From 33c7ce3b6a315a09f5b27d936bcd43f6105a46fc Mon Sep 17 00:00:00 2001 From: "anthropic-code-agent[bot]" <242468646+Claude@users.noreply.github.com> Date: Mon, 13 Apr 2026 10:10:53 +0000 Subject: [PATCH 1/8] feat: add Vercel deployment support to app-host example using Hono Agent-Logs-Url: https://github.com/objectstack-ai/framework/sessions/cc91e2f2-a734-4a52-b865-5fa83a86e934 Co-authored-by: xuyushun441-sys <255036401+xuyushun441-sys@users.noreply.github.com> --- examples/app-host/.npmrc | 3 + examples/app-host/api/[[...route]].js | 16 + examples/app-host/api/_handler.js | 167931 +++++++++++++++++++ examples/app-host/api/_handler.js.map | 7 + examples/app-host/package.json | 7 +- examples/app-host/scripts/build-vercel.sh | 49 + examples/app-host/scripts/bundle-api.mjs | 62 + examples/app-host/server/index.ts | 220 + examples/app-host/vercel.json | 18 +- pnpm-lock.yaml | 281 + 10 files changed, 168587 insertions(+), 7 deletions(-) create mode 100644 examples/app-host/.npmrc create mode 100644 examples/app-host/api/[[...route]].js create mode 100644 examples/app-host/api/_handler.js create mode 100644 examples/app-host/api/_handler.js.map create mode 100755 examples/app-host/scripts/build-vercel.sh create mode 100644 examples/app-host/scripts/bundle-api.mjs create mode 100644 examples/app-host/server/index.ts diff --git a/examples/app-host/.npmrc b/examples/app-host/.npmrc new file mode 100644 index 000000000..1501d084b --- /dev/null +++ b/examples/app-host/.npmrc @@ -0,0 +1,3 @@ +# Vercel deployment configuration +# Use hoisted node_modules to prevent symlink issues +node-linker=hoisted diff --git a/examples/app-host/api/[[...route]].js b/examples/app-host/api/[[...route]].js new file mode 100644 index 000000000..1bbcc8746 --- /dev/null +++ b/examples/app-host/api/[[...route]].js @@ -0,0 +1,16 @@ +// Vercel Serverless Function — Catch-all API route. +// +// This file MUST be committed to the repository so Vercel can detect it +// as a serverless function during the pre-build phase. +// +// It delegates to the esbuild bundle (`_handler.js`) generated by +// `scripts/bundle-api.mjs` during the Vercel build step. A separate +// bundle file is used (rather than overwriting this file) so that: +// 1. Vercel always finds this committed entry point (no "File not found"). +// 2. Vercel does not TypeScript-compile a .ts stub that references +// source files absent at runtime (no ERR_MODULE_NOT_FOUND). +// +// @see ../server/index.ts — the actual server entrypoint +// @see ../scripts/bundle-api.mjs — the esbuild bundler + +export { default, config } from './_handler.js'; diff --git a/examples/app-host/api/_handler.js b/examples/app-host/api/_handler.js new file mode 100644 index 000000000..43f1ae53b --- /dev/null +++ b/examples/app-host/api/_handler.js @@ -0,0 +1,167931 @@ +// Bundled by esbuild — see scripts/bundle-api.mjs +import { createRequire } from "module"; +const require = createRequire(import.meta.url); +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); +var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); +var __privateWrapper = (obj, member, setter, getter) => ({ + set _(value) { + __privateSet(obj, member, value, setter); + }, + get _() { + return __privateGet(obj, member, getter); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, params) { + function init2(inst, def) { + if (!inst._zod) { + Object.defineProperty(inst, "_zod", { + value: { + def, + constr: _, + traits: /* @__PURE__ */ new Set() + }, + enumerable: false + }); + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(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 _a30; + const inst = params?.Parent ? new Definition() : this; + init2(inst, def); + (_a30 = inst._zod).deferred ?? (_a30.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init2 }); + 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 NEVER, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig; +var init_core = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js"() { + NEVER = Object.freeze({ + status: "aborted" + }); + $brand = Symbol("zod_brand"); + $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } + }; + $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } + }; + globalConfig = {}; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert2, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + base64ToUint8Array: () => base64ToUint8Array, + base64urlToUint8Array: () => base64urlToUint8Array, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + cloneDef: () => cloneDef, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType, + getSizableOrigin: () => getSizableOrigin, + hexToUint8Array: () => hexToUint8Array, + isObject: () => isObject2, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + mergeDefs: () => mergeDefs, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + objectClone: () => objectClone, + omit: () => omit, + optionalKeys: () => optionalKeys, + parsedType: () => parsedType, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + safeExtend: () => safeExtend, + shallowClone: () => shallowClone, + slugify: () => slugify, + stringifyPrimitive: () => stringifyPrimitive, + uint8ArrayToBase64: () => uint8ArrayToBase64, + uint8ArrayToBase64url: () => uint8ArrayToBase64url, + uint8ArrayToHex: () => uint8ArrayToHex, + unwrapMessage: () => unwrapMessage +}); +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { +} +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert2(_) { +} +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(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set2 = false; + return { + get value() { + if (!set2) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + } + }; +} +function nullish(input) { + return input === null || input === void 0; +} +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 stepString = step.toString(); + let stepDecCount = (stepString.split(".")[1] || "").length; + if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { + const match2 = stepString.match(/\d?e-(\d?)/); + if (match2?.[1]) { + stepDecCount = Number.parseInt(match2[1]); + } + } + 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(object2, key, getter) { + let value = void 0; + Object.defineProperty(object2, key, { + get() { + if (value === EVALUATING) { + return void 0; + } + if (value === void 0) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object2, key, { + value: v + // configurable: true, + }); + }, + configurable: true + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +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 cloneDef(schema3) { + return mergeDefs(schema3._zod.def); +} +function getElementAtPath(obj, path3) { + if (!path3) + return obj; + return path3.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +} +function isObject2(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +function isPlainObject(o) { + if (isObject2(o) === false) + return false; + const ctor = o.constructor; + if (ctor === void 0) + return true; + if (typeof ctor !== "function") + return true; + const prot = ctor.prototype; + if (isObject2(prot) === false) + return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +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(_params2) { + const params = _params2; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) + 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 createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + } + }); +} +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"; + }); +} +function pick(schema3, mask) { + const currDef = schema3._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema3._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(schema3, def); +} +function omit(schema3, mask) { + const currDef = schema3._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema3._zod.def, { + get shape() { + const newShape = { ...schema3._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(schema3, def); +} +function extend(schema3, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema3._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + const existingShape = schema3._zod.def.shape; + for (const key in shape) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema3._zod.def, { + get shape() { + const _shape = { ...schema3._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone(schema3, def); +} +function safeExtend(schema3, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema3._zod.def, { + get shape() { + const _shape = { ...schema3._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone(schema3, 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); + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: [] + // delete existing checks + }); + return clone(a, def); +} +function partial(Class2, schema3, mask) { + const currDef = schema3._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(schema3._zod.def, { + get shape() { + const oldShape = schema3._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] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + assignProp(this, "shape", shape); + return shape; + }, + checks: [] + }); + return clone(schema3, def); +} +function required(Class2, schema3, mask) { + const def = mergeDefs(schema3._zod.def, { + get shape() { + const oldShape = schema3._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 Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } + assignProp(this, "shape", shape); + return shape; + } + }); + return clone(schema3, def); +} +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +function prefixIssues(path3, issues) { + return issues.map((iss) => { + var _a30; + (_a30 = iss).path ?? (_a30.path = []); + iss.path.unshift(path3); + return iss; + }); +} +function unwrapMessage(message2) { + return typeof message2 === "string" ? message2 : message2?.message; +} +function finalizeIssue(iss, ctx, config4) { + const full = { ...iss, path: iss.path ?? [] }; + if (!iss.message) { + const message2 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config4.customError?.(iss)) ?? unwrapMessage(config4.localeError?.(iss)) ?? "Invalid input"; + full.message = message2; + } + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + 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") { + return { + message: iss, + code: "custom", + input, + inst + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj).filter(([k, _]) => { + return Number.isNaN(Number.parseInt(k, 10)); + }).map((el) => el[1]); +} +function base64ToUint8Array(base644) { + const binaryString = atob(base644); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url3) { + const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - base644.length % 4) % 4); + return base64ToUint8Array(base644 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex4) { + const cleanHex = hex4.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +var EVALUATING, captureStackTrace, allowsEval, getParsedType, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class; +var init_util = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js"() { + EVALUATING = Symbol("evaluating"); + captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { + }; + allowsEval = cached(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } catch (_) { + return false; + } + }); + getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } + }; + propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); + primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); + NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] + }; + BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] + }; + Class = class { + constructor(..._args) { + } + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js +function flattenError(error49, mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error49.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(error49, mapper = (issue2) => issue2.message) { + const fieldErrors = { _errors: [] }; + const processError = (error50) => { + for (const issue2 of error50.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues })); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue2.path.length) { + const el = issue2.path[i]; + const terminal = i === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(error49); + return fieldErrors; +} +function treeifyError(error49, mapper = (issue2) => issue2.message) { + const result = { errors: [] }; + const processError = (error50, path3 = []) => { + var _a30, _b2; + for (const issue2 of error50.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues }, issue2.path)); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }, issue2.path); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }, issue2.path); + } else { + const fullpath = [...path3, ...issue2.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue2)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a30 = curr.properties)[el] ?? (_a30[el] = { errors: [] }); + curr = curr.properties[el]; + } else { + curr.items ?? (curr.items = []); + (_b2 = curr.items)[el] ?? (_b2[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue2)); + } + i++; + } + } + } + }; + processError(error49); + return result; +} +function toDotPath(_path3) { + const segs = []; + const path3 = _path3.map((seg) => typeof seg === "object" ? seg.key : seg); + for (const seg of path3) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error49) { + const lines = []; + const issues = [...error49.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + for (const issue2 of issues) { + lines.push(`\u2716 ${issue2.message}`); + if (issue2.path?.length) + lines.push(` \u2192 at ${toDotPath(issue2.path)}`); + } + return lines.join("\n"); +} +var initializer, $ZodError, $ZodRealError; +var init_errors = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js"() { + init_core(); + init_util(); + 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 + }); + }; + $ZodError = $constructor("$ZodError", initializer); + $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js +var _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, encode, _decode, decode, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync; +var init_parse = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js"() { + init_core(); + init_errors(); + init_util(); + _parse = (_Err) => (schema3, value, _ctx, _params2) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema3._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params2?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params2?.callee); + throw e; + } + return result.value; + }; + parse = /* @__PURE__ */ _parse($ZodRealError); + _parseAsync = (_Err) => async (schema3, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema3._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; + }; + parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); + _safeParse = (_Err) => (schema3, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema3._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 = /* @__PURE__ */ _safeParse($ZodRealError); + _safeParseAsync = (_Err) => async (schema3, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema3._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 = /* @__PURE__ */ _safeParseAsync($ZodRealError); + _encode = (_Err) => (schema3, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parse(_Err)(schema3, value, ctx); + }; + encode = /* @__PURE__ */ _encode($ZodRealError); + _decode = (_Err) => (schema3, value, _ctx) => { + return _parse(_Err)(schema3, value, _ctx); + }; + decode = /* @__PURE__ */ _decode($ZodRealError); + _encodeAsync = (_Err) => async (schema3, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parseAsync(_Err)(schema3, value, ctx); + }; + encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); + _decodeAsync = (_Err) => async (schema3, value, _ctx) => { + return _parseAsync(_Err)(schema3, value, _ctx); + }; + decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); + _safeEncode = (_Err) => (schema3, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParse(_Err)(schema3, value, ctx); + }; + safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); + _safeDecode = (_Err) => (schema3, value, _ctx) => { + return _safeParse(_Err)(schema3, value, _ctx); + }; + safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); + _safeEncodeAsync = (_Err) => async (schema3, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParseAsync(_Err)(schema3, value, ctx); + }; + safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); + _safeDecodeAsync = (_Err) => async (schema3, value, _ctx) => { + return _safeParseAsync(_Err)(schema3, value, _ctx); + }; + safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js +var regexes_exports = {}; +__export(regexes_exports, { + base64: () => base64, + base64url: () => base64url, + bigint: () => bigint, + boolean: () => boolean, + browserEmail: () => browserEmail, + cidrv4: () => cidrv4, + cidrv6: () => cidrv6, + cuid: () => cuid, + cuid2: () => cuid2, + date: () => date, + datetime: () => datetime, + domain: () => domain, + duration: () => duration, + e164: () => e164, + email: () => email, + emoji: () => emoji, + extendedDuration: () => extendedDuration, + guid: () => guid, + hex: () => hex, + hostname: () => hostname, + html5Email: () => html5Email, + idnEmail: () => idnEmail, + integer: () => integer, + ipv4: () => ipv4, + ipv6: () => ipv6, + ksuid: () => ksuid, + lowercase: () => lowercase, + mac: () => mac, + md5_base64: () => md5_base64, + md5_base64url: () => md5_base64url, + md5_hex: () => md5_hex, + nanoid: () => nanoid, + null: () => _null, + number: () => number, + rfc5322Email: () => rfc5322Email, + sha1_base64: () => sha1_base64, + sha1_base64url: () => sha1_base64url, + sha1_hex: () => sha1_hex, + sha256_base64: () => sha256_base64, + sha256_base64url: () => sha256_base64url, + sha256_hex: () => sha256_hex, + sha384_base64: () => sha384_base64, + sha384_base64url: () => sha384_base64url, + sha384_hex: () => sha384_hex, + sha512_base64: () => sha512_base64, + sha512_base64url: () => sha512_base64url, + sha512_hex: () => sha512_hex, + string: () => string, + time: () => time, + ulid: () => ulid, + undefined: () => _undefined, + unicodeEmail: () => unicodeEmail, + uppercase: () => uppercase, + uuid: () => uuid, + uuid4: () => uuid4, + uuid6: () => uuid6, + uuid7: () => uuid7, + xid: () => xid +}); +function emoji() { + return new RegExp(_emoji, "u"); +} +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(args) { + return new RegExp(`^${timeSource(args)}$`); +} +function datetime(args) { + const time3 = 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 = `${time3}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url; +var init_regexes = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js"() { + init_util(); + cuid = /^[cC][^\s-]{8,}$/; + cuid2 = /^[0-9a-z]+$/; + ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; + 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)?)?)$/; + extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + 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})$/; + uuid = (version3) => { + if (!version3) + 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}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); + }; + uuid4 = /* @__PURE__ */ uuid(4); + uuid6 = /* @__PURE__ */ uuid(6); + uuid7 = /* @__PURE__ */ uuid(7); + email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; + html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; + idnEmail = unicodeEmail; + browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + 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}|:))$/; + mac = (delimiter) => { + const escapedDelim = escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); + }; + 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])$/; + base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; + base64url = /^[A-Za-z0-9_-]*$/; + hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; + domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; + e164 = /^\+[1-9]\d{6,14}$/; + 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 = /* @__PURE__ */ new RegExp(`^${dateSource}$`); + string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); + }; + bigint = /^-?\d+n?$/; + integer = /^-?\d+$/; + number = /^-?\d+(?:\.\d+)?$/; + boolean = /^(?:true|false)$/i; + _null = /^null$/i; + _undefined = /^undefined$/i; + lowercase = /^[^A-Z]*$/; + uppercase = /^[^a-z]*$/; + hex = /^[0-9a-fA-F]*$/; + md5_hex = /^[0-9a-fA-F]{32}$/; + md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); + md5_base64url = /* @__PURE__ */ fixedBase64url(22); + sha1_hex = /^[0-9a-fA-F]{40}$/; + sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); + sha1_base64url = /* @__PURE__ */ fixedBase64url(27); + sha256_hex = /^[0-9a-fA-F]{64}$/; + sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); + sha256_base64url = /* @__PURE__ */ fixedBase64url(43); + sha384_hex = /^[0-9a-fA-F]{96}$/; + sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); + sha384_base64url = /* @__PURE__ */ fixedBase64url(64); + sha512_hex = /^[0-9a-fA-F]{128}$/; + sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); + sha512_base64url = /* @__PURE__ */ fixedBase64url(86); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...prefixIssues(property, result.issues)); + } +} +var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite; +var init_checks = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js"() { + init_core(); + init_regexes(); + init_util(); + $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { + var _a30; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a30 = inst._zod).onattach ?? (_a30.onattach = []); + }); + numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" + }; + $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._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: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._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: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + var _a30; + (_a30 = inst2._zod.bag).multipleOf ?? (_a30.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 + }); + }; + }); + $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); + 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((inst2) => { + const bag = inst2._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)) { + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + } else { + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + 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, + inclusive: true, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { + var _a30; + $ZodCheck.init(inst, def); + (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { + var _a30; + $ZodCheck.init(inst, def); + (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a30; + $ZodCheck.init(inst, def); + (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: getSizableOrigin(input), + ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a30; + $ZodCheck.init(inst, def); + (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._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 + }); + }; + }); + $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a30; + $ZodCheck.init(inst, def); + (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._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 + }); + }; + }); + $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a30; + $ZodCheck.init(inst, def); + (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._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 + }); + }; + }); + $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a30, _b2; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a30 = inst._zod).check ?? (_a30.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 + (_b2 = inst._zod).check ?? (_b2.check = () => { + }); + }); + $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 + }); + }; + }); + $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); + }); + $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); + }); + $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((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 + }); + }; + }); + $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((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 + }); + }; + }); + $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((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 + }); + }; + }); + $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [] + }, {}); + if (result instanceof Promise) { + return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; + }); + $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; + }); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js +var Doc; +var init_doc = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js"() { + Doc = class { + 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 line2 of dedented) { + this.content.push(line2); + } + } + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + return new F(...args, lines.join("\n")); + } + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js +var version; +var init_versions = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js"() { + version = { + major: 4, + minor: 3, + patch: 6 + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js +function isValidBase64(data) { + if (data === "") + return true; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; + } catch { + return false; + } +} +function isValidBase64URL(data) { + if (!base64url.test(data)) + return false; + const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "="); + return isValidBase64(padded); +} +function isValidJWT(token, algorithm2 = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm2 && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm2)) + return false; + return true; + } catch { + return false; + } +} +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handlePropertyResult(result, final, key, input, isOptionalOut) { + if (result.issues.length) { + if (isOptionalOut && !(key in input)) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (result.value === void 0) { + if (key in input) { + final.value[key] = void 0; + } + } else { + final.value[key] = result.value; + } +} +function normalizeDef(def) { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const isOptionalOut = _catchall.optout === "optional"; + for (const key in input) { + if (keySet.has(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((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); + } else { + handlePropertyResult(r, payload, key, input, isOptionalOut); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + return final; +} +function handleExclusiveUnionResults(results, final, inst, ctx) { + const successes = results.filter((r) => r.issues.length === 0); + if (successes.length === 1) { + final.value = successes[0].value; + return final; + } + if (successes.length === 0) { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + } else { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false + }); + } + return final; +} +function mergeValues(a, b) { + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath] + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + const unrecKeys = /* @__PURE__ */ new Map(); + let unrecIssue; + for (const iss of left.issues) { + if (iss.code === "unrecognized_keys") { + unrecIssue ?? (unrecIssue = iss); + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).l = true; + } + } else { + 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 { + 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 (aborted(result)) + return result; + const merged = mergeValues(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, keyResult.issues)); + } else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key, + issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +function handleOptionalResult(result, input) { + if (result.issues.length && input === void 0) { + return { issues: [], value: void 0 }; + } + return result; +} +function handleDefaultResult(payload, def) { + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return payload; +} +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + } + return payload; +} +function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + // incorporates params.error into issue reporting + path: [...inst._zod.def.path ?? []], + // incorporates params.error into issue reporting + continue: !inst._zod.def.abort + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + 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, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom; +var init_schemas = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js"() { + init_checks(); + init_core(); + init_doc(); + init_parse(); + init_regexes(); + init_util(); + init_versions(); + init_util(); + $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { + var _a30; + 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); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a30 = inst._zod).deferred ?? (_a30.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks2, ctx) => { + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks2) { + 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; + }; + const handleCanaryResult = (canary, payload, ctx) => { + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary2) => { + return handleCanaryResult(canary2, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); + } + 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 + })); + }); + $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } catch (_2) { + } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); + }); + $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); + }); + $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 = versionMap[def.version]; + if (v === void 0) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); + }); + $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); + }); + $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const trimmed = payload.value.trim(); + const url2 = new URL(trimmed); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url2.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) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + } + if (def.normalize) { + payload.value = url2.href; + } else { + payload.value = trimmed; + } + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); + }); + $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); + }); + $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); + }); + $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); + }); + $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); + }); + $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); + }); + $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); + }); + $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + }); + $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); + }); + $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time(def)); + $ZodStringFormat.init(inst, def); + }); + $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); + }); + $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; + }); + $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 { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; + }); + $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); + }); + $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 { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); + }); + $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } catch (_) { + } + const input = payload.value; + 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" : void 0 : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} + }); + return payload; + }; + }); + $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); + }); + $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } catch (_) { + } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } catch (_) { + } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { + $ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); + }); + $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _undefined; + inst._zod.values = /* @__PURE__ */ new Set([void 0]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = /* @__PURE__ */ new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } catch (_err) { + } + } + const input = payload.value; + const isDate3 = input instanceof Date; + const isValidDate2 = isDate3 && !Number.isNaN(input.getTime()); + if (isValidDate2) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...isDate3 ? { received: "Invalid Date" } : {}, + inst + }); + return payload; + }; + }); + $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); + } else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; + }); + $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 _normalized = cached(() => normalizeDef(def)); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const isObject5 = isObject2; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject5(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = {}; + const proms = []; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const isOptionalOut = el._zod.optout === "optional"; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); + } else { + handlePropertyResult(r, payload, key, input, isOptionalOut); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; + }); + $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached(() => normalizeDef(def)); + 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)`; + }; + doc.write(`const input = payload.value;`); + const ids = /* @__PURE__ */ Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + doc.write(`const newResult = {};`); + for (const key of normalized.keys) { + const id = ids[key]; + const k = esc(key); + const schema3 = shape[key]; + const isOptionalOut = schema3?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(key)};`); + if (isOptionalOut) { + 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}] + }))); + } + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + 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 { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject5 = isObject2; + const jit = !globalConfig.jitless; + const allowsEval2 = allowsEval; + const fastEnabled = jit && allowsEval2.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject5(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + 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" : void 0); + defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return void 0; + }); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return void 0; + }); + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx) => { + if (single) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleUnionResults(results2, payload, inst, ctx); + }); + }; + }); + $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx) => { + if (single) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleExclusiveUnionResults(results2, payload, inst, ctx); + }); + }; + }); + $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of 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)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = /* @__PURE__ */ new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = cached(() => { + const opts = def.options; + const map3 = /* @__PURE__ */ 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 (map3.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map3.set(v, o); + } + } + return map3; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isObject2(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + if (def.unionFallback) { + return _super(payload, ctx); + } + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + input, + path: [def.discriminator], + inst + }); + return payload; + }; + }); + $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left2, right2]) => { + return handleIntersectionResults(payload, left2, right2); + }); + } + return handleIntersectionResults(payload, left, right); + }; + }); + $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" + }); + return payload; + } + payload.value = []; + const proms = []; + const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length }, + input, + inst, + origin: "array" + }); + return payload; + } + } + let i = -1; + for (const item of items) { + i++; + if (i >= input.length) { + if (i >= optStart) + continue; + } + const result = item._zod.run({ + value: input[i], + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); + } else { + handleTupleResult(result, payload, i); + } + } + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ + value: el, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); + } else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values) { + payload.value = {}; + const recordKeys = /* @__PURE__ */ 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); + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[key] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); + } + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + payload.value[key] = input[key]; + } else { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + } + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; + }); + $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { + handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + })); + } else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type" + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleSetResult(result2, payload))); + } else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(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("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst + }); + return payload; + }; + }); + $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("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst + }); + return payload; + }; + }); + $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output2) => { + payload.value = output2; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; + }); + $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) + return result.then((r) => handleOptionalResult(r, payload.value)); + return handleOptionalResult(result, payload.value); + } + if (payload.value === void 0) { + return payload; + } + 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); + 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; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + payload.value = def.defaultValue; + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult(result2, def)); + } + return handleDefaultResult(result, def); + }; + }); + $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult(result2, inst)); + } + return handleNonOptionalResult(result, inst); + }; + }); + $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; + }); + $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (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, "values", () => 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); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.value; + if (result2.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + 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 = []; + } + return payload; + }; + }); + $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type" + }); + return payload; + } + return payload; + }; + }); + $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); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handlePipeResult(right2, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult(left2, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; + }); + $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (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); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handleCodecAResult(left2, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handleCodecAResult(right2, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; + }); + $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); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; + }); + $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + if (!part._zod.pattern) { + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } else if (part === null || primitiveTypes.has(typeof part)) { + regexParts.push(escapeRegex(`${part}`)); + } else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type" + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source + }); + return payload; + } + return payload; + }; + }); + $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + inst._def = def; + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + return function(...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }; + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return async function(...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }; + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst + }); + return payload; + } + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1] + }), + output: inst._def.output + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output + }); + }; + return inst; + }); + $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; + }); + $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "innerType", () => def.getter()); + defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); + defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); + defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); + defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; + }); + $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; + }); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js +function ar_default() { + return { + localeError: error() + }; +} +var error; +var init_ar = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"() { + init_util(); + error = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0645\u062F\u062E\u0644", + email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", + url: "\u0631\u0627\u0628\u0637", + emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", + ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", + cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", + base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", + base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", + json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", + e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + jwt: "JWT", + template_literal: "\u0645\u062F\u062E\u0644" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; + return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; + if (_issue.format === "ends_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; + } + case "not_multiple_of": + return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + case "invalid_union": + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + case "invalid_element": + return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + default: + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js +function az_default() { + return { + localeError: error2() + }; +} +var error2; +var init_az = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"() { + init_util(); + error2 = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "element", verb: "olmal\u0131d\u0131r" }, + set: { unit: "element", verb: "olmal\u0131d\u0131r" } + }; + 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", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; + } + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; + return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; + if (_issue.format === "ends_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; + if (_issue.format === "includes") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; + if (_issue.format === "regex") + return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; + return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; + case "unrecognized_keys": + return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; + case "invalid_union": + return "Yanl\u0131\u015F d\u0259y\u0259r"; + case "invalid_element": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; + default: + return `Yanl\u0131\u015F d\u0259y\u0259r`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js +function getBelarusianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +function be_default() { + return { + localeError: error3() + }; +} +var error3; +var init_be = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"() { + init_util(); + error3 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0456\u043C\u0432\u0430\u043B", + few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", + many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u044B", + many: "\u0431\u0430\u0439\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0443\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0430\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0447\u0430\u0441", + duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", + base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", + json_string: "JSON \u0440\u0430\u0434\u043E\u043A", + e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + jwt: "JWT", + template_literal: "\u0443\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u043B\u0456\u043A", + array: "\u043C\u0430\u0441\u0456\u045E" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; + case "invalid_element": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; + default: + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js +function bg_default() { + return { + localeError: error4() + }; +} +var error4; +var init_bg = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"() { + init_util(); + error4 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u043E\u0434", + email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + json_string: "JSON \u043D\u0438\u0437", + e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + jwt: "JWT", + template_literal: "\u0432\u0445\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; + let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; + if (_issue.format === "emoji") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "datetime") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "date") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + if (_issue.format === "time") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "duration") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; + case "invalid_element": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js +function ca_default() { + return { + localeError: error5() + }; +} +var error5; +var init_ca = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"() { + init_util(); + error5 = () => { + const Sizable = { + string: { unit: "car\xE0cters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entrada", + email: "adre\xE7a electr\xF2nica", + 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: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adre\xE7a IPv4", + ipv6: "adre\xE7a IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; + } + return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; + case "too_big": { + const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; + return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Clau inv\xE0lida a ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE0lida"; + // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element inv\xE0lid a ${issue2.origin}`; + default: + return `Entrada inv\xE0lida`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js +function cs_default() { + return { + localeError: error6() + }; +} +var error6; +var init_cs = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"() { + init_util(); + error6 = () => { + const Sizable = { + string: { unit: "znak\u016F", verb: "m\xEDt" }, + file: { unit: "bajt\u016F", verb: "m\xEDt" }, + array: { unit: "prvk\u016F", verb: "m\xEDt" }, + set: { unit: "prvk\u016F", verb: "m\xEDt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rn\xED v\xFDraz", + email: "e-mailov\xE1 adresa", + 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: "datum a \u010Das ve form\xE1tu ISO", + date: "datum ve form\xE1tu ISO", + time: "\u010Das ve form\xE1tu ISO", + duration: "doba trv\xE1n\xED ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", + base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", + json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", + e164: "\u010D\xEDslo E.164", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "\u0159et\u011Bzec", + function: "funkce", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js +function da_default() { + return { + localeError: error7() + }; +} +var error7; +var init_da = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"() { + init_util(); + error7 = () => { + const Sizable = { + string: { unit: "tegn", verb: "havde" }, + file: { unit: "bytes", verb: "havde" }, + array: { unit: "elementer", verb: "indeholdt" }, + set: { unit: "elementer", verb: "indeholdt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-mailadresse", + 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 dato- og klokkesl\xE6t", + date: "ISO-dato", + time: "ISO-klokkesl\xE6t", + duration: "ISO-varighed", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodet streng", + base64url: "base64url-kodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + string: "streng", + number: "tal", + boolean: "boolean", + array: "liste", + object: "objekt", + set: "s\xE6t", + file: "fil" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; + } + return `Ugyldigt input: forventede ${expected}, fik ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: skal starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: skal ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: skal indeholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8gle i ${issue2.origin}`; + case "invalid_union": + return "Ugyldigt input: matcher ingen af de tilladte typer"; + case "invalid_element": + return `Ugyldig v\xE6rdi i ${issue2.origin}`; + default: + return `Ugyldigt input`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js +function de_default() { + return { + localeError: error8() + }; +} +var error8; +var init_de = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"() { + init_util(); + error8 = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "Eingabe", + email: "E-Mail-Adresse", + 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-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe" + }; + const TypeDictionary = { + nan: "NaN", + number: "Zahl", + array: "Array" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; + } + return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; + return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; + case "invalid_union": + return "Ung\xFCltige Eingabe"; + case "invalid_element": + return `Ung\xFCltiger Wert in ${issue2.origin}`; + default: + return `Ung\xFCltige Eingabe`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js +function en_default() { + return { + localeError: error9() + }; +} +var error9; +var init_en = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"() { + init_util(); + error9 = () => { + 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", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + 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] ?? issue2.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue2.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue2.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue2.origin}`; + default: + return `Invalid input`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js +function eo_default() { + return { + localeError: error10() + }; +} +var error10; +var init_eo = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"() { + init_util(); + error10 = () => { + const Sizable = { + string: { unit: "karaktrojn", verb: "havi" }, + file: { unit: "bajtojn", verb: "havi" }, + array: { unit: "elementojn", verb: "havi" }, + set: { unit: "elementojn", verb: "havi" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "enigo", + email: "retadreso", + url: "URL", + emoji: "emo\u011Dio", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datotempo", + date: "ISO-dato", + time: "ISO-tempo", + duration: "ISO-da\u016Dro", + ipv4: "IPv4-adreso", + ipv6: "IPv6-adreso", + cidrv4: "IPv4-rango", + cidrv6: "IPv6-rango", + base64: "64-ume kodita karaktraro", + base64url: "URL-64-ume kodita karaktraro", + json_string: "JSON-karaktraro", + e164: "E.164-nombro", + jwt: "JWT", + template_literal: "enigo" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombro", + array: "tabelo", + null: "senvalora" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; + } + return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; + return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; + return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nevalida \u015Dlosilo en ${issue2.origin}`; + case "invalid_union": + return "Nevalida enigo"; + case "invalid_element": + return `Nevalida valoro en ${issue2.origin}`; + default: + return `Nevalida enigo`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js +function es_default() { + return { + localeError: error11() + }; +} +var error11; +var init_es = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"() { + init_util(); + error11 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entrada", + email: "direcci\xF3n de correo electr\xF3nico", + 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: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duraci\xF3n ISO", + ipv4: "direcci\xF3n IPv4", + ipv6: "direcci\xF3n IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + string: "texto", + number: "n\xFAmero", + boolean: "booleano", + array: "arreglo", + object: "objeto", + set: "conjunto", + file: "archivo", + date: "fecha", + bigint: "n\xFAmero grande", + symbol: "s\xEDmbolo", + undefined: "indefinido", + null: "nulo", + function: "funci\xF3n", + map: "mapa", + record: "registro", + tuple: "tupla", + enum: "enumeraci\xF3n", + union: "uni\xF3n", + literal: "literal", + promise: "promesa", + void: "vac\xEDo", + never: "nunca", + unknown: "desconocido", + any: "cualquiera" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; + } + return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; + return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + default: + return `Entrada inv\xE1lida`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js +function fa_default() { + return { + localeError: error12() + }; +} +var error12; +var init_fa = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"() { + init_util(); + error12 = () => { + const Sizable = { + string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u06CC", + email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", + url: "URL", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", + time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + ipv4: "IPv4 \u0622\u062F\u0631\u0633", + ipv6: "IPv6 \u0622\u062F\u0631\u0633", + cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", + cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", + base64: "base64-encoded \u0631\u0634\u062A\u0647", + base64url: "base64url-encoded \u0631\u0634\u062A\u0647", + json_string: "JSON \u0631\u0634\u062A\u0647", + e164: "E.164 \u0639\u062F\u062F", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u06CC" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0622\u0631\u0627\u06CC\u0647" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; + } + return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; + } + if (_issue.format === "ends_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; + } + if (_issue.format === "includes") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; + } + if (_issue.format === "regex") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; + } + return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + case "not_multiple_of": + return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; + case "invalid_union": + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + case "invalid_element": + return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; + default: + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js +function fi_default() { + return { + localeError: error13() + }; +} +var error13; +var init_fi = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"() { + init_util(); + error13 = () => { + const Sizable = { + string: { unit: "merkki\xE4", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "s\xE4\xE4nn\xF6llinen lauseke", + email: "s\xE4hk\xF6postiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; + } + return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; + return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen sy\xF6te`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js +function fr_default() { + return { + localeError: error14() + }; +} +var error14; +var init_fr = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"() { + init_util(); + error14 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse e-mail", + 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: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombre", + array: "tableau" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + } + return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; + return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; + return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js +function fr_CA_default() { + return { + localeError: error15() + }; +} +var error15; +var init_fr_CA = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"() { + init_util(); + error15 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse courriel", + 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: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; + } + return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u2264" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u2265" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js +function he_default() { + return { + localeError: error16() + }; +} +var error16; +var init_he = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"() { + init_util(); + error16 = () => { + const TypeNames = { + string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, + number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, + boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, + bigint: { label: "BigInt", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, + array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, + object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, + null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, + undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, + symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, + function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, + map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, + set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, + file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, + promise: { label: "Promise", gender: "m" }, + NaN: { label: "NaN", gender: "m" }, + unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, + value: { label: "\u05E2\u05E8\u05DA", gender: "m" } + }; + const Sizable = { + string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, + file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } + // no unit + }; + const typeEntry = (t) => t ? TypeNames[t] : void 0; + const typeLabel = (t) => { + const e = typeEntry(t); + if (e) + return e.label; + return t ?? TypeNames.unknown.label; + }; + const withDefinite = (t) => `\u05D4${typeLabel(t)}`; + const verbFor = (t) => { + const e = typeEntry(t); + const gender = e?.gender ?? "m"; + return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; + }; + const getSizing = (origin) => { + if (!origin) + return null; + return Sizable[origin] ?? null; + }; + const FormatDictionary = { + regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, + url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, + uuid: { label: "UUID", gender: "m" }, + nanoid: { label: "nanoid", gender: "m" }, + guid: { label: "GUID", gender: "m" }, + cuid: { label: "cuid", gender: "m" }, + cuid2: { label: "cuid2", gender: "m" }, + ulid: { label: "ULID", gender: "m" }, + xid: { label: "XID", gender: "m" }, + ksuid: { label: "KSUID", gender: "m" }, + datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, + time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, + duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, + ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, + ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, + cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, + base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, + base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, + e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + jwt: { label: "JWT", gender: "m" }, + ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expectedKey = issue2.expected; + const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + case "invalid_value": { + if (issue2.values.length === 1) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; + } + const stringified = issue2.values.map((v) => stringifyPrimitive(v)); + if (issue2.values.length === 2) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; + } + const lastValue = stringified[stringified.length - 1]; + const restValues = stringified.slice(0, -1).join(", "); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; + } + case "too_big": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite(issue2.origin ?? "value"); + if (issue2.origin === "string") { + return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? "<=" : "<"; + const be = verbFor(issue2.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + } + return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite(issue2.origin ?? "value"); + if (issue2.origin === "string") { + return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + if (issue2.minimum === 1 && issue2.inclusive) { + const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; + } + const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? ">=" : ">"; + const be = verbFor(issue2.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; + const nounEntry = FormatDictionary[_issue.format]; + const noun = nounEntry?.label ?? _issue.format; + const gender = nounEntry?.gender ?? "m"; + const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; + return `${noun} \u05DC\u05D0 ${adjective}`; + } + case "not_multiple_of": + return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; + case "unrecognized_keys": + return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": { + return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; + } + case "invalid_union": + return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; + case "invalid_element": { + const place = withDefinite(issue2.origin ?? "array"); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; + } + default: + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js +function hu_default() { + return { + localeError: error17() + }; +} +var error17; +var init_hu = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"() { + init_util(); + error17 = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "bemenet", + email: "email c\xEDm", + 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 id\u0151b\xE9lyeg", + date: "ISO d\xE1tum", + time: "ISO id\u0151", + duration: "ISO id\u0151intervallum", + ipv4: "IPv4 c\xEDm", + ipv6: "IPv6 c\xEDm", + cidrv4: "IPv4 tartom\xE1ny", + cidrv6: "IPv6 tartom\xE1ny", + base64: "base64-k\xF3dolt string", + base64url: "base64url-k\xF3dolt string", + json_string: "JSON string", + e164: "E.164 sz\xE1m", + jwt: "JWT", + template_literal: "bemenet" + }; + const TypeDictionary = { + nan: "NaN", + number: "sz\xE1m", + array: "t\xF6mb" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; + } + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; + return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; + if (_issue.format === "ends_with") + return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; + if (_issue.format === "includes") + return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; + if (_issue.format === "regex") + return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; + return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; + case "invalid_union": + return "\xC9rv\xE9nytelen bemenet"; + case "invalid_element": + return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; + default: + return `\xC9rv\xE9nytelen bemenet`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js +function getArmenianPlural(count, one, many) { + return Math.abs(count) === 1 ? one : many; +} +function withDefiniteArticle(word) { + if (!word) + return ""; + const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; + const lastChar = word[word.length - 1]; + return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); +} +function hy_default() { + return { + localeError: error18() + }; +} +var error18; +var init_hy = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"() { + init_util(); + error18 = () => { + const Sizable = { + string: { + unit: { + one: "\u0576\u0577\u0561\u0576", + many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + file: { + unit: { + one: "\u0562\u0561\u0575\u0569", + many: "\u0562\u0561\u0575\u0569\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + array: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + set: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0574\u0578\u0582\u057F\u0584", + email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", + url: "URL", + emoji: "\u0567\u0574\u0578\u057B\u056B", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", + date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", + time: "ISO \u056A\u0561\u0574", + duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", + ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", + ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + json_string: "JSON \u057F\u0578\u0572", + e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + jwt: "JWT", + template_literal: "\u0574\u0578\u0582\u057F\u0584" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0569\u056B\u057E", + array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; + return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; + if (_issue.format === "ends_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; + if (_issue.format === "includes") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; + return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; + case "unrecognized_keys": + return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + case "invalid_union": + return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; + case "invalid_element": + return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + default: + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js +function id_default() { + return { + localeError: error19() + }; +} +var error19; +var init_id = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"() { + init_util(); + error19 = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "alamat email", + 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: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue2.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue2.origin}`; + default: + return `Input tidak valid`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js +function is_default() { + return { + localeError: error20() + }; +} +var error20; +var init_is = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"() { + init_util(); + error20 = () => { + const Sizable = { + string: { unit: "stafi", verb: "a\xF0 hafa" }, + file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, + array: { unit: "hluti", verb: "a\xF0 hafa" }, + set: { unit: "hluti", verb: "a\xF0 hafa" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "gildi", + email: "netfang", + url: "vefsl\xF3\xF0", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dagsetning og t\xEDmi", + date: "ISO dagsetning", + time: "ISO t\xEDmi", + duration: "ISO t\xEDmalengd", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded strengur", + base64url: "base64url-encoded strengur", + json_string: "JSON strengur", + e164: "E.164 t\xF6lugildi", + jwt: "JWT", + template_literal: "gildi" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmer", + array: "fylki" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; + } + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; + return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`; + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; + if (_issue.format === "regex") + return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; + return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; + case "unrecognized_keys": + return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Rangur lykill \xED ${issue2.origin}`; + case "invalid_union": + return "Rangt gildi"; + case "invalid_element": + return `Rangt gildi \xED ${issue2.origin}`; + default: + return `Rangt gildi`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js +function it_default() { + return { + localeError: error21() + }; +} +var error21; +var init_it = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"() { + init_util(); + error21 = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "indirizzo email", + 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: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "numero", + array: "vettore" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; + } + return `Input non valido: atteso ${expected}, ricevuto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; + return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; + case "unrecognized_keys": + return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue2.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue2.origin}`; + default: + return `Input non valido`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js +function ja_default() { + return { + localeError: error22() + }; +} +var error22; +var init_ja = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"() { + init_util(); + error22 = () => { + const Sizable = { + string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, + file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, + array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u5165\u529B\u5024", + email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", + url: "URL", + emoji: "\u7D75\u6587\u5B57", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u6642", + date: "ISO\u65E5\u4ED8", + time: "ISO\u6642\u523B", + duration: "ISO\u671F\u9593", + ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", + ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + cidrv4: "IPv4\u7BC4\u56F2", + cidrv6: "IPv6\u7BC4\u56F2", + base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + json_string: "JSON\u6587\u5B57\u5217", + e164: "E.164\u756A\u53F7", + jwt: "JWT", + template_literal: "\u5165\u529B\u5024" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5024", + array: "\u914D\u5217" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; + return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "too_big": { + const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "ends_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "includes") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "regex") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "unrecognized_keys": + return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; + case "invalid_union": + return "\u7121\u52B9\u306A\u5165\u529B"; + case "invalid_element": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; + default: + return `\u7121\u52B9\u306A\u5165\u529B`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js +function ka_default() { + return { + localeError: error23() + }; +} +var error23; +var init_ka = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"() { + init_util(); + error23 = () => { + const Sizable = { + string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", + email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + url: "URL", + emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", + date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", + time: "\u10D3\u10E0\u10DD", + duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", + ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + json_string: "JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + jwt: "JWT", + template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", + string: "\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", + function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", + array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; + } + if (_issue.format === "ends_with") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; + if (_issue.format === "includes") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; + if (_issue.format === "regex") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; + case "unrecognized_keys": + return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; + case "invalid_union": + return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; + case "invalid_element": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; + default: + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js +function km_default() { + return { + localeError: error24() + }; +} +var error24; +var init_km = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"() { + init_util(); + error24 = () => { + const Sizable = { + string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", + email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", + url: "URL", + emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", + date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", + time: "\u1798\u17C9\u17C4\u1784 ISO", + duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", + ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", + base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", + json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", + e164: "\u179B\u17C1\u1781 E.164", + jwt: "JWT", + template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u179B\u17C1\u1781", + array: "\u17A2\u17B6\u179A\u17C1 (Array)", + null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; + return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; + return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + case "invalid_union": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + case "invalid_element": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + default: + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js +function kh_default() { + return km_default(); +} +var init_kh = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js"() { + init_km(); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js +function ko_default() { + return { + localeError: error25() + }; +} +var error25; +var init_ko = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"() { + init_util(); + error25 = () => { + const Sizable = { + string: { unit: "\uBB38\uC790", verb: "to have" }, + file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, + array: { unit: "\uAC1C", verb: "to have" }, + set: { unit: "\uAC1C", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\uC785\uB825", + email: "\uC774\uBA54\uC77C \uC8FC\uC18C", + url: "URL", + emoji: "\uC774\uBAA8\uC9C0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", + date: "ISO \uB0A0\uC9DC", + time: "ISO \uC2DC\uAC04", + duration: "ISO \uAE30\uAC04", + ipv4: "IPv4 \uC8FC\uC18C", + ipv6: "IPv6 \uC8FC\uC18C", + cidrv4: "IPv4 \uBC94\uC704", + cidrv6: "IPv6 \uBC94\uC704", + base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + json_string: "JSON \uBB38\uC790\uC5F4", + e164: "E.164 \uBC88\uD638", + jwt: "JWT", + template_literal: "\uC785\uB825" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "too_big": { + const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; + const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; + const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) { + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; + } + if (_issue.format === "ends_with") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "includes") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "regex") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "unrecognized_keys": + return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; + case "invalid_union": + return `\uC798\uBABB\uB41C \uC785\uB825`; + case "invalid_element": + return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; + default: + return `\uC798\uBABB\uB41C \uC785\uB825`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js +function getUnitTypeFromNumber(number4) { + const abs = Math.abs(number4); + const last = abs % 10; + const last2 = abs % 100; + if (last2 >= 11 && last2 <= 19 || last === 0) + return "many"; + if (last === 1) + return "one"; + return "few"; +} +function lt_default() { + return { + localeError: error26() + }; +} +var capitalizeFirstCharacter, error26; +var init_lt = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"() { + init_util(); + capitalizeFirstCharacter = (text) => { + return text.charAt(0).toUpperCase() + text.slice(1); + }; + error26 = () => { + const Sizable = { + string: { + unit: { + one: "simbolis", + few: "simboliai", + many: "simboli\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", + notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", + notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" + } + } + }, + file: { + unit: { + one: "baitas", + few: "baitai", + many: "bait\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne didesnis kaip", + notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", + notInclusive: "turi b\u016Bti didesnis kaip" + } + } + }, + array: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + }, + set: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + } + }; + function getSizing(origin, unitType, inclusive, targetShouldBe) { + const result = Sizable[origin] ?? null; + if (result === null) + return result; + return { + unit: result.unit[unitType], + verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] + }; + } + const FormatDictionary = { + regex: "\u012Fvestis", + email: "el. pa\u0161to adresas", + url: "URL", + emoji: "jaustukas", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO data ir laikas", + date: "ISO data", + time: "ISO laikas", + duration: "ISO trukm\u0117", + ipv4: "IPv4 adresas", + ipv6: "IPv6 adresas", + cidrv4: "IPv4 tinklo prefiksas (CIDR)", + cidrv6: "IPv6 tinklo prefiksas (CIDR)", + base64: "base64 u\u017Ekoduota eilut\u0117", + base64url: "base64url u\u017Ekoduota eilut\u0117", + json_string: "JSON eilut\u0117", + e164: "E.164 numeris", + jwt: "JWT", + template_literal: "\u012Fvestis" + }; + const TypeDictionary = { + nan: "NaN", + number: "skai\u010Dius", + bigint: "sveikasis skai\u010Dius", + string: "eilut\u0117", + boolean: "login\u0117 reik\u0161m\u0117", + undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", + function: "funkcija", + symbol: "simbolis", + array: "masyvas", + object: "objektas", + null: "nulin\u0117 reik\u0161m\u0117" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; + } + return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; + return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; + case "too_big": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; + const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`; + } + case "too_small": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; + const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; + if (_issue.format === "regex") + return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; + return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; + case "unrecognized_keys": + return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Rastas klaidingas raktas"; + case "invalid_union": + return "Klaidinga \u012Fvestis"; + case "invalid_element": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; + } + default: + return "Klaidinga \u012Fvestis"; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js +function mk_default() { + return { + localeError: error27() + }; +} +var error27; +var init_mk = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"() { + init_util(); + error27 = () => { + const Sizable = { + string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u043D\u0435\u0441", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", + url: "URL", + emoji: "\u0435\u043C\u043E\u045F\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0443\u043C", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", + cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", + base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + json_string: "JSON \u043D\u0438\u0437\u0430", + e164: "E.164 \u0431\u0440\u043E\u0458", + jwt: "JWT", + template_literal: "\u0432\u043D\u0435\u0441" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0431\u0440\u043E\u0458", + array: "\u043D\u0438\u0437\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; + case "invalid_union": + return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; + case "invalid_element": + return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; + default: + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js +function ms_default() { + return { + localeError: error28() + }; +} +var error28; +var init_ms = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"() { + init_util(); + error28 = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "alamat e-mel", + 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: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombor" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak sah: dijangka ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue2.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue2.origin}`; + default: + return `Input tidak sah`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js +function nl_default() { + return { + localeError: error29() + }; +} +var error29; +var init_nl = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"() { + init_util(); + error29 = () => { + const Sizable = { + string: { unit: "tekens", verb: "heeft" }, + file: { unit: "bytes", verb: "heeft" }, + array: { unit: "elementen", verb: "heeft" }, + set: { unit: "elementen", verb: "heeft" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "invoer", + email: "emailadres", + 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 datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer" + }; + const TypeDictionary = { + nan: "NaN", + number: "getal" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; + } + return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; + return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; + if (sizing) + return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; + return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; + if (sizing) { + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue2.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue2.origin}`; + default: + return `Ongeldige invoer`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js +function no_default() { + return { + localeError: error30() + }; +} +var error30; +var init_no = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"() { + init_util(); + error30 = () => { + const Sizable = { + string: { unit: "tegn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "elementer", verb: "\xE5 inneholde" }, + set: { unit: "elementer", verb: "\xE5 inneholde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + 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 dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tall", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; + } + return `Ugyldig input: forventet ${expected}, fikk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js +function ota_default() { + return { + localeError: error31() + }; +} +var error31; +var init_ota = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"() { + init_util(); + error31 = () => { + const Sizable = { + string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giren", + email: "epostag\xE2h", + 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 heng\xE2m\u0131", + date: "ISO tarihi", + time: "ISO zaman\u0131", + duration: "ISO m\xFCddeti", + ipv4: "IPv4 ni\u015F\xE2n\u0131", + ipv6: "IPv6 ni\u015F\xE2n\u0131", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-\u015Fifreli metin", + base64url: "base64url-\u015Fifreli metin", + json_string: "JSON metin", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "giren" + }; + const TypeDictionary = { + nan: "NaN", + number: "numara", + array: "saf", + null: "gayb" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; + return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; + } + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; + if (_issue.format === "ends_with") + return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; + if (_issue.format === "regex") + return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; + return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; + case "invalid_union": + return "Giren tan\u0131namad\u0131."; + case "invalid_element": + return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; + default: + return `K\u0131ymet tan\u0131namad\u0131.`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js +function ps_default() { + return { + localeError: error32() + }; +} +var error32; +var init_ps = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"() { + init_util(); + error32 = () => { + const Sizable = { + string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, + array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u064A", + email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", + date: "\u0646\u06D0\u067C\u0647", + time: "\u0648\u062E\u062A", + duration: "\u0645\u0648\u062F\u0647", + ipv4: "\u062F IPv4 \u067E\u062A\u0647", + ipv6: "\u062F IPv6 \u067E\u062A\u0647", + cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", + cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", + base64: "base64-encoded \u0645\u062A\u0646", + base64url: "base64url-encoded \u0645\u062A\u0646", + json_string: "JSON \u0645\u062A\u0646", + e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u064A" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0627\u0631\u06D0" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; + } + return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; + } + if (_issue.format === "ends_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; + } + if (_issue.format === "includes") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; + } + if (_issue.format === "regex") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; + } + return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; + } + case "not_multiple_of": + return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; + case "unrecognized_keys": + return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + case "invalid_union": + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + case "invalid_element": + return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + default: + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js +function pl_default() { + return { + localeError: error33() + }; +} +var error33; +var init_pl = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"() { + init_util(); + error33 = () => { + const Sizable = { + string: { unit: "znak\xF3w", verb: "mie\u0107" }, + file: { unit: "bajt\xF3w", verb: "mie\u0107" }, + array: { unit: "element\xF3w", verb: "mie\u0107" }, + set: { unit: "element\xF3w", verb: "mie\u0107" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "wyra\u017Cenie", + email: "adres email", + 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: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", + base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", + json_string: "ci\u0105g znak\xF3w w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wej\u015Bcie" + }; + const TypeDictionary = { + nan: "NaN", + number: "liczba", + array: "tablica" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; + } + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; + return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; + return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nieprawid\u0142owy klucz w ${issue2.origin}`; + case "invalid_union": + return "Nieprawid\u0142owe dane wej\u015Bciowe"; + case "invalid_element": + return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; + default: + return `Nieprawid\u0142owe dane wej\u015Bciowe`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js +function pt_default() { + return { + localeError: error34() + }; +} +var error34; +var init_pt = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"() { + init_util(); + error34 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "padr\xE3o", + email: "endere\xE7o de e-mail", + 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: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "dura\xE7\xE3o ISO", + ipv4: "endere\xE7o IPv4", + ipv6: "endere\xE7o IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmero", + null: "nulo" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; + } + return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chave inv\xE1lida em ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido em ${issue2.origin}`; + default: + return `Campo inv\xE1lido`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js +function getRussianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +function ru_default() { + return { + localeError: error35() + }; +} +var error35; +var init_ru = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"() { + init_util(); + error35 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0438\u043C\u0432\u043E\u043B", + few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", + many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u0430", + many: "\u0431\u0430\u0439\u0442" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u044F", + duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", + base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", + json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; + case "invalid_element": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js +function sl_default() { + return { + localeError: error36() + }; +} +var error36; +var init_sl = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"() { + init_util(); + error36 = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "vnos", + email: "e-po\u0161tni naslov", + 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 datum in \u010Das", + date: "ISO datum", + time: "ISO \u010Das", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 \u0161tevilka", + jwt: "JWT", + template_literal: "vnos" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0161tevilo", + array: "tabela" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; + } + return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; + return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neveljaven klju\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue2.origin}`; + default: + return "Neveljaven vnos"; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js +function sv_default() { + return { + localeError: error37() + }; +} +var error37; +var init_sv = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"() { + init_util(); + error37 = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att inneh\xE5lla" }, + set: { unit: "objekt", verb: "att inneh\xE5lla" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regulj\xE4rt uttryck", + email: "e-postadress", + 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-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad str\xE4ng", + base64url: "base64url-kodad str\xE4ng", + json_string: "JSON-str\xE4ng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal" + }; + const TypeDictionary = { + nan: "NaN", + number: "antal", + array: "lista" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; + } + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; + return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + } + return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; + return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; + default: + return `Ogiltig input`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js +function ta_default() { + return { + localeError: error38() + }; +} +var error38; +var init_ta = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"() { + init_util(); + error38 = () => { + const Sizable = { + string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", + email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + 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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", + time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", + ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", + e164: "E.164 \u0B8E\u0BA3\u0BCD", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0B8E\u0BA3\u0BCD", + array: "\u0B85\u0BA3\u0BBF", + null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "ends_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "includes") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "regex") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + case "unrecognized_keys": + return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; + case "invalid_union": + return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; + case "invalid_element": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; + default: + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js +function th_default() { + return { + localeError: error39() + }; +} +var error39; +var init_th = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"() { + init_util(); + error39 = () => { + const Sizable = { + string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", + email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", + url: "URL", + emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", + time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", + ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", + cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", + base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", + base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", + json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", + e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", + template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", + array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", + null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; + if (_issue.format === "regex") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; + case "unrecognized_keys": + return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + case "invalid_union": + return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; + case "invalid_element": + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + default: + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js +function tr_default() { + return { + localeError: error40() + }; +} +var error40; +var init_tr = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"() { + init_util(); + error40 = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmal\u0131" }, + file: { unit: "bayt", verb: "olmal\u0131" }, + array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "girdi", + email: "e-posta adresi", + 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 tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO s\xFCre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aral\u0131\u011F\u0131", + cidrv6: "IPv6 aral\u0131\u011F\u0131", + base64: "base64 ile \u015Fifrelenmi\u015F metin", + base64url: "base64url ile \u015Fifrelenmi\u015F metin", + json_string: "JSON dizesi", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "\u015Eablon dizesi" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; + return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; + if (_issue.format === "ends_with") + return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; + if (_issue.format === "regex") + return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; + return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; + case "invalid_union": + return "Ge\xE7ersiz de\u011Fer"; + case "invalid_element": + return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; + default: + return `Ge\xE7ersiz de\u011Fer`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js +function uk_default() { + return { + localeError: error41() + }; +} +var error41; +var init_uk = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"() { + init_util(); + error41 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", + date: "\u0434\u0430\u0442\u0430 ISO", + time: "\u0447\u0430\u0441 ISO", + duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", + ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", + ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", + cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", + base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", + base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", + json_string: "\u0440\u044F\u0434\u043E\u043A JSON", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; + case "invalid_element": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; + default: + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js +function ua_default() { + return uk_default(); +} +var init_ua = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js"() { + init_uk(); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js +function ur_default() { + return { + localeError: error42() + }; +} +var error42; +var init_ur = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"() { + init_util(); + error42 = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, + file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, + array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0627\u0646 \u067E\u0679", + email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", + uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", + nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", + guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", + ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", + xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", + ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", + date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", + time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", + duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", + ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", + ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", + cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", + base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", + e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", + template_literal: "\u0627\u0646 \u067E\u0679" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0646\u0645\u0628\u0631", + array: "\u0622\u0631\u06D2", + null: "\u0646\u0644" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + } + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + } + if (_issue.format === "ends_with") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "includes") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "regex") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + case "unrecognized_keys": + return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; + case "invalid_union": + return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; + case "invalid_element": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; + default: + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js +function uz_default() { + return { + localeError: error43() + }; +} +var error43; +var init_uz = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"() { + init_util(); + error43 = () => { + const Sizable = { + string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, + file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, + array: { unit: "element", verb: "bo\u2018lishi kerak" }, + set: { unit: "element", verb: "bo\u2018lishi kerak" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "kirish", + email: "elektron pochta manzili", + 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 sana va vaqti", + date: "ISO sana", + time: "ISO vaqt", + duration: "ISO davomiylik", + ipv4: "IPv4 manzil", + ipv6: "IPv6 manzil", + mac: "MAC manzil", + cidrv4: "IPv4 diapazon", + cidrv6: "IPv6 diapazon", + base64: "base64 kodlangan satr", + base64url: "base64url kodlangan satr", + json_string: "JSON satr", + e164: "E.164 raqam", + jwt: "JWT", + template_literal: "kirish" + }; + const TypeDictionary = { + nan: "NaN", + number: "raqam", + array: "massiv" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; + } + return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; + return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; + if (_issue.format === "ends_with") + return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; + if (_issue.format === "includes") + return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; + if (_issue.format === "regex") + return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; + return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; + case "unrecognized_keys": + return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; + case "invalid_union": + return "Noto\u2018g\u2018ri kirish"; + case "invalid_element": + return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; + default: + return `Noto\u2018g\u2018ri kirish`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js +function vi_default() { + return { + localeError: error44() + }; +} +var error44; +var init_vi = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"() { + init_util(); + error44 = () => { + const Sizable = { + string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, + file: { unit: "byte", verb: "c\xF3" }, + array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0111\u1EA7u v\xE0o", + email: "\u0111\u1ECBa ch\u1EC9 email", + 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: "ng\xE0y gi\u1EDD ISO", + date: "ng\xE0y ISO", + time: "gi\u1EDD ISO", + duration: "kho\u1EA3ng th\u1EDDi gian ISO", + ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", + ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + cidrv4: "d\u1EA3i IPv4", + cidrv6: "d\u1EA3i IPv6", + base64: "chu\u1ED7i m\xE3 h\xF3a base64", + base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", + json_string: "chu\u1ED7i JSON", + e164: "s\u1ED1 E.164", + jwt: "JWT", + template_literal: "\u0111\u1EA7u v\xE0o" + }; + const TypeDictionary = { + nan: "NaN", + number: "s\u1ED1", + array: "m\u1EA3ng" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; + return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; + } + case "not_multiple_of": + return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; + case "unrecognized_keys": + return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + case "invalid_union": + return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; + case "invalid_element": + return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + default: + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js +function zh_CN_default() { + return { + localeError: error45() + }; +} +var error45; +var init_zh_CN = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"() { + init_util(); + error45 = () => { + const Sizable = { + string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, + file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, + array: { unit: "\u9879", verb: "\u5305\u542B" }, + set: { unit: "\u9879", verb: "\u5305\u542B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u8F93\u5165", + email: "\u7535\u5B50\u90AE\u4EF6", + url: "URL", + emoji: "\u8868\u60C5\u7B26\u53F7", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u671F\u65F6\u95F4", + date: "ISO\u65E5\u671F", + time: "ISO\u65F6\u95F4", + duration: "ISO\u65F6\u957F", + ipv4: "IPv4\u5730\u5740", + ipv6: "IPv6\u5730\u5740", + cidrv4: "IPv4\u7F51\u6BB5", + cidrv6: "IPv6\u7F51\u6BB5", + base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", + base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", + json_string: "JSON\u5B57\u7B26\u4E32", + e164: "E.164\u53F7\u7801", + jwt: "JWT", + template_literal: "\u8F93\u5165" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5B57", + array: "\u6570\u7EC4", + null: "\u7A7A\u503C(null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; + return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; + if (_issue.format === "ends_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; + if (_issue.format === "includes") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; + return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; + case "unrecognized_keys": + return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; + case "invalid_union": + return "\u65E0\u6548\u8F93\u5165"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; + default: + return `\u65E0\u6548\u8F93\u5165`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js +function zh_TW_default() { + return { + localeError: error46() + }; +} +var error46; +var init_zh_TW = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"() { + init_util(); + error46 = () => { + const Sizable = { + string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, + file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, + array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u8F38\u5165", + email: "\u90F5\u4EF6\u5730\u5740", + 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 \u65E5\u671F\u6642\u9593", + date: "ISO \u65E5\u671F", + time: "ISO \u6642\u9593", + duration: "ISO \u671F\u9593", + ipv4: "IPv4 \u4F4D\u5740", + ipv6: "IPv6 \u4F4D\u5740", + cidrv4: "IPv4 \u7BC4\u570D", + cidrv6: "IPv6 \u7BC4\u570D", + base64: "base64 \u7DE8\u78BC\u5B57\u4E32", + base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", + json_string: "JSON \u5B57\u4E32", + e164: "E.164 \u6578\u503C", + jwt: "JWT", + template_literal: "\u8F38\u5165" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; + return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; + } + if (_issue.format === "ends_with") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; + if (_issue.format === "includes") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; + return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; + case "unrecognized_keys": + return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; + case "invalid_union": + return "\u7121\u6548\u7684\u8F38\u5165\u503C"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; + default: + return `\u7121\u6548\u7684\u8F38\u5165\u503C`; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js +function yo_default() { + return { + localeError: error47() + }; +} +var error47; +var init_yo = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"() { + init_util(); + error47 = () => { + const Sizable = { + string: { unit: "\xE0mi", verb: "n\xED" }, + file: { unit: "bytes", verb: "n\xED" }, + array: { unit: "nkan", verb: "n\xED" }, + set: { unit: "nkan", verb: "n\xED" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", + email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", + 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: "\xE0k\xF3k\xF2 ISO", + date: "\u1ECDj\u1ECD\u0301 ISO", + time: "\xE0k\xF3k\xF2 ISO", + duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", + ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", + ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + cidrv4: "\xE0gb\xE8gb\xE8 IPv4", + cidrv6: "\xE0gb\xE8gb\xE8 IPv6", + base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", + base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", + json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", + e164: "n\u1ECD\u0301mb\xE0 E.164", + jwt: "JWT", + template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\u1ECD\u0301mb\xE0", + array: "akop\u1ECD" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; + return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; + return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; + case "unrecognized_keys": + return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + case "invalid_union": + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + case "invalid_element": + return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + default: + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + } + }; + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js +var locales_exports = {}; +__export(locales_exports, { + ar: () => ar_default, + az: () => az_default, + be: () => be_default, + bg: () => bg_default, + ca: () => ca_default, + cs: () => cs_default, + da: () => da_default, + de: () => de_default, + en: () => en_default, + eo: () => eo_default, + es: () => es_default, + fa: () => fa_default, + fi: () => fi_default, + fr: () => fr_default, + frCA: () => fr_CA_default, + he: () => he_default, + hu: () => hu_default, + hy: () => hy_default, + id: () => id_default, + is: () => is_default, + it: () => it_default, + ja: () => ja_default, + ka: () => ka_default, + kh: () => kh_default, + km: () => km_default, + ko: () => ko_default, + lt: () => lt_default, + mk: () => mk_default, + ms: () => ms_default, + nl: () => nl_default, + no: () => no_default, + ota: () => ota_default, + pl: () => pl_default, + ps: () => ps_default, + pt: () => pt_default, + ru: () => ru_default, + sl: () => sl_default, + sv: () => sv_default, + ta: () => ta_default, + th: () => th_default, + tr: () => tr_default, + ua: () => ua_default, + uk: () => uk_default, + ur: () => ur_default, + uz: () => uz_default, + vi: () => vi_default, + yo: () => yo_default, + zhCN: () => zh_CN_default, + zhTW: () => zh_TW_default +}); +var init_locales = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js"() { + init_ar(); + init_az(); + init_be(); + init_bg(); + init_ca(); + init_cs(); + init_da(); + init_de(); + init_en(); + init_eo(); + init_es(); + init_fa(); + init_fi(); + init_fr(); + init_fr_CA(); + init_he(); + init_hu(); + init_hy(); + init_id(); + init_is(); + init_it(); + init_ja(); + init_ka(); + init_kh(); + init_km(); + init_ko(); + init_lt(); + init_mk(); + init_ms(); + init_nl(); + init_no(); + init_ota(); + init_ps(); + init_pl(); + init_pt(); + init_ru(); + init_sl(); + init_sv(); + init_ta(); + init_th(); + init_tr(); + init_ua(); + init_uk(); + init_ur(); + init_uz(); + init_vi(); + init_zh_CN(); + init_zh_TW(); + init_yo(); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js +function registry() { + return new $ZodRegistry(); +} +var _a, $output, $input, $ZodRegistry, globalRegistry; +var init_registries = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js"() { + $output = Symbol("ZodOutput"); + $input = Symbol("ZodInput"); + $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema3, ..._meta) { + const meta3 = _meta[0]; + this._map.set(schema3, meta3); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.set(meta3.id, schema3); + } + return this; + } + clear() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema3) { + const meta3 = this._map.get(schema3); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.delete(meta3.id); + } + this._map.delete(schema3); + return this; + } + get(schema3) { + const p = schema3._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + const f = { ...pm, ...this._map.get(schema3) }; + return Object.keys(f).length ? f : void 0; + } + return this._map.get(schema3); + } + has(schema3) { + return this._map.has(schema3); + } + }; + (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); + globalRegistry = globalThis.__zod_globalRegistry; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js +// @__NO_SIDE_EFFECTS__ +function _string(Class2, params) { + return new Class2({ + type: "string", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class2, params) { + return new Class2({ + type: "string", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class2, params) { + return new Class2({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class2, params) { + return new Class2({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class2, params) { + return new Class2({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _emoji2(Class2, params) { + return new Class2({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class2, params) { + return new Class2({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid(Class2, params) { + return new Class2({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class2, params) { + return new Class2({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class2, params) { + return new Class2({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class2, params) { + return new Class2({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class2, params) { + return new Class2({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class2, params) { + return new Class2({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class2, params) { + return new Class2({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class2, params) { + return new Class2({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class2, params) { + return new Class2({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class2, params) { + return new Class2({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class2, params) { + return new Class2({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class2, params) { + return new Class2({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class2, params) { + return new Class2({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class2, params) { + return new Class2({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class2, params) { + return new Class2({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class2, params) { + return new Class2({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class2, params) { + return new Class2({ + type: "number", + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class2, params) { + return new Class2({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class2, params) { + return new Class2({ + type: "boolean", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class2, params) { + return new Class2({ + type: "boolean", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class2, params) { + return new Class2({ + type: "bigint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class2, params) { + return new Class2({ + type: "bigint", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class2, params) { + return new Class2({ + type: "symbol", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _undefined2(Class2, params) { + return new Class2({ + type: "undefined", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _null2(Class2, params) { + return new Class2({ + type: "null", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class2) { + return new Class2({ + type: "any" + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class2, params) { + return new Class2({ + type: "void", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class2, params) { + return new Class2({ + type: "date", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class2, params) { + return new Class2({ + type: "date", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class2, params) { + return new Class2({ + type: "nan", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return /* @__PURE__ */ _gt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return /* @__PURE__ */ _lt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return /* @__PURE__ */ _lte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return /* @__PURE__ */ _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...normalizeParams(params), + size + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema3, params) { + return new $ZodCheckProperty({ + check: "property", + property, + schema: schema3, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); +} +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); +} +// @__NO_SIDE_EFFECTS__ +function _trim() { + return /* @__PURE__ */ _overwrite((input) => input.trim()); +} +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); +} +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); +} +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return /* @__PURE__ */ _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class2, element, params) { + return new Class2({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class2, options, params) { + return new Class2({ + type: "union", + options, + ...normalizeParams(params) + }); +} +function _xor(Class2, options, params) { + return new Class2({ + type: "union", + options, + inclusive: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class2, discriminator, options, params) { + return new Class2({ + type: "union", + options, + discriminator, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class2, left, right) { + return new Class2({ + type: "intersection", + left, + right + }); +} +// @__NO_SIDE_EFFECTS__ +function _tuple(Class2, items, _paramsOrRest, _params2) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params2 : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class2({ + type: "tuple", + items, + rest, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class2, keyType, valueType, params) { + return new Class2({ + type: "record", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class2, keyType, valueType, params) { + return new Class2({ + type: "map", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class2, valueType, params) { + return new Class2({ + type: "set", + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class2, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nativeEnum(Class2, entries, params) { + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class2, value, params) { + return new Class2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class2, params) { + return new Class2({ + type: "file", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class2, fn) { + return new Class2({ + type: "transform", + transform: fn + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class2, innerType) { + return new Class2({ + type: "optional", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class2, innerType) { + return new Class2({ + type: "nullable", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class2, innerType, defaultValue) { + return new Class2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class2, innerType, params) { + return new Class2({ + type: "nonoptional", + innerType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class2, innerType) { + return new Class2({ + type: "success", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class2, innerType, catchValue) { + return new Class2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class2, in_, out) { + return new Class2({ + type: "pipe", + in: in_, + out + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class2, innerType) { + return new Class2({ + type: "readonly", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class2, parts, params) { + return new Class2({ + type: "template_literal", + parts, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class2, getter) { + return new Class2({ + type: "lazy", + getter + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class2, innerType) { + return new Class2({ + type: "promise", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class2, fn, _params2) { + const norm = normalizeParams(_params2); + norm.abort ?? (norm.abort = true); + const schema3 = new Class2({ + type: "custom", + check: "custom", + fn, + ...norm + }); + return schema3; +} +// @__NO_SIDE_EFFECTS__ +function _refine(Class2, fn, _params2) { + const schema3 = new Class2({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params2) + }); + return schema3; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn) { + const ch = /* @__PURE__ */ _check((payload) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(issue(issue2, payload.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(issue(_issue)); + } + }; + return fn(payload.value, payload); + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params) + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params2) { + const params = normalizeParams(_params2); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); + falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? $ZodCodec; + const _Boolean = Classes.Boolean ?? $ZodBoolean; + const _String = Classes.String ?? $ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec2 = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: (input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } else if (falsySet.has(data)) { + return false; + } else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec2, + continue: false + }); + return {}; + } + }, + reverseTransform: (input, _payload3) => { + if (input === true) { + return truthyArray[0] || "true"; + } else { + return falsyArray[0] || "false"; + } + }, + error: params.error + }); + return codec2; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class2, format, fnOrRegex, _params2 = {}) { + const params = normalizeParams(_params2); + const def = { + ...normalizeParams(_params2), + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class2(def); + return inst; +} +var TimePrecision; +var init_api = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js"() { + init_checks(); + init_registries(); + init_schemas(); + init_util(); + TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6 + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js +function initializeContext(params) { + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { + }), + io: params?.io ?? "output", + counter: 0, + seen: /* @__PURE__ */ new Map(), + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + external: params?.external ?? void 0 + }; +} +function process2(schema3, ctx, _params2 = { path: [], schemaPath: [] }) { + var _a30; + const def = schema3._zod.def; + const seen = ctx.seen.get(schema3); + if (seen) { + seen.count++; + const isCycle = _params2.schemaPath.includes(schema3); + if (isCycle) { + seen.cycle = _params2.path; + } + return seen.schema; + } + const result = { schema: {}, count: 1, cycle: void 0, path: _params2.path }; + ctx.seen.set(schema3, result); + const overrideSchema = schema3._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params2, + schemaPath: [..._params2.schemaPath, schema3], + path: _params2.path + }; + if (schema3._zod.processJSONSchema) { + schema3._zod.processJSONSchema(ctx, result.schema, params); + } else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema3, ctx, _json, params); + } + const parent = schema3._zod.parent; + if (parent) { + if (!result.ref) + result.ref = parent; + process2(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta3 = ctx.metadataRegistry.get(schema3); + if (meta3) + Object.assign(result.schema, meta3); + if (ctx.io === "input" && isTransforming(schema3)) { + delete result.schema.examples; + delete result.schema.default; + } + if (ctx.io === "input" && result.schema._prefault) + (_a30 = result.schema).default ?? (_a30.default = result.schema._prefault); + delete result.schema._prefault; + const _result = ctx.seen.get(schema3); + return _result.schema; +} +function extractDefs(ctx, schema3) { + const root = ctx.seen.get(schema3); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const idToSchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + const makeURI = (entry) => { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; + const uriGenerator = ctx.external.uri ?? ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + 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: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema4 = seen.schema; + for (const key in schema4) { + delete schema4[key]; + } + schema4.$ref = ref; + }; + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + } + } + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (schema3 === entry[0]) { + extractToDef(entry); + continue; + } + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema3 !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + continue; + } + } + } +} +function finalize(ctx, schema3) { + const root = ctx.seen.get(schema3); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + if (seen.ref === null) + return; + const schema4 = seen.def ?? seen.schema; + const _cached2 = { ...schema4 }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema4.allOf = schema4.allOf ?? []; + schema4.allOf.push(refSchema); + } else { + Object.assign(schema4, refSchema); + } + Object.assign(schema4, _cached2); + const isParentRef = zodSchema._zod.parent === ref; + if (isParentRef) { + for (const key in schema4) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached2)) { + delete schema4[key]; + } + } + } + if (refSchema.$ref && refSeen.def) { + for (const key in schema4) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema4[key]) === JSON.stringify(refSeen.def[key])) { + delete schema4[key]; + } + } + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema4.$ref = parentSeen.schema.$ref; + if (parentSeen.def) { + for (const key in schema4) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema4[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema4[key]; + } + } + } + } + } + ctx.override({ + zodSchema, + jsonSchema: schema4, + path: seen.path ?? [] + }); + }; + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } else if (ctx.target === "openapi-3.0") { + } else { + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema3)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + Object.assign(result, root.def ?? root.schema); + const defs = ctx.external?.defs ?? {}; + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } + } + if (ctx.external) { + } else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema3["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema3, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema3, "output", ctx.processors) + } + }, + enumerable: false, + writable: false + }); + return finalized; + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema2, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema2)) + return false; + ctx.seen.add(_schema2); + const def = _schema2._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + 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") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +var createToJSONSchemaMethod, createStandardJSONSchemaMethod; +var init_to_json_schema = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"() { + init_registries(); + createToJSONSchemaMethod = (schema3, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + process2(schema3, ctx); + extractDefs(ctx, schema3); + return finalize(ctx, schema3); + }; + createStandardJSONSchemaMethod = (schema3, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); + process2(schema3, ctx); + extractDefs(ctx, schema3); + return finalize(ctx, schema3); + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js +function toJSONSchema(input, params) { + if ("_idmap" in input) { + const registry2 = input; + const ctx2 = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + for (const entry of registry2._idmap.entries()) { + const [_, schema3] = entry; + process2(schema3, ctx2); + } + const schemas = {}; + const external = { + registry: registry2, + uri: params?.uri, + defs + }; + ctx2.external = external; + for (const entry of registry2._idmap.entries()) { + const [key, schema3] = entry; + extractDefs(ctx2, schema3); + schemas[key] = finalize(ctx2, schema3); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; + } + const ctx = initializeContext({ ...params, processors: allProcessors }); + process2(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} +var formatMap, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, recordProcessor, nullableProcessor, nonoptionalProcessor, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors; +var init_json_schema_processors = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"() { + init_to_json_schema(); + init_util(); + formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set + }; + stringProcessor = (schema3, ctx, _json, _params2) => { + const json2 = _json; + json2.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema3._zod.bag; + if (typeof minimum === "number") + json2.minLength = minimum; + if (typeof maximum === "number") + json2.maxLength = maximum; + if (format) { + json2.format = formatMap[format] ?? format; + if (json2.format === "") + delete json2.format; + if (format === "time") { + delete json2.format; + } + } + if (contentEncoding) + json2.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json2.pattern = regexes[0].source; + else if (regexes.length > 1) { + json2.allOf = [ + ...regexes.map((regex) => ({ + ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } + }; + numberProcessor = (schema3, ctx, _json, _params2) => { + const json2 = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema3._zod.bag; + if (typeof format === "string" && format.includes("int")) + json2.type = "integer"; + else + json2.type = "number"; + if (typeof exclusiveMinimum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.minimum = exclusiveMinimum; + json2.exclusiveMinimum = true; + } else { + json2.exclusiveMinimum = exclusiveMinimum; + } + } + if (typeof minimum === "number") { + json2.minimum = minimum; + if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { + if (exclusiveMinimum >= minimum) + delete json2.minimum; + else + delete json2.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.maximum = exclusiveMaximum; + json2.exclusiveMaximum = true; + } else { + json2.exclusiveMaximum = exclusiveMaximum; + } + } + if (typeof maximum === "number") { + json2.maximum = maximum; + if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { + if (exclusiveMaximum <= maximum) + delete json2.maximum; + else + delete json2.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json2.multipleOf = multipleOf; + }; + booleanProcessor = (_schema2, _ctx, json2, _params2) => { + json2.type = "boolean"; + }; + bigintProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + }; + symbolProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + }; + nullProcessor = (_schema2, ctx, json2, _params2) => { + if (ctx.target === "openapi-3.0") { + json2.type = "string"; + json2.nullable = true; + json2.enum = [null]; + } else { + json2.type = "null"; + } + }; + undefinedProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } + }; + voidProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + }; + neverProcessor = (_schema2, _ctx, json2, _params2) => { + json2.not = {}; + }; + anyProcessor = (_schema2, _ctx, _json, _params2) => { + }; + unknownProcessor = (_schema2, _ctx, _json, _params2) => { + }; + dateProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + }; + enumProcessor = (schema3, _ctx, json2, _params2) => { + const def = schema3._zod.def; + const values = getEnumValues(def.entries); + if (values.every((v) => typeof v === "number")) + json2.type = "number"; + if (values.every((v) => typeof v === "string")) + json2.type = "string"; + json2.enum = values; + }; + literalProcessor = (schema3, ctx, json2, _params2) => { + const def = schema3._zod.def; + const vals = []; + for (const val of def.values) { + if (val === void 0) { + if (ctx.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } 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)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json2.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.enum = [val]; + } else { + json2.const = val; + } + } else { + if (vals.every((v) => typeof v === "number")) + json2.type = "number"; + if (vals.every((v) => typeof v === "string")) + json2.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json2.type = "boolean"; + if (vals.every((v) => v === null)) + json2.type = "null"; + json2.enum = vals; + } + }; + nanProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + }; + templateLiteralProcessor = (schema3, _ctx, json2, _params2) => { + const _json = json2; + const pattern = schema3._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; + }; + fileProcessor = (schema3, _ctx, json2, _params2) => { + const _json = json2; + const file2 = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema3._zod.bag; + if (minimum !== void 0) + file2.minLength = minimum; + if (maximum !== void 0) + file2.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file2.contentMediaType = mime[0]; + Object.assign(_json, file2); + } else { + Object.assign(_json, file2); + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); + } + } else { + Object.assign(_json, file2); + } + }; + successProcessor = (_schema2, _ctx, json2, _params2) => { + json2.type = "boolean"; + }; + customProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + }; + functionProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Function types cannot be represented in JSON Schema"); + } + }; + transformProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + }; + mapProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + }; + setProcessor = (_schema2, ctx, _json, _params2) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + }; + arrayProcessor = (schema3, ctx, _json, params) => { + const json2 = _json; + const def = schema3._zod.def; + const { minimum, maximum } = schema3._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + json2.type = "array"; + json2.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); + }; + objectProcessor = (schema3, ctx, _json, params) => { + const json2 = _json; + const def = schema3._zod.def; + json2.type = "object"; + json2.properties = {}; + const shape = def.shape; + for (const key in shape) { + json2.properties[key] = process2(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 === void 0; + } else { + return v.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json2.required = Array.from(requiredKeys); + } + if (def.catchall?._zod.def.type === "never") { + json2.additionalProperties = false; + } else if (!def.catchall) { + if (ctx.io === "output") + json2.additionalProperties = false; + } else if (def.catchall) { + json2.additionalProperties = process2(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + }; + unionProcessor = (schema3, ctx, json2, params) => { + const def = schema3._zod.def; + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => process2(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] + })); + if (isExclusive) { + json2.oneOf = options; + } else { + json2.anyOf = options; + } + }; + intersectionProcessor = (schema3, ctx, json2, params) => { + const def = schema3._zod.def; + const a = process2(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b = process2(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [a], + ...isSimpleIntersection(b) ? b.allOf : [b] + ]; + json2.allOf = allOf; + }; + tupleProcessor = (schema3, ctx, _json, params) => { + const json2 = _json; + const def = schema3._zod.def; + json2.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => process2(x, ctx, { + ...params, + path: [...params.path, prefixPath, i] + })); + const rest = def.rest ? process2(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] + }) : null; + if (ctx.target === "draft-2020-12") { + json2.prefixItems = prefixItems; + if (rest) { + json2.items = rest; + } + } else if (ctx.target === "openapi-3.0") { + json2.items = { + anyOf: prefixItems + }; + if (rest) { + json2.items.anyOf.push(rest); + } + json2.minItems = prefixItems.length; + if (!rest) { + json2.maxItems = prefixItems.length; + } + } else { + json2.items = prefixItems; + if (rest) { + json2.additionalItems = rest; + } + } + const { minimum, maximum } = schema3._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + }; + recordProcessor = (schema3, ctx, _json, params) => { + const json2 = _json; + const def = schema3._zod.def; + json2.type = "object"; + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + const valueSchema = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"] + }); + json2.patternProperties = {}; + for (const pattern of patterns) { + json2.patternProperties[pattern.source] = valueSchema; + } + } else { + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json2.propertyNames = process2(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"] + }); + } + json2.additionalProperties = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + const keyValues = keyType._zod.values; + if (keyValues) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json2.required = validKeyValues; + } + } + }; + nullableProcessor = (schema3, ctx, json2, params) => { + const def = schema3._zod.def; + const inner = process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema3); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json2.nullable = true; + } else { + json2.anyOf = [inner, { type: "null" }]; + } + }; + nonoptionalProcessor = (schema3, ctx, _json, params) => { + const def = schema3._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = def.innerType; + }; + defaultProcessor = (schema3, ctx, json2, params) => { + const def = schema3._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = def.innerType; + json2.default = JSON.parse(JSON.stringify(def.defaultValue)); + }; + prefaultProcessor = (schema3, ctx, json2, params) => { + const def = schema3._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = def.innerType; + if (ctx.io === "input") + json2._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + }; + catchProcessor = (schema3, ctx, json2, params) => { + const def = schema3._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json2.default = catchValue; + }; + pipeProcessor = (schema3, ctx, _json, params) => { + const def = schema3._zod.def; + const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = innerType; + }; + readonlyProcessor = (schema3, ctx, json2, params) => { + const def = schema3._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = def.innerType; + json2.readOnly = true; + }; + promiseProcessor = (schema3, ctx, _json, params) => { + const def = schema3._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = def.innerType; + }; + optionalProcessor = (schema3, ctx, _json, params) => { + const def = schema3._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = def.innerType; + }; + lazyProcessor = (schema3, ctx, _json, params) => { + const innerType = schema3._zod.innerType; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema3); + seen.ref = innerType; + }; + allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js +var JSONSchemaGenerator; +var init_json_schema_generator = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"() { + init_json_schema_processors(); + init_to_json_schema(); + JSONSchemaGenerator = class { + /** @deprecated Access via ctx instead */ + get metadataRegistry() { + return this.ctx.metadataRegistry; + } + /** @deprecated Access via ctx instead */ + get target() { + return this.ctx.target; + } + /** @deprecated Access via ctx instead */ + get unrepresentable() { + return this.ctx.unrepresentable; + } + /** @deprecated Access via ctx instead */ + get override() { + return this.ctx.override; + } + /** @deprecated Access via ctx instead */ + get io() { + return this.ctx.io; + } + /** @deprecated Access via ctx instead */ + get counter() { + return this.ctx.counter; + } + set counter(value) { + this.ctx.counter = value; + } + /** @deprecated Access via ctx instead */ + get seen() { + return this.ctx.seen; + } + constructor(params) { + let normalizedTarget = params?.target ?? "draft-2020-12"; + if (normalizedTarget === "draft-4") + normalizedTarget = "draft-04"; + if (normalizedTarget === "draft-7") + normalizedTarget = "draft-07"; + this.ctx = initializeContext({ + processors: allProcessors, + target: normalizedTarget, + ...params?.metadata && { metadata: params.metadata }, + ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, + ...params?.override && { override: params.override }, + ...params?.io && { io: params.io } + }); + } + /** + * Process a schema to prepare it for JSON Schema generation. + * This must be called before emit(). + */ + process(schema3, _params2 = { path: [], schemaPath: [] }) { + return process2(schema3, this.ctx, _params2); + } + /** + * Emit the final JSON Schema after processing. + * Must call process() first. + */ + emit(schema3, _params2) { + if (_params2) { + if (_params2.cycles) + this.ctx.cycles = _params2.cycles; + if (_params2.reused) + this.ctx.reused = _params2.reused; + if (_params2.external) + this.ctx.external = _params2.external; + } + extractDefs(this.ctx, schema3); + const result = finalize(this.ctx, schema3); + const { "~standard": _, ...plainResult } = result; + return plainResult; + } + }; + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js +var json_schema_exports = {}; +var init_json_schema = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"() { + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js +var core_exports2 = {}; +__export(core_exports2, { + $ZodAny: () => $ZodAny, + $ZodArray: () => $ZodArray, + $ZodAsyncError: () => $ZodAsyncError, + $ZodBase64: () => $ZodBase64, + $ZodBase64URL: () => $ZodBase64URL, + $ZodBigInt: () => $ZodBigInt, + $ZodBigIntFormat: () => $ZodBigIntFormat, + $ZodBoolean: () => $ZodBoolean, + $ZodCIDRv4: () => $ZodCIDRv4, + $ZodCIDRv6: () => $ZodCIDRv6, + $ZodCUID: () => $ZodCUID, + $ZodCUID2: () => $ZodCUID2, + $ZodCatch: () => $ZodCatch, + $ZodCheck: () => $ZodCheck, + $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, + $ZodCheckEndsWith: () => $ZodCheckEndsWith, + $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, + $ZodCheckIncludes: () => $ZodCheckIncludes, + $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, + $ZodCheckLessThan: () => $ZodCheckLessThan, + $ZodCheckLowerCase: () => $ZodCheckLowerCase, + $ZodCheckMaxLength: () => $ZodCheckMaxLength, + $ZodCheckMaxSize: () => $ZodCheckMaxSize, + $ZodCheckMimeType: () => $ZodCheckMimeType, + $ZodCheckMinLength: () => $ZodCheckMinLength, + $ZodCheckMinSize: () => $ZodCheckMinSize, + $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, + $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, + $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperty: () => $ZodCheckProperty, + $ZodCheckRegex: () => $ZodCheckRegex, + $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, + $ZodCheckStartsWith: () => $ZodCheckStartsWith, + $ZodCheckStringFormat: () => $ZodCheckStringFormat, + $ZodCheckUpperCase: () => $ZodCheckUpperCase, + $ZodCodec: () => $ZodCodec, + $ZodCustom: () => $ZodCustom, + $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodDate: () => $ZodDate, + $ZodDefault: () => $ZodDefault, + $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, + $ZodE164: () => $ZodE164, + $ZodEmail: () => $ZodEmail, + $ZodEmoji: () => $ZodEmoji, + $ZodEncodeError: () => $ZodEncodeError, + $ZodEnum: () => $ZodEnum, + $ZodError: () => $ZodError, + $ZodExactOptional: () => $ZodExactOptional, + $ZodFile: () => $ZodFile, + $ZodFunction: () => $ZodFunction, + $ZodGUID: () => $ZodGUID, + $ZodIPv4: () => $ZodIPv4, + $ZodIPv6: () => $ZodIPv6, + $ZodISODate: () => $ZodISODate, + $ZodISODateTime: () => $ZodISODateTime, + $ZodISODuration: () => $ZodISODuration, + $ZodISOTime: () => $ZodISOTime, + $ZodIntersection: () => $ZodIntersection, + $ZodJWT: () => $ZodJWT, + $ZodKSUID: () => $ZodKSUID, + $ZodLazy: () => $ZodLazy, + $ZodLiteral: () => $ZodLiteral, + $ZodMAC: () => $ZodMAC, + $ZodMap: () => $ZodMap, + $ZodNaN: () => $ZodNaN, + $ZodNanoID: () => $ZodNanoID, + $ZodNever: () => $ZodNever, + $ZodNonOptional: () => $ZodNonOptional, + $ZodNull: () => $ZodNull, + $ZodNullable: () => $ZodNullable, + $ZodNumber: () => $ZodNumber, + $ZodNumberFormat: () => $ZodNumberFormat, + $ZodObject: () => $ZodObject, + $ZodObjectJIT: () => $ZodObjectJIT, + $ZodOptional: () => $ZodOptional, + $ZodPipe: () => $ZodPipe, + $ZodPrefault: () => $ZodPrefault, + $ZodPromise: () => $ZodPromise, + $ZodReadonly: () => $ZodReadonly, + $ZodRealError: () => $ZodRealError, + $ZodRecord: () => $ZodRecord, + $ZodRegistry: () => $ZodRegistry, + $ZodSet: () => $ZodSet, + $ZodString: () => $ZodString, + $ZodStringFormat: () => $ZodStringFormat, + $ZodSuccess: () => $ZodSuccess, + $ZodSymbol: () => $ZodSymbol, + $ZodTemplateLiteral: () => $ZodTemplateLiteral, + $ZodTransform: () => $ZodTransform, + $ZodTuple: () => $ZodTuple, + $ZodType: () => $ZodType, + $ZodULID: () => $ZodULID, + $ZodURL: () => $ZodURL, + $ZodUUID: () => $ZodUUID, + $ZodUndefined: () => $ZodUndefined, + $ZodUnion: () => $ZodUnion, + $ZodUnknown: () => $ZodUnknown, + $ZodVoid: () => $ZodVoid, + $ZodXID: () => $ZodXID, + $ZodXor: () => $ZodXor, + $brand: () => $brand, + $constructor: () => $constructor, + $input: () => $input, + $output: () => $output, + Doc: () => Doc, + JSONSchema: () => json_schema_exports, + JSONSchemaGenerator: () => JSONSchemaGenerator, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + _any: () => _any, + _array: () => _array, + _base64: () => _base64, + _base64url: () => _base64url, + _bigint: () => _bigint, + _boolean: () => _boolean, + _catch: () => _catch, + _check: () => _check, + _cidrv4: () => _cidrv4, + _cidrv6: () => _cidrv6, + _coercedBigint: () => _coercedBigint, + _coercedBoolean: () => _coercedBoolean, + _coercedDate: () => _coercedDate, + _coercedNumber: () => _coercedNumber, + _coercedString: () => _coercedString, + _cuid: () => _cuid, + _cuid2: () => _cuid2, + _custom: () => _custom, + _date: () => _date, + _decode: () => _decode, + _decodeAsync: () => _decodeAsync, + _default: () => _default, + _discriminatedUnion: () => _discriminatedUnion, + _e164: () => _e164, + _email: () => _email, + _emoji: () => _emoji2, + _encode: () => _encode, + _encodeAsync: () => _encodeAsync, + _endsWith: () => _endsWith, + _enum: () => _enum, + _file: () => _file, + _float32: () => _float32, + _float64: () => _float64, + _gt: () => _gt, + _gte: () => _gte, + _guid: () => _guid, + _includes: () => _includes, + _int: () => _int, + _int32: () => _int32, + _int64: () => _int64, + _intersection: () => _intersection, + _ipv4: () => _ipv4, + _ipv6: () => _ipv6, + _isoDate: () => _isoDate, + _isoDateTime: () => _isoDateTime, + _isoDuration: () => _isoDuration, + _isoTime: () => _isoTime, + _jwt: () => _jwt, + _ksuid: () => _ksuid, + _lazy: () => _lazy, + _length: () => _length, + _literal: () => _literal, + _lowercase: () => _lowercase, + _lt: () => _lt, + _lte: () => _lte, + _mac: () => _mac, + _map: () => _map, + _max: () => _lte, + _maxLength: () => _maxLength, + _maxSize: () => _maxSize, + _mime: () => _mime, + _min: () => _gte, + _minLength: () => _minLength, + _minSize: () => _minSize, + _multipleOf: () => _multipleOf, + _nan: () => _nan, + _nanoid: () => _nanoid, + _nativeEnum: () => _nativeEnum, + _negative: () => _negative, + _never: () => _never, + _nonnegative: () => _nonnegative, + _nonoptional: () => _nonoptional, + _nonpositive: () => _nonpositive, + _normalize: () => _normalize, + _null: () => _null2, + _nullable: () => _nullable, + _number: () => _number, + _optional: () => _optional, + _overwrite: () => _overwrite, + _parse: () => _parse, + _parseAsync: () => _parseAsync, + _pipe: () => _pipe, + _positive: () => _positive, + _promise: () => _promise, + _property: () => _property, + _readonly: () => _readonly, + _record: () => _record, + _refine: () => _refine, + _regex: () => _regex, + _safeDecode: () => _safeDecode, + _safeDecodeAsync: () => _safeDecodeAsync, + _safeEncode: () => _safeEncode, + _safeEncodeAsync: () => _safeEncodeAsync, + _safeParse: () => _safeParse, + _safeParseAsync: () => _safeParseAsync, + _set: () => _set, + _size: () => _size, + _slugify: () => _slugify, + _startsWith: () => _startsWith, + _string: () => _string, + _stringFormat: () => _stringFormat, + _stringbool: () => _stringbool, + _success: () => _success, + _superRefine: () => _superRefine, + _symbol: () => _symbol, + _templateLiteral: () => _templateLiteral, + _toLowerCase: () => _toLowerCase, + _toUpperCase: () => _toUpperCase, + _transform: () => _transform, + _trim: () => _trim, + _tuple: () => _tuple, + _uint32: () => _uint32, + _uint64: () => _uint64, + _ulid: () => _ulid, + _undefined: () => _undefined2, + _union: () => _union, + _unknown: () => _unknown, + _uppercase: () => _uppercase, + _url: () => _url, + _uuid: () => _uuid, + _uuidv4: () => _uuidv4, + _uuidv6: () => _uuidv6, + _uuidv7: () => _uuidv7, + _void: () => _void, + _xid: () => _xid, + _xor: () => _xor, + clone: () => clone, + config: () => config, + createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, + createToJSONSchemaMethod: () => createToJSONSchemaMethod, + decode: () => decode, + decodeAsync: () => decodeAsync, + describe: () => describe, + encode: () => encode, + encodeAsync: () => encodeAsync, + extractDefs: () => extractDefs, + finalize: () => finalize, + flattenError: () => flattenError, + formatError: () => formatError, + globalConfig: () => globalConfig, + globalRegistry: () => globalRegistry, + initializeContext: () => initializeContext, + isValidBase64: () => isValidBase64, + isValidBase64URL: () => isValidBase64URL, + isValidJWT: () => isValidJWT, + locales: () => locales_exports, + meta: () => meta, + parse: () => parse, + parseAsync: () => parseAsync, + prettifyError: () => prettifyError, + process: () => process2, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode, + safeDecodeAsync: () => safeDecodeAsync, + safeEncode: () => safeEncode, + safeEncodeAsync: () => safeEncodeAsync, + safeParse: () => safeParse, + safeParseAsync: () => safeParseAsync, + toDotPath: () => toDotPath, + toJSONSchema: () => toJSONSchema, + treeifyError: () => treeifyError, + util: () => util_exports, + version: () => version +}); +var init_core2 = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"() { + init_core(); + init_parse(); + init_errors(); + init_schemas(); + init_checks(); + init_versions(); + init_util(); + init_regexes(); + init_locales(); + init_registries(); + init_doc(); + init_api(); + init_to_json_schema(); + init_json_schema_processors(); + init_json_schema_generator(); + init_json_schema(); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js +var checks_exports2 = {}; +__export(checks_exports2, { + endsWith: () => _endsWith, + gt: () => _gt, + gte: () => _gte, + includes: () => _includes, + length: () => _length, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + negative: () => _negative, + nonnegative: () => _nonnegative, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + overwrite: () => _overwrite, + positive: () => _positive, + property: () => _property, + regex: () => _regex, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + trim: () => _trim, + uppercase: () => _uppercase +}); +var init_checks2 = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"() { + init_core2(); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date2, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +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({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"() { + 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/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js +var initializer2, ZodError, ZodRealError; +var init_errors2 = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"() { + init_core2(); + init_core2(); + init_util(); + initializer2 = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper) + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper) + // enumerable: false, + }, + addIssue: { + value: (issue2) => { + inst.issues.push(issue2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + addIssues: { + value: (issues2) => { + inst.issues.push(...issues2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + } + // enumerable: false, + } + }); + }; + ZodError = $constructor("ZodError", initializer2); + ZodRealError = $constructor("ZodError", initializer2, { + Parent: Error + }); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js +var parse2, parseAsync2, safeParse2, safeParseAsync2, encode2, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2; +var init_parse2 = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"() { + init_core2(); + init_errors2(); + parse2 = /* @__PURE__ */ _parse(ZodRealError); + parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); + safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); + safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); + encode2 = /* @__PURE__ */ _encode(ZodRealError); + decode2 = /* @__PURE__ */ _decode(ZodRealError); + encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); + decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); + safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); + safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); + safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); + safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js +var schemas_exports2 = {}; +__export(schemas_exports2, { + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFunction: () => ZodFunction, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodIntersection: () => ZodIntersection, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + codec: () => codec, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + float32: () => float32, + float64: () => float64, + function: () => _function, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection2, + ipv4: () => ipv42, + ipv6: () => ipv62, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + literal: () => literal, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + mac: () => mac2, + map: () => map, + meta: () => meta2, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + never: () => never, + nonoptional: () => nonoptional, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + partialRecord: () => partialRecord, + pipe: () => pipe, + prefault: () => prefault, + preprocess: () => preprocess, + promise: () => promise, + readonly: () => readonly, + record: () => record, + refine: () => refine, + set: () => set, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + transform: () => transform, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + url: () => url, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor +}); +function string2(params) { + return _string(ZodString, params); +} +function email2(params) { + return _email(ZodEmail, params); +} +function guid2(params) { + return _guid(ZodGUID, params); +} +function uuid2(params) { + return _uuid(ZodUUID, params); +} +function uuidv4(params) { + return _uuidv4(ZodUUID, params); +} +function uuidv6(params) { + return _uuidv6(ZodUUID, params); +} +function uuidv7(params) { + return _uuidv7(ZodUUID, params); +} +function url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return _url(ZodURL, { + protocol: /^https?$/, + hostname: regexes_exports.domain, + ...util_exports.normalizeParams(params) + }); +} +function emoji2(params) { + return _emoji2(ZodEmoji, params); +} +function nanoid2(params) { + return _nanoid(ZodNanoID, params); +} +function cuid3(params) { + return _cuid(ZodCUID, params); +} +function cuid22(params) { + return _cuid2(ZodCUID2, params); +} +function ulid2(params) { + return _ulid(ZodULID, params); +} +function xid2(params) { + return _xid(ZodXID, params); +} +function ksuid2(params) { + return _ksuid(ZodKSUID, params); +} +function ipv42(params) { + return _ipv4(ZodIPv4, params); +} +function mac2(params) { + return _mac(ZodMAC, params); +} +function ipv62(params) { + return _ipv6(ZodIPv6, params); +} +function cidrv42(params) { + return _cidrv4(ZodCIDRv4, params); +} +function cidrv62(params) { + return _cidrv6(ZodCIDRv6, params); +} +function base642(params) { + return _base64(ZodBase64, params); +} +function base64url2(params) { + return _base64url(ZodBase64URL, params); +} +function e1642(params) { + return _e164(ZodE164, params); +} +function jwt(params) { + return _jwt(ZodJWT, params); +} +function stringFormat(format, fnOrRegex, _params2 = {}) { + return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params2); +} +function hostname2(_params2) { + return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params2); +} +function hex2(_params2) { + return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params2); +} +function hash(alg2, params) { + const enc2 = params?.enc ?? "hex"; + const format = `${alg2}_${enc2}`; + const regex = regexes_exports[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return _stringFormat(ZodCustomStringFormat, format, regex, params); +} +function number2(params) { + return _number(ZodNumber, params); +} +function int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return _float32(ZodNumberFormat, params); +} +function float64(params) { + return _float64(ZodNumberFormat, params); +} +function int32(params) { + return _int32(ZodNumberFormat, params); +} +function uint32(params) { + return _uint32(ZodNumberFormat, params); +} +function boolean2(params) { + return _boolean(ZodBoolean, params); +} +function bigint2(params) { + return _bigint(ZodBigInt, params); +} +function int64(params) { + return _int64(ZodBigIntFormat, params); +} +function uint64(params) { + return _uint64(ZodBigIntFormat, params); +} +function symbol(params) { + return _symbol(ZodSymbol, params); +} +function _undefined3(params) { + return _undefined2(ZodUndefined, params); +} +function _null3(params) { + return _null2(ZodNull, params); +} +function any() { + return _any(ZodAny); +} +function unknown() { + return _unknown(ZodUnknown); +} +function never(params) { + return _never(ZodNever, params); +} +function _void2(params) { + return _void(ZodVoid, params); +} +function date3(params) { + return _date(ZodDate, params); +} +function array(element, params) { + return _array(ZodArray, element, params); +} +function keyof(schema3) { + const shape = schema3._zod.def.shape; + return _enum2(Object.keys(shape)); +} +function object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...util_exports.normalizeParams(params) + }; + return new ZodObject(def); +} +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util_exports.normalizeParams(params) + }); +} +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...util_exports.normalizeParams(params) + }); +} +function union(options, params) { + return new ZodUnion({ + type: "union", + options, + ...util_exports.normalizeParams(params) + }); +} +function xor(options, params) { + return new ZodXor({ + type: "union", + options, + inclusive: false, + ...util_exports.normalizeParams(params) + }); +} +function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, + ...util_exports.normalizeParams(params) + }); +} +function intersection2(left, right) { + return new ZodIntersection({ + type: "intersection", + left, + right + }); +} +function tuple(items, _paramsOrRest, _params2) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params2 : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items, + rest, + ...util_exports.normalizeParams(params) + }); +} +function record(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function partialRecord(keyType, valueType, params) { + const k = clone(keyType); + k._zod.values = void 0; + return new ZodRecord({ + type: "record", + keyType: k, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType, + mode: "loose", + ...util_exports.normalizeParams(params) + }); +} +function map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function set(valueType, params) { + return new ZodSet({ + type: "set", + valueType, + ...util_exports.normalizeParams(params) + }); +} +function _enum2(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util_exports.normalizeParams(params) + }); +} +function file(params) { + return _file(ZodFile, params); +} +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); +} +function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType + }); +} +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType + }); +} +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType + }); +} +function nullish2(innerType) { + return optional(nullable(innerType)); +} +function _default2(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...util_exports.normalizeParams(params) + }); +} +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType + }); +} +function _catch2(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +function nan(params) { + return _nan(ZodNaN, params); +} +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + // ...util.normalizeParams(params), + }); +} +function codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out, + transform: params.decode, + reverseTransform: params.encode + }); +} +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType + }); +} +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util_exports.normalizeParams(params) + }); +} +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter + }); +} +function promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType + }); +} +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), + output: params?.output ?? unknown() + }); +} +function check(fn) { + const ch = new $ZodCheck({ + check: "custom" + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params2) { + return _custom(ZodCustom, fn ?? (() => true), _params2); +} +function refine(fn, _params2 = {}) { + return _refine(ZodCustom, fn, _params2); +} +function superRefine(fn) { + return _superRefine(fn); +} +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util_exports.normalizeParams(params) + }); + inst._zod.bag.Class = cls; + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...inst._zod.def.path ?? []] + }); + } + }; + return inst; +} +function json(params) { + const jsonSchema = lazy(() => { + return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); + }); + return jsonSchema; +} +function preprocess(fn, schema3) { + return pipe(transform(fn), schema3); +} +var ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodXor, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodCodec, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodFunction, ZodCustom, describe2, meta2, stringbool; +var init_schemas2 = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"() { + init_core2(); + init_core2(); + init_json_schema_processors(); + init_to_json_schema(); + init_checks2(); + init_iso(); + init_parse2(); + ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + $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.check = (...checks) => { + return inst.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { + parent: true + }); + }; + inst.with = inst.check; + inst.clone = (def2, params) => clone(inst, def2, params); + inst.brand = () => inst; + inst.register = (reg, meta3) => { + reg.add(inst, meta3); + return inst; + }; + inst.parse = (data, params) => parse2(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) => encode2(inst, data, params); + inst.decode = (data, params) => decode2(inst, data, params); + inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); + inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); + inst.safeEncode = (data, params) => safeEncode2(inst, data, params); + inst.safeDecode = (data, params) => safeDecode2(inst, data, params); + inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); + inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); + inst.refine = (check3, params) => inst.check(refine(check3, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(_overwrite(fn)); + inst.optional = () => optional(inst); + inst.exactOptional = () => exactOptional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg) => union([inst, arg]); + inst.and = (arg) => intersection2(inst, arg); + inst.transform = (tx) => pipe(inst, transform(tx)); + inst.default = (def2) => _default2(inst, def2); + inst.prefault = (def2) => prefault(inst, def2); + inst.catch = (params) => _catch2(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + inst.describe = (description) => { + const cl = inst.clone(); + globalRegistry.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + inst.meta = (...args) => { + if (args.length === 0) { + return globalRegistry.get(inst); + } + const cl = inst.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }; + inst.isOptional = () => inst.safeParse(void 0).success; + inst.isNullable = () => inst.safeParse(null).success; + inst.apply = (fn) => fn(inst); + return inst; + }); + _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + inst.regex = (...args) => inst.check(_regex(...args)); + inst.includes = (...args) => inst.check(_includes(...args)); + inst.startsWith = (...args) => inst.check(_startsWith(...args)); + inst.endsWith = (...args) => inst.check(_endsWith(...args)); + inst.min = (...args) => inst.check(_minLength(...args)); + inst.max = (...args) => inst.check(_maxLength(...args)); + inst.length = (...args) => inst.check(_length(...args)); + inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); + inst.lowercase = (params) => inst.check(_lowercase(params)); + inst.uppercase = (params) => inst.check(_uppercase(params)); + inst.trim = () => inst.check(_trim()); + inst.normalize = (...args) => inst.check(_normalize(...args)); + inst.toLowerCase = () => inst.check(_toLowerCase()); + inst.toUpperCase = () => inst.check(_toUpperCase()); + inst.slugify = () => inst.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)); + }); + ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); + }); + ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { + $ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { + $ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.int = (params) => inst.check(int(params)); + inst.safe = (params) => inst.check(int(params)); + inst.positive = (params) => inst.check(_gt(0, params)); + inst.nonnegative = (params) => inst.check(_gte(0, params)); + inst.negative = (params) => inst.check(_lt(0, params)); + inst.nonpositive = (params) => inst.check(_lte(0, params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + inst.step = (value, params) => inst.check(_multipleOf(value, params)); + inst.finite = () => inst; + 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; + }); + ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); + }); + ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); + }); + ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.positive = (params) => inst.check(_gt(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; + }); + ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { + $ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); + }); + ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { + $ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); + }); + ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { + $ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); + }); + ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); + }); + ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); + }); + ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); + }); + ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); + }); + ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { + $ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); + }); + ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; + }); + ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); + inst.element = def.element; + inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); + inst.nonempty = (params) => inst.check(_minLength(1, params)); + inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(_length(len, params)); + inst.unwrap = () => inst.element; + }); + ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); + util_exports.defineLazy(inst, "shape", () => { + return def.shape; + }); + inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); + inst.extend = (incoming) => { + return util_exports.extend(inst, incoming); + }; + inst.safeExtend = (incoming) => { + return util_exports.safeExtend(inst, incoming); + }; + inst.merge = (other) => util_exports.merge(inst, other); + inst.pick = (mask) => util_exports.pick(inst, mask); + inst.omit = (mask) => util_exports.omit(inst, mask); + inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]); + inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); + }); + ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); + inst.options = def.options; + }); + ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + $ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); + inst.options = def.options; + }); + ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); + }); + ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); + }); + ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + $ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest + }); + }); + ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + }); + ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + $ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); + }); + ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + $ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); + }); + ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + }); + ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + } + }); + }); + ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { + $ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); + inst.min = (size, params) => inst.check(_minSize(size, params)); + inst.max = (size, params) => inst.check(_maxSize(size, params)); + inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); + }); + ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + payload.issues.push(util_exports.issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output2) => { + payload.value = output2; + return payload; + }); + } + payload.value = output; + return payload; + }; + }); + ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; + }); + ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { + $ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; + }); + ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { + $ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); + }); + ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); + inst.in = def.in; + inst.out = def.out; + }); + ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + $ZodCodec.init(inst, def); + }); + ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { + $ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); + }); + ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.getter(); + }); + ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { + $ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { + $ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); + }); + ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); + }); + describe2 = describe; + meta2 = meta; + stringbool = (...args) => _stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString + }, ...args); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js +function setErrorMap(map3) { + config({ + customError: map3 + }); +} +function getErrorMap() { + return config().customError; +} +var ZodIssueCode, ZodFirstPartyTypeKind; +var init_compat = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"() { + init_core2(); + init_core2(); + ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom" + }; + /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { + })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js +function detectVersion(schema3, defaultTarget) { + const $schema = schema3.$schema; + if ($schema === "https://json-schema.org/draft/2020-12/schema") { + return "draft-2020-12"; + } + if ($schema === "http://json-schema.org/draft-07/schema#") { + return "draft-7"; + } + if ($schema === "http://json-schema.org/draft-04/schema#") { + return "draft-4"; + } + return defaultTarget ?? "draft-2020-12"; +} +function resolveRef(ref, ctx) { + if (!ref.startsWith("#")) { + throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); + } + const path3 = ref.slice(1).split("/").filter(Boolean); + if (path3.length === 0) { + return ctx.rootSchema; + } + const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; + if (path3[0] === defsKey) { + const key = path3[1]; + if (!key || !ctx.defs[key]) { + throw new Error(`Reference not found: ${ref}`); + } + return ctx.defs[key]; + } + throw new Error(`Reference not found: ${ref}`); +} +function convertBaseSchema(schema3, ctx) { + if (schema3.not !== void 0) { + if (typeof schema3.not === "object" && Object.keys(schema3.not).length === 0) { + return z.never(); + } + throw new Error("not is not supported in Zod (except { not: {} } for never)"); + } + if (schema3.unevaluatedItems !== void 0) { + throw new Error("unevaluatedItems is not supported"); + } + if (schema3.unevaluatedProperties !== void 0) { + throw new Error("unevaluatedProperties is not supported"); + } + if (schema3.if !== void 0 || schema3.then !== void 0 || schema3.else !== void 0) { + throw new Error("Conditional schemas (if/then/else) are not supported"); + } + if (schema3.dependentSchemas !== void 0 || schema3.dependentRequired !== void 0) { + throw new Error("dependentSchemas and dependentRequired are not supported"); + } + if (schema3.$ref) { + const refPath = schema3.$ref; + if (ctx.refs.has(refPath)) { + return ctx.refs.get(refPath); + } + if (ctx.processing.has(refPath)) { + return z.lazy(() => { + if (!ctx.refs.has(refPath)) { + throw new Error(`Circular reference not resolved: ${refPath}`); + } + return ctx.refs.get(refPath); + }); + } + ctx.processing.add(refPath); + const resolved = resolveRef(refPath, ctx); + const zodSchema2 = convertSchema(resolved, ctx); + ctx.refs.set(refPath, zodSchema2); + ctx.processing.delete(refPath); + return zodSchema2; + } + if (schema3.enum !== void 0) { + const enumValues = schema3.enum; + if (ctx.version === "openapi-3.0" && schema3.nullable === true && enumValues.length === 1 && enumValues[0] === null) { + return z.null(); + } + if (enumValues.length === 0) { + return z.never(); + } + if (enumValues.length === 1) { + return z.literal(enumValues[0]); + } + if (enumValues.every((v) => typeof v === "string")) { + return z.enum(enumValues); + } + const literalSchemas = enumValues.map((v) => z.literal(v)); + if (literalSchemas.length < 2) { + return literalSchemas[0]; + } + return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); + } + if (schema3.const !== void 0) { + return z.literal(schema3.const); + } + const type = schema3.type; + if (Array.isArray(type)) { + const typeSchemas = type.map((t) => { + const typeSchema = { ...schema3, type: t }; + return convertBaseSchema(typeSchema, ctx); + }); + if (typeSchemas.length === 0) { + return z.never(); + } + if (typeSchemas.length === 1) { + return typeSchemas[0]; + } + return z.union(typeSchemas); + } + if (!type) { + return z.any(); + } + let zodSchema; + switch (type) { + case "string": { + let stringSchema = z.string(); + if (schema3.format) { + const format = schema3.format; + if (format === "email") { + stringSchema = stringSchema.check(z.email()); + } else if (format === "uri" || format === "uri-reference") { + stringSchema = stringSchema.check(z.url()); + } else if (format === "uuid" || format === "guid") { + stringSchema = stringSchema.check(z.uuid()); + } else if (format === "date-time") { + stringSchema = stringSchema.check(z.iso.datetime()); + } else if (format === "date") { + stringSchema = stringSchema.check(z.iso.date()); + } else if (format === "time") { + stringSchema = stringSchema.check(z.iso.time()); + } else if (format === "duration") { + stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "ipv4") { + stringSchema = stringSchema.check(z.ipv4()); + } else if (format === "ipv6") { + stringSchema = stringSchema.check(z.ipv6()); + } else if (format === "mac") { + stringSchema = stringSchema.check(z.mac()); + } else if (format === "cidr") { + stringSchema = stringSchema.check(z.cidrv4()); + } else if (format === "cidr-v6") { + stringSchema = stringSchema.check(z.cidrv6()); + } else if (format === "base64") { + stringSchema = stringSchema.check(z.base64()); + } else if (format === "base64url") { + stringSchema = stringSchema.check(z.base64url()); + } else if (format === "e164") { + stringSchema = stringSchema.check(z.e164()); + } else if (format === "jwt") { + stringSchema = stringSchema.check(z.jwt()); + } else if (format === "emoji") { + stringSchema = stringSchema.check(z.emoji()); + } else if (format === "nanoid") { + stringSchema = stringSchema.check(z.nanoid()); + } else if (format === "cuid") { + stringSchema = stringSchema.check(z.cuid()); + } else if (format === "cuid2") { + stringSchema = stringSchema.check(z.cuid2()); + } else if (format === "ulid") { + stringSchema = stringSchema.check(z.ulid()); + } else if (format === "xid") { + stringSchema = stringSchema.check(z.xid()); + } else if (format === "ksuid") { + stringSchema = stringSchema.check(z.ksuid()); + } + } + if (typeof schema3.minLength === "number") { + stringSchema = stringSchema.min(schema3.minLength); + } + if (typeof schema3.maxLength === "number") { + stringSchema = stringSchema.max(schema3.maxLength); + } + if (schema3.pattern) { + stringSchema = stringSchema.regex(new RegExp(schema3.pattern)); + } + zodSchema = stringSchema; + break; + } + case "number": + case "integer": { + let numberSchema = type === "integer" ? z.number().int() : z.number(); + if (typeof schema3.minimum === "number") { + numberSchema = numberSchema.min(schema3.minimum); + } + if (typeof schema3.maximum === "number") { + numberSchema = numberSchema.max(schema3.maximum); + } + if (typeof schema3.exclusiveMinimum === "number") { + numberSchema = numberSchema.gt(schema3.exclusiveMinimum); + } else if (schema3.exclusiveMinimum === true && typeof schema3.minimum === "number") { + numberSchema = numberSchema.gt(schema3.minimum); + } + if (typeof schema3.exclusiveMaximum === "number") { + numberSchema = numberSchema.lt(schema3.exclusiveMaximum); + } else if (schema3.exclusiveMaximum === true && typeof schema3.maximum === "number") { + numberSchema = numberSchema.lt(schema3.maximum); + } + if (typeof schema3.multipleOf === "number") { + numberSchema = numberSchema.multipleOf(schema3.multipleOf); + } + zodSchema = numberSchema; + break; + } + case "boolean": { + zodSchema = z.boolean(); + break; + } + case "null": { + zodSchema = z.null(); + break; + } + case "object": { + const shape = {}; + const properties = schema3.properties || {}; + const requiredSet = new Set(schema3.required || []); + for (const [key, propSchema] of Object.entries(properties)) { + const propZodSchema = convertSchema(propSchema, ctx); + shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); + } + if (schema3.propertyNames) { + const keySchema = convertSchema(schema3.propertyNames, ctx); + const valueSchema = schema3.additionalProperties && typeof schema3.additionalProperties === "object" ? convertSchema(schema3.additionalProperties, ctx) : z.any(); + if (Object.keys(shape).length === 0) { + zodSchema = z.record(keySchema, valueSchema); + break; + } + const objectSchema2 = z.object(shape).passthrough(); + const recordSchema = z.looseRecord(keySchema, valueSchema); + zodSchema = z.intersection(objectSchema2, recordSchema); + break; + } + if (schema3.patternProperties) { + const patternProps = schema3.patternProperties; + const patternKeys = Object.keys(patternProps); + const looseRecords = []; + for (const pattern of patternKeys) { + const patternValue = convertSchema(patternProps[pattern], ctx); + const keySchema = z.string().regex(new RegExp(pattern)); + looseRecords.push(z.looseRecord(keySchema, patternValue)); + } + const schemasToIntersect = []; + if (Object.keys(shape).length > 0) { + schemasToIntersect.push(z.object(shape).passthrough()); + } + schemasToIntersect.push(...looseRecords); + if (schemasToIntersect.length === 0) { + zodSchema = z.object({}).passthrough(); + } else if (schemasToIntersect.length === 1) { + zodSchema = schemasToIntersect[0]; + } else { + let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]); + for (let i = 2; i < schemasToIntersect.length; i++) { + result = z.intersection(result, schemasToIntersect[i]); + } + zodSchema = result; + } + break; + } + const objectSchema = z.object(shape); + if (schema3.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (typeof schema3.additionalProperties === "object") { + zodSchema = objectSchema.catchall(convertSchema(schema3.additionalProperties, ctx)); + } else { + zodSchema = objectSchema.passthrough(); + } + break; + } + case "array": { + const prefixItems = schema3.prefixItems; + const items = schema3.items; + if (prefixItems && Array.isArray(prefixItems)) { + const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); + const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; + if (rest) { + zodSchema = z.tuple(tupleItems).rest(rest); + } else { + zodSchema = z.tuple(tupleItems); + } + if (typeof schema3.minItems === "number") { + zodSchema = zodSchema.check(z.minLength(schema3.minItems)); + } + if (typeof schema3.maxItems === "number") { + zodSchema = zodSchema.check(z.maxLength(schema3.maxItems)); + } + } else if (Array.isArray(items)) { + const tupleItems = items.map((item) => convertSchema(item, ctx)); + const rest = schema3.additionalItems && typeof schema3.additionalItems === "object" ? convertSchema(schema3.additionalItems, ctx) : void 0; + if (rest) { + zodSchema = z.tuple(tupleItems).rest(rest); + } else { + zodSchema = z.tuple(tupleItems); + } + if (typeof schema3.minItems === "number") { + zodSchema = zodSchema.check(z.minLength(schema3.minItems)); + } + if (typeof schema3.maxItems === "number") { + zodSchema = zodSchema.check(z.maxLength(schema3.maxItems)); + } + } else if (items !== void 0) { + const element = convertSchema(items, ctx); + let arraySchema = z.array(element); + if (typeof schema3.minItems === "number") { + arraySchema = arraySchema.min(schema3.minItems); + } + if (typeof schema3.maxItems === "number") { + arraySchema = arraySchema.max(schema3.maxItems); + } + zodSchema = arraySchema; + } else { + zodSchema = z.array(z.any()); + } + break; + } + default: + throw new Error(`Unsupported type: ${type}`); + } + if (schema3.description) { + zodSchema = zodSchema.describe(schema3.description); + } + if (schema3.default !== void 0) { + zodSchema = zodSchema.default(schema3.default); + } + return zodSchema; +} +function convertSchema(schema3, ctx) { + if (typeof schema3 === "boolean") { + return schema3 ? z.any() : z.never(); + } + let baseSchema = convertBaseSchema(schema3, ctx); + const hasExplicitType = schema3.type || schema3.enum !== void 0 || schema3.const !== void 0; + if (schema3.anyOf && Array.isArray(schema3.anyOf)) { + const options = schema3.anyOf.map((s) => convertSchema(s, ctx)); + const anyOfUnion = z.union(options); + baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion; + } + if (schema3.oneOf && Array.isArray(schema3.oneOf)) { + const options = schema3.oneOf.map((s) => convertSchema(s, ctx)); + const oneOfUnion = z.xor(options); + baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion; + } + if (schema3.allOf && Array.isArray(schema3.allOf)) { + if (schema3.allOf.length === 0) { + baseSchema = hasExplicitType ? baseSchema : z.any(); + } else { + let result = hasExplicitType ? baseSchema : convertSchema(schema3.allOf[0], ctx); + const startIdx = hasExplicitType ? 0 : 1; + for (let i = startIdx; i < schema3.allOf.length; i++) { + result = z.intersection(result, convertSchema(schema3.allOf[i], ctx)); + } + baseSchema = result; + } + } + if (schema3.nullable === true && ctx.version === "openapi-3.0") { + baseSchema = z.nullable(baseSchema); + } + if (schema3.readOnly === true) { + baseSchema = z.readonly(baseSchema); + } + const extraMeta = {}; + const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; + for (const key of coreMetadataKeys) { + if (key in schema3) { + extraMeta[key] = schema3[key]; + } + } + const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; + for (const key of contentMetadataKeys) { + if (key in schema3) { + extraMeta[key] = schema3[key]; + } + } + for (const key of Object.keys(schema3)) { + if (!RECOGNIZED_KEYS.has(key)) { + extraMeta[key] = schema3[key]; + } + } + if (Object.keys(extraMeta).length > 0) { + ctx.registry.add(baseSchema, extraMeta); + } + return baseSchema; +} +function fromJSONSchema(schema3, params) { + if (typeof schema3 === "boolean") { + return schema3 ? z.any() : z.never(); + } + const version3 = detectVersion(schema3, params?.defaultTarget); + const defs = schema3.$defs || schema3.definitions || {}; + const ctx = { + version: version3, + defs, + refs: /* @__PURE__ */ new Map(), + processing: /* @__PURE__ */ new Set(), + rootSchema: schema3, + registry: params?.registry ?? globalRegistry + }; + return convertSchema(schema3, ctx); +} +var z, RECOGNIZED_KEYS; +var init_from_json_schema = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"() { + init_registries(); + init_checks2(); + init_iso(); + init_schemas2(); + z = { + ...schemas_exports2, + ...checks_exports2, + iso: iso_exports + }; + RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ + // Schema identification + "$schema", + "$ref", + "$defs", + "definitions", + // Core schema keywords + "$id", + "id", + "$comment", + "$anchor", + "$vocabulary", + "$dynamicRef", + "$dynamicAnchor", + // Type + "type", + "enum", + "const", + // Composition + "anyOf", + "oneOf", + "allOf", + "not", + // Object + "properties", + "required", + "additionalProperties", + "patternProperties", + "propertyNames", + "minProperties", + "maxProperties", + // Array + "items", + "prefixItems", + "additionalItems", + "minItems", + "maxItems", + "uniqueItems", + "contains", + "minContains", + "maxContains", + // String + "minLength", + "maxLength", + "pattern", + "format", + // Number + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "multipleOf", + // Already handled metadata + "description", + "default", + // Content + "contentEncoding", + "contentMediaType", + "contentSchema", + // Unsupported (error-throwing) + "unevaluatedItems", + "unevaluatedProperties", + "if", + "then", + "else", + "dependentSchemas", + "dependentRequired", + // OpenAPI + "nullable", + "readOnly" + ]); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js +var coerce_exports = {}; +__export(coerce_exports, { + bigint: () => bigint3, + boolean: () => boolean3, + date: () => date4, + number: () => number3, + string: () => string3 +}); +function string3(params) { + return _coercedString(ZodString, params); +} +function number3(params) { + return _coercedNumber(ZodNumber, params); +} +function boolean3(params) { + return _coercedBoolean(ZodBoolean, params); +} +function bigint3(params) { + return _coercedBigint(ZodBigInt, params); +} +function date4(params) { + return _coercedDate(ZodDate, params); +} +var init_coerce = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"() { + init_core2(); + init_schemas2(); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js +var external_exports = {}; +__export(external_exports, { + $brand: () => $brand, + $input: () => $input, + $output: () => $output, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRealError: () => ZodRealError, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + clone: () => clone, + codec: () => codec, + coerce: () => coerce_exports, + config: () => config, + core: () => core_exports2, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + decode: () => decode2, + decodeAsync: () => decodeAsync2, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + encode: () => encode2, + encodeAsync: () => encodeAsync2, + endsWith: () => _endsWith, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + flattenError: () => flattenError, + float32: () => float32, + float64: () => float64, + formatError: () => formatError, + fromJSONSchema: () => fromJSONSchema, + function: () => _function, + getErrorMap: () => getErrorMap, + globalRegistry: () => globalRegistry, + gt: () => _gt, + gte: () => _gte, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + includes: () => _includes, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection2, + ipv4: () => ipv42, + ipv6: () => ipv62, + iso: () => iso_exports, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + length: () => _length, + literal: () => literal, + locales: () => locales_exports, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + mac: () => mac2, + map: () => map, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + meta: () => meta2, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + negative: () => _negative, + never: () => never, + nonnegative: () => _nonnegative, + nonoptional: () => nonoptional, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + overwrite: () => _overwrite, + parse: () => parse2, + parseAsync: () => parseAsync2, + partialRecord: () => partialRecord, + pipe: () => pipe, + positive: () => _positive, + prefault: () => prefault, + preprocess: () => preprocess, + prettifyError: () => prettifyError, + promise: () => promise, + property: () => _property, + readonly: () => readonly, + record: () => record, + refine: () => refine, + regex: () => _regex, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode2, + safeDecodeAsync: () => safeDecodeAsync2, + safeEncode: () => safeEncode2, + safeEncodeAsync: () => safeEncodeAsync2, + safeParse: () => safeParse2, + safeParseAsync: () => safeParseAsync2, + set: () => set, + setErrorMap: () => setErrorMap, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + toJSONSchema: () => toJSONSchema, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + transform: () => transform, + treeifyError: () => treeifyError, + trim: () => _trim, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + uppercase: () => _uppercase, + url: () => url, + util: () => util_exports, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor +}); +var init_external = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"() { + init_core2(); + init_schemas2(); + init_checks2(); + init_errors2(); + init_parse2(); + init_compat(); + init_core2(); + init_en(); + init_core2(); + init_json_schema_processors(); + init_from_json_schema(); + init_locales(); + init_iso(); + init_iso(); + init_coerce(); + config(en_default()); + } +}); + +// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js +var zod_exports = {}; +__export(zod_exports, { + $brand: () => $brand, + $input: () => $input, + $output: () => $output, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRealError: () => ZodRealError, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + clone: () => clone, + codec: () => codec, + coerce: () => coerce_exports, + config: () => config, + core: () => core_exports2, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + decode: () => decode2, + decodeAsync: () => decodeAsync2, + default: () => zod_default, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + encode: () => encode2, + encodeAsync: () => encodeAsync2, + endsWith: () => _endsWith, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + flattenError: () => flattenError, + float32: () => float32, + float64: () => float64, + formatError: () => formatError, + fromJSONSchema: () => fromJSONSchema, + function: () => _function, + getErrorMap: () => getErrorMap, + globalRegistry: () => globalRegistry, + gt: () => _gt, + gte: () => _gte, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + includes: () => _includes, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection2, + ipv4: () => ipv42, + ipv6: () => ipv62, + iso: () => iso_exports, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + length: () => _length, + literal: () => literal, + locales: () => locales_exports, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + mac: () => mac2, + map: () => map, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + meta: () => meta2, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + negative: () => _negative, + never: () => never, + nonnegative: () => _nonnegative, + nonoptional: () => nonoptional, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + overwrite: () => _overwrite, + parse: () => parse2, + parseAsync: () => parseAsync2, + partialRecord: () => partialRecord, + pipe: () => pipe, + positive: () => _positive, + prefault: () => prefault, + preprocess: () => preprocess, + prettifyError: () => prettifyError, + promise: () => promise, + property: () => _property, + readonly: () => readonly, + record: () => record, + refine: () => refine, + regex: () => _regex, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode2, + safeDecodeAsync: () => safeDecodeAsync2, + safeEncode: () => safeEncode2, + safeEncodeAsync: () => safeEncodeAsync2, + safeParse: () => safeParse2, + safeParseAsync: () => safeParseAsync2, + set: () => set, + setErrorMap: () => setErrorMap, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + toJSONSchema: () => toJSONSchema, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + transform: () => transform, + treeifyError: () => treeifyError, + trim: () => _trim, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + uppercase: () => _uppercase, + url: () => url, + util: () => util_exports, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor, + z: () => external_exports +}); +var zod_default; +var init_zod = __esm({ + "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js"() { + init_external(); + init_external(); + zod_default = external_exports; + } +}); + +// ../../packages/spec/dist/data/index.mjs +var data_exports = {}; +__export(data_exports, { + ALL_OPERATORS: () => ALL_OPERATORS, + AddressSchema: () => AddressSchema, + AggregationFunction: () => AggregationFunction2, + AggregationMetricType: () => AggregationMetricType2, + AggregationNodeSchema: () => AggregationNodeSchema2, + AggregationPipelineSchema: () => AggregationPipelineSchema, + AggregationStageSchema: () => AggregationStageSchema, + AnalyticsQuerySchema: () => AnalyticsQuerySchema2, + ApiMethod: () => ApiMethod3, + AsyncValidationSchema: () => AsyncValidationSchema3, + BaseEngineOptionsSchema: () => BaseEngineOptionsSchema, + CDCConfigSchema: () => CDCConfigSchema3, + ComparisonOperatorSchema: () => ComparisonOperatorSchema, + ComputedFieldCacheSchema: () => ComputedFieldCacheSchema3, + ConditionalValidationSchema: () => ConditionalValidationSchema3, + ConsistencyLevelSchema: () => ConsistencyLevelSchema, + CrossFieldValidationSchema: () => CrossFieldValidationSchema3, + CubeJoinSchema: () => CubeJoinSchema2, + CubeSchema: () => CubeSchema2, + CurrencyConfigSchema: () => CurrencyConfigSchema3, + CurrencyValueSchema: () => CurrencyValueSchema, + CustomValidatorSchema: () => CustomValidatorSchema3, + DataEngineAggregateOptionsSchema: () => DataEngineAggregateOptionsSchema, + DataEngineAggregateRequestSchema: () => DataEngineAggregateRequestSchema, + DataEngineBatchRequestSchema: () => DataEngineBatchRequestSchema, + DataEngineContractSchema: () => DataEngineContractSchema, + DataEngineCountOptionsSchema: () => DataEngineCountOptionsSchema, + DataEngineCountRequestSchema: () => DataEngineCountRequestSchema, + DataEngineDeleteOptionsSchema: () => DataEngineDeleteOptionsSchema, + DataEngineDeleteRequestSchema: () => DataEngineDeleteRequestSchema, + DataEngineExecuteRequestSchema: () => DataEngineExecuteRequestSchema, + DataEngineFilterSchema: () => DataEngineFilterSchema, + DataEngineFindOneRequestSchema: () => DataEngineFindOneRequestSchema, + DataEngineFindRequestSchema: () => DataEngineFindRequestSchema, + DataEngineInsertOptionsSchema: () => DataEngineInsertOptionsSchema, + DataEngineInsertRequestSchema: () => DataEngineInsertRequestSchema, + DataEngineQueryOptionsSchema: () => DataEngineQueryOptionsSchema, + DataEngineRequestSchema: () => DataEngineRequestSchema, + DataEngineSortSchema: () => DataEngineSortSchema, + DataEngineUpdateOptionsSchema: () => DataEngineUpdateOptionsSchema, + DataEngineUpdateRequestSchema: () => DataEngineUpdateRequestSchema, + DataEngineVectorFindRequestSchema: () => DataEngineVectorFindRequestSchema, + DataQualityRulesSchema: () => DataQualityRulesSchema3, + DataTypeMappingSchema: () => DataTypeMappingSchema, + DatasetLoadResultSchema: () => DatasetLoadResultSchema, + DatasetMode: () => DatasetMode2, + DatasetSchema: () => DatasetSchema2, + DatasourceCapabilities: () => DatasourceCapabilities, + DatasourceSchema: () => DatasourceSchema, + DimensionSchema: () => DimensionSchema2, + DimensionType: () => DimensionType2, + DocumentSchema: () => DocumentSchema, + DocumentSchemaValidationSchema: () => DocumentSchemaValidationSchema, + DocumentTemplateSchema: () => DocumentTemplateSchema, + DocumentVersionSchema: () => DocumentVersionSchema, + DriverCapabilitiesSchema: () => DriverCapabilitiesSchema, + DriverConfigSchema: () => DriverConfigSchema, + DriverDefinitionSchema: () => DriverDefinitionSchema, + DriverInterfaceSchema: () => DriverInterfaceSchema, + DriverOptionsSchema: () => DriverOptionsSchema, + DriverType: () => DriverType, + ESignatureConfigSchema: () => ESignatureConfigSchema, + EngineAggregateOptionsSchema: () => EngineAggregateOptionsSchema, + EngineCountOptionsSchema: () => EngineCountOptionsSchema, + EngineDeleteOptionsSchema: () => EngineDeleteOptionsSchema, + EngineQueryOptionsSchema: () => EngineQueryOptionsSchema, + EngineUpdateOptionsSchema: () => EngineUpdateOptionsSchema, + EqualityOperatorSchema: () => EqualityOperatorSchema, + ExternalDataSourceSchema: () => ExternalDataSourceSchema, + ExternalFieldMappingSchema: () => ExternalFieldMappingSchema, + ExternalLookupSchema: () => ExternalLookupSchema, + FILTER_OPERATORS: () => FILTER_OPERATORS, + FeedActorSchema: () => FeedActorSchema2, + FeedFilterMode: () => FeedFilterMode, + FeedItemSchema: () => FeedItemSchema2, + FeedItemType: () => FeedItemType2, + FeedVisibility: () => FeedVisibility2, + Field: () => Field, + FieldChangeEntrySchema: () => FieldChangeEntrySchema2, + FieldMappingSchema: () => FieldMappingSchema, + FieldNodeSchema: () => FieldNodeSchema2, + FieldOperatorsSchema: () => FieldOperatorsSchema2, + FieldReferenceSchema: () => FieldReferenceSchema2, + FieldSchema: () => FieldSchema3, + FieldType: () => FieldType3, + FileAttachmentConfigSchema: () => FileAttachmentConfigSchema3, + FilterConditionSchema: () => FilterConditionSchema2, + FormatValidationSchema: () => FormatValidationSchema3, + FullTextSearchSchema: () => FullTextSearchSchema2, + HookContextSchema: () => HookContextSchema, + HookEvent: () => HookEvent, + HookSchema: () => HookSchema, + IndexSchema: () => IndexSchema3, + JSONValidationSchema: () => JSONValidationSchema3, + JoinNodeSchema: () => JoinNodeSchema2, + JoinStrategy: () => JoinStrategy2, + JoinType: () => JoinType2, + LOGICAL_OPERATORS: () => LOGICAL_OPERATORS, + LocationCoordinatesSchema: () => LocationCoordinatesSchema, + MappingSchema: () => MappingSchema, + MentionSchema: () => MentionSchema2, + MetricSchema: () => MetricSchema2, + NoSQLDataTypeMappingSchema: () => NoSQLDataTypeMappingSchema, + NoSQLDatabaseTypeSchema: () => NoSQLDatabaseTypeSchema, + NoSQLDriverConfigSchema: () => NoSQLDriverConfigSchema, + NoSQLIndexSchema: () => NoSQLIndexSchema, + NoSQLIndexTypeSchema: () => NoSQLIndexTypeSchema, + NoSQLOperationTypeSchema: () => NoSQLOperationTypeSchema, + NoSQLQueryOptionsSchema: () => NoSQLQueryOptionsSchema, + NoSQLTransactionOptionsSchema: () => NoSQLTransactionOptionsSchema, + NormalizedFilterSchema: () => NormalizedFilterSchema2, + NotificationChannel: () => NotificationChannel2, + ObjectCapabilities: () => ObjectCapabilities3, + ObjectDependencyGraphSchema: () => ObjectDependencyGraphSchema, + ObjectDependencyNodeSchema: () => ObjectDependencyNodeSchema, + ObjectExtensionSchema: () => ObjectExtensionSchema, + ObjectOwnershipEnum: () => ObjectOwnershipEnum, + ObjectSchema: () => ObjectSchema3, + PartitioningConfigSchema: () => PartitioningConfigSchema3, + PoolConfigSchema: () => PoolConfigSchema, + QueryFilterSchema: () => QueryFilterSchema, + QuerySchema: () => QuerySchema2, + RangeOperatorSchema: () => RangeOperatorSchema, + ReactionSchema: () => ReactionSchema2, + RecordSubscriptionSchema: () => RecordSubscriptionSchema2, + ReferenceResolutionErrorSchema: () => ReferenceResolutionErrorSchema, + ReferenceResolutionSchema: () => ReferenceResolutionSchema, + ReplicationConfigSchema: () => ReplicationConfigSchema, + SQLDialectSchema: () => SQLDialectSchema, + SQLDriverConfigSchema: () => SQLDriverConfigSchema, + SQLiteAlterTableLimitations: () => SQLiteAlterTableLimitations, + SQLiteDataTypeMappingDefaults: () => SQLiteDataTypeMappingDefaults, + SSLConfigSchema: () => SSLConfigSchema, + ScriptValidationSchema: () => ScriptValidationSchema3, + SearchConfigSchema: () => SearchConfigSchema4, + SeedLoaderConfigSchema: () => SeedLoaderConfigSchema, + SeedLoaderRequestSchema: () => SeedLoaderRequestSchema, + SeedLoaderResultSchema: () => SeedLoaderResultSchema, + SelectOptionSchema: () => SelectOptionSchema3, + SetOperatorSchema: () => SetOperatorSchema, + ShardingConfigSchema: () => ShardingConfigSchema, + SoftDeleteConfigSchema: () => SoftDeleteConfigSchema3, + SortNodeSchema: () => SortNodeSchema2, + SpecialOperatorSchema: () => SpecialOperatorSchema, + StateMachineValidationSchema: () => StateMachineValidationSchema3, + StringOperatorSchema: () => StringOperatorSchema, + SubscriptionEventType: () => SubscriptionEventType2, + TenancyConfigSchema: () => TenancyConfigSchema3, + TenantDatabaseLifecycleSchema: () => TenantDatabaseLifecycleSchema, + TenantResolverStrategySchema: () => TenantResolverStrategySchema, + TimeUpdateInterval: () => TimeUpdateInterval2, + TransformType: () => TransformType, + TursoGroupSchema: () => TursoGroupSchema, + TursoMultiTenantConfigSchema: () => TursoMultiTenantConfigSchema, + UniquenessValidationSchema: () => UniquenessValidationSchema3, + VALID_AST_OPERATORS: () => VALID_AST_OPERATORS, + ValidationRuleSchema: () => ValidationRuleSchema3, + VectorConfigSchema: () => VectorConfigSchema3, + VersioningConfigSchema: () => VersioningConfigSchema3, + WindowFunction: () => WindowFunction2, + WindowFunctionNodeSchema: () => WindowFunctionNodeSchema2, + WindowSpecSchema: () => WindowSpecSchema2, + isFilterAST: () => isFilterAST, + parseFilterAST: () => parseFilterAST +}); +function isFilterAST(filter) { + if (!Array.isArray(filter) || filter.length === 0) return false; + const first = filter[0]; + if (typeof first === "string") { + const lower = first.toLowerCase(); + if (lower === "and" || lower === "or") { + return filter.length >= 2 && filter.slice(1).every((child) => isFilterAST(child)); + } + if (filter.length >= 2 && typeof filter[1] === "string") { + return VALID_AST_OPERATORS.has(filter[1].toLowerCase()); + } + } + if (filter.every((item) => isFilterAST(item))) { + return filter.length > 0; + } + return false; +} +function convertComparison(node) { + const [field, operator, value] = node; + const op = operator.toLowerCase(); + if (op === "=" || op === "==") { + return { [field]: value }; + } + if (op === "is_null") { + return { [field]: { $null: true } }; + } + if (op === "is_not_null") { + return { [field]: { $null: false } }; + } + const mapped = AST_OPERATOR_MAP[op]; + if (mapped) { + return { [field]: { [mapped]: value } }; + } + return { [field]: { [`$${op}`]: value } }; +} +function parseFilterAST(filter) { + if (filter == null) return void 0; + if (!Array.isArray(filter)) return filter; + if (filter.length === 0) return void 0; + const first = filter[0]; + if (typeof first === "string" && (first.toLowerCase() === "and" || first.toLowerCase() === "or")) { + const logicOp = `$${first.toLowerCase()}`; + const children = filter.slice(1).map((child) => parseFilterAST(child)).filter(Boolean); + if (children.length === 0) return void 0; + if (children.length === 1) return children[0]; + return { [logicOp]: children }; + } + if (filter.length >= 2 && typeof first === "string") { + return convertComparison(filter); + } + if (filter.every((item) => Array.isArray(item))) { + const children = filter.map((child) => parseFilterAST(child)).filter(Boolean); + if (children.length === 0) return void 0; + if (children.length === 1) return children[0]; + return { $and: children }; + } + return void 0; +} +function snakeCaseToLabel3(name) { + return name.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); +} +var FieldReferenceSchema2, EqualityOperatorSchema, ComparisonOperatorSchema, SetOperatorSchema, RangeOperatorSchema, StringOperatorSchema, SpecialOperatorSchema, FieldOperatorsSchema2, FilterConditionSchema2, QueryFilterSchema, NormalizedFilterSchema2, VALID_AST_OPERATORS, AST_OPERATOR_MAP, FILTER_OPERATORS, LOGICAL_OPERATORS, ALL_OPERATORS, SortNodeSchema2, AggregationFunction2, AggregationNodeSchema2, JoinType2, JoinStrategy2, JoinNodeSchema2, WindowFunction2, WindowSpecSchema2, WindowFunctionNodeSchema2, FieldNodeSchema2, FullTextSearchSchema2, BaseQuerySchema2, QuerySchema2, SystemIdentifierSchema3, SnakeCaseIdentifierSchema3, EncryptionAlgorithmSchema3, KeyManagementProviderSchema3, KeyRotationPolicySchema3, EncryptionConfigSchema3, MaskingStrategySchema3, MaskingRuleSchema3, FieldType3, SelectOptionSchema3, LocationCoordinatesSchema, CurrencyConfigSchema3, CurrencyValueSchema, AddressSchema, VectorConfigSchema3, FileAttachmentConfigSchema3, DataQualityRulesSchema3, ComputedFieldCacheSchema3, FieldSchema3, Field, BaseValidationSchema3, ScriptValidationSchema3, UniquenessValidationSchema3, StateMachineValidationSchema3, FormatValidationSchema3, CrossFieldValidationSchema3, JSONValidationSchema3, AsyncValidationSchema3, CustomValidatorSchema3, ValidationRuleSchema3, ConditionalValidationSchema3, ActionRefSchema3, GuardRefSchema3, TransitionSchema3, StateNodeSchema3, StateMachineSchema3, I18nLabelSchema3, AriaPropsSchema3, NumberFormatSchema3, DateFormatSchema3, ActionParamSchema3, ActionType3, TARGET_REQUIRED_TYPES3, ActionSchema3, ApiMethod3, ObjectCapabilities3, IndexSchema3, SearchConfigSchema4, TenancyConfigSchema3, SoftDeleteConfigSchema3, VersioningConfigSchema3, PartitioningConfigSchema3, CDCConfigSchema3, ObjectSchemaBase3, ObjectSchema3, ObjectOwnershipEnum, ObjectExtensionSchema, HookEvent, HookSchema, HookContextSchema, TransformType, FieldMappingSchema, MappingSchema, ExecutionContextSchema, DataEngineFilterSchema, DataEngineSortSchema, BaseEngineOptionsSchema, EngineQueryOptionsSchema, DataEngineQueryOptionsSchema, DataEngineInsertOptionsSchema, EngineUpdateOptionsSchema, DataEngineUpdateOptionsSchema, EngineDeleteOptionsSchema, DataEngineDeleteOptionsSchema, EngineAggregateOptionsSchema, DataEngineAggregateOptionsSchema, EngineCountOptionsSchema, DataEngineCountOptionsSchema, DataEngineContractSchema, RpcLegacyFilterMixin, RpcQueryOptionsSchema, DataEngineFindRequestSchema, DataEngineFindOneRequestSchema, DataEngineInsertRequestSchema, DataEngineUpdateRequestSchema, DataEngineDeleteRequestSchema, DataEngineCountRequestSchema, DataEngineAggregateRequestSchema, DataEngineExecuteRequestSchema, DataEngineVectorFindRequestSchema, DataEngineBatchRequestSchema, DataEngineRequestSchema, SortDirectionEnum, IsolationLevelEnum, DriverOptionsSchema, DriverCapabilitiesSchema, DriverInterfaceSchema, PoolConfigSchema, DriverConfigSchema, SQLDialectSchema, DataTypeMappingSchema, SSLConfigSchema, SQLDriverConfigSchema, SQLiteDataTypeMappingDefaults, SQLiteAlterTableLimitations, NoSQLDatabaseTypeSchema, NoSQLOperationTypeSchema, ConsistencyLevelSchema, NoSQLIndexTypeSchema, ShardingConfigSchema, ReplicationConfigSchema, DocumentSchemaValidationSchema, NoSQLDataTypeMappingSchema, NoSQLDriverConfigSchema, NoSQLQueryOptionsSchema, AggregationStageSchema, AggregationPipelineSchema, NoSQLIndexSchema, NoSQLTransactionOptionsSchema, DatasetMode2, DatasetSchema2, ReferenceResolutionSchema, ObjectDependencyNodeSchema, ObjectDependencyGraphSchema, ReferenceResolutionErrorSchema, SeedLoaderConfigSchema, DatasetLoadResultSchema, SeedLoaderResultSchema, SeedLoaderRequestSchema, DocumentVersionSchema, DocumentTemplateSchema, ESignatureConfigSchema, DocumentSchema, TransformTypeSchema, FieldMappingSchema2, ExternalDataSourceSchema, ExternalFieldMappingSchema, ExternalLookupSchema, DriverType, DriverDefinitionSchema, DatasourceCapabilities, DatasourceSchema, AggregationMetricType2, DimensionType2, TimeUpdateInterval2, MetricSchema2, DimensionSchema2, CubeJoinSchema2, CubeSchema2, AnalyticsQuerySchema2, FeedItemType2, MentionSchema2, FieldChangeEntrySchema2, ReactionSchema2, FeedActorSchema2, FeedVisibility2, FeedItemSchema2, FeedFilterMode, SubscriptionEventType2, NotificationChannel2, RecordSubscriptionSchema2, TenantResolverStrategySchema, TursoGroupSchema, TenantDatabaseLifecycleSchema, TursoMultiTenantConfigSchema; +var init_data = __esm({ + "../../packages/spec/dist/data/index.mjs"() { + "use strict"; + init_zod(); + FieldReferenceSchema2 = external_exports.object({ + $field: external_exports.string().describe("Field Reference/Column Name") + }); + EqualityOperatorSchema = external_exports.object({ + /** Equal to (default) - SQL: = | MongoDB: $eq */ + $eq: external_exports.any().optional(), + /** Not equal to - SQL: <> or != | MongoDB: $ne */ + $ne: external_exports.any().optional() + }); + ComparisonOperatorSchema = external_exports.object({ + /** Greater than - SQL: > | MongoDB: $gt */ + $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), + /** Greater than or equal to - SQL: >= | MongoDB: $gte */ + $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), + /** Less than - SQL: < | MongoDB: $lt */ + $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), + /** Less than or equal to - SQL: <= | MongoDB: $lte */ + $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional() + }); + SetOperatorSchema = external_exports.object({ + /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */ + $in: external_exports.array(external_exports.any()).optional(), + /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */ + $nin: external_exports.array(external_exports.any()).optional() + }); + RangeOperatorSchema = external_exports.object({ + /** Between (inclusive) - takes [min, max] array */ + $between: external_exports.tuple([ + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]), + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]) + ]).optional() + }); + StringOperatorSchema = external_exports.object({ + /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */ + $contains: external_exports.string().optional(), + /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */ + $notContains: external_exports.string().optional(), + /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */ + $startsWith: external_exports.string().optional(), + /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */ + $endsWith: external_exports.string().optional() + }); + SpecialOperatorSchema = external_exports.object({ + /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */ + $null: external_exports.boolean().optional(), + /** Field exists check (primarily for NoSQL) - MongoDB: $exists */ + $exists: external_exports.boolean().optional() + }); + FieldOperatorsSchema2 = external_exports.object({ + // Equality + $eq: external_exports.any().optional(), + $ne: external_exports.any().optional(), + // Comparison (numeric/date) + $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), + $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), + $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), + $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), + // Set & Range + $in: external_exports.array(external_exports.any()).optional(), + $nin: external_exports.array(external_exports.any()).optional(), + $between: external_exports.tuple([ + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]), + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]) + ]).optional(), + // String-specific + $contains: external_exports.string().optional(), + $notContains: external_exports.string().optional(), + $startsWith: external_exports.string().optional(), + $endsWith: external_exports.string().optional(), + // Special + $null: external_exports.boolean().optional(), + $exists: external_exports.boolean().optional() + }); + FilterConditionSchema2 = external_exports.lazy( + () => external_exports.record(external_exports.string(), external_exports.unknown()).and( + external_exports.object({ + $and: external_exports.array(FilterConditionSchema2).optional(), + $or: external_exports.array(FilterConditionSchema2).optional(), + $not: FilterConditionSchema2.optional() + }) + ) + ); + QueryFilterSchema = external_exports.object({ + where: FilterConditionSchema2.optional() + }); + NormalizedFilterSchema2 = external_exports.lazy( + () => external_exports.object({ + $and: external_exports.array( + external_exports.union([ + // Field condition: { field: { $op: value } } + external_exports.record(external_exports.string(), FieldOperatorsSchema2), + // Nested logical group + NormalizedFilterSchema2 + ]) + ).optional(), + $or: external_exports.array( + external_exports.union([ + external_exports.record(external_exports.string(), FieldOperatorsSchema2), + NormalizedFilterSchema2 + ]) + ).optional(), + $not: external_exports.union([ + external_exports.record(external_exports.string(), FieldOperatorsSchema2), + NormalizedFilterSchema2 + ]).optional() + }) + ); + VALID_AST_OPERATORS = /* @__PURE__ */ new Set([ + "=", + "==", + "!=", + "<>", + ">", + ">=", + "<", + "<=", + "in", + "nin", + "not_in", + "contains", + "notcontains", + "not_contains", + "like", + "startswith", + "starts_with", + "endswith", + "ends_with", + "between", + "is_null", + "is_not_null" + ]); + AST_OPERATOR_MAP = { + "=": "$eq", + "==": "$eq", + "!=": "$ne", + "<>": "$ne", + ">": "$gt", + ">=": "$gte", + "<": "$lt", + "<=": "$lte", + "in": "$in", + "nin": "$nin", + "not_in": "$nin", + "contains": "$contains", + "notcontains": "$notContains", + "not_contains": "$notContains", + "like": "$contains", + "startswith": "$startsWith", + "starts_with": "$startsWith", + "endswith": "$endsWith", + "ends_with": "$endsWith", + "between": "$between", + "is_null": "$null", + "is_not_null": "$null" + }; + FILTER_OPERATORS = [ + // Equality + "$eq", + "$ne", + // Comparison + "$gt", + "$gte", + "$lt", + "$lte", + // Set & Range + "$in", + "$nin", + "$between", + // String + "$contains", + "$notContains", + "$startsWith", + "$endsWith", + // Special + "$null", + "$exists" + ]; + LOGICAL_OPERATORS = ["$and", "$or", "$not"]; + ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS]; + SortNodeSchema2 = external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]).default("asc") + }); + AggregationFunction2 = external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "array_agg", + "string_agg" + ]); + AggregationNodeSchema2 = external_exports.object({ + function: AggregationFunction2.describe("Aggregation function"), + field: external_exports.string().optional().describe("Field to aggregate (optional for COUNT(*))"), + alias: external_exports.string().describe("Result column alias"), + distinct: external_exports.boolean().optional().describe("Apply DISTINCT before aggregation"), + filter: FilterConditionSchema2.optional().describe("Filter/Condition to apply to the aggregation (FILTER WHERE clause)") + }); + JoinType2 = external_exports.enum(["inner", "left", "right", "full"]); + JoinStrategy2 = external_exports.enum(["auto", "database", "hash", "loop"]); + JoinNodeSchema2 = external_exports.lazy( + () => external_exports.object({ + type: JoinType2.describe("Join type"), + strategy: JoinStrategy2.optional().describe("Execution strategy hint"), + object: external_exports.string().describe("Object/table to join"), + alias: external_exports.string().optional().describe("Table alias"), + on: FilterConditionSchema2.describe("Join condition"), + subquery: external_exports.lazy(() => QuerySchema2).optional().describe("Subquery instead of object") + }) + ); + WindowFunction2 = external_exports.enum([ + "row_number", + "rank", + "dense_rank", + "percent_rank", + "lag", + "lead", + "first_value", + "last_value", + "sum", + "avg", + "count", + "min", + "max" + ]); + WindowSpecSchema2 = external_exports.object({ + partitionBy: external_exports.array(external_exports.string()).optional().describe("PARTITION BY fields"), + orderBy: external_exports.array(SortNodeSchema2).optional().describe("ORDER BY specification"), + frame: external_exports.object({ + type: external_exports.enum(["rows", "range"]).optional(), + start: external_exports.string().optional().describe('Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")'), + end: external_exports.string().optional().describe('Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")') + }).optional().describe("Window frame specification") + }); + WindowFunctionNodeSchema2 = external_exports.object({ + function: WindowFunction2.describe("Window function name"), + field: external_exports.string().optional().describe("Field to operate on (for aggregate window functions)"), + alias: external_exports.string().describe("Result column alias"), + over: WindowSpecSchema2.describe("Window specification (OVER clause)") + }); + FieldNodeSchema2 = external_exports.lazy( + () => external_exports.union([ + external_exports.string(), + // Primitive field: "name" + external_exports.object({ + field: external_exports.string(), + // Relationship field: "owner" + fields: external_exports.array(FieldNodeSchema2).optional(), + // Nested select: ["name", "email"] + alias: external_exports.string().optional() + }) + ]) + ); + FullTextSearchSchema2 = external_exports.object({ + query: external_exports.string().describe("Search query text"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to search in (if not specified, searches all text fields)"), + fuzzy: external_exports.boolean().optional().default(false).describe("Enable fuzzy matching (tolerates typos)"), + operator: external_exports.enum(["and", "or"]).optional().default("or").describe("Logical operator between terms"), + boost: external_exports.record(external_exports.string(), external_exports.number()).optional().describe("Field-specific relevance boosting (field name -> boost factor)"), + minScore: external_exports.number().optional().describe("Minimum relevance score threshold"), + language: external_exports.string().optional().describe('Language for text analysis (e.g., "en", "zh", "es")'), + highlight: external_exports.boolean().optional().default(false).describe("Enable search result highlighting") + }); + BaseQuerySchema2 = external_exports.object({ + /** Target Entity */ + object: external_exports.string().describe("Object name (e.g. account)"), + /** Select Clause */ + fields: external_exports.array(FieldNodeSchema2).optional().describe("Fields to retrieve"), + /** Where Clause (Filtering) */ + where: FilterConditionSchema2.optional().describe("Filtering criteria (WHERE)"), + /** Full-Text Search */ + search: FullTextSearchSchema2.optional().describe("Full-text search configuration ($search parameter)"), + /** Order By Clause (Sorting) */ + orderBy: external_exports.array(SortNodeSchema2).optional().describe("Sorting instructions (ORDER BY)"), + /** Pagination */ + limit: external_exports.number().optional().describe("Max records to return (LIMIT)"), + offset: external_exports.number().optional().describe("Records to skip (OFFSET)"), + top: external_exports.number().optional().describe("Alias for limit (OData compatibility)"), + cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Cursor for keyset pagination"), + /** Joins */ + joins: external_exports.array(JoinNodeSchema2).optional().describe("Explicit Table Joins"), + /** Aggregations */ + aggregations: external_exports.array(AggregationNodeSchema2).optional().describe("Aggregation functions"), + /** Group By Clause */ + groupBy: external_exports.array(external_exports.string()).optional().describe("GROUP BY fields"), + /** Having Clause */ + having: FilterConditionSchema2.optional().describe("HAVING clause for aggregation filtering"), + /** Window Functions */ + windowFunctions: external_exports.array(WindowFunctionNodeSchema2).optional().describe("Window functions with OVER clause"), + /** Subquery flag */ + distinct: external_exports.boolean().optional().describe("SELECT DISTINCT flag") + }); + QuerySchema2 = BaseQuerySchema2.extend({ + expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema2)).optional().describe( + "Recursive relation loading map. Keys are lookup/master_detail field names; values are nested QueryAST objects that control select, filter, sort, and further expansion on the related object. The engine resolves expand via batch $in queries (driver-agnostic) with a default max depth of 3." + ) + }); + SystemIdentifierSchema3 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' + }).describe("System identifier (lowercase with underscores or dots)"); + SnakeCaseIdentifierSchema3 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { + message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' + }).describe("Snake case identifier (lowercase with underscores only)"); + external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' + }).describe("Event name (lowercase with dot notation for namespacing)"); + EncryptionAlgorithmSchema3 = external_exports.enum([ + "aes-256-gcm", + "aes-256-cbc", + "chacha20-poly1305" + ]).describe("Supported encryption algorithm"); + KeyManagementProviderSchema3 = external_exports.enum([ + "local", + "aws-kms", + "azure-key-vault", + "gcp-kms", + "hashicorp-vault" + ]).describe("Key management service provider"); + KeyRotationPolicySchema3 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), + frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), + retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), + autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") + }).describe("Policy for automatic encryption key rotation"); + EncryptionConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), + algorithm: EncryptionAlgorithmSchema3.default("aes-256-gcm").describe("Encryption algorithm"), + keyManagement: external_exports.object({ + provider: KeyManagementProviderSchema3.describe("Key management service provider"), + keyId: external_exports.string().optional().describe("Key identifier in the provider"), + rotationPolicy: KeyRotationPolicySchema3.optional().describe("Key rotation policy") + }).describe("Key management configuration"), + scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), + deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), + searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") + }).describe("Field-level encryption configuration"); + external_exports.object({ + fieldName: external_exports.string().describe("Name of the field to encrypt"), + encryptionConfig: EncryptionConfigSchema3.describe("Encryption settings for this field"), + indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") + }).describe("Per-field encryption assignment"); + MaskingStrategySchema3 = external_exports.enum([ + "redact", + // Complete redaction: **** + "partial", + // Partial masking: 138****5678 + "hash", + // Hash value: sha256(value) + "tokenize", + // Tokenization: token-12345 + "randomize", + // Randomize: generate random value + "nullify", + // Null value: null + "substitute" + // Substitute with dummy data + ]).describe("Data masking strategy for PII protection"); + MaskingRuleSchema3 = external_exports.object({ + field: external_exports.string().describe("Field name to apply masking to"), + strategy: MaskingStrategySchema3.describe("Masking strategy to use"), + pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), + preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), + preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), + roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), + exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") + }).describe("Masking rule for a single field"); + external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable data masking"), + rules: external_exports.array(MaskingRuleSchema3).describe("List of field-level masking rules"), + auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") + }).describe("Top-level data masking configuration for PII protection"); + FieldType3 = external_exports.enum([ + // Core Text + "text", + "textarea", + "email", + "url", + "phone", + "password", + // Rich Content + "markdown", + "html", + "richtext", + // Numbers + "number", + "currency", + "percent", + // Date & Time + "date", + "datetime", + "time", + // Logic + "boolean", + "toggle", + // Toggle is a distinct UI from checkbox + // Selection + "select", + // Single select dropdown + "multiselect", + // Multi select (often tags) + "radio", + // Radio group + "checkboxes", + // Checkbox group + // Relational + "lookup", + "master_detail", + // Dynamic reference + "tree", + // Hierarchical reference + // Media + "image", + "file", + "avatar", + "video", + "audio", + // Calculated / System + "formula", + "summary", + "autonumber", + // Enhanced Types + "location", + // GPS coordinates + "address", + // Structured address + "code", + // Code editor (JSON/SQL/JS) + "json", + // Structured JSON data + "color", + // Color picker + "rating", + // Star rating + "slider", + // Numeric slider + "signature", + // Digital signature + "qrcode", + // QR code / Barcode + "progress", + // Progress bar + "tags", + // Simple tag list + // AI/ML Types + "vector" + // Vector embeddings for AI/ML (semantic search, RAG) + ]); + SelectOptionSchema3 = external_exports.object({ + label: external_exports.string().describe("Display label (human-readable, any case allowed)"), + value: SystemIdentifierSchema3.describe("Stored value (lowercase machine identifier)"), + color: external_exports.string().optional().describe("Color code for badges/charts"), + default: external_exports.boolean().optional().describe("Is default option") + }); + LocationCoordinatesSchema = external_exports.object({ + latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), + longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), + altitude: external_exports.number().optional().describe("Altitude in meters"), + accuracy: external_exports.number().optional().describe("Accuracy in meters") + }); + CurrencyConfigSchema3 = external_exports.object({ + precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), + currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), + defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") + }); + CurrencyValueSchema = external_exports.object({ + value: external_exports.number().describe("Monetary amount"), + currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") + }); + AddressSchema = external_exports.object({ + street: external_exports.string().optional().describe("Street address"), + city: external_exports.string().optional().describe("City name"), + state: external_exports.string().optional().describe("State/Province"), + postalCode: external_exports.string().optional().describe("Postal/ZIP code"), + country: external_exports.string().optional().describe("Country name or code"), + countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), + formatted: external_exports.string().optional().describe("Formatted address string") + }); + VectorConfigSchema3 = external_exports.object({ + dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), + distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), + normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), + indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), + indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") + }); + FileAttachmentConfigSchema3 = external_exports.object({ + /** File Size Limits */ + minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), + maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), + /** File Type Restrictions */ + allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), + blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), + allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), + blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), + /** Virus Scanning */ + virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), + virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), + virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), + quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), + /** Storage Configuration */ + storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), + storageBucket: external_exports.string().optional().describe("Target bucket name"), + storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), + /** Image-Specific Validation */ + imageValidation: external_exports.object({ + minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), + maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), + minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), + maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), + aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), + generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), + thumbnailSizes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), + width: external_exports.number().min(1).describe("Thumbnail width in pixels"), + height: external_exports.number().min(1).describe("Thumbnail height in pixels"), + crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") + })).optional().describe("Thumbnail size configurations"), + preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), + autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") + }).optional().describe("Image-specific validation rules"), + /** Upload Behavior */ + allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), + allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), + allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), + requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), + /** Metadata Extraction */ + extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), + extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), + /** Versioning */ + versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), + maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), + /** Access Control */ + publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), + presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") + }).refine((data) => { + if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { + return false; + } + return true; + }, { + message: "minSize must be less than or equal to maxSize" + }).refine((data) => { + if (data.virusScanProvider !== void 0 && data.virusScan !== true) { + return false; + } + return true; + }, { + message: "virusScanProvider requires virusScan to be enabled" + }); + DataQualityRulesSchema3 = external_exports.object({ + /** Enforce uniqueness constraint */ + uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), + /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ + completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), + /** Accuracy validation against authoritative source */ + accuracy: external_exports.object({ + source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), + threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") + }).optional().describe("Accuracy validation configuration") + }); + ComputedFieldCacheSchema3 = external_exports.object({ + /** Enable caching for this computed field */ + enabled: external_exports.boolean().describe("Enable caching for computed field results"), + /** Time-to-live in seconds */ + ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), + /** Array of field paths that trigger cache invalidation when changed */ + invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') + }); + FieldSchema3 = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), + label: external_exports.string().optional().describe("Human readable label"), + type: FieldType3.describe("Field Data Type"), + description: external_exports.string().optional().describe("Tooltip/Help text"), + format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), + /** Storage Layer Mapping */ + columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), + /** Database Constraints */ + required: external_exports.boolean().default(false).describe("Is required"), + searchable: external_exports.boolean().default(false).describe("Is searchable"), + multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), + unique: external_exports.boolean().default(false).describe("Is unique constraint"), + defaultValue: external_exports.unknown().optional().describe("Default value"), + /** Text/String Constraints */ + maxLength: external_exports.number().optional().describe("Max character length"), + minLength: external_exports.number().optional().describe("Min character length"), + /** Number Constraints */ + precision: external_exports.number().optional().describe("Total digits"), + scale: external_exports.number().optional().describe("Decimal places"), + min: external_exports.number().optional().describe("Minimum value"), + max: external_exports.number().optional().describe("Maximum value"), + /** Selection Options */ + options: external_exports.array(SelectOptionSchema3).optional().describe("Static options for select/multiselect"), + /** + * Relationship Config + * + * Used by `lookup` and `master_detail` field types to define cross-object references. + * The `reference` property is **required** for these types — it identifies the target + * object whose records this field links to. The engine uses `reference` during $expand + * post-processing to resolve foreign key IDs into full related objects via batch queries. + * + * For `master_detail` fields, the parent record controls the lifecycle of child records + * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. + */ + reference: external_exports.string().optional().describe( + "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." + ), + referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), + writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), + deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), + /** Calculation */ + expression: external_exports.string().optional().describe("Formula expression"), + summaryOperations: external_exports.object({ + object: external_exports.string().describe("Source child object name for roll-up"), + field: external_exports.string().describe("Field on child object to aggregate"), + function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") + }).optional().describe("Roll-up summary definition"), + /** Enhanced Field Type Configurations */ + // Code field config + language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), + theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), + lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), + // Rating field config + maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), + allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), + // Location field config + displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), + allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), + // Address field config + addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), + // Color field config + colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), + allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), + presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), + // Slider field config + step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), + showValue: external_exports.boolean().optional().describe("Display current value on slider"), + marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), + // QR Code / Barcode field config + // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' + // Runtime validation should enforce this constraint + barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), + qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), + displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), + allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), + // Currency field config + currencyConfig: CurrencyConfigSchema3.optional().describe("Configuration for currency field type"), + // Vector field config + vectorConfig: VectorConfigSchema3.optional().describe("Configuration for vector field type (AI/ML embeddings)"), + // File attachment field config + fileAttachmentConfig: FileAttachmentConfigSchema3.optional().describe("Configuration for file and attachment field types"), + /** Enhanced Security & Compliance */ + // Encryption configuration + encryptionConfig: EncryptionConfigSchema3.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), + // Data masking rules + maskingRule: MaskingRuleSchema3.optional().describe("Data masking rules for PII protection"), + // Audit trail + auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), + /** Field Dependencies & Relationships */ + // Field dependencies + dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), + /** Computed Field Optimization */ + // Computed field caching + cached: ComputedFieldCacheSchema3.optional().describe("Caching configuration for computed/formula fields"), + /** Data Quality & Governance */ + // Data quality rules + dataQuality: DataQualityRulesSchema3.optional().describe("Data quality validation and monitoring rules"), + /** Layout & Grouping */ + group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), + /** Conditional Requirements */ + conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), + /** Security & Visibility */ + hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), + readonly: external_exports.boolean().default(false).describe("Read-only in UI"), + sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), + inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), + trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), + caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), + autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), + /** Indexing */ + index: external_exports.boolean().default(false).describe("Create standard database index"), + externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") + }); + Field = { + text: (config4 = {}) => ({ type: "text", ...config4 }), + textarea: (config4 = {}) => ({ type: "textarea", ...config4 }), + number: (config4 = {}) => ({ type: "number", ...config4 }), + boolean: (config4 = {}) => ({ type: "boolean", ...config4 }), + date: (config4 = {}) => ({ type: "date", ...config4 }), + datetime: (config4 = {}) => ({ type: "datetime", ...config4 }), + currency: (config4 = {}) => ({ type: "currency", ...config4 }), + percent: (config4 = {}) => ({ type: "percent", ...config4 }), + url: (config4 = {}) => ({ type: "url", ...config4 }), + email: (config4 = {}) => ({ type: "email", ...config4 }), + phone: (config4 = {}) => ({ type: "phone", ...config4 }), + image: (config4 = {}) => ({ type: "image", ...config4 }), + file: (config4 = {}) => ({ type: "file", ...config4 }), + avatar: (config4 = {}) => ({ type: "avatar", ...config4 }), + formula: (config4 = {}) => ({ type: "formula", ...config4 }), + summary: (config4 = {}) => ({ type: "summary", ...config4 }), + autonumber: (config4 = {}) => ({ type: "autonumber", ...config4 }), + markdown: (config4 = {}) => ({ type: "markdown", ...config4 }), + html: (config4 = {}) => ({ type: "html", ...config4 }), + password: (config4 = {}) => ({ type: "password", ...config4 }), + /** + * Select field helper with backward-compatible API + * + * Automatically converts option values to lowercase to enforce naming conventions. + * + * @example Old API (array first) - auto-converts to lowercase + * Field.select(['High', 'Low'], { label: 'Priority' }) + * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }] + * + * @example New API (config object) - enforces lowercase + * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' }) + * + * @example Multi-word values - converts to snake_case + * Field.select(['In Progress', 'Closed Won'], { label: 'Status' }) + * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }] + */ + select: (optionsOrConfig, config4) => { + const toSnakeCase = (str) => { + return str.toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, ""); + }; + let options; + let finalConfig; + if (Array.isArray(optionsOrConfig)) { + options = optionsOrConfig.map( + (o) => typeof o === "string" ? { label: o, value: toSnakeCase(o) } : { ...o, value: o.value.toLowerCase() } + // Ensure value is lowercase + ); + finalConfig = config4 || {}; + } else { + options = (optionsOrConfig.options || []).map( + (o) => typeof o === "string" ? { label: o, value: toSnakeCase(o) } : { ...o, value: o.value.toLowerCase() } + // Ensure value is lowercase + ); + const { options: _, ...restConfig } = optionsOrConfig; + finalConfig = restConfig; + } + return { type: "select", options, ...finalConfig }; + }, + lookup: (reference, config4 = {}) => ({ + type: "lookup", + reference, + ...config4 + }), + masterDetail: (reference, config4 = {}) => ({ + type: "master_detail", + reference, + ...config4 + }), + // Enhanced Field Type Helpers + location: (config4 = {}) => ({ + type: "location", + ...config4 + }), + address: (config4 = {}) => ({ + type: "address", + ...config4 + }), + richtext: (config4 = {}) => ({ + type: "richtext", + ...config4 + }), + code: (language, config4 = {}) => ({ + type: "code", + language, + ...config4 + }), + color: (config4 = {}) => ({ + type: "color", + ...config4 + }), + rating: (maxRating = 5, config4 = {}) => ({ + type: "rating", + maxRating, + ...config4 + }), + signature: (config4 = {}) => ({ + type: "signature", + ...config4 + }), + slider: (config4 = {}) => ({ + type: "slider", + ...config4 + }), + qrcode: (config4 = {}) => ({ + type: "qrcode", + ...config4 + }), + json: (config4 = {}) => ({ + type: "json", + ...config4 + }), + vector: (dimensions, config4 = {}) => ({ + type: "vector", + vectorConfig: { + dimensions, + distanceMetric: "cosine", + normalized: false, + indexed: true, + ...config4.vectorConfig + }, + ...config4 + }) + }; + BaseValidationSchema3 = external_exports.object({ + // Identification + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label for the rule listing"), + description: external_exports.string().optional().describe("Administrative notes explaining the business reason"), + // Execution Control + active: external_exports.boolean().default(true), + events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).default(["insert", "update"]).describe("Validation contexts"), + priority: external_exports.number().int().min(0).max(9999).default(100).describe("Execution priority (lower runs first, default: 100)"), + // Classification + tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g., "compliance", "billing")'), + // Feedback + severity: external_exports.enum(["error", "warning", "info"]).default("error"), + message: external_exports.string().describe("Error message to display to the user") + }); + ScriptValidationSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("script"), + condition: external_exports.string().describe("Formula expression. If TRUE, validation fails. (e.g. amount < 0)") + }); + UniquenessValidationSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("unique"), + fields: external_exports.array(external_exports.string()).describe("Fields that must be combined unique"), + scope: external_exports.string().optional().describe("Formula condition for scope (e.g. active = true)"), + caseSensitive: external_exports.boolean().default(true) + }); + StateMachineValidationSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("state_machine"), + field: external_exports.string().describe("State field (e.g. status)"), + transitions: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).describe("Map of { OldState: [AllowedNewStates] }") + }); + FormatValidationSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("format"), + field: external_exports.string(), + regex: external_exports.string().optional(), + format: external_exports.enum(["email", "url", "phone", "json"]).optional() + }); + CrossFieldValidationSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("cross_field"), + condition: external_exports.string().describe('Formula expression comparing fields (e.g. "end_date > start_date")'), + fields: external_exports.array(external_exports.string()).describe("Fields involved in the validation") + }); + JSONValidationSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("json_schema"), + field: external_exports.string().describe("JSON field to validate"), + schema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema object definition") + }); + AsyncValidationSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("async"), + field: external_exports.string().describe("Field to validate"), + validatorUrl: external_exports.string().optional().describe("External API endpoint for validation"), + method: external_exports.enum(["GET", "POST"]).default("GET").describe("HTTP method for external call"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for the request"), + validatorFunction: external_exports.string().optional().describe("Reference to custom validator function"), + timeout: external_exports.number().optional().default(5e3).describe("Timeout in milliseconds"), + debounce: external_exports.number().optional().describe("Debounce delay in milliseconds"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional parameters to pass to validator") + }); + CustomValidatorSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("custom"), + handler: external_exports.string().describe("Name of the custom validation function registered in the system"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the custom handler") + }); + ValidationRuleSchema3 = external_exports.lazy( + () => external_exports.discriminatedUnion("type", [ + ScriptValidationSchema3, + UniquenessValidationSchema3, + StateMachineValidationSchema3, + FormatValidationSchema3, + CrossFieldValidationSchema3, + JSONValidationSchema3, + AsyncValidationSchema3, + CustomValidatorSchema3, + ConditionalValidationSchema3 + ]) + ); + ConditionalValidationSchema3 = BaseValidationSchema3.extend({ + type: external_exports.literal("conditional"), + when: external_exports.string().describe(`Condition formula (e.g. "type = 'enterprise'")`), + then: ValidationRuleSchema3.describe("Validation rule to apply when condition is true"), + otherwise: ValidationRuleSchema3.optional().describe("Validation rule to apply when condition is false") + }); + ActionRefSchema3 = external_exports.union([ + external_exports.string().describe("Action Name"), + external_exports.object({ + type: external_exports.string(), + // e.g., 'xstate.assign', 'log', 'email' + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }) + ]); + GuardRefSchema3 = external_exports.union([ + external_exports.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'), + external_exports.object({ + type: external_exports.string(), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }) + ]); + TransitionSchema3 = external_exports.object({ + target: external_exports.string().optional().describe("Target State ID"), + cond: GuardRefSchema3.optional().describe("Condition (Guard) required to take this path"), + actions: external_exports.array(ActionRefSchema3).optional().describe("Actions to execute during transition"), + description: external_exports.string().optional().describe("Human readable description of this rule") + }); + external_exports.object({ + type: external_exports.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'), + // Payload validation schema could go here if we want deep validation + schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Expected event payload structure") + }); + StateNodeSchema3 = external_exports.lazy(() => external_exports.object({ + /** Type of state */ + type: external_exports.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"), + /** Entry/Exit Actions */ + entry: external_exports.array(ActionRefSchema3).optional().describe("Actions to run when entering this state"), + exit: external_exports.array(ActionRefSchema3).optional().describe("Actions to run when leaving this state"), + /** Transitions (Events) */ + on: external_exports.record(external_exports.string(), external_exports.union([ + external_exports.string(), + // Shorthand target + TransitionSchema3, + external_exports.array(TransitionSchema3) + ])).optional().describe("Map of Event Type -> Transition Definition"), + /** Always Transitions (Eventless) */ + always: external_exports.array(TransitionSchema3).optional(), + /** Nesting (Hierarchical States) */ + initial: external_exports.string().optional().describe("Initial child state (if compound)"), + states: external_exports.record(external_exports.string(), StateNodeSchema3).optional(), + /** Metadata for UI/AI */ + meta: external_exports.object({ + label: external_exports.string().optional(), + description: external_exports.string().optional(), + color: external_exports.string().optional(), + // For UI diagrams + // Instructions for AI Agent when in this state + aiInstructions: external_exports.string().optional().describe("Specific instructions for AI when in this state") + }).optional() + })); + StateMachineSchema3 = external_exports.object({ + id: SnakeCaseIdentifierSchema3.describe("Unique Machine ID"), + description: external_exports.string().optional(), + /** Context (Memory) Schema */ + contextSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Zod Schema for the machine context/memory"), + /** Initial State */ + initial: external_exports.string().describe("Initial State ID"), + /** State Definitions */ + states: external_exports.record(external_exports.string(), StateNodeSchema3).describe("State Nodes"), + /** Global Listeners */ + on: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), TransitionSchema3, external_exports.array(TransitionSchema3)])).optional() + }); + external_exports.object({ + /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ + key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), + /** Default value when translation is not available */ + defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), + /** Interpolation parameters for dynamic translations */ + params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") + }); + I18nLabelSchema3 = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); + AriaPropsSchema3 = external_exports.object({ + /** Accessible label for screen readers */ + ariaLabel: I18nLabelSchema3.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), + /** ID of element that describes this component */ + ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), + /** WAI-ARIA role override */ + role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') + }).describe("ARIA accessibility attributes"); + external_exports.object({ + /** Translation key for the plural form */ + key: external_exports.string().describe("Translation key"), + /** Form for zero quantity */ + zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), + /** Form for singular (1) */ + one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), + /** Form for dual (2) — used in Arabic, Welsh, etc. */ + two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), + /** Form for few (2-4 in Slavic languages) */ + few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), + /** Form for many (5+ in Slavic languages) */ + many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), + /** Default/fallback form */ + other: external_exports.string().describe('Default plural form (e.g., "{count} items")') + }).describe("ICU plural rules for a translation key"); + NumberFormatSchema3 = external_exports.object({ + style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), + currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), + unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), + minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), + maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), + useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") + }).describe("Number formatting rules"); + DateFormatSchema3 = external_exports.object({ + dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), + timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), + timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), + hour12: external_exports.boolean().optional().describe("Use 12-hour format") + }).describe("Date/time formatting rules"); + external_exports.object({ + /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ + code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), + /** Ordered fallback chain for missing translations */ + fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), + /** Text direction */ + direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), + /** Default number formatting */ + numberFormat: NumberFormatSchema3.optional().describe("Default number formatting rules"), + /** Default date formatting */ + dateFormat: DateFormatSchema3.optional().describe("Default date/time formatting rules") + }).describe("Locale configuration"); + ActionParamSchema3 = external_exports.object({ + name: external_exports.string(), + label: I18nLabelSchema3, + type: FieldType3, + required: external_exports.boolean().default(false), + options: external_exports.array(external_exports.object({ label: I18nLabelSchema3, value: external_exports.string() })).optional() + }); + ActionType3 = external_exports.enum(["script", "url", "modal", "flow", "api"]); + TARGET_REQUIRED_TYPES3 = new Set( + ActionType3.options.filter((t) => t !== "script") + ); + ActionSchema3 = external_exports.object({ + /** Machine name of the action */ + name: SnakeCaseIdentifierSchema3.describe("Machine name (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema3.describe("Display label"), + /** Target object this action belongs to (optional, snake_case) */ + objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Icon name"), + /** Where does this action appear? */ + locations: external_exports.array(external_exports.enum([ + "list_toolbar", + "list_item", + "record_header", + "record_more", + "record_related", + "global_nav" + ])).optional().describe("Locations where this action is visible"), + /** + * Visual Component Type + * Defaults to 'button' or 'menu_item' based on location, + * but can be overridden. + */ + component: external_exports.enum([ + "action:button", + // Standard Button + "action:icon", + // Icon only + "action:menu", + // Dropdown menu + "action:group" + // Button Group + ]).optional().describe("Visual component override"), + /** What type of interaction? */ + type: ActionType3.default("script").describe("Action functionality type"), + /** + * Payload / Target — the canonical binding for the action handler. + * Required for url, flow, modal, and api types. + * Recommended for script type. + */ + target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), + /** + * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. + */ + execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), + /** User Input Requirements */ + params: external_exports.array(ActionParamSchema3).optional().describe("Input parameters required from user"), + /** Visual Style */ + variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), + /** UX Behavior */ + confirmText: I18nLabelSchema3.optional().describe("Confirmation message before execution"), + successMessage: I18nLabelSchema3.optional().describe("Success message to show after execution"), + refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), + /** Access */ + visible: external_exports.string().optional().describe("Formula returning boolean"), + disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), + /** Keyboard Shortcut */ + shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), + /** Bulk Operations */ + bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), + /** Execution */ + timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema3.optional().describe("ARIA accessibility attributes") + }).transform((data) => { + if (data.execute && !data.target) { + return { ...data, target: data.execute }; + } + return data; + }).refine((data) => { + if (TARGET_REQUIRED_TYPES3.has(data.type) && !data.target) { + return false; + } + return true; + }, { + message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", + path: ["target"] + }); + ApiMethod3 = external_exports.enum([ + "get", + "list", + // Read + "create", + "update", + "delete", + // Write + "upsert", + // Idempotent Write + "bulk", + // Batch operations + "aggregate", + // Analytics (count, sum) + "history", + // Audit access + "search", + // Search access + "restore", + "purge", + // Trash management + "import", + "export" + // Data portability + ]); + ObjectCapabilities3 = external_exports.object({ + /** Enable history tracking (Audit Trail) */ + trackHistory: external_exports.boolean().default(false).describe("Enable field history tracking for audit compliance"), + /** Enable global search indexing */ + searchable: external_exports.boolean().default(true).describe("Index records for global search"), + /** Enable REST/GraphQL API access */ + apiEnabled: external_exports.boolean().default(true).describe("Expose object via automatic APIs"), + /** + * API Supported Operations + * Granular control over API exposure. + */ + apiMethods: external_exports.array(ApiMethod3).optional().describe("Whitelist of allowed API operations"), + /** Enable standard attachments/files engine */ + files: external_exports.boolean().default(false).describe("Enable file attachments and document management"), + /** Enable social collaboration (Comments, Mentions, Feeds) */ + feeds: external_exports.boolean().default(false).describe("Enable social feed, comments, and mentions (Chatter-like)"), + /** Enable standard Activity suite (Tasks, Calendars, Events) */ + activities: external_exports.boolean().default(false).describe("Enable standard tasks and events tracking"), + /** Enable Recycle Bin / Soft Delete */ + trash: external_exports.boolean().default(true).describe("Enable soft-delete with restore capability"), + /** Enable "Recently Viewed" tracking */ + mru: external_exports.boolean().default(true).describe("Track Most Recently Used (MRU) list for users"), + /** Allow cloning records */ + clone: external_exports.boolean().default(true).describe("Allow record deep cloning") + }); + IndexSchema3 = external_exports.object({ + name: external_exports.string().optional().describe("Index name (auto-generated if not provided)"), + fields: external_exports.array(external_exports.string()).describe("Fields included in the index"), + type: external_exports.enum(["btree", "hash", "gin", "gist", "fulltext"]).optional().default("btree").describe("Index algorithm type"), + unique: external_exports.boolean().optional().default(false).describe("Whether the index enforces uniqueness"), + partial: external_exports.string().optional().describe("Partial index condition (SQL WHERE clause for conditional indexes)") + }); + SearchConfigSchema4 = external_exports.object({ + fields: external_exports.array(external_exports.string()).describe("Fields to index for full-text search weighting"), + displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display in search result cards"), + filters: external_exports.array(external_exports.string()).optional().describe("Default filters for search results") + }); + TenancyConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable multi-tenancy for this object"), + strategy: external_exports.enum(["shared", "isolated", "hybrid"]).describe("Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)"), + tenantField: external_exports.string().default("tenant_id").describe("Field name for tenant identifier"), + crossTenantAccess: external_exports.boolean().default(false).describe("Allow cross-tenant data access (with explicit permission)") + }); + SoftDeleteConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable soft delete (trash/recycle bin)"), + field: external_exports.string().default("deleted_at").describe("Field name for soft delete timestamp"), + cascadeDelete: external_exports.boolean().default(false).describe("Cascade soft delete to related records") + }); + VersioningConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable record versioning"), + strategy: external_exports.enum(["snapshot", "delta", "event-sourcing"]).describe("Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)"), + retentionDays: external_exports.number().min(1).optional().describe("Number of days to retain old versions (undefined = infinite)"), + versionField: external_exports.string().default("version").describe("Field name for version number/timestamp") + }); + PartitioningConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable table partitioning"), + strategy: external_exports.enum(["range", "hash", "list"]).describe("Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)"), + key: external_exports.string().describe("Field name to partition by"), + interval: external_exports.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")') + }).refine((data) => { + if (data.strategy === "range" && !data.interval) { + return false; + } + return true; + }, { + message: 'interval is required when strategy is "range"' + }); + CDCConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable Change Data Capture"), + events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).describe("Event types to capture"), + destination: external_exports.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")') + }); + ObjectSchemaBase3 = external_exports.object({ + /** + * Identity & Metadata + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine unique key (snake_case). Immutable."), + label: external_exports.string().optional().describe('Human readable singular label (e.g. "Account")'), + pluralLabel: external_exports.string().optional().describe('Human readable plural label (e.g. "Accounts")'), + description: external_exports.string().optional().describe("Developer documentation / description"), + icon: external_exports.string().optional().describe("Icon name (Lucide/Material) for UI representation"), + /** + * Namespace & Domain Classification + * + * Groups objects into logical domains for routing, permissions, and discovery. + * System objects use `'sys'`; business packages use their own namespace. + * + * When set, `tableName` is auto-derived as `{namespace}_{name}` by + * `ObjectSchema.create()` unless an explicit `tableName` is provided. + * + * Namespace must be a single lowercase word (no underscores or hyphens) + * to ensure clean auto-derivation of `{namespace}_{name}` table names. + * + * @example namespace: 'sys' → tableName defaults to 'sys_user' + * @example namespace: 'crm' → tableName defaults to 'crm_account' + */ + namespace: external_exports.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace \u2014 single lowercase word (e.g. "sys", "crm"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'), + /** + * Taxonomy & Organization + */ + tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'), + active: external_exports.boolean().optional().default(true).describe("Is the object active and usable"), + isSystem: external_exports.boolean().optional().default(false).describe("Is system object (protected from deletion)"), + abstract: external_exports.boolean().optional().default(false).describe("Is abstract base object (cannot be instantiated)"), + /** + * Storage & Virtualization + */ + datasource: external_exports.string().optional().default("default").describe('Target Datasource ID. "default" is the primary DB.'), + tableName: external_exports.string().optional().describe("Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set."), + /** + * Data Model + */ + fields: external_exports.record(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/, { + message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")' + }), FieldSchema3).describe("Field definitions map. Keys must be snake_case identifiers."), + indexes: external_exports.array(IndexSchema3).optional().describe("Database performance indexes"), + /** + * Advanced Data Management + */ + // Multi-tenancy configuration + tenancy: TenancyConfigSchema3.optional().describe("Multi-tenancy configuration for SaaS applications"), + // Soft delete configuration + softDelete: SoftDeleteConfigSchema3.optional().describe("Soft delete (trash/recycle bin) configuration"), + // Versioning configuration + versioning: VersioningConfigSchema3.optional().describe("Record versioning and history tracking configuration"), + // Partitioning strategy + partitioning: PartitioningConfigSchema3.optional().describe("Table partitioning configuration for performance"), + // Change Data Capture + cdc: CDCConfigSchema3.optional().describe("Change Data Capture (CDC) configuration for real-time data streaming"), + /** + * Logic & Validation (Co-located) + * Best Practice: Define rules close to data. + */ + validations: external_exports.array(ValidationRuleSchema3).optional().describe("Object-level validation rules"), + /** + * State Machine(s) + * Named record of state machines, where each key is a unique machine identifier. + * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status). + * + * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} } + */ + stateMachines: external_exports.record(external_exports.string(), StateMachineSchema3).optional().describe("Named state machines for parallel lifecycles (e.g., status, payment, approval)"), + /** + * Display & UI Hints (Data-Layer) + */ + displayNameField: external_exports.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'), + recordName: external_exports.object({ + type: external_exports.enum(["text", "autonumber"]).describe("Record name type: text (user-entered) or autonumber (system-generated)"), + displayFormat: external_exports.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'), + startNumber: external_exports.number().int().min(0).optional().describe("Starting number for autonumber (default: 1)") + }).optional().describe("Record name generation configuration (Salesforce pattern)"), + titleFormat: external_exports.string().optional().describe('Title expression (e.g. "{name} - {code}"). Overrides displayNameField.'), + compactLayout: external_exports.array(external_exports.string()).optional().describe("Primary fields for hover/cards/lookups"), + /** + * Search Engine Config + */ + search: SearchConfigSchema4.optional().describe("Search engine configuration"), + /** + * System Capabilities + */ + enable: ObjectCapabilities3.optional().describe("Enabled system features modules"), + /** Record Types */ + recordTypes: external_exports.array(external_exports.string()).optional().describe("Record type names for this object"), + /** Sharing Model */ + sharingModel: external_exports.enum(["private", "read", "read_write", "full"]).optional().describe("Default sharing model"), + /** Key Prefix */ + keyPrefix: external_exports.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'), + /** + * Object Actions + * + * Actions associated with this object. Populated automatically by `defineStack()` + * when top-level actions specify `objectName` matching this object. + * Can also be defined directly on the object. + * + * Aligns with Salesforce/ServiceNow patterns where actions are part of the + * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`) + * include the action list without requiring downstream merge. + */ + actions: external_exports.array(ActionSchema3).optional().describe("Actions associated with this object (auto-populated from top-level actions via objectName)") + }); + ObjectSchema3 = Object.assign(ObjectSchemaBase3, { + /** + * Type-safe factory for creating business object definitions. + * + * Enhancements over raw schema: + * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case). + * - **Validation**: Runs Zod `.parse()` to validate the config at creation time. + * + * @example + * ```ts + * const Task = ObjectSchema.create({ + * name: 'project_task', + * // label auto-generated as 'Project Task' + * fields: { + * subject: { type: 'text', label: 'Subject', required: true }, + * }, + * }); + * ``` + */ + create: (config4) => { + const withDefaults = { + ...config4, + label: config4.label ?? snakeCaseToLabel3(config4.name), + // Auto-derive tableName as {namespace}_{name} when namespace is set + tableName: config4.tableName ?? (config4.namespace ? `${config4.namespace}_${config4.name}` : void 0) + }; + return ObjectSchemaBase3.parse(withDefaults); + } + }); + ObjectOwnershipEnum = external_exports.enum(["own", "extend"]); + ObjectExtensionSchema = external_exports.object({ + /** The target object name (FQN) to extend */ + extend: external_exports.string().describe("Target object name (FQN) to extend"), + /** Fields to merge into the target object (additive) */ + fields: external_exports.record(external_exports.string(), FieldSchema3).optional().describe("Fields to add/override"), + /** Override label */ + label: external_exports.string().optional().describe("Override label for the extended object"), + /** Override plural label */ + pluralLabel: external_exports.string().optional().describe("Override plural label for the extended object"), + /** Override description */ + description: external_exports.string().optional().describe("Override description for the extended object"), + /** Additional validation rules to add */ + validations: external_exports.array(ValidationRuleSchema3).optional().describe("Additional validation rules to merge into the target object"), + /** Additional indexes to add */ + indexes: external_exports.array(IndexSchema3).optional().describe("Additional indexes to merge into the target object"), + /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ + priority: external_exports.number().int().min(0).max(999).default(200).describe("Merge priority (higher = applied later)") + }); + HookEvent = external_exports.enum([ + // Read Operations + "beforeFind", + "afterFind", + "beforeFindOne", + "afterFindOne", + "beforeCount", + "afterCount", + "beforeAggregate", + "afterAggregate", + // Write Operations + "beforeInsert", + "afterInsert", + "beforeUpdate", + "afterUpdate", + "beforeDelete", + "afterDelete", + // Bulk Operations (Query-based) + "beforeUpdateMany", + "afterUpdateMany", + "beforeDeleteMany", + "afterDeleteMany" + ]); + HookSchema = external_exports.object({ + /** + * Unique identifier for the hook + * Required for debugging and overriding. + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Hook unique name (snake_case)"), + /** + * Human readable label + */ + label: external_exports.string().optional().describe("Description of what this hook does"), + /** + * Target Object(s) + * can be: + * - Single object: "account" + * - List of objects: ["account", "contact"] + * - Wildcard: "*" (All objects) + */ + object: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Target object(s)"), + /** + * Events to subscribe to + * Combinations of timing (before/after) and action (find/insert/update/delete/etc) + */ + events: external_exports.array(HookEvent).describe("Lifecycle events"), + /** + * Handler Logic + * Reference to a registered function in the plugin system OR a direct function (runtime only). + */ + handler: external_exports.union([external_exports.string(), external_exports.function()]).optional().describe("Handler function name (string) or inline function reference"), + /** + * Execution Order + * Lower numbers run first. + * - System Hooks: 0-99 + * - App Hooks: 100-999 + * - User Hooks: 1000+ + */ + priority: external_exports.number().default(100).describe("Execution priority"), + /** + * Async / Background Execution + * If true, the hook runs in the background and does not block the transaction. + * Only applicable for 'after*' events. + * Default: false (Blocking) + */ + async: external_exports.boolean().default(false).describe("Run specifically as fire-and-forget"), + /** + * Declarative Condition + * Formula expression evaluated before the handler runs. + * If provided and evaluates to FALSE, the hook is skipped entirely. + * Useful for filtering by record data without writing handler code. + * + * @example "status = 'active' AND amount > 1000" + */ + condition: external_exports.string().optional().describe(`Formula expression; hook runs only when TRUE (e.g., "status = 'closed' AND amount > 1000")`), + /** + * Human-readable description + */ + description: external_exports.string().optional().describe("Human-readable description of what this hook does"), + /** + * Retry Policy + */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().default(3).describe("Maximum retry attempts on failure"), + backoffMs: external_exports.number().default(1e3).describe("Backoff delay between retries in milliseconds") + }).optional().describe("Retry policy for failed hook executions"), + /** + * Execution Timeout + */ + timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds before the hook is aborted"), + /** + * Error Policy + * What to do if the hook throws an exception? + * - abort: Rollback transaction (if blocking) + * - log: Log error and continue + */ + onError: external_exports.enum(["abort", "log"]).default("abort").describe("Error handling strategy") + }); + HookContextSchema = external_exports.object({ + /** Tracing ID */ + id: external_exports.string().optional().describe("Unique execution ID for tracing"), + /** Target Object Name */ + object: external_exports.string(), + /** Current Lifecycle Event */ + event: HookEvent, + /** + * Input Parameters (Mutable) + * Modify this to change the behavior of the operation. + * + * - find: { query: QueryAST, options: DriverOptions } + * - insert: { doc: Record, options: DriverOptions } + * - update: { id: ID, doc: Record, options: DriverOptions } + * - delete: { id: ID, options: DriverOptions } + * - updateMany: { query: QueryAST, doc: Record, options: DriverOptions } + * - deleteMany: { query: QueryAST, options: DriverOptions } + */ + input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Mutable input parameters"), + /** + * Operation Result (Mutable) + * Available in 'after*' events. Modify this to transform the output. + */ + result: external_exports.unknown().optional().describe("Operation result (After hooks only)"), + /** + * Data Snapshot + * The state of the record BEFORE the operation (for update/delete). + */ + previous: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record state before operation"), + /** + * Execution Session + * Contains authentication and tenancy information. + */ + session: external_exports.object({ + userId: external_exports.string().optional(), + tenantId: external_exports.string().optional(), + roles: external_exports.array(external_exports.string()).optional(), + accessToken: external_exports.string().optional() + }).optional().describe("Current session context"), + /** + * Transaction Handle + * If the operation is part of a transaction, use this handle for side-effects. + */ + transaction: external_exports.unknown().optional().describe("Database transaction handle"), + /** + * Engine Access + * Reference to the ObjectQL engine for performing side effects. + */ + ql: external_exports.unknown().describe("ObjectQL Engine Reference"), + /** + * Cross-Object API + * Provides a scoped data access interface for performing CRUD operations + * on other objects within hooks. Bound to the current execution context + * (userId, tenantId, transaction). + * + * Usage in hooks: + * const users = ctx.api.object('user'); + * const admin = await users.findOne({ filter: { role: 'admin' } }); + */ + api: external_exports.unknown().optional().describe("Cross-object data access (ScopedContext)"), + /** + * Current User Info + * Convenience shortcut for session.userId + additional user metadata. + * Populated by the engine when available. + */ + user: external_exports.object({ + id: external_exports.string().optional(), + name: external_exports.string().optional(), + email: external_exports.string().optional() + }).optional().describe("Current user info shortcut") + }); + TransformType = external_exports.enum([ + "none", + // Direct copy + "constant", + // Use a hardcoded value + "lookup", + // Resolve FK (Name -> ID) + "split", + // "John Doe" -> ["John", "Doe"] + "join", + // ["John", "Doe"] -> "John Doe" + "javascript", + // Custom script (Review security!) + "map" + // Value mapping (e.g. "Active" -> "active") + ]); + FieldMappingSchema = external_exports.object({ + /** Source Column */ + source: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Source column header(s)"), + /** Target Field */ + target: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Target object field(s)"), + /** Transformation */ + transform: TransformType.default("none"), + /** Configuration for transform */ + params: external_exports.object({ + // Constant + value: external_exports.unknown().optional(), + // Lookup + object: external_exports.string().optional(), + // Lookup Object + fromField: external_exports.string().optional(), + // Match on (e.g. "name") + toField: external_exports.string().optional(), + // Value to take (e.g. "id") + autoCreate: external_exports.boolean().optional(), + // Create if missing + // Map + valueMap: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + // { "Open": "draft" } + // Split/Join + separator: external_exports.string().optional() + }).optional() + }); + MappingSchema = external_exports.object({ + /** Identity */ + name: SnakeCaseIdentifierSchema3.describe("Mapping unique name (lowercase snake_case)"), + label: external_exports.string().optional(), + /** Scope */ + sourceFormat: external_exports.enum(["csv", "json", "xml", "sql"]).default("csv"), + targetObject: external_exports.string().describe("Target Object Name"), + /** Column Mappings */ + fieldMapping: external_exports.array(FieldMappingSchema), + /** Upsert Logic */ + mode: external_exports.enum(["insert", "update", "upsert"]).default("insert"), + upsertKey: external_exports.array(external_exports.string()).optional().describe("Fields to match for upsert (e.g. email)"), + /** Extract Logic (For Export) */ + extractQuery: QuerySchema2.optional().describe("Query to run for export only"), + /** Error Handling */ + errorPolicy: external_exports.enum(["skip", "abort", "retry"]).default("skip"), + batchSize: external_exports.number().default(1e3) + }); + ExecutionContextSchema = external_exports.object({ + /** Current user ID (resolved from session) */ + userId: external_exports.string().optional(), + /** Current organization/tenant ID (resolved from session.activeOrganizationId) */ + tenantId: external_exports.string().optional(), + /** User role names (resolved from Member + Role) */ + roles: external_exports.array(external_exports.string()).default([]), + /** Aggregated permission names (resolved from PermissionSet) */ + permissions: external_exports.array(external_exports.string()).default([]), + /** Whether this is a system-level operation (bypasses permission checks) */ + isSystem: external_exports.boolean().default(false), + /** Raw access token (for external API call pass-through) */ + accessToken: external_exports.string().optional(), + /** Database transaction handle */ + transaction: external_exports.unknown().optional(), + /** Request trace ID (for distributed tracing) */ + traceId: external_exports.string().optional() + }); + DataEngineFilterSchema = external_exports.union([ + external_exports.record(external_exports.string(), external_exports.unknown()), + FilterConditionSchema2 + ]).describe("Data Engine query filter conditions"); + DataEngineSortSchema = external_exports.union([ + external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])), + external_exports.record(external_exports.string(), external_exports.union([external_exports.literal(1), external_exports.literal(-1)])), + external_exports.array(SortNodeSchema2) + ]).describe("Sort order definition"); + BaseEngineOptionsSchema = external_exports.object({ + /** Execution context (identity, tenant, transaction) */ + context: ExecutionContextSchema.optional() + }); + EngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({ + /** Filter conditions (WHERE) — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), + /** Fields to retrieve (SELECT) — standard QueryAST `fields` */ + fields: external_exports.array(FieldNodeSchema2).optional(), + /** Sorting instructions (ORDER BY) — standard QueryAST `orderBy` */ + orderBy: external_exports.array(SortNodeSchema2).optional(), + /** Max records to return (LIMIT) */ + limit: external_exports.number().optional(), + /** Records to skip (OFFSET) — standard QueryAST `offset` */ + offset: external_exports.number().optional(), + /** Alias for limit (OData compatibility) */ + top: external_exports.number().optional(), + /** Cursor for keyset pagination */ + cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** Full-text search configuration */ + search: FullTextSearchSchema2.optional(), + /** + * Recursive relation loading map (expand). + * + * Keys are lookup/master_detail field names; values are nested QueryAST + * objects that control select, filter, sort, and further expansion on + * the related object. The engine resolves expand via batch $in queries + * (driver-agnostic) with a default max depth of 3. + */ + expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema2)).optional(), + /** SELECT DISTINCT flag */ + distinct: external_exports.boolean().optional() + }).describe("QueryAST-aligned query options for IDataEngine.find() operations"); + DataEngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({ + /** @deprecated Use `where` (EngineQueryOptionsSchema) */ + filter: DataEngineFilterSchema.optional(), + /** @deprecated Use `fields` (EngineQueryOptionsSchema) */ + select: external_exports.array(external_exports.string()).optional(), + /** @deprecated Use `orderBy` (EngineQueryOptionsSchema) */ + sort: DataEngineSortSchema.optional(), + limit: external_exports.number().int().min(1).optional(), + /** @deprecated Use `offset` (EngineQueryOptionsSchema) */ + skip: external_exports.number().int().min(0).optional(), + top: external_exports.number().int().min(1).optional(), + /** @deprecated Use `expand` (EngineQueryOptionsSchema) */ + populate: external_exports.array(external_exports.string()).optional() + }).describe("Query options for IDataEngine.find() operations"); + DataEngineInsertOptionsSchema = BaseEngineOptionsSchema.extend({ + /** + * Return the inserted record(s)? + * Some drivers support RETURNING clause for efficiency. + * Default: true + */ + returning: external_exports.boolean().default(true).optional() + }).describe("Options for DataEngine.insert operations"); + EngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({ + /** Filter conditions to identify records to update — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), + /** Perform an upsert? If true, insert if not found. */ + upsert: external_exports.boolean().default(false).optional(), + /** Update multiple records? If false, only the first match is updated. Default: false */ + multi: external_exports.boolean().default(false).optional(), + /** Return the updated record(s)? Default: false (returns update count/status) */ + returning: external_exports.boolean().default(false).optional() + }).describe("QueryAST-aligned options for DataEngine.update operations"); + DataEngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({ + /** @deprecated Use `where` (EngineUpdateOptionsSchema) */ + filter: DataEngineFilterSchema.optional(), + upsert: external_exports.boolean().default(false).optional(), + multi: external_exports.boolean().default(false).optional(), + returning: external_exports.boolean().default(false).optional() + }).describe("Options for DataEngine.update operations"); + EngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({ + /** Filter conditions to identify records to delete — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), + /** Delete multiple records? If false, only the first match is deleted. Default: false */ + multi: external_exports.boolean().default(false).optional() + }).describe("QueryAST-aligned options for DataEngine.delete operations"); + DataEngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({ + /** @deprecated Use `where` (EngineDeleteOptionsSchema) */ + filter: DataEngineFilterSchema.optional(), + multi: external_exports.boolean().default(false).optional() + }).describe("Options for DataEngine.delete operations"); + EngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({ + /** Filter conditions (WHERE) — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), + /** Group By fields */ + groupBy: external_exports.array(external_exports.string()).optional(), + /** + * Aggregation definitions — uses standard AggregationNodeSchema (`function` key). + * e.g. [{ function: 'sum', field: 'amount', alias: 'total' }] + */ + aggregations: external_exports.array(AggregationNodeSchema2).optional() + }).describe("QueryAST-aligned options for DataEngine.aggregate operations"); + DataEngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({ + /** @deprecated Use `where` (EngineAggregateOptionsSchema) */ + filter: DataEngineFilterSchema.optional(), + groupBy: external_exports.array(external_exports.string()).optional(), + /** + * @deprecated Use `EngineAggregateOptionsSchema` with standard AggregationNodeSchema (`function` key). + */ + aggregations: external_exports.array(external_exports.object({ + field: external_exports.string(), + method: external_exports.enum(["count", "sum", "avg", "min", "max", "count_distinct"]), + alias: external_exports.string().optional() + })).optional() + }).describe("Options for DataEngine.aggregate operations"); + EngineCountOptionsSchema = BaseEngineOptionsSchema.extend({ + /** Filter conditions — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional() + }).describe("QueryAST-aligned options for DataEngine.count operations"); + DataEngineCountOptionsSchema = BaseEngineOptionsSchema.extend({ + /** @deprecated Use `where` (EngineCountOptionsSchema) */ + filter: DataEngineFilterSchema.optional() + }).describe("Options for DataEngine.count operations"); + DataEngineContractSchema = external_exports.object({ + find: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineQueryOptionsSchema.optional()])).output(external_exports.promise(external_exports.array(external_exports.unknown()))), + findOne: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineQueryOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())), + insert: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown()))]), DataEngineInsertOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())), + update: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), EngineUpdateOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())), + delete: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineDeleteOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())), + count: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineCountOptionsSchema.optional()])).output(external_exports.promise(external_exports.number())), + aggregate: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineAggregateOptionsSchema])).output(external_exports.promise(external_exports.array(external_exports.unknown()))) + }).describe("Standard Data Engine Contract"); + RpcLegacyFilterMixin = { + /** @deprecated Use `where` */ + filter: DataEngineFilterSchema.optional() + }; + RpcQueryOptionsSchema = EngineQueryOptionsSchema.extend({ + ...RpcLegacyFilterMixin, + /** @deprecated Use `fields` */ + select: external_exports.array(external_exports.string()).optional(), + /** @deprecated Use `orderBy` */ + sort: DataEngineSortSchema.optional(), + /** @deprecated Use `offset` */ + skip: external_exports.number().int().min(0).optional(), + /** @deprecated Use `expand` */ + populate: external_exports.array(external_exports.string()).optional() + }); + DataEngineFindRequestSchema = external_exports.object({ + method: external_exports.literal("find"), + object: external_exports.string(), + query: RpcQueryOptionsSchema.optional() + }); + DataEngineFindOneRequestSchema = external_exports.object({ + method: external_exports.literal("findOne"), + object: external_exports.string(), + query: RpcQueryOptionsSchema.optional() + }); + DataEngineInsertRequestSchema = external_exports.object({ + method: external_exports.literal("insert"), + object: external_exports.string(), + data: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown()))]), + options: DataEngineInsertOptionsSchema.optional() + }); + DataEngineUpdateRequestSchema = external_exports.object({ + method: external_exports.literal("update"), + object: external_exports.string(), + data: external_exports.record(external_exports.string(), external_exports.unknown()), + id: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("ID for single update, or use where in options"), + options: EngineUpdateOptionsSchema.extend(RpcLegacyFilterMixin).optional() + }); + DataEngineDeleteRequestSchema = external_exports.object({ + method: external_exports.literal("delete"), + object: external_exports.string(), + id: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("ID for single delete, or use where in options"), + options: EngineDeleteOptionsSchema.extend(RpcLegacyFilterMixin).optional() + }); + DataEngineCountRequestSchema = external_exports.object({ + method: external_exports.literal("count"), + object: external_exports.string(), + query: EngineCountOptionsSchema.extend(RpcLegacyFilterMixin).optional() + }); + DataEngineAggregateRequestSchema = external_exports.object({ + method: external_exports.literal("aggregate"), + object: external_exports.string(), + query: EngineAggregateOptionsSchema.extend(RpcLegacyFilterMixin) + }); + DataEngineExecuteRequestSchema = external_exports.object({ + method: external_exports.literal("execute"), + /** The abstract command (string SQL, or JSON object) */ + command: external_exports.unknown(), + /** Optional options */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }); + DataEngineVectorFindRequestSchema = external_exports.object({ + method: external_exports.literal("vectorFind"), + object: external_exports.string(), + /** The vector embedding to search for */ + vector: external_exports.array(external_exports.number()), + /** Optional pre-filter (Metadata filtering) — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), + /** Fields to retrieve — standard QueryAST `fields` */ + fields: external_exports.array(external_exports.string()).optional(), + /** Number of results */ + limit: external_exports.number().int().default(5).optional(), + /** Minimum similarity score (0-1) or distance threshold */ + threshold: external_exports.number().optional() + }); + DataEngineBatchRequestSchema = external_exports.object({ + method: external_exports.literal("batch"), + requests: external_exports.array(external_exports.discriminatedUnion("method", [ + DataEngineFindRequestSchema, + DataEngineFindOneRequestSchema, + DataEngineInsertRequestSchema, + DataEngineUpdateRequestSchema, + DataEngineDeleteRequestSchema, + DataEngineCountRequestSchema, + DataEngineAggregateRequestSchema, + DataEngineExecuteRequestSchema, + DataEngineVectorFindRequestSchema + ])), + /** + * Transaction Mode + * - true: All or nothing (Atomic) + * - false: Best effort, continue on error + */ + transaction: external_exports.boolean().default(true).optional() + }); + DataEngineRequestSchema = external_exports.discriminatedUnion("method", [ + DataEngineFindRequestSchema, + DataEngineFindOneRequestSchema, + DataEngineInsertRequestSchema, + DataEngineUpdateRequestSchema, + DataEngineDeleteRequestSchema, + DataEngineCountRequestSchema, + DataEngineAggregateRequestSchema, + DataEngineBatchRequestSchema, + DataEngineExecuteRequestSchema, + DataEngineVectorFindRequestSchema + ]).describe("Virtual ObjectQL Request Protocol"); + external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "percentile", + "median", + "stddev", + "variance" + ]).describe("Standard aggregation functions"); + SortDirectionEnum = external_exports.enum(["asc", "desc"]).describe("Sort order direction"); + external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + order: SortDirectionEnum.describe("Sort direction") + }).describe("Sort field and direction pair"); + external_exports.enum([ + "insert", + "update", + "delete", + "upsert" + ]).describe("Data mutation event types"); + IsolationLevelEnum = external_exports.enum([ + "read_uncommitted", + "read_committed", + "repeatable_read", + "serializable", + "snapshot" + ]).describe("Transaction isolation levels (snake_case standard)"); + external_exports.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy"); + DriverOptionsSchema = external_exports.object({ + /** + * Transaction handle/identifier. + * If provided, the operation must run within this transaction. + */ + transaction: external_exports.unknown().optional().describe("Transaction handle"), + /** + * Operation timeout in milliseconds. + */ + timeout: external_exports.number().optional().describe("Timeout in ms"), + /** + * Whether to bypass cache and force a fresh read. + */ + skipCache: external_exports.boolean().optional().describe("Bypass cache"), + /** + * Distributed Tracing Context. + * Used for passing OpenTelemetry span context or request IDs for observability. + */ + traceContext: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("OpenTelemetry context or request ID"), + /** + * Tenant Identifier. + * For multi-tenant databases (row-level security or schema-per-tenant). + */ + tenantId: external_exports.string().optional().describe("Tenant Isolation identifier") + }); + DriverCapabilitiesSchema = external_exports.object({ + // ============================================================================ + // Basic CRUD Operations + // ============================================================================ + /** + * Whether the driver supports create operations. + */ + create: external_exports.boolean().default(true).describe("Supports CREATE operations"), + /** + * Whether the driver supports read operations. + */ + read: external_exports.boolean().default(true).describe("Supports READ operations"), + /** + * Whether the driver supports update operations. + */ + update: external_exports.boolean().default(true).describe("Supports UPDATE operations"), + /** + * Whether the driver supports delete operations. + */ + delete: external_exports.boolean().default(true).describe("Supports DELETE operations"), + // ============================================================================ + // Bulk Operations + // ============================================================================ + /** + * Whether the driver supports bulk create operations. + */ + bulkCreate: external_exports.boolean().default(false).describe("Supports bulk CREATE operations"), + /** + * Whether the driver supports bulk update operations. + */ + bulkUpdate: external_exports.boolean().default(false).describe("Supports bulk UPDATE operations"), + /** + * Whether the driver supports bulk delete operations. + */ + bulkDelete: external_exports.boolean().default(false).describe("Supports bulk DELETE operations"), + // ============================================================================ + // Transaction & Connection Management + // ============================================================================ + /** + * Whether the driver supports database transactions. + * If true, beginTransaction, commit, and rollback must be implemented. + */ + transactions: external_exports.boolean().default(false).describe("Supports ACID transactions"), + /** + * Whether the driver supports savepoints within transactions. + */ + savepoints: external_exports.boolean().default(false).describe("Supports transaction savepoints"), + /** + * Supported transaction isolation levels. + */ + isolationLevels: external_exports.array(IsolationLevelEnum).optional().describe("Supported isolation levels"), + // ============================================================================ + // Query Operations + // ============================================================================ + /** + * Whether the driver supports WHERE clause filters. + * If false, ObjectQL will fetch all records and filter in memory. + * + * Example: Memory driver might not support complex filter conditions. + */ + queryFilters: external_exports.boolean().default(true).describe("Supports WHERE clause filtering"), + /** + * Whether the driver supports aggregation functions (COUNT, SUM, AVG, etc.). + * If false, ObjectQL will compute aggregations in memory. + */ + queryAggregations: external_exports.boolean().default(false).describe("Supports GROUP BY and aggregation functions"), + /** + * Whether the driver supports ORDER BY sorting. + * If false, ObjectQL will sort results in memory. + */ + querySorting: external_exports.boolean().default(true).describe("Supports ORDER BY sorting"), + /** + * Whether the driver supports LIMIT/OFFSET pagination. + * If false, ObjectQL will fetch all records and paginate in memory. + */ + queryPagination: external_exports.boolean().default(true).describe("Supports LIMIT/OFFSET pagination"), + /** + * Whether the driver supports window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.). + * If false, ObjectQL will compute window functions in memory. + */ + queryWindowFunctions: external_exports.boolean().default(false).describe("Supports window functions with OVER clause"), + /** + * Whether the driver supports subqueries (nested SELECT statements). + * If false, ObjectQL will execute queries separately and combine results. + */ + querySubqueries: external_exports.boolean().default(false).describe("Supports subqueries"), + /** + * Whether the driver supports Common Table Expressions (WITH clause). + */ + queryCTE: external_exports.boolean().default(false).describe("Supports Common Table Expressions (WITH clause)"), + /** + * Whether the driver supports SQL-style joins. + * If false, ObjectQL will fetch related data separately and join in memory. + */ + joins: external_exports.boolean().default(false).describe("Supports SQL joins"), + // ============================================================================ + // Advanced Features + // ============================================================================ + /** + * Whether the driver supports full-text search. + * If true, text search queries can be pushed to the database. + */ + fullTextSearch: external_exports.boolean().default(false).describe("Supports full-text search"), + /** + * Whether the driver supports JSON querying capabilities. + */ + jsonQuery: external_exports.boolean().default(false).describe("Supports JSON field querying"), + /** + * Whether the driver supports geospatial queries. + */ + geospatialQuery: external_exports.boolean().default(false).describe("Supports geospatial queries"), + /** + * Whether the driver supports streaming large result sets. + */ + streaming: external_exports.boolean().default(false).describe("Supports result streaming (cursors/iterators)"), + /** + * Whether the driver supports JSON field types. + * If false, JSON data will be serialized as strings. + */ + jsonFields: external_exports.boolean().default(false).describe("Supports JSON field types"), + /** + * Whether the driver supports array field types. + * If false, arrays will be stored as JSON strings or in separate tables. + */ + arrayFields: external_exports.boolean().default(false).describe("Supports array field types"), + /** + * Whether the driver supports vector embeddings and similarity search. + * Required for RAG (Retrieval-Augmented Generation) and AI features. + */ + vectorSearch: external_exports.boolean().default(false).describe("Supports vector embeddings and similarity search"), + // ============================================================================ + // Schema Management + // ============================================================================ + /** + * Whether the driver supports automatic schema synchronization. + */ + schemaSync: external_exports.boolean().default(false).describe("Supports automatic schema synchronization"), + /** + * Whether the driver supports batching multiple schema sync operations + * into a single (or fewer) round-trips for the DDL phase. When true, + * the engine may call `syncSchemasBatch()` instead of calling + * `syncSchema()` per object, reducing network round-trips for remote drivers. + */ + batchSchemaSync: external_exports.boolean().default(false).describe("Supports batched schema sync to reduce schema DDL round-trips"), + /** + * Whether the driver supports database migrations. + */ + migrations: external_exports.boolean().default(false).describe("Supports database migrations"), + /** + * Whether the driver supports index management. + */ + indexes: external_exports.boolean().default(false).describe("Supports index creation and management"), + // ============================================================================ + // Performance & Optimization + // ============================================================================ + /** + * Whether the driver supports connection pooling. + */ + connectionPooling: external_exports.boolean().default(false).describe("Supports connection pooling"), + /** + * Whether the driver supports prepared statements. + */ + preparedStatements: external_exports.boolean().default(false).describe("Supports prepared statements (SQL injection prevention)"), + /** + * Whether the driver supports query result caching. + */ + queryCache: external_exports.boolean().default(false).describe("Supports query result caching") + }); + DriverInterfaceSchema = external_exports.object({ + /** + * Driver name (e.g., 'postgresql', 'mongodb', 'rest_api'). + */ + name: external_exports.string().describe("Driver unique name"), + /** + * Driver version. + */ + version: external_exports.string().describe("Driver version"), + /** + * Capabilities descriptor. + */ + supports: DriverCapabilitiesSchema, + // ============================================================================ + // Lifecycle Management + // ============================================================================ + /** + * Initialize connection pool or authenticate. + */ + connect: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.void())).describe("Establish connection"), + /** + * Close connections and cleanup resources. + */ + disconnect: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.void())).describe("Close connection"), + /** + * Check connection health. + * @returns true if healthy, false otherwise. + */ + checkHealth: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.boolean())).describe("Health check"), + /** + * Get Connection Pool Statistics. + * Useful for monitoring database load. + */ + getPoolStats: external_exports.function().input(external_exports.tuple([])).output(external_exports.object({ + total: external_exports.number(), + idle: external_exports.number(), + active: external_exports.number(), + waiting: external_exports.number() + }).optional()).optional().describe("Get connection pool statistics"), + // ============================================================================ + // Raw Execution (Escape Hatch) + // ============================================================================ + /** + * Execute a raw command/query native to the driver. + * Useful for complex reports, stored procedures, or DDL not covered by standard sync. + * + * @param command - The raw command (e.g., SQL string, shell command, or remote API payload). + * @param parameters - Optional array of bound parameters for safe execution (prevention of injection). + * @param options - Driver options (transaction context, timeout). + * @returns Promise resolving to the raw result from the driver. + * + * @example + * // SQL Driver + * await driver.execute('SELECT * FROM complex_view WHERE id = ?', [123]); + * + * // Mongo Driver + * await driver.execute({ aggregate: 'orders', pipeline: [...] }); + */ + execute: external_exports.function().input(external_exports.tuple([external_exports.unknown(), external_exports.array(external_exports.unknown()).optional(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())).describe("Execute raw command"), + // ============================================================================ + // CRUD Operations + // ============================================================================ + /** + * Find multiple records matching the structured query. + * Parsing the QueryAST is the responsibility of the driver implementation. + * + * @param object - The name of the object/table to query (e.g. 'account'). + * @param query - The structured QueryAST (filters, sorts, joins, pagination). + * @param options - Driver options. + * @returns Array of records. + * + * @example + * await driver.find('account', { + * filters: [['status', '=', 'active'], 'and', ['amount', '>', 500]], + * sort: [{ field: 'created_at', order: 'desc' }], + * top: 10 + * }); + * @returns Array of records. + * MUST return `id` as string. MUST NOT return implementation details like `_id`. + */ + find: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))).describe("Find records"), + /** + * Stream records matching the structured query. + * Optimized for large datasets to avoid memory overflow. + * + * @param object - The name of the object. + * @param query - The structured QueryAST. + * @param options - Driver options. + * @returns AsyncIterable/ReadableStream of records. + */ + findStream: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.unknown()).describe("Stream records (AsyncIterable)"), + /** + * Find a single record by query. + * Similar to find(), but returns only the first match or null. + * + * @param object - The name of the object. + * @param query - QueryAST. + * @param options - Driver options. + * @returns The record or null. + * MUST return `id` as string. MUST NOT return implementation details like `_id`. + */ + findOne: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()).nullable())).describe("Find one record"), + /** + * Create a new record. + * + * @param object - The object name. + * @param data - Key-value map of field data. + * @param options - Driver options. + * @returns The created record, including server-generated fields (id, created_at, etc.). + * MUST return `id` as string. MUST NOT return implementation details like `_id`. + */ + create: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Create record"), + /** + * Update an existing record by ID. + * + * @param object - The object name. + * @param id - The unique identifier of the record. + * @param data - The fields to update. + * @param options - Driver options. + * @returns The updated record. + * MUST return `id` as string. MUST NOT return implementation details like `_id`. + */ + update: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.string().or(external_exports.number()), external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Update record"), + /** + * Upsert (Update or Insert) a record. + * + * @param object - The object name. + * @param data - The data to upsert. + * @param conflictKeys - Fields to check for conflict (uniqueness). + * @param options - Driver options. + * @returns The created or updated record. + */ + upsert: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.string()).optional(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Upsert record"), + /** + * Delete a record by ID. + * + * @param object - The object name. + * @param id - The unique identifier of the record. + * @param options - Driver options. + * @returns True if deleted, false if not found. + */ + delete: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.string().or(external_exports.number()), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.boolean())).describe("Delete record"), + /** + * Count records matching a query. + * + * @param object - The object name. + * @param query - Optional filtering criteria. + * @param options - Driver options. + * @returns Total count. + */ + count: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2.optional(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.number())).describe("Count records"), + // ============================================================================ + // Bulk Operations + // ============================================================================ + /** + * Create multiple records in a single batch. + * Optimized for performance. + * + * @param object - The object name. + * @param dataArray - Array of record data. + * @returns Array of created records. + */ + bulkCreate: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))), + /** + * Update multiple records in a single batch. + * + * @param object - The object name. + * @param updates - Array of objects containing {id, data}. + * @returns Array of updated records. + */ + bulkUpdate: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.object({ id: external_exports.string().or(external_exports.number()), data: external_exports.record(external_exports.string(), external_exports.unknown()) })), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))), + /** + * Delete multiple records in a single batch. + * + * @param object - The object name. + * @param ids - Array of record IDs. + */ + bulkDelete: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.string().or(external_exports.number())), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.void())), + /** + * Update multiple records matching a query. + * Direct database push-down. DOES NOT trigger per-record hooks. + * + * @param object - The object name. + * @param query - The filtering criteria. + * @param data - The data to update. + * @returns Count of modified records. + */ + updateMany: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.number())).optional(), + /** + * Delete multiple records matching a query. + * Direct database push-down. DOES NOT trigger per-record hooks. + * + * @param object - The object name. + * @param query - The filtering criteria. + * @returns Count of deleted records. + */ + deleteMany: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.number())).optional(), + // ============================================================================ + // Transaction Management + // ============================================================================ + /** + * Begin a new database transaction. + * @param options - Isolation level and other settings. + * @returns A transaction handle to be passed to subsequent operations via `options.transaction`. + */ + beginTransaction: external_exports.function().input(external_exports.tuple([external_exports.object({ + isolationLevel: IsolationLevelEnum.optional() + }).optional()])).output(external_exports.promise(external_exports.unknown())).describe("Start transaction"), + /** + * Commit the transaction. + * @param transaction - The transaction handle. + */ + commit: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.promise(external_exports.void())).describe("Commit transaction"), + /** + * Rollback the transaction. + * @param transaction - The transaction handle. + */ + rollback: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.promise(external_exports.void())).describe("Rollback transaction"), + // ============================================================================ + // Schema Management + // ============================================================================ + /** + * Synchronize the database schema with the Object definition. + * This is an idempotent operation: it should create tables if missing, + * add columns if missing, and update indexes. + * + * @param object - The object name. + * @param schema - The full Object Schema (fields, indexes, etc). + * @param options - Driver options. + */ + syncSchema: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.unknown(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.void())).describe("Sync object schema to DB"), + /** + * Batch-synchronize multiple object schemas with fewer round-trips. + * + * Drivers that advertise `supports.batchSchemaSync = true` MUST implement + * this method. The engine will call it once with every + * `{ object, schema }` pair instead of calling `syncSchema()` N times. + * + * @param schemas - Array of `{ object: string; schema: unknown }` pairs. + * @param options - Driver options. + */ + syncSchemasBatch: external_exports.function().input(external_exports.tuple([ + external_exports.array(external_exports.object({ object: external_exports.string(), schema: external_exports.unknown() })), + DriverOptionsSchema.optional() + ])).output(external_exports.promise(external_exports.void())).optional().describe("Batch sync multiple schemas in one round-trip"), + /** + * Drop the underlying table or collection for an object. + * WARNING: Destructive operation. + * + * @param object - The object name. + */ + dropTable: external_exports.function().input(external_exports.tuple([external_exports.string(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.void())), + /** + * Analyze query performance. + * Returns execution plan without executing the query (where possible). + * + * @param object - The object name. + * @param query - The query to explain. + * @returns The execution plan details. + */ + explain: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())).optional() + }); + PoolConfigSchema = external_exports.object({ + min: external_exports.number().min(0).default(2).describe("Minimum number of connections in pool"), + max: external_exports.number().min(1).default(10).describe("Maximum number of connections in pool"), + idleTimeoutMillis: external_exports.number().min(0).default(3e4).describe("Time in ms before idle connection is closed"), + connectionTimeoutMillis: external_exports.number().min(0).default(5e3).describe("Time in ms to wait for available connection") + }); + DriverConfigSchema = external_exports.object({ + name: external_exports.string().describe("Driver instance name"), + type: external_exports.enum(["sql", "nosql", "cache", "search", "graph", "timeseries"]).describe("Driver type category"), + capabilities: DriverCapabilitiesSchema.describe("Driver capability flags"), + connectionString: external_exports.string().optional().describe("Database connection string (driver-specific format)"), + poolConfig: PoolConfigSchema.optional().describe("Connection pool configuration") + }); + SQLDialectSchema = external_exports.enum([ + "postgresql", + "mysql", + "sqlite", + "mssql", + "oracle", + "mariadb" + ]); + DataTypeMappingSchema = external_exports.object({ + text: external_exports.string().describe("SQL type for text fields (e.g., VARCHAR, TEXT)"), + number: external_exports.string().describe("SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)"), + boolean: external_exports.string().describe("SQL type for boolean fields (e.g., BOOLEAN, BIT)"), + date: external_exports.string().describe("SQL type for date fields (e.g., DATE)"), + datetime: external_exports.string().describe("SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)"), + json: external_exports.string().optional().describe("SQL type for JSON fields (e.g., JSON, JSONB)"), + uuid: external_exports.string().optional().describe("SQL type for UUID fields (e.g., UUID, CHAR(36))"), + binary: external_exports.string().optional().describe("SQL type for binary fields (e.g., BLOB, BYTEA)") + }); + SSLConfigSchema = external_exports.object({ + rejectUnauthorized: external_exports.boolean().default(true).describe("Reject connections with invalid certificates"), + ca: external_exports.string().optional().describe("CA certificate file path or content"), + cert: external_exports.string().optional().describe("Client certificate file path or content"), + key: external_exports.string().optional().describe("Client private key file path or content") + }).refine((data) => { + const hasCert = data.cert !== void 0; + const hasKey = data.key !== void 0; + return hasCert === hasKey; + }, { + message: "Client certificate (cert) and private key (key) must be provided together" + }); + SQLDriverConfigSchema = DriverConfigSchema.extend({ + type: external_exports.literal("sql").describe('Driver type must be "sql"'), + dialect: SQLDialectSchema.describe("SQL database dialect"), + dataTypeMapping: DataTypeMappingSchema.describe("SQL data type mapping configuration"), + ssl: external_exports.boolean().default(false).describe("Enable SSL/TLS connection"), + sslConfig: SSLConfigSchema.optional().describe("SSL/TLS configuration (required when ssl is true)") + }).refine((data) => { + if (data.ssl && !data.sslConfig) { + return false; + } + return true; + }, { + message: "sslConfig is required when ssl is true" + }); + SQLiteDataTypeMappingDefaults = { + text: "TEXT", + number: "REAL", + boolean: "INTEGER", + date: "TEXT", + datetime: "TEXT", + json: "TEXT", + uuid: "TEXT", + binary: "BLOB" + }; + SQLiteAlterTableLimitations = { + /** SQLite supports ADD COLUMN */ + supportsAddColumn: true, + /** SQLite supports RENAME COLUMN (3.25.0+) */ + supportsRenameColumn: true, + /** SQLite supports DROP COLUMN (3.35.0+) */ + supportsDropColumn: true, + /** SQLite does NOT support MODIFY/ALTER COLUMN type */ + supportsModifyColumn: false, + /** SQLite does NOT support adding constraints to existing columns */ + supportsAddConstraint: false, + /** + * When an unsupported alteration is needed, the migration planner + * must use the 12-step table rebuild strategy: + * 1. CREATE new table with desired schema + * 2. Copy data from old table + * 3. DROP old table + * 4. RENAME new table to old name + */ + rebuildStrategy: "create_copy_drop_rename" + }; + NoSQLDatabaseTypeSchema = external_exports.enum([ + "mongodb", + "couchdb", + "dynamodb", + "cassandra", + "redis", + "elasticsearch", + "neo4j", + "orientdb" + ]); + NoSQLOperationTypeSchema = external_exports.enum([ + "find", + // Query documents/records + "findOne", + // Get single document + "insert", + // Insert document + "update", + // Update document + "delete", + // Delete document + "aggregate", + // Aggregation pipeline + "mapReduce", + // MapReduce operation + "count", + // Count documents + "distinct", + // Get distinct values + "createIndex", + // Create index + "dropIndex" + // Drop index + ]); + ConsistencyLevelSchema = external_exports.enum([ + "all", + "quorum", + "one", + "local_quorum", + "each_quorum", + "eventual" + ]); + NoSQLIndexTypeSchema = external_exports.enum([ + "single", + // Single field index + "compound", + // Multiple fields index + "unique", + // Unique constraint + "text", + // Full-text search index + "geospatial", + // Geospatial index (2d, 2dsphere) + "hashed", + // Hashed index for sharding + "ttl", + // Time-to-live index (auto-deletion) + "sparse" + // Sparse index (only indexed documents with field) + ]); + ShardingConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable sharding"), + shardKey: external_exports.string().optional().describe("Field to use as shard key"), + shardingStrategy: external_exports.enum(["hash", "range", "zone"]).optional().describe("Sharding strategy"), + numShards: external_exports.number().int().positive().optional().describe("Number of shards") + }); + ReplicationConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable replication"), + replicaSetName: external_exports.string().optional().describe("Replica set name"), + replicas: external_exports.number().int().positive().optional().describe("Number of replicas"), + readPreference: external_exports.enum(["primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"]).optional().describe("Read preference for replica set"), + writeConcern: external_exports.enum(["majority", "acknowledged", "unacknowledged"]).optional().describe("Write concern level") + }); + DocumentSchemaValidationSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable schema validation"), + validationLevel: external_exports.enum(["strict", "moderate", "off"]).optional().describe("Validation strictness"), + validationAction: external_exports.enum(["error", "warn"]).optional().describe("Action on validation failure"), + jsonSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON Schema for validation") + }); + NoSQLDataTypeMappingSchema = external_exports.object({ + text: external_exports.string().describe("NoSQL type for text fields"), + number: external_exports.string().describe("NoSQL type for number fields"), + boolean: external_exports.string().describe("NoSQL type for boolean fields"), + date: external_exports.string().describe("NoSQL type for date fields"), + datetime: external_exports.string().describe("NoSQL type for datetime fields"), + json: external_exports.string().optional().describe("NoSQL type for JSON/object fields"), + uuid: external_exports.string().optional().describe("NoSQL type for UUID fields"), + binary: external_exports.string().optional().describe("NoSQL type for binary fields"), + array: external_exports.string().optional().describe("NoSQL type for array fields"), + objectId: external_exports.string().optional().describe("NoSQL type for ObjectID fields (MongoDB)"), + geopoint: external_exports.string().optional().describe("NoSQL type for geospatial point fields") + }); + NoSQLDriverConfigSchema = DriverConfigSchema.extend({ + type: external_exports.literal("nosql").describe('Driver type must be "nosql"'), + databaseType: NoSQLDatabaseTypeSchema.describe("Specific NoSQL database type"), + dataTypeMapping: NoSQLDataTypeMappingSchema.describe("NoSQL data type mapping configuration"), + /** + * Consistency level for reads/writes + */ + consistency: ConsistencyLevelSchema.optional().describe("Consistency level for operations"), + /** + * Replication configuration + */ + replication: ReplicationConfigSchema.optional().describe("Replication configuration"), + /** + * Sharding configuration + */ + sharding: ShardingConfigSchema.optional().describe("Sharding configuration"), + /** + * Schema validation rules (for document databases) + */ + schemaValidation: DocumentSchemaValidationSchema.optional().describe("Document schema validation"), + /** + * AWS Region (for DynamoDB, DocumentDB, etc.) + */ + region: external_exports.string().optional().describe("AWS region (for managed NoSQL services)"), + /** + * AWS Access Key ID (for DynamoDB, DocumentDB, etc.) + */ + accessKeyId: external_exports.string().optional().describe("AWS access key ID"), + /** + * AWS Secret Access Key (for DynamoDB, DocumentDB, etc.) + */ + secretAccessKey: external_exports.string().optional().describe("AWS secret access key"), + /** + * Time-to-live (TTL) field name + * Automatically delete documents after a specified time + */ + ttlField: external_exports.string().optional().describe("Field name for TTL (auto-deletion)"), + /** + * Maximum document size in bytes + */ + maxDocumentSize: external_exports.number().int().positive().optional().describe("Maximum document size in bytes"), + /** + * Collection/Table name prefix + * Useful for multi-tenancy or environment isolation + */ + collectionPrefix: external_exports.string().optional().describe("Prefix for collection/table names") + }); + NoSQLQueryOptionsSchema = external_exports.object({ + /** + * Consistency level for this query + */ + consistency: ConsistencyLevelSchema.optional().describe("Consistency level override"), + /** + * Read from secondary replicas + */ + readFromSecondary: external_exports.boolean().optional().describe("Allow reading from secondary replicas"), + /** + * Projection (fields to include/exclude) + */ + projection: external_exports.record(external_exports.string(), external_exports.union([external_exports.literal(0), external_exports.literal(1)])).optional().describe("Field projection"), + /** + * Query timeout in milliseconds + */ + timeout: external_exports.number().int().positive().optional().describe("Query timeout (ms)"), + /** + * Use cursor for large result sets + */ + useCursor: external_exports.boolean().optional().describe("Use cursor instead of loading all results"), + /** + * Batch size for cursor iteration + */ + batchSize: external_exports.number().int().positive().optional().describe("Cursor batch size"), + /** + * Enable query profiling + */ + profile: external_exports.boolean().optional().describe("Enable query profiling"), + /** + * Use hinted index + */ + hint: external_exports.string().optional().describe("Index hint for query optimization") + }); + AggregationStageSchema = external_exports.object({ + /** + * Stage operator (e.g., $match, $group, $sort, $project) + */ + operator: external_exports.string().describe("Aggregation operator (e.g., $match, $group, $sort)"), + /** + * Stage parameters/options + */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Stage-specific options") + }); + AggregationPipelineSchema = external_exports.object({ + /** + * Collection/Table to aggregate + */ + collection: external_exports.string().describe("Collection/table name"), + /** + * Pipeline stages + */ + stages: external_exports.array(AggregationStageSchema).describe("Aggregation pipeline stages"), + /** + * Additional options + */ + options: NoSQLQueryOptionsSchema.optional().describe("Query options") + }); + NoSQLIndexSchema = external_exports.object({ + /** + * Index name + */ + name: external_exports.string().describe("Index name"), + /** + * Index type + */ + type: NoSQLIndexTypeSchema.describe("Index type"), + /** + * Fields to index + * For compound indexes, order matters + */ + fields: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name"), + order: external_exports.enum(["asc", "desc", "text", "2dsphere"]).optional().describe("Index order or type") + })).describe("Fields to index"), + /** + * Unique constraint + */ + unique: external_exports.boolean().default(false).describe("Enforce uniqueness"), + /** + * Sparse index (only index documents with the field) + */ + sparse: external_exports.boolean().default(false).describe("Sparse index"), + /** + * TTL in seconds (for TTL indexes) + */ + expireAfterSeconds: external_exports.number().int().positive().optional().describe("TTL in seconds"), + /** + * Partial index filter + */ + partialFilterExpression: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Partial index filter"), + /** + * Background index creation + */ + background: external_exports.boolean().default(false).describe("Create index in background") + }); + NoSQLTransactionOptionsSchema = external_exports.object({ + /** + * Read concern level + */ + readConcern: external_exports.enum(["local", "majority", "linearizable", "snapshot"]).optional().describe("Read concern level"), + /** + * Write concern level + */ + writeConcern: external_exports.enum(["majority", "acknowledged", "unacknowledged"]).optional().describe("Write concern level"), + /** + * Read preference + */ + readPreference: external_exports.enum(["primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"]).optional().describe("Read preference"), + /** + * Transaction timeout in milliseconds + */ + maxCommitTimeMS: external_exports.number().int().positive().optional().describe("Transaction commit timeout (ms)") + }); + DatasetMode2 = external_exports.enum([ + "insert", + // Try to insert, fail on duplicate + "update", + // Only update found records, ignore new + "upsert", + // Create new or Update existing (Standard) + "replace", + // Delete ALL records in object then insert (Dangerous - use for cache tables) + "ignore" + // Try to insert, silently skip duplicates + ]); + DatasetSchema2 = external_exports.object({ + /** + * Target Object + * The machine name of the object to populate. + */ + object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target Object Name"), + /** + * Idempotency Key (The "Upsert" Key) + * The field used to check if a record already exists. + * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'. + * Standard: 'id' is rarely used for portable seed data — prefer natural keys. + */ + externalId: external_exports.string().default("name").describe("Field match for uniqueness check"), + /** + * Import Strategy + */ + mode: DatasetMode2.default("upsert").describe("Conflict resolution strategy"), + /** + * Environment Scope + * - 'all': Always load + * - 'dev': Only for development/demo + * - 'test': Only for CI/CD tests + */ + env: external_exports.array(external_exports.enum(["prod", "dev", "test"])).default(["prod", "dev", "test"]).describe("Applicable environments"), + /** + * The Payload + * Array of raw JSON objects matching the Object Schema. + */ + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Data records") + }); + ReferenceResolutionSchema = external_exports.object({ + /** The field name on the source object (e.g., 'account_id') */ + field: external_exports.string().describe("Source field name containing the reference value"), + /** The target object being referenced (e.g., 'account') */ + targetObject: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target object name (snake_case)"), + /** + * The field on the target object used to match the reference value. + * Defaults to the target object's externalId (usually 'name'). + */ + targetField: external_exports.string().default("name").describe("Field on target object used for matching"), + /** The field type that triggered this resolution (lookup or master_detail) */ + fieldType: external_exports.enum(["lookup", "master_detail"]).describe("Relationship field type") + }).describe("Describes how a field reference is resolved during seed loading"); + ObjectDependencyNodeSchema = external_exports.object({ + /** Object machine name */ + object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Object name (snake_case)"), + /** + * Objects that this object depends on (via lookup/master_detail fields). + * These must be loaded before this object. + */ + dependsOn: external_exports.array(external_exports.string()).describe("Objects this object depends on"), + /** + * Field-level reference details for each dependency. + * Maps field name → reference resolution info. + */ + references: external_exports.array(ReferenceResolutionSchema).describe("Field-level reference details") + }).describe("Object node in the seed data dependency graph"); + ObjectDependencyGraphSchema = external_exports.object({ + /** All object nodes in the graph */ + nodes: external_exports.array(ObjectDependencyNodeSchema).describe("All objects in the dependency graph"), + /** + * Topologically sorted object names for insertion order. + * Parent objects appear before child objects. + */ + insertOrder: external_exports.array(external_exports.string()).describe("Topologically sorted insert order"), + /** + * Circular dependency chains detected in the graph. + * Each chain is an array of object names forming a cycle. + * When present, the loader must use a multi-pass strategy. + * + * @example [['project', 'task', 'project']] + */ + circularDependencies: external_exports.array(external_exports.array(external_exports.string())).default([]).describe('Circular dependency chains (e.g., [["a", "b", "a"]])') + }).describe("Complete object dependency graph for seed data loading"); + ReferenceResolutionErrorSchema = external_exports.object({ + /** The source object containing the broken reference */ + sourceObject: external_exports.string().describe("Object with the broken reference"), + /** The field containing the unresolved value */ + field: external_exports.string().describe("Field name with unresolved reference"), + /** The target object that was searched */ + targetObject: external_exports.string().describe("Target object searched for the reference"), + /** The externalId field used for matching on the target object */ + targetField: external_exports.string().describe("ExternalId field used for matching"), + /** The value that could not be resolved */ + attemptedValue: external_exports.unknown().describe("Value that failed to resolve"), + /** The index of the record in the dataset's records array */ + recordIndex: external_exports.number().int().min(0).describe("Index of the record in the dataset"), + /** Human-readable error message */ + message: external_exports.string().describe("Human-readable error description") + }).describe("Actionable error for a failed reference resolution"); + SeedLoaderConfigSchema = external_exports.object({ + /** + * Dry-run mode: validate all references without writing data. + * Surfaces broken references before any mutations occur. + * @default false + */ + dryRun: external_exports.boolean().default(false).describe("Validate references without writing data"), + /** + * Whether to halt on the first reference resolution error. + * When false, collects all errors and continues loading. + * @default false + */ + haltOnError: external_exports.boolean().default(false).describe("Stop on first reference resolution error"), + /** + * Enable multi-pass loading for circular dependencies. + * Pass 1: Insert records with null for circular references. + * Pass 2: Update records to fill deferred references. + * @default true + */ + multiPass: external_exports.boolean().default(true).describe("Enable multi-pass loading for circular dependencies"), + /** + * Default dataset mode when not specified per-dataset. + * @default 'upsert' + */ + defaultMode: DatasetMode2.default("upsert").describe("Default conflict resolution strategy"), + /** + * Maximum number of records to process in a single batch. + * Controls memory usage for large datasets. + * @default 1000 + */ + batchSize: external_exports.number().int().min(1).default(1e3).describe("Maximum records per batch insert/upsert"), + /** + * Whether to wrap the entire load operation in a transaction. + * When true, all-or-nothing semantics apply. + * @default false + */ + transaction: external_exports.boolean().default(false).describe("Wrap entire load in a transaction (all-or-nothing)"), + /** + * Environment filter. Only datasets matching this environment are loaded. + * When not specified, all datasets are loaded regardless of env scope. + */ + env: external_exports.enum(["prod", "dev", "test"]).optional().describe("Only load datasets matching this environment") + }).describe("Seed data loader configuration"); + DatasetLoadResultSchema = external_exports.object({ + /** Target object name */ + object: external_exports.string().describe("Object that was loaded"), + /** Import mode used */ + mode: DatasetMode2.describe("Import mode used"), + /** Number of records successfully inserted */ + inserted: external_exports.number().int().min(0).describe("Records inserted"), + /** Number of records successfully updated (upsert matched existing) */ + updated: external_exports.number().int().min(0).describe("Records updated"), + /** Number of records skipped (mode: ignore, or already exists) */ + skipped: external_exports.number().int().min(0).describe("Records skipped"), + /** Number of records with errors */ + errored: external_exports.number().int().min(0).describe("Records with errors"), + /** Total records in the dataset */ + total: external_exports.number().int().min(0).describe("Total records in dataset"), + /** Number of references resolved via externalId */ + referencesResolved: external_exports.number().int().min(0).describe("References resolved via externalId"), + /** Number of references deferred to pass 2 (circular dependencies) */ + referencesDeferred: external_exports.number().int().min(0).describe("References deferred to second pass"), + /** Reference resolution errors for this object */ + errors: external_exports.array(ReferenceResolutionErrorSchema).default([]).describe("Reference resolution errors") + }).describe("Result of loading a single dataset"); + SeedLoaderResultSchema = external_exports.object({ + /** Whether the overall load operation succeeded */ + success: external_exports.boolean().describe("Overall success status"), + /** Was this a dry-run (validation only, no writes)? */ + dryRun: external_exports.boolean().describe("Whether this was a dry-run"), + /** The dependency graph used for ordering */ + dependencyGraph: ObjectDependencyGraphSchema.describe("Object dependency graph"), + /** Per-object load results, in the order they were processed */ + results: external_exports.array(DatasetLoadResultSchema).describe("Per-object load results"), + /** All reference resolution errors across all objects */ + errors: external_exports.array(ReferenceResolutionErrorSchema).describe("All reference resolution errors"), + /** Summary statistics */ + summary: external_exports.object({ + /** Total objects processed */ + objectsProcessed: external_exports.number().int().min(0).describe("Total objects processed"), + /** Total records across all objects */ + totalRecords: external_exports.number().int().min(0).describe("Total records across all objects"), + /** Total records inserted */ + totalInserted: external_exports.number().int().min(0).describe("Total records inserted"), + /** Total records updated */ + totalUpdated: external_exports.number().int().min(0).describe("Total records updated"), + /** Total records skipped */ + totalSkipped: external_exports.number().int().min(0).describe("Total records skipped"), + /** Total records with errors */ + totalErrored: external_exports.number().int().min(0).describe("Total records with errors"), + /** Total references resolved via externalId */ + totalReferencesResolved: external_exports.number().int().min(0).describe("Total references resolved"), + /** Total references deferred to second pass */ + totalReferencesDeferred: external_exports.number().int().min(0).describe("Total references deferred"), + /** Number of circular dependency chains detected */ + circularDependencyCount: external_exports.number().int().min(0).describe("Circular dependency chains detected"), + /** Duration of the load operation in milliseconds */ + durationMs: external_exports.number().min(0).describe("Load duration in milliseconds") + }).describe("Summary statistics") + }).describe("Complete seed loader result"); + SeedLoaderRequestSchema = external_exports.object({ + /** Datasets to load */ + datasets: external_exports.array(DatasetSchema2).min(1).describe("Datasets to load"), + /** Loader configuration */ + config: external_exports.preprocess((val) => val ?? {}, SeedLoaderConfigSchema).describe("Loader configuration") + }).describe("Seed loader request with datasets and configuration"); + DocumentVersionSchema = external_exports.object({ + /** + * Sequential version number (increments with each new version) + */ + versionNumber: external_exports.number().describe("Version number"), + /** + * Timestamp when this version was created (Unix milliseconds) + */ + createdAt: external_exports.number().describe("Creation timestamp"), + /** + * User ID who created this version + */ + createdBy: external_exports.string().describe("Creator user ID"), + /** + * File size in bytes + */ + size: external_exports.number().describe("File size in bytes"), + /** + * Checksum/hash of the file content (for integrity verification) + */ + checksum: external_exports.string().describe("File checksum"), + /** + * URL to download this specific version + */ + downloadUrl: external_exports.string().url().describe("Download URL"), + /** + * Whether this is the latest version + * @default false + */ + isLatest: external_exports.boolean().optional().default(false).describe("Is latest version") + }); + DocumentTemplateSchema = external_exports.object({ + /** + * Unique identifier for the template + */ + id: external_exports.string().describe("Template ID"), + /** + * Human-readable name of the template + */ + name: external_exports.string().describe("Template name"), + /** + * Optional description of the template's purpose + */ + description: external_exports.string().optional().describe("Template description"), + /** + * URL to the template file + */ + fileUrl: external_exports.string().url().describe("Template file URL"), + /** + * MIME type of the template file + */ + fileType: external_exports.string().describe("File MIME type"), + /** + * List of dynamic placeholders in the template + */ + placeholders: external_exports.array(external_exports.object({ + /** + * Placeholder identifier (used in template) + */ + key: external_exports.string().describe("Placeholder key"), + /** + * Human-readable label for the placeholder + */ + label: external_exports.string().describe("Placeholder label"), + /** + * Data type of the placeholder value + */ + type: external_exports.enum(["text", "number", "date", "image"]).describe("Placeholder type"), + /** + * Whether this placeholder must be filled + * @default false + */ + required: external_exports.boolean().optional().default(false).describe("Is required") + })).describe("Template placeholders") + }); + ESignatureConfigSchema = external_exports.object({ + /** + * E-signature service provider + */ + provider: external_exports.enum(["docusign", "adobe-sign", "hellosign", "custom"]).describe("E-signature provider"), + /** + * Whether e-signature is enabled for this document + * @default false + */ + enabled: external_exports.boolean().optional().default(false).describe("E-signature enabled"), + /** + * List of signers in signing order + */ + signers: external_exports.array(external_exports.object({ + /** + * Signer's email address + */ + email: external_exports.string().email().describe("Signer email"), + /** + * Signer's full name + */ + name: external_exports.string().describe("Signer name"), + /** + * Signer's role in the document + */ + role: external_exports.string().describe("Signer role"), + /** + * Signing order (lower numbers sign first) + */ + order: external_exports.number().describe("Signing order") + })).describe("Document signers"), + /** + * Days until signature request expires + * @default 30 + */ + expirationDays: external_exports.number().optional().default(30).describe("Expiration days"), + /** + * Days between reminder emails + * @default 7 + */ + reminderDays: external_exports.number().optional().default(7).describe("Reminder interval days") + }); + DocumentSchema = external_exports.object({ + /** + * Unique document identifier + */ + id: external_exports.string().describe("Document ID"), + /** + * Document name + */ + name: external_exports.string().describe("Document name"), + /** + * Optional document description + */ + description: external_exports.string().optional().describe("Document description"), + /** + * MIME type of the document + */ + fileType: external_exports.string().describe("File MIME type"), + /** + * File size in bytes + */ + fileSize: external_exports.number().describe("File size in bytes"), + /** + * Document category for organization + */ + category: external_exports.string().optional().describe("Document category"), + /** + * Tags for searchability and organization + */ + tags: external_exports.array(external_exports.string()).optional().describe("Document tags"), + /** + * Version control configuration + */ + versioning: external_exports.object({ + /** + * Whether versioning is enabled + */ + enabled: external_exports.boolean().describe("Versioning enabled"), + /** + * List of all document versions + */ + versions: external_exports.array(DocumentVersionSchema).describe("Version history"), + /** + * Current major version number + */ + majorVersion: external_exports.number().describe("Major version"), + /** + * Current minor version number + */ + minorVersion: external_exports.number().describe("Minor version") + }).optional().describe("Version control"), + /** + * Template configuration (if document is generated from template) + */ + template: DocumentTemplateSchema.optional().describe("Document template"), + /** + * E-signature configuration + */ + eSignature: ESignatureConfigSchema.optional().describe("E-signature config"), + /** + * Access control settings + */ + access: external_exports.object({ + /** + * Whether document is publicly accessible + * @default false + */ + isPublic: external_exports.boolean().optional().default(false).describe("Public access"), + /** + * List of user/team IDs with access + */ + sharedWith: external_exports.array(external_exports.string()).optional().describe("Shared with"), + /** + * Timestamp when access expires (Unix milliseconds) + */ + expiresAt: external_exports.number().optional().describe("Access expiration") + }).optional().describe("Access control"), + /** + * Custom metadata fields + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") + }); + TransformTypeSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("constant"), + value: external_exports.unknown().describe("Constant value to use") + }).describe("Set a constant value"), + external_exports.object({ + type: external_exports.literal("cast"), + targetType: external_exports.enum(["string", "number", "boolean", "date"]).describe("Target data type") + }).describe("Cast to a specific data type"), + external_exports.object({ + type: external_exports.literal("lookup"), + table: external_exports.string().describe("Lookup table name"), + keyField: external_exports.string().describe("Field to match on"), + valueField: external_exports.string().describe("Field to retrieve") + }).describe("Lookup value from another table"), + external_exports.object({ + type: external_exports.literal("javascript"), + expression: external_exports.string().describe('JavaScript expression (e.g., "value.toUpperCase()")') + }).describe("Custom JavaScript transformation"), + external_exports.object({ + type: external_exports.literal("map"), + mappings: external_exports.record(external_exports.string(), external_exports.unknown()).describe('Value mappings (e.g., {"Active": "active"})') + }).describe("Map values using a dictionary") + ]); + FieldMappingSchema2 = external_exports.object({ + /** + * Source field name + */ + source: external_exports.string().describe("Source field name"), + /** + * Target field name (should be snake_case for ObjectStack) + */ + target: external_exports.string().describe("Target field name"), + /** + * Transformation to apply + */ + transform: TransformTypeSchema.optional().describe("Transformation to apply"), + /** + * Default value if source is null/undefined + */ + defaultValue: external_exports.unknown().optional().describe("Default if source is null/undefined") + }); + ExternalDataSourceSchema = external_exports.object({ + /** + * Unique identifier for the external data source + */ + id: external_exports.string().describe("Data source ID"), + /** + * Human-readable name of the data source + */ + name: external_exports.string().describe("Data source name"), + /** + * Protocol type for connecting to the data source + */ + type: external_exports.enum(["odata", "rest-api", "graphql", "custom"]).describe("Protocol type"), + /** + * Base URL endpoint for the external system + */ + endpoint: external_exports.string().url().describe("API endpoint URL"), + /** + * Authentication configuration + */ + authentication: external_exports.object({ + /** + * Authentication method + */ + type: external_exports.enum(["oauth2", "api-key", "basic", "none"]).describe("Auth type"), + /** + * Authentication-specific configuration + * Structure varies based on auth type + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Auth configuration") + }).describe("Authentication") + }); + ExternalFieldMappingSchema = FieldMappingSchema2.extend({ + /** + * Field data type + */ + type: external_exports.string().optional().describe("Field type"), + /** + * Whether the field is read-only + * @default true + */ + readonly: external_exports.boolean().optional().default(true).describe("Read-only field") + }); + ExternalLookupSchema = external_exports.object({ + /** + * Name of the field that uses external lookup + */ + fieldName: external_exports.string().describe("Field name"), + /** + * External data source configuration + */ + dataSource: ExternalDataSourceSchema.describe("External data source"), + /** + * Query configuration for fetching external data + */ + query: external_exports.object({ + /** + * API endpoint path (relative to base endpoint) + */ + endpoint: external_exports.string().describe("Query endpoint path"), + /** + * HTTP method for the query + * @default 'GET' + */ + method: external_exports.enum(["GET", "POST"]).optional().default("GET").describe("HTTP method"), + /** + * Query parameters or request body + */ + parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters") + }).describe("Query configuration"), + /** + * Mapping between external and local fields + */ + fieldMappings: external_exports.array(ExternalFieldMappingSchema).describe("Field mappings"), + /** + * Cache configuration for external data + */ + caching: external_exports.object({ + /** + * Whether caching is enabled + * @default true + */ + enabled: external_exports.boolean().optional().default(true).describe("Cache enabled"), + /** + * Time-to-live in seconds + * @default 300 + */ + ttl: external_exports.number().optional().default(300).describe("Cache TTL (seconds)"), + /** + * Cache eviction strategy + * @default 'ttl' + */ + strategy: external_exports.enum(["lru", "lfu", "ttl"]).optional().default("ttl").describe("Cache strategy") + }).optional().describe("Caching configuration"), + /** + * Fallback behavior when external system is unavailable + */ + fallback: external_exports.object({ + /** + * Whether fallback is enabled + * @default true + */ + enabled: external_exports.boolean().optional().default(true).describe("Fallback enabled"), + /** + * Default value to use when external system fails + */ + defaultValue: external_exports.unknown().optional().describe("Default fallback value"), + /** + * Whether to show error message to user + * @default true + */ + showError: external_exports.boolean().optional().default(true).describe("Show error to user") + }).optional().describe("Fallback configuration"), + /** + * Rate limiting to prevent overwhelming external system + */ + rateLimit: external_exports.object({ + /** + * Maximum requests per second + */ + requestsPerSecond: external_exports.number().describe("Requests per second limit"), + /** + * Burst size for handling spikes + */ + burstSize: external_exports.number().optional().describe("Burst size") + }).optional().describe("Rate limiting"), + /** + * Retry configuration with exponential backoff + * + * @example + * ```json + * { + * "maxRetries": 3, + * "initialDelayMs": 1000, + * "maxDelayMs": 30000, + * "backoffMultiplier": 2, + * "retryableStatusCodes": [429, 500, 502, 503, 504] + * } + * ``` + */ + retry: external_exports.object({ + /** Maximum number of retry attempts */ + maxRetries: external_exports.number().min(0).default(3).describe("Maximum retry attempts"), + /** Initial delay before first retry (ms) */ + initialDelayMs: external_exports.number().default(1e3).describe("Initial retry delay in milliseconds"), + /** Maximum delay between retries (ms) */ + maxDelayMs: external_exports.number().default(3e4).describe("Maximum retry delay in milliseconds"), + /** Backoff multiplier for exponential backoff */ + backoffMultiplier: external_exports.number().default(2).describe("Exponential backoff multiplier"), + /** HTTP status codes that trigger a retry */ + retryableStatusCodes: external_exports.array(external_exports.number()).default([429, 500, 502, 503, 504]).describe("HTTP status codes that are retryable") + }).optional().describe("Retry configuration with exponential backoff"), + /** + * Request/response transformation pipeline + * + * Allows transforming request parameters and response data + * before they are processed by the external lookup system. + */ + transform: external_exports.object({ + /** Transform request parameters before sending */ + request: external_exports.object({ + /** Header transformations (key-value additions) */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Additional request headers"), + /** Query parameter transformations */ + queryParams: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Additional query parameters") + }).optional().describe("Request transformation"), + /** Transform response data after receiving */ + response: external_exports.object({ + /** JSONPath expression to extract data from response */ + dataPath: external_exports.string().optional().describe('JSONPath to extract data (e.g., "$.data.results")'), + /** JSONPath expression to extract total count for pagination */ + totalPath: external_exports.string().optional().describe('JSONPath to extract total count (e.g., "$.meta.total")') + }).optional().describe("Response transformation") + }).optional().describe("Request/response transformation pipeline"), + /** Pagination support for external data sources */ + pagination: external_exports.object({ + /** Pagination type */ + type: external_exports.enum(["offset", "cursor", "page"]).default("offset").describe("Pagination type"), + /** Page size */ + pageSize: external_exports.number().default(100).describe("Items per page"), + /** Maximum pages to fetch */ + maxPages: external_exports.number().optional().describe("Maximum number of pages to fetch") + }).optional().describe("Pagination configuration for external data") + }); + DriverType = external_exports.string().describe("Underlying driver identifier"); + DriverDefinitionSchema = external_exports.object({ + id: external_exports.string().describe('Unique driver identifier (e.g. "postgres")'), + label: external_exports.string().describe('Display label (e.g. "PostgreSQL")'), + description: external_exports.string().optional(), + icon: external_exports.string().optional(), + /** + * Configuration Schema (JSON Schema) + * Describes the structure of the `config` object needed for this driver. + * Used by the UI to generate the connection form. + */ + configSchema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema for connection configuration"), + /** + * Default Capabilities + * What this driver supports out-of-the-box. + */ + capabilities: external_exports.lazy(() => DatasourceCapabilities).optional() + }); + DatasourceCapabilities = external_exports.object({ + // ============================================================================ + // Transaction & Connection Management + // ============================================================================ + /** Can handle ACID transactions? */ + transactions: external_exports.boolean().default(false), + // ============================================================================ + // Query Operations + // ============================================================================ + /** Can execute WHERE clause filters natively? */ + queryFilters: external_exports.boolean().default(false), + /** Can perform aggregation (group by, sum, avg)? */ + queryAggregations: external_exports.boolean().default(false), + /** Can perform ORDER BY sorting? */ + querySorting: external_exports.boolean().default(false), + /** Can perform LIMIT/OFFSET pagination? */ + queryPagination: external_exports.boolean().default(false), + /** Can perform window functions? */ + queryWindowFunctions: external_exports.boolean().default(false), + /** Can perform subqueries? */ + querySubqueries: external_exports.boolean().default(false), + /** Can execute SQL-like joins natively? */ + joins: external_exports.boolean().default(false), + // ============================================================================ + // Advanced Features + // ============================================================================ + /** Can perform full-text search? */ + fullTextSearch: external_exports.boolean().default(false), + /** Is read-only? */ + readOnly: external_exports.boolean().default(false), + /** Is scheme-less (needs schema inference)? */ + dynamicSchema: external_exports.boolean().default(false) + }); + DatasourceSchema = external_exports.object({ + /** Machine Name */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique datasource identifier"), + /** Human Label */ + label: external_exports.string().optional().describe("Display label"), + /** Driver */ + driver: DriverType.describe("Underlying driver type"), + /** + * Connection Configuration + * Specific to the driver (e.g., host, port, user, password, bucket, etc.) + * Stored securely (passwords usually interpolated from ENV). + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Driver specific configuration"), + /** + * Connection Pool Configuration + * Standard connection pooling settings. + */ + pool: external_exports.object({ + min: external_exports.number().default(0).describe("Minimum connections"), + max: external_exports.number().default(10).describe("Maximum connections"), + idleTimeoutMillis: external_exports.number().default(3e4).describe("Idle timeout"), + connectionTimeoutMillis: external_exports.number().default(3e3).describe("Connection establishment timeout") + }).optional().describe("Connection pool settings"), + /** + * Read Replicas + * Optional list of duplicate configurations for read-only operations. + * Useful for scaling read throughput. + */ + readReplicas: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Read-only replica configurations"), + /** + * Capability Overrides + * Manually override what the driver claims to support. + */ + capabilities: DatasourceCapabilities.optional().describe("Capability overrides"), + /** Health Check */ + healthCheck: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable health check endpoint"), + intervalMs: external_exports.number().default(3e4).describe("Health check interval in milliseconds"), + timeoutMs: external_exports.number().default(5e3).describe("Health check timeout in milliseconds") + }).optional().describe("Datasource health check configuration"), + /** SSL/TLS Configuration */ + ssl: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable SSL/TLS for database connection"), + rejectUnauthorized: external_exports.boolean().default(true).describe("Reject connections with invalid/self-signed certificates"), + ca: external_exports.string().optional().describe("CA certificate (PEM format or path to file)"), + cert: external_exports.string().optional().describe("Client certificate (PEM format or path to file)"), + key: external_exports.string().optional().describe("Client private key (PEM format or path to file)") + }).optional().describe("SSL/TLS configuration for secure database connections"), + /** Retry Policy */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().default(3).describe("Maximum number of retry attempts"), + baseDelayMs: external_exports.number().default(1e3).describe("Base delay between retries in milliseconds"), + maxDelayMs: external_exports.number().default(3e4).describe("Maximum delay between retries in milliseconds"), + backoffMultiplier: external_exports.number().default(2).describe("Exponential backoff multiplier") + }).optional().describe("Connection retry policy for transient failures"), + /** Description */ + description: external_exports.string().optional().describe("Internal description"), + /** Is enabled? */ + active: external_exports.boolean().default(true).describe("Is datasource enabled") + }); + AggregationMetricType2 = external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "number", + // Custom SQL expression returning a number + "string", + // Custom SQL expression returning a string + "boolean" + // Custom SQL expression returning a boolean + ]); + DimensionType2 = external_exports.enum([ + "string", + "number", + "boolean", + "time", + "geo" + ]); + TimeUpdateInterval2 = external_exports.enum([ + "second", + "minute", + "hour", + "day", + "week", + "month", + "quarter", + "year" + ]); + MetricSchema2 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique metric ID"), + label: external_exports.string().describe("Human readable label"), + description: external_exports.string().optional(), + type: AggregationMetricType2, + /** Source Calculation */ + sql: external_exports.string().describe("SQL expression or field reference"), + /** Filtering for this specific metric (e.g. "Revenue from Premium Users") */ + filters: external_exports.array(external_exports.object({ + sql: external_exports.string() + })).optional(), + /** Format for display (e.g. "currency", "percent") */ + format: external_exports.string().optional() + }); + DimensionSchema2 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique dimension ID"), + label: external_exports.string().describe("Human readable label"), + description: external_exports.string().optional(), + type: DimensionType2, + /** Source Column */ + sql: external_exports.string().describe("SQL expression or column reference"), + /** For Time Dimensions: Supported Granularities */ + granularities: external_exports.array(TimeUpdateInterval2).optional() + }); + CubeJoinSchema2 = external_exports.object({ + name: external_exports.string().describe("Target cube name"), + relationship: external_exports.enum(["one_to_one", "one_to_many", "many_to_one"]).default("many_to_one"), + sql: external_exports.string().describe("Join condition (ON clause)") + }); + CubeSchema2 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Cube name (snake_case)"), + title: external_exports.string().optional(), + description: external_exports.string().optional(), + /** Physical Data Source */ + sql: external_exports.string().describe("Base SQL statement or Table Name"), + /** Semantic Definitions */ + measures: external_exports.record(external_exports.string(), MetricSchema2).describe("Quantitative metrics"), + dimensions: external_exports.record(external_exports.string(), DimensionSchema2).describe("Qualitative attributes"), + /** Relationships */ + joins: external_exports.record(external_exports.string(), CubeJoinSchema2).optional(), + /** Pre-aggregations / Caching */ + refreshKey: external_exports.object({ + every: external_exports.string().optional(), + // e.g. "1 hour" + sql: external_exports.string().optional() + // SQL to check for data changes + }).optional(), + /** Access Control */ + public: external_exports.boolean().default(false) + }); + AnalyticsQuerySchema2 = external_exports.object({ + cube: external_exports.string().optional().describe("Target cube name (optional when provided externally, e.g. in API request wrapper)"), + measures: external_exports.array(external_exports.string()).describe("List of metrics to calculate"), + dimensions: external_exports.array(external_exports.string()).optional().describe("List of dimensions to group by"), + filters: external_exports.array(external_exports.object({ + member: external_exports.string().describe("Dimension or Measure"), + operator: external_exports.enum(["equals", "notEquals", "contains", "notContains", "gt", "gte", "lt", "lte", "set", "notSet", "inDateRange"]), + values: external_exports.array(external_exports.string()).optional() + })).optional(), + timeDimensions: external_exports.array(external_exports.object({ + dimension: external_exports.string(), + granularity: TimeUpdateInterval2.optional(), + dateRange: external_exports.union([ + external_exports.string(), + // "Last 7 days" + external_exports.array(external_exports.string()) + // ["2023-01-01", "2023-01-31"] + ]).optional() + })).optional(), + order: external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])).optional(), + limit: external_exports.number().optional(), + offset: external_exports.number().optional(), + timezone: external_exports.string().optional().default("UTC") + }); + FeedItemType2 = external_exports.enum([ + "comment", + "field_change", + "task", + "event", + "email", + "call", + "note", + "file", + "record_create", + "record_delete", + "approval", + "sharing", + "system" + ]); + MentionSchema2 = external_exports.object({ + type: external_exports.enum(["user", "team", "record"]).describe("Mention target type"), + id: external_exports.string().describe("Target ID"), + name: external_exports.string().describe("Display name for rendering"), + offset: external_exports.number().int().min(0).describe("Character offset in body text"), + length: external_exports.number().int().min(1).describe("Length of mention token in body text") + }); + FieldChangeEntrySchema2 = external_exports.object({ + field: external_exports.string().describe("Field machine name"), + fieldLabel: external_exports.string().optional().describe("Field display label"), + oldValue: external_exports.unknown().optional().describe("Previous value"), + newValue: external_exports.unknown().optional().describe("New value"), + oldDisplayValue: external_exports.string().optional().describe("Human-readable old value"), + newDisplayValue: external_exports.string().optional().describe("Human-readable new value") + }); + ReactionSchema2 = external_exports.object({ + emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")'), + userIds: external_exports.array(external_exports.string()).describe("Users who reacted"), + count: external_exports.number().int().min(1).describe("Total reaction count") + }); + FeedActorSchema2 = external_exports.object({ + type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), + id: external_exports.string().describe("Actor ID"), + name: external_exports.string().optional().describe("Actor display name"), + avatarUrl: external_exports.string().url().optional().describe("Actor avatar URL"), + source: external_exports.string().optional().describe('Source application (e.g., "Omni", "API", "Studio")') + }); + FeedVisibility2 = external_exports.enum(["public", "internal", "private"]); + FeedItemSchema2 = external_exports.object({ + /** Unique identifier */ + id: external_exports.string().describe("Feed item ID"), + /** Feed item type */ + type: FeedItemType2.describe("Activity type"), + /** Target record reference */ + object: external_exports.string().describe('Object name (e.g., "account")'), + recordId: external_exports.string().describe("Record ID this feed item belongs to"), + /** Actor (who performed the action) */ + actor: FeedActorSchema2.describe("Who performed this action"), + /** Content (for comments/notes) */ + body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), + /** @Mentions */ + mentions: external_exports.array(MentionSchema2).optional().describe("Mentioned users/teams/records"), + /** Field changes (for field_change type) */ + changes: external_exports.array(FieldChangeEntrySchema2).optional().describe("Field-level changes"), + /** Reactions */ + reactions: external_exports.array(ReactionSchema2).optional().describe("Emoji reactions on this item"), + /** Reply threading */ + parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), + replyCount: external_exports.number().int().min(0).default(0).describe("Number of replies"), + /** Pin / Star */ + pinned: external_exports.boolean().default(false).describe("Whether the feed item is pinned to the top of the timeline"), + pinnedAt: external_exports.string().datetime().optional().describe("Timestamp when the item was pinned"), + pinnedBy: external_exports.string().optional().describe("User ID who pinned the item"), + starred: external_exports.boolean().default(false).describe("Whether the feed item is starred/bookmarked by the current user"), + starredAt: external_exports.string().datetime().optional().describe("Timestamp when the item was starred"), + /** Visibility */ + visibility: FeedVisibility2.default("public").describe("Visibility: public (all users), internal (team only), private (author + mentioned)"), + /** Timestamps */ + createdAt: external_exports.string().datetime().describe("Creation timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + editedAt: external_exports.string().datetime().optional().describe("When comment was last edited"), + isEdited: external_exports.boolean().default(false).describe("Whether comment has been edited") + }); + FeedFilterMode = external_exports.enum([ + "all", + "comments_only", + "changes_only", + "tasks_only" + ]); + SubscriptionEventType2 = external_exports.enum([ + "comment", + "mention", + "field_change", + "task", + "approval", + "all" + ]); + NotificationChannel2 = external_exports.enum([ + "in_app", + "email", + "push", + "slack" + ]); + RecordSubscriptionSchema2 = external_exports.object({ + /** Target */ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + /** Subscriber */ + userId: external_exports.string().describe("Subscribing user ID"), + /** Events to subscribe to */ + events: external_exports.array(SubscriptionEventType2).default(["all"]).describe("Event types to receive notifications for"), + /** Notification channels */ + channels: external_exports.array(NotificationChannel2).default(["in_app"]).describe("Notification delivery channels"), + /** Active */ + active: external_exports.boolean().default(true).describe("Whether the subscription is active"), + /** Timestamps */ + createdAt: external_exports.string().datetime().describe("Subscription creation timestamp") + }); + TenantResolverStrategySchema = external_exports.enum([ + "header", + // Resolve from X-Tenant-ID request header + "subdomain", + // Resolve from subdomain (e.g., acme.app.com → acme) + "path", + // Resolve from URL path segment (e.g., /api/acme/...) + "token", + // Resolve from JWT claim (e.g., tenant_id in access token) + "lookup" + // Resolve from control-plane database lookup + ]).describe("Strategy for resolving tenant identity from request context"); + TursoGroupSchema = external_exports.object({ + /** + * Group name identifier. + * Used to reference the group when creating new tenant databases. + */ + name: external_exports.string().min(1).describe("Turso database group name"), + /** + * Primary location for the group (Turso region code). + * Example: 'iad' (US East), 'lhr' (London), 'nrt' (Tokyo) + */ + primaryLocation: external_exports.string().min(2).describe("Primary Turso region code (e.g., iad, lhr, nrt)"), + /** + * Additional replica locations for read performance. + * Databases in this group will have read replicas in these regions. + */ + replicaLocations: external_exports.array(external_exports.string().min(2)).default([]).describe("Additional replica region codes"), + /** + * Schema database name within the group. + * When using multi-db schemas, this is the "parent" database + * whose schema is shared by all child (tenant) databases. + */ + schemaDatabase: external_exports.string().optional().describe("Schema database name for multi-db schemas") + }).describe("Turso database group configuration"); + TenantDatabaseLifecycleSchema = external_exports.object({ + /** + * Hook executed when a new tenant is created. + * Defines how the tenant database is provisioned. + */ + onTenantCreate: external_exports.object({ + /** Whether to automatically create a Turso database */ + autoCreate: external_exports.boolean().default(true).describe("Auto-create database on tenant registration"), + /** Database group to create the database in */ + group: external_exports.string().optional().describe("Turso group for the new database"), + /** Whether to apply schema from the group schema database */ + applyGroupSchema: external_exports.boolean().default(true).describe("Apply shared schema from group"), + /** Seed data to populate on creation */ + seedData: external_exports.boolean().default(false).describe("Populate seed data on creation") + }).describe("Tenant creation hook"), + /** + * Hook executed when a tenant is deleted/destroyed. + */ + onTenantDelete: external_exports.object({ + /** Whether to destroy the database immediately or schedule for deletion */ + immediate: external_exports.boolean().default(false).describe("Destroy database immediately"), + /** Grace period in hours before permanent deletion (soft-delete) */ + gracePeriodHours: external_exports.number().int().min(0).default(72).describe("Grace period before permanent deletion"), + /** Whether to create a final backup before deletion */ + createBackup: external_exports.boolean().default(true).describe("Create backup before deletion") + }).describe("Tenant deletion hook"), + /** + * Hook executed when a tenant is suspended (e.g., unpaid, policy violation). + */ + onTenantSuspend: external_exports.object({ + /** Whether to revoke auth tokens on suspension */ + revokeTokens: external_exports.boolean().default(true).describe("Revoke auth tokens on suspension"), + /** Whether to set database to read-only mode */ + readOnly: external_exports.boolean().default(true).describe("Set database to read-only on suspension") + }).describe("Tenant suspension hook") + }).describe("Tenant database lifecycle hooks"); + TursoMultiTenantConfigSchema = external_exports.object({ + /** + * Turso organization slug. + * Used for Platform API calls and URL construction. + */ + organizationSlug: external_exports.string().min(1).describe("Turso organization slug"), + /** + * URL template for constructing tenant database URLs. + * Use `{tenant_id}` as placeholder for the tenant identifier. + * + * Example: 'libsql://{tenant_id}-myorg.turso.io' + */ + urlTemplate: external_exports.string().min(1).describe("URL template with {tenant_id} placeholder"), + /** + * Group-level auth token for Turso Platform API operations. + * Used for database creation, deletion, and management. + * This token has full access to all databases in the group. + */ + groupAuthToken: external_exports.string().min(1).describe("Group-level auth token for platform operations"), + /** + * Strategy for resolving tenant identity from the request context. + */ + tenantResolverStrategy: TenantResolverStrategySchema.default("token"), + /** + * Turso database group configuration. + */ + group: TursoGroupSchema.optional().describe("Database group configuration"), + /** + * Lifecycle hooks for tenant database management. + */ + lifecycle: TenantDatabaseLifecycleSchema.optional().describe("Lifecycle hooks"), + /** + * Maximum number of cached tenant database connections. + * Connections are evicted using LRU strategy when the limit is reached. + */ + maxCachedConnections: external_exports.number().int().min(1).default(100).describe("Max cached tenant connections (LRU)"), + /** + * Connection cache TTL in seconds. + * Cached connections are refreshed after this period. + */ + connectionCacheTTL: external_exports.number().int().min(0).default(300).describe("Connection cache TTL in seconds") + }).describe("Turso multi-tenant router configuration"); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_hash.js +var require_hash = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_hash.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var hash_exports = {}; + __export5(hash_exports, { + hashCode: () => hashCode2 + }); + module.exports = __toCommonJS(hash_exports); + var MULTIPLIER = 16777619; + function mix(h, x) { + return h * MULTIPLIER ^ x >>> 0; + } + function hashNumber(n) { + if (Number.isNaN(n)) return 2143289344; + if (!Number.isFinite(n)) return n > 0 ? 2139095040 : 4286578688; + const intPart = Math.trunc(n); + const frac = n - intPart; + let h = intPart | 0; + if (frac !== 0) { + const scaled = Math.floor(frac * 4294967296); + h = mix(h, scaled | 0); + } + return h >>> 0; + } + function hashString(str) { + let h = 0; + for (let i = 0; i < str.length; i++) { + h = mix(h, str.charCodeAt(i)); + } + return h >>> 0; + } + function hashBigInt(b) { + let h = 0; + const isNegative = b < 0n; + let x = isNegative ? -b : b; + if (x === 0n) { + h = mix(h, 0); + } else { + while (x > 0n) { + const byte = Number(x & 0xffn); + h = mix(h, byte); + x >>= 8n; + } + } + return mix(h, +isNegative) >>> 0; + } + function hashFunction(fn) { + let h = hashString((fn.name || "") + fn.toString()); + h = mix(h, fn.length); + return h >>> 0; + } + function hashBytes(bytes) { + let h = 0; + for (let i = 0; i < bytes.length; i++) { + h = mix(h, bytes[i]); + } + return h >>> 0; + } + function hashTypedArray(view) { + let h = hashString(view.constructor.name); + const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength); + h = mix(h, hashBytes(bytes)); + return h >>> 0; + } + function hashArray(arr, seen) { + if (seen.has(arr)) return 13; + seen.add(arr); + let h = 1; + for (let i = 0; i < arr.length; i++) { + h = mix(h, internalHash(arr[i], seen)); + } + seen.delete(arr); + return h >>> 0; + } + function hashObject(obj, seen) { + if (seen.has(obj)) return 13; + seen.add(obj); + const keys = Object.keys(obj).sort(); + let h = hashString(obj?.constructor?.name); + for (const k of keys) { + h = mix(h, hashString(k)); + h = mix(h, internalHash(obj[k], seen)); + } + seen.delete(obj); + return h >>> 0; + } + var BOOLEAN_HASH = [3735928559, 305441741].map((b) => mix(3, b)); + var NULL_HASH = mix(1, 0); + var UNDEF_HASH = mix(2, 0); + function internalHash(value, seen) { + if (value === null) return NULL_HASH; + const t = typeof value; + switch (t) { + case "undefined": + return UNDEF_HASH; + case "boolean": + return BOOLEAN_HASH[+value]; + case "number": + return mix(4, hashNumber(value)); + case "string": + return mix(5, hashString(value)); + case "bigint": + return mix(6, hashBigInt(value)); + case "function": + return mix(7, hashFunction(value)); + default: { + if (ArrayBuffer.isView(value) && !(value instanceof DataView)) + return mix(12, hashTypedArray(value)); + if (value instanceof Date) + return mix(10, hashNumber(value.getTime())); + if (value instanceof RegExp) { + const h = hashString(value.source); + return mix(11, mix(h, hashString(value.flags))); + } + if (Array.isArray(value)) return mix(8, hashArray(value, seen)); + return mix( + 9, + hashObject(value, seen) + ); + } + } + } + function hashCode2(value) { + return internalHash(value, /* @__PURE__ */ new WeakSet()) >>> 0; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_internal.js +var require_internal = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + HashMap: () => HashMap2, + MISSING: () => MISSING, + MingoError: () => MingoError2, + PathValidator: () => PathValidator, + assert: () => assert3, + cloneDeep: () => cloneDeep2, + compare: () => compare2, + ensureArray: () => ensureArray2, + filterMissing: () => filterMissing, + findInsertIndex: () => findInsertIndex2, + flatten: () => flatten2, + groupBy: () => groupBy2, + has: () => has2, + hashCode: () => import_hash22.hashCode, + intersection: () => intersection3, + isArray: () => isArray2, + isBoolean: () => isBoolean3, + isDate: () => isDate3, + isEmpty: () => isEmpty2, + isEqual: () => isEqual2, + isFunction: () => isFunction4, + isInteger: () => isInteger2, + isNil: () => isNil2, + isNumber: () => isNumber3, + isObject: () => isObject5, + isObjectLike: () => isObjectLike3, + isOperator: () => isOperator2, + isPrimitive: () => isPrimitive, + isRegExp: () => isRegExp2, + isString: () => isString3, + isSymbol: () => isSymbol2, + normalize: () => normalize2, + removeValue: () => removeValue2, + resolve: () => resolve2, + resolveGraph: () => resolveGraph, + setValue: () => setValue2, + simpleCmp: () => simpleCmp, + truthy: () => truthy, + typeOf: () => typeOf2, + unique: () => unique2, + walk: () => walk + }); + module.exports = __toCommonJS(internal_exports); + var import_hash6 = require_hash(); + var import_hash22 = require_hash(); + var MingoError2 = class extends Error { + }; + var MISSING = /* @__PURE__ */ Symbol("missing"); + var ERR_CYCLE_FOUND = "mingo: cycle detected while processing object/array"; + var isPrimitive = (v) => typeof v !== "object" && typeof v !== "function" || v === null; + var isScalar = (v) => isPrimitive(v) || isDate3(v) || isRegExp2(v); + var SORT_ORDER = { + undefined: 1, + null: 2, + number: 3, + string: 4, + symbol: 5, + object: 6, + array: 7, + arraybuffer: 8, + boolean: 9, + date: 10, + regexp: 11, + function: 12 + }; + var simpleCmp = (a, b) => a < b ? -1 : a > b ? 1 : 0; + var typedArraysCmp = (a, b) => { + const bytesA = new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + const bytesB = new Uint8Array(b.buffer, b.byteOffset, b.byteLength); + const size = Math.min(bytesA.length, bytesB.length); + for (let i = 0; i < size; i++) { + const order = simpleCmp(bytesA[i], bytesB[i]); + if (order !== 0) return order; + } + return simpleCmp(bytesA.length, bytesB.length); + }; + function mingoCmp(a, b, descendArray = false) { + if (a === MISSING) a = void 0; + if (b === MISSING) b = void 0; + if (a === b || Object.is(a, b)) return 0; + const typeA = typeOf2(a); + const typeB = typeOf2(b); + let neq = 0; + if (typeA === typeB) { + switch (typeA) { + case "number": + case "string": + case "boolean": + return simpleCmp(a, b); + case "date": + return simpleCmp(+a, +b); + case "regexp": + if (neq = simpleCmp(a.source, b.source)) + return neq; + return simpleCmp(a.flags, b.flags); + case "arraybuffer": + return typedArraysCmp(a, b); + case "array": { + const xs = a.slice().sort(mingoCmp); + const ys = b.slice().sort(mingoCmp); + const size = Math.min(xs.length, ys.length); + for (let i = 0; i < size; i++) + if (neq = mingoCmp(xs[i], ys[i])) return neq; + return simpleCmp(xs.length, ys.length); + } + default: { + if (typeA !== "object") { + const isSameType = a?.constructor === b?.constructor; + if (isSameType && hasCustomString(a)) + return simpleCmp(a.toString(), b.toString()); + if (neq = simpleCmp(a?.constructor?.name, b?.constructor?.name)) + return neq; + } + const keysA = Object.keys(a).sort(); + const keysB = Object.keys(b).sort(); + if (neq = mingoCmp(keysA, keysB)) return neq; + for (const k of keysA) + if (neq = mingoCmp(a[k], b[k])) + return neq; + return 0; + } + } + } + if (typeA == "undefined") return -1; + if (typeB == "undefined") return 1; + if (descendArray) { + if (typeA == "array") { + const xs = a; + if (!xs.length) return -1; + const sorted = xs.slice().sort(mingoCmp); + neq = 1; + for (const v of sorted) + if ((neq = Math.min(neq, mingoCmp(v, b))) < 0) return neq; + return neq; + } + if (typeB == "array") { + const ys = b; + if (!ys.length) return 1; + const sorted = ys.slice().sort(mingoCmp); + neq = -1; + for (const v of sorted) + if ((neq = Math.max(neq, mingoCmp(a, v))) > 0) return neq; + return neq; + } + } + const orderA = SORT_ORDER[typeA] ?? Number.MAX_VALUE; + const orderB = SORT_ORDER[typeB] ?? Number.MAX_VALUE; + return orderA !== orderB ? simpleCmp(orderA, orderB) : simpleCmp(typeA, typeB); + } + var compare2 = (a, b) => mingoCmp(a, b, true); + var hasCustomString = (o) => o !== null && o !== void 0 && o["toString"] !== Object.prototype.toString; + function isEqual2(a, b) { + if (a === b || Object.is(a, b)) return true; + if (a === null || b === null) return false; + if (typeof a !== typeof b) return false; + if (typeof a !== "object") return false; + if (a.constructor !== b?.constructor) return false; + if (isDate3(a)) return isDate3(b) && +a === +b; + if (isRegExp2(a)) + return isRegExp2(b) && a.source === b.source && a.flags === b.flags; + if (isArray2(a) && isArray2(b)) { + return a.length === b.length && a.every((v, i) => isEqual2(v, b[i])); + } + if (a?.constructor !== Object && hasCustomString(a)) { + return a?.toString() === b?.toString(); + } + const objA = a; + const objB = b; + const keysA = Object.keys(objA); + const keysB = Object.keys(objB); + if (keysA.length !== keysB.length) return false; + return keysA.every((k) => has2(objB, k) && isEqual2(objA[k], objB[k])); + } + var _keyMap, _unpack; + var _HashMap = class _HashMap extends Map { + constructor() { + super(); + // maps the hashcode to key set + __privateAdd(this, _keyMap, /* @__PURE__ */ new Map()); + // returns a tuple of [, ]. Expects an object key. + __privateAdd(this, _unpack, (key) => { + const hash2 = (0, import_hash6.hashCode)(key); + const items = __privateGet(this, _keyMap).get(hash2) ?? []; + return [items.find((k) => isEqual2(k, key)), hash2]; + }); + } + /** + * Returns a new {@link HashMap} object. + * @param fn An optional custom hash function + */ + static init() { + return new _HashMap(); + } + clear() { + super.clear(); + __privateGet(this, _keyMap).clear(); + } + /** + * @returns true if an element in the Map existed and has been removed, or false if the element does not exist. + */ + delete(key) { + if (isPrimitive(key)) return super.delete(key); + const [masterKey, hash2] = __privateGet(this, _unpack).call(this, key); + if (!super.delete(masterKey)) return false; + __privateGet(this, _keyMap).set( + hash2, + __privateGet(this, _keyMap).get(hash2).filter((k) => !isEqual2(k, masterKey)) + ); + return true; + } + /** + * Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map. + * @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. + */ + get(key) { + if (isPrimitive(key)) return super.get(key); + const [masterKey, _] = __privateGet(this, _unpack).call(this, key); + return super.get(masterKey); + } + /** + * @returns boolean indicating whether an element with the specified key exists or not. + */ + has(key) { + if (isPrimitive(key)) return super.has(key); + const [masterKey, _] = __privateGet(this, _unpack).call(this, key); + return super.has(masterKey); + } + /** + * Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated. + */ + set(key, value) { + if (isPrimitive(key)) return super.set(key, value); + const [masterKey, hash2] = __privateGet(this, _unpack).call(this, key); + if (super.has(masterKey)) { + super.set(masterKey, value); + } else { + super.set(key, value); + const keys = __privateGet(this, _keyMap).get(hash2) || []; + keys.push(key); + __privateGet(this, _keyMap).set(hash2, keys); + } + return this; + } + /** + * @returns the number of elements in the Map. + */ + get size() { + return super.size; + } + }; + _keyMap = new WeakMap(); + _unpack = new WeakMap(); + var HashMap2 = _HashMap; + function assert3(condition, msg) { + if (!condition) throw new MingoError2(msg); + } + function typeOf2(v) { + const t = typeof v; + switch (t) { + case "number": + case "string": + case "boolean": + case "undefined": + case "function": + case "symbol": + return t; + } + if (v === null) return "null"; + if (isArray2(v)) return "array"; + if (isDate3(v)) return "date"; + if (isRegExp2(v)) return "regexp"; + if (isTypedArray(v)) return "arraybuffer"; + if (v?.constructor === Object) return "object"; + return v?.constructor?.name?.toLowerCase() ?? "object"; + } + var isBoolean3 = (v) => typeof v === "boolean"; + var isString3 = (v) => typeof v === "string"; + var isSymbol2 = (v) => typeof v === "symbol"; + var isNumber3 = (v) => !Number.isNaN(v) && typeof v === "number"; + var isInteger2 = Number.isInteger; + var isArray2 = Array.isArray; + var isObject5 = (v) => typeOf2(v) === "object"; + var isObjectLike3 = (v) => !isPrimitive(v); + var isDate3 = (v) => v instanceof Date; + var isRegExp2 = (v) => v instanceof RegExp; + var isFunction4 = (v) => typeof v === "function"; + var isNil2 = (v) => v === null || v === void 0; + var truthy = (arg, strict = true) => !!arg || strict && arg === ""; + var isEmpty2 = (x) => isNil2(x) || isString3(x) && !x || isArray2(x) && x.length === 0 || isObject5(x) && Object.keys(x).length === 0; + var ensureArray2 = (x) => isArray2(x) ? x : [x]; + var has2 = (obj, ...props) => !!obj && props.every((p) => Object.prototype.hasOwnProperty.call(obj, p)); + var isTypedArray = (v) => typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(v); + var cloneDeep2 = (v, refs) => { + if (isNil2(v) || isBoolean3(v) || isNumber3(v) || isString3(v)) return v; + if (isDate3(v)) return new Date(v); + if (isRegExp2(v)) return new RegExp(v); + if (isTypedArray(v)) { + const ctor = v.constructor; + return new ctor(v); + } + if (!(refs instanceof WeakSet)) refs = /* @__PURE__ */ new WeakSet(); + if (refs.has(v)) throw new Error(ERR_CYCLE_FOUND); + refs.add(v); + try { + if (isArray2(v)) { + const arr = new Array(v.length); + for (let i = 0; i < v.length; i++) arr[i] = cloneDeep2(v[i], refs); + return arr; + } + if (isObject5(v)) { + const obj = {}; + for (const k of Object.keys(v)) obj[k] = cloneDeep2(v[k], refs); + return obj; + } + } finally { + refs.delete(v); + } + return v; + }; + function intersection3(input) { + if (input.length === 0) return []; + if (input.length === 1) return input[0].slice(); + for (const arr of input) if (arr.length === 0) return []; + const maps = [HashMap2.init(), HashMap2.init()]; + let index = 0; + for (const v of input[input.length - 1]) maps[0].set(v, true); + for (let i = input.length - 2; i >= 0; i--) { + for (let j = 0; j < input[i].length; j++) { + const v = input[i][j]; + if (maps[index].has(v)) maps[index ^ 1].set(v, true); + } + if (maps[index ^ 1].size === 0) return []; + maps[index].clear(); + index = index ^ 1; + } + return Array.from(maps[index].keys()); + } + function flatten2(xs, depth = 1) { + const arr = new Array(); + function flatten22(ys, n) { + for (let i = 0, len = ys.length; i < len; i++) { + if (isArray2(ys[i]) && (n > 0 || n < 0)) { + flatten22(ys[i], Math.max(-1, n - 1)); + } else { + arr.push(ys[i]); + } + } + } + flatten22(xs, depth); + return arr; + } + function unique2(input) { + const m = HashMap2.init(); + for (const v of input) m.set(v, true); + return Array.from(m.keys()); + } + function groupBy2(collection, keyFunc) { + if (collection.length < 1) return /* @__PURE__ */ new Map(); + const result = HashMap2.init(); + for (let i = 0; i < collection.length; i++) { + const obj = collection[i]; + const key = keyFunc(obj, i) ?? null; + let a = result.get(key); + if (!a) { + a = [obj]; + result.set(key, a); + } else { + a.push(obj); + } + } + return result; + } + function getValue(obj, key) { + return isObjectLike3(obj) ? obj[key] : void 0; + } + function unwrap4(arr, depth) { + if (depth < 1) return arr; + while (depth-- && arr.length === 1 && isArray2(arr[0])) arr = arr[0]; + return arr; + } + function resolve2(obj, selector, options) { + if (isScalar(obj)) return obj; + const path3 = options?.pathArray ?? selector.split("."); + if (path3.length === 1 && !isArray2(obj)) { + return getValue(obj, path3[0]); + } + if (path3.length === 2 && !isArray2(obj)) { + const first = getValue(obj, path3[0]); + if (first == null) return void 0; + if (!isArray2(first)) return getValue(first, path3[1]); + } + let depth = 0; + function resolve22(o, path22) { + let value = o; + for (let i = 0; i < path22.length; i++) { + const field = path22[i]; + const isText = !DIGITS_RE.test(field); + if (isText && isArray2(value)) { + if (i === 0 && depth > 0) break; + depth += 1; + const subpath = path22.slice(i); + value = value.reduce((acc, item) => { + const v = resolve22(item, subpath); + if (v !== void 0) acc.push(v); + return acc; + }, []); + break; + } else { + value = getValue(value, field); + } + if (value === void 0) break; + } + return value; + } + const res = resolve22(obj, path3); + return isArray2(res) && options?.unwrapArray ? unwrap4(res, depth) : res; + } + function resolveGraph(obj, selector, options) { + const sep = selector.indexOf("."); + const key = sep == -1 ? selector : selector.substring(0, sep); + const next = selector.substring(sep + 1); + const hasNext = sep != -1; + if (isArray2(obj)) { + const isIndex = /^\d+$/.test(key); + const arr = isIndex && options?.preserveIndex ? obj.slice() : []; + if (isIndex) { + const index = parseInt(key); + let value2 = getValue(obj, index); + if (hasNext) { + value2 = resolveGraph(value2, next, options); + } + if (options?.preserveIndex) { + arr[index] = value2; + } else { + arr.push(value2); + } + } else { + for (const item of obj) { + const value2 = resolveGraph(item, selector, options); + if (options?.preserveMissing) { + arr.push(value2 == void 0 ? MISSING : value2); + } else if (value2 != void 0 || options?.preserveIndex) { + arr.push(value2); + } + } + } + return arr; + } + const res = options?.preserveKeys ? { ...obj } : {}; + let value = getValue(obj, key); + if (hasNext) { + value = resolveGraph(value, next, options); + } + if (value === void 0) return void 0; + res[key] = value; + return res; + } + function filterMissing(obj) { + if (isArray2(obj)) { + for (let i = obj.length - 1; i >= 0; i--) { + if (obj[i] === MISSING) { + obj.splice(i, 1); + } else { + filterMissing(obj[i]); + } + } + } else if (isObject5(obj)) { + for (const k of Object.keys(obj)) { + if (has2(obj, k)) { + filterMissing(obj[k]); + } + } + } + } + var DIGITS_RE = /^\d+$/; + function walk(obj, selector, fn, options) { + const names = selector.split("."); + const key = names[0]; + const next = names.slice(1).join("."); + if (names.length === 1) { + if (isObject5(obj) || isArray2(obj) && DIGITS_RE.test(key)) { + fn(obj, key); + } + } else { + if (options?.buildGraph && isNil2(obj[key])) { + obj[key] = {}; + } + const item = obj[key]; + if (!item) return; + const isNextArrayIndex = !!(names.length > 1 && DIGITS_RE.test(names[1])); + if (isArray2(item) && options?.descendArray && !isNextArrayIndex) { + item.forEach((e) => walk(e, next, fn, options)); + } else { + walk(item, next, fn, options); + } + } + } + function setValue2(obj, selector, value) { + walk(obj, selector, (item, key) => item[key] = value, { + buildGraph: true + }); + } + function removeValue2(obj, selector, options) { + walk( + obj, + selector, + (item, key) => { + if (isArray2(item)) { + item.splice(parseInt(key), 1); + } else if (isObject5(item)) { + delete item[key]; + } + }, + options + ); + } + var isOperator2 = (name) => !!name && name[0] === "$" && /^\$[a-zA-Z0-9_]+$/.test(name); + function normalize2(expr) { + if (isScalar(expr)) { + return isRegExp2(expr) ? { $regex: expr } : { $eq: expr }; + } + if (isObjectLike3(expr)) { + if (!Object.keys(expr).some(isOperator2)) return { $eq: expr }; + if (isObject5(expr) && has2(expr, "$regex")) { + const newExpr = { ...expr }; + newExpr["$regex"] = new RegExp( + expr["$regex"], + expr["$options"] + ); + delete newExpr["$options"]; + return newExpr; + } + } + return expr; + } + function findInsertIndex2(sorted, item, comparator = compare2) { + let lo = 0; + let hi = sorted.length - 1; + while (lo <= hi) { + const mid = Math.round(lo + (hi - lo) / 2); + if (comparator(item, sorted[mid]) < 0) { + hi = mid - 1; + } else if (comparator(item, sorted[mid]) > 0) { + lo = mid + 1; + } else { + return mid; + } + } + return lo; + } + var PathValidator = class { + constructor() { + this.root = { + children: /* @__PURE__ */ new Map(), + isTerminal: false + }; + } + add(selector) { + const parts = selector.split("."); + let current = this.root; + for (const part of parts) { + if (current.isTerminal) return false; + if (!current.children.has(part)) { + current.children.set(part, { + children: /* @__PURE__ */ new Map(), + isTerminal: false + }); + } + current = current.children.get(part); + } + if (current.isTerminal || current.children.size) return false; + return current.isTerminal = true; + } + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/index.js +var require_util = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var util_exports2 = {}; + __export5(util_exports2, { + HashMap: () => import_internal.HashMap, + MingoError: () => import_internal.MingoError, + assert: () => import_internal.assert, + cloneDeep: () => import_internal.cloneDeep, + compare: () => import_internal.compare, + ensureArray: () => import_internal.ensureArray, + findInsertIndex: () => import_internal.findInsertIndex, + flatten: () => import_internal.flatten, + groupBy: () => import_internal.groupBy, + has: () => import_internal.has, + hashCode: () => import_internal.hashCode, + intersection: () => import_internal.intersection, + isArray: () => import_internal.isArray, + isBoolean: () => import_internal.isBoolean, + isDate: () => import_internal.isDate, + isEmpty: () => import_internal.isEmpty, + isEqual: () => import_internal.isEqual, + isFunction: () => import_internal.isFunction, + isInteger: () => import_internal.isInteger, + isNil: () => import_internal.isNil, + isNumber: () => import_internal.isNumber, + isObject: () => import_internal.isObject, + isObjectLike: () => import_internal.isObjectLike, + isOperator: () => import_internal.isOperator, + isRegExp: () => import_internal.isRegExp, + isString: () => import_internal.isString, + isSymbol: () => import_internal.isSymbol, + normalize: () => import_internal.normalize, + removeValue: () => import_internal.removeValue, + resolve: () => import_internal.resolve, + setValue: () => import_internal.setValue, + typeOf: () => import_internal.typeOf, + unique: () => import_internal.unique + }); + module.exports = __toCommonJS(util_exports2); + var import_internal = require_internal(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/_internal.js +var require_internal2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + ComputeOptions: () => ComputeOptions, + Context: () => Context3, + OpType: () => OpType2, + ProcessingMode: () => ProcessingMode2, + computeValue: () => computeValue2, + evalExpr: () => evalExpr2 + }); + module.exports = __toCommonJS(internal_exports); + var import_util3 = require_util(); + var ProcessingMode2 = /* @__PURE__ */ ((ProcessingMode22) => { + ProcessingMode22[ProcessingMode22["CLONE_OFF"] = 0] = "CLONE_OFF"; + ProcessingMode22[ProcessingMode22["CLONE_INPUT"] = 1] = "CLONE_INPUT"; + ProcessingMode22[ProcessingMode22["CLONE_OUTPUT"] = 2] = "CLONE_OUTPUT"; + ProcessingMode22[ProcessingMode22["CLONE_ALL"] = 3] = "CLONE_ALL"; + return ProcessingMode22; + })(ProcessingMode2 || {}); + var _locals; + var _ComputeOptions = class _ComputeOptions { + constructor(options, locals) { + __privateAdd(this, _locals); + this.options = options; + __privateSet(this, _locals, locals ? { ...locals } : {}); + } + /** + * Initializes a new instance of the `ComputeOptions` class with the provided options. + * + * @param options - A partial set of options to configure the `ComputeOptions` instance. + * If an instance of `ComputeOptions` is provided, its internal options and locals are used. + * @returns A new `ComputeOptions` instance configured with the provided options and root. + */ + static init(options) { + return options instanceof _ComputeOptions ? new _ComputeOptions(options.options, __privateGet(options, _locals)) : new _ComputeOptions({ + idKey: "_id", + scriptEnabled: true, + useStrictMode: true, + failOnError: true, + processingMode: 0, + ...options, + context: options?.context ? Context3.from(options?.context) : Context3.init() + }); + } + update(locals) { + Object.assign(__privateGet(this, _locals), locals, { + // DO NOT override timestamp + timestamp: __privateGet(this, _locals).timestamp, + // merge variables. + variables: { ...__privateGet(this, _locals)?.variables, ...locals?.variables } + }); + return this; + } + get local() { + return __privateGet(this, _locals); + } + get now() { + let timestamp = __privateGet(this, _locals).timestamp ?? 0; + if (!timestamp) { + timestamp = Date.now(); + Object.assign(__privateGet(this, _locals), { timestamp }); + } + return new Date(timestamp); + } + get idKey() { + return this.options.idKey; + } + get collation() { + return this.options?.collation; + } + get processingMode() { + return this.options?.processingMode; + } + get useStrictMode() { + return this.options?.useStrictMode; + } + get scriptEnabled() { + return this.options?.scriptEnabled; + } + get failOnError() { + return this.options?.failOnError; + } + get collectionResolver() { + return this.options?.collectionResolver; + } + get jsonSchemaValidator() { + return this.options?.jsonSchemaValidator; + } + get variables() { + return this.options?.variables; + } + get context() { + return this.options?.context; + } + }; + _locals = new WeakMap(); + var ComputeOptions = _ComputeOptions; + var OpType2 = /* @__PURE__ */ ((OpType22) => { + OpType22["ACCUMULATOR"] = "accumulator"; + OpType22["EXPRESSION"] = "expression"; + OpType22["PIPELINE"] = "pipeline"; + OpType22["PROJECTION"] = "projection"; + OpType22["QUERY"] = "query"; + OpType22["WINDOW"] = "window"; + return OpType22; + })(OpType2 || {}); + var _operators; + var _Context = class _Context { + constructor() { + __privateAdd(this, _operators); + __privateSet(this, _operators, { + [ + "accumulator" + /* ACCUMULATOR */ + ]: {}, + [ + "expression" + /* EXPRESSION */ + ]: {}, + [ + "pipeline" + /* PIPELINE */ + ]: {}, + [ + "projection" + /* PROJECTION */ + ]: {}, + [ + "query" + /* QUERY */ + ]: {}, + [ + "window" + /* WINDOW */ + ]: {} + }); + } + static init(ops = {}) { + const ctx = new _Context(); + for (const type of Object.keys(ops)) { + __privateGet(ctx, _operators)[type] = { ...ops[type] }; + } + return ctx; + } + /** Returns a new context with the operators from the provided contexts merged left to right. */ + static from(...ctx) { + if (ctx.length === 1) return _Context.init(__privateGet(ctx[0], _operators)); + const newCtx = new _Context(); + for (const context of ctx) { + for (const type of Object.values(OpType2)) { + newCtx.addOps(type, __privateGet(context, _operators)[type]); + } + } + return newCtx; + } + addOps(type, operators) { + __privateGet(this, _operators)[type] = Object.assign({}, operators, __privateGet(this, _operators)[type]); + return this; + } + getOperator(type, name) { + return __privateGet(this, _operators)[type][name] ?? null; + } + addAccumulatorOps(ops) { + return this.addOps("accumulator", ops); + } + addExpressionOps(ops) { + return this.addOps("expression", ops); + } + addQueryOps(ops) { + return this.addOps("query", ops); + } + addPipelineOps(ops) { + return this.addOps("pipeline", ops); + } + addProjectionOps(ops) { + return this.addOps("projection", ops); + } + addWindowOps(ops) { + return this.addOps("window", ops); + } + }; + _operators = new WeakMap(); + var Context3 = _Context; + function computeValue2(obj, expr, operator, options) { + return evalExpr2(obj, { [operator]: expr }, options); + } + function evalExpr2(obj, expr, options) { + const copts = !(options instanceof ComputeOptions) || (0, import_util3.isNil)(options.local.root) ? ComputeOptions.init(options).update({ root: obj }) : options; + return computeExpression(obj, expr, copts); + } + var SYSTEM_VARS = /* @__PURE__ */ new Set(["$$ROOT", "$$CURRENT", "$$REMOVE", "$$NOW"]); + function computeExpression(obj, expr, options) { + if ((0, import_util3.isString)(expr) && expr.length > 0 && expr[0] === "$") { + if (expr === "$$KEEP" || expr === "$$PRUNE" || expr === "$$DESCEND") + return expr; + let ctx = options.local.root; + const arr = expr.split("."); + const dotIdx = expr.indexOf("."); + const prefix = dotIdx === -1 ? expr : expr.substring(0, dotIdx); + if (SYSTEM_VARS.has(arr[0])) { + switch (prefix) { + case "$$ROOT": + break; + case "$$CURRENT": + ctx = obj; + break; + case "$$REMOVE": + ctx = void 0; + break; + case "$$NOW": + ctx = new Date(options.now); + break; + } + expr = dotIdx === -1 ? "" : expr.substring(dotIdx + 1); + } else if (prefix.length >= 2 && prefix[1] === "$") { + ctx = Object.assign( + {}, + // global vars + options.variables, + // current item is added before local variables because the binding may be changed. + { this: obj }, + // local vars + options?.local?.variables + ); + const name = prefix.substring(2); + (0, import_util3.assert)((0, import_util3.has)(ctx, name), `Use of undefined variable: ${name}`); + expr = expr.substring(2); + } else { + expr = expr.substring(1); + } + return expr === "" ? ctx : (0, import_util3.resolve)(ctx, expr); + } + if ((0, import_util3.isArray)(expr)) { + return expr.map((item) => computeExpression(obj, item, options)); + } + if ((0, import_util3.isObject)(expr)) { + const keys = Object.keys(expr); + if ((0, import_util3.isOperator)(keys[0])) { + (0, import_util3.assert)(keys.length === 1, "Expression must contain a single operator."); + return computeOperator(obj, expr[keys[0]], keys[0], options); + } + const result = {}; + for (let i = 0; i < keys.length; i++) { + result[keys[i]] = computeExpression(obj, expr[keys[i]], options); + } + return result; + } + return expr; + } + function computeOperator(obj, expr, operator, options) { + const context = options.context; + const fn = context.getOperator("expression", operator); + if (fn) return fn(obj, expr, options); + const accFn = context.getOperator("accumulator", operator); + (0, import_util3.assert)(!!accFn, `accumulator '${operator}' is not registered.`); + if (!(0, import_util3.isArray)(obj)) { + obj = computeExpression(obj, expr, options); + expr = null; + } + (0, import_util3.assert)((0, import_util3.isArray)(obj), `arguments must resolve to array for ${operator}.`); + return accFn(obj, expr, options); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/lazy.js +var require_lazy = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/lazy.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var lazy_exports = {}; + __export5(lazy_exports, { + Iterator: () => Iterator, + Lazy: () => Lazy, + concat: () => concat2 + }); + module.exports = __toCommonJS(lazy_exports); + var import_util3 = require_util(); + function Lazy(source) { + return new Iterator(source); + } + function concat2(...iterators) { + let index = 0; + return Lazy(() => { + while (index < iterators.length) { + const o = iterators[index].next(); + if (!o.done) return o; + index++; + } + return { done: true, value: void 0 }; + }); + } + function isGenerator(o) { + return !!o && typeof o === "object" && typeof o?.next === "function"; + } + function isIterable(o) { + return !!o && (typeof o === "object" || typeof o === "function") && typeof o[Symbol.iterator] === "function"; + } + var _iteratees, _buffer, _getNext, _done; + var Iterator = class { + constructor(source) { + __privateAdd(this, _iteratees, []); + __privateAdd(this, _buffer, []); + __privateAdd(this, _getNext); + __privateAdd(this, _done, false); + let iter; + if (isIterable(source)) + iter = source[Symbol.iterator](); + else if (isGenerator(source)) iter = source; + else if (typeof source === "function") iter = { next: source }; + else + (0, import_util3.assert)(0, "mingo: iterator requires an iterable, generator or function"); + let index = -1; + __privateSet(this, _getNext, () => { + while (true) { + let { value, done } = iter.next(); + if (done) return { done }; + let ok2 = true; + index++; + for (let i = 0; i < __privateGet(this, _iteratees).length; i++) { + const { op, fn } = __privateGet(this, _iteratees)[i]; + const res = fn(value, index); + if (op === "map") { + value = res; + } else if (!res) { + ok2 = false; + break; + } + } + if (ok2) return { value, done }; + } + }); + } + /** + * Add an iteratee to this lazy sequence + */ + push(op, fn) { + __privateGet(this, _iteratees).push({ op, fn }); + return this; + } + next() { + return __privateGet(this, _getNext).call(this); + } + // Iteratees methods + /** + * Transform each item in the sequence to a new value + * @param {Function} f + */ + map(f) { + return this.push("map", f); + } + /** + * Select only items matching the given predicate + * @param {Function} f + */ + filter(f) { + return this.push("filter", f); + } + /** + * Take given numbe for values from sequence + * @param {Number} n A number greater than 0 + */ + take(n) { + (0, import_util3.assert)(n >= 0, "value must be a non-negative integer"); + return this.filter((_) => n-- > 0); + } + /** + * Drop a number of values from the sequence + * @param {Number} n Number of items to drop greater than 0 + */ + drop(n) { + (0, import_util3.assert)(n >= 0, "value must be a non-negative integer"); + return this.filter((_) => n-- <= 0); + } + // Transformations + /** + * Returns a new lazy object with results of the transformation + * The entire sequence is realized. + * + * @param {Callback} f Tranform function of type (Array) => (Any) + */ + transform(f) { + const self = this; + let iter; + return Lazy(() => { + if (!iter) iter = f(self.collect()); + return iter.next(); + }); + } + /** + * Retrieves all remaining values from the lazy evaluation and returns them as an array. + * This method processes the underlying iterator until it is exhausted, storing the results + * in an internal buffer to ensure subsequent calls return the same data. + */ + collect() { + while (!__privateGet(this, _done)) { + const { done, value } = __privateGet(this, _getNext).call(this); + if (!done) __privateGet(this, _buffer).push(value); + __privateSet(this, _done, done); + } + return __privateGet(this, _buffer); + } + /** + * Execute the callback for each value. + * @param f The callback function. + */ + each(f) { + for (let o = this.next(); o.done !== true; o = this.next()) f(o.value); + } + /** + * Returns the reduction of sequence according the reducing function + * + * @param f The reducing function + * @param initialValue The initial value + */ + reduce(f, initialValue) { + let o = this.next(); + if (initialValue === void 0 && !o.done) { + initialValue = o.value; + o = this.next(); + } + while (!o.done) { + initialValue = f(initialValue, o.value); + o = this.next(); + } + return initialValue; + } + /** + * Returns the number of matched items in the sequence. + * The stream is realized and buffered for later retrieval with {@link collect}. + */ + size() { + return this.collect().length; + } + [Symbol.iterator]() { + return this; + } + }; + _iteratees = new WeakMap(); + _buffer = new WeakMap(); + _getNext = new WeakMap(); + _done = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/aggregator.js +var require_aggregator = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/aggregator.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var aggregator_exports = {}; + __export5(aggregator_exports, { + Aggregator: () => Aggregator2 + }); + module.exports = __toCommonJS(aggregator_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + var _pipeline, _options2; + var Aggregator2 = class { + /** + * Creates an instance of the Aggregator class. + * + * @param pipeline - An array of objects representing the aggregation pipeline stages. + * @param options - Optional configuration settings for the aggregator. + */ + constructor(pipeline, options) { + __privateAdd(this, _pipeline); + __privateAdd(this, _options2); + __privateSet(this, _pipeline, pipeline); + __privateSet(this, _options2, import_internal.ComputeOptions.init(options)); + } + /** + * Processes a collection through an aggregation pipeline and returns an iterator + * for the transformed results. + * + * @param collection - The input collection to process. This can be any source + * that implements the `Source` interface. + * @param options - Optional configuration for processing. If not provided, the + * default options of the aggregator instance will be used. + * @returns An iterator that yields the results of the aggregation pipeline. + * + * @throws Will throw an error if: + * - A pipeline stage contains more than one operator. + * - The `$documents` operator is not the first stage in the pipeline. + * - An unregistered pipeline operator is encountered. + */ + stream(collection, options) { + let iter = (0, import_lazy.Lazy)(collection); + const opts = options ?? __privateGet(this, _options2); + const mode = opts.processingMode; + if (mode & import_internal.ProcessingMode.CLONE_INPUT) iter.map((o) => (0, import_util3.cloneDeep)(o)); + iter = __privateGet(this, _pipeline).map((stage, i) => { + const keys = Object.keys(stage); + (0, import_util3.assert)( + keys.length === 1, + `aggregation stage must have single operator, got ${keys.toString()}.` + ); + const name = keys[0]; + (0, import_util3.assert)( + name !== "$documents" || i == 0, + "$documents must be first stage in pipeline." + ); + const op = opts.context.getOperator(import_internal.OpType.PIPELINE, name); + (0, import_util3.assert)(!!op, `unregistered pipeline operator ${name}.`); + return [op, stage[name]]; + }).reduce((acc, [op, expr]) => op(acc, expr, opts), iter); + if (mode & import_internal.ProcessingMode.CLONE_OUTPUT) iter.map((o) => (0, import_util3.cloneDeep)(o)); + return iter; + } + /** + * Executes the aggregation pipeline on the provided collection and returns the resulting array. + * + * @template T - The type of the objects in the resulting array. + * @param collection - The input data source to run the aggregation on. + * @param options - Optional settings to customize the aggregation behavior. + * @returns An array of objects of type `T` resulting from the aggregation. + */ + run(collection, options) { + return this.stream(collection, options).collect(); + } + }; + _pipeline = new WeakMap(); + _options2 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/push.js +var require_push = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/push.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var push_exports = {}; + __export5(push_exports, { + $push: () => $push + }); + module.exports = __toCommonJS(push_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $push = (coll, expr, options) => { + if ((0, import_util3.isNil)(expr)) return coll; + const copts = import_internal.ComputeOptions.init(options); + const result = new Array(coll.length); + for (let i = 0; i < coll.length; i++) { + const root = coll[i]; + result[i] = (0, import_internal.evalExpr)(root, expr, copts.update({ root })) ?? null; + } + return result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/accumulator.js +var require_accumulator = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/accumulator.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var accumulator_exports = {}; + __export5(accumulator_exports, { + $accumulator: () => $accumulator + }); + module.exports = __toCommonJS(accumulator_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_push = require_push(); + var $accumulator = (coll, expr, options) => { + (0, import_util3.assert)( + options.scriptEnabled, + "$accumulator requires 'scriptEnabled' option to be true" + ); + const copts = import_internal.ComputeOptions.init(options); + const input = expr; + const initArgs = (0, import_internal.evalExpr)( + copts?.local?.groupId, + input.initArgs || [], + copts.update({ root: copts?.local?.groupId }) + ); + const args = (0, import_push.$push)(coll, input.accumulateArgs, copts); + for (let i = 0; i < args.length; i++) { + for (let j = 0; j < args[i].length; j++) { + args[i][j] = args[i][j] ?? null; + } + } + const initialValue = input.init.apply(null, initArgs); + const f = input.accumulate; + let result = initialValue; + for (let i = 0; i < args.length; i++) { + result = f.apply(null, [result, ...args[i]]); + } + if (input.finalize) result = input.finalize.call(null, result); + return result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/addToSet.js +var require_addToSet = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/addToSet.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var addToSet_exports = {}; + __export5(addToSet_exports, { + $addToSet: () => $addToSet + }); + module.exports = __toCommonJS(addToSet_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var $addToSet = (coll, expr, options) => (0, import_util3.unique)((0, import_push.$push)(coll, expr, options)); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/avg.js +var require_avg = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/avg.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var avg_exports = {}; + __export5(avg_exports, { + $avg: () => $avg + }); + module.exports = __toCommonJS(avg_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var $avg = (coll, expr, options) => { + const data = (0, import_push.$push)(coll, expr, options).filter(import_util3.isNumber); + if (data.length === 0) return null; + const sum = data.reduce((acc, n) => acc + n, 0); + return sum / data.length; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sort.js +var require_sort = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sort.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sort_exports = {}; + __export5(sort_exports, { + $sort: () => $sort + }); + module.exports = __toCommonJS(sort_exports); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + function $sort(coll, sortKeys, options) { + (0, import_util3.assert)( + (0, import_util3.isObject)(sortKeys) && Object.keys(sortKeys).length > 0, + "$sort specification is invalid" + ); + let cmp = import_util3.compare; + const collationSpec = options.collation; + if ((0, import_util3.isObject)(collationSpec) && (0, import_util3.isString)(collationSpec.locale)) { + cmp = collationComparator(collationSpec); + } + return coll.transform((coll2) => { + const modifiers = Object.keys(sortKeys); + for (const key of modifiers.reverse()) { + const groups = (0, import_util3.groupBy)(coll2, (obj) => (0, import_util3.resolve)(obj, key)); + const sortedKeys = Array.from(groups.keys()); + let nativeSorted = false; + if (cmp === import_util3.compare) { + let t_str = true; + let t_num = true; + for (const v of sortedKeys) { + t_str && (t_str = (0, import_util3.isString)(v)); + t_num && (t_num = (0, import_util3.isNumber)(v)); + if (!t_str && !t_num) break; + } + nativeSorted = t_str || t_num; + if (t_str) sortedKeys.sort(); + else if (t_num) { + const numbers = new Float64Array(sortedKeys).sort(); + for (let i2 = 0; i2 < numbers.length; i2++) { + sortedKeys[i2] = numbers[i2]; + } + } + } + if (!nativeSorted) sortedKeys.sort(cmp); + if (sortKeys[key] === -1) sortedKeys.reverse(); + let i = 0; + for (const k of sortedKeys) for (const v of groups.get(k)) coll2[i++] = v; + (0, import_util3.assert)(i == coll2.length, "bug: counter must match collection size."); + } + return (0, import_lazy.Lazy)(coll2); + }); + } + var COLLATION_STRENGTH = { + // Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A. + 1: "base", + // Only strings that differ in base letters or accents and other diacritic marks compare as unequal. + // Examples: a ≠ b, a ≠ á, a = A. + 2: "accent", + // Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. + // Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A + 3: "variant" + // case - Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A. + }; + function collationComparator(spec) { + const localeOpt = { + sensitivity: COLLATION_STRENGTH[spec.strength || 3], + caseFirst: spec.caseFirst === "off" ? "false" : spec.caseFirst, + numeric: spec.numericOrdering || false, + ignorePunctuation: spec.alternate === "shifted" + }; + if (spec.caseLevel === true) { + if (localeOpt.sensitivity === "base") localeOpt.sensitivity = "case"; + if (localeOpt.sensitivity === "accent") localeOpt.sensitivity = "variant"; + } + const collator = new Intl.Collator(spec.locale, localeOpt); + return (a, b) => (0, import_util3.isString)(a) && (0, import_util3.isString)(b) ? collator.compare(a, b) : (0, import_util3.compare)(a, b); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottomN.js +var require_bottomN = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottomN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bottomN_exports = {}; + __export5(bottomN_exports, { + $bottomN: () => $bottomN + }); + module.exports = __toCommonJS(bottomN_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_sort = require_sort(); + var import_push = require_push(); + var $bottomN = (coll, expr, options) => { + const copts = options; + const args = expr; + const n = (0, import_internal.evalExpr)(copts?.local?.groupId, args.n, copts); + const result = (0, import_sort.$sort)((0, import_lazy.Lazy)(coll), args.sortBy, options).collect(); + const m = result.length; + return (0, import_push.$push)(m <= n ? result : result.slice(m - n), args.output, copts); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottom.js +var require_bottom = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottom.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bottom_exports = {}; + __export5(bottom_exports, { + $bottom: () => $bottom + }); + module.exports = __toCommonJS(bottom_exports); + var import_bottomN = require_bottomN(); + var $bottom = (coll, expr, options) => { + return (0, import_bottomN.$bottomN)(coll, { ...expr, n: 1 }, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/count.js +var require_count = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/count.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var count_exports = {}; + __export5(count_exports, { + $count: () => $count + }); + module.exports = __toCommonJS(count_exports); + var $count = (coll, _expr2, _opts) => coll.length; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/_internal.js +var require_internal3 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + covariance: () => covariance, + stddev: () => stddev + }); + module.exports = __toCommonJS(internal_exports); + function stddev(data, sampled = true) { + const sum = data.reduce((acc, n) => acc + n, 0); + const N = Math.max(data.length, 1); + const avg = sum / N; + return Math.sqrt( + data.reduce((acc, n) => acc + Math.pow(n - avg, 2), 0) / (N - Number(sampled)) + ); + } + function covariance(dataset, sampled = true) { + if (dataset.length < 2) return sampled ? null : 0; + let meanX = 0; + let meanY = 0; + for (const [x, y] of dataset) { + meanX += x; + meanY += y; + } + meanX /= dataset.length; + meanY /= dataset.length; + let result = 0; + for (const [x, y] of dataset) { + result += (x - meanX) * (y - meanY); + } + return result / (dataset.length - Number(sampled)); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covariancePop.js +var require_covariancePop = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covariancePop.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var covariancePop_exports = {}; + __export5(covariancePop_exports, { + $covariancePop: () => $covariancePop + }); + module.exports = __toCommonJS(covariancePop_exports); + var import_internal = require_internal3(); + var import_push = require_push(); + var $covariancePop = (coll, expr, options) => (0, import_internal.covariance)((0, import_push.$push)(coll, expr, options), false); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covarianceSamp.js +var require_covarianceSamp = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covarianceSamp.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var covarianceSamp_exports = {}; + __export5(covarianceSamp_exports, { + $covarianceSamp: () => $covarianceSamp + }); + module.exports = __toCommonJS(covarianceSamp_exports); + var import_internal = require_internal3(); + var import_push = require_push(); + var $covarianceSamp = (coll, expr, options) => (0, import_internal.covariance)((0, import_push.$push)(coll, expr, options), true); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/first.js +var require_first = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/first.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var first_exports = {}; + __export5(first_exports, { + $first: () => $first + }); + module.exports = __toCommonJS(first_exports); + var import_internal = require_internal2(); + var $first = (coll, expr, options) => { + const obj = coll[0]; + const copts = import_internal.ComputeOptions.init(options).update({ root: obj }); + return (0, import_internal.evalExpr)(obj, expr, copts) ?? null; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/_internal.js +var require_internal4 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + ARR_OPTS: () => ARR_OPTS, + INT_OPTS: () => INT_OPTS, + errExpectArray: () => errExpectArray, + errExpectNumber: () => errExpectNumber, + errExpectObject: () => errExpectObject, + errExpectString: () => errExpectString, + errInvalidArgs: () => errInvalidArgs + }); + module.exports = __toCommonJS(internal_exports); + var import_util3 = require_util(); + var INT_OPTS = { + int: { int: true }, + // (-∞, ∞) + pos: { min: 1, int: true }, + // [1, ∞] + index: { min: 0, int: true }, + // [0, ∞] + nzero: { min: 0, max: 0, int: true } + // non-zero + }; + var ARR_OPTS = { + int: { type: "integers" }, + obj: { type: "objects" } + }; + function errInvalidArgs(failOnError, message2) { + (0, import_util3.assert)(!failOnError, message2); + return null; + } + function errExpectObject(failOnError, prefix) { + const msg = `${prefix} expression must resolve to object`; + (0, import_util3.assert)(!failOnError, msg); + return null; + } + function errExpectString(failOnError, prefix) { + const msg = `${prefix} expression must resolve to string`; + (0, import_util3.assert)(!failOnError, msg); + return null; + } + function errExpectNumber(failOnError, name, opts) { + const type = opts?.int ? "integer" : "number"; + const min = opts?.min ?? -Infinity; + const max = opts?.max ?? Infinity; + let msg; + if (min === 0 && max === 0) { + msg = `${name} expression must resolve to non-zero ${type}`; + } else if (min === 0 && max === Infinity) { + msg = `${name} expression must resolve to non-negative ${type}`; + } else if (min !== -Infinity && max !== Infinity) { + msg = `${name} expression must resolve to ${type} in range [${min}, ${max}]`; + } else if (min > 0) { + msg = `${name} expression must resolve to positive ${type}`; + } else { + msg = `${name} expression must resolve to ${type}`; + } + (0, import_util3.assert)(!failOnError, msg); + return null; + } + function errExpectArray(failOnError, prefix, opts) { + let suffix = "array"; + if (!(0, import_util3.isNil)(opts?.size) && opts?.size >= 0) + suffix = opts.size === 0 ? "non-zero array" : `array(${opts.size})`; + if (opts?.type) suffix = `array of ${opts.type}`; + const msg = `${prefix} expression must resolve to ${suffix}`; + (0, import_util3.assert)(!failOnError, msg); + return null; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/firstN.js +var require_firstN = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/firstN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var firstN_exports = {}; + __export5(firstN_exports, { + $firstN: () => $firstN + }); + module.exports = __toCommonJS(firstN_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var import_push = require_push(); + var $firstN = (coll, expr, options) => { + const foe = options.failOnError; + const copts = options; + const m = coll.length; + const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts); + if (!(0, import_util3.isInteger)(n) || n < 1) + return (0, import_internal2.errExpectNumber)(foe, "$firstN 'n'", import_internal2.INT_OPTS.pos); + return (0, import_push.$push)(m <= n ? coll : coll.slice(0, n), expr.input, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/last.js +var require_last = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/last.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var last_exports = {}; + __export5(last_exports, { + $last: () => $last + }); + module.exports = __toCommonJS(last_exports); + var import_internal = require_internal2(); + var $last = (coll, expr, options) => { + const obj = coll[coll.length - 1]; + const copts = import_internal.ComputeOptions.init(options).update({ root: obj }); + return (0, import_internal.evalExpr)(obj, expr, copts) ?? null; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/lastN.js +var require_lastN = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/lastN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var lastN_exports = {}; + __export5(lastN_exports, { + $lastN: () => $lastN + }); + module.exports = __toCommonJS(lastN_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var import_push = require_push(); + var $lastN = (coll, expr, options) => { + const copts = options; + const m = coll.length; + const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts); + const foe = options.failOnError; + if (!(0, import_util3.isInteger)(n) || n < 1) { + return (0, import_internal2.errExpectNumber)(foe, "$lastN 'n'", import_internal2.INT_OPTS.pos); + } + return (0, import_push.$push)(m <= n ? coll : coll.slice(m - n), expr.input, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/max.js +var require_max = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/max.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var max_exports = {}; + __export5(max_exports, { + $max: () => $max + }); + module.exports = __toCommonJS(max_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var $max = (coll, expr, options) => { + const items = (0, import_push.$push)(coll, expr, options).filter((v) => !(0, import_util3.isNil)(v)); + if (!items.length) return null; + return items.reduce((r, v) => (0, import_util3.compare)(r, v) >= 0 ? r : v); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/maxN.js +var require_maxN = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/maxN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var maxN_exports = {}; + __export5(maxN_exports, { + $maxN: () => $maxN + }); + module.exports = __toCommonJS(maxN_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var import_push = require_push(); + var $maxN = (coll, expr, options) => { + const copts = options; + const m = coll.length; + const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts); + if (!(0, import_util3.isInteger)(n) || n < 1) { + return (0, import_internal2.errExpectNumber)(options.failOnError, "$maxN 'n'", import_internal2.INT_OPTS.pos); + } + const arr = (0, import_push.$push)(coll, expr.input, options).filter((o) => !(0, import_util3.isNil)(o)); + arr.sort((a, b) => -1 * (0, import_util3.compare)(a, b)); + return m <= n ? arr : arr.slice(0, n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/percentile.js +var require_percentile = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/percentile.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var percentile_exports = {}; + __export5(percentile_exports, { + $percentile: () => $percentile + }); + module.exports = __toCommonJS(percentile_exports); + var import_util3 = require_util(); + var import_internal = require_internal4(); + var import_push = require_push(); + var $percentile = (coll, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "p") && (0, import_util3.isArray)(expr.p), + "$percentile expects object { input, p }" + ); + const X = (0, import_push.$push)(coll, expr.input, options).filter(import_util3.isNumber).sort(); + const centiles = (0, import_push.$push)(expr.p, "$$CURRENT", options); + const method = expr.method || "approximate"; + for (const n of centiles) { + if (!(0, import_util3.isNumber)(n) || n < 0 || n > 1) { + return (0, import_internal.errInvalidArgs)( + options.failOnError, + "$percentile 'p' must resolve to array of numbers between [0.0, 1.0]" + ); + } + } + return centiles.map((p) => { + const r = p * (X.length - 1) + 1; + const ri = Math.floor(r); + const result = r === ri ? X[r - 1] : X[ri - 1] + r % 1 * (X[ri] - X[ri - 1]); + switch (method) { + case "exact": + return result; + case "approximate": { + const i = (0, import_util3.findInsertIndex)(X, result); + return i / X.length >= p ? X[Math.max(i - 1, 0)] : X[i]; + } + } + }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/median.js +var require_median = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/median.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var median_exports = {}; + __export5(median_exports, { + $median: () => $median + }); + module.exports = __toCommonJS(median_exports); + var import_percentile = require_percentile(); + var $median = (coll, expr, options) => (0, import_percentile.$percentile)(coll, { ...expr, p: [0.5] }, options)?.pop(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/mergeObjects.js +var require_mergeObjects = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/mergeObjects.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var mergeObjects_exports = {}; + __export5(mergeObjects_exports, { + $mergeObjects: () => $mergeObjects + }); + module.exports = __toCommonJS(mergeObjects_exports); + var import_util3 = require_util(); + var $mergeObjects = (coll, _expr2, _options2) => { + const acc = {}; + for (const o of coll) { + if ((0, import_util3.isNil)(o)) continue; + for (const k of Object.keys(o)) { + if (o[k] !== void 0) acc[k] = o[k]; + } + } + return acc; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/min.js +var require_min = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/min.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var min_exports = {}; + __export5(min_exports, { + $min: () => $min + }); + module.exports = __toCommonJS(min_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var $min = (coll, expr, options) => { + const items = (0, import_push.$push)(coll, expr, options).filter((v) => !(0, import_util3.isNil)(v)); + if (!items.length) return null; + return items.reduce((r, v) => (0, import_util3.compare)(r, v) <= 0 ? r : v); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/minN.js +var require_minN = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/minN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var minN_exports = {}; + __export5(minN_exports, { + $minN: () => $minN + }); + module.exports = __toCommonJS(minN_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var import_push = require_push(); + var $minN = (coll, expr, options) => { + const copts = options; + const m = coll.length; + const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts); + if (!(0, import_util3.isInteger)(n) || n < 1) { + return (0, import_internal2.errExpectNumber)(options.failOnError, "$minN 'n'", import_internal2.INT_OPTS.pos); + } + const arr = (0, import_push.$push)(coll, expr.input, options).filter((o) => !(0, import_util3.isNil)(o)); + arr.sort(import_util3.compare); + return m <= n ? arr : arr.slice(0, n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevPop.js +var require_stdDevPop = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevPop.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var stdDevPop_exports = {}; + __export5(stdDevPop_exports, { + $stdDevPop: () => $stdDevPop + }); + module.exports = __toCommonJS(stdDevPop_exports); + var import_util3 = require_util(); + var import_internal = require_internal3(); + var import_push = require_push(); + var $stdDevPop = (coll, expr, options) => (0, import_internal.stddev)((0, import_push.$push)(coll, expr, options).filter(import_util3.isNumber), false); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevSamp.js +var require_stdDevSamp = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevSamp.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var stdDevSamp_exports = {}; + __export5(stdDevSamp_exports, { + $stdDevSamp: () => $stdDevSamp + }); + module.exports = __toCommonJS(stdDevSamp_exports); + var import_util3 = require_util(); + var import_internal = require_internal3(); + var import_push = require_push(); + var $stdDevSamp = (coll, expr, options) => (0, import_internal.stddev)((0, import_push.$push)(coll, expr, options).filter(import_util3.isNumber), true); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/sum.js +var require_sum = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/sum.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sum_exports = {}; + __export5(sum_exports, { + $sum: () => $sum + }); + module.exports = __toCommonJS(sum_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var $sum = (coll, expr, options) => { + if ((0, import_util3.isNumber)(expr)) return coll.length * expr; + const nums = (0, import_push.$push)(coll, expr, options).filter(import_util3.isNumber); + return nums.reduce((r, n) => r + n, 0); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/topN.js +var require_topN = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/topN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var topN_exports = {}; + __export5(topN_exports, { + $topN: () => $topN + }); + module.exports = __toCommonJS(topN_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_sort = require_sort(); + var import_push = require_push(); + var $topN = (coll, expr, options) => { + const copts = options; + const { n, sortBy } = (0, import_internal.evalExpr)(copts?.local?.groupId, expr, copts); + const result = (0, import_sort.$sort)((0, import_lazy.Lazy)(coll), sortBy, options).take(n).collect(); + return (0, import_push.$push)(result, expr.output, copts); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/top.js +var require_top = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/top.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var top_exports = {}; + __export5(top_exports, { + $top: () => $top + }); + module.exports = __toCommonJS(top_exports); + var import_topN = require_topN(); + var $top = (coll, expr, options) => (0, import_topN.$topN)(coll, { ...expr, n: 1 }, options); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/index.js +var require_accumulator2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var accumulator_exports = {}; + module.exports = __toCommonJS(accumulator_exports); + __reExport(accumulator_exports, require_accumulator(), module.exports); + __reExport(accumulator_exports, require_addToSet(), module.exports); + __reExport(accumulator_exports, require_avg(), module.exports); + __reExport(accumulator_exports, require_bottom(), module.exports); + __reExport(accumulator_exports, require_bottomN(), module.exports); + __reExport(accumulator_exports, require_count(), module.exports); + __reExport(accumulator_exports, require_covariancePop(), module.exports); + __reExport(accumulator_exports, require_covarianceSamp(), module.exports); + __reExport(accumulator_exports, require_first(), module.exports); + __reExport(accumulator_exports, require_firstN(), module.exports); + __reExport(accumulator_exports, require_last(), module.exports); + __reExport(accumulator_exports, require_lastN(), module.exports); + __reExport(accumulator_exports, require_max(), module.exports); + __reExport(accumulator_exports, require_maxN(), module.exports); + __reExport(accumulator_exports, require_median(), module.exports); + __reExport(accumulator_exports, require_mergeObjects(), module.exports); + __reExport(accumulator_exports, require_min(), module.exports); + __reExport(accumulator_exports, require_minN(), module.exports); + __reExport(accumulator_exports, require_percentile(), module.exports); + __reExport(accumulator_exports, require_push(), module.exports); + __reExport(accumulator_exports, require_stdDevPop(), module.exports); + __reExport(accumulator_exports, require_stdDevSamp(), module.exports); + __reExport(accumulator_exports, require_sum(), module.exports); + __reExport(accumulator_exports, require_top(), module.exports); + __reExport(accumulator_exports, require_topN(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/abs.js +var require_abs = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/abs.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var abs_exports = {}; + __export5(abs_exports, { + $abs: () => $abs + }); + module.exports = __toCommonJS(abs_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $abs = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(n)) return null; + if (typeof n !== "number") + return (0, import_internal2.errExpectNumber)(options.failOnError, "$abs"); + return Math.abs(n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/add.js +var require_add = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/add.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var add_exports = {}; + __export5(add_exports, { + $add: () => $add + }); + module.exports = __toCommonJS(add_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var err = "$add expression must resolve to array of numbers."; + var $add = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + const failOnError = options.failOnError; + let dateFound = false; + let result = 0; + if (!(0, import_util3.isArray)(args)) return (0, import_internal2.errInvalidArgs)(failOnError, err); + for (const n of args) { + if ((0, import_util3.isNil)(n)) return null; + if (typeof n === "number") { + result += n; + } else if ((0, import_util3.isDate)(n)) { + if (dateFound) { + return (0, import_internal2.errInvalidArgs)(failOnError, "$add must only have one date"); + } + dateFound = true; + result += +n; + } else { + return (0, import_internal2.errInvalidArgs)(failOnError, err); + } + } + return dateFound ? new Date(result) : result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ceil.js +var require_ceil = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ceil.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var ceil_exports = {}; + __export5(ceil_exports, { + $ceil: () => $ceil + }); + module.exports = __toCommonJS(ceil_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $ceil = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(n)) return null; + if (typeof n !== "number") + return (0, import_internal2.errExpectNumber)(options.failOnError, "$ceil"); + return Math.ceil(n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/divide.js +var require_divide = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/divide.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var divide_exports = {}; + __export5(divide_exports, { + $divide: () => $divide + }); + module.exports = __toCommonJS(divide_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $divide = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), "$divide expects array(2)"); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + let t_num = true; + for (const v of args) { + if ((0, import_util3.isNil)(v)) return null; + t_num && (t_num = (0, import_util3.isNumber)(v)); + } + if (!t_num) { + return (0, import_internal2.errExpectArray)(foe, "$divide", { + size: 2, + type: "number" + }); + } + if (args[1] === 0) + return (0, import_internal2.errInvalidArgs)(foe, "$divide cannot divide by zero"); + return args[0] / args[1]; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/exp.js +var require_exp = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/exp.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var exp_exports = {}; + __export5(exp_exports, { + $exp: () => $exp + }); + module.exports = __toCommonJS(exp_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $exp = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(n)) return null; + if (typeof n !== "number") { + return (0, import_internal2.errExpectNumber)(options.failOnError, "$exp"); + } + return Math.exp(n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/floor.js +var require_floor = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/floor.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var floor_exports = {}; + __export5(floor_exports, { + $floor: () => $floor + }); + module.exports = __toCommonJS(floor_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $floor = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(n)) return null; + if (typeof n !== "number") { + return (0, import_internal2.errExpectNumber)(options.failOnError, "$floor"); + } + return Math.floor(n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ln.js +var require_ln = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ln.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var ln_exports = {}; + __export5(ln_exports, { + $ln: () => $ln + }); + module.exports = __toCommonJS(ln_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $ln = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(n)) return null; + if (typeof n !== "number") { + return (0, import_internal2.errExpectNumber)(options.failOnError, "$ln"); + } + return Math.log(n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log.js +var require_log = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var log_exports = {}; + __export5(log_exports, { + $log: () => $log + }); + module.exports = __toCommonJS(log_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $log = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isArray)(args) && args.length == 2) { + let t_num = true; + for (const v of args) { + if ((0, import_util3.isNil)(v)) return null; + t_num && (t_num = typeof v === "number"); + } + if (t_num) return Math.log10(args[0]) / Math.log10(args[1]); + } + return (0, import_internal2.errExpectArray)(options.failOnError, "$log", { + size: 2, + type: "number" + }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log10.js +var require_log10 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log10.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var log10_exports = {}; + __export5(log10_exports, { + $log10: () => $log10 + }); + module.exports = __toCommonJS(log10_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $log10 = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(n)) return null; + if (typeof n === "number") return Math.log10(n); + return (0, import_internal2.errExpectNumber)(options.failOnError, "$log10"); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/mod.js +var require_mod = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/mod.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var mod_exports = {}; + __export5(mod_exports, { + $mod: () => $mod + }); + module.exports = __toCommonJS(mod_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $mod = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + let invalid = !(0, import_util3.isArray)(args) || args.length != 2; + invalid || (invalid = !args.every((v) => typeof v === "number")); + if (invalid) + return (0, import_internal2.errExpectArray)(options.failOnError, "$mod", { + size: 2, + type: "number" + }); + return args[0] % args[1]; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/multiply.js +var require_multiply = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/multiply.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var multiply_exports = {}; + __export5(multiply_exports, { + $multiply: () => $multiply + }); + module.exports = __toCommonJS(multiply_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $multiply = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), "$multiply expects array"); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + if (args.some(import_util3.isNil)) return null; + let res = 1; + for (const n of args) { + if (!(0, import_util3.isNumber)(n)) + return (0, import_internal2.errExpectArray)(foe, "$multiply", { type: "number" }); + res *= n; + } + return res; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/pow.js +var require_pow = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/pow.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var pow_exports = {}; + __export5(pow_exports, { + $pow: () => $pow + }); + module.exports = __toCommonJS(pow_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $pow = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, "$pow expects array(2)"); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + let t_num = true; + for (const v of args) { + if ((0, import_util3.isNil)(v)) return null; + t_num && (t_num = (0, import_util3.isNumber)(v)); + } + if (!t_num) { + return (0, import_internal2.errExpectArray)(foe, "$pow", { + size: 2, + type: "number" + }); + } + if (args[0] === 0 && args[1] < 0) + (0, import_internal2.errInvalidArgs)(foe, "$pow cannot raise 0 to a negative exponent"); + return Math.pow(args[0], args[1]); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/_internal.js +var require_internal5 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + truncate: () => truncate + }); + module.exports = __toCommonJS(internal_exports); + var import_util3 = require_util(); + var import_internal = require_internal4(); + function truncate(num, precision, opts) { + const { name, roundOff, failOnError } = opts; + if ((0, import_util3.isNil)(num)) return null; + if (Number.isNaN(num) || Math.abs(num) === Infinity) return num; + if (!(0, import_util3.isNumber)(num)) { + return (0, import_internal.errExpectNumber)(failOnError, `${name} arg1 `); + } + if (!(0, import_util3.isInteger)(precision) || precision < -20 || precision > 100) { + return (0, import_internal.errExpectNumber)(failOnError, `${name} arg2 `, { + min: -20, + max: 100, + int: true + }); + } + const sign2 = Math.abs(num) === num ? 1 : -1; + num = Math.abs(num); + let result = Math.trunc(num); + const decimals = parseFloat((num - result).toFixed(Math.abs(precision) + 1)); + if (precision === 0) { + const firstDigit = Math.trunc(10 * decimals); + if (roundOff && ((result & 1) === 1 && firstDigit >= 5 || firstDigit > 5)) { + result++; + } + } else if (precision > 0) { + const offset = Math.pow(10, precision); + let remainder = Math.trunc(decimals * offset); + const lastDigit = Math.trunc(decimals * offset * 10) % 10; + if (roundOff && lastDigit > 5) { + remainder += 1; + } + result = (result * offset + remainder) / offset; + } else if (precision < 0) { + const offset = Math.pow(10, -1 * precision); + let excess = result % offset; + result = Math.max(0, result - excess); + if (roundOff && sign2 === -1) { + while (excess > 10) { + excess -= excess / 10; + } + if (result > 0 && excess >= 5) { + result += offset; + } + } + } + return result * sign2; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/round.js +var require_round = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/round.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var round_exports = {}; + __export5(round_exports, { + $round: () => $round + }); + module.exports = __toCommonJS(round_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal5(); + var $round = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), "$round expects array(2)"); + const [n, precision] = (0, import_internal.evalExpr)(obj, expr, options); + return (0, import_internal2.truncate)(n, precision ?? 0, { + name: "$round", + roundOff: true, + failOnError: options.failOnError + }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sigmoid.js +var require_sigmoid = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sigmoid.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sigmoid_exports = {}; + __export5(sigmoid_exports, { + $sigmoid: () => $sigmoid + }); + module.exports = __toCommonJS(sigmoid_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var PRECISION = 1e10; + var $sigmoid = (obj, expr, options) => { + if ((0, import_util3.isNil)(expr)) return null; + const args = (0, import_internal.evalExpr)(obj, expr, options); + const { input, onNull } = (0, import_util3.isObject)(args) ? args : { input: args }; + if ((0, import_util3.isNil)(input)) return (0, import_util3.isNumber)(onNull) ? onNull : null; + if ((0, import_util3.isNumber)(input)) { + const result = 1 / (1 + Math.exp(-input)); + return Math.round(result * PRECISION) / PRECISION; + } + return (0, import_internal2.errExpectNumber)(options.failOnError, "$sigmoid"); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sqrt.js +var require_sqrt = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sqrt.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sqrt_exports = {}; + __export5(sqrt_exports, { + $sqrt: () => $sqrt + }); + module.exports = __toCommonJS(sqrt_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $sqrt = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + const skip = !options.failOnError; + if ((0, import_util3.isNil)(n)) return null; + if (typeof n !== "number" || n < 0) { + (0, import_util3.assert)(skip, "$sqrt expression must resolve to non-negative number."); + return null; + } + return Math.sqrt(n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/subtract.js +var require_subtract = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/subtract.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var subtract_exports = {}; + __export5(subtract_exports, { + $subtract: () => $subtract + }); + module.exports = __toCommonJS(subtract_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $subtract = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), "$subtract expects array(2)"); + const args = (0, import_internal.evalExpr)(obj, expr, options); + if (args.some(import_util3.isNil)) return null; + const foe = options.failOnError; + const [a, b] = args; + if ((0, import_util3.isDate)(a) && (0, import_util3.isNumber)(b)) return new Date(+a - Math.round(b)); + if ((0, import_util3.isDate)(a) && (0, import_util3.isDate)(b)) return +a - +b; + if (args.every((v) => typeof v === "number")) return a - b; + if ((0, import_util3.isNumber)(a) && (0, import_util3.isDate)(b)) { + return (0, import_internal2.errInvalidArgs)(foe, "$subtract cannot subtract date from number"); + } + return (0, import_internal2.errExpectArray)(foe, "$subtract", { + size: 2, + type: "number|date" + }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/trunc.js +var require_trunc = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/trunc.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var trunc_exports = {}; + __export5(trunc_exports, { + $trunc: () => $trunc + }); + module.exports = __toCommonJS(trunc_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal5(); + var $trunc = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), "$trunc expects array(2)"); + const [n, precision] = (0, import_internal.evalExpr)(obj, expr, options); + return (0, import_internal2.truncate)(n, precision ?? 0, { + name: "$trunc", + roundOff: false, + failOnError: options.failOnError + }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/index.js +var require_arithmetic = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var arithmetic_exports = {}; + module.exports = __toCommonJS(arithmetic_exports); + __reExport(arithmetic_exports, require_abs(), module.exports); + __reExport(arithmetic_exports, require_add(), module.exports); + __reExport(arithmetic_exports, require_ceil(), module.exports); + __reExport(arithmetic_exports, require_divide(), module.exports); + __reExport(arithmetic_exports, require_exp(), module.exports); + __reExport(arithmetic_exports, require_floor(), module.exports); + __reExport(arithmetic_exports, require_ln(), module.exports); + __reExport(arithmetic_exports, require_log(), module.exports); + __reExport(arithmetic_exports, require_log10(), module.exports); + __reExport(arithmetic_exports, require_mod(), module.exports); + __reExport(arithmetic_exports, require_multiply(), module.exports); + __reExport(arithmetic_exports, require_pow(), module.exports); + __reExport(arithmetic_exports, require_round(), module.exports); + __reExport(arithmetic_exports, require_sigmoid(), module.exports); + __reExport(arithmetic_exports, require_sqrt(), module.exports); + __reExport(arithmetic_exports, require_subtract(), module.exports); + __reExport(arithmetic_exports, require_trunc(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayElemAt.js +var require_arrayElemAt = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayElemAt.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var arrayElemAt_exports = {}; + __export5(arrayElemAt_exports, { + $arrayElemAt: () => $arrayElemAt + }); + module.exports = __toCommonJS(arrayElemAt_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$arrayElemAt"; + var $arrayElemAt = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, `${OP} expects array(2)`); + const args = (0, import_internal.evalExpr)(obj, expr, options); + if (args.some(import_util3.isNil)) return null; + const foe = options.failOnError; + const [arr, index] = args; + if (!(0, import_util3.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, `${OP} arg1 `); + if (!(0, import_util3.isInteger)(index)) + return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `, import_internal2.INT_OPTS.int); + if (index < 0 && Math.abs(index) <= arr.length) { + return arr[(index + arr.length) % arr.length]; + } else if (index >= 0 && index < arr.length) { + return arr[index]; + } + return void 0; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayToObject.js +var require_arrayToObject = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayToObject.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var arrayToObject_exports = {}; + __export5(arrayToObject_exports, { + $arrayToObject: () => $arrayToObject + }); + module.exports = __toCommonJS(arrayToObject_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var ERR_OPTS = { + generic: { type: "key-value pairs" }, + array: { type: "[k,v]" }, + object: { type: "{k,v}" } + }; + var $arrayToObject = (obj, expr, options) => { + const foe = options.failOnError; + const arr = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(arr)) return null; + if (!(0, import_util3.isArray)(arr)) + return (0, import_internal2.errExpectArray)(foe, "$arrayToObject", ERR_OPTS.generic); + let tag2 = 0; + const newObj = {}; + for (const item of arr) { + if ((0, import_util3.isArray)(item)) { + const val = (0, import_util3.flatten)(item); + if (!tag2) tag2 = 1; + if (tag2 !== 1) { + return (0, import_internal2.errExpectArray)(foe, "$arrayToObject", ERR_OPTS.object); + } + const [k, v] = val; + newObj[k] = v; + } else if ((0, import_util3.isObject)(item) && (0, import_util3.has)(item, "k", "v")) { + if (!tag2) tag2 = 2; + if (tag2 !== 2) { + return (0, import_internal2.errExpectArray)(foe, "$arrayToObject", ERR_OPTS.array); + } + const { k, v } = item; + newObj[k] = v; + } else { + return (0, import_internal2.errExpectArray)(foe, "$arrayToObject", ERR_OPTS.generic); + } + } + return newObj; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/concatArrays.js +var require_concatArrays = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/concatArrays.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var concatArrays_exports = {}; + __export5(concatArrays_exports, { + $concatArrays: () => $concatArrays + }); + module.exports = __toCommonJS(concatArrays_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $concatArrays = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + if ((0, import_util3.isNil)(args)) return null; + if (!(0, import_util3.isArray)(args)) return (0, import_internal2.errExpectArray)(foe, "$concatArrays"); + let size = 0; + for (const arr of args) { + if ((0, import_util3.isNil)(arr)) return null; + if (!(0, import_util3.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, "$concatArrays"); + size += arr.length; + } + const result = new Array(size); + let i = 0; + for (const arr of args) for (const item of arr) result[i++] = item; + return result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/filter.js +var require_filter = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/filter.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var filter_exports = {}; + __export5(filter_exports, { + $filter: () => $filter + }); + module.exports = __toCommonJS(filter_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var import_internal3 = require_internal4(); + var $filter = (obj, expr, options) => { + (0, import_internal2.assert)( + (0, import_internal2.isObject)(expr) && (0, import_internal2.has)(expr, "input", "cond"), + "$filter expects object { input, as, cond, limit }" + ); + const input = (0, import_internal.evalExpr)(obj, expr.input, options); + const foe = options.failOnError; + if ((0, import_internal2.isNil)(input)) return null; + if (!(0, import_internal2.isArray)(input)) return (0, import_internal3.errExpectArray)(foe, "$filter 'input'"); + const limit = expr.limit ?? Math.max(input.length, 1); + if (!(0, import_internal2.isInteger)(limit) || limit < 1) + return (0, import_internal3.errExpectNumber)(foe, "$filter 'limit'", { min: 1, int: true }); + if (input.length === 0) return []; + const copts = import_internal.ComputeOptions.init(options); + const k = expr?.as || "this"; + const locals = { variables: {} }; + const res = []; + for (let i = 0, j = 0; i < input.length && j < limit; i++) { + locals.variables[k] = input[i]; + const cond = (0, import_internal.evalExpr)(obj, expr.cond, copts.update(locals)); + if ((0, import_internal2.truthy)(cond, options.useStrictMode)) { + res.push(input[i]); + j++; + } + } + return res; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/first.js +var require_first2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/first.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var first_exports = {}; + __export5(first_exports, { + $first: () => $first + }); + module.exports = __toCommonJS(first_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_first = require_first(); + var import_internal2 = require_internal4(); + var $first = (obj, expr, options) => { + if ((0, import_util3.isArray)(obj)) return (0, import_first.$first)(obj, expr, options); + const arr = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(arr)) return null; + if (!(0, import_util3.isArray)(arr)) { + return (0, import_internal2.errExpectArray)(options.failOnError, "$first"); + } + return (0, import_util3.flatten)(arr)[0]; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/firstN.js +var require_firstN2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/firstN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var firstN_exports = {}; + __export5(firstN_exports, { + $firstN: () => $firstN + }); + module.exports = __toCommonJS(firstN_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_firstN = require_firstN(); + var import_internal2 = require_internal4(); + var $firstN = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "n"), + "$firstN expects object { input, n }" + ); + if ((0, import_util3.isArray)(obj)) return (0, import_firstN.$firstN)(obj, expr, options); + const { input, n } = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(input)) return null; + if (!(0, import_util3.isArray)(input)) + return (0, import_internal2.errExpectArray)(options.failOnError, "$firstN 'input'"); + return (0, import_firstN.$firstN)(input, { n, input: "$$this" }, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/in.js +var require_in = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/in.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var in_exports = {}; + __export5(in_exports, { + $in: () => $in2 + }); + module.exports = __toCommonJS(in_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $in2 = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, "$in expects array(2)"); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const [item, arr] = args; + if (!(0, import_util3.isArray)(arr)) + return (0, import_internal2.errInvalidArgs)(options.failOnError, "$in arg2 "); + for (const v of arr) if ((0, import_util3.isEqual)(v, item)) return true; + return false; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/indexOfArray.js +var require_indexOfArray = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/indexOfArray.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var indexOfArray_exports = {}; + __export5(indexOfArray_exports, { + $indexOfArray: () => $indexOfArray + }); + module.exports = __toCommonJS(indexOfArray_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var import_internal3 = require_internal4(); + var OP = "$indexOfArray"; + var $indexOfArray = (obj, expr, options) => { + (0, import_internal2.assert)( + (0, import_internal2.isArray)(expr) && expr.length > 1 && expr.length < 5, + `${OP} expects array(4)` + ); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + const arr = args[0]; + if ((0, import_internal2.isNil)(arr)) return null; + if (!(0, import_internal2.isArray)(arr)) return (0, import_internal3.errExpectArray)(foe, `${OP} arg1 `); + const search = args[1]; + const start = args[2] ?? 0; + const end = args[3] ?? arr.length; + if (!(0, import_internal2.isInteger)(start) || start < 0) + return (0, import_internal3.errExpectNumber)(foe, `${OP} arg3 `, import_internal3.INT_OPTS.pos); + if (!(0, import_internal2.isInteger)(end) || end < 0) + return (0, import_internal3.errExpectNumber)(foe, `${OP} arg4 `, import_internal3.INT_OPTS.pos); + if (start > end) return -1; + const input = start > 0 || end < arr.length ? arr.slice(start, end) : arr; + return input.findIndex((v) => (0, import_internal2.isEqual)(v, search)) + start; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/isArray.js +var require_isArray = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/isArray.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var isArray_exports = {}; + __export5(isArray_exports, { + $isArray: () => $isArray + }); + module.exports = __toCommonJS(isArray_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $isArray = (obj, expr, options) => { + let input = expr; + if ((0, import_util3.isArray)(expr)) { + (0, import_util3.assert)(expr.length === 1, "$isArray expects array(1)"); + input = expr[0]; + } + return (0, import_util3.isArray)((0, import_internal.evalExpr)(obj, input, options)); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/last.js +var require_last2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/last.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var last_exports = {}; + __export5(last_exports, { + $last: () => $last + }); + module.exports = __toCommonJS(last_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_last = require_last(); + var import_internal2 = require_internal4(); + var $last = (obj, expr, options) => { + if ((0, import_util3.isArray)(obj)) return (0, import_last.$last)(obj, expr, options); + const arr = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(arr)) return null; + if (!(0, import_util3.isArray)(arr) || arr.length === 0) { + return (0, import_internal2.errExpectArray)(options.failOnError, "$last", { size: 0 }); + } + return (0, import_util3.flatten)(arr)[arr.length - 1]; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/lastN.js +var require_lastN2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/lastN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var lastN_exports = {}; + __export5(lastN_exports, { + $lastN: () => $lastN + }); + module.exports = __toCommonJS(lastN_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_lastN = require_lastN(); + var import_internal2 = require_internal4(); + var $lastN = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "n"), + "$lastN expects object { input, n }" + ); + if ((0, import_util3.isArray)(obj)) return (0, import_lastN.$lastN)(obj, expr, options); + const { input, n } = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(input)) return null; + if (!(0, import_util3.isArray)(input)) { + return (0, import_internal2.errExpectArray)(options.failOnError, "$lastN 'input'"); + } + return (0, import_lastN.$lastN)(input, { n, input: "$$this" }, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/map.js +var require_map = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/map.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var map_exports = {}; + __export5(map_exports, { + $map: () => $map + }); + module.exports = __toCommonJS(map_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $map = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "in"), + "$map expects object { input, as, in }" + ); + const input = (0, import_internal.evalExpr)(obj, expr.input, options); + const foe = options.failOnError; + if ((0, import_util3.isNil)(input)) return null; + if (!(0, import_util3.isArray)(input)) return (0, import_internal2.errExpectArray)(foe, "$map 'input'"); + if (!(0, import_util3.isNil)(expr.as) && !(0, import_util3.isString)(expr.as)) + return (0, import_internal2.errExpectString)(foe, "$map 'as'"); + const copts = import_internal.ComputeOptions.init(options); + const k = expr.as || "this"; + const locals = { variables: {} }; + return input.map((o) => { + locals.variables[k] = o; + return (0, import_internal.evalExpr)(obj, expr.in, copts.update(locals)); + }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/maxN.js +var require_maxN2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/maxN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var maxN_exports = {}; + __export5(maxN_exports, { + $maxN: () => $maxN + }); + module.exports = __toCommonJS(maxN_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_maxN = require_maxN(); + var import_internal2 = require_internal4(); + var $maxN = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "n"), + "$maxN expects object { input, n }" + ); + if ((0, import_util3.isArray)(obj)) return (0, import_maxN.$maxN)(obj, expr, options); + const { input, n } = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(input)) return null; + if (!(0, import_util3.isArray)(input)) + return (0, import_internal2.errExpectArray)(options.failOnError, "$maxN 'input'"); + return (0, import_maxN.$maxN)(input, { n, input: "$$this" }, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/minN.js +var require_minN2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/minN.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var minN_exports = {}; + __export5(minN_exports, { + $minN: () => $minN + }); + module.exports = __toCommonJS(minN_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_minN = require_minN(); + var import_internal2 = require_internal4(); + var $minN = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "n"), + "$minN expects object { input, n }" + ); + if ((0, import_util3.isArray)(obj)) return (0, import_minN.$minN)(obj, expr, options); + const { input, n } = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(input)) return null; + if (!(0, import_util3.isArray)(input)) + return (0, import_internal2.errExpectArray)(options.failOnError, "$minN 'input'"); + return (0, import_minN.$minN)(input, { n, input: "$$this" }, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/range.js +var require_range = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/range.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var range_exports = {}; + __export5(range_exports, { + $range: () => $range + }); + module.exports = __toCommonJS(range_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $range = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isArray)(expr) && expr.length > 1 && expr.length < 4, + "$range expects array(3)" + ); + const [start, end, arg3] = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + const step = arg3 ?? 1; + if (!(0, import_util3.isInteger)(start)) + return (0, import_internal2.errExpectNumber)(foe, `$range arg1 `, import_internal2.INT_OPTS.int); + if (!(0, import_util3.isInteger)(end)) + return (0, import_internal2.errExpectNumber)(foe, `$range arg2 `, import_internal2.INT_OPTS.int); + if (!(0, import_util3.isInteger)(step) || step === 0) + return (0, import_internal2.errExpectNumber)(foe, `$range arg3 `, import_internal2.INT_OPTS.nzero); + const result = new Array(); + let counter = start; + while (counter < end && step > 0 || counter > end && step < 0) { + result.push(counter); + counter += step; + } + return result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reduce.js +var require_reduce = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reduce.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var reduce_exports = {}; + __export5(reduce_exports, { + $reduce: () => $reduce + }); + module.exports = __toCommonJS(reduce_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + function $reduce(obj, expr, options) { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "initialValue", "in"), + "$reduce expects object { input, initialValue, in }" + ); + const input = (0, import_internal.evalExpr)(obj, expr.input, options); + const initialValue = (0, import_internal.evalExpr)(obj, expr.initialValue, options); + const inExpr = expr["in"]; + if ((0, import_util3.isNil)(input)) return null; + if (!(0, import_util3.isArray)(input)) + return (0, import_internal2.errExpectArray)(options.failOnError, "$reduce 'input'"); + const copts = import_internal.ComputeOptions.init(options); + const locals = { variables: { value: null } }; + let result = initialValue; + for (let i = 0; i < input.length; i++) { + locals.variables.value = result; + result = (0, import_internal.evalExpr)(input[i], inExpr, copts.update(locals)); + } + return result; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reverseArray.js +var require_reverseArray = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reverseArray.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var reverseArray_exports = {}; + __export5(reverseArray_exports, { + $reverseArray: () => $reverseArray + }); + module.exports = __toCommonJS(reverseArray_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $reverseArray = (obj, expr, options) => { + const arr = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(arr)) return null; + if (!(0, import_util3.isArray)(arr)) + return (0, import_internal2.errExpectArray)(options.failOnError, "$reverseArray"); + return arr.slice().reverse(); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/size.js +var require_size = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/size.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var size_exports = {}; + __export5(size_exports, { + $size: () => $size + }); + module.exports = __toCommonJS(size_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $size = (obj, expr, options) => { + const value = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(value)) return null; + return (0, import_util3.isArray)(value) ? value.length : (0, import_internal2.errExpectNumber)(options.failOnError, "$size"); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/slice.js +var require_slice = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/slice.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var slice_exports = {}; + __export5(slice_exports, { + $slice: () => $slice + }); + module.exports = __toCommonJS(slice_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $slice = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isArray)(expr) && expr.length > 1 && expr.length < 4, + "$slice expects array(3)" + ); + const foe = options.failOnError; + const args = (0, import_internal.evalExpr)(obj, expr, options); + const arr = args[0]; + let skip = args[1]; + let limit = args[2]; + if (!(0, import_util3.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, "$slice arg1 "); + if (!(0, import_util3.isInteger)(skip)) + return (0, import_internal2.errExpectNumber)(foe, "$slice arg2 ", import_internal2.INT_OPTS.int); + if (!(0, import_util3.isNil)(limit) && !(0, import_util3.isInteger)(limit)) + return (0, import_internal2.errExpectNumber)(foe, "$slice arg3 ", import_internal2.INT_OPTS.int); + if ((0, import_util3.isNil)(limit)) { + if (skip < 0) { + skip = Math.max(0, arr.length + skip); + } else { + limit = skip; + skip = 0; + } + } else { + if (skip < 0) { + skip = Math.max(0, arr.length + skip); + } + if (limit < 1) { + return (0, import_internal2.errExpectNumber)(foe, "$slice arg3 ", import_internal2.INT_OPTS.pos); + } + limit += skip; + } + return arr.slice(skip, limit); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/sortArray.js +var require_sortArray = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/sortArray.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sortArray_exports = {}; + __export5(sortArray_exports, { + $sortArray: () => $sortArray + }); + module.exports = __toCommonJS(sortArray_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + var import_sort = require_sort(); + var import_internal2 = require_internal4(); + var $sortArray = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && "input" in expr && "sortBy" in expr, + "$sortArray expects object { input, sortBy }" + ); + const { input, sortBy } = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(input)) return null; + if (!(0, import_util3.isArray)(input)) + return (0, import_internal2.errExpectArray)(options.failOnError, "$sortArray 'input'"); + if ((0, import_util3.isObject)(sortBy)) { + return (0, import_sort.$sort)((0, import_lazy.Lazy)(input), sortBy, options).collect(); + } + const result = input.slice().sort(import_util3.compare); + if (sortBy === -1) result.reverse(); + return result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/zip.js +var require_zip = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/zip.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var zip_exports = {}; + __export5(zip_exports, { + $zip: () => $zip + }); + module.exports = __toCommonJS(zip_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $zip = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "inputs"), + "$zip received invalid arguments" + ); + const inputs = (0, import_internal.evalExpr)(obj, expr.inputs, options); + const defaults = (0, import_internal.evalExpr)(obj, expr.defaults, options) ?? []; + const useLongestLength = expr.useLongestLength ?? false; + const foe = options.failOnError; + if ((0, import_util3.isNil)(inputs)) return null; + if (!(0, import_util3.isArray)(inputs)) return (0, import_internal2.errExpectArray)(foe, "$zip 'inputs'"); + let invalid = 0; + for (const elem of inputs) { + if ((0, import_util3.isNil)(elem)) return null; + if (!(0, import_util3.isArray)(elem)) invalid++; + } + if (invalid) return (0, import_internal2.errExpectArray)(foe, "$zip elements of 'inputs'"); + if (!(0, import_util3.isBoolean)(useLongestLength)) + (0, import_internal2.errInvalidArgs)(foe, "$zip 'useLongestLength' must be boolean"); + if ((0, import_util3.isArray)(defaults) && defaults.length > 0) { + (0, import_util3.assert)( + useLongestLength && defaults.length === inputs.length, + "$zip 'useLongestLength' must be set to true to use 'defaults'" + ); + } + let zipCount = 0; + for (const arr of inputs) { + zipCount = useLongestLength ? Math.max(zipCount, arr.length) : Math.min(zipCount || arr.length, arr.length); + } + const result = []; + for (let i = 0; i < zipCount; i++) { + const temp = inputs.map((val, index) => { + return (0, import_util3.isNil)(val[i]) ? defaults[index] ?? null : val[i]; + }); + result.push(temp); + } + return result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/index.js +var require_array = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var array_exports = {}; + module.exports = __toCommonJS(array_exports); + __reExport(array_exports, require_arrayElemAt(), module.exports); + __reExport(array_exports, require_arrayToObject(), module.exports); + __reExport(array_exports, require_concatArrays(), module.exports); + __reExport(array_exports, require_filter(), module.exports); + __reExport(array_exports, require_first2(), module.exports); + __reExport(array_exports, require_firstN2(), module.exports); + __reExport(array_exports, require_in(), module.exports); + __reExport(array_exports, require_indexOfArray(), module.exports); + __reExport(array_exports, require_isArray(), module.exports); + __reExport(array_exports, require_last2(), module.exports); + __reExport(array_exports, require_lastN2(), module.exports); + __reExport(array_exports, require_map(), module.exports); + __reExport(array_exports, require_maxN2(), module.exports); + __reExport(array_exports, require_minN2(), module.exports); + __reExport(array_exports, require_range(), module.exports); + __reExport(array_exports, require_reduce(), module.exports); + __reExport(array_exports, require_reverseArray(), module.exports); + __reExport(array_exports, require_size(), module.exports); + __reExport(array_exports, require_slice(), module.exports); + __reExport(array_exports, require_sortArray(), module.exports); + __reExport(array_exports, require_zip(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/_internal.js +var require_internal6 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + processBitwise: () => processBitwise + }); + module.exports = __toCommonJS(internal_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + function processBitwise(obj, expr, options, operator, fn) { + (0, import_util3.assert)((0, import_util3.isArray)(expr), `${operator} expects array as argument`); + const nums = (0, import_internal.evalExpr)(obj, expr, options); + let t_num = true; + for (const v of nums) { + if ((0, import_util3.isNil)(v)) return null; + t_num && (t_num = (0, import_util3.isInteger)(v)); + } + if (t_num) return fn(nums); + return (0, import_internal2.errInvalidArgs)( + options.failOnError, + `${operator} array elements must resolve to integers` + ); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitAnd.js +var require_bitAnd = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitAnd.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitAnd_exports = {}; + __export5(bitAnd_exports, { + $bitAnd: () => $bitAnd + }); + module.exports = __toCommonJS(bitAnd_exports); + var import_internal = require_internal6(); + var $bitAnd = (obj, expr, options) => (0, import_internal.processBitwise)( + obj, + expr, + options, + "$bitAnd", + (nums) => nums.reduce((a, b) => a & b, -1) + ); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitNot.js +var require_bitNot = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitNot.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitNot_exports = {}; + __export5(bitNot_exports, { + $bitNot: () => $bitNot + }); + module.exports = __toCommonJS(bitNot_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $bitNot = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(n)) return null; + if (!(0, import_util3.isInteger)(n)) + return (0, import_internal2.errExpectNumber)(options.failOnError, "$bitNot", import_internal2.INT_OPTS.int); + return ~n; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitOr.js +var require_bitOr = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitOr.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitOr_exports = {}; + __export5(bitOr_exports, { + $bitOr: () => $bitOr + }); + module.exports = __toCommonJS(bitOr_exports); + var import_internal = require_internal6(); + var $bitOr = (obj, expr, options) => (0, import_internal.processBitwise)( + obj, + expr, + options, + "$bitOr", + (nums) => nums.reduce((a, b) => a | b, 0) + ); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitXor.js +var require_bitXor = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitXor.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitXor_exports = {}; + __export5(bitXor_exports, { + $bitXor: () => $bitXor + }); + module.exports = __toCommonJS(bitXor_exports); + var import_internal = require_internal6(); + var $bitXor = (obj, expr, options) => (0, import_internal.processBitwise)( + obj, + expr, + options, + "$bitXor", + (nums) => nums.reduce((a, b) => a ^ b, 0) + ); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/index.js +var require_bitwise = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitwise_exports = {}; + module.exports = __toCommonJS(bitwise_exports); + __reExport(bitwise_exports, require_bitAnd(), module.exports); + __reExport(bitwise_exports, require_bitNot(), module.exports); + __reExport(bitwise_exports, require_bitOr(), module.exports); + __reExport(bitwise_exports, require_bitXor(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/and.js +var require_and = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/and.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var and_exports = {}; + __export5(and_exports, { + $and: () => $and + }); + module.exports = __toCommonJS(and_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var $and = (obj, expr, options) => { + (0, import_internal2.assert)((0, import_internal2.isArray)(expr), "$and expects array"); + const mode = options.useStrictMode; + return expr.every((e) => (0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, e, options), mode)); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/not.js +var require_not = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/not.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var not_exports = {}; + __export5(not_exports, { + $not: () => $not + }); + module.exports = __toCommonJS(not_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $not = (obj, expr, options) => { + const booleanExpr = (0, import_util3.ensureArray)(expr); + if (booleanExpr.length === 0) return false; + if (booleanExpr.length > 1) + return (0, import_internal2.errExpectArray)(options.failOnError, "$not", { size: 1 }); + return !(0, import_internal.evalExpr)(obj, booleanExpr[0], options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/or.js +var require_or = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/or.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var or_exports = {}; + __export5(or_exports, { + $or: () => $or + }); + module.exports = __toCommonJS(or_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var $or = (obj, expr, options) => { + (0, import_internal2.assert)((0, import_internal2.isArray)(expr), "$or expects array of expressions"); + const strict = options.useStrictMode; + for (const v of expr) + if ((0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, v, options), strict)) return true; + return false; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/index.js +var require_boolean = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var boolean_exports = {}; + module.exports = __toCommonJS(boolean_exports); + __reExport(boolean_exports, require_and(), module.exports); + __reExport(boolean_exports, require_not(), module.exports); + __reExport(boolean_exports, require_or(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/cmp.js +var require_cmp = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/cmp.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var cmp_exports = {}; + __export5(cmp_exports, { + $cmp: () => $cmp + }); + module.exports = __toCommonJS(cmp_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $cmp = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, "$cmp expects array(2)"); + const [a, b] = (0, import_internal.evalExpr)(obj, expr, options); + return (0, import_util3.compare)(a, b); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/limit.js +var require_limit = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/limit.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var limit_exports = {}; + __export5(limit_exports, { + $limit: () => $limit + }); + module.exports = __toCommonJS(limit_exports); + function $limit(coll, expr, _options2) { + return coll.take(expr); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/documents.js +var require_documents = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/documents.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var documents_exports = {}; + __export5(documents_exports, { + $documents: () => $documents + }); + module.exports = __toCommonJS(documents_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + function $documents(_, expr, options) { + const docs = (0, import_internal.evalExpr)(null, expr, options); + (0, import_util3.assert)((0, import_util3.isArray)(docs), "$documents expression must resolve to an array."); + const iter = (0, import_lazy.Lazy)(docs); + const mode = options.processingMode; + return mode & import_internal.ProcessingMode.CLONE_ALL ? iter.map((o) => (0, import_util3.cloneDeep)(o)) : iter; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/_internal.js +var require_internal7 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + filterDocumentsStage: () => filterDocumentsStage, + resolveCollection: () => resolveCollection, + validateProjection: () => validateProjection + }); + module.exports = __toCommonJS(internal_exports); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + var import_internal = require_internal(); + var import_documents = require_documents(); + var EMPTY = (0, import_lazy.Lazy)([]); + function filterDocumentsStage(pipeline, options) { + if (!pipeline) return {}; + const docs = pipeline[0]?.$documents; + if (!docs) return { pipeline }; + return { + documents: (0, import_documents.$documents)(EMPTY, docs, options).collect(), + pipeline: pipeline.slice(1) + }; + } + function validateProjection(expr, options, isRoot = true) { + const res = { + exclusions: [], + inclusions: [], + positional: 0 + }; + const keys = Object.keys(expr); + (0, import_internal.assert)(keys.length, "Invalid empty sub-projection"); + const idKey = options?.idKey; + let idKeyExcluded = false; + for (const k of keys) { + if (k.startsWith("$")) { + (0, import_internal.assert)( + !isRoot && keys.length === 1, + `FieldPath field names may not start with '$', given '${k}'.` + ); + return res; + } + if (k.endsWith(".$")) res.positional++; + const v = expr[k]; + if (v === false || (0, import_util3.isNumber)(v) && v === 0) { + if (k === idKey) { + idKeyExcluded = true; + } else res.exclusions.push(k); + } else if (!(0, import_util3.isObject)(v)) { + res.inclusions.push(k); + } else { + const meta3 = validateProjection(v, options, false); + if (!meta3.inclusions.length && !meta3.exclusions.length) { + if (!res.inclusions.includes(k)) res.inclusions.push(k); + } else { + for (const n of meta3.exclusions) res.exclusions.push(`${k}.${n}`); + for (const n of meta3.inclusions) res.inclusions.push(`${k}.${n}`); + } + res.positional += meta3.positional; + } + (0, import_internal.assert)( + !(res.exclusions.length && res.inclusions.length), + "Cannot do exclusion and inclusion in projection." + ); + (0, import_internal.assert)( + res.positional <= 1, + "Cannot specify more than one positional projection." + ); + } + if (idKeyExcluded) { + res.exclusions.push(idKey); + } + if (isRoot) { + const p = new import_internal.PathValidator(); + for (const k of res.exclusions) (0, import_internal.assert)(p.add(k), `Path collision at ${k}.`); + for (const k of res.inclusions) (0, import_internal.assert)(p.add(k), `Path collision at ${k}.`); + res.exclusions.sort(); + res.inclusions.sort(); + } + return res; + } + function resolveCollection(op, expr, options) { + if ((0, import_internal.isString)(expr)) { + (0, import_internal.assert)( + options.collectionResolver, + `${op} requires 'collectionResolver' option to resolve named collection` + ); + } + const coll = (0, import_internal.isString)(expr) ? options.collectionResolver(expr) : expr; + (0, import_internal.assert)((0, import_internal.isArray)(coll), `${op} could not resolve input collection`); + return coll; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/project.js +var require_project = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/project.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var project_exports = {}; + __export5(project_exports, { + $project: () => $project + }); + module.exports = __toCommonJS(project_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var import_internal3 = require_internal7(); + var OP = "$project"; + function $project(coll, expr, options) { + if ((0, import_internal2.isEmpty)(expr)) return coll; + const meta3 = (0, import_internal3.validateProjection)(expr, options); + const handler = createHandler(expr, import_internal.ComputeOptions.init(options), meta3); + return coll.map(handler); + } + function createHandler(expr, options, meta3) { + const idKey = options.idKey; + const { exclusions, inclusions } = meta3; + const handlers = {}; + const resolveOpts = { + preserveMissing: true + }; + for (const k of exclusions) { + handlers[k] = (t, _) => { + (0, import_internal2.removeValue)(t, k, { descendArray: true }); + }; + } + for (const selector of inclusions) { + const v = (0, import_internal2.resolve)(expr, selector) ?? expr[selector]; + if (selector.endsWith(".$") && v === 1) { + const cond = options?.local?.condition ?? {}; + (0, import_internal2.assert)(cond, `${OP}: positional operator '.$' requires array condition.`); + const field = selector.slice(0, -2); + handlers[field] = getPositionalFilter(field, cond, options); + continue; + } + if ((0, import_internal2.isArray)(v)) { + handlers[selector] = (t, o) => { + options.update({ root: o }); + const newVal = v.map((e) => (0, import_internal.evalExpr)(o, e, options) ?? null); + (0, import_internal2.setValue)(t, selector, newVal); + }; + } else if ((0, import_internal2.isNumber)(v) || v === true) { + handlers[selector] = (t, o) => { + options.update({ root: o }); + const extractedVal = (0, import_internal2.resolveGraph)(o, selector, resolveOpts); + mergeInto(t, extractedVal); + }; + } else if (!(0, import_internal2.isObject)(v)) { + handlers[selector] = (t, o) => { + options.update({ root: o }); + const newVal = (0, import_internal.evalExpr)(o, v, options); + (0, import_internal2.setValue)(t, selector, newVal); + }; + } else { + const opKeys = Object.keys(v); + (0, import_internal2.assert)( + opKeys.length === 1 && (0, import_internal2.isOperator)(opKeys[0]), + "Not a valid operator" + ); + const operator = opKeys[0]; + const opExpr = v[operator]; + const fn = options.context.getOperator(import_internal.OpType.PROJECTION, operator); + const foundSlice = operator === "$slice"; + if (!fn || foundSlice && !(0, import_internal2.ensureArray)(opExpr).every(import_internal2.isNumber)) { + handlers[selector] = (t, o) => { + options.update({ root: o }); + const newval = (0, import_internal.evalExpr)(o, v, options); + (0, import_internal2.setValue)(t, selector, newval); + }; + } else { + handlers[selector] = (t, o) => { + options.update({ root: o }); + const newval = fn(o, opExpr, selector, options); + (0, import_internal2.setValue)(t, selector, newval); + }; + } + } + } + const onlyIdKeyExcluded = exclusions.length === 1 && exclusions.includes(idKey); + const noIdKeyExcluded = !exclusions.includes(idKey); + const noInclusions = !inclusions.length; + const allKeysIncluded = noInclusions && onlyIdKeyExcluded || noInclusions && exclusions.length && !onlyIdKeyExcluded; + return (o) => { + const newObj = {}; + if (allKeysIncluded) Object.assign(newObj, o); + for (const k in handlers) { + handlers[k](newObj, o); + } + if (!noInclusions) (0, import_internal2.filterMissing)(newObj); + if (noIdKeyExcluded && !(0, import_internal2.has)(newObj, idKey) && (0, import_internal2.has)(o, idKey)) { + newObj[idKey] = (0, import_internal2.resolve)(o, idKey); + } + return newObj; + }; + } + var findMatches = (o, key, leaf, pred) => { + let arr = (0, import_internal2.resolve)(o, key); + if (!(0, import_internal2.isArray)(arr)) arr = (0, import_internal2.resolve)(arr, leaf); + (0, import_internal2.assert)((0, import_internal2.isArray)(arr), `${OP}: field '${key}' must resolve to array`); + const matches = []; + for (let i = 0; i < arr.length; i++) { + if (pred({ [leaf]: [arr[i]] })) matches.push(i); + } + return matches; + }; + var complement = (p) => (e) => !p(e); + var COMPOUND_OPS = { $and: 1, $or: 1, $nor: 1 }; + function getPositionalFilter(field, condition, options) { + const stack = Object.entries(condition).slice(); + const selectors = { + $and: [], + $or: [] + }; + for (let i = 0; i < stack.length; i++) { + const [key, val, op] = stack[i]; + if (key === field || key.startsWith(field + ".")) { + const normalizedExpr = (0, import_internal2.normalize)(val); + const operator = Object.keys(normalizedExpr)[0]; + const expr = normalizedExpr[operator]; + const fn = options.context.getOperator( + import_internal.OpType.QUERY, + operator + ); + const leaf2 = key.substring(key.lastIndexOf(".") + 1); + const pred = fn(leaf2, expr, options); + if (!op || op === "$and") { + selectors.$and.push([key, pred, leaf2]); + } else if (op === "$nor") { + selectors.$and.push([key, complement(pred), leaf2]); + } else if (op === "$or") { + selectors.$or.push([key, pred, leaf2]); + } + } else if ((0, import_internal2.isOperator)(key)) { + (0, import_internal2.assert)( + !!COMPOUND_OPS[key], + `${OP}: '${key}' is not allowed in this context` + ); + for (const item of val) { + for (const k of Object.keys(item)) stack.push([k, item[k], key]); + } + } + } + const sep = field.lastIndexOf("."); + const parent = field.substring(0, sep) || field; + const leaf = field.substring(sep + 1); + return (t, o) => { + const matches = []; + for (const [key, pred, leaf2] of selectors.$and) { + matches.push(findMatches(o, key, leaf2, pred)); + } + if (selectors.$or.length) { + const orMatches = []; + for (const [key, pred, leaf2] of selectors.$or) { + orMatches.push(...findMatches(o, key, leaf2, pred)); + } + matches.push((0, import_internal2.unique)(orMatches)); + } + const i = (0, import_internal2.intersection)(matches).sort()[0]; + let first = (0, import_internal2.resolve)(o, field)[i]; + if (parent != leaf && !(0, import_internal2.isObject)(first)) { + first = { [leaf]: first }; + } + (0, import_internal2.setValue)(t, parent, [first]); + }; + } + function mergeInto(target, input) { + if (target === import_internal2.MISSING || (0, import_internal2.isNil)(target)) return input; + if ((0, import_internal2.isNil)(input)) return target; + const out = target; + const src = input; + for (const k of Object.keys(input)) { + out[k] = mergeInto(out[k], src[k]); + } + return out; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/skip.js +var require_skip = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/skip.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var skip_exports = {}; + __export5(skip_exports, { + $skip: () => $skip + }); + module.exports = __toCommonJS(skip_exports); + var import_util3 = require_util(); + function $skip(coll, expr, _options2) { + (0, import_util3.assert)(expr >= 0, "$skip value must be a non-negative integer"); + return coll.drop(expr); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/cursor.js +var require_cursor = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/cursor.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var cursor_exports = {}; + __export5(cursor_exports, { + Cursor: () => Cursor + }); + module.exports = __toCommonJS(cursor_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_limit = require_limit(); + var import_project = require_project(); + var import_skip = require_skip(); + var import_sort = require_sort(); + var import_util3 = require_util(); + var OPERATORS2 = { $sort: import_sort.$sort, $skip: import_skip.$skip, $limit: import_limit.$limit }; + var _source, _predicate, _projection, _options2, _operators, _result, _buffer; + var Cursor = class { + /** + * Creates an instance of the Cursor class. + * + * @param source - The source of data to be iterated over. + * @param predicate - A function or condition to filter the data. + * @param projection - An object specifying the fields to include or exclude in the result. + * @param options - Optional settings to customize the behavior of the cursor. + */ + constructor(source, predicate, projection, options) { + __privateAdd(this, _source); + __privateAdd(this, _predicate); + __privateAdd(this, _projection); + __privateAdd(this, _options2); + __privateAdd(this, _operators, {}); + __privateAdd(this, _result, null); + __privateAdd(this, _buffer, []); + __privateSet(this, _source, source); + __privateSet(this, _predicate, predicate); + __privateSet(this, _projection, projection); + __privateSet(this, _options2, options); + } + /** Returns the iterator from running the query */ + fetch() { + if (__privateGet(this, _result)) return __privateGet(this, _result); + __privateSet(this, _result, (0, import_lazy.Lazy)(__privateGet(this, _source)).filter(__privateGet(this, _predicate))); + const mode = __privateGet(this, _options2).processingMode; + if (mode & import_internal.ProcessingMode.CLONE_INPUT) __privateGet(this, _result).map((o) => (0, import_util3.cloneDeep)(o)); + for (const op of Object.keys(OPERATORS2)) { + if ((0, import_util3.has)(__privateGet(this, _operators), op)) { + const f = OPERATORS2[op]; + __privateSet(this, _result, f(__privateGet(this, _result), __privateGet(this, _operators)[op], __privateGet(this, _options2))); + } + } + if (Object.keys(__privateGet(this, _projection)).length) { + __privateSet(this, _result, (0, import_project.$project)(__privateGet(this, _result), __privateGet(this, _projection), __privateGet(this, _options2))); + } + if (mode & import_internal.ProcessingMode.CLONE_OUTPUT) __privateGet(this, _result).map((o) => (0, import_util3.cloneDeep)(o)); + return __privateGet(this, _result); + } + /** Returns an iterator with the buffered data included */ + fetchAll() { + const buffered = (0, import_lazy.Lazy)(Array.from(__privateGet(this, _buffer))); + __privateGet(this, _buffer).length = 0; + return (0, import_lazy.concat)(buffered, this.fetch()); + } + /** + * Return remaining objects in the cursor as an array. This method exhausts the cursor + * @returns {Array} + */ + all() { + return this.fetchAll().collect(); + } + /** + * Returns a cursor that begins returning results only after passing or skipping a number of documents. + * @param {Number} n the number of results to skip. + * @return {Cursor} Returns the cursor, so you can chain this call. + */ + skip(n) { + __privateGet(this, _operators)["$skip"] = n; + return this; + } + /** + * Limits the number of items returned by the cursor. + * + * @param n - The maximum number of items to return. + * @returns The current cursor instance for chaining. + */ + limit(n) { + __privateGet(this, _operators)["$limit"] = n; + return this; + } + /** + * Returns results ordered according to a sort specification. + * @param {AnyObject} modifier an object of key and values specifying the sort order. 1 for ascending and -1 for descending + * @return {Cursor} Returns the cursor, so you can chain this call. + */ + sort(modifier) { + __privateGet(this, _operators)["$sort"] = modifier; + return this; + } + /** + * Sets the collation options for the cursor. + * Collation allows users to specify language-specific rules for string comparison, + * such as case sensitivity and accent marks. + * + * @param spec - The collation specification to apply. + * @returns The current cursor instance for chaining. + */ + collation(spec) { + __privateSet(this, _options2, { ...__privateGet(this, _options2), collation: spec }); + return this; + } + /** + * Retrieves the next item in the cursor. + */ + next() { + if (__privateGet(this, _buffer).length > 0) { + return __privateGet(this, _buffer).pop(); + } + const o = this.fetch().next(); + if (o.done) return void 0; + return o.value; + } + /** + * Determines if there are more elements available in the cursor. + * + * @returns {boolean} `true` if there are more elements to iterate over, otherwise `false`. + */ + hasNext() { + if (__privateGet(this, _buffer).length > 0) return true; + const o = this.fetch().next(); + if (o.done) return false; + __privateGet(this, _buffer).push(o.value); + return true; + } + /** + * Returns an iterator for the cursor, allowing it to be used in `for...of` loops. + * The iterator fetches all the results from the cursor. + * + * @returns {Iterator} An iterator over the fetched results. + */ + [Symbol.iterator]() { + return this.fetchAll(); + } + }; + _source = new WeakMap(); + _predicate = new WeakMap(); + _projection = new WeakMap(); + _options2 = new WeakMap(); + _operators = new WeakMap(); + _result = new WeakMap(); + _buffer = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/query.js +var require_query = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/query.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var query_exports = {}; + __export5(query_exports, { + Query: () => Query2 + }); + module.exports = __toCommonJS(query_exports); + var import_internal = require_internal2(); + var import_cursor = require_cursor(); + var import_util3 = require_util(); + var TOP_LEVEL_OPS = /* @__PURE__ */ new Set(["$and", "$or", "$nor", "$expr", "$jsonSchema"]); + var _compiled, _condition, _options2; + var Query2 = class { + /** + * Creates an instance of the query with the specified condition and options. + * This object is preloaded with all query and projection operators. + * + * @param condition - The query condition object used to define the criteria for matching documents. + * @param options - Optional configuration settings to customize the query behavior. + */ + constructor(condition, options) { + __privateAdd(this, _compiled); + __privateAdd(this, _condition); + __privateAdd(this, _options2); + __privateSet(this, _condition, (0, import_util3.cloneDeep)(condition)); + __privateSet(this, _options2, import_internal.ComputeOptions.init(options).update({ + condition + })); + __privateSet(this, _compiled, []); + this.compile(); + } + compile() { + (0, import_util3.assert)( + (0, import_util3.isObject)(__privateGet(this, _condition)), + `query criteria must be an object: ${JSON.stringify(__privateGet(this, _condition))}` + ); + const whereOperator = {}; + for (const field of Object.keys(__privateGet(this, _condition))) { + const expr = __privateGet(this, _condition)[field]; + if ("$where" === field) { + (0, import_util3.assert)( + __privateGet(this, _options2).scriptEnabled, + "$where operator requires 'scriptEnabled' option to be true." + ); + Object.assign(whereOperator, { field, expr }); + } else if (TOP_LEVEL_OPS.has(field)) { + this.processOperator(field, field, expr); + } else { + (0, import_util3.assert)(!(0, import_util3.isOperator)(field), `unknown top level operator: ${field}`); + const normalizedExpr = (0, import_util3.normalize)(expr); + for (const operator of Object.keys(normalizedExpr)) { + this.processOperator(field, operator, normalizedExpr[operator]); + } + } + if (whereOperator.field) { + this.processOperator( + whereOperator.field, + whereOperator.field, + whereOperator.expr + ); + } + } + } + processOperator(field, operator, value) { + const fn = __privateGet(this, _options2).context.getOperator( + import_internal.OpType.QUERY, + operator + ); + (0, import_util3.assert)(!!fn, `unknown query operator ${operator}`); + __privateGet(this, _compiled).push(fn(field, value, __privateGet(this, _options2))); + } + /** + * Tests whether the given object satisfies all compiled predicates. + * + * @template T - The type of the object to test. + * @param obj - The object to be tested against the compiled predicates. + * @returns `true` if the object satisfies all predicates, otherwise `false`. + */ + test(obj) { + return __privateGet(this, _compiled).every((p) => p(obj)); + } + /** + * Returns a cursor for iterating over the items in the given collection that match the query criteria. + * + * @typeParam T - The type of the items in the resulting cursor. + * @param collection - The source collection to search through. + * @param projection - An optional object specifying fields to include or exclude + * in the returned items. + * @returns A `Cursor` instance for iterating over the matching items. + */ + find(collection, projection) { + return new import_cursor.Cursor( + collection, + (o) => this.test(o), + projection || {}, + __privateGet(this, _options2) + ); + } + }; + _compiled = new WeakMap(); + _condition = new WeakMap(); + _options2 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/_predicates.js +var require_predicates = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/_predicates.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var predicates_exports = {}; + __export5(predicates_exports, { + $all: () => $all, + $elemMatch: () => $elemMatch, + $eq: () => $eq2, + $gt: () => $gt2, + $gte: () => $gte2, + $in: () => $in2, + $lt: () => $lt2, + $lte: () => $lte2, + $mod: () => $mod, + $ne: () => $ne2, + $nin: () => $nin2, + $regex: () => $regex, + $size: () => $size, + $type: () => $type, + processExpression: () => processExpression, + processQuery: () => processQuery + }); + module.exports = __toCommonJS(predicates_exports); + var import_internal = require_internal2(); + var import_query = require_query(); + var import_internal2 = require_internal(); + function elemMatchPredicate(criteria, options) { + let format = (x) => x; + let wrap4 = true; + for (const k of Object.keys(criteria)) { + wrap4 && (wrap4 = (0, import_internal2.isOperator)(k) && "$and" !== k && "$or" !== k && "$nor" !== k); + if (!wrap4) break; + } + if (wrap4) { + criteria = { field: criteria }; + format = (x) => ({ field: x }); + } + const q = new import_query.Query(criteria, options); + return (v) => q.test(format(v)); + } + function processQuery(selector, value, options, predicate) { + const pathArray = selector.split("."); + const depth = Math.max(1, pathArray.length - 1); + const copts = import_internal.ComputeOptions.init(options).update({ depth }); + const opts = { unwrapArray: true, pathArray }; + if (predicate === $elemMatch) { + value = elemMatchPredicate(value, options); + } + return (o) => { + const lhs = (0, import_internal2.resolve)(o, selector, opts); + return predicate(lhs, value, copts); + }; + } + function processExpression(obj, expr, options, predicate) { + (0, import_internal2.assert)( + (0, import_internal2.isArray)(expr) && expr.length === 2, + `${predicate.name} expects array(2)` + ); + const [lhs, rhs] = (0, import_internal.evalExpr)(obj, expr, options); + return predicate(lhs, rhs, options); + } + function $eq2(a, b, options) { + if ((0, import_internal2.isEqual)(a, b)) return true; + if ((0, import_internal2.isNil)(a) && (0, import_internal2.isNil)(b)) return true; + if ((0, import_internal2.isArray)(a)) { + const depth = options?.local?.depth ?? 1; + return a.some((v) => (0, import_internal2.isEqual)(v, b)) || (0, import_internal2.flatten)(a, depth).some((v) => (0, import_internal2.isEqual)(v, b)); + } + return false; + } + function $ne2(a, b, options) { + return !$eq2(a, b, options); + } + function $in2(a, b, _options2) { + if ((0, import_internal2.isNil)(a)) return b.some((v) => v === null); + return (0, import_internal2.intersection)([(0, import_internal2.ensureArray)(a), b]).length > 0; + } + function $nin2(a, b, options) { + return !$in2(a, b, options); + } + function $lt2(a, b, _options2) { + return compare2(a, b, (x, y) => (0, import_internal2.compare)(x, y) < 0); + } + function $lte2(a, b, _options2) { + return compare2(a, b, (x, y) => (0, import_internal2.compare)(x, y) <= 0); + } + function $gt2(a, b, _options2) { + return compare2(a, b, (x, y) => (0, import_internal2.compare)(x, y) > 0); + } + function $gte2(a, b, _options2) { + return compare2(a, b, (x, y) => (0, import_internal2.compare)(x, y) >= 0); + } + function $mod(a, b, _options2) { + return (0, import_internal2.ensureArray)(a).some( + (x) => b.length === 2 && x % b[0] === b[1] + ); + } + function $regex(a, b, options) { + const lhs = (0, import_internal2.ensureArray)(a); + const match2 = (x) => (0, import_internal2.isString)(x) && (0, import_internal2.truthy)(b.exec(x), options?.useStrictMode); + return lhs.some(match2) || (0, import_internal2.flatten)(lhs, 1).some(match2); + } + function $all(values, rhs, options) { + if (!(0, import_internal2.isArray)(values) || !(0, import_internal2.isArray)(rhs) || !values.length || !rhs.length) { + return false; + } + let matched = true; + for (const expr of rhs) { + if (!matched) break; + if ((0, import_internal2.isObject)(expr) && Object.keys(expr)[0] === "$elemMatch") { + const criteria = expr["$elemMatch"]; + const pred = elemMatchPredicate(criteria, options); + matched = $elemMatch(values, pred, options); + } else if ((0, import_internal2.isRegExp)(expr)) { + matched = values.some((s) => (0, import_internal2.isString)(s) && expr.test(s)); + } else { + matched = values.some((v) => (0, import_internal2.isEqual)(expr, v)); + } + } + return matched; + } + function $size(a, b, _options2) { + return Array.isArray(a) && a.length === b; + } + function $elemMatch(a, b, _options2) { + if ((0, import_internal2.isArray)(a) && !(0, import_internal2.isEmpty)(a)) { + for (let i = 0, len = a.length; i < len; i++) if (b(a[i])) return true; + } + return false; + } + var isNull2 = (a) => a === null; + var compareFuncs = { + array: import_internal2.isArray, + boolean: import_internal2.isBoolean, + bool: import_internal2.isBoolean, + date: import_internal2.isDate, + number: import_internal2.isNumber, + int: import_internal2.isNumber, + long: import_internal2.isNumber, + double: import_internal2.isNumber, + decimal: import_internal2.isNumber, + null: isNull2, + object: import_internal2.isObject, + regexp: import_internal2.isRegExp, + regex: import_internal2.isRegExp, + string: import_internal2.isString, + // added for completeness + undefined: import_internal2.isNil, + // deprecated + // Mongo identifiers + 1: import_internal2.isNumber, + //double + 2: import_internal2.isString, + 3: import_internal2.isObject, + 4: import_internal2.isArray, + 6: import_internal2.isNil, + // deprecated + 8: import_internal2.isBoolean, + 9: import_internal2.isDate, + 10: isNull2, + 11: import_internal2.isRegExp, + 16: import_internal2.isNumber, + //int + 18: import_internal2.isNumber, + //long + 19: import_internal2.isNumber + //decimal + }; + function compareType(a, b, _) { + const f = compareFuncs[b]; + return f ? f(a) : false; + } + function $type(a, b, options) { + return (0, import_internal2.isArray)(b) ? b.findIndex((t) => compareType(a, t, options)) >= 0 : compareType(a, b, options); + } + function compare2(a, b, f) { + for (const v of (0, import_internal2.ensureArray)(a)) { + if ((0, import_internal2.typeOf)(v) === (0, import_internal2.typeOf)(b) && f(v, b)) return true; + } + return false; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/eq.js +var require_eq = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/eq.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var eq_exports = {}; + __export5(eq_exports, { + $eq: () => $eq2 + }); + module.exports = __toCommonJS(eq_exports); + var import_predicates = require_predicates(); + var $eq2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$eq); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gt.js +var require_gt = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gt.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var gt_exports = {}; + __export5(gt_exports, { + $gt: () => $gt2 + }); + module.exports = __toCommonJS(gt_exports); + var import_predicates = require_predicates(); + var $gt2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$gt); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gte.js +var require_gte = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gte.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var gte_exports = {}; + __export5(gte_exports, { + $gte: () => $gte2 + }); + module.exports = __toCommonJS(gte_exports); + var import_predicates = require_predicates(); + var $gte2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$gte); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lt.js +var require_lt = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lt.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var lt_exports = {}; + __export5(lt_exports, { + $lt: () => $lt2 + }); + module.exports = __toCommonJS(lt_exports); + var import_predicates = require_predicates(); + var $lt2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$lt); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lte.js +var require_lte = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lte.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var lte_exports = {}; + __export5(lte_exports, { + $lte: () => $lte2 + }); + module.exports = __toCommonJS(lte_exports); + var import_predicates = require_predicates(); + var $lte2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$lte); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/ne.js +var require_ne = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/ne.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var ne_exports = {}; + __export5(ne_exports, { + $ne: () => $ne2 + }); + module.exports = __toCommonJS(ne_exports); + var import_predicates = require_predicates(); + var $ne2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$ne); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/index.js +var require_comparison = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var comparison_exports = {}; + module.exports = __toCommonJS(comparison_exports); + __reExport(comparison_exports, require_cmp(), module.exports); + __reExport(comparison_exports, require_eq(), module.exports); + __reExport(comparison_exports, require_gt(), module.exports); + __reExport(comparison_exports, require_gte(), module.exports); + __reExport(comparison_exports, require_lt(), module.exports); + __reExport(comparison_exports, require_lte(), module.exports); + __reExport(comparison_exports, require_ne(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/cond.js +var require_cond = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/cond.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var cond_exports = {}; + __export5(cond_exports, { + $cond: () => $cond + }); + module.exports = __toCommonJS(cond_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var err = "$cond expects array(3) or object with 'if-then-else' expressions"; + var $cond = (obj, expr, options) => { + let ifExpr; + let thenExpr; + let elseExpr; + if ((0, import_internal2.isArray)(expr)) { + (0, import_internal2.assert)(expr.length === 3, err); + ifExpr = expr[0]; + thenExpr = expr[1]; + elseExpr = expr[2]; + } else { + (0, import_internal2.assert)((0, import_internal2.isObject)(expr), err); + ifExpr = expr.if; + thenExpr = expr.then; + elseExpr = expr.else; + } + const condition = (0, import_internal2.truthy)( + (0, import_internal.evalExpr)(obj, ifExpr, options), + options.useStrictMode + ); + return (0, import_internal.evalExpr)(obj, condition ? thenExpr : elseExpr, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/ifNull.js +var require_ifNull = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/ifNull.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var ifNull_exports = {}; + __export5(ifNull_exports, { + $ifNull: () => $ifNull + }); + module.exports = __toCommonJS(ifNull_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $ifNull = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), "$ifNull expects an array"); + let val = void 0; + for (const input of expr) { + val = (0, import_internal.evalExpr)(obj, input, options); + if (!(0, import_util3.isNil)(val)) return val; + } + return val; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/switch.js +var require_switch = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/switch.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var switch_exports = {}; + __export5(switch_exports, { + $switch: () => $switch + }); + module.exports = __toCommonJS(switch_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var $switch = (obj, expr, options) => { + (0, import_internal2.assert)((0, import_internal2.isObject)(expr), "$switch received invalid arguments"); + for (const { case: caseExpr, then } of expr.branches) { + const condition = (0, import_internal2.truthy)( + (0, import_internal.evalExpr)(obj, caseExpr, options), + options.useStrictMode + ); + if (condition) return (0, import_internal.evalExpr)(obj, then, options); + } + return (0, import_internal.evalExpr)(obj, expr.default, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/index.js +var require_conditional = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var conditional_exports = {}; + module.exports = __toCommonJS(conditional_exports); + __reExport(conditional_exports, require_cond(), module.exports); + __reExport(conditional_exports, require_ifNull(), module.exports); + __reExport(conditional_exports, require_switch(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/function.js +var require_function = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/function.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var function_exports = {}; + __export5(function_exports, { + $function: () => $function + }); + module.exports = __toCommonJS(function_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $function = (obj, expr, options) => { + (0, import_util3.assert)( + options.scriptEnabled, + "$function requires 'scriptEnabled' option to be true" + ); + const fn = (0, import_internal.evalExpr)(obj, expr, options); + return fn.body.apply(null, fn.args); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/index.js +var require_custom = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var custom_exports = {}; + module.exports = __toCommonJS(custom_exports); + __reExport(custom_exports, require_function(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/_internal.js +var require_internal8 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + DATE_FORMAT: () => DATE_FORMAT, + DATE_FORMAT_SEP_RE: () => DATE_FORMAT_SEP_RE, + DATE_FORMAT_SYM_RE: () => DATE_FORMAT_SYM_RE, + DATE_PART_INTERVAL: () => DATE_PART_INTERVAL, + DATE_SYM_TABLE: () => DATE_SYM_TABLE, + DAYS_PER_WEEK: () => DAYS_PER_WEEK, + LEAP_YEAR_REF_POINT: () => LEAP_YEAR_REF_POINT, + MINUTES_PER_HOUR: () => MINUTES_PER_HOUR, + MONTHS: () => MONTHS, + TIMEUNIT_IN_MILLIS: () => TIMEUNIT_IN_MILLIS, + TIME_UNITS: () => TIME_UNITS, + adjustDate: () => adjustDate, + computeDate: () => computeDate, + dateAdd: () => dateAdd, + dateDiffDay: () => dateDiffDay, + dateDiffHour: () => dateDiffHour, + dateDiffMonth: () => dateDiffMonth, + dateDiffQuarter: () => dateDiffQuarter, + dateDiffWeek: () => dateDiffWeek, + dateDiffYear: () => dateDiffYear, + dayOfYear: () => dayOfYear, + daysBetweenYears: () => daysBetweenYears, + formatTimezone: () => formatTimezone, + isDST: () => isDST, + isLeapYear: () => isLeapYear, + isoWeek: () => isoWeek, + isoWeekYear: () => isoWeekYear, + isoWeekday: () => isoWeekday, + padDigits: () => padDigits, + parseTimezone: () => parseTimezone, + weekOfYear: () => weekOfYear + }); + module.exports = __toCommonJS(internal_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var TIME_UNITS = [ + "year", + "quarter", + "month", + "week", + "day", + "hour", + "minute", + "second", + "millisecond" + ]; + var ISO_WEEKDAYS = { + mon: 1, + tue: 2, + wed: 3, + thu: 4, + fri: 5, + sat: 6, + sun: 7 + }; + var LEAP_YEAR_REF_POINT = -1e9; + var DAYS_PER_WEEK = 7; + var isLeapYear = (y) => (y & 3) == 0 && (y % 100 != 0 || y % 400 == 0); + function isDST(date5) { + const jan = new Date(date5.getFullYear(), 0, 1).getTimezoneOffset(); + const jul = new Date(date5.getFullYear(), 6, 1).getTimezoneOffset(); + return Math.max(jan, jul) !== date5.getTimezoneOffset(); + } + var DAYS_IN_YEAR = [ + 365, + 366 + /*leap*/ + ]; + var YEAR_DAYS_OFFSET = [ + [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], + [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] + /*leap*/ + ]; + var dayOfYear = (d) => YEAR_DAYS_OFFSET[+isLeapYear(d.getUTCFullYear())][d.getUTCMonth()] + d.getUTCDate(); + var isoWeekday = (date5, startOfWeek) => { + const dow = date5.getUTCDay() || 7; + const name = startOfWeek.toLowerCase().substring(0, 3); + return (dow - ISO_WEEKDAYS[name] + DAYS_PER_WEEK) % DAYS_PER_WEEK; + }; + var p = (y) => (y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400)) % 7; + var weeks = (y) => 52 + Number(p(y) == 4 || p(y - 1) == 3); + function isoWeek(d) { + const dow = d.getUTCDay() || 7; + const w = Math.floor((10 + dayOfYear(d) - dow) / 7); + if (w < 1) return weeks(d.getUTCFullYear() - 1); + if (w > weeks(d.getUTCFullYear())) return 1; + return w; + } + function weekOfYear(d) { + const result = isoWeek(d); + if (d.getUTCDay() > 0 && d.getUTCDate() == 1 && d.getUTCMonth() == 0) + return 0; + if (d.getUTCDay() == 0) return result + 1; + return result; + } + function isoWeekYear(d) { + return d.getUTCFullYear() - Number(d.getUTCMonth() === 0 && d.getUTCDate() == 1 && d.getUTCDay() < 1); + } + var MINUTES_PER_HOUR = 60; + var TIMEUNIT_IN_MILLIS = { + week: 6048e5, + day: 864e5, + hour: 36e5, + minute: 6e4, + second: 1e3, + millisecond: 1 + }; + var DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%LZ"; + var DATE_PART_INTERVAL = [ + ["year", 0, 9999], + ["month", 1, 12], + ["day", 1, 31], + ["hour", 0, 23], + ["minute", 0, 59], + ["second", 0, 59], + ["millisecond", 0, 999] + ]; + var MONTHS = { + jan: 1, + feb: 2, + mar: 3, + apr: 4, + may: 5, + jun: 6, + jul: 7, + aug: 8, + sep: 9, + oct: 10, + nov: 11, + dec: 12 + }; + var DATE_SYM_TABLE = { + "%b": { + name: "abbr_month", + padding: 3, + re: /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i + }, + "%B": { + name: "full_month", + padding: 0, + re: /(January|February|March|April|May|June|July|August|September|October|November|December)/i + }, + "%Y": { name: "year", padding: 4, re: /([0-9]{4})/ }, + "%G": { name: "year", padding: 4, re: /([0-9]{4})/ }, + "%m": { name: "month", padding: 2, re: /(0[1-9]|1[012])/ }, + "%d": { name: "day", padding: 2, re: /(0[1-9]|[12][0-9]|3[01])/ }, + "%j": { + name: "day_of_year", + padding: 3, + re: /(0[0-9][1-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-6])/ + }, + "%H": { name: "hour", padding: 2, re: /([01][0-9]|2[0-3])/ }, + "%M": { name: "minute", padding: 2, re: /([0-5][0-9])/ }, + "%S": { name: "second", padding: 2, re: /([0-5][0-9]|60)/ }, + "%L": { name: "millisecond", padding: 3, re: /([0-9]{3})/ }, + "%w": { name: "day_of_week", padding: 1, re: /([0-6])/ }, + "%u": { name: "day_of_week_iso", padding: 1, re: /([1-7])/ }, + "%U": { name: "week_of_year", padding: 2, re: /([1-4][0-9]?|5[0-3]?)/ }, + "%V": { name: "week_of_year_iso", padding: 2, re: /([1-4][0-9]?|5[0-3]?)/ }, + "%z": { + name: "timezone", + padding: 2, + re: /(([+-][01][0-9]|2[0-3]):?([0-5][0-9])?)/ + }, + "%Z": { name: "minute_offset", padding: 3, re: /([+-][0-9]{3})/ }, + "%%": { name: "percent_literal", padding: 1, re: /%%/ } + }; + var DATE_FORMAT_SYM_RE = /(%[bBYGmdjHMSLwuUVzZ%])/g; + var DATE_FORMAT_SEP_RE = /%[bBYGmdjHMSLwuUVzZ%]/; + var TIMEZONE_RE = /^[a-zA-Z_]+\/[a-zA-Z_]+$/; + function parseTimezone(timeZone, date5) { + if (timeZone === void 0) return 0; + if (TIMEZONE_RE.test(timeZone)) { + const utcDate = new Date(date5.toLocaleString("en-US", { timeZone: "UTC" })); + const tzDate = new Date(date5.toLocaleString("en-US", { timeZone })); + return Math.round((tzDate.getTime() - utcDate.getTime()) / 6e4); + } + const match2 = DATE_SYM_TABLE["%z"].re.exec(timeZone) ?? []; + (0, import_util3.assert)(!!match2, `timezone '${timeZone}' is invalid or not supported.`); + const hr = parseInt(match2[2]) || 0; + const min = parseInt(match2[3]) || 0; + return (Math.abs(hr * MINUTES_PER_HOUR) + min) * (hr < 0 ? -1 : 1); + } + function formatTimezone(minuteOffset) { + return (minuteOffset < 0 ? "-" : "+") + padDigits(Math.abs(Math.floor(minuteOffset / MINUTES_PER_HOUR)), 2) + padDigits(Math.abs(minuteOffset) % MINUTES_PER_HOUR, 2); + } + function adjustDate(d, minuteOffset) { + d.setUTCMinutes(d.getUTCMinutes() + minuteOffset); + } + function computeDate(obj, expr, options) { + if ((0, import_util3.isDate)(obj)) return obj; + const d = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isDate)(d)) return new Date(d); + if ((0, import_util3.isNumber)(d)) return new Date(d * 1e3); + (0, import_util3.assert)(!!d?.date, `cannot convert ${JSON.stringify(expr)} to date`); + const date5 = (0, import_util3.isDate)(d.date) ? new Date(d.date) : new Date(d.date * 1e3); + if (d.timezone) adjustDate(date5, parseTimezone(d.timezone, date5)); + return date5; + } + function padDigits(n, digits) { + return new Array(Math.max(digits - String(n).length + 1, 0)).join("0") + n.toString(); + } + var leapYearsSinceReferencePoint = (year2) => { + const yearsSinceReferencePoint = year2 - LEAP_YEAR_REF_POINT; + return Math.trunc(yearsSinceReferencePoint / 4) - Math.trunc(yearsSinceReferencePoint / 100) + Math.trunc(yearsSinceReferencePoint / 400); + }; + function daysBetweenYears(startYear, endYear) { + return Math.trunc( + leapYearsSinceReferencePoint(endYear - 1) - leapYearsSinceReferencePoint(startYear - 1) + (endYear - startYear) * DAYS_IN_YEAR[0] + ); + } + var dateDiffYear = (start, end) => end.getUTCFullYear() - start.getUTCFullYear(); + var dateDiffMonth = (start, end) => end.getUTCMonth() - start.getUTCMonth() + dateDiffYear(start, end) * 12; + var dateDiffQuarter = (start, end) => { + const a = Math.trunc(start.getUTCMonth() / 3); + const b = Math.trunc(end.getUTCMonth() / 3); + return b - a + dateDiffYear(start, end) * 4; + }; + var dateDiffDay = (start, end) => dayOfYear(end) - dayOfYear(start) + daysBetweenYears(start.getUTCFullYear(), end.getUTCFullYear()); + var dateDiffWeek = (start, end, startOfWeek) => { + const wk = (startOfWeek || "sun").substring(0, 3); + return Math.trunc( + (dateDiffDay(start, end) + isoWeekday(start, wk) - isoWeekday(end, wk)) / DAYS_PER_WEEK + ); + }; + var dateDiffHour = (start, end) => end.getUTCHours() - start.getUTCHours() + dateDiffDay(start, end) * 24; + var addMonth = (d, amount) => { + const m = d.getUTCMonth() + amount; + const yearOffset = Math.floor(m / 12); + if (m < 0) { + const month = m % 12 + 12; + d.setUTCFullYear(d.getUTCFullYear() + yearOffset, month, d.getUTCDate()); + } else { + d.setUTCFullYear(d.getUTCFullYear() + yearOffset, m % 12, d.getUTCDate()); + } + }; + var dateAdd = (date5, unit, amount, _timezone) => { + const d = new Date(date5); + switch (unit) { + case "year": + d.setUTCFullYear(d.getUTCFullYear() + amount); + break; + case "quarter": + addMonth(d, 3 * amount); + break; + case "month": + addMonth(d, amount); + break; + default: + d.setTime(d.getTime() + TIMEUNIT_IN_MILLIS[unit] * amount); + } + return d; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateAdd.js +var require_dateAdd = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateAdd.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dateAdd_exports = {}; + __export5(dateAdd_exports, { + $dateAdd: () => $dateAdd + }); + module.exports = __toCommonJS(dateAdd_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal8(); + var $dateAdd = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + return (0, import_internal2.dateAdd)(args.startDate, args.unit, args.amount, args.timezone); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateDiff.js +var require_dateDiff = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateDiff.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dateDiff_exports = {}; + __export5(dateDiff_exports, { + $dateDiff: () => $dateDiff + }); + module.exports = __toCommonJS(dateDiff_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal8(); + var $dateDiff = (obj, expr, options) => { + const { startDate, endDate, unit, timezone, startOfWeek } = (0, import_internal.evalExpr)( + obj, + expr, + options + ); + const d1 = new Date(startDate); + const d2 = new Date(endDate); + (0, import_internal2.adjustDate)(d1, (0, import_internal2.parseTimezone)(timezone, d1)); + (0, import_internal2.adjustDate)(d2, (0, import_internal2.parseTimezone)(timezone, d2)); + switch (unit) { + case "year": + return (0, import_internal2.dateDiffYear)(d1, d2); + case "quarter": + return (0, import_internal2.dateDiffQuarter)(d1, d2); + case "month": + return (0, import_internal2.dateDiffMonth)(d1, d2); + case "week": + return (0, import_internal2.dateDiffWeek)(d1, d2, startOfWeek); + case "day": + return (0, import_internal2.dateDiffDay)(d1, d2); + case "hour": + return (0, import_internal2.dateDiffHour)(d1, d2); + case "minute": + d1.setUTCSeconds(0); + d1.setUTCMilliseconds(0); + d2.setUTCSeconds(0); + d2.setUTCMilliseconds(0); + return Math.round( + (d2.getTime() - d1.getTime()) / import_internal2.TIMEUNIT_IN_MILLIS[unit] + ); + default: + return Math.round( + (d2.getTime() - d1.getTime()) / import_internal2.TIMEUNIT_IN_MILLIS[unit] + ); + } + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromParts.js +var require_dateFromParts = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromParts.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dateFromParts_exports = {}; + __export5(dateFromParts_exports, { + $dateFromParts: () => $dateFromParts + }); + module.exports = __toCommonJS(dateFromParts_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal8(); + var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + var getDaysInMonth = (date5) => { + return date5.month == 2 && (0, import_internal2.isLeapYear)(date5.year) ? 29 : DAYS_IN_MONTH[date5.month - 1]; + }; + var $dateFromParts = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + const minuteOffset = (0, import_internal2.parseTimezone)(args.timezone, /* @__PURE__ */ new Date()); + for (let i = import_internal2.DATE_PART_INTERVAL.length - 1, remainder = 0; i >= 0; i--) { + const datePartInterval = import_internal2.DATE_PART_INTERVAL[i]; + const k = datePartInterval[0]; + const min = datePartInterval[1]; + const max = datePartInterval[2]; + let part = (args[k] || 0) + remainder; + remainder = 0; + const limit = max + 1; + if (k == "hour") part += Math.floor(minuteOffset / import_internal2.MINUTES_PER_HOUR) * -1; + if (k == "minute") part += minuteOffset % import_internal2.MINUTES_PER_HOUR * -1; + if (part < min) { + const delta = min - part; + remainder = -1 * Math.ceil(delta / limit); + part = limit - delta % limit; + } else if (part > max) { + part += min; + remainder = Math.trunc(part / limit); + part %= limit; + } + args[k] = part; + } + args.day = Math.min(args.day, getDaysInMonth(args)); + return new Date( + Date.UTC( + args.year, + args.month - 1, + args.day, + args.hour, + args.minute, + args.second, + args.millisecond + ) + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromString.js +var require_dateFromString = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromString.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dateFromString_exports = {}; + __export5(dateFromString_exports, { + $dateFromString: () => $dateFromString + }); + module.exports = __toCommonJS(dateFromString_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal8(); + function tzLetterOffset(c) { + if (c === "Z") return 0; + if (c >= "A" && c < "N") return c.charCodeAt(0) - 64; + return 77 - c.charCodeAt(0); + } + var regexStrip = (s) => s.replace(/^\//, "").replace(/\/$/, "").replace(/\/i/, ""); + var REGEX_SPECIAL_CHARS = ["^", ".", "-", "*", "?", "$"]; + function regexQuote(s) { + for (const c of REGEX_SPECIAL_CHARS) s = s.replace(c, `\\${c}`); + return s; + } + function $dateFromString(obj, expr, options) { + const args = (0, import_internal.evalExpr)(obj, expr, options); + const format = args.format || import_internal2.DATE_FORMAT; + const onNull = args.onNull || null; + let dateString = args.dateString; + if ((0, import_util3.isNil)(dateString)) return onNull; + const separators = format.split(import_internal2.DATE_FORMAT_SEP_RE); + separators.reverse(); + const matches = format.match(import_internal2.DATE_FORMAT_SYM_RE); + const dateParts = {}; + let expectedPattern = ""; + for (let i = 0, len = matches.length; i < len; i++) { + const formatSpecifier = matches[i]; + const props = import_internal2.DATE_SYM_TABLE[formatSpecifier]; + if ((0, import_util3.isObject)(props)) { + const m2 = props.re.exec(dateString); + const delimiter = separators.pop() || ""; + if (m2 !== null) { + dateParts[props.name] = /^\d+$/.exec(m2[0]) ? parseInt(m2[0]) : m2[0]; + dateString = dateString.substring(m2.index + m2[0].length + 1); + expectedPattern += regexQuote(delimiter) + regexStrip(props.re.toString()); + } else { + dateParts[props.name] = null; + } + } + } + if ((0, import_util3.isNil)(dateParts.month)) { + const abbrMonth = (dateParts.full_month?.slice(0, 3) ?? dateParts.abbr_month ?? "").toLowerCase(); + if (import_internal2.MONTHS[abbrMonth]) { + dateParts.month = import_internal2.MONTHS[abbrMonth]; + } + } + if ((0, import_util3.isNil)(dateParts.year) || (0, import_util3.isNil)(dateParts.month) || (0, import_util3.isNil)(dateParts.day) || !new RegExp("^" + expectedPattern + "[A-Z]?$").test(args.dateString)) { + return args.onError; + } + const m = args.dateString.match(/([A-Z])$/); + (0, import_util3.assert)( + // only one of in-date timeone or timezone argument but not both. + !(m && args.timezone), + `$dateFromString: you cannot pass in a date/time string with time zone information ('${m && m[0]}') together with a timezone argument` + ); + const minuteOffset = m ? tzLetterOffset(m[0]) * import_internal2.MINUTES_PER_HOUR : (0, import_internal2.parseTimezone)(args.timezone, /* @__PURE__ */ new Date()); + const d = new Date( + Date.UTC(dateParts.year, dateParts.month - 1, dateParts.day, 0, 0, 0) + ); + if (!(0, import_util3.isNil)(dateParts.hour)) d.setUTCHours(dateParts.hour); + if (!(0, import_util3.isNil)(dateParts.minute)) d.setUTCMinutes(dateParts.minute); + if (!(0, import_util3.isNil)(dateParts.second)) d.setUTCSeconds(dateParts.second); + if (!(0, import_util3.isNil)(dateParts.millisecond)) + d.setUTCMilliseconds(dateParts.millisecond); + (0, import_internal2.adjustDate)(d, -minuteOffset); + return d; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateSubtract.js +var require_dateSubtract = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateSubtract.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dateSubtract_exports = {}; + __export5(dateSubtract_exports, { + $dateSubtract: () => $dateSubtract + }); + module.exports = __toCommonJS(dateSubtract_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal8(); + var $dateSubtract = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + return (0, import_internal2.dateAdd)(args.startDate, args.unit, -args.amount, args.timezone); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToParts.js +var require_dateToParts = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToParts.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dateToParts_exports = {}; + __export5(dateToParts_exports, { + $dateToParts: () => $dateToParts + }); + module.exports = __toCommonJS(dateToParts_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal8(); + var $dateToParts = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + const d = new Date(args.date); + (0, import_internal2.adjustDate)(d, (0, import_internal2.parseTimezone)(args.timezone, d)); + const timePart = { + hour: d.getUTCHours(), + minute: d.getUTCMinutes(), + second: d.getUTCSeconds(), + millisecond: d.getUTCMilliseconds() + }; + if (args.iso8601 == true) { + return Object.assign(timePart, { + isoWeekYear: (0, import_internal2.isoWeekYear)(d), + isoWeek: (0, import_internal2.isoWeek)(d), + isoDayOfWeek: d.getUTCDay() || 7 + }); + } + return Object.assign(timePart, { + year: d.getUTCFullYear(), + month: d.getUTCMonth() + 1, + day: d.getUTCDate() + }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToString.js +var require_dateToString = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToString.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dateToString_exports = {}; + __export5(dateToString_exports, { + $dateToString: () => $dateToString + }); + module.exports = __toCommonJS(dateToString_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal8(); + var DATE_FUNCTIONS = { + "%Y": (d) => d.getUTCFullYear(), + //year + "%G": (d) => d.getUTCFullYear(), + //year + "%m": (d) => d.getUTCMonth() + 1, + //month + "%d": (d) => d.getUTCDate(), + //dayOfMonth + "%H": (d) => d.getUTCHours(), + //hour + "%M": (d) => d.getUTCMinutes(), + //minutes + "%S": (d) => d.getUTCSeconds(), + //seconds + "%L": (d) => d.getUTCMilliseconds(), + //milliseconds + "%u": (d) => d.getUTCDay() || 7, + //isoDayOfWeek + "%U": import_internal2.weekOfYear, + "%V": import_internal2.isoWeek, + "%j": import_internal2.dayOfYear, + "%w": (d) => d.getUTCDay() + //dayOfWeek + }; + var $dateToString = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(args.onNull)) args.onNull = null; + if ((0, import_util3.isNil)(args.date)) return args.onNull; + const date5 = (0, import_internal2.computeDate)(obj, args.date, options); + let format = args.format ?? import_internal2.DATE_FORMAT; + const minuteOffset = (0, import_internal2.parseTimezone)(args.timezone, date5); + const matches = format.match(import_internal2.DATE_FORMAT_SYM_RE); + if (!matches) return format; + (0, import_internal2.adjustDate)(date5, minuteOffset); + for (let i = 0, len = matches.length; i < len; i++) { + const formatSpec = matches[i]; + (0, import_util3.assert)( + formatSpec in import_internal2.DATE_SYM_TABLE, + `$dateToString: invalid format specifier ${formatSpec}` + ); + const { name, padding } = import_internal2.DATE_SYM_TABLE[formatSpec]; + const fn = DATE_FUNCTIONS[formatSpec]; + let value = ""; + if (fn) { + value = (0, import_internal2.padDigits)(fn(date5), padding); + } else { + switch (name) { + case "timezone": + value = (0, import_internal2.formatTimezone)(minuteOffset); + break; + case "minute_offset": + value = minuteOffset.toString(); + break; + case "abbr_month": + case "full_month": { + const format2 = name.startsWith("abbr") ? "short" : "long"; + value = date5.toLocaleString("en-US", { month: format2 }); + break; + } + } + } + format = format.replace(formatSpec, value); + } + return format; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateTrunc.js +var require_dateTrunc = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateTrunc.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dateTrunc_exports = {}; + __export5(dateTrunc_exports, { + $dateTrunc: () => $dateTrunc + }); + module.exports = __toCommonJS(dateTrunc_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal8(); + var REF_DATE_MILLIS = 9466848e5; + var distanceToBinLowerBound = (value, binSize) => { + let remainder = value % binSize; + if (remainder < 0) { + remainder += binSize; + } + return remainder; + }; + var DATE_DIFF_FN = { + day: import_internal2.dateDiffDay, + month: import_internal2.dateDiffMonth, + quarter: import_internal2.dateDiffQuarter, + year: import_internal2.dateDiffYear + }; + var DAYS_OF_WEEK_RE = /(mon(day)?|tue(sday)?|wed(nesday)?|thu(rsday)?|fri(day)?|sat(urday)?|sun(day)?)/i; + var $dateTrunc = (obj, expr, options) => { + const { + date: date5, + unit, + binSize: optBinSize, + timezone, + startOfWeek: optStartOfWeek + } = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(date5) || (0, import_util3.isNil)(unit)) return null; + const startOfWeek = (optStartOfWeek ?? "sun").toLowerCase().substring(0, 3); + (0, import_util3.assert)( + (0, import_util3.isDate)(date5), + "$dateTrunc: 'date' must resolve to a valid Date object." + ); + (0, import_util3.assert)(import_internal2.TIME_UNITS.includes(unit), "$dateTrunc: unit is invalid."); + (0, import_util3.assert)( + unit != "week" || DAYS_OF_WEEK_RE.test(startOfWeek), + `$dateTrunc: startOfWeek '${startOfWeek}' is not a valid.` + ); + (0, import_util3.assert)( + (0, import_util3.isNil)(optBinSize) || optBinSize > 0, + "$dateTrunc requires 'binSize' to be greater than 0, but got value 0." + ); + const binSize = optBinSize ?? 1; + switch (unit) { + case "millisecond": + case "second": + case "minute": + case "hour": { + const binSizeMillis = binSize * import_internal2.TIMEUNIT_IN_MILLIS[unit]; + const shiftedDate = date5.getTime() - REF_DATE_MILLIS; + return new Date( + date5.getTime() - distanceToBinLowerBound(shiftedDate, binSizeMillis) + ); + } + default: { + (0, import_util3.assert)(binSize <= 1e11, "dateTrunc unsupported binSize value"); + const d = new Date(date5); + const refPointDate = new Date(REF_DATE_MILLIS); + let distanceFromRefPoint = 0; + if (unit == "week") { + const refPointDayOfWeek = (0, import_internal2.isoWeekday)(refPointDate, startOfWeek); + const daysToAdjustBy = (import_internal2.DAYS_PER_WEEK - refPointDayOfWeek) % import_internal2.DAYS_PER_WEEK; + refPointDate.setTime( + refPointDate.getTime() + daysToAdjustBy * import_internal2.TIMEUNIT_IN_MILLIS.day + ); + distanceFromRefPoint = (0, import_internal2.dateDiffWeek)(refPointDate, d, startOfWeek); + } else { + distanceFromRefPoint = DATE_DIFF_FN[unit](refPointDate, d); + } + const binLowerBoundFromRefPoint = distanceFromRefPoint - distanceToBinLowerBound(distanceFromRefPoint, binSize); + const newDate = (0, import_internal2.dateAdd)( + refPointDate, + unit, + binLowerBoundFromRefPoint, + timezone + ); + const minuteOffset = (0, import_internal2.parseTimezone)(timezone, newDate); + (0, import_internal2.adjustDate)(newDate, -minuteOffset); + return newDate; + } + } + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfMonth.js +var require_dayOfMonth = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfMonth.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dayOfMonth_exports = {}; + __export5(dayOfMonth_exports, { + $dayOfMonth: () => $dayOfMonth + }); + module.exports = __toCommonJS(dayOfMonth_exports); + var import_internal = require_internal8(); + var $dayOfMonth = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDate(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfWeek.js +var require_dayOfWeek = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfWeek.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dayOfWeek_exports = {}; + __export5(dayOfWeek_exports, { + $dayOfWeek: () => $dayOfWeek + }); + module.exports = __toCommonJS(dayOfWeek_exports); + var import_internal = require_internal8(); + var $dayOfWeek = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDay() + 1; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfYear.js +var require_dayOfYear = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfYear.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var dayOfYear_exports = {}; + __export5(dayOfYear_exports, { + $dayOfYear: () => $dayOfYear + }); + module.exports = __toCommonJS(dayOfYear_exports); + var import_internal = require_internal8(); + var $dayOfYear = (obj, expr, options) => (0, import_internal.dayOfYear)((0, import_internal.computeDate)(obj, expr, options)); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/hour.js +var require_hour = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/hour.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var hour_exports = {}; + __export5(hour_exports, { + $hour: () => $hour + }); + module.exports = __toCommonJS(hour_exports); + var import_internal = require_internal8(); + var $hour = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCHours(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoDayOfWeek.js +var require_isoDayOfWeek = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoDayOfWeek.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var isoDayOfWeek_exports = {}; + __export5(isoDayOfWeek_exports, { + $isoDayOfWeek: () => $isoDayOfWeek + }); + module.exports = __toCommonJS(isoDayOfWeek_exports); + var import_internal = require_internal8(); + var $isoDayOfWeek = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDay() || 7; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeek.js +var require_isoWeek = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeek.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var isoWeek_exports = {}; + __export5(isoWeek_exports, { + $isoWeek: () => $isoWeek + }); + module.exports = __toCommonJS(isoWeek_exports); + var import_internal = require_internal8(); + var $isoWeek = (obj, expr, options) => (0, import_internal.isoWeek)((0, import_internal.computeDate)(obj, expr, options)); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeekYear.js +var require_isoWeekYear = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeekYear.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var isoWeekYear_exports = {}; + __export5(isoWeekYear_exports, { + $isoWeekYear: () => $isoWeekYear + }); + module.exports = __toCommonJS(isoWeekYear_exports); + var import_internal = require_internal8(); + var $isoWeekYear = (obj, expr, options) => (0, import_internal.isoWeekYear)((0, import_internal.computeDate)(obj, expr, options)); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/millisecond.js +var require_millisecond = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/millisecond.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var millisecond_exports = {}; + __export5(millisecond_exports, { + $millisecond: () => $millisecond + }); + module.exports = __toCommonJS(millisecond_exports); + var import_internal = require_internal8(); + var $millisecond = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMilliseconds(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/minute.js +var require_minute = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/minute.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var minute_exports = {}; + __export5(minute_exports, { + $minute: () => $minute + }); + module.exports = __toCommonJS(minute_exports); + var import_internal = require_internal8(); + var $minute = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMinutes(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/month.js +var require_month = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/month.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var month_exports = {}; + __export5(month_exports, { + $month: () => $month + }); + module.exports = __toCommonJS(month_exports); + var import_internal = require_internal8(); + var $month = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMonth() + 1; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/second.js +var require_second = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/second.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var second_exports = {}; + __export5(second_exports, { + $second: () => $second + }); + module.exports = __toCommonJS(second_exports); + var import_internal = require_internal8(); + var $second = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCSeconds(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/week.js +var require_week = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/week.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var week_exports = {}; + __export5(week_exports, { + $week: () => $week + }); + module.exports = __toCommonJS(week_exports); + var import_internal = require_internal8(); + var $week = (obj, expr, options) => (0, import_internal.weekOfYear)((0, import_internal.computeDate)(obj, expr, options)); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/year.js +var require_year = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/year.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var year_exports = {}; + __export5(year_exports, { + $year: () => $year + }); + module.exports = __toCommonJS(year_exports); + var import_internal = require_internal8(); + var $year = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCFullYear(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/index.js +var require_date = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var date_exports = {}; + module.exports = __toCommonJS(date_exports); + __reExport(date_exports, require_dateAdd(), module.exports); + __reExport(date_exports, require_dateDiff(), module.exports); + __reExport(date_exports, require_dateFromParts(), module.exports); + __reExport(date_exports, require_dateFromString(), module.exports); + __reExport(date_exports, require_dateSubtract(), module.exports); + __reExport(date_exports, require_dateToParts(), module.exports); + __reExport(date_exports, require_dateToString(), module.exports); + __reExport(date_exports, require_dateTrunc(), module.exports); + __reExport(date_exports, require_dayOfMonth(), module.exports); + __reExport(date_exports, require_dayOfWeek(), module.exports); + __reExport(date_exports, require_dayOfYear(), module.exports); + __reExport(date_exports, require_hour(), module.exports); + __reExport(date_exports, require_isoDayOfWeek(), module.exports); + __reExport(date_exports, require_isoWeek(), module.exports); + __reExport(date_exports, require_isoWeekYear(), module.exports); + __reExport(date_exports, require_millisecond(), module.exports); + __reExport(date_exports, require_minute(), module.exports); + __reExport(date_exports, require_month(), module.exports); + __reExport(date_exports, require_second(), module.exports); + __reExport(date_exports, require_week(), module.exports); + __reExport(date_exports, require_year(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/literal.js +var require_literal = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/literal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var literal_exports = {}; + __export5(literal_exports, { + $literal: () => $literal + }); + module.exports = __toCommonJS(literal_exports); + var $literal = (_obj, expr, _options2) => expr; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/median.js +var require_median2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/median.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var median_exports = {}; + __export5(median_exports, { + $median: () => $median + }); + module.exports = __toCommonJS(median_exports); + var import_internal = require_internal2(); + var import_median = require_median(); + var $median = (obj, expr, options) => { + const input = (0, import_internal.evalExpr)(obj, expr.input, options); + return (0, import_median.$median)(input, { input: "$$CURRENT", method: expr.method }, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/getField.js +var require_getField = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/getField.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var getField_exports = {}; + __export5(getField_exports, { + $getField: () => $getField + }); + module.exports = __toCommonJS(getField_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $getField = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + const { field, input } = (0, import_util3.isString)(args) ? { field: args, input: obj } : { field: args.field, input: args.input ?? obj }; + return input[field]; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/rand.js +var require_rand = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/rand.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var rand_exports = {}; + __export5(rand_exports, { + $rand: () => $rand + }); + module.exports = __toCommonJS(rand_exports); + var $rand = (_obj, _expr2, _options2) => Math.random(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/sampleRate.js +var require_sampleRate = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/sampleRate.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sampleRate_exports = {}; + __export5(sampleRate_exports, { + $sampleRate: () => $sampleRate + }); + module.exports = __toCommonJS(sampleRate_exports); + var import_internal = require_internal2(); + var $sampleRate = (obj, expr, options) => Math.random() <= (0, import_internal.evalExpr)(obj, expr, options); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/index.js +var require_misc = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var misc_exports = {}; + module.exports = __toCommonJS(misc_exports); + __reExport(misc_exports, require_getField(), module.exports); + __reExport(misc_exports, require_rand(), module.exports); + __reExport(misc_exports, require_sampleRate(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/mergeObjects.js +var require_mergeObjects2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/mergeObjects.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var mergeObjects_exports = {}; + __export5(mergeObjects_exports, { + $mergeObjects: () => $mergeObjects + }); + module.exports = __toCommonJS(mergeObjects_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_mergeObjects = require_mergeObjects(); + var import_internal2 = require_internal4(); + var $mergeObjects = (obj, expr, options) => { + const docs = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(docs)) return {}; + if (!(0, import_util3.isArray)(docs)) + return (0, import_internal2.errExpectArray)(options.failOnError, "$mergeObjects", import_internal2.ARR_OPTS.obj); + return (0, import_mergeObjects.$mergeObjects)(docs, expr, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/objectToArray.js +var require_objectToArray = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/objectToArray.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var objectToArray_exports = {}; + __export5(objectToArray_exports, { + $objectToArray: () => $objectToArray + }); + module.exports = __toCommonJS(objectToArray_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $objectToArray = (obj, expr, options) => { + const val = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(val)) return null; + if (!(0, import_util3.isObject)(val)) + return (0, import_internal2.errExpectObject)(options.failOnError, "$objectToArray"); + const keys = Object.keys(val); + const result = new Array(keys.length); + let i = 0; + for (const k of keys) { + result[i++] = { k, v: val[k] }; + } + return result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/setField.js +var require_setField = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/setField.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var setField_exports = {}; + __export5(setField_exports, { + $setField: () => $setField + }); + module.exports = __toCommonJS(setField_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$setField"; + var $setField = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "field", "value"), + "$setField expects object { input, field, value }" + ); + const { input, field, value } = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(input)) return null; + const foe = options.failOnError; + if (!(0, import_util3.isObject)(input)) return (0, import_internal2.errExpectObject)(foe, `${OP} 'input'`); + if (!(0, import_util3.isString)(field)) return (0, import_internal2.errExpectString)(foe, `${OP} 'field'`); + const newObj = { ...input }; + if (expr.value == "$$REMOVE") { + delete newObj[field]; + } else { + newObj[field] = value; + } + return newObj; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/unsetField.js +var require_unsetField = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/unsetField.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var unsetField_exports = {}; + __export5(unsetField_exports, { + $unsetField: () => $unsetField + }); + module.exports = __toCommonJS(unsetField_exports); + var import_setField = require_setField(); + var $unsetField = (obj, expr, options) => { + return (0, import_setField.$setField)(obj, { ...expr, value: "$$REMOVE" }, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/index.js +var require_object = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var object_exports = {}; + module.exports = __toCommonJS(object_exports); + __reExport(object_exports, require_mergeObjects2(), module.exports); + __reExport(object_exports, require_objectToArray(), module.exports); + __reExport(object_exports, require_setField(), module.exports); + __reExport(object_exports, require_unsetField(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/percentile.js +var require_percentile2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/percentile.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var percentile_exports = {}; + __export5(percentile_exports, { + $percentile: () => $percentile + }); + module.exports = __toCommonJS(percentile_exports); + var import_internal = require_internal2(); + var import_percentile = require_percentile(); + var $percentile = (obj, expr, options) => { + const input = (0, import_internal.evalExpr)(obj, expr.input, options); + return (0, import_percentile.$percentile)( + input, + { ...expr, input: "$$CURRENT" }, + options + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/allElementsTrue.js +var require_allElementsTrue = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/allElementsTrue.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var allElementsTrue_exports = {}; + __export5(allElementsTrue_exports, { + $allElementsTrue: () => $allElementsTrue + }); + module.exports = __toCommonJS(allElementsTrue_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var import_internal3 = require_internal4(); + var $allElementsTrue = (obj, expr, options) => { + if ((0, import_internal2.isArray)(expr)) { + if (expr.length === 0) return true; + (0, import_internal2.assert)(expr.length === 1, "$allElementsTrue expects array(1)"); + expr = expr[0]; + } + const foe = options.failOnError; + const args = (0, import_internal.evalExpr)(obj, expr, options); + if (!(0, import_internal2.isArray)(args)) return (0, import_internal3.errExpectArray)(foe, `$allElementsTrue argument`); + for (const v of args) if (!(0, import_internal2.truthy)(v, options.useStrictMode)) return false; + return true; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/anyElementTrue.js +var require_anyElementTrue = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/anyElementTrue.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var anyElementTrue_exports = {}; + __export5(anyElementTrue_exports, { + $anyElementTrue: () => $anyElementTrue + }); + module.exports = __toCommonJS(anyElementTrue_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var import_internal3 = require_internal4(); + var $anyElementTrue = (obj, expr, options) => { + if ((0, import_internal2.isArray)(expr)) { + if (expr.length === 0) return false; + (0, import_internal2.assert)(expr.length === 1, "$anyElementTrue expects array(1)"); + expr = expr[0]; + } + const foe = options.failOnError; + const args = (0, import_internal.evalExpr)(obj, expr, options); + if (!(0, import_internal2.isArray)(args)) return (0, import_internal3.errExpectArray)(foe, `$anyElementTrue argument`); + for (const v of args) if ((0, import_internal2.truthy)(v, options.useStrictMode)) return true; + return false; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setDifference.js +var require_setDifference = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setDifference.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var setDifference_exports = {}; + __export5(setDifference_exports, { + $setDifference: () => $setDifference + }); + module.exports = __toCommonJS(setDifference_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$setDifference"; + var $setDifference = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length == 2, `${OP} expects array(2)`); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + let ok2 = true; + for (const v of args) { + if ((0, import_util3.isNil)(v)) return null; + ok2 && (ok2 = (0, import_util3.isArray)(v)); + } + if (!ok2) return (0, import_internal2.errExpectArray)(foe, `${OP} arguments`); + const m = import_util3.HashMap.init(); + for (const v of args[0]) m.set(v, true); + for (const v of args[1]) m.delete(v); + return Array.from(m.keys()); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setEquals.js +var require_setEquals = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setEquals.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var setEquals_exports = {}; + __export5(setEquals_exports, { + $setEquals: () => $setEquals + }); + module.exports = __toCommonJS(setEquals_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $setEquals = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), "$setEquals expects array"); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + if (!args.every(import_util3.isArray)) return (0, import_internal2.errExpectArray)(foe, "$setEquals arguments"); + const map3 = import_util3.HashMap.init(); + const first = args[0]; + for (let i = 0; i < first.length; i++) map3.set(first[i], i); + for (let i = 1; i < args.length; i++) { + const arr = args[i]; + const set2 = /* @__PURE__ */ new Set(); + for (let j = 0; j < arr.length; j++) { + const n = map3.get(arr[j]) ?? -1; + if (n === -1) return false; + set2.add(n); + } + if (set2.size !== map3.size) return false; + } + return true; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIntersection.js +var require_setIntersection = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIntersection.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var setIntersection_exports = {}; + __export5(setIntersection_exports, { + $setIntersection: () => $setIntersection + }); + module.exports = __toCommonJS(setIntersection_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$setIntersection"; + var $setIntersection = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), `${OP} expects array`); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + let ok2 = true; + for (const v of args) { + if ((0, import_util3.isNil)(v)) return null; + ok2 && (ok2 = (0, import_util3.isArray)(v)); + } + if (!ok2) return (0, import_internal2.errExpectArray)(foe, `${OP} arguments`); + return (0, import_util3.intersection)(args); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIsSubset.js +var require_setIsSubset = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIsSubset.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var setIsSubset_exports = {}; + __export5(setIsSubset_exports, { + $setIsSubset: () => $setIsSubset + }); + module.exports = __toCommonJS(setIsSubset_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$setIsSubset"; + var $setIsSubset = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, `${OP} expects array(2)`); + const args = (0, import_internal.evalExpr)(obj, expr, options); + if (!args.every(import_util3.isArray)) + return (0, import_internal2.errExpectArray)(options.failOnError, `${OP} arguments`); + const [first, second] = args; + const map3 = import_util3.HashMap.init(); + for (const v of second) map3.set(v, 0); + for (const v of first) if (!map3.has(v)) return false; + return true; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setUnion.js +var require_setUnion = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setUnion.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var setUnion_exports = {}; + __export5(setUnion_exports, { + $setUnion: () => $setUnion + }); + module.exports = __toCommonJS(setUnion_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $setUnion = (obj, expr, options) => { + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + if ((0, import_util3.isNil)(args)) return null; + if (!(0, import_util3.isArray)(args)) return (0, import_internal2.errExpectArray)(foe, "$setUnion"); + if ((0, import_util3.isArray)(expr)) { + if (!args.every(import_util3.isArray)) return (0, import_internal2.errExpectArray)(foe, "$setUnion arguments"); + return (0, import_util3.unique)((0, import_util3.flatten)(args)); + } + return (0, import_util3.unique)(args); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/index.js +var require_set = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var set_exports = {}; + module.exports = __toCommonJS(set_exports); + __reExport(set_exports, require_allElementsTrue(), module.exports); + __reExport(set_exports, require_anyElementTrue(), module.exports); + __reExport(set_exports, require_setDifference(), module.exports); + __reExport(set_exports, require_setEquals(), module.exports); + __reExport(set_exports, require_setIntersection(), module.exports); + __reExport(set_exports, require_setIsSubset(), module.exports); + __reExport(set_exports, require_setUnion(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/concat.js +var require_concat = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/concat.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var concat_exports = {}; + __export5(concat_exports, { + $concat: () => $concat + }); + module.exports = __toCommonJS(concat_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $concat = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr), "$concat expects array"); + const foe = options.failOnError; + const args = (0, import_internal.evalExpr)(obj, expr, options); + let ok2 = true; + for (const s of args) { + if ((0, import_util3.isNil)(s)) return null; + ok2 && (ok2 = (0, import_util3.isString)(s)); + } + if (!ok2) return (0, import_internal2.errExpectArray)(foe, "$concat", { type: "string" }); + return args.join(""); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/indexOfBytes.js +var require_indexOfBytes = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/indexOfBytes.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var indexOfBytes_exports = {}; + __export5(indexOfBytes_exports, { + $indexOfBytes: () => $indexOfBytes + }); + module.exports = __toCommonJS(indexOfBytes_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var import_internal3 = require_internal4(); + var OP = "$indexOfBytes"; + var $indexOfBytes = (obj, expr, options) => { + (0, import_internal2.assert)( + (0, import_internal2.isArray)(expr) && expr.length > 1 && expr.length < 5, + `${OP} expects array(4)` + ); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + const str = args[0]; + if ((0, import_internal2.isNil)(str)) return null; + if (!(0, import_internal2.isString)(str)) return (0, import_internal3.errExpectString)(foe, `${OP} arg1 `); + const search = args[1]; + if (!(0, import_internal2.isString)(search)) return (0, import_internal3.errExpectString)(foe, `${OP} arg2 `); + const start = args[2] ?? 0; + const end = args[3] ?? str.length; + if (!(0, import_internal2.isInteger)(start) || start < 0) + return (0, import_internal3.errExpectNumber)(foe, `${OP} arg3 `, import_internal3.INT_OPTS.index); + if (!(0, import_internal2.isInteger)(end) || end < 0) + return (0, import_internal3.errExpectNumber)(foe, `${OP} arg4 `, import_internal3.INT_OPTS.index); + if (start > end) return -1; + const index = str.substring(start, end).indexOf(search); + return index > -1 ? index + start : index; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/_internal.js +var require_internal9 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + regexSearch: () => regexSearch, + trimString: () => trimString + }); + module.exports = __toCommonJS(internal_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var WHITESPACE_CHARS = [ + 0, + // '\0' Null character + 32, + // ' ', Space + 9, + // '\t' Horizontal tab + 10, + // '\n' Line feed/new line + 11, + // '\v' Vertical tab + 12, + // '\f' Form feed + 13, + // '\r' Carriage return + 160, + // Non-breaking space + 5760, + // Ogham space mark + 8192, + // En quad + 8193, + // Em quad + 8194, + // En space + 8195, + // Em space + 8196, + // Three-per-em space + 8197, + // Four-per-em space + 8198, + // Six-per-em space + 8199, + // Figure space + 8200, + // Punctuation space + 8201, + // Thin space + 8202 + // Hair space + ]; + function trimString(obj, expr, options, trimOpts) { + const val = (0, import_internal.evalExpr)(obj, expr, options); + const s = val.input; + if ((0, import_util3.isNil)(s)) return null; + const codepoints = (0, import_util3.isNil)(val.chars) ? WHITESPACE_CHARS : val.chars.split("").map((c) => c.codePointAt(0)); + let i = 0; + let j = s.length - 1; + while (trimOpts.left && i <= j && codepoints.indexOf(s[i].codePointAt(0)) !== -1) + i++; + while (trimOpts.right && i <= j && codepoints.indexOf(s[j].codePointAt(0)) !== -1) + j--; + return s.substring(i, j + 1); + } + function regexSearch(obj, expr, options, reOpts) { + const val = (0, import_internal.evalExpr)(obj, expr, options); + if (!(0, import_util3.isString)(val.input)) return []; + const regexOptions = val.options; + if (regexOptions) { + (0, import_util3.assert)( + regexOptions.indexOf("x") === -1, + "extended capability option 'x' not supported" + ); + (0, import_util3.assert)(regexOptions.indexOf("g") === -1, "global option 'g' not supported"); + } + let input = val.input; + const re2 = new RegExp(val.regex, regexOptions); + let m; + const matches = new Array(); + let offset = 0; + while (m = re2.exec(input)) { + const result = { + match: m[0], + idx: m.index + offset, + captures: [] + }; + for (let i = 1; i < m.length; i++) result.captures.push(m[i] || null); + matches.push(result); + if (!reOpts.global) break; + offset = m.index + m[0].length; + input = input.substring(offset); + } + return matches; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/ltrim.js +var require_ltrim = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/ltrim.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var ltrim_exports = {}; + __export5(ltrim_exports, { + $ltrim: () => $ltrim + }); + module.exports = __toCommonJS(ltrim_exports); + var import_internal = require_internal9(); + var $ltrim = (obj, expr, options) => { + return (0, import_internal.trimString)(obj, expr, options, { left: true, right: false }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFind.js +var require_regexFind = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFind.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var regexFind_exports = {}; + __export5(regexFind_exports, { + $regexFind: () => $regexFind + }); + module.exports = __toCommonJS(regexFind_exports); + var import_util3 = require_util(); + var import_internal = require_internal9(); + var $regexFind = (obj, expr, options) => { + const result = (0, import_internal.regexSearch)(obj, expr, options, { global: false }); + return (0, import_util3.isArray)(result) && result.length > 0 ? result[0] : null; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFindAll.js +var require_regexFindAll = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFindAll.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var regexFindAll_exports = {}; + __export5(regexFindAll_exports, { + $regexFindAll: () => $regexFindAll + }); + module.exports = __toCommonJS(regexFindAll_exports); + var import_internal = require_internal9(); + var $regexFindAll = (obj, expr, options) => { + return (0, import_internal.regexSearch)(obj, expr, options, { global: true }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexMatch.js +var require_regexMatch = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexMatch.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var regexMatch_exports = {}; + __export5(regexMatch_exports, { + $regexMatch: () => $regexMatch + }); + module.exports = __toCommonJS(regexMatch_exports); + var import_internal = require_internal9(); + var $regexMatch = (obj, expr, options) => { + return (0, import_internal.regexSearch)(obj, expr, options, { global: false })?.length != 0; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceAll.js +var require_replaceAll = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceAll.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var replaceAll_exports = {}; + __export5(replaceAll_exports, { + $replaceAll: () => $replaceAll + }); + module.exports = __toCommonJS(replaceAll_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$replaceAll"; + var $replaceAll = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isObject)(expr), `${OP} expects an object argument`); + const foe = options.failOnError; + const args = (0, import_internal.evalExpr)(obj, expr, options); + const { input, find, replacement } = args; + if ((0, import_util3.isNil)(input) || (0, import_util3.isNil)(find) || (0, import_util3.isNil)(replacement)) return null; + if (!(0, import_util3.isString)(input)) return (0, import_internal2.errExpectString)(foe, `${OP} 'input'`); + if (!(0, import_util3.isString)(find)) return (0, import_internal2.errExpectString)(foe, `${OP} 'find'`); + if (!(0, import_util3.isString)(replacement)) + return (0, import_internal2.errExpectString)(foe, `${OP} 'replacement'`); + return input.replace(new RegExp(find, "g"), replacement); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceOne.js +var require_replaceOne = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceOne.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var replaceOne_exports = {}; + __export5(replaceOne_exports, { + $replaceOne: () => $replaceOne + }); + module.exports = __toCommonJS(replaceOne_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$replaceOne"; + var $replaceOne = (obj, expr, options) => { + const foe = options.failOnError; + const args = (0, import_internal.evalExpr)(obj, expr, options); + const { input, find, replacement } = args; + if ((0, import_util3.isNil)(input) || (0, import_util3.isNil)(find) || (0, import_util3.isNil)(replacement)) return null; + if (!(0, import_util3.isString)(input)) return (0, import_internal2.errExpectString)(foe, `${OP} 'input'`); + if (!(0, import_util3.isString)(find)) return (0, import_internal2.errExpectString)(foe, `${OP} 'find'`); + if (!(0, import_util3.isString)(replacement)) + return (0, import_internal2.errExpectString)(foe, `${OP} 'replacement'`); + return args.input.replace(args.find, args.replacement); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/rtrim.js +var require_rtrim = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/rtrim.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var rtrim_exports = {}; + __export5(rtrim_exports, { + $rtrim: () => $rtrim + }); + module.exports = __toCommonJS(rtrim_exports); + var import_internal = require_internal9(); + var $rtrim = (obj, expr, options) => { + return (0, import_internal.trimString)(obj, expr, options, { left: false, right: true }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/split.js +var require_split = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/split.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var split_exports = {}; + __export5(split_exports, { + $split: () => $split + }); + module.exports = __toCommonJS(split_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $split = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, `$split expects array(2)`); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + if ((0, import_util3.isNil)(args[0])) return null; + if (!args.every(import_util3.isString)) + return (0, import_internal2.errExpectArray)(foe, `$split `, { size: 2, type: "string" }); + return args[0].split(args[1]); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strcasecmp.js +var require_strcasecmp = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strcasecmp.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var strcasecmp_exports = {}; + __export5(strcasecmp_exports, { + $strcasecmp: () => $strcasecmp + }); + module.exports = __toCommonJS(strcasecmp_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal(); + var import_internal3 = require_internal4(); + var $strcasecmp = (obj, expr, options) => { + (0, import_internal2.assert)((0, import_util3.isArray)(expr) && expr.length === 2, `$strcasecmp expects array(2)`); + const args = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + let t_nil = true; + let t_str = true; + for (const v of args) { + t_nil && (t_nil = (0, import_util3.isNil)(v)); + t_str && (t_str = (0, import_util3.isString)(v)); + } + if (t_nil) return 0; + if (!t_str) + return (0, import_internal3.errExpectArray)(foe, `$strcasecmp arguments`, { type: "string" }); + return (0, import_internal2.simpleCmp)(args[0].toLowerCase(), args[1].toLowerCase()); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenBytes.js +var require_strLenBytes = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenBytes.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var strLenBytes_exports = {}; + __export5(strLenBytes_exports, { + $strLenBytes: () => $strLenBytes + }); + module.exports = __toCommonJS(strLenBytes_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $strLenBytes = (obj, expr, options) => { + const s = (0, import_internal.evalExpr)(obj, expr, options); + if (!(0, import_util3.isString)(s)) return (0, import_internal2.errExpectString)(options.failOnError, "$strLenBytes"); + return ~-encodeURI(s).split(/%..|./).length; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenCP.js +var require_strLenCP = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenCP.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var strLenCP_exports = {}; + __export5(strLenCP_exports, { + $strLenCP: () => $strLenCP + }); + module.exports = __toCommonJS(strLenCP_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var $strLenCP = (obj, expr, options) => { + const s = (0, import_internal.evalExpr)(obj, expr, options); + if (!(0, import_util3.isString)(s)) return (0, import_internal2.errExpectString)(options.failOnError, "$strLenCP"); + return s.length; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrBytes.js +var require_substrBytes = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrBytes.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var substrBytes_exports = {}; + __export5(substrBytes_exports, { + $substrBytes: () => $substrBytes + }); + module.exports = __toCommonJS(substrBytes_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$substrBytes"; + var $substrBytes = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 3, `${OP} expects array(3)`); + const [s, index, count] = (0, import_internal.evalExpr)(obj, expr, options); + const foe = options.failOnError; + const nil = (0, import_util3.isNil)(s); + if (!nil && !(0, import_util3.isString)(s)) return (0, import_internal2.errExpectString)(foe, `${OP} arg1 `); + if (!(0, import_util3.isInteger)(index) || index < 0) + return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `, import_internal2.INT_OPTS.index); + if (!(0, import_util3.isInteger)(count) || count < 0) + return (0, import_internal2.errExpectNumber)(foe, `${OP} arg3 `, import_internal2.INT_OPTS.index); + if (nil) return ""; + let utf8Pos = 0; + let start16 = null; + let end16 = null; + const err = `${OP} UTF-8 boundary falls inside a continuation byte`; + for (let i = 0; i < s.length; ) { + const cp = s.codePointAt(i); + if (cp === void 0) + return (0, import_internal2.errInvalidArgs)(foe, `${OP} byte index out of range`); + const utf8Len = cp < 128 ? 1 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4; + const utf16Len = cp > 65535 ? 2 : 1; + if (start16 === null) { + if (index > utf8Pos && index < utf8Pos + utf8Len) + return (0, import_internal2.errInvalidArgs)(foe, err); + if (utf8Pos === index) { + start16 = i; + } + } + const endByte = index + count; + if (start16 !== null && end16 === null) { + if (endByte > utf8Pos && endByte < utf8Pos + utf8Len) + return (0, import_internal2.errInvalidArgs)(foe, err); + if (utf8Pos === endByte) { + end16 = i; + break; + } + } + utf8Pos += utf8Len; + i += utf16Len; + } + if (start16 === null) { + if (index === utf8Pos) return ""; + return (0, import_internal2.errInvalidArgs)(foe, `${OP} byte index out of range`); + } + if (end16 === null) { + const endByte = index + count; + if (endByte !== utf8Pos) + return (0, import_internal2.errInvalidArgs)(foe, `${OP} count extends beyond UTF-8 length`); + end16 = s.length; + } + return s.slice(start16, end16); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substr.js +var require_substr = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substr.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var substr_exports = {}; + __export5(substr_exports, { + $substr: () => $substr + }); + module.exports = __toCommonJS(substr_exports); + var import_substrBytes = require_substrBytes(); + var $substr = import_substrBytes.$substrBytes; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrCP.js +var require_substrCP = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrCP.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var substrCP_exports = {}; + __export5(substrCP_exports, { + $substrCP: () => $substrCP + }); + module.exports = __toCommonJS(substrCP_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var OP = "$substrCP"; + var $substrCP = (obj, expr, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 3, `${OP} expects array(3)`); + const [s, index, count] = (0, import_internal.evalExpr)(obj, expr, options); + const nil = (0, import_util3.isNil)(s); + const foe = options.failOnError; + if (!nil && !(0, import_util3.isString)(s)) return (0, import_internal2.errExpectString)(foe, `${OP} arg1 `); + if (!(0, import_util3.isInteger)(index)) return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `); + if (!(0, import_util3.isInteger)(count)) return (0, import_internal2.errExpectNumber)(foe, `${OP} arg3 `); + if (nil) return ""; + if (index < 0) return ""; + if (count < 0) return s.substring(index); + return s.substring(index, index + count); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toBool.js +var require_toBool = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toBool.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toBool_exports = {}; + __export5(toBool_exports, { + $toBool: () => $toBool + }); + module.exports = __toCommonJS(toBool_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $toBool = (obj, expr, options) => { + const val = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(val)) return null; + if ((0, import_util3.isString)(val)) return true; + return Boolean(val); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDate.js +var require_toDate = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDate.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toDate_exports = {}; + __export5(toDate_exports, { + $toDate: () => $toDate + }); + module.exports = __toCommonJS(toDate_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $toDate = (obj, expr, options) => { + const val = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isDate)(val)) return val; + if ((0, import_util3.isNil)(val)) return null; + const d = new Date(val); + (0, import_util3.assert)(!isNaN(d.getTime()), `cannot convert '${val}' to date`); + return d; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDouble.js +var require_toDouble = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDouble.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toDouble_exports = {}; + __export5(toDouble_exports, { + $toDouble: () => $toDouble + }); + module.exports = __toCommonJS(toDouble_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $toDouble = (obj, expr, options) => { + const val = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_util3.isNil)(val)) return null; + if ((0, import_util3.isDate)(val)) return val.getTime(); + if (val === true) return 1; + if (val === false) return 0; + const n = Number(val); + (0, import_util3.assert)((0, import_util3.isNumber)(n), `cannot convert '${val}' to double/decimal`); + return n; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/_internal.js +var require_internal10 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + MAX_INT: () => MAX_INT, + MAX_LONG: () => MAX_LONG, + MIN_INT: () => MIN_INT, + MIN_LONG: () => MIN_LONG, + toInteger: () => toInteger + }); + module.exports = __toCommonJS(internal_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var MAX_INT = 2147483647; + var MIN_INT = -2147483648; + var MAX_LONG = 9007199254740991; + var MIN_LONG = -9007199254740991; + function toInteger(obj, expr, options, min, max) { + const val = (0, import_internal.evalExpr)(obj, expr, options); + if (val === true) return 1; + if (val === false) return 0; + if ((0, import_util3.isNil)(val)) return null; + if ((0, import_util3.isDate)(val)) return val.getTime(); + const n = Number(val); + (0, import_util3.assert)( + (0, import_util3.isNumber)(n) && n >= min && n <= max && (!(0, import_util3.isString)(val) || n.toString().indexOf(".") === -1), + `cannot convert '${val}' to ${max == MAX_INT ? "int" : "long"}` + ); + return Math.trunc(n); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toInt.js +var require_toInt = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toInt.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toInt_exports = {}; + __export5(toInt_exports, { + $toInt: () => $toInt + }); + module.exports = __toCommonJS(toInt_exports); + var import_internal = require_internal10(); + var $toInt = (obj, expr, options) => (0, import_internal.toInteger)(obj, expr, options, import_internal.MIN_INT, import_internal.MAX_INT); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toLong.js +var require_toLong = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toLong.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toLong_exports = {}; + __export5(toLong_exports, { + $toLong: () => $toLong + }); + module.exports = __toCommonJS(toLong_exports); + var import_internal = require_internal10(); + var $toLong = (obj, expr, options) => (0, import_internal.toInteger)(obj, expr, options, import_internal.MIN_LONG, import_internal.MAX_LONG); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toString.js +var require_toString = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toString.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toString_exports = {}; + __export5(toString_exports, { + $toString: () => $toString + }); + module.exports = __toCommonJS(toString_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + var import_internal3 = require_internal4(); + var $toString = (obj, expr, options) => { + const val = (0, import_internal.evalExpr)(obj, expr, options); + if ((0, import_internal2.isNil)(val)) return null; + if ((0, import_internal2.isDate)(val)) return val.toISOString(); + if ((0, import_internal2.isPrimitive)(val) || (0, import_internal2.isRegExp)(val)) return String(val); + return (0, import_internal3.errInvalidArgs)( + options.failOnError, + "$toString cannot convert from object to string" + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/convert.js +var require_convert = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/convert.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var convert_exports = {}; + __export5(convert_exports, { + $convert: () => $convert + }); + module.exports = __toCommonJS(convert_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + var import_toBool = require_toBool(); + var import_toDate = require_toDate(); + var import_toDouble = require_toDouble(); + var import_toInt = require_toInt(); + var import_toLong = require_toLong(); + var import_toString = require_toString(); + var $convert = (obj, expr, options) => { + (0, import_util3.assert)( + (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "to"), + "$convert expects object { input, to, onError, onNull }" + ); + const input = (0, import_internal.evalExpr)(obj, expr.input, options); + if ((0, import_util3.isNil)(input)) return (0, import_internal.evalExpr)(obj, expr.onNull, options) ?? null; + const toExpr = (0, import_internal.evalExpr)(obj, expr.to, options); + try { + switch (toExpr) { + case 2: + case "string": + return (0, import_toString.$toString)(obj, input, options); + case 8: + case "boolean": + case "bool": + return (0, import_toBool.$toBool)(obj, input, options); + case 9: + case "date": + return (0, import_toDate.$toDate)(obj, input, options); + case 1: + case 19: + case "double": + case "decimal": + case "number": + return (0, import_toDouble.$toDouble)(obj, input, options); + case 16: + case "int": + return (0, import_toInt.$toInt)(obj, input, options); + case 18: + case "long": + return (0, import_toLong.$toLong)(obj, input, options); + } + } catch { + } + if (expr.onError === void 0) + return (0, import_internal2.errInvalidArgs)( + options.failOnError, + `$convert cannot convert from object to ${expr.to} with no onError value` + ); + return (0, import_internal.evalExpr)(obj, expr.onError, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/isNumber.js +var require_isNumber = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/isNumber.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var isNumber_exports = {}; + __export5(isNumber_exports, { + $isNumber: () => $isNumber + }); + module.exports = __toCommonJS(isNumber_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $isNumber = (obj, expr, options) => { + const n = (0, import_internal.evalExpr)(obj, expr, options); + return (0, import_util3.isNumber)(n); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDecimal.js +var require_toDecimal = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDecimal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toDecimal_exports = {}; + __export5(toDecimal_exports, { + $toDecimal: () => $toDecimal + }); + module.exports = __toCommonJS(toDecimal_exports); + var import_toDouble = require_toDouble(); + var $toDecimal = import_toDouble.$toDouble; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/type.js +var require_type = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/type.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var type_exports = {}; + __export5(type_exports, { + $type: () => $type + }); + module.exports = __toCommonJS(type_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal10(); + var $type = (obj, expr, options) => { + const v = (0, import_internal.evalExpr)(obj, expr, options); + if (options.useStrictMode) { + if (v === void 0) return "missing"; + if (v === true || v === false) return "bool"; + if ((0, import_util3.isNumber)(v)) { + if (v % 1 != 0) return "double"; + return v >= import_internal2.MIN_INT && v <= import_internal2.MAX_INT ? "int" : "long"; + } + if ((0, import_util3.isRegExp)(v)) return "regex"; + } + return (0, import_util3.typeOf)(v); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/index.js +var require_type2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var type_exports = {}; + module.exports = __toCommonJS(type_exports); + __reExport(type_exports, require_convert(), module.exports); + __reExport(type_exports, require_isNumber(), module.exports); + __reExport(type_exports, require_toBool(), module.exports); + __reExport(type_exports, require_toDate(), module.exports); + __reExport(type_exports, require_toDecimal(), module.exports); + __reExport(type_exports, require_toDouble(), module.exports); + __reExport(type_exports, require_toInt(), module.exports); + __reExport(type_exports, require_toLong(), module.exports); + __reExport(type_exports, require_toString(), module.exports); + __reExport(type_exports, require_type(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toLower.js +var require_toLower = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toLower.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toLower_exports = {}; + __export5(toLower_exports, { + $toLower: () => $toLower + }); + module.exports = __toCommonJS(toLower_exports); + var import_internal = require_internal(); + var import_type = require_type2(); + var $toLower = (obj, expr, options) => { + if ((0, import_internal.isArray)(expr) && expr.length === 1) expr = expr[0]; + const s = (0, import_type.$toString)(obj, expr, options); + return s === null ? s : s.toLowerCase(); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toUpper.js +var require_toUpper = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toUpper.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toUpper_exports = {}; + __export5(toUpper_exports, { + $toUpper: () => $toUpper + }); + module.exports = __toCommonJS(toUpper_exports); + var import_util3 = require_util(); + var import_type = require_type2(); + var $toUpper = (obj, expr, options) => { + if ((0, import_util3.isArray)(expr) && expr.length === 1) expr = expr[0]; + const s = (0, import_type.$toString)(obj, expr, options); + return s === null ? s : s.toUpperCase(); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/trim.js +var require_trim = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/trim.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var trim_exports = {}; + __export5(trim_exports, { + $trim: () => $trim + }); + module.exports = __toCommonJS(trim_exports); + var import_internal = require_internal9(); + var $trim = (obj, expr, options) => { + return (0, import_internal.trimString)(obj, expr, options, { left: true, right: true }); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/index.js +var require_string = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var string_exports = {}; + module.exports = __toCommonJS(string_exports); + __reExport(string_exports, require_concat(), module.exports); + __reExport(string_exports, require_indexOfBytes(), module.exports); + __reExport(string_exports, require_ltrim(), module.exports); + __reExport(string_exports, require_regexFind(), module.exports); + __reExport(string_exports, require_regexFindAll(), module.exports); + __reExport(string_exports, require_regexMatch(), module.exports); + __reExport(string_exports, require_replaceAll(), module.exports); + __reExport(string_exports, require_replaceOne(), module.exports); + __reExport(string_exports, require_rtrim(), module.exports); + __reExport(string_exports, require_split(), module.exports); + __reExport(string_exports, require_strcasecmp(), module.exports); + __reExport(string_exports, require_strLenBytes(), module.exports); + __reExport(string_exports, require_strLenCP(), module.exports); + __reExport(string_exports, require_substr(), module.exports); + __reExport(string_exports, require_substrBytes(), module.exports); + __reExport(string_exports, require_substrCP(), module.exports); + __reExport(string_exports, require_toLower(), module.exports); + __reExport(string_exports, require_toUpper(), module.exports); + __reExport(string_exports, require_trim(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/toHashedIndexKey.js +var require_toHashedIndexKey = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/toHashedIndexKey.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var toHashedIndexKey_exports = {}; + __export5(toHashedIndexKey_exports, { + $toHashedIndexKey: () => $toHashedIndexKey + }); + module.exports = __toCommonJS(toHashedIndexKey_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $toHashedIndexKey = (obj, expr, options) => (0, import_util3.hashCode)((0, import_internal.evalExpr)(obj, expr, options)); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/_internal.js +var require_internal11 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + processOperator: () => processOperator + }); + module.exports = __toCommonJS(internal_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal4(); + function processOperator(obj, expr, options, fn, fixedPoints) { + const fp = { + undefined: null, + null: null, + NaN: NaN, + Infinity: new Error(), + "-Infinity": new Error(), + ...fixedPoints + }; + const foe = options.failOnError; + const op = fn.name; + const n = (0, import_internal.evalExpr)(obj, expr, options); + if (n in fp) { + const res = fp[n]; + if (res instanceof Error) + return (0, import_internal2.errExpectNumber)(foe, `$${op} invalid input '${n}'`); + return res; + } + if (!(0, import_util3.isNumber)(n)) return (0, import_internal2.errExpectNumber)(foe, `$${op}`); + return fn(n); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acos.js +var require_acos = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acos.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var acos_exports = {}; + __export5(acos_exports, { + $acos: () => $acos + }); + module.exports = __toCommonJS(acos_exports); + var import_internal = require_internal11(); + var $acos = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.acos, { + Infinity: Infinity, + 0: new Error() + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acosh.js +var require_acosh = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acosh.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var acosh_exports = {}; + __export5(acosh_exports, { + $acosh: () => $acosh + }); + module.exports = __toCommonJS(acosh_exports); + var import_internal = require_internal11(); + var $acosh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.acosh, { + Infinity: Infinity, + 0: new Error() + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asin.js +var require_asin = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asin.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var asin_exports = {}; + __export5(asin_exports, { + $asin: () => $asin + }); + module.exports = __toCommonJS(asin_exports); + var import_internal = require_internal11(); + var $asin = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.asin); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asinh.js +var require_asinh = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asinh.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var asinh_exports = {}; + __export5(asinh_exports, { + $asinh: () => $asinh + }); + module.exports = __toCommonJS(asinh_exports); + var import_internal = require_internal11(); + var $asinh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.asinh, { + Infinity: Infinity, + "-Infinity": -Infinity + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan.js +var require_atan = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var atan_exports = {}; + __export5(atan_exports, { + $atan: () => $atan + }); + module.exports = __toCommonJS(atan_exports); + var import_internal = require_internal11(); + var $atan = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.atan); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan2.js +var require_atan2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan2.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var atan2_exports = {}; + __export5(atan2_exports, { + $atan2: () => $atan2 + }); + module.exports = __toCommonJS(atan2_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var $atan2 = (obj, expr, options) => { + const [y, x] = (0, import_internal.evalExpr)(obj, expr, options); + if (isNaN(y) || (0, import_util3.isNil)(y)) return y; + if (isNaN(x) || (0, import_util3.isNil)(x)) return x; + return Math.atan2(y, x); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atanh.js +var require_atanh = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atanh.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var atanh_exports = {}; + __export5(atanh_exports, { + $atanh: () => $atanh + }); + module.exports = __toCommonJS(atanh_exports); + var import_internal = require_internal11(); + var $atanh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.atanh, { + 1: Infinity, + "-1": -Infinity + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cos.js +var require_cos = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cos.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var cos_exports = {}; + __export5(cos_exports, { + $cos: () => $cos + }); + module.exports = __toCommonJS(cos_exports); + var import_internal = require_internal11(); + var $cos = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.cos); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cosh.js +var require_cosh = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cosh.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var cosh_exports = {}; + __export5(cosh_exports, { + $cosh: () => $cosh + }); + module.exports = __toCommonJS(cosh_exports); + var import_internal = require_internal11(); + var $cosh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.cosh, { + "-Infinity": Infinity, + Infinity: Infinity + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/degreesToRadians.js +var require_degreesToRadians = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/degreesToRadians.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var degreesToRadians_exports = {}; + __export5(degreesToRadians_exports, { + $degreesToRadians: () => $degreesToRadians + }); + module.exports = __toCommonJS(degreesToRadians_exports); + var import_internal = require_internal11(); + var degreesToRadians = (n) => n * (Math.PI / 180); + var $degreesToRadians = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, degreesToRadians, { + Infinity: Infinity, + "-Infinity": Infinity + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/radiansToDegrees.js +var require_radiansToDegrees = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/radiansToDegrees.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var radiansToDegrees_exports = {}; + __export5(radiansToDegrees_exports, { + $radiansToDegrees: () => $radiansToDegrees + }); + module.exports = __toCommonJS(radiansToDegrees_exports); + var import_internal = require_internal11(); + var radiansToDegrees = (n) => n * (180 / Math.PI); + var $radiansToDegrees = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, radiansToDegrees, { + Infinity: Infinity, + "-Infinity": Infinity + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sin.js +var require_sin = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sin.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sin_exports = {}; + __export5(sin_exports, { + $sin: () => $sin + }); + module.exports = __toCommonJS(sin_exports); + var import_internal = require_internal11(); + var $sin = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.sin); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sinh.js +var require_sinh = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sinh.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sinh_exports = {}; + __export5(sinh_exports, { + $sinh: () => $sinh + }); + module.exports = __toCommonJS(sinh_exports); + var import_internal = require_internal11(); + var $sinh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.sinh, { + "-Infinity": -Infinity, + Infinity: Infinity + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tan.js +var require_tan = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tan.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var tan_exports = {}; + __export5(tan_exports, { + $tan: () => $tan + }); + module.exports = __toCommonJS(tan_exports); + var import_internal = require_internal11(); + var $tan = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.tan); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tanh.js +var require_tanh = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tanh.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var tanh_exports = {}; + __export5(tanh_exports, { + $tanh: () => $tanh + }); + module.exports = __toCommonJS(tanh_exports); + var import_internal = require_internal11(); + var $tanh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.tanh, { + Infinity: 1, + "-Infinity": -1 + }); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/index.js +var require_trignometry = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var trignometry_exports = {}; + module.exports = __toCommonJS(trignometry_exports); + __reExport(trignometry_exports, require_acos(), module.exports); + __reExport(trignometry_exports, require_acosh(), module.exports); + __reExport(trignometry_exports, require_asin(), module.exports); + __reExport(trignometry_exports, require_asinh(), module.exports); + __reExport(trignometry_exports, require_atan(), module.exports); + __reExport(trignometry_exports, require_atan2(), module.exports); + __reExport(trignometry_exports, require_atanh(), module.exports); + __reExport(trignometry_exports, require_cos(), module.exports); + __reExport(trignometry_exports, require_cosh(), module.exports); + __reExport(trignometry_exports, require_degreesToRadians(), module.exports); + __reExport(trignometry_exports, require_radiansToDegrees(), module.exports); + __reExport(trignometry_exports, require_sin(), module.exports); + __reExport(trignometry_exports, require_sinh(), module.exports); + __reExport(trignometry_exports, require_tan(), module.exports); + __reExport(trignometry_exports, require_tanh(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/let.js +var require_let = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/let.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var let_exports = {}; + __export5(let_exports, { + $let: () => $let + }); + module.exports = __toCommonJS(let_exports); + var import_internal = require_internal2(); + var $let = (obj, expr, options) => { + const variables = {}; + for (const key of Object.keys(expr.vars)) { + variables[key] = (0, import_internal.evalExpr)(obj, expr.vars[key], options); + } + return (0, import_internal.evalExpr)( + obj, + expr.in, + import_internal.ComputeOptions.init(options).update({ variables }) + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/index.js +var require_variable = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var variable_exports = {}; + module.exports = __toCommonJS(variable_exports); + __reExport(variable_exports, require_let(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/index.js +var require_expression = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var expression_exports = {}; + module.exports = __toCommonJS(expression_exports); + __reExport(expression_exports, require_arithmetic(), module.exports); + __reExport(expression_exports, require_array(), module.exports); + __reExport(expression_exports, require_bitwise(), module.exports); + __reExport(expression_exports, require_boolean(), module.exports); + __reExport(expression_exports, require_comparison(), module.exports); + __reExport(expression_exports, require_conditional(), module.exports); + __reExport(expression_exports, require_custom(), module.exports); + __reExport(expression_exports, require_date(), module.exports); + __reExport(expression_exports, require_literal(), module.exports); + __reExport(expression_exports, require_median2(), module.exports); + __reExport(expression_exports, require_misc(), module.exports); + __reExport(expression_exports, require_object(), module.exports); + __reExport(expression_exports, require_percentile2(), module.exports); + __reExport(expression_exports, require_set(), module.exports); + __reExport(expression_exports, require_string(), module.exports); + __reExport(expression_exports, require_toHashedIndexKey(), module.exports); + __reExport(expression_exports, require_trignometry(), module.exports); + __reExport(expression_exports, require_type2(), module.exports); + __reExport(expression_exports, require_variable(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/addFields.js +var require_addFields = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/addFields.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var addFields_exports = {}; + __export5(addFields_exports, { + $addFields: () => $addFields + }); + module.exports = __toCommonJS(addFields_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + function $addFields(coll, expr, options) { + const newFields = Object.keys(expr); + if (newFields.length === 0) return coll; + return coll.map((obj) => { + const newObj = { ...obj }; + for (const field of newFields) { + const newValue = (0, import_internal.evalExpr)(obj, expr[field], options); + if (newValue !== void 0) { + (0, import_util3.setValue)(newObj, field, newValue); + } else { + (0, import_util3.removeValue)(newObj, field); + } + } + return newObj; + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucket.js +var require_bucket = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucket.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bucket_exports = {}; + __export5(bucket_exports, { + $bucket: () => $bucket + }); + module.exports = __toCommonJS(bucket_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + function $bucket(coll, expr, options) { + const bounds = expr.boundaries.slice(); + const defaultKey = expr.default; + const lower = bounds[0]; + const upper = bounds[bounds.length - 1]; + const outputExpr = expr.output || { count: { $sum: 1 } }; + (0, import_util3.assert)(bounds.length > 1, "$bucket: must specify at least two boundaries."); + const isValid = bounds.every( + (v, i) => i === 0 || (0, import_util3.typeOf)(v) === (0, import_util3.typeOf)(bounds[i - 1]) && (0, import_util3.compare)(v, bounds[i - 1]) > 0 + ); + (0, import_util3.assert)( + isValid, + `$bucket: bounds must be of same type and in ascending order` + ); + (0, import_util3.assert)( + (0, import_util3.isNil)(defaultKey) || (0, import_util3.typeOf)(defaultKey) !== (0, import_util3.typeOf)(lower) || (0, import_util3.compare)(defaultKey, upper) >= 0 || (0, import_util3.compare)(defaultKey, lower) < 0, + "$bucket: 'default' expression must be out of boundaries range" + ); + const createBuckets = () => { + const buckets = /* @__PURE__ */ new Map(); + for (let i = 0; i < bounds.length - 1; i++) { + buckets.set(bounds[i], []); + } + if (!(0, import_util3.isNil)(defaultKey)) buckets.set(defaultKey, []); + coll.each((obj) => { + const key = (0, import_internal.evalExpr)(obj, expr.groupBy, options); + if ((0, import_util3.isNil)(key) || (0, import_util3.compare)(key, lower) < 0 || (0, import_util3.compare)(key, upper) >= 0) { + (0, import_util3.assert)( + !(0, import_util3.isNil)(defaultKey), + "$bucket require a default for out of range values" + ); + buckets.get(defaultKey)?.push(obj); + } else { + (0, import_util3.assert)( + (0, import_util3.compare)(key, lower) >= 0 && (0, import_util3.compare)(key, upper) < 0, + "$bucket 'groupBy' expression must resolve to a value in range of boundaries" + ); + const index = (0, import_util3.findInsertIndex)(bounds, key); + const boundKey = bounds[Math.max(0, index - 1)]; + buckets.get(boundKey)?.push(obj); + } + }); + bounds.pop(); + if (!(0, import_util3.isNil)(defaultKey)) { + if (buckets.get(defaultKey)?.length) bounds.push(defaultKey); + else buckets.delete(defaultKey); + } + (0, import_util3.assert)( + buckets.size === bounds.length, + "bounds and groups must be of equal size." + ); + return (0, import_lazy.Lazy)(bounds).map((key) => { + return { + ...(0, import_internal.evalExpr)(buckets.get(key), outputExpr, options), + _id: key + }; + }); + }; + let iterator; + return (0, import_lazy.Lazy)(() => { + if (!iterator) iterator = createBuckets(); + return iterator.next(); + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucketAuto.js +var require_bucketAuto = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucketAuto.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bucketAuto_exports = {}; + __export5(bucketAuto_exports, { + $bucketAuto: () => $bucketAuto + }); + module.exports = __toCommonJS(bucketAuto_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + function $bucketAuto(coll, expr, options) { + const { + buckets: bucketCount, + groupBy: groupByExpr, + output: optOutputExpr, + // Available only if the all groupBy values are numeric and none of them are NaN. + granularity + } = expr; + const outputExpr = optOutputExpr ?? { count: { $sum: 1 } }; + (0, import_util3.assert)( + bucketCount > 0, + `$bucketAuto: 'buckets' field must be greater than 0, but found: ${bucketCount}` + ); + if (granularity) { + (0, import_util3.assert)( + /^(POWERSOF2|1-2-5|E(6|12|24|48|96|192)|R(5|10|20|40|80))$/.test( + granularity + ), + `$bucketAuto: invalid granularity '${granularity}'.` + ); + } + const keyMap = /* @__PURE__ */ new Map(); + const setKey = !granularity ? (o, k) => keyMap.set(o, k) : (_, _2) => { + }; + const sorted = coll.map((o) => { + const k = (0, import_internal.evalExpr)(o, groupByExpr, options) ?? null; + (0, import_util3.assert)( + !granularity || (0, import_util3.isNumber)(k), + "$bucketAuto: groupBy values must be numeric when granularity is specified." + ); + setKey(o, k ?? null); + return [k ?? null, o]; + }).collect(); + sorted.sort((x, y) => { + if ((0, import_util3.isNil)(x[0])) return -1; + if ((0, import_util3.isNil)(y[0])) return 1; + return (0, import_util3.compare)(x[0], y[0]); + }); + let getNext; + if (!granularity) { + getNext = granularityDefault(sorted, bucketCount, keyMap); + } else if (granularity == "POWERSOF2") { + getNext = granularityPowerOfTwo( + sorted, + bucketCount + ); + } else { + getNext = granularityPreferredSeries( + sorted, + bucketCount, + granularity + ); + } + let terminate = false; + return (0, import_lazy.Lazy)(() => { + if (terminate) return { done: true }; + const { min, max, bucket, done } = getNext(); + terminate = done; + const outFields = (0, import_internal.evalExpr)(bucket, outputExpr, options); + for (const k of Object.keys(outFields)) { + const v = outFields[k]; + if ((0, import_util3.isArray)(v)) outFields[k] = v.filter((v2) => !(0, import_util3.isNil)(v2)); + } + return { + done: false, + value: { + ...outFields, + _id: { min, max } + } + }; + }); + } + function granularityDefault(sorted, bucketCount, keyMap) { + const size = sorted.length; + const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount)); + let index = 0; + let nBuckets = 0; + return () => { + const isLastBucket = ++nBuckets == bucketCount; + const bucket = new Array(); + while (index < size && (isLastBucket || bucket.length < approxBucketSize || index > 0 && (0, import_util3.isEqual)(sorted[index - 1][0], sorted[index][0]))) { + bucket.push(sorted[index++][1]); + } + const min = keyMap.get(bucket[0]); + let max; + if (index < size) { + max = sorted[index][0]; + } else { + max = keyMap.get(bucket[bucket.length - 1]); + } + (0, import_util3.assert)( + (0, import_util3.isNil)(max) || (0, import_util3.isNil)(min) || (0, import_util3.compare)(min, max) <= 0, + `error: $bucketAuto boundary must be in order.` + ); + return { + min, + max, + bucket, + done: index >= size + }; + }; + } + function granularityPowerOfTwo(sorted, bucketCount) { + const size = sorted.length; + const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount)); + const roundUp2 = (n) => n === 0 ? 0 : 2 ** (Math.floor(Math.log2(n)) + 1); + let index = 0; + let min = 0; + let max = 0; + return () => { + const bucket = new Array(); + const boundValue = roundUp2(max); + min = index > 0 ? max : 0; + while (bucket.length < approxBucketSize && index < size && (max === 0 || sorted[index][0] < boundValue)) { + bucket.push(sorted[index++][1]); + } + max = max == 0 ? roundUp2(sorted[index - 1][0]) : boundValue; + while (index < size && sorted[index][0] < max) { + bucket.push(sorted[index++][1]); + } + return { + min, + max, + bucket, + done: index >= size + }; + }; + } + var PREFERRED_NUMBERS = { + // "Least rounded" Renard number series, taken from Wikipedia page on preferred + // numbers: https://en.wikipedia.org/wiki/Preferred_number#Renard_numbers + R5: [10, 16, 25, 40, 63], + R10: [100, 125, 160, 200, 250, 315, 400, 500, 630, 800], + R20: [ + 100, + 112, + 125, + 140, + 160, + 180, + 200, + 224, + 250, + 280, + 315, + 355, + 400, + 450, + 500, + 560, + 630, + 710, + 800, + 900 + ], + R40: [ + 100, + 106, + 112, + 118, + 125, + 132, + 140, + 150, + 160, + 170, + 180, + 190, + 200, + 212, + 224, + 236, + 250, + 265, + 280, + 300, + 315, + 355, + 375, + 400, + 425, + 450, + 475, + 500, + 530, + 560, + 600, + 630, + 670, + 710, + 750, + 800, + 850, + 900, + 950 + ], + R80: [ + 103, + 109, + 115, + 122, + 128, + 136, + 145, + 155, + 165, + 175, + 185, + 195, + 206, + 218, + 230, + 243, + 258, + 272, + 290, + 307, + 325, + 345, + 365, + 387, + 412, + 437, + 462, + 487, + 515, + 545, + 575, + 615, + 650, + 690, + 730, + 775, + 825, + 875, + 925, + 975 + ], + // https://en.wikipedia.org/wiki/Preferred_number#1-2-5_series + "1-2-5": [10, 20, 50], + // E series, taken from Wikipedia page on preferred numbers: + // https://en.wikipedia.org/wiki/Preferred_number#E_series + E6: [10, 15, 22, 33, 47, 68], + E12: [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82], + E24: [ + 10, + 11, + 12, + 13, + 15, + 16, + 18, + 20, + 22, + 24, + 27, + 30, + 33, + 36, + 39, + 43, + 47, + 51, + 56, + 62, + 68, + 75, + 82, + 91 + ], + E48: [ + 100, + 105, + 110, + 115, + 121, + 127, + 133, + 140, + 147, + 154, + 162, + 169, + 178, + 187, + 196, + 205, + 215, + 226, + 237, + 249, + 261, + 274, + 287, + 301, + 316, + 332, + 348, + 365, + 383, + 402, + 422, + 442, + 464, + 487, + 511, + 536, + 562, + 590, + 619, + 649, + 681, + 715, + 750, + 787, + 825, + 866, + 909, + 953 + ], + E96: [ + 100, + 102, + 105, + 107, + 110, + 113, + 115, + 118, + 121, + 124, + 127, + 130, + 133, + 137, + 140, + 143, + 147, + 150, + 154, + 158, + 162, + 165, + 169, + 174, + 178, + 182, + 187, + 191, + 196, + 200, + 205, + 210, + 215, + 221, + 226, + 232, + 237, + 243, + 249, + 255, + 261, + 267, + 274, + 280, + 287, + 294, + 301, + 309, + 316, + 324, + 332, + 340, + 348, + 357, + 365, + 374, + 383, + 392, + 402, + 412, + 422, + 432, + 442, + 453, + 464, + 475, + 487, + 499, + 511, + 523, + 536, + 549, + 562, + 576, + 590, + 604, + 619, + 634, + 649, + 665, + 681, + 698, + 715, + 732, + 750, + 768, + 787, + 806, + 825, + 845, + 866, + 887, + 909, + 931, + 953, + 976 + ], + E192: [ + 100, + 101, + 102, + 104, + 105, + 106, + 107, + 109, + 110, + 111, + 113, + 114, + 115, + 117, + 118, + 120, + 121, + 123, + 124, + 126, + 127, + 129, + 130, + 132, + 133, + 135, + 137, + 138, + 140, + 142, + 143, + 145, + 147, + 149, + 150, + 152, + 154, + 156, + 158, + 160, + 162, + 164, + 165, + 167, + 169, + 172, + 174, + 176, + 178, + 180, + 182, + 184, + 187, + 189, + 191, + 193, + 196, + 198, + 200, + 203, + 205, + 208, + 210, + 213, + 215, + 218, + 221, + 223, + 226, + 229, + 232, + 234, + 237, + 240, + 243, + 246, + 249, + 252, + 255, + 258, + 261, + 264, + 267, + 271, + 274, + 277, + 280, + 284, + 287, + 291, + 294, + 298, + 301, + 305, + 309, + 312, + 316, + 320, + 324, + 328, + 332, + 336, + 340, + 344, + 348, + 352, + 357, + 361, + 365, + 370, + 374, + 379, + 383, + 388, + 392, + 397, + 402, + 407, + 412, + 417, + 422, + 427, + 432, + 437, + 442, + 448, + 453, + 459, + 464, + 470, + 475, + 481, + 487, + 493, + 499, + 505, + 511, + 517, + 523, + 530, + 536, + 542, + 549, + 556, + 562, + 569, + 576, + 583, + 590, + 597, + 604, + 612, + 619, + 626, + 634, + 642, + 649, + 657, + 665, + 673, + 681, + 690, + 698, + 706, + 715, + 723, + 732, + 741, + 750, + 759, + 768, + 777, + 787, + 796, + 806, + 816, + 825, + 835, + 845, + 856, + 866, + 876, + 887, + 898, + 909, + 920, + 931, + 942, + 953, + 965, + 976, + 988 + ] + }; + var roundUp = (n, granularity) => { + if (n == 0) return 0; + const series = PREFERRED_NUMBERS[granularity]; + const first = series[0]; + const last = series[series.length - 1]; + let multiplier = 1; + while (n >= last * multiplier) { + multiplier *= 10; + } + let previousMin = 0; + while (n < first * multiplier) { + previousMin = first * multiplier; + multiplier /= 10; + if (n >= last * multiplier) { + return previousMin; + } + } + (0, import_util3.assert)( + n >= first * multiplier && n < last * multiplier, + "$bucketAuto: number out of range of series." + ); + const i = (0, import_util3.findInsertIndex)(series, n, (a, b) => { + b *= multiplier; + if (a < b) return -1; + if (a > b) return 1; + return 0; + }); + const seriesNumber = series[i] * multiplier; + return n == seriesNumber ? series[i + 1] * multiplier : seriesNumber; + }; + function granularityPreferredSeries(sorted, bucketCount, granularity) { + const size = sorted.length; + const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount)); + let index = 0; + let nBuckets = 0; + let min = 0; + let max = 0; + return () => { + const isLastBucket = ++nBuckets == bucketCount; + const bucket = new Array(); + min = index > 0 ? max : 0; + while (index < size && (isLastBucket || bucket.length < approxBucketSize)) { + bucket.push(sorted[index++][1]); + } + max = roundUp(sorted[index - 1][0], granularity); + const nItems = bucket.length; + while (index < size && (isLastBucket || sorted[index][0] < max)) { + bucket.push(sorted[index++][1]); + } + if (nItems != bucket.length) { + max = roundUp(sorted[index - 1][0], granularity); + } + (0, import_util3.assert)(min < max, `$bucketAuto: ${min} < ${max}.`); + return { min, max, bucket, done: index >= size }; + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/count.js +var require_count2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/count.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var count_exports = {}; + __export5(count_exports, { + $count: () => $count + }); + module.exports = __toCommonJS(count_exports); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + function $count(coll, expr, _options2) { + (0, import_util3.assert)( + (0, import_util3.isString)(expr) && expr.trim().length > 0 && !expr.includes(".") && expr[0] !== "$", + "$count expression must evaluate to valid field name" + ); + let i = 0; + return (0, import_lazy.Lazy)(() => { + if (i++ == 0) return { value: { [expr]: coll.size() }, done: false }; + return { done: true }; + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/densify.js +var require_densify = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/densify.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var densify_exports = {}; + __export5(densify_exports, { + $densify: () => $densify + }); + module.exports = __toCommonJS(densify_exports); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + var import_internal = require_internal8(); + var import_dateAdd = require_dateAdd(); + var import_sort = require_sort(); + var OP = "$densify"; + function $densify(coll, expr, options) { + const { step, bounds, unit } = expr.range; + if (unit) { + (0, import_util3.assert)( + import_internal.TIME_UNITS.includes(unit), + `${OP} 'range.unit' value is not supported.` + ); + (0, import_util3.assert)( + (0, import_util3.isInteger)(step) && step > 0, + `${OP} 'range.step' must resolve to integer if 'range.unit' is specified.` + ); + } else { + (0, import_util3.assert)((0, import_util3.isNumber)(step), `${OP} 'range.step' must resolve to number.`); + } + if ((0, import_util3.isArray)(bounds)) { + (0, import_util3.assert)( + !!bounds && bounds.length === 2, + `${OP} 'range.bounds' must have exactly two elements.` + ); + (0, import_util3.assert)( + (bounds.every(import_util3.isNumber) || bounds.every(import_util3.isDate)) && bounds[0] < bounds[1], + `${OP} 'range.bounds' must be ordered lower then upper.` + ); + if (unit) { + (0, import_util3.assert)( + bounds.every(import_util3.isDate), + `${OP} 'range.bounds' must be dates if 'range.unit' is specified.` + ); + } + } + if (expr.partitionByFields) { + (0, import_util3.assert)( + (0, import_util3.isArray)(expr.partitionByFields), + `${OP} 'partitionByFields' must resolve to array of strings.` + ); + } + const partitionByFields = expr.partitionByFields ?? []; + coll = (0, import_sort.$sort)(coll, { [expr.field]: 1 }, options); + const computeNextValue = (value) => { + return (0, import_util3.isNumber)(value) ? value + step : (0, import_dateAdd.$dateAdd)({}, { startDate: value, unit, amount: step }, options); + }; + const isValidUnit = !!unit && import_internal.TIME_UNITS.includes(unit); + const getFieldValue = (o) => { + const v = (0, import_util3.resolve)(o, expr.field); + (0, import_util3.assert)( + (0, import_util3.isNil)(v) || (0, import_util3.isDate)(v) && isValidUnit || (0, import_util3.isNumber)(v) && !isValidUnit, + `${OP} Densify field type must be numeric with 'unit' unspecified, or a date with 'unit' specified.` + ); + return v; + }; + const peekItem = new Array(); + const nilFieldsIterator = (0, import_lazy.Lazy)(() => { + const item = coll.next(); + const fieldValue = getFieldValue(item.value); + if ((0, import_util3.isNil)(fieldValue)) return item; + peekItem.push(item); + return { done: true }; + }); + const nextDensifyValueMap = import_util3.HashMap.init(); + const [lower, upper] = (0, import_util3.isArray)(bounds) ? bounds : [bounds, bounds]; + let maxFieldValue; + const updateMaxFieldValue = (value) => { + maxFieldValue = maxFieldValue === void 0 || maxFieldValue < value ? value : maxFieldValue; + }; + const rootKey = []; + const densifyIterator = (0, import_lazy.Lazy)(() => { + const item = peekItem.pop() || coll.next(); + if (item.done) return item; + let partitionKey = rootKey; + if ((0, import_util3.isArray)(partitionByFields)) { + partitionKey = partitionByFields.map( + (k) => (0, import_util3.resolve)(item.value, k) + ); + (0, import_util3.assert)( + partitionKey.every(import_util3.isString), + "$densify: Partition fields must evaluate to string values." + ); + } + (0, import_util3.assert)((0, import_util3.isObject)(item.value), "$densify: collection must contain documents"); + const itemValue = getFieldValue(item.value); + if (!nextDensifyValueMap.has(partitionKey)) { + if (lower == "full") { + if (!nextDensifyValueMap.has(rootKey)) { + nextDensifyValueMap.set(rootKey, itemValue); + } + nextDensifyValueMap.set( + partitionKey, + nextDensifyValueMap.get(rootKey) + ); + } else if (lower == "partition") { + nextDensifyValueMap.set(partitionKey, itemValue); + } else { + nextDensifyValueMap.set(partitionKey, lower); + } + } + const densifyValue = nextDensifyValueMap.get(partitionKey); + if ( + // current item field value is lower than current densify value. + itemValue <= densifyValue || // range value equals or exceeds upper bound + upper != "full" && upper != "partition" && densifyValue >= upper + ) { + if (densifyValue <= itemValue) { + nextDensifyValueMap.set(partitionKey, computeNextValue(densifyValue)); + } + updateMaxFieldValue(itemValue); + return item; + } + nextDensifyValueMap.set(partitionKey, computeNextValue(densifyValue)); + updateMaxFieldValue(densifyValue); + const denseObj = { [expr.field]: densifyValue }; + if (partitionKey) { + for (let i = 0; i < partitionKey.length; i++) { + denseObj[partitionByFields[i]] = partitionKey[i]; + } + } + peekItem.push(item); + return { done: false, value: denseObj }; + }); + if (lower !== "full") return (0, import_lazy.concat)(nilFieldsIterator, densifyIterator); + let paritionIndex = -1; + let partitionKeysSet; + const fullBoundsIterator = (0, import_lazy.Lazy)(() => { + if (paritionIndex === -1) { + const fullDensifyValue = nextDensifyValueMap.get(rootKey); + nextDensifyValueMap.delete(rootKey); + partitionKeysSet = Array.from(nextDensifyValueMap.keys()); + if (partitionKeysSet.length === 0) { + partitionKeysSet.push(rootKey); + nextDensifyValueMap.set(rootKey, fullDensifyValue); + } + paritionIndex++; + } + do { + const partitionKey = partitionKeysSet[paritionIndex]; + const partitionMaxValue = nextDensifyValueMap.get(partitionKey); + if (partitionMaxValue < maxFieldValue) { + nextDensifyValueMap.set( + partitionKey, + computeNextValue(partitionMaxValue) + ); + const denseObj = { [expr.field]: partitionMaxValue }; + for (let i = 0; i < partitionKey.length; i++) { + denseObj[partitionByFields[i]] = partitionKey[i]; + } + return { done: false, value: denseObj }; + } + paritionIndex++; + } while (paritionIndex < partitionKeysSet.length); + return { done: true }; + }); + return (0, import_lazy.concat)(nilFieldsIterator, densifyIterator, fullBoundsIterator); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/facet.js +var require_facet = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/facet.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var facet_exports = {}; + __export5(facet_exports, { + $facet: () => $facet + }); + module.exports = __toCommonJS(facet_exports); + var import_aggregator = require_aggregator(); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + function $facet(coll, expr, options) { + if (!(options.processingMode & import_internal.ProcessingMode.CLONE_INPUT)) { + options = { + ...import_internal.ComputeOptions.init(options).options, + processingMode: import_internal.ProcessingMode.CLONE_INPUT + }; + } + return coll.transform((arr) => { + const o = {}; + for (const k of Object.keys(expr)) { + o[k] = new import_aggregator.Aggregator(expr[k], options).run(arr); + } + return (0, import_lazy.Lazy)([o]); + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/_internal.js +var require_internal12 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + cached: () => cached2, + rank: () => rank, + withMemo: () => withMemo + }); + module.exports = __toCommonJS(internal_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var memo = /* @__PURE__ */ new WeakMap(); + var cached2 = (xs) => memo.has(xs); + function withMemo(collection, expr, initialize, fn) { + if (!memo.has(collection)) { + memo.set(collection, {}); + } + const data = memo.get(collection); + if (!(expr.field in data)) { + data[expr.field] = initialize(); + } + let ok2 = false; + try { + const res = fn(data[expr.field]); + ok2 = true; + return res; + } finally { + if (!ok2) { + memo.delete(collection); + } else if (expr.documentNumber === collection.length) { + delete data[expr.field]; + if (Object.keys(data).length === 0) memo.delete(collection); + } + } + } + function rank(_, collection, expr, options, dense) { + return withMemo( + collection, + expr, + () => { + const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0]; + const values = (0, import_push.$push)(collection, sortKey, options); + const groups = (0, import_util3.groupBy)( + values, + (_2, n) => values[n] + ); + let i = 0; + let offset = 0; + for (const key of groups.keys()) { + const len = groups.get(key).length; + groups.set(key, [i++, offset]); + offset += len; + } + return { values, groups }; + }, + ({ values, groups }) => { + if (groups.size == collection.length) return expr.documentNumber; + const current = values[expr.documentNumber - 1]; + const [i, n] = groups.get(current); + return (dense ? i : n) + 1; + } + ); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/linearFill.js +var require_linearFill = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/linearFill.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var linearFill_exports = {}; + __export5(linearFill_exports, { + $linearFill: () => $linearFill + }); + module.exports = __toCommonJS(linearFill_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var import_internal = require_internal12(); + var interpolate = (x1, y1, x2, y2, x) => y1 + (x - x1) * ((y2 - y1) / (x2 - x1)); + var $linearFill = (_, coll, expr, options) => { + return (0, import_internal.withMemo)( + coll, + expr, + () => { + const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0]; + const points = (0, import_push.$push)(coll, [sortKey, expr.inputExpr], options).filter(([ + x, + _2 + ]) => (0, import_util3.isNumber)(+x)); + let lindex = -1; + let rindex = 0; + while (rindex < points.length) { + while (lindex + 1 < points.length && (0, import_util3.isNumber)(points[lindex + 1][1])) { + lindex++; + rindex = lindex; + } + while (rindex + 1 < points.length && !(0, import_util3.isNumber)(points[rindex + 1][1])) { + rindex++; + } + if (rindex + 1 >= points.length) break; + rindex++; + while (lindex + 1 < rindex) { + points[lindex + 1][1] = interpolate( + points[lindex][0], + points[lindex][1], + points[rindex][0], + points[rindex][1], + points[lindex + 1][0] + ); + lindex++; + } + lindex = rindex; + } + return points.map(([_2, y]) => y); + }, + (values) => values[expr.documentNumber - 1] + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/locf.js +var require_locf = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/locf.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var locf_exports = {}; + __export5(locf_exports, { + $locf: () => $locf + }); + module.exports = __toCommonJS(locf_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var import_internal = require_internal12(); + var $locf = (_, coll, expr, options) => { + return (0, import_internal.withMemo)( + coll, + expr, + () => { + const values = (0, import_push.$push)(coll, expr.inputExpr, options); + for (let i = 1; i < values.length; i++) { + if ((0, import_util3.isNil)(values[i])) values[i] = values[i - 1]; + } + return values; + }, + (series) => series[expr.documentNumber - 1] + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/group.js +var require_group = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/group.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var group_exports = {}; + __export5(group_exports, { + $group: () => $group + }); + module.exports = __toCommonJS(group_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + var ID_KEY = "_id"; + function $group(coll, expr, options) { + (0, import_util3.assert)((0, import_util3.has)(expr, ID_KEY), "$group specification must include an '_id'"); + const idExpr = expr[ID_KEY]; + const copts = import_internal.ComputeOptions.init(options); + const newFields = Object.keys(expr).filter((k) => k != ID_KEY); + return coll.transform((items) => { + const partitions = (0, import_util3.groupBy)(items, (obj) => (0, import_internal.evalExpr)(obj, idExpr, options)); + let i = -1; + const partitionKeys = Array.from(partitions.keys()); + return (0, import_lazy.Lazy)(() => { + if (++i === partitions.size) return { done: true }; + const groupId = partitionKeys[i]; + const obj = {}; + if (groupId !== void 0) { + obj[ID_KEY] = groupId; + } + for (const key of newFields) { + obj[key] = (0, import_internal.evalExpr)( + partitions.get(groupId), + expr[key], + copts.update({ root: null, groupId }) + ); + } + return { value: obj, done: false }; + }); + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/setWindowFields.js +var require_setWindowFields = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/setWindowFields.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var setWindowFields_exports = {}; + __export5(setWindowFields_exports, { + $setWindowFields: () => $setWindowFields + }); + module.exports = __toCommonJS(setWindowFields_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + var import_function = require_function(); + var import_dateAdd = require_dateAdd(); + var import_addFields = require_addFields(); + var import_group = require_group(); + var import_sort = require_sort(); + var SORT_REQUIRED_OPS = [ + "$denseRank", + "$documentNumber", + "$first", + "$last", + "$linearFill", + "$rank", + "$shift" + ]; + var WINDOW_UNBOUNDED_OPS = [ + "$denseRank", + "$expMovingAvg", + "$linearFill", + "$locf", + "$rank", + "$shift" + ]; + var isUnbounded = (window2) => { + const boundary = window2?.documents || window2?.range; + return !boundary || boundary[0] === "unbounded" && boundary[1] === "unbounded"; + }; + var OP = "$setWindowFields"; + function $setWindowFields(coll, expr, options) { + options = import_internal.ComputeOptions.init(options); + options.context.addExpressionOps({ $function: import_function.$function }); + const operators = {}; + const outputFields = Object.keys(expr.output); + for (const field of outputFields) { + const outputExpr = expr.output[field]; + const keys = Object.keys(outputExpr); + const op = keys.find(import_util3.isOperator); + const context = options.context; + (0, import_util3.assert)( + op && (!!context.getOperator(import_internal.OpType.WINDOW, op) || !!context.getOperator(import_internal.OpType.ACCUMULATOR, op)), + `${OP} '${op}' is not a valid window operator` + ); + (0, import_util3.assert)( + keys.length > 0 && keys.length <= 2 && (keys.length == 1 || keys.includes("window")), + `${OP} 'output' option should have a single window operator.` + ); + if (outputExpr?.window) { + const { documents, range } = outputExpr.window; + (0, import_util3.assert)( + (+!!documents ^ +!!range) === 1, + "'window' option supports only one of 'documents' or 'range'." + ); + } + operators[field] = op; + } + if (expr.sortBy) { + coll = (0, import_sort.$sort)(coll, expr.sortBy, options); + } + coll = (0, import_group.$group)( + coll, + { + _id: expr.partitionBy, + items: { $push: "$$CURRENT" } + }, + options + ); + return coll.transform((partitions) => { + const iterators = []; + const outputConfig = []; + for (const field of outputFields) { + const outputExpr = expr.output[field]; + const op = operators[field]; + const config4 = { + operatorName: op, + func: { + left: options.context.getOperator(import_internal.OpType.ACCUMULATOR, op), + right: options.context.getOperator(import_internal.OpType.WINDOW, op) + }, + args: outputExpr[op], + field, + window: outputExpr.window + }; + const unbounded = isUnbounded(config4.window); + if (unbounded == false || SORT_REQUIRED_OPS.includes(op)) { + const suffix = unbounded ? `'${op}'` : "bounded window operations"; + (0, import_util3.assert)(expr.sortBy, `${OP} 'sortBy' is required for ${suffix}.`); + } + (0, import_util3.assert)( + unbounded || !WINDOW_UNBOUNDED_OPS.includes(op), + `${OP} cannot use bounded window for operator '${op}'.` + ); + outputConfig.push(config4); + } + for (const group of partitions) { + const items = group.items; + let iterator = (0, import_lazy.Lazy)(items); + const windowResultMap = {}; + for (const config4 of outputConfig) { + const { func, args, field, window: window2 } = config4; + const makeResultFunc = (getItemsFn) => { + let index = -1; + return (obj) => { + ++index; + if (func.left) { + return func.left(getItemsFn(obj, index), args, options); + } else if (func.right) { + return func.right( + obj, + getItemsFn(obj, index), + { + parentExpr: expr, + inputExpr: args, + documentNumber: index + 1, + field + }, + // must use raw options only since it operates over a collection. + options + ); + } + }; + }; + if (window2) { + const { documents, range, unit } = window2; + const boundary = documents || range; + if (!isUnbounded(window2)) { + const [begin, end] = boundary; + const toBeginIndex = (currentIndex) => { + if (begin == "current") return currentIndex; + if (begin == "unbounded") return 0; + return Math.max(begin + currentIndex, 0); + }; + const toEndIndex = (currentIndex) => { + if (end == "current") return currentIndex + 1; + if (end == "unbounded") return items.length; + return end + currentIndex + 1; + }; + const getItems = (current, index) => { + if (!!documents || boundary?.every(import_util3.isString)) { + return items.slice(toBeginIndex(index), toEndIndex(index)); + } + const sortKey = Object.keys(expr.sortBy)[0]; + let lower; + let upper; + if (unit) { + const startDate = new Date(current[sortKey]); + const getTime = (amount) => { + const addExpr = { startDate, unit, amount }; + const d = (0, import_dateAdd.$dateAdd)(current, addExpr, options); + return d.getTime(); + }; + lower = (0, import_util3.isNumber)(begin) ? getTime(begin) : -Infinity; + upper = (0, import_util3.isNumber)(end) ? getTime(end) : Infinity; + } else { + const currentValue = current[sortKey]; + lower = (0, import_util3.isNumber)(begin) ? currentValue + begin : -Infinity; + upper = (0, import_util3.isNumber)(end) ? currentValue + end : Infinity; + } + let i = begin == "current" ? index : 0; + const sliceEnd = end == "current" ? index + 1 : items.length; + const array2 = new Array(); + while (i < sliceEnd) { + const o = items[i++]; + const n = +o[sortKey]; + if (n >= lower && n <= upper) array2.push(o); + } + return array2; + }; + windowResultMap[field] = makeResultFunc(getItems); + } + } + if (!windowResultMap[field]) { + windowResultMap[field] = makeResultFunc((_) => items); + } + iterator = (0, import_addFields.$addFields)( + iterator, + { + [field]: { + $function: { + body: (obj) => windowResultMap[field](obj), + args: ["$$CURRENT"] + } + } + }, + options + ); + } + iterators.push(iterator); + } + return (0, import_lazy.concat)(...iterators); + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/fill.js +var require_fill = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/fill.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var fill_exports = {}; + __export5(fill_exports, { + $fill: () => $fill + }); + module.exports = __toCommonJS(fill_exports); + var import_util3 = require_util(); + var import_ifNull = require_ifNull(); + var import_linearFill = require_linearFill(); + var import_locf = require_locf(); + var import_addFields = require_addFields(); + var import_setWindowFields = require_setWindowFields(); + var FILL_METHODS = { locf: "$locf", linear: "$linearFill" }; + function $fill(coll, expr, options) { + (0, import_util3.assert)(!expr.sortBy || (0, import_util3.isObject)(expr.sortBy), "sortBy must be an object."); + (0, import_util3.assert)( + !!expr.sortBy || Object.values(expr.output).every((m) => (0, import_util3.has)(m, "value")), + "sortBy required if any output field specifies a 'method'." + ); + (0, import_util3.assert)( + !(expr.partitionBy && expr.partitionByFields), + "specify either partitionBy or partitionByFields." + ); + (0, import_util3.assert)( + !expr.partitionByFields || expr?.partitionByFields?.every((s) => s[0] !== "$"), + "fields in partitionByFields cannot begin with '$'." + ); + options.context.addExpressionOps({ $ifNull: import_ifNull.$ifNull }); + options.context.addWindowOps({ $locf: import_locf.$locf, $linearFill: import_linearFill.$linearFill }); + const partitionExpr = expr.partitionBy || expr?.partitionByFields?.map((s) => "$" + s); + const valueExpr = {}; + const methodExpr = {}; + for (const k of Object.keys(expr.output)) { + const m = expr.output[k]; + if ((0, import_util3.has)(m, "value")) { + const out = m; + valueExpr[k] = { $ifNull: [`$$CURRENT.${k}`, out.value] }; + } else { + const out = m; + const fillOp = FILL_METHODS[out.method]; + (0, import_util3.assert)(!!fillOp, `invalid fill method '${out.method}'.`); + methodExpr[k] = { [fillOp]: "$" + k }; + } + } + if (Object.keys(methodExpr).length > 0) { + coll = (0, import_setWindowFields.$setWindowFields)( + coll, + { + sortBy: expr.sortBy || {}, + partitionBy: partitionExpr, + output: methodExpr + }, + options + ); + } + if (Object.keys(valueExpr).length > 0) { + coll = (0, import_addFields.$addFields)(coll, valueExpr, options); + } + return coll; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/lookup.js +var require_lookup = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/lookup.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var lookup_exports = {}; + __export5(lookup_exports, { + $lookup: () => $lookup + }); + module.exports = __toCommonJS(lookup_exports); + var import_aggregator = require_aggregator(); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_internal2 = require_internal7(); + function $lookup(coll, expr, options) { + const { let: letExpr, foreignField, localField } = expr; + let lookupEq = (_) => [true, []]; + let joinColl = (0, import_util3.isString)(expr.from) ? (0, import_internal2.resolveCollection)("$lookup", expr.from, options) : expr.from; + const { documents, pipeline } = (0, import_internal2.filterDocumentsStage)( + expr.pipeline ?? [], + options + ); + (0, import_util3.assert)( + !joinColl !== !documents, + "$lookup: must specify single join input with `expr.from` or `expr.pipeline`." + ); + joinColl = joinColl ?? documents; + (0, import_util3.assert)( + (0, import_util3.isArray)(joinColl), + "$lookup: join collection must resolve to an array." + ); + if (foreignField && localField) { + const map3 = import_util3.HashMap.init(); + for (const doc of joinColl) { + for (const v of (0, import_util3.ensureArray)((0, import_util3.resolve)(doc, foreignField) ?? null)) { + const xs = map3.get(v); + const arr = xs ?? []; + arr.push(doc); + if (arr !== xs) map3.set(v, arr); + } + } + lookupEq = (o) => { + const local = (0, import_util3.resolve)(o, localField) ?? null; + if ((0, import_util3.isArray)(local)) { + if (pipeline?.length) { + return [local.some((v) => map3.has(v)), []]; + } + const result2 = Array.from(new Set((0, import_util3.flatten)(local.map((v) => map3.get(v))))); + return [result2.length > 0, result2]; + } + const result = map3.get(local) ?? null; + return [result !== null, result ?? []]; + }; + if (pipeline?.length === 0) { + return coll.map((obj) => { + return { ...obj, [expr.as]: lookupEq(obj).pop() }; + }); + } + } + const agg = new import_aggregator.Aggregator(pipeline ?? [], options); + const opts = import_internal.ComputeOptions.init(options); + return coll.map((obj) => { + const vars = (0, import_internal.evalExpr)(obj, letExpr, options); + opts.update({ root: null, variables: vars }); + const [ok2, res] = lookupEq(obj); + return { ...obj, [expr.as]: ok2 ? agg.run(joinColl, opts) : res }; + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/graphLookup.js +var require_graphLookup = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/graphLookup.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var graphLookup_exports = {}; + __export5(graphLookup_exports, { + $graphLookup: () => $graphLookup + }); + module.exports = __toCommonJS(graphLookup_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + var import_internal2 = require_internal7(); + var import_lookup = require_lookup(); + function $graphLookup(coll, expr, options) { + const fromColl = (0, import_internal2.resolveCollection)("$graphLookup", expr.from, options); + (0, import_util3.assert)( + (0, import_util3.isArray)(fromColl), + "$graphLookup: expression 'from' must resolve to array" + ); + const { + connectFromField, + connectToField, + as: asField, + maxDepth, + depthField, + restrictSearchWithMatch: matchExpr + } = expr; + const pipelineExpr = matchExpr ? { pipeline: [{ $match: matchExpr }] } : {}; + return coll.map((obj) => { + const matchObj = {}; + (0, import_util3.setValue)( + matchObj, + connectFromField, + (0, import_internal.evalExpr)(obj, expr.startWith, options) + ); + let matches = [matchObj]; + let i = -1; + const map3 = import_util3.HashMap.init(); + do { + i++; + matches = (0, import_util3.flatten)( + (0, import_lookup.$lookup)( + (0, import_lazy.Lazy)(matches), + { + from: fromColl, + localField: connectFromField, + foreignField: connectToField, + as: asField, + ...pipelineExpr + }, + options + ).map((o) => o[asField]).collect() + ); + const oldSize = map3.size; + for (const k of matches) map3.set(k, map3.get(k) ?? i); + if (oldSize == map3.size) break; + } while ((0, import_util3.isNil)(maxDepth) || i < maxDepth); + const result = new Array(map3.size); + let n = 0; + for (const [k, v] of map3.entries()) { + result[n++] = Object.assign(depthField ? { [depthField]: v } : {}, k); + } + return { ...obj, [asField]: result }; + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/match.js +var require_match = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/match.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var match_exports = {}; + __export5(match_exports, { + $match: () => $match + }); + module.exports = __toCommonJS(match_exports); + var import_query = require_query(); + function $match(coll, expr, options) { + const q = new import_query.Query(expr, options); + return coll.filter((o) => q.test(o)); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/merge.js +var require_merge = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/merge.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var merge_exports = {}; + __export5(merge_exports, { + $merge: () => $merge + }); + module.exports = __toCommonJS(merge_exports); + var import_aggregator = require_aggregator(); + var import_internal = require_internal2(); + var import_util3 = require_util(); + var import_expression3 = require_expression(); + var import_internal2 = require_internal7(); + function $merge(coll, expr, options) { + const output = (0, import_internal2.resolveCollection)("$merge", expr.into, options); + (0, import_util3.assert)((0, import_util3.isArray)(output), `$merge: expression 'into' must resolve to an array`); + const onField = expr.on || options.idKey; + const getHash = (0, import_util3.isString)(onField) ? (o) => (0, import_util3.hashCode)((0, import_util3.resolve)(o, onField)) : (o) => (0, import_util3.hashCode)(onField.map((s) => (0, import_util3.resolve)(o, s))); + const map3 = import_util3.HashMap.init(); + for (let i = 0; i < output.length; i++) { + const obj = output[i]; + const k = getHash(obj); + (0, import_util3.assert)( + !map3.has(k), + "$merge: 'into' collection must have unique entries for the 'on' field." + ); + map3.set(k, [obj, i]); + } + const copts = import_internal.ComputeOptions.init(options); + return coll.map((o) => { + const k = getHash(o); + if (map3.has(k)) { + const [target, i] = map3.get(k); + const variables = (0, import_internal.evalExpr)( + target, + expr.let || { new: "$$ROOT" }, + // 'root' is the item from the iteration. + copts.update({ root: o }) + ); + if ((0, import_util3.isArray)(expr.whenMatched)) { + const aggregator = new import_aggregator.Aggregator( + expr.whenMatched, + copts.update({ root: null, variables }) + ); + output[i] = aggregator.run([target])[0]; + } else { + switch (expr.whenMatched) { + case "replace": + output[i] = o; + break; + case "fail": + throw new import_util3.MingoError( + "$merge: failed due to matching as specified by 'whenMatched' option." + ); + case "keepExisting": + break; + case "merge": + default: + output[i] = (0, import_expression3.$mergeObjects)( + target, + [target, o], + // 'root' is the item from the iteration. + copts.update({ root: o, variables }) + ); + break; + } + } + } else { + switch (expr.whenNotMatched) { + case "discard": + break; + case "fail": + throw new import_util3.MingoError( + "$merge: failed due to matching as specified by 'whenMatched' option." + ); + case "insert": + default: + output.push(o); + break; + } + } + return o; + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/out.js +var require_out = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/out.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var out_exports = {}; + __export5(out_exports, { + $out: () => $out + }); + module.exports = __toCommonJS(out_exports); + var import_util3 = require_util(); + var import_internal = require_internal7(); + function $out(coll, expr, options) { + const out = (0, import_internal.resolveCollection)("$out", expr, options); + (0, import_util3.assert)((0, import_util3.isArray)(out), `$out: expression must resolve to an array`); + return coll.map((o) => { + out.push((0, import_util3.cloneDeep)(o)); + return o; + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/redact.js +var require_redact = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/redact.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var redact_exports = {}; + __export5(redact_exports, { + $redact: () => $redact + }); + module.exports = __toCommonJS(redact_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + function $redact(coll, expr, options) { + const copts = import_internal.ComputeOptions.init(options); + return coll.map( + (root) => redact(root, expr, copts.update({ root })) + ); + } + function redact(obj, expr, options) { + const action = (0, import_internal.evalExpr)(obj, expr, options); + switch (action) { + case "$$KEEP": + return obj; + case "$$PRUNE": + return void 0; + case "$$DESCEND": { + if (!(0, import_util3.has)(expr, "$cond")) return obj; + const output = {}; + for (const key of Object.keys(obj)) { + const value = obj[key]; + if ((0, import_util3.isArray)(value)) { + const res = new Array(); + for (let elem of value) { + if ((0, import_util3.isObject)(elem)) { + elem = redact(elem, expr, options.update({ root: elem })); + } + if (!(0, import_util3.isNil)(elem)) res.push(elem); + } + output[key] = res; + } else if ((0, import_util3.isObject)(value)) { + const res = redact( + value, + expr, + options.update({ root: value }) + ); + if (!(0, import_util3.isNil)(res)) output[key] = res; + } else { + output[key] = value; + } + } + return output; + } + default: + return action; + } + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceRoot.js +var require_replaceRoot = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceRoot.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var replaceRoot_exports = {}; + __export5(replaceRoot_exports, { + $replaceRoot: () => $replaceRoot + }); + module.exports = __toCommonJS(replaceRoot_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + function $replaceRoot(coll, expr, options) { + return coll.map((obj) => { + obj = (0, import_internal.evalExpr)(obj, expr.newRoot, options); + (0, import_util3.assert)((0, import_util3.isObject)(obj), "$replaceRoot expression must return an object"); + return obj; + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceWith.js +var require_replaceWith = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceWith.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var replaceWith_exports = {}; + __export5(replaceWith_exports, { + $replaceWith: () => $replaceWith + }); + module.exports = __toCommonJS(replaceWith_exports); + var import_internal = require_internal2(); + var import_util3 = require_util(); + function $replaceWith(coll, expr, options) { + return coll.map((obj) => { + obj = (0, import_internal.evalExpr)(obj, expr, options); + (0, import_util3.assert)((0, import_util3.isObject)(obj), "$replaceWith expression must return an object"); + return obj; + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sample.js +var require_sample = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sample.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sample_exports = {}; + __export5(sample_exports, { + $sample: () => $sample + }); + module.exports = __toCommonJS(sample_exports); + var import_lazy = require_lazy(); + function $sample(coll, expr, _options2) { + return coll.transform((xs) => { + const len = xs.length; + let i = -1; + return (0, import_lazy.Lazy)(() => { + if (++i === expr.size) return { done: true }; + const n = Math.floor(Math.random() * len); + return { value: xs[n], done: false }; + }); + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/set.js +var require_set2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/set.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var set_exports = {}; + __export5(set_exports, { + $set: () => $set + }); + module.exports = __toCommonJS(set_exports); + var import_addFields = require_addFields(); + var $set = import_addFields.$addFields; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sortByCount.js +var require_sortByCount = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sortByCount.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var sortByCount_exports = {}; + __export5(sortByCount_exports, { + $sortByCount: () => $sortByCount + }); + module.exports = __toCommonJS(sortByCount_exports); + var import_group = require_group(); + var import_sort = require_sort(); + function $sortByCount(coll, expr, options) { + return (0, import_sort.$sort)( + (0, import_group.$group)(coll, { _id: expr, count: { $sum: 1 } }, options), + { count: -1 }, + options + ); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unionWith.js +var require_unionWith = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unionWith.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var unionWith_exports = {}; + __export5(unionWith_exports, { + $unionWith: () => $unionWith + }); + module.exports = __toCommonJS(unionWith_exports); + var import_aggregator = require_aggregator(); + var import_lazy = require_lazy(); + var import_util3 = require_util(); + var import_internal = require_internal7(); + function $unionWith(collection, expr, options) { + const { coll: inputColl, pipeline: stages } = (0, import_util3.isString)(expr) || (0, import_util3.isArray)(expr) ? { coll: expr } : expr; + const docsFromInput = (0, import_util3.isString)(inputColl) ? (0, import_internal.resolveCollection)("$unionWith", inputColl, options) : inputColl; + const { documents, pipeline } = (0, import_internal.filterDocumentsStage)(stages, options); + (0, import_util3.assert)( + docsFromInput || documents, + "$unionWith must specify single collection input with `expr.coll` or `expr.pipeline`." + ); + const xs = docsFromInput ?? documents; + return (0, import_lazy.concat)( + collection, + pipeline ? new import_aggregator.Aggregator(pipeline, options).stream(xs) : (0, import_lazy.Lazy)(xs) + ); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unset.js +var require_unset = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unset.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var unset_exports = {}; + __export5(unset_exports, { + $unset: () => $unset + }); + module.exports = __toCommonJS(unset_exports); + var import_util3 = require_util(); + var import_project = require_project(); + function $unset(coll, expr, options) { + expr = (0, import_util3.ensureArray)(expr); + const doc = {}; + for (const k of expr) doc[k] = 0; + return (0, import_project.$project)(coll, doc, options); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unwind.js +var require_unwind = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unwind.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var unwind_exports = {}; + __export5(unwind_exports, { + $unwind: () => $unwind + }); + module.exports = __toCommonJS(unwind_exports); + var import_lazy = require_lazy(); + var import_internal = require_internal(); + function $unwind(coll, expr, _options2) { + if ((0, import_internal.isString)(expr)) expr = { path: expr }; + const path3 = expr.path; + const field = path3.substring(1); + const includeArrayIndex = expr?.includeArrayIndex || false; + const preserveNullAndEmptyArrays = expr.preserveNullAndEmptyArrays || false; + const format = (o, i) => { + if (includeArrayIndex !== false) o[includeArrayIndex] = i; + return o; + }; + let value; + return (0, import_lazy.Lazy)(() => { + for (; ; ) { + if (value instanceof import_lazy.Iterator) { + const tmp = value.next(); + if (!tmp.done) return tmp; + } + const wrapper = coll.next(); + if (wrapper.done) return wrapper; + const obj = wrapper.value; + value = (0, import_internal.resolve)(obj, field); + if ((0, import_internal.isArray)(value)) { + if (value.length === 0 && preserveNullAndEmptyArrays === true) { + value = null; + (0, import_internal.removeValue)(obj, field); + return { value: format(obj, null), done: false }; + } else { + value = (0, import_lazy.Lazy)(value).map((item, i) => { + const newObj = (0, import_internal.resolveGraph)(obj, field, { + preserveKeys: true + }); + (0, import_internal.setValue)(newObj, field, item); + return format(newObj, i); + }); + } + } else if (!(0, import_internal.isEmpty)(value) || preserveNullAndEmptyArrays === true) { + return { value: format(obj, null), done: false }; + } + } + }); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/index.js +var require_pipeline = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var pipeline_exports = {}; + module.exports = __toCommonJS(pipeline_exports); + __reExport(pipeline_exports, require_addFields(), module.exports); + __reExport(pipeline_exports, require_bucket(), module.exports); + __reExport(pipeline_exports, require_bucketAuto(), module.exports); + __reExport(pipeline_exports, require_count2(), module.exports); + __reExport(pipeline_exports, require_densify(), module.exports); + __reExport(pipeline_exports, require_documents(), module.exports); + __reExport(pipeline_exports, require_facet(), module.exports); + __reExport(pipeline_exports, require_fill(), module.exports); + __reExport(pipeline_exports, require_graphLookup(), module.exports); + __reExport(pipeline_exports, require_group(), module.exports); + __reExport(pipeline_exports, require_limit(), module.exports); + __reExport(pipeline_exports, require_lookup(), module.exports); + __reExport(pipeline_exports, require_match(), module.exports); + __reExport(pipeline_exports, require_merge(), module.exports); + __reExport(pipeline_exports, require_out(), module.exports); + __reExport(pipeline_exports, require_project(), module.exports); + __reExport(pipeline_exports, require_redact(), module.exports); + __reExport(pipeline_exports, require_replaceRoot(), module.exports); + __reExport(pipeline_exports, require_replaceWith(), module.exports); + __reExport(pipeline_exports, require_sample(), module.exports); + __reExport(pipeline_exports, require_set2(), module.exports); + __reExport(pipeline_exports, require_setWindowFields(), module.exports); + __reExport(pipeline_exports, require_skip(), module.exports); + __reExport(pipeline_exports, require_sort(), module.exports); + __reExport(pipeline_exports, require_sortByCount(), module.exports); + __reExport(pipeline_exports, require_unionWith(), module.exports); + __reExport(pipeline_exports, require_unset(), module.exports); + __reExport(pipeline_exports, require_unwind(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/elemMatch.js +var require_elemMatch = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/elemMatch.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var elemMatch_exports = {}; + __export5(elemMatch_exports, { + $elemMatch: () => $elemMatch + }); + module.exports = __toCommonJS(elemMatch_exports); + var import_query = require_query(); + var import_util3 = require_util(); + var $elemMatch = (obj, expr, field, options) => { + const arr = (0, import_util3.resolve)(obj, field); + const query = new import_query.Query(expr, options); + if (!(0, import_util3.isArray)(arr)) return void 0; + const result = []; + for (let i = 0; i < arr.length; i++) { + if (query.test(arr[i])) { + if (options.useStrictMode) return [arr[i]]; + result.push(arr[i]); + } + } + return result.length > 0 ? result : void 0; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/slice.js +var require_slice2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/slice.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var slice_exports = {}; + __export5(slice_exports, { + $slice: () => $slice + }); + module.exports = __toCommonJS(slice_exports); + var import_util3 = require_util(); + var import_slice = require_slice(); + var $slice = (obj, expr, field, options) => { + const xs = (0, import_util3.resolve)(obj, field); + if (!(0, import_util3.isArray)(xs)) return xs; + return (0, import_slice.$slice)( + obj, + (0, import_util3.isArray)(expr) ? [xs, ...expr] : [xs, expr], + options + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/index.js +var require_projection = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var projection_exports = {}; + module.exports = __toCommonJS(projection_exports); + __reExport(projection_exports, require_elemMatch(), module.exports); + __reExport(projection_exports, require_slice2(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/all.js +var require_all = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/all.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var all_exports = {}; + __export5(all_exports, { + $all: () => $all + }); + module.exports = __toCommonJS(all_exports); + var import_predicates = require_predicates(); + var $all = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$all); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/elemMatch.js +var require_elemMatch2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/elemMatch.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var elemMatch_exports = {}; + __export5(elemMatch_exports, { + $elemMatch: () => $elemMatch + }); + module.exports = __toCommonJS(elemMatch_exports); + var import_predicates = require_predicates(); + var $elemMatch = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$elemMatch); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/size.js +var require_size2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/size.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var size_exports = {}; + __export5(size_exports, { + $size: () => $size + }); + module.exports = __toCommonJS(size_exports); + var import_predicates = require_predicates(); + var $size = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$size); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/index.js +var require_array2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var array_exports = {}; + module.exports = __toCommonJS(array_exports); + __reExport(array_exports, require_all(), module.exports); + __reExport(array_exports, require_elemMatch2(), module.exports); + __reExport(array_exports, require_size2(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/_internal.js +var require_internal13 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/_internal.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + processBitwiseQuery: () => processBitwiseQuery + }); + module.exports = __toCommonJS(internal_exports); + var import_util3 = require_util(); + var import_predicates = require_predicates(); + var processBitwiseQuery = (selector, value, predicate) => { + return (0, import_predicates.processQuery)( + selector, + value, + null, + (value2, mask) => { + let b = 0; + if ((0, import_util3.isArray)(mask)) { + for (const n of mask) b = b | 1 << n; + } else { + b = mask; + } + return predicate(value2 & b, b); + } + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllClear.js +var require_bitsAllClear = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllClear.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitsAllClear_exports = {}; + __export5(bitsAllClear_exports, { + $bitsAllClear: () => $bitsAllClear2 + }); + module.exports = __toCommonJS(bitsAllClear_exports); + var import_internal = require_internal13(); + var $bitsAllClear2 = (selector, value, _options2) => (0, import_internal.processBitwiseQuery)(selector, value, (result, _) => result == 0); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllSet.js +var require_bitsAllSet = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllSet.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitsAllSet_exports = {}; + __export5(bitsAllSet_exports, { + $bitsAllSet: () => $bitsAllSet2 + }); + module.exports = __toCommonJS(bitsAllSet_exports); + var import_internal = require_internal13(); + var $bitsAllSet2 = (selector, value, _options2) => (0, import_internal.processBitwiseQuery)(selector, value, (result, mask) => result == mask); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnyClear.js +var require_bitsAnyClear = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnyClear.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitsAnyClear_exports = {}; + __export5(bitsAnyClear_exports, { + $bitsAnyClear: () => $bitsAnyClear2 + }); + module.exports = __toCommonJS(bitsAnyClear_exports); + var import_internal = require_internal13(); + var $bitsAnyClear2 = (selector, value, _options2) => (0, import_internal.processBitwiseQuery)(selector, value, (result, mask) => result < mask); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnySet.js +var require_bitsAnySet = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnySet.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitsAnySet_exports = {}; + __export5(bitsAnySet_exports, { + $bitsAnySet: () => $bitsAnySet2 + }); + module.exports = __toCommonJS(bitsAnySet_exports); + var import_internal = require_internal13(); + var $bitsAnySet2 = (selector, value, _options2) => (0, import_internal.processBitwiseQuery)(selector, value, (result, _) => result > 0); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/index.js +var require_bitwise2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bitwise_exports = {}; + __export5(bitwise_exports, { + $bitsAllClear: () => import_bitsAllClear.$bitsAllClear, + $bitsAllSet: () => import_bitsAllSet.$bitsAllSet, + $bitsAnyClear: () => import_bitsAnyClear.$bitsAnyClear, + $bitsAnySet: () => import_bitsAnySet.$bitsAnySet + }); + module.exports = __toCommonJS(bitwise_exports); + var import_bitsAllClear = require_bitsAllClear(); + var import_bitsAllSet = require_bitsAllSet(); + var import_bitsAnyClear = require_bitsAnyClear(); + var import_bitsAnySet = require_bitsAnySet(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/eq.js +var require_eq2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/eq.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var eq_exports = {}; + __export5(eq_exports, { + $eq: () => $eq2 + }); + module.exports = __toCommonJS(eq_exports); + var import_predicates = require_predicates(); + var $eq2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$eq); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gt.js +var require_gt2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gt.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var gt_exports = {}; + __export5(gt_exports, { + $gt: () => $gt2 + }); + module.exports = __toCommonJS(gt_exports); + var import_predicates = require_predicates(); + var $gt2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$gt); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gte.js +var require_gte2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gte.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var gte_exports = {}; + __export5(gte_exports, { + $gte: () => $gte2 + }); + module.exports = __toCommonJS(gte_exports); + var import_predicates = require_predicates(); + var $gte2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$gte); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/in.js +var require_in2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/in.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var in_exports = {}; + __export5(in_exports, { + $in: () => $in2 + }); + module.exports = __toCommonJS(in_exports); + var import_predicates = require_predicates(); + var $in2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$in); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lt.js +var require_lt2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lt.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var lt_exports = {}; + __export5(lt_exports, { + $lt: () => $lt2 + }); + module.exports = __toCommonJS(lt_exports); + var import_predicates = require_predicates(); + var $lt2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$lt); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lte.js +var require_lte2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lte.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var lte_exports = {}; + __export5(lte_exports, { + $lte: () => $lte2 + }); + module.exports = __toCommonJS(lte_exports); + var import_predicates = require_predicates(); + var $lte2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$lte); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/ne.js +var require_ne2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/ne.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var ne_exports = {}; + __export5(ne_exports, { + $ne: () => $ne2 + }); + module.exports = __toCommonJS(ne_exports); + var import_predicates = require_predicates(); + var $ne2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$ne); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/nin.js +var require_nin = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/nin.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var nin_exports = {}; + __export5(nin_exports, { + $nin: () => $nin2 + }); + module.exports = __toCommonJS(nin_exports); + var import_predicates = require_predicates(); + var $nin2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$nin); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/index.js +var require_comparison2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var comparison_exports = {}; + __export5(comparison_exports, { + $eq: () => import_eq.$eq, + $gt: () => import_gt.$gt, + $gte: () => import_gte.$gte, + $in: () => import_in.$in, + $lt: () => import_lt2.$lt, + $lte: () => import_lte.$lte, + $ne: () => import_ne.$ne, + $nin: () => import_nin.$nin + }); + module.exports = __toCommonJS(comparison_exports); + var import_eq = require_eq2(); + var import_gt = require_gt2(); + var import_gte = require_gte2(); + var import_in = require_in2(); + var import_lt2 = require_lt2(); + var import_lte = require_lte2(); + var import_ne = require_ne2(); + var import_nin = require_nin(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/exists.js +var require_exists = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/exists.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var exists_exports = {}; + __export5(exists_exports, { + $exists: () => $exists + }); + module.exports = __toCommonJS(exists_exports); + var import_internal = require_internal(); + var $exists = (selector, value, _options2) => { + const nested = selector.includes("."); + const b = !!value; + if (!nested || selector.match(/\.\d+$/)) { + const opts2 = { pathArray: selector.split(".") }; + return (o) => (0, import_internal.resolve)(o, selector, opts2) !== void 0 === b; + } + const parentSelector = selector.substring(0, selector.lastIndexOf(".")); + const opts = { pathArray: parentSelector.split("."), preserveIndex: true }; + return (o) => { + const path3 = (0, import_internal.resolveGraph)(o, selector, opts); + const val = (0, import_internal.resolve)(path3, parentSelector, opts); + return (0, import_internal.isArray)(val) ? val.some((v) => v !== void 0) === b : val !== void 0 === b; + }; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/type.js +var require_type3 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/type.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var type_exports = {}; + __export5(type_exports, { + $type: () => $type + }); + module.exports = __toCommonJS(type_exports); + var import_predicates = require_predicates(); + var $type = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$type); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/index.js +var require_element = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var element_exports = {}; + module.exports = __toCommonJS(element_exports); + __reExport(element_exports, require_exists(), module.exports); + __reExport(element_exports, require_type3(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/expr.js +var require_expr = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/expr.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var expr_exports = {}; + __export5(expr_exports, { + $expr: () => $expr + }); + module.exports = __toCommonJS(expr_exports); + var import_internal = require_internal2(); + var import_internal2 = require_internal(); + function $expr(_, expr, options) { + return (obj) => (0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, expr, options), options.useStrictMode); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/jsonSchema.js +var require_jsonSchema = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/jsonSchema.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var jsonSchema_exports = {}; + __export5(jsonSchema_exports, { + $jsonSchema: () => $jsonSchema + }); + module.exports = __toCommonJS(jsonSchema_exports); + var import_util3 = require_util(); + function $jsonSchema(_, schema3, options) { + (0, import_util3.assert)( + !!options?.jsonSchemaValidator, + "$jsonSchema requires 'jsonSchemaValidator' option to be defined." + ); + const validate = options.jsonSchemaValidator(schema3); + return (obj) => validate(obj); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/mod.js +var require_mod2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/mod.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var mod_exports = {}; + __export5(mod_exports, { + $mod: () => $mod + }); + module.exports = __toCommonJS(mod_exports); + var import_predicates = require_predicates(); + var $mod = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$mod); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/regex.js +var require_regex = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/regex.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var regex_exports = {}; + __export5(regex_exports, { + $regex: () => $regex + }); + module.exports = __toCommonJS(regex_exports); + var import_predicates = require_predicates(); + var $regex = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$regex); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/where.js +var require_where = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/where.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var where_exports = {}; + __export5(where_exports, { + $where: () => $where + }); + module.exports = __toCommonJS(where_exports); + var import_internal = require_internal(); + function $where(_, rhs, opts) { + (0, import_internal.assert)( + opts.scriptEnabled, + "$where requires 'scriptEnabled' option to be true" + ); + const f = rhs; + (0, import_internal.assert)((0, import_internal.isFunction)(f), "$where only accepts a Function objects"); + return (obj) => (0, import_internal.truthy)(f.call(obj), opts?.useStrictMode); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/index.js +var require_evaluation = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var evaluation_exports = {}; + module.exports = __toCommonJS(evaluation_exports); + __reExport(evaluation_exports, require_expr(), module.exports); + __reExport(evaluation_exports, require_jsonSchema(), module.exports); + __reExport(evaluation_exports, require_mod2(), module.exports); + __reExport(evaluation_exports, require_regex(), module.exports); + __reExport(evaluation_exports, require_where(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/and.js +var require_and2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/and.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var and_exports = {}; + __export5(and_exports, { + $and: () => $and + }); + module.exports = __toCommonJS(and_exports); + var import_query = require_query(); + var import_util3 = require_util(); + var $and = (_, rhs, options) => { + (0, import_util3.assert)((0, import_util3.isArray)(rhs), "$and expects value to be an Array."); + const queries = rhs.map((expr) => new import_query.Query(expr, options)); + return (obj) => queries.every((q) => q.test(obj)); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/or.js +var require_or2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/or.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var or_exports = {}; + __export5(or_exports, { + $or: () => $or + }); + module.exports = __toCommonJS(or_exports); + var import_query = require_query(); + var import_util3 = require_util(); + function $or(_, rhs, options) { + (0, import_util3.assert)((0, import_util3.isArray)(rhs), "Invalid expression. $or expects value to be an Array"); + const queries = rhs.map((expr) => new import_query.Query(expr, options)); + return (obj) => queries.some((q) => q.test(obj)); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/nor.js +var require_nor = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/nor.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var nor_exports = {}; + __export5(nor_exports, { + $nor: () => $nor + }); + module.exports = __toCommonJS(nor_exports); + var import_util3 = require_util(); + var import_or = require_or2(); + function $nor(_, rhs, options) { + (0, import_util3.assert)( + (0, import_util3.isArray)(rhs), + "Invalid expression. $nor expects value to be an array." + ); + const f = (0, import_or.$or)("$or", rhs, options); + return (obj) => !f(obj); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/not.js +var require_not2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/not.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var not_exports = {}; + __export5(not_exports, { + $not: () => $not + }); + module.exports = __toCommonJS(not_exports); + var import_query = require_query(); + var import_util3 = require_util(); + function $not(selector, rhs, options) { + const criteria = {}; + criteria[selector] = (0, import_util3.normalize)(rhs); + const query = new import_query.Query(criteria, options); + return (obj) => !query.test(obj); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/index.js +var require_logical = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var logical_exports = {}; + module.exports = __toCommonJS(logical_exports); + __reExport(logical_exports, require_and2(), module.exports); + __reExport(logical_exports, require_nor(), module.exports); + __reExport(logical_exports, require_not2(), module.exports); + __reExport(logical_exports, require_or2(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/index.js +var require_query2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var query_exports = {}; + module.exports = __toCommonJS(query_exports); + __reExport(query_exports, require_array2(), module.exports); + __reExport(query_exports, require_bitwise2(), module.exports); + __reExport(query_exports, require_comparison2(), module.exports); + __reExport(query_exports, require_element(), module.exports); + __reExport(query_exports, require_evaluation(), module.exports); + __reExport(query_exports, require_logical(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/denseRank.js +var require_denseRank = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/denseRank.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var denseRank_exports = {}; + __export5(denseRank_exports, { + $denseRank: () => $denseRank + }); + module.exports = __toCommonJS(denseRank_exports); + var import_internal = require_internal12(); + var $denseRank = (obj, coll, expr, options) => (0, import_internal.rank)( + obj, + coll, + expr, + options, + true + /*dense*/ + ); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/derivative.js +var require_derivative = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/derivative.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var derivative_exports = {}; + __export5(derivative_exports, { + $derivative: () => $derivative + }); + module.exports = __toCommonJS(derivative_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var import_internal = require_internal8(); + var $derivative = (_, coll, expr, options) => { + if (coll.length < 2) return null; + const { input, unit } = expr.inputExpr; + const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0]; + const values = [coll[0], coll[coll.length - 1]]; + const points = (0, import_push.$push)(values, [sortKey, input], options).filter( + ([x, y]) => (0, import_util3.isNumber)(+x) && (0, import_util3.isNumber)(+y) + ); + (0, import_util3.assert)(points.length === 2, "$derivative arguments must resolve to numeric"); + const [[x1, y1], [x2, y2]] = points; + const deltaX = (x2 - x1) / import_internal.TIMEUNIT_IN_MILLIS[unit ?? "millisecond"]; + return (y2 - y1) / deltaX; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/documentNumber.js +var require_documentNumber = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/documentNumber.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var documentNumber_exports = {}; + __export5(documentNumber_exports, { + $documentNumber: () => $documentNumber + }); + module.exports = __toCommonJS(documentNumber_exports); + var $documentNumber = (_obj, _coll, expr, _options2) => expr.documentNumber; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/expMovingAvg.js +var require_expMovingAvg = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/expMovingAvg.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var expMovingAvg_exports = {}; + __export5(expMovingAvg_exports, { + $expMovingAvg: () => $expMovingAvg + }); + module.exports = __toCommonJS(expMovingAvg_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var import_internal = require_internal12(); + var $expMovingAvg = (_, coll, expr, options) => { + const { input, N, alpha } = expr.inputExpr; + (0, import_util3.assert)( + !(N && alpha), + `$expMovingAvg: must provide either 'N' or 'alpha' field.` + ); + (0, import_util3.assert)( + !N || (0, import_util3.isNumber)(N) && N > 0, + `$expMovingAvg: 'N' must be greater than zero. Got ${N}.` + ); + (0, import_util3.assert)( + !alpha || (0, import_util3.isNumber)(alpha) && alpha > 0 && alpha < 1, + `$expMovingAvg: 'alpha' must be between 0 and 1 (exclusive), found alpha: ${alpha}` + ); + return (0, import_internal.withMemo)( + coll, + expr, + () => { + const weight = N != void 0 ? 2 / (N + 1) : alpha; + const values = (0, import_push.$push)(coll, input, options); + for (let i = 0; i < values.length; i++) { + if (i === 0) { + if (!(0, import_util3.isNumber)(values[i])) values[i] = null; + continue; + } + if (!(0, import_util3.isNumber)(values[i])) { + values[i] = values[i - 1]; + continue; + } + if (!(0, import_util3.isNumber)(values[i - 1])) continue; + values[i] = values[i] * weight + values[i - 1] * (1 - weight); + } + return values; + }, + (series) => series[expr.documentNumber - 1] + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/integral.js +var require_integral = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/integral.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var integral_exports = {}; + __export5(integral_exports, { + $integral: () => $integral + }); + module.exports = __toCommonJS(integral_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var import_internal = require_internal8(); + var $integral = (_, coll, expr, options) => { + const { input, unit } = expr.inputExpr; + const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0]; + const points = (0, import_push.$push)(coll, [sortKey, input], options).filter( + ([x, y]) => (0, import_util3.isNumber)(+x) && (0, import_util3.isNumber)(+y) + ); + const size = points.length; + (0, import_util3.assert)(coll.length === size, "$integral expects an array of numeric values"); + let result = 0; + for (let k = 1; k < size; k++) { + const [x1, y1] = points[k - 1]; + const [x2, y2] = points[k]; + const deltaX = (x2 - x1) / import_internal.TIMEUNIT_IN_MILLIS[unit ?? "millisecond"]; + result += 0.5 * (y1 + y2) * deltaX; + } + return result; + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/minMaxScaler.js +var require_minMaxScaler = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/minMaxScaler.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var minMaxScaler_exports = {}; + __export5(minMaxScaler_exports, { + $minMaxScaler: () => $minMaxScaler + }); + module.exports = __toCommonJS(minMaxScaler_exports); + var import_util3 = require_util(); + var import_push = require_push(); + var import_internal = require_internal12(); + var $minMaxScaler = (_, coll, expr, options) => { + return (0, import_internal.withMemo)( + coll, + expr, + () => { + const args = expr.inputExpr; + const min = args.min || 0; + const max = args.max || 1; + const nums = (0, import_push.$push)( + coll, + args.input || expr.inputExpr, + options + ); + (0, import_util3.assert)( + (0, import_util3.isArray)(nums) && nums.length > 0 && nums.every(import_util3.isNumber), + "$minMaxScaler: input must be a numeric array" + ); + let rmin = nums[0]; + let rmax = nums[0]; + for (const n of nums) { + if (n < rmin) rmin = n; + else if (n > rmax) rmax = n; + } + const scale = max - min; + const range = rmax - rmin; + (0, import_util3.assert)(range !== 0, "$minMaxScaler: input range must not be zero"); + return { + min, + scale, + rmin, + range, + nums + }; + }, + (data) => { + const { min, rmin, scale, range, nums } = data; + return (nums[expr.documentNumber - 1] - rmin) / range * scale + min; + } + ); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/rank.js +var require_rank = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/rank.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var rank_exports = {}; + __export5(rank_exports, { + $rank: () => $rank + }); + module.exports = __toCommonJS(rank_exports); + var import_internal = require_internal12(); + var $rank = (obj, coll, expr, options) => (0, import_internal.rank)( + obj, + coll, + expr, + options, + false + /*dense*/ + ); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/shift.js +var require_shift = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/shift.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var shift_exports = {}; + __export5(shift_exports, { + $shift: () => $shift + }); + module.exports = __toCommonJS(shift_exports); + var import_internal = require_internal2(); + var $shift = (obj, coll, expr, options) => { + const input = expr.inputExpr; + const shiftedIndex = expr.documentNumber - 1 + input.by; + if (shiftedIndex < 0 || shiftedIndex > coll.length - 1) { + return (0, import_internal.evalExpr)(obj, input.default, options) ?? null; + } + return (0, import_internal.evalExpr)(coll[shiftedIndex], input.output, options); + }; + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/index.js +var require_window = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var window_exports = {}; + module.exports = __toCommonJS(window_exports); + __reExport(window_exports, require_denseRank(), module.exports); + __reExport(window_exports, require_derivative(), module.exports); + __reExport(window_exports, require_documentNumber(), module.exports); + __reExport(window_exports, require_expMovingAvg(), module.exports); + __reExport(window_exports, require_integral(), module.exports); + __reExport(window_exports, require_linearFill(), module.exports); + __reExport(window_exports, require_locf(), module.exports); + __reExport(window_exports, require_minMaxScaler(), module.exports); + __reExport(window_exports, require_rank(), module.exports); + __reExport(window_exports, require_shift(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/_internal.js +var require_internal14 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/_internal.js"(exports, module) { + var __create2 = Object.create; + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp6(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var internal_exports = {}; + __export5(internal_exports, { + DEFAULT_OPTIONS: () => DEFAULT_OPTIONS, + applyUpdate: () => applyUpdate, + buildParams: () => buildParams, + clone: () => clone2, + walkExpression: () => walkExpression + }); + module.exports = __toCommonJS(internal_exports); + var import_internal = require_internal2(); + var booleanOperators = __toESM2(require_boolean()); + var comparisonOperators = __toESM2(require_comparison()); + var queryOperators = __toESM2(require_query2()); + var import_query = require_query(); + var import_internal2 = require_internal(); + var DEFAULT_OPTIONS = import_internal.ComputeOptions.init({ + context: import_internal.Context.init().addQueryOps(queryOperators).addExpressionOps(booleanOperators).addExpressionOps(comparisonOperators) + }).update({ updateConfig: { cloneMode: "copy" } }); + var clone2 = (val, opts) => { + const mode = opts?.local?.updateConfig?.cloneMode; + switch (mode) { + case "deep": + return (0, import_internal2.cloneDeep)(val); + case "copy": { + if ((0, import_internal2.isDate)(val)) return new Date(val); + if ((0, import_internal2.isArray)(val)) return val.slice(); + if ((0, import_internal2.isObject)(val)) return Object.assign({}, val); + if ((0, import_internal2.isRegExp)(val)) return new RegExp(val); + return val; + } + } + return val; + }; + var FIRST_ONLY = "$"; + var ARRAY_WIDE = "$[]"; + var applyUpdate = (o, n, q, f, opts) => { + const { selector, position: c, next } = n; + if (!c) { + let b = false; + const g = (u, k) => b = Boolean(f(u, k)) || b; + (0, import_internal2.walk)(o, selector, g, opts); + return b; + } + const arr = (0, import_internal2.resolve)(o, selector); + if (!(0, import_internal2.isArray)(arr) || !arr.length) return false; + if (c === FIRST_ONLY) { + const i = arr.findIndex((e) => q[selector].test({ [selector]: [e] })); + (0, import_internal2.assert)(i > -1, "BUG: positional operator found no match for " + selector); + return next ? applyUpdate(arr[i], next, q, f, opts) : f(arr, i); + } + return arr.map((e, i) => { + if (c !== ARRAY_WIDE && q[c] && !q[c].test({ [c]: [e] })) return false; + return next ? applyUpdate(e, next, q, f, opts) : f(arr, i); + }).some((v) => !!v); + }; + var ERR_MISSING_FIELD = "You must include the array field for '.$' as part of the query document."; + var ERR_IMMUTABLE_FIELD = (path3, idKey) => `Performing an update on the path '${path3}' would modify the immutable field '${idKey}'.`; + function walkExpression(expr, arrayFilters, options, callback) { + const opts = options; + const params = opts.local.updateParams ?? buildParams([expr], arrayFilters, opts); + const modified = []; + for (const key of Object.keys(expr)) { + const { node, queries } = params[key]; + if (callback(expr[key], node, queries)) modified.push(node.selector); + } + return modified.sort(); + } + function buildParams(exprList, arrayFilters, options) { + const params = {}; + arrayFilters || (arrayFilters = []); + const filterIndexMap = arrayFilters.reduce( + (res, filter) => { + for (const k of Object.keys(filter)) { + const parent = k.split(".")[0]; + if (res[parent]) { + res[parent][k] = filter[k]; + } else { + res[parent] = { [k]: filter[k] }; + } + } + return res; + }, + {} + ); + let { condition } = options.local; + condition = condition ?? {}; + const queryKeys = Object.keys(condition); + const conflictDetector = new import_internal2.PathValidator(); + for (const expr of exprList) { + for (const selector of Object.keys(expr)) { + const identifiers = []; + const node = selector.includes("$") ? { selector: "" } : { selector }; + if (!node.selector) { + selector.split(".").reduce((n, v) => { + if (v === FIRST_ONLY || v === ARRAY_WIDE) { + n.position = v; + } else if (v.startsWith("$[") && v.endsWith("]")) { + const id = v.slice(2, -1); + (0, import_internal2.assert)( + /^[a-z]+\w*$/.test(id), + `The filter must begin with a lowercase letter and contain only alphanumeric characters. '${v}' is invalid.` + ); + identifiers.push(id); + n.position = id; + } else if (!n.selector) { + n.selector = v; + } else if (!n.position) { + n.selector += "." + v; + } else { + n.next = { selector: v }; + return n.next; + } + return n; + }, node); + } + const queries = {}; + if (identifiers.length) { + const filters = {}; + for (const v of identifiers) filters[v] = filterIndexMap[v]; + for (const k of Object.keys(filters)) { + queries[k] = new import_query.Query(filters[k], options); + } + } + if (node.position === FIRST_ONLY) { + const field = node.selector; + (0, import_internal2.assert)(queryKeys && queryKeys.length, ERR_MISSING_FIELD); + const matches = queryKeys.filter( + (k2) => k2 === field || k2.startsWith(field + ".") + ); + (0, import_internal2.assert)(matches.length === 1, ERR_MISSING_FIELD); + const k = matches[0]; + queries[field] = new import_query.Query({ [k]: condition[k] }, options); + } + const idKey = options.idKey; + (0, import_internal2.assert)( + node.selector !== idKey && !node.selector.startsWith(`${idKey}.`), + ERR_IMMUTABLE_FIELD(node.selector, idKey) + ); + (0, import_internal2.assert)( + conflictDetector.add(node.selector), + `updating the path '${node.selector}' would create a conflict at '${node.selector}'` + ); + params[selector] = { node, queries }; + } + } + return params; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/addToSet.js +var require_addToSet2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/addToSet.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var addToSet_exports = {}; + __export5(addToSet_exports, { + $addToSet: () => $addToSet + }); + module.exports = __toCommonJS(addToSet_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $addToSet(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { + const args = { $each: [val] }; + if ((0, import_util3.isObject)(val) && (0, import_util3.has)(val, "$each")) { + Object.assign(args, val); + } + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + const prev = o[k]; + if ((0, import_util3.isArray)(prev)) { + const set2 = (0, import_util3.unique)(prev.concat(args.$each)); + if (set2.length === prev.length) return false; + o[k] = (0, import_internal.clone)(set2, options); + } else if (prev === void 0) { + o[k] = (0, import_internal.clone)(args.$each, options); + } else { + return false; + } + return true; + }, + { buildGraph: true } + ); + }); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/bit.js +var require_bit = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/bit.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var bit_exports = {}; + __export5(bit_exports, { + $bit: () => $bit + }); + module.exports = __toCommonJS(bit_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + var BIT_OPS = ["and", "or", "xor"]; + function $bit(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + for (const vals of Object.values(expr)) { + (0, import_util3.assert)((0, import_util3.isObject)(vals), `$bit operator expression must be an object.`); + const op = Object.keys(vals); + (0, import_util3.assert)( + op.length === 1 && BIT_OPS.includes(op[0]), + `$bit spec is invalid '${op[0]}'. Must be one of 'and', 'or', or 'xor'.` + ); + (0, import_util3.assert)( + (0, import_util3.isNumber)(vals[op[0]]), + `$bit expression value must be a number. Got ${typeof vals[op[0]]}` + ); + } + return (obj) => { + return (0, import_internal.walkExpression)( + expr, + arrayFilters, + options, + (val, node, queries) => { + const op = Object.keys(val); + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + let n = o[k]; + const v = val[op[0]]; + if (n !== void 0 && !((0, import_util3.isNumber)(n) && (0, import_util3.isNumber)(v))) return false; + n = n || 0; + switch (op[0]) { + case "and": + return (o[k] = n & v) !== n; + case "or": + return (o[k] = n | v) !== n; + case "xor": + return (o[k] = n ^ v) !== n; + } + }, + { buildGraph: true } + ); + } + ); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/currentDate.js +var require_currentDate = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/currentDate.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var currentDate_exports = {}; + __export5(currentDate_exports, { + $currentDate: () => $currentDate + }); + module.exports = __toCommonJS(currentDate_exports); + var import_internal = require_internal14(); + function $currentDate(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)( + expr, + arrayFilters, + options, + (val, node, queries) => { + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + o[k] = val === true || val.$type === "date" ? options.now : options.now.getTime(); + return true; + }, + { buildGraph: true } + ); + } + ); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/inc.js +var require_inc = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/inc.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var inc_exports = {}; + __export5(inc_exports, { + $inc: () => $inc + }); + module.exports = __toCommonJS(inc_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $inc(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)( + expr, + arrayFilters, + options, + (val, node, queries) => { + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + if ((0, import_util3.isNumber)(o[k]) || o[k] === void 0) { + o[k] || (o[k] = 0); + o[k] += val; + return true; + } + return false; + }, + { buildGraph: true } + ); + } + ); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/max.js +var require_max2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/max.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var max_exports = {}; + __export5(max_exports, { + $max: () => $max + }); + module.exports = __toCommonJS(max_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $max(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + if ((0, import_util3.compare)(o[k], val) > -1) return false; + o[k] = val; + return true; + }, + { buildGraph: true } + ); + }); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/min.js +var require_min2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/min.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var min_exports = {}; + __export5(min_exports, { + $min: () => $min + }); + module.exports = __toCommonJS(min_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $min(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + if ((0, import_util3.compare)(o[k], val) < 1) return false; + o[k] = val; + return true; + }, + { buildGraph: true } + ); + }); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/mul.js +var require_mul = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/mul.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var mul_exports = {}; + __export5(mul_exports, { + $mul: () => $mul + }); + module.exports = __toCommonJS(mul_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $mul(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)( + expr, + arrayFilters, + options, + (val, node, queries) => { + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + const prev = o[k]; + if ((0, import_util3.isNumber)(o[k])) o[k] = o[k] * val; + else if (o[k] === void 0) o[k] = 0; + return o[k] !== prev; + }, + { buildGraph: true } + ); + } + ); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pop.js +var require_pop = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pop.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var pop_exports = {}; + __export5(pop_exports, { + $pop: () => $pop + }); + module.exports = __toCommonJS(pop_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $pop(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)( + expr, + arrayFilters, + options, + (val, node, queries) => { + return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => { + const arr = o[k]; + if (!(0, import_util3.isArray)(arr) || !arr.length) return false; + if (val === -1) arr.splice(0, 1); + else arr.pop(); + return true; + }); + } + ); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pull.js +var require_pull = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pull.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var pull_exports = {}; + __export5(pull_exports, { + $pull: () => $pull + }); + module.exports = __toCommonJS(pull_exports); + var import_query = require_query(); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $pull(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { + const wrap4 = !(0, import_util3.isObject)(val) || Object.keys(val).some(import_util3.isOperator); + const query = new import_query.Query(wrap4 ? { k: val } : val, options); + const pred = wrap4 ? (v) => query.test({ k: v }) : (v) => query.test(v); + return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => { + const prev = o[k]; + if (!(0, import_util3.isArray)(prev) || !prev.length) return false; + const curr = new Array(); + let ok2 = false; + for (const v of prev) { + const b = pred(v); + if (!b) curr.push(v); + ok2 || (ok2 = b); + } + if (!ok2) return false; + o[k] = curr; + return true; + }); + }); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pullAll.js +var require_pullAll = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pullAll.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var pullAll_exports = {}; + __export5(pullAll_exports, { + $pullAll: () => $pullAll + }); + module.exports = __toCommonJS(pullAll_exports); + var import_internal = require_internal14(); + var import_pull = require_pull(); + function $pullAll(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + const pullExpr = {}; + for (const k of Object.keys(expr)) { + pullExpr[k] = { $in: expr[k] }; + } + return (0, import_pull.$pull)(pullExpr, arrayFilters, options); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/push.js +var require_push2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/push.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var push_exports = {}; + __export5(push_exports, { + $push: () => $push + }); + module.exports = __toCommonJS(push_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + var MODIFIERS = ["$each", "$slice", "$sort", "$position"]; + function $push(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { + const args = { + $each: [val] + }; + if ((0, import_util3.isObject)(val) && MODIFIERS.some((m) => (0, import_util3.has)(val, m))) { + Object.assign(args, val); + } + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + const arr = o[k]; + if (!(0, import_util3.isArray)(arr)) { + if (arr === void 0) { + o[k] = (0, import_internal.clone)(args.$each, options); + return true; + } + return false; + } + const prev = arr.slice(0, args.$slice || arr.length); + const oldsize = arr.length; + const pos = (0, import_util3.isNumber)(args.$position) ? args.$position : arr.length; + arr.splice(pos, 0, ...(0, import_internal.clone)(args.$each, options)); + if (args.$sort) { + const sortKey = (0, import_util3.isObject)(args.$sort) ? Object.keys(args.$sort)[0] : ""; + const order = !sortKey ? args.$sort : args.$sort[sortKey]; + const f = !sortKey ? (a) => a : (a) => (0, import_util3.resolve)(a, sortKey); + arr.sort((a, b) => order * (0, import_util3.compare)(f(a), f(b))); + } + if ((0, import_util3.isNumber)(args.$slice)) { + if (args.$slice < 0) arr.splice(0, arr.length + args.$slice); + else arr.splice(args.$slice); + } + return oldsize != arr.length || !(0, import_util3.isEqual)(prev, arr); + }, + { descendArray: true, buildGraph: true } + ); + }); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/set.js +var require_set3 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/set.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var set_exports = {}; + __export5(set_exports, { + $set: () => $set + }); + module.exports = __toCommonJS(set_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $set(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { + return (0, import_internal.applyUpdate)( + obj, + node, + queries, + (o, k) => { + if ((0, import_util3.isEqual)(o[k], val)) return false; + o[k] = (0, import_internal.clone)(val, options); + return true; + }, + { buildGraph: true } + ); + }); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/rename.js +var require_rename = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/rename.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var rename_exports = {}; + __export5(rename_exports, { + $rename: () => $rename + }); + module.exports = __toCommonJS(rename_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + var import_set = require_set3(); + var isIdPath = (path3, idKey) => path3 === idKey || path3.startsWith(`${idKey}.`); + function $rename(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + const idKey = options.idKey; + for (const target of Object.values(expr)) { + (0, import_util3.assert)( + !isIdPath(target, idKey), + `Performing an update on the path '${target}' would modify the immutable field '${idKey}'.` + ); + } + return (obj) => { + const res = []; + const changed = (0, import_internal.walkExpression)( + expr, + arrayFilters, + options, + (val, node, queries) => { + return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => { + if (!(0, import_util3.has)(o, k)) return false; + Array.prototype.push.apply( + res, + (0, import_set.$set)({ [val]: o[k] }, arrayFilters, options)(obj) + ); + delete o[k]; + return true; + }); + } + ); + return Array.from(new Set(changed.concat(res))); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/unset.js +var require_unset2 = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/unset.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var unset_exports = {}; + __export5(unset_exports, { + $unset: () => $unset + }); + module.exports = __toCommonJS(unset_exports); + var import_util3 = require_util(); + var import_internal = require_internal14(); + function $unset(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { + return (obj) => { + return (0, import_internal.walkExpression)(expr, arrayFilters, options, (_, node, queries) => { + return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => { + if (!(0, import_util3.has)(o, k)) return false; + const prev = o[k]; + if ((0, import_util3.isArray)(o)) o[k] = null; + else delete o[k]; + return !(0, import_util3.isEqual)(prev, o[k]); + }); + }); + }; + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/index.js +var require_update = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var update_exports = {}; + module.exports = __toCommonJS(update_exports); + __reExport(update_exports, require_addToSet2(), module.exports); + __reExport(update_exports, require_bit(), module.exports); + __reExport(update_exports, require_currentDate(), module.exports); + __reExport(update_exports, require_inc(), module.exports); + __reExport(update_exports, require_max2(), module.exports); + __reExport(update_exports, require_min2(), module.exports); + __reExport(update_exports, require_mul(), module.exports); + __reExport(update_exports, require_pop(), module.exports); + __reExport(update_exports, require_pull(), module.exports); + __reExport(update_exports, require_pullAll(), module.exports); + __reExport(update_exports, require_push2(), module.exports); + __reExport(update_exports, require_rename(), module.exports); + __reExport(update_exports, require_set3(), module.exports); + __reExport(update_exports, require_unset2(), module.exports); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/updater.js +var require_updater = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/updater.js"(exports, module) { + var __create2 = Object.create; + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp6(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var updater_exports = {}; + __export5(updater_exports, { + update: () => update, + updateMany: () => updateMany, + updateOne: () => updateOne + }); + module.exports = __toCommonJS(updater_exports); + var import_internal = require_internal2(); + var import_lazy = require_lazy(); + var booleanOperators = __toESM2(require_boolean()); + var comparisonOperators = __toESM2(require_comparison()); + var import_addFields = require_addFields(); + var import_project = require_project(); + var import_replaceRoot = require_replaceRoot(); + var import_replaceWith = require_replaceWith(); + var import_set = require_set2(); + var import_sort = require_sort(); + var import_unset = require_unset(); + var queryOperators = __toESM2(require_query2()); + var updateOperators = __toESM2(require_update()); + var import_internal2 = require_internal14(); + var import_query = require_query(); + var import_internal3 = require_internal(); + var UPDATE_OPERATORS = updateOperators; + var PIPELINE_OPERATORS = { + $addFields: import_addFields.$addFields, + $set: import_set.$set, + $project: import_project.$project, + $unset: import_unset.$unset, + $replaceRoot: import_replaceRoot.$replaceRoot, + $replaceWith: import_replaceWith.$replaceWith + }; + function update(obj, modifier, arrayFilters, condition, options) { + const docs = [obj]; + const res = updateOne( + docs, + condition || {}, + modifier, + { arrayFilters, cloneMode: options?.cloneMode ?? "copy" }, + options?.queryOptions + ); + return res.modifiedFields ?? []; + } + function updateMany(documents, condition, modifier, updateConfig = {}, options) { + const { modifiedCount, matchedCount } = updateDocuments( + documents, + condition, + modifier, + updateConfig, + options + ); + return { modifiedCount, matchedCount }; + } + function updateOne(documents, condition, modifier, updateConfig = {}, options) { + return updateDocuments(documents, condition, modifier, updateConfig, { + ...options, + firstOnly: true + }); + } + function updateDocuments(documents, condition, modifier, updateConfig = {}, options) { + options || (options = {}); + const firstOnly = options?.firstOnly ?? false; + const opts = import_internal.ComputeOptions.init({ + ...options, + collation: Object.assign({}, options?.collation, updateConfig?.collation) + }).update({ + condition, + updateConfig: { cloneMode: "copy", ...updateConfig }, + variables: updateConfig.let, + updateParams: {} + }); + opts.context.addExpressionOps(booleanOperators).addExpressionOps(comparisonOperators).addQueryOps(queryOperators).addPipelineOps(PIPELINE_OPERATORS); + const filterExists = Object.keys(condition).length > 0; + const matchedDocs = /* @__PURE__ */ new Map(); + let docsIter = (0, import_lazy.Lazy)(documents); + if (filterExists) { + const query = new import_query.Query(condition, opts); + docsIter = docsIter.filter((o, i) => { + if (query.test(o)) { + matchedDocs.set(o, i); + return true; + } + return false; + }); + } + let modifiedIndex = -1; + if (firstOnly) { + const indexes = /* @__PURE__ */ new Map(); + if (updateConfig.sort) { + if (!filterExists) { + docsIter = docsIter.map((o, i) => { + indexes.set(o, i); + return o; + }); + } + docsIter = (0, import_sort.$sort)(docsIter, updateConfig.sort, opts); + } + docsIter = docsIter.take(1); + const firstDoc = docsIter.collect()[0]; + modifiedIndex = matchedDocs.get(firstDoc) ?? indexes.get(firstDoc) ?? 0; + } + const foundDocs = docsIter.collect(); + if (foundDocs.length === 0) return { matchedCount: 0, modifiedCount: 0 }; + if ((0, import_internal3.isArray)(modifier)) { + const indexes = firstOnly ? [modifiedIndex] : Array.from(matchedDocs.values()); + const hashes = indexes.length ? indexes.map((i) => (0, import_internal3.hashCode)(documents[i])) : foundDocs.map((o) => (0, import_internal3.hashCode)(o)); + const output2 = { matchedCount: hashes.length, modifiedCount: 0 }; + const oldFirstDoc = firstOnly ? (0, import_internal3.cloneDeep)(documents[indexes[0]]) : void 0; + let updateIter = (0, import_lazy.Lazy)(foundDocs); + for (const stage of modifier) { + const [op, expr] = Object.entries(stage)[0]; + const pipelineOp = PIPELINE_OPERATORS[op]; + (0, import_internal3.assert)(pipelineOp, `Unknown pipeline operator: '${op}'.`); + updateIter = pipelineOp(updateIter, expr, opts); + } + const matches = updateIter.collect(); + if (indexes.length) { + (0, import_internal3.assert)( + indexes.length === matches.length, + "bug: indexes and result size must match." + ); + for (let i = 0; i < indexes.length; i++) { + if ((0, import_internal3.hashCode)(matches[i]) !== hashes[i]) { + documents[indexes[i]] = matches[i]; + output2.modifiedCount++; + } + } + } else { + for (let i = 0; i < documents.length; i++) { + if ((0, import_internal3.hashCode)(matches[i]) !== hashes[i]) { + documents[i] = matches[i]; + output2.modifiedCount++; + } + } + } + if (firstOnly && output2.modifiedCount && oldFirstDoc) { + const newDoc = documents[indexes[0]]; + const modifiedFields2 = getModifiedFields( + modifier, + oldFirstDoc, + newDoc + ); + (0, import_internal3.assert)(modifiedFields2.length, "bug: failed to retrieve modified fields"); + Object.assign(output2, { modifiedFields: modifiedFields2, modifiedIndex }); + } + return output2; + } + const unknownOp = Object.keys(modifier).find((op) => !UPDATE_OPERATORS[op]); + (0, import_internal3.assert)(!unknownOp, `Unknown update operator: '${unknownOp}'.`); + const arrayFilters = updateConfig?.arrayFilters ?? []; + opts.update({ + updateParams: (0, import_internal2.buildParams)( + Object.values(modifier), + arrayFilters, + opts + ) + }); + const matchedCount = foundDocs.length; + const output = { matchedCount, modifiedCount: 0 }; + const modifiedFields = []; + const fns = []; + for (const op of Object.keys(modifier)) { + const fn = UPDATE_OPERATORS[op]; + const expr = modifier[op]; + fns.push(fn(expr, arrayFilters, opts)); + } + for (const doc of foundDocs) { + let modified = false; + for (const mutate of fns) { + const fields = mutate(doc); + if (fields.length) { + modified = true; + if (firstOnly) Array.prototype.push.apply(modifiedFields, fields); + } + } + output.modifiedCount += +modified; + } + if (firstOnly && modifiedFields.length) { + modifiedFields.sort(); + Object.assign(output, { modifiedFields, modifiedIndex }); + } + return output; + } + function getModifiedFields(pipeline, oldDoc, newDoc) { + const stageFields = []; + for (const stage of pipeline) { + const op = Object.keys(stage)[0]; + const expr = stage[op]; + switch (op) { + case "$addFields": + case "$set": + case "$project": + case "$replaceWith": + stageFields.push(...Object.keys(expr)); + break; + case "$unset": + stageFields.push(...(0, import_internal3.ensureArray)(expr)); + break; + case "$replaceRoot": + stageFields.length = 0; + stageFields.push( + ...Object.keys(expr?.newRoot) + ); + break; + } + } + const stageFieldsSet = new Set(stageFields.sort()); + const pathValidator = new import_internal3.PathValidator(); + const modifiedFields = []; + for (const key of stageFieldsSet) { + if (pathValidator.add(key) && !(0, import_internal3.isEqual)((0, import_internal3.resolve)(newDoc, key), (0, import_internal3.resolve)(oldDoc, key))) { + modifiedFields.push(key); + } + } + for (const key of Object.keys(oldDoc)) { + if (stageFieldsSet.has(key)) continue; + if (!pathValidator.add(key) || !(0, import_internal3.isEqual)(newDoc[key], oldDoc[key])) { + modifiedFields.push(key); + } + } + const topLevelValidator = new import_internal3.PathValidator(); + return modifiedFields.sort().filter((key) => topLevelValidator.add(key)); + } + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/index.js +var require_core = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/index.js"(exports, module) { + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var core_exports3 = {}; + __export5(core_exports3, { + Context: () => import_internal.Context, + OpType: () => import_internal.OpType, + ProcessingMode: () => import_internal.ProcessingMode, + computeValue: () => import_internal.computeValue, + evalExpr: () => import_internal.evalExpr + }); + module.exports = __toCommonJS(core_exports3); + var import_internal = require_internal2(); + } +}); + +// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/index.js +var require_cjs = __commonJS({ + "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/index.js"(exports, module) { + var __create2 = Object.create; + var __defProp6 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; + var __hasOwnProp3 = Object.prototype.hasOwnProperty; + var __export5 = (target, all) => { + for (var name in all) + __defProp6(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp3.call(to, key) && key !== except) + __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp6(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export5(index_exports, { + Aggregator: () => Aggregator2, + Context: () => import_core15.Context, + ProcessingMode: () => import_core15.ProcessingMode, + Query: () => Query2, + aggregate: () => aggregate, + default: () => index_default2, + find: () => find, + update: () => update, + updateMany: () => updateMany, + updateOne: () => updateOne + }); + module.exports = __toCommonJS(index_exports); + var import_aggregator = require_aggregator(); + var import_internal = require_internal2(); + var accumulatorOperators = __toESM2(require_accumulator2()); + var expressionOperators = __toESM2(require_expression()); + var pipelineOperators = __toESM2(require_pipeline()); + var projectionOperators = __toESM2(require_projection()); + var queryOperators = __toESM2(require_query2()); + var windowOperators = __toESM2(require_window()); + var import_query = require_query(); + var updater = __toESM2(require_updater()); + var import_core15 = require_core(); + var CONTEXT = import_internal.Context.init({ + accumulator: accumulatorOperators, + expression: expressionOperators, + pipeline: pipelineOperators, + projection: projectionOperators, + query: queryOperators, + window: windowOperators + }); + var makeOpts = (options) => Object.assign({ + ...options, + context: options?.context ? import_internal.Context.from(CONTEXT, options?.context) : CONTEXT + }); + var Query2 = class extends import_query.Query { + constructor(condition, options) { + super(condition, makeOpts(options)); + } + }; + var Aggregator2 = class extends import_aggregator.Aggregator { + constructor(pipeline, options) { + super(pipeline, makeOpts(options)); + } + }; + function find(collection, condition, projection, options) { + return new Query2(condition, makeOpts(options)).find( + collection, + projection + ); + } + function aggregate(collection, pipeline, options) { + return new Aggregator2(pipeline, makeOpts(options)).run(collection); + } + function update(obj, modifier, arrayFilters, condition, options) { + return updater.update(obj, modifier, arrayFilters, condition, { + cloneMode: options?.cloneMode, + queryOptions: makeOpts(options?.queryOptions) + }); + } + function updateMany(documents, condition, modifer, updateConfig = {}, options) { + return updater.updateMany( + documents, + condition, + modifer, + updateConfig, + makeOpts(options) + ); + } + function updateOne(documents, condition, modifier, updateConfig = {}, options) { + return updater.updateOne( + documents, + condition, + modifier, + updateConfig, + makeOpts(options) + ); + } + var index_default2 = { + Aggregator: Aggregator2, + Context: import_internal.Context, + ProcessingMode: import_internal.ProcessingMode, + Query: Query2, + aggregate, + find, + update, + updateMany, + updateOne + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/env-impl.mjs +function toBoolean(val) { + return val ? val !== "false" : false; +} +function getEnvVar(key, fallback) { + if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback; + if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback; + if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback; + return fallback; +} +function getBooleanEnvVar(key, fallback = true) { + const value = getEnvVar(key); + if (!value) return fallback; + return value !== "0" && value.toLowerCase() !== "false" && value !== ""; +} +var _envShim, _getEnv, env, nodeENV, isProduction, isDevelopment, isTest, ENV; +var init_env_impl = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/env-impl.mjs"() { + _envShim = /* @__PURE__ */ Object.create(null); + _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis); + env = new Proxy(_envShim, { + get(_, prop) { + return _getEnv()[prop] ?? _envShim[prop]; + }, + has(_, prop) { + return prop in _getEnv() || prop in _envShim; + }, + set(_, prop, value) { + const env2 = _getEnv(true); + env2[prop] = value; + return true; + }, + deleteProperty(_, prop) { + if (!prop) return false; + const env2 = _getEnv(true); + delete env2[prop]; + return true; + }, + ownKeys() { + const env2 = _getEnv(true); + return Object.keys(env2); + } + }); + nodeENV = typeof process !== "undefined" && process.env && process.env.NODE_ENV || ""; + isProduction = nodeENV === "production"; + isDevelopment = () => nodeENV === "dev" || nodeENV === "development"; + isTest = () => nodeENV === "test" || toBoolean(env.TEST); + ENV = Object.freeze({ + get BETTER_AUTH_SECRET() { + return getEnvVar("BETTER_AUTH_SECRET"); + }, + get AUTH_SECRET() { + return getEnvVar("AUTH_SECRET"); + }, + get BETTER_AUTH_TELEMETRY() { + return getEnvVar("BETTER_AUTH_TELEMETRY"); + }, + get BETTER_AUTH_TELEMETRY_ID() { + return getEnvVar("BETTER_AUTH_TELEMETRY_ID"); + }, + get NODE_ENV() { + return getEnvVar("NODE_ENV", "development"); + }, + get PACKAGE_VERSION() { + return getEnvVar("PACKAGE_VERSION", "0.0.0"); + }, + get BETTER_AUTH_TELEMETRY_ENDPOINT() { + return getEnvVar("BETTER_AUTH_TELEMETRY_ENDPOINT", ""); + } + }); + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/color-depth.mjs +function getColorDepth() { + if (getEnvVar("FORCE_COLOR") !== void 0) switch (getEnvVar("FORCE_COLOR")) { + case "": + case "1": + case "true": + return COLORS_16; + case "2": + return COLORS_256; + case "3": + return COLORS_16m; + default: + return COLORS_2; + } + if (getEnvVar("NODE_DISABLE_COLORS") !== void 0 && getEnvVar("NODE_DISABLE_COLORS") !== "" || getEnvVar("NO_COLOR") !== void 0 && getEnvVar("NO_COLOR") !== "" || getEnvVar("TERM") === "dumb") return COLORS_2; + if (getEnvVar("TMUX")) return COLORS_16m; + if ("TF_BUILD" in env && "AGENT_NAME" in env) return COLORS_16; + if ("CI" in env) { + for (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors; + if (getEnvVar("CI_NAME") === "codeship") return COLORS_256; + return COLORS_2; + } + if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(getEnvVar("TEAMCITY_VERSION")) !== null ? COLORS_16 : COLORS_2; + switch (getEnvVar("TERM_PROGRAM")) { + case "iTerm.app": + if (!getEnvVar("TERM_PROGRAM_VERSION") || /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null) return COLORS_256; + return COLORS_16m; + case "HyperTerm": + case "MacTerm": + return COLORS_16m; + case "Apple_Terminal": + return COLORS_256; + } + if (getEnvVar("COLORTERM") === "truecolor" || getEnvVar("COLORTERM") === "24bit") return COLORS_16m; + if (getEnvVar("TERM")) { + if (/truecolor/.exec(getEnvVar("TERM")) !== null) return COLORS_16m; + if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) return COLORS_256; + const termEnv = getEnvVar("TERM").toLowerCase(); + if (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv]; + if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16; + } + if (getEnvVar("COLORTERM")) return COLORS_16; + return COLORS_2; +} +var COLORS_2, COLORS_16, COLORS_256, COLORS_16m, TERM_ENVS, CI_ENVS_MAP, TERM_ENVS_REG_EXP; +var init_color_depth = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/color-depth.mjs"() { + init_env_impl(); + COLORS_2 = 1; + COLORS_16 = 4; + COLORS_256 = 8; + COLORS_16m = 24; + TERM_ENVS = { + eterm: COLORS_16, + cons25: COLORS_16, + console: COLORS_16, + cygwin: COLORS_16, + dtterm: COLORS_16, + gnome: COLORS_16, + hurd: COLORS_16, + jfbterm: COLORS_16, + konsole: COLORS_16, + kterm: COLORS_16, + mlterm: COLORS_16, + mosh: COLORS_16m, + putty: COLORS_16, + st: COLORS_16, + "rxvt-unicode-24bit": COLORS_16m, + terminator: COLORS_16m, + "xterm-kitty": COLORS_16m + }; + CI_ENVS_MAP = new Map(Object.entries({ + APPVEYOR: COLORS_256, + BUILDKITE: COLORS_256, + CIRCLECI: COLORS_16m, + DRONE: COLORS_256, + GITEA_ACTIONS: COLORS_16m, + GITHUB_ACTIONS: COLORS_16m, + GITLAB_CI: COLORS_256, + TRAVIS: COLORS_256 + })); + TERM_ENVS_REG_EXP = [ + /ansi/, + /color/, + /linux/, + /direct/, + /^con[0-9]*x[0-9]/, + /^rxvt/, + /^screen/, + /^xterm/, + /^vt100/, + /^vt220/ + ]; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/logger.mjs +function shouldPublishLog(currentLogLevel, logLevel) { + return levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel); +} +var TTY_COLORS, levels, levelColors, formatMessage, createLogger2, logger; +var init_logger = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/logger.mjs"() { + init_color_depth(); + TTY_COLORS = { + reset: "\x1B[0m", + bright: "\x1B[1m", + dim: "\x1B[2m", + undim: "\x1B[22m", + underscore: "\x1B[4m", + blink: "\x1B[5m", + reverse: "\x1B[7m", + hidden: "\x1B[8m", + fg: { + black: "\x1B[30m", + red: "\x1B[31m", + green: "\x1B[32m", + yellow: "\x1B[33m", + blue: "\x1B[34m", + magenta: "\x1B[35m", + cyan: "\x1B[36m", + white: "\x1B[37m" + }, + bg: { + black: "\x1B[40m", + red: "\x1B[41m", + green: "\x1B[42m", + yellow: "\x1B[43m", + blue: "\x1B[44m", + magenta: "\x1B[45m", + cyan: "\x1B[46m", + white: "\x1B[47m" + } + }; + levels = [ + "debug", + "info", + "success", + "warn", + "error" + ]; + levelColors = { + info: TTY_COLORS.fg.blue, + success: TTY_COLORS.fg.green, + warn: TTY_COLORS.fg.yellow, + error: TTY_COLORS.fg.red, + debug: TTY_COLORS.fg.magenta + }; + formatMessage = (level, message2, colorsEnabled) => { + const timestamp = (/* @__PURE__ */ new Date()).toISOString(); + if (colorsEnabled) return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message2}`; + return `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message2}`; + }; + createLogger2 = (options) => { + const enabled = options?.disabled !== true; + const logLevel = options?.level ?? "warn"; + const colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1; + const LogFunc = (level, message2, args = []) => { + if (!enabled || !shouldPublishLog(logLevel, level)) return; + const formattedMessage = formatMessage(level, message2, colorsEnabled); + if (!options || typeof options.log !== "function") { + if (level === "error") console.error(formattedMessage, ...args); + else if (level === "warn") console.warn(formattedMessage, ...args); + else console.log(formattedMessage, ...args); + return; + } + options.log(level === "success" ? "info" : level, message2, ...args); + }; + return { + ...Object.fromEntries(levels.map((level) => [level, (...[message2, ...args]) => LogFunc(level, message2, args)])), + get level() { + return logLevel; + } + }; + }; + logger = createLogger2(); + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/index.mjs +var init_env = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/index.mjs"() { + init_env_impl(); + init_logger(); + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/error-codes.mjs +function defineErrorCodes(codes) { + return Object.fromEntries(Object.entries(codes).map(([key, value]) => [key, { + code: key, + message: value, + toString: () => key + }])); +} +var init_error_codes = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/error-codes.mjs"() { + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/codes.mjs +var BASE_ERROR_CODES; +var init_codes = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/codes.mjs"() { + init_error_codes(); + BASE_ERROR_CODES = defineErrorCodes({ + USER_NOT_FOUND: "User not found", + FAILED_TO_CREATE_USER: "Failed to create user", + FAILED_TO_CREATE_SESSION: "Failed to create session", + FAILED_TO_UPDATE_USER: "Failed to update user", + FAILED_TO_GET_SESSION: "Failed to get session", + INVALID_PASSWORD: "Invalid password", + INVALID_EMAIL: "Invalid email", + INVALID_EMAIL_OR_PASSWORD: "Invalid email or password", + INVALID_USER: "Invalid user", + SOCIAL_ACCOUNT_ALREADY_LINKED: "Social account already linked", + PROVIDER_NOT_FOUND: "Provider not found", + INVALID_TOKEN: "Invalid token", + TOKEN_EXPIRED: "Token expired", + ID_TOKEN_NOT_SUPPORTED: "id_token not supported", + FAILED_TO_GET_USER_INFO: "Failed to get user info", + USER_EMAIL_NOT_FOUND: "User email not found", + EMAIL_NOT_VERIFIED: "Email not verified", + PASSWORD_TOO_SHORT: "Password too short", + PASSWORD_TOO_LONG: "Password too long", + USER_ALREADY_EXISTS: "User already exists.", + USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "User already exists. Use another email.", + EMAIL_CAN_NOT_BE_UPDATED: "Email can not be updated", + CREDENTIAL_ACCOUNT_NOT_FOUND: "Credential account not found", + SESSION_EXPIRED: "Session expired. Re-authenticate to perform this action.", + FAILED_TO_UNLINK_LAST_ACCOUNT: "You can't unlink your last account", + ACCOUNT_NOT_FOUND: "Account not found", + USER_ALREADY_HAS_PASSWORD: "User already has a password. Provide that to delete the account.", + CROSS_SITE_NAVIGATION_LOGIN_BLOCKED: "Cross-site navigation login blocked. This request appears to be a CSRF attack.", + VERIFICATION_EMAIL_NOT_ENABLED: "Verification email isn't enabled", + EMAIL_ALREADY_VERIFIED: "Email is already verified", + EMAIL_MISMATCH: "Email mismatch", + SESSION_NOT_FRESH: "Session is not fresh", + LINKED_ACCOUNT_ALREADY_EXISTS: "Linked account already exists", + INVALID_ORIGIN: "Invalid origin", + INVALID_CALLBACK_URL: "Invalid callbackURL", + INVALID_REDIRECT_URL: "Invalid redirectURL", + INVALID_ERROR_CALLBACK_URL: "Invalid errorCallbackURL", + INVALID_NEW_USER_CALLBACK_URL: "Invalid newUserCallbackURL", + MISSING_OR_NULL_ORIGIN: "Missing or null Origin", + CALLBACK_URL_REQUIRED: "callbackURL is required", + FAILED_TO_CREATE_VERIFICATION: "Unable to create verification", + FIELD_NOT_ALLOWED: "Field not allowed to be set", + ASYNC_VALIDATION_NOT_SUPPORTED: "Async validation is not supported", + VALIDATION_ERROR: "Validation Error", + MISSING_FIELD: "Field is required", + METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED: "POST method requires deferSessionRefresh to be enabled in session config", + BODY_MUST_BE_AN_OBJECT: "Body must be an object", + PASSWORD_ALREADY_SET: "User already has a password set" + }); + } +}); + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/error.mjs +function isErrorStackTraceLimitWritable() { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.prototype.hasOwnProperty.call(desc, "writable") ? desc.writable : desc.set !== void 0; +} +function hideInternalStackFrames(stack) { + const lines = stack.split("\n at "); + if (lines.length <= 1) return stack; + lines.splice(1, 1); + return lines.join("\n at "); +} +function makeErrorForHideStackFrame(Base, clazz) { + var _hiddenStack; + class HideStackFramesError extends Base { + constructor(...args2) { + var __super = (...args) => { + super(...args); + __privateAdd(this, _hiddenStack); + return this; + }; + if (isErrorStackTraceLimitWritable()) { + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + __super(...args2); + Error.stackTraceLimit = limit; + } else __super(...args2); + const stack = (/* @__PURE__ */ new Error()).stack; + if (stack) __privateSet(this, _hiddenStack, hideInternalStackFrames(stack.replace(/^Error/, this.name))); + } + get errorStack() { + return __privateGet(this, _hiddenStack); + } + } + _hiddenStack = new WeakMap(); + Object.defineProperty(HideStackFramesError.prototype, "constructor", { + get() { + return clazz; + }, + enumerable: false, + configurable: true + }); + return HideStackFramesError; +} +var statusCodes, InternalAPIError, ValidationError, BetterCallError, kAPIErrorHeaderSymbol, APIError; +var init_error = __esm({ + "../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/error.mjs"() { + statusCodes = { + OK: 200, + CREATED: 201, + ACCEPTED: 202, + NO_CONTENT: 204, + MULTIPLE_CHOICES: 300, + MOVED_PERMANENTLY: 301, + FOUND: 302, + SEE_OTHER: 303, + NOT_MODIFIED: 304, + TEMPORARY_REDIRECT: 307, + BAD_REQUEST: 400, + UNAUTHORIZED: 401, + PAYMENT_REQUIRED: 402, + FORBIDDEN: 403, + NOT_FOUND: 404, + METHOD_NOT_ALLOWED: 405, + NOT_ACCEPTABLE: 406, + PROXY_AUTHENTICATION_REQUIRED: 407, + REQUEST_TIMEOUT: 408, + CONFLICT: 409, + GONE: 410, + LENGTH_REQUIRED: 411, + PRECONDITION_FAILED: 412, + PAYLOAD_TOO_LARGE: 413, + URI_TOO_LONG: 414, + UNSUPPORTED_MEDIA_TYPE: 415, + RANGE_NOT_SATISFIABLE: 416, + EXPECTATION_FAILED: 417, + "I'M_A_TEAPOT": 418, + MISDIRECTED_REQUEST: 421, + UNPROCESSABLE_ENTITY: 422, + LOCKED: 423, + FAILED_DEPENDENCY: 424, + TOO_EARLY: 425, + UPGRADE_REQUIRED: 426, + PRECONDITION_REQUIRED: 428, + TOO_MANY_REQUESTS: 429, + REQUEST_HEADER_FIELDS_TOO_LARGE: 431, + UNAVAILABLE_FOR_LEGAL_REASONS: 451, + INTERNAL_SERVER_ERROR: 500, + NOT_IMPLEMENTED: 501, + BAD_GATEWAY: 502, + SERVICE_UNAVAILABLE: 503, + GATEWAY_TIMEOUT: 504, + HTTP_VERSION_NOT_SUPPORTED: 505, + VARIANT_ALSO_NEGOTIATES: 506, + INSUFFICIENT_STORAGE: 507, + LOOP_DETECTED: 508, + NOT_EXTENDED: 510, + NETWORK_AUTHENTICATION_REQUIRED: 511 + }; + InternalAPIError = class extends Error { + constructor(status = "INTERNAL_SERVER_ERROR", body = void 0, headers = {}, statusCode = typeof status === "number" ? status : statusCodes[status]) { + super(body?.message, body?.cause ? { cause: body.cause } : void 0); + this.status = status; + this.body = body; + this.headers = headers; + this.statusCode = statusCode; + this.name = "APIError"; + this.status = status; + this.headers = headers; + this.statusCode = statusCode; + this.body = body; + } + }; + ValidationError = class extends InternalAPIError { + constructor(message2, issues) { + super(400, { + message: message2, + code: "VALIDATION_ERROR" + }); + this.message = message2; + this.issues = issues; + this.issues = issues; + } + }; + BetterCallError = class extends Error { + constructor(message2) { + super(message2); + this.name = "BetterCallError"; + } + }; + kAPIErrorHeaderSymbol = Symbol.for("better-call:api-error-headers"); + APIError = makeErrorForHideStackFrame(InternalAPIError, Error); + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/index.mjs +var BetterAuthError, APIError2; +var init_error2 = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/index.mjs"() { + init_codes(); + init_error(); + BetterAuthError = class extends Error { + constructor(message2, options) { + super(message2, options); + this.name = "BetterAuthError"; + this.message = message2; + this.stack = ""; + } + }; + APIError2 = class APIError3 extends APIError { + constructor(...args) { + super(...args); + } + static fromStatus(status, body) { + return new APIError3(status, body); + } + static from(status, error49) { + return new APIError3(status, { + message: error49.message, + code: error49.code + }); + } + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/random.mjs +function expandAlphabet(alphabet) { + switch (alphabet) { + case "a-z": + return "abcdefghijklmnopqrstuvwxyz"; + case "A-Z": + return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + case "0-9": + return "0123456789"; + case "-_": + return "-_"; + default: + throw new Error(`Unsupported alphabet: ${alphabet}`); + } +} +function createRandomStringGenerator(...baseAlphabets) { + const baseCharSet = baseAlphabets.map(expandAlphabet).join(""); + if (baseCharSet.length === 0) { + throw new Error( + "No valid characters provided for random string generation." + ); + } + const baseCharSetLength = baseCharSet.length; + return (length, ...alphabets) => { + if (length <= 0) { + throw new Error("Length must be a positive integer."); + } + let charSet = baseCharSet; + let charSetLength = baseCharSetLength; + if (alphabets.length > 0) { + charSet = alphabets.map(expandAlphabet).join(""); + charSetLength = charSet.length; + } + const maxValid = Math.floor(256 / charSetLength) * charSetLength; + const buf = new Uint8Array(length * 2); + const bufLength = buf.length; + let result = ""; + let bufIndex = bufLength; + let rand; + while (result.length < length) { + if (bufIndex >= bufLength) { + crypto.getRandomValues(buf); + bufIndex = 0; + } + rand = buf[bufIndex++]; + if (rand < maxValid) { + result += charSet[rand % charSetLength]; + } + } + return result; + }; +} +var init_random = __esm({ + "../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/random.mjs"() { + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/get-tables.mjs +var getAuthTables; +var init_get_tables = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/get-tables.mjs"() { + getAuthTables = (options) => { + const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => { + const schema3 = plugin.schema; + if (!schema3) return acc; + for (const [key, value] of Object.entries(schema3)) acc[key] = { + fields: { + ...acc[key]?.fields, + ...value.fields + }, + modelName: value.modelName || key + }; + return acc; + }, {}); + const shouldAddRateLimitTable = options.rateLimit?.storage === "database"; + const rateLimitTable = { rateLimit: { + modelName: options.rateLimit?.modelName || "rateLimit", + fields: { + key: { + type: "string", + unique: true, + required: true, + fieldName: options.rateLimit?.fields?.key || "key" + }, + count: { + type: "number", + required: true, + fieldName: options.rateLimit?.fields?.count || "count" + }, + lastRequest: { + type: "number", + bigint: true, + required: true, + fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest", + defaultValue: () => Date.now() + } + } + } }; + const { user, session, account, verification, ...pluginTables } = pluginSchema; + const verificationTable = { verification: { + modelName: options.verification?.modelName || "verification", + fields: { + identifier: { + type: "string", + required: true, + fieldName: options.verification?.fields?.identifier || "identifier", + index: true + }, + value: { + type: "string", + required: true, + fieldName: options.verification?.fields?.value || "value" + }, + expiresAt: { + type: "date", + required: true, + fieldName: options.verification?.fields?.expiresAt || "expiresAt" + }, + createdAt: { + type: "date", + required: true, + defaultValue: () => /* @__PURE__ */ new Date(), + fieldName: options.verification?.fields?.createdAt || "createdAt" + }, + updatedAt: { + type: "date", + required: true, + defaultValue: () => /* @__PURE__ */ new Date(), + onUpdate: () => /* @__PURE__ */ new Date(), + fieldName: options.verification?.fields?.updatedAt || "updatedAt" + }, + ...verification?.fields, + ...options.verification?.additionalFields + }, + order: 4 + } }; + const sessionTable = { session: { + modelName: options.session?.modelName || "session", + fields: { + expiresAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.expiresAt || "expiresAt" + }, + token: { + type: "string", + required: true, + fieldName: options.session?.fields?.token || "token", + unique: true + }, + createdAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.createdAt || "createdAt", + defaultValue: () => /* @__PURE__ */ new Date() + }, + updatedAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.updatedAt || "updatedAt", + onUpdate: () => /* @__PURE__ */ new Date() + }, + ipAddress: { + type: "string", + required: false, + fieldName: options.session?.fields?.ipAddress || "ipAddress" + }, + userAgent: { + type: "string", + required: false, + fieldName: options.session?.fields?.userAgent || "userAgent" + }, + userId: { + type: "string", + fieldName: options.session?.fields?.userId || "userId", + references: { + model: options.user?.modelName || "user", + field: "id", + onDelete: "cascade" + }, + required: true, + index: true + }, + ...session?.fields, + ...options.session?.additionalFields + }, + order: 2 + } }; + return { + user: { + modelName: options.user?.modelName || "user", + fields: { + name: { + type: "string", + required: true, + fieldName: options.user?.fields?.name || "name", + sortable: true + }, + email: { + type: "string", + unique: true, + required: true, + fieldName: options.user?.fields?.email || "email", + sortable: true + }, + emailVerified: { + type: "boolean", + defaultValue: false, + required: true, + fieldName: options.user?.fields?.emailVerified || "emailVerified", + input: false + }, + image: { + type: "string", + required: false, + fieldName: options.user?.fields?.image || "image" + }, + createdAt: { + type: "date", + defaultValue: () => /* @__PURE__ */ new Date(), + required: true, + fieldName: options.user?.fields?.createdAt || "createdAt" + }, + updatedAt: { + type: "date", + defaultValue: () => /* @__PURE__ */ new Date(), + onUpdate: () => /* @__PURE__ */ new Date(), + required: true, + fieldName: options.user?.fields?.updatedAt || "updatedAt" + }, + ...user?.fields, + ...options.user?.additionalFields + }, + order: 1 + }, + ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {}, + account: { + modelName: options.account?.modelName || "account", + fields: { + accountId: { + type: "string", + required: true, + fieldName: options.account?.fields?.accountId || "accountId" + }, + providerId: { + type: "string", + required: true, + fieldName: options.account?.fields?.providerId || "providerId" + }, + userId: { + type: "string", + references: { + model: options.user?.modelName || "user", + field: "id", + onDelete: "cascade" + }, + required: true, + fieldName: options.account?.fields?.userId || "userId", + index: true + }, + accessToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.accessToken || "accessToken" + }, + refreshToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.refreshToken || "refreshToken" + }, + idToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.idToken || "idToken" + }, + accessTokenExpiresAt: { + type: "date", + required: false, + returned: false, + fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt" + }, + refreshTokenExpiresAt: { + type: "date", + required: false, + returned: false, + fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt" + }, + scope: { + type: "string", + required: false, + fieldName: options.account?.fields?.scope || "scope" + }, + password: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.password || "password" + }, + createdAt: { + type: "date", + required: true, + fieldName: options.account?.fields?.createdAt || "createdAt", + defaultValue: () => /* @__PURE__ */ new Date() + }, + updatedAt: { + type: "date", + required: true, + fieldName: options.account?.fields?.updatedAt || "updatedAt", + onUpdate: () => /* @__PURE__ */ new Date() + }, + ...account?.fields, + ...options.account?.additionalFields + }, + order: 3 + }, + ...!options.secondaryStorage || options.verification?.storeInDatabase ? verificationTable : {}, + ...pluginTables, + ...shouldAddRateLimitTable ? rateLimitTable : {} + }; + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/json.mjs +function reviveDate(value) { + if (typeof value === "string" && iso8601Regex.test(value)) { + const date5 = new Date(value); + if (!isNaN(date5.getTime())) return date5; + } + return value; +} +function reviveDates(value) { + if (value === null || value === void 0) return value; + if (typeof value === "string") return reviveDate(value); + if (value instanceof Date) return value; + if (Array.isArray(value)) return value.map(reviveDates); + if (typeof value === "object") { + const result = {}; + for (const key of Object.keys(value)) result[key] = reviveDates(value[key]); + return result; + } + return value; +} +function safeJSONParse(data) { + try { + if (typeof data !== "string") { + if (data === null || data === void 0) return null; + return reviveDates(data); + } + return JSON.parse(data, (_, value) => reviveDate(value)); + } catch (e) { + logger.error("Error parsing JSON", { error: e }); + return null; + } +} +var iso8601Regex; +var init_json = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/json.mjs"() { + init_logger(); + iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/; + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js +var init_SemanticAttributes = __esm({ + "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js"() { + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js +var init_trace = __esm({ + "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js"() { + init_SemanticAttributes(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js +var init_SemanticResourceAttributes = __esm({ + "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js"() { + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js +var init_resource = __esm({ + "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js"() { + init_SemanticResourceAttributes(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js +var ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE; +var init_stable_attributes = __esm({ + "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js"() { + ATTR_DB_COLLECTION_NAME = "db.collection.name"; + ATTR_DB_OPERATION_NAME = "db.operation.name"; + ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; + ATTR_HTTP_ROUTE = "http.route"; + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.js +var init_stable_metrics = __esm({ + "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.js"() { + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.js +var init_stable_events = __esm({ + "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.js"() { + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/index.js +var init_esm = __esm({ + "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/index.js"() { + init_trace(); + init_resource(); + init_stable_attributes(); + init_stable_metrics(); + init_stable_events(); + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/attributes.mjs +var ATTR_OPERATION_ID, ATTR_HOOK_TYPE, ATTR_CONTEXT; +var init_attributes = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/attributes.mjs"() { + init_esm(); + ATTR_OPERATION_ID = "better_auth.operation_id"; + ATTR_HOOK_TYPE = "better_auth.hook.type"; + ATTR_CONTEXT = "better_auth.context"; + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js +var _globalThis; +var init_globalThis = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js"() { + _globalThis = typeof globalThis === "object" ? globalThis : global; + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/index.js +var init_node = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/index.js"() { + init_globalThis(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/index.js +var init_platform = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/index.js"() { + init_node(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/version.js +var VERSION; +var init_version = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/version.js"() { + VERSION = "1.9.0"; + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/semver.js +function _makeCompatibilityCheck(ownVersion) { + var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); + var rejectedVersions = /* @__PURE__ */ new Set(); + var myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + return function() { + return false; + }; + } + var ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4] + }; + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject2(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible2(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + var globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + return _reject2(globalVersion); + } + var globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4] + }; + if (globalVersionParsed.prerelease != null) { + return _reject2(globalVersion); + } + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject2(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject2(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject2(globalVersion); + }; +} +var re, isCompatible; +var init_semver = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/semver.js"() { + init_version(); + re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; + isCompatible = _makeCompatibilityCheck(VERSION); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js +function registerGlobal(type, instance, diag, allowOverride) { + var _a30; + if (allowOverride === void 0) { + allowOverride = false; + } + var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a30 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a30 !== void 0 ? _a30 : { + version: VERSION + }; + if (!allowOverride && api[type]) { + var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== VERSION) { + var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + "."); + return true; +} +function getGlobal(type) { + var _a30, _b2; + var globalVersion = (_a30 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a30 === void 0 ? void 0 : _a30.version; + if (!globalVersion || !isCompatible(globalVersion)) { + return; + } + return (_b2 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b2 === void 0 ? void 0 : _b2[type]; +} +function unregisterGlobal(type, diag) { + diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + "."); + var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } +} +var major, GLOBAL_OPENTELEMETRY_API_KEY, _global; +var init_global_utils = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js"() { + init_platform(); + init_version(); + init_semver(); + major = VERSION.split(".")[0]; + GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); + _global = _globalThis; + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js +function logProxy(funcName, namespace, args) { + var logger2 = getGlobal("diag"); + if (!logger2) { + return; + } + args.unshift(namespace); + return logger2[funcName].apply(logger2, __spreadArray([], __read(args), false)); +} +var __read, __spreadArray, DiagComponentLogger; +var init_ComponentLogger = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js"() { + init_global_utils(); + __read = function(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error49) { + e = { error: error49 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; + }; + __spreadArray = function(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + DiagComponentLogger = /** @class */ + function() { + function DiagComponentLogger2(props) { + this._namespace = props.namespace || "DiagComponentLogger"; + } + DiagComponentLogger2.prototype.debug = function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy("debug", this._namespace, args); + }; + DiagComponentLogger2.prototype.error = function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy("error", this._namespace, args); + }; + DiagComponentLogger2.prototype.info = function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy("info", this._namespace, args); + }; + DiagComponentLogger2.prototype.warn = function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy("warn", this._namespace, args); + }; + DiagComponentLogger2.prototype.verbose = function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy("verbose", this._namespace, args); + }; + return DiagComponentLogger2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/types.js +var DiagLogLevel; +var init_types = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/types.js"() { + (function(DiagLogLevel2) { + DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE"; + DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR"; + DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN"; + DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO"; + DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG"; + DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE"; + DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL"; + })(DiagLogLevel || (DiagLogLevel = {})); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js +function createLogLevelDiagLogger(maxLevel, logger2) { + if (maxLevel < DiagLogLevel.NONE) { + maxLevel = DiagLogLevel.NONE; + } else if (maxLevel > DiagLogLevel.ALL) { + maxLevel = DiagLogLevel.ALL; + } + logger2 = logger2 || {}; + function _filterFunc(funcName, theLevel) { + var theFunc = logger2[funcName]; + if (typeof theFunc === "function" && maxLevel >= theLevel) { + return theFunc.bind(logger2); + } + return function() { + }; + } + return { + error: _filterFunc("error", DiagLogLevel.ERROR), + warn: _filterFunc("warn", DiagLogLevel.WARN), + info: _filterFunc("info", DiagLogLevel.INFO), + debug: _filterFunc("debug", DiagLogLevel.DEBUG), + verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE) + }; +} +var init_logLevelLogger = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js"() { + init_types(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/diag.js +var __read2, __spreadArray2, API_NAME, DiagAPI; +var init_diag = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/diag.js"() { + init_ComponentLogger(); + init_logLevelLogger(); + init_types(); + init_global_utils(); + __read2 = function(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error49) { + e = { error: error49 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; + }; + __spreadArray2 = function(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + API_NAME = "diag"; + DiagAPI = /** @class */ + function() { + function DiagAPI2() { + function _logProxy(funcName) { + return function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var logger2 = getGlobal("diag"); + if (!logger2) + return; + return logger2[funcName].apply(logger2, __spreadArray2([], __read2(args), false)); + }; + } + var self = this; + var setLogger = function(logger2, optionsOrLogLevel) { + var _a30, _b2, _c; + if (optionsOrLogLevel === void 0) { + optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }; + } + if (logger2 === self) { + var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); + self.error((_a30 = err.stack) !== null && _a30 !== void 0 ? _a30 : err.message); + return false; + } + if (typeof optionsOrLogLevel === "number") { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel + }; + } + var oldLogger = getGlobal("diag"); + var newLogger = createLogLevelDiagLogger((_b2 = optionsOrLogLevel.logLevel) !== null && _b2 !== void 0 ? _b2 : DiagLogLevel.INFO, logger2); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; + oldLogger.warn("Current logger will be overwritten from " + stack); + newLogger.warn("Current logger will overwrite one already registered from " + stack); + } + return registerGlobal("diag", newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = function() { + unregisterGlobal(API_NAME, self); + }; + self.createComponentLogger = function(options) { + return new DiagComponentLogger(options); + }; + self.verbose = _logProxy("verbose"); + self.debug = _logProxy("debug"); + self.info = _logProxy("info"); + self.warn = _logProxy("warn"); + self.error = _logProxy("error"); + } + DiagAPI2.instance = function() { + if (!this._instance) { + this._instance = new DiagAPI2(); + } + return this._instance; + }; + return DiagAPI2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/context.js +function createContextKey(description) { + return Symbol.for(description); +} +var BaseContext, ROOT_CONTEXT; +var init_context = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/context.js"() { + BaseContext = /** @class */ + /* @__PURE__ */ function() { + function BaseContext2(parentContext) { + var self = this; + self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); + self.getValue = function(key) { + return self._currentContext.get(key); + }; + self.setValue = function(key, value) { + var context = new BaseContext2(self._currentContext); + context._currentContext.set(key, value); + return context; + }; + self.deleteValue = function(key) { + var context = new BaseContext2(self._currentContext); + context._currentContext.delete(key); + return context; + }; + } + return BaseContext2; + }(); + ROOT_CONTEXT = new BaseContext(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js +var __read3, __spreadArray3, NoopContextManager; +var init_NoopContextManager = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js"() { + init_context(); + __read3 = function(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error49) { + e = { error: error49 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; + }; + __spreadArray3 = function(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + NoopContextManager = /** @class */ + function() { + function NoopContextManager2() { + } + NoopContextManager2.prototype.active = function() { + return ROOT_CONTEXT; + }; + NoopContextManager2.prototype.with = function(_context2, fn, thisArg) { + var args = []; + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false)); + }; + NoopContextManager2.prototype.bind = function(_context2, target) { + return target; + }; + NoopContextManager2.prototype.enable = function() { + return this; + }; + NoopContextManager2.prototype.disable = function() { + return this; + }; + return NoopContextManager2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/context.js +var __read4, __spreadArray4, API_NAME2, NOOP_CONTEXT_MANAGER, ContextAPI; +var init_context2 = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/context.js"() { + init_NoopContextManager(); + init_global_utils(); + init_diag(); + __read4 = function(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error49) { + e = { error: error49 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; + }; + __spreadArray4 = function(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + API_NAME2 = "context"; + NOOP_CONTEXT_MANAGER = new NoopContextManager(); + ContextAPI = /** @class */ + function() { + function ContextAPI2() { + } + ContextAPI2.getInstance = function() { + if (!this._instance) { + this._instance = new ContextAPI2(); + } + return this._instance; + }; + ContextAPI2.prototype.setGlobalContextManager = function(contextManager) { + return registerGlobal(API_NAME2, contextManager, DiagAPI.instance()); + }; + ContextAPI2.prototype.active = function() { + return this._getContextManager().active(); + }; + ContextAPI2.prototype.with = function(context, fn, thisArg) { + var _a30; + var args = []; + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + return (_a30 = this._getContextManager()).with.apply(_a30, __spreadArray4([context, fn, thisArg], __read4(args), false)); + }; + ContextAPI2.prototype.bind = function(context, target) { + return this._getContextManager().bind(context, target); + }; + ContextAPI2.prototype._getContextManager = function() { + return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER; + }; + ContextAPI2.prototype.disable = function() { + this._getContextManager().disable(); + unregisterGlobal(API_NAME2, DiagAPI.instance()); + }; + return ContextAPI2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js +var TraceFlags; +var init_trace_flags = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js"() { + (function(TraceFlags2) { + TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE"; + TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED"; + })(TraceFlags || (TraceFlags = {})); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js +var INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT; +var init_invalid_span_constants = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js"() { + init_trace_flags(); + INVALID_SPANID = "0000000000000000"; + INVALID_TRACEID = "00000000000000000000000000000000"; + INVALID_SPAN_CONTEXT = { + traceId: INVALID_TRACEID, + spanId: INVALID_SPANID, + traceFlags: TraceFlags.NONE + }; + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js +var NonRecordingSpan; +var init_NonRecordingSpan = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js"() { + init_invalid_span_constants(); + NonRecordingSpan = /** @class */ + function() { + function NonRecordingSpan2(_spanContext) { + if (_spanContext === void 0) { + _spanContext = INVALID_SPAN_CONTEXT; + } + this._spanContext = _spanContext; + } + NonRecordingSpan2.prototype.spanContext = function() { + return this._spanContext; + }; + NonRecordingSpan2.prototype.setAttribute = function(_key, _value) { + return this; + }; + NonRecordingSpan2.prototype.setAttributes = function(_attributes) { + return this; + }; + NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) { + return this; + }; + NonRecordingSpan2.prototype.addLink = function(_link) { + return this; + }; + NonRecordingSpan2.prototype.addLinks = function(_links) { + return this; + }; + NonRecordingSpan2.prototype.setStatus = function(_status2) { + return this; + }; + NonRecordingSpan2.prototype.updateName = function(_name) { + return this; + }; + NonRecordingSpan2.prototype.end = function(_endTime) { + }; + NonRecordingSpan2.prototype.isRecording = function() { + return false; + }; + NonRecordingSpan2.prototype.recordException = function(_exception, _time) { + }; + return NonRecordingSpan2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js +function getSpan(context) { + return context.getValue(SPAN_KEY) || void 0; +} +function getActiveSpan() { + return getSpan(ContextAPI.getInstance().active()); +} +function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan(spanContext)); +} +function getSpanContext(context) { + var _a30; + return (_a30 = getSpan(context)) === null || _a30 === void 0 ? void 0 : _a30.spanContext(); +} +var SPAN_KEY; +var init_context_utils = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js"() { + init_context(); + init_NonRecordingSpan(); + init_context2(); + SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN"); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js +function isValidTraceId(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID; +} +function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID; +} +function isSpanContextValid(spanContext) { + return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); +} +function wrapSpanContext(spanContext) { + return new NonRecordingSpan(spanContext); +} +var VALID_TRACEID_REGEX, VALID_SPANID_REGEX; +var init_spancontext_utils = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js"() { + init_invalid_span_constants(); + init_NonRecordingSpan(); + VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; + VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js +function isSpanContext(spanContext) { + return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number"; +} +var contextApi, NoopTracer; +var init_NoopTracer = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js"() { + init_context2(); + init_context_utils(); + init_NonRecordingSpan(); + init_spancontext_utils(); + contextApi = ContextAPI.getInstance(); + NoopTracer = /** @class */ + function() { + function NoopTracer2() { + } + NoopTracer2.prototype.startSpan = function(name, options, context) { + if (context === void 0) { + context = contextApi.active(); + } + var root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan(); + } + var parentFromContext = context && getSpanContext(context); + if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) { + return new NonRecordingSpan(parentFromContext); + } else { + return new NonRecordingSpan(); + } + }; + NoopTracer2.prototype.startActiveSpan = function(name, arg2, arg3, arg4) { + var opts; + var ctx; + var fn; + if (arguments.length < 2) { + return; + } else if (arguments.length === 2) { + fn = arg2; + } else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + var span = this.startSpan(name, opts, parentContext); + var contextWithSpanSet = setSpan(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, void 0, span); + }; + return NoopTracer2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js +var NOOP_TRACER, ProxyTracer; +var init_ProxyTracer = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js"() { + init_NoopTracer(); + NOOP_TRACER = new NoopTracer(); + ProxyTracer = /** @class */ + function() { + function ProxyTracer2(_provider, name, version3, options) { + this._provider = _provider; + this.name = name; + this.version = version3; + this.options = options; + } + ProxyTracer2.prototype.startSpan = function(name, options, context) { + return this._getTracer().startSpan(name, options, context); + }; + ProxyTracer2.prototype.startActiveSpan = function(_name, _options2, _context2, _fn) { + var tracer2 = this._getTracer(); + return Reflect.apply(tracer2.startActiveSpan, tracer2, arguments); + }; + ProxyTracer2.prototype._getTracer = function() { + if (this._delegate) { + return this._delegate; + } + var tracer2 = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer2) { + return NOOP_TRACER; + } + this._delegate = tracer2; + return this._delegate; + }; + return ProxyTracer2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js +var NoopTracerProvider; +var init_NoopTracerProvider = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js"() { + init_NoopTracer(); + NoopTracerProvider = /** @class */ + function() { + function NoopTracerProvider2() { + } + NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options2) { + return new NoopTracer(); + }; + return NoopTracerProvider2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js +var NOOP_TRACER_PROVIDER, ProxyTracerProvider; +var init_ProxyTracerProvider = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js"() { + init_ProxyTracer(); + init_NoopTracerProvider(); + NOOP_TRACER_PROVIDER = new NoopTracerProvider(); + ProxyTracerProvider = /** @class */ + function() { + function ProxyTracerProvider2() { + } + ProxyTracerProvider2.prototype.getTracer = function(name, version3, options) { + var _a30; + return (_a30 = this.getDelegateTracer(name, version3, options)) !== null && _a30 !== void 0 ? _a30 : new ProxyTracer(this, name, version3, options); + }; + ProxyTracerProvider2.prototype.getDelegate = function() { + var _a30; + return (_a30 = this._delegate) !== null && _a30 !== void 0 ? _a30 : NOOP_TRACER_PROVIDER; + }; + ProxyTracerProvider2.prototype.setDelegate = function(delegate) { + this._delegate = delegate; + }; + ProxyTracerProvider2.prototype.getDelegateTracer = function(name, version3, options) { + var _a30; + return (_a30 = this._delegate) === null || _a30 === void 0 ? void 0 : _a30.getTracer(name, version3, options); + }; + return ProxyTracerProvider2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js +var SpanStatusCode; +var init_status = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"() { + (function(SpanStatusCode2) { + SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET"; + SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK"; + SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR"; + })(SpanStatusCode || (SpanStatusCode = {})); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/trace.js +var API_NAME3, TraceAPI; +var init_trace2 = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/trace.js"() { + init_global_utils(); + init_ProxyTracerProvider(); + init_spancontext_utils(); + init_context_utils(); + init_diag(); + API_NAME3 = "trace"; + TraceAPI = /** @class */ + function() { + function TraceAPI2() { + this._proxyTracerProvider = new ProxyTracerProvider(); + this.wrapSpanContext = wrapSpanContext; + this.isSpanContextValid = isSpanContextValid; + this.deleteSpan = deleteSpan; + this.getSpan = getSpan; + this.getActiveSpan = getActiveSpan; + this.getSpanContext = getSpanContext; + this.setSpan = setSpan; + this.setSpanContext = setSpanContext; + } + TraceAPI2.getInstance = function() { + if (!this._instance) { + this._instance = new TraceAPI2(); + } + return this._instance; + }; + TraceAPI2.prototype.setGlobalTracerProvider = function(provider) { + var success2 = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance()); + if (success2) { + this._proxyTracerProvider.setDelegate(provider); + } + return success2; + }; + TraceAPI2.prototype.getTracerProvider = function() { + return getGlobal(API_NAME3) || this._proxyTracerProvider; + }; + TraceAPI2.prototype.getTracer = function(name, version3) { + return this.getTracerProvider().getTracer(name, version3); + }; + TraceAPI2.prototype.disable = function() { + unregisterGlobal(API_NAME3, DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider(); + }; + return TraceAPI2; + }(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js +var trace; +var init_trace_api = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"() { + init_trace2(); + trace = TraceAPI.getInstance(); + } +}); + +// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/index.js +var init_esm2 = __esm({ + "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/index.js"() { + init_status(); + init_trace_api(); + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/tracer.mjs +function isRedirectError(err) { + if (err != null && typeof err === "object" && "name" in err && err.name === "APIError" && "statusCode" in err) { + const status = err.statusCode; + return status >= 300 && status < 400; + } + return false; +} +function endSpanWithError(span, err) { + if (isRedirectError(err)) { + span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, err.statusCode); + span.setStatus({ code: SpanStatusCode.OK }); + } else { + span.recordException(err); + span.setStatus({ + code: SpanStatusCode.ERROR, + message: String(err?.message ?? err) + }); + } + span.end(); +} +function withSpan(name, attributes, fn) { + return tracer.startActiveSpan(name, { attributes }, (span) => { + try { + const result = fn(); + if (result instanceof Promise) return result.then((value) => { + span.end(); + return value; + }).catch((err) => { + endSpanWithError(span, err); + throw err; + }); + span.end(); + return result; + } catch (err) { + endSpanWithError(span, err); + throw err; + } + }); +} +var tracer; +var init_tracer = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/tracer.mjs"() { + init_attributes(); + init_esm2(); + tracer = trace.getTracer("better-auth", "1.6.2"); + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/id.mjs +var generateId; +var init_id2 = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/id.mjs"() { + init_random(); + generateId = (size) => { + return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32); + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs +var initGetDefaultModelName; +var init_get_default_model_name = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs"() { + init_error2(); + initGetDefaultModelName = ({ usePlural, schema: schema3 }) => { + const getDefaultModelName = (model) => { + if (usePlural && model.charAt(model.length - 1) === "s") { + const pluralessModel = model.slice(0, -1); + let m2 = schema3[pluralessModel] ? pluralessModel : void 0; + if (!m2) m2 = Object.entries(schema3).find(([_, f]) => f.modelName === pluralessModel)?.[0]; + if (m2) return m2; + } + let m = schema3[model] ? model : void 0; + if (!m) m = Object.entries(schema3).find(([_, f]) => f.modelName === model)?.[0]; + if (!m) throw new BetterAuthError(`Model "${model}" not found in schema`); + return m; + }; + return getDefaultModelName; + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs +var initGetDefaultFieldName; +var init_get_default_field_name = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs"() { + init_error2(); + init_get_default_model_name(); + initGetDefaultFieldName = ({ schema: schema3, usePlural }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema: schema3, + usePlural + }); + const getDefaultFieldName = ({ field, model: unsafeModel }) => { + if (field === "id" || field === "_id") return "id"; + const model = getDefaultModelName(unsafeModel); + let f = schema3[model]?.fields[field]; + if (!f) { + const result = Object.entries(schema3[model].fields).find(([_, f2]) => f2.fieldName === field); + if (result) { + f = result[1]; + field = result[0]; + } + } + if (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`); + return field; + }; + return getDefaultFieldName; + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs +var initGetIdField; +var init_get_id_field = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs"() { + init_logger(); + init_id2(); + init_get_default_model_name(); + initGetIdField = ({ usePlural, schema: schema3, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => { + const getDefaultModelName = initGetDefaultModelName({ + usePlural, + schema: schema3 + }); + const idField = ({ customModelName, forceAllowId }) => { + const useNumberId = options.advanced?.database?.generateId === "serial"; + const useUUIDs = options.advanced?.database?.generateId === "uuid"; + const shouldGenerateId = (() => { + if (disableIdGeneration) return false; + else if (useNumberId && !forceAllowId) return false; + else if (useUUIDs) return !supportsUUIDs; + else return true; + })(); + const model = getDefaultModelName(customModelName ?? "id"); + return { + type: useNumberId ? "number" : "string", + required: shouldGenerateId ? true : false, + ...shouldGenerateId ? { defaultValue() { + if (disableIdGeneration) return void 0; + const generateId$1 = options.advanced?.database?.generateId; + if (generateId$1 === false || generateId$1 === "serial") return void 0; + if (typeof generateId$1 === "function") return generateId$1({ model }); + if (generateId$1 === "uuid") return crypto.randomUUID(); + if (customIdGenerator) return customIdGenerator({ model }); + return generateId(); + } } : {}, + transform: { + input: (value) => { + if (!value) return void 0; + if (useNumberId) { + const numberValue = Number(value); + if (isNaN(numberValue)) return; + return numberValue; + } + if (useUUIDs) { + if (shouldGenerateId && !forceAllowId) return value; + if (disableIdGeneration) return void 0; + if (supportsUUIDs) return void 0; + if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value; + else { + const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", ""); + logger.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack); + } + if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID(); + return; + } + return value; + }, + output: (value) => { + if (!value) return void 0; + return String(value); + } + } + }; + }; + return idField; + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs +var initGetFieldAttributes; +var init_get_field_attributes = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs"() { + init_error2(); + init_get_default_model_name(); + init_get_default_field_name(); + init_get_id_field(); + initGetFieldAttributes = ({ usePlural, schema: schema3, options, customIdGenerator, disableIdGeneration }) => { + const getDefaultModelName = initGetDefaultModelName({ + usePlural, + schema: schema3 + }); + const getDefaultFieldName = initGetDefaultFieldName({ + usePlural, + schema: schema3 + }); + const idField = initGetIdField({ + usePlural, + schema: schema3, + options, + customIdGenerator, + disableIdGeneration + }); + const getFieldAttributes = ({ model, field }) => { + const defaultModelName = getDefaultModelName(model); + const defaultFieldName = getDefaultFieldName({ + field, + model: defaultModelName + }); + const fields = schema3[defaultModelName].fields; + fields.id = idField({ customModelName: defaultModelName }); + const fieldAttributes = fields[defaultFieldName]; + if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`); + return fieldAttributes; + }; + return getFieldAttributes; + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs +var initGetFieldName; +var init_get_field_name = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs"() { + init_get_default_model_name(); + init_get_default_field_name(); + initGetFieldName = ({ schema: schema3, usePlural }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema: schema3, + usePlural + }); + const getDefaultFieldName = initGetDefaultFieldName({ + schema: schema3, + usePlural + }); + function getFieldName({ model: modelName, field: fieldName }) { + const model = getDefaultModelName(modelName); + const field = getDefaultFieldName({ + model, + field: fieldName + }); + return schema3[model]?.fields[field]?.fieldName || field; + } + return getFieldName; + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs +var initGetModelName; +var init_get_model_name = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs"() { + init_get_default_model_name(); + initGetModelName = ({ usePlural, schema: schema3 }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema: schema3, + usePlural + }); + const getModelName = (model) => { + const defaultModelKey = getDefaultModelName(model); + if (schema3 && schema3[defaultModelKey] && schema3[defaultModelKey].modelName !== model) return usePlural ? `${schema3[defaultModelKey].modelName}s` : schema3[defaultModelKey].modelName; + return usePlural ? `${model}s` : model; + }; + return getModelName; + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/utils.mjs +function withApplyDefault(value, field, action) { + if (action === "update") { + if (value === void 0 && field.onUpdate !== void 0) { + if (typeof field.onUpdate === "function") return field.onUpdate(); + return field.onUpdate; + } + return value; + } + if (action === "create") { + if (value === void 0 || field.required === true && value === null) { + if (field.defaultValue !== void 0) { + if (typeof field.defaultValue === "function") return field.defaultValue(); + return field.defaultValue; + } + } + } + return value; +} +var init_utils = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/utils.mjs"() { + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/factory.mjs +function formatTransactionId(transactionId2) { + if (getColorDepth() < 8) return `#${transactionId2}`; + return `${TTY_COLORS.fg.magenta}#${transactionId2}${TTY_COLORS.reset}`; +} +function formatStep(step, total) { + return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`; +} +function formatMethod(method) { + return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`; +} +function formatAction(action) { + return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`; +} +var debugLogs, transactionId, createAsIsTransaction, createAdapterFactory; +var init_factory = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/factory.mjs"() { + init_get_tables(); + init_color_depth(); + init_logger(); + init_error2(); + init_attributes(); + init_tracer(); + init_json(); + init_get_default_model_name(); + init_get_default_field_name(); + init_get_id_field(); + init_get_field_attributes(); + init_get_field_name(); + init_get_model_name(); + init_utils(); + debugLogs = []; + transactionId = -1; + createAsIsTransaction = (adapter) => (fn) => fn(adapter); + createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => { + const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15); + const config4 = { + ...cfg, + supportsBooleans: cfg.supportsBooleans ?? true, + supportsDates: cfg.supportsDates ?? true, + supportsJSON: cfg.supportsJSON ?? false, + adapterName: cfg.adapterName ?? cfg.adapterId, + supportsNumericIds: cfg.supportsNumericIds ?? true, + supportsUUIDs: cfg.supportsUUIDs ?? false, + supportsArrays: cfg.supportsArrays ?? false, + transaction: cfg.transaction ?? false, + disableTransformInput: cfg.disableTransformInput ?? false, + disableTransformOutput: cfg.disableTransformOutput ?? false, + disableTransformJoin: cfg.disableTransformJoin ?? false + }; + if (options.advanced?.database?.generateId === "serial" && config4.supportsNumericIds === false) throw new BetterAuthError(`[${config4.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`); + const schema3 = getAuthTables(options); + const debugLog = (...args) => { + if (config4.debugLogs === true || typeof config4.debugLogs === "object") { + const logger3 = createLogger2({ level: "info" }); + if (typeof config4.debugLogs === "object" && "isRunningAdapterTests" in config4.debugLogs) { + if (config4.debugLogs.isRunningAdapterTests) { + args.shift(); + debugLogs.push({ + instance: uniqueAdapterFactoryInstanceId, + args + }); + } + return; + } + if (typeof config4.debugLogs === "object" && config4.debugLogs.logCondition && !config4.debugLogs.logCondition?.()) return; + if (typeof args[0] === "object" && "method" in args[0]) { + const method = args.shift().method; + if (typeof config4.debugLogs === "object") { + if (method === "create" && !config4.debugLogs.create) return; + else if (method === "update" && !config4.debugLogs.update) return; + else if (method === "updateMany" && !config4.debugLogs.updateMany) return; + else if (method === "findOne" && !config4.debugLogs.findOne) return; + else if (method === "findMany" && !config4.debugLogs.findMany) return; + else if (method === "delete" && !config4.debugLogs.delete) return; + else if (method === "deleteMany" && !config4.debugLogs.deleteMany) return; + else if (method === "count" && !config4.debugLogs.count) return; + } + logger3.info(`[${config4.adapterName}]`, ...args); + } else logger3.info(`[${config4.adapterName}]`, ...args); + } + }; + const logger2 = createLogger2(options.logger); + const getDefaultModelName = initGetDefaultModelName({ + usePlural: config4.usePlural, + schema: schema3 + }); + const getDefaultFieldName = initGetDefaultFieldName({ + usePlural: config4.usePlural, + schema: schema3 + }); + const getModelName = initGetModelName({ + usePlural: config4.usePlural, + schema: schema3 + }); + const getFieldName = initGetFieldName({ + schema: schema3, + usePlural: config4.usePlural + }); + const idField = initGetIdField({ + schema: schema3, + options, + usePlural: config4.usePlural, + disableIdGeneration: config4.disableIdGeneration, + customIdGenerator: config4.customIdGenerator, + supportsUUIDs: config4.supportsUUIDs + }); + const getFieldAttributes = initGetFieldAttributes({ + schema: schema3, + options, + usePlural: config4.usePlural, + disableIdGeneration: config4.disableIdGeneration, + customIdGenerator: config4.customIdGenerator + }); + const transformInput = async (data, defaultModelName, action, forceAllowId) => { + const transformedData = {}; + const fields = schema3[defaultModelName].fields; + const newMappedKeys = config4.mapKeysTransformInput ?? {}; + const useNumberId = options.advanced?.database?.generateId === "serial"; + fields.id = idField({ + customModelName: defaultModelName, + forceAllowId: forceAllowId && "id" in data + }); + for (const field in fields) { + let value = data[field]; + const fieldAttributes = fields[field]; + const newFieldName = newMappedKeys[field] || fields[field].fieldName || field; + if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue; + if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try { + value = new Date(value); + } catch { + logger2.error("[Adapter Factory] Failed to convert string to date", { + value, + field + }); + } + let newValue = withApplyDefault(value, fieldAttributes, action); + if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue); + if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null); + else newValue = newValue !== null ? Number(newValue) : null; + else if (config4.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue); + else if (config4.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue); + else if (config4.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString(); + else if (config4.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0; + if (config4.customTransformInput) newValue = config4.customTransformInput({ + data: newValue, + action, + field: newFieldName, + fieldAttributes, + model: getModelName(defaultModelName), + schema: schema3, + options + }); + if (newValue !== void 0) transformedData[newFieldName] = newValue; + } + return transformedData; + }; + const transformOutput = async (data, unsafe_model, select = [], join2) => { + const transformSingleOutput = async (data2, unsafe_model2, select2 = []) => { + if (!data2) return null; + const newMappedKeys = config4.mapKeysTransformOutput ?? {}; + const transformedData2 = {}; + const tableSchema = schema3[getDefaultModelName(unsafe_model2)].fields; + const idKey = Object.entries(newMappedKeys).find(([_, v]) => v === "id")?.[0]; + tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.generateId === "serial" ? "number" : "string" }; + for (const key in tableSchema) { + if (select2.length && !select2.includes(key)) continue; + const field = tableSchema[key]; + if (field) { + const originalKey = field.fieldName || key; + let newValue = data2[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey]; + if (field.transform?.output) newValue = await field.transform.output(newValue); + const newFieldName = newMappedKeys[key] || key; + if (originalKey === "id" || field.references?.field === "id") { + if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue); + } else if (config4.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue); + else if (config4.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue); + else if (config4.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue); + else if (config4.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1; + if (config4.customTransformOutput) newValue = config4.customTransformOutput({ + data: newValue, + field: newFieldName, + fieldAttributes: field, + select: select2, + model: getModelName(unsafe_model2), + schema: schema3, + options + }); + transformedData2[newFieldName] = newValue; + } + } + return transformedData2; + }; + if (!join2 || Object.keys(join2).length === 0) return await transformSingleOutput(data, unsafe_model, select); + unsafe_model = getDefaultModelName(unsafe_model); + const transformedData = await transformSingleOutput(data, unsafe_model, select); + const requiredModels = Object.entries(join2).map(([model, joinConfig]) => ({ + modelName: getModelName(model), + defaultModelName: getDefaultModelName(model), + joinConfig + })); + if (!data) return null; + for (const { modelName, defaultModelName, joinConfig } of requiredModels) { + let joinedData = await (async () => { + if (options.experimental?.joins) return data[modelName]; + else return await handleFallbackJoin({ + baseModel: unsafe_model, + baseData: transformedData, + joinModel: modelName, + specificJoinConfig: joinConfig + }); + })(); + if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : []; + if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData]; + const transformed = []; + if (Array.isArray(joinedData)) for (const item of joinedData) { + const transformedItem = await transformSingleOutput(item, modelName, []); + transformed.push(transformedItem); + } + else { + const transformedItem = await transformSingleOutput(joinedData, modelName, []); + transformed.push(transformedItem); + } + transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null; + } + return transformedData; + }; + const transformWhereClause = ({ model, where, action }) => { + if (!where) return void 0; + const newMappedKeys = config4.mapKeysTransformInput ?? {}; + return where.map((w) => { + const { field: unsafe_field, value, operator = "eq", connector = "AND", mode = "sensitive" } = w; + if (operator === "in") { + if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array"); + } + let newValue = value; + const defaultModelName = getDefaultModelName(model); + const defaultFieldName = getDefaultFieldName({ + field: unsafe_field, + model + }); + const fieldName = newMappedKeys[defaultFieldName] || getFieldName({ + field: defaultFieldName, + model: defaultModelName + }); + const fieldAttr = getFieldAttributes({ + field: defaultFieldName, + model: defaultModelName + }); + const useNumberId = options.advanced?.database?.generateId === "serial"; + if (defaultFieldName === "id" || fieldAttr.references?.field === "id") { + if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number); + else newValue = Number(value); + } + if (fieldAttr.type === "date" && value instanceof Date && !config4.supportsDates) newValue = value.toISOString(); + if (fieldAttr.type === "boolean" && typeof newValue === "string") newValue = newValue === "true"; + if (fieldAttr.type === "number") { + if (typeof newValue === "string" && newValue.trim() !== "") { + const parsed = Number(newValue); + if (!Number.isNaN(parsed)) newValue = parsed; + } else if (Array.isArray(newValue)) { + const parsed = newValue.map((v) => typeof v === "string" && v.trim() !== "" ? Number(v) : NaN); + if (parsed.every((n) => !Number.isNaN(n))) newValue = parsed; + } + } + if (fieldAttr.type === "boolean" && typeof newValue === "boolean" && !config4.supportsBooleans) newValue = newValue ? 1 : 0; + if (fieldAttr.type === "json" && typeof value === "object" && !config4.supportsJSON) try { + newValue = JSON.stringify(value); + } catch (error49) { + throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error49 }); + } + if (config4.customTransformInput) newValue = config4.customTransformInput({ + data: newValue, + fieldAttributes: fieldAttr, + field: fieldName, + model: getModelName(model), + schema: schema3, + options, + action + }); + return { + operator, + connector, + field: fieldName, + value: newValue, + mode + }; + }); + }; + const transformJoinClause = (baseModel, unsanitizedJoin, select) => { + if (!unsanitizedJoin) return void 0; + if (Object.keys(unsanitizedJoin).length === 0) return void 0; + const transformedJoin = {}; + for (const [model, join2] of Object.entries(unsanitizedJoin)) { + if (!join2) continue; + const defaultModelName = getDefaultModelName(model); + const defaultBaseModelName = getDefaultModelName(baseModel); + let foreignKeys = Object.entries(schema3[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName); + let isForwardJoin = true; + if (!foreignKeys.length) { + foreignKeys = Object.entries(schema3[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName); + isForwardJoin = false; + } + if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`); + else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`); + const [foreignKey, foreignKeyAttributes] = foreignKeys[0]; + if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`); + let from; + let to; + let requiredSelectField; + if (isForwardJoin) { + requiredSelectField = foreignKeyAttributes.references.field; + from = getFieldName({ + model: baseModel, + field: requiredSelectField + }); + to = getFieldName({ + model, + field: foreignKey + }); + } else { + requiredSelectField = foreignKey; + from = getFieldName({ + model: baseModel, + field: requiredSelectField + }); + to = getFieldName({ + model, + field: foreignKeyAttributes.references.field + }); + } + if (select && !select.includes(requiredSelectField)) select.push(requiredSelectField); + const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false; + let limit = options.advanced?.database?.defaultFindManyLimit ?? 100; + if (isUnique) limit = 1; + else if (typeof join2 === "object" && typeof join2.limit === "number") limit = join2.limit; + transformedJoin[getModelName(model)] = { + on: { + from, + to + }, + limit, + relation: isUnique ? "one-to-one" : "one-to-many" + }; + } + return { + join: transformedJoin, + select + }; + }; + const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => { + if (!baseData) return baseData; + const modelName = getModelName(joinModel); + const field = joinConfig.on.to; + const value = baseData[getDefaultFieldName({ + field: joinConfig.on.from, + model: baseModel + })]; + if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : []; + let result; + const where = transformWhereClause({ + model: modelName, + where: [{ + field, + value, + operator: "eq", + connector: "AND" + }], + action: "findOne" + }); + try { + if (joinConfig.relation === "one-to-one") result = await withSpan(`db findOne ${modelName}`, { + [ATTR_DB_OPERATION_NAME]: "findOne", + [ATTR_DB_COLLECTION_NAME]: modelName + }, () => adapterInstance.findOne({ + model: modelName, + where + })); + else { + const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; + result = await withSpan(`db findMany ${modelName}`, { + [ATTR_DB_OPERATION_NAME]: "findMany", + [ATTR_DB_COLLECTION_NAME]: modelName + }, () => adapterInstance.findMany({ + model: modelName, + where, + limit + })); + } + } catch (error49) { + logger2.error(`Failed to query fallback join for model ${modelName}:`, { + where, + limit: joinConfig.limit + }); + console.error(error49); + throw error49; + } + return result; + }; + const adapterInstance = customAdapter({ + options, + schema: schema3, + debugLog, + getFieldName, + getModelName, + getDefaultModelName, + getDefaultFieldName, + getFieldAttributes, + transformInput, + transformOutput, + transformWhereClause + }); + let lazyLoadTransaction = null; + const adapter = { + transaction: async (cb) => { + if (!lazyLoadTransaction) if (!config4.transaction) lazyLoadTransaction = createAsIsTransaction(adapter); + else { + logger2.debug(`[${config4.adapterName}] - Using provided transaction implementation.`); + lazyLoadTransaction = config4.transaction; + } + return lazyLoadTransaction(cb); + }, + create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + unsafeModel = getDefaultModelName(unsafeModel); + if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) { + logger2.warn(`[${config4.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`); + const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "Create method with `id` being called at:"); + console.log(stack); + unsafeData.id = void 0; + } + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data = unsafeData; + if (!config4.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create", forceAllowId); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, { + model, + data + }); + const res = await withSpan(`db create ${model}`, { + [ATTR_DB_OPERATION_NAME]: "create", + [ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.create({ + data, + model + })); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, { + model, + res + }); + let transformed = res; + if (!config4.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; + }, + update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { + transactionId++; + const thisTransactionId = transactionId; + unsafeModel = getDefaultModelName(unsafeModel); + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "update" + }); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data = unsafeData; + if (!config4.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, { + model, + data + }); + const res = await withSpan(`db update ${model}`, { + [ATTR_DB_OPERATION_NAME]: "update", + [ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.update({ + model, + where, + update: data + })); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config4.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; + }, + updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "updateMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data = unsafeData; + if (!config4.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, { + model, + data + }); + const updatedCount = await withSpan(`db updateMany ${model}`, { + [ATTR_DB_OPERATION_NAME]: "updateMany", + [ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.updateMany({ + model, + where, + update: data + })); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, { + model, + data: updatedCount + }); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, { + model, + data: updatedCount + }); + return updatedCount; + }, + findOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "findOne" + }); + unsafeModel = getDefaultModelName(unsafeModel); + let join2; + let passJoinToAdapter = true; + if (!config4.disableTransformJoin) { + const result = transformJoinClause(unsafeModel, unsafeJoin, select); + if (result) { + join2 = result.join; + select = result.select; + } + if (!options.experimental?.joins && join2 && Object.keys(join2).length > 0) passJoinToAdapter = false; + } else join2 = unsafeJoin; + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, { + model, + where, + select, + join: join2 + }); + const res = await withSpan(`db findOne ${model}`, { + [ATTR_DB_OPERATION_NAME]: "findOne", + [ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.findOne({ + model, + where, + select, + join: passJoinToAdapter ? join2 : void 0 + })); + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config4.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join2); + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; + }, + findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, select, sortBy, offset, join: unsafeJoin }) => { + transactionId++; + const thisTransactionId = transactionId; + const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "findMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + let join2; + let passJoinToAdapter = true; + if (!config4.disableTransformJoin) { + const result = transformJoinClause(unsafeModel, unsafeJoin, select); + if (result) { + join2 = result.join; + select = result.select; + } + if (!options.experimental?.joins && join2 && Object.keys(join2).length > 0) passJoinToAdapter = false; + } else join2 = unsafeJoin; + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, { + model, + where, + limit, + sortBy, + offset, + join: join2 + }); + const res = await withSpan(`db findMany ${model}`, { + [ATTR_DB_OPERATION_NAME]: "findMany", + [ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.findMany({ + model, + where, + limit, + select, + sortBy, + offset, + join: passJoinToAdapter ? join2 : void 0 + })); + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config4.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => { + return await transformOutput(r, unsafeModel, void 0, join2); + })); + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; + }, + delete: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "delete" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, { + model, + where + }); + await withSpan(`db delete ${model}`, { + [ATTR_DB_OPERATION_NAME]: "delete", + [ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.delete({ + model, + where + })); + debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model }); + }, + deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "deleteMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, { + model, + where + }); + const res = await withSpan(`db deleteMany ${model}`, { + [ATTR_DB_OPERATION_NAME]: "deleteMany", + [ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.deleteMany({ + model, + where + })); + debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + return res; + }, + count: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "count" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, { + model, + where + }); + const res = await withSpan(`db count ${model}`, { + [ATTR_DB_OPERATION_NAME]: "count", + [ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.count({ + model, + where + })); + debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, { + model, + data: res + }); + return res; + }, + createSchema: adapterInstance.createSchema ? async (_, file2) => { + const tables = getAuthTables(options); + if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session; + return adapterInstance.createSchema({ + file: file2, + tables + }); + } : void 0, + options: { + adapterConfig: config4, + ...adapterInstance.options ?? {} + }, + id: config4.adapterId, + ...config4.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: { + resetDebugLogs() { + debugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId); + }, + printDebugLogs() { + const separator = `\u2500`.repeat(80); + const logs = debugLogs.filter((log2) => log2.instance === uniqueAdapterFactoryInstanceId); + if (logs.length === 0) return; + const log = logs.reverse().map((log2) => { + log2.args[0] = ` +${log2.args[0]}`; + return [...log2.args, "\n"]; + }).reduce((prev, curr) => { + return [...curr, ...prev]; + }, [` +${separator}`]); + console.log(...log); + } + } } : {} + }; + return adapter; + }; + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/index.mjs +var whereOperators; +var init_adapter = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/index.mjs"() { + init_get_field_name(); + init_get_model_name(); + init_factory(); + whereOperators = [ + "eq", + "ne", + "lt", + "lte", + "gt", + "gte", + "in", + "not_in", + "contains", + "starts_with", + "ends_with" + ]; + } +}); + +// ../../node_modules/.pnpm/@better-auth+memory-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_9b6e7edc5b5cf527f9fdae30e619266b/node_modules/@better-auth/memory-adapter/dist/index.mjs +var dist_exports = {}; +__export(dist_exports, { + memoryAdapter: () => memoryAdapter +}); +function insensitiveCompare(a, b) { + if (typeof a === "string" && typeof b === "string") return a.toLowerCase() === b.toLowerCase(); + return a === b; +} +function insensitiveIn(recordVal, values) { + if (typeof recordVal !== "string") return values.includes(recordVal); + return values.some((v) => typeof v === "string" && recordVal.toLowerCase() === v.toLowerCase()); +} +function insensitiveNotIn(recordVal, values) { + return !insensitiveIn(recordVal, values); +} +function insensitiveContains(recordVal, value) { + if (typeof recordVal !== "string" || typeof value !== "string") return false; + return recordVal.toLowerCase().includes(value.toLowerCase()); +} +function insensitiveStartsWith(recordVal, value) { + if (typeof recordVal !== "string" || typeof value !== "string") return false; + return recordVal.toLowerCase().startsWith(value.toLowerCase()); +} +function insensitiveEndsWith(recordVal, value) { + if (typeof recordVal !== "string" || typeof value !== "string") return false; + return recordVal.toLowerCase().endsWith(value.toLowerCase()); +} +var memoryAdapter; +var init_dist = __esm({ + "../../node_modules/.pnpm/@better-auth+memory-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_9b6e7edc5b5cf527f9fdae30e619266b/node_modules/@better-auth/memory-adapter/dist/index.mjs"() { + init_adapter(); + init_env(); + memoryAdapter = (db, config4) => { + let lazyOptions = null; + const adapterCreator = createAdapterFactory({ + config: { + adapterId: "memory", + adapterName: "Memory Adapter", + usePlural: false, + debugLogs: config4?.debugLogs || false, + supportsArrays: true, + customTransformInput(props) { + if (props.options.advanced?.database?.generateId === "serial" && props.field === "id" && props.action === "create") return db[props.model].length + 1; + return props.data; + }, + transaction: async (cb) => { + const clone2 = structuredClone(db); + try { + return await cb(adapterCreator(lazyOptions)); + } catch (error49) { + Object.keys(db).forEach((key) => { + db[key] = clone2[key]; + }); + throw error49; + } + } + }, + adapter: ({ getFieldName, getDefaultFieldName, options, getModelName }) => { + const applySortToRecords = (records, sortBy, model) => { + if (!sortBy) return records; + return records.sort((a, b) => { + const field = getFieldName({ + model, + field: sortBy.field + }); + const aValue = a[field]; + const bValue = b[field]; + let comparison = 0; + if (aValue == null && bValue == null) comparison = 0; + else if (aValue == null) comparison = -1; + else if (bValue == null) comparison = 1; + else if (typeof aValue === "string" && typeof bValue === "string") comparison = aValue.localeCompare(bValue); + else if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime(); + else if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue; + else if (typeof aValue === "boolean" && typeof bValue === "boolean") comparison = aValue === bValue ? 0 : aValue ? 1 : -1; + else comparison = String(aValue).localeCompare(String(bValue)); + return sortBy.direction === "asc" ? comparison : -comparison; + }); + }; + function convertWhereClause(where, model, join2, select) { + const baseRecords = (() => { + const table = db[model]; + if (!table) { + logger.error(`[MemoryAdapter] Model ${model} not found in the DB`, Object.keys(db)); + throw new Error(`Model ${model} not found`); + } + const evalClause = (record2, clause) => { + const { field, value, operator, mode = "sensitive" } = clause; + const isInsensitive = mode === "insensitive" && (typeof value === "string" || Array.isArray(value) && value.every((v) => typeof v === "string")); + switch (operator) { + case "in": + if (!Array.isArray(value)) throw new Error("Value must be an array"); + if (isInsensitive) return insensitiveIn(record2[field], value); + return value.includes(record2[field]); + case "not_in": + if (!Array.isArray(value)) throw new Error("Value must be an array"); + if (isInsensitive) return insensitiveNotIn(record2[field], value); + return !value.includes(record2[field]); + case "contains": + if (isInsensitive) return insensitiveContains(record2[field], value); + return record2[field]?.includes(value); + case "starts_with": + if (isInsensitive) return insensitiveStartsWith(record2[field], value); + return record2[field].startsWith(value); + case "ends_with": + if (isInsensitive) return insensitiveEndsWith(record2[field], value); + return record2[field].endsWith(value); + case "ne": + return isInsensitive ? !insensitiveCompare(record2[field], value) : record2[field] !== value; + case "gt": + return value != null && Boolean(record2[field] > value); + case "gte": + return value != null && Boolean(record2[field] >= value); + case "lt": + return value != null && Boolean(record2[field] < value); + case "lte": + return value != null && Boolean(record2[field] <= value); + default: + return isInsensitive ? insensitiveCompare(record2[field], value) : record2[field] === value; + } + }; + let records = table.filter((record2) => { + if (!where.length || where.length === 0) return true; + let result = evalClause(record2, where[0]); + for (const clause of where) { + const clauseResult = evalClause(record2, clause); + if (clause.connector === "OR") result = result || clauseResult; + else result = result && clauseResult; + } + return result; + }); + if (select?.length && select.length > 0) records = records.map((record2) => Object.fromEntries(Object.entries(record2).filter(([key]) => select.includes(getDefaultFieldName({ + model, + field: key + }))))); + return records; + })(); + if (!join2) return baseRecords; + const grouped = /* @__PURE__ */ new Map(); + const seenIds = /* @__PURE__ */ new Map(); + for (const baseRecord of baseRecords) { + const baseId = String(baseRecord.id); + if (!grouped.has(baseId)) { + const nested = { ...baseRecord }; + for (const [joinModel, joinAttr] of Object.entries(join2)) { + const joinModelName = getModelName(joinModel); + if (joinAttr.relation === "one-to-one") nested[joinModelName] = null; + else { + nested[joinModelName] = []; + seenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set()); + } + } + grouped.set(baseId, nested); + } + const nestedEntry = grouped.get(baseId); + for (const [joinModel, joinAttr] of Object.entries(join2)) { + const joinModelName = getModelName(joinModel); + const joinTable = db[joinModelName]; + if (!joinTable) { + logger.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db)); + throw new Error(`JoinOption model ${joinModelName} not found`); + } + const matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]); + if (joinAttr.relation === "one-to-one") nestedEntry[joinModelName] = matchingRecords[0] || null; + else { + const seenSet = seenIds.get(`${baseId}-${joinModel}`); + const limit = joinAttr.limit ?? 100; + let count = 0; + for (const matchingRecord of matchingRecords) { + if (count >= limit) break; + if (!seenSet.has(matchingRecord.id)) { + nestedEntry[joinModelName].push(matchingRecord); + seenSet.add(matchingRecord.id); + count++; + } + } + } + } + } + return Array.from(grouped.values()); + } + return { + create: async ({ model, data }) => { + if (options.advanced?.database?.generateId === "serial") data.id = db[getModelName(model)].length + 1; + if (!db[model]) db[model] = []; + db[model].push(data); + return data; + }, + findOne: async ({ model, where, select, join: join2 }) => { + const res = convertWhereClause(where, model, join2, select); + if (join2) { + const resArray = res; + if (!resArray.length) return null; + return resArray[0]; + } + return res[0] || null; + }, + findMany: async ({ model, where, sortBy, limit, select, offset, join: join2 }) => { + const res = convertWhereClause(where || [], model, join2, select); + if (join2) { + const resArray = res; + if (!resArray.length) return []; + applySortToRecords(resArray, sortBy, model); + let paginatedRecords = resArray; + if (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset); + if (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit); + return paginatedRecords; + } + let table = applySortToRecords(res, sortBy, model); + if (offset !== void 0) table = table.slice(offset); + if (limit !== void 0) table = table.slice(0, limit); + return table || []; + }, + count: async ({ model, where }) => { + if (where) return convertWhereClause(where, model).length; + return db[model].length; + }, + update: async ({ model, where, update }) => { + const res = convertWhereClause(where, model); + res.forEach((record2) => { + Object.assign(record2, update); + }); + return res[0] || null; + }, + delete: async ({ model, where }) => { + const table = db[model]; + const res = convertWhereClause(where, model); + db[model] = table.filter((record2) => !res.includes(record2)); + }, + deleteMany: async ({ model, where }) => { + const table = db[model]; + const res = convertWhereClause(where, model); + let count = 0; + db[model] = table.filter((record2) => { + if (res.includes(record2)) { + count++; + return false; + } + return !res.includes(record2); + }); + return count; + }, + updateMany({ model, where, update }) { + const res = convertWhereClause(where, model); + res.forEach((record2) => { + Object.assign(record2, update); + }); + return res[0] || null; + } + }; + } + }); + return (options) => { + lazyOptions = options; + return adapterCreator(options); + }; + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js +function isUndefined(obj) { + return typeof obj === "undefined" || obj === void 0; +} +function isString2(obj) { + return typeof obj === "string"; +} +function isNumber2(obj) { + return typeof obj === "number"; +} +function isBoolean2(obj) { + return typeof obj === "boolean"; +} +function isNull(obj) { + return obj === null; +} +function isDate2(obj) { + return obj instanceof Date; +} +function isBigInt(obj) { + return typeof obj === "bigint"; +} +function isBuffer(obj) { + return typeof Buffer !== "undefined" && Buffer.isBuffer(obj); +} +function isFunction3(obj) { + return typeof obj === "function"; +} +function isObject4(obj) { + return typeof obj === "object" && obj !== null; +} +function freeze(obj) { + return Object.freeze(obj); +} +function asArray(arg) { + if (isReadonlyArray(arg)) { + return arg; + } else { + return [arg]; + } +} +function isReadonlyArray(arg) { + return Array.isArray(arg); +} +function noop(obj) { + return obj; +} +var init_object_utils = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js +var AlterTableNode; +var init_alter_table_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js"() { + init_object_utils(); + AlterTableNode = freeze({ + is(node) { + return node.kind === "AlterTableNode"; + }, + create(table) { + return freeze({ + kind: "AlterTableNode", + table + }); + }, + cloneWithTableProps(node, props) { + return freeze({ + ...node, + ...props + }); + }, + cloneWithColumnAlteration(node, columnAlteration) { + return freeze({ + ...node, + columnAlterations: node.columnAlterations ? [...node.columnAlterations, columnAlteration] : [columnAlteration] + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js +var IdentifierNode; +var init_identifier_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js"() { + init_object_utils(); + IdentifierNode = freeze({ + is(node) { + return node.kind === "IdentifierNode"; + }, + create(name) { + return freeze({ + kind: "IdentifierNode", + name + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js +var CreateIndexNode; +var init_create_index_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js"() { + init_object_utils(); + init_identifier_node(); + CreateIndexNode = freeze({ + is(node) { + return node.kind === "CreateIndexNode"; + }, + create(name) { + return freeze({ + kind: "CreateIndexNode", + name: IdentifierNode.create(name) + }); + }, + cloneWith(node, props) { + return freeze({ + ...node, + ...props + }); + }, + cloneWithColumns(node, columns) { + return freeze({ + ...node, + columns: [...node.columns || [], ...columns] + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js +var CreateSchemaNode; +var init_create_schema_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js"() { + init_object_utils(); + init_identifier_node(); + CreateSchemaNode = freeze({ + is(node) { + return node.kind === "CreateSchemaNode"; + }, + create(schema3, params) { + return freeze({ + kind: "CreateSchemaNode", + schema: IdentifierNode.create(schema3), + ...params + }); + }, + cloneWith(createSchema, params) { + return freeze({ + ...createSchema, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js +var ON_COMMIT_ACTIONS, CreateTableNode; +var init_create_table_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js"() { + init_object_utils(); + ON_COMMIT_ACTIONS = ["preserve rows", "delete rows", "drop"]; + CreateTableNode = freeze({ + is(node) { + return node.kind === "CreateTableNode"; + }, + create(table) { + return freeze({ + kind: "CreateTableNode", + table, + columns: freeze([]) + }); + }, + cloneWithColumn(createTable, column) { + return freeze({ + ...createTable, + columns: freeze([...createTable.columns, column]) + }); + }, + cloneWithConstraint(createTable, constraint) { + return freeze({ + ...createTable, + constraints: createTable.constraints ? freeze([...createTable.constraints, constraint]) : freeze([constraint]) + }); + }, + cloneWithFrontModifier(createTable, modifier) { + return freeze({ + ...createTable, + frontModifiers: createTable.frontModifiers ? freeze([...createTable.frontModifiers, modifier]) : freeze([modifier]) + }); + }, + cloneWithEndModifier(createTable, modifier) { + return freeze({ + ...createTable, + endModifiers: createTable.endModifiers ? freeze([...createTable.endModifiers, modifier]) : freeze([modifier]) + }); + }, + cloneWith(createTable, params) { + return freeze({ + ...createTable, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js +var SchemableIdentifierNode; +var init_schemable_identifier_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js"() { + init_object_utils(); + init_identifier_node(); + SchemableIdentifierNode = freeze({ + is(node) { + return node.kind === "SchemableIdentifierNode"; + }, + create(identifier) { + return freeze({ + kind: "SchemableIdentifierNode", + identifier: IdentifierNode.create(identifier) + }); + }, + createWithSchema(schema3, identifier) { + return freeze({ + kind: "SchemableIdentifierNode", + schema: IdentifierNode.create(schema3), + identifier: IdentifierNode.create(identifier) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js +var DropIndexNode; +var init_drop_index_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + DropIndexNode = freeze({ + is(node) { + return node.kind === "DropIndexNode"; + }, + create(name, params) { + return freeze({ + kind: "DropIndexNode", + name: SchemableIdentifierNode.create(name), + ...params + }); + }, + cloneWith(dropIndex, props) { + return freeze({ + ...dropIndex, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js +var DropSchemaNode; +var init_drop_schema_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js"() { + init_object_utils(); + init_identifier_node(); + DropSchemaNode = freeze({ + is(node) { + return node.kind === "DropSchemaNode"; + }, + create(schema3, params) { + return freeze({ + kind: "DropSchemaNode", + schema: IdentifierNode.create(schema3), + ...params + }); + }, + cloneWith(dropSchema, params) { + return freeze({ + ...dropSchema, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js +var DropTableNode; +var init_drop_table_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js"() { + init_object_utils(); + DropTableNode = freeze({ + is(node) { + return node.kind === "DropTableNode"; + }, + create(table, params) { + return freeze({ + kind: "DropTableNode", + table, + ...params + }); + }, + cloneWith(dropIndex, params) { + return freeze({ + ...dropIndex, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js +var AliasNode; +var init_alias_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js"() { + init_object_utils(); + AliasNode = freeze({ + is(node) { + return node.kind === "AliasNode"; + }, + create(node, alias) { + return freeze({ + kind: "AliasNode", + node, + alias + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js +var TableNode; +var init_table_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + TableNode = freeze({ + is(node) { + return node.kind === "TableNode"; + }, + create(table) { + return freeze({ + kind: "TableNode", + table: SchemableIdentifierNode.create(table) + }); + }, + createWithSchema(schema3, table) { + return freeze({ + kind: "TableNode", + table: SchemableIdentifierNode.createWithSchema(schema3, table) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js +function isOperationNodeSource(obj) { + return isObject4(obj) && isFunction3(obj.toOperationNode); +} +var init_operation_node_source = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js"() { + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js +function isExpression(obj) { + return isObject4(obj) && "expressionType" in obj && isOperationNodeSource(obj); +} +function isAliasedExpression(obj) { + return isObject4(obj) && "expression" in obj && isString2(obj.alias) && isOperationNodeSource(obj); +} +var init_expression = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js"() { + init_operation_node_source(); + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js +var SelectModifierNode; +var init_select_modifier_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js"() { + init_object_utils(); + SelectModifierNode = freeze({ + is(node) { + return node.kind === "SelectModifierNode"; + }, + create(modifier, of) { + return freeze({ + kind: "SelectModifierNode", + modifier, + of + }); + }, + createWithExpression(modifier) { + return freeze({ + kind: "SelectModifierNode", + rawModifier: modifier + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js +var AndNode; +var init_and_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js"() { + init_object_utils(); + AndNode = freeze({ + is(node) { + return node.kind === "AndNode"; + }, + create(left, right) { + return freeze({ + kind: "AndNode", + left, + right + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js +var OrNode; +var init_or_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js"() { + init_object_utils(); + OrNode = freeze({ + is(node) { + return node.kind === "OrNode"; + }, + create(left, right) { + return freeze({ + kind: "OrNode", + left, + right + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js +var OnNode; +var init_on_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js"() { + init_object_utils(); + init_and_node(); + init_or_node(); + OnNode = freeze({ + is(node) { + return node.kind === "OnNode"; + }, + create(filter) { + return freeze({ + kind: "OnNode", + on: filter + }); + }, + cloneWithOperation(onNode, operator, operation) { + return freeze({ + ...onNode, + on: operator === "And" ? AndNode.create(onNode.on, operation) : OrNode.create(onNode.on, operation) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js +var JoinNode; +var init_join_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js"() { + init_object_utils(); + init_on_node(); + JoinNode = freeze({ + is(node) { + return node.kind === "JoinNode"; + }, + create(joinType, table) { + return freeze({ + kind: "JoinNode", + joinType, + table, + on: void 0 + }); + }, + createWithOn(joinType, table, on) { + return freeze({ + kind: "JoinNode", + joinType, + table, + on: OnNode.create(on) + }); + }, + cloneWithOn(joinNode, operation) { + return freeze({ + ...joinNode, + on: joinNode.on ? OnNode.cloneWithOperation(joinNode.on, "And", operation) : OnNode.create(operation) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js +var BinaryOperationNode; +var init_binary_operation_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js"() { + init_object_utils(); + BinaryOperationNode = freeze({ + is(node) { + return node.kind === "BinaryOperationNode"; + }, + create(leftOperand, operator, rightOperand) { + return freeze({ + kind: "BinaryOperationNode", + leftOperand, + operator, + rightOperand + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js +function isJSONOperator(op) { + return isString2(op) && JSON_OPERATORS.includes(op); +} +var COMPARISON_OPERATORS, ARITHMETIC_OPERATORS, JSON_OPERATORS, BINARY_OPERATORS, UNARY_FILTER_OPERATORS, UNARY_OPERATORS, OPERATORS, OperatorNode; +var init_operator_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js"() { + init_object_utils(); + COMPARISON_OPERATORS = [ + "=", + "==", + "!=", + "<>", + ">", + ">=", + "<", + "<=", + "in", + "not in", + "is", + "is not", + "like", + "not like", + "match", + "ilike", + "not ilike", + "@>", + "<@", + "^@", + "&&", + "?", + "?&", + "?|", + "!<", + "!>", + "<=>", + "!~", + "~", + "~*", + "!~*", + "@@", + "@@@", + "!!", + "<->", + "regexp", + "is distinct from", + "is not distinct from" + ]; + ARITHMETIC_OPERATORS = [ + "+", + "-", + "*", + "/", + "%", + "^", + "&", + "|", + "#", + "<<", + ">>" + ]; + JSON_OPERATORS = ["->", "->>"]; + BINARY_OPERATORS = [ + ...COMPARISON_OPERATORS, + ...ARITHMETIC_OPERATORS, + "&&", + "||" + ]; + UNARY_FILTER_OPERATORS = ["exists", "not exists"]; + UNARY_OPERATORS = ["not", "-", ...UNARY_FILTER_OPERATORS]; + OPERATORS = [ + ...BINARY_OPERATORS, + ...JSON_OPERATORS, + ...UNARY_OPERATORS, + "between", + "between symmetric" + ]; + OperatorNode = freeze({ + is(node) { + return node.kind === "OperatorNode"; + }, + create(operator) { + return freeze({ + kind: "OperatorNode", + operator + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js +var ColumnNode; +var init_column_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js"() { + init_object_utils(); + init_identifier_node(); + ColumnNode = freeze({ + is(node) { + return node.kind === "ColumnNode"; + }, + create(column) { + return freeze({ + kind: "ColumnNode", + column: IdentifierNode.create(column) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js +var SelectAllNode; +var init_select_all_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js"() { + init_object_utils(); + SelectAllNode = freeze({ + is(node) { + return node.kind === "SelectAllNode"; + }, + create() { + return freeze({ + kind: "SelectAllNode" + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js +var ReferenceNode; +var init_reference_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js"() { + init_select_all_node(); + init_object_utils(); + ReferenceNode = freeze({ + is(node) { + return node.kind === "ReferenceNode"; + }, + create(column, table) { + return freeze({ + kind: "ReferenceNode", + table, + column + }); + }, + createSelectAll(table) { + return freeze({ + kind: "ReferenceNode", + table, + column: SelectAllNode.create() + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js +function isDynamicReferenceBuilder(obj) { + return isObject4(obj) && isOperationNodeSource(obj) && isString2(obj.dynamicReference); +} +var _dynamicReference, DynamicReferenceBuilder; +var init_dynamic_reference_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js"() { + init_operation_node_source(); + init_reference_parser(); + init_object_utils(); + DynamicReferenceBuilder = class { + constructor(reference) { + __privateAdd(this, _dynamicReference); + __privateSet(this, _dynamicReference, reference); + } + get dynamicReference() { + return __privateGet(this, _dynamicReference); + } + /** + * @private + * + * This needs to be here just so that the typings work. Without this + * the generated .d.ts file contains no reference to the type param R + * which causes this type to be equal to DynamicReferenceBuilder with + * any R. + */ + get refType() { + return void 0; + } + toOperationNode() { + return parseSimpleReferenceExpression(__privateGet(this, _dynamicReference)); + } + }; + _dynamicReference = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js +var OrderByItemNode; +var init_order_by_item_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js"() { + init_object_utils(); + OrderByItemNode = freeze({ + is(node) { + return node.kind === "OrderByItemNode"; + }, + create(orderBy, direction) { + return freeze({ + kind: "OrderByItemNode", + orderBy, + direction + }); + }, + cloneWith(node, props) { + return freeze({ + ...node, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js +var RawNode; +var init_raw_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js"() { + init_object_utils(); + RawNode = freeze({ + is(node) { + return node.kind === "RawNode"; + }, + create(sqlFragments, parameters) { + return freeze({ + kind: "RawNode", + sqlFragments: freeze(sqlFragments), + parameters: freeze(parameters) + }); + }, + createWithSql(sql2) { + return RawNode.create([sql2], []); + }, + createWithChild(child) { + return RawNode.create(["", ""], [child]); + }, + createWithChildren(children) { + return RawNode.create(new Array(children.length + 1).fill(""), children); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js +var CollateNode; +var init_collate_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js"() { + init_object_utils(); + init_identifier_node(); + CollateNode = freeze({ + is(node) { + return node.kind === "CollateNode"; + }, + create(collation) { + return freeze({ + kind: "CollateNode", + collation: IdentifierNode.create(collation) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js +var _props, _OrderByItemBuilder, OrderByItemBuilder; +var init_order_by_item_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js"() { + init_collate_node(); + init_order_by_item_node(); + init_raw_node(); + init_object_utils(); + _OrderByItemBuilder = class _OrderByItemBuilder { + constructor(props) { + __privateAdd(this, _props); + __privateSet(this, _props, freeze(props)); + } + /** + * Adds `desc` to the `order by` item. + * + * See {@link asc} for the opposite. + */ + desc() { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { + direction: RawNode.createWithSql("desc") + }) + }); + } + /** + * Adds `asc` to the `order by` item. + * + * See {@link desc} for the opposite. + */ + asc() { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { + direction: RawNode.createWithSql("asc") + }) + }); + } + /** + * Adds `nulls last` to the `order by` item. + * + * This is only supported by some dialects like PostgreSQL and SQLite. + * + * See {@link nullsFirst} for the opposite. + */ + nullsLast() { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { nulls: "last" }) + }); + } + /** + * Adds `nulls first` to the `order by` item. + * + * This is only supported by some dialects like PostgreSQL and SQLite. + * + * See {@link nullsLast} for the opposite. + */ + nullsFirst() { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { nulls: "first" }) + }); + } + /** + * Adds `collate ` to the `order by` item. + */ + collate(collation) { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { + collation: CollateNode.create(collation) + }) + }); + } + toOperationNode() { + return __privateGet(this, _props).node; + } + }; + _props = new WeakMap(); + OrderByItemBuilder = _OrderByItemBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js +function logOnce(message2) { + if (LOGGED_MESSAGES.has(message2)) { + return; + } + LOGGED_MESSAGES.add(message2); + console.log(message2); +} +var LOGGED_MESSAGES; +var init_log_once = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js"() { + LOGGED_MESSAGES = /* @__PURE__ */ new Set(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js +function isOrderByDirection(thing) { + return thing === "asc" || thing === "desc"; +} +function parseOrderBy(args) { + if (args.length === 2) { + return [parseOrderByItem(args[0], args[1])]; + } + if (args.length === 1) { + const [orderBy] = args; + if (Array.isArray(orderBy)) { + logOnce("orderBy(array) is deprecated, use multiple orderBy calls instead."); + return orderBy.map((item) => parseOrderByItem(item)); + } + return [parseOrderByItem(orderBy)]; + } + throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`); +} +function parseOrderByItem(expr, modifiers) { + const parsedRef = parseOrderByExpression(expr); + if (OrderByItemNode.is(parsedRef)) { + if (modifiers) { + throw new Error("Cannot specify direction twice!"); + } + return parsedRef; + } + return parseOrderByWithModifiers(parsedRef, modifiers); +} +function parseOrderByExpression(expr) { + if (isExpressionOrFactory(expr)) { + return parseExpression(expr); + } + if (isDynamicReferenceBuilder(expr)) { + return expr.toOperationNode(); + } + const [ref, direction] = expr.split(" "); + if (direction) { + logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."); + return parseOrderByWithModifiers(parseStringReference(ref), direction); + } + return parseStringReference(expr); +} +function parseOrderByWithModifiers(expr, modifiers) { + if (typeof modifiers === "string") { + if (!isOrderByDirection(modifiers)) { + throw new Error(`Invalid order by direction: ${modifiers}`); + } + return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers)); + } + if (isExpression(modifiers)) { + logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."); + return OrderByItemNode.create(expr, modifiers.toOperationNode()); + } + const node = OrderByItemNode.create(expr); + if (!modifiers) { + return node; + } + return modifiers(new OrderByItemBuilder({ node })).toOperationNode(); +} +var init_order_by_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js"() { + init_dynamic_reference_builder(); + init_expression(); + init_order_by_item_node(); + init_raw_node(); + init_order_by_item_builder(); + init_log_once(); + init_expression_parser(); + init_reference_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js +var JSONReferenceNode; +var init_json_reference_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js"() { + init_object_utils(); + JSONReferenceNode = freeze({ + is(node) { + return node.kind === "JSONReferenceNode"; + }, + create(reference, traversal) { + return freeze({ + kind: "JSONReferenceNode", + reference, + traversal + }); + }, + cloneWithTraversal(node, traversal) { + return freeze({ + ...node, + traversal + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js +var JSONOperatorChainNode; +var init_json_operator_chain_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js"() { + init_object_utils(); + JSONOperatorChainNode = freeze({ + is(node) { + return node.kind === "JSONOperatorChainNode"; + }, + create(operator) { + return freeze({ + kind: "JSONOperatorChainNode", + operator, + values: freeze([]) + }); + }, + cloneWithValue(node, value) { + return freeze({ + ...node, + values: freeze([...node.values, value]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js +var JSONPathNode; +var init_json_path_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js"() { + init_object_utils(); + JSONPathNode = freeze({ + is(node) { + return node.kind === "JSONPathNode"; + }, + create(inOperator) { + return freeze({ + kind: "JSONPathNode", + inOperator, + pathLegs: freeze([]) + }); + }, + cloneWithLeg(jsonPathNode, pathLeg) { + return freeze({ + ...jsonPathNode, + pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js +function parseSimpleReferenceExpression(exp) { + if (isString2(exp)) { + return parseStringReference(exp); + } + return exp.toOperationNode(); +} +function parseReferenceExpressionOrList(arg) { + if (isReadonlyArray(arg)) { + return arg.map((it) => parseReferenceExpression(it)); + } else { + return [parseReferenceExpression(arg)]; + } +} +function parseReferenceExpression(exp) { + if (isExpressionOrFactory(exp)) { + return parseExpression(exp); + } + return parseSimpleReferenceExpression(exp); +} +function parseJSONReference(ref, op) { + const referenceNode = parseStringReference(ref); + if (isJSONOperator(op)) { + return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op))); + } + const opWithoutLastChar = op.slice(0, -1); + if (isJSONOperator(opWithoutLastChar)) { + return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar))); + } + throw new Error(`Invalid JSON operator: ${op}`); +} +function parseStringReference(ref) { + const COLUMN_SEPARATOR = "."; + if (!ref.includes(COLUMN_SEPARATOR)) { + return ReferenceNode.create(ColumnNode.create(ref)); + } + const parts = ref.split(COLUMN_SEPARATOR).map(trim); + if (parts.length === 3) { + return parseStringReferenceWithTableAndSchema(parts); + } + if (parts.length === 2) { + return parseStringReferenceWithTable(parts); + } + throw new Error(`invalid column reference ${ref}`); +} +function parseAliasedStringReference(ref) { + const ALIAS_SEPARATOR = " as "; + if (ref.includes(ALIAS_SEPARATOR)) { + const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim); + return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias)); + } else { + return parseStringReference(ref); + } +} +function parseColumnName(column) { + return ColumnNode.create(column); +} +function parseOrderedColumnName(column) { + const ORDER_SEPARATOR = " "; + if (column.includes(ORDER_SEPARATOR)) { + const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim); + if (!isOrderByDirection(order)) { + throw new Error(`invalid order direction "${order}" next to "${columnName}"`); + } + return parseOrderBy([columnName, order])[0]; + } else { + return parseColumnName(column); + } +} +function parseStringReferenceWithTableAndSchema(parts) { + const [schema3, table, column] = parts; + return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema3, table)); +} +function parseStringReferenceWithTable(parts) { + const [table, column] = parts; + return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table)); +} +function trim(str) { + return str.trim(); +} +var init_reference_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js"() { + init_alias_node(); + init_column_node(); + init_reference_node(); + init_table_node(); + init_object_utils(); + init_expression_parser(); + init_identifier_node(); + init_order_by_parser(); + init_operator_node(); + init_json_reference_node(); + init_json_operator_chain_node(); + init_json_path_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js +var PrimitiveValueListNode; +var init_primitive_value_list_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js"() { + init_object_utils(); + PrimitiveValueListNode = freeze({ + is(node) { + return node.kind === "PrimitiveValueListNode"; + }, + create(values) { + return freeze({ + kind: "PrimitiveValueListNode", + values: freeze([...values]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js +var ValueListNode; +var init_value_list_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js"() { + init_object_utils(); + ValueListNode = freeze({ + is(node) { + return node.kind === "ValueListNode"; + }, + create(values) { + return freeze({ + kind: "ValueListNode", + values: freeze(values) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js +var ValueNode; +var init_value_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js"() { + init_object_utils(); + ValueNode = freeze({ + is(node) { + return node.kind === "ValueNode"; + }, + create(value) { + return freeze({ + kind: "ValueNode", + value + }); + }, + createImmediate(value) { + return freeze({ + kind: "ValueNode", + value, + immediate: true + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js +function parseValueExpressionOrList(arg) { + if (isReadonlyArray(arg)) { + return parseValueExpressionList(arg); + } + return parseValueExpression(arg); +} +function parseValueExpression(exp) { + if (isExpressionOrFactory(exp)) { + return parseExpression(exp); + } + return ValueNode.create(exp); +} +function isSafeImmediateValue(value) { + return isNumber2(value) || isBoolean2(value) || isNull(value); +} +function parseSafeImmediateValue(value) { + if (!isSafeImmediateValue(value)) { + throw new Error(`unsafe immediate value ${JSON.stringify(value)}`); + } + return ValueNode.createImmediate(value); +} +function parseValueExpressionList(arg) { + if (arg.some(isExpressionOrFactory)) { + return ValueListNode.create(arg.map((it) => parseValueExpression(it))); + } + return PrimitiveValueListNode.create(arg); +} +var init_value_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js"() { + init_primitive_value_list_node(); + init_value_list_node(); + init_value_node(); + init_object_utils(); + init_expression_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js +var ParensNode; +var init_parens_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js"() { + init_object_utils(); + ParensNode = freeze({ + is(node) { + return node.kind === "ParensNode"; + }, + create(node) { + return freeze({ + kind: "ParensNode", + node + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js +function parseValueBinaryOperationOrExpression(args) { + if (args.length === 3) { + return parseValueBinaryOperation(args[0], args[1], args[2]); + } else if (args.length === 1) { + return parseValueExpression(args[0]); + } + throw new Error(`invalid arguments: ${JSON.stringify(args)}`); +} +function parseValueBinaryOperation(left, operator, right) { + if (isIsOperator(operator) && needsIsOperator(right)) { + return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right)); + } + return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right)); +} +function parseReferentialBinaryOperation(left, operator, right) { + return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right)); +} +function parseFilterObject(obj, combinator) { + return parseFilterList(Object.entries(obj).filter(([, v]) => !isUndefined(v)).map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? "is" : "=", v)), combinator); +} +function parseFilterList(list, combinator, withParens = true) { + const combine = combinator === "and" ? AndNode.create : OrNode.create; + if (list.length === 0) { + return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create("="), ValueNode.createImmediate(combinator === "and" ? 1 : 0)); + } + let node = toOperationNode(list[0]); + for (let i = 1; i < list.length; ++i) { + node = combine(node, toOperationNode(list[i])); + } + if (list.length > 1 && withParens) { + return ParensNode.create(node); + } + return node; +} +function isIsOperator(operator) { + return operator === "is" || operator === "is not"; +} +function needsIsOperator(value) { + return isNull(value) || isBoolean2(value); +} +function parseOperator(operator) { + if (isString2(operator) && OPERATORS.includes(operator)) { + return OperatorNode.create(operator); + } + if (isOperationNodeSource(operator)) { + return operator.toOperationNode(); + } + throw new Error(`invalid operator ${JSON.stringify(operator)}`); +} +function toOperationNode(nodeOrSource) { + return isOperationNodeSource(nodeOrSource) ? nodeOrSource.toOperationNode() : nodeOrSource; +} +var init_binary_operation_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js"() { + init_binary_operation_node(); + init_object_utils(); + init_operation_node_source(); + init_operator_node(); + init_reference_parser(); + init_value_parser(); + init_value_node(); + init_and_node(); + init_parens_node(); + init_or_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js +var OrderByNode; +var init_order_by_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js"() { + init_object_utils(); + OrderByNode = freeze({ + is(node) { + return node.kind === "OrderByNode"; + }, + create(items) { + return freeze({ + kind: "OrderByNode", + items: freeze([...items]) + }); + }, + cloneWithItems(orderBy, items) { + return freeze({ + ...orderBy, + items: freeze([...orderBy.items, ...items]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js +var PartitionByNode; +var init_partition_by_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js"() { + init_object_utils(); + PartitionByNode = freeze({ + is(node) { + return node.kind === "PartitionByNode"; + }, + create(items) { + return freeze({ + kind: "PartitionByNode", + items: freeze(items) + }); + }, + cloneWithItems(partitionBy, items) { + return freeze({ + ...partitionBy, + items: freeze([...partitionBy.items, ...items]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js +var OverNode; +var init_over_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js"() { + init_object_utils(); + init_order_by_node(); + init_partition_by_node(); + OverNode = freeze({ + is(node) { + return node.kind === "OverNode"; + }, + create() { + return freeze({ + kind: "OverNode" + }); + }, + cloneWithOrderByItems(overNode, items) { + return freeze({ + ...overNode, + orderBy: overNode.orderBy ? OrderByNode.cloneWithItems(overNode.orderBy, items) : OrderByNode.create(items) + }); + }, + cloneWithPartitionByItems(overNode, items) { + return freeze({ + ...overNode, + partitionBy: overNode.partitionBy ? PartitionByNode.cloneWithItems(overNode.partitionBy, items) : PartitionByNode.create(items) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js +var FromNode; +var init_from_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js"() { + init_object_utils(); + FromNode = freeze({ + is(node) { + return node.kind === "FromNode"; + }, + create(froms) { + return freeze({ + kind: "FromNode", + froms: freeze(froms) + }); + }, + cloneWithFroms(from, froms) { + return freeze({ + ...from, + froms: freeze([...from.froms, ...froms]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js +var GroupByNode; +var init_group_by_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js"() { + init_object_utils(); + GroupByNode = freeze({ + is(node) { + return node.kind === "GroupByNode"; + }, + create(items) { + return freeze({ + kind: "GroupByNode", + items: freeze(items) + }); + }, + cloneWithItems(groupBy2, items) { + return freeze({ + ...groupBy2, + items: freeze([...groupBy2.items, ...items]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js +var HavingNode; +var init_having_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js"() { + init_object_utils(); + init_and_node(); + init_or_node(); + HavingNode = freeze({ + is(node) { + return node.kind === "HavingNode"; + }, + create(filter) { + return freeze({ + kind: "HavingNode", + having: filter + }); + }, + cloneWithOperation(havingNode, operator, operation) { + return freeze({ + ...havingNode, + having: operator === "And" ? AndNode.create(havingNode.having, operation) : OrNode.create(havingNode.having, operation) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js +var InsertQueryNode; +var init_insert_query_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js"() { + init_object_utils(); + InsertQueryNode = freeze({ + is(node) { + return node.kind === "InsertQueryNode"; + }, + create(into, withNode, replace) { + return freeze({ + kind: "InsertQueryNode", + into, + ...withNode && { with: withNode }, + replace + }); + }, + createWithoutInto() { + return freeze({ + kind: "InsertQueryNode" + }); + }, + cloneWith(insertQuery, props) { + return freeze({ + ...insertQuery, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js +var ListNode; +var init_list_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js"() { + init_object_utils(); + ListNode = freeze({ + is(node) { + return node.kind === "ListNode"; + }, + create(items) { + return freeze({ + kind: "ListNode", + items: freeze(items) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js +var UpdateQueryNode; +var init_update_query_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js"() { + init_object_utils(); + init_from_node(); + init_list_node(); + UpdateQueryNode = freeze({ + is(node) { + return node.kind === "UpdateQueryNode"; + }, + create(tables, withNode) { + return freeze({ + kind: "UpdateQueryNode", + // For backwards compatibility, use the raw table node when there's only one table + // and don't rename the property to something like `tables`. + table: tables.length === 1 ? tables[0] : ListNode.create(tables), + ...withNode && { with: withNode } + }); + }, + createWithoutTable() { + return freeze({ + kind: "UpdateQueryNode" + }); + }, + cloneWithFromItems(updateQuery, fromItems) { + return freeze({ + ...updateQuery, + from: updateQuery.from ? FromNode.cloneWithFroms(updateQuery.from, fromItems) : FromNode.create(fromItems) + }); + }, + cloneWithUpdates(updateQuery, updates) { + return freeze({ + ...updateQuery, + updates: updateQuery.updates ? freeze([...updateQuery.updates, ...updates]) : updates + }); + }, + cloneWithLimit(updateQuery, limit) { + return freeze({ + ...updateQuery, + limit + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js +var UsingNode; +var init_using_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js"() { + init_object_utils(); + UsingNode = freeze({ + is(node) { + return node.kind === "UsingNode"; + }, + create(tables) { + return freeze({ + kind: "UsingNode", + tables: freeze(tables) + }); + }, + cloneWithTables(using, tables) { + return freeze({ + ...using, + tables: freeze([...using.tables, ...tables]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js +var DeleteQueryNode; +var init_delete_query_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js"() { + init_object_utils(); + init_from_node(); + init_using_node(); + init_query_node(); + DeleteQueryNode = freeze({ + is(node) { + return node.kind === "DeleteQueryNode"; + }, + create(fromItems, withNode) { + return freeze({ + kind: "DeleteQueryNode", + from: FromNode.create(fromItems), + ...withNode && { with: withNode } + }); + }, + // TODO: remove in v0.29 + /** + * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. + */ + cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items), + // TODO: remove in v0.29 + /** + * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. + */ + cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node), + cloneWithLimit(deleteNode, limit) { + return freeze({ + ...deleteNode, + limit + }); + }, + cloneWithoutLimit(deleteNode) { + return freeze({ + ...deleteNode, + limit: void 0 + }); + }, + cloneWithUsing(deleteNode, tables) { + return freeze({ + ...deleteNode, + using: deleteNode.using !== void 0 ? UsingNode.cloneWithTables(deleteNode.using, tables) : UsingNode.create(tables) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js +var WhereNode; +var init_where_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js"() { + init_object_utils(); + init_and_node(); + init_or_node(); + WhereNode = freeze({ + is(node) { + return node.kind === "WhereNode"; + }, + create(filter) { + return freeze({ + kind: "WhereNode", + where: filter + }); + }, + cloneWithOperation(whereNode, operator, operation) { + return freeze({ + ...whereNode, + where: operator === "And" ? AndNode.create(whereNode.where, operation) : OrNode.create(whereNode.where, operation) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js +var ReturningNode; +var init_returning_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js"() { + init_object_utils(); + ReturningNode = freeze({ + is(node) { + return node.kind === "ReturningNode"; + }, + create(selections) { + return freeze({ + kind: "ReturningNode", + selections: freeze(selections) + }); + }, + cloneWithSelections(returning, selections) { + return freeze({ + ...returning, + selections: returning.selections ? freeze([...returning.selections, ...selections]) : freeze(selections) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js +var ExplainNode; +var init_explain_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js"() { + init_object_utils(); + ExplainNode = freeze({ + is(node) { + return node.kind === "ExplainNode"; + }, + create(format, options) { + return freeze({ + kind: "ExplainNode", + format, + options + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js +var WhenNode; +var init_when_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js"() { + init_object_utils(); + WhenNode = freeze({ + is(node) { + return node.kind === "WhenNode"; + }, + create(condition) { + return freeze({ + kind: "WhenNode", + condition + }); + }, + cloneWithResult(whenNode, result) { + return freeze({ + ...whenNode, + result + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js +var MergeQueryNode; +var init_merge_query_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js"() { + init_object_utils(); + init_when_node(); + MergeQueryNode = freeze({ + is(node) { + return node.kind === "MergeQueryNode"; + }, + create(into, withNode) { + return freeze({ + kind: "MergeQueryNode", + into, + ...withNode && { with: withNode } + }); + }, + cloneWithUsing(mergeNode, using) { + return freeze({ + ...mergeNode, + using + }); + }, + cloneWithWhen(mergeNode, when) { + return freeze({ + ...mergeNode, + whens: mergeNode.whens ? freeze([...mergeNode.whens, when]) : freeze([when]) + }); + }, + cloneWithThen(mergeNode, then) { + return freeze({ + ...mergeNode, + whens: mergeNode.whens ? freeze([ + ...mergeNode.whens.slice(0, -1), + WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then) + ]) : void 0 + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js +var OutputNode; +var init_output_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js"() { + init_object_utils(); + OutputNode = freeze({ + is(node) { + return node.kind === "OutputNode"; + }, + create(selections) { + return freeze({ + kind: "OutputNode", + selections: freeze(selections) + }); + }, + cloneWithSelections(output, selections) { + return freeze({ + ...output, + selections: output.selections ? freeze([...output.selections, ...selections]) : freeze(selections) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js +var QueryNode; +var init_query_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js"() { + init_insert_query_node(); + init_select_query_node(); + init_update_query_node(); + init_delete_query_node(); + init_where_node(); + init_object_utils(); + init_returning_node(); + init_explain_node(); + init_merge_query_node(); + init_output_node(); + init_order_by_node(); + QueryNode = freeze({ + is(node) { + return SelectQueryNode.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node) || MergeQueryNode.is(node); + }, + cloneWithEndModifier(node, modifier) { + return freeze({ + ...node, + endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : freeze([modifier]) + }); + }, + cloneWithWhere(node, operation) { + return freeze({ + ...node, + where: node.where ? WhereNode.cloneWithOperation(node.where, "And", operation) : WhereNode.create(operation) + }); + }, + cloneWithJoin(node, join2) { + return freeze({ + ...node, + joins: node.joins ? freeze([...node.joins, join2]) : freeze([join2]) + }); + }, + cloneWithReturning(node, selections) { + return freeze({ + ...node, + returning: node.returning ? ReturningNode.cloneWithSelections(node.returning, selections) : ReturningNode.create(selections) + }); + }, + cloneWithoutReturning(node) { + return freeze({ + ...node, + returning: void 0 + }); + }, + cloneWithoutWhere(node) { + return freeze({ + ...node, + where: void 0 + }); + }, + cloneWithExplain(node, format, options) { + return freeze({ + ...node, + explain: ExplainNode.create(format, options?.toOperationNode()) + }); + }, + cloneWithTop(node, top) { + return freeze({ + ...node, + top + }); + }, + cloneWithOutput(node, selections) { + return freeze({ + ...node, + output: node.output ? OutputNode.cloneWithSelections(node.output, selections) : OutputNode.create(selections) + }); + }, + cloneWithOrderByItems(node, items) { + return freeze({ + ...node, + orderBy: node.orderBy ? OrderByNode.cloneWithItems(node.orderBy, items) : OrderByNode.create(items) + }); + }, + cloneWithoutOrderBy(node) { + return freeze({ + ...node, + orderBy: void 0 + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js +var SelectQueryNode; +var init_select_query_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js"() { + init_object_utils(); + init_from_node(); + init_group_by_node(); + init_having_node(); + init_query_node(); + SelectQueryNode = freeze({ + is(node) { + return node.kind === "SelectQueryNode"; + }, + create(withNode) { + return freeze({ + kind: "SelectQueryNode", + ...withNode && { with: withNode } + }); + }, + createFrom(fromItems, withNode) { + return freeze({ + kind: "SelectQueryNode", + from: FromNode.create(fromItems), + ...withNode && { with: withNode } + }); + }, + cloneWithSelections(select, selections) { + return freeze({ + ...select, + selections: select.selections ? freeze([...select.selections, ...selections]) : freeze(selections) + }); + }, + cloneWithDistinctOn(select, expressions) { + return freeze({ + ...select, + distinctOn: select.distinctOn ? freeze([...select.distinctOn, ...expressions]) : freeze(expressions) + }); + }, + cloneWithFrontModifier(select, modifier) { + return freeze({ + ...select, + frontModifiers: select.frontModifiers ? freeze([...select.frontModifiers, modifier]) : freeze([modifier]) + }); + }, + // TODO: remove in v0.29 + /** + * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. + */ + cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items), + cloneWithGroupByItems(selectNode, items) { + return freeze({ + ...selectNode, + groupBy: selectNode.groupBy ? GroupByNode.cloneWithItems(selectNode.groupBy, items) : GroupByNode.create(items) + }); + }, + cloneWithLimit(selectNode, limit) { + return freeze({ + ...selectNode, + limit + }); + }, + cloneWithOffset(selectNode, offset) { + return freeze({ + ...selectNode, + offset + }); + }, + cloneWithFetch(selectNode, fetch2) { + return freeze({ + ...selectNode, + fetch: fetch2 + }); + }, + cloneWithHaving(selectNode, operation) { + return freeze({ + ...selectNode, + having: selectNode.having ? HavingNode.cloneWithOperation(selectNode.having, "And", operation) : HavingNode.create(operation) + }); + }, + cloneWithSetOperations(selectNode, setOperations) { + return freeze({ + ...selectNode, + setOperations: selectNode.setOperations ? freeze([...selectNode.setOperations, ...setOperations]) : freeze([...setOperations]) + }); + }, + cloneWithoutSelections(select) { + return freeze({ + ...select, + selections: [] + }); + }, + cloneWithoutLimit(select) { + return freeze({ + ...select, + limit: void 0 + }); + }, + cloneWithoutOffset(select) { + return freeze({ + ...select, + offset: void 0 + }); + }, + // TODO: remove in v0.29 + /** + * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. + */ + cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node), + cloneWithoutGroupBy(select) { + return freeze({ + ...select, + groupBy: void 0 + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js +var _props2, _JoinBuilder, JoinBuilder; +var init_join_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js"() { + init_join_node(); + init_raw_node(); + init_binary_operation_parser(); + init_object_utils(); + _JoinBuilder = class _JoinBuilder { + constructor(props) { + __privateAdd(this, _props2); + __privateSet(this, _props2, freeze(props)); + } + on(...args) { + return new _JoinBuilder({ + ...__privateGet(this, _props2), + joinNode: JoinNode.cloneWithOn(__privateGet(this, _props2).joinNode, parseValueBinaryOperationOrExpression(args)) + }); + } + /** + * Just like {@link WhereInterface.whereRef} but adds an item to the join's + * `on` clause instead. + * + * See {@link WhereInterface.whereRef} for documentation and examples. + */ + onRef(lhs, op, rhs) { + return new _JoinBuilder({ + ...__privateGet(this, _props2), + joinNode: JoinNode.cloneWithOn(__privateGet(this, _props2).joinNode, parseReferentialBinaryOperation(lhs, op, rhs)) + }); + } + /** + * Adds `on true`. + */ + onTrue() { + return new _JoinBuilder({ + ...__privateGet(this, _props2), + joinNode: JoinNode.cloneWithOn(__privateGet(this, _props2).joinNode, RawNode.createWithSql("true")) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props2).joinNode; + } + }; + _props2 = new WeakMap(); + JoinBuilder = _JoinBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js +var PartitionByItemNode; +var init_partition_by_item_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js"() { + init_object_utils(); + PartitionByItemNode = freeze({ + is(node) { + return node.kind === "PartitionByItemNode"; + }, + create(partitionBy) { + return freeze({ + kind: "PartitionByItemNode", + partitionBy + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js +function parsePartitionBy(partitionBy) { + return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create); +} +var init_partition_by_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js"() { + init_partition_by_item_node(); + init_reference_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js +var _props3, _OverBuilder, OverBuilder; +var init_over_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js"() { + init_over_node(); + init_query_node(); + init_order_by_parser(); + init_partition_by_parser(); + init_object_utils(); + _OverBuilder = class _OverBuilder { + constructor(props) { + __privateAdd(this, _props3); + __privateSet(this, _props3, freeze(props)); + } + orderBy(...args) { + return new _OverBuilder({ + overNode: OverNode.cloneWithOrderByItems(__privateGet(this, _props3).overNode, parseOrderBy(args)) + }); + } + clearOrderBy() { + return new _OverBuilder({ + overNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props3).overNode) + }); + } + partitionBy(partitionBy) { + return new _OverBuilder({ + overNode: OverNode.cloneWithPartitionByItems(__privateGet(this, _props3).overNode, parsePartitionBy(partitionBy)) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props3).overNode; + } + }; + _props3 = new WeakMap(); + OverBuilder = _OverBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js +var SelectionNode; +var init_selection_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js"() { + init_object_utils(); + init_reference_node(); + init_select_all_node(); + SelectionNode = freeze({ + is(node) { + return node.kind === "SelectionNode"; + }, + create(selection) { + return freeze({ + kind: "SelectionNode", + selection + }); + }, + createSelectAll() { + return freeze({ + kind: "SelectionNode", + selection: SelectAllNode.create() + }); + }, + createSelectAllFromTable(table) { + return freeze({ + kind: "SelectionNode", + selection: ReferenceNode.createSelectAll(table) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js +function parseSelectArg(selection) { + if (isFunction3(selection)) { + return parseSelectArg(selection(expressionBuilder())); + } else if (isReadonlyArray(selection)) { + return selection.map((it) => parseSelectExpression(it)); + } else { + return [parseSelectExpression(selection)]; + } +} +function parseSelectExpression(selection) { + if (isString2(selection)) { + return SelectionNode.create(parseAliasedStringReference(selection)); + } else if (isDynamicReferenceBuilder(selection)) { + return SelectionNode.create(selection.toOperationNode()); + } else { + return SelectionNode.create(parseAliasedExpression(selection)); + } +} +function parseSelectAll(table) { + if (!table) { + return [SelectionNode.createSelectAll()]; + } else if (Array.isArray(table)) { + return table.map(parseSelectAllArg); + } else { + return [parseSelectAllArg(table)]; + } +} +function parseSelectAllArg(table) { + if (isString2(table)) { + return SelectionNode.createSelectAllFromTable(parseTable(table)); + } + throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`); +} +var init_select_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js"() { + init_object_utils(); + init_selection_node(); + init_reference_parser(); + init_dynamic_reference_builder(); + init_expression_parser(); + init_table_parser(); + init_expression_builder(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js +var ValuesNode; +var init_values_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js"() { + init_object_utils(); + ValuesNode = freeze({ + is(node) { + return node.kind === "ValuesNode"; + }, + create(values) { + return freeze({ + kind: "ValuesNode", + values: freeze(values) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js +var DefaultInsertValueNode; +var init_default_insert_value_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js"() { + init_object_utils(); + DefaultInsertValueNode = freeze({ + is(node) { + return node.kind === "DefaultInsertValueNode"; + }, + create() { + return freeze({ + kind: "DefaultInsertValueNode" + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js +function parseInsertExpression(arg) { + const objectOrList = isFunction3(arg) ? arg(expressionBuilder()) : arg; + const list = isReadonlyArray(objectOrList) ? objectOrList : freeze([objectOrList]); + return parseInsertColumnsAndValues(list); +} +function parseInsertColumnsAndValues(rows) { + const columns = parseColumnNamesAndIndexes(rows); + return [ + freeze([...columns.keys()].map(ColumnNode.create)), + ValuesNode.create(rows.map((row) => parseRowValues(row, columns))) + ]; +} +function parseColumnNamesAndIndexes(rows) { + const columns = /* @__PURE__ */ new Map(); + for (const row of rows) { + const cols = Object.keys(row); + for (const col of cols) { + if (!columns.has(col) && row[col] !== void 0) { + columns.set(col, columns.size); + } + } + } + return columns; +} +function parseRowValues(row, columns) { + const rowColumns = Object.keys(row); + const rowValues = Array.from({ + length: columns.size + }); + let hasUndefinedOrComplexColumns = false; + let indexedRowColumns = rowColumns.length; + for (const col of rowColumns) { + const columnIdx = columns.get(col); + if (isUndefined(columnIdx)) { + indexedRowColumns--; + continue; + } + const value = row[col]; + if (isUndefined(value) || isExpressionOrFactory(value)) { + hasUndefinedOrComplexColumns = true; + } + rowValues[columnIdx] = value; + } + const hasMissingColumns = indexedRowColumns < columns.size; + if (hasMissingColumns || hasUndefinedOrComplexColumns) { + const defaultValue = DefaultInsertValueNode.create(); + return ValueListNode.create(rowValues.map((it) => isUndefined(it) ? defaultValue : parseValueExpression(it))); + } + return PrimitiveValueListNode.create(rowValues); +} +var init_insert_values_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js"() { + init_column_node(); + init_primitive_value_list_node(); + init_value_list_node(); + init_object_utils(); + init_value_parser(); + init_values_node(); + init_expression_parser(); + init_default_insert_value_node(); + init_expression_builder(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js +var ColumnUpdateNode; +var init_column_update_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js"() { + init_object_utils(); + ColumnUpdateNode = freeze({ + is(node) { + return node.kind === "ColumnUpdateNode"; + }, + create(column, value) { + return freeze({ + kind: "ColumnUpdateNode", + column, + value + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js +function parseUpdate(...args) { + if (args.length === 2) { + return [ + ColumnUpdateNode.create(parseReferenceExpression(args[0]), parseValueExpression(args[1])) + ]; + } + return parseUpdateObjectExpression(args[0]); +} +function parseUpdateObjectExpression(update) { + const updateObj = isFunction3(update) ? update(expressionBuilder()) : update; + return Object.entries(updateObj).filter(([_, value]) => value !== void 0).map(([key, value]) => { + return ColumnUpdateNode.create(ColumnNode.create(key), parseValueExpression(value)); + }); +} +var init_update_set_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js"() { + init_column_node(); + init_column_update_node(); + init_expression_builder(); + init_object_utils(); + init_value_parser(); + init_reference_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js +var OnDuplicateKeyNode; +var init_on_duplicate_key_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js"() { + init_object_utils(); + OnDuplicateKeyNode = freeze({ + is(node) { + return node.kind === "OnDuplicateKeyNode"; + }, + create(updates) { + return freeze({ + kind: "OnDuplicateKeyNode", + updates + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js +var InsertResult; +var init_insert_result = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js"() { + InsertResult = class { + constructor(insertId, numInsertedOrUpdatedRows) { + /** + * The auto incrementing primary key of the inserted row. + * + * This property can be undefined when the query contains an `on conflict` + * clause that makes the query succeed even when nothing gets inserted. + * + * This property is always undefined on dialects like PostgreSQL that + * don't return the inserted id by default. On those dialects you need + * to use the {@link ReturningInterface.returning | returning} method. + */ + __publicField(this, "insertId"); + /** + * Affected rows count. + */ + __publicField(this, "numInsertedOrUpdatedRows"); + this.insertId = insertId; + this.numInsertedOrUpdatedRows = numInsertedOrUpdatedRows; + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js +function isNoResultErrorConstructor(fn) { + return Object.prototype.hasOwnProperty.call(fn, "prototype"); +} +var NoResultError; +var init_no_result_error = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js"() { + NoResultError = class extends Error { + constructor(node) { + super("no result"); + /** + * The operation node tree of the query that was executed. + */ + __publicField(this, "node"); + this.node = node; + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js +var OnConflictNode; +var init_on_conflict_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js"() { + init_object_utils(); + init_where_node(); + OnConflictNode = freeze({ + is(node) { + return node.kind === "OnConflictNode"; + }, + create() { + return freeze({ + kind: "OnConflictNode" + }); + }, + cloneWith(node, props) { + return freeze({ + ...node, + ...props + }); + }, + cloneWithIndexWhere(node, operation) { + return freeze({ + ...node, + indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "And", operation) : WhereNode.create(operation) + }); + }, + cloneWithIndexOrWhere(node, operation) { + return freeze({ + ...node, + indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "Or", operation) : WhereNode.create(operation) + }); + }, + cloneWithUpdateWhere(node, operation) { + return freeze({ + ...node, + updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "And", operation) : WhereNode.create(operation) + }); + }, + cloneWithUpdateOrWhere(node, operation) { + return freeze({ + ...node, + updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "Or", operation) : WhereNode.create(operation) + }); + }, + cloneWithoutIndexWhere(node) { + return freeze({ + ...node, + indexWhere: void 0 + }); + }, + cloneWithoutUpdateWhere(node) { + return freeze({ + ...node, + updateWhere: void 0 + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js +var _props4, _OnConflictBuilder, OnConflictBuilder, _props5, OnConflictDoNothingBuilder, _props6, _OnConflictUpdateBuilder, OnConflictUpdateBuilder; +var init_on_conflict_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js"() { + init_column_node(); + init_identifier_node(); + init_on_conflict_node(); + init_binary_operation_parser(); + init_update_set_parser(); + init_object_utils(); + _OnConflictBuilder = class _OnConflictBuilder { + constructor(props) { + __privateAdd(this, _props4); + __privateSet(this, _props4, freeze(props)); + } + /** + * Specify a single column as the conflict target. + * + * Also see the {@link columns}, {@link constraint} and {@link expression} + * methods for alternative ways to specify the conflict target. + */ + column(column) { + const columnNode = ColumnNode.create(column); + return new _OnConflictBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { + columns: __privateGet(this, _props4).onConflictNode.columns ? freeze([...__privateGet(this, _props4).onConflictNode.columns, columnNode]) : freeze([columnNode]) + }) + }); + } + /** + * Specify a list of columns as the conflict target. + * + * Also see the {@link column}, {@link constraint} and {@link expression} + * methods for alternative ways to specify the conflict target. + */ + columns(columns) { + const columnNodes = columns.map(ColumnNode.create); + return new _OnConflictBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { + columns: __privateGet(this, _props4).onConflictNode.columns ? freeze([...__privateGet(this, _props4).onConflictNode.columns, ...columnNodes]) : freeze(columnNodes) + }) + }); + } + /** + * Specify a specific constraint by name as the conflict target. + * + * Also see the {@link column}, {@link columns} and {@link expression} + * methods for alternative ways to specify the conflict target. + */ + constraint(constraintName) { + return new _OnConflictBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { + constraint: IdentifierNode.create(constraintName) + }) + }); + } + /** + * Specify an expression as the conflict target. + * + * This can be used if the unique index is an expression index. + * + * Also see the {@link column}, {@link columns} and {@link constraint} + * methods for alternative ways to specify the conflict target. + */ + expression(expression) { + return new _OnConflictBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { + indexExpression: expression.toOperationNode() + }) + }); + } + where(...args) { + return new _OnConflictBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWithIndexWhere(__privateGet(this, _props4).onConflictNode, parseValueBinaryOperationOrExpression(args)) + }); + } + whereRef(lhs, op, rhs) { + return new _OnConflictBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWithIndexWhere(__privateGet(this, _props4).onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs)) + }); + } + clearWhere() { + return new _OnConflictBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWithoutIndexWhere(__privateGet(this, _props4).onConflictNode) + }); + } + /** + * Adds the "do nothing" conflict action. + * + * ### Examples + * + * ```ts + * const id = 1 + * const first_name = 'John' + * + * await db + * .insertInto('person') + * .values({ first_name, id }) + * .onConflict((oc) => oc + * .column('id') + * .doNothing() + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "id") + * values ($1, $2) + * on conflict ("id") do nothing + * ``` + */ + doNothing() { + return new OnConflictDoNothingBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { + doNothing: true + }) + }); + } + /** + * Adds the "do update set" conflict action. + * + * ### Examples + * + * ```ts + * const id = 1 + * const first_name = 'John' + * + * await db + * .insertInto('person') + * .values({ first_name, id }) + * .onConflict((oc) => oc + * .column('id') + * .doUpdateSet({ first_name }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "id") + * values ($1, $2) + * on conflict ("id") + * do update set "first_name" = $3 + * ``` + * + * In the next example we use the `ref` method to reference + * columns of the virtual table `excluded` in a type-safe way + * to create an upsert operation: + * + * ```ts + * import type { NewPerson } from 'type-editor' // imaginary module + * + * async function upsertPerson(person: NewPerson): Promise { + * await db.insertInto('person') + * .values(person) + * .onConflict((oc) => oc + * .column('id') + * .doUpdateSet((eb) => ({ + * first_name: eb.ref('excluded.first_name'), + * last_name: eb.ref('excluded.last_name') + * }) + * ) + * ) + * .execute() + * } + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name") + * values ($1, $2) + * on conflict ("id") + * do update set + * "first_name" = excluded."first_name", + * "last_name" = excluded."last_name" + * ``` + */ + doUpdateSet(update) { + return new OnConflictUpdateBuilder({ + ...__privateGet(this, _props4), + onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { + updates: parseUpdateObjectExpression(update) + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + }; + _props4 = new WeakMap(); + OnConflictBuilder = _OnConflictBuilder; + OnConflictDoNothingBuilder = class { + constructor(props) { + __privateAdd(this, _props5); + __privateSet(this, _props5, freeze(props)); + } + toOperationNode() { + return __privateGet(this, _props5).onConflictNode; + } + }; + _props5 = new WeakMap(); + _OnConflictUpdateBuilder = class _OnConflictUpdateBuilder { + constructor(props) { + __privateAdd(this, _props6); + __privateSet(this, _props6, freeze(props)); + } + where(...args) { + return new _OnConflictUpdateBuilder({ + ...__privateGet(this, _props6), + onConflictNode: OnConflictNode.cloneWithUpdateWhere(__privateGet(this, _props6).onConflictNode, parseValueBinaryOperationOrExpression(args)) + }); + } + /** + * Specify a where condition for the update operation. + * + * See {@link WhereInterface.whereRef} for more info. + */ + whereRef(lhs, op, rhs) { + return new _OnConflictUpdateBuilder({ + ...__privateGet(this, _props6), + onConflictNode: OnConflictNode.cloneWithUpdateWhere(__privateGet(this, _props6).onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs)) + }); + } + clearWhere() { + return new _OnConflictUpdateBuilder({ + ...__privateGet(this, _props6), + onConflictNode: OnConflictNode.cloneWithoutUpdateWhere(__privateGet(this, _props6).onConflictNode) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props6).onConflictNode; + } + }; + _props6 = new WeakMap(); + OnConflictUpdateBuilder = _OnConflictUpdateBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js +var TopNode; +var init_top_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js"() { + init_object_utils(); + TopNode = freeze({ + is(node) { + return node.kind === "TopNode"; + }, + create(expression, modifiers) { + return freeze({ + kind: "TopNode", + expression, + modifiers + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js +function parseTop(expression, modifiers) { + if (!isNumber2(expression) && !isBigInt(expression)) { + throw new Error(`Invalid top expression: ${expression}`); + } + if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) { + throw new Error(`Invalid top modifiers: ${modifiers}`); + } + return TopNode.create(expression, modifiers); +} +function isTopModifiers(modifiers) { + return modifiers === "percent" || modifiers === "with ties" || modifiers === "percent with ties"; +} +var init_top_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js"() { + init_top_node(); + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js +var OrActionNode; +var init_or_action_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js"() { + init_object_utils(); + OrActionNode = freeze({ + is(node) { + return node.kind === "OrActionNode"; + }, + create(action) { + return freeze({ + kind: "OrActionNode", + action + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js +var _props7, _InsertQueryBuilder, InsertQueryBuilder; +var init_insert_query_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js"() { + init_select_parser(); + init_insert_values_parser(); + init_insert_query_node(); + init_query_node(); + init_update_set_parser(); + init_object_utils(); + init_on_duplicate_key_node(); + init_insert_result(); + init_no_result_error(); + init_expression_parser(); + init_column_node(); + init_on_conflict_builder(); + init_on_conflict_node(); + init_top_parser(); + init_or_action_node(); + _InsertQueryBuilder = class _InsertQueryBuilder { + constructor(props) { + __privateAdd(this, _props7); + __privateSet(this, _props7, freeze(props)); + } + /** + * Sets the values to insert for an {@link Kysely.insertInto | insert} query. + * + * This method takes an object whose keys are column names and values are + * values to insert. In addition to the column's type, the values can be + * raw {@link sql} snippets or select queries. + * + * You must provide all fields you haven't explicitly marked as nullable + * or optional using {@link Generated} or {@link ColumnType}. + * + * The return value of an `insert` query is an instance of {@link InsertResult}. The + * {@link InsertResult.insertId | insertId} field holds the auto incremented primary + * key if the database returned one. + * + * On PostgreSQL and some other dialects, you need to call `returning` to get + * something out of the query. + * + * Also see the {@link expression} method for inserting the result of a select + * query or any other expression. + * + * ### Examples + * + * + * + * Insert a single row: + * + * ```ts + * const result = await db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40 + * }) + * .executeTakeFirst() + * + * // `insertId` is only available on dialects that + * // automatically return the id of the inserted row + * // such as MySQL and SQLite. On PostgreSQL, for example, + * // you need to add a `returning` clause to the query to + * // get anything out. See the "returning data" example. + * console.log(result.insertId) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert into `person` (`first_name`, `last_name`, `age`) values (?, ?, ?) + * ``` + * + * + * + * On dialects that support it (for example PostgreSQL) you can insert multiple + * rows by providing an array. Note that the return value is once again very + * dialect-specific. Some databases may only return the id of the *last* inserted + * row and some return nothing at all unless you call `returning`. + * + * ```ts + * await db + * .insertInto('person') + * .values([{ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }, { + * first_name: 'Arnold', + * last_name: 'Schwarzenegger', + * age: 70, + * }]) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name", "age") values (($1, $2, $3), ($4, $5, $6)) + * ``` + * + * + * + * On supported dialects like PostgreSQL you need to chain `returning` to the query to get + * the inserted row's columns (or any other expression) as the return value. `returning` + * works just like `select`. Refer to `select` method's examples and documentation for + * more info. + * + * ```ts + * const result = await db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }) + * .returning(['id', 'first_name as name']) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name", "age") values ($1, $2, $3) returning "id", "first_name" as "name" + * ``` + * + * + * + * In addition to primitives, the values can also be arbitrary expressions. + * You can build the expressions by using a callback and calling the methods + * on the expression builder passed to it: + * + * ```ts + * import { sql } from 'kysely' + * + * const ani = "Ani" + * const ston = "ston" + * + * const result = await db + * .insertInto('person') + * .values(({ ref, selectFrom, fn }) => ({ + * first_name: 'Jennifer', + * last_name: sql`concat(${ani}, ${ston})`, + * middle_name: ref('first_name'), + * age: selectFrom('person') + * .select(fn.avg('age').as('avg_age')), + * })) + * .executeTakeFirst() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ( + * "first_name", + * "last_name", + * "middle_name", + * "age" + * ) + * values ( + * $1, + * concat($2, $3), + * "first_name", + * (select avg("age") as "avg_age" from "person") + * ) + * ``` + * + * You can also use the callback version of subqueries or raw expressions: + * + * ```ts + * await db.with('jennifer', (db) => db + * .selectFrom('person') + * .where('first_name', '=', 'Jennifer') + * .select(['id', 'first_name', 'gender']) + * .limit(1) + * ).insertInto('pet').values((eb) => ({ + * owner_id: eb.selectFrom('jennifer').select('id'), + * name: eb.selectFrom('jennifer').select('first_name'), + * species: 'cat', + * })) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * with "jennifer" as ( + * select "id", "first_name", "gender" + * from "person" + * where "first_name" = $1 + * limit $2 + * ) + * insert into "pet" ("owner_id", "name", "species") + * values ( + * (select "id" from "jennifer"), + * (select "first_name" from "jennifer"), + * $3 + * ) + * ``` + */ + values(insert) { + const [columns, values] = parseInsertExpression(insert); + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + columns, + values + }) + }); + } + /** + * Sets the columns to insert. + * + * The {@link values} method sets both the columns and the values and this method + * is not needed. But if you are using the {@link expression} method, you can use + * this method to set the columns to insert. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .columns(['first_name']) + * .expression((eb) => eb.selectFrom('pet').select('pet.name')) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name") + * select "pet"."name" from "pet" + * ``` + */ + columns(columns) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + columns: freeze(columns.map(ColumnNode.create)) + }) + }); + } + /** + * Insert an arbitrary expression. For example the result of a select query. + * + * ### Examples + * + * + * + * You can create an `INSERT INTO SELECT FROM` query using the `expression` method. + * This API doesn't follow our WYSIWYG principles and might be a bit difficult to + * remember. The reasons for this design stem from implementation difficulties. + * + * ```ts + * const result = await db.insertInto('person') + * .columns(['first_name', 'last_name', 'age']) + * .expression((eb) => eb + * .selectFrom('pet') + * .select((eb) => [ + * 'pet.name', + * eb.val('Petson').as('last_name'), + * eb.lit(7).as('age'), + * ]) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name", "age") + * select "pet"."name", $1 as "last_name", 7 as "age from "pet" + * ``` + */ + expression(expression) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + values: parseExpression(expression) + }) + }); + } + /** + * Creates an `insert into "person" default values` query. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .defaultValues() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" default values + * ``` + */ + defaultValues() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + defaultValues: true + }) + }); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.insertInto('person') + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * }) + * .modifyEnd(sql`-- This is a comment`) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert into `person` ("first_name", "last_name", "gender") + * values (?, ?, ?) -- This is a comment + * ``` + */ + modifyEnd(modifier) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props7).queryNode, modifier.toOperationNode()) + }); + } + /** + * Changes an `insert into` query to an `insert ignore into` query. + * + * This is only supported by some dialects like MySQL. + * + * To avoid a footgun, when invoked with the SQLite dialect, this method will + * be handled like {@link orIgnore}. See also, {@link orAbort}, {@link orFail}, + * {@link orReplace}, and {@link orRollback}. + * + * If you use the ignore modifier, ignorable errors that occur while executing the + * insert statement are ignored. For example, without ignore, a row that duplicates + * an existing unique index or primary key value in the table causes a duplicate-key + * error and the statement is aborted. With ignore, the row is discarded and no error + * occurs. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .ignore() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?) + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + ignore() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + orAction: OrActionNode.create("ignore") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or ignore into` query. + * + * This is only supported by some dialects like SQLite. + * + * To avoid a footgun, when invoked with the MySQL dialect, this method will + * be handled like {@link ignore}. + * + * See also, {@link orAbort}, {@link orFail}, {@link orReplace}, and {@link orRollback}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orIgnore() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?) + * ``` + */ + orIgnore() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + orAction: OrActionNode.create("ignore") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or abort into` query. + * + * This is only supported by some dialects like SQLite. + * + * See also, {@link orIgnore}, {@link orFail}, {@link orReplace}, and {@link orRollback}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orAbort() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or abort into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + orAbort() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + orAction: OrActionNode.create("abort") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or fail into` query. + * + * This is only supported by some dialects like SQLite. + * + * See also, {@link orIgnore}, {@link orAbort}, {@link orReplace}, and {@link orRollback}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orFail() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or fail into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + orFail() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + orAction: OrActionNode.create("fail") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or replace into` query. + * + * This is only supported by some dialects like SQLite. + * + * You can also use {@link Kysely.replaceInto} to achieve the same result. + * + * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orRollback}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orReplace() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or replace into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + orReplace() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + orAction: OrActionNode.create("replace") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or rollback into` query. + * + * This is only supported by some dialects like SQLite. + * + * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orReplace}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orRollback() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or rollback into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + orRollback() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + orAction: OrActionNode.create("rollback") + }) + }); + } + /** + * Changes an `insert into` query to an `insert top into` query. + * + * `top` clause is only supported by some dialects like MS SQL Server. + * + * ### Examples + * + * Insert the first 5 rows: + * + * ```ts + * import { sql } from 'kysely' + * + * await db.insertInto('person') + * .top(5) + * .columns(['first_name', 'gender']) + * .expression( + * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')]) + * ) + * .execute() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * insert top(5) into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet" + * ``` + * + * Insert the first 50 percent of rows: + * + * ```ts + * import { sql } from 'kysely' + * + * await db.insertInto('person') + * .top(50, 'percent') + * .columns(['first_name', 'gender']) + * .expression( + * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')]) + * ) + * .execute() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * insert top(50) percent into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet" + * ``` + */ + top(expression, modifiers) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: QueryNode.cloneWithTop(__privateGet(this, _props7).queryNode, parseTop(expression, modifiers)) + }); + } + /** + * Adds an `on conflict` clause to the query. + * + * `on conflict` is only supported by some dialects like PostgreSQL and SQLite. On MySQL + * you can use {@link ignore} and {@link onDuplicateKeyUpdate} to achieve similar results. + * + * ### Examples + * + * ```ts + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .column('name') + * .doUpdateSet({ species: 'hamster' }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict ("name") + * do update set "species" = $4 + * ``` + * + * You can provide the name of the constraint instead of a column name: + * + * ```ts + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .constraint('pet_name_key') + * .doUpdateSet({ species: 'hamster' }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict on constraint "pet_name_key" + * do update set "species" = $4 + * ``` + * + * You can also specify an expression as the conflict target in case + * the unique index is an expression index: + * + * ```ts + * import { sql } from 'kysely' + * + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .expression(sql`lower(name)`) + * .doUpdateSet({ species: 'hamster' }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict (lower(name)) + * do update set "species" = $4 + * ``` + * + * You can add a filter for the update statement like this: + * + * ```ts + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .column('name') + * .doUpdateSet({ species: 'hamster' }) + * .where('excluded.name', '!=', 'Catto') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict ("name") + * do update set "species" = $4 + * where "excluded"."name" != $5 + * ``` + * + * You can create an `on conflict do nothing` clauses like this: + * + * ```ts + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .column('name') + * .doNothing() + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict ("name") do nothing + * ``` + * + * You can refer to the columns of the virtual `excluded` table + * in a type-safe way using a callback and the `ref` method of + * `ExpressionBuilder`: + * + * ```ts + * await db.insertInto('person') + * .values({ + * id: 1, + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * }) + * .onConflict(oc => oc + * .column('id') + * .doUpdateSet({ + * first_name: (eb) => eb.ref('excluded.first_name'), + * last_name: (eb) => eb.ref('excluded.last_name') + * }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("id", "first_name", "last_name", "gender") + * values ($1, $2, $3, $4) + * on conflict ("id") + * do update set + * "first_name" = "excluded"."first_name", + * "last_name" = "excluded"."last_name" + * ``` + */ + onConflict(callback) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + onConflict: callback(new OnConflictBuilder({ + onConflictNode: OnConflictNode.create() + })).toOperationNode() + }) + }); + } + /** + * Adds `on duplicate key update` to the query. + * + * If you specify `on duplicate key update`, and a row is inserted that would cause + * a duplicate value in a unique index or primary key, an update of the old row occurs. + * + * This is only implemented by some dialects like MySQL. On most dialects you should + * use {@link onConflict} instead. + * + * ### Examples + * + * ```ts + * await db + * .insertInto('person') + * .values({ + * id: 1, + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * }) + * .onDuplicateKeyUpdate({ updated_at: new Date().toISOString() }) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert into `person` (`id`, `first_name`, `last_name`, `gender`) + * values (?, ?, ?, ?) + * on duplicate key update `updated_at` = ? + * ``` + */ + onDuplicateKeyUpdate(update) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { + onDuplicateKey: OnDuplicateKeyNode.create(parseUpdateObjectExpression(update)) + }) + }); + } + returning(selection) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props7).queryNode, parseSelectArg(selection)) + }); + } + returningAll() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props7).queryNode, parseSelectAll()) + }); + } + output(args) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props7).queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props7).queryNode, parseSelectAll(table)) + }); + } + /** + * Clears all `returning` clauses from the query. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .values({ first_name: 'James', last_name: 'Smith', gender: 'male' }) + * .returning(['first_name']) + * .clearReturning() + * .execute() + * ``` + * + * The generated SQL(PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name", "gender") values ($1, $2, $3) + * ``` + */ + clearReturning() { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: QueryNode.cloneWithoutReturning(__privateGet(this, _props7).queryNode) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + * + * If you want to conditionally call a method on `this`, see + * the {@link $if} method. + * + * ### Examples + * + * The next example uses a helper function `log` to log a query: + * + * ```ts + * import type { Compilable } from 'kysely' + * + * function log(qb: T): T { + * console.log(qb.compile()) + * return qb + * } + * + * await db.insertInto('person') + * .values({ first_name: 'John', last_name: 'Doe', gender: 'male' }) + * .$call(log) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + /** + * Call `func(this)` if `condition` is true. + * + * This method is especially handy with optional selects. Any `returning` or `returningAll` + * method calls add columns as optional fields to the output type when called inside + * the `func` callback. This is because we can't know if those selections were actually + * made before running the code. + * + * You can also call any other methods inside the callback. + * + * ### Examples + * + * ```ts + * import type { NewPerson } from 'type-editor' // imaginary module + * + * async function insertPerson(values: NewPerson, returnLastName: boolean) { + * return await db + * .insertInto('person') + * .values(values) + * .returning(['id', 'first_name']) + * .$if(returnLastName, (qb) => qb.returning('last_name')) + * .executeTakeFirstOrThrow() + * } + * ``` + * + * Any selections added inside the `if` callback will be added as optional fields to the + * output type since we can't know if the selections were actually made before running + * the code. In the example above the return type of the `insertPerson` function is: + * + * ```ts + * Promise<{ + * id: number + * first_name: string + * last_name?: string + * }> + * ``` + */ + $if(condition, func) { + if (condition) { + return func(this); + } + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7) + }); + } + /** + * Change the output type of the query. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `InsertQueryBuilder` with a new output type. + */ + $castTo() { + return new _InsertQueryBuilder(__privateGet(this, _props7)); + } + /** + * Narrows (parts of) the output type of the query. + * + * Kysely tries to be as type-safe as possible, but in some cases we have to make + * compromises for better maintainability and compilation performance. At present, + * Kysely doesn't narrow the output type of the query based on {@link values} input + * when using {@link returning} or {@link returningAll}. + * + * This utility method is very useful for these situations, as it removes unncessary + * runtime assertion/guard code. Its input type is limited to the output type + * of the query, so you can't add a column that doesn't exist, or change a column's + * type to something that doesn't exist in its union type. + * + * ### Examples + * + * Turn this code: + * + * ```ts + * import type { Person } from 'type-editor' // imaginary module + * + * const person = await db.insertInto('person') + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * nullable_column: 'hell yeah!' + * }) + * .returningAll() + * .executeTakeFirstOrThrow() + * + * if (isWithNoNullValue(person)) { + * functionThatExpectsPersonWithNonNullValue(person) + * } + * + * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { + * return person.nullable_column != null + * } + * ``` + * + * Into this: + * + * ```ts + * import type { NotNull } from 'kysely' + * + * const person = await db.insertInto('person') + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * nullable_column: 'hell yeah!' + * }) + * .returningAll() + * .$narrowType<{ nullable_column: NotNull }>() + * .executeTakeFirstOrThrow() + * + * functionThatExpectsPersonWithNonNullValue(person) + * ``` + */ + $narrowType() { + return new _InsertQueryBuilder(__privateGet(this, _props7)); + } + /** + * Asserts that query's output row type equals the given type `T`. + * + * This method can be used to simplify excessively complex types to make TypeScript happy + * and much faster. + * + * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much + * for TypeScript and you get errors like this: + * + * ``` + * error TS2589: Type instantiation is excessively deep and possibly infinite. + * ``` + * + * In these case you can often use this method to help TypeScript a little bit. When you use this + * method to assert the output type of a query, Kysely can drop the complex output type that + * consists of multiple nested helper types and replace it with the simple asserted type. + * + * Using this method doesn't reduce type safety at all. You have to pass in a type that is + * structurally equal to the current type. + * + * ### Examples + * + * ```ts + * import type { NewPerson, NewPet, Species } from 'type-editor' // imaginary module + * + * async function insertPersonAndPet(person: NewPerson, pet: Omit) { + * return await db + * .with('new_person', (qb) => qb + * .insertInto('person') + * .values(person) + * .returning('id') + * .$assertType<{ id: number }>() + * ) + * .with('new_pet', (qb) => qb + * .insertInto('pet') + * .values((eb) => ({ + * owner_id: eb.selectFrom('new_person').select('id'), + * ...pet + * })) + * .returning(['name as pet_name', 'species']) + * .$assertType<{ pet_name: string, species: Species }>() + * ) + * .selectFrom(['new_person', 'new_pet']) + * .selectAll() + * .executeTakeFirstOrThrow() + * } + * ``` + */ + $assertType() { + return new _InsertQueryBuilder(__privateGet(this, _props7)); + } + /** + * Returns a copy of this InsertQueryBuilder instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + executor: __privateGet(this, _props7).executor.withPlugin(plugin) + }); + } + toOperationNode() { + return __privateGet(this, _props7).executor.transformQuery(__privateGet(this, _props7).queryNode, __privateGet(this, _props7).queryId); + } + compile() { + return __privateGet(this, _props7).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props7).queryId); + } + /** + * Executes the query and returns an array of rows. + * + * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. + */ + async execute() { + const compiledQuery = this.compile(); + const result = await __privateGet(this, _props7).executor.executeQuery(compiledQuery); + const { adapter } = __privateGet(this, _props7).executor; + const query = compiledQuery.query; + if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { + return result.rows; + } + return [ + new InsertResult(result.insertId, result.numAffectedRows ?? BigInt(0)) + ]; + } + /** + * Executes the query and returns the first result or undefined if + * the query returned no result. + */ + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + /** + * Executes the query and returns the first result or throws if + * the query returned no result. + * + * By default an instance of {@link NoResultError} is thrown, but you can + * provide a custom error class, or callback as the only argument to throw a different + * error. + */ + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error49; + } + return result; + } + async *stream(chunkSize = 100) { + const compiledQuery = this.compile(); + const stream = __privateGet(this, _props7).executor.stream(compiledQuery, chunkSize); + for await (const item of stream) { + yield* item.rows; + } + } + async explain(format, options) { + const builder = new _InsertQueryBuilder({ + ...__privateGet(this, _props7), + queryNode: QueryNode.cloneWithExplain(__privateGet(this, _props7).queryNode, format, options) + }); + return await builder.execute(); + } + }; + _props7 = new WeakMap(); + InsertQueryBuilder = _InsertQueryBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js +var DeleteResult; +var init_delete_result = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js"() { + DeleteResult = class { + constructor(numDeletedRows) { + __publicField(this, "numDeletedRows"); + this.numDeletedRows = numDeletedRows; + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js +var LimitNode; +var init_limit_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js"() { + init_object_utils(); + LimitNode = freeze({ + is(node) { + return node.kind === "LimitNode"; + }, + create(limit) { + return freeze({ + kind: "LimitNode", + limit + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js +var _a12, _props8, _DeleteQueryBuilder_instances, join_fn, DeleteQueryBuilder; +var init_delete_query_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js"() { + init_join_parser(); + init_table_parser(); + init_select_parser(); + init_query_node(); + init_object_utils(); + init_no_result_error(); + init_delete_result(); + init_delete_query_node(); + init_limit_node(); + init_order_by_parser(); + init_binary_operation_parser(); + init_value_parser(); + init_top_parser(); + DeleteQueryBuilder = class { + constructor(props) { + __privateAdd(this, _DeleteQueryBuilder_instances); + __privateAdd(this, _props8); + __privateSet(this, _props8, freeze(props)); + } + where(...args) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props8).queryNode, parseValueBinaryOperationOrExpression(args)) + }); + } + whereRef(lhs, op, rhs) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props8).queryNode, parseReferentialBinaryOperation(lhs, op, rhs)) + }); + } + clearWhere() { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithoutWhere(__privateGet(this, _props8).queryNode) + }); + } + /** + * Changes a `delete from` query into a `delete top from` query. + * + * `top` clause is only supported by some dialects like MS SQL Server. + * + * ### Examples + * + * Delete the first 5 rows: + * + * ```ts + * await db + * .deleteFrom('person') + * .top(5) + * .where('age', '>', 18) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * delete top(5) from "person" where "age" > @1 + * ``` + * + * Delete the first 50% of rows: + * + * ```ts + * await db + * .deleteFrom('person') + * .top(50, 'percent') + * .where('age', '>', 18) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * delete top(50) percent from "person" where "age" > @1 + * ``` + */ + top(expression, modifiers) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithTop(__privateGet(this, _props8).queryNode, parseTop(expression, modifiers)) + }); + } + using(tables) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: DeleteQueryNode.cloneWithUsing(__privateGet(this, _props8).queryNode, parseTableExpressionOrList(tables)) + }); + } + innerJoin(...args) { + return __privateMethod(this, _DeleteQueryBuilder_instances, join_fn).call(this, "InnerJoin", args); + } + leftJoin(...args) { + return __privateMethod(this, _DeleteQueryBuilder_instances, join_fn).call(this, "LeftJoin", args); + } + rightJoin(...args) { + return __privateMethod(this, _DeleteQueryBuilder_instances, join_fn).call(this, "RightJoin", args); + } + fullJoin(...args) { + return __privateMethod(this, _DeleteQueryBuilder_instances, join_fn).call(this, "FullJoin", args); + } + returning(selection) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props8).queryNode, parseSelectArg(selection)) + }); + } + returningAll(table) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props8).queryNode, parseSelectAll(table)) + }); + } + output(args) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props8).queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props8).queryNode, parseSelectAll(table)) + }); + } + /** + * Clears all `returning` clauses from the query. + * + * ### Examples + * + * ```ts + * await db.deleteFrom('pet') + * .returningAll() + * .where('name', '=', 'Max') + * .clearReturning() + * .execute() + * ``` + * + * The generated SQL(PostgreSQL): + * + * ```sql + * delete from "pet" where "name" = "Max" + * ``` + */ + clearReturning() { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithoutReturning(__privateGet(this, _props8).queryNode) + }); + } + /** + * Clears the `limit` clause from the query. + * + * ### Examples + * + * ```ts + * await db.deleteFrom('pet') + * .returningAll() + * .where('name', '=', 'Max') + * .limit(5) + * .clearLimit() + * .execute() + * ``` + * + * The generated SQL(PostgreSQL): + * + * ```sql + * delete from "pet" where "name" = "Max" returning * + * ``` + */ + clearLimit() { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: DeleteQueryNode.cloneWithoutLimit(__privateGet(this, _props8).queryNode) + }); + } + orderBy(...args) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithOrderByItems(__privateGet(this, _props8).queryNode, parseOrderBy(args)) + }); + } + clearOrderBy() { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props8).queryNode) + }); + } + /** + * Adds a limit clause to the query. + * + * A limit clause in a delete query is only supported by some dialects + * like MySQL. + * + * ### Examples + * + * Delete 5 oldest items in a table: + * + * ```ts + * await db + * .deleteFrom('pet') + * .orderBy('created_at') + * .limit(5) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * delete from `pet` order by `created_at` limit ? + * ``` + */ + limit(limit) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: DeleteQueryNode.cloneWithLimit(__privateGet(this, _props8).queryNode, LimitNode.create(parseValueExpression(limit))) + }); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.deleteFrom('person') + * .where('first_name', '=', 'John') + * .modifyEnd(sql`-- This is a comment`) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * delete from `person` + * where `first_name` = "John" -- This is a comment + * ``` + */ + modifyEnd(modifier) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props8).queryNode, modifier.toOperationNode()) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + * + * If you want to conditionally call a method on `this`, see + * the {@link $if} method. + * + * ### Examples + * + * The next example uses a helper function `log` to log a query: + * + * ```ts + * import type { Compilable } from 'kysely' + * + * function log(qb: T): T { + * console.log(qb.compile()) + * return qb + * } + * + * await db.deleteFrom('person') + * .$call(log) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + /** + * Call `func(this)` if `condition` is true. + * + * This method is especially handy with optional selects. Any `returning` or `returningAll` + * method calls add columns as optional fields to the output type when called inside + * the `func` callback. This is because we can't know if those selections were actually + * made before running the code. + * + * You can also call any other methods inside the callback. + * + * ### Examples + * + * ```ts + * async function deletePerson(id: number, returnLastName: boolean) { + * return await db + * .deleteFrom('person') + * .where('id', '=', id) + * .returning(['id', 'first_name']) + * .$if(returnLastName, (qb) => qb.returning('last_name')) + * .executeTakeFirstOrThrow() + * } + * ``` + * + * Any selections added inside the `if` callback will be added as optional fields to the + * output type since we can't know if the selections were actually made before running + * the code. In the example above the return type of the `deletePerson` function is: + * + * ```ts + * Promise<{ + * id: number + * first_name: string + * last_name?: string + * }> + * ``` + */ + $if(condition, func) { + if (condition) { + return func(this); + } + return new _a12({ + ...__privateGet(this, _props8) + }); + } + /** + * Change the output type of the query. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `DeleteQueryBuilder` with a new output type. + */ + $castTo() { + return new _a12(__privateGet(this, _props8)); + } + /** + * Narrows (parts of) the output type of the query. + * + * Kysely tries to be as type-safe as possible, but in some cases we have to make + * compromises for better maintainability and compilation performance. At present, + * Kysely doesn't narrow the output type of the query when using {@link where} and {@link returning} or {@link returningAll}. + * + * This utility method is very useful for these situations, as it removes unncessary + * runtime assertion/guard code. Its input type is limited to the output type + * of the query, so you can't add a column that doesn't exist, or change a column's + * type to something that doesn't exist in its union type. + * + * ### Examples + * + * Turn this code: + * + * ```ts + * import type { Person } from 'type-editor' // imaginary module + * + * const person = await db.deleteFrom('person') + * .where('id', '=', 3) + * .where('nullable_column', 'is not', null) + * .returningAll() + * .executeTakeFirstOrThrow() + * + * if (isWithNoNullValue(person)) { + * functionThatExpectsPersonWithNonNullValue(person) + * } + * + * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { + * return person.nullable_column != null + * } + * ``` + * + * Into this: + * + * ```ts + * import type { NotNull } from 'kysely' + * + * const person = await db.deleteFrom('person') + * .where('id', '=', 3) + * .where('nullable_column', 'is not', null) + * .returningAll() + * .$narrowType<{ nullable_column: NotNull }>() + * .executeTakeFirstOrThrow() + * + * functionThatExpectsPersonWithNonNullValue(person) + * ``` + */ + $narrowType() { + return new _a12(__privateGet(this, _props8)); + } + /** + * Asserts that query's output row type equals the given type `T`. + * + * This method can be used to simplify excessively complex types to make TypeScript happy + * and much faster. + * + * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much + * for TypeScript and you get errors like this: + * + * ``` + * error TS2589: Type instantiation is excessively deep and possibly infinite. + * ``` + * + * In these case you can often use this method to help TypeScript a little bit. When you use this + * method to assert the output type of a query, Kysely can drop the complex output type that + * consists of multiple nested helper types and replace it with the simple asserted type. + * + * Using this method doesn't reduce type safety at all. You have to pass in a type that is + * structurally equal to the current type. + * + * ### Examples + * + * ```ts + * import type { Species } from 'type-editor' // imaginary module + * + * async function deletePersonAndPets(personId: number) { + * return await db + * .with('deleted_person', (qb) => qb + * .deleteFrom('person') + * .where('id', '=', personId) + * .returning('first_name') + * .$assertType<{ first_name: string }>() + * ) + * .with('deleted_pets', (qb) => qb + * .deleteFrom('pet') + * .where('owner_id', '=', personId) + * .returning(['name as pet_name', 'species']) + * .$assertType<{ pet_name: string, species: Species }>() + * ) + * .selectFrom(['deleted_person', 'deleted_pets']) + * .selectAll() + * .execute() + * } + * ``` + */ + $assertType() { + return new _a12(__privateGet(this, _props8)); + } + /** + * Returns a copy of this DeleteQueryBuilder instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _a12({ + ...__privateGet(this, _props8), + executor: __privateGet(this, _props8).executor.withPlugin(plugin) + }); + } + toOperationNode() { + return __privateGet(this, _props8).executor.transformQuery(__privateGet(this, _props8).queryNode, __privateGet(this, _props8).queryId); + } + compile() { + return __privateGet(this, _props8).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props8).queryId); + } + /** + * Executes the query and returns an array of rows. + * + * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. + */ + async execute() { + const compiledQuery = this.compile(); + const result = await __privateGet(this, _props8).executor.executeQuery(compiledQuery); + const { adapter } = __privateGet(this, _props8).executor; + const query = compiledQuery.query; + if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { + return result.rows; + } + return [new DeleteResult(result.numAffectedRows ?? BigInt(0))]; + } + /** + * Executes the query and returns the first result or undefined if + * the query returned no result. + */ + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + /** + * Executes the query and returns the first result or throws if + * the query returned no result. + * + * By default an instance of {@link NoResultError} is thrown, but you can + * provide a custom error class, or callback as the only argument to throw a different + * error. + */ + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error49; + } + return result; + } + async *stream(chunkSize = 100) { + const compiledQuery = this.compile(); + const stream = __privateGet(this, _props8).executor.stream(compiledQuery, chunkSize); + for await (const item of stream) { + yield* item.rows; + } + } + async explain(format, options) { + const builder = new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithExplain(__privateGet(this, _props8).queryNode, format, options) + }); + return await builder.execute(); + } + }; + _props8 = new WeakMap(); + _DeleteQueryBuilder_instances = new WeakSet(); + join_fn = function(joinType, args) { + return new _a12({ + ...__privateGet(this, _props8), + queryNode: QueryNode.cloneWithJoin(__privateGet(this, _props8).queryNode, parseJoin(joinType, args)) + }); + }; + _a12 = DeleteQueryBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js +var UpdateResult; +var init_update_result = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js"() { + UpdateResult = class { + constructor(numUpdatedRows, numChangedRows) { + /** + * The number of rows the update query updated (even if not changed). + */ + __publicField(this, "numUpdatedRows"); + /** + * The number of rows the update query changed. + * + * This is **optional** and only supported in dialects such as MySQL. + * You would probably use {@link numUpdatedRows} in most cases. + */ + __publicField(this, "numChangedRows"); + this.numUpdatedRows = numUpdatedRows; + this.numChangedRows = numChangedRows; + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js +var _a13, _props9, _UpdateQueryBuilder_instances, join_fn2, UpdateQueryBuilder; +var init_update_query_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js"() { + init_join_parser(); + init_table_parser(); + init_select_parser(); + init_query_node(); + init_update_query_node(); + init_update_set_parser(); + init_object_utils(); + init_update_result(); + init_no_result_error(); + init_binary_operation_parser(); + init_value_parser(); + init_limit_node(); + init_top_parser(); + init_order_by_parser(); + UpdateQueryBuilder = class { + constructor(props) { + __privateAdd(this, _UpdateQueryBuilder_instances); + __privateAdd(this, _props9); + __privateSet(this, _props9, freeze(props)); + } + where(...args) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props9).queryNode, parseValueBinaryOperationOrExpression(args)) + }); + } + whereRef(lhs, op, rhs) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props9).queryNode, parseReferentialBinaryOperation(lhs, op, rhs)) + }); + } + clearWhere() { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithoutWhere(__privateGet(this, _props9).queryNode) + }); + } + /** + * Changes an `update` query into a `update top` query. + * + * `top` clause is only supported by some dialects like MS SQL Server. + * + * ### Examples + * + * Update the first row: + * + * ```ts + * await db.updateTable('person') + * .top(1) + * .set({ first_name: 'Foo' }) + * .where('age', '>', 18) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * update top(1) "person" set "first_name" = @1 where "age" > @2 + * ``` + * + * Update the 50% first rows: + * + * ```ts + * await db.updateTable('person') + * .top(50, 'percent') + * .set({ first_name: 'Foo' }) + * .where('age', '>', 18) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * update top(50) percent "person" set "first_name" = @1 where "age" > @2 + * ``` + */ + top(expression, modifiers) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithTop(__privateGet(this, _props9).queryNode, parseTop(expression, modifiers)) + }); + } + from(from) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: UpdateQueryNode.cloneWithFromItems(__privateGet(this, _props9).queryNode, parseTableExpressionOrList(from)) + }); + } + innerJoin(...args) { + return __privateMethod(this, _UpdateQueryBuilder_instances, join_fn2).call(this, "InnerJoin", args); + } + leftJoin(...args) { + return __privateMethod(this, _UpdateQueryBuilder_instances, join_fn2).call(this, "LeftJoin", args); + } + rightJoin(...args) { + return __privateMethod(this, _UpdateQueryBuilder_instances, join_fn2).call(this, "RightJoin", args); + } + fullJoin(...args) { + return __privateMethod(this, _UpdateQueryBuilder_instances, join_fn2).call(this, "FullJoin", args); + } + orderBy(...args) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithOrderByItems(__privateGet(this, _props9).queryNode, parseOrderBy(args)) + }); + } + clearOrderBy() { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props9).queryNode) + }); + } + /** + * Adds a limit clause to the update query for supported databases, such as MySQL. + * + * ### Examples + * + * Update the first 2 rows in the 'person' table: + * + * ```ts + * await db + * .updateTable('person') + * .set({ first_name: 'Foo' }) + * .limit(2) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * update `person` set `first_name` = ? limit ? + * ``` + */ + limit(limit) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: UpdateQueryNode.cloneWithLimit(__privateGet(this, _props9).queryNode, LimitNode.create(parseValueExpression(limit))) + }); + } + set(...args) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: UpdateQueryNode.cloneWithUpdates(__privateGet(this, _props9).queryNode, parseUpdate(...args)) + }); + } + returning(selection) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props9).queryNode, parseSelectArg(selection)) + }); + } + returningAll(table) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props9).queryNode, parseSelectAll(table)) + }); + } + output(args) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props9).queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props9).queryNode, parseSelectAll(table)) + }); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.updateTable('person') + * .set({ age: 39 }) + * .where('first_name', '=', 'John') + * .modifyEnd(sql.raw('-- This is a comment')) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * update `person` + * set `age` = 39 + * where `first_name` = "John" -- This is a comment + * ``` + */ + modifyEnd(modifier) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props9).queryNode, modifier.toOperationNode()) + }); + } + /** + * Clears all `returning` clauses from the query. + * + * ### Examples + * + * ```ts + * db.updateTable('person') + * .returningAll() + * .set({ age: 39 }) + * .where('first_name', '=', 'John') + * .clearReturning() + * ``` + * + * The generated SQL(PostgreSQL): + * + * ```sql + * update "person" set "age" = 39 where "first_name" = "John" + * ``` + */ + clearReturning() { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithoutReturning(__privateGet(this, _props9).queryNode) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + * + * If you want to conditionally call a method on `this`, see + * the {@link $if} method. + * + * ### Examples + * + * The next example uses a helper function `log` to log a query: + * + * ```ts + * import type { Compilable } from 'kysely' + * import type { PersonUpdate } from 'type-editor' // imaginary module + * + * function log(qb: T): T { + * console.log(qb.compile()) + * return qb + * } + * + * const values = { + * first_name: 'John', + * } satisfies PersonUpdate + * + * db.updateTable('person') + * .set(values) + * .$call(log) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + /** + * Call `func(this)` if `condition` is true. + * + * This method is especially handy with optional selects. Any `returning` or `returningAll` + * method calls add columns as optional fields to the output type when called inside + * the `func` callback. This is because we can't know if those selections were actually + * made before running the code. + * + * You can also call any other methods inside the callback. + * + * ### Examples + * + * ```ts + * import type { PersonUpdate } from 'type-editor' // imaginary module + * + * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) { + * return await db + * .updateTable('person') + * .set(updates) + * .where('id', '=', id) + * .returning(['id', 'first_name']) + * .$if(returnLastName, (qb) => qb.returning('last_name')) + * .executeTakeFirstOrThrow() + * } + * ``` + * + * Any selections added inside the `if` callback will be added as optional fields to the + * output type since we can't know if the selections were actually made before running + * the code. In the example above the return type of the `updatePerson` function is: + * + * ```ts + * Promise<{ + * id: number + * first_name: string + * last_name?: string + * }> + * ``` + */ + $if(condition, func) { + if (condition) { + return func(this); + } + return new _a13({ + ...__privateGet(this, _props9) + }); + } + /** + * Change the output type of the query. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `UpdateQueryBuilder` with a new output type. + */ + $castTo() { + return new _a13(__privateGet(this, _props9)); + } + /** + * Narrows (parts of) the output type of the query. + * + * Kysely tries to be as type-safe as possible, but in some cases we have to make + * compromises for better maintainability and compilation performance. At present, + * Kysely doesn't narrow the output type of the query based on {@link set} input + * when using {@link where} and/or {@link returning} or {@link returningAll}. + * + * This utility method is very useful for these situations, as it removes unncessary + * runtime assertion/guard code. Its input type is limited to the output type + * of the query, so you can't add a column that doesn't exist, or change a column's + * type to something that doesn't exist in its union type. + * + * ### Examples + * + * Turn this code: + * + * ```ts + * import type { Person } from 'type-editor' // imaginary module + * + * const id = 1 + * const now = new Date().toISOString() + * + * const person = await db.updateTable('person') + * .set({ deleted_at: now }) + * .where('id', '=', id) + * .where('nullable_column', 'is not', null) + * .returningAll() + * .executeTakeFirstOrThrow() + * + * if (isWithNoNullValue(person)) { + * functionThatExpectsPersonWithNonNullValue(person) + * } + * + * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { + * return person.nullable_column != null + * } + * ``` + * + * Into this: + * + * ```ts + * import type { NotNull } from 'kysely' + * + * const id = 1 + * const now = new Date().toISOString() + * + * const person = await db.updateTable('person') + * .set({ deleted_at: now }) + * .where('id', '=', id) + * .where('nullable_column', 'is not', null) + * .returningAll() + * .$narrowType<{ deleted_at: Date; nullable_column: NotNull }>() + * .executeTakeFirstOrThrow() + * + * functionThatExpectsPersonWithNonNullValue(person) + * ``` + */ + $narrowType() { + return new _a13(__privateGet(this, _props9)); + } + /** + * Asserts that query's output row type equals the given type `T`. + * + * This method can be used to simplify excessively complex types to make TypeScript happy + * and much faster. + * + * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much + * for TypeScript and you get errors like this: + * + * ``` + * error TS2589: Type instantiation is excessively deep and possibly infinite. + * ``` + * + * In these case you can often use this method to help TypeScript a little bit. When you use this + * method to assert the output type of a query, Kysely can drop the complex output type that + * consists of multiple nested helper types and replace it with the simple asserted type. + * + * Using this method doesn't reduce type safety at all. You have to pass in a type that is + * structurally equal to the current type. + * + * ### Examples + * + * ```ts + * import type { PersonUpdate, PetUpdate, Species } from 'type-editor' // imaginary module + * + * const person = { + * id: 1, + * gender: 'other', + * } satisfies PersonUpdate + * + * const pet = { + * name: 'Fluffy', + * } satisfies PetUpdate + * + * const result = await db + * .with('updated_person', (qb) => qb + * .updateTable('person') + * .set(person) + * .where('id', '=', person.id) + * .returning('first_name') + * .$assertType<{ first_name: string }>() + * ) + * .with('updated_pet', (qb) => qb + * .updateTable('pet') + * .set(pet) + * .where('owner_id', '=', person.id) + * .returning(['name as pet_name', 'species']) + * .$assertType<{ pet_name: string, species: Species }>() + * ) + * .selectFrom(['updated_person', 'updated_pet']) + * .selectAll() + * .executeTakeFirstOrThrow() + * ``` + */ + $assertType() { + return new _a13(__privateGet(this, _props9)); + } + /** + * Returns a copy of this UpdateQueryBuilder instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _a13({ + ...__privateGet(this, _props9), + executor: __privateGet(this, _props9).executor.withPlugin(plugin) + }); + } + toOperationNode() { + return __privateGet(this, _props9).executor.transformQuery(__privateGet(this, _props9).queryNode, __privateGet(this, _props9).queryId); + } + compile() { + return __privateGet(this, _props9).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props9).queryId); + } + /** + * Executes the query and returns an array of rows. + * + * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. + */ + async execute() { + const compiledQuery = this.compile(); + const result = await __privateGet(this, _props9).executor.executeQuery(compiledQuery); + const { adapter } = __privateGet(this, _props9).executor; + const query = compiledQuery.query; + if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { + return result.rows; + } + return [ + new UpdateResult(result.numAffectedRows ?? BigInt(0), result.numChangedRows) + ]; + } + /** + * Executes the query and returns the first result or undefined if + * the query returned no result. + */ + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + /** + * Executes the query and returns the first result or throws if + * the query returned no result. + * + * By default an instance of {@link NoResultError} is thrown, but you can + * provide a custom error class, or callback as the only argument to throw a different + * error. + */ + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error49; + } + return result; + } + async *stream(chunkSize = 100) { + const compiledQuery = this.compile(); + const stream = __privateGet(this, _props9).executor.stream(compiledQuery, chunkSize); + for await (const item of stream) { + yield* item.rows; + } + } + async explain(format, options) { + const builder = new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithExplain(__privateGet(this, _props9).queryNode, format, options) + }); + return await builder.execute(); + } + }; + _props9 = new WeakMap(); + _UpdateQueryBuilder_instances = new WeakSet(); + join_fn2 = function(joinType, args) { + return new _a13({ + ...__privateGet(this, _props9), + queryNode: QueryNode.cloneWithJoin(__privateGet(this, _props9).queryNode, parseJoin(joinType, args)) + }); + }; + _a13 = UpdateQueryBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js +var CommonTableExpressionNameNode; +var init_common_table_expression_name_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js"() { + init_object_utils(); + init_column_node(); + init_table_node(); + CommonTableExpressionNameNode = freeze({ + is(node) { + return node.kind === "CommonTableExpressionNameNode"; + }, + create(tableName, columnNames) { + return freeze({ + kind: "CommonTableExpressionNameNode", + table: TableNode.create(tableName), + columns: columnNames ? freeze(columnNames.map(ColumnNode.create)) : void 0 + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js +var CommonTableExpressionNode; +var init_common_table_expression_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js"() { + init_object_utils(); + CommonTableExpressionNode = freeze({ + is(node) { + return node.kind === "CommonTableExpressionNode"; + }, + create(name, expression) { + return freeze({ + kind: "CommonTableExpressionNode", + name, + expression + }); + }, + cloneWith(node, props) { + return freeze({ + ...node, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js +var _props10, _CTEBuilder, CTEBuilder; +var init_cte_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js"() { + init_common_table_expression_node(); + init_object_utils(); + _CTEBuilder = class _CTEBuilder { + constructor(props) { + __privateAdd(this, _props10); + __privateSet(this, _props10, freeze(props)); + } + /** + * Makes the common table expression materialized. + */ + materialized() { + return new _CTEBuilder({ + ...__privateGet(this, _props10), + node: CommonTableExpressionNode.cloneWith(__privateGet(this, _props10).node, { + materialized: true + }) + }); + } + /** + * Makes the common table expression not materialized. + */ + notMaterialized() { + return new _CTEBuilder({ + ...__privateGet(this, _props10), + node: CommonTableExpressionNode.cloneWith(__privateGet(this, _props10).node, { + materialized: false + }) + }); + } + toOperationNode() { + return __privateGet(this, _props10).node; + } + }; + _props10 = new WeakMap(); + CTEBuilder = _CTEBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js +function parseCommonTableExpression(nameOrBuilderCallback, expression) { + const expressionNode = expression(createQueryCreator()).toOperationNode(); + if (isFunction3(nameOrBuilderCallback)) { + return nameOrBuilderCallback(cteBuilderFactory(expressionNode)).toOperationNode(); + } + return CommonTableExpressionNode.create(parseCommonTableExpressionName(nameOrBuilderCallback), expressionNode); +} +function cteBuilderFactory(expressionNode) { + return (name) => { + return new CTEBuilder({ + node: CommonTableExpressionNode.create(parseCommonTableExpressionName(name), expressionNode) + }); + }; +} +function parseCommonTableExpressionName(name) { + if (name.includes("(")) { + const parts = name.split(/[\(\)]/); + const table = parts[0]; + const columns = parts[1].split(",").map((it) => it.trim()); + return CommonTableExpressionNameNode.create(table, columns); + } else { + return CommonTableExpressionNameNode.create(name); + } +} +var init_with_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js"() { + init_common_table_expression_name_node(); + init_parse_utils(); + init_object_utils(); + init_cte_builder(); + init_common_table_expression_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js +var WithNode; +var init_with_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js"() { + init_object_utils(); + WithNode = freeze({ + is(node) { + return node.kind === "WithNode"; + }, + create(expression, params) { + return freeze({ + kind: "WithNode", + expressions: freeze([expression]), + ...params + }); + }, + cloneWithExpression(withNode, expression) { + return freeze({ + ...withNode, + expressions: freeze([...withNode.expressions, expression]) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js +function randomString2(length) { + let chars = ""; + for (let i = 0; i < length; ++i) { + chars += randomChar(); + } + return chars; +} +function randomChar() { + return CHARS[~~(Math.random() * CHARS.length)]; +} +var CHARS; +var init_random_string = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js"() { + CHARS = [ + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9" + ]; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js +function createQueryId() { + return new LazyQueryId(); +} +var _queryId, LazyQueryId; +var init_query_id = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js"() { + init_random_string(); + LazyQueryId = class { + constructor() { + __privateAdd(this, _queryId); + } + get queryId() { + if (__privateGet(this, _queryId) === void 0) { + __privateSet(this, _queryId, randomString2(8)); + } + return __privateGet(this, _queryId); + } + }; + _queryId = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js +function requireAllProps(obj) { + return obj; +} +var init_require_all_props = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js +var _transformers, OperationNodeTransformer; +var init_operation_node_transformer = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js"() { + init_object_utils(); + init_require_all_props(); + OperationNodeTransformer = class { + constructor() { + __publicField(this, "nodeStack", []); + __privateAdd(this, _transformers, freeze({ + AliasNode: this.transformAlias.bind(this), + ColumnNode: this.transformColumn.bind(this), + IdentifierNode: this.transformIdentifier.bind(this), + SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this), + RawNode: this.transformRaw.bind(this), + ReferenceNode: this.transformReference.bind(this), + SelectQueryNode: this.transformSelectQuery.bind(this), + SelectionNode: this.transformSelection.bind(this), + TableNode: this.transformTable.bind(this), + FromNode: this.transformFrom.bind(this), + SelectAllNode: this.transformSelectAll.bind(this), + AndNode: this.transformAnd.bind(this), + OrNode: this.transformOr.bind(this), + ValueNode: this.transformValue.bind(this), + ValueListNode: this.transformValueList.bind(this), + PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this), + ParensNode: this.transformParens.bind(this), + JoinNode: this.transformJoin.bind(this), + OperatorNode: this.transformOperator.bind(this), + WhereNode: this.transformWhere.bind(this), + InsertQueryNode: this.transformInsertQuery.bind(this), + DeleteQueryNode: this.transformDeleteQuery.bind(this), + ReturningNode: this.transformReturning.bind(this), + CreateTableNode: this.transformCreateTable.bind(this), + AddColumnNode: this.transformAddColumn.bind(this), + ColumnDefinitionNode: this.transformColumnDefinition.bind(this), + DropTableNode: this.transformDropTable.bind(this), + DataTypeNode: this.transformDataType.bind(this), + OrderByNode: this.transformOrderBy.bind(this), + OrderByItemNode: this.transformOrderByItem.bind(this), + GroupByNode: this.transformGroupBy.bind(this), + GroupByItemNode: this.transformGroupByItem.bind(this), + UpdateQueryNode: this.transformUpdateQuery.bind(this), + ColumnUpdateNode: this.transformColumnUpdate.bind(this), + LimitNode: this.transformLimit.bind(this), + OffsetNode: this.transformOffset.bind(this), + OnConflictNode: this.transformOnConflict.bind(this), + OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this), + CreateIndexNode: this.transformCreateIndex.bind(this), + DropIndexNode: this.transformDropIndex.bind(this), + ListNode: this.transformList.bind(this), + PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this), + UniqueConstraintNode: this.transformUniqueConstraint.bind(this), + ReferencesNode: this.transformReferences.bind(this), + CheckConstraintNode: this.transformCheckConstraint.bind(this), + WithNode: this.transformWith.bind(this), + CommonTableExpressionNode: this.transformCommonTableExpression.bind(this), + CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this), + HavingNode: this.transformHaving.bind(this), + CreateSchemaNode: this.transformCreateSchema.bind(this), + DropSchemaNode: this.transformDropSchema.bind(this), + AlterTableNode: this.transformAlterTable.bind(this), + DropColumnNode: this.transformDropColumn.bind(this), + RenameColumnNode: this.transformRenameColumn.bind(this), + AlterColumnNode: this.transformAlterColumn.bind(this), + ModifyColumnNode: this.transformModifyColumn.bind(this), + AddConstraintNode: this.transformAddConstraint.bind(this), + DropConstraintNode: this.transformDropConstraint.bind(this), + RenameConstraintNode: this.transformRenameConstraint.bind(this), + ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this), + CreateViewNode: this.transformCreateView.bind(this), + RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this), + DropViewNode: this.transformDropView.bind(this), + GeneratedNode: this.transformGenerated.bind(this), + DefaultValueNode: this.transformDefaultValue.bind(this), + OnNode: this.transformOn.bind(this), + ValuesNode: this.transformValues.bind(this), + SelectModifierNode: this.transformSelectModifier.bind(this), + CreateTypeNode: this.transformCreateType.bind(this), + DropTypeNode: this.transformDropType.bind(this), + ExplainNode: this.transformExplain.bind(this), + DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this), + AggregateFunctionNode: this.transformAggregateFunction.bind(this), + OverNode: this.transformOver.bind(this), + PartitionByNode: this.transformPartitionBy.bind(this), + PartitionByItemNode: this.transformPartitionByItem.bind(this), + SetOperationNode: this.transformSetOperation.bind(this), + BinaryOperationNode: this.transformBinaryOperation.bind(this), + UnaryOperationNode: this.transformUnaryOperation.bind(this), + UsingNode: this.transformUsing.bind(this), + FunctionNode: this.transformFunction.bind(this), + CaseNode: this.transformCase.bind(this), + WhenNode: this.transformWhen.bind(this), + JSONReferenceNode: this.transformJSONReference.bind(this), + JSONPathNode: this.transformJSONPath.bind(this), + JSONPathLegNode: this.transformJSONPathLeg.bind(this), + JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this), + TupleNode: this.transformTuple.bind(this), + MergeQueryNode: this.transformMergeQuery.bind(this), + MatchedNode: this.transformMatched.bind(this), + AddIndexNode: this.transformAddIndex.bind(this), + CastNode: this.transformCast.bind(this), + FetchNode: this.transformFetch.bind(this), + TopNode: this.transformTop.bind(this), + OutputNode: this.transformOutput.bind(this), + OrActionNode: this.transformOrAction.bind(this), + CollateNode: this.transformCollate.bind(this) + })); + } + transformNode(node, queryId) { + if (!node) { + return node; + } + this.nodeStack.push(node); + const out = this.transformNodeImpl(node, queryId); + this.nodeStack.pop(); + return freeze(out); + } + transformNodeImpl(node, queryId) { + return __privateGet(this, _transformers)[node.kind](node, queryId); + } + transformNodeList(list, queryId) { + if (!list) { + return list; + } + return freeze(list.map((node) => this.transformNode(node, queryId))); + } + transformSelectQuery(node, queryId) { + return requireAllProps({ + kind: "SelectQueryNode", + from: this.transformNode(node.from, queryId), + selections: this.transformNodeList(node.selections, queryId), + distinctOn: this.transformNodeList(node.distinctOn, queryId), + joins: this.transformNodeList(node.joins, queryId), + groupBy: this.transformNode(node.groupBy, queryId), + orderBy: this.transformNode(node.orderBy, queryId), + where: this.transformNode(node.where, queryId), + frontModifiers: this.transformNodeList(node.frontModifiers, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + limit: this.transformNode(node.limit, queryId), + offset: this.transformNode(node.offset, queryId), + with: this.transformNode(node.with, queryId), + having: this.transformNode(node.having, queryId), + explain: this.transformNode(node.explain, queryId), + setOperations: this.transformNodeList(node.setOperations, queryId), + fetch: this.transformNode(node.fetch, queryId), + top: this.transformNode(node.top, queryId) + }); + } + transformSelection(node, queryId) { + return requireAllProps({ + kind: "SelectionNode", + selection: this.transformNode(node.selection, queryId) + }); + } + transformColumn(node, queryId) { + return requireAllProps({ + kind: "ColumnNode", + column: this.transformNode(node.column, queryId) + }); + } + transformAlias(node, queryId) { + return requireAllProps({ + kind: "AliasNode", + node: this.transformNode(node.node, queryId), + alias: this.transformNode(node.alias, queryId) + }); + } + transformTable(node, queryId) { + return requireAllProps({ + kind: "TableNode", + table: this.transformNode(node.table, queryId) + }); + } + transformFrom(node, queryId) { + return requireAllProps({ + kind: "FromNode", + froms: this.transformNodeList(node.froms, queryId) + }); + } + transformReference(node, queryId) { + return requireAllProps({ + kind: "ReferenceNode", + column: this.transformNode(node.column, queryId), + table: this.transformNode(node.table, queryId) + }); + } + transformAnd(node, queryId) { + return requireAllProps({ + kind: "AndNode", + left: this.transformNode(node.left, queryId), + right: this.transformNode(node.right, queryId) + }); + } + transformOr(node, queryId) { + return requireAllProps({ + kind: "OrNode", + left: this.transformNode(node.left, queryId), + right: this.transformNode(node.right, queryId) + }); + } + transformValueList(node, queryId) { + return requireAllProps({ + kind: "ValueListNode", + values: this.transformNodeList(node.values, queryId) + }); + } + transformParens(node, queryId) { + return requireAllProps({ + kind: "ParensNode", + node: this.transformNode(node.node, queryId) + }); + } + transformJoin(node, queryId) { + return requireAllProps({ + kind: "JoinNode", + joinType: node.joinType, + table: this.transformNode(node.table, queryId), + on: this.transformNode(node.on, queryId) + }); + } + transformRaw(node, queryId) { + return requireAllProps({ + kind: "RawNode", + sqlFragments: freeze([...node.sqlFragments]), + parameters: this.transformNodeList(node.parameters, queryId) + }); + } + transformWhere(node, queryId) { + return requireAllProps({ + kind: "WhereNode", + where: this.transformNode(node.where, queryId) + }); + } + transformInsertQuery(node, queryId) { + return requireAllProps({ + kind: "InsertQueryNode", + into: this.transformNode(node.into, queryId), + columns: this.transformNodeList(node.columns, queryId), + values: this.transformNode(node.values, queryId), + returning: this.transformNode(node.returning, queryId), + onConflict: this.transformNode(node.onConflict, queryId), + onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + with: this.transformNode(node.with, queryId), + ignore: node.ignore, + orAction: this.transformNode(node.orAction, queryId), + replace: node.replace, + explain: this.transformNode(node.explain, queryId), + defaultValues: node.defaultValues, + top: this.transformNode(node.top, queryId), + output: this.transformNode(node.output, queryId) + }); + } + transformValues(node, queryId) { + return requireAllProps({ + kind: "ValuesNode", + values: this.transformNodeList(node.values, queryId) + }); + } + transformDeleteQuery(node, queryId) { + return requireAllProps({ + kind: "DeleteQueryNode", + from: this.transformNode(node.from, queryId), + using: this.transformNode(node.using, queryId), + joins: this.transformNodeList(node.joins, queryId), + where: this.transformNode(node.where, queryId), + returning: this.transformNode(node.returning, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + with: this.transformNode(node.with, queryId), + orderBy: this.transformNode(node.orderBy, queryId), + limit: this.transformNode(node.limit, queryId), + explain: this.transformNode(node.explain, queryId), + top: this.transformNode(node.top, queryId), + output: this.transformNode(node.output, queryId) + }); + } + transformReturning(node, queryId) { + return requireAllProps({ + kind: "ReturningNode", + selections: this.transformNodeList(node.selections, queryId) + }); + } + transformCreateTable(node, queryId) { + return requireAllProps({ + kind: "CreateTableNode", + table: this.transformNode(node.table, queryId), + columns: this.transformNodeList(node.columns, queryId), + constraints: this.transformNodeList(node.constraints, queryId), + temporary: node.temporary, + ifNotExists: node.ifNotExists, + onCommit: node.onCommit, + frontModifiers: this.transformNodeList(node.frontModifiers, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + selectQuery: this.transformNode(node.selectQuery, queryId) + }); + } + transformColumnDefinition(node, queryId) { + return requireAllProps({ + kind: "ColumnDefinitionNode", + column: this.transformNode(node.column, queryId), + dataType: this.transformNode(node.dataType, queryId), + references: this.transformNode(node.references, queryId), + primaryKey: node.primaryKey, + autoIncrement: node.autoIncrement, + unique: node.unique, + notNull: node.notNull, + unsigned: node.unsigned, + defaultTo: this.transformNode(node.defaultTo, queryId), + check: this.transformNode(node.check, queryId), + generated: this.transformNode(node.generated, queryId), + frontModifiers: this.transformNodeList(node.frontModifiers, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + nullsNotDistinct: node.nullsNotDistinct, + identity: node.identity, + ifNotExists: node.ifNotExists + }); + } + transformAddColumn(node, queryId) { + return requireAllProps({ + kind: "AddColumnNode", + column: this.transformNode(node.column, queryId) + }); + } + transformDropTable(node, queryId) { + return requireAllProps({ + kind: "DropTableNode", + table: this.transformNode(node.table, queryId), + ifExists: node.ifExists, + cascade: node.cascade + }); + } + transformOrderBy(node, queryId) { + return requireAllProps({ + kind: "OrderByNode", + items: this.transformNodeList(node.items, queryId) + }); + } + transformOrderByItem(node, queryId) { + return requireAllProps({ + kind: "OrderByItemNode", + orderBy: this.transformNode(node.orderBy, queryId), + direction: this.transformNode(node.direction, queryId), + collation: this.transformNode(node.collation, queryId), + nulls: node.nulls + }); + } + transformGroupBy(node, queryId) { + return requireAllProps({ + kind: "GroupByNode", + items: this.transformNodeList(node.items, queryId) + }); + } + transformGroupByItem(node, queryId) { + return requireAllProps({ + kind: "GroupByItemNode", + groupBy: this.transformNode(node.groupBy, queryId) + }); + } + transformUpdateQuery(node, queryId) { + return requireAllProps({ + kind: "UpdateQueryNode", + table: this.transformNode(node.table, queryId), + from: this.transformNode(node.from, queryId), + joins: this.transformNodeList(node.joins, queryId), + where: this.transformNode(node.where, queryId), + updates: this.transformNodeList(node.updates, queryId), + returning: this.transformNode(node.returning, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + with: this.transformNode(node.with, queryId), + explain: this.transformNode(node.explain, queryId), + limit: this.transformNode(node.limit, queryId), + top: this.transformNode(node.top, queryId), + output: this.transformNode(node.output, queryId), + orderBy: this.transformNode(node.orderBy, queryId) + }); + } + transformColumnUpdate(node, queryId) { + return requireAllProps({ + kind: "ColumnUpdateNode", + column: this.transformNode(node.column, queryId), + value: this.transformNode(node.value, queryId) + }); + } + transformLimit(node, queryId) { + return requireAllProps({ + kind: "LimitNode", + limit: this.transformNode(node.limit, queryId) + }); + } + transformOffset(node, queryId) { + return requireAllProps({ + kind: "OffsetNode", + offset: this.transformNode(node.offset, queryId) + }); + } + transformOnConflict(node, queryId) { + return requireAllProps({ + kind: "OnConflictNode", + columns: this.transformNodeList(node.columns, queryId), + constraint: this.transformNode(node.constraint, queryId), + indexExpression: this.transformNode(node.indexExpression, queryId), + indexWhere: this.transformNode(node.indexWhere, queryId), + updates: this.transformNodeList(node.updates, queryId), + updateWhere: this.transformNode(node.updateWhere, queryId), + doNothing: node.doNothing + }); + } + transformOnDuplicateKey(node, queryId) { + return requireAllProps({ + kind: "OnDuplicateKeyNode", + updates: this.transformNodeList(node.updates, queryId) + }); + } + transformCreateIndex(node, queryId) { + return requireAllProps({ + kind: "CreateIndexNode", + name: this.transformNode(node.name, queryId), + table: this.transformNode(node.table, queryId), + columns: this.transformNodeList(node.columns, queryId), + unique: node.unique, + using: this.transformNode(node.using, queryId), + ifNotExists: node.ifNotExists, + where: this.transformNode(node.where, queryId), + nullsNotDistinct: node.nullsNotDistinct + }); + } + transformList(node, queryId) { + return requireAllProps({ + kind: "ListNode", + items: this.transformNodeList(node.items, queryId) + }); + } + transformDropIndex(node, queryId) { + return requireAllProps({ + kind: "DropIndexNode", + name: this.transformNode(node.name, queryId), + table: this.transformNode(node.table, queryId), + ifExists: node.ifExists, + cascade: node.cascade + }); + } + transformPrimaryKeyConstraint(node, queryId) { + return requireAllProps({ + kind: "PrimaryKeyConstraintNode", + columns: this.transformNodeList(node.columns, queryId), + name: this.transformNode(node.name, queryId), + deferrable: node.deferrable, + initiallyDeferred: node.initiallyDeferred + }); + } + transformUniqueConstraint(node, queryId) { + return requireAllProps({ + kind: "UniqueConstraintNode", + columns: this.transformNodeList(node.columns, queryId), + name: this.transformNode(node.name, queryId), + nullsNotDistinct: node.nullsNotDistinct, + deferrable: node.deferrable, + initiallyDeferred: node.initiallyDeferred + }); + } + transformForeignKeyConstraint(node, queryId) { + return requireAllProps({ + kind: "ForeignKeyConstraintNode", + columns: this.transformNodeList(node.columns, queryId), + references: this.transformNode(node.references, queryId), + name: this.transformNode(node.name, queryId), + onDelete: node.onDelete, + onUpdate: node.onUpdate, + deferrable: node.deferrable, + initiallyDeferred: node.initiallyDeferred + }); + } + transformSetOperation(node, queryId) { + return requireAllProps({ + kind: "SetOperationNode", + operator: node.operator, + expression: this.transformNode(node.expression, queryId), + all: node.all + }); + } + transformReferences(node, queryId) { + return requireAllProps({ + kind: "ReferencesNode", + table: this.transformNode(node.table, queryId), + columns: this.transformNodeList(node.columns, queryId), + onDelete: node.onDelete, + onUpdate: node.onUpdate + }); + } + transformCheckConstraint(node, queryId) { + return requireAllProps({ + kind: "CheckConstraintNode", + expression: this.transformNode(node.expression, queryId), + name: this.transformNode(node.name, queryId) + }); + } + transformWith(node, queryId) { + return requireAllProps({ + kind: "WithNode", + expressions: this.transformNodeList(node.expressions, queryId), + recursive: node.recursive + }); + } + transformCommonTableExpression(node, queryId) { + return requireAllProps({ + kind: "CommonTableExpressionNode", + name: this.transformNode(node.name, queryId), + materialized: node.materialized, + expression: this.transformNode(node.expression, queryId) + }); + } + transformCommonTableExpressionName(node, queryId) { + return requireAllProps({ + kind: "CommonTableExpressionNameNode", + table: this.transformNode(node.table, queryId), + columns: this.transformNodeList(node.columns, queryId) + }); + } + transformHaving(node, queryId) { + return requireAllProps({ + kind: "HavingNode", + having: this.transformNode(node.having, queryId) + }); + } + transformCreateSchema(node, queryId) { + return requireAllProps({ + kind: "CreateSchemaNode", + schema: this.transformNode(node.schema, queryId), + ifNotExists: node.ifNotExists + }); + } + transformDropSchema(node, queryId) { + return requireAllProps({ + kind: "DropSchemaNode", + schema: this.transformNode(node.schema, queryId), + ifExists: node.ifExists, + cascade: node.cascade + }); + } + transformAlterTable(node, queryId) { + return requireAllProps({ + kind: "AlterTableNode", + table: this.transformNode(node.table, queryId), + renameTo: this.transformNode(node.renameTo, queryId), + setSchema: this.transformNode(node.setSchema, queryId), + columnAlterations: this.transformNodeList(node.columnAlterations, queryId), + addConstraint: this.transformNode(node.addConstraint, queryId), + dropConstraint: this.transformNode(node.dropConstraint, queryId), + renameConstraint: this.transformNode(node.renameConstraint, queryId), + addIndex: this.transformNode(node.addIndex, queryId), + dropIndex: this.transformNode(node.dropIndex, queryId) + }); + } + transformDropColumn(node, queryId) { + return requireAllProps({ + kind: "DropColumnNode", + column: this.transformNode(node.column, queryId) + }); + } + transformRenameColumn(node, queryId) { + return requireAllProps({ + kind: "RenameColumnNode", + column: this.transformNode(node.column, queryId), + renameTo: this.transformNode(node.renameTo, queryId) + }); + } + transformAlterColumn(node, queryId) { + return requireAllProps({ + kind: "AlterColumnNode", + column: this.transformNode(node.column, queryId), + dataType: this.transformNode(node.dataType, queryId), + dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId), + setDefault: this.transformNode(node.setDefault, queryId), + dropDefault: node.dropDefault, + setNotNull: node.setNotNull, + dropNotNull: node.dropNotNull + }); + } + transformModifyColumn(node, queryId) { + return requireAllProps({ + kind: "ModifyColumnNode", + column: this.transformNode(node.column, queryId) + }); + } + transformAddConstraint(node, queryId) { + return requireAllProps({ + kind: "AddConstraintNode", + constraint: this.transformNode(node.constraint, queryId) + }); + } + transformDropConstraint(node, queryId) { + return requireAllProps({ + kind: "DropConstraintNode", + constraintName: this.transformNode(node.constraintName, queryId), + ifExists: node.ifExists, + modifier: node.modifier + }); + } + transformRenameConstraint(node, queryId) { + return requireAllProps({ + kind: "RenameConstraintNode", + oldName: this.transformNode(node.oldName, queryId), + newName: this.transformNode(node.newName, queryId) + }); + } + transformCreateView(node, queryId) { + return requireAllProps({ + kind: "CreateViewNode", + name: this.transformNode(node.name, queryId), + temporary: node.temporary, + orReplace: node.orReplace, + ifNotExists: node.ifNotExists, + materialized: node.materialized, + columns: this.transformNodeList(node.columns, queryId), + as: this.transformNode(node.as, queryId) + }); + } + transformRefreshMaterializedView(node, queryId) { + return requireAllProps({ + kind: "RefreshMaterializedViewNode", + name: this.transformNode(node.name, queryId), + concurrently: node.concurrently, + withNoData: node.withNoData + }); + } + transformDropView(node, queryId) { + return requireAllProps({ + kind: "DropViewNode", + name: this.transformNode(node.name, queryId), + ifExists: node.ifExists, + materialized: node.materialized, + cascade: node.cascade + }); + } + transformGenerated(node, queryId) { + return requireAllProps({ + kind: "GeneratedNode", + byDefault: node.byDefault, + always: node.always, + identity: node.identity, + stored: node.stored, + expression: this.transformNode(node.expression, queryId) + }); + } + transformDefaultValue(node, queryId) { + return requireAllProps({ + kind: "DefaultValueNode", + defaultValue: this.transformNode(node.defaultValue, queryId) + }); + } + transformOn(node, queryId) { + return requireAllProps({ + kind: "OnNode", + on: this.transformNode(node.on, queryId) + }); + } + transformSelectModifier(node, queryId) { + return requireAllProps({ + kind: "SelectModifierNode", + modifier: node.modifier, + rawModifier: this.transformNode(node.rawModifier, queryId), + of: this.transformNodeList(node.of, queryId) + }); + } + transformCreateType(node, queryId) { + return requireAllProps({ + kind: "CreateTypeNode", + name: this.transformNode(node.name, queryId), + enum: this.transformNode(node.enum, queryId) + }); + } + transformDropType(node, queryId) { + return requireAllProps({ + kind: "DropTypeNode", + name: this.transformNode(node.name, queryId), + ifExists: node.ifExists + }); + } + transformExplain(node, queryId) { + return requireAllProps({ + kind: "ExplainNode", + format: node.format, + options: this.transformNode(node.options, queryId) + }); + } + transformSchemableIdentifier(node, queryId) { + return requireAllProps({ + kind: "SchemableIdentifierNode", + schema: this.transformNode(node.schema, queryId), + identifier: this.transformNode(node.identifier, queryId) + }); + } + transformAggregateFunction(node, queryId) { + return requireAllProps({ + kind: "AggregateFunctionNode", + func: node.func, + aggregated: this.transformNodeList(node.aggregated, queryId), + distinct: node.distinct, + orderBy: this.transformNode(node.orderBy, queryId), + withinGroup: this.transformNode(node.withinGroup, queryId), + filter: this.transformNode(node.filter, queryId), + over: this.transformNode(node.over, queryId) + }); + } + transformOver(node, queryId) { + return requireAllProps({ + kind: "OverNode", + orderBy: this.transformNode(node.orderBy, queryId), + partitionBy: this.transformNode(node.partitionBy, queryId) + }); + } + transformPartitionBy(node, queryId) { + return requireAllProps({ + kind: "PartitionByNode", + items: this.transformNodeList(node.items, queryId) + }); + } + transformPartitionByItem(node, queryId) { + return requireAllProps({ + kind: "PartitionByItemNode", + partitionBy: this.transformNode(node.partitionBy, queryId) + }); + } + transformBinaryOperation(node, queryId) { + return requireAllProps({ + kind: "BinaryOperationNode", + leftOperand: this.transformNode(node.leftOperand, queryId), + operator: this.transformNode(node.operator, queryId), + rightOperand: this.transformNode(node.rightOperand, queryId) + }); + } + transformUnaryOperation(node, queryId) { + return requireAllProps({ + kind: "UnaryOperationNode", + operator: this.transformNode(node.operator, queryId), + operand: this.transformNode(node.operand, queryId) + }); + } + transformUsing(node, queryId) { + return requireAllProps({ + kind: "UsingNode", + tables: this.transformNodeList(node.tables, queryId) + }); + } + transformFunction(node, queryId) { + return requireAllProps({ + kind: "FunctionNode", + func: node.func, + arguments: this.transformNodeList(node.arguments, queryId) + }); + } + transformCase(node, queryId) { + return requireAllProps({ + kind: "CaseNode", + value: this.transformNode(node.value, queryId), + when: this.transformNodeList(node.when, queryId), + else: this.transformNode(node.else, queryId), + isStatement: node.isStatement + }); + } + transformWhen(node, queryId) { + return requireAllProps({ + kind: "WhenNode", + condition: this.transformNode(node.condition, queryId), + result: this.transformNode(node.result, queryId) + }); + } + transformJSONReference(node, queryId) { + return requireAllProps({ + kind: "JSONReferenceNode", + reference: this.transformNode(node.reference, queryId), + traversal: this.transformNode(node.traversal, queryId) + }); + } + transformJSONPath(node, queryId) { + return requireAllProps({ + kind: "JSONPathNode", + inOperator: this.transformNode(node.inOperator, queryId), + pathLegs: this.transformNodeList(node.pathLegs, queryId) + }); + } + transformJSONPathLeg(node, _queryId2) { + return requireAllProps({ + kind: "JSONPathLegNode", + type: node.type, + value: node.value + }); + } + transformJSONOperatorChain(node, queryId) { + return requireAllProps({ + kind: "JSONOperatorChainNode", + operator: this.transformNode(node.operator, queryId), + values: this.transformNodeList(node.values, queryId) + }); + } + transformTuple(node, queryId) { + return requireAllProps({ + kind: "TupleNode", + values: this.transformNodeList(node.values, queryId) + }); + } + transformMergeQuery(node, queryId) { + return requireAllProps({ + kind: "MergeQueryNode", + into: this.transformNode(node.into, queryId), + using: this.transformNode(node.using, queryId), + whens: this.transformNodeList(node.whens, queryId), + with: this.transformNode(node.with, queryId), + top: this.transformNode(node.top, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + output: this.transformNode(node.output, queryId), + returning: this.transformNode(node.returning, queryId) + }); + } + transformMatched(node, _queryId2) { + return requireAllProps({ + kind: "MatchedNode", + not: node.not, + bySource: node.bySource + }); + } + transformAddIndex(node, queryId) { + return requireAllProps({ + kind: "AddIndexNode", + name: this.transformNode(node.name, queryId), + columns: this.transformNodeList(node.columns, queryId), + unique: node.unique, + using: this.transformNode(node.using, queryId), + ifNotExists: node.ifNotExists + }); + } + transformCast(node, queryId) { + return requireAllProps({ + kind: "CastNode", + expression: this.transformNode(node.expression, queryId), + dataType: this.transformNode(node.dataType, queryId) + }); + } + transformFetch(node, queryId) { + return requireAllProps({ + kind: "FetchNode", + rowCount: this.transformNode(node.rowCount, queryId), + modifier: node.modifier + }); + } + transformTop(node, _queryId2) { + return requireAllProps({ + kind: "TopNode", + expression: node.expression, + modifiers: node.modifiers + }); + } + transformOutput(node, queryId) { + return requireAllProps({ + kind: "OutputNode", + selections: this.transformNodeList(node.selections, queryId) + }); + } + transformDataType(node, _queryId2) { + return node; + } + transformSelectAll(node, _queryId2) { + return node; + } + transformIdentifier(node, _queryId2) { + return node; + } + transformValue(node, _queryId2) { + return node; + } + transformPrimitiveValueList(node, _queryId2) { + return node; + } + transformOperator(node, _queryId2) { + return node; + } + transformDefaultInsertValue(node, _queryId2) { + return node; + } + transformOrAction(node, _queryId2) { + return node; + } + transformCollate(node, _queryId2) { + return node; + } + }; + _transformers = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js +var ROOT_OPERATION_NODES, SCHEMALESS_FUNCTIONS, _schema, _schemableIds, _ctes, _WithSchemaTransformer_instances, transformTableArgsWithoutSchemas_fn, isRootOperationNode_fn, collectSchemableIds_fn, collectCTEs_fn, collectSchemableIdsFromTableExpr_fn, collectSchemableId_fn, collectCTEIds_fn, WithSchemaTransformer; +var init_with_schema_transformer = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js"() { + init_alias_node(); + init_identifier_node(); + init_join_node(); + init_list_node(); + init_operation_node_transformer(); + init_schemable_identifier_node(); + init_table_node(); + init_using_node(); + init_object_utils(); + ROOT_OPERATION_NODES = freeze({ + AlterTableNode: true, + CreateIndexNode: true, + CreateSchemaNode: true, + CreateTableNode: true, + CreateTypeNode: true, + CreateViewNode: true, + RefreshMaterializedViewNode: true, + DeleteQueryNode: true, + DropIndexNode: true, + DropSchemaNode: true, + DropTableNode: true, + DropTypeNode: true, + DropViewNode: true, + InsertQueryNode: true, + RawNode: true, + SelectQueryNode: true, + UpdateQueryNode: true, + MergeQueryNode: true + }); + SCHEMALESS_FUNCTIONS = { + json_agg: true, + to_json: true + }; + WithSchemaTransformer = class extends OperationNodeTransformer { + constructor(schema3) { + super(); + __privateAdd(this, _WithSchemaTransformer_instances); + __privateAdd(this, _schema); + __privateAdd(this, _schemableIds, /* @__PURE__ */ new Set()); + __privateAdd(this, _ctes, /* @__PURE__ */ new Set()); + __privateSet(this, _schema, schema3); + } + transformNodeImpl(node, queryId) { + if (!__privateMethod(this, _WithSchemaTransformer_instances, isRootOperationNode_fn).call(this, node)) { + return super.transformNodeImpl(node, queryId); + } + const ctes = __privateMethod(this, _WithSchemaTransformer_instances, collectCTEs_fn).call(this, node); + for (const cte of ctes) { + __privateGet(this, _ctes).add(cte); + } + const tables = __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIds_fn).call(this, node); + for (const table of tables) { + __privateGet(this, _schemableIds).add(table); + } + const transformed = super.transformNodeImpl(node, queryId); + for (const table of tables) { + __privateGet(this, _schemableIds).delete(table); + } + for (const cte of ctes) { + __privateGet(this, _ctes).delete(cte); + } + return transformed; + } + transformSchemableIdentifier(node, queryId) { + const transformed = super.transformSchemableIdentifier(node, queryId); + if (transformed.schema || !__privateGet(this, _schemableIds).has(node.identifier.name)) { + return transformed; + } + return { + ...transformed, + schema: IdentifierNode.create(__privateGet(this, _schema)) + }; + } + transformReferences(node, queryId) { + const transformed = super.transformReferences(node, queryId); + if (transformed.table.table.schema) { + return transformed; + } + return { + ...transformed, + table: TableNode.createWithSchema(__privateGet(this, _schema), transformed.table.table.identifier.name) + }; + } + transformAggregateFunction(node, queryId) { + return { + ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId), + aggregated: __privateMethod(this, _WithSchemaTransformer_instances, transformTableArgsWithoutSchemas_fn).call(this, node, queryId, "aggregated") + }; + } + transformFunction(node, queryId) { + return { + ...super.transformFunction({ ...node, arguments: [] }, queryId), + arguments: __privateMethod(this, _WithSchemaTransformer_instances, transformTableArgsWithoutSchemas_fn).call(this, node, queryId, "arguments") + }; + } + transformSelectModifier(node, queryId) { + return { + ...super.transformSelectModifier({ ...node, of: void 0 }, queryId), + of: node.of?.map((item) => TableNode.is(item) && !item.table.schema ? { + ...item, + table: this.transformIdentifier(item.table.identifier, queryId) + } : this.transformNode(item, queryId)) + }; + } + }; + _schema = new WeakMap(); + _schemableIds = new WeakMap(); + _ctes = new WeakMap(); + _WithSchemaTransformer_instances = new WeakSet(); + transformTableArgsWithoutSchemas_fn = function(node, queryId, argsKey) { + return SCHEMALESS_FUNCTIONS[node.func] ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema ? this.transformNode(arg, queryId) : { + ...arg, + table: this.transformIdentifier(arg.table.identifier, queryId) + }) : this.transformNodeList(node[argsKey], queryId); + }; + isRootOperationNode_fn = function(node) { + return node.kind in ROOT_OPERATION_NODES; + }; + collectSchemableIds_fn = function(node) { + const schemableIds = /* @__PURE__ */ new Set(); + if ("name" in node && node.name && SchemableIdentifierNode.is(node.name)) { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableId_fn).call(this, node.name, schemableIds); + } + if ("from" in node && node.from) { + for (const from of node.from.froms) { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, from, schemableIds); + } + } + if ("into" in node && node.into) { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, node.into, schemableIds); + } + if ("table" in node && node.table) { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, node.table, schemableIds); + } + if ("joins" in node && node.joins) { + for (const join2 of node.joins) { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, join2.table, schemableIds); + } + } + if ("using" in node && node.using) { + if (JoinNode.is(node.using)) { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, node.using.table, schemableIds); + } else { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, node.using, schemableIds); + } + } + return schemableIds; + }; + collectCTEs_fn = function(node) { + const ctes = /* @__PURE__ */ new Set(); + if ("with" in node && node.with) { + __privateMethod(this, _WithSchemaTransformer_instances, collectCTEIds_fn).call(this, node.with, ctes); + } + return ctes; + }; + collectSchemableIdsFromTableExpr_fn = function(node, schemableIds) { + if (TableNode.is(node)) { + return __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableId_fn).call(this, node.table, schemableIds); + } + if (AliasNode.is(node) && TableNode.is(node.node)) { + return __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableId_fn).call(this, node.node.table, schemableIds); + } + if (ListNode.is(node)) { + for (const table of node.items) { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, table, schemableIds); + } + return; + } + if (UsingNode.is(node)) { + for (const table of node.tables) { + __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, table, schemableIds); + } + return; + } + }; + collectSchemableId_fn = function(node, schemableIds) { + const id = node.identifier.name; + if (!__privateGet(this, _schemableIds).has(id) && !__privateGet(this, _ctes).has(id)) { + schemableIds.add(id); + } + }; + collectCTEIds_fn = function(node, ctes) { + for (const expr of node.expressions) { + const cteId = expr.name.table.table.identifier.name; + if (!__privateGet(this, _ctes).has(cteId)) { + ctes.add(cteId); + } + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js +var _transformer, WithSchemaPlugin; +var init_with_schema_plugin = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js"() { + init_with_schema_transformer(); + WithSchemaPlugin = class { + constructor(schema3) { + __privateAdd(this, _transformer); + __privateSet(this, _transformer, new WithSchemaTransformer(schema3)); + } + transformQuery(args) { + return __privateGet(this, _transformer).transformNode(args.node, args.queryId); + } + async transformResult(args) { + return args.result; + } + }; + _transformer = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js +var MatchedNode; +var init_matched_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js"() { + init_object_utils(); + MatchedNode = freeze({ + is(node) { + return node.kind === "MatchedNode"; + }, + create(not, bySource = false) { + return freeze({ + kind: "MatchedNode", + not, + bySource + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js +function parseMergeWhen(type, args, refRight) { + return WhenNode.create(parseFilterList([ + MatchedNode.create(!type.isMatched, type.bySource), + ...args && args.length > 0 ? [ + args.length === 3 && refRight ? parseReferentialBinaryOperation(args[0], args[1], args[2]) : parseValueBinaryOperationOrExpression(args) + ] : [] + ], "and", false)); +} +function parseMergeThen(result) { + if (isString2(result)) { + return RawNode.create([result], []); + } + if (isOperationNodeSource(result)) { + return result.toOperationNode(); + } + return result; +} +var init_merge_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js"() { + init_matched_node(); + init_operation_node_source(); + init_raw_node(); + init_when_node(); + init_object_utils(); + init_binary_operation_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js +var _promise2, _resolve, _reject, Deferred; +var init_deferred = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js"() { + Deferred = class { + constructor() { + __privateAdd(this, _promise2); + __privateAdd(this, _resolve); + __privateAdd(this, _reject); + __publicField(this, "resolve", (value) => { + if (__privateGet(this, _resolve)) { + __privateGet(this, _resolve).call(this, value); + } + }); + __publicField(this, "reject", (reason) => { + if (__privateGet(this, _reject)) { + __privateGet(this, _reject).call(this, reason); + } + }); + __privateSet(this, _promise2, new Promise((resolve2, reject) => { + __privateSet(this, _reject, reject); + __privateSet(this, _resolve, resolve2); + })); + } + get promise() { + return __privateGet(this, _promise2); + } + }; + _promise2 = new WeakMap(); + _resolve = new WeakMap(); + _reject = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js +async function provideControlledConnection(connectionProvider) { + const connectionDefer = new Deferred(); + const connectionReleaseDefer = new Deferred(); + connectionProvider.provideConnection(async (connection) => { + connectionDefer.resolve(connection); + return await connectionReleaseDefer.promise; + }).catch((ex) => connectionDefer.reject(ex)); + return freeze({ + connection: await connectionDefer.promise, + release: connectionReleaseDefer.resolve + }); +} +var init_provide_controlled_connection = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js"() { + init_deferred(); + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js +var NO_PLUGINS, _plugins, _QueryExecutorBase_instances, transformResult_fn, QueryExecutorBase; +var init_query_executor_base = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js"() { + init_object_utils(); + init_provide_controlled_connection(); + init_log_once(); + NO_PLUGINS = freeze([]); + QueryExecutorBase = class { + constructor(plugins = NO_PLUGINS) { + __privateAdd(this, _QueryExecutorBase_instances); + __privateAdd(this, _plugins); + __privateSet(this, _plugins, plugins); + } + get plugins() { + return __privateGet(this, _plugins); + } + transformQuery(node, queryId) { + for (const plugin of __privateGet(this, _plugins)) { + const transformedNode = plugin.transformQuery({ node, queryId }); + if (transformedNode.kind === node.kind) { + node = transformedNode; + } else { + throw new Error([ + `KyselyPlugin.transformQuery must return a node`, + `of the same kind that was given to it.`, + `The plugin was given a ${node.kind}`, + `but it returned a ${transformedNode.kind}` + ].join(" ")); + } + } + return node; + } + async executeQuery(compiledQuery) { + return await this.provideConnection(async (connection) => { + const result = await connection.executeQuery(compiledQuery); + if ("numUpdatedOrDeletedRows" in result) { + logOnce("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`."); + } + return await __privateMethod(this, _QueryExecutorBase_instances, transformResult_fn).call(this, result, compiledQuery.queryId); + }); + } + async *stream(compiledQuery, chunkSize) { + const { connection, release } = await provideControlledConnection(this); + try { + for await (const result of connection.streamQuery(compiledQuery, chunkSize)) { + yield await __privateMethod(this, _QueryExecutorBase_instances, transformResult_fn).call(this, result, compiledQuery.queryId); + } + } finally { + release(); + } + } + }; + _plugins = new WeakMap(); + _QueryExecutorBase_instances = new WeakSet(); + transformResult_fn = async function(result, queryId) { + for (const plugin of __privateGet(this, _plugins)) { + result = await plugin.transformResult({ result, queryId }); + } + return result; + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js +var NoopQueryExecutor, NOOP_QUERY_EXECUTOR; +var init_noop_query_executor = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js"() { + init_query_executor_base(); + NoopQueryExecutor = class _NoopQueryExecutor extends QueryExecutorBase { + get adapter() { + throw new Error("this query cannot be compiled to SQL"); + } + compileQuery() { + throw new Error("this query cannot be compiled to SQL"); + } + provideConnection() { + throw new Error("this query cannot be executed"); + } + withConnectionProvider() { + throw new Error("this query cannot have a connection provider"); + } + withPlugin(plugin) { + return new _NoopQueryExecutor([...this.plugins, plugin]); + } + withPlugins(plugins) { + return new _NoopQueryExecutor([...this.plugins, ...plugins]); + } + withPluginAtFront(plugin) { + return new _NoopQueryExecutor([plugin, ...this.plugins]); + } + withoutPlugins() { + return new _NoopQueryExecutor([]); + } + }; + NOOP_QUERY_EXECUTOR = new NoopQueryExecutor(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js +var MergeResult; +var init_merge_result = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js"() { + MergeResult = class { + constructor(numChangedRows) { + __publicField(this, "numChangedRows"); + this.numChangedRows = numChangedRows; + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js +var _props11, _MergeQueryBuilder, MergeQueryBuilder, _props12, _WheneableMergeQueryBuilder_instances, whenMatched_fn, whenNotMatched_fn, _WheneableMergeQueryBuilder, WheneableMergeQueryBuilder, _props13, MatchedThenableMergeQueryBuilder, _props14, NotMatchedThenableMergeQueryBuilder; +var init_merge_query_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js"() { + init_insert_query_node(); + init_merge_query_node(); + init_query_node(); + init_update_query_node(); + init_insert_values_parser(); + init_join_parser(); + init_merge_parser(); + init_select_parser(); + init_top_parser(); + init_noop_query_executor(); + init_object_utils(); + init_merge_result(); + init_no_result_error(); + init_update_query_builder(); + _MergeQueryBuilder = class _MergeQueryBuilder { + constructor(props) { + __privateAdd(this, _props11); + __privateSet(this, _props11, freeze(props)); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db + * .mergeInto('person') + * .using('pet', 'pet.owner_id', 'person.id') + * .whenMatched() + * .thenDelete() + * .modifyEnd(sql.raw('-- this is a comment')) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment + * ``` + */ + modifyEnd(modifier) { + return new _MergeQueryBuilder({ + ...__privateGet(this, _props11), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props11).queryNode, modifier.toOperationNode()) + }); + } + /** + * Changes a `merge into` query to an `merge top into` query. + * + * `top` clause is only supported by some dialects like MS SQL Server. + * + * ### Examples + * + * Affect 5 matched rows at most: + * + * ```ts + * await db.mergeInto('person') + * .top(5) + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDelete() + * .execute() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * merge top(5) into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * delete + * ``` + * + * Affect 50% of matched rows: + * + * ```ts + * await db.mergeInto('person') + * .top(50, 'percent') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDelete() + * .execute() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * merge top(50) percent into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * delete + * ``` + */ + top(expression, modifiers) { + return new _MergeQueryBuilder({ + ...__privateGet(this, _props11), + queryNode: QueryNode.cloneWithTop(__privateGet(this, _props11).queryNode, parseTop(expression, modifiers)) + }); + } + using(...args) { + return new WheneableMergeQueryBuilder({ + ...__privateGet(this, _props11), + queryNode: MergeQueryNode.cloneWithUsing(__privateGet(this, _props11).queryNode, parseJoin("Using", args)) + }); + } + returning(args) { + return new _MergeQueryBuilder({ + ...__privateGet(this, _props11), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props11).queryNode, parseSelectArg(args)) + }); + } + returningAll(table) { + return new _MergeQueryBuilder({ + ...__privateGet(this, _props11), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props11).queryNode, parseSelectAll(table)) + }); + } + output(args) { + return new _MergeQueryBuilder({ + ...__privateGet(this, _props11), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props11).queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _MergeQueryBuilder({ + ...__privateGet(this, _props11), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props11).queryNode, parseSelectAll(table)) + }); + } + }; + _props11 = new WeakMap(); + MergeQueryBuilder = _MergeQueryBuilder; + _WheneableMergeQueryBuilder = class _WheneableMergeQueryBuilder { + constructor(props) { + __privateAdd(this, _WheneableMergeQueryBuilder_instances); + __privateAdd(this, _props12); + __privateSet(this, _props12, freeze(props)); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db + * .mergeInto('person') + * .using('pet', 'pet.owner_id', 'person.id') + * .whenMatched() + * .thenDelete() + * .modifyEnd(sql.raw('-- this is a comment')) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment + * ``` + */ + modifyEnd(modifier) { + return new _WheneableMergeQueryBuilder({ + ...__privateGet(this, _props12), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props12).queryNode, modifier.toOperationNode()) + }); + } + /** + * See {@link MergeQueryBuilder.top}. + */ + top(expression, modifiers) { + return new _WheneableMergeQueryBuilder({ + ...__privateGet(this, _props12), + queryNode: QueryNode.cloneWithTop(__privateGet(this, _props12).queryNode, parseTop(expression, modifiers)) + }); + } + /** + * Adds a simple `when matched` clause to the query. + * + * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}. + * + * For a simple `when not matched` clause, see {@link whenNotMatched}. + * + * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDelete() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * delete + * ``` + */ + whenMatched() { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenMatched_fn).call(this, []); + } + whenMatchedAnd(...args) { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenMatched_fn).call(this, args); + } + /** + * Adds the `when matched` clause to the query with an `and` condition. But unlike + * {@link whenMatchedAnd}, this method accepts a column reference as the 3rd argument. + * + * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation + * for that method for more examples. + */ + whenMatchedAndRef(lhs, op, rhs) { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenMatched_fn).call(this, [lhs, op, rhs], true); + } + /** + * Adds a simple `when not matched` clause to the query. + * + * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}. + * + * For a simple `when matched` clause, see {@link whenMatched}. + * + * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenNotMatched() + * .thenInsertValues({ + * first_name: 'John', + * last_name: 'Doe', + * }) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when not matched then + * insert ("first_name", "last_name") values ($1, $2) + * ``` + */ + whenNotMatched() { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, []); + } + whenNotMatchedAnd(...args) { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, args); + } + /** + * Adds the `when not matched` clause to the query with an `and` condition. But unlike + * {@link whenNotMatchedAnd}, this method accepts a column reference as the 3rd argument. + * + * Unlike {@link whenMatchedAndRef}, you cannot reference columns from the target table. + * + * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation + * for that method for more examples. + */ + whenNotMatchedAndRef(lhs, op, rhs) { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, [lhs, op, rhs], true); + } + /** + * Adds a simple `when not matched by source` clause to the query. + * + * Supported in MS SQL Server. + * + * Similar to {@link whenNotMatched}, but returns a {@link MatchedThenableMergeQueryBuilder}. + */ + whenNotMatchedBySource() { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, [], false, true); + } + whenNotMatchedBySourceAnd(...args) { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, args, false, true); + } + /** + * Adds the `when not matched by source` clause to the query with an `and` condition. + * + * Similar to {@link whenNotMatchedAndRef}, but you can reference columns from + * the target table, and not from source table and returns a {@link MatchedThenableMergeQueryBuilder}. + */ + whenNotMatchedBySourceAndRef(lhs, op, rhs) { + return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, [lhs, op, rhs], true, true); + } + returning(args) { + return new _WheneableMergeQueryBuilder({ + ...__privateGet(this, _props12), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props12).queryNode, parseSelectArg(args)) + }); + } + returningAll(table) { + return new _WheneableMergeQueryBuilder({ + ...__privateGet(this, _props12), + queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props12).queryNode, parseSelectAll(table)) + }); + } + output(args) { + return new _WheneableMergeQueryBuilder({ + ...__privateGet(this, _props12), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props12).queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _WheneableMergeQueryBuilder({ + ...__privateGet(this, _props12), + queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props12).queryNode, parseSelectAll(table)) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + * + * If you want to conditionally call a method on `this`, see + * the {@link $if} method. + * + * ### Examples + * + * The next example uses a helper function `log` to log a query: + * + * ```ts + * import type { Compilable } from 'kysely' + * + * function log(qb: T): T { + * console.log(qb.compile()) + * return qb + * } + * + * await db.updateTable('person') + * .set({ first_name: 'John' }) + * .$call(log) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + /** + * Call `func(this)` if `condition` is true. + * + * This method is especially handy with optional selects. Any `returning` or `returningAll` + * method calls add columns as optional fields to the output type when called inside + * the `func` callback. This is because we can't know if those selections were actually + * made before running the code. + * + * You can also call any other methods inside the callback. + * + * ### Examples + * + * ```ts + * import type { PersonUpdate } from 'type-editor' // imaginary module + * + * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) { + * return await db + * .updateTable('person') + * .set(updates) + * .where('id', '=', id) + * .returning(['id', 'first_name']) + * .$if(returnLastName, (qb) => qb.returning('last_name')) + * .executeTakeFirstOrThrow() + * } + * ``` + * + * Any selections added inside the `if` callback will be added as optional fields to the + * output type since we can't know if the selections were actually made before running + * the code. In the example above the return type of the `updatePerson` function is: + * + * ```ts + * Promise<{ + * id: number + * first_name: string + * last_name?: string + * }> + * ``` + */ + $if(condition, func) { + if (condition) { + return func(this); + } + return new _WheneableMergeQueryBuilder({ + ...__privateGet(this, _props12) + }); + } + toOperationNode() { + return __privateGet(this, _props12).executor.transformQuery(__privateGet(this, _props12).queryNode, __privateGet(this, _props12).queryId); + } + compile() { + return __privateGet(this, _props12).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props12).queryId); + } + /** + * Executes the query and returns an array of rows. + * + * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. + */ + async execute() { + const compiledQuery = this.compile(); + const result = await __privateGet(this, _props12).executor.executeQuery(compiledQuery); + const { adapter } = __privateGet(this, _props12).executor; + const query = compiledQuery.query; + if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { + return result.rows; + } + return [new MergeResult(result.numAffectedRows)]; + } + /** + * Executes the query and returns the first result or undefined if + * the query returned no result. + */ + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + /** + * Executes the query and returns the first result or throws if + * the query returned no result. + * + * By default an instance of {@link NoResultError} is thrown, but you can + * provide a custom error class, or callback as the only argument to throw a different + * error. + */ + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error49; + } + return result; + } + }; + _props12 = new WeakMap(); + _WheneableMergeQueryBuilder_instances = new WeakSet(); + whenMatched_fn = function(args, refRight) { + return new MatchedThenableMergeQueryBuilder({ + ...__privateGet(this, _props12), + queryNode: MergeQueryNode.cloneWithWhen(__privateGet(this, _props12).queryNode, parseMergeWhen({ isMatched: true }, args, refRight)) + }); + }; + whenNotMatched_fn = function(args, refRight = false, bySource = false) { + const props = { + ...__privateGet(this, _props12), + queryNode: MergeQueryNode.cloneWithWhen(__privateGet(this, _props12).queryNode, parseMergeWhen({ isMatched: false, bySource }, args, refRight)) + }; + const Builder = bySource ? MatchedThenableMergeQueryBuilder : NotMatchedThenableMergeQueryBuilder; + return new Builder(props); + }; + WheneableMergeQueryBuilder = _WheneableMergeQueryBuilder; + MatchedThenableMergeQueryBuilder = class { + constructor(props) { + __privateAdd(this, _props13); + __privateSet(this, _props13, freeze(props)); + } + /** + * Performs the `delete` action. + * + * To perform the `do nothing` action, see {@link thenDoNothing}. + * + * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDelete() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * delete + * ``` + */ + thenDelete() { + return new WheneableMergeQueryBuilder({ + ...__privateGet(this, _props13), + queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props13).queryNode, parseMergeThen("delete")) + }); + } + /** + * Performs the `do nothing` action. + * + * This is supported in PostgreSQL. + * + * To perform the `delete` action, see {@link thenDelete}. + * + * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDoNothing() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * do nothing + * ``` + */ + thenDoNothing() { + return new WheneableMergeQueryBuilder({ + ...__privateGet(this, _props13), + queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props13).queryNode, parseMergeThen("do nothing")) + }); + } + /** + * Perform an `update` operation with a full-fledged {@link UpdateQueryBuilder}. + * This is handy when multiple `set` invocations are needed. + * + * For a shorthand version of this method, see {@link thenUpdateSet}. + * + * To perform the `delete` action, see {@link thenDelete}. + * + * To perform the `do nothing` action, see {@link thenDoNothing}. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenUpdate((ub) => ub + * .set(sql`metadata['has_pets']`, 'Y') + * .set({ + * updated_at: new Date().toISOString(), + * }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * update set metadata['has_pets'] = $1, "updated_at" = $2 + * ``` + */ + thenUpdate(set2) { + return new WheneableMergeQueryBuilder({ + ...__privateGet(this, _props13), + queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props13).queryNode, parseMergeThen(set2(new UpdateQueryBuilder({ + queryId: __privateGet(this, _props13).queryId, + executor: NOOP_QUERY_EXECUTOR, + queryNode: UpdateQueryNode.createWithoutTable() + })))) + }); + } + thenUpdateSet(...args) { + return this.thenUpdate((ub) => ub.set(...args)); + } + }; + _props13 = new WeakMap(); + NotMatchedThenableMergeQueryBuilder = class { + constructor(props) { + __privateAdd(this, _props14); + __privateSet(this, _props14, freeze(props)); + } + /** + * Performs the `do nothing` action. + * + * This is supported in PostgreSQL. + * + * To perform the `insert` action, see {@link thenInsertValues}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenNotMatched() + * .thenDoNothing() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when not matched then + * do nothing + * ``` + */ + thenDoNothing() { + return new WheneableMergeQueryBuilder({ + ...__privateGet(this, _props14), + queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props14).queryNode, parseMergeThen("do nothing")) + }); + } + thenInsertValues(insert) { + const [columns, values] = parseInsertExpression(insert); + return new WheneableMergeQueryBuilder({ + ...__privateGet(this, _props14), + queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props14).queryNode, parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(), { + columns, + values + }))) + }); + } + }; + _props14 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js +var _props15, _QueryCreator, QueryCreator; +var init_query_creator = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js"() { + init_select_query_builder(); + init_insert_query_builder(); + init_delete_query_builder(); + init_update_query_builder(); + init_delete_query_node(); + init_insert_query_node(); + init_select_query_node(); + init_update_query_node(); + init_table_parser(); + init_with_parser(); + init_with_node(); + init_query_id(); + init_with_schema_plugin(); + init_object_utils(); + init_select_parser(); + init_merge_query_builder(); + init_merge_query_node(); + _QueryCreator = class _QueryCreator { + constructor(props) { + __privateAdd(this, _props15); + __privateSet(this, _props15, freeze(props)); + } + /** + * Creates a `select` query builder for the given table or tables. + * + * The tables passed to this method are built as the query's `from` clause. + * + * ### Examples + * + * Create a select query for one table: + * + * ```ts + * db.selectFrom('person').selectAll() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select * from "person" + * ``` + * + * Create a select query for one table with an alias: + * + * ```ts + * const persons = await db.selectFrom('person as p') + * .select(['p.id', 'first_name']) + * .execute() + * + * console.log(persons[0].id) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "p"."id", "first_name" from "person" as "p" + * ``` + * + * Create a select query from a subquery: + * + * ```ts + * const persons = await db.selectFrom( + * (eb) => eb.selectFrom('person').select('person.id as identifier').as('p') + * ) + * .select('p.identifier') + * .execute() + * + * console.log(persons[0].identifier) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "p"."identifier", + * from ( + * select "person"."id" as "identifier" from "person" + * ) as p + * ``` + * + * Create a select query from raw sql: + * + * ```ts + * import { sql } from 'kysely' + * + * const items = await db + * .selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q')) + * .select('q.one') + * .execute() + * + * console.log(items[0].one) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "q"."one", + * from ( + * select 1 as one + * ) as q + * ``` + * + * When you use the `sql` tag you need to also provide the result type of the + * raw snippet / query so that Kysely can figure out what columns are + * available for the rest of the query. + * + * The `selectFrom` method also accepts an array for multiple tables. All + * the above examples can also be used in an array. + * + * ```ts + * import { sql } from 'kysely' + * + * const items = await db.selectFrom([ + * 'person as p', + * db.selectFrom('pet').select('pet.species').as('a'), + * sql<{ one: number }>`(select 1 as one)`.as('q') + * ]) + * .select(['p.id', 'a.species', 'q.one']) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "p".id, "a"."species", "q"."one" + * from + * "person" as "p", + * (select "pet"."species" from "pet") as a, + * (select 1 as one) as "q" + * ``` + */ + selectFrom(from) { + return createSelectQueryBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _props15).executor, + queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(from), __privateGet(this, _props15).withNode) + }); + } + selectNoFrom(selection) { + return createSelectQueryBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _props15).executor, + queryNode: SelectQueryNode.cloneWithSelections(SelectQueryNode.create(__privateGet(this, _props15).withNode), parseSelectArg(selection)) + }); + } + /** + * Creates an insert query. + * + * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult} + * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of + * the inserted row if the db returned one. + * + * See the {@link InsertQueryBuilder.values | values} method for more info and examples. Also see + * the {@link ReturningInterface.returning | returning} method for a way to return columns + * on supported databases like PostgreSQL. + * + * ### Examples + * + * ```ts + * const result = await db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston' + * }) + * .executeTakeFirst() + * + * console.log(result.insertId) + * ``` + * + * Some databases like PostgreSQL support the `returning` method: + * + * ```ts + * const { id } = await db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston' + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * ``` + */ + insertInto(table) { + return new InsertQueryBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _props15).executor, + queryNode: InsertQueryNode.create(parseTable(table), __privateGet(this, _props15).withNode) + }); + } + /** + * Creates a "replace into" query. + * + * This is only supported by some dialects like MySQL or SQLite. + * + * Similar to MySQL's {@link InsertQueryBuilder.onDuplicateKeyUpdate} that deletes + * and inserts values on collision instead of updating existing rows. + * + * An alias of SQLite's {@link InsertQueryBuilder.orReplace}. + * + * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult} + * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of + * the inserted row if the db returned one. + * + * See the {@link InsertQueryBuilder.values | values} method for more info and examples. + * + * ### Examples + * + * ```ts + * const result = await db + * .replaceInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston' + * }) + * .executeTakeFirstOrThrow() + * + * console.log(result.insertId) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * replace into `person` (`first_name`, `last_name`) values (?, ?) + * ``` + */ + replaceInto(table) { + return new InsertQueryBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _props15).executor, + queryNode: InsertQueryNode.create(parseTable(table), __privateGet(this, _props15).withNode, true) + }); + } + /** + * Creates a delete query. + * + * See the {@link DeleteQueryBuilder.where} method for examples on how to specify + * a where clause for the delete operation. + * + * The return value of the query is an instance of {@link DeleteResult}. + * + * ### Examples + * + * + * + * Delete a single row: + * + * ```ts + * const result = await db + * .deleteFrom('person') + * .where('person.id', '=', 1) + * .executeTakeFirst() + * + * console.log(result.numDeletedRows) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * delete from "person" where "person"."id" = $1 + * ``` + * + * Some databases such as MySQL support deleting from multiple tables: + * + * ```ts + * const result = await db + * .deleteFrom(['person', 'pet']) + * .using('person') + * .innerJoin('pet', 'pet.owner_id', 'person.id') + * .where('person.id', '=', 1) + * .executeTakeFirst() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * delete from `person`, `pet` + * using `person` + * inner join `pet` on `pet`.`owner_id` = `person`.`id` + * where `person`.`id` = ? + * ``` + */ + deleteFrom(from) { + return new DeleteQueryBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _props15).executor, + queryNode: DeleteQueryNode.create(parseTableExpressionOrList(from), __privateGet(this, _props15).withNode) + }); + } + /** + * Creates an update query. + * + * See the {@link UpdateQueryBuilder.where} method for examples on how to specify + * a where clause for the update operation. + * + * See the {@link UpdateQueryBuilder.set} method for examples on how to + * specify the updates. + * + * The return value of the query is an {@link UpdateResult}. + * + * ### Examples + * + * ```ts + * const result = await db + * .updateTable('person') + * .set({ first_name: 'Jennifer' }) + * .where('person.id', '=', 1) + * .executeTakeFirst() + * + * console.log(result.numUpdatedRows) + * ``` + */ + updateTable(tables) { + return new UpdateQueryBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _props15).executor, + queryNode: UpdateQueryNode.create(parseTableExpressionOrList(tables), __privateGet(this, _props15).withNode) + }); + } + /** + * Creates a merge query. + * + * The return value of the query is a {@link MergeResult}. + * + * See the {@link MergeQueryBuilder.using} method for examples on how to specify + * the other table. + * + * ### Examples + * + * + * + * Update a target column based on the existence of a source row: + * + * ```ts + * const result = await db + * .mergeInto('person as target') + * .using('pet as source', 'source.owner_id', 'target.id') + * .whenMatchedAnd('target.has_pets', '!=', 'Y') + * .thenUpdateSet({ has_pets: 'Y' }) + * .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y') + * .thenUpdateSet({ has_pets: 'N' }) + * .executeTakeFirstOrThrow() + * + * console.log(result.numChangedRows) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" + * on "pet"."owner_id" = "person"."id" + * when matched and "has_pets" != $1 + * then update set "has_pets" = $2 + * when not matched by source and "has_pets" = $3 + * then update set "has_pets" = $4 + * ``` + * + * + * + * Merge new entries from a temporary changes table: + * + * ```ts + * const result = await db + * .mergeInto('wine as target') + * .using( + * 'wine_stock_change as source', + * 'source.wine_name', + * 'target.name', + * ) + * .whenNotMatchedAnd('source.stock_delta', '>', 0) + * .thenInsertValues(({ ref }) => ({ + * name: ref('source.wine_name'), + * stock: ref('source.stock_delta'), + * })) + * .whenMatchedAnd( + * (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')), + * '>', + * 0, + * ) + * .thenUpdateSet('stock', (eb) => + * eb('target.stock', '+', eb.ref('source.stock_delta')), + * ) + * .whenMatched() + * .thenDelete() + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "wine" as "target" + * using "wine_stock_change" as "source" + * on "source"."wine_name" = "target"."name" + * when not matched and "source"."stock_delta" > $1 + * then insert ("name", "stock") values ("source"."wine_name", "source"."stock_delta") + * when matched and "target"."stock" + "source"."stock_delta" > $2 + * then update set "stock" = "target"."stock" + "source"."stock_delta" + * when matched + * then delete + * ``` + */ + mergeInto(targetTable) { + return new MergeQueryBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _props15).executor, + queryNode: MergeQueryNode.create(parseAliasedTable(targetTable), __privateGet(this, _props15).withNode) + }); + } + /** + * Creates a `with` query (Common Table Expression). + * + * ### Examples + * + * + * + * Common table expressions (CTE) are a great way to modularize complex queries. + * Essentially they allow you to run multiple separate queries within a + * single roundtrip to the DB. + * + * Since CTEs are a part of the main query, query optimizers inside DB + * engines are able to optimize the overall query. For example, postgres + * is able to inline the CTEs inside the using queries if it decides it's + * faster. + * + * ```ts + * const result = await db + * // Create a CTE called `jennifers` that selects all + * // persons named 'Jennifer'. + * .with('jennifers', (db) => db + * .selectFrom('person') + * .where('first_name', '=', 'Jennifer') + * .select(['id', 'age']) + * ) + * // Select all rows from the `jennifers` CTE and + * // further filter it. + * .with('adult_jennifers', (db) => db + * .selectFrom('jennifers') + * .where('age', '>', 18) + * .select(['id', 'age']) + * ) + * // Finally select all adult jennifers that are + * // also younger than 60. + * .selectFrom('adult_jennifers') + * .where('age', '<', 60) + * .selectAll() + * .execute() + * ``` + * + * + * + * Some databases like postgres also allow you to run other queries than selects + * in CTEs. On these databases CTEs are extremely powerful: + * + * ```ts + * const result = await db + * .with('new_person', (db) => db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * age: 35, + * }) + * .returning('id') + * ) + * .with('new_pet', (db) => db + * .insertInto('pet') + * .values({ + * name: 'Doggo', + * species: 'dog', + * is_favorite: true, + * // Use the id of the person we just inserted. + * owner_id: db + * .selectFrom('new_person') + * .select('id') + * }) + * .returning('id') + * ) + * .selectFrom(['new_person', 'new_pet']) + * .select([ + * 'new_person.id as person_id', + * 'new_pet.id as pet_id' + * ]) + * .execute() + * ``` + * + * The CTE name can optionally specify column names in addition to + * a name. In that case Kysely requires the expression to retun + * rows with the same columns. + * + * ```ts + * await db + * .with('jennifers(id, age)', (db) => db + * .selectFrom('person') + * .where('first_name', '=', 'Jennifer') + * // This is ok since we return columns with the same + * // names as specified by `jennifers(id, age)`. + * .select(['id', 'age']) + * ) + * .selectFrom('jennifers') + * .selectAll() + * .execute() + * ``` + * + * The first argument can also be a callback. The callback is passed + * a `CTEBuilder` instance that can be used to configure the CTE: + * + * ```ts + * await db + * .with( + * (cte) => cte('jennifers').materialized(), + * (db) => db + * .selectFrom('person') + * .where('first_name', '=', 'Jennifer') + * .select(['id', 'age']) + * ) + * .selectFrom('jennifers') + * .selectAll() + * .execute() + * ``` + */ + with(nameOrBuilder, expression) { + const cte = parseCommonTableExpression(nameOrBuilder, expression); + return new _QueryCreator({ + ...__privateGet(this, _props15), + withNode: __privateGet(this, _props15).withNode ? WithNode.cloneWithExpression(__privateGet(this, _props15).withNode, cte) : WithNode.create(cte) + }); + } + /** + * Creates a recursive `with` query (Common Table Expression). + * + * Note that recursiveness is a property of the whole `with` statement. + * You cannot have recursive and non-recursive CTEs in a same `with` statement. + * Therefore the recursiveness is determined by the **first** `with` or + * `withRecusive` call you make. + * + * See the {@link with} method for examples and more documentation. + */ + withRecursive(nameOrBuilder, expression) { + const cte = parseCommonTableExpression(nameOrBuilder, expression); + return new _QueryCreator({ + ...__privateGet(this, _props15), + withNode: __privateGet(this, _props15).withNode ? WithNode.cloneWithExpression(__privateGet(this, _props15).withNode, cte) : WithNode.create(cte, { recursive: true }) + }); + } + /** + * Returns a copy of this query creator instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _QueryCreator({ + ...__privateGet(this, _props15), + executor: __privateGet(this, _props15).executor.withPlugin(plugin) + }); + } + /** + * Returns a copy of this query creator instance without any plugins. + */ + withoutPlugins() { + return new _QueryCreator({ + ...__privateGet(this, _props15), + executor: __privateGet(this, _props15).executor.withoutPlugins() + }); + } + /** + * Sets the schema to be used for all table references that don't explicitly + * specify a schema. + * + * This only affects the query created through the builder returned from + * this method and doesn't modify the `db` instance. + * + * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0007-schemas.md) + * for a more detailed explanation. + * + * ### Examples + * + * ``` + * await db + * .withSchema('mammals') + * .selectFrom('pet') + * .selectAll() + * .innerJoin('public.person', 'public.person.id', 'pet.owner_id') + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select * from "mammals"."pet" + * inner join "public"."person" + * on "public"."person"."id" = "mammals"."pet"."owner_id" + * ``` + * + * `withSchema` is smart enough to not add schema for aliases, + * common table expressions or other places where the schema + * doesn't belong to: + * + * ``` + * await db + * .withSchema('mammals') + * .selectFrom('pet as p') + * .select('p.name') + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "p"."name" from "mammals"."pet" as "p" + * ``` + */ + withSchema(schema3) { + return new _QueryCreator({ + ...__privateGet(this, _props15), + executor: __privateGet(this, _props15).executor.withPluginAtFront(new WithSchemaPlugin(schema3)) + }); + } + }; + _props15 = new WeakMap(); + QueryCreator = _QueryCreator; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js +function createQueryCreator() { + return new QueryCreator({ + executor: NOOP_QUERY_EXECUTOR + }); +} +function createJoinBuilder(joinType, table) { + return new JoinBuilder({ + joinNode: JoinNode.create(joinType, parseTableExpression(table)) + }); +} +function createOverBuilder() { + return new OverBuilder({ + overNode: OverNode.create() + }); +} +var init_parse_utils = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js"() { + init_join_node(); + init_over_node(); + init_join_builder(); + init_over_builder(); + init_query_creator(); + init_noop_query_executor(); + init_table_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js +function parseJoin(joinType, args) { + if (args.length === 3) { + return parseSingleOnJoin(joinType, args[0], args[1], args[2]); + } else if (args.length === 2) { + return parseCallbackJoin(joinType, args[0], args[1]); + } else if (args.length === 1) { + return parseOnlessJoin(joinType, args[0]); + } else { + throw new Error("not implemented"); + } +} +function parseCallbackJoin(joinType, from, callback) { + return callback(createJoinBuilder(joinType, from)).toOperationNode(); +} +function parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) { + return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, "=", rhsColumn)); +} +function parseOnlessJoin(joinType, from) { + return JoinNode.create(joinType, parseTableExpression(from)); +} +var init_join_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js"() { + init_join_node(); + init_binary_operation_parser(); + init_parse_utils(); + init_table_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js +var OffsetNode; +var init_offset_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js"() { + init_object_utils(); + OffsetNode = freeze({ + is(node) { + return node.kind === "OffsetNode"; + }, + create(offset) { + return freeze({ + kind: "OffsetNode", + offset + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js +var GroupByItemNode; +var init_group_by_item_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js"() { + init_object_utils(); + GroupByItemNode = freeze({ + is(node) { + return node.kind === "GroupByItemNode"; + }, + create(groupBy2) { + return freeze({ + kind: "GroupByItemNode", + groupBy: groupBy2 + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js +function parseGroupBy(groupBy2) { + groupBy2 = isFunction3(groupBy2) ? groupBy2(expressionBuilder()) : groupBy2; + return parseReferenceExpressionOrList(groupBy2).map(GroupByItemNode.create); +} +var init_group_by_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js"() { + init_group_by_item_node(); + init_expression_builder(); + init_object_utils(); + init_reference_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js +var SetOperationNode; +var init_set_operation_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js"() { + init_object_utils(); + SetOperationNode = freeze({ + is(node) { + return node.kind === "SetOperationNode"; + }, + create(operator, expression, all) { + return freeze({ + kind: "SetOperationNode", + operator, + expression, + all + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js +function parseSetOperations(operator, expression, all) { + if (isFunction3(expression)) { + expression = expression(createExpressionBuilder()); + } + if (!isReadonlyArray(expression)) { + expression = [expression]; + } + return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all)); +} +var init_set_operation_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js"() { + init_expression_builder(); + init_set_operation_node(); + init_object_utils(); + init_expression_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js +var _node2, _ExpressionWrapper, ExpressionWrapper, _expr, _alias, AliasedExpressionWrapper, _node3, _OrWrapper, OrWrapper, _node4, _AndWrapper, AndWrapper; +var init_expression_wrapper = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js"() { + init_alias_node(); + init_and_node(); + init_identifier_node(); + init_operation_node_source(); + init_or_node(); + init_parens_node(); + init_binary_operation_parser(); + _ExpressionWrapper = class _ExpressionWrapper { + constructor(node) { + __privateAdd(this, _node2); + __privateSet(this, _node2, node); + } + /** @private */ + get expressionType() { + return void 0; + } + as(alias) { + return new AliasedExpressionWrapper(this, alias); + } + or(...args) { + return new OrWrapper(OrNode.create(__privateGet(this, _node2), parseValueBinaryOperationOrExpression(args))); + } + and(...args) { + return new AndWrapper(AndNode.create(__privateGet(this, _node2), parseValueBinaryOperationOrExpression(args))); + } + /** + * Change the output type of the expression. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `ExpressionWrapper` with a new output type. + */ + $castTo() { + return new _ExpressionWrapper(__privateGet(this, _node2)); + } + /** + * Omit null from the expression's type. + * + * This function can be useful in cases where you know an expression can't be + * null, but Kysely is unable to infer it. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of `this` with a new output type. + */ + $notNull() { + return new _ExpressionWrapper(__privateGet(this, _node2)); + } + toOperationNode() { + return __privateGet(this, _node2); + } + }; + _node2 = new WeakMap(); + ExpressionWrapper = _ExpressionWrapper; + AliasedExpressionWrapper = class { + constructor(expr, alias) { + __privateAdd(this, _expr); + __privateAdd(this, _alias); + __privateSet(this, _expr, expr); + __privateSet(this, _alias, alias); + } + /** @private */ + get expression() { + return __privateGet(this, _expr); + } + /** @private */ + get alias() { + return __privateGet(this, _alias); + } + toOperationNode() { + return AliasNode.create(__privateGet(this, _expr).toOperationNode(), isOperationNodeSource(__privateGet(this, _alias)) ? __privateGet(this, _alias).toOperationNode() : IdentifierNode.create(__privateGet(this, _alias))); + } + }; + _expr = new WeakMap(); + _alias = new WeakMap(); + _OrWrapper = class _OrWrapper { + constructor(node) { + __privateAdd(this, _node3); + __privateSet(this, _node3, node); + } + /** @private */ + get expressionType() { + return void 0; + } + as(alias) { + return new AliasedExpressionWrapper(this, alias); + } + or(...args) { + return new _OrWrapper(OrNode.create(__privateGet(this, _node3), parseValueBinaryOperationOrExpression(args))); + } + /** + * Change the output type of the expression. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `OrWrapper` with a new output type. + */ + $castTo() { + return new _OrWrapper(__privateGet(this, _node3)); + } + toOperationNode() { + return ParensNode.create(__privateGet(this, _node3)); + } + }; + _node3 = new WeakMap(); + OrWrapper = _OrWrapper; + _AndWrapper = class _AndWrapper { + constructor(node) { + __privateAdd(this, _node4); + __privateSet(this, _node4, node); + } + /** @private */ + get expressionType() { + return void 0; + } + as(alias) { + return new AliasedExpressionWrapper(this, alias); + } + and(...args) { + return new _AndWrapper(AndNode.create(__privateGet(this, _node4), parseValueBinaryOperationOrExpression(args))); + } + /** + * Change the output type of the expression. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `AndWrapper` with a new output type. + */ + $castTo() { + return new _AndWrapper(__privateGet(this, _node4)); + } + toOperationNode() { + return ParensNode.create(__privateGet(this, _node4)); + } + }; + _node4 = new WeakMap(); + AndWrapper = _AndWrapper; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js +var FetchNode; +var init_fetch_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js"() { + init_object_utils(); + init_value_node(); + FetchNode = freeze({ + is(node) { + return node.kind === "FetchNode"; + }, + create(rowCount, modifier) { + return { + kind: "FetchNode", + rowCount: ValueNode.create(rowCount), + modifier + }; + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js +function parseFetch(rowCount, modifier) { + if (!isNumber2(rowCount) && !isBigInt(rowCount)) { + throw new Error(`Invalid fetch row count: ${rowCount}`); + } + if (!isFetchModifier(modifier)) { + throw new Error(`Invalid fetch modifier: ${modifier}`); + } + return FetchNode.create(rowCount, modifier); +} +function isFetchModifier(value) { + return value === "only" || value === "with ties"; +} +var init_fetch_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js"() { + init_fetch_node(); + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js +function createSelectQueryBuilder(props) { + return new SelectQueryBuilderImpl(props); +} +var _a14, _props16, _SelectQueryBuilderImpl_instances, join_fn3, SelectQueryBuilderImpl, _queryBuilder, _alias2, AliasedSelectQueryBuilderImpl; +var init_select_query_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js"() { + init_alias_node(); + init_select_modifier_node(); + init_join_parser(); + init_table_parser(); + init_select_parser(); + init_reference_parser(); + init_select_query_node(); + init_query_node(); + init_order_by_parser(); + init_limit_node(); + init_offset_node(); + init_object_utils(); + init_group_by_parser(); + init_no_result_error(); + init_identifier_node(); + init_set_operation_parser(); + init_binary_operation_parser(); + init_expression_wrapper(); + init_value_parser(); + init_fetch_parser(); + init_top_parser(); + SelectQueryBuilderImpl = class { + constructor(props) { + __privateAdd(this, _SelectQueryBuilderImpl_instances); + __privateAdd(this, _props16); + __privateSet(this, _props16, freeze(props)); + } + get expressionType() { + return void 0; + } + get isSelectQueryBuilder() { + return true; + } + where(...args) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props16).queryNode, parseValueBinaryOperationOrExpression(args)) + }); + } + whereRef(lhs, op, rhs) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props16).queryNode, parseReferentialBinaryOperation(lhs, op, rhs)) + }); + } + having(...args) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithHaving(__privateGet(this, _props16).queryNode, parseValueBinaryOperationOrExpression(args)) + }); + } + havingRef(lhs, op, rhs) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithHaving(__privateGet(this, _props16).queryNode, parseReferentialBinaryOperation(lhs, op, rhs)) + }); + } + select(selection) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithSelections(__privateGet(this, _props16).queryNode, parseSelectArg(selection)) + }); + } + distinctOn(selection) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithDistinctOn(__privateGet(this, _props16).queryNode, parseReferenceExpressionOrList(selection)) + }); + } + modifyFront(modifier) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithFrontModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())) + }); + } + modifyEnd(modifier) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())) + }); + } + distinct() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithFrontModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("Distinct")) + }); + } + forUpdate(of) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("ForUpdate", of ? asArray(of).map(parseTable) : void 0)) + }); + } + forShare(of) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("ForShare", of ? asArray(of).map(parseTable) : void 0)) + }); + } + forKeyShare(of) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("ForKeyShare", of ? asArray(of).map(parseTable) : void 0)) + }); + } + forNoKeyUpdate(of) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("ForNoKeyUpdate", of ? asArray(of).map(parseTable) : void 0)) + }); + } + skipLocked() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("SkipLocked")) + }); + } + noWait() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("NoWait")) + }); + } + selectAll(table) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithSelections(__privateGet(this, _props16).queryNode, parseSelectAll(table)) + }); + } + innerJoin(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "InnerJoin", args); + } + leftJoin(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "LeftJoin", args); + } + rightJoin(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "RightJoin", args); + } + fullJoin(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "FullJoin", args); + } + crossJoin(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "CrossJoin", args); + } + innerJoinLateral(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "LateralInnerJoin", args); + } + leftJoinLateral(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "LateralLeftJoin", args); + } + crossJoinLateral(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "LateralCrossJoin", args); + } + crossApply(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "CrossApply", args); + } + outerApply(...args) { + return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "OuterApply", args); + } + orderBy(...args) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithOrderByItems(__privateGet(this, _props16).queryNode, parseOrderBy(args)) + }); + } + groupBy(groupBy2) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithGroupByItems(__privateGet(this, _props16).queryNode, parseGroupBy(groupBy2)) + }); + } + limit(limit) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithLimit(__privateGet(this, _props16).queryNode, LimitNode.create(parseValueExpression(limit))) + }); + } + offset(offset) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithOffset(__privateGet(this, _props16).queryNode, OffsetNode.create(parseValueExpression(offset))) + }); + } + fetch(rowCount, modifier = "only") { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithFetch(__privateGet(this, _props16).queryNode, parseFetch(rowCount, modifier)) + }); + } + top(expression, modifiers) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithTop(__privateGet(this, _props16).queryNode, parseTop(expression, modifiers)) + }); + } + union(expression) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("union", expression, false)) + }); + } + unionAll(expression) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("union", expression, true)) + }); + } + intersect(expression) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("intersect", expression, false)) + }); + } + intersectAll(expression) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("intersect", expression, true)) + }); + } + except(expression) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("except", expression, false)) + }); + } + exceptAll(expression) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("except", expression, true)) + }); + } + as(alias) { + return new AliasedSelectQueryBuilderImpl(this, alias); + } + clearSelect() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithoutSelections(__privateGet(this, _props16).queryNode) + }); + } + clearWhere() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithoutWhere(__privateGet(this, _props16).queryNode) + }); + } + clearLimit() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithoutLimit(__privateGet(this, _props16).queryNode) + }); + } + clearOffset() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithoutOffset(__privateGet(this, _props16).queryNode) + }); + } + clearOrderBy() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props16).queryNode) + }); + } + clearGroupBy() { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: SelectQueryNode.cloneWithoutGroupBy(__privateGet(this, _props16).queryNode) + }); + } + $call(func) { + return func(this); + } + $if(condition, func) { + if (condition) { + return func(this); + } + return new _a14({ + ...__privateGet(this, _props16) + }); + } + $castTo() { + return new _a14(__privateGet(this, _props16)); + } + $narrowType() { + return new _a14(__privateGet(this, _props16)); + } + $assertType() { + return new _a14(__privateGet(this, _props16)); + } + $asTuple() { + return new ExpressionWrapper(this.toOperationNode()); + } + $asScalar() { + return new ExpressionWrapper(this.toOperationNode()); + } + withPlugin(plugin) { + return new _a14({ + ...__privateGet(this, _props16), + executor: __privateGet(this, _props16).executor.withPlugin(plugin) + }); + } + toOperationNode() { + return __privateGet(this, _props16).executor.transformQuery(__privateGet(this, _props16).queryNode, __privateGet(this, _props16).queryId); + } + compile() { + return __privateGet(this, _props16).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props16).queryId); + } + async execute() { + const compiledQuery = this.compile(); + const result = await __privateGet(this, _props16).executor.executeQuery(compiledQuery); + return result.rows; + } + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error49; + } + return result; + } + async *stream(chunkSize = 100) { + const compiledQuery = this.compile(); + const stream = __privateGet(this, _props16).executor.stream(compiledQuery, chunkSize); + for await (const item of stream) { + yield* item.rows; + } + } + async explain(format, options) { + const builder = new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithExplain(__privateGet(this, _props16).queryNode, format, options) + }); + return await builder.execute(); + } + }; + _props16 = new WeakMap(); + _SelectQueryBuilderImpl_instances = new WeakSet(); + join_fn3 = function(joinType, args) { + return new _a14({ + ...__privateGet(this, _props16), + queryNode: QueryNode.cloneWithJoin(__privateGet(this, _props16).queryNode, parseJoin(joinType, args)) + }); + }; + _a14 = SelectQueryBuilderImpl; + AliasedSelectQueryBuilderImpl = class { + constructor(queryBuilder, alias) { + __privateAdd(this, _queryBuilder); + __privateAdd(this, _alias2); + __privateSet(this, _queryBuilder, queryBuilder); + __privateSet(this, _alias2, alias); + } + get expression() { + return __privateGet(this, _queryBuilder); + } + get alias() { + return __privateGet(this, _alias2); + } + get isAliasedSelectQueryBuilder() { + return true; + } + toOperationNode() { + return AliasNode.create(__privateGet(this, _queryBuilder).toOperationNode(), IdentifierNode.create(__privateGet(this, _alias2))); + } + }; + _queryBuilder = new WeakMap(); + _alias2 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js +var AggregateFunctionNode; +var init_aggregate_function_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js"() { + init_object_utils(); + init_where_node(); + init_order_by_node(); + AggregateFunctionNode = freeze({ + is(node) { + return node.kind === "AggregateFunctionNode"; + }, + create(aggregateFunction, aggregated = []) { + return freeze({ + kind: "AggregateFunctionNode", + func: aggregateFunction, + aggregated + }); + }, + cloneWithDistinct(aggregateFunctionNode) { + return freeze({ + ...aggregateFunctionNode, + distinct: true + }); + }, + cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) { + const prop = withinGroup ? "withinGroup" : "orderBy"; + return freeze({ + ...aggregateFunctionNode, + [prop]: aggregateFunctionNode[prop] ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems) : OrderByNode.create(orderItems) + }); + }, + cloneWithFilter(aggregateFunctionNode, filter) { + return freeze({ + ...aggregateFunctionNode, + filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "And", filter) : WhereNode.create(filter) + }); + }, + cloneWithOrFilter(aggregateFunctionNode, filter) { + return freeze({ + ...aggregateFunctionNode, + filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "Or", filter) : WhereNode.create(filter) + }); + }, + cloneWithOver(aggregateFunctionNode, over) { + return freeze({ + ...aggregateFunctionNode, + over + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js +var FunctionNode; +var init_function_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js"() { + init_object_utils(); + FunctionNode = freeze({ + is(node) { + return node.kind === "FunctionNode"; + }, + create(func, args) { + return freeze({ + kind: "FunctionNode", + func, + arguments: args + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js +var _props17, _AggregateFunctionBuilder, AggregateFunctionBuilder, _aggregateFunctionBuilder, _alias3, AliasedAggregateFunctionBuilder; +var init_aggregate_function_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js"() { + init_object_utils(); + init_aggregate_function_node(); + init_alias_node(); + init_identifier_node(); + init_parse_utils(); + init_binary_operation_parser(); + init_order_by_parser(); + init_query_node(); + _AggregateFunctionBuilder = class _AggregateFunctionBuilder { + constructor(props) { + __privateAdd(this, _props17); + __privateSet(this, _props17, freeze(props)); + } + /** @private */ + get expressionType() { + return void 0; + } + /** + * Returns an aliased version of the function. + * + * In addition to slapping `as "the_alias"` to the end of the SQL, + * this method also provides strict typing: + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select( + * (eb) => eb.fn.count('id').as('person_count') + * ) + * .executeTakeFirstOrThrow() + * + * // `person_count: number` field exists in the result type. + * console.log(result.person_count) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select count("id") as "person_count" + * from "person" + * ``` + */ + as(alias) { + return new AliasedAggregateFunctionBuilder(this, alias); + } + /** + * Adds a `distinct` clause inside the function. + * + * ### Examples + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select((eb) => + * eb.fn.count('first_name').distinct().as('first_name_count') + * ) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select count(distinct "first_name") as "first_name_count" + * from "person" + * ``` + */ + distinct() { + return new _AggregateFunctionBuilder({ + ...__privateGet(this, _props17), + aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(__privateGet(this, _props17).aggregateFunctionNode) + }); + } + orderBy(...args) { + return new _AggregateFunctionBuilder({ + ...__privateGet(this, _props17), + aggregateFunctionNode: QueryNode.cloneWithOrderByItems(__privateGet(this, _props17).aggregateFunctionNode, parseOrderBy(args)) + }); + } + clearOrderBy() { + return new _AggregateFunctionBuilder({ + ...__privateGet(this, _props17), + aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props17).aggregateFunctionNode) + }); + } + withinGroupOrderBy(...args) { + return new _AggregateFunctionBuilder({ + ...__privateGet(this, _props17), + aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(__privateGet(this, _props17).aggregateFunctionNode, parseOrderBy(args), true) + }); + } + filterWhere(...args) { + return new _AggregateFunctionBuilder({ + ...__privateGet(this, _props17), + aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(__privateGet(this, _props17).aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)) + }); + } + /** + * Adds a `filter` clause with a nested `where` clause after the function, where + * both sides of the operator are references to columns. + * + * Similar to {@link WhereInterface}'s `whereRef` method. + * + * ### Examples + * + * Count people with same first and last names versus general public: + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select((eb) => [ + * eb.fn + * .count('id') + * .filterWhereRef('first_name', '=', 'last_name') + * .as('repeat_name_count'), + * eb.fn.count('id').as('total_count'), + * ]) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select + * count("id") filter(where "first_name" = "last_name") as "repeat_name_count", + * count("id") as "total_count" + * from "person" + * ``` + */ + filterWhereRef(lhs, op, rhs) { + return new _AggregateFunctionBuilder({ + ...__privateGet(this, _props17), + aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(__privateGet(this, _props17).aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs)) + }); + } + /** + * Adds an `over` clause (window functions) after the function. + * + * ### Examples + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select( + * (eb) => eb.fn.avg('age').over().as('average_age') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select avg("age") over() as "average_age" + * from "person" + * ``` + * + * Also supports passing a callback that returns an over builder, + * allowing to add partition by and sort by clauses inside over. + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select( + * (eb) => eb.fn.avg('age').over( + * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc') + * ).as('average_age') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select avg("age") over(partition by "last_name" order by "first_name" asc) as "average_age" + * from "person" + * ``` + */ + over(over) { + const builder = createOverBuilder(); + return new _AggregateFunctionBuilder({ + ...__privateGet(this, _props17), + aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(__privateGet(this, _props17).aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + /** + * Casts the expression to the given type. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `AggregateFunctionBuilder` with a new output type. + */ + $castTo() { + return new _AggregateFunctionBuilder(__privateGet(this, _props17)); + } + /** + * Omit null from the expression's type. + * + * This function can be useful in cases where you know an expression can't be + * null, but Kysely is unable to infer it. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of `this` with a new output type. + */ + $notNull() { + return new _AggregateFunctionBuilder(__privateGet(this, _props17)); + } + toOperationNode() { + return __privateGet(this, _props17).aggregateFunctionNode; + } + }; + _props17 = new WeakMap(); + AggregateFunctionBuilder = _AggregateFunctionBuilder; + AliasedAggregateFunctionBuilder = class { + constructor(aggregateFunctionBuilder, alias) { + __privateAdd(this, _aggregateFunctionBuilder); + __privateAdd(this, _alias3); + __privateSet(this, _aggregateFunctionBuilder, aggregateFunctionBuilder); + __privateSet(this, _alias3, alias); + } + /** @private */ + get expression() { + return __privateGet(this, _aggregateFunctionBuilder); + } + /** @private */ + get alias() { + return __privateGet(this, _alias3); + } + toOperationNode() { + return AliasNode.create(__privateGet(this, _aggregateFunctionBuilder).toOperationNode(), IdentifierNode.create(__privateGet(this, _alias3))); + } + }; + _aggregateFunctionBuilder = new WeakMap(); + _alias3 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js +function createFunctionModule() { + const fn = (name, args) => { + return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? []))); + }; + const agg = (name, args) => { + return new AggregateFunctionBuilder({ + aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : void 0) + }); + }; + return Object.assign(fn, { + agg, + avg(column) { + return agg("avg", [column]); + }, + coalesce(...values) { + return fn("coalesce", values); + }, + count(column) { + return agg("count", [column]); + }, + countAll(table) { + return new AggregateFunctionBuilder({ + aggregateFunctionNode: AggregateFunctionNode.create("count", parseSelectAll(table)) + }); + }, + max(column) { + return agg("max", [column]); + }, + min(column) { + return agg("min", [column]); + }, + sum(column) { + return agg("sum", [column]); + }, + any(column) { + return fn("any", [column]); + }, + jsonAgg(table) { + return new AggregateFunctionBuilder({ + aggregateFunctionNode: AggregateFunctionNode.create("json_agg", [ + isString2(table) ? parseTable(table) : table.toOperationNode() + ]) + }); + }, + toJson(table) { + return new ExpressionWrapper(FunctionNode.create("to_json", [ + isString2(table) ? parseTable(table) : table.toOperationNode() + ])); + } + }); +} +var init_function_module = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js"() { + init_expression_wrapper(); + init_aggregate_function_node(); + init_function_node(); + init_reference_parser(); + init_select_parser(); + init_aggregate_function_builder(); + init_object_utils(); + init_table_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js +var UnaryOperationNode; +var init_unary_operation_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js"() { + init_object_utils(); + UnaryOperationNode = freeze({ + is(node) { + return node.kind === "UnaryOperationNode"; + }, + create(operator, operand) { + return freeze({ + kind: "UnaryOperationNode", + operator, + operand + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js +function parseUnaryOperation(operator, operand) { + return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand)); +} +var init_unary_operation_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js"() { + init_operator_node(); + init_unary_operation_node(); + init_reference_parser(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js +var CaseNode; +var init_case_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js"() { + init_object_utils(); + init_when_node(); + CaseNode = freeze({ + is(node) { + return node.kind === "CaseNode"; + }, + create(value) { + return freeze({ + kind: "CaseNode", + value + }); + }, + cloneWithWhen(caseNode, when) { + return freeze({ + ...caseNode, + when: freeze(caseNode.when ? [...caseNode.when, when] : [when]) + }); + }, + cloneWithThen(caseNode, then) { + return freeze({ + ...caseNode, + when: caseNode.when ? freeze([ + ...caseNode.when.slice(0, -1), + WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then) + ]) : void 0 + }); + }, + cloneWith(caseNode, props) { + return freeze({ + ...caseNode, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js +var _props18, CaseBuilder, _props19, CaseThenBuilder, _props20, CaseWhenBuilder, _props21, CaseEndBuilder; +var init_case_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js"() { + init_expression_wrapper(); + init_object_utils(); + init_case_node(); + init_when_node(); + init_binary_operation_parser(); + init_value_parser(); + CaseBuilder = class { + constructor(props) { + __privateAdd(this, _props18); + __privateSet(this, _props18, freeze(props)); + } + when(...args) { + return new CaseThenBuilder({ + ...__privateGet(this, _props18), + node: CaseNode.cloneWithWhen(__privateGet(this, _props18).node, WhenNode.create(parseValueBinaryOperationOrExpression(args))) + }); + } + }; + _props18 = new WeakMap(); + CaseThenBuilder = class { + constructor(props) { + __privateAdd(this, _props19); + __privateSet(this, _props19, freeze(props)); + } + then(valueExpression) { + return new CaseWhenBuilder({ + ...__privateGet(this, _props19), + node: CaseNode.cloneWithThen(__privateGet(this, _props19).node, isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression)) + }); + } + }; + _props19 = new WeakMap(); + CaseWhenBuilder = class { + constructor(props) { + __privateAdd(this, _props20); + __privateSet(this, _props20, freeze(props)); + } + when(...args) { + return new CaseThenBuilder({ + ...__privateGet(this, _props20), + node: CaseNode.cloneWithWhen(__privateGet(this, _props20).node, WhenNode.create(parseValueBinaryOperationOrExpression(args))) + }); + } + else(valueExpression) { + return new CaseEndBuilder({ + ...__privateGet(this, _props20), + node: CaseNode.cloneWith(__privateGet(this, _props20).node, { + else: isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression) + }) + }); + } + end() { + return new ExpressionWrapper(CaseNode.cloneWith(__privateGet(this, _props20).node, { isStatement: false })); + } + endCase() { + return new ExpressionWrapper(CaseNode.cloneWith(__privateGet(this, _props20).node, { isStatement: true })); + } + }; + _props20 = new WeakMap(); + CaseEndBuilder = class { + constructor(props) { + __privateAdd(this, _props21); + __privateSet(this, _props21, freeze(props)); + } + end() { + return new ExpressionWrapper(CaseNode.cloneWith(__privateGet(this, _props21).node, { isStatement: false })); + } + endCase() { + return new ExpressionWrapper(CaseNode.cloneWith(__privateGet(this, _props21).node, { isStatement: true })); + } + }; + _props21 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js +var JSONPathLegNode; +var init_json_path_leg_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js"() { + init_object_utils(); + JSONPathLegNode = freeze({ + is(node) { + return node.kind === "JSONPathLegNode"; + }, + create(type, value) { + return freeze({ + kind: "JSONPathLegNode", + type, + value + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js +var _node5, _JSONPathBuilder_instances, createBuilderWithPathLeg_fn, JSONPathBuilder, _node6, _TraversedJSONPathBuilder, TraversedJSONPathBuilder, _jsonPath, _alias4, AliasedJSONPathBuilder; +var init_json_path_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js"() { + init_alias_node(); + init_identifier_node(); + init_json_operator_chain_node(); + init_json_path_leg_node(); + init_json_path_node(); + init_json_reference_node(); + init_operation_node_source(); + init_value_node(); + JSONPathBuilder = class { + constructor(node) { + __privateAdd(this, _JSONPathBuilder_instances); + __privateAdd(this, _node5); + __privateSet(this, _node5, node); + } + /** + * Access an element of a JSON array in a specific location. + * + * Since there's no guarantee an element exists in the given array location, the + * resulting type is always nullable. If you're sure the element exists, you + * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely. + * + * See also {@link key} to access properties of JSON objects. + * + * ### Examples + * + * ```ts + * await db.selectFrom('person') + * .select(eb => + * eb.ref('nicknames', '->').at(0).as('primary_nickname') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "nicknames"->0 as "primary_nickname" from "person" + *``` + * + * Combined with {@link key}: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('experience', '->').at(0).key('role').as('first_role') + * ) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "experience"->0->'role' as "first_role" from "person" + * ``` + * + * You can use `'last'` to access the last element of the array in MySQL: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('nicknames', '->$').at('last').as('last_nickname') + * ) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * select `nicknames`->'$[last]' as `last_nickname` from `person` + * ``` + * + * Or `'#-1'` in SQLite: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname') + * ) + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * select "nicknames"->>'$[#-1]' as `last_nickname` from `person` + * ``` + */ + at(index) { + return __privateMethod(this, _JSONPathBuilder_instances, createBuilderWithPathLeg_fn).call(this, "ArrayLocation", index); + } + /** + * Access a property of a JSON object. + * + * If a field is optional, the resulting type will be nullable. + * + * See also {@link at} to access elements of JSON arrays. + * + * ### Examples + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('address', '->').key('city').as('city') + * ) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "address"->'city' as "city" from "person" + * ``` + * + * Going deeper: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('profile', '->$').key('website').key('url').as('website_url') + * ) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * select `profile`->'$.website.url' as `website_url` from `person` + * ``` + * + * Combined with {@link at}: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city') + * ) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "profile"->'addresses'->0->'city' as "city" from "person" + * ``` + */ + key(key) { + return __privateMethod(this, _JSONPathBuilder_instances, createBuilderWithPathLeg_fn).call(this, "Member", key); + } + }; + _node5 = new WeakMap(); + _JSONPathBuilder_instances = new WeakSet(); + createBuilderWithPathLeg_fn = function(legType, value) { + if (JSONReferenceNode.is(__privateGet(this, _node5))) { + return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(__privateGet(this, _node5), JSONPathNode.is(__privateGet(this, _node5).traversal) ? JSONPathNode.cloneWithLeg(__privateGet(this, _node5).traversal, JSONPathLegNode.create(legType, value)) : JSONOperatorChainNode.cloneWithValue(__privateGet(this, _node5).traversal, ValueNode.createImmediate(value)))); + } + return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(__privateGet(this, _node5), JSONPathLegNode.create(legType, value))); + }; + _TraversedJSONPathBuilder = class _TraversedJSONPathBuilder extends JSONPathBuilder { + constructor(node) { + super(node); + __privateAdd(this, _node6); + __privateSet(this, _node6, node); + } + /** @private */ + get expressionType() { + return void 0; + } + as(alias) { + return new AliasedJSONPathBuilder(this, alias); + } + /** + * Change the output type of the json path. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `JSONPathBuilder` with a new output type. + */ + $castTo() { + return new _TraversedJSONPathBuilder(__privateGet(this, _node6)); + } + $notNull() { + return new _TraversedJSONPathBuilder(__privateGet(this, _node6)); + } + toOperationNode() { + return __privateGet(this, _node6); + } + }; + _node6 = new WeakMap(); + TraversedJSONPathBuilder = _TraversedJSONPathBuilder; + AliasedJSONPathBuilder = class { + constructor(jsonPath, alias) { + __privateAdd(this, _jsonPath); + __privateAdd(this, _alias4); + __privateSet(this, _jsonPath, jsonPath); + __privateSet(this, _alias4, alias); + } + /** @private */ + get expression() { + return __privateGet(this, _jsonPath); + } + /** @private */ + get alias() { + return __privateGet(this, _alias4); + } + toOperationNode() { + return AliasNode.create(__privateGet(this, _jsonPath).toOperationNode(), isOperationNodeSource(__privateGet(this, _alias4)) ? __privateGet(this, _alias4).toOperationNode() : IdentifierNode.create(__privateGet(this, _alias4))); + } + }; + _jsonPath = new WeakMap(); + _alias4 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js +var TupleNode; +var init_tuple_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js"() { + init_object_utils(); + TupleNode = freeze({ + is(node) { + return node.kind === "TupleNode"; + }, + create(values) { + return freeze({ + kind: "TupleNode", + values: freeze(values) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js +function isColumnDataType(dataType) { + if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) { + return true; + } + if (COLUMN_DATA_TYPE_REGEX.some((r) => r.test(dataType))) { + return true; + } + return false; +} +var SIMPLE_COLUMN_DATA_TYPES, COLUMN_DATA_TYPE_REGEX, DataTypeNode; +var init_data_type_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js"() { + init_object_utils(); + SIMPLE_COLUMN_DATA_TYPES = [ + "varchar", + "char", + "text", + "integer", + "int2", + "int4", + "int8", + "smallint", + "bigint", + "boolean", + "real", + "double precision", + "float4", + "float8", + "decimal", + "numeric", + "binary", + "bytea", + "date", + "datetime", + "time", + "timetz", + "timestamp", + "timestamptz", + "serial", + "bigserial", + "uuid", + "json", + "jsonb", + "blob", + "varbinary", + "int4range", + "int4multirange", + "int8range", + "int8multirange", + "numrange", + "nummultirange", + "tsrange", + "tsmultirange", + "tstzrange", + "tstzmultirange", + "daterange", + "datemultirange" + ]; + COLUMN_DATA_TYPE_REGEX = [ + /^varchar\(\d+\)$/, + /^char\(\d+\)$/, + /^decimal\(\d+, \d+\)$/, + /^numeric\(\d+, \d+\)$/, + /^binary\(\d+\)$/, + /^datetime\(\d+\)$/, + /^time\(\d+\)$/, + /^timetz\(\d+\)$/, + /^timestamp\(\d+\)$/, + /^timestamptz\(\d+\)$/, + /^varbinary\(\d+\)$/ + ]; + DataTypeNode = freeze({ + is(node) { + return node.kind === "DataTypeNode"; + }, + create(dataType) { + return freeze({ + kind: "DataTypeNode", + dataType + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js +function parseDataTypeExpression(dataType) { + if (isOperationNodeSource(dataType)) { + return dataType.toOperationNode(); + } + if (isColumnDataType(dataType)) { + return DataTypeNode.create(dataType); + } + throw new Error(`invalid column data type ${JSON.stringify(dataType)}`); +} +var init_data_type_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js"() { + init_data_type_node(); + init_operation_node_source(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js +var CastNode; +var init_cast_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js"() { + init_object_utils(); + CastNode = freeze({ + is(node) { + return node.kind === "CastNode"; + }, + create(expression, dataType) { + return freeze({ + kind: "CastNode", + expression, + dataType + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js +function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) { + function binary2(lhs, op, rhs) { + return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs)); + } + function unary(op, expr) { + return new ExpressionWrapper(parseUnaryOperation(op, expr)); + } + const eb = Object.assign(binary2, { + fn: void 0, + eb: void 0, + selectFrom(table) { + return createSelectQueryBuilder({ + queryId: createQueryId(), + executor, + queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)) + }); + }, + case(reference) { + return new CaseBuilder({ + node: CaseNode.create(isUndefined(reference) ? void 0 : parseReferenceExpression(reference)) + }); + }, + ref(reference, op) { + if (isUndefined(op)) { + return new ExpressionWrapper(parseStringReference(reference)); + } + return new JSONPathBuilder(parseJSONReference(reference, op)); + }, + jsonPath() { + return new JSONPathBuilder(JSONPathNode.create()); + }, + table(table) { + return new ExpressionWrapper(parseTable(table)); + }, + val(value) { + return new ExpressionWrapper(parseValueExpression(value)); + }, + refTuple(...values) { + return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression))); + }, + tuple(...values) { + return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression))); + }, + lit(value) { + return new ExpressionWrapper(parseSafeImmediateValue(value)); + }, + unary, + not(expr) { + return unary("not", expr); + }, + exists(expr) { + return unary("exists", expr); + }, + neg(expr) { + return unary("-", expr); + }, + between(expr, start, end) { + return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between"), AndNode.create(parseValueExpression(start), parseValueExpression(end)))); + }, + betweenSymmetric(expr, start, end) { + return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between symmetric"), AndNode.create(parseValueExpression(start), parseValueExpression(end)))); + }, + and(exprs) { + if (isReadonlyArray(exprs)) { + return new ExpressionWrapper(parseFilterList(exprs, "and")); + } + return new ExpressionWrapper(parseFilterObject(exprs, "and")); + }, + or(exprs) { + if (isReadonlyArray(exprs)) { + return new ExpressionWrapper(parseFilterList(exprs, "or")); + } + return new ExpressionWrapper(parseFilterObject(exprs, "or")); + }, + parens(...args) { + const node = parseValueBinaryOperationOrExpression(args); + if (ParensNode.is(node)) { + return new ExpressionWrapper(node); + } else { + return new ExpressionWrapper(ParensNode.create(node)); + } + }, + cast(expr, dataType) { + return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType))); + }, + withSchema(schema3) { + return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema3))); + } + }); + eb.fn = createFunctionModule(); + eb.eb = eb; + return eb; +} +function expressionBuilder(_) { + return createExpressionBuilder(); +} +var init_expression_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js"() { + init_select_query_builder(); + init_select_query_node(); + init_table_parser(); + init_with_schema_plugin(); + init_query_id(); + init_function_module(); + init_reference_parser(); + init_binary_operation_parser(); + init_parens_node(); + init_expression_wrapper(); + init_operator_node(); + init_unary_operation_parser(); + init_value_parser(); + init_noop_query_executor(); + init_case_builder(); + init_case_node(); + init_object_utils(); + init_json_path_builder(); + init_binary_operation_node(); + init_and_node(); + init_tuple_node(); + init_json_path_node(); + init_data_type_parser(); + init_cast_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js +function parseExpression(exp) { + if (isOperationNodeSource(exp)) { + return exp.toOperationNode(); + } else if (isFunction3(exp)) { + return exp(expressionBuilder()).toOperationNode(); + } + throw new Error(`invalid expression: ${JSON.stringify(exp)}`); +} +function parseAliasedExpression(exp) { + if (isOperationNodeSource(exp)) { + return exp.toOperationNode(); + } else if (isFunction3(exp)) { + return exp(expressionBuilder()).toOperationNode(); + } + throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`); +} +function isExpressionOrFactory(obj) { + return isExpression(obj) || isAliasedExpression(obj) || isFunction3(obj); +} +var init_expression_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js"() { + init_expression(); + init_operation_node_source(); + init_expression_builder(); + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js +function isAliasedDynamicTableBuilder(obj) { + return isObject4(obj) && isOperationNodeSource(obj) && isString2(obj.table) && isString2(obj.alias); +} +var _table, DynamicTableBuilder, _table2, _alias5, AliasedDynamicTableBuilder; +var init_dynamic_table_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js"() { + init_alias_node(); + init_identifier_node(); + init_operation_node_source(); + init_table_parser(); + init_object_utils(); + DynamicTableBuilder = class { + constructor(table) { + __privateAdd(this, _table); + __privateSet(this, _table, table); + } + get table() { + return __privateGet(this, _table); + } + as(alias) { + return new AliasedDynamicTableBuilder(__privateGet(this, _table), alias); + } + }; + _table = new WeakMap(); + AliasedDynamicTableBuilder = class { + constructor(table, alias) { + __privateAdd(this, _table2); + __privateAdd(this, _alias5); + __privateSet(this, _table2, table); + __privateSet(this, _alias5, alias); + } + get table() { + return __privateGet(this, _table2); + } + get alias() { + return __privateGet(this, _alias5); + } + toOperationNode() { + return AliasNode.create(parseTable(__privateGet(this, _table2)), IdentifierNode.create(__privateGet(this, _alias5))); + } + }; + _table2 = new WeakMap(); + _alias5 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js +function parseTableExpressionOrList(table) { + if (isReadonlyArray(table)) { + return table.map((it) => parseTableExpression(it)); + } else { + return [parseTableExpression(table)]; + } +} +function parseTableExpression(table) { + if (isString2(table)) { + return parseAliasedTable(table); + } else if (isAliasedDynamicTableBuilder(table)) { + return table.toOperationNode(); + } else { + return parseAliasedExpression(table); + } +} +function parseAliasedTable(from) { + const ALIAS_SEPARATOR = " as "; + if (from.includes(ALIAS_SEPARATOR)) { + const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim2); + return AliasNode.create(parseTable(table), IdentifierNode.create(alias)); + } else { + return parseTable(from); + } +} +function parseTable(from) { + const SCHEMA_SEPARATOR = "."; + if (from.includes(SCHEMA_SEPARATOR)) { + const [schema3, table] = from.split(SCHEMA_SEPARATOR).map(trim2); + return TableNode.createWithSchema(schema3, table); + } else { + return TableNode.create(from); + } +} +function trim2(str) { + return str.trim(); +} +var init_table_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js"() { + init_object_utils(); + init_alias_node(); + init_table_node(); + init_expression_parser(); + init_identifier_node(); + init_dynamic_table_builder(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js +var AddColumnNode; +var init_add_column_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js"() { + init_object_utils(); + AddColumnNode = freeze({ + is(node) { + return node.kind === "AddColumnNode"; + }, + create(column) { + return freeze({ + kind: "AddColumnNode", + column + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js +var ColumnDefinitionNode; +var init_column_definition_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js"() { + init_object_utils(); + init_column_node(); + ColumnDefinitionNode = freeze({ + is(node) { + return node.kind === "ColumnDefinitionNode"; + }, + create(column, dataType) { + return freeze({ + kind: "ColumnDefinitionNode", + column: ColumnNode.create(column), + dataType + }); + }, + cloneWithFrontModifier(node, modifier) { + return freeze({ + ...node, + frontModifiers: node.frontModifiers ? freeze([...node.frontModifiers, modifier]) : [modifier] + }); + }, + cloneWithEndModifier(node, modifier) { + return freeze({ + ...node, + endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : [modifier] + }); + }, + cloneWith(node, props) { + return freeze({ + ...node, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js +var DropColumnNode; +var init_drop_column_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js"() { + init_object_utils(); + init_column_node(); + DropColumnNode = freeze({ + is(node) { + return node.kind === "DropColumnNode"; + }, + create(column) { + return freeze({ + kind: "DropColumnNode", + column: ColumnNode.create(column) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js +var RenameColumnNode; +var init_rename_column_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js"() { + init_object_utils(); + init_column_node(); + RenameColumnNode = freeze({ + is(node) { + return node.kind === "RenameColumnNode"; + }, + create(column, newColumn) { + return freeze({ + kind: "RenameColumnNode", + column: ColumnNode.create(column), + renameTo: ColumnNode.create(newColumn) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js +var CheckConstraintNode; +var init_check_constraint_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js"() { + init_object_utils(); + init_identifier_node(); + CheckConstraintNode = freeze({ + is(node) { + return node.kind === "CheckConstraintNode"; + }, + create(expression, constraintName) { + return freeze({ + kind: "CheckConstraintNode", + expression, + name: constraintName ? IdentifierNode.create(constraintName) : void 0 + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js +var ON_MODIFY_FOREIGN_ACTIONS, ReferencesNode; +var init_references_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js"() { + init_object_utils(); + ON_MODIFY_FOREIGN_ACTIONS = [ + "no action", + "restrict", + "cascade", + "set null", + "set default" + ]; + ReferencesNode = freeze({ + is(node) { + return node.kind === "ReferencesNode"; + }, + create(table, columns) { + return freeze({ + kind: "ReferencesNode", + table, + columns: freeze([...columns]) + }); + }, + cloneWithOnDelete(references, onDelete) { + return freeze({ + ...references, + onDelete + }); + }, + cloneWithOnUpdate(references, onUpdate) { + return freeze({ + ...references, + onUpdate + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js +function parseDefaultValueExpression(value) { + return isOperationNodeSource(value) ? value.toOperationNode() : ValueNode.createImmediate(value); +} +var init_default_value_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js"() { + init_operation_node_source(); + init_value_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js +var GeneratedNode; +var init_generated_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js"() { + init_object_utils(); + GeneratedNode = freeze({ + is(node) { + return node.kind === "GeneratedNode"; + }, + create(params) { + return freeze({ + kind: "GeneratedNode", + ...params + }); + }, + createWithExpression(expression) { + return freeze({ + kind: "GeneratedNode", + always: true, + expression + }); + }, + cloneWith(node, params) { + return freeze({ + ...node, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js +var DefaultValueNode; +var init_default_value_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js"() { + init_object_utils(); + DefaultValueNode = freeze({ + is(node) { + return node.kind === "DefaultValueNode"; + }, + create(defaultValue) { + return freeze({ + kind: "DefaultValueNode", + defaultValue + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js +function parseOnModifyForeignAction(action) { + if (ON_MODIFY_FOREIGN_ACTIONS.includes(action)) { + return action; + } + throw new Error(`invalid OnModifyForeignAction ${action}`); +} +var init_on_modify_action_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js"() { + init_references_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js +var _node7, _ColumnDefinitionBuilder, ColumnDefinitionBuilder; +var init_column_definition_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js"() { + init_check_constraint_node(); + init_references_node(); + init_select_all_node(); + init_reference_parser(); + init_column_definition_node(); + init_default_value_parser(); + init_generated_node(); + init_default_value_node(); + init_on_modify_action_parser(); + _ColumnDefinitionBuilder = class _ColumnDefinitionBuilder { + constructor(node) { + __privateAdd(this, _node7); + __privateSet(this, _node7, node); + } + /** + * Adds `auto_increment` or `autoincrement` to the column definition + * depending on the dialect. + * + * Some dialects like PostgreSQL don't support this. On PostgreSQL + * you can use the `serial` or `bigserial` data type instead. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.autoIncrement().primaryKey()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key auto_increment + * ) + * ``` + */ + autoIncrement() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { autoIncrement: true })); + } + /** + * Makes the column an identity column. + * + * This only works on some dialects like MS SQL Server (MSSQL). + * + * For PostgreSQL's `generated always as identity` use {@link generatedAlwaysAsIdentity}. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.identity().primaryKey()) + * .execute() + * ``` + * + * The generated SQL (MSSQL): + * + * ```sql + * create table "person" ( + * "id" integer identity primary key + * ) + * ``` + */ + identity() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { identity: true })); + } + /** + * Makes the column the primary key. + * + * If you want to specify a composite primary key use the + * {@link CreateTableBuilder.addPrimaryKeyConstraint} method. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key + * ) + */ + primaryKey() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { primaryKey: true })); + } + /** + * Adds a foreign key constraint for the column. + * + * If your database engine doesn't support foreign key constraints in the + * column definition (like MySQL 5) you need to call the table level + * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('owner_id', 'integer', (col) => col.references('person.id')) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "pet" ( + * "owner_id" integer references "person" ("id") + * ) + * ``` + */ + references(ref) { + const references = parseStringReference(ref); + if (!references.table || SelectAllNode.is(references.column)) { + throw new Error(`invalid call references('${ref}'). The reference must have format table.column or schema.table.column`); + } + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + references: ReferencesNode.create(references.table, [ + references.column + ]) + })); + } + /** + * Adds an `on delete` constraint for the foreign key column. + * + * If your database engine doesn't support foreign key constraints in the + * column definition (like MySQL 5) you need to call the table level + * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn( + * 'owner_id', + * 'integer', + * (col) => col.references('person.id').onDelete('cascade') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "pet" ( + * "owner_id" integer references "person" ("id") on delete cascade + * ) + * ``` + */ + onDelete(onDelete) { + if (!__privateGet(this, _node7).references) { + throw new Error("on delete constraint can only be added for foreign keys"); + } + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + references: ReferencesNode.cloneWithOnDelete(__privateGet(this, _node7).references, parseOnModifyForeignAction(onDelete)) + })); + } + /** + * Adds an `on update` constraint for the foreign key column. + * + * If your database engine doesn't support foreign key constraints in the + * column definition (like MySQL 5) you need to call the table level + * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn( + * 'owner_id', + * 'integer', + * (col) => col.references('person.id').onUpdate('cascade') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "pet" ( + * "owner_id" integer references "person" ("id") on update cascade + * ) + * ``` + */ + onUpdate(onUpdate) { + if (!__privateGet(this, _node7).references) { + throw new Error("on update constraint can only be added for foreign keys"); + } + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + references: ReferencesNode.cloneWithOnUpdate(__privateGet(this, _node7).references, parseOnModifyForeignAction(onUpdate)) + })); + } + /** + * Adds a unique constraint for the column. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('email', 'varchar(255)', col => col.unique()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `email` varchar(255) unique + * ) + * ``` + */ + unique() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { unique: true })); + } + /** + * Adds a `not null` constraint for the column. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('first_name', 'varchar(255)', col => col.notNull()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `first_name` varchar(255) not null + * ) + * ``` + */ + notNull() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { notNull: true })); + } + /** + * Adds a `unsigned` modifier for the column. + * + * This only works on some dialects like MySQL. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('age', 'integer', col => col.unsigned()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `age` integer unsigned + * ) + * ``` + */ + unsigned() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { unsigned: true })); + } + /** + * Adds a default value constraint for the column. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('number_of_legs', 'integer', (col) => col.defaultTo(4)) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `pet` ( + * `number_of_legs` integer default 4 + * ) + * ``` + * + * Values passed to `defaultTo` are interpreted as value literals by default. You can define + * an arbitrary SQL expression using the {@link sql} template tag: + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('pet') + * .addColumn( + * 'created_at', + * 'timestamp', + * (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`) + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `pet` ( + * `created_at` timestamp default CURRENT_TIMESTAMP + * ) + * ``` + */ + defaultTo(value) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + defaultTo: DefaultValueNode.create(parseDefaultValueExpression(value)) + })); + } + /** + * Adds a check constraint for the column. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('pet') + * .addColumn('number_of_legs', 'integer', (col) => + * col.check(sql`number_of_legs < 5`) + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `pet` ( + * `number_of_legs` integer check (number_of_legs < 5) + * ) + * ``` + */ + check(expression) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + check: CheckConstraintNode.create(expression.toOperationNode()) + })); + } + /** + * Makes the column a generated column using a `generated always as` statement. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('full_name', 'varchar(255)', + * (col) => col.generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`) + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) + * ) + * ``` + */ + generatedAlwaysAs(expression) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + generated: GeneratedNode.createWithExpression(expression.toOperationNode()) + })); + } + /** + * Adds the `generated always as identity` specifier. + * + * This only works on some dialects like PostgreSQL. + * + * For MS SQL Server (MSSQL)'s identity column use {@link identity}. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.generatedAlwaysAsIdentity().primaryKey()) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "person" ( + * "id" integer generated always as identity primary key + * ) + * ``` + */ + generatedAlwaysAsIdentity() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + generated: GeneratedNode.create({ identity: true, always: true }) + })); + } + /** + * Adds the `generated by default as identity` specifier on supported dialects. + * + * This only works on some dialects like PostgreSQL. + * + * For MS SQL Server (MSSQL)'s identity column use {@link identity}. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.generatedByDefaultAsIdentity().primaryKey()) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "person" ( + * "id" integer generated by default as identity primary key + * ) + * ``` + */ + generatedByDefaultAsIdentity() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + generated: GeneratedNode.create({ identity: true, byDefault: true }) + })); + } + /** + * Makes a generated column stored instead of virtual. This method can only + * be used with {@link generatedAlwaysAs} + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('full_name', 'varchar(255)', (col) => col + * .generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`) + * .stored() + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) stored + * ) + * ``` + */ + stored() { + if (!__privateGet(this, _node7).generated) { + throw new Error("stored() can only be called after generatedAlwaysAs"); + } + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { + generated: GeneratedNode.cloneWith(__privateGet(this, _node7).generated, { + stored: true + }) + })); + } + /** + * This can be used to add any additional SQL right after the column's data type. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn( + * 'first_name', + * 'varchar(36)', + * (col) => col.modifyFront(sql`collate utf8mb4_general_ci`).notNull() + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key, + * `first_name` varchar(36) collate utf8mb4_general_ci not null + * ) + * ``` + */ + modifyFront(modifier) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(__privateGet(this, _node7), modifier.toOperationNode())); + } + /** + * Adds `nulls not distinct` specifier. + * Should be used with `unique` constraint. + * + * This only works on some dialects like PostgreSQL. + * + * ### Examples + * + * ```ts + * db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn('first_name', 'varchar(30)', col => col.unique().nullsNotDistinct()) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "person" ( + * "id" integer primary key, + * "first_name" varchar(30) unique nulls not distinct + * ) + * ``` + */ + nullsNotDistinct() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { nullsNotDistinct: true })); + } + /** + * Adds `if not exists` specifier. This only works for PostgreSQL. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .addColumn('email', 'varchar(255)', col => col.unique().ifNotExists()) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * alter table "person" add column if not exists "email" varchar(255) unique + * ``` + */ + ifNotExists() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { ifNotExists: true })); + } + /** + * This can be used to add any additional SQL to the end of the column definition. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn( + * 'age', + * 'integer', + * col => col.unsigned() + * .notNull() + * .modifyEnd(sql`comment ${sql.lit('it is not polite to ask a woman her age')}`) + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key, + * `age` integer unsigned not null comment 'it is not polite to ask a woman her age' + * ) + * ``` + */ + modifyEnd(modifier) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(__privateGet(this, _node7), modifier.toOperationNode())); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _node7); + } + }; + _node7 = new WeakMap(); + ColumnDefinitionBuilder = _ColumnDefinitionBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js +var ModifyColumnNode; +var init_modify_column_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js"() { + init_object_utils(); + ModifyColumnNode = freeze({ + is(node) { + return node.kind === "ModifyColumnNode"; + }, + create(column) { + return freeze({ + kind: "ModifyColumnNode", + column + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js +var ForeignKeyConstraintNode; +var init_foreign_key_constraint_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js"() { + init_object_utils(); + init_identifier_node(); + init_references_node(); + ForeignKeyConstraintNode = freeze({ + is(node) { + return node.kind === "ForeignKeyConstraintNode"; + }, + create(sourceColumns, targetTable, targetColumns, constraintName) { + return freeze({ + kind: "ForeignKeyConstraintNode", + columns: sourceColumns, + references: ReferencesNode.create(targetTable, targetColumns), + name: constraintName ? IdentifierNode.create(constraintName) : void 0 + }); + }, + cloneWith(node, props) { + return freeze({ + ...node, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js +var _node8, _ForeignKeyConstraintBuilder, ForeignKeyConstraintBuilder; +var init_foreign_key_constraint_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js"() { + init_foreign_key_constraint_node(); + init_on_modify_action_parser(); + _ForeignKeyConstraintBuilder = class _ForeignKeyConstraintBuilder { + constructor(node) { + __privateAdd(this, _node8); + __privateSet(this, _node8, node); + } + onDelete(onDelete) { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { + onDelete: parseOnModifyForeignAction(onDelete) + })); + } + onUpdate(onUpdate) { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { + onUpdate: parseOnModifyForeignAction(onUpdate) + })); + } + deferrable() { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { deferrable: true })); + } + notDeferrable() { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { deferrable: false })); + } + initiallyDeferred() { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { + initiallyDeferred: true + })); + } + initiallyImmediate() { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { + initiallyDeferred: false + })); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _node8); + } + }; + _node8 = new WeakMap(); + ForeignKeyConstraintBuilder = _ForeignKeyConstraintBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js +var AddConstraintNode; +var init_add_constraint_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js"() { + init_object_utils(); + AddConstraintNode = freeze({ + is(node) { + return node.kind === "AddConstraintNode"; + }, + create(constraint) { + return freeze({ + kind: "AddConstraintNode", + constraint + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js +var UniqueConstraintNode; +var init_unique_constraint_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js"() { + init_object_utils(); + init_column_node(); + init_identifier_node(); + UniqueConstraintNode = freeze({ + is(node) { + return node.kind === "UniqueConstraintNode"; + }, + create(columns, constraintName, nullsNotDistinct) { + return freeze({ + kind: "UniqueConstraintNode", + columns: freeze(columns.map(ColumnNode.create)), + name: constraintName ? IdentifierNode.create(constraintName) : void 0, + nullsNotDistinct + }); + }, + cloneWith(node, props) { + return freeze({ + ...node, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js +var DropConstraintNode; +var init_drop_constraint_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js"() { + init_object_utils(); + init_identifier_node(); + DropConstraintNode = freeze({ + is(node) { + return node.kind === "DropConstraintNode"; + }, + create(constraintName) { + return freeze({ + kind: "DropConstraintNode", + constraintName: IdentifierNode.create(constraintName) + }); + }, + cloneWith(dropConstraint, props) { + return freeze({ + ...dropConstraint, + ...props + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js +var AlterColumnNode; +var init_alter_column_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js"() { + init_object_utils(); + init_column_node(); + AlterColumnNode = freeze({ + is(node) { + return node.kind === "AlterColumnNode"; + }, + create(column, prop, value) { + return freeze({ + kind: "AlterColumnNode", + column: ColumnNode.create(column), + [prop]: value + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js +var _column, AlterColumnBuilder, _alterColumnNode, AlteredColumnBuilder; +var init_alter_column_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js"() { + init_alter_column_node(); + init_data_type_parser(); + init_default_value_parser(); + AlterColumnBuilder = class { + constructor(column) { + __privateAdd(this, _column); + __privateSet(this, _column, column); + } + setDataType(dataType) { + return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "dataType", parseDataTypeExpression(dataType))); + } + setDefault(value) { + return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "setDefault", parseDefaultValueExpression(value))); + } + dropDefault() { + return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "dropDefault", true)); + } + setNotNull() { + return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "setNotNull", true)); + } + dropNotNull() { + return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "dropNotNull", true)); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + }; + _column = new WeakMap(); + AlteredColumnBuilder = class { + constructor(alterColumnNode) { + __privateAdd(this, _alterColumnNode); + __privateSet(this, _alterColumnNode, alterColumnNode); + } + toOperationNode() { + return __privateGet(this, _alterColumnNode); + } + }; + _alterColumnNode = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js +var _props22, AlterTableExecutor; +var init_alter_table_executor = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js"() { + init_object_utils(); + AlterTableExecutor = class { + constructor(props) { + __privateAdd(this, _props22); + __privateSet(this, _props22, freeze(props)); + } + toOperationNode() { + return __privateGet(this, _props22).executor.transformQuery(__privateGet(this, _props22).node, __privateGet(this, _props22).queryId); + } + compile() { + return __privateGet(this, _props22).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props22).queryId); + } + async execute() { + await __privateGet(this, _props22).executor.executeQuery(this.compile()); + } + }; + _props22 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js +var _props23, _AlterTableAddForeignKeyConstraintBuilder, AlterTableAddForeignKeyConstraintBuilder; +var init_alter_table_add_foreign_key_constraint_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js"() { + init_add_constraint_node(); + init_alter_table_node(); + init_object_utils(); + _AlterTableAddForeignKeyConstraintBuilder = class _AlterTableAddForeignKeyConstraintBuilder { + constructor(props) { + __privateAdd(this, _props23); + __privateSet(this, _props23, freeze(props)); + } + onDelete(onDelete) { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...__privateGet(this, _props23), + constraintBuilder: __privateGet(this, _props23).constraintBuilder.onDelete(onDelete) + }); + } + onUpdate(onUpdate) { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...__privateGet(this, _props23), + constraintBuilder: __privateGet(this, _props23).constraintBuilder.onUpdate(onUpdate) + }); + } + deferrable() { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...__privateGet(this, _props23), + constraintBuilder: __privateGet(this, _props23).constraintBuilder.deferrable() + }); + } + notDeferrable() { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...__privateGet(this, _props23), + constraintBuilder: __privateGet(this, _props23).constraintBuilder.notDeferrable() + }); + } + initiallyDeferred() { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...__privateGet(this, _props23), + constraintBuilder: __privateGet(this, _props23).constraintBuilder.initiallyDeferred() + }); + } + initiallyImmediate() { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...__privateGet(this, _props23), + constraintBuilder: __privateGet(this, _props23).constraintBuilder.initiallyImmediate() + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props23).executor.transformQuery(AlterTableNode.cloneWithTableProps(__privateGet(this, _props23).node, { + addConstraint: AddConstraintNode.create(__privateGet(this, _props23).constraintBuilder.toOperationNode()) + }), __privateGet(this, _props23).queryId); + } + compile() { + return __privateGet(this, _props23).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props23).queryId); + } + async execute() { + await __privateGet(this, _props23).executor.executeQuery(this.compile()); + } + }; + _props23 = new WeakMap(); + AlterTableAddForeignKeyConstraintBuilder = _AlterTableAddForeignKeyConstraintBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js +var _props24, _AlterTableDropConstraintBuilder, AlterTableDropConstraintBuilder; +var init_alter_table_drop_constraint_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js"() { + init_alter_table_node(); + init_drop_constraint_node(); + init_object_utils(); + _AlterTableDropConstraintBuilder = class _AlterTableDropConstraintBuilder { + constructor(props) { + __privateAdd(this, _props24); + __privateSet(this, _props24, freeze(props)); + } + ifExists() { + return new _AlterTableDropConstraintBuilder({ + ...__privateGet(this, _props24), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props24).node, { + dropConstraint: DropConstraintNode.cloneWith(__privateGet(this, _props24).node.dropConstraint, { + ifExists: true + }) + }) + }); + } + cascade() { + return new _AlterTableDropConstraintBuilder({ + ...__privateGet(this, _props24), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props24).node, { + dropConstraint: DropConstraintNode.cloneWith(__privateGet(this, _props24).node.dropConstraint, { + modifier: "cascade" + }) + }) + }); + } + restrict() { + return new _AlterTableDropConstraintBuilder({ + ...__privateGet(this, _props24), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props24).node, { + dropConstraint: DropConstraintNode.cloneWith(__privateGet(this, _props24).node.dropConstraint, { + modifier: "restrict" + }) + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props24).executor.transformQuery(__privateGet(this, _props24).node, __privateGet(this, _props24).queryId); + } + compile() { + return __privateGet(this, _props24).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props24).queryId); + } + async execute() { + await __privateGet(this, _props24).executor.executeQuery(this.compile()); + } + }; + _props24 = new WeakMap(); + AlterTableDropConstraintBuilder = _AlterTableDropConstraintBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js +var PrimaryKeyConstraintNode; +var init_primary_key_constraint_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js"() { + init_object_utils(); + init_column_node(); + init_identifier_node(); + PrimaryKeyConstraintNode = freeze({ + is(node) { + return node.kind === "PrimaryKeyConstraintNode"; + }, + create(columns, constraintName) { + return freeze({ + kind: "PrimaryKeyConstraintNode", + columns: freeze(columns.map(ColumnNode.create)), + name: constraintName ? IdentifierNode.create(constraintName) : void 0 + }); + }, + cloneWith(node, props) { + return freeze({ ...node, ...props }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js +var AddIndexNode; +var init_add_index_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js"() { + init_object_utils(); + init_identifier_node(); + AddIndexNode = freeze({ + is(node) { + return node.kind === "AddIndexNode"; + }, + create(name) { + return freeze({ + kind: "AddIndexNode", + name: IdentifierNode.create(name) + }); + }, + cloneWith(node, props) { + return freeze({ + ...node, + ...props + }); + }, + cloneWithColumns(node, columns) { + return freeze({ + ...node, + columns: [...node.columns || [], ...columns] + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js +var _props25, _AlterTableAddIndexBuilder, AlterTableAddIndexBuilder; +var init_alter_table_add_index_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js"() { + init_add_index_node(); + init_alter_table_node(); + init_raw_node(); + init_reference_parser(); + init_object_utils(); + _AlterTableAddIndexBuilder = class _AlterTableAddIndexBuilder { + constructor(props) { + __privateAdd(this, _props25); + __privateSet(this, _props25, freeze(props)); + } + /** + * Makes the index unique. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .addIndex('person_first_name_index') + * .unique() + * .column('email') + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add unique index `person_first_name_index` (`email`) + * ``` + */ + unique() { + return new _AlterTableAddIndexBuilder({ + ...__privateGet(this, _props25), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { + addIndex: AddIndexNode.cloneWith(__privateGet(this, _props25).node.addIndex, { + unique: true + }) + }) + }); + } + /** + * Adds a column to the index. + * + * Also see {@link columns} for adding multiple columns at once or {@link expression} + * for specifying an arbitrary expression. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .addIndex('person_first_name_and_age_index') + * .column('first_name') + * .column('age desc') + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc) + * ``` + */ + column(column) { + return new _AlterTableAddIndexBuilder({ + ...__privateGet(this, _props25), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { + addIndex: AddIndexNode.cloneWithColumns(__privateGet(this, _props25).node.addIndex, [ + parseOrderedColumnName(column) + ]) + }) + }); + } + /** + * Specifies a list of columns for the index. + * + * Also see {@link column} for adding a single column or {@link expression} for + * specifying an arbitrary expression. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .addIndex('person_first_name_and_age_index') + * .columns(['first_name', 'age desc']) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc) + * ``` + */ + columns(columns) { + return new _AlterTableAddIndexBuilder({ + ...__privateGet(this, _props25), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { + addIndex: AddIndexNode.cloneWithColumns(__privateGet(this, _props25).node.addIndex, columns.map(parseOrderedColumnName)) + }) + }); + } + /** + * Specifies an arbitrary expression for the index. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .alterTable('person') + * .addIndex('person_first_name_index') + * .expression(sql`(first_name < 'Sami')`) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add index `person_first_name_index` ((first_name < 'Sami')) + * ``` + */ + expression(expression) { + return new _AlterTableAddIndexBuilder({ + ...__privateGet(this, _props25), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { + addIndex: AddIndexNode.cloneWithColumns(__privateGet(this, _props25).node.addIndex, [ + expression.toOperationNode() + ]) + }) + }); + } + using(indexType) { + return new _AlterTableAddIndexBuilder({ + ...__privateGet(this, _props25), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { + addIndex: AddIndexNode.cloneWith(__privateGet(this, _props25).node.addIndex, { + using: RawNode.createWithSql(indexType) + }) + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props25).executor.transformQuery(__privateGet(this, _props25).node, __privateGet(this, _props25).queryId); + } + compile() { + return __privateGet(this, _props25).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props25).queryId); + } + async execute() { + await __privateGet(this, _props25).executor.executeQuery(this.compile()); + } + }; + _props25 = new WeakMap(); + AlterTableAddIndexBuilder = _AlterTableAddIndexBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js +var _node9, _UniqueConstraintNodeBuilder, UniqueConstraintNodeBuilder; +var init_unique_constraint_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js"() { + init_unique_constraint_node(); + _UniqueConstraintNodeBuilder = class _UniqueConstraintNodeBuilder { + constructor(node) { + __privateAdd(this, _node9); + __privateSet(this, _node9, node); + } + /** + * Adds `nulls not distinct` to the unique constraint definition + * + * Supported by PostgreSQL dialect only + */ + nullsNotDistinct() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { nullsNotDistinct: true })); + } + deferrable() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { deferrable: true })); + } + notDeferrable() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { deferrable: false })); + } + initiallyDeferred() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { + initiallyDeferred: true + })); + } + initiallyImmediate() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { + initiallyDeferred: false + })); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _node9); + } + }; + _node9 = new WeakMap(); + UniqueConstraintNodeBuilder = _UniqueConstraintNodeBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js +var _node10, _PrimaryKeyConstraintBuilder, PrimaryKeyConstraintBuilder; +var init_primary_key_constraint_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js"() { + init_primary_key_constraint_node(); + _PrimaryKeyConstraintBuilder = class _PrimaryKeyConstraintBuilder { + constructor(node) { + __privateAdd(this, _node10); + __privateSet(this, _node10, node); + } + deferrable() { + return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(__privateGet(this, _node10), { deferrable: true })); + } + notDeferrable() { + return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(__privateGet(this, _node10), { deferrable: false })); + } + initiallyDeferred() { + return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(__privateGet(this, _node10), { + initiallyDeferred: true + })); + } + initiallyImmediate() { + return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(__privateGet(this, _node10), { + initiallyDeferred: false + })); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _node10); + } + }; + _node10 = new WeakMap(); + PrimaryKeyConstraintBuilder = _PrimaryKeyConstraintBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js +var _node11, CheckConstraintBuilder; +var init_check_constraint_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js"() { + CheckConstraintBuilder = class { + constructor(node) { + __privateAdd(this, _node11); + __privateSet(this, _node11, node); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _node11); + } + }; + _node11 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js +var RenameConstraintNode; +var init_rename_constraint_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js"() { + init_object_utils(); + init_identifier_node(); + RenameConstraintNode = freeze({ + is(node) { + return node.kind === "RenameConstraintNode"; + }, + create(oldName, newName) { + return freeze({ + kind: "RenameConstraintNode", + oldName: IdentifierNode.create(oldName), + newName: IdentifierNode.create(newName) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js +var _props26, AlterTableBuilder, _props27, _AlterTableColumnAlteringBuilder, AlterTableColumnAlteringBuilder; +var init_alter_table_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js"() { + init_add_column_node(); + init_alter_table_node(); + init_column_definition_node(); + init_drop_column_node(); + init_identifier_node(); + init_rename_column_node(); + init_object_utils(); + init_column_definition_builder(); + init_modify_column_node(); + init_data_type_parser(); + init_foreign_key_constraint_builder(); + init_add_constraint_node(); + init_unique_constraint_node(); + init_check_constraint_node(); + init_foreign_key_constraint_node(); + init_column_node(); + init_table_parser(); + init_drop_constraint_node(); + init_alter_column_builder(); + init_alter_table_executor(); + init_alter_table_add_foreign_key_constraint_builder(); + init_alter_table_drop_constraint_builder(); + init_primary_key_constraint_node(); + init_drop_index_node(); + init_add_index_node(); + init_alter_table_add_index_builder(); + init_unique_constraint_builder(); + init_primary_key_constraint_builder(); + init_check_constraint_builder(); + init_rename_constraint_node(); + AlterTableBuilder = class { + constructor(props) { + __privateAdd(this, _props26); + __privateSet(this, _props26, freeze(props)); + } + renameTo(newTableName) { + return new AlterTableExecutor({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + renameTo: parseTable(newTableName) + }) + }); + } + setSchema(newSchema) { + return new AlterTableExecutor({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + setSchema: IdentifierNode.create(newSchema) + }) + }); + } + alterColumn(column, alteration) { + const builder = alteration(new AlterColumnBuilder(column)); + return new AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, builder.toOperationNode()) + }); + } + dropColumn(column) { + return new AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, DropColumnNode.create(column)) + }); + } + renameColumn(column, newColumn) { + return new AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, RenameColumnNode.create(column, newColumn)) + }); + } + addColumn(columnName, dataType, build = noop) { + const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, AddColumnNode.create(builder.toOperationNode())) + }); + } + modifyColumn(columnName, dataType, build = noop) { + const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, ModifyColumnNode.create(builder.toOperationNode())) + }); + } + /** + * See {@link CreateTableBuilder.addUniqueConstraint} + */ + addUniqueConstraint(constraintName, columns, build = noop) { + const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName))); + return new AlterTableExecutor({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + addConstraint: AddConstraintNode.create(uniqueConstraintBuilder.toOperationNode()) + }) + }); + } + /** + * See {@link CreateTableBuilder.addCheckConstraint} + */ + addCheckConstraint(constraintName, checkExpression, build = noop) { + const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName))); + return new AlterTableExecutor({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) + }) + }); + } + /** + * See {@link CreateTableBuilder.addForeignKeyConstraint} + * + * Unlike {@link CreateTableBuilder.addForeignKeyConstraint} this method returns + * the constraint builder and doesn't take a callback as the last argument. This + * is because you can only add one column per `ALTER TABLE` query. + */ + addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) { + const constraintBuilder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName))); + return new AlterTableAddForeignKeyConstraintBuilder({ + ...__privateGet(this, _props26), + constraintBuilder + }); + } + /** + * See {@link CreateTableBuilder.addPrimaryKeyConstraint} + */ + addPrimaryKeyConstraint(constraintName, columns, build = noop) { + const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName))); + return new AlterTableExecutor({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) + }) + }); + } + dropConstraint(constraintName) { + return new AlterTableDropConstraintBuilder({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + dropConstraint: DropConstraintNode.create(constraintName) + }) + }); + } + renameConstraint(oldName, newName) { + return new AlterTableDropConstraintBuilder({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + renameConstraint: RenameConstraintNode.create(oldName, newName) + }) + }); + } + /** + * This can be used to add index to table. + * + * ### Examples + * + * ```ts + * db.schema.alterTable('person') + * .addIndex('person_email_index') + * .column('email') + * .unique() + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add unique index `person_email_index` (`email`) + * ``` + */ + addIndex(indexName) { + return new AlterTableAddIndexBuilder({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + addIndex: AddIndexNode.create(indexName) + }) + }); + } + /** + * This can be used to drop index from table. + * + * ### Examples + * + * ```ts + * db.schema.alterTable('person') + * .dropIndex('person_email_index') + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` drop index `test_first_name_index` + * ``` + */ + dropIndex(indexName) { + return new AlterTableExecutor({ + ...__privateGet(this, _props26), + node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { + dropIndex: DropIndexNode.create(indexName) + }) + }); + } + /** + * Calls the given function passing `this` as the only argument. + * + * See {@link CreateTableBuilder.$call} + */ + $call(func) { + return func(this); + } + }; + _props26 = new WeakMap(); + _AlterTableColumnAlteringBuilder = class _AlterTableColumnAlteringBuilder { + constructor(props) { + __privateAdd(this, _props27); + __privateSet(this, _props27, freeze(props)); + } + alterColumn(column, alteration) { + const builder = alteration(new AlterColumnBuilder(column)); + return new _AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props27), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, builder.toOperationNode()) + }); + } + dropColumn(column) { + return new _AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props27), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, DropColumnNode.create(column)) + }); + } + renameColumn(column, newColumn) { + return new _AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props27), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, RenameColumnNode.create(column, newColumn)) + }); + } + addColumn(columnName, dataType, build = noop) { + const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new _AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props27), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, AddColumnNode.create(builder.toOperationNode())) + }); + } + modifyColumn(columnName, dataType, build = noop) { + const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new _AlterTableColumnAlteringBuilder({ + ...__privateGet(this, _props27), + node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, ModifyColumnNode.create(builder.toOperationNode())) + }); + } + toOperationNode() { + return __privateGet(this, _props27).executor.transformQuery(__privateGet(this, _props27).node, __privateGet(this, _props27).queryId); + } + compile() { + return __privateGet(this, _props27).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props27).queryId); + } + async execute() { + await __privateGet(this, _props27).executor.executeQuery(this.compile()); + } + }; + _props27 = new WeakMap(); + AlterTableColumnAlteringBuilder = _AlterTableColumnAlteringBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js +var ImmediateValueTransformer; +var init_immediate_value_transformer = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js"() { + init_operation_node_transformer(); + init_value_list_node(); + init_value_node(); + ImmediateValueTransformer = class extends OperationNodeTransformer { + transformPrimitiveValueList(node) { + return ValueListNode.create(node.values.map(ValueNode.createImmediate)); + } + transformValue(node) { + return ValueNode.createImmediate(node.value); + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js +var _props28, _CreateIndexBuilder, CreateIndexBuilder; +var init_create_index_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js"() { + init_create_index_node(); + init_raw_node(); + init_reference_parser(); + init_table_parser(); + init_object_utils(); + init_binary_operation_parser(); + init_query_node(); + init_immediate_value_transformer(); + _CreateIndexBuilder = class _CreateIndexBuilder { + constructor(props) { + __privateAdd(this, _props28); + __privateSet(this, _props28, freeze(props)); + } + /** + * Adds the "if not exists" modifier. + * + * If the index already exists, no error is thrown if this method has been called. + */ + ifNotExists() { + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { + ifNotExists: true + }) + }); + } + /** + * Makes the index unique. + */ + unique() { + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { + unique: true + }) + }); + } + /** + * Adds `nulls not distinct` specifier to index. + * This only works on some dialects like PostgreSQL. + * + * ### Examples + * + * ```ts + * db.schema.createIndex('person_first_name_index') + * .on('person') + * .column('first_name') + * .nullsNotDistinct() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create index "person_first_name_index" + * on "test" ("first_name") + * nulls not distinct; + * ``` + */ + nullsNotDistinct() { + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { + nullsNotDistinct: true + }) + }); + } + /** + * Specifies the table for the index. + */ + on(table) { + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { + table: parseTable(table) + }) + }); + } + /** + * Adds a column to the index. + * + * Also see {@link columns} for adding multiple columns at once or {@link expression} + * for specifying an arbitrary expression. + * + * ### Examples + * + * ```ts + * await db.schema + * .createIndex('person_first_name_and_age_index') + * .on('person') + * .column('first_name') + * .column('age desc') + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc) + * ``` + */ + column(column) { + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: CreateIndexNode.cloneWithColumns(__privateGet(this, _props28).node, [ + parseOrderedColumnName(column) + ]) + }); + } + /** + * Specifies a list of columns for the index. + * + * Also see {@link column} for adding a single column or {@link expression} for + * specifying an arbitrary expression. + * + * ### Examples + * + * ```ts + * await db.schema + * .createIndex('person_first_name_and_age_index') + * .on('person') + * .columns(['first_name', 'age desc']) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc) + * ``` + */ + columns(columns) { + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: CreateIndexNode.cloneWithColumns(__privateGet(this, _props28).node, columns.map(parseOrderedColumnName)) + }); + } + /** + * Specifies an arbitrary expression for the index. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createIndex('person_first_name_index') + * .on('person') + * .expression(sql`first_name COLLATE "fi_FI"`) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create index "person_first_name_index" on "person" (first_name COLLATE "fi_FI") + * ``` + */ + expression(expression) { + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: CreateIndexNode.cloneWithColumns(__privateGet(this, _props28).node, [ + expression.toOperationNode() + ]) + }); + } + using(indexType) { + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { + using: RawNode.createWithSql(indexType) + }) + }); + } + where(...args) { + const transformer = new ImmediateValueTransformer(); + return new _CreateIndexBuilder({ + ...__privateGet(this, _props28), + node: QueryNode.cloneWithWhere(__privateGet(this, _props28).node, transformer.transformNode(parseValueBinaryOperationOrExpression(args), __privateGet(this, _props28).queryId)) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props28).executor.transformQuery(__privateGet(this, _props28).node, __privateGet(this, _props28).queryId); + } + compile() { + return __privateGet(this, _props28).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props28).queryId); + } + async execute() { + await __privateGet(this, _props28).executor.executeQuery(this.compile()); + } + }; + _props28 = new WeakMap(); + CreateIndexBuilder = _CreateIndexBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js +var _props29, _CreateSchemaBuilder, CreateSchemaBuilder; +var init_create_schema_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js"() { + init_create_schema_node(); + init_object_utils(); + _CreateSchemaBuilder = class _CreateSchemaBuilder { + constructor(props) { + __privateAdd(this, _props29); + __privateSet(this, _props29, freeze(props)); + } + ifNotExists() { + return new _CreateSchemaBuilder({ + ...__privateGet(this, _props29), + node: CreateSchemaNode.cloneWith(__privateGet(this, _props29).node, { ifNotExists: true }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props29).executor.transformQuery(__privateGet(this, _props29).node, __privateGet(this, _props29).queryId); + } + compile() { + return __privateGet(this, _props29).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props29).queryId); + } + async execute() { + await __privateGet(this, _props29).executor.executeQuery(this.compile()); + } + }; + _props29 = new WeakMap(); + CreateSchemaBuilder = _CreateSchemaBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js +function parseOnCommitAction(action) { + if (ON_COMMIT_ACTIONS.includes(action)) { + return action; + } + throw new Error(`invalid OnCommitAction ${action}`); +} +var init_on_commit_action_parse = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js"() { + init_create_table_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js +var _props30, _CreateTableBuilder, CreateTableBuilder; +var init_create_table_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js"() { + init_column_definition_node(); + init_create_table_node(); + init_column_definition_builder(); + init_object_utils(); + init_foreign_key_constraint_node(); + init_column_node(); + init_foreign_key_constraint_builder(); + init_data_type_parser(); + init_primary_key_constraint_node(); + init_unique_constraint_node(); + init_check_constraint_node(); + init_table_parser(); + init_on_commit_action_parse(); + init_unique_constraint_builder(); + init_expression_parser(); + init_primary_key_constraint_builder(); + init_check_constraint_builder(); + _CreateTableBuilder = class _CreateTableBuilder { + constructor(props) { + __privateAdd(this, _props30); + __privateSet(this, _props30, freeze(props)); + } + /** + * Adds the "temporary" modifier. + * + * Use this to create a temporary table. + */ + temporary() { + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWith(__privateGet(this, _props30).node, { + temporary: true + }) + }); + } + /** + * Adds an "on commit" statement. + * + * This can be used in conjunction with temporary tables on supported databases + * like PostgreSQL. + */ + onCommit(onCommit) { + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWith(__privateGet(this, _props30).node, { + onCommit: parseOnCommitAction(onCommit) + }) + }); + } + /** + * Adds the "if not exists" modifier. + * + * If the table already exists, no error is thrown if this method has been called. + */ + ifNotExists() { + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWith(__privateGet(this, _props30).node, { + ifNotExists: true + }) + }); + } + /** + * Adds a column to the table. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', (col) => col.autoIncrement().primaryKey()) + * .addColumn('first_name', 'varchar(50)', (col) => col.notNull()) + * .addColumn('last_name', 'varchar(255)') + * .addColumn('bank_balance', 'numeric(8, 2)') + * // You can specify any data type using the `sql` tag if the types + * // don't include it. + * .addColumn('data', sql`any_type_here`) + * .addColumn('parent_id', 'integer', (col) => + * col.references('person.id').onDelete('cascade') + * ) + * ``` + * + * With this method, it's once again good to remember that Kysely just builds the + * query and doesn't provide the same API for all databases. For example, some + * databases like older MySQL don't support the `references` statement in the + * column definition. Instead foreign key constraints need to be defined in the + * `create table` query. See the next example: + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', (col) => col.primaryKey()) + * .addColumn('parent_id', 'integer') + * .addForeignKeyConstraint( + * 'person_parent_id_fk', + * ['parent_id'], + * 'person', + * ['id'], + * (cb) => cb.onDelete('cascade') + * ) + * .execute() + * ``` + * + * Another good example is that PostgreSQL doesn't support the `auto_increment` + * keyword and you need to define an autoincrementing column for example using + * `serial`: + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'serial', (col) => col.primaryKey()) + * .execute() + * ``` + */ + addColumn(columnName, dataType, build = noop) { + const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWithColumn(__privateGet(this, _props30).node, columnBuilder.toOperationNode()) + }); + } + /** + * Adds a primary key constraint for one or more columns. + * + * The constraint name can be anything you want, but it must be unique + * across the whole database. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('first_name', 'varchar(64)') + * .addColumn('last_name', 'varchar(64)') + * .addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name']) + * .execute() + * ``` + */ + addPrimaryKeyConstraint(constraintName, columns, build = noop) { + const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName))); + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWithConstraint(__privateGet(this, _props30).node, constraintBuilder.toOperationNode()) + }); + } + /** + * Adds a unique constraint for one or more columns. + * + * The constraint name can be anything you want, but it must be unique + * across the whole database. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('first_name', 'varchar(64)') + * .addColumn('last_name', 'varchar(64)') + * .addUniqueConstraint( + * 'first_name_last_name_unique', + * ['first_name', 'last_name'] + * ) + * .execute() + * ``` + * + * In dialects such as PostgreSQL you can specify `nulls not distinct` as follows: + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('first_name', 'varchar(64)') + * .addColumn('last_name', 'varchar(64)') + * .addUniqueConstraint( + * 'first_name_last_name_unique', + * ['first_name', 'last_name'], + * (cb) => cb.nullsNotDistinct() + * ) + * .execute() + * ``` + */ + addUniqueConstraint(constraintName, columns, build = noop) { + const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName))); + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWithConstraint(__privateGet(this, _props30).node, uniqueConstraintBuilder.toOperationNode()) + }); + } + /** + * Adds a check constraint. + * + * The constraint name can be anything you want, but it must be unique + * across the whole database. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('animal') + * .addColumn('number_of_legs', 'integer') + * .addCheckConstraint('check_legs', sql`number_of_legs < 5`) + * .execute() + * ``` + */ + addCheckConstraint(constraintName, checkExpression, build = noop) { + const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName))); + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWithConstraint(__privateGet(this, _props30).node, constraintBuilder.toOperationNode()) + }); + } + /** + * Adds a foreign key constraint. + * + * The constraint name can be anything you want, but it must be unique + * across the whole database. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('owner_id', 'integer') + * .addForeignKeyConstraint( + * 'owner_id_foreign', + * ['owner_id'], + * 'person', + * ['id'], + * ) + * .execute() + * ``` + * + * Add constraint for multiple columns: + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('owner_id1', 'integer') + * .addColumn('owner_id2', 'integer') + * .addForeignKeyConstraint( + * 'owner_id_foreign', + * ['owner_id1', 'owner_id2'], + * 'person', + * ['id1', 'id2'], + * (cb) => cb.onDelete('cascade') + * ) + * .execute() + * ``` + */ + addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) { + const builder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName))); + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWithConstraint(__privateGet(this, _props30).node, builder.toOperationNode()) + }); + } + /** + * This can be used to add any additional SQL to the front of the query __after__ the `create` keyword. + * + * Also see {@link temporary}. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .modifyFront(sql`global temporary`) + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn('first_name', 'varchar(64)', col => col.notNull()) + * .addColumn('last_name', 'varchar(64)', col => col.notNull()) + * .execute() + * ``` + * + * The generated SQL (Postgres): + * + * ```sql + * create global temporary table "person" ( + * "id" integer primary key, + * "first_name" varchar(64) not null, + * "last_name" varchar(64) not null + * ) + * ``` + */ + modifyFront(modifier) { + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWithFrontModifier(__privateGet(this, _props30).node, modifier.toOperationNode()) + }); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * Also see {@link onCommit}. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn('first_name', 'varchar(64)', col => col.notNull()) + * .addColumn('last_name', 'varchar(64)', col => col.notNull()) + * .modifyEnd(sql`collate utf8_unicode_ci`) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key, + * `first_name` varchar(64) not null, + * `last_name` varchar(64) not null + * ) collate utf8_unicode_ci + * ``` + */ + modifyEnd(modifier) { + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWithEndModifier(__privateGet(this, _props30).node, modifier.toOperationNode()) + }); + } + /** + * Allows to create table from `select` query. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('copy') + * .temporary() + * .as(db.selectFrom('person').select(['first_name', 'last_name'])) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create temporary table "copy" as + * select "first_name", "last_name" from "person" + * ``` + */ + as(expression) { + return new _CreateTableBuilder({ + ...__privateGet(this, _props30), + node: CreateTableNode.cloneWith(__privateGet(this, _props30).node, { + selectQuery: parseExpression(expression) + }) + }); + } + /** + * Calls the given function passing `this` as the only argument. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('test') + * .$call((builder) => builder.addColumn('id', 'integer')) + * .execute() + * ``` + * + * This is useful for creating reusable functions that can be called with a builder. + * + * ```ts + * import { type CreateTableBuilder, sql } from 'kysely' + * + * const addDefaultColumns = (ctb: CreateTableBuilder) => { + * return ctb + * .addColumn('id', 'integer', (col) => col.notNull()) + * .addColumn('created_at', 'date', (col) => + * col.notNull().defaultTo(sql`now()`) + * ) + * .addColumn('updated_at', 'date', (col) => + * col.notNull().defaultTo(sql`now()`) + * ) + * } + * + * await db.schema + * .createTable('test') + * .$call(addDefaultColumns) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props30).executor.transformQuery(__privateGet(this, _props30).node, __privateGet(this, _props30).queryId); + } + compile() { + return __privateGet(this, _props30).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props30).queryId); + } + async execute() { + await __privateGet(this, _props30).executor.executeQuery(this.compile()); + } + }; + _props30 = new WeakMap(); + CreateTableBuilder = _CreateTableBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js +var _props31, _DropIndexBuilder, DropIndexBuilder; +var init_drop_index_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js"() { + init_drop_index_node(); + init_table_parser(); + init_object_utils(); + _DropIndexBuilder = class _DropIndexBuilder { + constructor(props) { + __privateAdd(this, _props31); + __privateSet(this, _props31, freeze(props)); + } + /** + * Specifies the table the index was created for. This is not needed + * in all dialects. + */ + on(table) { + return new _DropIndexBuilder({ + ...__privateGet(this, _props31), + node: DropIndexNode.cloneWith(__privateGet(this, _props31).node, { + table: parseTable(table) + }) + }); + } + ifExists() { + return new _DropIndexBuilder({ + ...__privateGet(this, _props31), + node: DropIndexNode.cloneWith(__privateGet(this, _props31).node, { + ifExists: true + }) + }); + } + cascade() { + return new _DropIndexBuilder({ + ...__privateGet(this, _props31), + node: DropIndexNode.cloneWith(__privateGet(this, _props31).node, { + cascade: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props31).executor.transformQuery(__privateGet(this, _props31).node, __privateGet(this, _props31).queryId); + } + compile() { + return __privateGet(this, _props31).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props31).queryId); + } + async execute() { + await __privateGet(this, _props31).executor.executeQuery(this.compile()); + } + }; + _props31 = new WeakMap(); + DropIndexBuilder = _DropIndexBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js +var _props32, _DropSchemaBuilder, DropSchemaBuilder; +var init_drop_schema_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js"() { + init_drop_schema_node(); + init_object_utils(); + _DropSchemaBuilder = class _DropSchemaBuilder { + constructor(props) { + __privateAdd(this, _props32); + __privateSet(this, _props32, freeze(props)); + } + ifExists() { + return new _DropSchemaBuilder({ + ...__privateGet(this, _props32), + node: DropSchemaNode.cloneWith(__privateGet(this, _props32).node, { + ifExists: true + }) + }); + } + cascade() { + return new _DropSchemaBuilder({ + ...__privateGet(this, _props32), + node: DropSchemaNode.cloneWith(__privateGet(this, _props32).node, { + cascade: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props32).executor.transformQuery(__privateGet(this, _props32).node, __privateGet(this, _props32).queryId); + } + compile() { + return __privateGet(this, _props32).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props32).queryId); + } + async execute() { + await __privateGet(this, _props32).executor.executeQuery(this.compile()); + } + }; + _props32 = new WeakMap(); + DropSchemaBuilder = _DropSchemaBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js +var _props33, _DropTableBuilder, DropTableBuilder; +var init_drop_table_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js"() { + init_drop_table_node(); + init_object_utils(); + _DropTableBuilder = class _DropTableBuilder { + constructor(props) { + __privateAdd(this, _props33); + __privateSet(this, _props33, freeze(props)); + } + ifExists() { + return new _DropTableBuilder({ + ...__privateGet(this, _props33), + node: DropTableNode.cloneWith(__privateGet(this, _props33).node, { + ifExists: true + }) + }); + } + cascade() { + return new _DropTableBuilder({ + ...__privateGet(this, _props33), + node: DropTableNode.cloneWith(__privateGet(this, _props33).node, { + cascade: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props33).executor.transformQuery(__privateGet(this, _props33).node, __privateGet(this, _props33).queryId); + } + compile() { + return __privateGet(this, _props33).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props33).queryId); + } + async execute() { + await __privateGet(this, _props33).executor.executeQuery(this.compile()); + } + }; + _props33 = new WeakMap(); + DropTableBuilder = _DropTableBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js +var CreateViewNode; +var init_create_view_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + CreateViewNode = freeze({ + is(node) { + return node.kind === "CreateViewNode"; + }, + create(name) { + return freeze({ + kind: "CreateViewNode", + name: SchemableIdentifierNode.create(name) + }); + }, + cloneWith(createView3, params) { + return freeze({ + ...createView3, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js +var _transformer2, ImmediateValuePlugin; +var init_immediate_value_plugin = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js"() { + init_immediate_value_transformer(); + ImmediateValuePlugin = class { + constructor() { + __privateAdd(this, _transformer2, new ImmediateValueTransformer()); + } + transformQuery(args) { + return __privateGet(this, _transformer2).transformNode(args.node, args.queryId); + } + transformResult(args) { + return Promise.resolve(args.result); + } + }; + _transformer2 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js +var _props34, _CreateViewBuilder, CreateViewBuilder; +var init_create_view_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js"() { + init_object_utils(); + init_create_view_node(); + init_reference_parser(); + init_immediate_value_plugin(); + _CreateViewBuilder = class _CreateViewBuilder { + constructor(props) { + __privateAdd(this, _props34); + __privateSet(this, _props34, freeze(props)); + } + /** + * Adds the "temporary" modifier. + * + * Use this to create a temporary view. + */ + temporary() { + return new _CreateViewBuilder({ + ...__privateGet(this, _props34), + node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { + temporary: true + }) + }); + } + materialized() { + return new _CreateViewBuilder({ + ...__privateGet(this, _props34), + node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { + materialized: true + }) + }); + } + /** + * Only implemented on some dialects like SQLite. On most dialects, use {@link orReplace}. + */ + ifNotExists() { + return new _CreateViewBuilder({ + ...__privateGet(this, _props34), + node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { + ifNotExists: true + }) + }); + } + orReplace() { + return new _CreateViewBuilder({ + ...__privateGet(this, _props34), + node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { + orReplace: true + }) + }); + } + columns(columns) { + return new _CreateViewBuilder({ + ...__privateGet(this, _props34), + node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { + columns: columns.map(parseColumnName) + }) + }); + } + /** + * Sets the select query or a `values` statement that creates the view. + * + * WARNING! + * Some dialects don't support parameterized queries in DDL statements and therefore + * the query or raw {@link sql } expression passed here is interpolated into a single + * string opening an SQL injection vulnerability. DO NOT pass unchecked user input + * into the query or raw expression passed to this method! + */ + as(query) { + const queryNode = query.withPlugin(new ImmediateValuePlugin()).toOperationNode(); + return new _CreateViewBuilder({ + ...__privateGet(this, _props34), + node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { + as: queryNode + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props34).executor.transformQuery(__privateGet(this, _props34).node, __privateGet(this, _props34).queryId); + } + compile() { + return __privateGet(this, _props34).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props34).queryId); + } + async execute() { + await __privateGet(this, _props34).executor.executeQuery(this.compile()); + } + }; + _props34 = new WeakMap(); + CreateViewBuilder = _CreateViewBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js +var DropViewNode; +var init_drop_view_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + DropViewNode = freeze({ + is(node) { + return node.kind === "DropViewNode"; + }, + create(name) { + return freeze({ + kind: "DropViewNode", + name: SchemableIdentifierNode.create(name) + }); + }, + cloneWith(dropView, params) { + return freeze({ + ...dropView, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js +var _props35, _DropViewBuilder, DropViewBuilder; +var init_drop_view_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js"() { + init_object_utils(); + init_drop_view_node(); + _DropViewBuilder = class _DropViewBuilder { + constructor(props) { + __privateAdd(this, _props35); + __privateSet(this, _props35, freeze(props)); + } + materialized() { + return new _DropViewBuilder({ + ...__privateGet(this, _props35), + node: DropViewNode.cloneWith(__privateGet(this, _props35).node, { + materialized: true + }) + }); + } + ifExists() { + return new _DropViewBuilder({ + ...__privateGet(this, _props35), + node: DropViewNode.cloneWith(__privateGet(this, _props35).node, { + ifExists: true + }) + }); + } + cascade() { + return new _DropViewBuilder({ + ...__privateGet(this, _props35), + node: DropViewNode.cloneWith(__privateGet(this, _props35).node, { + cascade: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props35).executor.transformQuery(__privateGet(this, _props35).node, __privateGet(this, _props35).queryId); + } + compile() { + return __privateGet(this, _props35).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props35).queryId); + } + async execute() { + await __privateGet(this, _props35).executor.executeQuery(this.compile()); + } + }; + _props35 = new WeakMap(); + DropViewBuilder = _DropViewBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js +var CreateTypeNode; +var init_create_type_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js"() { + init_object_utils(); + init_value_list_node(); + init_value_node(); + CreateTypeNode = freeze({ + is(node) { + return node.kind === "CreateTypeNode"; + }, + create(name) { + return freeze({ + kind: "CreateTypeNode", + name + }); + }, + cloneWithEnum(createType, values) { + return freeze({ + ...createType, + enum: ValueListNode.create(values.map(ValueNode.createImmediate)) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js +var _props36, _CreateTypeBuilder, CreateTypeBuilder; +var init_create_type_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js"() { + init_object_utils(); + init_create_type_node(); + _CreateTypeBuilder = class _CreateTypeBuilder { + constructor(props) { + __privateAdd(this, _props36); + __privateSet(this, _props36, freeze(props)); + } + toOperationNode() { + return __privateGet(this, _props36).executor.transformQuery(__privateGet(this, _props36).node, __privateGet(this, _props36).queryId); + } + /** + * Creates an anum type. + * + * ### Examples + * + * ```ts + * db.schema.createType('species').asEnum(['cat', 'dog', 'frog']) + * ``` + */ + asEnum(values) { + return new _CreateTypeBuilder({ + ...__privateGet(this, _props36), + node: CreateTypeNode.cloneWithEnum(__privateGet(this, _props36).node, values) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + compile() { + return __privateGet(this, _props36).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props36).queryId); + } + async execute() { + await __privateGet(this, _props36).executor.executeQuery(this.compile()); + } + }; + _props36 = new WeakMap(); + CreateTypeBuilder = _CreateTypeBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js +var DropTypeNode; +var init_drop_type_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js"() { + init_object_utils(); + DropTypeNode = freeze({ + is(node) { + return node.kind === "DropTypeNode"; + }, + create(name) { + return freeze({ + kind: "DropTypeNode", + name + }); + }, + cloneWith(dropType, params) { + return freeze({ + ...dropType, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js +var _props37, _DropTypeBuilder, DropTypeBuilder; +var init_drop_type_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js"() { + init_drop_type_node(); + init_object_utils(); + _DropTypeBuilder = class _DropTypeBuilder { + constructor(props) { + __privateAdd(this, _props37); + __privateSet(this, _props37, freeze(props)); + } + ifExists() { + return new _DropTypeBuilder({ + ...__privateGet(this, _props37), + node: DropTypeNode.cloneWith(__privateGet(this, _props37).node, { + ifExists: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props37).executor.transformQuery(__privateGet(this, _props37).node, __privateGet(this, _props37).queryId); + } + compile() { + return __privateGet(this, _props37).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props37).queryId); + } + async execute() { + await __privateGet(this, _props37).executor.executeQuery(this.compile()); + } + }; + _props37 = new WeakMap(); + DropTypeBuilder = _DropTypeBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js +function parseSchemableIdentifier(id) { + const SCHEMA_SEPARATOR = "."; + if (id.includes(SCHEMA_SEPARATOR)) { + const parts = id.split(SCHEMA_SEPARATOR).map(trim3); + if (parts.length === 2) { + return SchemableIdentifierNode.createWithSchema(parts[0], parts[1]); + } else { + throw new Error(`invalid schemable identifier ${id}`); + } + } else { + return SchemableIdentifierNode.create(id); + } +} +function trim3(str) { + return str.trim(); +} +var init_identifier_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js"() { + init_schemable_identifier_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js +var RefreshMaterializedViewNode; +var init_refresh_materialized_view_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + RefreshMaterializedViewNode = freeze({ + is(node) { + return node.kind === "RefreshMaterializedViewNode"; + }, + create(name) { + return freeze({ + kind: "RefreshMaterializedViewNode", + name: SchemableIdentifierNode.create(name) + }); + }, + cloneWith(createView3, params) { + return freeze({ + ...createView3, + ...params + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js +var _props38, _RefreshMaterializedViewBuilder, RefreshMaterializedViewBuilder; +var init_refresh_materialized_view_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js"() { + init_object_utils(); + init_refresh_materialized_view_node(); + _RefreshMaterializedViewBuilder = class _RefreshMaterializedViewBuilder { + constructor(props) { + __privateAdd(this, _props38); + __privateSet(this, _props38, freeze(props)); + } + /** + * Adds the "concurrently" modifier. + * + * Use this to refresh the view without locking out concurrent selects on the materialized view. + * + * WARNING! + * This cannot be used with the "with no data" modifier. + */ + concurrently() { + return new _RefreshMaterializedViewBuilder({ + ...__privateGet(this, _props38), + node: RefreshMaterializedViewNode.cloneWith(__privateGet(this, _props38).node, { + concurrently: true, + withNoData: false + }) + }); + } + /** + * Adds the "with data" modifier. + * + * If specified (or defaults) the backing query is executed to provide the new data, and the materialized view is left in a scannable state + */ + withData() { + return new _RefreshMaterializedViewBuilder({ + ...__privateGet(this, _props38), + node: RefreshMaterializedViewNode.cloneWith(__privateGet(this, _props38).node, { + withNoData: false + }) + }); + } + /** + * Adds the "with no data" modifier. + * + * If specified, no new data is generated and the materialized view is left in an unscannable state. + * + * WARNING! + * This cannot be used with the "concurrently" modifier. + */ + withNoData() { + return new _RefreshMaterializedViewBuilder({ + ...__privateGet(this, _props38), + node: RefreshMaterializedViewNode.cloneWith(__privateGet(this, _props38).node, { + withNoData: true, + concurrently: false + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return __privateGet(this, _props38).executor.transformQuery(__privateGet(this, _props38).node, __privateGet(this, _props38).queryId); + } + compile() { + return __privateGet(this, _props38).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props38).queryId); + } + async execute() { + await __privateGet(this, _props38).executor.executeQuery(this.compile()); + } + }; + _props38 = new WeakMap(); + RefreshMaterializedViewBuilder = _RefreshMaterializedViewBuilder; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js +var _executor, _SchemaModule, SchemaModule; +var init_schema = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js"() { + init_alter_table_node(); + init_create_index_node(); + init_create_schema_node(); + init_create_table_node(); + init_drop_index_node(); + init_drop_schema_node(); + init_drop_table_node(); + init_table_parser(); + init_alter_table_builder(); + init_create_index_builder(); + init_create_schema_builder(); + init_create_table_builder(); + init_drop_index_builder(); + init_drop_schema_builder(); + init_drop_table_builder(); + init_query_id(); + init_with_schema_plugin(); + init_create_view_builder(); + init_create_view_node(); + init_drop_view_builder(); + init_drop_view_node(); + init_create_type_builder(); + init_drop_type_builder(); + init_create_type_node(); + init_drop_type_node(); + init_identifier_parser(); + init_refresh_materialized_view_builder(); + init_refresh_materialized_view_node(); + _SchemaModule = class _SchemaModule { + constructor(executor) { + __privateAdd(this, _executor); + __privateSet(this, _executor, executor); + } + /** + * Create a new table. + * + * ### Examples + * + * This example creates a new table with columns `id`, `first_name`, + * `last_name` and `gender`: + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) + * .addColumn('first_name', 'varchar', col => col.notNull()) + * .addColumn('last_name', 'varchar', col => col.notNull()) + * .addColumn('gender', 'varchar') + * .execute() + * ``` + * + * This example creates a table with a foreign key. Not all database + * engines support column-level foreign key constraint definitions. + * For example if you are using MySQL 5.X see the next example after + * this one. + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) + * .addColumn('owner_id', 'integer', col => col + * .references('person.id') + * .onDelete('cascade') + * ) + * .execute() + * ``` + * + * This example adds a foreign key constraint for a columns just + * like the previous example, but using a table-level statement. + * On MySQL 5.X you need to define foreign key constraints like + * this: + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) + * .addColumn('owner_id', 'integer') + * .addForeignKeyConstraint( + * 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'], + * (constraint) => constraint.onDelete('cascade') + * ) + * .execute() + * ``` + */ + createTable(table) { + return new CreateTableBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: CreateTableNode.create(parseTable(table)) + }); + } + /** + * Drop a table. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropTable('person') + * .execute() + * ``` + */ + dropTable(table) { + return new DropTableBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: DropTableNode.create(parseTable(table)) + }); + } + /** + * Create a new index. + * + * ### Examples + * + * ```ts + * await db.schema + * .createIndex('person_full_name_unique_index') + * .on('person') + * .columns(['first_name', 'last_name']) + * .execute() + * ``` + */ + createIndex(indexName) { + return new CreateIndexBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: CreateIndexNode.create(indexName) + }); + } + /** + * Drop an index. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropIndex('person_full_name_unique_index') + * .execute() + * ``` + */ + dropIndex(indexName) { + return new DropIndexBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: DropIndexNode.create(indexName) + }); + } + /** + * Create a new schema. + * + * ### Examples + * + * ```ts + * await db.schema + * .createSchema('some_schema') + * .execute() + * ``` + */ + createSchema(schema3) { + return new CreateSchemaBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: CreateSchemaNode.create(schema3) + }); + } + /** + * Drop a schema. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropSchema('some_schema') + * .execute() + * ``` + */ + dropSchema(schema3) { + return new DropSchemaBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: DropSchemaNode.create(schema3) + }); + } + /** + * Alter a table. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .alterColumn('first_name', (ac) => ac.setDataType('text')) + * .execute() + * ``` + */ + alterTable(table) { + return new AlterTableBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: AlterTableNode.create(parseTable(table)) + }); + } + /** + * Create a new view. + * + * ### Examples + * + * ```ts + * await db.schema + * .createView('dogs') + * .orReplace() + * .as(db.selectFrom('pet').selectAll().where('species', '=', 'dog')) + * .execute() + * ``` + */ + createView(viewName) { + return new CreateViewBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: CreateViewNode.create(viewName) + }); + } + /** + * Refresh a materialized view. + * + * ### Examples + * + * ```ts + * await db.schema + * .refreshMaterializedView('my_view') + * .concurrently() + * .execute() + * ``` + */ + refreshMaterializedView(viewName) { + return new RefreshMaterializedViewBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: RefreshMaterializedViewNode.create(viewName) + }); + } + /** + * Drop a view. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropView('dogs') + * .ifExists() + * .execute() + * ``` + */ + dropView(viewName) { + return new DropViewBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: DropViewNode.create(viewName) + }); + } + /** + * Create a new type. + * + * Only some dialects like PostgreSQL have user-defined types. + * + * ### Examples + * + * ```ts + * await db.schema + * .createType('species') + * .asEnum(['dog', 'cat', 'frog']) + * .execute() + * ``` + */ + createType(typeName) { + return new CreateTypeBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: CreateTypeNode.create(parseSchemableIdentifier(typeName)) + }); + } + /** + * Drop a type. + * + * Only some dialects like PostgreSQL have user-defined types. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropType('species') + * .ifExists() + * .execute() + * ``` + */ + dropType(typeName) { + return new DropTypeBuilder({ + queryId: createQueryId(), + executor: __privateGet(this, _executor), + node: DropTypeNode.create(parseSchemableIdentifier(typeName)) + }); + } + /** + * Returns a copy of this schema module with the given plugin installed. + */ + withPlugin(plugin) { + return new _SchemaModule(__privateGet(this, _executor).withPlugin(plugin)); + } + /** + * Returns a copy of this schema module without any plugins. + */ + withoutPlugins() { + return new _SchemaModule(__privateGet(this, _executor).withoutPlugins()); + } + /** + * See {@link QueryCreator.withSchema} + */ + withSchema(schema3) { + return new _SchemaModule(__privateGet(this, _executor).withPluginAtFront(new WithSchemaPlugin(schema3))); + } + }; + _executor = new WeakMap(); + SchemaModule = _SchemaModule; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js +var DynamicModule; +var init_dynamic = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js"() { + init_dynamic_reference_builder(); + init_dynamic_table_builder(); + DynamicModule = class { + /** + * Creates a dynamic reference to a column that is not know at compile time. + * + * Kysely is built in a way that by default you can't refer to tables or columns + * that are not actually visible in the current query and context. This is all + * done by TypeScript at compile time, which means that you need to know the + * columns and tables at compile time. This is not always the case of course. + * + * This method is meant to be used in those cases where the column names + * come from the user input or are not otherwise known at compile time. + * + * WARNING! Unlike values, column names are not escaped by the database engine + * or Kysely and if you pass in unchecked column names using this method, you + * create an SQL injection vulnerability. Always __always__ validate the user + * input before passing it to this method. + * + * There are couple of examples below for some use cases, but you can pass + * `ref` to other methods as well. If the types allow you to pass a `ref` + * value to some place, it should work. + * + * ### Examples + * + * Filter by a column not know at compile time: + * + * ```ts + * async function someQuery(filterColumn: string, filterValue: string) { + * const { ref } = db.dynamic + * + * return await db + * .selectFrom('person') + * .selectAll() + * .where(ref(filterColumn), '=', filterValue) + * .execute() + * } + * + * someQuery('first_name', 'Arnold') + * someQuery('person.last_name', 'Aniston') + * ``` + * + * Order by a column not know at compile time: + * + * ```ts + * async function someQuery(orderBy: string) { + * const { ref } = db.dynamic + * + * return await db + * .selectFrom('person') + * .select('person.first_name as fn') + * .orderBy(ref(orderBy)) + * .execute() + * } + * + * someQuery('fn') + * ``` + * + * In this example we add selections dynamically: + * + * ```ts + * const { ref } = db.dynamic + * + * // Some column name provided by the user. Value not known at compile time. + * const columnFromUserInput: PossibleColumns = 'birthdate'; + * + * // A type that lists all possible values `columnFromUserInput` can have. + * // You can use `keyof Person` if any column of an interface is allowed. + * type PossibleColumns = 'last_name' | 'first_name' | 'birthdate' + * + * const [person] = await db.selectFrom('person') + * .select([ + * ref(columnFromUserInput), + * 'id' + * ]) + * .execute() + * + * // The resulting type contains all `PossibleColumns` as optional fields + * // because we cannot know which field was actually selected before + * // running the code. + * const lastName: string | null | undefined = person?.last_name + * const firstName: string | undefined = person?.first_name + * const birthDate: Date | null | undefined = person?.birthdate + * + * // The result type also contains the compile time selection `id`. + * person?.id + * ``` + */ + ref(reference) { + return new DynamicReferenceBuilder(reference); + } + /** + * Creates a table reference to a table that's not fully known at compile time. + * + * The type `T` is allowed to be a union of multiple tables. + * + * + * + * A generic type-safe helper function for finding a row by a column value: + * + * ```ts + * import { SelectType } from 'kysely' + * import { Database } from 'type-editor' + * + * async function getRowByColumn< + * T extends keyof Database, + * C extends keyof Database[T] & string, + * V extends SelectType, + * >(t: T, c: C, v: V) { + * // We need to use the dynamic module since the table name + * // is not known at compile time. + * const { table, ref } = db.dynamic + * + * return await db + * .selectFrom(table(t).as('t')) + * .selectAll() + * .where(ref(c), '=', v) + * .orderBy('t.id') + * .executeTakeFirstOrThrow() + * } + * + * const person = await getRowByColumn('person', 'first_name', 'Arnold') + * ``` + */ + table(table) { + return new DynamicTableBuilder(table); + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js +var _driver, DefaultConnectionProvider; +var init_default_connection_provider = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js"() { + DefaultConnectionProvider = class { + constructor(driver) { + __privateAdd(this, _driver); + __privateSet(this, _driver, driver); + } + async provideConnection(consumer) { + const connection = await __privateGet(this, _driver).acquireConnection(); + try { + return await consumer(connection); + } finally { + await __privateGet(this, _driver).releaseConnection(connection); + } + } + }; + _driver = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js +var _compiler, _adapter, _connectionProvider, _DefaultQueryExecutor, DefaultQueryExecutor; +var init_default_query_executor = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js"() { + init_query_executor_base(); + _DefaultQueryExecutor = class _DefaultQueryExecutor extends QueryExecutorBase { + constructor(compiler, adapter, connectionProvider, plugins = []) { + super(plugins); + __privateAdd(this, _compiler); + __privateAdd(this, _adapter); + __privateAdd(this, _connectionProvider); + __privateSet(this, _compiler, compiler); + __privateSet(this, _adapter, adapter); + __privateSet(this, _connectionProvider, connectionProvider); + } + get adapter() { + return __privateGet(this, _adapter); + } + compileQuery(node, queryId) { + return __privateGet(this, _compiler).compileQuery(node, queryId); + } + provideConnection(consumer) { + return __privateGet(this, _connectionProvider).provideConnection(consumer); + } + withPlugins(plugins) { + return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), __privateGet(this, _connectionProvider), [...this.plugins, ...plugins]); + } + withPlugin(plugin) { + return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), __privateGet(this, _connectionProvider), [...this.plugins, plugin]); + } + withPluginAtFront(plugin) { + return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), __privateGet(this, _connectionProvider), [plugin, ...this.plugins]); + } + withConnectionProvider(connectionProvider) { + return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), connectionProvider, [...this.plugins]); + } + withoutPlugins() { + return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), __privateGet(this, _connectionProvider), []); + } + }; + _compiler = new WeakMap(); + _adapter = new WeakMap(); + _connectionProvider = new WeakMap(); + DefaultQueryExecutor = _DefaultQueryExecutor; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js +function performanceNow() { + if (typeof performance !== "undefined" && isFunction3(performance.now)) { + return performance.now(); + } else { + return Date.now(); + } +} +var init_performance_now = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js"() { + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js +var _driver2, _log, _initPromise, _initDone, _destroyPromise, _connections, _RuntimeDriver_instances, needsLogging_fn, addLogging_fn, logError_fn, logQuery_fn, calculateDurationMillis_fn, RuntimeDriver; +var init_runtime_driver = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js"() { + init_performance_now(); + RuntimeDriver = class { + constructor(driver, log) { + __privateAdd(this, _RuntimeDriver_instances); + __privateAdd(this, _driver2); + __privateAdd(this, _log); + __privateAdd(this, _initPromise); + __privateAdd(this, _initDone); + __privateAdd(this, _destroyPromise); + __privateAdd(this, _connections, /* @__PURE__ */ new WeakSet()); + __privateSet(this, _initDone, false); + __privateSet(this, _driver2, driver); + __privateSet(this, _log, log); + } + async init() { + if (__privateGet(this, _destroyPromise)) { + throw new Error("driver has already been destroyed"); + } + if (!__privateGet(this, _initPromise)) { + __privateSet(this, _initPromise, __privateGet(this, _driver2).init().then(() => { + __privateSet(this, _initDone, true); + }).catch((err) => { + __privateSet(this, _initPromise, void 0); + return Promise.reject(err); + })); + } + await __privateGet(this, _initPromise); + } + async acquireConnection() { + if (__privateGet(this, _destroyPromise)) { + throw new Error("driver has already been destroyed"); + } + if (!__privateGet(this, _initDone)) { + await this.init(); + } + const connection = await __privateGet(this, _driver2).acquireConnection(); + if (!__privateGet(this, _connections).has(connection)) { + if (__privateMethod(this, _RuntimeDriver_instances, needsLogging_fn).call(this)) { + __privateMethod(this, _RuntimeDriver_instances, addLogging_fn).call(this, connection); + } + __privateGet(this, _connections).add(connection); + } + return connection; + } + async releaseConnection(connection) { + await __privateGet(this, _driver2).releaseConnection(connection); + } + beginTransaction(connection, settings) { + return __privateGet(this, _driver2).beginTransaction(connection, settings); + } + commitTransaction(connection) { + return __privateGet(this, _driver2).commitTransaction(connection); + } + rollbackTransaction(connection) { + return __privateGet(this, _driver2).rollbackTransaction(connection); + } + savepoint(connection, savepointName, compileQuery) { + if (__privateGet(this, _driver2).savepoint) { + return __privateGet(this, _driver2).savepoint(connection, savepointName, compileQuery); + } + throw new Error("The `savepoint` method is not supported by this driver"); + } + rollbackToSavepoint(connection, savepointName, compileQuery) { + if (__privateGet(this, _driver2).rollbackToSavepoint) { + return __privateGet(this, _driver2).rollbackToSavepoint(connection, savepointName, compileQuery); + } + throw new Error("The `rollbackToSavepoint` method is not supported by this driver"); + } + releaseSavepoint(connection, savepointName, compileQuery) { + if (__privateGet(this, _driver2).releaseSavepoint) { + return __privateGet(this, _driver2).releaseSavepoint(connection, savepointName, compileQuery); + } + throw new Error("The `releaseSavepoint` method is not supported by this driver"); + } + async destroy() { + if (!__privateGet(this, _initPromise)) { + return; + } + await __privateGet(this, _initPromise); + if (!__privateGet(this, _destroyPromise)) { + __privateSet(this, _destroyPromise, __privateGet(this, _driver2).destroy().catch((err) => { + __privateSet(this, _destroyPromise, void 0); + return Promise.reject(err); + })); + } + await __privateGet(this, _destroyPromise); + } + }; + _driver2 = new WeakMap(); + _log = new WeakMap(); + _initPromise = new WeakMap(); + _initDone = new WeakMap(); + _destroyPromise = new WeakMap(); + _connections = new WeakMap(); + _RuntimeDriver_instances = new WeakSet(); + needsLogging_fn = function() { + return __privateGet(this, _log).isLevelEnabled("query") || __privateGet(this, _log).isLevelEnabled("error"); + }; + // This method monkey patches the database connection's executeQuery method + // by adding logging code around it. Monkey patching is not pretty, but it's + // the best option in this case. + addLogging_fn = function(connection) { + const executeQuery = connection.executeQuery; + const streamQuery = connection.streamQuery; + const dis = this; + connection.executeQuery = async (compiledQuery) => { + var _a30, _b2; + let caughtError; + const startTime = performanceNow(); + try { + return await executeQuery.call(connection, compiledQuery); + } catch (error49) { + caughtError = error49; + await __privateMethod(_a30 = dis, _RuntimeDriver_instances, logError_fn).call(_a30, error49, compiledQuery, startTime); + throw error49; + } finally { + if (!caughtError) { + await __privateMethod(_b2 = dis, _RuntimeDriver_instances, logQuery_fn).call(_b2, compiledQuery, startTime); + } + } + }; + connection.streamQuery = async function* (compiledQuery, chunkSize) { + var _a30, _b2; + let caughtError; + const startTime = performanceNow(); + try { + for await (const result of streamQuery.call(connection, compiledQuery, chunkSize)) { + yield result; + } + } catch (error49) { + caughtError = error49; + await __privateMethod(_a30 = dis, _RuntimeDriver_instances, logError_fn).call(_a30, error49, compiledQuery, startTime); + throw error49; + } finally { + if (!caughtError) { + await __privateMethod(_b2 = dis, _RuntimeDriver_instances, logQuery_fn).call(_b2, compiledQuery, startTime, true); + } + } + }; + }; + logError_fn = async function(error49, compiledQuery, startTime) { + await __privateGet(this, _log).error(() => ({ + level: "error", + error: error49, + query: compiledQuery, + queryDurationMillis: __privateMethod(this, _RuntimeDriver_instances, calculateDurationMillis_fn).call(this, startTime) + })); + }; + logQuery_fn = async function(compiledQuery, startTime, isStream = false) { + await __privateGet(this, _log).query(() => ({ + level: "query", + isStream, + query: compiledQuery, + queryDurationMillis: __privateMethod(this, _RuntimeDriver_instances, calculateDurationMillis_fn).call(this, startTime) + })); + }; + calculateDurationMillis_fn = function(startTime) { + return performanceNow() - startTime; + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js +var ignoreError, _connection, _runningPromise, _SingleConnectionProvider_instances, run_fn, SingleConnectionProvider; +var init_single_connection_provider = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js"() { + ignoreError = () => { + }; + SingleConnectionProvider = class { + constructor(connection) { + __privateAdd(this, _SingleConnectionProvider_instances); + __privateAdd(this, _connection); + __privateAdd(this, _runningPromise); + __privateSet(this, _connection, connection); + } + async provideConnection(consumer) { + while (__privateGet(this, _runningPromise)) { + await __privateGet(this, _runningPromise).catch(ignoreError); + } + __privateSet(this, _runningPromise, __privateMethod(this, _SingleConnectionProvider_instances, run_fn).call(this, consumer).finally(() => { + __privateSet(this, _runningPromise, void 0); + })); + return __privateGet(this, _runningPromise); + } + }; + _connection = new WeakMap(); + _runningPromise = new WeakMap(); + _SingleConnectionProvider_instances = new WeakSet(); + run_fn = async function(runner) { + return await runner(__privateGet(this, _connection)); + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js +function validateTransactionSettings(settings) { + if (settings.accessMode && !TRANSACTION_ACCESS_MODES.includes(settings.accessMode)) { + throw new Error(`invalid transaction access mode ${settings.accessMode}`); + } + if (settings.isolationLevel && !TRANSACTION_ISOLATION_LEVELS.includes(settings.isolationLevel)) { + throw new Error(`invalid transaction isolation level ${settings.isolationLevel}`); + } +} +var TRANSACTION_ACCESS_MODES, TRANSACTION_ISOLATION_LEVELS; +var init_driver = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js"() { + TRANSACTION_ACCESS_MODES = ["read only", "read write"]; + TRANSACTION_ISOLATION_LEVELS = [ + "read uncommitted", + "read committed", + "repeatable read", + "serializable", + "snapshot" + ]; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js +function defaultLogger(event) { + if (event.level === "query") { + const prefix = `kysely:query:${event.isStream ? "stream:" : ""}`; + console.log(`${prefix} ${event.query.sql}`); + console.log(`${prefix} duration: ${event.queryDurationMillis.toFixed(1)}ms`); + } else if (event.level === "error") { + if (event.error instanceof Error) { + console.error(`kysely:error: ${event.error.stack ?? event.error.message}`); + } else { + console.error(`kysely:error: ${JSON.stringify({ + error: event.error, + query: event.query.sql, + queryDurationMillis: event.queryDurationMillis + })}`); + } + } +} +var logLevels, LOG_LEVELS, _levels, _logger, Log; +var init_log = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js"() { + init_object_utils(); + logLevels = ["query", "error"]; + LOG_LEVELS = freeze(logLevels); + Log = class { + constructor(config4) { + __privateAdd(this, _levels); + __privateAdd(this, _logger); + if (isFunction3(config4)) { + __privateSet(this, _logger, config4); + __privateSet(this, _levels, freeze({ + query: true, + error: true + })); + } else { + __privateSet(this, _logger, defaultLogger); + __privateSet(this, _levels, freeze({ + query: config4.includes("query"), + error: config4.includes("error") + })); + } + } + isLevelEnabled(level) { + return __privateGet(this, _levels)[level]; + } + async query(getEvent) { + if (__privateGet(this, _levels).query) { + await __privateGet(this, _logger).call(this, getEvent()); + } + } + async error(getEvent) { + if (__privateGet(this, _levels).error) { + await __privateGet(this, _logger).call(this, getEvent()); + } + } + }; + _levels = new WeakMap(); + _logger = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js +function isCompilable(value) { + return isObject4(value) && isFunction3(value.compile); +} +var init_compilable = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js"() { + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js +function isKyselyProps(obj) { + return isObject4(obj) && isObject4(obj.config) && isObject4(obj.driver) && isObject4(obj.executor) && isObject4(obj.dialect); +} +function assertNotCommittedOrRolledBack(state) { + if (state.isCommitted) { + throw new Error("Transaction is already committed"); + } + if (state.isRolledBack) { + throw new Error("Transaction is already rolled back"); + } +} +var _props39, _Kysely, Kysely, _props40, _Transaction, Transaction, _props41, ConnectionBuilder, _props42, _TransactionBuilder, TransactionBuilder, _props43, _ControlledTransactionBuilder, ControlledTransactionBuilder, _props44, _compileQuery, _state, _ControlledTransaction, ControlledTransaction, _cb, Command, _executor2, _state2, _NotCommittedOrRolledBackAssertingExecutor, NotCommittedOrRolledBackAssertingExecutor; +var init_kysely = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js"() { + init_schema(); + init_dynamic(); + init_default_connection_provider(); + init_query_creator(); + init_default_query_executor(); + init_object_utils(); + init_runtime_driver(); + init_single_connection_provider(); + init_driver(); + init_function_module(); + init_log(); + init_query_id(); + init_compilable(); + init_case_builder(); + init_case_node(); + init_expression_parser(); + init_with_schema_plugin(); + init_provide_controlled_connection(); + init_log_once(); + Symbol.asyncDispose ?? (Symbol.asyncDispose = Symbol("Symbol.asyncDispose")); + _Kysely = class _Kysely extends QueryCreator { + constructor(args) { + let superProps; + let props; + if (isKyselyProps(args)) { + superProps = { executor: args.executor }; + props = { ...args }; + } else { + const dialect = args.dialect; + const driver = dialect.createDriver(); + const compiler = dialect.createQueryCompiler(); + const adapter = dialect.createAdapter(); + const log = new Log(args.log ?? []); + const runtimeDriver = new RuntimeDriver(driver, log); + const connectionProvider = new DefaultConnectionProvider(runtimeDriver); + const executor = new DefaultQueryExecutor(compiler, adapter, connectionProvider, args.plugins ?? []); + superProps = { executor }; + props = { + config: args, + executor, + dialect, + driver: runtimeDriver + }; + } + super(superProps); + __privateAdd(this, _props39); + __privateSet(this, _props39, freeze(props)); + } + /** + * Returns the {@link SchemaModule} module for building database schema. + */ + get schema() { + return new SchemaModule(__privateGet(this, _props39).executor); + } + /** + * Returns a the {@link DynamicModule} module. + * + * The {@link DynamicModule} module can be used to bypass strict typing and + * passing in dynamic values for the queries. + */ + get dynamic() { + return new DynamicModule(); + } + /** + * Returns a {@link DatabaseIntrospector | database introspector}. + */ + get introspection() { + return __privateGet(this, _props39).dialect.createIntrospector(this.withoutPlugins()); + } + case(value) { + return new CaseBuilder({ + node: CaseNode.create(isUndefined(value) ? void 0 : parseExpression(value)) + }); + } + /** + * Returns a {@link FunctionModule} that can be used to write somewhat type-safe function + * calls. + * + * ```ts + * const { count } = db.fn + * + * await db.selectFrom('person') + * .innerJoin('pet', 'pet.owner_id', 'person.id') + * .select([ + * 'id', + * count('pet.id').as('person_count'), + * ]) + * .groupBy('person.id') + * .having(count('pet.id'), '>', 10) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "person"."id", count("pet"."id") as "person_count" + * from "person" + * inner join "pet" on "pet"."owner_id" = "person"."id" + * group by "person"."id" + * having count("pet"."id") > $1 + * ``` + * + * Why "somewhat" type-safe? Because the function calls are not bound to the + * current query context. They allow you to reference columns and tables that + * are not in the current query. E.g. remove the `innerJoin` from the previous + * query and TypeScript won't even complain. + * + * If you want to make the function calls fully type-safe, you can use the + * {@link ExpressionBuilder.fn} getter for a query context-aware, stricter {@link FunctionModule}. + * + * ```ts + * await db.selectFrom('person') + * .innerJoin('pet', 'pet.owner_id', 'person.id') + * .select((eb) => [ + * 'person.id', + * eb.fn.count('pet.id').as('pet_count') + * ]) + * .groupBy('person.id') + * .having((eb) => eb.fn.count('pet.id'), '>', 10) + * .execute() + * ``` + */ + get fn() { + return createFunctionModule(); + } + /** + * Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction. + * + * The returned {@link TransactionBuilder} can be used to configure the transaction. The + * {@link TransactionBuilder.execute} method can then be called to run the transaction. + * {@link TransactionBuilder.execute} takes a function that is run inside the + * transaction. If the function throws an exception, + * 1. the exception is caught, + * 2. the transaction is rolled back, and + * 3. the exception is thrown again. + * Otherwise the transaction is committed. + * + * The callback function passed to the {@link TransactionBuilder.execute | execute} + * method gets the transaction object as its only argument. The transaction is + * of type {@link Transaction} which inherits {@link Kysely}. Any query + * started through the transaction object is executed inside the transaction. + * + * To run a controlled transaction, allowing you to commit and rollback manually, + * use {@link startTransaction} instead. + * + * ### Examples + * + * + * + * This example inserts two rows in a transaction. If an exception is thrown inside + * the callback passed to the `execute` method, + * 1. the exception is caught, + * 2. the transaction is rolled back, and + * 3. the exception is thrown again. + * Otherwise the transaction is committed. + * + * ```ts + * const catto = await db.transaction().execute(async (trx) => { + * const jennifer = await trx.insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * + * return await trx.insertInto('pet') + * .values({ + * owner_id: jennifer.id, + * name: 'Catto', + * species: 'cat', + * is_favorite: false, + * }) + * .returningAll() + * .executeTakeFirst() + * }) + * ``` + * + * Setting the isolation level: + * + * ```ts + * import type { Kysely } from 'kysely' + * + * await db + * .transaction() + * .setIsolationLevel('serializable') + * .execute(async (trx) => { + * await doStuff(trx) + * }) + * + * async function doStuff(kysely: typeof db) { + * // ... + * } + * ``` + */ + transaction() { + return new TransactionBuilder({ ...__privateGet(this, _props39) }); + } + /** + * Creates a {@link ControlledTransactionBuilder} that can be used to run queries inside a controlled transaction. + * + * The returned {@link ControlledTransactionBuilder} can be used to configure the transaction. + * The {@link ControlledTransactionBuilder.execute} method can then be called + * to start the transaction and return a {@link ControlledTransaction}. + * + * A {@link ControlledTransaction} allows you to commit and rollback manually, + * execute savepoint commands. It extends {@link Transaction} which extends {@link Kysely}, + * so you can run queries inside the transaction. Once the transaction is committed, + * or rolled back, it can't be used anymore - all queries will throw an error. + * This is to prevent accidentally running queries outside the transaction - where + * atomicity is not guaranteed anymore. + * + * ### Examples + * + * + * + * A controlled transaction allows you to commit and rollback manually, execute + * savepoint commands, and queries in general. + * + * In this example we start a transaction, use it to insert two rows and then commit + * the transaction. If an error is thrown, we catch it and rollback the transaction. + * + * ```ts + * const trx = await db.startTransaction().execute() + * + * try { + * const jennifer = await trx.insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * + * const catto = await trx.insertInto('pet') + * .values({ + * owner_id: jennifer.id, + * name: 'Catto', + * species: 'cat', + * is_favorite: false, + * }) + * .returningAll() + * .executeTakeFirstOrThrow() + * + * await trx.commit().execute() + * + * // ... + * } catch (error) { + * await trx.rollback().execute() + * } + * ``` + * + * + * + * A controlled transaction allows you to commit and rollback manually, execute + * savepoint commands, and queries in general. + * + * In this example we start a transaction, insert a person, create a savepoint, + * try inserting a toy and a pet, and if an error is thrown, we rollback to the + * savepoint. Eventually we release the savepoint, insert an audit record and + * commit the transaction. If an error is thrown, we catch it and rollback the + * transaction. + * + * ```ts + * const trx = await db.startTransaction().execute() + * + * try { + * const jennifer = await trx + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * + * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() + * + * try { + * const catto = await trxAfterJennifer + * .insertInto('pet') + * .values({ + * owner_id: jennifer.id, + * name: 'Catto', + * species: 'cat', + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * + * await trxAfterJennifer + * .insertInto('toy') + * .values({ name: 'Bone', price: 1.99, pet_id: catto.id }) + * .execute() + * } catch (error) { + * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() + * } + * + * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() + * + * await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute() + * + * await trx.commit().execute() + * } catch (error) { + * await trx.rollback().execute() + * } + * ``` + */ + startTransaction() { + return new ControlledTransactionBuilder({ ...__privateGet(this, _props39) }); + } + /** + * Provides a kysely instance bound to a single database connection. + * + * ### Examples + * + * ```ts + * await db + * .connection() + * .execute(async (db) => { + * // `db` is an instance of `Kysely` that's bound to a single + * // database connection. All queries executed through `db` use + * // the same connection. + * await doStuff(db) + * }) + * + * async function doStuff(kysely: typeof db) { + * // ... + * } + * ``` + */ + connection() { + return new ConnectionBuilder({ ...__privateGet(this, _props39) }); + } + /** + * Returns a copy of this Kysely instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _Kysely({ + ...__privateGet(this, _props39), + executor: __privateGet(this, _props39).executor.withPlugin(plugin) + }); + } + /** + * Returns a copy of this Kysely instance without any plugins. + */ + withoutPlugins() { + return new _Kysely({ + ...__privateGet(this, _props39), + executor: __privateGet(this, _props39).executor.withoutPlugins() + }); + } + /** + * @override + */ + withSchema(schema3) { + return new _Kysely({ + ...__privateGet(this, _props39), + executor: __privateGet(this, _props39).executor.withPluginAtFront(new WithSchemaPlugin(schema3)) + }); + } + /** + * Returns a copy of this Kysely instance with tables added to its + * database type. + * + * This method only modifies the types and doesn't affect any of the + * executed queries in any way. + * + * ### Examples + * + * The following example adds and uses a temporary table: + * + * ```ts + * await db.schema + * .createTable('temp_table') + * .temporary() + * .addColumn('some_column', 'integer') + * .execute() + * + * const tempDb = db.withTables<{ + * temp_table: { + * some_column: number + * } + * }>() + * + * await tempDb + * .insertInto('temp_table') + * .values({ some_column: 100 }) + * .execute() + * ``` + */ + withTables() { + return new _Kysely({ ...__privateGet(this, _props39) }); + } + /** + * Releases all resources and disconnects from the database. + * + * You need to call this when you are done using the `Kysely` instance. + */ + async destroy() { + await __privateGet(this, _props39).driver.destroy(); + } + /** + * Returns true if this `Kysely` instance is a transaction. + * + * You can also use `db instanceof Transaction`. + */ + get isTransaction() { + return false; + } + /** + * @internal + * @private + */ + getExecutor() { + return __privateGet(this, _props39).executor; + } + /** + * Executes a given compiled query or query builder. + * + * See {@link https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0004-splitting-query-building-and-execution.md#execute-compiled-queries splitting build, compile and execute code recipe} for more information. + */ + executeQuery(query, queryId) { + if (queryId !== void 0) { + logOnce("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future."); + } + const compiledQuery = isCompilable(query) ? query.compile() : query; + return this.getExecutor().executeQuery(compiledQuery); + } + async [Symbol.asyncDispose]() { + await this.destroy(); + } + }; + _props39 = new WeakMap(); + Kysely = _Kysely; + _Transaction = class _Transaction extends Kysely { + constructor(props) { + super(props); + __privateAdd(this, _props40); + __privateSet(this, _props40, props); + } + // The return type is `true` instead of `boolean` to make Kysely + // unassignable to Transaction while allowing assignment the + // other way around. + get isTransaction() { + return true; + } + transaction() { + throw new Error("calling the transaction method for a Transaction is not supported"); + } + connection() { + throw new Error("calling the connection method for a Transaction is not supported"); + } + async destroy() { + throw new Error("calling the destroy method for a Transaction is not supported"); + } + withPlugin(plugin) { + return new _Transaction({ + ...__privateGet(this, _props40), + executor: __privateGet(this, _props40).executor.withPlugin(plugin) + }); + } + withoutPlugins() { + return new _Transaction({ + ...__privateGet(this, _props40), + executor: __privateGet(this, _props40).executor.withoutPlugins() + }); + } + withSchema(schema3) { + return new _Transaction({ + ...__privateGet(this, _props40), + executor: __privateGet(this, _props40).executor.withPluginAtFront(new WithSchemaPlugin(schema3)) + }); + } + withTables() { + return new _Transaction({ ...__privateGet(this, _props40) }); + } + }; + _props40 = new WeakMap(); + Transaction = _Transaction; + ConnectionBuilder = class { + constructor(props) { + __privateAdd(this, _props41); + __privateSet(this, _props41, freeze(props)); + } + async execute(callback) { + return __privateGet(this, _props41).executor.provideConnection(async (connection) => { + const executor = __privateGet(this, _props41).executor.withConnectionProvider(new SingleConnectionProvider(connection)); + const db = new Kysely({ + ...__privateGet(this, _props41), + executor + }); + return await callback(db); + }); + } + }; + _props41 = new WeakMap(); + _TransactionBuilder = class _TransactionBuilder { + constructor(props) { + __privateAdd(this, _props42); + __privateSet(this, _props42, freeze(props)); + } + setAccessMode(accessMode) { + return new _TransactionBuilder({ + ...__privateGet(this, _props42), + accessMode + }); + } + setIsolationLevel(isolationLevel) { + return new _TransactionBuilder({ + ...__privateGet(this, _props42), + isolationLevel + }); + } + async execute(callback) { + const { isolationLevel, accessMode, ...kyselyProps } = __privateGet(this, _props42); + const settings = { isolationLevel, accessMode }; + validateTransactionSettings(settings); + return __privateGet(this, _props42).executor.provideConnection(async (connection) => { + const state = { isCommitted: false, isRolledBack: false }; + const executor = new NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _props42).executor.withConnectionProvider(new SingleConnectionProvider(connection)), state); + const transaction = new Transaction({ + ...kyselyProps, + executor + }); + let transactionBegun = false; + try { + await __privateGet(this, _props42).driver.beginTransaction(connection, settings); + transactionBegun = true; + const result = await callback(transaction); + await __privateGet(this, _props42).driver.commitTransaction(connection); + state.isCommitted = true; + return result; + } catch (error49) { + if (transactionBegun) { + await __privateGet(this, _props42).driver.rollbackTransaction(connection); + state.isRolledBack = true; + } + throw error49; + } + }); + } + }; + _props42 = new WeakMap(); + TransactionBuilder = _TransactionBuilder; + _ControlledTransactionBuilder = class _ControlledTransactionBuilder { + constructor(props) { + __privateAdd(this, _props43); + __privateSet(this, _props43, freeze(props)); + } + setAccessMode(accessMode) { + return new _ControlledTransactionBuilder({ + ...__privateGet(this, _props43), + accessMode + }); + } + setIsolationLevel(isolationLevel) { + return new _ControlledTransactionBuilder({ + ...__privateGet(this, _props43), + isolationLevel + }); + } + async execute() { + const { isolationLevel, accessMode, ...props } = __privateGet(this, _props43); + const settings = { isolationLevel, accessMode }; + validateTransactionSettings(settings); + const connection = await provideControlledConnection(__privateGet(this, _props43).executor); + await __privateGet(this, _props43).driver.beginTransaction(connection.connection, settings); + return new ControlledTransaction({ + ...props, + connection, + executor: __privateGet(this, _props43).executor.withConnectionProvider(new SingleConnectionProvider(connection.connection)) + }); + } + }; + _props43 = new WeakMap(); + ControlledTransactionBuilder = _ControlledTransactionBuilder; + _ControlledTransaction = class _ControlledTransaction extends Transaction { + constructor(props) { + const state = { isCommitted: false, isRolledBack: false }; + props = { + ...props, + executor: new NotCommittedOrRolledBackAssertingExecutor(props.executor, state) + }; + const { connection, ...transactionProps } = props; + super(transactionProps); + __privateAdd(this, _props44); + __privateAdd(this, _compileQuery); + __privateAdd(this, _state); + __privateSet(this, _props44, freeze(props)); + __privateSet(this, _state, state); + const queryId = createQueryId(); + __privateSet(this, _compileQuery, (node) => props.executor.compileQuery(node, queryId)); + } + get isCommitted() { + return __privateGet(this, _state).isCommitted; + } + get isRolledBack() { + return __privateGet(this, _state).isRolledBack; + } + /** + * Commits the transaction. + * + * See {@link rollback}. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * try { + * await doSomething(trx) + * + * await trx.commit().execute() + * } catch (error) { + * await trx.rollback().execute() + * } + * + * async function doSomething(kysely: Kysely) {} + * ``` + */ + commit() { + assertNotCommittedOrRolledBack(__privateGet(this, _state)); + return new Command(async () => { + await __privateGet(this, _props44).driver.commitTransaction(__privateGet(this, _props44).connection.connection); + __privateGet(this, _state).isCommitted = true; + __privateGet(this, _props44).connection.release(); + }); + } + /** + * Rolls back the transaction. + * + * See {@link commit} and {@link rollbackToSavepoint}. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * try { + * await doSomething(trx) + * + * await trx.commit().execute() + * } catch (error) { + * await trx.rollback().execute() + * } + * + * async function doSomething(kysely: Kysely) {} + * ``` + */ + rollback() { + assertNotCommittedOrRolledBack(__privateGet(this, _state)); + return new Command(async () => { + await __privateGet(this, _props44).driver.rollbackTransaction(__privateGet(this, _props44).connection.connection); + __privateGet(this, _state).isRolledBack = true; + __privateGet(this, _props44).connection.release(); + }); + } + /** + * Creates a savepoint with a given name. + * + * See {@link rollbackToSavepoint} and {@link releaseSavepoint}. + * + * For a type-safe experience, you should use the returned instance from now on. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * await insertJennifer(trx) + * + * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() + * + * try { + * await doSomething(trxAfterJennifer) + * } catch (error) { + * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() + * } + * + * async function insertJennifer(kysely: Kysely) {} + * async function doSomething(kysely: Kysely) {} + * ``` + */ + savepoint(savepointName) { + assertNotCommittedOrRolledBack(__privateGet(this, _state)); + return new Command(async () => { + await __privateGet(this, _props44).driver.savepoint?.(__privateGet(this, _props44).connection.connection, savepointName, __privateGet(this, _compileQuery)); + return new _ControlledTransaction({ ...__privateGet(this, _props44) }); + }); + } + /** + * Rolls back to a savepoint with a given name. + * + * See {@link savepoint} and {@link releaseSavepoint}. + * + * You must use the same instance returned by {@link savepoint}, or + * escape the type-check by using `as any`. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * await insertJennifer(trx) + * + * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() + * + * try { + * await doSomething(trxAfterJennifer) + * } catch (error) { + * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() + * } + * + * async function insertJennifer(kysely: Kysely) {} + * async function doSomething(kysely: Kysely) {} + * ``` + */ + rollbackToSavepoint(savepointName) { + assertNotCommittedOrRolledBack(__privateGet(this, _state)); + return new Command(async () => { + await __privateGet(this, _props44).driver.rollbackToSavepoint?.(__privateGet(this, _props44).connection.connection, savepointName, __privateGet(this, _compileQuery)); + return new _ControlledTransaction({ ...__privateGet(this, _props44) }); + }); + } + /** + * Releases a savepoint with a given name. + * + * See {@link savepoint} and {@link rollbackToSavepoint}. + * + * You must use the same instance returned by {@link savepoint}, or + * escape the type-check by using `as any`. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * await insertJennifer(trx) + * + * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() + * + * try { + * await doSomething(trxAfterJennifer) + * } catch (error) { + * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() + * } + * + * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() + * + * await doSomethingElse(trx) + * + * async function insertJennifer(kysely: Kysely) {} + * async function doSomething(kysely: Kysely) {} + * async function doSomethingElse(kysely: Kysely) {} + * ``` + */ + releaseSavepoint(savepointName) { + assertNotCommittedOrRolledBack(__privateGet(this, _state)); + return new Command(async () => { + await __privateGet(this, _props44).driver.releaseSavepoint?.(__privateGet(this, _props44).connection.connection, savepointName, __privateGet(this, _compileQuery)); + return new _ControlledTransaction({ ...__privateGet(this, _props44) }); + }); + } + withPlugin(plugin) { + return new _ControlledTransaction({ + ...__privateGet(this, _props44), + executor: __privateGet(this, _props44).executor.withPlugin(plugin) + }); + } + withoutPlugins() { + return new _ControlledTransaction({ + ...__privateGet(this, _props44), + executor: __privateGet(this, _props44).executor.withoutPlugins() + }); + } + withSchema(schema3) { + return new _ControlledTransaction({ + ...__privateGet(this, _props44), + executor: __privateGet(this, _props44).executor.withPluginAtFront(new WithSchemaPlugin(schema3)) + }); + } + withTables() { + return new _ControlledTransaction({ ...__privateGet(this, _props44) }); + } + }; + _props44 = new WeakMap(); + _compileQuery = new WeakMap(); + _state = new WeakMap(); + ControlledTransaction = _ControlledTransaction; + Command = class { + constructor(cb) { + __privateAdd(this, _cb); + __privateSet(this, _cb, cb); + } + /** + * Executes the command. + */ + async execute() { + return await __privateGet(this, _cb).call(this); + } + }; + _cb = new WeakMap(); + _NotCommittedOrRolledBackAssertingExecutor = class _NotCommittedOrRolledBackAssertingExecutor { + constructor(executor, state) { + __privateAdd(this, _executor2); + __privateAdd(this, _state2); + if (executor instanceof _NotCommittedOrRolledBackAssertingExecutor) { + __privateSet(this, _executor2, __privateGet(executor, _executor2)); + } else { + __privateSet(this, _executor2, executor); + } + __privateSet(this, _state2, state); + } + get adapter() { + return __privateGet(this, _executor2).adapter; + } + get plugins() { + return __privateGet(this, _executor2).plugins; + } + transformQuery(node, queryId) { + return __privateGet(this, _executor2).transformQuery(node, queryId); + } + compileQuery(node, queryId) { + return __privateGet(this, _executor2).compileQuery(node, queryId); + } + provideConnection(consumer) { + return __privateGet(this, _executor2).provideConnection(consumer); + } + executeQuery(compiledQuery) { + assertNotCommittedOrRolledBack(__privateGet(this, _state2)); + return __privateGet(this, _executor2).executeQuery(compiledQuery); + } + stream(compiledQuery, chunkSize) { + assertNotCommittedOrRolledBack(__privateGet(this, _state2)); + return __privateGet(this, _executor2).stream(compiledQuery, chunkSize); + } + withConnectionProvider(connectionProvider) { + return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withConnectionProvider(connectionProvider), __privateGet(this, _state2)); + } + withPlugin(plugin) { + return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withPlugin(plugin), __privateGet(this, _state2)); + } + withPlugins(plugins) { + return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withPlugins(plugins), __privateGet(this, _state2)); + } + withPluginAtFront(plugin) { + return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withPluginAtFront(plugin), __privateGet(this, _state2)); + } + withoutPlugins() { + return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withoutPlugins(), __privateGet(this, _state2)); + } + }; + _executor2 = new WeakMap(); + _state2 = new WeakMap(); + NotCommittedOrRolledBackAssertingExecutor = _NotCommittedOrRolledBackAssertingExecutor; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js +var init_where_interface = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js +var init_returning_interface = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js +var init_output_interface = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js +var init_having_interface = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js +var init_order_by_interface = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js +function createRawBuilder(props) { + return new RawBuilderImpl(props); +} +var _props45, _RawBuilderImpl_instances, getExecutor_fn, toOperationNode_fn, compile_fn, _RawBuilderImpl, RawBuilderImpl, _rawBuilder, _alias6, AliasedRawBuilderImpl; +var init_raw_builder = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js"() { + init_alias_node(); + init_object_utils(); + init_noop_query_executor(); + init_identifier_node(); + init_operation_node_source(); + _RawBuilderImpl = class _RawBuilderImpl { + constructor(props) { + __privateAdd(this, _RawBuilderImpl_instances); + __privateAdd(this, _props45); + __privateSet(this, _props45, freeze(props)); + } + get expressionType() { + return void 0; + } + get isRawBuilder() { + return true; + } + as(alias) { + return new AliasedRawBuilderImpl(this, alias); + } + $castTo() { + return new _RawBuilderImpl({ ...__privateGet(this, _props45) }); + } + $notNull() { + return new _RawBuilderImpl(__privateGet(this, _props45)); + } + withPlugin(plugin) { + return new _RawBuilderImpl({ + ...__privateGet(this, _props45), + plugins: __privateGet(this, _props45).plugins !== void 0 ? freeze([...__privateGet(this, _props45).plugins, plugin]) : freeze([plugin]) + }); + } + toOperationNode() { + return __privateMethod(this, _RawBuilderImpl_instances, toOperationNode_fn).call(this, __privateMethod(this, _RawBuilderImpl_instances, getExecutor_fn).call(this)); + } + compile(executorProvider) { + return __privateMethod(this, _RawBuilderImpl_instances, compile_fn).call(this, __privateMethod(this, _RawBuilderImpl_instances, getExecutor_fn).call(this, executorProvider)); + } + async execute(executorProvider) { + const executor = __privateMethod(this, _RawBuilderImpl_instances, getExecutor_fn).call(this, executorProvider); + return executor.executeQuery(__privateMethod(this, _RawBuilderImpl_instances, compile_fn).call(this, executor)); + } + }; + _props45 = new WeakMap(); + _RawBuilderImpl_instances = new WeakSet(); + getExecutor_fn = function(executorProvider) { + const executor = executorProvider !== void 0 ? executorProvider.getExecutor() : NOOP_QUERY_EXECUTOR; + return __privateGet(this, _props45).plugins !== void 0 ? executor.withPlugins(__privateGet(this, _props45).plugins) : executor; + }; + toOperationNode_fn = function(executor) { + return executor.transformQuery(__privateGet(this, _props45).rawNode, __privateGet(this, _props45).queryId); + }; + compile_fn = function(executor) { + return executor.compileQuery(__privateMethod(this, _RawBuilderImpl_instances, toOperationNode_fn).call(this, executor), __privateGet(this, _props45).queryId); + }; + RawBuilderImpl = _RawBuilderImpl; + AliasedRawBuilderImpl = class { + constructor(rawBuilder, alias) { + __privateAdd(this, _rawBuilder); + __privateAdd(this, _alias6); + __privateSet(this, _rawBuilder, rawBuilder); + __privateSet(this, _alias6, alias); + } + get expression() { + return __privateGet(this, _rawBuilder); + } + get alias() { + return __privateGet(this, _alias6); + } + get rawBuilder() { + return __privateGet(this, _rawBuilder); + } + toOperationNode() { + return AliasNode.create(__privateGet(this, _rawBuilder).toOperationNode(), isOperationNodeSource(__privateGet(this, _alias6)) ? __privateGet(this, _alias6).toOperationNode() : IdentifierNode.create(__privateGet(this, _alias6))); + } + }; + _rawBuilder = new WeakMap(); + _alias6 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js +function parseParameter(param) { + if (isOperationNodeSource(param)) { + return param.toOperationNode(); + } + return parseValueExpression(param); +} +var sql; +var init_sql = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js"() { + init_identifier_node(); + init_operation_node_source(); + init_raw_node(); + init_value_node(); + init_reference_parser(); + init_table_parser(); + init_value_parser(); + init_query_id(); + init_raw_builder(); + sql = Object.assign((sqlFragments, ...parameters) => { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []) + }); + }, { + ref(columnReference) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChild(parseStringReference(columnReference)) + }); + }, + val(value) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChild(parseValueExpression(value)) + }); + }, + value(value) { + return this.val(value); + }, + table(tableReference) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChild(parseTable(tableReference)) + }); + }, + id(...ids) { + const fragments = new Array(ids.length + 1).fill("."); + fragments[0] = ""; + fragments[fragments.length - 1] = ""; + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)) + }); + }, + lit(value) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)) + }); + }, + literal(value) { + return this.lit(value); + }, + raw(sql2) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithSql(sql2) + }); + }, + join(array2, separator = sql`, `) { + const nodes = new Array(Math.max(2 * array2.length - 1, 0)); + const sep = separator.toOperationNode(); + for (let i = 0; i < array2.length; ++i) { + nodes[2 * i] = parseParameter(array2[i]); + if (i !== array2.length - 1) { + nodes[2 * i + 1] = sep; + } + } + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChildren(nodes) + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js +var init_query_executor = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js +var init_query_executor_provider = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js +var _visitors, OperationNodeVisitor; +var init_operation_node_visitor = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js"() { + init_object_utils(); + OperationNodeVisitor = class { + constructor() { + __publicField(this, "nodeStack", []); + __privateAdd(this, _visitors, freeze({ + AliasNode: this.visitAlias.bind(this), + ColumnNode: this.visitColumn.bind(this), + IdentifierNode: this.visitIdentifier.bind(this), + SchemableIdentifierNode: this.visitSchemableIdentifier.bind(this), + RawNode: this.visitRaw.bind(this), + ReferenceNode: this.visitReference.bind(this), + SelectQueryNode: this.visitSelectQuery.bind(this), + SelectionNode: this.visitSelection.bind(this), + TableNode: this.visitTable.bind(this), + FromNode: this.visitFrom.bind(this), + SelectAllNode: this.visitSelectAll.bind(this), + AndNode: this.visitAnd.bind(this), + OrNode: this.visitOr.bind(this), + ValueNode: this.visitValue.bind(this), + ValueListNode: this.visitValueList.bind(this), + PrimitiveValueListNode: this.visitPrimitiveValueList.bind(this), + ParensNode: this.visitParens.bind(this), + JoinNode: this.visitJoin.bind(this), + OperatorNode: this.visitOperator.bind(this), + WhereNode: this.visitWhere.bind(this), + InsertQueryNode: this.visitInsertQuery.bind(this), + DeleteQueryNode: this.visitDeleteQuery.bind(this), + ReturningNode: this.visitReturning.bind(this), + CreateTableNode: this.visitCreateTable.bind(this), + AddColumnNode: this.visitAddColumn.bind(this), + ColumnDefinitionNode: this.visitColumnDefinition.bind(this), + DropTableNode: this.visitDropTable.bind(this), + DataTypeNode: this.visitDataType.bind(this), + OrderByNode: this.visitOrderBy.bind(this), + OrderByItemNode: this.visitOrderByItem.bind(this), + GroupByNode: this.visitGroupBy.bind(this), + GroupByItemNode: this.visitGroupByItem.bind(this), + UpdateQueryNode: this.visitUpdateQuery.bind(this), + ColumnUpdateNode: this.visitColumnUpdate.bind(this), + LimitNode: this.visitLimit.bind(this), + OffsetNode: this.visitOffset.bind(this), + OnConflictNode: this.visitOnConflict.bind(this), + OnDuplicateKeyNode: this.visitOnDuplicateKey.bind(this), + CreateIndexNode: this.visitCreateIndex.bind(this), + DropIndexNode: this.visitDropIndex.bind(this), + ListNode: this.visitList.bind(this), + PrimaryKeyConstraintNode: this.visitPrimaryKeyConstraint.bind(this), + UniqueConstraintNode: this.visitUniqueConstraint.bind(this), + ReferencesNode: this.visitReferences.bind(this), + CheckConstraintNode: this.visitCheckConstraint.bind(this), + WithNode: this.visitWith.bind(this), + CommonTableExpressionNode: this.visitCommonTableExpression.bind(this), + CommonTableExpressionNameNode: this.visitCommonTableExpressionName.bind(this), + HavingNode: this.visitHaving.bind(this), + CreateSchemaNode: this.visitCreateSchema.bind(this), + DropSchemaNode: this.visitDropSchema.bind(this), + AlterTableNode: this.visitAlterTable.bind(this), + DropColumnNode: this.visitDropColumn.bind(this), + RenameColumnNode: this.visitRenameColumn.bind(this), + AlterColumnNode: this.visitAlterColumn.bind(this), + ModifyColumnNode: this.visitModifyColumn.bind(this), + AddConstraintNode: this.visitAddConstraint.bind(this), + DropConstraintNode: this.visitDropConstraint.bind(this), + RenameConstraintNode: this.visitRenameConstraint.bind(this), + ForeignKeyConstraintNode: this.visitForeignKeyConstraint.bind(this), + CreateViewNode: this.visitCreateView.bind(this), + RefreshMaterializedViewNode: this.visitRefreshMaterializedView.bind(this), + DropViewNode: this.visitDropView.bind(this), + GeneratedNode: this.visitGenerated.bind(this), + DefaultValueNode: this.visitDefaultValue.bind(this), + OnNode: this.visitOn.bind(this), + ValuesNode: this.visitValues.bind(this), + SelectModifierNode: this.visitSelectModifier.bind(this), + CreateTypeNode: this.visitCreateType.bind(this), + DropTypeNode: this.visitDropType.bind(this), + ExplainNode: this.visitExplain.bind(this), + DefaultInsertValueNode: this.visitDefaultInsertValue.bind(this), + AggregateFunctionNode: this.visitAggregateFunction.bind(this), + OverNode: this.visitOver.bind(this), + PartitionByNode: this.visitPartitionBy.bind(this), + PartitionByItemNode: this.visitPartitionByItem.bind(this), + SetOperationNode: this.visitSetOperation.bind(this), + BinaryOperationNode: this.visitBinaryOperation.bind(this), + UnaryOperationNode: this.visitUnaryOperation.bind(this), + UsingNode: this.visitUsing.bind(this), + FunctionNode: this.visitFunction.bind(this), + CaseNode: this.visitCase.bind(this), + WhenNode: this.visitWhen.bind(this), + JSONReferenceNode: this.visitJSONReference.bind(this), + JSONPathNode: this.visitJSONPath.bind(this), + JSONPathLegNode: this.visitJSONPathLeg.bind(this), + JSONOperatorChainNode: this.visitJSONOperatorChain.bind(this), + TupleNode: this.visitTuple.bind(this), + MergeQueryNode: this.visitMergeQuery.bind(this), + MatchedNode: this.visitMatched.bind(this), + AddIndexNode: this.visitAddIndex.bind(this), + CastNode: this.visitCast.bind(this), + FetchNode: this.visitFetch.bind(this), + TopNode: this.visitTop.bind(this), + OutputNode: this.visitOutput.bind(this), + OrActionNode: this.visitOrAction.bind(this), + CollateNode: this.visitCollate.bind(this) + })); + __publicField(this, "visitNode", (node) => { + this.nodeStack.push(node); + __privateGet(this, _visitors)[node.kind](node); + this.nodeStack.pop(); + }); + } + get parentNode() { + return this.nodeStack[this.nodeStack.length - 2]; + } + }; + _visitors = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js +var LIT_WRAP_REGEX, _sql, _parameters, DefaultQueryCompiler, SELECT_MODIFIER_SQL, SELECT_MODIFIER_PRIORITY, JOIN_TYPE_SQL; +var init_default_query_compiler = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js"() { + init_create_table_node(); + init_insert_query_node(); + init_operation_node_visitor(); + init_operator_node(); + init_parens_node(); + init_raw_node(); + init_object_utils(); + init_create_view_node(); + init_set_operation_node(); + init_when_node(); + init_log_once(); + LIT_WRAP_REGEX = /'/g; + DefaultQueryCompiler = class extends OperationNodeVisitor { + constructor() { + super(...arguments); + __privateAdd(this, _sql, ""); + __privateAdd(this, _parameters, []); + } + get numParameters() { + return __privateGet(this, _parameters).length; + } + compileQuery(node, queryId) { + __privateSet(this, _sql, ""); + __privateSet(this, _parameters, []); + this.nodeStack.splice(0, this.nodeStack.length); + this.visitNode(node); + return freeze({ + query: node, + queryId, + sql: this.getSql(), + parameters: [...__privateGet(this, _parameters)] + }); + } + getSql() { + return __privateGet(this, _sql); + } + visitSelectQuery(node) { + const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !InsertQueryNode.is(this.parentNode) && !CreateTableNode.is(this.parentNode) && !CreateViewNode.is(this.parentNode) && !SetOperationNode.is(this.parentNode); + if (this.parentNode === void 0 && node.explain) { + this.visitNode(node.explain); + this.append(" "); + } + if (wrapInParens) { + this.append("("); + } + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append("select"); + if (node.distinctOn) { + this.append(" "); + this.compileDistinctOn(node.distinctOn); + } + if (node.frontModifiers?.length) { + this.append(" "); + this.compileList(node.frontModifiers, " "); + } + if (node.top) { + this.append(" "); + this.visitNode(node.top); + } + if (node.selections) { + this.append(" "); + this.compileList(node.selections); + } + if (node.from) { + this.append(" "); + this.visitNode(node.from); + } + if (node.joins) { + this.append(" "); + this.compileList(node.joins, " "); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + if (node.groupBy) { + this.append(" "); + this.visitNode(node.groupBy); + } + if (node.having) { + this.append(" "); + this.visitNode(node.having); + } + if (node.setOperations) { + this.append(" "); + this.compileList(node.setOperations, " "); + } + if (node.orderBy) { + this.append(" "); + this.visitNode(node.orderBy); + } + if (node.limit) { + this.append(" "); + this.visitNode(node.limit); + } + if (node.offset) { + this.append(" "); + this.visitNode(node.offset); + } + if (node.fetch) { + this.append(" "); + this.visitNode(node.fetch); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(this.sortSelectModifiers([...node.endModifiers]), " "); + } + if (wrapInParens) { + this.append(")"); + } + } + visitFrom(node) { + this.append("from "); + this.compileList(node.froms); + } + visitSelection(node) { + this.visitNode(node.selection); + } + visitColumn(node) { + this.visitNode(node.column); + } + compileDistinctOn(expressions) { + this.append("distinct on ("); + this.compileList(expressions); + this.append(")"); + } + compileList(nodes, separator = ", ") { + const lastIndex = nodes.length - 1; + for (let i = 0; i <= lastIndex; i++) { + this.visitNode(nodes[i]); + if (i < lastIndex) { + this.append(separator); + } + } + } + visitWhere(node) { + this.append("where "); + this.visitNode(node.where); + } + visitHaving(node) { + this.append("having "); + this.visitNode(node.having); + } + visitInsertQuery(node) { + const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode); + if (this.parentNode === void 0 && node.explain) { + this.visitNode(node.explain); + this.append(" "); + } + if (wrapInParens) { + this.append("("); + } + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append(node.replace ? "replace" : "insert"); + if (node.ignore) { + logOnce("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."); + this.append(" ignore"); + } + if (node.orAction) { + this.append(" "); + this.visitNode(node.orAction); + } + if (node.top) { + this.append(" "); + this.visitNode(node.top); + } + if (node.into) { + this.append(" into "); + this.visitNode(node.into); + } + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } + if (node.output) { + this.append(" "); + this.visitNode(node.output); + } + if (node.values) { + this.append(" "); + this.visitNode(node.values); + } + if (node.defaultValues) { + this.append(" "); + this.append("default values"); + } + if (node.onConflict) { + this.append(" "); + this.visitNode(node.onConflict); + } + if (node.onDuplicateKey) { + this.append(" "); + this.visitNode(node.onDuplicateKey); + } + if (node.returning) { + this.append(" "); + this.visitNode(node.returning); + } + if (wrapInParens) { + this.append(")"); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + visitValues(node) { + this.append("values "); + this.compileList(node.values); + } + visitDeleteQuery(node) { + const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode); + if (this.parentNode === void 0 && node.explain) { + this.visitNode(node.explain); + this.append(" "); + } + if (wrapInParens) { + this.append("("); + } + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append("delete "); + if (node.top) { + this.visitNode(node.top); + this.append(" "); + } + this.visitNode(node.from); + if (node.output) { + this.append(" "); + this.visitNode(node.output); + } + if (node.using) { + this.append(" "); + this.visitNode(node.using); + } + if (node.joins) { + this.append(" "); + this.compileList(node.joins, " "); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + if (node.orderBy) { + this.append(" "); + this.visitNode(node.orderBy); + } + if (node.limit) { + this.append(" "); + this.visitNode(node.limit); + } + if (node.returning) { + this.append(" "); + this.visitNode(node.returning); + } + if (wrapInParens) { + this.append(")"); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + visitReturning(node) { + this.append("returning "); + this.compileList(node.selections); + } + visitAlias(node) { + this.visitNode(node.node); + this.append(" as "); + this.visitNode(node.alias); + } + visitReference(node) { + if (node.table) { + this.visitNode(node.table); + this.append("."); + } + this.visitNode(node.column); + } + visitSelectAll(_) { + this.append("*"); + } + visitIdentifier(node) { + this.append(this.getLeftIdentifierWrapper()); + this.compileUnwrappedIdentifier(node); + this.append(this.getRightIdentifierWrapper()); + } + compileUnwrappedIdentifier(node) { + if (!isString2(node.name)) { + throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier."); + } + this.append(this.sanitizeIdentifier(node.name)); + } + visitAnd(node) { + this.visitNode(node.left); + this.append(" and "); + this.visitNode(node.right); + } + visitOr(node) { + this.visitNode(node.left); + this.append(" or "); + this.visitNode(node.right); + } + visitValue(node) { + if (node.immediate) { + this.appendImmediateValue(node.value); + } else { + this.appendValue(node.value); + } + } + visitValueList(node) { + this.append("("); + this.compileList(node.values); + this.append(")"); + } + visitTuple(node) { + this.append("("); + this.compileList(node.values); + this.append(")"); + } + visitPrimitiveValueList(node) { + this.append("("); + const { values } = node; + for (let i = 0; i < values.length; ++i) { + this.appendValue(values[i]); + if (i !== values.length - 1) { + this.append(", "); + } + } + this.append(")"); + } + visitParens(node) { + this.append("("); + this.visitNode(node.node); + this.append(")"); + } + visitJoin(node) { + this.append(JOIN_TYPE_SQL[node.joinType]); + this.append(" "); + this.visitNode(node.table); + if (node.on) { + this.append(" "); + this.visitNode(node.on); + } + } + visitOn(node) { + this.append("on "); + this.visitNode(node.on); + } + visitRaw(node) { + const { sqlFragments, parameters: params } = node; + for (let i = 0; i < sqlFragments.length; ++i) { + this.append(sqlFragments[i]); + if (params.length > i) { + this.visitNode(params[i]); + } + } + } + visitOperator(node) { + this.append(node.operator); + } + visitTable(node) { + this.visitNode(node.table); + } + visitSchemableIdentifier(node) { + if (node.schema) { + this.visitNode(node.schema); + this.append("."); + } + this.visitNode(node.identifier); + } + visitCreateTable(node) { + this.append("create "); + if (node.frontModifiers?.length) { + this.compileList(node.frontModifiers, " "); + this.append(" "); + } + if (node.temporary) { + this.append("temporary "); + } + this.append("table "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.table); + if (!node.selectQuery) { + this.append(" ("); + this.compileList([...node.columns, ...node.constraints ?? []]); + this.append(")"); + } + if (node.onCommit) { + this.append(" on commit "); + this.append(node.onCommit); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + if (node.selectQuery) { + this.append(" as "); + this.visitNode(node.selectQuery); + } + } + visitColumnDefinition(node) { + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.column); + this.append(" "); + this.visitNode(node.dataType); + if (node.unsigned) { + this.append(" unsigned"); + } + if (node.frontModifiers && node.frontModifiers.length > 0) { + this.append(" "); + this.compileList(node.frontModifiers, " "); + } + if (node.generated) { + this.append(" "); + this.visitNode(node.generated); + } + if (node.identity) { + this.append(" identity"); + } + if (node.defaultTo) { + this.append(" "); + this.visitNode(node.defaultTo); + } + if (node.notNull) { + this.append(" not null"); + } + if (node.unique) { + this.append(" unique"); + } + if (node.nullsNotDistinct) { + this.append(" nulls not distinct"); + } + if (node.primaryKey) { + this.append(" primary key"); + } + if (node.autoIncrement) { + this.append(" "); + this.append(this.getAutoIncrement()); + } + if (node.references) { + this.append(" "); + this.visitNode(node.references); + } + if (node.check) { + this.append(" "); + this.visitNode(node.check); + } + if (node.endModifiers && node.endModifiers.length > 0) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + getAutoIncrement() { + return "auto_increment"; + } + visitReferences(node) { + this.append("references "); + this.visitNode(node.table); + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + if (node.onDelete) { + this.append(" on delete "); + this.append(node.onDelete); + } + if (node.onUpdate) { + this.append(" on update "); + this.append(node.onUpdate); + } + } + visitDropTable(node) { + this.append("drop table "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.table); + if (node.cascade) { + this.append(" cascade"); + } + } + visitDataType(node) { + this.append(node.dataType); + } + visitOrderBy(node) { + this.append("order by "); + this.compileList(node.items); + } + visitOrderByItem(node) { + this.visitNode(node.orderBy); + if (node.collation) { + this.append(" "); + this.visitNode(node.collation); + } + if (node.direction) { + this.append(" "); + this.visitNode(node.direction); + } + if (node.nulls) { + this.append(" nulls "); + this.append(node.nulls); + } + } + visitGroupBy(node) { + this.append("group by "); + this.compileList(node.items); + } + visitGroupByItem(node) { + this.visitNode(node.groupBy); + } + visitUpdateQuery(node) { + const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode); + if (this.parentNode === void 0 && node.explain) { + this.visitNode(node.explain); + this.append(" "); + } + if (wrapInParens) { + this.append("("); + } + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append("update "); + if (node.top) { + this.visitNode(node.top); + this.append(" "); + } + if (node.table) { + this.visitNode(node.table); + this.append(" "); + } + this.append("set "); + if (node.updates) { + this.compileList(node.updates); + } + if (node.output) { + this.append(" "); + this.visitNode(node.output); + } + if (node.from) { + this.append(" "); + this.visitNode(node.from); + } + if (node.joins) { + if (!node.from) { + throw new Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins"); + } + this.append(" "); + this.compileList(node.joins, " "); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + if (node.returning) { + this.append(" "); + this.visitNode(node.returning); + } + if (node.orderBy) { + this.append(" "); + this.visitNode(node.orderBy); + } + if (node.limit) { + this.append(" "); + this.visitNode(node.limit); + } + if (wrapInParens) { + this.append(")"); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + visitColumnUpdate(node) { + this.visitNode(node.column); + this.append(" = "); + this.visitNode(node.value); + } + visitLimit(node) { + this.append("limit "); + this.visitNode(node.limit); + } + visitOffset(node) { + this.append("offset "); + this.visitNode(node.offset); + } + visitOnConflict(node) { + this.append("on conflict"); + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } else if (node.constraint) { + this.append(" on constraint "); + this.visitNode(node.constraint); + } else if (node.indexExpression) { + this.append(" ("); + this.visitNode(node.indexExpression); + this.append(")"); + } + if (node.indexWhere) { + this.append(" "); + this.visitNode(node.indexWhere); + } + if (node.doNothing === true) { + this.append(" do nothing"); + } else if (node.updates) { + this.append(" do update set "); + this.compileList(node.updates); + if (node.updateWhere) { + this.append(" "); + this.visitNode(node.updateWhere); + } + } + } + visitOnDuplicateKey(node) { + this.append("on duplicate key update "); + this.compileList(node.updates); + } + visitCreateIndex(node) { + this.append("create "); + if (node.unique) { + this.append("unique "); + } + this.append("index "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.name); + if (node.table) { + this.append(" on "); + this.visitNode(node.table); + } + if (node.using) { + this.append(" using "); + this.visitNode(node.using); + } + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } + if (node.nullsNotDistinct) { + this.append(" nulls not distinct"); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + } + visitDropIndex(node) { + this.append("drop index "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.name); + if (node.table) { + this.append(" on "); + this.visitNode(node.table); + } + if (node.cascade) { + this.append(" cascade"); + } + } + visitCreateSchema(node) { + this.append("create schema "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.schema); + } + visitDropSchema(node) { + this.append("drop schema "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.schema); + if (node.cascade) { + this.append(" cascade"); + } + } + visitPrimaryKeyConstraint(node) { + if (node.name) { + this.append("constraint "); + this.visitNode(node.name); + this.append(" "); + } + this.append("primary key ("); + this.compileList(node.columns); + this.append(")"); + this.buildDeferrable(node); + } + buildDeferrable(node) { + if (node.deferrable !== void 0) { + if (node.deferrable) { + this.append(" deferrable"); + } else { + this.append(" not deferrable"); + } + } + if (node.initiallyDeferred !== void 0) { + if (node.initiallyDeferred) { + this.append(" initially deferred"); + } else { + this.append(" initially immediate"); + } + } + } + visitUniqueConstraint(node) { + if (node.name) { + this.append("constraint "); + this.visitNode(node.name); + this.append(" "); + } + this.append("unique"); + if (node.nullsNotDistinct) { + this.append(" nulls not distinct"); + } + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + this.buildDeferrable(node); + } + visitCheckConstraint(node) { + if (node.name) { + this.append("constraint "); + this.visitNode(node.name); + this.append(" "); + } + this.append("check ("); + this.visitNode(node.expression); + this.append(")"); + } + visitForeignKeyConstraint(node) { + if (node.name) { + this.append("constraint "); + this.visitNode(node.name); + this.append(" "); + } + this.append("foreign key ("); + this.compileList(node.columns); + this.append(") "); + this.visitNode(node.references); + if (node.onDelete) { + this.append(" on delete "); + this.append(node.onDelete); + } + if (node.onUpdate) { + this.append(" on update "); + this.append(node.onUpdate); + } + this.buildDeferrable(node); + } + visitList(node) { + this.compileList(node.items); + } + visitWith(node) { + this.append("with "); + if (node.recursive) { + this.append("recursive "); + } + this.compileList(node.expressions); + } + visitCommonTableExpression(node) { + this.visitNode(node.name); + this.append(" as "); + if (isBoolean2(node.materialized)) { + if (!node.materialized) { + this.append("not "); + } + this.append("materialized "); + } + this.visitNode(node.expression); + } + visitCommonTableExpressionName(node) { + this.visitNode(node.table); + if (node.columns) { + this.append("("); + this.compileList(node.columns); + this.append(")"); + } + } + visitAlterTable(node) { + this.append("alter table "); + this.visitNode(node.table); + this.append(" "); + if (node.renameTo) { + this.append("rename to "); + this.visitNode(node.renameTo); + } + if (node.setSchema) { + this.append("set schema "); + this.visitNode(node.setSchema); + } + if (node.addConstraint) { + this.visitNode(node.addConstraint); + } + if (node.dropConstraint) { + this.visitNode(node.dropConstraint); + } + if (node.renameConstraint) { + this.visitNode(node.renameConstraint); + } + if (node.columnAlterations) { + this.compileColumnAlterations(node.columnAlterations); + } + if (node.addIndex) { + this.visitNode(node.addIndex); + } + if (node.dropIndex) { + this.visitNode(node.dropIndex); + } + } + visitAddColumn(node) { + this.append("add column "); + this.visitNode(node.column); + } + visitRenameColumn(node) { + this.append("rename column "); + this.visitNode(node.column); + this.append(" to "); + this.visitNode(node.renameTo); + } + visitDropColumn(node) { + this.append("drop column "); + this.visitNode(node.column); + } + visitAlterColumn(node) { + this.append("alter column "); + this.visitNode(node.column); + this.append(" "); + if (node.dataType) { + if (this.announcesNewColumnDataType()) { + this.append("type "); + } + this.visitNode(node.dataType); + if (node.dataTypeExpression) { + this.append("using "); + this.visitNode(node.dataTypeExpression); + } + } + if (node.setDefault) { + this.append("set default "); + this.visitNode(node.setDefault); + } + if (node.dropDefault) { + this.append("drop default"); + } + if (node.setNotNull) { + this.append("set not null"); + } + if (node.dropNotNull) { + this.append("drop not null"); + } + } + visitModifyColumn(node) { + this.append("modify column "); + this.visitNode(node.column); + } + visitAddConstraint(node) { + this.append("add "); + this.visitNode(node.constraint); + } + visitDropConstraint(node) { + this.append("drop constraint "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.constraintName); + if (node.modifier === "cascade") { + this.append(" cascade"); + } else if (node.modifier === "restrict") { + this.append(" restrict"); + } + } + visitRenameConstraint(node) { + this.append("rename constraint "); + this.visitNode(node.oldName); + this.append(" to "); + this.visitNode(node.newName); + } + visitSetOperation(node) { + this.append(node.operator); + this.append(" "); + if (node.all) { + this.append("all "); + } + this.visitNode(node.expression); + } + visitCreateView(node) { + this.append("create "); + if (node.orReplace) { + this.append("or replace "); + } + if (node.materialized) { + this.append("materialized "); + } + if (node.temporary) { + this.append("temporary "); + } + this.append("view "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.name); + this.append(" "); + if (node.columns) { + this.append("("); + this.compileList(node.columns); + this.append(") "); + } + if (node.as) { + this.append("as "); + this.visitNode(node.as); + } + } + visitRefreshMaterializedView(node) { + this.append("refresh materialized view "); + if (node.concurrently) { + this.append("concurrently "); + } + this.visitNode(node.name); + if (node.withNoData) { + this.append(" with no data"); + } else { + this.append(" with data"); + } + } + visitDropView(node) { + this.append("drop "); + if (node.materialized) { + this.append("materialized "); + } + this.append("view "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.name); + if (node.cascade) { + this.append(" cascade"); + } + } + visitGenerated(node) { + this.append("generated "); + if (node.always) { + this.append("always "); + } + if (node.byDefault) { + this.append("by default "); + } + this.append("as "); + if (node.identity) { + this.append("identity"); + } + if (node.expression) { + this.append("("); + this.visitNode(node.expression); + this.append(")"); + } + if (node.stored) { + this.append(" stored"); + } + } + visitDefaultValue(node) { + this.append("default "); + this.visitNode(node.defaultValue); + } + visitSelectModifier(node) { + if (node.rawModifier) { + this.visitNode(node.rawModifier); + } else { + this.append(SELECT_MODIFIER_SQL[node.modifier]); + } + if (node.of) { + this.append(" of "); + this.compileList(node.of, ", "); + } + } + visitCreateType(node) { + this.append("create type "); + this.visitNode(node.name); + if (node.enum) { + this.append(" as enum "); + this.visitNode(node.enum); + } + } + visitDropType(node) { + this.append("drop type "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.name); + } + visitExplain(node) { + this.append("explain"); + if (node.options || node.format) { + this.append(" "); + this.append(this.getLeftExplainOptionsWrapper()); + if (node.options) { + this.visitNode(node.options); + if (node.format) { + this.append(this.getExplainOptionsDelimiter()); + } + } + if (node.format) { + this.append("format"); + this.append(this.getExplainOptionAssignment()); + this.append(node.format); + } + this.append(this.getRightExplainOptionsWrapper()); + } + } + visitDefaultInsertValue(_) { + this.append("default"); + } + visitAggregateFunction(node) { + this.append(node.func); + this.append("("); + if (node.distinct) { + this.append("distinct "); + } + this.compileList(node.aggregated); + if (node.orderBy) { + this.append(" "); + this.visitNode(node.orderBy); + } + this.append(")"); + if (node.withinGroup) { + this.append(" within group ("); + this.visitNode(node.withinGroup); + this.append(")"); + } + if (node.filter) { + this.append(" filter("); + this.visitNode(node.filter); + this.append(")"); + } + if (node.over) { + this.append(" "); + this.visitNode(node.over); + } + } + visitOver(node) { + this.append("over("); + if (node.partitionBy) { + this.visitNode(node.partitionBy); + if (node.orderBy) { + this.append(" "); + } + } + if (node.orderBy) { + this.visitNode(node.orderBy); + } + this.append(")"); + } + visitPartitionBy(node) { + this.append("partition by "); + this.compileList(node.items); + } + visitPartitionByItem(node) { + this.visitNode(node.partitionBy); + } + visitBinaryOperation(node) { + this.visitNode(node.leftOperand); + this.append(" "); + this.visitNode(node.operator); + this.append(" "); + this.visitNode(node.rightOperand); + } + visitUnaryOperation(node) { + this.visitNode(node.operator); + if (!this.isMinusOperator(node.operator)) { + this.append(" "); + } + this.visitNode(node.operand); + } + isMinusOperator(node) { + return OperatorNode.is(node) && node.operator === "-"; + } + visitUsing(node) { + this.append("using "); + this.compileList(node.tables); + } + visitFunction(node) { + this.append(node.func); + this.append("("); + this.compileList(node.arguments); + this.append(")"); + } + visitCase(node) { + this.append("case"); + if (node.value) { + this.append(" "); + this.visitNode(node.value); + } + if (node.when) { + this.append(" "); + this.compileList(node.when, " "); + } + if (node.else) { + this.append(" else "); + this.visitNode(node.else); + } + this.append(" end"); + if (node.isStatement) { + this.append(" case"); + } + } + visitWhen(node) { + this.append("when "); + this.visitNode(node.condition); + if (node.result) { + this.append(" then "); + this.visitNode(node.result); + } + } + visitJSONReference(node) { + this.visitNode(node.reference); + this.visitNode(node.traversal); + } + visitJSONPath(node) { + if (node.inOperator) { + this.visitNode(node.inOperator); + } + this.append("'$"); + for (const pathLeg of node.pathLegs) { + this.visitNode(pathLeg); + } + this.append("'"); + } + visitJSONPathLeg(node) { + const isArrayLocation = node.type === "ArrayLocation"; + this.append(isArrayLocation ? "[" : "."); + this.append(typeof node.value === "string" ? this.sanitizeStringLiteral(node.value) : String(node.value)); + if (isArrayLocation) { + this.append("]"); + } + } + visitJSONOperatorChain(node) { + for (let i = 0, len = node.values.length; i < len; i++) { + if (i === len - 1) { + this.visitNode(node.operator); + } else { + this.append("->"); + } + this.visitNode(node.values[i]); + } + } + visitMergeQuery(node) { + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append("merge "); + if (node.top) { + this.visitNode(node.top); + this.append(" "); + } + this.append("into "); + this.visitNode(node.into); + if (node.using) { + this.append(" "); + this.visitNode(node.using); + } + if (node.whens) { + this.append(" "); + this.compileList(node.whens, " "); + } + if (node.returning) { + this.append(" "); + this.visitNode(node.returning); + } + if (node.output) { + this.append(" "); + this.visitNode(node.output); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + visitMatched(node) { + if (node.not) { + this.append("not "); + } + this.append("matched"); + if (node.bySource) { + this.append(" by source"); + } + } + visitAddIndex(node) { + this.append("add "); + if (node.unique) { + this.append("unique "); + } + this.append("index "); + this.visitNode(node.name); + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } + if (node.using) { + this.append(" using "); + this.visitNode(node.using); + } + } + visitCast(node) { + this.append("cast("); + this.visitNode(node.expression); + this.append(" as "); + this.visitNode(node.dataType); + this.append(")"); + } + visitFetch(node) { + this.append("fetch next "); + this.visitNode(node.rowCount); + this.append(` rows ${node.modifier}`); + } + visitOutput(node) { + this.append("output "); + this.compileList(node.selections); + } + visitTop(node) { + this.append(`top(${node.expression})`); + if (node.modifiers) { + this.append(` ${node.modifiers}`); + } + } + visitOrAction(node) { + this.append(node.action); + } + visitCollate(node) { + this.append("collate "); + this.visitNode(node.collation); + } + append(str) { + __privateSet(this, _sql, __privateGet(this, _sql) + str); + } + appendValue(parameter) { + this.addParameter(parameter); + this.append(this.getCurrentParameterPlaceholder()); + } + getLeftIdentifierWrapper() { + return '"'; + } + getRightIdentifierWrapper() { + return '"'; + } + getCurrentParameterPlaceholder() { + return "$" + this.numParameters; + } + getLeftExplainOptionsWrapper() { + return "("; + } + getExplainOptionAssignment() { + return " "; + } + getExplainOptionsDelimiter() { + return ", "; + } + getRightExplainOptionsWrapper() { + return ")"; + } + sanitizeIdentifier(identifier) { + const leftWrap = this.getLeftIdentifierWrapper(); + const rightWrap = this.getRightIdentifierWrapper(); + let sanitized = ""; + for (const c of identifier) { + sanitized += c; + if (c === leftWrap) { + sanitized += leftWrap; + } else if (c === rightWrap) { + sanitized += rightWrap; + } + } + return sanitized; + } + sanitizeStringLiteral(value) { + return value.replace(LIT_WRAP_REGEX, "''"); + } + addParameter(parameter) { + __privateGet(this, _parameters).push(parameter); + } + appendImmediateValue(value) { + if (isString2(value)) { + this.appendStringLiteral(value); + } else if (isNumber2(value) || isBoolean2(value) || isBigInt(value)) { + this.append(value.toString()); + } else if (isNull(value)) { + this.append("null"); + } else if (isDate2(value)) { + this.appendImmediateValue(value.toISOString()); + } else { + throw new Error(`invalid immediate value ${value}`); + } + } + appendStringLiteral(value) { + this.append("'"); + this.append(this.sanitizeStringLiteral(value)); + this.append("'"); + } + sortSelectModifiers(arr) { + arr.sort((left, right) => left.modifier && right.modifier ? SELECT_MODIFIER_PRIORITY[left.modifier] - SELECT_MODIFIER_PRIORITY[right.modifier] : 1); + return freeze(arr); + } + compileColumnAlterations(columnAlterations) { + this.compileList(columnAlterations); + } + /** + * controls whether the dialect adds a "type" keyword before a column's new data + * type in an ALTER TABLE statement. + */ + announcesNewColumnDataType() { + return true; + } + }; + _sql = new WeakMap(); + _parameters = new WeakMap(); + SELECT_MODIFIER_SQL = freeze({ + ForKeyShare: "for key share", + ForNoKeyUpdate: "for no key update", + ForUpdate: "for update", + ForShare: "for share", + NoWait: "nowait", + SkipLocked: "skip locked", + Distinct: "distinct" + }); + SELECT_MODIFIER_PRIORITY = freeze({ + ForKeyShare: 1, + ForNoKeyUpdate: 1, + ForUpdate: 1, + ForShare: 1, + NoWait: 2, + SkipLocked: 2, + Distinct: 0 + }); + JOIN_TYPE_SQL = freeze({ + InnerJoin: "inner join", + LeftJoin: "left join", + RightJoin: "right join", + FullJoin: "full join", + CrossJoin: "cross join", + LateralInnerJoin: "inner join lateral", + LateralLeftJoin: "left join lateral", + LateralCrossJoin: "cross join lateral", + OuterApply: "outer apply", + CrossApply: "cross apply", + Using: "using" + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js +var CompiledQuery; +var init_compiled_query = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js"() { + init_raw_node(); + init_object_utils(); + init_query_id(); + CompiledQuery = freeze({ + raw(sql2, parameters = []) { + return freeze({ + sql: sql2, + query: RawNode.createWithSql(sql2), + parameters: freeze(parameters), + queryId: createQueryId() + }); + } + }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js +var init_database_connection = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js +var init_connection_provider = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js +var init_dummy_driver = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js +var init_dialect = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js +var init_dialect_adapter = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js +var DialectAdapterBase; +var init_dialect_adapter_base = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js"() { + DialectAdapterBase = class { + get supportsCreateIfNotExists() { + return true; + } + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return false; + } + get supportsOutput() { + return false; + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js +var init_database_introspector = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js +function parseSavepointCommand(command, savepointName) { + return RawNode.createWithChildren([ + RawNode.createWithSql(`${command} `), + IdentifierNode.create(savepointName) + // ensures savepointName gets sanitized + ]); +} +var init_savepoint_parser = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js"() { + init_identifier_node(); + init_raw_node(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js +var _config, _connectionMutex, _db, _connection2, SqliteDriver, _db2, SqliteConnection, _promise3, _resolve2, ConnectionMutex; +var init_sqlite_driver = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js"() { + init_select_query_node(); + init_savepoint_parser(); + init_compiled_query(); + init_object_utils(); + init_query_id(); + SqliteDriver = class { + constructor(config4) { + __privateAdd(this, _config); + __privateAdd(this, _connectionMutex, new ConnectionMutex()); + __privateAdd(this, _db); + __privateAdd(this, _connection2); + __privateSet(this, _config, freeze({ ...config4 })); + } + async init() { + __privateSet(this, _db, isFunction3(__privateGet(this, _config).database) ? await __privateGet(this, _config).database() : __privateGet(this, _config).database); + __privateSet(this, _connection2, new SqliteConnection(__privateGet(this, _db))); + if (__privateGet(this, _config).onCreateConnection) { + await __privateGet(this, _config).onCreateConnection(__privateGet(this, _connection2)); + } + } + async acquireConnection() { + await __privateGet(this, _connectionMutex).lock(); + return __privateGet(this, _connection2); + } + async beginTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("begin")); + } + async commitTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("rollback")); + } + async savepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); + } + async rollbackToSavepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); + } + async releaseSavepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId())); + } + async releaseConnection() { + __privateGet(this, _connectionMutex).unlock(); + } + async destroy() { + __privateGet(this, _db)?.close(); + } + }; + _config = new WeakMap(); + _connectionMutex = new WeakMap(); + _db = new WeakMap(); + _connection2 = new WeakMap(); + SqliteConnection = class { + constructor(db) { + __privateAdd(this, _db2); + __privateSet(this, _db2, db); + } + executeQuery(compiledQuery) { + const { sql: sql2, parameters } = compiledQuery; + const stmt = __privateGet(this, _db2).prepare(sql2); + if (stmt.reader) { + return Promise.resolve({ + rows: stmt.all(parameters) + }); + } + const { changes, lastInsertRowid } = stmt.run(parameters); + return Promise.resolve({ + numAffectedRows: changes !== void 0 && changes !== null ? BigInt(changes) : void 0, + insertId: lastInsertRowid !== void 0 && lastInsertRowid !== null ? BigInt(lastInsertRowid) : void 0, + rows: [] + }); + } + async *streamQuery(compiledQuery, _chunkSize) { + const { sql: sql2, parameters, query } = compiledQuery; + const stmt = __privateGet(this, _db2).prepare(sql2); + if (SelectQueryNode.is(query)) { + const iter = stmt.iterate(parameters); + for (const row of iter) { + yield { + rows: [row] + }; + } + } else { + throw new Error("Sqlite driver only supports streaming of select queries"); + } + } + }; + _db2 = new WeakMap(); + ConnectionMutex = class { + constructor() { + __privateAdd(this, _promise3); + __privateAdd(this, _resolve2); + } + async lock() { + while (__privateGet(this, _promise3)) { + await __privateGet(this, _promise3); + } + __privateSet(this, _promise3, new Promise((resolve2) => { + __privateSet(this, _resolve2, resolve2); + })); + } + unlock() { + const resolve2 = __privateGet(this, _resolve2); + __privateSet(this, _promise3, void 0); + __privateSet(this, _resolve2, void 0); + resolve2?.(); + } + }; + _promise3 = new WeakMap(); + _resolve2 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js +var ID_WRAP_REGEX, SqliteQueryCompiler; +var init_sqlite_query_compiler = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js"() { + init_default_query_compiler(); + ID_WRAP_REGEX = /"/g; + SqliteQueryCompiler = class extends DefaultQueryCompiler { + visitOrAction(node) { + this.append("or "); + this.append(node.action); + } + getCurrentParameterPlaceholder() { + return "?"; + } + getLeftExplainOptionsWrapper() { + return ""; + } + getRightExplainOptionsWrapper() { + return ""; + } + getLeftIdentifierWrapper() { + return '"'; + } + getRightIdentifierWrapper() { + return '"'; + } + getAutoIncrement() { + return "autoincrement"; + } + sanitizeIdentifier(identifier) { + return identifier.replace(ID_WRAP_REGEX, '""'); + } + visitDefaultInsertValue(_) { + this.append("null"); + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js +var DEFAULT_MIGRATION_TABLE, DEFAULT_MIGRATION_LOCK_TABLE, NO_MIGRATIONS; +var init_migrator = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js"() { + init_object_utils(); + DEFAULT_MIGRATION_TABLE = "kysely_migration"; + DEFAULT_MIGRATION_LOCK_TABLE = "kysely_migration_lock"; + NO_MIGRATIONS = freeze({ __noMigrations__: true }); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js +var _db3, _SqliteIntrospector_instances, tablesQuery_fn, getTableMetadata_fn, SqliteIntrospector; +var init_sqlite_introspector = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js"() { + init_migrator(); + init_sql(); + SqliteIntrospector = class { + constructor(db) { + __privateAdd(this, _SqliteIntrospector_instances); + __privateAdd(this, _db3); + __privateSet(this, _db3, db); + } + async getSchemas() { + return []; + } + async getTables(options = { withInternalKyselyTables: false }) { + return await __privateMethod(this, _SqliteIntrospector_instances, getTableMetadata_fn).call(this, options); + } + async getMetadata(options) { + return { + tables: await this.getTables(options) + }; + } + }; + _db3 = new WeakMap(); + _SqliteIntrospector_instances = new WeakSet(); + tablesQuery_fn = function(qb, options) { + let tablesQuery = qb.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").select(["name", "sql", "type"]).orderBy("name"); + if (!options.withInternalKyselyTables) { + tablesQuery = tablesQuery.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + } + return tablesQuery; + }; + getTableMetadata_fn = async function(options) { + var _a30; + const tablesResult = await __privateMethod(this, _SqliteIntrospector_instances, tablesQuery_fn).call(this, __privateGet(this, _db3), options).execute(); + const tableMetadata = await __privateGet(this, _db3).with("table_list", (qb) => __privateMethod(this, _SqliteIntrospector_instances, tablesQuery_fn).call(this, qb, options)).selectFrom([ + "table_list as tl", + sql`pragma_table_info(tl.name)`.as("p") + ]).select([ + "tl.name as table", + "p.cid", + "p.name", + "p.type", + "p.notnull", + "p.dflt_value", + "p.pk" + ]).orderBy("tl.name").orderBy("p.cid").execute(); + const columnsByTable = {}; + for (const row of tableMetadata) { + columnsByTable[_a30 = row.table] ?? (columnsByTable[_a30] = []); + columnsByTable[row.table].push(row); + } + return tablesResult.map(({ name, sql: sql2, type }) => { + let autoIncrementCol = sql2?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); + const columns = columnsByTable[name] ?? []; + if (!autoIncrementCol) { + const pkCols = columns.filter((r) => r.pk > 0); + if (pkCols.length === 1 && pkCols[0].type.toLowerCase() === "integer") { + autoIncrementCol = pkCols[0].name; + } + } + return { + name, + isView: type === "view", + columns: columns.map((col) => ({ + name: col.name, + dataType: col.type, + isNullable: !col.notnull, + isAutoIncrementing: col.name === autoIncrementCol, + hasDefaultValue: col.dflt_value != null, + comment: void 0 + })) + }; + }); + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js +var SqliteAdapter; +var init_sqlite_adapter = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js"() { + init_dialect_adapter_base(); + SqliteAdapter = class extends DialectAdapterBase { + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return true; + } + async acquireMigrationLock(_db15, _opt) { + } + async releaseMigrationLock(_db15, _opt) { + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js +var _config2, SqliteDialect; +var init_sqlite_dialect = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js"() { + init_sqlite_driver(); + init_sqlite_query_compiler(); + init_sqlite_introspector(); + init_sqlite_adapter(); + init_object_utils(); + SqliteDialect = class { + constructor(config4) { + __privateAdd(this, _config2); + __privateSet(this, _config2, freeze({ ...config4 })); + } + createDriver() { + return new SqliteDriver(__privateGet(this, _config2)); + } + createQueryCompiler() { + return new SqliteQueryCompiler(); + } + createAdapter() { + return new SqliteAdapter(); + } + createIntrospector(db) { + return new SqliteIntrospector(db); + } + }; + _config2 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js +var init_sqlite_dialect_config = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js +var ID_WRAP_REGEX2, PostgresQueryCompiler; +var init_postgres_query_compiler = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js"() { + init_default_query_compiler(); + ID_WRAP_REGEX2 = /"/g; + PostgresQueryCompiler = class extends DefaultQueryCompiler { + sanitizeIdentifier(identifier) { + return identifier.replace(ID_WRAP_REGEX2, '""'); + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js +var _db4, _PostgresIntrospector_instances, parseTableMetadata_fn, PostgresIntrospector; +var init_postgres_introspector = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js"() { + init_migrator(); + init_object_utils(); + init_sql(); + PostgresIntrospector = class { + constructor(db) { + __privateAdd(this, _PostgresIntrospector_instances); + __privateAdd(this, _db4); + __privateSet(this, _db4, db); + } + async getSchemas() { + let rawSchemas = await __privateGet(this, _db4).selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute(); + return rawSchemas.map((it) => ({ name: it.nspname })); + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = __privateGet(this, _db4).selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c", "a.attrelid", "c.oid").innerJoin("pg_catalog.pg_namespace as ns", "c.relnamespace", "ns.oid").innerJoin("pg_catalog.pg_type as typ", "a.atttypid", "typ.oid").innerJoin("pg_catalog.pg_namespace as dtns", "typ.typnamespace", "dtns.oid").select([ + "a.attname as column", + "a.attnotnull as not_null", + "a.atthasdef as has_default", + "c.relname as table", + "c.relkind as table_type", + "ns.nspname as schema", + "typ.typname as type", + "dtns.nspname as type_schema", + sql`col_description(a.attrelid, a.attnum)`.as("column_description"), + sql`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing") + ]).where("c.relkind", "in", [ + "r", + "v", + "p" + ]).where("ns.nspname", "!~", "^pg_").where("ns.nspname", "!=", "information_schema").where("ns.nspname", "!=", "crdb_internal").where(sql`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum", ">=", 0).where("a.attisdropped", "!=", true).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo(); + if (!options.withInternalKyselyTables) { + query = query.where("c.relname", "!=", DEFAULT_MIGRATION_TABLE).where("c.relname", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + } + const rawColumns = await query.execute(); + return __privateMethod(this, _PostgresIntrospector_instances, parseTableMetadata_fn).call(this, rawColumns); + } + async getMetadata(options) { + return { + tables: await this.getTables(options) + }; + } + }; + _db4 = new WeakMap(); + _PostgresIntrospector_instances = new WeakSet(); + parseTableMetadata_fn = function(columns) { + const tableDictionary = /* @__PURE__ */ new Map(); + for (let i = 0, len = columns.length; i < len; i++) { + const column = columns[i]; + const { schema: schema3, table } = column; + const tableKey = `schema:${schema3};table:${table}`; + if (!tableDictionary.has(tableKey)) { + tableDictionary.set(tableKey, freeze({ + columns: [], + isView: column.table_type === "v", + name: table, + schema: schema3 + })); + } + tableDictionary.get(tableKey).columns.push(freeze({ + comment: column.column_description ?? void 0, + dataType: column.type, + dataTypeSchema: column.type_schema, + hasDefaultValue: column.has_default, + isAutoIncrementing: column.auto_incrementing !== null, + isNullable: !column.not_null, + name: column.column + })); + } + return Array.from(tableDictionary.values()); + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js +var LOCK_ID, PostgresAdapter; +var init_postgres_adapter = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js"() { + init_sql(); + init_dialect_adapter_base(); + LOCK_ID = BigInt("3853314791062309107"); + PostgresAdapter = class extends DialectAdapterBase { + get supportsTransactionalDdl() { + return true; + } + get supportsReturning() { + return true; + } + async acquireMigrationLock(db, _opt) { + await sql`select pg_advisory_xact_lock(${sql.lit(LOCK_ID)})`.execute(db); + } + async releaseMigrationLock(_db15, _opt) { + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js +function extendStackTrace(err, stackError) { + if (isStackHolder(err) && stackError.stack) { + const stackExtension = stackError.stack.split("\n").slice(1).join("\n"); + err.stack += ` +${stackExtension}`; + return err; + } + return err; +} +function isStackHolder(obj) { + return isObject4(obj) && isString2(obj.stack); +} +var init_stack_trace_utils = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js"() { + init_object_utils(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js +function isOkPacket(obj) { + return isObject4(obj) && "insertId" in obj && "affectedRows" in obj; +} +var PRIVATE_RELEASE_METHOD, _config3, _connections2, _pool, _MysqlDriver_instances, acquireConnection_fn, MysqlDriver, _rawConnection, _MysqlConnection_instances, executeQuery_fn, MysqlConnection; +var init_mysql_driver = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js"() { + init_savepoint_parser(); + init_compiled_query(); + init_object_utils(); + init_query_id(); + init_stack_trace_utils(); + PRIVATE_RELEASE_METHOD = Symbol(); + MysqlDriver = class { + constructor(configOrPool) { + __privateAdd(this, _MysqlDriver_instances); + __privateAdd(this, _config3); + __privateAdd(this, _connections2, /* @__PURE__ */ new WeakMap()); + __privateAdd(this, _pool); + __privateSet(this, _config3, freeze({ ...configOrPool })); + } + async init() { + __privateSet(this, _pool, isFunction3(__privateGet(this, _config3).pool) ? await __privateGet(this, _config3).pool() : __privateGet(this, _config3).pool); + } + async acquireConnection() { + const rawConnection = await __privateMethod(this, _MysqlDriver_instances, acquireConnection_fn).call(this); + let connection = __privateGet(this, _connections2).get(rawConnection); + if (!connection) { + connection = new MysqlConnection(rawConnection); + __privateGet(this, _connections2).set(rawConnection, connection); + if (__privateGet(this, _config3)?.onCreateConnection) { + await __privateGet(this, _config3).onCreateConnection(connection); + } + } + if (__privateGet(this, _config3)?.onReserveConnection) { + await __privateGet(this, _config3).onReserveConnection(connection); + } + return connection; + } + async beginTransaction(connection, settings) { + if (settings.isolationLevel || settings.accessMode) { + const parts = []; + if (settings.isolationLevel) { + parts.push(`isolation level ${settings.isolationLevel}`); + } + if (settings.accessMode) { + parts.push(settings.accessMode); + } + const sql2 = `set transaction ${parts.join(", ")}`; + await connection.executeQuery(CompiledQuery.raw(sql2)); + } + await connection.executeQuery(CompiledQuery.raw("begin")); + } + async commitTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("rollback")); + } + async savepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); + } + async rollbackToSavepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); + } + async releaseSavepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("release savepoint", savepointName), createQueryId())); + } + async releaseConnection(connection) { + connection[PRIVATE_RELEASE_METHOD](); + } + async destroy() { + return new Promise((resolve2, reject) => { + __privateGet(this, _pool).end((err) => { + if (err) { + reject(err); + } else { + resolve2(); + } + }); + }); + } + }; + _config3 = new WeakMap(); + _connections2 = new WeakMap(); + _pool = new WeakMap(); + _MysqlDriver_instances = new WeakSet(); + acquireConnection_fn = async function() { + return new Promise((resolve2, reject) => { + __privateGet(this, _pool).getConnection(async (err, rawConnection) => { + if (err) { + reject(err); + } else { + resolve2(rawConnection); + } + }); + }); + }; + MysqlConnection = class { + constructor(rawConnection) { + __privateAdd(this, _MysqlConnection_instances); + __privateAdd(this, _rawConnection); + __privateSet(this, _rawConnection, rawConnection); + } + async executeQuery(compiledQuery) { + try { + const result = await __privateMethod(this, _MysqlConnection_instances, executeQuery_fn).call(this, compiledQuery); + if (isOkPacket(result)) { + const { insertId, affectedRows, changedRows } = result; + return { + insertId: insertId !== void 0 && insertId !== null && insertId.toString() !== "0" ? BigInt(insertId) : void 0, + numAffectedRows: affectedRows !== void 0 && affectedRows !== null ? BigInt(affectedRows) : void 0, + numChangedRows: changedRows !== void 0 && changedRows !== null ? BigInt(changedRows) : void 0, + rows: [] + }; + } else if (Array.isArray(result)) { + return { + rows: result + }; + } + return { + rows: [] + }; + } catch (err) { + throw extendStackTrace(err, new Error()); + } + } + async *streamQuery(compiledQuery, _chunkSize) { + const stream = __privateGet(this, _rawConnection).query(compiledQuery.sql, compiledQuery.parameters).stream({ + objectMode: true + }); + try { + for await (const row of stream) { + yield { + rows: [row] + }; + } + } catch (ex) { + if (ex && typeof ex === "object" && "code" in ex && // @ts-ignore + ex.code === "ERR_STREAM_PREMATURE_CLOSE") { + return; + } + throw ex; + } + } + [PRIVATE_RELEASE_METHOD]() { + __privateGet(this, _rawConnection).release(); + } + }; + _rawConnection = new WeakMap(); + _MysqlConnection_instances = new WeakSet(); + executeQuery_fn = function(compiledQuery) { + return new Promise((resolve2, reject) => { + __privateGet(this, _rawConnection).query(compiledQuery.sql, compiledQuery.parameters, (err, result) => { + if (err) { + reject(err); + } else { + resolve2(result); + } + }); + }); + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js +var LITERAL_ESCAPE_REGEX, ID_WRAP_REGEX3, MysqlQueryCompiler; +var init_mysql_query_compiler = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js"() { + init_default_query_compiler(); + LITERAL_ESCAPE_REGEX = /\\|'/g; + ID_WRAP_REGEX3 = /`/g; + MysqlQueryCompiler = class extends DefaultQueryCompiler { + getCurrentParameterPlaceholder() { + return "?"; + } + getLeftExplainOptionsWrapper() { + return ""; + } + getExplainOptionAssignment() { + return "="; + } + getExplainOptionsDelimiter() { + return " "; + } + getRightExplainOptionsWrapper() { + return ""; + } + getLeftIdentifierWrapper() { + return ID_WRAP_REGEX3.source; + } + getRightIdentifierWrapper() { + return ID_WRAP_REGEX3.source; + } + sanitizeIdentifier(identifier) { + return identifier.replace(ID_WRAP_REGEX3, "``"); + } + /** + * MySQL requires escaping backslashes in string literals when using the + * default NO_BACKSLASH_ESCAPES=OFF mode. Without this, a backslash + * followed by a quote (\') can break out of the string literal. + * + * @see https://dev.mysql.com/doc/refman/9.6/en/string-literals.html + */ + sanitizeStringLiteral(value) { + return value.replace(LITERAL_ESCAPE_REGEX, (char) => char === "\\" ? "\\\\" : "''"); + } + visitCreateIndex(node) { + this.append("create "); + if (node.unique) { + this.append("unique "); + } + this.append("index "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.name); + if (node.using) { + this.append(" using "); + this.visitNode(node.using); + } + if (node.table) { + this.append(" on "); + this.visitNode(node.table); + } + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js +var _db5, _MysqlIntrospector_instances, parseTableMetadata_fn2, MysqlIntrospector; +var init_mysql_introspector = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js"() { + init_migrator(); + init_object_utils(); + init_sql(); + MysqlIntrospector = class { + constructor(db) { + __privateAdd(this, _MysqlIntrospector_instances); + __privateAdd(this, _db5); + __privateSet(this, _db5, db); + } + async getSchemas() { + let rawSchemas = await __privateGet(this, _db5).selectFrom("information_schema.schemata").select("schema_name").$castTo().execute(); + return rawSchemas.map((it) => ({ name: it.SCHEMA_NAME })); + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = __privateGet(this, _db5).selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables", (b) => b.onRef("columns.TABLE_CATALOG", "=", "tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA", "=", "tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME", "=", "tables.TABLE_NAME")).select([ + "columns.COLUMN_NAME", + "columns.COLUMN_DEFAULT", + "columns.TABLE_NAME", + "columns.TABLE_SCHEMA", + "tables.TABLE_TYPE", + "columns.IS_NULLABLE", + "columns.DATA_TYPE", + "columns.EXTRA", + "columns.COLUMN_COMMENT" + ]).where("columns.TABLE_SCHEMA", "=", sql`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo(); + if (!options.withInternalKyselyTables) { + query = query.where("columns.TABLE_NAME", "!=", DEFAULT_MIGRATION_TABLE).where("columns.TABLE_NAME", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + } + const rawColumns = await query.execute(); + return __privateMethod(this, _MysqlIntrospector_instances, parseTableMetadata_fn2).call(this, rawColumns); + } + async getMetadata(options) { + return { + tables: await this.getTables(options) + }; + } + }; + _db5 = new WeakMap(); + _MysqlIntrospector_instances = new WeakSet(); + parseTableMetadata_fn2 = function(columns) { + return columns.reduce((tables, it) => { + let table = tables.find((tbl) => tbl.name === it.TABLE_NAME); + if (!table) { + table = freeze({ + name: it.TABLE_NAME, + isView: it.TABLE_TYPE === "VIEW", + schema: it.TABLE_SCHEMA, + columns: [] + }); + tables.push(table); + } + table.columns.push(freeze({ + name: it.COLUMN_NAME, + dataType: it.DATA_TYPE, + isNullable: it.IS_NULLABLE === "YES", + isAutoIncrementing: it.EXTRA.toLowerCase().includes("auto_increment"), + hasDefaultValue: it.COLUMN_DEFAULT !== null, + comment: it.COLUMN_COMMENT === "" ? void 0 : it.COLUMN_COMMENT + })); + return tables; + }, []); + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js +var LOCK_ID2, LOCK_TIMEOUT_SECONDS, MysqlAdapter; +var init_mysql_adapter = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js"() { + init_sql(); + init_dialect_adapter_base(); + LOCK_ID2 = "ea586330-2c93-47c8-908d-981d9d270f9d"; + LOCK_TIMEOUT_SECONDS = 60 * 60; + MysqlAdapter = class extends DialectAdapterBase { + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return false; + } + async acquireMigrationLock(db, _opt) { + await sql`select get_lock(${sql.lit(LOCK_ID2)}, ${sql.lit(LOCK_TIMEOUT_SECONDS)})`.execute(db); + } + async releaseMigrationLock(db, _opt) { + await sql`select release_lock(${sql.lit(LOCK_ID2)})`.execute(db); + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js +var _config4, MysqlDialect; +var init_mysql_dialect = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js"() { + init_mysql_driver(); + init_mysql_query_compiler(); + init_mysql_introspector(); + init_mysql_adapter(); + MysqlDialect = class { + constructor(config4) { + __privateAdd(this, _config4); + __privateSet(this, _config4, config4); + } + createDriver() { + return new MysqlDriver(__privateGet(this, _config4)); + } + createQueryCompiler() { + return new MysqlQueryCompiler(); + } + createAdapter() { + return new MysqlAdapter(); + } + createIntrospector(db) { + return new MysqlIntrospector(db); + } + }; + _config4 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js +var init_mysql_dialect_config = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js +var PRIVATE_RELEASE_METHOD2, _config5, _connections3, _pool2, PostgresDriver, _client, _options, PostgresConnection; +var init_postgres_driver = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js"() { + init_savepoint_parser(); + init_compiled_query(); + init_object_utils(); + init_query_id(); + init_stack_trace_utils(); + PRIVATE_RELEASE_METHOD2 = Symbol(); + PostgresDriver = class { + constructor(config4) { + __privateAdd(this, _config5); + __privateAdd(this, _connections3, /* @__PURE__ */ new WeakMap()); + __privateAdd(this, _pool2); + __privateSet(this, _config5, freeze({ ...config4 })); + } + async init() { + __privateSet(this, _pool2, isFunction3(__privateGet(this, _config5).pool) ? await __privateGet(this, _config5).pool() : __privateGet(this, _config5).pool); + } + async acquireConnection() { + const client = await __privateGet(this, _pool2).connect(); + let connection = __privateGet(this, _connections3).get(client); + if (!connection) { + connection = new PostgresConnection(client, { + cursor: __privateGet(this, _config5).cursor ?? null + }); + __privateGet(this, _connections3).set(client, connection); + if (__privateGet(this, _config5).onCreateConnection) { + await __privateGet(this, _config5).onCreateConnection(connection); + } + } + if (__privateGet(this, _config5).onReserveConnection) { + await __privateGet(this, _config5).onReserveConnection(connection); + } + return connection; + } + async beginTransaction(connection, settings) { + if (settings.isolationLevel || settings.accessMode) { + let sql2 = "start transaction"; + if (settings.isolationLevel) { + sql2 += ` isolation level ${settings.isolationLevel}`; + } + if (settings.accessMode) { + sql2 += ` ${settings.accessMode}`; + } + await connection.executeQuery(CompiledQuery.raw(sql2)); + } else { + await connection.executeQuery(CompiledQuery.raw("begin")); + } + } + async commitTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("rollback")); + } + async savepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); + } + async rollbackToSavepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); + } + async releaseSavepoint(connection, savepointName, compileQuery) { + await connection.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId())); + } + async releaseConnection(connection) { + connection[PRIVATE_RELEASE_METHOD2](); + } + async destroy() { + if (__privateGet(this, _pool2)) { + const pool = __privateGet(this, _pool2); + __privateSet(this, _pool2, void 0); + await pool.end(); + } + } + }; + _config5 = new WeakMap(); + _connections3 = new WeakMap(); + _pool2 = new WeakMap(); + PostgresConnection = class { + constructor(client, options) { + __privateAdd(this, _client); + __privateAdd(this, _options); + __privateSet(this, _client, client); + __privateSet(this, _options, options); + } + async executeQuery(compiledQuery) { + try { + const { command, rowCount, rows } = await __privateGet(this, _client).query(compiledQuery.sql, [...compiledQuery.parameters]); + return { + numAffectedRows: command === "INSERT" || command === "UPDATE" || command === "DELETE" || command === "MERGE" ? BigInt(rowCount) : void 0, + rows: rows ?? [] + }; + } catch (err) { + throw extendStackTrace(err, new Error()); + } + } + async *streamQuery(compiledQuery, chunkSize) { + if (!__privateGet(this, _options).cursor) { + throw new Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres."); + } + if (!Number.isInteger(chunkSize) || chunkSize <= 0) { + throw new Error("chunkSize must be a positive integer"); + } + const cursor = __privateGet(this, _client).query(new (__privateGet(this, _options)).cursor(compiledQuery.sql, compiledQuery.parameters.slice())); + try { + while (true) { + const rows = await cursor.read(chunkSize); + if (rows.length === 0) { + break; + } + yield { + rows + }; + } + } finally { + await cursor.close(); + } + } + [PRIVATE_RELEASE_METHOD2]() { + __privateGet(this, _client).release(); + } + }; + _client = new WeakMap(); + _options = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js +var init_postgres_dialect_config = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js +var _config6, PostgresDialect; +var init_postgres_dialect = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js"() { + init_postgres_driver(); + init_postgres_introspector(); + init_postgres_query_compiler(); + init_postgres_adapter(); + PostgresDialect = class { + constructor(config4) { + __privateAdd(this, _config6); + __privateSet(this, _config6, config4); + } + createDriver() { + return new PostgresDriver(__privateGet(this, _config6)); + } + createQueryCompiler() { + return new PostgresQueryCompiler(); + } + createAdapter() { + return new PostgresAdapter(); + } + createIntrospector(db) { + return new PostgresIntrospector(db); + } + }; + _config6 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js +var MssqlAdapter; +var init_mssql_adapter = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js"() { + init_migrator(); + init_sql(); + init_dialect_adapter_base(); + MssqlAdapter = class extends DialectAdapterBase { + get supportsCreateIfNotExists() { + return false; + } + get supportsTransactionalDdl() { + return true; + } + get supportsOutput() { + return true; + } + async acquireMigrationLock(db) { + await sql`exec sp_getapplock @DbPrincipal = ${sql.lit("dbo")}, @Resource = ${sql.lit(DEFAULT_MIGRATION_TABLE)}, @LockMode = ${sql.lit("Exclusive")}`.execute(db); + } + async releaseMigrationLock() { + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js +var init_mssql_dialect_config = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js +var PRIVATE_RESET_METHOD, PRIVATE_DESTROY_METHOD, PRIVATE_VALIDATE_METHOD, _config7, _pool3, MssqlDriver, _connection3, _hasSocketError, _tedious, _MssqlConnection_instances, getTediousIsolationLevel_fn, cancelRequest_fn, isConnectionClosed_fn, MssqlConnection, _request, _rows, _streamChunkSize, _subscribers, _tedious2, _rowCount, _MssqlRequest_instances, addParametersToRequest_fn, attachListeners_fn, getTediousDataType_fn, MssqlRequest; +var init_mssql_driver = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js"() { + init_object_utils(); + init_compiled_query(); + init_stack_trace_utils(); + init_random_string(); + init_deferred(); + PRIVATE_RESET_METHOD = Symbol(); + PRIVATE_DESTROY_METHOD = Symbol(); + PRIVATE_VALIDATE_METHOD = Symbol(); + MssqlDriver = class { + constructor(config4) { + __privateAdd(this, _config7); + __privateAdd(this, _pool3); + __privateSet(this, _config7, freeze({ ...config4 })); + const { tarn, tedious, validateConnections } = __privateGet(this, _config7); + const { validateConnections: deprecatedValidateConnections, ...poolOptions } = tarn.options; + __privateSet(this, _pool3, new tarn.Pool({ + ...poolOptions, + create: async () => { + const connection = await tedious.connectionFactory(); + return await new MssqlConnection(connection, tedious).connect(); + }, + destroy: async (connection) => { + await connection[PRIVATE_DESTROY_METHOD](); + }, + // @ts-ignore `tarn` accepts a function that returns a promise here, but + // the types are not aligned and it type errors. + validate: validateConnections === false || deprecatedValidateConnections === false ? void 0 : (connection) => connection[PRIVATE_VALIDATE_METHOD]() + })); + } + async init() { + } + async acquireConnection() { + return await __privateGet(this, _pool3).acquire().promise; + } + async beginTransaction(connection, settings) { + await connection.beginTransaction(settings); + } + async commitTransaction(connection) { + await connection.commitTransaction(); + } + async rollbackTransaction(connection) { + await connection.rollbackTransaction(); + } + async savepoint(connection, savepointName) { + await connection.savepoint(savepointName); + } + async rollbackToSavepoint(connection, savepointName) { + await connection.rollbackTransaction(savepointName); + } + async releaseConnection(connection) { + if (__privateGet(this, _config7).resetConnectionsOnRelease || __privateGet(this, _config7).tedious.resetConnectionOnRelease) { + await connection[PRIVATE_RESET_METHOD](); + } + __privateGet(this, _pool3).release(connection); + } + async destroy() { + await __privateGet(this, _pool3).destroy(); + } + }; + _config7 = new WeakMap(); + _pool3 = new WeakMap(); + MssqlConnection = class { + constructor(connection, tedious) { + __privateAdd(this, _MssqlConnection_instances); + __privateAdd(this, _connection3); + __privateAdd(this, _hasSocketError); + __privateAdd(this, _tedious); + __privateSet(this, _connection3, connection); + __privateSet(this, _hasSocketError, false); + __privateSet(this, _tedious, tedious); + } + async beginTransaction(settings) { + const { isolationLevel } = settings; + await new Promise((resolve2, reject) => __privateGet(this, _connection3).beginTransaction((error49) => { + if (error49) + reject(error49); + else + resolve2(void 0); + }, isolationLevel ? randomString2(8) : void 0, isolationLevel ? __privateMethod(this, _MssqlConnection_instances, getTediousIsolationLevel_fn).call(this, isolationLevel) : void 0)); + } + async commitTransaction() { + await new Promise((resolve2, reject) => __privateGet(this, _connection3).commitTransaction((error49) => { + if (error49) + reject(error49); + else + resolve2(void 0); + })); + } + async connect() { + const { promise: waitForConnected, reject, resolve: resolve2 } = new Deferred(); + __privateGet(this, _connection3).connect((error49) => { + if (error49) { + return reject(error49); + } + resolve2(); + }); + __privateGet(this, _connection3).on("error", (error49) => { + if (error49 instanceof Error && "code" in error49 && error49.code === "ESOCKET") { + __privateSet(this, _hasSocketError, true); + } + console.error(error49); + reject(error49); + }); + function endListener() { + reject(new Error("The connection ended without ever completing the connection")); + } + __privateGet(this, _connection3).once("end", endListener); + await waitForConnected; + __privateGet(this, _connection3).off("end", endListener); + return this; + } + async executeQuery(compiledQuery) { + try { + const deferred = new Deferred(); + const request = new MssqlRequest({ + compiledQuery, + tedious: __privateGet(this, _tedious), + onDone: deferred + }); + __privateGet(this, _connection3).execSql(request.request); + const { rowCount, rows } = await deferred.promise; + return { + numAffectedRows: rowCount !== void 0 ? BigInt(rowCount) : void 0, + rows + }; + } catch (err) { + throw extendStackTrace(err, new Error()); + } + } + async rollbackTransaction(savepointName) { + await new Promise((resolve2, reject) => __privateGet(this, _connection3).rollbackTransaction((error49) => { + if (error49) + reject(error49); + else + resolve2(void 0); + }, savepointName)); + } + async savepoint(savepointName) { + await new Promise((resolve2, reject) => __privateGet(this, _connection3).saveTransaction((error49) => { + if (error49) + reject(error49); + else + resolve2(void 0); + }, savepointName)); + } + async *streamQuery(compiledQuery, chunkSize) { + if (!Number.isInteger(chunkSize) || chunkSize <= 0) { + throw new Error("chunkSize must be a positive integer"); + } + const request = new MssqlRequest({ + compiledQuery, + streamChunkSize: chunkSize, + tedious: __privateGet(this, _tedious) + }); + __privateGet(this, _connection3).execSql(request.request); + try { + while (true) { + const rows = await request.readChunk(); + if (rows.length === 0) { + break; + } + yield { rows }; + if (rows.length < chunkSize) { + break; + } + } + } finally { + await __privateMethod(this, _MssqlConnection_instances, cancelRequest_fn).call(this, request); + } + } + [PRIVATE_DESTROY_METHOD]() { + if ("closed" in __privateGet(this, _connection3) && __privateGet(this, _connection3).closed) { + return Promise.resolve(); + } + return new Promise((resolve2) => { + __privateGet(this, _connection3).once("end", resolve2); + __privateGet(this, _connection3).close(); + }); + } + async [PRIVATE_RESET_METHOD]() { + await new Promise((resolve2, reject) => { + __privateGet(this, _connection3).reset((error49) => { + if (error49) { + return reject(error49); + } + resolve2(); + }); + }); + } + async [PRIVATE_VALIDATE_METHOD]() { + if (__privateGet(this, _hasSocketError) || __privateMethod(this, _MssqlConnection_instances, isConnectionClosed_fn).call(this)) { + return false; + } + try { + const deferred = new Deferred(); + const request = new MssqlRequest({ + compiledQuery: CompiledQuery.raw("select 1"), + onDone: deferred, + tedious: __privateGet(this, _tedious) + }); + __privateGet(this, _connection3).execSql(request.request); + await deferred.promise; + return true; + } catch { + return false; + } + } + }; + _connection3 = new WeakMap(); + _hasSocketError = new WeakMap(); + _tedious = new WeakMap(); + _MssqlConnection_instances = new WeakSet(); + getTediousIsolationLevel_fn = function(isolationLevel) { + const { ISOLATION_LEVEL } = __privateGet(this, _tedious); + const mapper = { + "read committed": ISOLATION_LEVEL.READ_COMMITTED, + "read uncommitted": ISOLATION_LEVEL.READ_UNCOMMITTED, + "repeatable read": ISOLATION_LEVEL.REPEATABLE_READ, + serializable: ISOLATION_LEVEL.SERIALIZABLE, + snapshot: ISOLATION_LEVEL.SNAPSHOT + }; + const tediousIsolationLevel = mapper[isolationLevel]; + if (tediousIsolationLevel === void 0) { + throw new Error(`Unknown isolation level: ${isolationLevel}`); + } + return tediousIsolationLevel; + }; + cancelRequest_fn = function(request) { + return new Promise((resolve2) => { + request.request.once("requestCompleted", resolve2); + const wasCanceled = __privateGet(this, _connection3).cancel(); + if (!wasCanceled) { + request.request.off("requestCompleted", resolve2); + resolve2(); + } + }); + }; + isConnectionClosed_fn = function() { + return "closed" in __privateGet(this, _connection3) && Boolean(__privateGet(this, _connection3).closed); + }; + MssqlRequest = class { + constructor(props) { + __privateAdd(this, _MssqlRequest_instances); + __privateAdd(this, _request); + __privateAdd(this, _rows); + __privateAdd(this, _streamChunkSize); + __privateAdd(this, _subscribers); + __privateAdd(this, _tedious2); + __privateAdd(this, _rowCount); + const { compiledQuery, onDone, streamChunkSize, tedious } = props; + __privateSet(this, _rows, []); + __privateSet(this, _streamChunkSize, streamChunkSize); + __privateSet(this, _subscribers, {}); + __privateSet(this, _tedious2, tedious); + if (onDone) { + const subscriptionKey = "onDone"; + __privateGet(this, _subscribers)[subscriptionKey] = (event, error49) => { + if (event === "chunkReady") { + return; + } + delete __privateGet(this, _subscribers)[subscriptionKey]; + if (event === "error") { + return onDone.reject(error49); + } + onDone.resolve({ + rowCount: __privateGet(this, _rowCount), + rows: __privateGet(this, _rows) + }); + }; + } + __privateSet(this, _request, new (__privateGet(this, _tedious2)).Request(compiledQuery.sql, (err, rowCount) => { + if (err) { + return Object.values(__privateGet(this, _subscribers)).forEach((subscriber) => subscriber("error", err instanceof AggregateError ? err.errors : err)); + } + __privateSet(this, _rowCount, rowCount); + })); + __privateMethod(this, _MssqlRequest_instances, addParametersToRequest_fn).call(this, compiledQuery.parameters); + __privateMethod(this, _MssqlRequest_instances, attachListeners_fn).call(this); + } + get request() { + return __privateGet(this, _request); + } + readChunk() { + const subscriptionKey = this.readChunk.name; + return new Promise((resolve2, reject) => { + __privateGet(this, _subscribers)[subscriptionKey] = (event, error49) => { + delete __privateGet(this, _subscribers)[subscriptionKey]; + if (event === "error") { + return reject(error49); + } + resolve2(__privateGet(this, _rows).splice(0, __privateGet(this, _streamChunkSize))); + }; + __privateGet(this, _request).resume(); + }); + } + }; + _request = new WeakMap(); + _rows = new WeakMap(); + _streamChunkSize = new WeakMap(); + _subscribers = new WeakMap(); + _tedious2 = new WeakMap(); + _rowCount = new WeakMap(); + _MssqlRequest_instances = new WeakSet(); + addParametersToRequest_fn = function(parameters) { + for (let i = 0; i < parameters.length; i++) { + const parameter = parameters[i]; + __privateGet(this, _request).addParameter(String(i + 1), __privateMethod(this, _MssqlRequest_instances, getTediousDataType_fn).call(this, parameter), parameter); + } + }; + attachListeners_fn = function() { + const pauseAndEmitChunkReady = __privateGet(this, _streamChunkSize) ? () => { + if (__privateGet(this, _streamChunkSize) <= __privateGet(this, _rows).length) { + __privateGet(this, _request).pause(); + Object.values(__privateGet(this, _subscribers)).forEach((subscriber) => subscriber("chunkReady")); + } + } : () => { + }; + const rowListener = (columns) => { + const row = {}; + for (const column of columns) { + row[column.metadata.colName] = column.value; + } + __privateGet(this, _rows).push(row); + pauseAndEmitChunkReady(); + }; + __privateGet(this, _request).on("row", rowListener); + __privateGet(this, _request).once("requestCompleted", () => { + Object.values(__privateGet(this, _subscribers)).forEach((subscriber) => subscriber("completed")); + __privateGet(this, _request).off("row", rowListener); + }); + }; + getTediousDataType_fn = function(value) { + if (isNull(value) || isUndefined(value) || isString2(value)) { + return __privateGet(this, _tedious2).TYPES.NVarChar; + } + if (isBigInt(value) || isNumber2(value) && value % 1 === 0) { + if (value < -2147483648 || value > 2147483647) { + return __privateGet(this, _tedious2).TYPES.BigInt; + } else { + return __privateGet(this, _tedious2).TYPES.Int; + } + } + if (isNumber2(value)) { + return __privateGet(this, _tedious2).TYPES.Float; + } + if (isBoolean2(value)) { + return __privateGet(this, _tedious2).TYPES.Bit; + } + if (isDate2(value)) { + return __privateGet(this, _tedious2).TYPES.DateTime; + } + if (isBuffer(value)) { + return __privateGet(this, _tedious2).TYPES.VarBinary; + } + return __privateGet(this, _tedious2).TYPES.NVarChar; + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js +var _db6, MssqlIntrospector; +var init_mssql_introspector = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js"() { + init_migrator(); + init_object_utils(); + MssqlIntrospector = class { + constructor(db) { + __privateAdd(this, _db6); + __privateSet(this, _db6, db); + } + async getSchemas() { + return await __privateGet(this, _db6).selectFrom("sys.schemas").select("name").execute(); + } + async getTables(options = { withInternalKyselyTables: false }) { + const rawColumns = await __privateGet(this, _db6).selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas", "table_schemas.schema_id", "tables.schema_id").innerJoin("sys.columns as columns", "columns.object_id", "tables.object_id").innerJoin("sys.types as types", "types.user_type_id", "columns.user_type_id").leftJoin("sys.schemas as type_schemas", "type_schemas.schema_id", "types.schema_id").leftJoin("sys.extended_properties as comments", (join2) => join2.onRef("comments.major_id", "=", "tables.object_id").onRef("comments.minor_id", "=", "columns.column_id").on("comments.name", "=", "MS_Description")).$if(!options.withInternalKyselyTables, (qb) => qb.where("tables.name", "!=", DEFAULT_MIGRATION_TABLE).where("tables.name", "!=", DEFAULT_MIGRATION_LOCK_TABLE)).select([ + "tables.name as table_name", + (eb) => eb.ref("tables.type").$castTo().as("table_type"), + "table_schemas.name as table_schema_name", + "columns.default_object_id as column_default_object_id", + "columns.generated_always_type_desc as column_generated_always_type", + "columns.is_computed as column_is_computed", + "columns.is_identity as column_is_identity", + "columns.is_nullable as column_is_nullable", + "columns.is_rowguidcol as column_is_rowguidcol", + "columns.name as column_name", + "types.is_nullable as type_is_nullable", + "types.name as type_name", + "type_schemas.name as type_schema_name", + "comments.value as column_comment" + ]).unionAll(__privateGet(this, _db6).selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas", "view_schemas.schema_id", "views.schema_id").innerJoin("sys.columns as columns", "columns.object_id", "views.object_id").innerJoin("sys.types as types", "types.user_type_id", "columns.user_type_id").leftJoin("sys.schemas as type_schemas", "type_schemas.schema_id", "types.schema_id").leftJoin("sys.extended_properties as comments", (join2) => join2.onRef("comments.major_id", "=", "views.object_id").onRef("comments.minor_id", "=", "columns.column_id").on("comments.name", "=", "MS_Description")).select([ + "views.name as table_name", + "views.type as table_type", + "view_schemas.name as table_schema_name", + "columns.default_object_id as column_default_object_id", + "columns.generated_always_type_desc as column_generated_always_type", + "columns.is_computed as column_is_computed", + "columns.is_identity as column_is_identity", + "columns.is_nullable as column_is_nullable", + "columns.is_rowguidcol as column_is_rowguidcol", + "columns.name as column_name", + "types.is_nullable as type_is_nullable", + "types.name as type_name", + "type_schemas.name as type_schema_name", + "comments.value as column_comment" + ])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(); + const tableDictionary = {}; + for (const rawColumn of rawColumns) { + const key = `${rawColumn.table_schema_name}.${rawColumn.table_name}`; + const table = tableDictionary[key] = tableDictionary[key] || freeze({ + columns: [], + isView: rawColumn.table_type === "V ", + name: rawColumn.table_name, + schema: rawColumn.table_schema_name ?? void 0 + }); + table.columns.push(freeze({ + dataType: rawColumn.type_name, + dataTypeSchema: rawColumn.type_schema_name ?? void 0, + hasDefaultValue: rawColumn.column_default_object_id > 0 || rawColumn.column_generated_always_type !== "NOT_APPLICABLE" || rawColumn.column_is_identity || rawColumn.column_is_computed || rawColumn.column_is_rowguidcol, + isAutoIncrementing: rawColumn.column_is_identity, + isNullable: rawColumn.column_is_nullable && rawColumn.type_is_nullable, + name: rawColumn.column_name, + comment: rawColumn.column_comment ?? void 0 + })); + } + return Object.values(tableDictionary); + } + async getMetadata(options) { + return { + tables: await this.getTables(options) + }; + } + }; + _db6 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js +var COLLATION_CHAR_REGEX, MssqlQueryCompiler; +var init_mssql_query_compiler = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js"() { + init_default_query_compiler(); + COLLATION_CHAR_REGEX = /^[a-z0-9_]$/i; + MssqlQueryCompiler = class extends DefaultQueryCompiler { + getCurrentParameterPlaceholder() { + return `@${this.numParameters}`; + } + visitOffset(node) { + super.visitOffset(node); + this.append(" rows"); + } + // mssql allows multi-column alterations in a single statement, + // but you can only use the command keyword/s once. + // it also doesn't support multiple kinds of commands in the same + // alter table statement, but we compile that anyway for the sake + // of WYSIWYG. + compileColumnAlterations(columnAlterations) { + const nodesByKind = {}; + for (const columnAlteration of columnAlterations) { + if (!nodesByKind[columnAlteration.kind]) { + nodesByKind[columnAlteration.kind] = []; + } + nodesByKind[columnAlteration.kind].push(columnAlteration); + } + let first = true; + if (nodesByKind.AddColumnNode) { + this.append("add "); + this.compileList(nodesByKind.AddColumnNode); + first = false; + } + if (nodesByKind.AlterColumnNode) { + if (!first) + this.append(", "); + this.compileList(nodesByKind.AlterColumnNode); + } + if (nodesByKind.DropColumnNode) { + if (!first) + this.append(", "); + this.append("drop column "); + this.compileList(nodesByKind.DropColumnNode); + } + if (nodesByKind.ModifyColumnNode) { + if (!first) + this.append(", "); + this.compileList(nodesByKind.ModifyColumnNode); + } + if (nodesByKind.RenameColumnNode) { + if (!first) + this.append(", "); + this.compileList(nodesByKind.RenameColumnNode); + } + } + visitAddColumn(node) { + this.visitNode(node.column); + } + visitDropColumn(node) { + this.visitNode(node.column); + } + visitMergeQuery(node) { + super.visitMergeQuery(node); + this.append(";"); + } + visitCollate(node) { + this.append("collate "); + const { name } = node.collation; + for (const char of name) { + if (!COLLATION_CHAR_REGEX.test(char)) { + throw new Error(`Invalid collation: ${name}`); + } + } + this.append(name); + } + announcesNewColumnDataType() { + return false; + } + }; + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js +var _config8, MssqlDialect; +var init_mssql_dialect = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js"() { + init_mssql_adapter(); + init_mssql_driver(); + init_mssql_introspector(); + init_mssql_query_compiler(); + MssqlDialect = class { + constructor(config4) { + __privateAdd(this, _config8); + __privateSet(this, _config8, config4); + } + createDriver() { + return new MssqlDriver(__privateGet(this, _config8)); + } + createQueryCompiler() { + return new MssqlQueryCompiler(); + } + createAdapter() { + return new MssqlAdapter(); + } + createIntrospector(db) { + return new MssqlIntrospector(db); + } + }; + _config8 = new WeakMap(); + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js +var init_query_compiler = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js +var init_file_migration_provider = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js +var init_kysely_plugin = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js +var init_camel_case_plugin = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js +var init_deduplicate_joins_plugin = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js +var init_parse_json_results_plugin = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js +var init_handle_empty_in_lists_plugin = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js +var init_handle_empty_in_lists = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js +var init_constraint_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js +var init_operation_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js +var init_simple_reference_expression_node = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js +var init_column_type = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js +var init_explainable = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js +var init_streamable = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js +var init_infer_result = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js"() { + } +}); + +// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js +var init_esm3 = __esm({ + "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js"() { + init_kysely(); + init_query_creator(); + init_expression(); + init_expression_wrapper(); + init_where_interface(); + init_returning_interface(); + init_output_interface(); + init_having_interface(); + init_order_by_interface(); + init_select_query_builder(); + init_insert_query_builder(); + init_update_query_builder(); + init_delete_query_builder(); + init_no_result_error(); + init_join_builder(); + init_function_module(); + init_insert_result(); + init_delete_result(); + init_update_result(); + init_on_conflict_builder(); + init_aggregate_function_builder(); + init_case_builder(); + init_json_path_builder(); + init_merge_query_builder(); + init_merge_result(); + init_order_by_item_builder(); + init_raw_builder(); + init_sql(); + init_query_executor(); + init_default_query_executor(); + init_noop_query_executor(); + init_query_executor_provider(); + init_default_query_compiler(); + init_compiled_query(); + init_schema(); + init_create_table_builder(); + init_create_type_builder(); + init_drop_table_builder(); + init_drop_type_builder(); + init_create_index_builder(); + init_drop_index_builder(); + init_create_schema_builder(); + init_drop_schema_builder(); + init_column_definition_builder(); + init_foreign_key_constraint_builder(); + init_alter_table_builder(); + init_create_view_builder(); + init_refresh_materialized_view_builder(); + init_drop_view_builder(); + init_alter_column_builder(); + init_dynamic(); + init_dynamic_reference_builder(); + init_dynamic_table_builder(); + init_driver(); + init_database_connection(); + init_connection_provider(); + init_default_connection_provider(); + init_single_connection_provider(); + init_dummy_driver(); + init_dialect(); + init_dialect_adapter(); + init_dialect_adapter_base(); + init_database_introspector(); + init_sqlite_dialect(); + init_sqlite_dialect_config(); + init_sqlite_driver(); + init_postgres_query_compiler(); + init_postgres_introspector(); + init_postgres_adapter(); + init_mysql_dialect(); + init_mysql_dialect_config(); + init_mysql_driver(); + init_mysql_query_compiler(); + init_mysql_introspector(); + init_mysql_adapter(); + init_postgres_driver(); + init_postgres_dialect_config(); + init_postgres_dialect(); + init_sqlite_query_compiler(); + init_sqlite_introspector(); + init_sqlite_adapter(); + init_mssql_adapter(); + init_mssql_dialect_config(); + init_mssql_dialect(); + init_mssql_driver(); + init_mssql_introspector(); + init_mssql_query_compiler(); + init_default_query_compiler(); + init_query_compiler(); + init_migrator(); + init_file_migration_provider(); + init_kysely_plugin(); + init_camel_case_plugin(); + init_deduplicate_joins_plugin(); + init_with_schema_plugin(); + init_parse_json_results_plugin(); + init_handle_empty_in_lists_plugin(); + init_handle_empty_in_lists(); + init_add_column_node(); + init_add_constraint_node(); + init_add_index_node(); + init_aggregate_function_node(); + init_alias_node(); + init_alter_column_node(); + init_alter_table_node(); + init_and_node(); + init_binary_operation_node(); + init_case_node(); + init_cast_node(); + init_check_constraint_node(); + init_collate_node(); + init_column_definition_node(); + init_column_node(); + init_column_update_node(); + init_common_table_expression_name_node(); + init_common_table_expression_node(); + init_constraint_node(); + init_create_index_node(); + init_create_schema_node(); + init_create_table_node(); + init_create_type_node(); + init_create_view_node(); + init_refresh_materialized_view_node(); + init_data_type_node(); + init_default_insert_value_node(); + init_default_value_node(); + init_delete_query_node(); + init_drop_column_node(); + init_drop_constraint_node(); + init_drop_index_node(); + init_drop_schema_node(); + init_drop_table_node(); + init_drop_type_node(); + init_drop_view_node(); + init_explain_node(); + init_fetch_node(); + init_foreign_key_constraint_node(); + init_from_node(); + init_function_node(); + init_generated_node(); + init_group_by_item_node(); + init_group_by_node(); + init_having_node(); + init_identifier_node(); + init_insert_query_node(); + init_join_node(); + init_json_operator_chain_node(); + init_json_path_leg_node(); + init_json_path_node(); + init_json_reference_node(); + init_limit_node(); + init_list_node(); + init_matched_node(); + init_merge_query_node(); + init_modify_column_node(); + init_offset_node(); + init_on_conflict_node(); + init_on_duplicate_key_node(); + init_on_node(); + init_operation_node_source(); + init_operation_node_transformer(); + init_operation_node_visitor(); + init_operation_node(); + init_operator_node(); + init_or_action_node(); + init_or_node(); + init_order_by_item_node(); + init_order_by_node(); + init_output_node(); + init_over_node(); + init_parens_node(); + init_partition_by_item_node(); + init_partition_by_node(); + init_primary_key_constraint_node(); + init_primitive_value_list_node(); + init_query_node(); + init_raw_node(); + init_reference_node(); + init_references_node(); + init_rename_column_node(); + init_rename_constraint_node(); + init_returning_node(); + init_schemable_identifier_node(); + init_select_all_node(); + init_select_modifier_node(); + init_select_query_node(); + init_selection_node(); + init_set_operation_node(); + init_simple_reference_expression_node(); + init_table_node(); + init_top_node(); + init_tuple_node(); + init_unary_operation_node(); + init_unique_constraint_node(); + init_update_query_node(); + init_using_node(); + init_value_list_node(); + init_value_node(); + init_values_node(); + init_when_node(); + init_where_node(); + init_with_node(); + init_column_type(); + init_compilable(); + init_explainable(); + init_streamable(); + init_log(); + init_infer_result(); + } +}); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/string.mjs +function capitalizeFirstLetter(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} +var init_string = __esm({ + "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/string.mjs"() { + } +}); + +// ../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/bun-sqlite-dialect-na--YwnN.mjs +var bun_sqlite_dialect_na_YwnN_exports = {}; +__export(bun_sqlite_dialect_na_YwnN_exports, { + BunSqliteDialect: () => BunSqliteDialect +}); +var BunSqliteAdapter, _config9, _connectionMutex2, _db7, _connection4, _a15, BunSqliteDriver, _db8, _a16, BunSqliteConnection, _promise4, _resolve3, _a17, ConnectionMutex2, _db9, _BunSqliteIntrospector_instances, getTableMetadata_fn2, _a18, BunSqliteIntrospector, BunSqliteQueryCompiler, _config10, _a19, BunSqliteDialect; +var init_bun_sqlite_dialect_na_YwnN = __esm({ + "../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/bun-sqlite-dialect-na--YwnN.mjs"() { + init_esm3(); + BunSqliteAdapter = class { + get supportsCreateIfNotExists() { + return true; + } + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return true; + } + async acquireMigrationLock() { + } + async releaseMigrationLock() { + } + get supportsOutput() { + return true; + } + }; + BunSqliteDriver = (_a15 = class { + constructor(config4) { + __privateAdd(this, _config9); + __privateAdd(this, _connectionMutex2, new ConnectionMutex2()); + __privateAdd(this, _db7); + __privateAdd(this, _connection4); + __privateSet(this, _config9, { ...config4 }); + } + async init() { + __privateSet(this, _db7, __privateGet(this, _config9).database); + __privateSet(this, _connection4, new BunSqliteConnection(__privateGet(this, _db7))); + if (__privateGet(this, _config9).onCreateConnection) await __privateGet(this, _config9).onCreateConnection(__privateGet(this, _connection4)); + } + async acquireConnection() { + await __privateGet(this, _connectionMutex2).lock(); + return __privateGet(this, _connection4); + } + async beginTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("begin")); + } + async commitTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("rollback")); + } + async releaseConnection() { + __privateGet(this, _connectionMutex2).unlock(); + } + async destroy() { + __privateGet(this, _db7)?.close(); + } + }, _config9 = new WeakMap(), _connectionMutex2 = new WeakMap(), _db7 = new WeakMap(), _connection4 = new WeakMap(), _a15); + BunSqliteConnection = (_a16 = class { + constructor(db) { + __privateAdd(this, _db8); + __privateSet(this, _db8, db); + } + executeQuery(compiledQuery) { + const { sql: sql2, parameters } = compiledQuery; + const stmt = __privateGet(this, _db8).prepare(sql2); + return Promise.resolve({ rows: stmt.all(parameters) }); + } + async *streamQuery() { + throw new Error("Streaming query is not supported by SQLite driver."); + } + }, _db8 = new WeakMap(), _a16); + ConnectionMutex2 = (_a17 = class { + constructor() { + __privateAdd(this, _promise4); + __privateAdd(this, _resolve3); + } + async lock() { + while (__privateGet(this, _promise4) !== void 0) await __privateGet(this, _promise4); + __privateSet(this, _promise4, new Promise((resolve2) => { + __privateSet(this, _resolve3, resolve2); + })); + } + unlock() { + const resolve2 = __privateGet(this, _resolve3); + __privateSet(this, _promise4, void 0); + __privateSet(this, _resolve3, void 0); + resolve2?.(); + } + }, _promise4 = new WeakMap(), _resolve3 = new WeakMap(), _a17); + BunSqliteIntrospector = (_a18 = class { + constructor(db) { + __privateAdd(this, _BunSqliteIntrospector_instances); + __privateAdd(this, _db9); + __privateSet(this, _db9, db); + } + async getSchemas() { + return []; + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = __privateGet(this, _db9).selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo(); + if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + const tables = await query.execute(); + return Promise.all(tables.map(({ name }) => __privateMethod(this, _BunSqliteIntrospector_instances, getTableMetadata_fn2).call(this, name))); + } + async getMetadata(options) { + return { tables: await this.getTables(options) }; + } + }, _db9 = new WeakMap(), _BunSqliteIntrospector_instances = new WeakSet(), getTableMetadata_fn2 = async function(table) { + const db = __privateGet(this, _db9); + const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); + return { + name: table, + columns: (await db.selectFrom(sql`pragma_table_info(${table})`.as("table_info")).select([ + "name", + "type", + "notnull", + "dflt_value" + ]).execute()).map((col) => ({ + name: col.name, + dataType: col.type, + isNullable: !col.notnull, + isAutoIncrementing: col.name === autoIncrementCol, + hasDefaultValue: col.dflt_value != null + })), + isView: true + }; + }, _a18); + BunSqliteQueryCompiler = class extends DefaultQueryCompiler { + getCurrentParameterPlaceholder() { + return "?"; + } + getLeftIdentifierWrapper() { + return '"'; + } + getRightIdentifierWrapper() { + return '"'; + } + getAutoIncrement() { + return "autoincrement"; + } + }; + BunSqliteDialect = (_a19 = class { + constructor(config4) { + __privateAdd(this, _config10); + __privateSet(this, _config10, { ...config4 }); + } + createDriver() { + return new BunSqliteDriver(__privateGet(this, _config10)); + } + createQueryCompiler() { + return new BunSqliteQueryCompiler(); + } + createAdapter() { + return new BunSqliteAdapter(); + } + createIntrospector(db) { + return new BunSqliteIntrospector(db); + } + }, _config10 = new WeakMap(), _a19); + } +}); + +// ../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/node-sqlite-dialect.mjs +var node_sqlite_dialect_exports = {}; +__export(node_sqlite_dialect_exports, { + NodeSqliteDialect: () => NodeSqliteDialect +}); +var NodeSqliteAdapter, _config11, _connectionMutex3, _db10, _connection5, _a20, NodeSqliteDriver, _db11, _a21, NodeSqliteConnection, _promise5, _resolve4, _a22, ConnectionMutex3, _db12, _NodeSqliteIntrospector_instances, getTableMetadata_fn3, _a23, NodeSqliteIntrospector, NodeSqliteQueryCompiler, _config12, _a24, NodeSqliteDialect; +var init_node_sqlite_dialect = __esm({ + "../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/node-sqlite-dialect.mjs"() { + init_esm3(); + NodeSqliteAdapter = class { + get supportsCreateIfNotExists() { + return true; + } + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return true; + } + async acquireMigrationLock() { + } + async releaseMigrationLock() { + } + get supportsOutput() { + return true; + } + }; + NodeSqliteDriver = (_a20 = class { + constructor(config4) { + __privateAdd(this, _config11); + __privateAdd(this, _connectionMutex3, new ConnectionMutex3()); + __privateAdd(this, _db10); + __privateAdd(this, _connection5); + __privateSet(this, _config11, { ...config4 }); + } + async init() { + __privateSet(this, _db10, __privateGet(this, _config11).database); + __privateSet(this, _connection5, new NodeSqliteConnection(__privateGet(this, _db10))); + if (__privateGet(this, _config11).onCreateConnection) await __privateGet(this, _config11).onCreateConnection(__privateGet(this, _connection5)); + } + async acquireConnection() { + await __privateGet(this, _connectionMutex3).lock(); + return __privateGet(this, _connection5); + } + async beginTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("begin")); + } + async commitTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection) { + await connection.executeQuery(CompiledQuery.raw("rollback")); + } + async releaseConnection() { + __privateGet(this, _connectionMutex3).unlock(); + } + async destroy() { + __privateGet(this, _db10)?.close(); + } + }, _config11 = new WeakMap(), _connectionMutex3 = new WeakMap(), _db10 = new WeakMap(), _connection5 = new WeakMap(), _a20); + NodeSqliteConnection = (_a21 = class { + constructor(db) { + __privateAdd(this, _db11); + __privateSet(this, _db11, db); + } + executeQuery(compiledQuery) { + const { sql: sql2, parameters } = compiledQuery; + const rows = __privateGet(this, _db11).prepare(sql2).all(...parameters); + return Promise.resolve({ rows }); + } + async *streamQuery() { + throw new Error("Streaming query is not supported by SQLite driver."); + } + }, _db11 = new WeakMap(), _a21); + ConnectionMutex3 = (_a22 = class { + constructor() { + __privateAdd(this, _promise5); + __privateAdd(this, _resolve4); + } + async lock() { + while (__privateGet(this, _promise5) !== void 0) await __privateGet(this, _promise5); + __privateSet(this, _promise5, new Promise((resolve2) => { + __privateSet(this, _resolve4, resolve2); + })); + } + unlock() { + const resolve2 = __privateGet(this, _resolve4); + __privateSet(this, _promise5, void 0); + __privateSet(this, _resolve4, void 0); + resolve2?.(); + } + }, _promise5 = new WeakMap(), _resolve4 = new WeakMap(), _a22); + NodeSqliteIntrospector = (_a23 = class { + constructor(db) { + __privateAdd(this, _NodeSqliteIntrospector_instances); + __privateAdd(this, _db12); + __privateSet(this, _db12, db); + } + async getSchemas() { + return []; + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = __privateGet(this, _db12).selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo(); + if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + const tables = await query.execute(); + return Promise.all(tables.map(({ name }) => __privateMethod(this, _NodeSqliteIntrospector_instances, getTableMetadata_fn3).call(this, name))); + } + async getMetadata(options) { + return { tables: await this.getTables(options) }; + } + }, _db12 = new WeakMap(), _NodeSqliteIntrospector_instances = new WeakSet(), getTableMetadata_fn3 = async function(table) { + const db = __privateGet(this, _db12); + const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); + return { + name: table, + columns: (await db.selectFrom(sql`pragma_table_info(${table})`.as("table_info")).select([ + "name", + "type", + "notnull", + "dflt_value" + ]).execute()).map((col) => ({ + name: col.name, + dataType: col.type, + isNullable: !col.notnull, + isAutoIncrementing: col.name === autoIncrementCol, + hasDefaultValue: col.dflt_value != null + })), + isView: true + }; + }, _a23); + NodeSqliteQueryCompiler = class extends DefaultQueryCompiler { + getCurrentParameterPlaceholder() { + return "?"; + } + getLeftIdentifierWrapper() { + return '"'; + } + getRightIdentifierWrapper() { + return '"'; + } + getAutoIncrement() { + return "autoincrement"; + } + }; + NodeSqliteDialect = (_a24 = class { + constructor(config4) { + __privateAdd(this, _config12); + __privateSet(this, _config12, { ...config4 }); + } + createDriver() { + return new NodeSqliteDriver(__privateGet(this, _config12)); + } + createQueryCompiler() { + return new NodeSqliteQueryCompiler(); + } + createAdapter() { + return new NodeSqliteAdapter(); + } + createIntrospector(db) { + return new NodeSqliteIntrospector(db); + } + }, _config12 = new WeakMap(), _a24); + } +}); + +// ../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/d1-sqlite-dialect-C2B7YsIT.mjs +var d1_sqlite_dialect_C2B7YsIT_exports = {}; +__export(d1_sqlite_dialect_C2B7YsIT_exports, { + D1SqliteDialect: () => D1SqliteDialect +}); +var D1SqliteAdapter, _config13, _connection6, _a25, D1SqliteDriver, _db13, _a26, D1SqliteConnection, _db14, _d1, _a27, D1SqliteIntrospector, D1SqliteQueryCompiler, _config14, _a28, D1SqliteDialect; +var init_d1_sqlite_dialect_C2B7YsIT = __esm({ + "../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/d1-sqlite-dialect-C2B7YsIT.mjs"() { + init_esm3(); + D1SqliteAdapter = class extends SqliteAdapter { + }; + D1SqliteDriver = (_a25 = class { + constructor(config4) { + __privateAdd(this, _config13); + __privateAdd(this, _connection6); + __privateSet(this, _config13, { ...config4 }); + } + async init() { + __privateSet(this, _connection6, new D1SqliteConnection(__privateGet(this, _config13).database)); + if (__privateGet(this, _config13).onCreateConnection) await __privateGet(this, _config13).onCreateConnection(__privateGet(this, _connection6)); + } + async acquireConnection() { + return __privateGet(this, _connection6); + } + async beginTransaction() { + throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead."); + } + async commitTransaction() { + throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead."); + } + async rollbackTransaction() { + throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead."); + } + async releaseConnection() { + } + async destroy() { + } + }, _config13 = new WeakMap(), _connection6 = new WeakMap(), _a25); + D1SqliteConnection = (_a26 = class { + constructor(db) { + __privateAdd(this, _db13); + __privateSet(this, _db13, db); + } + async executeQuery(compiledQuery) { + const results = await __privateGet(this, _db13).prepare(compiledQuery.sql).bind(...compiledQuery.parameters).all(); + const numAffectedRows = results.meta.changes != null ? BigInt(results.meta.changes) : void 0; + return { + insertId: results.meta.last_row_id === void 0 || results.meta.last_row_id === null ? void 0 : BigInt(results.meta.last_row_id), + rows: results?.results || [], + numAffectedRows + }; + } + async *streamQuery() { + throw new Error("D1 does not support streaming queries."); + } + }, _db13 = new WeakMap(), _a26); + D1SqliteIntrospector = (_a27 = class { + constructor(db, d1) { + __privateAdd(this, _db14); + __privateAdd(this, _d1); + __privateSet(this, _db14, db); + __privateSet(this, _d1, d1); + } + async getSchemas() { + return []; + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = __privateGet(this, _db14).selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").where("name", "not like", "_cf_%").select([ + "name", + "type", + "sql" + ]).$castTo(); + if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + const tables = await query.execute(); + if (tables.length === 0) return []; + const statements = tables.map((table) => __privateGet(this, _d1).prepare("SELECT * FROM pragma_table_info(?)").bind(table.name)); + const batchResults = await __privateGet(this, _d1).batch(statements); + return tables.map((table, index) => { + const columnInfo = batchResults[index]?.results ?? []; + let autoIncrementCol = table.sql?.split(/[(),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.filter(Boolean)?.[0]?.replace(/["`]/g, ""); + if (!autoIncrementCol) { + const pkCols = columnInfo.filter((r) => r.pk > 0); + const singlePk = pkCols.length === 1 ? pkCols[0] : void 0; + if (singlePk && singlePk.type.toLowerCase() === "integer") autoIncrementCol = singlePk.name; + } + return { + name: table.name, + isView: table.type === "view", + columns: columnInfo.map((col) => ({ + name: col.name, + dataType: col.type, + isNullable: !col.notnull, + isAutoIncrementing: col.name === autoIncrementCol, + hasDefaultValue: col.dflt_value != null + })) + }; + }); + } + async getMetadata(options) { + return { tables: await this.getTables(options) }; + } + }, _db14 = new WeakMap(), _d1 = new WeakMap(), _a27); + D1SqliteQueryCompiler = class extends SqliteQueryCompiler { + }; + D1SqliteDialect = (_a28 = class { + constructor(config4) { + __privateAdd(this, _config14); + __privateSet(this, _config14, { ...config4 }); + } + createDriver() { + return new D1SqliteDriver(__privateGet(this, _config14)); + } + createQueryCompiler() { + return new D1SqliteQueryCompiler(); + } + createAdapter() { + return new D1SqliteAdapter(); + } + createIntrospector(db) { + return new D1SqliteIntrospector(db, __privateGet(this, _config14).database); + } + }, _config14 = new WeakMap(), _a28); + } +}); + +// ../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/index.mjs +function getKyselyDatabaseType(db) { + if (!db) return null; + if ("dialect" in db) return getKyselyDatabaseType(db.dialect); + if ("createDriver" in db) { + if (db instanceof SqliteDialect) return "sqlite"; + if (db instanceof MysqlDialect) return "mysql"; + if (db instanceof PostgresDialect) return "postgres"; + if (db instanceof MssqlDialect) return "mssql"; + } + if ("aggregate" in db) return "sqlite"; + if ("getConnection" in db) return "mysql"; + if ("connect" in db) return "postgres"; + if ("fileControl" in db) return "sqlite"; + if ("open" in db && "close" in db && "prepare" in db) return "sqlite"; + if ("batch" in db && "exec" in db && "prepare" in db) return "sqlite"; + return null; +} +function insensitiveIlike(columnRef, pattern, dbType) { + return dbType === "postgres" ? sql`${sql.ref(columnRef)} ILIKE ${pattern}` : sql`LOWER(${sql.ref(columnRef)}) LIKE LOWER(${pattern})`; +} +function insensitiveIn2(columnRef, values) { + return { + lhs: sql`LOWER(${sql.ref(columnRef)})`, + values: values.map((v) => v.toLowerCase()) + }; +} +function insensitiveNotIn2(columnRef, values) { + return { + lhs: sql`LOWER(${sql.ref(columnRef)})`, + values: values.map((v) => v.toLowerCase()) + }; +} +function insensitiveEq(columnRef, value) { + return { + lhs: sql`LOWER(${sql.ref(columnRef)})`, + value: value.toLowerCase() + }; +} +function insensitiveNe(columnRef, value) { + return { + lhs: sql`LOWER(${sql.ref(columnRef)})`, + value: value.toLowerCase() + }; +} +var createKyselyAdapter, kyselyAdapter; +var init_dist2 = __esm({ + "../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/index.mjs"() { + init_esm3(); + init_adapter(); + init_string(); + createKyselyAdapter = async (config4) => { + const db = config4.database; + if (!db) return { + kysely: null, + databaseType: null, + transaction: void 0 + }; + if ("db" in db) return { + kysely: db.db, + databaseType: db.type, + transaction: db.transaction + }; + if ("dialect" in db) return { + kysely: new Kysely({ dialect: db.dialect }), + databaseType: db.type, + transaction: db.transaction + }; + let dialect = void 0; + const databaseType = getKyselyDatabaseType(db); + if ("createDriver" in db) dialect = db; + if ("aggregate" in db && !("createSession" in db)) dialect = new SqliteDialect({ database: db }); + if ("getConnection" in db) dialect = new MysqlDialect(db); + if ("connect" in db) dialect = new PostgresDialect({ pool: db }); + if ("fileControl" in db) { + const { BunSqliteDialect: BunSqliteDialect2 } = await Promise.resolve().then(() => (init_bun_sqlite_dialect_na_YwnN(), bun_sqlite_dialect_na_YwnN_exports)); + dialect = new BunSqliteDialect2({ database: db }); + } + if ("createSession" in db) { + let DatabaseSync = void 0; + try { + const nodeSqlite = "node:sqlite"; + ({ DatabaseSync } = await import( + /* @vite-ignore */ + /* webpackIgnore: true */ + nodeSqlite + )); + } catch (error49) { + if (error49 !== null && typeof error49 === "object" && "code" in error49 && error49.code !== "ERR_UNKNOWN_BUILTIN_MODULE") throw error49; + } + if (DatabaseSync && db instanceof DatabaseSync) { + const { NodeSqliteDialect: NodeSqliteDialect2 } = await Promise.resolve().then(() => (init_node_sqlite_dialect(), node_sqlite_dialect_exports)); + dialect = new NodeSqliteDialect2({ database: db }); + } + } + if ("batch" in db && "exec" in db && "prepare" in db) { + const { D1SqliteDialect: D1SqliteDialect2 } = await Promise.resolve().then(() => (init_d1_sqlite_dialect_C2B7YsIT(), d1_sqlite_dialect_C2B7YsIT_exports)); + dialect = new D1SqliteDialect2({ database: db }); + } + return { + kysely: dialect ? new Kysely({ dialect }) : null, + databaseType, + transaction: void 0 + }; + }; + kyselyAdapter = (db, config4) => { + let lazyOptions = null; + const createCustomAdapter = (db2) => { + return ({ getFieldName, schema: schema3, getDefaultFieldName, getDefaultModelName, getFieldAttributes, getModelName }) => { + const selectAllJoins = (join2) => { + const allSelects = []; + const allSelectsStr = []; + if (join2) for (const [joinModel, _] of Object.entries(join2)) { + const fields = schema3[getDefaultModelName(joinModel)]?.fields; + const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; + if (!fields) continue; + fields.id = { type: "string" }; + for (const [field, fieldAttr] of Object.entries(fields)) { + allSelects.push(sql`${sql.ref(`join_${joinModelName}`)}.${sql.ref(fieldAttr.fieldName || field)} as ${sql.ref(`_joined_${joinModelName}_${fieldAttr.fieldName || field}`)}`); + allSelectsStr.push({ + joinModel, + joinModelRef: joinModelName, + fieldName: fieldAttr.fieldName || field + }); + } + } + return { + allSelectsStr, + allSelects + }; + }; + const withReturning = async (values, builder, model, where) => { + let res; + if (config4?.type === "mysql") { + await builder.execute(); + const field = values.id ? "id" : where.length > 0 && where[0]?.field ? where[0].field : "id"; + if (!values.id && where.length === 0) { + res = await db2.selectFrom(model).selectAll().orderBy(getFieldName({ + model, + field + }), "desc").limit(1).executeTakeFirst(); + return res; + } + const value = values[field] !== void 0 ? values[field] : where[0]?.value; + res = await db2.selectFrom(model).selectAll().orderBy(getFieldName({ + model, + field + }), "desc").where(getFieldName({ + model, + field + }), value === null ? "is" : "=", value).limit(1).executeTakeFirst(); + return res; + } + if (config4?.type === "mssql") { + res = await builder.outputAll("inserted").executeTakeFirst(); + return res; + } + res = await builder.returningAll().executeTakeFirst(); + return res; + }; + function convertWhereClause(model, w) { + if (!w) return { + and: null, + or: null + }; + const conditions = { + and: [], + or: [] + }; + w.forEach((condition) => { + const { field: _field, value: _value, operator = "eq", connector = "AND", mode = "sensitive" } = condition; + const value = _value; + const field = getFieldName({ + model, + field: _field + }); + const isInsensitive = mode === "insensitive" && (typeof value === "string" || Array.isArray(value) && value.every((v) => typeof v === "string")); + const expr = (eb) => { + const f = `${model}.${field}`; + if (operator.toLowerCase() === "in") { + if (isInsensitive) { + const { lhs, values } = insensitiveIn2(f, Array.isArray(value) ? value : [value]); + return eb(lhs, "in", values); + } + return eb(f, "in", Array.isArray(value) ? value : [value]); + } + if (operator.toLowerCase() === "not_in") { + if (isInsensitive) { + const { lhs, values } = insensitiveNotIn2(f, Array.isArray(value) ? value : [value]); + return eb(lhs, "not in", values); + } + return eb(f, "not in", Array.isArray(value) ? value : [value]); + } + if (operator === "contains") { + if (isInsensitive && typeof value === "string") return insensitiveIlike(f, `%${value}%`, config4?.type); + return eb(f, "like", `%${value}%`); + } + if (operator === "starts_with") { + if (isInsensitive && typeof value === "string") return insensitiveIlike(f, `${value}%`, config4?.type); + return eb(f, "like", `${value}%`); + } + if (operator === "ends_with") { + if (isInsensitive && typeof value === "string") return insensitiveIlike(f, `%${value}`, config4?.type); + return eb(f, "like", `%${value}`); + } + if (operator === "eq") { + if (value === null) return eb(f, "is", null); + if (isInsensitive && typeof value === "string") { + const { lhs, value: v } = insensitiveEq(f, value); + return eb(lhs, "=", v); + } + return eb(f, "=", value); + } + if (operator === "ne") { + if (value === null) return eb(f, "is not", null); + if (isInsensitive && typeof value === "string") { + const { lhs, value: v } = insensitiveNe(f, value); + return eb(lhs, "<>", v); + } + return eb(f, "<>", value); + } + if (operator === "gt") return eb(f, ">", value); + if (operator === "gte") return eb(f, ">=", value); + if (operator === "lt") return eb(f, "<", value); + if (operator === "lte") return eb(f, "<=", value); + return eb(f, operator, value); + }; + if (connector === "OR") conditions.or.push(expr); + else conditions.and.push(expr); + }); + return { + and: conditions.and.length ? conditions.and : null, + or: conditions.or.length ? conditions.or : null + }; + } + function processJoinedResults(rows, joinConfig, allSelectsStr) { + if (!joinConfig || !rows.length) return rows; + const groupedByMainId = /* @__PURE__ */ new Map(); + for (const currentRow of rows) { + const mainModelFields = {}; + const joinedModelFields = {}; + for (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[getModelName(joinModel)] = {}; + for (const [key, value] of Object.entries(currentRow)) { + const keyStr = String(key); + let assigned = false; + for (const { joinModel, fieldName, joinModelRef } of allSelectsStr) if (keyStr === `_joined_${joinModelRef}_${fieldName}` || keyStr === `_Joined${capitalizeFirstLetter(joinModelRef)}${capitalizeFirstLetter(fieldName)}`) { + joinedModelFields[getModelName(joinModel)][getFieldName({ + model: joinModel, + field: fieldName + })] = value; + assigned = true; + break; + } + if (!assigned) mainModelFields[key] = value; + } + const mainId = mainModelFields.id; + if (!mainId) continue; + if (!groupedByMainId.has(mainId)) { + const entry2 = { ...mainModelFields }; + for (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry2[getModelName(joinModel)] = joinAttr.relation === "one-to-one" ? null : []; + groupedByMainId.set(mainId, entry2); + } + const entry = groupedByMainId.get(mainId); + for (const [joinModel, joinAttr] of Object.entries(joinConfig)) { + const isUnique = joinAttr.relation === "one-to-one"; + const limit = joinAttr.limit ?? 100; + const joinedObj = joinedModelFields[getModelName(joinModel)]; + const hasData = joinedObj && Object.keys(joinedObj).length > 0 && Object.values(joinedObj).some((value) => value !== null && value !== void 0); + if (isUnique) entry[getModelName(joinModel)] = hasData ? joinedObj : null; + else { + const joinModelName = getModelName(joinModel); + if (Array.isArray(entry[joinModelName]) && hasData) { + if (entry[joinModelName].length >= limit) continue; + const idFieldName = getFieldName({ + model: joinModel, + field: "id" + }); + const joinedId = joinedObj[idFieldName]; + if (joinedId) { + if (!entry[joinModelName].some((item) => item[idFieldName] === joinedId) && entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj); + } else if (entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj); + } + } + } + } + const result = Array.from(groupedByMainId.values()); + for (const entry of result) for (const [joinModel, joinAttr] of Object.entries(joinConfig)) if (joinAttr.relation !== "one-to-one") { + const joinModelName = getModelName(joinModel); + if (Array.isArray(entry[joinModelName])) { + const limit = joinAttr.limit ?? 100; + if (entry[joinModelName].length > limit) entry[joinModelName] = entry[joinModelName].slice(0, limit); + } + } + return result; + } + return { + async create({ data, model }) { + return await withReturning(data, db2.insertInto(model).values(data), model, []); + }, + async findOne({ model, where, select, join: join2 }) { + const { and, or } = convertWhereClause(model, where); + let query = db2.selectFrom((eb) => { + let b = eb.selectFrom(model); + if (and) b = b.where((eb2) => eb2.and(and.map((expr) => expr(eb2)))); + if (or) b = b.where((eb2) => eb2.or(or.map((expr) => expr(eb2)))); + if (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({ + model, + field + }))); + else b = b.selectAll(); + return b.as("primary"); + }).selectAll("primary"); + if (join2) for (const [joinModel, joinAttr] of Object.entries(join2)) { + const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; + query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join3) => join3.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`)); + } + const { allSelectsStr, allSelects } = selectAllJoins(join2); + query = query.select(allSelects); + const res = await query.execute(); + if (!res || !Array.isArray(res) || res.length === 0) return null; + const row = res[0]; + if (join2) return processJoinedResults(res, join2, allSelectsStr)[0]; + return row; + }, + async findMany({ model, where, limit, select, offset, sortBy, join: join2 }) { + const { and, or } = convertWhereClause(model, where); + let query = db2.selectFrom((eb) => { + let b = eb.selectFrom(model); + if (config4?.type === "mssql") { + if (offset !== void 0) { + if (!sortBy) b = b.orderBy(getFieldName({ + model, + field: "id" + })); + b = b.offset(offset).fetch(limit || 100); + } else if (limit !== void 0) b = b.top(limit); + } else { + if (limit !== void 0) b = b.limit(limit); + if (offset !== void 0) b = b.offset(offset); + } + if (sortBy?.field) b = b.orderBy(`${getFieldName({ + model, + field: sortBy.field + })}`, sortBy.direction); + if (and) b = b.where((eb2) => eb2.and(and.map((expr) => expr(eb2)))); + if (or) b = b.where((eb2) => eb2.or(or.map((expr) => expr(eb2)))); + if (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({ + model, + field + }))); + else b = b.selectAll(); + return b.as("primary"); + }).selectAll("primary"); + if (join2) for (const [joinModel, joinAttr] of Object.entries(join2)) { + const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; + query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join3) => join3.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`)); + } + const { allSelectsStr, allSelects } = selectAllJoins(join2); + query = query.select(allSelects); + if (sortBy?.field) query = query.orderBy(`${getFieldName({ + model, + field: sortBy.field + })}`, sortBy.direction); + const res = await query.execute(); + if (!res) return []; + if (join2) return processJoinedResults(res, join2, allSelectsStr); + return res; + }, + async update({ model, where, update: values }) { + const { and, or } = convertWhereClause(model, where); + let query = db2.updateTable(model).set(values); + if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); + if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); + return await withReturning(values, query, model, where); + }, + async updateMany({ model, where, update: values }) { + const { and, or } = convertWhereClause(model, where); + let query = db2.updateTable(model).set(values); + if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); + if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); + const res = (await query.executeTakeFirst()).numUpdatedRows; + return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res); + }, + async count({ model, where }) { + const { and, or } = convertWhereClause(model, where); + let query = db2.selectFrom(model).select(db2.fn.count("id").as("count")); + if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); + if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); + const res = await query.execute(); + if (typeof res[0].count === "number") return res[0].count; + if (typeof res[0].count === "bigint") return Number(res[0].count); + return parseInt(res[0].count); + }, + async delete({ model, where }) { + const { and, or } = convertWhereClause(model, where); + let query = db2.deleteFrom(model); + if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); + if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); + await query.execute(); + }, + async deleteMany({ model, where }) { + const { and, or } = convertWhereClause(model, where); + let query = db2.deleteFrom(model); + if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); + if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); + const res = (await query.executeTakeFirst()).numDeletedRows; + return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res); + }, + options: config4 + }; + }; + }; + let adapterOptions = null; + adapterOptions = { + config: { + adapterId: "kysely", + adapterName: "Kysely Adapter", + usePlural: config4?.usePlural, + debugLogs: config4?.debugLogs, + supportsBooleans: config4?.type === "sqlite" || config4?.type === "mssql" || config4?.type === "mysql" || !config4?.type ? false : true, + supportsDates: config4?.type === "sqlite" || config4?.type === "mssql" || !config4?.type ? false : true, + supportsJSON: config4?.type === "postgres" ? true : false, + supportsArrays: false, + supportsUUIDs: config4?.type === "postgres" ? true : false, + transaction: config4?.transaction ? (cb) => db.transaction().execute((trx) => { + return cb(createAdapterFactory({ + config: adapterOptions.config, + adapter: createCustomAdapter(trx) + })(lazyOptions)); + }) : false + }, + adapter: createCustomAdapter(db) + }; + const adapter = createAdapterFactory(adapterOptions); + return (options) => { + lazyOptions = options; + return adapter(options); + }; + }; + } +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs +var kysely_adapter_exports = {}; +__export(kysely_adapter_exports, { + createKyselyAdapter: () => createKyselyAdapter, + getKyselyDatabaseType: () => getKyselyDatabaseType, + kyselyAdapter: () => kyselyAdapter +}); +var init_kysely_adapter = __esm({ + "../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs"() { + init_dist2(); + } +}); + +// ../../packages/spec/dist/system/index.mjs +init_zod(); +var CacheStrategySchema = external_exports.enum([ + "lru", + // Least Recently Used + "lfu", + // Least Frequently Used + "fifo", + // First In First Out + "ttl", + // Time To Live only + "adaptive" + // Dynamic strategy selection +]).describe("Cache eviction strategy"); +var CacheTierSchema = external_exports.object({ + name: external_exports.string().describe("Unique cache tier name"), + type: external_exports.enum(["memory", "redis", "memcached", "cdn"]).describe("Cache backend type"), + maxSize: external_exports.number().optional().describe("Max size in MB"), + ttl: external_exports.number().default(300).describe("Default TTL in seconds"), + strategy: CacheStrategySchema.default("lru").describe("Eviction strategy"), + warmup: external_exports.boolean().default(false).describe("Pre-populate cache on startup") +}).describe("Configuration for a single cache tier in the hierarchy"); +var CacheInvalidationSchema = external_exports.object({ + trigger: external_exports.enum(["create", "update", "delete", "manual"]).describe("Event that triggers invalidation"), + scope: external_exports.enum(["key", "pattern", "tag", "all"]).describe("Invalidation scope"), + pattern: external_exports.string().optional().describe("Key pattern for pattern-based invalidation"), + tags: external_exports.array(external_exports.string()).optional().describe("Cache tags to invalidate") +}).describe("Rule defining when and how cached entries are invalidated"); +var CacheConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable application-level caching"), + tiers: external_exports.array(CacheTierSchema).describe("Ordered cache tier hierarchy"), + invalidation: external_exports.array(CacheInvalidationSchema).describe("Cache invalidation rules"), + prefetch: external_exports.boolean().default(false).describe("Enable cache prefetching"), + compression: external_exports.boolean().default(false).describe("Enable data compression in cache"), + encryption: external_exports.boolean().default(false).describe("Enable encryption for cached data") +}).describe("Top-level application cache configuration"); +var CacheConsistencySchema = external_exports.enum([ + "write_through", + "write_behind", + "write_around", + "refresh_ahead" +]).describe("Distributed cache write consistency strategy"); +var CacheAvalanchePreventionSchema = external_exports.object({ + /** TTL jitter to stagger cache expiration */ + jitterTtl: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Add random jitter to TTL values"), + maxJitterSeconds: external_exports.number().default(60).describe("Maximum jitter added to TTL in seconds") + }).optional().describe("TTL jitter to prevent simultaneous expiration"), + /** Circuit breaker to protect backend under cache pressure */ + circuitBreaker: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable circuit breaker for backend protection"), + failureThreshold: external_exports.number().default(5).describe("Failures before circuit opens"), + resetTimeout: external_exports.number().default(30).describe("Seconds before half-open state") + }).optional().describe("Circuit breaker for backend protection"), + /** Cache lock to prevent thundering herd on key miss */ + lockout: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable cache locking for key regeneration"), + lockTimeoutMs: external_exports.number().default(5e3).describe("Maximum lock wait time in milliseconds") + }).optional().describe("Lock-based stampede prevention") +}).describe("Cache avalanche/stampede prevention configuration"); +var CacheWarmupSchema = external_exports.object({ + /** Enable cache warming */ + enabled: external_exports.boolean().default(false).describe("Enable cache warmup"), + /** Warmup strategy */ + strategy: external_exports.enum(["eager", "lazy", "scheduled"]).default("lazy").describe("Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)"), + /** Cron schedule for scheduled warmup */ + schedule: external_exports.string().optional().describe("Cron expression for scheduled warmup"), + /** Keys/patterns to warm up */ + patterns: external_exports.array(external_exports.string()).optional().describe('Key patterns to warm up (e.g., "user:*", "config:*")'), + /** Maximum concurrent warmup operations */ + concurrency: external_exports.number().default(10).describe("Maximum concurrent warmup operations") +}).describe("Cache warmup strategy"); +var DistributedCacheConfigSchema = CacheConfigSchema.extend({ + /** Distributed write consistency strategy */ + consistency: CacheConsistencySchema.optional().describe("Distributed cache consistency strategy"), + /** Avalanche/stampede prevention settings */ + avalanchePrevention: CacheAvalanchePreventionSchema.optional().describe("Cache avalanche and stampede prevention"), + /** Cache warmup configuration */ + warmup: CacheWarmupSchema.optional().describe("Cache warmup strategy") +}).describe("Distributed cache configuration with consistency and avalanche prevention"); +var BackupStrategySchema = external_exports.enum([ + "full", + "incremental", + "differential" +]).describe("Backup strategy type"); +var BackupRetentionSchema = external_exports.object({ + /** Number of days to retain backups */ + days: external_exports.number().min(1).describe("Retention period in days"), + /** Minimum number of backup copies to keep regardless of age */ + minCopies: external_exports.number().min(1).default(3).describe("Minimum backup copies to retain"), + /** Maximum number of backup copies */ + maxCopies: external_exports.number().optional().describe("Maximum backup copies to store") +}).describe("Backup retention policy"); +var BackupConfigSchema = external_exports.object({ + /** Backup strategy */ + strategy: BackupStrategySchema.default("incremental").describe("Backup strategy"), + /** Cron schedule for automated backups */ + schedule: external_exports.string().optional().describe('Cron expression for backup schedule (e.g., "0 2 * * *")'), + /** Retention policy */ + retention: BackupRetentionSchema.describe("Backup retention policy"), + /** Storage destination */ + destination: external_exports.object({ + type: external_exports.enum(["s3", "gcs", "azure_blob", "local"]).describe("Storage backend type"), + bucket: external_exports.string().optional().describe("Cloud storage bucket/container name"), + path: external_exports.string().optional().describe("Storage path prefix"), + region: external_exports.string().optional().describe("Cloud storage region") + }).describe("Backup storage destination"), + /** Encryption settings */ + encryption: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable backup encryption"), + algorithm: external_exports.enum(["AES-256-GCM", "AES-256-CBC", "ChaCha20-Poly1305"]).default("AES-256-GCM").describe("Encryption algorithm"), + keyId: external_exports.string().optional().describe("KMS key ID for encryption") + }).optional().describe("Backup encryption settings"), + /** Compression settings */ + compression: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable backup compression"), + algorithm: external_exports.enum(["gzip", "zstd", "lz4", "snappy"]).default("zstd").describe("Compression algorithm") + }).optional().describe("Backup compression settings"), + /** Verify backup integrity after creation */ + verifyAfterBackup: external_exports.boolean().default(true).describe("Verify backup integrity after creation") +}).describe("Backup configuration"); +var FailoverModeSchema = external_exports.enum([ + "active_passive", + "active_active", + "pilot_light", + "warm_standby" +]).describe("Failover mode"); +var FailoverConfigSchema = external_exports.object({ + /** Failover mode */ + mode: FailoverModeSchema.default("active_passive").describe("Failover mode"), + /** Automatic failover enabled */ + autoFailover: external_exports.boolean().default(true).describe("Enable automatic failover"), + /** Health check interval in seconds */ + healthCheckInterval: external_exports.number().default(30).describe("Health check interval in seconds"), + /** Number of consecutive failures before triggering failover */ + failureThreshold: external_exports.number().default(3).describe("Consecutive failures before failover"), + /** Regions/zones for disaster recovery */ + regions: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Region identifier (e.g., "us-east-1", "eu-west-1")'), + role: external_exports.enum(["primary", "secondary", "witness"]).describe("Region role"), + endpoint: external_exports.string().optional().describe("Region endpoint URL"), + priority: external_exports.number().optional().describe("Failover priority (lower = higher priority)") + })).min(2).describe("Multi-region configuration (minimum 2 regions)"), + /** DNS failover configuration */ + dns: external_exports.object({ + ttl: external_exports.number().default(60).describe("DNS TTL in seconds for failover"), + provider: external_exports.enum(["route53", "cloudflare", "azure_dns", "custom"]).optional().describe("DNS provider for automatic failover") + }).optional().describe("DNS failover settings") +}).describe("Failover configuration"); +var RPOSchema = external_exports.object({ + /** RPO value */ + value: external_exports.number().min(0).describe("RPO value"), + /** RPO time unit */ + unit: external_exports.enum(["seconds", "minutes", "hours"]).default("minutes").describe("RPO time unit") +}).describe("Recovery Point Objective (maximum acceptable data loss)"); +var RTOSchema = external_exports.object({ + /** RTO value */ + value: external_exports.number().min(0).describe("RTO value"), + /** RTO time unit */ + unit: external_exports.enum(["seconds", "minutes", "hours"]).default("minutes").describe("RTO time unit") +}).describe("Recovery Time Objective (maximum acceptable downtime)"); +var DisasterRecoveryPlanSchema = external_exports.object({ + /** Enable disaster recovery */ + enabled: external_exports.boolean().default(false).describe("Enable disaster recovery plan"), + /** Recovery Point Objective */ + rpo: RPOSchema.describe("Recovery Point Objective"), + /** Recovery Time Objective */ + rto: RTOSchema.describe("Recovery Time Objective"), + /** Backup configuration */ + backup: BackupConfigSchema.describe("Backup configuration"), + /** Failover configuration */ + failover: FailoverConfigSchema.optional().describe("Multi-region failover configuration"), + /** Data replication settings */ + replication: external_exports.object({ + /** Replication mode */ + mode: external_exports.enum(["synchronous", "asynchronous", "semi_synchronous"]).default("asynchronous").describe("Data replication mode"), + /** Maximum replication lag allowed (seconds) */ + maxLagSeconds: external_exports.number().optional().describe("Maximum acceptable replication lag in seconds"), + /** Objects/tables to replicate (empty = all) */ + includeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to replicate (empty = all)"), + /** Objects/tables to exclude from replication */ + excludeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to exclude from replication") + }).optional().describe("Data replication settings"), + /** Automated recovery testing */ + testing: external_exports.object({ + /** Enable periodic DR testing */ + enabled: external_exports.boolean().default(false).describe("Enable automated DR testing"), + /** Cron schedule for DR tests */ + schedule: external_exports.string().optional().describe("Cron expression for DR test schedule"), + /** Notification channel for test results */ + notificationChannel: external_exports.string().optional().describe("Notification channel for DR test results") + }).optional().describe("Automated disaster recovery testing"), + /** Runbook URL for manual procedures */ + runbookUrl: external_exports.string().optional().describe("URL to disaster recovery runbook/playbook"), + /** Contact list for DR incidents */ + contacts: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Contact name"), + role: external_exports.string().describe('Contact role (e.g., "DBA", "SRE Lead")'), + email: external_exports.string().optional().describe("Contact email"), + phone: external_exports.string().optional().describe("Contact phone") + })).optional().describe("Emergency contact list for DR incidents") +}).describe("Complete disaster recovery plan configuration"); +var MessageQueueProviderSchema = external_exports.enum([ + "kafka", + "rabbitmq", + "aws-sqs", + "redis-pubsub", + "google-pubsub", + "azure-service-bus" +]).describe("Supported message queue backend provider"); +var TopicConfigSchema = external_exports.object({ + name: external_exports.string().describe("Topic name identifier"), + partitions: external_exports.number().default(1).describe("Number of partitions for parallel consumption"), + replicationFactor: external_exports.number().default(1).describe("Number of replicas for fault tolerance"), + retentionMs: external_exports.number().optional().describe("Message retention period in milliseconds"), + compressionType: external_exports.enum(["none", "gzip", "snappy", "lz4"]).default("none").describe("Message compression algorithm") +}).describe("Configuration for a message queue topic"); +var ConsumerConfigSchema = external_exports.object({ + groupId: external_exports.string().describe("Consumer group identifier"), + autoOffsetReset: external_exports.enum(["earliest", "latest"]).default("latest").describe("Where to start reading when no offset exists"), + enableAutoCommit: external_exports.boolean().default(true).describe("Automatically commit consumed offsets"), + maxPollRecords: external_exports.number().default(500).describe("Maximum records returned per poll") +}).describe("Consumer group configuration for topic consumption"); +var DeadLetterQueueSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable dead letter queue for failed messages"), + maxRetries: external_exports.number().default(3).describe("Maximum delivery attempts before sending to DLQ"), + queueName: external_exports.string().describe("Name of the dead letter queue") +}).describe("Dead letter queue configuration for unprocessable messages"); +var MessageQueueConfigSchema = external_exports.object({ + provider: MessageQueueProviderSchema.describe("Message queue backend provider"), + topics: external_exports.array(TopicConfigSchema).describe("List of topic configurations"), + consumers: external_exports.array(ConsumerConfigSchema).optional().describe("Consumer group configurations"), + deadLetterQueue: DeadLetterQueueSchema.optional().describe("Dead letter queue for failed messages"), + ssl: external_exports.boolean().default(false).describe("Enable SSL/TLS for broker connections"), + sasl: external_exports.object({ + mechanism: external_exports.enum(["plain", "scram-sha-256", "scram-sha-512"]).describe("SASL authentication mechanism"), + username: external_exports.string().describe("SASL username"), + password: external_exports.string().describe("SASL password") + }).optional().describe("SASL authentication configuration") +}).describe("Top-level message queue configuration"); +var SystemIdentifierSchema = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' +}).describe("System identifier (lowercase with underscores or dots)"); +var SnakeCaseIdentifierSchema = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { + message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' +}).describe("Snake case identifier (lowercase with underscores only)"); +external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' +}).describe("Event name (lowercase with dot notation for namespacing)"); +var StorageScopeSchema = external_exports.enum([ + "global", + // Global application-wide storage + "tenant", + // Tenant-scoped storage (multi-tenant apps) + "user", + // User-scoped storage + "session", + // Session-scoped storage (ephemeral) + "temp", + // Ephemeral, cleared on restart + "cache", + // Ephemeral, survives restarts, cleared on LRU/Expiration + "data", + // Persistent, backed up + "logs", + // Append-only, rotated + "config", + // Read-heavy, versioned + "public" + // Publicly accessible static assets +]).describe("Storage scope classification"); +var FileMetadataSchema = external_exports.object({ + path: external_exports.string().describe("File path"), + name: external_exports.string().describe("File name"), + size: external_exports.number().int().describe("File size in bytes"), + mimeType: external_exports.string().describe("MIME type"), + lastModified: external_exports.string().datetime().describe("Last modified timestamp"), + created: external_exports.string().datetime().describe("Creation timestamp"), + etag: external_exports.string().optional().describe("Entity tag") +}); +var StorageProviderSchema = external_exports.enum([ + "s3", + // Amazon S3 + "azure_blob", + // Azure Blob Storage + "gcs", + // Google Cloud Storage + "minio", + // MinIO (self-hosted S3-compatible) + "r2", + // Cloudflare R2 + "spaces", + // DigitalOcean Spaces + "wasabi", + // Wasabi Hot Cloud Storage + "backblaze", + // Backblaze B2 + "local" + // Local filesystem (development only) +]).describe("Storage provider type"); +var StorageAclSchema = external_exports.enum([ + "private", + // Owner has full control, no one else has access + "public_read", + // Owner has full control, everyone can read + "public_read_write", + // Owner has full control, everyone can read/write (not recommended) + "authenticated_read", + // Owner has full control, authenticated users can read + "bucket_owner_read", + // Object owner has full control, bucket owner can read + "bucket_owner_full_control" + // Both object and bucket owner have full control +]).describe("Storage access control level"); +var StorageClassSchema = external_exports.enum([ + "standard", + // Standard/hot storage for frequently accessed data + "intelligent", + // Intelligent tiering (auto-moves between hot/cool) + "infrequent_access", + // Infrequent access/cool storage + "glacier", + // Archive/cold storage (slower retrieval) + "deep_archive" + // Deep archive (cheapest, slowest retrieval) +]).describe("Storage class/tier for cost optimization"); +var LifecycleActionSchema = external_exports.enum([ + "transition", + // Move to different storage class + "delete", + // Delete the object + "abort" + // Abort incomplete multipart uploads +]).describe("Lifecycle policy action type"); +var ObjectMetadataSchema = external_exports.object({ + contentType: external_exports.string().describe("MIME type (e.g., image/jpeg, application/pdf)"), + contentLength: external_exports.number().min(0).describe("File size in bytes"), + contentEncoding: external_exports.string().optional().describe("Content encoding (e.g., gzip)"), + contentDisposition: external_exports.string().optional().describe("Content disposition header"), + contentLanguage: external_exports.string().optional().describe("Content language"), + cacheControl: external_exports.string().optional().describe("Cache control directives"), + etag: external_exports.string().optional().describe("Entity tag for versioning/caching"), + lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), + versionId: external_exports.string().optional().describe("Object version identifier"), + storageClass: StorageClassSchema.optional().describe("Storage class/tier"), + encryption: external_exports.object({ + algorithm: external_exports.string().describe("Encryption algorithm (e.g., AES256, aws:kms)"), + keyId: external_exports.string().optional().describe("KMS key ID if using managed encryption") + }).optional().describe("Server-side encryption configuration"), + custom: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom user-defined metadata") +}); +var PresignedUrlConfigSchema = external_exports.object({ + operation: external_exports.enum(["get", "put", "delete", "head"]).describe("Allowed operation"), + expiresIn: external_exports.number().min(1).max(604800).describe("Expiration time in seconds (max 7 days)"), + contentType: external_exports.string().optional().describe("Required content type for PUT operations"), + maxSize: external_exports.number().min(0).optional().describe("Maximum file size in bytes for PUT operations"), + responseContentType: external_exports.string().optional().describe("Override content-type for GET operations"), + responseContentDisposition: external_exports.string().optional().describe("Override content-disposition for GET operations") +}); +var MultipartUploadConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable multipart uploads"), + partSize: external_exports.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe("Part size in bytes (min 5MB, max 5GB)"), + maxParts: external_exports.number().min(1).max(1e4).default(1e4).describe("Maximum number of parts (max 10,000)"), + threshold: external_exports.number().min(0).default(100 * 1024 * 1024).describe("File size threshold to trigger multipart upload (bytes)"), + maxConcurrent: external_exports.number().min(1).max(100).default(4).describe("Maximum concurrent part uploads"), + abortIncompleteAfterDays: external_exports.number().min(1).optional().describe("Auto-abort incomplete uploads after N days") +}); +var AccessControlConfigSchema = external_exports.object({ + acl: StorageAclSchema.default("private").describe("Default access control level"), + allowedOrigins: external_exports.array(external_exports.string()).optional().describe("CORS allowed origins"), + allowedMethods: external_exports.array(external_exports.enum(["GET", "PUT", "POST", "DELETE", "HEAD"])).optional().describe("CORS allowed HTTP methods"), + allowedHeaders: external_exports.array(external_exports.string()).optional().describe("CORS allowed headers"), + exposeHeaders: external_exports.array(external_exports.string()).optional().describe("CORS exposed headers"), + maxAge: external_exports.number().min(0).optional().describe("CORS preflight cache duration in seconds"), + corsEnabled: external_exports.boolean().default(false).describe("Enable CORS configuration"), + publicAccess: external_exports.object({ + allowPublicRead: external_exports.boolean().default(false).describe("Allow public read access"), + allowPublicWrite: external_exports.boolean().default(false).describe("Allow public write access"), + allowPublicList: external_exports.boolean().default(false).describe("Allow public bucket listing") + }).optional().describe("Public access control"), + allowedIps: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses/CIDR blocks"), + blockedIps: external_exports.array(external_exports.string()).optional().describe("Blocked IP addresses/CIDR blocks") +}); +var LifecyclePolicyRuleSchema = external_exports.object({ + id: SystemIdentifierSchema.describe("Rule identifier"), + enabled: external_exports.boolean().default(true).describe("Enable this rule"), + action: LifecycleActionSchema.describe("Action to perform"), + prefix: external_exports.string().optional().describe('Object key prefix filter (e.g., "uploads/")'), + tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Object tag filters"), + daysAfterCreation: external_exports.number().min(0).optional().describe("Days after object creation"), + daysAfterModification: external_exports.number().min(0).optional().describe("Days after last modification"), + targetStorageClass: StorageClassSchema.optional().describe("Target storage class for transition action") +}).refine((data) => { + if (data.action === "transition" && !data.targetStorageClass) { + return false; + } + return true; +}, { + message: 'targetStorageClass is required when action is "transition"' +}); +var LifecyclePolicyConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable lifecycle policies"), + rules: external_exports.array(LifecyclePolicyRuleSchema).default([]).describe("Lifecycle rules") +}); +var BucketConfigSchema = external_exports.object({ + name: SystemIdentifierSchema.describe("Bucket identifier in ObjectStack (snake_case)"), + label: external_exports.string().describe("Display label"), + bucketName: external_exports.string().describe("Actual bucket/container name in storage provider"), + region: external_exports.string().optional().describe("Storage region (e.g., us-east-1, westus)"), + provider: StorageProviderSchema.describe("Storage provider"), + endpoint: external_exports.string().optional().describe("Custom endpoint URL (for S3-compatible providers)"), + pathStyle: external_exports.boolean().default(false).describe("Use path-style URLs (for S3-compatible providers)"), + versioning: external_exports.boolean().default(false).describe("Enable object versioning"), + encryption: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable server-side encryption"), + algorithm: external_exports.enum(["AES256", "aws:kms", "azure:kms", "gcp:kms"]).default("AES256").describe("Encryption algorithm"), + kmsKeyId: external_exports.string().optional().describe("KMS key ID for managed encryption") + }).optional().describe("Server-side encryption configuration"), + accessControl: AccessControlConfigSchema.optional().describe("Access control configuration"), + lifecyclePolicy: LifecyclePolicyConfigSchema.optional().describe("Lifecycle policy configuration"), + multipartConfig: MultipartUploadConfigSchema.optional().describe("Multipart upload configuration"), + tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Bucket tags for organization"), + description: external_exports.string().optional().describe("Bucket description"), + enabled: external_exports.boolean().default(true).describe("Enable this bucket") +}); +var StorageConnectionSchema = external_exports.object({ + // AWS S3 / MinIO + accessKeyId: external_exports.string().optional().describe("AWS access key ID or MinIO access key"), + secretAccessKey: external_exports.string().optional().describe("AWS secret access key or MinIO secret key"), + sessionToken: external_exports.string().optional().describe("AWS session token for temporary credentials"), + // Azure Blob Storage + accountName: external_exports.string().optional().describe("Azure storage account name"), + accountKey: external_exports.string().optional().describe("Azure storage account key"), + sasToken: external_exports.string().optional().describe("Azure SAS token"), + // Google Cloud Storage + projectId: external_exports.string().optional().describe("GCP project ID"), + credentials: external_exports.string().optional().describe("GCP service account credentials JSON"), + // Common + endpoint: external_exports.string().optional().describe("Custom endpoint URL"), + region: external_exports.string().optional().describe("Default region"), + useSSL: external_exports.boolean().default(true).describe("Use SSL/TLS for connections"), + timeout: external_exports.number().min(0).optional().describe("Connection timeout in milliseconds") +}); +var ObjectStorageConfigSchema = external_exports.object({ + name: SystemIdentifierSchema.describe("Storage configuration identifier"), + label: external_exports.string().describe("Display label"), + provider: StorageProviderSchema.describe("Primary storage provider"), + /** + * Storage scope + * Defines the lifecycle and access pattern for this storage + */ + scope: StorageScopeSchema.optional().default("global").describe("Storage scope"), + connection: StorageConnectionSchema.describe("Connection credentials"), + buckets: external_exports.array(BucketConfigSchema).default([]).describe("Configured buckets"), + defaultBucket: external_exports.string().optional().describe("Default bucket name for operations"), + /** + * Base path or location + * For local/scoped storage configurations + */ + location: external_exports.string().optional().describe("Root path (local) or base location"), + /** + * Storage quota in bytes + */ + quota: external_exports.number().int().positive().optional().describe("Max size in bytes"), + /** + * Provider-specific options + */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration options"), + enabled: external_exports.boolean().default(true).describe("Enable this storage configuration"), + description: external_exports.string().optional().describe("Configuration description") +}); +var s3StorageExample = ObjectStorageConfigSchema.parse({ + name: "aws_s3_storage", + label: "AWS S3 Production Storage", + provider: "s3", + connection: { + accessKeyId: "${AWS_ACCESS_KEY_ID}", + secretAccessKey: "${AWS_SECRET_ACCESS_KEY}", + region: "us-east-1" + }, + buckets: [ + { + name: "user_uploads", + label: "User Uploads", + bucketName: "my-app-user-uploads", + region: "us-east-1", + provider: "s3", + versioning: true, + encryption: { + enabled: true, + algorithm: "aws:kms", + kmsKeyId: "${AWS_KMS_KEY_ID}" + }, + accessControl: { + acl: "private", + corsEnabled: true, + allowedOrigins: ["https://app.example.com"], + allowedMethods: ["GET", "PUT", "POST"] + }, + lifecyclePolicy: { + enabled: true, + rules: [ + { + id: "archive_old_uploads", + enabled: true, + action: "transition", + daysAfterCreation: 90, + targetStorageClass: "glacier" + } + ] + }, + multipartConfig: { + enabled: true, + partSize: 10 * 1024 * 1024, + threshold: 100 * 1024 * 1024, + maxConcurrent: 4 + } + } + ], + defaultBucket: "user_uploads", + enabled: true +}); +var minioStorageExample = ObjectStorageConfigSchema.parse({ + name: "minio_local", + label: "MinIO Local Storage", + provider: "minio", + connection: { + accessKeyId: "minioadmin", + secretAccessKey: "minioadmin", + endpoint: "http://localhost:9000", + useSSL: false + }, + buckets: [ + { + name: "development_files", + label: "Development Files", + bucketName: "dev-files", + provider: "minio", + endpoint: "http://localhost:9000", + pathStyle: true, + accessControl: { + acl: "private" + } + } + ], + defaultBucket: "development_files", + enabled: true +}); +var azureBlobStorageExample = ObjectStorageConfigSchema.parse({ + name: "azure_blob_storage", + label: "Azure Blob Storage", + provider: "azure_blob", + connection: { + accountName: "mystorageaccount", + accountKey: "${AZURE_STORAGE_KEY}", + endpoint: "https://mystorageaccount.blob.core.windows.net" + }, + buckets: [ + { + name: "media_files", + label: "Media Files", + bucketName: "media", + provider: "azure_blob", + region: "eastus", + accessControl: { + acl: "public_read", + publicAccess: { + allowPublicRead: true, + allowPublicWrite: false, + allowPublicList: false + } + } + } + ], + defaultBucket: "media_files", + enabled: true +}); +var gcsStorageExample = ObjectStorageConfigSchema.parse({ + name: "gcs_storage", + label: "Google Cloud Storage", + provider: "gcs", + connection: { + projectId: "my-gcp-project", + credentials: "${GCP_SERVICE_ACCOUNT_JSON}" + }, + buckets: [ + { + name: "backup_storage", + label: "Backup Storage", + bucketName: "my-app-backups", + region: "us-central1", + provider: "gcs", + lifecyclePolicy: { + enabled: true, + rules: [ + { + id: "delete_old_backups", + enabled: true, + action: "delete", + daysAfterCreation: 30 + } + ] + } + } + ], + defaultBucket: "backup_storage", + enabled: true +}); +var SearchProviderSchema = external_exports.enum([ + "elasticsearch", + "algolia", + "meilisearch", + "typesense", + "opensearch" +]).describe("Supported full-text search engine provider"); +var AnalyzerConfigSchema = external_exports.object({ + type: external_exports.enum(["standard", "simple", "whitespace", "keyword", "pattern", "language"]).describe("Text analyzer type"), + language: external_exports.string().optional().describe("Language for language-specific analysis"), + stopwords: external_exports.array(external_exports.string()).optional().describe("Custom stopwords to filter during analysis"), + customFilters: external_exports.array(external_exports.string()).optional().describe("Additional token filter names to apply") +}).describe("Text analyzer configuration for index tokenization and normalization"); +var SearchIndexConfigSchema = external_exports.object({ + indexName: external_exports.string().describe("Name of the search index"), + objectName: external_exports.string().describe("Source ObjectQL object"), + fields: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Field name to index"), + type: external_exports.enum(["text", "keyword", "number", "date", "boolean", "geo"]).describe("Index field data type"), + analyzer: external_exports.string().optional().describe("Named analyzer to use for this field"), + searchable: external_exports.boolean().default(true).describe("Include field in full-text search"), + filterable: external_exports.boolean().default(false).describe("Allow filtering on this field"), + sortable: external_exports.boolean().default(false).describe("Allow sorting by this field"), + boost: external_exports.number().default(1).describe("Relevance boost factor for this field") + })).describe("Fields to include in the search index"), + replicas: external_exports.number().default(1).describe("Number of index replicas for availability"), + shards: external_exports.number().default(1).describe("Number of index shards for distribution") +}).describe("Search index definition mapping an ObjectQL object to a search engine index"); +var FacetConfigSchema = external_exports.object({ + field: external_exports.string().describe("Field name to generate facets from"), + maxValues: external_exports.number().default(10).describe("Maximum number of facet values to return"), + sort: external_exports.enum(["count", "alpha"]).default("count").describe("Facet value sort order") +}).describe("Faceted search configuration for a single field"); +var SearchConfigSchema = external_exports.object({ + provider: SearchProviderSchema.describe("Search engine backend provider"), + indexes: external_exports.array(SearchIndexConfigSchema).describe("Search index definitions"), + analyzers: external_exports.record(external_exports.string(), AnalyzerConfigSchema).optional().describe("Named text analyzer configurations"), + facets: external_exports.array(FacetConfigSchema).optional().describe("Faceted search configurations"), + typoTolerance: external_exports.boolean().default(true).describe("Enable typo-tolerant search"), + synonyms: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional().describe("Synonym mappings for search expansion"), + ranking: external_exports.array(external_exports.enum(["typo", "geo", "words", "filters", "proximity", "attribute", "exact", "custom"])).optional().describe("Custom ranking rule order") +}).describe("Top-level full-text search engine configuration"); +var HttpMethod = external_exports.enum([ + "GET", + "POST", + "PUT", + "DELETE", + "PATCH", + "HEAD", + "OPTIONS" +]); +var HttpMethodSchema = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); +external_exports.object({ + url: external_exports.string().describe("API endpoint URL"), + method: HttpMethodSchema.optional().default("GET").describe("HTTP method"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), + body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") +}); +var CorsConfigSchema = external_exports.object({ + /** + * Enable CORS + */ + enabled: external_exports.boolean().default(true).describe("Enable CORS"), + /** + * Allowed origins (* for all) + */ + origins: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.string()) + ]).default("*").describe("Allowed origins (* for all)"), + /** + * Allowed HTTP methods + */ + methods: external_exports.array(HttpMethod).optional().describe("Allowed HTTP methods"), + /** + * Allow credentials (cookies, authorization headers) + */ + credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), + /** + * Preflight cache duration in seconds + */ + maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") +}); +var RateLimitConfigSchema = external_exports.object({ + /** + * Enable rate limiting + */ + enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), + /** + * Time window in milliseconds + */ + windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), + /** + * Max requests per window + */ + maxRequests: external_exports.number().int().default(100).describe("Max requests per window") +}); +var StaticMountSchema = external_exports.object({ + /** + * URL path to serve from + */ + path: external_exports.string().describe("URL path to serve from"), + /** + * Physical directory to serve + */ + directory: external_exports.string().describe("Physical directory to serve"), + /** + * Cache-Control header value + */ + cacheControl: external_exports.string().optional().describe("Cache-Control header value") +}); +var HttpServerConfigSchema = external_exports.object({ + /** + * Server port number + */ + port: external_exports.number().int().min(1).max(65535).default(3e3).describe("Port number to listen on"), + /** + * Server host address + */ + host: external_exports.string().default("0.0.0.0").describe("Host address to bind to"), + /** + * CORS configuration + */ + cors: CorsConfigSchema.optional().describe("CORS configuration"), + /** + * Request handling options + */ + requestTimeout: external_exports.number().int().default(3e4).describe("Request timeout in milliseconds"), + bodyLimit: external_exports.string().default("10mb").describe("Maximum request body size"), + /** + * Compression settings + */ + compression: external_exports.boolean().default(true).describe("Enable response compression"), + /** + * Security headers + */ + security: external_exports.object({ + helmet: external_exports.boolean().default(true).describe("Enable security headers via helmet"), + rateLimit: RateLimitConfigSchema.optional().describe("Global rate limiting configuration") + }).optional().describe("Security configuration"), + /** + * Static file serving + */ + static: external_exports.array(StaticMountSchema).optional().describe("Static file serving configuration"), + /** + * Trust proxy settings + */ + trustProxy: external_exports.boolean().default(false).describe("Trust X-Forwarded-* headers") +}); +var RouteHandlerMetadataSchema = external_exports.object({ + /** + * HTTP method + */ + method: HttpMethod.describe("HTTP method"), + /** + * URL path pattern (supports parameters like /api/users/:id) + */ + path: external_exports.string().describe("URL path pattern"), + /** + * Handler function name or identifier + */ + handler: external_exports.string().describe("Handler identifier or name"), + /** + * Route metadata + */ + metadata: external_exports.object({ + summary: external_exports.string().optional().describe("Route summary for documentation"), + description: external_exports.string().optional().describe("Route description"), + tags: external_exports.array(external_exports.string()).optional().describe("Tags for grouping"), + operationId: external_exports.string().optional().describe("Unique operation identifier") + }).optional(), + /** + * Security requirements + */ + security: external_exports.object({ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + rateLimit: external_exports.string().optional().describe("Rate limit policy override") + }).optional() +}); +var MiddlewareType = external_exports.enum([ + "authentication", + // Authentication middleware + "authorization", + // Authorization/permission checks + "logging", + // Request/response logging + "validation", + // Input validation + "transformation", + // Request/response transformation + "error", + // Error handling + "custom" + // Custom middleware +]); +var MiddlewareConfigSchema = external_exports.object({ + /** + * Middleware identifier + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Middleware name (snake_case)"), + /** + * Middleware type + */ + type: MiddlewareType.describe("Middleware type"), + /** + * Enable/disable middleware + */ + enabled: external_exports.boolean().default(true).describe("Whether middleware is enabled"), + /** + * Execution order (lower numbers execute first) + */ + order: external_exports.number().int().default(100).describe("Execution order priority"), + /** + * Middleware-specific configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Middleware configuration object"), + /** + * Path patterns to apply middleware to + */ + paths: external_exports.object({ + include: external_exports.array(external_exports.string()).optional().describe("Include path patterns (glob)"), + exclude: external_exports.array(external_exports.string()).optional().describe("Exclude path patterns (glob)") + }).optional().describe("Path filtering") +}); +var ServerEventType = external_exports.enum([ + "starting", + // Server is starting + "started", + // Server has started and is listening + "stopping", + // Server is stopping + "stopped", + // Server has stopped + "request", + // Request received + "response", + // Response sent + "error" + // Error occurred +]); +var ServerEventSchema = external_exports.object({ + /** + * Event type + */ + type: ServerEventType.describe("Event type"), + /** + * Timestamp + */ + timestamp: external_exports.string().datetime().describe("Event timestamp (ISO 8601)"), + /** + * Event payload + */ + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific data") +}); +var ServerCapabilitiesSchema = external_exports.object({ + /** + * Supported HTTP versions + */ + httpVersions: external_exports.array(external_exports.enum(["1.0", "1.1", "2.0", "3.0"])).default(["1.1"]).describe("Supported HTTP versions"), + /** + * WebSocket support + */ + websocket: external_exports.boolean().default(false).describe("WebSocket support"), + /** + * Server-Sent Events support + */ + sse: external_exports.boolean().default(false).describe("Server-Sent Events support"), + /** + * HTTP/2 Server Push + */ + serverPush: external_exports.boolean().default(false).describe("HTTP/2 Server Push support"), + /** + * Streaming support + */ + streaming: external_exports.boolean().default(true).describe("Response streaming support"), + /** + * Middleware support + */ + middleware: external_exports.boolean().default(true).describe("Middleware chain support"), + /** + * Route parameterization + */ + routeParams: external_exports.boolean().default(true).describe("URL parameter support (/users/:id)"), + /** + * Built-in compression + */ + compression: external_exports.boolean().default(true).describe("Built-in compression support") +}); +var ServerStatusSchema = external_exports.object({ + /** + * Server state + */ + state: external_exports.enum(["stopped", "starting", "running", "stopping", "error"]).describe("Current server state"), + /** + * Uptime in milliseconds + */ + uptime: external_exports.number().int().optional().describe("Server uptime in milliseconds"), + /** + * Server information + */ + server: external_exports.object({ + port: external_exports.number().int().describe("Listening port"), + host: external_exports.string().describe("Bound host"), + url: external_exports.string().optional().describe("Full server URL") + }).optional(), + /** + * Connection metrics + */ + connections: external_exports.object({ + active: external_exports.number().int().describe("Active connections"), + total: external_exports.number().int().describe("Total connections handled") + }).optional(), + /** + * Request metrics + */ + requests: external_exports.object({ + total: external_exports.number().int().describe("Total requests processed"), + success: external_exports.number().int().describe("Successful requests"), + errors: external_exports.number().int().describe("Failed requests") + }).optional() +}); +var HttpServerConfig = Object.assign(HttpServerConfigSchema, { + create: (config4) => config4 +}); +var MiddlewareConfig = Object.assign(MiddlewareConfigSchema, { + create: (config4) => config4 +}); +var AuditEventType = external_exports.enum([ + // Data Operations (CRUD) + "data.create", + // Record creation + "data.read", + // Record retrieval/viewing + "data.update", + // Record modification + "data.delete", + // Record deletion + "data.export", + // Data export operations + "data.import", + // Data import operations + "data.bulk_update", + // Bulk update operations + "data.bulk_delete", + // Bulk delete operations + // Authentication Events + "auth.login", + // Successful login + "auth.login_failed", + // Failed login attempt + "auth.logout", + // User logout + "auth.session_created", + // New session created + "auth.session_expired", + // Session expiration + "auth.password_reset", + // Password reset initiated + "auth.password_changed", + // Password successfully changed + "auth.email_verified", + // Email verification completed + "auth.mfa_enabled", + // Multi-factor auth enabled + "auth.mfa_disabled", + // Multi-factor auth disabled + "auth.account_locked", + // Account locked (too many failures) + "auth.account_unlocked", + // Account unlocked + // Authorization Events + "authz.permission_granted", + // Permission granted to user + "authz.permission_revoked", + // Permission revoked from user + "authz.role_assigned", + // Role assigned to user + "authz.role_removed", + // Role removed from user + "authz.role_created", + // New role created + "authz.role_updated", + // Role permissions modified + "authz.role_deleted", + // Role deleted + "authz.policy_created", + // Security policy created + "authz.policy_updated", + // Security policy updated + "authz.policy_deleted", + // Security policy deleted + // System Events + "system.config_changed", + // System configuration modified + "system.plugin_installed", + // Plugin installed + "system.plugin_uninstalled", + // Plugin uninstalled + "system.backup_created", + // Backup created + "system.backup_restored", + // Backup restored + "system.integration_added", + // External integration added + "system.integration_removed", + // External integration removed + // Security Events + "security.access_denied", + // Access denied (authorization failure) + "security.suspicious_activity", + // Suspicious activity detected + "security.data_breach", + // Potential data breach detected + "security.api_key_created", + // API key created + "security.api_key_revoked" + // API key revoked +]); +var AuditEventSeverity = external_exports.enum([ + "debug", + // Diagnostic information + "info", + // Informational events (normal operations) + "notice", + // Normal but significant events + "warning", + // Warning conditions + "error", + // Error conditions + "critical", + // Critical conditions requiring immediate attention + "alert", + // Action must be taken immediately + "emergency" + // System is unusable +]); +var AuditEventActorSchema = external_exports.object({ + /** + * Actor type (user, system, service, api_client, etc.) + */ + type: external_exports.enum(["user", "system", "service", "api_client", "integration"]).describe("Actor type"), + /** + * Unique identifier for the actor + */ + id: external_exports.string().describe("Actor identifier"), + /** + * Display name of the actor + */ + name: external_exports.string().optional().describe("Actor display name"), + /** + * Email address (for user actors) + */ + email: external_exports.string().email().optional().describe("Actor email address"), + /** + * IP address of the actor + */ + ipAddress: external_exports.string().optional().describe("Actor IP address"), + /** + * User agent string (for web/API requests) + */ + userAgent: external_exports.string().optional().describe("User agent string") +}); +var AuditEventTargetSchema = external_exports.object({ + /** + * Target type (e.g., 'object', 'record', 'user', 'role', 'config') + */ + type: external_exports.string().describe("Target type"), + /** + * Unique identifier for the target + */ + id: external_exports.string().describe("Target identifier"), + /** + * Display name of the target + */ + name: external_exports.string().optional().describe("Target display name"), + /** + * Additional metadata about the target + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Target metadata") +}); +var AuditEventChangeSchema = external_exports.object({ + /** + * Field/property that changed + */ + field: external_exports.string().describe("Changed field name"), + /** + * Value before the change + */ + oldValue: external_exports.unknown().optional().describe("Previous value"), + /** + * Value after the change + */ + newValue: external_exports.unknown().optional().describe("New value") +}); +var AuditEventSchema = external_exports.object({ + /** + * Unique identifier for this audit event + */ + id: external_exports.string().describe("Audit event ID"), + /** + * Type of event being audited + */ + eventType: AuditEventType.describe("Event type"), + /** + * Severity level of the event + */ + severity: AuditEventSeverity.default("info").describe("Event severity"), + /** + * Timestamp when the event occurred (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("Event timestamp"), + /** + * Who/what performed the action + */ + actor: AuditEventActorSchema.describe("Event actor"), + /** + * What was acted upon + */ + target: AuditEventTargetSchema.optional().describe("Event target"), + /** + * Human-readable description of the action + */ + description: external_exports.string().describe("Event description"), + /** + * Detailed changes (for update operations) + */ + changes: external_exports.array(AuditEventChangeSchema).optional().describe("List of changes"), + /** + * Result of the action (success, failure, partial) + */ + result: external_exports.enum(["success", "failure", "partial"]).default("success").describe("Action result"), + /** + * Error message (if result is failure) + */ + errorMessage: external_exports.string().optional().describe("Error message"), + /** + * Tenant identifier (for multi-tenant systems) + */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** + * Request/trace ID for correlation + */ + requestId: external_exports.string().optional().describe("Request ID for tracing"), + /** + * Additional context and metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata"), + /** + * Geographic location (if available) + */ + location: external_exports.object({ + country: external_exports.string().optional(), + region: external_exports.string().optional(), + city: external_exports.string().optional() + }).optional().describe("Geographic location") +}); +var AuditRetentionPolicySchema = external_exports.object({ + /** + * Retention period in days + * Default: 180 days (GDPR 6-month requirement) + */ + retentionDays: external_exports.number().int().min(1).default(180).describe("Retention period in days"), + /** + * Whether to archive logs after retention period + * If true, logs are moved to cold storage; if false, they are deleted + */ + archiveAfterRetention: external_exports.boolean().default(true).describe("Archive logs after retention period"), + /** + * Archive storage configuration + */ + archiveStorage: external_exports.object({ + type: external_exports.enum(["s3", "gcs", "azure_blob", "filesystem"]).describe("Archive storage type"), + endpoint: external_exports.string().optional().describe("Storage endpoint URL"), + bucket: external_exports.string().optional().describe("Storage bucket/container name"), + path: external_exports.string().optional().describe("Storage path prefix"), + credentials: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage credentials") + }).optional().describe("Archive storage configuration"), + /** + * Event types that have different retention periods + * Overrides the default retentionDays for specific event types + */ + customRetention: external_exports.record(external_exports.string(), external_exports.number().int().positive()).optional().describe("Custom retention by event type"), + /** + * Minimum retention period for compliance + * Prevents accidental deletion below compliance requirements + */ + minimumRetentionDays: external_exports.number().int().positive().optional().describe("Minimum retention for compliance") +}); +var SuspiciousActivityRuleSchema = external_exports.object({ + /** + * Unique identifier for the rule + */ + id: external_exports.string().describe("Rule identifier"), + /** + * Rule name + */ + name: external_exports.string().describe("Rule name"), + /** + * Rule description + */ + description: external_exports.string().optional().describe("Rule description"), + /** + * Whether the rule is enabled + */ + enabled: external_exports.boolean().default(true).describe("Rule enabled status"), + /** + * Event types to monitor + */ + eventTypes: external_exports.array(AuditEventType).describe("Event types to monitor"), + /** + * Detection condition + */ + condition: external_exports.object({ + /** + * Number of events that trigger the rule + */ + threshold: external_exports.number().int().positive().describe("Event threshold"), + /** + * Time window in seconds + */ + windowSeconds: external_exports.number().int().positive().describe("Time window in seconds"), + /** + * Grouping criteria (e.g., by actor.id, by ipAddress) + */ + groupBy: external_exports.array(external_exports.string()).optional().describe("Grouping criteria"), + /** + * Additional filters + */ + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional filters") + }).describe("Detection condition"), + /** + * Actions to take when rule is triggered + */ + actions: external_exports.array(external_exports.enum([ + "alert", + // Send alert notification + "lock_account", + // Lock the user account + "block_ip", + // Block the IP address + "require_mfa", + // Require multi-factor authentication + "log_critical", + // Log as critical event + "webhook" + // Call webhook + ])).describe("Actions to take"), + /** + * Severity level for triggered alerts + */ + alertSeverity: AuditEventSeverity.default("warning").describe("Alert severity"), + /** + * Notification configuration + */ + notifications: external_exports.object({ + /** + * Email addresses to notify + */ + email: external_exports.array(external_exports.string().email()).optional().describe("Email recipients"), + /** + * Slack webhook URL + */ + slack: external_exports.string().url().optional().describe("Slack webhook URL"), + /** + * Custom webhook URL + */ + webhook: external_exports.string().url().optional().describe("Custom webhook URL") + }).optional().describe("Notification configuration") +}); +var AuditStorageConfigSchema = external_exports.object({ + /** + * Storage backend type + */ + type: external_exports.enum([ + "database", + // Store in database (PostgreSQL, MySQL, etc.) + "elasticsearch", + // Store in Elasticsearch + "mongodb", + // Store in MongoDB + "clickhouse", + // Store in ClickHouse (for analytics) + "s3", + // Store in S3-compatible storage + "gcs", + // Store in Google Cloud Storage + "azure_blob", + // Store in Azure Blob Storage + "custom" + // Custom storage implementation + ]).describe("Storage backend type"), + /** + * Connection string or configuration + */ + connectionString: external_exports.string().optional().describe("Connection string"), + /** + * Storage configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage-specific configuration"), + /** + * Whether to enable buffering/batching + */ + bufferEnabled: external_exports.boolean().default(true).describe("Enable buffering"), + /** + * Buffer size (number of events before flush) + */ + bufferSize: external_exports.number().int().positive().default(100).describe("Buffer size"), + /** + * Buffer flush interval in seconds + */ + flushIntervalSeconds: external_exports.number().int().positive().default(5).describe("Flush interval in seconds"), + /** + * Whether to compress stored data + */ + compression: external_exports.boolean().default(true).describe("Enable compression") +}); +var AuditEventFilterSchema = external_exports.object({ + /** + * Filter by event types + */ + eventTypes: external_exports.array(AuditEventType).optional().describe("Event types to include"), + /** + * Filter by severity levels + */ + severities: external_exports.array(AuditEventSeverity).optional().describe("Severity levels to include"), + /** + * Filter by actor ID + */ + actorId: external_exports.string().optional().describe("Actor identifier"), + /** + * Filter by tenant ID + */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** + * Filter by time range + */ + timeRange: external_exports.object({ + from: external_exports.string().datetime().describe("Start time"), + to: external_exports.string().datetime().describe("End time") + }).optional().describe("Time range filter"), + /** + * Filter by result status + */ + result: external_exports.enum(["success", "failure", "partial"]).optional().describe("Result status"), + /** + * Search query (full-text search) + */ + searchQuery: external_exports.string().optional().describe("Search query"), + /** + * Custom filters + */ + customFilters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom filters") +}); +var AuditConfigSchema = external_exports.object({ + /** + * Unique identifier for this audit configuration + * Must be in snake_case following ObjectStack conventions + * Maximum length: 64 characters + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), + /** + * Human-readable label + */ + label: external_exports.string().describe("Display label"), + /** + * Whether audit logging is enabled + */ + enabled: external_exports.boolean().default(true).describe("Enable audit logging"), + /** + * Event types to audit + * If not specified, all event types are audited + */ + eventTypes: external_exports.array(AuditEventType).optional().describe("Event types to audit"), + /** + * Event types to exclude from auditing + */ + excludeEventTypes: external_exports.array(AuditEventType).optional().describe("Event types to exclude"), + /** + * Minimum severity level to log + * Events below this level are not logged + */ + minimumSeverity: AuditEventSeverity.default("info").describe("Minimum severity level"), + /** + * Storage configuration + */ + storage: AuditStorageConfigSchema.describe("Storage configuration"), + /** + * Retention policy + */ + retentionPolicy: AuditRetentionPolicySchema.optional().describe("Retention policy"), + /** + * Suspicious activity detection rules + */ + suspiciousActivityRules: external_exports.array(SuspiciousActivityRuleSchema).default([]).describe("Suspicious activity rules"), + /** + * Whether to include sensitive data in audit logs + * If false, sensitive fields are redacted/masked + */ + includeSensitiveData: external_exports.boolean().default(false).describe("Include sensitive data"), + /** + * Fields to redact from audit logs + */ + redactFields: external_exports.array(external_exports.string()).default([ + "password", + "passwordHash", + "token", + "apiKey", + "secret", + "creditCard", + "ssn" + ]).describe("Fields to redact"), + /** + * Whether to log successful read operations + * Can be disabled to reduce log volume + */ + logReads: external_exports.boolean().default(false).describe("Log read operations"), + /** + * Sampling rate for read operations (0.0 to 1.0) + * Only applies if logReads is true + */ + readSamplingRate: external_exports.number().min(0).max(1).default(0.1).describe("Read sampling rate"), + /** + * Whether to log system/internal operations + */ + logSystemEvents: external_exports.boolean().default(true).describe("Log system events"), + /** + * Custom audit event handlers + * Note: Function handlers are for runtime configuration only and will not be serialized to JSON Schema + */ + customHandlers: external_exports.array(external_exports.object({ + eventType: AuditEventType.describe("Event type to handle"), + handlerId: external_exports.string().describe("Unique identifier for the handler") + })).optional().describe("Custom event handler references"), + /** + * Compliance mode configuration + */ + compliance: external_exports.object({ + /** + * Compliance standards to enforce + */ + standards: external_exports.array(external_exports.enum([ + "sox", + // Sarbanes-Oxley Act + "hipaa", + // Health Insurance Portability and Accountability Act + "gdpr", + // General Data Protection Regulation + "pci_dss", + // Payment Card Industry Data Security Standard + "iso_27001", + // ISO/IEC 27001 + "fedramp" + // Federal Risk and Authorization Management Program + ])).optional().describe("Compliance standards"), + /** + * Whether to enforce immutable audit logs + */ + immutableLogs: external_exports.boolean().default(true).describe("Enforce immutable logs"), + /** + * Whether to require cryptographic signing + */ + requireSigning: external_exports.boolean().default(false).describe("Require log signing"), + /** + * Signing key configuration + */ + signingKey: external_exports.string().optional().describe("Signing key") + }).optional().describe("Compliance configuration") +}); +var LogLevel = external_exports.enum([ + "debug", + "info", + "warn", + "error", + "fatal", + "silent" +]).describe("Log severity level"); +var LogFormat = external_exports.enum([ + "json", + // Structured JSON for machine parsing + "text", + // Simple text format + "pretty" + // Colored human-readable output for CLI/console +]).describe("Log output format"); +var LoggerConfigSchema = external_exports.object({ + /** + * Logger name + */ + name: external_exports.string().optional().describe("Logger name identifier"), + /** + * Minimum level to log + */ + level: LogLevel.optional().default("info"), + /** + * Output format + */ + format: LogFormat.optional().default("json"), + /** + * Redact sensitive keys + */ + redact: external_exports.array(external_exports.string()).optional().default(["password", "token", "secret", "key"]).describe("Keys to redact from log context"), + /** + * Enable source location (file/line) + */ + sourceLocation: external_exports.boolean().optional().default(false).describe("Include file and line number"), + /** + * Log to file (optional) + */ + file: external_exports.string().optional().describe("Path to log file"), + /** + * Log rotation config (if file is set) + */ + rotation: external_exports.object({ + maxSize: external_exports.string().optional().default("10m"), + maxFiles: external_exports.number().optional().default(5) + }).optional() +}); +var LogEntrySchema = external_exports.object({ + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), + level: LogLevel, + message: external_exports.string().describe("Log message"), + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Structured context data"), + error: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Error object if present"), + /** Tracing */ + traceId: external_exports.string().optional().describe("Distributed trace ID"), + spanId: external_exports.string().optional().describe("Span ID"), + /** Source */ + service: external_exports.string().optional().describe("Service name"), + component: external_exports.string().optional().describe("Component name (e.g. plugin id)") +}); +var ExtendedLogLevel = external_exports.enum([ + "trace", + // Very detailed debugging information + "debug", + // Debugging information + "info", + // Informational messages + "warn", + // Warning messages + "error", + // Error messages + "fatal" + // Fatal errors causing shutdown +]).describe("Extended log severity level"); +var LogDestinationType = external_exports.enum([ + "console", + // Standard output/error + "file", + // File system + "syslog", + // System logger + "elasticsearch", + // Elasticsearch + "cloudwatch", + // AWS CloudWatch + "stackdriver", + // Google Cloud Logging + "azure_monitor", + // Azure Monitor + "datadog", + // Datadog + "splunk", + // Splunk + "loki", + // Grafana Loki + "http", + // HTTP endpoint + "kafka", + // Apache Kafka + "redis", + // Redis streams + "custom" + // Custom implementation +]).describe("Log destination type"); +var ConsoleDestinationConfigSchema = external_exports.object({ + /** + * Output stream + */ + stream: external_exports.enum(["stdout", "stderr"]).optional().default("stdout"), + /** + * Enable colored output + */ + colors: external_exports.boolean().optional().default(true), + /** + * Pretty print JSON + */ + prettyPrint: external_exports.boolean().optional().default(false) +}).describe("Console destination configuration"); +var FileDestinationConfigSchema = external_exports.object({ + /** + * File path + */ + path: external_exports.string().describe("Log file path"), + /** + * Enable log rotation + */ + rotation: external_exports.object({ + /** + * Maximum file size before rotation (e.g., '10m', '100k', '1g') + */ + maxSize: external_exports.string().optional().default("10m"), + /** + * Maximum number of files to keep + */ + maxFiles: external_exports.number().int().positive().optional().default(5), + /** + * Compress rotated files + */ + compress: external_exports.boolean().optional().default(true), + /** + * Rotation interval (e.g., 'daily', 'weekly') + */ + interval: external_exports.enum(["hourly", "daily", "weekly", "monthly"]).optional() + }).optional(), + /** + * File encoding + */ + encoding: external_exports.string().optional().default("utf8"), + /** + * Append to existing file + */ + append: external_exports.boolean().optional().default(true) +}).describe("File destination configuration"); +var HttpDestinationConfigSchema = external_exports.object({ + /** + * HTTP endpoint URL + */ + url: external_exports.string().url().describe("HTTP endpoint URL"), + /** + * HTTP method + */ + method: external_exports.enum(["POST", "PUT"]).optional().default("POST"), + /** + * Headers to include + */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional(), + /** + * Authentication + */ + auth: external_exports.object({ + type: external_exports.enum(["basic", "bearer", "api_key"]).describe("Auth type"), + username: external_exports.string().optional(), + password: external_exports.string().optional(), + token: external_exports.string().optional(), + apiKey: external_exports.string().optional(), + apiKeyHeader: external_exports.string().optional().default("X-API-Key") + }).optional(), + /** + * Batch configuration + */ + batch: external_exports.object({ + /** + * Maximum batch size + */ + maxSize: external_exports.number().int().positive().optional().default(100), + /** + * Flush interval in milliseconds + */ + flushInterval: external_exports.number().int().positive().optional().default(5e3) + }).optional(), + /** + * Retry configuration + */ + retry: external_exports.object({ + /** + * Maximum retry attempts + */ + maxAttempts: external_exports.number().int().positive().optional().default(3), + /** + * Initial retry delay in milliseconds + */ + initialDelay: external_exports.number().int().positive().optional().default(1e3), + /** + * Backoff multiplier + */ + backoffMultiplier: external_exports.number().positive().optional().default(2) + }).optional(), + /** + * Timeout in milliseconds + */ + timeout: external_exports.number().int().positive().optional().default(3e4) +}).describe("HTTP destination configuration"); +var ExternalServiceDestinationConfigSchema = external_exports.object({ + /** + * Service-specific endpoint + */ + endpoint: external_exports.string().url().optional(), + /** + * Region (for cloud services) + */ + region: external_exports.string().optional(), + /** + * Credentials + */ + credentials: external_exports.object({ + accessKeyId: external_exports.string().optional(), + secretAccessKey: external_exports.string().optional(), + apiKey: external_exports.string().optional(), + projectId: external_exports.string().optional() + }).optional(), + /** + * Log group/stream/index name + */ + logGroup: external_exports.string().optional(), + logStream: external_exports.string().optional(), + index: external_exports.string().optional(), + /** + * Service-specific configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}).describe("External service destination configuration"); +var LogDestinationSchema = external_exports.object({ + /** + * Destination name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Destination name (snake_case)"), + /** + * Destination type + */ + type: LogDestinationType.describe("Destination type"), + /** + * Minimum log level for this destination + */ + level: ExtendedLogLevel.optional().default("info"), + /** + * Enabled flag + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Console configuration + */ + console: ConsoleDestinationConfigSchema.optional(), + /** + * File configuration + */ + file: FileDestinationConfigSchema.optional(), + /** + * HTTP configuration + */ + http: HttpDestinationConfigSchema.optional(), + /** + * External service configuration + */ + externalService: ExternalServiceDestinationConfigSchema.optional(), + /** + * Format for this destination + */ + format: external_exports.enum(["json", "text", "pretty"]).optional().default("json"), + /** + * Filter function reference (runtime only) + */ + filterId: external_exports.string().optional().describe("Filter function identifier") +}).describe("Log destination configuration"); +var LogEnrichmentConfigSchema = external_exports.object({ + /** + * Static fields to add to all logs + */ + staticFields: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Static fields added to every log"), + /** + * Dynamic field enrichers (runtime only) + * References to functions that add dynamic context + */ + dynamicEnrichers: external_exports.array(external_exports.string()).optional().describe("Dynamic enricher function IDs"), + /** + * Add hostname + */ + addHostname: external_exports.boolean().optional().default(true), + /** + * Add process ID + */ + addProcessId: external_exports.boolean().optional().default(true), + /** + * Add environment info + */ + addEnvironment: external_exports.boolean().optional().default(true), + /** + * Add timestamp in additional formats + */ + addTimestampFormats: external_exports.object({ + unix: external_exports.boolean().optional().default(false), + iso: external_exports.boolean().optional().default(true) + }).optional(), + /** + * Add caller information (file, line, function) + */ + addCaller: external_exports.boolean().optional().default(false), + /** + * Add correlation IDs + */ + addCorrelationIds: external_exports.boolean().optional().default(true) +}).describe("Log enrichment configuration"); +var StructuredLogEntrySchema = external_exports.object({ + /** + * Timestamp (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), + /** + * Log level + */ + level: ExtendedLogLevel.describe("Log severity level"), + /** + * Log message + */ + message: external_exports.string().describe("Log message"), + /** + * Structured context data + */ + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Structured context"), + /** + * Error information + */ + error: external_exports.object({ + name: external_exports.string().optional(), + message: external_exports.string().optional(), + stack: external_exports.string().optional(), + code: external_exports.string().optional(), + details: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional().describe("Error details"), + /** + * Trace context + */ + trace: external_exports.object({ + traceId: external_exports.string().describe("Trace ID"), + spanId: external_exports.string().describe("Span ID"), + parentSpanId: external_exports.string().optional().describe("Parent span ID"), + traceFlags: external_exports.number().int().optional().describe("Trace flags") + }).optional().describe("Distributed tracing context"), + /** + * Source information + */ + source: external_exports.object({ + service: external_exports.string().optional().describe("Service name"), + component: external_exports.string().optional().describe("Component name"), + file: external_exports.string().optional().describe("Source file"), + line: external_exports.number().int().optional().describe("Line number"), + function: external_exports.string().optional().describe("Function name") + }).optional().describe("Source information"), + /** + * Host information + */ + host: external_exports.object({ + hostname: external_exports.string().optional(), + pid: external_exports.number().int().optional(), + ip: external_exports.string().optional() + }).optional().describe("Host information"), + /** + * Environment + */ + environment: external_exports.string().optional().describe("Environment (e.g., production, staging)"), + /** + * User information + */ + user: external_exports.object({ + id: external_exports.string().optional(), + username: external_exports.string().optional(), + email: external_exports.string().optional() + }).optional().describe("User context"), + /** + * Request information + */ + request: external_exports.object({ + id: external_exports.string().optional(), + method: external_exports.string().optional(), + path: external_exports.string().optional(), + userAgent: external_exports.string().optional(), + ip: external_exports.string().optional() + }).optional().describe("Request context"), + /** + * Custom labels/tags + */ + labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom labels"), + /** + * Additional metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata") +}).describe("Structured log entry"); +var LoggingConfigSchema = external_exports.object({ + /** + * Configuration name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Enable logging + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Global minimum log level + */ + level: ExtendedLogLevel.optional().default("info"), + /** + * Default logger configuration + * Basic logger config for the kernel + */ + default: LoggerConfigSchema.optional().describe("Default logger configuration"), + /** + * Named logger configurations + * Map of logger name to logger config for different components/modules + */ + loggers: external_exports.record(external_exports.string(), LoggerConfigSchema).optional().describe("Named logger configurations"), + /** + * Log destinations + */ + destinations: external_exports.array(LogDestinationSchema).describe("Log destinations"), + /** + * Log enrichment configuration + */ + enrichment: LogEnrichmentConfigSchema.optional(), + /** + * Fields to redact from logs + */ + redact: external_exports.array(external_exports.string()).optional().default([ + "password", + "passwordHash", + "token", + "apiKey", + "secret", + "creditCard", + "ssn", + "authorization" + ]).describe("Fields to redact"), + /** + * Sampling configuration + */ + sampling: external_exports.object({ + /** + * Enable sampling + */ + enabled: external_exports.boolean().optional().default(false), + /** + * Sample rate (0.0 to 1.0) + */ + rate: external_exports.number().min(0).max(1).optional().default(1), + /** + * Sample rate by level + */ + rateByLevel: external_exports.record(external_exports.string(), external_exports.number().min(0).max(1)).optional() + }).optional(), + /** + * Buffer configuration + */ + buffer: external_exports.object({ + /** + * Enable buffering + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Buffer size + */ + size: external_exports.number().int().positive().optional().default(1e3), + /** + * Flush interval in milliseconds + */ + flushInterval: external_exports.number().int().positive().optional().default(1e3), + /** + * Flush on shutdown + */ + flushOnShutdown: external_exports.boolean().optional().default(true) + }).optional(), + /** + * Performance configuration + */ + performance: external_exports.object({ + /** + * Async logging + */ + async: external_exports.boolean().optional().default(true), + /** + * Worker threads for async logging + */ + workers: external_exports.number().int().positive().optional().default(1) + }).optional() +}).describe("Logging configuration"); +var MetricType = external_exports.enum([ + "counter", + // Monotonically increasing value + "gauge", + // Value that can go up and down + "histogram", + // Observations bucketed by configurable ranges + "summary" + // Observations with quantiles +]).describe("Metric type"); +var MetricUnit = external_exports.enum([ + // Time units + "nanoseconds", + "microseconds", + "milliseconds", + "seconds", + "minutes", + "hours", + "days", + // Size units + "bytes", + "kilobytes", + "megabytes", + "gigabytes", + "terabytes", + // Rate units + "requests_per_second", + "events_per_second", + "bytes_per_second", + // Percentage + "percent", + "ratio", + // Count + "count", + "operations", + // Custom + "custom" +]).describe("Metric unit"); +var MetricAggregationType = external_exports.enum([ + "sum", + // Sum of all values + "avg", + // Average of all values + "min", + // Minimum value + "max", + // Maximum value + "count", + // Count of observations + "p50", + // 50th percentile (median) + "p75", + // 75th percentile + "p90", + // 90th percentile + "p95", + // 95th percentile + "p99", + // 99th percentile + "p999", + // 99.9th percentile + "rate", + // Rate of change + "stddev" + // Standard deviation +]).describe("Metric aggregation type"); +var HistogramBucketConfigSchema = external_exports.object({ + /** + * Bucket type + */ + type: external_exports.enum(["linear", "exponential", "explicit"]).describe("Bucket type"), + /** + * Linear bucket configuration + */ + linear: external_exports.object({ + start: external_exports.number().describe("Start value"), + width: external_exports.number().positive().describe("Bucket width"), + count: external_exports.number().int().positive().describe("Number of buckets") + }).optional(), + /** + * Exponential bucket configuration + */ + exponential: external_exports.object({ + start: external_exports.number().positive().describe("Start value"), + factor: external_exports.number().positive().describe("Growth factor"), + count: external_exports.number().int().positive().describe("Number of buckets") + }).optional(), + /** + * Explicit bucket boundaries + */ + explicit: external_exports.object({ + boundaries: external_exports.array(external_exports.number()).describe("Bucket boundaries") + }).optional() +}).describe("Histogram bucket configuration"); +var MetricLabelsSchema = external_exports.record(external_exports.string(), external_exports.string()).describe("Metric labels"); +var MetricDefinitionSchema = external_exports.object({ + /** + * Metric name (snake_case) + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Metric name (snake_case)"), + /** + * Display label + */ + label: external_exports.string().optional().describe("Display label"), + /** + * Metric type + */ + type: MetricType.describe("Metric type"), + /** + * Metric unit + */ + unit: MetricUnit.optional().describe("Metric unit"), + /** + * Description + */ + description: external_exports.string().optional().describe("Metric description"), + /** + * Label names for this metric + */ + labelNames: external_exports.array(external_exports.string()).optional().default([]).describe("Label names"), + /** + * Histogram configuration (for histogram type) + */ + histogram: HistogramBucketConfigSchema.optional(), + /** + * Summary configuration (for summary type) + */ + summary: external_exports.object({ + /** + * Quantiles to track + */ + quantiles: external_exports.array(external_exports.number().min(0).max(1)).optional().default([0.5, 0.9, 0.99]), + /** + * Max age of observations in seconds + */ + maxAge: external_exports.number().int().positive().optional().default(600), + /** + * Number of age buckets + */ + ageBuckets: external_exports.number().int().positive().optional().default(5) + }).optional(), + /** + * Enabled flag + */ + enabled: external_exports.boolean().optional().default(true) +}).describe("Metric definition"); +var MetricDataPointSchema = external_exports.object({ + /** + * Metric name + */ + name: external_exports.string().describe("Metric name"), + /** + * Metric type + */ + type: MetricType.describe("Metric type"), + /** + * Timestamp (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("Observation timestamp"), + /** + * Value (for counter and gauge) + */ + value: external_exports.number().optional().describe("Metric value"), + /** + * Labels + */ + labels: MetricLabelsSchema.optional().describe("Metric labels"), + /** + * Histogram data + */ + histogram: external_exports.object({ + count: external_exports.number().int().nonnegative().describe("Total count"), + sum: external_exports.number().describe("Sum of all values"), + buckets: external_exports.array(external_exports.object({ + upperBound: external_exports.number().describe("Upper bound of bucket"), + count: external_exports.number().int().nonnegative().describe("Count in bucket") + })).describe("Histogram buckets") + }).optional(), + /** + * Summary data + */ + summary: external_exports.object({ + count: external_exports.number().int().nonnegative().describe("Total count"), + sum: external_exports.number().describe("Sum of all values"), + quantiles: external_exports.array(external_exports.object({ + quantile: external_exports.number().min(0).max(1).describe("Quantile (0-1)"), + value: external_exports.number().describe("Quantile value") + })).describe("Summary quantiles") + }).optional() +}).describe("Metric data point"); +var TimeSeriesDataPointSchema = external_exports.object({ + /** + * Timestamp (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("Timestamp"), + /** + * Value + */ + value: external_exports.number().describe("Value"), + /** + * Labels/tags + */ + labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Labels") +}).describe("Time series data point"); +var TimeSeriesSchema = external_exports.object({ + /** + * Series name + */ + name: external_exports.string().describe("Series name"), + /** + * Series labels + */ + labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Series labels"), + /** + * Data points + */ + dataPoints: external_exports.array(TimeSeriesDataPointSchema).describe("Data points"), + /** + * Start time + */ + startTime: external_exports.string().datetime().optional().describe("Start time"), + /** + * End time + */ + endTime: external_exports.string().datetime().optional().describe("End time") +}).describe("Time series"); +var MetricAggregationConfigSchema = external_exports.object({ + /** + * Aggregation type + */ + type: MetricAggregationType.describe("Aggregation type"), + /** + * Time window for aggregation + */ + window: external_exports.object({ + /** + * Window size in seconds + */ + size: external_exports.number().int().positive().describe("Window size in seconds"), + /** + * Sliding window (true) or tumbling window (false) + */ + sliding: external_exports.boolean().optional().default(false), + /** + * Slide interval for sliding windows + */ + slideInterval: external_exports.number().int().positive().optional() + }).optional(), + /** + * Group by labels + */ + groupBy: external_exports.array(external_exports.string()).optional().describe("Group by label names"), + /** + * Filters + */ + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria") +}).describe("Metric aggregation configuration"); +var ServiceLevelIndicatorSchema = external_exports.object({ + /** + * SLI name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("SLI name (snake_case)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Description + */ + description: external_exports.string().optional().describe("SLI description"), + /** + * Metric name this SLI is based on + */ + metric: external_exports.string().describe("Base metric name"), + /** + * SLI type + */ + type: external_exports.enum([ + "availability", + // Percentage of successful requests + "latency", + // Response time percentile + "throughput", + // Requests per second + "error_rate", + // Error percentage + "saturation", + // Resource utilization + "custom" + // Custom calculation + ]).describe("SLI type"), + /** + * Success criteria + */ + successCriteria: external_exports.object({ + /** + * Threshold value + */ + threshold: external_exports.number().describe("Threshold value"), + /** + * Comparison operator + */ + operator: external_exports.enum(["lt", "lte", "gt", "gte", "eq"]).describe("Comparison operator"), + /** + * Percentile (for latency SLIs) + */ + percentile: external_exports.number().min(0).max(1).optional().describe("Percentile (0-1)") + }).describe("Success criteria"), + /** + * Measurement window + */ + window: external_exports.object({ + /** + * Window size in seconds + */ + size: external_exports.number().int().positive().describe("Window size in seconds"), + /** + * Rolling window (true) or calendar-aligned (false) + */ + rolling: external_exports.boolean().optional().default(true) + }).describe("Measurement window"), + /** + * Enabled flag + */ + enabled: external_exports.boolean().optional().default(true) +}).describe("Service Level Indicator"); +var ServiceLevelObjectiveSchema = external_exports.object({ + /** + * SLO name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("SLO name (snake_case)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Description + */ + description: external_exports.string().optional().describe("SLO description"), + /** + * SLI this SLO is based on + */ + sli: external_exports.string().describe("SLI name"), + /** + * Target percentage (0-100) + */ + target: external_exports.number().min(0).max(100).describe("Target percentage"), + /** + * Time period for SLO + */ + period: external_exports.object({ + /** + * Period type + */ + type: external_exports.enum(["rolling", "calendar"]).describe("Period type"), + /** + * Duration in seconds (for rolling) + */ + duration: external_exports.number().int().positive().optional().describe("Duration in seconds"), + /** + * Calendar period (for calendar) + */ + calendar: external_exports.enum(["daily", "weekly", "monthly", "quarterly", "yearly"]).optional() + }).describe("Time period"), + /** + * Error budget configuration + */ + errorBudget: external_exports.object({ + /** + * Auto-calculated budget (1 - target) + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Alert when budget consumed percentage exceeds threshold + */ + alertThreshold: external_exports.number().min(0).max(100).optional().default(80), + /** + * Burn rate alert windows + */ + burnRateWindows: external_exports.array(external_exports.object({ + /** + * Window size in seconds + */ + window: external_exports.number().int().positive().describe("Window size"), + /** + * Burn rate multiplier threshold + */ + threshold: external_exports.number().positive().describe("Burn rate threshold") + })).optional() + }).optional(), + /** + * Alert configuration + */ + alerts: external_exports.array(external_exports.object({ + /** + * Alert name + */ + name: external_exports.string().describe("Alert name"), + /** + * Severity + */ + severity: external_exports.enum(["info", "warning", "critical"]).describe("Alert severity"), + /** + * Condition + */ + condition: external_exports.object({ + type: external_exports.enum(["slo_breach", "error_budget", "burn_rate"]).describe("Condition type"), + threshold: external_exports.number().optional().describe("Threshold value") + }).describe("Alert condition") + })).optional().default([]), + /** + * Enabled flag + */ + enabled: external_exports.boolean().optional().default(true) +}).describe("Service Level Objective"); +var MetricExportConfigSchema = external_exports.object({ + /** + * Export type + */ + type: external_exports.enum([ + "prometheus", + // Prometheus exposition format + "openmetrics", + // OpenMetrics format + "graphite", + // Graphite plaintext protocol + "statsd", + // StatsD protocol + "influxdb", + // InfluxDB line protocol + "datadog", + // Datadog agent + "cloudwatch", + // AWS CloudWatch + "stackdriver", + // Google Cloud Monitoring + "azure_monitor", + // Azure Monitor + "http", + // HTTP push + "custom" + // Custom exporter + ]).describe("Export type"), + /** + * Endpoint configuration + */ + endpoint: external_exports.string().optional().describe("Export endpoint"), + /** + * Export interval in seconds + */ + interval: external_exports.number().int().positive().optional().default(60), + /** + * Batch configuration + */ + batch: external_exports.object({ + enabled: external_exports.boolean().optional().default(true), + size: external_exports.number().int().positive().optional().default(1e3) + }).optional(), + /** + * Authentication + */ + auth: external_exports.object({ + type: external_exports.enum(["none", "basic", "bearer", "api_key"]).describe("Auth type"), + username: external_exports.string().optional(), + password: external_exports.string().optional(), + token: external_exports.string().optional(), + apiKey: external_exports.string().optional() + }).optional(), + /** + * Additional configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional configuration") +}).describe("Metric export configuration"); +var MetricsConfigSchema = external_exports.object({ + /** + * Configuration name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Enable metrics collection + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Metric definitions + */ + metrics: external_exports.array(MetricDefinitionSchema).optional().default([]), + /** + * Default labels applied to all metrics + */ + defaultLabels: MetricLabelsSchema.optional().default({}), + /** + * Aggregation configurations + */ + aggregations: external_exports.array(MetricAggregationConfigSchema).optional().default([]), + /** + * Service Level Indicators + */ + slis: external_exports.array(ServiceLevelIndicatorSchema).optional().default([]), + /** + * Service Level Objectives + */ + slos: external_exports.array(ServiceLevelObjectiveSchema).optional().default([]), + /** + * Export configurations + */ + exports: external_exports.array(MetricExportConfigSchema).optional().default([]), + /** + * Collection interval in seconds + */ + collectionInterval: external_exports.number().int().positive().optional().default(15), + /** + * Retention configuration + */ + retention: external_exports.object({ + /** + * Retention period in seconds + */ + period: external_exports.number().int().positive().optional().default(604800), + // 7 days + /** + * Downsampling configuration + */ + downsampling: external_exports.array(external_exports.object({ + /** + * After this duration, downsample to this resolution + */ + afterSeconds: external_exports.number().int().positive().describe("Downsample after seconds"), + /** + * Resolution in seconds + */ + resolution: external_exports.number().int().positive().describe("Downsampled resolution") + })).optional() + }).optional(), + /** + * Cardinality limits + */ + cardinalityLimits: external_exports.object({ + /** + * Maximum unique label combinations per metric + */ + maxLabelCombinations: external_exports.number().int().positive().optional().default(1e4), + /** + * Action when limit exceeded + */ + onLimitExceeded: external_exports.enum(["drop", "sample", "alert"]).optional().default("alert") + }).optional() +}).describe("Metrics configuration"); +var TraceStateSchema = external_exports.object({ + /** + * Vendor-specific key-value pairs + */ + entries: external_exports.record(external_exports.string(), external_exports.string()).describe("Trace state entries") +}).describe("Trace state"); +var TraceFlagsSchema = external_exports.number().int().min(0).max(255).describe("Trace flags bitmap"); +var TraceContextSchema = external_exports.object({ + /** + * Trace ID (128-bit identifier, 32 hex chars) + */ + traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).describe("Trace ID (32 hex chars)"), + /** + * Span ID (64-bit identifier, 16 hex chars) + */ + spanId: external_exports.string().regex(/^[0-9a-f]{16}$/).describe("Span ID (16 hex chars)"), + /** + * Trace flags (8-bit) + */ + traceFlags: TraceFlagsSchema.optional().default(1), + /** + * Trace state (vendor-specific) + */ + traceState: TraceStateSchema.optional(), + /** + * Parent span ID + */ + parentSpanId: external_exports.string().regex(/^[0-9a-f]{16}$/).optional().describe("Parent span ID (16 hex chars)"), + /** + * Is sampled + */ + sampled: external_exports.boolean().optional().default(true), + /** + * Remote context (from incoming request) + */ + remote: external_exports.boolean().optional().default(false) +}).describe("Trace context (W3C Trace Context)"); +var SpanKind = external_exports.enum([ + "internal", + // Internal operation + "server", + // Server-side request handling + "client", + // Client-side request + "producer", + // Message producer + "consumer" + // Message consumer +]).describe("Span kind"); +var SpanStatus = external_exports.enum([ + "unset", + // Default status + "ok", + // Successful operation + "error" + // Error occurred +]).describe("Span status"); +var SpanAttributeValueSchema = external_exports.union([ + external_exports.string(), + external_exports.number(), + external_exports.boolean(), + external_exports.array(external_exports.string()), + external_exports.array(external_exports.number()), + external_exports.array(external_exports.boolean()) +]).describe("Span attribute value"); +var SpanAttributesSchema = external_exports.record(external_exports.string(), SpanAttributeValueSchema).describe("Span attributes"); +var SpanEventSchema = external_exports.object({ + /** + * Event name + */ + name: external_exports.string().describe("Event name"), + /** + * Event timestamp (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("Event timestamp"), + /** + * Event attributes + */ + attributes: SpanAttributesSchema.optional().describe("Event attributes") +}).describe("Span event"); +var SpanLinkSchema = external_exports.object({ + /** + * Linked trace context + */ + context: TraceContextSchema.describe("Linked trace context"), + /** + * Link attributes + */ + attributes: SpanAttributesSchema.optional().describe("Link attributes") +}).describe("Span link"); +var SpanSchema = external_exports.object({ + /** + * Trace context + */ + context: TraceContextSchema.describe("Trace context"), + /** + * Span name + */ + name: external_exports.string().describe("Span name"), + /** + * Span kind + */ + kind: SpanKind.optional().default("internal"), + /** + * Start time (ISO 8601) + */ + startTime: external_exports.string().datetime().describe("Span start time"), + /** + * End time (ISO 8601) + */ + endTime: external_exports.string().datetime().optional().describe("Span end time"), + /** + * Duration in milliseconds + */ + duration: external_exports.number().nonnegative().optional().describe("Duration in milliseconds"), + /** + * Span status + */ + status: external_exports.object({ + code: SpanStatus.describe("Status code"), + message: external_exports.string().optional().describe("Status message") + }).optional(), + /** + * Span attributes + */ + attributes: SpanAttributesSchema.optional().default({}), + /** + * Span events + */ + events: external_exports.array(SpanEventSchema).optional().default([]), + /** + * Span links + */ + links: external_exports.array(SpanLinkSchema).optional().default([]), + /** + * Resource attributes + */ + resource: SpanAttributesSchema.optional().describe("Resource attributes"), + /** + * Instrumentation library + */ + instrumentationLibrary: external_exports.object({ + name: external_exports.string().describe("Library name"), + version: external_exports.string().optional().describe("Library version") + }).optional() +}).describe("OpenTelemetry span"); +var SamplingDecision = external_exports.enum([ + "drop", + // Do not record or export + "record_only", + // Record but do not export + "record_and_sample" + // Record and export +]).describe("Sampling decision"); +var SamplingStrategyType = external_exports.enum([ + "always_on", + // Always sample + "always_off", + // Never sample + "trace_id_ratio", + // Sample based on trace ID ratio + "rate_limiting", + // Rate-limited sampling + "parent_based", + // Respect parent span sampling decision + "probability", + // Probability-based sampling + "composite", + // Combine multiple strategies + "custom" + // Custom sampling logic +]).describe("Sampling strategy type"); +var TraceSamplingConfigSchema = external_exports.object({ + /** + * Sampling strategy type + */ + type: SamplingStrategyType.describe("Sampling strategy"), + /** + * Sample ratio (0.0 to 1.0) for trace_id_ratio and probability strategies + */ + ratio: external_exports.number().min(0).max(1).optional().describe("Sample ratio (0-1)"), + /** + * Rate limit (traces per second) for rate_limiting strategy + */ + rateLimit: external_exports.number().positive().optional().describe("Traces per second"), + /** + * Parent-based configuration + */ + parentBased: external_exports.object({ + /** + * Sampler to use when parent is sampled + */ + whenParentSampled: SamplingStrategyType.optional().default("always_on"), + /** + * Sampler to use when parent is not sampled + */ + whenParentNotSampled: SamplingStrategyType.optional().default("always_off"), + /** + * Sampler to use when there is no parent (root span) + */ + root: SamplingStrategyType.optional().default("trace_id_ratio"), + /** + * Root sampler ratio + */ + rootRatio: external_exports.number().min(0).max(1).optional().default(0.1) + }).optional(), + /** + * Composite sampling (multiple strategies) + */ + composite: external_exports.array(external_exports.object({ + strategy: SamplingStrategyType.describe("Strategy type"), + ratio: external_exports.number().min(0).max(1).optional(), + condition: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Condition for this strategy") + })).optional(), + /** + * Sampling rules + */ + rules: external_exports.array(external_exports.object({ + /** + * Rule name + */ + name: external_exports.string().describe("Rule name"), + /** + * Match condition + */ + match: external_exports.object({ + /** + * Service name pattern + */ + service: external_exports.string().optional(), + /** + * Span name pattern (regex) + */ + spanName: external_exports.string().optional(), + /** + * Attribute filters + */ + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional(), + /** + * Sampling decision for matching spans + */ + decision: SamplingDecision.describe("Sampling decision"), + /** + * Sample rate for this rule + */ + rate: external_exports.number().min(0).max(1).optional() + })).optional().default([]), + /** + * Custom sampler ID (for custom strategy) + */ + customSamplerId: external_exports.string().optional().describe("Custom sampler identifier") +}).describe("Trace sampling configuration"); +var TracePropagationFormat = external_exports.enum([ + "w3c", + // W3C Trace Context + "b3", + // Zipkin B3 (single header) + "b3_multi", + // Zipkin B3 (multi header) + "jaeger", + // Jaeger propagation + "xray", + // AWS X-Ray + "ottrace", + // OpenTracing + "custom" + // Custom format +]).describe("Trace propagation format"); +var TraceContextPropagationSchema = external_exports.object({ + /** + * Propagation formats (in priority order) + */ + formats: external_exports.array(TracePropagationFormat).optional().default(["w3c"]), + /** + * Extract context from incoming requests + */ + extract: external_exports.boolean().optional().default(true), + /** + * Inject context into outgoing requests + */ + inject: external_exports.boolean().optional().default(true), + /** + * Custom header mappings + */ + headers: external_exports.object({ + /** + * Trace ID header name + */ + traceId: external_exports.string().optional(), + /** + * Span ID header name + */ + spanId: external_exports.string().optional(), + /** + * Trace flags header name + */ + traceFlags: external_exports.string().optional(), + /** + * Trace state header name + */ + traceState: external_exports.string().optional() + }).optional(), + /** + * Baggage propagation + */ + baggage: external_exports.object({ + /** + * Enable baggage propagation + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Maximum baggage size in bytes + */ + maxSize: external_exports.number().int().positive().optional().default(8192), + /** + * Allowed baggage keys (whitelist) + */ + allowedKeys: external_exports.array(external_exports.string()).optional() + }).optional() +}).describe("Trace context propagation"); +var OtelExporterType = external_exports.enum([ + "otlp_http", + // OTLP over HTTP + "otlp_grpc", + // OTLP over gRPC + "jaeger", + // Jaeger + "zipkin", + // Zipkin + "console", + // Console (for debugging) + "datadog", + // Datadog + "honeycomb", + // Honeycomb + "lightstep", + // Lightstep + "newrelic", + // New Relic + "custom" + // Custom exporter +]).describe("OpenTelemetry exporter type"); +var OpenTelemetryCompatibilitySchema = external_exports.object({ + /** + * OpenTelemetry SDK version + */ + sdkVersion: external_exports.string().optional().describe("OTel SDK version"), + /** + * Exporter configuration + */ + exporter: external_exports.object({ + /** + * Exporter type + */ + type: OtelExporterType.describe("Exporter type"), + /** + * Endpoint URL + */ + endpoint: external_exports.string().url().optional().describe("Exporter endpoint"), + /** + * Protocol version + */ + protocol: external_exports.string().optional().describe("Protocol version"), + /** + * Headers + */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP headers"), + /** + * Timeout in milliseconds + */ + timeout: external_exports.number().int().positive().optional().default(1e4), + /** + * Compression + */ + compression: external_exports.enum(["none", "gzip"]).optional().default("none"), + /** + * Batch configuration + */ + batch: external_exports.object({ + /** + * Maximum batch size + */ + maxBatchSize: external_exports.number().int().positive().optional().default(512), + /** + * Maximum queue size + */ + maxQueueSize: external_exports.number().int().positive().optional().default(2048), + /** + * Export timeout in milliseconds + */ + exportTimeout: external_exports.number().int().positive().optional().default(3e4), + /** + * Scheduled delay in milliseconds + */ + scheduledDelay: external_exports.number().int().positive().optional().default(5e3) + }).optional() + }).describe("Exporter configuration"), + /** + * Resource attributes (service identification) + */ + resource: external_exports.object({ + /** + * Service name + */ + serviceName: external_exports.string().describe("Service name"), + /** + * Service version + */ + serviceVersion: external_exports.string().optional().describe("Service version"), + /** + * Service instance ID + */ + serviceInstanceId: external_exports.string().optional().describe("Service instance ID"), + /** + * Service namespace + */ + serviceNamespace: external_exports.string().optional().describe("Service namespace"), + /** + * Deployment environment + */ + deploymentEnvironment: external_exports.string().optional().describe("Deployment environment"), + /** + * Additional resource attributes + */ + attributes: SpanAttributesSchema.optional().describe("Additional resource attributes") + }).describe("Resource attributes"), + /** + * Instrumentation configuration + */ + instrumentation: external_exports.object({ + /** + * Auto-instrumentation enabled + */ + autoInstrumentation: external_exports.boolean().optional().default(true), + /** + * Instrumentation libraries to enable + */ + libraries: external_exports.array(external_exports.string()).optional().describe("Enabled libraries"), + /** + * Instrumentation libraries to disable + */ + disabledLibraries: external_exports.array(external_exports.string()).optional().describe("Disabled libraries") + }).optional(), + /** + * Semantic conventions version + */ + semanticConventionsVersion: external_exports.string().optional().describe("Semantic conventions version") +}).describe("OpenTelemetry compatibility configuration"); +var TracingConfigSchema = external_exports.object({ + /** + * Configuration name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Enable tracing + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Sampling configuration + */ + sampling: TraceSamplingConfigSchema.optional().default({ type: "always_on", rules: [] }), + /** + * Context propagation + */ + propagation: TraceContextPropagationSchema.optional().default({ formats: ["w3c"], extract: true, inject: true }), + /** + * OpenTelemetry configuration + */ + openTelemetry: OpenTelemetryCompatibilitySchema.optional(), + /** + * Span limits + */ + spanLimits: external_exports.object({ + /** + * Maximum number of attributes per span + */ + maxAttributes: external_exports.number().int().positive().optional().default(128), + /** + * Maximum number of events per span + */ + maxEvents: external_exports.number().int().positive().optional().default(128), + /** + * Maximum number of links per span + */ + maxLinks: external_exports.number().int().positive().optional().default(128), + /** + * Maximum attribute value length + */ + maxAttributeValueLength: external_exports.number().int().positive().optional().default(4096) + }).optional(), + /** + * Trace ID generator + */ + traceIdGenerator: external_exports.enum(["random", "uuid", "custom"]).optional().default("random"), + /** + * Custom trace ID generator ID + */ + customTraceIdGeneratorId: external_exports.string().optional().describe("Custom generator identifier"), + /** + * Performance configuration + */ + performance: external_exports.object({ + /** + * Async span export + */ + asyncExport: external_exports.boolean().optional().default(true), + /** + * Background export interval in milliseconds + */ + exportInterval: external_exports.number().int().positive().optional().default(5e3) + }).optional() +}).describe("Tracing configuration"); +var DataClassificationSchema = external_exports.enum([ + "pii", + "phi", + "pci", + "financial", + "confidential", + "internal", + "public" +]).describe("Data classification level"); +var ComplianceFrameworkSchema = external_exports.enum([ + "gdpr", + "hipaa", + "sox", + "pci_dss", + "ccpa", + "iso27001" +]).describe("Compliance framework identifier"); +var ComplianceAuditRequirementSchema = external_exports.object({ + framework: ComplianceFrameworkSchema.describe("Compliance framework identifier"), + requiredEvents: external_exports.array(external_exports.string()).describe('Audit event types required by this framework (e.g., "data.delete", "auth.login")'), + retentionDays: external_exports.number().min(1).describe("Minimum audit log retention period required by this framework (in days)"), + alertOnMissing: external_exports.boolean().default(true).describe("Raise alert if a required audit event is not being captured") +}).describe("Compliance framework audit event requirements"); +var ComplianceEncryptionRequirementSchema = external_exports.object({ + framework: ComplianceFrameworkSchema.describe("Compliance framework identifier"), + dataClassifications: external_exports.array(DataClassificationSchema).describe("Data classifications that must be encrypted under this framework"), + minimumAlgorithm: external_exports.enum(["aes-256-gcm", "aes-256-cbc", "chacha20-poly1305"]).default("aes-256-gcm").describe("Minimum encryption algorithm strength required"), + keyRotationMaxDays: external_exports.number().min(1).default(90).describe("Maximum key rotation interval required (in days)") +}).describe("Compliance framework encryption requirements"); +var MaskingVisibilityRuleSchema = external_exports.object({ + dataClassification: DataClassificationSchema.describe("Data classification this rule applies to"), + defaultMasked: external_exports.boolean().default(true).describe("Whether data is masked by default"), + unmaskRoles: external_exports.array(external_exports.string()).optional().describe("Roles allowed to view unmasked data"), + auditUnmask: external_exports.boolean().default(true).describe("Log an audit event when data is unmasked"), + requireApproval: external_exports.boolean().default(false).describe("Require explicit approval before unmasking"), + approvalRoles: external_exports.array(external_exports.string()).optional().describe("Roles that can approve unmasking requests") +}).describe("Masking visibility and audit rule per data classification"); +var SecurityEventCorrelationSchema = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable cross-subsystem security event correlation"), + correlationId: external_exports.boolean().default(true).describe("Inject a shared correlation ID into audit, encryption, and masking events"), + linkAuthToAudit: external_exports.boolean().default(true).describe("Link authentication events to subsequent data operation audit trails"), + linkEncryptionToAudit: external_exports.boolean().default(true).describe("Log encryption/decryption operations in the audit trail"), + linkMaskingToAudit: external_exports.boolean().default(true).describe("Log masking/unmasking operations in the audit trail") +}).describe("Cross-subsystem security event correlation configuration"); +var DataClassificationPolicySchema = external_exports.object({ + classification: DataClassificationSchema.describe("Data classification level"), + requireEncryption: external_exports.boolean().default(false).describe("Encryption required for this classification"), + requireMasking: external_exports.boolean().default(false).describe("Masking required for this classification"), + requireAudit: external_exports.boolean().default(false).describe("Audit trail required for access to this classification"), + retentionDays: external_exports.number().optional().describe("Data retention limit in days (for compliance)") +}).describe("Security policy for a specific data classification level"); +var SecurityContextConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable unified security context governance"), + complianceAuditRequirements: external_exports.array(ComplianceAuditRequirementSchema).optional().describe("Compliance-driven audit event requirements"), + complianceEncryptionRequirements: external_exports.array(ComplianceEncryptionRequirementSchema).optional().describe("Compliance-driven encryption requirements by data classification"), + maskingVisibility: external_exports.array(MaskingVisibilityRuleSchema).optional().describe("Masking visibility rules per data classification"), + dataClassifications: external_exports.array(DataClassificationPolicySchema).optional().describe("Data classification policies for unified security enforcement"), + eventCorrelation: SecurityEventCorrelationSchema.optional().describe("Cross-subsystem security event correlation settings"), + enforceOnWrite: external_exports.boolean().default(true).describe("Enforce encryption and masking requirements on data write operations"), + enforceOnRead: external_exports.boolean().default(true).describe("Enforce masking and audit requirements on data read operations"), + failOpen: external_exports.boolean().default(false).describe("When false (default), deny access if security context cannot be evaluated") +}).describe("Unified security context governance configuration"); +var ChangeTypeSchema = external_exports.enum([ + "standard", + // Pre-approved, low-risk changes + "normal", + // Requires standard approval process + "emergency", + // Fast-track approval for critical issues + "major" + // Requires CAB (Change Advisory Board) approval +]); +var ChangePrioritySchema = external_exports.enum([ + "critical", + "high", + "medium", + "low" +]); +var ChangeStatusSchema = external_exports.enum([ + "draft", + "submitted", + "in-review", + "approved", + "scheduled", + "in-progress", + "completed", + "failed", + "rolled-back", + "cancelled" +]); +var ChangeImpactSchema = external_exports.object({ + /** + * Overall impact level of the change + */ + level: external_exports.enum(["low", "medium", "high", "critical"]).describe("Impact level"), + /** + * List of systems affected by this change + */ + affectedSystems: external_exports.array(external_exports.string()).describe("Affected systems"), + /** + * Estimated number of users affected + */ + affectedUsers: external_exports.number().optional().describe("Affected user count"), + /** + * Downtime requirements + */ + downtime: external_exports.object({ + /** + * Whether downtime is required + */ + required: external_exports.boolean().describe("Downtime required"), + /** + * Duration of downtime in minutes + */ + durationMinutes: external_exports.number().optional().describe("Downtime duration") + }).optional().describe("Downtime information") +}); +var RollbackPlanSchema = external_exports.object({ + /** + * High-level description of the rollback approach + */ + description: external_exports.string().describe("Rollback description"), + /** + * Sequential steps to execute rollback + */ + steps: external_exports.array(external_exports.object({ + /** + * Step execution order + */ + order: external_exports.number().describe("Step order"), + /** + * Detailed description of this step + */ + description: external_exports.string().describe("Step description"), + /** + * Estimated time to complete this step + */ + estimatedMinutes: external_exports.number().describe("Estimated duration") + })).describe("Rollback steps"), + /** + * Testing procedure to verify successful rollback + */ + testProcedure: external_exports.string().optional().describe("Test procedure") +}); +var ChangeRequestSchema = external_exports.object({ + /** + * Unique change request identifier + */ + id: external_exports.string().describe("Change request ID"), + /** + * Short descriptive title of the change + */ + title: external_exports.string().describe("Change title"), + /** + * Detailed description of the change and its purpose + */ + description: external_exports.string().describe("Change description"), + /** + * Change classification type + */ + type: ChangeTypeSchema.describe("Change type"), + /** + * Priority level for processing + */ + priority: ChangePrioritySchema.describe("Change priority"), + /** + * Current status in the change lifecycle + */ + status: ChangeStatusSchema.describe("Change status"), + /** + * User ID of the change requester + */ + requestedBy: external_exports.string().describe("Requester user ID"), + /** + * Timestamp when change was requested (Unix milliseconds) + */ + requestedAt: external_exports.number().describe("Request timestamp"), + /** + * Impact assessment of the change + */ + impact: ChangeImpactSchema.describe("Impact assessment"), + /** + * Implementation plan and procedures + */ + implementation: external_exports.object({ + /** + * High-level implementation description + */ + description: external_exports.string().describe("Implementation description"), + /** + * Sequential implementation steps + */ + steps: external_exports.array(external_exports.object({ + /** + * Step execution order + */ + order: external_exports.number().describe("Step order"), + /** + * Detailed description of this step + */ + description: external_exports.string().describe("Step description"), + /** + * Estimated time to complete this step + */ + estimatedMinutes: external_exports.number().describe("Estimated duration") + })).describe("Implementation steps"), + /** + * Testing procedures to verify successful implementation + */ + testing: external_exports.string().optional().describe("Testing procedure") + }).describe("Implementation plan"), + /** + * Rollback plan in case of failure + */ + rollbackPlan: RollbackPlanSchema.describe("Rollback plan"), + /** + * Change schedule and timing + */ + schedule: external_exports.object({ + /** + * Planned start time (Unix milliseconds) + */ + plannedStart: external_exports.number().describe("Planned start time"), + /** + * Planned end time (Unix milliseconds) + */ + plannedEnd: external_exports.number().describe("Planned end time"), + /** + * Actual start time (Unix milliseconds) + */ + actualStart: external_exports.number().optional().describe("Actual start time"), + /** + * Actual end time (Unix milliseconds) + */ + actualEnd: external_exports.number().optional().describe("Actual end time") + }).optional().describe("Schedule"), + /** + * Security impact assessment for the change (A.8.32) + */ + securityImpact: external_exports.object({ + /** + * Whether a security impact assessment has been performed + */ + assessed: external_exports.boolean().describe("Whether security impact has been assessed"), + /** + * Security risk level of this change + */ + riskLevel: external_exports.enum(["none", "low", "medium", "high", "critical"]).optional().describe("Security risk level"), + /** + * Data classifications affected by this change + */ + affectedDataClassifications: external_exports.array(DataClassificationSchema).optional().describe("Affected data classifications"), + /** + * Whether the change requires security team approval + */ + requiresSecurityApproval: external_exports.boolean().default(false).describe("Whether security team approval is required"), + /** + * Security reviewer user ID + */ + reviewedBy: external_exports.string().optional().describe("Security reviewer user ID"), + /** + * Security review completion timestamp (Unix milliseconds) + */ + reviewedAt: external_exports.number().optional().describe("Security review timestamp"), + /** + * Security review notes or conditions + */ + reviewNotes: external_exports.string().optional().describe("Security review notes or conditions") + }).optional().describe("Security impact assessment per ISO 27001:2022 A.8.32"), + /** + * Approval workflow configuration + */ + approval: external_exports.object({ + /** + * Whether approval is required for this change + */ + required: external_exports.boolean().describe("Approval required"), + /** + * List of approvers and their approval status + */ + approvers: external_exports.array(external_exports.object({ + /** + * Approver user ID + */ + userId: external_exports.string().describe("Approver user ID"), + /** + * Timestamp when approval was granted (Unix milliseconds) + */ + approvedAt: external_exports.number().optional().describe("Approval timestamp"), + /** + * Comments from the approver + */ + comments: external_exports.string().optional().describe("Approver comments") + })).describe("Approvers") + }).optional().describe("Approval workflow"), + /** + * Supporting documentation and files + */ + attachments: external_exports.array(external_exports.object({ + /** + * Attachment file name + */ + name: external_exports.string().describe("Attachment name"), + /** + * URL to download the attachment + */ + url: external_exports.string().url().describe("Attachment URL") + })).optional().describe("Attachments"), + /** + * Custom metadata key-value pairs for extensibility + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") +}); +var EncryptionAlgorithmSchema = external_exports.enum([ + "aes-256-gcm", + "aes-256-cbc", + "chacha20-poly1305" +]).describe("Supported encryption algorithm"); +var KeyManagementProviderSchema = external_exports.enum([ + "local", + "aws-kms", + "azure-key-vault", + "gcp-kms", + "hashicorp-vault" +]).describe("Key management service provider"); +var KeyRotationPolicySchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), + frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), + retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), + autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") +}).describe("Policy for automatic encryption key rotation"); +var EncryptionConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), + algorithm: EncryptionAlgorithmSchema.default("aes-256-gcm").describe("Encryption algorithm"), + keyManagement: external_exports.object({ + provider: KeyManagementProviderSchema.describe("Key management service provider"), + keyId: external_exports.string().optional().describe("Key identifier in the provider"), + rotationPolicy: KeyRotationPolicySchema.optional().describe("Key rotation policy") + }).describe("Key management configuration"), + scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), + deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), + searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") +}).describe("Field-level encryption configuration"); +var FieldEncryptionSchema = external_exports.object({ + fieldName: external_exports.string().describe("Name of the field to encrypt"), + encryptionConfig: EncryptionConfigSchema.describe("Encryption settings for this field"), + indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") +}).describe("Per-field encryption assignment"); +var MaskingStrategySchema = external_exports.enum([ + "redact", + // Complete redaction: **** + "partial", + // Partial masking: 138****5678 + "hash", + // Hash value: sha256(value) + "tokenize", + // Tokenization: token-12345 + "randomize", + // Randomize: generate random value + "nullify", + // Null value: null + "substitute" + // Substitute with dummy data +]).describe("Data masking strategy for PII protection"); +var MaskingRuleSchema = external_exports.object({ + field: external_exports.string().describe("Field name to apply masking to"), + strategy: MaskingStrategySchema.describe("Masking strategy to use"), + pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), + preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), + preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), + roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), + exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") +}).describe("Masking rule for a single field"); +var MaskingConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable data masking"), + rules: external_exports.array(MaskingRuleSchema).describe("List of field-level masking rules"), + auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") +}).describe("Top-level data masking configuration for PII protection"); +var FieldType = external_exports.enum([ + // Core Text + "text", + "textarea", + "email", + "url", + "phone", + "password", + // Rich Content + "markdown", + "html", + "richtext", + // Numbers + "number", + "currency", + "percent", + // Date & Time + "date", + "datetime", + "time", + // Logic + "boolean", + "toggle", + // Toggle is a distinct UI from checkbox + // Selection + "select", + // Single select dropdown + "multiselect", + // Multi select (often tags) + "radio", + // Radio group + "checkboxes", + // Checkbox group + // Relational + "lookup", + "master_detail", + // Dynamic reference + "tree", + // Hierarchical reference + // Media + "image", + "file", + "avatar", + "video", + "audio", + // Calculated / System + "formula", + "summary", + "autonumber", + // Enhanced Types + "location", + // GPS coordinates + "address", + // Structured address + "code", + // Code editor (JSON/SQL/JS) + "json", + // Structured JSON data + "color", + // Color picker + "rating", + // Star rating + "slider", + // Numeric slider + "signature", + // Digital signature + "qrcode", + // QR code / Barcode + "progress", + // Progress bar + "tags", + // Simple tag list + // AI/ML Types + "vector" + // Vector embeddings for AI/ML (semantic search, RAG) +]); +var SelectOptionSchema = external_exports.object({ + label: external_exports.string().describe("Display label (human-readable, any case allowed)"), + value: SystemIdentifierSchema.describe("Stored value (lowercase machine identifier)"), + color: external_exports.string().optional().describe("Color code for badges/charts"), + default: external_exports.boolean().optional().describe("Is default option") +}); +external_exports.object({ + latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), + longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), + altitude: external_exports.number().optional().describe("Altitude in meters"), + accuracy: external_exports.number().optional().describe("Accuracy in meters") +}); +var CurrencyConfigSchema = external_exports.object({ + precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), + currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), + defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") +}); +external_exports.object({ + value: external_exports.number().describe("Monetary amount"), + currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") +}); +external_exports.object({ + street: external_exports.string().optional().describe("Street address"), + city: external_exports.string().optional().describe("City name"), + state: external_exports.string().optional().describe("State/Province"), + postalCode: external_exports.string().optional().describe("Postal/ZIP code"), + country: external_exports.string().optional().describe("Country name or code"), + countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), + formatted: external_exports.string().optional().describe("Formatted address string") +}); +var VectorConfigSchema = external_exports.object({ + dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), + distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), + normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), + indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), + indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") +}); +var FileAttachmentConfigSchema = external_exports.object({ + /** File Size Limits */ + minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), + maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), + /** File Type Restrictions */ + allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), + blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), + allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), + blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), + /** Virus Scanning */ + virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), + virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), + virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), + quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), + /** Storage Configuration */ + storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), + storageBucket: external_exports.string().optional().describe("Target bucket name"), + storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), + /** Image-Specific Validation */ + imageValidation: external_exports.object({ + minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), + maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), + minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), + maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), + aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), + generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), + thumbnailSizes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), + width: external_exports.number().min(1).describe("Thumbnail width in pixels"), + height: external_exports.number().min(1).describe("Thumbnail height in pixels"), + crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") + })).optional().describe("Thumbnail size configurations"), + preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), + autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") + }).optional().describe("Image-specific validation rules"), + /** Upload Behavior */ + allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), + allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), + allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), + requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), + /** Metadata Extraction */ + extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), + extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), + /** Versioning */ + versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), + maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), + /** Access Control */ + publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), + presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") +}).refine((data) => { + if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { + return false; + } + return true; +}, { + message: "minSize must be less than or equal to maxSize" +}).refine((data) => { + if (data.virusScanProvider !== void 0 && data.virusScan !== true) { + return false; + } + return true; +}, { + message: "virusScanProvider requires virusScan to be enabled" +}); +var DataQualityRulesSchema = external_exports.object({ + /** Enforce uniqueness constraint */ + uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), + /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ + completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), + /** Accuracy validation against authoritative source */ + accuracy: external_exports.object({ + source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), + threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") + }).optional().describe("Accuracy validation configuration") +}); +var ComputedFieldCacheSchema = external_exports.object({ + /** Enable caching for this computed field */ + enabled: external_exports.boolean().describe("Enable caching for computed field results"), + /** Time-to-live in seconds */ + ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), + /** Array of field paths that trigger cache invalidation when changed */ + invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') +}); +var FieldSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), + label: external_exports.string().optional().describe("Human readable label"), + type: FieldType.describe("Field Data Type"), + description: external_exports.string().optional().describe("Tooltip/Help text"), + format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), + /** Storage Layer Mapping */ + columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), + /** Database Constraints */ + required: external_exports.boolean().default(false).describe("Is required"), + searchable: external_exports.boolean().default(false).describe("Is searchable"), + multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), + unique: external_exports.boolean().default(false).describe("Is unique constraint"), + defaultValue: external_exports.unknown().optional().describe("Default value"), + /** Text/String Constraints */ + maxLength: external_exports.number().optional().describe("Max character length"), + minLength: external_exports.number().optional().describe("Min character length"), + /** Number Constraints */ + precision: external_exports.number().optional().describe("Total digits"), + scale: external_exports.number().optional().describe("Decimal places"), + min: external_exports.number().optional().describe("Minimum value"), + max: external_exports.number().optional().describe("Maximum value"), + /** Selection Options */ + options: external_exports.array(SelectOptionSchema).optional().describe("Static options for select/multiselect"), + /** + * Relationship Config + * + * Used by `lookup` and `master_detail` field types to define cross-object references. + * The `reference` property is **required** for these types — it identifies the target + * object whose records this field links to. The engine uses `reference` during $expand + * post-processing to resolve foreign key IDs into full related objects via batch queries. + * + * For `master_detail` fields, the parent record controls the lifecycle of child records + * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. + */ + reference: external_exports.string().optional().describe( + "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." + ), + referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), + writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), + deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), + /** Calculation */ + expression: external_exports.string().optional().describe("Formula expression"), + summaryOperations: external_exports.object({ + object: external_exports.string().describe("Source child object name for roll-up"), + field: external_exports.string().describe("Field on child object to aggregate"), + function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") + }).optional().describe("Roll-up summary definition"), + /** Enhanced Field Type Configurations */ + // Code field config + language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), + theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), + lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), + // Rating field config + maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), + allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), + // Location field config + displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), + allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), + // Address field config + addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), + // Color field config + colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), + allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), + presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), + // Slider field config + step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), + showValue: external_exports.boolean().optional().describe("Display current value on slider"), + marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), + // QR Code / Barcode field config + // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' + // Runtime validation should enforce this constraint + barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), + qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), + displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), + allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), + // Currency field config + currencyConfig: CurrencyConfigSchema.optional().describe("Configuration for currency field type"), + // Vector field config + vectorConfig: VectorConfigSchema.optional().describe("Configuration for vector field type (AI/ML embeddings)"), + // File attachment field config + fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe("Configuration for file and attachment field types"), + /** Enhanced Security & Compliance */ + // Encryption configuration + encryptionConfig: EncryptionConfigSchema.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), + // Data masking rules + maskingRule: MaskingRuleSchema.optional().describe("Data masking rules for PII protection"), + // Audit trail + auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), + /** Field Dependencies & Relationships */ + // Field dependencies + dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), + /** Computed Field Optimization */ + // Computed field caching + cached: ComputedFieldCacheSchema.optional().describe("Caching configuration for computed/formula fields"), + /** Data Quality & Governance */ + // Data quality rules + dataQuality: DataQualityRulesSchema.optional().describe("Data quality validation and monitoring rules"), + /** Layout & Grouping */ + group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), + /** Conditional Requirements */ + conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), + /** Security & Visibility */ + hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), + readonly: external_exports.boolean().default(false).describe("Read-only in UI"), + sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), + inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), + trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), + caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), + autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), + /** Indexing */ + index: external_exports.boolean().default(false).describe("Create standard database index"), + externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") +}); +var BaseValidationSchema = external_exports.object({ + // Identification + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label for the rule listing"), + description: external_exports.string().optional().describe("Administrative notes explaining the business reason"), + // Execution Control + active: external_exports.boolean().default(true), + events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).default(["insert", "update"]).describe("Validation contexts"), + priority: external_exports.number().int().min(0).max(9999).default(100).describe("Execution priority (lower runs first, default: 100)"), + // Classification + tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g., "compliance", "billing")'), + // Feedback + severity: external_exports.enum(["error", "warning", "info"]).default("error"), + message: external_exports.string().describe("Error message to display to the user") +}); +var ScriptValidationSchema = BaseValidationSchema.extend({ + type: external_exports.literal("script"), + condition: external_exports.string().describe("Formula expression. If TRUE, validation fails. (e.g. amount < 0)") +}); +var UniquenessValidationSchema = BaseValidationSchema.extend({ + type: external_exports.literal("unique"), + fields: external_exports.array(external_exports.string()).describe("Fields that must be combined unique"), + scope: external_exports.string().optional().describe("Formula condition for scope (e.g. active = true)"), + caseSensitive: external_exports.boolean().default(true) +}); +var StateMachineValidationSchema = BaseValidationSchema.extend({ + type: external_exports.literal("state_machine"), + field: external_exports.string().describe("State field (e.g. status)"), + transitions: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).describe("Map of { OldState: [AllowedNewStates] }") +}); +var FormatValidationSchema = BaseValidationSchema.extend({ + type: external_exports.literal("format"), + field: external_exports.string(), + regex: external_exports.string().optional(), + format: external_exports.enum(["email", "url", "phone", "json"]).optional() +}); +var CrossFieldValidationSchema = BaseValidationSchema.extend({ + type: external_exports.literal("cross_field"), + condition: external_exports.string().describe('Formula expression comparing fields (e.g. "end_date > start_date")'), + fields: external_exports.array(external_exports.string()).describe("Fields involved in the validation") +}); +var JSONValidationSchema = BaseValidationSchema.extend({ + type: external_exports.literal("json_schema"), + field: external_exports.string().describe("JSON field to validate"), + schema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema object definition") +}); +var AsyncValidationSchema = BaseValidationSchema.extend({ + type: external_exports.literal("async"), + field: external_exports.string().describe("Field to validate"), + validatorUrl: external_exports.string().optional().describe("External API endpoint for validation"), + method: external_exports.enum(["GET", "POST"]).default("GET").describe("HTTP method for external call"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for the request"), + validatorFunction: external_exports.string().optional().describe("Reference to custom validator function"), + timeout: external_exports.number().optional().default(5e3).describe("Timeout in milliseconds"), + debounce: external_exports.number().optional().describe("Debounce delay in milliseconds"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional parameters to pass to validator") +}); +var CustomValidatorSchema = BaseValidationSchema.extend({ + type: external_exports.literal("custom"), + handler: external_exports.string().describe("Name of the custom validation function registered in the system"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the custom handler") +}); +var ValidationRuleSchema = external_exports.lazy( + () => external_exports.discriminatedUnion("type", [ + ScriptValidationSchema, + UniquenessValidationSchema, + StateMachineValidationSchema, + FormatValidationSchema, + CrossFieldValidationSchema, + JSONValidationSchema, + AsyncValidationSchema, + CustomValidatorSchema, + ConditionalValidationSchema + ]) +); +var ConditionalValidationSchema = BaseValidationSchema.extend({ + type: external_exports.literal("conditional"), + when: external_exports.string().describe(`Condition formula (e.g. "type = 'enterprise'")`), + then: ValidationRuleSchema.describe("Validation rule to apply when condition is true"), + otherwise: ValidationRuleSchema.optional().describe("Validation rule to apply when condition is false") +}); +var ActionRefSchema = external_exports.union([ + external_exports.string().describe("Action Name"), + external_exports.object({ + type: external_exports.string(), + // e.g., 'xstate.assign', 'log', 'email' + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }) +]); +var GuardRefSchema = external_exports.union([ + external_exports.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'), + external_exports.object({ + type: external_exports.string(), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }) +]); +var TransitionSchema = external_exports.object({ + target: external_exports.string().optional().describe("Target State ID"), + cond: GuardRefSchema.optional().describe("Condition (Guard) required to take this path"), + actions: external_exports.array(ActionRefSchema).optional().describe("Actions to execute during transition"), + description: external_exports.string().optional().describe("Human readable description of this rule") +}); +external_exports.object({ + type: external_exports.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'), + // Payload validation schema could go here if we want deep validation + schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Expected event payload structure") +}); +var StateNodeSchema = external_exports.lazy(() => external_exports.object({ + /** Type of state */ + type: external_exports.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"), + /** Entry/Exit Actions */ + entry: external_exports.array(ActionRefSchema).optional().describe("Actions to run when entering this state"), + exit: external_exports.array(ActionRefSchema).optional().describe("Actions to run when leaving this state"), + /** Transitions (Events) */ + on: external_exports.record(external_exports.string(), external_exports.union([ + external_exports.string(), + // Shorthand target + TransitionSchema, + external_exports.array(TransitionSchema) + ])).optional().describe("Map of Event Type -> Transition Definition"), + /** Always Transitions (Eventless) */ + always: external_exports.array(TransitionSchema).optional(), + /** Nesting (Hierarchical States) */ + initial: external_exports.string().optional().describe("Initial child state (if compound)"), + states: external_exports.record(external_exports.string(), StateNodeSchema).optional(), + /** Metadata for UI/AI */ + meta: external_exports.object({ + label: external_exports.string().optional(), + description: external_exports.string().optional(), + color: external_exports.string().optional(), + // For UI diagrams + // Instructions for AI Agent when in this state + aiInstructions: external_exports.string().optional().describe("Specific instructions for AI when in this state") + }).optional() +})); +var StateMachineSchema = external_exports.object({ + id: SnakeCaseIdentifierSchema.describe("Unique Machine ID"), + description: external_exports.string().optional(), + /** Context (Memory) Schema */ + contextSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Zod Schema for the machine context/memory"), + /** Initial State */ + initial: external_exports.string().describe("Initial State ID"), + /** State Definitions */ + states: external_exports.record(external_exports.string(), StateNodeSchema).describe("State Nodes"), + /** Global Listeners */ + on: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), TransitionSchema, external_exports.array(TransitionSchema)])).optional() +}); +external_exports.object({ + /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ + key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), + /** Default value when translation is not available */ + defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), + /** Interpolation parameters for dynamic translations */ + params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") +}); +var I18nLabelSchema = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); +var AriaPropsSchema = external_exports.object({ + /** Accessible label for screen readers */ + ariaLabel: I18nLabelSchema.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), + /** ID of element that describes this component */ + ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), + /** WAI-ARIA role override */ + role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') +}).describe("ARIA accessibility attributes"); +external_exports.object({ + /** Translation key for the plural form */ + key: external_exports.string().describe("Translation key"), + /** Form for zero quantity */ + zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), + /** Form for singular (1) */ + one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), + /** Form for dual (2) — used in Arabic, Welsh, etc. */ + two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), + /** Form for few (2-4 in Slavic languages) */ + few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), + /** Form for many (5+ in Slavic languages) */ + many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), + /** Default/fallback form */ + other: external_exports.string().describe('Default plural form (e.g., "{count} items")') +}).describe("ICU plural rules for a translation key"); +var NumberFormatSchema = external_exports.object({ + style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), + currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), + unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), + minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), + maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), + useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") +}).describe("Number formatting rules"); +var DateFormatSchema = external_exports.object({ + dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), + timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), + timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), + hour12: external_exports.boolean().optional().describe("Use 12-hour format") +}).describe("Date/time formatting rules"); +external_exports.object({ + /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ + code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), + /** Ordered fallback chain for missing translations */ + fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), + /** Text direction */ + direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), + /** Default number formatting */ + numberFormat: NumberFormatSchema.optional().describe("Default number formatting rules"), + /** Default date formatting */ + dateFormat: DateFormatSchema.optional().describe("Default date/time formatting rules") +}).describe("Locale configuration"); +var ActionParamSchema = external_exports.object({ + name: external_exports.string(), + label: I18nLabelSchema, + type: FieldType, + required: external_exports.boolean().default(false), + options: external_exports.array(external_exports.object({ label: I18nLabelSchema, value: external_exports.string() })).optional() +}); +var ActionType = external_exports.enum(["script", "url", "modal", "flow", "api"]); +var TARGET_REQUIRED_TYPES = new Set( + ActionType.options.filter((t) => t !== "script") +); +var ActionSchema = external_exports.object({ + /** Machine name of the action */ + name: SnakeCaseIdentifierSchema.describe("Machine name (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema.describe("Display label"), + /** Target object this action belongs to (optional, snake_case) */ + objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Icon name"), + /** Where does this action appear? */ + locations: external_exports.array(external_exports.enum([ + "list_toolbar", + "list_item", + "record_header", + "record_more", + "record_related", + "global_nav" + ])).optional().describe("Locations where this action is visible"), + /** + * Visual Component Type + * Defaults to 'button' or 'menu_item' based on location, + * but can be overridden. + */ + component: external_exports.enum([ + "action:button", + // Standard Button + "action:icon", + // Icon only + "action:menu", + // Dropdown menu + "action:group" + // Button Group + ]).optional().describe("Visual component override"), + /** What type of interaction? */ + type: ActionType.default("script").describe("Action functionality type"), + /** + * Payload / Target — the canonical binding for the action handler. + * Required for url, flow, modal, and api types. + * Recommended for script type. + */ + target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), + /** + * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. + */ + execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), + /** User Input Requirements */ + params: external_exports.array(ActionParamSchema).optional().describe("Input parameters required from user"), + /** Visual Style */ + variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), + /** UX Behavior */ + confirmText: I18nLabelSchema.optional().describe("Confirmation message before execution"), + successMessage: I18nLabelSchema.optional().describe("Success message to show after execution"), + refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), + /** Access */ + visible: external_exports.string().optional().describe("Formula returning boolean"), + disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), + /** Keyboard Shortcut */ + shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), + /** Bulk Operations */ + bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), + /** Execution */ + timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema.optional().describe("ARIA accessibility attributes") +}).transform((data) => { + if (data.execute && !data.target) { + return { ...data, target: data.execute }; + } + return data; +}).refine((data) => { + if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) { + return false; + } + return true; +}, { + message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", + path: ["target"] +}); +var ApiMethod = external_exports.enum([ + "get", + "list", + // Read + "create", + "update", + "delete", + // Write + "upsert", + // Idempotent Write + "bulk", + // Batch operations + "aggregate", + // Analytics (count, sum) + "history", + // Audit access + "search", + // Search access + "restore", + "purge", + // Trash management + "import", + "export" + // Data portability +]); +var ObjectCapabilities = external_exports.object({ + /** Enable history tracking (Audit Trail) */ + trackHistory: external_exports.boolean().default(false).describe("Enable field history tracking for audit compliance"), + /** Enable global search indexing */ + searchable: external_exports.boolean().default(true).describe("Index records for global search"), + /** Enable REST/GraphQL API access */ + apiEnabled: external_exports.boolean().default(true).describe("Expose object via automatic APIs"), + /** + * API Supported Operations + * Granular control over API exposure. + */ + apiMethods: external_exports.array(ApiMethod).optional().describe("Whitelist of allowed API operations"), + /** Enable standard attachments/files engine */ + files: external_exports.boolean().default(false).describe("Enable file attachments and document management"), + /** Enable social collaboration (Comments, Mentions, Feeds) */ + feeds: external_exports.boolean().default(false).describe("Enable social feed, comments, and mentions (Chatter-like)"), + /** Enable standard Activity suite (Tasks, Calendars, Events) */ + activities: external_exports.boolean().default(false).describe("Enable standard tasks and events tracking"), + /** Enable Recycle Bin / Soft Delete */ + trash: external_exports.boolean().default(true).describe("Enable soft-delete with restore capability"), + /** Enable "Recently Viewed" tracking */ + mru: external_exports.boolean().default(true).describe("Track Most Recently Used (MRU) list for users"), + /** Allow cloning records */ + clone: external_exports.boolean().default(true).describe("Allow record deep cloning") +}); +var IndexSchema = external_exports.object({ + name: external_exports.string().optional().describe("Index name (auto-generated if not provided)"), + fields: external_exports.array(external_exports.string()).describe("Fields included in the index"), + type: external_exports.enum(["btree", "hash", "gin", "gist", "fulltext"]).optional().default("btree").describe("Index algorithm type"), + unique: external_exports.boolean().optional().default(false).describe("Whether the index enforces uniqueness"), + partial: external_exports.string().optional().describe("Partial index condition (SQL WHERE clause for conditional indexes)") +}); +var SearchConfigSchema2 = external_exports.object({ + fields: external_exports.array(external_exports.string()).describe("Fields to index for full-text search weighting"), + displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display in search result cards"), + filters: external_exports.array(external_exports.string()).optional().describe("Default filters for search results") +}); +var TenancyConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable multi-tenancy for this object"), + strategy: external_exports.enum(["shared", "isolated", "hybrid"]).describe("Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)"), + tenantField: external_exports.string().default("tenant_id").describe("Field name for tenant identifier"), + crossTenantAccess: external_exports.boolean().default(false).describe("Allow cross-tenant data access (with explicit permission)") +}); +var SoftDeleteConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable soft delete (trash/recycle bin)"), + field: external_exports.string().default("deleted_at").describe("Field name for soft delete timestamp"), + cascadeDelete: external_exports.boolean().default(false).describe("Cascade soft delete to related records") +}); +var VersioningConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable record versioning"), + strategy: external_exports.enum(["snapshot", "delta", "event-sourcing"]).describe("Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)"), + retentionDays: external_exports.number().min(1).optional().describe("Number of days to retain old versions (undefined = infinite)"), + versionField: external_exports.string().default("version").describe("Field name for version number/timestamp") +}); +var PartitioningConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable table partitioning"), + strategy: external_exports.enum(["range", "hash", "list"]).describe("Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)"), + key: external_exports.string().describe("Field name to partition by"), + interval: external_exports.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")') +}).refine((data) => { + if (data.strategy === "range" && !data.interval) { + return false; + } + return true; +}, { + message: 'interval is required when strategy is "range"' +}); +var CDCConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable Change Data Capture"), + events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).describe("Event types to capture"), + destination: external_exports.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")') +}); +var ObjectSchemaBase = external_exports.object({ + /** + * Identity & Metadata + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine unique key (snake_case). Immutable."), + label: external_exports.string().optional().describe('Human readable singular label (e.g. "Account")'), + pluralLabel: external_exports.string().optional().describe('Human readable plural label (e.g. "Accounts")'), + description: external_exports.string().optional().describe("Developer documentation / description"), + icon: external_exports.string().optional().describe("Icon name (Lucide/Material) for UI representation"), + /** + * Namespace & Domain Classification + * + * Groups objects into logical domains for routing, permissions, and discovery. + * System objects use `'sys'`; business packages use their own namespace. + * + * When set, `tableName` is auto-derived as `{namespace}_{name}` by + * `ObjectSchema.create()` unless an explicit `tableName` is provided. + * + * Namespace must be a single lowercase word (no underscores or hyphens) + * to ensure clean auto-derivation of `{namespace}_{name}` table names. + * + * @example namespace: 'sys' → tableName defaults to 'sys_user' + * @example namespace: 'crm' → tableName defaults to 'crm_account' + */ + namespace: external_exports.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace \u2014 single lowercase word (e.g. "sys", "crm"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'), + /** + * Taxonomy & Organization + */ + tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'), + active: external_exports.boolean().optional().default(true).describe("Is the object active and usable"), + isSystem: external_exports.boolean().optional().default(false).describe("Is system object (protected from deletion)"), + abstract: external_exports.boolean().optional().default(false).describe("Is abstract base object (cannot be instantiated)"), + /** + * Storage & Virtualization + */ + datasource: external_exports.string().optional().default("default").describe('Target Datasource ID. "default" is the primary DB.'), + tableName: external_exports.string().optional().describe("Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set."), + /** + * Data Model + */ + fields: external_exports.record(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/, { + message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")' + }), FieldSchema).describe("Field definitions map. Keys must be snake_case identifiers."), + indexes: external_exports.array(IndexSchema).optional().describe("Database performance indexes"), + /** + * Advanced Data Management + */ + // Multi-tenancy configuration + tenancy: TenancyConfigSchema.optional().describe("Multi-tenancy configuration for SaaS applications"), + // Soft delete configuration + softDelete: SoftDeleteConfigSchema.optional().describe("Soft delete (trash/recycle bin) configuration"), + // Versioning configuration + versioning: VersioningConfigSchema.optional().describe("Record versioning and history tracking configuration"), + // Partitioning strategy + partitioning: PartitioningConfigSchema.optional().describe("Table partitioning configuration for performance"), + // Change Data Capture + cdc: CDCConfigSchema.optional().describe("Change Data Capture (CDC) configuration for real-time data streaming"), + /** + * Logic & Validation (Co-located) + * Best Practice: Define rules close to data. + */ + validations: external_exports.array(ValidationRuleSchema).optional().describe("Object-level validation rules"), + /** + * State Machine(s) + * Named record of state machines, where each key is a unique machine identifier. + * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status). + * + * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} } + */ + stateMachines: external_exports.record(external_exports.string(), StateMachineSchema).optional().describe("Named state machines for parallel lifecycles (e.g., status, payment, approval)"), + /** + * Display & UI Hints (Data-Layer) + */ + displayNameField: external_exports.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'), + recordName: external_exports.object({ + type: external_exports.enum(["text", "autonumber"]).describe("Record name type: text (user-entered) or autonumber (system-generated)"), + displayFormat: external_exports.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'), + startNumber: external_exports.number().int().min(0).optional().describe("Starting number for autonumber (default: 1)") + }).optional().describe("Record name generation configuration (Salesforce pattern)"), + titleFormat: external_exports.string().optional().describe('Title expression (e.g. "{name} - {code}"). Overrides displayNameField.'), + compactLayout: external_exports.array(external_exports.string()).optional().describe("Primary fields for hover/cards/lookups"), + /** + * Search Engine Config + */ + search: SearchConfigSchema2.optional().describe("Search engine configuration"), + /** + * System Capabilities + */ + enable: ObjectCapabilities.optional().describe("Enabled system features modules"), + /** Record Types */ + recordTypes: external_exports.array(external_exports.string()).optional().describe("Record type names for this object"), + /** Sharing Model */ + sharingModel: external_exports.enum(["private", "read", "read_write", "full"]).optional().describe("Default sharing model"), + /** Key Prefix */ + keyPrefix: external_exports.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'), + /** + * Object Actions + * + * Actions associated with this object. Populated automatically by `defineStack()` + * when top-level actions specify `objectName` matching this object. + * Can also be defined directly on the object. + * + * Aligns with Salesforce/ServiceNow patterns where actions are part of the + * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`) + * include the action list without requiring downstream merge. + */ + actions: external_exports.array(ActionSchema).optional().describe("Actions associated with this object (auto-populated from top-level actions via objectName)") +}); +function snakeCaseToLabel(name) { + return name.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); +} +var ObjectSchema = Object.assign(ObjectSchemaBase, { + /** + * Type-safe factory for creating business object definitions. + * + * Enhancements over raw schema: + * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case). + * - **Validation**: Runs Zod `.parse()` to validate the config at creation time. + * + * @example + * ```ts + * const Task = ObjectSchema.create({ + * name: 'project_task', + * // label auto-generated as 'Project Task' + * fields: { + * subject: { type: 'text', label: 'Subject', required: true }, + * }, + * }); + * ``` + */ + create: (config4) => { + const withDefaults = { + ...config4, + label: config4.label ?? snakeCaseToLabel(config4.name), + // Auto-derive tableName as {namespace}_{name} when namespace is set + tableName: config4.tableName ?? (config4.namespace ? `${config4.namespace}_${config4.name}` : void 0) + }; + return ObjectSchemaBase.parse(withDefaults); + } +}); +external_exports.enum(["own", "extend"]); +external_exports.object({ + /** The target object name (FQN) to extend */ + extend: external_exports.string().describe("Target object name (FQN) to extend"), + /** Fields to merge into the target object (additive) */ + fields: external_exports.record(external_exports.string(), FieldSchema).optional().describe("Fields to add/override"), + /** Override label */ + label: external_exports.string().optional().describe("Override label for the extended object"), + /** Override plural label */ + pluralLabel: external_exports.string().optional().describe("Override plural label for the extended object"), + /** Override description */ + description: external_exports.string().optional().describe("Override description for the extended object"), + /** Additional validation rules to add */ + validations: external_exports.array(ValidationRuleSchema).optional().describe("Additional validation rules to merge into the target object"), + /** Additional indexes to add */ + indexes: external_exports.array(IndexSchema).optional().describe("Additional indexes to merge into the target object"), + /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ + priority: external_exports.number().int().min(0).max(999).default(200).describe("Merge priority (higher = applied later)") +}); +var AddFieldOperation = external_exports.object({ + type: external_exports.literal("add_field"), + objectName: external_exports.string().describe("Target object name"), + fieldName: external_exports.string().describe("Name of the field to add"), + field: FieldSchema.describe("Full field definition to add") +}).describe("Add a new field to an existing object"); +var ModifyFieldOperation = external_exports.object({ + type: external_exports.literal("modify_field"), + objectName: external_exports.string().describe("Target object name"), + fieldName: external_exports.string().describe("Name of the field to modify"), + changes: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Partial field definition updates") +}).describe("Modify properties of an existing field"); +var RemoveFieldOperation = external_exports.object({ + type: external_exports.literal("remove_field"), + objectName: external_exports.string().describe("Target object name"), + fieldName: external_exports.string().describe("Name of the field to remove") +}).describe("Remove a field from an existing object"); +var CreateObjectOperation = external_exports.object({ + type: external_exports.literal("create_object"), + object: ObjectSchema.describe("Full object definition to create") +}).describe("Create a new object"); +var RenameObjectOperation = external_exports.object({ + type: external_exports.literal("rename_object"), + oldName: external_exports.string().describe("Current object name"), + newName: external_exports.string().describe("New object name") +}).describe("Rename an existing object"); +var DeleteObjectOperation = external_exports.object({ + type: external_exports.literal("delete_object"), + objectName: external_exports.string().describe("Name of the object to delete") +}).describe("Delete an existing object"); +var ExecuteSqlOperation = external_exports.object({ + type: external_exports.literal("execute_sql"), + sql: external_exports.string().describe("Raw SQL statement to execute"), + description: external_exports.string().optional().describe("Human-readable description of the SQL") +}).describe("Execute a raw SQL statement"); +var MigrationOperationSchema = external_exports.discriminatedUnion("type", [ + AddFieldOperation, + ModifyFieldOperation, + RemoveFieldOperation, + CreateObjectOperation, + RenameObjectOperation, + DeleteObjectOperation, + ExecuteSqlOperation +]); +var MigrationDependencySchema = external_exports.object({ + migrationId: external_exports.string().describe("ID of the migration this depends on"), + package: external_exports.string().optional().describe("Package that owns the dependency migration") +}).describe("Dependency reference to another migration that must run first"); +var ChangeSetSchema = external_exports.object({ + id: external_exports.string().uuid().describe("Unique identifier for this change set"), + name: external_exports.string().describe("Human readable name for the migration"), + description: external_exports.string().optional().describe("Detailed description of what this migration does"), + author: external_exports.string().optional().describe("Author who created this migration"), + createdAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp when the migration was created"), + // Dependencies ensure migrations run in order + dependencies: external_exports.array(MigrationDependencySchema).optional().describe("Migrations that must run before this one"), + // The actual atomic operations + operations: external_exports.array(MigrationOperationSchema).describe("Ordered list of atomic migration operations"), + // Rollback operations (AI should generate these too) + rollback: external_exports.array(MigrationOperationSchema).optional().describe("Operations to reverse this migration") +}).describe("A versioned set of atomic schema migration operations"); +var AuthProviderConfigSchema = external_exports.object({ + id: external_exports.string().describe("Provider ID (github, google)"), + clientId: external_exports.string().describe("OAuth Client ID"), + clientSecret: external_exports.string().describe("OAuth Client Secret"), + scope: external_exports.array(external_exports.string()).optional().describe("Requested permissions") +}); +var AuthPluginConfigSchema = external_exports.object({ + organization: external_exports.boolean().default(false).describe("Enable Organization/Teams support"), + twoFactor: external_exports.boolean().default(false).describe("Enable 2FA"), + passkeys: external_exports.boolean().default(false).describe("Enable Passkey support"), + magicLink: external_exports.boolean().default(false).describe("Enable Magic Link login") +}); +var MutualTLSConfigSchema = external_exports.object({ + /** Enable mutual TLS authentication */ + enabled: external_exports.boolean().default(false).describe("Enable mutual TLS authentication"), + /** Require client certificates for all connections */ + clientCertRequired: external_exports.boolean().default(false).describe("Require client certificates for all connections"), + /** PEM-encoded CA certificates or file paths for trust validation */ + trustedCAs: external_exports.array(external_exports.string()).describe("PEM-encoded CA certificates or file paths"), + /** Certificate Revocation List URL */ + crlUrl: external_exports.string().optional().describe("Certificate Revocation List (CRL) URL"), + /** Online Certificate Status Protocol URL */ + ocspUrl: external_exports.string().optional().describe("Online Certificate Status Protocol (OCSP) URL"), + /** Certificate validation strictness level */ + certificateValidation: external_exports.enum(["strict", "relaxed", "none"]).describe("Certificate validation strictness level"), + /** Allowed Common Names on client certificates */ + allowedCNs: external_exports.array(external_exports.string()).optional().describe("Allowed Common Names (CN) on client certificates"), + /** Allowed Organizational Units on client certificates */ + allowedOUs: external_exports.array(external_exports.string()).optional().describe("Allowed Organizational Units (OU) on client certificates"), + /** Certificate pinning configuration */ + pinning: external_exports.object({ + /** Enable certificate pinning */ + enabled: external_exports.boolean().describe("Enable certificate pinning"), + /** Array of pinned certificate hashes */ + pins: external_exports.array(external_exports.string()).describe("Pinned certificate hashes") + }).optional().describe("Certificate pinning configuration") +}); +var SocialProviderConfigSchema = external_exports.record( + external_exports.string(), + external_exports.object({ + clientId: external_exports.string().describe("OAuth Client ID"), + clientSecret: external_exports.string().describe("OAuth Client Secret"), + enabled: external_exports.boolean().optional().default(true).describe("Enable this provider"), + scope: external_exports.array(external_exports.string()).optional().describe("Additional OAuth scopes") + }).catchall(external_exports.unknown()) +).optional().describe( + "Social/OAuth provider map forwarded to better-auth socialProviders. Keys are provider ids (google, github, apple, \u2026)." +); +var EmailAndPasswordConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable email/password auth"), + disableSignUp: external_exports.boolean().optional().describe("Disable new user registration via email/password"), + requireEmailVerification: external_exports.boolean().optional().describe( + "Require email verification before creating a session" + ), + minPasswordLength: external_exports.number().optional().describe("Minimum password length (default 8)"), + maxPasswordLength: external_exports.number().optional().describe("Maximum password length (default 128)"), + resetPasswordTokenExpiresIn: external_exports.number().optional().describe( + "Reset-password token TTL in seconds (default 3600)" + ), + autoSignIn: external_exports.boolean().optional().describe("Auto sign-in after sign-up (default true)"), + revokeSessionsOnPasswordReset: external_exports.boolean().optional().describe( + "Revoke all other sessions on password reset" + ) +}).optional().describe("Email and password authentication options forwarded to better-auth"); +var EmailVerificationConfigSchema = external_exports.object({ + sendOnSignUp: external_exports.boolean().optional().describe( + "Automatically send verification email after sign-up" + ), + sendOnSignIn: external_exports.boolean().optional().describe( + "Send verification email on sign-in when not yet verified" + ), + autoSignInAfterVerification: external_exports.boolean().optional().describe( + "Auto sign-in the user after email verification" + ), + expiresIn: external_exports.number().optional().describe( + "Verification token TTL in seconds (default 3600)" + ) +}).optional().describe("Email verification options forwarded to better-auth"); +var AdvancedAuthConfigSchema = external_exports.object({ + crossSubDomainCookies: external_exports.object({ + enabled: external_exports.boolean().describe("Enable cross-subdomain cookies"), + additionalCookies: external_exports.array(external_exports.string()).optional().describe("Extra cookies shared across subdomains"), + domain: external_exports.string().optional().describe( + "Cookie domain override \u2014 defaults to root domain derived from baseUrl" + ) + }).optional().describe( + "Share auth cookies across subdomains (critical for *.example.com multi-tenant)" + ), + useSecureCookies: external_exports.boolean().optional().describe("Force Secure flag on cookies"), + disableCSRFCheck: external_exports.boolean().optional().describe( + "\u26A0 Disable CSRF check \u2014 security risk, use with caution" + ), + cookiePrefix: external_exports.string().optional().describe("Prefix for auth cookie names") +}).optional().describe("Advanced / low-level Better-Auth options"); +var AuthConfigSchema = external_exports.object({ + secret: external_exports.string().optional().describe("Encryption secret"), + baseUrl: external_exports.string().optional().describe("Base URL for auth routes"), + databaseUrl: external_exports.string().optional().describe("Database connection string"), + providers: external_exports.array(AuthProviderConfigSchema).optional(), + plugins: AuthPluginConfigSchema.optional(), + session: external_exports.object({ + expiresIn: external_exports.number().default(60 * 60 * 24 * 7).describe("Session duration in seconds"), + updateAge: external_exports.number().default(60 * 60 * 24).describe("Session update frequency") + }).optional(), + trustedOrigins: external_exports.array(external_exports.string()).optional().describe( + 'Trusted origins for CSRF protection. Supports wildcards (e.g. "https://*.example.com"). The baseUrl origin is always trusted implicitly.' + ), + socialProviders: SocialProviderConfigSchema, + emailAndPassword: EmailAndPasswordConfigSchema, + emailVerification: EmailVerificationConfigSchema, + advanced: AdvancedAuthConfigSchema, + mutualTls: MutualTLSConfigSchema.optional().describe("Mutual TLS (mTLS) configuration") +}).catchall(external_exports.unknown()); +var GDPRConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable GDPR compliance controls"), + dataSubjectRights: external_exports.object({ + rightToAccess: external_exports.boolean().default(true).describe("Allow data subjects to access their data"), + rightToRectification: external_exports.boolean().default(true).describe("Allow data subjects to correct their data"), + rightToErasure: external_exports.boolean().default(true).describe("Allow data subjects to request deletion"), + rightToRestriction: external_exports.boolean().default(true).describe("Allow data subjects to restrict processing"), + rightToPortability: external_exports.boolean().default(true).describe("Allow data subjects to export their data"), + rightToObjection: external_exports.boolean().default(true).describe("Allow data subjects to object to processing") + }).describe("Data subject rights configuration per GDPR Articles 15-21"), + legalBasis: external_exports.enum([ + "consent", + "contract", + "legal-obligation", + "vital-interests", + "public-task", + "legitimate-interests" + ]).describe("Legal basis for data processing under GDPR Article 6"), + consentTracking: external_exports.boolean().default(true).describe("Track and record user consent"), + dataRetentionDays: external_exports.number().optional().describe("Maximum data retention period in days"), + dataProcessingAgreement: external_exports.string().optional().describe("URL or reference to the data processing agreement") +}).describe("GDPR (General Data Protection Regulation) compliance configuration"); +var HIPAAConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable HIPAA compliance controls"), + phi: external_exports.object({ + encryption: external_exports.boolean().default(true).describe("Encrypt Protected Health Information at rest"), + accessControl: external_exports.boolean().default(true).describe("Enforce role-based access to PHI"), + auditTrail: external_exports.boolean().default(true).describe("Log all PHI access events"), + backupAndRecovery: external_exports.boolean().default(true).describe("Enable PHI backup and disaster recovery") + }).describe("Protected Health Information safeguards"), + businessAssociateAgreement: external_exports.boolean().default(false).describe("BAA is in place with third-party processors") +}).describe("HIPAA (Health Insurance Portability and Accountability Act) compliance configuration"); +var PCIDSSConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable PCI-DSS compliance controls"), + level: external_exports.enum(["1", "2", "3", "4"]).describe("PCI-DSS compliance level (1 = highest)"), + cardDataFields: external_exports.array(external_exports.string()).describe("Field names containing cardholder data"), + tokenization: external_exports.boolean().default(true).describe("Replace card data with secure tokens"), + encryptionInTransit: external_exports.boolean().default(true).describe("Encrypt cardholder data during transmission"), + encryptionAtRest: external_exports.boolean().default(true).describe("Encrypt stored cardholder data") +}).describe("PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration"); +var AuditLogConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable audit logging"), + retentionDays: external_exports.number().default(365).describe("Number of days to retain audit logs"), + immutable: external_exports.boolean().default(true).describe("Prevent modification or deletion of audit logs"), + signLogs: external_exports.boolean().default(false).describe("Cryptographically sign log entries for tamper detection"), + events: external_exports.array(external_exports.enum([ + "create", + "read", + "update", + "delete", + "export", + "permission-change", + "login", + "logout", + "failed-login" + ])).describe("Event types to capture in the audit log") +}).describe("Audit log configuration for compliance and security monitoring"); +var AuditFindingSeveritySchema = external_exports.enum([ + "critical", + // Immediate remediation required + "major", + // Significant non-conformity + "minor", + // Minor non-conformity + "observation" + // Improvement opportunity +]); +var AuditFindingStatusSchema = external_exports.enum([ + "open", + // Finding identified, not yet addressed + "in_remediation", + // Remediation in progress + "remediated", + // Remediation completed, pending verification + "verified", + // Remediation verified and accepted + "accepted_risk", + // Risk accepted by management + "closed" + // Finding closed +]); +var AuditFindingSchema = external_exports.object({ + /** + * Unique finding identifier + */ + id: external_exports.string().describe("Unique finding identifier"), + /** + * Short descriptive title + */ + title: external_exports.string().describe("Finding title"), + /** + * Detailed description of the finding + */ + description: external_exports.string().describe("Finding description"), + /** + * Finding severity + */ + severity: AuditFindingSeveritySchema.describe("Finding severity"), + /** + * Current status + */ + status: AuditFindingStatusSchema.describe("Finding status"), + /** + * ISO 27001 control reference (e.g., "A.5.35", "A.8.15") + */ + controlReference: external_exports.string().optional().describe("ISO 27001 control reference"), + /** + * Compliance framework + */ + framework: ComplianceFrameworkSchema.optional().describe("Related compliance framework"), + /** + * Timestamp when finding was identified (Unix milliseconds) + */ + identifiedAt: external_exports.number().describe("Identification timestamp"), + /** + * User or entity who identified the finding + */ + identifiedBy: external_exports.string().describe("Identifier (auditor name or system)"), + /** + * Planned remediation actions + */ + remediationPlan: external_exports.string().optional().describe("Remediation plan"), + /** + * Remediation deadline (Unix milliseconds) + */ + remediationDeadline: external_exports.number().optional().describe("Remediation deadline timestamp"), + /** + * Timestamp when remediation was verified (Unix milliseconds) + */ + verifiedAt: external_exports.number().optional().describe("Verification timestamp"), + /** + * Verifier name or role + */ + verifiedBy: external_exports.string().optional().describe("Verifier name or role"), + /** + * Notes or comments + */ + notes: external_exports.string().optional().describe("Additional notes") +}).describe("Audit finding with remediation tracking per ISO 27001:2022 A.5.35"); +var AuditScheduleSchema = external_exports.object({ + /** + * Unique audit schedule identifier + */ + id: external_exports.string().describe("Unique audit schedule identifier"), + /** + * Audit title or name + */ + title: external_exports.string().describe("Audit title"), + /** + * Scope of areas to audit + */ + scope: external_exports.array(external_exports.string()).describe("Audit scope areas"), + /** + * Target compliance framework + */ + framework: ComplianceFrameworkSchema.describe("Target compliance framework"), + /** + * Scheduled audit date (Unix milliseconds) + */ + scheduledAt: external_exports.number().describe("Scheduled audit timestamp"), + /** + * Actual completion date (Unix milliseconds) + */ + completedAt: external_exports.number().optional().describe("Completion timestamp"), + /** + * Assessor name, team, or external firm + */ + assessor: external_exports.string().describe("Assessor or audit team"), + /** + * Whether this is an external (independent) audit + */ + isExternal: external_exports.boolean().default(false).describe("Whether this is an external audit"), + /** + * Recurrence interval in months (0 = one-time) + */ + recurrenceMonths: external_exports.number().default(0).describe("Recurrence interval in months (0 = one-time)"), + /** + * Findings from this audit + */ + findings: external_exports.array(AuditFindingSchema).optional().describe("Audit findings") +}).describe("Audit schedule for independent security reviews per ISO 27001:2022 A.5.35"); +var ComplianceConfigSchema = external_exports.object({ + gdpr: GDPRConfigSchema.optional().describe("GDPR compliance settings"), + hipaa: HIPAAConfigSchema.optional().describe("HIPAA compliance settings"), + pciDss: PCIDSSConfigSchema.optional().describe("PCI-DSS compliance settings"), + auditLog: AuditLogConfigSchema.describe("Audit log configuration"), + auditSchedules: external_exports.array(AuditScheduleSchema).optional().describe("Scheduled compliance audits (A.5.35)") +}).describe("Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance"); +var IncidentSeveritySchema = external_exports.enum([ + "critical", + // Immediate threat to business operations or data integrity + "high", + // Significant impact requiring urgent response + "medium", + // Moderate impact with controlled response timeline + "low" + // Minor impact with standard response procedures +]); +var IncidentCategorySchema = external_exports.enum([ + "data_breach", + // Unauthorized access or disclosure of data + "malware", + // Malicious software detection + "unauthorized_access", + // Unauthorized system or data access + "denial_of_service", + // Service availability attack + "social_engineering", + // Phishing, pretexting, or manipulation + "insider_threat", + // Threat originating from internal actors + "physical_security", + // Physical security breach + "configuration_error", + // Security misconfiguration + "vulnerability_exploit", + // Exploitation of known vulnerability + "policy_violation", + // Violation of security policies + "other" + // Other security incidents +]); +var IncidentStatusSchema = external_exports.enum([ + "reported", + // Initial report received + "triaged", + // Severity and category assessed + "investigating", + // Active investigation in progress + "containing", + // Containment measures being applied + "eradicating", + // Root cause being removed + "recovering", + // Systems being restored to normal + "resolved", + // Incident resolved + "closed" + // Post-incident review complete +]); +var IncidentResponsePhaseSchema = external_exports.object({ + /** + * Phase name identifier + */ + phase: external_exports.enum([ + "identification", + "containment", + "eradication", + "recovery", + "lessons_learned" + ]).describe("Response phase name"), + /** + * Phase description and objectives + */ + description: external_exports.string().describe("Phase description and objectives"), + /** + * Responsible team or role for this phase + */ + assignedTo: external_exports.string().describe("Responsible team or role"), + /** + * Target completion time in hours from incident start + */ + targetHours: external_exports.number().min(0).describe("Target completion time in hours"), + /** + * Actual completion timestamp (Unix milliseconds) + */ + completedAt: external_exports.number().optional().describe("Actual completion timestamp"), + /** + * Notes and findings during this phase + */ + notes: external_exports.string().optional().describe("Phase notes and findings") +}).describe("Incident response phase with timing and assignment"); +var IncidentNotificationRuleSchema = external_exports.object({ + /** + * Minimum severity level that triggers this notification + */ + severity: IncidentSeveritySchema.describe("Minimum severity to trigger notification"), + /** + * Notification channels to use + */ + channels: external_exports.array(external_exports.enum([ + "email", + "sms", + "slack", + "pagerduty", + "webhook" + ])).describe("Notification channels"), + /** + * Roles or teams to notify + */ + recipients: external_exports.array(external_exports.string()).describe("Roles or teams to notify"), + /** + * Maximum time in minutes to send notification after incident detection + */ + withinMinutes: external_exports.number().min(1).describe("Notification deadline in minutes from detection"), + /** + * Whether to notify external regulators (for data breaches) + */ + notifyRegulators: external_exports.boolean().default(false).describe("Whether to notify regulatory authorities"), + /** + * Regulatory notification deadline in hours (e.g., GDPR 72h) + */ + regulatorDeadlineHours: external_exports.number().optional().describe("Regulatory notification deadline in hours") +}).describe("Incident notification rule per severity level"); +var IncidentNotificationMatrixSchema = external_exports.object({ + /** + * Notification rules ordered by severity + */ + rules: external_exports.array(IncidentNotificationRuleSchema).describe("Notification rules by severity level"), + /** + * Default escalation timeout in minutes before auto-escalation + */ + escalationTimeoutMinutes: external_exports.number().default(30).describe("Auto-escalation timeout in minutes"), + /** + * Escalation chain: ordered list of roles to escalate to + */ + escalationChain: external_exports.array(external_exports.string()).default([]).describe("Ordered escalation chain of roles") +}).describe("Incident notification matrix with escalation policies"); +var IncidentSchema = external_exports.object({ + /** + * Unique incident identifier + */ + id: external_exports.string().describe("Unique incident identifier"), + /** + * Short descriptive title of the incident + */ + title: external_exports.string().describe("Incident title"), + /** + * Detailed description of the security event + */ + description: external_exports.string().describe("Detailed incident description"), + /** + * Severity classification + */ + severity: IncidentSeveritySchema.describe("Incident severity level"), + /** + * Incident category / type + */ + category: IncidentCategorySchema.describe("Incident category"), + /** + * Current status in the incident lifecycle + */ + status: IncidentStatusSchema.describe("Current incident status"), + /** + * User or system that reported the incident + */ + reportedBy: external_exports.string().describe("Reporter user ID or system name"), + /** + * Timestamp when the incident was reported (Unix milliseconds) + */ + reportedAt: external_exports.number().describe("Report timestamp"), + /** + * Timestamp when the incident was detected (may differ from reported) + */ + detectedAt: external_exports.number().optional().describe("Detection timestamp"), + /** + * Timestamp when the incident was resolved + */ + resolvedAt: external_exports.number().optional().describe("Resolution timestamp"), + /** + * Systems affected by the incident + */ + affectedSystems: external_exports.array(external_exports.string()).describe("Affected systems"), + /** + * Data classifications affected (for data breach assessment) + */ + affectedDataClassifications: external_exports.array(DataClassificationSchema).optional().describe("Affected data classifications"), + /** + * Structured response phases tracking + */ + responsePhases: external_exports.array(IncidentResponsePhaseSchema).optional().describe("Incident response phases"), + /** + * Root cause analysis (completed post-incident) + */ + rootCause: external_exports.string().optional().describe("Root cause analysis"), + /** + * Corrective actions taken or planned + */ + correctiveActions: external_exports.array(external_exports.string()).optional().describe("Corrective actions taken or planned"), + /** + * Lessons learned from the incident (A.5.28) + */ + lessonsLearned: external_exports.string().optional().describe("Lessons learned from the incident"), + /** + * Related change request IDs (if changes resulted from incident) + */ + relatedChangeRequestIds: external_exports.array(external_exports.string()).optional().describe("Related change request IDs"), + /** + * Custom metadata for extensibility + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs") +}).describe("Security incident record per ISO 27001:2022 A.5.24\u2013A.5.28"); +var IncidentResponsePolicySchema = external_exports.object({ + /** + * Whether incident response is enabled + */ + enabled: external_exports.boolean().default(true).describe("Enable incident response management"), + /** + * Notification matrix configuration + */ + notificationMatrix: IncidentNotificationMatrixSchema.describe("Notification and escalation matrix"), + /** + * Default response team or role + */ + defaultResponseTeam: external_exports.string().describe("Default incident response team or role"), + /** + * Maximum time in hours to begin initial triage + */ + triageDeadlineHours: external_exports.number().default(1).describe("Maximum hours to begin triage after detection"), + /** + * Whether to require post-incident review for all incidents + */ + requirePostIncidentReview: external_exports.boolean().default(true).describe("Require post-incident review for all incidents"), + /** + * Minimum severity level that requires regulatory notification + */ + regulatoryNotificationThreshold: IncidentSeveritySchema.default("high").describe("Minimum severity requiring regulatory notification"), + /** + * Retention period for incident records in days + */ + retentionDays: external_exports.number().default(2555).describe("Incident record retention period in days (default ~7 years)") +}).describe("Organization-level incident response policy per ISO 27001:2022"); +var SupplierRiskLevelSchema = external_exports.enum([ + "critical", + // Direct access to sensitive data or core infrastructure + "high", + // Significant data processing or service dependency + "medium", + // Limited data access with moderate dependency + "low" + // Minimal data access and low service dependency +]); +var SupplierAssessmentStatusSchema = external_exports.enum([ + "pending", + // Assessment not yet started + "in_progress", + // Assessment currently underway + "completed", + // Assessment completed + "expired", + // Assessment past its validity period + "failed" + // Supplier did not meet security requirements +]); +var SupplierSecurityRequirementSchema = external_exports.object({ + /** + * Requirement identifier + */ + id: external_exports.string().describe("Requirement identifier"), + /** + * Requirement description + */ + description: external_exports.string().describe("Requirement description"), + /** + * ISO 27001 control reference (e.g., "A.5.19") + */ + controlReference: external_exports.string().optional().describe("ISO 27001 control reference"), + /** + * Whether this requirement is mandatory + */ + mandatory: external_exports.boolean().default(true).describe("Whether this requirement is mandatory"), + /** + * Compliance status + */ + compliant: external_exports.boolean().optional().describe("Whether the supplier meets this requirement"), + /** + * Evidence or notes for compliance assessment + */ + evidence: external_exports.string().optional().describe("Compliance evidence or assessment notes") +}).describe("Individual supplier security requirement"); +var SupplierSecurityAssessmentSchema = external_exports.object({ + /** + * Unique supplier identifier + */ + supplierId: external_exports.string().describe("Unique supplier identifier"), + /** + * Supplier name + */ + supplierName: external_exports.string().describe("Supplier display name"), + /** + * Risk classification + */ + riskLevel: SupplierRiskLevelSchema.describe("Supplier risk classification"), + /** + * Assessment status + */ + status: SupplierAssessmentStatusSchema.describe("Assessment status"), + /** + * User or team who performed the assessment + */ + assessedBy: external_exports.string().describe("Assessor user ID or team"), + /** + * Assessment completion timestamp (Unix milliseconds) + */ + assessedAt: external_exports.number().describe("Assessment timestamp"), + /** + * Assessment validity expiry (Unix milliseconds) + */ + validUntil: external_exports.number().describe("Assessment validity expiry timestamp"), + /** + * Security requirements assessed + */ + requirements: external_exports.array(SupplierSecurityRequirementSchema).describe("Security requirements and their compliance status"), + /** + * Overall compliance result + */ + overallCompliant: external_exports.boolean().describe("Whether supplier meets all mandatory requirements"), + /** + * Data classifications shared with this supplier + */ + dataClassificationsShared: external_exports.array(DataClassificationSchema).optional().describe("Data classifications shared with supplier"), + /** + * Services provided by the supplier + */ + servicesProvided: external_exports.array(external_exports.string()).optional().describe("Services provided by this supplier"), + /** + * Certifications held by the supplier + */ + certifications: external_exports.array(external_exports.string()).optional().describe("Supplier certifications (e.g., ISO 27001, SOC 2)"), + /** + * Remediation items for non-compliant requirements + */ + remediationItems: external_exports.array(external_exports.object({ + requirementId: external_exports.string().describe("Non-compliant requirement ID"), + action: external_exports.string().describe("Required remediation action"), + deadline: external_exports.number().describe("Remediation deadline timestamp"), + status: external_exports.enum(["pending", "in_progress", "completed"]).default("pending").describe("Remediation status") + })).optional().describe("Remediation items for non-compliant requirements"), + /** + * Custom metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs") +}).describe("Supplier security assessment record per ISO 27001:2022 A.5.19\u2013A.5.21"); +var SupplierSecurityPolicySchema = external_exports.object({ + /** + * Whether supplier security management is enabled + */ + enabled: external_exports.boolean().default(true).describe("Enable supplier security management"), + /** + * Reassessment interval in days + */ + reassessmentIntervalDays: external_exports.number().default(365).describe("Supplier reassessment interval in days"), + /** + * Whether to require supplier security assessment before onboarding + */ + requirePreOnboardingAssessment: external_exports.boolean().default(true).describe("Require security assessment before supplier onboarding"), + /** + * Minimum risk level that requires formal assessment + */ + formalAssessmentThreshold: SupplierRiskLevelSchema.default("medium").describe("Minimum risk level requiring formal assessment"), + /** + * Whether to monitor supplier security changes (A.5.22) + */ + monitorChanges: external_exports.boolean().default(true).describe("Monitor supplier security posture changes"), + /** + * Required certifications for critical suppliers + */ + requiredCertifications: external_exports.array(external_exports.string()).default([]).describe("Required certifications for critical-risk suppliers") +}).describe("Organization-level supplier security management policy per ISO 27001:2022"); +var TrainingCategorySchema = external_exports.enum([ + "security_awareness", + // General security awareness + "data_protection", + // Data handling and privacy + "incident_response", + // Incident reporting and response + "access_control", + // Access management best practices + "phishing_awareness", + // Phishing and social engineering + "compliance", + // Regulatory compliance (GDPR, HIPAA, etc.) + "secure_development", + // Secure coding and development practices + "physical_security", + // Physical security awareness + "business_continuity", + // Business continuity and disaster recovery + "other" + // Other training categories +]); +var TrainingCompletionStatusSchema = external_exports.enum([ + "not_started", + // Training not yet begun + "in_progress", + // Training currently underway + "completed", + // Training completed successfully + "failed", + // Training assessment not passed + "expired" + // Training certification has expired +]); +var TrainingCourseSchema = external_exports.object({ + /** + * Unique course identifier + */ + id: external_exports.string().describe("Unique course identifier"), + /** + * Course title + */ + title: external_exports.string().describe("Course title"), + /** + * Course description and objectives + */ + description: external_exports.string().describe("Course description and learning objectives"), + /** + * Training category + */ + category: TrainingCategorySchema.describe("Training category"), + /** + * Estimated duration in minutes + */ + durationMinutes: external_exports.number().min(1).describe("Estimated course duration in minutes"), + /** + * Whether this training is mandatory + */ + mandatory: external_exports.boolean().default(false).describe("Whether training is mandatory"), + /** + * Target roles or groups for this training + */ + targetRoles: external_exports.array(external_exports.string()).describe("Target roles or groups"), + /** + * Validity period in days before recertification is needed + */ + validityDays: external_exports.number().optional().describe("Certification validity period in days"), + /** + * Minimum passing score (percentage) for assessment + */ + passingScore: external_exports.number().min(0).max(100).optional().describe("Minimum passing score percentage"), + /** + * Course version for tracking content updates + */ + version: external_exports.string().optional().describe("Course content version") +}).describe("Security training course definition"); +var TrainingRecordSchema = external_exports.object({ + /** + * Reference to the course ID + */ + courseId: external_exports.string().describe("Training course identifier"), + /** + * User who completed (or is assigned) the training + */ + userId: external_exports.string().describe("User identifier"), + /** + * Completion status + */ + status: TrainingCompletionStatusSchema.describe("Training completion status"), + /** + * Training assignment date (Unix milliseconds) + */ + assignedAt: external_exports.number().describe("Assignment timestamp"), + /** + * Training completion date (Unix milliseconds) + */ + completedAt: external_exports.number().optional().describe("Completion timestamp"), + /** + * Assessment score (percentage) + */ + score: external_exports.number().min(0).max(100).optional().describe("Assessment score percentage"), + /** + * Certification expiry date (Unix milliseconds) + */ + expiresAt: external_exports.number().optional().describe("Certification expiry timestamp"), + /** + * Notes or comments from instructor or system + */ + notes: external_exports.string().optional().describe("Training notes or comments") +}).describe("Individual training completion record"); +var TrainingPlanSchema = external_exports.object({ + /** + * Whether training management is enabled + */ + enabled: external_exports.boolean().default(true).describe("Enable training management"), + /** + * Training courses in the plan + */ + courses: external_exports.array(TrainingCourseSchema).describe("Training courses"), + /** + * Default recertification interval in days + */ + recertificationIntervalDays: external_exports.number().default(365).describe("Default recertification interval in days"), + /** + * Whether to track training completion for compliance reporting + */ + trackCompletion: external_exports.boolean().default(true).describe("Track training completion for compliance"), + /** + * Grace period in days after expiry before non-compliance escalation + */ + gracePeriodDays: external_exports.number().default(30).describe("Grace period in days after certification expiry"), + /** + * Whether to send reminders for upcoming training deadlines + */ + sendReminders: external_exports.boolean().default(true).describe("Send reminders for upcoming training deadlines"), + /** + * Days before deadline to send first reminder + */ + reminderDaysBefore: external_exports.number().default(14).describe("Days before deadline to send first reminder") +}).describe("Organizational training plan per ISO 27001:2022 A.6.3"); +var CronScheduleSchema = external_exports.object({ + type: external_exports.literal("cron"), + expression: external_exports.string().describe('Cron expression (e.g., "0 0 * * *" for daily at midnight)'), + timezone: external_exports.string().optional().default("UTC").describe('Timezone for cron execution (e.g., "America/New_York")') +}); +var IntervalScheduleSchema = external_exports.object({ + type: external_exports.literal("interval"), + intervalMs: external_exports.number().int().positive().describe("Interval in milliseconds") +}); +var OnceScheduleSchema = external_exports.object({ + type: external_exports.literal("once"), + at: external_exports.string().datetime().describe("ISO 8601 datetime when to execute") +}); +var ScheduleSchema = external_exports.discriminatedUnion("type", [ + CronScheduleSchema, + IntervalScheduleSchema, + OnceScheduleSchema +]); +var RetryPolicySchema = external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum number of retry attempts"), + backoffMs: external_exports.number().int().positive().default(1e3).describe("Initial backoff delay in milliseconds"), + backoffMultiplier: external_exports.number().positive().default(2).describe("Multiplier for exponential backoff") +}); +var JobSchema = external_exports.object({ + id: external_exports.string().describe("Unique job identifier"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Job name (snake_case)"), + schedule: ScheduleSchema.describe("Job schedule configuration"), + handler: external_exports.string().describe('Handler path (e.g. "path/to/file:functionName") or script ID'), + retryPolicy: RetryPolicySchema.optional().describe("Retry policy configuration"), + timeout: external_exports.number().int().positive().optional().describe("Timeout in milliseconds"), + enabled: external_exports.boolean().default(true).describe("Whether the job is enabled") +}); +var JobExecutionStatus = external_exports.enum([ + "running", + "success", + "failed", + "timeout" +]); +var JobExecutionSchema = external_exports.object({ + jobId: external_exports.string().describe("Job identifier"), + startedAt: external_exports.string().datetime().describe("ISO 8601 datetime when execution started"), + completedAt: external_exports.string().datetime().optional().describe("ISO 8601 datetime when execution completed"), + status: JobExecutionStatus.describe("Execution status"), + error: external_exports.string().optional().describe("Error message if failed"), + duration: external_exports.number().int().optional().describe("Execution duration in milliseconds") +}); +var TaskPriority = external_exports.enum([ + "critical", + // 0 - Must execute immediately + "high", + // 1 - Execute soon + "normal", + // 2 - Default priority + "low", + // 3 - Execute when resources available + "background" + // 4 - Execute during low-traffic periods +]); +var TaskStatus = external_exports.enum([ + "pending", + // Waiting to be processed + "queued", + // In queue, ready for worker + "processing", + // Currently being executed + "completed", + // Successfully completed + "failed", + // Failed (may retry) + "cancelled", + // Manually cancelled + "timeout", + // Exceeded execution timeout + "dead" + // Moved to dead letter queue +]); +var TaskRetryPolicySchema = external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retry attempts"), + backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy between retries"), + initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay in milliseconds"), + maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Maximum retry delay in milliseconds"), + backoffMultiplier: external_exports.number().positive().default(2).describe("Multiplier for exponential backoff") +}); +var TaskSchema = external_exports.object({ + /** + * Unique task identifier + */ + id: external_exports.string().describe("Unique task identifier"), + /** + * Task type (handler identifier) + */ + type: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Task type (snake_case)"), + /** + * Task payload data + */ + payload: external_exports.unknown().describe("Task payload data"), + /** + * Queue name + */ + queue: external_exports.string().default("default").describe("Queue name"), + /** + * Task priority + */ + priority: TaskPriority.default("normal").describe("Task priority level"), + /** + * Retry policy + */ + retryPolicy: TaskRetryPolicySchema.optional().describe("Retry policy configuration"), + /** + * Execution timeout in milliseconds + */ + timeoutMs: external_exports.number().int().positive().optional().describe("Task timeout in milliseconds"), + /** + * Scheduled execution time + */ + scheduledAt: external_exports.string().datetime().optional().describe("ISO 8601 datetime to execute task"), + /** + * Maximum execution attempts + */ + attempts: external_exports.number().int().min(0).default(0).describe("Number of execution attempts"), + /** + * Task status + */ + status: TaskStatus.default("pending").describe("Current task status"), + /** + * Task metadata + */ + metadata: external_exports.object({ + createdAt: external_exports.string().datetime().optional().describe("When task was created"), + updatedAt: external_exports.string().datetime().optional().describe("Last update time"), + createdBy: external_exports.string().optional().describe("User who created task"), + tags: external_exports.array(external_exports.string()).optional().describe("Task tags for filtering") + }).optional().describe("Task metadata") +}); +var TaskExecutionResultSchema = external_exports.object({ + /** + * Task identifier + */ + taskId: external_exports.string().describe("Task identifier"), + /** + * Execution status + */ + status: TaskStatus.describe("Execution status"), + /** + * Execution result data + */ + result: external_exports.unknown().optional().describe("Execution result data"), + /** + * Error information + */ + error: external_exports.object({ + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Error stack trace"), + code: external_exports.string().optional().describe("Error code") + }).optional().describe("Error details if failed"), + /** + * Execution duration + */ + durationMs: external_exports.number().int().optional().describe("Execution duration in milliseconds"), + /** + * Execution timestamps + */ + startedAt: external_exports.string().datetime().describe("When execution started"), + completedAt: external_exports.string().datetime().optional().describe("When execution completed"), + /** + * Retry information + */ + attempt: external_exports.number().int().min(1).describe("Attempt number (1-indexed)"), + willRetry: external_exports.boolean().describe("Whether task will be retried") +}); +var QueueConfigSchema = external_exports.object({ + /** + * Queue name + */ + name: external_exports.string().describe("Queue name (snake_case)"), + /** + * Maximum concurrent workers + */ + concurrency: external_exports.number().int().min(1).default(5).describe("Max concurrent task executions"), + /** + * Rate limiting + */ + rateLimit: external_exports.object({ + max: external_exports.number().int().positive().describe("Maximum tasks per duration"), + duration: external_exports.number().int().positive().describe("Duration in milliseconds") + }).optional().describe("Rate limit configuration"), + /** + * Default retry policy + */ + defaultRetryPolicy: TaskRetryPolicySchema.optional().describe("Default retry policy for tasks"), + /** + * Dead letter queue + */ + deadLetterQueue: external_exports.string().optional().describe("Dead letter queue name"), + /** + * Queue priority + */ + priority: external_exports.number().int().min(0).default(0).describe("Queue priority (lower = higher priority)"), + /** + * Auto-scaling configuration + */ + autoScale: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable auto-scaling"), + minWorkers: external_exports.number().int().min(1).default(1).describe("Minimum workers"), + maxWorkers: external_exports.number().int().min(1).default(10).describe("Maximum workers"), + scaleUpThreshold: external_exports.number().int().positive().default(100).describe("Queue size to scale up"), + scaleDownThreshold: external_exports.number().int().min(0).default(10).describe("Queue size to scale down") + }).optional().describe("Auto-scaling configuration") +}); +var BatchTaskSchema = external_exports.object({ + /** + * Batch job identifier + */ + id: external_exports.string().describe("Unique batch job identifier"), + /** + * Task type for processing each item + */ + type: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Task type (snake_case)"), + /** + * Items to process + */ + items: external_exports.array(external_exports.unknown()).describe("Array of items to process"), + /** + * Batch size (items per task) + */ + batchSize: external_exports.number().int().min(1).default(100).describe("Number of items per batch"), + /** + * Queue name + */ + queue: external_exports.string().default("batch").describe("Queue for batch tasks"), + /** + * Priority + */ + priority: TaskPriority.default("normal").describe("Batch task priority"), + /** + * Parallel processing + */ + parallel: external_exports.boolean().default(true).describe("Process batches in parallel"), + /** + * Stop on error + */ + stopOnError: external_exports.boolean().default(false).describe("Stop batch if any item fails"), + /** + * Progress callback + * + * Called after each batch completes to report progress. + * Invoked asynchronously and should not throw errors. + * If the callback throws, the error is logged but batch processing continues. + * + * @param progress - Object containing processed count, total count, and failed count + */ + onProgress: external_exports.function().input(external_exports.tuple([external_exports.object({ + processed: external_exports.number(), + total: external_exports.number(), + failed: external_exports.number() + })])).output(external_exports.void()).optional().describe("Progress callback function (called after each batch)") +}); +var BatchProgressSchema = external_exports.object({ + /** + * Batch job identifier + */ + batchId: external_exports.string().describe("Batch job identifier"), + /** + * Total items + */ + total: external_exports.number().int().min(0).describe("Total number of items"), + /** + * Processed items + */ + processed: external_exports.number().int().min(0).default(0).describe("Items processed"), + /** + * Successful items + */ + succeeded: external_exports.number().int().min(0).default(0).describe("Items succeeded"), + /** + * Failed items + */ + failed: external_exports.number().int().min(0).default(0).describe("Items failed"), + /** + * Progress percentage + */ + percentage: external_exports.number().min(0).max(100).describe("Progress percentage"), + /** + * Status + */ + status: external_exports.enum(["pending", "running", "completed", "failed", "cancelled"]).describe("Batch status"), + /** + * Timestamps + */ + startedAt: external_exports.string().datetime().optional().describe("When batch started"), + completedAt: external_exports.string().datetime().optional().describe("When batch completed") +}); +var WorkerConfigSchema = external_exports.object({ + /** + * Worker name + */ + name: external_exports.string().describe("Worker name"), + /** + * Queues to process + */ + queues: external_exports.array(external_exports.string()).min(1).describe("Queue names to process"), + /** + * Queue configurations + */ + queueConfigs: external_exports.array(QueueConfigSchema).optional().describe("Queue configurations"), + /** + * Polling interval + */ + pollIntervalMs: external_exports.number().int().positive().default(1e3).describe("Queue polling interval in milliseconds"), + /** + * Visibility timeout + */ + visibilityTimeoutMs: external_exports.number().int().positive().default(3e4).describe("How long a task is invisible after being claimed"), + /** + * Task timeout + */ + defaultTimeoutMs: external_exports.number().int().positive().default(3e5).describe("Default task timeout in milliseconds"), + /** + * Graceful shutdown timeout + */ + shutdownTimeoutMs: external_exports.number().int().positive().default(3e4).describe("Graceful shutdown timeout in milliseconds"), + /** + * Task handlers + */ + handlers: external_exports.record(external_exports.string(), external_exports.function()).optional().describe("Task type handlers") +}); +var WorkerStatsSchema = external_exports.object({ + /** + * Worker name + */ + workerName: external_exports.string().describe("Worker name"), + /** + * Total tasks processed + */ + totalProcessed: external_exports.number().int().min(0).describe("Total tasks processed"), + /** + * Successful tasks + */ + succeeded: external_exports.number().int().min(0).describe("Successful tasks"), + /** + * Failed tasks + */ + failed: external_exports.number().int().min(0).describe("Failed tasks"), + /** + * Active tasks + */ + active: external_exports.number().int().min(0).describe("Currently active tasks"), + /** + * Average execution time + */ + avgExecutionMs: external_exports.number().min(0).optional().describe("Average execution time in milliseconds"), + /** + * Uptime + */ + uptimeMs: external_exports.number().int().min(0).describe("Worker uptime in milliseconds"), + /** + * Queue stats + */ + queues: external_exports.record(external_exports.string(), external_exports.object({ + pending: external_exports.number().int().min(0).describe("Pending tasks"), + active: external_exports.number().int().min(0).describe("Active tasks"), + completed: external_exports.number().int().min(0).describe("Completed tasks"), + failed: external_exports.number().int().min(0).describe("Failed tasks") + })).optional().describe("Per-queue statistics") +}); +var Task = Object.assign(TaskSchema, { + create: (task) => task +}); +var QueueConfig = Object.assign(QueueConfigSchema, { + create: (config4) => config4 +}); +var WorkerConfig = Object.assign(WorkerConfigSchema, { + create: (config4) => config4 +}); +var BatchTask = Object.assign(BatchTaskSchema, { + create: (batch) => batch +}); +var EmailTemplateSchema = external_exports.object({ + /** + * Unique identifier for the email template + */ + id: external_exports.string().describe("Template identifier"), + /** + * Email subject line (supports variable interpolation) + */ + subject: external_exports.string().describe("Email subject"), + /** + * Email body content + */ + body: external_exports.string().describe("Email body content"), + /** + * Content type of the email body + * @default 'html' + */ + bodyType: external_exports.enum(["text", "html", "markdown"]).optional().default("html").describe("Body content type"), + /** + * List of template variables for dynamic content + */ + variables: external_exports.array(external_exports.string()).optional().describe("Template variables"), + /** + * File attachments to include with the email + */ + attachments: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Attachment filename"), + url: external_exports.string().url().describe("Attachment URL") + })).optional().describe("Email attachments") +}); +var SMSTemplateSchema = external_exports.object({ + /** + * Unique identifier for the SMS template + */ + id: external_exports.string().describe("Template identifier"), + /** + * SMS message content (supports variable interpolation) + */ + message: external_exports.string().describe("SMS message content"), + /** + * Maximum character length for the SMS + * @default 160 + */ + maxLength: external_exports.number().optional().default(160).describe("Maximum message length"), + /** + * List of template variables for dynamic content + */ + variables: external_exports.array(external_exports.string()).optional().describe("Template variables") +}); +var PushNotificationSchema = external_exports.object({ + /** + * Notification title + */ + title: external_exports.string().describe("Notification title"), + /** + * Notification body text + */ + body: external_exports.string().describe("Notification body"), + /** + * Icon URL to display with notification + */ + icon: external_exports.string().url().optional().describe("Notification icon URL"), + /** + * Badge count to display on app icon + */ + badge: external_exports.number().optional().describe("Badge count"), + /** + * Custom data payload + */ + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom data"), + /** + * Action buttons for the notification + */ + actions: external_exports.array(external_exports.object({ + action: external_exports.string().describe("Action identifier"), + title: external_exports.string().describe("Action button title") + })).optional().describe("Notification actions") +}); +var InAppNotificationSchema = external_exports.object({ + /** + * Notification title + */ + title: external_exports.string().describe("Notification title"), + /** + * Notification message content + */ + message: external_exports.string().describe("Notification message"), + /** + * Notification severity type + */ + type: external_exports.enum(["info", "success", "warning", "error"]).describe("Notification type"), + /** + * Optional URL to navigate to when clicked + */ + actionUrl: external_exports.string().optional().describe("Action URL"), + /** + * Whether the notification can be dismissed by the user + * @default true + */ + dismissible: external_exports.boolean().optional().default(true).describe("User dismissible"), + /** + * Timestamp when notification expires (Unix milliseconds) + */ + expiresAt: external_exports.number().optional().describe("Expiration timestamp") +}); +var NotificationChannelSchema = external_exports.enum([ + "email", + "sms", + "push", + "in-app", + "slack", + "teams", + "webhook" +]); +var NotificationConfigSchema = external_exports.object({ + /** + * Unique identifier for this notification configuration + */ + id: external_exports.string().describe("Notification ID"), + /** + * Human-readable name for this notification + */ + name: external_exports.string().describe("Notification name"), + /** + * Delivery channel for the notification + */ + channel: NotificationChannelSchema.describe("Notification channel"), + /** + * Notification template based on channel type + */ + template: external_exports.union([ + EmailTemplateSchema, + SMSTemplateSchema, + PushNotificationSchema, + InAppNotificationSchema + ]).describe("Notification template"), + /** + * Recipient configuration + */ + recipients: external_exports.object({ + /** + * Primary recipients + */ + to: external_exports.array(external_exports.string()).describe("Primary recipients"), + /** + * CC recipients (email only) + */ + cc: external_exports.array(external_exports.string()).optional().describe("CC recipients"), + /** + * BCC recipients (email only) + */ + bcc: external_exports.array(external_exports.string()).optional().describe("BCC recipients") + }).describe("Recipients"), + /** + * Scheduling configuration + */ + schedule: external_exports.object({ + /** + * Scheduling type + */ + type: external_exports.enum(["immediate", "delayed", "scheduled"]).describe("Schedule type"), + /** + * Delay in milliseconds (for delayed type) + */ + delay: external_exports.number().optional().describe("Delay in milliseconds"), + /** + * Scheduled send time (Unix timestamp in milliseconds) + */ + scheduledAt: external_exports.number().optional().describe("Scheduled timestamp") + }).optional().describe("Scheduling"), + /** + * Retry policy for failed deliveries + */ + retryPolicy: external_exports.object({ + /** + * Enable automatic retries + * @default true + */ + enabled: external_exports.boolean().optional().default(true).describe("Enable retries"), + /** + * Maximum number of retry attempts + * @default 3 + */ + maxRetries: external_exports.number().optional().default(3).describe("Max retry attempts"), + /** + * Backoff strategy for retries + */ + backoffStrategy: external_exports.enum(["exponential", "linear", "fixed"]).describe("Backoff strategy") + }).optional().describe("Retry policy"), + /** + * Delivery tracking configuration + */ + tracking: external_exports.object({ + /** + * Track when emails are opened + * @default false + */ + trackOpens: external_exports.boolean().optional().default(false).describe("Track opens"), + /** + * Track when links are clicked + * @default false + */ + trackClicks: external_exports.boolean().optional().default(false).describe("Track clicks"), + /** + * Track delivery status + * @default true + */ + trackDelivery: external_exports.boolean().optional().default(true).describe("Track delivery") + }).optional().describe("Tracking configuration") +}); +var LocaleSchema = external_exports.string().describe("BCP-47 Language Tag (e.g. en-US, zh-CN)"); +var FieldTranslationSchema = external_exports.object({ + label: external_exports.string().optional().describe("Translated field label"), + help: external_exports.string().optional().describe("Translated help text"), + placeholder: external_exports.string().optional().describe("Translated placeholder text for form inputs"), + options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Option value to translated label map") +}).describe("Translation data for a single field"); +var ObjectTranslationDataSchema = external_exports.object({ + /** Translated singular label for the object */ + label: external_exports.string().describe("Translated singular label"), + /** Translated plural label for the object */ + pluralLabel: external_exports.string().optional().describe("Translated plural label"), + /** Field-level translations keyed by field name (snake_case) */ + fields: external_exports.record(external_exports.string(), FieldTranslationSchema).optional().describe("Field-level translations") +}).describe("Translation data for a single object"); +var TranslationDataSchema = external_exports.object({ + /** Object translations */ + objects: external_exports.record(external_exports.string(), ObjectTranslationDataSchema).optional().describe("Object translations keyed by object name"), + /** App/Menu translations */ + apps: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().describe("Translated app label"), + description: external_exports.string().optional().describe("Translated app description") + })).optional().describe("App translations keyed by app name"), + /** UI Messages */ + messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID"), + /** Validation Error Messages */ + validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%"})') +}).describe("Translation data for objects, apps, and UI messages"); +var TranslationBundleSchema = external_exports.record(LocaleSchema, TranslationDataSchema).describe("Map of locale codes to translation data"); +var TranslationFileOrganizationSchema = external_exports.enum([ + "bundled", + "per_locale", + "per_namespace" +]).describe("Translation file organization strategy"); +var MessageFormatSchema = external_exports.enum([ + "icu", + "simple" +]).describe("Message interpolation format: ICU MessageFormat or simple {variable} replacement"); +var TranslationConfigSchema = external_exports.object({ + /** Default locale for the application */ + defaultLocale: LocaleSchema.describe('Default locale (e.g., "en")'), + /** Supported BCP-47 locale codes */ + supportedLocales: external_exports.array(LocaleSchema).describe("Supported BCP-47 locale codes"), + /** Fallback locale when translation is not found */ + fallbackLocale: LocaleSchema.optional().describe("Fallback locale code"), + /** How translation files are organized on disk */ + fileOrganization: TranslationFileOrganizationSchema.default("per_locale").describe("File organization strategy"), + /** + * Message interpolation format. + * When set to `'icu'`, messages and validationMessages are expected to use + * ICU MessageFormat syntax (plurals, select, number/date skeletons). + * @default 'simple' + */ + messageFormat: MessageFormatSchema.default("simple").describe("Message interpolation format (ICU MessageFormat or simple)"), + /** Load translations on demand instead of eagerly */ + lazyLoad: external_exports.boolean().default(false).describe("Load translations on demand"), + /** Cache loaded translations in memory */ + cache: external_exports.boolean().default(true).describe("Cache loaded translations") +}).describe("Internationalization configuration"); +var OptionTranslationMapSchema = external_exports.record(external_exports.string(), external_exports.string()).describe("Option value to translated label map"); +var ObjectTranslationNodeSchema = external_exports.object({ + /** Translated singular label */ + label: external_exports.string().describe("Translated singular label"), + /** Translated plural label */ + pluralLabel: external_exports.string().optional().describe("Translated plural label"), + /** Translated object description */ + description: external_exports.string().optional().describe("Translated object description"), + /** Translated help text shown in tooltips or guidance panels */ + helpText: external_exports.string().optional().describe("Translated help text for the object"), + /** Field-level translations keyed by field name (snake_case) */ + fields: external_exports.record(external_exports.string(), FieldTranslationSchema).optional().describe("Field translations keyed by field name"), + /** + * Global picklist / select option overrides scoped to this object. + * Keyed by field name → { optionValue: translatedLabel }. + */ + _options: external_exports.record(external_exports.string(), OptionTranslationMapSchema).optional().describe("Object-scoped picklist option translations keyed by field name"), + /** View translations keyed by view name */ + _views: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated view label"), + description: external_exports.string().optional().describe("Translated view description") + })).optional().describe("View translations keyed by view name"), + /** Section (form section / tab) translations keyed by section name */ + _sections: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated section label") + })).optional().describe("Section translations keyed by section name"), + /** Action translations keyed by action name */ + _actions: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated action label"), + confirmMessage: external_exports.string().optional().describe("Translated confirmation message") + })).optional().describe("Action translations keyed by action name"), + /** Notification message translations keyed by notification name */ + _notifications: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated notification title"), + body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") + })).optional().describe("Notification translations keyed by notification name"), + /** Error message translations keyed by error code */ + _errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Error message translations keyed by error code") +}).describe("Object-first aggregated translation node"); +var AppTranslationBundleSchema = external_exports.object({ + /** + * Bundle-level metadata. + * Provides locale-aware rendering hints such as text direction (bidi) + * and the canonical locale code this bundle represents. + */ + _meta: external_exports.object({ + /** BCP-47 locale code this bundle represents */ + locale: external_exports.string().optional().describe("BCP-47 locale code for this bundle"), + /** Text direction for the locale */ + direction: external_exports.enum(["ltr", "rtl"]).optional().describe("Text direction: left-to-right or right-to-left") + }).optional().describe("Bundle-level metadata (locale, bidi direction)"), + /** + * Namespace for plugin/extension isolation. + * When multiple plugins contribute translations, each should use a unique + * namespace to avoid key collisions (e.g. "crm", "helpdesk", "plugin-xyz"). + */ + namespace: external_exports.string().optional().describe("Namespace for plugin isolation to avoid translation key collisions"), + /** Object-first translations keyed by object name (snake_case) */ + o: external_exports.record(external_exports.string(), ObjectTranslationNodeSchema).optional().describe("Object-first translations keyed by object name"), + /** Global picklist options not bound to any specific object */ + _globalOptions: external_exports.record(external_exports.string(), OptionTranslationMapSchema).optional().describe("Global picklist option translations keyed by option set name"), + /** App-level translations */ + app: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().describe("Translated app label"), + description: external_exports.string().optional().describe("Translated app description") + })).optional().describe("App translations keyed by app name"), + /** Navigation menu translations */ + nav: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Navigation item translations keyed by nav item name"), + /** Dashboard translations keyed by dashboard name */ + dashboard: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated dashboard label"), + description: external_exports.string().optional().describe("Translated dashboard description") + })).optional().describe("Dashboard translations keyed by dashboard name"), + /** Report translations keyed by report name */ + reports: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated report label"), + description: external_exports.string().optional().describe("Translated report description") + })).optional().describe("Report translations keyed by report name"), + /** Page translations keyed by page name */ + pages: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated page title"), + description: external_exports.string().optional().describe("Translated page description") + })).optional().describe("Page translations keyed by page name"), + /** UI message translations (supports ICU MessageFormat when enabled) */ + messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID (supports ICU MessageFormat)"), + /** Validation error message translations (supports ICU MessageFormat when enabled) */ + validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Validation error message translations keyed by rule name (supports ICU MessageFormat)"), + /** Global notification translations not bound to a specific object */ + notifications: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated notification title"), + body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") + })).optional().describe("Global notification translations keyed by notification name"), + /** Global error message translations not bound to a specific object */ + errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Global error message translations keyed by error code") +}).describe("Object-first application translation bundle for a single locale"); +var TranslationDiffStatusSchema = external_exports.enum([ + "missing", + "redundant", + "stale" +]).describe("Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)"); +var TranslationDiffItemSchema = external_exports.object({ + /** Dot-path translation key (e.g. "o.account.fields.website.label") */ + key: external_exports.string().describe("Dot-path translation key"), + /** Diff status */ + status: TranslationDiffStatusSchema.describe("Diff status of this translation key"), + /** Object name if the key belongs to an object translation node */ + objectName: external_exports.string().optional().describe("Associated object name (snake_case)"), + /** Locale code */ + locale: external_exports.string().describe("BCP-47 locale code"), + /** + * Hash of the source metadata value at the time the translation was made. + * Used by CLI/Workbench to detect stale translations without a full diff. + */ + sourceHash: external_exports.string().optional().describe("Hash of source metadata for precise stale detection"), + /** + * AI-suggested translation text for missing or stale entries. + * Populated by AI translation hooks or TMS integrations. + */ + aiSuggested: external_exports.string().optional().describe("AI-suggested translation for this key"), + /** Confidence score (0-1) for the AI suggestion */ + aiConfidence: external_exports.number().min(0).max(1).optional().describe("AI suggestion confidence score (0\u20131)") +}).describe("A single translation diff item"); +var CoverageBreakdownEntrySchema = external_exports.object({ + /** Group category (e.g. "fields", "views", "actions", "messages") */ + group: external_exports.string().describe("Translation group category"), + /** Total translatable keys in this group */ + totalKeys: external_exports.number().int().nonnegative().describe("Total keys in this group"), + /** Number of translated keys in this group */ + translatedKeys: external_exports.number().int().nonnegative().describe("Translated keys in this group"), + /** Coverage percentage for this group */ + coveragePercent: external_exports.number().min(0).max(100).describe("Coverage percentage for this group") +}).describe("Coverage breakdown for a single translation group"); +var TranslationCoverageResultSchema = external_exports.object({ + /** BCP-47 locale code */ + locale: external_exports.string().describe("BCP-47 locale code"), + /** Optional object name scope */ + objectName: external_exports.string().optional().describe("Object name scope (omit for full bundle)"), + /** Total translatable keys derived from metadata */ + totalKeys: external_exports.number().int().nonnegative().describe("Total translatable keys from metadata"), + /** Number of keys that have a translation */ + translatedKeys: external_exports.number().int().nonnegative().describe("Number of translated keys"), + /** Number of missing translations */ + missingKeys: external_exports.number().int().nonnegative().describe("Number of missing translations"), + /** Number of redundant (orphaned) translations */ + redundantKeys: external_exports.number().int().nonnegative().describe("Number of redundant translations"), + /** Number of stale translations */ + staleKeys: external_exports.number().int().nonnegative().describe("Number of stale translations"), + /** Coverage percentage (0-100) */ + coveragePercent: external_exports.number().min(0).max(100).describe("Translation coverage percentage"), + /** Individual diff items */ + items: external_exports.array(TranslationDiffItemSchema).describe("Detailed diff items"), + /** + * Per-group coverage breakdown for translation project management. + * Each entry represents a logical group (e.g. "fields", "views", "actions", + * "messages") with its own coverage statistics. + */ + breakdown: external_exports.array(CoverageBreakdownEntrySchema).optional().describe("Per-group coverage breakdown") +}).describe("Aggregated translation coverage result"); +var OTOperationType = external_exports.enum([ + "insert", + // Insert characters at position + "delete", + // Delete characters at position + "retain" + // Keep characters (used for composing operations) +]); +var OTComponentSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("insert"), + text: external_exports.string().describe("Text to insert"), + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Text formatting attributes (e.g., bold, italic)") + }), + external_exports.object({ + type: external_exports.literal("delete"), + count: external_exports.number().int().positive().describe("Number of characters to delete") + }), + external_exports.object({ + type: external_exports.literal("retain"), + count: external_exports.number().int().positive().describe("Number of characters to retain"), + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Attribute changes to apply") + }) +]); +var OTOperationSchema = external_exports.object({ + operationId: external_exports.string().uuid().describe("Unique operation identifier"), + documentId: external_exports.string().describe("Document identifier"), + userId: external_exports.string().describe("User who created the operation"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + components: external_exports.array(OTComponentSchema).describe("Operation components"), + baseVersion: external_exports.number().int().nonnegative().describe("Document version this operation is based on"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when operation was created"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional operation metadata") +}); +var OTTransformResultSchema = external_exports.object({ + operation: OTOperationSchema.describe("Transformed operation"), + transformed: external_exports.boolean().describe("Whether transformation was applied"), + conflicts: external_exports.array(external_exports.string()).optional().describe("Conflict descriptions if any") +}); +var CRDTType = external_exports.enum([ + "lww-register", + // Last-Write-Wins Register + "g-counter", + // Grow-only Counter + "pn-counter", + // Positive-Negative Counter + "g-set", + // Grow-only Set + "or-set", + // Observed-Remove Set + "lww-map", + // Last-Write-Wins Map + "text", + // CRDT-based Text (e.g., Yjs, Automerge) + "tree", + // CRDT-based Tree structure + "json" + // CRDT-based JSON (e.g., Automerge) +]); +var VectorClockSchema = external_exports.object({ + clock: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Map of replica ID to logical timestamp") +}); +var LWWRegisterSchema = external_exports.object({ + type: external_exports.literal("lww-register"), + value: external_exports.unknown().describe("Current register value"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of last write"), + replicaId: external_exports.string().describe("ID of replica that performed last write"), + vectorClock: VectorClockSchema.optional().describe("Optional vector clock for causality tracking") +}); +var CounterOperationSchema = external_exports.object({ + replicaId: external_exports.string().describe("Replica identifier"), + delta: external_exports.number().int().describe("Change amount (positive for increment, negative for decrement)"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of operation") +}); +var GCounterSchema = external_exports.object({ + type: external_exports.literal("g-counter"), + counts: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Map of replica ID to count") +}); +var PNCounterSchema = external_exports.object({ + type: external_exports.literal("pn-counter"), + positive: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Positive increments per replica"), + negative: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Negative increments per replica") +}); +var ORSetElementSchema = external_exports.object({ + value: external_exports.unknown().describe("Element value"), + timestamp: external_exports.string().datetime().describe("Addition timestamp"), + replicaId: external_exports.string().describe("Replica that added the element"), + uid: external_exports.string().uuid().describe("Unique identifier for this addition"), + removed: external_exports.boolean().optional().default(false).describe("Whether element has been removed") +}); +var ORSetSchema = external_exports.object({ + type: external_exports.literal("or-set"), + elements: external_exports.array(ORSetElementSchema).describe("Set elements with metadata") +}); +var TextCRDTOperationSchema = external_exports.object({ + operationId: external_exports.string().uuid().describe("Unique operation identifier"), + replicaId: external_exports.string().describe("Replica identifier"), + position: external_exports.number().int().nonnegative().describe("Position in document"), + insert: external_exports.string().optional().describe("Text to insert"), + delete: external_exports.number().int().positive().optional().describe("Number of characters to delete"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of operation"), + lamportTimestamp: external_exports.number().int().nonnegative().describe("Lamport timestamp for ordering") +}); +var TextCRDTStateSchema = external_exports.object({ + type: external_exports.literal("text"), + documentId: external_exports.string().describe("Document identifier"), + content: external_exports.string().describe("Current text content"), + operations: external_exports.array(TextCRDTOperationSchema).describe("History of operations"), + lamportClock: external_exports.number().int().nonnegative().describe("Current Lamport clock value"), + vectorClock: VectorClockSchema.describe("Vector clock for causality") +}); +var CRDTStateSchema = external_exports.discriminatedUnion("type", [ + LWWRegisterSchema, + GCounterSchema, + PNCounterSchema, + ORSetSchema, + TextCRDTStateSchema +]); +var CRDTMergeResultSchema = external_exports.object({ + state: CRDTStateSchema.describe("Merged CRDT state"), + conflicts: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Conflict type"), + description: external_exports.string().describe("Conflict description"), + resolved: external_exports.boolean().describe("Whether conflict was automatically resolved") + })).optional().describe("Conflicts encountered during merge") +}); +var CursorColorPreset = external_exports.enum([ + "blue", + "green", + "red", + "yellow", + "purple", + "orange", + "pink", + "teal", + "indigo", + "cyan" +]); +var CursorStyleSchema = external_exports.object({ + color: external_exports.union([CursorColorPreset, external_exports.string()]).describe("Cursor color (preset or custom hex)"), + opacity: external_exports.number().min(0).max(1).optional().default(1).describe("Cursor opacity (0-1)"), + label: external_exports.string().optional().describe("Label to display with cursor (usually username)"), + showLabel: external_exports.boolean().optional().default(true).describe("Whether to show label"), + pulseOnUpdate: external_exports.boolean().optional().default(true).describe("Whether to pulse when cursor moves") +}); +var CursorSelectionSchema = external_exports.object({ + anchor: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Anchor line number"), + column: external_exports.number().int().nonnegative().describe("Anchor column number") + }).describe("Selection anchor (start point)"), + focus: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Focus line number"), + column: external_exports.number().int().nonnegative().describe("Focus column number") + }).describe("Selection focus (end point)"), + direction: external_exports.enum(["forward", "backward"]).optional().describe("Selection direction") +}); +var CollaborativeCursorSchema = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + documentId: external_exports.string().describe("Document identifier"), + userName: external_exports.string().describe("Display name of user"), + position: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Cursor line number (0-indexed)"), + column: external_exports.number().int().nonnegative().describe("Cursor column number (0-indexed)") + }).describe("Current cursor position"), + selection: CursorSelectionSchema.optional().describe("Current text selection"), + style: CursorStyleSchema.describe("Visual style for this cursor"), + isTyping: external_exports.boolean().optional().default(false).describe("Whether user is currently typing"), + lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last cursor update"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional cursor metadata") +}); +var CursorUpdateSchema = external_exports.object({ + position: external_exports.object({ + line: external_exports.number().int().nonnegative(), + column: external_exports.number().int().nonnegative() + }).optional().describe("Updated cursor position"), + selection: CursorSelectionSchema.optional().describe("Updated selection"), + isTyping: external_exports.boolean().optional().describe("Updated typing state"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") +}); +var UserActivityStatus = external_exports.enum([ + "active", + // User is actively editing + "idle", + // User is idle but connected + "viewing", + // User is viewing but not editing + "disconnected" + // User is disconnected +]); +var AwarenessUserStateSchema = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + userName: external_exports.string().describe("Display name"), + userAvatar: external_exports.string().optional().describe("User avatar URL"), + status: UserActivityStatus.describe("Current activity status"), + currentDocument: external_exports.string().optional().describe("Document ID user is currently editing"), + currentView: external_exports.string().optional().describe("Current view/page user is on"), + lastActivity: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), + joinedAt: external_exports.string().datetime().describe("ISO 8601 datetime when user joined session"), + permissions: external_exports.array(external_exports.string()).optional().describe("User permissions in this session"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional user state metadata") +}); +var AwarenessSessionSchema = external_exports.object({ + sessionId: external_exports.string().uuid().describe("Session identifier"), + documentId: external_exports.string().optional().describe("Document ID this session is for"), + users: external_exports.array(AwarenessUserStateSchema).describe("Active users in session"), + startedAt: external_exports.string().datetime().describe("ISO 8601 datetime when session started"), + lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last update"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Session metadata") +}); +var AwarenessUpdateSchema = external_exports.object({ + status: UserActivityStatus.optional().describe("Updated status"), + currentDocument: external_exports.string().optional().describe("Updated current document"), + currentView: external_exports.string().optional().describe("Updated current view"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") +}); +var AwarenessEventSchema = external_exports.object({ + eventId: external_exports.string().uuid().describe("Event identifier"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + eventType: external_exports.enum([ + "user.joined", + "user.left", + "user.updated", + "session.created", + "session.ended" + ]).describe("Type of awareness event"), + userId: external_exports.string().optional().describe("User involved in event"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of event"), + payload: external_exports.unknown().describe("Event payload") +}); +var CollaborationMode = external_exports.enum([ + "ot", + // Operational Transformation + "crdt", + // CRDT-based + "lock", + // Pessimistic locking (turn-based) + "hybrid" + // Hybrid approach +]); +var CollaborationSessionConfigSchema = external_exports.object({ + mode: CollaborationMode.describe("Collaboration mode to use"), + enableCursorSharing: external_exports.boolean().optional().default(true).describe("Enable cursor sharing"), + enablePresence: external_exports.boolean().optional().default(true).describe("Enable presence tracking"), + enableAwareness: external_exports.boolean().optional().default(true).describe("Enable awareness state"), + maxUsers: external_exports.number().int().positive().optional().describe("Maximum concurrent users"), + idleTimeout: external_exports.number().int().positive().optional().default(3e5).describe("Idle timeout in milliseconds"), + conflictResolution: external_exports.enum(["ot", "crdt", "manual"]).optional().default("ot").describe("Conflict resolution strategy"), + persistence: external_exports.boolean().optional().default(true).describe("Enable operation persistence"), + snapshot: external_exports.object({ + enabled: external_exports.boolean().describe("Enable periodic snapshots"), + interval: external_exports.number().int().positive().describe("Snapshot interval in milliseconds") + }).optional().describe("Snapshot configuration") +}); +var CollaborationSessionSchema = external_exports.object({ + sessionId: external_exports.string().uuid().describe("Session identifier"), + documentId: external_exports.string().describe("Document identifier"), + config: CollaborationSessionConfigSchema.describe("Session configuration"), + users: external_exports.array(AwarenessUserStateSchema).describe("Active users"), + cursors: external_exports.array(CollaborativeCursorSchema).describe("Active cursors"), + version: external_exports.number().int().nonnegative().describe("Current document version"), + operations: external_exports.array(external_exports.union([OTOperationSchema, TextCRDTOperationSchema])).optional().describe("Recent operations"), + createdAt: external_exports.string().datetime().describe("ISO 8601 datetime when session was created"), + lastActivity: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), + status: external_exports.enum(["active", "idle", "ended"]).describe("Session status") +}); +var MetadataScopeSchema = external_exports.enum([ + "system", + // Defined in Code (Files). Read-only at runtime. Upgraded via deployment. + "platform", + // Defined in DB (Global). admin-configured. Overrides system. + "user" + // Defined in DB (Personal). User-configured. Overrides platform/system. +]); +var MetadataStateSchema = external_exports.enum([ + "draft", + // Work in progress, not active + "active", + // Live and running + "archived", + // Soft deleted + "deprecated" + // Running but flagged for removal +]); +var MetadataRecordSchema = external_exports.object({ + /** Primary Key (UUID) */ + id: external_exports.string(), + /** + * Machine Name + * The unique identifier used in code references (e.g. "account_list_view"). + */ + name: external_exports.string(), + /** + * Metadata Type + * e.g. "object", "view", "permission_set", "flow" + */ + type: external_exports.string(), + /** + * Namespace / Module + * Groups metadata into packages (e.g. "crm", "finance", "core"). + */ + namespace: external_exports.string().default("default"), + /** + * Package Ownership Reference + * Links this metadata record to the package that delivered it. + * When set, the record is "managed" by the package and should not be + * directly edited — customizations go through the overlay system. + * Null/undefined means the record was created independently (not from a package). + */ + packageId: external_exports.string().optional().describe("Package ID that owns/delivered this metadata"), + /** + * Managed By Indicator + * Determines who controls this metadata record's lifecycle. + * - "package": Delivered and upgraded by a plugin package (read-only base) + * - "platform": Created by platform admin via UI + * - "user": Created by end user + */ + managedBy: external_exports.enum(["package", "platform", "user"]).optional().describe("Who manages this metadata record lifecycle"), + /** + * Ownership differentiation + */ + scope: MetadataScopeSchema.default("platform"), + /** + * The Payload + * Stores the actual configuration JSON. + * This field holds the value of `ViewSchema`, `ObjectSchema`, etc. + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()), + /** + * Extension / Merge Strategy + * If this record overrides a system record, how should it be applied? + */ + extends: external_exports.string().optional().describe("Name of the parent metadata to extend/override"), + strategy: external_exports.enum(["merge", "replace"]).default("merge"), + /** Owner (for user-scope items) */ + owner: external_exports.string().optional(), + /** State */ + state: MetadataStateSchema.default("active"), + /** Tenant ID for multi-tenant isolation */ + tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant isolation"), + /** Version number for optimistic concurrency */ + version: external_exports.number().default(1).describe("Record version for optimistic concurrency control"), + /** Checksum for change detection */ + checksum: external_exports.string().optional().describe("Content checksum for change detection"), + /** Source origin marker */ + source: external_exports.enum(["filesystem", "database", "api", "migration"]).optional().describe("Origin of this metadata record"), + /** Classification tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Classification tags for filtering and grouping"), + /** Package Publishing */ + publishedDefinition: external_exports.unknown().optional().describe("Snapshot of the last published definition"), + publishedAt: external_exports.string().datetime().optional().describe("When this metadata was last published"), + publishedBy: external_exports.string().optional().describe("Who published this version"), + /** Audit */ + createdBy: external_exports.string().optional(), + createdAt: external_exports.string().datetime().optional().describe("Creation timestamp"), + updatedBy: external_exports.string().optional(), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp") +}); +var PackagePublishResultSchema = external_exports.object({ + success: external_exports.boolean().describe("Whether the publish succeeded"), + packageId: external_exports.string().describe("The package ID that was published"), + version: external_exports.number().int().describe("New version number after publish"), + publishedAt: external_exports.string().datetime().describe("Publish timestamp"), + itemsPublished: external_exports.number().int().describe("Total metadata items published"), + validationErrors: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type that failed validation"), + name: external_exports.string().describe("Item name that failed validation"), + message: external_exports.string().describe("Validation error message") + })).optional().describe("Validation errors if publish failed") +}); +var MetadataFormatSchema = external_exports.enum([ + "json", + "yaml", + "yml", + "ts", + "js", + "typescript", + "javascript" + // Aliases +]); +var MetadataStatsSchema = external_exports.object({ + path: external_exports.string().optional(), + size: external_exports.number().optional(), + mtime: external_exports.string().datetime().optional(), + hash: external_exports.string().optional(), + etag: external_exports.string().optional(), + // Required by local cache + modifiedAt: external_exports.string().datetime().optional(), + // Alias for mtime + format: MetadataFormatSchema.optional() + // Required for serialization +}); +var MetadataLoaderContractSchema = external_exports.object({ + name: external_exports.string(), + protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Loader protocol identifier"), + description: external_exports.string().optional(), + supportedFormats: external_exports.array(external_exports.string()).optional(), + supportsWatch: external_exports.boolean().optional(), + supportsWrite: external_exports.boolean().optional(), + supportsCache: external_exports.boolean().optional(), + capabilities: external_exports.object({ + read: external_exports.boolean().default(true), + write: external_exports.boolean().default(false), + watch: external_exports.boolean().default(false), + list: external_exports.boolean().default(true) + }) +}); +var MetadataLoadOptionsSchema = external_exports.object({ + scope: MetadataScopeSchema.optional(), + namespace: external_exports.string().optional(), + raw: external_exports.boolean().optional().describe("Return raw file content instead of parsed JSON"), + cache: external_exports.boolean().optional(), + useCache: external_exports.boolean().optional(), + // Alias for cache + validate: external_exports.boolean().optional(), + ifNoneMatch: external_exports.string().optional(), + // For caching + recursive: external_exports.boolean().optional(), + limit: external_exports.number().optional(), + patterns: external_exports.array(external_exports.string()).optional(), + loader: external_exports.string().optional().describe("Specific loader to use (e.g. filesystem, database)") +}); +var MetadataLoadResultSchema = external_exports.object({ + data: external_exports.unknown(), + stats: MetadataStatsSchema.optional(), + format: MetadataFormatSchema.optional(), + source: external_exports.string().optional(), + // File path or URL + fromCache: external_exports.boolean().optional(), + etag: external_exports.string().optional(), + notModified: external_exports.boolean().optional(), + loadTime: external_exports.number().optional() +}); +var MetadataSaveOptionsSchema = external_exports.object({ + format: MetadataFormatSchema.optional(), + create: external_exports.boolean().default(true), + overwrite: external_exports.boolean().default(true), + path: external_exports.string().optional(), + prettify: external_exports.boolean().optional(), + indent: external_exports.number().optional(), + sortKeys: external_exports.boolean().optional(), + backup: external_exports.boolean().optional(), + atomic: external_exports.boolean().optional(), + loader: external_exports.string().optional().describe("Specific loader to use (e.g. filesystem, database)") +}); +var MetadataSaveResultSchema = external_exports.object({ + success: external_exports.boolean(), + path: external_exports.string().optional(), + stats: MetadataStatsSchema.optional(), + etag: external_exports.string().optional(), + size: external_exports.number().optional(), + saveTime: external_exports.number().optional(), + backupPath: external_exports.string().optional() +}); +var MetadataWatchEventSchema = external_exports.object({ + type: external_exports.enum(["add", "change", "unlink", "added", "changed", "deleted"]), + path: external_exports.string(), + name: external_exports.string().optional(), + stats: MetadataStatsSchema.optional(), + metadataType: external_exports.string().optional(), + data: external_exports.unknown().optional(), + timestamp: external_exports.string().datetime().optional() +}); +var MetadataCollectionInfoSchema = external_exports.object({ + type: external_exports.string(), + count: external_exports.number(), + namespaces: external_exports.array(external_exports.string()) +}); +var MetadataExportOptionsSchema = external_exports.object({ + types: external_exports.array(external_exports.string()).optional(), + namespaces: external_exports.array(external_exports.string()).optional(), + output: external_exports.string().describe("Output directory or file"), + format: MetadataFormatSchema.default("json") +}); +var MetadataImportOptionsSchema = external_exports.object({ + source: external_exports.string().describe("Input directory or file"), + strategy: external_exports.enum(["merge", "replace", "skip"]).default("merge"), + validate: external_exports.boolean().default(true) +}); +var MetadataFallbackStrategySchema = external_exports.enum([ + "filesystem", + // Fall back to filesystem-based loading + "memory", + // Fall back to in-memory storage + "none" + // No fallback — fail immediately +]); +var MetadataSourceSchema = external_exports.enum([ + "filesystem", + // Loaded from local files + "database", + // Loaded from database via datasource + "api", + // Loaded from remote API + "migration" + // Created during a migration process +]); +var MetadataManagerConfigSchema = external_exports.object({ + /** + * Datasource Name Reference + * References a DatasourceSchema.name (e.g. 'default'). + * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. + * When provided, metadata is persisted to a database table. + */ + datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), + /** + * Metadata Table Name + * The database table used for metadata storage when datasource is configured. + */ + tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), + /** + * Fallback Strategy + * Determines behavior when the primary datasource is unavailable. + */ + fallback: MetadataFallbackStrategySchema.default("none").describe("Fallback strategy when datasource is unavailable"), + /** + * Root directory for metadata (for filesystem loaders) + */ + rootDir: external_exports.string().optional().describe("Root directory for filesystem-based metadata"), + /** + * Enabled serialization formats + */ + formats: external_exports.array(MetadataFormatSchema).optional().describe("Enabled metadata formats"), + /** + * Enable file watching + */ + watch: external_exports.boolean().optional().describe("Enable file watching for filesystem loaders"), + /** + * Cache configuration + */ + cache: external_exports.boolean().optional().describe("Enable metadata caching"), + /** + * Watch options + */ + watchOptions: external_exports.object({ + ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), + persistent: external_exports.boolean().default(true).describe("Keep process running") + }).optional().describe("File watcher options") +}); +var MetadataHistoryRecordSchema = external_exports.object({ + /** Primary Key (UUID) */ + id: external_exports.string(), + /** Reference to the parent metadata record ID */ + metadataId: external_exports.string().describe("Foreign key to sys_metadata.id"), + /** + * Machine Name + * Denormalized from parent for easier querying. + */ + name: external_exports.string(), + /** + * Metadata Type + * Denormalized from parent for easier querying. + */ + type: external_exports.string(), + /** + * Version Number + * Snapshot of the metadata version at this point in history. + */ + version: external_exports.number().describe("Version number at this snapshot"), + /** + * Operation Type + * Indicates what kind of change triggered this history record. + */ + operationType: external_exports.enum(["create", "update", "publish", "revert", "delete"]).describe("Type of operation that created this history entry"), + /** + * Historical Metadata Snapshot + * Full JSON payload of the metadata definition at this version. + * May be stored as a raw JSON string in the history table, or as a parsed object + * in higher-level APIs. When `includeMetadata` is false, this field is null. + */ + metadata: external_exports.union([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown())]).nullable().optional().describe("Snapshot of metadata definition at this version (raw JSON string or parsed object)"), + /** + * Content Checksum + * SHA-256 checksum of the normalized metadata JSON for change detection. + */ + checksum: external_exports.string().describe("SHA-256 checksum of metadata content"), + /** + * Previous Checksum + * Checksum of the previous version for diff optimization. + */ + previousChecksum: external_exports.string().optional().describe("Checksum of the previous version"), + /** + * Change Note + * Human-readable description of what changed in this version. + */ + changeNote: external_exports.string().optional().describe("Description of changes made in this version"), + /** Tenant ID for multi-tenant isolation */ + tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant isolation"), + /** Audit: who made this change */ + recordedBy: external_exports.string().optional().describe("User who made this change"), + /** Audit: when was this version recorded */ + recordedAt: external_exports.string().datetime().describe("Timestamp when this version was recorded") +}); +var MetadataHistoryQueryOptionsSchema = external_exports.object({ + /** Limit number of history records returned */ + limit: external_exports.number().int().positive().optional().describe("Maximum number of history records to return"), + /** Offset for pagination */ + offset: external_exports.number().int().nonnegative().optional().describe("Number of records to skip"), + /** Only return versions after this timestamp */ + since: external_exports.string().datetime().optional().describe("Only return history after this timestamp"), + /** Only return versions before this timestamp */ + until: external_exports.string().datetime().optional().describe("Only return history before this timestamp"), + /** Filter by operation type */ + operationType: external_exports.enum(["create", "update", "publish", "revert", "delete"]).optional().describe("Filter by operation type"), + /** Include full metadata payload in results (default: true) */ + includeMetadata: external_exports.boolean().optional().default(true).describe("Include full metadata payload") +}); +var MetadataHistoryQueryResultSchema = external_exports.object({ + /** Array of history records */ + records: external_exports.array(MetadataHistoryRecordSchema), + /** Total number of history records (for pagination) */ + total: external_exports.number().int().nonnegative(), + /** Whether there are more records available */ + hasMore: external_exports.boolean() +}); +var MetadataDiffResultSchema = external_exports.object({ + /** Metadata type */ + type: external_exports.string(), + /** Metadata name */ + name: external_exports.string(), + /** Version 1 (older) */ + version1: external_exports.number(), + /** Version 2 (newer) */ + version2: external_exports.number(), + /** Checksum of version 1 */ + checksum1: external_exports.string(), + /** Checksum of version 2 */ + checksum2: external_exports.string(), + /** Whether the versions are identical */ + identical: external_exports.boolean(), + /** JSON patch operations to transform v1 into v2 */ + patch: external_exports.array(external_exports.unknown()).optional().describe("JSON patch operations"), + /** Human-readable diff summary */ + summary: external_exports.string().optional().describe("Human-readable summary of changes") +}); +var MetadataHistoryRetentionPolicySchema = external_exports.object({ + /** Maximum number of versions to keep per metadata item */ + maxVersions: external_exports.number().int().positive().optional().describe("Maximum number of versions to retain"), + /** Maximum age of history records in days */ + maxAgeDays: external_exports.number().int().positive().optional().describe("Maximum age of history records in days"), + /** Whether to enable automatic cleanup */ + autoCleanup: external_exports.boolean().default(false).describe("Enable automatic cleanup of old history"), + /** Cleanup interval in hours */ + cleanupIntervalHours: external_exports.number().int().positive().default(24).describe("How often to run cleanup (in hours)") +}); +var CoreServiceName = external_exports.enum([ + // Core Data & Metadata + "metadata", + // Object/Field Definitions + "data", + // CRUD & Query Engine + "auth", + // Authentication & Identity + // Infrastructure + "file-storage", + // Storage Driver (Local/S3) + "search", + // Search Engine (Elastic/Meili) + "cache", + // Cache Driver (Redis/Memory) + "queue", + // Job Queue (BullMQ/Redis) + // Advanced Capabilities + "automation", + // Flow & Script Engine + "graphql", + // GraphQL API Engine + "analytics", + // BI & Semantic Layer + "realtime", + // WebSocket & PubSub + "job", + // Background Job Manager + "notification", + // Email/Push/SMS + "ai", + // AI Engine (NLQ, Chat, Suggest, Insights) + "i18n", + // Internationalization Service + "ui", + // UI Metadata Service (View CRUD) + "workflow" + // Workflow State Machine Engine +]); +var ServiceCriticalitySchema = external_exports.enum([ + "required", + // System fails to start if missing (Exit Code 1) + "core", + // System warns if missing, functionality degraded (Warn) + "optional" + // System ignores if missing, feature disabled (Info) +]); +var ServiceRequirementDef = { + // Required: The kernel cannot function without these + data: "required", + // Core: Highly recommended, defaults to in-memory / no-op if missing + metadata: "core", + auth: "core", + // Core: Highly recommended, defaults to in-memory / no-op if missing + cache: "core", + queue: "core", + job: "core", + i18n: "core", + // Optional: Add-on capabilities + "file-storage": "optional", + search: "optional", + automation: "optional", + graphql: "optional", + analytics: "optional", + realtime: "optional", + notification: "optional", + ai: "optional", + ui: "optional", + workflow: "optional" +}; +var ServiceStatusSchema = external_exports.object({ + name: CoreServiceName, + enabled: external_exports.boolean(), + status: external_exports.enum(["running", "stopped", "degraded", "initializing"]), + version: external_exports.string().optional(), + provider: external_exports.string().optional().describe('Implementation provider (e.g. "s3" for storage)'), + features: external_exports.array(external_exports.string()).optional().describe("List of supported sub-features") +}); +var KernelServiceMapSchema = external_exports.record( + CoreServiceName, + external_exports.unknown().describe("Service Instance implementing the protocol interface") +); +var ServiceConfigSchema = external_exports.object({ + id: external_exports.string(), + name: CoreServiceName, + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var TenantIsolationLevel = external_exports.enum([ + "shared_schema", + // Shared DB, shared schema, row-level isolation (most economical) + "isolated_schema", + // Shared DB, separate schema per tenant (balanced) + "isolated_db" + // Separate database per tenant (maximum isolation) +]); +var DatabaseProviderSchema = external_exports.enum([ + "turso", + // Turso/libSQL (DB-per-Tenant, edge-native) + "postgres", + // PostgreSQL (traditional, self-hosted or managed) + "memory" + // In-memory (testing/development only) +]).describe("Database provider for tenant data"); +var TenantConnectionConfigSchema = external_exports.object({ + /** Database connection URL */ + url: external_exports.string().min(1).describe("Database connection URL"), + /** Authentication token (JWT for Turso, password for Postgres) */ + authToken: external_exports.string().optional().describe("Database auth token (encrypted at rest)"), + /** Turso database group name */ + group: external_exports.string().optional().describe("Turso database group name") +}).describe("Tenant database connection configuration"); +var TenantQuotaSchema = external_exports.object({ + /** + * Maximum number of users allowed for this tenant + */ + maxUsers: external_exports.number().int().positive().optional().describe("Maximum number of users"), + /** + * Maximum storage space in bytes + */ + maxStorage: external_exports.number().int().positive().optional().describe("Maximum storage in bytes"), + /** + * API rate limit (requests per minute) + */ + apiRateLimit: external_exports.number().int().positive().optional().describe("API requests per minute"), + /** + * Maximum number of custom objects the tenant can create + */ + maxObjects: external_exports.number().int().positive().optional().describe("Maximum number of custom objects"), + /** + * Maximum records per object/table + */ + maxRecordsPerObject: external_exports.number().int().positive().optional().describe("Maximum records per object"), + /** + * Maximum deployments allowed per day + */ + maxDeploymentsPerDay: external_exports.number().int().positive().optional().describe("Maximum deployments per day"), + /** + * Maximum storage in bytes + */ + maxStorageBytes: external_exports.number().int().positive().optional().describe("Maximum storage in bytes") +}); +var TenantUsageSchema = external_exports.object({ + /** Current number of custom objects */ + currentObjectCount: external_exports.number().int().min(0).default(0).describe("Current number of custom objects"), + /** Current total record count across all objects */ + currentRecordCount: external_exports.number().int().min(0).default(0).describe("Total records across all objects"), + /** Current storage usage in bytes */ + currentStorageBytes: external_exports.number().int().min(0).default(0).describe("Current storage usage in bytes"), + /** Deployments executed today */ + deploymentsToday: external_exports.number().int().min(0).default(0).describe("Deployments executed today"), + /** Current number of active users */ + currentUsers: external_exports.number().int().min(0).default(0).describe("Current number of active users"), + /** API requests in the current minute */ + apiRequestsThisMinute: external_exports.number().int().min(0).default(0).describe("API requests in the current minute"), + /** Last updated timestamp (ISO 8601) */ + lastUpdatedAt: external_exports.string().datetime().optional().describe("Last usage update time") +}).describe("Current tenant resource usage"); +var QuotaEnforcementResultSchema = external_exports.object({ + /** Whether the operation is allowed */ + allowed: external_exports.boolean().describe("Whether the operation is within quota"), + /** Quota that would be exceeded (if not allowed) */ + exceededQuota: external_exports.string().optional().describe("Name of the exceeded quota"), + /** Current usage value */ + currentUsage: external_exports.number().optional().describe("Current usage value"), + /** Quota limit value */ + limit: external_exports.number().optional().describe("Quota limit"), + /** Human-readable message */ + message: external_exports.string().optional().describe("Human-readable quota message") +}).describe("Quota enforcement check result"); +var TenantSchema = external_exports.object({ + /** + * Unique tenant identifier + */ + id: external_exports.string().describe("Unique tenant identifier"), + /** + * Tenant display name + */ + name: external_exports.string().describe("Tenant display name"), + /** + * Data isolation level + */ + isolationLevel: TenantIsolationLevel, + /** + * Database provider for this tenant + */ + databaseProvider: DatabaseProviderSchema.optional().describe("Database provider"), + /** + * Database connection configuration (encrypted at rest) + */ + connectionConfig: TenantConnectionConfigSchema.optional().describe("Database connection config"), + /** + * Current provisioning status + */ + provisioningStatus: external_exports.enum([ + "provisioning", + "active", + "suspended", + "failed", + "destroying" + ]).optional().describe("Current provisioning lifecycle status"), + /** + * Tenant subscription plan + */ + plan: external_exports.enum(["free", "pro", "enterprise"]).optional().describe("Subscription plan"), + /** + * Custom configuration values + */ + customizations: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom configuration values"), + /** + * Resource quotas + */ + quotas: TenantQuotaSchema.optional() +}); +var RowLevelIsolationStrategySchema = external_exports.object({ + strategy: external_exports.literal("shared_schema").describe("Row-level isolation strategy"), + /** + * Database configuration for row-level isolation + */ + database: external_exports.object({ + /** + * Whether to enable Row-Level Security (RLS) + */ + enableRLS: external_exports.boolean().default(true).describe("Enable PostgreSQL Row-Level Security"), + /** + * Tenant context setting method + */ + contextMethod: external_exports.enum([ + "session_variable", + // SET app.current_tenant = 'tenant_123' + "search_path", + // SET search_path = tenant_123, public + "application_name" + // SET application_name = 'tenant_123' + ]).default("session_variable").describe("How to set tenant context"), + /** + * Session variable name for tenant context + */ + contextVariable: external_exports.string().default("app.current_tenant").describe("Session variable name"), + /** + * Whether to validate tenant_id at application level + */ + applicationValidation: external_exports.boolean().default(true).describe("Application-level tenant validation") + }).optional().describe("Database configuration"), + /** + * Performance optimization settings + */ + performance: external_exports.object({ + /** + * Whether to use partial indexes for tenant_id + */ + usePartialIndexes: external_exports.boolean().default(true).describe("Use partial indexes per tenant"), + /** + * Whether to use table partitioning + */ + usePartitioning: external_exports.boolean().default(false).describe("Use table partitioning by tenant_id"), + /** + * Connection pool size per tenant + */ + poolSizePerTenant: external_exports.number().int().positive().optional().describe("Connection pool size per tenant") + }).optional().describe("Performance settings") +}); +var SchemaLevelIsolationStrategySchema = external_exports.object({ + strategy: external_exports.literal("isolated_schema").describe("Schema-level isolation strategy"), + /** + * Schema configuration + */ + schema: external_exports.object({ + /** + * Schema naming pattern + * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) + * The tenant_id will be sanitized before substitution to prevent SQL injection + */ + namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Schema naming pattern"), + /** + * Whether to include public schema in search_path + */ + includePublicSchema: external_exports.boolean().default(true).describe("Include public schema"), + /** + * Default schema for shared resources + */ + sharedSchema: external_exports.string().default("public").describe("Schema for shared resources"), + /** + * Whether to automatically create schema on tenant creation + */ + autoCreateSchema: external_exports.boolean().default(true).describe("Auto-create schema") + }).optional().describe("Schema configuration"), + /** + * Migration configuration + */ + migrations: external_exports.object({ + /** + * Migration strategy + */ + strategy: external_exports.enum([ + "parallel", + // Run migrations on all schemas in parallel + "sequential", + // Run migrations one schema at a time + "on_demand" + // Run migrations when tenant accesses system + ]).default("parallel").describe("Migration strategy"), + /** + * Maximum concurrent migrations + */ + maxConcurrent: external_exports.number().int().positive().default(10).describe("Max concurrent migrations"), + /** + * Whether to rollback on first failure + */ + rollbackOnError: external_exports.boolean().default(true).describe("Rollback on error") + }).optional().describe("Migration configuration"), + /** + * Performance optimization settings + */ + performance: external_exports.object({ + /** + * Whether to use connection pooling per schema + */ + poolPerSchema: external_exports.boolean().default(false).describe("Separate pool per schema"), + /** + * Schema cache TTL in seconds + */ + schemaCacheTTL: external_exports.number().int().positive().default(3600).describe("Schema cache TTL") + }).optional().describe("Performance settings") +}); +var DatabaseLevelIsolationStrategySchema = external_exports.object({ + strategy: external_exports.literal("isolated_db").describe("Database-level isolation strategy"), + /** + * Database configuration + */ + database: external_exports.object({ + /** + * Database naming pattern + * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) + * The tenant_id will be sanitized before substitution to prevent SQL injection + */ + namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Database naming pattern"), + /** + * Database server/cluster assignment strategy + */ + serverStrategy: external_exports.enum([ + "shared", + // All tenant databases on same server + "sharded", + // Tenant databases distributed across servers + "dedicated" + // Each tenant gets dedicated server (enterprise) + ]).default("shared").describe("Server assignment strategy"), + /** + * Whether to use separate credentials per tenant + */ + separateCredentials: external_exports.boolean().default(true).describe("Separate credentials per tenant"), + /** + * Whether to automatically create database on tenant creation + */ + autoCreateDatabase: external_exports.boolean().default(true).describe("Auto-create database") + }).optional().describe("Database configuration"), + /** + * Connection pooling configuration + */ + connectionPool: external_exports.object({ + /** + * Pool size per tenant database + */ + poolSize: external_exports.number().int().positive().default(10).describe("Connection pool size"), + /** + * Maximum number of tenant pools to keep active + */ + maxActivePools: external_exports.number().int().positive().default(100).describe("Max active pools"), + /** + * Idle pool timeout in seconds + */ + idleTimeout: external_exports.number().int().positive().default(300).describe("Idle pool timeout"), + /** + * Whether to use connection pooler (PgBouncer, etc.) + */ + usePooler: external_exports.boolean().default(true).describe("Use connection pooler") + }).optional().describe("Connection pool configuration"), + /** + * Backup and restore configuration + */ + backup: external_exports.object({ + /** + * Backup strategy per tenant + */ + strategy: external_exports.enum([ + "individual", + // Separate backup per tenant + "consolidated", + // Combined backup with all tenants + "on_demand" + // Backup only when requested + ]).default("individual").describe("Backup strategy"), + /** + * Backup frequency in hours + */ + frequencyHours: external_exports.number().int().positive().default(24).describe("Backup frequency"), + /** + * Retention period in days + */ + retentionDays: external_exports.number().int().positive().default(30).describe("Backup retention days") + }).optional().describe("Backup configuration"), + /** + * Encryption configuration + */ + encryption: external_exports.object({ + /** + * Whether to use per-tenant encryption keys + */ + perTenantKeys: external_exports.boolean().default(false).describe("Per-tenant encryption keys"), + /** + * Encryption algorithm + */ + algorithm: external_exports.string().default("AES-256-GCM").describe("Encryption algorithm"), + /** + * Key management service + */ + keyManagement: external_exports.enum(["aws_kms", "azure_key_vault", "gcp_kms", "hashicorp_vault", "custom"]).optional().describe("Key management service") + }).optional().describe("Encryption configuration") +}); +var TenantIsolationConfigSchema = external_exports.discriminatedUnion("strategy", [ + RowLevelIsolationStrategySchema, + SchemaLevelIsolationStrategySchema, + DatabaseLevelIsolationStrategySchema +]); +var TenantSecurityPolicySchema = external_exports.object({ + /** + * Encryption requirements + */ + encryption: external_exports.object({ + /** + * Require encryption at rest + */ + atRest: external_exports.boolean().default(true).describe("Require encryption at rest"), + /** + * Require encryption in transit + */ + inTransit: external_exports.boolean().default(true).describe("Require encryption in transit"), + /** + * Require field-level encryption for sensitive data + */ + fieldLevel: external_exports.boolean().default(false).describe("Require field-level encryption") + }).optional().describe("Encryption requirements"), + /** + * Access control requirements + */ + accessControl: external_exports.object({ + /** + * Require multi-factor authentication + */ + requireMFA: external_exports.boolean().default(false).describe("Require MFA"), + /** + * Require SSO/SAML authentication + */ + requireSSO: external_exports.boolean().default(false).describe("Require SSO"), + /** + * IP whitelist + */ + ipWhitelist: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses"), + /** + * Session timeout in seconds + */ + sessionTimeout: external_exports.number().int().positive().default(3600).describe("Session timeout") + }).optional().describe("Access control requirements"), + /** + * Audit and compliance requirements + */ + compliance: external_exports.object({ + /** + * Compliance standards to enforce + */ + standards: external_exports.array(external_exports.enum([ + "sox", + "hipaa", + "gdpr", + "pci_dss", + "iso_27001", + "fedramp" + ])).optional().describe("Compliance standards"), + /** + * Require audit logging for all operations + */ + requireAuditLog: external_exports.boolean().default(true).describe("Require audit logging"), + /** + * Audit log retention period in days + */ + auditRetentionDays: external_exports.number().int().positive().default(365).describe("Audit retention days"), + /** + * Data residency requirements + */ + dataResidency: external_exports.object({ + /** + * Required geographic region + */ + region: external_exports.string().optional().describe("Required region (e.g., US, EU, APAC)"), + /** + * Prohibited regions + */ + excludeRegions: external_exports.array(external_exports.string()).optional().describe("Prohibited regions") + }).optional().describe("Data residency requirements") + }).optional().describe("Compliance requirements") +}); +var LicenseMetricType = external_exports.enum([ + "boolean", + // Feature Flag (Enabled/Disabled) + "counter", + // Usage Count (e.g. API Calls, Records Created) - Accumulates + "gauge" + // Current Level (e.g. Storage Used, Users Active) - Point in time +]).describe("License metric type"); +var FeatureSchema = external_exports.object({ + code: external_exports.string().regex(/^[a-z_][a-z0-9_.]*$/).describe("Feature code (e.g. core.api_access)"), + label: external_exports.string(), + description: external_exports.string().optional(), + type: LicenseMetricType.default("boolean"), + /** For counters/gauges */ + unit: external_exports.enum(["count", "bytes", "seconds", "percent"]).optional(), + /** Dependencies (e.g. 'audit_log' requires 'enterprise_tier') */ + requires: external_exports.array(external_exports.string()).optional() +}); +var PlanSchema = external_exports.object({ + code: external_exports.string().describe("Plan code (e.g. pro_v1)"), + label: external_exports.string(), + active: external_exports.boolean().default(true), + /** Feature Entitlements */ + features: external_exports.array(external_exports.string()).describe("List of enabled boolean features"), + /** Limit Quotas */ + limits: external_exports.record(external_exports.string(), external_exports.number()).describe("Map of metric codes to limit values (e.g. { storage_gb: 10 })"), + /** Pricing (Optional Metadata) */ + currency: external_exports.string().default("USD").optional(), + priceMonthly: external_exports.number().optional(), + priceYearly: external_exports.number().optional() +}); +var LicenseSchema = external_exports.object({ + /** Identity */ + spaceId: external_exports.string().describe("Target Space ID"), + planCode: external_exports.string(), + /** Validity */ + issuedAt: external_exports.string().datetime(), + expiresAt: external_exports.string().datetime().optional(), + // Null = Perpetual + /** Status */ + status: external_exports.enum(["active", "expired", "suspended", "trial"]), + /** Overrides (Specific to this space, exceeding the plan) */ + customFeatures: external_exports.array(external_exports.string()).optional(), + customLimits: external_exports.record(external_exports.string(), external_exports.number()).optional(), + /** Authorized Add-ons */ + plugins: external_exports.array(external_exports.string()).optional().describe("List of enabled plugin package IDs"), + /** Signature */ + signature: external_exports.string().optional().describe("Cryptographic signature of the license") +}); +var RegistrySyncPolicySchema = external_exports.enum([ + "manual", + // Manual synchronization only + "auto", + // Automatic synchronization + "proxy" + // Proxy requests to upstream without caching +]).describe("Registry synchronization strategy"); +var RegistryUpstreamSchema = external_exports.object({ + /** + * Upstream registry URL + */ + url: external_exports.string().url().describe("Upstream registry endpoint"), + /** + * Synchronization policy + */ + syncPolicy: RegistrySyncPolicySchema.default("auto"), + /** + * Sync interval in seconds (for auto sync) + */ + syncInterval: external_exports.number().int().min(60).optional().describe("Auto-sync interval in seconds"), + /** + * Authentication credentials + */ + auth: external_exports.object({ + type: external_exports.enum(["none", "basic", "bearer", "api-key", "oauth2"]).default("none"), + username: external_exports.string().optional(), + password: external_exports.string().optional(), + token: external_exports.string().optional(), + apiKey: external_exports.string().optional() + }).optional(), + /** + * TLS/SSL configuration + */ + tls: external_exports.object({ + enabled: external_exports.boolean().default(true), + verifyCertificate: external_exports.boolean().default(true), + certificate: external_exports.string().optional(), + privateKey: external_exports.string().optional() + }).optional(), + /** + * Timeout settings + */ + timeout: external_exports.number().int().min(1e3).default(3e4).describe("Request timeout in milliseconds"), + /** + * Retry configuration + */ + retry: external_exports.object({ + maxAttempts: external_exports.number().int().min(0).default(3), + backoff: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential") + }).optional() +}); +var RegistryConfigSchema = external_exports.object({ + /** + * Registry type + */ + type: external_exports.enum([ + "public", + // Public marketplace (e.g., plugins.objectstack.com) + "private", + // Private enterprise registry + "hybrid" + // Hybrid with upstream federation + ]).describe("Registry deployment type"), + /** + * Upstream registries (for hybrid/private registries) + */ + upstream: external_exports.array(RegistryUpstreamSchema).optional().describe("Upstream registries to sync from or proxy to"), + /** + * Scopes managed by this registry + */ + scope: external_exports.array(external_exports.string()).optional().describe("npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)"), + /** + * Default scope for new plugins + */ + defaultScope: external_exports.string().optional().describe("Default scope prefix for new plugins"), + /** + * Registry storage configuration + */ + storage: external_exports.object({ + /** + * Storage backend type + */ + backend: external_exports.enum(["local", "s3", "gcs", "azure-blob", "oss"]).default("local"), + /** + * Storage path or bucket name + */ + path: external_exports.string().optional(), + /** + * Credentials + */ + credentials: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional(), + /** + * Registry visibility + */ + visibility: external_exports.enum(["public", "private", "internal"]).default("private").describe("Who can access this registry"), + /** + * Access control + */ + accessControl: external_exports.object({ + /** + * Require authentication for read + */ + requireAuthForRead: external_exports.boolean().default(false), + /** + * Require authentication for write + */ + requireAuthForWrite: external_exports.boolean().default(true), + /** + * Allowed users/teams + */ + allowedPrincipals: external_exports.array(external_exports.string()).optional() + }).optional(), + /** + * Caching configuration + */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(true), + ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), + maxSize: external_exports.number().int().optional().describe("Maximum cache size in bytes") + }).optional(), + /** + * Mirroring configuration (for high availability) + */ + mirrors: external_exports.array(external_exports.object({ + url: external_exports.string().url(), + priority: external_exports.number().int().min(1).default(1) + })).optional().describe("Mirror registries for redundancy") +}); +var TenantProvisioningStatusEnum = external_exports.enum([ + "provisioning", + // Database creation in progress + "active", + // Fully provisioned and operational + "suspended", + // Temporarily disabled (billing, policy) + "failed", + // Provisioning failed (requires retry or manual intervention) + "destroying" + // Deletion in progress +]).describe("Tenant provisioning lifecycle status"); +var TenantPlanSchema = external_exports.enum([ + "free", + // Free tier with limited quotas + "pro", + // Professional tier with higher quotas + "enterprise" + // Enterprise tier with custom quotas and SLAs +]).describe("Tenant subscription plan"); +var TenantRegionSchema = external_exports.enum([ + "us-east", + // US East (Virginia) + "us-west", + // US West (Oregon) + "eu-west", + // EU West (Ireland) + "eu-central", + // EU Central (Frankfurt) + "ap-southeast", + // Asia Pacific (Singapore) + "ap-northeast" + // Asia Pacific (Tokyo) +]).describe("Available deployment region"); +var ProvisioningStepSchema = external_exports.object({ + /** Step identifier */ + name: external_exports.string().min(1).describe("Step name (e.g., create_database, sync_schema)"), + /** Step execution status */ + status: external_exports.enum(["pending", "running", "completed", "failed", "skipped"]).describe("Step status"), + /** When the step started (ISO 8601) */ + startedAt: external_exports.string().datetime().optional().describe("Step start time"), + /** When the step completed (ISO 8601) */ + completedAt: external_exports.string().datetime().optional().describe("Step completion time"), + /** Duration in milliseconds */ + durationMs: external_exports.number().int().min(0).optional().describe("Step duration in ms"), + /** Error message if the step failed */ + error: external_exports.string().optional().describe("Error message on failure") +}).describe("Individual provisioning step status"); +var TenantProvisioningRequestSchema = external_exports.object({ + /** Organization ID that owns this tenant */ + orgId: external_exports.string().min(1).describe("Organization ID"), + /** Requested subscription plan */ + plan: TenantPlanSchema.default("free"), + /** Preferred deployment region */ + region: TenantRegionSchema.default("us-east"), + /** Optional tenant display name */ + displayName: external_exports.string().optional().describe("Tenant display name"), + /** Optional initial admin user email */ + adminEmail: external_exports.string().email().optional().describe("Initial admin user email"), + /** Optional metadata to attach to the tenant */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata") +}).describe("Tenant provisioning request"); +var TenantProvisioningResultSchema = external_exports.object({ + /** Unique tenant identifier */ + tenantId: external_exports.string().min(1).describe("Provisioned tenant ID"), + /** Database connection URL (libsql:// or https://) */ + connectionUrl: external_exports.string().min(1).describe("Database connection URL"), + /** Current provisioning status */ + status: TenantProvisioningStatusEnum, + /** Deployment region */ + region: TenantRegionSchema, + /** Active subscription plan */ + plan: TenantPlanSchema, + /** Provisioning pipeline steps with status */ + steps: external_exports.array(ProvisioningStepSchema).default([]).describe("Pipeline step statuses"), + /** Total provisioning duration in milliseconds */ + totalDurationMs: external_exports.number().int().min(0).optional().describe("Total provisioning duration"), + /** Provisioned timestamp (ISO 8601) */ + provisionedAt: external_exports.string().datetime().optional().describe("Provisioning completion time"), + /** Error message if provisioning failed */ + error: external_exports.string().optional().describe("Error message on failure") +}).describe("Tenant provisioning result"); +var DeployStatusEnum = external_exports.enum([ + "validating", + // Zod schema validation in progress + "diffing", + // Comparing desired state vs current state + "migrating", + // Executing DDL statements + "registering", + // Updating metadata registry + "ready", + // Deployment complete and live + "failed", + // Deployment failed at some stage + "rolling_back" + // Rollback in progress +]).describe("Deployment lifecycle status"); +var SchemaChangeSchema = external_exports.object({ + /** Type of entity being changed */ + entityType: external_exports.enum(["object", "field", "index", "view", "flow", "permission"]).describe("Entity type"), + /** Name of the entity */ + entityName: external_exports.string().min(1).describe("Entity name"), + /** Parent entity name (e.g., object name for a field change) */ + parentEntity: external_exports.string().optional().describe("Parent entity name"), + /** Type of change */ + changeType: external_exports.enum(["added", "modified", "removed"]).describe("Change type"), + /** Previous value (for modified/removed) */ + oldValue: external_exports.unknown().optional().describe("Previous value"), + /** New value (for added/modified) */ + newValue: external_exports.unknown().optional().describe("New value") +}).describe("Individual schema change"); +var DeployDiffSchema = external_exports.object({ + /** List of all schema changes */ + changes: external_exports.array(SchemaChangeSchema).default([]).describe("List of schema changes"), + /** Summary counts */ + summary: external_exports.object({ + added: external_exports.number().int().min(0).default(0).describe("Number of added entities"), + modified: external_exports.number().int().min(0).default(0).describe("Number of modified entities"), + removed: external_exports.number().int().min(0).default(0).describe("Number of removed entities") + }).describe("Change summary counts"), + /** Whether the diff contains breaking changes (e.g., column removal) */ + hasBreakingChanges: external_exports.boolean().default(false).describe("Whether diff contains breaking changes") +}).describe("Schema diff between current and desired state"); +var MigrationStatementSchema = external_exports.object({ + /** SQL DDL statement to execute */ + sql: external_exports.string().min(1).describe("SQL DDL statement"), + /** Whether this statement is reversible */ + reversible: external_exports.boolean().default(true).describe("Whether the statement can be reversed"), + /** Reverse SQL statement (for rollback) */ + rollbackSql: external_exports.string().optional().describe("Reverse SQL for rollback"), + /** Execution order (lower = earlier) */ + order: external_exports.number().int().min(0).describe("Execution order") +}).describe("Single DDL migration statement"); +var MigrationPlanSchema = external_exports.object({ + /** Ordered list of migration statements */ + statements: external_exports.array(MigrationStatementSchema).default([]).describe("Ordered DDL statements"), + /** SQL dialect the statements are written for */ + dialect: external_exports.string().min(1).describe("Target SQL dialect"), + /** Whether the entire plan is reversible */ + reversible: external_exports.boolean().default(true).describe("Whether the plan can be fully rolled back"), + /** Estimated execution time in milliseconds */ + estimatedDurationMs: external_exports.number().int().min(0).optional().describe("Estimated execution time") +}).describe("Ordered migration plan"); +var DeployValidationIssueSchema = external_exports.object({ + /** Severity of the issue */ + severity: external_exports.enum(["error", "warning", "info"]).describe("Issue severity"), + /** Entity path where the issue was found */ + path: external_exports.string().describe("Entity path (e.g., objects.project_task.fields.name)"), + /** Human-readable issue description */ + message: external_exports.string().describe("Issue description"), + /** Zod error code if applicable */ + code: external_exports.string().optional().describe("Validation error code") +}).describe("Validation issue"); +var DeployValidationResultSchema = external_exports.object({ + /** Whether the bundle passed validation */ + valid: external_exports.boolean().describe("Whether the bundle is valid"), + /** List of validation issues */ + issues: external_exports.array(DeployValidationIssueSchema).default([]).describe("Validation issues"), + /** Number of errors */ + errorCount: external_exports.number().int().min(0).default(0).describe("Number of errors"), + /** Number of warnings */ + warningCount: external_exports.number().int().min(0).default(0).describe("Number of warnings") +}).describe("Bundle validation result"); +var DeployManifestSchema = external_exports.object({ + /** Deployment version (semver) */ + version: external_exports.string().min(1).describe("Deployment version"), + /** SHA256 checksum of the bundle contents */ + checksum: external_exports.string().optional().describe("SHA256 checksum"), + /** Object definitions included in this deployment */ + objects: external_exports.array(external_exports.string()).default([]).describe("Object names included"), + /** View definitions included */ + views: external_exports.array(external_exports.string()).default([]).describe("View names included"), + /** Flow definitions included */ + flows: external_exports.array(external_exports.string()).default([]).describe("Flow names included"), + /** Permission definitions included */ + permissions: external_exports.array(external_exports.string()).default([]).describe("Permission names included"), + /** Timestamp of bundle creation (ISO 8601) */ + createdAt: external_exports.string().datetime().optional().describe("Bundle creation time") +}).describe("Deployment manifest"); +var DeployBundleSchema = external_exports.object({ + /** Bundle manifest with version and contents list */ + manifest: DeployManifestSchema, + /** Object definitions (JSON-serialized ObjectStack objects) */ + objects: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Object definitions"), + /** View definitions */ + views: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("View definitions"), + /** Flow definitions */ + flows: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Flow definitions"), + /** Permission definitions */ + permissions: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Permission definitions"), + /** Seed data records to populate after schema migration */ + seedData: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Seed data records") +}).describe("Deploy bundle containing all metadata for deployment"); +var AppManifestSchema = external_exports.object({ + /** Unique app identifier (snake_case) */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("App identifier (snake_case)"), + /** Display label for the app */ + label: external_exports.string().min(1).describe("App display label"), + /** App version (semver) */ + version: external_exports.string().min(1).describe("App version (semver)"), + /** App description */ + description: external_exports.string().optional().describe("App description"), + /** Minimum kernel version required */ + minKernelVersion: external_exports.string().optional().describe("Minimum required kernel version"), + /** Object definitions provided by this app */ + objects: external_exports.array(external_exports.string()).default([]).describe("Object names provided"), + /** View definitions provided */ + views: external_exports.array(external_exports.string()).default([]).describe("View names provided"), + /** Flow definitions provided */ + flows: external_exports.array(external_exports.string()).default([]).describe("Flow names provided"), + /** Whether seed data is included */ + hasSeedData: external_exports.boolean().default(false).describe("Whether app includes seed data"), + /** Seed data records to populate on install */ + seedData: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Seed data records"), + /** App dependencies (other apps that must be installed first) */ + dependencies: external_exports.array(external_exports.string()).default([]).describe("Required app dependencies") +}).describe("App manifest for marketplace installation"); +var AppCompatibilityCheckSchema = external_exports.object({ + /** Whether the app is compatible with the current environment */ + compatible: external_exports.boolean().describe("Whether the app is compatible"), + /** Compatibility issues found */ + issues: external_exports.array(external_exports.object({ + /** Issue severity */ + severity: external_exports.enum(["error", "warning"]).describe("Issue severity"), + /** Issue description */ + message: external_exports.string().describe("Issue description"), + /** Issue category */ + category: external_exports.enum([ + "kernel_version", + // Kernel version mismatch + "object_conflict", + // Object name already exists + "dependency_missing", + // Required dependency not installed + "quota_exceeded" + // Tenant quota would be exceeded + ]).describe("Issue category") + })).default([]).describe("Compatibility issues") +}).describe("App compatibility check result"); +var AppInstallRequestSchema = external_exports.object({ + /** Target tenant ID */ + tenantId: external_exports.string().min(1).describe("Target tenant ID"), + /** App identifier to install */ + appId: external_exports.string().min(1).describe("App identifier"), + /** Optional configuration overrides */ + configOverrides: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Configuration overrides"), + /** Whether to skip seed data */ + skipSeedData: external_exports.boolean().default(false).describe("Skip seed data population") +}).describe("App install request"); +var AppInstallResultSchema = external_exports.object({ + /** Whether the installation succeeded */ + success: external_exports.boolean().describe("Whether installation succeeded"), + /** App identifier that was installed */ + appId: external_exports.string().describe("Installed app identifier"), + /** App version installed */ + version: external_exports.string().describe("Installed app version"), + /** Objects created or updated */ + installedObjects: external_exports.array(external_exports.string()).default([]).describe("Objects created/updated"), + /** Tables created in the database */ + createdTables: external_exports.array(external_exports.string()).default([]).describe("Database tables created"), + /** Number of seed records inserted */ + seededRecords: external_exports.number().int().min(0).default(0).describe("Seed records inserted"), + /** Installation duration in milliseconds */ + durationMs: external_exports.number().int().min(0).optional().describe("Installation duration"), + /** Error message if installation failed */ + error: external_exports.string().optional().describe("Error message on failure") +}).describe("App install result"); +var SystemObjectName = { + /** Authentication: user identity */ + USER: "sys_user", + /** Authentication: active session */ + SESSION: "sys_session", + /** Authentication: OAuth / credential account */ + ACCOUNT: "sys_account", + /** Authentication: email / phone verification */ + VERIFICATION: "sys_verification", + /** Authentication: organization (multi-org support) */ + ORGANIZATION: "sys_organization", + /** Authentication: organization member */ + MEMBER: "sys_member", + /** Authentication: organization invitation */ + INVITATION: "sys_invitation", + /** Authentication: team within an organization */ + TEAM: "sys_team", + /** Authentication: team membership */ + TEAM_MEMBER: "sys_team_member", + /** Authentication: API key for programmatic access */ + API_KEY: "sys_api_key", + /** Authentication: two-factor authentication credentials */ + TWO_FACTOR: "sys_two_factor", + /** Authentication: user preferences (theme, locale, etc.) */ + USER_PREFERENCE: "sys_user_preference", + /** Security: role definition for RBAC */ + ROLE: "sys_role", + /** Security: permission set grouping */ + PERMISSION_SET: "sys_permission_set", + /** Audit: system audit log */ + AUDIT_LOG: "sys_audit_log", + /** System metadata storage */ + METADATA: "sys_metadata", + /** Realtime: user presence state */ + PRESENCE: "sys_presence" +}; + +// ../../packages/core/dist/index.js +init_zod(); + +// ../../packages/spec/dist/api/index.mjs +init_zod(); +var FieldReferenceSchema = external_exports.object({ + $field: external_exports.string().describe("Field Reference/Column Name") +}); +external_exports.object({ + /** Equal to (default) - SQL: = | MongoDB: $eq */ + $eq: external_exports.any().optional(), + /** Not equal to - SQL: <> or != | MongoDB: $ne */ + $ne: external_exports.any().optional() +}); +external_exports.object({ + /** Greater than - SQL: > | MongoDB: $gt */ + $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), + /** Greater than or equal to - SQL: >= | MongoDB: $gte */ + $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), + /** Less than - SQL: < | MongoDB: $lt */ + $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), + /** Less than or equal to - SQL: <= | MongoDB: $lte */ + $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional() +}); +external_exports.object({ + /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */ + $in: external_exports.array(external_exports.any()).optional(), + /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */ + $nin: external_exports.array(external_exports.any()).optional() +}); +external_exports.object({ + /** Between (inclusive) - takes [min, max] array */ + $between: external_exports.tuple([ + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]), + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]) + ]).optional() +}); +external_exports.object({ + /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */ + $contains: external_exports.string().optional(), + /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */ + $notContains: external_exports.string().optional(), + /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */ + $startsWith: external_exports.string().optional(), + /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */ + $endsWith: external_exports.string().optional() +}); +external_exports.object({ + /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */ + $null: external_exports.boolean().optional(), + /** Field exists check (primarily for NoSQL) - MongoDB: $exists */ + $exists: external_exports.boolean().optional() +}); +var FieldOperatorsSchema = external_exports.object({ + // Equality + $eq: external_exports.any().optional(), + $ne: external_exports.any().optional(), + // Comparison (numeric/date) + $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), + $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), + $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), + $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), + // Set & Range + $in: external_exports.array(external_exports.any()).optional(), + $nin: external_exports.array(external_exports.any()).optional(), + $between: external_exports.tuple([ + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]), + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]) + ]).optional(), + // String-specific + $contains: external_exports.string().optional(), + $notContains: external_exports.string().optional(), + $startsWith: external_exports.string().optional(), + $endsWith: external_exports.string().optional(), + // Special + $null: external_exports.boolean().optional(), + $exists: external_exports.boolean().optional() +}); +var FilterConditionSchema = external_exports.lazy( + () => external_exports.record(external_exports.string(), external_exports.unknown()).and( + external_exports.object({ + $and: external_exports.array(FilterConditionSchema).optional(), + $or: external_exports.array(FilterConditionSchema).optional(), + $not: FilterConditionSchema.optional() + }) + ) +); +external_exports.object({ + where: FilterConditionSchema.optional() +}); +var NormalizedFilterSchema = external_exports.lazy( + () => external_exports.object({ + $and: external_exports.array( + external_exports.union([ + // Field condition: { field: { $op: value } } + external_exports.record(external_exports.string(), FieldOperatorsSchema), + // Nested logical group + NormalizedFilterSchema + ]) + ).optional(), + $or: external_exports.array( + external_exports.union([ + external_exports.record(external_exports.string(), FieldOperatorsSchema), + NormalizedFilterSchema + ]) + ).optional(), + $not: external_exports.union([ + external_exports.record(external_exports.string(), FieldOperatorsSchema), + NormalizedFilterSchema + ]).optional() + }) +); +var SortNodeSchema = external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]).default("asc") +}); +var AggregationFunction = external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "array_agg", + "string_agg" +]); +var AggregationNodeSchema = external_exports.object({ + function: AggregationFunction.describe("Aggregation function"), + field: external_exports.string().optional().describe("Field to aggregate (optional for COUNT(*))"), + alias: external_exports.string().describe("Result column alias"), + distinct: external_exports.boolean().optional().describe("Apply DISTINCT before aggregation"), + filter: FilterConditionSchema.optional().describe("Filter/Condition to apply to the aggregation (FILTER WHERE clause)") +}); +var JoinType = external_exports.enum(["inner", "left", "right", "full"]); +var JoinStrategy = external_exports.enum(["auto", "database", "hash", "loop"]); +var JoinNodeSchema = external_exports.lazy( + () => external_exports.object({ + type: JoinType.describe("Join type"), + strategy: JoinStrategy.optional().describe("Execution strategy hint"), + object: external_exports.string().describe("Object/table to join"), + alias: external_exports.string().optional().describe("Table alias"), + on: FilterConditionSchema.describe("Join condition"), + subquery: external_exports.lazy(() => QuerySchema).optional().describe("Subquery instead of object") + }) +); +var WindowFunction = external_exports.enum([ + "row_number", + "rank", + "dense_rank", + "percent_rank", + "lag", + "lead", + "first_value", + "last_value", + "sum", + "avg", + "count", + "min", + "max" +]); +var WindowSpecSchema = external_exports.object({ + partitionBy: external_exports.array(external_exports.string()).optional().describe("PARTITION BY fields"), + orderBy: external_exports.array(SortNodeSchema).optional().describe("ORDER BY specification"), + frame: external_exports.object({ + type: external_exports.enum(["rows", "range"]).optional(), + start: external_exports.string().optional().describe('Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")'), + end: external_exports.string().optional().describe('Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")') + }).optional().describe("Window frame specification") +}); +var WindowFunctionNodeSchema = external_exports.object({ + function: WindowFunction.describe("Window function name"), + field: external_exports.string().optional().describe("Field to operate on (for aggregate window functions)"), + alias: external_exports.string().describe("Result column alias"), + over: WindowSpecSchema.describe("Window specification (OVER clause)") +}); +var FieldNodeSchema = external_exports.lazy( + () => external_exports.union([ + external_exports.string(), + // Primitive field: "name" + external_exports.object({ + field: external_exports.string(), + // Relationship field: "owner" + fields: external_exports.array(FieldNodeSchema).optional(), + // Nested select: ["name", "email"] + alias: external_exports.string().optional() + }) + ]) +); +var FullTextSearchSchema = external_exports.object({ + query: external_exports.string().describe("Search query text"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to search in (if not specified, searches all text fields)"), + fuzzy: external_exports.boolean().optional().default(false).describe("Enable fuzzy matching (tolerates typos)"), + operator: external_exports.enum(["and", "or"]).optional().default("or").describe("Logical operator between terms"), + boost: external_exports.record(external_exports.string(), external_exports.number()).optional().describe("Field-specific relevance boosting (field name -> boost factor)"), + minScore: external_exports.number().optional().describe("Minimum relevance score threshold"), + language: external_exports.string().optional().describe('Language for text analysis (e.g., "en", "zh", "es")'), + highlight: external_exports.boolean().optional().default(false).describe("Enable search result highlighting") +}); +var BaseQuerySchema = external_exports.object({ + /** Target Entity */ + object: external_exports.string().describe("Object name (e.g. account)"), + /** Select Clause */ + fields: external_exports.array(FieldNodeSchema).optional().describe("Fields to retrieve"), + /** Where Clause (Filtering) */ + where: FilterConditionSchema.optional().describe("Filtering criteria (WHERE)"), + /** Full-Text Search */ + search: FullTextSearchSchema.optional().describe("Full-text search configuration ($search parameter)"), + /** Order By Clause (Sorting) */ + orderBy: external_exports.array(SortNodeSchema).optional().describe("Sorting instructions (ORDER BY)"), + /** Pagination */ + limit: external_exports.number().optional().describe("Max records to return (LIMIT)"), + offset: external_exports.number().optional().describe("Records to skip (OFFSET)"), + top: external_exports.number().optional().describe("Alias for limit (OData compatibility)"), + cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Cursor for keyset pagination"), + /** Joins */ + joins: external_exports.array(JoinNodeSchema).optional().describe("Explicit Table Joins"), + /** Aggregations */ + aggregations: external_exports.array(AggregationNodeSchema).optional().describe("Aggregation functions"), + /** Group By Clause */ + groupBy: external_exports.array(external_exports.string()).optional().describe("GROUP BY fields"), + /** Having Clause */ + having: FilterConditionSchema.optional().describe("HAVING clause for aggregation filtering"), + /** Window Functions */ + windowFunctions: external_exports.array(WindowFunctionNodeSchema).optional().describe("Window functions with OVER clause"), + /** Subquery flag */ + distinct: external_exports.boolean().optional().describe("SELECT DISTINCT flag") +}); +var QuerySchema = BaseQuerySchema.extend({ + expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema)).optional().describe( + "Recursive relation loading map. Keys are lookup/master_detail field names; values are nested QueryAST objects that control select, filter, sort, and further expansion on the related object. The engine resolves expand via batch $in queries (driver-agnostic) with a default max depth of 3." + ) +}); +var ApiErrorSchema = external_exports.object({ + code: external_exports.string().describe("Error code (e.g. validation_error)"), + message: external_exports.string().describe("Readable error message"), + category: external_exports.string().optional().describe("Error category (e.g. validation, authorization)"), + details: external_exports.unknown().optional().describe("Additional error context (e.g. field validation errors)"), + requestId: external_exports.string().optional().describe("Request ID for tracking") +}); +var BaseResponseSchema = external_exports.object({ + success: external_exports.boolean().describe("Operation success status"), + error: ApiErrorSchema.optional().describe("Error details if success is false"), + meta: external_exports.object({ + timestamp: external_exports.string(), + duration: external_exports.number().optional(), + requestId: external_exports.string().optional(), + traceId: external_exports.string().optional() + }).optional().describe("Response metadata") +}); +var RecordDataSchema = external_exports.record(external_exports.string(), external_exports.unknown()).describe("Key-value map of record data"); +var CreateRequestSchema = external_exports.object({ + data: RecordDataSchema.describe("Record data to insert") +}); +var UpdateRequestSchema = external_exports.object({ + data: RecordDataSchema.describe("Partial record data to update") +}); +var BulkRequestSchema = external_exports.object({ + records: external_exports.array(RecordDataSchema).describe("Array of records to process"), + allOrNone: external_exports.boolean().default(true).describe("If true, rollback entire transaction on any failure") +}); +var ExportRequestSchema = external_exports.intersection( + QuerySchema, + external_exports.object({ + format: external_exports.enum(["csv", "json", "xlsx"]).default("csv") + }) +); +var SingleRecordResponseSchema = BaseResponseSchema.extend({ + data: RecordDataSchema.describe("The requested or modified record") +}); +var ListRecordResponseSchema = BaseResponseSchema.extend({ + data: external_exports.array(RecordDataSchema).describe("Array of matching records"), + pagination: external_exports.object({ + total: external_exports.number().optional().describe("Total matching records count"), + limit: external_exports.number().optional().describe("Page size"), + offset: external_exports.number().optional().describe("Page offset"), + cursor: external_exports.string().optional().describe("Cursor for next page"), + nextCursor: external_exports.string().optional().describe("Next cursor for pagination"), + hasMore: external_exports.boolean().describe("Are there more pages?") + }).describe("Pagination info") +}); +var IdRequestSchema = external_exports.object({ + id: external_exports.string().describe("Record ID") +}); +var ModificationResultSchema = external_exports.object({ + id: external_exports.string().optional().describe("Record ID if processed"), + success: external_exports.boolean(), + errors: external_exports.array(ApiErrorSchema).optional(), + index: external_exports.number().optional().describe("Index in original request"), + data: external_exports.unknown().optional().describe("Result data (e.g. created record)") +}); +var BulkResponseSchema = BaseResponseSchema.extend({ + data: external_exports.array(ModificationResultSchema).describe("Results for each item in the batch") +}); +var DeleteResponseSchema = BaseResponseSchema.extend({ + id: external_exports.string().describe("ID of the deleted record") +}); +var StandardApiContracts = { + create: { + input: CreateRequestSchema, + output: SingleRecordResponseSchema + }, + delete: { + input: IdRequestSchema, + output: DeleteResponseSchema + }, + get: { + input: IdRequestSchema, + output: SingleRecordResponseSchema + }, + update: { + input: UpdateRequestSchema, + output: SingleRecordResponseSchema + }, + list: { + input: QuerySchema, + output: ListRecordResponseSchema + }, + bulkCreate: { + input: BulkRequestSchema, + output: BulkResponseSchema + }, + bulkUpdate: { + input: BulkRequestSchema, + output: BulkResponseSchema + }, + bulkUpsert: { + input: BulkRequestSchema, + output: BulkResponseSchema + }, + bulkDelete: { + input: external_exports.object({ ids: external_exports.array(external_exports.string()) }), + output: BulkResponseSchema + } +}; +var DataLoaderConfigSchema = external_exports.object({ + maxBatchSize: external_exports.number().int().default(100).describe("Maximum number of keys per batch load"), + batchScheduleFn: external_exports.enum(["microtask", "timeout", "manual"]).default("microtask").describe("Scheduling strategy for collecting batch keys"), + cacheEnabled: external_exports.boolean().default(true).describe("Enable per-request result caching"), + cacheKeyFn: external_exports.string().optional().describe("Name or identifier of the cache key function"), + cacheTtl: external_exports.number().min(0).optional().describe("Cache time-to-live in seconds (0 = no expiration)"), + coalesceRequests: external_exports.boolean().default(true).describe("Deduplicate identical requests within a batch window"), + maxConcurrency: external_exports.number().int().optional().describe("Maximum parallel batch requests") +}); +var BatchLoadingStrategySchema = external_exports.object({ + strategy: external_exports.enum(["dataloader", "windowed", "prefetch"]).describe("Batch loading strategy type"), + windowMs: external_exports.number().optional().describe("Collection window duration in milliseconds (for windowed strategy)"), + prefetchDepth: external_exports.number().int().optional().describe("Depth of relation prefetching (for prefetch strategy)"), + associationLoading: external_exports.enum(["lazy", "eager", "batch"]).default("batch").describe("How to load related associations") +}); +var QueryOptimizationConfigSchema = external_exports.object({ + preventNPlusOne: external_exports.boolean().describe("Enable N+1 query detection and prevention"), + dataLoader: DataLoaderConfigSchema.optional().describe("DataLoader batch loading configuration"), + batchStrategy: BatchLoadingStrategySchema.optional().describe("Batch loading strategy configuration"), + maxQueryDepth: external_exports.number().int().describe("Maximum depth for nested relation queries"), + queryComplexityLimit: external_exports.number().optional().describe("Maximum allowed query complexity score"), + enableQueryPlan: external_exports.boolean().default(false).describe("Log query execution plans for debugging") +}); +var HttpMethod2 = external_exports.enum([ + "GET", + "POST", + "PUT", + "DELETE", + "PATCH", + "HEAD", + "OPTIONS" +]); +var HttpMethodSchema2 = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); +var HttpRequestSchema = external_exports.object({ + url: external_exports.string().describe("API endpoint URL"), + method: HttpMethodSchema2.optional().default("GET").describe("HTTP method"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), + body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") +}); +var CorsConfigSchema2 = external_exports.object({ + /** + * Enable CORS + */ + enabled: external_exports.boolean().default(true).describe("Enable CORS"), + /** + * Allowed origins (* for all) + */ + origins: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.string()) + ]).default("*").describe("Allowed origins (* for all)"), + /** + * Allowed HTTP methods + */ + methods: external_exports.array(HttpMethod2).optional().describe("Allowed HTTP methods"), + /** + * Allow credentials (cookies, authorization headers) + */ + credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), + /** + * Preflight cache duration in seconds + */ + maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") +}); +var RateLimitConfigSchema2 = external_exports.object({ + /** + * Enable rate limiting + */ + enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), + /** + * Time window in milliseconds + */ + windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), + /** + * Max requests per window + */ + maxRequests: external_exports.number().int().default(100).describe("Max requests per window") +}); +var StaticMountSchema2 = external_exports.object({ + /** + * URL path to serve from + */ + path: external_exports.string().describe("URL path to serve from"), + /** + * Physical directory to serve + */ + directory: external_exports.string().describe("Physical directory to serve"), + /** + * Cache-Control header value + */ + cacheControl: external_exports.string().optional().describe("Cache-Control header value") +}); +var ApiMappingSchema = external_exports.object({ + source: external_exports.string().describe("Source field/path"), + target: external_exports.string().describe("Target field/path"), + transform: external_exports.string().optional().describe("Transformation function name") +}); +var ApiEndpointSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique endpoint ID"), + path: external_exports.string().regex(/^\//).describe("URL Path (e.g. /api/v1/customers)"), + method: HttpMethod2.describe("HTTP Method"), + /** Documentation */ + summary: external_exports.string().optional(), + description: external_exports.string().optional(), + /** Execution Logic */ + type: external_exports.enum(["flow", "script", "object_operation", "proxy"]).describe("Implementation type"), + target: external_exports.string().describe("Target Flow ID, Script Name, or Proxy URL"), + /** Logic Config */ + objectParams: external_exports.object({ + object: external_exports.string().optional(), + operation: external_exports.enum(["find", "get", "create", "update", "delete"]).optional() + }).optional().describe("For object_operation type"), + /** Data Transformation */ + inputMapping: external_exports.array(ApiMappingSchema).optional().describe("Map Request Body to Internal Params"), + outputMapping: external_exports.array(ApiMappingSchema).optional().describe("Map Internal Result to Response Body"), + /** Policies */ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + rateLimit: RateLimitConfigSchema2.optional().describe("Rate limiting policy"), + cacheTtl: external_exports.number().optional().describe("Response cache TTL in seconds") +}); +var ApiEndpoint = Object.assign(ApiEndpointSchema, { + create: (config4) => config4 +}); +var ServiceStatus = external_exports.enum([ + "available", + "registered", + "unavailable", + "degraded", + "stub" +]).describe( + "available = fully operational, registered = route declared but handler unverified, unavailable = not installed, degraded = partial, stub = placeholder that returns 501" +); +var ServiceInfoSchema = external_exports.object({ + /** Whether the service is enabled and available */ + enabled: external_exports.boolean(), + /** Current operational status */ + status: ServiceStatus, + /** + * Whether the HTTP handler for this service is confirmed to be mounted. + * + * Semantics: + * - `undefined` (omitted) = handler readiness is unknown / not yet verified. + * - `true` = handler is registered in the adapter / dispatcher (safe to call). + * - `false` = route is declared but no handler exists or only a stub is present + * — requests are expected to receive 501 Not Implemented. + * + * Clients SHOULD check this flag before displaying or invoking a service endpoint and may + * distinguish between "unknown" (omitted) and "known missing" (`false`). + */ + handlerReady: external_exports.boolean().optional().describe( + "Whether the HTTP handler is confirmed to be mounted. Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501)." + ), + /** Route path (only present if enabled) */ + route: external_exports.string().optional().describe("e.g. /api/v1/analytics"), + /** Implementation provider name */ + provider: external_exports.string().optional().describe('e.g. "objectql", "plugin-redis", "driver-memory"'), + /** Service version */ + version: external_exports.string().optional().describe('Semantic version of the service implementation (e.g. "3.0.6")'), + /** Human-readable reason if unavailable */ + message: external_exports.string().optional().describe('e.g. "Install plugin-workflow to enable"'), + /** Rate limit configuration for this service */ + rateLimit: external_exports.object({ + requestsPerMinute: external_exports.number().int().optional().describe("Maximum requests per minute"), + requestsPerHour: external_exports.number().int().optional().describe("Maximum requests per hour"), + burstLimit: external_exports.number().int().optional().describe("Maximum burst request count"), + retryAfterMs: external_exports.number().int().optional().describe("Suggested retry-after delay in milliseconds when rate-limited") + }).optional().describe("Rate limit and quota info for this service") +}); +var ApiRoutesSchema = external_exports.object({ + /** Base URL for Object CRUD (Data Protocol) */ + data: external_exports.string().describe("e.g. /api/v1/data"), + /** Base URL for Schema Definitions (Metadata Protocol) */ + metadata: external_exports.string().describe("e.g. /api/v1/meta"), + /** Base URL for API Discovery endpoint */ + discovery: external_exports.string().optional().describe("e.g. /api/v1/discovery"), + /** Base URL for UI Configurations (Views, Menus) */ + ui: external_exports.string().optional().describe("e.g. /api/v1/ui"), + /** Base URL for Authentication (plugin-provided) */ + auth: external_exports.string().optional().describe("e.g. /api/v1/auth"), + /** Base URL for Automation (Flows/Scripts) */ + automation: external_exports.string().optional().describe("e.g. /api/v1/automation"), + /** Base URL for File/Storage operations */ + storage: external_exports.string().optional().describe("e.g. /api/v1/storage"), + /** Base URL for Analytics/BI operations */ + analytics: external_exports.string().optional().describe("e.g. /api/v1/analytics"), + /** GraphQL Endpoint (if enabled) */ + graphql: external_exports.string().optional().describe("e.g. /graphql"), + /** Base URL for Package Management */ + packages: external_exports.string().optional().describe("e.g. /api/v1/packages"), + /** Base URL for Workflow Engine */ + workflow: external_exports.string().optional().describe("e.g. /api/v1/workflow"), + /** Base URL for Realtime (WebSocket/SSE) */ + realtime: external_exports.string().optional().describe("e.g. /api/v1/realtime"), + /** Base URL for Notification Service */ + notifications: external_exports.string().optional().describe("e.g. /api/v1/notifications"), + /** Base URL for AI Engine (NLQ, Chat, Suggest) */ + ai: external_exports.string().optional().describe("e.g. /api/v1/ai"), + /** Base URL for Internationalization */ + i18n: external_exports.string().optional().describe("e.g. /api/v1/i18n"), + /** Base URL for Feed / Chatter API */ + feed: external_exports.string().optional().describe("e.g. /api/v1/feed") +}); +var DiscoverySchema = external_exports.object({ + /** System Identity */ + name: external_exports.string(), + version: external_exports.string(), + environment: external_exports.enum(["production", "sandbox", "development"]), + /** Dynamic Routing — convenience shortcut for client routing */ + routes: ApiRoutesSchema, + /** Localization Info (helping frontend init i18n) */ + locale: external_exports.object({ + default: external_exports.string(), + supported: external_exports.array(external_exports.string()), + timezone: external_exports.string() + }), + /** + * Per-service status map. + * This is the **single source of truth** for service availability. + * Clients use this to determine which features are available, + * show/hide UI elements, and display appropriate messages. + */ + services: external_exports.record(external_exports.string(), ServiceInfoSchema).describe( + "Per-service availability map keyed by CoreServiceName" + ), + /** + * Hierarchical capability descriptors. + * Declares platform features so clients can adapt UI without probing individual services. + * Each key is a capability domain (e.g., "comments", "automation", "search"), + * and its value describes what sub-features are available. + */ + capabilities: external_exports.record(external_exports.string(), external_exports.object({ + enabled: external_exports.boolean().describe("Whether this capability is available"), + features: external_exports.record(external_exports.string(), external_exports.boolean()).optional().describe("Sub-feature flags within this capability"), + description: external_exports.string().optional().describe("Human-readable capability description") + })).optional().describe("Hierarchical capability descriptors for frontend intelligent adaptation"), + /** + * Schema discovery URLs for cross-ecosystem interoperability. + */ + schemaDiscovery: external_exports.object({ + openapi: external_exports.string().optional().describe('URL to OpenAPI (Swagger) specification (e.g., "/api/v1/openapi.json")'), + graphql: external_exports.string().optional().describe('URL to GraphQL schema endpoint (e.g., "/graphql")'), + jsonSchema: external_exports.string().optional().describe("URL to JSON Schema definitions") + }).optional().describe("Schema discovery endpoints for API toolchain integration"), + /** + * Custom metadata key-value pairs for extensibility + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") +}); +var WellKnownCapabilitiesSchema = external_exports.object({ + /** Whether the backend supports Feed / Chatter API */ + feed: external_exports.boolean().describe("Whether the backend supports Feed / Chatter API"), + /** Whether the backend supports comments (a subset of Feed) */ + comments: external_exports.boolean().describe("Whether the backend supports comments (a subset of Feed)"), + /** Whether the backend supports Automation CRUD (flows, triggers) */ + automation: external_exports.boolean().describe("Whether the backend supports Automation CRUD (flows, triggers)"), + /** Whether the backend supports cron scheduling */ + cron: external_exports.boolean().describe("Whether the backend supports cron scheduling"), + /** Whether the backend supports full-text search */ + search: external_exports.boolean().describe("Whether the backend supports full-text search"), + /** Whether the backend supports async export */ + export: external_exports.boolean().describe("Whether the backend supports async export"), + /** Whether the backend supports chunked (multipart) uploads */ + chunkedUpload: external_exports.boolean().describe("Whether the backend supports chunked (multipart) uploads") +}).describe("Well-known capability flags for frontend intelligent adaptation"); +var RouteHealthEntrySchema = external_exports.object({ + /** Route path (e.g. /api/v1/analytics) */ + route: external_exports.string().describe("Route path pattern"), + /** HTTP method */ + method: HttpMethod2.describe("HTTP method (GET, POST, etc.)"), + /** Target service name */ + service: external_exports.string().describe("Target service name"), + /** Whether the route is declared in discovery */ + declared: external_exports.boolean().describe("Whether the route is declared in discovery/metadata"), + /** Whether the handler is actually registered in the adapter/dispatcher */ + handlerRegistered: external_exports.boolean().describe("Whether the HTTP handler is registered"), + /** + * Health check result: + * - `pass` – Handler exists and responds (2xx/4xx — i.e., not 404/501/503) + * - `fail` – Handler returned 501 or 503 + * - `missing` – No handler registered (404) + * - `skip` – Health check was not performed + */ + healthStatus: external_exports.enum(["pass", "fail", "missing", "skip"]).describe( + "pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked" + ), + /** Optional diagnostic message */ + message: external_exports.string().optional().describe("Diagnostic message") +}); +var RouteHealthReportSchema = external_exports.object({ + /** ISO 8601 timestamp of when the report was generated */ + timestamp: external_exports.string().describe("ISO 8601 timestamp of report generation"), + /** Adapter name that generated the report (e.g. "hono", "express", "nextjs") */ + adapter: external_exports.string().describe("Adapter or runtime that produced this report"), + /** Total routes declared in discovery / dispatcher table */ + totalDeclared: external_exports.number().int().describe("Total routes declared in discovery"), + /** Routes with a confirmed handler registration */ + totalRegistered: external_exports.number().int().describe("Routes with confirmed handler"), + /** Routes missing a handler */ + totalMissing: external_exports.number().int().describe("Routes missing a handler"), + /** Per-route health entries */ + routes: external_exports.array(RouteHealthEntrySchema).describe("Per-route health entries") +}); +var MetadataEventType = external_exports.enum([ + "metadata.object.created", + "metadata.object.updated", + "metadata.object.deleted", + "metadata.field.created", + "metadata.field.updated", + "metadata.field.deleted", + "metadata.view.created", + "metadata.view.updated", + "metadata.view.deleted", + "metadata.app.created", + "metadata.app.updated", + "metadata.app.deleted", + "metadata.agent.created", + "metadata.agent.updated", + "metadata.agent.deleted", + "metadata.tool.created", + "metadata.tool.updated", + "metadata.tool.deleted", + "metadata.flow.created", + "metadata.flow.updated", + "metadata.flow.deleted", + "metadata.action.created", + "metadata.action.updated", + "metadata.action.deleted", + "metadata.workflow.created", + "metadata.workflow.updated", + "metadata.workflow.deleted", + "metadata.dashboard.created", + "metadata.dashboard.updated", + "metadata.dashboard.deleted", + "metadata.report.created", + "metadata.report.updated", + "metadata.report.deleted", + "metadata.role.created", + "metadata.role.updated", + "metadata.role.deleted", + "metadata.permission.created", + "metadata.permission.updated", + "metadata.permission.deleted" +]); +var DataEventType = external_exports.enum([ + "data.record.created", + "data.record.updated", + "data.record.deleted", + "data.field.changed" +]); +var MetadataEventSchema = external_exports.object({ + /** Unique event identifier */ + id: external_exports.string().uuid().describe("Unique event identifier"), + /** Event type (metadata.{type}.{action}) */ + type: MetadataEventType.describe("Event type"), + /** Metadata type (object, view, agent, tool, etc.) */ + metadataType: external_exports.string().describe("Metadata type (object, view, agent, etc.)"), + /** Metadata item name */ + name: external_exports.string().describe("Metadata item name"), + /** Package ID (if applicable) */ + packageId: external_exports.string().optional().describe("Package ID"), + /** Full definition (only for create/update events) */ + definition: external_exports.unknown().optional().describe("Full definition (create/update only)"), + /** User who triggered the event */ + userId: external_exports.string().optional().describe("User who triggered the event"), + /** Event timestamp (ISO 8601) */ + timestamp: external_exports.string().datetime().describe("Event timestamp") +}); +var DataEventSchema = external_exports.object({ + /** Unique event identifier */ + id: external_exports.string().uuid().describe("Unique event identifier"), + /** Event type (data.record.{action}) */ + type: DataEventType.describe("Event type"), + /** Object name */ + object: external_exports.string().describe("Object name"), + /** Record ID */ + recordId: external_exports.string().describe("Record ID"), + /** Changed fields (update events only) */ + changes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Changed fields"), + /** Record before update (update events only) */ + before: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Before state"), + /** Record after update (create/update events) */ + after: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("After state"), + /** User who triggered the event */ + userId: external_exports.string().optional().describe("User who triggered the event"), + /** Event timestamp (ISO 8601) */ + timestamp: external_exports.string().datetime().describe("Event timestamp") +}); +var PresenceStatus = external_exports.enum([ + "online", + // User is actively connected + "away", + // User is idle/inactive + "busy", + // User is busy (do not disturb) + "offline" + // User is disconnected +]); +var RealtimeRecordAction = external_exports.enum([ + "created", + "updated", + "deleted" +]); +var BasePresenceSchema = external_exports.object({ + /** User identifier */ + userId: external_exports.string().describe("User identifier"), + /** Current presence status */ + status: PresenceStatus.describe("Current presence status"), + /** Last activity timestamp */ + lastSeen: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), + /** Custom metadata */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom presence data (e.g., current page, custom status)") +}); +var TransportProtocol = external_exports.enum([ + "websocket", + // Full-duplex, low latency communication + "sse", + // Server-Sent Events, unidirectional push + "polling" + // Short polling, best compatibility +]); +var RealtimeEventType = external_exports.enum([ + "record.created", + "record.updated", + "record.deleted", + "field.changed" +]); +var SubscriptionEventSchema = external_exports.object({ + type: RealtimeEventType.describe("Type of event to subscribe to"), + object: external_exports.string().optional().describe("Object name to subscribe to"), + filters: external_exports.unknown().optional().describe("Filter conditions") +}); +var SubscriptionSchema = external_exports.object({ + id: external_exports.string().uuid().describe("Unique subscription identifier"), + events: external_exports.array(SubscriptionEventSchema).describe("Array of events to subscribe to"), + transport: TransportProtocol.describe("Transport protocol to use"), + channel: external_exports.string().optional().describe("Optional channel name for grouping subscriptions") +}); +var RealtimePresenceSchema = BasePresenceSchema; +var RealtimeEventSchema = external_exports.object({ + id: external_exports.string().uuid().describe("Unique event identifier"), + type: external_exports.string().describe("Event type (e.g., record.created, record.updated)"), + object: external_exports.string().optional().describe("Object name the event relates to"), + action: RealtimeRecordAction.optional().describe("Action performed"), + payload: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Event payload data"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when event occurred"), + userId: external_exports.string().optional().describe("User who triggered the event"), + sessionId: external_exports.string().optional().describe("Session identifier") +}); +var RealtimeConfigSchema = external_exports.object({ + /** Enable realtime sync */ + enabled: external_exports.boolean().default(true).describe("Enable realtime synchronization"), + /** Transport protocol */ + transport: TransportProtocol.default("websocket").describe("Transport protocol"), + /** Default subscriptions */ + subscriptions: external_exports.array(SubscriptionSchema).optional().describe("Default subscriptions") +}).passthrough(); +var SystemIdentifierSchema2 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' +}).describe("System identifier (lowercase with underscores or dots)"); +var SnakeCaseIdentifierSchema2 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { + message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' +}).describe("Snake case identifier (lowercase with underscores only)"); +var EventNameSchema = external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' +}).describe("Event name (lowercase with dot notation for namespacing)"); +var WebSocketMessageType = external_exports.enum([ + "subscribe", + // Client subscribes to events + "unsubscribe", + // Client unsubscribes from events + "event", + // Server sends event to client + "ping", + // Keepalive ping + "pong", + // Keepalive pong response + "ack", + // Acknowledgment of message receipt + "error", + // Error message + "presence", + // Presence update (user status) + "cursor", + // Cursor position update (collaborative editing) + "edit" + // Document edit operation (collaborative editing) +]); +var FilterOperator = external_exports.enum([ + "eq", + // Equal + "ne", + // Not equal + "gt", + // Greater than + "gte", + // Greater than or equal + "lt", + // Less than + "lte", + // Less than or equal + "in", + // In array + "nin", + // Not in array + "contains", + // String contains + "startsWith", + // String starts with + "endsWith", + // String ends with + "exists", + // Field exists + "regex" + // Regex match +]); +var EventFilterCondition = external_exports.object({ + field: external_exports.string().describe('Field path to filter on (supports dot notation, e.g., "user.email")'), + operator: FilterOperator.describe("Comparison operator"), + value: external_exports.unknown().optional().describe('Value to compare against (not needed for "exists" operator)') +}); +var EventFilterSchema = external_exports.object({ + conditions: external_exports.array(EventFilterCondition).optional().describe("Array of filter conditions"), + and: external_exports.lazy(() => external_exports.array(EventFilterSchema)).optional().describe("AND logical combination of filters"), + or: external_exports.lazy(() => external_exports.array(EventFilterSchema)).optional().describe("OR logical combination of filters"), + not: external_exports.lazy(() => EventFilterSchema).optional().describe("NOT logical negation of filter") +}); +var EventPatternSchema = external_exports.string().min(1).regex(/^[a-z*][a-z0-9_.*]*$/, { + message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., "record.*", "*.created", "user.login")' +}).describe('Event pattern (supports wildcards like "record.*" or "*.created")'); +var EventSubscriptionSchema = external_exports.object({ + subscriptionId: external_exports.string().uuid().describe("Unique subscription identifier"), + events: external_exports.array(EventPatternSchema).describe('Event patterns to subscribe to (supports wildcards, e.g., "record.*", "user.created")'), + objects: external_exports.array(external_exports.string()).optional().describe('Object names to filter events by (e.g., ["account", "contact"])'), + filters: EventFilterSchema.optional().describe("Advanced filter conditions for event payloads"), + channels: external_exports.array(external_exports.string()).optional().describe("Channel names for scoped subscriptions") +}); +var UnsubscribeRequestSchema = external_exports.object({ + subscriptionId: external_exports.string().uuid().describe("Subscription ID to unsubscribe from") +}); +var WebSocketPresenceStatus = PresenceStatus; +var PresenceStateSchema = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + sessionId: external_exports.string().uuid().describe("Unique session identifier"), + status: WebSocketPresenceStatus.describe("Current presence status"), + lastSeen: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), + currentLocation: external_exports.string().optional().describe("Current page/route user is viewing"), + device: external_exports.enum(["desktop", "mobile", "tablet", "other"]).optional().describe("Device type"), + customStatus: external_exports.string().optional().describe("Custom user status message"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom presence data") +}); +var PresenceUpdateSchema = external_exports.object({ + status: WebSocketPresenceStatus.optional().describe("Updated presence status"), + currentLocation: external_exports.string().optional().describe("Updated current location"), + customStatus: external_exports.string().optional().describe("Updated custom status message"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") +}); +var CursorPositionSchema = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + documentId: external_exports.string().describe("Document identifier being edited"), + position: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Line number (0-indexed)"), + column: external_exports.number().int().nonnegative().describe("Column number (0-indexed)") + }).optional().describe("Cursor position in document"), + selection: external_exports.object({ + start: external_exports.object({ + line: external_exports.number().int().nonnegative(), + column: external_exports.number().int().nonnegative() + }), + end: external_exports.object({ + line: external_exports.number().int().nonnegative(), + column: external_exports.number().int().nonnegative() + }) + }).optional().describe("Selection range (if text is selected)"), + color: external_exports.string().optional().describe("Cursor color for visual representation"), + userName: external_exports.string().optional().describe("Display name of user"), + lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last cursor update") +}); +var EditOperationType = external_exports.enum([ + "insert", + // Insert text at position + "delete", + // Delete text from range + "replace" + // Replace text in range +]); +var EditOperationSchema = external_exports.object({ + operationId: external_exports.string().uuid().describe("Unique operation identifier"), + documentId: external_exports.string().describe("Document identifier"), + userId: external_exports.string().describe("User who performed the edit"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + type: EditOperationType.describe("Type of edit operation"), + position: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Line number (0-indexed)"), + column: external_exports.number().int().nonnegative().describe("Column number (0-indexed)") + }).describe("Starting position of the operation"), + endPosition: external_exports.object({ + line: external_exports.number().int().nonnegative(), + column: external_exports.number().int().nonnegative() + }).optional().describe("Ending position (for delete/replace operations)"), + content: external_exports.string().optional().describe("Content to insert/replace"), + version: external_exports.number().int().nonnegative().describe("Document version before this operation"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when operation was created"), + baseOperationId: external_exports.string().uuid().optional().describe("Previous operation ID this builds upon (for OT)") +}); +var DocumentStateSchema = external_exports.object({ + documentId: external_exports.string().describe("Document identifier"), + version: external_exports.number().int().nonnegative().describe("Current document version"), + content: external_exports.string().describe("Current document content"), + lastModified: external_exports.string().datetime().describe("ISO 8601 datetime of last modification"), + activeSessions: external_exports.array(external_exports.string().uuid()).describe("Active editing session IDs"), + checksum: external_exports.string().optional().describe("Content checksum for integrity verification") +}); +var BaseWebSocketMessage = external_exports.object({ + messageId: external_exports.string().uuid().describe("Unique message identifier"), + type: WebSocketMessageType.describe("Message type"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when message was sent") +}); +var SubscribeMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("subscribe"), + subscription: EventSubscriptionSchema.describe("Subscription configuration") +}); +var UnsubscribeMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("unsubscribe"), + request: UnsubscribeRequestSchema.describe("Unsubscribe request") +}); +var EventMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("event"), + subscriptionId: external_exports.string().uuid().describe("Subscription ID this event belongs to"), + eventName: EventNameSchema.describe("Event name"), + object: external_exports.string().optional().describe("Object name the event relates to"), + payload: external_exports.unknown().describe("Event payload data"), + userId: external_exports.string().optional().describe("User who triggered the event") +}); +var PresenceMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("presence"), + presence: PresenceStateSchema.describe("Presence state") +}); +var CursorMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("cursor"), + cursor: CursorPositionSchema.describe("Cursor position") +}); +var EditMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("edit"), + operation: EditOperationSchema.describe("Edit operation") +}); +var AckMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("ack"), + ackMessageId: external_exports.string().uuid().describe("ID of the message being acknowledged"), + success: external_exports.boolean().describe("Whether the operation was successful"), + error: external_exports.string().optional().describe("Error message if operation failed") +}); +var ErrorMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("error"), + code: external_exports.string().describe("Error code"), + message: external_exports.string().describe("Error message"), + details: external_exports.unknown().optional().describe("Additional error details") +}); +var PingMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("ping") +}); +var PongMessageSchema = BaseWebSocketMessage.extend({ + type: external_exports.literal("pong"), + pingMessageId: external_exports.string().uuid().optional().describe("ID of ping message being responded to") +}); +var WebSocketMessageSchema = external_exports.discriminatedUnion("type", [ + SubscribeMessageSchema, + UnsubscribeMessageSchema, + EventMessageSchema, + PresenceMessageSchema, + CursorMessageSchema, + EditMessageSchema, + AckMessageSchema, + ErrorMessageSchema, + PingMessageSchema, + PongMessageSchema +]); +var WebSocketConfigSchema = external_exports.object({ + url: external_exports.string().url().describe("WebSocket server URL"), + protocols: external_exports.array(external_exports.string()).optional().describe("WebSocket sub-protocols"), + reconnect: external_exports.boolean().optional().default(true).describe("Enable automatic reconnection"), + reconnectInterval: external_exports.number().int().positive().optional().default(1e3).describe("Reconnection interval in milliseconds"), + maxReconnectAttempts: external_exports.number().int().positive().optional().default(5).describe("Maximum reconnection attempts"), + pingInterval: external_exports.number().int().positive().optional().default(3e4).describe("Ping interval in milliseconds"), + timeout: external_exports.number().int().positive().optional().default(5e3).describe("Message timeout in milliseconds"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for WebSocket handshake") +}); +var WebSocketEventSchema = external_exports.object({ + type: external_exports.enum([ + "subscribe", + // Client subscribes to channel + "unsubscribe", + // Client unsubscribes from channel + "data-change", + // Data modification event + "presence-update", + // User presence change + "cursor-update", + // Cursor position change (collaborative editing) + "error" + // Error message + ]).describe("Event type"), + channel: external_exports.string().describe('Channel identifier (e.g., "record.account.123", "user.456")'), + payload: external_exports.unknown().describe("Event payload data"), + timestamp: external_exports.number().describe("Unix timestamp in milliseconds") +}); +var SimplePresenceStateSchema = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + userName: external_exports.string().describe("User display name"), + status: external_exports.enum(["online", "away", "offline"]).describe("User presence status"), + lastSeen: external_exports.number().describe("Unix timestamp of last activity in milliseconds"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional presence metadata (e.g., current page, custom status)") +}); +var SimpleCursorPositionSchema = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + recordId: external_exports.string().describe("Record identifier being edited"), + fieldName: external_exports.string().describe("Field name being edited"), + position: external_exports.number().describe("Cursor position (character offset from start)"), + selection: external_exports.object({ + start: external_exports.number().describe("Selection start position"), + end: external_exports.number().describe("Selection end position") + }).optional().describe("Text selection range (if text is selected)") +}); +var WebSocketServerConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable WebSocket server"), + path: external_exports.string().default("/ws").describe("WebSocket endpoint path"), + heartbeatInterval: external_exports.number().default(3e4).describe("Heartbeat interval in milliseconds"), + reconnectAttempts: external_exports.number().default(5).describe("Maximum reconnection attempts for clients"), + presence: external_exports.boolean().default(false).describe("Enable presence tracking"), + cursorSharing: external_exports.boolean().default(false).describe("Enable collaborative cursor sharing") +}); +var RouteCategory = external_exports.enum([ + "system", + // Health, Metrics, Info (No Auth usually) + "api", + // Business Logic API (Auth required) + "auth", + // Login/Callback endpoints + "static", + // Asset serving + "webhook", + // External callbacks + "plugin" + // Plugin extensions +]); +var RouteDefinitionSchema = external_exports.object({ + /** + * HTTP Method + */ + method: HttpMethod2, + /** + * URL Path Pattern (supports parameters like /user/:id) + */ + path: external_exports.string().describe("URL Path pattern"), + /** + * Route Type/Category + */ + category: RouteCategory.default("api"), + /** + * Handler Identifier + * References an internal function or plugin action ID. + */ + handler: external_exports.string().describe("Unique handler identifier"), + /** + * Route specific metadata + */ + summary: external_exports.string().optional().describe("OpenAPI summary"), + description: external_exports.string().optional().describe("OpenAPI description"), + /** + * Security constraints + */ + public: external_exports.boolean().default(false).describe("Is publicly accessible"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + /** + * Performance hints + */ + timeout: external_exports.number().int().optional().describe("Execution timeout in ms"), + rateLimit: external_exports.string().optional().describe("Rate limit policy name") +}); +var RouterConfigSchema = external_exports.object({ + /** + * URL Prefix for all kernel routes + */ + basePath: external_exports.string().default("/api").describe("Global API prefix"), + /** + * Standard Protocol Mounts (Relative to basePath) + */ + mounts: external_exports.object({ + data: external_exports.string().default("/data").describe("Data Protocol (CRUD)"), + metadata: external_exports.string().default("/meta").describe("Metadata Protocol (Schemas)"), + auth: external_exports.string().default("/auth").describe("Auth Protocol"), + automation: external_exports.string().default("/automation").describe("Automation Protocol"), + storage: external_exports.string().default("/storage").describe("Storage Protocol"), + analytics: external_exports.string().default("/analytics").describe("Analytics Protocol"), + graphql: external_exports.string().default("/graphql").describe("GraphQL Endpoint"), + ui: external_exports.string().default("/ui").describe("UI Metadata Protocol (Views, Layouts)"), + workflow: external_exports.string().default("/workflow").describe("Workflow Engine Protocol"), + realtime: external_exports.string().default("/realtime").describe("Realtime/WebSocket Protocol"), + notifications: external_exports.string().default("/notifications").describe("Notification Protocol"), + ai: external_exports.string().default("/ai").describe("AI Engine Protocol (NLQ, Chat, Suggest)"), + i18n: external_exports.string().default("/i18n").describe("Internationalization Protocol"), + packages: external_exports.string().default("/packages").describe("Package Management Protocol") + }).default({ + data: "/data", + metadata: "/meta", + auth: "/auth", + automation: "/automation", + storage: "/storage", + analytics: "/analytics", + graphql: "/graphql", + ui: "/ui", + workflow: "/workflow", + realtime: "/realtime", + notifications: "/notifications", + ai: "/ai", + i18n: "/i18n", + packages: "/packages" + }), + // Defaults match standardized spec + /** + * Cross-Origin Resource Sharing + */ + cors: CorsConfigSchema2.optional(), + /** + * Static asset mounts + */ + staticMounts: external_exports.array(StaticMountSchema2).optional() +}); +var ODataQuerySchema = external_exports.object({ + /** + * $select - Select specific fields to return + * + * Comma-separated list of field names to include in the response. + * Reduces payload size and improves performance. + * + * @example "name,email,phone" + * @example "id,customer/name" - With navigation path + */ + $select: external_exports.union([ + external_exports.string(), + // "name,email" + external_exports.array(external_exports.string()) + // ["name", "email"] + ]).optional().describe("Fields to select"), + /** + * $filter - Filter results with conditions + * + * OData filter expression using comparison operators, logical operators, + * and functions. + * + * Comparison: eq, ne, lt, le, gt, ge + * Logical: and, or, not + * Functions: contains, startswith, endswith, length, indexof, substring, etc. + * + * @example "age gt 18" + * @example "country eq 'US' and revenue gt 100000" + * @example "contains(name, 'Smith')" + * @example "startswith(email, 'admin') and isActive eq true" + */ + $filter: external_exports.string().optional().describe("Filter expression (OData filter syntax)"), + /** + * $orderby - Sort results + * + * Comma-separated list of fields with optional asc/desc. + * Default is ascending. + * + * @example "name" + * @example "revenue desc" + * @example "country asc, revenue desc" + */ + $orderby: external_exports.union([ + external_exports.string(), + // "name desc" + external_exports.array(external_exports.string()) + // ["name desc", "email asc"] + ]).optional().describe("Sort order"), + /** + * $top - Limit number of results + * + * Maximum number of results to return. + * Equivalent to SQL LIMIT or FETCH FIRST. + * + * @example 10 + * @example 100 + */ + $top: external_exports.number().int().min(0).optional().describe("Max results to return"), + /** + * $skip - Skip results for pagination + * + * Number of results to skip before returning results. + * Equivalent to SQL OFFSET. + * + * @example 20 + * @example 100 + */ + $skip: external_exports.number().int().min(0).optional().describe("Results to skip"), + /** + * $expand - Include related entities (lookup/master_detail fields) + * + * Comma-separated list of navigation properties (relationship field names) to expand. + * Loads related data in the same request by resolving lookup and master_detail fields. + * The engine replaces foreign key IDs with full related objects via batch $in queries. + * Supports nested expand via OData parenthetical syntax. + * + * Behavior: + * - Only fields with `type: 'lookup'` or `type: 'master_detail'` and a valid `reference` are expanded. + * - Fields without a schema or reference definition are silently skipped (ID returned as-is). + * - Maximum expand depth defaults to 3 (configurable via QueryAdapterConfig). + * + * @example "orders" + * @example "customer,products" + * @example "orders($select=id,total)" - With nested query options + */ + $expand: external_exports.union([ + external_exports.string(), + // "orders" + external_exports.array(external_exports.string()) + // ["orders", "customer"] + ]).optional().describe("Navigation properties to expand (lookup/master_detail fields)"), + /** + * $count - Include total count + * + * When true, includes totalResults count in response. + * Useful for pagination UI. + * + * @example true + */ + $count: external_exports.boolean().optional().describe("Include total count"), + /** + * $search - Full-text search + * + * Free-text search expression. + * Search implementation is service-specific. + * + * @example "John Smith" + * @example "urgent AND support" + */ + $search: external_exports.string().optional().describe("Search expression"), + /** + * $format - Response format + * + * Preferred response format. + * + * @example "json" + * @example "xml" + */ + $format: external_exports.enum(["json", "xml", "atom"]).optional().describe("Response format"), + /** + * $apply - Data aggregation + * + * Aggregation transformations (groupby, aggregate, etc.) + * Part of OData aggregation extension. + * + * @example "groupby((country),aggregate(revenue with sum as totalRevenue))" + */ + $apply: external_exports.string().optional().describe("Aggregation expression") +}); +var ODataFilterOperatorSchema = external_exports.enum([ + // Comparison Operators + "eq", + // Equal to + "ne", + // Not equal to + "lt", + // Less than + "le", + // Less than or equal to + "gt", + // Greater than + "ge", + // Greater than or equal to + // Logical Operators + "and", + // Logical AND + "or", + // Logical OR + "not", + // Logical NOT + // Grouping + "(", + // Left parenthesis + ")", + // Right parenthesis + // Other + "in", + // Value in list + "has" + // Has flag (for enum flags) +]); +var ODataFilterFunctionSchema = external_exports.enum([ + // String Functions + "contains", + // contains(field, 'value') + "startswith", + // startswith(field, 'value') + "endswith", + // endswith(field, 'value') + "length", + // length(field) + "indexof", + // indexof(field, 'substring') + "substring", + // substring(field, start, length) + "tolower", + // tolower(field) + "toupper", + // toupper(field) + "trim", + // trim(field) + "concat", + // concat(field1, field2) + // Date/Time Functions + "year", + // year(dateField) + "month", + // month(dateField) + "day", + // day(dateField) + "hour", + // hour(datetimeField) + "minute", + // minute(datetimeField) + "second", + // second(datetimeField) + "date", + // date(datetimeField) + "time", + // time(datetimeField) + "now", + // now() + "maxdatetime", + // maxdatetime() + "mindatetime", + // mindatetime() + // Math Functions + "round", + // round(numField) + "floor", + // floor(numField) + "ceiling", + // ceiling(numField) + // Type Functions + "cast", + // cast(field, 'Edm.String') + "isof", + // isof(field, 'Type') + // Collection Functions + "any", + // collection/any(d:d/prop eq value) + "all" + // collection/all(d:d/prop eq value) +]); +var ODataResponseSchema = external_exports.object({ + /** + * OData context URL + * Describes the payload structure + */ + "@odata.context": external_exports.string().url().optional().describe("Metadata context URL"), + /** + * Total count (when $count=true) + */ + "@odata.count": external_exports.number().int().optional().describe("Total results count"), + /** + * Next link for pagination + */ + "@odata.nextLink": external_exports.string().url().optional().describe("Next page URL"), + /** + * Result array + */ + value: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Results array") +}); +var ODataErrorSchema = external_exports.object({ + error: external_exports.object({ + /** + * Error code + */ + code: external_exports.string().describe("Error code"), + /** + * Error message + */ + message: external_exports.string().describe("Error message"), + /** + * Target of the error (field name, etc.) + */ + target: external_exports.string().optional().describe("Error target"), + /** + * Additional error details + */ + details: external_exports.array(external_exports.object({ + code: external_exports.string(), + message: external_exports.string(), + target: external_exports.string().optional() + })).optional().describe("Error details"), + /** + * Inner error for debugging + */ + innererror: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Inner error details") + }) +}); +var ODataMetadataSchema = external_exports.object({ + /** + * Service namespace + */ + namespace: external_exports.string().describe("Service namespace"), + /** + * Entity types to expose + */ + entityTypes: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Entity type name"), + key: external_exports.array(external_exports.string()).describe("Key fields"), + properties: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string().describe("OData type (Edm.String, Edm.Int32, etc.)"), + nullable: external_exports.boolean().default(true) + })), + navigationProperties: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string(), + partner: external_exports.string().optional() + })).optional() + })).describe("Entity types"), + /** + * Entity sets + */ + entitySets: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Entity set name"), + entityType: external_exports.string().describe("Entity type") + })).describe("Entity sets") +}); +var ODataConfigSchema = external_exports.object({ + /** Enable OData endpoint */ + enabled: external_exports.boolean().default(true).describe("Enable OData API"), + /** OData endpoint path */ + path: external_exports.string().default("/odata").describe("OData endpoint path"), + /** Metadata configuration */ + metadata: ODataMetadataSchema.optional().describe("OData metadata configuration") +}).passthrough(); +var GraphQLScalarType = external_exports.enum([ + // Built-in GraphQL Scalars + "ID", + "String", + "Int", + "Float", + "Boolean", + // Extended Scalars (common custom types) + "DateTime", + "Date", + "Time", + "JSON", + "JSONObject", + "Upload", + "URL", + "Email", + "PhoneNumber", + "Currency", + "Decimal", + "BigInt", + "Long", + "UUID", + "Base64", + "Void" +]); +var GraphQLTypeConfigSchema = external_exports.object({ + /** Type name in GraphQL schema */ + name: external_exports.string().describe("GraphQL type name (PascalCase recommended)"), + /** Source Object name */ + object: external_exports.string().describe("Source ObjectQL object name"), + /** Description for GraphQL schema documentation */ + description: external_exports.string().optional().describe("Type description"), + /** Fields to include/exclude */ + fields: external_exports.object({ + /** Include only these fields (allow list) */ + include: external_exports.array(external_exports.string()).optional().describe("Fields to include"), + /** Exclude these fields (deny list) */ + exclude: external_exports.array(external_exports.string()).optional().describe("Fields to exclude (e.g., sensitive fields)"), + /** Custom field mappings */ + mappings: external_exports.record(external_exports.string(), external_exports.object({ + graphqlName: external_exports.string().optional().describe("Custom GraphQL field name"), + graphqlType: external_exports.string().optional().describe("Override GraphQL type"), + description: external_exports.string().optional().describe("Field description"), + deprecationReason: external_exports.string().optional().describe("Why field is deprecated"), + nullable: external_exports.boolean().optional().describe("Override nullable") + })).optional().describe("Field-level customizations") + }).optional().describe("Field configuration"), + /** Interfaces this type implements */ + interfaces: external_exports.array(external_exports.string()).optional().describe("GraphQL interface names"), + /** Whether this is an interface definition */ + isInterface: external_exports.boolean().optional().default(false).describe("Define as GraphQL interface"), + /** Custom directives */ + directives: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Directive name"), + args: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Directive arguments") + })).optional().describe("GraphQL directives") +}); +var GraphQLQueryConfigSchema = external_exports.object({ + /** Query name */ + name: external_exports.string().describe("Query field name (camelCase recommended)"), + /** Source Object */ + object: external_exports.string().describe("Source ObjectQL object name"), + /** Query type: single record or list */ + type: external_exports.enum(["get", "list", "search"]).describe("Query type"), + /** Description */ + description: external_exports.string().optional().describe("Query description"), + /** Input arguments */ + args: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.string().describe('GraphQL type (e.g., "ID!", "String", "Int")'), + description: external_exports.string().optional().describe("Argument description"), + defaultValue: external_exports.unknown().optional().describe("Default value") + })).optional().describe("Query arguments"), + /** Filtering configuration */ + filtering: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Allow filtering"), + fields: external_exports.array(external_exports.string()).optional().describe("Filterable fields"), + operators: external_exports.array(external_exports.enum([ + "eq", + "ne", + "gt", + "gte", + "lt", + "lte", + "in", + "notIn", + "contains", + "startsWith", + "endsWith", + "isNull", + "isNotNull" + ])).optional().describe("Allowed filter operators") + }).optional().describe("Filtering capabilities"), + /** Sorting configuration */ + sorting: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Allow sorting"), + fields: external_exports.array(external_exports.string()).optional().describe("Sortable fields"), + defaultSort: external_exports.object({ + field: external_exports.string(), + direction: external_exports.enum(["ASC", "DESC"]) + }).optional().describe("Default sort order") + }).optional().describe("Sorting capabilities"), + /** Pagination configuration */ + pagination: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable pagination"), + type: external_exports.enum(["offset", "cursor", "relay"]).default("offset").describe("Pagination style"), + defaultLimit: external_exports.number().int().min(1).default(20).describe("Default page size"), + maxLimit: external_exports.number().int().min(1).default(100).describe("Maximum page size"), + cursors: external_exports.object({ + field: external_exports.string().default("id").describe("Field to use for cursor pagination") + }).optional() + }).optional().describe("Pagination configuration"), + /** Field selection */ + fields: external_exports.object({ + /** Always include these fields */ + required: external_exports.array(external_exports.string()).optional().describe("Required fields (always returned)"), + /** Allow selecting these fields */ + selectable: external_exports.array(external_exports.string()).optional().describe("Selectable fields") + }).optional().describe("Field selection configuration"), + /** Authorization */ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + /** Caching */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable caching"), + ttl: external_exports.number().int().min(0).optional().describe("Cache TTL in seconds"), + key: external_exports.string().optional().describe("Cache key template") + }).optional().describe("Query caching") +}); +var GraphQLMutationConfigSchema = external_exports.object({ + /** Mutation name */ + name: external_exports.string().describe("Mutation field name (camelCase recommended)"), + /** Source Object */ + object: external_exports.string().describe("Source ObjectQL object name"), + /** Mutation type */ + type: external_exports.enum(["create", "update", "delete", "upsert", "custom"]).describe("Mutation type"), + /** Description */ + description: external_exports.string().optional().describe("Mutation description"), + /** Input type configuration */ + input: external_exports.object({ + /** Input type name */ + typeName: external_exports.string().optional().describe("Custom input type name"), + /** Fields to include in input */ + fields: external_exports.object({ + include: external_exports.array(external_exports.string()).optional().describe("Fields to include"), + exclude: external_exports.array(external_exports.string()).optional().describe("Fields to exclude"), + required: external_exports.array(external_exports.string()).optional().describe("Required input fields") + }).optional().describe("Input field configuration"), + /** Validation */ + validation: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable input validation"), + rules: external_exports.array(external_exports.string()).optional().describe("Custom validation rules") + }).optional().describe("Input validation") + }).optional().describe("Input configuration"), + /** Return type configuration */ + output: external_exports.object({ + /** Type of output */ + type: external_exports.enum(["object", "payload", "boolean", "custom"]).default("object").describe("Output type"), + /** Include success/error envelope */ + includeEnvelope: external_exports.boolean().optional().default(false).describe("Wrap in success/error payload"), + /** Custom output type */ + customType: external_exports.string().optional().describe("Custom output type name") + }).optional().describe("Output configuration"), + /** Transaction handling */ + transaction: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Use database transaction"), + isolationLevel: external_exports.enum(["read_uncommitted", "read_committed", "repeatable_read", "serializable"]).optional().describe("Transaction isolation level") + }).optional().describe("Transaction configuration"), + /** Authorization */ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + /** Hooks */ + hooks: external_exports.object({ + before: external_exports.array(external_exports.string()).optional().describe("Pre-mutation hooks"), + after: external_exports.array(external_exports.string()).optional().describe("Post-mutation hooks") + }).optional().describe("Lifecycle hooks") +}); +var GraphQLSubscriptionConfigSchema = external_exports.object({ + /** Subscription name */ + name: external_exports.string().describe("Subscription field name (camelCase recommended)"), + /** Source Object */ + object: external_exports.string().describe("Source ObjectQL object name"), + /** Subscription trigger events */ + events: external_exports.array(external_exports.enum(["created", "updated", "deleted", "custom"])).describe("Events to subscribe to"), + /** Description */ + description: external_exports.string().optional().describe("Subscription description"), + /** Filtering */ + filter: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Allow filtering subscriptions"), + fields: external_exports.array(external_exports.string()).optional().describe("Filterable fields") + }).optional().describe("Subscription filtering"), + /** Payload configuration */ + payload: external_exports.object({ + /** Include the modified entity */ + includeEntity: external_exports.boolean().default(true).describe("Include entity in payload"), + /** Include previous values (for updates) */ + includePreviousValues: external_exports.boolean().optional().default(false).describe("Include previous field values"), + /** Include mutation metadata */ + includeMeta: external_exports.boolean().optional().default(true).describe("Include metadata (timestamp, user, etc.)") + }).optional().describe("Payload configuration"), + /** Authorization */ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + /** Rate limiting for subscriptions */ + rateLimit: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable rate limiting"), + maxSubscriptionsPerUser: external_exports.number().int().min(1).default(10).describe("Max concurrent subscriptions per user"), + throttleMs: external_exports.number().int().min(0).optional().describe("Throttle interval in milliseconds") + }).optional().describe("Subscription rate limiting") +}); +var GraphQLResolverConfigSchema = external_exports.object({ + /** Field path (e.g., "Query.users", "Mutation.createUser") */ + path: external_exports.string().describe("Resolver path (Type.field)"), + /** Resolver implementation type */ + type: external_exports.enum(["datasource", "computed", "script", "proxy"]).describe("Resolver implementation type"), + /** Implementation details */ + implementation: external_exports.object({ + /** For datasource type */ + datasource: external_exports.string().optional().describe("Datasource ID"), + query: external_exports.string().optional().describe("Query/SQL to execute"), + /** For computed type */ + expression: external_exports.string().optional().describe("Computation expression"), + dependencies: external_exports.array(external_exports.string()).optional().describe("Dependent fields"), + /** For script type */ + script: external_exports.string().optional().describe("Script ID or inline code"), + /** For proxy type */ + url: external_exports.string().optional().describe("Proxy URL"), + method: external_exports.enum(["GET", "POST", "PUT", "DELETE"]).optional().describe("HTTP method") + }).optional().describe("Implementation configuration"), + /** Caching */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable resolver caching"), + ttl: external_exports.number().int().min(0).optional().describe("Cache TTL in seconds"), + keyArgs: external_exports.array(external_exports.string()).optional().describe("Arguments to include in cache key") + }).optional().describe("Resolver caching") +}); +var GraphQLDataLoaderConfigSchema = external_exports.object({ + /** Loader name */ + name: external_exports.string().describe("DataLoader name"), + /** Source Object or datasource */ + source: external_exports.string().describe("Source object or datasource"), + /** Batch function configuration */ + batchFunction: external_exports.object({ + /** Type of batch operation */ + type: external_exports.enum(["findByIds", "query", "script", "custom"]).describe("Batch function type"), + /** For findByIds */ + keyField: external_exports.string().optional().describe('Field to batch on (e.g., "id")'), + /** For query */ + query: external_exports.string().optional().describe("Query template"), + /** For script */ + script: external_exports.string().optional().describe("Script ID"), + /** Maximum batch size */ + maxBatchSize: external_exports.number().int().min(1).optional().default(100).describe("Maximum batch size") + }).describe("Batch function configuration"), + /** Caching */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable per-request caching"), + /** Cache key function */ + keyFn: external_exports.string().optional().describe("Custom cache key function") + }).optional().describe("DataLoader caching"), + /** Options */ + options: external_exports.object({ + /** Batch multiple requests in single tick */ + batch: external_exports.boolean().default(true).describe("Enable batching"), + /** Cache loaded values */ + cache: external_exports.boolean().default(true).describe("Enable caching"), + /** Maximum cache size */ + maxCacheSize: external_exports.number().int().min(0).optional().describe("Max cache entries") + }).optional().describe("DataLoader options") +}); +var GraphQLDirectiveLocation = external_exports.enum([ + // Executable Directive Locations + "QUERY", + "MUTATION", + "SUBSCRIPTION", + "FIELD", + "FRAGMENT_DEFINITION", + "FRAGMENT_SPREAD", + "INLINE_FRAGMENT", + "VARIABLE_DEFINITION", + // Type System Directive Locations + "SCHEMA", + "SCALAR", + "OBJECT", + "FIELD_DEFINITION", + "ARGUMENT_DEFINITION", + "INTERFACE", + "UNION", + "ENUM", + "ENUM_VALUE", + "INPUT_OBJECT", + "INPUT_FIELD_DEFINITION" +]); +var GraphQLDirectiveConfigSchema = external_exports.object({ + /** Directive name */ + name: external_exports.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe("Directive name (camelCase)"), + /** Description */ + description: external_exports.string().optional().describe("Directive description"), + /** Where directive can be used */ + locations: external_exports.array(GraphQLDirectiveLocation).describe("Directive locations"), + /** Arguments */ + args: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.string().describe("Argument type"), + description: external_exports.string().optional().describe("Argument description"), + defaultValue: external_exports.unknown().optional().describe("Default value") + })).optional().describe("Directive arguments"), + /** Is repeatable */ + repeatable: external_exports.boolean().optional().default(false).describe("Can be applied multiple times"), + /** Implementation */ + implementation: external_exports.object({ + /** Directive behavior type */ + type: external_exports.enum(["auth", "validation", "transform", "cache", "deprecation", "custom"]).describe("Directive type"), + /** Handler function */ + handler: external_exports.string().optional().describe("Handler function name or script") + }).optional().describe("Directive implementation") +}); +var GraphQLQueryDepthLimitSchema = external_exports.object({ + /** Enable depth limiting */ + enabled: external_exports.boolean().default(true).describe("Enable query depth limiting"), + /** Maximum allowed depth */ + maxDepth: external_exports.number().int().min(1).default(10).describe("Maximum query depth"), + /** Fields to ignore in depth calculation */ + ignoreFields: external_exports.array(external_exports.string()).optional().describe("Fields excluded from depth calculation"), + /** Callback on depth exceeded */ + onDepthExceeded: external_exports.enum(["reject", "log", "warn"]).default("reject").describe("Action when depth exceeded"), + /** Custom error message */ + errorMessage: external_exports.string().optional().describe("Custom error message for depth violations") +}); +var GraphQLQueryComplexitySchema = external_exports.object({ + /** Enable complexity limiting */ + enabled: external_exports.boolean().default(true).describe("Enable query complexity limiting"), + /** Maximum allowed complexity score */ + maxComplexity: external_exports.number().int().min(1).default(1e3).describe("Maximum query complexity"), + /** Default field complexity */ + defaultFieldComplexity: external_exports.number().int().min(0).default(1).describe("Default complexity per field"), + /** Field-specific complexity scores */ + fieldComplexity: external_exports.record(external_exports.string(), external_exports.union([ + external_exports.number().int().min(0), + external_exports.object({ + /** Base complexity */ + base: external_exports.number().int().min(0).describe("Base complexity"), + /** Multiplier based on arguments */ + multiplier: external_exports.string().optional().describe('Argument multiplier (e.g., "limit")'), + /** Custom complexity calculation */ + calculator: external_exports.string().optional().describe("Custom calculator function") + }) + ])).optional().describe("Per-field complexity configuration"), + /** List multiplier */ + listMultiplier: external_exports.number().min(0).default(10).describe("Multiplier for list fields"), + /** Callback on complexity exceeded */ + onComplexityExceeded: external_exports.enum(["reject", "log", "warn"]).default("reject").describe("Action when complexity exceeded"), + /** Custom error message */ + errorMessage: external_exports.string().optional().describe("Custom error message for complexity violations") +}); +var GraphQLRateLimitSchema = external_exports.object({ + /** Enable rate limiting */ + enabled: external_exports.boolean().default(true).describe("Enable rate limiting"), + /** Rate limit strategy */ + strategy: external_exports.enum(["token_bucket", "fixed_window", "sliding_window", "cost_based"]).default("token_bucket").describe("Rate limiting strategy"), + /** Global rate limits */ + global: external_exports.object({ + /** Requests per time window */ + maxRequests: external_exports.number().int().min(1).default(1e3).describe("Maximum requests per window"), + /** Time window in milliseconds */ + windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds") + }).optional().describe("Global rate limits"), + /** Per-user rate limits */ + perUser: external_exports.object({ + /** Requests per time window */ + maxRequests: external_exports.number().int().min(1).default(100).describe("Maximum requests per user per window"), + /** Time window in milliseconds */ + windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds") + }).optional().describe("Per-user rate limits"), + /** Cost-based rate limiting */ + costBased: external_exports.object({ + /** Enable cost-based limiting */ + enabled: external_exports.boolean().default(false).describe("Enable cost-based rate limiting"), + /** Maximum cost per time window */ + maxCost: external_exports.number().int().min(1).default(1e4).describe("Maximum cost per window"), + /** Time window in milliseconds */ + windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds"), + /** Use complexity as cost */ + useComplexityAsCost: external_exports.boolean().default(true).describe("Use query complexity as cost") + }).optional().describe("Cost-based rate limiting"), + /** Operation-specific limits */ + operations: external_exports.record(external_exports.string(), external_exports.object({ + maxRequests: external_exports.number().int().min(1).describe("Max requests for this operation"), + windowMs: external_exports.number().int().min(1e3).describe("Time window") + })).optional().describe("Per-operation rate limits"), + /** Callback on limit exceeded */ + onLimitExceeded: external_exports.enum(["reject", "queue", "log"]).default("reject").describe("Action when rate limit exceeded"), + /** Custom error message */ + errorMessage: external_exports.string().optional().describe("Custom error message for rate limit violations"), + /** Headers to include in response */ + includeHeaders: external_exports.boolean().default(true).describe("Include rate limit headers in response") +}); +var GraphQLPersistedQuerySchema = external_exports.object({ + /** Enable persisted queries */ + enabled: external_exports.boolean().default(false).describe("Enable persisted queries"), + /** Enforcement mode */ + mode: external_exports.enum(["optional", "required"]).default("optional").describe("Persisted query mode (optional: allow both, required: only persisted)"), + /** Query store configuration */ + store: external_exports.object({ + /** Store type */ + type: external_exports.enum(["memory", "redis", "database", "file"]).default("memory").describe("Query store type"), + /** Store connection string */ + connection: external_exports.string().optional().describe("Store connection string or path"), + /** TTL for cached queries */ + ttl: external_exports.number().int().min(0).optional().describe("TTL in seconds for stored queries") + }).optional().describe("Query store configuration"), + /** Automatic Persisted Queries (APQ) */ + apq: external_exports.object({ + /** Enable APQ */ + enabled: external_exports.boolean().default(true).describe("Enable Automatic Persisted Queries"), + /** Hash algorithm */ + hashAlgorithm: external_exports.enum(["sha256", "sha1", "md5"]).default("sha256").describe("Hash algorithm for query IDs"), + /** Cache control */ + cache: external_exports.object({ + /** Cache TTL */ + ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), + /** Max cache size */ + maxSize: external_exports.number().int().min(1).optional().describe("Maximum number of cached queries") + }).optional().describe("APQ cache configuration") + }).optional().describe("Automatic Persisted Queries configuration"), + /** Query allow list */ + allowlist: external_exports.object({ + /** Enable allow list mode */ + enabled: external_exports.boolean().default(false).describe("Enable query allow list (reject queries not in list)"), + /** Allowed query IDs */ + queries: external_exports.array(external_exports.object({ + id: external_exports.string().describe("Query ID or hash"), + operation: external_exports.string().optional().describe("Operation name"), + query: external_exports.string().optional().describe("Query string") + })).optional().describe("Allowed queries"), + /** External allow list source */ + source: external_exports.string().optional().describe("External allow list source (file path or URL)") + }).optional().describe("Query allow list configuration"), + /** Security */ + security: external_exports.object({ + /** Maximum query size */ + maxQuerySize: external_exports.number().int().min(1).optional().describe("Maximum query string size in bytes"), + /** Reject introspection in production */ + rejectIntrospection: external_exports.boolean().default(false).describe("Reject introspection queries") + }).optional().describe("Security configuration") +}); +var FederationEntityKeySchema = external_exports.object({ + /** Fields composing the key (e.g., "id" or "sku packageId") */ + fields: external_exports.string().describe("Selection set of fields composing the entity key"), + /** Whether this key can be used for resolution across subgraphs */ + resolvable: external_exports.boolean().optional().default(true).describe("Whether entities can be resolved from this subgraph") +}); +var FederationExternalFieldSchema = external_exports.object({ + /** Field name */ + field: external_exports.string().describe("Field name marked as external"), + /** The subgraph that owns this field */ + ownerSubgraph: external_exports.string().optional().describe("Subgraph that owns this field") +}); +var FederationRequiresSchema = external_exports.object({ + /** The field that has this requirement */ + field: external_exports.string().describe("Field with the requirement"), + /** Selection set of external fields required for resolution */ + fields: external_exports.string().describe('Selection set of required fields (e.g., "price weight")') +}); +var FederationProvidesSchema = external_exports.object({ + /** The field that provides additional data */ + field: external_exports.string().describe("Field that provides additional entity fields"), + /** Selection set of fields provided during resolution */ + fields: external_exports.string().describe('Selection set of provided fields (e.g., "name price")') +}); +var FederationEntitySchema = external_exports.object({ + /** Type/Object name */ + typeName: external_exports.string().describe("GraphQL type name for this entity"), + /** Entity keys (`@key` directive) */ + keys: external_exports.array(FederationEntityKeySchema).min(1).describe("Entity key definitions"), + /** External fields (`@external`) */ + externalFields: external_exports.array(FederationExternalFieldSchema).optional().describe("Fields owned by other subgraphs"), + /** Requires directives (`@requires`) */ + requires: external_exports.array(FederationRequiresSchema).optional().describe("Required external fields for computed fields"), + /** Provides directives (`@provides`) */ + provides: external_exports.array(FederationProvidesSchema).optional().describe("Fields provided during resolution"), + /** Whether this subgraph owns this entity */ + owner: external_exports.boolean().optional().default(false).describe("Whether this subgraph is the owner of this entity") +}); +var SubgraphConfigSchema = external_exports.object({ + /** Subgraph name */ + name: external_exports.string().describe("Unique subgraph identifier"), + /** Subgraph URL */ + url: external_exports.string().describe("Subgraph endpoint URL"), + /** Schema source */ + schemaSource: external_exports.enum(["introspection", "file", "registry"]).default("introspection").describe("How to obtain the subgraph schema"), + /** Schema file path (when schemaSource is "file") */ + schemaPath: external_exports.string().optional().describe("Path to schema file (SDL format)"), + /** Federated entities defined by this subgraph */ + entities: external_exports.array(FederationEntitySchema).optional().describe("Entity definitions for this subgraph"), + /** Health check endpoint */ + healthCheck: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable health checking"), + path: external_exports.string().default("/health").describe("Health check endpoint path"), + intervalMs: external_exports.number().int().min(1e3).default(3e4).describe("Health check interval in milliseconds") + }).optional().describe("Subgraph health check configuration"), + /** Request headers to forward */ + forwardHeaders: external_exports.array(external_exports.string()).optional().describe("HTTP headers to forward to this subgraph") +}); +var FederationGatewaySchema = external_exports.object({ + /** Enable federation mode */ + enabled: external_exports.boolean().default(false).describe("Enable GraphQL Federation gateway mode"), + /** Federation specification version */ + version: external_exports.enum(["v1", "v2"]).default("v2").describe("Federation specification version"), + /** Registered subgraphs */ + subgraphs: external_exports.array(SubgraphConfigSchema).describe("Subgraph configurations"), + /** Service discovery */ + serviceDiscovery: external_exports.object({ + /** Discovery mode */ + type: external_exports.enum(["static", "dns", "consul", "kubernetes"]).default("static").describe("Service discovery method"), + /** Poll interval for dynamic discovery */ + pollIntervalMs: external_exports.number().int().min(1e3).optional().describe("Discovery poll interval in milliseconds"), + /** Kubernetes namespace (when type is "kubernetes") */ + namespace: external_exports.string().optional().describe("Kubernetes namespace for subgraph discovery") + }).optional().describe("Service discovery configuration"), + /** Query planning */ + queryPlanning: external_exports.object({ + /** Execution strategy */ + strategy: external_exports.enum(["parallel", "sequential", "adaptive"]).default("parallel").describe("Query execution strategy across subgraphs"), + /** Maximum query depth across subgraphs */ + maxDepth: external_exports.number().int().min(1).optional().describe("Max query depth in federated execution"), + /** Dry-run mode for debugging query plans */ + dryRun: external_exports.boolean().optional().default(false).describe("Log query plans without executing") + }).optional().describe("Query planning configuration"), + /** Schema composition settings */ + composition: external_exports.object({ + /** How schema conflicts are resolved */ + conflictResolution: external_exports.enum(["error", "first_wins", "last_wins"]).default("error").describe("Strategy for resolving schema conflicts"), + /** Whether to validate composed schema */ + validate: external_exports.boolean().default(true).describe("Validate composed supergraph schema") + }).optional().describe("Schema composition configuration"), + /** Gateway-level error handling */ + errorHandling: external_exports.object({ + /** Whether to include subgraph names in errors */ + includeSubgraphName: external_exports.boolean().default(false).describe("Include subgraph name in error responses"), + /** Partial error behavior */ + partialErrors: external_exports.enum(["propagate", "nullify", "reject"]).default("propagate").describe("Behavior when a subgraph returns partial errors") + }).optional().describe("Error handling configuration") +}); +var GraphQLConfigSchema = external_exports.object({ + /** Enable GraphQL API */ + enabled: external_exports.boolean().default(true).describe("Enable GraphQL API"), + /** GraphQL endpoint path */ + path: external_exports.string().default("/graphql").describe("GraphQL endpoint path"), + /** GraphQL Playground */ + playground: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable GraphQL Playground"), + path: external_exports.string().default("/playground").describe("Playground path") + }).optional().describe("GraphQL Playground configuration"), + /** Schema generation */ + schema: external_exports.object({ + /** Auto-generate types from Objects */ + autoGenerateTypes: external_exports.boolean().default(true).describe("Auto-generate types from Objects"), + /** Type configurations */ + types: external_exports.array(GraphQLTypeConfigSchema).optional().describe("Type configurations"), + /** Query configurations */ + queries: external_exports.array(GraphQLQueryConfigSchema).optional().describe("Query configurations"), + /** Mutation configurations */ + mutations: external_exports.array(GraphQLMutationConfigSchema).optional().describe("Mutation configurations"), + /** Subscription configurations */ + subscriptions: external_exports.array(GraphQLSubscriptionConfigSchema).optional().describe("Subscription configurations"), + /** Custom resolvers */ + resolvers: external_exports.array(GraphQLResolverConfigSchema).optional().describe("Custom resolver configurations"), + /** Custom directives */ + directives: external_exports.array(GraphQLDirectiveConfigSchema).optional().describe("Custom directive configurations") + }).optional().describe("Schema generation configuration"), + /** DataLoader configurations */ + dataLoaders: external_exports.array(GraphQLDataLoaderConfigSchema).optional().describe("DataLoader configurations"), + /** Security configuration */ + security: external_exports.object({ + /** Query depth limiting */ + depthLimit: GraphQLQueryDepthLimitSchema.optional().describe("Query depth limiting"), + /** Query complexity */ + complexity: GraphQLQueryComplexitySchema.optional().describe("Query complexity calculation"), + /** Rate limiting */ + rateLimit: GraphQLRateLimitSchema.optional().describe("Rate limiting"), + /** Persisted queries */ + persistedQueries: GraphQLPersistedQuerySchema.optional().describe("Persisted queries") + }).optional().describe("Security configuration"), + /** Federation configuration */ + federation: FederationGatewaySchema.optional().describe("GraphQL Federation gateway configuration") +}); +var GraphQLConfig = Object.assign(GraphQLConfigSchema, { + create: (config4) => config4 +}); +var BatchOperationType = external_exports.enum([ + "create", + // Batch insert + "update", + // Batch update + "upsert", + // Batch upsert (insert or update based on external ID) + "delete" + // Batch delete +]); +var BatchRecordSchema = external_exports.object({ + id: external_exports.string().optional().describe("Record ID (required for update/delete)"), + data: RecordDataSchema.optional().describe("Record data (required for create/update/upsert)"), + externalId: external_exports.string().optional().describe("External ID for upsert matching") +}); +var BatchOptionsSchema = external_exports.object({ + atomic: external_exports.boolean().optional().default(true).describe("If true, rollback entire batch on any failure (transaction mode)"), + returnRecords: external_exports.boolean().optional().default(false).describe("If true, return full record data in response"), + continueOnError: external_exports.boolean().optional().default(false).describe("If true (and atomic=false), continue processing remaining records after errors"), + validateOnly: external_exports.boolean().optional().default(false).describe("If true, validate records without persisting changes (dry-run mode)") +}); +var BatchUpdateRequestSchema = external_exports.object({ + operation: BatchOperationType.describe("Type of batch operation"), + records: external_exports.array(BatchRecordSchema).min(1).max(200).describe("Array of records to process (max 200 per batch)"), + options: BatchOptionsSchema.optional().describe("Batch operation options") +}); +var UpdateManyRequestSchema = external_exports.object({ + records: external_exports.array(BatchRecordSchema).min(1).max(200).describe("Array of records to update (max 200 per batch)"), + options: BatchOptionsSchema.optional().describe("Update options") +}); +var BatchOperationResultSchema = external_exports.object({ + id: external_exports.string().optional().describe("Record ID if operation succeeded"), + success: external_exports.boolean().describe("Whether this record was processed successfully"), + errors: external_exports.array(ApiErrorSchema).optional().describe("Array of errors if operation failed"), + data: RecordDataSchema.optional().describe("Full record data (if returnRecords=true)"), + index: external_exports.number().optional().describe("Index of the record in the request array") +}); +var BatchUpdateResponseSchema = BaseResponseSchema.extend({ + operation: BatchOperationType.optional().describe("Operation type that was performed"), + total: external_exports.number().describe("Total number of records in the batch"), + succeeded: external_exports.number().describe("Number of records that succeeded"), + failed: external_exports.number().describe("Number of records that failed"), + results: external_exports.array(BatchOperationResultSchema).describe("Detailed results for each record") +}); +var DeleteManyRequestSchema = external_exports.object({ + ids: external_exports.array(external_exports.string()).min(1).max(200).describe("Array of record IDs to delete (max 200)"), + options: BatchOptionsSchema.optional().describe("Delete options") +}); +var BatchConfigSchema = external_exports.object({ + /** Enable batch operations */ + enabled: external_exports.boolean().default(true).describe("Enable batch operations"), + /** Maximum records per batch */ + maxRecordsPerBatch: external_exports.number().int().min(1).max(1e3).default(200).describe("Maximum records per batch"), + /** Default options */ + defaultOptions: BatchOptionsSchema.optional().describe("Default batch options") +}).passthrough(); +var CacheDirective = external_exports.enum([ + "public", + // Cacheable by any cache + "private", + // Cacheable only by user-agent + "no-cache", + // Must revalidate with server + "no-store", + // Never cache + "must-revalidate", + // Must revalidate stale responses + "max-age" + // Maximum cache age in seconds +]); +var CacheControlSchema = external_exports.object({ + directives: external_exports.array(CacheDirective).describe("Cache control directives"), + maxAge: external_exports.number().optional().describe("Maximum cache age in seconds"), + staleWhileRevalidate: external_exports.number().optional().describe("Allow serving stale content while revalidating (seconds)"), + staleIfError: external_exports.number().optional().describe("Allow serving stale content on error (seconds)") +}); +var ETagSchema = external_exports.object({ + value: external_exports.string().describe("ETag value (hash or version identifier)"), + weak: external_exports.boolean().optional().default(false).describe("Whether this is a weak ETag") +}); +var MetadataCacheRequestSchema = external_exports.object({ + ifNoneMatch: external_exports.string().optional().describe("ETag value for conditional request (If-None-Match header)"), + ifModifiedSince: external_exports.string().datetime().optional().describe("Timestamp for conditional request (If-Modified-Since header)"), + cacheControl: CacheControlSchema.optional().describe("Client cache control preferences") +}); +var MetadataCacheResponseSchema = external_exports.object({ + data: external_exports.unknown().optional().describe("Metadata payload (omitted for 304 Not Modified)"), + etag: ETagSchema.optional().describe("ETag for this resource version"), + lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), + cacheControl: CacheControlSchema.optional().describe("Cache control directives"), + notModified: external_exports.boolean().optional().default(false).describe("True if resource has not been modified (304 response)"), + version: external_exports.string().optional().describe("Metadata version identifier") +}); +var CacheInvalidationTarget = external_exports.enum([ + "all", + // Invalidate all cached metadata + "object", + // Invalidate specific object metadata + "field", + // Invalidate specific field metadata + "permission", + // Invalidate permission metadata + "layout", + // Invalidate layout metadata + "custom" + // Custom invalidation pattern +]); +var CacheInvalidationRequestSchema = external_exports.object({ + target: CacheInvalidationTarget.describe("What to invalidate"), + identifiers: external_exports.array(external_exports.string()).optional().describe("Specific resources to invalidate (e.g., object names)"), + cascade: external_exports.boolean().optional().default(false).describe("If true, invalidate dependent resources"), + pattern: external_exports.string().optional().describe("Pattern for custom invalidation (supports wildcards)") +}); +var CacheInvalidationResponseSchema = external_exports.object({ + success: external_exports.boolean().describe("Whether invalidation succeeded"), + invalidated: external_exports.number().describe("Number of cache entries invalidated"), + targets: external_exports.array(external_exports.string()).optional().describe("List of invalidated resources") +}); +var ErrorCategory = external_exports.enum([ + "validation", + // Input validation errors (400) + "authentication", + // Authentication failures (401) + "authorization", + // Permission denied errors (403) + "not_found", + // Resource not found (404) + "conflict", + // Resource conflict (409) + "rate_limit", + // Rate limiting (429) + "server", + // Internal server errors (500) + "external", + // External service errors (502/503) + "maintenance" + // Planned maintenance (503) +]); +var StandardErrorCode = external_exports.enum([ + // Validation Errors (400) + "validation_error", + // Generic validation failure + "invalid_field", + // Invalid field value + "missing_required_field", + // Required field missing + "invalid_format", + // Field format invalid (e.g., email, date) + "value_too_long", + // Field value exceeds max length + "value_too_short", + // Field value below min length + "value_out_of_range", + // Numeric value out of range + "invalid_reference", + // Invalid foreign key reference + "duplicate_value", + // Unique constraint violation + "invalid_query", + // Malformed query syntax + "invalid_filter", + // Invalid filter expression + "invalid_sort", + // Invalid sort specification + "max_records_exceeded", + // Query would return too many records + // Authentication Errors (401) + "unauthenticated", + // No valid authentication provided + "invalid_credentials", + // Wrong username/password + "expired_token", + // Authentication token expired + "invalid_token", + // Authentication token invalid + "session_expired", + // User session expired + "mfa_required", + // Multi-factor authentication required + "email_not_verified", + // Email verification required + // Authorization Errors (403) + "permission_denied", + // User lacks required permission + "insufficient_privileges", + // Operation requires higher privileges + "field_not_accessible", + // Field-level security restriction + "record_not_accessible", + // Sharing rule restriction + "license_required", + // Feature requires license + "ip_restricted", + // IP address not allowed + "time_restricted", + // Access outside allowed time window + // Not Found Errors (404) + "resource_not_found", + // Generic resource not found + "object_not_found", + // Object/table not found + "record_not_found", + // Record with given ID not found + "field_not_found", + // Field not found in object + "endpoint_not_found", + // API endpoint not found + // Conflict Errors (409) + "resource_conflict", + // Generic resource conflict + "concurrent_modification", + // Record modified by another user + "delete_restricted", + // Cannot delete due to dependencies + "duplicate_record", + // Record already exists + "lock_conflict", + // Record is locked by another process + // Rate Limiting (429) + "rate_limit_exceeded", + // Too many requests + "quota_exceeded", + // API quota exceeded + "concurrent_limit_exceeded", + // Too many concurrent requests + // Server Errors (500) + "internal_error", + // Generic internal server error + "database_error", + // Database operation failed + "timeout", + // Operation timed out + "service_unavailable", + // Service temporarily unavailable + "not_implemented", + // Feature not yet implemented + // External Service Errors (502/503) + "external_service_error", + // External API call failed + "integration_error", + // Integration service error + "webhook_delivery_failed", + // Webhook delivery failed + // Batch Operation Errors + "batch_partial_failure", + // Batch operation partially succeeded + "batch_complete_failure", + // Batch operation completely failed + "transaction_failed" + // Transaction rolled back +]); +var RetryStrategy = external_exports.enum([ + "no_retry", + // Do not retry (permanent failure) + "retry_immediate", + // Retry immediately + "retry_backoff", + // Retry with exponential backoff + "retry_after" + // Retry after specified delay +]); +var FieldErrorSchema = external_exports.object({ + field: external_exports.string().describe("Field path (supports dot notation)"), + code: StandardErrorCode.describe("Error code for this field"), + message: external_exports.string().describe("Human-readable error message"), + value: external_exports.unknown().optional().describe("The invalid value that was provided"), + constraint: external_exports.unknown().optional().describe("The constraint that was violated (e.g., max length)") +}); +var EnhancedApiErrorSchema = external_exports.object({ + code: StandardErrorCode.describe("Machine-readable error code"), + message: external_exports.string().describe("Human-readable error message"), + category: ErrorCategory.optional().describe("Error category"), + httpStatus: external_exports.number().optional().describe("HTTP status code"), + retryable: external_exports.boolean().default(false).describe("Whether the request can be retried"), + retryStrategy: RetryStrategy.optional().describe("Recommended retry strategy"), + retryAfter: external_exports.number().optional().describe("Seconds to wait before retrying"), + details: external_exports.unknown().optional().describe("Additional error context"), + fieldErrors: external_exports.array(FieldErrorSchema).optional().describe("Field-specific validation errors"), + timestamp: external_exports.string().datetime().optional().describe("When the error occurred"), + requestId: external_exports.string().optional().describe("Request ID for tracking"), + traceId: external_exports.string().optional().describe("Distributed trace ID"), + documentation: external_exports.string().url().optional().describe("URL to error documentation"), + helpText: external_exports.string().optional().describe("Suggested actions to resolve the error") +}); +var ErrorResponseSchema = external_exports.object({ + success: external_exports.literal(false).describe("Always false for error responses"), + error: EnhancedApiErrorSchema.describe("Error details"), + meta: external_exports.object({ + timestamp: external_exports.string().datetime().optional(), + requestId: external_exports.string().optional(), + traceId: external_exports.string().optional() + }).optional().describe("Response metadata") +}); +external_exports.object({ + /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ + key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), + /** Default value when translation is not available */ + defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), + /** Interpolation parameters for dynamic translations */ + params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") +}); +var I18nLabelSchema2 = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); +var AriaPropsSchema2 = external_exports.object({ + /** Accessible label for screen readers */ + ariaLabel: I18nLabelSchema2.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), + /** ID of element that describes this component */ + ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), + /** WAI-ARIA role override */ + role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') +}).describe("ARIA accessibility attributes"); +external_exports.object({ + /** Translation key for the plural form */ + key: external_exports.string().describe("Translation key"), + /** Form for zero quantity */ + zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), + /** Form for singular (1) */ + one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), + /** Form for dual (2) — used in Arabic, Welsh, etc. */ + two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), + /** Form for few (2-4 in Slavic languages) */ + few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), + /** Form for many (5+ in Slavic languages) */ + many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), + /** Default/fallback form */ + other: external_exports.string().describe('Default plural form (e.g., "{count} items")') +}).describe("ICU plural rules for a translation key"); +var NumberFormatSchema2 = external_exports.object({ + style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), + currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), + unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), + minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), + maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), + useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") +}).describe("Number formatting rules"); +var DateFormatSchema2 = external_exports.object({ + dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), + timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), + timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), + hour12: external_exports.boolean().optional().describe("Use 12-hour format") +}).describe("Date/time formatting rules"); +external_exports.object({ + /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ + code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), + /** Ordered fallback chain for missing translations */ + fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), + /** Text direction */ + direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), + /** Default number formatting */ + numberFormat: NumberFormatSchema2.optional().describe("Default number formatting rules"), + /** Default date formatting */ + dateFormat: DateFormatSchema2.optional().describe("Default date/time formatting rules") +}).describe("Locale configuration"); +var SharingConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable public sharing"), + publicLink: external_exports.string().optional().describe("Generated public share URL"), + password: external_exports.string().optional().describe("Password required to access shared link"), + allowedDomains: external_exports.array(external_exports.string()).optional().describe('Restrict access to specific email domains (e.g. ["example.com"])'), + expiresAt: external_exports.string().optional().describe("Expiration date/time in ISO 8601 format"), + allowAnonymous: external_exports.boolean().optional().default(false).describe("Allow access without authentication") +}); +var EmbedConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable iframe embedding"), + allowedOrigins: external_exports.array(external_exports.string()).optional().describe('Allowed iframe parent origins (e.g. ["https://example.com"])'), + width: external_exports.string().optional().default("100%").describe("Embed width (CSS value)"), + height: external_exports.string().optional().default("600px").describe("Embed height (CSS value)"), + showHeader: external_exports.boolean().optional().default(true).describe("Show interface header in embed"), + showNavigation: external_exports.boolean().optional().default(false).describe("Show navigation in embed"), + responsive: external_exports.boolean().optional().default(true).describe("Enable responsive resizing") +}); +var BreakpointName = external_exports.enum(["xs", "sm", "md", "lg", "xl", "2xl"]); +var BreakpointColumnMapSchema = external_exports.object({ + xs: external_exports.number().min(1).max(12).optional(), + sm: external_exports.number().min(1).max(12).optional(), + md: external_exports.number().min(1).max(12).optional(), + lg: external_exports.number().min(1).max(12).optional(), + xl: external_exports.number().min(1).max(12).optional(), + "2xl": external_exports.number().min(1).max(12).optional() +}).describe("Grid columns per breakpoint (1-12)"); +var BreakpointOrderMapSchema = external_exports.object({ + xs: external_exports.number().optional(), + sm: external_exports.number().optional(), + md: external_exports.number().optional(), + lg: external_exports.number().optional(), + xl: external_exports.number().optional(), + "2xl": external_exports.number().optional() +}).describe("Display order per breakpoint"); +var ResponsiveConfigSchema = external_exports.object({ + /** Minimum breakpoint for visibility */ + breakpoint: BreakpointName.optional().describe("Minimum breakpoint for visibility"), + /** Hide on specific breakpoints */ + hiddenOn: external_exports.array(BreakpointName).optional().describe("Hide on these breakpoints"), + /** Grid columns per breakpoint (1-12 column grid) */ + columns: BreakpointColumnMapSchema.optional().describe("Grid columns per breakpoint"), + /** Display order per breakpoint */ + order: BreakpointOrderMapSchema.optional().describe("Display order per breakpoint") +}).describe("Responsive layout configuration"); +var PerformanceConfigSchema = external_exports.object({ + /** Enable lazy loading for this component */ + lazyLoad: external_exports.boolean().optional().describe("Enable lazy loading (defer rendering until visible)"), + /** Virtual scrolling configuration for large datasets */ + virtualScroll: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable virtual scrolling"), + itemHeight: external_exports.number().optional().describe("Fixed item height in pixels (for estimation)"), + overscan: external_exports.number().optional().describe("Number of extra items to render outside viewport") + }).optional().describe("Virtual scrolling configuration"), + /** Client-side caching strategy */ + cacheStrategy: external_exports.enum([ + "none", + "cache-first", + "network-first", + "stale-while-revalidate" + ]).optional().describe("Client-side data caching strategy"), + /** Enable data prefetching */ + prefetch: external_exports.boolean().optional().describe("Prefetch data before component is visible"), + /** Maximum number of items to render before pagination */ + pageSize: external_exports.number().optional().describe("Number of items per page for pagination"), + /** Debounce interval for user interactions (ms) */ + debounceMs: external_exports.number().optional().describe("Debounce interval for user interactions in milliseconds") +}).describe("Performance optimization configuration"); +var ViewDataSchema = external_exports.discriminatedUnion("provider", [ + external_exports.object({ + provider: external_exports.literal("object"), + object: external_exports.string().describe("Target object name") + }), + external_exports.object({ + provider: external_exports.literal("api"), + read: HttpRequestSchema.optional().describe("Configuration for fetching data"), + write: HttpRequestSchema.optional().describe("Configuration for submitting data (for forms/editable tables)") + }), + external_exports.object({ + provider: external_exports.literal("value"), + items: external_exports.array(external_exports.unknown()).describe("Static data array") + }) +]); +var ViewFilterRuleSchema = external_exports.object({ + /** Field name to filter on */ + field: external_exports.string().describe("Field name to filter on"), + /** Filter operator */ + operator: external_exports.string().describe("Filter operator (e.g. equals, not_equals, contains, this_quarter)"), + /** Filter value (optional for unary operators like is_null, this_quarter) */ + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Filter value") +}).describe("View filter rule"); +var ColumnSummarySchema = external_exports.enum([ + "none", + "count", + "count_empty", + "count_filled", + "count_unique", + "percent_empty", + "percent_filled", + "sum", + "avg", + "min", + "max" +]).describe("Aggregation function for column footer summary"); +var ListColumnSchema = external_exports.object({ + field: external_exports.string().describe("Field name (snake_case)"), + label: I18nLabelSchema2.optional().describe("Display label override"), + width: external_exports.number().positive().optional().describe("Column width in pixels"), + align: external_exports.enum(["left", "center", "right"]).optional().describe("Text alignment"), + hidden: external_exports.boolean().optional().describe("Hide column by default"), + sortable: external_exports.boolean().optional().describe("Allow sorting by this column"), + resizable: external_exports.boolean().optional().describe("Allow resizing this column"), + wrap: external_exports.boolean().optional().describe("Allow text wrapping"), + type: external_exports.string().optional().describe('Renderer type override (e.g., "currency", "date")'), + /** Pinning (Airtable-style frozen columns) */ + pinned: external_exports.enum(["left", "right"]).optional().describe("Pin/freeze column to left or right side"), + /** Column Footer Summary (Airtable-style aggregation) */ + summary: ColumnSummarySchema.optional().describe("Footer aggregation function for this column"), + /** Interaction */ + link: external_exports.boolean().optional().describe("Functions as the primary navigation link (triggers View navigation)"), + action: external_exports.string().optional().describe("Registered Action ID to execute when clicked") +}); +var SelectionConfigSchema = external_exports.object({ + type: external_exports.enum(["none", "single", "multiple"]).default("none").describe("Selection mode") +}); +var PaginationConfigSchema = external_exports.object({ + pageSize: external_exports.number().int().positive().default(25).describe("Number of records per page"), + pageSizeOptions: external_exports.array(external_exports.number().int().positive()).optional().describe("Available page size options") +}); +var RowHeightSchema = external_exports.enum([ + "compact", + // Minimal padding, single line + "short", + // Reduced padding + "medium", + // Default padding + "tall", + // Extra padding, multi-line preview + "extra_tall" + // Maximum padding, rich content preview +]).describe("Row height / density setting for list view"); +var GroupingFieldSchema = external_exports.object({ + field: external_exports.string().describe("Field name to group by"), + order: external_exports.enum(["asc", "desc"]).default("asc").describe("Group sort order"), + collapsed: external_exports.boolean().default(false).describe("Collapse groups by default") +}); +var GroupingConfigSchema = external_exports.object({ + fields: external_exports.array(GroupingFieldSchema).min(1).describe("Fields to group by (supports up to 3 levels)") +}).describe("Record grouping configuration"); +var GalleryConfigSchema = external_exports.object({ + coverField: external_exports.string().optional().describe("Attachment/image field to display as card cover"), + coverFit: external_exports.enum(["cover", "contain"]).default("cover").describe("Image fit mode for card cover"), + cardSize: external_exports.enum(["small", "medium", "large"]).default("medium").describe("Card size in gallery view"), + titleField: external_exports.string().optional().describe("Field to display as card title"), + visibleFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on card body") +}).describe("Gallery/card view configuration"); +var TimelineConfigSchema = external_exports.object({ + startDateField: external_exports.string().describe("Field for timeline item start date"), + endDateField: external_exports.string().optional().describe("Field for timeline item end date"), + titleField: external_exports.string().describe("Field to display as timeline item title"), + groupByField: external_exports.string().optional().describe("Field to group timeline rows"), + colorField: external_exports.string().optional().describe("Field to determine item color"), + scale: external_exports.enum(["hour", "day", "week", "month", "quarter", "year"]).default("week").describe("Default timeline scale") +}).describe("Timeline view configuration"); +var ViewSharingSchema = external_exports.object({ + type: external_exports.enum(["personal", "collaborative"]).default("collaborative").describe("View ownership type"), + lockedBy: external_exports.string().optional().describe("User who locked the view configuration") +}).describe("View sharing and access configuration"); +var RowColorConfigSchema = external_exports.object({ + field: external_exports.string().describe("Field to derive color from (typically a select/status field)"), + colors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Map of field value to color (hex/token)") +}).describe("Row color configuration based on field values"); +var VisualizationTypeSchema = external_exports.enum([ + "grid", + "kanban", + "gallery", + "calendar", + "timeline", + "gantt", + "map" +]).describe("Visualization type that users can switch to"); +var UserActionsConfigSchema = external_exports.object({ + sort: external_exports.boolean().default(true).describe("Allow users to sort records"), + search: external_exports.boolean().default(true).describe("Allow users to search records"), + filter: external_exports.boolean().default(true).describe("Allow users to filter records"), + rowHeight: external_exports.boolean().default(true).describe("Allow users to toggle row height/density"), + addRecordForm: external_exports.boolean().default(false).describe("Add records through a form instead of inline"), + buttons: external_exports.array(external_exports.string()).optional().describe("Custom action button IDs to show in the toolbar") +}).describe("User action toggles for the view toolbar"); +var AppearanceConfigSchema = external_exports.object({ + showDescription: external_exports.boolean().default(true).describe("Show the view description text"), + allowedVisualizations: external_exports.array(VisualizationTypeSchema).optional().describe('Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])') +}).describe("Appearance and visualization configuration"); +var ViewTabSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema2.describe("Tab identifier (snake_case)"), + label: I18nLabelSchema2.optional().describe("Display label"), + icon: external_exports.string().optional().describe("Tab icon name"), + view: external_exports.string().optional().describe("Referenced list view name from listViews"), + filter: external_exports.array(ViewFilterRuleSchema).optional().describe("Tab-specific filter criteria"), + order: external_exports.number().int().min(0).optional().describe("Tab display order"), + pinned: external_exports.boolean().default(false).describe("Pin tab (cannot be removed by users)"), + isDefault: external_exports.boolean().default(false).describe("Set as the default active tab"), + visible: external_exports.boolean().default(true).describe("Tab visibility") +}).describe("Tab configuration for multi-tab view interface"); +var AddRecordConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Show the add record entry point"), + position: external_exports.enum(["top", "bottom", "both"]).default("bottom").describe("Position of the add record button"), + mode: external_exports.enum(["inline", "form", "modal"]).default("inline").describe("How to add a new record"), + formView: external_exports.string().optional().describe('Named form view to use when mode is "form" or "modal"') +}).describe("Add record entry point configuration"); +var KanbanConfigSchema = external_exports.object({ + groupByField: external_exports.string().describe("Field to group columns by (usually status/select)"), + summarizeField: external_exports.string().optional().describe("Field to sum at top of column (e.g. amount)"), + columns: external_exports.array(external_exports.string()).describe("Fields to show on cards") +}); +var CalendarConfigSchema = external_exports.object({ + startDateField: external_exports.string(), + endDateField: external_exports.string().optional(), + titleField: external_exports.string(), + colorField: external_exports.string().optional() +}); +var GanttConfigSchema = external_exports.object({ + startDateField: external_exports.string(), + endDateField: external_exports.string(), + titleField: external_exports.string(), + progressField: external_exports.string().optional(), + dependenciesField: external_exports.string().optional() +}); +var NavigationModeSchema = external_exports.enum([ + "page", + // Navigate to a new route (default) + "drawer", + // Open details in a side drawer/panel + "modal", + // Open details in a modal dialog + "split", + // Show details side-by-side with the list (master-detail) + "popover", + // Show details in a popover (lightweight) + "new_window", + // Open in new browser tab/window + "none" + // No navigation (read-only list) +]); +var NavigationConfigSchema = external_exports.object({ + mode: NavigationModeSchema.default("page"), + /** Target View Config */ + view: external_exports.string().optional().describe('Name of the form view to use for details (e.g. "summary_view", "edit_form")'), + /** Interaction Triggers */ + preventNavigation: external_exports.boolean().default(false).describe("Disable standard navigation entirely"), + openNewTab: external_exports.boolean().default(false).describe("Force open in new tab (applies to page mode)"), + /** Dimensions (for modal/drawer) */ + width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Width of the drawer/modal (e.g. "600px", "50%")') +}); +var ListViewSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema2.optional().describe("Internal view name (lowercase snake_case)"), + label: I18nLabelSchema2.optional(), + // Display label override (supports i18n) + type: external_exports.enum([ + "grid", + // Standard Data Table + "kanban", + // Board / Columns + "gallery", + // Card Deck / Masonry + "calendar", + // Monthly/Weekly/Daily + "timeline", + // Chronological Stream (Feed) + "gantt", + // Project Timeline + "map" + // Geospatial + ]).default("grid"), + /** Data Source Configuration */ + data: ViewDataSchema.optional().describe('Data source configuration (defaults to "object" provider)'), + /** Shared Query Config */ + columns: external_exports.union([ + external_exports.array(external_exports.string()), + // Legacy: simple field names + external_exports.array(ListColumnSchema) + // Enhanced: detailed column config + ]).describe("Fields to display as columns"), + filter: external_exports.array(ViewFilterRuleSchema).optional().describe("Filter criteria (JSON Rules)"), + sort: external_exports.union([ + external_exports.string(), + //Legacy "field desc" + external_exports.array(external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]) + })) + ]).optional(), + /** Search & Filter */ + searchableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for search"), + filterableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for end-user filtering in the top bar"), + /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */ + quickFilters: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name to filter by"), + label: external_exports.string().optional().describe("Display label for the chip"), + operator: external_exports.enum(["equals", "not_equals", "contains", "in", "is_null", "is_not_null"]).default("equals").describe("Filter operator"), + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Preset filter value") + })).optional().describe("One-click filter chips for quick record filtering"), + /** Grid Features */ + resizable: external_exports.boolean().optional().describe("Enable column resizing"), + striped: external_exports.boolean().optional().describe("Striped row styling"), + bordered: external_exports.boolean().optional().describe("Show borders"), + /** Selection */ + selection: SelectionConfigSchema.optional().describe("Row selection configuration"), + /** Navigation / Interaction */ + navigation: NavigationConfigSchema.optional().describe("Configuration for item click navigation (page, drawer, modal, etc.)"), + /** Pagination */ + pagination: PaginationConfigSchema.optional().describe("Pagination configuration"), + /** Type Specific Config */ + kanban: KanbanConfigSchema.optional(), + calendar: CalendarConfigSchema.optional(), + gantt: GanttConfigSchema.optional(), + gallery: GalleryConfigSchema.optional(), + timeline: TimelineConfigSchema.optional(), + /** View Metadata (Airtable-style view management) */ + description: I18nLabelSchema2.optional().describe("View description for documentation/tooltips"), + sharing: ViewSharingSchema.optional().describe("View sharing and access configuration"), + /** Row Height / Density (Airtable-style) */ + rowHeight: RowHeightSchema.optional().describe("Row height / density setting"), + /** Record Grouping (Airtable-style) */ + grouping: GroupingConfigSchema.optional().describe("Group records by one or more fields"), + /** Row Color (Airtable-style) */ + rowColor: RowColorConfigSchema.optional().describe("Color rows based on field value"), + /** Field Visibility & Ordering per View (Airtable-style) */ + hiddenFields: external_exports.array(external_exports.string()).optional().describe("Fields to hide in this specific view"), + fieldOrder: external_exports.array(external_exports.string()).optional().describe("Explicit field display order for this view"), + /** Row & Bulk Actions */ + rowActions: external_exports.array(external_exports.string()).optional().describe("Actions available for individual row items"), + bulkActions: external_exports.array(external_exports.string()).optional().describe("Actions available when multiple rows are selected"), + /** Performance */ + virtualScroll: external_exports.boolean().optional().describe("Enable virtual scrolling for large datasets"), + /** Conditional Formatting */ + conditionalFormatting: external_exports.array(external_exports.object({ + condition: external_exports.string().describe("Condition expression to evaluate"), + style: external_exports.record(external_exports.string(), external_exports.string()).describe("CSS styles to apply when condition is true") + })).optional().describe("Conditional formatting rules for list rows"), + /** Inline Edit */ + inlineEdit: external_exports.boolean().optional().describe("Allow inline editing of records directly in the list view"), + /** Export */ + exportOptions: external_exports.array(external_exports.enum(["csv", "xlsx", "pdf", "json"])).optional().describe("Available export format options"), + /** User Actions (Airtable Interface parity) */ + userActions: UserActionsConfigSchema.optional().describe("User action toggles for the view toolbar"), + /** Appearance (Airtable Interface parity) */ + appearance: AppearanceConfigSchema.optional().describe("Appearance and visualization configuration"), + /** Tabs (Airtable Interface parity) */ + tabs: external_exports.array(ViewTabSchema).optional().describe("Tab definitions for multi-tab view interface"), + /** Add Record (Airtable Interface parity) */ + addRecord: AddRecordConfigSchema.optional().describe("Add record entry point configuration"), + /** Record Count Display (Airtable Interface parity) */ + showRecordCount: external_exports.boolean().optional().describe("Show record count at the bottom of the list"), + /** Advanced: Allow Printing (Airtable Interface parity) */ + allowPrinting: external_exports.boolean().optional().describe("Allow users to print the view"), + /** Empty State */ + emptyState: external_exports.object({ + title: I18nLabelSchema2.optional(), + message: I18nLabelSchema2.optional(), + icon: external_exports.string().optional() + }).optional().describe("Empty state configuration when no records found"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema2.optional().describe("ARIA accessibility attributes for the list view"), + /** Responsive layout overrides per breakpoint */ + responsive: ResponsiveConfigSchema.optional().describe("Responsive layout configuration"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema.optional().describe("Performance optimization settings") +}); +var FormFieldSchema = external_exports.object({ + field: external_exports.string().describe("Field name (snake_case)"), + label: I18nLabelSchema2.optional().describe("Display label override"), + placeholder: I18nLabelSchema2.optional().describe("Placeholder text"), + helpText: I18nLabelSchema2.optional().describe("Help/hint text"), + readonly: external_exports.boolean().optional().describe("Read-only override"), + required: external_exports.boolean().optional().describe("Required override"), + hidden: external_exports.boolean().optional().describe("Hidden override"), + colSpan: external_exports.number().int().min(1).max(4).optional().describe("Column span in grid layout (1-4)"), + widget: external_exports.string().optional().describe("Custom widget/component name"), + dependsOn: external_exports.string().optional().describe("Parent field name for cascading"), + visibleOn: external_exports.string().optional().describe("Visibility condition expression") +}); +var FormSectionSchema = external_exports.object({ + label: I18nLabelSchema2.optional(), + collapsible: external_exports.boolean().default(false), + collapsed: external_exports.boolean().default(false), + columns: external_exports.enum(["1", "2", "3", "4"]).default("2").transform((val) => parseInt(val)), + fields: external_exports.array(external_exports.union([ + external_exports.string(), + // Legacy: simple field name + FormFieldSchema + // Enhanced: detailed field config + ])) +}); +var FormViewSchema = external_exports.object({ + type: external_exports.enum([ + "simple", + // Single column or sections + "tabbed", + // Tabs + "wizard", + // Step by step + "split", + // Master-Detail split + "drawer", + // Side panel + "modal" + // Dialog + ]).default("simple"), + /** Data Source Configuration */ + data: ViewDataSchema.optional().describe('Data source configuration (defaults to "object" provider)'), + sections: external_exports.array(FormSectionSchema).optional(), + // For simple layout + groups: external_exports.array(FormSectionSchema).optional(), + // Legacy support -> alias to sections + /** Default Sort for Related Lists (e.g., sort child records by date) */ + defaultSort: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + order: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction") + })).optional().describe("Default sort order for related list views within this form"), + /** Public form sharing configuration */ + sharing: SharingConfigSchema.optional().describe("Public sharing configuration for this form"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema2.optional().describe("ARIA accessibility attributes for the form view") +}); +var ViewSchema = external_exports.object({ + list: ListViewSchema.optional(), + // Default list view + form: FormViewSchema.optional(), + // Default form view + listViews: external_exports.record(external_exports.string(), ListViewSchema).optional().describe("Additional named list views"), + formViews: external_exports.record(external_exports.string(), FormViewSchema).optional().describe("Additional named form views") +}); +var RLSOperation = external_exports.enum(["select", "insert", "update", "delete", "all"]); +var RowLevelSecurityPolicySchema = external_exports.object({ + /** + * Unique identifier for this policy. + * Must be unique within the object. + * Use snake_case following ObjectStack naming conventions. + * + * @example "tenant_isolation", "owner_access", "manager_team_view" + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Policy unique identifier (snake_case)"), + /** + * Human-readable label for the policy. + * Used in admin UI and logs. + * + * @example "Multi-Tenant Data Isolation", "Owner-Based Access" + */ + label: external_exports.string().optional().describe("Human-readable policy label"), + /** + * Description explaining what this policy does and why. + * Helps with governance and compliance. + * + * @example "Ensures users can only access records from their own tenant organization" + */ + description: external_exports.string().optional().describe("Policy description and business justification"), + /** + * Target object (table) this policy applies to. + * Must reference a valid ObjectStack object name. + * + * @example "account", "opportunity", "contact", "custom_object" + */ + object: external_exports.string().describe("Target object name"), + /** + * Database operation(s) this policy applies to. + * + * - **select**: Controls read access (SELECT queries) + * - **insert**: Controls insert access (INSERT statements) + * - **update**: Controls update access (UPDATE statements) + * - **delete**: Controls delete access (DELETE statements) + * - **all**: Applies to all operations + * + * @example "select" - Most common, controls what users can view + * @example "all" - Apply same rule to all operations + */ + operation: RLSOperation.describe("Database operation this policy applies to"), + /** + * USING clause - Filter condition for SELECT/UPDATE/DELETE. + * + * This is a SQL-like expression evaluated for each row. + * Only rows where this expression returns TRUE are accessible. + * + * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed). + * For SELECT/UPDATE/DELETE operations, USING is required. + * + * **Security Note**: RLS conditions are executed at the database level with + * parameterized queries. The implementation must use prepared statements + * to prevent SQL injection. Never concatenate user input directly into + * RLS conditions. + * + * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations + * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain + * semantic equivalence. + * + * Available context variables: + * - `current_user.id` - Current user's ID + * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext) + * - `current_user.role` - Current user's role + * - `current_user.department` - Current user's department + * - `current_user.*` - Any custom user field + * - `NOW()` - Current timestamp + * - `CURRENT_DATE` - Current date + * - `CURRENT_TIME` - Current time + * + * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`), + * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`). + * Implementations must handle this mapping. + * + * Supported operators: + * - Comparison: =, !=, <, >, <=, >=, <> (not equal) + * - Logical: AND, OR, NOT + * - NULL checks: IS NULL, IS NOT NULL + * - Set operations: IN, NOT IN + * - String: LIKE, NOT LIKE, ILIKE (case-insensitive) + * - Pattern matching: ~ (regex), !~ (not regex) + * - Subqueries: (SELECT ...) + * - Array operations: ANY, ALL + * + * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE) + * + * @example "tenant_id = current_user.tenant_id" + * @example "owner_id = current_user.id OR created_by = current_user.id" + * @example "department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)" + * @example "status = 'active' AND expiry_date > NOW()" + */ + using: external_exports.string().optional().describe("Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies."), + /** + * CHECK clause - Validation for INSERT/UPDATE operations. + * + * Similar to USING but applies to new/modified rows. + * Prevents users from creating/updating rows they wouldn't be able to see. + * + * **Default Behavior**: If not specified, implementations should use the + * USING clause as the CHECK clause. This ensures data integrity by preventing + * users from creating records they cannot view. + * + * Use cases: + * - Prevent cross-tenant data creation + * - Enforce mandatory field values + * - Validate data integrity rules + * - Restrict certain operations (e.g., only allow creating "draft" status) + * + * @example "tenant_id = current_user.tenant_id" + * @example "status IN ('draft', 'pending')" - Only allow certain statuses + * @example "created_by = current_user.id" - Must be the creator + */ + check: external_exports.string().optional().describe("Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)"), + /** + * Restrict this policy to specific roles. + * If specified, only users with these roles will have this policy applied. + * If omitted, policy applies to all users (except those with bypassRLS permission). + * + * Role names must match defined roles in the system. + * + * @example ["sales_rep", "account_manager"] + * @example ["employee"] - Apply to all employees + * @example ["guest"] - Special restrictions for guests + */ + roles: external_exports.array(external_exports.string()).optional().describe("Roles this policy applies to (omit for all roles)"), + /** + * Whether this policy is currently active. + * Disabled policies are not evaluated. + * Useful for temporary policy changes without deletion. + * + * @default true + */ + enabled: external_exports.boolean().default(true).describe("Whether this policy is active"), + /** + * Policy priority for conflict resolution. + * Higher numbers = higher priority. + * When multiple policies apply, the most permissive wins (OR logic). + * Priority is only used for ordering evaluation (performance). + * + * @default 0 + */ + priority: external_exports.number().int().default(0).describe("Policy evaluation priority (higher = evaluated first)"), + /** + * Tags for policy categorization and reporting. + * Useful for governance, compliance, and auditing. + * + * @example ["compliance", "gdpr", "pci"] + * @example ["multi-tenant", "security"] + */ + tags: external_exports.array(external_exports.string()).optional().describe("Policy categorization tags") +}).superRefine((data, ctx) => { + if (!data.using && !data.check) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: 'At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".' + }); + } +}); +external_exports.object({ + /** ISO 8601 timestamp of the evaluation */ + timestamp: external_exports.string().describe("ISO 8601 timestamp of the evaluation"), + /** ID of the user whose access was evaluated */ + userId: external_exports.string().describe("User ID whose access was evaluated"), + /** Database operation being performed */ + operation: external_exports.enum(["select", "insert", "update", "delete"]).describe("Database operation being performed"), + /** Target object (table) name */ + object: external_exports.string().describe("Target object name"), + /** Name of the RLS policy evaluated */ + policyName: external_exports.string().describe("Name of the RLS policy evaluated"), + /** Whether access was granted */ + granted: external_exports.boolean().describe("Whether access was granted"), + /** Time taken to evaluate the policy in milliseconds */ + evaluationDurationMs: external_exports.number().describe("Policy evaluation duration in milliseconds"), + /** Which USING/CHECK clause matched */ + matchedCondition: external_exports.string().optional().describe("Which USING/CHECK clause matched"), + /** Number of rows affected by the operation */ + rowCount: external_exports.number().optional().describe("Number of rows affected"), + /** Additional metadata for the audit event */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional audit event metadata") +}); +var RLSAuditConfigSchema = external_exports.object({ + /** Enable RLS audit logging */ + enabled: external_exports.boolean().describe("Enable RLS audit logging"), + /** Which evaluations to log */ + logLevel: external_exports.enum(["all", "denied_only", "granted_only", "none"]).describe("Which evaluations to log"), + /** Where to send audit logs */ + destination: external_exports.enum(["system_log", "audit_trail", "external"]).describe("Audit log destination"), + /** Sampling rate for high-traffic environments (0-1) */ + sampleRate: external_exports.number().min(0).max(1).describe("Sampling rate (0-1) for high-traffic environments"), + /** Number of days to retain audit logs */ + retentionDays: external_exports.number().int().default(90).describe("Audit log retention period in days"), + /** Whether to include row data in audit logs (security-sensitive) */ + includeRowData: external_exports.boolean().default(false).describe("Include row data in audit logs (security-sensitive)"), + /** Alert when access is denied */ + alertOnDenied: external_exports.boolean().default(true).describe("Send alerts when access is denied") +}); +external_exports.object({ + /** + * Global RLS enable/disable flag. + * When false, all RLS policies are ignored (use with caution!). + * + * @default true + */ + enabled: external_exports.boolean().default(true).describe("Enable RLS enforcement globally"), + /** + * Default behavior when no policies match. + * + * - **deny**: Deny access (secure default) + * - **allow**: Allow access (permissive mode, not recommended) + * + * @default "deny" + */ + defaultPolicy: external_exports.enum(["deny", "allow"]).default("deny").describe("Default action when no policies match"), + /** + * Whether to allow superusers to bypass RLS. + * Superusers include system administrators and service accounts. + * + * @default true + */ + allowSuperuserBypass: external_exports.boolean().default(true).describe("Allow superusers to bypass RLS"), + /** + * List of roles that can bypass RLS. + * Users with these roles see all records regardless of policies. + * + * @example ["system_admin", "data_auditor"] + */ + bypassRoles: external_exports.array(external_exports.string()).optional().describe("Roles that bypass RLS (see all data)"), + /** + * Whether to log RLS policy evaluations. + * Useful for debugging and auditing. + * Can impact performance if enabled globally. + * + * @default false + */ + logEvaluations: external_exports.boolean().default(false).describe("Log RLS policy evaluations for debugging"), + /** + * Cache RLS policy evaluation results. + * Can improve performance for frequently accessed records. + * Cache is invalidated when policies change or user context changes. + * + * @default true + */ + cacheResults: external_exports.boolean().default(true).describe("Cache RLS evaluation results"), + /** + * Cache TTL in seconds. + * How long to cache RLS evaluation results. + * + * @default 300 (5 minutes) + */ + cacheTtlSeconds: external_exports.number().int().positive().default(300).describe("Cache TTL in seconds"), + /** + * Performance optimization: Pre-fetch user context. + * Load user context once per request instead of per-query. + * + * @default true + */ + prefetchUserContext: external_exports.boolean().default(true).describe("Pre-fetch user context for performance"), + /** + * Audit logging configuration for RLS evaluations. + */ + audit: RLSAuditConfigSchema.optional().describe("RLS audit logging configuration") +}); +external_exports.object({ + /** + * User ID + */ + id: external_exports.string().describe("User ID"), + /** + * User email + */ + email: external_exports.string().email().optional().describe("User email"), + /** + * Tenant/Organization ID + */ + tenantId: external_exports.string().optional().describe("Tenant/Organization ID"), + /** + * User role(s) + */ + role: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.string()) + ]).optional().describe("User role(s)"), + /** + * User department + */ + department: external_exports.string().optional().describe("User department"), + /** + * Additional custom attributes + * Can include any custom user fields for RLS evaluation + */ + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom user attributes") +}); +external_exports.object({ + /** + * Policy name that was evaluated + */ + policyName: external_exports.string().describe("Policy name"), + /** + * Whether access was granted + */ + granted: external_exports.boolean().describe("Whether access was granted"), + /** + * Evaluation duration in milliseconds + */ + durationMs: external_exports.number().optional().describe("Evaluation duration in milliseconds"), + /** + * Error message if evaluation failed + */ + error: external_exports.string().optional().describe("Error message if evaluation failed"), + /** + * Evaluated USING clause result + */ + usingResult: external_exports.boolean().optional().describe("USING clause evaluation result"), + /** + * Evaluated CHECK clause result (for INSERT/UPDATE) + */ + checkResult: external_exports.boolean().optional().describe("CHECK clause evaluation result") +}); +var ObjectPermissionSchema = external_exports.object({ + /** C: Create */ + allowCreate: external_exports.boolean().default(false).describe("Create permission"), + /** R: Read (Owned records or Shared records) */ + allowRead: external_exports.boolean().default(false).describe("Read permission"), + /** U: Edit (Owned records or Shared records) */ + allowEdit: external_exports.boolean().default(false).describe("Edit permission"), + /** D: Delete (Owned records or Shared records) */ + allowDelete: external_exports.boolean().default(false).describe("Delete permission"), + /** Lifecycle Operations */ + allowTransfer: external_exports.boolean().default(false).describe("Change record ownership"), + allowRestore: external_exports.boolean().default(false).describe("Restore from trash (Undelete)"), + allowPurge: external_exports.boolean().default(false).describe("Permanently delete (Hard Delete/GDPR)"), + /** + * View All Records: Super-user read access. + * Bypasses Sharing Rules and Ownership checks. + * Equivalent to Microsoft Dataverse "Organization" level read access. + */ + viewAllRecords: external_exports.boolean().default(false).describe("View All Data (Bypass Sharing)"), + /** + * Modify All Records: Super-user write access. + * Bypasses Sharing Rules and Ownership checks. + * Equivalent to Microsoft Dataverse "Organization" level write access. + */ + modifyAllRecords: external_exports.boolean().default(false).describe("Modify All Data (Bypass Sharing)") +}); +var FieldPermissionSchema = external_exports.object({ + /** Can see this field */ + readable: external_exports.boolean().default(true).describe("Field read access"), + /** Can edit this field */ + editable: external_exports.boolean().default(false).describe("Field edit access") +}); +external_exports.object({ + /** Unique permission set name */ + name: SnakeCaseIdentifierSchema2.describe("Permission set unique name (lowercase snake_case)"), + /** Display label */ + label: external_exports.string().optional().describe("Display label"), + /** Is this a Profile? (Base set for a user) */ + isProfile: external_exports.boolean().default(false).describe("Whether this is a user profile"), + /** Object Permissions Map: -> permissions */ + objects: external_exports.record(external_exports.string(), ObjectPermissionSchema).describe("Entity permissions"), + /** Field Permissions Map: . -> permissions */ + fields: external_exports.record(external_exports.string(), FieldPermissionSchema).optional().describe("Field level security"), + /** System permissions (e.g., "manage_users") */ + systemPermissions: external_exports.array(external_exports.string()).optional().describe("System level capabilities"), + /** + * Tab/App Visibility Permissions (Salesforce Pattern) + * Controls which app tabs are visible, hidden, or set as default for this permission set. + * + * @example + * ```typescript + * tabPermissions: { + * 'app_crm': 'visible', + * 'app_admin': 'hidden', + * 'app_sales': 'default_on' + * } + * ``` + */ + tabPermissions: external_exports.record(external_exports.string(), external_exports.enum(["visible", "hidden", "default_on", "default_off"])).optional().describe("App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)"), + /** + * Row-Level Security Rules + * + * Row-level security policies that filter records based on user context. + * These rules are applied in addition to object-level permissions. + * + * Uses the canonical RLS protocol from rls.zod.ts for comprehensive + * row-level security features including PostgreSQL-style USING and CHECK clauses. + * + * @see {@link RowLevelSecurityPolicySchema} for full RLS specification + * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation + * + * @example Multi-tenant isolation + * ```typescript + * rls: [{ + * name: 'tenant_filter', + * object: 'account', + * operation: 'select', + * using: 'tenant_id = current_user.tenant_id' + * }] + * ``` + */ + rowLevelSecurity: external_exports.array(RowLevelSecurityPolicySchema).optional().describe("Row-level security policies (see rls.zod.ts for full spec)"), + /** + * Context-Based Access Control Variables + * + * Custom context variables that can be referenced in RLS rules. + * These variables are evaluated at runtime based on the user's session. + * + * Common context variables: + * - `current_user.id` - Current user ID + * - `current_user.tenant_id` - User's tenant/organization ID + * - `current_user.department` - User's department + * - `current_user.role` - User's role + * - `current_user.region` - User's geographic region + * + * @example Custom context + * ```typescript + * contextVariables: { + * allowed_regions: ['US', 'EU'], + * access_level: 2, + * custom_attribute: 'value' + * } + * ``` + */ + contextVariables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Context variables for RLS evaluation") +}); +var WorkflowTriggerType = external_exports.enum([ + "on_create", + // When record is created + "on_update", + // When record is updated + "on_create_or_update", + // Both + "on_delete", + // When record is deleted + "schedule" + // Time-based (cron) +]); +var FieldUpdateActionSchema = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("field_update"), + field: external_exports.string().describe("Field to update"), + value: external_exports.unknown().describe("Value or Formula to set") +}); +var EmailAlertActionSchema = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("email_alert"), + template: external_exports.string().describe("Email template ID/DevName"), + recipients: external_exports.array(external_exports.string()).describe("List of recipient emails or user IDs") +}); +var ConnectorActionRefSchema = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("connector_action"), + connectorId: external_exports.string().describe("Target Connector ID (e.g. slack, twilio)"), + actionId: external_exports.string().describe("Target Action ID (e.g. send_message)"), + input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Input parameters matching the action schema") +}); +var HttpCallActionSchema = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("http_call"), + url: external_exports.string().describe("Target URL"), + method: external_exports.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).default("POST").describe("HTTP Method"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP Headers"), + body: external_exports.string().optional().describe("Request body (JSON or text)") +}); +var TaskCreationActionSchema = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("task_creation"), + taskObject: external_exports.string().describe('Task object name (e.g., "task", "project_task")'), + subject: external_exports.string().describe("Task subject/title"), + description: external_exports.string().optional().describe("Task description"), + assignedTo: external_exports.string().optional().describe("User ID or field reference for assignee"), + dueDate: external_exports.string().optional().describe("Due date (ISO string or formula)"), + priority: external_exports.string().optional().describe("Task priority"), + relatedTo: external_exports.string().optional().describe("Related record ID or field reference"), + additionalFields: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom fields") +}); +var PushNotificationActionSchema = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("push_notification"), + title: external_exports.string().describe("Notification title"), + body: external_exports.string().describe("Notification body text"), + recipients: external_exports.array(external_exports.string()).describe("User IDs or device tokens"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data payload"), + badge: external_exports.number().optional().describe("Badge count (iOS)"), + sound: external_exports.string().optional().describe("Notification sound"), + clickAction: external_exports.string().optional().describe("Action/URL when notification is clicked") +}); +var CustomScriptActionSchema = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("custom_script"), + language: external_exports.enum(["javascript", "typescript", "python"]).default("javascript").describe("Script language"), + code: external_exports.string().describe("Script code to execute"), + timeout: external_exports.number().default(3e4).describe("Execution timeout in milliseconds"), + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context variables") +}); +var WorkflowActionSchema = external_exports.discriminatedUnion("type", [ + FieldUpdateActionSchema, + EmailAlertActionSchema, + HttpCallActionSchema, + ConnectorActionRefSchema, + TaskCreationActionSchema, + PushNotificationActionSchema, + CustomScriptActionSchema +]); +var TimeTriggerSchema = external_exports.object({ + id: external_exports.string().optional().describe("Unique identifier"), + /** Timing Logic */ + timeLength: external_exports.number().int().describe("Duration amount (e.g. 1, 30)"), + timeUnit: external_exports.enum(["minutes", "hours", "days"]).describe("Unit of time"), + /** Reference Point */ + offsetDirection: external_exports.enum(["before", "after"]).describe("Before or After the reference date"), + offsetFrom: external_exports.enum(["trigger_date", "date_field"]).describe("Basis for calculation"), + dateField: external_exports.string().optional().describe("Date field to calculate from (required if offsetFrom is date_field)"), + /** Actions */ + actions: external_exports.array(WorkflowActionSchema).describe("Actions to execute at the scheduled time") +}); +var WorkflowRuleSchema = external_exports.object({ + /** Machine name */ + name: SnakeCaseIdentifierSchema2.describe("Unique workflow name (lowercase snake_case)"), + /** Target Object */ + objectName: external_exports.string().describe("Target Object"), + /** When to evaluate the rule */ + triggerType: WorkflowTriggerType.describe("When to evaluate"), + /** + * Condition to start the workflow. + * If empty, runs on every trigger event. + */ + criteria: external_exports.string().optional().describe("Formula condition. If TRUE, actions execute."), + /** Actions to execute immediately */ + actions: external_exports.array(WorkflowActionSchema).optional().describe("Immediate actions"), + /** + * Time-Dependent Actions + * Actions scheduled to run in the future. + */ + timeTriggers: external_exports.array(TimeTriggerSchema).optional().describe("Scheduled actions relative to trigger or date field"), + /** Active status */ + active: external_exports.boolean().default(true).describe("Whether this workflow is active"), + /** Execution Order */ + executionOrder: external_exports.number().int().min(0).default(100).describe("Deterministic execution order when multiple workflows match (lower runs first)"), + /** Recursion Control */ + reevaluateOnChange: external_exports.boolean().default(false).describe("Re-evaluate rule if field updates change the record validity") +}); +var LocaleSchema2 = external_exports.string().describe("BCP-47 Language Tag (e.g. en-US, zh-CN)"); +var FieldTranslationSchema2 = external_exports.object({ + label: external_exports.string().optional().describe("Translated field label"), + help: external_exports.string().optional().describe("Translated help text"), + placeholder: external_exports.string().optional().describe("Translated placeholder text for form inputs"), + options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Option value to translated label map") +}).describe("Translation data for a single field"); +var ObjectTranslationDataSchema2 = external_exports.object({ + /** Translated singular label for the object */ + label: external_exports.string().describe("Translated singular label"), + /** Translated plural label for the object */ + pluralLabel: external_exports.string().optional().describe("Translated plural label"), + /** Field-level translations keyed by field name (snake_case) */ + fields: external_exports.record(external_exports.string(), FieldTranslationSchema2).optional().describe("Field-level translations") +}).describe("Translation data for a single object"); +var TranslationDataSchema2 = external_exports.object({ + /** Object translations */ + objects: external_exports.record(external_exports.string(), ObjectTranslationDataSchema2).optional().describe("Object translations keyed by object name"), + /** App/Menu translations */ + apps: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().describe("Translated app label"), + description: external_exports.string().optional().describe("Translated app description") + })).optional().describe("App translations keyed by app name"), + /** UI Messages */ + messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID"), + /** Validation Error Messages */ + validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%"})') +}).describe("Translation data for objects, apps, and UI messages"); +external_exports.record(LocaleSchema2, TranslationDataSchema2).describe("Map of locale codes to translation data"); +var TranslationFileOrganizationSchema2 = external_exports.enum([ + "bundled", + "per_locale", + "per_namespace" +]).describe("Translation file organization strategy"); +var MessageFormatSchema2 = external_exports.enum([ + "icu", + "simple" +]).describe("Message interpolation format: ICU MessageFormat or simple {variable} replacement"); +external_exports.object({ + /** Default locale for the application */ + defaultLocale: LocaleSchema2.describe('Default locale (e.g., "en")'), + /** Supported BCP-47 locale codes */ + supportedLocales: external_exports.array(LocaleSchema2).describe("Supported BCP-47 locale codes"), + /** Fallback locale when translation is not found */ + fallbackLocale: LocaleSchema2.optional().describe("Fallback locale code"), + /** How translation files are organized on disk */ + fileOrganization: TranslationFileOrganizationSchema2.default("per_locale").describe("File organization strategy"), + /** + * Message interpolation format. + * When set to `'icu'`, messages and validationMessages are expected to use + * ICU MessageFormat syntax (plurals, select, number/date skeletons). + * @default 'simple' + */ + messageFormat: MessageFormatSchema2.default("simple").describe("Message interpolation format (ICU MessageFormat or simple)"), + /** Load translations on demand instead of eagerly */ + lazyLoad: external_exports.boolean().default(false).describe("Load translations on demand"), + /** Cache loaded translations in memory */ + cache: external_exports.boolean().default(true).describe("Cache loaded translations") +}).describe("Internationalization configuration"); +var OptionTranslationMapSchema2 = external_exports.record(external_exports.string(), external_exports.string()).describe("Option value to translated label map"); +var ObjectTranslationNodeSchema2 = external_exports.object({ + /** Translated singular label */ + label: external_exports.string().describe("Translated singular label"), + /** Translated plural label */ + pluralLabel: external_exports.string().optional().describe("Translated plural label"), + /** Translated object description */ + description: external_exports.string().optional().describe("Translated object description"), + /** Translated help text shown in tooltips or guidance panels */ + helpText: external_exports.string().optional().describe("Translated help text for the object"), + /** Field-level translations keyed by field name (snake_case) */ + fields: external_exports.record(external_exports.string(), FieldTranslationSchema2).optional().describe("Field translations keyed by field name"), + /** + * Global picklist / select option overrides scoped to this object. + * Keyed by field name → { optionValue: translatedLabel }. + */ + _options: external_exports.record(external_exports.string(), OptionTranslationMapSchema2).optional().describe("Object-scoped picklist option translations keyed by field name"), + /** View translations keyed by view name */ + _views: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated view label"), + description: external_exports.string().optional().describe("Translated view description") + })).optional().describe("View translations keyed by view name"), + /** Section (form section / tab) translations keyed by section name */ + _sections: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated section label") + })).optional().describe("Section translations keyed by section name"), + /** Action translations keyed by action name */ + _actions: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated action label"), + confirmMessage: external_exports.string().optional().describe("Translated confirmation message") + })).optional().describe("Action translations keyed by action name"), + /** Notification message translations keyed by notification name */ + _notifications: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated notification title"), + body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") + })).optional().describe("Notification translations keyed by notification name"), + /** Error message translations keyed by error code */ + _errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Error message translations keyed by error code") +}).describe("Object-first aggregated translation node"); +external_exports.object({ + /** + * Bundle-level metadata. + * Provides locale-aware rendering hints such as text direction (bidi) + * and the canonical locale code this bundle represents. + */ + _meta: external_exports.object({ + /** BCP-47 locale code this bundle represents */ + locale: external_exports.string().optional().describe("BCP-47 locale code for this bundle"), + /** Text direction for the locale */ + direction: external_exports.enum(["ltr", "rtl"]).optional().describe("Text direction: left-to-right or right-to-left") + }).optional().describe("Bundle-level metadata (locale, bidi direction)"), + /** + * Namespace for plugin/extension isolation. + * When multiple plugins contribute translations, each should use a unique + * namespace to avoid key collisions (e.g. "crm", "helpdesk", "plugin-xyz"). + */ + namespace: external_exports.string().optional().describe("Namespace for plugin isolation to avoid translation key collisions"), + /** Object-first translations keyed by object name (snake_case) */ + o: external_exports.record(external_exports.string(), ObjectTranslationNodeSchema2).optional().describe("Object-first translations keyed by object name"), + /** Global picklist options not bound to any specific object */ + _globalOptions: external_exports.record(external_exports.string(), OptionTranslationMapSchema2).optional().describe("Global picklist option translations keyed by option set name"), + /** App-level translations */ + app: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().describe("Translated app label"), + description: external_exports.string().optional().describe("Translated app description") + })).optional().describe("App translations keyed by app name"), + /** Navigation menu translations */ + nav: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Navigation item translations keyed by nav item name"), + /** Dashboard translations keyed by dashboard name */ + dashboard: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated dashboard label"), + description: external_exports.string().optional().describe("Translated dashboard description") + })).optional().describe("Dashboard translations keyed by dashboard name"), + /** Report translations keyed by report name */ + reports: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated report label"), + description: external_exports.string().optional().describe("Translated report description") + })).optional().describe("Report translations keyed by report name"), + /** Page translations keyed by page name */ + pages: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated page title"), + description: external_exports.string().optional().describe("Translated page description") + })).optional().describe("Page translations keyed by page name"), + /** UI message translations (supports ICU MessageFormat when enabled) */ + messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID (supports ICU MessageFormat)"), + /** Validation error message translations (supports ICU MessageFormat when enabled) */ + validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Validation error message translations keyed by rule name (supports ICU MessageFormat)"), + /** Global notification translations not bound to a specific object */ + notifications: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated notification title"), + body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") + })).optional().describe("Global notification translations keyed by notification name"), + /** Global error message translations not bound to a specific object */ + errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Global error message translations keyed by error code") +}).describe("Object-first application translation bundle for a single locale"); +var TranslationDiffStatusSchema2 = external_exports.enum([ + "missing", + "redundant", + "stale" +]).describe("Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)"); +var TranslationDiffItemSchema2 = external_exports.object({ + /** Dot-path translation key (e.g. "o.account.fields.website.label") */ + key: external_exports.string().describe("Dot-path translation key"), + /** Diff status */ + status: TranslationDiffStatusSchema2.describe("Diff status of this translation key"), + /** Object name if the key belongs to an object translation node */ + objectName: external_exports.string().optional().describe("Associated object name (snake_case)"), + /** Locale code */ + locale: external_exports.string().describe("BCP-47 locale code"), + /** + * Hash of the source metadata value at the time the translation was made. + * Used by CLI/Workbench to detect stale translations without a full diff. + */ + sourceHash: external_exports.string().optional().describe("Hash of source metadata for precise stale detection"), + /** + * AI-suggested translation text for missing or stale entries. + * Populated by AI translation hooks or TMS integrations. + */ + aiSuggested: external_exports.string().optional().describe("AI-suggested translation for this key"), + /** Confidence score (0-1) for the AI suggestion */ + aiConfidence: external_exports.number().min(0).max(1).optional().describe("AI suggestion confidence score (0\u20131)") +}).describe("A single translation diff item"); +var CoverageBreakdownEntrySchema2 = external_exports.object({ + /** Group category (e.g. "fields", "views", "actions", "messages") */ + group: external_exports.string().describe("Translation group category"), + /** Total translatable keys in this group */ + totalKeys: external_exports.number().int().nonnegative().describe("Total keys in this group"), + /** Number of translated keys in this group */ + translatedKeys: external_exports.number().int().nonnegative().describe("Translated keys in this group"), + /** Coverage percentage for this group */ + coveragePercent: external_exports.number().min(0).max(100).describe("Coverage percentage for this group") +}).describe("Coverage breakdown for a single translation group"); +external_exports.object({ + /** BCP-47 locale code */ + locale: external_exports.string().describe("BCP-47 locale code"), + /** Optional object name scope */ + objectName: external_exports.string().optional().describe("Object name scope (omit for full bundle)"), + /** Total translatable keys derived from metadata */ + totalKeys: external_exports.number().int().nonnegative().describe("Total translatable keys from metadata"), + /** Number of keys that have a translation */ + translatedKeys: external_exports.number().int().nonnegative().describe("Number of translated keys"), + /** Number of missing translations */ + missingKeys: external_exports.number().int().nonnegative().describe("Number of missing translations"), + /** Number of redundant (orphaned) translations */ + redundantKeys: external_exports.number().int().nonnegative().describe("Number of redundant translations"), + /** Number of stale translations */ + staleKeys: external_exports.number().int().nonnegative().describe("Number of stale translations"), + /** Coverage percentage (0-100) */ + coveragePercent: external_exports.number().min(0).max(100).describe("Translation coverage percentage"), + /** Individual diff items */ + items: external_exports.array(TranslationDiffItemSchema2).describe("Detailed diff items"), + /** + * Per-group coverage breakdown for translation project management. + * Each entry represents a logical group (e.g. "fields", "views", "actions", + * "messages") with its own coverage statistics. + */ + breakdown: external_exports.array(CoverageBreakdownEntrySchema2).optional().describe("Per-group coverage breakdown") +}).describe("Aggregated translation coverage result"); +var CapabilityConformanceLevelSchema = external_exports.enum([ + "full", + // Complete implementation of all protocol features + "partial", + // Subset implementation with specific features listed + "experimental", + // Unstable/preview implementation + "deprecated" + // Still supported but scheduled for removal +]).describe("Level of protocol conformance"); +var ProtocolVersionSchema = external_exports.object({ + major: external_exports.number().int().min(0), + minor: external_exports.number().int().min(0), + patch: external_exports.number().int().min(0) +}).describe("Semantic version of the protocol"); +var ProtocolReferenceSchema = external_exports.object({ + /** + * Protocol identifier using reverse domain notation. + * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major} + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+protocol\.[a-z][a-z0-9._]*\.v\d+$/).describe("Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)"), + /** + * Human-readable protocol name + */ + label: external_exports.string(), + /** + * Protocol version + */ + version: ProtocolVersionSchema, + /** + * Detailed protocol specification URL or file reference + */ + specification: external_exports.string().optional().describe("URL or path to protocol specification"), + /** + * Brief description of what this protocol defines + */ + description: external_exports.string().optional() +}); +var ProtocolFeatureSchema = external_exports.object({ + name: external_exports.string().describe("Feature identifier within the protocol"), + enabled: external_exports.boolean().default(true), + description: external_exports.string().optional(), + sinceVersion: external_exports.string().optional().describe("Version when this feature was added"), + deprecatedSince: external_exports.string().optional().describe("Version when deprecated") +}); +var PluginCapabilitySchema = external_exports.object({ + /** + * The protocol being implemented + */ + protocol: ProtocolReferenceSchema, + /** + * Conformance level + */ + conformance: CapabilityConformanceLevelSchema.default("full"), + /** + * Specific features implemented (required if conformance is 'partial') + */ + implementedFeatures: external_exports.array(external_exports.string()).optional().describe("List of implemented feature names"), + /** + * Optional feature flags indicating advanced capabilities + */ + features: external_exports.array(ProtocolFeatureSchema).optional(), + /** + * Custom metadata for vendor-specific information + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Testing/Certification status + */ + certified: external_exports.boolean().default(false).describe("Has passed official conformance tests"), + certificationDate: external_exports.string().datetime().optional() +}); +var PluginInterfaceSchema = external_exports.object({ + /** + * Unique interface identifier + * Format: {plugin-id}.interface.{name} + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+interface\.[a-z][a-z0-9._]+$/).describe("Unique interface identifier"), + /** + * Interface name + */ + name: external_exports.string(), + /** + * Description of what this interface provides + */ + description: external_exports.string().optional(), + /** + * Interface version + */ + version: ProtocolVersionSchema, + /** + * Methods exposed by this interface + */ + methods: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Method name"), + description: external_exports.string().optional(), + parameters: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string().describe("Type notation (e.g., string, number, User)"), + required: external_exports.boolean().default(true), + description: external_exports.string().optional() + })).optional(), + returnType: external_exports.string().optional().describe("Return value type"), + async: external_exports.boolean().default(false).describe("Whether method returns a Promise") + })), + /** + * Events emitted by this interface + */ + events: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Event name"), + description: external_exports.string().optional(), + payload: external_exports.string().optional().describe("Event payload type") + })).optional(), + /** + * Stability level + */ + stability: external_exports.enum(["stable", "beta", "alpha", "experimental"]).default("stable") +}); +var PluginDependencySchema = external_exports.object({ + /** + * Plugin ID using reverse domain notation + */ + pluginId: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Required plugin identifier"), + /** + * Version constraint (supports semver ranges) + * Examples: "1.0.0", "^1.2.3", ">=2.0.0 <3.0.0" + */ + version: external_exports.string().describe("Semantic version constraint"), + /** + * Whether this dependency is optional + */ + optional: external_exports.boolean().default(false), + /** + * Reason for the dependency + */ + reason: external_exports.string().optional(), + /** + * Minimum required capabilities from the dependency + */ + requiredCapabilities: external_exports.array(external_exports.string()).optional().describe("Protocol IDs the dependency must support") +}); +var ExtensionPointSchema = external_exports.object({ + /** + * Extension point identifier + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+extension\.[a-z][a-z0-9._]+$/).describe("Unique extension point identifier"), + /** + * Extension point name + */ + name: external_exports.string(), + /** + * Description + */ + description: external_exports.string().optional(), + /** + * Type of extension point + */ + type: external_exports.enum([ + "action", + // Plugins can register executable actions + "hook", + // Plugins can listen to lifecycle events + "widget", + // Plugins can contribute UI widgets + "provider", + // Plugins can provide data/services + "transformer", + // Plugins can transform data + "validator", + // Plugins can validate data + "decorator" + // Plugins can enhance/wrap functionality + ]), + /** + * Expected interface contract for extensions + */ + contract: external_exports.object({ + input: external_exports.string().optional().describe("Input type/schema"), + output: external_exports.string().optional().describe("Output type/schema"), + signature: external_exports.string().optional().describe("Function signature if applicable") + }).optional(), + /** + * Cardinality + */ + cardinality: external_exports.enum(["single", "multiple"]).default("multiple").describe("Whether multiple extensions can register to this point") +}); +var PluginCapabilityManifestSchema = external_exports.object({ + /** + * Protocols this plugin implements + */ + implements: external_exports.array(PluginCapabilitySchema).optional().describe("List of protocols this plugin conforms to"), + /** + * Interfaces this plugin exposes to other plugins + */ + provides: external_exports.array(PluginInterfaceSchema).optional().describe("Services/APIs this plugin offers to others"), + /** + * Dependencies on other plugins + */ + requires: external_exports.array(PluginDependencySchema).optional().describe("Required plugins and their capabilities"), + /** + * Extension points this plugin defines + */ + extensionPoints: external_exports.array(ExtensionPointSchema).optional().describe("Points where other plugins can extend this plugin"), + /** + * Extensions this plugin contributes to other plugins + */ + extensions: external_exports.array(external_exports.object({ + targetPluginId: external_exports.string().describe("Plugin ID being extended"), + extensionPointId: external_exports.string().describe("Extension point identifier"), + implementation: external_exports.string().describe("Path to implementation module"), + priority: external_exports.number().int().default(100).describe("Registration priority (lower = higher priority)") + })).optional().describe("Extensions contributed to other plugins") +}); +var PluginLoadingStrategySchema = external_exports.enum([ + "eager", + // Load immediately during bootstrap (critical plugins) + "lazy", + // Load on first use (feature plugins) + "parallel", + // Load in parallel with other plugins + "deferred", + // Load after initial bootstrap complete + "on-demand" + // Load only when explicitly requested +]).describe("Plugin loading strategy"); +var PluginPreloadConfigSchema = external_exports.object({ + /** + * Enable preloading for this plugin + */ + enabled: external_exports.boolean().default(false), + /** + * Preload priority (lower = higher priority) + */ + priority: external_exports.number().int().min(0).default(100), + /** + * Resources to preload + */ + resources: external_exports.array(external_exports.enum([ + "metadata", + // Plugin manifest and metadata + "dependencies", + // Plugin dependencies + "assets", + // Static assets (icons, translations) + "code", + // JavaScript code chunks + "services" + // Service definitions + ])).optional(), + /** + * Conditions for preloading + */ + conditions: external_exports.object({ + /** + * Preload only on specific routes + */ + routes: external_exports.array(external_exports.string()).optional(), + /** + * Preload only for specific user roles + */ + roles: external_exports.array(external_exports.string()).optional(), + /** + * Preload based on device type + */ + deviceType: external_exports.array(external_exports.enum(["desktop", "mobile", "tablet"])).optional(), + /** + * Network connection quality threshold + */ + minNetworkSpeed: external_exports.enum(["slow-2g", "2g", "3g", "4g"]).optional() + }).optional() +}).describe("Plugin preloading configuration"); +var PluginCodeSplittingSchema = external_exports.object({ + /** + * Enable code splitting for this plugin + */ + enabled: external_exports.boolean().default(true), + /** + * Split strategy + */ + strategy: external_exports.enum([ + "route", + // Split by UI routes + "feature", + // Split by feature modules + "size", + // Split by bundle size threshold + "custom" + // Custom split points defined by plugin + ]).default("feature"), + /** + * Chunk naming strategy + */ + chunkNaming: external_exports.enum(["hashed", "named", "sequential"]).default("hashed"), + /** + * Maximum chunk size in KB + */ + maxChunkSize: external_exports.number().int().min(10).optional().describe("Max chunk size in KB"), + /** + * Shared dependencies optimization + */ + sharedDependencies: external_exports.object({ + enabled: external_exports.boolean().default(true), + /** + * Minimum times a module must be shared before extraction + */ + minChunks: external_exports.number().int().min(1).default(2) + }).optional() +}).describe("Plugin code splitting configuration"); +var PluginDynamicImportSchema = external_exports.object({ + /** + * Enable dynamic imports + */ + enabled: external_exports.boolean().default(true), + /** + * Import mode + */ + mode: external_exports.enum([ + "async", + // Asynchronous import (recommended) + "sync", + // Synchronous import (blocking) + "eager", + // Eager evaluation + "lazy" + // Lazy evaluation + ]).default("async"), + /** + * Prefetch strategy + */ + prefetch: external_exports.boolean().default(false).describe("Prefetch module in idle time"), + /** + * Preload strategy + */ + preload: external_exports.boolean().default(false).describe("Preload module in parallel with parent"), + /** + * Webpack magic comments support + */ + webpackChunkName: external_exports.string().optional().describe("Custom chunk name for webpack"), + /** + * Import timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4).describe("Dynamic import timeout (ms)"), + /** + * Retry configuration on import failure + */ + retry: external_exports.object({ + enabled: external_exports.boolean().default(true), + maxAttempts: external_exports.number().int().min(1).max(10).default(3), + backoffMs: external_exports.number().int().min(0).default(1e3).describe("Exponential backoff base delay") + }).optional() +}).describe("Plugin dynamic import configuration"); +var PluginInitializationSchema = external_exports.object({ + /** + * Initialization mode + */ + mode: external_exports.enum([ + "sync", + // Synchronous initialization + "async", + // Asynchronous initialization + "parallel", + // Parallel with other plugins + "sequential" + // Must complete before next plugin + ]).default("async"), + /** + * Initialization timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4), + /** + * Startup priority (lower = higher priority, earlier initialization) + */ + priority: external_exports.number().int().min(0).default(100), + /** + * Whether to continue bootstrap if this plugin fails + */ + critical: external_exports.boolean().default(false).describe("If true, kernel bootstrap fails if plugin fails"), + /** + * Retry configuration on initialization failure + */ + retry: external_exports.object({ + enabled: external_exports.boolean().default(false), + maxAttempts: external_exports.number().int().min(1).max(5).default(3), + backoffMs: external_exports.number().int().min(0).default(1e3) + }).optional(), + /** + * Health check interval for monitoring + */ + healthCheckInterval: external_exports.number().int().min(0).optional().describe("Health check interval in ms (0 = disabled)") +}).describe("Plugin initialization configuration"); +var PluginDependencyResolutionSchema = external_exports.object({ + /** + * Dependency resolution strategy + */ + strategy: external_exports.enum([ + "strict", + // Exact version match required + "compatible", + // Semver compatible versions (^) + "latest", + // Always use latest compatible + "pinned" + // Lock to specific version + ]).default("compatible"), + /** + * Peer dependency handling + */ + peerDependencies: external_exports.object({ + /** + * Whether to resolve peer dependencies + */ + resolve: external_exports.boolean().default(true), + /** + * Action on missing peer dependency + */ + onMissing: external_exports.enum(["error", "warn", "ignore"]).default("warn"), + /** + * Action on peer version mismatch + */ + onMismatch: external_exports.enum(["error", "warn", "ignore"]).default("warn") + }).optional(), + /** + * Optional dependency handling + */ + optionalDependencies: external_exports.object({ + /** + * Whether to attempt loading optional dependencies + */ + load: external_exports.boolean().default(true), + /** + * Action on optional dependency load failure + */ + onFailure: external_exports.enum(["warn", "ignore"]).default("warn") + }).optional(), + /** + * Conflict resolution + */ + conflictResolution: external_exports.enum([ + "fail", + // Fail on any version conflict + "latest", + // Use latest version + "oldest", + // Use oldest version + "manual" + // Require manual resolution + ]).default("latest"), + /** + * Circular dependency handling + */ + circularDependencies: external_exports.enum([ + "error", + // Throw error on circular dependency + "warn", + // Warn but continue + "allow" + // Allow circular dependencies + ]).default("warn") +}).describe("Plugin dependency resolution configuration"); +var PluginHotReloadSchema = external_exports.object({ + /** + * Enable hot reload + */ + enabled: external_exports.boolean().default(false), + /** + * Target environment for hot reload behavior + */ + environment: external_exports.enum([ + "development", + // Fast reload with relaxed safety (file watchers, no health validation) + "staging", + // Production-like reload with validation but relaxed rollback + "production" + // Full safety: health validation, rollback, connection draining + ]).default("development").describe("Target environment controlling safety level"), + /** + * Hot reload strategy + */ + strategy: external_exports.enum([ + "full", + // Full plugin reload (destroy and reinitialize) + "partial", + // Partial reload (update changed modules only) + "state-preserve" + // Preserve plugin state during reload + ]).default("full"), + /** + * Files to watch for changes + */ + watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to watch"), + /** + * Files to ignore + */ + ignorePatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to ignore"), + /** + * Debounce delay in milliseconds + */ + debounceMs: external_exports.number().int().min(0).default(300), + /** + * Whether to preserve state during reload + */ + preserveState: external_exports.boolean().default(false), + /** + * State serialization + */ + stateSerialization: external_exports.object({ + enabled: external_exports.boolean().default(false), + /** + * Path to state serialization handler + */ + handler: external_exports.string().optional() + }).optional(), + /** + * Hooks for hot reload lifecycle + */ + hooks: external_exports.object({ + beforeReload: external_exports.string().optional().describe("Function to call before reload"), + afterReload: external_exports.string().optional().describe("Function to call after reload"), + onError: external_exports.string().optional().describe("Function to call on reload error") + }).optional(), + /** + * Production safety configuration + * Applied when environment is 'staging' or 'production' + */ + productionSafety: external_exports.object({ + /** + * Validate plugin health before completing reload + */ + healthValidation: external_exports.boolean().default(true).describe("Run health checks after reload before accepting traffic"), + /** + * Automatically rollback to previous version on reload failure + */ + rollbackOnFailure: external_exports.boolean().default(true).describe("Auto-rollback if reloaded plugin fails health check"), + /** + * Maximum time to wait for health validation after reload (ms) + */ + healthTimeout: external_exports.number().int().min(1e3).default(3e4).describe("Health check timeout after reload in ms"), + /** + * Drain active connections before reload + */ + drainConnections: external_exports.boolean().default(true).describe("Gracefully drain active requests before reloading"), + /** + * Maximum time to wait for connection draining (ms) + */ + drainTimeout: external_exports.number().int().min(0).default(15e3).describe("Max wait time for connection draining in ms"), + /** + * Maximum number of concurrent plugin reloads + */ + maxConcurrentReloads: external_exports.number().int().min(1).default(1).describe("Limit concurrent reloads to prevent system instability"), + /** + * Minimum interval between reloads of the same plugin (ms) + */ + minReloadInterval: external_exports.number().int().min(1e3).default(5e3).describe("Cooldown period between reloads of the same plugin") + }).optional() +}).describe("Plugin hot reload configuration"); +var PluginCachingSchema = external_exports.object({ + /** + * Enable caching + */ + enabled: external_exports.boolean().default(true), + /** + * Cache storage type + */ + storage: external_exports.enum([ + "memory", + // In-memory cache (fastest, not persistent) + "disk", + // Disk cache (persistent) + "indexeddb", + // Browser IndexedDB (persistent, browser only) + "hybrid" + // Memory + Disk hybrid + ]).default("memory"), + /** + * Cache key strategy + */ + keyStrategy: external_exports.enum([ + "version", + // Cache by plugin version + "hash", + // Cache by content hash + "timestamp" + // Cache by last modified timestamp + ]).default("version"), + /** + * Cache TTL in seconds + */ + ttl: external_exports.number().int().min(0).optional().describe("Time to live in seconds (0 = infinite)"), + /** + * Maximum cache size in MB + */ + maxSize: external_exports.number().int().min(1).optional().describe("Max cache size in MB"), + /** + * Cache invalidation triggers + */ + invalidateOn: external_exports.array(external_exports.enum([ + "version-change", + "dependency-change", + "manual", + "error" + ])).optional(), + /** + * Compression + */ + compression: external_exports.object({ + enabled: external_exports.boolean().default(false), + algorithm: external_exports.enum(["gzip", "brotli", "deflate"]).default("gzip") + }).optional() +}).describe("Plugin caching configuration"); +var PluginSandboxingSchema = external_exports.object({ + /** + * Enable sandboxing + */ + enabled: external_exports.boolean().default(false), + /** + * Isolation scope - which plugins are subject to sandboxing + */ + scope: external_exports.enum([ + "automation-only", + // Sandbox automation/scripting plugins only (current behavior) + "untrusted-only", + // Sandbox plugins below a trust threshold + "all-plugins" + // Sandbox all plugins (maximum isolation) + ]).default("automation-only").describe("Which plugins are subject to isolation"), + /** + * Sandbox isolation level + */ + isolationLevel: external_exports.enum([ + "none", + // No isolation + "process", + // Separate process (Node.js worker threads) + "vm", + // VM context isolation + "iframe", + // iframe isolation (browser) + "web-worker" + // Web Worker (browser) + ]).default("none"), + /** + * Allowed capabilities + */ + allowedCapabilities: external_exports.array(external_exports.string()).optional().describe("List of allowed capability IDs"), + /** + * Resource quotas + */ + resourceQuotas: external_exports.object({ + /** + * Maximum memory usage in MB + */ + maxMemoryMB: external_exports.number().int().min(1).optional(), + /** + * Maximum CPU time in milliseconds + */ + maxCpuTimeMs: external_exports.number().int().min(100).optional(), + /** + * Maximum number of file descriptors + */ + maxFileDescriptors: external_exports.number().int().min(1).optional(), + /** + * Maximum network bandwidth in KB/s + */ + maxNetworkKBps: external_exports.number().int().min(1).optional() + }).optional(), + /** + * Permissions + */ + permissions: external_exports.object({ + /** + * Allowed API access + */ + allowedAPIs: external_exports.array(external_exports.string()).optional(), + /** + * Allowed file system paths + */ + allowedPaths: external_exports.array(external_exports.string()).optional(), + /** + * Allowed network endpoints + */ + allowedEndpoints: external_exports.array(external_exports.string()).optional(), + /** + * Allowed environment variables + */ + allowedEnvVars: external_exports.array(external_exports.string()).optional() + }).optional(), + /** + * Inter-Plugin Communication (IPC) configuration + * Enables isolated plugins to communicate with the kernel and other plugins + */ + ipc: external_exports.object({ + /** + * Enable IPC for sandboxed plugins + */ + enabled: external_exports.boolean().default(true).describe("Allow sandboxed plugins to communicate via IPC"), + /** + * IPC transport mechanism + */ + transport: external_exports.enum([ + "message-port", + // MessagePort (worker threads / Web Workers) + "unix-socket", + // Unix domain sockets (process isolation) + "tcp", + // TCP sockets (container isolation) + "memory" + // Shared memory channel (in-process VM) + ]).default("message-port").describe("IPC transport for cross-boundary communication"), + /** + * Maximum message size in bytes + */ + maxMessageSize: external_exports.number().int().min(1024).default(1048576).describe("Maximum IPC message size in bytes (default 1MB)"), + /** + * Message timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4).describe("IPC message response timeout in ms"), + /** + * Allowed service calls through IPC + */ + allowedServices: external_exports.array(external_exports.string()).optional().describe("Service names the sandboxed plugin may invoke via IPC") + }).optional() +}).describe("Plugin sandboxing configuration"); +var PluginPerformanceMonitoringSchema = external_exports.object({ + /** + * Enable performance monitoring + */ + enabled: external_exports.boolean().default(false), + /** + * Metrics to collect + */ + metrics: external_exports.array(external_exports.enum([ + "load-time", + "init-time", + "memory-usage", + "cpu-usage", + "api-calls", + "error-rate", + "cache-hit-rate" + ])).optional(), + /** + * Sampling rate (0-1, where 1 = 100%) + */ + samplingRate: external_exports.number().min(0).max(1).default(1), + /** + * Reporting interval in seconds + */ + reportingInterval: external_exports.number().int().min(1).default(60), + /** + * Performance budget thresholds + */ + budgets: external_exports.object({ + /** + * Maximum load time in milliseconds + */ + maxLoadTimeMs: external_exports.number().int().min(0).optional(), + /** + * Maximum init time in milliseconds + */ + maxInitTimeMs: external_exports.number().int().min(0).optional(), + /** + * Maximum memory usage in MB + */ + maxMemoryMB: external_exports.number().int().min(0).optional() + }).optional(), + /** + * Action on budget violation + */ + onBudgetViolation: external_exports.enum(["warn", "error", "ignore"]).default("warn") +}).describe("Plugin performance monitoring configuration"); +var PluginLoadingConfigSchema = external_exports.object({ + /** + * Loading strategy + */ + strategy: PluginLoadingStrategySchema.default("lazy"), + /** + * Preloading configuration + */ + preload: PluginPreloadConfigSchema.optional(), + /** + * Code splitting configuration + */ + codeSplitting: PluginCodeSplittingSchema.optional(), + /** + * Dynamic import configuration + */ + dynamicImport: PluginDynamicImportSchema.optional(), + /** + * Initialization configuration + */ + initialization: PluginInitializationSchema.optional(), + /** + * Dependency resolution configuration + */ + dependencyResolution: PluginDependencyResolutionSchema.optional(), + /** + * Hot reload configuration (development and production) + */ + hotReload: PluginHotReloadSchema.optional(), + /** + * Caching configuration + */ + caching: PluginCachingSchema.optional(), + /** + * Sandboxing configuration + */ + sandboxing: PluginSandboxingSchema.optional(), + /** + * Performance monitoring + */ + monitoring: PluginPerformanceMonitoringSchema.optional() +}).describe("Complete plugin loading configuration"); +external_exports.object({ + /** + * Event type + */ + type: external_exports.enum([ + "load-started", + "load-completed", + "load-failed", + "init-started", + "init-completed", + "init-failed", + "preload-started", + "preload-completed", + "cache-hit", + "cache-miss", + "hot-reload", + "dynamic-load", + // Plugin loaded at runtime + "dynamic-unload", + // Plugin unloaded at runtime + "dynamic-discover" + // Plugin discovered via registry + ]), + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Timestamp + */ + timestamp: external_exports.number().int().min(0), + /** + * Duration in milliseconds + */ + durationMs: external_exports.number().int().min(0).optional(), + /** + * Additional metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Error if event represents a failure + */ + error: external_exports.object({ + message: external_exports.string(), + code: external_exports.string().optional(), + stack: external_exports.string().optional() + }).optional() +}).describe("Plugin loading lifecycle event"); +external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Current state + */ + state: external_exports.enum([ + "pending", + // Not yet loaded + "loading", + // Currently loading + "loaded", + // Code loaded, not initialized + "initializing", + // Currently initializing + "ready", + // Fully initialized and ready + "failed", + // Failed to load or initialize + "reloading", + // Hot reloading in progress + "unloading", + // Being unloaded at runtime + "unloaded" + // Successfully unloaded (dynamic loading) + ]), + /** + * Load progress (0-100) + */ + progress: external_exports.number().min(0).max(100).default(0), + /** + * Loading start time + */ + startedAt: external_exports.number().int().min(0).optional(), + /** + * Loading completion time + */ + completedAt: external_exports.number().int().min(0).optional(), + /** + * Last error + */ + lastError: external_exports.string().optional(), + /** + * Retry count + */ + retryCount: external_exports.number().int().min(0).default(0) +}).describe("Plugin loading state"); +external_exports.object({ + ql: external_exports.object({ + object: external_exports.function().describe("Get object handle for method chaining"), + query: external_exports.function().describe("Execute a query") + }).passthrough().describe("ObjectQL Engine Interface"), + os: external_exports.object({ + getCurrentUser: external_exports.function().describe("Get the current authenticated user"), + getConfig: external_exports.function().describe("Get platform configuration") + }).passthrough().describe("ObjectStack Kernel Interface"), + logger: external_exports.object({ + debug: external_exports.function().describe("Log debug message"), + info: external_exports.function().describe("Log info message"), + warn: external_exports.function().describe("Log warning message"), + error: external_exports.function().describe("Log error message") + }).passthrough().describe("Logger Interface"), + storage: external_exports.object({ + get: external_exports.function().describe("Get a value from storage"), + set: external_exports.function().describe("Set a value in storage"), + delete: external_exports.function().describe("Delete a value from storage") + }).passthrough().describe("Storage Interface"), + i18n: external_exports.object({ + t: external_exports.function().describe("Translate a key"), + getLocale: external_exports.function().describe("Get current locale") + }).passthrough().describe("Internationalization Interface"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()), + events: external_exports.record(external_exports.string(), external_exports.unknown()), + app: external_exports.object({ + router: external_exports.object({ + get: external_exports.function().describe("Register GET route handler"), + post: external_exports.function().describe("Register POST route handler"), + use: external_exports.function().describe("Register middleware") + }).passthrough() + }).passthrough().describe("App Framework Interface"), + drivers: external_exports.object({ + register: external_exports.function().describe("Register a driver") + }).passthrough().describe("Driver Registry") +}); +external_exports.object({ + /** Version before upgrade */ + previousVersion: external_exports.string().describe("Version before upgrade"), + /** Version after upgrade */ + newVersion: external_exports.string().describe("Version after upgrade"), + /** Whether this is a major version bump */ + isMajorUpgrade: external_exports.boolean().describe("Whether this is a major version bump"), + /** Metadata snapshot before upgrade (for migration logic) */ + previousMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Metadata snapshot before upgrade") +}).describe("Version migration context for onUpgrade hook"); +var PluginLifecycleSchema = external_exports.object({ + onInstall: external_exports.function().optional().describe("Called when plugin is installed"), + onEnable: external_exports.function().optional().describe("Called when plugin is enabled"), + onDisable: external_exports.function().optional().describe("Called when plugin is disabled"), + onUninstall: external_exports.function().optional().describe("Called when plugin is uninstalled"), + onUpgrade: external_exports.function().optional().describe("Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade") +}); +var CORE_PLUGIN_TYPES = [ + "ui", + // Frontend: Serves static assets/SPA (e.g. Console, Studio) + "driver", + // Connectivity: Database or Storage adapters (e.g. SQL, S3) + "server", + // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL) + "app", + // Business: Vertical Solution Bundle (Metadata + Logic) + "theme", + // Appearance: UI Overrides & CSS Variables + "agent", + // AI: Autonomous Agent & Tool Definitions + "objectql" + // Core: ObjectQL Engine Data Provider +]; +PluginLifecycleSchema.extend({ + id: external_exports.string().min(1).optional().describe("Unique Plugin ID (e.g. com.example.crm)"), + type: external_exports.enum([ + "standard", + // Default: General purpose backend logic (Service, Hook, etc.) + ...CORE_PLUGIN_TYPES + ]).default("standard").optional().describe("Plugin Type categorization for runtime behavior"), + staticPath: external_exports.string().optional().describe('Absolute path to static assets (Required for type="ui-plugin")'), + slug: external_exports.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type="ui-plugin")'), + default: external_exports.boolean().optional().describe('Serve at root path (Only one "ui-plugin" can be default)'), + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic Version"), + description: external_exports.string().optional(), + author: external_exports.string().optional(), + homepage: external_exports.string().url().optional() +}); +var DatasetMode = external_exports.enum([ + "insert", + // Try to insert, fail on duplicate + "update", + // Only update found records, ignore new + "upsert", + // Create new or Update existing (Standard) + "replace", + // Delete ALL records in object then insert (Dangerous - use for cache tables) + "ignore" + // Try to insert, silently skip duplicates +]); +var DatasetSchema = external_exports.object({ + /** + * Target Object + * The machine name of the object to populate. + */ + object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target Object Name"), + /** + * Idempotency Key (The "Upsert" Key) + * The field used to check if a record already exists. + * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'. + * Standard: 'id' is rarely used for portable seed data — prefer natural keys. + */ + externalId: external_exports.string().default("name").describe("Field match for uniqueness check"), + /** + * Import Strategy + */ + mode: DatasetMode.default("upsert").describe("Conflict resolution strategy"), + /** + * Environment Scope + * - 'all': Always load + * - 'dev': Only for development/demo + * - 'test': Only for CI/CD tests + */ + env: external_exports.array(external_exports.enum(["prod", "dev", "test"])).default(["prod", "dev", "test"]).describe("Applicable environments"), + /** + * The Payload + * Array of raw JSON objects matching the Object Schema. + */ + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Data records") +}); +var ManifestSchema = external_exports.object({ + /** + * Unique package identifier using reverse domain notation. + * Must be unique across the entire ecosystem. + * + * @example "com.steedos.crm" + * @example "org.apache.superset" + */ + id: external_exports.string().describe("Unique package identifier (reverse domain style)"), + /** + * Short namespace identifier for metadata scoping. + * Used as a prefix for objects and other metadata to prevent naming collisions + * across packages from different vendors. + * + * Rules: + * - 2-20 characters, lowercase letters, digits, and underscores only. + * - Must be unique within a running instance. + * - Platform-reserved namespaces (no prefix applied): "base", "system". + * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator). + * + * @example "crm" → objects become crm__account, crm__deal + * @example "todo" → objects become todo__task + * @example "base" → objects keep short name (platform reserved) + */ + namespace: external_exports.string().regex(/^[a-z][a-z0-9_]{1,19}$/, "Namespace must be 2-20 chars, lowercase alphanumeric + underscore").optional().describe('Short namespace identifier for metadata scoping (e.g. "crm", "todo")'), + /** + * Package version following semantic versioning (major.minor.patch). + * + * @example "1.0.0" + * @example "2.1.0-beta.1" + */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Package version (semantic versioning)"), + /** + * Type of the package in the ObjectStack ecosystem. + * - plugin: General-purpose functionality extension (Runtime: standard) + * - app: Business application package + * - driver: Connectivity adapter + * - server: Protocol gateway (Hono, GraphQL) + * - ui: Frontend package (Static/SPA) + * - theme: UI Theme + * - agent: AI Agent + * - module: Reusable code library/shared module + * - objectql: Core engine + * - adapter: Host adapter (Express, Fastify) + */ + type: external_exports.enum([ + "plugin", + ...CORE_PLUGIN_TYPES, + "module", + "gateway", + // Deprecated: use 'server' + "adapter" + ]).describe("Type of package"), + /** + * Human-readable name of the package. + * Displayed in the UI for users. + * + * @example "Project Management" + */ + name: external_exports.string().describe("Human-readable package name"), + /** + * Brief description of the package functionality. + * Displayed in the marketplace and plugin manager. + */ + description: external_exports.string().optional().describe("Package description"), + /** + * Array of permission strings that the package requires. + * These form the "Scope" requested by the package at installation. + * + * @example ["system.user.read", "system.data.write"] + */ + permissions: external_exports.array(external_exports.string()).optional().describe("Array of required permission strings"), + /** + * Glob patterns specifying ObjectQL schemas files. + * Matches `*.object.yml` or `*.object.ts` files to load business objects. + * + * @example ["./src/objects/*.object.yml"] + */ + objects: external_exports.array(external_exports.string()).optional().describe("Glob patterns for ObjectQL schemas files"), + /** + * Defines system level DataSources. + * Matches `*.datasource.yml` files. + * + * @example ["./src/datasources/*.datasource.mongo.yml"] + */ + datasources: external_exports.array(external_exports.string()).optional().describe("Glob patterns for Datasource definitions"), + /** + * Package Dependencies. + * Map of package IDs to version requirements. + * + * @example { "@steedos/plugin-auth": "^2.0.0" } + */ + dependencies: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Package dependencies"), + /** + * Plugin Configuration Schema. + * Defines the settings this plugin exposes to the user via UI/ENV. + * Uses a simplified JSON Schema format. + * + * @example + * { + * "title": "Stripe Config", + * "properties": { + * "apiKey": { "type": "string", "secret": true }, + * "currency": { "type": "string", "default": "USD" } + * } + * } + */ + configuration: external_exports.object({ + title: external_exports.string().optional(), + properties: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["string", "number", "boolean", "array", "object"]).describe("Data type of the setting"), + default: external_exports.unknown().optional().describe("Default value"), + description: external_exports.string().optional().describe("Tooltip description"), + required: external_exports.boolean().optional().describe("Is this setting required?"), + secret: external_exports.boolean().optional().describe("If true, value is encrypted/masked (e.g. API Keys)"), + enum: external_exports.array(external_exports.string()).optional().describe("Allowed values for select inputs") + })).describe("Map of configuration keys to their definitions") + }).optional().describe("Plugin configuration settings"), + /** + * Contribution Points (VS Code Style). + * formalized way to extend the platform capabilities. + */ + contributes: external_exports.object({ + /** + * Register new Metadata Kinds (CRDs). + * Enables the system to parse and validate new file types. + * Example: Registering a BI plugin to handle *.report.ts + */ + kinds: external_exports.array(external_exports.object({ + id: external_exports.string().describe('The generic identifier of the kind (e.g., "sys.bi.report")'), + globs: external_exports.array(external_exports.string()).describe('File patterns to watch (e.g., ["**/*.report.ts"])'), + description: external_exports.string().optional().describe("Description of what this kind represents") + })).optional().describe("New Metadata Types to recognize"), + /** + * Register System Hooks. + * Declares that this plugin listens to specific system events. + */ + events: external_exports.array(external_exports.string()).optional().describe("Events this plugin listens to"), + /** + * Register UI Menus. + */ + menus: external_exports.record(external_exports.string(), external_exports.array(external_exports.object({ + id: external_exports.string(), + label: external_exports.string(), + command: external_exports.string().optional() + }))).optional().describe("UI Menu contributions"), + /** + * Register Custom Themes. + */ + themes: external_exports.array(external_exports.object({ + id: external_exports.string(), + label: external_exports.string(), + path: external_exports.string() + })).optional().describe("Theme contributions"), + /** + * Register Translations. + * Path to translation files (e.g. "locales/en.json"). + */ + translations: external_exports.array(external_exports.object({ + locale: external_exports.string(), + path: external_exports.string() + })).optional().describe("Translation resources"), + /** + * Register Server Actions. + * Invocable functions exposed to Flows or API. + */ + actions: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Unique action name"), + label: external_exports.string().optional(), + description: external_exports.string().optional(), + input: external_exports.unknown().optional().describe("Input validation schema"), + output: external_exports.unknown().optional().describe("Output schema") + })).optional().describe("Exposed server actions"), + /** + * Register Storage Drivers. + * Enables connecting to new types of datasources. + */ + drivers: external_exports.array(external_exports.object({ + id: external_exports.string().describe('Driver unique identifier (e.g. "postgres", "mongo")'), + label: external_exports.string().describe("Human readable name"), + description: external_exports.string().optional() + })).optional().describe("Driver contributions"), + /** + * Register Custom Field Types. + * Extends the data model with new widget types. + */ + fieldTypes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Unique field type name (e.g. "vector")'), + label: external_exports.string().describe("Display label"), + description: external_exports.string().optional() + })).optional().describe("Field Type contributions"), + /** + * Register Custom Query Operators/Functions. + * Extends ObjectQL with new functions (e.g. distance()). + */ + functions: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Function name (e.g. "distance")'), + description: external_exports.string().optional(), + args: external_exports.array(external_exports.string()).optional().describe("Argument types"), + returnType: external_exports.string().optional() + })).optional().describe("Query Function contributions"), + /** + * Register API Route Namespaces. + * Declares the API endpoints this plugin provides to the HttpDispatcher. + * The kernel routes matching prefixes to this plugin's handler. + * + * @example + * routes: [ + * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] } + * ] + */ + routes: external_exports.array(external_exports.object({ + /** URL path prefix (e.g. "/api/v1/ai") */ + prefix: external_exports.string().regex(/^\//).describe("API path prefix"), + /** Service name this plugin provides */ + service: external_exports.string().describe("Service name this plugin provides"), + /** Protocol method names implemented */ + methods: external_exports.array(external_exports.string()).optional().describe('Protocol method names implemented (e.g. ["aiNlq", "aiChat"])') + })).optional().describe("API route contributions to HttpDispatcher"), + /** + * Register CLI Commands. + * Allows plugins to extend the ObjectStack CLI with custom commands. + * Each command entry declares metadata; the actual Commander.js command + * is resolved at runtime by importing the plugin's module. + * + * The plugin package must export a `commands` array of Commander.js `Command` instances + * from its main entry point or from the path specified in `module`. + * + * @example + * ```yaml + * commands: + * - name: marketplace + * description: "Manage marketplace apps" + * module: "./cli" # optional, defaults to package main + * - name: deploy + * description: "Deploy to cloud" + * ``` + */ + commands: external_exports.array(external_exports.object({ + /** CLI command name (e.g., "marketplace", "deploy"). Must be a valid CLI identifier. */ + name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), + /** Brief description shown in `os --help` */ + description: external_exports.string().optional().describe("Command description for help text"), + /** + * Optional module path (relative to package root) that exports the Commander.js commands. + * If omitted, the CLI will import from the package's main entry point. + * The module must export a `commands` array of Commander.js `Command` instances, + * or a single `Command` instance as default export. + */ + module: external_exports.string().optional().describe("Module path exporting Commander.js commands") + })).optional().describe("CLI command contributions") + }).optional().describe("Platform contributions"), + /** + * Initial data seeding configuration. + * Defines default records to be inserted when the package is installed. + * + * Uses the standard DatasetSchema which supports idempotent upsert via + * `externalId`, environment scoping via `env`, and multiple conflict + * resolution modes. + * + * @deprecated Prefer using the top-level `data` field on the Stack Definition + * (defineStack({ data: [...] })) for better visibility and metadata registration. + * This field is retained for backward compatibility with manifest-only packages. + */ + data: external_exports.array(DatasetSchema).optional().describe("Initial seed data (prefer top-level data field)"), + /** + * Plugin Capability Manifest. + * Declares protocols implemented, interfaces provided, dependencies, and extension points. + * This enables plugin interoperability and automatic discovery. + */ + capabilities: PluginCapabilityManifestSchema.optional().describe("Plugin capability declarations for interoperability"), + /** + * Extension points contributed by this package. + * Allows packages to extend UI components, add functionality, etc. + */ + extensions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Extension points and contributions"), + /** + * Plugin Loading Configuration. + * Configures how the plugin is loaded, initialized, and managed at runtime. + * Includes strategies for lazy loading, code splitting, caching, and hot reload. + */ + loading: PluginLoadingConfigSchema.optional().describe("Plugin loading and runtime behavior configuration"), + /** + * Platform Compatibility Requirements. + * Specifies the minimum ObjectStack platform version required to run this package. + * Used at install time to prevent incompatible packages from being installed. + * + * @example + * ```yaml + * engine: + * objectstack: ">=3.0.0" + * ``` + */ + engine: external_exports.object({ + /** ObjectStack platform version requirement (SemVer range) */ + objectstack: external_exports.string().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe('ObjectStack platform version requirement (SemVer range, e.g. ">=3.0.0")') + }).optional().describe("Platform compatibility requirements") +}); +var DependencyStatusEnum = external_exports.enum([ + "satisfied", + // Already installed and version compatible + "needs_install", + // Not installed, needs to be installed + "needs_upgrade", + // Installed but version incompatible, needs upgrade + "conflict" + // Conflicts with another package's dependency +]).describe("Resolution status for a dependency"); +var ResolvedDependencySchema = external_exports.object({ + /** Package identifier of the dependency */ + packageId: external_exports.string().describe("Dependency package identifier"), + /** SemVer range required by the parent package */ + requiredRange: external_exports.string().describe('SemVer range required (e.g. "^2.0.0")'), + /** Actual version resolved (if available) */ + resolvedVersion: external_exports.string().optional().describe("Actual version resolved from registry"), + /** Currently installed version (if any) */ + installedVersion: external_exports.string().optional().describe("Currently installed version"), + /** Resolution status */ + status: DependencyStatusEnum.describe("Resolution status"), + /** Conflict details (when status is "conflict") */ + conflictReason: external_exports.string().optional().describe("Explanation of the conflict") +}).describe("Resolution result for a single dependency"); +var RequiredActionSchema = external_exports.object({ + /** Type of action required */ + type: external_exports.enum(["install", "upgrade", "confirm_conflict"]).describe("Type of action required"), + /** Target package identifier */ + packageId: external_exports.string().describe("Target package identifier"), + /** Human-readable description of the action */ + description: external_exports.string().describe("Human-readable action description") +}).describe("Action required before installation can proceed"); +var DependencyResolutionResultSchema = external_exports.object({ + /** All dependencies and their resolution results */ + dependencies: external_exports.array(ResolvedDependencySchema).describe("Resolution result for each dependency"), + /** Whether installation can proceed without conflicts */ + canProceed: external_exports.boolean().describe("Whether installation can proceed"), + /** Actions that require user confirmation or system execution */ + requiredActions: external_exports.array(RequiredActionSchema).describe("Actions required before proceeding"), + /** Topologically sorted package IDs for installation order */ + installOrder: external_exports.array(external_exports.string()).describe("Topologically sorted package IDs for installation"), + /** Detected circular dependency chains */ + circularDependencies: external_exports.array(external_exports.array(external_exports.string())).optional().describe('Circular dependency chains detected (e.g. [["A", "B", "A"]])') +}).describe("Complete dependency resolution result"); +var PackageStatusEnum = external_exports.enum([ + "installed", + // Successfully installed and enabled + "disabled", + // Installed but disabled (metadata not active) + "installing", + // Installation in progress + "upgrading", + // Upgrade in progress + "uninstalling", + // Removal in progress + "error" + // Installation or runtime error +]).describe("Package installation status"); +var InstalledPackageSchema = external_exports.object({ + /** + * The full package manifest (source of truth for package definition). + */ + manifest: ManifestSchema.describe("Full package manifest"), + /** + * Current lifecycle status. + */ + status: PackageStatusEnum.default("installed").describe("Package state: installed, disabled, installing, upgrading, uninstalling, or error"), + /** + * Whether the package is currently enabled (active). + * When disabled, the package's metadata is not loaded into the registry. + */ + enabled: external_exports.boolean().default(true).describe("Whether the package is currently enabled"), + /** + * ISO 8601 timestamp of when the package was installed. + */ + installedAt: external_exports.string().datetime().optional().describe("Installation timestamp"), + /** + * ISO 8601 timestamp of last update. + */ + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + /** + * The currently installed version string. + * Mirrors manifest.version for quick access without parsing the full manifest. + */ + installedVersion: external_exports.string().optional().describe("Currently installed version for quick access"), + /** + * The previously installed version (before last upgrade). + * Useful for rollback and upgrade tracking. + */ + previousVersion: external_exports.string().optional().describe("Version before the last upgrade"), + /** + * ISO 8601 timestamp of when the package was last enabled/disabled. + */ + statusChangedAt: external_exports.string().datetime().optional().describe("Status change timestamp"), + /** + * Error message if status is 'error'. + */ + errorMessage: external_exports.string().optional().describe("Error message when status is error"), + /** + * Configuration values set by the user for this package. + * Keys correspond to the package's `configuration.properties`. + */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided configuration settings"), + /** + * Upgrade history for this package. + * Records each version migration with status and optional log. + */ + upgradeHistory: external_exports.array(external_exports.object({ + /** Previous version before upgrade */ + fromVersion: external_exports.string().describe("Version before upgrade"), + /** New version after upgrade */ + toVersion: external_exports.string().describe("Version after upgrade"), + /** Timestamp of the upgrade */ + upgradedAt: external_exports.string().datetime().describe("Upgrade timestamp"), + /** Outcome of the upgrade */ + status: external_exports.enum(["success", "failed", "rolled_back"]).describe("Upgrade outcome"), + /** Migration log entries */ + migrationLog: external_exports.array(external_exports.string()).optional().describe("Migration step logs") + })).optional().describe("Version upgrade history"), + /** + * Namespaces registered by this package. + * Tracks which namespace prefixes are occupied by this package. + */ + registeredNamespaces: external_exports.array(external_exports.string()).optional().describe("Namespace prefixes registered by this package") +}).describe("Installed package with runtime lifecycle state"); +external_exports.object({ + /** Namespace prefix */ + namespace: external_exports.string().describe("Namespace prefix"), + /** Package that owns this namespace */ + packageId: external_exports.string().describe("Owning package ID"), + /** Registration timestamp */ + registeredAt: external_exports.string().datetime().describe("Registration timestamp"), + /** Namespace status */ + status: external_exports.enum(["active", "disabled", "reserved"]).describe("Namespace status") +}).describe("Namespace ownership entry in the registry"); +external_exports.object({ + /** Error type discriminator */ + type: external_exports.literal("namespace_conflict").describe("Error type"), + /** Namespace that was requested */ + requestedNamespace: external_exports.string().describe("Requested namespace"), + /** ID of the package that already owns the namespace */ + conflictingPackageId: external_exports.string().describe("Conflicting package ID"), + /** Name of the conflicting package */ + conflictingPackageName: external_exports.string().describe("Conflicting package display name"), + /** Suggested alternative namespace */ + suggestion: external_exports.string().optional().describe("Suggested alternative namespace") +}).describe("Namespace collision error during installation"); +var ListPackagesRequestSchema = external_exports.object({ + /** Filter by status */ + status: PackageStatusEnum.optional().describe("Filter by package status"), + /** Filter by package type */ + type: ManifestSchema.shape.type.optional().describe("Filter by package type"), + /** Filter by enabled state */ + enabled: external_exports.boolean().optional().describe("Filter by enabled state") +}).describe("List packages request"); +var ListPackagesResponseSchema = external_exports.object({ + packages: external_exports.array(InstalledPackageSchema).describe("List of installed packages"), + total: external_exports.number().describe("Total package count") +}).describe("List packages response"); +var GetPackageRequestSchema = external_exports.object({ + /** Package ID (reverse domain identifier from manifest) */ + id: external_exports.string().describe("Package identifier") +}).describe("Get package request"); +var GetPackageResponseSchema = external_exports.object({ + package: InstalledPackageSchema.describe("Package details") +}).describe("Get package response"); +var InstallPackageRequestSchema = external_exports.object({ + /** The package manifest to install */ + manifest: ManifestSchema.describe("Package manifest to install"), + /** Optional: user-provided settings at install time */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), + /** Whether to enable immediately after install (default: true) */ + enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), + /** + * Current platform version for compatibility checking. + * When provided, the system compares this against the package's + * `engine.objectstack` requirement to verify compatibility. + */ + platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification") +}).describe("Install package request"); +var InstallPackageResponseSchema = external_exports.object({ + package: InstalledPackageSchema.describe("Installed package details"), + message: external_exports.string().optional().describe("Installation status message"), + /** Dependency resolution result (when dependencies were analyzed) */ + dependencyResolution: DependencyResolutionResultSchema.optional().describe("Dependency resolution result from install analysis") +}).describe("Install package response"); +var UninstallPackageRequestSchema = external_exports.object({ + /** Package ID to uninstall */ + id: external_exports.string().describe("Package ID to uninstall") +}).describe("Uninstall package request"); +var UninstallPackageResponseSchema = external_exports.object({ + id: external_exports.string().describe("Uninstalled package ID"), + success: external_exports.boolean().describe("Whether uninstall succeeded"), + message: external_exports.string().optional().describe("Uninstall status message") +}).describe("Uninstall package response"); +var EnablePackageRequestSchema = external_exports.object({ + /** Package ID to enable */ + id: external_exports.string().describe("Package ID to enable") +}).describe("Enable package request"); +var EnablePackageResponseSchema = external_exports.object({ + package: InstalledPackageSchema.describe("Enabled package details"), + message: external_exports.string().optional().describe("Enable status message") +}).describe("Enable package response"); +var DisablePackageRequestSchema = external_exports.object({ + /** Package ID to disable */ + id: external_exports.string().describe("Package ID to disable") +}).describe("Disable package request"); +var DisablePackageResponseSchema = external_exports.object({ + package: InstalledPackageSchema.describe("Disabled package details"), + message: external_exports.string().optional().describe("Disable status message") +}).describe("Disable package response"); +var AutomationTriggerRequestSchema = external_exports.object({ + trigger: external_exports.string(), + payload: external_exports.record(external_exports.string(), external_exports.unknown()) +}); +var AutomationTriggerResponseSchema = external_exports.object({ + success: external_exports.boolean(), + jobId: external_exports.string().optional(), + result: external_exports.unknown().optional() +}); +var GetDiscoveryRequestSchema = external_exports.object({}); +var GetDiscoveryResponseSchema = DiscoverySchema.partial().required({ version: true }).extend({ + /** @deprecated Use `name` instead. Kept for backward compatibility. */ + apiName: external_exports.string().optional().describe("API name (deprecated \u2014 use name)") +}); +var GetMetaTypesRequestSchema = external_exports.object({}); +var GetMetaTypesResponseSchema = external_exports.object({ + types: external_exports.array(external_exports.string()).describe('Available metadata type names (e.g., "object", "plugin", "view")') +}); +var GetMetaItemsRequestSchema = external_exports.object({ + type: external_exports.string().describe('Metadata type name (e.g., "object", "plugin")'), + packageId: external_exports.string().optional().describe("Optional package ID to filter items by") +}); +var GetMetaItemsResponseSchema = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + items: external_exports.array(external_exports.unknown()).describe("Array of metadata items") +}); +var GetMetaItemRequestSchema = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + name: external_exports.string().describe("Item name (snake_case identifier)"), + packageId: external_exports.string().optional().describe("Optional package ID to filter items by") +}); +var GetMetaItemResponseSchema = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + name: external_exports.string().describe("Item name"), + item: external_exports.unknown().describe("Metadata item definition") +}); +var SaveMetaItemRequestSchema = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + name: external_exports.string().describe("Item name"), + item: external_exports.unknown().describe("Metadata item definition") +}); +var SaveMetaItemResponseSchema = external_exports.object({ + success: external_exports.boolean(), + message: external_exports.string().optional() +}); +var GetMetaItemCachedRequestSchema = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + name: external_exports.string().describe("Item name"), + cacheRequest: MetadataCacheRequestSchema.optional().describe("Cache validation parameters") +}); +var GetUiViewRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + type: external_exports.enum(["list", "form"]).describe("View type") +}); +var FindDataRequestSchema = external_exports.object({ + object: external_exports.string().describe('The unique machine name of the object to query (e.g. "account").'), + query: QuerySchema.optional().describe("Structured query definition (filter, sort, select, pagination).") +}); +var FindDataResponseSchema = external_exports.object({ + object: external_exports.string().describe("The object name for the returned records."), + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("The list of matching records."), + total: external_exports.number().optional().describe("Total number of records matching the filter (if requested)."), + nextCursor: external_exports.string().optional().describe("Cursor for the next page of results (cursor-based pagination)."), + hasMore: external_exports.boolean().optional().describe("True if there are more records available (pagination).") +}); +var HttpFindQueryParamsSchema = external_exports.object({ + /** @canonical Singular form — the standard going forward. JSON string of filter expression or AST. */ + filter: external_exports.string().optional().describe("JSON-encoded filter expression (canonical, singular)."), + /** @deprecated Use `filter` (singular). Accepted for backward compatibility. */ + filters: external_exports.string().optional().describe("JSON-encoded filter expression (deprecated plural alias)."), + select: external_exports.string().optional().describe("Comma-separated list of fields to retrieve."), + sort: external_exports.string().optional().describe('Sort expression (e.g. "name asc,created_at desc" or "-created_at").'), + orderBy: external_exports.string().optional().describe("Alias for sort (OData compatibility)."), + top: external_exports.coerce.number().optional().describe("Max records to return (limit)."), + skip: external_exports.coerce.number().optional().describe("Records to skip (offset)."), + expand: external_exports.string().optional().describe( + "Comma-separated list of lookup/master_detail field names to expand. Resolved to populate array and passed to the engine for batch $in expansion." + ), + search: external_exports.string().optional().describe("Full-text search query."), + distinct: external_exports.coerce.boolean().optional().describe("SELECT DISTINCT flag."), + count: external_exports.coerce.boolean().optional().describe("Include total count in response.") +}); +var GetDataRequestSchema = external_exports.object({ + object: external_exports.string().describe("The object name."), + id: external_exports.string().describe("The unique record identifier (primary key)."), + select: external_exports.array(external_exports.string()).optional().describe("Fields to include in the response (allowlisted query param)."), + expand: external_exports.array(external_exports.string()).optional().describe( + "Lookup/master_detail field names to expand. The engine resolves these via batch $in queries, replacing foreign key IDs with full objects." + ) +}); +var GetDataResponseSchema = external_exports.object({ + object: external_exports.string().describe("The object name."), + id: external_exports.string().describe("The record ID."), + record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The complete record data.") +}); +var CreateDataRequestSchema = external_exports.object({ + object: external_exports.string().describe("The object name."), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The dictionary of field values to insert.") +}); +var CreateDataResponseSchema = external_exports.object({ + object: external_exports.string().describe("The object name."), + id: external_exports.string().describe("The ID of the newly created record."), + record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The created record, including server-generated fields (created_at, owner).") +}); +var UpdateDataRequestSchema = external_exports.object({ + object: external_exports.string().describe("The object name."), + id: external_exports.string().describe("The ID of the record to update."), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The fields to update (partial update).") +}); +var UpdateDataResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + id: external_exports.string().describe("Updated record ID"), + record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Updated record") +}); +var DeleteDataRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + id: external_exports.string().describe("Record ID to delete") +}); +var DeleteDataResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + id: external_exports.string().describe("Deleted record ID"), + success: external_exports.boolean().describe("Whether deletion succeeded") +}); +var BatchDataRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + request: BatchUpdateRequestSchema.describe("Batch operation request") +}); +var CreateManyDataRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Array of records to create") +}); +var CreateManyDataResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Created records"), + count: external_exports.number().describe("Number of records created") +}); +var UpdateManyDataRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + records: external_exports.array(external_exports.object({ + id: external_exports.string().describe("Record ID"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Fields to update") + })).describe("Array of updates"), + options: BatchOptionsSchema.optional().describe("Update options") +}); +var DeleteManyDataRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + ids: external_exports.array(external_exports.string()).describe("Array of record IDs to delete"), + options: BatchOptionsSchema.optional().describe("Delete options") +}); +var ListViewsRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + type: external_exports.enum(["list", "form"]).optional().describe("Filter by view type") +}); +var ListViewsResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + views: external_exports.array(ViewSchema).describe("Array of view definitions") +}); +var GetViewRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + viewId: external_exports.string().describe("View identifier") +}); +var GetViewResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + view: ViewSchema.describe("View definition") +}); +var CreateViewRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + data: ViewSchema.describe("View definition to create") +}); +var CreateViewResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + viewId: external_exports.string().describe("Created view identifier"), + view: ViewSchema.describe("Created view definition") +}); +var UpdateViewRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + viewId: external_exports.string().describe("View identifier"), + data: ViewSchema.partial().describe("Partial view data to update") +}); +var UpdateViewResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + viewId: external_exports.string().describe("Updated view identifier"), + view: ViewSchema.describe("Updated view definition") +}); +var DeleteViewRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + viewId: external_exports.string().describe("View identifier to delete") +}); +var DeleteViewResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + viewId: external_exports.string().describe("Deleted view identifier"), + success: external_exports.boolean().describe("Whether deletion succeeded") +}); +var CheckPermissionRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name to check permissions for"), + action: external_exports.enum(["create", "read", "edit", "delete", "transfer", "restore", "purge"]).describe("Action to check"), + recordId: external_exports.string().optional().describe("Specific record ID (for record-level checks)"), + field: external_exports.string().optional().describe("Specific field name (for field-level checks)") +}); +var CheckPermissionResponseSchema = external_exports.object({ + allowed: external_exports.boolean().describe("Whether the action is permitted"), + reason: external_exports.string().optional().describe("Reason if denied") +}); +var GetObjectPermissionsRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name to get permissions for") +}); +var GetObjectPermissionsResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + permissions: ObjectPermissionSchema.describe("Object-level permissions"), + fieldPermissions: external_exports.record(external_exports.string(), FieldPermissionSchema).optional().describe("Field-level permissions keyed by field name") +}); +var GetEffectivePermissionsRequestSchema = external_exports.object({}); +var GetEffectivePermissionsResponseSchema = external_exports.object({ + objects: external_exports.record(external_exports.string(), ObjectPermissionSchema).describe("Effective object permissions keyed by object name"), + systemPermissions: external_exports.array(external_exports.string()).describe("Effective system-level permissions") +}); +var GetWorkflowConfigRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name to get workflow config for") +}); +var GetWorkflowConfigResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + workflows: external_exports.array(WorkflowRuleSchema).describe("Active workflow rules for this object") +}); +var WorkflowStateSchema = external_exports.object({ + currentState: external_exports.string().describe("Current workflow state name"), + availableTransitions: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Transition name"), + targetState: external_exports.string().describe("Target state after transition"), + label: external_exports.string().optional().describe("Display label"), + requiresApproval: external_exports.boolean().default(false).describe("Whether transition requires approval") + })).describe("Available transitions from current state"), + history: external_exports.array(external_exports.object({ + fromState: external_exports.string().describe("Previous state"), + toState: external_exports.string().describe("New state"), + action: external_exports.string().describe("Action that triggered the transition"), + userId: external_exports.string().describe("User who performed the action"), + timestamp: external_exports.string().datetime().describe("When the transition occurred"), + comment: external_exports.string().optional().describe("Optional comment") + })).optional().describe("State transition history") +}); +var GetWorkflowStateRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID to get workflow state for") +}); +var GetWorkflowStateResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + state: WorkflowStateSchema.describe("Current workflow state and available transitions") +}); +var WorkflowTransitionRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + transition: external_exports.string().describe("Transition name to execute"), + comment: external_exports.string().optional().describe("Optional comment for the transition"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data for the transition") +}); +var WorkflowTransitionResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + success: external_exports.boolean().describe("Whether the transition succeeded"), + state: WorkflowStateSchema.describe("New workflow state after transition") +}); +var WorkflowApproveRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + comment: external_exports.string().optional().describe("Approval comment"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data") +}); +var WorkflowApproveResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + success: external_exports.boolean().describe("Whether the approval succeeded"), + state: WorkflowStateSchema.describe("New workflow state after approval") +}); +var WorkflowRejectRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + reason: external_exports.string().describe("Rejection reason"), + comment: external_exports.string().optional().describe("Additional comment") +}); +var WorkflowRejectResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + success: external_exports.boolean().describe("Whether the rejection succeeded"), + state: WorkflowStateSchema.describe("New workflow state after rejection") +}); +var RealtimeConnectRequestSchema = external_exports.object({ + transport: TransportProtocol.optional().describe("Preferred transport protocol"), + channels: external_exports.array(external_exports.string()).optional().describe("Channels to subscribe to on connect"), + token: external_exports.string().optional().describe("Authentication token") +}); +var RealtimeConnectResponseSchema = external_exports.object({ + connectionId: external_exports.string().describe("Unique connection identifier"), + transport: TransportProtocol.describe("Negotiated transport protocol"), + url: external_exports.string().optional().describe("WebSocket/SSE endpoint URL") +}); +var RealtimeDisconnectRequestSchema = external_exports.object({ + connectionId: external_exports.string().optional().describe("Connection ID to disconnect") +}); +var RealtimeDisconnectResponseSchema = external_exports.object({ + success: external_exports.boolean().describe("Whether disconnection succeeded") +}); +var RealtimeSubscribeRequestSchema = external_exports.object({ + channel: external_exports.string().describe("Channel name to subscribe to"), + events: external_exports.array(external_exports.string()).optional().describe("Specific event types to listen for"), + filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event filter criteria") +}); +var RealtimeSubscribeResponseSchema = external_exports.object({ + subscriptionId: external_exports.string().describe("Unique subscription identifier"), + channel: external_exports.string().describe("Subscribed channel name") +}); +var RealtimeUnsubscribeRequestSchema = external_exports.object({ + subscriptionId: external_exports.string().describe("Subscription ID to cancel") +}); +var RealtimeUnsubscribeResponseSchema = external_exports.object({ + success: external_exports.boolean().describe("Whether unsubscription succeeded") +}); +var SetPresenceRequestSchema = external_exports.object({ + channel: external_exports.string().describe("Channel to set presence in"), + state: RealtimePresenceSchema.describe("Presence state to set") +}); +var SetPresenceResponseSchema = external_exports.object({ + success: external_exports.boolean().describe("Whether presence was set") +}); +var GetPresenceRequestSchema = external_exports.object({ + channel: external_exports.string().describe("Channel to get presence for") +}); +var GetPresenceResponseSchema = external_exports.object({ + channel: external_exports.string().describe("Channel name"), + members: external_exports.array(RealtimePresenceSchema).describe("Active members and their presence state") +}); +var RegisterDeviceRequestSchema = external_exports.object({ + token: external_exports.string().describe("Device push notification token"), + platform: external_exports.enum(["ios", "android", "web"]).describe("Device platform"), + deviceId: external_exports.string().optional().describe("Unique device identifier"), + name: external_exports.string().optional().describe("Device friendly name") +}); +var RegisterDeviceResponseSchema = external_exports.object({ + deviceId: external_exports.string().describe("Registered device ID"), + success: external_exports.boolean().describe("Whether registration succeeded") +}); +var UnregisterDeviceRequestSchema = external_exports.object({ + deviceId: external_exports.string().describe("Device ID to unregister") +}); +var UnregisterDeviceResponseSchema = external_exports.object({ + success: external_exports.boolean().describe("Whether unregistration succeeded") +}); +var NotificationPreferencesSchema = external_exports.object({ + email: external_exports.boolean().default(true).describe("Receive email notifications"), + push: external_exports.boolean().default(true).describe("Receive push notifications"), + inApp: external_exports.boolean().default(true).describe("Receive in-app notifications"), + digest: external_exports.enum(["none", "daily", "weekly"]).default("none").describe("Email digest frequency"), + channels: external_exports.record(external_exports.string(), external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Whether this channel is enabled"), + email: external_exports.boolean().optional().describe("Override email setting"), + push: external_exports.boolean().optional().describe("Override push setting") + })).optional().describe("Per-channel notification preferences") +}); +var GetNotificationPreferencesRequestSchema = external_exports.object({}); +var GetNotificationPreferencesResponseSchema = external_exports.object({ + preferences: NotificationPreferencesSchema.describe("Current notification preferences") +}); +var UpdateNotificationPreferencesRequestSchema = external_exports.object({ + preferences: NotificationPreferencesSchema.partial().describe("Preferences to update") +}); +var UpdateNotificationPreferencesResponseSchema = external_exports.object({ + preferences: NotificationPreferencesSchema.describe("Updated notification preferences") +}); +var NotificationSchema = external_exports.object({ + id: external_exports.string().describe("Notification ID"), + type: external_exports.string().describe("Notification type"), + title: external_exports.string().describe("Notification title"), + body: external_exports.string().describe("Notification body text"), + read: external_exports.boolean().default(false).describe("Whether notification has been read"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional notification data"), + actionUrl: external_exports.string().optional().describe("URL to navigate to when clicked"), + createdAt: external_exports.string().datetime().describe("When notification was created") +}); +var ListNotificationsRequestSchema = external_exports.object({ + read: external_exports.boolean().optional().describe("Filter by read status"), + type: external_exports.string().optional().describe("Filter by notification type"), + limit: external_exports.number().default(20).describe("Maximum number of notifications to return"), + cursor: external_exports.string().optional().describe("Pagination cursor") +}); +var ListNotificationsResponseSchema = external_exports.object({ + notifications: external_exports.array(NotificationSchema).describe("List of notifications"), + unreadCount: external_exports.number().describe("Total number of unread notifications"), + cursor: external_exports.string().optional().describe("Next page cursor") +}); +var MarkNotificationsReadRequestSchema = external_exports.object({ + ids: external_exports.array(external_exports.string()).describe("Notification IDs to mark as read") +}); +var MarkNotificationsReadResponseSchema = external_exports.object({ + success: external_exports.boolean().describe("Whether the operation succeeded"), + readCount: external_exports.number().describe("Number of notifications marked as read") +}); +var MarkAllNotificationsReadRequestSchema = external_exports.object({}); +var MarkAllNotificationsReadResponseSchema = external_exports.object({ + success: external_exports.boolean().describe("Whether the operation succeeded"), + readCount: external_exports.number().describe("Number of notifications marked as read") +}); +var AiNlqRequestSchema = external_exports.object({ + query: external_exports.string().describe("Natural language query string"), + object: external_exports.string().optional().describe("Target object context"), + conversationId: external_exports.string().optional().describe("Conversation ID for multi-turn queries") +}); +var AiNlqResponseSchema = external_exports.object({ + query: external_exports.unknown().describe("Generated structured query (AST)"), + explanation: external_exports.string().optional().describe("Human-readable explanation of the query"), + confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), + suggestions: external_exports.array(external_exports.string()).optional().describe("Suggested follow-up queries") +}); +var AiSuggestRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name for context"), + field: external_exports.string().optional().describe("Field to suggest values for"), + recordId: external_exports.string().optional().describe("Record ID for context"), + partial: external_exports.string().optional().describe("Partial input for completion") +}); +var AiSuggestResponseSchema = external_exports.object({ + suggestions: external_exports.array(external_exports.object({ + value: external_exports.unknown().describe("Suggested value"), + label: external_exports.string().describe("Display label"), + confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), + reason: external_exports.string().optional().describe("Reason for this suggestion") + })).describe("Suggested values") +}); +var AiInsightsRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name to analyze"), + recordId: external_exports.string().optional().describe("Specific record to analyze"), + type: external_exports.enum(["summary", "trends", "anomalies", "recommendations"]).optional().describe("Type of insight") +}); +var AiInsightsResponseSchema = external_exports.object({ + insights: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Insight type"), + title: external_exports.string().describe("Insight title"), + description: external_exports.string().describe("Detailed description"), + confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Supporting data") + })).describe("Generated insights") +}); +var GetLocalesRequestSchema = external_exports.object({}); +var GetLocalesResponseSchema = external_exports.object({ + locales: external_exports.array(external_exports.object({ + code: external_exports.string().describe("BCP-47 locale code (e.g., en-US, zh-CN)"), + label: external_exports.string().describe("Display name of the locale"), + isDefault: external_exports.boolean().default(false).describe("Whether this is the default locale") + })).describe("Available locales") +}); +var GetTranslationsRequestSchema = external_exports.object({ + locale: external_exports.string().describe("BCP-47 locale code"), + namespace: external_exports.string().optional().describe("Translation namespace (e.g., objects, apps, messages)"), + keys: external_exports.array(external_exports.string()).optional().describe("Specific translation keys to fetch") +}); +var GetTranslationsResponseSchema = external_exports.object({ + locale: external_exports.string().describe("Locale code"), + translations: TranslationDataSchema2.describe("Translation data") +}); +var GetFieldLabelsRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + locale: external_exports.string().describe("BCP-47 locale code") +}); +var GetFieldLabelsResponseSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + locale: external_exports.string().describe("Locale code"), + labels: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().describe("Translated field label"), + help: external_exports.string().optional().describe("Translated help text"), + options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Translated option labels") + })).describe("Field labels keyed by field name") +}); +var ObjectStackProtocolSchema = external_exports.object({ + // Discovery & Metadata + getDiscovery: external_exports.function().describe("Get API discovery information"), + getMetaTypes: external_exports.function().describe("Get available metadata types"), + getMetaItems: external_exports.function().describe("Get all items of a metadata type"), + getMetaItem: external_exports.function().describe("Get a specific metadata item"), + saveMetaItem: external_exports.function().describe("Save metadata item"), + getMetaItemCached: external_exports.function().describe("Get a metadata item with cache validation"), + getUiView: external_exports.function().describe("Get UI view definition"), + // Analytics Operations + analyticsQuery: external_exports.function().describe("Execute analytics query"), + getAnalyticsMeta: external_exports.function().describe("Get analytics metadata (cubes)"), + // Automation Operations + triggerAutomation: external_exports.function().describe("Trigger an automation flow or script"), + // Package Management Operations + listPackages: external_exports.function().describe("List installed packages with optional filters"), + getPackage: external_exports.function().describe("Get a specific installed package by ID"), + installPackage: external_exports.function().describe("Install a new package from manifest"), + uninstallPackage: external_exports.function().describe("Uninstall a package by ID"), + enablePackage: external_exports.function().describe("Enable a disabled package"), + disablePackage: external_exports.function().describe("Disable an installed package"), + // Data Operations + findData: external_exports.function().describe("Find data records"), + getData: external_exports.function().describe("Get single data record"), + createData: external_exports.function().describe("Create a data record"), + updateData: external_exports.function().describe("Update a data record"), + deleteData: external_exports.function().describe("Delete a data record"), + // Batch Operations + batchData: external_exports.function().describe("Perform batch operations"), + createManyData: external_exports.function().describe("Create multiple records"), + updateManyData: external_exports.function().describe("Update multiple records"), + deleteManyData: external_exports.function().describe("Delete multiple records"), + // View Management Operations + listViews: external_exports.function().describe("List views for an object"), + getView: external_exports.function().describe("Get a specific view"), + createView: external_exports.function().describe("Create a new view"), + updateView: external_exports.function().describe("Update an existing view"), + deleteView: external_exports.function().describe("Delete a view"), + // Permission Operations + checkPermission: external_exports.function().describe("Check if an action is permitted"), + getObjectPermissions: external_exports.function().describe("Get permissions for an object"), + getEffectivePermissions: external_exports.function().describe("Get effective permissions for current user"), + // Workflow Operations + getWorkflowConfig: external_exports.function().describe("Get workflow configuration for an object"), + getWorkflowState: external_exports.function().describe("Get workflow state for a record"), + workflowTransition: external_exports.function().describe("Execute a workflow state transition"), + workflowApprove: external_exports.function().describe("Approve a workflow step"), + workflowReject: external_exports.function().describe("Reject a workflow step"), + // Realtime Operations + realtimeConnect: external_exports.function().describe("Establish realtime connection"), + realtimeDisconnect: external_exports.function().describe("Close realtime connection"), + realtimeSubscribe: external_exports.function().describe("Subscribe to a realtime channel"), + realtimeUnsubscribe: external_exports.function().describe("Unsubscribe from a realtime channel"), + setPresence: external_exports.function().describe("Set user presence state"), + getPresence: external_exports.function().describe("Get channel presence information"), + // Notification Operations + registerDevice: external_exports.function().describe("Register a device for push notifications"), + unregisterDevice: external_exports.function().describe("Unregister a device"), + getNotificationPreferences: external_exports.function().describe("Get notification preferences"), + updateNotificationPreferences: external_exports.function().describe("Update notification preferences"), + listNotifications: external_exports.function().describe("List notifications"), + markNotificationsRead: external_exports.function().describe("Mark specific notifications as read"), + markAllNotificationsRead: external_exports.function().describe("Mark all notifications as read"), + // AI Operations + aiNlq: external_exports.function().describe("Natural language query"), + aiChat: external_exports.function().describe("AI chat interaction"), + aiSuggest: external_exports.function().describe("Get AI-powered suggestions"), + aiInsights: external_exports.function().describe("Get AI-generated insights"), + // i18n Operations + getLocales: external_exports.function().describe("Get available locales"), + getTranslations: external_exports.function().describe("Get translations for a locale"), + getFieldLabels: external_exports.function().describe("Get translated field labels for an object"), + // Feed Operations + listFeed: external_exports.function().describe("List feed items for a record"), + createFeedItem: external_exports.function().describe("Create a new feed item"), + updateFeedItem: external_exports.function().describe("Update an existing feed item"), + deleteFeedItem: external_exports.function().describe("Delete a feed item"), + addReaction: external_exports.function().describe("Add an emoji reaction to a feed item"), + removeReaction: external_exports.function().describe("Remove an emoji reaction from a feed item"), + pinFeedItem: external_exports.function().describe("Pin a feed item"), + unpinFeedItem: external_exports.function().describe("Unpin a feed item"), + starFeedItem: external_exports.function().describe("Star a feed item"), + unstarFeedItem: external_exports.function().describe("Unstar a feed item"), + searchFeed: external_exports.function().describe("Search feed items"), + getChangelog: external_exports.function().describe("Get field-level changelog for a record"), + feedSubscribe: external_exports.function().describe("Subscribe to record notifications"), + feedUnsubscribe: external_exports.function().describe("Unsubscribe from record notifications") +}); +var RestApiConfigSchema = external_exports.object({ + /** + * API version identifier + */ + version: external_exports.string().regex(/^[a-zA-Z0-9_\-\.]+$/).default("v1").describe("API version (e.g., v1, v2, 2024-01)"), + /** + * Base path for all API routes + */ + basePath: external_exports.string().default("/api").describe("Base URL path for API"), + /** + * Full API path (combines basePath and version) + */ + apiPath: external_exports.string().optional().describe("Full API path (defaults to {basePath}/{version})"), + /** + * Enable automatic CRUD endpoints + */ + enableCrud: external_exports.boolean().default(true).describe("Enable automatic CRUD endpoint generation"), + /** + * Enable metadata endpoints + */ + enableMetadata: external_exports.boolean().default(true).describe("Enable metadata API endpoints"), + /** + * Enable UI API endpoints + */ + enableUi: external_exports.boolean().default(true).describe("Enable UI API endpoints (Views, Menus, Layouts)"), + /** + * Enable batch operation endpoints + */ + enableBatch: external_exports.boolean().default(true).describe("Enable batch operation endpoints"), + /** + * Enable discovery endpoint + */ + enableDiscovery: external_exports.boolean().default(true).describe("Enable API discovery endpoint"), + /** + * API documentation configuration + */ + documentation: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable API documentation"), + title: external_exports.string().default("ObjectStack API").describe("API documentation title"), + description: external_exports.string().optional().describe("API description"), + version: external_exports.string().optional().describe("Documentation version"), + termsOfService: external_exports.string().optional().describe("Terms of service URL"), + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().optional(), + email: external_exports.string().optional() + }).optional(), + license: external_exports.object({ + name: external_exports.string(), + url: external_exports.string().optional() + }).optional() + }).optional().describe("OpenAPI/Swagger documentation config"), + /** + * Response format configuration + */ + responseFormat: external_exports.object({ + envelope: external_exports.boolean().default(true).describe("Wrap responses in standard envelope"), + includeMetadata: external_exports.boolean().default(true).describe("Include response metadata (timestamp, requestId)"), + includePagination: external_exports.boolean().default(true).describe("Include pagination info in list responses") + }).optional().describe("Response format options") +}); +var CrudOperation = external_exports.enum([ + "create", + // POST /api/v1/data/{object} + "read", + // GET /api/v1/data/{object}/:id + "update", + // PATCH /api/v1/data/{object}/:id + "delete", + // DELETE /api/v1/data/{object}/:id + "list" + // GET /api/v1/data/{object} +]); +var CrudEndpointPatternSchema = external_exports.object({ + /** + * HTTP method + */ + method: HttpMethod2.describe("HTTP method"), + /** + * URL path pattern (relative to API base) + */ + path: external_exports.string().describe("URL path pattern"), + /** + * Operation summary for documentation + */ + summary: external_exports.string().optional().describe("Operation summary"), + /** + * Operation description + */ + description: external_exports.string().optional().describe("Operation description") +}); +var CrudEndpointsConfigSchema = external_exports.object({ + /** + * Enable/disable specific CRUD operations + */ + operations: external_exports.object({ + create: external_exports.boolean().default(true).describe("Enable create operation"), + read: external_exports.boolean().default(true).describe("Enable read operation"), + update: external_exports.boolean().default(true).describe("Enable update operation"), + delete: external_exports.boolean().default(true).describe("Enable delete operation"), + list: external_exports.boolean().default(true).describe("Enable list operation") + }).optional().describe("Enable/disable operations"), + /** + * Custom endpoint patterns (override defaults) + */ + patterns: external_exports.record(CrudOperation, CrudEndpointPatternSchema.optional()).optional().describe("Custom URL patterns for operations"), + /** + * Path prefix for data operations + */ + dataPrefix: external_exports.string().default("/data").describe("URL prefix for data endpoints"), + /** + * Object name parameter style + */ + objectParamStyle: external_exports.enum(["path", "query"]).default("path").describe("How object name is passed (path param or query param)") +}); +var MetadataEndpointsConfigSchema = external_exports.object({ + /** + * Path prefix for metadata operations + */ + prefix: external_exports.string().default("/meta").describe("URL prefix for metadata endpoints"), + /** + * Enable HTTP caching for metadata + */ + enableCache: external_exports.boolean().default(true).describe("Enable HTTP cache headers (ETag, Last-Modified)"), + /** + * Cache TTL in seconds + */ + cacheTtl: external_exports.number().int().default(3600).describe("Cache TTL in seconds"), + /** + * Enable specific metadata endpoints + */ + endpoints: external_exports.object({ + types: external_exports.boolean().default(true).describe("GET /meta - List all metadata types"), + items: external_exports.boolean().default(true).describe("GET /meta/:type - List items of type"), + item: external_exports.boolean().default(true).describe("GET /meta/:type/:name - Get specific item"), + schema: external_exports.boolean().default(true).describe("GET /meta/:type/:name/schema - Get JSON schema") + }).optional().describe("Enable/disable specific endpoints") +}); +var BatchEndpointsConfigSchema = external_exports.object({ + /** + * Maximum batch size + */ + maxBatchSize: external_exports.number().int().min(1).max(1e3).default(200).describe("Maximum records per batch operation"), + /** + * Enable generic batch endpoint + */ + enableBatchEndpoint: external_exports.boolean().default(true).describe("Enable POST /data/:object/batch endpoint"), + /** + * Enable specific batch operations + */ + operations: external_exports.object({ + createMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/createMany"), + updateMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/updateMany"), + deleteMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/deleteMany"), + upsertMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/upsertMany") + }).optional().describe("Enable/disable specific batch operations"), + /** + * Transaction mode default + */ + defaultAtomic: external_exports.boolean().default(true).describe("Default atomic/transaction mode for batch operations") +}); +var RouteGenerationConfigSchema = external_exports.object({ + /** + * Objects to include (if empty, include all) + */ + includeObjects: external_exports.array(external_exports.string()).optional().describe("Specific objects to generate routes for (empty = all)"), + /** + * Objects to exclude + */ + excludeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to exclude from route generation"), + /** + * Object name transformations + */ + nameTransform: external_exports.enum(["none", "plural", "kebab-case", "camelCase"]).default("none").describe("Transform object names in URLs"), + /** + * Custom route overrides per object + */ + overrides: external_exports.record(external_exports.string(), external_exports.object({ + enabled: external_exports.boolean().optional().describe("Enable/disable routes for this object"), + basePath: external_exports.string().optional().describe("Custom base path"), + operations: external_exports.record(CrudOperation, external_exports.boolean()).optional().describe("Enable/disable specific operations") + })).optional().describe("Per-object route customization") +}); +var WebhookEventSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Webhook event identifier (snake_case)"), + description: external_exports.string().describe("Human-readable event description"), + method: HttpMethod2.default("POST").describe("HTTP method for webhook delivery"), + payloadSchema: external_exports.string().describe("JSON Schema $ref for the webhook payload"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers to include in webhook delivery"), + security: external_exports.array( + external_exports.enum(["hmac_sha256", "basic", "bearer", "api_key"]) + ).describe("Supported authentication methods for webhook verification") +}); +var WebhookConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable webhook support"), + events: external_exports.array(WebhookEventSchema).describe("Registered webhook events"), + deliveryConfig: external_exports.object({ + maxRetries: external_exports.number().int().default(3).describe("Maximum delivery retry attempts"), + retryIntervalMs: external_exports.number().int().default(5e3).describe("Milliseconds between retry attempts"), + timeoutMs: external_exports.number().int().default(3e4).describe("Delivery request timeout in milliseconds"), + signatureHeader: external_exports.string().default("X-Signature-256").describe("Header name for webhook signature") + }).describe("Webhook delivery configuration"), + registrationEndpoint: external_exports.string().default("/webhooks").describe("URL path for webhook registration") +}); +var CallbackSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Callback identifier (snake_case)"), + expression: external_exports.string().describe("Runtime expression (e.g., {$request.body#/callbackUrl})"), + method: HttpMethod2.describe("HTTP method for callback request"), + url: external_exports.string().describe("Callback URL template with runtime expressions") +}); +var OpenApi31ExtensionsSchema = external_exports.object({ + webhooks: external_exports.record(external_exports.string(), WebhookEventSchema).optional().describe("OpenAPI 3.1 webhooks (top-level webhook definitions)"), + callbacks: external_exports.record(external_exports.string(), external_exports.array(CallbackSchema)).optional().describe("OpenAPI 3.1 callbacks (async response definitions)"), + jsonSchemaDialect: external_exports.string().default("https://json-schema.org/draft/2020-12/schema").describe("JSON Schema dialect for schema definitions"), + pathItemReferences: external_exports.boolean().default(false).describe("Allow $ref in path items (OpenAPI 3.1 feature)") +}); +var RestServerConfigSchema = external_exports.object({ + /** + * API configuration + */ + api: RestApiConfigSchema.optional().describe("REST API configuration"), + /** + * CRUD endpoints configuration + */ + crud: CrudEndpointsConfigSchema.optional().describe("CRUD endpoints configuration"), + /** + * Metadata endpoints configuration + */ + metadata: MetadataEndpointsConfigSchema.optional().describe("Metadata endpoints configuration"), + /** + * Batch endpoints configuration + */ + batch: BatchEndpointsConfigSchema.optional().describe("Batch endpoints configuration"), + /** + * Route generation configuration + */ + routes: RouteGenerationConfigSchema.optional().describe("Route generation configuration"), + /** + * OpenAPI 3.1 extensions (webhooks, callbacks) + */ + openApi31: OpenApi31ExtensionsSchema.optional().describe("OpenAPI 3.1 extensions configuration") +}); +var GeneratedEndpointSchema = external_exports.object({ + /** + * Endpoint identifier + */ + id: external_exports.string().describe("Unique endpoint identifier"), + /** + * HTTP method + */ + method: HttpMethod2.describe("HTTP method"), + /** + * Full URL path + */ + path: external_exports.string().describe("Full URL path"), + /** + * Object this endpoint operates on + */ + object: external_exports.string().describe("Object name (snake_case)"), + /** + * Operation type + */ + operation: external_exports.union([CrudOperation, external_exports.string()]).describe("Operation type"), + /** + * Handler reference + */ + handler: external_exports.string().describe("Handler function identifier"), + /** + * Endpoint metadata + */ + metadata: external_exports.object({ + summary: external_exports.string().optional(), + description: external_exports.string().optional(), + tags: external_exports.array(external_exports.string()).optional(), + deprecated: external_exports.boolean().optional() + }).optional() +}); +var EndpointRegistrySchema = external_exports.object({ + /** + * Generated endpoints + */ + endpoints: external_exports.array(GeneratedEndpointSchema).describe("All generated endpoints"), + /** + * Total endpoint count + */ + total: external_exports.number().int().describe("Total number of endpoints"), + /** + * Endpoints by object + */ + byObject: external_exports.record(external_exports.string(), external_exports.array(GeneratedEndpointSchema)).optional().describe("Endpoints grouped by object"), + /** + * Endpoints by operation + */ + byOperation: external_exports.record(external_exports.string(), external_exports.array(GeneratedEndpointSchema)).optional().describe("Endpoints grouped by operation") +}); +var RestApiConfig = Object.assign(RestApiConfigSchema, { + create: (config4) => config4 +}); +var RestServerConfig = Object.assign(RestServerConfigSchema, { + create: (config4) => config4 +}); +var ApiProtocolType = external_exports.enum([ + "rest", + // RESTful API (CRUD operations) + "graphql", + // GraphQL API (flexible queries) + "odata", + // OData v4 API (enterprise integration) + "websocket", + // WebSocket API (real-time) + "file", + // File/Storage API (uploads/downloads) + "auth", + // Authentication/Authorization API + "metadata", + // Metadata/Schema API + "plugin", + // Plugin-registered custom API + "webhook", + // Webhook endpoints + "rpc" + // JSON-RPC or similar +]); +var HttpStatusCode = external_exports.union([ + external_exports.number().int().min(100).max(599), + external_exports.enum(["2xx", "3xx", "4xx", "5xx"]) + // Pattern matching +]); +var ObjectQLReferenceSchema = external_exports.object({ + /** Referenced object name (snake_case) */ + objectId: SnakeCaseIdentifierSchema2.describe("Object name to reference"), + /** Include only specific fields (optional) */ + includeFields: external_exports.array(external_exports.string()).optional().describe("Include only these fields in the schema"), + /** Exclude specific fields (optional) */ + excludeFields: external_exports.array(external_exports.string()).optional().describe("Exclude these fields from the schema"), + /** Include related objects via lookup fields */ + includeRelated: external_exports.array(external_exports.string()).optional().describe("Include related objects via lookup fields") +}); +var SchemaDefinition = external_exports.union([ + external_exports.unknown().describe("Static JSON Schema definition"), + external_exports.object({ + $ref: ObjectQLReferenceSchema.describe("Dynamic reference to ObjectQL object") + }).describe("Dynamic ObjectQL reference") +]); +var ApiParameterSchema = external_exports.object({ + /** Parameter name */ + name: external_exports.string().describe("Parameter name"), + /** Parameter location */ + in: external_exports.enum(["path", "query", "header", "body", "cookie"]).describe("Parameter location"), + /** Parameter description */ + description: external_exports.string().optional().describe("Parameter description"), + /** Required flag */ + required: external_exports.boolean().default(false).describe("Whether parameter is required"), + /** Parameter type/schema - supports static or dynamic (ObjectQL) schemas */ + schema: external_exports.union([ + external_exports.object({ + type: external_exports.enum(["string", "number", "integer", "boolean", "array", "object"]).describe("Parameter type"), + format: external_exports.string().optional().describe("Format (e.g., date-time, email, uuid)"), + enum: external_exports.array(external_exports.unknown()).optional().describe("Allowed values"), + default: external_exports.unknown().optional().describe("Default value"), + items: external_exports.unknown().optional().describe("Array item schema"), + properties: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Object properties") + }).describe("Static JSON Schema"), + external_exports.object({ + $ref: ObjectQLReferenceSchema + }).describe("Dynamic ObjectQL reference") + ]).describe("Parameter schema definition"), + /** Example value */ + example: external_exports.unknown().optional().describe("Example value") +}); +var ApiResponseSchema = external_exports.object({ + /** HTTP status code */ + statusCode: HttpStatusCode.describe("HTTP status code"), + /** Response description */ + description: external_exports.string().describe("Response description"), + /** Response content type */ + contentType: external_exports.string().default("application/json").describe("Response content type"), + /** Response schema - supports static or dynamic (ObjectQL) schemas */ + schema: external_exports.union([ + external_exports.unknown().describe("Static JSON Schema"), + external_exports.object({ + $ref: ObjectQLReferenceSchema + }).describe("Dynamic ObjectQL reference") + ]).optional().describe("Response body schema"), + /** Response headers */ + headers: external_exports.record(external_exports.string(), external_exports.object({ + description: external_exports.string().optional(), + schema: external_exports.unknown() + })).optional().describe("Response headers"), + /** Example response */ + example: external_exports.unknown().optional().describe("Example response") +}); +var ApiEndpointRegistrationSchema = external_exports.object({ + /** Unique endpoint identifier */ + id: external_exports.string().describe("Unique endpoint identifier"), + /** HTTP method (for HTTP-based APIs) */ + method: HttpMethod2.optional().describe("HTTP method"), + /** URL path pattern */ + path: external_exports.string().describe("URL path pattern"), + /** Short summary */ + summary: external_exports.string().optional().describe("Short endpoint summary"), + /** Detailed description */ + description: external_exports.string().optional().describe("Detailed endpoint description"), + /** Operation ID (OpenAPI) */ + operationId: external_exports.string().optional().describe("Unique operation identifier"), + /** Tags for grouping */ + tags: external_exports.array(external_exports.string()).optional().default([]).describe("Tags for categorization"), + /** Parameters */ + parameters: external_exports.array(ApiParameterSchema).optional().default([]).describe("Endpoint parameters"), + /** Request body schema */ + requestBody: external_exports.object({ + description: external_exports.string().optional(), + required: external_exports.boolean().default(false), + contentType: external_exports.string().default("application/json"), + schema: external_exports.unknown().optional(), + example: external_exports.unknown().optional() + }).optional().describe("Request body specification"), + /** Response definitions */ + responses: external_exports.array(ApiResponseSchema).optional().default([]).describe("Possible responses"), + /** Rate Limiting */ + rateLimit: RateLimitConfigSchema2.optional().describe("Endpoint specific rate limiting"), + /** Security Requirements */ + security: external_exports.array(external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))).optional().describe('Security requirements (e.g. [{"bearerAuth": []}])'), + /** + * Required Permissions (RBAC Integration) + * + * Array of permission names required to access this endpoint. + * The gateway layer automatically validates these permissions before + * allowing the request to proceed, eliminating the need for permission + * checks in individual API handlers. + * + * **Format:** `.` or system permission name + * + * **Object Permissions:** + * - `customer.read` - Read customer records + * - `customer.create` - Create customer records + * - `customer.edit` - Update customer records + * - `customer.delete` - Delete customer records + * - `customer.viewAll` - View all customer records (bypass sharing) + * - `customer.modifyAll` - Modify all customer records (bypass sharing) + * + * **System Permissions:** + * - `manage_users` - User management + * - `view_setup` - Access to system setup + * - `customize_application` - Modify metadata + * - `api_enabled` - API access + * + * @example Object-level permissions + * ```json + * { + * "requiredPermissions": ["customer.read"] + * } + * ``` + * + * @example Multiple permissions (ALL required) + * ```json + * { + * "requiredPermissions": ["customer.read", "account.read"] + * } + * ``` + * + * @example System permission + * ```json + * { + * "requiredPermissions": ["manage_users"] + * } + * ``` + * + * @see {@link file://../../permission/permission.zod.ts} for permission definitions + */ + requiredPermissions: external_exports.array(external_exports.string()).optional().default([]).describe('Required RBAC permissions (e.g., "customer.read", "manage_users")'), + /** + * Route Priority + * + * Priority level for route conflict resolution. Higher priority routes + * are registered first and take precedence when multiple routes match + * the same path pattern. + * + * **Default:** 100 (medium priority) + * **Range:** 0-1000 (higher = more important) + * + * **Use Cases:** + * - Core system APIs: 900-1000 + * - Plugin APIs: 100-500 + * - Custom/override APIs: 500-900 + * - Fallback routes: 0-100 + * + * @example High priority core endpoint + * ```json + * { + * "path": "/api/v1/data/:object/:id", + * "priority": 950 + * } + * ``` + * + * @example Medium priority plugin endpoint + * ```json + * { + * "path": "/api/v1/custom/action", + * "priority": 300 + * } + * ``` + */ + priority: external_exports.number().int().min(0).max(1e3).optional().default(100).describe("Route priority for conflict resolution (0-1000, higher = more important)"), + /** + * Protocol-Specific Configuration + * + * Allows plugins and custom APIs to define protocol-specific metadata + * that can be used for specialized handling or documentation generation. + * + * **Examples:** + * - gRPC: Service and method names + * - tRPC: Procedure type (query/mutation) + * - WebSocket: Event names and handlers + * - Custom protocols: Any metadata needed + * + * @example gRPC configuration + * ```json + * { + * "protocolConfig": { + * "subProtocol": "grpc", + * "serviceName": "CustomerService", + * "methodName": "GetCustomer", + * "streaming": false + * } + * } + * ``` + * + * @example tRPC configuration + * ```json + * { + * "protocolConfig": { + * "subProtocol": "trpc", + * "procedureType": "query", + * "router": "customer" + * } + * } + * ``` + * + * @example WebSocket configuration + * ```json + * { + * "protocolConfig": { + * "subProtocol": "websocket", + * "eventName": "customer.updated", + * "direction": "server-to-client" + * } + * } + * ``` + */ + protocolConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)"), + /** Deprecation flag */ + deprecated: external_exports.boolean().default(false).describe("Whether endpoint is deprecated"), + /** External documentation */ + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional().describe("External documentation link") +}); +var ApiMetadataSchema = external_exports.object({ + /** API owner/team */ + owner: external_exports.string().optional().describe("Owner team or person"), + /** API status */ + status: external_exports.enum(["active", "deprecated", "experimental", "beta"]).default("active").describe("API lifecycle status"), + /** Categorization tags */ + tags: external_exports.array(external_exports.string()).optional().default([]).describe("Classification tags"), + /** Plugin source (if plugin-registered) */ + pluginSource: external_exports.string().optional().describe("Source plugin name"), + /** Custom metadata */ + custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata fields") +}); +var ApiRegistryEntrySchema = external_exports.object({ + /** Unique API identifier */ + id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique API identifier (snake_case)"), + /** Human-readable name */ + name: external_exports.string().describe("API display name"), + /** API protocol type */ + type: ApiProtocolType.describe("API protocol type"), + /** API version */ + version: external_exports.string().describe("API version (e.g., v1, 2024-01)"), + /** Base URL path */ + basePath: external_exports.string().describe("Base URL path for this API"), + /** API description */ + description: external_exports.string().optional().describe("API description"), + /** Endpoints in this API */ + endpoints: external_exports.array(ApiEndpointRegistrationSchema).describe("Registered endpoints"), + /** OpenAPI/GraphQL/OData specific configuration */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Protocol-specific configuration"), + /** API metadata */ + metadata: ApiMetadataSchema.optional().describe("Additional metadata"), + /** Terms of service URL */ + termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), + /** Contact information */ + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().url().optional(), + email: external_exports.string().email().optional() + }).optional().describe("Contact information"), + /** License information */ + license: external_exports.object({ + name: external_exports.string(), + url: external_exports.string().url().optional() + }).optional().describe("License information") +}); +var ConflictResolutionStrategy = external_exports.enum([ + "error", + // Throw error on conflict (safest, default) + "priority", + // Use priority field to resolve (highest priority wins) + "first-wins", + // First registered endpoint wins + "last-wins" + // Last registered endpoint wins (override mode) +]); +var ApiRegistrySchema = external_exports.object({ + /** Registry version */ + version: external_exports.string().describe("Registry version"), + /** + * Conflict Resolution Strategy + * + * Defines how to handle route conflicts when multiple endpoints + * register the same or overlapping URL patterns. + * + * **Strategies:** + * - `error`: Throw error on conflict (safest, prevents silent overwrites) + * - `priority`: Use endpoint priority field (highest priority wins) + * - `first-wins`: First registered endpoint wins (stable, predictable) + * - `last-wins`: Last registered endpoint wins (allows overrides) + * + * **Default:** `error` + * + * **Best Practices:** + * - Use `error` in production to catch configuration issues + * - Use `priority` when mixing core and plugin APIs + * - Use `last-wins` for development/testing overrides + * + * @example Prevent accidental conflicts + * ```json + * { + * "conflictResolution": "error" + * } + * ``` + * + * @example Allow plugin overrides with priority + * ```json + * { + * "conflictResolution": "priority" + * } + * ``` + */ + conflictResolution: ConflictResolutionStrategy.optional().default("error").describe("Strategy for handling route conflicts"), + /** Registered APIs */ + apis: external_exports.array(ApiRegistryEntrySchema).describe("All registered APIs"), + /** Total API count */ + totalApis: external_exports.number().int().describe("Total number of registered APIs"), + /** Total endpoint count across all APIs */ + totalEndpoints: external_exports.number().int().describe("Total number of endpoints"), + /** APIs grouped by type */ + byType: external_exports.record(ApiProtocolType, external_exports.array(ApiRegistryEntrySchema)).optional().describe("APIs grouped by protocol type"), + /** APIs grouped by status */ + byStatus: external_exports.record(external_exports.string(), external_exports.array(ApiRegistryEntrySchema)).optional().describe("APIs grouped by status"), + /** Last updated timestamp */ + updatedAt: external_exports.string().datetime().optional().describe("Last registry update time") +}); +var ApiDiscoveryQuerySchema = external_exports.object({ + /** Filter by API type */ + type: ApiProtocolType.optional().describe("Filter by API protocol type"), + /** Filter by tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags (ANY match)"), + /** Filter by status */ + status: external_exports.enum(["active", "deprecated", "experimental", "beta"]).optional().describe("Filter by lifecycle status"), + /** Filter by plugin source */ + pluginSource: external_exports.string().optional().describe("Filter by plugin name"), + /** Search in name/description */ + search: external_exports.string().optional().describe("Full-text search in name/description"), + /** Filter by version */ + version: external_exports.string().optional().describe("Filter by specific version") +}); +var ApiDiscoveryResponseSchema = external_exports.object({ + /** Matching APIs */ + apis: external_exports.array(ApiRegistryEntrySchema).describe("Matching API entries"), + /** Total matches */ + total: external_exports.number().int().describe("Total matching APIs"), + /** Applied filters */ + filters: ApiDiscoveryQuerySchema.optional().describe("Applied query filters") +}); +var ApiEndpointRegistration = Object.assign(ApiEndpointRegistrationSchema, { + create: (config4) => config4 +}); +var ApiRegistryEntry = Object.assign(ApiRegistryEntrySchema, { + create: (config4) => config4 +}); +var ApiRegistry = Object.assign(ApiRegistrySchema, { + create: (config4) => config4 +}); +var OpenApiServerSchema = external_exports.object({ + /** Server URL */ + url: external_exports.string().url().describe("Server base URL"), + /** Server description */ + description: external_exports.string().optional().describe("Server description"), + /** Server variables */ + variables: external_exports.record(external_exports.string(), external_exports.object({ + default: external_exports.string(), + description: external_exports.string().optional(), + enum: external_exports.array(external_exports.string()).optional() + })).optional().describe("URL template variables") +}); +var OpenApiSecuritySchemeSchema = external_exports.object({ + /** Security scheme type */ + type: external_exports.enum(["apiKey", "http", "oauth2", "openIdConnect"]).describe("Security type"), + /** Scheme name */ + scheme: external_exports.string().optional().describe("HTTP auth scheme (bearer, basic, etc.)"), + /** Bearer format */ + bearerFormat: external_exports.string().optional().describe("Bearer token format (e.g., JWT)"), + /** API key name */ + name: external_exports.string().optional().describe("API key parameter name"), + /** API key location */ + in: external_exports.enum(["header", "query", "cookie"]).optional().describe("API key location"), + /** OAuth flows */ + flows: external_exports.object({ + implicit: external_exports.unknown().optional(), + password: external_exports.unknown().optional(), + clientCredentials: external_exports.unknown().optional(), + authorizationCode: external_exports.unknown().optional() + }).optional().describe("OAuth2 flows"), + /** OpenID Connect URL */ + openIdConnectUrl: external_exports.string().url().optional().describe("OpenID Connect discovery URL"), + /** Description */ + description: external_exports.string().optional().describe("Security scheme description") +}); +var OpenApiSpecSchema = external_exports.object({ + /** OpenAPI version */ + openapi: external_exports.string().default("3.0.0").describe("OpenAPI specification version"), + /** API information */ + info: external_exports.object({ + title: external_exports.string().describe("API title"), + version: external_exports.string().describe("API version"), + description: external_exports.string().optional().describe("API description"), + termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().url().optional(), + email: external_exports.string().email().optional() + }).optional(), + license: external_exports.object({ + name: external_exports.string(), + url: external_exports.string().url().optional() + }).optional() + }).describe("API metadata"), + /** Servers */ + servers: external_exports.array(OpenApiServerSchema).optional().default([]).describe("API servers"), + /** API paths */ + paths: external_exports.record(external_exports.string(), external_exports.unknown()).describe("API paths and operations"), + /** Reusable components */ + components: external_exports.object({ + schemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + responses: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + examples: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + requestBodies: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + headers: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + securitySchemes: external_exports.record(external_exports.string(), OpenApiSecuritySchemeSchema).optional(), + links: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + callbacks: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional().describe("Reusable components"), + /** Security requirements */ + security: external_exports.array(external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))).optional().describe("Global security requirements"), + /** Tags */ + tags: external_exports.array(external_exports.object({ + name: external_exports.string(), + description: external_exports.string().optional(), + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional() + })).optional().describe("Tag definitions"), + /** External documentation */ + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional().describe("External documentation") +}); +var ApiTestingUiType = external_exports.enum([ + "swagger-ui", + // Swagger UI + "redoc", + // Redoc + "rapidoc", + // RapiDoc + "stoplight", + // Stoplight Elements + "scalar", + // Scalar API Reference + "graphql-playground", + // GraphQL Playground + "graphiql", + // GraphiQL + "postman", + // Postman-like interface + "custom" + // Custom implementation +]); +var ApiTestingUiConfigSchema = external_exports.object({ + /** UI type */ + type: ApiTestingUiType.describe("Testing UI implementation"), + /** UI path */ + path: external_exports.string().default("/api-docs").describe("URL path for documentation UI"), + /** UI theme */ + theme: external_exports.enum(["light", "dark", "auto"]).default("light").describe("UI color theme"), + /** Enable try-it-out feature */ + enableTryItOut: external_exports.boolean().default(true).describe("Enable interactive API testing"), + /** Enable filtering */ + enableFilter: external_exports.boolean().default(true).describe("Enable endpoint filtering"), + /** Enable CORS for testing */ + enableCors: external_exports.boolean().default(true).describe("Enable CORS for browser testing"), + /** Default expand depth for models */ + defaultModelsExpandDepth: external_exports.number().int().min(-1).default(1).describe("Default expand depth for schemas (-1 = fully expand)"), + /** Display request duration */ + displayRequestDuration: external_exports.boolean().default(true).describe("Show request duration"), + /** Syntax highlighting */ + syntaxHighlighting: external_exports.boolean().default(true).describe("Enable syntax highlighting"), + /** Custom CSS URL */ + customCssUrl: external_exports.string().url().optional().describe("Custom CSS stylesheet URL"), + /** Custom JavaScript URL */ + customJsUrl: external_exports.string().url().optional().describe("Custom JavaScript URL"), + /** Layout options */ + layout: external_exports.object({ + showExtensions: external_exports.boolean().default(false).describe("Show vendor extensions"), + showCommonExtensions: external_exports.boolean().default(false).describe("Show common extensions"), + deepLinking: external_exports.boolean().default(true).describe("Enable deep linking"), + displayOperationId: external_exports.boolean().default(false).describe("Display operation IDs"), + defaultModelRendering: external_exports.enum(["example", "model"]).default("example").describe("Default model rendering mode"), + defaultModelsExpandDepth: external_exports.number().int().default(1).describe("Models expand depth"), + defaultModelExpandDepth: external_exports.number().int().default(1).describe("Single model expand depth"), + docExpansion: external_exports.enum(["list", "full", "none"]).default("list").describe("Documentation expansion mode") + }).optional().describe("Layout configuration") +}); +var ApiTestRequestSchema = external_exports.object({ + /** Request name */ + name: external_exports.string().describe("Test request name"), + /** Request description */ + description: external_exports.string().optional().describe("Request description"), + /** HTTP method */ + method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]).describe("HTTP method"), + /** Request URL */ + url: external_exports.string().describe("Request URL (can include variables)"), + /** Request headers */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().default({}).describe("Request headers"), + /** Query parameters */ + queryParams: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().default({}).describe("Query parameters"), + /** Request body */ + body: external_exports.unknown().optional().describe("Request body"), + /** Environment variables */ + variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().default({}).describe("Template variables"), + /** Expected response */ + expectedResponse: external_exports.object({ + statusCode: external_exports.number().int(), + body: external_exports.unknown().optional() + }).optional().describe("Expected response for validation") +}); +var ApiTestCollectionSchema = external_exports.object({ + /** Collection name */ + name: external_exports.string().describe("Collection name"), + /** Collection description */ + description: external_exports.string().optional().describe("Collection description"), + /** Collection variables */ + variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().default({}).describe("Shared variables"), + /** Test requests */ + requests: external_exports.array(ApiTestRequestSchema).describe("Test requests in this collection"), + /** Folders/grouping */ + folders: external_exports.array(external_exports.object({ + name: external_exports.string(), + description: external_exports.string().optional(), + requests: external_exports.array(ApiTestRequestSchema) + })).optional().describe("Request folders for organization") +}); +var ApiChangelogEntrySchema = external_exports.object({ + /** Version */ + version: external_exports.string().describe("API version"), + /** Release date */ + date: external_exports.string().date().describe("Release date"), + /** Changes */ + changes: external_exports.object({ + added: external_exports.array(external_exports.string()).optional().default([]).describe("New features"), + changed: external_exports.array(external_exports.string()).optional().default([]).describe("Changes"), + deprecated: external_exports.array(external_exports.string()).optional().default([]).describe("Deprecations"), + removed: external_exports.array(external_exports.string()).optional().default([]).describe("Removed features"), + fixed: external_exports.array(external_exports.string()).optional().default([]).describe("Bug fixes"), + security: external_exports.array(external_exports.string()).optional().default([]).describe("Security fixes") + }).describe("Version changes"), + /** Migration guide */ + migrationGuide: external_exports.string().optional().describe("Migration guide URL or text") +}); +var CodeGenerationTemplateSchema = external_exports.object({ + /** Language/framework */ + language: external_exports.string().describe("Target language/framework (e.g., typescript, python, curl)"), + /** Template name */ + name: external_exports.string().describe("Template name"), + /** Template content */ + template: external_exports.string().describe("Code template with placeholders"), + /** Template variables */ + variables: external_exports.array(external_exports.string()).optional().describe("Required template variables") +}); +var ApiDocumentationConfigSchema = external_exports.object({ + /** Enable documentation */ + enabled: external_exports.boolean().default(true).describe("Enable API documentation"), + /** Documentation title */ + title: external_exports.string().default("API Documentation").describe("Documentation title"), + /** API version */ + version: external_exports.string().describe("API version"), + /** API description */ + description: external_exports.string().optional().describe("API description"), + /** Server configurations */ + servers: external_exports.array(OpenApiServerSchema).optional().default([]).describe("API server URLs"), + /** UI configuration */ + ui: ApiTestingUiConfigSchema.optional().describe("Testing UI configuration"), + /** Generate OpenAPI spec */ + generateOpenApi: external_exports.boolean().default(true).describe("Generate OpenAPI 3.0 specification"), + /** Generate test collections */ + generateTestCollections: external_exports.boolean().default(true).describe("Generate API test collections"), + /** Test collections */ + testCollections: external_exports.array(ApiTestCollectionSchema).optional().default([]).describe("Predefined test collections"), + /** API changelog */ + changelog: external_exports.array(ApiChangelogEntrySchema).optional().default([]).describe("API version changelog"), + /** Code generation templates */ + codeTemplates: external_exports.array(CodeGenerationTemplateSchema).optional().default([]).describe("Code generation templates"), + /** Terms of service */ + termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), + /** Contact information */ + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().url().optional(), + email: external_exports.string().email().optional() + }).optional().describe("Contact information"), + /** License */ + license: external_exports.object({ + name: external_exports.string(), + url: external_exports.string().url().optional() + }).optional().describe("API license"), + /** External documentation */ + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional().describe("External documentation link"), + /** Security schemes */ + securitySchemes: external_exports.record(external_exports.string(), OpenApiSecuritySchemeSchema).optional().describe("Security scheme definitions"), + /** Global tags */ + tags: external_exports.array(external_exports.object({ + name: external_exports.string(), + description: external_exports.string().optional(), + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional() + })).optional().describe("Global tag definitions") +}); +var GeneratedApiDocumentationSchema = external_exports.object({ + /** OpenAPI specification */ + openApiSpec: OpenApiSpecSchema.optional().describe("Generated OpenAPI specification"), + /** Test collections */ + testCollections: external_exports.array(ApiTestCollectionSchema).optional().describe("Generated test collections"), + /** Markdown documentation */ + markdown: external_exports.string().optional().describe("Generated markdown documentation"), + /** HTML documentation */ + html: external_exports.string().optional().describe("Generated HTML documentation"), + /** Generation timestamp */ + generatedAt: external_exports.string().datetime().describe("Generation timestamp"), + /** Source APIs */ + sourceApis: external_exports.array(external_exports.string()).describe("Source API IDs used for generation") +}); +var ApiDocumentationConfig = Object.assign(ApiDocumentationConfigSchema, { + create: (config4) => config4 +}); +var ApiTestCollection = Object.assign(ApiTestCollectionSchema, { + create: (config4) => config4 +}); +var OpenApiSpec = Object.assign(OpenApiSpecSchema, { + create: (config4) => config4 +}); +var AggregationMetricType = external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "number", + // Custom SQL expression returning a number + "string", + // Custom SQL expression returning a string + "boolean" + // Custom SQL expression returning a boolean +]); +var DimensionType = external_exports.enum([ + "string", + "number", + "boolean", + "time", + "geo" +]); +var TimeUpdateInterval = external_exports.enum([ + "second", + "minute", + "hour", + "day", + "week", + "month", + "quarter", + "year" +]); +var MetricSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique metric ID"), + label: external_exports.string().describe("Human readable label"), + description: external_exports.string().optional(), + type: AggregationMetricType, + /** Source Calculation */ + sql: external_exports.string().describe("SQL expression or field reference"), + /** Filtering for this specific metric (e.g. "Revenue from Premium Users") */ + filters: external_exports.array(external_exports.object({ + sql: external_exports.string() + })).optional(), + /** Format for display (e.g. "currency", "percent") */ + format: external_exports.string().optional() +}); +var DimensionSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique dimension ID"), + label: external_exports.string().describe("Human readable label"), + description: external_exports.string().optional(), + type: DimensionType, + /** Source Column */ + sql: external_exports.string().describe("SQL expression or column reference"), + /** For Time Dimensions: Supported Granularities */ + granularities: external_exports.array(TimeUpdateInterval).optional() +}); +var CubeJoinSchema = external_exports.object({ + name: external_exports.string().describe("Target cube name"), + relationship: external_exports.enum(["one_to_one", "one_to_many", "many_to_one"]).default("many_to_one"), + sql: external_exports.string().describe("Join condition (ON clause)") +}); +var CubeSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Cube name (snake_case)"), + title: external_exports.string().optional(), + description: external_exports.string().optional(), + /** Physical Data Source */ + sql: external_exports.string().describe("Base SQL statement or Table Name"), + /** Semantic Definitions */ + measures: external_exports.record(external_exports.string(), MetricSchema).describe("Quantitative metrics"), + dimensions: external_exports.record(external_exports.string(), DimensionSchema).describe("Qualitative attributes"), + /** Relationships */ + joins: external_exports.record(external_exports.string(), CubeJoinSchema).optional(), + /** Pre-aggregations / Caching */ + refreshKey: external_exports.object({ + every: external_exports.string().optional(), + // e.g. "1 hour" + sql: external_exports.string().optional() + // SQL to check for data changes + }).optional(), + /** Access Control */ + public: external_exports.boolean().default(false) +}); +var AnalyticsQuerySchema = external_exports.object({ + cube: external_exports.string().optional().describe("Target cube name (optional when provided externally, e.g. in API request wrapper)"), + measures: external_exports.array(external_exports.string()).describe("List of metrics to calculate"), + dimensions: external_exports.array(external_exports.string()).optional().describe("List of dimensions to group by"), + filters: external_exports.array(external_exports.object({ + member: external_exports.string().describe("Dimension or Measure"), + operator: external_exports.enum(["equals", "notEquals", "contains", "notContains", "gt", "gte", "lt", "lte", "set", "notSet", "inDateRange"]), + values: external_exports.array(external_exports.string()).optional() + })).optional(), + timeDimensions: external_exports.array(external_exports.object({ + dimension: external_exports.string(), + granularity: TimeUpdateInterval.optional(), + dateRange: external_exports.union([ + external_exports.string(), + // "Last 7 days" + external_exports.array(external_exports.string()) + // ["2023-01-01", "2023-01-31"] + ]).optional() + })).optional(), + order: external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])).optional(), + limit: external_exports.number().optional(), + offset: external_exports.number().optional(), + timezone: external_exports.string().optional().default("UTC") +}); +var AnalyticsEndpoint = external_exports.enum([ + "/api/v1/analytics/query", + // Execute analysis + "/api/v1/analytics/meta", + // Discover cubes/metrics + "/api/v1/analytics/sql" + // Dry-run SQL generation +]); +var AnalyticsQueryRequestSchema = external_exports.object({ + query: AnalyticsQuerySchema.describe("The analytic query definition"), + cube: external_exports.string().describe("Target cube name"), + format: external_exports.enum(["json", "csv", "xlsx"]).default("json").describe("Response format") +}); +var AnalyticsResultResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + rows: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Result rows"), + fields: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string() + })).describe("Column metadata"), + sql: external_exports.string().optional().describe("Executed SQL (if debug enabled)") + }) +}); +var GetAnalyticsMetaRequestSchema = external_exports.object({ + cube: external_exports.string().optional().describe("Optional cube name to filter") +}); +var AnalyticsMetadataResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + cubes: external_exports.array(CubeSchema).describe("Available cubes") + }) +}); +var AnalyticsSqlResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + sql: external_exports.string(), + params: external_exports.array(external_exports.unknown()) + }) +}); +var VersioningStrategy = external_exports.enum([ + "urlPath", + "header", + "queryParam", + "dateBased" +]); +var VersionStatus = external_exports.enum([ + "preview", + "current", + "supported", + "deprecated", + "retired" +]); +var VersionDefinitionSchema = external_exports.object({ + /** Version identifier (e.g., "v1", "v2beta1", "2025-01-01") */ + version: external_exports.string().describe('Version identifier (e.g., "v1", "v2beta1", "2025-01-01")'), + /** Current lifecycle status */ + status: VersionStatus.describe("Lifecycle status of this version"), + /** Date this version was released (ISO 8601 date) */ + releasedAt: external_exports.string().describe('Release date (ISO 8601, e.g., "2025-01-15")'), + /** Date this version was deprecated (ISO 8601 date) */ + deprecatedAt: external_exports.string().optional().describe("Deprecation date (ISO 8601). Only set for deprecated/retired versions"), + /** Date this version will be retired (ISO 8601 date) */ + sunsetAt: external_exports.string().optional().describe("Sunset date (ISO 8601). After this date, the version returns 410 Gone"), + /** URL to migration guide for moving to a newer version */ + migrationGuide: external_exports.string().url().optional().describe("URL to migration guide for upgrading from this version"), + /** Human-readable description of this version */ + description: external_exports.string().optional().describe("Human-readable description or release notes summary"), + /** Breaking changes introduced in or since this version */ + breakingChanges: external_exports.array(external_exports.string()).optional().describe("List of breaking changes (for preview/new versions)") +}); +var VersioningConfigSchema2 = external_exports.object({ + /** Versioning strategy */ + strategy: VersioningStrategy.default("urlPath").describe("How the API version is specified by clients"), + /** Current (recommended) API version */ + current: external_exports.string().describe("The current/recommended API version identifier"), + /** Default version when none specified by client */ + default: external_exports.string().describe("Fallback version when client does not specify one"), + /** All available API versions */ + versions: external_exports.array(VersionDefinitionSchema).min(1).describe("All available API versions with lifecycle metadata"), + /** Header name for header-based versioning */ + headerName: external_exports.string().default("ObjectStack-Version").describe("HTTP header name for version negotiation (header/dateBased strategies)"), + /** Query parameter name for queryParam strategy */ + queryParamName: external_exports.string().default("version").describe("Query parameter name for version specification (queryParam strategy)"), + /** URL prefix pattern for urlPath strategy */ + urlPrefix: external_exports.string().default("/api").describe("URL prefix before version segment (urlPath strategy)"), + /** Deprecation behavior */ + deprecation: external_exports.object({ + /** Include Deprecation header in responses for deprecated versions */ + warnHeader: external_exports.boolean().default(true).describe("Include Deprecation header (RFC 8594) in responses"), + /** Include Sunset header with retirement date */ + sunsetHeader: external_exports.boolean().default(true).describe("Include Sunset header (RFC 8594) with retirement date"), + /** Include Link header pointing to migration guide */ + linkHeader: external_exports.boolean().default(true).describe("Include Link header pointing to migration guide URL"), + /** Whether to reject requests to retired versions */ + rejectRetired: external_exports.boolean().default(true).describe("Return 410 Gone for retired API versions"), + /** Custom deprecation warning message */ + warningMessage: external_exports.string().optional().describe("Custom warning message for deprecated version responses") + }).optional().describe("Deprecation lifecycle behavior"), + /** Whether to include version info in discovery response */ + includeInDiscovery: external_exports.boolean().default(true).describe("Include version information in the API discovery endpoint") +}); +var VersionNegotiationResponseSchema = external_exports.object({ + /** The current/recommended version */ + current: external_exports.string().describe("Current recommended API version"), + /** The version the client requested (if any) */ + requested: external_exports.string().optional().describe("Version requested by the client"), + /** The version actually being used for this request */ + resolved: external_exports.string().describe("Resolved API version for this request"), + /** All supported (non-retired) version identifiers */ + supported: external_exports.array(external_exports.string()).describe("All supported version identifiers"), + /** Deprecated version identifiers (still functional but will be removed) */ + deprecated: external_exports.array(external_exports.string()).optional().describe("Deprecated version identifiers"), + /** Full version definitions (optional, for detailed clients) */ + versions: external_exports.array(VersionDefinitionSchema).optional().describe("Full version definitions with lifecycle metadata") +}); +var AuthProvider = external_exports.enum([ + "local", + "google", + "github", + "microsoft", + "ldap", + "saml" +]); +var SessionUserSchema = external_exports.object({ + id: external_exports.string().describe("User ID"), + email: external_exports.string().email().describe("Email address"), + emailVerified: external_exports.boolean().default(false).describe("Is email verified?"), + name: external_exports.string().describe("Display name"), + image: external_exports.string().optional().describe("Avatar URL"), + username: external_exports.string().optional().describe("Username (optional)"), + roles: external_exports.array(external_exports.string()).optional().default([]).describe("Assigned role IDs"), + tenantId: external_exports.string().optional().describe("Current tenant ID"), + language: external_exports.string().default("en").describe("Preferred language"), + timezone: external_exports.string().optional().describe("Preferred timezone"), + createdAt: external_exports.string().datetime().optional(), + updatedAt: external_exports.string().datetime().optional() +}); +var SessionSchema = external_exports.object({ + id: external_exports.string(), + expiresAt: external_exports.string().datetime(), + token: external_exports.string().optional(), + ipAddress: external_exports.string().optional(), + userAgent: external_exports.string().optional(), + userId: external_exports.string() +}); +var LoginType = external_exports.enum(["email", "username", "phone", "magic-link", "social"]); +var LoginRequestSchema = external_exports.object({ + type: LoginType.default("email").describe("Login method"), + email: external_exports.string().email().optional().describe("Required for email/magic-link"), + username: external_exports.string().optional().describe("Required for username login"), + password: external_exports.string().optional().describe("Required for password login"), + provider: external_exports.string().optional().describe("Required for social (google, github)"), + redirectTo: external_exports.string().optional().describe("Redirect URL after successful login") +}); +var RegisterRequestSchema = external_exports.object({ + email: external_exports.string().email(), + password: external_exports.string(), + name: external_exports.string(), + image: external_exports.string().optional() +}); +var RefreshTokenRequestSchema = external_exports.object({ + refreshToken: external_exports.string().describe("Refresh token") +}); +var SessionResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + session: SessionSchema.describe("Active Session Info"), + user: SessionUserSchema.describe("Current User Details"), + token: external_exports.string().optional().describe("Bearer token if not using cookies") + }) +}); +var UserProfileResponseSchema = BaseResponseSchema.extend({ + data: SessionUserSchema +}); +var AuthEndpointPaths = { + // Email/Password Authentication + signInEmail: "/sign-in/email", + signUpEmail: "/sign-up/email", + signOut: "/sign-out", + // Session Management + getSession: "/get-session", + // Password Management + forgetPassword: "/forget-password", + resetPassword: "/reset-password", + // Email Verification + sendVerificationEmail: "/send-verification-email", + verifyEmail: "/verify-email", + // OAuth (dynamic based on provider) + // authorize: '/authorize/:provider' + // callback: '/callback/:provider' + // 2FA (when enabled) + twoFactorEnable: "/two-factor/enable", + twoFactorVerify: "/two-factor/verify", + // Passkeys (when enabled) + passkeyRegister: "/passkey/register", + passkeyAuthenticate: "/passkey/authenticate", + // Magic Links (when enabled) + magicLinkSend: "/magic-link/send", + magicLinkVerify: "/magic-link/verify" +}; +var AuthEndpointSchema = external_exports.object({ + /** Sign in with email and password */ + signInEmail: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths.signInEmail), + description: external_exports.literal("Sign in with email and password") + }), + /** Register new user with email and password */ + signUpEmail: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths.signUpEmail), + description: external_exports.literal("Register new user with email and password") + }), + /** Sign out current user */ + signOut: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths.signOut), + description: external_exports.literal("Sign out current user") + }), + /** Get current user session */ + getSession: external_exports.object({ + method: external_exports.literal("GET"), + path: external_exports.literal(AuthEndpointPaths.getSession), + description: external_exports.literal("Get current user session") + }), + /** Request password reset email */ + forgetPassword: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths.forgetPassword), + description: external_exports.literal("Request password reset email") + }), + /** Reset password with token */ + resetPassword: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths.resetPassword), + description: external_exports.literal("Reset password with token") + }), + /** Send email verification */ + sendVerificationEmail: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths.sendVerificationEmail), + description: external_exports.literal("Send email verification link") + }), + /** Verify email with token */ + verifyEmail: external_exports.object({ + method: external_exports.literal("GET"), + path: external_exports.literal(AuthEndpointPaths.verifyEmail), + description: external_exports.literal("Verify email with token") + }) +}); +var AuthEndpointAliases = { + login: AuthEndpointPaths.signInEmail, + register: AuthEndpointPaths.signUpEmail, + logout: AuthEndpointPaths.signOut, + me: AuthEndpointPaths.getSession +}; +var EndpointMapping = { + "/login": AuthEndpointPaths.signInEmail, + "/register": AuthEndpointPaths.signUpEmail, + "/logout": AuthEndpointPaths.signOut, + "/me": AuthEndpointPaths.getSession, + "/refresh": AuthEndpointPaths.getSession + // Session refresh handled by better-auth automatically +}; +var StorageScopeSchema2 = external_exports.enum([ + "global", + // Global application-wide storage + "tenant", + // Tenant-scoped storage (multi-tenant apps) + "user", + // User-scoped storage + "session", + // Session-scoped storage (ephemeral) + "temp", + // Ephemeral, cleared on restart + "cache", + // Ephemeral, survives restarts, cleared on LRU/Expiration + "data", + // Persistent, backed up + "logs", + // Append-only, rotated + "config", + // Read-heavy, versioned + "public" + // Publicly accessible static assets +]).describe("Storage scope classification"); +var FileMetadataSchema2 = external_exports.object({ + path: external_exports.string().describe("File path"), + name: external_exports.string().describe("File name"), + size: external_exports.number().int().describe("File size in bytes"), + mimeType: external_exports.string().describe("MIME type"), + lastModified: external_exports.string().datetime().describe("Last modified timestamp"), + created: external_exports.string().datetime().describe("Creation timestamp"), + etag: external_exports.string().optional().describe("Entity tag") +}); +var StorageProviderSchema2 = external_exports.enum([ + "s3", + // Amazon S3 + "azure_blob", + // Azure Blob Storage + "gcs", + // Google Cloud Storage + "minio", + // MinIO (self-hosted S3-compatible) + "r2", + // Cloudflare R2 + "spaces", + // DigitalOcean Spaces + "wasabi", + // Wasabi Hot Cloud Storage + "backblaze", + // Backblaze B2 + "local" + // Local filesystem (development only) +]).describe("Storage provider type"); +var StorageAclSchema2 = external_exports.enum([ + "private", + // Owner has full control, no one else has access + "public_read", + // Owner has full control, everyone can read + "public_read_write", + // Owner has full control, everyone can read/write (not recommended) + "authenticated_read", + // Owner has full control, authenticated users can read + "bucket_owner_read", + // Object owner has full control, bucket owner can read + "bucket_owner_full_control" + // Both object and bucket owner have full control +]).describe("Storage access control level"); +var StorageClassSchema2 = external_exports.enum([ + "standard", + // Standard/hot storage for frequently accessed data + "intelligent", + // Intelligent tiering (auto-moves between hot/cool) + "infrequent_access", + // Infrequent access/cool storage + "glacier", + // Archive/cold storage (slower retrieval) + "deep_archive" + // Deep archive (cheapest, slowest retrieval) +]).describe("Storage class/tier for cost optimization"); +var LifecycleActionSchema2 = external_exports.enum([ + "transition", + // Move to different storage class + "delete", + // Delete the object + "abort" + // Abort incomplete multipart uploads +]).describe("Lifecycle policy action type"); +external_exports.object({ + contentType: external_exports.string().describe("MIME type (e.g., image/jpeg, application/pdf)"), + contentLength: external_exports.number().min(0).describe("File size in bytes"), + contentEncoding: external_exports.string().optional().describe("Content encoding (e.g., gzip)"), + contentDisposition: external_exports.string().optional().describe("Content disposition header"), + contentLanguage: external_exports.string().optional().describe("Content language"), + cacheControl: external_exports.string().optional().describe("Cache control directives"), + etag: external_exports.string().optional().describe("Entity tag for versioning/caching"), + lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), + versionId: external_exports.string().optional().describe("Object version identifier"), + storageClass: StorageClassSchema2.optional().describe("Storage class/tier"), + encryption: external_exports.object({ + algorithm: external_exports.string().describe("Encryption algorithm (e.g., AES256, aws:kms)"), + keyId: external_exports.string().optional().describe("KMS key ID if using managed encryption") + }).optional().describe("Server-side encryption configuration"), + custom: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom user-defined metadata") +}); +external_exports.object({ + operation: external_exports.enum(["get", "put", "delete", "head"]).describe("Allowed operation"), + expiresIn: external_exports.number().min(1).max(604800).describe("Expiration time in seconds (max 7 days)"), + contentType: external_exports.string().optional().describe("Required content type for PUT operations"), + maxSize: external_exports.number().min(0).optional().describe("Maximum file size in bytes for PUT operations"), + responseContentType: external_exports.string().optional().describe("Override content-type for GET operations"), + responseContentDisposition: external_exports.string().optional().describe("Override content-disposition for GET operations") +}); +var MultipartUploadConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable multipart uploads"), + partSize: external_exports.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe("Part size in bytes (min 5MB, max 5GB)"), + maxParts: external_exports.number().min(1).max(1e4).default(1e4).describe("Maximum number of parts (max 10,000)"), + threshold: external_exports.number().min(0).default(100 * 1024 * 1024).describe("File size threshold to trigger multipart upload (bytes)"), + maxConcurrent: external_exports.number().min(1).max(100).default(4).describe("Maximum concurrent part uploads"), + abortIncompleteAfterDays: external_exports.number().min(1).optional().describe("Auto-abort incomplete uploads after N days") +}); +var AccessControlConfigSchema2 = external_exports.object({ + acl: StorageAclSchema2.default("private").describe("Default access control level"), + allowedOrigins: external_exports.array(external_exports.string()).optional().describe("CORS allowed origins"), + allowedMethods: external_exports.array(external_exports.enum(["GET", "PUT", "POST", "DELETE", "HEAD"])).optional().describe("CORS allowed HTTP methods"), + allowedHeaders: external_exports.array(external_exports.string()).optional().describe("CORS allowed headers"), + exposeHeaders: external_exports.array(external_exports.string()).optional().describe("CORS exposed headers"), + maxAge: external_exports.number().min(0).optional().describe("CORS preflight cache duration in seconds"), + corsEnabled: external_exports.boolean().default(false).describe("Enable CORS configuration"), + publicAccess: external_exports.object({ + allowPublicRead: external_exports.boolean().default(false).describe("Allow public read access"), + allowPublicWrite: external_exports.boolean().default(false).describe("Allow public write access"), + allowPublicList: external_exports.boolean().default(false).describe("Allow public bucket listing") + }).optional().describe("Public access control"), + allowedIps: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses/CIDR blocks"), + blockedIps: external_exports.array(external_exports.string()).optional().describe("Blocked IP addresses/CIDR blocks") +}); +var LifecyclePolicyRuleSchema2 = external_exports.object({ + id: SystemIdentifierSchema2.describe("Rule identifier"), + enabled: external_exports.boolean().default(true).describe("Enable this rule"), + action: LifecycleActionSchema2.describe("Action to perform"), + prefix: external_exports.string().optional().describe('Object key prefix filter (e.g., "uploads/")'), + tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Object tag filters"), + daysAfterCreation: external_exports.number().min(0).optional().describe("Days after object creation"), + daysAfterModification: external_exports.number().min(0).optional().describe("Days after last modification"), + targetStorageClass: StorageClassSchema2.optional().describe("Target storage class for transition action") +}).refine((data) => { + if (data.action === "transition" && !data.targetStorageClass) { + return false; + } + return true; +}, { + message: 'targetStorageClass is required when action is "transition"' +}); +var LifecyclePolicyConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable lifecycle policies"), + rules: external_exports.array(LifecyclePolicyRuleSchema2).default([]).describe("Lifecycle rules") +}); +var BucketConfigSchema2 = external_exports.object({ + name: SystemIdentifierSchema2.describe("Bucket identifier in ObjectStack (snake_case)"), + label: external_exports.string().describe("Display label"), + bucketName: external_exports.string().describe("Actual bucket/container name in storage provider"), + region: external_exports.string().optional().describe("Storage region (e.g., us-east-1, westus)"), + provider: StorageProviderSchema2.describe("Storage provider"), + endpoint: external_exports.string().optional().describe("Custom endpoint URL (for S3-compatible providers)"), + pathStyle: external_exports.boolean().default(false).describe("Use path-style URLs (for S3-compatible providers)"), + versioning: external_exports.boolean().default(false).describe("Enable object versioning"), + encryption: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable server-side encryption"), + algorithm: external_exports.enum(["AES256", "aws:kms", "azure:kms", "gcp:kms"]).default("AES256").describe("Encryption algorithm"), + kmsKeyId: external_exports.string().optional().describe("KMS key ID for managed encryption") + }).optional().describe("Server-side encryption configuration"), + accessControl: AccessControlConfigSchema2.optional().describe("Access control configuration"), + lifecyclePolicy: LifecyclePolicyConfigSchema2.optional().describe("Lifecycle policy configuration"), + multipartConfig: MultipartUploadConfigSchema2.optional().describe("Multipart upload configuration"), + tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Bucket tags for organization"), + description: external_exports.string().optional().describe("Bucket description"), + enabled: external_exports.boolean().default(true).describe("Enable this bucket") +}); +var StorageConnectionSchema2 = external_exports.object({ + // AWS S3 / MinIO + accessKeyId: external_exports.string().optional().describe("AWS access key ID or MinIO access key"), + secretAccessKey: external_exports.string().optional().describe("AWS secret access key or MinIO secret key"), + sessionToken: external_exports.string().optional().describe("AWS session token for temporary credentials"), + // Azure Blob Storage + accountName: external_exports.string().optional().describe("Azure storage account name"), + accountKey: external_exports.string().optional().describe("Azure storage account key"), + sasToken: external_exports.string().optional().describe("Azure SAS token"), + // Google Cloud Storage + projectId: external_exports.string().optional().describe("GCP project ID"), + credentials: external_exports.string().optional().describe("GCP service account credentials JSON"), + // Common + endpoint: external_exports.string().optional().describe("Custom endpoint URL"), + region: external_exports.string().optional().describe("Default region"), + useSSL: external_exports.boolean().default(true).describe("Use SSL/TLS for connections"), + timeout: external_exports.number().min(0).optional().describe("Connection timeout in milliseconds") +}); +var ObjectStorageConfigSchema2 = external_exports.object({ + name: SystemIdentifierSchema2.describe("Storage configuration identifier"), + label: external_exports.string().describe("Display label"), + provider: StorageProviderSchema2.describe("Primary storage provider"), + /** + * Storage scope + * Defines the lifecycle and access pattern for this storage + */ + scope: StorageScopeSchema2.optional().default("global").describe("Storage scope"), + connection: StorageConnectionSchema2.describe("Connection credentials"), + buckets: external_exports.array(BucketConfigSchema2).default([]).describe("Configured buckets"), + defaultBucket: external_exports.string().optional().describe("Default bucket name for operations"), + /** + * Base path or location + * For local/scoped storage configurations + */ + location: external_exports.string().optional().describe("Root path (local) or base location"), + /** + * Storage quota in bytes + */ + quota: external_exports.number().int().positive().optional().describe("Max size in bytes"), + /** + * Provider-specific options + */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration options"), + enabled: external_exports.boolean().default(true).describe("Enable this storage configuration"), + description: external_exports.string().optional().describe("Configuration description") +}); +ObjectStorageConfigSchema2.parse({ + name: "aws_s3_storage", + label: "AWS S3 Production Storage", + provider: "s3", + connection: { + accessKeyId: "${AWS_ACCESS_KEY_ID}", + secretAccessKey: "${AWS_SECRET_ACCESS_KEY}", + region: "us-east-1" + }, + buckets: [ + { + name: "user_uploads", + label: "User Uploads", + bucketName: "my-app-user-uploads", + region: "us-east-1", + provider: "s3", + versioning: true, + encryption: { + enabled: true, + algorithm: "aws:kms", + kmsKeyId: "${AWS_KMS_KEY_ID}" + }, + accessControl: { + acl: "private", + corsEnabled: true, + allowedOrigins: ["https://app.example.com"], + allowedMethods: ["GET", "PUT", "POST"] + }, + lifecyclePolicy: { + enabled: true, + rules: [ + { + id: "archive_old_uploads", + enabled: true, + action: "transition", + daysAfterCreation: 90, + targetStorageClass: "glacier" + } + ] + }, + multipartConfig: { + enabled: true, + partSize: 10 * 1024 * 1024, + threshold: 100 * 1024 * 1024, + maxConcurrent: 4 + } + } + ], + defaultBucket: "user_uploads", + enabled: true +}); +ObjectStorageConfigSchema2.parse({ + name: "minio_local", + label: "MinIO Local Storage", + provider: "minio", + connection: { + accessKeyId: "minioadmin", + secretAccessKey: "minioadmin", + endpoint: "http://localhost:9000", + useSSL: false + }, + buckets: [ + { + name: "development_files", + label: "Development Files", + bucketName: "dev-files", + provider: "minio", + endpoint: "http://localhost:9000", + pathStyle: true, + accessControl: { + acl: "private" + } + } + ], + defaultBucket: "development_files", + enabled: true +}); +ObjectStorageConfigSchema2.parse({ + name: "azure_blob_storage", + label: "Azure Blob Storage", + provider: "azure_blob", + connection: { + accountName: "mystorageaccount", + accountKey: "${AZURE_STORAGE_KEY}", + endpoint: "https://mystorageaccount.blob.core.windows.net" + }, + buckets: [ + { + name: "media_files", + label: "Media Files", + bucketName: "media", + provider: "azure_blob", + region: "eastus", + accessControl: { + acl: "public_read", + publicAccess: { + allowPublicRead: true, + allowPublicWrite: false, + allowPublicList: false + } + } + } + ], + defaultBucket: "media_files", + enabled: true +}); +ObjectStorageConfigSchema2.parse({ + name: "gcs_storage", + label: "Google Cloud Storage", + provider: "gcs", + connection: { + projectId: "my-gcp-project", + credentials: "${GCP_SERVICE_ACCOUNT_JSON}" + }, + buckets: [ + { + name: "backup_storage", + label: "Backup Storage", + bucketName: "my-app-backups", + region: "us-central1", + provider: "gcs", + lifecyclePolicy: { + enabled: true, + rules: [ + { + id: "delete_old_backups", + enabled: true, + action: "delete", + daysAfterCreation: 30 + } + ] + } + } + ], + defaultBucket: "backup_storage", + enabled: true +}); +var GetPresignedUrlRequestSchema = external_exports.object({ + filename: external_exports.string().describe("Original filename"), + mimeType: external_exports.string().describe("File MIME type"), + size: external_exports.number().describe("File size in bytes"), + scope: external_exports.string().default("user").describe("Target storage scope (e.g. user, private, public)"), + bucket: external_exports.string().optional().describe("Specific bucket override (admin only)") +}); +var CompleteUploadRequestSchema = external_exports.object({ + fileId: external_exports.string().describe("File ID returned from presigned request"), + eTag: external_exports.string().optional().describe("S3 ETag verification") +}); +var PresignedUrlResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + uploadUrl: external_exports.string().describe("PUT/POST URL for direct upload"), + downloadUrl: external_exports.string().optional().describe("Public/Private preview URL"), + fileId: external_exports.string().describe("Temporary File ID"), + method: external_exports.enum(["PUT", "POST"]).describe("HTTP Method to use"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Required headers for upload"), + expiresIn: external_exports.number().describe("URL expiry in seconds") + }) +}); +var FileUploadResponseSchema = BaseResponseSchema.extend({ + data: FileMetadataSchema2.describe("Uploaded file metadata") +}); +var FileTypeValidationSchema = external_exports.object({ + mode: external_exports.enum(["whitelist", "blacklist"]).describe("whitelist = only allow listed types, blacklist = block listed types"), + mimeTypes: external_exports.array(external_exports.string()).min(1).describe('List of MIME types to allow or block (e.g., "image/jpeg", "application/pdf")'), + extensions: external_exports.array(external_exports.string()).optional().describe('List of file extensions to allow or block (e.g., ".jpg", ".pdf")'), + maxFileSize: external_exports.number().int().min(1).optional().describe("Maximum file size in bytes"), + minFileSize: external_exports.number().int().min(0).optional().describe("Minimum file size in bytes (e.g., reject empty files)") +}); +var InitiateChunkedUploadRequestSchema = external_exports.object({ + filename: external_exports.string().describe("Original filename"), + mimeType: external_exports.string().describe("File MIME type"), + totalSize: external_exports.number().int().min(1).describe("Total file size in bytes"), + chunkSize: external_exports.number().int().min(5242880).default(5242880).describe("Size of each chunk in bytes (minimum 5MB per S3 spec)"), + scope: external_exports.string().default("user").describe("Target storage scope"), + bucket: external_exports.string().optional().describe("Specific bucket override (admin only)"), + metadata: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom metadata key-value pairs") +}); +var InitiateChunkedUploadResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + uploadId: external_exports.string().describe("Multipart upload session ID"), + resumeToken: external_exports.string().describe("Opaque token for resuming interrupted uploads"), + fileId: external_exports.string().describe("Assigned file ID"), + totalChunks: external_exports.number().int().min(1).describe("Expected number of chunks"), + chunkSize: external_exports.number().int().describe("Chunk size in bytes"), + expiresAt: external_exports.string().datetime().describe("Upload session expiration timestamp") + }) +}); +var UploadChunkRequestSchema = external_exports.object({ + uploadId: external_exports.string().describe("Multipart upload session ID"), + chunkIndex: external_exports.number().int().min(0).describe("Zero-based chunk index"), + resumeToken: external_exports.string().describe("Resume token from initiate response") +}); +var UploadChunkResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + chunkIndex: external_exports.number().int().describe("Chunk index that was uploaded"), + eTag: external_exports.string().describe("Chunk ETag for multipart completion"), + bytesReceived: external_exports.number().int().describe("Bytes received for this chunk") + }) +}); +var CompleteChunkedUploadRequestSchema = external_exports.object({ + uploadId: external_exports.string().describe("Multipart upload session ID"), + parts: external_exports.array(external_exports.object({ + chunkIndex: external_exports.number().int().describe("Chunk index"), + eTag: external_exports.string().describe("ETag returned from chunk upload") + })).min(1).describe("Ordered list of uploaded parts for assembly") +}); +var CompleteChunkedUploadResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + fileId: external_exports.string().describe("Final file ID"), + key: external_exports.string().describe("Storage key/path of the assembled file"), + size: external_exports.number().int().describe("Total file size in bytes"), + mimeType: external_exports.string().describe("File MIME type"), + eTag: external_exports.string().optional().describe("Final ETag of the assembled file"), + url: external_exports.string().optional().describe("Download URL for the assembled file") + }) +}); +var UploadProgressSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + uploadId: external_exports.string().describe("Multipart upload session ID"), + fileId: external_exports.string().describe("Assigned file ID"), + filename: external_exports.string().describe("Original filename"), + totalSize: external_exports.number().int().describe("Total file size in bytes"), + uploadedSize: external_exports.number().int().describe("Bytes uploaded so far"), + totalChunks: external_exports.number().int().describe("Total expected chunks"), + uploadedChunks: external_exports.number().int().describe("Number of chunks uploaded"), + percentComplete: external_exports.number().min(0).max(100).describe("Upload progress percentage"), + status: external_exports.enum(["in_progress", "completing", "completed", "failed", "expired"]).describe("Current upload session status"), + startedAt: external_exports.string().datetime().describe("Upload session start timestamp"), + expiresAt: external_exports.string().datetime().describe("Session expiration timestamp") + }) +}); +var EncryptionAlgorithmSchema2 = external_exports.enum([ + "aes-256-gcm", + "aes-256-cbc", + "chacha20-poly1305" +]).describe("Supported encryption algorithm"); +var KeyManagementProviderSchema2 = external_exports.enum([ + "local", + "aws-kms", + "azure-key-vault", + "gcp-kms", + "hashicorp-vault" +]).describe("Key management service provider"); +var KeyRotationPolicySchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), + frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), + retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), + autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") +}).describe("Policy for automatic encryption key rotation"); +var EncryptionConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), + algorithm: EncryptionAlgorithmSchema2.default("aes-256-gcm").describe("Encryption algorithm"), + keyManagement: external_exports.object({ + provider: KeyManagementProviderSchema2.describe("Key management service provider"), + keyId: external_exports.string().optional().describe("Key identifier in the provider"), + rotationPolicy: KeyRotationPolicySchema2.optional().describe("Key rotation policy") + }).describe("Key management configuration"), + scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), + deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), + searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") +}).describe("Field-level encryption configuration"); +external_exports.object({ + fieldName: external_exports.string().describe("Name of the field to encrypt"), + encryptionConfig: EncryptionConfigSchema2.describe("Encryption settings for this field"), + indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") +}).describe("Per-field encryption assignment"); +var MaskingStrategySchema2 = external_exports.enum([ + "redact", + // Complete redaction: **** + "partial", + // Partial masking: 138****5678 + "hash", + // Hash value: sha256(value) + "tokenize", + // Tokenization: token-12345 + "randomize", + // Randomize: generate random value + "nullify", + // Null value: null + "substitute" + // Substitute with dummy data +]).describe("Data masking strategy for PII protection"); +var MaskingRuleSchema2 = external_exports.object({ + field: external_exports.string().describe("Field name to apply masking to"), + strategy: MaskingStrategySchema2.describe("Masking strategy to use"), + pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), + preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), + preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), + roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), + exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") +}).describe("Masking rule for a single field"); +external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable data masking"), + rules: external_exports.array(MaskingRuleSchema2).describe("List of field-level masking rules"), + auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") +}).describe("Top-level data masking configuration for PII protection"); +var FieldType2 = external_exports.enum([ + // Core Text + "text", + "textarea", + "email", + "url", + "phone", + "password", + // Rich Content + "markdown", + "html", + "richtext", + // Numbers + "number", + "currency", + "percent", + // Date & Time + "date", + "datetime", + "time", + // Logic + "boolean", + "toggle", + // Toggle is a distinct UI from checkbox + // Selection + "select", + // Single select dropdown + "multiselect", + // Multi select (often tags) + "radio", + // Radio group + "checkboxes", + // Checkbox group + // Relational + "lookup", + "master_detail", + // Dynamic reference + "tree", + // Hierarchical reference + // Media + "image", + "file", + "avatar", + "video", + "audio", + // Calculated / System + "formula", + "summary", + "autonumber", + // Enhanced Types + "location", + // GPS coordinates + "address", + // Structured address + "code", + // Code editor (JSON/SQL/JS) + "json", + // Structured JSON data + "color", + // Color picker + "rating", + // Star rating + "slider", + // Numeric slider + "signature", + // Digital signature + "qrcode", + // QR code / Barcode + "progress", + // Progress bar + "tags", + // Simple tag list + // AI/ML Types + "vector" + // Vector embeddings for AI/ML (semantic search, RAG) +]); +var SelectOptionSchema2 = external_exports.object({ + label: external_exports.string().describe("Display label (human-readable, any case allowed)"), + value: SystemIdentifierSchema2.describe("Stored value (lowercase machine identifier)"), + color: external_exports.string().optional().describe("Color code for badges/charts"), + default: external_exports.boolean().optional().describe("Is default option") +}); +external_exports.object({ + latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), + longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), + altitude: external_exports.number().optional().describe("Altitude in meters"), + accuracy: external_exports.number().optional().describe("Accuracy in meters") +}); +var CurrencyConfigSchema2 = external_exports.object({ + precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), + currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), + defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") +}); +external_exports.object({ + value: external_exports.number().describe("Monetary amount"), + currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") +}); +external_exports.object({ + street: external_exports.string().optional().describe("Street address"), + city: external_exports.string().optional().describe("City name"), + state: external_exports.string().optional().describe("State/Province"), + postalCode: external_exports.string().optional().describe("Postal/ZIP code"), + country: external_exports.string().optional().describe("Country name or code"), + countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), + formatted: external_exports.string().optional().describe("Formatted address string") +}); +var VectorConfigSchema2 = external_exports.object({ + dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), + distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), + normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), + indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), + indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") +}); +var FileAttachmentConfigSchema2 = external_exports.object({ + /** File Size Limits */ + minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), + maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), + /** File Type Restrictions */ + allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), + blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), + allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), + blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), + /** Virus Scanning */ + virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), + virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), + virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), + quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), + /** Storage Configuration */ + storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), + storageBucket: external_exports.string().optional().describe("Target bucket name"), + storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), + /** Image-Specific Validation */ + imageValidation: external_exports.object({ + minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), + maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), + minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), + maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), + aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), + generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), + thumbnailSizes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), + width: external_exports.number().min(1).describe("Thumbnail width in pixels"), + height: external_exports.number().min(1).describe("Thumbnail height in pixels"), + crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") + })).optional().describe("Thumbnail size configurations"), + preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), + autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") + }).optional().describe("Image-specific validation rules"), + /** Upload Behavior */ + allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), + allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), + allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), + requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), + /** Metadata Extraction */ + extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), + extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), + /** Versioning */ + versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), + maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), + /** Access Control */ + publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), + presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") +}).refine((data) => { + if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { + return false; + } + return true; +}, { + message: "minSize must be less than or equal to maxSize" +}).refine((data) => { + if (data.virusScanProvider !== void 0 && data.virusScan !== true) { + return false; + } + return true; +}, { + message: "virusScanProvider requires virusScan to be enabled" +}); +var DataQualityRulesSchema2 = external_exports.object({ + /** Enforce uniqueness constraint */ + uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), + /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ + completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), + /** Accuracy validation against authoritative source */ + accuracy: external_exports.object({ + source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), + threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") + }).optional().describe("Accuracy validation configuration") +}); +var ComputedFieldCacheSchema2 = external_exports.object({ + /** Enable caching for this computed field */ + enabled: external_exports.boolean().describe("Enable caching for computed field results"), + /** Time-to-live in seconds */ + ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), + /** Array of field paths that trigger cache invalidation when changed */ + invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') +}); +var FieldSchema2 = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), + label: external_exports.string().optional().describe("Human readable label"), + type: FieldType2.describe("Field Data Type"), + description: external_exports.string().optional().describe("Tooltip/Help text"), + format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), + /** Storage Layer Mapping */ + columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), + /** Database Constraints */ + required: external_exports.boolean().default(false).describe("Is required"), + searchable: external_exports.boolean().default(false).describe("Is searchable"), + multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), + unique: external_exports.boolean().default(false).describe("Is unique constraint"), + defaultValue: external_exports.unknown().optional().describe("Default value"), + /** Text/String Constraints */ + maxLength: external_exports.number().optional().describe("Max character length"), + minLength: external_exports.number().optional().describe("Min character length"), + /** Number Constraints */ + precision: external_exports.number().optional().describe("Total digits"), + scale: external_exports.number().optional().describe("Decimal places"), + min: external_exports.number().optional().describe("Minimum value"), + max: external_exports.number().optional().describe("Maximum value"), + /** Selection Options */ + options: external_exports.array(SelectOptionSchema2).optional().describe("Static options for select/multiselect"), + /** + * Relationship Config + * + * Used by `lookup` and `master_detail` field types to define cross-object references. + * The `reference` property is **required** for these types — it identifies the target + * object whose records this field links to. The engine uses `reference` during $expand + * post-processing to resolve foreign key IDs into full related objects via batch queries. + * + * For `master_detail` fields, the parent record controls the lifecycle of child records + * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. + */ + reference: external_exports.string().optional().describe( + "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." + ), + referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), + writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), + deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), + /** Calculation */ + expression: external_exports.string().optional().describe("Formula expression"), + summaryOperations: external_exports.object({ + object: external_exports.string().describe("Source child object name for roll-up"), + field: external_exports.string().describe("Field on child object to aggregate"), + function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") + }).optional().describe("Roll-up summary definition"), + /** Enhanced Field Type Configurations */ + // Code field config + language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), + theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), + lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), + // Rating field config + maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), + allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), + // Location field config + displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), + allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), + // Address field config + addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), + // Color field config + colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), + allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), + presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), + // Slider field config + step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), + showValue: external_exports.boolean().optional().describe("Display current value on slider"), + marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), + // QR Code / Barcode field config + // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' + // Runtime validation should enforce this constraint + barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), + qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), + displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), + allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), + // Currency field config + currencyConfig: CurrencyConfigSchema2.optional().describe("Configuration for currency field type"), + // Vector field config + vectorConfig: VectorConfigSchema2.optional().describe("Configuration for vector field type (AI/ML embeddings)"), + // File attachment field config + fileAttachmentConfig: FileAttachmentConfigSchema2.optional().describe("Configuration for file and attachment field types"), + /** Enhanced Security & Compliance */ + // Encryption configuration + encryptionConfig: EncryptionConfigSchema2.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), + // Data masking rules + maskingRule: MaskingRuleSchema2.optional().describe("Data masking rules for PII protection"), + // Audit trail + auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), + /** Field Dependencies & Relationships */ + // Field dependencies + dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), + /** Computed Field Optimization */ + // Computed field caching + cached: ComputedFieldCacheSchema2.optional().describe("Caching configuration for computed/formula fields"), + /** Data Quality & Governance */ + // Data quality rules + dataQuality: DataQualityRulesSchema2.optional().describe("Data quality validation and monitoring rules"), + /** Layout & Grouping */ + group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), + /** Conditional Requirements */ + conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), + /** Security & Visibility */ + hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), + readonly: external_exports.boolean().default(false).describe("Read-only in UI"), + sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), + inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), + trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), + caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), + autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), + /** Indexing */ + index: external_exports.boolean().default(false).describe("Create standard database index"), + externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") +}); +var BaseValidationSchema2 = external_exports.object({ + // Identification + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label for the rule listing"), + description: external_exports.string().optional().describe("Administrative notes explaining the business reason"), + // Execution Control + active: external_exports.boolean().default(true), + events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).default(["insert", "update"]).describe("Validation contexts"), + priority: external_exports.number().int().min(0).max(9999).default(100).describe("Execution priority (lower runs first, default: 100)"), + // Classification + tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g., "compliance", "billing")'), + // Feedback + severity: external_exports.enum(["error", "warning", "info"]).default("error"), + message: external_exports.string().describe("Error message to display to the user") +}); +var ScriptValidationSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("script"), + condition: external_exports.string().describe("Formula expression. If TRUE, validation fails. (e.g. amount < 0)") +}); +var UniquenessValidationSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("unique"), + fields: external_exports.array(external_exports.string()).describe("Fields that must be combined unique"), + scope: external_exports.string().optional().describe("Formula condition for scope (e.g. active = true)"), + caseSensitive: external_exports.boolean().default(true) +}); +var StateMachineValidationSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("state_machine"), + field: external_exports.string().describe("State field (e.g. status)"), + transitions: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).describe("Map of { OldState: [AllowedNewStates] }") +}); +var FormatValidationSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("format"), + field: external_exports.string(), + regex: external_exports.string().optional(), + format: external_exports.enum(["email", "url", "phone", "json"]).optional() +}); +var CrossFieldValidationSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("cross_field"), + condition: external_exports.string().describe('Formula expression comparing fields (e.g. "end_date > start_date")'), + fields: external_exports.array(external_exports.string()).describe("Fields involved in the validation") +}); +var JSONValidationSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("json_schema"), + field: external_exports.string().describe("JSON field to validate"), + schema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema object definition") +}); +var AsyncValidationSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("async"), + field: external_exports.string().describe("Field to validate"), + validatorUrl: external_exports.string().optional().describe("External API endpoint for validation"), + method: external_exports.enum(["GET", "POST"]).default("GET").describe("HTTP method for external call"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for the request"), + validatorFunction: external_exports.string().optional().describe("Reference to custom validator function"), + timeout: external_exports.number().optional().default(5e3).describe("Timeout in milliseconds"), + debounce: external_exports.number().optional().describe("Debounce delay in milliseconds"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional parameters to pass to validator") +}); +var CustomValidatorSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("custom"), + handler: external_exports.string().describe("Name of the custom validation function registered in the system"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the custom handler") +}); +var ValidationRuleSchema2 = external_exports.lazy( + () => external_exports.discriminatedUnion("type", [ + ScriptValidationSchema2, + UniquenessValidationSchema2, + StateMachineValidationSchema2, + FormatValidationSchema2, + CrossFieldValidationSchema2, + JSONValidationSchema2, + AsyncValidationSchema2, + CustomValidatorSchema2, + ConditionalValidationSchema2 + ]) +); +var ConditionalValidationSchema2 = BaseValidationSchema2.extend({ + type: external_exports.literal("conditional"), + when: external_exports.string().describe(`Condition formula (e.g. "type = 'enterprise'")`), + then: ValidationRuleSchema2.describe("Validation rule to apply when condition is true"), + otherwise: ValidationRuleSchema2.optional().describe("Validation rule to apply when condition is false") +}); +var ActionRefSchema2 = external_exports.union([ + external_exports.string().describe("Action Name"), + external_exports.object({ + type: external_exports.string(), + // e.g., 'xstate.assign', 'log', 'email' + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }) +]); +var GuardRefSchema2 = external_exports.union([ + external_exports.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'), + external_exports.object({ + type: external_exports.string(), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }) +]); +var TransitionSchema2 = external_exports.object({ + target: external_exports.string().optional().describe("Target State ID"), + cond: GuardRefSchema2.optional().describe("Condition (Guard) required to take this path"), + actions: external_exports.array(ActionRefSchema2).optional().describe("Actions to execute during transition"), + description: external_exports.string().optional().describe("Human readable description of this rule") +}); +external_exports.object({ + type: external_exports.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'), + // Payload validation schema could go here if we want deep validation + schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Expected event payload structure") +}); +var StateNodeSchema2 = external_exports.lazy(() => external_exports.object({ + /** Type of state */ + type: external_exports.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"), + /** Entry/Exit Actions */ + entry: external_exports.array(ActionRefSchema2).optional().describe("Actions to run when entering this state"), + exit: external_exports.array(ActionRefSchema2).optional().describe("Actions to run when leaving this state"), + /** Transitions (Events) */ + on: external_exports.record(external_exports.string(), external_exports.union([ + external_exports.string(), + // Shorthand target + TransitionSchema2, + external_exports.array(TransitionSchema2) + ])).optional().describe("Map of Event Type -> Transition Definition"), + /** Always Transitions (Eventless) */ + always: external_exports.array(TransitionSchema2).optional(), + /** Nesting (Hierarchical States) */ + initial: external_exports.string().optional().describe("Initial child state (if compound)"), + states: external_exports.record(external_exports.string(), StateNodeSchema2).optional(), + /** Metadata for UI/AI */ + meta: external_exports.object({ + label: external_exports.string().optional(), + description: external_exports.string().optional(), + color: external_exports.string().optional(), + // For UI diagrams + // Instructions for AI Agent when in this state + aiInstructions: external_exports.string().optional().describe("Specific instructions for AI when in this state") + }).optional() +})); +var StateMachineSchema2 = external_exports.object({ + id: SnakeCaseIdentifierSchema2.describe("Unique Machine ID"), + description: external_exports.string().optional(), + /** Context (Memory) Schema */ + contextSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Zod Schema for the machine context/memory"), + /** Initial State */ + initial: external_exports.string().describe("Initial State ID"), + /** State Definitions */ + states: external_exports.record(external_exports.string(), StateNodeSchema2).describe("State Nodes"), + /** Global Listeners */ + on: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), TransitionSchema2, external_exports.array(TransitionSchema2)])).optional() +}); +var ActionParamSchema2 = external_exports.object({ + name: external_exports.string(), + label: I18nLabelSchema2, + type: FieldType2, + required: external_exports.boolean().default(false), + options: external_exports.array(external_exports.object({ label: I18nLabelSchema2, value: external_exports.string() })).optional() +}); +var ActionType2 = external_exports.enum(["script", "url", "modal", "flow", "api"]); +var TARGET_REQUIRED_TYPES2 = new Set( + ActionType2.options.filter((t) => t !== "script") +); +var ActionSchema2 = external_exports.object({ + /** Machine name of the action */ + name: SnakeCaseIdentifierSchema2.describe("Machine name (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema2.describe("Display label"), + /** Target object this action belongs to (optional, snake_case) */ + objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Icon name"), + /** Where does this action appear? */ + locations: external_exports.array(external_exports.enum([ + "list_toolbar", + "list_item", + "record_header", + "record_more", + "record_related", + "global_nav" + ])).optional().describe("Locations where this action is visible"), + /** + * Visual Component Type + * Defaults to 'button' or 'menu_item' based on location, + * but can be overridden. + */ + component: external_exports.enum([ + "action:button", + // Standard Button + "action:icon", + // Icon only + "action:menu", + // Dropdown menu + "action:group" + // Button Group + ]).optional().describe("Visual component override"), + /** What type of interaction? */ + type: ActionType2.default("script").describe("Action functionality type"), + /** + * Payload / Target — the canonical binding for the action handler. + * Required for url, flow, modal, and api types. + * Recommended for script type. + */ + target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), + /** + * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. + */ + execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), + /** User Input Requirements */ + params: external_exports.array(ActionParamSchema2).optional().describe("Input parameters required from user"), + /** Visual Style */ + variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), + /** UX Behavior */ + confirmText: I18nLabelSchema2.optional().describe("Confirmation message before execution"), + successMessage: I18nLabelSchema2.optional().describe("Success message to show after execution"), + refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), + /** Access */ + visible: external_exports.string().optional().describe("Formula returning boolean"), + disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), + /** Keyboard Shortcut */ + shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), + /** Bulk Operations */ + bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), + /** Execution */ + timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema2.optional().describe("ARIA accessibility attributes") +}).transform((data) => { + if (data.execute && !data.target) { + return { ...data, target: data.execute }; + } + return data; +}).refine((data) => { + if (TARGET_REQUIRED_TYPES2.has(data.type) && !data.target) { + return false; + } + return true; +}, { + message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", + path: ["target"] +}); +var ApiMethod2 = external_exports.enum([ + "get", + "list", + // Read + "create", + "update", + "delete", + // Write + "upsert", + // Idempotent Write + "bulk", + // Batch operations + "aggregate", + // Analytics (count, sum) + "history", + // Audit access + "search", + // Search access + "restore", + "purge", + // Trash management + "import", + "export" + // Data portability +]); +var ObjectCapabilities2 = external_exports.object({ + /** Enable history tracking (Audit Trail) */ + trackHistory: external_exports.boolean().default(false).describe("Enable field history tracking for audit compliance"), + /** Enable global search indexing */ + searchable: external_exports.boolean().default(true).describe("Index records for global search"), + /** Enable REST/GraphQL API access */ + apiEnabled: external_exports.boolean().default(true).describe("Expose object via automatic APIs"), + /** + * API Supported Operations + * Granular control over API exposure. + */ + apiMethods: external_exports.array(ApiMethod2).optional().describe("Whitelist of allowed API operations"), + /** Enable standard attachments/files engine */ + files: external_exports.boolean().default(false).describe("Enable file attachments and document management"), + /** Enable social collaboration (Comments, Mentions, Feeds) */ + feeds: external_exports.boolean().default(false).describe("Enable social feed, comments, and mentions (Chatter-like)"), + /** Enable standard Activity suite (Tasks, Calendars, Events) */ + activities: external_exports.boolean().default(false).describe("Enable standard tasks and events tracking"), + /** Enable Recycle Bin / Soft Delete */ + trash: external_exports.boolean().default(true).describe("Enable soft-delete with restore capability"), + /** Enable "Recently Viewed" tracking */ + mru: external_exports.boolean().default(true).describe("Track Most Recently Used (MRU) list for users"), + /** Allow cloning records */ + clone: external_exports.boolean().default(true).describe("Allow record deep cloning") +}); +var IndexSchema2 = external_exports.object({ + name: external_exports.string().optional().describe("Index name (auto-generated if not provided)"), + fields: external_exports.array(external_exports.string()).describe("Fields included in the index"), + type: external_exports.enum(["btree", "hash", "gin", "gist", "fulltext"]).optional().default("btree").describe("Index algorithm type"), + unique: external_exports.boolean().optional().default(false).describe("Whether the index enforces uniqueness"), + partial: external_exports.string().optional().describe("Partial index condition (SQL WHERE clause for conditional indexes)") +}); +var SearchConfigSchema3 = external_exports.object({ + fields: external_exports.array(external_exports.string()).describe("Fields to index for full-text search weighting"), + displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display in search result cards"), + filters: external_exports.array(external_exports.string()).optional().describe("Default filters for search results") +}); +var TenancyConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable multi-tenancy for this object"), + strategy: external_exports.enum(["shared", "isolated", "hybrid"]).describe("Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)"), + tenantField: external_exports.string().default("tenant_id").describe("Field name for tenant identifier"), + crossTenantAccess: external_exports.boolean().default(false).describe("Allow cross-tenant data access (with explicit permission)") +}); +var SoftDeleteConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable soft delete (trash/recycle bin)"), + field: external_exports.string().default("deleted_at").describe("Field name for soft delete timestamp"), + cascadeDelete: external_exports.boolean().default(false).describe("Cascade soft delete to related records") +}); +var VersioningConfigSchema22 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable record versioning"), + strategy: external_exports.enum(["snapshot", "delta", "event-sourcing"]).describe("Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)"), + retentionDays: external_exports.number().min(1).optional().describe("Number of days to retain old versions (undefined = infinite)"), + versionField: external_exports.string().default("version").describe("Field name for version number/timestamp") +}); +var PartitioningConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable table partitioning"), + strategy: external_exports.enum(["range", "hash", "list"]).describe("Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)"), + key: external_exports.string().describe("Field name to partition by"), + interval: external_exports.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")') +}).refine((data) => { + if (data.strategy === "range" && !data.interval) { + return false; + } + return true; +}, { + message: 'interval is required when strategy is "range"' +}); +var CDCConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable Change Data Capture"), + events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).describe("Event types to capture"), + destination: external_exports.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")') +}); +var ObjectSchemaBase2 = external_exports.object({ + /** + * Identity & Metadata + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine unique key (snake_case). Immutable."), + label: external_exports.string().optional().describe('Human readable singular label (e.g. "Account")'), + pluralLabel: external_exports.string().optional().describe('Human readable plural label (e.g. "Accounts")'), + description: external_exports.string().optional().describe("Developer documentation / description"), + icon: external_exports.string().optional().describe("Icon name (Lucide/Material) for UI representation"), + /** + * Namespace & Domain Classification + * + * Groups objects into logical domains for routing, permissions, and discovery. + * System objects use `'sys'`; business packages use their own namespace. + * + * When set, `tableName` is auto-derived as `{namespace}_{name}` by + * `ObjectSchema.create()` unless an explicit `tableName` is provided. + * + * Namespace must be a single lowercase word (no underscores or hyphens) + * to ensure clean auto-derivation of `{namespace}_{name}` table names. + * + * @example namespace: 'sys' → tableName defaults to 'sys_user' + * @example namespace: 'crm' → tableName defaults to 'crm_account' + */ + namespace: external_exports.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace \u2014 single lowercase word (e.g. "sys", "crm"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'), + /** + * Taxonomy & Organization + */ + tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'), + active: external_exports.boolean().optional().default(true).describe("Is the object active and usable"), + isSystem: external_exports.boolean().optional().default(false).describe("Is system object (protected from deletion)"), + abstract: external_exports.boolean().optional().default(false).describe("Is abstract base object (cannot be instantiated)"), + /** + * Storage & Virtualization + */ + datasource: external_exports.string().optional().default("default").describe('Target Datasource ID. "default" is the primary DB.'), + tableName: external_exports.string().optional().describe("Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set."), + /** + * Data Model + */ + fields: external_exports.record(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/, { + message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")' + }), FieldSchema2).describe("Field definitions map. Keys must be snake_case identifiers."), + indexes: external_exports.array(IndexSchema2).optional().describe("Database performance indexes"), + /** + * Advanced Data Management + */ + // Multi-tenancy configuration + tenancy: TenancyConfigSchema2.optional().describe("Multi-tenancy configuration for SaaS applications"), + // Soft delete configuration + softDelete: SoftDeleteConfigSchema2.optional().describe("Soft delete (trash/recycle bin) configuration"), + // Versioning configuration + versioning: VersioningConfigSchema22.optional().describe("Record versioning and history tracking configuration"), + // Partitioning strategy + partitioning: PartitioningConfigSchema2.optional().describe("Table partitioning configuration for performance"), + // Change Data Capture + cdc: CDCConfigSchema2.optional().describe("Change Data Capture (CDC) configuration for real-time data streaming"), + /** + * Logic & Validation (Co-located) + * Best Practice: Define rules close to data. + */ + validations: external_exports.array(ValidationRuleSchema2).optional().describe("Object-level validation rules"), + /** + * State Machine(s) + * Named record of state machines, where each key is a unique machine identifier. + * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status). + * + * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} } + */ + stateMachines: external_exports.record(external_exports.string(), StateMachineSchema2).optional().describe("Named state machines for parallel lifecycles (e.g., status, payment, approval)"), + /** + * Display & UI Hints (Data-Layer) + */ + displayNameField: external_exports.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'), + recordName: external_exports.object({ + type: external_exports.enum(["text", "autonumber"]).describe("Record name type: text (user-entered) or autonumber (system-generated)"), + displayFormat: external_exports.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'), + startNumber: external_exports.number().int().min(0).optional().describe("Starting number for autonumber (default: 1)") + }).optional().describe("Record name generation configuration (Salesforce pattern)"), + titleFormat: external_exports.string().optional().describe('Title expression (e.g. "{name} - {code}"). Overrides displayNameField.'), + compactLayout: external_exports.array(external_exports.string()).optional().describe("Primary fields for hover/cards/lookups"), + /** + * Search Engine Config + */ + search: SearchConfigSchema3.optional().describe("Search engine configuration"), + /** + * System Capabilities + */ + enable: ObjectCapabilities2.optional().describe("Enabled system features modules"), + /** Record Types */ + recordTypes: external_exports.array(external_exports.string()).optional().describe("Record type names for this object"), + /** Sharing Model */ + sharingModel: external_exports.enum(["private", "read", "read_write", "full"]).optional().describe("Default sharing model"), + /** Key Prefix */ + keyPrefix: external_exports.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'), + /** + * Object Actions + * + * Actions associated with this object. Populated automatically by `defineStack()` + * when top-level actions specify `objectName` matching this object. + * Can also be defined directly on the object. + * + * Aligns with Salesforce/ServiceNow patterns where actions are part of the + * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`) + * include the action list without requiring downstream merge. + */ + actions: external_exports.array(ActionSchema2).optional().describe("Actions associated with this object (auto-populated from top-level actions via objectName)") +}); +function snakeCaseToLabel2(name) { + return name.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); +} +var ObjectSchema2 = Object.assign(ObjectSchemaBase2, { + /** + * Type-safe factory for creating business object definitions. + * + * Enhancements over raw schema: + * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case). + * - **Validation**: Runs Zod `.parse()` to validate the config at creation time. + * + * @example + * ```ts + * const Task = ObjectSchema.create({ + * name: 'project_task', + * // label auto-generated as 'Project Task' + * fields: { + * subject: { type: 'text', label: 'Subject', required: true }, + * }, + * }); + * ``` + */ + create: (config4) => { + const withDefaults = { + ...config4, + label: config4.label ?? snakeCaseToLabel2(config4.name), + // Auto-derive tableName as {namespace}_{name} when namespace is set + tableName: config4.tableName ?? (config4.namespace ? `${config4.namespace}_${config4.name}` : void 0) + }; + return ObjectSchemaBase2.parse(withDefaults); + } +}); +external_exports.enum(["own", "extend"]); +external_exports.object({ + /** The target object name (FQN) to extend */ + extend: external_exports.string().describe("Target object name (FQN) to extend"), + /** Fields to merge into the target object (additive) */ + fields: external_exports.record(external_exports.string(), FieldSchema2).optional().describe("Fields to add/override"), + /** Override label */ + label: external_exports.string().optional().describe("Override label for the extended object"), + /** Override plural label */ + pluralLabel: external_exports.string().optional().describe("Override plural label for the extended object"), + /** Override description */ + description: external_exports.string().optional().describe("Override description for the extended object"), + /** Additional validation rules to add */ + validations: external_exports.array(ValidationRuleSchema2).optional().describe("Additional validation rules to merge into the target object"), + /** Additional indexes to add */ + indexes: external_exports.array(IndexSchema2).optional().describe("Additional indexes to merge into the target object"), + /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ + priority: external_exports.number().int().min(0).max(999).default(200).describe("Merge priority (higher = applied later)") +}); +var BaseNavItemSchema = external_exports.object({ + /** Unique identifier for the item */ + id: SnakeCaseIdentifierSchema2.describe("Unique identifier for this navigation item (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema2.describe("Display proper label"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Icon name"), + /** Sort order within the same level (lower numbers appear first) */ + order: external_exports.number().optional().describe("Sort order within the same level (lower = first)"), + /** Badge text or count displayed on the navigation item (e.g. "3", "New") */ + badge: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("Badge text or count displayed on the item"), + /** + * Visibility condition. + * Formula expression returning boolean. + * e.g. "user.is_admin || user.department == 'sales'" + */ + visible: external_exports.string().optional().describe("Visibility formula condition"), + /** Permissions required to see/access this navigation item */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this item") +}); +var ObjectNavItemSchema = BaseNavItemSchema.extend({ + type: external_exports.literal("object"), + objectName: external_exports.string().describe("Target object name"), + viewName: external_exports.string().optional().describe('Default list view to open. Defaults to "all"') +}); +var DashboardNavItemSchema = BaseNavItemSchema.extend({ + type: external_exports.literal("dashboard"), + dashboardName: external_exports.string().describe("Target dashboard name") +}); +var PageNavItemSchema = BaseNavItemSchema.extend({ + type: external_exports.literal("page"), + pageName: external_exports.string().describe("Target custom page component name"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the page context") +}); +var UrlNavItemSchema = BaseNavItemSchema.extend({ + type: external_exports.literal("url"), + url: external_exports.string().describe("Target external URL"), + target: external_exports.enum(["_self", "_blank"]).default("_self").describe("Link target window") +}); +var ReportNavItemSchema = BaseNavItemSchema.extend({ + type: external_exports.literal("report"), + reportName: external_exports.string().describe("Target report name") +}); +var ActionNavItemSchema = BaseNavItemSchema.extend({ + type: external_exports.literal("action"), + actionDef: external_exports.object({ + actionName: external_exports.string().describe("Action machine name to execute"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the action") + }).describe("Action definition to execute when clicked") +}); +var GroupNavItemSchema = BaseNavItemSchema.extend({ + type: external_exports.literal("group"), + expanded: external_exports.boolean().default(false).describe("Default expansion state in sidebar") + // children property is added in the recursive definition below +}); +var NavigationItemSchema = external_exports.lazy( + () => external_exports.union([ + ObjectNavItemSchema.extend({ + children: external_exports.array(NavigationItemSchema).optional().describe("Child navigation items (e.g. specific views)") + }), + DashboardNavItemSchema, + PageNavItemSchema, + UrlNavItemSchema, + ReportNavItemSchema, + ActionNavItemSchema, + GroupNavItemSchema.extend({ + children: external_exports.array(NavigationItemSchema).describe("Child navigation items") + }) + ]) +); +var AppBrandingSchema = external_exports.object({ + primaryColor: external_exports.string().optional().describe("Primary theme color hex code"), + logo: external_exports.string().optional().describe("Custom logo URL for this app"), + favicon: external_exports.string().optional().describe("Custom favicon URL for this app") +}); +var NavigationAreaSchema = external_exports.object({ + /** Unique area identifier */ + id: SnakeCaseIdentifierSchema2.describe("Unique area identifier (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema2.describe("Area display label"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Area icon name"), + /** Sort order among areas (lower = first) */ + order: external_exports.number().optional().describe("Sort order among areas (lower = first)"), + /** Area description */ + description: I18nLabelSchema2.optional().describe("Area description"), + /** + * Visibility condition. + * Formula expression returning boolean. + */ + visible: external_exports.string().optional().describe("Visibility formula condition for this area"), + /** Permissions required to access this area */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this area"), + /** Navigation items within this area */ + navigation: external_exports.array(NavigationItemSchema).describe("Navigation items within this area") +}); +var AppSchema = external_exports.object({ + /** Machine name (id) */ + name: SnakeCaseIdentifierSchema2.describe("App unique machine name (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema2.describe("App display label"), + /** App version */ + version: external_exports.string().optional().describe("App version"), + /** Description */ + description: I18nLabelSchema2.optional().describe("App description"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("App icon used in the App Launcher"), + /** Branding/Theming Configuration */ + branding: AppBrandingSchema.optional().describe("App-specific branding"), + /** Application status */ + active: external_exports.boolean().optional().default(true).describe("Whether the app is enabled"), + /** Is this the default app for new users? */ + isDefault: external_exports.boolean().optional().default(false).describe("Is default app"), + /** + * Full Navigation Tree — supports unlimited nesting depth. + * Pages are referenced by name via `type: 'page'` items. + * Groups can contain other groups for arbitrary sidebar depth. + * + * For simple apps, use `navigation` directly. + * For enterprise apps with multiple business domains, use `areas` instead. + */ + navigation: external_exports.array(NavigationItemSchema).optional().describe("Full navigation tree for the app sidebar"), + /** + * Navigation Areas — partitions navigation by business domain. + * Each area defines an independent navigation tree (e.g. Sales, Service, Settings). + * When areas are defined, they take precedence over the top-level `navigation` array. + * + * @example + * ```ts + * areas: [ + * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] }, + * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] }, + * ] + * ``` + */ + areas: external_exports.array(NavigationAreaSchema).optional().describe("Navigation areas for partitioning navigation by business domain"), + /** + * App-level Home Page Override + * ID of the navigation item to act as the landing page. + * If not set, usually defaults to the first navigation item. + */ + homePageId: external_exports.string().optional().describe("ID of the navigation item to serve as landing page"), + /** + * Access Control + * List of permissions required to access this app. + * Modern replacement for role/profile based assignment. + * Example: ["app.access.crm"] + */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this app"), + /** + * Package Components (For config file convenience) + * In a real monorepo these might be auto-discovered, but here we allow explicit registration. + */ + objects: external_exports.array(external_exports.unknown()).optional().describe("Objects belonging to this app"), + apis: external_exports.array(external_exports.unknown()).optional().describe("Custom APIs belonging to this app"), + /** Sharing configuration for public access */ + sharing: SharingConfigSchema.optional().describe("Public sharing configuration"), + /** Embed configuration for iframe embedding */ + embed: EmbedConfigSchema.optional().describe("Iframe embedding configuration"), + /** Mobile navigation mode */ + mobileNavigation: external_exports.object({ + mode: external_exports.enum(["drawer", "bottom_nav", "hamburger"]).default("drawer").describe("Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu"), + bottomNavItems: external_exports.array(external_exports.string()).optional().describe("Navigation item IDs to show in bottom nav (max 5)") + }).optional().describe("Mobile-specific navigation configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema2.optional().describe("ARIA accessibility attributes for the application") +}); +var MetadataFormatSchema2 = external_exports.enum(["json", "yaml", "typescript", "javascript"]); +var MetadataStatsSchema2 = external_exports.object({ + /** + * Size of the metadata file in bytes + */ + size: external_exports.number().int().min(0).describe("File size in bytes"), + /** + * Last modification timestamp + */ + modifiedAt: external_exports.string().datetime().describe("Last modified date"), + /** + * ETag for cache validation + * Used for conditional requests (If-None-Match header) + */ + etag: external_exports.string().describe("Entity tag for cache validation"), + /** + * Serialization format + */ + format: MetadataFormatSchema2.describe("Serialization format"), + /** + * Full file path (if applicable) + */ + path: external_exports.string().optional().describe("File system path"), + /** + * Additional metadata provider-specific properties + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific metadata") +}); +external_exports.object({ + /** + * Glob patterns to match files + * Example: ["**\/*.object.ts", "**\/*.object.json"] + */ + patterns: external_exports.array(external_exports.string()).optional().describe("File glob patterns"), + /** + * If-None-Match header for conditional loading + * Only load if ETag doesn't match + */ + ifNoneMatch: external_exports.string().optional().describe("ETag for conditional request"), + /** + * If-Modified-Since header for conditional loading + */ + ifModifiedSince: external_exports.string().datetime().optional().describe("Only load if modified after this date"), + /** + * Whether to validate against Zod schema + */ + validate: external_exports.boolean().default(true).describe("Validate against schema"), + /** + * Whether to use cache if available + */ + useCache: external_exports.boolean().default(true).describe("Enable caching"), + /** + * Filter function (serialized as string) + * Example: "(item) => item.name.startsWith('sys_')" + */ + filter: external_exports.string().optional().describe("Filter predicate as string"), + /** + * Maximum number of items to load + */ + limit: external_exports.number().int().min(1).optional().describe("Maximum items to load"), + /** + * Recursively search subdirectories + */ + recursive: external_exports.boolean().default(true).describe("Search subdirectories") +}); +external_exports.object({ + /** + * Serialization format + */ + format: MetadataFormatSchema2.default("typescript").describe("Output format"), + /** + * Prettify output (formatted with indentation) + */ + prettify: external_exports.boolean().default(true).describe("Format with indentation"), + /** + * Indentation size (spaces) + */ + indent: external_exports.number().int().min(0).max(8).default(2).describe("Indentation spaces"), + /** + * Sort object keys alphabetically + */ + sortKeys: external_exports.boolean().default(false).describe("Sort object keys"), + /** + * Include default values in output + */ + includeDefaults: external_exports.boolean().default(false).describe("Include default values"), + /** + * Create backup before overwriting + */ + backup: external_exports.boolean().default(false).describe("Create backup file"), + /** + * Overwrite if exists + */ + overwrite: external_exports.boolean().default(true).describe("Overwrite existing file"), + /** + * Atomic write (write to temp file, then rename) + */ + atomic: external_exports.boolean().default(true).describe("Use atomic write operation"), + /** + * Custom file path (overrides default location) + */ + path: external_exports.string().optional().describe("Custom output path") +}); +external_exports.object({ + /** + * Output file path + */ + output: external_exports.string().describe("Output file path"), + /** + * Export format + */ + format: MetadataFormatSchema2.default("json").describe("Export format"), + /** + * Filter predicate as string + */ + filter: external_exports.string().optional().describe("Filter items to export"), + /** + * Include statistics in export + */ + includeStats: external_exports.boolean().default(false).describe("Include metadata statistics"), + /** + * Compress output + */ + compress: external_exports.boolean().default(false).describe("Compress output (gzip)"), + /** + * Pretty print output + */ + prettify: external_exports.boolean().default(true).describe("Pretty print output") +}); +external_exports.object({ + /** + * Conflict resolution strategy + */ + conflictResolution: external_exports.enum(["skip", "overwrite", "merge", "fail"]).default("merge").describe("How to handle existing items"), + /** + * Validate items against schema + */ + validate: external_exports.boolean().default(true).describe("Validate before import"), + /** + * Dry run (don't actually save) + */ + dryRun: external_exports.boolean().default(false).describe("Simulate import without saving"), + /** + * Continue on errors + */ + continueOnError: external_exports.boolean().default(false).describe("Continue if validation fails"), + /** + * Transform function (as string) + * Example: "(item) => ({ ...item, imported: true })" + */ + transform: external_exports.string().optional().describe("Transform items before import") +}); +external_exports.object({ + /** + * Loaded data + */ + data: external_exports.unknown().nullable().describe("Loaded metadata"), + /** + * Whether data came from cache (304 Not Modified) + */ + fromCache: external_exports.boolean().default(false).describe("Loaded from cache"), + /** + * Not modified (conditional request matched) + */ + notModified: external_exports.boolean().default(false).describe("Not modified since last request"), + /** + * ETag of loaded data + */ + etag: external_exports.string().optional().describe("Entity tag"), + /** + * Statistics about loaded data + */ + stats: MetadataStatsSchema2.optional().describe("Metadata statistics"), + /** + * Load time in milliseconds + */ + loadTime: external_exports.number().min(0).optional().describe("Load duration in ms") +}); +external_exports.object({ + /** + * Whether save was successful + */ + success: external_exports.boolean().describe("Save successful"), + /** + * Path where file was saved + */ + path: external_exports.string().describe("Output path"), + /** + * Generated ETag + */ + etag: external_exports.string().optional().describe("Generated entity tag"), + /** + * File size in bytes + */ + size: external_exports.number().int().min(0).optional().describe("File size"), + /** + * Save time in milliseconds + */ + saveTime: external_exports.number().min(0).optional().describe("Save duration in ms"), + /** + * Backup path (if created) + */ + backupPath: external_exports.string().optional().describe("Backup file path") +}); +external_exports.object({ + /** + * Event type + */ + type: external_exports.enum(["added", "changed", "deleted"]).describe("Event type"), + /** + * Metadata type (e.g., 'object', 'view', 'app') + */ + metadataType: external_exports.string().describe("Type of metadata"), + /** + * Item name/identifier + */ + name: external_exports.string().describe("Item identifier"), + /** + * Full file path + */ + path: external_exports.string().describe("File path"), + /** + * Loaded item data (for added/changed events) + */ + data: external_exports.unknown().optional().describe("Item data"), + /** + * Timestamp + */ + timestamp: external_exports.string().datetime().describe("Event timestamp") +}); +external_exports.object({ + /** + * Collection type (e.g., 'object', 'view', 'app') + */ + type: external_exports.string().describe("Collection type"), + /** + * Total items in collection + */ + count: external_exports.number().int().min(0).describe("Number of items"), + /** + * Formats found in collection + */ + formats: external_exports.array(MetadataFormatSchema2).describe("Formats in collection"), + /** + * Total size in bytes + */ + totalSize: external_exports.number().int().min(0).optional().describe("Total size in bytes"), + /** + * Last modified timestamp + */ + lastModified: external_exports.string().datetime().optional().describe("Last modification date"), + /** + * Collection location (path or URL) + */ + location: external_exports.string().optional().describe("Collection location") +}); +external_exports.object({ + /** + * Loader name/identifier + */ + name: external_exports.string().describe("Loader identifier"), + /** + * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:') + */ + protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Protocol identifier"), + /** + * Detailed capabilities + */ + capabilities: external_exports.object({ + read: external_exports.boolean().default(true), + write: external_exports.boolean().default(false), + watch: external_exports.boolean().default(false), + list: external_exports.boolean().default(true) + }).describe("Loader capabilities"), + /** + * Supported formats + */ + supportedFormats: external_exports.array(MetadataFormatSchema2).describe("Supported formats"), + /** + * Whether loader supports watching for changes + */ + supportsWatch: external_exports.boolean().default(false).describe("Supports file watching"), + /** + * Whether loader supports saving + */ + supportsWrite: external_exports.boolean().default(true).describe("Supports write operations"), + /** + * Whether loader supports caching + */ + supportsCache: external_exports.boolean().default(true).describe("Supports caching") +}); +var MetadataFallbackStrategySchema2 = external_exports.enum([ + "filesystem", + // Fall back to filesystem-based loading + "memory", + // Fall back to in-memory storage + "none" + // No fallback — fail immediately +]); +var MetadataManagerConfigSchema2 = external_exports.object({ + /** + * Datasource Name Reference + * References a DatasourceSchema.name (e.g. 'default'). + * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. + */ + datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), + /** + * Metadata Table Name + * The database table used for metadata storage when datasource is configured. + */ + tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), + /** + * Fallback Strategy + * Determines behavior when the primary datasource is unavailable. + */ + fallback: MetadataFallbackStrategySchema2.default("none").describe("Fallback strategy when datasource is unavailable"), + /** + * Root directory for metadata (for filesystem loaders) + */ + rootDir: external_exports.string().optional().describe("Root directory path"), + /** + * Enabled serialization formats + */ + formats: external_exports.array(MetadataFormatSchema2).default(["typescript", "json", "yaml"]).describe("Enabled formats"), + /** + * Cache configuration + */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable caching"), + ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), + maxSize: external_exports.number().int().min(0).optional().describe("Max cache size in bytes") + }).optional().describe("Cache settings"), + /** + * Watch for file changes + */ + watch: external_exports.boolean().default(false).describe("Enable file watching"), + /** + * Watch options + */ + watchOptions: external_exports.object({ + ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), + persistent: external_exports.boolean().default(true).describe("Keep process running"), + ignoreInitial: external_exports.boolean().default(true).describe("Ignore initial add events") + }).optional().describe("File watcher options"), + /** + * Validation settings + */ + validation: external_exports.object({ + strict: external_exports.boolean().default(true).describe("Strict validation"), + throwOnError: external_exports.boolean().default(true).describe("Throw on validation error") + }).optional().describe("Validation settings"), + /** + * Loader-specific options + */ + loaderOptions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Loader-specific configuration") +}); +external_exports.enum([ + "package", + // Delivered by a plugin package (system layer, read-only) + "admin", + // Created/modified by platform admin via UI + "user", + // Created/modified by end user via UI + "migration", + // Created during data migration + "api" + // Created via API +]); +var FieldChangeSchema = external_exports.object({ + /** JSON path to the changed field (e.g. "fields.status.label") */ + path: external_exports.string().describe("JSON path to the changed field"), + /** Original value from the package (for diff/rollback) */ + originalValue: external_exports.unknown().optional().describe("Original value from the package"), + /** Current customized value */ + currentValue: external_exports.unknown().describe("Current customized value"), + /** Who made this change */ + changedBy: external_exports.string().optional().describe("User or admin who made this change"), + /** When this change was made */ + changedAt: external_exports.string().datetime().optional().describe("Timestamp of the change") +}); +var MetadataOverlaySchema = external_exports.object({ + /** Primary key */ + id: external_exports.string().describe("Overlay record ID (UUID)"), + /** The metadata type being customized (e.g. "object", "view", "flow") */ + baseType: external_exports.string().describe("Metadata type being customized"), + /** The metadata name being customized (e.g. "crm__account") */ + baseName: external_exports.string().describe("Metadata name being customized"), + /** Package that owns the base metadata (null for platform-created metadata) */ + packageId: external_exports.string().optional().describe("Package ID that delivered the base metadata"), + /** Package version when the customization was made (for upgrade diffing) */ + packageVersion: external_exports.string().optional().describe("Package version when overlay was created"), + /** Customization scope */ + scope: external_exports.enum(["platform", "user"]).default("platform").describe("Customization scope (platform=admin, user=personal)"), + /** Tenant ID for multi-tenant isolation */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** Owner user ID (for user-scope overlays) */ + owner: external_exports.string().optional().describe("Owner user ID for user-scope overlays"), + /** + * The overlay payload. + * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396). + * - To modify a field: include the field with its new value + * - To delete a field: set its value to null + * - Omitted fields remain unchanged from base + */ + patch: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Merge Patch payload (changed fields only)"), + /** + * Detailed change tracking for each modified field. + * Enables field-level conflict detection during upgrades. + */ + changes: external_exports.array(FieldChangeSchema).optional().describe("Field-level change tracking for conflict detection"), + /** Whether this overlay is currently active */ + active: external_exports.boolean().default(true).describe("Whether this overlay is active"), + /** Audit timestamps */ + createdAt: external_exports.string().datetime().optional(), + createdBy: external_exports.string().optional(), + updatedAt: external_exports.string().datetime().optional(), + updatedBy: external_exports.string().optional() +}); +var MergeConflictSchema = external_exports.object({ + /** JSON path to the conflicting field */ + path: external_exports.string().describe("JSON path to the conflicting field"), + /** Value in the old package version */ + baseValue: external_exports.unknown().describe("Value in the old package version"), + /** Value in the new package version */ + incomingValue: external_exports.unknown().describe("Value in the new package version"), + /** Customer's customized value */ + customValue: external_exports.unknown().describe("Customer customized value"), + /** Suggested resolution strategy */ + suggestedResolution: external_exports.enum([ + "keep-custom", + // Keep customer's customization + "accept-incoming", + // Accept package update + "manual" + // Requires manual resolution + ]).describe("Suggested resolution strategy"), + /** Reason for the suggested resolution */ + reason: external_exports.string().optional().describe("Explanation for the suggested resolution") +}); +var MergeStrategyConfigSchema = external_exports.object({ + /** Default strategy when no field-level rule matches */ + defaultStrategy: external_exports.enum([ + "keep-custom", + // Preserve all customer customizations (safe) + "accept-incoming", + // Accept all package updates (overwrite) + "three-way-merge" + // Intelligent 3-way merge with conflict detection + ]).default("three-way-merge").describe("Default merge strategy"), + /** + * Field paths that should always accept incoming package updates. + * Use for fields that the package vendor considers "owned" and should not be customized. + * @example ["fields.*.type", "triggers.*"] + */ + alwaysAcceptIncoming: external_exports.array(external_exports.string()).optional().describe("Field paths that always accept package updates"), + /** + * Field paths where customer customizations always win. + * Use for UI-facing fields like labels, descriptions, help text. + * @example ["fields.*.label", "fields.*.helpText", "description"] + */ + alwaysKeepCustom: external_exports.array(external_exports.string()).optional().describe("Field paths where customer customizations always win"), + /** Whether to automatically resolve non-conflicting changes */ + autoResolveNonConflicting: external_exports.boolean().default(true).describe("Auto-resolve changes that do not conflict") +}); +external_exports.object({ + /** Whether the merge completed successfully (no unresolved conflicts) */ + success: external_exports.boolean().describe("Whether merge completed without unresolved conflicts"), + /** The merged metadata payload */ + mergedMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Merged metadata result"), + /** Updated overlay with remaining customizations */ + updatedOverlay: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated overlay after merge"), + /** List of conflicts that require manual resolution */ + conflicts: external_exports.array(MergeConflictSchema).optional().describe("Unresolved merge conflicts"), + /** Summary of automatically resolved changes */ + autoResolved: external_exports.array(external_exports.object({ + path: external_exports.string(), + resolution: external_exports.string(), + description: external_exports.string().optional() + })).optional().describe("Summary of auto-resolved changes"), + /** Statistics */ + stats: external_exports.object({ + totalFields: external_exports.number().int().min(0).describe("Total fields evaluated"), + unchanged: external_exports.number().int().min(0).describe("Fields with no changes"), + autoResolved: external_exports.number().int().min(0).describe("Fields auto-resolved"), + conflicts: external_exports.number().int().min(0).describe("Fields with conflicts") + }).optional() +}); +var CustomizationPolicySchema = external_exports.object({ + /** Metadata type this policy applies to */ + metadataType: external_exports.string().describe('Metadata type (e.g. "object", "view")'), + /** Whether customization is allowed at all for this type */ + allowCustomization: external_exports.boolean().default(true), + /** + * Field paths that are locked (cannot be customized). + * @example ["name", "type", "fields.*.type"] + */ + lockedFields: external_exports.array(external_exports.string()).optional().describe("Field paths that cannot be customized"), + /** + * Field paths that are customizable. + * If specified, only these fields can be customized (whitelist mode). + * @example ["label", "description", "fields.*.label", "fields.*.helpText"] + */ + customizableFields: external_exports.array(external_exports.string()).optional().describe("Field paths that can be customized (whitelist)"), + /** + * Whether users can add new fields to package objects. + * When true, admins can extend package objects with custom fields. + */ + allowAddFields: external_exports.boolean().default(true).describe("Whether admins can add new fields to package objects"), + /** + * Whether users can delete package-delivered fields. + * Typically false — fields can only be hidden, not deleted. + */ + allowDeleteFields: external_exports.boolean().default(false).describe("Whether admins can delete package-delivered fields") +}); +var MetadataTypeSchema = external_exports.enum([ + // Data Protocol + "object", + // Business entity definition (ObjectSchema) + "field", + // Standalone field definition (FieldSchema) + "trigger", + // Data-layer event triggers (TriggerSchema) + "validation", + // Validation rules (ValidationSchema) + "hook", + // Data hooks (HookSchema) + // UI Protocol + "view", + // List/form views (ViewSchema) + "page", + // Standalone pages (PageSchema) + "dashboard", + // Dashboard layouts (DashboardSchema) + "app", + // Application shell (AppSchema) + "action", + // UI/Server actions (ActionSchema) + "report", + // Report definitions (ReportSchema) + // Automation Protocol + "flow", + // Visual logic flows (FlowSchema) + "workflow", + // State machines (WorkflowSchema) + "approval", + // Approval processes (ApprovalSchema) + // System Protocol + "datasource", + // Data connections (DatasourceSchema) + "translation", + // i18n resources (TranslationSchema) + "router", + // API routes + "function", + // Serverless functions + "service", + // Service definitions + // Security Protocol + "permission", + // Permission sets (PermissionSetSchema) + "profile", + // User profiles (ProfileSchema) + "role", + // Security roles + // AI Protocol + "agent", + // AI agent definitions (AgentSchema) + "tool", + // AI tool definitions (ToolSchema) + "skill" + // AI skill definitions (SkillSchema) +]); +var MetadataTypeRegistryEntrySchema = external_exports.object({ + /** Metadata type identifier (e.g., 'object', 'view') */ + type: MetadataTypeSchema.describe("Metadata type identifier"), + /** Human-readable label */ + label: external_exports.string().describe("Display label for the metadata type"), + /** Brief description */ + description: external_exports.string().optional().describe("Description of the metadata type"), + /** + * File glob patterns for this type. + * Used to discover metadata files on disk. + * @example ["**\/*.object.ts", "**\/*.object.yml"] + */ + filePatterns: external_exports.array(external_exports.string()).describe("Glob patterns to discover files of this type"), + /** + * Whether this type supports the customization overlay system. + * When true, platform/user overlays can be applied on top of package-delivered metadata. + */ + supportsOverlay: external_exports.boolean().default(true).describe("Whether overlay customization is supported"), + /** + * Whether metadata of this type can be created at runtime via API. + * Some types (e.g., 'object') may be restricted to deployment-only. + */ + allowRuntimeCreate: external_exports.boolean().default(true).describe("Allow runtime creation via API"), + /** + * Whether this type supports versioning. + * When true, changes are tracked with version history. + */ + supportsVersioning: external_exports.boolean().default(false).describe("Whether version history is tracked"), + /** + * Priority order for loading (lower = earlier). + * Objects load before views, views before dashboards. + */ + loadOrder: external_exports.number().int().min(0).default(100).describe("Loading priority (lower = earlier)"), + /** The domain this type belongs to */ + domain: external_exports.enum(["data", "ui", "automation", "system", "security", "ai"]).describe("Protocol domain") +}); +var MetadataQuerySchema = external_exports.object({ + /** Filter by metadata type(s) */ + types: external_exports.array(MetadataTypeSchema).optional().describe("Filter by metadata types"), + /** Filter by namespace(s) */ + namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), + /** Filter by package ID */ + packageId: external_exports.string().optional().describe("Filter by owning package"), + /** Full-text search across name, label, description */ + search: external_exports.string().optional().describe("Full-text search query"), + /** Filter by scope */ + scope: external_exports.enum(["system", "platform", "user"]).optional().describe("Filter by scope"), + /** Filter by state */ + state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional().describe("Filter by lifecycle state"), + /** Filter by tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), + /** Sort field */ + sortBy: external_exports.enum(["name", "type", "updatedAt", "createdAt"]).default("name").describe("Sort field"), + /** Sort direction */ + sortOrder: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction"), + /** Pagination: page number (1-based) */ + page: external_exports.number().int().min(1).default(1).describe("Page number"), + /** Pagination: items per page */ + pageSize: external_exports.number().int().min(1).max(500).default(50).describe("Items per page") +}); +var MetadataQueryResultSchema = external_exports.object({ + /** Matched items */ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + namespace: external_exports.string().optional().describe("Namespace"), + label: external_exports.string().optional().describe("Display label"), + scope: external_exports.enum(["system", "platform", "user"]).optional(), + state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional(), + packageId: external_exports.string().optional(), + updatedAt: external_exports.string().datetime().optional() + })).describe("Matched metadata items"), + /** Total count (for pagination) */ + total: external_exports.number().int().min(0).describe("Total matching items"), + /** Current page */ + page: external_exports.number().int().min(1).describe("Current page"), + /** Page size */ + pageSize: external_exports.number().int().min(1).describe("Page size") +}); +external_exports.object({ + /** Event type */ + event: external_exports.enum([ + "metadata.registered", + "metadata.updated", + "metadata.unregistered", + "metadata.validated", + "metadata.deployed", + "metadata.overlay.applied", + "metadata.overlay.removed", + "metadata.imported", + "metadata.exported" + ]).describe("Event type"), + /** Metadata type */ + metadataType: MetadataTypeSchema.describe("Metadata type"), + /** Item name */ + name: external_exports.string().describe("Metadata item name"), + /** Namespace */ + namespace: external_exports.string().optional().describe("Namespace"), + /** Package ID (if package-managed) */ + packageId: external_exports.string().optional().describe("Owning package ID"), + /** Timestamp */ + timestamp: external_exports.string().datetime().describe("Event timestamp"), + /** Actor who caused the event */ + actor: external_exports.string().optional().describe("User or system that triggered the event"), + /** Additional event-specific payload */ + payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific payload") +}); +var MetadataValidationResultSchema = external_exports.object({ + /** Whether validation passed */ + valid: external_exports.boolean().describe("Whether the metadata is valid"), + /** Validation errors */ + errors: external_exports.array(external_exports.object({ + path: external_exports.string().describe("JSON path to the invalid field"), + message: external_exports.string().describe("Error description"), + code: external_exports.string().optional().describe("Error code") + })).optional().describe("Validation errors"), + /** Validation warnings (non-blocking) */ + warnings: external_exports.array(external_exports.object({ + path: external_exports.string().describe("JSON path to the field"), + message: external_exports.string().describe("Warning description") + })).optional().describe("Validation warnings") +}); +var MetadataPluginConfigSchema = external_exports.object({ + /** + * Storage configuration. + * References MetadataManagerConfigSchema for the underlying storage backend. + */ + storage: MetadataManagerConfigSchema2.describe("Storage backend configuration"), + /** + * Default customization policies per metadata type. + * Controls what parts of metadata can be customized by admins/users. + */ + customizationPolicies: external_exports.array(CustomizationPolicySchema).optional().describe("Default customization policies per type"), + /** + * Merge strategy for package upgrades. + */ + mergeStrategy: MergeStrategyConfigSchema.optional().describe("Merge strategy for package upgrades"), + /** + * Additional metadata type registrations. + * Used by plugins to register custom metadata types beyond the built-in set. + */ + additionalTypes: external_exports.array(MetadataTypeRegistryEntrySchema.omit({ type: true }).extend({ + type: external_exports.string().describe("Custom metadata type identifier") + })).optional().describe("Additional custom metadata types"), + /** + * Enable metadata change events. + * When true, the plugin emits events on every metadata change. + */ + enableEvents: external_exports.boolean().default(true).describe("Emit metadata change events"), + /** + * Enable metadata validation on write operations. + * When true, all metadata is validated against its type schema before saving. + */ + validateOnWrite: external_exports.boolean().default(true).describe("Validate metadata on write"), + /** + * Enable metadata versioning. + * When true, changes to metadata are tracked with version history. + */ + enableVersioning: external_exports.boolean().default(false).describe("Track metadata version history"), + /** + * Maximum number of metadata items to keep in memory cache. + */ + cacheMaxItems: external_exports.number().int().min(0).default(1e4).describe("Max items in memory cache") +}); +external_exports.object({ + /** Plugin identifier */ + id: external_exports.literal("com.objectstack.metadata").describe("Metadata plugin ID"), + /** Plugin name */ + name: external_exports.literal("ObjectStack Metadata Service").describe("Plugin name"), + /** Plugin version */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Plugin version"), + /** Plugin type */ + type: external_exports.literal("standard").describe("Plugin type"), + /** Plugin description */ + description: external_exports.string().default("Core metadata management service for ObjectStack platform").describe("Plugin description"), + /** + * Capabilities this plugin provides. + * The kernel uses this to route metadata requests to this plugin. + */ + capabilities: external_exports.object({ + /** Supports CRUD operations on metadata */ + crud: external_exports.boolean().default(true).describe("Supports metadata CRUD"), + /** Supports metadata query/search */ + query: external_exports.boolean().default(true).describe("Supports metadata query"), + /** Supports the overlay/customization system */ + overlay: external_exports.boolean().default(true).describe("Supports customization overlays"), + /** Supports file watching for hot reload */ + watch: external_exports.boolean().default(false).describe("Supports file watching"), + /** Supports bulk import/export */ + importExport: external_exports.boolean().default(true).describe("Supports import/export"), + /** Supports metadata validation */ + validation: external_exports.boolean().default(true).describe("Supports schema validation"), + /** Supports metadata versioning */ + versioning: external_exports.boolean().default(false).describe("Supports version history"), + /** Supports metadata events */ + events: external_exports.boolean().default(true).describe("Emits metadata events") + }).describe("Plugin capabilities"), + /** Plugin configuration */ + config: MetadataPluginConfigSchema.optional().describe("Plugin configuration") +}); +external_exports.object({ + /** Items to register */ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), + namespace: external_exports.string().optional().describe("Namespace") + })).min(1).describe("Items to register"), + /** Continue on individual item failure */ + continueOnError: external_exports.boolean().default(false).describe("Continue if individual item fails"), + /** Validate items before registering */ + validate: external_exports.boolean().default(true).describe("Validate before register") +}); +var MetadataBulkResultSchema = external_exports.object({ + /** Total items processed */ + total: external_exports.number().int().min(0).describe("Total items processed"), + /** Successfully processed items */ + succeeded: external_exports.number().int().min(0).describe("Successfully processed"), + /** Failed items */ + failed: external_exports.number().int().min(0).describe("Failed items"), + /** Per-item error details */ + errors: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + error: external_exports.string().describe("Error message") + })).optional().describe("Per-item errors") +}); +var MetadataDependencySchema = external_exports.object({ + /** Source metadata type */ + sourceType: external_exports.string().describe("Dependent metadata type"), + /** Source metadata name */ + sourceName: external_exports.string().describe("Dependent metadata name"), + /** Target metadata type */ + targetType: external_exports.string().describe("Referenced metadata type"), + /** Target metadata name */ + targetName: external_exports.string().describe("Referenced metadata name"), + /** Dependency kind */ + kind: external_exports.enum(["reference", "extends", "includes", "triggers"]).describe("How the dependency is formed") +}); +var ObjectDefinitionResponseSchema = BaseResponseSchema.extend({ + data: ObjectSchema2.describe("Full Object Schema") +}); +var AppDefinitionResponseSchema = BaseResponseSchema.extend({ + data: AppSchema.describe("Full App Configuration") +}); +var ConceptListResponseSchema = BaseResponseSchema.extend({ + data: external_exports.array(external_exports.object({ + name: external_exports.string(), + label: external_exports.string(), + icon: external_exports.string().optional(), + description: external_exports.string().optional() + })).describe("List of available concepts (Objects, Apps, Flows)") +}); +var MetadataRegisterRequestSchema = external_exports.object({ + type: MetadataTypeSchema.describe("Metadata type"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Item name (snake_case)"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), + namespace: external_exports.string().optional().describe("Optional namespace") +}); +var MetadataItemResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + definition: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata definition payload") + }).describe("Metadata item") +}); +var MetadataListResponseSchema = BaseResponseSchema.extend({ + data: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Array of metadata definitions") +}); +var MetadataNamesResponseSchema = BaseResponseSchema.extend({ + data: external_exports.array(external_exports.string()).describe("Array of metadata item names") +}); +var MetadataExistsResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + exists: external_exports.boolean().describe("Whether the item exists") + }) +}); +var MetadataDeleteResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Deleted item name") + }) +}); +var MetadataQueryRequestSchema = MetadataQuerySchema.describe( + "Metadata query with filtering, sorting, and pagination" +); +var MetadataQueryResponseSchema = BaseResponseSchema.extend({ + data: MetadataQueryResultSchema.describe("Paginated query result") +}); +var MetadataBulkRegisterRequestSchema2 = external_exports.object({ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload") + })).min(1).describe("Items to register"), + continueOnError: external_exports.boolean().default(false).describe("Continue on individual failure"), + validate: external_exports.boolean().default(true).describe("Validate before registering") +}); +var MetadataBulkUnregisterRequestSchema = external_exports.object({ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name") + })).min(1).describe("Items to unregister") +}); +var MetadataBulkResponseSchema = BaseResponseSchema.extend({ + data: MetadataBulkResultSchema.describe("Bulk operation result") +}); +var MetadataOverlayResponseSchema = BaseResponseSchema.extend({ + data: MetadataOverlaySchema.optional().describe("Overlay definition, undefined if none") +}); +var MetadataOverlaySaveRequestSchema = MetadataOverlaySchema.describe( + "Overlay to save" +); +var MetadataEffectiveResponseSchema = BaseResponseSchema.extend({ + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Effective metadata with all overlays applied") +}); +var MetadataExportRequestSchema = external_exports.object({ + types: external_exports.array(external_exports.string()).optional().describe("Filter by metadata types"), + namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), + format: external_exports.enum(["json", "yaml"]).default("json").describe("Export format") +}); +var MetadataExportResponseSchema = BaseResponseSchema.extend({ + data: external_exports.unknown().describe("Exported metadata bundle") +}); +var MetadataImportRequestSchema = external_exports.object({ + data: external_exports.unknown().describe("Metadata bundle to import"), + conflictResolution: external_exports.enum(["skip", "overwrite", "merge"]).default("skip").describe("Conflict resolution strategy"), + validate: external_exports.boolean().default(true).describe("Validate before import"), + dryRun: external_exports.boolean().default(false).describe("Dry run (no save)") +}); +var MetadataImportResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + total: external_exports.number().int().min(0), + imported: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + failed: external_exports.number().int().min(0), + errors: external_exports.array(external_exports.object({ + type: external_exports.string(), + name: external_exports.string(), + error: external_exports.string() + })).optional() + }).describe("Import result") +}); +var MetadataValidateRequestSchema = external_exports.object({ + type: external_exports.string().describe("Metadata type to validate against"), + data: external_exports.unknown().describe("Metadata payload to validate") +}); +var MetadataValidateResponseSchema = BaseResponseSchema.extend({ + data: MetadataValidationResultSchema.describe("Validation result") +}); +var MetadataTypesResponseSchema = BaseResponseSchema.extend({ + data: external_exports.array(external_exports.string()).describe("Registered metadata type identifiers") +}); +var MetadataTypeInfoResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + type: external_exports.string().describe("Metadata type identifier"), + label: external_exports.string().describe("Display label"), + description: external_exports.string().optional().describe("Description"), + filePatterns: external_exports.array(external_exports.string()).describe("File glob patterns"), + supportsOverlay: external_exports.boolean().describe("Overlay support"), + domain: external_exports.string().describe("Protocol domain") + }).optional().describe("Type info") +}); +var MetadataDependenciesResponseSchema = BaseResponseSchema.extend({ + data: external_exports.array(MetadataDependencySchema).describe("Items this item depends on") +}); +var MetadataDependentsResponseSchema = BaseResponseSchema.extend({ + data: external_exports.array(MetadataDependencySchema).describe("Items that depend on this item") +}); +var CoreServiceName2 = external_exports.enum([ + // Core Data & Metadata + "metadata", + // Object/Field Definitions + "data", + // CRUD & Query Engine + "auth", + // Authentication & Identity + // Infrastructure + "file-storage", + // Storage Driver (Local/S3) + "search", + // Search Engine (Elastic/Meili) + "cache", + // Cache Driver (Redis/Memory) + "queue", + // Job Queue (BullMQ/Redis) + // Advanced Capabilities + "automation", + // Flow & Script Engine + "graphql", + // GraphQL API Engine + "analytics", + // BI & Semantic Layer + "realtime", + // WebSocket & PubSub + "job", + // Background Job Manager + "notification", + // Email/Push/SMS + "ai", + // AI Engine (NLQ, Chat, Suggest, Insights) + "i18n", + // Internationalization Service + "ui", + // UI Metadata Service (View CRUD) + "workflow" + // Workflow State Machine Engine +]); +var ServiceCriticalitySchema2 = external_exports.enum([ + "required", + // System fails to start if missing (Exit Code 1) + "core", + // System warns if missing, functionality degraded (Warn) + "optional" + // System ignores if missing, feature disabled (Info) +]); +external_exports.object({ + name: CoreServiceName2, + enabled: external_exports.boolean(), + status: external_exports.enum(["running", "stopped", "degraded", "initializing"]), + version: external_exports.string().optional(), + provider: external_exports.string().optional().describe('Implementation provider (e.g. "s3" for storage)'), + features: external_exports.array(external_exports.string()).optional().describe("List of supported sub-features") +}); +external_exports.record( + CoreServiceName2, + external_exports.unknown().describe("Service Instance implementing the protocol interface") +); +external_exports.object({ + id: external_exports.string(), + name: CoreServiceName2, + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var DispatcherRouteSchema = external_exports.object({ + /** + * URL path prefix for routing. + * Incoming requests matching this prefix are routed to the target service. + * Must start with '/'. + */ + prefix: external_exports.string().regex(/^\//).describe("URL path prefix for routing (e.g. /api/v1/data)"), + /** + * Target core service name. + * The service that handles requests matching this prefix. + */ + service: CoreServiceName2.describe("Target core service name"), + /** + * Whether requests to this route require authentication. + * Discovery endpoint is typically public; most others require auth. + * @default true + */ + authRequired: external_exports.boolean().default(true).describe("Whether authentication is required"), + /** + * Service criticality level. + * Determines behavior when the service is unavailable: + * - required: return 500 Internal Server Error + * - core: return 503 with degraded notice + * - optional: return 503 Service Unavailable + * @default 'optional' + */ + criticality: ServiceCriticalitySchema2.default("optional").describe("Service criticality level for unavailability handling"), + /** + * Required permissions for accessing this route namespace. + * Applied as a baseline before individual endpoint permission checks. + */ + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions for this route namespace") +}); +var DispatcherConfigSchema = external_exports.object({ + /** + * Registered route mappings. + * Routes are matched by longest-prefix-first strategy. + */ + routes: external_exports.array(DispatcherRouteSchema).describe("Route-to-service mappings"), + /** + * Behavior when no route matches the request. + * - 404: Return 404 Not Found (default) + * - proxy: Forward to a configured proxy target + * - custom: Delegate to a custom handler + * @default '404' + */ + fallback: external_exports.enum(["404", "proxy", "custom"]).default("404").describe("Behavior when no route matches"), + /** + * Proxy target URL for fallback: 'proxy' mode. + */ + proxyTarget: external_exports.string().url().optional().describe('Proxy target URL when fallback is "proxy"') +}); +var DispatcherErrorCode = external_exports.enum(["404", "405", "501", "503"]).describe( + "404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable" +); +var DispatcherErrorResponseSchema = external_exports.object({ + /** Always `false` for error responses */ + success: external_exports.literal(false), + error: external_exports.object({ + /** HTTP status code */ + code: external_exports.number().int().describe("HTTP status code (404, 405, 501, 503, \u2026)"), + /** Human-readable error message */ + message: external_exports.string().describe("Human-readable error message"), + /** + * Machine-readable error type for programmatic branching. + */ + type: external_exports.enum([ + "ROUTE_NOT_FOUND", + "METHOD_NOT_ALLOWED", + "NOT_IMPLEMENTED", + "SERVICE_UNAVAILABLE" + ]).optional().describe("Machine-readable error type"), + /** Route that was requested */ + route: external_exports.string().optional().describe("Requested route path"), + /** Service that the route maps to (if known) */ + service: external_exports.string().optional().describe("Target service name, if resolvable"), + /** Guidance for the developer */ + hint: external_exports.string().optional().describe('Actionable hint for the developer (e.g., "Install plugin-workflow")') + }) +}); +var HttpServerConfigSchema2 = external_exports.object({ + /** + * Server port number + */ + port: external_exports.number().int().min(1).max(65535).default(3e3).describe("Port number to listen on"), + /** + * Server host address + */ + host: external_exports.string().default("0.0.0.0").describe("Host address to bind to"), + /** + * CORS configuration + */ + cors: CorsConfigSchema2.optional().describe("CORS configuration"), + /** + * Request handling options + */ + requestTimeout: external_exports.number().int().default(3e4).describe("Request timeout in milliseconds"), + bodyLimit: external_exports.string().default("10mb").describe("Maximum request body size"), + /** + * Compression settings + */ + compression: external_exports.boolean().default(true).describe("Enable response compression"), + /** + * Security headers + */ + security: external_exports.object({ + helmet: external_exports.boolean().default(true).describe("Enable security headers via helmet"), + rateLimit: RateLimitConfigSchema2.optional().describe("Global rate limiting configuration") + }).optional().describe("Security configuration"), + /** + * Static file serving + */ + static: external_exports.array(StaticMountSchema2).optional().describe("Static file serving configuration"), + /** + * Trust proxy settings + */ + trustProxy: external_exports.boolean().default(false).describe("Trust X-Forwarded-* headers") +}); +external_exports.object({ + /** + * HTTP method + */ + method: HttpMethod2.describe("HTTP method"), + /** + * URL path pattern (supports parameters like /api/users/:id) + */ + path: external_exports.string().describe("URL path pattern"), + /** + * Handler function name or identifier + */ + handler: external_exports.string().describe("Handler identifier or name"), + /** + * Route metadata + */ + metadata: external_exports.object({ + summary: external_exports.string().optional().describe("Route summary for documentation"), + description: external_exports.string().optional().describe("Route description"), + tags: external_exports.array(external_exports.string()).optional().describe("Tags for grouping"), + operationId: external_exports.string().optional().describe("Unique operation identifier") + }).optional(), + /** + * Security requirements + */ + security: external_exports.object({ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + rateLimit: external_exports.string().optional().describe("Rate limit policy override") + }).optional() +}); +var MiddlewareType2 = external_exports.enum([ + "authentication", + // Authentication middleware + "authorization", + // Authorization/permission checks + "logging", + // Request/response logging + "validation", + // Input validation + "transformation", + // Request/response transformation + "error", + // Error handling + "custom" + // Custom middleware +]); +var MiddlewareConfigSchema2 = external_exports.object({ + /** + * Middleware identifier + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Middleware name (snake_case)"), + /** + * Middleware type + */ + type: MiddlewareType2.describe("Middleware type"), + /** + * Enable/disable middleware + */ + enabled: external_exports.boolean().default(true).describe("Whether middleware is enabled"), + /** + * Execution order (lower numbers execute first) + */ + order: external_exports.number().int().default(100).describe("Execution order priority"), + /** + * Middleware-specific configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Middleware configuration object"), + /** + * Path patterns to apply middleware to + */ + paths: external_exports.object({ + include: external_exports.array(external_exports.string()).optional().describe("Include path patterns (glob)"), + exclude: external_exports.array(external_exports.string()).optional().describe("Exclude path patterns (glob)") + }).optional().describe("Path filtering") +}); +var ServerEventType2 = external_exports.enum([ + "starting", + // Server is starting + "started", + // Server has started and is listening + "stopping", + // Server is stopping + "stopped", + // Server has stopped + "request", + // Request received + "response", + // Response sent + "error" + // Error occurred +]); +external_exports.object({ + /** + * Event type + */ + type: ServerEventType2.describe("Event type"), + /** + * Timestamp + */ + timestamp: external_exports.string().datetime().describe("Event timestamp (ISO 8601)"), + /** + * Event payload + */ + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific data") +}); +external_exports.object({ + /** + * Supported HTTP versions + */ + httpVersions: external_exports.array(external_exports.enum(["1.0", "1.1", "2.0", "3.0"])).default(["1.1"]).describe("Supported HTTP versions"), + /** + * WebSocket support + */ + websocket: external_exports.boolean().default(false).describe("WebSocket support"), + /** + * Server-Sent Events support + */ + sse: external_exports.boolean().default(false).describe("Server-Sent Events support"), + /** + * HTTP/2 Server Push + */ + serverPush: external_exports.boolean().default(false).describe("HTTP/2 Server Push support"), + /** + * Streaming support + */ + streaming: external_exports.boolean().default(true).describe("Response streaming support"), + /** + * Middleware support + */ + middleware: external_exports.boolean().default(true).describe("Middleware chain support"), + /** + * Route parameterization + */ + routeParams: external_exports.boolean().default(true).describe("URL parameter support (/users/:id)"), + /** + * Built-in compression + */ + compression: external_exports.boolean().default(true).describe("Built-in compression support") +}); +external_exports.object({ + /** + * Server state + */ + state: external_exports.enum(["stopped", "starting", "running", "stopping", "error"]).describe("Current server state"), + /** + * Uptime in milliseconds + */ + uptime: external_exports.number().int().optional().describe("Server uptime in milliseconds"), + /** + * Server information + */ + server: external_exports.object({ + port: external_exports.number().int().describe("Listening port"), + host: external_exports.string().describe("Bound host"), + url: external_exports.string().optional().describe("Full server URL") + }).optional(), + /** + * Connection metrics + */ + connections: external_exports.object({ + active: external_exports.number().int().describe("Active connections"), + total: external_exports.number().int().describe("Total connections handled") + }).optional(), + /** + * Request metrics + */ + requests: external_exports.object({ + total: external_exports.number().int().describe("Total requests processed"), + success: external_exports.number().int().describe("Successful requests"), + errors: external_exports.number().int().describe("Failed requests") + }).optional() +}); +Object.assign(HttpServerConfigSchema2, { + create: (config4) => config4 +}); +Object.assign(MiddlewareConfigSchema2, { + create: (config4) => config4 +}); +var RestApiRouteCategory = external_exports.enum([ + "discovery", + // API discovery and capabilities + "metadata", + // Metadata operations (objects, fields, views) + "data", + // Data CRUD operations + "batch", + // Batch/bulk operations + "permission", + // Permission/authorization checks + "analytics", + // Analytics and reporting + "automation", + // Automation triggers and flows + "workflow", + // Workflow state management + "ui", + // UI metadata (views, layouts) + "realtime", + // Realtime/WebSocket + "notification", + // Notification management + "ai", + // AI operations (NLQ, chat) + "i18n" + // Internationalization +]); +var HandlerStatusSchema = external_exports.enum(["implemented", "stub", "planned"]); +var RestApiEndpointSchema = external_exports.object({ + /** + * HTTP method + */ + method: HttpMethod2.describe("HTTP method for this endpoint"), + /** + * URL path pattern (supports parameters like :id) + */ + path: external_exports.string().describe("URL path pattern (e.g., /api/v1/data/:object/:id)"), + /** + * Handler reference (protocol method name) + */ + handler: external_exports.string().describe("Protocol method name or handler identifier"), + /** + * Route category + */ + category: RestApiRouteCategory.describe("Route category"), + /** + * Whether endpoint is publicly accessible (no auth required) + */ + public: external_exports.boolean().default(false).describe("Is publicly accessible without authentication"), + /** + * Required permissions + */ + permissions: external_exports.array(external_exports.string()).optional().describe('Required permissions (e.g., ["data.read", "object.account.read"])'), + /** + * OpenAPI documentation metadata + */ + summary: external_exports.string().optional().describe("Short description for OpenAPI"), + description: external_exports.string().optional().describe("Detailed description for OpenAPI"), + tags: external_exports.array(external_exports.string()).optional().describe("OpenAPI tags for grouping"), + /** + * Request/Response schema references + */ + requestSchema: external_exports.string().optional().describe("Request schema name (for validation)"), + responseSchema: external_exports.string().optional().describe("Response schema name (for documentation)"), + /** + * Performance and reliability settings + */ + timeout: external_exports.number().int().optional().describe("Request timeout in milliseconds"), + rateLimit: external_exports.string().optional().describe("Rate limit policy name"), + cacheable: external_exports.boolean().default(false).describe("Whether response can be cached"), + cacheTtl: external_exports.number().int().optional().describe("Cache TTL in seconds"), + /** + * Handler implementation status. + * Tracks whether this endpoint has a real handler or is only declared. + * + * - `implemented` – A real handler is coded and registered. + * - `stub` – A placeholder handler exists that returns 501 Not Implemented. + * - `planned` – Declared in the protocol spec but not yet implemented. + * @default 'implemented' + */ + handlerStatus: HandlerStatusSchema.optional().describe("Handler implementation status: implemented (default if omitted), stub, or planned") +}); +var RestApiRouteRegistrationSchema = external_exports.object({ + /** + * URL prefix for this route group (e.g., /api/v1/data) + */ + prefix: external_exports.string().regex(/^\//).describe("URL path prefix for this route group"), + /** + * Service name that handles these routes + */ + service: external_exports.string().describe("Core service name (metadata, data, auth, etc.)"), + /** + * Route category + */ + category: RestApiRouteCategory.describe("Primary category for this route group"), + /** + * Protocol methods implemented + */ + methods: external_exports.array(external_exports.string()).optional().describe("Protocol method names implemented"), + /** + * Detailed endpoint definitions + */ + endpoints: external_exports.array(RestApiEndpointSchema).optional().describe("Endpoint definitions"), + /** + * Middleware applied to all routes in this group + */ + middleware: external_exports.array(MiddlewareConfigSchema2).optional().describe("Middleware stack for this route group"), + /** + * Whether authentication is required for all routes + */ + authRequired: external_exports.boolean().default(true).describe("Whether authentication is required by default"), + /** + * OpenAPI documentation + */ + documentation: external_exports.object({ + title: external_exports.string().optional().describe("Route group title"), + description: external_exports.string().optional().describe("Route group description"), + tags: external_exports.array(external_exports.string()).optional().describe("OpenAPI tags") + }).optional().describe("Documentation metadata for this route group") +}); +var ValidationMode = external_exports.enum([ + "strict", + // Reject requests with validation errors (400 Bad Request) + "permissive", + // Log validation errors but allow request to proceed + "strip" + // Remove invalid fields and continue with valid data +]); +var RequestValidationConfigSchema = external_exports.object({ + /** + * Enable request validation + */ + enabled: external_exports.boolean().default(true).describe("Enable automatic request validation"), + /** + * Validation mode + */ + mode: ValidationMode.default("strict").describe("How to handle validation errors"), + /** + * Validate request body + */ + validateBody: external_exports.boolean().default(true).describe("Validate request body against schema"), + /** + * Validate query parameters + */ + validateQuery: external_exports.boolean().default(true).describe("Validate query string parameters"), + /** + * Validate URL parameters + */ + validateParams: external_exports.boolean().default(true).describe("Validate URL path parameters"), + /** + * Validate request headers + */ + validateHeaders: external_exports.boolean().default(false).describe("Validate request headers"), + /** + * Include detailed field errors in response + */ + includeFieldErrors: external_exports.boolean().default(true).describe("Include field-level error details in response"), + /** + * Custom error message prefix + */ + errorPrefix: external_exports.string().optional().describe("Custom prefix for validation error messages"), + /** + * Schema registry reference + */ + schemaRegistry: external_exports.string().optional().describe("Schema registry name to use for validation") +}); +var ResponseEnvelopeConfigSchema = external_exports.object({ + /** + * Enable response envelope wrapping + */ + enabled: external_exports.boolean().default(true).describe("Enable automatic response envelope wrapping"), + /** + * Include metadata object + */ + includeMetadata: external_exports.boolean().default(true).describe("Include meta object in responses"), + /** + * Include timestamp in metadata + */ + includeTimestamp: external_exports.boolean().default(true).describe("Include timestamp in response metadata"), + /** + * Include request ID in metadata + */ + includeRequestId: external_exports.boolean().default(true).describe("Include requestId in response metadata"), + /** + * Include request duration in metadata + */ + includeDuration: external_exports.boolean().default(false).describe("Include request duration in ms"), + /** + * Include trace ID for distributed tracing + */ + includeTraceId: external_exports.boolean().default(false).describe("Include distributed traceId"), + /** + * Custom metadata fields + */ + customMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata fields to include"), + /** + * Whether to wrap already-wrapped responses + */ + skipIfWrapped: external_exports.boolean().default(true).describe("Skip wrapping if response already has success field") +}); +var ErrorHandlingConfigSchema = external_exports.object({ + /** + * Enable standardized error handling + */ + enabled: external_exports.boolean().default(true).describe("Enable standardized error handling"), + /** + * Include stack traces in error responses (dev only) + */ + includeStackTrace: external_exports.boolean().default(false).describe("Include stack traces in error responses"), + /** + * Log errors to logger + */ + logErrors: external_exports.boolean().default(true).describe("Log errors to system logger"), + /** + * Expose internal error details + */ + exposeInternalErrors: external_exports.boolean().default(false).describe("Expose internal error details in responses"), + /** + * Include request ID in errors + */ + includeRequestId: external_exports.boolean().default(true).describe("Include requestId in error responses"), + /** + * Include timestamp in errors + */ + includeTimestamp: external_exports.boolean().default(true).describe("Include timestamp in error responses"), + /** + * Include error documentation URLs + */ + includeDocumentation: external_exports.boolean().default(true).describe("Include documentation URLs for errors"), + /** + * Documentation base URL + */ + documentationBaseUrl: external_exports.string().url().optional().describe("Base URL for error documentation"), + /** + * Custom error messages by code + */ + customErrorMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom error messages by error code"), + /** + * Sensitive fields to redact from error details + */ + redactFields: external_exports.array(external_exports.string()).optional().describe("Field names to redact from error details") +}); +var OpenApiGenerationConfigSchema = external_exports.object({ + /** + * Enable OpenAPI generation + */ + enabled: external_exports.boolean().default(true).describe("Enable automatic OpenAPI documentation generation"), + /** + * OpenAPI specification version + */ + version: external_exports.enum(["3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.1.0"]).default("3.0.3").describe("OpenAPI specification version"), + /** + * API title + */ + title: external_exports.string().default("ObjectStack API").describe("API title"), + /** + * API description + */ + description: external_exports.string().optional().describe("API description"), + /** + * API version + */ + apiVersion: external_exports.string().default("1.0.0").describe("API version"), + /** + * Output path for OpenAPI spec + */ + outputPath: external_exports.string().default("/api/docs/openapi.json").describe("URL path to serve OpenAPI JSON"), + /** + * UI path for Swagger/Redoc + */ + uiPath: external_exports.string().default("/api/docs").describe("URL path to serve documentation UI"), + /** + * UI framework to use + */ + uiFramework: external_exports.enum(["swagger-ui", "redoc", "rapidoc", "elements"]).default("swagger-ui").describe("Documentation UI framework"), + /** + * Include internal/admin endpoints + */ + includeInternal: external_exports.boolean().default(false).describe("Include internal endpoints in documentation"), + /** + * Generate JSON schemas from Zod + */ + generateSchemas: external_exports.boolean().default(true).describe("Auto-generate schemas from Zod definitions"), + /** + * Include examples in documentation + */ + includeExamples: external_exports.boolean().default(true).describe("Include request/response examples"), + /** + * Server URLs + */ + servers: external_exports.array(external_exports.object({ + url: external_exports.string().describe("Server URL"), + description: external_exports.string().optional().describe("Server description") + })).optional().describe("Server URLs for API"), + /** + * Contact information + */ + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().url().optional(), + email: external_exports.string().email().optional() + }).optional().describe("API contact information"), + /** + * License information + */ + license: external_exports.object({ + name: external_exports.string().describe("License name"), + url: external_exports.string().url().optional().describe("License URL") + }).optional().describe("API license information"), + /** + * Security schemes + */ + securitySchemes: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["apiKey", "http", "oauth2", "openIdConnect"]), + scheme: external_exports.string().optional(), + bearerFormat: external_exports.string().optional() + })).optional().describe("Security scheme definitions") +}); +var RestApiPluginConfigSchema = external_exports.object({ + /** + * Enable REST API plugin + */ + enabled: external_exports.boolean().default(true).describe("Enable REST API plugin"), + /** + * API base path + */ + basePath: external_exports.string().default("/api").describe("Base path for all API routes"), + /** + * API version + */ + version: external_exports.string().default("v1").describe("API version identifier"), + /** + * Route registrations + */ + routes: external_exports.array(RestApiRouteRegistrationSchema).describe("Route registrations"), + /** + * Request validation configuration + */ + validation: RequestValidationConfigSchema.optional().describe("Request validation configuration"), + /** + * Response envelope configuration + */ + responseEnvelope: ResponseEnvelopeConfigSchema.optional().describe("Response envelope configuration"), + /** + * Error handling configuration + */ + errorHandling: ErrorHandlingConfigSchema.optional().describe("Error handling configuration"), + /** + * OpenAPI documentation configuration + */ + openApi: OpenApiGenerationConfigSchema.optional().describe("OpenAPI documentation configuration"), + /** + * Global middleware applied to all routes + */ + globalMiddleware: external_exports.array(MiddlewareConfigSchema2).optional().describe("Global middleware stack"), + /** + * CORS configuration + */ + cors: external_exports.object({ + enabled: external_exports.boolean().default(true), + origins: external_exports.array(external_exports.string()).optional(), + methods: external_exports.array(HttpMethod2).optional(), + credentials: external_exports.boolean().default(true) + }).optional().describe("CORS configuration"), + /** + * Performance settings + */ + performance: external_exports.object({ + enableCompression: external_exports.boolean().default(true).describe("Enable response compression"), + enableETag: external_exports.boolean().default(true).describe("Enable ETag generation"), + enableCaching: external_exports.boolean().default(true).describe("Enable HTTP caching"), + defaultCacheTtl: external_exports.number().int().default(300).describe("Default cache TTL in seconds") + }).optional().describe("Performance optimization settings") +}); +var RestApiPluginConfig = Object.assign(RestApiPluginConfigSchema, { + create: (config4) => config4 +}); +var RestApiRouteRegistration = Object.assign(RestApiRouteRegistrationSchema, { + create: (registration) => registration +}); +var RouteCoverageEntrySchema = external_exports.object({ + /** Full URL path of the endpoint */ + path: external_exports.string().describe("Full URL path (e.g. /api/v1/analytics/query)"), + /** HTTP method */ + method: HttpMethod2.describe("HTTP method (GET, POST, etc.)"), + /** Route category */ + category: RestApiRouteCategory.describe("Route category"), + /** Handler implementation status */ + handlerStatus: HandlerStatusSchema.describe("Handler status"), + /** Target service */ + service: external_exports.string().describe("Target service name"), + /** Whether the handler was successfully called during health check */ + healthCheckPassed: external_exports.boolean().optional().describe("Whether the health check probe succeeded") +}); +var RouteCoverageReportSchema = external_exports.object({ + /** ISO 8601 timestamp of report generation */ + timestamp: external_exports.string().describe("ISO 8601 timestamp"), + /** Adapter that generated the report */ + adapter: external_exports.string().describe('Adapter name (e.g. "hono", "express", "nextjs")'), + /** Summary counters */ + summary: external_exports.object({ + total: external_exports.number().int().describe("Total declared endpoints"), + implemented: external_exports.number().int().describe("Endpoints with real handlers"), + stub: external_exports.number().int().describe("Endpoints with stub handlers (501)"), + planned: external_exports.number().int().describe("Endpoints not yet implemented") + }), + /** Per-endpoint entries */ + entries: external_exports.array(RouteCoverageEntrySchema).describe("Per-endpoint coverage entries") +}); +var QueryAdapterTargetSchema = external_exports.enum([ + "rest", + // REST API (?filter[field][op]=value) + "graphql", + // GraphQL (where: \{ field: \{ op: value \}\}) + "odata" + // OData ($filter=field op value) +]); +var OperatorMappingSchema = external_exports.object({ + /** Unified DSL operator (e.g., 'eq', 'gt', 'contains') */ + operator: external_exports.string().describe("Unified DSL operator"), + /** REST query parameter format (e.g., 'filter[{field}][{op}]') */ + rest: external_exports.string().optional().describe("REST query parameter template"), + /** GraphQL where clause format (e.g., '{field}: { {op}: $value }') */ + graphql: external_exports.string().optional().describe("GraphQL where clause template"), + /** OData $filter expression format (e.g., '{field} {op} {value}') */ + odata: external_exports.string().optional().describe("OData $filter expression template") +}); +var RestQueryAdapterSchema = external_exports.object({ + /** Filter parameter style */ + filterStyle: external_exports.enum([ + "bracket", + // ?filter[field][op]=value (JSON API style) + "dot", + // ?filter.field.op=value + "flat", + // ?field=value (simple equality) + "rsql" + // ?filter=field==value;field=gt=10 (RSQL / FIQL) + ]).default("bracket").describe("REST filter parameter encoding style"), + /** Pagination parameter names */ + pagination: external_exports.object({ + /** Page size parameter name */ + limitParam: external_exports.string().default("limit").describe("Page size parameter name"), + /** Offset parameter name */ + offsetParam: external_exports.string().default("offset").describe("Offset parameter name"), + /** Cursor parameter name (for cursor-based pagination) */ + cursorParam: external_exports.string().default("cursor").describe("Cursor parameter name"), + /** Page number parameter name (for page-based pagination) */ + pageParam: external_exports.string().default("page").describe("Page number parameter name") + }).optional().describe("Pagination parameter name mappings"), + /** Sort parameter name and format */ + sorting: external_exports.object({ + /** Sort parameter name */ + param: external_exports.string().default("sort").describe("Sort parameter name"), + /** Sort format */ + format: external_exports.enum([ + "comma", + // ?sort=field1,-field2 + "array", + // ?sort[]=field1&sort[]=-field2 + "pipe" + // ?sort=field1|asc,field2|desc + ]).default("comma").describe("Sort parameter encoding format") + }).optional().describe("Sort parameter mapping"), + /** Field selection parameter name */ + fieldsParam: external_exports.string().default("fields").describe("Field selection parameter name") +}); +var GraphQLQueryAdapterSchema = external_exports.object({ + /** Filter argument name in GraphQL queries */ + filterArgName: external_exports.string().default("where").describe("GraphQL filter argument name"), + /** Filter nesting style */ + filterStyle: external_exports.enum([ + "nested", + // where: { field: { op: value } } (Prisma style) + "flat", + // where: { field_op: value } (Hasura style) + "array" + // where: [{ field, op, value }] (Array of conditions) + ]).default("nested").describe("GraphQL filter nesting style"), + /** Pagination argument names */ + pagination: external_exports.object({ + limitArg: external_exports.string().default("limit").describe("Page size argument name"), + offsetArg: external_exports.string().default("offset").describe("Offset argument name"), + firstArg: external_exports.string().default("first").describe('Relay "first" argument name'), + afterArg: external_exports.string().default("after").describe('Relay "after" cursor argument name') + }).optional().describe("Pagination argument name mappings"), + /** Sort argument configuration */ + sorting: external_exports.object({ + argName: external_exports.string().default("orderBy").describe("Sort argument name"), + format: external_exports.enum([ + "enum", + // orderBy: { field: ASC } + "array" + // orderBy: [{ field: "name", direction: "ASC" }] + ]).default("enum").describe("Sort argument format") + }).optional().describe("Sort argument mapping") +}); +var ODataQueryAdapterSchema = external_exports.object({ + /** OData version */ + version: external_exports.enum(["v2", "v4"]).default("v4").describe("OData version"), + /** System query option prefixes */ + usePrefix: external_exports.boolean().default(true).describe("Use $ prefix for system query options ($filter vs filter)"), + /** String function support */ + stringFunctions: external_exports.array(external_exports.enum([ + "contains", + "startswith", + "endswith", + "tolower", + "toupper", + "trim", + "concat", + "substring", + "length" + ])).optional().describe("Supported OData string functions"), + /** Expand (nested resource) configuration */ + expand: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable $expand support"), + maxDepth: external_exports.number().int().min(1).default(3).describe("Maximum expand depth") + }).optional().describe("$expand configuration") +}); +var QueryAdapterConfigSchema = external_exports.object({ + /** Default operator mappings */ + operatorMappings: external_exports.array(OperatorMappingSchema).optional().describe("Custom operator mappings"), + /** REST adapter configuration */ + rest: RestQueryAdapterSchema.optional().describe("REST query adapter configuration"), + /** GraphQL adapter configuration */ + graphql: GraphQLQueryAdapterSchema.optional().describe("GraphQL query adapter configuration"), + /** OData adapter configuration */ + odata: ODataQueryAdapterSchema.optional().describe("OData query adapter configuration") +}); +var FeedItemType = external_exports.enum([ + "comment", + "field_change", + "task", + "event", + "email", + "call", + "note", + "file", + "record_create", + "record_delete", + "approval", + "sharing", + "system" +]); +var MentionSchema = external_exports.object({ + type: external_exports.enum(["user", "team", "record"]).describe("Mention target type"), + id: external_exports.string().describe("Target ID"), + name: external_exports.string().describe("Display name for rendering"), + offset: external_exports.number().int().min(0).describe("Character offset in body text"), + length: external_exports.number().int().min(1).describe("Length of mention token in body text") +}); +var FieldChangeEntrySchema = external_exports.object({ + field: external_exports.string().describe("Field machine name"), + fieldLabel: external_exports.string().optional().describe("Field display label"), + oldValue: external_exports.unknown().optional().describe("Previous value"), + newValue: external_exports.unknown().optional().describe("New value"), + oldDisplayValue: external_exports.string().optional().describe("Human-readable old value"), + newDisplayValue: external_exports.string().optional().describe("Human-readable new value") +}); +var ReactionSchema = external_exports.object({ + emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")'), + userIds: external_exports.array(external_exports.string()).describe("Users who reacted"), + count: external_exports.number().int().min(1).describe("Total reaction count") +}); +var FeedActorSchema = external_exports.object({ + type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), + id: external_exports.string().describe("Actor ID"), + name: external_exports.string().optional().describe("Actor display name"), + avatarUrl: external_exports.string().url().optional().describe("Actor avatar URL"), + source: external_exports.string().optional().describe('Source application (e.g., "Omni", "API", "Studio")') +}); +var FeedVisibility = external_exports.enum(["public", "internal", "private"]); +var FeedItemSchema = external_exports.object({ + /** Unique identifier */ + id: external_exports.string().describe("Feed item ID"), + /** Feed item type */ + type: FeedItemType.describe("Activity type"), + /** Target record reference */ + object: external_exports.string().describe('Object name (e.g., "account")'), + recordId: external_exports.string().describe("Record ID this feed item belongs to"), + /** Actor (who performed the action) */ + actor: FeedActorSchema.describe("Who performed this action"), + /** Content (for comments/notes) */ + body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), + /** @Mentions */ + mentions: external_exports.array(MentionSchema).optional().describe("Mentioned users/teams/records"), + /** Field changes (for field_change type) */ + changes: external_exports.array(FieldChangeEntrySchema).optional().describe("Field-level changes"), + /** Reactions */ + reactions: external_exports.array(ReactionSchema).optional().describe("Emoji reactions on this item"), + /** Reply threading */ + parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), + replyCount: external_exports.number().int().min(0).default(0).describe("Number of replies"), + /** Pin / Star */ + pinned: external_exports.boolean().default(false).describe("Whether the feed item is pinned to the top of the timeline"), + pinnedAt: external_exports.string().datetime().optional().describe("Timestamp when the item was pinned"), + pinnedBy: external_exports.string().optional().describe("User ID who pinned the item"), + starred: external_exports.boolean().default(false).describe("Whether the feed item is starred/bookmarked by the current user"), + starredAt: external_exports.string().datetime().optional().describe("Timestamp when the item was starred"), + /** Visibility */ + visibility: FeedVisibility.default("public").describe("Visibility: public (all users), internal (team only), private (author + mentioned)"), + /** Timestamps */ + createdAt: external_exports.string().datetime().describe("Creation timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + editedAt: external_exports.string().datetime().optional().describe("When comment was last edited"), + isEdited: external_exports.boolean().default(false).describe("Whether comment has been edited") +}); +external_exports.enum([ + "all", + "comments_only", + "changes_only", + "tasks_only" +]); +var SubscriptionEventType = external_exports.enum([ + "comment", + "mention", + "field_change", + "task", + "approval", + "all" +]); +var NotificationChannel = external_exports.enum([ + "in_app", + "email", + "push", + "slack" +]); +var RecordSubscriptionSchema = external_exports.object({ + /** Target */ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + /** Subscriber */ + userId: external_exports.string().describe("Subscribing user ID"), + /** Events to subscribe to */ + events: external_exports.array(SubscriptionEventType).default(["all"]).describe("Event types to receive notifications for"), + /** Notification channels */ + channels: external_exports.array(NotificationChannel).default(["in_app"]).describe("Notification delivery channels"), + /** Active */ + active: external_exports.boolean().default(true).describe("Whether the subscription is active"), + /** Timestamps */ + createdAt: external_exports.string().datetime().describe("Subscription creation timestamp") +}); +var FeedPathParamsSchema = external_exports.object({ + object: external_exports.string().describe('Object name (e.g., "account")'), + recordId: external_exports.string().describe("Record ID") +}); +var FeedItemPathParamsSchema = FeedPathParamsSchema.extend({ + feedId: external_exports.string().describe("Feed item ID") +}); +var FeedListFilterType = external_exports.enum([ + "all", + "comments_only", + "changes_only", + "tasks_only" +]); +var GetFeedRequestSchema = FeedPathParamsSchema.extend({ + type: FeedListFilterType.default("all").describe("Filter by feed item category"), + limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of items to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination (opaque string from previous response)") +}); +var GetFeedResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + items: external_exports.array(FeedItemSchema).describe("Feed items in reverse chronological order"), + total: external_exports.number().int().optional().describe("Total feed items matching filter"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more items are available") + }) +}); +var CreateFeedItemRequestSchema = FeedPathParamsSchema.extend({ + type: FeedItemType.describe("Type of feed item to create"), + body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), + mentions: external_exports.array(MentionSchema).optional().describe("Mentioned users, teams, or records"), + parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), + visibility: FeedVisibility.default("public").describe("Visibility: public, internal, or private") +}); +var CreateFeedItemResponseSchema = BaseResponseSchema.extend({ + data: FeedItemSchema.describe("The created feed item") +}); +var UpdateFeedItemRequestSchema = FeedItemPathParamsSchema.extend({ + body: external_exports.string().optional().describe("Updated rich text body"), + mentions: external_exports.array(MentionSchema).optional().describe("Updated mentions"), + visibility: FeedVisibility.optional().describe("Updated visibility") +}); +var UpdateFeedItemResponseSchema = BaseResponseSchema.extend({ + data: FeedItemSchema.describe("The updated feed item") +}); +var DeleteFeedItemResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the deleted feed item") + }) +}); +var AddReactionRequestSchema = FeedItemPathParamsSchema.extend({ + emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")') +}); +var AddReactionResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + reactions: external_exports.array(ReactionSchema).describe("Updated reaction list for the feed item") + }) +}); +var RemoveReactionRequestSchema = FeedItemPathParamsSchema.extend({ + emoji: external_exports.string().describe("Emoji character or shortcode to remove") +}); +var RemoveReactionResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + reactions: external_exports.array(ReactionSchema).describe("Updated reaction list for the feed item") + }) +}); +var PinFeedItemResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the pinned feed item"), + pinned: external_exports.boolean().describe("Whether the item is now pinned"), + pinnedAt: external_exports.string().datetime().describe("Timestamp when pinned") + }) +}); +var UnpinFeedItemResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the unpinned feed item"), + pinned: external_exports.boolean().describe("Whether the item is now pinned (should be false)") + }) +}); +var StarFeedItemResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the starred feed item"), + starred: external_exports.boolean().describe("Whether the item is now starred"), + starredAt: external_exports.string().datetime().describe("Timestamp when starred") + }) +}); +var UnstarFeedItemResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the unstarred feed item"), + starred: external_exports.boolean().describe("Whether the item is now starred (should be false)") + }) +}); +var SearchFeedRequestSchema = FeedPathParamsSchema.extend({ + query: external_exports.string().min(1).describe("Full-text search query against feed body content"), + type: FeedListFilterType.optional().describe("Filter by feed item category"), + actorId: external_exports.string().optional().describe("Filter by actor user ID"), + dateFrom: external_exports.string().datetime().optional().describe("Filter feed items created after this timestamp"), + dateTo: external_exports.string().datetime().optional().describe("Filter feed items created before this timestamp"), + hasAttachments: external_exports.boolean().optional().describe("Filter for items with file attachments"), + pinnedOnly: external_exports.boolean().optional().describe("Return only pinned items"), + starredOnly: external_exports.boolean().optional().describe("Return only starred items"), + limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of items to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination") +}); +var SearchFeedResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + items: external_exports.array(FeedItemSchema).describe("Matching feed items sorted by relevance"), + total: external_exports.number().int().optional().describe("Total matching items"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more items are available") + }) +}); +var GetChangelogRequestSchema = FeedPathParamsSchema.extend({ + field: external_exports.string().optional().describe("Filter changelog to a specific field name"), + actorId: external_exports.string().optional().describe("Filter changelog by actor user ID"), + dateFrom: external_exports.string().datetime().optional().describe("Filter changes after this timestamp"), + dateTo: external_exports.string().datetime().optional().describe("Filter changes before this timestamp"), + limit: external_exports.number().int().min(1).max(200).default(50).describe("Maximum number of changelog entries to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination") +}); +var ChangelogEntrySchema = external_exports.object({ + id: external_exports.string().describe("Changelog entry ID"), + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + actor: external_exports.object({ + type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), + id: external_exports.string().describe("Actor ID"), + name: external_exports.string().optional().describe("Actor display name") + }).describe("Who made the change"), + changes: external_exports.array(FieldChangeEntrySchema).min(1).describe("Field-level changes"), + timestamp: external_exports.string().datetime().describe("When the change occurred"), + source: external_exports.string().optional().describe('Change source (e.g., "API", "UI", "automation")') +}); +var GetChangelogResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + entries: external_exports.array(ChangelogEntrySchema).describe("Changelog entries in reverse chronological order"), + total: external_exports.number().int().optional().describe("Total changelog entries matching filter"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more entries are available") + }) +}); +var SubscribeRequestSchema = FeedPathParamsSchema.extend({ + events: external_exports.array(SubscriptionEventType).default(["all"]).describe("Event types to subscribe to"), + channels: external_exports.array(NotificationChannel).default(["in_app"]).describe("Notification delivery channels") +}); +var SubscribeResponseSchema = BaseResponseSchema.extend({ + data: RecordSubscriptionSchema.describe("The created or updated subscription") +}); +var UnsubscribeResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + unsubscribed: external_exports.boolean().describe("Whether the user was unsubscribed") + }) +}); +var FeedApiErrorCode = external_exports.enum([ + "feed_item_not_found", + "feed_permission_denied", + "feed_item_not_editable", + "feed_invalid_parent", + "reaction_already_exists", + "reaction_not_found", + "subscription_already_exists", + "subscription_not_found", + "invalid_feed_type", + "feed_already_pinned", + "feed_not_pinned", + "feed_already_starred", + "feed_not_starred", + "feed_search_query_too_short" +]); +var ExportFormat = external_exports.enum([ + "csv", + "json", + "jsonl", + "xlsx", + "parquet" +]); +var ExportJobStatus = external_exports.enum([ + "pending", + "processing", + "completed", + "failed", + "cancelled", + "expired" +]); +var CreateExportJobRequestSchema = external_exports.object({ + object: external_exports.string().describe("Object name to export"), + format: ExportFormat.default("csv").describe("Export file format"), + fields: external_exports.array(external_exports.string()).optional().describe("Specific fields to include (omit for all fields)"), + filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria for records to export"), + sort: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + direction: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction") + })).optional().describe("Sort order for exported records"), + limit: external_exports.number().int().min(1).optional().describe("Maximum number of records to export"), + includeHeaders: external_exports.boolean().default(true).describe("Include header row (CSV/XLSX)"), + encoding: external_exports.string().default("utf-8").describe("Character encoding for the export file"), + templateId: external_exports.string().optional().describe("Export template ID for predefined field mappings") +}); +var CreateExportJobResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + jobId: external_exports.string().describe("Export job ID"), + status: ExportJobStatus.describe("Initial job status"), + estimatedRecords: external_exports.number().int().optional().describe("Estimated total records"), + createdAt: external_exports.string().datetime().describe("Job creation timestamp") + }) +}); +var ExportJobProgressSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + jobId: external_exports.string().describe("Export job ID"), + status: ExportJobStatus.describe("Current job status"), + format: ExportFormat.describe("Export format"), + totalRecords: external_exports.number().int().optional().describe("Total records to export"), + processedRecords: external_exports.number().int().describe("Records processed so far"), + percentComplete: external_exports.number().min(0).max(100).describe("Export progress percentage"), + fileSize: external_exports.number().int().optional().describe("Current file size in bytes"), + downloadUrl: external_exports.string().optional().describe('Presigned download URL (available when status is "completed")'), + downloadExpiresAt: external_exports.string().datetime().optional().describe("Download URL expiration timestamp"), + error: external_exports.object({ + code: external_exports.string().describe("Error code"), + message: external_exports.string().describe("Error message") + }).optional().describe("Error details if job failed"), + startedAt: external_exports.string().datetime().optional().describe("Processing start timestamp"), + completedAt: external_exports.string().datetime().optional().describe("Completion timestamp") + }) +}); +var ImportValidationMode = external_exports.enum([ + "strict", + // Reject entire import on any validation error + "lenient", + // Skip invalid records, import valid ones + "dry_run" + // Validate all records without persisting +]); +var DeduplicationStrategy = external_exports.enum([ + "skip", + // Skip duplicates (keep existing) + "update", + // Update existing with import data + "create_new", + // Create new record even if duplicate + "fail" + // Fail the import if duplicates found +]); +var ImportValidationConfigSchema = external_exports.object({ + mode: ImportValidationMode.default("strict").describe("Validation mode for the import"), + deduplication: external_exports.object({ + strategy: DeduplicationStrategy.default("skip").describe("How to handle duplicate records"), + matchFields: external_exports.array(external_exports.string()).min(1).describe('Fields used to identify duplicates (e.g., "email", "external_id")') + }).optional().describe("Deduplication configuration"), + maxErrors: external_exports.number().int().min(1).default(100).describe("Maximum validation errors before aborting"), + trimWhitespace: external_exports.boolean().default(true).describe("Trim leading/trailing whitespace from string fields"), + dateFormat: external_exports.string().optional().describe('Expected date format in import data (e.g., "YYYY-MM-DD")'), + nullValues: external_exports.array(external_exports.string()).optional().describe('Strings to treat as null (e.g., ["", "N/A", "null"])') +}); +var ImportValidationResultSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + totalRecords: external_exports.number().int().describe("Total records in import file"), + validRecords: external_exports.number().int().describe("Records that passed validation"), + invalidRecords: external_exports.number().int().describe("Records that failed validation"), + duplicateRecords: external_exports.number().int().describe("Duplicate records detected"), + errors: external_exports.array(external_exports.object({ + row: external_exports.number().int().describe("Row number in the import file"), + field: external_exports.string().optional().describe("Field that failed validation"), + code: external_exports.string().describe("Validation error code"), + message: external_exports.string().describe("Validation error message") + })).describe("List of validation errors"), + preview: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Preview of first N valid records (for dry_run mode)") + }) +}); +var FieldMappingEntrySchema = external_exports.object({ + sourceField: external_exports.string().describe("Field name in the source data (import) or object (export)"), + targetField: external_exports.string().describe("Field name in the target object (import) or file column (export)"), + targetLabel: external_exports.string().optional().describe("Display label for the target column (export)"), + transform: external_exports.enum(["none", "uppercase", "lowercase", "trim", "date_format", "lookup"]).default("none").describe("Transformation to apply during mapping"), + defaultValue: external_exports.unknown().optional().describe("Default value if source field is null/empty"), + required: external_exports.boolean().default(false).describe("Whether this field is required (import validation)") +}); +var ExportImportTemplateSchema = external_exports.object({ + id: external_exports.string().optional().describe("Template ID (generated on save)"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Template machine name (snake_case)"), + label: external_exports.string().describe("Human-readable template label"), + description: external_exports.string().optional().describe("Template description"), + object: external_exports.string().describe("Target object name"), + direction: external_exports.enum(["import", "export", "bidirectional"]).describe("Template direction"), + format: ExportFormat.optional().describe("Default file format for this template"), + mappings: external_exports.array(FieldMappingEntrySchema).min(1).describe("Field mapping entries"), + createdAt: external_exports.string().datetime().optional().describe("Template creation timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + createdBy: external_exports.string().optional().describe("User who created the template") +}); +var ScheduledExportSchema = external_exports.object({ + id: external_exports.string().optional().describe("Scheduled export ID"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Schedule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label"), + object: external_exports.string().describe("Object name to export"), + format: ExportFormat.default("csv").describe("Export file format"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to include"), + filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record filter criteria"), + templateId: external_exports.string().optional().describe("Export template ID for field mappings"), + schedule: external_exports.object({ + cronExpression: external_exports.string().describe("Cron expression for schedule"), + timezone: external_exports.string().default("UTC").describe("IANA timezone") + }).describe("Schedule timing configuration"), + delivery: external_exports.object({ + method: external_exports.enum(["email", "storage", "webhook"]).describe("How to deliver the export file"), + recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients (for email delivery)"), + storagePath: external_exports.string().optional().describe("Storage path (for storage delivery)"), + webhookUrl: external_exports.string().optional().describe("Webhook URL (for webhook delivery)") + }).describe("Export delivery configuration"), + enabled: external_exports.boolean().default(true).describe("Whether the scheduled export is active"), + lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp"), + nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution"), + createdAt: external_exports.string().datetime().optional().describe("Creation timestamp"), + createdBy: external_exports.string().optional().describe("User who created the schedule") +}); +var GetExportJobDownloadRequestSchema = external_exports.object({ + jobId: external_exports.string().describe("Export job ID") +}); +var GetExportJobDownloadResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + jobId: external_exports.string().describe("Export job ID"), + downloadUrl: external_exports.string().describe("Presigned download URL"), + fileName: external_exports.string().describe("Suggested file name"), + fileSize: external_exports.number().int().describe("File size in bytes"), + format: ExportFormat.describe("Export file format"), + expiresAt: external_exports.string().datetime().describe("Download URL expiration timestamp"), + checksum: external_exports.string().optional().describe("File checksum (SHA-256)") + }) +}); +var ListExportJobsRequestSchema = external_exports.object({ + object: external_exports.string().optional().describe("Filter by object name"), + status: ExportJobStatus.optional().describe("Filter by job status"), + limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of jobs to return"), + cursor: external_exports.string().optional().describe("Pagination cursor from a previous response") +}); +var ExportJobSummarySchema = external_exports.object({ + jobId: external_exports.string().describe("Export job ID"), + object: external_exports.string().describe("Object name that was exported"), + status: ExportJobStatus.describe("Current job status"), + format: ExportFormat.describe("Export file format"), + totalRecords: external_exports.number().int().optional().describe("Total records exported"), + fileSize: external_exports.number().int().optional().describe("File size in bytes"), + createdAt: external_exports.string().datetime().describe("Job creation timestamp"), + completedAt: external_exports.string().datetime().optional().describe("Completion timestamp"), + createdBy: external_exports.string().optional().describe("User who initiated the export") +}); +var ListExportJobsResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + jobs: external_exports.array(ExportJobSummarySchema).describe("List of export jobs"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more jobs are available") + }) +}); +var ScheduleExportRequestSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Schedule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label"), + object: external_exports.string().describe("Object name to export"), + format: ExportFormat.default("csv").describe("Export file format"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to include"), + filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record filter criteria"), + templateId: external_exports.string().optional().describe("Export template ID for field mappings"), + schedule: external_exports.object({ + cronExpression: external_exports.string().describe("Cron expression for schedule"), + timezone: external_exports.string().default("UTC").describe("IANA timezone") + }).describe("Schedule timing configuration"), + delivery: external_exports.object({ + method: external_exports.enum(["email", "storage", "webhook"]).describe("How to deliver the export file"), + recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients (for email delivery)"), + storagePath: external_exports.string().optional().describe("Storage path (for storage delivery)"), + webhookUrl: external_exports.string().optional().describe("Webhook URL (for webhook delivery)") + }).describe("Export delivery configuration") +}); +var ScheduleExportResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + id: external_exports.string().describe("Scheduled export ID"), + name: external_exports.string().describe("Schedule name"), + enabled: external_exports.boolean().describe("Whether the schedule is active"), + nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution"), + createdAt: external_exports.string().datetime().describe("Creation timestamp") + }) +}); +var ExportApiContracts = { + createExportJob: { + method: "POST", + path: "/api/v1/data/:object/export", + input: CreateExportJobRequestSchema, + output: CreateExportJobResponseSchema + }, + getExportJobProgress: { + method: "GET", + path: "/api/v1/data/export/:jobId", + input: external_exports.object({ jobId: external_exports.string() }), + output: ExportJobProgressSchema + }, + getExportJobDownload: { + method: "GET", + path: "/api/v1/data/export/:jobId/download", + input: GetExportJobDownloadRequestSchema, + output: GetExportJobDownloadResponseSchema + }, + listExportJobs: { + method: "GET", + path: "/api/v1/data/export", + input: ListExportJobsRequestSchema, + output: ListExportJobsResponseSchema + }, + scheduleExport: { + method: "POST", + path: "/api/v1/data/export/schedules", + input: ScheduleExportRequestSchema, + output: ScheduleExportResponseSchema + }, + cancelExportJob: { + method: "POST", + path: "/api/v1/data/export/:jobId/cancel", + input: external_exports.object({ jobId: external_exports.string() }), + output: BaseResponseSchema + } +}; +var FlowNodeAction = external_exports.enum([ + "start", + // Trigger + "end", + // Return/Stop + "decision", + // If/Else logic + "assignment", + // Set Variable + "loop", + // For Each + "create_record", + // CRUD: Create + "update_record", + // CRUD: Update + "delete_record", + // CRUD: Delete + "get_record", + // CRUD: Get/Query + "http_request", + // Webhook/API Call + "script", + // Custom Script (JS/TS) + "screen", + // Screen / User-Input Element + "wait", + // Delay/Sleep + "subflow", + // Call another flow + "connector_action", + // Zapier-style integration action + "parallel_gateway", + // BPMN Parallel Gateway — AND-split (all outgoing branches execute concurrently) + "join_gateway", + // BPMN Join Gateway — AND-join (waits for all incoming branches to complete) + "boundary_event" + // BPMN Boundary Event — attached to a host node for timer/error/signal interrupts +]); +var FlowVariableSchema = external_exports.object({ + name: external_exports.string().describe("Variable name"), + type: external_exports.string().describe("Data type (text, number, boolean, object, list)"), + isInput: external_exports.boolean().default(false).describe("Is input parameter"), + isOutput: external_exports.boolean().default(false).describe("Is output parameter") +}); +var FlowNodeSchema = external_exports.object({ + id: external_exports.string().describe("Node unique ID"), + type: FlowNodeAction.describe("Action type"), + label: external_exports.string().describe("Node label"), + /** Node Configuration Options (Specific to type) */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Node configuration"), + /** + * Connector Action Configuration + * Used when type is 'connector_action' + */ + connectorConfig: external_exports.object({ + connectorId: external_exports.string(), + actionId: external_exports.string(), + input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Mapped inputs for the action") + }).optional(), + /** UI Position (for the canvas) */ + position: external_exports.object({ x: external_exports.number(), y: external_exports.number() }).optional(), + /** Node-level execution timeout */ + timeoutMs: external_exports.number().int().min(0).optional().describe("Maximum execution time for this node in milliseconds"), + /** Node input schema declaration for Studio form generation and runtime validation */ + inputSchema: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["string", "number", "boolean", "object", "array"]).describe("Parameter type"), + required: external_exports.boolean().default(false).describe("Whether the parameter is required"), + description: external_exports.string().optional().describe("Parameter description") + })).optional().describe("Input parameter schema for this node"), + /** Node output schema declaration */ + outputSchema: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["string", "number", "boolean", "object", "array"]).describe("Output type"), + description: external_exports.string().optional().describe("Output description") + })).optional().describe("Output schema declaration for this node"), + /** + * Wait Event Configuration (for 'wait' nodes) + * Defines what external event or condition should resume the paused execution. + * Industry alignment: BPMN Intermediate Catch Events, Temporal Signals. + */ + waitEventConfig: external_exports.object({ + /** Type of event to wait for */ + eventType: external_exports.enum(["timer", "signal", "webhook", "manual", "condition"]).describe("What kind of event resumes the execution"), + /** Duration to wait (ISO 8601 duration or milliseconds) — for timer events */ + timerDuration: external_exports.string().optional().describe('ISO 8601 duration (e.g., "PT1H") or wait time for timer events'), + /** Signal name to listen for — for signal/webhook events */ + signalName: external_exports.string().optional().describe("Named signal or webhook event to wait for"), + /** Timeout before auto-failing or continuing — optional guard */ + timeoutMs: external_exports.number().int().min(0).optional().describe("Maximum wait time before timeout (ms)"), + /** Action to take on timeout */ + onTimeout: external_exports.enum(["fail", "continue"]).default("fail").describe("Behavior when the wait times out") + }).optional().describe("Configuration for wait node event resumption"), + /** + * Boundary Event Configuration (for 'boundary_event' nodes) + * Attaches an event handler to a host activity node (BPMN Boundary Event pattern). + * Industry alignment: BPMN Boundary Error/Timer/Signal Events. + */ + boundaryConfig: external_exports.object({ + /** ID of the host node this boundary event is attached to */ + attachedToNodeId: external_exports.string().describe("Host node ID this boundary event monitors"), + /** Type of boundary event */ + eventType: external_exports.enum(["error", "timer", "signal", "cancel"]).describe("Boundary event trigger type"), + /** Whether the boundary event interrupts the host activity */ + interrupting: external_exports.boolean().default(true).describe("If true, the host activity is cancelled when this event fires"), + /** Error code filter — only for error boundary events */ + errorCode: external_exports.string().optional().describe("Specific error code to catch (empty = catch all errors)"), + /** Timer duration — only for timer boundary events */ + timerDuration: external_exports.string().optional().describe("ISO 8601 duration for timer boundary events"), + /** Signal name — only for signal boundary events */ + signalName: external_exports.string().optional().describe("Named signal to catch") + }).optional().describe("Configuration for boundary events attached to host nodes") +}); +var FlowEdgeSchema = external_exports.object({ + id: external_exports.string().describe("Edge unique ID"), + source: external_exports.string().describe("Source Node ID"), + target: external_exports.string().describe("Target Node ID"), + /** Condition for this path (only for decision/branch nodes) */ + condition: external_exports.string().optional().describe("Expression returning boolean used for branching"), + type: external_exports.enum(["default", "fault", "conditional"]).default("default").describe("Connection type: default (normal flow), fault (error path), or conditional (expression-guarded)"), + label: external_exports.string().optional().describe("Label on the connector"), + /** + * Default Sequence Flow marker (BPMN Default Flow semantics). + * When true, this edge is taken when no sibling conditional edges match. + * Only meaningful on outgoing edges of decision/gateway nodes. + */ + isDefault: external_exports.boolean().default(false).describe("Marks this edge as the default path when no other conditions match") +}); +var FlowSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name"), + label: external_exports.string().describe("Flow label"), + description: external_exports.string().optional(), + /** Metadata & Versioning */ + version: external_exports.number().int().default(1).describe("Version number"), + status: external_exports.enum(["draft", "active", "obsolete", "invalid"]).default("draft").describe("Deployment status"), + template: external_exports.boolean().default(false).describe("Is logic template (Subflow)"), + /** Trigger Type */ + type: external_exports.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).describe("Flow type"), + /** Configuration Variables */ + variables: external_exports.array(FlowVariableSchema).optional().describe("Flow variables"), + /** Graph Definition */ + nodes: external_exports.array(FlowNodeSchema).describe("Flow nodes"), + edges: external_exports.array(FlowEdgeSchema).describe("Flow connections"), + /** Execution Config */ + active: external_exports.boolean().default(false).describe("Is active (Deprecated: use status)"), + runAs: external_exports.enum(["system", "user"]).default("user").describe("Execution context"), + /** Error Handling Strategy */ + errorHandling: external_exports.object({ + strategy: external_exports.enum(["fail", "retry", "continue"]).default("fail").describe("How to handle node execution errors"), + maxRetries: external_exports.number().int().min(0).max(10).default(0).describe("Number of retry attempts (only for retry strategy)"), + retryDelayMs: external_exports.number().int().min(0).default(1e3).describe("Delay between retries in milliseconds"), + backoffMultiplier: external_exports.number().min(1).default(1).describe("Multiplier for exponential backoff between retries"), + maxRetryDelayMs: external_exports.number().int().min(0).default(3e4).describe("Maximum delay between retries in milliseconds"), + jitter: external_exports.boolean().default(false).describe("Add random jitter to retry delay to avoid thundering herd"), + fallbackNodeId: external_exports.string().optional().describe("Node ID to jump to on unrecoverable error") + }).optional().describe("Flow-level error handling configuration") +}); +external_exports.object({ + flowName: external_exports.string().describe("Flow machine name"), + version: external_exports.number().int().min(1).describe("Version number"), + definition: FlowSchema.describe("Complete flow definition snapshot"), + createdAt: external_exports.string().datetime().describe("When this version was created"), + createdBy: external_exports.string().optional().describe("User who created this version"), + changeNote: external_exports.string().optional().describe("Description of what changed in this version") +}); +var ExecutionStatus = external_exports.enum([ + "pending", + // Queued, not yet started + "running", + // Currently executing + "paused", + // Paused at a wait/checkpoint node + "completed", + // Successfully finished + "failed", + // Terminated with error + "cancelled", + // Manually cancelled + "timed_out", + // Exceeded max execution time + "retrying" + // Failed and retrying +]); +var ExecutionStepLogSchema = external_exports.object({ + nodeId: external_exports.string().describe("Node ID that was executed"), + nodeType: external_exports.string().describe('Node action type (e.g., "decision", "http_request")'), + nodeLabel: external_exports.string().optional().describe("Human-readable node label"), + status: external_exports.enum(["success", "failure", "skipped"]).describe("Step execution result"), + startedAt: external_exports.string().datetime().describe("When the step started"), + completedAt: external_exports.string().datetime().optional().describe("When the step completed"), + durationMs: external_exports.number().int().min(0).optional().describe("Step execution duration in milliseconds"), + input: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Input data passed to the node"), + output: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Output data produced by the node"), + error: external_exports.object({ + code: external_exports.string().describe("Error code"), + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Stack trace") + }).optional().describe("Error details if step failed"), + retryAttempt: external_exports.number().int().min(0).optional().describe("Retry attempt number (0 = first try)") +}); +var ExecutionLogSchema = external_exports.object({ + /** Unique execution ID */ + id: external_exports.string().describe("Execution instance ID"), + /** Flow reference */ + flowName: external_exports.string().describe("Machine name of the executed flow"), + flowVersion: external_exports.number().int().optional().describe("Version of the flow that was executed"), + /** Execution status */ + status: ExecutionStatus.describe("Current execution status"), + /** Trigger context */ + trigger: external_exports.object({ + type: external_exports.string().describe('Trigger type (e.g., "record_change", "schedule", "api", "manual")'), + recordId: external_exports.string().optional().describe("Triggering record ID"), + object: external_exports.string().optional().describe("Triggering object name"), + userId: external_exports.string().optional().describe("User who triggered the execution"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional trigger context") + }).describe("What triggered this execution"), + /** Step-by-step execution history */ + steps: external_exports.array(ExecutionStepLogSchema).describe("Ordered list of executed steps"), + /** Execution variables snapshot */ + variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Final state of flow variables"), + /** Timing */ + startedAt: external_exports.string().datetime().describe("Execution start timestamp"), + completedAt: external_exports.string().datetime().optional().describe("Execution completion timestamp"), + durationMs: external_exports.number().int().min(0).optional().describe("Total execution duration in milliseconds"), + /** Context */ + runAs: external_exports.enum(["system", "user"]).optional().describe("Execution context identity"), + tenantId: external_exports.string().optional().describe("Tenant ID for multi-tenant isolation") +}); +var ExecutionErrorSeverity = external_exports.enum([ + "warning", + // Non-fatal issue (e.g., deprecated node type) + "error", + // Node-level failure (may be retried) + "critical" + // Flow-level failure (execution terminated) +]); +external_exports.object({ + id: external_exports.string().describe("Error record ID"), + executionId: external_exports.string().describe("Parent execution ID"), + nodeId: external_exports.string().optional().describe("Node where the error occurred"), + severity: ExecutionErrorSeverity.describe("Error severity level"), + code: external_exports.string().describe("Machine-readable error code"), + message: external_exports.string().describe("Human-readable error message"), + stack: external_exports.string().optional().describe("Stack trace for debugging"), + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional diagnostic context (input data, config snapshot)"), + timestamp: external_exports.string().datetime().describe("When the error occurred"), + retryable: external_exports.boolean().default(false).describe("Whether this error can be retried"), + resolvedAt: external_exports.string().datetime().optional().describe("When the error was resolved (e.g., after successful retry)") +}); +external_exports.object({ + /** Unique checkpoint ID */ + id: external_exports.string().describe("Checkpoint ID"), + /** Execution reference */ + executionId: external_exports.string().describe("Parent execution ID"), + flowName: external_exports.string().describe("Flow machine name"), + /** State snapshot */ + currentNodeId: external_exports.string().describe("Node ID where execution is paused"), + variables: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Flow variable state at checkpoint"), + completedNodeIds: external_exports.array(external_exports.string()).describe("List of node IDs already executed"), + /** Timing */ + createdAt: external_exports.string().datetime().describe("Checkpoint creation timestamp"), + expiresAt: external_exports.string().datetime().optional().describe("Checkpoint expiration (auto-cleanup)"), + /** Reason */ + reason: external_exports.enum(["wait", "screen_input", "approval", "error", "manual_pause", "parallel_join", "boundary_event"]).describe("Why the execution was checkpointed") +}); +external_exports.object({ + /** Maximum concurrent executions of this flow */ + maxConcurrent: external_exports.number().int().min(1).default(1).describe("Maximum number of concurrent executions allowed"), + /** What to do when max concurrency is reached */ + onConflict: external_exports.enum(["queue", "reject", "cancel_existing"]).default("queue").describe("queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance"), + /** Lock scope for concurrency */ + lockScope: external_exports.enum(["global", "per_record", "per_user"]).default("global").describe("Scope of the concurrency lock"), + /** Queue timeout (only when onConflict is "queue") */ + queueTimeoutMs: external_exports.number().int().min(0).optional().describe("Maximum time to wait in queue before timing out (ms)") +}); +external_exports.object({ + /** Unique schedule ID */ + id: external_exports.string().describe("Schedule instance ID"), + /** Flow reference */ + flowName: external_exports.string().describe("Flow machine name"), + /** Schedule configuration */ + cronExpression: external_exports.string().describe('Cron expression (e.g., "0 9 * * MON-FRI")'), + timezone: external_exports.string().default("UTC").describe("IANA timezone for cron evaluation"), + /** Runtime state */ + status: external_exports.enum(["active", "paused", "disabled", "expired"]).default("active").describe("Current schedule status"), + nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution timestamp"), + lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp"), + lastExecutionId: external_exports.string().optional().describe("Execution ID of the last run"), + lastRunStatus: ExecutionStatus.optional().describe("Status of the last run"), + /** Execution tracking */ + totalRuns: external_exports.number().int().min(0).default(0).describe("Total number of executions"), + consecutiveFailures: external_exports.number().int().min(0).default(0).describe("Consecutive failed executions"), + /** Bounds */ + startDate: external_exports.string().datetime().optional().describe("Schedule effective start date"), + endDate: external_exports.string().datetime().optional().describe("Schedule expiration date"), + maxRuns: external_exports.number().int().min(1).optional().describe("Maximum total executions before auto-disable"), + /** Metadata */ + createdAt: external_exports.string().datetime().describe("Schedule creation timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + createdBy: external_exports.string().optional().describe("User who created the schedule") +}); +var AutomationFlowPathParamsSchema = external_exports.object({ + name: external_exports.string().describe("Flow machine name (snake_case)") +}); +var AutomationRunPathParamsSchema = AutomationFlowPathParamsSchema.extend({ + runId: external_exports.string().describe("Execution run ID") +}); +var ListFlowsRequestSchema = external_exports.object({ + status: external_exports.enum(["draft", "active", "obsolete", "invalid"]).optional().describe("Filter by flow status"), + type: external_exports.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).optional().describe("Filter by flow type"), + limit: external_exports.number().int().min(1).max(100).default(50).describe("Maximum number of flows to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination") +}); +var FlowSummarySchema = external_exports.object({ + name: external_exports.string().describe("Flow machine name"), + label: external_exports.string().describe("Flow display label"), + type: external_exports.string().describe("Flow type"), + status: external_exports.string().describe("Flow deployment status"), + version: external_exports.number().int().describe("Flow version number"), + enabled: external_exports.boolean().describe("Whether the flow is enabled for execution"), + nodeCount: external_exports.number().int().optional().describe("Number of nodes in the flow"), + lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp") +}); +var ListFlowsResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + flows: external_exports.array(FlowSummarySchema).describe("Flow summaries"), + total: external_exports.number().int().optional().describe("Total matching flows"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more flows are available") + }) +}); +var GetFlowResponseSchema = BaseResponseSchema.extend({ + data: FlowSchema.describe("Full flow definition") +}); +var CreateFlowResponseSchema = BaseResponseSchema.extend({ + data: FlowSchema.describe("The created flow definition") +}); +var UpdateFlowRequestSchema = AutomationFlowPathParamsSchema.extend({ + definition: FlowSchema.partial().describe("Partial flow definition to update") +}); +var UpdateFlowResponseSchema = BaseResponseSchema.extend({ + data: FlowSchema.describe("The updated flow definition") +}); +var DeleteFlowResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + name: external_exports.string().describe("Name of the deleted flow"), + deleted: external_exports.boolean().describe("Whether the flow was deleted") + }) +}); +var TriggerFlowRequestSchema = AutomationFlowPathParamsSchema.extend({ + record: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record that triggered the automation"), + object: external_exports.string().optional().describe("Object name the record belongs to"), + event: external_exports.string().optional().describe("Trigger event type"), + userId: external_exports.string().optional().describe("User who triggered the automation"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional contextual data") +}); +var TriggerFlowResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + success: external_exports.boolean().describe("Whether the automation completed successfully"), + output: external_exports.unknown().optional().describe("Output data from the automation"), + error: external_exports.string().optional().describe("Error message if execution failed"), + durationMs: external_exports.number().optional().describe("Execution duration in milliseconds") + }) +}); +var ToggleFlowRequestSchema = AutomationFlowPathParamsSchema.extend({ + enabled: external_exports.boolean().describe("Whether to enable (true) or disable (false) the flow") +}); +var ToggleFlowResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + name: external_exports.string().describe("Flow name"), + enabled: external_exports.boolean().describe("New enabled state") + }) +}); +var ListRunsRequestSchema = AutomationFlowPathParamsSchema.extend({ + status: external_exports.enum(["pending", "running", "paused", "completed", "failed", "cancelled", "timed_out", "retrying"]).optional().describe("Filter by execution status"), + limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of runs to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination") +}); +var ListRunsResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + runs: external_exports.array(ExecutionLogSchema).describe("Execution run logs"), + total: external_exports.number().int().optional().describe("Total matching runs"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more runs are available") + }) +}); +var GetRunResponseSchema = BaseResponseSchema.extend({ + data: ExecutionLogSchema.describe("Full execution log with step details") +}); +var AutomationApiErrorCode = external_exports.enum([ + "flow_not_found", + "flow_already_exists", + "flow_validation_failed", + "flow_disabled", + "execution_not_found", + "execution_failed", + "execution_timeout", + "node_executor_not_found", + "concurrent_execution_limit" +]); +var MetadataChangeTypeSchema = external_exports.enum([ + "added", + // New metadata item added in new version + "modified", + // Existing metadata item modified + "removed", + // Metadata item removed in new version + "renamed" + // Metadata item renamed +]).describe("Type of metadata change between package versions"); +var MetadataDiffItemSchema = external_exports.object({ + /** Metadata type (e.g. "object", "view", "flow") */ + type: external_exports.string().describe("Metadata type"), + /** Metadata name */ + name: external_exports.string().describe("Metadata name"), + /** Type of change */ + changeType: MetadataChangeTypeSchema.describe("Category of metadata modification (added, modified, removed, or renamed)"), + /** Whether this change has potential conflicts with customizations */ + hasConflict: external_exports.boolean().default(false).describe("Whether this change may conflict with customizations"), + /** Human-readable summary of the change */ + summary: external_exports.string().optional().describe("Human-readable change summary"), + /** Previous name (for renames) */ + previousName: external_exports.string().optional().describe("Previous name if renamed") +}).describe("Single metadata change between package versions"); +var UpgradeImpactLevelSchema = external_exports.enum([ + "none", + // No impact, seamless upgrade + "low", + // Minor changes, no user action needed + "medium", + // Some changes that may affect workflows + "high", + // Significant changes, user review recommended + "critical" + // Breaking changes, manual intervention required +]).describe("Severity of upgrade impact"); +var UpgradePlanSchema = external_exports.object({ + /** Package being upgraded */ + packageId: external_exports.string().describe("Package identifier"), + /** Current installed version */ + fromVersion: external_exports.string().describe("Currently installed version"), + /** Target version to upgrade to */ + toVersion: external_exports.string().describe("Target upgrade version"), + /** Overall impact level */ + impactLevel: UpgradeImpactLevelSchema.describe("Severity assessment from none (seamless) to critical (breaking changes)"), + /** List of all metadata changes between versions */ + changes: external_exports.array(MetadataDiffItemSchema).describe("All metadata changes"), + /** Number of customer customizations that may be affected */ + affectedCustomizations: external_exports.number().int().min(0).default(0).describe("Count of customizations that may be affected"), + /** Whether any migration scripts need to run */ + requiresMigration: external_exports.boolean().default(false).describe("Whether data migration scripts are needed"), + /** Migration script paths (relative to package root) */ + migrationScripts: external_exports.array(external_exports.string()).optional().describe("Paths to migration scripts"), + /** Dependencies that also need upgrading */ + dependencyUpgrades: external_exports.array(external_exports.object({ + packageId: external_exports.string(), + fromVersion: external_exports.string(), + toVersion: external_exports.string() + })).optional().describe("Dependent packages that also need upgrading"), + /** Estimated upgrade duration in seconds */ + estimatedDuration: external_exports.number().int().min(0).optional().describe("Estimated upgrade duration in seconds"), + /** Human-readable summary */ + summary: external_exports.string().optional().describe("Human-readable upgrade summary") +}).describe("Upgrade analysis plan generated before execution"); +external_exports.object({ + /** Snapshot ID (UUID) */ + id: external_exports.string().describe("Snapshot identifier"), + /** Package being upgraded */ + packageId: external_exports.string().describe("Package identifier"), + /** Version being upgraded from */ + fromVersion: external_exports.string().describe("Version before upgrade"), + /** Version being upgraded to */ + toVersion: external_exports.string().describe("Target upgrade version"), + /** Tenant ID */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** Complete manifest of the old package version */ + previousManifest: ManifestSchema.describe("Complete manifest of the previous package version"), + /** + * Snapshot of all metadata records owned by this package. + * Stored as array of { type, name, metadata } tuples. + */ + metadataSnapshot: external_exports.array(external_exports.object({ + type: external_exports.string(), + name: external_exports.string(), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()) + })).describe("Snapshot of all package metadata"), + /** + * Snapshot of all customer customizations (overlays) for this package's metadata. + */ + customizationSnapshot: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Snapshot of customer customizations"), + /** When the snapshot was created */ + createdAt: external_exports.string().datetime().describe("Snapshot creation timestamp"), + /** Expiry time for snapshot cleanup */ + expiresAt: external_exports.string().datetime().optional().describe("Snapshot expiry timestamp") +}).describe("Pre-upgrade state snapshot for rollback capability"); +external_exports.object({ + /** Package ID to upgrade */ + packageId: external_exports.string().describe("Package ID to upgrade"), + /** Target version (if omitted, upgrades to latest) */ + targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), + /** New manifest for the target version */ + manifest: ManifestSchema.optional().describe("New manifest (if installing from local)"), + /** Whether to create a pre-upgrade snapshot */ + createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), + /** Merge strategy for handling customizations */ + mergeStrategy: external_exports.enum([ + "keep-custom", + "accept-incoming", + "three-way-merge" + ]).default("three-way-merge").describe("How to handle customer customizations"), + /** Whether to run in dry-run mode (preview only, no changes) */ + dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), + /** Whether to skip pre-upgrade validation */ + skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") +}).describe("Upgrade package request"); +var UpgradePhaseSchema = external_exports.enum([ + "pending", + // Upgrade requested but not started + "analyzing", + // Generating upgrade plan + "snapshot", + // Creating pre-upgrade snapshot + "executing", + // Applying metadata changes + "migrating", + // Running migration scripts + "validating", + // Post-upgrade validation + "completed", + // Upgrade completed successfully + "failed", + // Upgrade failed + "rolling-back", + // Rollback in progress + "rolled-back" + // Rollback completed +]).describe("Current phase of the upgrade process"); +external_exports.object({ + /** Whether the upgrade was successful */ + success: external_exports.boolean().describe("Whether the upgrade succeeded"), + /** Current upgrade phase */ + phase: UpgradePhaseSchema.describe("Current upgrade phase"), + /** The upgrade plan that was executed */ + plan: UpgradePlanSchema.optional().describe("Upgrade plan"), + /** Snapshot ID for rollback */ + snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), + /** Merge conflicts that need manual resolution (if any) */ + conflicts: external_exports.array(external_exports.object({ + path: external_exports.string(), + baseValue: external_exports.unknown(), + incomingValue: external_exports.unknown(), + customValue: external_exports.unknown() + })).optional().describe("Unresolved merge conflicts"), + /** Error message (if failed) */ + errorMessage: external_exports.string().optional().describe("Error message if upgrade failed"), + /** Human-readable summary */ + message: external_exports.string().optional().describe("Human-readable status message") +}).describe("Upgrade package response"); +external_exports.object({ + /** Package ID to rollback */ + packageId: external_exports.string().describe("Package ID to rollback"), + /** Snapshot ID to restore from */ + snapshotId: external_exports.string().describe("Snapshot ID to restore from"), + /** Whether to also rollback customizations */ + rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") +}).describe("Rollback package request"); +external_exports.object({ + /** Whether the rollback was successful */ + success: external_exports.boolean().describe("Whether the rollback succeeded"), + /** Restored version */ + restoredVersion: external_exports.string().optional().describe("Version restored to"), + /** Message */ + message: external_exports.string().optional().describe("Rollback status message") +}).describe("Rollback package response"); +var MetadataCategoryEnum = external_exports.enum([ + "objects", + "views", + "pages", + "flows", + "dashboards", + "permissions", + "agents", + "reports", + "actions", + "translations", + "themes", + "datasets", + "apis", + "triggers", + "workflows" +]).describe("Metadata category within the artifact"); +var ArtifactFileEntrySchema = external_exports.object({ + /** Relative path within the artifact (e.g. "metadata/objects/account.object.json") */ + path: external_exports.string().describe("Relative file path within the artifact"), + /** File size in bytes */ + size: external_exports.number().int().nonnegative().describe("File size in bytes"), + /** Metadata category (if under metadata/) */ + category: MetadataCategoryEnum.optional().describe("Metadata category this file belongs to") +}).describe("A single file entry within the artifact"); +var ArtifactChecksumSchema = external_exports.object({ + /** Hash algorithm used (default: SHA256) */ + algorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm used for checksums"), + /** Map of relative file paths to their hash values */ + files: external_exports.record(external_exports.string(), external_exports.string().regex(/^[a-f0-9]+$/)).describe("File path to hash value mapping") +}).describe("Checksum manifest for artifact integrity verification"); +var ArtifactSignatureSchema = external_exports.object({ + /** Signature algorithm */ + algorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).default("RSA-SHA256").describe("Signing algorithm used"), + /** Public key reference (URL or fingerprint) for verification */ + publicKeyRef: external_exports.string().describe("Public key reference (URL or fingerprint) for signature verification"), + /** Base64-encoded signature value */ + signature: external_exports.string().describe("Base64-encoded digital signature"), + /** Timestamp of when the artifact was signed */ + signedAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp of when the artifact was signed"), + /** Signer identity (publisher ID or email) */ + signedBy: external_exports.string().optional().describe("Identity of the signer (publisher ID or email)") +}).describe("Digital signature for artifact authenticity verification"); +var PackageArtifactSchema = external_exports.object({ + /** Artifact format version (for forward compatibility) */ + formatVersion: external_exports.string().regex(/^\d+\.\d+$/).default("1.0").describe('Artifact format version (e.g. "1.0")'), + /** Package ID from the manifest */ + packageId: external_exports.string().describe("Package identifier from manifest"), + /** Package version from the manifest */ + version: external_exports.string().describe("Package version from manifest"), + /** Artifact format */ + format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format of the artifact"), + /** Total artifact size in bytes */ + size: external_exports.number().int().positive().optional().describe("Total artifact file size in bytes"), + /** Build timestamp */ + builtAt: external_exports.string().datetime().describe("ISO 8601 timestamp of when the artifact was built"), + /** Build tool and version that produced this artifact */ + builtWith: external_exports.string().optional().describe('Build tool identifier (e.g. "os-cli@3.2.0")'), + /** File listing within the artifact */ + files: external_exports.array(ArtifactFileEntrySchema).optional().describe("List of files contained in the artifact"), + /** Metadata categories present in the artifact */ + metadataCategories: external_exports.array(MetadataCategoryEnum).optional().describe("Metadata categories included in this artifact"), + /** Integrity checksums for all files */ + checksums: ArtifactChecksumSchema.optional().describe("SHA256 checksums for artifact integrity verification"), + /** Digital signature for authenticity */ + signature: ArtifactSignatureSchema.optional().describe("Digital signature for artifact authenticity verification") +}).describe("Package artifact structure and metadata"); +var PublisherVerificationSchema = external_exports.enum([ + "unverified", + // Not yet verified + "pending", + // Verification in progress + "verified", + // Identity verified by platform + "trusted", + // Trusted publisher (track record of quality) + "partner" + // Official platform partner +]).describe("Publisher verification status"); +external_exports.object({ + /** Publisher unique identifier */ + id: external_exports.string().describe("Publisher ID"), + /** Display name */ + name: external_exports.string().describe("Publisher display name"), + /** Publisher type */ + type: external_exports.enum(["individual", "organization"]).describe("Publisher type"), + /** Verification status */ + verification: PublisherVerificationSchema.default("unverified").describe("Publisher verification status"), + /** Contact email */ + email: external_exports.string().email().optional().describe("Contact email"), + /** Website URL */ + website: external_exports.string().url().optional().describe("Publisher website"), + /** Organization logo URL */ + logoUrl: external_exports.string().url().optional().describe("Publisher logo URL"), + /** Short description/bio */ + description: external_exports.string().optional().describe("Publisher description"), + /** Registration date */ + registeredAt: external_exports.string().datetime().optional().describe("Publisher registration timestamp") +}).describe("Developer or organization that publishes packages"); +var ArtifactReferenceSchema = external_exports.object({ + /** Artifact download URL */ + url: external_exports.string().url().describe("Artifact download URL"), + /** SHA256 integrity checksum */ + sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).describe("SHA256 checksum"), + /** File size in bytes */ + size: external_exports.number().int().positive().describe("Artifact size in bytes"), + /** Artifact format */ + format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Artifact format"), + /** Upload timestamp */ + uploadedAt: external_exports.string().datetime().describe("Upload timestamp") +}).describe("Reference to a downloadable package artifact"); +external_exports.object({ + /** Pre-signed or direct download URL */ + downloadUrl: external_exports.string().url().describe("Artifact download URL (may be pre-signed)"), + /** SHA256 checksum for download verification */ + sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).describe("SHA256 checksum for verification"), + /** File size in bytes */ + size: external_exports.number().int().positive().describe("Artifact size in bytes"), + /** Artifact format */ + format: external_exports.enum(["tgz", "zip"]).describe("Artifact format"), + /** URL expiration time (for pre-signed URLs) */ + expiresAt: external_exports.string().datetime().optional().describe("URL expiration timestamp for pre-signed URLs") +}).describe("Artifact download response with integrity metadata"); +var MarketplaceCategorySchema = external_exports.enum([ + "crm", + // Customer Relationship Management + "erp", + // Enterprise Resource Planning + "hr", + // Human Resources + "finance", + // Finance & Accounting + "project", + // Project Management + "collaboration", + // Collaboration & Communication + "analytics", + // Analytics & Reporting + "integration", + // Integrations & Connectors + "automation", + // Automation & Workflows + "ai", + // AI & Machine Learning + "security", + // Security & Compliance + "developer-tools", + // Developer Tools + "ui-theme", + // UI Themes & Appearance + "storage", + // Storage & Drivers + "other" + // Other / Uncategorized +]).describe("Marketplace package category"); +var ListingStatusSchema = external_exports.enum([ + "draft", + // Not yet submitted + "submitted", + // Submitted for review + "in-review", + // Under review + "approved", + // Approved, ready to publish + "published", + // Live on marketplace + "rejected", + // Review rejected + "suspended", + // Suspended by platform (policy violation) + "deprecated", + // Deprecated by publisher + "unlisted" + // Available by direct link only +]).describe("Marketplace listing status"); +var PricingModelSchema = external_exports.enum([ + "free", + // Free to install + "freemium", + // Free with paid premium features + "paid", + // Requires purchase + "subscription", + // Recurring subscription + "usage-based", + // Pay per usage + "contact-sales" + // Enterprise pricing, contact for quote +]).describe("Package pricing model"); +var MarketplaceListingSchema = external_exports.object({ + /** Listing ID (matches package ID) */ + id: external_exports.string().describe("Listing ID (matches package manifest ID)"), + /** Package ID (reverse domain notation) */ + packageId: external_exports.string().describe("Package identifier"), + /** Publisher information */ + publisherId: external_exports.string().describe("Publisher ID"), + /** Current listing status */ + status: ListingStatusSchema.default("draft").describe("Publication state: draft, published, under-review, suspended, deprecated, or unlisted"), + /** Display name */ + name: external_exports.string().describe("Display name"), + /** Tagline (short description for cards/search results) */ + tagline: external_exports.string().max(120).optional().describe("Short tagline (max 120 chars)"), + /** Full description (supports Markdown) */ + description: external_exports.string().optional().describe("Full description (Markdown)"), + /** Category */ + category: MarketplaceCategorySchema.describe("Package category"), + /** Additional tags for search discovery */ + tags: external_exports.array(external_exports.string()).optional().describe("Search tags"), + /** Icon/logo URL */ + iconUrl: external_exports.string().url().optional().describe("Package icon URL"), + /** Screenshot URLs */ + screenshots: external_exports.array(external_exports.object({ + url: external_exports.string().url(), + caption: external_exports.string().optional() + })).optional().describe("Screenshots"), + /** Documentation URL */ + documentationUrl: external_exports.string().url().optional().describe("Documentation URL"), + /** Support URL */ + supportUrl: external_exports.string().url().optional().describe("Support URL"), + /** Source repository URL (if open source) */ + repositoryUrl: external_exports.string().url().optional().describe("Source repository URL"), + /** Pricing model */ + pricing: PricingModelSchema.default("free").describe("Pricing model"), + /** Price in cents (if paid) */ + priceInCents: external_exports.number().int().min(0).optional().describe("Price in cents (e.g. 999 = $9.99)"), + /** Latest published version */ + latestVersion: external_exports.string().describe("Latest published version"), + /** Minimum platform version required */ + minPlatformVersion: external_exports.string().optional().describe("Minimum ObjectStack platform version"), + /** Available versions for installation */ + versions: external_exports.array(external_exports.object({ + version: external_exports.string().describe("Version string"), + releaseDate: external_exports.string().datetime().describe("Release date"), + releaseNotes: external_exports.string().optional().describe("Release notes"), + minPlatformVersion: external_exports.string().optional().describe("Minimum platform version"), + deprecated: external_exports.boolean().default(false).describe("Whether this version is deprecated"), + /** Artifact reference for this version */ + artifact: ArtifactReferenceSchema.optional().describe("Downloadable artifact for this version") + })).optional().describe("Published versions"), + /** Aggregate statistics */ + stats: external_exports.object({ + totalInstalls: external_exports.number().int().min(0).default(0).describe("Total installs"), + activeInstalls: external_exports.number().int().min(0).default(0).describe("Active installs"), + averageRating: external_exports.number().min(0).max(5).optional().describe("Average user rating (0-5)"), + totalRatings: external_exports.number().int().min(0).default(0).describe("Total ratings count"), + totalReviews: external_exports.number().int().min(0).default(0).describe("Total reviews count") + }).optional().describe("Aggregate marketplace statistics"), + /** First published date */ + publishedAt: external_exports.string().datetime().optional().describe("First published timestamp"), + /** Last updated date */ + updatedAt: external_exports.string().datetime().optional().describe("Last updated timestamp") +}).describe("Public-facing package listing on the marketplace"); +external_exports.object({ + /** Submission ID */ + id: external_exports.string().describe("Submission ID"), + /** Package ID */ + packageId: external_exports.string().describe("Package identifier"), + /** Version being submitted */ + version: external_exports.string().describe("Version being submitted"), + /** Publisher ID */ + publisherId: external_exports.string().describe("Publisher submitting"), + /** Submission status */ + status: external_exports.enum([ + "pending", + // Awaiting review + "scanning", + // Automated scan in progress + "in-review", + // Under manual review + "changes-requested", + // Reviewer requests changes + "approved", + // Approved for publishing + "rejected" + // Rejected + ]).default("pending").describe("Review status"), + /** + * Package artifact URL or reference. + * Points to the built package bundle for review. + */ + artifactUrl: external_exports.string().describe("Package artifact URL for review"), + /** Release notes for this version */ + releaseNotes: external_exports.string().optional().describe("Release notes for this version"), + /** Whether this is the first submission (new listing) vs version update */ + isNewListing: external_exports.boolean().default(false).describe("Whether this is a new listing submission"), + /** Automated scan results */ + scanResults: external_exports.object({ + /** Whether automated scan passed */ + passed: external_exports.boolean(), + /** Security scan score (0-100) */ + securityScore: external_exports.number().min(0).max(100).optional(), + /** Compatibility check passed */ + compatibilityCheck: external_exports.boolean().optional(), + /** Issues found during scan */ + issues: external_exports.array(external_exports.object({ + severity: external_exports.enum(["critical", "high", "medium", "low", "info"]), + message: external_exports.string(), + file: external_exports.string().optional(), + line: external_exports.number().optional() + })).optional() + }).optional().describe("Automated scan results"), + /** Reviewer notes (from platform reviewer) */ + reviewerNotes: external_exports.string().optional().describe("Notes from the platform reviewer"), + /** Submitted timestamp */ + submittedAt: external_exports.string().datetime().optional().describe("Submission timestamp"), + /** Review completed timestamp */ + reviewedAt: external_exports.string().datetime().optional().describe("Review completion timestamp") +}).describe("Developer submission of a package version for review"); +external_exports.object({ + /** Search query string */ + query: external_exports.string().optional().describe("Full-text search query"), + /** Filter by category */ + category: MarketplaceCategorySchema.optional().describe("Filter by category"), + /** Filter by tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), + /** Filter by pricing model */ + pricing: PricingModelSchema.optional().describe("Filter by pricing model"), + /** Filter by publisher verification level */ + publisherVerification: PublisherVerificationSchema.optional().describe("Filter by publisher verification level"), + /** Sort by */ + sortBy: external_exports.enum([ + "relevance", + // Best match (default for search) + "popularity", + // Most installs + "rating", + // Highest rated + "newest", + // Most recently published + "updated", + // Most recently updated + "name" + // Alphabetical + ]).default("relevance").describe("Sort field"), + /** Sort direction */ + sortDirection: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction"), + /** Pagination: page number */ + page: external_exports.number().int().min(1).default(1).describe("Page number"), + /** Pagination: items per page */ + pageSize: external_exports.number().int().min(1).max(100).default(20).describe("Items per page"), + /** Filter by minimum platform version compatibility */ + platformVersion: external_exports.string().optional().describe("Filter by platform version compatibility") +}).describe("Marketplace search request"); +external_exports.object({ + /** Search results */ + items: external_exports.array(MarketplaceListingSchema).describe("Search result listings"), + /** Total count (for pagination) */ + total: external_exports.number().int().min(0).describe("Total matching results"), + /** Current page */ + page: external_exports.number().int().min(1).describe("Current page number"), + /** Items per page */ + pageSize: external_exports.number().int().min(1).describe("Items per page"), + /** Facets for filtering */ + facets: external_exports.object({ + categories: external_exports.array(external_exports.object({ + category: MarketplaceCategorySchema, + count: external_exports.number().int().min(0) + })).optional(), + pricing: external_exports.array(external_exports.object({ + model: PricingModelSchema, + count: external_exports.number().int().min(0) + })).optional() + }).optional().describe("Aggregation facets for refining search") +}).describe("Marketplace search response"); +external_exports.object({ + /** Listing ID to install */ + listingId: external_exports.string().describe("Marketplace listing ID"), + /** Specific version to install (defaults to latest) */ + version: external_exports.string().optional().describe("Version to install"), + /** License key (for paid packages) */ + licenseKey: external_exports.string().optional().describe("License key for paid packages"), + /** User-provided settings at install time */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), + /** Whether to enable immediately after install */ + enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), + /** Artifact reference (resolved from listing version, or provided directly) */ + artifactRef: ArtifactReferenceSchema.optional().describe("Artifact reference for direct installation"), + /** Tenant ID */ + tenantId: external_exports.string().optional().describe("Tenant identifier") +}).describe("Install from marketplace request"); +external_exports.object({ + /** Whether installation was successful */ + success: external_exports.boolean().describe("Whether installation succeeded"), + /** Installed package ID */ + packageId: external_exports.string().optional().describe("Installed package identifier"), + /** Installed version */ + version: external_exports.string().optional().describe("Installed version"), + /** Human-readable message */ + message: external_exports.string().optional().describe("Installation status message") +}).describe("Install from marketplace response"); +var PackagePathParamsSchema = external_exports.object({ + packageId: external_exports.string().describe("Package identifier") +}); +var ListInstalledPackagesRequestSchema = external_exports.object({ + /** Filter by package status */ + status: external_exports.enum(["installed", "disabled", "installing", "upgrading", "uninstalling", "error"]).optional().describe("Filter by package status"), + /** Filter by enabled state */ + enabled: external_exports.boolean().optional().describe("Filter by enabled state"), + /** Maximum number of packages to return */ + limit: external_exports.number().int().min(1).max(100).default(50).describe("Maximum number of packages to return"), + /** Cursor for pagination */ + cursor: external_exports.string().optional().describe("Cursor for pagination") +}).describe("List installed packages request"); +var ListInstalledPackagesResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + packages: external_exports.array(InstalledPackageSchema).describe("Installed packages"), + total: external_exports.number().int().optional().describe("Total matching packages"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more packages are available") + }) +}).describe("List installed packages response"); +var GetInstalledPackageResponseSchema = BaseResponseSchema.extend({ + data: InstalledPackageSchema.describe("Installed package details") +}).describe("Get installed package response"); +var PackageInstallRequestSchema = external_exports.object({ + /** Package manifest to install */ + manifest: ManifestSchema.describe("Package manifest to install"), + /** User-provided settings at install time */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), + /** Whether to enable immediately after install */ + enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), + /** Current platform version for compatibility verification */ + platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification"), + /** Artifact reference for the package (if installing from marketplace) */ + artifactRef: ArtifactReferenceSchema.optional().describe("Artifact reference for marketplace installation") +}).describe("Install package request"); +var PackageInstallResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + package: InstalledPackageSchema.describe("Installed package details"), + dependencyResolution: DependencyResolutionResultSchema.optional().describe("Dependency resolution result"), + namespaceConflicts: external_exports.array(external_exports.object({ + type: external_exports.literal("namespace_conflict").describe("Error type"), + requestedNamespace: external_exports.string().describe("Requested namespace"), + conflictingPackageId: external_exports.string().describe("Conflicting package ID"), + conflictingPackageName: external_exports.string().describe("Conflicting package name"), + suggestion: external_exports.string().optional().describe("Suggested alternative") + })).optional().describe("Namespace conflicts detected"), + message: external_exports.string().optional().describe("Installation status message") + }) +}).describe("Install package response"); +var PackageUpgradeRequestSchema = external_exports.object({ + /** Package ID to upgrade */ + packageId: external_exports.string().describe("Package ID to upgrade"), + /** Target version (defaults to latest) */ + targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), + /** New manifest for the target version */ + manifest: ManifestSchema.optional().describe("New manifest for the target version"), + /** Whether to create a pre-upgrade snapshot */ + createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), + /** Merge strategy for handling customizations */ + mergeStrategy: external_exports.enum(["keep-custom", "accept-incoming", "three-way-merge"]).default("three-way-merge").describe("How to handle customer customizations"), + /** Preview upgrade without making changes */ + dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), + /** Skip pre-upgrade compatibility checks */ + skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") +}).describe("Upgrade package request"); +var PackageUpgradeResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + success: external_exports.boolean().describe("Whether the upgrade succeeded"), + phase: external_exports.string().describe("Current upgrade phase"), + plan: UpgradePlanSchema.optional().describe("Upgrade plan that was executed"), + snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), + conflicts: external_exports.array(external_exports.object({ + path: external_exports.string().describe("Conflict path"), + baseValue: external_exports.unknown().describe("Base value"), + incomingValue: external_exports.unknown().describe("Incoming value"), + customValue: external_exports.unknown().describe("Custom value") + })).optional().describe("Unresolved merge conflicts"), + errorMessage: external_exports.string().optional().describe("Error message if failed"), + message: external_exports.string().optional().describe("Human-readable status message") + }) +}).describe("Upgrade package response"); +var ResolveDependenciesRequestSchema = external_exports.object({ + /** Package manifest whose dependencies to resolve */ + manifest: ManifestSchema.describe("Package manifest to resolve dependencies for"), + /** Current platform version for compatibility checking */ + platformVersion: external_exports.string().optional().describe("Current platform version for compatibility filtering") +}).describe("Resolve dependencies request"); +var ResolveDependenciesResponseSchema = BaseResponseSchema.extend({ + data: DependencyResolutionResultSchema.describe("Dependency resolution result with topological sort") +}).describe("Resolve dependencies response"); +var UploadArtifactRequestSchema = external_exports.object({ + /** Artifact metadata */ + artifact: PackageArtifactSchema.describe("Package artifact metadata"), + /** SHA256 checksum of the uploaded file (for verification) */ + sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).optional().describe("SHA256 checksum of the uploaded file"), + /** Publisher authentication token */ + token: external_exports.string().optional().describe("Publisher authentication token"), + /** Release notes for this version */ + releaseNotes: external_exports.string().optional().describe("Release notes for this version") +}).describe("Upload artifact request"); +var UploadArtifactResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + /** Whether the upload succeeded */ + success: external_exports.boolean().describe("Whether the upload succeeded"), + /** Artifact reference for the uploaded package */ + artifactRef: ArtifactReferenceSchema.optional().describe("Artifact reference in the registry"), + /** Submission ID for review tracking */ + submissionId: external_exports.string().optional().describe("Marketplace submission ID for review tracking"), + /** Message */ + message: external_exports.string().optional().describe("Upload status message") + }) +}).describe("Upload artifact response"); +var PackageRollbackRequestSchema = PackagePathParamsSchema.extend({ + /** Snapshot ID to restore from */ + snapshotId: external_exports.string().describe("Snapshot ID to restore from"), + /** Whether to also rollback customizations */ + rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") +}).describe("Rollback package request"); +var PackageRollbackResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + success: external_exports.boolean().describe("Whether the rollback succeeded"), + restoredVersion: external_exports.string().optional().describe("Restored version"), + message: external_exports.string().optional().describe("Rollback status message") + }) +}).describe("Rollback package response"); +var UninstallPackageApiResponseSchema = BaseResponseSchema.extend({ + data: external_exports.object({ + packageId: external_exports.string().describe("Uninstalled package ID"), + success: external_exports.boolean().describe("Whether uninstall succeeded"), + message: external_exports.string().optional().describe("Uninstall status message") + }) +}).describe("Uninstall package response"); +var PackageApiErrorCode = external_exports.enum([ + "package_not_found", + "package_already_installed", + "version_not_found", + "dependency_conflict", + "namespace_conflict", + "platform_incompatible", + "artifact_invalid", + "checksum_mismatch", + "signature_invalid", + "upgrade_failed", + "rollback_failed", + "snapshot_not_found", + "upload_failed" +]); + +// ../../packages/core/dist/index.js +import nodePath from "path"; +var __defProp2 = Object.defineProperty; +var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); +}; +var isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null; +function getEnv(key, defaultValue) { + if (typeof process !== "undefined" && process.env) { + return process.env[key] || defaultValue; + } + try { + if (typeof globalThis !== "undefined" && globalThis.process?.env) { + return globalThis.process.env[key] || defaultValue; + } + } catch (e) { + } + return defaultValue; +} +function safeExit(code = 0) { + if (isNode) { + process.exit(code); + } +} +function getMemoryUsage() { + if (isNode) { + return process.memoryUsage(); + } + return { heapUsed: 0, heapTotal: 0 }; +} +var ObjectLogger = class _ObjectLogger { + // CommonJS require function for Node.js + constructor(config4 = {}) { + this.isNode = isNode; + this.config = { + name: config4.name, + level: config4.level ?? "info", + format: config4.format ?? (this.isNode ? "json" : "pretty"), + redact: config4.redact ?? ["password", "token", "secret", "key"], + sourceLocation: config4.sourceLocation ?? false, + file: config4.file, + rotation: config4.rotation ?? { + maxSize: "10m", + maxFiles: 5 + } + }; + if (this.isNode) { + this.initPinoLogger(); + } + } + /** + * Initialize Pino logger for Node.js + */ + async initPinoLogger() { + if (!this.isNode) return; + try { + const { createRequire } = await import("module"); + this.require = createRequire(import.meta.url); + const pino = this.require("pino"); + const pinoOptions = { + level: this.config.level, + redact: { + paths: this.config.redact, + censor: "***REDACTED***" + } + }; + if (this.config.name) { + pinoOptions.name = this.config.name; + } + const targets = []; + if (this.config.format === "pretty") { + let hasPretty = false; + try { + this.require.resolve("pino-pretty"); + hasPretty = true; + } catch (e) { + } + if (hasPretty) { + targets.push({ + target: "pino-pretty", + options: { + colorize: true, + translateTime: "SYS:standard", + ignore: "pid,hostname" + }, + level: this.config.level + }); + } else { + console.warn("[Logger] pino-pretty not found. Install it for pretty logging: pnpm add -D pino-pretty"); + targets.push({ + target: "pino/file", + options: { destination: 1 }, + level: this.config.level + }); + } + } else if (this.config.format === "json") { + targets.push({ + target: "pino/file", + options: { destination: 1 }, + // stdout + level: this.config.level + }); + } else { + targets.push({ + target: "pino/file", + options: { destination: 1 }, + level: this.config.level + }); + } + if (this.config.file) { + targets.push({ + target: "pino/file", + options: { + destination: this.config.file, + mkdir: true + }, + level: this.config.level + }); + } + if (targets.length > 0) { + pinoOptions.transport = targets.length === 1 ? targets[0] : { targets }; + } + this.pinoInstance = pino(pinoOptions); + this.pinoLogger = this.pinoInstance; + } catch (error49) { + console.warn("[Logger] Pino not available, falling back to console:", error49); + this.pinoLogger = null; + } + } + /** + * Redact sensitive keys from context object (for browser) + */ + redactSensitive(obj) { + if (!obj || typeof obj !== "object") return obj; + const redacted = Array.isArray(obj) ? [...obj] : { ...obj }; + for (const key in redacted) { + const lowerKey = key.toLowerCase(); + const shouldRedact = this.config.redact.some( + (pattern) => lowerKey.includes(pattern.toLowerCase()) + ); + if (shouldRedact) { + redacted[key] = "***REDACTED***"; + } else if (typeof redacted[key] === "object" && redacted[key] !== null) { + redacted[key] = this.redactSensitive(redacted[key]); + } + } + return redacted; + } + /** + * Format log entry for browser + */ + formatBrowserLog(level, message2, context) { + if (this.config.format === "json") { + return JSON.stringify({ + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + level, + message: message2, + ...context + }); + } + if (this.config.format === "text") { + const parts = [(/* @__PURE__ */ new Date()).toISOString(), level.toUpperCase(), message2]; + if (context && Object.keys(context).length > 0) { + parts.push(JSON.stringify(context)); + } + return parts.join(" | "); + } + const levelColors2 = { + debug: "\x1B[36m", + // Cyan + info: "\x1B[32m", + // Green + warn: "\x1B[33m", + // Yellow + error: "\x1B[31m", + // Red + fatal: "\x1B[35m", + // Magenta + silent: "" + }; + const reset = "\x1B[0m"; + const color = levelColors2[level] || ""; + let output = `${color}[${level.toUpperCase()}]${reset} ${message2}`; + if (context && Object.keys(context).length > 0) { + output += ` ${JSON.stringify(context, null, 2)}`; + } + return output; + } + /** + * Log using browser console + */ + logBrowser(level, message2, context, error49) { + const redactedContext = context ? this.redactSensitive(context) : void 0; + const mergedContext = error49 ? { ...redactedContext, error: { message: error49.message, stack: error49.stack } } : redactedContext; + const formatted = this.formatBrowserLog(level, message2, mergedContext); + const consoleMethod = level === "debug" ? "debug" : level === "info" ? "log" : level === "warn" ? "warn" : level === "error" || level === "fatal" ? "error" : "log"; + console[consoleMethod](formatted); + } + /** + * Public logging methods + */ + debug(message2, meta3) { + if (this.isNode && this.pinoLogger) { + this.pinoLogger.debug(meta3 || {}, message2); + } else { + this.logBrowser("debug", message2, meta3); + } + } + info(message2, meta3) { + if (this.isNode && this.pinoLogger) { + this.pinoLogger.info(meta3 || {}, message2); + } else { + this.logBrowser("info", message2, meta3); + } + } + warn(message2, meta3) { + if (this.isNode && this.pinoLogger) { + this.pinoLogger.warn(meta3 || {}, message2); + } else { + this.logBrowser("warn", message2, meta3); + } + } + error(message2, errorOrMeta, meta3) { + let error49; + let context = {}; + if (errorOrMeta instanceof Error) { + error49 = errorOrMeta; + context = meta3 || {}; + } else { + context = errorOrMeta || {}; + } + if (this.isNode && this.pinoLogger) { + const errorContext = error49 ? { err: error49, ...context } : context; + this.pinoLogger.error(errorContext, message2); + } else { + this.logBrowser("error", message2, context, error49); + } + } + fatal(message2, errorOrMeta, meta3) { + let error49; + let context = {}; + if (errorOrMeta instanceof Error) { + error49 = errorOrMeta; + context = meta3 || {}; + } else { + context = errorOrMeta || {}; + } + if (this.isNode && this.pinoLogger) { + const errorContext = error49 ? { err: error49, ...context } : context; + this.pinoLogger.fatal(errorContext, message2); + } else { + this.logBrowser("fatal", message2, context, error49); + } + } + /** + * Create a child logger with additional context + * Note: Child loggers share the parent's Pino instance + */ + child(context) { + const childLogger = new _ObjectLogger(this.config); + if (this.isNode && this.pinoInstance) { + childLogger.pinoLogger = this.pinoInstance.child(context); + childLogger.pinoInstance = this.pinoInstance; + } + return childLogger; + } + /** + * Set trace context for distributed tracing + */ + withTrace(traceId, spanId) { + return this.child({ traceId, spanId }); + } + /** + * Cleanup resources + */ + async destroy() { + if (this.pinoLogger && this.pinoLogger.flush) { + await new Promise((resolve2) => { + this.pinoLogger.flush(() => resolve2()); + }); + } + } + /** + * Compatibility method for console.log usage + */ + log(message2, ...args) { + this.info(message2, args.length > 0 ? { args } : void 0); + } +}; +function createLogger(config4) { + return new ObjectLogger(config4); +} +var PluginConfigValidator = class { + constructor(logger2) { + this.logger = logger2; + } + /** + * Validate plugin configuration against its Zod schema + * + * @param plugin - Plugin metadata with configSchema + * @param config - User-provided configuration + * @returns Validated and typed configuration + * @throws Error with detailed validation errors + */ + validatePluginConfig(plugin, config4) { + if (!plugin.configSchema) { + this.logger.debug(`Plugin ${plugin.name} has no config schema - skipping validation`); + return config4; + } + try { + const validatedConfig = plugin.configSchema.parse(config4); + this.logger.debug(`\u2705 Plugin config validated: ${plugin.name}`, { + plugin: plugin.name, + configKeys: Object.keys(config4 || {}).length + }); + return validatedConfig; + } catch (error49) { + if (error49 instanceof external_exports.ZodError) { + const formattedErrors = this.formatZodErrors(error49); + const errorMessage = [ + `Plugin ${plugin.name} configuration validation failed:`, + ...formattedErrors.map((e) => ` - ${e.path}: ${e.message}`) + ].join("\n"); + this.logger.error(errorMessage, void 0, { + plugin: plugin.name, + errors: formattedErrors + }); + throw new Error(errorMessage); + } + throw error49; + } + } + /** + * Validate partial configuration (for incremental updates) + * + * @param plugin - Plugin metadata + * @param partialConfig - Partial configuration to validate + * @returns Validated partial configuration + */ + validatePartialConfig(plugin, partialConfig) { + if (!plugin.configSchema) { + return partialConfig; + } + try { + const partialSchema = plugin.configSchema.partial(); + const validatedConfig = partialSchema.parse(partialConfig); + this.logger.debug(`\u2705 Partial config validated: ${plugin.name}`); + return validatedConfig; + } catch (error49) { + if (error49 instanceof external_exports.ZodError) { + const formattedErrors = this.formatZodErrors(error49); + const errorMessage = [ + `Plugin ${plugin.name} partial configuration validation failed:`, + ...formattedErrors.map((e) => ` - ${e.path}: ${e.message}`) + ].join("\n"); + throw new Error(errorMessage); + } + throw error49; + } + } + /** + * Get default configuration from schema + * + * @param plugin - Plugin metadata + * @returns Default configuration object + */ + getDefaultConfig(plugin) { + if (!plugin.configSchema) { + return void 0; + } + try { + const defaults = plugin.configSchema.parse({}); + this.logger.debug(`Default config extracted: ${plugin.name}`); + return defaults; + } catch (error49) { + this.logger.debug(`No default config available: ${plugin.name}`); + return void 0; + } + } + /** + * Check if configuration is valid without throwing + * + * @param plugin - Plugin metadata + * @param config - Configuration to check + * @returns True if valid, false otherwise + */ + isConfigValid(plugin, config4) { + if (!plugin.configSchema) { + return true; + } + const result = plugin.configSchema.safeParse(config4); + return result.success; + } + /** + * Get configuration errors without throwing + * + * @param plugin - Plugin metadata + * @param config - Configuration to check + * @returns Array of validation errors, or empty array if valid + */ + getConfigErrors(plugin, config4) { + if (!plugin.configSchema) { + return []; + } + const result = plugin.configSchema.safeParse(config4); + if (result.success) { + return []; + } + return this.formatZodErrors(result.error); + } + // Private methods + formatZodErrors(error49) { + return error49.issues.map((e) => ({ + path: e.path.join(".") || "root", + message: e.message + })); + } +}; +var PluginLoader = class { + constructor(logger2) { + this.loadedPlugins = /* @__PURE__ */ new Map(); + this.serviceFactories = /* @__PURE__ */ new Map(); + this.serviceInstances = /* @__PURE__ */ new Map(); + this.scopedServices = /* @__PURE__ */ new Map(); + this.creating = /* @__PURE__ */ new Set(); + this.logger = logger2; + this.configValidator = new PluginConfigValidator(logger2); + } + /** + * Set the plugin context for service factories + */ + setContext(context) { + this.context = context; + } + /** + * Get a synchronous service instance if it exists (Sync Helper) + */ + getServiceInstance(name) { + return this.serviceInstances.get(name); + } + /** + * Load a plugin asynchronously with validation + */ + async loadPlugin(plugin) { + const startTime = Date.now(); + try { + this.logger.info(`Loading plugin: ${plugin.name}`); + const metadata = this.toPluginMetadata(plugin); + this.validatePluginStructure(metadata); + const versionCheck = this.checkVersionCompatibility(metadata); + if (!versionCheck.compatible) { + throw new Error(`Version incompatible: ${versionCheck.message}`); + } + if (metadata.configSchema) { + this.validatePluginConfig(metadata); + } + if (metadata.signature) { + await this.verifyPluginSignature(metadata); + } + this.loadedPlugins.set(metadata.name, metadata); + const loadTime = Date.now() - startTime; + this.logger.info(`Plugin loaded: ${plugin.name} (${loadTime}ms)`); + return { + success: true, + plugin: metadata, + loadTime + }; + } catch (error49) { + this.logger.error(`Failed to load plugin: ${plugin.name}`, error49); + return { + success: false, + error: error49, + loadTime: Date.now() - startTime + }; + } + } + /** + * Register a service with factory function + */ + registerServiceFactory(registration) { + if (this.serviceFactories.has(registration.name)) { + throw new Error(`Service factory '${registration.name}' already registered`); + } + this.serviceFactories.set(registration.name, registration); + this.logger.debug(`Service factory registered: ${registration.name} (${registration.lifecycle})`); + } + /** + * Get or create a service instance based on lifecycle type + */ + async getService(name, scopeId) { + const registration = this.serviceFactories.get(name); + if (!registration) { + const instance = this.serviceInstances.get(name); + if (!instance) { + throw new Error(`Service '${name}' not found`); + } + return instance; + } + switch (registration.lifecycle) { + case "singleton": + return await this.getSingletonService(registration); + case "transient": + return await this.createTransientService(registration); + case "scoped": + if (!scopeId) { + throw new Error(`Scope ID required for scoped service '${name}'`); + } + return await this.getScopedService(registration, scopeId); + default: + throw new Error(`Unknown service lifecycle: ${registration.lifecycle}`); + } + } + /** + * Register a static service instance (legacy support) + */ + registerService(name, service) { + if (this.serviceInstances.has(name)) { + throw new Error(`Service '${name}' already registered`); + } + this.serviceInstances.set(name, service); + } + /** + * Replace an existing service instance. + * Used by optimization plugins to swap kernel internals. + * @throws Error if service does not exist + */ + replaceService(name, service) { + if (!this.hasService(name)) { + throw new Error(`Service '${name}' not found`); + } + this.serviceInstances.set(name, service); + } + /** + * Check if a service is registered (either as instance or factory) + */ + hasService(name) { + return this.serviceInstances.has(name) || this.serviceFactories.has(name); + } + /** + * Detect circular dependencies in service factories + * Note: This only detects cycles in service dependencies, not plugin dependencies. + * Plugin dependency cycles are detected in the kernel's resolveDependencies method. + */ + detectCircularDependencies() { + const cycles = []; + const visited = /* @__PURE__ */ new Set(); + const visiting = /* @__PURE__ */ new Set(); + const visit = (serviceName, path3 = []) => { + if (visiting.has(serviceName)) { + const cycle = [...path3, serviceName].join(" -> "); + cycles.push(cycle); + return; + } + if (visited.has(serviceName)) { + return; + } + visiting.add(serviceName); + const registration = this.serviceFactories.get(serviceName); + if (registration?.dependencies) { + for (const dep of registration.dependencies) { + visit(dep, [...path3, serviceName]); + } + } + visiting.delete(serviceName); + visited.add(serviceName); + }; + for (const serviceName of this.serviceFactories.keys()) { + visit(serviceName); + } + return cycles; + } + /** + * Check plugin health + */ + async checkPluginHealth(pluginName) { + const plugin = this.loadedPlugins.get(pluginName); + if (!plugin) { + return { + healthy: false, + message: "Plugin not found", + lastCheck: /* @__PURE__ */ new Date() + }; + } + if (!plugin.healthCheck) { + return { + healthy: true, + message: "No health check defined", + lastCheck: /* @__PURE__ */ new Date() + }; + } + try { + const status = await plugin.healthCheck(); + return { + ...status, + lastCheck: /* @__PURE__ */ new Date() + }; + } catch (error49) { + return { + healthy: false, + message: `Health check failed: ${error49.message}`, + lastCheck: /* @__PURE__ */ new Date() + }; + } + } + /** + * Clear scoped services for a scope + */ + clearScope(scopeId) { + this.scopedServices.delete(scopeId); + this.logger.debug(`Cleared scope: ${scopeId}`); + } + /** + * Get all loaded plugins + */ + getLoadedPlugins() { + return new Map(this.loadedPlugins); + } + // Private helper methods + toPluginMetadata(plugin) { + const metadata = plugin; + if (!metadata.version) { + metadata.version = "0.0.0"; + } + return metadata; + } + validatePluginStructure(plugin) { + if (!plugin.name) { + throw new Error("Plugin name is required"); + } + if (!plugin.init) { + throw new Error("Plugin init function is required"); + } + if (!this.isValidSemanticVersion(plugin.version)) { + throw new Error(`Invalid semantic version: ${plugin.version}`); + } + } + checkVersionCompatibility(plugin) { + const version3 = plugin.version; + if (!this.isValidSemanticVersion(version3)) { + return { + compatible: false, + pluginVersion: version3, + message: "Invalid semantic version format" + }; + } + return { + compatible: true, + pluginVersion: version3 + }; + } + isValidSemanticVersion(version3) { + const semverRegex = /^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/; + return semverRegex.test(version3); + } + validatePluginConfig(plugin, config4) { + if (!plugin.configSchema) { + return; + } + if (config4 === void 0) { + this.logger.debug(`Plugin ${plugin.name} has configuration schema (config validation postponed)`); + return; + } + this.configValidator.validatePluginConfig(plugin, config4); + } + async verifyPluginSignature(plugin) { + if (!plugin.signature) { + return; + } + this.logger.debug(`Plugin ${plugin.name} has signature (use PluginSignatureVerifier for verification)`); + } + async getSingletonService(registration) { + let instance = this.serviceInstances.get(registration.name); + if (!instance) { + instance = await this.createServiceInstance(registration); + this.serviceInstances.set(registration.name, instance); + this.logger.debug(`Singleton service created: ${registration.name}`); + } + return instance; + } + async createTransientService(registration) { + const instance = await this.createServiceInstance(registration); + this.logger.debug(`Transient service created: ${registration.name}`); + return instance; + } + async getScopedService(registration, scopeId) { + if (!this.scopedServices.has(scopeId)) { + this.scopedServices.set(scopeId, /* @__PURE__ */ new Map()); + } + const scope = this.scopedServices.get(scopeId); + let instance = scope.get(registration.name); + if (!instance) { + instance = await this.createServiceInstance(registration); + scope.set(registration.name, instance); + this.logger.debug(`Scoped service created: ${registration.name} (scope: ${scopeId})`); + } + return instance; + } + async createServiceInstance(registration) { + if (!this.context) { + throw new Error(`[PluginLoader] Context not set - cannot create service '${registration.name}'`); + } + if (this.creating.has(registration.name)) { + throw new Error(`Circular dependency detected: ${Array.from(this.creating).join(" -> ")} -> ${registration.name}`); + } + this.creating.add(registration.name); + try { + return await registration.factory(this.context); + } finally { + this.creating.delete(registration.name); + } + } +}; +function createMemoryCache() { + const store = /* @__PURE__ */ new Map(); + let hits = 0; + let misses = 0; + return { + _fallback: true, + _serviceName: "cache", + async get(key) { + const entry = store.get(key); + if (!entry || entry.expires && Date.now() > entry.expires) { + store.delete(key); + misses++; + return void 0; + } + hits++; + return entry.value; + }, + async set(key, value, ttl) { + store.set(key, { value, expires: ttl ? Date.now() + ttl * 1e3 : void 0 }); + }, + async delete(key) { + return store.delete(key); + }, + async has(key) { + return store.has(key); + }, + async clear() { + store.clear(); + }, + async stats() { + return { hits, misses, keyCount: store.size }; + } + }; +} +function createMemoryQueue() { + const handlers = /* @__PURE__ */ new Map(); + let msgId = 0; + return { + _fallback: true, + _serviceName: "queue", + async publish(queue, data) { + const id = `fallback-msg-${++msgId}`; + const fns = handlers.get(queue) ?? []; + for (const fn of fns) fn({ id, data, attempts: 1, timestamp: Date.now() }); + return id; + }, + async subscribe(queue, handler) { + handlers.set(queue, [...handlers.get(queue) ?? [], handler]); + }, + async unsubscribe(queue) { + handlers.delete(queue); + }, + async getQueueSize() { + return 0; + }, + async purge(queue) { + handlers.delete(queue); + } + }; +} +function createMemoryJob() { + const jobs = /* @__PURE__ */ new Map(); + return { + _fallback: true, + _serviceName: "job", + async schedule(name, schedule, handler) { + jobs.set(name, { schedule, handler }); + }, + async cancel(name) { + jobs.delete(name); + }, + async trigger(name, data) { + const job = jobs.get(name); + if (job?.handler) await job.handler({ jobId: name, data }); + }, + async getExecutions() { + return []; + }, + async listJobs() { + return [...jobs.keys()]; + } + }; +} +function resolveLocale(requestedLocale, availableLocales) { + if (availableLocales.length === 0) return void 0; + if (availableLocales.includes(requestedLocale)) return requestedLocale; + const lower = requestedLocale.toLowerCase(); + const caseMatch = availableLocales.find((l) => l.toLowerCase() === lower); + if (caseMatch) return caseMatch; + const baseLang = requestedLocale.split("-")[0].toLowerCase(); + const baseMatch = availableLocales.find((l) => l.toLowerCase() === baseLang); + if (baseMatch) return baseMatch; + const variantMatch = availableLocales.find((l) => l.split("-")[0].toLowerCase() === baseLang); + if (variantMatch) return variantMatch; + return void 0; +} +function createMemoryI18n() { + const translations = /* @__PURE__ */ new Map(); + let defaultLocale = "en"; + function resolveKey(data, key) { + const parts = key.split("."); + let current = data; + for (const part of parts) { + if (current == null || typeof current !== "object") return void 0; + current = current[part]; + } + return typeof current === "string" ? current : void 0; + } + function resolveTranslations(locale) { + if (translations.has(locale)) return translations.get(locale); + const resolved = resolveLocale(locale, [...translations.keys()]); + if (resolved) return translations.get(resolved); + return void 0; + } + return { + _fallback: true, + _serviceName: "i18n", + t(key, locale, params) { + const data = resolveTranslations(locale) ?? translations.get(defaultLocale); + const value = data ? resolveKey(data, key) : void 0; + if (value == null) return key; + if (!params) return value; + return value.replace(/\{\{(\w+)\}\}/g, (_, name) => String(params[name] ?? `{{${name}}}`)); + }, + getTranslations(locale) { + return resolveTranslations(locale) ?? {}; + }, + loadTranslations(locale, data) { + const existing = translations.get(locale) ?? {}; + translations.set(locale, { ...existing, ...data }); + }, + getLocales() { + return [...translations.keys()]; + }, + getDefaultLocale() { + return defaultLocale; + }, + setDefaultLocale(locale) { + defaultLocale = locale; + } + }; +} +function createMemoryMetadata() { + const store = /* @__PURE__ */ new Map(); + function getTypeMap(type) { + let map3 = store.get(type); + if (!map3) { + map3 = /* @__PURE__ */ new Map(); + store.set(type, map3); + } + return map3; + } + return { + _fallback: true, + _serviceName: "metadata", + async register(type, name, data) { + getTypeMap(type).set(name, data); + }, + async get(type, name) { + return getTypeMap(type).get(name); + }, + async list(type) { + return Array.from(getTypeMap(type).values()); + }, + async unregister(type, name) { + getTypeMap(type).delete(name); + }, + async exists(type, name) { + return getTypeMap(type).has(name); + }, + async listNames(type) { + return Array.from(getTypeMap(type).keys()); + }, + async getObject(name) { + return getTypeMap("object").get(name); + }, + async listObjects() { + return Array.from(getTypeMap("object").values()); + } + }; +} +var CORE_FALLBACK_FACTORIES = { + metadata: createMemoryMetadata, + cache: createMemoryCache, + queue: createMemoryQueue, + job: createMemoryJob, + i18n: createMemoryI18n +}; +var ObjectKernel = class { + constructor(config4 = {}) { + this.plugins = /* @__PURE__ */ new Map(); + this.services = /* @__PURE__ */ new Map(); + this.hooks = /* @__PURE__ */ new Map(); + this.state = "idle"; + this.startedPlugins = /* @__PURE__ */ new Set(); + this.pluginStartTimes = /* @__PURE__ */ new Map(); + this.shutdownHandlers = []; + this.config = { + defaultStartupTimeout: 3e4, + // 30 seconds + gracefulShutdown: true, + shutdownTimeout: 6e4, + // 60 seconds + rollbackOnFailure: true, + ...config4 + }; + this.logger = createLogger(config4.logger); + this.pluginLoader = new PluginLoader(this.logger); + this.context = { + registerService: (name, service) => { + this.registerService(name, service); + }, + getService: (name) => { + const service = this.services.get(name); + if (service) { + return service; + } + const loaderService = this.pluginLoader.getServiceInstance(name); + if (loaderService) { + this.services.set(name, loaderService); + return loaderService; + } + try { + const service2 = this.pluginLoader.getService(name); + if (service2 instanceof Promise) { + service2.catch(() => { + }); + throw new Error(`Service '${name}' is async - use await`); + } + return service2; + } catch (error49) { + if (error49.message?.includes("is async")) { + throw error49; + } + const isNotFoundError = error49.message === `Service '${name}' not found`; + if (!isNotFoundError) { + throw error49; + } + throw new Error(`[Kernel] Service '${name}' not found`); + } + }, + replaceService: (name, implementation) => { + const hasService = this.services.has(name) || this.pluginLoader.hasService(name); + if (!hasService) { + throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`); + } + this.services.set(name, implementation); + this.pluginLoader.replaceService(name, implementation); + this.logger.info(`Service '${name}' replaced`, { service: name }); + }, + hook: (name, handler) => { + if (!this.hooks.has(name)) { + this.hooks.set(name, []); + } + this.hooks.get(name).push(handler); + }, + trigger: async (name, ...args) => { + const handlers = this.hooks.get(name) || []; + for (const handler of handlers) { + await handler(...args); + } + }, + getServices: () => { + return new Map(this.services); + }, + logger: this.logger, + getKernel: () => this + // Type compatibility + }; + this.pluginLoader.setContext(this.context); + if (this.config.gracefulShutdown) { + this.registerShutdownSignals(); + } + } + /** + * Register a plugin with enhanced validation + */ + async use(plugin) { + if (this.state !== "idle") { + throw new Error("[Kernel] Cannot register plugins after bootstrap has started"); + } + const result = await this.pluginLoader.loadPlugin(plugin); + if (!result.success || !result.plugin) { + throw new Error(`Failed to load plugin: ${plugin.name} - ${result.error?.message}`); + } + const pluginMeta = result.plugin; + this.plugins.set(pluginMeta.name, pluginMeta); + this.logger.info(`Plugin registered: ${pluginMeta.name}@${pluginMeta.version}`, { + plugin: pluginMeta.name, + version: pluginMeta.version + }); + return this; + } + /** + * Register a service instance directly + */ + registerService(name, service) { + if (this.services.has(name)) { + throw new Error(`[Kernel] Service '${name}' already registered`); + } + this.services.set(name, service); + this.pluginLoader.registerService(name, service); + this.logger.info(`Service '${name}' registered`, { service: name }); + return this; + } + /** + * Register a service factory with lifecycle management + */ + registerServiceFactory(name, factory, lifecycle = "singleton", dependencies) { + this.pluginLoader.registerServiceFactory({ + name, + factory, + lifecycle, + dependencies + }); + return this; + } + /** + * Pre-inject in-memory fallbacks for 'core' services that were not registered + * by plugins during Phase 1. Called before Phase 2 so that all core services + * (e.g. 'metadata', 'cache', 'queue') are resolvable via ctx.getService() + * when plugin start() methods execute. + */ + preInjectCoreFallbacks() { + if (this.config.skipSystemValidation) return; + for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) { + if (criticality !== "core") continue; + const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName); + if (!hasService) { + const factory = CORE_FALLBACK_FACTORIES[serviceName]; + if (factory) { + const fallback = factory(); + this.registerService(serviceName, fallback); + this.logger.debug(`[Kernel] Pre-injected in-memory fallback for '${serviceName}' before Phase 2`); + } + } + } + } + /** + * Validate Critical System Requirements + */ + validateSystemRequirements() { + if (this.config.skipSystemValidation) { + this.logger.debug("System requirement validation skipped"); + return; + } + this.logger.debug("Validating system service requirements..."); + const missingServices = []; + const missingCoreServices = []; + for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) { + const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName); + if (!hasService) { + if (criticality === "required") { + this.logger.error(`CRITICAL: Required service missing: ${serviceName}`); + missingServices.push(serviceName); + } else if (criticality === "core") { + const factory = CORE_FALLBACK_FACTORIES[serviceName]; + if (factory) { + const fallback = factory(); + this.registerService(serviceName, fallback); + this.logger.warn(`Service '${serviceName}' not provided \u2014 using in-memory fallback`); + } else { + this.logger.warn(`CORE: Core service missing, functionality may be degraded: ${serviceName}`); + missingCoreServices.push(serviceName); + } + } else { + this.logger.info(`Info: Optional service not present: ${serviceName}`); + } + } + } + if (missingServices.length > 0) { + const errorMsg = `System failed to start. Missing critical services: ${missingServices.join(", ")}`; + this.logger.error(errorMsg); + throw new Error(errorMsg); + } + if (missingCoreServices.length > 0) { + this.logger.warn(`System started with degraded capabilities. Missing core services: ${missingCoreServices.join(", ")}`); + } + this.logger.info("System requirement check passed"); + } + /** + * Bootstrap the kernel with enhanced features + */ + async bootstrap() { + if (this.state !== "idle") { + throw new Error("[Kernel] Kernel already bootstrapped"); + } + this.state = "initializing"; + this.logger.info("Bootstrap started"); + try { + const cycles = this.pluginLoader.detectCircularDependencies(); + if (cycles.length > 0) { + this.logger.warn("Circular service dependencies detected:", { cycles }); + } + const orderedPlugins = this.resolveDependencies(); + this.logger.info("Phase 1: Init plugins"); + for (const plugin of orderedPlugins) { + await this.initPluginWithTimeout(plugin); + } + this.preInjectCoreFallbacks(); + this.logger.info("Phase 2: Start plugins"); + this.state = "running"; + for (const plugin of orderedPlugins) { + const result = await this.startPluginWithTimeout(plugin); + if (!result.success) { + this.logger.error(`Plugin startup failed: ${plugin.name}`, result.error); + if (this.config.rollbackOnFailure) { + this.logger.warn("Rolling back started plugins..."); + await this.rollbackStartedPlugins(); + throw new Error(`Plugin ${plugin.name} failed to start - rollback complete`); + } + } + } + this.validateSystemRequirements(); + this.logger.debug("Triggering kernel:ready hook"); + await this.context.trigger("kernel:ready"); + this.logger.info("\u2705 Bootstrap complete"); + } catch (error49) { + this.state = "stopped"; + throw error49; + } + } + /** + * Graceful shutdown with timeout + */ + async shutdown() { + if (this.state === "stopped" || this.state === "stopping") { + this.logger.warn("Kernel already stopped or stopping"); + return; + } + if (this.state !== "running") { + throw new Error("[Kernel] Kernel not running"); + } + this.state = "stopping"; + this.logger.info("Graceful shutdown started"); + try { + const shutdownPromise = this.performShutdown(); + const timeoutPromise = new Promise((_, reject) => { + setTimeout(() => { + reject(new Error("Shutdown timeout exceeded")); + }, this.config.shutdownTimeout); + }); + await Promise.race([shutdownPromise, timeoutPromise]); + this.state = "stopped"; + this.logger.info("\u2705 Graceful shutdown complete"); + } catch (error49) { + this.logger.error("Shutdown error - forcing stop", error49); + this.state = "stopped"; + throw error49; + } finally { + await this.logger.destroy(); + } + } + /** + * Check health of a specific plugin + */ + async checkPluginHealth(pluginName) { + return await this.pluginLoader.checkPluginHealth(pluginName); + } + /** + * Check health of all plugins + */ + async checkAllPluginsHealth() { + const results = /* @__PURE__ */ new Map(); + for (const pluginName of this.plugins.keys()) { + const health = await this.checkPluginHealth(pluginName); + results.set(pluginName, health); + } + return results; + } + /** + * Get plugin startup metrics + */ + getPluginMetrics() { + return new Map(this.pluginStartTimes); + } + /** + * Get a service (sync helper) + */ + getService(name) { + return this.context.getService(name); + } + /** + * Get a service asynchronously (supports factories) + */ + async getServiceAsync(name, scopeId) { + return await this.pluginLoader.getService(name, scopeId); + } + /** + * Check if kernel is running + */ + isRunning() { + return this.state === "running"; + } + /** + * Get kernel state + */ + getState() { + return this.state; + } + // Private methods + async initPluginWithTimeout(plugin) { + const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout; + this.logger.debug(`Init: ${plugin.name}`, { plugin: plugin.name }); + const initPromise = plugin.init(this.context); + const timeoutPromise = new Promise((_, reject) => { + setTimeout(() => { + reject(new Error(`Plugin ${plugin.name} init timeout after ${timeout}ms`)); + }, timeout); + }); + await Promise.race([initPromise, timeoutPromise]); + } + async startPluginWithTimeout(plugin) { + if (!plugin.start) { + return { success: true, pluginName: plugin.name }; + } + const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout; + const startTime = Date.now(); + this.logger.debug(`Start: ${plugin.name}`, { plugin: plugin.name }); + try { + const startPromise = plugin.start(this.context); + const timeoutPromise = new Promise((_, reject) => { + setTimeout(() => { + reject(new Error(`Plugin ${plugin.name} start timeout after ${timeout}ms`)); + }, timeout); + }); + await Promise.race([startPromise, timeoutPromise]); + const duration3 = Date.now() - startTime; + this.startedPlugins.add(plugin.name); + this.pluginStartTimes.set(plugin.name, duration3); + this.logger.debug(`Plugin started: ${plugin.name} (${duration3}ms)`); + return { + success: true, + pluginName: plugin.name, + startTime: duration3 + }; + } catch (error49) { + const duration3 = Date.now() - startTime; + const isTimeout = error49.message.includes("timeout"); + return { + success: false, + pluginName: plugin.name, + error: error49, + startTime: duration3, + timedOut: isTimeout + }; + } + } + async rollbackStartedPlugins() { + const pluginsToRollback = Array.from(this.startedPlugins).reverse(); + for (const pluginName of pluginsToRollback) { + const plugin = this.plugins.get(pluginName); + if (plugin?.destroy) { + try { + this.logger.debug(`Rollback: ${pluginName}`); + await plugin.destroy(); + } catch (error49) { + this.logger.error(`Rollback failed for ${pluginName}`, error49); + } + } + } + this.startedPlugins.clear(); + } + async performShutdown() { + await this.context.trigger("kernel:shutdown"); + const orderedPlugins = Array.from(this.plugins.values()).reverse(); + for (const plugin of orderedPlugins) { + if (plugin.destroy) { + this.logger.debug(`Destroy: ${plugin.name}`, { plugin: plugin.name }); + try { + await plugin.destroy(); + } catch (error49) { + this.logger.error(`Error destroying plugin ${plugin.name}`, error49); + } + } + } + for (const handler of this.shutdownHandlers) { + try { + await handler(); + } catch (error49) { + this.logger.error("Shutdown handler error", error49); + } + } + } + resolveDependencies() { + const resolved = []; + const visited = /* @__PURE__ */ new Set(); + const visiting = /* @__PURE__ */ new Set(); + const visit = (pluginName) => { + if (visited.has(pluginName)) return; + if (visiting.has(pluginName)) { + throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`); + } + const plugin = this.plugins.get(pluginName); + if (!plugin) { + throw new Error(`[Kernel] Plugin '${pluginName}' not found`); + } + visiting.add(pluginName); + const deps = plugin.dependencies || []; + for (const dep of deps) { + if (!this.plugins.has(dep)) { + throw new Error(`[Kernel] Dependency '${dep}' not found for plugin '${pluginName}'`); + } + visit(dep); + } + visiting.delete(pluginName); + visited.add(pluginName); + resolved.push(plugin); + }; + for (const pluginName of this.plugins.keys()) { + visit(pluginName); + } + return resolved; + } + registerShutdownSignals() { + const signals = ["SIGINT", "SIGTERM", "SIGQUIT"]; + let shutdownInProgress = false; + const handleShutdown = async (signal) => { + if (shutdownInProgress) { + this.logger.warn(`Shutdown already in progress, ignoring ${signal}`); + return; + } + shutdownInProgress = true; + this.logger.info(`Received ${signal} - initiating graceful shutdown`); + try { + await this.shutdown(); + safeExit(0); + } catch (error49) { + this.logger.error("Shutdown failed", error49); + safeExit(1); + } + }; + if (isNode) { + for (const signal of signals) { + process.on(signal, () => handleShutdown(signal)); + } + } + } + /** + * Register a custom shutdown handler + */ + onShutdown(handler) { + this.shutdownHandlers.push(handler); + } +}; +var qa_exports = {}; +__export2(qa_exports, { + HttpTestAdapter: () => HttpTestAdapter, + TestRunner: () => TestRunner +}); +var TestRunner = class { + constructor(adapter) { + this.adapter = adapter; + } + async runSuite(suite) { + const results = []; + for (const scenario of suite.scenarios) { + results.push(await this.runScenario(scenario)); + } + return results; + } + async runScenario(scenario) { + const startTime = Date.now(); + const context = {}; + if (scenario.setup) { + for (const step of scenario.setup) { + try { + await this.runStep(step, context); + } catch (e) { + return { + scenarioId: scenario.id, + passed: false, + steps: [], + error: `Setup failed: ${e instanceof Error ? e.message : String(e)}`, + duration: Date.now() - startTime + }; + } + } + } + const stepResults = []; + let scenarioPassed = true; + let scenarioError = void 0; + for (const step of scenario.steps) { + const stepStartTime = Date.now(); + try { + const output = await this.runStep(step, context); + stepResults.push({ + stepName: step.name, + passed: true, + output, + duration: Date.now() - stepStartTime + }); + } catch (e) { + scenarioPassed = false; + scenarioError = e; + stepResults.push({ + stepName: step.name, + passed: false, + error: e, + duration: Date.now() - stepStartTime + }); + break; + } + } + if (scenario.teardown) { + for (const step of scenario.teardown) { + try { + await this.runStep(step, context); + } catch (e) { + if (scenarioPassed) { + scenarioPassed = false; + scenarioError = `Teardown failed: ${e instanceof Error ? e.message : String(e)}`; + } + } + } + } + return { + scenarioId: scenario.id, + passed: scenarioPassed, + steps: stepResults, + error: scenarioError, + duration: Date.now() - startTime + }; + } + async runStep(step, context) { + const resolvedAction = this.resolveVariables(step.action, context); + const result = await this.adapter.execute(resolvedAction, context); + if (step.capture) { + for (const [varName, path3] of Object.entries(step.capture)) { + context[varName] = this.getValueByPath(result, path3); + } + } + if (step.assertions) { + for (const assertion of step.assertions) { + this.assert(result, assertion, context); + } + } + return result; + } + resolveVariables(action, context) { + const actionStr = JSON.stringify(action); + const resolved = actionStr.replace(/\{\{([^}]+)\}\}/g, (_match, varPath) => { + const value = this.getValueByPath(context, varPath.trim()); + if (value === void 0) return _match; + return typeof value === "string" ? value : JSON.stringify(value); + }); + try { + return JSON.parse(resolved); + } catch { + return action; + } + } + getValueByPath(obj, path3) { + if (!path3) return obj; + const parts = path3.split("."); + let current = obj; + for (const part of parts) { + if (current === null || current === void 0) return void 0; + current = current[part]; + } + return current; + } + assert(result, assertion, _context2) { + const actual = this.getValueByPath(result, assertion.field); + const expected = assertion.expectedValue; + switch (assertion.operator) { + case "equals": + if (actual !== expected) throw new Error(`Assertion failed: ${assertion.field} expected ${expected}, got ${actual}`); + break; + case "not_equals": + if (actual === expected) throw new Error(`Assertion failed: ${assertion.field} expected not ${expected}, got ${actual}`); + break; + case "contains": + if (Array.isArray(actual)) { + if (!actual.includes(expected)) throw new Error(`Assertion failed: ${assertion.field} array does not contain ${expected}`); + } else if (typeof actual === "string") { + if (!actual.includes(String(expected))) throw new Error(`Assertion failed: ${assertion.field} string does not contain ${expected}`); + } + break; + case "not_null": + if (actual === null || actual === void 0) throw new Error(`Assertion failed: ${assertion.field} is null`); + break; + case "is_null": + if (actual !== null && actual !== void 0) throw new Error(`Assertion failed: ${assertion.field} is not null`); + break; + // ... Add other operators + default: + throw new Error(`Unknown assertion operator: ${assertion.operator}`); + } + } +}; +var HttpTestAdapter = class { + constructor(baseUrl, authToken) { + this.baseUrl = baseUrl; + this.authToken = authToken; + } + async execute(action, _context2) { + const headers = { + "Content-Type": "application/json" + }; + if (this.authToken) { + headers["Authorization"] = `Bearer ${this.authToken}`; + } + if (action.user) { + headers["X-Run-As"] = action.user; + } + switch (action.type) { + case "create_record": + return this.createRecord(action.target, action.payload || {}, headers); + case "update_record": + return this.updateRecord(action.target, action.payload || {}, headers); + case "delete_record": + return this.deleteRecord(action.target, action.payload || {}, headers); + case "read_record": + return this.readRecord(action.target, action.payload || {}, headers); + case "query_records": + return this.queryRecords(action.target, action.payload || {}, headers); + case "api_call": + return this.rawApiCall(action.target, action.payload || {}, headers); + case "wait": + const ms = Number(action.payload?.duration || 1e3); + return new Promise((resolve2) => setTimeout(() => resolve2({ waited: ms }), ms)); + default: + throw new Error(`Unsupported action type in HttpAdapter: ${action.type}`); + } + } + async createRecord(objectName, data, headers) { + const response = await fetch(`${this.baseUrl}/api/data/${objectName}`, { + method: "POST", + headers, + body: JSON.stringify(data) + }); + return this.handleResponse(response); + } + async updateRecord(objectName, data, headers) { + const id = data.id; + if (!id) throw new Error("Update record requires id in payload"); + const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, { + method: "PUT", + headers, + body: JSON.stringify(data) + }); + return this.handleResponse(response); + } + async deleteRecord(objectName, data, headers) { + const id = data.id; + if (!id) throw new Error("Delete record requires id in payload"); + const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, { + method: "DELETE", + headers + }); + return this.handleResponse(response); + } + async readRecord(objectName, data, headers) { + const id = data.id; + if (!id) throw new Error("Read record requires id in payload"); + const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, { + method: "GET", + headers + }); + return this.handleResponse(response); + } + async queryRecords(objectName, data, headers) { + const response = await fetch(`${this.baseUrl}/api/data/${objectName}/query`, { + method: "POST", + headers, + body: JSON.stringify(data) + }); + return this.handleResponse(response); + } + async rawApiCall(endpoint, data, headers) { + const method = data.method || "GET"; + const body = data.body ? JSON.stringify(data.body) : void 0; + const url2 = endpoint.startsWith("http") ? endpoint : `${this.baseUrl}${endpoint}`; + const response = await fetch(url2, { + method, + headers, + body + }); + return this.handleResponse(response); + } + async handleResponse(response) { + if (!response.ok) { + const text = await response.text(); + throw new Error(`HTTP Error ${response.status}: ${text}`); + } + const contentType = response.headers.get("content-type"); + if (contentType && contentType.includes("application/json")) { + return response.json(); + } + return response.text(); + } +}; +var _PluginSandboxRuntime = class _PluginSandboxRuntime2 { + constructor(logger2) { + this.sandboxes = /* @__PURE__ */ new Map(); + this.monitoringIntervals = /* @__PURE__ */ new Map(); + this.memoryBaselines = /* @__PURE__ */ new Map(); + this.cpuBaselines = /* @__PURE__ */ new Map(); + this.logger = logger2.child({ component: "SandboxRuntime" }); + } + /** + * Create a sandbox for a plugin + */ + createSandbox(pluginId, config4) { + if (this.sandboxes.has(pluginId)) { + throw new Error(`Sandbox already exists for plugin: ${pluginId}`); + } + const context = { + pluginId, + config: config4, + startTime: /* @__PURE__ */ new Date(), + resourceUsage: { + memory: { current: 0, peak: 0, limit: config4.memory?.maxHeap }, + cpu: { current: 0, average: 0, limit: config4.cpu?.maxCpuPercent }, + connections: { current: 0, limit: config4.network?.maxConnections } + } + }; + this.sandboxes.set(pluginId, context); + const baselineMemory = getMemoryUsage(); + this.memoryBaselines.set(pluginId, baselineMemory.heapUsed); + this.cpuBaselines.set(pluginId, process.cpuUsage()); + this.startResourceMonitoring(pluginId); + this.logger.info("Sandbox created", { + pluginId, + level: config4.level, + memoryLimit: config4.memory?.maxHeap, + cpuLimit: config4.cpu?.maxCpuPercent + }); + return context; + } + /** + * Destroy a sandbox + */ + destroySandbox(pluginId) { + const context = this.sandboxes.get(pluginId); + if (!context) { + return; + } + this.stopResourceMonitoring(pluginId); + this.memoryBaselines.delete(pluginId); + this.cpuBaselines.delete(pluginId); + this.sandboxes.delete(pluginId); + this.logger.info("Sandbox destroyed", { pluginId }); + } + /** + * Check if resource access is allowed + */ + checkResourceAccess(pluginId, resourceType, resourcePath) { + const context = this.sandboxes.get(pluginId); + if (!context) { + return { allowed: false, reason: "Sandbox not found" }; + } + const { config: config4 } = context; + switch (resourceType) { + case "file": + return this.checkFileAccess(config4, resourcePath); + case "network": + return this.checkNetworkAccess(config4, resourcePath); + case "process": + return this.checkProcessAccess(config4); + case "env": + return this.checkEnvAccess(config4, resourcePath); + default: + return { allowed: false, reason: "Unknown resource type" }; + } + } + /** + * Check file system access + * Uses path.resolve() and path.normalize() to prevent directory traversal. + */ + checkFileAccess(config4, filePath) { + if (config4.level === "none") { + return { allowed: true }; + } + if (!config4.filesystem) { + return { allowed: false, reason: "File system access not configured" }; + } + if (!filePath) { + return { allowed: config4.filesystem.mode !== "none" }; + } + const allowedPaths = config4.filesystem.allowedPaths || []; + const resolvedPath = nodePath.normalize(nodePath.resolve(filePath)); + const isAllowed = allowedPaths.some((allowed2) => { + const resolvedAllowed = nodePath.normalize(nodePath.resolve(allowed2)); + return resolvedPath.startsWith(resolvedAllowed); + }); + if (allowedPaths.length > 0 && !isAllowed) { + return { + allowed: false, + reason: `Path not in allowed list: ${filePath}` + }; + } + const deniedPaths = config4.filesystem.deniedPaths || []; + const isDenied = deniedPaths.some((denied) => { + const resolvedDenied = nodePath.normalize(nodePath.resolve(denied)); + return resolvedPath.startsWith(resolvedDenied); + }); + if (isDenied) { + return { + allowed: false, + reason: `Path is explicitly denied: ${filePath}` + }; + } + return { allowed: true }; + } + /** + * Check network access + * Uses URL parsing to properly validate hostnames. + */ + checkNetworkAccess(config4, url2) { + if (config4.level === "none") { + return { allowed: true }; + } + if (!config4.network) { + return { allowed: false, reason: "Network access not configured" }; + } + if (config4.network.mode === "none") { + return { allowed: false, reason: "Network access disabled" }; + } + if (!url2) { + return { allowed: config4.network.mode !== "none" }; + } + let parsedHostname; + try { + parsedHostname = new URL(url2).hostname; + } catch { + return { allowed: false, reason: `Invalid URL: ${url2}` }; + } + const allowedHosts = config4.network.allowedHosts || []; + if (allowedHosts.length > 0) { + const isAllowed = allowedHosts.some((host) => { + return parsedHostname === host; + }); + if (!isAllowed) { + return { + allowed: false, + reason: `Host not in allowed list: ${url2}` + }; + } + } + const deniedHosts = config4.network.deniedHosts || []; + const isDenied = deniedHosts.some((host) => { + return parsedHostname === host; + }); + if (isDenied) { + return { + allowed: false, + reason: `Host is blocked: ${url2}` + }; + } + return { allowed: true }; + } + /** + * Check process spawning access + */ + checkProcessAccess(config4) { + if (config4.level === "none") { + return { allowed: true }; + } + if (!config4.process) { + return { allowed: false, reason: "Process access not configured" }; + } + if (!config4.process.allowSpawn) { + return { allowed: false, reason: "Process spawning not allowed" }; + } + return { allowed: true }; + } + /** + * Check environment variable access + */ + checkEnvAccess(config4, varName) { + if (config4.level === "none") { + return { allowed: true }; + } + if (!config4.process) { + return { allowed: false, reason: "Environment access not configured" }; + } + if (!varName) { + return { allowed: true }; + } + return { allowed: true }; + } + /** + * Check resource limits + */ + checkResourceLimits(pluginId) { + const context = this.sandboxes.get(pluginId); + if (!context) { + return { withinLimits: true, violations: [] }; + } + const violations = []; + const { resourceUsage, config: config4 } = context; + if (config4.memory?.maxHeap && resourceUsage.memory.current > config4.memory.maxHeap) { + violations.push(`Memory limit exceeded: ${resourceUsage.memory.current} > ${config4.memory.maxHeap}`); + } + if (config4.runtime?.resourceLimits?.maxCpu && resourceUsage.cpu.current > config4.runtime.resourceLimits.maxCpu) { + violations.push(`CPU limit exceeded: ${resourceUsage.cpu.current}% > ${config4.runtime.resourceLimits.maxCpu}%`); + } + if (config4.network?.maxConnections && resourceUsage.connections.current > config4.network.maxConnections) { + violations.push(`Connection limit exceeded: ${resourceUsage.connections.current} > ${config4.network.maxConnections}`); + } + return { + withinLimits: violations.length === 0, + violations + }; + } + /** + * Get resource usage for a plugin + */ + getResourceUsage(pluginId) { + const context = this.sandboxes.get(pluginId); + return context?.resourceUsage; + } + /** + * Start monitoring resource usage + */ + startResourceMonitoring(pluginId) { + const interval = setInterval(() => { + this.updateResourceUsage(pluginId); + }, _PluginSandboxRuntime2.MONITORING_INTERVAL_MS); + this.monitoringIntervals.set(pluginId, interval); + } + /** + * Stop monitoring resource usage + */ + stopResourceMonitoring(pluginId) { + const interval = this.monitoringIntervals.get(pluginId); + if (interval) { + clearInterval(interval); + this.monitoringIntervals.delete(pluginId); + } + } + /** + * Update resource usage statistics + * + * Tracks per-plugin memory and CPU usage using delta from baseline + * captured at sandbox creation time. This is an approximation since + * true per-plugin isolation isn't possible in a single Node.js process. + */ + updateResourceUsage(pluginId) { + const context = this.sandboxes.get(pluginId); + if (!context) { + return; + } + const memoryUsage = getMemoryUsage(); + const memoryBaseline = this.memoryBaselines.get(pluginId) ?? 0; + const memoryDelta = Math.max(0, memoryUsage.heapUsed - memoryBaseline); + context.resourceUsage.memory.current = memoryDelta; + context.resourceUsage.memory.peak = Math.max( + context.resourceUsage.memory.peak, + memoryDelta + ); + const cpuBaseline = this.cpuBaselines.get(pluginId) ?? { user: 0, system: 0 }; + const cpuCurrent = process.cpuUsage(); + const cpuDeltaUser = cpuCurrent.user - cpuBaseline.user; + const cpuDeltaSystem = cpuCurrent.system - cpuBaseline.system; + const totalCpuMicros = cpuDeltaUser + cpuDeltaSystem; + const intervalMicros = _PluginSandboxRuntime2.MONITORING_INTERVAL_MS * 1e3; + context.resourceUsage.cpu.current = totalCpuMicros / intervalMicros * 100; + this.cpuBaselines.set(pluginId, cpuCurrent); + const { withinLimits, violations } = this.checkResourceLimits(pluginId); + if (!withinLimits) { + this.logger.warn("Resource limit violations detected", { + pluginId, + violations + }); + } + } + /** + * Get all active sandboxes + */ + getAllSandboxes() { + return new Map(this.sandboxes); + } + /** + * Shutdown sandbox runtime + */ + shutdown() { + for (const pluginId of this.monitoringIntervals.keys()) { + this.stopResourceMonitoring(pluginId); + } + this.sandboxes.clear(); + this.memoryBaselines.clear(); + this.cpuBaselines.clear(); + this.logger.info("Sandbox runtime shutdown complete"); + } +}; +_PluginSandboxRuntime.MONITORING_INTERVAL_MS = 5e3; + +// ../../packages/runtime/dist/index.js +init_data(); + +// ../../packages/spec/dist/shared/index.mjs +init_zod(); +var SystemIdentifierSchema4 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' +}).describe("System identifier (lowercase with underscores or dots)"); +var SnakeCaseIdentifierSchema4 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { + message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' +}).describe("Snake case identifier (lowercase with underscores only)"); +var EventNameSchema2 = external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' +}).describe("Event name (lowercase with dot notation for namespacing)"); +var TransformTypeSchema2 = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("constant"), + value: external_exports.unknown().describe("Constant value to use") + }).describe("Set a constant value"), + external_exports.object({ + type: external_exports.literal("cast"), + targetType: external_exports.enum(["string", "number", "boolean", "date"]).describe("Target data type") + }).describe("Cast to a specific data type"), + external_exports.object({ + type: external_exports.literal("lookup"), + table: external_exports.string().describe("Lookup table name"), + keyField: external_exports.string().describe("Field to match on"), + valueField: external_exports.string().describe("Field to retrieve") + }).describe("Lookup value from another table"), + external_exports.object({ + type: external_exports.literal("javascript"), + expression: external_exports.string().describe('JavaScript expression (e.g., "value.toUpperCase()")') + }).describe("Custom JavaScript transformation"), + external_exports.object({ + type: external_exports.literal("map"), + mappings: external_exports.record(external_exports.string(), external_exports.unknown()).describe('Value mappings (e.g., {"Active": "active"})') + }).describe("Map values using a dictionary") +]); +var FieldMappingSchema3 = external_exports.object({ + /** + * Source field name + */ + source: external_exports.string().describe("Source field name"), + /** + * Target field name (should be snake_case for ObjectStack) + */ + target: external_exports.string().describe("Target field name"), + /** + * Transformation to apply + */ + transform: TransformTypeSchema2.optional().describe("Transformation to apply"), + /** + * Default value if source is null/undefined + */ + defaultValue: external_exports.unknown().optional().describe("Default if source is null/undefined") +}); +var HttpMethod3 = external_exports.enum([ + "GET", + "POST", + "PUT", + "DELETE", + "PATCH", + "HEAD", + "OPTIONS" +]); +var HttpMethodSchema3 = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); +var HttpRequestSchema2 = external_exports.object({ + url: external_exports.string().describe("API endpoint URL"), + method: HttpMethodSchema3.optional().default("GET").describe("HTTP method"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), + body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") +}); +var CorsConfigSchema3 = external_exports.object({ + /** + * Enable CORS + */ + enabled: external_exports.boolean().default(true).describe("Enable CORS"), + /** + * Allowed origins (* for all) + */ + origins: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.string()) + ]).default("*").describe("Allowed origins (* for all)"), + /** + * Allowed HTTP methods + */ + methods: external_exports.array(HttpMethod3).optional().describe("Allowed HTTP methods"), + /** + * Allow credentials (cookies, authorization headers) + */ + credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), + /** + * Preflight cache duration in seconds + */ + maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") +}); +var RateLimitConfigSchema3 = external_exports.object({ + /** + * Enable rate limiting + */ + enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), + /** + * Time window in milliseconds + */ + windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), + /** + * Max requests per window + */ + maxRequests: external_exports.number().int().default(100).describe("Max requests per window") +}); +var StaticMountSchema3 = external_exports.object({ + /** + * URL path to serve from + */ + path: external_exports.string().describe("URL path to serve from"), + /** + * Physical directory to serve + */ + directory: external_exports.string().describe("Physical directory to serve"), + /** + * Cache-Control header value + */ + cacheControl: external_exports.string().optional().describe("Cache-Control header value") +}); +var AggregationFunctionEnum = external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "percentile", + "median", + "stddev", + "variance" +]).describe("Standard aggregation functions"); +var SortDirectionEnum2 = external_exports.enum(["asc", "desc"]).describe("Sort order direction"); +var SortItemSchema = external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + order: SortDirectionEnum2.describe("Sort direction") +}).describe("Sort field and direction pair"); +var MutationEventEnum = external_exports.enum([ + "insert", + "update", + "delete", + "upsert" +]).describe("Data mutation event types"); +var IsolationLevelEnum2 = external_exports.enum([ + "read_uncommitted", + "read_committed", + "repeatable_read", + "serializable", + "snapshot" +]).describe("Transaction isolation levels (snake_case standard)"); +var CacheStrategyEnum = external_exports.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy"); +var MetadataFormatSchema3 = external_exports.enum(["yaml", "json", "typescript", "javascript"]).describe("Metadata file format"); +var BaseMetadataRecordSchema = external_exports.object({ + id: external_exports.string().describe("Unique metadata record identifier"), + type: external_exports.string().describe('Metadata type (e.g. "object", "view", "flow")'), + name: SnakeCaseIdentifierSchema4.describe("Machine name (snake_case)"), + format: MetadataFormatSchema3.optional().describe("Source file format") +}).describe("Base metadata record fields shared across kernel and system"); +var ObjectNameSchema = SnakeCaseIdentifierSchema4.brand().describe("Branded object name (snake_case, no dots)"); +var FieldNameSchema = SnakeCaseIdentifierSchema4.brand().describe("Branded field name (snake_case, no dots)"); +var ViewNameSchema = SystemIdentifierSchema4.brand().describe("Branded view name (system identifier)"); +var AppNameSchema = SystemIdentifierSchema4.brand().describe("Branded app name (system identifier)"); +var FlowNameSchema = SystemIdentifierSchema4.brand().describe("Branded flow name (system identifier)"); +var RoleNameSchema = SystemIdentifierSchema4.brand().describe("Branded role name (system identifier)"); +var EncryptionAlgorithmSchema4 = external_exports.enum([ + "aes-256-gcm", + "aes-256-cbc", + "chacha20-poly1305" +]).describe("Supported encryption algorithm"); +var KeyManagementProviderSchema4 = external_exports.enum([ + "local", + "aws-kms", + "azure-key-vault", + "gcp-kms", + "hashicorp-vault" +]).describe("Key management service provider"); +var KeyRotationPolicySchema4 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), + frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), + retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), + autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") +}).describe("Policy for automatic encryption key rotation"); +var EncryptionConfigSchema4 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), + algorithm: EncryptionAlgorithmSchema4.default("aes-256-gcm").describe("Encryption algorithm"), + keyManagement: external_exports.object({ + provider: KeyManagementProviderSchema4.describe("Key management service provider"), + keyId: external_exports.string().optional().describe("Key identifier in the provider"), + rotationPolicy: KeyRotationPolicySchema4.optional().describe("Key rotation policy") + }).describe("Key management configuration"), + scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), + deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), + searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") +}).describe("Field-level encryption configuration"); +external_exports.object({ + fieldName: external_exports.string().describe("Name of the field to encrypt"), + encryptionConfig: EncryptionConfigSchema4.describe("Encryption settings for this field"), + indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") +}).describe("Per-field encryption assignment"); +var MaskingStrategySchema4 = external_exports.enum([ + "redact", + // Complete redaction: **** + "partial", + // Partial masking: 138****5678 + "hash", + // Hash value: sha256(value) + "tokenize", + // Tokenization: token-12345 + "randomize", + // Randomize: generate random value + "nullify", + // Null value: null + "substitute" + // Substitute with dummy data +]).describe("Data masking strategy for PII protection"); +var MaskingRuleSchema4 = external_exports.object({ + field: external_exports.string().describe("Field name to apply masking to"), + strategy: MaskingStrategySchema4.describe("Masking strategy to use"), + pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), + preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), + preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), + roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), + exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") +}).describe("Masking rule for a single field"); +external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable data masking"), + rules: external_exports.array(MaskingRuleSchema4).describe("List of field-level masking rules"), + auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") +}).describe("Top-level data masking configuration for PII protection"); +var FieldType4 = external_exports.enum([ + // Core Text + "text", + "textarea", + "email", + "url", + "phone", + "password", + // Rich Content + "markdown", + "html", + "richtext", + // Numbers + "number", + "currency", + "percent", + // Date & Time + "date", + "datetime", + "time", + // Logic + "boolean", + "toggle", + // Toggle is a distinct UI from checkbox + // Selection + "select", + // Single select dropdown + "multiselect", + // Multi select (often tags) + "radio", + // Radio group + "checkboxes", + // Checkbox group + // Relational + "lookup", + "master_detail", + // Dynamic reference + "tree", + // Hierarchical reference + // Media + "image", + "file", + "avatar", + "video", + "audio", + // Calculated / System + "formula", + "summary", + "autonumber", + // Enhanced Types + "location", + // GPS coordinates + "address", + // Structured address + "code", + // Code editor (JSON/SQL/JS) + "json", + // Structured JSON data + "color", + // Color picker + "rating", + // Star rating + "slider", + // Numeric slider + "signature", + // Digital signature + "qrcode", + // QR code / Barcode + "progress", + // Progress bar + "tags", + // Simple tag list + // AI/ML Types + "vector" + // Vector embeddings for AI/ML (semantic search, RAG) +]); +var SelectOptionSchema4 = external_exports.object({ + label: external_exports.string().describe("Display label (human-readable, any case allowed)"), + value: SystemIdentifierSchema4.describe("Stored value (lowercase machine identifier)"), + color: external_exports.string().optional().describe("Color code for badges/charts"), + default: external_exports.boolean().optional().describe("Is default option") +}); +external_exports.object({ + latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), + longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), + altitude: external_exports.number().optional().describe("Altitude in meters"), + accuracy: external_exports.number().optional().describe("Accuracy in meters") +}); +var CurrencyConfigSchema4 = external_exports.object({ + precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), + currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), + defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") +}); +external_exports.object({ + value: external_exports.number().describe("Monetary amount"), + currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") +}); +external_exports.object({ + street: external_exports.string().optional().describe("Street address"), + city: external_exports.string().optional().describe("City name"), + state: external_exports.string().optional().describe("State/Province"), + postalCode: external_exports.string().optional().describe("Postal/ZIP code"), + country: external_exports.string().optional().describe("Country name or code"), + countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), + formatted: external_exports.string().optional().describe("Formatted address string") +}); +var VectorConfigSchema4 = external_exports.object({ + dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), + distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), + normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), + indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), + indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") +}); +var FileAttachmentConfigSchema4 = external_exports.object({ + /** File Size Limits */ + minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), + maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), + /** File Type Restrictions */ + allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), + blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), + allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), + blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), + /** Virus Scanning */ + virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), + virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), + virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), + quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), + /** Storage Configuration */ + storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), + storageBucket: external_exports.string().optional().describe("Target bucket name"), + storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), + /** Image-Specific Validation */ + imageValidation: external_exports.object({ + minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), + maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), + minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), + maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), + aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), + generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), + thumbnailSizes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), + width: external_exports.number().min(1).describe("Thumbnail width in pixels"), + height: external_exports.number().min(1).describe("Thumbnail height in pixels"), + crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") + })).optional().describe("Thumbnail size configurations"), + preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), + autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") + }).optional().describe("Image-specific validation rules"), + /** Upload Behavior */ + allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), + allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), + allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), + requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), + /** Metadata Extraction */ + extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), + extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), + /** Versioning */ + versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), + maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), + /** Access Control */ + publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), + presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") +}).refine((data) => { + if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { + return false; + } + return true; +}, { + message: "minSize must be less than or equal to maxSize" +}).refine((data) => { + if (data.virusScanProvider !== void 0 && data.virusScan !== true) { + return false; + } + return true; +}, { + message: "virusScanProvider requires virusScan to be enabled" +}); +var DataQualityRulesSchema4 = external_exports.object({ + /** Enforce uniqueness constraint */ + uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), + /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ + completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), + /** Accuracy validation against authoritative source */ + accuracy: external_exports.object({ + source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), + threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") + }).optional().describe("Accuracy validation configuration") +}); +var ComputedFieldCacheSchema4 = external_exports.object({ + /** Enable caching for this computed field */ + enabled: external_exports.boolean().describe("Enable caching for computed field results"), + /** Time-to-live in seconds */ + ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), + /** Array of field paths that trigger cache invalidation when changed */ + invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') +}); +external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), + label: external_exports.string().optional().describe("Human readable label"), + type: FieldType4.describe("Field Data Type"), + description: external_exports.string().optional().describe("Tooltip/Help text"), + format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), + /** Storage Layer Mapping */ + columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), + /** Database Constraints */ + required: external_exports.boolean().default(false).describe("Is required"), + searchable: external_exports.boolean().default(false).describe("Is searchable"), + multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), + unique: external_exports.boolean().default(false).describe("Is unique constraint"), + defaultValue: external_exports.unknown().optional().describe("Default value"), + /** Text/String Constraints */ + maxLength: external_exports.number().optional().describe("Max character length"), + minLength: external_exports.number().optional().describe("Min character length"), + /** Number Constraints */ + precision: external_exports.number().optional().describe("Total digits"), + scale: external_exports.number().optional().describe("Decimal places"), + min: external_exports.number().optional().describe("Minimum value"), + max: external_exports.number().optional().describe("Maximum value"), + /** Selection Options */ + options: external_exports.array(SelectOptionSchema4).optional().describe("Static options for select/multiselect"), + /** + * Relationship Config + * + * Used by `lookup` and `master_detail` field types to define cross-object references. + * The `reference` property is **required** for these types — it identifies the target + * object whose records this field links to. The engine uses `reference` during $expand + * post-processing to resolve foreign key IDs into full related objects via batch queries. + * + * For `master_detail` fields, the parent record controls the lifecycle of child records + * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. + */ + reference: external_exports.string().optional().describe( + "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." + ), + referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), + writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), + deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), + /** Calculation */ + expression: external_exports.string().optional().describe("Formula expression"), + summaryOperations: external_exports.object({ + object: external_exports.string().describe("Source child object name for roll-up"), + field: external_exports.string().describe("Field on child object to aggregate"), + function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") + }).optional().describe("Roll-up summary definition"), + /** Enhanced Field Type Configurations */ + // Code field config + language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), + theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), + lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), + // Rating field config + maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), + allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), + // Location field config + displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), + allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), + // Address field config + addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), + // Color field config + colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), + allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), + presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), + // Slider field config + step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), + showValue: external_exports.boolean().optional().describe("Display current value on slider"), + marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), + // QR Code / Barcode field config + // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' + // Runtime validation should enforce this constraint + barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), + qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), + displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), + allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), + // Currency field config + currencyConfig: CurrencyConfigSchema4.optional().describe("Configuration for currency field type"), + // Vector field config + vectorConfig: VectorConfigSchema4.optional().describe("Configuration for vector field type (AI/ML embeddings)"), + // File attachment field config + fileAttachmentConfig: FileAttachmentConfigSchema4.optional().describe("Configuration for file and attachment field types"), + /** Enhanced Security & Compliance */ + // Encryption configuration + encryptionConfig: EncryptionConfigSchema4.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), + // Data masking rules + maskingRule: MaskingRuleSchema4.optional().describe("Data masking rules for PII protection"), + // Audit trail + auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), + /** Field Dependencies & Relationships */ + // Field dependencies + dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), + /** Computed Field Optimization */ + // Computed field caching + cached: ComputedFieldCacheSchema4.optional().describe("Caching configuration for computed/formula fields"), + /** Data Quality & Governance */ + // Data quality rules + dataQuality: DataQualityRulesSchema4.optional().describe("Data quality validation and monitoring rules"), + /** Layout & Grouping */ + group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), + /** Conditional Requirements */ + conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), + /** Security & Visibility */ + hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), + readonly: external_exports.boolean().default(false).describe("Read-only in UI"), + sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), + inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), + trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), + caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), + autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), + /** Indexing */ + index: external_exports.boolean().default(false).describe("Create standard database index"), + externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") +}); +var PLURAL_TO_SINGULAR = { + objects: "object", + apps: "app", + pages: "page", + dashboards: "dashboard", + reports: "report", + actions: "action", + themes: "theme", + workflows: "workflow", + approvals: "approval", + flows: "flow", + roles: "role", + permissions: "permission", + profiles: "profile", + sharingRules: "sharingRule", + policies: "policy", + apis: "api", + webhooks: "webhook", + agents: "agent", + ragPipelines: "ragPipeline", + hooks: "hook", + mappings: "mapping", + analyticsCubes: "analyticsCube", + connectors: "connector", + datasources: "datasource", + views: "view" +}; +var SINGULAR_TO_PLURAL = Object.fromEntries( + Object.entries(PLURAL_TO_SINGULAR).map(([plural, singular]) => [singular, plural]) +); +function pluralToSingular(key) { + return PLURAL_TO_SINGULAR[key] ?? key; +} + +// ../../packages/runtime/dist/index.js +var DriverPlugin = class { + constructor(driver, driverName) { + this.type = "driver"; + this.version = "1.0.0"; + this.init = async (ctx) => { + const serviceName = `driver.${this.driver.name || "unknown"}`; + ctx.registerService(serviceName, this.driver); + ctx.logger.info("Driver service registered", { + serviceName, + driverName: this.driver.name, + driverVersion: this.driver.version + }); + }; + this.start = async (ctx) => { + if (this.name.startsWith("com.objectstack.driver.")) { + } + try { + const metadata = ctx.getService("metadata"); + if (metadata && metadata.addDatasource) { + const datasources = metadata.getDatasources ? metadata.getDatasources() : []; + const hasDefault = datasources.some((ds) => ds.name === "default"); + if (!hasDefault) { + ctx.logger.info(`[DriverPlugin] No 'default' datasource found. Auto-configuring '${this.driver.name}' as default.`); + await metadata.addDatasource({ + name: "default", + driver: this.driver.name + // The driver's internal name (e.g. com.objectstack.driver.memory) + }); + } + } + } catch (e) { + ctx.logger.debug("[DriverPlugin] Failed to auto-configure default datasource (Metadata service missing?)", { error: e }); + } + ctx.logger.debug("Driver plugin started", { driverName: this.driver.name || "unknown" }); + }; + this.driver = driver; + this.name = `com.objectstack.driver.${driverName || driver.name || "unknown"}`; + } +}; +var DEFAULT_EXTERNAL_ID_FIELD = "name"; +var SeedLoaderService = class { + constructor(engine, metadata, logger2) { + this.engine = engine; + this.metadata = metadata; + this.logger = logger2; + } + // ========================================================================== + // Public API + // ========================================================================== + async load(request) { + const startTime = Date.now(); + const config4 = request.config; + const allErrors = []; + const allResults = []; + const datasets = this.filterByEnv(request.datasets, config4.env); + if (datasets.length === 0) { + return this.buildEmptyResult(config4, Date.now() - startTime); + } + const objectNames = datasets.map((d) => d.object); + const graph = await this.buildDependencyGraph(objectNames); + this.logger.info("[SeedLoader] Dependency graph built", { + objects: objectNames.length, + insertOrder: graph.insertOrder, + circularDeps: graph.circularDependencies.length + }); + const orderedDatasets = this.orderDatasets(datasets, graph.insertOrder); + const refMap = this.buildReferenceMap(graph); + const insertedRecords = /* @__PURE__ */ new Map(); + const deferredUpdates = []; + for (const dataset of orderedDatasets) { + const result = await this.loadDataset( + dataset, + config4, + refMap, + insertedRecords, + deferredUpdates, + allErrors + ); + allResults.push(result); + if (config4.haltOnError && result.errored > 0) { + this.logger.warn("[SeedLoader] Halting on first error", { object: dataset.object }); + break; + } + } + if (config4.multiPass && deferredUpdates.length > 0 && !config4.dryRun) { + this.logger.info("[SeedLoader] Pass 2: resolving deferred references", { + count: deferredUpdates.length + }); + await this.resolveDeferredUpdates(deferredUpdates, insertedRecords, allResults, allErrors); + } + const durationMs = Date.now() - startTime; + return this.buildResult(config4, graph, allResults, allErrors, durationMs); + } + async buildDependencyGraph(objectNames) { + const nodes = []; + const objectSet = new Set(objectNames); + for (const objectName of objectNames) { + const objDef = await this.metadata.getObject(objectName); + const dependsOn = []; + const references = []; + if (objDef && objDef.fields) { + const fields = objDef.fields; + for (const [fieldName, fieldDef] of Object.entries(fields)) { + if ((fieldDef.type === "lookup" || fieldDef.type === "master_detail") && fieldDef.reference) { + const targetObject = fieldDef.reference; + if (objectSet.has(targetObject) && !dependsOn.includes(targetObject)) { + dependsOn.push(targetObject); + } + references.push({ + field: fieldName, + targetObject, + targetField: DEFAULT_EXTERNAL_ID_FIELD, + fieldType: fieldDef.type + }); + } + } + } + nodes.push({ object: objectName, dependsOn, references }); + } + const { insertOrder, circularDependencies } = this.topologicalSort(nodes); + return { nodes, insertOrder, circularDependencies }; + } + async validate(datasets, config4) { + const parsedConfig = SeedLoaderConfigSchema.parse({ ...config4, dryRun: true }); + return this.load({ datasets, config: parsedConfig }); + } + // ========================================================================== + // Internal: Dataset Loading + // ========================================================================== + async loadDataset(dataset, config4, refMap, insertedRecords, deferredUpdates, allErrors) { + const objectName = dataset.object; + const mode = dataset.mode || config4.defaultMode; + const externalId = dataset.externalId || "name"; + let inserted = 0; + let updated = 0; + let skipped = 0; + let errored = 0; + let referencesResolved = 0; + let referencesDeferred = 0; + const errors = []; + if (!insertedRecords.has(objectName)) { + insertedRecords.set(objectName, /* @__PURE__ */ new Map()); + } + let existingRecords; + if ((mode === "upsert" || mode === "update" || mode === "ignore") && !config4.dryRun) { + existingRecords = await this.loadExistingRecords(objectName, externalId); + } + const objectRefs = refMap.get(objectName) || []; + for (let i = 0; i < dataset.records.length; i++) { + const record2 = { ...dataset.records[i] }; + for (const ref of objectRefs) { + const fieldValue = record2[ref.field]; + if (fieldValue === void 0 || fieldValue === null) continue; + if (typeof fieldValue !== "string" || this.looksLikeInternalId(fieldValue)) continue; + const targetMap = insertedRecords.get(ref.targetObject); + const resolvedId = targetMap?.get(String(fieldValue)); + if (resolvedId) { + record2[ref.field] = resolvedId; + referencesResolved++; + } else if (!config4.dryRun) { + const dbId = await this.resolveFromDatabase(ref.targetObject, ref.targetField, fieldValue); + if (dbId) { + record2[ref.field] = dbId; + referencesResolved++; + } else if (config4.multiPass) { + record2[ref.field] = null; + deferredUpdates.push({ + objectName, + recordExternalId: String(record2[externalId] ?? ""), + field: ref.field, + targetObject: ref.targetObject, + targetField: ref.targetField, + attemptedValue: fieldValue, + recordIndex: i + }); + referencesDeferred++; + } else { + const error49 = { + sourceObject: objectName, + field: ref.field, + targetObject: ref.targetObject, + targetField: ref.targetField, + attemptedValue: fieldValue, + recordIndex: i, + message: `Cannot resolve reference: ${objectName}.${ref.field} = '${fieldValue}' \u2192 ${ref.targetObject}.${ref.targetField} not found` + }; + errors.push(error49); + allErrors.push(error49); + } + } else { + const targetMap2 = insertedRecords.get(ref.targetObject); + if (!targetMap2?.has(String(fieldValue))) { + const error49 = { + sourceObject: objectName, + field: ref.field, + targetObject: ref.targetObject, + targetField: ref.targetField, + attemptedValue: fieldValue, + recordIndex: i, + message: `[dry-run] Reference may not resolve: ${objectName}.${ref.field} = '${fieldValue}' \u2192 ${ref.targetObject}.${ref.targetField}` + }; + errors.push(error49); + allErrors.push(error49); + } + } + } + if (!config4.dryRun) { + try { + const result = await this.writeRecord( + objectName, + record2, + mode, + externalId, + existingRecords + ); + if (result.action === "inserted") inserted++; + else if (result.action === "updated") updated++; + else if (result.action === "skipped") skipped++; + const externalIdValue = String(record2[externalId] ?? ""); + const internalId = result.id; + if (externalIdValue && internalId) { + insertedRecords.get(objectName).set(externalIdValue, String(internalId)); + } + } catch (err) { + errored++; + this.logger.warn(`[SeedLoader] Failed to write ${objectName} record`, { + error: err.message, + recordIndex: i + }); + } + } else { + const externalIdValue = String(record2[externalId] ?? ""); + if (externalIdValue) { + insertedRecords.get(objectName).set(externalIdValue, `dry-run-id-${i}`); + } + inserted++; + } + } + return { + object: objectName, + mode, + inserted, + updated, + skipped, + errored, + total: dataset.records.length, + referencesResolved, + referencesDeferred, + errors + }; + } + // ========================================================================== + // Internal: Reference Resolution + // ========================================================================== + async resolveFromDatabase(targetObject, targetField, value) { + try { + const records = await this.engine.find(targetObject, { + where: { [targetField]: value }, + fields: ["id"], + limit: 1 + }); + if (records && records.length > 0) { + return String(records[0].id || records[0]._id); + } + } catch { + } + return null; + } + async resolveDeferredUpdates(deferredUpdates, insertedRecords, allResults, allErrors) { + for (const deferred of deferredUpdates) { + const targetMap = insertedRecords.get(deferred.targetObject); + let resolvedId = targetMap?.get(String(deferred.attemptedValue)); + if (!resolvedId) { + resolvedId = await this.resolveFromDatabase( + deferred.targetObject, + deferred.targetField, + deferred.attemptedValue + ) ?? void 0; + } + if (resolvedId) { + const objectRecordMap = insertedRecords.get(deferred.objectName); + const recordId = objectRecordMap?.get(deferred.recordExternalId); + if (recordId) { + try { + await this.engine.update(deferred.objectName, { + id: recordId, + [deferred.field]: resolvedId + }); + const resultEntry = allResults.find((r) => r.object === deferred.objectName); + if (resultEntry) { + resultEntry.referencesResolved++; + resultEntry.referencesDeferred--; + } + } catch (err) { + this.logger.warn("[SeedLoader] Failed to resolve deferred reference", { + object: deferred.objectName, + field: deferred.field, + error: err.message + }); + } + } + } else { + const error49 = { + sourceObject: deferred.objectName, + field: deferred.field, + targetObject: deferred.targetObject, + targetField: deferred.targetField, + attemptedValue: deferred.attemptedValue, + recordIndex: deferred.recordIndex, + message: `Deferred reference unresolved after pass 2: ${deferred.objectName}.${deferred.field} = '${deferred.attemptedValue}' \u2192 ${deferred.targetObject}.${deferred.targetField} not found` + }; + const resultEntry = allResults.find((r) => r.object === deferred.objectName); + if (resultEntry) { + resultEntry.errors.push(error49); + } + allErrors.push(error49); + } + } + } + // ========================================================================== + // Internal: Write Operations + // ========================================================================== + async writeRecord(objectName, record2, mode, externalId, existingRecords) { + const externalIdValue = record2[externalId]; + const existing = existingRecords?.get(String(externalIdValue ?? "")); + switch (mode) { + case "insert": { + const result = await this.engine.insert(objectName, record2); + return { action: "inserted", id: this.extractId(result) }; + } + case "update": { + if (!existing) { + return { action: "skipped" }; + } + const id = this.extractId(existing); + await this.engine.update(objectName, { ...record2, id }); + return { action: "updated", id }; + } + case "upsert": { + if (existing) { + const id = this.extractId(existing); + await this.engine.update(objectName, { ...record2, id }); + return { action: "updated", id }; + } else { + const result = await this.engine.insert(objectName, record2); + return { action: "inserted", id: this.extractId(result) }; + } + } + case "ignore": { + if (existing) { + return { action: "skipped", id: this.extractId(existing) }; + } + const result = await this.engine.insert(objectName, record2); + return { action: "inserted", id: this.extractId(result) }; + } + case "replace": { + const result = await this.engine.insert(objectName, record2); + return { action: "inserted", id: this.extractId(result) }; + } + default: { + const result = await this.engine.insert(objectName, record2); + return { action: "inserted", id: this.extractId(result) }; + } + } + } + // ========================================================================== + // Internal: Dependency Graph + // ========================================================================== + /** + * Kahn's algorithm for topological sort with cycle detection. + */ + topologicalSort(nodes) { + const inDegree = /* @__PURE__ */ new Map(); + const adjacency = /* @__PURE__ */ new Map(); + const objectSet = new Set(nodes.map((n) => n.object)); + for (const node of nodes) { + inDegree.set(node.object, 0); + adjacency.set(node.object, []); + } + for (const node of nodes) { + for (const dep of node.dependsOn) { + if (objectSet.has(dep) && dep !== node.object) { + adjacency.get(dep).push(node.object); + inDegree.set(node.object, (inDegree.get(node.object) || 0) + 1); + } + } + } + const queue = []; + for (const [obj, degree] of inDegree) { + if (degree === 0) queue.push(obj); + } + const insertOrder = []; + while (queue.length > 0) { + const current = queue.shift(); + insertOrder.push(current); + for (const neighbor of adjacency.get(current) || []) { + const newDegree = (inDegree.get(neighbor) || 0) - 1; + inDegree.set(neighbor, newDegree); + if (newDegree === 0) { + queue.push(neighbor); + } + } + } + const circularDependencies = []; + const remaining = nodes.filter((n) => !insertOrder.includes(n.object)); + if (remaining.length > 0) { + const cycles = this.findCycles(remaining); + circularDependencies.push(...cycles); + for (const node of remaining) { + if (!insertOrder.includes(node.object)) { + insertOrder.push(node.object); + } + } + } + return { insertOrder, circularDependencies }; + } + findCycles(nodes) { + const cycles = []; + const nodeMap = new Map(nodes.map((n) => [n.object, n])); + const visited = /* @__PURE__ */ new Set(); + const inStack = /* @__PURE__ */ new Set(); + const dfs = (current, path3) => { + if (inStack.has(current)) { + const cycleStart = path3.indexOf(current); + if (cycleStart !== -1) { + cycles.push([...path3.slice(cycleStart), current]); + } + return; + } + if (visited.has(current)) return; + visited.add(current); + inStack.add(current); + path3.push(current); + const node = nodeMap.get(current); + if (node) { + for (const dep of node.dependsOn) { + if (nodeMap.has(dep)) { + dfs(dep, [...path3]); + } + } + } + inStack.delete(current); + }; + for (const node of nodes) { + if (!visited.has(node.object)) { + dfs(node.object, []); + } + } + return cycles; + } + // ========================================================================== + // Internal: Helpers + // ========================================================================== + filterByEnv(datasets, env2) { + if (!env2) return datasets; + return datasets.filter((d) => d.env.includes(env2)); + } + orderDatasets(datasets, insertOrder) { + const orderMap = new Map(insertOrder.map((name, i) => [name, i])); + return [...datasets].sort((a, b) => { + const orderA = orderMap.get(a.object) ?? Number.MAX_SAFE_INTEGER; + const orderB = orderMap.get(b.object) ?? Number.MAX_SAFE_INTEGER; + return orderA - orderB; + }); + } + buildReferenceMap(graph) { + const map3 = /* @__PURE__ */ new Map(); + for (const node of graph.nodes) { + if (node.references.length > 0) { + map3.set(node.object, node.references); + } + } + return map3; + } + async loadExistingRecords(objectName, externalId) { + const map3 = /* @__PURE__ */ new Map(); + try { + const records = await this.engine.find(objectName, { + fields: ["id", externalId] + }); + for (const record2 of records || []) { + const key = String(record2[externalId] ?? ""); + if (key) { + map3.set(key, record2); + } + } + } catch { + } + return map3; + } + looksLikeInternalId(value) { + if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) { + return true; + } + if (/^[0-9a-f]{24}$/i.test(value)) { + return true; + } + return false; + } + extractId(record2) { + if (!record2) return void 0; + return String(record2.id || record2._id || ""); + } + buildEmptyResult(config4, durationMs) { + return { + success: true, + dryRun: config4.dryRun, + dependencyGraph: { nodes: [], insertOrder: [], circularDependencies: [] }, + results: [], + errors: [], + summary: { + objectsProcessed: 0, + totalRecords: 0, + totalInserted: 0, + totalUpdated: 0, + totalSkipped: 0, + totalErrored: 0, + totalReferencesResolved: 0, + totalReferencesDeferred: 0, + circularDependencyCount: 0, + durationMs + } + }; + } + buildResult(config4, graph, results, errors, durationMs) { + const summary = { + objectsProcessed: results.length, + totalRecords: results.reduce((sum, r) => sum + r.total, 0), + totalInserted: results.reduce((sum, r) => sum + r.inserted, 0), + totalUpdated: results.reduce((sum, r) => sum + r.updated, 0), + totalSkipped: results.reduce((sum, r) => sum + r.skipped, 0), + totalErrored: results.reduce((sum, r) => sum + r.errored, 0), + totalReferencesResolved: results.reduce((sum, r) => sum + r.referencesResolved, 0), + totalReferencesDeferred: results.reduce((sum, r) => sum + r.referencesDeferred, 0), + circularDependencyCount: graph.circularDependencies.length, + durationMs + }; + const hasErrors = errors.length > 0 || summary.totalErrored > 0; + return { + success: !hasErrors, + dryRun: config4.dryRun, + dependencyGraph: graph, + results, + errors, + summary + }; + } +}; +var AppPlugin = class { + constructor(bundle) { + this.type = "app"; + this.init = async (ctx) => { + const sys2 = this.bundle.manifest || this.bundle; + const appId2 = sys2.id || sys2.name; + ctx.logger.info("Registering App Service", { + appId: appId2, + pluginName: this.name, + version: this.version + }); + const servicePayload = this.bundle.manifest ? { ...this.bundle.manifest, ...this.bundle } : this.bundle; + ctx.getService("manifest").register(servicePayload); + }; + this.start = async (ctx) => { + const sys2 = this.bundle.manifest || this.bundle; + const appId2 = sys2.id || sys2.name; + let ql; + try { + ql = ctx.getService("objectql"); + } catch { + } + if (!ql) { + ctx.logger.warn("ObjectQL engine service not found", { + appName: this.name, + appId: appId2 + }); + return; + } + ctx.logger.debug("Retrieved ObjectQL engine service", { appId: appId2 }); + const runtime = this.bundle.default || this.bundle; + if (runtime && typeof runtime.onEnable === "function") { + ctx.logger.info("Executing runtime.onEnable", { + appName: this.name, + appId: appId2 + }); + const hostContext = { + ...ctx, + ql, + logger: ctx.logger, + drivers: { + register: (driver) => { + ctx.logger.debug("Registering driver via app runtime", { + driverName: driver.name, + appId: appId2 + }); + ql.registerDriver(driver); + } + } + }; + await runtime.onEnable(hostContext); + ctx.logger.debug("Runtime.onEnable completed", { appId: appId2 }); + } else { + ctx.logger.debug("No runtime.onEnable function found", { appId: appId2 }); + } + this.loadTranslations(ctx, appId2); + const seedDatasets = []; + if (Array.isArray(this.bundle.data)) { + seedDatasets.push(...this.bundle.data); + } + const manifest = this.bundle.manifest || this.bundle; + if (manifest && Array.isArray(manifest.data)) { + seedDatasets.push(...manifest.data); + } + const namespace = (this.bundle.manifest || this.bundle)?.namespace; + const RESERVED_NS = /* @__PURE__ */ new Set(["base", "system"]); + const toFQN = (name) => { + if (name.includes("__") || !namespace || RESERVED_NS.has(namespace)) return name; + return `${namespace}__${name}`; + }; + if (seedDatasets.length > 0) { + ctx.logger.info(`[AppPlugin] Found ${seedDatasets.length} seed datasets for ${appId2}`); + const normalizedDatasets = seedDatasets.filter((d) => d.object && Array.isArray(d.records)).map((d) => ({ + ...d, + object: toFQN(d.object) + })); + try { + const metadata = ctx.getService("metadata"); + if (metadata) { + const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger); + const { SeedLoaderRequestSchema: SeedLoaderRequestSchema3 } = await Promise.resolve().then(() => (init_data(), data_exports)); + const request = SeedLoaderRequestSchema3.parse({ + datasets: normalizedDatasets, + config: { defaultMode: "upsert", multiPass: true } + }); + const result = await seedLoader.load(request); + ctx.logger.info("[Seeder] Seed loading complete", { + inserted: result.summary.totalInserted, + updated: result.summary.totalUpdated, + errors: result.errors.length + }); + } else { + ctx.logger.debug("[Seeder] No metadata service; using basic insert fallback"); + for (const dataset of normalizedDatasets) { + ctx.logger.info(`[Seeder] Seeding ${dataset.records.length} records for ${dataset.object}`); + for (const record2 of dataset.records) { + try { + await ql.insert(dataset.object, record2); + } catch (err) { + ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: err.message }); + } + } + } + ctx.logger.info("[Seeder] Data seeding complete."); + } + } catch (err) { + ctx.logger.warn("[Seeder] SeedLoaderService failed, falling back to basic insert", { error: err.message }); + for (const dataset of normalizedDatasets) { + for (const record2 of dataset.records) { + try { + await ql.insert(dataset.object, record2); + } catch (insertErr) { + ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: insertErr.message }); + } + } + } + ctx.logger.info("[Seeder] Data seeding complete (fallback)."); + } + } + }; + this.bundle = bundle; + const sys = bundle.manifest || bundle; + const appId = sys.id || sys.name || "unnamed-app"; + this.name = `plugin.app.${appId}`; + this.version = sys.version; + } + /** + * Auto-load i18n translation bundles from the app config into the + * kernel's i18n service. Handles both `translations` (array of + * TranslationBundle) and `i18n` config (default locale, etc.). + * + * Gracefully skips when the i18n service is not registered — + * this keeps AppPlugin resilient across server/dev/mock environments. + */ + loadTranslations(ctx, appId) { + let i18nService; + try { + i18nService = ctx.getService("i18n"); + } catch { + } + const bundles = []; + if (Array.isArray(this.bundle.translations)) { + bundles.push(...this.bundle.translations); + } + const manifest = this.bundle.manifest || this.bundle; + if (manifest && Array.isArray(manifest.translations) && manifest.translations !== this.bundle.translations) { + bundles.push(...manifest.translations); + } + if (!i18nService) { + if (bundles.length > 0) { + ctx.logger.warn( + `[i18n] App "${appId}" has ${bundles.length} translation bundle(s) but no i18n service is registered. Translations will not be served via REST API. Register I18nServicePlugin from @objectstack/service-i18n, or use DevPlugin which auto-detects translations and registers the i18n service automatically.` + ); + } else { + ctx.logger.debug("[i18n] No i18n service registered; skipping translation loading", { appId }); + } + return; + } + const i18nConfig = this.bundle.i18n || (this.bundle.manifest || this.bundle)?.i18n; + if (i18nConfig?.defaultLocale && typeof i18nService.setDefaultLocale === "function") { + i18nService.setDefaultLocale(i18nConfig.defaultLocale); + ctx.logger.debug("[i18n] Set default locale", { appId, locale: i18nConfig.defaultLocale }); + } + if (bundles.length === 0) { + return; + } + let loadedLocales = 0; + for (const bundle of bundles) { + for (const [locale, data] of Object.entries(bundle)) { + if (data && typeof data === "object") { + try { + i18nService.loadTranslations(locale, data); + loadedLocales++; + } catch (err) { + ctx.logger.warn("[i18n] Failed to load translations", { appId, locale, error: err.message }); + } + } + } + } + const svcAny = i18nService; + if (svcAny._fallback || svcAny._dev) { + ctx.logger.info( + `[i18n] Loaded ${loadedLocales} locale(s) into in-memory i18n fallback for "${appId}". For production, consider registering I18nServicePlugin from @objectstack/service-i18n.` + ); + } else { + ctx.logger.info("[i18n] Loaded translation bundles", { appId, bundles: bundles.length, locales: loadedLocales }); + } + } +}; +function randomUUID() { + if (globalThis.crypto && typeof globalThis.crypto.randomUUID === "function") { + return globalThis.crypto.randomUUID(); + } + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = Math.random() * 16 | 0; + const v = c === "x" ? r : r & 3 | 8; + return v.toString(16); + }); +} +var HttpDispatcher = class { + // Casting to any to access dynamic props like broker, services, graphql + constructor(kernel) { + this.kernel = kernel; + } + success(data, meta3) { + return { + status: 200, + body: { success: true, data, meta: meta3 } + }; + } + error(message2, code = 500, details) { + return { + status: code, + body: { success: false, error: { message: message2, code, details } } + }; + } + /** + * 404 Route Not Found — no route is registered for this path. + */ + routeNotFound(route) { + return { + status: 404, + body: { + success: false, + error: { + code: 404, + message: `Route Not Found: ${route}`, + type: "ROUTE_NOT_FOUND", + route, + hint: "No route is registered for this path. Check the API discovery endpoint for available routes." + } + } + }; + } + ensureBroker() { + if (!this.kernel.broker) { + throw { statusCode: 500, message: "Kernel Broker not available" }; + } + return this.kernel.broker; + } + /** + * Generates the discovery JSON response for the API root. + * + * Uses the same async `resolveService()` fallback chain that request + * handlers use, so the reported service status is always consistent + * with the actual runtime availability. + */ + async getDiscoveryInfo(prefix) { + const [ + authSvc, + graphqlSvc, + searchSvc, + realtimeSvc, + filesSvc, + analyticsSvc, + workflowSvc, + aiSvc, + notificationSvc, + i18nSvc, + uiSvc, + automationSvc, + cacheSvc, + queueSvc, + jobSvc + ] = await Promise.all([ + this.resolveService(CoreServiceName.enum.auth), + this.resolveService(CoreServiceName.enum.graphql), + this.resolveService(CoreServiceName.enum.search), + this.resolveService(CoreServiceName.enum.realtime), + this.resolveService(CoreServiceName.enum["file-storage"]), + this.resolveService(CoreServiceName.enum.analytics), + this.resolveService(CoreServiceName.enum.workflow), + this.resolveService(CoreServiceName.enum.ai), + this.resolveService(CoreServiceName.enum.notification), + this.resolveService(CoreServiceName.enum.i18n), + this.resolveService(CoreServiceName.enum.ui), + this.resolveService(CoreServiceName.enum.automation), + this.resolveService(CoreServiceName.enum.cache), + this.resolveService(CoreServiceName.enum.queue), + this.resolveService(CoreServiceName.enum.job) + ]); + const hasAuth = !!authSvc; + const hasGraphQL = !!(graphqlSvc || this.kernel.graphql); + const hasSearch = !!searchSvc; + const hasWebSockets = !!realtimeSvc; + const hasFiles = !!filesSvc; + const hasAnalytics = !!analyticsSvc; + const hasWorkflow = !!workflowSvc; + const hasAi = !!aiSvc; + const hasNotification = !!notificationSvc; + const hasI18n = !!i18nSvc; + const hasUi = !!uiSvc; + const hasAutomation = !!automationSvc; + const hasCache = !!cacheSvc; + const hasQueue = !!queueSvc; + const hasJob = !!jobSvc; + const routes = { + data: `${prefix}/data`, + metadata: `${prefix}/meta`, + packages: `${prefix}/packages`, + auth: hasAuth ? `${prefix}/auth` : void 0, + ui: hasUi ? `${prefix}/ui` : void 0, + graphql: hasGraphQL ? `${prefix}/graphql` : void 0, + storage: hasFiles ? `${prefix}/storage` : void 0, + analytics: hasAnalytics ? `${prefix}/analytics` : void 0, + automation: hasAutomation ? `${prefix}/automation` : void 0, + workflow: hasWorkflow ? `${prefix}/workflow` : void 0, + realtime: hasWebSockets ? `${prefix}/realtime` : void 0, + notifications: hasNotification ? `${prefix}/notifications` : void 0, + ai: hasAi ? `${prefix}/ai` : void 0, + i18n: hasI18n ? `${prefix}/i18n` : void 0 + }; + const svcAvailable = (route, provider) => ({ + enabled: true, + status: "available", + handlerReady: true, + route, + provider + }); + const svcUnavailable = (name) => ({ + enabled: false, + status: "unavailable", + handlerReady: false, + message: `Install a ${name} plugin to enable` + }); + let locale = { default: "en", supported: ["en"], timezone: "UTC" }; + if (hasI18n && i18nSvc) { + const defaultLocale = typeof i18nSvc.getDefaultLocale === "function" ? i18nSvc.getDefaultLocale() : "en"; + const locales = typeof i18nSvc.getLocales === "function" ? i18nSvc.getLocales() : []; + locale = { + default: defaultLocale, + supported: locales.length > 0 ? locales : [defaultLocale], + timezone: "UTC" + }; + } + return { + name: "ObjectOS", + version: "1.0.0", + environment: getEnv("NODE_ENV", "development"), + routes, + endpoints: routes, + // Alias for backward compatibility with some clients + features: { + graphql: hasGraphQL, + search: hasSearch, + websockets: hasWebSockets, + files: hasFiles, + analytics: hasAnalytics, + ai: hasAi, + workflow: hasWorkflow, + notifications: hasNotification, + i18n: hasI18n + }, + services: { + // Kernel-provided (always available via protocol implementation) + metadata: { enabled: true, status: "degraded", handlerReady: true, route: routes.metadata, provider: "kernel", message: "In-memory registry; DB persistence pending" }, + data: svcAvailable(routes.data, "kernel"), + // Plugin-provided — only available when a plugin registers the service + auth: hasAuth ? svcAvailable(routes.auth) : svcUnavailable("auth"), + automation: hasAutomation ? svcAvailable(routes.automation) : svcUnavailable("automation"), + analytics: hasAnalytics ? svcAvailable(routes.analytics) : svcUnavailable("analytics"), + cache: hasCache ? svcAvailable() : svcUnavailable("cache"), + queue: hasQueue ? svcAvailable() : svcUnavailable("queue"), + job: hasJob ? svcAvailable() : svcUnavailable("job"), + ui: hasUi ? svcAvailable(routes.ui) : svcUnavailable("ui"), + workflow: hasWorkflow ? svcAvailable(routes.workflow) : svcUnavailable("workflow"), + realtime: hasWebSockets ? svcAvailable(routes.realtime) : svcUnavailable("realtime"), + notification: hasNotification ? svcAvailable(routes.notifications) : svcUnavailable("notification"), + ai: hasAi ? svcAvailable(routes.ai) : svcUnavailable("ai"), + i18n: hasI18n ? svcAvailable(routes.i18n) : svcUnavailable("i18n"), + graphql: hasGraphQL ? svcAvailable(routes.graphql) : svcUnavailable("graphql"), + "file-storage": hasFiles ? svcAvailable(routes.storage) : svcUnavailable("file-storage"), + search: hasSearch ? svcAvailable() : svcUnavailable("search") + }, + locale + }; + } + /** + * Handles GraphQL requests + */ + async handleGraphQL(body, context) { + if (!body || !body.query) { + throw { statusCode: 400, message: "Missing query in request body" }; + } + if (typeof this.kernel.graphql !== "function") { + throw { statusCode: 501, message: "GraphQL service not available" }; + } + return this.kernel.graphql(body.query, body.variables, { + request: context.request + }); + } + /** + * Handles Auth requests + * path: sub-path after /auth/ + */ + async handleAuth(path3, method, body, context) { + const authService = await this.getService(CoreServiceName.enum.auth); + if (authService && typeof authService.handler === "function") { + const response = await authService.handler(context.request, context.response); + return { handled: true, result: response }; + } + const normalizedPath = path3.replace(/^\/+/, ""); + if (normalizedPath === "login" && method.toUpperCase() === "POST") { + try { + const broker = this.ensureBroker(); + const data = await broker.call("auth.login", body, { request: context.request }); + return { handled: true, response: { status: 200, body: data } }; + } catch (error49) { + const statusCode = error49?.statusCode ?? error49?.status; + if (statusCode !== 500 || !error49?.message?.includes("Broker not available")) { + throw error49; + } + } + } + return this.mockAuthFallback(normalizedPath, method, body); + } + /** + * Provides mock auth responses for core better-auth endpoints when + * AuthPlugin is not loaded (e.g. MSW/browser-only environments). + * This ensures registration/sign-in flows do not 404 in mock mode. + */ + mockAuthFallback(path3, method, body) { + const m = method.toUpperCase(); + const MOCK_SESSION_EXPIRY_MS = 864e5; + if ((path3 === "sign-up/email" || path3 === "register") && m === "POST") { + const id = `mock_${randomUUID()}`; + return { + handled: true, + response: { + status: 200, + body: { + user: { id, name: body?.name || "Mock User", email: body?.email || "mock@test.local", emailVerified: false, createdAt: (/* @__PURE__ */ new Date()).toISOString(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, + session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() } + } + } + }; + } + if ((path3 === "sign-in/email" || path3 === "login") && m === "POST") { + const id = `mock_${randomUUID()}`; + return { + handled: true, + response: { + status: 200, + body: { + user: { id, name: "Mock User", email: body?.email || "mock@test.local", emailVerified: true, createdAt: (/* @__PURE__ */ new Date()).toISOString(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, + session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() } + } + } + }; + } + if (path3 === "get-session" && m === "GET") { + return { + handled: true, + response: { status: 200, body: { session: null, user: null } } + }; + } + if (path3 === "sign-out" && m === "POST") { + return { + handled: true, + response: { status: 200, body: { success: true } } + }; + } + return { handled: false }; + } + /** + * Handles Metadata requests + * Standard: /metadata/:type/:name + * Fallback for backward compat: /metadata (all objects), /metadata/:objectName (get object) + */ + async handleMetadata(path3, context, method, body, query) { + const broker = this.kernel.broker ?? null; + const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); + if (parts[0] === "types") { + console.log("[HttpDispatcher] Attempting to resolve MetadataService..."); + console.log("[HttpDispatcher] Available kernel methods:", { + hasGetServiceAsync: typeof this.kernel.getServiceAsync === "function", + hasGetService: typeof this.kernel.getService === "function", + hasContext: !!this.kernel.context, + hasContextGetService: typeof this.kernel.context?.getService === "function" + }); + let metadataService = null; + if (typeof this.kernel.getServiceAsync === "function") { + try { + metadataService = await this.kernel.getServiceAsync("metadata"); + console.log('[HttpDispatcher] kernel.getServiceAsync("metadata") returned:', !!metadataService); + } catch (e) { + console.log('[HttpDispatcher] kernel.getServiceAsync("metadata") failed:', e.message); + } + } + if (!metadataService && typeof this.kernel.getService === "function") { + try { + metadataService = await this.kernel.getService("metadata"); + console.log('[HttpDispatcher] kernel.getService("metadata") returned:', !!metadataService); + } catch (e) { + console.log('[HttpDispatcher] kernel.getService("metadata") failed:', e.message); + } + } + if (!metadataService && this.kernel.context?.getService) { + try { + metadataService = await this.kernel.context.getService("metadata"); + console.log('[HttpDispatcher] kernel.context.getService("metadata") returned:', !!metadataService); + } catch (e) { + console.log('[HttpDispatcher] kernel.context.getService("metadata") failed:', e.message); + } + } + console.log("[HttpDispatcher] Final metadataService:", !!metadataService, "has getRegisteredTypes:", typeof metadataService?.getRegisteredTypes); + if (metadataService && typeof metadataService.getRegisteredTypes === "function") { + try { + const types = await metadataService.getRegisteredTypes(); + console.log("[HttpDispatcher] MetadataService.getRegisteredTypes() returned:", types); + return { handled: true, response: this.success({ types }) }; + } catch (e) { + console.warn("[HttpDispatcher] MetadataService.getRegisteredTypes() failed:", e.message, e.stack); + } + } else { + console.log("[HttpDispatcher] MetadataService not available or missing getRegisteredTypes, falling back to protocol service"); + } + const protocol = await this.resolveService("protocol"); + if (protocol && typeof protocol.getMetaTypes === "function") { + const result = await protocol.getMetaTypes({}); + console.log("[HttpDispatcher] Protocol service returned types:", result); + return { handled: true, response: this.success(result) }; + } + if (broker) { + try { + const data = await broker.call("metadata.types", {}, { request: context.request }); + console.log("[HttpDispatcher] Broker returned types:", data); + return { handled: true, response: this.success(data) }; + } catch (e) { + console.log("[HttpDispatcher] Broker call failed:", e); + } + } + console.warn("[HttpDispatcher] Falling back to hardcoded defaults for metadata types"); + return { handled: true, response: this.success({ types: ["object", "app", "plugin"] }) }; + } + if (parts.length === 3 && parts[2] === "published" && (!method || method === "GET")) { + const [type, name] = parts; + const metadataService = await this.getService(CoreServiceName.enum.metadata); + if (metadataService && typeof metadataService.getPublished === "function") { + const data = await metadataService.getPublished(type, name); + if (data === void 0) return { handled: true, response: this.error("Not found", 404) }; + return { handled: true, response: this.success(data) }; + } + if (broker) { + try { + const data = await broker.call("metadata.getPublished", { type, name }, { request: context.request }); + return { handled: true, response: this.success(data) }; + } catch (e) { + return { handled: true, response: this.error(e.message, 404) }; + } + } + return { handled: true, response: this.error("Not found", 404) }; + } + if (parts.length === 2) { + const [type, name] = parts; + const packageId = query?.package || void 0; + if (method === "PUT" && body) { + const protocol = await this.resolveService("protocol"); + if (protocol && typeof protocol.saveMetaItem === "function") { + try { + const result = await protocol.saveMetaItem({ type, name, item: body }); + return { handled: true, response: this.success(result) }; + } catch (e) { + return { handled: true, response: this.error(e.message, 400) }; + } + } + if (broker) { + try { + const data = await broker.call("metadata.saveItem", { type, name, item: body }, { request: context.request }); + return { handled: true, response: this.success(data) }; + } catch (e) { + return { handled: true, response: this.error(e.message || "Save not supported", 501) }; + } + } + return { handled: true, response: this.error("Save not supported", 501) }; + } + try { + if (type === "objects" || type === "object") { + if (broker) { + const data = await broker.call("metadata.getObject", { objectName: name }, { request: context.request }); + return { handled: true, response: this.success(data) }; + } + const qlService = await this.getObjectQLService(); + if (qlService?.registry) { + const data = qlService.registry.getObject(name); + if (data) return { handled: true, response: this.success(data) }; + } + return { handled: true, response: this.error("Not found", 404) }; + } + const singularType = pluralToSingular(type); + const protocol = await this.resolveService("protocol"); + if (protocol && typeof protocol.getMetaItem === "function") { + try { + const data = await protocol.getMetaItem({ type: singularType, name, packageId }); + return { handled: true, response: this.success(data) }; + } catch (e) { + } + } + if (broker) { + const method2 = `metadata.get${this.capitalize(singularType)}`; + const data = await broker.call(method2, { name }, { request: context.request }); + return { handled: true, response: this.success(data) }; + } + return { handled: true, response: this.error("Not found", 404) }; + } catch (e) { + return { handled: true, response: this.error(e.message, 404) }; + } + } + if (parts.length === 1) { + const typeOrName = parts[0]; + const packageId = query?.package || void 0; + const protocol = await this.resolveService("protocol"); + if (protocol && typeof protocol.getMetaItems === "function") { + try { + const data = await protocol.getMetaItems({ type: typeOrName, packageId }); + if (data && (data.items !== void 0 || Array.isArray(data))) { + return { handled: true, response: this.success(data) }; + } + } catch { + } + } + const metadataService = await this.getService(CoreServiceName.enum.metadata); + if (metadataService && typeof metadataService.list === "function") { + try { + const items = await metadataService.list(typeOrName); + if (items && items.length > 0) { + return { handled: true, response: this.success({ type: typeOrName, items }) }; + } + } catch (e) { + const sanitizedType = String(typeOrName).replace(/[\r\n\t]/g, ""); + console.debug(`[HttpDispatcher] MetadataService.list() failed for type:`, sanitizedType, "error:", e.message); + } + } + if (broker) { + try { + if (typeOrName === "objects") { + const data2 = await broker.call("metadata.objects", { packageId }, { request: context.request }); + return { handled: true, response: this.success(data2) }; + } + const data = await broker.call(`metadata.${typeOrName}`, { packageId }, { request: context.request }); + if (data !== null && data !== void 0) { + return { handled: true, response: this.success(data) }; + } + } catch { + } + try { + const data = await broker.call("metadata.getObject", { objectName: typeOrName }, { request: context.request }); + return { handled: true, response: this.success(data) }; + } catch (e) { + return { handled: true, response: this.error(e.message, 404) }; + } + } + const qlService = await this.getObjectQLService(); + if (qlService?.registry) { + if (typeOrName === "objects") { + const objs = qlService.registry.getAllObjects(packageId); + return { handled: true, response: this.success({ type: "object", items: objs }) }; + } + const items = qlService.registry.listItems?.(typeOrName, packageId); + if (items && items.length > 0) { + return { handled: true, response: this.success({ type: typeOrName, items }) }; + } + const obj = qlService.registry.getObject(typeOrName); + if (obj) return { handled: true, response: this.success(obj) }; + } + return { handled: true, response: this.error("Not found", 404) }; + } + if (parts.length === 0) { + const protocol = await this.resolveService("protocol"); + if (protocol && typeof protocol.getMetaTypes === "function") { + const result = await protocol.getMetaTypes({}); + return { handled: true, response: this.success(result) }; + } + if (broker) { + try { + const data = await broker.call("metadata.types", {}, { request: context.request }); + return { handled: true, response: this.success(data) }; + } catch { + } + } + return { handled: true, response: this.success({ types: ["object", "app", "plugin"] }) }; + } + return { handled: false }; + } + /** + * Handles Data requests + * path: sub-path after /data/ (e.g. "contacts", "contacts/123", "contacts/query") + */ + async handleData(path3, method, body, query, context) { + const broker = this.ensureBroker(); + const parts = path3.replace(/^\/+/, "").split("/"); + const objectName = parts[0]; + if (!objectName) { + return { handled: true, response: this.error("Object name required", 400) }; + } + const m = method.toUpperCase(); + if (parts.length > 1) { + const action = parts[1]; + if (action === "query" && m === "POST") { + const result = await broker.call("data.query", { object: objectName, ...body }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (action === "batch" && m === "POST") { + const result = await broker.call("data.batch", { object: objectName, ...body }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (parts.length === 2 && m === "GET") { + const id = parts[1]; + const { select, expand: expand2 } = query || {}; + const allowedParams = {}; + if (select != null) allowedParams.select = select; + if (expand2 != null) allowedParams.expand = expand2; + const result = await broker.call("data.get", { object: objectName, id, ...allowedParams }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (parts.length === 2 && m === "PATCH") { + const id = parts[1]; + const result = await broker.call("data.update", { object: objectName, id, data: body }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (parts.length === 2 && m === "DELETE") { + const id = parts[1]; + const result = await broker.call("data.delete", { object: objectName, id }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + } else { + if (m === "GET") { + const normalized = { ...query }; + if (normalized.filter != null || normalized.filters != null) { + normalized.where = normalized.where ?? normalized.filter ?? normalized.filters; + delete normalized.filter; + delete normalized.filters; + } + if (normalized.select != null && normalized.fields == null) { + normalized.fields = normalized.select; + delete normalized.select; + } + if (normalized.sort != null && normalized.orderBy == null) { + normalized.orderBy = normalized.sort; + delete normalized.sort; + } + if (normalized.top != null && normalized.limit == null) { + normalized.limit = normalized.top; + delete normalized.top; + } + if (normalized.skip != null && normalized.offset == null) { + normalized.offset = normalized.skip; + delete normalized.skip; + } + const result = await broker.call("data.query", { object: objectName, query: normalized }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (m === "POST") { + const result = await broker.call("data.create", { object: objectName, data: body }, { request: context.request }); + const res = this.success(result); + res.status = 201; + return { handled: true, response: res }; + } + } + return { handled: false }; + } + /** + * Handles Analytics requests + * path: sub-path after /analytics/ + */ + async handleAnalytics(path3, method, body, _context2) { + const analyticsService = await this.getService(CoreServiceName.enum.analytics); + if (!analyticsService) return { handled: false }; + const m = method.toUpperCase(); + const subPath = path3.replace(/^\/+/, ""); + if (subPath === "query" && m === "POST") { + const result = await analyticsService.query(body); + return { handled: true, response: this.success(result) }; + } + if (subPath === "meta" && m === "GET") { + const result = await analyticsService.getMeta(); + return { handled: true, response: this.success(result) }; + } + if (subPath === "sql" && m === "POST") { + const result = await analyticsService.generateSql(body); + return { handled: true, response: this.success(result) }; + } + return { handled: false }; + } + /** + * Handles i18n requests + * path: sub-path after /i18n/ + * + * Routes: + * GET /locales → getLocales + * GET /translations/:locale → getTranslations (locale from path) + * GET /translations?locale=xx → getTranslations (locale from query) + * GET /labels/:object/:locale → getFieldLabels (both from path) + * GET /labels/:object?locale=xx → getFieldLabels (locale from query) + */ + async handleI18n(path3, method, query, _context2) { + const i18nService = await this.getService(CoreServiceName.enum.i18n); + if (!i18nService) return { handled: true, response: this.error("i18n service not available", 501) }; + const m = method.toUpperCase(); + const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); + if (m !== "GET") return { handled: false }; + if (parts[0] === "locales" && parts.length === 1) { + const locales = i18nService.getLocales(); + return { handled: true, response: this.success({ locales }) }; + } + if (parts[0] === "translations") { + const locale = parts[1] ? decodeURIComponent(parts[1]) : query?.locale; + if (!locale) return { handled: true, response: this.error("Missing locale parameter", 400) }; + let translations = i18nService.getTranslations(locale); + if (Object.keys(translations).length === 0) { + const availableLocales = typeof i18nService.getLocales === "function" ? i18nService.getLocales() : []; + const resolved = resolveLocale(locale, availableLocales); + if (resolved && resolved !== locale) { + translations = i18nService.getTranslations(resolved); + return { handled: true, response: this.success({ locale: resolved, requestedLocale: locale, translations }) }; + } + } + return { handled: true, response: this.success({ locale, translations }) }; + } + if (parts[0] === "labels" && parts.length >= 2) { + const objectName = decodeURIComponent(parts[1]); + let locale = parts[2] ? decodeURIComponent(parts[2]) : query?.locale; + if (!locale) return { handled: true, response: this.error("Missing locale parameter", 400) }; + const availableLocales = typeof i18nService.getLocales === "function" ? i18nService.getLocales() : []; + const resolved = resolveLocale(locale, availableLocales); + if (resolved) locale = resolved; + if (typeof i18nService.getFieldLabels === "function") { + const labels2 = i18nService.getFieldLabels(objectName, locale); + return { handled: true, response: this.success({ object: objectName, locale, labels: labels2 }) }; + } + const translations = i18nService.getTranslations(locale); + const prefix = `o.${objectName}.fields.`; + const labels = {}; + for (const [key, value] of Object.entries(translations)) { + if (key.startsWith(prefix)) { + labels[key.substring(prefix.length)] = value; + } + } + return { handled: true, response: this.success({ object: objectName, locale, labels }) }; + } + return { handled: false }; + } + /** + * Handles Package Management requests + * + * REST Endpoints: + * - GET /packages → list all installed packages + * - GET /packages/:id → get a specific package + * - POST /packages → install a new package + * - DELETE /packages/:id → uninstall a package + * - PATCH /packages/:id/enable → enable a package + * - PATCH /packages/:id/disable → disable a package + * - POST /packages/:id/publish → publish a package (metadata snapshot) + * - POST /packages/:id/revert → revert a package to last published state + * + * Uses ObjectQL SchemaRegistry directly (via the 'objectql' service) + * with broker fallback for backward compatibility. + */ + async handlePackages(path3, method, body, query, context) { + const m = method.toUpperCase(); + const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); + const qlService = await this.getObjectQLService(); + const registry2 = qlService?.registry; + if (!registry2) { + if (this.kernel.broker) { + return this.handlePackagesViaBroker(parts, m, body, query, context); + } + return { handled: true, response: this.error("Package service not available", 503) }; + } + try { + if (parts.length === 0 && m === "GET") { + let packages = registry2.getAllPackages(); + if (query?.status) { + packages = packages.filter((p) => p.status === query.status); + } + if (query?.type) { + packages = packages.filter((p) => p.manifest?.type === query.type); + } + return { handled: true, response: this.success({ packages, total: packages.length }) }; + } + if (parts.length === 0 && m === "POST") { + const pkg = registry2.installPackage(body.manifest || body, body.settings); + const res = this.success(pkg); + res.status = 201; + return { handled: true, response: res }; + } + if (parts.length === 2 && parts[1] === "enable" && m === "PATCH") { + const id = decodeURIComponent(parts[0]); + const pkg = registry2.enablePackage(id); + if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) }; + return { handled: true, response: this.success(pkg) }; + } + if (parts.length === 2 && parts[1] === "disable" && m === "PATCH") { + const id = decodeURIComponent(parts[0]); + const pkg = registry2.disablePackage(id); + if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) }; + return { handled: true, response: this.success(pkg) }; + } + if (parts.length === 2 && parts[1] === "publish" && m === "POST") { + const id = decodeURIComponent(parts[0]); + const metadataService = await this.getService(CoreServiceName.enum.metadata); + if (metadataService && typeof metadataService.publishPackage === "function") { + const result = await metadataService.publishPackage(id, body || {}); + return { handled: true, response: this.success(result) }; + } + if (this.kernel.broker) { + const result = await this.kernel.broker.call("metadata.publishPackage", { packageId: id, ...body }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + return { handled: true, response: this.error("Metadata service not available", 503) }; + } + if (parts.length === 2 && parts[1] === "revert" && m === "POST") { + const id = decodeURIComponent(parts[0]); + const metadataService = await this.getService(CoreServiceName.enum.metadata); + if (metadataService && typeof metadataService.revertPackage === "function") { + await metadataService.revertPackage(id); + return { handled: true, response: this.success({ success: true }) }; + } + if (this.kernel.broker) { + await this.kernel.broker.call("metadata.revertPackage", { packageId: id }, { request: context.request }); + return { handled: true, response: this.success({ success: true }) }; + } + return { handled: true, response: this.error("Metadata service not available", 503) }; + } + if (parts.length === 1 && m === "GET") { + const id = decodeURIComponent(parts[0]); + const pkg = registry2.getPackage(id); + if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) }; + return { handled: true, response: this.success(pkg) }; + } + if (parts.length === 1 && m === "DELETE") { + const id = decodeURIComponent(parts[0]); + const success2 = registry2.uninstallPackage(id); + if (!success2) return { handled: true, response: this.error(`Package '${id}' not found`, 404) }; + return { handled: true, response: this.success({ success: true }) }; + } + } catch (e) { + return { handled: true, response: this.error(e.message, e.statusCode || 500) }; + } + return { handled: false }; + } + /** + * Fallback: handle packages via broker (for backward compatibility) + */ + async handlePackagesViaBroker(parts, m, body, query, context) { + const broker = this.kernel.broker; + try { + if (parts.length === 0 && m === "GET") { + const result = await broker.call("package.list", query || {}, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (parts.length === 0 && m === "POST") { + const result = await broker.call("package.install", body, { request: context.request }); + const res = this.success(result); + res.status = 201; + return { handled: true, response: res }; + } + if (parts.length === 2 && parts[1] === "enable" && m === "PATCH") { + const id = decodeURIComponent(parts[0]); + const result = await broker.call("package.enable", { id }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (parts.length === 2 && parts[1] === "disable" && m === "PATCH") { + const id = decodeURIComponent(parts[0]); + const result = await broker.call("package.disable", { id }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (parts.length === 1 && m === "GET") { + const id = decodeURIComponent(parts[0]); + const result = await broker.call("package.get", { id }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (parts.length === 1 && m === "DELETE") { + const id = decodeURIComponent(parts[0]); + const result = await broker.call("package.uninstall", { id }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + } catch (e) { + return { handled: true, response: this.error(e.message, e.statusCode || 500) }; + } + return { handled: false }; + } + /** + * Handles Storage requests + * path: sub-path after /storage/ + */ + async handleStorage(path3, method, file2, context) { + const storageService = await this.getService(CoreServiceName.enum["file-storage"]) || this.kernel.services?.["file-storage"]; + if (!storageService) { + return { handled: true, response: this.error("File storage not configured", 501) }; + } + const m = method.toUpperCase(); + const parts = path3.replace(/^\/+/, "").split("/"); + if (parts[0] === "upload" && m === "POST") { + if (!file2) { + return { handled: true, response: this.error("No file provided", 400) }; + } + const result = await storageService.upload(file2, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (parts[0] === "file" && parts[1] && m === "GET") { + const id = parts[1]; + const result = await storageService.download(id, { request: context.request }); + if (result.url && result.redirect) { + return { handled: true, result: { type: "redirect", url: result.url } }; + } + if (result.stream) { + return { + handled: true, + result: { + type: "stream", + stream: result.stream, + headers: { + "Content-Type": result.mimeType || "application/octet-stream", + "Content-Length": result.size + } + } + }; + } + return { handled: true, response: this.success(result) }; + } + return { handled: false }; + } + /** + * Handles UI requests + * path: sub-path after /ui/ + */ + async handleUi(path3, query, _context2) { + const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); + if (parts[0] === "view" && parts[1]) { + const objectName = parts[1]; + const type = parts[2] || query?.type || "list"; + const protocol = await this.resolveService("protocol"); + if (protocol && typeof protocol.getUiView === "function") { + try { + const result = await protocol.getUiView({ object: objectName, type }); + return { handled: true, response: this.success(result) }; + } catch (e) { + return { handled: true, response: this.error(e.message, 500) }; + } + } else { + return { handled: true, response: this.error("Protocol service not available", 503) }; + } + } + return { handled: false }; + } + /** + * Handles Automation requests + * path: sub-path after /automation/ + * + * Routes: + * GET / → listFlows + * GET /:name → getFlow + * POST / → createFlow (registerFlow) + * PUT /:name → updateFlow + * DELETE /:name → deleteFlow (unregisterFlow) + * POST /:name/trigger → execute (legacy: trigger/:name also supported) + * POST /:name/toggle → toggleFlow + * GET /:name/runs → listRuns + * GET /:name/runs/:runId → getRun + */ + async handleAutomation(path3, method, body, context, query) { + const automationService = await this.getService(CoreServiceName.enum.automation); + if (!automationService) return { handled: false }; + const m = method.toUpperCase(); + const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); + if (parts[0] === "trigger" && parts[1] && m === "POST") { + const triggerName = parts[1]; + if (typeof automationService.trigger === "function") { + const result = await automationService.trigger(triggerName, body, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (typeof automationService.execute === "function") { + const result = await automationService.execute(triggerName, body); + return { handled: true, response: this.success(result) }; + } + } + if (parts.length === 0 && m === "GET") { + if (typeof automationService.listFlows === "function") { + const names = await automationService.listFlows(); + return { handled: true, response: this.success({ flows: names, total: names.length, hasMore: false }) }; + } + } + if (parts.length === 0 && m === "POST") { + if (typeof automationService.registerFlow === "function") { + automationService.registerFlow(body?.name, body); + return { handled: true, response: this.success(body) }; + } + } + if (parts.length >= 1) { + const name = parts[0]; + if (parts[1] === "trigger" && m === "POST") { + if (typeof automationService.execute === "function") { + const result = await automationService.execute(name, body); + return { handled: true, response: this.success(result) }; + } + } + if (parts[1] === "toggle" && m === "POST") { + if (typeof automationService.toggleFlow === "function") { + await automationService.toggleFlow(name, body?.enabled ?? true); + return { handled: true, response: this.success({ name, enabled: body?.enabled ?? true }) }; + } + } + if (parts[1] === "runs" && parts[2] && m === "GET") { + if (typeof automationService.getRun === "function") { + const run = await automationService.getRun(parts[2]); + if (!run) return { handled: true, response: this.error("Execution not found", 404) }; + return { handled: true, response: this.success(run) }; + } + } + if (parts[1] === "runs" && !parts[2] && m === "GET") { + if (typeof automationService.listRuns === "function") { + const options = query ? { limit: query.limit ? Number(query.limit) : void 0, cursor: query.cursor } : void 0; + const runs = await automationService.listRuns(name, options); + return { handled: true, response: this.success({ runs, hasMore: false }) }; + } + } + if (parts.length === 1 && m === "GET") { + if (typeof automationService.getFlow === "function") { + const flow = await automationService.getFlow(name); + if (!flow) return { handled: true, response: this.error("Flow not found", 404) }; + return { handled: true, response: this.success(flow) }; + } + } + if (parts.length === 1 && m === "PUT") { + if (typeof automationService.registerFlow === "function") { + automationService.registerFlow(name, body?.definition ?? body); + return { handled: true, response: this.success(body?.definition ?? body) }; + } + } + if (parts.length === 1 && m === "DELETE") { + if (typeof automationService.unregisterFlow === "function") { + automationService.unregisterFlow(name); + return { handled: true, response: this.success({ name, deleted: true }) }; + } + } + } + return { handled: false }; + } + getServicesMap() { + if (this.kernel.services instanceof Map) { + return Object.fromEntries(this.kernel.services); + } + return this.kernel.services || {}; + } + async getService(name) { + return this.resolveService(name); + } + /** + * Resolve any service by name, supporting async factories. + * Fallback chain: getServiceAsync → getService (sync) → context.getService → services map. + * Only returns when a non-null service is found; otherwise falls through to the next step. + */ + async resolveService(name) { + if (typeof this.kernel.getServiceAsync === "function") { + try { + const svc = await this.kernel.getServiceAsync(name); + if (svc != null) return svc; + } catch { + } + } + if (typeof this.kernel.getService === "function") { + try { + const svc = await this.kernel.getService(name); + if (svc != null) return svc; + } catch { + } + } + if (this.kernel?.context?.getService) { + try { + const svc = await this.kernel.context.getService(name); + if (svc != null) return svc; + } catch { + } + } + const services = this.getServicesMap(); + return services[name]; + } + /** + * Get the ObjectQL service which provides access to SchemaRegistry. + * Tries multiple access patterns since kernel structure varies. + */ + async getObjectQLService() { + try { + const svc = await this.resolveService("objectql"); + if (svc?.registry) return svc; + } catch { + } + return null; + } + capitalize(s) { + return s.charAt(0).toUpperCase() + s.slice(1); + } + /** + * Handle AI service routes (/ai/chat, /ai/models, /ai/conversations, etc.) + * Resolves the AI service and its built-in route handlers, then dispatches. + */ + async handleAI(subPath, method, body, query, _context2) { + let aiService; + try { + aiService = await this.resolveService("ai"); + } catch { + } + if (!aiService) { + return { + handled: true, + response: { + status: 404, + body: { success: false, error: { message: "AI service is not configured", code: 404 } } + } + }; + } + const fullPath = `/api/v1${subPath}`; + const matchRoute = (pattern, path3) => { + const patternParts = pattern.split("/"); + const pathParts = path3.split("/"); + if (patternParts.length !== pathParts.length) return null; + const params = {}; + for (let i = 0; i < patternParts.length; i++) { + if (patternParts[i].startsWith(":")) { + params[patternParts[i].substring(1)] = pathParts[i]; + } else if (patternParts[i] !== pathParts[i]) { + return null; + } + } + return params; + }; + const routes = this.kernel.__aiRoutes; + if (!routes) { + return { + handled: true, + response: { + status: 503, + body: { success: false, error: { message: "AI service routes not yet initialized", code: 503 } } + } + }; + } + for (const route of routes) { + if (route.method !== method) continue; + const params = matchRoute(route.path, fullPath); + if (params === null) continue; + const result = await route.handler({ body, params, query }); + if (result.stream && result.events) { + return { + handled: true, + result: { + type: "stream", + contentType: result.vercelDataStream ? "text/plain; charset=utf-8" : "text/event-stream", + events: result.events, + vercelDataStream: result.vercelDataStream, + headers: { + "Content-Type": result.vercelDataStream ? "text/plain; charset=utf-8" : "text/event-stream", + "Cache-Control": "no-cache", + "Connection": "keep-alive" + } + } + }; + } + return { + handled: true, + response: { + status: result.status, + body: result.body + } + }; + } + return { + handled: true, + response: this.routeNotFound(subPath) + }; + } + /** + * Main Dispatcher Entry Point + * Routes the request to the appropriate handler based on path and precedence + */ + async dispatch(method, path3, body, query, context, prefix) { + const cleanPath = path3.replace(/\/$/, ""); + if ((cleanPath === "/discovery" || cleanPath === "") && method === "GET") { + const info2 = await this.getDiscoveryInfo(prefix ?? ""); + return { + handled: true, + response: this.success(info2) + }; + } + if (cleanPath === "/health" && method === "GET") { + return { + handled: true, + response: this.success({ + status: "ok", + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + version: "1.0.0", + uptime: typeof process !== "undefined" ? process.uptime() : void 0 + }) + }; + } + if (cleanPath.startsWith("/auth")) { + return this.handleAuth(cleanPath.substring(5), method, body, context); + } + if (cleanPath.startsWith("/meta")) { + return this.handleMetadata(cleanPath.substring(5), context, method, body, query); + } + if (cleanPath.startsWith("/data")) { + return this.handleData(cleanPath.substring(5), method, body, query, context); + } + if (cleanPath.startsWith("/graphql")) { + if (method === "POST") return this.handleGraphQL(body, context); + } + if (cleanPath.startsWith("/storage")) { + return this.handleStorage(cleanPath.substring(8), method, body, context); + } + if (cleanPath.startsWith("/ui")) { + return this.handleUi(cleanPath.substring(3), query, context); + } + if (cleanPath.startsWith("/automation")) { + return this.handleAutomation(cleanPath.substring(11), method, body, context, query); + } + if (cleanPath.startsWith("/analytics")) { + return this.handleAnalytics(cleanPath.substring(10), method, body, context); + } + if (cleanPath.startsWith("/packages")) { + return this.handlePackages(cleanPath.substring(9), method, body, query, context); + } + if (cleanPath.startsWith("/i18n")) { + return this.handleI18n(cleanPath.substring(5), method, query, context); + } + if (cleanPath.startsWith("/ai")) { + return this.handleAI(cleanPath, method, body, query, context); + } + if (cleanPath === "/openapi.json" && method === "GET") { + const broker = this.ensureBroker(); + try { + const result2 = await broker.call("metadata.generateOpenApi", {}, { request: context.request }); + return { handled: true, response: this.success(result2) }; + } catch (e) { + } + } + const result = await this.handleApiEndpoint(cleanPath, method, body, query, context); + if (result.handled) return result; + return { + handled: true, + response: this.routeNotFound(cleanPath) + }; + } + /** + * Handles Custom API Endpoints defined in metadata + */ + async handleApiEndpoint(path3, method, body, query, context) { + const broker = this.ensureBroker(); + try { + const endpoint = await broker.call("metadata.matchEndpoint", { path: path3, method }); + if (endpoint) { + if (endpoint.type === "flow") { + const result = await broker.call("automation.runFlow", { + flowId: endpoint.target, + inputs: { ...query, ...body, _request: context.request } + }); + return { handled: true, response: this.success(result) }; + } + if (endpoint.type === "script") { + const result = await broker.call("automation.runScript", { + scriptName: endpoint.target, + context: { ...query, ...body, request: context.request } + }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (endpoint.type === "object_operation") { + if (endpoint.objectParams) { + const { object: object2, operation } = endpoint.objectParams; + if (operation === "find") { + const result = await broker.call("data.query", { object: object2, query }, { request: context.request }); + return { handled: true, response: this.success(result.records, { total: result.total }) }; + } + if (operation === "get" && query.id) { + const result = await broker.call("data.get", { object: object2, id: query.id }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + if (operation === "create") { + const result = await broker.call("data.create", { object: object2, data: body }, { request: context.request }); + return { handled: true, response: this.success(result) }; + } + } + } + if (endpoint.type === "proxy") { + return { + handled: true, + response: { + status: 200, + body: { proxy: true, target: endpoint.target, note: "Proxy execution requires http-client service" } + } + }; + } + } + } catch (e) { + } + return { handled: false }; + } +}; + +// ../../packages/objectql/dist/index.mjs +init_data(); + +// ../../packages/spec/dist/kernel/index.mjs +init_zod(); +var CLICommandContributionSchema = external_exports.object({ + /** + * CLI command name. Must be a valid identifier: lowercase alphanumeric with hyphens. + * This becomes a top-level subcommand of the `os` CLI. + * + * @example "marketplace" + * @example "deploy" + * @example "cloud-sync" + */ + name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), + /** Brief description shown in `os --help` output. */ + description: external_exports.string().optional().describe("Command description for help text"), + /** + * Module path that exports the oclif Command class(es). + * Relative to the plugin package root. With oclif, this is typically + * auto-discovered from the `commands` directory, but can be specified + * for documentation or manifest purposes. + * + * @example "./dist/commands/marketplace.js" + * @example "./dist/commands" + */ + module: external_exports.string().optional().describe("Module path exporting oclif Command classes") +}); +var OclifPluginConfigSchema = external_exports.object({ + /** Command discovery configuration */ + commands: external_exports.object({ + /** Discovery strategy — typically "pattern" for file-based discovery */ + strategy: external_exports.enum(["pattern", "explicit", "single"]).optional().describe("Command discovery strategy"), + /** Directory path containing compiled command files */ + target: external_exports.string().optional().describe("Target directory for command files"), + /** Glob pattern for matching command files */ + glob: external_exports.string().optional().describe("Glob pattern for command file matching") + }).optional().describe("Command discovery configuration"), + /** Topic separator character (default: space) */ + topicSeparator: external_exports.string().optional().describe("Character separating topic and command names") +}).describe("oclif plugin configuration section"); +var MetadataCategoryEnum2 = external_exports.enum([ + "objects", + "views", + "pages", + "flows", + "dashboards", + "permissions", + "agents", + "reports", + "actions", + "translations", + "themes", + "datasets", + "apis", + "triggers", + "workflows" +]).describe("Metadata category within the artifact"); +var ArtifactFileEntrySchema2 = external_exports.object({ + /** Relative path within the artifact (e.g. "metadata/objects/account.object.json") */ + path: external_exports.string().describe("Relative file path within the artifact"), + /** File size in bytes */ + size: external_exports.number().int().nonnegative().describe("File size in bytes"), + /** Metadata category (if under metadata/) */ + category: MetadataCategoryEnum2.optional().describe("Metadata category this file belongs to") +}).describe("A single file entry within the artifact"); +var ArtifactChecksumSchema2 = external_exports.object({ + /** Hash algorithm used (default: SHA256) */ + algorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm used for checksums"), + /** Map of relative file paths to their hash values */ + files: external_exports.record(external_exports.string(), external_exports.string().regex(/^[a-f0-9]+$/)).describe("File path to hash value mapping") +}).describe("Checksum manifest for artifact integrity verification"); +var ArtifactSignatureSchema2 = external_exports.object({ + /** Signature algorithm */ + algorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).default("RSA-SHA256").describe("Signing algorithm used"), + /** Public key reference (URL or fingerprint) for verification */ + publicKeyRef: external_exports.string().describe("Public key reference (URL or fingerprint) for signature verification"), + /** Base64-encoded signature value */ + signature: external_exports.string().describe("Base64-encoded digital signature"), + /** Timestamp of when the artifact was signed */ + signedAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp of when the artifact was signed"), + /** Signer identity (publisher ID or email) */ + signedBy: external_exports.string().optional().describe("Identity of the signer (publisher ID or email)") +}).describe("Digital signature for artifact authenticity verification"); +var PackageArtifactSchema2 = external_exports.object({ + /** Artifact format version (for forward compatibility) */ + formatVersion: external_exports.string().regex(/^\d+\.\d+$/).default("1.0").describe('Artifact format version (e.g. "1.0")'), + /** Package ID from the manifest */ + packageId: external_exports.string().describe("Package identifier from manifest"), + /** Package version from the manifest */ + version: external_exports.string().describe("Package version from manifest"), + /** Artifact format */ + format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format of the artifact"), + /** Total artifact size in bytes */ + size: external_exports.number().int().positive().optional().describe("Total artifact file size in bytes"), + /** Build timestamp */ + builtAt: external_exports.string().datetime().describe("ISO 8601 timestamp of when the artifact was built"), + /** Build tool and version that produced this artifact */ + builtWith: external_exports.string().optional().describe('Build tool identifier (e.g. "os-cli@3.2.0")'), + /** File listing within the artifact */ + files: external_exports.array(ArtifactFileEntrySchema2).optional().describe("List of files contained in the artifact"), + /** Metadata categories present in the artifact */ + metadataCategories: external_exports.array(MetadataCategoryEnum2).optional().describe("Metadata categories included in this artifact"), + /** Integrity checksums for all files */ + checksums: ArtifactChecksumSchema2.optional().describe("SHA256 checksums for artifact integrity verification"), + /** Digital signature for authenticity */ + signature: ArtifactSignatureSchema2.optional().describe("Digital signature for artifact authenticity verification") +}).describe("Package artifact structure and metadata"); +var PluginBuildOptionsSchema = external_exports.object({ + /** Project root directory (defaults to cwd) */ + directory: external_exports.string().optional().describe("Project root directory (defaults to current working directory)"), + /** Output directory for the built artifact */ + outDir: external_exports.string().optional().describe("Output directory for the built artifact (defaults to ./dist)"), + /** Archive format */ + format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format for the artifact"), + /** Whether to sign the artifact */ + sign: external_exports.boolean().default(false).describe("Whether to digitally sign the artifact"), + /** Path to the private key for signing */ + privateKeyPath: external_exports.string().optional().describe("Path to RSA/ECDSA private key file for signing"), + /** Signing algorithm */ + signAlgorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).optional().describe("Signing algorithm to use"), + /** Checksum algorithm */ + checksumAlgorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm for file checksums"), + /** Whether to include seed data */ + includeData: external_exports.boolean().default(true).describe("Whether to include seed data in the artifact"), + /** Whether to include locale/translation files */ + includeLocales: external_exports.boolean().default(true).describe("Whether to include locale/translation files") +}).describe("Options for the os plugin build command"); +var PluginBuildResultSchema = external_exports.object({ + /** Whether the build succeeded */ + success: external_exports.boolean().describe("Whether the build succeeded"), + /** Path to the generated artifact file */ + artifactPath: external_exports.string().optional().describe("Absolute path to the generated artifact file"), + /** Artifact metadata (validated against PackageArtifactSchema) */ + artifact: PackageArtifactSchema2.optional().describe("Artifact metadata"), + /** Total file count in the artifact */ + fileCount: external_exports.number().int().min(0).optional().describe("Total number of files in the artifact"), + /** Total artifact size in bytes */ + size: external_exports.number().int().min(0).optional().describe("Total artifact size in bytes"), + /** Build duration in milliseconds */ + durationMs: external_exports.number().optional().describe("Build duration in milliseconds"), + /** Error message if build failed */ + errorMessage: external_exports.string().optional().describe("Error message if build failed"), + /** Warnings emitted during build */ + warnings: external_exports.array(external_exports.string()).optional().describe("Warnings emitted during build") +}).describe("Result of the os plugin build command"); +var ValidationSeverityEnum = external_exports.enum([ + "error", + // Must fix — artifact is invalid + "warning", + // Should fix — may cause issues + "info" + // Informational — suggestion +]).describe("Validation issue severity"); +var ValidationFindingSchema = external_exports.object({ + /** Finding severity */ + severity: ValidationSeverityEnum.describe("Issue severity level"), + /** Rule or check that produced this finding */ + rule: external_exports.string().describe("Validation rule identifier"), + /** Human-readable message */ + message: external_exports.string().describe("Human-readable finding description"), + /** File path within the artifact (if applicable) */ + path: external_exports.string().optional().describe("Relative file path within the artifact") +}).describe("A single validation finding"); +var PluginValidateOptionsSchema = external_exports.object({ + /** Path to the .tgz artifact file to validate */ + artifactPath: external_exports.string().describe("Path to the artifact file to validate"), + /** Whether to verify the digital signature */ + verifySignature: external_exports.boolean().default(true).describe("Whether to verify the digital signature"), + /** Path to the public key for signature verification */ + publicKeyPath: external_exports.string().optional().describe("Path to the public key for signature verification"), + /** Whether to verify SHA256 checksums of all files */ + verifyChecksums: external_exports.boolean().default(true).describe("Whether to verify checksums of all files"), + /** Whether to validate metadata schema compliance */ + validateMetadata: external_exports.boolean().default(true).describe("Whether to validate metadata against schemas"), + /** Target platform version for compatibility check */ + platformVersion: external_exports.string().optional().describe("Platform version for compatibility verification") +}).describe("Options for the os plugin validate command"); +var PluginValidateResultSchema = external_exports.object({ + /** Whether the artifact is valid (no error-level findings) */ + valid: external_exports.boolean().describe("Whether the artifact passed validation"), + /** Artifact metadata extracted from the archive */ + artifact: PackageArtifactSchema2.optional().describe("Extracted artifact metadata"), + /** Checksum verification result */ + checksumVerification: external_exports.object({ + /** Whether all checksums match */ + passed: external_exports.boolean().describe("Whether all checksums match"), + /** Checksum details */ + checksums: ArtifactChecksumSchema2.optional().describe("Verified checksums"), + /** Files with mismatched checksums */ + mismatches: external_exports.array(external_exports.string()).optional().describe("Files with checksum mismatches") + }).optional().describe("Checksum verification result"), + /** Signature verification result */ + signatureVerification: external_exports.object({ + /** Whether the signature is valid */ + passed: external_exports.boolean().describe("Whether the signature is valid"), + /** Signature details */ + signature: ArtifactSignatureSchema2.optional().describe("Signature details"), + /** Reason for failure */ + failureReason: external_exports.string().optional().describe("Signature verification failure reason") + }).optional().describe("Signature verification result"), + /** Platform compatibility result */ + platformCompatibility: external_exports.object({ + /** Whether the artifact is compatible with the target platform */ + compatible: external_exports.boolean().describe("Whether artifact is compatible"), + /** Required platform version range */ + requiredRange: external_exports.string().optional().describe("Required platform version range"), + /** Target platform version checked against */ + targetVersion: external_exports.string().optional().describe("Target platform version") + }).optional().describe("Platform compatibility check result"), + /** All validation findings */ + findings: external_exports.array(ValidationFindingSchema).describe("All validation findings"), + /** Counts by severity */ + summary: external_exports.object({ + errors: external_exports.number().int().min(0).describe("Error count"), + warnings: external_exports.number().int().min(0).describe("Warning count"), + infos: external_exports.number().int().min(0).describe("Info count") + }).optional().describe("Finding counts by severity") +}).describe("Result of the os plugin validate command"); +var PluginPublishOptionsSchema = external_exports.object({ + /** Path to the .tgz artifact file to publish */ + artifactPath: external_exports.string().describe("Path to the artifact file to publish"), + /** Marketplace API base URL */ + registryUrl: external_exports.string().url().optional().describe("Marketplace API base URL"), + /** Authentication token for the marketplace API */ + token: external_exports.string().optional().describe("Authentication token for marketplace API"), + /** Release notes for this version */ + releaseNotes: external_exports.string().optional().describe("Release notes for this version"), + /** Whether this is a pre-release */ + preRelease: external_exports.boolean().default(false).describe("Whether this is a pre-release version"), + /** Whether to skip validation before publishing */ + skipValidation: external_exports.boolean().default(false).describe("Whether to skip local validation before publish"), + /** Access level for the published package */ + access: external_exports.enum(["public", "restricted"]).default("public").describe("Package access level on the marketplace"), + /** Tags for categorization */ + tags: external_exports.array(external_exports.string()).optional().describe("Tags for marketplace categorization") +}).describe("Options for the os plugin publish command"); +var PluginPublishResultSchema = external_exports.object({ + /** Whether the publish succeeded */ + success: external_exports.boolean().describe("Whether the publish succeeded"), + /** Package ID that was published */ + packageId: external_exports.string().optional().describe("Published package identifier"), + /** Version that was published */ + version: external_exports.string().optional().describe("Published version string"), + /** Artifact reference in the marketplace */ + artifactUrl: external_exports.string().url().optional().describe("URL of the published artifact in the marketplace"), + /** SHA256 checksum of the uploaded artifact */ + sha256: external_exports.string().optional().describe("SHA256 checksum of the uploaded artifact"), + /** Submission ID for tracking the review process */ + submissionId: external_exports.string().optional().describe("Marketplace submission ID for review tracking"), + /** Error message if publish failed */ + errorMessage: external_exports.string().optional().describe("Error message if publish failed"), + /** Human-readable status message */ + message: external_exports.string().optional().describe("Human-readable status message") +}).describe("Result of the os plugin publish command"); +var TenantIsolationLevel2 = external_exports.enum([ + "shared_schema", + // Shared DB, shared schema, row-level isolation (most economical) + "isolated_schema", + // Shared DB, separate schema per tenant (balanced) + "isolated_db" + // Separate database per tenant (maximum isolation) +]); +var DatabaseProviderSchema2 = external_exports.enum([ + "turso", + // Turso/libSQL (DB-per-Tenant, edge-native) + "postgres", + // PostgreSQL (traditional, self-hosted or managed) + "memory" + // In-memory (testing/development only) +]).describe("Database provider for tenant data"); +var TenantConnectionConfigSchema2 = external_exports.object({ + /** Database connection URL */ + url: external_exports.string().min(1).describe("Database connection URL"), + /** Authentication token (JWT for Turso, password for Postgres) */ + authToken: external_exports.string().optional().describe("Database auth token (encrypted at rest)"), + /** Turso database group name */ + group: external_exports.string().optional().describe("Turso database group name") +}).describe("Tenant database connection configuration"); +var TenantQuotaSchema2 = external_exports.object({ + /** + * Maximum number of users allowed for this tenant + */ + maxUsers: external_exports.number().int().positive().optional().describe("Maximum number of users"), + /** + * Maximum storage space in bytes + */ + maxStorage: external_exports.number().int().positive().optional().describe("Maximum storage in bytes"), + /** + * API rate limit (requests per minute) + */ + apiRateLimit: external_exports.number().int().positive().optional().describe("API requests per minute"), + /** + * Maximum number of custom objects the tenant can create + */ + maxObjects: external_exports.number().int().positive().optional().describe("Maximum number of custom objects"), + /** + * Maximum records per object/table + */ + maxRecordsPerObject: external_exports.number().int().positive().optional().describe("Maximum records per object"), + /** + * Maximum deployments allowed per day + */ + maxDeploymentsPerDay: external_exports.number().int().positive().optional().describe("Maximum deployments per day"), + /** + * Maximum storage in bytes + */ + maxStorageBytes: external_exports.number().int().positive().optional().describe("Maximum storage in bytes") +}); +external_exports.object({ + /** Current number of custom objects */ + currentObjectCount: external_exports.number().int().min(0).default(0).describe("Current number of custom objects"), + /** Current total record count across all objects */ + currentRecordCount: external_exports.number().int().min(0).default(0).describe("Total records across all objects"), + /** Current storage usage in bytes */ + currentStorageBytes: external_exports.number().int().min(0).default(0).describe("Current storage usage in bytes"), + /** Deployments executed today */ + deploymentsToday: external_exports.number().int().min(0).default(0).describe("Deployments executed today"), + /** Current number of active users */ + currentUsers: external_exports.number().int().min(0).default(0).describe("Current number of active users"), + /** API requests in the current minute */ + apiRequestsThisMinute: external_exports.number().int().min(0).default(0).describe("API requests in the current minute"), + /** Last updated timestamp (ISO 8601) */ + lastUpdatedAt: external_exports.string().datetime().optional().describe("Last usage update time") +}).describe("Current tenant resource usage"); +external_exports.object({ + /** Whether the operation is allowed */ + allowed: external_exports.boolean().describe("Whether the operation is within quota"), + /** Quota that would be exceeded (if not allowed) */ + exceededQuota: external_exports.string().optional().describe("Name of the exceeded quota"), + /** Current usage value */ + currentUsage: external_exports.number().optional().describe("Current usage value"), + /** Quota limit value */ + limit: external_exports.number().optional().describe("Quota limit"), + /** Human-readable message */ + message: external_exports.string().optional().describe("Human-readable quota message") +}).describe("Quota enforcement check result"); +external_exports.object({ + /** + * Unique tenant identifier + */ + id: external_exports.string().describe("Unique tenant identifier"), + /** + * Tenant display name + */ + name: external_exports.string().describe("Tenant display name"), + /** + * Data isolation level + */ + isolationLevel: TenantIsolationLevel2, + /** + * Database provider for this tenant + */ + databaseProvider: DatabaseProviderSchema2.optional().describe("Database provider"), + /** + * Database connection configuration (encrypted at rest) + */ + connectionConfig: TenantConnectionConfigSchema2.optional().describe("Database connection config"), + /** + * Current provisioning status + */ + provisioningStatus: external_exports.enum([ + "provisioning", + "active", + "suspended", + "failed", + "destroying" + ]).optional().describe("Current provisioning lifecycle status"), + /** + * Tenant subscription plan + */ + plan: external_exports.enum(["free", "pro", "enterprise"]).optional().describe("Subscription plan"), + /** + * Custom configuration values + */ + customizations: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom configuration values"), + /** + * Resource quotas + */ + quotas: TenantQuotaSchema2.optional() +}); +var RowLevelIsolationStrategySchema2 = external_exports.object({ + strategy: external_exports.literal("shared_schema").describe("Row-level isolation strategy"), + /** + * Database configuration for row-level isolation + */ + database: external_exports.object({ + /** + * Whether to enable Row-Level Security (RLS) + */ + enableRLS: external_exports.boolean().default(true).describe("Enable PostgreSQL Row-Level Security"), + /** + * Tenant context setting method + */ + contextMethod: external_exports.enum([ + "session_variable", + // SET app.current_tenant = 'tenant_123' + "search_path", + // SET search_path = tenant_123, public + "application_name" + // SET application_name = 'tenant_123' + ]).default("session_variable").describe("How to set tenant context"), + /** + * Session variable name for tenant context + */ + contextVariable: external_exports.string().default("app.current_tenant").describe("Session variable name"), + /** + * Whether to validate tenant_id at application level + */ + applicationValidation: external_exports.boolean().default(true).describe("Application-level tenant validation") + }).optional().describe("Database configuration"), + /** + * Performance optimization settings + */ + performance: external_exports.object({ + /** + * Whether to use partial indexes for tenant_id + */ + usePartialIndexes: external_exports.boolean().default(true).describe("Use partial indexes per tenant"), + /** + * Whether to use table partitioning + */ + usePartitioning: external_exports.boolean().default(false).describe("Use table partitioning by tenant_id"), + /** + * Connection pool size per tenant + */ + poolSizePerTenant: external_exports.number().int().positive().optional().describe("Connection pool size per tenant") + }).optional().describe("Performance settings") +}); +var SchemaLevelIsolationStrategySchema2 = external_exports.object({ + strategy: external_exports.literal("isolated_schema").describe("Schema-level isolation strategy"), + /** + * Schema configuration + */ + schema: external_exports.object({ + /** + * Schema naming pattern + * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) + * The tenant_id will be sanitized before substitution to prevent SQL injection + */ + namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Schema naming pattern"), + /** + * Whether to include public schema in search_path + */ + includePublicSchema: external_exports.boolean().default(true).describe("Include public schema"), + /** + * Default schema for shared resources + */ + sharedSchema: external_exports.string().default("public").describe("Schema for shared resources"), + /** + * Whether to automatically create schema on tenant creation + */ + autoCreateSchema: external_exports.boolean().default(true).describe("Auto-create schema") + }).optional().describe("Schema configuration"), + /** + * Migration configuration + */ + migrations: external_exports.object({ + /** + * Migration strategy + */ + strategy: external_exports.enum([ + "parallel", + // Run migrations on all schemas in parallel + "sequential", + // Run migrations one schema at a time + "on_demand" + // Run migrations when tenant accesses system + ]).default("parallel").describe("Migration strategy"), + /** + * Maximum concurrent migrations + */ + maxConcurrent: external_exports.number().int().positive().default(10).describe("Max concurrent migrations"), + /** + * Whether to rollback on first failure + */ + rollbackOnError: external_exports.boolean().default(true).describe("Rollback on error") + }).optional().describe("Migration configuration"), + /** + * Performance optimization settings + */ + performance: external_exports.object({ + /** + * Whether to use connection pooling per schema + */ + poolPerSchema: external_exports.boolean().default(false).describe("Separate pool per schema"), + /** + * Schema cache TTL in seconds + */ + schemaCacheTTL: external_exports.number().int().positive().default(3600).describe("Schema cache TTL") + }).optional().describe("Performance settings") +}); +var DatabaseLevelIsolationStrategySchema2 = external_exports.object({ + strategy: external_exports.literal("isolated_db").describe("Database-level isolation strategy"), + /** + * Database configuration + */ + database: external_exports.object({ + /** + * Database naming pattern + * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) + * The tenant_id will be sanitized before substitution to prevent SQL injection + */ + namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Database naming pattern"), + /** + * Database server/cluster assignment strategy + */ + serverStrategy: external_exports.enum([ + "shared", + // All tenant databases on same server + "sharded", + // Tenant databases distributed across servers + "dedicated" + // Each tenant gets dedicated server (enterprise) + ]).default("shared").describe("Server assignment strategy"), + /** + * Whether to use separate credentials per tenant + */ + separateCredentials: external_exports.boolean().default(true).describe("Separate credentials per tenant"), + /** + * Whether to automatically create database on tenant creation + */ + autoCreateDatabase: external_exports.boolean().default(true).describe("Auto-create database") + }).optional().describe("Database configuration"), + /** + * Connection pooling configuration + */ + connectionPool: external_exports.object({ + /** + * Pool size per tenant database + */ + poolSize: external_exports.number().int().positive().default(10).describe("Connection pool size"), + /** + * Maximum number of tenant pools to keep active + */ + maxActivePools: external_exports.number().int().positive().default(100).describe("Max active pools"), + /** + * Idle pool timeout in seconds + */ + idleTimeout: external_exports.number().int().positive().default(300).describe("Idle pool timeout"), + /** + * Whether to use connection pooler (PgBouncer, etc.) + */ + usePooler: external_exports.boolean().default(true).describe("Use connection pooler") + }).optional().describe("Connection pool configuration"), + /** + * Backup and restore configuration + */ + backup: external_exports.object({ + /** + * Backup strategy per tenant + */ + strategy: external_exports.enum([ + "individual", + // Separate backup per tenant + "consolidated", + // Combined backup with all tenants + "on_demand" + // Backup only when requested + ]).default("individual").describe("Backup strategy"), + /** + * Backup frequency in hours + */ + frequencyHours: external_exports.number().int().positive().default(24).describe("Backup frequency"), + /** + * Retention period in days + */ + retentionDays: external_exports.number().int().positive().default(30).describe("Backup retention days") + }).optional().describe("Backup configuration"), + /** + * Encryption configuration + */ + encryption: external_exports.object({ + /** + * Whether to use per-tenant encryption keys + */ + perTenantKeys: external_exports.boolean().default(false).describe("Per-tenant encryption keys"), + /** + * Encryption algorithm + */ + algorithm: external_exports.string().default("AES-256-GCM").describe("Encryption algorithm"), + /** + * Key management service + */ + keyManagement: external_exports.enum(["aws_kms", "azure_key_vault", "gcp_kms", "hashicorp_vault", "custom"]).optional().describe("Key management service") + }).optional().describe("Encryption configuration") +}); +external_exports.discriminatedUnion("strategy", [ + RowLevelIsolationStrategySchema2, + SchemaLevelIsolationStrategySchema2, + DatabaseLevelIsolationStrategySchema2 +]); +external_exports.object({ + /** + * Encryption requirements + */ + encryption: external_exports.object({ + /** + * Require encryption at rest + */ + atRest: external_exports.boolean().default(true).describe("Require encryption at rest"), + /** + * Require encryption in transit + */ + inTransit: external_exports.boolean().default(true).describe("Require encryption in transit"), + /** + * Require field-level encryption for sensitive data + */ + fieldLevel: external_exports.boolean().default(false).describe("Require field-level encryption") + }).optional().describe("Encryption requirements"), + /** + * Access control requirements + */ + accessControl: external_exports.object({ + /** + * Require multi-factor authentication + */ + requireMFA: external_exports.boolean().default(false).describe("Require MFA"), + /** + * Require SSO/SAML authentication + */ + requireSSO: external_exports.boolean().default(false).describe("Require SSO"), + /** + * IP whitelist + */ + ipWhitelist: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses"), + /** + * Session timeout in seconds + */ + sessionTimeout: external_exports.number().int().positive().default(3600).describe("Session timeout") + }).optional().describe("Access control requirements"), + /** + * Audit and compliance requirements + */ + compliance: external_exports.object({ + /** + * Compliance standards to enforce + */ + standards: external_exports.array(external_exports.enum([ + "sox", + "hipaa", + "gdpr", + "pci_dss", + "iso_27001", + "fedramp" + ])).optional().describe("Compliance standards"), + /** + * Require audit logging for all operations + */ + requireAuditLog: external_exports.boolean().default(true).describe("Require audit logging"), + /** + * Audit log retention period in days + */ + auditRetentionDays: external_exports.number().int().positive().default(365).describe("Audit retention days"), + /** + * Data residency requirements + */ + dataResidency: external_exports.object({ + /** + * Required geographic region + */ + region: external_exports.string().optional().describe("Required region (e.g., US, EU, APAC)"), + /** + * Prohibited regions + */ + excludeRegions: external_exports.array(external_exports.string()).optional().describe("Prohibited regions") + }).optional().describe("Data residency requirements") + }).optional().describe("Compliance requirements") +}); +var RuntimeMode = external_exports.enum([ + "development", + // Hot-reload, verbose logging + "production", + // Optimized, strict security + "test", + // Mocked interfaces + "provisioning", + // Setup/Migration mode + "preview" + // Demo/preview mode — bypass auth, simulate admin identity +]).describe("Kernel operating mode"); +var PreviewModeConfigSchema = external_exports.object({ + /** + * Automatically log in as a simulated user on startup. + * When enabled, the frontend skips login/registration screens entirely. + */ + autoLogin: external_exports.boolean().default(true).describe("Auto-login as simulated user, skipping login/registration pages"), + /** + * Role of the simulated user. + * Determines the permission level of the auto-created preview session. + */ + simulatedRole: external_exports.enum(["admin", "user", "viewer"]).default("admin").describe("Permission role for the simulated preview user"), + /** + * Display name for the simulated user shown in the UI. + */ + simulatedUserName: external_exports.string().default("Preview User").describe("Display name for the simulated preview user"), + /** + * Whether the preview session is read-only. + * When true, all write operations (create, update, delete) are blocked. + */ + readOnly: external_exports.boolean().default(false).describe("Restrict the preview session to read-only operations"), + /** + * Session duration in seconds. After expiry the preview session ends. + * 0 means no expiration. + */ + expiresInSeconds: external_exports.number().int().min(0).default(0).describe("Preview session duration in seconds (0 = no expiration)"), + /** + * Optional banner message shown in the UI to indicate preview mode. + * Useful for marketplace demos so visitors know they are in a sandbox. + */ + bannerMessage: external_exports.string().optional().describe("Banner message displayed in the UI during preview mode") +}); +var KernelContextSchema = external_exports.object({ + /** + * Instance Identity + */ + instanceId: external_exports.string().uuid().describe("Unique UUID for this running kernel process"), + /** + * Environment Metadata + */ + mode: RuntimeMode.default("production"), + version: external_exports.string().describe("Kernel version"), + appName: external_exports.string().optional().describe("Host application name"), + /** + * Paths + */ + cwd: external_exports.string().describe("Current working directory"), + workspaceRoot: external_exports.string().optional().describe("Workspace root if different from cwd"), + /** + * Telemetry + */ + startTime: external_exports.number().int().describe("Boot timestamp (ms)"), + /** + * Feature Flags (Global) + */ + features: external_exports.record(external_exports.string(), external_exports.boolean()).default({}).describe("Global feature toggles"), + /** + * Preview Mode Configuration. + * Only relevant when `mode` is `'preview'`. Configures auto-login, + * simulated identity, read-only restrictions, and UI banner. + */ + previewMode: PreviewModeConfigSchema.optional().describe('Preview/demo mode configuration (used when mode is "preview")') +}); +var TenantRuntimeContextSchema = KernelContextSchema.extend({ + /** Unique tenant identifier resolved from the current session */ + tenantId: external_exports.string().min(1).describe("Resolved tenant identifier"), + /** Tenant subscription plan */ + tenantPlan: external_exports.enum(["free", "pro", "enterprise"]).describe("Tenant subscription plan"), + /** Tenant deployment region */ + tenantRegion: external_exports.string().optional().describe("Tenant deployment region"), + /** Tenant database connection URL */ + tenantDbUrl: external_exports.string().min(1).describe("Tenant database connection URL"), + /** Optional tenant quotas for the current plan */ + tenantQuotas: TenantQuotaSchema2.optional().describe("Tenant resource quotas") +}).describe("Tenant-aware kernel runtime context"); +var DependencyStatusEnum2 = external_exports.enum([ + "satisfied", + // Already installed and version compatible + "needs_install", + // Not installed, needs to be installed + "needs_upgrade", + // Installed but version incompatible, needs upgrade + "conflict" + // Conflicts with another package's dependency +]).describe("Resolution status for a dependency"); +var ResolvedDependencySchema2 = external_exports.object({ + /** Package identifier of the dependency */ + packageId: external_exports.string().describe("Dependency package identifier"), + /** SemVer range required by the parent package */ + requiredRange: external_exports.string().describe('SemVer range required (e.g. "^2.0.0")'), + /** Actual version resolved (if available) */ + resolvedVersion: external_exports.string().optional().describe("Actual version resolved from registry"), + /** Currently installed version (if any) */ + installedVersion: external_exports.string().optional().describe("Currently installed version"), + /** Resolution status */ + status: DependencyStatusEnum2.describe("Resolution status"), + /** Conflict details (when status is "conflict") */ + conflictReason: external_exports.string().optional().describe("Explanation of the conflict") +}).describe("Resolution result for a single dependency"); +var RequiredActionSchema2 = external_exports.object({ + /** Type of action required */ + type: external_exports.enum(["install", "upgrade", "confirm_conflict"]).describe("Type of action required"), + /** Target package identifier */ + packageId: external_exports.string().describe("Target package identifier"), + /** Human-readable description of the action */ + description: external_exports.string().describe("Human-readable action description") +}).describe("Action required before installation can proceed"); +var DependencyResolutionResultSchema2 = external_exports.object({ + /** All dependencies and their resolution results */ + dependencies: external_exports.array(ResolvedDependencySchema2).describe("Resolution result for each dependency"), + /** Whether installation can proceed without conflicts */ + canProceed: external_exports.boolean().describe("Whether installation can proceed"), + /** Actions that require user confirmation or system execution */ + requiredActions: external_exports.array(RequiredActionSchema2).describe("Actions required before proceeding"), + /** Topologically sorted package IDs for installation order */ + installOrder: external_exports.array(external_exports.string()).describe("Topologically sorted package IDs for installation"), + /** Detected circular dependency chains */ + circularDependencies: external_exports.array(external_exports.array(external_exports.string())).optional().describe('Circular dependency chains detected (e.g. [["A", "B", "A"]])') +}).describe("Complete dependency resolution result"); +var DevServiceOverrideSchema = external_exports.object({ + /** Service identifier (e.g. 'auth', 'eventBus', 'fileStorage') */ + service: external_exports.string().min(1).describe("Target service identifier"), + /** Whether this service is enabled in dev mode */ + enabled: external_exports.boolean().default(true).describe("Enable or disable this service"), + /** + * Implementation strategy for the service in dev mode. + * - mock: Use a mock/stub that records calls (for assertions) + * - memory: Use a real but in-memory implementation (e.g. SQLite, Map) + * - stub: Use a static/no-op implementation + * - passthrough: Use the real production implementation (for integration testing) + */ + strategy: external_exports.enum(["mock", "memory", "stub", "passthrough"]).default("memory").describe("Implementation strategy for development"), + /** Optional per-service configuration (strategy-specific) */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Strategy-specific configuration for this service override") +}); +var DevFixtureConfigSchema = external_exports.object({ + /** Whether to load fixtures on startup */ + enabled: external_exports.boolean().default(true).describe("Load fixture data on startup"), + /** + * Glob patterns pointing to fixture files + * (e.g. `["./fixtures/*.json", "./test/data/*.yml"]`) + */ + paths: external_exports.array(external_exports.string()).optional().describe("Glob patterns for fixture files"), + /** Whether to reset data before loading fixtures */ + resetBeforeLoad: external_exports.boolean().default(true).describe("Clear existing data before loading fixtures"), + /** + * Environment tag filter – only load fixtures tagged for these environments. + * When omitted, all fixtures are loaded. + */ + envFilter: external_exports.array(external_exports.string()).optional().describe("Only load fixtures matching these environment tags") +}); +var DevToolsConfigSchema = external_exports.object({ + /** Enable hot-module replacement / live reload */ + hotReload: external_exports.boolean().default(true).describe("Enable HMR / live-reload"), + /** Enable request inspector UI for debugging HTTP traffic */ + requestInspector: external_exports.boolean().default(false).describe("Enable request inspector"), + /** Enable an in-browser database explorer */ + dbExplorer: external_exports.boolean().default(false).describe("Enable database explorer UI"), + /** Enable verbose logging across all services */ + verboseLogging: external_exports.boolean().default(true).describe("Enable verbose logging"), + /** Enable OpenAPI / Swagger documentation endpoint */ + apiDocs: external_exports.boolean().default(true).describe("Serve OpenAPI docs at /_dev/docs"), + /** Enable a mail catcher for outbound email (like MailHog) */ + mailCatcher: external_exports.boolean().default(false).describe("Capture outbound emails in dev") +}); +var DevPluginPreset = external_exports.enum([ + "minimal", + "standard", + "full" +]).describe("Predefined dev configuration profile"); +var DevPluginConfigSchema = external_exports.object({ + /** + * Configuration preset. + * When provided, services and tools are pre-configured for the selected + * profile. Individual `services` and `tools` settings override the preset. + * @default 'standard' + */ + preset: DevPluginPreset.default("standard").describe("Base configuration preset"), + /** + * Per-service overrides. + * Keys are service names; values configure the dev strategy. + * Only services explicitly listed here override the preset defaults. + */ + services: external_exports.record( + external_exports.string().min(1), + DevServiceOverrideSchema.omit({ service: true }) + ).optional().describe("Per-service dev overrides keyed by service name"), + /** Fixture / seed data configuration */ + fixtures: DevFixtureConfigSchema.optional().describe("Fixture data loading configuration"), + /** Developer tooling configuration */ + tools: DevToolsConfigSchema.optional().describe("Developer tooling settings"), + /** + * Port for the dev-tools UI dashboard. + * Serves a lightweight web dashboard for inspecting services, events, + * and request logs during development. + * @default 4400 + */ + port: external_exports.number().int().min(1).max(65535).default(4400).describe("Port for the dev-tools dashboard"), + /** + * Auto-open the dev-tools dashboard in the default browser on startup. + */ + open: external_exports.boolean().default(false).describe("Auto-open dev dashboard in browser"), + /** + * Seed a default admin user for development. + * When enabled, the dev plugin creates a pre-authenticated admin user + * so that developers can bypass login flows. + */ + seedAdminUser: external_exports.boolean().default(true).describe("Create a default admin user for development"), + /** + * Simulated latency (ms) to add to service calls. + * Helps developers build UIs that handle loading states correctly. + * Set to 0 to disable. + */ + simulatedLatency: external_exports.number().int().min(0).default(0).describe("Artificial latency (ms) added to service calls") +}); +external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' +}).describe("System identifier (lowercase with underscores or dots)"); +var SnakeCaseIdentifierSchema5 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { + message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' +}).describe("Snake case identifier (lowercase with underscores only)"); +var EventNameSchema3 = external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' +}).describe("Event name (lowercase with dot notation for namespacing)"); +var EventPriority = external_exports.enum([ + "critical", + // 0 - Process immediately, block if necessary + "high", + // 1 - Process soon, minimal delay + "normal", + // 2 - Default priority + "low", + // 3 - Process when resources available + "background" + // 4 - Process during idle time +]); +var EventMetadataSchema = external_exports.object({ + source: external_exports.string().describe("Event source (e.g., plugin name, system component)"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when event was created"), + userId: external_exports.string().optional().describe("User who triggered the event"), + tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant systems"), + correlationId: external_exports.string().optional().describe("Correlation ID for event tracing"), + causationId: external_exports.string().optional().describe("ID of the event that caused this event"), + priority: EventPriority.optional().default("normal").describe("Event priority") +}); +var EventTypeDefinitionSchema = external_exports.object({ + name: EventNameSchema3.describe("Event type name (lowercase with dots)"), + version: external_exports.string().default("1.0.0").describe("Event schema version"), + schema: external_exports.unknown().optional().describe("JSON Schema for event payload validation"), + description: external_exports.string().optional().describe("Event type description"), + deprecated: external_exports.boolean().optional().default(false).describe("Whether this event type is deprecated"), + tags: external_exports.array(external_exports.string()).optional().describe("Event type tags") +}); +var EventSchema = external_exports.object({ + /** + * Event identifier (for tracking and deduplication) + */ + id: external_exports.string().optional().describe("Unique event identifier"), + /** + * Event name + */ + name: EventNameSchema3.describe("Event name (lowercase with dots, e.g., user.created, order.paid)"), + /** + * Event payload + */ + payload: external_exports.unknown().describe("Event payload schema"), + /** + * Event metadata + */ + metadata: EventMetadataSchema.describe("Event metadata") +}); +var EventHandlerSchema = external_exports.object({ + /** + * Handler identifier + */ + id: external_exports.string().optional().describe("Unique handler identifier"), + /** + * Event name pattern + */ + eventName: external_exports.string().describe("Name of event to handle (supports wildcards like user.*)"), + /** + * Handler function + */ + handler: external_exports.unknown().describe("Handler function"), + /** + * Execution priority + */ + priority: external_exports.number().int().default(0).describe("Execution priority (lower numbers execute first)"), + /** + * Async execution + */ + async: external_exports.boolean().default(true).describe("Execute in background (true) or block (false)"), + /** + * Retry configuration + */ + retry: external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retry attempts"), + backoffMs: external_exports.number().int().positive().default(1e3).describe("Initial backoff delay"), + backoffMultiplier: external_exports.number().positive().default(2).describe("Backoff multiplier") + }).optional().describe("Retry policy for failed handlers"), + /** + * Timeout + */ + timeoutMs: external_exports.number().int().positive().optional().describe("Handler timeout in milliseconds"), + /** + * Filter function + */ + filter: external_exports.unknown().optional().describe("Optional filter to determine if handler should execute") +}); +var EventRouteSchema = external_exports.object({ + from: external_exports.string().describe("Source event pattern (supports wildcards, e.g., user.* or *.created)"), + to: external_exports.array(external_exports.string()).describe("Target event names to route to"), + transform: external_exports.unknown().optional().describe("Optional function to transform payload") +}); +var EventPersistenceSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable event persistence"), + retention: external_exports.number().int().positive().describe("Days to retain persisted events"), + filter: external_exports.unknown().optional().describe("Optional filter function to select which events to persist"), + storage: external_exports.enum(["database", "file", "s3", "custom"]).default("database").describe("Storage backend for persisted events") +}); +var EventQueueConfigSchema = external_exports.object({ + /** + * Queue name + */ + name: external_exports.string().default("events").describe("Event queue name"), + /** + * Concurrency + */ + concurrency: external_exports.number().int().min(1).default(10).describe("Max concurrent event handlers"), + /** + * Retry policy + */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Max retries for failed events"), + backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy"), + initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay"), + maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Maximum retry delay") + }).optional().describe("Default retry policy for events"), + /** + * Dead letter queue + */ + deadLetterQueue: external_exports.string().optional().describe("Dead letter queue name for failed events"), + /** + * Enable priority processing + */ + priorityEnabled: external_exports.boolean().default(true).describe("Process events based on priority") +}); +var EventReplayConfigSchema = external_exports.object({ + /** + * Start timestamp + */ + fromTimestamp: external_exports.string().datetime().describe("Start timestamp for replay (ISO 8601)"), + /** + * End timestamp + */ + toTimestamp: external_exports.string().datetime().optional().describe("End timestamp for replay (ISO 8601)"), + /** + * Event types to replay + */ + eventTypes: external_exports.array(external_exports.string()).optional().describe("Event types to replay (empty = all)"), + /** + * Event filters + */ + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional filters for event selection"), + /** + * Replay speed multiplier + */ + speed: external_exports.number().positive().default(1).describe("Replay speed multiplier (1 = real-time)"), + /** + * Target handlers + */ + targetHandlers: external_exports.array(external_exports.string()).optional().describe("Handler IDs to execute (empty = all)") +}); +var EventSourcingConfigSchema = external_exports.object({ + /** + * Enable event sourcing + */ + enabled: external_exports.boolean().default(false).describe("Enable event sourcing"), + /** + * Snapshot interval + */ + snapshotInterval: external_exports.number().int().positive().default(100).describe("Create snapshot every N events"), + /** + * Snapshot retention + */ + snapshotRetention: external_exports.number().int().positive().default(10).describe("Number of snapshots to retain"), + /** + * Event retention + */ + retention: external_exports.number().int().positive().default(365).describe("Days to retain events"), + /** + * Aggregate types + */ + aggregateTypes: external_exports.array(external_exports.string()).optional().describe("Aggregate types to enable event sourcing for"), + /** + * Storage configuration + */ + storage: external_exports.object({ + type: external_exports.enum(["database", "file", "s3", "eventstore"]).default("database").describe("Storage backend"), + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage-specific options") + }).optional().describe("Event store configuration") +}); +var DeadLetterQueueEntrySchema = external_exports.object({ + /** + * Entry identifier + */ + id: external_exports.string().describe("Unique entry identifier"), + /** + * Original event + */ + event: EventSchema.describe("Original event"), + /** + * Failure reason + */ + error: external_exports.object({ + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Error stack trace"), + code: external_exports.string().optional().describe("Error code") + }).describe("Failure details"), + /** + * Retry count + */ + retries: external_exports.number().int().min(0).describe("Number of retry attempts"), + /** + * Timestamps + */ + firstFailedAt: external_exports.string().datetime().describe("When event first failed"), + lastFailedAt: external_exports.string().datetime().describe("When event last failed"), + /** + * Handler that failed + */ + failedHandler: external_exports.string().optional().describe("Handler ID that failed") +}); +var EventLogEntrySchema = external_exports.object({ + /** + * Log entry ID + */ + id: external_exports.string().describe("Unique log entry identifier"), + /** + * Event + */ + event: EventSchema.describe("The event"), + /** + * Status + */ + status: external_exports.enum(["pending", "processing", "completed", "failed"]).describe("Processing status"), + /** + * Handlers executed + */ + handlersExecuted: external_exports.array(external_exports.object({ + handlerId: external_exports.string().describe("Handler identifier"), + status: external_exports.enum(["success", "failed", "timeout"]).describe("Handler execution status"), + durationMs: external_exports.number().int().optional().describe("Execution duration"), + error: external_exports.string().optional().describe("Error message if failed") + })).optional().describe("Handlers that processed this event"), + /** + * Timestamps + */ + receivedAt: external_exports.string().datetime().describe("When event was received"), + processedAt: external_exports.string().datetime().optional().describe("When event was processed"), + /** + * Total duration + */ + totalDurationMs: external_exports.number().int().optional().describe("Total processing time") +}); +var EventWebhookConfigSchema = external_exports.object({ + /** + * Webhook identifier + */ + id: external_exports.string().optional().describe("Unique webhook identifier"), + /** + * Event pattern to match + */ + eventPattern: external_exports.string().describe("Event name pattern (supports wildcards)"), + /** + * Target URL + */ + url: external_exports.string().url().describe("Webhook endpoint URL"), + /** + * HTTP method + */ + method: external_exports.enum(["GET", "POST", "PUT", "PATCH"]).default("POST").describe("HTTP method"), + /** + * Headers + */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP headers"), + /** + * Authentication + */ + authentication: external_exports.object({ + type: external_exports.enum(["none", "bearer", "basic", "api-key"]).describe("Auth type"), + credentials: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Auth credentials") + }).optional().describe("Authentication configuration"), + /** + * Retry policy + */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Max retry attempts"), + backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential"), + initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay"), + maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Max retry delay") + }).optional().describe("Retry policy"), + /** + * Timeout + */ + timeoutMs: external_exports.number().int().positive().default(3e4).describe("Request timeout in milliseconds"), + /** + * Event transformation + */ + transform: external_exports.unknown().optional().describe("Transform event before sending"), + /** + * Enabled + */ + enabled: external_exports.boolean().default(true).describe("Whether webhook is enabled") +}); +var EventMessageQueueConfigSchema = external_exports.object({ + /** + * Provider + */ + provider: external_exports.enum(["kafka", "rabbitmq", "aws-sqs", "redis-pubsub", "google-pubsub", "azure-service-bus"]).describe("Message queue provider"), + /** + * Topic/Queue name + */ + topic: external_exports.string().describe("Topic or queue name"), + /** + * Event pattern + */ + eventPattern: external_exports.string().default("*").describe("Event name pattern to publish (supports wildcards)"), + /** + * Partition key + */ + partitionKey: external_exports.string().optional().describe('JSON path for partition key (e.g., "metadata.tenantId")'), + /** + * Message format + */ + format: external_exports.enum(["json", "avro", "protobuf"]).default("json").describe("Message serialization format"), + /** + * Include metadata + */ + includeMetadata: external_exports.boolean().default(true).describe("Include event metadata in message"), + /** + * Compression + */ + compression: external_exports.enum(["none", "gzip", "snappy", "lz4"]).default("none").describe("Message compression"), + /** + * Batch size + */ + batchSize: external_exports.number().int().min(1).default(1).describe("Batch size for publishing"), + /** + * Flush interval + */ + flushIntervalMs: external_exports.number().int().positive().default(1e3).describe("Flush interval for batching") +}); +var RealTimeNotificationConfigSchema = external_exports.object({ + /** + * Enable real-time notifications + */ + enabled: external_exports.boolean().default(true).describe("Enable real-time notifications"), + /** + * Protocol + */ + protocol: external_exports.enum(["websocket", "sse", "long-polling"]).default("websocket").describe("Real-time protocol"), + /** + * Event pattern + */ + eventPattern: external_exports.string().default("*").describe("Event pattern to broadcast"), + /** + * User-specific filtering + */ + userFilter: external_exports.boolean().default(true).describe("Filter events by user"), + /** + * Tenant-specific filtering + */ + tenantFilter: external_exports.boolean().default(true).describe("Filter events by tenant"), + /** + * Channels + */ + channels: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Channel name"), + eventPattern: external_exports.string().describe("Event pattern for channel"), + filter: external_exports.unknown().optional().describe("Additional filter function") + })).optional().describe("Named channels for event broadcasting"), + /** + * Rate limiting + */ + rateLimit: external_exports.object({ + maxEventsPerSecond: external_exports.number().int().positive().describe("Max events per second per client"), + windowMs: external_exports.number().int().positive().default(1e3).describe("Rate limit window") + }).optional().describe("Rate limiting configuration") +}); +var EventBusConfigSchema = external_exports.object({ + /** + * Event persistence + */ + persistence: EventPersistenceSchema.optional().describe("Event persistence configuration"), + /** + * Event queue + */ + queue: EventQueueConfigSchema.optional().describe("Event queue configuration"), + /** + * Event sourcing + */ + eventSourcing: EventSourcingConfigSchema.optional().describe("Event sourcing configuration"), + /** + * Event replay + */ + replay: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable event replay capability") + }).optional().describe("Event replay configuration"), + /** + * Webhooks + */ + webhooks: external_exports.array(EventWebhookConfigSchema).optional().describe("Webhook configurations"), + /** + * Message queue integration + */ + messageQueue: EventMessageQueueConfigSchema.optional().describe("Message queue integration"), + /** + * Real-time notifications + */ + realtime: RealTimeNotificationConfigSchema.optional().describe("Real-time notification configuration"), + /** + * Event type definitions + */ + eventTypes: external_exports.array(EventTypeDefinitionSchema).optional().describe("Event type definitions"), + /** + * Global handlers + */ + handlers: external_exports.array(EventHandlerSchema).optional().describe("Global event handlers") +}); +var FeatureStrategy = external_exports.enum([ + "boolean", + // Simple On/Off + "percentage", + // Gradual rollout (0-100%) + "user_list", + // Specific users + "group", + // Specific groups/roles + "custom" + // Custom constraint/script +]); +var FeatureFlagSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema5.describe("Feature key (snake_case)"), + label: external_exports.string().optional().describe("Display label"), + description: external_exports.string().optional(), + /** Default state */ + enabled: external_exports.boolean().default(false).describe("Is globally enabled"), + /** Rollout Strategy */ + strategy: FeatureStrategy.default("boolean"), + /** Strategy Configuration */ + conditions: external_exports.object({ + percentage: external_exports.number().min(0).max(100).optional(), + users: external_exports.array(external_exports.string()).optional(), + groups: external_exports.array(external_exports.string()).optional(), + expression: external_exports.string().optional().describe("Custom formula expression") + }).optional(), + /** Integration */ + environment: external_exports.enum(["dev", "staging", "prod", "all"]).default("all").describe("Environment validity"), + /** Expiration */ + expiresAt: external_exports.string().datetime().optional().describe("Feature flag expiration date") +}); +var FeatureFlag = Object.assign(FeatureFlagSchema, { + create: (config4) => config4 +}); +var CapabilityConformanceLevelSchema2 = external_exports.enum([ + "full", + // Complete implementation of all protocol features + "partial", + // Subset implementation with specific features listed + "experimental", + // Unstable/preview implementation + "deprecated" + // Still supported but scheduled for removal +]).describe("Level of protocol conformance"); +var ProtocolVersionSchema2 = external_exports.object({ + major: external_exports.number().int().min(0), + minor: external_exports.number().int().min(0), + patch: external_exports.number().int().min(0) +}).describe("Semantic version of the protocol"); +var ProtocolReferenceSchema2 = external_exports.object({ + /** + * Protocol identifier using reverse domain notation. + * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major} + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+protocol\.[a-z][a-z0-9._]*\.v\d+$/).describe("Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)"), + /** + * Human-readable protocol name + */ + label: external_exports.string(), + /** + * Protocol version + */ + version: ProtocolVersionSchema2, + /** + * Detailed protocol specification URL or file reference + */ + specification: external_exports.string().optional().describe("URL or path to protocol specification"), + /** + * Brief description of what this protocol defines + */ + description: external_exports.string().optional() +}); +var ProtocolFeatureSchema2 = external_exports.object({ + name: external_exports.string().describe("Feature identifier within the protocol"), + enabled: external_exports.boolean().default(true), + description: external_exports.string().optional(), + sinceVersion: external_exports.string().optional().describe("Version when this feature was added"), + deprecatedSince: external_exports.string().optional().describe("Version when deprecated") +}); +var PluginCapabilitySchema2 = external_exports.object({ + /** + * The protocol being implemented + */ + protocol: ProtocolReferenceSchema2, + /** + * Conformance level + */ + conformance: CapabilityConformanceLevelSchema2.default("full"), + /** + * Specific features implemented (required if conformance is 'partial') + */ + implementedFeatures: external_exports.array(external_exports.string()).optional().describe("List of implemented feature names"), + /** + * Optional feature flags indicating advanced capabilities + */ + features: external_exports.array(ProtocolFeatureSchema2).optional(), + /** + * Custom metadata for vendor-specific information + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Testing/Certification status + */ + certified: external_exports.boolean().default(false).describe("Has passed official conformance tests"), + certificationDate: external_exports.string().datetime().optional() +}); +var PluginInterfaceSchema2 = external_exports.object({ + /** + * Unique interface identifier + * Format: {plugin-id}.interface.{name} + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+interface\.[a-z][a-z0-9._]+$/).describe("Unique interface identifier"), + /** + * Interface name + */ + name: external_exports.string(), + /** + * Description of what this interface provides + */ + description: external_exports.string().optional(), + /** + * Interface version + */ + version: ProtocolVersionSchema2, + /** + * Methods exposed by this interface + */ + methods: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Method name"), + description: external_exports.string().optional(), + parameters: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string().describe("Type notation (e.g., string, number, User)"), + required: external_exports.boolean().default(true), + description: external_exports.string().optional() + })).optional(), + returnType: external_exports.string().optional().describe("Return value type"), + async: external_exports.boolean().default(false).describe("Whether method returns a Promise") + })), + /** + * Events emitted by this interface + */ + events: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Event name"), + description: external_exports.string().optional(), + payload: external_exports.string().optional().describe("Event payload type") + })).optional(), + /** + * Stability level + */ + stability: external_exports.enum(["stable", "beta", "alpha", "experimental"]).default("stable") +}); +var PluginDependencySchema2 = external_exports.object({ + /** + * Plugin ID using reverse domain notation + */ + pluginId: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Required plugin identifier"), + /** + * Version constraint (supports semver ranges) + * Examples: "1.0.0", "^1.2.3", ">=2.0.0 <3.0.0" + */ + version: external_exports.string().describe("Semantic version constraint"), + /** + * Whether this dependency is optional + */ + optional: external_exports.boolean().default(false), + /** + * Reason for the dependency + */ + reason: external_exports.string().optional(), + /** + * Minimum required capabilities from the dependency + */ + requiredCapabilities: external_exports.array(external_exports.string()).optional().describe("Protocol IDs the dependency must support") +}); +var ExtensionPointSchema2 = external_exports.object({ + /** + * Extension point identifier + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+extension\.[a-z][a-z0-9._]+$/).describe("Unique extension point identifier"), + /** + * Extension point name + */ + name: external_exports.string(), + /** + * Description + */ + description: external_exports.string().optional(), + /** + * Type of extension point + */ + type: external_exports.enum([ + "action", + // Plugins can register executable actions + "hook", + // Plugins can listen to lifecycle events + "widget", + // Plugins can contribute UI widgets + "provider", + // Plugins can provide data/services + "transformer", + // Plugins can transform data + "validator", + // Plugins can validate data + "decorator" + // Plugins can enhance/wrap functionality + ]), + /** + * Expected interface contract for extensions + */ + contract: external_exports.object({ + input: external_exports.string().optional().describe("Input type/schema"), + output: external_exports.string().optional().describe("Output type/schema"), + signature: external_exports.string().optional().describe("Function signature if applicable") + }).optional(), + /** + * Cardinality + */ + cardinality: external_exports.enum(["single", "multiple"]).default("multiple").describe("Whether multiple extensions can register to this point") +}); +var PluginCapabilityManifestSchema2 = external_exports.object({ + /** + * Protocols this plugin implements + */ + implements: external_exports.array(PluginCapabilitySchema2).optional().describe("List of protocols this plugin conforms to"), + /** + * Interfaces this plugin exposes to other plugins + */ + provides: external_exports.array(PluginInterfaceSchema2).optional().describe("Services/APIs this plugin offers to others"), + /** + * Dependencies on other plugins + */ + requires: external_exports.array(PluginDependencySchema2).optional().describe("Required plugins and their capabilities"), + /** + * Extension points this plugin defines + */ + extensionPoints: external_exports.array(ExtensionPointSchema2).optional().describe("Points where other plugins can extend this plugin"), + /** + * Extensions this plugin contributes to other plugins + */ + extensions: external_exports.array(external_exports.object({ + targetPluginId: external_exports.string().describe("Plugin ID being extended"), + extensionPointId: external_exports.string().describe("Extension point identifier"), + implementation: external_exports.string().describe("Path to implementation module"), + priority: external_exports.number().int().default(100).describe("Registration priority (lower = higher priority)") + })).optional().describe("Extensions contributed to other plugins") +}); +var PluginLoadingStrategySchema2 = external_exports.enum([ + "eager", + // Load immediately during bootstrap (critical plugins) + "lazy", + // Load on first use (feature plugins) + "parallel", + // Load in parallel with other plugins + "deferred", + // Load after initial bootstrap complete + "on-demand" + // Load only when explicitly requested +]).describe("Plugin loading strategy"); +var PluginPreloadConfigSchema2 = external_exports.object({ + /** + * Enable preloading for this plugin + */ + enabled: external_exports.boolean().default(false), + /** + * Preload priority (lower = higher priority) + */ + priority: external_exports.number().int().min(0).default(100), + /** + * Resources to preload + */ + resources: external_exports.array(external_exports.enum([ + "metadata", + // Plugin manifest and metadata + "dependencies", + // Plugin dependencies + "assets", + // Static assets (icons, translations) + "code", + // JavaScript code chunks + "services" + // Service definitions + ])).optional(), + /** + * Conditions for preloading + */ + conditions: external_exports.object({ + /** + * Preload only on specific routes + */ + routes: external_exports.array(external_exports.string()).optional(), + /** + * Preload only for specific user roles + */ + roles: external_exports.array(external_exports.string()).optional(), + /** + * Preload based on device type + */ + deviceType: external_exports.array(external_exports.enum(["desktop", "mobile", "tablet"])).optional(), + /** + * Network connection quality threshold + */ + minNetworkSpeed: external_exports.enum(["slow-2g", "2g", "3g", "4g"]).optional() + }).optional() +}).describe("Plugin preloading configuration"); +var PluginCodeSplittingSchema2 = external_exports.object({ + /** + * Enable code splitting for this plugin + */ + enabled: external_exports.boolean().default(true), + /** + * Split strategy + */ + strategy: external_exports.enum([ + "route", + // Split by UI routes + "feature", + // Split by feature modules + "size", + // Split by bundle size threshold + "custom" + // Custom split points defined by plugin + ]).default("feature"), + /** + * Chunk naming strategy + */ + chunkNaming: external_exports.enum(["hashed", "named", "sequential"]).default("hashed"), + /** + * Maximum chunk size in KB + */ + maxChunkSize: external_exports.number().int().min(10).optional().describe("Max chunk size in KB"), + /** + * Shared dependencies optimization + */ + sharedDependencies: external_exports.object({ + enabled: external_exports.boolean().default(true), + /** + * Minimum times a module must be shared before extraction + */ + minChunks: external_exports.number().int().min(1).default(2) + }).optional() +}).describe("Plugin code splitting configuration"); +var PluginDynamicImportSchema2 = external_exports.object({ + /** + * Enable dynamic imports + */ + enabled: external_exports.boolean().default(true), + /** + * Import mode + */ + mode: external_exports.enum([ + "async", + // Asynchronous import (recommended) + "sync", + // Synchronous import (blocking) + "eager", + // Eager evaluation + "lazy" + // Lazy evaluation + ]).default("async"), + /** + * Prefetch strategy + */ + prefetch: external_exports.boolean().default(false).describe("Prefetch module in idle time"), + /** + * Preload strategy + */ + preload: external_exports.boolean().default(false).describe("Preload module in parallel with parent"), + /** + * Webpack magic comments support + */ + webpackChunkName: external_exports.string().optional().describe("Custom chunk name for webpack"), + /** + * Import timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4).describe("Dynamic import timeout (ms)"), + /** + * Retry configuration on import failure + */ + retry: external_exports.object({ + enabled: external_exports.boolean().default(true), + maxAttempts: external_exports.number().int().min(1).max(10).default(3), + backoffMs: external_exports.number().int().min(0).default(1e3).describe("Exponential backoff base delay") + }).optional() +}).describe("Plugin dynamic import configuration"); +var PluginInitializationSchema2 = external_exports.object({ + /** + * Initialization mode + */ + mode: external_exports.enum([ + "sync", + // Synchronous initialization + "async", + // Asynchronous initialization + "parallel", + // Parallel with other plugins + "sequential" + // Must complete before next plugin + ]).default("async"), + /** + * Initialization timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4), + /** + * Startup priority (lower = higher priority, earlier initialization) + */ + priority: external_exports.number().int().min(0).default(100), + /** + * Whether to continue bootstrap if this plugin fails + */ + critical: external_exports.boolean().default(false).describe("If true, kernel bootstrap fails if plugin fails"), + /** + * Retry configuration on initialization failure + */ + retry: external_exports.object({ + enabled: external_exports.boolean().default(false), + maxAttempts: external_exports.number().int().min(1).max(5).default(3), + backoffMs: external_exports.number().int().min(0).default(1e3) + }).optional(), + /** + * Health check interval for monitoring + */ + healthCheckInterval: external_exports.number().int().min(0).optional().describe("Health check interval in ms (0 = disabled)") +}).describe("Plugin initialization configuration"); +var PluginDependencyResolutionSchema2 = external_exports.object({ + /** + * Dependency resolution strategy + */ + strategy: external_exports.enum([ + "strict", + // Exact version match required + "compatible", + // Semver compatible versions (^) + "latest", + // Always use latest compatible + "pinned" + // Lock to specific version + ]).default("compatible"), + /** + * Peer dependency handling + */ + peerDependencies: external_exports.object({ + /** + * Whether to resolve peer dependencies + */ + resolve: external_exports.boolean().default(true), + /** + * Action on missing peer dependency + */ + onMissing: external_exports.enum(["error", "warn", "ignore"]).default("warn"), + /** + * Action on peer version mismatch + */ + onMismatch: external_exports.enum(["error", "warn", "ignore"]).default("warn") + }).optional(), + /** + * Optional dependency handling + */ + optionalDependencies: external_exports.object({ + /** + * Whether to attempt loading optional dependencies + */ + load: external_exports.boolean().default(true), + /** + * Action on optional dependency load failure + */ + onFailure: external_exports.enum(["warn", "ignore"]).default("warn") + }).optional(), + /** + * Conflict resolution + */ + conflictResolution: external_exports.enum([ + "fail", + // Fail on any version conflict + "latest", + // Use latest version + "oldest", + // Use oldest version + "manual" + // Require manual resolution + ]).default("latest"), + /** + * Circular dependency handling + */ + circularDependencies: external_exports.enum([ + "error", + // Throw error on circular dependency + "warn", + // Warn but continue + "allow" + // Allow circular dependencies + ]).default("warn") +}).describe("Plugin dependency resolution configuration"); +var PluginHotReloadSchema2 = external_exports.object({ + /** + * Enable hot reload + */ + enabled: external_exports.boolean().default(false), + /** + * Target environment for hot reload behavior + */ + environment: external_exports.enum([ + "development", + // Fast reload with relaxed safety (file watchers, no health validation) + "staging", + // Production-like reload with validation but relaxed rollback + "production" + // Full safety: health validation, rollback, connection draining + ]).default("development").describe("Target environment controlling safety level"), + /** + * Hot reload strategy + */ + strategy: external_exports.enum([ + "full", + // Full plugin reload (destroy and reinitialize) + "partial", + // Partial reload (update changed modules only) + "state-preserve" + // Preserve plugin state during reload + ]).default("full"), + /** + * Files to watch for changes + */ + watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to watch"), + /** + * Files to ignore + */ + ignorePatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to ignore"), + /** + * Debounce delay in milliseconds + */ + debounceMs: external_exports.number().int().min(0).default(300), + /** + * Whether to preserve state during reload + */ + preserveState: external_exports.boolean().default(false), + /** + * State serialization + */ + stateSerialization: external_exports.object({ + enabled: external_exports.boolean().default(false), + /** + * Path to state serialization handler + */ + handler: external_exports.string().optional() + }).optional(), + /** + * Hooks for hot reload lifecycle + */ + hooks: external_exports.object({ + beforeReload: external_exports.string().optional().describe("Function to call before reload"), + afterReload: external_exports.string().optional().describe("Function to call after reload"), + onError: external_exports.string().optional().describe("Function to call on reload error") + }).optional(), + /** + * Production safety configuration + * Applied when environment is 'staging' or 'production' + */ + productionSafety: external_exports.object({ + /** + * Validate plugin health before completing reload + */ + healthValidation: external_exports.boolean().default(true).describe("Run health checks after reload before accepting traffic"), + /** + * Automatically rollback to previous version on reload failure + */ + rollbackOnFailure: external_exports.boolean().default(true).describe("Auto-rollback if reloaded plugin fails health check"), + /** + * Maximum time to wait for health validation after reload (ms) + */ + healthTimeout: external_exports.number().int().min(1e3).default(3e4).describe("Health check timeout after reload in ms"), + /** + * Drain active connections before reload + */ + drainConnections: external_exports.boolean().default(true).describe("Gracefully drain active requests before reloading"), + /** + * Maximum time to wait for connection draining (ms) + */ + drainTimeout: external_exports.number().int().min(0).default(15e3).describe("Max wait time for connection draining in ms"), + /** + * Maximum number of concurrent plugin reloads + */ + maxConcurrentReloads: external_exports.number().int().min(1).default(1).describe("Limit concurrent reloads to prevent system instability"), + /** + * Minimum interval between reloads of the same plugin (ms) + */ + minReloadInterval: external_exports.number().int().min(1e3).default(5e3).describe("Cooldown period between reloads of the same plugin") + }).optional() +}).describe("Plugin hot reload configuration"); +var PluginCachingSchema2 = external_exports.object({ + /** + * Enable caching + */ + enabled: external_exports.boolean().default(true), + /** + * Cache storage type + */ + storage: external_exports.enum([ + "memory", + // In-memory cache (fastest, not persistent) + "disk", + // Disk cache (persistent) + "indexeddb", + // Browser IndexedDB (persistent, browser only) + "hybrid" + // Memory + Disk hybrid + ]).default("memory"), + /** + * Cache key strategy + */ + keyStrategy: external_exports.enum([ + "version", + // Cache by plugin version + "hash", + // Cache by content hash + "timestamp" + // Cache by last modified timestamp + ]).default("version"), + /** + * Cache TTL in seconds + */ + ttl: external_exports.number().int().min(0).optional().describe("Time to live in seconds (0 = infinite)"), + /** + * Maximum cache size in MB + */ + maxSize: external_exports.number().int().min(1).optional().describe("Max cache size in MB"), + /** + * Cache invalidation triggers + */ + invalidateOn: external_exports.array(external_exports.enum([ + "version-change", + "dependency-change", + "manual", + "error" + ])).optional(), + /** + * Compression + */ + compression: external_exports.object({ + enabled: external_exports.boolean().default(false), + algorithm: external_exports.enum(["gzip", "brotli", "deflate"]).default("gzip") + }).optional() +}).describe("Plugin caching configuration"); +var PluginSandboxingSchema2 = external_exports.object({ + /** + * Enable sandboxing + */ + enabled: external_exports.boolean().default(false), + /** + * Isolation scope - which plugins are subject to sandboxing + */ + scope: external_exports.enum([ + "automation-only", + // Sandbox automation/scripting plugins only (current behavior) + "untrusted-only", + // Sandbox plugins below a trust threshold + "all-plugins" + // Sandbox all plugins (maximum isolation) + ]).default("automation-only").describe("Which plugins are subject to isolation"), + /** + * Sandbox isolation level + */ + isolationLevel: external_exports.enum([ + "none", + // No isolation + "process", + // Separate process (Node.js worker threads) + "vm", + // VM context isolation + "iframe", + // iframe isolation (browser) + "web-worker" + // Web Worker (browser) + ]).default("none"), + /** + * Allowed capabilities + */ + allowedCapabilities: external_exports.array(external_exports.string()).optional().describe("List of allowed capability IDs"), + /** + * Resource quotas + */ + resourceQuotas: external_exports.object({ + /** + * Maximum memory usage in MB + */ + maxMemoryMB: external_exports.number().int().min(1).optional(), + /** + * Maximum CPU time in milliseconds + */ + maxCpuTimeMs: external_exports.number().int().min(100).optional(), + /** + * Maximum number of file descriptors + */ + maxFileDescriptors: external_exports.number().int().min(1).optional(), + /** + * Maximum network bandwidth in KB/s + */ + maxNetworkKBps: external_exports.number().int().min(1).optional() + }).optional(), + /** + * Permissions + */ + permissions: external_exports.object({ + /** + * Allowed API access + */ + allowedAPIs: external_exports.array(external_exports.string()).optional(), + /** + * Allowed file system paths + */ + allowedPaths: external_exports.array(external_exports.string()).optional(), + /** + * Allowed network endpoints + */ + allowedEndpoints: external_exports.array(external_exports.string()).optional(), + /** + * Allowed environment variables + */ + allowedEnvVars: external_exports.array(external_exports.string()).optional() + }).optional(), + /** + * Inter-Plugin Communication (IPC) configuration + * Enables isolated plugins to communicate with the kernel and other plugins + */ + ipc: external_exports.object({ + /** + * Enable IPC for sandboxed plugins + */ + enabled: external_exports.boolean().default(true).describe("Allow sandboxed plugins to communicate via IPC"), + /** + * IPC transport mechanism + */ + transport: external_exports.enum([ + "message-port", + // MessagePort (worker threads / Web Workers) + "unix-socket", + // Unix domain sockets (process isolation) + "tcp", + // TCP sockets (container isolation) + "memory" + // Shared memory channel (in-process VM) + ]).default("message-port").describe("IPC transport for cross-boundary communication"), + /** + * Maximum message size in bytes + */ + maxMessageSize: external_exports.number().int().min(1024).default(1048576).describe("Maximum IPC message size in bytes (default 1MB)"), + /** + * Message timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4).describe("IPC message response timeout in ms"), + /** + * Allowed service calls through IPC + */ + allowedServices: external_exports.array(external_exports.string()).optional().describe("Service names the sandboxed plugin may invoke via IPC") + }).optional() +}).describe("Plugin sandboxing configuration"); +var PluginPerformanceMonitoringSchema2 = external_exports.object({ + /** + * Enable performance monitoring + */ + enabled: external_exports.boolean().default(false), + /** + * Metrics to collect + */ + metrics: external_exports.array(external_exports.enum([ + "load-time", + "init-time", + "memory-usage", + "cpu-usage", + "api-calls", + "error-rate", + "cache-hit-rate" + ])).optional(), + /** + * Sampling rate (0-1, where 1 = 100%) + */ + samplingRate: external_exports.number().min(0).max(1).default(1), + /** + * Reporting interval in seconds + */ + reportingInterval: external_exports.number().int().min(1).default(60), + /** + * Performance budget thresholds + */ + budgets: external_exports.object({ + /** + * Maximum load time in milliseconds + */ + maxLoadTimeMs: external_exports.number().int().min(0).optional(), + /** + * Maximum init time in milliseconds + */ + maxInitTimeMs: external_exports.number().int().min(0).optional(), + /** + * Maximum memory usage in MB + */ + maxMemoryMB: external_exports.number().int().min(0).optional() + }).optional(), + /** + * Action on budget violation + */ + onBudgetViolation: external_exports.enum(["warn", "error", "ignore"]).default("warn") +}).describe("Plugin performance monitoring configuration"); +var PluginLoadingConfigSchema2 = external_exports.object({ + /** + * Loading strategy + */ + strategy: PluginLoadingStrategySchema2.default("lazy"), + /** + * Preloading configuration + */ + preload: PluginPreloadConfigSchema2.optional(), + /** + * Code splitting configuration + */ + codeSplitting: PluginCodeSplittingSchema2.optional(), + /** + * Dynamic import configuration + */ + dynamicImport: PluginDynamicImportSchema2.optional(), + /** + * Initialization configuration + */ + initialization: PluginInitializationSchema2.optional(), + /** + * Dependency resolution configuration + */ + dependencyResolution: PluginDependencyResolutionSchema2.optional(), + /** + * Hot reload configuration (development and production) + */ + hotReload: PluginHotReloadSchema2.optional(), + /** + * Caching configuration + */ + caching: PluginCachingSchema2.optional(), + /** + * Sandboxing configuration + */ + sandboxing: PluginSandboxingSchema2.optional(), + /** + * Performance monitoring + */ + monitoring: PluginPerformanceMonitoringSchema2.optional() +}).describe("Complete plugin loading configuration"); +var PluginLoadingEventSchema = external_exports.object({ + /** + * Event type + */ + type: external_exports.enum([ + "load-started", + "load-completed", + "load-failed", + "init-started", + "init-completed", + "init-failed", + "preload-started", + "preload-completed", + "cache-hit", + "cache-miss", + "hot-reload", + "dynamic-load", + // Plugin loaded at runtime + "dynamic-unload", + // Plugin unloaded at runtime + "dynamic-discover" + // Plugin discovered via registry + ]), + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Timestamp + */ + timestamp: external_exports.number().int().min(0), + /** + * Duration in milliseconds + */ + durationMs: external_exports.number().int().min(0).optional(), + /** + * Additional metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Error if event represents a failure + */ + error: external_exports.object({ + message: external_exports.string(), + code: external_exports.string().optional(), + stack: external_exports.string().optional() + }).optional() +}).describe("Plugin loading lifecycle event"); +var PluginLoadingStateSchema = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Current state + */ + state: external_exports.enum([ + "pending", + // Not yet loaded + "loading", + // Currently loading + "loaded", + // Code loaded, not initialized + "initializing", + // Currently initializing + "ready", + // Fully initialized and ready + "failed", + // Failed to load or initialize + "reloading", + // Hot reloading in progress + "unloading", + // Being unloaded at runtime + "unloaded" + // Successfully unloaded (dynamic loading) + ]), + /** + * Load progress (0-100) + */ + progress: external_exports.number().min(0).max(100).default(0), + /** + * Loading start time + */ + startedAt: external_exports.number().int().min(0).optional(), + /** + * Loading completion time + */ + completedAt: external_exports.number().int().min(0).optional(), + /** + * Last error + */ + lastError: external_exports.string().optional(), + /** + * Retry count + */ + retryCount: external_exports.number().int().min(0).default(0) +}).describe("Plugin loading state"); +var PluginContextSchema = external_exports.object({ + ql: external_exports.object({ + object: external_exports.function().describe("Get object handle for method chaining"), + query: external_exports.function().describe("Execute a query") + }).passthrough().describe("ObjectQL Engine Interface"), + os: external_exports.object({ + getCurrentUser: external_exports.function().describe("Get the current authenticated user"), + getConfig: external_exports.function().describe("Get platform configuration") + }).passthrough().describe("ObjectStack Kernel Interface"), + logger: external_exports.object({ + debug: external_exports.function().describe("Log debug message"), + info: external_exports.function().describe("Log info message"), + warn: external_exports.function().describe("Log warning message"), + error: external_exports.function().describe("Log error message") + }).passthrough().describe("Logger Interface"), + storage: external_exports.object({ + get: external_exports.function().describe("Get a value from storage"), + set: external_exports.function().describe("Set a value in storage"), + delete: external_exports.function().describe("Delete a value from storage") + }).passthrough().describe("Storage Interface"), + i18n: external_exports.object({ + t: external_exports.function().describe("Translate a key"), + getLocale: external_exports.function().describe("Get current locale") + }).passthrough().describe("Internationalization Interface"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()), + events: external_exports.record(external_exports.string(), external_exports.unknown()), + app: external_exports.object({ + router: external_exports.object({ + get: external_exports.function().describe("Register GET route handler"), + post: external_exports.function().describe("Register POST route handler"), + use: external_exports.function().describe("Register middleware") + }).passthrough() + }).passthrough().describe("App Framework Interface"), + drivers: external_exports.object({ + register: external_exports.function().describe("Register a driver") + }).passthrough().describe("Driver Registry") +}); +var UpgradeContextSchema = external_exports.object({ + /** Version before upgrade */ + previousVersion: external_exports.string().describe("Version before upgrade"), + /** Version after upgrade */ + newVersion: external_exports.string().describe("Version after upgrade"), + /** Whether this is a major version bump */ + isMajorUpgrade: external_exports.boolean().describe("Whether this is a major version bump"), + /** Metadata snapshot before upgrade (for migration logic) */ + previousMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Metadata snapshot before upgrade") +}).describe("Version migration context for onUpgrade hook"); +var PluginLifecycleSchema2 = external_exports.object({ + onInstall: external_exports.function().optional().describe("Called when plugin is installed"), + onEnable: external_exports.function().optional().describe("Called when plugin is enabled"), + onDisable: external_exports.function().optional().describe("Called when plugin is disabled"), + onUninstall: external_exports.function().optional().describe("Called when plugin is uninstalled"), + onUpgrade: external_exports.function().optional().describe("Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade") +}); +var CORE_PLUGIN_TYPES2 = [ + "ui", + // Frontend: Serves static assets/SPA (e.g. Console, Studio) + "driver", + // Connectivity: Database or Storage adapters (e.g. SQL, S3) + "server", + // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL) + "app", + // Business: Vertical Solution Bundle (Metadata + Logic) + "theme", + // Appearance: UI Overrides & CSS Variables + "agent", + // AI: Autonomous Agent & Tool Definitions + "objectql" + // Core: ObjectQL Engine Data Provider +]; +var PluginSchema = PluginLifecycleSchema2.extend({ + id: external_exports.string().min(1).optional().describe("Unique Plugin ID (e.g. com.example.crm)"), + type: external_exports.enum([ + "standard", + // Default: General purpose backend logic (Service, Hook, etc.) + ...CORE_PLUGIN_TYPES2 + ]).default("standard").optional().describe("Plugin Type categorization for runtime behavior"), + staticPath: external_exports.string().optional().describe('Absolute path to static assets (Required for type="ui-plugin")'), + slug: external_exports.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type="ui-plugin")'), + default: external_exports.boolean().optional().describe('Serve at root path (Only one "ui-plugin" can be default)'), + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic Version"), + description: external_exports.string().optional(), + author: external_exports.string().optional(), + homepage: external_exports.string().url().optional() +}); +var DatasetMode3 = external_exports.enum([ + "insert", + // Try to insert, fail on duplicate + "update", + // Only update found records, ignore new + "upsert", + // Create new or Update existing (Standard) + "replace", + // Delete ALL records in object then insert (Dangerous - use for cache tables) + "ignore" + // Try to insert, silently skip duplicates +]); +var DatasetSchema3 = external_exports.object({ + /** + * Target Object + * The machine name of the object to populate. + */ + object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target Object Name"), + /** + * Idempotency Key (The "Upsert" Key) + * The field used to check if a record already exists. + * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'. + * Standard: 'id' is rarely used for portable seed data — prefer natural keys. + */ + externalId: external_exports.string().default("name").describe("Field match for uniqueness check"), + /** + * Import Strategy + */ + mode: DatasetMode3.default("upsert").describe("Conflict resolution strategy"), + /** + * Environment Scope + * - 'all': Always load + * - 'dev': Only for development/demo + * - 'test': Only for CI/CD tests + */ + env: external_exports.array(external_exports.enum(["prod", "dev", "test"])).default(["prod", "dev", "test"]).describe("Applicable environments"), + /** + * The Payload + * Array of raw JSON objects matching the Object Schema. + */ + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Data records") +}); +var ManifestSchema2 = external_exports.object({ + /** + * Unique package identifier using reverse domain notation. + * Must be unique across the entire ecosystem. + * + * @example "com.steedos.crm" + * @example "org.apache.superset" + */ + id: external_exports.string().describe("Unique package identifier (reverse domain style)"), + /** + * Short namespace identifier for metadata scoping. + * Used as a prefix for objects and other metadata to prevent naming collisions + * across packages from different vendors. + * + * Rules: + * - 2-20 characters, lowercase letters, digits, and underscores only. + * - Must be unique within a running instance. + * - Platform-reserved namespaces (no prefix applied): "base", "system". + * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator). + * + * @example "crm" → objects become crm__account, crm__deal + * @example "todo" → objects become todo__task + * @example "base" → objects keep short name (platform reserved) + */ + namespace: external_exports.string().regex(/^[a-z][a-z0-9_]{1,19}$/, "Namespace must be 2-20 chars, lowercase alphanumeric + underscore").optional().describe('Short namespace identifier for metadata scoping (e.g. "crm", "todo")'), + /** + * Package version following semantic versioning (major.minor.patch). + * + * @example "1.0.0" + * @example "2.1.0-beta.1" + */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Package version (semantic versioning)"), + /** + * Type of the package in the ObjectStack ecosystem. + * - plugin: General-purpose functionality extension (Runtime: standard) + * - app: Business application package + * - driver: Connectivity adapter + * - server: Protocol gateway (Hono, GraphQL) + * - ui: Frontend package (Static/SPA) + * - theme: UI Theme + * - agent: AI Agent + * - module: Reusable code library/shared module + * - objectql: Core engine + * - adapter: Host adapter (Express, Fastify) + */ + type: external_exports.enum([ + "plugin", + ...CORE_PLUGIN_TYPES2, + "module", + "gateway", + // Deprecated: use 'server' + "adapter" + ]).describe("Type of package"), + /** + * Human-readable name of the package. + * Displayed in the UI for users. + * + * @example "Project Management" + */ + name: external_exports.string().describe("Human-readable package name"), + /** + * Brief description of the package functionality. + * Displayed in the marketplace and plugin manager. + */ + description: external_exports.string().optional().describe("Package description"), + /** + * Array of permission strings that the package requires. + * These form the "Scope" requested by the package at installation. + * + * @example ["system.user.read", "system.data.write"] + */ + permissions: external_exports.array(external_exports.string()).optional().describe("Array of required permission strings"), + /** + * Glob patterns specifying ObjectQL schemas files. + * Matches `*.object.yml` or `*.object.ts` files to load business objects. + * + * @example ["./src/objects/*.object.yml"] + */ + objects: external_exports.array(external_exports.string()).optional().describe("Glob patterns for ObjectQL schemas files"), + /** + * Defines system level DataSources. + * Matches `*.datasource.yml` files. + * + * @example ["./src/datasources/*.datasource.mongo.yml"] + */ + datasources: external_exports.array(external_exports.string()).optional().describe("Glob patterns for Datasource definitions"), + /** + * Package Dependencies. + * Map of package IDs to version requirements. + * + * @example { "@steedos/plugin-auth": "^2.0.0" } + */ + dependencies: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Package dependencies"), + /** + * Plugin Configuration Schema. + * Defines the settings this plugin exposes to the user via UI/ENV. + * Uses a simplified JSON Schema format. + * + * @example + * { + * "title": "Stripe Config", + * "properties": { + * "apiKey": { "type": "string", "secret": true }, + * "currency": { "type": "string", "default": "USD" } + * } + * } + */ + configuration: external_exports.object({ + title: external_exports.string().optional(), + properties: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["string", "number", "boolean", "array", "object"]).describe("Data type of the setting"), + default: external_exports.unknown().optional().describe("Default value"), + description: external_exports.string().optional().describe("Tooltip description"), + required: external_exports.boolean().optional().describe("Is this setting required?"), + secret: external_exports.boolean().optional().describe("If true, value is encrypted/masked (e.g. API Keys)"), + enum: external_exports.array(external_exports.string()).optional().describe("Allowed values for select inputs") + })).describe("Map of configuration keys to their definitions") + }).optional().describe("Plugin configuration settings"), + /** + * Contribution Points (VS Code Style). + * formalized way to extend the platform capabilities. + */ + contributes: external_exports.object({ + /** + * Register new Metadata Kinds (CRDs). + * Enables the system to parse and validate new file types. + * Example: Registering a BI plugin to handle *.report.ts + */ + kinds: external_exports.array(external_exports.object({ + id: external_exports.string().describe('The generic identifier of the kind (e.g., "sys.bi.report")'), + globs: external_exports.array(external_exports.string()).describe('File patterns to watch (e.g., ["**/*.report.ts"])'), + description: external_exports.string().optional().describe("Description of what this kind represents") + })).optional().describe("New Metadata Types to recognize"), + /** + * Register System Hooks. + * Declares that this plugin listens to specific system events. + */ + events: external_exports.array(external_exports.string()).optional().describe("Events this plugin listens to"), + /** + * Register UI Menus. + */ + menus: external_exports.record(external_exports.string(), external_exports.array(external_exports.object({ + id: external_exports.string(), + label: external_exports.string(), + command: external_exports.string().optional() + }))).optional().describe("UI Menu contributions"), + /** + * Register Custom Themes. + */ + themes: external_exports.array(external_exports.object({ + id: external_exports.string(), + label: external_exports.string(), + path: external_exports.string() + })).optional().describe("Theme contributions"), + /** + * Register Translations. + * Path to translation files (e.g. "locales/en.json"). + */ + translations: external_exports.array(external_exports.object({ + locale: external_exports.string(), + path: external_exports.string() + })).optional().describe("Translation resources"), + /** + * Register Server Actions. + * Invocable functions exposed to Flows or API. + */ + actions: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Unique action name"), + label: external_exports.string().optional(), + description: external_exports.string().optional(), + input: external_exports.unknown().optional().describe("Input validation schema"), + output: external_exports.unknown().optional().describe("Output schema") + })).optional().describe("Exposed server actions"), + /** + * Register Storage Drivers. + * Enables connecting to new types of datasources. + */ + drivers: external_exports.array(external_exports.object({ + id: external_exports.string().describe('Driver unique identifier (e.g. "postgres", "mongo")'), + label: external_exports.string().describe("Human readable name"), + description: external_exports.string().optional() + })).optional().describe("Driver contributions"), + /** + * Register Custom Field Types. + * Extends the data model with new widget types. + */ + fieldTypes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Unique field type name (e.g. "vector")'), + label: external_exports.string().describe("Display label"), + description: external_exports.string().optional() + })).optional().describe("Field Type contributions"), + /** + * Register Custom Query Operators/Functions. + * Extends ObjectQL with new functions (e.g. distance()). + */ + functions: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Function name (e.g. "distance")'), + description: external_exports.string().optional(), + args: external_exports.array(external_exports.string()).optional().describe("Argument types"), + returnType: external_exports.string().optional() + })).optional().describe("Query Function contributions"), + /** + * Register API Route Namespaces. + * Declares the API endpoints this plugin provides to the HttpDispatcher. + * The kernel routes matching prefixes to this plugin's handler. + * + * @example + * routes: [ + * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] } + * ] + */ + routes: external_exports.array(external_exports.object({ + /** URL path prefix (e.g. "/api/v1/ai") */ + prefix: external_exports.string().regex(/^\//).describe("API path prefix"), + /** Service name this plugin provides */ + service: external_exports.string().describe("Service name this plugin provides"), + /** Protocol method names implemented */ + methods: external_exports.array(external_exports.string()).optional().describe('Protocol method names implemented (e.g. ["aiNlq", "aiChat"])') + })).optional().describe("API route contributions to HttpDispatcher"), + /** + * Register CLI Commands. + * Allows plugins to extend the ObjectStack CLI with custom commands. + * Each command entry declares metadata; the actual Commander.js command + * is resolved at runtime by importing the plugin's module. + * + * The plugin package must export a `commands` array of Commander.js `Command` instances + * from its main entry point or from the path specified in `module`. + * + * @example + * ```yaml + * commands: + * - name: marketplace + * description: "Manage marketplace apps" + * module: "./cli" # optional, defaults to package main + * - name: deploy + * description: "Deploy to cloud" + * ``` + */ + commands: external_exports.array(external_exports.object({ + /** CLI command name (e.g., "marketplace", "deploy"). Must be a valid CLI identifier. */ + name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), + /** Brief description shown in `os --help` */ + description: external_exports.string().optional().describe("Command description for help text"), + /** + * Optional module path (relative to package root) that exports the Commander.js commands. + * If omitted, the CLI will import from the package's main entry point. + * The module must export a `commands` array of Commander.js `Command` instances, + * or a single `Command` instance as default export. + */ + module: external_exports.string().optional().describe("Module path exporting Commander.js commands") + })).optional().describe("CLI command contributions") + }).optional().describe("Platform contributions"), + /** + * Initial data seeding configuration. + * Defines default records to be inserted when the package is installed. + * + * Uses the standard DatasetSchema which supports idempotent upsert via + * `externalId`, environment scoping via `env`, and multiple conflict + * resolution modes. + * + * @deprecated Prefer using the top-level `data` field on the Stack Definition + * (defineStack({ data: [...] })) for better visibility and metadata registration. + * This field is retained for backward compatibility with manifest-only packages. + */ + data: external_exports.array(DatasetSchema3).optional().describe("Initial seed data (prefer top-level data field)"), + /** + * Plugin Capability Manifest. + * Declares protocols implemented, interfaces provided, dependencies, and extension points. + * This enables plugin interoperability and automatic discovery. + */ + capabilities: PluginCapabilityManifestSchema2.optional().describe("Plugin capability declarations for interoperability"), + /** + * Extension points contributed by this package. + * Allows packages to extend UI components, add functionality, etc. + */ + extensions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Extension points and contributions"), + /** + * Plugin Loading Configuration. + * Configures how the plugin is loaded, initialized, and managed at runtime. + * Includes strategies for lazy loading, code splitting, caching, and hot reload. + */ + loading: PluginLoadingConfigSchema2.optional().describe("Plugin loading and runtime behavior configuration"), + /** + * Platform Compatibility Requirements. + * Specifies the minimum ObjectStack platform version required to run this package. + * Used at install time to prevent incompatible packages from being installed. + * + * @example + * ```yaml + * engine: + * objectstack: ">=3.0.0" + * ``` + */ + engine: external_exports.object({ + /** ObjectStack platform version requirement (SemVer range) */ + objectstack: external_exports.string().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe('ObjectStack platform version requirement (SemVer range, e.g. ">=3.0.0")') + }).optional().describe("Platform compatibility requirements") +}); +var CustomizationOriginSchema = external_exports.enum([ + "package", + // Delivered by a plugin package (system layer, read-only) + "admin", + // Created/modified by platform admin via UI + "user", + // Created/modified by end user via UI + "migration", + // Created during data migration + "api" + // Created via API +]); +var FieldChangeSchema2 = external_exports.object({ + /** JSON path to the changed field (e.g. "fields.status.label") */ + path: external_exports.string().describe("JSON path to the changed field"), + /** Original value from the package (for diff/rollback) */ + originalValue: external_exports.unknown().optional().describe("Original value from the package"), + /** Current customized value */ + currentValue: external_exports.unknown().describe("Current customized value"), + /** Who made this change */ + changedBy: external_exports.string().optional().describe("User or admin who made this change"), + /** When this change was made */ + changedAt: external_exports.string().datetime().optional().describe("Timestamp of the change") +}); +var MetadataOverlaySchema2 = external_exports.object({ + /** Primary key */ + id: external_exports.string().describe("Overlay record ID (UUID)"), + /** The metadata type being customized (e.g. "object", "view", "flow") */ + baseType: external_exports.string().describe("Metadata type being customized"), + /** The metadata name being customized (e.g. "crm__account") */ + baseName: external_exports.string().describe("Metadata name being customized"), + /** Package that owns the base metadata (null for platform-created metadata) */ + packageId: external_exports.string().optional().describe("Package ID that delivered the base metadata"), + /** Package version when the customization was made (for upgrade diffing) */ + packageVersion: external_exports.string().optional().describe("Package version when overlay was created"), + /** Customization scope */ + scope: external_exports.enum(["platform", "user"]).default("platform").describe("Customization scope (platform=admin, user=personal)"), + /** Tenant ID for multi-tenant isolation */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** Owner user ID (for user-scope overlays) */ + owner: external_exports.string().optional().describe("Owner user ID for user-scope overlays"), + /** + * The overlay payload. + * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396). + * - To modify a field: include the field with its new value + * - To delete a field: set its value to null + * - Omitted fields remain unchanged from base + */ + patch: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Merge Patch payload (changed fields only)"), + /** + * Detailed change tracking for each modified field. + * Enables field-level conflict detection during upgrades. + */ + changes: external_exports.array(FieldChangeSchema2).optional().describe("Field-level change tracking for conflict detection"), + /** Whether this overlay is currently active */ + active: external_exports.boolean().default(true).describe("Whether this overlay is active"), + /** Audit timestamps */ + createdAt: external_exports.string().datetime().optional(), + createdBy: external_exports.string().optional(), + updatedAt: external_exports.string().datetime().optional(), + updatedBy: external_exports.string().optional() +}); +var MergeConflictSchema2 = external_exports.object({ + /** JSON path to the conflicting field */ + path: external_exports.string().describe("JSON path to the conflicting field"), + /** Value in the old package version */ + baseValue: external_exports.unknown().describe("Value in the old package version"), + /** Value in the new package version */ + incomingValue: external_exports.unknown().describe("Value in the new package version"), + /** Customer's customized value */ + customValue: external_exports.unknown().describe("Customer customized value"), + /** Suggested resolution strategy */ + suggestedResolution: external_exports.enum([ + "keep-custom", + // Keep customer's customization + "accept-incoming", + // Accept package update + "manual" + // Requires manual resolution + ]).describe("Suggested resolution strategy"), + /** Reason for the suggested resolution */ + reason: external_exports.string().optional().describe("Explanation for the suggested resolution") +}); +var MergeStrategyConfigSchema2 = external_exports.object({ + /** Default strategy when no field-level rule matches */ + defaultStrategy: external_exports.enum([ + "keep-custom", + // Preserve all customer customizations (safe) + "accept-incoming", + // Accept all package updates (overwrite) + "three-way-merge" + // Intelligent 3-way merge with conflict detection + ]).default("three-way-merge").describe("Default merge strategy"), + /** + * Field paths that should always accept incoming package updates. + * Use for fields that the package vendor considers "owned" and should not be customized. + * @example ["fields.*.type", "triggers.*"] + */ + alwaysAcceptIncoming: external_exports.array(external_exports.string()).optional().describe("Field paths that always accept package updates"), + /** + * Field paths where customer customizations always win. + * Use for UI-facing fields like labels, descriptions, help text. + * @example ["fields.*.label", "fields.*.helpText", "description"] + */ + alwaysKeepCustom: external_exports.array(external_exports.string()).optional().describe("Field paths where customer customizations always win"), + /** Whether to automatically resolve non-conflicting changes */ + autoResolveNonConflicting: external_exports.boolean().default(true).describe("Auto-resolve changes that do not conflict") +}); +var MergeResultSchema = external_exports.object({ + /** Whether the merge completed successfully (no unresolved conflicts) */ + success: external_exports.boolean().describe("Whether merge completed without unresolved conflicts"), + /** The merged metadata payload */ + mergedMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Merged metadata result"), + /** Updated overlay with remaining customizations */ + updatedOverlay: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated overlay after merge"), + /** List of conflicts that require manual resolution */ + conflicts: external_exports.array(MergeConflictSchema2).optional().describe("Unresolved merge conflicts"), + /** Summary of automatically resolved changes */ + autoResolved: external_exports.array(external_exports.object({ + path: external_exports.string(), + resolution: external_exports.string(), + description: external_exports.string().optional() + })).optional().describe("Summary of auto-resolved changes"), + /** Statistics */ + stats: external_exports.object({ + totalFields: external_exports.number().int().min(0).describe("Total fields evaluated"), + unchanged: external_exports.number().int().min(0).describe("Fields with no changes"), + autoResolved: external_exports.number().int().min(0).describe("Fields auto-resolved"), + conflicts: external_exports.number().int().min(0).describe("Fields with conflicts") + }).optional() +}); +var CustomizationPolicySchema2 = external_exports.object({ + /** Metadata type this policy applies to */ + metadataType: external_exports.string().describe('Metadata type (e.g. "object", "view")'), + /** Whether customization is allowed at all for this type */ + allowCustomization: external_exports.boolean().default(true), + /** + * Field paths that are locked (cannot be customized). + * @example ["name", "type", "fields.*.type"] + */ + lockedFields: external_exports.array(external_exports.string()).optional().describe("Field paths that cannot be customized"), + /** + * Field paths that are customizable. + * If specified, only these fields can be customized (whitelist mode). + * @example ["label", "description", "fields.*.label", "fields.*.helpText"] + */ + customizableFields: external_exports.array(external_exports.string()).optional().describe("Field paths that can be customized (whitelist)"), + /** + * Whether users can add new fields to package objects. + * When true, admins can extend package objects with custom fields. + */ + allowAddFields: external_exports.boolean().default(true).describe("Whether admins can add new fields to package objects"), + /** + * Whether users can delete package-delivered fields. + * Typically false — fields can only be hidden, not deleted. + */ + allowDeleteFields: external_exports.boolean().default(false).describe("Whether admins can delete package-delivered fields") +}); +var MetadataFormatSchema4 = external_exports.enum(["json", "yaml", "typescript", "javascript"]); +var MetadataStatsSchema3 = external_exports.object({ + /** + * Size of the metadata file in bytes + */ + size: external_exports.number().int().min(0).describe("File size in bytes"), + /** + * Last modification timestamp + */ + modifiedAt: external_exports.string().datetime().describe("Last modified date"), + /** + * ETag for cache validation + * Used for conditional requests (If-None-Match header) + */ + etag: external_exports.string().describe("Entity tag for cache validation"), + /** + * Serialization format + */ + format: MetadataFormatSchema4.describe("Serialization format"), + /** + * Full file path (if applicable) + */ + path: external_exports.string().optional().describe("File system path"), + /** + * Additional metadata provider-specific properties + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific metadata") +}); +var MetadataLoadOptionsSchema2 = external_exports.object({ + /** + * Glob patterns to match files + * Example: ["**\/*.object.ts", "**\/*.object.json"] + */ + patterns: external_exports.array(external_exports.string()).optional().describe("File glob patterns"), + /** + * If-None-Match header for conditional loading + * Only load if ETag doesn't match + */ + ifNoneMatch: external_exports.string().optional().describe("ETag for conditional request"), + /** + * If-Modified-Since header for conditional loading + */ + ifModifiedSince: external_exports.string().datetime().optional().describe("Only load if modified after this date"), + /** + * Whether to validate against Zod schema + */ + validate: external_exports.boolean().default(true).describe("Validate against schema"), + /** + * Whether to use cache if available + */ + useCache: external_exports.boolean().default(true).describe("Enable caching"), + /** + * Filter function (serialized as string) + * Example: "(item) => item.name.startsWith('sys_')" + */ + filter: external_exports.string().optional().describe("Filter predicate as string"), + /** + * Maximum number of items to load + */ + limit: external_exports.number().int().min(1).optional().describe("Maximum items to load"), + /** + * Recursively search subdirectories + */ + recursive: external_exports.boolean().default(true).describe("Search subdirectories") +}); +var MetadataSaveOptionsSchema2 = external_exports.object({ + /** + * Serialization format + */ + format: MetadataFormatSchema4.default("typescript").describe("Output format"), + /** + * Prettify output (formatted with indentation) + */ + prettify: external_exports.boolean().default(true).describe("Format with indentation"), + /** + * Indentation size (spaces) + */ + indent: external_exports.number().int().min(0).max(8).default(2).describe("Indentation spaces"), + /** + * Sort object keys alphabetically + */ + sortKeys: external_exports.boolean().default(false).describe("Sort object keys"), + /** + * Include default values in output + */ + includeDefaults: external_exports.boolean().default(false).describe("Include default values"), + /** + * Create backup before overwriting + */ + backup: external_exports.boolean().default(false).describe("Create backup file"), + /** + * Overwrite if exists + */ + overwrite: external_exports.boolean().default(true).describe("Overwrite existing file"), + /** + * Atomic write (write to temp file, then rename) + */ + atomic: external_exports.boolean().default(true).describe("Use atomic write operation"), + /** + * Custom file path (overrides default location) + */ + path: external_exports.string().optional().describe("Custom output path") +}); +var MetadataExportOptionsSchema2 = external_exports.object({ + /** + * Output file path + */ + output: external_exports.string().describe("Output file path"), + /** + * Export format + */ + format: MetadataFormatSchema4.default("json").describe("Export format"), + /** + * Filter predicate as string + */ + filter: external_exports.string().optional().describe("Filter items to export"), + /** + * Include statistics in export + */ + includeStats: external_exports.boolean().default(false).describe("Include metadata statistics"), + /** + * Compress output + */ + compress: external_exports.boolean().default(false).describe("Compress output (gzip)"), + /** + * Pretty print output + */ + prettify: external_exports.boolean().default(true).describe("Pretty print output") +}); +var MetadataImportOptionsSchema2 = external_exports.object({ + /** + * Conflict resolution strategy + */ + conflictResolution: external_exports.enum(["skip", "overwrite", "merge", "fail"]).default("merge").describe("How to handle existing items"), + /** + * Validate items against schema + */ + validate: external_exports.boolean().default(true).describe("Validate before import"), + /** + * Dry run (don't actually save) + */ + dryRun: external_exports.boolean().default(false).describe("Simulate import without saving"), + /** + * Continue on errors + */ + continueOnError: external_exports.boolean().default(false).describe("Continue if validation fails"), + /** + * Transform function (as string) + * Example: "(item) => ({ ...item, imported: true })" + */ + transform: external_exports.string().optional().describe("Transform items before import") +}); +var MetadataLoadResultSchema2 = external_exports.object({ + /** + * Loaded data + */ + data: external_exports.unknown().nullable().describe("Loaded metadata"), + /** + * Whether data came from cache (304 Not Modified) + */ + fromCache: external_exports.boolean().default(false).describe("Loaded from cache"), + /** + * Not modified (conditional request matched) + */ + notModified: external_exports.boolean().default(false).describe("Not modified since last request"), + /** + * ETag of loaded data + */ + etag: external_exports.string().optional().describe("Entity tag"), + /** + * Statistics about loaded data + */ + stats: MetadataStatsSchema3.optional().describe("Metadata statistics"), + /** + * Load time in milliseconds + */ + loadTime: external_exports.number().min(0).optional().describe("Load duration in ms") +}); +var MetadataSaveResultSchema2 = external_exports.object({ + /** + * Whether save was successful + */ + success: external_exports.boolean().describe("Save successful"), + /** + * Path where file was saved + */ + path: external_exports.string().describe("Output path"), + /** + * Generated ETag + */ + etag: external_exports.string().optional().describe("Generated entity tag"), + /** + * File size in bytes + */ + size: external_exports.number().int().min(0).optional().describe("File size"), + /** + * Save time in milliseconds + */ + saveTime: external_exports.number().min(0).optional().describe("Save duration in ms"), + /** + * Backup path (if created) + */ + backupPath: external_exports.string().optional().describe("Backup file path") +}); +var MetadataWatchEventSchema2 = external_exports.object({ + /** + * Event type + */ + type: external_exports.enum(["added", "changed", "deleted"]).describe("Event type"), + /** + * Metadata type (e.g., 'object', 'view', 'app') + */ + metadataType: external_exports.string().describe("Type of metadata"), + /** + * Item name/identifier + */ + name: external_exports.string().describe("Item identifier"), + /** + * Full file path + */ + path: external_exports.string().describe("File path"), + /** + * Loaded item data (for added/changed events) + */ + data: external_exports.unknown().optional().describe("Item data"), + /** + * Timestamp + */ + timestamp: external_exports.string().datetime().describe("Event timestamp") +}); +var MetadataCollectionInfoSchema2 = external_exports.object({ + /** + * Collection type (e.g., 'object', 'view', 'app') + */ + type: external_exports.string().describe("Collection type"), + /** + * Total items in collection + */ + count: external_exports.number().int().min(0).describe("Number of items"), + /** + * Formats found in collection + */ + formats: external_exports.array(MetadataFormatSchema4).describe("Formats in collection"), + /** + * Total size in bytes + */ + totalSize: external_exports.number().int().min(0).optional().describe("Total size in bytes"), + /** + * Last modified timestamp + */ + lastModified: external_exports.string().datetime().optional().describe("Last modification date"), + /** + * Collection location (path or URL) + */ + location: external_exports.string().optional().describe("Collection location") +}); +var MetadataLoaderContractSchema2 = external_exports.object({ + /** + * Loader name/identifier + */ + name: external_exports.string().describe("Loader identifier"), + /** + * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:') + */ + protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Protocol identifier"), + /** + * Detailed capabilities + */ + capabilities: external_exports.object({ + read: external_exports.boolean().default(true), + write: external_exports.boolean().default(false), + watch: external_exports.boolean().default(false), + list: external_exports.boolean().default(true) + }).describe("Loader capabilities"), + /** + * Supported formats + */ + supportedFormats: external_exports.array(MetadataFormatSchema4).describe("Supported formats"), + /** + * Whether loader supports watching for changes + */ + supportsWatch: external_exports.boolean().default(false).describe("Supports file watching"), + /** + * Whether loader supports saving + */ + supportsWrite: external_exports.boolean().default(true).describe("Supports write operations"), + /** + * Whether loader supports caching + */ + supportsCache: external_exports.boolean().default(true).describe("Supports caching") +}); +var MetadataFallbackStrategySchema3 = external_exports.enum([ + "filesystem", + // Fall back to filesystem-based loading + "memory", + // Fall back to in-memory storage + "none" + // No fallback — fail immediately +]); +var MetadataManagerConfigSchema3 = external_exports.object({ + /** + * Datasource Name Reference + * References a DatasourceSchema.name (e.g. 'default'). + * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. + */ + datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), + /** + * Metadata Table Name + * The database table used for metadata storage when datasource is configured. + */ + tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), + /** + * Fallback Strategy + * Determines behavior when the primary datasource is unavailable. + */ + fallback: MetadataFallbackStrategySchema3.default("none").describe("Fallback strategy when datasource is unavailable"), + /** + * Root directory for metadata (for filesystem loaders) + */ + rootDir: external_exports.string().optional().describe("Root directory path"), + /** + * Enabled serialization formats + */ + formats: external_exports.array(MetadataFormatSchema4).default(["typescript", "json", "yaml"]).describe("Enabled formats"), + /** + * Cache configuration + */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable caching"), + ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), + maxSize: external_exports.number().int().min(0).optional().describe("Max cache size in bytes") + }).optional().describe("Cache settings"), + /** + * Watch for file changes + */ + watch: external_exports.boolean().default(false).describe("Enable file watching"), + /** + * Watch options + */ + watchOptions: external_exports.object({ + ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), + persistent: external_exports.boolean().default(true).describe("Keep process running"), + ignoreInitial: external_exports.boolean().default(true).describe("Ignore initial add events") + }).optional().describe("File watcher options"), + /** + * Validation settings + */ + validation: external_exports.object({ + strict: external_exports.boolean().default(true).describe("Strict validation"), + throwOnError: external_exports.boolean().default(true).describe("Throw on validation error") + }).optional().describe("Validation settings"), + /** + * Loader-specific options + */ + loaderOptions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Loader-specific configuration") +}); +var MetadataTypeSchema2 = external_exports.enum([ + // Data Protocol + "object", + // Business entity definition (ObjectSchema) + "field", + // Standalone field definition (FieldSchema) + "trigger", + // Data-layer event triggers (TriggerSchema) + "validation", + // Validation rules (ValidationSchema) + "hook", + // Data hooks (HookSchema) + // UI Protocol + "view", + // List/form views (ViewSchema) + "page", + // Standalone pages (PageSchema) + "dashboard", + // Dashboard layouts (DashboardSchema) + "app", + // Application shell (AppSchema) + "action", + // UI/Server actions (ActionSchema) + "report", + // Report definitions (ReportSchema) + // Automation Protocol + "flow", + // Visual logic flows (FlowSchema) + "workflow", + // State machines (WorkflowSchema) + "approval", + // Approval processes (ApprovalSchema) + // System Protocol + "datasource", + // Data connections (DatasourceSchema) + "translation", + // i18n resources (TranslationSchema) + "router", + // API routes + "function", + // Serverless functions + "service", + // Service definitions + // Security Protocol + "permission", + // Permission sets (PermissionSetSchema) + "profile", + // User profiles (ProfileSchema) + "role", + // Security roles + // AI Protocol + "agent", + // AI agent definitions (AgentSchema) + "tool", + // AI tool definitions (ToolSchema) + "skill" + // AI skill definitions (SkillSchema) +]); +var MetadataTypeRegistryEntrySchema2 = external_exports.object({ + /** Metadata type identifier (e.g., 'object', 'view') */ + type: MetadataTypeSchema2.describe("Metadata type identifier"), + /** Human-readable label */ + label: external_exports.string().describe("Display label for the metadata type"), + /** Brief description */ + description: external_exports.string().optional().describe("Description of the metadata type"), + /** + * File glob patterns for this type. + * Used to discover metadata files on disk. + * @example ["**\/*.object.ts", "**\/*.object.yml"] + */ + filePatterns: external_exports.array(external_exports.string()).describe("Glob patterns to discover files of this type"), + /** + * Whether this type supports the customization overlay system. + * When true, platform/user overlays can be applied on top of package-delivered metadata. + */ + supportsOverlay: external_exports.boolean().default(true).describe("Whether overlay customization is supported"), + /** + * Whether metadata of this type can be created at runtime via API. + * Some types (e.g., 'object') may be restricted to deployment-only. + */ + allowRuntimeCreate: external_exports.boolean().default(true).describe("Allow runtime creation via API"), + /** + * Whether this type supports versioning. + * When true, changes are tracked with version history. + */ + supportsVersioning: external_exports.boolean().default(false).describe("Whether version history is tracked"), + /** + * Priority order for loading (lower = earlier). + * Objects load before views, views before dashboards. + */ + loadOrder: external_exports.number().int().min(0).default(100).describe("Loading priority (lower = earlier)"), + /** The domain this type belongs to */ + domain: external_exports.enum(["data", "ui", "automation", "system", "security", "ai"]).describe("Protocol domain") +}); +var MetadataQuerySchema2 = external_exports.object({ + /** Filter by metadata type(s) */ + types: external_exports.array(MetadataTypeSchema2).optional().describe("Filter by metadata types"), + /** Filter by namespace(s) */ + namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), + /** Filter by package ID */ + packageId: external_exports.string().optional().describe("Filter by owning package"), + /** Full-text search across name, label, description */ + search: external_exports.string().optional().describe("Full-text search query"), + /** Filter by scope */ + scope: external_exports.enum(["system", "platform", "user"]).optional().describe("Filter by scope"), + /** Filter by state */ + state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional().describe("Filter by lifecycle state"), + /** Filter by tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), + /** Sort field */ + sortBy: external_exports.enum(["name", "type", "updatedAt", "createdAt"]).default("name").describe("Sort field"), + /** Sort direction */ + sortOrder: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction"), + /** Pagination: page number (1-based) */ + page: external_exports.number().int().min(1).default(1).describe("Page number"), + /** Pagination: items per page */ + pageSize: external_exports.number().int().min(1).max(500).default(50).describe("Items per page") +}); +var MetadataQueryResultSchema2 = external_exports.object({ + /** Matched items */ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + namespace: external_exports.string().optional().describe("Namespace"), + label: external_exports.string().optional().describe("Display label"), + scope: external_exports.enum(["system", "platform", "user"]).optional(), + state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional(), + packageId: external_exports.string().optional(), + updatedAt: external_exports.string().datetime().optional() + })).describe("Matched metadata items"), + /** Total count (for pagination) */ + total: external_exports.number().int().min(0).describe("Total matching items"), + /** Current page */ + page: external_exports.number().int().min(1).describe("Current page"), + /** Page size */ + pageSize: external_exports.number().int().min(1).describe("Page size") +}); +var MetadataEventSchema2 = external_exports.object({ + /** Event type */ + event: external_exports.enum([ + "metadata.registered", + "metadata.updated", + "metadata.unregistered", + "metadata.validated", + "metadata.deployed", + "metadata.overlay.applied", + "metadata.overlay.removed", + "metadata.imported", + "metadata.exported" + ]).describe("Event type"), + /** Metadata type */ + metadataType: MetadataTypeSchema2.describe("Metadata type"), + /** Item name */ + name: external_exports.string().describe("Metadata item name"), + /** Namespace */ + namespace: external_exports.string().optional().describe("Namespace"), + /** Package ID (if package-managed) */ + packageId: external_exports.string().optional().describe("Owning package ID"), + /** Timestamp */ + timestamp: external_exports.string().datetime().describe("Event timestamp"), + /** Actor who caused the event */ + actor: external_exports.string().optional().describe("User or system that triggered the event"), + /** Additional event-specific payload */ + payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific payload") +}); +var MetadataValidationResultSchema2 = external_exports.object({ + /** Whether validation passed */ + valid: external_exports.boolean().describe("Whether the metadata is valid"), + /** Validation errors */ + errors: external_exports.array(external_exports.object({ + path: external_exports.string().describe("JSON path to the invalid field"), + message: external_exports.string().describe("Error description"), + code: external_exports.string().optional().describe("Error code") + })).optional().describe("Validation errors"), + /** Validation warnings (non-blocking) */ + warnings: external_exports.array(external_exports.object({ + path: external_exports.string().describe("JSON path to the field"), + message: external_exports.string().describe("Warning description") + })).optional().describe("Validation warnings") +}); +var MetadataPluginConfigSchema2 = external_exports.object({ + /** + * Storage configuration. + * References MetadataManagerConfigSchema for the underlying storage backend. + */ + storage: MetadataManagerConfigSchema3.describe("Storage backend configuration"), + /** + * Default customization policies per metadata type. + * Controls what parts of metadata can be customized by admins/users. + */ + customizationPolicies: external_exports.array(CustomizationPolicySchema2).optional().describe("Default customization policies per type"), + /** + * Merge strategy for package upgrades. + */ + mergeStrategy: MergeStrategyConfigSchema2.optional().describe("Merge strategy for package upgrades"), + /** + * Additional metadata type registrations. + * Used by plugins to register custom metadata types beyond the built-in set. + */ + additionalTypes: external_exports.array(MetadataTypeRegistryEntrySchema2.omit({ type: true }).extend({ + type: external_exports.string().describe("Custom metadata type identifier") + })).optional().describe("Additional custom metadata types"), + /** + * Enable metadata change events. + * When true, the plugin emits events on every metadata change. + */ + enableEvents: external_exports.boolean().default(true).describe("Emit metadata change events"), + /** + * Enable metadata validation on write operations. + * When true, all metadata is validated against its type schema before saving. + */ + validateOnWrite: external_exports.boolean().default(true).describe("Validate metadata on write"), + /** + * Enable metadata versioning. + * When true, changes to metadata are tracked with version history. + */ + enableVersioning: external_exports.boolean().default(false).describe("Track metadata version history"), + /** + * Maximum number of metadata items to keep in memory cache. + */ + cacheMaxItems: external_exports.number().int().min(0).default(1e4).describe("Max items in memory cache") +}); +var MetadataPluginManifestSchema = external_exports.object({ + /** Plugin identifier */ + id: external_exports.literal("com.objectstack.metadata").describe("Metadata plugin ID"), + /** Plugin name */ + name: external_exports.literal("ObjectStack Metadata Service").describe("Plugin name"), + /** Plugin version */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Plugin version"), + /** Plugin type */ + type: external_exports.literal("standard").describe("Plugin type"), + /** Plugin description */ + description: external_exports.string().default("Core metadata management service for ObjectStack platform").describe("Plugin description"), + /** + * Capabilities this plugin provides. + * The kernel uses this to route metadata requests to this plugin. + */ + capabilities: external_exports.object({ + /** Supports CRUD operations on metadata */ + crud: external_exports.boolean().default(true).describe("Supports metadata CRUD"), + /** Supports metadata query/search */ + query: external_exports.boolean().default(true).describe("Supports metadata query"), + /** Supports the overlay/customization system */ + overlay: external_exports.boolean().default(true).describe("Supports customization overlays"), + /** Supports file watching for hot reload */ + watch: external_exports.boolean().default(false).describe("Supports file watching"), + /** Supports bulk import/export */ + importExport: external_exports.boolean().default(true).describe("Supports import/export"), + /** Supports metadata validation */ + validation: external_exports.boolean().default(true).describe("Supports schema validation"), + /** Supports metadata versioning */ + versioning: external_exports.boolean().default(false).describe("Supports version history"), + /** Supports metadata events */ + events: external_exports.boolean().default(true).describe("Emits metadata events") + }).describe("Plugin capabilities"), + /** Plugin configuration */ + config: MetadataPluginConfigSchema2.optional().describe("Plugin configuration") +}); +var MetadataBulkRegisterRequestSchema = external_exports.object({ + /** Items to register */ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), + namespace: external_exports.string().optional().describe("Namespace") + })).min(1).describe("Items to register"), + /** Continue on individual item failure */ + continueOnError: external_exports.boolean().default(false).describe("Continue if individual item fails"), + /** Validate items before registering */ + validate: external_exports.boolean().default(true).describe("Validate before register") +}); +var MetadataBulkResultSchema2 = external_exports.object({ + /** Total items processed */ + total: external_exports.number().int().min(0).describe("Total items processed"), + /** Successfully processed items */ + succeeded: external_exports.number().int().min(0).describe("Successfully processed"), + /** Failed items */ + failed: external_exports.number().int().min(0).describe("Failed items"), + /** Per-item error details */ + errors: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + error: external_exports.string().describe("Error message") + })).optional().describe("Per-item errors") +}); +var MetadataDependencySchema2 = external_exports.object({ + /** Source metadata type */ + sourceType: external_exports.string().describe("Dependent metadata type"), + /** Source metadata name */ + sourceName: external_exports.string().describe("Dependent metadata name"), + /** Target metadata type */ + targetType: external_exports.string().describe("Referenced metadata type"), + /** Target metadata name */ + targetName: external_exports.string().describe("Referenced metadata name"), + /** Dependency kind */ + kind: external_exports.enum(["reference", "extends", "includes", "triggers"]).describe("How the dependency is formed") +}); +var PackageStatusEnum2 = external_exports.enum([ + "installed", + // Successfully installed and enabled + "disabled", + // Installed but disabled (metadata not active) + "installing", + // Installation in progress + "upgrading", + // Upgrade in progress + "uninstalling", + // Removal in progress + "error" + // Installation or runtime error +]).describe("Package installation status"); +var InstalledPackageSchema2 = external_exports.object({ + /** + * The full package manifest (source of truth for package definition). + */ + manifest: ManifestSchema2.describe("Full package manifest"), + /** + * Current lifecycle status. + */ + status: PackageStatusEnum2.default("installed").describe("Package state: installed, disabled, installing, upgrading, uninstalling, or error"), + /** + * Whether the package is currently enabled (active). + * When disabled, the package's metadata is not loaded into the registry. + */ + enabled: external_exports.boolean().default(true).describe("Whether the package is currently enabled"), + /** + * ISO 8601 timestamp of when the package was installed. + */ + installedAt: external_exports.string().datetime().optional().describe("Installation timestamp"), + /** + * ISO 8601 timestamp of last update. + */ + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + /** + * The currently installed version string. + * Mirrors manifest.version for quick access without parsing the full manifest. + */ + installedVersion: external_exports.string().optional().describe("Currently installed version for quick access"), + /** + * The previously installed version (before last upgrade). + * Useful for rollback and upgrade tracking. + */ + previousVersion: external_exports.string().optional().describe("Version before the last upgrade"), + /** + * ISO 8601 timestamp of when the package was last enabled/disabled. + */ + statusChangedAt: external_exports.string().datetime().optional().describe("Status change timestamp"), + /** + * Error message if status is 'error'. + */ + errorMessage: external_exports.string().optional().describe("Error message when status is error"), + /** + * Configuration values set by the user for this package. + * Keys correspond to the package's `configuration.properties`. + */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided configuration settings"), + /** + * Upgrade history for this package. + * Records each version migration with status and optional log. + */ + upgradeHistory: external_exports.array(external_exports.object({ + /** Previous version before upgrade */ + fromVersion: external_exports.string().describe("Version before upgrade"), + /** New version after upgrade */ + toVersion: external_exports.string().describe("Version after upgrade"), + /** Timestamp of the upgrade */ + upgradedAt: external_exports.string().datetime().describe("Upgrade timestamp"), + /** Outcome of the upgrade */ + status: external_exports.enum(["success", "failed", "rolled_back"]).describe("Upgrade outcome"), + /** Migration log entries */ + migrationLog: external_exports.array(external_exports.string()).optional().describe("Migration step logs") + })).optional().describe("Version upgrade history"), + /** + * Namespaces registered by this package. + * Tracks which namespace prefixes are occupied by this package. + */ + registeredNamespaces: external_exports.array(external_exports.string()).optional().describe("Namespace prefixes registered by this package") +}).describe("Installed package with runtime lifecycle state"); +var NamespaceRegistryEntrySchema = external_exports.object({ + /** Namespace prefix */ + namespace: external_exports.string().describe("Namespace prefix"), + /** Package that owns this namespace */ + packageId: external_exports.string().describe("Owning package ID"), + /** Registration timestamp */ + registeredAt: external_exports.string().datetime().describe("Registration timestamp"), + /** Namespace status */ + status: external_exports.enum(["active", "disabled", "reserved"]).describe("Namespace status") +}).describe("Namespace ownership entry in the registry"); +var NamespaceConflictErrorSchema = external_exports.object({ + /** Error type discriminator */ + type: external_exports.literal("namespace_conflict").describe("Error type"), + /** Namespace that was requested */ + requestedNamespace: external_exports.string().describe("Requested namespace"), + /** ID of the package that already owns the namespace */ + conflictingPackageId: external_exports.string().describe("Conflicting package ID"), + /** Name of the conflicting package */ + conflictingPackageName: external_exports.string().describe("Conflicting package display name"), + /** Suggested alternative namespace */ + suggestion: external_exports.string().optional().describe("Suggested alternative namespace") +}).describe("Namespace collision error during installation"); +var ListPackagesRequestSchema2 = external_exports.object({ + /** Filter by status */ + status: PackageStatusEnum2.optional().describe("Filter by package status"), + /** Filter by package type */ + type: ManifestSchema2.shape.type.optional().describe("Filter by package type"), + /** Filter by enabled state */ + enabled: external_exports.boolean().optional().describe("Filter by enabled state") +}).describe("List packages request"); +var ListPackagesResponseSchema2 = external_exports.object({ + packages: external_exports.array(InstalledPackageSchema2).describe("List of installed packages"), + total: external_exports.number().describe("Total package count") +}).describe("List packages response"); +var GetPackageRequestSchema2 = external_exports.object({ + /** Package ID (reverse domain identifier from manifest) */ + id: external_exports.string().describe("Package identifier") +}).describe("Get package request"); +var GetPackageResponseSchema2 = external_exports.object({ + package: InstalledPackageSchema2.describe("Package details") +}).describe("Get package response"); +var InstallPackageRequestSchema2 = external_exports.object({ + /** The package manifest to install */ + manifest: ManifestSchema2.describe("Package manifest to install"), + /** Optional: user-provided settings at install time */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), + /** Whether to enable immediately after install (default: true) */ + enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), + /** + * Current platform version for compatibility checking. + * When provided, the system compares this against the package's + * `engine.objectstack` requirement to verify compatibility. + */ + platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification") +}).describe("Install package request"); +var InstallPackageResponseSchema2 = external_exports.object({ + package: InstalledPackageSchema2.describe("Installed package details"), + message: external_exports.string().optional().describe("Installation status message"), + /** Dependency resolution result (when dependencies were analyzed) */ + dependencyResolution: DependencyResolutionResultSchema2.optional().describe("Dependency resolution result from install analysis") +}).describe("Install package response"); +var UninstallPackageRequestSchema2 = external_exports.object({ + /** Package ID to uninstall */ + id: external_exports.string().describe("Package ID to uninstall") +}).describe("Uninstall package request"); +var UninstallPackageResponseSchema2 = external_exports.object({ + id: external_exports.string().describe("Uninstalled package ID"), + success: external_exports.boolean().describe("Whether uninstall succeeded"), + message: external_exports.string().optional().describe("Uninstall status message") +}).describe("Uninstall package response"); +var EnablePackageRequestSchema2 = external_exports.object({ + /** Package ID to enable */ + id: external_exports.string().describe("Package ID to enable") +}).describe("Enable package request"); +var EnablePackageResponseSchema2 = external_exports.object({ + package: InstalledPackageSchema2.describe("Enabled package details"), + message: external_exports.string().optional().describe("Enable status message") +}).describe("Enable package response"); +var DisablePackageRequestSchema2 = external_exports.object({ + /** Package ID to disable */ + id: external_exports.string().describe("Package ID to disable") +}).describe("Disable package request"); +var DisablePackageResponseSchema2 = external_exports.object({ + package: InstalledPackageSchema2.describe("Disabled package details"), + message: external_exports.string().optional().describe("Disable status message") +}).describe("Disable package response"); +var MetadataChangeTypeSchema2 = external_exports.enum([ + "added", + // New metadata item added in new version + "modified", + // Existing metadata item modified + "removed", + // Metadata item removed in new version + "renamed" + // Metadata item renamed +]).describe("Type of metadata change between package versions"); +var MetadataDiffItemSchema2 = external_exports.object({ + /** Metadata type (e.g. "object", "view", "flow") */ + type: external_exports.string().describe("Metadata type"), + /** Metadata name */ + name: external_exports.string().describe("Metadata name"), + /** Type of change */ + changeType: MetadataChangeTypeSchema2.describe("Category of metadata modification (added, modified, removed, or renamed)"), + /** Whether this change has potential conflicts with customizations */ + hasConflict: external_exports.boolean().default(false).describe("Whether this change may conflict with customizations"), + /** Human-readable summary of the change */ + summary: external_exports.string().optional().describe("Human-readable change summary"), + /** Previous name (for renames) */ + previousName: external_exports.string().optional().describe("Previous name if renamed") +}).describe("Single metadata change between package versions"); +var UpgradeImpactLevelSchema2 = external_exports.enum([ + "none", + // No impact, seamless upgrade + "low", + // Minor changes, no user action needed + "medium", + // Some changes that may affect workflows + "high", + // Significant changes, user review recommended + "critical" + // Breaking changes, manual intervention required +]).describe("Severity of upgrade impact"); +var UpgradePlanSchema2 = external_exports.object({ + /** Package being upgraded */ + packageId: external_exports.string().describe("Package identifier"), + /** Current installed version */ + fromVersion: external_exports.string().describe("Currently installed version"), + /** Target version to upgrade to */ + toVersion: external_exports.string().describe("Target upgrade version"), + /** Overall impact level */ + impactLevel: UpgradeImpactLevelSchema2.describe("Severity assessment from none (seamless) to critical (breaking changes)"), + /** List of all metadata changes between versions */ + changes: external_exports.array(MetadataDiffItemSchema2).describe("All metadata changes"), + /** Number of customer customizations that may be affected */ + affectedCustomizations: external_exports.number().int().min(0).default(0).describe("Count of customizations that may be affected"), + /** Whether any migration scripts need to run */ + requiresMigration: external_exports.boolean().default(false).describe("Whether data migration scripts are needed"), + /** Migration script paths (relative to package root) */ + migrationScripts: external_exports.array(external_exports.string()).optional().describe("Paths to migration scripts"), + /** Dependencies that also need upgrading */ + dependencyUpgrades: external_exports.array(external_exports.object({ + packageId: external_exports.string(), + fromVersion: external_exports.string(), + toVersion: external_exports.string() + })).optional().describe("Dependent packages that also need upgrading"), + /** Estimated upgrade duration in seconds */ + estimatedDuration: external_exports.number().int().min(0).optional().describe("Estimated upgrade duration in seconds"), + /** Human-readable summary */ + summary: external_exports.string().optional().describe("Human-readable upgrade summary") +}).describe("Upgrade analysis plan generated before execution"); +var UpgradeSnapshotSchema = external_exports.object({ + /** Snapshot ID (UUID) */ + id: external_exports.string().describe("Snapshot identifier"), + /** Package being upgraded */ + packageId: external_exports.string().describe("Package identifier"), + /** Version being upgraded from */ + fromVersion: external_exports.string().describe("Version before upgrade"), + /** Version being upgraded to */ + toVersion: external_exports.string().describe("Target upgrade version"), + /** Tenant ID */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** Complete manifest of the old package version */ + previousManifest: ManifestSchema2.describe("Complete manifest of the previous package version"), + /** + * Snapshot of all metadata records owned by this package. + * Stored as array of { type, name, metadata } tuples. + */ + metadataSnapshot: external_exports.array(external_exports.object({ + type: external_exports.string(), + name: external_exports.string(), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()) + })).describe("Snapshot of all package metadata"), + /** + * Snapshot of all customer customizations (overlays) for this package's metadata. + */ + customizationSnapshot: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Snapshot of customer customizations"), + /** When the snapshot was created */ + createdAt: external_exports.string().datetime().describe("Snapshot creation timestamp"), + /** Expiry time for snapshot cleanup */ + expiresAt: external_exports.string().datetime().optional().describe("Snapshot expiry timestamp") +}).describe("Pre-upgrade state snapshot for rollback capability"); +var UpgradePackageRequestSchema = external_exports.object({ + /** Package ID to upgrade */ + packageId: external_exports.string().describe("Package ID to upgrade"), + /** Target version (if omitted, upgrades to latest) */ + targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), + /** New manifest for the target version */ + manifest: ManifestSchema2.optional().describe("New manifest (if installing from local)"), + /** Whether to create a pre-upgrade snapshot */ + createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), + /** Merge strategy for handling customizations */ + mergeStrategy: external_exports.enum([ + "keep-custom", + "accept-incoming", + "three-way-merge" + ]).default("three-way-merge").describe("How to handle customer customizations"), + /** Whether to run in dry-run mode (preview only, no changes) */ + dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), + /** Whether to skip pre-upgrade validation */ + skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") +}).describe("Upgrade package request"); +var UpgradePhaseSchema2 = external_exports.enum([ + "pending", + // Upgrade requested but not started + "analyzing", + // Generating upgrade plan + "snapshot", + // Creating pre-upgrade snapshot + "executing", + // Applying metadata changes + "migrating", + // Running migration scripts + "validating", + // Post-upgrade validation + "completed", + // Upgrade completed successfully + "failed", + // Upgrade failed + "rolling-back", + // Rollback in progress + "rolled-back" + // Rollback completed +]).describe("Current phase of the upgrade process"); +var UpgradePackageResponseSchema = external_exports.object({ + /** Whether the upgrade was successful */ + success: external_exports.boolean().describe("Whether the upgrade succeeded"), + /** Current upgrade phase */ + phase: UpgradePhaseSchema2.describe("Current upgrade phase"), + /** The upgrade plan that was executed */ + plan: UpgradePlanSchema2.optional().describe("Upgrade plan"), + /** Snapshot ID for rollback */ + snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), + /** Merge conflicts that need manual resolution (if any) */ + conflicts: external_exports.array(external_exports.object({ + path: external_exports.string(), + baseValue: external_exports.unknown(), + incomingValue: external_exports.unknown(), + customValue: external_exports.unknown() + })).optional().describe("Unresolved merge conflicts"), + /** Error message (if failed) */ + errorMessage: external_exports.string().optional().describe("Error message if upgrade failed"), + /** Human-readable summary */ + message: external_exports.string().optional().describe("Human-readable status message") +}).describe("Upgrade package response"); +var RollbackPackageRequestSchema = external_exports.object({ + /** Package ID to rollback */ + packageId: external_exports.string().describe("Package ID to rollback"), + /** Snapshot ID to restore from */ + snapshotId: external_exports.string().describe("Snapshot ID to restore from"), + /** Whether to also rollback customizations */ + rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") +}).describe("Rollback package request"); +var RollbackPackageResponseSchema = external_exports.object({ + /** Whether the rollback was successful */ + success: external_exports.boolean().describe("Whether the rollback succeeded"), + /** Restored version */ + restoredVersion: external_exports.string().optional().describe("Version restored to"), + /** Message */ + message: external_exports.string().optional().describe("Rollback status message") +}).describe("Rollback package response"); +var PluginHealthStatusSchema = external_exports.enum([ + "healthy", + // Plugin is operating normally + "degraded", + // Plugin is operational but with reduced functionality + "unhealthy", + // Plugin has critical issues but still running + "failed", + // Plugin has failed and is not operational + "recovering", + // Plugin is in recovery process + "unknown" + // Health status cannot be determined +]).describe("Current health status of the plugin"); +var PluginHealthCheckSchema = external_exports.object({ + /** + * Health check interval in milliseconds + */ + interval: external_exports.number().int().min(1e3).default(3e4).describe("How often to perform health checks (default: 30s)"), + /** + * Timeout for health check in milliseconds + */ + timeout: external_exports.number().int().min(100).default(5e3).describe("Maximum time to wait for health check response"), + /** + * Number of consecutive failures before marking as unhealthy + */ + failureThreshold: external_exports.number().int().min(1).default(3).describe("Consecutive failures needed to mark unhealthy"), + /** + * Number of consecutive successes to recover from unhealthy state + */ + successThreshold: external_exports.number().int().min(1).default(1).describe("Consecutive successes needed to mark healthy"), + /** + * Custom health check function name or endpoint + */ + checkMethod: external_exports.string().optional().describe("Method name to call for health check"), + /** + * Enable automatic restart on failure + */ + autoRestart: external_exports.boolean().default(false).describe("Automatically restart plugin on health check failure"), + /** + * Maximum number of restart attempts + */ + maxRestartAttempts: external_exports.number().int().min(0).default(3).describe("Maximum restart attempts before giving up"), + /** + * Backoff strategy for restarts + */ + restartBackoff: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy for restart delays") +}); +var PluginHealthReportSchema = external_exports.object({ + /** + * Overall health status + */ + status: PluginHealthStatusSchema, + /** + * Timestamp of the health check + */ + timestamp: external_exports.string().datetime(), + /** + * Human-readable message about health status + */ + message: external_exports.string().optional(), + /** + * Detailed metrics + */ + metrics: external_exports.object({ + uptime: external_exports.number().describe("Plugin uptime in milliseconds"), + memoryUsage: external_exports.number().optional().describe("Memory usage in bytes"), + cpuUsage: external_exports.number().optional().describe("CPU usage percentage"), + activeConnections: external_exports.number().optional().describe("Number of active connections"), + errorRate: external_exports.number().optional().describe("Error rate (errors per minute)"), + responseTime: external_exports.number().optional().describe("Average response time in ms") + }).partial().optional(), + /** + * List of checks performed + */ + checks: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Check name"), + status: external_exports.enum(["passed", "failed", "warning"]), + message: external_exports.string().optional(), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + })).optional(), + /** + * Dependencies health + */ + dependencies: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + status: PluginHealthStatusSchema, + message: external_exports.string().optional() + })).optional() +}); +var DistributedStateConfigSchema = external_exports.object({ + /** + * Distributed cache provider + */ + provider: external_exports.enum(["redis", "etcd", "custom"]).describe("Distributed state backend provider"), + /** + * Connection URL or endpoints + */ + endpoints: external_exports.array(external_exports.string()).optional().describe("Backend connection endpoints"), + /** + * Key prefix for namespacing + */ + keyPrefix: external_exports.string().optional().describe('Prefix for all keys (e.g., "plugin:my-plugin:")'), + /** + * Time to live in seconds + */ + ttl: external_exports.number().int().min(0).optional().describe("State expiration time in seconds"), + /** + * Authentication configuration + */ + auth: external_exports.object({ + username: external_exports.string().optional(), + password: external_exports.string().optional(), + token: external_exports.string().optional(), + certificate: external_exports.string().optional() + }).optional(), + /** + * Replication settings + */ + replication: external_exports.object({ + enabled: external_exports.boolean().default(true), + minReplicas: external_exports.number().int().min(1).default(1) + }).optional(), + /** + * Custom provider configuration + */ + customConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration") +}); +var HotReloadConfigSchema = external_exports.object({ + /** + * Enable hot reload capability + */ + enabled: external_exports.boolean().default(false), + /** + * Watch file patterns for auto-reload + */ + watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns to watch for changes"), + /** + * Debounce delay before reloading (milliseconds) + */ + debounceDelay: external_exports.number().int().min(0).default(1e3).describe("Wait time after change detection before reload"), + /** + * Preserve plugin state during reload + */ + preserveState: external_exports.boolean().default(true).describe("Keep plugin state across reloads"), + /** + * State serialization strategy + */ + stateStrategy: external_exports.enum(["memory", "disk", "distributed", "none"]).default("memory").describe("How to preserve state during reload"), + /** + * Distributed state configuration (required when stateStrategy is "distributed") + */ + distributedConfig: DistributedStateConfigSchema.optional().describe("Configuration for distributed state management"), + /** + * Graceful shutdown timeout + */ + shutdownTimeout: external_exports.number().int().min(0).default(3e4).describe("Maximum time to wait for graceful shutdown"), + /** + * Pre-reload hooks + */ + beforeReload: external_exports.array(external_exports.string()).optional().describe("Hook names to call before reload"), + /** + * Post-reload hooks + */ + afterReload: external_exports.array(external_exports.string()).optional().describe("Hook names to call after reload") +}); +var GracefulDegradationSchema = external_exports.object({ + /** + * Enable graceful degradation + */ + enabled: external_exports.boolean().default(true), + /** + * Fallback mode when dependencies fail + */ + fallbackMode: external_exports.enum([ + "minimal", + // Provide minimal functionality + "cached", + // Use cached data + "readonly", + // Allow read-only operations + "offline", + // Offline mode with local data + "disabled" + // Disable plugin functionality + ]).default("minimal"), + /** + * Critical dependencies that must be available + */ + criticalDependencies: external_exports.array(external_exports.string()).optional().describe("Plugin IDs that are required for operation"), + /** + * Optional dependencies that can fail + */ + optionalDependencies: external_exports.array(external_exports.string()).optional().describe("Plugin IDs that are nice to have but not required"), + /** + * Feature flags for degraded mode + */ + degradedFeatures: external_exports.array(external_exports.object({ + feature: external_exports.string().describe("Feature name"), + enabled: external_exports.boolean().describe("Whether feature is available in degraded mode"), + reason: external_exports.string().optional() + })).optional(), + /** + * Automatic recovery attempts + */ + autoRecovery: external_exports.object({ + enabled: external_exports.boolean().default(true), + retryInterval: external_exports.number().int().min(1e3).default(6e4).describe("Interval between recovery attempts (ms)"), + maxAttempts: external_exports.number().int().min(0).default(5).describe("Maximum recovery attempts before giving up") + }).optional() +}); +var PluginUpdateStrategySchema = external_exports.object({ + /** + * Update mode + */ + mode: external_exports.enum([ + "manual", + // Manual updates only + "automatic", + // Automatic updates + "scheduled", + // Scheduled update windows + "rolling" + // Rolling updates with zero downtime + ]).default("manual"), + /** + * Version constraints for automatic updates + */ + autoUpdateConstraints: external_exports.object({ + major: external_exports.boolean().default(false).describe("Allow major version updates"), + minor: external_exports.boolean().default(true).describe("Allow minor version updates"), + patch: external_exports.boolean().default(true).describe("Allow patch version updates") + }).optional(), + /** + * Update schedule (for scheduled mode) + */ + schedule: external_exports.object({ + /** + * Cron expression for update window + */ + cron: external_exports.string().optional(), + /** + * Timezone for schedule + */ + timezone: external_exports.string().default("UTC"), + /** + * Maintenance window duration in minutes + */ + maintenanceWindow: external_exports.number().int().min(1).default(60) + }).optional(), + /** + * Rollback configuration + */ + rollback: external_exports.object({ + enabled: external_exports.boolean().default(true), + /** + * Automatic rollback on failure + */ + automatic: external_exports.boolean().default(true), + /** + * Keep N previous versions for rollback + */ + keepVersions: external_exports.number().int().min(1).default(3), + /** + * Rollback timeout in milliseconds + */ + timeout: external_exports.number().int().min(1e3).default(3e4) + }).optional(), + /** + * Pre-update validation + */ + validation: external_exports.object({ + /** + * Run compatibility checks before update + */ + checkCompatibility: external_exports.boolean().default(true), + /** + * Run tests before applying update + */ + runTests: external_exports.boolean().default(false), + /** + * Test suite to run + */ + testSuite: external_exports.string().optional() + }).optional() +}); +var PluginStateSnapshotSchema = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Version at time of snapshot + */ + version: external_exports.string(), + /** + * Snapshot timestamp + */ + timestamp: external_exports.string().datetime(), + /** + * Serialized state data + */ + state: external_exports.record(external_exports.string(), external_exports.unknown()), + /** + * State metadata + */ + metadata: external_exports.object({ + checksum: external_exports.string().optional().describe("State checksum for verification"), + compressed: external_exports.boolean().default(false), + encryption: external_exports.string().optional().describe("Encryption algorithm if encrypted") + }).optional() +}); +var AdvancedPluginLifecycleConfigSchema = external_exports.object({ + /** + * Health monitoring configuration + */ + health: PluginHealthCheckSchema.optional(), + /** + * Hot reload configuration + */ + hotReload: HotReloadConfigSchema.optional(), + /** + * Graceful degradation configuration + */ + degradation: GracefulDegradationSchema.optional(), + /** + * Update strategy + */ + updates: PluginUpdateStrategySchema.optional(), + /** + * Resource limits + */ + resources: external_exports.object({ + maxMemory: external_exports.number().int().optional().describe("Maximum memory in bytes"), + maxCpu: external_exports.number().min(0).max(100).optional().describe("Maximum CPU percentage"), + maxConnections: external_exports.number().int().optional().describe("Maximum concurrent connections"), + timeout: external_exports.number().int().optional().describe("Operation timeout in milliseconds") + }).optional(), + /** + * Monitoring and observability + */ + observability: external_exports.object({ + enableMetrics: external_exports.boolean().default(true), + enableTracing: external_exports.boolean().default(true), + enableProfiling: external_exports.boolean().default(false), + metricsInterval: external_exports.number().int().min(1e3).default(6e4).describe("Metrics collection interval in ms") + }).optional() +}); +var EventPhaseSchema = external_exports.enum(["init", "start", "destroy"]).describe("Plugin lifecycle phase"); +var PluginEventBaseSchema = external_exports.object({ + /** + * Plugin name + */ + pluginName: external_exports.string().describe("Name of the plugin"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds when event occurred") +}); +var PluginRegisteredEventSchema = PluginEventBaseSchema.extend({ + /** + * Plugin version (optional) + */ + version: external_exports.string().optional().describe("Plugin version") +}); +var PluginLifecyclePhaseEventSchema = PluginEventBaseSchema.extend({ + /** + * Duration of the phase (milliseconds) + */ + duration: external_exports.number().min(0).optional().describe("Duration of the lifecycle phase in milliseconds"), + /** + * Lifecycle phase + */ + phase: EventPhaseSchema.optional().describe("Lifecycle phase") +}); +var PluginErrorEventSchema = PluginEventBaseSchema.extend({ + /** + * Error object + */ + error: external_exports.object({ + name: external_exports.string().describe("Error class name"), + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Stack trace"), + code: external_exports.string().optional().describe("Error code") + }).describe("Serializable error representation"), + /** + * Lifecycle phase where error occurred + */ + phase: EventPhaseSchema.describe("Lifecycle phase where error occurred"), + /** + * Error message (for serialization) + */ + errorMessage: external_exports.string().optional().describe("Error message"), + /** + * Error stack trace (for debugging) + */ + errorStack: external_exports.string().optional().describe("Error stack trace") +}); +var ServiceRegisteredEventSchema = external_exports.object({ + /** + * Service name + */ + serviceName: external_exports.string().describe("Name of the registered service"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), + /** + * Service type (optional) + */ + serviceType: external_exports.string().optional().describe("Type or interface name of the service") +}); +var ServiceUnregisteredEventSchema = external_exports.object({ + /** + * Service name + */ + serviceName: external_exports.string().describe("Name of the unregistered service"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds") +}); +var HookRegisteredEventSchema = external_exports.object({ + /** + * Hook name + */ + hookName: external_exports.string().describe("Name of the hook"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), + /** + * Number of handlers registered for this hook + */ + handlerCount: external_exports.number().int().min(0).describe("Number of handlers registered for this hook") +}); +var HookTriggeredEventSchema = external_exports.object({ + /** + * Hook name + */ + hookName: external_exports.string().describe("Name of the hook"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), + /** + * Arguments passed to the hook + */ + args: external_exports.array(external_exports.unknown()).describe("Arguments passed to the hook handlers"), + /** + * Number of handlers that will handle this event + */ + handlerCount: external_exports.number().int().min(0).optional().describe("Number of handlers that will handle this event") +}); +var KernelEventBaseSchema = external_exports.object({ + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds") +}); +var KernelReadyEventSchema = KernelEventBaseSchema.extend({ + /** + * Total initialization duration (milliseconds) + */ + duration: external_exports.number().min(0).optional().describe("Total initialization duration in milliseconds"), + /** + * Number of plugins initialized + */ + pluginCount: external_exports.number().int().min(0).optional().describe("Number of plugins initialized") +}); +var KernelShutdownEventSchema = KernelEventBaseSchema.extend({ + /** + * Shutdown reason (optional) + */ + reason: external_exports.string().optional().describe("Reason for kernel shutdown") +}); +var PluginLifecycleEventType = external_exports.enum([ + "kernel:ready", + "kernel:shutdown", + "kernel:before-init", + "kernel:after-init", + "plugin:registered", + "plugin:before-init", + "plugin:init", + "plugin:after-init", + "plugin:before-start", + "plugin:started", + "plugin:after-start", + "plugin:before-destroy", + "plugin:destroyed", + "plugin:after-destroy", + "plugin:error", + "service:registered", + "service:unregistered", + "hook:registered", + "hook:triggered" +]).describe("Plugin lifecycle event type"); +var DynamicPluginOperationSchema = external_exports.enum([ + "load", + // Load and initialize a plugin at runtime + "unload", + // Gracefully unload a running plugin + "reload", + // Unload then load (e.g., version upgrade) + "enable", + // Enable a loaded but disabled plugin + "disable" + // Disable a running plugin without unloading +]).describe("Runtime plugin operation type"); +var PluginSourceSchema = external_exports.object({ + /** + * Source type + */ + type: external_exports.enum([ + "npm", + // npm registry package + "local", + // Local filesystem path + "url", + // Remote URL (tarball or module) + "registry", + // ObjectStack plugin registry + "git" + // Git repository + ]).describe("Plugin source type"), + /** + * Source location (package name, path, URL, or git repo) + */ + location: external_exports.string().describe("Package name, file path, URL, or git repository"), + /** + * Version constraint (semver range) + */ + version: external_exports.string().optional().describe('Semver version range (e.g., "^1.0.0")'), + /** + * Integrity hash for verification + */ + integrity: external_exports.string().optional().describe('Subresource Integrity hash (e.g., "sha384-...")') +}).describe("Plugin source location for dynamic resolution"); +var ActivationEventSchema = external_exports.object({ + /** + * Event type + */ + type: external_exports.enum([ + "onCommand", + // Activate when a specific command is executed + "onRoute", + // Activate when a URL route is matched + "onObject", + // Activate when a specific object type is accessed + "onEvent", + // Activate when a system event fires + "onService", + // Activate when a service is requested + "onSchedule", + // Activate on a cron schedule + "onStartup" + // Activate immediately on kernel startup + ]).describe("Trigger type for lazy activation"), + /** + * Pattern to match (command name, route glob, object name, event pattern, etc.) + */ + pattern: external_exports.string().describe("Match pattern for the activation trigger") +}).describe("Lazy activation trigger for a dynamic plugin"); +var DynamicLoadRequestSchema = external_exports.object({ + /** + * Plugin identifier to load + */ + pluginId: external_exports.string().describe("Unique plugin identifier"), + /** + * Plugin source + */ + source: PluginSourceSchema, + /** + * Activation events (if omitted, plugin activates immediately) + */ + activationEvents: external_exports.array(ActivationEventSchema).optional().describe("Lazy activation triggers; if omitted plugin starts immediately"), + /** + * Configuration overrides for the plugin + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Runtime configuration overrides"), + /** + * Loading priority (lower = higher priority) + */ + priority: external_exports.number().int().min(0).default(100).describe("Loading priority (lower is higher)"), + /** + * Whether to enable sandboxing for this dynamically loaded plugin + */ + sandbox: external_exports.boolean().default(false).describe("Run in an isolated sandbox"), + /** + * Timeout for the load operation in milliseconds + */ + timeout: external_exports.number().int().min(1e3).default(6e4).describe("Maximum time to complete loading in ms") +}).describe("Request to dynamically load a plugin at runtime"); +var DynamicUnloadRequestSchema = external_exports.object({ + /** + * Plugin identifier to unload + */ + pluginId: external_exports.string().describe("Plugin to unload"), + /** + * Unload strategy + */ + strategy: external_exports.enum([ + "graceful", + // Wait for in-flight requests, then unload + "forceful", + // Unload immediately, cancel pending work + "drain" + // Stop accepting new work, finish existing, then unload + ]).default("graceful").describe("How to handle in-flight work during unload"), + /** + * Timeout for the unload operation in milliseconds + */ + timeout: external_exports.number().int().min(1e3).default(3e4).describe("Maximum time to complete unloading in ms"), + /** + * Whether to remove cached artifacts + */ + cleanupCache: external_exports.boolean().default(false).describe("Remove cached code and assets after unload"), + /** + * Action for dependents: plugins that depend on this one + */ + dependentAction: external_exports.enum([ + "cascade", + // Also unload dependent plugins + "warn", + // Warn about dependents but proceed + "block" + // Block unload if dependents exist + ]).default("block").describe("How to handle plugins that depend on this one") +}).describe("Request to dynamically unload a plugin at runtime"); +var DynamicPluginResultSchema = external_exports.object({ + /** + * Whether the operation succeeded + */ + success: external_exports.boolean(), + /** + * The operation that was performed + */ + operation: DynamicPluginOperationSchema, + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Operation duration in milliseconds + */ + durationMs: external_exports.number().int().min(0).optional(), + /** + * Resulting plugin version (for load/reload) + */ + version: external_exports.string().optional(), + /** + * Error details if operation failed + */ + error: external_exports.object({ + code: external_exports.string().describe("Machine-readable error code"), + message: external_exports.string().describe("Human-readable error message"), + details: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional(), + /** + * Warnings (e.g., dependents affected) + */ + warnings: external_exports.array(external_exports.string()).optional() +}).describe("Result of a dynamic plugin operation"); +var PluginDiscoverySourceSchema = external_exports.object({ + /** + * Discovery source type + */ + type: external_exports.enum([ + "registry", + // ObjectStack plugin registry API + "npm", + // npm registry search + "directory", + // Local filesystem directory scan + "url" + // Remote manifest URL + ]).describe("Discovery source type"), + /** + * Source endpoint or path + */ + endpoint: external_exports.string().describe("Registry URL, directory path, or manifest URL"), + /** + * Polling interval in milliseconds (0 = manual only) + */ + pollInterval: external_exports.number().int().min(0).default(0).describe("How often to re-scan for new plugins (0 = manual)"), + /** + * Filter criteria for discovered plugins + */ + filter: external_exports.object({ + /** + * Only discover plugins matching these tags + */ + tags: external_exports.array(external_exports.string()).optional(), + /** + * Only discover plugins from these vendors + */ + vendors: external_exports.array(external_exports.string()).optional(), + /** + * Minimum trust level + */ + minTrustLevel: external_exports.enum(["verified", "trusted", "community", "untrusted"]).optional() + }).optional() +}).describe("Source for runtime plugin discovery"); +var PluginDiscoveryConfigSchema = external_exports.object({ + /** + * Enable runtime plugin discovery + */ + enabled: external_exports.boolean().default(false), + /** + * Discovery sources + */ + sources: external_exports.array(PluginDiscoverySourceSchema).default([]), + /** + * Auto-load discovered plugins matching criteria + */ + autoLoad: external_exports.boolean().default(false).describe("Automatically load newly discovered plugins"), + /** + * Require approval before loading discovered plugins + */ + requireApproval: external_exports.boolean().default(true).describe("Require admin approval before loading discovered plugins") +}).describe("Runtime plugin discovery configuration"); +var DynamicLoadingConfigSchema = external_exports.object({ + /** + * Enable dynamic loading/unloading at runtime + */ + enabled: external_exports.boolean().default(false).describe("Enable runtime load/unload of plugins"), + /** + * Maximum number of dynamically loaded plugins + */ + maxDynamicPlugins: external_exports.number().int().min(1).default(50).describe("Upper limit on runtime-loaded plugins"), + /** + * Plugin discovery configuration + */ + discovery: PluginDiscoveryConfigSchema.optional(), + /** + * Default sandbox policy for dynamically loaded plugins + */ + defaultSandbox: external_exports.boolean().default(true).describe("Sandbox dynamically loaded plugins by default"), + /** + * Allowed plugin sources (empty = all allowed) + */ + allowedSources: external_exports.array(external_exports.enum(["npm", "local", "url", "registry", "git"])).optional().describe("Restrict which source types are permitted"), + /** + * Require integrity verification for remote plugins + */ + requireIntegrity: external_exports.boolean().default(true).describe("Require integrity hash verification for remote sources"), + /** + * Global timeout for dynamic operations in milliseconds + */ + operationTimeout: external_exports.number().int().min(1e3).default(6e4).describe("Default timeout for load/unload operations in ms") +}).describe("Dynamic plugin loading subsystem configuration"); +var PermissionScopeSchema = external_exports.enum([ + "global", + // Applies to entire system + "tenant", + // Applies to specific tenant + "user", + // Applies to specific user + "resource", + // Applies to specific resource + "plugin" + // Applies within plugin boundaries +]).describe("Scope of permission application"); +var PermissionActionSchema = external_exports.enum([ + "create", + // Create new resources + "read", + // Read existing resources + "update", + // Update existing resources + "delete", + // Delete resources + "execute", + // Execute operations/functions + "manage", + // Full management rights + "configure", + // Configuration changes + "share", + // Share with others + "export", + // Export data + "import", + // Import data + "admin" + // Administrative access +]).describe("Type of action being permitted"); +var ResourceTypeSchema = external_exports.enum([ + "data.object", + // ObjectQL objects + "data.record", + // Individual records + "data.field", + // Specific fields + "ui.view", + // UI views + "ui.dashboard", + // Dashboards + "ui.report", + // Reports + "system.config", + // System configuration + "system.plugin", + // Other plugins + "system.api", + // API endpoints + "system.service", + // System services + "storage.file", + // File storage + "storage.database", + // Database access + "network.http", + // HTTP requests + "network.websocket", + // WebSocket connections + "process.spawn", + // Process spawning + "process.env" + // Environment variables +]).describe("Type of resource being accessed"); +var PermissionSchema = external_exports.object({ + /** + * Permission identifier + */ + id: external_exports.string().describe("Unique permission identifier"), + /** + * Resource type + */ + resource: ResourceTypeSchema, + /** + * Allowed actions + */ + actions: external_exports.array(PermissionActionSchema), + /** + * Permission scope + */ + scope: PermissionScopeSchema.default("plugin"), + /** + * Resource filter + */ + filter: external_exports.object({ + /** + * Specific resource IDs + */ + resourceIds: external_exports.array(external_exports.string()).optional(), + /** + * Filter condition + */ + condition: external_exports.string().optional().describe("Filter expression (e.g., owner = currentUser)"), + /** + * Field-level access + */ + fields: external_exports.array(external_exports.string()).optional().describe("Allowed fields for data resources") + }).optional(), + /** + * Human-readable description + */ + description: external_exports.string(), + /** + * Whether this permission is required or optional + */ + required: external_exports.boolean().default(true), + /** + * Justification for permission + */ + justification: external_exports.string().optional().describe("Why this permission is needed") +}); +var PermissionSetSchema = external_exports.object({ + /** + * All permissions required by plugin + */ + permissions: external_exports.array(PermissionSchema), + /** + * Permission groups for easier management + */ + groups: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Group name"), + description: external_exports.string(), + permissions: external_exports.array(external_exports.string()).describe("Permission IDs in this group") + })).optional(), + /** + * Default grant strategy + */ + defaultGrant: external_exports.enum([ + "prompt", + // Always prompt user + "allow", + // Allow by default + "deny", + // Deny by default + "inherit" + // Inherit from parent + ]).default("prompt") +}); +var RuntimeConfigSchema = external_exports.object({ + /** + * Runtime engine type + */ + engine: external_exports.enum([ + "v8-isolate", + // V8 isolate-based isolation (lightweight, fast) + "wasm", + // WebAssembly-based isolation (secure, portable) + "container", + // Container-based isolation (Docker, podman) + "process" + // Process-based isolation (traditional) + ]).default("v8-isolate").describe("Execution environment engine"), + /** + * Engine-specific configuration + */ + engineConfig: external_exports.object({ + /** + * WASM-specific settings (when engine is "wasm") + */ + wasm: external_exports.object({ + /** + * Maximum memory pages (64KB per page) + */ + maxMemoryPages: external_exports.number().int().min(1).max(65536).optional().describe("Maximum WASM memory pages (64KB each)"), + /** + * Instruction execution limit + */ + instructionLimit: external_exports.number().int().min(1).optional().describe("Maximum instructions before timeout"), + /** + * Enable SIMD instructions + */ + enableSimd: external_exports.boolean().default(false).describe("Enable WebAssembly SIMD support"), + /** + * Enable threads + */ + enableThreads: external_exports.boolean().default(false).describe("Enable WebAssembly threads"), + /** + * Enable bulk memory operations + */ + enableBulkMemory: external_exports.boolean().default(true).describe("Enable bulk memory operations") + }).optional(), + /** + * Container-specific settings (when engine is "container") + */ + container: external_exports.object({ + /** + * Container image + */ + image: external_exports.string().optional().describe("Container image to use"), + /** + * Container runtime + */ + runtime: external_exports.enum(["docker", "podman", "containerd"]).default("docker"), + /** + * Resource limits + */ + resources: external_exports.object({ + cpuLimit: external_exports.string().optional().describe('CPU limit (e.g., "0.5", "2")'), + memoryLimit: external_exports.string().optional().describe('Memory limit (e.g., "512m", "1g")') + }).optional(), + /** + * Network mode + */ + networkMode: external_exports.enum(["none", "bridge", "host"]).default("bridge") + }).optional(), + /** + * V8 Isolate-specific settings (when engine is "v8-isolate") + */ + v8Isolate: external_exports.object({ + /** + * Heap size limit in MB + */ + heapSizeMb: external_exports.number().int().min(1).optional(), + /** + * Enable snapshot + */ + enableSnapshot: external_exports.boolean().default(true) + }).optional() + }).optional(), + /** + * General resource limits (applies to all engines) + */ + resourceLimits: external_exports.object({ + /** + * Maximum memory in bytes + */ + maxMemory: external_exports.number().int().optional().describe("Maximum memory allocation"), + /** + * Maximum CPU percentage + */ + maxCpu: external_exports.number().min(0).max(100).optional().describe("Maximum CPU usage percentage"), + /** + * Execution timeout in milliseconds + */ + timeout: external_exports.number().int().min(0).optional().describe("Maximum execution time") + }).optional() +}); +var SandboxConfigSchema = external_exports.object({ + /** + * Enable sandboxing + */ + enabled: external_exports.boolean().default(true), + /** + * Sandboxing level + */ + level: external_exports.enum([ + "none", + // No sandboxing + "minimal", + // Basic isolation + "standard", + // Standard sandboxing + "strict", + // Strict isolation + "paranoid" + // Maximum isolation + ]).default("standard"), + /** + * Runtime environment configuration + */ + runtime: RuntimeConfigSchema.optional().describe("Execution environment and isolation settings"), + /** + * File system access + */ + filesystem: external_exports.object({ + mode: external_exports.enum(["none", "readonly", "restricted", "full"]).default("restricted"), + allowedPaths: external_exports.array(external_exports.string()).optional().describe("Whitelisted paths"), + deniedPaths: external_exports.array(external_exports.string()).optional().describe("Blacklisted paths"), + maxFileSize: external_exports.number().int().optional().describe("Maximum file size in bytes") + }).optional(), + /** + * Network access + */ + network: external_exports.object({ + mode: external_exports.enum(["none", "local", "restricted", "full"]).default("restricted"), + allowedHosts: external_exports.array(external_exports.string()).optional().describe("Whitelisted hosts"), + deniedHosts: external_exports.array(external_exports.string()).optional().describe("Blacklisted hosts"), + allowedPorts: external_exports.array(external_exports.number()).optional().describe("Allowed port numbers"), + maxConnections: external_exports.number().int().optional() + }).optional(), + /** + * Process execution + */ + process: external_exports.object({ + allowSpawn: external_exports.boolean().default(false).describe("Allow spawning child processes"), + allowedCommands: external_exports.array(external_exports.string()).optional().describe("Whitelisted commands"), + timeout: external_exports.number().int().optional().describe("Process timeout in ms") + }).optional(), + /** + * Memory limits + */ + memory: external_exports.object({ + maxHeap: external_exports.number().int().optional().describe("Maximum heap size in bytes"), + maxStack: external_exports.number().int().optional().describe("Maximum stack size in bytes") + }).optional(), + /** + * CPU limits + */ + cpu: external_exports.object({ + maxCpuPercent: external_exports.number().min(0).max(100).optional(), + maxThreads: external_exports.number().int().optional() + }).optional(), + /** + * Environment variables + */ + environment: external_exports.object({ + mode: external_exports.enum(["none", "readonly", "restricted", "full"]).default("readonly"), + allowedVars: external_exports.array(external_exports.string()).optional(), + deniedVars: external_exports.array(external_exports.string()).optional() + }).optional() +}); +var KernelSecurityVulnerabilitySchema = external_exports.object({ + /** + * CVE identifier + */ + cve: external_exports.string().optional(), + /** + * Vulnerability identifier + */ + id: external_exports.string(), + /** + * Severity level + */ + severity: external_exports.enum(["critical", "high", "medium", "low", "info"]), + /** + * Category (e.g., SAST, DAST, Dependency) + */ + category: external_exports.string().optional(), + /** + * Title + */ + title: external_exports.string(), + /** + * Location of the vulnerability + */ + location: external_exports.string().optional(), + /** + * Remediation steps + */ + remediation: external_exports.string().optional(), + /** + * Description + */ + description: external_exports.string(), + /** + * Affected versions + */ + affectedVersions: external_exports.array(external_exports.string()), + /** + * Fixed in versions + */ + fixedIn: external_exports.array(external_exports.string()).optional(), + /** + * CVSS score + */ + cvssScore: external_exports.number().min(0).max(10).optional(), + /** + * Exploit availability + */ + exploitAvailable: external_exports.boolean().default(false), + /** + * Patch available + */ + patchAvailable: external_exports.boolean().default(false), + /** + * Workaround + */ + workaround: external_exports.string().optional(), + /** + * References + */ + references: external_exports.array(external_exports.string()).optional(), + /** + * Discovered date + */ + discoveredDate: external_exports.string().datetime().optional(), + /** + * Published date + */ + publishedDate: external_exports.string().datetime().optional() +}); +var KernelSecurityScanResultSchema = external_exports.object({ + /** + * Scan timestamp + */ + timestamp: external_exports.string().datetime(), + /** + * Scanner information + */ + scanner: external_exports.object({ + name: external_exports.string(), + version: external_exports.string() + }), + /** + * Overall status + */ + status: external_exports.enum(["passed", "failed", "warning"]), + /** + * Vulnerabilities found + */ + vulnerabilities: external_exports.array(KernelSecurityVulnerabilitySchema).optional(), + /** + * Code quality issues + */ + codeIssues: external_exports.array(external_exports.object({ + severity: external_exports.enum(["error", "warning", "info"]), + type: external_exports.string().describe("Issue type (e.g., sql-injection, xss)"), + file: external_exports.string(), + line: external_exports.number().int().optional(), + message: external_exports.string(), + suggestion: external_exports.string().optional() + })).optional(), + /** + * Dependency vulnerabilities + */ + dependencyVulnerabilities: external_exports.array(external_exports.object({ + package: external_exports.string(), + version: external_exports.string(), + vulnerability: KernelSecurityVulnerabilitySchema + })).optional(), + /** + * License compliance + */ + licenseCompliance: external_exports.object({ + status: external_exports.enum(["compliant", "non-compliant", "unknown"]), + issues: external_exports.array(external_exports.object({ + package: external_exports.string(), + license: external_exports.string(), + reason: external_exports.string() + })).optional() + }).optional(), + /** + * Summary statistics + */ + summary: external_exports.object({ + totalVulnerabilities: external_exports.number().int(), + criticalCount: external_exports.number().int(), + highCount: external_exports.number().int(), + mediumCount: external_exports.number().int(), + lowCount: external_exports.number().int(), + infoCount: external_exports.number().int() + }) +}); +var KernelSecurityPolicySchema = external_exports.object({ + /** + * Content Security Policy + */ + csp: external_exports.object({ + directives: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional(), + reportOnly: external_exports.boolean().default(false) + }).optional(), + /** + * CORS policy + */ + cors: external_exports.object({ + allowedOrigins: external_exports.array(external_exports.string()), + allowedMethods: external_exports.array(external_exports.string()), + allowedHeaders: external_exports.array(external_exports.string()), + allowCredentials: external_exports.boolean().default(false), + maxAge: external_exports.number().int().optional() + }).optional(), + /** + * Rate limiting + */ + rateLimit: external_exports.object({ + enabled: external_exports.boolean().default(true), + maxRequests: external_exports.number().int(), + windowMs: external_exports.number().int().describe("Time window in milliseconds"), + strategy: external_exports.enum(["fixed", "sliding", "token-bucket"]).default("sliding") + }).optional(), + /** + * Authentication requirements + */ + authentication: external_exports.object({ + required: external_exports.boolean().default(true), + methods: external_exports.array(external_exports.enum(["jwt", "oauth2", "api-key", "session", "certificate"])), + tokenExpiration: external_exports.number().int().optional().describe("Token expiration in seconds") + }).optional(), + /** + * Encryption requirements + */ + encryption: external_exports.object({ + dataAtRest: external_exports.boolean().default(false).describe("Encrypt data at rest"), + dataInTransit: external_exports.boolean().default(true).describe("Enforce HTTPS/TLS"), + algorithm: external_exports.string().optional().describe("Encryption algorithm"), + minKeyLength: external_exports.number().int().optional().describe("Minimum key length in bits") + }).optional(), + /** + * Audit logging + */ + auditLog: external_exports.object({ + enabled: external_exports.boolean().default(true), + events: external_exports.array(external_exports.string()).optional().describe("Events to log"), + retention: external_exports.number().int().optional().describe("Log retention in days") + }).optional() +}); +var PluginTrustLevelSchema = external_exports.enum([ + "verified", + // Official/verified plugin + "trusted", + // Trusted third-party + "community", + // Community plugin + "untrusted", + // Unverified plugin + "blocked" + // Blocked/malicious +]).describe("Trust level of the plugin"); +var PluginSecurityManifestSchema = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Trust level + */ + trustLevel: PluginTrustLevelSchema, + /** + * Required permissions + */ + permissions: PermissionSetSchema, + /** + * Sandbox configuration + */ + sandbox: SandboxConfigSchema, + /** + * Security policy + */ + policy: KernelSecurityPolicySchema.optional(), + /** + * Security scan results + */ + scanResults: external_exports.array(KernelSecurityScanResultSchema).optional(), + /** + * Known vulnerabilities + */ + vulnerabilities: external_exports.array(KernelSecurityVulnerabilitySchema).optional(), + /** + * Code signing + */ + codeSigning: external_exports.object({ + signed: external_exports.boolean(), + signature: external_exports.string().optional(), + certificate: external_exports.string().optional(), + algorithm: external_exports.string().optional(), + timestamp: external_exports.string().datetime().optional() + }).optional(), + /** + * Security certifications + */ + certifications: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Certification name (e.g., SOC 2, ISO 27001)"), + issuer: external_exports.string(), + issuedDate: external_exports.string().datetime(), + expiryDate: external_exports.string().datetime().optional(), + certificateUrl: external_exports.string().url().optional() + })).optional(), + /** + * Security contact + */ + securityContact: external_exports.object({ + email: external_exports.string().email().optional(), + url: external_exports.string().url().optional(), + pgpKey: external_exports.string().optional() + }).optional(), + /** + * Vulnerability disclosure policy + */ + vulnerabilityDisclosure: external_exports.object({ + policyUrl: external_exports.string().url().optional(), + responseTime: external_exports.number().int().optional().describe("Expected response time in hours"), + bugBounty: external_exports.boolean().default(false) + }).optional() +}); +var SNAKE_CASE_REGEX = /^[a-z][a-z0-9_]*$/; +var OpsFilePathSchema = external_exports.string().describe("Validates a file path against OPS naming conventions").superRefine((path3, ctx) => { + if (!path3.startsWith("src/")) { + return; + } + const parts = path3.split("/"); + if (parts.length > 2) { + const domainDir = parts[1]; + if (!SNAKE_CASE_REGEX.test(domainDir)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Domain directory '${domainDir}' must be lowercase snake_case` + }); + } + } + const filename = parts[parts.length - 1]; + if (filename === "index.ts" || filename === "main.ts") return; + if (!SNAKE_CASE_REGEX.test(filename.split(".")[0])) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Filename '${filename}' base name must be lowercase snake_case` + }); + } +}); +var OpsDomainModuleSchema = external_exports.object({ + name: external_exports.string().regex(SNAKE_CASE_REGEX).describe("Module name (snake_case)"), + files: external_exports.array(external_exports.string()).describe("List of files in this module"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") +}).describe("Scanned domain module representing a plugin folder").superRefine((module, ctx) => { + if (!module.files.includes("index.ts")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Module '${module.name}' is missing an 'index.ts' entry point.` + }); + } +}); +var OpsPluginStructureSchema = external_exports.object({ + root: external_exports.string().describe("Root directory path of the plugin project"), + files: external_exports.array(external_exports.string()).describe("List of all file paths relative to root"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") +}).describe("Full plugin project layout validated against OPS conventions").superRefine((project, ctx) => { + if (!project.files.includes("objectstack.config.ts")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "Missing 'objectstack.config.ts' configuration file." + }); + } + project.files.filter((f) => f.startsWith("src/")).forEach((file2) => { + const result = OpsFilePathSchema.safeParse(file2); + if (!result.success) { + result.error.issues.forEach((issue2) => { + ctx.addIssue({ ...issue2, path: [file2] }); + }); + } + }); +}); +var ValidationErrorSchema = external_exports.object({ + /** + * Field that failed validation + */ + field: external_exports.string().describe("Field name that failed validation"), + /** + * Human-readable error message + */ + message: external_exports.string().describe("Human-readable error message"), + /** + * Machine-readable error code (optional) + */ + code: external_exports.string().optional().describe("Machine-readable error code") +}); +var ValidationWarningSchema = external_exports.object({ + /** + * Field with warning + */ + field: external_exports.string().describe("Field name with warning"), + /** + * Human-readable warning message + */ + message: external_exports.string().describe("Human-readable warning message"), + /** + * Machine-readable warning code (optional) + */ + code: external_exports.string().optional().describe("Machine-readable warning code") +}); +var ValidationResultSchema = external_exports.object({ + /** + * Whether validation passed + */ + valid: external_exports.boolean().describe("Whether the plugin passed validation"), + /** + * Validation errors (if any) + */ + errors: external_exports.array(ValidationErrorSchema).optional().describe("Validation errors"), + /** + * Validation warnings (non-fatal issues) + */ + warnings: external_exports.array(ValidationWarningSchema).optional().describe("Validation warnings") +}); +var PluginMetadataSchema = external_exports.object({ + /** + * Unique plugin identifier (snake_case) + */ + name: external_exports.string().min(1).describe("Unique plugin identifier"), + /** + * Plugin version (semver) + */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic version (e.g., 1.0.0)"), + /** + * Plugin dependencies (array of plugin names) + */ + dependencies: external_exports.array(external_exports.string()).optional().describe("Array of plugin names this plugin depends on"), + /** + * Plugin signature for cryptographic verification (optional) + */ + signature: external_exports.string().optional().describe("Cryptographic signature for plugin verification") + /** + * Additional plugin metadata + */ +}).passthrough().describe("Plugin metadata for validation"); +var SemanticVersionSchema = external_exports.object({ + major: external_exports.number().int().min(0).describe("Major version (breaking changes)"), + minor: external_exports.number().int().min(0).describe("Minor version (backward compatible features)"), + patch: external_exports.number().int().min(0).describe("Patch version (backward compatible fixes)"), + preRelease: external_exports.string().optional().describe("Pre-release identifier (alpha, beta, rc.1)"), + build: external_exports.string().optional().describe("Build metadata") +}).describe("Semantic version number"); +var VersionConstraintSchema = external_exports.union([ + external_exports.string().regex(/^[\d.]+$/).describe("Exact version: `1.2.3`"), + external_exports.string().regex(/^\^[\d.]+$/).describe("Compatible with: `^1.2.3` (`>=1.2.3 <2.0.0`)"), + external_exports.string().regex(/^~[\d.]+$/).describe("Approximately: `~1.2.3` (`>=1.2.3 <1.3.0`)"), + external_exports.string().regex(/^>=[\d.]+$/).describe("Greater than or equal: `>=1.2.3`"), + external_exports.string().regex(/^>[\d.]+$/).describe("Greater than: `>1.2.3`"), + external_exports.string().regex(/^<=[\d.]+$/).describe("Less than or equal: `<=1.2.3`"), + external_exports.string().regex(/^<[\d.]+$/).describe("Less than: `<1.2.3`"), + external_exports.string().regex(/^[\d.]+ - [\d.]+$/).describe("Range: `1.2.3 - 2.3.4`"), + external_exports.literal("*").describe("Any version"), + external_exports.literal("latest").describe("Latest stable version") +]); +var CompatibilityLevelSchema = external_exports.enum([ + "fully-compatible", + // 100% compatible, drop-in replacement + "backward-compatible", + // Backward compatible, new features added + "deprecated-compatible", + // Compatible but uses deprecated features + "breaking-changes", + // Breaking changes, migration required + "incompatible" + // Completely incompatible +]).describe("Compatibility level between versions"); +var BreakingChangeSchema = external_exports.object({ + /** + * Version where the change was introduced + */ + introducedIn: external_exports.string().describe("Version that introduced this breaking change"), + /** + * Type of breaking change + */ + type: external_exports.enum([ + "api-removed", + // API removed + "api-renamed", + // API renamed + "api-signature-changed", + // Function signature changed + "behavior-changed", + // Behavior changed + "dependency-changed", + // Dependency requirement changed + "configuration-changed", + // Configuration schema changed + "protocol-changed" + // Protocol implementation changed + ]), + /** + * What was changed + */ + description: external_exports.string(), + /** + * Migration guide + */ + migrationGuide: external_exports.string().optional().describe("How to migrate from old to new"), + /** + * Deprecated in version + */ + deprecatedIn: external_exports.string().optional().describe("Version where old API was deprecated"), + /** + * Will be removed in version + */ + removedIn: external_exports.string().optional().describe("Version where old API will be removed"), + /** + * Automated migration available + */ + automatedMigration: external_exports.boolean().default(false).describe("Whether automated migration tool is available"), + /** + * Impact severity + */ + severity: external_exports.enum(["critical", "major", "minor"]).describe("Impact severity") +}); +var DeprecationNoticeSchema = external_exports.object({ + /** + * Feature or API being deprecated + */ + feature: external_exports.string().describe("Deprecated feature identifier"), + /** + * Version when deprecated + */ + deprecatedIn: external_exports.string(), + /** + * Planned removal version + */ + removeIn: external_exports.string().optional(), + /** + * Reason for deprecation + */ + reason: external_exports.string(), + /** + * Recommended alternative + */ + alternative: external_exports.string().optional().describe("What to use instead"), + /** + * Migration path + */ + migrationPath: external_exports.string().optional().describe("How to migrate to alternative") +}); +var CompatibilityMatrixEntrySchema = external_exports.object({ + /** + * Source version + */ + from: external_exports.string().describe("Version being upgraded from"), + /** + * Target version + */ + to: external_exports.string().describe("Version being upgraded to"), + /** + * Compatibility level + */ + compatibility: CompatibilityLevelSchema, + /** + * Breaking changes list + */ + breakingChanges: external_exports.array(BreakingChangeSchema).optional(), + /** + * Migration required + */ + migrationRequired: external_exports.boolean().default(false), + /** + * Migration complexity + */ + migrationComplexity: external_exports.enum(["trivial", "simple", "moderate", "complex", "major"]).optional(), + /** + * Estimated migration time in hours + */ + estimatedMigrationTime: external_exports.number().optional(), + /** + * Migration script available + */ + migrationScript: external_exports.string().optional().describe("Path to migration script"), + /** + * Test coverage for migration + */ + testCoverage: external_exports.number().min(0).max(100).optional().describe("Percentage of migration covered by tests") +}); +var PluginCompatibilityMatrixSchema = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Current version + */ + currentVersion: external_exports.string(), + /** + * Compatibility entries + */ + compatibilityMatrix: external_exports.array(CompatibilityMatrixEntrySchema), + /** + * Supported versions + */ + supportedVersions: external_exports.array(external_exports.object({ + version: external_exports.string(), + supported: external_exports.boolean(), + endOfLife: external_exports.string().datetime().optional().describe("End of support date"), + securitySupport: external_exports.boolean().default(false).describe("Still receives security updates") + })), + /** + * Minimum compatible version + */ + minimumCompatibleVersion: external_exports.string().optional().describe("Oldest version that can be directly upgraded") +}); +var DependencyConflictSchema = external_exports.object({ + /** + * Type of conflict + */ + type: external_exports.enum([ + "version-mismatch", + // Different versions required + "missing-dependency", + // Required dependency not found + "circular-dependency", + // Circular dependency detected + "incompatible-versions", + // Incompatible versions required by different plugins + "conflicting-interfaces" + // Plugins implement conflicting interfaces + ]), + /** + * Plugins involved in conflict + */ + plugins: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + version: external_exports.string(), + requirement: external_exports.string().optional().describe("What this plugin requires") + })), + /** + * Conflict description + */ + description: external_exports.string(), + /** + * Possible resolutions + */ + resolutions: external_exports.array(external_exports.object({ + strategy: external_exports.enum([ + "upgrade", + // Upgrade one or more plugins + "downgrade", + // Downgrade one or more plugins + "replace", + // Replace with alternative plugin + "disable", + // Disable conflicting plugin + "manual" + // Manual intervention required + ]), + description: external_exports.string(), + automaticResolution: external_exports.boolean().default(false), + riskLevel: external_exports.enum(["low", "medium", "high"]) + })).optional(), + /** + * Severity of conflict + */ + severity: external_exports.enum(["critical", "error", "warning", "info"]) +}); +var PluginDependencyResolutionResultSchema = external_exports.object({ + /** + * Resolution successful + */ + success: external_exports.boolean(), + /** + * Resolved plugin versions + */ + resolved: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + version: external_exports.string(), + resolvedVersion: external_exports.string() + })).optional(), + /** + * Conflicts found + */ + conflicts: external_exports.array(DependencyConflictSchema).optional(), + /** + * Warnings + */ + warnings: external_exports.array(external_exports.string()).optional(), + /** + * Installation order (topologically sorted) + */ + installationOrder: external_exports.array(external_exports.string()).optional().describe("Plugin IDs in order they should be installed"), + /** + * Dependency graph + */ + dependencyGraph: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional().describe("Map of plugin ID to its dependencies") +}); +var MultiVersionSupportSchema = external_exports.object({ + /** + * Enable multi-version support + */ + enabled: external_exports.boolean().default(false), + /** + * Maximum concurrent versions + */ + maxConcurrentVersions: external_exports.number().int().min(1).default(2).describe("How many versions can run at the same time"), + /** + * Version selection strategy + */ + selectionStrategy: external_exports.enum([ + "latest", + // Always use latest version + "stable", + // Use latest stable version + "compatible", + // Use version compatible with dependencies + "pinned", + // Use pinned version + "canary", + // Use canary/preview version + "custom" + // Custom selection logic + ]).default("latest"), + /** + * Version routing rules + */ + routing: external_exports.array(external_exports.object({ + condition: external_exports.string().describe("Routing condition (e.g., tenant, user, feature flag)"), + version: external_exports.string().describe("Version to use when condition matches"), + priority: external_exports.number().int().default(100).describe("Rule priority") + })).optional(), + /** + * Gradual rollout configuration + */ + rollout: external_exports.object({ + enabled: external_exports.boolean().default(false), + strategy: external_exports.enum(["percentage", "blue-green", "canary"]), + percentage: external_exports.number().min(0).max(100).optional().describe("Percentage of traffic to new version"), + duration: external_exports.number().int().optional().describe("Rollout duration in milliseconds") + }).optional() +}); +var PluginVersionMetadataSchema = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Version number + */ + version: SemanticVersionSchema, + /** + * Version string (computed) + */ + versionString: external_exports.string().describe("Full version string (e.g., 1.2.3-beta.1+build.123)"), + /** + * Release date + */ + releaseDate: external_exports.string().datetime(), + /** + * Release notes + */ + releaseNotes: external_exports.string().optional(), + /** + * Breaking changes + */ + breakingChanges: external_exports.array(BreakingChangeSchema).optional(), + /** + * Deprecations + */ + deprecations: external_exports.array(DeprecationNoticeSchema).optional(), + /** + * Compatibility matrix + */ + compatibilityMatrix: external_exports.array(CompatibilityMatrixEntrySchema).optional(), + /** + * Security vulnerabilities fixed + */ + securityFixes: external_exports.array(external_exports.object({ + cve: external_exports.string().optional().describe("CVE identifier"), + severity: external_exports.enum(["critical", "high", "medium", "low"]), + description: external_exports.string(), + fixedIn: external_exports.string().describe("Version where vulnerability was fixed") + })).optional(), + /** + * Download statistics + */ + statistics: external_exports.object({ + downloads: external_exports.number().int().min(0).optional(), + installations: external_exports.number().int().min(0).optional(), + ratings: external_exports.number().min(0).max(5).optional() + }).optional(), + /** + * Support status + */ + support: external_exports.object({ + status: external_exports.enum(["active", "maintenance", "deprecated", "eol"]), + endOfLife: external_exports.string().datetime().optional(), + securitySupport: external_exports.boolean().default(true) + }) +}); +var ServiceScopeType = external_exports.enum([ + "singleton", + // Single instance shared across the application + "transient", + // New instance created each time + "scoped" + // Instance per scope (request, session, transaction, etc.) +]).describe("Service scope type"); +var ServiceMetadataSchema = external_exports.object({ + /** + * Service name (unique identifier) + */ + name: external_exports.string().min(1).describe("Unique service name identifier"), + /** + * Service scope type + */ + scope: ServiceScopeType.optional().default("singleton").describe("Service scope type"), + /** + * Service type or interface name (optional) + */ + type: external_exports.string().optional().describe("Service type or interface name"), + /** + * Registration timestamp (Unix milliseconds) + */ + registeredAt: external_exports.number().int().optional().describe("Unix timestamp in milliseconds when service was registered"), + /** + * Additional metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional service-specific metadata") +}); +var ServiceRegistryConfigSchema = external_exports.object({ + /** + * Strict mode: throw errors on invalid operations + * @default true + */ + strictMode: external_exports.boolean().optional().default(true).describe("Throw errors on invalid operations (duplicate registration, service not found, etc.)"), + /** + * Allow overwriting existing services + * @default false + */ + allowOverwrite: external_exports.boolean().optional().default(false).describe("Allow overwriting existing service registrations"), + /** + * Enable logging for service operations + * @default false + */ + enableLogging: external_exports.boolean().optional().default(false).describe("Enable logging for service registration and retrieval"), + /** + * Custom scope types (beyond singleton, transient, scoped) + * @default ['singleton', 'transient', 'scoped'] + */ + scopeTypes: external_exports.array(external_exports.string()).optional().describe("Supported scope types"), + /** + * Maximum number of services (prevent memory leaks) + */ + maxServices: external_exports.number().int().min(1).optional().describe("Maximum number of services that can be registered") +}); +var ServiceFactoryRegistrationSchema = external_exports.object({ + /** + * Service name (unique identifier) + */ + name: external_exports.string().min(1).describe("Unique service name identifier"), + /** + * Service scope type + */ + scope: ServiceScopeType.optional().default("singleton").describe("Service scope type"), + /** + * Factory type (sync or async) + */ + factoryType: external_exports.enum(["sync", "async"]).optional().default("sync").describe("Whether factory is synchronous or asynchronous"), + /** + * Whether this is a singleton (cache factory result) + */ + singleton: external_exports.boolean().optional().default(true).describe("Whether to cache the factory result (singleton pattern)") +}); +var ScopeConfigSchema = external_exports.object({ + /** + * Type of scope (request, session, transaction, etc.) + */ + scopeType: external_exports.string().describe("Type of scope"), + /** + * Scope identifier (optional, auto-generated if not provided) + */ + scopeId: external_exports.string().optional().describe("Unique scope identifier"), + /** + * Scope metadata (context information) + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Scope-specific context metadata") +}); +var ScopeInfoSchema = external_exports.object({ + /** + * Scope identifier + */ + scopeId: external_exports.string().describe("Unique scope identifier"), + /** + * Type of scope + */ + scopeType: external_exports.string().describe("Type of scope"), + /** + * Creation timestamp (Unix milliseconds) + */ + createdAt: external_exports.number().int().describe("Unix timestamp in milliseconds when scope was created"), + /** + * Number of services in this scope + */ + serviceCount: external_exports.number().int().min(0).optional().describe("Number of services registered in this scope"), + /** + * Scope metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Scope-specific context metadata") +}); +var StartupOptionsSchema = external_exports.object({ + /** + * Maximum time (ms) to wait for each plugin to start + * @default 30000 (30 seconds) + */ + timeout: external_exports.number().int().min(0).optional().default(3e4).describe("Maximum time in milliseconds to wait for each plugin to start"), + /** + * Whether to rollback (destroy) already-started plugins on failure + * @default true + */ + rollbackOnFailure: external_exports.boolean().optional().default(true).describe("Whether to rollback already-started plugins if any plugin fails"), + /** + * Whether to run health checks after startup + * @default false + */ + healthCheck: external_exports.boolean().optional().default(false).describe("Whether to run health checks after plugin startup"), + /** + * Whether to run plugins in parallel (if dependencies allow) + * @default false (sequential startup) + */ + parallel: external_exports.boolean().optional().default(false).describe("Whether to start plugins in parallel when dependencies allow"), + /** + * Custom context to pass to plugin lifecycle methods + */ + context: external_exports.unknown().optional().describe("Custom context object to pass to plugin lifecycle methods") +}); +var HealthStatusSchema = external_exports.object({ + /** + * Whether the plugin is healthy + */ + healthy: external_exports.boolean().describe("Whether the plugin is healthy"), + /** + * Health check timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds when health check was performed"), + /** + * Optional health details (plugin-specific) + */ + details: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Optional plugin-specific health details"), + /** + * Optional error message if unhealthy + */ + message: external_exports.string().optional().describe("Error message if plugin is unhealthy") +}); +var PluginStartupResultSchema = external_exports.object({ + /** + * Plugin that was started + */ + plugin: external_exports.object({ + name: external_exports.string(), + version: external_exports.string().optional() + }).passthrough().describe("Plugin metadata"), + /** + * Whether startup was successful + */ + success: external_exports.boolean().describe("Whether the plugin started successfully"), + /** + * Time taken to start (milliseconds) + */ + duration: external_exports.number().min(0).describe("Time taken to start the plugin in milliseconds"), + /** + * Error if startup failed + */ + error: external_exports.object({ + name: external_exports.string().describe("Error class name"), + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Stack trace"), + code: external_exports.string().optional().describe("Error code") + }).optional().describe("Serializable error representation if startup failed"), + /** + * Health status after startup (if healthCheck enabled) + */ + health: HealthStatusSchema.optional().describe("Health status after startup if health check was enabled") +}); +var StartupOrchestrationResultSchema = external_exports.object({ + /** + * Individual plugin startup results + */ + results: external_exports.array(PluginStartupResultSchema).describe("Startup results for each plugin"), + /** + * Total time taken for all plugins (milliseconds) + */ + totalDuration: external_exports.number().min(0).describe("Total time taken for all plugins in milliseconds"), + /** + * Whether all plugins started successfully + */ + allSuccessful: external_exports.boolean().describe("Whether all plugins started successfully"), + /** + * Plugins that were rolled back (if rollbackOnFailure was enabled) + */ + rolledBack: external_exports.array(external_exports.string()).optional().describe("Names of plugins that were rolled back") +}); +var PluginVendorSchema = external_exports.object({ + /** + * Vendor identifier (reverse domain notation) + * Example: "com.acme", "org.apache", "com.objectstack" + */ + id: external_exports.string().regex(/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)+$/).describe("Vendor identifier (reverse domain)"), + /** + * Vendor display name + */ + name: external_exports.string(), + /** + * Vendor website + */ + website: external_exports.string().url().optional(), + /** + * Contact email + */ + email: external_exports.string().email().optional(), + /** + * Verification status + */ + verified: external_exports.boolean().default(false).describe("Whether vendor is verified by ObjectStack"), + /** + * Trust level + */ + trustLevel: external_exports.enum(["official", "verified", "community", "unverified"]).default("unverified") +}); +var PluginQualityMetricsSchema = external_exports.object({ + /** + * Test coverage percentage + */ + testCoverage: external_exports.number().min(0).max(100).optional(), + /** + * Documentation score (0-100) + */ + documentationScore: external_exports.number().min(0).max(100).optional(), + /** + * Code quality score (0-100) + */ + codeQuality: external_exports.number().min(0).max(100).optional(), + /** + * Security scan status + */ + securityScan: external_exports.object({ + lastScanDate: external_exports.string().datetime().optional(), + vulnerabilities: external_exports.object({ + critical: external_exports.number().int().min(0).default(0), + high: external_exports.number().int().min(0).default(0), + medium: external_exports.number().int().min(0).default(0), + low: external_exports.number().int().min(0).default(0) + }).optional(), + passed: external_exports.boolean().default(false) + }).optional(), + /** + * Conformance test results + */ + conformanceTests: external_exports.array(external_exports.object({ + protocolId: external_exports.string().describe("Protocol being tested"), + passed: external_exports.boolean(), + totalTests: external_exports.number().int().min(0), + passedTests: external_exports.number().int().min(0), + lastRunDate: external_exports.string().datetime().optional() + })).optional() +}); +var PluginStatisticsSchema = external_exports.object({ + /** + * Total downloads + */ + downloads: external_exports.number().int().min(0).default(0), + /** + * Downloads in the last 30 days + */ + downloadsLastMonth: external_exports.number().int().min(0).default(0), + /** + * Number of active installations + */ + activeInstallations: external_exports.number().int().min(0).default(0), + /** + * User ratings + */ + ratings: external_exports.object({ + average: external_exports.number().min(0).max(5).default(0), + count: external_exports.number().int().min(0).default(0), + distribution: external_exports.object({ + "5": external_exports.number().int().min(0).default(0), + "4": external_exports.number().int().min(0).default(0), + "3": external_exports.number().int().min(0).default(0), + "2": external_exports.number().int().min(0).default(0), + "1": external_exports.number().int().min(0).default(0) + }).optional() + }).optional(), + /** + * GitHub stars (if open source) + */ + stars: external_exports.number().int().min(0).optional(), + /** + * Number of dependent plugins + */ + dependents: external_exports.number().int().min(0).default(0) +}); +var PluginRegistryEntrySchema = external_exports.object({ + /** + * Plugin identifier (must match manifest.id) + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Plugin identifier (reverse domain notation)"), + /** + * Current version + */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/), + /** + * Plugin display name + */ + name: external_exports.string(), + /** + * Short description + */ + description: external_exports.string().optional(), + /** + * Detailed documentation/README + */ + readme: external_exports.string().optional(), + /** + * Plugin type/category + */ + category: external_exports.enum([ + "data", + // Data management, storage, databases + "integration", + // External service integrations + "ui", + // UI components and themes + "analytics", + // Analytics and reporting + "security", + // Security, auth, compliance + "automation", + // Workflows and automation + "ai", + // AI/ML capabilities + "utility", + // General utilities + "driver", + // Database/storage drivers + "gateway", + // API gateways + "adapter" + // Runtime adapters + ]).optional(), + /** + * Tags for categorization + */ + tags: external_exports.array(external_exports.string()).optional(), + /** + * Vendor information + */ + vendor: PluginVendorSchema, + /** + * Capability manifest (what the plugin implements/provides) + */ + capabilities: PluginCapabilityManifestSchema2.optional(), + /** + * Compatibility information + */ + compatibility: external_exports.object({ + /** + * Minimum ObjectStack version required + */ + minObjectStackVersion: external_exports.string().optional(), + /** + * Maximum ObjectStack version supported + */ + maxObjectStackVersion: external_exports.string().optional(), + /** + * Node.js version requirement + */ + nodeVersion: external_exports.string().optional(), + /** + * Supported platforms + */ + platforms: external_exports.array(external_exports.enum(["linux", "darwin", "win32", "browser"])).optional() + }).optional(), + /** + * Links and resources + */ + links: external_exports.object({ + homepage: external_exports.string().url().optional(), + repository: external_exports.string().url().optional(), + documentation: external_exports.string().url().optional(), + bugs: external_exports.string().url().optional(), + changelog: external_exports.string().url().optional() + }).optional(), + /** + * Media assets + */ + media: external_exports.object({ + icon: external_exports.string().url().optional(), + logo: external_exports.string().url().optional(), + screenshots: external_exports.array(external_exports.string().url()).optional(), + video: external_exports.string().url().optional() + }).optional(), + /** + * Quality metrics + */ + quality: PluginQualityMetricsSchema.optional(), + /** + * Usage statistics + */ + statistics: PluginStatisticsSchema.optional(), + /** + * License information + */ + license: external_exports.string().optional().describe("SPDX license identifier"), + /** + * Pricing (if commercial) + */ + pricing: external_exports.object({ + model: external_exports.enum(["free", "freemium", "paid", "enterprise"]), + price: external_exports.number().min(0).optional(), + currency: external_exports.string().default("USD").optional(), + billingPeriod: external_exports.enum(["one-time", "monthly", "yearly"]).optional() + }).optional(), + /** + * Publication dates + */ + publishedAt: external_exports.string().datetime().optional(), + updatedAt: external_exports.string().datetime().optional(), + /** + * Deprecation status + */ + deprecated: external_exports.boolean().default(false), + deprecationMessage: external_exports.string().optional(), + replacedBy: external_exports.string().optional().describe("Plugin ID that replaces this one"), + /** + * Feature flags + */ + flags: external_exports.object({ + experimental: external_exports.boolean().default(false), + beta: external_exports.boolean().default(false), + featured: external_exports.boolean().default(false), + verified: external_exports.boolean().default(false) + }).optional() +}); +var PluginSearchFiltersSchema = external_exports.object({ + /** + * Search query + */ + query: external_exports.string().optional(), + /** + * Filter by category + */ + category: external_exports.array(external_exports.string()).optional(), + /** + * Filter by tags + */ + tags: external_exports.array(external_exports.string()).optional(), + /** + * Filter by vendor trust level + */ + trustLevel: external_exports.array(external_exports.enum(["official", "verified", "community", "unverified"])).optional(), + /** + * Filter by protocols implemented + */ + implementsProtocols: external_exports.array(external_exports.string()).optional(), + /** + * Filter by pricing model + */ + pricingModel: external_exports.array(external_exports.enum(["free", "freemium", "paid", "enterprise"])).optional(), + /** + * Minimum rating + */ + minRating: external_exports.number().min(0).max(5).optional(), + /** + * Sort options + */ + sortBy: external_exports.enum([ + "relevance", + "downloads", + "rating", + "updated", + "name" + ]).optional(), + /** + * Sort order + */ + sortOrder: external_exports.enum(["asc", "desc"]).default("desc").optional(), + /** + * Pagination + */ + page: external_exports.number().int().min(1).default(1).optional(), + limit: external_exports.number().int().min(1).max(100).default(20).optional() +}); +var PluginInstallConfigSchema = external_exports.object({ + /** + * Plugin identifier to install + */ + pluginId: external_exports.string(), + /** + * Version to install (supports semver ranges) + */ + version: external_exports.string().optional().describe("Defaults to latest"), + /** + * Plugin-specific configuration values + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Whether to auto-update + */ + autoUpdate: external_exports.boolean().default(false).optional(), + /** + * Installation options + */ + options: external_exports.object({ + /** + * Skip dependency installation + */ + skipDependencies: external_exports.boolean().default(false).optional(), + /** + * Force reinstall + */ + force: external_exports.boolean().default(false).optional(), + /** + * Installation target + */ + target: external_exports.enum(["system", "space", "user"]).default("space").optional() + }).optional() +}); +var VulnerabilitySeverity = external_exports.enum([ + "critical", + "high", + "medium", + "low", + "info" +]).describe("Severity level of a security vulnerability"); +var SecurityVulnerabilitySchema = external_exports.object({ + /** + * CVE identifier (if applicable) + */ + cve: external_exports.string().regex(/^CVE-\d{4}-\d+$/).optional().describe("CVE identifier"), + /** + * Vulnerability identifier (GHSA, SNYK, etc.) + */ + id: external_exports.string().describe("Vulnerability ID"), + /** + * Title + */ + title: external_exports.string().describe("Short title summarizing the vulnerability"), + /** + * Description + */ + description: external_exports.string().describe("Detailed description of the vulnerability"), + /** + * Severity + */ + severity: VulnerabilitySeverity.describe("Severity level of this vulnerability"), + /** + * CVSS score (0-10) + */ + cvss: external_exports.number().min(0).max(10).optional().describe("CVSS score ranging from 0 to 10"), + /** + * Affected package + */ + package: external_exports.object({ + name: external_exports.string().describe("Name of the affected package"), + version: external_exports.string().describe("Version of the affected package"), + ecosystem: external_exports.string().optional().describe("Package ecosystem (e.g., npm, pip, maven)") + }).describe("Affected package information"), + /** + * Vulnerable version range + */ + vulnerableVersions: external_exports.string().describe("Semver range of vulnerable versions"), + /** + * Patched versions + */ + patchedVersions: external_exports.string().optional().describe("Semver range of patched versions"), + /** + * References + */ + references: external_exports.array(external_exports.object({ + type: external_exports.enum(["advisory", "article", "report", "web"]).describe("Type of reference source"), + url: external_exports.string().url().describe("URL of the reference") + })).default([]).describe("External references related to the vulnerability"), + /** + * CWE (Common Weakness Enumeration) + */ + cwe: external_exports.array(external_exports.string()).default([]).describe("CWE identifiers associated with this vulnerability"), + /** + * Published date + */ + publishedAt: external_exports.string().datetime().optional().describe("ISO 8601 date when the vulnerability was published"), + /** + * Mitigation advice + */ + mitigation: external_exports.string().optional().describe("Recommended steps to mitigate the vulnerability") +}).describe("A known security vulnerability in a package dependency"); +var SecurityScanResultSchema = external_exports.object({ + /** + * Scan identifier + */ + scanId: external_exports.string().uuid().describe("Unique identifier for this security scan"), + /** + * Plugin being scanned + */ + plugin: external_exports.object({ + id: external_exports.string().describe("Plugin identifier"), + version: external_exports.string().describe("Plugin version that was scanned") + }).describe("Plugin that was scanned"), + /** + * Scan timestamp + */ + scannedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the scan was performed"), + /** + * Scanner information + */ + scanner: external_exports.object({ + name: external_exports.string().describe("Scanner name (e.g., snyk, osv, trivy)"), + version: external_exports.string().describe("Version of the scanner tool") + }).describe("Information about the scanner tool used"), + /** + * Scan status + */ + status: external_exports.enum(["passed", "failed", "warning"]).describe("Overall result status of the security scan"), + /** + * Vulnerabilities found + */ + vulnerabilities: external_exports.array(SecurityVulnerabilitySchema).describe("List of vulnerabilities discovered during the scan"), + /** + * Vulnerability summary + */ + summary: external_exports.object({ + critical: external_exports.number().int().min(0).default(0).describe("Count of critical severity vulnerabilities"), + high: external_exports.number().int().min(0).default(0).describe("Count of high severity vulnerabilities"), + medium: external_exports.number().int().min(0).default(0).describe("Count of medium severity vulnerabilities"), + low: external_exports.number().int().min(0).default(0).describe("Count of low severity vulnerabilities"), + info: external_exports.number().int().min(0).default(0).describe("Count of informational severity vulnerabilities"), + total: external_exports.number().int().min(0).default(0).describe("Total count of all vulnerabilities") + }).describe("Summary counts of vulnerabilities by severity"), + /** + * License compliance issues + */ + licenseIssues: external_exports.array(external_exports.object({ + package: external_exports.string().describe("Name of the package with a license issue"), + license: external_exports.string().describe("License identifier of the package"), + reason: external_exports.string().describe("Reason the license is flagged"), + severity: external_exports.enum(["error", "warning", "info"]).describe("Severity of the license compliance issue") + })).default([]).describe("License compliance issues found during the scan"), + /** + * Code quality issues + */ + codeQuality: external_exports.object({ + score: external_exports.number().min(0).max(100).optional().describe("Overall code quality score from 0 to 100"), + issues: external_exports.array(external_exports.object({ + type: external_exports.enum(["security", "quality", "style"]).describe("Category of the code quality issue"), + severity: external_exports.enum(["error", "warning", "info"]).describe("Severity of the code quality issue"), + message: external_exports.string().describe("Description of the code quality issue"), + file: external_exports.string().optional().describe("File path where the issue was found"), + line: external_exports.number().int().optional().describe("Line number where the issue was found") + })).default([]).describe("List of individual code quality issues") + }).optional().describe("Code quality analysis results"), + /** + * Next scan scheduled + */ + nextScanAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp for the next scheduled scan") +}).describe("Result of a security scan performed on a plugin"); +var SecurityPolicySchema = external_exports.object({ + /** + * Policy identifier + */ + id: external_exports.string().describe("Unique identifier for the security policy"), + /** + * Policy name + */ + name: external_exports.string().describe("Human-readable name of the security policy"), + /** + * Automatic scanning + */ + autoScan: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Whether automatic scanning is enabled"), + frequency: external_exports.enum(["on-publish", "daily", "weekly", "monthly"]).default("daily").describe("How often automatic scans are performed") + }).describe("Automatic security scanning configuration"), + /** + * Vulnerability thresholds + */ + thresholds: external_exports.object({ + /** + * Block plugin if critical vulnerabilities exceed this + */ + maxCritical: external_exports.number().int().min(0).default(0).describe("Maximum allowed critical vulnerabilities before blocking"), + /** + * Block plugin if high vulnerabilities exceed this + */ + maxHigh: external_exports.number().int().min(0).default(0).describe("Maximum allowed high vulnerabilities before blocking"), + /** + * Warn if medium vulnerabilities exceed this + */ + maxMedium: external_exports.number().int().min(0).default(5).describe("Maximum allowed medium vulnerabilities before warning") + }).describe("Vulnerability count thresholds for policy enforcement"), + /** + * Allowed licenses + */ + allowedLicenses: external_exports.array(external_exports.string()).default([ + "MIT", + "Apache-2.0", + "BSD-3-Clause", + "BSD-2-Clause", + "ISC" + ]).describe("List of SPDX license identifiers that are permitted"), + /** + * Prohibited licenses + */ + prohibitedLicenses: external_exports.array(external_exports.string()).default([ + "GPL-3.0", + "AGPL-3.0" + ]).describe("List of SPDX license identifiers that are prohibited"), + /** + * Code signing requirements + */ + codeSigning: external_exports.object({ + required: external_exports.boolean().default(false).describe("Whether code signing is required for plugins"), + allowedSigners: external_exports.array(external_exports.string()).default([]).describe("List of trusted signer identities") + }).optional().describe("Code signing requirements for plugin artifacts"), + /** + * Sandbox restrictions + */ + sandbox: external_exports.object({ + /** + * Restrict network access + */ + networkAccess: external_exports.enum(["none", "localhost", "allowlist", "all"]).default("all").describe("Level of network access granted to the plugin"), + /** + * Allowed network destinations (if allowlist) + */ + allowedDestinations: external_exports.array(external_exports.string()).default([]).describe("Permitted network destinations when using allowlist mode"), + /** + * File system access + */ + filesystemAccess: external_exports.enum(["none", "read-only", "temp-only", "full"]).default("full").describe("Level of file system access granted to the plugin"), + /** + * Maximum memory (MB) + */ + maxMemoryMB: external_exports.number().int().positive().optional().describe("Maximum memory allocation in megabytes"), + /** + * Maximum CPU time (seconds) + */ + maxCPUSeconds: external_exports.number().int().positive().optional().describe("Maximum CPU time allowed in seconds") + }).optional().describe("Sandbox restrictions for plugin execution") +}).describe("Security policy governing plugin scanning and enforcement"); +var PackageDependencySchema = external_exports.object({ + /** + * Package name/ID + */ + name: external_exports.string().describe("Package name or identifier"), + /** + * Version constraint (semver range) + */ + versionConstraint: external_exports.string().describe("Semver range (e.g., `^1.0.0`, `>=2.0.0 <3.0.0`)"), + /** + * Dependency type + */ + type: external_exports.enum(["required", "optional", "peer", "dev"]).default("required").describe("Category of the dependency relationship"), + /** + * Resolved version (filled during resolution) + */ + resolvedVersion: external_exports.string().optional().describe("Concrete version resolved during dependency resolution") +}).describe("A package dependency with its version constraint"); +var DependencyGraphNodeSchema = external_exports.object({ + /** + * Package identifier + */ + id: external_exports.string().describe("Unique identifier of the package"), + /** + * Package version + */ + version: external_exports.string().describe("Resolved version of the package"), + /** + * Dependencies of this package + */ + dependencies: external_exports.array(PackageDependencySchema).default([]).describe("Dependencies required by this package"), + /** + * Depth in dependency tree + */ + depth: external_exports.number().int().min(0).describe("Depth level in the dependency tree (0 = root)"), + /** + * Whether this is a direct dependency + */ + isDirect: external_exports.boolean().describe("Whether this is a direct (top-level) dependency"), + /** + * Package metadata + */ + metadata: external_exports.object({ + name: external_exports.string().describe("Display name of the package"), + description: external_exports.string().optional().describe("Short description of the package"), + license: external_exports.string().optional().describe("SPDX license identifier of the package"), + homepage: external_exports.string().url().optional().describe("Homepage URL of the package") + }).optional().describe("Additional metadata about the package") +}).describe("A node in the dependency graph representing a resolved package"); +var DependencyGraphSchema = external_exports.object({ + /** + * Root package + */ + root: external_exports.object({ + id: external_exports.string().describe("Identifier of the root package"), + version: external_exports.string().describe("Version of the root package") + }).describe("Root package of the dependency graph"), + /** + * All nodes in the graph + */ + nodes: external_exports.array(DependencyGraphNodeSchema).describe("All resolved package nodes in the dependency graph"), + /** + * Edges (dependency relationships) + */ + edges: external_exports.array(external_exports.object({ + from: external_exports.string().describe("Package ID"), + to: external_exports.string().describe("Package ID"), + constraint: external_exports.string().describe("Version constraint") + })).describe("Directed edges representing dependency relationships"), + /** + * Resolution statistics + */ + stats: external_exports.object({ + totalDependencies: external_exports.number().int().min(0).describe("Total number of resolved dependencies"), + directDependencies: external_exports.number().int().min(0).describe("Number of direct (top-level) dependencies"), + maxDepth: external_exports.number().int().min(0).describe("Maximum depth of the dependency tree") + }).describe("Summary statistics for the dependency graph") +}).describe("Complete dependency graph for a package and its transitive dependencies"); +var PackageDependencyConflictSchema = external_exports.object({ + /** + * Package with conflict + */ + package: external_exports.string().describe("Name of the package with conflicting version requirements"), + /** + * Conflicting versions + */ + conflicts: external_exports.array(external_exports.object({ + version: external_exports.string().describe("Conflicting version of the package"), + requestedBy: external_exports.array(external_exports.string()).describe("Packages that require this version"), + constraint: external_exports.string().describe("Semver constraint that produced this version requirement") + })).describe("List of conflicting version requirements"), + /** + * Suggested resolution + */ + resolution: external_exports.object({ + strategy: external_exports.enum(["pick-highest", "pick-lowest", "manual"]).describe("Strategy used to resolve the conflict"), + version: external_exports.string().optional().describe("Resolved version selected by the strategy"), + reason: external_exports.string().optional().describe("Explanation of why this resolution was chosen") + }).optional().describe("Suggested resolution for the conflict"), + /** + * Severity + */ + severity: external_exports.enum(["error", "warning", "info"]).describe("Severity level of the dependency conflict") +}).describe("A detected conflict between dependency version requirements"); +var PackageDependencyResolutionResultSchema = external_exports.object({ + /** + * Resolution status + */ + status: external_exports.enum(["success", "conflict", "error"]).describe("Overall status of the dependency resolution"), + /** + * Resolved dependency graph + */ + graph: DependencyGraphSchema.optional().describe("Resolved dependency graph if resolution succeeded"), + /** + * Conflicts detected + */ + conflicts: external_exports.array(PackageDependencyConflictSchema).default([]).describe("List of dependency conflicts detected during resolution"), + /** + * Errors encountered + */ + errors: external_exports.array(external_exports.object({ + package: external_exports.string().describe("Name of the package that caused the error"), + error: external_exports.string().describe("Error message describing what went wrong") + })).default([]).describe("Errors encountered during dependency resolution"), + /** + * Installation order (topological sort) + */ + installOrder: external_exports.array(external_exports.string()).default([]).describe("Topologically sorted list of package IDs for installation"), + /** + * Resolution time (ms) + */ + resolvedIn: external_exports.number().int().min(0).optional().describe("Time taken to resolve dependencies in milliseconds") +}).describe("Result of a dependency resolution process"); +var SBOMEntrySchema = external_exports.object({ + /** + * Component name + */ + name: external_exports.string().describe("Name of the software component"), + /** + * Component version + */ + version: external_exports.string().describe("Version of the software component"), + /** + * Package URL (purl) + */ + purl: external_exports.string().optional().describe("Package URL identifier"), + /** + * License + */ + license: external_exports.string().optional().describe("SPDX license identifier of the component"), + /** + * Hashes + */ + hashes: external_exports.object({ + sha256: external_exports.string().optional().describe("SHA-256 hash of the component artifact"), + sha512: external_exports.string().optional().describe("SHA-512 hash of the component artifact") + }).optional().describe("Cryptographic hashes for integrity verification"), + /** + * Supplier + */ + supplier: external_exports.object({ + name: external_exports.string().describe("Name of the component supplier"), + url: external_exports.string().url().optional().describe("URL of the component supplier") + }).optional().describe("Supplier information for the component"), + /** + * External references + */ + externalRefs: external_exports.array(external_exports.object({ + type: external_exports.enum(["website", "repository", "documentation", "issue-tracker"]).describe("Type of external reference"), + url: external_exports.string().url().describe("URL of the external reference") + })).default([]).describe("External references related to the component") +}).describe("A single entry in a Software Bill of Materials"); +var SBOMSchema = external_exports.object({ + /** + * SBOM format + */ + format: external_exports.enum(["spdx", "cyclonedx"]).default("cyclonedx").describe("SBOM standard format used"), + /** + * SBOM version + */ + version: external_exports.string().describe("Version of the SBOM specification"), + /** + * Plugin metadata + */ + plugin: external_exports.object({ + id: external_exports.string().describe("Plugin identifier"), + version: external_exports.string().describe("Plugin version"), + name: external_exports.string().describe("Human-readable plugin name") + }).describe("Metadata about the plugin this SBOM describes"), + /** + * Components (dependencies) + */ + components: external_exports.array(SBOMEntrySchema).describe("List of software components included in the plugin"), + /** + * Generation timestamp + */ + generatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the SBOM was generated"), + /** + * Generator tool + */ + generator: external_exports.object({ + name: external_exports.string().describe("Name of the SBOM generator tool"), + version: external_exports.string().describe("Version of the SBOM generator tool") + }).optional().describe("Tool used to generate this SBOM") +}).describe("Software Bill of Materials for a plugin"); +var PluginProvenanceSchema = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string().describe("Unique identifier of the plugin"), + /** + * Plugin version + */ + version: external_exports.string().describe("Version of the plugin artifact"), + /** + * Build information + */ + build: external_exports.object({ + /** + * Build timestamp + */ + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the build was produced"), + /** + * Build environment + */ + environment: external_exports.object({ + os: external_exports.string().describe("Operating system used for the build"), + arch: external_exports.string().describe("CPU architecture used for the build"), + nodeVersion: external_exports.string().describe("Node.js version used for the build") + }).optional().describe("Environment details where the build was executed"), + /** + * Source repository + */ + source: external_exports.object({ + repository: external_exports.string().url().describe("URL of the source repository"), + commit: external_exports.string().regex(/^[a-f0-9]{40}$/).describe("Full SHA-1 commit hash of the source"), + branch: external_exports.string().optional().describe("Branch name the build was produced from"), + tag: external_exports.string().optional().describe("Git tag associated with the build") + }).optional().describe("Source repository information for the build"), + /** + * Builder identity + */ + builder: external_exports.object({ + name: external_exports.string().describe("Name of the person or system that produced the build"), + email: external_exports.string().email().optional().describe("Email address of the builder") + }).optional().describe("Identity of the builder who produced the artifact") + }).describe("Build provenance information"), + /** + * Artifact hashes + */ + artifacts: external_exports.array(external_exports.object({ + filename: external_exports.string().describe("Name of the artifact file"), + sha256: external_exports.string().describe("SHA-256 hash of the artifact"), + size: external_exports.number().int().positive().describe("Size of the artifact in bytes") + })).describe("List of build artifacts with integrity hashes"), + /** + * Signatures + */ + signatures: external_exports.array(external_exports.object({ + algorithm: external_exports.enum(["rsa", "ecdsa", "ed25519"]).describe("Cryptographic algorithm used for signing"), + publicKey: external_exports.string().describe("Public key used to verify the signature"), + signature: external_exports.string().describe("Digital signature value"), + signedBy: external_exports.string().describe("Identity of the signer"), + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the signature was created") + })).default([]).describe("Cryptographic signatures for the plugin artifact"), + /** + * Attestations + */ + attestations: external_exports.array(external_exports.object({ + type: external_exports.enum(["code-review", "security-scan", "test-results", "ci-build"]).describe("Type of attestation"), + status: external_exports.enum(["passed", "failed"]).describe("Result status of the attestation"), + url: external_exports.string().url().optional().describe("URL with details about the attestation"), + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the attestation was issued") + })).default([]).describe("Verification attestations for the plugin") +}).describe("Verifiable provenance and chain of custody for a plugin artifact"); +var PluginTrustScoreSchema = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string().describe("Unique identifier of the plugin"), + /** + * Overall trust score (0-100) + */ + score: external_exports.number().min(0).max(100).describe("Overall trust score from 0 to 100"), + /** + * Score components + */ + components: external_exports.object({ + /** + * Vendor reputation (0-100) + */ + vendorReputation: external_exports.number().min(0).max(100).describe("Vendor reputation score from 0 to 100"), + /** + * Security scan results (0-100) + */ + securityScore: external_exports.number().min(0).max(100).describe("Security scan results score from 0 to 100"), + /** + * Code quality (0-100) + */ + codeQuality: external_exports.number().min(0).max(100).describe("Code quality score from 0 to 100"), + /** + * Community engagement (0-100) + */ + communityScore: external_exports.number().min(0).max(100).describe("Community engagement score from 0 to 100"), + /** + * Update frequency (0-100) + */ + maintenanceScore: external_exports.number().min(0).max(100).describe("Maintenance and update frequency score from 0 to 100") + }).describe("Individual score components contributing to the overall trust score"), + /** + * Trust level + */ + level: external_exports.enum(["verified", "trusted", "neutral", "untrusted", "blocked"]).describe("Computed trust level based on the overall score"), + /** + * Verification badges + */ + badges: external_exports.array(external_exports.enum([ + "official", + // Official ObjectStack plugin + "verified-vendor", + // Verified vendor + "security-scanned", + // Passed security scan + "code-signed", + // Digitally signed + "open-source", + // Open source + "popular" + // High downloads + ])).default([]).describe("Verification badges earned by the plugin"), + /** + * Last updated + */ + updatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the trust score was last updated") +}).describe("Trust score and verification status for a plugin"); +var ExecutionContextSchema2 = external_exports.object({ + /** Current user ID (resolved from session) */ + userId: external_exports.string().optional(), + /** Current organization/tenant ID (resolved from session.activeOrganizationId) */ + tenantId: external_exports.string().optional(), + /** User role names (resolved from Member + Role) */ + roles: external_exports.array(external_exports.string()).default([]), + /** Aggregated permission names (resolved from PermissionSet) */ + permissions: external_exports.array(external_exports.string()).default([]), + /** Whether this is a system-level operation (bypasses permission checks) */ + isSystem: external_exports.boolean().default(false), + /** Raw access token (for external API call pass-through) */ + accessToken: external_exports.string().optional(), + /** Database transaction handle */ + transaction: external_exports.unknown().optional(), + /** Request trace ID (for distributed tracing) */ + traceId: external_exports.string().optional() +}); + +// ../../packages/spec/dist/ui/index.mjs +init_zod(); +var I18nObjectSchema = external_exports.object({ + /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ + key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), + /** Default value when translation is not available */ + defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), + /** Interpolation parameters for dynamic translations */ + params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") +}); +var I18nLabelSchema4 = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); +var AriaPropsSchema4 = external_exports.object({ + /** Accessible label for screen readers */ + ariaLabel: I18nLabelSchema4.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), + /** ID of element that describes this component */ + ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), + /** WAI-ARIA role override */ + role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') +}).describe("ARIA accessibility attributes"); +var PluralRuleSchema = external_exports.object({ + /** Translation key for the plural form */ + key: external_exports.string().describe("Translation key"), + /** Form for zero quantity */ + zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), + /** Form for singular (1) */ + one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), + /** Form for dual (2) — used in Arabic, Welsh, etc. */ + two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), + /** Form for few (2-4 in Slavic languages) */ + few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), + /** Form for many (5+ in Slavic languages) */ + many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), + /** Default/fallback form */ + other: external_exports.string().describe('Default plural form (e.g., "{count} items")') +}).describe("ICU plural rules for a translation key"); +var NumberFormatSchema4 = external_exports.object({ + style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), + currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), + unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), + minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), + maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), + useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") +}).describe("Number formatting rules"); +var DateFormatSchema4 = external_exports.object({ + dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), + timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), + timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), + hour12: external_exports.boolean().optional().describe("Use 12-hour format") +}).describe("Date/time formatting rules"); +var LocaleConfigSchema = external_exports.object({ + /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ + code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), + /** Ordered fallback chain for missing translations */ + fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), + /** Text direction */ + direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), + /** Default number formatting */ + numberFormat: NumberFormatSchema4.optional().describe("Default number formatting rules"), + /** Default date formatting */ + dateFormat: DateFormatSchema4.optional().describe("Default date/time formatting rules") +}).describe("Locale configuration"); +var ChartTypeSchema = external_exports.enum([ + // Comparison + "bar", + "horizontal-bar", + "column", + "grouped-bar", + "stacked-bar", + "bi-polar-bar", + // Trend + "line", + "area", + "stacked-area", + "step-line", + "spline", + // Distribution + "pie", + "donut", + "funnel", + "pyramid", + // Relationship + "scatter", + "bubble", + // Composition + "treemap", + "sunburst", + "sankey", + "word-cloud", + // Performance + "gauge", + "solid-gauge", + "metric", + "kpi", + "bullet", + // Geo + "choropleth", + "bubble-map", + "gl-map", + // Advanced + "heatmap", + "radar", + "waterfall", + "box-plot", + "violin", + "candlestick", + "stock", + // Tabular + "table", + "pivot" +]); +var ChartAxisSchema = external_exports.object({ + /** Data field to map to this axis */ + field: external_exports.string().describe("Data field key"), + /** Axis title */ + title: I18nLabelSchema4.optional().describe("Axis display title"), + /** Value formatting (d3-format or similar) */ + format: external_exports.string().optional().describe('Value format string (e.g., "$0,0.00")'), + /** Axis scale settings */ + min: external_exports.number().optional().describe("Minimum value"), + max: external_exports.number().optional().describe("Maximum value"), + stepSize: external_exports.number().optional().describe("Step size for ticks"), + /** Appearance */ + showGridLines: external_exports.boolean().default(true), + position: external_exports.enum(["left", "right", "top", "bottom"]).optional().describe("Axis position"), + /** Logarithmic scale */ + logarithmic: external_exports.boolean().default(false) +}); +var ChartSeriesSchema = external_exports.object({ + /** Field name for values */ + name: external_exports.string().describe("Field name or series identifier"), + /** Display label */ + label: I18nLabelSchema4.optional().describe("Series display label"), + /** Series type override (combo charts) */ + type: ChartTypeSchema.optional().describe("Override chart type for this series"), + /** Specific color */ + color: external_exports.string().optional().describe("Series color (hex/rgb/token)"), + /** Stacking group */ + stack: external_exports.string().optional().describe("Stack identifier to group series"), + /** Axis binding */ + yAxis: external_exports.enum(["left", "right"]).default("left").describe("Bind to specific Y-Axis") +}); +var ChartAnnotationSchema = external_exports.object({ + type: external_exports.enum(["line", "region"]).default("line"), + axis: external_exports.enum(["x", "y"]).default("y"), + value: external_exports.union([external_exports.number(), external_exports.string()]).describe("Start value"), + endValue: external_exports.union([external_exports.number(), external_exports.string()]).optional().describe("End value for regions"), + color: external_exports.string().optional(), + label: I18nLabelSchema4.optional(), + style: external_exports.enum(["solid", "dashed", "dotted"]).default("dashed") +}); +var ChartInteractionSchema = external_exports.object({ + tooltips: external_exports.boolean().default(true), + zoom: external_exports.boolean().default(false), + brush: external_exports.boolean().default(false), + clickAction: external_exports.string().optional().describe("Action ID to trigger on click") +}); +var ChartConfigSchema = external_exports.object({ + /** Chart Type */ + type: ChartTypeSchema, + /** Titles */ + title: I18nLabelSchema4.optional().describe("Chart title"), + subtitle: I18nLabelSchema4.optional().describe("Chart subtitle"), + description: I18nLabelSchema4.optional().describe("Accessibility description"), + /** Axes Mapping */ + xAxis: ChartAxisSchema.optional().describe("X-Axis configuration"), + yAxis: external_exports.array(ChartAxisSchema).optional().describe("Y-Axis configuration (support dual axis)"), + /** Series Configuration */ + series: external_exports.array(ChartSeriesSchema).optional().describe("Defined series configuration"), + /** Appearance */ + colors: external_exports.array(external_exports.string()).optional().describe("Color palette"), + height: external_exports.number().optional().describe("Fixed height in pixels"), + /** Components */ + showLegend: external_exports.boolean().default(true).describe("Display legend"), + showDataLabels: external_exports.boolean().default(false).describe("Display data labels"), + /** Annotations & Reference Lines */ + annotations: external_exports.array(ChartAnnotationSchema).optional(), + /** Interactions */ + interaction: ChartInteractionSchema.optional(), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var BreakpointName2 = external_exports.enum(["xs", "sm", "md", "lg", "xl", "2xl"]); +var BreakpointColumnMapSchema2 = external_exports.object({ + xs: external_exports.number().min(1).max(12).optional(), + sm: external_exports.number().min(1).max(12).optional(), + md: external_exports.number().min(1).max(12).optional(), + lg: external_exports.number().min(1).max(12).optional(), + xl: external_exports.number().min(1).max(12).optional(), + "2xl": external_exports.number().min(1).max(12).optional() +}).describe("Grid columns per breakpoint (1-12)"); +var BreakpointOrderMapSchema2 = external_exports.object({ + xs: external_exports.number().optional(), + sm: external_exports.number().optional(), + md: external_exports.number().optional(), + lg: external_exports.number().optional(), + xl: external_exports.number().optional(), + "2xl": external_exports.number().optional() +}).describe("Display order per breakpoint"); +var ResponsiveConfigSchema2 = external_exports.object({ + /** Minimum breakpoint for visibility */ + breakpoint: BreakpointName2.optional().describe("Minimum breakpoint for visibility"), + /** Hide on specific breakpoints */ + hiddenOn: external_exports.array(BreakpointName2).optional().describe("Hide on these breakpoints"), + /** Grid columns per breakpoint (1-12 column grid) */ + columns: BreakpointColumnMapSchema2.optional().describe("Grid columns per breakpoint"), + /** Display order per breakpoint */ + order: BreakpointOrderMapSchema2.optional().describe("Display order per breakpoint") +}).describe("Responsive layout configuration"); +var PerformanceConfigSchema2 = external_exports.object({ + /** Enable lazy loading for this component */ + lazyLoad: external_exports.boolean().optional().describe("Enable lazy loading (defer rendering until visible)"), + /** Virtual scrolling configuration for large datasets */ + virtualScroll: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable virtual scrolling"), + itemHeight: external_exports.number().optional().describe("Fixed item height in pixels (for estimation)"), + overscan: external_exports.number().optional().describe("Number of extra items to render outside viewport") + }).optional().describe("Virtual scrolling configuration"), + /** Client-side caching strategy */ + cacheStrategy: external_exports.enum([ + "none", + "cache-first", + "network-first", + "stale-while-revalidate" + ]).optional().describe("Client-side data caching strategy"), + /** Enable data prefetching */ + prefetch: external_exports.boolean().optional().describe("Prefetch data before component is visible"), + /** Maximum number of items to render before pagination */ + pageSize: external_exports.number().optional().describe("Number of items per page for pagination"), + /** Debounce interval for user interactions (ms) */ + debounceMs: external_exports.number().optional().describe("Debounce interval for user interactions in milliseconds") +}).describe("Performance optimization configuration"); +var SystemIdentifierSchema5 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' +}).describe("System identifier (lowercase with underscores or dots)"); +var SnakeCaseIdentifierSchema6 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { + message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' +}).describe("Snake case identifier (lowercase with underscores only)"); +external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' +}).describe("Event name (lowercase with dot notation for namespacing)"); +var SharingConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable public sharing"), + publicLink: external_exports.string().optional().describe("Generated public share URL"), + password: external_exports.string().optional().describe("Password required to access shared link"), + allowedDomains: external_exports.array(external_exports.string()).optional().describe('Restrict access to specific email domains (e.g. ["example.com"])'), + expiresAt: external_exports.string().optional().describe("Expiration date/time in ISO 8601 format"), + allowAnonymous: external_exports.boolean().optional().default(false).describe("Allow access without authentication") +}); +var EmbedConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable iframe embedding"), + allowedOrigins: external_exports.array(external_exports.string()).optional().describe('Allowed iframe parent origins (e.g. ["https://example.com"])'), + width: external_exports.string().optional().default("100%").describe("Embed width (CSS value)"), + height: external_exports.string().optional().default("600px").describe("Embed height (CSS value)"), + showHeader: external_exports.boolean().optional().default(true).describe("Show interface header in embed"), + showNavigation: external_exports.boolean().optional().default(false).describe("Show navigation in embed"), + responsive: external_exports.boolean().optional().default(true).describe("Enable responsive resizing") +}); +var BaseNavItemSchema2 = external_exports.object({ + /** Unique identifier for the item */ + id: SnakeCaseIdentifierSchema6.describe("Unique identifier for this navigation item (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema4.describe("Display proper label"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Icon name"), + /** Sort order within the same level (lower numbers appear first) */ + order: external_exports.number().optional().describe("Sort order within the same level (lower = first)"), + /** Badge text or count displayed on the navigation item (e.g. "3", "New") */ + badge: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("Badge text or count displayed on the item"), + /** + * Visibility condition. + * Formula expression returning boolean. + * e.g. "user.is_admin || user.department == 'sales'" + */ + visible: external_exports.string().optional().describe("Visibility formula condition"), + /** Permissions required to see/access this navigation item */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this item") +}); +var ObjectNavItemSchema2 = BaseNavItemSchema2.extend({ + type: external_exports.literal("object"), + objectName: external_exports.string().describe("Target object name"), + viewName: external_exports.string().optional().describe('Default list view to open. Defaults to "all"') +}); +var DashboardNavItemSchema2 = BaseNavItemSchema2.extend({ + type: external_exports.literal("dashboard"), + dashboardName: external_exports.string().describe("Target dashboard name") +}); +var PageNavItemSchema2 = BaseNavItemSchema2.extend({ + type: external_exports.literal("page"), + pageName: external_exports.string().describe("Target custom page component name"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the page context") +}); +var UrlNavItemSchema2 = BaseNavItemSchema2.extend({ + type: external_exports.literal("url"), + url: external_exports.string().describe("Target external URL"), + target: external_exports.enum(["_self", "_blank"]).default("_self").describe("Link target window") +}); +var ReportNavItemSchema2 = BaseNavItemSchema2.extend({ + type: external_exports.literal("report"), + reportName: external_exports.string().describe("Target report name") +}); +var ActionNavItemSchema2 = BaseNavItemSchema2.extend({ + type: external_exports.literal("action"), + actionDef: external_exports.object({ + actionName: external_exports.string().describe("Action machine name to execute"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the action") + }).describe("Action definition to execute when clicked") +}); +var GroupNavItemSchema2 = BaseNavItemSchema2.extend({ + type: external_exports.literal("group"), + expanded: external_exports.boolean().default(false).describe("Default expansion state in sidebar") + // children property is added in the recursive definition below +}); +var NavigationItemSchema2 = external_exports.lazy( + () => external_exports.union([ + ObjectNavItemSchema2.extend({ + children: external_exports.array(NavigationItemSchema2).optional().describe("Child navigation items (e.g. specific views)") + }), + DashboardNavItemSchema2, + PageNavItemSchema2, + UrlNavItemSchema2, + ReportNavItemSchema2, + ActionNavItemSchema2, + GroupNavItemSchema2.extend({ + children: external_exports.array(NavigationItemSchema2).describe("Child navigation items") + }) + ]) +); +var AppBrandingSchema2 = external_exports.object({ + primaryColor: external_exports.string().optional().describe("Primary theme color hex code"), + logo: external_exports.string().optional().describe("Custom logo URL for this app"), + favicon: external_exports.string().optional().describe("Custom favicon URL for this app") +}); +var NavigationAreaSchema2 = external_exports.object({ + /** Unique area identifier */ + id: SnakeCaseIdentifierSchema6.describe("Unique area identifier (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema4.describe("Area display label"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Area icon name"), + /** Sort order among areas (lower = first) */ + order: external_exports.number().optional().describe("Sort order among areas (lower = first)"), + /** Area description */ + description: I18nLabelSchema4.optional().describe("Area description"), + /** + * Visibility condition. + * Formula expression returning boolean. + */ + visible: external_exports.string().optional().describe("Visibility formula condition for this area"), + /** Permissions required to access this area */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this area"), + /** Navigation items within this area */ + navigation: external_exports.array(NavigationItemSchema2).describe("Navigation items within this area") +}); +var AppSchema2 = external_exports.object({ + /** Machine name (id) */ + name: SnakeCaseIdentifierSchema6.describe("App unique machine name (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema4.describe("App display label"), + /** App version */ + version: external_exports.string().optional().describe("App version"), + /** Description */ + description: I18nLabelSchema4.optional().describe("App description"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("App icon used in the App Launcher"), + /** Branding/Theming Configuration */ + branding: AppBrandingSchema2.optional().describe("App-specific branding"), + /** Application status */ + active: external_exports.boolean().optional().default(true).describe("Whether the app is enabled"), + /** Is this the default app for new users? */ + isDefault: external_exports.boolean().optional().default(false).describe("Is default app"), + /** + * Full Navigation Tree — supports unlimited nesting depth. + * Pages are referenced by name via `type: 'page'` items. + * Groups can contain other groups for arbitrary sidebar depth. + * + * For simple apps, use `navigation` directly. + * For enterprise apps with multiple business domains, use `areas` instead. + */ + navigation: external_exports.array(NavigationItemSchema2).optional().describe("Full navigation tree for the app sidebar"), + /** + * Navigation Areas — partitions navigation by business domain. + * Each area defines an independent navigation tree (e.g. Sales, Service, Settings). + * When areas are defined, they take precedence over the top-level `navigation` array. + * + * @example + * ```ts + * areas: [ + * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] }, + * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] }, + * ] + * ``` + */ + areas: external_exports.array(NavigationAreaSchema2).optional().describe("Navigation areas for partitioning navigation by business domain"), + /** + * App-level Home Page Override + * ID of the navigation item to act as the landing page. + * If not set, usually defaults to the first navigation item. + */ + homePageId: external_exports.string().optional().describe("ID of the navigation item to serve as landing page"), + /** + * Access Control + * List of permissions required to access this app. + * Modern replacement for role/profile based assignment. + * Example: ["app.access.crm"] + */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this app"), + /** + * Package Components (For config file convenience) + * In a real monorepo these might be auto-discovered, but here we allow explicit registration. + */ + objects: external_exports.array(external_exports.unknown()).optional().describe("Objects belonging to this app"), + apis: external_exports.array(external_exports.unknown()).optional().describe("Custom APIs belonging to this app"), + /** Sharing configuration for public access */ + sharing: SharingConfigSchema2.optional().describe("Public sharing configuration"), + /** Embed configuration for iframe embedding */ + embed: EmbedConfigSchema2.optional().describe("Iframe embedding configuration"), + /** Mobile navigation mode */ + mobileNavigation: external_exports.object({ + mode: external_exports.enum(["drawer", "bottom_nav", "hamburger"]).default("drawer").describe("Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu"), + bottomNavItems: external_exports.array(external_exports.string()).optional().describe("Navigation item IDs to show in bottom nav (max 5)") + }).optional().describe("Mobile-specific navigation configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes for the application") +}); +var App = { + create: (config4) => AppSchema2.parse(config4) +}; +function defineApp(config4) { + return AppSchema2.parse(config4); +} +var HttpMethod4 = external_exports.enum([ + "GET", + "POST", + "PUT", + "DELETE", + "PATCH", + "HEAD", + "OPTIONS" +]); +var HttpMethodSchema4 = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); +var HttpRequestSchema3 = external_exports.object({ + url: external_exports.string().describe("API endpoint URL"), + method: HttpMethodSchema4.optional().default("GET").describe("HTTP method"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), + body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") +}); +external_exports.object({ + /** + * Enable CORS + */ + enabled: external_exports.boolean().default(true).describe("Enable CORS"), + /** + * Allowed origins (* for all) + */ + origins: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.string()) + ]).default("*").describe("Allowed origins (* for all)"), + /** + * Allowed HTTP methods + */ + methods: external_exports.array(HttpMethod4).optional().describe("Allowed HTTP methods"), + /** + * Allow credentials (cookies, authorization headers) + */ + credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), + /** + * Preflight cache duration in seconds + */ + maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") +}); +external_exports.object({ + /** + * Enable rate limiting + */ + enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), + /** + * Time window in milliseconds + */ + windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), + /** + * Max requests per window + */ + maxRequests: external_exports.number().int().default(100).describe("Max requests per window") +}); +external_exports.object({ + /** + * URL path to serve from + */ + path: external_exports.string().describe("URL path to serve from"), + /** + * Physical directory to serve + */ + directory: external_exports.string().describe("Physical directory to serve"), + /** + * Cache-Control header value + */ + cacheControl: external_exports.string().optional().describe("Cache-Control header value") +}); +var ViewDataSchema2 = external_exports.discriminatedUnion("provider", [ + external_exports.object({ + provider: external_exports.literal("object"), + object: external_exports.string().describe("Target object name") + }), + external_exports.object({ + provider: external_exports.literal("api"), + read: HttpRequestSchema3.optional().describe("Configuration for fetching data"), + write: HttpRequestSchema3.optional().describe("Configuration for submitting data (for forms/editable tables)") + }), + external_exports.object({ + provider: external_exports.literal("value"), + items: external_exports.array(external_exports.unknown()).describe("Static data array") + }) +]); +var ViewFilterRuleSchema2 = external_exports.object({ + /** Field name to filter on */ + field: external_exports.string().describe("Field name to filter on"), + /** Filter operator */ + operator: external_exports.string().describe("Filter operator (e.g. equals, not_equals, contains, this_quarter)"), + /** Filter value (optional for unary operators like is_null, this_quarter) */ + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Filter value") +}).describe("View filter rule"); +var ColumnSummarySchema2 = external_exports.enum([ + "none", + "count", + "count_empty", + "count_filled", + "count_unique", + "percent_empty", + "percent_filled", + "sum", + "avg", + "min", + "max" +]).describe("Aggregation function for column footer summary"); +var ListColumnSchema2 = external_exports.object({ + field: external_exports.string().describe("Field name (snake_case)"), + label: I18nLabelSchema4.optional().describe("Display label override"), + width: external_exports.number().positive().optional().describe("Column width in pixels"), + align: external_exports.enum(["left", "center", "right"]).optional().describe("Text alignment"), + hidden: external_exports.boolean().optional().describe("Hide column by default"), + sortable: external_exports.boolean().optional().describe("Allow sorting by this column"), + resizable: external_exports.boolean().optional().describe("Allow resizing this column"), + wrap: external_exports.boolean().optional().describe("Allow text wrapping"), + type: external_exports.string().optional().describe('Renderer type override (e.g., "currency", "date")'), + /** Pinning (Airtable-style frozen columns) */ + pinned: external_exports.enum(["left", "right"]).optional().describe("Pin/freeze column to left or right side"), + /** Column Footer Summary (Airtable-style aggregation) */ + summary: ColumnSummarySchema2.optional().describe("Footer aggregation function for this column"), + /** Interaction */ + link: external_exports.boolean().optional().describe("Functions as the primary navigation link (triggers View navigation)"), + action: external_exports.string().optional().describe("Registered Action ID to execute when clicked") +}); +var SelectionConfigSchema2 = external_exports.object({ + type: external_exports.enum(["none", "single", "multiple"]).default("none").describe("Selection mode") +}); +var PaginationConfigSchema2 = external_exports.object({ + pageSize: external_exports.number().int().positive().default(25).describe("Number of records per page"), + pageSizeOptions: external_exports.array(external_exports.number().int().positive()).optional().describe("Available page size options") +}); +var RowHeightSchema2 = external_exports.enum([ + "compact", + // Minimal padding, single line + "short", + // Reduced padding + "medium", + // Default padding + "tall", + // Extra padding, multi-line preview + "extra_tall" + // Maximum padding, rich content preview +]).describe("Row height / density setting for list view"); +var GroupingFieldSchema2 = external_exports.object({ + field: external_exports.string().describe("Field name to group by"), + order: external_exports.enum(["asc", "desc"]).default("asc").describe("Group sort order"), + collapsed: external_exports.boolean().default(false).describe("Collapse groups by default") +}); +var GroupingConfigSchema2 = external_exports.object({ + fields: external_exports.array(GroupingFieldSchema2).min(1).describe("Fields to group by (supports up to 3 levels)") +}).describe("Record grouping configuration"); +var GalleryConfigSchema2 = external_exports.object({ + coverField: external_exports.string().optional().describe("Attachment/image field to display as card cover"), + coverFit: external_exports.enum(["cover", "contain"]).default("cover").describe("Image fit mode for card cover"), + cardSize: external_exports.enum(["small", "medium", "large"]).default("medium").describe("Card size in gallery view"), + titleField: external_exports.string().optional().describe("Field to display as card title"), + visibleFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on card body") +}).describe("Gallery/card view configuration"); +var TimelineConfigSchema2 = external_exports.object({ + startDateField: external_exports.string().describe("Field for timeline item start date"), + endDateField: external_exports.string().optional().describe("Field for timeline item end date"), + titleField: external_exports.string().describe("Field to display as timeline item title"), + groupByField: external_exports.string().optional().describe("Field to group timeline rows"), + colorField: external_exports.string().optional().describe("Field to determine item color"), + scale: external_exports.enum(["hour", "day", "week", "month", "quarter", "year"]).default("week").describe("Default timeline scale") +}).describe("Timeline view configuration"); +var ViewSharingSchema2 = external_exports.object({ + type: external_exports.enum(["personal", "collaborative"]).default("collaborative").describe("View ownership type"), + lockedBy: external_exports.string().optional().describe("User who locked the view configuration") +}).describe("View sharing and access configuration"); +var RowColorConfigSchema2 = external_exports.object({ + field: external_exports.string().describe("Field to derive color from (typically a select/status field)"), + colors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Map of field value to color (hex/token)") +}).describe("Row color configuration based on field values"); +var VisualizationTypeSchema2 = external_exports.enum([ + "grid", + "kanban", + "gallery", + "calendar", + "timeline", + "gantt", + "map" +]).describe("Visualization type that users can switch to"); +var UserActionsConfigSchema2 = external_exports.object({ + sort: external_exports.boolean().default(true).describe("Allow users to sort records"), + search: external_exports.boolean().default(true).describe("Allow users to search records"), + filter: external_exports.boolean().default(true).describe("Allow users to filter records"), + rowHeight: external_exports.boolean().default(true).describe("Allow users to toggle row height/density"), + addRecordForm: external_exports.boolean().default(false).describe("Add records through a form instead of inline"), + buttons: external_exports.array(external_exports.string()).optional().describe("Custom action button IDs to show in the toolbar") +}).describe("User action toggles for the view toolbar"); +var AppearanceConfigSchema2 = external_exports.object({ + showDescription: external_exports.boolean().default(true).describe("Show the view description text"), + allowedVisualizations: external_exports.array(VisualizationTypeSchema2).optional().describe('Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])') +}).describe("Appearance and visualization configuration"); +var ViewTabSchema2 = external_exports.object({ + name: SnakeCaseIdentifierSchema6.describe("Tab identifier (snake_case)"), + label: I18nLabelSchema4.optional().describe("Display label"), + icon: external_exports.string().optional().describe("Tab icon name"), + view: external_exports.string().optional().describe("Referenced list view name from listViews"), + filter: external_exports.array(ViewFilterRuleSchema2).optional().describe("Tab-specific filter criteria"), + order: external_exports.number().int().min(0).optional().describe("Tab display order"), + pinned: external_exports.boolean().default(false).describe("Pin tab (cannot be removed by users)"), + isDefault: external_exports.boolean().default(false).describe("Set as the default active tab"), + visible: external_exports.boolean().default(true).describe("Tab visibility") +}).describe("Tab configuration for multi-tab view interface"); +var AddRecordConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Show the add record entry point"), + position: external_exports.enum(["top", "bottom", "both"]).default("bottom").describe("Position of the add record button"), + mode: external_exports.enum(["inline", "form", "modal"]).default("inline").describe("How to add a new record"), + formView: external_exports.string().optional().describe('Named form view to use when mode is "form" or "modal"') +}).describe("Add record entry point configuration"); +var KanbanConfigSchema2 = external_exports.object({ + groupByField: external_exports.string().describe("Field to group columns by (usually status/select)"), + summarizeField: external_exports.string().optional().describe("Field to sum at top of column (e.g. amount)"), + columns: external_exports.array(external_exports.string()).describe("Fields to show on cards") +}); +var CalendarConfigSchema2 = external_exports.object({ + startDateField: external_exports.string(), + endDateField: external_exports.string().optional(), + titleField: external_exports.string(), + colorField: external_exports.string().optional() +}); +var GanttConfigSchema2 = external_exports.object({ + startDateField: external_exports.string(), + endDateField: external_exports.string(), + titleField: external_exports.string(), + progressField: external_exports.string().optional(), + dependenciesField: external_exports.string().optional() +}); +var NavigationModeSchema2 = external_exports.enum([ + "page", + // Navigate to a new route (default) + "drawer", + // Open details in a side drawer/panel + "modal", + // Open details in a modal dialog + "split", + // Show details side-by-side with the list (master-detail) + "popover", + // Show details in a popover (lightweight) + "new_window", + // Open in new browser tab/window + "none" + // No navigation (read-only list) +]); +var NavigationConfigSchema2 = external_exports.object({ + mode: NavigationModeSchema2.default("page"), + /** Target View Config */ + view: external_exports.string().optional().describe('Name of the form view to use for details (e.g. "summary_view", "edit_form")'), + /** Interaction Triggers */ + preventNavigation: external_exports.boolean().default(false).describe("Disable standard navigation entirely"), + openNewTab: external_exports.boolean().default(false).describe("Force open in new tab (applies to page mode)"), + /** Dimensions (for modal/drawer) */ + width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Width of the drawer/modal (e.g. "600px", "50%")') +}); +var ListViewSchema2 = external_exports.object({ + name: SnakeCaseIdentifierSchema6.optional().describe("Internal view name (lowercase snake_case)"), + label: I18nLabelSchema4.optional(), + // Display label override (supports i18n) + type: external_exports.enum([ + "grid", + // Standard Data Table + "kanban", + // Board / Columns + "gallery", + // Card Deck / Masonry + "calendar", + // Monthly/Weekly/Daily + "timeline", + // Chronological Stream (Feed) + "gantt", + // Project Timeline + "map" + // Geospatial + ]).default("grid"), + /** Data Source Configuration */ + data: ViewDataSchema2.optional().describe('Data source configuration (defaults to "object" provider)'), + /** Shared Query Config */ + columns: external_exports.union([ + external_exports.array(external_exports.string()), + // Legacy: simple field names + external_exports.array(ListColumnSchema2) + // Enhanced: detailed column config + ]).describe("Fields to display as columns"), + filter: external_exports.array(ViewFilterRuleSchema2).optional().describe("Filter criteria (JSON Rules)"), + sort: external_exports.union([ + external_exports.string(), + //Legacy "field desc" + external_exports.array(external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]) + })) + ]).optional(), + /** Search & Filter */ + searchableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for search"), + filterableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for end-user filtering in the top bar"), + /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */ + quickFilters: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name to filter by"), + label: external_exports.string().optional().describe("Display label for the chip"), + operator: external_exports.enum(["equals", "not_equals", "contains", "in", "is_null", "is_not_null"]).default("equals").describe("Filter operator"), + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Preset filter value") + })).optional().describe("One-click filter chips for quick record filtering"), + /** Grid Features */ + resizable: external_exports.boolean().optional().describe("Enable column resizing"), + striped: external_exports.boolean().optional().describe("Striped row styling"), + bordered: external_exports.boolean().optional().describe("Show borders"), + /** Selection */ + selection: SelectionConfigSchema2.optional().describe("Row selection configuration"), + /** Navigation / Interaction */ + navigation: NavigationConfigSchema2.optional().describe("Configuration for item click navigation (page, drawer, modal, etc.)"), + /** Pagination */ + pagination: PaginationConfigSchema2.optional().describe("Pagination configuration"), + /** Type Specific Config */ + kanban: KanbanConfigSchema2.optional(), + calendar: CalendarConfigSchema2.optional(), + gantt: GanttConfigSchema2.optional(), + gallery: GalleryConfigSchema2.optional(), + timeline: TimelineConfigSchema2.optional(), + /** View Metadata (Airtable-style view management) */ + description: I18nLabelSchema4.optional().describe("View description for documentation/tooltips"), + sharing: ViewSharingSchema2.optional().describe("View sharing and access configuration"), + /** Row Height / Density (Airtable-style) */ + rowHeight: RowHeightSchema2.optional().describe("Row height / density setting"), + /** Record Grouping (Airtable-style) */ + grouping: GroupingConfigSchema2.optional().describe("Group records by one or more fields"), + /** Row Color (Airtable-style) */ + rowColor: RowColorConfigSchema2.optional().describe("Color rows based on field value"), + /** Field Visibility & Ordering per View (Airtable-style) */ + hiddenFields: external_exports.array(external_exports.string()).optional().describe("Fields to hide in this specific view"), + fieldOrder: external_exports.array(external_exports.string()).optional().describe("Explicit field display order for this view"), + /** Row & Bulk Actions */ + rowActions: external_exports.array(external_exports.string()).optional().describe("Actions available for individual row items"), + bulkActions: external_exports.array(external_exports.string()).optional().describe("Actions available when multiple rows are selected"), + /** Performance */ + virtualScroll: external_exports.boolean().optional().describe("Enable virtual scrolling for large datasets"), + /** Conditional Formatting */ + conditionalFormatting: external_exports.array(external_exports.object({ + condition: external_exports.string().describe("Condition expression to evaluate"), + style: external_exports.record(external_exports.string(), external_exports.string()).describe("CSS styles to apply when condition is true") + })).optional().describe("Conditional formatting rules for list rows"), + /** Inline Edit */ + inlineEdit: external_exports.boolean().optional().describe("Allow inline editing of records directly in the list view"), + /** Export */ + exportOptions: external_exports.array(external_exports.enum(["csv", "xlsx", "pdf", "json"])).optional().describe("Available export format options"), + /** User Actions (Airtable Interface parity) */ + userActions: UserActionsConfigSchema2.optional().describe("User action toggles for the view toolbar"), + /** Appearance (Airtable Interface parity) */ + appearance: AppearanceConfigSchema2.optional().describe("Appearance and visualization configuration"), + /** Tabs (Airtable Interface parity) */ + tabs: external_exports.array(ViewTabSchema2).optional().describe("Tab definitions for multi-tab view interface"), + /** Add Record (Airtable Interface parity) */ + addRecord: AddRecordConfigSchema2.optional().describe("Add record entry point configuration"), + /** Record Count Display (Airtable Interface parity) */ + showRecordCount: external_exports.boolean().optional().describe("Show record count at the bottom of the list"), + /** Advanced: Allow Printing (Airtable Interface parity) */ + allowPrinting: external_exports.boolean().optional().describe("Allow users to print the view"), + /** Empty State */ + emptyState: external_exports.object({ + title: I18nLabelSchema4.optional(), + message: I18nLabelSchema4.optional(), + icon: external_exports.string().optional() + }).optional().describe("Empty state configuration when no records found"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes for the list view"), + /** Responsive layout overrides per breakpoint */ + responsive: ResponsiveConfigSchema2.optional().describe("Responsive layout configuration"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema2.optional().describe("Performance optimization settings") +}); +var FormFieldSchema2 = external_exports.object({ + field: external_exports.string().describe("Field name (snake_case)"), + label: I18nLabelSchema4.optional().describe("Display label override"), + placeholder: I18nLabelSchema4.optional().describe("Placeholder text"), + helpText: I18nLabelSchema4.optional().describe("Help/hint text"), + readonly: external_exports.boolean().optional().describe("Read-only override"), + required: external_exports.boolean().optional().describe("Required override"), + hidden: external_exports.boolean().optional().describe("Hidden override"), + colSpan: external_exports.number().int().min(1).max(4).optional().describe("Column span in grid layout (1-4)"), + widget: external_exports.string().optional().describe("Custom widget/component name"), + dependsOn: external_exports.string().optional().describe("Parent field name for cascading"), + visibleOn: external_exports.string().optional().describe("Visibility condition expression") +}); +var FormSectionSchema2 = external_exports.object({ + label: I18nLabelSchema4.optional(), + collapsible: external_exports.boolean().default(false), + collapsed: external_exports.boolean().default(false), + columns: external_exports.enum(["1", "2", "3", "4"]).default("2").transform((val) => parseInt(val)), + fields: external_exports.array(external_exports.union([ + external_exports.string(), + // Legacy: simple field name + FormFieldSchema2 + // Enhanced: detailed field config + ])) +}); +var FormViewSchema2 = external_exports.object({ + type: external_exports.enum([ + "simple", + // Single column or sections + "tabbed", + // Tabs + "wizard", + // Step by step + "split", + // Master-Detail split + "drawer", + // Side panel + "modal" + // Dialog + ]).default("simple"), + /** Data Source Configuration */ + data: ViewDataSchema2.optional().describe('Data source configuration (defaults to "object" provider)'), + sections: external_exports.array(FormSectionSchema2).optional(), + // For simple layout + groups: external_exports.array(FormSectionSchema2).optional(), + // Legacy support -> alias to sections + /** Default Sort for Related Lists (e.g., sort child records by date) */ + defaultSort: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + order: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction") + })).optional().describe("Default sort order for related list views within this form"), + /** Public form sharing configuration */ + sharing: SharingConfigSchema2.optional().describe("Public sharing configuration for this form"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes for the form view") +}); +var ViewSchema2 = external_exports.object({ + list: ListViewSchema2.optional(), + // Default list view + form: FormViewSchema2.optional(), + // Default form view + listViews: external_exports.record(external_exports.string(), ListViewSchema2).optional().describe("Additional named list views"), + formViews: external_exports.record(external_exports.string(), FormViewSchema2).optional().describe("Additional named form views") +}); +var FieldReferenceSchema3 = external_exports.object({ + $field: external_exports.string().describe("Field Reference/Column Name") +}); +external_exports.object({ + /** Equal to (default) - SQL: = | MongoDB: $eq */ + $eq: external_exports.any().optional(), + /** Not equal to - SQL: <> or != | MongoDB: $ne */ + $ne: external_exports.any().optional() +}); +external_exports.object({ + /** Greater than - SQL: > | MongoDB: $gt */ + $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), + /** Greater than or equal to - SQL: >= | MongoDB: $gte */ + $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), + /** Less than - SQL: < | MongoDB: $lt */ + $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), + /** Less than or equal to - SQL: <= | MongoDB: $lte */ + $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional() +}); +external_exports.object({ + /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */ + $in: external_exports.array(external_exports.any()).optional(), + /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */ + $nin: external_exports.array(external_exports.any()).optional() +}); +external_exports.object({ + /** Between (inclusive) - takes [min, max] array */ + $between: external_exports.tuple([ + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]), + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]) + ]).optional() +}); +external_exports.object({ + /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */ + $contains: external_exports.string().optional(), + /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */ + $notContains: external_exports.string().optional(), + /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */ + $startsWith: external_exports.string().optional(), + /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */ + $endsWith: external_exports.string().optional() +}); +external_exports.object({ + /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */ + $null: external_exports.boolean().optional(), + /** Field exists check (primarily for NoSQL) - MongoDB: $exists */ + $exists: external_exports.boolean().optional() +}); +var FieldOperatorsSchema3 = external_exports.object({ + // Equality + $eq: external_exports.any().optional(), + $ne: external_exports.any().optional(), + // Comparison (numeric/date) + $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), + $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), + $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), + $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), + // Set & Range + $in: external_exports.array(external_exports.any()).optional(), + $nin: external_exports.array(external_exports.any()).optional(), + $between: external_exports.tuple([ + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]), + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]) + ]).optional(), + // String-specific + $contains: external_exports.string().optional(), + $notContains: external_exports.string().optional(), + $startsWith: external_exports.string().optional(), + $endsWith: external_exports.string().optional(), + // Special + $null: external_exports.boolean().optional(), + $exists: external_exports.boolean().optional() +}); +var FilterConditionSchema3 = external_exports.lazy( + () => external_exports.record(external_exports.string(), external_exports.unknown()).and( + external_exports.object({ + $and: external_exports.array(FilterConditionSchema3).optional(), + $or: external_exports.array(FilterConditionSchema3).optional(), + $not: FilterConditionSchema3.optional() + }) + ) +); +external_exports.object({ + where: FilterConditionSchema3.optional() +}); +var NormalizedFilterSchema3 = external_exports.lazy( + () => external_exports.object({ + $and: external_exports.array( + external_exports.union([ + // Field condition: { field: { $op: value } } + external_exports.record(external_exports.string(), FieldOperatorsSchema3), + // Nested logical group + NormalizedFilterSchema3 + ]) + ).optional(), + $or: external_exports.array( + external_exports.union([ + external_exports.record(external_exports.string(), FieldOperatorsSchema3), + NormalizedFilterSchema3 + ]) + ).optional(), + $not: external_exports.union([ + external_exports.record(external_exports.string(), FieldOperatorsSchema3), + NormalizedFilterSchema3 + ]).optional() + }) +); +var WidgetColorVariantSchema = external_exports.enum([ + "default", + "blue", + "teal", + "orange", + "purple", + "success", + "warning", + "danger" +]).describe("Widget color variant"); +var WidgetActionTypeSchema = external_exports.enum([ + "script", + "url", + "modal", + "flow", + "api" +]).describe("Widget action type"); +var DashboardHeaderActionSchema = external_exports.object({ + /** Action label */ + label: I18nLabelSchema4.describe("Action button label"), + /** Action URL or target */ + actionUrl: external_exports.string().describe("URL or target for the action"), + /** Action type */ + actionType: WidgetActionTypeSchema.optional().describe("Type of action"), + /** Icon identifier */ + icon: external_exports.string().optional().describe("Icon identifier for the action button") +}).describe("Dashboard header action"); +var DashboardHeaderSchema = external_exports.object({ + /** Whether to show the dashboard title in the header */ + showTitle: external_exports.boolean().default(true).describe("Show dashboard title in header"), + /** Whether to show the dashboard description in the header */ + showDescription: external_exports.boolean().default(true).describe("Show dashboard description in header"), + /** Action buttons displayed in the header */ + actions: external_exports.array(DashboardHeaderActionSchema).optional().describe("Header action buttons") +}).describe("Dashboard header configuration"); +var WidgetMeasureSchema = external_exports.object({ + /** Value field to aggregate */ + valueField: external_exports.string().describe("Field to aggregate"), + /** Aggregate function */ + aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).default("count").describe("Aggregate function"), + /** Display label for the measure */ + label: I18nLabelSchema4.optional().describe("Measure display label"), + /** Number format string (e.g., "$0,0.00", "0.0%") */ + format: external_exports.string().optional().describe("Number format string") +}).describe("Widget measure definition"); +var DashboardWidgetSchema = external_exports.object({ + /** Unique widget identifier (snake_case, used for targetWidgets references) */ + id: SnakeCaseIdentifierSchema6.describe("Unique widget identifier (snake_case)"), + /** Widget Title */ + title: I18nLabelSchema4.optional().describe("Widget title"), + /** Widget Description (displayed below the title) */ + description: I18nLabelSchema4.optional().describe("Widget description text below the header"), + /** Visualization Type */ + type: ChartTypeSchema.default("metric").describe("Visualization type"), + /** Chart Configuration */ + chartConfig: ChartConfigSchema.optional().describe("Chart visualization configuration"), + /** Color variant for the widget (e.g., KPI card accent color) */ + colorVariant: WidgetColorVariantSchema.optional().describe("Widget color variant for theming"), + /** Action URL for the widget header action button */ + actionUrl: external_exports.string().optional().describe("URL or target for the widget action button"), + /** Action type for the widget header action button */ + actionType: WidgetActionTypeSchema.optional().describe("Type of action for the widget action button"), + /** Icon for the widget header action button */ + actionIcon: external_exports.string().optional().describe("Icon identifier for the widget action button"), + /** Data Source Object */ + object: external_exports.string().optional().describe("Data source object name"), + /** Data Filter (MongoDB-style FilterCondition) */ + filter: FilterConditionSchema3.optional().describe("Data filter criteria"), + /** Category Field (X-Axis / Group By) */ + categoryField: external_exports.string().optional().describe("Field for grouping (X-Axis)"), + /** Value Field (Y-Axis) */ + valueField: external_exports.string().optional().describe("Field for values (Y-Axis)"), + /** Aggregate operation */ + aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).optional().default("count").describe("Aggregate function"), + /** Multi-measure definitions for pivot/matrix widgets */ + measures: external_exports.array(WidgetMeasureSchema).optional().describe("Multiple measures for pivot/matrix analysis"), + /** + * Layout Position (React-Grid-Layout style) + * x: column (0-11) + * y: row + * w: width (1-12) + * h: height + */ + layout: external_exports.object({ + x: external_exports.number(), + y: external_exports.number(), + w: external_exports.number(), + h: external_exports.number() + }).describe("Grid layout position"), + /** Widget specific options (colors, legend, etc.) */ + options: external_exports.unknown().optional().describe("Widget specific configuration"), + /** Responsive layout overrides per breakpoint */ + responsive: ResponsiveConfigSchema2.optional().describe("Responsive layout configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var GlobalFilterOptionsFromSchema = external_exports.object({ + /** Source object name to fetch options from */ + object: external_exports.string().describe("Source object name"), + /** Field to use as option value */ + valueField: external_exports.string().describe("Field to use as option value"), + /** Field to use as option label */ + labelField: external_exports.string().describe("Field to use as option label"), + /** Optional filter to apply when fetching options */ + filter: FilterConditionSchema3.optional().describe("Filter to apply to source object") +}).describe("Dynamic filter options from object"); +var GlobalFilterSchema = external_exports.object({ + /** Field name to filter on */ + field: external_exports.string().describe("Field name to filter on"), + /** Display label for the filter */ + label: I18nLabelSchema4.optional().describe("Display label for the filter"), + /** Filter input type */ + type: external_exports.enum(["text", "select", "date", "number", "lookup"]).optional().describe("Filter input type"), + /** Static options for select/lookup filters */ + options: external_exports.array(external_exports.object({ + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).describe("Option value"), + label: I18nLabelSchema4 + })).optional().describe("Static filter options"), + /** Dynamic data binding for filter options */ + optionsFrom: GlobalFilterOptionsFromSchema.optional().describe("Dynamic filter options from object"), + /** Default filter value */ + defaultValue: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Default filter value"), + /** Filter application scope */ + scope: external_exports.enum(["dashboard", "widget"]).default("dashboard").describe("Filter application scope"), + /** Widget IDs to apply this filter to (when scope is widget) */ + targetWidgets: external_exports.array(external_exports.string()).optional().describe("Widget IDs to apply this filter to") +}); +var DashboardSchema = external_exports.object({ + /** Machine name */ + name: SnakeCaseIdentifierSchema6.describe("Dashboard unique name"), + /** Display label */ + label: I18nLabelSchema4.describe("Dashboard label"), + /** Description */ + description: I18nLabelSchema4.optional().describe("Dashboard description"), + /** Structured header configuration */ + header: DashboardHeaderSchema.optional().describe("Dashboard header configuration"), + /** Collection of widgets */ + widgets: external_exports.array(DashboardWidgetSchema).describe("Widgets to display"), + /** Auto-refresh */ + refreshInterval: external_exports.number().optional().describe("Auto-refresh interval in seconds"), + /** Dashboard Date Range (Global time filter) */ + dateRange: external_exports.object({ + field: external_exports.string().optional().describe("Default date field name for time-based filtering"), + defaultRange: external_exports.enum(["today", "yesterday", "this_week", "last_week", "this_month", "last_month", "this_quarter", "last_quarter", "this_year", "last_year", "last_7_days", "last_30_days", "last_90_days", "custom"]).default("this_month").describe("Default date range preset"), + allowCustomRange: external_exports.boolean().default(true).describe("Allow users to pick a custom date range") + }).optional().describe("Global dashboard date range filter configuration"), + /** Global Filters */ + globalFilters: external_exports.array(GlobalFilterSchema).optional().describe("Global filters that apply to all widgets in the dashboard"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema2.optional().describe("Performance optimization settings") +}); +var ReportType = external_exports.enum([ + "tabular", + // Simple list + "summary", + // Grouped by row + "matrix", + // Grouped by row and column + "joined" + // Joined multiple blocks +]); +var ReportColumnSchema = external_exports.object({ + field: external_exports.string().describe("Field name"), + label: I18nLabelSchema4.optional().describe("Override label"), + aggregate: external_exports.enum(["sum", "avg", "max", "min", "count", "unique"]).optional().describe("Aggregation function"), + /** Responsive visibility/priority per breakpoint */ + responsive: ResponsiveConfigSchema2.optional().describe("Responsive visibility for this column") +}); +var ReportGroupingSchema = external_exports.object({ + field: external_exports.string().describe("Field to group by"), + sortOrder: external_exports.enum(["asc", "desc"]).default("asc"), + dateGranularity: external_exports.enum(["day", "week", "month", "quarter", "year"]).optional().describe("For date fields") +}); +var ReportChartSchema = ChartConfigSchema.extend({ + /** Report-specific chart configuration */ + xAxis: external_exports.string().describe("Grouping field for X-Axis"), + yAxis: external_exports.string().describe("Summary field for Y-Axis"), + groupBy: external_exports.string().optional().describe("Additional grouping field") +}); +var ReportSchema = external_exports.object({ + /** Identity */ + name: SnakeCaseIdentifierSchema6.describe("Report unique name"), + label: I18nLabelSchema4.describe("Report label"), + description: I18nLabelSchema4.optional(), + /** Data Source */ + objectName: external_exports.string().describe("Primary object"), + /** Report Configuration */ + type: ReportType.default("tabular").describe("Report format type"), + columns: external_exports.array(ReportColumnSchema).describe("Columns to display"), + /** Grouping (for Summary/Matrix) */ + groupingsDown: external_exports.array(ReportGroupingSchema).optional().describe("Row groupings"), + groupingsAcross: external_exports.array(ReportGroupingSchema).optional().describe("Column groupings (Matrix only)"), + /** Filtering (MongoDB-style FilterCondition) */ + filter: FilterConditionSchema3.optional().describe("Filter criteria"), + /** Visualization */ + chart: ReportChartSchema.optional().describe("Embedded chart configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema2.optional().describe("Performance optimization settings") +}); +var EncryptionAlgorithmSchema5 = external_exports.enum([ + "aes-256-gcm", + "aes-256-cbc", + "chacha20-poly1305" +]).describe("Supported encryption algorithm"); +var KeyManagementProviderSchema5 = external_exports.enum([ + "local", + "aws-kms", + "azure-key-vault", + "gcp-kms", + "hashicorp-vault" +]).describe("Key management service provider"); +var KeyRotationPolicySchema5 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), + frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), + retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), + autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") +}).describe("Policy for automatic encryption key rotation"); +var EncryptionConfigSchema5 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), + algorithm: EncryptionAlgorithmSchema5.default("aes-256-gcm").describe("Encryption algorithm"), + keyManagement: external_exports.object({ + provider: KeyManagementProviderSchema5.describe("Key management service provider"), + keyId: external_exports.string().optional().describe("Key identifier in the provider"), + rotationPolicy: KeyRotationPolicySchema5.optional().describe("Key rotation policy") + }).describe("Key management configuration"), + scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), + deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), + searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") +}).describe("Field-level encryption configuration"); +external_exports.object({ + fieldName: external_exports.string().describe("Name of the field to encrypt"), + encryptionConfig: EncryptionConfigSchema5.describe("Encryption settings for this field"), + indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") +}).describe("Per-field encryption assignment"); +var MaskingStrategySchema5 = external_exports.enum([ + "redact", + // Complete redaction: **** + "partial", + // Partial masking: 138****5678 + "hash", + // Hash value: sha256(value) + "tokenize", + // Tokenization: token-12345 + "randomize", + // Randomize: generate random value + "nullify", + // Null value: null + "substitute" + // Substitute with dummy data +]).describe("Data masking strategy for PII protection"); +var MaskingRuleSchema5 = external_exports.object({ + field: external_exports.string().describe("Field name to apply masking to"), + strategy: MaskingStrategySchema5.describe("Masking strategy to use"), + pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), + preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), + preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), + roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), + exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") +}).describe("Masking rule for a single field"); +external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable data masking"), + rules: external_exports.array(MaskingRuleSchema5).describe("List of field-level masking rules"), + auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") +}).describe("Top-level data masking configuration for PII protection"); +var FieldType5 = external_exports.enum([ + // Core Text + "text", + "textarea", + "email", + "url", + "phone", + "password", + // Rich Content + "markdown", + "html", + "richtext", + // Numbers + "number", + "currency", + "percent", + // Date & Time + "date", + "datetime", + "time", + // Logic + "boolean", + "toggle", + // Toggle is a distinct UI from checkbox + // Selection + "select", + // Single select dropdown + "multiselect", + // Multi select (often tags) + "radio", + // Radio group + "checkboxes", + // Checkbox group + // Relational + "lookup", + "master_detail", + // Dynamic reference + "tree", + // Hierarchical reference + // Media + "image", + "file", + "avatar", + "video", + "audio", + // Calculated / System + "formula", + "summary", + "autonumber", + // Enhanced Types + "location", + // GPS coordinates + "address", + // Structured address + "code", + // Code editor (JSON/SQL/JS) + "json", + // Structured JSON data + "color", + // Color picker + "rating", + // Star rating + "slider", + // Numeric slider + "signature", + // Digital signature + "qrcode", + // QR code / Barcode + "progress", + // Progress bar + "tags", + // Simple tag list + // AI/ML Types + "vector" + // Vector embeddings for AI/ML (semantic search, RAG) +]); +var SelectOptionSchema5 = external_exports.object({ + label: external_exports.string().describe("Display label (human-readable, any case allowed)"), + value: SystemIdentifierSchema5.describe("Stored value (lowercase machine identifier)"), + color: external_exports.string().optional().describe("Color code for badges/charts"), + default: external_exports.boolean().optional().describe("Is default option") +}); +external_exports.object({ + latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), + longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), + altitude: external_exports.number().optional().describe("Altitude in meters"), + accuracy: external_exports.number().optional().describe("Accuracy in meters") +}); +var CurrencyConfigSchema5 = external_exports.object({ + precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), + currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), + defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") +}); +external_exports.object({ + value: external_exports.number().describe("Monetary amount"), + currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") +}); +external_exports.object({ + street: external_exports.string().optional().describe("Street address"), + city: external_exports.string().optional().describe("City name"), + state: external_exports.string().optional().describe("State/Province"), + postalCode: external_exports.string().optional().describe("Postal/ZIP code"), + country: external_exports.string().optional().describe("Country name or code"), + countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), + formatted: external_exports.string().optional().describe("Formatted address string") +}); +var VectorConfigSchema5 = external_exports.object({ + dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), + distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), + normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), + indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), + indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") +}); +var FileAttachmentConfigSchema5 = external_exports.object({ + /** File Size Limits */ + minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), + maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), + /** File Type Restrictions */ + allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), + blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), + allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), + blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), + /** Virus Scanning */ + virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), + virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), + virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), + quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), + /** Storage Configuration */ + storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), + storageBucket: external_exports.string().optional().describe("Target bucket name"), + storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), + /** Image-Specific Validation */ + imageValidation: external_exports.object({ + minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), + maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), + minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), + maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), + aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), + generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), + thumbnailSizes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), + width: external_exports.number().min(1).describe("Thumbnail width in pixels"), + height: external_exports.number().min(1).describe("Thumbnail height in pixels"), + crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") + })).optional().describe("Thumbnail size configurations"), + preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), + autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") + }).optional().describe("Image-specific validation rules"), + /** Upload Behavior */ + allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), + allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), + allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), + requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), + /** Metadata Extraction */ + extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), + extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), + /** Versioning */ + versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), + maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), + /** Access Control */ + publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), + presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") +}).refine((data) => { + if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { + return false; + } + return true; +}, { + message: "minSize must be less than or equal to maxSize" +}).refine((data) => { + if (data.virusScanProvider !== void 0 && data.virusScan !== true) { + return false; + } + return true; +}, { + message: "virusScanProvider requires virusScan to be enabled" +}); +var DataQualityRulesSchema5 = external_exports.object({ + /** Enforce uniqueness constraint */ + uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), + /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ + completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), + /** Accuracy validation against authoritative source */ + accuracy: external_exports.object({ + source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), + threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") + }).optional().describe("Accuracy validation configuration") +}); +var ComputedFieldCacheSchema5 = external_exports.object({ + /** Enable caching for this computed field */ + enabled: external_exports.boolean().describe("Enable caching for computed field results"), + /** Time-to-live in seconds */ + ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), + /** Array of field paths that trigger cache invalidation when changed */ + invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') +}); +var FieldSchema4 = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), + label: external_exports.string().optional().describe("Human readable label"), + type: FieldType5.describe("Field Data Type"), + description: external_exports.string().optional().describe("Tooltip/Help text"), + format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), + /** Storage Layer Mapping */ + columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), + /** Database Constraints */ + required: external_exports.boolean().default(false).describe("Is required"), + searchable: external_exports.boolean().default(false).describe("Is searchable"), + multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), + unique: external_exports.boolean().default(false).describe("Is unique constraint"), + defaultValue: external_exports.unknown().optional().describe("Default value"), + /** Text/String Constraints */ + maxLength: external_exports.number().optional().describe("Max character length"), + minLength: external_exports.number().optional().describe("Min character length"), + /** Number Constraints */ + precision: external_exports.number().optional().describe("Total digits"), + scale: external_exports.number().optional().describe("Decimal places"), + min: external_exports.number().optional().describe("Minimum value"), + max: external_exports.number().optional().describe("Maximum value"), + /** Selection Options */ + options: external_exports.array(SelectOptionSchema5).optional().describe("Static options for select/multiselect"), + /** + * Relationship Config + * + * Used by `lookup` and `master_detail` field types to define cross-object references. + * The `reference` property is **required** for these types — it identifies the target + * object whose records this field links to. The engine uses `reference` during $expand + * post-processing to resolve foreign key IDs into full related objects via batch queries. + * + * For `master_detail` fields, the parent record controls the lifecycle of child records + * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. + */ + reference: external_exports.string().optional().describe( + "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." + ), + referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), + writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), + deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), + /** Calculation */ + expression: external_exports.string().optional().describe("Formula expression"), + summaryOperations: external_exports.object({ + object: external_exports.string().describe("Source child object name for roll-up"), + field: external_exports.string().describe("Field on child object to aggregate"), + function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") + }).optional().describe("Roll-up summary definition"), + /** Enhanced Field Type Configurations */ + // Code field config + language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), + theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), + lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), + // Rating field config + maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), + allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), + // Location field config + displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), + allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), + // Address field config + addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), + // Color field config + colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), + allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), + presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), + // Slider field config + step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), + showValue: external_exports.boolean().optional().describe("Display current value on slider"), + marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), + // QR Code / Barcode field config + // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' + // Runtime validation should enforce this constraint + barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), + qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), + displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), + allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), + // Currency field config + currencyConfig: CurrencyConfigSchema5.optional().describe("Configuration for currency field type"), + // Vector field config + vectorConfig: VectorConfigSchema5.optional().describe("Configuration for vector field type (AI/ML embeddings)"), + // File attachment field config + fileAttachmentConfig: FileAttachmentConfigSchema5.optional().describe("Configuration for file and attachment field types"), + /** Enhanced Security & Compliance */ + // Encryption configuration + encryptionConfig: EncryptionConfigSchema5.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), + // Data masking rules + maskingRule: MaskingRuleSchema5.optional().describe("Data masking rules for PII protection"), + // Audit trail + auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), + /** Field Dependencies & Relationships */ + // Field dependencies + dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), + /** Computed Field Optimization */ + // Computed field caching + cached: ComputedFieldCacheSchema5.optional().describe("Caching configuration for computed/formula fields"), + /** Data Quality & Governance */ + // Data quality rules + dataQuality: DataQualityRulesSchema5.optional().describe("Data quality validation and monitoring rules"), + /** Layout & Grouping */ + group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), + /** Conditional Requirements */ + conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), + /** Security & Visibility */ + hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), + readonly: external_exports.boolean().default(false).describe("Read-only in UI"), + sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), + inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), + trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), + caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), + autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), + /** Indexing */ + index: external_exports.boolean().default(false).describe("Create standard database index"), + externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") +}); +var ActionParamSchema4 = external_exports.object({ + name: external_exports.string(), + label: I18nLabelSchema4, + type: FieldType5, + required: external_exports.boolean().default(false), + options: external_exports.array(external_exports.object({ label: I18nLabelSchema4, value: external_exports.string() })).optional() +}); +var ActionType4 = external_exports.enum(["script", "url", "modal", "flow", "api"]); +var TARGET_REQUIRED_TYPES4 = new Set( + ActionType4.options.filter((t) => t !== "script") +); +var ActionSchema4 = external_exports.object({ + /** Machine name of the action */ + name: SnakeCaseIdentifierSchema6.describe("Machine name (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema4.describe("Display label"), + /** Target object this action belongs to (optional, snake_case) */ + objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Icon name"), + /** Where does this action appear? */ + locations: external_exports.array(external_exports.enum([ + "list_toolbar", + "list_item", + "record_header", + "record_more", + "record_related", + "global_nav" + ])).optional().describe("Locations where this action is visible"), + /** + * Visual Component Type + * Defaults to 'button' or 'menu_item' based on location, + * but can be overridden. + */ + component: external_exports.enum([ + "action:button", + // Standard Button + "action:icon", + // Icon only + "action:menu", + // Dropdown menu + "action:group" + // Button Group + ]).optional().describe("Visual component override"), + /** What type of interaction? */ + type: ActionType4.default("script").describe("Action functionality type"), + /** + * Payload / Target — the canonical binding for the action handler. + * Required for url, flow, modal, and api types. + * Recommended for script type. + */ + target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), + /** + * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. + */ + execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), + /** User Input Requirements */ + params: external_exports.array(ActionParamSchema4).optional().describe("Input parameters required from user"), + /** Visual Style */ + variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), + /** UX Behavior */ + confirmText: I18nLabelSchema4.optional().describe("Confirmation message before execution"), + successMessage: I18nLabelSchema4.optional().describe("Success message to show after execution"), + refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), + /** Access */ + visible: external_exports.string().optional().describe("Formula returning boolean"), + disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), + /** Keyboard Shortcut */ + shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), + /** Bulk Operations */ + bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), + /** Execution */ + timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}).transform((data) => { + if (data.execute && !data.target) { + return { ...data, target: data.execute }; + } + return data; +}).refine((data) => { + if (TARGET_REQUIRED_TYPES4.has(data.type) && !data.target) { + return false; + } + return true; +}, { + message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", + path: ["target"] +}); +external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "percentile", + "median", + "stddev", + "variance" +]).describe("Standard aggregation functions"); +var SortDirectionEnum3 = external_exports.enum(["asc", "desc"]).describe("Sort order direction"); +var SortItemSchema2 = external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + order: SortDirectionEnum3.describe("Sort direction") +}).describe("Sort field and direction pair"); +external_exports.enum([ + "insert", + "update", + "delete", + "upsert" +]).describe("Data mutation event types"); +external_exports.enum([ + "read_uncommitted", + "read_committed", + "repeatable_read", + "serializable", + "snapshot" +]).describe("Transaction isolation levels (snake_case standard)"); +external_exports.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy"); +var PageRegionSchema = external_exports.object({ + name: external_exports.string().describe('Region name (e.g. "sidebar", "main", "header")'), + width: external_exports.enum(["small", "medium", "large", "full"]).optional(), + components: external_exports.array(external_exports.lazy(() => PageComponentSchema)).describe("Components in this region") +}); +var PageComponentType = external_exports.enum([ + // Structure + "page:header", + "page:footer", + "page:sidebar", + "page:tabs", + "page:accordion", + "page:card", + "page:section", + // Record Context + "record:details", + "record:highlights", + "record:related_list", + "record:activity", + "record:chatter", + "record:path", + // Navigation + "app:launcher", + "nav:menu", + "nav:breadcrumb", + // Utility + "global:search", + "global:notifications", + "user:profile", + // AI + "ai:chat_window", + "ai:suggestion", + // Content Elements (Airtable Interface parity) + "element:text", + "element:number", + "element:image", + "element:divider", + // Interactive Elements (Phase B — Element Library) + "element:button", + "element:filter", + "element:form", + "element:record_picker" +]); +var ElementDataSourceSchema = external_exports.object({ + object: external_exports.string().describe("Object to query"), + view: external_exports.string().optional().describe("Named view to apply"), + filter: FilterConditionSchema3.optional().describe("Additional filter criteria"), + sort: external_exports.array(SortItemSchema2).optional().describe("Sort order"), + limit: external_exports.number().int().positive().optional().describe("Max records to display") +}); +var PageComponentSchema = external_exports.object({ + /** Definition */ + type: external_exports.union([ + PageComponentType, + external_exports.string() + ]).describe("Component Type (Standard enum or custom string)"), + id: external_exports.string().optional().describe("Unique instance ID"), + /** Configuration */ + label: I18nLabelSchema4.optional(), + properties: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Component props passed to the widget. See component.zod.ts for schemas."), + /** + * Event Handlers + * Map event names to Action expressions. + * "onClick": "set_variable('userId', $event.id)" + * "onRowSelect": "navigate_to('page_detail', { id: $event.id })" + */ + events: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Event handlers map"), + /** Appearance */ + style: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Inline styles or utility classes"), + className: external_exports.string().optional().describe("CSS class names"), + /** Visibility Rule */ + visibility: external_exports.string().optional().describe("Visibility filter/formula"), + /** Per-element data binding, overrides page-level object context */ + dataSource: ElementDataSourceSchema.optional().describe("Per-element data binding for multi-object pages"), + /** Responsive layout overrides per breakpoint */ + responsive: ResponsiveConfigSchema2.optional().describe("Responsive layout configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var PageVariableSchema = external_exports.object({ + name: external_exports.string().describe("Variable name"), + type: external_exports.enum(["string", "number", "boolean", "object", "array", "record_id"]).default("string"), + defaultValue: external_exports.unknown().optional(), + /** Source element binding (e.g. element:record_picker writes to this variable) */ + source: external_exports.string().optional().describe("Component ID that writes to this variable") +}); +var BlankPageLayoutItemSchema = external_exports.object({ + componentId: external_exports.string().describe("Reference to a PageComponent.id in the page"), + x: external_exports.number().int().min(0).describe("Grid column position (0-based)"), + y: external_exports.number().int().min(0).describe("Grid row position (0-based)"), + width: external_exports.number().int().min(1).describe("Width in grid columns"), + height: external_exports.number().int().min(1).describe("Height in grid rows") +}); +var BlankPageLayoutSchema = external_exports.object({ + columns: external_exports.number().int().min(1).default(12).describe("Number of grid columns"), + rowHeight: external_exports.number().int().min(1).default(40).describe("Height of each grid row in pixels"), + gap: external_exports.number().int().min(0).default(8).describe("Gap between grid items in pixels"), + items: external_exports.array(BlankPageLayoutItemSchema).describe("Positioned components on the canvas") +}); +var PageTypeSchema = external_exports.enum([ + // Platform page types (Salesforce FlexiPage style) + "record", + // Component-based record layout page with regions + "home", + // Platform-level home/landing page + "app", + // App-level page with navigation context + "utility", + // Floating utility panel (e.g. notes, phone dialer) + // Interface page types (Airtable Interface parity) + "dashboard", + // KPI summary with charts/metrics + "grid", + // Spreadsheet-like data table + "list", + // Record list with quick actions + "gallery", + // Card-based visual browsing + "kanban", + // Status-based board + "calendar", + // Date-based scheduling + "timeline", + // Gantt-like project timeline + "form", + // Data entry form + "record_detail", + // Auto-generated single record field display + "record_review", + // Sequential record review/approval + "overview", + // Interface-level navigation/landing hub + "blank" + // Free-form canvas for custom composition +]).describe("Page type \u2014 platform or interface page types"); +var RecordReviewConfigSchema = external_exports.object({ + object: external_exports.string().describe("Target object for review"), + filter: FilterConditionSchema3.optional().describe("Filter criteria for review queue"), + sort: external_exports.array(SortItemSchema2).optional().describe("Sort order for review queue"), + displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on the review page"), + actions: external_exports.array(external_exports.object({ + label: external_exports.string().describe("Action button label"), + type: external_exports.enum(["approve", "reject", "skip", "custom"]).describe("Action type"), + field: external_exports.string().optional().describe("Field to update on action"), + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Value to set on action"), + nextRecord: external_exports.boolean().optional().default(true).describe("Auto-advance to next record after action") + })).describe("Review actions"), + navigation: external_exports.enum(["sequential", "random", "filtered"]).optional().default("sequential").describe("Record navigation mode"), + showProgress: external_exports.boolean().optional().default(true).describe("Show review progress indicator") +}); +var InterfacePageConfigSchema = external_exports.object({ + /** Data binding */ + source: external_exports.string().optional().describe("Source object name for the page"), + levels: external_exports.number().int().min(1).optional().describe("Number of hierarchy levels to display"), + filterBy: external_exports.array(ViewFilterRuleSchema2).optional().describe("Page-level filter criteria"), + /** Appearance */ + appearance: AppearanceConfigSchema2.optional().describe("Appearance and visualization configuration"), + /** User filters */ + userFilters: external_exports.object({ + elements: external_exports.array(external_exports.enum(["grid", "gallery", "kanban"])).optional().describe("Visualization element types available in user filter bar"), + tabs: external_exports.array(ViewTabSchema2).optional().describe("User-configurable tabs") + }).optional().describe("User filter configuration"), + /** User actions */ + userActions: UserActionsConfigSchema2.optional().describe("User action toggles"), + /** Add record */ + addRecord: AddRecordConfigSchema2.optional().describe("Add record entry point configuration"), + /** Record count */ + showRecordCount: external_exports.boolean().optional().describe("Show record count at page bottom"), + /** Advanced */ + allowPrinting: external_exports.boolean().optional().describe("Allow users to print the page") +}).describe("Interface-level page configuration (Airtable parity)"); +var PageSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema6.describe("Page unique name (lowercase snake_case)"), + label: I18nLabelSchema4, + description: I18nLabelSchema4.optional(), + /** Icon (used in interface navigation) */ + icon: external_exports.string().optional().describe("Page icon name"), + /** Page Type */ + type: PageTypeSchema.default("record").describe("Page type"), + /** Page State Definitions */ + variables: external_exports.array(PageVariableSchema).optional().describe("Local page state variables"), + /** Context */ + object: external_exports.string().optional().describe("Bound object (for Record pages)"), + /** Record Review Configuration (only for record_review pages) */ + recordReview: RecordReviewConfigSchema.optional().describe('Record review configuration (required when type is "record_review")'), + /** Blank Page Layout (only for blank pages) */ + blankLayout: BlankPageLayoutSchema.optional().describe('Free-form grid layout for blank pages (used when type is "blank")'), + /** Layout Template */ + template: external_exports.string().default("default").describe('Layout template name (e.g. "header-sidebar-main")'), + /** Regions & Content */ + regions: external_exports.array(PageRegionSchema).describe("Defined regions with components"), + /** Activation */ + isDefault: external_exports.boolean().default(false), + assignedProfiles: external_exports.array(external_exports.string()).optional(), + /** Interface Page Configuration (Airtable Interface parity) */ + interfaceConfig: InterfacePageConfigSchema.optional().describe("Interface-level page configuration (for Airtable-style interface pages)"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}).superRefine((data, ctx) => { + if (data.type === "record_review" && !data.recordReview) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: ["recordReview"], + message: 'recordReview is required when type is "record_review"' + }); + } + if (data.type === "blank" && !data.blankLayout) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: ["blankLayout"], + message: 'blankLayout is required when type is "blank"' + }); + } +}); +var WidgetLifecycleSchema = external_exports.object({ + /** + * Called when widget is mounted/rendered for the first time + * Use for initialization, setting up event listeners, loading data, etc. + * + * @example "initializeDatePicker(); loadOptions();" + */ + onMount: external_exports.string().optional().describe("Initialization code when widget mounts"), + /** + * Called when widget props change + * Receives previous props for comparison + * + * @example "if (prevProps.value !== props.value) { updateDisplay() }" + */ + onUpdate: external_exports.string().optional().describe("Code to run when props change"), + /** + * Called when widget is about to be removed from DOM + * Use for cleanup, removing event listeners, canceling timers, etc. + * + * @example "destroyDatePicker(); cancelPendingRequests();" + */ + onUnmount: external_exports.string().optional().describe("Cleanup code when widget unmounts"), + /** + * Custom validation logic for this widget + * Should return error message string if invalid, null/undefined if valid + * + * @example "return value && value.length >= 10 ? null : 'Minimum 10 characters'" + */ + onValidate: external_exports.string().optional().describe("Custom validation logic"), + /** + * Called when widget receives focus + * + * @example "highlightField(); logFocusEvent();" + */ + onFocus: external_exports.string().optional().describe("Code to run on focus"), + /** + * Called when widget loses focus + * + * @example "validateField(); saveFieldState();" + */ + onBlur: external_exports.string().optional().describe("Code to run on blur"), + /** + * Called on any error in the widget + * + * @example "logError(error); showErrorNotification();" + */ + onError: external_exports.string().optional().describe("Error handling code") +}); +var WidgetEventSchema = external_exports.object({ + /** + * Event name + * Should be lowercase, dash-separated for consistency + * + * @example "value-change", "item-selected", "search-complete" + */ + name: external_exports.string().describe("Event name"), + /** + * Event label for documentation + */ + label: I18nLabelSchema4.optional().describe("Human-readable event label"), + /** + * Event description + */ + description: I18nLabelSchema4.optional().describe("Event description and usage"), + /** + * Whether event bubbles up through the DOM hierarchy + * + * @default false + */ + bubbles: external_exports.boolean().default(false).describe("Whether event bubbles"), + /** + * Whether event can be cancelled + * + * @default false + */ + cancelable: external_exports.boolean().default(false).describe("Whether event is cancelable"), + /** + * Event payload schema + * Defines the data structure sent with the event + * + * @example { userId: 'string', timestamp: 'number' } + */ + payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event payload schema") +}); +var WidgetPropertySchema = external_exports.object({ + /** + * Property name + * Should be camelCase following ObjectStack conventions + */ + name: external_exports.string().describe("Property name (camelCase)"), + /** + * Property label for UI + */ + label: I18nLabelSchema4.optional().describe("Human-readable label"), + /** + * Property data type + * + * @example "string", "number", "boolean", "array", "object", "function" + */ + type: external_exports.enum(["string", "number", "boolean", "array", "object", "function", "any"]).describe("TypeScript type"), + /** + * Whether property is required + * + * @default false + */ + required: external_exports.boolean().default(false).describe("Whether property is required"), + /** + * Default value for the property + */ + default: external_exports.unknown().optional().describe("Default value"), + /** + * Property description + */ + description: I18nLabelSchema4.optional().describe("Property description"), + /** + * Property validation schema + * Can include min/max, regex, enum values, etc. + */ + validation: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation rules"), + /** + * Property category for grouping in UI + */ + category: external_exports.string().optional().describe("Property category") +}); +var WidgetSourceSchema = external_exports.discriminatedUnion("type", [ + // NPM Registry (standard) + external_exports.object({ + type: external_exports.literal("npm"), + packageName: external_exports.string().describe("NPM package name"), + version: external_exports.string().default("latest"), + exportName: external_exports.string().optional().describe("Named export (default: default)") + }), + // Module Federation (Remote) + external_exports.object({ + type: external_exports.literal("remote"), + url: external_exports.string().url().describe("Remote entry URL (.js)"), + moduleName: external_exports.string().describe("Exposed module name"), + scope: external_exports.string().describe("Remote scope name") + }), + // Inline Code (Simple scripts) + external_exports.object({ + type: external_exports.literal("inline"), + code: external_exports.string().describe("JavaScript code body") + }) +]); +var WidgetManifestSchema = external_exports.object({ + /** + * Widget identifier (snake_case) + */ + name: SnakeCaseIdentifierSchema6.describe("Widget identifier (snake_case)"), + /** + * Human-readable widget name + */ + label: I18nLabelSchema4.describe("Widget display name"), + /** + * Widget description + */ + description: I18nLabelSchema4.optional().describe("Widget description"), + /** + * Widget version (semver) + */ + version: external_exports.string().optional().describe("Widget version (semver)"), + /** + * Widget author/organization + */ + author: external_exports.string().optional().describe("Widget author"), + /** + * Icon name or URL + */ + icon: external_exports.string().optional().describe("Widget icon"), + /** + * Field types this widget supports + * + * @example ["text", "email", "url"] + */ + fieldTypes: external_exports.array(external_exports.string()).optional().describe("Supported field types"), + /** + * Widget category for organization + */ + category: external_exports.enum(["input", "display", "picker", "editor", "custom"]).default("custom").describe("Widget category"), + /** + * Widget lifecycle hooks + */ + lifecycle: WidgetLifecycleSchema.optional().describe("Lifecycle hooks"), + /** + * Custom events this widget emits + */ + events: external_exports.array(WidgetEventSchema).optional().describe("Custom events"), + /** + * Widget configuration properties + */ + properties: external_exports.array(WidgetPropertySchema).optional().describe("Configuration properties"), + /** + * Widget implementation + * Defines how to load the widget code + */ + implementation: WidgetSourceSchema.optional().describe("Widget implementation source"), + /** + * Widget dependencies + * External libraries or scripts needed + */ + dependencies: external_exports.array(external_exports.object({ + name: external_exports.string(), + version: external_exports.string().optional(), + url: external_exports.string().url().optional() + })).optional().describe("Widget dependencies"), + /** + * Widget screenshots for showcase + */ + screenshots: external_exports.array(external_exports.string().url()).optional().describe("Screenshot URLs"), + /** + * Widget documentation URL + */ + documentation: external_exports.string().url().optional().describe("Documentation URL"), + /** + * License information + */ + license: external_exports.string().optional().describe("License (SPDX identifier)"), + /** + * Tags for discovery + */ + tags: external_exports.array(external_exports.string()).optional().describe("Tags for categorization"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema2.optional().describe("Performance optimization settings") +}); +var FieldWidgetPropsSchema = external_exports.object({ + /** + * Current field value. + * Type depends on the field type (string, number, boolean, array, object, etc.) + */ + value: external_exports.unknown().describe("Current field value"), + /** + * Callback function to update the field value. + * Should be called when user interaction changes the value. + * + * @param newValue - The new value to set + */ + onChange: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.void()).describe("Callback to update field value"), + /** + * Whether the field is in read-only mode. + * When true, the widget should display the value but not allow editing. + */ + readonly: external_exports.boolean().default(false).describe("Read-only mode flag"), + /** + * Whether the field is required. + * Widget should indicate required state visually and validate accordingly. + */ + required: external_exports.boolean().default(false).describe("Required field flag"), + /** + * Validation error message to display. + * When present, widget should display the error in its UI. + */ + error: external_exports.string().optional().describe("Validation error message"), + /** + * Complete field definition from the schema. + * Contains metadata like type, constraints, options, etc. + */ + field: FieldSchema4.describe("Field schema definition"), + /** + * The complete record/document being edited. + * Useful for conditional logic and cross-field dependencies. + */ + record: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Complete record data"), + /** + * Custom options passed to the widget. + * Can contain widget-specific configuration like themes, behaviors, etc. + */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom widget options") +}); +var FeedItemType3 = external_exports.enum([ + "comment", + "field_change", + "task", + "event", + "email", + "call", + "note", + "file", + "record_create", + "record_delete", + "approval", + "sharing", + "system" +]); +var MentionSchema3 = external_exports.object({ + type: external_exports.enum(["user", "team", "record"]).describe("Mention target type"), + id: external_exports.string().describe("Target ID"), + name: external_exports.string().describe("Display name for rendering"), + offset: external_exports.number().int().min(0).describe("Character offset in body text"), + length: external_exports.number().int().min(1).describe("Length of mention token in body text") +}); +var FieldChangeEntrySchema3 = external_exports.object({ + field: external_exports.string().describe("Field machine name"), + fieldLabel: external_exports.string().optional().describe("Field display label"), + oldValue: external_exports.unknown().optional().describe("Previous value"), + newValue: external_exports.unknown().optional().describe("New value"), + oldDisplayValue: external_exports.string().optional().describe("Human-readable old value"), + newDisplayValue: external_exports.string().optional().describe("Human-readable new value") +}); +var ReactionSchema3 = external_exports.object({ + emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")'), + userIds: external_exports.array(external_exports.string()).describe("Users who reacted"), + count: external_exports.number().int().min(1).describe("Total reaction count") +}); +var FeedActorSchema3 = external_exports.object({ + type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), + id: external_exports.string().describe("Actor ID"), + name: external_exports.string().optional().describe("Actor display name"), + avatarUrl: external_exports.string().url().optional().describe("Actor avatar URL"), + source: external_exports.string().optional().describe('Source application (e.g., "Omni", "API", "Studio")') +}); +var FeedVisibility3 = external_exports.enum(["public", "internal", "private"]); +external_exports.object({ + /** Unique identifier */ + id: external_exports.string().describe("Feed item ID"), + /** Feed item type */ + type: FeedItemType3.describe("Activity type"), + /** Target record reference */ + object: external_exports.string().describe('Object name (e.g., "account")'), + recordId: external_exports.string().describe("Record ID this feed item belongs to"), + /** Actor (who performed the action) */ + actor: FeedActorSchema3.describe("Who performed this action"), + /** Content (for comments/notes) */ + body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), + /** @Mentions */ + mentions: external_exports.array(MentionSchema3).optional().describe("Mentioned users/teams/records"), + /** Field changes (for field_change type) */ + changes: external_exports.array(FieldChangeEntrySchema3).optional().describe("Field-level changes"), + /** Reactions */ + reactions: external_exports.array(ReactionSchema3).optional().describe("Emoji reactions on this item"), + /** Reply threading */ + parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), + replyCount: external_exports.number().int().min(0).default(0).describe("Number of replies"), + /** Pin / Star */ + pinned: external_exports.boolean().default(false).describe("Whether the feed item is pinned to the top of the timeline"), + pinnedAt: external_exports.string().datetime().optional().describe("Timestamp when the item was pinned"), + pinnedBy: external_exports.string().optional().describe("User ID who pinned the item"), + starred: external_exports.boolean().default(false).describe("Whether the feed item is starred/bookmarked by the current user"), + starredAt: external_exports.string().datetime().optional().describe("Timestamp when the item was starred"), + /** Visibility */ + visibility: FeedVisibility3.default("public").describe("Visibility: public (all users), internal (team only), private (author + mentioned)"), + /** Timestamps */ + createdAt: external_exports.string().datetime().describe("Creation timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + editedAt: external_exports.string().datetime().optional().describe("When comment was last edited"), + isEdited: external_exports.boolean().default(false).describe("Whether comment has been edited") +}); +var FeedFilterMode2 = external_exports.enum([ + "all", + "comments_only", + "changes_only", + "tasks_only" +]); +var EmptyProps = external_exports.object({}); +var PageHeaderProps = external_exports.object({ + title: I18nLabelSchema4.describe("Page title"), + subtitle: I18nLabelSchema4.optional().describe("Page subtitle"), + icon: external_exports.string().optional().describe("Icon name"), + breadcrumb: external_exports.boolean().default(true).describe("Show breadcrumb"), + actions: external_exports.array(external_exports.string()).optional().describe("Action IDs to show in header"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var PageTabsProps = external_exports.object({ + type: external_exports.enum(["line", "card", "pill"]).default("line"), + position: external_exports.enum(["top", "left"]).default("top"), + items: external_exports.array(external_exports.object({ + label: I18nLabelSchema4, + icon: external_exports.string().optional(), + children: external_exports.array(external_exports.unknown()).describe("Child components") + })), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var PageCardProps = external_exports.object({ + title: I18nLabelSchema4.optional(), + bordered: external_exports.boolean().default(true), + actions: external_exports.array(external_exports.string()).optional(), + /** Slot for nested content in the Card body */ + body: external_exports.array(external_exports.unknown()).optional().describe("Card content components (slot)"), + /** Slot for footer content */ + footer: external_exports.array(external_exports.unknown()).optional().describe("Card footer components (slot)"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var RecordDetailsProps = external_exports.object({ + columns: external_exports.enum(["1", "2", "3", "4"]).default("2").describe("Number of columns for field layout (1-4)"), + layout: external_exports.enum(["auto", "custom"]).default("auto").describe("Layout mode: auto uses object compactLayout, custom uses explicit sections"), + sections: external_exports.array(external_exports.string()).optional().describe('Section IDs to show (required when layout is "custom")'), + fields: external_exports.array(external_exports.string()).optional().describe("Explicit field list to display (optional, overrides compactLayout)"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var RecordRelatedListProps = external_exports.object({ + objectName: external_exports.string().describe('Related object name (e.g., "task", "opportunity")'), + relationshipField: external_exports.string().describe('Field on related object that points to this record (e.g., "account_id")'), + columns: external_exports.array(external_exports.string()).describe("Fields to display in the related list"), + sort: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]) + })) + ]).optional().describe("Sort order for related records"), + limit: external_exports.number().int().positive().default(5).describe("Number of records to display initially"), + filter: external_exports.array(ViewFilterRuleSchema2).optional().describe("Additional filter criteria for related records"), + title: I18nLabelSchema4.optional().describe("Custom title for the related list"), + showViewAll: external_exports.boolean().default(true).describe('Show "View All" link to see all related records'), + actions: external_exports.array(external_exports.string()).optional().describe("Action IDs available for related records"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var RecordHighlightsProps = external_exports.object({ + fields: external_exports.array(external_exports.string()).min(1).max(7).describe("Key fields to highlight (1-7 fields max, typically displayed as prominent cards)"), + layout: external_exports.enum(["horizontal", "vertical"]).default("horizontal").describe("Layout orientation for highlight fields"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var RecordActivityProps = external_exports.object({ + /** Activity types to display (unified enum including comment, field_change, etc.) */ + types: external_exports.array(FeedItemType3).optional().describe("Feed item types to show (default: all)"), + /** Default filter mode (Airtable-style dropdown) */ + filterMode: FeedFilterMode2.default("all").describe("Default activity filter"), + /** Allow user to switch filter modes */ + showFilterToggle: external_exports.boolean().default(true).describe("Show filter dropdown in panel header"), + /** Pagination */ + limit: external_exports.number().int().positive().default(20).describe("Number of items to load per page"), + /** Show completed activities */ + showCompleted: external_exports.boolean().default(false).describe("Include completed activities"), + /** Merge field_change + comment in a unified timeline */ + unifiedTimeline: external_exports.boolean().default(true).describe("Mix field changes and comments in one timeline (Airtable style)"), + /** Show the comment input box at the bottom */ + showCommentInput: external_exports.boolean().default(true).describe('Show "Leave a comment" input at the bottom'), + /** Enable @mentions in comments */ + enableMentions: external_exports.boolean().default(true).describe("Enable @mentions in comments"), + /** Enable emoji reactions */ + enableReactions: external_exports.boolean().default(false).describe("Enable emoji reactions on feed items"), + /** Enable threaded replies */ + enableThreading: external_exports.boolean().default(false).describe("Enable threaded replies on comments"), + /** Show notification subscription toggle (bell icon) */ + showSubscriptionToggle: external_exports.boolean().default(true).describe("Show bell icon for record-level notification subscription"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var RecordChatterProps = external_exports.object({ + /** Panel position */ + position: external_exports.enum(["sidebar", "inline", "drawer"]).default("sidebar").describe("Where to render the chatter panel"), + /** Panel width (for sidebar/drawer) */ + width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Panel width (e.g., "350px", "30%")'), + /** Collapsible */ + collapsible: external_exports.boolean().default(true).describe("Whether the panel can be collapsed"), + /** Default collapsed state */ + defaultCollapsed: external_exports.boolean().default(false).describe("Whether the panel starts collapsed"), + /** Feed configuration (delegates to RecordActivityProps) */ + feed: RecordActivityProps.optional().describe("Embedded activity feed configuration"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var RecordPathProps = external_exports.object({ + statusField: external_exports.string().describe("Field name representing the current status/stage"), + stages: external_exports.array(external_exports.object({ + value: external_exports.string(), + label: I18nLabelSchema4 + })).optional().describe("Explicit stage definitions (if not using field metadata)"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var PageAccordionProps = external_exports.object({ + items: external_exports.array(external_exports.object({ + label: I18nLabelSchema4, + icon: external_exports.string().optional(), + collapsed: external_exports.boolean().default(false), + children: external_exports.array(external_exports.unknown()).describe("Child components") + })), + allowMultiple: external_exports.boolean().default(false).describe("Allow multiple panels to be expanded simultaneously"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var AIChatWindowProps = external_exports.object({ + mode: external_exports.enum(["float", "sidebar", "inline"]).default("float").describe("Display mode for the chat window"), + agentId: external_exports.string().optional().describe("Specific AI agent to use"), + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Contextual data to pass to the AI"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var ElementTextPropsSchema = external_exports.object({ + content: external_exports.string().describe("Text or Markdown content"), + variant: external_exports.enum(["heading", "subheading", "body", "caption"]).optional().default("body").describe("Text style variant"), + align: external_exports.enum(["left", "center", "right"]).optional().default("left").describe("Text alignment"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var ElementNumberPropsSchema = external_exports.object({ + object: external_exports.string().describe("Source object"), + field: external_exports.string().optional().describe("Field to aggregate"), + aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).describe("Aggregation function"), + filter: FilterConditionSchema3.optional().describe("Filter criteria"), + format: external_exports.enum(["number", "currency", "percent"]).optional().describe("Number display format"), + prefix: external_exports.string().optional().describe('Prefix text (e.g. "$")'), + suffix: external_exports.string().optional().describe('Suffix text (e.g. "%")'), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var ElementImagePropsSchema = external_exports.object({ + src: external_exports.string().describe("Image URL or attachment field"), + alt: external_exports.string().optional().describe("Alt text for accessibility"), + fit: external_exports.enum(["cover", "contain", "fill"]).optional().default("cover").describe("Image object-fit mode"), + height: external_exports.number().optional().describe("Fixed height in pixels"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var ElementButtonPropsSchema = external_exports.object({ + label: I18nLabelSchema4.describe("Button display label"), + variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().default("primary").describe("Button visual variant"), + size: external_exports.enum(["small", "medium", "large"]).optional().default("medium").describe("Button size"), + icon: external_exports.string().optional().describe("Icon name (Lucide icon)"), + iconPosition: external_exports.enum(["left", "right"]).optional().default("left").describe("Icon position relative to label"), + disabled: external_exports.boolean().optional().default(false).describe("Disable the button"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var ElementFilterPropsSchema = external_exports.object({ + object: external_exports.string().describe("Object to filter"), + fields: external_exports.array(external_exports.string()).describe("Filterable field names"), + targetVariable: external_exports.string().optional().describe("Page variable to store filter state"), + layout: external_exports.enum(["inline", "dropdown", "sidebar"]).optional().default("inline").describe("Filter display layout"), + showSearch: external_exports.boolean().optional().default(true).describe("Show search input"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var ElementFormPropsSchema = external_exports.object({ + object: external_exports.string().describe("Object for the form"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to display (defaults to all editable fields)"), + mode: external_exports.enum(["create", "edit"]).optional().default("create").describe("Form mode"), + submitLabel: I18nLabelSchema4.optional().describe("Submit button label"), + onSubmit: external_exports.string().optional().describe("Action expression on form submit"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var ElementRecordPickerPropsSchema = external_exports.object({ + object: external_exports.string().describe("Object to pick records from"), + displayField: external_exports.string().describe("Field to display as the record label"), + searchFields: external_exports.array(external_exports.string()).optional().describe("Fields to search against"), + filter: FilterConditionSchema3.optional().describe("Filter criteria for available records"), + multiple: external_exports.boolean().optional().default(false).describe("Allow multiple record selection"), + targetVariable: external_exports.string().optional().describe("Page variable to bind selected record ID(s)"), + placeholder: I18nLabelSchema4.optional().describe("Placeholder text"), + /** ARIA accessibility */ + aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") +}); +var ComponentPropsMap = { + // Structure + "page:header": PageHeaderProps, + "page:tabs": PageTabsProps, + "page:card": PageCardProps, + "page:footer": EmptyProps, + "page:sidebar": EmptyProps, + "page:accordion": PageAccordionProps, + "page:section": EmptyProps, + // Record + "record:details": RecordDetailsProps, + "record:related_list": RecordRelatedListProps, + "record:highlights": RecordHighlightsProps, + "record:activity": RecordActivityProps, + "record:chatter": RecordChatterProps, + "record:path": RecordPathProps, + // Navigation + "app:launcher": EmptyProps, + "nav:menu": EmptyProps, + "nav:breadcrumb": EmptyProps, + // Utility + "global:search": EmptyProps, + "global:notifications": EmptyProps, + "user:profile": EmptyProps, + // AI + "ai:chat_window": AIChatWindowProps, + "ai:suggestion": external_exports.object({ context: external_exports.string().optional() }), + // Content Elements + "element:text": ElementTextPropsSchema, + "element:number": ElementNumberPropsSchema, + "element:image": ElementImagePropsSchema, + "element:divider": EmptyProps, + // Interactive Elements + "element:button": ElementButtonPropsSchema, + "element:filter": ElementFilterPropsSchema, + "element:form": ElementFormPropsSchema, + "element:record_picker": ElementRecordPickerPropsSchema +}; +var TouchTargetConfigSchema = external_exports.object({ + minWidth: external_exports.number().default(44).describe("Minimum touch target width in pixels (WCAG 2.5.5: 44px)"), + minHeight: external_exports.number().default(44).describe("Minimum touch target height in pixels (WCAG 2.5.5: 44px)"), + padding: external_exports.number().optional().describe("Additional padding around touch target in pixels"), + hitSlop: external_exports.object({ + top: external_exports.number().optional().describe("Extra hit area above the element"), + right: external_exports.number().optional().describe("Extra hit area to the right of the element"), + bottom: external_exports.number().optional().describe("Extra hit area below the element"), + left: external_exports.number().optional().describe("Extra hit area to the left of the element") + }).optional().describe("Invisible hit area extension beyond the visible bounds") +}).describe("Touch target sizing configuration (WCAG accessible)"); +var GestureTypeSchema = external_exports.enum([ + "swipe", + "pinch", + "long_press", + "double_tap", + "drag", + "rotate", + "pan" +]).describe("Touch gesture type"); +var SwipeDirectionSchema = external_exports.enum(["up", "down", "left", "right"]); +var SwipeGestureConfigSchema = external_exports.object({ + direction: external_exports.array(SwipeDirectionSchema).describe("Allowed swipe directions"), + threshold: external_exports.number().optional().describe("Minimum distance in pixels to recognize swipe"), + velocity: external_exports.number().optional().describe("Minimum velocity (px/ms) to trigger swipe") +}).describe("Swipe gesture recognition settings"); +var PinchGestureConfigSchema = external_exports.object({ + minScale: external_exports.number().optional().describe("Minimum scale factor (e.g., 0.5 for 50%)"), + maxScale: external_exports.number().optional().describe("Maximum scale factor (e.g., 3.0 for 300%)") +}).describe("Pinch/zoom gesture recognition settings"); +var LongPressGestureConfigSchema = external_exports.object({ + duration: external_exports.number().default(500).describe("Hold duration in milliseconds to trigger long press"), + moveTolerance: external_exports.number().optional().describe("Max movement in pixels allowed during press") +}).describe("Long press gesture recognition settings"); +var GestureConfigSchema = external_exports.object({ + type: GestureTypeSchema.describe("Gesture type to configure"), + label: I18nLabelSchema4.optional().describe("Descriptive label for the gesture action"), + enabled: external_exports.boolean().default(true).describe("Whether this gesture is active"), + swipe: SwipeGestureConfigSchema.optional().describe("Swipe gesture settings (when type is swipe)"), + pinch: PinchGestureConfigSchema.optional().describe("Pinch gesture settings (when type is pinch)"), + longPress: LongPressGestureConfigSchema.optional().describe("Long press settings (when type is long_press)") +}).describe("Per-gesture configuration"); +var TouchInteractionSchema = external_exports.object({ + gestures: external_exports.array(GestureConfigSchema).optional().describe("Configured gesture recognizers"), + touchTarget: TouchTargetConfigSchema.optional().describe("Touch target sizing and hit area"), + hapticFeedback: external_exports.boolean().optional().describe("Enable haptic feedback on touch interactions") +}).merge(AriaPropsSchema4.partial()).describe("Touch and gesture interaction configuration"); +var FocusTrapConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable focus trapping within this container"), + initialFocus: external_exports.string().optional().describe("CSS selector for the element to focus on activation"), + returnFocus: external_exports.boolean().default(true).describe("Return focus to trigger element on deactivation"), + escapeDeactivates: external_exports.boolean().default(true).describe("Allow Escape key to deactivate the focus trap") +}).describe("Focus trap configuration for modal-like containers"); +var KeyboardShortcutSchema = external_exports.object({ + key: external_exports.string().describe('Key combination (e.g., "Ctrl+S", "Alt+N", "Escape")'), + action: external_exports.string().describe("Action identifier to invoke when shortcut is triggered"), + description: I18nLabelSchema4.optional().describe("Human-readable description of what the shortcut does"), + scope: external_exports.enum(["global", "view", "form", "modal", "list"]).default("global").describe("Scope in which this shortcut is active") +}).describe("Keyboard shortcut binding"); +var FocusManagementSchema = external_exports.object({ + tabOrder: external_exports.enum(["auto", "manual"]).default("auto").describe("Tab order strategy: auto (DOM order) or manual (explicit tabIndex)"), + skipLinks: external_exports.boolean().default(false).describe("Provide skip-to-content navigation links"), + focusVisible: external_exports.boolean().default(true).describe("Show visible focus indicators for keyboard users"), + focusTrap: FocusTrapConfigSchema.optional().describe("Focus trap settings"), + arrowNavigation: external_exports.boolean().default(false).describe("Enable arrow key navigation between focusable items") +}).describe("Focus and tab navigation management"); +var KeyboardNavigationConfigSchema = external_exports.object({ + shortcuts: external_exports.array(KeyboardShortcutSchema).optional().describe("Registered keyboard shortcuts"), + focusManagement: FocusManagementSchema.optional().describe("Focus and tab order management"), + rovingTabindex: external_exports.boolean().default(false).describe("Enable roving tabindex pattern for composite widgets") +}).merge(AriaPropsSchema4.partial()).describe("Keyboard navigation and shortcut configuration"); +var ColorPaletteSchema = external_exports.object({ + primary: external_exports.string().describe("Primary brand color (hex, rgb, or hsl)"), + secondary: external_exports.string().optional().describe("Secondary brand color"), + accent: external_exports.string().optional().describe("Accent color for highlights"), + success: external_exports.string().optional().describe("Success state color (default: green)"), + warning: external_exports.string().optional().describe("Warning state color (default: yellow)"), + error: external_exports.string().optional().describe("Error state color (default: red)"), + info: external_exports.string().optional().describe("Info state color (default: blue)"), + // Neutral colors + background: external_exports.string().optional().describe("Background color"), + surface: external_exports.string().optional().describe("Surface/card background color"), + text: external_exports.string().optional().describe("Primary text color"), + textSecondary: external_exports.string().optional().describe("Secondary text color"), + border: external_exports.string().optional().describe("Border color"), + disabled: external_exports.string().optional().describe("Disabled state color"), + // Color variants (shades) + primaryLight: external_exports.string().optional().describe("Lighter shade of primary"), + primaryDark: external_exports.string().optional().describe("Darker shade of primary"), + secondaryLight: external_exports.string().optional().describe("Lighter shade of secondary"), + secondaryDark: external_exports.string().optional().describe("Darker shade of secondary") +}); +var TypographySchema = external_exports.object({ + fontFamily: external_exports.object({ + base: external_exports.string().optional().describe("Base font family (default: system fonts)"), + heading: external_exports.string().optional().describe("Heading font family"), + mono: external_exports.string().optional().describe("Monospace font family for code") + }).optional(), + fontSize: external_exports.object({ + xs: external_exports.string().optional().describe("Extra small font size (e.g., 0.75rem)"), + sm: external_exports.string().optional().describe("Small font size (e.g., 0.875rem)"), + base: external_exports.string().optional().describe("Base font size (e.g., 1rem)"), + lg: external_exports.string().optional().describe("Large font size (e.g., 1.125rem)"), + xl: external_exports.string().optional().describe("Extra large font size (e.g., 1.25rem)"), + "2xl": external_exports.string().optional().describe("2X large font size (e.g., 1.5rem)"), + "3xl": external_exports.string().optional().describe("3X large font size (e.g., 1.875rem)"), + "4xl": external_exports.string().optional().describe("4X large font size (e.g., 2.25rem)") + }).optional(), + fontWeight: external_exports.object({ + light: external_exports.number().optional().describe("Light weight (default: 300)"), + normal: external_exports.number().optional().describe("Normal weight (default: 400)"), + medium: external_exports.number().optional().describe("Medium weight (default: 500)"), + semibold: external_exports.number().optional().describe("Semibold weight (default: 600)"), + bold: external_exports.number().optional().describe("Bold weight (default: 700)") + }).optional(), + lineHeight: external_exports.object({ + tight: external_exports.string().optional().describe("Tight line height (e.g., 1.25)"), + normal: external_exports.string().optional().describe("Normal line height (e.g., 1.5)"), + relaxed: external_exports.string().optional().describe("Relaxed line height (e.g., 1.75)"), + loose: external_exports.string().optional().describe("Loose line height (e.g., 2)") + }).optional(), + letterSpacing: external_exports.object({ + tighter: external_exports.string().optional().describe("Tighter letter spacing (e.g., -0.05em)"), + tight: external_exports.string().optional().describe("Tight letter spacing (e.g., -0.025em)"), + normal: external_exports.string().optional().describe("Normal letter spacing (e.g., 0)"), + wide: external_exports.string().optional().describe("Wide letter spacing (e.g., 0.025em)"), + wider: external_exports.string().optional().describe("Wider letter spacing (e.g., 0.05em)") + }).optional() +}); +var SpacingSchema = external_exports.object({ + "0": external_exports.string().optional().describe("0 spacing (0)"), + "1": external_exports.string().optional().describe("Spacing unit 1 (e.g., 0.25rem)"), + "2": external_exports.string().optional().describe("Spacing unit 2 (e.g., 0.5rem)"), + "3": external_exports.string().optional().describe("Spacing unit 3 (e.g., 0.75rem)"), + "4": external_exports.string().optional().describe("Spacing unit 4 (e.g., 1rem)"), + "5": external_exports.string().optional().describe("Spacing unit 5 (e.g., 1.25rem)"), + "6": external_exports.string().optional().describe("Spacing unit 6 (e.g., 1.5rem)"), + "8": external_exports.string().optional().describe("Spacing unit 8 (e.g., 2rem)"), + "10": external_exports.string().optional().describe("Spacing unit 10 (e.g., 2.5rem)"), + "12": external_exports.string().optional().describe("Spacing unit 12 (e.g., 3rem)"), + "16": external_exports.string().optional().describe("Spacing unit 16 (e.g., 4rem)"), + "20": external_exports.string().optional().describe("Spacing unit 20 (e.g., 5rem)"), + "24": external_exports.string().optional().describe("Spacing unit 24 (e.g., 6rem)") +}); +var BorderRadiusSchema = external_exports.object({ + none: external_exports.string().optional().describe("No border radius (0)"), + sm: external_exports.string().optional().describe("Small border radius (e.g., 0.125rem)"), + base: external_exports.string().optional().describe("Base border radius (e.g., 0.25rem)"), + md: external_exports.string().optional().describe("Medium border radius (e.g., 0.375rem)"), + lg: external_exports.string().optional().describe("Large border radius (e.g., 0.5rem)"), + xl: external_exports.string().optional().describe("Extra large border radius (e.g., 0.75rem)"), + "2xl": external_exports.string().optional().describe("2X large border radius (e.g., 1rem)"), + full: external_exports.string().optional().describe("Full border radius (50%)") +}); +var ShadowSchema = external_exports.object({ + none: external_exports.string().optional().describe("No shadow"), + sm: external_exports.string().optional().describe("Small shadow"), + base: external_exports.string().optional().describe("Base shadow"), + md: external_exports.string().optional().describe("Medium shadow"), + lg: external_exports.string().optional().describe("Large shadow"), + xl: external_exports.string().optional().describe("Extra large shadow"), + "2xl": external_exports.string().optional().describe("2X large shadow"), + inner: external_exports.string().optional().describe("Inner shadow (inset)") +}); +var BreakpointsSchema = external_exports.object({ + xs: external_exports.string().optional().describe("Extra small breakpoint (e.g., 480px)"), + sm: external_exports.string().optional().describe("Small breakpoint (e.g., 640px)"), + md: external_exports.string().optional().describe("Medium breakpoint (e.g., 768px)"), + lg: external_exports.string().optional().describe("Large breakpoint (e.g., 1024px)"), + xl: external_exports.string().optional().describe("Extra large breakpoint (e.g., 1280px)"), + "2xl": external_exports.string().optional().describe("2X large breakpoint (e.g., 1536px)") +}); +var AnimationSchema = external_exports.object({ + duration: external_exports.object({ + fast: external_exports.string().optional().describe("Fast animation (e.g., 150ms)"), + base: external_exports.string().optional().describe("Base animation (e.g., 300ms)"), + slow: external_exports.string().optional().describe("Slow animation (e.g., 500ms)") + }).optional(), + timing: external_exports.object({ + linear: external_exports.string().optional().describe("Linear timing function"), + ease: external_exports.string().optional().describe("Ease timing function"), + ease_in: external_exports.string().optional().describe("Ease-in timing function"), + ease_out: external_exports.string().optional().describe("Ease-out timing function"), + ease_in_out: external_exports.string().optional().describe("Ease-in-out timing function") + }).optional() +}); +var ZIndexSchema = external_exports.object({ + base: external_exports.number().optional().describe("Base z-index (e.g., 0)"), + dropdown: external_exports.number().optional().describe("Dropdown z-index (e.g., 1000)"), + sticky: external_exports.number().optional().describe("Sticky z-index (e.g., 1020)"), + fixed: external_exports.number().optional().describe("Fixed z-index (e.g., 1030)"), + modalBackdrop: external_exports.number().optional().describe("Modal backdrop z-index (e.g., 1040)"), + modal: external_exports.number().optional().describe("Modal z-index (e.g., 1050)"), + popover: external_exports.number().optional().describe("Popover z-index (e.g., 1060)"), + tooltip: external_exports.number().optional().describe("Tooltip z-index (e.g., 1070)") +}); +var ThemeModeSchema = external_exports.enum(["light", "dark", "auto"]); +var DensityModeSchema = external_exports.enum(["compact", "regular", "spacious"]); +var WcagContrastLevelSchema = external_exports.enum(["AA", "AAA"]); +var ThemeSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema6.describe("Unique theme identifier (snake_case)"), + label: external_exports.string().describe("Human-readable theme name"), + description: external_exports.string().optional().describe("Theme description"), + /** Theme mode */ + mode: ThemeModeSchema.default("light").describe("Theme mode (light, dark, or auto)"), + /** Color system */ + colors: ColorPaletteSchema.describe("Color palette configuration"), + /** Typography */ + typography: TypographySchema.optional().describe("Typography settings"), + /** Spacing */ + spacing: SpacingSchema.optional().describe("Spacing scale"), + /** Border radius */ + borderRadius: BorderRadiusSchema.optional().describe("Border radius scale"), + /** Shadows */ + shadows: ShadowSchema.optional().describe("Box shadow effects"), + /** Breakpoints */ + breakpoints: BreakpointsSchema.optional().describe("Responsive breakpoints"), + /** Animation */ + animation: AnimationSchema.optional().describe("Animation settings"), + /** Z-Index */ + zIndex: ZIndexSchema.optional().describe("Z-index scale for layering"), + /** Custom CSS variables */ + customVars: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom CSS variables (key-value pairs)"), + /** Logo */ + logo: external_exports.object({ + light: external_exports.string().optional().describe("Logo URL for light mode"), + dark: external_exports.string().optional().describe("Logo URL for dark mode"), + favicon: external_exports.string().optional().describe("Favicon URL") + }).optional().describe("Logo assets"), + /** Extends another theme */ + extends: external_exports.string().optional().describe("Base theme to extend from"), + /** Display density mode */ + density: DensityModeSchema.optional().describe("Display density: compact, regular, or spacious"), + /** WCAG contrast level requirement */ + wcagContrast: WcagContrastLevelSchema.optional().describe("WCAG color contrast level (AA or AAA)"), + /** Right-to-left language support */ + rtl: external_exports.boolean().optional().describe("Enable right-to-left layout direction"), + /** Touch target accessibility configuration */ + touchTarget: TouchTargetConfigSchema.optional().describe("Touch target sizing defaults"), + /** Keyboard navigation and focus management */ + keyboardNavigation: FocusManagementSchema.optional().describe("Keyboard focus management settings") +}); +var OfflineStrategySchema = external_exports.enum([ + "cache_first", + "network_first", + "stale_while_revalidate", + "network_only", + "cache_only" +]).describe("Data fetching strategy for offline/online transitions"); +var ConflictResolutionSchema = external_exports.enum([ + "client_wins", + "server_wins", + "manual", + "last_write_wins" +]).describe("How to resolve conflicts when syncing offline changes"); +var SyncConfigSchema = external_exports.object({ + strategy: OfflineStrategySchema.default("network_first").describe("Sync fetch strategy"), + conflictResolution: ConflictResolutionSchema.default("last_write_wins").describe("Conflict resolution policy"), + retryInterval: external_exports.number().optional().describe("Retry interval in milliseconds between sync attempts"), + maxRetries: external_exports.number().optional().describe("Maximum number of sync retry attempts"), + batchSize: external_exports.number().optional().describe("Number of mutations to sync per batch") +}).describe("Offline-to-online synchronization configuration"); +var PersistStorageSchema = external_exports.enum([ + "indexeddb", + "localstorage", + "sqlite" +]).describe("Client-side storage backend for offline cache"); +var EvictionPolicySchema = external_exports.enum([ + "lru", + "lfu", + "fifo" +]).describe("Cache eviction policy"); +var OfflineCacheConfigSchema = external_exports.object({ + maxSize: external_exports.number().optional().describe("Maximum cache size in bytes"), + ttl: external_exports.number().optional().describe("Time-to-live for cached entries in milliseconds"), + persistStorage: PersistStorageSchema.default("indexeddb").describe("Storage backend"), + evictionPolicy: EvictionPolicySchema.default("lru").describe("Cache eviction policy when full") +}).describe("Client-side offline cache configuration"); +var OfflineConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable offline support"), + strategy: OfflineStrategySchema.default("network_first").describe("Default offline fetch strategy"), + cache: OfflineCacheConfigSchema.optional().describe("Cache settings for offline data"), + sync: SyncConfigSchema.optional().describe("Sync settings for offline mutations"), + offlineIndicator: external_exports.boolean().default(true).describe("Show a visual indicator when offline"), + offlineMessage: I18nLabelSchema4.optional().describe("Customizable offline status message shown to users"), + queueMaxSize: external_exports.number().optional().describe("Maximum number of queued offline mutations") +}).describe("Offline support configuration"); +var TransitionPresetSchema = external_exports.enum([ + "fade", + "slide_up", + "slide_down", + "slide_left", + "slide_right", + "scale", + "rotate", + "flip", + "none" +]).describe("Transition preset type"); +var EasingFunctionSchema = external_exports.enum([ + "linear", + "ease", + "ease_in", + "ease_out", + "ease_in_out", + "spring" +]).describe("Animation easing function"); +var TransitionConfigSchema = external_exports.object({ + preset: TransitionPresetSchema.optional().describe("Transition preset to apply"), + duration: external_exports.number().optional().describe("Transition duration in milliseconds"), + easing: EasingFunctionSchema.optional().describe("Easing function for the transition"), + delay: external_exports.number().optional().describe("Delay before transition starts in milliseconds"), + customKeyframes: external_exports.string().optional().describe("CSS @keyframes name for custom animations"), + themeToken: external_exports.string().optional().describe('Reference to a theme animation token (e.g. "animation.duration.fast")') +}).describe("Animation transition configuration"); +var AnimationTriggerSchema = external_exports.enum([ + "on_mount", + "on_unmount", + "on_hover", + "on_focus", + "on_click", + "on_scroll", + "on_visible" +]).describe("Event that triggers the animation"); +var ComponentAnimationSchema = external_exports.object({ + label: I18nLabelSchema4.optional().describe("Descriptive label for this animation configuration"), + enter: TransitionConfigSchema.optional().describe("Enter/mount animation"), + exit: TransitionConfigSchema.optional().describe("Exit/unmount animation"), + hover: TransitionConfigSchema.optional().describe("Hover state animation"), + trigger: AnimationTriggerSchema.optional().describe("When to trigger the animation"), + reducedMotion: external_exports.enum(["respect", "disable", "alternative"]).default("respect").describe("Accessibility: how to handle prefers-reduced-motion") +}).merge(AriaPropsSchema4.partial()).describe("Component-level animation configuration"); +var PageTransitionSchema = external_exports.object({ + type: TransitionPresetSchema.default("fade").describe("Page transition type"), + duration: external_exports.number().default(300).describe("Transition duration in milliseconds"), + easing: EasingFunctionSchema.default("ease_in_out").describe("Easing function for the transition"), + crossFade: external_exports.boolean().default(false).describe("Whether to cross-fade between pages") +}).describe("Page-level transition configuration"); +var MotionConfigSchema = external_exports.object({ + label: I18nLabelSchema4.optional().describe("Descriptive label for the motion configuration"), + defaultTransition: TransitionConfigSchema.optional().describe("Default transition applied to all animations"), + pageTransitions: PageTransitionSchema.optional().describe("Page navigation transition settings"), + componentAnimations: external_exports.record(external_exports.string(), ComponentAnimationSchema).optional().describe("Component name to animation configuration mapping"), + reducedMotion: external_exports.boolean().default(false).describe("When true, respect prefers-reduced-motion and suppress animations globally"), + enabled: external_exports.boolean().default(true).describe("Enable or disable all animations globally") +}).describe("Top-level motion and animation design configuration"); +var NotificationTypeSchema = external_exports.enum([ + "toast", + "snackbar", + "banner", + "alert", + "inline" +]).describe("Notification presentation style"); +var NotificationSeveritySchema = external_exports.enum([ + "info", + "success", + "warning", + "error" +]).describe("Notification severity level"); +var NotificationPositionSchema = external_exports.enum([ + "top_left", + "top_center", + "top_right", + "bottom_left", + "bottom_center", + "bottom_right" +]).describe("Screen position for notification placement"); +var NotificationActionSchema = external_exports.object({ + label: I18nLabelSchema4.describe("Action button label"), + action: external_exports.string().describe("Action identifier to execute"), + variant: external_exports.enum(["primary", "secondary", "link"]).default("primary").describe("Button variant style") +}).describe("Notification action button"); +var NotificationSchema2 = external_exports.object({ + type: NotificationTypeSchema.default("toast").describe("Notification presentation style"), + severity: NotificationSeveritySchema.default("info").describe("Notification severity level"), + title: I18nLabelSchema4.optional().describe("Notification title"), + message: I18nLabelSchema4.describe("Notification message body"), + icon: external_exports.string().optional().describe("Icon name override"), + duration: external_exports.number().optional().describe("Auto-dismiss duration in ms, omit for persistent"), + dismissible: external_exports.boolean().default(true).describe("Allow user to dismiss the notification"), + actions: external_exports.array(NotificationActionSchema).optional().describe("Action buttons"), + position: NotificationPositionSchema.optional().describe("Override default position") +}).merge(AriaPropsSchema4.partial()).describe("Notification instance definition"); +var NotificationConfigSchema2 = external_exports.object({ + defaultPosition: NotificationPositionSchema.default("top_right").describe("Default screen position for notifications"), + defaultDuration: external_exports.number().default(5e3).describe("Default auto-dismiss duration in ms"), + maxVisible: external_exports.number().default(5).describe("Maximum number of notifications visible at once"), + stackDirection: external_exports.enum(["up", "down"]).default("down").describe("Stack direction for multiple notifications"), + pauseOnHover: external_exports.boolean().default(true).describe("Pause auto-dismiss timer on hover") +}).describe("Global notification system configuration"); +var DragHandleSchema = external_exports.enum([ + "element", + "handle", + "grip_icon" +]).describe("Drag initiation method"); +var DropEffectSchema = external_exports.enum([ + "move", + "copy", + "link", + "none" +]).describe("Drop operation effect"); +var DragConstraintSchema = external_exports.object({ + axis: external_exports.enum(["x", "y", "both"]).default("both").describe("Constrain drag axis"), + bounds: external_exports.enum(["parent", "viewport", "none"]).default("none").describe("Constrain within bounds"), + grid: external_exports.tuple([external_exports.number(), external_exports.number()]).optional().describe("Snap to grid [x, y] in pixels") +}).describe("Drag movement constraints"); +var DropZoneSchema = external_exports.object({ + label: I18nLabelSchema4.optional().describe("Accessible label for the drop zone"), + accept: external_exports.array(external_exports.string()).describe("Accepted drag item types"), + maxItems: external_exports.number().optional().describe("Maximum items allowed in drop zone"), + highlightOnDragOver: external_exports.boolean().default(true).describe("Highlight drop zone when dragging over"), + dropEffect: DropEffectSchema.default("move").describe("Visual effect on drop") +}).merge(AriaPropsSchema4.partial()).describe("Drop zone configuration"); +var DragItemSchema = external_exports.object({ + type: external_exports.string().describe("Drag item type identifier for matching with drop zones"), + label: I18nLabelSchema4.optional().describe("Accessible label describing the draggable item"), + handle: DragHandleSchema.default("element").describe("How to initiate drag"), + constraint: DragConstraintSchema.optional().describe("Drag movement constraints"), + preview: external_exports.enum(["element", "custom", "none"]).default("element").describe("Drag preview type"), + disabled: external_exports.boolean().default(false).describe("Disable dragging") +}).merge(AriaPropsSchema4.partial()).describe("Draggable item configuration"); +var DndConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable drag and drop"), + dragItem: DragItemSchema.optional().describe("Configuration for draggable item"), + dropZone: DropZoneSchema.optional().describe("Configuration for drop target"), + sortable: external_exports.boolean().default(false).describe("Enable sortable list behavior"), + autoScroll: external_exports.boolean().default(true).describe("Auto-scroll during drag near edges"), + touchDelay: external_exports.number().default(200).describe("Delay in ms before drag starts on touch devices") +}).describe("Drag and drop interaction configuration"); + +// ../../packages/objectql/dist/index.mjs +init_data(); +var RESERVED_NAMESPACES = /* @__PURE__ */ new Set(["base", "system"]); +var DEFAULT_OWNER_PRIORITY = 100; +var DEFAULT_EXTENDER_PRIORITY = 200; +function computeFQN(namespace, shortName) { + if (!namespace || RESERVED_NAMESPACES.has(namespace)) { + return shortName; + } + return `${namespace}__${shortName}`; +} +function parseFQN(fqn) { + const idx = fqn.indexOf("__"); + if (idx === -1) { + return { namespace: void 0, shortName: fqn }; + } + return { + namespace: fqn.slice(0, idx), + shortName: fqn.slice(idx + 2) + }; +} +function mergeObjectDefinitions(base, extension) { + const merged = { ...base }; + if (extension.fields) { + merged.fields = { ...base.fields, ...extension.fields }; + } + if (extension.validations) { + merged.validations = [...base.validations || [], ...extension.validations]; + } + if (extension.indexes) { + merged.indexes = [...base.indexes || [], ...extension.indexes]; + } + if (extension.label !== void 0) merged.label = extension.label; + if (extension.pluralLabel !== void 0) merged.pluralLabel = extension.pluralLabel; + if (extension.description !== void 0) merged.description = extension.description; + return merged; +} +var SchemaRegistry = class { + static get logLevel() { + return this._logLevel; + } + static set logLevel(level) { + this._logLevel = level; + } + static log(msg) { + if (this._logLevel === "silent" || this._logLevel === "error" || this._logLevel === "warn") return; + console.log(msg); + } + // ========================================== + // Namespace Management + // ========================================== + /** + * Register a namespace for a package. + * Multiple packages can share the same namespace (e.g. 'sys'). + */ + static registerNamespace(namespace, packageId) { + if (!namespace) return; + let owners = this.namespaceRegistry.get(namespace); + if (!owners) { + owners = /* @__PURE__ */ new Set(); + this.namespaceRegistry.set(namespace, owners); + } + owners.add(packageId); + this.log(`[Registry] Registered namespace: ${namespace} \u2192 ${packageId}`); + } + /** + * Unregister a namespace when a package is uninstalled. + */ + static unregisterNamespace(namespace, packageId) { + const owners = this.namespaceRegistry.get(namespace); + if (owners) { + owners.delete(packageId); + if (owners.size === 0) { + this.namespaceRegistry.delete(namespace); + } + this.log(`[Registry] Unregistered namespace: ${namespace} \u2190 ${packageId}`); + } + } + /** + * Get the packages that use a namespace. + */ + static getNamespaceOwner(namespace) { + const owners = this.namespaceRegistry.get(namespace); + if (!owners || owners.size === 0) return void 0; + return owners.values().next().value; + } + /** + * Get all packages that share a namespace. + */ + static getNamespaceOwners(namespace) { + const owners = this.namespaceRegistry.get(namespace); + return owners ? Array.from(owners) : []; + } + // ========================================== + // Object Registration (Ownership Model) + // ========================================== + /** + * Register an object with ownership semantics. + * + * @param schema - The object definition + * @param packageId - The owning package ID + * @param namespace - The package namespace (for FQN computation) + * @param ownership - 'own' (single owner) or 'extend' (additive merge) + * @param priority - Merge priority (lower applied first, higher wins on conflict) + * + * @throws Error if trying to 'own' an object that already has an owner + */ + static registerObject(schema3, packageId, namespace, ownership = "own", priority = ownership === "own" ? DEFAULT_OWNER_PRIORITY : DEFAULT_EXTENDER_PRIORITY) { + const shortName = schema3.name; + const fqn = computeFQN(namespace, shortName); + if (namespace) { + this.registerNamespace(namespace, packageId); + } + let contributors = this.objectContributors.get(fqn); + if (!contributors) { + contributors = []; + this.objectContributors.set(fqn, contributors); + } + if (ownership === "own") { + const existingOwner = contributors.find((c) => c.ownership === "own"); + if (existingOwner && existingOwner.packageId !== packageId) { + throw new Error( + `Object "${fqn}" is already owned by package "${existingOwner.packageId}". Package "${packageId}" cannot claim ownership. Use 'extend' to add fields.` + ); + } + const idx = contributors.findIndex((c) => c.packageId === packageId && c.ownership === "own"); + if (idx !== -1) { + contributors.splice(idx, 1); + console.warn(`[Registry] Re-registering owned object: ${fqn} from ${packageId}`); + } + } else { + const idx = contributors.findIndex((c) => c.packageId === packageId && c.ownership === "extend"); + if (idx !== -1) { + contributors.splice(idx, 1); + } + } + const contributor = { + packageId, + namespace: namespace || "", + ownership, + priority, + definition: { ...schema3, name: fqn } + // Store with FQN as name + }; + contributors.push(contributor); + contributors.sort((a, b) => a.priority - b.priority); + this.mergedObjectCache.delete(fqn); + this.log(`[Registry] Registered object: ${fqn} (${ownership}, priority=${priority}) from ${packageId}`); + return fqn; + } + /** + * Resolve an object by FQN, merging all contributions. + * Returns the merged object or undefined if not found. + */ + static resolveObject(fqn) { + const cached2 = this.mergedObjectCache.get(fqn); + if (cached2) return cached2; + const contributors = this.objectContributors.get(fqn); + if (!contributors || contributors.length === 0) { + return void 0; + } + const ownerContrib = contributors.find((c) => c.ownership === "own"); + if (!ownerContrib) { + console.warn(`[Registry] Object "${fqn}" has extenders but no owner. Skipping.`); + return void 0; + } + let merged = { ...ownerContrib.definition }; + for (const contrib of contributors) { + if (contrib.ownership === "extend") { + merged = mergeObjectDefinitions(merged, contrib.definition); + } + } + this.mergedObjectCache.set(fqn, merged); + return merged; + } + /** + * Get object by name (FQN, short name, or physical table name). + * + * Resolution order: + * 1. Exact FQN match (e.g., 'crm__account') + * 2. Short name fallback (e.g., 'account' → 'crm__account') + * 3. Physical table name match (e.g., 'sys_user' → 'sys__user') + * ObjectSchema.create() auto-derives tableName as {namespace}_{name}, + * which uses a single underscore — different from the FQN double underscore. + */ + static getObject(name) { + const direct = this.resolveObject(name); + if (direct) return direct; + for (const fqn of this.objectContributors.keys()) { + const { shortName } = parseFQN(fqn); + if (shortName === name) { + return this.resolveObject(fqn); + } + } + for (const fqn of this.objectContributors.keys()) { + const resolved = this.resolveObject(fqn); + if (resolved?.tableName === name) { + return resolved; + } + } + return void 0; + } + /** + * Get all registered objects (merged). + * + * @param packageId - Optional filter: only objects contributed by this package + */ + static getAllObjects(packageId) { + const results = []; + for (const fqn of this.objectContributors.keys()) { + if (packageId) { + const contributors = this.objectContributors.get(fqn); + const hasContribution = contributors?.some((c) => c.packageId === packageId); + if (!hasContribution) continue; + } + const merged = this.resolveObject(fqn); + if (merged) { + merged._packageId = this.getObjectOwner(fqn)?.packageId; + results.push(merged); + } + } + return results; + } + /** + * Get all contributors for an object. + */ + static getObjectContributors(fqn) { + return this.objectContributors.get(fqn) || []; + } + /** + * Get the owner contributor for an object. + */ + static getObjectOwner(fqn) { + const contributors = this.objectContributors.get(fqn); + return contributors?.find((c) => c.ownership === "own"); + } + /** + * Unregister all objects contributed by a package. + * + * @throws Error if trying to uninstall an owner that has extenders + */ + static unregisterObjectsByPackage(packageId, force = false) { + for (const [fqn, contributors] of this.objectContributors.entries()) { + const packageContribs = contributors.filter((c) => c.packageId === packageId); + for (const contrib of packageContribs) { + if (contrib.ownership === "own" && !force) { + const otherExtenders = contributors.filter( + (c) => c.packageId !== packageId && c.ownership === "extend" + ); + if (otherExtenders.length > 0) { + throw new Error( + `Cannot uninstall package "${packageId}": object "${fqn}" is extended by ${otherExtenders.map((c) => c.packageId).join(", ")}. Uninstall extenders first.` + ); + } + } + const idx = contributors.indexOf(contrib); + if (idx !== -1) { + contributors.splice(idx, 1); + this.log(`[Registry] Removed ${contrib.ownership} contribution to ${fqn} from ${packageId}`); + } + } + if (contributors.length === 0) { + this.objectContributors.delete(fqn); + } + this.mergedObjectCache.delete(fqn); + } + } + // ========================================== + // Generic Metadata (Non-Object Types) + // ========================================== + /** + * Universal Register Method for non-object metadata. + */ + static registerItem(type, item, keyField = "name", packageId) { + if (!this.metadata.has(type)) { + this.metadata.set(type, /* @__PURE__ */ new Map()); + } + const collection = this.metadata.get(type); + const baseName = String(item[keyField]); + if (packageId) { + item._packageId = packageId; + } + try { + this.validate(type, item); + } catch (e) { + console.error(`[Registry] Validation failed for ${type} ${baseName}: ${e.message}`); + } + const storageKey = packageId ? `${packageId}:${baseName}` : baseName; + if (collection.has(storageKey)) { + console.warn(`[Registry] Overwriting ${type}: ${storageKey}`); + } + collection.set(storageKey, item); + this.log(`[Registry] Registered ${type}: ${storageKey}`); + } + /** + * Validate Metadata against Spec Zod Schemas + */ + static validate(type, item) { + if (type === "object") { + return ObjectSchema3.parse(item); + } + if (type === "app") { + return AppSchema2.parse(item); + } + if (type === "package") { + return InstalledPackageSchema2.parse(item); + } + if (type === "plugin") { + return ManifestSchema2.parse(item); + } + return true; + } + /** + * Universal Unregister Method + */ + static unregisterItem(type, name) { + const collection = this.metadata.get(type); + if (!collection) { + console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`); + return; + } + if (collection.has(name)) { + collection.delete(name); + this.log(`[Registry] Unregistered ${type}: ${name}`); + return; + } + for (const key of collection.keys()) { + if (key.endsWith(`:${name}`)) { + collection.delete(key); + this.log(`[Registry] Unregistered ${type}: ${key}`); + return; + } + } + console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`); + } + /** + * Universal Get Method + */ + static getItem(type, name) { + if (type === "object" || type === "objects") { + return this.getObject(name); + } + const collection = this.metadata.get(type); + if (!collection) return void 0; + const direct = collection.get(name); + if (direct) return direct; + for (const [key, item] of collection) { + if (key.endsWith(`:${name}`)) return item; + } + return void 0; + } + /** + * Universal List Method + */ + static listItems(type, packageId) { + if (type === "object" || type === "objects") { + return this.getAllObjects(packageId); + } + const items = Array.from(this.metadata.get(type)?.values() || []); + if (packageId) { + return items.filter((item) => item._packageId === packageId); + } + return items; + } + /** + * Get all registered metadata types (Kinds) + */ + static getRegisteredTypes() { + const types = Array.from(this.metadata.keys()); + if (!types.includes("object") && this.objectContributors.size > 0) { + types.push("object"); + } + return types; + } + // ========================================== + // Package Management + // ========================================== + static installPackage(manifest, settings) { + const now2 = (/* @__PURE__ */ new Date()).toISOString(); + const pkg = { + manifest, + status: "installed", + enabled: true, + installedAt: now2, + updatedAt: now2, + settings + }; + if (manifest.namespace) { + this.registerNamespace(manifest.namespace, manifest.id); + } + if (!this.metadata.has("package")) { + this.metadata.set("package", /* @__PURE__ */ new Map()); + } + const collection = this.metadata.get("package"); + if (collection.has(manifest.id)) { + console.warn(`[Registry] Overwriting package: ${manifest.id}`); + } + collection.set(manifest.id, pkg); + this.log(`[Registry] Installed package: ${manifest.id} (${manifest.name})`); + return pkg; + } + static uninstallPackage(id) { + const pkg = this.getPackage(id); + if (!pkg) { + console.warn(`[Registry] Package not found for uninstall: ${id}`); + return false; + } + if (pkg.manifest.namespace) { + this.unregisterNamespace(pkg.manifest.namespace, id); + } + this.unregisterObjectsByPackage(id); + const collection = this.metadata.get("package"); + if (collection) { + collection.delete(id); + this.log(`[Registry] Uninstalled package: ${id}`); + return true; + } + return false; + } + static getPackage(id) { + return this.metadata.get("package")?.get(id); + } + static getAllPackages() { + return this.listItems("package"); + } + static enablePackage(id) { + const pkg = this.getPackage(id); + if (pkg) { + pkg.enabled = true; + pkg.status = "installed"; + pkg.statusChangedAt = (/* @__PURE__ */ new Date()).toISOString(); + pkg.updatedAt = (/* @__PURE__ */ new Date()).toISOString(); + this.log(`[Registry] Enabled package: ${id}`); + } + return pkg; + } + static disablePackage(id) { + const pkg = this.getPackage(id); + if (pkg) { + pkg.enabled = false; + pkg.status = "disabled"; + pkg.statusChangedAt = (/* @__PURE__ */ new Date()).toISOString(); + pkg.updatedAt = (/* @__PURE__ */ new Date()).toISOString(); + this.log(`[Registry] Disabled package: ${id}`); + } + return pkg; + } + // ========================================== + // App Helpers + // ========================================== + static registerApp(app, packageId) { + this.registerItem("app", app, "name", packageId); + } + static getApp(name) { + return this.getItem("app", name); + } + static getAllApps() { + return this.listItems("app"); + } + // ========================================== + // Plugin Helpers + // ========================================== + static registerPlugin(manifest) { + this.registerItem("plugin", manifest, "id"); + } + static getAllPlugins() { + return this.listItems("plugin"); + } + // ========================================== + // Kind Helpers + // ========================================== + static registerKind(kind) { + this.registerItem("kind", kind, "id"); + } + static getAllKinds() { + return this.listItems("kind"); + } + // ========================================== + // Reset (for testing) + // ========================================== + /** + * Clear all registry state. Use only for testing. + */ + static reset() { + this.objectContributors.clear(); + this.mergedObjectCache.clear(); + this.namespaceRegistry.clear(); + this.metadata.clear(); + this.log("[Registry] Reset complete"); + } +}; +SchemaRegistry._logLevel = "info"; +SchemaRegistry.objectContributors = /* @__PURE__ */ new Map(); +SchemaRegistry.mergedObjectCache = /* @__PURE__ */ new Map(); +SchemaRegistry.namespaceRegistry = /* @__PURE__ */ new Map(); +SchemaRegistry.metadata = /* @__PURE__ */ new Map(); +function simpleHash(str) { + let hash2 = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash2 = (hash2 << 5) - hash2 + char; + hash2 = hash2 & hash2; + } + return Math.abs(hash2).toString(16); +} +var SERVICE_CONFIG = { + auth: { route: "/api/v1/auth", plugin: "plugin-auth" }, + automation: { route: "/api/v1/automation", plugin: "plugin-automation" }, + cache: { route: "/api/v1/cache", plugin: "plugin-redis" }, + queue: { route: "/api/v1/queue", plugin: "plugin-bullmq" }, + job: { route: "/api/v1/jobs", plugin: "job-scheduler" }, + ui: { route: "/api/v1/ui", plugin: "ui-plugin" }, + workflow: { route: "/api/v1/workflow", plugin: "plugin-workflow" }, + realtime: { route: "/api/v1/realtime", plugin: "plugin-realtime" }, + notification: { route: "/api/v1/notifications", plugin: "plugin-notifications" }, + ai: { route: "/api/v1/ai", plugin: "plugin-ai" }, + i18n: { route: "/api/v1/i18n", plugin: "service-i18n" }, + graphql: { route: "/graphql", plugin: "plugin-graphql" }, + // GraphQL uses /graphql by convention (not versioned REST) + "file-storage": { route: "/api/v1/storage", plugin: "plugin-storage" }, + search: { route: "/api/v1/search", plugin: "plugin-search" } +}; +var ObjectStackProtocolImplementation = class { + constructor(engine, getServicesRegistry, getFeedService) { + this.engine = engine; + this.getServicesRegistry = getServicesRegistry; + this.getFeedService = getFeedService; + } + requireFeedService() { + const svc = this.getFeedService?.(); + if (!svc) { + throw new Error("Feed service not available. Install and register service-feed to enable feed operations."); + } + return svc; + } + async getDiscovery() { + const registeredServices = this.getServicesRegistry ? this.getServicesRegistry() : /* @__PURE__ */ new Map(); + const services = { + // --- Kernel-provided (objectql is an example kernel implementation) --- + metadata: { enabled: true, status: "available", route: "/api/v1/meta", provider: "objectql" }, + data: { enabled: true, status: "available", route: "/api/v1/data", provider: "objectql" }, + analytics: { enabled: true, status: "available", route: "/api/v1/analytics", provider: "objectql" } + }; + for (const [serviceName, config4] of Object.entries(SERVICE_CONFIG)) { + if (registeredServices.has(serviceName)) { + services[serviceName] = { + enabled: true, + status: "available", + route: config4.route, + provider: config4.plugin + }; + } else { + services[serviceName] = { + enabled: false, + status: "unavailable", + message: `Install ${config4.plugin} to enable` + }; + } + } + const serviceToRouteKey = { + auth: "auth", + automation: "automation", + ui: "ui", + workflow: "workflow", + realtime: "realtime", + notification: "notifications", + ai: "ai", + i18n: "i18n", + graphql: "graphql", + "file-storage": "storage" + }; + const optionalRoutes = { + analytics: "/api/v1/analytics" + }; + for (const [serviceName, config4] of Object.entries(SERVICE_CONFIG)) { + if (registeredServices.has(serviceName)) { + const routeKey = serviceToRouteKey[serviceName]; + if (routeKey) { + optionalRoutes[routeKey] = config4.route; + } + } + } + if (registeredServices.has("feed")) { + services["feed"] = { + enabled: true, + status: "available", + route: "/api/v1/data", + provider: "service-feed" + }; + } else { + services["feed"] = { + enabled: false, + status: "unavailable", + message: "Install service-feed to enable" + }; + } + const routes = { + data: "/api/v1/data", + metadata: "/api/v1/meta", + ...optionalRoutes + }; + const wellKnown = { + feed: registeredServices.has("feed"), + comments: registeredServices.has("feed"), + automation: registeredServices.has("automation"), + cron: registeredServices.has("job"), + search: registeredServices.has("search"), + export: registeredServices.has("automation") || registeredServices.has("queue"), + chunkedUpload: registeredServices.has("file-storage") + }; + const capabilities = {}; + for (const [key, enabled] of Object.entries(wellKnown)) { + capabilities[key] = { enabled }; + } + return { + version: "1.0", + apiName: "ObjectStack API", + routes, + services, + capabilities + }; + } + async getMetaTypes() { + const schemaTypes = SchemaRegistry.getRegisteredTypes(); + let runtimeTypes = []; + try { + const services = this.getServicesRegistry?.(); + const metadataService = services?.get("metadata"); + if (metadataService && typeof metadataService.getRegisteredTypes === "function") { + runtimeTypes = await metadataService.getRegisteredTypes(); + } + } catch { + } + const allTypes = Array.from(/* @__PURE__ */ new Set([...schemaTypes, ...runtimeTypes])); + return { types: allTypes }; + } + async getMetaItems(request) { + const { packageId } = request; + let items = SchemaRegistry.listItems(request.type, packageId); + if (items.length === 0) { + const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; + if (alt) items = SchemaRegistry.listItems(alt, packageId); + } + if (items.length === 0) { + try { + const whereClause = { type: request.type, state: "active" }; + if (packageId) whereClause._packageId = packageId; + const allRecords = await this.engine.find("sys_metadata", { + where: whereClause + }); + if (allRecords && allRecords.length > 0) { + items = allRecords.map((record2) => { + const data = typeof record2.metadata === "string" ? JSON.parse(record2.metadata) : record2.metadata; + SchemaRegistry.registerItem(request.type, data, "name"); + return data; + }); + } else { + const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; + if (alt) { + const altRecords = await this.engine.find("sys_metadata", { + where: { type: alt, state: "active" } + }); + if (altRecords && altRecords.length > 0) { + items = altRecords.map((record2) => { + const data = typeof record2.metadata === "string" ? JSON.parse(record2.metadata) : record2.metadata; + SchemaRegistry.registerItem(request.type, data, "name"); + return data; + }); + } + } + } + } catch { + } + } + try { + const services = this.getServicesRegistry?.(); + const metadataService = services?.get("metadata"); + if (metadataService && typeof metadataService.list === "function") { + const runtimeItems = await metadataService.list(request.type); + if (runtimeItems && runtimeItems.length > 0) { + const itemMap = /* @__PURE__ */ new Map(); + for (const item of items) { + const entry = item; + if (entry && typeof entry === "object" && "name" in entry) { + itemMap.set(entry.name, entry); + } + } + for (const item of runtimeItems) { + const entry = item; + if (entry && typeof entry === "object" && "name" in entry) { + itemMap.set(entry.name, entry); + } + } + items = Array.from(itemMap.values()); + } + } + } catch { + } + return { + type: request.type, + items + }; + } + async getMetaItem(request) { + let item = SchemaRegistry.getItem(request.type, request.name); + if (item === void 0) { + const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; + if (alt) item = SchemaRegistry.getItem(alt, request.name); + } + if (item === void 0) { + try { + const record2 = await this.engine.findOne("sys_metadata", { + where: { type: request.type, name: request.name, state: "active" } + }); + if (record2) { + item = typeof record2.metadata === "string" ? JSON.parse(record2.metadata) : record2.metadata; + SchemaRegistry.registerItem(request.type, item, "name"); + } else { + const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; + if (alt) { + const altRecord = await this.engine.findOne("sys_metadata", { + where: { type: alt, name: request.name, state: "active" } + }); + if (altRecord) { + item = typeof altRecord.metadata === "string" ? JSON.parse(altRecord.metadata) : altRecord.metadata; + SchemaRegistry.registerItem(request.type, item, "name"); + } + } + } + } catch { + } + } + if (item === void 0) { + try { + const services = this.getServicesRegistry?.(); + const metadataService = services?.get("metadata"); + if (metadataService && typeof metadataService.get === "function") { + item = await metadataService.get(request.type, request.name); + } + } catch { + } + } + return { + type: request.type, + name: request.name, + item + }; + } + async getUiView(request) { + const schema3 = SchemaRegistry.getObject(request.object); + if (!schema3) throw new Error(`Object ${request.object} not found`); + const fields = schema3.fields || {}; + const fieldKeys = Object.keys(fields); + if (request.type === "list") { + const priorityFields = ["name", "title", "label", "subject", "email", "status", "type", "category", "created_at"]; + let columns = fieldKeys.filter((k) => priorityFields.includes(k)); + if (columns.length < 5) { + const remaining = fieldKeys.filter((k) => !columns.includes(k) && k !== "id" && !fields[k].hidden); + columns = [...columns, ...remaining.slice(0, 5 - columns.length)]; + } + return { + list: { + type: "grid", + object: request.object, + label: schema3.label || schema3.name, + columns: columns.map((f) => ({ + field: f, + label: fields[f]?.label || f, + sortable: true + })), + sort: fields["created_at"] ? [{ field: "created_at", order: "desc" }] : void 0, + searchableFields: columns.slice(0, 3) + // Make first few textual columns searchable + } + }; + } else { + const formFields = fieldKeys.filter((k) => k !== "id" && k !== "created_at" && k !== "updated_at" && !fields[k].hidden).map((f) => ({ + field: f, + label: fields[f]?.label, + required: fields[f]?.required, + readonly: fields[f]?.readonly, + type: fields[f]?.type, + // Default to 2 columns for most, 1 for textareas + colSpan: fields[f]?.type === "textarea" || fields[f]?.type === "html" ? 2 : 1 + })); + return { + form: { + type: "simple", + object: request.object, + label: `Edit ${schema3.label || schema3.name}`, + sections: [ + { + label: "General Information", + columns: 2, + collapsible: false, + collapsed: false, + fields: formFields + } + ] + } + }; + } + } + async findData(request) { + const options = { ...request.query }; + if (options.top != null) { + options.limit = Number(options.top); + delete options.top; + } + if (options.skip != null) { + options.offset = Number(options.skip); + delete options.skip; + } + if (options.limit != null) options.limit = Number(options.limit); + if (options.offset != null) options.offset = Number(options.offset); + if (typeof options.select === "string") { + options.fields = options.select.split(",").map((s) => s.trim()).filter(Boolean); + } else if (Array.isArray(options.select)) { + options.fields = options.select; + } + if (options.select !== void 0) delete options.select; + const sortValue = options.orderBy ?? options.sort; + if (typeof sortValue === "string") { + const parsed = sortValue.split(",").map((part) => { + const trimmed = part.trim(); + if (trimmed.startsWith("-")) { + return { field: trimmed.slice(1), order: "desc" }; + } + const [field, order] = trimmed.split(/\s+/); + return { field, order: order?.toLowerCase() === "desc" ? "desc" : "asc" }; + }).filter((s) => s.field); + options.orderBy = parsed; + } else if (Array.isArray(sortValue)) { + options.orderBy = sortValue; + } + delete options.sort; + const filterValue = options.filter ?? options.filters ?? options.$filter ?? options.where; + delete options.filter; + delete options.filters; + delete options.$filter; + if (filterValue !== void 0) { + let parsedFilter = filterValue; + if (typeof parsedFilter === "string") { + try { + parsedFilter = JSON.parse(parsedFilter); + } catch { + } + } + if (isFilterAST(parsedFilter)) { + parsedFilter = parseFilterAST(parsedFilter); + } + options.where = parsedFilter; + } + const populateValue = options.populate; + const expandValue = options.$expand ?? options.expand; + const expandNames = []; + if (typeof populateValue === "string") { + expandNames.push(...populateValue.split(",").map((s) => s.trim()).filter(Boolean)); + } else if (Array.isArray(populateValue)) { + expandNames.push(...populateValue); + } + if (!expandNames.length && expandValue) { + if (typeof expandValue === "string") { + expandNames.push(...expandValue.split(",").map((s) => s.trim()).filter(Boolean)); + } else if (Array.isArray(expandValue)) { + expandNames.push(...expandValue); + } + } + delete options.populate; + delete options.$expand; + if (typeof options.expand !== "object" || options.expand === null) { + delete options.expand; + } + if (expandNames.length > 0 && !options.expand) { + options.expand = {}; + for (const rel of expandNames) { + options.expand[rel] = { object: rel }; + } + } + for (const key of ["distinct", "count"]) { + if (options[key] === "true") options[key] = true; + else if (options[key] === "false") options[key] = false; + } + const knownParams = /* @__PURE__ */ new Set([ + "top", + "limit", + "offset", + "orderBy", + "fields", + "where", + "expand", + "distinct", + "count", + "aggregations", + "groupBy", + "search", + "context", + "cursor" + ]); + if (!options.where) { + const implicitFilters = {}; + for (const key of Object.keys(options)) { + if (!knownParams.has(key)) { + implicitFilters[key] = options[key]; + delete options[key]; + } + } + if (Object.keys(implicitFilters).length > 0) { + options.where = implicitFilters; + } + } + const records = await this.engine.find(request.object, options); + return { + object: request.object, + records, + total: records.length, + hasMore: false + }; + } + async getData(request) { + const queryOptions = { + where: { id: request.id } + }; + if (request.select) { + queryOptions.fields = typeof request.select === "string" ? request.select.split(",").map((s) => s.trim()).filter(Boolean) : request.select; + } + if (request.expand) { + const expandNames = typeof request.expand === "string" ? request.expand.split(",").map((s) => s.trim()).filter(Boolean) : request.expand; + queryOptions.expand = {}; + for (const rel of expandNames) { + queryOptions.expand[rel] = { object: rel }; + } + } + const result = await this.engine.findOne(request.object, queryOptions); + if (result) { + return { + object: request.object, + id: request.id, + record: result + }; + } + throw new Error(`Record ${request.id} not found in ${request.object}`); + } + async createData(request) { + const result = await this.engine.insert(request.object, request.data); + return { + object: request.object, + id: result.id, + record: result + }; + } + async updateData(request) { + const result = await this.engine.update(request.object, request.data, { where: { id: request.id } }); + return { + object: request.object, + id: request.id, + record: result + }; + } + async deleteData(request) { + await this.engine.delete(request.object, { where: { id: request.id } }); + return { + object: request.object, + id: request.id, + success: true + }; + } + // ========================================== + // Metadata Caching + // ========================================== + async getMetaItemCached(request) { + try { + let item = SchemaRegistry.getItem(request.type, request.name); + if (!item) { + const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; + if (alt) item = SchemaRegistry.getItem(alt, request.name); + } + if (!item) { + try { + const services = this.getServicesRegistry?.(); + const metadataService = services?.get("metadata"); + if (metadataService && typeof metadataService.get === "function") { + item = await metadataService.get(request.type, request.name); + } + } catch { + } + } + if (!item) { + throw new Error(`Metadata item ${request.type}/${request.name} not found`); + } + const content = JSON.stringify(item); + const hash2 = simpleHash(content); + const etag = { value: hash2, weak: false }; + if (request.cacheRequest?.ifNoneMatch) { + const clientEtag = request.cacheRequest.ifNoneMatch.replace(/^"(.*)"$/, "$1").replace(/^W\/"(.*)"$/, "$1"); + if (clientEtag === hash2) { + return { + notModified: true, + etag + }; + } + } + return { + data: item, + etag, + lastModified: (/* @__PURE__ */ new Date()).toISOString(), + cacheControl: { + directives: ["public", "max-age"], + maxAge: 3600 + // 1 hour + }, + notModified: false + }; + } catch (error49) { + throw error49; + } + } + // ========================================== + // Batch Operations + // ========================================== + async batchData(request) { + const { object: object2, request: batchReq } = request; + const { operation, records, options } = batchReq; + const results = []; + let succeeded = 0; + let failed = 0; + for (const record2 of records) { + try { + switch (operation) { + case "create": { + const created = await this.engine.insert(object2, record2.data || record2); + results.push({ id: created.id, success: true, record: created }); + succeeded++; + break; + } + case "update": { + if (!record2.id) throw new Error("Record id is required for update"); + const updated = await this.engine.update(object2, record2.data || {}, { where: { id: record2.id } }); + results.push({ id: record2.id, success: true, record: updated }); + succeeded++; + break; + } + case "upsert": { + if (record2.id) { + try { + const existing = await this.engine.findOne(object2, { where: { id: record2.id } }); + if (existing) { + const updated = await this.engine.update(object2, record2.data || {}, { where: { id: record2.id } }); + results.push({ id: record2.id, success: true, record: updated }); + } else { + const created = await this.engine.insert(object2, { id: record2.id, ...record2.data || {} }); + results.push({ id: created.id, success: true, record: created }); + } + } catch { + const created = await this.engine.insert(object2, { id: record2.id, ...record2.data || {} }); + results.push({ id: created.id, success: true, record: created }); + } + } else { + const created = await this.engine.insert(object2, record2.data || record2); + results.push({ id: created.id, success: true, record: created }); + } + succeeded++; + break; + } + case "delete": { + if (!record2.id) throw new Error("Record id is required for delete"); + await this.engine.delete(object2, { where: { id: record2.id } }); + results.push({ id: record2.id, success: true }); + succeeded++; + break; + } + default: + results.push({ id: record2.id, success: false, error: `Unknown operation: ${operation}` }); + failed++; + } + } catch (err) { + results.push({ id: record2.id, success: false, error: err.message }); + failed++; + if (options?.atomic) { + break; + } + if (!options?.continueOnError) { + break; + } + } + } + return { + success: failed === 0, + operation, + total: records.length, + succeeded, + failed, + results: options?.returnRecords !== false ? results : results.map((r) => ({ id: r.id, success: r.success, error: r.error })) + }; + } + async createManyData(request) { + const records = await this.engine.insert(request.object, request.records); + return { + object: request.object, + records, + count: records.length + }; + } + async updateManyData(request) { + const { object: object2, records, options } = request; + const results = []; + let succeeded = 0; + let failed = 0; + for (const record2 of records) { + try { + const updated = await this.engine.update(object2, record2.data, { where: { id: record2.id } }); + results.push({ id: record2.id, success: true, record: updated }); + succeeded++; + } catch (err) { + results.push({ id: record2.id, success: false, error: err.message }); + failed++; + if (!options?.continueOnError) { + break; + } + } + } + return { + success: failed === 0, + operation: "update", + total: records.length, + succeeded, + failed, + results + }; + } + async analyticsQuery(request) { + const { query, cube } = request; + const object2 = cube; + const groupBy2 = query.dimensions || []; + const aggregations = []; + if (query.measures) { + for (const measure of query.measures) { + if (measure === "count" || measure === "count_all") { + aggregations.push({ field: "*", method: "count", alias: "count" }); + } else if (measure.includes(".")) { + const [field, method] = measure.split("."); + aggregations.push({ field, method, alias: `${field}_${method}` }); + } else { + aggregations.push({ field: measure, method: "sum", alias: measure }); + } + } + } + let filter = void 0; + if (query.filters && query.filters.length > 0) { + const conditions = query.filters.map((f) => { + const op = this.mapAnalyticsOperator(f.operator); + if (f.values && f.values.length === 1) { + return { [f.member]: { [op]: f.values[0] } }; + } else if (f.values && f.values.length > 1) { + return { [f.member]: { $in: f.values } }; + } + return { [f.member]: { [op]: true } }; + }); + filter = conditions.length === 1 ? conditions[0] : { $and: conditions }; + } + const rows = await this.engine.aggregate(object2, { + where: filter, + groupBy: groupBy2.length > 0 ? groupBy2 : void 0, + aggregations: aggregations.length > 0 ? aggregations.map((a) => ({ function: a.method, field: a.field, alias: a.alias })) : [{ function: "count", alias: "count" }] + }); + const fields = [ + ...groupBy2.map((d) => ({ name: d, type: "string" })), + ...aggregations.map((a) => ({ name: a.alias, type: "number" })) + ]; + return { + success: true, + data: { + rows, + fields + } + }; + } + async getAnalyticsMeta(request) { + const objects = SchemaRegistry.listItems("object"); + const cubeFilter = request?.cube; + const cubes = []; + for (const obj of objects) { + const schema3 = obj; + if (cubeFilter && schema3.name !== cubeFilter) continue; + const measures = {}; + const dimensions = {}; + const fields = schema3.fields || {}; + measures["count"] = { + name: "count", + label: "Count", + type: "count", + sql: "*" + }; + for (const [fieldName, fieldDef] of Object.entries(fields)) { + const fd = fieldDef; + const fieldType = fd.type || "text"; + if (["number", "currency", "percent"].includes(fieldType)) { + measures[`${fieldName}_sum`] = { + name: `${fieldName}_sum`, + label: `${fd.label || fieldName} (Sum)`, + type: "sum", + sql: fieldName + }; + measures[`${fieldName}_avg`] = { + name: `${fieldName}_avg`, + label: `${fd.label || fieldName} (Avg)`, + type: "avg", + sql: fieldName + }; + dimensions[fieldName] = { + name: fieldName, + label: fd.label || fieldName, + type: "number", + sql: fieldName + }; + } else if (["date", "datetime"].includes(fieldType)) { + dimensions[fieldName] = { + name: fieldName, + label: fd.label || fieldName, + type: "time", + sql: fieldName, + granularities: ["day", "week", "month", "quarter", "year"] + }; + } else if (["boolean"].includes(fieldType)) { + dimensions[fieldName] = { + name: fieldName, + label: fd.label || fieldName, + type: "boolean", + sql: fieldName + }; + } else { + dimensions[fieldName] = { + name: fieldName, + label: fd.label || fieldName, + type: "string", + sql: fieldName + }; + } + } + cubes.push({ + name: schema3.name, + title: schema3.label || schema3.name, + description: schema3.description, + sql: schema3.name, + measures, + dimensions, + public: true + }); + } + return { + success: true, + data: { cubes } + }; + } + mapAnalyticsOperator(op) { + const map3 = { + equals: "$eq", + notEquals: "$ne", + contains: "$contains", + notContains: "$notContains", + gt: "$gt", + gte: "$gte", + lt: "$lt", + lte: "$lte", + set: "$ne", + notSet: "$eq" + }; + return map3[op] || "$eq"; + } + async triggerAutomation(_request2) { + throw new Error('triggerAutomation requires plugin-automation service. Install and register a plugin that provides the "automation" service.'); + } + async deleteManyData(request) { + return this.engine.delete(request.object, { + where: { id: { $in: request.ids } }, + ...request.options + }); + } + async saveMetaItem(request) { + if (!request.item) { + throw new Error("Item data is required"); + } + SchemaRegistry.registerItem(request.type, request.item, "name"); + try { + const now2 = (/* @__PURE__ */ new Date()).toISOString(); + const existing = await this.engine.findOne("sys_metadata", { + where: { type: request.type, name: request.name } + }); + if (existing) { + await this.engine.update("sys_metadata", { + metadata: JSON.stringify(request.item), + updated_at: now2, + version: (existing.version || 0) + 1 + }, { + where: { id: existing.id } + }); + } else { + const id = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `meta_${Date.now()}_${Math.random().toString(36).slice(2)}`; + await this.engine.insert("sys_metadata", { + id, + name: request.name, + type: request.type, + scope: "platform", + metadata: JSON.stringify(request.item), + state: "active", + version: 1, + created_at: now2, + updated_at: now2 + }); + } + return { + success: true, + message: "Saved to database and registry" + }; + } catch (dbError) { + console.warn(`[Protocol] DB persistence failed for ${request.type}/${request.name}: ${dbError.message}`); + return { + success: true, + message: "Saved to memory registry (DB persistence unavailable)", + warning: dbError.message + }; + } + } + /** + * Hydrate SchemaRegistry from the database on startup. + * Loads all active metadata records and registers them in the in-memory registry. + * Safe to call repeatedly — idempotent (latest DB record wins). + */ + async loadMetaFromDb() { + let loaded = 0; + let errors = 0; + try { + const records = await this.engine.find("sys_metadata", { + where: { state: "active" } + }); + for (const record2 of records) { + try { + const data = typeof record2.metadata === "string" ? JSON.parse(record2.metadata) : record2.metadata; + const normalizedType = PLURAL_TO_SINGULAR[record2.type] ?? record2.type; + if (normalizedType === "object") { + SchemaRegistry.registerObject(data, record2.packageId || "sys_metadata"); + } else { + SchemaRegistry.registerItem(normalizedType, data, "name"); + } + loaded++; + } catch (e) { + errors++; + console.warn(`[Protocol] Failed to hydrate ${record2.type}/${record2.name}: ${e instanceof Error ? e.message : String(e)}`); + } + } + } catch (e) { + console.warn(`[Protocol] DB hydration skipped: ${e.message}`); + } + return { loaded, errors }; + } + // ========================================== + // Feed Operations + // ========================================== + async listFeed(request) { + const svc = this.requireFeedService(); + const result = await svc.listFeed({ + object: request.object, + recordId: request.recordId, + filter: request.type, + limit: request.limit, + cursor: request.cursor + }); + return { success: true, data: result }; + } + async createFeedItem(request) { + const svc = this.requireFeedService(); + const item = await svc.createFeedItem({ + object: request.object, + recordId: request.recordId, + type: request.type, + actor: { type: "user", id: "current_user" }, + body: request.body, + mentions: request.mentions, + parentId: request.parentId, + visibility: request.visibility + }); + return { success: true, data: item }; + } + async updateFeedItem(request) { + const svc = this.requireFeedService(); + const item = await svc.updateFeedItem(request.feedId, { + body: request.body, + mentions: request.mentions, + visibility: request.visibility + }); + return { success: true, data: item }; + } + async deleteFeedItem(request) { + const svc = this.requireFeedService(); + await svc.deleteFeedItem(request.feedId); + return { success: true, data: { feedId: request.feedId } }; + } + async addReaction(request) { + const svc = this.requireFeedService(); + const reactions = await svc.addReaction(request.feedId, request.emoji, "current_user"); + return { success: true, data: { reactions } }; + } + async removeReaction(request) { + const svc = this.requireFeedService(); + const reactions = await svc.removeReaction(request.feedId, request.emoji, "current_user"); + return { success: true, data: { reactions } }; + } + async pinFeedItem(request) { + const svc = this.requireFeedService(); + const item = await svc.getFeedItem(request.feedId); + if (!item) throw new Error(`Feed item ${request.feedId} not found`); + await svc.updateFeedItem(request.feedId, { visibility: item.visibility }); + return { success: true, data: { feedId: request.feedId, pinned: true, pinnedAt: (/* @__PURE__ */ new Date()).toISOString() } }; + } + async unpinFeedItem(request) { + const svc = this.requireFeedService(); + const item = await svc.getFeedItem(request.feedId); + if (!item) throw new Error(`Feed item ${request.feedId} not found`); + await svc.updateFeedItem(request.feedId, { visibility: item.visibility }); + return { success: true, data: { feedId: request.feedId, pinned: false } }; + } + async starFeedItem(request) { + const svc = this.requireFeedService(); + const item = await svc.getFeedItem(request.feedId); + if (!item) throw new Error(`Feed item ${request.feedId} not found`); + await svc.updateFeedItem(request.feedId, { visibility: item.visibility }); + return { success: true, data: { feedId: request.feedId, starred: true, starredAt: (/* @__PURE__ */ new Date()).toISOString() } }; + } + async unstarFeedItem(request) { + const svc = this.requireFeedService(); + const item = await svc.getFeedItem(request.feedId); + if (!item) throw new Error(`Feed item ${request.feedId} not found`); + await svc.updateFeedItem(request.feedId, { visibility: item.visibility }); + return { success: true, data: { feedId: request.feedId, starred: false } }; + } + async searchFeed(request) { + const svc = this.requireFeedService(); + const result = await svc.listFeed({ + object: request.object, + recordId: request.recordId, + filter: request.type, + limit: request.limit, + cursor: request.cursor + }); + const queryLower = (request.query || "").toLowerCase(); + const filtered = result.items.filter( + (item) => item.body?.toLowerCase().includes(queryLower) + ); + return { success: true, data: { items: filtered, total: filtered.length, hasMore: false } }; + } + async getChangelog(request) { + const svc = this.requireFeedService(); + const result = await svc.listFeed({ + object: request.object, + recordId: request.recordId, + filter: "changes_only", + limit: request.limit, + cursor: request.cursor + }); + const entries = result.items.map((item) => ({ + id: item.id, + object: item.object, + recordId: item.recordId, + actor: item.actor, + changes: item.changes || [], + timestamp: item.createdAt, + source: item.source + })); + return { success: true, data: { entries, total: result.total, nextCursor: result.nextCursor, hasMore: result.hasMore } }; + } + async feedSubscribe(request) { + const svc = this.requireFeedService(); + const subscription = await svc.subscribe({ + object: request.object, + recordId: request.recordId, + userId: "current_user", + events: request.events, + channels: request.channels + }); + return { success: true, data: subscription }; + } + async feedUnsubscribe(request) { + const svc = this.requireFeedService(); + const unsubscribed = await svc.unsubscribe(request.object, request.recordId, "current_user"); + return { success: true, data: { object: request.object, recordId: request.recordId, unsubscribed } }; + } +}; +var _ObjectQL = class _ObjectQL2 { + constructor(hostContext = {}) { + this.drivers = /* @__PURE__ */ new Map(); + this.defaultDriver = null; + this.hooks = /* @__PURE__ */ new Map([ + ["beforeFind", []], + ["afterFind", []], + ["beforeInsert", []], + ["afterInsert", []], + ["beforeUpdate", []], + ["afterUpdate", []], + ["beforeDelete", []], + ["afterDelete", []] + ]); + this.middlewares = []; + this.actions = /* @__PURE__ */ new Map(); + this.hostContext = {}; + this.hostContext = hostContext; + this.logger = hostContext.logger || createLogger({ level: "info", format: "pretty" }); + this.logger.info("ObjectQL Engine Instance Created"); + } + /** + * Service Status Report + * Used by Kernel to verify health and capabilities. + */ + getStatus() { + return { + name: CoreServiceName.enum.data, + status: "running", + version: "0.9.0", + features: ["crud", "query", "aggregate", "transactions", "metadata"] + }; + } + /** + * Expose the SchemaRegistry for plugins to register metadata + */ + get registry() { + return SchemaRegistry; + } + /** + * Load and Register a Plugin + */ + async use(manifestPart, runtimePart) { + this.logger.debug("Loading plugin", { + hasManifest: !!manifestPart, + hasRuntime: !!runtimePart + }); + if (manifestPart) { + this.registerApp(manifestPart); + } + if (runtimePart) { + const pluginDef = runtimePart.default || runtimePart; + if (pluginDef.onEnable) { + this.logger.debug("Executing plugin runtime onEnable"); + const context = { + ql: this, + logger: this.logger, + // Expose the driver registry helper explicitly if needed + drivers: { + register: (driver) => this.registerDriver(driver) + }, + ...this.hostContext + }; + await pluginDef.onEnable(context); + this.logger.debug("Plugin runtime onEnable completed"); + } + } + } + /** + * Register a hook + * @param event The event name (e.g. 'beforeFind', 'afterInsert') + * @param handler The handler function + * @param options Optional: target object(s) and priority + */ + registerHook(event, handler, options) { + if (!this.hooks.has(event)) { + this.hooks.set(event, []); + } + const entries = this.hooks.get(event); + entries.push({ + handler, + object: options?.object, + priority: options?.priority ?? 100, + packageId: options?.packageId + }); + entries.sort((a, b) => a.priority - b.priority); + this.logger.debug("Registered hook", { event, object: options?.object, priority: options?.priority ?? 100, totalHandlers: entries.length }); + } + async triggerHooks(event, context) { + const entries = this.hooks.get(event) || []; + if (entries.length === 0) { + this.logger.debug("No hooks registered for event", { event }); + return; + } + this.logger.debug("Triggering hooks", { event, count: entries.length }); + for (const entry of entries) { + if (entry.object) { + const targets = Array.isArray(entry.object) ? entry.object : [entry.object]; + if (!targets.includes("*") && !targets.includes(context.object)) { + continue; + } + } + await entry.handler(context); + } + } + // ======================================== + // Action System + // ======================================== + /** + * Register a named action on an object. + * Actions are custom business logic callable via `repo.execute(actionName, params)`. + * + * @param objectName Target object + * @param actionName Unique action name within the object + * @param handler Handler function + * @param packageName Optional package owner (for cleanup) + */ + registerAction(objectName, actionName, handler, packageName) { + const key = `${objectName}:${actionName}`; + this.actions.set(key, { handler, package: packageName }); + this.logger.debug("Registered action", { objectName, actionName, package: packageName }); + } + /** + * Execute a named action on an object. + */ + async executeAction(objectName, actionName, ctx) { + const entry = this.actions.get(`${objectName}:${actionName}`); + if (!entry) { + throw new Error(`Action '${actionName}' on object '${objectName}' not found`); + } + return entry.handler(ctx); + } + /** + * Remove all actions registered by a specific package. + */ + removeActionsByPackage(packageName) { + for (const [key, entry] of this.actions.entries()) { + if (entry.package === packageName) { + this.actions.delete(key); + } + } + } + /** + * Register a middleware function + * Middlewares execute in onion model around every data operation. + * @param fn The middleware function + * @param options Optional: target object filter + */ + registerMiddleware(fn, options) { + this.middlewares.push({ fn, object: options?.object }); + this.logger.debug("Registered middleware", { object: options?.object, total: this.middlewares.length }); + } + /** + * Execute an operation through the middleware chain + */ + async executeWithMiddleware(ctx, executor) { + const applicable = this.middlewares.filter( + (m) => !m.object || m.object === "*" || m.object === ctx.object + ); + let index = 0; + const next = async () => { + if (index < applicable.length) { + const mw = applicable[index++]; + await mw.fn(ctx, next); + } else { + ctx.result = await executor(); + } + }; + await next(); + return ctx.result; + } + /** + * Build a HookContext.session from ExecutionContext + */ + buildSession(execCtx) { + if (!execCtx) return void 0; + return { + userId: execCtx.userId, + tenantId: execCtx.tenantId, + roles: execCtx.roles, + accessToken: execCtx.accessToken + }; + } + /** + * Register contribution (Manifest) + * + * Installs the manifest as a Package (the unit of installation), + * then decomposes it into individual metadata items (objects, apps, actions, etc.) + * and registers each into the SchemaRegistry. + * + * Key: Package ≠ App. The manifest is the package. The apps[] array inside + * the manifest contains UI navigation definitions (AppSchema). + */ + registerApp(manifest) { + const id = manifest.id || manifest.name; + const namespace = manifest.namespace; + this.logger.debug("Registering package manifest", { id, namespace }); + SchemaRegistry.installPackage(manifest); + this.logger.debug("Installed Package", { id: manifest.id, name: manifest.name, namespace }); + if (manifest.objects) { + if (Array.isArray(manifest.objects)) { + this.logger.debug("Registering objects from manifest (Array)", { id, objectCount: manifest.objects.length }); + for (const objDef of manifest.objects) { + const fqn = SchemaRegistry.registerObject(objDef, id, namespace, "own"); + this.logger.debug("Registered Object", { fqn, from: id }); + } + } else { + this.logger.debug("Registering objects from manifest (Map)", { id, objectCount: Object.keys(manifest.objects).length }); + for (const [name, objDef] of Object.entries(manifest.objects)) { + objDef.name = name; + const fqn = SchemaRegistry.registerObject(objDef, id, namespace, "own"); + this.logger.debug("Registered Object", { fqn, from: id }); + } + } + } + if (Array.isArray(manifest.objectExtensions) && manifest.objectExtensions.length > 0) { + this.logger.debug("Registering object extensions", { id, count: manifest.objectExtensions.length }); + for (const ext of manifest.objectExtensions) { + const targetFqn = ext.extend; + const priority = ext.priority ?? 200; + const extDef = { + name: targetFqn, + // Use the target FQN as name + fields: ext.fields, + label: ext.label, + pluralLabel: ext.pluralLabel, + description: ext.description, + validations: ext.validations, + indexes: ext.indexes + }; + SchemaRegistry.registerObject(extDef, id, void 0, "extend", priority); + this.logger.debug("Registered Object Extension", { target: targetFqn, priority, from: id }); + } + } + if (Array.isArray(manifest.apps) && manifest.apps.length > 0) { + this.logger.debug("Registering apps from manifest", { id, count: manifest.apps.length }); + for (const app of manifest.apps) { + const appName = app.name || app.id; + if (appName) { + SchemaRegistry.registerApp(app, id); + this.logger.debug("Registered App", { app: appName, from: id }); + } + } + } + if (manifest.name && manifest.navigation && !manifest.apps?.length) { + SchemaRegistry.registerApp(manifest, id); + this.logger.debug("Registered manifest-as-app", { app: manifest.name, from: id }); + } + const metadataArrayKeys = [ + // UI Protocol + "actions", + "views", + "pages", + "dashboards", + "reports", + "themes", + // Automation Protocol + "flows", + "workflows", + "approvals", + "webhooks", + // Security Protocol + "roles", + "permissions", + "profiles", + "sharingRules", + "policies", + // AI Protocol + "agents", + "ragPipelines", + // API Protocol + "apis", + // Data Extensions + "hooks", + "mappings", + "analyticsCubes", + // Integration Protocol + "connectors" + ]; + for (const key of metadataArrayKeys) { + const items = manifest[key]; + if (Array.isArray(items) && items.length > 0) { + this.logger.debug(`Registering ${key} from manifest`, { id, count: items.length }); + for (const item of items) { + const itemName = item.name || item.id; + if (itemName) { + SchemaRegistry.registerItem(pluralToSingular(key), item, "name", id); + } + } + } + } + const seedData = manifest.data; + if (Array.isArray(seedData) && seedData.length > 0) { + this.logger.debug("Registering seed data datasets", { id, count: seedData.length }); + for (const dataset of seedData) { + if (dataset.object) { + SchemaRegistry.registerItem("data", dataset, "object", id); + } + } + } + if (manifest.contributes?.kinds) { + this.logger.debug("Registering kinds from manifest", { id, kindCount: manifest.contributes.kinds.length }); + for (const kind of manifest.contributes.kinds) { + SchemaRegistry.registerKind(kind); + this.logger.debug("Registered Kind", { kind: kind.name || kind.type, from: id }); + } + } + if (Array.isArray(manifest.plugins) && manifest.plugins.length > 0) { + this.logger.debug("Processing nested plugins", { id, count: manifest.plugins.length }); + for (const plugin of manifest.plugins) { + if (plugin && typeof plugin === "object") { + const pluginName = plugin.name || plugin.id || "unnamed-plugin"; + this.logger.debug("Registering nested plugin", { pluginName, parentId: id }); + this.registerPlugin(plugin, id, namespace); + } + } + } + } + /** + * Register a nested plugin's metadata (objects, actions, views, etc.) + * + * Unlike registerApp(), this does NOT call SchemaRegistry.installPackage() + * because plugins are not formal manifests — they are lightweight config + * bundles with objects, actions, triggers, and navigation. + * + * @param plugin - The plugin config object + * @param parentId - The parent package ID (for ownership tracking) + * @param parentNamespace - The parent package's namespace (for FQN resolution) + */ + registerPlugin(plugin, parentId, parentNamespace) { + const pluginName = plugin.name || plugin.id || "unnamed"; + const pluginNamespace = plugin.namespace || parentNamespace; + const ownerId = parentId; + if (plugin.objects) { + try { + if (Array.isArray(plugin.objects)) { + this.logger.debug("Registering plugin objects (Array)", { pluginName, count: plugin.objects.length }); + for (const objDef of plugin.objects) { + const fqn = SchemaRegistry.registerObject(objDef, ownerId, pluginNamespace, "own"); + this.logger.debug("Registered Object", { fqn, from: pluginName }); + } + } else { + const entries = Object.entries(plugin.objects); + this.logger.debug("Registering plugin objects (Map)", { pluginName, count: entries.length }); + for (const [name, objDef] of entries) { + objDef.name = name; + const fqn = SchemaRegistry.registerObject(objDef, ownerId, pluginNamespace, "own"); + this.logger.debug("Registered Object", { fqn, from: pluginName }); + } + } + } catch (err) { + this.logger.warn("Failed to register plugin objects", { pluginName, error: err.message }); + } + } + if (plugin.name && plugin.navigation) { + try { + SchemaRegistry.registerApp(plugin, ownerId); + this.logger.debug("Registered plugin-as-app", { app: plugin.name, from: pluginName }); + } catch (err) { + this.logger.warn("Failed to register plugin as app", { pluginName, error: err.message }); + } + } + const metadataArrayKeys = [ + "actions", + "views", + "pages", + "dashboards", + "reports", + "themes", + "flows", + "workflows", + "approvals", + "webhooks", + "roles", + "permissions", + "profiles", + "sharingRules", + "policies", + "agents", + "ragPipelines", + "apis", + "hooks", + "mappings", + "analyticsCubes", + "connectors" + ]; + for (const key of metadataArrayKeys) { + const items = plugin[key]; + if (Array.isArray(items) && items.length > 0) { + for (const item of items) { + const itemName = item.name || item.id; + if (itemName) { + SchemaRegistry.registerItem(pluralToSingular(key), item, "name", ownerId); + } + } + } + } + } + /** + * Register a new storage driver + */ + registerDriver(driver, isDefault = false) { + if (this.drivers.has(driver.name)) { + this.logger.warn("Driver already registered, skipping", { driverName: driver.name }); + return; + } + this.drivers.set(driver.name, driver); + this.logger.info("Registered driver", { + driverName: driver.name, + version: driver.version + }); + if (isDefault || this.drivers.size === 1) { + this.defaultDriver = driver.name; + this.logger.info("Set default driver", { driverName: driver.name }); + } + } + /** + * Set the realtime service for publishing data change events. + * Should be called after kernel resolves the realtime service. + * + * @param service - An IRealtimeService instance for event publishing + */ + setRealtimeService(service) { + this.realtimeService = service; + this.logger.info("RealtimeService configured for data events"); + } + /** + * Helper to get object definition + */ + getSchema(objectName) { + return SchemaRegistry.getObject(objectName); + } + /** + * Resolve an object name to its Fully Qualified Name (FQN). + * + * Short names like 'task' are resolved to FQN like 'todo__task' + * via SchemaRegistry lookup. If no match is found, the name is + * returned as-is (for ad-hoc / unregistered objects). + * + * This ensures that all driver operations use a consistent key + * regardless of whether the caller uses the short name or FQN. + */ + resolveObjectName(name) { + const schema3 = SchemaRegistry.getObject(name); + if (schema3) { + return schema3.tableName || schema3.name; + } + return name; + } + /** + * Helper to get the target driver + */ + getDriver(objectName) { + const object2 = SchemaRegistry.getObject(objectName); + if (object2) { + const datasourceName = object2.datasource || "default"; + if (datasourceName === "default") { + if (this.defaultDriver && this.drivers.has(this.defaultDriver)) { + return this.drivers.get(this.defaultDriver); + } + } else { + if (this.drivers.has(datasourceName)) { + return this.drivers.get(datasourceName); + } + throw new Error(`[ObjectQL] Datasource '${datasourceName}' configured for object '${objectName}' is not registered.`); + } + } + if (this.defaultDriver) { + return this.drivers.get(this.defaultDriver); + } + throw new Error(`[ObjectQL] No driver available for object '${objectName}'`); + } + /** + * Initialize the engine and all registered drivers + */ + async init() { + this.logger.info("Initializing ObjectQL engine", { + driverCount: this.drivers.size, + drivers: Array.from(this.drivers.keys()) + }); + const failedDrivers = []; + for (const [name, driver] of this.drivers) { + try { + await driver.connect(); + this.logger.info("Driver connected successfully", { driverName: name }); + } catch (e) { + failedDrivers.push(name); + this.logger.error("Failed to connect driver", e, { driverName: name }); + } + } + if (failedDrivers.length > 0) { + this.logger.warn( + `${failedDrivers.length} of ${this.drivers.size} driver(s) failed initial connect. Operations may recover via lazy reconnection or fail at query time.`, + { failedDrivers } + ); + } + this.logger.info("ObjectQL engine initialization complete"); + } + async destroy() { + this.logger.info("Destroying ObjectQL engine", { driverCount: this.drivers.size }); + for (const [name, driver] of this.drivers.entries()) { + try { + await driver.disconnect(); + } catch (e) { + this.logger.error("Error disconnecting driver", e, { driverName: name }); + } + } + this.logger.info("ObjectQL engine destroyed"); + } + /** + * Post-process expand: resolve lookup/master_detail fields by batch-loading related records. + * + * This is a driver-agnostic implementation that uses secondary queries ($in batches) + * to load related records, then injects them into the result set. + * + * @param objectName - The source object name + * @param records - The records returned by the driver + * @param expand - The expand map from QueryAST (field name → nested QueryAST) + * @param depth - Current recursion depth (0-based) + * @returns Records with expanded lookup fields (IDs replaced by full objects) + */ + async expandRelatedRecords(objectName, records, expand2, depth = 0) { + if (!records || records.length === 0) return records; + if (depth >= _ObjectQL2.MAX_EXPAND_DEPTH) return records; + const objectSchema = SchemaRegistry.getObject(objectName); + if (!objectSchema || !objectSchema.fields) return records; + for (const [fieldName, nestedAST] of Object.entries(expand2)) { + const fieldDef = objectSchema.fields[fieldName]; + if (!fieldDef || !fieldDef.reference) continue; + if (fieldDef.type !== "lookup" && fieldDef.type !== "master_detail") continue; + const referenceObject = fieldDef.reference; + const allIds = []; + for (const record2 of records) { + const val = record2[fieldName]; + if (val == null) continue; + if (Array.isArray(val)) { + allIds.push(...val.filter((id) => id != null)); + } else if (typeof val === "object") { + continue; + } else { + allIds.push(val); + } + } + const uniqueIds = [...new Set(allIds)]; + if (uniqueIds.length === 0) continue; + try { + const relatedQuery = { + object: referenceObject, + where: { id: { $in: uniqueIds } }, + ...nestedAST.fields ? { fields: nestedAST.fields } : {}, + ...nestedAST.orderBy ? { orderBy: nestedAST.orderBy } : {} + }; + const driver = this.getDriver(referenceObject); + const relatedRecords = await driver.find(referenceObject, relatedQuery) ?? []; + const recordMap = /* @__PURE__ */ new Map(); + for (const rec of relatedRecords) { + const id = rec.id; + if (id != null) recordMap.set(String(id), rec); + } + if (nestedAST.expand && Object.keys(nestedAST.expand).length > 0) { + const expandedRelated = await this.expandRelatedRecords( + referenceObject, + relatedRecords, + nestedAST.expand, + depth + 1 + ); + recordMap.clear(); + for (const rec of expandedRelated) { + const id = rec.id; + if (id != null) recordMap.set(String(id), rec); + } + } + for (const record2 of records) { + const val = record2[fieldName]; + if (val == null) continue; + if (Array.isArray(val)) { + record2[fieldName] = val.map((id) => recordMap.get(String(id)) ?? id); + } else if (typeof val !== "object") { + record2[fieldName] = recordMap.get(String(val)) ?? val; + } + } + } catch (e) { + this.logger.warn("Failed to expand relationship field; retaining foreign key IDs", { + object: objectName, + field: fieldName, + reference: referenceObject, + error: e.message + }); + } + } + return records; + } + // ============================================ + // Data Access Methods (IDataEngine Interface) + // ============================================ + async find(object2, query) { + object2 = this.resolveObjectName(object2); + this.logger.debug("Find operation starting", { object: object2, query }); + const driver = this.getDriver(object2); + const ast = { object: object2, ...query }; + delete ast.context; + if (ast.top != null && ast.limit == null) { + ast.limit = ast.top; + } + delete ast.top; + const opCtx = { + object: object2, + operation: "find", + ast, + options: query, + context: query?.context + }; + await this.executeWithMiddleware(opCtx, async () => { + const hookContext = { + object: object2, + event: "beforeFind", + input: { ast: opCtx.ast, options: opCtx.options }, + session: this.buildSession(opCtx.context), + transaction: opCtx.context?.transaction, + ql: this + }; + await this.triggerHooks("beforeFind", hookContext); + try { + let result = await driver.find(object2, hookContext.input.ast, hookContext.input.options); + if (ast.expand && Object.keys(ast.expand).length > 0 && Array.isArray(result)) { + result = await this.expandRelatedRecords(object2, result, ast.expand, 0); + } + hookContext.event = "afterFind"; + hookContext.result = result; + await this.triggerHooks("afterFind", hookContext); + return hookContext.result; + } catch (e) { + this.logger.error("Find operation failed", e, { object: object2 }); + throw e; + } + }); + return opCtx.result; + } + async findOne(objectName, query) { + objectName = this.resolveObjectName(objectName); + this.logger.debug("FindOne operation", { objectName }); + const driver = this.getDriver(objectName); + const ast = { object: objectName, ...query, limit: 1 }; + delete ast.context; + delete ast.top; + const opCtx = { + object: objectName, + operation: "findOne", + ast, + options: query, + context: query?.context + }; + await this.executeWithMiddleware(opCtx, async () => { + let result = await driver.findOne(objectName, opCtx.ast); + if (ast.expand && Object.keys(ast.expand).length > 0 && result != null) { + const expanded = await this.expandRelatedRecords(objectName, [result], ast.expand, 0); + result = expanded[0]; + } + return result; + }); + return opCtx.result; + } + async insert(object2, data, options) { + object2 = this.resolveObjectName(object2); + this.logger.debug("Insert operation starting", { object: object2, isBatch: Array.isArray(data) }); + const driver = this.getDriver(object2); + const opCtx = { + object: object2, + operation: "insert", + data, + options, + context: options?.context + }; + await this.executeWithMiddleware(opCtx, async () => { + const hookContext = { + object: object2, + event: "beforeInsert", + input: { data: opCtx.data, options: opCtx.options }, + session: this.buildSession(opCtx.context), + transaction: opCtx.context?.transaction, + ql: this + }; + await this.triggerHooks("beforeInsert", hookContext); + try { + let result; + if (Array.isArray(hookContext.input.data)) { + if (driver.bulkCreate) { + result = await driver.bulkCreate(object2, hookContext.input.data, hookContext.input.options); + } else { + result = await Promise.all(hookContext.input.data.map((item) => driver.create(object2, item, hookContext.input.options))); + } + } else { + result = await driver.create(object2, hookContext.input.data, hookContext.input.options); + } + hookContext.event = "afterInsert"; + hookContext.result = result; + await this.triggerHooks("afterInsert", hookContext); + if (this.realtimeService) { + try { + if (Array.isArray(result)) { + for (const record2 of result) { + const event = { + type: "data.record.created", + object: object2, + payload: { + recordId: record2.id, + after: record2 + }, + timestamp: (/* @__PURE__ */ new Date()).toISOString() + }; + await this.realtimeService.publish(event); + } + this.logger.debug(`Published ${result.length} data.record.created events`, { object: object2 }); + } else { + const event = { + type: "data.record.created", + object: object2, + payload: { + recordId: result.id, + after: result + }, + timestamp: (/* @__PURE__ */ new Date()).toISOString() + }; + await this.realtimeService.publish(event); + this.logger.debug("Published data.record.created event", { object: object2, recordId: result.id }); + } + } catch (error49) { + this.logger.warn("Failed to publish data event", { object: object2, error: error49 }); + } + } + return hookContext.result; + } catch (e) { + this.logger.error("Insert operation failed", e, { object: object2 }); + throw e; + } + }); + return opCtx.result; + } + async update(object2, data, options) { + object2 = this.resolveObjectName(object2); + this.logger.debug("Update operation starting", { object: object2 }); + const driver = this.getDriver(object2); + let id = data.id; + if (!id && options?.where && typeof options.where === "object" && "id" in options.where) { + id = options.where.id; + } + const opCtx = { + object: object2, + operation: "update", + data, + options, + context: options?.context + }; + await this.executeWithMiddleware(opCtx, async () => { + const hookContext = { + object: object2, + event: "beforeUpdate", + input: { id, data: opCtx.data, options: opCtx.options }, + session: this.buildSession(opCtx.context), + transaction: opCtx.context?.transaction, + ql: this + }; + await this.triggerHooks("beforeUpdate", hookContext); + try { + let result; + if (hookContext.input.id) { + result = await driver.update(object2, hookContext.input.id, hookContext.input.data, hookContext.input.options); + } else if (options?.multi && driver.updateMany) { + const ast = { object: object2, where: options.where }; + result = await driver.updateMany(object2, ast, hookContext.input.data, hookContext.input.options); + } else { + throw new Error("Update requires an ID or options.multi=true"); + } + hookContext.event = "afterUpdate"; + hookContext.result = result; + await this.triggerHooks("afterUpdate", hookContext); + if (this.realtimeService) { + try { + const resultId = typeof result === "object" && result && "id" in result ? result.id : void 0; + const recordId = String(hookContext.input.id || resultId || ""); + const event = { + type: "data.record.updated", + object: object2, + payload: { + recordId, + changes: hookContext.input.data, + after: result + }, + timestamp: (/* @__PURE__ */ new Date()).toISOString() + }; + await this.realtimeService.publish(event); + this.logger.debug("Published data.record.updated event", { object: object2, recordId }); + } catch (error49) { + this.logger.warn("Failed to publish data event", { object: object2, error: error49 }); + } + } + return hookContext.result; + } catch (e) { + this.logger.error("Update operation failed", e, { object: object2 }); + throw e; + } + }); + return opCtx.result; + } + async delete(object2, options) { + object2 = this.resolveObjectName(object2); + this.logger.debug("Delete operation starting", { object: object2 }); + const driver = this.getDriver(object2); + let id = void 0; + if (options?.where && typeof options.where === "object" && "id" in options.where) { + id = options.where.id; + } + const opCtx = { + object: object2, + operation: "delete", + options, + context: options?.context + }; + await this.executeWithMiddleware(opCtx, async () => { + const hookContext = { + object: object2, + event: "beforeDelete", + input: { id, options: opCtx.options }, + session: this.buildSession(opCtx.context), + transaction: opCtx.context?.transaction, + ql: this + }; + await this.triggerHooks("beforeDelete", hookContext); + try { + let result; + if (hookContext.input.id) { + result = await driver.delete(object2, hookContext.input.id, hookContext.input.options); + } else if (options?.multi && driver.deleteMany) { + const ast = { object: object2, where: options.where }; + result = await driver.deleteMany(object2, ast, hookContext.input.options); + } else { + throw new Error("Delete requires an ID or options.multi=true"); + } + hookContext.event = "afterDelete"; + hookContext.result = result; + await this.triggerHooks("afterDelete", hookContext); + if (this.realtimeService) { + try { + const resultId = typeof result === "object" && result && "id" in result ? result.id : void 0; + const recordId = String(hookContext.input.id || resultId || ""); + const event = { + type: "data.record.deleted", + object: object2, + payload: { + recordId + }, + timestamp: (/* @__PURE__ */ new Date()).toISOString() + }; + await this.realtimeService.publish(event); + this.logger.debug("Published data.record.deleted event", { object: object2, recordId }); + } catch (error49) { + this.logger.warn("Failed to publish data event", { object: object2, error: error49 }); + } + } + return hookContext.result; + } catch (e) { + this.logger.error("Delete operation failed", e, { object: object2 }); + throw e; + } + }); + return opCtx.result; + } + async count(object2, query) { + object2 = this.resolveObjectName(object2); + const driver = this.getDriver(object2); + const opCtx = { + object: object2, + operation: "count", + options: query, + context: query?.context + }; + await this.executeWithMiddleware(opCtx, async () => { + if (driver.count) { + const ast = { object: object2, where: query?.where }; + return driver.count(object2, ast); + } + const res = await this.find(object2, { where: query?.where, fields: ["id"] }); + return res.length; + }); + return opCtx.result; + } + async aggregate(object2, query) { + object2 = this.resolveObjectName(object2); + const driver = this.getDriver(object2); + this.logger.debug(`Aggregate on ${object2} using ${driver.name}`, query); + const opCtx = { + object: object2, + operation: "aggregate", + options: query, + context: query?.context + }; + await this.executeWithMiddleware(opCtx, async () => { + const ast = { + object: object2, + where: query.where, + groupBy: query.groupBy, + aggregations: query.aggregations + }; + return driver.find(object2, ast); + }); + return opCtx.result; + } + async execute(command, options) { + if (options?.object) { + const driver = this.getDriver(options.object); + if (driver.execute) { + return driver.execute(command, void 0, options); + } + } + throw new Error("Execute requires options.object to select driver"); + } + // ============================================ + // Compatibility / Convenience API + // ============================================ + // These methods provide a higher-level API matching the @objectql/core + // ObjectQL interface, enabling painless migration from the legacy layer. + /** + * Register a single object definition. + * + * Proxies to SchemaRegistry.registerObject() with sensible defaults. + * Fields without a `name` property are auto-assigned from their key. + */ + registerObject(schema3, packageId = "__runtime__", namespace) { + if (schema3.fields) { + for (const [key, field] of Object.entries(schema3.fields)) { + if (field && typeof field === "object" && !("name" in field)) { + field.name = key; + } + } + } + return SchemaRegistry.registerObject(schema3, packageId, namespace); + } + /** + * Unregister a single object by name. + */ + unregisterObject(name, packageId) { + if (packageId) { + SchemaRegistry.unregisterObjectsByPackage(packageId); + } else { + SchemaRegistry.unregisterItem("object", name); + } + } + /** + * Get an object definition by name. + * Alias for getSchema() — matches @objectql/core API. + */ + getObject(name) { + return this.getSchema(name); + } + /** + * Get all registered object configs as a name→config map. + * Matches @objectql/core getConfigs() API. + */ + getConfigs() { + const result = {}; + const objects = SchemaRegistry.getAllObjects(); + for (const obj of objects) { + if (obj.name) { + result[obj.name] = obj; + } + } + return result; + } + /** + * Get a registered driver by datasource name. + * + * Unlike the private getDriver() (which resolves by object name), + * this method directly looks up a driver by its registered name. + */ + getDriverByName(name) { + return this.drivers.get(name); + } + /** + * Get the driver responsible for the given object. + * + * Resolves datasource binding from the object's schema definition, + * falling back to the default driver. This is a public version of + * the internal getDriver() used by CRUD operations. + * + * @param objectName - FQN or short name of the registered object. + * @returns The resolved DriverInterface, or undefined if no driver is available. + */ + getDriverForObject(objectName) { + try { + return this.getDriver(objectName); + } catch { + return void 0; + } + } + /** + * Get a registered driver by datasource name. + * Alias matching @objectql/core datasource() API. + * + * @throws Error if the datasource is not found + */ + datasource(name) { + const driver = this.drivers.get(name); + if (!driver) { + throw new Error(`[ObjectQL] Datasource '${name}' not found`); + } + return driver; + } + /** + * Register a hook handler. + * Convenience alias for registerHook() matching @objectql/core on() API. + * + * Usage: + * ql.on('beforeInsert', 'user', async (ctx) => { ... }); + */ + on(event, objectName, handler, packageId) { + this.registerHook(event, handler, { object: objectName, packageId }); + } + /** + * Remove all hooks, actions, and objects contributed by a package. + */ + removePackage(packageId) { + for (const [key, handlers] of this.hooks.entries()) { + const filtered = handlers.filter((h) => h.packageId !== packageId); + if (filtered.length !== handlers.length) { + this.hooks.set(key, filtered); + } + } + this.removeActionsByPackage(packageId); + SchemaRegistry.unregisterObjectsByPackage(packageId, true); + } + /** + * Gracefully shut down the engine, disconnecting all drivers. + * Alias for destroy() — matches @objectql/core close() API. + */ + async close() { + return this.destroy(); + } + /** + * Create a scoped execution context bound to this engine. + * + * Usage: + * const ctx = engine.createContext({ userId: '...', tenantId: '...' }); + * const users = ctx.object('user'); + * await users.find({ filter: { status: 'active' } }); + */ + createContext(ctx) { + return new ScopedContext( + ExecutionContextSchema2.parse(ctx), + this + ); + } + /** + * Static factory: create a fully configured ObjectQL instance. + * + * Matches @objectql/core's `new ObjectQL(config)` pattern but also + * registers drivers and objects, then calls init(). + * + * Usage: + * const ql = await ObjectQL.create({ + * datasources: { default: myDriver }, + * objects: { user: { name: 'user', fields: { ... } } } + * }); + */ + static async create(config4) { + const ql = new _ObjectQL2(); + if (config4.datasources) { + for (const [name, driver] of Object.entries(config4.datasources)) { + if (!driver.name) { + driver.name = name; + } + ql.registerDriver(driver, name === "default"); + } + } + if (config4.objects) { + for (const [_key, schema3] of Object.entries(config4.objects)) { + ql.registerObject(schema3); + } + } + if (config4.hooks) { + for (const hook of config4.hooks) { + ql.on(hook.event, hook.object, hook.handler); + } + } + await ql.init(); + return ql; + } +}; +_ObjectQL.MAX_EXPAND_DEPTH = 3; +var ObjectQL = _ObjectQL; +var ObjectRepository = class { + constructor(objectName, context, engine) { + this.objectName = objectName; + this.context = context; + this.engine = engine; + } + async find(query = {}) { + return this.engine.find(this.objectName, { + ...query, + context: this.context + }); + } + async findOne(query = {}) { + return this.engine.findOne(this.objectName, { + ...query, + context: this.context + }); + } + async insert(data) { + return this.engine.insert(this.objectName, data, { + context: this.context + }); + } + /** Alias for insert() — matches @objectql/core convention */ + async create(data) { + return this.insert(data); + } + async update(data, options = {}) { + return this.engine.update(this.objectName, data, { + ...options, + context: this.context + }); + } + /** Update a single record by ID */ + async updateById(id, data) { + return this.engine.update(this.objectName, { ...data, id }, { + where: { id }, + context: this.context + }); + } + async delete(options = {}) { + return this.engine.delete(this.objectName, { + ...options, + context: this.context + }); + } + /** Delete a single record by ID */ + async deleteById(id) { + return this.engine.delete(this.objectName, { + where: { id }, + context: this.context + }); + } + async count(query = {}) { + return this.engine.count(this.objectName, { + ...query, + context: this.context + }); + } + /** Aggregate query */ + async aggregate(query = {}) { + return this.engine.aggregate(this.objectName, { + ...query, + context: this.context + }); + } + /** Execute a named action registered on this object */ + async execute(actionName, params) { + if (this.engine.executeAction) { + return this.engine.executeAction(this.objectName, actionName, { + ...params, + userId: this.context.userId, + tenantId: this.context.tenantId, + roles: this.context.roles + }); + } + throw new Error(`Actions not supported by engine`); + } +}; +var ScopedContext = class _ScopedContext { + constructor(executionContext, engine) { + this.executionContext = executionContext; + this.engine = engine; + } + /** Get a repository scoped to this context */ + object(name) { + return new ObjectRepository(name, this.executionContext, this.engine); + } + /** Create an elevated (system) context */ + sudo() { + return new _ScopedContext( + { ...this.executionContext, isSystem: true }, + this.engine + ); + } + /** + * Execute a callback within a database transaction. + * + * The callback receives a new ScopedContext whose operations + * share the same transaction handle. If the callback throws, + * the transaction is rolled back; otherwise it is committed. + * + * Falls back to non-transactional execution if the driver + * does not support transactions. + */ + async transaction(callback) { + const engine = this.engine; + const driver = engine.defaultDriver ? engine.drivers?.get(engine.defaultDriver) : void 0; + if (!driver?.beginTransaction) { + return callback(this); + } + const trx = await driver.beginTransaction(); + const trxCtx = new _ScopedContext( + { ...this.executionContext, transaction: trx }, + this.engine + ); + try { + const result = await callback(trxCtx); + if (driver.commit) await driver.commit(trx); + else if (driver.commitTransaction) await driver.commitTransaction(trx); + return result; + } catch (error49) { + if (driver.rollback) await driver.rollback(trx); + else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx); + throw error49; + } + } + get userId() { + return this.executionContext.userId; + } + get tenantId() { + return this.executionContext.tenantId; + } + /** Alias for tenantId — matches ObjectQLContext.spaceId convention */ + get spaceId() { + return this.executionContext.tenantId; + } + get roles() { + return this.executionContext.roles; + } + get isSystem() { + return this.executionContext.isSystem; + } + /** Internal: expose the transaction handle for driver-level access */ + get transactionHandle() { + return this.executionContext.transaction; + } +}; +function hasLoadMetaFromDb(service) { + return typeof service === "object" && service !== null && typeof service["loadMetaFromDb"] === "function"; +} +var ObjectQLPlugin = class { + constructor(ql, hostContext) { + this.name = "com.objectstack.engine.objectql"; + this.type = "objectql"; + this.version = "1.0.0"; + this.init = async (ctx) => { + if (!this.ql) { + const hostCtx = { ...this.hostContext, logger: ctx.logger }; + this.ql = new ObjectQL(hostCtx); + } + ctx.registerService("objectql", this.ql); + ctx.registerService("data", this.ql); + const ql2 = this.ql; + ctx.registerService("manifest", { + register: (manifest) => { + ql2.registerApp(manifest); + ctx.logger.debug("Manifest registered via manifest service", { + id: manifest.id || manifest.name + }); + } + }); + ctx.logger.info("ObjectQL engine registered", { + services: ["objectql", "data", "manifest"] + }); + const protocolShim = new ObjectStackProtocolImplementation( + this.ql, + () => ctx.getServices ? ctx.getServices() : /* @__PURE__ */ new Map() + ); + ctx.registerService("protocol", protocolShim); + ctx.logger.info("Protocol service registered"); + }; + this.start = async (ctx) => { + ctx.logger.info("ObjectQL engine starting..."); + try { + const metadataService = ctx.getService("metadata"); + if (metadataService && typeof metadataService.loadMany === "function" && this.ql) { + await this.loadMetadataFromService(metadataService, ctx); + } + } catch (e) { + ctx.logger.debug("No external metadata service to sync from"); + } + if (ctx.getServices && this.ql) { + const services = ctx.getServices(); + for (const [name, service] of services.entries()) { + if (name.startsWith("driver.")) { + this.ql.registerDriver(service); + ctx.logger.debug("Discovered and registered driver service", { serviceName: name }); + } + if (name.startsWith("app.")) { + ctx.logger.warn( + `[DEPRECATED] Service "${name}" uses legacy app.* convention. Migrate to ctx.getService('manifest').register(data).` + ); + this.ql.registerApp(service); + ctx.logger.debug("Discovered and registered app service (legacy)", { serviceName: name }); + } + } + try { + const realtimeService = ctx.getService("realtime"); + if (realtimeService && typeof realtimeService === "object" && "publish" in realtimeService) { + ctx.logger.info("[ObjectQLPlugin] Bridging realtime service to ObjectQL for event publishing"); + this.ql.setRealtimeService(realtimeService); + } + } catch (e) { + ctx.logger.debug("[ObjectQLPlugin] No realtime service found \u2014 data events will not be published", { + error: e.message + }); + } + } + await this.ql?.init(); + await this.restoreMetadataFromDb(ctx); + await this.syncRegisteredSchemas(ctx); + await this.bridgeObjectsToMetadataService(ctx); + this.registerAuditHooks(ctx); + this.registerTenantMiddleware(ctx); + ctx.logger.info("ObjectQL engine started", { + driversRegistered: this.ql?.["drivers"]?.size || 0, + objectsRegistered: this.ql?.registry?.getAllObjects?.()?.length || 0 + }); + }; + if (ql) { + this.ql = ql; + } else { + this.hostContext = hostContext; + } + } + /** + * Register built-in audit hooks for auto-stamping created_by/updated_by + * and fetching previousData for update/delete operations. + */ + registerAuditHooks(ctx) { + if (!this.ql) return; + this.ql.registerHook("beforeInsert", async (hookCtx) => { + if (hookCtx.session?.userId && hookCtx.input?.data) { + const data = hookCtx.input.data; + if (typeof data === "object" && data !== null) { + data.created_by = data.created_by ?? hookCtx.session.userId; + data.updated_by = hookCtx.session.userId; + data.created_at = data.created_at ?? (/* @__PURE__ */ new Date()).toISOString(); + data.updated_at = (/* @__PURE__ */ new Date()).toISOString(); + if (hookCtx.session.tenantId) { + data.tenant_id = data.tenant_id ?? hookCtx.session.tenantId; + } + } + } + }, { object: "*", priority: 10 }); + this.ql.registerHook("beforeUpdate", async (hookCtx) => { + if (hookCtx.session?.userId && hookCtx.input?.data) { + const data = hookCtx.input.data; + if (typeof data === "object" && data !== null) { + data.updated_by = hookCtx.session.userId; + data.updated_at = (/* @__PURE__ */ new Date()).toISOString(); + } + } + }, { object: "*", priority: 10 }); + this.ql.registerHook("beforeUpdate", async (hookCtx) => { + if (hookCtx.input?.id && !hookCtx.previous) { + try { + const existing = await this.ql.findOne(hookCtx.object, { + where: { id: hookCtx.input.id } + }); + if (existing) { + hookCtx.previous = existing; + } + } catch (_e) { + } + } + }, { object: "*", priority: 5 }); + this.ql.registerHook("beforeDelete", async (hookCtx) => { + if (hookCtx.input?.id && !hookCtx.previous) { + try { + const existing = await this.ql.findOne(hookCtx.object, { + where: { id: hookCtx.input.id } + }); + if (existing) { + hookCtx.previous = existing; + } + } catch (_e) { + } + } + }, { object: "*", priority: 5 }); + ctx.logger.debug("Audit hooks registered (created_by/updated_by, previousData)"); + } + /** + * Register tenant isolation middleware that auto-injects tenant_id filter + * for multi-tenant operations. + */ + registerTenantMiddleware(ctx) { + if (!this.ql) return; + this.ql.registerMiddleware(async (opCtx, next) => { + if (!opCtx.context?.tenantId || opCtx.context?.isSystem) { + return next(); + } + if (["find", "findOne", "count", "aggregate"].includes(opCtx.operation)) { + if (opCtx.ast) { + const tenantFilter = { tenant_id: opCtx.context.tenantId }; + if (opCtx.ast.where) { + opCtx.ast.where = { $and: [opCtx.ast.where, tenantFilter] }; + } else { + opCtx.ast.where = tenantFilter; + } + } + } + await next(); + }); + ctx.logger.debug("Tenant isolation middleware registered"); + } + /** + * Synchronize all registered object schemas to the database. + * + * Groups objects by their responsible driver, then: + * - If the driver advertises `supports.batchSchemaSync` and implements + * `syncSchemasBatch()`, submits all schemas in a single call (reducing + * network round-trips for remote drivers like Turso). + * - Otherwise falls back to sequential `syncSchema()` per object. + * + * This is idempotent — drivers must tolerate repeated calls without + * duplicating tables or erroring out. + * + * Drivers that do not implement `syncSchema` are silently skipped. + */ + async syncRegisteredSchemas(ctx) { + if (!this.ql) return; + const allObjects = this.ql.registry?.getAllObjects?.() ?? []; + if (allObjects.length === 0) return; + let synced = 0; + let skipped = 0; + const driverGroups = /* @__PURE__ */ new Map(); + for (const obj of allObjects) { + const driver = this.ql.getDriverForObject(obj.name); + if (!driver) { + ctx.logger.debug("No driver available for object, skipping schema sync", { + object: obj.name + }); + skipped++; + continue; + } + if (typeof driver.syncSchema !== "function") { + ctx.logger.debug("Driver does not support syncSchema, skipping", { + object: obj.name, + driver: driver.name + }); + skipped++; + continue; + } + const tableName = obj.tableName || obj.name; + let group = driverGroups.get(driver); + if (!group) { + group = []; + driverGroups.set(driver, group); + } + group.push({ obj, tableName }); + } + for (const [driver, entries] of driverGroups) { + if (driver.supports?.batchSchemaSync && typeof driver.syncSchemasBatch === "function") { + const batchPayload = entries.map((e) => ({ + object: e.tableName, + schema: e.obj + })); + try { + await driver.syncSchemasBatch(batchPayload); + synced += entries.length; + ctx.logger.debug("Batch schema sync succeeded", { + driver: driver.name, + count: entries.length + }); + } catch (e) { + ctx.logger.warn("Batch schema sync failed, falling back to sequential", { + driver: driver.name, + error: e instanceof Error ? e.message : String(e) + }); + for (const { obj, tableName } of entries) { + try { + await driver.syncSchema(tableName, obj); + synced++; + } catch (seqErr) { + ctx.logger.warn("Failed to sync schema for object", { + object: obj.name, + tableName, + driver: driver.name, + error: seqErr instanceof Error ? seqErr.message : String(seqErr) + }); + } + } + } + } else { + for (const { obj, tableName } of entries) { + try { + await driver.syncSchema(tableName, obj); + synced++; + } catch (e) { + ctx.logger.warn("Failed to sync schema for object", { + object: obj.name, + tableName, + driver: driver.name, + error: e instanceof Error ? e.message : String(e) + }); + } + } + } + } + if (synced > 0 || skipped > 0) { + ctx.logger.info("Schema sync complete", { synced, skipped, total: allObjects.length }); + } + } + /** + * Restore persisted metadata from the database (sys_metadata) on startup. + * + * Calls `protocol.loadMetaFromDb()` to bulk-load all active metadata + * records (objects, views, apps, etc.) into the in-memory SchemaRegistry. + * This closes the persistence loop so that user-created schemas survive + * kernel cold starts and redeployments. + * + * Gracefully degrades when: + * - The protocol service is unavailable (e.g., in-memory-only mode). + * - `loadMetaFromDb` is not implemented by the protocol shim. + * - The underlying driver/table does not exist yet (first-run scenario). + */ + async restoreMetadataFromDb(ctx) { + let protocol; + try { + const service = ctx.getService("protocol"); + if (!service || !hasLoadMetaFromDb(service)) { + ctx.logger.debug("Protocol service does not support loadMetaFromDb, skipping DB restore"); + return; + } + protocol = service; + } catch (e) { + ctx.logger.debug("Protocol service unavailable, skipping DB restore", { + error: e instanceof Error ? e.message : String(e) + }); + return; + } + try { + const { loaded, errors } = await protocol.loadMetaFromDb(); + if (loaded > 0 || errors > 0) { + ctx.logger.info("Metadata restored from database to SchemaRegistry", { loaded, errors }); + } else { + ctx.logger.debug("No persisted metadata found in database"); + } + } catch (e) { + ctx.logger.debug("DB metadata restore failed (non-fatal)", { + error: e instanceof Error ? e.message : String(e) + }); + } + } + /** + * Bridge all SchemaRegistry objects to the metadata service. + * + * This ensures objects registered by plugins and loaded from sys_metadata + * are visible to AI tools and other consumers that query IMetadataService. + * + * Runs after both restoreMetadataFromDb() and syncRegisteredSchemas() to + * catch all objects in the SchemaRegistry regardless of their source. + */ + async bridgeObjectsToMetadataService(ctx) { + try { + const metadataService = ctx.getService("metadata"); + if (!metadataService || typeof metadataService.register !== "function") { + ctx.logger.debug("Metadata service unavailable for bridging, skipping"); + return; + } + if (!this.ql?.registry) { + ctx.logger.debug("SchemaRegistry unavailable for bridging, skipping"); + return; + } + const objects = this.ql.registry.getAllObjects(); + let bridged = 0; + for (const obj of objects) { + try { + const existing = await metadataService.getObject(obj.name); + if (!existing) { + await metadataService.register("object", obj.name, obj); + bridged++; + } + } catch (e) { + ctx.logger.debug("Failed to bridge object to metadata service", { + object: obj.name, + error: e instanceof Error ? e.message : String(e) + }); + } + } + if (bridged > 0) { + ctx.logger.info("Bridged objects from SchemaRegistry to metadata service", { + count: bridged, + total: objects.length + }); + } else { + ctx.logger.debug("No objects needed bridging (all already in metadata service)"); + } + } catch (e) { + ctx.logger.debug("Failed to bridge objects to metadata service", { + error: e instanceof Error ? e.message : String(e) + }); + } + } + /** + * Load metadata from external metadata service into ObjectQL registry + * This enables ObjectQL to use file-based or remote metadata + */ + async loadMetadataFromService(metadataService, ctx) { + ctx.logger.info("Syncing metadata from external service into ObjectQL registry..."); + const metadataTypes = ["object", "view", "app", "flow", "workflow", "function"]; + let totalLoaded = 0; + for (const type of metadataTypes) { + try { + if (typeof metadataService.loadMany === "function") { + const items = await metadataService.loadMany(type); + if (items && items.length > 0) { + items.forEach((item) => { + const keyField = item.id ? "id" : "name"; + if (type === "object" && this.ql) { + return; + } + if (this.ql?.registry?.registerItem) { + this.ql.registry.registerItem(type, item, keyField); + } + }); + totalLoaded += items.length; + ctx.logger.info(`Synced ${items.length} ${type}(s) from metadata service`); + } + } + } catch (e) { + ctx.logger.debug(`No ${type} metadata found or error loading`, { + error: e.message + }); + } + } + if (totalLoaded > 0) { + ctx.logger.info(`Metadata sync complete: ${totalLoaded} items loaded into ObjectQL registry`); + } + } +}; + +// ../../packages/plugins/driver-memory/dist/index.mjs +import * as fs from "fs"; +import * as path from "path"; +var import_mingo = __toESM(require_cjs(), 1); +var __defProp3 = Object.defineProperty; +var __getOwnPropNames2 = Object.getOwnPropertyNames; +var __esm2 = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res; +}; +var __export3 = (target, all) => { + for (var name in all) + __defProp3(target, name, { get: all[name], enumerable: true }); +}; +var local_storage_adapter_exports = {}; +__export3(local_storage_adapter_exports, { + LocalStoragePersistenceAdapter: () => LocalStoragePersistenceAdapter +}); +var _LocalStoragePersistenceAdapter; +var LocalStoragePersistenceAdapter; +var init_local_storage_adapter = __esm2({ + "src/persistence/local-storage-adapter.ts"() { + "use strict"; + _LocalStoragePersistenceAdapter = class _LocalStoragePersistenceAdapter2 { + // 4.5MB warning threshold + constructor(options) { + this.storageKey = options?.key || "objectstack:memory-db"; + } + /** + * Load persisted data from localStorage. + * Returns null if no data exists. + */ + async load() { + try { + const raw2 = localStorage.getItem(this.storageKey); + if (!raw2) return null; + return JSON.parse(raw2); + } catch { + return null; + } + } + /** + * Save data to localStorage. + * Warns if data size approaches the ~5MB localStorage limit. + */ + async save(db) { + const json2 = JSON.stringify(db); + if (json2.length > _LocalStoragePersistenceAdapter2.SIZE_WARNING_BYTES) { + console.warn( + `[ObjectStack] localStorage persistence data size (${(json2.length / 1024 / 1024).toFixed(2)}MB) is approaching the ~5MB limit. Consider using a different persistence strategy.` + ); + } + try { + localStorage.setItem(this.storageKey, json2); + } catch (e) { + console.error("[ObjectStack] Failed to persist data to localStorage:", e?.message || e); + } + } + /** + * Flush is a no-op for localStorage (writes are synchronous). + */ + async flush() { + } + }; + _LocalStoragePersistenceAdapter.SIZE_WARNING_BYTES = 4.5 * 1024 * 1024; + LocalStoragePersistenceAdapter = _LocalStoragePersistenceAdapter; + } +}); +var file_adapter_exports = {}; +__export3(file_adapter_exports, { + FileSystemPersistenceAdapter: () => FileSystemPersistenceAdapter +}); +var FileSystemPersistenceAdapter; +var init_file_adapter = __esm2({ + "src/persistence/file-adapter.ts"() { + "use strict"; + FileSystemPersistenceAdapter = class { + constructor(options) { + this.dirty = false; + this.timer = null; + this.currentDb = null; + this.filePath = options?.path || path.join(".objectstack", "data", "memory-driver.json"); + this.autoSaveInterval = options?.autoSaveInterval ?? 2e3; + } + /** + * Load persisted data from disk. + * Returns null if no file exists. + */ + async load() { + try { + if (!fs.existsSync(this.filePath)) { + return null; + } + const raw2 = fs.readFileSync(this.filePath, "utf-8"); + const data = JSON.parse(raw2); + return data; + } catch { + return null; + } + } + /** + * Save data to disk using atomic write (temp file + rename). + */ + async save(db) { + this.currentDb = db; + this.dirty = true; + } + /** + * Flush pending writes to disk immediately. + */ + async flush() { + if (!this.dirty || !this.currentDb) return; + await this.writeToDisk(this.currentDb); + this.dirty = false; + } + /** + * Start the auto-save timer. + */ + startAutoSave() { + if (this.timer) return; + this.timer = setInterval(async () => { + if (this.dirty && this.currentDb) { + await this.writeToDisk(this.currentDb); + this.dirty = false; + } + }, this.autoSaveInterval); + if (this.timer) { + this.timer.unref(); + } + } + /** + * Stop the auto-save timer and flush pending writes. + */ + async stopAutoSave() { + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + await this.flush(); + } + /** + * Atomic write: write to temp file, then rename. + */ + async writeToDisk(db) { + const dir = path.dirname(this.filePath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + const tmpPath = this.filePath + ".tmp"; + const json2 = JSON.stringify(db, null, 2); + fs.writeFileSync(tmpPath, json2, "utf-8"); + fs.renameSync(tmpPath, this.filePath); + } + }; + } +}); +function getValueByPath(obj, path22) { + if (!path22.includes(".")) return obj[path22]; + return path22.split(".").reduce((o, i) => o ? o[i] : void 0, obj); +} +var _InMemoryDriver = class _InMemoryDriver2 { + constructor(config4) { + this.name = "com.objectstack.driver.memory"; + this.type = "driver"; + this.version = "1.0.0"; + this.idCounters = /* @__PURE__ */ new Map(); + this.transactions = /* @__PURE__ */ new Map(); + this.persistenceAdapter = null; + this.supports = { + // Basic CRUD Operations + create: true, + read: true, + update: true, + delete: true, + // Bulk Operations + bulkCreate: true, + bulkUpdate: true, + bulkDelete: true, + // Transaction & Connection Management + transactions: true, + // Snapshot-based transactions + savepoints: false, + // Query Operations + queryFilters: true, + // Implemented via memory-matcher + queryAggregations: true, + // Implemented + querySorting: true, + // Implemented via JS sort + queryPagination: true, + // Implemented + queryWindowFunctions: false, + // @planned: Window functions (ROW_NUMBER, RANK, etc.) + querySubqueries: false, + // @planned: Subquery execution + queryCTE: false, + joins: false, + // @planned: In-memory join operations + // Advanced Features + fullTextSearch: false, + // @planned: Text tokenization + matching + jsonQuery: false, + geospatialQuery: false, + streaming: true, + // Implemented via findStream() + jsonFields: true, + // Native JS object support + arrayFields: true, + // Native JS array support + vectorSearch: false, + // @planned: Cosine similarity search + // Schema Management + schemaSync: true, + // Implemented via syncSchema() + batchSchemaSync: false, + migrations: false, + indexes: false, + // Performance & Optimization + connectionPooling: false, + preparedStatements: false, + queryCache: false + }; + this.db = {}; + this.config = config4 || {}; + this.logger = config4?.logger || createLogger({ level: "info", format: "pretty" }); + this.logger.debug("InMemory driver instance created"); + } + // Duck-typed RuntimePlugin hook + install(ctx) { + this.logger.debug("Installing InMemory driver via plugin hook"); + if (ctx.engine && ctx.engine.ql && typeof ctx.engine.ql.registerDriver === "function") { + ctx.engine.ql.registerDriver(this); + this.logger.info("InMemory driver registered with ObjectQL engine"); + } else { + this.logger.warn("Could not register driver - ObjectQL engine not found in context"); + } + } + // =================================== + // Lifecycle + // =================================== + async connect() { + await this.initPersistence(); + if (this.persistenceAdapter) { + const persisted = await this.persistenceAdapter.load(); + if (persisted) { + for (const [objectName, records] of Object.entries(persisted)) { + this.db[objectName] = records; + for (const record2 of records) { + if (record2.id && typeof record2.id === "string") { + const parts = record2.id.split("-"); + const lastPart = parts[parts.length - 1]; + const counter = parseInt(lastPart, 10); + if (!isNaN(counter)) { + const current = this.idCounters.get(objectName) || 0; + if (counter > current) { + this.idCounters.set(objectName, counter); + } + } + } + } + } + this.logger.info("InMemory Database restored from persistence", { + tables: Object.keys(persisted).length + }); + } + } + if (this.config.initialData) { + for (const [objectName, records] of Object.entries(this.config.initialData)) { + const table = this.getTable(objectName); + for (const record2 of records) { + const id = record2.id || this.generateId(objectName); + table.push({ ...record2, id }); + } + } + this.logger.info("InMemory Database Connected with initial data", { + tables: Object.keys(this.config.initialData).length + }); + } else { + this.logger.info("InMemory Database Connected (Virtual)"); + } + if (this.persistenceAdapter?.startAutoSave) { + this.persistenceAdapter.startAutoSave(); + } + } + async disconnect() { + if (this.persistenceAdapter) { + if (this.persistenceAdapter.stopAutoSave) { + await this.persistenceAdapter.stopAutoSave(); + } + await this.persistenceAdapter.flush(); + } + const tableCount = Object.keys(this.db).length; + const recordCount = Object.values(this.db).reduce((sum, table) => sum + table.length, 0); + this.db = {}; + this.logger.info("InMemory Database Disconnected & Cleared", { + tableCount, + recordCount + }); + } + async checkHealth() { + this.logger.debug("Health check performed", { + tableCount: Object.keys(this.db).length, + status: "healthy" + }); + return true; + } + // =================================== + // Execution + // =================================== + async execute(command, params) { + this.logger.warn("Raw execution not supported in InMemory driver", { command }); + return null; + } + // =================================== + // CRUD + // =================================== + async find(object2, query, options) { + this.logger.debug("Find operation", { object: object2, query }); + const table = this.getTable(object2); + let results = [...table]; + if (query.where) { + const mongoQuery = this.convertToMongoQuery(query.where); + if (mongoQuery && Object.keys(mongoQuery).length > 0) { + const mingoQuery = new import_mingo.Query(mongoQuery); + results = mingoQuery.find(results).all(); + } + } + if (query.groupBy || query.aggregations && query.aggregations.length > 0) { + results = this.performAggregation(results, query); + } + if (query.orderBy) { + const sortFields = Array.isArray(query.orderBy) ? query.orderBy : [query.orderBy]; + results = this.applySort(results, sortFields); + } + if (query.offset) { + results = results.slice(query.offset); + } + if (query.limit) { + results = results.slice(0, query.limit); + } + if (query.fields && Array.isArray(query.fields) && query.fields.length > 0) { + results = results.map((record2) => this.projectFields(record2, query.fields)); + } + this.logger.debug("Find completed", { object: object2, resultCount: results.length }); + return results; + } + async *findStream(object2, query, options) { + this.logger.debug("FindStream operation", { object: object2 }); + const results = await this.find(object2, query, options); + for (const record2 of results) { + yield record2; + } + } + async findOne(object2, query, options) { + this.logger.debug("FindOne operation", { object: object2, query }); + const results = await this.find(object2, { ...query, limit: 1 }, options); + const result = results[0] || null; + this.logger.debug("FindOne completed", { object: object2, found: !!result }); + return result; + } + async create(object2, data, options) { + this.logger.debug("Create operation", { object: object2, hasData: !!data }); + const table = this.getTable(object2); + const newRecord = { + id: data.id || this.generateId(object2), + ...data, + created_at: data.created_at || (/* @__PURE__ */ new Date()).toISOString(), + updated_at: data.updated_at || (/* @__PURE__ */ new Date()).toISOString() + }; + table.push(newRecord); + this.markDirty(); + this.logger.debug("Record created", { object: object2, id: newRecord.id, tableSize: table.length }); + return { ...newRecord }; + } + async update(object2, id, data, options) { + this.logger.debug("Update operation", { object: object2, id }); + const table = this.getTable(object2); + const index = table.findIndex((r) => r.id == id); + if (index === -1) { + if (this.config.strictMode) { + this.logger.warn("Record not found for update", { object: object2, id }); + throw new Error(`Record with ID ${id} not found in ${object2}`); + } + return null; + } + const updatedRecord = { + ...table[index], + ...data, + id: table[index].id, + // Preserve original ID + created_at: table[index].created_at, + // Preserve created_at + updated_at: (/* @__PURE__ */ new Date()).toISOString() + }; + table[index] = updatedRecord; + this.markDirty(); + this.logger.debug("Record updated", { object: object2, id }); + return { ...updatedRecord }; + } + async upsert(object2, data, conflictKeys, options) { + this.logger.debug("Upsert operation", { object: object2, conflictKeys }); + const table = this.getTable(object2); + let existingRecord = null; + if (data.id) { + existingRecord = table.find((r) => r.id === data.id); + } else if (conflictKeys && conflictKeys.length > 0) { + existingRecord = table.find((r) => conflictKeys.every((key) => r[key] === data[key])); + } + if (existingRecord) { + this.logger.debug("Record exists, updating", { object: object2, id: existingRecord.id }); + return this.update(object2, existingRecord.id, data, options); + } else { + this.logger.debug("Record does not exist, creating", { object: object2 }); + return this.create(object2, data, options); + } + } + async delete(object2, id, options) { + this.logger.debug("Delete operation", { object: object2, id }); + const table = this.getTable(object2); + const index = table.findIndex((r) => r.id == id); + if (index === -1) { + if (this.config.strictMode) { + throw new Error(`Record with ID ${id} not found in ${object2}`); + } + this.logger.warn("Record not found for deletion", { object: object2, id }); + return false; + } + table.splice(index, 1); + this.markDirty(); + this.logger.debug("Record deleted", { object: object2, id, tableSize: table.length }); + return true; + } + async count(object2, query, options) { + let records = this.getTable(object2); + if (query?.where) { + const mongoQuery = this.convertToMongoQuery(query.where); + if (mongoQuery && Object.keys(mongoQuery).length > 0) { + const mingoQuery = new import_mingo.Query(mongoQuery); + records = mingoQuery.find(records).all(); + } + } + const count = records.length; + this.logger.debug("Count operation", { object: object2, count }); + return count; + } + // =================================== + // Bulk Operations + // =================================== + async bulkCreate(object2, dataArray, options) { + this.logger.debug("BulkCreate operation", { object: object2, count: dataArray.length }); + const results = await Promise.all(dataArray.map((data) => this.create(object2, data, options))); + this.logger.debug("BulkCreate completed", { object: object2, count: results.length }); + return results; + } + async updateMany(object2, query, data, options) { + this.logger.debug("UpdateMany operation", { object: object2, query }); + const table = this.getTable(object2); + let targetRecords = table; + if (query && query.where) { + const mongoQuery = this.convertToMongoQuery(query.where); + if (mongoQuery && Object.keys(mongoQuery).length > 0) { + const mingoQuery = new import_mingo.Query(mongoQuery); + targetRecords = mingoQuery.find(targetRecords).all(); + } + } + const count = targetRecords.length; + for (const record2 of targetRecords) { + const index = table.findIndex((r) => r.id === record2.id); + if (index !== -1) { + const updated = { + ...table[index], + ...data, + updated_at: (/* @__PURE__ */ new Date()).toISOString() + }; + table[index] = updated; + } + } + if (count > 0) this.markDirty(); + this.logger.debug("UpdateMany completed", { object: object2, count }); + return count; + } + async deleteMany(object2, query, options) { + this.logger.debug("DeleteMany operation", { object: object2, query }); + const table = this.getTable(object2); + const initialLength = table.length; + if (query && query.where) { + const mongoQuery = this.convertToMongoQuery(query.where); + if (mongoQuery && Object.keys(mongoQuery).length > 0) { + const mingoQuery = new import_mingo.Query(mongoQuery); + const matched = mingoQuery.find(table).all(); + const matchedIds = new Set(matched.map((r) => r.id)); + this.db[object2] = table.filter((r) => !matchedIds.has(r.id)); + } else { + this.db[object2] = []; + } + } else { + this.db[object2] = []; + } + const count = initialLength - this.db[object2].length; + if (count > 0) this.markDirty(); + this.logger.debug("DeleteMany completed", { object: object2, count }); + return count; + } + // Compatibility aliases + async bulkUpdate(object2, updates, options) { + this.logger.debug("BulkUpdate operation", { object: object2, count: updates.length }); + const results = await Promise.all(updates.map((u) => this.update(object2, u.id, u.data, options))); + this.logger.debug("BulkUpdate completed", { object: object2, count: results.length }); + return results; + } + async bulkDelete(object2, ids, options) { + this.logger.debug("BulkDelete operation", { object: object2, count: ids.length }); + await Promise.all(ids.map((id) => this.delete(object2, id, options))); + this.logger.debug("BulkDelete completed", { object: object2, count: ids.length }); + } + // =================================== + // Transaction Management + // =================================== + async beginTransaction() { + const txId = `tx_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`; + const snapshot = {}; + for (const [table, records] of Object.entries(this.db)) { + snapshot[table] = records.map((r) => ({ ...r })); + } + const transaction = { id: txId, snapshot }; + this.transactions.set(txId, transaction); + this.logger.debug("Transaction started", { txId }); + return { id: txId }; + } + async commit(txHandle) { + const txId = txHandle?.id; + if (!txId || !this.transactions.has(txId)) { + this.logger.warn("Commit called with unknown transaction"); + return; + } + this.transactions.delete(txId); + this.logger.debug("Transaction committed", { txId }); + } + async rollback(txHandle) { + const txId = txHandle?.id; + if (!txId || !this.transactions.has(txId)) { + this.logger.warn("Rollback called with unknown transaction"); + return; + } + const tx = this.transactions.get(txId); + this.db = tx.snapshot; + this.transactions.delete(txId); + this.markDirty(); + this.logger.debug("Transaction rolled back", { txId }); + } + // =================================== + // Utility Methods + // =================================== + /** + * Remove all data from the store. + */ + async clear() { + this.db = {}; + this.idCounters.clear(); + this.markDirty(); + this.logger.debug("All data cleared"); + } + /** + * Get total number of records across all tables. + */ + getSize() { + return Object.values(this.db).reduce((sum, table) => sum + table.length, 0); + } + /** + * Get distinct values for a field, optionally filtered. + */ + async distinct(object2, field, query) { + let records = this.getTable(object2); + if (query?.where) { + const mongoQuery = this.convertToMongoQuery(query.where); + if (mongoQuery && Object.keys(mongoQuery).length > 0) { + const mingoQuery = new import_mingo.Query(mongoQuery); + records = mingoQuery.find(records).all(); + } + } + const values = /* @__PURE__ */ new Set(); + for (const record2 of records) { + const value = getValueByPath(record2, field); + if (value !== void 0 && value !== null) { + values.add(value); + } + } + return Array.from(values); + } + /** + * Execute a MongoDB-style aggregation pipeline using Mingo. + * + * Supports all standard MongoDB pipeline stages: + * - $match, $group, $sort, $project, $unwind, $limit, $skip + * - $addFields, $replaceRoot, $lookup (limited), $count + * - Accumulator operators: $sum, $avg, $min, $max, $first, $last, $push, $addToSet + * + * @example + * // Group by status and count + * const results = await driver.aggregate('orders', [ + * { $match: { status: 'completed' } }, + * { $group: { _id: '$customer', totalAmount: { $sum: '$amount' } } } + * ]); + * + * @example + * // Calculate average with filter + * const results = await driver.aggregate('products', [ + * { $match: { category: 'electronics' } }, + * { $group: { _id: null, avgPrice: { $avg: '$price' } } } + * ]); + */ + async aggregate(object2, pipeline, options) { + this.logger.debug("Aggregate operation", { object: object2, stageCount: pipeline.length }); + const records = this.getTable(object2).map((r) => ({ ...r })); + const aggregator = new import_mingo.Aggregator(pipeline); + const results = aggregator.run(records); + this.logger.debug("Aggregate completed", { object: object2, resultCount: results.length }); + return results; + } + // =================================== + // Query Conversion (ObjectQL → MongoDB) + // =================================== + /** + * Convert ObjectQL filter format to MongoDB query format for Mingo. + * + * Supports: + * 1. AST Comparison Node: { type: 'comparison', field, operator, value } + * 2. AST Logical Node: { type: 'logical', operator: 'and'|'or', conditions: [...] } + * 3. Legacy Array Format: [['field', 'op', value], 'and', ['field2', 'op', value2]] + * 4. MongoDB Format: { field: value } or { field: { $eq: value } } (passthrough) + */ + convertToMongoQuery(filters) { + if (!filters) return {}; + if (!Array.isArray(filters) && typeof filters === "object") { + if (filters.type === "comparison") { + return this.convertConditionToMongo(filters.field, filters.operator, filters.value) || {}; + } + if (filters.type === "logical") { + const conditions = filters.conditions?.map((c) => this.convertToMongoQuery(c)) || []; + if (conditions.length === 0) return {}; + if (conditions.length === 1) return conditions[0]; + const op = filters.operator === "or" ? "$or" : "$and"; + return { [op]: conditions }; + } + return this.normalizeFilterCondition(filters); + } + if (!Array.isArray(filters) || filters.length === 0) return {}; + const logicGroups = [ + { logic: "and", conditions: [] } + ]; + let currentLogic = "and"; + for (const item of filters) { + if (typeof item === "string") { + const newLogic = item.toLowerCase(); + if (newLogic !== currentLogic) { + currentLogic = newLogic; + logicGroups.push({ logic: currentLogic, conditions: [] }); + } + } else if (Array.isArray(item)) { + const [field, operator, value] = item; + const cond = this.convertConditionToMongo(field, operator, value); + if (cond) logicGroups[logicGroups.length - 1].conditions.push(cond); + } + } + const allConditions = []; + for (const group of logicGroups) { + if (group.conditions.length === 0) continue; + if (group.conditions.length === 1) { + allConditions.push(group.conditions[0]); + } else { + const op = group.logic === "or" ? "$or" : "$and"; + allConditions.push({ [op]: group.conditions }); + } + } + if (allConditions.length === 0) return {}; + if (allConditions.length === 1) return allConditions[0]; + return { $and: allConditions }; + } + /** + * Convert a single ObjectQL condition to MongoDB operator format. + */ + convertConditionToMongo(field, operator, value) { + switch (operator) { + case "=": + case "==": + return { [field]: value }; + case "!=": + case "<>": + return { [field]: { $ne: value } }; + case ">": + return { [field]: { $gt: value } }; + case ">=": + return { [field]: { $gte: value } }; + case "<": + return { [field]: { $lt: value } }; + case "<=": + return { [field]: { $lte: value } }; + case "in": + return { [field]: { $in: value } }; + case "nin": + case "not in": + return { [field]: { $nin: value } }; + case "contains": + case "like": + return { [field]: { $regex: new RegExp(this.escapeRegex(value), "i") } }; + case "notcontains": + case "not_contains": + return { [field]: { $not: { $regex: new RegExp(this.escapeRegex(value), "i") } } }; + case "startswith": + case "starts_with": + return { [field]: { $regex: new RegExp(`^${this.escapeRegex(value)}`, "i") } }; + case "endswith": + case "ends_with": + return { [field]: { $regex: new RegExp(`${this.escapeRegex(value)}$`, "i") } }; + case "between": + if (Array.isArray(value) && value.length === 2) { + return { [field]: { $gte: value[0], $lte: value[1] } }; + } + return null; + default: + return null; + } + } + /** + * Normalize a FilterCondition object by converting non-standard $-prefixed + * operators ($contains, $notContains, $startsWith, $endsWith, $between, $null) + * to Mingo-compatible equivalents ($regex, $gte/$lte, null checks). + */ + normalizeFilterCondition(filter) { + const result = {}; + const extraAndConditions = []; + for (const key of Object.keys(filter)) { + const value = filter[key]; + if (key === "$and" || key === "$or") { + result[key] = Array.isArray(value) ? value.map((child) => this.normalizeFilterCondition(child)) : value; + continue; + } + if (key === "$not") { + result[key] = value && typeof value === "object" ? this.normalizeFilterCondition(value) : value; + continue; + } + if (key.startsWith("$")) { + result[key] = value; + continue; + } + if (value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp)) { + const normalized = this.normalizeFieldOperators(value); + if (normalized._multiRegex) { + const regexConditions = normalized._multiRegex; + delete normalized._multiRegex; + for (const rc of regexConditions) { + extraAndConditions.push({ [key]: { ...normalized, ...rc } }); + } + } else { + result[key] = normalized; + } + } else { + result[key] = value; + } + } + if (extraAndConditions.length > 0) { + const existing = result.$and; + const andArray = Array.isArray(existing) ? existing : []; + if (Object.keys(result).filter((k) => k !== "$and").length > 0) { + const rest = { ...result }; + delete rest.$and; + andArray.push(rest); + } + andArray.push(...extraAndConditions); + return { $and: andArray }; + } + return result; + } + /** + * Convert non-standard field operators to Mingo-compatible format. + * When multiple regex-producing operators appear on the same field + * (e.g. $startsWith + $endsWith), they are combined via $and. + */ + normalizeFieldOperators(ops) { + const result = {}; + const regexConditions = []; + for (const op of Object.keys(ops)) { + const val = ops[op]; + switch (op) { + case "$contains": + regexConditions.push({ $regex: new RegExp(this.escapeRegex(val), "i") }); + break; + case "$notContains": + result.$not = { $regex: new RegExp(this.escapeRegex(val), "i") }; + break; + case "$startsWith": + regexConditions.push({ $regex: new RegExp(`^${this.escapeRegex(val)}`, "i") }); + break; + case "$endsWith": + regexConditions.push({ $regex: new RegExp(`${this.escapeRegex(val)}$`, "i") }); + break; + case "$between": + if (Array.isArray(val) && val.length === 2) { + result.$gte = val[0]; + result.$lte = val[1]; + } + break; + case "$null": + if (val === true) { + result.$eq = null; + } else { + result.$ne = null; + } + break; + default: + result[op] = val; + break; + } + } + if (regexConditions.length === 1) { + Object.assign(result, regexConditions[0]); + } else if (regexConditions.length > 1) { + result._multiRegex = regexConditions; + } + return result; + } + /** + * Escape special regex characters for safe literal matching. + */ + escapeRegex(str) { + return String(str).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + // =================================== + // Aggregation Logic + // =================================== + performAggregation(records, query) { + const { groupBy: groupBy2, aggregations } = query; + const groups = /* @__PURE__ */ new Map(); + if (groupBy2 && groupBy2.length > 0) { + for (const record2 of records) { + const keyParts = groupBy2.map((field) => { + const val = getValueByPath(record2, field); + return val === void 0 || val === null ? "null" : String(val); + }); + const key = JSON.stringify(keyParts); + if (!groups.has(key)) { + groups.set(key, []); + } + groups.get(key).push(record2); + } + } else { + groups.set("all", records); + } + const resultRows = []; + for (const [_key, groupRecords] of groups.entries()) { + const row = {}; + if (groupBy2 && groupBy2.length > 0) { + if (groupRecords.length > 0) { + const firstRecord = groupRecords[0]; + for (const field of groupBy2) { + this.setValueByPath(row, field, getValueByPath(firstRecord, field)); + } + } + } + if (aggregations) { + for (const agg of aggregations) { + const value = this.computeAggregate(groupRecords, agg); + row[agg.alias] = value; + } + } + resultRows.push(row); + } + return resultRows; + } + computeAggregate(records, agg) { + const { function: func, field } = agg; + const values = field ? records.map((r) => getValueByPath(r, field)) : []; + switch (func) { + case "count": + if (!field || field === "*") return records.length; + return values.filter((v) => v !== null && v !== void 0).length; + case "sum": + case "avg": { + const nums = values.filter((v) => typeof v === "number"); + const sum = nums.reduce((a, b) => a + b, 0); + if (func === "sum") return sum; + return nums.length > 0 ? sum / nums.length : null; + } + case "min": { + const valid = values.filter((v) => v !== null && v !== void 0); + if (valid.length === 0) return null; + return valid.reduce((min, v) => v < min ? v : min, valid[0]); + } + case "max": { + const valid = values.filter((v) => v !== null && v !== void 0); + if (valid.length === 0) return null; + return valid.reduce((max, v) => v > max ? v : max, valid[0]); + } + default: + return null; + } + } + setValueByPath(obj, path22, value) { + const parts = path22.split("."); + let current = obj; + for (let i = 0; i < parts.length - 1; i++) { + const part = parts[i]; + if (!current[part]) current[part] = {}; + current = current[part]; + } + current[parts[parts.length - 1]] = value; + } + // =================================== + // Schema Management + // =================================== + async syncSchema(object2, schema3, options) { + if (!this.db[object2]) { + this.db[object2] = []; + this.logger.info("Created in-memory table", { object: object2 }); + } + } + async dropTable(object2, options) { + if (this.db[object2]) { + const recordCount = this.db[object2].length; + delete this.db[object2]; + this.logger.info("Dropped in-memory table", { object: object2, recordCount }); + } + } + // =================================== + // Helpers + // =================================== + /** + * Apply manual sorting (Mingo sort has CJS build issues). + */ + applySort(records, sortFields) { + const sorted = [...records]; + for (let i = sortFields.length - 1; i >= 0; i--) { + const sortItem = sortFields[i]; + let field; + let direction; + if (typeof sortItem === "object" && !Array.isArray(sortItem)) { + field = sortItem.field; + direction = sortItem.order || sortItem.direction || "asc"; + } else if (Array.isArray(sortItem)) { + [field, direction] = sortItem; + } else { + continue; + } + sorted.sort((a, b) => { + const aVal = getValueByPath(a, field); + const bVal = getValueByPath(b, field); + if (aVal == null && bVal == null) return 0; + if (aVal == null) return 1; + if (bVal == null) return -1; + if (aVal < bVal) return direction === "desc" ? 1 : -1; + if (aVal > bVal) return direction === "desc" ? -1 : 1; + return 0; + }); + } + return sorted; + } + /** + * Project specific fields from a record. + */ + projectFields(record2, fields) { + const result = {}; + for (const field of fields) { + const value = getValueByPath(record2, field); + if (value !== void 0) { + result[field] = value; + } + } + if (!fields.includes("id") && record2.id !== void 0) { + result.id = record2.id; + } + return result; + } + getTable(name) { + if (!this.db[name]) { + this.db[name] = []; + } + return this.db[name]; + } + generateId(objectName) { + const key = objectName || "_global"; + const counter = (this.idCounters.get(key) || 0) + 1; + this.idCounters.set(key, counter); + const timestamp = Date.now(); + return `${key}-${timestamp}-${counter}`; + } + // =================================== + // Persistence + // =================================== + /** + * Mark the database as dirty, triggering persistence save. + */ + markDirty() { + if (this.persistenceAdapter) { + this.persistenceAdapter.save(this.db); + } + } + /** + * Flush pending persistence writes to ensure data is safely stored. + */ + async flush() { + if (this.persistenceAdapter) { + await this.persistenceAdapter.flush(); + } + } + /** + * Detect whether the current runtime is a browser environment. + */ + isBrowserEnvironment() { + return typeof globalThis.localStorage !== "undefined"; + } + /** + * Detect whether the current runtime is a serverless/edge environment. + * + * Checks well-known environment variables set by serverless platforms: + * - `VERCEL` / `VERCEL_ENV` — Vercel Functions / Edge + * - `AWS_LAMBDA_FUNCTION_NAME` — AWS Lambda + * - `NETLIFY` — Netlify Functions + * - `FUNCTIONS_WORKER_RUNTIME` — Azure Functions + * - `K_SERVICE` — Google Cloud Run / Cloud Functions + * - `FUNCTION_TARGET` — Google Cloud Functions (Node.js) + * - `DENO_DEPLOYMENT_ID` — Deno Deploy + * + * Returns `false` when `process` or `process.env` is unavailable + * (e.g. browser or edge runtimes without a Node.js process object). + */ + isServerlessEnvironment() { + if (typeof globalThis.process === "undefined" || !globalThis.process.env) { + return false; + } + const env2 = globalThis.process.env; + return !!(env2.VERCEL || env2.VERCEL_ENV || env2.AWS_LAMBDA_FUNCTION_NAME || env2.NETLIFY || env2.FUNCTIONS_WORKER_RUNTIME || env2.K_SERVICE || env2.FUNCTION_TARGET || env2.DENO_DEPLOYMENT_ID); + } + /** + * Initialize the persistence adapter based on configuration. + * Defaults to 'auto' when persistence is not specified. + * Use `persistence: false` to explicitly disable persistence. + * + * In serverless environments (Vercel, AWS Lambda, etc.), auto mode disables + * file-system persistence and emits a warning. Use `persistence: false` or + * supply a custom adapter for serverless-safe operation. + */ + async initPersistence() { + const persistence = this.config.persistence === void 0 ? "auto" : this.config.persistence; + if (persistence === false) return; + if (typeof persistence === "string") { + if (persistence === "auto") { + if (this.isBrowserEnvironment()) { + const { LocalStoragePersistenceAdapter: LocalStoragePersistenceAdapter2 } = await Promise.resolve().then(() => (init_local_storage_adapter(), local_storage_adapter_exports)); + this.persistenceAdapter = new LocalStoragePersistenceAdapter2(); + this.logger.debug("Auto-detected browser environment, using localStorage persistence"); + } else if (this.isServerlessEnvironment()) { + this.logger.warn(_InMemoryDriver2.SERVERLESS_PERSISTENCE_WARNING); + } else { + const { FileSystemPersistenceAdapter: FileSystemPersistenceAdapter2 } = await Promise.resolve().then(() => (init_file_adapter(), file_adapter_exports)); + this.persistenceAdapter = new FileSystemPersistenceAdapter2(); + this.logger.debug("Auto-detected Node.js environment, using file persistence"); + } + } else if (persistence === "file") { + const { FileSystemPersistenceAdapter: FileSystemPersistenceAdapter2 } = await Promise.resolve().then(() => (init_file_adapter(), file_adapter_exports)); + this.persistenceAdapter = new FileSystemPersistenceAdapter2(); + } else if (persistence === "local") { + const { LocalStoragePersistenceAdapter: LocalStoragePersistenceAdapter2 } = await Promise.resolve().then(() => (init_local_storage_adapter(), local_storage_adapter_exports)); + this.persistenceAdapter = new LocalStoragePersistenceAdapter2(); + } else { + throw new Error(`Unknown persistence type: "${persistence}". Use 'file', 'local', or 'auto'.`); + } + } else if ("adapter" in persistence && persistence.adapter) { + this.persistenceAdapter = persistence.adapter; + } else if ("type" in persistence) { + if (persistence.type === "auto") { + if (this.isBrowserEnvironment()) { + const { LocalStoragePersistenceAdapter: LocalStoragePersistenceAdapter2 } = await Promise.resolve().then(() => (init_local_storage_adapter(), local_storage_adapter_exports)); + this.persistenceAdapter = new LocalStoragePersistenceAdapter2({ + key: persistence.key + }); + this.logger.debug("Auto-detected browser environment, using localStorage persistence"); + } else if (this.isServerlessEnvironment()) { + this.logger.warn(_InMemoryDriver2.SERVERLESS_PERSISTENCE_WARNING); + } else { + const { FileSystemPersistenceAdapter: FileSystemPersistenceAdapter2 } = await Promise.resolve().then(() => (init_file_adapter(), file_adapter_exports)); + this.persistenceAdapter = new FileSystemPersistenceAdapter2({ + path: persistence.path, + autoSaveInterval: persistence.autoSaveInterval + }); + this.logger.debug("Auto-detected Node.js environment, using file persistence"); + } + } else if (persistence.type === "file") { + const { FileSystemPersistenceAdapter: FileSystemPersistenceAdapter2 } = await Promise.resolve().then(() => (init_file_adapter(), file_adapter_exports)); + this.persistenceAdapter = new FileSystemPersistenceAdapter2({ + path: persistence.path, + autoSaveInterval: persistence.autoSaveInterval + }); + } else if (persistence.type === "local") { + const { LocalStoragePersistenceAdapter: LocalStoragePersistenceAdapter2 } = await Promise.resolve().then(() => (init_local_storage_adapter(), local_storage_adapter_exports)); + this.persistenceAdapter = new LocalStoragePersistenceAdapter2({ + key: persistence.key + }); + } + } + if (this.persistenceAdapter) { + this.logger.debug("Persistence adapter initialized"); + } + } +}; +_InMemoryDriver.SERVERLESS_PERSISTENCE_WARNING = "Serverless environment detected \u2014 file-system persistence is disabled in auto mode. Data will NOT be persisted across function invocations. Set persistence: false to silence this warning, or provide a custom adapter (e.g. Upstash Redis, Vercel KV) via persistence: { adapter: yourAdapter }."; +var InMemoryDriver = _InMemoryDriver; +init_file_adapter(); +init_local_storage_adapter(); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/compose.js +var compose = (middleware, onError, onNotFound) => { + return (context, next) => { + let index = -1; + return dispatch(0); + async function dispatch(i) { + if (i <= index) { + throw new Error("next() called multiple times"); + } + index = i; + let res; + let isError = false; + let handler; + if (middleware[i]) { + handler = middleware[i][0][0]; + context.req.routeIndex = i; + } else { + handler = i === middleware.length && next || void 0; + } + if (handler) { + try { + res = await handler(context, () => dispatch(i + 1)); + } catch (err) { + if (err instanceof Error && onError) { + context.error = err; + res = await onError(err, context); + isError = true; + } else { + throw err; + } + } + } else { + if (context.finalized === false && onNotFound) { + res = await onNotFound(context); + } + } + if (res && (context.finalized === false || isError)) { + context.res = res; + } + return context; + } + }; +}; + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/request/constants.js +var GET_MATCH_RESULT = /* @__PURE__ */ Symbol(); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/body.js +var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => { + const { all = false, dot = false } = options; + const headers = request instanceof HonoRequest ? request.raw.headers : request.headers; + const contentType = headers.get("Content-Type"); + if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) { + return parseFormData(request, { all, dot }); + } + return {}; +}; +async function parseFormData(request, options) { + const formData = await request.formData(); + if (formData) { + return convertFormDataToBodyData(formData, options); + } + return {}; +} +function convertFormDataToBodyData(formData, options) { + const form = /* @__PURE__ */ Object.create(null); + formData.forEach((value, key) => { + const shouldParseAllValues = options.all || key.endsWith("[]"); + if (!shouldParseAllValues) { + form[key] = value; + } else { + handleParsingAllValues(form, key, value); + } + }); + if (options.dot) { + Object.entries(form).forEach(([key, value]) => { + const shouldParseDotValues = key.includes("."); + if (shouldParseDotValues) { + handleParsingNestedValues(form, key, value); + delete form[key]; + } + }); + } + return form; +} +var handleParsingAllValues = (form, key, value) => { + if (form[key] !== void 0) { + if (Array.isArray(form[key])) { + ; + form[key].push(value); + } else { + form[key] = [form[key], value]; + } + } else { + if (!key.endsWith("[]")) { + form[key] = value; + } else { + form[key] = [value]; + } + } +}; +var handleParsingNestedValues = (form, key, value) => { + if (/(?:^|\.)__proto__\./.test(key)) { + return; + } + let nestedForm = form; + const keys = key.split("."); + keys.forEach((key2, index) => { + if (index === keys.length - 1) { + nestedForm[key2] = value; + } else { + if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) { + nestedForm[key2] = /* @__PURE__ */ Object.create(null); + } + nestedForm = nestedForm[key2]; + } + }); +}; + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/url.js +var splitPath = (path3) => { + const paths2 = path3.split("/"); + if (paths2[0] === "") { + paths2.shift(); + } + return paths2; +}; +var splitRoutingPath = (routePath) => { + const { groups, path: path3 } = extractGroupsFromPath(routePath); + const paths2 = splitPath(path3); + return replaceGroupMarks(paths2, groups); +}; +var extractGroupsFromPath = (path3) => { + const groups = []; + path3 = path3.replace(/\{[^}]+\}/g, (match2, index) => { + const mark = `@${index}`; + groups.push([mark, match2]); + return mark; + }); + return { groups, path: path3 }; +}; +var replaceGroupMarks = (paths2, groups) => { + for (let i = groups.length - 1; i >= 0; i--) { + const [mark] = groups[i]; + for (let j = paths2.length - 1; j >= 0; j--) { + if (paths2[j].includes(mark)) { + paths2[j] = paths2[j].replace(mark, groups[i][1]); + break; + } + } + } + return paths2; +}; +var patternCache = {}; +var getPattern = (label, next) => { + if (label === "*") { + return "*"; + } + const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); + if (match2) { + const cacheKey2 = `${label}#${next}`; + if (!patternCache[cacheKey2]) { + if (match2[2]) { + patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)]; + } else { + patternCache[cacheKey2] = [label, match2[1], true]; + } + } + return patternCache[cacheKey2]; + } + return null; +}; +var tryDecode = (str, decoder2) => { + try { + return decoder2(str); + } catch { + return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => { + try { + return decoder2(match2); + } catch { + return match2; + } + }); + } +}; +var tryDecodeURI = (str) => tryDecode(str, decodeURI); +var getPath = (request) => { + const url2 = request.url; + const start = url2.indexOf("/", url2.indexOf(":") + 4); + let i = start; + for (; i < url2.length; i++) { + const charCode = url2.charCodeAt(i); + if (charCode === 37) { + const queryIndex = url2.indexOf("?", i); + const hashIndex = url2.indexOf("#", i); + const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex); + const path3 = url2.slice(start, end); + return tryDecodeURI(path3.includes("%25") ? path3.replace(/%25/g, "%2525") : path3); + } else if (charCode === 63 || charCode === 35) { + break; + } + } + return url2.slice(start, i); +}; +var getPathNoStrict = (request) => { + const result = getPath(request); + return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result; +}; +var mergePath = (base, sub, ...rest) => { + if (rest.length) { + sub = mergePath(sub, ...rest); + } + return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`; +}; +var checkOptionalParameter = (path3) => { + if (path3.charCodeAt(path3.length - 1) !== 63 || !path3.includes(":")) { + return null; + } + const segments = path3.split("/"); + const results = []; + let basePath = ""; + segments.forEach((segment) => { + if (segment !== "" && !/\:/.test(segment)) { + basePath += "/" + segment; + } else if (/\:/.test(segment)) { + if (/\?/.test(segment)) { + if (results.length === 0 && basePath === "") { + results.push("/"); + } else { + results.push(basePath); + } + const optionalSegment = segment.replace("?", ""); + basePath += "/" + optionalSegment; + results.push(basePath); + } else { + basePath += "/" + segment; + } + } + }); + return results.filter((v, i, a) => a.indexOf(v) === i); +}; +var _decodeURI = (value) => { + if (!/[%+]/.test(value)) { + return value; + } + if (value.indexOf("+") !== -1) { + value = value.replace(/\+/g, " "); + } + return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value; +}; +var _getQueryParam = (url2, key, multiple) => { + let encoded; + if (!multiple && key && !/[%+]/.test(key)) { + let keyIndex2 = url2.indexOf("?", 8); + if (keyIndex2 === -1) { + return void 0; + } + if (!url2.startsWith(key, keyIndex2 + 1)) { + keyIndex2 = url2.indexOf(`&${key}`, keyIndex2 + 1); + } + while (keyIndex2 !== -1) { + const trailingKeyCode = url2.charCodeAt(keyIndex2 + key.length + 1); + if (trailingKeyCode === 61) { + const valueIndex = keyIndex2 + key.length + 2; + const endIndex = url2.indexOf("&", valueIndex); + return _decodeURI(url2.slice(valueIndex, endIndex === -1 ? void 0 : endIndex)); + } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { + return ""; + } + keyIndex2 = url2.indexOf(`&${key}`, keyIndex2 + 1); + } + encoded = /[%+]/.test(url2); + if (!encoded) { + return void 0; + } + } + const results = {}; + encoded ?? (encoded = /[%+]/.test(url2)); + let keyIndex = url2.indexOf("?", 8); + while (keyIndex !== -1) { + const nextKeyIndex = url2.indexOf("&", keyIndex + 1); + let valueIndex = url2.indexOf("=", keyIndex); + if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { + valueIndex = -1; + } + let name = url2.slice( + keyIndex + 1, + valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex + ); + if (encoded) { + name = _decodeURI(name); + } + keyIndex = nextKeyIndex; + if (name === "") { + continue; + } + let value; + if (valueIndex === -1) { + value = ""; + } else { + value = url2.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex); + if (encoded) { + value = _decodeURI(value); + } + } + if (multiple) { + if (!(results[name] && Array.isArray(results[name]))) { + results[name] = []; + } + ; + results[name].push(value); + } else { + results[name] ?? (results[name] = value); + } + } + return key ? results[key] : results; +}; +var getQueryParam = _getQueryParam; +var getQueryParams = (url2, key) => { + return _getQueryParam(url2, key, true); +}; +var decodeURIComponent_ = decodeURIComponent; + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/request.js +var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_); +var _validatedData, _matchResult, _HonoRequest_instances, getDecodedParam_fn, getAllDecodedParams_fn, getParamValue_fn, _cachedBody, _a2; +var HonoRequest = (_a2 = class { + constructor(request, path3 = "/", matchResult = [[]]) { + __privateAdd(this, _HonoRequest_instances); + /** + * `.raw` can get the raw Request object. + * + * @see {@link https://hono.dev/docs/api/request#raw} + * + * @example + * ```ts + * // For Cloudflare Workers + * app.post('/', async (c) => { + * const metadata = c.req.raw.cf?.hostMetadata? + * ... + * }) + * ``` + */ + __publicField(this, "raw"); + __privateAdd(this, _validatedData); + // Short name of validatedData + __privateAdd(this, _matchResult); + __publicField(this, "routeIndex", 0); + /** + * `.path` can get the pathname of the request. + * + * @see {@link https://hono.dev/docs/api/request#path} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const pathname = c.req.path // `/about/me` + * }) + * ``` + */ + __publicField(this, "path"); + __publicField(this, "bodyCache", {}); + __privateAdd(this, _cachedBody, (key) => { + const { bodyCache, raw: raw2 } = this; + const cachedBody = bodyCache[key]; + if (cachedBody) { + return cachedBody; + } + const anyCachedKey = Object.keys(bodyCache)[0]; + if (anyCachedKey) { + return bodyCache[anyCachedKey].then((body) => { + if (anyCachedKey === "json") { + body = JSON.stringify(body); + } + return new Response(body)[key](); + }); + } + return bodyCache[key] = raw2[key](); + }); + this.raw = request; + this.path = path3; + __privateSet(this, _matchResult, matchResult); + __privateSet(this, _validatedData, {}); + } + param(key) { + return key ? __privateMethod(this, _HonoRequest_instances, getDecodedParam_fn).call(this, key) : __privateMethod(this, _HonoRequest_instances, getAllDecodedParams_fn).call(this); + } + query(key) { + return getQueryParam(this.url, key); + } + queries(key) { + return getQueryParams(this.url, key); + } + header(name) { + if (name) { + return this.raw.headers.get(name) ?? void 0; + } + const headerData = {}; + this.raw.headers.forEach((value, key) => { + headerData[key] = value; + }); + return headerData; + } + async parseBody(options) { + return parseBody(this, options); + } + /** + * `.json()` can parse Request body of type `application/json` + * + * @see {@link https://hono.dev/docs/api/request#json} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.json() + * }) + * ``` + */ + json() { + return __privateGet(this, _cachedBody).call(this, "text").then((text) => JSON.parse(text)); + } + /** + * `.text()` can parse Request body of type `text/plain` + * + * @see {@link https://hono.dev/docs/api/request#text} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.text() + * }) + * ``` + */ + text() { + return __privateGet(this, _cachedBody).call(this, "text"); + } + /** + * `.arrayBuffer()` parse Request body as an `ArrayBuffer` + * + * @see {@link https://hono.dev/docs/api/request#arraybuffer} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.arrayBuffer() + * }) + * ``` + */ + arrayBuffer() { + return __privateGet(this, _cachedBody).call(this, "arrayBuffer"); + } + /** + * Parses the request body as a `Blob`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.blob(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#blob + */ + blob() { + return __privateGet(this, _cachedBody).call(this, "blob"); + } + /** + * Parses the request body as `FormData`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.formData(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#formdata + */ + formData() { + return __privateGet(this, _cachedBody).call(this, "formData"); + } + /** + * Adds validated data to the request. + * + * @param target - The target of the validation. + * @param data - The validated data to add. + */ + addValidatedData(target, data) { + __privateGet(this, _validatedData)[target] = data; + } + valid(target) { + return __privateGet(this, _validatedData)[target]; + } + /** + * `.url()` can get the request url strings. + * + * @see {@link https://hono.dev/docs/api/request#url} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const url = c.req.url // `http://localhost:8787/about/me` + * ... + * }) + * ``` + */ + get url() { + return this.raw.url; + } + /** + * `.method()` can get the method name of the request. + * + * @see {@link https://hono.dev/docs/api/request#method} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const method = c.req.method // `GET` + * }) + * ``` + */ + get method() { + return this.raw.method; + } + get [GET_MATCH_RESULT]() { + return __privateGet(this, _matchResult); + } + /** + * `.matchedRoutes()` can return a matched route in the handler + * + * @deprecated + * + * Use matchedRoutes helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#matchedroutes} + * + * @example + * ```ts + * app.use('*', async function logger(c, next) { + * await next() + * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { + * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') + * console.log( + * method, + * ' ', + * path, + * ' '.repeat(Math.max(10 - path.length, 0)), + * name, + * i === c.req.routeIndex ? '<- respond from here' : '' + * ) + * }) + * }) + * ``` + */ + get matchedRoutes() { + return __privateGet(this, _matchResult)[0].map(([[, route]]) => route); + } + /** + * `routePath()` can retrieve the path registered within the handler + * + * @deprecated + * + * Use routePath helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#routepath} + * + * @example + * ```ts + * app.get('/posts/:id', (c) => { + * return c.json({ path: c.req.routePath }) + * }) + * ``` + */ + get routePath() { + return __privateGet(this, _matchResult)[0].map(([[, route]]) => route)[this.routeIndex].path; + } +}, _validatedData = new WeakMap(), _matchResult = new WeakMap(), _HonoRequest_instances = new WeakSet(), getDecodedParam_fn = function(key) { + const paramKey = __privateGet(this, _matchResult)[0][this.routeIndex][1][key]; + const param = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, paramKey); + return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param; +}, getAllDecodedParams_fn = function() { + const decoded = {}; + const keys = Object.keys(__privateGet(this, _matchResult)[0][this.routeIndex][1]); + for (const key of keys) { + const value = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, __privateGet(this, _matchResult)[0][this.routeIndex][1][key]); + if (value !== void 0) { + decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value; + } + } + return decoded; +}, getParamValue_fn = function(paramKey) { + return __privateGet(this, _matchResult)[1] ? __privateGet(this, _matchResult)[1][paramKey] : paramKey; +}, _cachedBody = new WeakMap(), _a2); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/html.js +var HtmlEscapedCallbackPhase = { + Stringify: 1, + BeforeStream: 2, + Stream: 3 +}; +var raw = (value, callbacks) => { + const escapedString = new String(value); + escapedString.isEscaped = true; + escapedString.callbacks = callbacks; + return escapedString; +}; +var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => { + if (typeof str === "object" && !(str instanceof String)) { + if (!(str instanceof Promise)) { + str = str.toString(); + } + if (str instanceof Promise) { + str = await str; + } + } + const callbacks = str.callbacks; + if (!callbacks?.length) { + return Promise.resolve(str); + } + if (buffer) { + buffer[0] += str; + } else { + buffer = [str]; + } + const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then( + (res) => Promise.all( + res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer)) + ).then(() => buffer[0]) + ); + if (preserveCallbacks) { + return raw(await resStr, callbacks); + } else { + return resStr; + } +}; + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/context.js +var TEXT_PLAIN = "text/plain; charset=UTF-8"; +var setDefaultContentType = (contentType, headers) => { + return { + "Content-Type": contentType, + ...headers + }; +}; +var createResponseInstance = (body, init2) => new Response(body, init2); +var _rawRequest, _req, _var, _status, _executionCtx, _res, _layout, _renderer, _notFoundHandler, _preparedHeaders, _matchResult2, _path, _Context_instances, newResponse_fn, _a3; +var Context2 = (_a3 = class { + /** + * Creates an instance of the Context class. + * + * @param req - The Request object. + * @param options - Optional configuration options for the context. + */ + constructor(req, options) { + __privateAdd(this, _Context_instances); + __privateAdd(this, _rawRequest); + __privateAdd(this, _req); + /** + * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers. + * + * @see {@link https://hono.dev/docs/api/context#env} + * + * @example + * ```ts + * // Environment object for Cloudflare Workers + * app.get('*', async c => { + * const counter = c.env.COUNTER + * }) + * ``` + */ + __publicField(this, "env", {}); + __privateAdd(this, _var); + __publicField(this, "finalized", false); + /** + * `.error` can get the error object from the middleware if the Handler throws an error. + * + * @see {@link https://hono.dev/docs/api/context#error} + * + * @example + * ```ts + * app.use('*', async (c, next) => { + * await next() + * if (c.error) { + * // do something... + * } + * }) + * ``` + */ + __publicField(this, "error"); + __privateAdd(this, _status); + __privateAdd(this, _executionCtx); + __privateAdd(this, _res); + __privateAdd(this, _layout); + __privateAdd(this, _renderer); + __privateAdd(this, _notFoundHandler); + __privateAdd(this, _preparedHeaders); + __privateAdd(this, _matchResult2); + __privateAdd(this, _path); + /** + * `.render()` can create a response within a layout. + * + * @see {@link https://hono.dev/docs/api/context#render-setrenderer} + * + * @example + * ```ts + * app.get('/', (c) => { + * return c.render('Hello!') + * }) + * ``` + */ + __publicField(this, "render", (...args) => { + __privateGet(this, _renderer) ?? __privateSet(this, _renderer, (content) => this.html(content)); + return __privateGet(this, _renderer).call(this, ...args); + }); + /** + * Sets the layout for the response. + * + * @param layout - The layout to set. + * @returns The layout function. + */ + __publicField(this, "setLayout", (layout) => __privateSet(this, _layout, layout)); + /** + * Gets the current layout for the response. + * + * @returns The current layout function. + */ + __publicField(this, "getLayout", () => __privateGet(this, _layout)); + /** + * `.setRenderer()` can set the layout in the custom middleware. + * + * @see {@link https://hono.dev/docs/api/context#render-setrenderer} + * + * @example + * ```tsx + * app.use('*', async (c, next) => { + * c.setRenderer((content) => { + * return c.html( + * + * + *

{content}

+ * + * + * ) + * }) + * await next() + * }) + * ``` + */ + __publicField(this, "setRenderer", (renderer) => { + __privateSet(this, _renderer, renderer); + }); + /** + * `.header()` can set headers. + * + * @see {@link https://hono.dev/docs/api/context#header} + * + * @example + * ```ts + * app.get('/welcome', (c) => { + * // Set headers + * c.header('X-Message', 'Hello!') + * c.header('Content-Type', 'text/plain') + * + * return c.body('Thank you for coming') + * }) + * ``` + */ + __publicField(this, "header", (name, value, options) => { + if (this.finalized) { + __privateSet(this, _res, createResponseInstance(__privateGet(this, _res).body, __privateGet(this, _res))); + } + const headers = __privateGet(this, _res) ? __privateGet(this, _res).headers : __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, new Headers()); + if (value === void 0) { + headers.delete(name); + } else if (options?.append) { + headers.append(name, value); + } else { + headers.set(name, value); + } + }); + __publicField(this, "status", (status) => { + __privateSet(this, _status, status); + }); + /** + * `.set()` can set the value specified by the key. + * + * @see {@link https://hono.dev/docs/api/context#set-get} + * + * @example + * ```ts + * app.use('*', async (c, next) => { + * c.set('message', 'Hono is hot!!') + * await next() + * }) + * ``` + */ + __publicField(this, "set", (key, value) => { + __privateGet(this, _var) ?? __privateSet(this, _var, /* @__PURE__ */ new Map()); + __privateGet(this, _var).set(key, value); + }); + /** + * `.get()` can use the value specified by the key. + * + * @see {@link https://hono.dev/docs/api/context#set-get} + * + * @example + * ```ts + * app.get('/', (c) => { + * const message = c.get('message') + * return c.text(`The message is "${message}"`) + * }) + * ``` + */ + __publicField(this, "get", (key) => { + return __privateGet(this, _var) ? __privateGet(this, _var).get(key) : void 0; + }); + __publicField(this, "newResponse", (...args) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, ...args)); + /** + * `.body()` can return the HTTP response. + * You can set headers with `.header()` and set HTTP status code with `.status`. + * This can also be set in `.text()`, `.json()` and so on. + * + * @see {@link https://hono.dev/docs/api/context#body} + * + * @example + * ```ts + * app.get('/welcome', (c) => { + * // Set headers + * c.header('X-Message', 'Hello!') + * c.header('Content-Type', 'text/plain') + * // Set HTTP status code + * c.status(201) + * + * // Return the response body + * return c.body('Thank you for coming') + * }) + * ``` + */ + __publicField(this, "body", (data, arg, headers) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg, headers)); + /** + * `.text()` can render text as `Content-Type:text/plain`. + * + * @see {@link https://hono.dev/docs/api/context#text} + * + * @example + * ```ts + * app.get('/say', (c) => { + * return c.text('Hello!') + * }) + * ``` + */ + __publicField(this, "text", (text, arg, headers) => { + return !__privateGet(this, _preparedHeaders) && !__privateGet(this, _status) && !arg && !headers && !this.finalized ? new Response(text) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg, setDefaultContentType(TEXT_PLAIN, headers)); + }); + /** + * `.json()` can render JSON as `Content-Type:application/json`. + * + * @see {@link https://hono.dev/docs/api/context#json} + * + * @example + * ```ts + * app.get('/api', (c) => { + * return c.json({ message: 'Hello!' }) + * }) + * ``` + */ + __publicField(this, "json", (object2, arg, headers) => { + return __privateMethod(this, _Context_instances, newResponse_fn).call(this, JSON.stringify(object2), arg, setDefaultContentType("application/json", headers)); + }); + __publicField(this, "html", (html2, arg, headers) => { + const res = (html22) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, html22, arg, setDefaultContentType("text/html; charset=UTF-8", headers)); + return typeof html2 === "object" ? resolveCallback(html2, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html2); + }); + /** + * `.redirect()` can Redirect, default status code is 302. + * + * @see {@link https://hono.dev/docs/api/context#redirect} + * + * @example + * ```ts + * app.get('/redirect', (c) => { + * return c.redirect('/') + * }) + * app.get('/redirect-permanently', (c) => { + * return c.redirect('/', 301) + * }) + * ``` + */ + __publicField(this, "redirect", (location, status) => { + const locationString = String(location); + this.header( + "Location", + // Multibyes should be encoded + // eslint-disable-next-line no-control-regex + !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString) + ); + return this.newResponse(null, status ?? 302); + }); + /** + * `.notFound()` can return the Not Found Response. + * + * @see {@link https://hono.dev/docs/api/context#notfound} + * + * @example + * ```ts + * app.get('/notfound', (c) => { + * return c.notFound() + * }) + * ``` + */ + __publicField(this, "notFound", () => { + __privateGet(this, _notFoundHandler) ?? __privateSet(this, _notFoundHandler, () => createResponseInstance()); + return __privateGet(this, _notFoundHandler).call(this, this); + }); + __privateSet(this, _rawRequest, req); + if (options) { + __privateSet(this, _executionCtx, options.executionCtx); + this.env = options.env; + __privateSet(this, _notFoundHandler, options.notFoundHandler); + __privateSet(this, _path, options.path); + __privateSet(this, _matchResult2, options.matchResult); + } + } + /** + * `.req` is the instance of {@link HonoRequest}. + */ + get req() { + __privateGet(this, _req) ?? __privateSet(this, _req, new HonoRequest(__privateGet(this, _rawRequest), __privateGet(this, _path), __privateGet(this, _matchResult2))); + return __privateGet(this, _req); + } + /** + * @see {@link https://hono.dev/docs/api/context#event} + * The FetchEvent associated with the current request. + * + * @throws Will throw an error if the context does not have a FetchEvent. + */ + get event() { + if (__privateGet(this, _executionCtx) && "respondWith" in __privateGet(this, _executionCtx)) { + return __privateGet(this, _executionCtx); + } else { + throw Error("This context has no FetchEvent"); + } + } + /** + * @see {@link https://hono.dev/docs/api/context#executionctx} + * The ExecutionContext associated with the current request. + * + * @throws Will throw an error if the context does not have an ExecutionContext. + */ + get executionCtx() { + if (__privateGet(this, _executionCtx)) { + return __privateGet(this, _executionCtx); + } else { + throw Error("This context has no ExecutionContext"); + } + } + /** + * @see {@link https://hono.dev/docs/api/context#res} + * The Response object for the current request. + */ + get res() { + return __privateGet(this, _res) || __privateSet(this, _res, createResponseInstance(null, { + headers: __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, new Headers()) + })); + } + /** + * Sets the Response object for the current request. + * + * @param _res - The Response object to set. + */ + set res(_res2) { + if (__privateGet(this, _res) && _res2) { + _res2 = createResponseInstance(_res2.body, _res2); + for (const [k, v] of __privateGet(this, _res).headers.entries()) { + if (k === "content-type") { + continue; + } + if (k === "set-cookie") { + const cookies = __privateGet(this, _res).headers.getSetCookie(); + _res2.headers.delete("set-cookie"); + for (const cookie of cookies) { + _res2.headers.append("set-cookie", cookie); + } + } else { + _res2.headers.set(k, v); + } + } + } + __privateSet(this, _res, _res2); + this.finalized = true; + } + /** + * `.var` can access the value of a variable. + * + * @see {@link https://hono.dev/docs/api/context#var} + * + * @example + * ```ts + * const result = c.var.client.oneMethod() + * ``` + */ + // c.var.propName is a read-only + get var() { + if (!__privateGet(this, _var)) { + return {}; + } + return Object.fromEntries(__privateGet(this, _var)); + } +}, _rawRequest = new WeakMap(), _req = new WeakMap(), _var = new WeakMap(), _status = new WeakMap(), _executionCtx = new WeakMap(), _res = new WeakMap(), _layout = new WeakMap(), _renderer = new WeakMap(), _notFoundHandler = new WeakMap(), _preparedHeaders = new WeakMap(), _matchResult2 = new WeakMap(), _path = new WeakMap(), _Context_instances = new WeakSet(), newResponse_fn = function(data, arg, headers) { + const responseHeaders = __privateGet(this, _res) ? new Headers(__privateGet(this, _res).headers) : __privateGet(this, _preparedHeaders) ?? new Headers(); + if (typeof arg === "object" && "headers" in arg) { + const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers); + for (const [key, value] of argHeaders) { + if (key.toLowerCase() === "set-cookie") { + responseHeaders.append(key, value); + } else { + responseHeaders.set(key, value); + } + } + } + if (headers) { + for (const [k, v] of Object.entries(headers)) { + if (typeof v === "string") { + responseHeaders.set(k, v); + } else { + responseHeaders.delete(k); + for (const v2 of v) { + responseHeaders.append(k, v2); + } + } + } + } + const status = typeof arg === "number" ? arg : arg?.status ?? __privateGet(this, _status); + return createResponseInstance(data, { status, headers: responseHeaders }); +}, _a3); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router.js +var METHOD_NAME_ALL = "ALL"; +var METHOD_NAME_ALL_LOWERCASE = "all"; +var METHODS = ["get", "post", "put", "delete", "options", "patch"]; +var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built."; +var UnsupportedPathError = class extends Error { +}; + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/constants.js +var COMPOSED_HANDLER = "__COMPOSED_HANDLER"; + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/hono-base.js +var notFoundHandler = (c) => { + return c.text("404 Not Found", 404); +}; +var errorHandler = (err, c) => { + if ("getResponse" in err) { + const res = err.getResponse(); + return c.newResponse(res.body, res); + } + console.error(err); + return c.text("Internal Server Error", 500); +}; +var _path2, __Hono_instances, clone_fn, _notFoundHandler2, addRoute_fn, handleError_fn, dispatch_fn, _a4; +var Hono = (_a4 = class { + constructor(options = {}) { + __privateAdd(this, __Hono_instances); + __publicField(this, "get"); + __publicField(this, "post"); + __publicField(this, "put"); + __publicField(this, "delete"); + __publicField(this, "options"); + __publicField(this, "patch"); + __publicField(this, "all"); + __publicField(this, "on"); + __publicField(this, "use"); + /* + This class is like an abstract class and does not have a router. + To use it, inherit the class and implement router in the constructor. + */ + __publicField(this, "router"); + __publicField(this, "getPath"); + // Cannot use `#` because it requires visibility at JavaScript runtime. + __publicField(this, "_basePath", "/"); + __privateAdd(this, _path2, "/"); + __publicField(this, "routes", []); + __privateAdd(this, _notFoundHandler2, notFoundHandler); + // Cannot use `#` because it requires visibility at JavaScript runtime. + __publicField(this, "errorHandler", errorHandler); + /** + * `.onError()` handles an error and returns a customized Response. + * + * @see {@link https://hono.dev/docs/api/hono#error-handling} + * + * @param {ErrorHandler} handler - request Handler for error + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.onError((err, c) => { + * console.error(`${err}`) + * return c.text('Custom Error Message', 500) + * }) + * ``` + */ + __publicField(this, "onError", (handler) => { + this.errorHandler = handler; + return this; + }); + /** + * `.notFound()` allows you to customize a Not Found Response. + * + * @see {@link https://hono.dev/docs/api/hono#not-found} + * + * @param {NotFoundHandler} handler - request handler for not-found + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.notFound((c) => { + * return c.text('Custom 404 Message', 404) + * }) + * ``` + */ + __publicField(this, "notFound", (handler) => { + __privateSet(this, _notFoundHandler2, handler); + return this; + }); + /** + * `.fetch()` will be entry point of your app. + * + * @see {@link https://hono.dev/docs/api/hono#fetch} + * + * @param {Request} request - request Object of request + * @param {Env} Env - env Object + * @param {ExecutionContext} - context of execution + * @returns {Response | Promise} response of request + * + */ + __publicField(this, "fetch", (request, ...rest) => { + return __privateMethod(this, __Hono_instances, dispatch_fn).call(this, request, rest[1], rest[0], request.method); + }); + /** + * `.request()` is a useful method for testing. + * You can pass a URL or pathname to send a GET request. + * app will return a Response object. + * ```ts + * test('GET /hello is ok', async () => { + * const res = await app.request('/hello') + * expect(res.status).toBe(200) + * }) + * ``` + * @see https://hono.dev/docs/api/hono#request + */ + __publicField(this, "request", (input, requestInit, Env, executionCtx) => { + if (input instanceof Request) { + return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx); + } + input = input.toString(); + return this.fetch( + new Request( + /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, + requestInit + ), + Env, + executionCtx + ); + }); + /** + * `.fire()` automatically adds a global fetch event listener. + * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers. + * @deprecated + * Use `fire` from `hono/service-worker` instead. + * ```ts + * import { Hono } from 'hono' + * import { fire } from 'hono/service-worker' + * + * const app = new Hono() + * // ... + * fire(app) + * ``` + * @see https://hono.dev/docs/api/hono#fire + * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API + * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ + */ + __publicField(this, "fire", () => { + addEventListener("fetch", (event) => { + event.respondWith(__privateMethod(this, __Hono_instances, dispatch_fn).call(this, event.request, event, void 0, event.request.method)); + }); + }); + const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]; + allMethods.forEach((method) => { + this[method] = (args1, ...args) => { + if (typeof args1 === "string") { + __privateSet(this, _path2, args1); + } else { + __privateMethod(this, __Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), args1); + } + args.forEach((handler) => { + __privateMethod(this, __Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), handler); + }); + return this; + }; + }); + this.on = (method, path3, ...handlers) => { + for (const p of [path3].flat()) { + __privateSet(this, _path2, p); + for (const m of [method].flat()) { + handlers.map((handler) => { + __privateMethod(this, __Hono_instances, addRoute_fn).call(this, m.toUpperCase(), __privateGet(this, _path2), handler); + }); + } + } + return this; + }; + this.use = (arg1, ...handlers) => { + if (typeof arg1 === "string") { + __privateSet(this, _path2, arg1); + } else { + __privateSet(this, _path2, "*"); + handlers.unshift(arg1); + } + handlers.forEach((handler) => { + __privateMethod(this, __Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, __privateGet(this, _path2), handler); + }); + return this; + }; + const { strict, ...optionsWithoutStrict } = options; + Object.assign(this, optionsWithoutStrict); + this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict; + } + /** + * `.route()` allows grouping other Hono instance in routes. + * + * @see {@link https://hono.dev/docs/api/routing#grouping} + * + * @param {string} path - base Path + * @param {Hono} app - other Hono instance + * @returns {Hono} routed Hono instance + * + * @example + * ```ts + * const app = new Hono() + * const app2 = new Hono() + * + * app2.get("/user", (c) => c.text("user")) + * app.route("/api", app2) // GET /api/user + * ``` + */ + route(path3, app) { + const subApp = this.basePath(path3); + app.routes.map((r) => { + var _a30; + let handler; + if (app.errorHandler === errorHandler) { + handler = r.handler; + } else { + handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res; + handler[COMPOSED_HANDLER] = r.handler; + } + __privateMethod(_a30 = subApp, __Hono_instances, addRoute_fn).call(_a30, r.method, r.path, handler); + }); + return this; + } + /** + * `.basePath()` allows base paths to be specified. + * + * @see {@link https://hono.dev/docs/api/routing#base-path} + * + * @param {string} path - base Path + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * const api = new Hono().basePath('/api') + * ``` + */ + basePath(path3) { + const subApp = __privateMethod(this, __Hono_instances, clone_fn).call(this); + subApp._basePath = mergePath(this._basePath, path3); + return subApp; + } + /** + * `.mount()` allows you to mount applications built with other frameworks into your Hono application. + * + * @see {@link https://hono.dev/docs/api/hono#mount} + * + * @param {string} path - base Path + * @param {Function} applicationHandler - other Request Handler + * @param {MountOptions} [options] - options of `.mount()` + * @returns {Hono} mounted Hono instance + * + * @example + * ```ts + * import { Router as IttyRouter } from 'itty-router' + * import { Hono } from 'hono' + * // Create itty-router application + * const ittyRouter = IttyRouter() + * // GET /itty-router/hello + * ittyRouter.get('/hello', () => new Response('Hello from itty-router')) + * + * const app = new Hono() + * app.mount('/itty-router', ittyRouter.handle) + * ``` + * + * @example + * ```ts + * const app = new Hono() + * // Send the request to another application without modification. + * app.mount('/app', anotherApp, { + * replaceRequest: (req) => req, + * }) + * ``` + */ + mount(path3, applicationHandler, options) { + let replaceRequest; + let optionHandler; + if (options) { + if (typeof options === "function") { + optionHandler = options; + } else { + optionHandler = options.optionHandler; + if (options.replaceRequest === false) { + replaceRequest = (request) => request; + } else { + replaceRequest = options.replaceRequest; + } + } + } + const getOptions = optionHandler ? (c) => { + const options2 = optionHandler(c); + return Array.isArray(options2) ? options2 : [options2]; + } : (c) => { + let executionContext = void 0; + try { + executionContext = c.executionCtx; + } catch { + } + return [c.env, executionContext]; + }; + replaceRequest || (replaceRequest = (() => { + const mergedPath = mergePath(this._basePath, path3); + const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; + return (request) => { + const url2 = new URL(request.url); + url2.pathname = url2.pathname.slice(pathPrefixLength) || "/"; + return new Request(url2, request); + }; + })()); + const handler = async (c, next) => { + const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c)); + if (res) { + return res; + } + await next(); + }; + __privateMethod(this, __Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, mergePath(path3, "*"), handler); + return this; + } +}, _path2 = new WeakMap(), __Hono_instances = new WeakSet(), clone_fn = function() { + const clone2 = new _a4({ + router: this.router, + getPath: this.getPath + }); + clone2.errorHandler = this.errorHandler; + __privateSet(clone2, _notFoundHandler2, __privateGet(this, _notFoundHandler2)); + clone2.routes = this.routes; + return clone2; +}, _notFoundHandler2 = new WeakMap(), addRoute_fn = function(method, path3, handler) { + method = method.toUpperCase(); + path3 = mergePath(this._basePath, path3); + const r = { basePath: this._basePath, path: path3, method, handler }; + this.router.add(method, path3, [handler, r]); + this.routes.push(r); +}, handleError_fn = function(err, c) { + if (err instanceof Error) { + return this.errorHandler(err, c); + } + throw err; +}, dispatch_fn = function(request, executionCtx, env2, method) { + if (method === "HEAD") { + return (async () => new Response(null, await __privateMethod(this, __Hono_instances, dispatch_fn).call(this, request, executionCtx, env2, "GET")))(); + } + const path3 = this.getPath(request, { env: env2 }); + const matchResult = this.router.match(method, path3); + const c = new Context2(request, { + path: path3, + matchResult, + env: env2, + executionCtx, + notFoundHandler: __privateGet(this, _notFoundHandler2) + }); + if (matchResult[0].length === 1) { + let res; + try { + res = matchResult[0][0][0][0](c, async () => { + c.res = await __privateGet(this, _notFoundHandler2).call(this, c); + }); + } catch (err) { + return __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c); + } + return res instanceof Promise ? res.then( + (resolved) => resolved || (c.finalized ? c.res : __privateGet(this, _notFoundHandler2).call(this, c)) + ).catch((err) => __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c)) : res ?? __privateGet(this, _notFoundHandler2).call(this, c); + } + const composed = compose(matchResult[0], this.errorHandler, __privateGet(this, _notFoundHandler2)); + return (async () => { + try { + const context = await composed(c); + if (!context.finalized) { + throw new Error( + "Context is not finalized. Did you forget to return a Response object or `await next()`?" + ); + } + return context.res; + } catch (err) { + return __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c); + } + })(); +}, _a4); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/matcher.js +var emptyParam = []; +function match(method, path3) { + const matchers = this.buildAllMatchers(); + const match2 = (method2, path22) => { + const matcher = matchers[method2] || matchers[METHOD_NAME_ALL]; + const staticMatch = matcher[2][path22]; + if (staticMatch) { + return staticMatch; + } + const match3 = path22.match(matcher[0]); + if (!match3) { + return [[], emptyParam]; + } + const index = match3.indexOf("", 1); + return [matcher[1][index], match3]; + }; + this.match = match2; + return match2(method, path3); +} + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/node.js +var LABEL_REG_EXP_STR = "[^/]+"; +var ONLY_WILDCARD_REG_EXP_STR = ".*"; +var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)"; +var PATH_ERROR = /* @__PURE__ */ Symbol(); +var regExpMetaChars = new Set(".\\+*[^]$()"); +function compareKey(a, b) { + if (a.length === 1) { + return b.length === 1 ? a < b ? -1 : 1 : -1; + } + if (b.length === 1) { + return 1; + } + if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { + return 1; + } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) { + return -1; + } + if (a === LABEL_REG_EXP_STR) { + return 1; + } else if (b === LABEL_REG_EXP_STR) { + return -1; + } + return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length; +} +var _index, _varIndex, _children, _a5; +var Node = (_a5 = class { + constructor() { + __privateAdd(this, _index); + __privateAdd(this, _varIndex); + __privateAdd(this, _children, /* @__PURE__ */ Object.create(null)); + } + insert(tokens, index, paramMap, context, pathErrorCheckOnly) { + if (tokens.length === 0) { + if (__privateGet(this, _index) !== void 0) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + __privateSet(this, _index, index); + return; + } + const [token, ...restTokens] = tokens; + const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); + let node; + if (pattern) { + const name = pattern[1]; + let regexpStr = pattern[2] || LABEL_REG_EXP_STR; + if (name && pattern[2]) { + if (regexpStr === ".*") { + throw PATH_ERROR; + } + regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"); + if (/\((?!\?:)/.test(regexpStr)) { + throw PATH_ERROR; + } + } + node = __privateGet(this, _children)[regexpStr]; + if (!node) { + if (Object.keys(__privateGet(this, _children)).some( + (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR + )) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + node = __privateGet(this, _children)[regexpStr] = new _a5(); + if (name !== "") { + __privateSet(node, _varIndex, context.varIndex++); + } + } + if (!pathErrorCheckOnly && name !== "") { + paramMap.push([name, __privateGet(node, _varIndex)]); + } + } else { + node = __privateGet(this, _children)[token]; + if (!node) { + if (Object.keys(__privateGet(this, _children)).some( + (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR + )) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + node = __privateGet(this, _children)[token] = new _a5(); + } + } + node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly); + } + buildRegExpStr() { + const childKeys = Object.keys(__privateGet(this, _children)).sort(compareKey); + const strList = childKeys.map((k) => { + const c = __privateGet(this, _children)[k]; + return (typeof __privateGet(c, _varIndex) === "number" ? `(${k})@${__privateGet(c, _varIndex)}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr(); + }); + if (typeof __privateGet(this, _index) === "number") { + strList.unshift(`#${__privateGet(this, _index)}`); + } + if (strList.length === 0) { + return ""; + } + if (strList.length === 1) { + return strList[0]; + } + return "(?:" + strList.join("|") + ")"; + } +}, _index = new WeakMap(), _varIndex = new WeakMap(), _children = new WeakMap(), _a5); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/trie.js +var _context, _root, _a6; +var Trie = (_a6 = class { + constructor() { + __privateAdd(this, _context, { varIndex: 0 }); + __privateAdd(this, _root, new Node()); + } + insert(path3, index, pathErrorCheckOnly) { + const paramAssoc = []; + const groups = []; + for (let i = 0; ; ) { + let replaced = false; + path3 = path3.replace(/\{[^}]+\}/g, (m) => { + const mark = `@\\${i}`; + groups[i] = [mark, m]; + i++; + replaced = true; + return mark; + }); + if (!replaced) { + break; + } + } + const tokens = path3.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []; + for (let i = groups.length - 1; i >= 0; i--) { + const [mark] = groups[i]; + for (let j = tokens.length - 1; j >= 0; j--) { + if (tokens[j].indexOf(mark) !== -1) { + tokens[j] = tokens[j].replace(mark, groups[i][1]); + break; + } + } + } + __privateGet(this, _root).insert(tokens, index, paramAssoc, __privateGet(this, _context), pathErrorCheckOnly); + return paramAssoc; + } + buildRegExp() { + let regexp = __privateGet(this, _root).buildRegExpStr(); + if (regexp === "") { + return [/^$/, [], []]; + } + let captureIndex = 0; + const indexReplacementMap = []; + const paramReplacementMap = []; + regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => { + if (handlerIndex !== void 0) { + indexReplacementMap[++captureIndex] = Number(handlerIndex); + return "$()"; + } + if (paramIndex !== void 0) { + paramReplacementMap[Number(paramIndex)] = ++captureIndex; + return ""; + } + return ""; + }); + return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]; + } +}, _context = new WeakMap(), _root = new WeakMap(), _a6); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/router.js +var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; +var wildcardRegExpCache = /* @__PURE__ */ Object.create(null); +function buildWildcardRegExp(path3) { + return wildcardRegExpCache[path3] ?? (wildcardRegExpCache[path3] = new RegExp( + path3 === "*" ? "" : `^${path3.replace( + /\/\*$|([.\\+*[^\]$()])/g, + (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)" + )}$` + )); +} +function clearWildcardRegExpCache() { + wildcardRegExpCache = /* @__PURE__ */ Object.create(null); +} +function buildMatcherFromPreprocessedRoutes(routes) { + const trie = new Trie(); + const handlerData = []; + if (routes.length === 0) { + return nullMatcher; + } + const routesWithStaticPathFlag = routes.map( + (route) => [!/\*|\/:/.test(route[0]), ...route] + ).sort( + ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length + ); + const staticMap = /* @__PURE__ */ Object.create(null); + for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) { + const [pathErrorCheckOnly, path3, handlers] = routesWithStaticPathFlag[i]; + if (pathErrorCheckOnly) { + staticMap[path3] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam]; + } else { + j++; + } + let paramAssoc; + try { + paramAssoc = trie.insert(path3, j, pathErrorCheckOnly); + } catch (e) { + throw e === PATH_ERROR ? new UnsupportedPathError(path3) : e; + } + if (pathErrorCheckOnly) { + continue; + } + handlerData[j] = handlers.map(([h, paramCount]) => { + const paramIndexMap = /* @__PURE__ */ Object.create(null); + paramCount -= 1; + for (; paramCount >= 0; paramCount--) { + const [key, value] = paramAssoc[paramCount]; + paramIndexMap[key] = value; + } + return [h, paramIndexMap]; + }); + } + const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp(); + for (let i = 0, len = handlerData.length; i < len; i++) { + for (let j = 0, len2 = handlerData[i].length; j < len2; j++) { + const map3 = handlerData[i][j]?.[1]; + if (!map3) { + continue; + } + const keys = Object.keys(map3); + for (let k = 0, len3 = keys.length; k < len3; k++) { + map3[keys[k]] = paramReplacementMap[map3[keys[k]]]; + } + } + } + const handlerMap = []; + for (const i in indexReplacementMap) { + handlerMap[i] = handlerData[indexReplacementMap[i]]; + } + return [regexp, handlerMap, staticMap]; +} +function findMiddleware(middleware, path3) { + if (!middleware) { + return void 0; + } + for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) { + if (buildWildcardRegExp(k).test(path3)) { + return [...middleware[k]]; + } + } + return void 0; +} +var _middleware, _routes, _RegExpRouter_instances, buildMatcher_fn, _a7; +var RegExpRouter = (_a7 = class { + constructor() { + __privateAdd(this, _RegExpRouter_instances); + __publicField(this, "name", "RegExpRouter"); + __privateAdd(this, _middleware); + __privateAdd(this, _routes); + __publicField(this, "match", match); + __privateSet(this, _middleware, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }); + __privateSet(this, _routes, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }); + } + add(method, path3, handler) { + var _a30; + const middleware = __privateGet(this, _middleware); + const routes = __privateGet(this, _routes); + if (!middleware || !routes) { + throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); + } + if (!middleware[method]) { + ; + [middleware, routes].forEach((handlerMap) => { + handlerMap[method] = /* @__PURE__ */ Object.create(null); + Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => { + handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]; + }); + }); + } + if (path3 === "/*") { + path3 = "*"; + } + const paramCount = (path3.match(/\/:/g) || []).length; + if (/\*$/.test(path3)) { + const re2 = buildWildcardRegExp(path3); + if (method === METHOD_NAME_ALL) { + Object.keys(middleware).forEach((m) => { + var _a31; + (_a31 = middleware[m])[path3] || (_a31[path3] = findMiddleware(middleware[m], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || []); + }); + } else { + (_a30 = middleware[method])[path3] || (_a30[path3] = findMiddleware(middleware[method], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || []); + } + Object.keys(middleware).forEach((m) => { + if (method === METHOD_NAME_ALL || method === m) { + Object.keys(middleware[m]).forEach((p) => { + re2.test(p) && middleware[m][p].push([handler, paramCount]); + }); + } + }); + Object.keys(routes).forEach((m) => { + if (method === METHOD_NAME_ALL || method === m) { + Object.keys(routes[m]).forEach( + (p) => re2.test(p) && routes[m][p].push([handler, paramCount]) + ); + } + }); + return; + } + const paths2 = checkOptionalParameter(path3) || [path3]; + for (let i = 0, len = paths2.length; i < len; i++) { + const path22 = paths2[i]; + Object.keys(routes).forEach((m) => { + var _a31; + if (method === METHOD_NAME_ALL || method === m) { + (_a31 = routes[m])[path22] || (_a31[path22] = [ + ...findMiddleware(middleware[m], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || [] + ]); + routes[m][path22].push([handler, paramCount - len + i + 1]); + } + }); + } + } + buildAllMatchers() { + const matchers = /* @__PURE__ */ Object.create(null); + Object.keys(__privateGet(this, _routes)).concat(Object.keys(__privateGet(this, _middleware))).forEach((method) => { + matchers[method] || (matchers[method] = __privateMethod(this, _RegExpRouter_instances, buildMatcher_fn).call(this, method)); + }); + __privateSet(this, _middleware, __privateSet(this, _routes, void 0)); + clearWildcardRegExpCache(); + return matchers; + } +}, _middleware = new WeakMap(), _routes = new WeakMap(), _RegExpRouter_instances = new WeakSet(), buildMatcher_fn = function(method) { + const routes = []; + let hasOwnRoute = method === METHOD_NAME_ALL; + [__privateGet(this, _middleware), __privateGet(this, _routes)].forEach((r) => { + const ownRoute = r[method] ? Object.keys(r[method]).map((path3) => [path3, r[method][path3]]) : []; + if (ownRoute.length !== 0) { + hasOwnRoute || (hasOwnRoute = true); + routes.push(...ownRoute); + } else if (method !== METHOD_NAME_ALL) { + routes.push( + ...Object.keys(r[METHOD_NAME_ALL]).map((path3) => [path3, r[METHOD_NAME_ALL][path3]]) + ); + } + }); + if (!hasOwnRoute) { + return null; + } else { + return buildMatcherFromPreprocessedRoutes(routes); + } +}, _a7); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/smart-router/router.js +var _routers, _routes2, _a8; +var SmartRouter = (_a8 = class { + constructor(init2) { + __publicField(this, "name", "SmartRouter"); + __privateAdd(this, _routers, []); + __privateAdd(this, _routes2, []); + __privateSet(this, _routers, init2.routers); + } + add(method, path3, handler) { + if (!__privateGet(this, _routes2)) { + throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); + } + __privateGet(this, _routes2).push([method, path3, handler]); + } + match(method, path3) { + if (!__privateGet(this, _routes2)) { + throw new Error("Fatal error"); + } + const routers = __privateGet(this, _routers); + const routes = __privateGet(this, _routes2); + const len = routers.length; + let i = 0; + let res; + for (; i < len; i++) { + const router2 = routers[i]; + try { + for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) { + router2.add(...routes[i2]); + } + res = router2.match(method, path3); + } catch (e) { + if (e instanceof UnsupportedPathError) { + continue; + } + throw e; + } + this.match = router2.match.bind(router2); + __privateSet(this, _routers, [router2]); + __privateSet(this, _routes2, void 0); + break; + } + if (i === len) { + throw new Error("Fatal error"); + } + this.name = `SmartRouter + ${this.activeRouter.name}`; + return res; + } + get activeRouter() { + if (__privateGet(this, _routes2) || __privateGet(this, _routers).length !== 1) { + throw new Error("No active router has been determined yet."); + } + return __privateGet(this, _routers)[0]; + } +}, _routers = new WeakMap(), _routes2 = new WeakMap(), _a8); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/trie-router/node.js +var emptyParams = /* @__PURE__ */ Object.create(null); +var hasChildren = (children) => { + for (const _ in children) { + return true; + } + return false; +}; +var _methods, _children2, _patterns, _order, _params, __Node_instances, pushHandlerSets_fn, _a9; +var Node2 = (_a9 = class { + constructor(method, handler, children) { + __privateAdd(this, __Node_instances); + __privateAdd(this, _methods); + __privateAdd(this, _children2); + __privateAdd(this, _patterns); + __privateAdd(this, _order, 0); + __privateAdd(this, _params, emptyParams); + __privateSet(this, _children2, children || /* @__PURE__ */ Object.create(null)); + __privateSet(this, _methods, []); + if (method && handler) { + const m = /* @__PURE__ */ Object.create(null); + m[method] = { handler, possibleKeys: [], score: 0 }; + __privateSet(this, _methods, [m]); + } + __privateSet(this, _patterns, []); + } + insert(method, path3, handler) { + __privateSet(this, _order, ++__privateWrapper(this, _order)._); + let curNode = this; + const parts = splitRoutingPath(path3); + const possibleKeys = []; + for (let i = 0, len = parts.length; i < len; i++) { + const p = parts[i]; + const nextP = parts[i + 1]; + const pattern = getPattern(p, nextP); + const key = Array.isArray(pattern) ? pattern[0] : p; + if (key in __privateGet(curNode, _children2)) { + curNode = __privateGet(curNode, _children2)[key]; + if (pattern) { + possibleKeys.push(pattern[1]); + } + continue; + } + __privateGet(curNode, _children2)[key] = new _a9(); + if (pattern) { + __privateGet(curNode, _patterns).push(pattern); + possibleKeys.push(pattern[1]); + } + curNode = __privateGet(curNode, _children2)[key]; + } + __privateGet(curNode, _methods).push({ + [method]: { + handler, + possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i), + score: __privateGet(this, _order) + } + }); + return curNode; + } + search(method, path3) { + const handlerSets = []; + __privateSet(this, _params, emptyParams); + const curNode = this; + let curNodes = [curNode]; + const parts = splitPath(path3); + const curNodesQueue = []; + const len = parts.length; + let partOffsets = null; + for (let i = 0; i < len; i++) { + const part = parts[i]; + const isLast = i === len - 1; + const tempNodes = []; + for (let j = 0, len2 = curNodes.length; j < len2; j++) { + const node = curNodes[j]; + const nextNode = __privateGet(node, _children2)[part]; + if (nextNode) { + __privateSet(nextNode, _params, __privateGet(node, _params)); + if (isLast) { + if (__privateGet(nextNode, _children2)["*"]) { + __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, __privateGet(nextNode, _children2)["*"], method, __privateGet(node, _params)); + } + __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, nextNode, method, __privateGet(node, _params)); + } else { + tempNodes.push(nextNode); + } + } + for (let k = 0, len3 = __privateGet(node, _patterns).length; k < len3; k++) { + const pattern = __privateGet(node, _patterns)[k]; + const params = __privateGet(node, _params) === emptyParams ? {} : { ...__privateGet(node, _params) }; + if (pattern === "*") { + const astNode = __privateGet(node, _children2)["*"]; + if (astNode) { + __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, astNode, method, __privateGet(node, _params)); + __privateSet(astNode, _params, params); + tempNodes.push(astNode); + } + continue; + } + const [key, name, matcher] = pattern; + if (!part && !(matcher instanceof RegExp)) { + continue; + } + const child = __privateGet(node, _children2)[key]; + if (matcher instanceof RegExp) { + if (partOffsets === null) { + partOffsets = new Array(len); + let offset = path3[0] === "/" ? 1 : 0; + for (let p = 0; p < len; p++) { + partOffsets[p] = offset; + offset += parts[p].length + 1; + } + } + const restPathString = path3.substring(partOffsets[i]); + const m = matcher.exec(restPathString); + if (m) { + params[name] = m[0]; + __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, child, method, __privateGet(node, _params), params); + if (hasChildren(__privateGet(child, _children2))) { + __privateSet(child, _params, params); + const componentCount = m[0].match(/\//)?.length ?? 0; + const targetCurNodes = curNodesQueue[componentCount] || (curNodesQueue[componentCount] = []); + targetCurNodes.push(child); + } + continue; + } + } + if (matcher === true || matcher.test(part)) { + params[name] = part; + if (isLast) { + __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, child, method, params, __privateGet(node, _params)); + if (__privateGet(child, _children2)["*"]) { + __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, __privateGet(child, _children2)["*"], method, params, __privateGet(node, _params)); + } + } else { + __privateSet(child, _params, params); + tempNodes.push(child); + } + } + } + } + const shifted = curNodesQueue.shift(); + curNodes = shifted ? tempNodes.concat(shifted) : tempNodes; + } + if (handlerSets.length > 1) { + handlerSets.sort((a, b) => { + return a.score - b.score; + }); + } + return [handlerSets.map(({ handler, params }) => [handler, params])]; + } +}, _methods = new WeakMap(), _children2 = new WeakMap(), _patterns = new WeakMap(), _order = new WeakMap(), _params = new WeakMap(), __Node_instances = new WeakSet(), pushHandlerSets_fn = function(handlerSets, node, method, nodeParams, params) { + for (let i = 0, len = __privateGet(node, _methods).length; i < len; i++) { + const m = __privateGet(node, _methods)[i]; + const handlerSet = m[method] || m[METHOD_NAME_ALL]; + const processedSet = {}; + if (handlerSet !== void 0) { + handlerSet.params = /* @__PURE__ */ Object.create(null); + handlerSets.push(handlerSet); + if (nodeParams !== emptyParams || params && params !== emptyParams) { + for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) { + const key = handlerSet.possibleKeys[i2]; + const processed = processedSet[handlerSet.score]; + handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key]; + processedSet[handlerSet.score] = true; + } + } + } + } +}, _a9); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/trie-router/router.js +var _node, _a10; +var TrieRouter = (_a10 = class { + constructor() { + __publicField(this, "name", "TrieRouter"); + __privateAdd(this, _node); + __privateSet(this, _node, new Node2()); + } + add(method, path3, handler) { + const results = checkOptionalParameter(path3); + if (results) { + for (let i = 0, len = results.length; i < len; i++) { + __privateGet(this, _node).insert(method, results[i], handler); + } + return; + } + __privateGet(this, _node).insert(method, path3, handler); + } + match(method, path3) { + return __privateGet(this, _node).search(method, path3); + } +}, _node = new WeakMap(), _a10); + +// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/hono.js +var Hono2 = class extends Hono { + /** + * Creates an instance of the Hono class. + * + * @param options - Optional configuration options for the Hono instance. + */ + constructor(options = {}) { + super(options); + this.router = options.router ?? new SmartRouter({ + routers: [new RegExpRouter(), new TrieRouter()] + }); + } +}; + +// ../../packages/adapters/hono/dist/index.mjs +function createHonoApp(options) { + const app = new Hono2(); + const prefix = options.prefix || "/api"; + const dispatcher = new HttpDispatcher(options.kernel); + const errorJson = (c, message2, code = 500) => { + return c.json({ success: false, error: { message: message2, code } }, code); + }; + const toResponse2 = (c, result) => { + if (result.handled) { + if (result.response) { + if (result.response.headers) { + Object.entries(result.response.headers).forEach(([k, v]) => c.header(k, v)); + } + return c.json(result.response.body, result.response.status); + } + if (result.result) { + const res = result.result; + if (res.type === "redirect" && res.url) { + return c.redirect(res.url); + } + if (res.type === "stream" && res.events) { + const headers = { + "Content-Type": res.contentType || "text/event-stream", + "Cache-Control": "no-cache", + "Connection": "keep-alive", + ...res.headers || {} + }; + const stream = new ReadableStream({ + async start(controller) { + try { + const encoder3 = new TextEncoder(); + for await (const event of res.events) { + const chunk = res.vercelDataStream ? typeof event === "string" ? event : JSON.stringify(event) + "\n" : `data: ${JSON.stringify(event)} + +`; + controller.enqueue(encoder3.encode(chunk)); + } + } catch (err) { + } finally { + controller.close(); + } + } + }); + return new Response(stream, { status: 200, headers }); + } + if (res.type === "stream" && res.stream) { + if (res.headers) { + Object.entries(res.headers).forEach(([k, v]) => c.header(k, v)); + } + return new Response(res.stream, { status: 200 }); + } + return c.json(res, 200); + } + } + return errorJson(c, "Not Found", 404); + }; + app.get(prefix, async (c) => { + return c.json({ data: await dispatcher.getDiscoveryInfo(prefix) }); + }); + app.get(`${prefix}/discovery`, async (c) => { + return c.json({ data: await dispatcher.getDiscoveryInfo(prefix) }); + }); + app.get("/.well-known/objectstack", (c) => { + return c.redirect(prefix); + }); + app.all(`${prefix}/auth/*`, async (c) => { + try { + const path3 = c.req.path.substring(`${prefix}/auth/`.length); + const method = c.req.method; + let authService = null; + try { + if (typeof options.kernel.getServiceAsync === "function") { + authService = await options.kernel.getServiceAsync("auth"); + } else if (typeof options.kernel.getService === "function") { + authService = options.kernel.getService("auth"); + } + } catch { + authService = null; + } + if (authService && typeof authService.handleRequest === "function") { + const response = await authService.handleRequest(c.req.raw); + return new Response(response.body, { + status: response.status, + headers: response.headers + }); + } + const body = method === "GET" || method === "HEAD" ? {} : await c.req.json().catch(() => ({})); + const result = await dispatcher.handleAuth(path3, method, body, { request: c.req.raw }); + return toResponse2(c, result); + } catch (err) { + return errorJson(c, err.message || "Internal Server Error", err.statusCode || 500); + } + }); + app.post(`${prefix}/graphql`, async (c) => { + try { + const body = await c.req.json(); + const result = await dispatcher.handleGraphQL(body, { request: c.req.raw }); + return c.json(result); + } catch (err) { + return errorJson(c, err.message || "Internal Server Error", err.statusCode || 500); + } + }); + app.all(`${prefix}/storage/*`, async (c) => { + try { + const subPath = c.req.path.substring(`${prefix}/storage`.length); + const method = c.req.method; + let file2 = void 0; + if (method === "POST" && subPath === "/upload") { + const formData = await c.req.formData(); + file2 = formData.get("file"); + } + const result = await dispatcher.handleStorage(subPath, method, file2, { request: c.req.raw }); + return toResponse2(c, result); + } catch (err) { + return errorJson(c, err.message || "Internal Server Error", err.statusCode || 500); + } + }); + app.all(`${prefix}/*`, async (c) => { + try { + const subPath = c.req.path.substring(prefix.length); + const method = c.req.method; + let body = void 0; + if (method === "POST" || method === "PUT" || method === "PATCH") { + body = await c.req.json().catch(() => ({})); + } + const queryParams = {}; + const url2 = new URL(c.req.url); + url2.searchParams.forEach((val, key) => { + queryParams[key] = val; + }); + const result = await dispatcher.dispatch(method, subPath, body, queryParams, { request: c.req.raw }, prefix); + return toResponse2(c, result); + } catch (err) { + return errorJson(c, err.message || "Internal Server Error", err.statusCode || 500); + } + }); + return app; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/wildcard.mjs +function escapeRegExpChar(char) { + if (char === "-" || char === "^" || char === "$" || char === "+" || char === "." || char === "(" || char === ")" || char === "|" || char === "[" || char === "]" || char === "{" || char === "}" || char === "*" || char === "?" || char === "\\") return `\\${char}`; + else return char; +} +function escapeRegExpString(str) { + let result = ""; + for (let i = 0; i < str.length; i++) result += escapeRegExpChar(str[i]); + return result; +} +function transform2(pattern, separator = true) { + if (Array.isArray(pattern)) return `(?:${pattern.map((p) => `^${transform2(p, separator)}$`).join("|")})`; + let separatorSplitter = ""; + let separatorMatcher = ""; + let wildcard = "."; + if (separator === true) { + separatorSplitter = "/"; + separatorMatcher = "[/\\\\]"; + wildcard = "[^/\\\\]"; + } else if (separator) { + separatorSplitter = separator; + separatorMatcher = escapeRegExpString(separatorSplitter); + if (separatorMatcher.length > 1) { + separatorMatcher = `(?:${separatorMatcher})`; + wildcard = `((?!${separatorMatcher}).)`; + } else wildcard = `[^${separatorMatcher}]`; + } + const requiredSeparator = separator ? `${separatorMatcher}+?` : ""; + const optionalSeparator = separator ? `${separatorMatcher}*?` : ""; + const segments = separator ? pattern.split(separatorSplitter) : [pattern]; + let result = ""; + for (let s = 0; s < segments.length; s++) { + const segment = segments[s]; + const nextSegment = segments[s + 1]; + let currentSeparator = ""; + if (!segment && s > 0) continue; + if (separator) if (s === segments.length - 1) currentSeparator = optionalSeparator; + else if (nextSegment !== "**") currentSeparator = requiredSeparator; + else currentSeparator = ""; + if (separator && segment === "**") { + if (currentSeparator) { + result += s === 0 ? "" : currentSeparator; + result += `(?:${wildcard}*?${currentSeparator})*?`; + } + continue; + } + for (let c = 0; c < segment.length; c++) { + const char = segment[c]; + if (char === "\\") { + if (c < segment.length - 1) { + result += escapeRegExpChar(segment[c + 1]); + c++; + } + } else if (char === "?") result += wildcard; + else if (char === "*") result += `${wildcard}*?`; + else result += escapeRegExpChar(char); + } + result += currentSeparator; + } + return result; +} +function isMatch(regexp, sample) { + if (typeof sample !== "string") throw new TypeError(`Sample must be a string, but ${typeof sample} given`); + return regexp.test(sample); +} +function wildcardMatch(pattern, options) { + if (typeof pattern !== "string" && !Array.isArray(pattern)) throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`); + if (typeof options === "string" || typeof options === "boolean") options = { separator: options }; + if (arguments.length === 2 && !(typeof options === "undefined" || typeof options === "object" && options !== null && !Array.isArray(options))) throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof options} given`); + options = options || {}; + if (options.separator === "\\") throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead"); + const regexpPattern = transform2(pattern, options.separator); + const regexp = new RegExp(`^${regexpPattern}$`, options.flags); + const fn = isMatch.bind(null, regexp); + fn.options = options; + fn.pattern = pattern; + fn.regexp = regexp; + return fn; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/url.mjs +init_env(); +init_error2(); +function checkHasPath(url2) { + try { + return (new URL(url2).pathname.replace(/\/+$/, "") || "/") !== "/"; + } catch { + throw new BetterAuthError(`Invalid base URL: ${url2}. Please provide a valid base URL.`); + } +} +function assertHasProtocol(url2) { + try { + const parsedUrl = new URL(url2); + if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") throw new BetterAuthError(`Invalid base URL: ${url2}. URL must include 'http://' or 'https://'`); + } catch (error49) { + if (error49 instanceof BetterAuthError) throw error49; + throw new BetterAuthError(`Invalid base URL: ${url2}. Please provide a valid base URL.`, { cause: error49 }); + } +} +function withPath(url2, path3 = "/api/auth") { + assertHasProtocol(url2); + if (checkHasPath(url2)) return url2; + const trimmedUrl = url2.replace(/\/+$/, ""); + if (!path3 || path3 === "/") return trimmedUrl; + path3 = path3.startsWith("/") ? path3 : `/${path3}`; + return `${trimmedUrl}${path3}`; +} +function validateProxyHeader(header, type) { + if (!header || header.trim() === "") return false; + if (type === "proto") return header === "http" || header === "https"; + if (type === "host") { + if ([ + /\.\./, + /\0/, + /[\s]/, + /^[.]/, + /[<>'"]/, + /javascript:/i, + /file:/i, + /data:/i + ].some((pattern) => pattern.test(header))) return false; + return /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(header) || /^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header); + } + return false; +} +function getBaseURL(url2, path3, request, loadEnv, trustedProxyHeaders) { + if (url2) return withPath(url2, path3); + if (loadEnv !== false) { + const fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== "/" ? env.BASE_URL : void 0); + if (fromEnv) return withPath(fromEnv, path3); + } + const fromRequest = request?.headers.get("x-forwarded-host"); + const fromRequestProto = request?.headers.get("x-forwarded-proto"); + if (fromRequest && fromRequestProto && trustedProxyHeaders) { + if (validateProxyHeader(fromRequestProto, "proto") && validateProxyHeader(fromRequest, "host")) try { + return withPath(`${fromRequestProto}://${fromRequest}`, path3); + } catch (_error) { + } + } + if (request) { + const url3 = getOrigin(request.url); + if (!url3) throw new BetterAuthError("Could not get origin from request. Please provide a valid base URL."); + return withPath(url3, path3); + } + if (typeof window !== "undefined" && window.location) return withPath(window.location.origin, path3); +} +function getOrigin(url2) { + try { + const parsedUrl = new URL(url2); + return parsedUrl.origin === "null" ? null : parsedUrl.origin; + } catch { + return null; + } +} +function getProtocol(url2) { + try { + return new URL(url2).protocol; + } catch { + return null; + } +} +function getHost(url2) { + try { + return new URL(url2).host; + } catch { + return null; + } +} +function isDynamicBaseURLConfig(config4) { + return typeof config4 === "object" && config4 !== null && "allowedHosts" in config4 && Array.isArray(config4.allowedHosts); +} +function getHostFromRequest(request) { + const forwardedHost = request.headers.get("x-forwarded-host"); + if (forwardedHost && validateProxyHeader(forwardedHost, "host")) return forwardedHost; + const host = request.headers.get("host"); + if (host && validateProxyHeader(host, "host")) return host; + try { + return new URL(request.url).host; + } catch { + return null; + } +} +function getProtocolFromRequest(request, configProtocol) { + if (configProtocol === "http" || configProtocol === "https") return configProtocol; + const forwardedProto = request.headers.get("x-forwarded-proto"); + if (forwardedProto && validateProxyHeader(forwardedProto, "proto")) return forwardedProto; + try { + const url2 = new URL(request.url); + if (url2.protocol === "http:" || url2.protocol === "https:") return url2.protocol.slice(0, -1); + } catch { + } + return "https"; +} +var matchesHostPattern = (host, pattern) => { + if (!host || !pattern) return false; + const normalizedHost = host.replace(/^https?:\/\//, "").split("/")[0].toLowerCase(); + const normalizedPattern = pattern.replace(/^https?:\/\//, "").split("/")[0].toLowerCase(); + if (normalizedPattern.includes("*") || normalizedPattern.includes("?")) return wildcardMatch(normalizedPattern)(normalizedHost); + return normalizedHost.toLowerCase() === normalizedPattern.toLowerCase(); +}; +function resolveDynamicBaseURL(config4, request, basePath) { + const host = getHostFromRequest(request); + if (!host) { + if (config4.fallback) return withPath(config4.fallback, basePath); + throw new BetterAuthError("Could not determine host from request headers. Please provide a fallback URL in your baseURL config."); + } + if (config4.allowedHosts.some((pattern) => matchesHostPattern(host, pattern))) return withPath(`${getProtocolFromRequest(request, config4.protocol)}://${host}`, basePath); + if (config4.fallback) return withPath(config4.fallback, basePath); + throw new BetterAuthError(`Host "${host}" is not in the allowed hosts list. Allowed hosts: ${config4.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`); +} +function resolveBaseURL(config4, basePath, request, loadEnv, trustedProxyHeaders) { + if (isDynamicBaseURLConfig(config4)) { + if (request) return resolveDynamicBaseURL(config4, request, basePath); + if (config4.fallback) return withPath(config4.fallback, basePath); + return getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders); + } + if (typeof config4 === "string") return getBaseURL(config4, basePath, request, loadEnv, trustedProxyHeaders); + return getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/random.mjs +init_random(); +var generateRandomString = createRandomStringGenerator("a-z", "0-9", "A-Z", "-_"); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/buffer.mjs +function constantTimeEqual(a, b) { + if (typeof a === "string") a = new TextEncoder().encode(a); + if (typeof b === "string") b = new TextEncoder().encode(b); + const aBuffer = new Uint8Array(a); + const bBuffer = new Uint8Array(b); + let c = aBuffer.length ^ bBuffer.length; + const length = Math.max(aBuffer.length, bBuffer.length); + for (let i = 0; i < length; i++) c |= (i < aBuffer.length ? aBuffer[i] : 0) ^ (i < bBuffer.length ? bBuffer[i] : 0); + return c === 0; +} + +// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; +} +function anumber(n, title = "") { + if (typeof n !== "number") { + const prefix = title && `"${title}" `; + throw new TypeError(`${prefix}expected number, got ${typeof n}`); + } + if (!Number.isSafeInteger(n) || n < 0) { + const prefix = title && `"${title}" `; + throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); + } +} +function abytes(value, length, title = "") { + const bytes = isBytes(value); + const len = value?.length; + const needsLen = length !== void 0; + if (!bytes || needsLen && len !== length) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ""; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message2 = prefix + "expected Uint8Array" + ofLen + ", got " + got; + if (!bytes) + throw new TypeError(message2); + throw new RangeError(message2); + } + return value; +} +function ahash(h) { + if (typeof h !== "function" || typeof h.create !== "function") + throw new TypeError("Hash must wrapped by utils.createHasher"); + anumber(h.outputLen); + anumber(h.blockLen); + if (h.outputLen < 1) + throw new Error('"outputLen" must be >= 1'); + if (h.blockLen < 1) + throw new Error('"blockLen" must be >= 1'); +} +function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function aoutput(out, instance) { + abytes(out, void 0, "digestInto() output"); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError('"digestInto() output" expected to be of length >=' + min); + } +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function rotr(word, shift) { + return word << 32 - shift | word >>> shift; +} +function createHasher(hashCons, info2 = {}) { + const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); + const tmp = hashCons(void 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts) => hashCons(opts); + Object.assign(hashC, info2); + return Object.freeze(hashC); +} +var oidNist = (suffix) => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) +}); + +// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js +var _HMAC = class { + constructor(hash2, key) { + __publicField(this, "oHash"); + __publicField(this, "iHash"); + __publicField(this, "blockLen"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF", false); + __publicField(this, "finished", false); + __publicField(this, "destroyed", false); + ahash(hash2); + abytes(key, void 0, "key"); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash2.create(); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + clean(pad); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const buf = out.subarray(0, this.outputLen); + this.iHash.digestInto(buf); + this.oHash.update(buf); + this.oHash.digestInto(buf); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone() { + return this._cloneInto(); + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +}; +var hmac = /* @__PURE__ */ (() => { + const hmac_ = (hash2, key, message2) => new _HMAC(hash2, key).update(message2).digest(); + hmac_.create = (hash2, key) => new _HMAC(hash2, key); + return hmac_; +})(); + +// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hkdf.js +function extract(hash2, ikm, salt) { + ahash(hash2); + if (salt === void 0) + salt = new Uint8Array(hash2.outputLen); + return hmac(hash2, salt, ikm); +} +var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); +var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); +function expand(hash2, prk, info2, length = 32) { + ahash(hash2); + anumber(length, "length"); + abytes(prk, void 0, "prk"); + const olen = hash2.outputLen; + if (prk.length < olen) + throw new Error('"prk" must be at least HashLen octets'); + if (length > 255 * olen) + throw new Error("Length must be <= 255*HashLen"); + const blocks = Math.ceil(length / olen); + if (info2 === void 0) + info2 = EMPTY_BUFFER; + else + abytes(info2, void 0, "info"); + const okm = new Uint8Array(blocks * olen); + const HMAC = hmac.create(hash2, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info2).update(HKDF_COUNTER).digestInto(T); + okm.set(T, olen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + clean(T, HKDF_COUNTER); + return okm.slice(0, length); +} +var hkdf = (hash2, ikm, salt, info2, length) => expand(hash2, extract(hash2, ikm, salt), info2, length); + +// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js +function Chi(a, b, c) { + return a & b ^ ~a & c; +} +function Maj(a, b, c) { + return a & b ^ a & c ^ b & c; +} +var HashMD = class { + constructor(blockLen, outputLen, padOffset, isLE2) { + __publicField(this, "blockLen"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF", false); + __publicField(this, "padOffset"); + __publicField(this, "isLE"); + // For partial updates less than block size + __publicField(this, "buffer"); + __publicField(this, "view"); + __publicField(this, "finished", false); + __publicField(this, "length", 0); + __publicField(this, "pos", 0); + __publicField(this, "destroyed", false); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + const { view, buffer, blockLen } = this; + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer[pos++] = 128; + clean(this.buffer.subarray(pos)); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen must be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } + clone() { + return this._cloneInto(); + } +}; +var SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); + +// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js +var SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var SHA256_W = /* @__PURE__ */ new Uint32Array(64); +var SHA2_32B = class extends HashMD { + constructor(outputLen) { + super(64, outputLen, 8, false); + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + clean(SHA256_W); + } + destroy() { + this.destroyed = true; + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } +}; +var _SHA256 = class extends SHA2_32B { + constructor() { + super(32); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + __publicField(this, "A", SHA256_IV[0] | 0); + __publicField(this, "B", SHA256_IV[1] | 0); + __publicField(this, "C", SHA256_IV[2] | 0); + __publicField(this, "D", SHA256_IV[3] | 0); + __publicField(this, "E", SHA256_IV[4] | 0); + __publicField(this, "F", SHA256_IV[5] | 0); + __publicField(this, "G", SHA256_IV[6] | 0); + __publicField(this, "H", SHA256_IV[7] | 0); + } +}; +var sha256 = /* @__PURE__ */ createHasher( + () => new _SHA256(), + /* @__PURE__ */ oidNist(1) +); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js +var base64url_exports = {}; +__export(base64url_exports, { + decode: () => decode3, + encode: () => encode4 +}); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js +var encoder = new TextEncoder(); +var decoder = new TextDecoder(); +var MAX_INT32 = 2 ** 32; +function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size); + let i = 0; + for (const buffer of buffers) { + buf.set(buffer, i); + i += buffer.length; + } + return buf; +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) { + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + } + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); +} +function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +function uint32be(value) { + const buf = new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +function encode3(string4) { + const bytes = new Uint8Array(string4.length); + for (let i = 0; i < string4.length; i++) { + const code = string4.charCodeAt(i); + if (code > 127) { + throw new TypeError("non-ASCII string encountered in encode()"); + } + bytes[i] = code; + } + return bytes; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js +function encodeBase64(input) { + if (Uint8Array.prototype.toBase64) { + return input.toBase64(); + } + const CHUNK_SIZE2 = 32768; + const arr = []; + for (let i = 0; i < input.length; i += CHUNK_SIZE2) { + arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE2))); + } + return btoa(arr.join("")); +} +function decodeBase64(encoded) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(encoded); + } + const binary2 = atob(encoded); + const bytes = new Uint8Array(binary2.length); + for (let i = 0; i < binary2.length; i++) { + bytes[i] = binary2.charCodeAt(i); + } + return bytes; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js +function decode3(input) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { + alphabet: "base64url" + }); + } + let encoded = input; + if (encoded instanceof Uint8Array) { + encoded = decoder.decode(encoded); + } + encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); + try { + return decodeBase64(encoded); + } catch { + throw new TypeError("The input to be decoded is not correctly encoded."); + } +} +function encode4(input) { + let unencoded = input; + if (typeof unencoded === "string") { + unencoded = encoder.encode(unencoded); + } + if (Uint8Array.prototype.toBase64) { + return unencoded.toBase64({ alphabet: "base64url", omitPadding: true }); + } + return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js +var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +var isAlgorithm = (algorithm2, name) => algorithm2.name === name; +function getHashLength(hash2) { + return parseInt(hash2.name.slice(4), 10); +} +function checkHashLength(algorithm2, expected) { + const actual = getHashLength(algorithm2.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, "algorithm.hash"); +} +function getNamedCurve(alg2) { + switch (alg2) { + case "ES256": + return "P-256"; + case "ES384": + return "P-384"; + case "ES512": + return "P-521"; + default: + throw new Error("unreachable"); + } +} +function checkUsage(key, usage) { + if (usage && !key.usages.includes(usage)) { + throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); + } +} +function checkSigCryptoKey(key, alg2, usage) { + switch (alg2) { + case "HS256": + case "HS384": + case "HS512": { + if (!isAlgorithm(key.algorithm, "HMAC")) + throw unusable("HMAC"); + checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); + break; + } + case "RS256": + case "RS384": + case "RS512": { + if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) + throw unusable("RSASSA-PKCS1-v1_5"); + checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); + break; + } + case "PS256": + case "PS384": + case "PS512": { + if (!isAlgorithm(key.algorithm, "RSA-PSS")) + throw unusable("RSA-PSS"); + checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); + break; + } + case "Ed25519": + case "EdDSA": { + if (!isAlgorithm(key.algorithm, "Ed25519")) + throw unusable("Ed25519"); + break; + } + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": { + if (!isAlgorithm(key.algorithm, alg2)) + throw unusable(alg2); + break; + } + case "ES256": + case "ES384": + case "ES512": { + if (!isAlgorithm(key.algorithm, "ECDSA")) + throw unusable("ECDSA"); + const expected = getNamedCurve(alg2); + const actual = key.algorithm.namedCurve; + if (actual !== expected) + throw unusable(expected, "algorithm.namedCurve"); + break; + } + default: + throw new TypeError("CryptoKey does not support this operation"); + } + checkUsage(key, usage); +} +function checkEncCryptoKey(key, alg2, usage) { + switch (alg2) { + case "A128GCM": + case "A192GCM": + case "A256GCM": { + if (!isAlgorithm(key.algorithm, "AES-GCM")) + throw unusable("AES-GCM"); + const expected = parseInt(alg2.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, "algorithm.length"); + break; + } + case "A128KW": + case "A192KW": + case "A256KW": { + if (!isAlgorithm(key.algorithm, "AES-KW")) + throw unusable("AES-KW"); + const expected = parseInt(alg2.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, "algorithm.length"); + break; + } + case "ECDH": { + switch (key.algorithm.name) { + case "ECDH": + case "X25519": + break; + default: + throw unusable("ECDH or X25519"); + } + break; + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": + if (!isAlgorithm(key.algorithm, "PBKDF2")) + throw unusable("PBKDF2"); + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + if (!isAlgorithm(key.algorithm, "RSA-OAEP")) + throw unusable("RSA-OAEP"); + checkHashLength(key.algorithm, parseInt(alg2.slice(9), 10) || 1); + break; + } + default: + throw new TypeError("CryptoKey does not support this operation"); + } + checkUsage(key, usage); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js +function message(msg, actual, ...types) { + types = types.filter(Boolean); + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(", ")}, or ${last}.`; + } else if (types.length === 2) { + msg += `one of type ${types[0]} or ${types[1]}.`; + } else { + msg += `of type ${types[0]}.`; + } + if (actual == null) { + msg += ` Received ${actual}`; + } else if (typeof actual === "function" && actual.name) { + msg += ` Received function ${actual.name}`; + } else if (typeof actual === "object" && actual != null) { + if (actual.constructor?.name) { + msg += ` Received an instance of ${actual.constructor.name}`; + } + } + return msg; +} +var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types); +var withAlg = (alg2, actual, ...types) => message(`Key for the ${alg2} algorithm must be `, actual, ...types); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js +var JOSEError = class extends Error { + constructor(message2, options) { + super(message2, options); + __publicField(this, "code", "ERR_JOSE_GENERIC"); + this.name = this.constructor.name; + Error.captureStackTrace?.(this, this.constructor); + } +}; +__publicField(JOSEError, "code", "ERR_JOSE_GENERIC"); +var JWTClaimValidationFailed = class extends JOSEError { + constructor(message2, payload, claim = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim, reason, payload } }); + __publicField(this, "code", "ERR_JWT_CLAIM_VALIDATION_FAILED"); + __publicField(this, "claim"); + __publicField(this, "reason"); + __publicField(this, "payload"); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } +}; +__publicField(JWTClaimValidationFailed, "code", "ERR_JWT_CLAIM_VALIDATION_FAILED"); +var JWTExpired = class extends JOSEError { + constructor(message2, payload, claim = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim, reason, payload } }); + __publicField(this, "code", "ERR_JWT_EXPIRED"); + __publicField(this, "claim"); + __publicField(this, "reason"); + __publicField(this, "payload"); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } +}; +__publicField(JWTExpired, "code", "ERR_JWT_EXPIRED"); +var JOSEAlgNotAllowed = class extends JOSEError { + constructor() { + super(...arguments); + __publicField(this, "code", "ERR_JOSE_ALG_NOT_ALLOWED"); + } +}; +__publicField(JOSEAlgNotAllowed, "code", "ERR_JOSE_ALG_NOT_ALLOWED"); +var JOSENotSupported = class extends JOSEError { + constructor() { + super(...arguments); + __publicField(this, "code", "ERR_JOSE_NOT_SUPPORTED"); + } +}; +__publicField(JOSENotSupported, "code", "ERR_JOSE_NOT_SUPPORTED"); +var JWEDecryptionFailed = class extends JOSEError { + constructor(message2 = "decryption operation failed", options) { + super(message2, options); + __publicField(this, "code", "ERR_JWE_DECRYPTION_FAILED"); + } +}; +__publicField(JWEDecryptionFailed, "code", "ERR_JWE_DECRYPTION_FAILED"); +var JWEInvalid = class extends JOSEError { + constructor() { + super(...arguments); + __publicField(this, "code", "ERR_JWE_INVALID"); + } +}; +__publicField(JWEInvalid, "code", "ERR_JWE_INVALID"); +var JWSInvalid = class extends JOSEError { + constructor() { + super(...arguments); + __publicField(this, "code", "ERR_JWS_INVALID"); + } +}; +__publicField(JWSInvalid, "code", "ERR_JWS_INVALID"); +var JWTInvalid = class extends JOSEError { + constructor() { + super(...arguments); + __publicField(this, "code", "ERR_JWT_INVALID"); + } +}; +__publicField(JWTInvalid, "code", "ERR_JWT_INVALID"); +var JWKInvalid = class extends JOSEError { + constructor() { + super(...arguments); + __publicField(this, "code", "ERR_JWK_INVALID"); + } +}; +__publicField(JWKInvalid, "code", "ERR_JWK_INVALID"); +var JWKSInvalid = class extends JOSEError { + constructor() { + super(...arguments); + __publicField(this, "code", "ERR_JWKS_INVALID"); + } +}; +__publicField(JWKSInvalid, "code", "ERR_JWKS_INVALID"); +var JWKSNoMatchingKey = class extends JOSEError { + constructor(message2 = "no applicable key found in the JSON Web Key Set", options) { + super(message2, options); + __publicField(this, "code", "ERR_JWKS_NO_MATCHING_KEY"); + } +}; +__publicField(JWKSNoMatchingKey, "code", "ERR_JWKS_NO_MATCHING_KEY"); +var _a11, _b; +var JWKSMultipleMatchingKeys = class extends (_b = JOSEError, _a11 = Symbol.asyncIterator, _b) { + constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) { + super(message2, options); + __publicField(this, _a11); + __publicField(this, "code", "ERR_JWKS_MULTIPLE_MATCHING_KEYS"); + } +}; +__publicField(JWKSMultipleMatchingKeys, "code", "ERR_JWKS_MULTIPLE_MATCHING_KEYS"); +var JWKSTimeout = class extends JOSEError { + constructor(message2 = "request timed out", options) { + super(message2, options); + __publicField(this, "code", "ERR_JWKS_TIMEOUT"); + } +}; +__publicField(JWKSTimeout, "code", "ERR_JWKS_TIMEOUT"); +var JWSSignatureVerificationFailed = class extends JOSEError { + constructor(message2 = "signature verification failed", options) { + super(message2, options); + __publicField(this, "code", "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"); + } +}; +__publicField(JWSSignatureVerificationFailed, "code", "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js +function assertCryptoKey(key) { + if (!isCryptoKey(key)) { + throw new Error("CryptoKey instance expected"); + } +} +var isCryptoKey = (key) => { + if (key?.[Symbol.toStringTag] === "CryptoKey") + return true; + try { + return key instanceof CryptoKey; + } catch { + return false; + } +}; +var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; +var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js +function cekLength(alg2) { + switch (alg2) { + case "A128GCM": + return 128; + case "A192GCM": + return 192; + case "A256GCM": + case "A128CBC-HS256": + return 256; + case "A192CBC-HS384": + return 384; + case "A256CBC-HS512": + return 512; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg2}`); + } +} +var generateCek = (alg2) => crypto.getRandomValues(new Uint8Array(cekLength(alg2) >> 3)); +function checkCekLength(cek, expected) { + const actual = cek.byteLength << 3; + if (actual !== expected) { + throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } +} +function ivBitLength(alg2) { + switch (alg2) { + case "A128GCM": + case "A128GCMKW": + case "A192GCM": + case "A192GCMKW": + case "A256GCM": + case "A256GCMKW": + return 96; + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + return 128; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg2}`); + } +} +var generateIv = (alg2) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg2) >> 3)); +function checkIvLength(enc2, iv) { + if (iv.length << 3 !== ivBitLength(enc2)) { + throw new JWEInvalid("Invalid Initialization Vector length"); + } +} +async function cbcKeySetup(enc2, cek, usage) { + if (!(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "Uint8Array")); + } + const keySize = parseInt(enc2.slice(1, 4), 10); + const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]); + const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { + hash: `SHA-${keySize << 1}`, + name: "HMAC" + }, false, ["sign"]); + return { encKey, macKey, keySize }; +} +async function cbcHmacTag(macKey, macData, keySize) { + return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); +} +async function cbcEncrypt(enc2, plaintext, cek, iv, aad) { + const { encKey, macKey, keySize } = await cbcKeySetup(enc2, cek, "encrypt"); + const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ + iv, + name: "AES-CBC" + }, encKey, plaintext)); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const tag2 = await cbcHmacTag(macKey, macData, keySize); + return { ciphertext, tag: tag2, iv }; +} +async function timingSafeEqual(a, b) { + if (!(a instanceof Uint8Array)) { + throw new TypeError("First argument must be a buffer"); + } + if (!(b instanceof Uint8Array)) { + throw new TypeError("Second argument must be a buffer"); + } + const algorithm2 = { name: "HMAC", hash: "SHA-256" }; + const key = await crypto.subtle.generateKey(algorithm2, false, ["sign"]); + const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm2, key, a)); + const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm2, key, b)); + let out = 0; + let i = -1; + while (++i < 32) { + out |= aHmac[i] ^ bHmac[i]; + } + return out === 0; +} +async function cbcDecrypt(enc2, cek, ciphertext, iv, tag2, aad) { + const { encKey, macKey, keySize } = await cbcKeySetup(enc2, cek, "decrypt"); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const expectedTag = await cbcHmacTag(macKey, macData, keySize); + let macCheckPassed; + try { + macCheckPassed = await timingSafeEqual(tag2, expectedTag); + } catch { + } + if (!macCheckPassed) { + throw new JWEDecryptionFailed(); + } + let plaintext; + try { + plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); + } catch { + } + if (!plaintext) { + throw new JWEDecryptionFailed(); + } + return plaintext; +} +async function gcmEncrypt(enc2, plaintext, cek, iv, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); + } else { + checkEncCryptoKey(cek, enc2, "encrypt"); + encKey = cek; + } + const encrypted = new Uint8Array(await crypto.subtle.encrypt({ + additionalData: aad, + iv, + name: "AES-GCM", + tagLength: 128 + }, encKey, plaintext)); + const tag2 = encrypted.slice(-16); + const ciphertext = encrypted.slice(0, -16); + return { ciphertext, tag: tag2, iv }; +} +async function gcmDecrypt(enc2, cek, ciphertext, iv, tag2, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); + } else { + checkEncCryptoKey(cek, enc2, "decrypt"); + encKey = cek; + } + try { + return new Uint8Array(await crypto.subtle.decrypt({ + additionalData: aad, + iv, + name: "AES-GCM", + tagLength: 128 + }, encKey, concat(ciphertext, tag2))); + } catch { + throw new JWEDecryptionFailed(); + } +} +var unsupportedEnc = "Unsupported JWE Content Encryption Algorithm"; +async function encrypt(enc2, plaintext, cek, iv, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); + } + if (iv) { + checkIvLength(enc2, iv); + } else { + iv = generateIv(enc2); + } + switch (enc2) { + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + if (cek instanceof Uint8Array) { + checkCekLength(cek, parseInt(enc2.slice(-3), 10)); + } + return cbcEncrypt(enc2, plaintext, cek, iv, aad); + case "A128GCM": + case "A192GCM": + case "A256GCM": + if (cek instanceof Uint8Array) { + checkCekLength(cek, parseInt(enc2.slice(1, 4), 10)); + } + return gcmEncrypt(enc2, plaintext, cek, iv, aad); + default: + throw new JOSENotSupported(unsupportedEnc); + } +} +async function decrypt(enc2, cek, ciphertext, iv, tag2, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); + } + if (!iv) { + throw new JWEInvalid("JWE Initialization Vector missing"); + } + if (!tag2) { + throw new JWEInvalid("JWE Authentication Tag missing"); + } + checkIvLength(enc2, iv); + switch (enc2) { + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc2.slice(-3), 10)); + return cbcDecrypt(enc2, cek, ciphertext, iv, tag2, aad); + case "A128GCM": + case "A192GCM": + case "A256GCM": + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc2.slice(1, 4), 10)); + return gcmDecrypt(enc2, cek, ciphertext, iv, tag2, aad); + default: + throw new JOSENotSupported(unsupportedEnc); + } +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js +var unprotected = Symbol(); +function assertNotSet(value, name) { + if (value) { + throw new TypeError(`${name} can only be called once`); + } +} +function decodeBase64url(value, label, ErrorClass) { + try { + return decode3(value); + } catch { + throw new ErrorClass(`Failed to base64url decode the ${label}`); + } +} +async function digest(algorithm2, data) { + const subtleDigest = `SHA-${algorithm2.slice(-3)}`; + return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js +var isObjectLike2 = (value) => typeof value === "object" && value !== null; +function isObject3(input) { + if (!isObjectLike2(input) || Object.prototype.toString.call(input) !== "[object Object]") { + return false; + } + if (Object.getPrototypeOf(input) === null) { + return true; + } + let proto = input; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(input) === proto; +} +function isDisjoint(...headers) { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) { + return true; + } + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; + } + for (const parameter of parameters) { + if (acc.has(parameter)) { + return false; + } + acc.add(parameter); + } + } + return true; +} +var isJWK = (key) => isObject3(key) && typeof key.kty === "string"; +var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); +var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; +var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js +function checkKeySize(key, alg2) { + if (key.algorithm.length !== parseInt(alg2.slice(1, 4), 10)) { + throw new TypeError(`Invalid key size for alg: ${alg2}`); + } +} +function getCryptoKey(key, alg2, usage) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]); + } + checkEncCryptoKey(key, alg2, usage); + return key; +} +async function wrap(alg2, key, cek) { + const cryptoKey = await getCryptoKey(key, alg2, "wrapKey"); + checkKeySize(cryptoKey, alg2); + const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); + return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); +} +async function unwrap(alg2, key, encryptedKey) { + const cryptoKey = await getCryptoKey(key, alg2, "unwrapKey"); + checkKeySize(cryptoKey, alg2); + const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); + return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek)); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js +function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +async function concatKdf(Z, L, OtherInfo) { + const dkLen = L >> 3; + const hashLen = 32; + const reps = Math.ceil(dkLen / hashLen); + const dk = new Uint8Array(reps * hashLen); + for (let i = 1; i <= reps; i++) { + const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length); + hashInput.set(uint32be(i), 0); + hashInput.set(Z, 4); + hashInput.set(OtherInfo, 4 + Z.length); + const hashResult = await digest("sha256", hashInput); + dk.set(hashResult, (i - 1) * hashLen); + } + return dk.slice(0, dkLen); +} +async function deriveKey(publicKey, privateKey, algorithm2, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) { + checkEncCryptoKey(publicKey, "ECDH"); + checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); + const algorithmID = lengthAndInput(encode3(algorithm2)); + const partyUInfo = lengthAndInput(apu); + const partyVInfo = lengthAndInput(apv); + const suppPubInfo = uint32be(keyLength); + const suppPrivInfo = new Uint8Array(); + const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); + const Z = new Uint8Array(await crypto.subtle.deriveBits({ + name: publicKey.algorithm.name, + public: publicKey + }, privateKey, getEcdhBitLength(publicKey))); + return concatKdf(Z, keyLength, otherInfo); +} +function getEcdhBitLength(publicKey) { + if (publicKey.algorithm.name === "X25519") { + return 256; + } + return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3; +} +function allowed(key) { + switch (key.algorithm.namedCurve) { + case "P-256": + case "P-384": + case "P-521": + return true; + default: + return key.algorithm.name === "X25519"; + } +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js +function getCryptoKey2(key, alg2) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey("raw", key, "PBKDF2", false, [ + "deriveBits" + ]); + } + checkEncCryptoKey(key, alg2, "deriveBits"); + return key; +} +var concatSalt = (alg2, p2sInput) => concat(encode3(alg2), Uint8Array.of(0), p2sInput); +async function deriveKey2(p2s, alg2, p2c, key) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) { + throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); + } + const salt = concatSalt(alg2, p2s); + const keylen = parseInt(alg2.slice(13, 16), 10); + const subtleAlg = { + hash: `SHA-${alg2.slice(8, 11)}`, + iterations: p2c, + name: "PBKDF2", + salt + }; + const cryptoKey = await getCryptoKey2(key, alg2); + return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); +} +async function wrap2(alg2, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) { + const derived = await deriveKey2(p2s, alg2, p2c, key); + const encryptedKey = await wrap(alg2.slice(-6), derived, cek); + return { encryptedKey, p2c, p2s: encode4(p2s) }; +} +async function unwrap2(alg2, key, encryptedKey, p2c, p2s) { + const derived = await deriveKey2(p2s, alg2, p2c, key); + return unwrap(alg2.slice(-6), derived, encryptedKey); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js +function checkKeyLength(alg2, key) { + if (alg2.startsWith("RS") || alg2.startsWith("PS")) { + const { modulusLength } = key.algorithm; + if (typeof modulusLength !== "number" || modulusLength < 2048) { + throw new TypeError(`${alg2} requires key modulusLength to be 2048 bits or larger`); + } + } +} +function subtleAlgorithm(alg2, algorithm2) { + const hash2 = `SHA-${alg2.slice(-3)}`; + switch (alg2) { + case "HS256": + case "HS384": + case "HS512": + return { hash: hash2, name: "HMAC" }; + case "PS256": + case "PS384": + case "PS512": + return { hash: hash2, name: "RSA-PSS", saltLength: parseInt(alg2.slice(-3), 10) >> 3 }; + case "RS256": + case "RS384": + case "RS512": + return { hash: hash2, name: "RSASSA-PKCS1-v1_5" }; + case "ES256": + case "ES384": + case "ES512": + return { hash: hash2, name: "ECDSA", namedCurve: algorithm2.namedCurve }; + case "Ed25519": + case "EdDSA": + return { name: "Ed25519" }; + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + return { name: alg2 }; + default: + throw new JOSENotSupported(`alg ${alg2} is not supported either by JOSE or your javascript runtime`); + } +} +async function getSigKey(alg2, key, usage) { + if (key instanceof Uint8Array) { + if (!alg2.startsWith("HS")) { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg2.slice(-3)}`, name: "HMAC" }, false, [usage]); + } + checkSigCryptoKey(key, alg2, usage); + return key; +} +async function sign(alg2, key, data) { + const cryptoKey = await getSigKey(alg2, key, "sign"); + checkKeyLength(alg2, cryptoKey); + const signature = await crypto.subtle.sign(subtleAlgorithm(alg2, cryptoKey.algorithm), cryptoKey, data); + return new Uint8Array(signature); +} +async function verify(alg2, key, signature, data) { + const cryptoKey = await getSigKey(alg2, key, "verify"); + checkKeyLength(alg2, cryptoKey); + const algorithm2 = subtleAlgorithm(alg2, cryptoKey.algorithm); + try { + return await crypto.subtle.verify(algorithm2, cryptoKey, signature, data); + } catch { + return false; + } +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js +var subtleAlgorithm2 = (alg2) => { + switch (alg2) { + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + return "RSA-OAEP"; + default: + throw new JOSENotSupported(`alg ${alg2} is not supported either by JOSE or your javascript runtime`); + } +}; +async function encrypt2(alg2, key, cek) { + checkEncCryptoKey(key, alg2, "encrypt"); + checkKeyLength(alg2, key); + return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm2(alg2), key, cek)); +} +async function decrypt2(alg2, key, encryptedKey) { + checkEncCryptoKey(key, alg2, "decrypt"); + checkKeyLength(alg2, key); + return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm2(alg2), key, encryptedKey)); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js +var unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value'; +function subtleMapping(jwk) { + let algorithm2; + let keyUsages; + switch (jwk.kty) { + case "AKP": { + switch (jwk.alg) { + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + algorithm2 = { name: jwk.alg }; + keyUsages = jwk.priv ? ["sign"] : ["verify"]; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "RSA": { + switch (jwk.alg) { + case "PS256": + case "PS384": + case "PS512": + algorithm2 = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "RS256": + case "RS384": + case "RS512": + algorithm2 = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + algorithm2 = { + name: "RSA-OAEP", + hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` + }; + keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "EC": { + switch (jwk.alg) { + case "ES256": + case "ES384": + case "ES512": + algorithm2 = { + name: "ECDSA", + namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg] + }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + algorithm2 = { name: "ECDH", namedCurve: jwk.crv }; + keyUsages = jwk.d ? ["deriveBits"] : []; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "OKP": { + switch (jwk.alg) { + case "Ed25519": + case "EdDSA": + algorithm2 = { name: "Ed25519" }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + algorithm2 = { name: jwk.crv }; + keyUsages = jwk.d ? ["deriveBits"] : []; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); + } + return { algorithm: algorithm2, keyUsages }; +} +async function jwkToKey(jwk) { + if (!jwk.alg) { + throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); + } + const { algorithm: algorithm2, keyUsages } = subtleMapping(jwk); + const keyData = { ...jwk }; + if (keyData.kty !== "AKP") { + delete keyData.alg; + } + delete keyData.use; + return crypto.subtle.importKey("jwk", keyData, algorithm2, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js +var unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; +var cache; +var handleJWK = async (key, jwk, alg2, freeze2 = false) => { + cache || (cache = /* @__PURE__ */ new WeakMap()); + let cached2 = cache.get(key); + if (cached2?.[alg2]) { + return cached2[alg2]; + } + const cryptoKey = await jwkToKey({ ...jwk, alg: alg2 }); + if (freeze2) + Object.freeze(key); + if (!cached2) { + cache.set(key, { [alg2]: cryptoKey }); + } else { + cached2[alg2] = cryptoKey; + } + return cryptoKey; +}; +var handleKeyObject = (keyObject, alg2) => { + cache || (cache = /* @__PURE__ */ new WeakMap()); + let cached2 = cache.get(keyObject); + if (cached2?.[alg2]) { + return cached2[alg2]; + } + const isPublic = keyObject.type === "public"; + const extractable = isPublic ? true : false; + let cryptoKey; + if (keyObject.asymmetricKeyType === "x25519") { + switch (alg2) { + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + break; + default: + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); + } + if (keyObject.asymmetricKeyType === "ed25519") { + if (alg2 !== "EdDSA" && alg2 !== "Ed25519") { + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ + isPublic ? "verify" : "sign" + ]); + } + switch (keyObject.asymmetricKeyType) { + case "ml-dsa-44": + case "ml-dsa-65": + case "ml-dsa-87": { + if (alg2 !== keyObject.asymmetricKeyType.toUpperCase()) { + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ + isPublic ? "verify" : "sign" + ]); + } + } + if (keyObject.asymmetricKeyType === "rsa") { + let hash2; + switch (alg2) { + case "RSA-OAEP": + hash2 = "SHA-1"; + break; + case "RS256": + case "PS256": + case "RSA-OAEP-256": + hash2 = "SHA-256"; + break; + case "RS384": + case "PS384": + case "RSA-OAEP-384": + hash2 = "SHA-384"; + break; + case "RS512": + case "PS512": + case "RSA-OAEP-512": + hash2 = "SHA-512"; + break; + default: + throw new TypeError(unusableForAlg); + } + if (alg2.startsWith("RSA-OAEP")) { + return keyObject.toCryptoKey({ + name: "RSA-OAEP", + hash: hash2 + }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); + } + cryptoKey = keyObject.toCryptoKey({ + name: alg2.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", + hash: hash2 + }, extractable, [isPublic ? "verify" : "sign"]); + } + if (keyObject.asymmetricKeyType === "ec") { + const nist = /* @__PURE__ */ new Map([ + ["prime256v1", "P-256"], + ["secp384r1", "P-384"], + ["secp521r1", "P-521"] + ]); + const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve); + if (!namedCurve) { + throw new TypeError(unusableForAlg); + } + const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }; + if (expectedCurve[alg2] && namedCurve === expectedCurve[alg2]) { + cryptoKey = keyObject.toCryptoKey({ + name: "ECDSA", + namedCurve + }, extractable, [isPublic ? "verify" : "sign"]); + } + if (alg2.startsWith("ECDH-ES")) { + cryptoKey = keyObject.toCryptoKey({ + name: "ECDH", + namedCurve + }, extractable, isPublic ? [] : ["deriveBits"]); + } + } + if (!cryptoKey) { + throw new TypeError(unusableForAlg); + } + if (!cached2) { + cache.set(keyObject, { [alg2]: cryptoKey }); + } else { + cached2[alg2] = cryptoKey; + } + return cryptoKey; +}; +async function normalizeKey(key, alg2) { + if (key instanceof Uint8Array) { + return key; + } + if (isCryptoKey(key)) { + return key; + } + if (isKeyObject(key)) { + if (key.type === "secret") { + return key.export(); + } + if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") { + try { + return handleKeyObject(key, alg2); + } catch (err) { + if (err instanceof TypeError) { + throw err; + } + } + } + let jwk = key.export({ format: "jwk" }); + return handleJWK(key, jwk, alg2); + } + if (isJWK(key)) { + if (key.k) { + return decode3(key.k); + } + return handleJWK(key, key, alg2, true); + } + throw new Error("unreachable"); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js +async function importJWK(jwk, alg2, options) { + if (!isObject3(jwk)) { + throw new TypeError("JWK must be an object"); + } + let ext; + alg2 ?? (alg2 = jwk.alg); + ext ?? (ext = options?.extractable ?? jwk.ext); + switch (jwk.kty) { + case "oct": + if (typeof jwk.k !== "string" || !jwk.k) { + throw new TypeError('missing "k" (Key Value) Parameter value'); + } + return decode3(jwk.k); + case "RSA": + if ("oth" in jwk && jwk.oth !== void 0) { + throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + } + return jwkToKey({ ...jwk, alg: alg2, ext }); + case "AKP": { + if (typeof jwk.alg !== "string" || !jwk.alg) { + throw new TypeError('missing "alg" (Algorithm) Parameter value'); + } + if (alg2 !== void 0 && alg2 !== jwk.alg) { + throw new TypeError("JWK alg and alg option value mismatch"); + } + return jwkToKey({ ...jwk, ext }); + } + case "EC": + case "OKP": + return jwkToKey({ ...jwk, alg: alg2, ext }); + default: + throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); + } +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js +async function keyToJWK(key) { + if (isKeyObject(key)) { + if (key.type === "secret") { + key = key.export(); + } else { + return key.export({ format: "jwk" }); + } + } + if (key instanceof Uint8Array) { + return { + kty: "oct", + k: encode4(key) + }; + } + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array")); + } + if (!key.extractable) { + throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); + } + const { ext, key_ops, alg: alg2, use: use2, ...jwk } = await crypto.subtle.exportKey("jwk", key); + if (jwk.kty === "AKP") { + ; + jwk.alg = alg2; + } + return jwk; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js +async function exportJWK(key) { + return keyToJWK(key); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js +async function wrap3(alg2, key, cek, iv) { + const jweAlgorithm = alg2.slice(0, 7); + const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array()); + return { + encryptedKey: wrapped.ciphertext, + iv: encode4(wrapped.iv), + tag: encode4(wrapped.tag) + }; +} +async function unwrap3(alg2, key, encryptedKey, iv, tag2) { + const jweAlgorithm = alg2.slice(0, 7); + return decrypt(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array()); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js +var unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value'; +function assertEncryptedKey(encryptedKey) { + if (encryptedKey === void 0) + throw new JWEInvalid("JWE Encrypted Key missing"); +} +async function decryptKeyManagement(alg2, key, encryptedKey, joseHeader, options) { + switch (alg2) { + case "dir": { + if (encryptedKey !== void 0) + throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); + return key; + } + case "ECDH-ES": + if (encryptedKey !== void 0) + throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": { + if (!isObject3(joseHeader.epk)) + throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); + assertCryptoKey(key); + if (!allowed(key)) + throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); + const epk = await importJWK(joseHeader.epk, alg2); + assertCryptoKey(epk); + let partyUInfo; + let partyVInfo; + if (joseHeader.apu !== void 0) { + if (typeof joseHeader.apu !== "string") + throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); + partyUInfo = decodeBase64url(joseHeader.apu, "apu", JWEInvalid); + } + if (joseHeader.apv !== void 0) { + if (typeof joseHeader.apv !== "string") + throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); + partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid); + } + const sharedSecret = await deriveKey(epk, key, alg2 === "ECDH-ES" ? joseHeader.enc : alg2, alg2 === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg2.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (alg2 === "ECDH-ES") + return sharedSecret; + assertEncryptedKey(encryptedKey); + return unwrap(alg2.slice(-6), sharedSecret, encryptedKey); + } + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + assertEncryptedKey(encryptedKey); + assertCryptoKey(key); + return decrypt2(alg2, key, encryptedKey); + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": { + assertEncryptedKey(encryptedKey); + if (typeof joseHeader.p2c !== "number") + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); + const p2cLimit = options?.maxPBES2Count || 1e4; + if (joseHeader.p2c > p2cLimit) + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); + if (typeof joseHeader.p2s !== "string") + throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); + let p2s; + p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid); + return unwrap2(alg2, key, encryptedKey, joseHeader.p2c, p2s); + } + case "A128KW": + case "A192KW": + case "A256KW": { + assertEncryptedKey(encryptedKey); + return unwrap(alg2, key, encryptedKey); + } + case "A128GCMKW": + case "A192GCMKW": + case "A256GCMKW": { + assertEncryptedKey(encryptedKey); + if (typeof joseHeader.iv !== "string") + throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); + if (typeof joseHeader.tag !== "string") + throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); + let iv; + iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid); + let tag2; + tag2 = decodeBase64url(joseHeader.tag, "tag", JWEInvalid); + return unwrap3(alg2, key, encryptedKey, iv, tag2); + } + default: { + throw new JOSENotSupported(unsupportedAlgHeader); + } + } +} +async function encryptKeyManagement(alg2, enc2, key, providedCek, providedParameters = {}) { + let encryptedKey; + let parameters; + let cek; + switch (alg2) { + case "dir": { + cek = key; + break; + } + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": { + assertCryptoKey(key); + if (!allowed(key)) { + throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); + } + const { apu, apv } = providedParameters; + let ephemeralKey; + if (providedParameters.epk) { + ephemeralKey = await normalizeKey(providedParameters.epk, alg2); + } else { + ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey; + } + const { x, y, crv, kty } = await exportJWK(ephemeralKey); + const sharedSecret = await deriveKey(key, ephemeralKey, alg2 === "ECDH-ES" ? enc2 : alg2, alg2 === "ECDH-ES" ? cekLength(enc2) : parseInt(alg2.slice(-5, -2), 10), apu, apv); + parameters = { epk: { x, crv, kty } }; + if (kty === "EC") + parameters.epk.y = y; + if (apu) + parameters.apu = encode4(apu); + if (apv) + parameters.apv = encode4(apv); + if (alg2 === "ECDH-ES") { + cek = sharedSecret; + break; + } + cek = providedCek || generateCek(enc2); + const kwAlg = alg2.slice(-6); + encryptedKey = await wrap(kwAlg, sharedSecret, cek); + break; + } + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + cek = providedCek || generateCek(enc2); + assertCryptoKey(key); + encryptedKey = await encrypt2(alg2, key, cek); + break; + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": { + cek = providedCek || generateCek(enc2); + const { p2c, p2s } = providedParameters; + ({ encryptedKey, ...parameters } = await wrap2(alg2, key, cek, p2c, p2s)); + break; + } + case "A128KW": + case "A192KW": + case "A256KW": { + cek = providedCek || generateCek(enc2); + encryptedKey = await wrap(alg2, key, cek); + break; + } + case "A128GCMKW": + case "A192GCMKW": + case "A256GCMKW": { + cek = providedCek || generateCek(enc2); + const { iv } = providedParameters; + ({ encryptedKey, ...parameters } = await wrap3(alg2, key, cek, iv)); + break; + } + default: { + throw new JOSENotSupported(unsupportedAlgHeader); + } + } + return { cek, encryptedKey, parameters }; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) { + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + } + if (!protectedHeader || protectedHeader.crit === void 0) { + return /* @__PURE__ */ new Set(); + } + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + } + let recognized; + if (recognizedOption !== void 0) { + recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + } else { + recognized = recognizedDefault; + } + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) { + throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + } + if (joseHeader[parameter] === void 0) { + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + } + if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + } + return new Set(protectedHeader.crit); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js +function validateAlgorithms(option, algorithms) { + if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) { + throw new TypeError(`"${option}" option must be an array of strings`); + } + if (!algorithms) { + return void 0; + } + return new Set(algorithms); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js +var tag = (key) => key?.[Symbol.toStringTag]; +var jwkMatchesOp = (alg2, key, usage) => { + if (key.use !== void 0) { + let expected; + switch (usage) { + case "sign": + case "verify": + expected = "sig"; + break; + case "encrypt": + case "decrypt": + expected = "enc"; + break; + } + if (key.use !== expected) { + throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); + } + } + if (key.alg !== void 0 && key.alg !== alg2) { + throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg2}" when present`); + } + if (Array.isArray(key.key_ops)) { + let expectedKeyOp; + switch (true) { + case (usage === "sign" || usage === "verify"): + case alg2 === "dir": + case alg2.includes("CBC-HS"): + expectedKeyOp = usage; + break; + case alg2.startsWith("PBES2"): + expectedKeyOp = "deriveBits"; + break; + case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg2): + if (!alg2.includes("GCM") && alg2.endsWith("KW")) { + expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; + } else { + expectedKeyOp = usage; + } + break; + case (usage === "encrypt" && alg2.startsWith("RSA")): + expectedKeyOp = "wrapKey"; + break; + case usage === "decrypt": + expectedKeyOp = alg2.startsWith("RSA") ? "unwrapKey" : "deriveBits"; + break; + } + if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) { + throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); + } + } + return true; +}; +var symmetricTypeCheck = (alg2, key, usage) => { + if (key instanceof Uint8Array) + return; + if (isJWK(key)) { + if (isSecretJWK(key) && jwkMatchesOp(alg2, key, usage)) + return; + throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); + } + if (!isKeyLike(key)) { + throw new TypeError(withAlg(alg2, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); + } + if (key.type !== "secret") { + throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); + } +}; +var asymmetricTypeCheck = (alg2, key, usage) => { + if (isJWK(key)) { + switch (usage) { + case "decrypt": + case "sign": + if (isPrivateJWK(key) && jwkMatchesOp(alg2, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation must be a private JWK`); + case "encrypt": + case "verify": + if (isPublicJWK(key) && jwkMatchesOp(alg2, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation must be a public JWK`); + } + } + if (!isKeyLike(key)) { + throw new TypeError(withAlg(alg2, key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + if (key.type === "secret") { + throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); + } + if (key.type === "public") { + switch (usage) { + case "sign": + throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); + case "decrypt": + throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); + } + } + if (key.type === "private") { + switch (usage) { + case "verify": + throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); + case "encrypt": + throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); + } + } +}; +function checkKeyType(alg2, key, usage) { + switch (alg2.substring(0, 2)) { + case "A1": + case "A2": + case "di": + case "HS": + case "PB": + symmetricTypeCheck(alg2, key, usage); + break; + default: + asymmetricTypeCheck(alg2, key, usage); + } +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js +function supported(name) { + if (typeof globalThis[name] === "undefined") { + throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`); + } +} +async function compress(input) { + supported("CompressionStream"); + const cs = new CompressionStream("deflate-raw"); + const writer = cs.writable.getWriter(); + writer.write(input).catch(() => { + }); + writer.close().catch(() => { + }); + const chunks = []; + const reader = cs.readable.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) + break; + chunks.push(value); + } + return concat(...chunks); +} +async function decompress(input, maxLength) { + supported("DecompressionStream"); + const ds = new DecompressionStream("deflate-raw"); + const writer = ds.writable.getWriter(); + writer.write(input).catch(() => { + }); + writer.close().catch(() => { + }); + const chunks = []; + let length = 0; + const reader = ds.readable.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) + break; + chunks.push(value); + length += value.byteLength; + if (maxLength !== Infinity && length > maxLength) { + throw new JWEInvalid("Decompressed plaintext exceeded the configured limit"); + } + } + return concat(...chunks); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js +async function flattenedDecrypt(jwe, key, options) { + if (!isObject3(jwe)) { + throw new JWEInvalid("Flattened JWE must be an object"); + } + if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { + throw new JWEInvalid("JOSE Header missing"); + } + if (jwe.iv !== void 0 && typeof jwe.iv !== "string") { + throw new JWEInvalid("JWE Initialization Vector incorrect type"); + } + if (typeof jwe.ciphertext !== "string") { + throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); + } + if (jwe.tag !== void 0 && typeof jwe.tag !== "string") { + throw new JWEInvalid("JWE Authentication Tag incorrect type"); + } + if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { + throw new JWEInvalid("JWE Protected Header incorrect type"); + } + if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { + throw new JWEInvalid("JWE Encrypted Key incorrect type"); + } + if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { + throw new JWEInvalid("JWE AAD incorrect type"); + } + if (jwe.header !== void 0 && !isObject3(jwe.header)) { + throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); + } + if (jwe.unprotected !== void 0 && !isObject3(jwe.unprotected)) { + throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); + } + let parsedProt; + if (jwe.protected) { + try { + const protectedHeader2 = decode3(jwe.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader2)); + } catch { + throw new JWEInvalid("JWE Protected Header is invalid"); + } + } + if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { + throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...parsedProt, + ...jwe.header, + ...jwe.unprotected + }; + validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader); + if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); + } + if (joseHeader.zip !== void 0 && !parsedProt?.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); + } + const { alg: alg2, enc: enc2 } = joseHeader; + if (typeof alg2 !== "string" || !alg2) { + throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); + } + if (typeof enc2 !== "string" || !enc2) { + throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); + } + const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms); + const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); + if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg2) || !keyManagementAlgorithms && alg2.startsWith("PBES2")) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc2)) { + throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); + } + let encryptedKey; + if (jwe.encrypted_key !== void 0) { + encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid); + } + let resolvedKey = false; + if (typeof key === "function") { + key = await key(parsedProt, jwe); + resolvedKey = true; + } + checkKeyType(alg2 === "dir" ? enc2 : alg2, key, "decrypt"); + const k = await normalizeKey(key, alg2); + let cek; + try { + cek = await decryptKeyManagement(alg2, k, encryptedKey, joseHeader, options); + } catch (err) { + if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { + throw err; + } + cek = generateCek(enc2); + } + let iv; + let tag2; + if (jwe.iv !== void 0) { + iv = decodeBase64url(jwe.iv, "iv", JWEInvalid); + } + if (jwe.tag !== void 0) { + tag2 = decodeBase64url(jwe.tag, "tag", JWEInvalid); + } + const protectedHeader = jwe.protected !== void 0 ? encode3(jwe.protected) : new Uint8Array(); + let additionalData; + if (jwe.aad !== void 0) { + additionalData = concat(protectedHeader, encode3("."), encode3(jwe.aad)); + } else { + additionalData = protectedHeader; + } + const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid); + const plaintext = await decrypt(enc2, cek, ciphertext, iv, tag2, additionalData); + const result = { plaintext }; + if (joseHeader.zip === "DEF") { + const maxDecompressedLength = options?.maxDecompressedLength ?? 25e4; + if (maxDecompressedLength === 0) { + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) { + throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity"); + } + result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => { + if (cause instanceof JWEInvalid) + throw cause; + throw new JWEInvalid("Failed to decompress plaintext", { cause }); + }); + } + if (jwe.protected !== void 0) { + result.protectedHeader = parsedProt; + } + if (jwe.aad !== void 0) { + result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid); + } + if (jwe.unprotected !== void 0) { + result.sharedUnprotectedHeader = jwe.unprotected; + } + if (jwe.header !== void 0) { + result.unprotectedHeader = jwe.header; + } + if (resolvedKey) { + return { ...result, key: k }; + } + return result; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js +async function compactDecrypt(jwe, key, options) { + if (jwe instanceof Uint8Array) { + jwe = decoder.decode(jwe); + } + if (typeof jwe !== "string") { + throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); + } + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split("."); + if (length !== 5) { + throw new JWEInvalid("Invalid Compact JWE"); + } + const decrypted = await flattenedDecrypt({ + ciphertext, + iv: iv || void 0, + protected: protectedHeader, + tag: tag2 || void 0, + encrypted_key: encryptedKey || void 0 + }, key, options); + const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: decrypted.key }; + } + return result; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js +var _plaintext, _protectedHeader, _sharedUnprotectedHeader, _unprotectedHeader, _aad, _cek, _iv, _keyManagementParameters; +var FlattenedEncrypt = class { + constructor(plaintext) { + __privateAdd(this, _plaintext); + __privateAdd(this, _protectedHeader); + __privateAdd(this, _sharedUnprotectedHeader); + __privateAdd(this, _unprotectedHeader); + __privateAdd(this, _aad); + __privateAdd(this, _cek); + __privateAdd(this, _iv); + __privateAdd(this, _keyManagementParameters); + if (!(plaintext instanceof Uint8Array)) { + throw new TypeError("plaintext must be an instance of Uint8Array"); + } + __privateSet(this, _plaintext, plaintext); + } + setKeyManagementParameters(parameters) { + assertNotSet(__privateGet(this, _keyManagementParameters), "setKeyManagementParameters"); + __privateSet(this, _keyManagementParameters, parameters); + return this; + } + setProtectedHeader(protectedHeader) { + assertNotSet(__privateGet(this, _protectedHeader), "setProtectedHeader"); + __privateSet(this, _protectedHeader, protectedHeader); + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + assertNotSet(__privateGet(this, _sharedUnprotectedHeader), "setSharedUnprotectedHeader"); + __privateSet(this, _sharedUnprotectedHeader, sharedUnprotectedHeader); + return this; + } + setUnprotectedHeader(unprotectedHeader) { + assertNotSet(__privateGet(this, _unprotectedHeader), "setUnprotectedHeader"); + __privateSet(this, _unprotectedHeader, unprotectedHeader); + return this; + } + setAdditionalAuthenticatedData(aad) { + __privateSet(this, _aad, aad); + return this; + } + setContentEncryptionKey(cek) { + assertNotSet(__privateGet(this, _cek), "setContentEncryptionKey"); + __privateSet(this, _cek, cek); + return this; + } + setInitializationVector(iv) { + assertNotSet(__privateGet(this, _iv), "setInitializationVector"); + __privateSet(this, _iv, iv); + return this; + } + async encrypt(key, options) { + if (!__privateGet(this, _protectedHeader) && !__privateGet(this, _unprotectedHeader) && !__privateGet(this, _sharedUnprotectedHeader)) { + throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); + } + if (!isDisjoint(__privateGet(this, _protectedHeader), __privateGet(this, _unprotectedHeader), __privateGet(this, _sharedUnprotectedHeader))) { + throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); + } + const joseHeader = { + ...__privateGet(this, _protectedHeader), + ...__privateGet(this, _unprotectedHeader), + ...__privateGet(this, _sharedUnprotectedHeader) + }; + validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, __privateGet(this, _protectedHeader), joseHeader); + if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); + } + if (joseHeader.zip !== void 0 && !__privateGet(this, _protectedHeader)?.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); + } + const { alg: alg2, enc: enc2 } = joseHeader; + if (typeof alg2 !== "string" || !alg2) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (typeof enc2 !== "string" || !enc2) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + let encryptedKey; + if (__privateGet(this, _cek) && (alg2 === "dir" || alg2 === "ECDH-ES")) { + throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg2}`); + } + checkKeyType(alg2 === "dir" ? enc2 : alg2, key, "encrypt"); + let cek; + { + let parameters; + const k = await normalizeKey(key, alg2); + ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg2, enc2, k, __privateGet(this, _cek), __privateGet(this, _keyManagementParameters))); + if (parameters) { + if (options && unprotected in options) { + if (!__privateGet(this, _unprotectedHeader)) { + this.setUnprotectedHeader(parameters); + } else { + __privateSet(this, _unprotectedHeader, { ...__privateGet(this, _unprotectedHeader), ...parameters }); + } + } else if (!__privateGet(this, _protectedHeader)) { + this.setProtectedHeader(parameters); + } else { + __privateSet(this, _protectedHeader, { ...__privateGet(this, _protectedHeader), ...parameters }); + } + } + } + let additionalData; + let protectedHeaderS; + let protectedHeaderB; + let aadMember; + if (__privateGet(this, _protectedHeader)) { + protectedHeaderS = encode4(JSON.stringify(__privateGet(this, _protectedHeader))); + protectedHeaderB = encode3(protectedHeaderS); + } else { + protectedHeaderS = ""; + protectedHeaderB = new Uint8Array(); + } + if (__privateGet(this, _aad)) { + aadMember = encode4(__privateGet(this, _aad)); + const aadMemberBytes = encode3(aadMember); + additionalData = concat(protectedHeaderB, encode3("."), aadMemberBytes); + } else { + additionalData = protectedHeaderB; + } + let plaintext = __privateGet(this, _plaintext); + if (joseHeader.zip === "DEF") { + plaintext = await compress(plaintext).catch((cause) => { + throw new JWEInvalid("Failed to compress plaintext", { cause }); + }); + } + const { ciphertext, tag: tag2, iv } = await encrypt(enc2, plaintext, cek, __privateGet(this, _iv), additionalData); + const jwe = { + ciphertext: encode4(ciphertext) + }; + if (iv) { + jwe.iv = encode4(iv); + } + if (tag2) { + jwe.tag = encode4(tag2); + } + if (encryptedKey) { + jwe.encrypted_key = encode4(encryptedKey); + } + if (aadMember) { + jwe.aad = aadMember; + } + if (__privateGet(this, _protectedHeader)) { + jwe.protected = protectedHeaderS; + } + if (__privateGet(this, _sharedUnprotectedHeader)) { + jwe.unprotected = __privateGet(this, _sharedUnprotectedHeader); + } + if (__privateGet(this, _unprotectedHeader)) { + jwe.header = __privateGet(this, _unprotectedHeader); + } + return jwe; + } +}; +_plaintext = new WeakMap(); +_protectedHeader = new WeakMap(); +_sharedUnprotectedHeader = new WeakMap(); +_unprotectedHeader = new WeakMap(); +_aad = new WeakMap(); +_cek = new WeakMap(); +_iv = new WeakMap(); +_keyManagementParameters = new WeakMap(); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js +async function flattenedVerify(jws, key, options) { + if (!isObject3(jws)) { + throw new JWSInvalid("Flattened JWS must be an object"); + } + if (jws.protected === void 0 && jws.header === void 0) { + throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); + } + if (jws.protected !== void 0 && typeof jws.protected !== "string") { + throw new JWSInvalid("JWS Protected Header incorrect type"); + } + if (jws.payload === void 0) { + throw new JWSInvalid("JWS Payload missing"); + } + if (typeof jws.signature !== "string") { + throw new JWSInvalid("JWS Signature missing or incorrect type"); + } + if (jws.header !== void 0 && !isObject3(jws.header)) { + throw new JWSInvalid("JWS Unprotected Header incorrect type"); + } + let parsedProt = {}; + if (jws.protected) { + try { + const protectedHeader = decode3(jws.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } catch { + throw new JWSInvalid("JWS Protected Header is invalid"); + } + } + if (!isDisjoint(parsedProt, jws.header)) { + throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...parsedProt, + ...jws.header + }; + const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has("b64")) { + b64 = parsedProt.b64; + if (typeof b64 !== "boolean") { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg: alg2 } = joseHeader; + if (typeof alg2 !== "string" || !alg2) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + const algorithms = options && validateAlgorithms("algorithms", options.algorithms); + if (algorithms && !algorithms.has(alg2)) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (b64) { + if (typeof jws.payload !== "string") { + throw new JWSInvalid("JWS Payload must be a string"); + } + } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { + throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); + } + let resolvedKey = false; + if (typeof key === "function") { + key = await key(parsedProt, jws); + resolvedKey = true; + } + checkKeyType(alg2, key, "verify"); + const data = concat(jws.protected !== void 0 ? encode3(jws.protected) : new Uint8Array(), encode3("."), typeof jws.payload === "string" ? b64 ? encode3(jws.payload) : encoder.encode(jws.payload) : jws.payload); + const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); + const k = await normalizeKey(key, alg2); + const verified = await verify(alg2, k, signature, data); + if (!verified) { + throw new JWSSignatureVerificationFailed(); + } + let payload; + if (b64) { + payload = decodeBase64url(jws.payload, "payload", JWSInvalid); + } else if (typeof jws.payload === "string") { + payload = encoder.encode(jws.payload); + } else { + payload = jws.payload; + } + const result = { payload }; + if (jws.protected !== void 0) { + result.protectedHeader = parsedProt; + } + if (jws.header !== void 0) { + result.unprotectedHeader = jws.header; + } + if (resolvedKey) { + return { ...result, key: k }; + } + return result; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js +async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) { + jws = decoder.decode(jws); + } + if (typeof jws !== "string") { + throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); + } + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); + if (length !== 3) { + throw new JWSInvalid("Invalid Compact JWS"); + } + const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); + const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: verified.key }; + } + return result; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +var epoch = (date5) => Math.floor(date5.getTime() / 1e3); +var minute = 60; +var hour = minute * 60; +var day = hour * 24; +var week = day * 7; +var year = day * 365.25; +var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; +function secs(str) { + const matched = REGEX.exec(str); + if (!matched || matched[4] && matched[1]) { + throw new TypeError("Invalid time period format"); + } + const value = parseFloat(matched[2]); + const unit = matched[3].toLowerCase(); + let numericDate; + switch (unit) { + case "sec": + case "secs": + case "second": + case "seconds": + case "s": + numericDate = Math.round(value); + break; + case "minute": + case "minutes": + case "min": + case "mins": + case "m": + numericDate = Math.round(value * minute); + break; + case "hour": + case "hours": + case "hr": + case "hrs": + case "h": + numericDate = Math.round(value * hour); + break; + case "day": + case "days": + case "d": + numericDate = Math.round(value * day); + break; + case "week": + case "weeks": + case "w": + numericDate = Math.round(value * week); + break; + default: + numericDate = Math.round(value * year); + break; + } + if (matched[1] === "-" || matched[4] === "ago") { + return -numericDate; + } + return numericDate; +} +function validateInput(label, input) { + if (!Number.isFinite(input)) { + throw new TypeError(`Invalid ${label} input`); + } + return input; +} +var normalizeTyp = (value) => { + if (value.includes("/")) { + return value.toLowerCase(); + } + return `application/${value.toLowerCase()}`; +}; +var checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === "string") { + return audOption.includes(audPayload); + } + if (Array.isArray(audPayload)) { + return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + } + return false; +}; +function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { + let payload; + try { + payload = JSON.parse(decoder.decode(encodedPayload)); + } catch { + } + if (!isObject3(payload)) { + throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); + } + const { typ } = options; + if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { + throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed"); + } + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + const presenceCheck = [...requiredClaims]; + if (maxTokenAge !== void 0) + presenceCheck.push("iat"); + if (audience !== void 0) + presenceCheck.push("aud"); + if (subject !== void 0) + presenceCheck.push("sub"); + if (issuer !== void 0) + presenceCheck.push("iss"); + for (const claim of new Set(presenceCheck.reverse())) { + if (!(claim in payload)) { + throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + } + } + if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { + throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed"); + } + if (subject && payload.sub !== subject) { + throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed"); + } + if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { + throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed"); + } + let tolerance; + switch (typeof options.clockTolerance) { + case "string": + tolerance = secs(options.clockTolerance); + break; + case "number": + tolerance = options.clockTolerance; + break; + case "undefined": + tolerance = 0; + break; + default: + throw new TypeError("Invalid clockTolerance option type"); + } + const { currentDate } = options; + const now2 = epoch(currentDate || /* @__PURE__ */ new Date()); + if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") { + throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid"); + } + if (payload.nbf !== void 0) { + if (typeof payload.nbf !== "number") { + throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid"); + } + if (payload.nbf > now2 + tolerance) { + throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed"); + } + } + if (payload.exp !== void 0) { + if (typeof payload.exp !== "number") { + throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid"); + } + if (payload.exp <= now2 - tolerance) { + throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed"); + } + } + if (maxTokenAge) { + const age = now2 - payload.iat; + const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); + if (age - tolerance > max) { + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed"); + } + if (age < 0 - tolerance) { + throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed"); + } + } + return payload; +} +var _payload; +var JWTClaimsBuilder = class { + constructor(payload) { + __privateAdd(this, _payload); + if (!isObject3(payload)) { + throw new TypeError("JWT Claims Set MUST be an object"); + } + __privateSet(this, _payload, structuredClone(payload)); + } + data() { + return encoder.encode(JSON.stringify(__privateGet(this, _payload))); + } + get iss() { + return __privateGet(this, _payload).iss; + } + set iss(value) { + __privateGet(this, _payload).iss = value; + } + get sub() { + return __privateGet(this, _payload).sub; + } + set sub(value) { + __privateGet(this, _payload).sub = value; + } + get aud() { + return __privateGet(this, _payload).aud; + } + set aud(value) { + __privateGet(this, _payload).aud = value; + } + set jti(value) { + __privateGet(this, _payload).jti = value; + } + set nbf(value) { + if (typeof value === "number") { + __privateGet(this, _payload).nbf = validateInput("setNotBefore", value); + } else if (value instanceof Date) { + __privateGet(this, _payload).nbf = validateInput("setNotBefore", epoch(value)); + } else { + __privateGet(this, _payload).nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); + } + } + set exp(value) { + if (typeof value === "number") { + __privateGet(this, _payload).exp = validateInput("setExpirationTime", value); + } else if (value instanceof Date) { + __privateGet(this, _payload).exp = validateInput("setExpirationTime", epoch(value)); + } else { + __privateGet(this, _payload).exp = epoch(/* @__PURE__ */ new Date()) + secs(value); + } + } + set iat(value) { + if (value === void 0) { + __privateGet(this, _payload).iat = epoch(/* @__PURE__ */ new Date()); + } else if (value instanceof Date) { + __privateGet(this, _payload).iat = validateInput("setIssuedAt", epoch(value)); + } else if (typeof value === "string") { + __privateGet(this, _payload).iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); + } else { + __privateGet(this, _payload).iat = validateInput("setIssuedAt", value); + } + } +}; +_payload = new WeakMap(); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js +async function jwtVerify(jwt2, key, options) { + const verified = await compactVerify(jwt2, key, options); + if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { + throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); + } + const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options); + const result = { payload, protectedHeader: verified.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: verified.key }; + } + return result; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js +async function jwtDecrypt(jwt2, key, options) { + const decrypted = await compactDecrypt(jwt2, key, options); + const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options); + const { protectedHeader } = decrypted; + if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) { + throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch"); + } + if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) { + throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch"); + } + if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { + throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch"); + } + const result = { payload, protectedHeader }; + if (typeof key === "function") { + return { ...result, key: decrypted.key }; + } + return result; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js +var _flattened; +var CompactEncrypt = class { + constructor(plaintext) { + __privateAdd(this, _flattened); + __privateSet(this, _flattened, new FlattenedEncrypt(plaintext)); + } + setContentEncryptionKey(cek) { + __privateGet(this, _flattened).setContentEncryptionKey(cek); + return this; + } + setInitializationVector(iv) { + __privateGet(this, _flattened).setInitializationVector(iv); + return this; + } + setProtectedHeader(protectedHeader) { + __privateGet(this, _flattened).setProtectedHeader(protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + __privateGet(this, _flattened).setKeyManagementParameters(parameters); + return this; + } + async encrypt(key, options) { + const jwe = await __privateGet(this, _flattened).encrypt(key, options); + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); + } +}; +_flattened = new WeakMap(); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js +var _payload2, _protectedHeader2, _unprotectedHeader2; +var FlattenedSign = class { + constructor(payload) { + __privateAdd(this, _payload2); + __privateAdd(this, _protectedHeader2); + __privateAdd(this, _unprotectedHeader2); + if (!(payload instanceof Uint8Array)) { + throw new TypeError("payload must be an instance of Uint8Array"); + } + __privateSet(this, _payload2, payload); + } + setProtectedHeader(protectedHeader) { + assertNotSet(__privateGet(this, _protectedHeader2), "setProtectedHeader"); + __privateSet(this, _protectedHeader2, protectedHeader); + return this; + } + setUnprotectedHeader(unprotectedHeader) { + assertNotSet(__privateGet(this, _unprotectedHeader2), "setUnprotectedHeader"); + __privateSet(this, _unprotectedHeader2, unprotectedHeader); + return this; + } + async sign(key, options) { + if (!__privateGet(this, _protectedHeader2) && !__privateGet(this, _unprotectedHeader2)) { + throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); + } + if (!isDisjoint(__privateGet(this, _protectedHeader2), __privateGet(this, _unprotectedHeader2))) { + throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...__privateGet(this, _protectedHeader2), + ...__privateGet(this, _unprotectedHeader2) + }; + const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, __privateGet(this, _protectedHeader2), joseHeader); + let b64 = true; + if (extensions.has("b64")) { + b64 = __privateGet(this, _protectedHeader2).b64; + if (typeof b64 !== "boolean") { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg: alg2 } = joseHeader; + if (typeof alg2 !== "string" || !alg2) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + checkKeyType(alg2, key, "sign"); + let payloadS; + let payloadB; + if (b64) { + payloadS = encode4(__privateGet(this, _payload2)); + payloadB = encode3(payloadS); + } else { + payloadB = __privateGet(this, _payload2); + payloadS = ""; + } + let protectedHeaderString; + let protectedHeaderBytes; + if (__privateGet(this, _protectedHeader2)) { + protectedHeaderString = encode4(JSON.stringify(__privateGet(this, _protectedHeader2))); + protectedHeaderBytes = encode3(protectedHeaderString); + } else { + protectedHeaderString = ""; + protectedHeaderBytes = new Uint8Array(); + } + const data = concat(protectedHeaderBytes, encode3("."), payloadB); + const k = await normalizeKey(key, alg2); + const signature = await sign(alg2, k, data); + const jws = { + signature: encode4(signature), + payload: payloadS + }; + if (__privateGet(this, _unprotectedHeader2)) { + jws.header = __privateGet(this, _unprotectedHeader2); + } + if (__privateGet(this, _protectedHeader2)) { + jws.protected = protectedHeaderString; + } + return jws; + } +}; +_payload2 = new WeakMap(); +_protectedHeader2 = new WeakMap(); +_unprotectedHeader2 = new WeakMap(); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js +var _flattened2; +var CompactSign = class { + constructor(payload) { + __privateAdd(this, _flattened2); + __privateSet(this, _flattened2, new FlattenedSign(payload)); + } + setProtectedHeader(protectedHeader) { + __privateGet(this, _flattened2).setProtectedHeader(protectedHeader); + return this; + } + async sign(key, options) { + const jws = await __privateGet(this, _flattened2).sign(key, options); + if (jws.payload === void 0) { + throw new TypeError("use the flattened module for creating JWS with b64: false"); + } + return `${jws.protected}.${jws.payload}.${jws.signature}`; + } +}; +_flattened2 = new WeakMap(); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js +var _protectedHeader3, _jwt2; +var SignJWT = class { + constructor(payload = {}) { + __privateAdd(this, _protectedHeader3); + __privateAdd(this, _jwt2); + __privateSet(this, _jwt2, new JWTClaimsBuilder(payload)); + } + setIssuer(issuer) { + __privateGet(this, _jwt2).iss = issuer; + return this; + } + setSubject(subject) { + __privateGet(this, _jwt2).sub = subject; + return this; + } + setAudience(audience) { + __privateGet(this, _jwt2).aud = audience; + return this; + } + setJti(jwtId) { + __privateGet(this, _jwt2).jti = jwtId; + return this; + } + setNotBefore(input) { + __privateGet(this, _jwt2).nbf = input; + return this; + } + setExpirationTime(input) { + __privateGet(this, _jwt2).exp = input; + return this; + } + setIssuedAt(input) { + __privateGet(this, _jwt2).iat = input; + return this; + } + setProtectedHeader(protectedHeader) { + __privateSet(this, _protectedHeader3, protectedHeader); + return this; + } + async sign(key, options) { + const sig = new CompactSign(__privateGet(this, _jwt2).data()); + sig.setProtectedHeader(__privateGet(this, _protectedHeader3)); + if (Array.isArray(__privateGet(this, _protectedHeader3)?.crit) && __privateGet(this, _protectedHeader3).crit.includes("b64") && __privateGet(this, _protectedHeader3).b64 === false) { + throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); + } + return sig.sign(key, options); + } +}; +_protectedHeader3 = new WeakMap(); +_jwt2 = new WeakMap(); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js +var _cek2, _iv2, _keyManagementParameters2, _protectedHeader4, _replicateIssuerAsHeader, _replicateSubjectAsHeader, _replicateAudienceAsHeader, _jwt3; +var EncryptJWT = class { + constructor(payload = {}) { + __privateAdd(this, _cek2); + __privateAdd(this, _iv2); + __privateAdd(this, _keyManagementParameters2); + __privateAdd(this, _protectedHeader4); + __privateAdd(this, _replicateIssuerAsHeader); + __privateAdd(this, _replicateSubjectAsHeader); + __privateAdd(this, _replicateAudienceAsHeader); + __privateAdd(this, _jwt3); + __privateSet(this, _jwt3, new JWTClaimsBuilder(payload)); + } + setIssuer(issuer) { + __privateGet(this, _jwt3).iss = issuer; + return this; + } + setSubject(subject) { + __privateGet(this, _jwt3).sub = subject; + return this; + } + setAudience(audience) { + __privateGet(this, _jwt3).aud = audience; + return this; + } + setJti(jwtId) { + __privateGet(this, _jwt3).jti = jwtId; + return this; + } + setNotBefore(input) { + __privateGet(this, _jwt3).nbf = input; + return this; + } + setExpirationTime(input) { + __privateGet(this, _jwt3).exp = input; + return this; + } + setIssuedAt(input) { + __privateGet(this, _jwt3).iat = input; + return this; + } + setProtectedHeader(protectedHeader) { + assertNotSet(__privateGet(this, _protectedHeader4), "setProtectedHeader"); + __privateSet(this, _protectedHeader4, protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + assertNotSet(__privateGet(this, _keyManagementParameters2), "setKeyManagementParameters"); + __privateSet(this, _keyManagementParameters2, parameters); + return this; + } + setContentEncryptionKey(cek) { + assertNotSet(__privateGet(this, _cek2), "setContentEncryptionKey"); + __privateSet(this, _cek2, cek); + return this; + } + setInitializationVector(iv) { + assertNotSet(__privateGet(this, _iv2), "setInitializationVector"); + __privateSet(this, _iv2, iv); + return this; + } + replicateIssuerAsHeader() { + __privateSet(this, _replicateIssuerAsHeader, true); + return this; + } + replicateSubjectAsHeader() { + __privateSet(this, _replicateSubjectAsHeader, true); + return this; + } + replicateAudienceAsHeader() { + __privateSet(this, _replicateAudienceAsHeader, true); + return this; + } + async encrypt(key, options) { + const enc2 = new CompactEncrypt(__privateGet(this, _jwt3).data()); + if (__privateGet(this, _protectedHeader4) && (__privateGet(this, _replicateIssuerAsHeader) || __privateGet(this, _replicateSubjectAsHeader) || __privateGet(this, _replicateAudienceAsHeader))) { + __privateSet(this, _protectedHeader4, { + ...__privateGet(this, _protectedHeader4), + iss: __privateGet(this, _replicateIssuerAsHeader) ? __privateGet(this, _jwt3).iss : void 0, + sub: __privateGet(this, _replicateSubjectAsHeader) ? __privateGet(this, _jwt3).sub : void 0, + aud: __privateGet(this, _replicateAudienceAsHeader) ? __privateGet(this, _jwt3).aud : void 0 + }); + } + enc2.setProtectedHeader(__privateGet(this, _protectedHeader4)); + if (__privateGet(this, _iv2)) { + enc2.setInitializationVector(__privateGet(this, _iv2)); + } + if (__privateGet(this, _cek2)) { + enc2.setContentEncryptionKey(__privateGet(this, _cek2)); + } + if (__privateGet(this, _keyManagementParameters2)) { + enc2.setKeyManagementParameters(__privateGet(this, _keyManagementParameters2)); + } + return enc2.encrypt(key, options); + } +}; +_cek2 = new WeakMap(); +_iv2 = new WeakMap(); +_keyManagementParameters2 = new WeakMap(); +_protectedHeader4 = new WeakMap(); +_replicateIssuerAsHeader = new WeakMap(); +_replicateSubjectAsHeader = new WeakMap(); +_replicateAudienceAsHeader = new WeakMap(); +_jwt3 = new WeakMap(); + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js +var check2 = (value, description) => { + if (typeof value !== "string" || !value) { + throw new JWKInvalid(`${description} missing or invalid`); + } +}; +async function calculateJwkThumbprint(key, digestAlgorithm) { + let jwk; + if (isJWK(key)) { + jwk = key; + } else if (isKeyLike(key)) { + jwk = await exportJWK(key); + } else { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + digestAlgorithm ?? (digestAlgorithm = "sha256"); + if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { + throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); + } + let components; + switch (jwk.kty) { + case "AKP": + check2(jwk.alg, '"alg" (Algorithm) Parameter'); + check2(jwk.pub, '"pub" (Public key) Parameter'); + components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub }; + break; + case "EC": + check2(jwk.crv, '"crv" (Curve) Parameter'); + check2(jwk.x, '"x" (X Coordinate) Parameter'); + check2(jwk.y, '"y" (Y Coordinate) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; + break; + case "OKP": + check2(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); + check2(jwk.x, '"x" (Public Key) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; + break; + case "RSA": + check2(jwk.e, '"e" (Exponent) Parameter'); + check2(jwk.n, '"n" (Modulus) Parameter'); + components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; + break; + case "oct": + check2(jwk.k, '"k" (Key Value) Parameter'); + components = { k: jwk.k, kty: jwk.kty }; + break; + default: + throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); + } + const data = encode3(JSON.stringify(components)); + return encode4(await digest(digestAlgorithm, data)); +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js +function getKtyFromAlg(alg2) { + switch (typeof alg2 === "string" && alg2.slice(0, 2)) { + case "RS": + case "PS": + return "RSA"; + case "ES": + return "EC"; + case "Ed": + return "OKP"; + case "ML": + return "AKP"; + default: + throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); + } +} +function isJWKSLike(jwks) { + return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); +} +function isJWKLike(key) { + return isObject3(key); +} +var _jwks, _cached; +var LocalJWKSet = class { + constructor(jwks) { + __privateAdd(this, _jwks); + __privateAdd(this, _cached, /* @__PURE__ */ new WeakMap()); + if (!isJWKSLike(jwks)) { + throw new JWKSInvalid("JSON Web Key Set malformed"); + } + __privateSet(this, _jwks, structuredClone(jwks)); + } + jwks() { + return __privateGet(this, _jwks); + } + async getKey(protectedHeader, token) { + const { alg: alg2, kid } = { ...protectedHeader, ...token?.header }; + const kty = getKtyFromAlg(alg2); + const candidates = __privateGet(this, _jwks).keys.filter((jwk2) => { + let candidate = kty === jwk2.kty; + if (candidate && typeof kid === "string") { + candidate = kid === jwk2.kid; + } + if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) { + candidate = alg2 === jwk2.alg; + } + if (candidate && typeof jwk2.use === "string") { + candidate = jwk2.use === "sig"; + } + if (candidate && Array.isArray(jwk2.key_ops)) { + candidate = jwk2.key_ops.includes("verify"); + } + if (candidate) { + switch (alg2) { + case "ES256": + candidate = jwk2.crv === "P-256"; + break; + case "ES384": + candidate = jwk2.crv === "P-384"; + break; + case "ES512": + candidate = jwk2.crv === "P-521"; + break; + case "Ed25519": + case "EdDSA": + candidate = jwk2.crv === "Ed25519"; + break; + } + } + return candidate; + }); + const { 0: jwk, length } = candidates; + if (length === 0) { + throw new JWKSNoMatchingKey(); + } + if (length !== 1) { + const error49 = new JWKSMultipleMatchingKeys(); + const _cached2 = __privateGet(this, _cached); + error49[Symbol.asyncIterator] = async function* () { + for (const jwk2 of candidates) { + try { + yield await importWithAlgCache(_cached2, jwk2, alg2); + } catch { + } + } + }; + throw error49; + } + return importWithAlgCache(__privateGet(this, _cached), jwk, alg2); + } +}; +_jwks = new WeakMap(); +_cached = new WeakMap(); +async function importWithAlgCache(cache3, jwk, alg2) { + const cached2 = cache3.get(jwk) || cache3.set(jwk, {}).get(jwk); + if (cached2[alg2] === void 0) { + const key = await importJWK({ ...jwk, ext: true }, alg2); + if (key instanceof Uint8Array || key.type !== "public") { + throw new JWKSInvalid("JSON Web Key Set members must be public keys"); + } + cached2[alg2] = key; + } + return cached2[alg2]; +} +function createLocalJWKSet(jwks) { + const set2 = new LocalJWKSet(jwks); + const localJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); + Object.defineProperties(localJWKSet, { + jwks: { + value: () => structuredClone(set2.jwks()), + enumerable: false, + configurable: false, + writable: false + } + }); + return localJWKSet; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js +function isCloudflareWorkers() { + return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; +} +var USER_AGENT; +if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { + const NAME = "jose"; + const VERSION2 = "v6.2.2"; + USER_AGENT = `${NAME}/${VERSION2}`; +} +var customFetch = Symbol(); +async function fetchJwks(url2, headers, signal, fetchImpl = fetch) { + const response = await fetchImpl(url2, { + method: "GET", + signal, + redirect: "manual", + headers + }).catch((err) => { + if (err.name === "TimeoutError") { + throw new JWKSTimeout(); + } + throw err; + }); + if (response.status !== 200) { + throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); + } + try { + return await response.json(); + } catch { + throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); + } +} +var jwksCache = Symbol(); +function isFreshJwksCache(input, cacheMaxAge) { + if (typeof input !== "object" || input === null) { + return false; + } + if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) { + return false; + } + if (!("jwks" in input) || !isObject3(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject3)) { + return false; + } + return true; +} +var _url2, _timeoutDuration, _cooldownDuration, _cacheMaxAge, _jwksTimestamp, _pendingFetch, _headers, _customFetch, _local, _cache; +var RemoteJWKSet = class { + constructor(url2, options) { + __privateAdd(this, _url2); + __privateAdd(this, _timeoutDuration); + __privateAdd(this, _cooldownDuration); + __privateAdd(this, _cacheMaxAge); + __privateAdd(this, _jwksTimestamp); + __privateAdd(this, _pendingFetch); + __privateAdd(this, _headers); + __privateAdd(this, _customFetch); + __privateAdd(this, _local); + __privateAdd(this, _cache); + if (!(url2 instanceof URL)) { + throw new TypeError("url must be an instance of URL"); + } + __privateSet(this, _url2, new URL(url2.href)); + __privateSet(this, _timeoutDuration, typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3); + __privateSet(this, _cooldownDuration, typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4); + __privateSet(this, _cacheMaxAge, typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5); + __privateSet(this, _headers, new Headers(options?.headers)); + if (USER_AGENT && !__privateGet(this, _headers).has("User-Agent")) { + __privateGet(this, _headers).set("User-Agent", USER_AGENT); + } + if (!__privateGet(this, _headers).has("accept")) { + __privateGet(this, _headers).set("accept", "application/json"); + __privateGet(this, _headers).append("accept", "application/jwk-set+json"); + } + __privateSet(this, _customFetch, options?.[customFetch]); + if (options?.[jwksCache] !== void 0) { + __privateSet(this, _cache, options?.[jwksCache]); + if (isFreshJwksCache(options?.[jwksCache], __privateGet(this, _cacheMaxAge))) { + __privateSet(this, _jwksTimestamp, __privateGet(this, _cache).uat); + __privateSet(this, _local, createLocalJWKSet(__privateGet(this, _cache).jwks)); + } + } + } + pendingFetch() { + return !!__privateGet(this, _pendingFetch); + } + coolingDown() { + return typeof __privateGet(this, _jwksTimestamp) === "number" ? Date.now() < __privateGet(this, _jwksTimestamp) + __privateGet(this, _cooldownDuration) : false; + } + fresh() { + return typeof __privateGet(this, _jwksTimestamp) === "number" ? Date.now() < __privateGet(this, _jwksTimestamp) + __privateGet(this, _cacheMaxAge) : false; + } + jwks() { + return __privateGet(this, _local)?.jwks(); + } + async getKey(protectedHeader, token) { + if (!__privateGet(this, _local) || !this.fresh()) { + await this.reload(); + } + try { + return await __privateGet(this, _local).call(this, protectedHeader, token); + } catch (err) { + if (err instanceof JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return __privateGet(this, _local).call(this, protectedHeader, token); + } + } + throw err; + } + } + async reload() { + if (__privateGet(this, _pendingFetch) && isCloudflareWorkers()) { + __privateSet(this, _pendingFetch, void 0); + } + __privateGet(this, _pendingFetch) || __privateSet(this, _pendingFetch, fetchJwks(__privateGet(this, _url2).href, __privateGet(this, _headers), AbortSignal.timeout(__privateGet(this, _timeoutDuration)), __privateGet(this, _customFetch)).then((json2) => { + __privateSet(this, _local, createLocalJWKSet(json2)); + if (__privateGet(this, _cache)) { + __privateGet(this, _cache).uat = Date.now(); + __privateGet(this, _cache).jwks = json2; + } + __privateSet(this, _jwksTimestamp, Date.now()); + __privateSet(this, _pendingFetch, void 0); + }).catch((err) => { + __privateSet(this, _pendingFetch, void 0); + throw err; + })); + await __privateGet(this, _pendingFetch); + } +}; +_url2 = new WeakMap(); +_timeoutDuration = new WeakMap(); +_cooldownDuration = new WeakMap(); +_cacheMaxAge = new WeakMap(); +_jwksTimestamp = new WeakMap(); +_pendingFetch = new WeakMap(); +_headers = new WeakMap(); +_customFetch = new WeakMap(); +_local = new WeakMap(); +_cache = new WeakMap(); +function createRemoteJWKSet(url2, options) { + const set2 = new RemoteJWKSet(url2, options); + const remoteJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); + Object.defineProperties(remoteJWKSet, { + coolingDown: { + get: () => set2.coolingDown(), + enumerable: true, + configurable: false + }, + fresh: { + get: () => set2.fresh(), + enumerable: true, + configurable: false + }, + reload: { + value: () => set2.reload(), + enumerable: true, + configurable: false, + writable: false + }, + reloading: { + get: () => set2.pendingFetch(), + enumerable: true, + configurable: false + }, + jwks: { + value: () => set2.jwks(), + enumerable: true, + configurable: false, + writable: false + } + }); + return remoteJWKSet; +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js +function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === "string") { + const parts = token.split("."); + if (parts.length === 3 || parts.length === 5) { + ; + [protectedB64u] = parts; + } + } else if (typeof token === "object" && token) { + if ("protected" in token) { + protectedB64u = token.protected; + } else { + throw new TypeError("Token does not contain a Protected Header"); + } + } + try { + if (typeof protectedB64u !== "string" || !protectedB64u) { + throw new Error(); + } + const result = JSON.parse(decoder.decode(decode3(protectedB64u))); + if (!isObject3(result)) { + throw new Error(); + } + return result; + } catch { + throw new TypeError("Invalid Token or Protected Header formatting"); + } +} + +// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js +function decodeJwt(jwt2) { + if (typeof jwt2 !== "string") + throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); + const { 1: payload, length } = jwt2.split("."); + if (length === 5) + throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); + if (length !== 3) + throw new JWTInvalid("Invalid JWT"); + if (!payload) + throw new JWTInvalid("JWTs must contain a payload"); + let decoded; + try { + decoded = decode3(payload); + } catch { + throw new JWTInvalid("Failed to base64url decode the payload"); + } + let result; + try { + result = JSON.parse(decoder.decode(decoded)); + } catch { + throw new JWTInvalid("Failed to parse the decoded payload as JSON"); + } + if (!isObject3(result)) + throw new JWTInvalid("Invalid JWT Claims Set"); + return result; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/jwt.mjs +async function signJWT(payload, secret, expiresIn = 3600) { + return await new SignJWT(payload).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret)); +} +async function verifyJWT(token, secret) { + try { + return (await jwtVerify(token, new TextEncoder().encode(secret))).payload; + } catch { + return null; + } +} +var info = new Uint8Array([ + 66, + 101, + 116, + 116, + 101, + 114, + 65, + 117, + 116, + 104, + 46, + 106, + 115, + 32, + 71, + 101, + 110, + 101, + 114, + 97, + 116, + 101, + 100, + 32, + 69, + 110, + 99, + 114, + 121, + 112, + 116, + 105, + 111, + 110, + 32, + 75, + 101, + 121 +]); +var now = () => Date.now() / 1e3 | 0; +var alg = "dir"; +var enc = "A256CBC-HS512"; +function deriveEncryptionSecret(secret, salt) { + return hkdf(sha256, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64); +} +function getCurrentSecret(secret) { + if (typeof secret === "string") return secret; + const value = secret.keys.get(secret.currentVersion); + if (!value) throw new Error(`Secret version ${secret.currentVersion} not found in keys`); + return value; +} +function getAllSecrets(secret) { + if (typeof secret === "string") return [{ + version: 0, + value: secret + }]; + const result = []; + for (const [version3, value] of secret.keys) result.push({ + version: version3, + value + }); + if (secret.legacySecret && !result.some((s) => s.value === secret.legacySecret)) result.push({ + version: -1, + value: secret.legacySecret + }); + return result; +} +async function symmetricEncodeJWT(payload, secret, salt, expiresIn = 3600) { + const encryptionSecret = deriveEncryptionSecret(getCurrentSecret(secret), salt); + const thumbprint = await calculateJwkThumbprint({ + kty: "oct", + k: base64url_exports.encode(encryptionSecret) + }, "sha256"); + return await new EncryptJWT(payload).setProtectedHeader({ + alg, + enc, + kid: thumbprint + }).setIssuedAt().setExpirationTime(now() + expiresIn).setJti(crypto.randomUUID()).encrypt(encryptionSecret); +} +var jwtDecryptOpts = { + clockTolerance: 15, + keyManagementAlgorithms: [alg], + contentEncryptionAlgorithms: [enc, "A256GCM"] +}; +async function symmetricDecodeJWT(token, secret, salt) { + if (!token) return null; + let hasKid = false; + try { + hasKid = decodeProtectedHeader(token).kid !== void 0; + } catch { + return null; + } + try { + const secrets = getAllSecrets(secret); + const { payload } = await jwtDecrypt(token, async (protectedHeader) => { + const kid = protectedHeader.kid; + if (kid !== void 0) { + for (const s of secrets) { + const encryptionSecret = deriveEncryptionSecret(s.value, salt); + if (kid === await calculateJwkThumbprint({ + kty: "oct", + k: base64url_exports.encode(encryptionSecret) + }, "sha256")) return encryptionSecret; + } + throw new Error("no matching decryption secret"); + } + if (secrets.length === 1) return deriveEncryptionSecret(secrets[0].value, salt); + return deriveEncryptionSecret(secrets[0].value, salt); + }, jwtDecryptOpts); + return payload; + } catch { + if (hasKid) return null; + const secrets = getAllSecrets(secret); + if (secrets.length <= 1) return null; + for (let i = 1; i < secrets.length; i++) try { + const s = secrets[i]; + const { payload } = await jwtDecrypt(token, deriveEncryptionSecret(s.value, salt), jwtDecryptOpts); + return payload; + } catch { + continue; + } + return null; + } +} + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/password.node.mjs +import { randomBytes, scrypt } from "node:crypto"; +var config2 = { + N: 16384, + r: 16, + p: 1, + dkLen: 64 +}; +function generateKey(password, salt) { + return new Promise((resolve2, reject) => { + scrypt( + password.normalize("NFKC"), + salt, + config2.dkLen, + { + N: config2.N, + r: config2.r, + p: config2.p, + maxmem: 128 * config2.N * config2.r * 2 + }, + (err, key) => { + if (err) + reject(err); + else + resolve2(key); + } + ); + }); +} +async function hashPassword(password) { + const salt = randomBytes(16).toString("hex"); + const key = await generateKey(password, salt); + return `${salt}:${key.toString("hex")}`; +} +async function verifyPassword(hash2, password) { + const [salt, key] = hash2.split(":"); + if (!salt || !key) { + throw new Error("Invalid password hash"); + } + const targetKey = await generateKey(password, salt); + return targetKey.toString("hex") === key; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/password.mjs +var hashPassword$1 = hashPassword; +var verifyPassword$1 = async ({ hash: hash2, password }) => { + return verifyPassword(hash2, password); +}; + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/base64.mjs +function getAlphabet(urlSafe) { + return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +} +function base64Encode(data, alphabet, padding) { + let result = ""; + let buffer = 0; + let shift = 0; + for (const byte of data) { + buffer = buffer << 8 | byte; + shift += 8; + while (shift >= 6) { + shift -= 6; + result += alphabet[buffer >> shift & 63]; + } + } + if (shift > 0) { + result += alphabet[buffer << 6 - shift & 63]; + } + if (padding) { + const padCount = (4 - result.length % 4) % 4; + result += "=".repeat(padCount); + } + return result; +} +function base64Decode(data, alphabet) { + const decodeMap = /* @__PURE__ */ new Map(); + for (let i = 0; i < alphabet.length; i++) { + decodeMap.set(alphabet[i], i); + } + const result = []; + let buffer = 0; + let bitsCollected = 0; + for (const char of data) { + if (char === "=") + break; + const value = decodeMap.get(char); + if (value === void 0) { + throw new Error(`Invalid Base64 character: ${char}`); + } + buffer = buffer << 6 | value; + bitsCollected += 6; + if (bitsCollected >= 8) { + bitsCollected -= 8; + result.push(buffer >> bitsCollected & 255); + } + } + return Uint8Array.from(result); +} +var base643 = { + encode(data, options = {}) { + const alphabet = getAlphabet(false); + const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data); + return base64Encode(buffer, alphabet, options.padding ?? true); + }, + decode(data) { + if (typeof data !== "string") { + data = new TextDecoder().decode(data); + } + const urlSafe = data.includes("-") || data.includes("_"); + const alphabet = getAlphabet(urlSafe); + return base64Decode(data, alphabet); + } +}; +var base64Url = { + encode(data, options = {}) { + const alphabet = getAlphabet(true); + const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data); + return base64Encode(buffer, alphabet, options.padding ?? true); + }, + decode(data) { + const urlSafe = data.includes("-") || data.includes("_"); + const alphabet = getAlphabet(urlSafe); + return base64Decode(data, alphabet); + } +}; + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/index.mjs +function getWebcryptoSubtle() { + const cr = typeof globalThis !== "undefined" && globalThis.crypto; + if (cr && typeof cr.subtle === "object" && cr.subtle != null) + return cr.subtle; + throw new Error("crypto.subtle must be defined"); +} + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hash.mjs +function createHash(algorithm2, encoding) { + return { + digest: async (input) => { + const encoder3 = new TextEncoder(); + const data = typeof input === "string" ? encoder3.encode(input) : input; + const hashBuffer = await getWebcryptoSubtle().digest(algorithm2, data); + if (encoding === "hex") { + const hashArray = Array.from(new Uint8Array(hashBuffer)); + const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); + return hashHex; + } + if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { + if (encoding.includes("url")) { + return base64Url.encode(hashBuffer, { + padding: encoding !== "base64urlnopad" + }); + } + const hashBase64 = base643.encode(hashBuffer); + return hashBase64; + } + return hashBuffer; + } + }; +} + +// ../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/utils.js +function isBytes2(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; +} +function abool(b) { + if (typeof b !== "boolean") + throw new TypeError(`boolean expected, not ${b}`); +} +function anumber2(n) { + if (typeof n !== "number") + throw new TypeError("number expected, got " + typeof n); + if (!Number.isSafeInteger(n) || n < 0) + throw new RangeError("positive integer expected, got " + n); +} +function abytes2(value, length, title = "") { + const bytes = isBytes2(value); + const len = value?.length; + const needsLen = length !== void 0; + if (!bytes || needsLen && len !== length) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ""; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message2 = prefix + "expected Uint8Array" + ofLen + ", got " + got; + if (!bytes) + throw new TypeError(message2); + throw new RangeError(message2); + } + return value; +} +function aexists2(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function aoutput2(out, instance, onlyAligned = false) { + abytes2(out, void 0, "output"); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError("digestInto() expects output buffer of length at least " + min); + } + if (onlyAligned && !isAligned32(out)) + throw new Error("invalid output, must be aligned"); +} +function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +function clean2(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +function createView2(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); +var byteSwap = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0; +var byteSwap32 = (arr) => { + for (let i = 0; i < arr.length; i++) + arr[i] = byteSwap(arr[i]); + return arr; +}; +var swap32IfBE = isLE ? (u) => u : byteSwap32; +var hasHexBuiltin = /* @__PURE__ */ (() => ( + // @ts-ignore + typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" +))(); +var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bytesToHex(bytes) { + abytes2(bytes); + if (hasHexBuiltin) + return bytes.toHex(); + let hex4 = ""; + for (let i = 0; i < bytes.length; i++) { + hex4 += hexes[bytes[i]]; + } + return hex4; +} +var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); + return; +} +function hexToBytes(hex4) { + if (typeof hex4 !== "string") + throw new TypeError("hex string expected, got " + typeof hex4); + if (hasHexBuiltin) { + try { + return Uint8Array.fromHex(hex4); + } catch (error49) { + if (error49 instanceof SyntaxError) + throw new RangeError(error49.message); + throw error49; + } + } + const hl = hex4.length; + const al = hl / 2; + if (hl % 2) + throw new RangeError("hex string expected, got unpadded hex of length " + hl); + const array2 = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex4.charCodeAt(hi)); + const n2 = asciiToBase16(hex4.charCodeAt(hi + 1)); + if (n1 === void 0 || n2 === void 0) { + const char = hex4[hi] + hex4[hi + 1]; + throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array2[ai] = n1 * 16 + n2; + } + return array2; +} +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new TypeError("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +function overlapBytes(a, b) { + if (!a.byteLength || !b.byteLength) + return false; + return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy + a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end + b.byteOffset < a.byteOffset + a.byteLength; +} +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes2(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +function checkOpts(defaults, opts) { + if (opts == null || typeof opts !== "object") + throw new Error("options must be defined"); + const merged = Object.assign(defaults, opts); + return merged; +} +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +function wrapMacConstructor(keyLen, macCons, fromMsg) { + const mac3 = macCons; + const getArgs = fromMsg || (() => []); + const macC = (msg, key) => mac3(key, ...getArgs(msg)).update(msg).digest(); + const tmp = mac3(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0))); + macC.outputLen = tmp.outputLen; + macC.blockLen = tmp.blockLen; + macC.create = (key, ...args) => mac3(key, ...args); + return macC; +} +var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => { + function wrappedCipher(key, ...args) { + abytes2(key, void 0, "key"); + if (params.nonceLength !== void 0) { + const nonce = args[0]; + abytes2(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce"); + } + const tagl = params.tagLength; + if (tagl && args[1] !== void 0) + abytes2(args[1], void 0, "AAD"); + const cipher = constructor(key, ...args); + const checkOutput = (fnLength, output) => { + if (output !== void 0) { + if (fnLength !== 2) + throw new Error("cipher output not supported"); + abytes2(output, void 0, "output"); + } + }; + let called = false; + const wrCipher = { + encrypt(data, output) { + if (called) + throw new Error("cannot encrypt() twice with same key + nonce"); + called = true; + abytes2(data); + checkOutput(cipher.encrypt.length, output); + return cipher.encrypt(data, output); + }, + decrypt(data, output) { + abytes2(data); + if (tagl && data.length < tagl) + throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl); + checkOutput(cipher.decrypt.length, output); + return cipher.decrypt(data, output); + } + }; + return wrCipher; + } + Object.assign(wrappedCipher, params); + return wrappedCipher; +}; +function getOutput(expectedLength, out, onlyAligned = true) { + if (out === void 0) + return new Uint8Array(expectedLength); + abytes2(out, void 0, "output"); + if (out.length !== expectedLength) + throw new Error('"output" expected Uint8Array of length ' + expectedLength + ", got: " + out.length); + if (onlyAligned && !isAligned32(out)) + throw new Error("invalid output, must be aligned"); + return out; +} +function u64Lengths(dataLength, aadLength, isLE2) { + anumber2(dataLength); + anumber2(aadLength); + abool(isLE2); + const num = new Uint8Array(16); + const view = createView2(num); + view.setBigUint64(0, BigInt(aadLength), isLE2); + view.setBigUint64(8, BigInt(dataLength), isLE2); + return num; +} +function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; +} +function copyBytes(bytes) { + return Uint8Array.from(abytes2(bytes)); +} +function randomBytes2(bytesLength = 32) { + anumber2(bytesLength); + const cr = typeof globalThis === "object" ? globalThis.crypto : null; + if (typeof cr?.getRandomValues !== "function") + throw new Error("crypto.getRandomValues must be defined"); + return cr.getRandomValues(new Uint8Array(bytesLength)); +} +function managedNonce(fn, randomBytes_ = randomBytes2) { + const { nonceLength } = fn; + anumber2(nonceLength); + const addNonce = (nonce, ciphertext, plaintext) => { + const out = concatBytes(nonce, ciphertext); + if (!overlapBytes(plaintext, ciphertext)) + ciphertext.fill(0); + return out; + }; + const res = (key, ...args) => ({ + encrypt(plaintext) { + abytes2(plaintext); + const nonce = randomBytes_(nonceLength); + const encrypted = fn(key, nonce, ...args).encrypt(plaintext); + if (encrypted instanceof Promise) + return encrypted.then((ct) => addNonce(nonce, ct, plaintext)); + return addNonce(nonce, encrypted, plaintext); + }, + decrypt(ciphertext) { + abytes2(ciphertext); + const nonce = ciphertext.subarray(0, nonceLength); + const decrypted = ciphertext.subarray(nonceLength); + return fn(key, nonce, ...args).decrypt(decrypted); + } + }); + if ("blockSize" in fn) + res.blockSize = fn.blockSize; + if ("tagLength" in fn) + res.tagLength = fn.tagLength; + return res; +} + +// ../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_arx.js +var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0)); +var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))(); +var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))(); +function rotl(a, b) { + return a << b | a >>> 32 - b; +} +var BLOCK_LEN = 64; +var BLOCK_LEN32 = 16; +var MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)(); +var U32_EMPTY = /* @__PURE__ */ Uint32Array.of(); +function runCipher(core, sigma, key, nonce, data, output, counter, rounds) { + const len = data.length; + const block = new Uint8Array(BLOCK_LEN); + const b32 = u32(block); + const isAligned = isLE && isAligned32(data) && isAligned32(output); + const d32 = isAligned ? u32(data) : U32_EMPTY; + const o32 = isAligned ? u32(output) : U32_EMPTY; + if (!isLE) { + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + swap32IfBE(b32); + if (counter >= MAX_COUNTER) + throw new Error("arx: counter overflow"); + const take = Math.min(BLOCK_LEN, len - pos); + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } + return; + } + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + if (counter >= MAX_COUNTER) + throw new Error("arx: counter overflow"); + const take = Math.min(BLOCK_LEN, len - pos); + if (isAligned && take === BLOCK_LEN) { + const pos32 = pos / 4; + if (pos % 4 !== 0) + throw new Error("arx: invalid block position"); + for (let j = 0, posj; j < BLOCK_LEN32; j++) { + posj = pos32 + j; + o32[posj] = d32[posj] ^ b32[j]; + } + pos += BLOCK_LEN; + continue; + } + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } +} +function createCipher(core, opts) { + const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); + if (typeof core !== "function") + throw new Error("core must be a function"); + anumber2(counterLength); + anumber2(rounds); + abool(counterRight); + abool(allowShortKeys); + return (key, nonce, data, output, counter = 0) => { + abytes2(key, void 0, "key"); + abytes2(nonce, void 0, "nonce"); + abytes2(data, void 0, "data"); + const len = data.length; + output = getOutput(len, output, false); + anumber2(counter); + if (counter < 0 || counter >= MAX_COUNTER) + throw new Error("arx: counter overflow"); + const toClean = []; + let l = key.length; + let k; + let sigma; + if (l === 32) { + toClean.push(k = copyBytes(key)); + sigma = sigma32_32; + } else if (l === 16 && allowShortKeys) { + k = new Uint8Array(32); + k.set(key); + k.set(key, 16); + sigma = sigma16_32; + toClean.push(k); + } else { + abytes2(key, 32, "arx key"); + throw new Error("invalid key size"); + } + if (!isLE || !isAligned32(nonce)) + toClean.push(nonce = copyBytes(nonce)); + let k32 = u32(k); + if (extendNonceFn) { + if (nonce.length !== 24) + throw new Error(`arx: extended nonce must be 24 bytes`); + const n16 = nonce.subarray(0, 16); + if (isLE) + extendNonceFn(sigma, k32, u32(n16), k32); + else { + const sigmaRaw = swap32IfBE(Uint32Array.from(sigma)); + extendNonceFn(sigmaRaw, k32, u32(n16), k32); + clean2(sigmaRaw); + swap32IfBE(k32); + } + nonce = nonce.subarray(16); + } else if (!isLE) + swap32IfBE(k32); + const nonceNcLen = 16 - counterLength; + if (nonceNcLen !== nonce.length) + throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); + if (nonceNcLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + nonce = nc; + toClean.push(nonce); + } + const n32 = swap32IfBE(u32(nonce)); + try { + runCipher(core, sigma, k32, n32, data, output, counter, rounds); + return output; + } finally { + clean2(...toClean); + } + }; +} + +// ../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_poly1305.js +function u8to16(a, i) { + return a[i++] & 255 | (a[i++] & 255) << 8; +} +var Poly1305 = class { + // Can be speed-up using BigUint64Array, at the cost of complexity + constructor(key) { + __publicField(this, "blockLen", 16); + __publicField(this, "outputLen", 16); + __publicField(this, "buffer", new Uint8Array(16)); + __publicField(this, "r", new Uint16Array(10)); + // Allocating 1 array with .subarray() here is slower than 3 + __publicField(this, "h", new Uint16Array(10)); + __publicField(this, "pad", new Uint16Array(8)); + __publicField(this, "pos", 0); + __publicField(this, "finished", false); + __publicField(this, "destroyed", false); + key = copyBytes(abytes2(key, 32, "key")); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t2 = u8to16(key, 4); + const t3 = u8to16(key, 6); + const t4 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + this.r[0] = t0 & 8191; + this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; + this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; + this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; + this.r[4] = (t3 >>> 4 | t4 << 12) & 255; + this.r[5] = t4 >>> 1 & 8190; + this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; + this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; + this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; + this.r[9] = t7 >>> 5 & 127; + for (let i = 0; i < 8; i++) + this.pad[i] = u8to16(key, 16 + 2 * i); + } + process(data, offset, isLast = false) { + const hibit = isLast ? 0 : 1 << 11; + const { h, r } = this; + const r0 = r[0]; + const r1 = r[1]; + const r2 = r[2]; + const r3 = r[3]; + const r4 = r[4]; + const r5 = r[5]; + const r6 = r[6]; + const r7 = r[7]; + const r8 = r[8]; + const r9 = r[9]; + const t0 = u8to16(data, offset + 0); + const t1 = u8to16(data, offset + 2); + const t2 = u8to16(data, offset + 4); + const t3 = u8to16(data, offset + 6); + const t4 = u8to16(data, offset + 8); + const t5 = u8to16(data, offset + 10); + const t6 = u8to16(data, offset + 12); + const t7 = u8to16(data, offset + 14); + let h0 = h[0] + (t0 & 8191); + let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191); + let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191); + let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191); + let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191); + let h5 = h[5] + (t4 >>> 1 & 8191); + let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191); + let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191); + let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191); + let h9 = h[9] + (t7 >>> 5 | hibit); + let c = 0; + let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 8191; + d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 8191; + let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 8191; + d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 8191; + let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 8191; + d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 8191; + let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 8191; + d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 8191; + let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; + c = d4 >>> 13; + d4 &= 8191; + d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 8191; + let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; + c = d5 >>> 13; + d5 &= 8191; + d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 8191; + let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; + c = d6 >>> 13; + d6 &= 8191; + d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 8191; + let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; + c = d7 >>> 13; + d7 &= 8191; + d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 8191; + let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; + c = d8 >>> 13; + d8 &= 8191; + d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 8191; + let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; + c = d9 >>> 13; + d9 &= 8191; + d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; + c += d9 >>> 13; + d9 &= 8191; + c = (c << 2) + c | 0; + c = c + d0 | 0; + d0 = c & 8191; + c = c >>> 13; + d1 += c; + h[0] = d0; + h[1] = d1; + h[2] = d2; + h[3] = d3; + h[4] = d4; + h[5] = d5; + h[6] = d6; + h[7] = d7; + h[8] = d8; + h[9] = d9; + } + finalize() { + const { h, pad } = this; + const g = new Uint16Array(10); + let c = h[1] >>> 13; + h[1] &= 8191; + for (let i = 2; i < 10; i++) { + h[i] += c; + c = h[i] >>> 13; + h[i] &= 8191; + } + h[0] += c * 5; + c = h[0] >>> 13; + h[0] &= 8191; + h[1] += c; + c = h[1] >>> 13; + h[1] &= 8191; + h[2] += c; + g[0] = h[0] + 5; + c = g[0] >>> 13; + g[0] &= 8191; + for (let i = 1; i < 10; i++) { + g[i] = h[i] + c; + c = g[i] >>> 13; + g[i] &= 8191; + } + g[9] -= 1 << 13; + let mask = (c ^ 1) - 1; + for (let i = 0; i < 10; i++) + g[i] &= mask; + mask = ~mask; + for (let i = 0; i < 10; i++) + h[i] = h[i] & mask | g[i]; + h[0] = (h[0] | h[1] << 13) & 65535; + h[1] = (h[1] >>> 3 | h[2] << 10) & 65535; + h[2] = (h[2] >>> 6 | h[3] << 7) & 65535; + h[3] = (h[3] >>> 9 | h[4] << 4) & 65535; + h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535; + h[5] = (h[6] >>> 2 | h[7] << 11) & 65535; + h[6] = (h[7] >>> 5 | h[8] << 8) & 65535; + h[7] = (h[8] >>> 8 | h[9] << 5) & 65535; + let f = h[0] + pad[0]; + h[0] = f & 65535; + for (let i = 1; i < 8; i++) { + f = (h[i] + pad[i] | 0) + (f >>> 16) | 0; + h[i] = f & 65535; + } + clean2(g); + } + update(data) { + aexists2(this); + abytes2(data); + data = copyBytes(data); + const { buffer, blockLen } = this; + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) + this.process(data, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer, 0, false); + this.pos = 0; + } + } + return this; + } + destroy() { + this.destroyed = true; + clean2(this.h, this.r, this.buffer, this.pad); + } + digestInto(out) { + aexists2(this); + aoutput2(out, this); + this.finished = true; + const { buffer, h } = this; + let { pos } = this; + if (pos) { + buffer[pos++] = 1; + for (; pos < 16; pos++) + buffer[pos] = 0; + this.process(buffer, 0, true); + } + this.finalize(); + let opos = 0; + for (let i = 0; i < 8; i++) { + out[opos++] = h[i] >>> 0; + out[opos++] = h[i] >>> 8; + } + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } +}; +var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key)); + +// ../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/chacha.js +function chachaCore(s, k, n, out, cnt, rounds = 20) { + let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r = 0; r < rounds; r += 2) { + x00 = x00 + x04 | 0; + x12 = rotl(x12 ^ x00, 16); + x08 = x08 + x12 | 0; + x04 = rotl(x04 ^ x08, 12); + x00 = x00 + x04 | 0; + x12 = rotl(x12 ^ x00, 8); + x08 = x08 + x12 | 0; + x04 = rotl(x04 ^ x08, 7); + x01 = x01 + x05 | 0; + x13 = rotl(x13 ^ x01, 16); + x09 = x09 + x13 | 0; + x05 = rotl(x05 ^ x09, 12); + x01 = x01 + x05 | 0; + x13 = rotl(x13 ^ x01, 8); + x09 = x09 + x13 | 0; + x05 = rotl(x05 ^ x09, 7); + x02 = x02 + x06 | 0; + x14 = rotl(x14 ^ x02, 16); + x10 = x10 + x14 | 0; + x06 = rotl(x06 ^ x10, 12); + x02 = x02 + x06 | 0; + x14 = rotl(x14 ^ x02, 8); + x10 = x10 + x14 | 0; + x06 = rotl(x06 ^ x10, 7); + x03 = x03 + x07 | 0; + x15 = rotl(x15 ^ x03, 16); + x11 = x11 + x15 | 0; + x07 = rotl(x07 ^ x11, 12); + x03 = x03 + x07 | 0; + x15 = rotl(x15 ^ x03, 8); + x11 = x11 + x15 | 0; + x07 = rotl(x07 ^ x11, 7); + x00 = x00 + x05 | 0; + x15 = rotl(x15 ^ x00, 16); + x10 = x10 + x15 | 0; + x05 = rotl(x05 ^ x10, 12); + x00 = x00 + x05 | 0; + x15 = rotl(x15 ^ x00, 8); + x10 = x10 + x15 | 0; + x05 = rotl(x05 ^ x10, 7); + x01 = x01 + x06 | 0; + x12 = rotl(x12 ^ x01, 16); + x11 = x11 + x12 | 0; + x06 = rotl(x06 ^ x11, 12); + x01 = x01 + x06 | 0; + x12 = rotl(x12 ^ x01, 8); + x11 = x11 + x12 | 0; + x06 = rotl(x06 ^ x11, 7); + x02 = x02 + x07 | 0; + x13 = rotl(x13 ^ x02, 16); + x08 = x08 + x13 | 0; + x07 = rotl(x07 ^ x08, 12); + x02 = x02 + x07 | 0; + x13 = rotl(x13 ^ x02, 8); + x08 = x08 + x13 | 0; + x07 = rotl(x07 ^ x08, 7); + x03 = x03 + x04 | 0; + x14 = rotl(x14 ^ x03, 16); + x09 = x09 + x14 | 0; + x04 = rotl(x04 ^ x09, 12); + x03 = x03 + x04 | 0; + x14 = rotl(x14 ^ x03, 8); + x09 = x09 + x14 | 0; + x04 = rotl(x04 ^ x09, 7); + } + let oi = 0; + out[oi++] = y00 + x00 | 0; + out[oi++] = y01 + x01 | 0; + out[oi++] = y02 + x02 | 0; + out[oi++] = y03 + x03 | 0; + out[oi++] = y04 + x04 | 0; + out[oi++] = y05 + x05 | 0; + out[oi++] = y06 + x06 | 0; + out[oi++] = y07 + x07 | 0; + out[oi++] = y08 + x08 | 0; + out[oi++] = y09 + x09 | 0; + out[oi++] = y10 + x10 | 0; + out[oi++] = y11 + x11 | 0; + out[oi++] = y12 + x12 | 0; + out[oi++] = y13 + x13 | 0; + out[oi++] = y14 + x14 | 0; + out[oi++] = y15 + x15 | 0; +} +function hchacha(s, k, i, out) { + let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]), x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]), x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]), x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]); + for (let r = 0; r < 20; r += 2) { + x00 = x00 + x04 | 0; + x12 = rotl(x12 ^ x00, 16); + x08 = x08 + x12 | 0; + x04 = rotl(x04 ^ x08, 12); + x00 = x00 + x04 | 0; + x12 = rotl(x12 ^ x00, 8); + x08 = x08 + x12 | 0; + x04 = rotl(x04 ^ x08, 7); + x01 = x01 + x05 | 0; + x13 = rotl(x13 ^ x01, 16); + x09 = x09 + x13 | 0; + x05 = rotl(x05 ^ x09, 12); + x01 = x01 + x05 | 0; + x13 = rotl(x13 ^ x01, 8); + x09 = x09 + x13 | 0; + x05 = rotl(x05 ^ x09, 7); + x02 = x02 + x06 | 0; + x14 = rotl(x14 ^ x02, 16); + x10 = x10 + x14 | 0; + x06 = rotl(x06 ^ x10, 12); + x02 = x02 + x06 | 0; + x14 = rotl(x14 ^ x02, 8); + x10 = x10 + x14 | 0; + x06 = rotl(x06 ^ x10, 7); + x03 = x03 + x07 | 0; + x15 = rotl(x15 ^ x03, 16); + x11 = x11 + x15 | 0; + x07 = rotl(x07 ^ x11, 12); + x03 = x03 + x07 | 0; + x15 = rotl(x15 ^ x03, 8); + x11 = x11 + x15 | 0; + x07 = rotl(x07 ^ x11, 7); + x00 = x00 + x05 | 0; + x15 = rotl(x15 ^ x00, 16); + x10 = x10 + x15 | 0; + x05 = rotl(x05 ^ x10, 12); + x00 = x00 + x05 | 0; + x15 = rotl(x15 ^ x00, 8); + x10 = x10 + x15 | 0; + x05 = rotl(x05 ^ x10, 7); + x01 = x01 + x06 | 0; + x12 = rotl(x12 ^ x01, 16); + x11 = x11 + x12 | 0; + x06 = rotl(x06 ^ x11, 12); + x01 = x01 + x06 | 0; + x12 = rotl(x12 ^ x01, 8); + x11 = x11 + x12 | 0; + x06 = rotl(x06 ^ x11, 7); + x02 = x02 + x07 | 0; + x13 = rotl(x13 ^ x02, 16); + x08 = x08 + x13 | 0; + x07 = rotl(x07 ^ x08, 12); + x02 = x02 + x07 | 0; + x13 = rotl(x13 ^ x02, 8); + x08 = x08 + x13 | 0; + x07 = rotl(x07 ^ x08, 7); + x03 = x03 + x04 | 0; + x14 = rotl(x14 ^ x03, 16); + x09 = x09 + x14 | 0; + x04 = rotl(x04 ^ x09, 12); + x03 = x03 + x04 | 0; + x14 = rotl(x14 ^ x03, 8); + x09 = x09 + x14 | 0; + x04 = rotl(x04 ^ x09, 7); + } + let oi = 0; + out[oi++] = x00; + out[oi++] = x01; + out[oi++] = x02; + out[oi++] = x03; + out[oi++] = x12; + out[oi++] = x13; + out[oi++] = x14; + out[oi++] = x15; + swap32IfBE(out); +} +var xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, + allowShortKeys: false +}); +var ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +var updatePadded = (h, msg) => { + h.update(msg); + const leftover = msg.length % 16; + if (leftover) + h.update(ZEROS16.subarray(leftover)); +}; +var ZEROS32 = /* @__PURE__ */ new Uint8Array(32); +function computeTag(fn, key, nonce, ciphertext, AAD) { + if (AAD !== void 0) + abytes2(AAD, void 0, "AAD"); + const authKey = fn(key, nonce, ZEROS32); + const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true); + const h = poly1305.create(authKey); + if (AAD) + updatePadded(h, AAD); + updatePadded(h, ciphertext); + h.update(lengths); + const res = h.digest(); + clean2(authKey, lengths); + return res; +} +var _poly1305_aead = (xorStream) => (key, nonce, AAD) => { + const tagLength = 16; + return { + encrypt(plaintext, output) { + const plength = plaintext.length; + output = getOutput(plength + tagLength, output, false); + output.set(plaintext); + const oPlain = output.subarray(0, -tagLength); + xorStream(key, nonce, oPlain, oPlain, 1); + const tag2 = computeTag(xorStream, key, nonce, oPlain, AAD); + output.set(tag2, plength); + clean2(tag2); + return output; + }, + decrypt(ciphertext, output) { + output = getOutput(ciphertext.length - tagLength, output, false); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag2 = computeTag(xorStream, key, nonce, data, AAD); + if (!equalBytes(passedTag, tag2)) { + clean2(tag2); + throw new Error("invalid tag"); + } + output.set(ciphertext.subarray(0, -tagLength)); + xorStream(key, nonce, output, output, 1); + clean2(tag2); + return output; + } + }; +}; +var xchacha20poly1305 = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 24, tagLength: 16 }, + /* @__PURE__ */ _poly1305_aead(xchacha20) +); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/index.mjs +var ENVELOPE_PREFIX = "$ba$"; +function parseEnvelope(data) { + if (!data.startsWith(ENVELOPE_PREFIX)) return null; + const firstSep = 4; + const secondSep = data.indexOf("$", firstSep); + if (secondSep === -1) return null; + const version3 = parseInt(data.slice(firstSep, secondSep), 10); + if (!Number.isInteger(version3) || version3 < 0) return null; + return { + version: version3, + ciphertext: data.slice(secondSep + 1) + }; +} +function formatEnvelope(version3, ciphertext) { + return `${ENVELOPE_PREFIX}${version3}$${ciphertext}`; +} +async function rawEncrypt(secret, data) { + const keyAsBytes = await createHash("SHA-256").digest(secret); + const dataAsBytes = utf8ToBytes(data); + return bytesToHex(managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)).encrypt(dataAsBytes)); +} +async function rawDecrypt(secret, hex4) { + const keyAsBytes = await createHash("SHA-256").digest(secret); + const dataAsBytes = hexToBytes(hex4); + const chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)); + return new TextDecoder().decode(chacha.decrypt(dataAsBytes)); +} +var symmetricEncrypt = async ({ key, data }) => { + if (typeof key === "string") return rawEncrypt(key, data); + const secret = key.keys.get(key.currentVersion); + if (!secret) throw new Error(`Secret version ${key.currentVersion} not found in keys`); + const ciphertext = await rawEncrypt(secret, data); + return formatEnvelope(key.currentVersion, ciphertext); +}; +var symmetricDecrypt = async ({ key, data }) => { + if (typeof key === "string") return rawDecrypt(key, data); + const envelope = parseEnvelope(data); + if (envelope) { + const secret = key.keys.get(envelope.version); + if (!secret) throw new Error(`Secret version ${envelope.version} not found in keys (key may have been retired)`); + return rawDecrypt(secret, envelope.ciphertext); + } + if (key.legacySecret) return rawDecrypt(key.legacySecret, data); + throw new Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility."); +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/date.mjs +var getDate = (span, unit = "ms") => { + return new Date(Date.now() + (unit === "sec" ? span * 1e3 : span)); +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/index.mjs +init_get_tables(); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/schema.mjs +init_error2(); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/db.mjs +function filterOutputFields(data, additionalFields) { + if (!data || !additionalFields) return data; + const returnFiltered = Object.entries(additionalFields).filter(([, { returned }]) => returned === false).map(([key]) => key); + return Object.entries(structuredClone(data)).filter(([key]) => !returnFiltered.includes(key)).reduce((acc, [key, value]) => ({ + ...acc, + [key]: value + }), {}); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/schema.mjs +var cache2 = /* @__PURE__ */ new WeakMap(); +function getFields(options, modelName, mode) { + const cacheKey2 = `${modelName}:${mode}`; + if (!cache2.has(options)) cache2.set(options, /* @__PURE__ */ new Map()); + const tableCache = cache2.get(options); + if (tableCache.has(cacheKey2)) return tableCache.get(cacheKey2); + const coreSchema = mode === "output" ? getAuthTables(options)[modelName]?.fields ?? {} : {}; + const additionalFields = modelName === "user" || modelName === "session" || modelName === "account" ? options[modelName]?.additionalFields : void 0; + let schema3 = { + ...coreSchema, + ...additionalFields ?? {} + }; + for (const plugin of options.plugins || []) if (plugin.schema && plugin.schema[modelName]) schema3 = { + ...schema3, + ...plugin.schema[modelName].fields + }; + tableCache.set(cacheKey2, schema3); + return schema3; +} +function parseUserOutput(options, user) { + return filterOutputFields(user, getFields(options, "user", "output")); +} +function parseSessionOutput(options, session) { + return filterOutputFields(session, getFields(options, "session", "output")); +} +function parseAccountOutput(options, account) { + const { accessToken: _accessToken, refreshToken: _refreshToken, idToken: _idToken, accessTokenExpiresAt: _accessTokenExpiresAt, refreshTokenExpiresAt: _refreshTokenExpiresAt, password: _password, ...rest } = filterOutputFields(account, getFields(options, "account", "output")); + return rest; +} +function parseInputData(data, schema3) { + const action = schema3.action || "create"; + const fields = schema3.fields; + const parsedData = /* @__PURE__ */ Object.create(null); + for (const key in fields) { + if (key in data) { + if (fields[key].input === false) { + if (fields[key].defaultValue !== void 0) { + if (action !== "update") { + parsedData[key] = fields[key].defaultValue; + continue; + } + } + if (data[key]) throw APIError2.from("BAD_REQUEST", { + ...BASE_ERROR_CODES.FIELD_NOT_ALLOWED, + message: `${key} is not allowed to be set` + }); + continue; + } + if (fields[key].validator?.input && data[key] !== void 0) { + const result = fields[key].validator.input["~standard"].validate(data[key]); + if (result instanceof Promise) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED); + if ("issues" in result && result.issues) throw APIError2.from("BAD_REQUEST", { + ...BASE_ERROR_CODES.VALIDATION_ERROR, + message: result.issues[0]?.message || "Validation Error" + }); + parsedData[key] = result.value; + continue; + } + if (fields[key].transform?.input && data[key] !== void 0) { + parsedData[key] = fields[key].transform?.input(data[key]); + continue; + } + parsedData[key] = data[key]; + continue; + } + if (fields[key].defaultValue !== void 0 && action === "create") { + if (typeof fields[key].defaultValue === "function") { + parsedData[key] = fields[key].defaultValue(); + continue; + } + parsedData[key] = fields[key].defaultValue; + continue; + } + if (fields[key].required && action === "create") throw APIError2.from("BAD_REQUEST", { + ...BASE_ERROR_CODES.MISSING_FIELD, + message: `${key} is required` + }); + } + return parsedData; +} +function parseUserInput(options, user = {}, action) { + return parseInputData(user, { + fields: getFields(options, "user", "input"), + action + }); +} +function parseSessionInput(options, session, action) { + return parseInputData(session, { + fields: getFields(options, "session", "input"), + action + }); +} +function getSessionDefaultFields(options) { + const fields = getFields(options, "session", "input"); + const defaults = {}; + for (const key in fields) if (fields[key].defaultValue !== void 0) defaults[key] = typeof fields[key].defaultValue === "function" ? fields[key].defaultValue() : fields[key].defaultValue; + return defaults; +} +function mergeSchema(schema3, newSchema) { + if (!newSchema) return schema3; + for (const table in newSchema) { + const newModelName = newSchema[table]?.modelName; + if (newModelName) schema3[table].modelName = newModelName; + for (const field in schema3[table].fields) { + const newField = newSchema[table]?.fields?.[field]; + if (!newField) continue; + schema3[table].fields[field].fieldName = newField; + } + } + return schema3; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-promise.mjs +function isPromise(obj) { + return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/session-store.mjs +init_json(); +init_zod(); +var ALLOWED_COOKIE_SIZE = 4096; +var ESTIMATED_EMPTY_COOKIE_SIZE = 200; +var CHUNK_SIZE = ALLOWED_COOKIE_SIZE - ESTIMATED_EMPTY_COOKIE_SIZE; +function parseCookiesFromContext(ctx) { + const cookieHeader = ctx.headers?.get("cookie"); + if (!cookieHeader) return {}; + const cookies = {}; + const pairs = cookieHeader.split("; "); + for (const pair of pairs) { + const [name, ...valueParts] = pair.split("="); + if (name && valueParts.length > 0) cookies[name] = valueParts.join("="); + } + return cookies; +} +function getChunkIndex(cookieName) { + const parts = cookieName.split("."); + const lastPart = parts[parts.length - 1]; + const index = parseInt(lastPart || "0", 10); + return isNaN(index) ? 0 : index; +} +function readExistingChunks(cookieName, ctx) { + const chunks = {}; + const cookies = parseCookiesFromContext(ctx); + for (const [name, value] of Object.entries(cookies)) if (name.startsWith(cookieName)) chunks[name] = value; + return chunks; +} +function joinChunks(chunks) { + return Object.keys(chunks).sort((a, b) => { + return getChunkIndex(a) - getChunkIndex(b); + }).map((key) => chunks[key]).join(""); +} +function chunkCookie(storeName, cookie, chunks, logger2) { + const chunkCount = Math.ceil(cookie.value.length / CHUNK_SIZE); + if (chunkCount === 1) { + chunks[cookie.name] = cookie.value; + return [cookie]; + } + const cookies = []; + for (let i = 0; i < chunkCount; i++) { + const name = `${cookie.name}.${i}`; + const start = i * CHUNK_SIZE; + const value = cookie.value.substring(start, start + CHUNK_SIZE); + cookies.push({ + ...cookie, + name, + value + }); + chunks[name] = value; + } + logger2.debug(`CHUNKING_${storeName.toUpperCase()}_COOKIE`, { + message: `${storeName} cookie exceeds allowed ${ALLOWED_COOKIE_SIZE} bytes.`, + emptyCookieSize: ESTIMATED_EMPTY_COOKIE_SIZE, + valueSize: cookie.value.length, + chunkCount, + chunks: cookies.map((c) => c.value.length + ESTIMATED_EMPTY_COOKIE_SIZE) + }); + return cookies; +} +function getCleanCookies(chunks, cookieOptions) { + const cleanedChunks = {}; + for (const name in chunks) cleanedChunks[name] = { + name, + value: "", + attributes: { + ...cookieOptions, + maxAge: 0 + } + }; + return cleanedChunks; +} +var storeFactory = (storeName) => (cookieName, cookieOptions, ctx) => { + const chunks = readExistingChunks(cookieName, ctx); + const logger2 = ctx.context.logger; + return { + getValue() { + return joinChunks(chunks); + }, + hasChunks() { + return Object.keys(chunks).length > 0; + }, + chunk(value, options) { + const cleanedChunks = getCleanCookies(chunks, cookieOptions); + for (const name in chunks) delete chunks[name]; + const cookies = cleanedChunks; + const chunked = chunkCookie(storeName, { + name: cookieName, + value, + attributes: { + ...cookieOptions, + ...options + } + }, chunks, logger2); + for (const chunk of chunked) cookies[chunk.name] = chunk; + return Object.values(cookies); + }, + clean() { + const cleanedChunks = getCleanCookies(chunks, cookieOptions); + for (const name in chunks) delete chunks[name]; + return Object.values(cleanedChunks); + }, + setCookies(cookies) { + for (const cookie of cookies) ctx.setCookie(cookie.name, cookie.value, cookie.attributes); + } + }; +}; +var createSessionStore = storeFactory("Session"); +var createAccountStore = storeFactory("Account"); +function getChunkedCookie(ctx, cookieName) { + const value = ctx.getCookie(cookieName); + if (value) return value; + const chunks = []; + const cookieHeader = ctx.headers?.get("cookie"); + if (!cookieHeader) return null; + const cookies = {}; + const pairs = cookieHeader.split("; "); + for (const pair of pairs) { + const [name, ...valueParts] = pair.split("="); + if (name && valueParts.length > 0) cookies[name] = valueParts.join("="); + } + for (const [name, val] of Object.entries(cookies)) if (name.startsWith(cookieName + ".")) { + const indexStr = name.split(".").at(-1); + const index = parseInt(indexStr || "0", 10); + if (!isNaN(index)) chunks.push({ + index, + value: val + }); + } + if (chunks.length > 0) { + chunks.sort((a, b) => a.index - b.index); + return chunks.map((c) => c.value).join(""); + } + return null; +} +async function setAccountCookie(c, accountData) { + const accountDataCookie = c.context.authCookies.accountData; + const options = { + maxAge: 300, + ...accountDataCookie.attributes + }; + const data = await symmetricEncodeJWT(accountData, c.context.secretConfig, "better-auth-account", options.maxAge); + if (data.length > ALLOWED_COOKIE_SIZE) { + const accountStore = createAccountStore(accountDataCookie.name, options, c); + const cookies = accountStore.chunk(data, options); + accountStore.setCookies(cookies); + } else { + const accountStore = createAccountStore(accountDataCookie.name, options, c); + if (accountStore.hasChunks()) { + const cleanCookies = accountStore.clean(); + accountStore.setCookies(cleanCookies); + } + c.setCookie(accountDataCookie.name, data, options); + } +} +async function getAccountCookie(c) { + const accountCookie = getChunkedCookie(c, c.context.authCookies.accountData.name); + if (accountCookie) { + const accountData = safeJSONParse(await symmetricDecodeJWT(accountCookie, c.context.secretConfig, "better-auth-account")); + if (accountData) return accountData; + } + return null; +} +var getSessionQuerySchema = optional(object({ + disableCookieCache: coerce_exports.boolean().meta({ description: "Disable cookie cache and fetch session from database" }).optional(), + disableRefresh: coerce_exports.boolean().meta({ description: "Disable session refresh. Useful for checking session status, without updating the session" }).optional() +})); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/time.mjs +var SEC = 1e3; +var MIN = SEC * 60; +var HOUR = MIN * 60; +var DAY = HOUR * 24; +var WEEK = DAY * 7; +var MONTH = DAY * 30; +var YEAR = DAY * 365.25; +var REGEX2 = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i; +function parse3(value) { + const match2 = REGEX2.exec(value); + if (!match2 || match2[4] && match2[1]) throw new TypeError(`Invalid time string format: "${value}". Use formats like "7d", "30m", "1 hour", etc.`); + const n = parseFloat(match2[2]); + const unit = match2[3].toLowerCase(); + let result; + switch (unit) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + result = n * YEAR; + break; + case "months": + case "month": + case "mo": + result = n * MONTH; + break; + case "weeks": + case "week": + case "w": + result = n * WEEK; + break; + case "days": + case "day": + case "d": + result = n * DAY; + break; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + result = n * HOUR; + break; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + result = n * MIN; + break; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + result = n * SEC; + break; + default: + throw new TypeError(`Unknown time unit: "${unit}"`); + } + if (match2[1] === "-" || match2[4] === "ago") return -result; + return result; +} +function sec(value) { + return Math.round(parse3(value) / 1e3); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/cookie-utils.mjs +var SECURE_COOKIE_PREFIX = "__Secure-"; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/index.mjs +init_env(); +init_error2(); + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/binary.mjs +var decoders = /* @__PURE__ */ new Map(); +var encoder2 = new TextEncoder(); +var binary = { + decode: (data, encoding = "utf-8") => { + if (!decoders.has(encoding)) { + decoders.set(encoding, new TextDecoder(encoding)); + } + const decoder2 = decoders.get(encoding); + return decoder2.decode(data); + }, + encode: encoder2.encode +}; + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hex.mjs +var hexadecimal = "0123456789abcdef"; +var hex3 = { + encode: (data) => { + if (typeof data === "string") { + data = new TextEncoder().encode(data); + } + if (data.byteLength === 0) { + return ""; + } + const buffer = new Uint8Array(data); + let result = ""; + for (const byte of buffer) { + result += byte.toString(16).padStart(2, "0"); + } + return result; + }, + decode: (data) => { + if (!data) { + return ""; + } + if (typeof data === "string") { + if (data.length % 2 !== 0) { + throw new Error("Invalid hexadecimal string"); + } + if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) { + throw new Error("Invalid hexadecimal string"); + } + const result = new Uint8Array(data.length / 2); + for (let i = 0; i < data.length; i += 2) { + result[i / 2] = parseInt(data.slice(i, i + 2), 16); + } + return new TextDecoder().decode(result); + } + return new TextDecoder().decode(data); + } +}; + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hmac.mjs +var createHMAC = (algorithm2 = "SHA-256", encoding = "none") => { + const hmac2 = { + importKey: async (key, keyUsage) => { + return getWebcryptoSubtle().importKey( + "raw", + typeof key === "string" ? new TextEncoder().encode(key) : key, + { name: "HMAC", hash: { name: algorithm2 } }, + false, + [keyUsage] + ); + }, + sign: async (hmacKey, data) => { + if (typeof hmacKey === "string") { + hmacKey = await hmac2.importKey(hmacKey, "sign"); + } + const signature = await getWebcryptoSubtle().sign( + "HMAC", + hmacKey, + typeof data === "string" ? new TextEncoder().encode(data) : data + ); + if (encoding === "hex") { + return hex3.encode(signature); + } + if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { + return base64Url.encode(signature, { + padding: encoding !== "base64urlnopad" + }); + } + return signature; + }, + verify: async (hmacKey, data, signature) => { + if (typeof hmacKey === "string") { + hmacKey = await hmac2.importKey(hmacKey, "verify"); + } + if (encoding === "hex") { + signature = hex3.decode(signature); + } + if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { + signature = await base643.decode(signature); + } + return getWebcryptoSubtle().verify( + "HMAC", + hmacKey, + typeof signature === "string" ? new TextEncoder().encode(signature) : signature, + typeof data === "string" ? new TextEncoder().encode(data) : data + ); + } + }; + return hmac2; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/index.mjs +function createCookieGetter(options) { + const baseURLString = typeof options.baseURL === "string" ? options.baseURL : void 0; + const dynamicProtocol = typeof options.baseURL === "object" && options.baseURL !== null ? options.baseURL.protocol : void 0; + const secureCookiePrefix = (options.advanced?.useSecureCookies !== void 0 ? options.advanced?.useSecureCookies : dynamicProtocol === "https" ? true : dynamicProtocol === "http" ? false : baseURLString ? baseURLString.startsWith("https://") : isProduction) ? SECURE_COOKIE_PREFIX : ""; + const crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled; + const domain2 = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (baseURLString ? new URL(baseURLString).hostname : void 0) : void 0; + if (crossSubdomainEnabled && !domain2 && !isDynamicBaseURLConfig(options.baseURL)) throw new BetterAuthError("baseURL is required when crossSubdomainCookies are enabled."); + function createCookie(cookieName, overrideAttributes = {}) { + const prefix = options.advanced?.cookiePrefix || "better-auth"; + const name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`; + const attributes = options.advanced?.cookies?.[cookieName]?.attributes ?? {}; + return { + name: `${secureCookiePrefix}${name}`, + attributes: { + secure: !!secureCookiePrefix, + sameSite: "lax", + path: "/", + httpOnly: true, + ...crossSubdomainEnabled ? { domain: domain2 } : {}, + ...options.advanced?.defaultCookieAttributes, + ...overrideAttributes, + ...attributes + } + }; + } + return createCookie; +} +function getCookies(options) { + const createCookie = createCookieGetter(options); + const sessionToken = createCookie("session_token", { maxAge: options.session?.expiresIn || sec("7d") }); + const sessionData = createCookie("session_data", { maxAge: options.session?.cookieCache?.maxAge || 300 }); + const accountData = createCookie("account_data", { maxAge: options.session?.cookieCache?.maxAge || 300 }); + const dontRememberToken = createCookie("dont_remember"); + return { + sessionToken: { + name: sessionToken.name, + attributes: sessionToken.attributes + }, + sessionData: { + name: sessionData.name, + attributes: sessionData.attributes + }, + dontRememberToken: { + name: dontRememberToken.name, + attributes: dontRememberToken.attributes + }, + accountData: { + name: accountData.name, + attributes: accountData.attributes + } + }; +} +async function setCookieCache(ctx, session, dontRememberMe) { + if (!ctx.context.options.session?.cookieCache?.enabled) return; + const filteredSession = filterOutputFields(session.session, ctx.context.options.session?.additionalFields); + const filteredUser = parseUserOutput(ctx.context.options, session.user); + const versionConfig = ctx.context.options.session?.cookieCache?.version; + let version3 = "1"; + if (versionConfig) { + if (typeof versionConfig === "string") version3 = versionConfig; + else if (typeof versionConfig === "function") { + const result = versionConfig(session.session, session.user); + version3 = isPromise(result) ? await result : result; + } + } + const sessionData = { + session: filteredSession, + user: filteredUser, + updatedAt: Date.now(), + version: version3 + }; + const options = { + ...ctx.context.authCookies.sessionData.attributes, + maxAge: dontRememberMe ? void 0 : ctx.context.authCookies.sessionData.attributes.maxAge + }; + const expiresAtDate = getDate(options.maxAge || 60, "sec").getTime(); + const strategy = ctx.context.options.session?.cookieCache?.strategy || "compact"; + let data; + if (strategy === "jwe") data = await symmetricEncodeJWT(sessionData, ctx.context.secretConfig, "better-auth-session", options.maxAge || 300); + else if (strategy === "jwt") data = await signJWT(sessionData, ctx.context.secret, options.maxAge || 300); + else data = base64Url.encode(JSON.stringify({ + session: sessionData, + expiresAt: expiresAtDate, + signature: await createHMAC("SHA-256", "base64urlnopad").sign(ctx.context.secret, JSON.stringify({ + ...sessionData, + expiresAt: expiresAtDate + })) + }), { padding: false }); + if (data.length > 4093) { + const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx); + const cookies = sessionStore.chunk(data, options); + sessionStore.setCookies(cookies); + } else { + const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx); + if (sessionStore.hasChunks()) { + const cleanCookies = sessionStore.clean(); + sessionStore.setCookies(cleanCookies); + } + ctx.setCookie(ctx.context.authCookies.sessionData.name, data, options); + } + if (ctx.context.options.account?.storeAccountCookie) { + const accountData = await getAccountCookie(ctx); + if (accountData) await setAccountCookie(ctx, accountData); + } +} +async function setSessionCookie(ctx, session, dontRememberMe, overrides) { + const dontRememberMeCookie = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); + dontRememberMe = dontRememberMe !== void 0 ? dontRememberMe : !!dontRememberMeCookie; + const options = ctx.context.authCookies.sessionToken.attributes; + const maxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn; + await ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, { + ...options, + maxAge, + ...overrides + }); + if (dontRememberMe) await ctx.setSignedCookie(ctx.context.authCookies.dontRememberToken.name, "true", ctx.context.secret, ctx.context.authCookies.dontRememberToken.attributes); + await setCookieCache(ctx, session, dontRememberMe); + ctx.context.setNewSession(session); +} +function expireCookie(ctx, cookie) { + ctx.setCookie(cookie.name, "", { + ...cookie.attributes, + maxAge: 0 + }); +} +function deleteSessionCookie(ctx, skipDontRememberMe) { + expireCookie(ctx, ctx.context.authCookies.sessionToken); + expireCookie(ctx, ctx.context.authCookies.sessionData); + if (ctx.context.options.account?.storeAccountCookie) { + expireCookie(ctx, ctx.context.authCookies.accountData); + const accountStore = createAccountStore(ctx.context.authCookies.accountData.name, ctx.context.authCookies.accountData.attributes, ctx); + const cleanCookies2 = accountStore.clean(); + accountStore.setCookies(cleanCookies2); + } + if (ctx.context.oauthConfig.storeStateStrategy === "cookie") expireCookie(ctx, ctx.context.createAuthCookie("oauth_state")); + const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, ctx.context.authCookies.sessionData.attributes, ctx); + const cleanCookies = sessionStore.clean(); + sessionStore.setCookies(cleanCookies); + if (!skipDontRememberMe) expireCookie(ctx, ctx.context.authCookies.dontRememberToken); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/state.mjs +init_error2(); +init_zod(); +var stateDataSchema = looseObject({ + callbackURL: string2(), + codeVerifier: string2(), + errorURL: string2().optional(), + newUserURL: string2().optional(), + expiresAt: number2(), + oauthState: string2().optional(), + link: object({ + email: string2(), + userId: coerce_exports.string() + }).optional(), + requestSignUp: boolean2().optional() +}); +var StateError = class extends BetterAuthError { + constructor(message2, options) { + super(message2, options); + __publicField(this, "code"); + __publicField(this, "details"); + this.code = options.code; + this.details = options.details; + } +}; +async function generateGenericState(c, stateData, settings) { + const state = generateRandomString(32); + if (c.context.oauthConfig.storeStateStrategy === "cookie") { + const payload = { + ...stateData, + oauthState: state + }; + const encryptedData = await symmetricEncrypt({ + key: c.context.secretConfig, + data: JSON.stringify(payload) + }); + const stateCookie2 = c.context.createAuthCookie(settings?.cookieName ?? "oauth_state", { maxAge: 600 }); + c.setCookie(stateCookie2.name, encryptedData, stateCookie2.attributes); + return { + state, + codeVerifier: stateData.codeVerifier + }; + } + const stateCookie = c.context.createAuthCookie(settings?.cookieName ?? "state", { maxAge: 300 }); + await c.setSignedCookie(stateCookie.name, state, c.context.secret, stateCookie.attributes); + const expiresAt = /* @__PURE__ */ new Date(); + expiresAt.setMinutes(expiresAt.getMinutes() + 10); + if (!await c.context.internalAdapter.createVerificationValue({ + value: JSON.stringify({ + ...stateData, + oauthState: state + }), + identifier: state, + expiresAt + })) throw new StateError("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database", { code: "state_generation_error" }); + return { + state, + codeVerifier: stateData.codeVerifier + }; +} +async function parseGenericState(c, state, settings) { + const storeStateStrategy = c.context.oauthConfig.storeStateStrategy; + let parsedData; + if (storeStateStrategy === "cookie") { + const stateCookie = c.context.createAuthCookie(settings?.cookieName ?? "oauth_state"); + const encryptedData = c.getCookie(stateCookie.name); + if (!encryptedData) throw new StateError("State mismatch: auth state cookie not found", { + code: "state_mismatch", + details: { state } + }); + try { + const decryptedData = await symmetricDecrypt({ + key: c.context.secretConfig, + data: encryptedData + }); + parsedData = stateDataSchema.parse(JSON.parse(decryptedData)); + } catch (error49) { + throw new StateError("State invalid: Failed to decrypt or parse auth state", { + code: "state_invalid", + details: { state }, + cause: error49 + }); + } + if (!parsedData.oauthState || parsedData.oauthState !== state) throw new StateError("State mismatch: OAuth state parameter does not match stored state", { + code: "state_security_mismatch", + details: { state } + }); + expireCookie(c, stateCookie); + } else { + const data = await c.context.internalAdapter.findVerificationValue(state); + if (!data) throw new StateError("State mismatch: verification not found", { + code: "state_mismatch", + details: { state } + }); + parsedData = stateDataSchema.parse(JSON.parse(data.value)); + if (parsedData.oauthState !== void 0 && parsedData.oauthState !== state) throw new StateError("State mismatch: OAuth state parameter does not match stored state", { + code: "state_security_mismatch", + details: { state } + }); + const stateCookie = c.context.createAuthCookie(settings?.cookieName ?? "state"); + const stateCookieValue = await c.getSignedCookie(stateCookie.name, c.context.secret); + if (!(settings?.skipStateCookieCheck ?? c.context.oauthConfig.skipStateCookieCheck) && (!stateCookieValue || stateCookieValue !== state)) throw new StateError("State mismatch: State not persisted correctly", { + code: "state_security_mismatch", + details: { state } + }); + expireCookie(c, stateCookie); + await c.context.internalAdapter.deleteVerificationByIdentifier(state); + } + if (parsedData.expiresAt < Date.now()) throw new StateError("Invalid state: request expired", { + code: "state_mismatch", + details: { expiresAt: parsedData.expiresAt } + }); + return parsedData; +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/global.mjs +var symbol2 = Symbol.for("better-auth:global"); +var bind = null; +var __context = {}; +var __betterAuthVersion = "1.6.2"; +function __getBetterAuthGlobal() { + if (!globalThis[symbol2]) { + globalThis[symbol2] = { + version: __betterAuthVersion, + epoch: 1, + context: __context + }; + bind = globalThis[symbol2]; + } + bind = globalThis[symbol2]; + if (bind.version !== __betterAuthVersion) { + bind.version = __betterAuthVersion; + bind.epoch++; + } + return globalThis[symbol2]; +} +function getBetterAuthVersion() { + return __getBetterAuthGlobal().version; +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/async_hooks/index.mjs +var AsyncLocalStoragePromise = import( + /* @vite-ignore */ + /* webpackIgnore: true */ + "node:async_hooks" +).then((mod) => mod.AsyncLocalStorage).catch((err) => { + if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage; + if (typeof window !== "undefined") return null; + console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."); + console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"); + console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"); + throw err; +}); +async function getAsyncLocalStorage() { + const mod = await AsyncLocalStoragePromise; + if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code"); + else return mod; +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/endpoint-context.mjs +var ensureAsyncStorage = async () => { + const betterAuthGlobal = __getBetterAuthGlobal(); + if (!betterAuthGlobal.context.endpointContextAsyncStorage) { + const AsyncLocalStorage = await getAsyncLocalStorage(); + betterAuthGlobal.context.endpointContextAsyncStorage = new AsyncLocalStorage(); + } + return betterAuthGlobal.context.endpointContextAsyncStorage; +}; +async function getCurrentAuthContext() { + const context = (await ensureAsyncStorage()).getStore(); + if (!context) throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback."); + return context; +} +async function runWithEndpointContext(context, fn) { + return (await ensureAsyncStorage()).run(context, fn); +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/request-state.mjs +var ensureAsyncStorage2 = async () => { + const betterAuthGlobal = __getBetterAuthGlobal(); + if (!betterAuthGlobal.context.requestStateAsyncStorage) { + const AsyncLocalStorage = await getAsyncLocalStorage(); + betterAuthGlobal.context.requestStateAsyncStorage = new AsyncLocalStorage(); + } + return betterAuthGlobal.context.requestStateAsyncStorage; +}; +async function hasRequestState() { + return (await ensureAsyncStorage2()).getStore() !== void 0; +} +async function getCurrentRequestState() { + const store = (await ensureAsyncStorage2()).getStore(); + if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback."); + return store; +} +async function runWithRequestState(store, fn) { + return (await ensureAsyncStorage2()).run(store, fn); +} +function defineRequestState(initFn) { + const ref = Object.freeze({}); + return { + get ref() { + return ref; + }, + async get() { + const store = await getCurrentRequestState(); + if (!store.has(ref)) { + const initialValue = await initFn(); + store.set(ref, initialValue); + return initialValue; + } + return store.get(ref); + }, + async set(value) { + (await getCurrentRequestState()).set(ref, value); + } + }; +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/transaction.mjs +var ensureAsyncStorage3 = async () => { + const betterAuthGlobal = __getBetterAuthGlobal(); + if (!betterAuthGlobal.context.adapterAsyncStorage) { + const AsyncLocalStorage = await getAsyncLocalStorage(); + betterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage(); + } + return betterAuthGlobal.context.adapterAsyncStorage; +}; +var getCurrentAdapter = async (fallback) => { + return ensureAsyncStorage3().then((als) => { + return als.getStore()?.adapter || fallback; + }).catch(() => { + return fallback; + }); +}; +var runWithAdapter = async (adapter, fn) => { + let called = false; + return ensureAsyncStorage3().then(async (als) => { + called = true; + const pendingHooks = []; + let result; + let error49; + let hasError = false; + try { + result = await als.run({ + adapter, + pendingHooks + }, fn); + } catch (err) { + error49 = err; + hasError = true; + } + for (const hook of pendingHooks) await hook(); + if (hasError) throw error49; + return result; + }).catch((err) => { + if (!called) return fn(); + throw err; + }); +}; +var runWithTransaction = async (adapter, fn) => { + let called = true; + return ensureAsyncStorage3().then(async (als) => { + called = true; + const pendingHooks = []; + let result; + let error49; + let hasError = false; + try { + result = await adapter.transaction(async (trx) => { + return als.run({ + adapter: trx, + pendingHooks + }, fn); + }); + } catch (e) { + hasError = true; + error49 = e; + } + for (const hook of pendingHooks) await hook(); + if (hasError) throw error49; + return result; + }).catch((err) => { + if (!called) return fn(); + throw err; + }); +}; +var queueAfterTransactionHook = async (hook) => { + return ensureAsyncStorage3().then((als) => { + const store = als.getStore(); + if (store) store.pendingHooks.push(hook); + else return hook(); + }).catch(() => { + return hook(); + }); +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/state/oauth.mjs +var { get: getOAuthState, set: setOAuthState } = defineRequestState(() => null); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/state.mjs +init_error2(); +async function generateState(c, link, additionalData) { + const callbackURL = c.body?.callbackURL || c.context.options.baseURL; + if (!callbackURL) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.CALLBACK_URL_REQUIRED); + const codeVerifier = generateRandomString(128); + const stateData = { + ...additionalData ? additionalData : {}, + callbackURL, + codeVerifier, + errorURL: c.body?.errorCallbackURL, + newUserURL: c.body?.newUserCallbackURL, + link, + expiresAt: Date.now() + 600 * 1e3, + requestSignUp: c.body?.requestSignUp + }; + await setOAuthState(stateData); + try { + return generateGenericState(c, stateData); + } catch (error49) { + c.context.logger.error("Failed to create verification", error49); + throw new APIError2("INTERNAL_SERVER_ERROR", { + message: "Unable to create verification", + cause: error49 + }); + } +} +async function parseState(c) { + const state = c.query.state || c.body.state; + const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`; + let parsedData; + try { + parsedData = await parseGenericState(c, state); + } catch (error49) { + c.context.logger.error("Failed to parse state", error49); + if (error49 instanceof StateError && error49.code === "state_security_mismatch") throw c.redirect(`${errorURL}?error=state_mismatch`); + throw c.redirect(`${errorURL}?error=please_restart_the_process`); + } + if (!parsedData.errorURL) parsedData.errorURL = errorURL; + if (parsedData) await setOAuthState(parsedData); + return parsedData; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/hide-metadata.mjs +var HIDE_METADATA = { scope: "server" }; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-api-error.mjs +init_error2(); + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/index.mjs +init_error(); + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/to-response.mjs +init_error(); + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/utils.mjs +init_error(); +var jsonContentTypeRegex = /^application\/([a-z0-9.+-]*\+)?json/i; +async function getBody(request, allowedMediaTypes) { + const contentType = request.headers.get("content-type") || ""; + const normalizedContentType = contentType.toLowerCase(); + if (!request.body) return; + if (allowedMediaTypes && allowedMediaTypes.length > 0) { + if (!allowedMediaTypes.some((allowed2) => { + const normalizedContentTypeBase = normalizedContentType.split(";")[0].trim(); + const normalizedAllowed = allowed2.toLowerCase().trim(); + return normalizedContentTypeBase === normalizedAllowed || normalizedContentTypeBase.includes(normalizedAllowed); + })) { + if (!normalizedContentType) throw new APIError(415, { + message: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(", ")}`, + code: "UNSUPPORTED_MEDIA_TYPE" + }); + throw new APIError(415, { + message: `Content-Type "${contentType}" is not allowed. Allowed types: ${allowedMediaTypes.join(", ")}`, + code: "UNSUPPORTED_MEDIA_TYPE" + }); + } + } + if (jsonContentTypeRegex.test(normalizedContentType)) return await request.json(); + if (normalizedContentType.includes("application/x-www-form-urlencoded")) { + const formData = await request.formData(); + const result = {}; + formData.forEach((value, key) => { + result[key] = value.toString(); + }); + return result; + } + if (normalizedContentType.includes("multipart/form-data")) { + const formData = await request.formData(); + const result = {}; + formData.forEach((value, key) => { + result[key] = value; + }); + return result; + } + if (normalizedContentType.includes("text/plain")) return await request.text(); + if (normalizedContentType.includes("application/octet-stream")) return await request.arrayBuffer(); + if (normalizedContentType.includes("application/pdf") || normalizedContentType.includes("image/") || normalizedContentType.includes("video/")) return await request.blob(); + if (normalizedContentType.includes("application/stream") || request.body instanceof ReadableStream) return request.body; + return await request.text(); +} +function isAPIError(error49) { + return error49 instanceof APIError || error49?.name === "APIError"; +} +function tryDecode2(str) { + try { + return str.includes("%") ? decodeURIComponent(str) : str; + } catch { + return str; + } +} +async function tryCatch(promise2) { + try { + return { + data: await promise2, + error: null + }; + } catch (error49) { + return { + data: null, + error: error49 + }; + } +} +function isRequest(obj) { + return obj instanceof Request || Object.prototype.toString.call(obj) === "[object Request]"; +} + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/to-response.mjs +function isJSONSerializable(value) { + if (value === void 0) return false; + const t = typeof value; + if (t === "string" || t === "number" || t === "boolean" || t === null) return true; + if (t !== "object") return false; + if (Array.isArray(value)) return true; + if (value.buffer) return false; + return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; +} +function safeStringify(obj, replacer, space) { + let id = 0; + const seen = /* @__PURE__ */ new WeakMap(); + const safeReplacer = (key, value) => { + if (typeof value === "bigint") return value.toString(); + if (typeof value === "object" && value !== null) { + if (seen.has(value)) return `[Circular ref-${seen.get(value)}]`; + seen.set(value, id++); + } + if (replacer) return replacer(key, value); + return value; + }; + return JSON.stringify(obj, safeReplacer, space); +} +function isJSONResponse(value) { + if (!value || typeof value !== "object") return false; + return "_flag" in value && value._flag === "json"; +} +var REQUEST_ONLY_HEADERS = /* @__PURE__ */ new Set([ + "host", + "user-agent", + "referer", + "from", + "expect", + "authorization", + "proxy-authorization", + "cookie", + "origin", + "accept-charset", + "accept-encoding", + "accept-language", + "if-match", + "if-none-match", + "if-modified-since", + "if-unmodified-since", + "if-range", + "range", + "max-forwards", + "connection", + "keep-alive", + "transfer-encoding", + "te", + "upgrade", + "trailer", + "proxy-connection", + "content-length" +]); +function stripRequestOnlyHeaders(headers) { + for (const name of REQUEST_ONLY_HEADERS) headers.delete(name); +} +function toResponse(data, init2) { + if (data instanceof Response) { + if (init2?.headers) { + const safeHeaders = new Headers(init2.headers); + stripRequestOnlyHeaders(safeHeaders); + safeHeaders.forEach((value, key) => { + data.headers.set(key, value); + }); + } + return data; + } + if (isJSONResponse(data)) { + const body2 = data.body; + const routerResponse = data.routerResponse; + if (routerResponse instanceof Response) return routerResponse; + const headers2 = new Headers(); + if (routerResponse?.headers) { + const headers3 = new Headers(routerResponse.headers); + for (const [key, value] of headers3.entries()) headers3.set(key, value); + } + if (data.headers) for (const [key, value] of new Headers(data.headers).entries()) headers2.set(key, value); + if (init2?.headers) { + const safeHeaders = new Headers(init2.headers); + stripRequestOnlyHeaders(safeHeaders); + for (const [key, value] of safeHeaders.entries()) headers2.set(key, value); + } + headers2.set("Content-Type", "application/json"); + return new Response(JSON.stringify(body2), { + ...routerResponse, + headers: headers2, + status: data.status ?? init2?.status ?? routerResponse?.status, + statusText: init2?.statusText ?? routerResponse?.statusText + }); + } + if (isAPIError(data)) return toResponse(data.body, { + status: init2?.status ?? data.statusCode, + statusText: data.status.toString(), + headers: init2?.headers || data.headers + }); + let body = data; + const headers = new Headers(init2?.headers); + stripRequestOnlyHeaders(headers); + if (!data) { + if (data === null) body = JSON.stringify(null); + headers.set("content-type", "application/json"); + } else if (typeof data === "string") { + body = data; + headers.set("Content-Type", "text/plain"); + } else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { + body = data; + headers.set("Content-Type", "application/octet-stream"); + } else if (data instanceof Blob) { + body = data; + headers.set("Content-Type", data.type || "application/octet-stream"); + } else if (data instanceof FormData) body = data; + else if (data instanceof URLSearchParams) { + body = data; + headers.set("Content-Type", "application/x-www-form-urlencoded"); + } else if (data instanceof ReadableStream) { + body = data; + headers.set("Content-Type", "application/octet-stream"); + } else if (isJSONSerializable(data)) { + body = safeStringify(data); + headers.set("Content-Type", "application/json"); + } + return new Response(body, { + ...init2, + headers + }); +} + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/crypto.mjs +var algorithm = { + name: "HMAC", + hash: "SHA-256" +}; +var getCryptoKey3 = async (secret) => { + const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret; + return await getWebcryptoSubtle().importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]); +}; +var verifySignature = async (base64Signature, value, secret) => { + try { + const signatureBinStr = atob(base64Signature); + const signature = new Uint8Array(signatureBinStr.length); + for (let i = 0, len = signatureBinStr.length; i < len; i++) signature[i] = signatureBinStr.charCodeAt(i); + return await getWebcryptoSubtle().verify(algorithm, secret, signature, new TextEncoder().encode(value)); + } catch (e) { + return false; + } +}; +var makeSignature = async (value, secret) => { + const key = await getCryptoKey3(secret); + const signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value)); + return btoa(String.fromCharCode(...new Uint8Array(signature))); +}; +var signCookieValue = async (value, secret) => { + const signature = await makeSignature(value, secret); + value = `${value}.${signature}`; + value = encodeURIComponent(value); + return value; +}; + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/cookies.mjs +var getCookieKey = (key, prefix) => { + let finalKey = key; + if (prefix) if (prefix === "secure") finalKey = "__Secure-" + key; + else if (prefix === "host") finalKey = "__Host-" + key; + else return; + return finalKey; +}; +function parseCookies(str) { + if (typeof str !== "string") throw new TypeError("argument str must be a string"); + const cookies = /* @__PURE__ */ new Map(); + let index = 0; + while (index < str.length) { + const eqIdx = str.indexOf("=", index); + if (eqIdx === -1) break; + let endIdx = str.indexOf(";", index); + if (endIdx === -1) endIdx = str.length; + else if (endIdx < eqIdx) { + index = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + const key = str.slice(index, eqIdx).trim(); + if (!cookies.has(key)) { + let val = str.slice(eqIdx + 1, endIdx).trim(); + if (val.codePointAt(0) === 34) val = val.slice(1, -1); + cookies.set(key, tryDecode2(val)); + } + index = endIdx + 1; + } + return cookies; +} +var _serialize = (key, value, opt = {}) => { + let cookie; + if (opt?.prefix === "secure") cookie = `${`__Secure-${key}`}=${value}`; + else if (opt?.prefix === "host") cookie = `${`__Host-${key}`}=${value}`; + else cookie = `${key}=${value}`; + if (key.startsWith("__Secure-") && !opt.secure) opt.secure = true; + if (key.startsWith("__Host-")) { + if (!opt.secure) opt.secure = true; + if (opt.path !== "/") opt.path = "/"; + if (opt.domain) opt.domain = void 0; + } + if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) { + if (opt.maxAge > 3456e4) throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration."); + cookie += `; Max-Age=${Math.floor(opt.maxAge)}`; + } + if (opt.domain && opt.prefix !== "host") cookie += `; Domain=${opt.domain}`; + if (opt.path) cookie += `; Path=${opt.path}`; + if (opt.expires) { + if (opt.expires.getTime() - Date.now() > 3456e7) throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future."); + cookie += `; Expires=${opt.expires.toUTCString()}`; + } + if (opt.httpOnly) cookie += "; HttpOnly"; + if (opt.secure) cookie += "; Secure"; + if (opt.sameSite) cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`; + if (opt.partitioned) { + if (!opt.secure) opt.secure = true; + cookie += "; Partitioned"; + } + return cookie; +}; +var serializeCookie = (key, value, opt) => { + value = encodeURIComponent(value); + return _serialize(key, value, opt); +}; +var serializeSignedCookie = async (key, value, secret, opt) => { + value = await signCookieValue(value, secret); + return _serialize(key, value, opt); +}; + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/context.mjs +init_error(); + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/validator.mjs +async function runValidation(options, context = {}) { + let request = { + body: context.body, + query: context.query + }; + if (options.body) { + const result = await options.body["~standard"].validate(context.body); + if (result.issues) return { + data: null, + error: fromError(result.issues, "body") + }; + request.body = result.value; + } + if (options.query) { + const result = await options.query["~standard"].validate(context.query); + if (result.issues) return { + data: null, + error: fromError(result.issues, "query") + }; + request.query = result.value; + } + if (options.requireHeaders && !context.headers) return { + data: null, + error: { + message: "Headers is required", + issues: [] + } + }; + if (options.requireRequest && !context.request) return { + data: null, + error: { + message: "Request is required", + issues: [] + } + }; + return { + data: request, + error: null + }; +} +function fromError(error49, validating) { + return { + message: error49.map((e) => { + return `[${e.path?.length ? `${validating}.` + e.path.map((x) => typeof x === "object" ? x.key : x).join(".") : validating}] ${e.message}`; + }).join("; "), + issues: error49 + }; +} + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/context.mjs +var createInternalContext = async (context, { options, path: path3 }) => { + const headers = new Headers(); + let responseStatus = void 0; + const { data, error: error49 } = await runValidation(options, context); + if (error49) throw new ValidationError(error49.message, error49.issues); + const requestHeaders = "headers" in context ? context.headers instanceof Headers ? context.headers : new Headers(context.headers) : "request" in context && isRequest(context.request) ? context.request.headers : null; + const requestCookies = requestHeaders?.get("cookie"); + const parsedCookies = requestCookies ? parseCookies(requestCookies) : void 0; + const internalContext = { + ...context, + body: data.body, + query: data.query, + path: context.path || path3 || "virtual:", + context: "context" in context && context.context ? context.context : {}, + returned: void 0, + headers: context?.headers, + request: context?.request, + params: "params" in context ? context.params : void 0, + method: context.method ?? (Array.isArray(options.method) ? options.method[0] : options.method === "*" ? "GET" : options.method), + setHeader: (key, value) => { + headers.set(key, value); + }, + getHeader: (key) => { + if (!requestHeaders) return null; + return requestHeaders.get(key); + }, + getCookie: (key, prefix) => { + const finalKey = getCookieKey(key, prefix); + if (!finalKey) return null; + return parsedCookies?.get(finalKey) || null; + }, + getSignedCookie: async (key, secret, prefix) => { + const finalKey = getCookieKey(key, prefix); + if (!finalKey) return null; + const value = parsedCookies?.get(finalKey); + if (!value) return null; + const signatureStartPos = value.lastIndexOf("."); + if (signatureStartPos < 1) return null; + const signedValue = value.substring(0, signatureStartPos); + const signature = value.substring(signatureStartPos + 1); + if (signature.length !== 44 || !signature.endsWith("=")) return null; + return await verifySignature(signature, signedValue, await getCryptoKey3(secret)) ? signedValue : false; + }, + setCookie: (key, value, options2) => { + const cookie = serializeCookie(key, value, options2); + headers.append("set-cookie", cookie); + return cookie; + }, + setSignedCookie: async (key, value, secret, options2) => { + const cookie = await serializeSignedCookie(key, value, secret, options2); + headers.append("set-cookie", cookie); + return cookie; + }, + redirect: (url2) => { + headers.set("location", url2); + return new APIError("FOUND", void 0, headers); + }, + error: (status, body, headers2) => { + return new APIError(status, body, headers2); + }, + setStatus: (status) => { + responseStatus = status; + }, + json: (json2, routerResponse) => { + if (!context.asResponse) return json2; + return { + body: routerResponse?.body || json2, + routerResponse, + _flag: "json" + }; + }, + responseHeaders: headers, + get responseStatus() { + return responseStatus; + } + }; + for (const middleware of options.use || []) { + const response = await middleware({ + ...internalContext, + returnHeaders: true, + asResponse: false + }); + if (response.response) Object.assign(internalContext.context, response.response); + if (response.headers) response.headers.forEach((value, key) => { + internalContext.responseHeaders.set(key, value); + }); + } + return internalContext; +}; + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/endpoint.mjs +init_error(); +function createEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { + const path3 = typeof pathOrOptions === "string" ? pathOrOptions : void 0; + const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; + const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; + if ((options.method === "GET" || options.method === "HEAD") && options.body) throw new BetterCallError("Body is not allowed with GET or HEAD methods"); + if (path3 && /\/{2,}/.test(path3)) throw new BetterCallError("Path cannot contain consecutive slashes"); + const internalHandler = async (...inputCtx) => { + const context = inputCtx[0] || {}; + const { data: internalContext, error: validationError } = await tryCatch(createInternalContext(context, { + options, + path: path3 + })); + if (validationError) { + if (!(validationError instanceof ValidationError)) throw validationError; + if (options.onValidationError) await options.onValidationError({ + message: validationError.message, + issues: validationError.issues + }); + throw new APIError(400, { + message: validationError.message, + code: "VALIDATION_ERROR" + }); + } + const response = await handler(internalContext).catch(async (e) => { + if (isAPIError(e)) { + const onAPIError = options.onAPIError; + if (onAPIError) await onAPIError(e); + if (context.asResponse) return e; + } + throw e; + }); + const headers = internalContext.responseHeaders; + const status = internalContext.responseStatus; + return context.asResponse ? toResponse(response, { + headers, + status + }) : context.returnHeaders ? context.returnStatus ? { + headers, + response, + status + } : { + headers, + response + } : context.returnStatus ? { + response, + status + } : response; + }; + internalHandler.options = options; + internalHandler.path = path3; + return internalHandler; +} +createEndpoint.create = (opts) => { + return (path3, options, handler) => { + return createEndpoint(path3, { + ...options, + use: [...options?.use || [], ...opts?.use || []] + }, handler); + }; +}; + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/middleware.mjs +init_error(); +function createMiddleware(optionsOrHandler, handler) { + const internalHandler = async (inputCtx) => { + const context = inputCtx; + const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler; + const internalContext = await createInternalContext(context, { + options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler, + path: "/" + }); + if (!_handler) throw new Error("handler must be defined"); + try { + const response = await _handler(internalContext); + const headers = internalContext.responseHeaders; + return context.returnHeaders ? { + headers, + response + } : response; + } catch (e) { + if (isAPIError(e)) Object.defineProperty(e, kAPIErrorHeaderSymbol, { + enumerable: false, + configurable: true, + get() { + return internalContext.responseHeaders; + } + }); + throw e; + } + }; + internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler; + return internalHandler; +} +createMiddleware.create = (opts) => { + function fn(optionsOrHandler, handler) { + if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler); + if (!handler) throw new Error("Middleware handler is required"); + return createMiddleware({ + ...optionsOrHandler, + method: "*", + use: [...opts?.use || [], ...optionsOrHandler.use || []] + }, handler); + } + return fn; +}; + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/openapi.mjs +init_zod(); +var paths = {}; +function getTypeFromZodType(zodType) { + switch (zodType.constructor.name) { + case "ZodString": + return "string"; + case "ZodNumber": + return "number"; + case "ZodBoolean": + return "boolean"; + case "ZodObject": + return "object"; + case "ZodArray": + return "array"; + default: + return "string"; + } +} +function getParameters(options) { + const parameters = []; + if (options.metadata?.openapi?.parameters) { + parameters.push(...options.metadata.openapi.parameters); + return parameters; + } + if (options.query instanceof ZodObject) Object.entries(options.query.shape).forEach(([key, value]) => { + if (value instanceof ZodObject) parameters.push({ + name: key, + in: "query", + schema: { + type: getTypeFromZodType(value), + ..."minLength" in value && value.minLength ? { minLength: value.minLength } : {}, + description: value.description + } + }); + }); + return parameters; +} +function getRequestBody(options) { + if (options.metadata?.openapi?.requestBody) return options.metadata.openapi.requestBody; + if (!options.body) return void 0; + if (options.body instanceof ZodObject || options.body instanceof ZodOptional) { + const shape = options.body.shape; + if (!shape) return void 0; + const properties = {}; + const required2 = []; + Object.entries(shape).forEach(([key, value]) => { + if (value instanceof ZodObject) { + properties[key] = { + type: getTypeFromZodType(value), + description: value.description + }; + if (!(value instanceof ZodOptional)) required2.push(key); + } + }); + return { + required: options.body instanceof ZodOptional ? false : options.body ? true : false, + content: { "application/json": { schema: { + type: "object", + properties, + required: required2 + } } } + }; + } +} +function getResponse(responses) { + return { + "400": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } }, + required: ["message"] + } } }, + description: "Bad Request. Usually due to missing parameters, or invalid parameters." + }, + "401": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } }, + required: ["message"] + } } }, + description: "Unauthorized. Due to missing or invalid authentication." + }, + "403": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } }, + description: "Forbidden. You do not have permission to access this resource or to perform this action." + }, + "404": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } }, + description: "Not Found. The requested resource was not found." + }, + "429": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } }, + description: "Too Many Requests. You have exceeded the rate limit. Try again later." + }, + "500": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } }, + description: "Internal Server Error. This is a problem with the server that you cannot fix." + }, + ...responses + }; +} +async function generator(endpoints, config4) { + const components = { schemas: {} }; + Object.entries(endpoints).forEach(([_, value]) => { + const options = value.options; + if (!value.path || options.metadata?.SERVER_ONLY) return; + if (options.method === "GET") paths[value.path] = { get: { + tags: ["Default", ...options.metadata?.openapi?.tags || []], + description: options.metadata?.openapi?.description, + operationId: options.metadata?.openapi?.operationId, + security: [{ bearerAuth: [] }], + parameters: getParameters(options), + responses: getResponse(options.metadata?.openapi?.responses) + } }; + if (options.method === "POST") { + const body = getRequestBody(options); + paths[value.path] = { post: { + tags: ["Default", ...options.metadata?.openapi?.tags || []], + description: options.metadata?.openapi?.description, + operationId: options.metadata?.openapi?.operationId, + security: [{ bearerAuth: [] }], + parameters: getParameters(options), + ...body ? { requestBody: body } : { requestBody: { content: { "application/json": { schema: { + type: "object", + properties: {} + } } } } }, + responses: getResponse(options.metadata?.openapi?.responses) + } }; + } + }); + return { + openapi: "3.1.1", + info: { + title: "Better Auth", + description: "API Reference for your Better Auth Instance", + version: "1.1.0" + }, + components, + security: [{ apiKeyCookie: [] }], + servers: [{ url: config4?.url }], + tags: [{ + name: "Default", + description: "Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin." + }], + paths + }; +} +var getHTML = (apiReference, config4) => ` + + + Scalar API Reference + + + + + + + + +`; + +// ../../node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs +var NullProtoObj = /* @__PURE__ */ (() => { + const e = function() { + }; + return e.prototype = /* @__PURE__ */ Object.create(null), Object.freeze(e.prototype), e; +})(); +function createRouter() { + return { + root: { key: "" }, + static: new NullProtoObj() + }; +} +function splitPath2(path3) { + const [_, ...s] = path3.split("/"); + return s[s.length - 1] === "" ? s.slice(0, -1) : s; +} +function getMatchParams(segments, paramsMap) { + const params = new NullProtoObj(); + for (const [index, name] of paramsMap) { + const segment = index < 0 ? segments.slice(-(index + 1)).join("/") : segments[index]; + if (typeof name === "string") params[name] = segment; + else { + const match2 = segment.match(name); + if (match2) for (const key in match2.groups) params[key] = match2.groups[key]; + } + } + return params; +} +function addRoute(ctx, method = "", path3, data) { + var _a30; + method = method.toUpperCase(); + if (path3.charCodeAt(0) !== 47) path3 = `/${path3}`; + path3 = path3.replace(/\\:/g, "%3A"); + const segments = splitPath2(path3); + let node = ctx.root; + let _unnamedParamIndex = 0; + const paramsMap = []; + const paramsRegexp = []; + for (let i = 0; i < segments.length; i++) { + let segment = segments[i]; + if (segment.startsWith("**")) { + if (!node.wildcard) node.wildcard = { key: "**" }; + node = node.wildcard; + paramsMap.push([ + -(i + 1), + segment.split(":")[1] || "_", + segment.length === 2 + ]); + break; + } + if (segment === "*" || segment.includes(":")) { + if (!node.param) node.param = { key: "*" }; + node = node.param; + if (segment === "*") paramsMap.push([ + i, + `_${_unnamedParamIndex++}`, + true + ]); + else if (segment.includes(":", 1)) { + const regexp = getParamRegexp(segment); + paramsRegexp[i] = regexp; + node.hasRegexParam = true; + paramsMap.push([ + i, + regexp, + false + ]); + } else paramsMap.push([ + i, + segment.slice(1), + false + ]); + continue; + } + if (segment === "\\*") segment = segments[i] = "*"; + else if (segment === "\\*\\*") segment = segments[i] = "**"; + const child = node.static?.[segment]; + if (child) node = child; + else { + const staticNode = { key: segment }; + if (!node.static) node.static = new NullProtoObj(); + node.static[segment] = staticNode; + node = staticNode; + } + } + const hasParams = paramsMap.length > 0; + if (!node.methods) node.methods = new NullProtoObj(); + (_a30 = node.methods)[method] ?? (_a30[method] = []); + node.methods[method].push({ + data: data || null, + paramsRegexp, + paramsMap: hasParams ? paramsMap : void 0 + }); + if (!hasParams) ctx.static["/" + segments.join("/")] = node; +} +function getParamRegexp(segment) { + const regex = segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\."); + return /* @__PURE__ */ new RegExp(`^${regex}$`); +} +function findRoute(ctx, method = "", path3, opts) { + if (path3.charCodeAt(path3.length - 1) === 47) path3 = path3.slice(0, -1); + const staticNode = ctx.static[path3]; + if (staticNode && staticNode.methods) { + const staticMatch = staticNode.methods[method] || staticNode.methods[""]; + if (staticMatch !== void 0) return staticMatch[0]; + } + const segments = splitPath2(path3); + const match2 = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0]; + if (match2 === void 0) return; + if (opts?.params === false) return match2; + return { + data: match2.data, + params: match2.paramsMap ? getMatchParams(segments, match2.paramsMap) : void 0 + }; +} +function _lookupTree(ctx, node, method, segments, index) { + if (index === segments.length) { + if (node.methods) { + const match2 = node.methods[method] || node.methods[""]; + if (match2) return match2; + } + if (node.param && node.param.methods) { + const match2 = node.param.methods[method] || node.param.methods[""]; + if (match2) { + const pMap = match2[0].paramsMap; + if (pMap?.[pMap?.length - 1]?.[2]) return match2; + } + } + if (node.wildcard && node.wildcard.methods) { + const match2 = node.wildcard.methods[method] || node.wildcard.methods[""]; + if (match2) { + const pMap = match2[0].paramsMap; + if (pMap?.[pMap?.length - 1]?.[2]) return match2; + } + } + return; + } + const segment = segments[index]; + if (node.static) { + const staticChild = node.static[segment]; + if (staticChild) { + const match2 = _lookupTree(ctx, staticChild, method, segments, index + 1); + if (match2) return match2; + } + } + if (node.param) { + const match2 = _lookupTree(ctx, node.param, method, segments, index + 1); + if (match2) { + if (node.param.hasRegexParam) { + const exactMatch = match2.find((m) => m.paramsRegexp[index]?.test(segment)) || match2.find((m) => !m.paramsRegexp[index]); + return exactMatch ? [exactMatch] : void 0; + } + return match2; + } + } + if (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[""]; +} +function findAllRoutes(ctx, method = "", path3, opts) { + if (path3.charCodeAt(path3.length - 1) === 47) path3 = path3.slice(0, -1); + const segments = splitPath2(path3); + const matches = _findAll(ctx, ctx.root, method, segments, 0); + if (opts?.params === false) return matches; + return matches.map((m) => { + return { + data: m.data, + params: m.paramsMap ? getMatchParams(segments, m.paramsMap) : void 0 + }; + }); +} +function _findAll(ctx, node, method, segments, index, matches = []) { + const segment = segments[index]; + if (node.wildcard && node.wildcard.methods) { + const match2 = node.wildcard.methods[method] || node.wildcard.methods[""]; + if (match2) matches.push(...match2); + } + if (node.param) { + _findAll(ctx, node.param, method, segments, index + 1, matches); + if (index === segments.length && node.param.methods) { + const match2 = node.param.methods[method] || node.param.methods[""]; + if (match2) { + const pMap = match2[0].paramsMap; + if (pMap?.[pMap?.length - 1]?.[2]) matches.push(...match2); + } + } + } + const staticChild = node.static?.[segment]; + if (staticChild) _findAll(ctx, staticChild, method, segments, index + 1, matches); + if (index === segments.length && node.methods) { + const match2 = node.methods[method] || node.methods[""]; + if (match2) matches.push(...match2); + } + return matches; +} + +// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/router.mjs +var createRouter$1 = (endpoints, config4) => { + if (!config4?.openapi?.disabled) { + const openapi = { + path: "/api/reference", + ...config4?.openapi + }; + endpoints["openapi"] = createEndpoint(openapi.path, { method: "GET" }, async (c) => { + const schema3 = await generator(endpoints); + return new Response(getHTML(schema3, openapi.scalar), { headers: { "Content-Type": "text/html" } }); + }); + } + const router2 = createRouter(); + const middlewareRouter = createRouter(); + for (const endpoint of Object.values(endpoints)) { + if (!endpoint.options || !endpoint.path) continue; + if (endpoint.options?.metadata?.SERVER_ONLY) continue; + const methods2 = Array.isArray(endpoint.options?.method) ? endpoint.options.method : [endpoint.options?.method]; + for (const method of methods2) addRoute(router2, method, endpoint.path, endpoint); + } + if (config4?.routerMiddleware?.length) for (const { path: path3, middleware } of config4.routerMiddleware) addRoute(middlewareRouter, "*", path3, middleware); + const processRequest = async (request) => { + const url2 = new URL(request.url); + const pathname = url2.pathname; + const path3 = config4?.basePath && config4.basePath !== "/" ? pathname.split(config4.basePath).reduce((acc, curr, index) => { + if (index !== 0) if (index > 1) acc.push(`${config4.basePath}${curr}`); + else acc.push(curr); + return acc; + }, []).join("") : url2.pathname; + if (!path3?.length) return new Response(null, { + status: 404, + statusText: "Not Found" + }); + if (/\/{2,}/.test(path3)) return new Response(null, { + status: 404, + statusText: "Not Found" + }); + const route = findRoute(router2, request.method, path3); + if (path3.endsWith("/") !== route?.data?.path?.endsWith("/") && !config4?.skipTrailingSlashes) return new Response(null, { + status: 404, + statusText: "Not Found" + }); + if (!route?.data) return new Response(null, { + status: 404, + statusText: "Not Found" + }); + const query = {}; + url2.searchParams.forEach((value, key) => { + if (key in query) if (Array.isArray(query[key])) query[key].push(value); + else query[key] = [query[key], value]; + else query[key] = value; + }); + const handler = route.data; + try { + const allowedMediaTypes = handler.options.metadata?.allowedMediaTypes || config4?.allowedMediaTypes; + const context = { + path: path3, + method: request.method, + headers: request.headers, + params: route.params ? JSON.parse(JSON.stringify(route.params)) : {}, + request, + body: handler.options.disableBody ? void 0 : await getBody(handler.options.cloneRequest ? request.clone() : request, allowedMediaTypes), + query, + _flag: "router", + asResponse: true, + context: config4?.routerContext + }; + const middlewareRoutes = findAllRoutes(middlewareRouter, "*", path3); + if (middlewareRoutes?.length) for (const { data: middleware, params } of middlewareRoutes) { + const res = await middleware({ + ...context, + params, + asResponse: false + }); + if (res instanceof Response) return res; + } + return await handler(context); + } catch (error49) { + if (config4?.onError) try { + const errorResponse = await config4.onError(error49, request); + if (errorResponse instanceof Response) return toResponse(errorResponse); + } catch (error50) { + if (isAPIError(error50)) return toResponse(error50); + throw error50; + } + if (config4?.throwError) throw error49; + if (isAPIError(error49)) return toResponse(error49); + console.error(`# SERVER_ERROR: `, error49); + return new Response(null, { + status: 500, + statusText: "Internal Server Error" + }); + } + }; + return { + handler: async (request) => { + const onReq = await config4?.onRequest?.(request); + if (onReq instanceof Response) return onReq; + const req = isRequest(onReq) ? onReq : request; + const res = await processRequest(req); + const onRes = await config4?.onResponse?.(res, req); + if (onRes instanceof Response) return onRes; + return res; + }, + endpoints + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-api-error.mjs +function isAPIError2(error49) { + return error49 instanceof APIError || error49 instanceof APIError2 || error49?.name === "APIError"; +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/api/index.mjs +var optionsMiddleware = createMiddleware(async () => { + return {}; +}); +var createAuthMiddleware = createMiddleware.create({ use: [optionsMiddleware, createMiddleware(async () => { + return {}; +})] }); +var use = [optionsMiddleware]; +function createAuthEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { + const path3 = typeof pathOrOptions === "string" ? pathOrOptions : void 0; + const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; + const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; + if (path3) return createEndpoint(path3, { + ...options, + use: [...options?.use || [], ...use] + }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx))); + return createEndpoint({ + ...options, + use: [...options?.use || [], ...use] + }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx))); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/trusted-origins.mjs +var matchesOriginPattern = (url2, pattern, settings) => { + if (url2.startsWith("/")) { + if (settings?.allowRelativePaths) return url2.startsWith("/") && /^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(url2); + return false; + } + if (pattern.includes("*") || pattern.includes("?")) { + if (pattern.includes("://")) return wildcardMatch(pattern)(getOrigin(url2) || url2); + const host = getHost(url2); + if (!host) return false; + return wildcardMatch(pattern)(host); + } + const protocol = getProtocol(url2); + return protocol === "http:" || protocol === "https:" || !protocol ? pattern === getOrigin(url2) : url2.startsWith(pattern); +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/middlewares/origin-check.mjs +init_error2(); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/url.mjs +function normalizePathname(requestUrl, basePath) { + let pathname; + try { + pathname = new URL(requestUrl).pathname.replace(/\/+$/, "") || "/"; + } catch { + return "/"; + } + if (basePath === "/" || basePath === "") return pathname; + if (pathname === basePath) return "/"; + if (pathname.startsWith(basePath + "/")) return pathname.slice(basePath.length).replace(/\/+$/, "") || "/"; + return pathname; +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/deprecate.mjs +function deprecate(fn, message2, logger2) { + let warned = false; + return function(...args) { + if (!warned) { + (logger2?.warn ?? console.warn)(`[Deprecation] ${message2}`); + warned = true; + } + return fn.apply(this, args); + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/middlewares/origin-check.mjs +function shouldSkipCSRFForBackwardCompat(ctx) { + return ctx.context.skipOriginCheck === true && ctx.context.options.advanced?.disableCSRFCheck === void 0; +} +function shouldSkipOriginCheck(ctx) { + const skipOriginCheck = ctx.context.skipOriginCheck; + if (skipOriginCheck === true) return true; + if (Array.isArray(skipOriginCheck) && ctx.request) try { + const basePath = new URL(ctx.context.baseURL).pathname; + const currentPath = normalizePathname(ctx.request.url, basePath); + return skipOriginCheck.some((skipPath) => currentPath.startsWith(skipPath)); + } catch { + } + return false; +} +var logBackwardCompatWarning = deprecate(function logBackwardCompatWarning2() { +}, "disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."); +var originCheckMiddleware = createAuthMiddleware(async (ctx) => { + if (ctx.request?.method === "GET" || ctx.request?.method === "OPTIONS" || ctx.request?.method === "HEAD" || !ctx.request) return; + await validateOrigin(ctx); + if (shouldSkipOriginCheck(ctx)) return; + const { body, query } = ctx; + const callbackURL = body?.callbackURL || query?.callbackURL; + const redirectURL = body?.redirectTo; + const errorCallbackURL = body?.errorCallbackURL; + const newUserCallbackURL = body?.newUserCallbackURL; + const validateURL = (url2, label) => { + if (!url2) return; + if (!ctx.context.isTrustedOrigin(url2, { allowRelativePaths: label !== "origin" })) { + ctx.context.logger.error(`Invalid ${label}: ${url2}`); + ctx.context.logger.info(`If it's a valid URL, please add ${url2} to trustedOrigins in your auth config +`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`); + if (label === "origin") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ORIGIN); + if (label === "callbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_CALLBACK_URL); + if (label === "redirectURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_REDIRECT_URL); + if (label === "errorCallbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL); + if (label === "newUserCallbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL); + throw APIError2.fromStatus("FORBIDDEN", { message: `Invalid ${label}` }); + } + }; + callbackURL && validateURL(callbackURL, "callbackURL"); + redirectURL && validateURL(redirectURL, "redirectURL"); + errorCallbackURL && validateURL(errorCallbackURL, "errorCallbackURL"); + newUserCallbackURL && validateURL(newUserCallbackURL, "newUserCallbackURL"); +}); +var originCheck = (getValue) => createAuthMiddleware(async (ctx) => { + if (!ctx.request) return; + if (shouldSkipOriginCheck(ctx)) return; + const callbackURL = getValue(ctx); + const validateURL = (url2, label) => { + if (!url2) return; + if (!ctx.context.isTrustedOrigin(url2, { allowRelativePaths: label !== "origin" })) { + ctx.context.logger.error(`Invalid ${label}: ${url2}`); + ctx.context.logger.info(`If it's a valid URL, please add ${url2} to trustedOrigins in your auth config +`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`); + if (label === "origin") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ORIGIN); + if (label === "callbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_CALLBACK_URL); + if (label === "redirectURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_REDIRECT_URL); + if (label === "errorCallbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL); + if (label === "newUserCallbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL); + throw APIError2.fromStatus("FORBIDDEN", { message: `Invalid ${label}` }); + } + }; + const callbacks = Array.isArray(callbackURL) ? callbackURL : [callbackURL]; + for (const url2 of callbacks) validateURL(url2, "callbackURL"); +}); +async function validateOrigin(ctx, forceValidate = false) { + const headers = ctx.request?.headers; + if (!headers || !ctx.request) return; + const originHeader = headers.get("origin") || headers.get("referer") || ""; + const useCookies = headers.has("cookie"); + if (ctx.context.skipCSRFCheck) return; + if (shouldSkipCSRFForBackwardCompat(ctx)) { + ctx.context.options.advanced?.disableOriginCheck === true && logBackwardCompatWarning(); + return; + } + if (shouldSkipOriginCheck(ctx)) return; + if (!(forceValidate || useCookies)) return; + if (!originHeader || originHeader === "null") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN); + const trustedOrigins = Array.isArray(ctx.context.options.trustedOrigins) ? ctx.context.trustedOrigins : [...ctx.context.trustedOrigins, ...(await ctx.context.options.trustedOrigins?.(ctx.request))?.filter((v) => Boolean(v)) || []]; + if (!trustedOrigins.some((origin) => matchesOriginPattern(originHeader, origin))) { + ctx.context.logger.error(`Invalid origin: ${originHeader}`); + ctx.context.logger.info(`If it's a valid URL, please add ${originHeader} to trustedOrigins in your auth config +`, `Current list of trustedOrigins: ${trustedOrigins}`); + throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ORIGIN); + } +} +var formCsrfMiddleware = createAuthMiddleware(async (ctx) => { + if (!ctx.request) return; + await validateFormCsrf(ctx); +}); +async function validateFormCsrf(ctx) { + const req = ctx.request; + if (!req) return; + if (ctx.context.skipCSRFCheck) return; + if (shouldSkipCSRFForBackwardCompat(ctx)) return; + const headers = req.headers; + if (headers.has("cookie")) return await validateOrigin(ctx); + const site = headers.get("Sec-Fetch-Site"); + const mode = headers.get("Sec-Fetch-Mode"); + const dest = headers.get("Sec-Fetch-Dest"); + if (Boolean(site && site.trim() || mode && mode.trim() || dest && dest.trim())) { + if (site === "cross-site" && mode === "navigate") { + ctx.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)", { + secFetchSite: site, + secFetchMode: mode, + secFetchDest: dest + }); + throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED); + } + return await validateOrigin(ctx, true); + } +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/get-request-ip.mjs +init_env(); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/ip.mjs +init_zod(); +function isValidIP(ip) { + return ipv42().safeParse(ip).success || ipv62().safeParse(ip).success; +} +function isIPv6(ip) { + return ipv62().safeParse(ip).success; +} +function extractIPv4FromMapped(ipv63) { + const lower = ipv63.toLowerCase(); + if (lower.startsWith("::ffff:")) { + const ipv4Part = lower.substring(7); + if (ipv42().safeParse(ipv4Part).success) return ipv4Part; + } + const parts = ipv63.split(":"); + if (parts.length === 7 && parts[5]?.toLowerCase() === "ffff") { + const ipv4Part = parts[6]; + if (ipv4Part && ipv42().safeParse(ipv4Part).success) return ipv4Part; + } + if (lower.includes("::ffff:") || lower.includes(":ffff:")) { + const groups = expandIPv6(ipv63); + if (groups.length === 8 && groups[0] === "0000" && groups[1] === "0000" && groups[2] === "0000" && groups[3] === "0000" && groups[4] === "0000" && groups[5] === "ffff" && groups[6] && groups[7]) return `${Number.parseInt(groups[6].substring(0, 2), 16)}.${Number.parseInt(groups[6].substring(2, 4), 16)}.${Number.parseInt(groups[7].substring(0, 2), 16)}.${Number.parseInt(groups[7].substring(2, 4), 16)}`; + } + return null; +} +function expandIPv6(ipv63) { + if (ipv63.includes("::")) { + const sides = ipv63.split("::"); + const left = sides[0] ? sides[0].split(":") : []; + const right = sides[1] ? sides[1].split(":") : []; + const missingGroups = 8 - left.length - right.length; + const zeros = Array(missingGroups).fill("0000"); + const paddedLeft = left.map((g) => g.padStart(4, "0")); + const paddedRight = right.map((g) => g.padStart(4, "0")); + return [ + ...paddedLeft, + ...zeros, + ...paddedRight + ]; + } + return ipv63.split(":").map((g) => g.padStart(4, "0")); +} +function normalizeIPv6(ipv63, subnetPrefix) { + const groups = expandIPv6(ipv63); + if (subnetPrefix && subnetPrefix < 128) { + let bitsRemaining = subnetPrefix; + return groups.map((group) => { + if (bitsRemaining <= 0) return "0000"; + if (bitsRemaining >= 16) { + bitsRemaining -= 16; + return group; + } + const masked = Number.parseInt(group, 16) & (65535 << 16 - bitsRemaining & 65535); + bitsRemaining = 0; + return masked.toString(16).padStart(4, "0"); + }).join(":").toLowerCase(); + } + return groups.join(":").toLowerCase(); +} +function normalizeIP(ip, options = {}) { + if (ipv42().safeParse(ip).success) return ip.toLowerCase(); + if (!isIPv6(ip)) return ip.toLowerCase(); + const ipv43 = extractIPv4FromMapped(ip); + if (ipv43) return ipv43.toLowerCase(); + return normalizeIPv6(ip, options.ipv6Subnet || 64); +} +function createRateLimitKey(ip, path3) { + return `${ip}|${path3}`; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/get-request-ip.mjs +var LOCALHOST_IP = "127.0.0.1"; +function getIp(req, options) { + if (options.advanced?.ipAddress?.disableIpTracking) return null; + const headers = "headers" in req ? req.headers : req; + const ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || ["x-forwarded-for"]; + for (const key of ipHeaders) { + const value = "get" in headers ? headers.get(key) : headers[key]; + if (typeof value === "string") { + const ip = value.split(",")[0].trim(); + if (isValidIP(ip)) return normalizeIP(ip, { ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet }); + } + } + if (isTest() || isDevelopment()) return LOCALHOST_IP; + return null; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/rate-limiter/index.mjs +init_json(); +var memory = /* @__PURE__ */ new Map(); +function shouldRateLimit(max, window2, rateLimitData) { + const now2 = Date.now(); + const windowInMs = window2 * 1e3; + return now2 - rateLimitData.lastRequest < windowInMs && rateLimitData.count >= max; +} +function rateLimitResponse(retryAfter) { + return new Response(JSON.stringify({ message: "Too many requests. Please try again later." }), { + status: 429, + statusText: "Too Many Requests", + headers: { "X-Retry-After": retryAfter.toString() } + }); +} +function getRetryAfter(lastRequest, window2) { + const now2 = Date.now(); + const windowInMs = window2 * 1e3; + return Math.ceil((lastRequest + windowInMs - now2) / 1e3); +} +function createDatabaseStorageWrapper(ctx) { + const model = "rateLimit"; + const db = ctx.adapter; + return { + get: async (key) => { + const data = (await db.findMany({ + model, + where: [{ + field: "key", + value: key + }] + }))[0]; + if (typeof data?.lastRequest === "bigint") data.lastRequest = Number(data.lastRequest); + return data; + }, + set: async (key, value, _update) => { + try { + if (_update) await db.updateMany({ + model, + where: [{ + field: "key", + value: key + }], + update: { + count: value.count, + lastRequest: value.lastRequest + } + }); + else await db.create({ + model, + data: { + key, + count: value.count, + lastRequest: value.lastRequest + } + }); + } catch (e) { + ctx.logger.error("Error setting rate limit", e); + } + } + }; +} +function getRateLimitStorage(ctx, rateLimitSettings) { + if (ctx.options.rateLimit?.customStorage) return ctx.options.rateLimit.customStorage; + const storage = ctx.rateLimit.storage; + if (storage === "secondary-storage") return { + get: async (key) => { + const data = await ctx.options.secondaryStorage?.get(key); + return data ? safeJSONParse(data) : null; + }, + set: async (key, value, _update) => { + const ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10; + await ctx.options.secondaryStorage?.set?.(key, JSON.stringify(value), ttl); + } + }; + else if (storage === "memory") return { + async get(key) { + const entry = memory.get(key); + if (!entry) return null; + if (Date.now() >= entry.expiresAt) { + memory.delete(key); + return null; + } + return entry.data; + }, + async set(key, value, _update) { + const ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10; + const expiresAt = Date.now() + ttl * 1e3; + memory.set(key, { + data: value, + expiresAt + }); + } + }; + return createDatabaseStorageWrapper(ctx); +} +var ipWarningLogged = false; +async function resolveRateLimitConfig(req, ctx) { + const basePath = new URL(ctx.baseURL).pathname; + const path3 = normalizePathname(req.url, basePath); + let currentWindow = ctx.rateLimit.window; + let currentMax = ctx.rateLimit.max; + const ip = getIp(req, ctx.options); + if (!ip) { + if (!ipWarningLogged) { + ctx.logger.warn("Rate limiting skipped: could not determine client IP address. Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed."); + ipWarningLogged = true; + } + return null; + } + const key = createRateLimitKey(ip, path3); + const specialRule = getDefaultSpecialRules().find((rule) => rule.pathMatcher(path3)); + if (specialRule) { + currentWindow = specialRule.window; + currentMax = specialRule.max; + } + for (const plugin of ctx.options.plugins || []) if (plugin.rateLimit) { + const matchedRule = plugin.rateLimit.find((rule) => rule.pathMatcher(path3)); + if (matchedRule) { + currentWindow = matchedRule.window; + currentMax = matchedRule.max; + break; + } + } + if (ctx.rateLimit.customRules) { + const _path3 = Object.keys(ctx.rateLimit.customRules).find((p) => { + if (p.includes("*")) return wildcardMatch(p)(path3); + return p === path3; + }); + if (_path3) { + const customRule = ctx.rateLimit.customRules[_path3]; + const resolved = typeof customRule === "function" ? await customRule(req, { + window: currentWindow, + max: currentMax + }) : customRule; + if (resolved) { + currentWindow = resolved.window; + currentMax = resolved.max; + } + if (resolved === false) return null; + } + } + return { + key, + currentWindow, + currentMax + }; +} +async function onRequestRateLimit(req, ctx) { + if (!ctx.rateLimit.enabled) return; + const config4 = await resolveRateLimitConfig(req, ctx); + if (!config4) return; + const { key, currentWindow, currentMax } = config4; + const data = await getRateLimitStorage(ctx, { window: currentWindow }).get(key); + if (data && shouldRateLimit(currentMax, currentWindow, data)) return rateLimitResponse(getRetryAfter(data.lastRequest, currentWindow)); +} +async function onResponseRateLimit(req, ctx) { + if (!ctx.rateLimit.enabled) return; + const config4 = await resolveRateLimitConfig(req, ctx); + if (!config4) return; + const { key, currentWindow } = config4; + const storage = getRateLimitStorage(ctx, { window: currentWindow }); + const data = await storage.get(key); + const now2 = Date.now(); + if (!data) await storage.set(key, { + key, + count: 1, + lastRequest: now2 + }); + else if (now2 - data.lastRequest > currentWindow * 1e3) await storage.set(key, { + ...data, + count: 1, + lastRequest: now2 + }, true); + else await storage.set(key, { + ...data, + count: data.count + 1, + lastRequest: now2 + }, true); +} +function getDefaultSpecialRules() { + return [{ + pathMatcher(path3) { + return path3.startsWith("/sign-in") || path3.startsWith("/sign-up") || path3.startsWith("/change-password") || path3.startsWith("/change-email"); + }, + window: 10, + max: 3 + }, { + pathMatcher(path3) { + return path3 === "/request-password-reset" || path3 === "/send-verification-email" || path3.startsWith("/forget-password") || path3 === "/email-otp/send-verification-otp" || path3 === "/email-otp/request-password-reset"; + }, + window: 60, + max: 3 + }]; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/state/should-session-refresh.mjs +var { get: getShouldSkipSessionRefresh, set: setShouldSkipSessionRefresh } = defineRequestState(() => false); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/session.mjs +init_error2(); +init_json(); +init_zod(); +var getSession = () => createAuthEndpoint("/get-session", { + method: ["GET", "POST"], + operationId: "getSession", + query: getSessionQuerySchema, + requireHeaders: true, + metadata: { openapi: { + operationId: "getSession", + description: "Get the current session", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + nullable: true, + properties: { + session: { $ref: "#/components/schemas/Session" }, + user: { $ref: "#/components/schemas/User" } + }, + required: ["session", "user"] + } } } + } } + } } +}, async (ctx) => { + const deferSessionRefresh = ctx.context.options.session?.deferSessionRefresh; + const isPostRequest = ctx.method === "POST"; + if (isPostRequest && !deferSessionRefresh) throw APIError2.from("METHOD_NOT_ALLOWED", BASE_ERROR_CODES.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED); + try { + const sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret); + if (!sessionCookieToken) return null; + const sessionDataCookie = getChunkedCookie(ctx, ctx.context.authCookies.sessionData.name); + let sessionDataPayload = null; + if (sessionDataCookie) { + const strategy = ctx.context.options.session?.cookieCache?.strategy || "compact"; + if (strategy === "jwe") { + const payload = await symmetricDecodeJWT(sessionDataCookie, ctx.context.secretConfig, "better-auth-session"); + if (payload && payload.session && payload.user) sessionDataPayload = { + session: { + session: payload.session, + user: payload.user, + updatedAt: payload.updatedAt, + version: payload.version + }, + expiresAt: payload.exp ? payload.exp * 1e3 : Date.now() + }; + else { + expireCookie(ctx, ctx.context.authCookies.sessionData); + return ctx.json(null); + } + } else if (strategy === "jwt") { + const payload = await verifyJWT(sessionDataCookie, ctx.context.secret); + if (payload && payload.session && payload.user) sessionDataPayload = { + session: { + session: payload.session, + user: payload.user, + updatedAt: payload.updatedAt, + version: payload.version + }, + expiresAt: payload.exp ? payload.exp * 1e3 : Date.now() + }; + else { + expireCookie(ctx, ctx.context.authCookies.sessionData); + return ctx.json(null); + } + } else { + const parsed = safeJSONParse(binary.decode(base64Url.decode(sessionDataCookie))); + if (parsed) if (await createHMAC("SHA-256", "base64urlnopad").verify(ctx.context.secret, JSON.stringify({ + ...parsed.session, + expiresAt: parsed.expiresAt + }), parsed.signature)) sessionDataPayload = parsed; + else { + expireCookie(ctx, ctx.context.authCookies.sessionData); + return ctx.json(null); + } + } + } + const dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); + if (sessionDataPayload?.session && ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache) { + const session2 = sessionDataPayload.session; + const versionConfig = ctx.context.options.session?.cookieCache?.version; + let expectedVersion = "1"; + if (versionConfig) { + if (typeof versionConfig === "string") expectedVersion = versionConfig; + else if (typeof versionConfig === "function") { + const result = versionConfig(session2.session, session2.user); + expectedVersion = result instanceof Promise ? await result : result; + } + } + if ((session2.version || "1") !== expectedVersion) expireCookie(ctx, ctx.context.authCookies.sessionData); + else { + const cachedSessionExpiresAt = new Date(session2.session.expiresAt); + if (sessionDataPayload.expiresAt < Date.now() || cachedSessionExpiresAt < /* @__PURE__ */ new Date()) expireCookie(ctx, ctx.context.authCookies.sessionData); + else { + const cookieRefreshCache = ctx.context.sessionConfig.cookieRefreshCache; + if (cookieRefreshCache === false) { + ctx.context.session = session2; + const parsedSession3 = parseSessionOutput(ctx.context.options, { + ...session2.session, + expiresAt: new Date(session2.session.expiresAt), + createdAt: new Date(session2.session.createdAt), + updatedAt: new Date(session2.session.updatedAt) + }); + const parsedUser3 = parseUserOutput(ctx.context.options, { + ...session2.user, + createdAt: new Date(session2.user.createdAt), + updatedAt: new Date(session2.user.updatedAt) + }); + return ctx.json({ + session: parsedSession3, + user: parsedUser3 + }); + } + const timeUntilExpiry = sessionDataPayload.expiresAt - Date.now(); + const updateAge2 = cookieRefreshCache.updateAge * 1e3; + const shouldSkipSessionRefresh2 = await getShouldSkipSessionRefresh(); + if (timeUntilExpiry < updateAge2 && !shouldSkipSessionRefresh2) { + const newExpiresAt = getDate(ctx.context.options.session?.cookieCache?.maxAge || 300, "sec"); + const refreshedSession = { + session: { + ...session2.session, + expiresAt: newExpiresAt + }, + user: session2.user, + updatedAt: Date.now() + }; + await setCookieCache(ctx, refreshedSession, false); + const sessionTokenOptions = ctx.context.authCookies.sessionToken.attributes; + const sessionTokenMaxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn; + await ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session2.session.token, ctx.context.secret, { + ...sessionTokenOptions, + maxAge: sessionTokenMaxAge + }); + const parsedRefreshedSession = parseSessionOutput(ctx.context.options, { + ...refreshedSession.session, + expiresAt: new Date(refreshedSession.session.expiresAt), + createdAt: new Date(refreshedSession.session.createdAt), + updatedAt: new Date(refreshedSession.session.updatedAt) + }); + const parsedRefreshedUser = parseUserOutput(ctx.context.options, { + ...refreshedSession.user, + createdAt: new Date(refreshedSession.user.createdAt), + updatedAt: new Date(refreshedSession.user.updatedAt) + }); + ctx.context.session = { + session: parsedRefreshedSession, + user: parsedRefreshedUser + }; + return ctx.json({ + session: parsedRefreshedSession, + user: parsedRefreshedUser + }); + } + const parsedSession2 = parseSessionOutput(ctx.context.options, { + ...session2.session, + expiresAt: new Date(session2.session.expiresAt), + createdAt: new Date(session2.session.createdAt), + updatedAt: new Date(session2.session.updatedAt) + }); + const parsedUser2 = parseUserOutput(ctx.context.options, { + ...session2.user, + createdAt: new Date(session2.user.createdAt), + updatedAt: new Date(session2.user.updatedAt) + }); + ctx.context.session = { + session: parsedSession2, + user: parsedUser2 + }; + return ctx.json({ + session: parsedSession2, + user: parsedUser2 + }); + } + } + } + const session = await ctx.context.internalAdapter.findSession(sessionCookieToken); + ctx.context.session = session; + if (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) { + deleteSessionCookie(ctx); + if (session) { + if (!deferSessionRefresh || isPostRequest) await ctx.context.internalAdapter.deleteSession(session.session.token); + } + return ctx.json(null); + } + if (dontRememberMe || ctx.query?.disableRefresh) { + const parsedSession2 = parseSessionOutput(ctx.context.options, session.session); + const parsedUser2 = parseUserOutput(ctx.context.options, session.user); + return ctx.json({ + session: parsedSession2, + user: parsedUser2 + }); + } + const expiresIn = ctx.context.sessionConfig.expiresIn; + const updateAge = ctx.context.sessionConfig.updateAge; + const shouldBeUpdated = session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3 <= Date.now(); + const disableRefresh = ctx.query?.disableRefresh || ctx.context.options.session?.disableSessionRefresh; + const shouldSkipSessionRefresh = await getShouldSkipSessionRefresh(); + const needsRefresh = shouldBeUpdated && !disableRefresh && !shouldSkipSessionRefresh; + if (deferSessionRefresh && !isPostRequest) { + await setCookieCache(ctx, session, !!dontRememberMe); + const parsedSession2 = parseSessionOutput(ctx.context.options, session.session); + const parsedUser2 = parseUserOutput(ctx.context.options, session.user); + return ctx.json({ + session: parsedSession2, + user: parsedUser2, + needsRefresh + }); + } + if (needsRefresh) { + const updatedSession = await ctx.context.internalAdapter.updateSession(session.session.token, { + expiresAt: getDate(ctx.context.sessionConfig.expiresIn, "sec"), + updatedAt: /* @__PURE__ */ new Date() + }); + if (!updatedSession) { + deleteSessionCookie(ctx); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_GET_SESSION); + } + const maxAge = (updatedSession.expiresAt.valueOf() - Date.now()) / 1e3; + await setSessionCookie(ctx, { + session: updatedSession, + user: session.user + }, false, { maxAge }); + const parsedUpdatedSession = parseSessionOutput(ctx.context.options, updatedSession); + const parsedUser2 = parseUserOutput(ctx.context.options, session.user); + return ctx.json({ + session: parsedUpdatedSession, + user: parsedUser2 + }); + } + await setCookieCache(ctx, session, !!dontRememberMe); + const parsedSession = parseSessionOutput(ctx.context.options, session.session); + const parsedUser = parseUserOutput(ctx.context.options, session.user); + return ctx.json({ + session: parsedSession, + user: parsedUser + }); + } catch (error49) { + if (isAPIError2(error49)) throw error49; + ctx.context.logger.error("INTERNAL_SERVER_ERROR", error49); + throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_GET_SESSION); + } +}); +var getSessionFromCtx = async (ctx, config4) => { + if (ctx.context.session) return ctx.context.session; + const session = await getSession()({ + ...ctx, + method: "GET", + asResponse: false, + headers: ctx.headers, + returnHeaders: false, + returnStatus: false, + query: { + ...config4, + ...ctx.query + } + }).catch((e) => { + return null; + }); + ctx.context.session = session; + return session; +}; +var sessionMiddleware = createAuthMiddleware(async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session?.session) throw APIError2.from("UNAUTHORIZED", { + message: "Unauthorized", + code: "UNAUTHORIZED" + }); + return { session }; +}); +var sensitiveSessionMiddleware = createAuthMiddleware(async (ctx) => { + const session = await getSessionFromCtx(ctx, { disableCookieCache: true }); + if (!session?.session) throw APIError2.from("UNAUTHORIZED", { + message: "Unauthorized", + code: "UNAUTHORIZED" + }); + return { session }; +}); +var requestOnlySessionMiddleware = createAuthMiddleware(async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session?.session && (ctx.request || ctx.headers)) throw APIError2.from("UNAUTHORIZED", { + message: "Unauthorized", + code: "UNAUTHORIZED" + }); + return { session }; +}); +var freshSessionMiddleware = createAuthMiddleware(async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session?.session) throw APIError2.from("UNAUTHORIZED", { + message: "Unauthorized", + code: "UNAUTHORIZED" + }); + if (ctx.context.sessionConfig.freshAge !== 0) { + const createdAt = new Date(session.session.createdAt).getTime(); + const freshAge = ctx.context.sessionConfig.freshAge * 1e3; + if (Date.now() - createdAt >= freshAge) throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.SESSION_NOT_FRESH); + } + return { session }; +}); +var listSessions = () => createAuthEndpoint("/list-sessions", { + method: "GET", + operationId: "listUserSessions", + use: [sessionMiddleware], + requireHeaders: true, + metadata: { openapi: { + operationId: "listUserSessions", + description: "List all active sessions for the user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "array", + items: { $ref: "#/components/schemas/Session" } + } } } + } } + } } +}, async (ctx) => { + try { + const activeSessions = (await ctx.context.internalAdapter.listSessions(ctx.context.session.user.id, { onlyActiveSessions: true })).filter((session) => { + return session.expiresAt > /* @__PURE__ */ new Date(); + }); + return ctx.json(activeSessions.map((session) => parseSessionOutput(ctx.context.options, session))); + } catch (e) { + ctx.context.logger.error(e); + throw ctx.error("INTERNAL_SERVER_ERROR"); + } +}); +var revokeSession = createAuthEndpoint("/revoke-session", { + method: "POST", + body: object({ token: string2().meta({ description: "The token to revoke" }) }), + use: [sensitiveSessionMiddleware], + requireHeaders: true, + metadata: { openapi: { + description: "Revoke a single session", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { token: { + type: "string", + description: "The token to revoke" + } }, + required: ["token"] + } } } }, + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { + type: "boolean", + description: "Indicates if the session was revoked successfully" + } }, + required: ["status"] + } } } + } } + } } +}, async (ctx) => { + const token = ctx.body.token; + if ((await ctx.context.internalAdapter.findSession(token))?.session.userId === ctx.context.session.user.id) try { + await ctx.context.internalAdapter.deleteSession(token); + } catch (error49) { + ctx.context.logger.error(error49 && typeof error49 === "object" && "name" in error49 ? error49.name : "", error49); + throw APIError2.from("INTERNAL_SERVER_ERROR", { + message: "Internal Server Error", + code: "INTERNAL_SERVER_ERROR" + }); + } + return ctx.json({ status: true }); +}); +var revokeSessions = createAuthEndpoint("/revoke-sessions", { + method: "POST", + use: [sensitiveSessionMiddleware], + requireHeaders: true, + metadata: { openapi: { + description: "Revoke all sessions for the user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { + type: "boolean", + description: "Indicates if all sessions were revoked successfully" + } }, + required: ["status"] + } } } + } } + } } +}, async (ctx) => { + try { + await ctx.context.internalAdapter.deleteSessions(ctx.context.session.user.id); + } catch (error49) { + ctx.context.logger.error(error49 && typeof error49 === "object" && "name" in error49 ? error49.name : "", error49); + throw APIError2.from("INTERNAL_SERVER_ERROR", { + message: "Internal Server Error", + code: "INTERNAL_SERVER_ERROR" + }); + } + return ctx.json({ status: true }); +}); +var revokeOtherSessions = createAuthEndpoint("/revoke-other-sessions", { + method: "POST", + requireHeaders: true, + use: [sensitiveSessionMiddleware], + metadata: { openapi: { + description: "Revoke all other sessions for the user except the current one", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { + type: "boolean", + description: "Indicates if all other sessions were revoked successfully" + } }, + required: ["status"] + } } } + } } + } } +}, async (ctx) => { + const session = ctx.context.session; + if (!session.user) throw APIError2.from("UNAUTHORIZED", { + message: "Unauthorized", + code: "UNAUTHORIZED" + }); + const otherSessions = (await ctx.context.internalAdapter.listSessions(session.user.id)).filter((session2) => { + return session2.expiresAt > /* @__PURE__ */ new Date(); + }).filter((session2) => session2.token !== ctx.context.session.session.token); + await Promise.all(otherSessions.map((session2) => ctx.context.internalAdapter.deleteSession(session2.token))); + return ctx.json({ status: true }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/verification-token-storage.mjs +var defaultKeyHasher = async (identifier) => { + const hash2 = await createHash("SHA-256").digest(new TextEncoder().encode(identifier)); + return base64Url.encode(new Uint8Array(hash2), { padding: false }); +}; +async function processIdentifier(identifier, option) { + if (!option || option === "plain") return identifier; + if (option === "hashed") return defaultKeyHasher(identifier); + if (typeof option === "object" && "hash" in option) return option.hash(identifier); + return identifier; +} +function getStorageOption(identifier, config4) { + if (!config4) return; + if (typeof config4 === "object" && "default" in config4) { + if (config4.overrides) { + for (const [prefix, option] of Object.entries(config4.overrides)) if (identifier.startsWith(prefix)) return option; + } + return config4.default; + } + return config4; +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/index.mjs +init_attributes(); +init_tracer(); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/with-hooks.mjs +function getWithHooks(adapter, ctx) { + const hooksEntries = ctx.hooks; + async function createWithHooks(data, model, customCreateFn) { + const context = await getCurrentAuthContext().catch(() => null); + let actualData = data; + for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.create?.before; + if (toRun) { + const result = await withSpan(`db create.before ${model}`, { + [ATTR_HOOK_TYPE]: "create.before", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(actualData, context)); + if (result === false) return null; + if (typeof result === "object" && "data" in result) actualData = { + ...actualData, + ...result.data + }; + } + } + let created = null; + if (!customCreateFn || customCreateFn.executeMainFn) created = await (await getCurrentAdapter(adapter)).create({ + model, + data: actualData, + forceAllowId: true + }); + if (customCreateFn?.fn) created = await customCreateFn.fn(created ?? actualData); + for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.create?.after; + if (toRun) await queueAfterTransactionHook(async () => { + await withSpan(`db create.after ${model}`, { + [ATTR_HOOK_TYPE]: "create.after", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(created, context)); + }); + } + return created; + } + async function updateWithHooks(data, where, model, customUpdateFn) { + const context = await getCurrentAuthContext().catch(() => null); + let actualData = data; + for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.update?.before; + if (toRun) { + const result = await withSpan(`db update.before ${model}`, { + [ATTR_HOOK_TYPE]: "update.before", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(data, context)); + if (result === false) return null; + if (typeof result === "object" && "data" in result) actualData = { + ...actualData, + ...result.data + }; + } + } + const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null; + const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).update({ + model, + update: actualData, + where + }) : customUpdated; + for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.update?.after; + if (toRun) await queueAfterTransactionHook(async () => { + await withSpan(`db update.after ${model}`, { + [ATTR_HOOK_TYPE]: "update.after", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(updated, context)); + }); + } + return updated; + } + async function updateManyWithHooks(data, where, model, customUpdateFn) { + const context = await getCurrentAuthContext().catch(() => null); + let actualData = data; + for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.update?.before; + if (toRun) { + const result = await withSpan(`db updateMany.before ${model}`, { + [ATTR_HOOK_TYPE]: "updateMany.before", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(data, context)); + if (result === false) return null; + if (typeof result === "object" && "data" in result) actualData = { + ...actualData, + ...result.data + }; + } + } + const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null; + const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).updateMany({ + model, + update: actualData, + where + }) : customUpdated; + for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.update?.after; + if (toRun) await queueAfterTransactionHook(async () => { + await withSpan(`db updateMany.after ${model}`, { + [ATTR_HOOK_TYPE]: "updateMany.after", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(updated, context)); + }); + } + return updated; + } + async function deleteWithHooks(where, model, customDeleteFn) { + const context = await getCurrentAuthContext().catch(() => null); + let entityToDelete = null; + try { + entityToDelete = (await (await getCurrentAdapter(adapter)).findMany({ + model, + where, + limit: 1 + }))[0] || null; + } catch { + } + if (entityToDelete) for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.delete?.before; + if (toRun) { + if (await withSpan(`db delete.before ${model}`, { + [ATTR_HOOK_TYPE]: "delete.before", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(entityToDelete, context)) === false) return null; + } + } + const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null; + const deleted = (!customDeleteFn || customDeleteFn.executeMainFn) && entityToDelete ? await (await getCurrentAdapter(adapter)).delete({ + model, + where + }) : customDeleted; + if (entityToDelete) for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.delete?.after; + if (toRun) await queueAfterTransactionHook(async () => { + await withSpan(`db delete.after ${model}`, { + [ATTR_HOOK_TYPE]: "delete.after", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(entityToDelete, context)); + }); + } + return deleted; + } + async function deleteManyWithHooks(where, model, customDeleteFn) { + const context = await getCurrentAuthContext().catch(() => null); + let entitiesToDelete = []; + try { + entitiesToDelete = await (await getCurrentAdapter(adapter)).findMany({ + model, + where + }); + } catch { + } + for (const entity of entitiesToDelete) for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.delete?.before; + if (toRun) { + if (await withSpan(`db delete.before ${model}`, { + [ATTR_HOOK_TYPE]: "delete.before", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(entity, context)) === false) return null; + } + } + const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null; + const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await (await getCurrentAdapter(adapter)).deleteMany({ + model, + where + }) : customDeleted; + for (const entity of entitiesToDelete) for (const { source, hooks } of hooksEntries) { + const toRun = hooks[model]?.delete?.after; + if (toRun) await queueAfterTransactionHook(async () => { + await withSpan(`db delete.after ${model}`, { + [ATTR_HOOK_TYPE]: "delete.after", + [ATTR_DB_COLLECTION_NAME]: model, + [ATTR_CONTEXT]: source + }, () => toRun(entity, context)); + }); + } + return deleted; + } + return { + createWithHooks, + updateWithHooks, + updateManyWithHooks, + deleteWithHooks, + deleteManyWithHooks + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/internal-adapter.mjs +init_id2(); +init_json(); +function getTTLSeconds(expiresAt, now2 = Date.now()) { + const expiresMs = typeof expiresAt === "number" ? expiresAt : expiresAt.getTime(); + return Math.max(Math.floor((expiresMs - now2) / 1e3), 0); +} +var createInternalAdapter = (adapter, ctx) => { + const logger2 = ctx.logger; + const options = ctx.options; + const secondaryStorage = options.secondaryStorage; + const sessionExpiration = options.session?.expiresIn || 3600 * 24 * 7; + const { createWithHooks, updateWithHooks, updateManyWithHooks, deleteWithHooks, deleteManyWithHooks } = getWithHooks(adapter, ctx); + async function refreshUserSessions(user) { + if (!secondaryStorage) return; + const listRaw = await secondaryStorage.get(`active-sessions-${user.id}`); + if (!listRaw) return; + const now2 = Date.now(); + const validSessions = (safeJSONParse(listRaw) || []).filter((s) => s.expiresAt > now2); + await Promise.all(validSessions.map(async ({ token }) => { + const cached2 = await secondaryStorage.get(token); + if (!cached2) return; + const parsed = safeJSONParse(cached2); + if (!parsed) return; + const sessionTTL = getTTLSeconds(parsed.session.expiresAt, now2); + await secondaryStorage.set(token, JSON.stringify({ + session: parsed.session, + user + }), Math.floor(sessionTTL)); + })); + } + return { + createOAuthUser: async (user, account) => { + return runWithTransaction(adapter, async () => { + const createdUser = await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...user + }, "user", void 0); + return { + user: createdUser, + account: await createWithHooks({ + ...account, + userId: createdUser.id, + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }, "account", void 0) + }; + }); + }, + createUser: async (user) => { + return await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...user, + email: user.email?.toLowerCase() + }, "user", void 0); + }, + createAccount: async (account) => { + return await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...account + }, "account", void 0); + }, + listSessions: async (userId, options2) => { + if (secondaryStorage) { + const currentList = await secondaryStorage.get(`active-sessions-${userId}`); + if (!currentList) return []; + const list = safeJSONParse(currentList) || []; + const now2 = Date.now(); + const seenTokens = /* @__PURE__ */ new Set(); + const sessions = []; + for (const { token, expiresAt } of list) { + if (expiresAt <= now2 || seenTokens.has(token)) continue; + seenTokens.add(token); + const data = await secondaryStorage.get(token); + if (!data) continue; + try { + const parsed = typeof data === "string" ? JSON.parse(data) : data; + if (!parsed?.session) continue; + sessions.push(parseSessionOutput(ctx.options, { + ...parsed.session, + expiresAt: new Date(parsed.session.expiresAt) + })); + } catch { + continue; + } + } + return sessions; + } + return await (await getCurrentAdapter(adapter)).findMany({ + model: "session", + where: [{ + field: "userId", + value: userId + }, ...options2?.onlyActiveSessions ? [{ + field: "expiresAt", + value: /* @__PURE__ */ new Date(), + operator: "gt" + }] : []] + }); + }, + listUsers: async (limit, offset, sortBy, where) => { + return await (await getCurrentAdapter(adapter)).findMany({ + model: "user", + limit, + offset, + sortBy, + where + }); + }, + countTotalUsers: async (where) => { + const total = await (await getCurrentAdapter(adapter)).count({ + model: "user", + where + }); + if (typeof total === "string") return parseInt(total); + return total; + }, + deleteUser: async (userId) => { + if (!secondaryStorage || options.session?.storeSessionInDatabase) await deleteManyWithHooks([{ + field: "userId", + value: userId + }], "session", void 0); + await deleteManyWithHooks([{ + field: "userId", + value: userId + }], "account", void 0); + await deleteWithHooks([{ + field: "id", + value: userId + }], "user", void 0); + }, + createSession: async (userId, dontRememberMe, override, overrideAll) => { + const headers = await (async () => { + const ctx2 = await getCurrentAuthContext().catch(() => null); + return ctx2?.headers || ctx2?.request?.headers; + })(); + const storeInDb = options.session?.storeSessionInDatabase; + const { id: _, ...rest } = override || {}; + let sessionId; + if (secondaryStorage && !storeInDb) { + const generatedId = ctx.generateId({ model: "session" }); + sessionId = generatedId !== false ? generatedId : generateId(); + } + const defaultAdditionalFields = getSessionDefaultFields(options); + const data = { + ...sessionId ? { id: sessionId } : {}, + ipAddress: headers ? getIp(headers, options) || "" : "", + userAgent: headers?.get("user-agent") || "", + ...rest, + expiresAt: dontRememberMe ? getDate(3600 * 24, "sec") : getDate(sessionExpiration, "sec"), + userId, + token: generateId(32), + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...defaultAdditionalFields, + ...overrideAll ? rest : {} + }; + return await createWithHooks(data, "session", secondaryStorage ? { + fn: async (sessionData) => { + const currentList = await secondaryStorage.get(`active-sessions-${userId}`); + let list = []; + const now2 = Date.now(); + if (currentList) { + list = safeJSONParse(currentList) || []; + list = list.filter((session) => session.expiresAt > now2 && session.token !== data.token); + } + const sorted = [...list, { + token: data.token, + expiresAt: data.expiresAt.getTime() + }].sort((a, b) => a.expiresAt - b.expiresAt); + const furthestSessionTTL = getTTLSeconds(sorted.at(-1)?.expiresAt ?? data.expiresAt.getTime(), now2); + if (furthestSessionTTL > 0) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(sorted), furthestSessionTTL); + const user = await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + field: "id", + value: userId + }] + }); + const sessionTTL = getTTLSeconds(data.expiresAt, now2); + if (sessionTTL > 0) await secondaryStorage.set(data.token, JSON.stringify({ + session: sessionData, + user + }), sessionTTL); + return sessionData; + }, + executeMainFn: storeInDb + } : void 0); + }, + findSession: async (token) => { + if (secondaryStorage) { + const sessionStringified = await secondaryStorage.get(token); + if (!sessionStringified && (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase)) return null; + if (sessionStringified) { + const s = safeJSONParse(sessionStringified); + if (!s) return null; + return { + session: parseSessionOutput(ctx.options, { + ...s.session, + expiresAt: new Date(s.session.expiresAt), + createdAt: new Date(s.session.createdAt), + updatedAt: new Date(s.session.updatedAt) + }), + user: parseUserOutput(ctx.options, { + ...s.user, + createdAt: new Date(s.user.createdAt), + updatedAt: new Date(s.user.updatedAt) + }) + }; + } + } + const result = await (await getCurrentAdapter(adapter)).findOne({ + model: "session", + where: [{ + value: token, + field: "token" + }], + join: { user: true } + }); + if (!result) return null; + const { user, ...session } = result; + if (!user) return null; + return { + session: parseSessionOutput(ctx.options, session), + user: parseUserOutput(ctx.options, user) + }; + }, + findSessions: async (sessionTokens, options2) => { + if (secondaryStorage) { + const sessions2 = []; + for (const sessionToken of sessionTokens) { + const sessionStringified = await secondaryStorage.get(sessionToken); + if (sessionStringified) try { + const s = typeof sessionStringified === "string" ? JSON.parse(sessionStringified) : sessionStringified; + if (!s) return []; + const expiresAt = new Date(s.session.expiresAt); + if (options2?.onlyActiveSessions && expiresAt <= /* @__PURE__ */ new Date()) continue; + const session = { + session: { + ...s.session, + expiresAt: new Date(s.session.expiresAt) + }, + user: { + ...s.user, + createdAt: new Date(s.user.createdAt), + updatedAt: new Date(s.user.updatedAt) + } + }; + sessions2.push(session); + } catch { + continue; + } + } + return sessions2; + } + const sessions = await (await getCurrentAdapter(adapter)).findMany({ + model: "session", + where: [{ + field: "token", + value: sessionTokens, + operator: "in" + }, ...options2?.onlyActiveSessions ? [{ + field: "expiresAt", + value: /* @__PURE__ */ new Date(), + operator: "gt" + }] : []], + join: { user: true } + }); + if (!sessions.length) return []; + if (sessions.some((session) => !session.user)) return []; + return sessions.map((_session) => { + const { user, ...session } = _session; + return { + session, + user + }; + }); + }, + updateSession: async (sessionToken, session) => { + return await updateWithHooks(session, [{ + field: "token", + value: sessionToken + }], "session", secondaryStorage ? { + async fn(data) { + const currentSession = await secondaryStorage.get(sessionToken); + if (!currentSession) return null; + const parsedSession = safeJSONParse(currentSession); + if (!parsedSession) return null; + const mergedSession = { + ...parsedSession.session, + ...data, + expiresAt: new Date(data.expiresAt ?? parsedSession.session.expiresAt), + createdAt: new Date(parsedSession.session.createdAt), + updatedAt: new Date(data.updatedAt ?? parsedSession.session.updatedAt) + }; + const updatedSession = parseSessionOutput(ctx.options, mergedSession); + const now2 = Date.now(); + const expiresMs = new Date(updatedSession.expiresAt).getTime(); + const sessionTTL = getTTLSeconds(expiresMs, now2); + if (sessionTTL > 0) { + await secondaryStorage.set(sessionToken, JSON.stringify({ + session: updatedSession, + user: parsedSession.user + }), sessionTTL); + const listKey = `active-sessions-${updatedSession.userId}`; + const listRaw = await secondaryStorage.get(listKey); + const sorted = (listRaw ? safeJSONParse(listRaw) || [] : []).filter((s) => s.token !== sessionToken && s.expiresAt > now2).concat([{ + token: sessionToken, + expiresAt: expiresMs + }]).sort((a, b) => a.expiresAt - b.expiresAt); + const furthestSessionExp = sorted.at(-1)?.expiresAt; + if (furthestSessionExp && furthestSessionExp > now2) await secondaryStorage.set(listKey, JSON.stringify(sorted), getTTLSeconds(furthestSessionExp, now2)); + else await secondaryStorage.delete(listKey); + } + return updatedSession; + }, + executeMainFn: options.session?.storeSessionInDatabase + } : void 0); + }, + deleteSession: async (token) => { + if (secondaryStorage) { + const data = await secondaryStorage.get(token); + if (data) { + const { session } = safeJSONParse(data) ?? {}; + if (!session) { + logger2.error("Session not found in secondary storage"); + return; + } + const userId = session.userId; + const currentList = await secondaryStorage.get(`active-sessions-${userId}`); + if (currentList) { + const list = safeJSONParse(currentList) || []; + const now2 = Date.now(); + const filtered = list.filter((session2) => session2.expiresAt > now2 && session2.token !== token); + const furthestSessionExp = filtered.sort((a, b) => a.expiresAt - b.expiresAt).at(-1)?.expiresAt; + if (filtered.length > 0 && furthestSessionExp && furthestSessionExp > Date.now()) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(filtered), getTTLSeconds(furthestSessionExp, now2)); + else await secondaryStorage.delete(`active-sessions-${userId}`); + } else logger2.error("Active sessions list not found in secondary storage"); + } + await secondaryStorage.delete(token); + if (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return; + } + await deleteWithHooks([{ + field: "token", + value: token + }], "session", void 0); + }, + deleteAccounts: async (userId) => { + await deleteManyWithHooks([{ + field: "userId", + value: userId + }], "account", void 0); + }, + deleteAccount: async (accountId) => { + await deleteWithHooks([{ + field: "id", + value: accountId + }], "account", void 0); + }, + deleteSessions: async (userIdOrSessionTokens) => { + if (secondaryStorage) { + if (typeof userIdOrSessionTokens === "string") { + const activeSession = await secondaryStorage.get(`active-sessions-${userIdOrSessionTokens}`); + const sessions = activeSession ? safeJSONParse(activeSession) : []; + if (!sessions) return; + for (const session of sessions) await secondaryStorage.delete(session.token); + await secondaryStorage.delete(`active-sessions-${userIdOrSessionTokens}`); + } else for (const sessionToken of userIdOrSessionTokens) if (await secondaryStorage.get(sessionToken)) await secondaryStorage.delete(sessionToken); + if (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return; + } + await deleteManyWithHooks([{ + field: Array.isArray(userIdOrSessionTokens) ? "token" : "userId", + value: userIdOrSessionTokens, + operator: Array.isArray(userIdOrSessionTokens) ? "in" : void 0 + }], "session", void 0); + }, + findOAuthUser: async (email3, accountId, providerId) => { + const account = await (await getCurrentAdapter(adapter)).findOne({ + model: "account", + where: [{ + value: accountId, + field: "accountId" + }, { + value: providerId, + field: "providerId" + }], + join: { user: true } + }); + if (account) if (account.user) return { + user: account.user, + linkedAccount: account, + accounts: [account] + }; + else { + const user = await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + value: email3.toLowerCase(), + field: "email" + }] + }); + if (user) return { + user, + linkedAccount: account, + accounts: [account] + }; + return null; + } + else { + const user = await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + value: email3.toLowerCase(), + field: "email" + }] + }); + if (user) return { + user, + linkedAccount: null, + accounts: await (await getCurrentAdapter(adapter)).findMany({ + model: "account", + where: [{ + value: user.id, + field: "userId" + }] + }) || [] + }; + else return null; + } + }, + findUserByEmail: async (email3, options2) => { + const result = await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + value: email3.toLowerCase(), + field: "email" + }], + join: { ...options2?.includeAccounts ? { account: true } : {} } + }); + if (!result) return null; + const { account: accounts2, ...user } = result; + return { + user, + accounts: accounts2 ?? [] + }; + }, + findUserById: async (userId) => { + if (!userId) return null; + return await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + field: "id", + value: userId + }] + }); + }, + linkAccount: async (account) => { + return await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...account + }, "account", void 0); + }, + updateUser: async (userId, data) => { + const user = await updateWithHooks(data, [{ + field: "id", + value: userId + }], "user", void 0); + await refreshUserSessions(user); + return user; + }, + updateUserByEmail: async (email3, data) => { + const user = await updateWithHooks(data, [{ + field: "email", + value: email3.toLowerCase() + }], "user", void 0); + await refreshUserSessions(user); + return user; + }, + updatePassword: async (userId, password) => { + await updateManyWithHooks({ password }, [{ + field: "userId", + value: userId + }, { + field: "providerId", + value: "credential" + }], "account", void 0); + }, + findAccounts: async (userId) => { + return await (await getCurrentAdapter(adapter)).findMany({ + model: "account", + where: [{ + field: "userId", + value: userId + }] + }); + }, + findAccount: async (accountId) => { + return await (await getCurrentAdapter(adapter)).findOne({ + model: "account", + where: [{ + field: "accountId", + value: accountId + }] + }); + }, + findAccountByProviderId: async (accountId, providerId) => { + return await (await getCurrentAdapter(adapter)).findOne({ + model: "account", + where: [{ + field: "accountId", + value: accountId + }, { + field: "providerId", + value: providerId + }] + }); + }, + findAccountByUserId: async (userId) => { + return await (await getCurrentAdapter(adapter)).findMany({ + model: "account", + where: [{ + field: "userId", + value: userId + }] + }); + }, + updateAccount: async (id, data) => { + return await updateWithHooks(data, [{ + field: "id", + value: id + }], "account", void 0); + }, + createVerificationValue: async (data) => { + const storageOption = getStorageOption(data.identifier, options.verification?.storeIdentifier); + const storedIdentifier = await processIdentifier(data.identifier, storageOption); + return await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...data, + identifier: storedIdentifier + }, "verification", secondaryStorage ? { + async fn(verificationData) { + const ttl = getTTLSeconds(verificationData.expiresAt); + if (ttl > 0) await secondaryStorage.set(`verification:${storedIdentifier}`, JSON.stringify(verificationData), ttl); + return verificationData; + }, + executeMainFn: options.verification?.storeInDatabase + } : void 0); + }, + findVerificationValue: async (identifier) => { + const storageOption = getStorageOption(identifier, options.verification?.storeIdentifier); + const storedIdentifier = await processIdentifier(identifier, storageOption); + if (secondaryStorage) { + const cached2 = await secondaryStorage.get(`verification:${storedIdentifier}`); + if (cached2) { + const parsed = safeJSONParse(cached2); + if (parsed) return parsed; + } + if (storageOption && storageOption !== "plain") { + const plainCached = await secondaryStorage.get(`verification:${identifier}`); + if (plainCached) { + const parsed = safeJSONParse(plainCached); + if (parsed) return parsed; + } + } + if (!options.verification?.storeInDatabase) return null; + } + const currentAdapter = await getCurrentAdapter(adapter); + async function findByIdentifier(id) { + return currentAdapter.findMany({ + model: "verification", + where: [{ + field: "identifier", + value: id + }], + sortBy: { + field: "createdAt", + direction: "desc" + }, + limit: 1 + }); + } + let verification = await findByIdentifier(storedIdentifier); + if (!verification.length && storageOption && storageOption !== "plain") verification = await findByIdentifier(identifier); + if (!options.verification?.disableCleanup) await deleteManyWithHooks([{ + field: "expiresAt", + value: /* @__PURE__ */ new Date(), + operator: "lt" + }], "verification", void 0); + return verification[0] || null; + }, + deleteVerificationByIdentifier: async (identifier) => { + const storedIdentifier = await processIdentifier(identifier, getStorageOption(identifier, options.verification?.storeIdentifier)); + if (secondaryStorage) await secondaryStorage.delete(`verification:${storedIdentifier}`); + if (!secondaryStorage || options.verification?.storeInDatabase) await deleteWithHooks([{ + field: "identifier", + value: storedIdentifier + }], "verification", void 0); + }, + updateVerificationByIdentifier: async (identifier, data) => { + const storedIdentifier = await processIdentifier(identifier, getStorageOption(identifier, options.verification?.storeIdentifier)); + if (secondaryStorage) { + const cached2 = await secondaryStorage.get(`verification:${storedIdentifier}`); + if (cached2) { + const parsed = safeJSONParse(cached2); + if (parsed) { + const updated = { + ...parsed, + ...data + }; + const expiresAt = updated.expiresAt ?? parsed.expiresAt; + const ttl = getTTLSeconds(expiresAt instanceof Date ? expiresAt : new Date(expiresAt)); + if (ttl > 0) await secondaryStorage.set(`verification:${storedIdentifier}`, JSON.stringify(updated), ttl); + if (!options.verification?.storeInDatabase) return updated; + } + } + } + if (!secondaryStorage || options.verification?.storeInDatabase) return await updateWithHooks(data, [{ + field: "identifier", + value: storedIdentifier + }], "verification", void 0); + return data; + } + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/helpers.mjs +init_env(); + +// ../../node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs +function isPlainObject2(value) { + if (value === null || typeof value !== "object") { + return false; + } + const prototype = Object.getPrototypeOf(value); + if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) { + return false; + } + if (Symbol.iterator in value) { + return false; + } + if (Symbol.toStringTag in value) { + return Object.prototype.toString.call(value) === "[object Module]"; + } + return true; +} +function _defu(baseObject, defaults, namespace = ".", merger) { + if (!isPlainObject2(defaults)) { + return _defu(baseObject, {}, namespace, merger); + } + const object2 = { ...defaults }; + for (const key of Object.keys(baseObject)) { + if (key === "__proto__" || key === "constructor") { + continue; + } + const value = baseObject[key]; + if (value === null || value === void 0) { + continue; + } + if (merger && merger(object2, key, value, namespace)) { + continue; + } + if (Array.isArray(value) && Array.isArray(object2[key])) { + object2[key] = [...value, ...object2[key]]; + } else if (isPlainObject2(value) && isPlainObject2(object2[key])) { + object2[key] = _defu( + value, + object2[key], + (namespace ? `${namespace}.` : "") + key.toString(), + merger + ); + } else { + object2[key] = value; + } + } + return object2; +} +function createDefu(merger) { + return (...arguments_) => ( + // eslint-disable-next-line unicorn/no-array-reduce + arguments_.reduce((p, c) => _defu(p, c, "", merger), {}) + ); +} +var defu = createDefu(); +var defuFn = createDefu((object2, key, currentValue) => { + if (object2[key] !== void 0 && typeof currentValue === "function") { + object2[key] = currentValue(object2[key]); + return true; + } +}); +var defuArrayFn = createDefu((object2, key, currentValue) => { + if (Array.isArray(object2[key]) && typeof currentValue === "function") { + object2[key] = currentValue(object2[key]); + return true; + } +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/helpers.mjs +async function runPluginInit(context) { + let options = context.options; + const plugins = options.plugins || []; + const pluginTrustedOrigins = []; + const dbHooks = []; + for (const plugin of plugins) if (plugin.init) { + const initPromise = plugin.init(context); + let result; + if (isPromise(initPromise)) result = await initPromise; + else result = initPromise; + if (typeof result === "object") { + if (result.options) { + const { databaseHooks, trustedOrigins, ...restOpts } = result.options; + if (databaseHooks) dbHooks.push({ + source: `plugin:${plugin.id}`, + hooks: databaseHooks + }); + if (trustedOrigins) pluginTrustedOrigins.push(trustedOrigins); + options = defu(options, restOpts); + } + if (result.context) Object.assign(context, result.context); + } + } + if (pluginTrustedOrigins.length > 0) { + const allSources = [...options.trustedOrigins ? [options.trustedOrigins] : [], ...pluginTrustedOrigins]; + const staticOrigins = allSources.filter(Array.isArray).flat(); + const dynamicOrigins = allSources.filter((s) => typeof s === "function"); + if (dynamicOrigins.length > 0) options.trustedOrigins = async (request) => { + const resolved = await Promise.all(dynamicOrigins.map((fn) => fn(request))); + return [...staticOrigins, ...resolved.flat()].filter((v) => typeof v === "string" && v !== ""); + }; + else options.trustedOrigins = staticOrigins; + } + if (options.databaseHooks) dbHooks.push({ + source: "user", + hooks: options.databaseHooks + }); + context.internalAdapter = createInternalAdapter(context.adapter, { + options, + logger: context.logger, + hooks: dbHooks, + generateId: context.generateId + }); + context.options = options; +} +function getInternalPlugins(options) { + const plugins = []; + if (options.advanced?.crossSubDomainCookies?.enabled) { + } + return plugins; +} +async function getTrustedOrigins(options, request) { + const trustedOrigins = []; + if (isDynamicBaseURLConfig(options.baseURL)) { + const allowedHosts = options.baseURL.allowedHosts; + for (const host of allowedHosts) if (!host.includes("://")) { + trustedOrigins.push(`https://${host}`); + if (host.includes("localhost") || host.includes("127.0.0.1")) trustedOrigins.push(`http://${host}`); + } else trustedOrigins.push(host); + if (options.baseURL.fallback) try { + trustedOrigins.push(new URL(options.baseURL.fallback).origin); + } catch { + } + } else { + const baseURL = getBaseURL(typeof options.baseURL === "string" ? options.baseURL : void 0, options.basePath, request); + if (baseURL) trustedOrigins.push(new URL(baseURL).origin); + } + if (options.trustedOrigins) { + if (Array.isArray(options.trustedOrigins)) trustedOrigins.push(...options.trustedOrigins); + if (typeof options.trustedOrigins === "function") { + const validOrigins = await options.trustedOrigins(request); + trustedOrigins.push(...validOrigins); + } + } + const envTrustedOrigins = env.BETTER_AUTH_TRUSTED_ORIGINS; + if (envTrustedOrigins) trustedOrigins.push(...envTrustedOrigins.split(",")); + return trustedOrigins.filter((v) => Boolean(v)); +} +async function getAwaitableValue(arr, item) { + if (!arr) return void 0; + for (const val of arr) { + const value = typeof val === "function" ? await val() : val; + if (value[item.field ?? "id"] === item.value) return value; + } +} +async function getTrustedProviders(options, request) { + const trustedProviders = options.account?.accountLinking?.trustedProviders; + if (!trustedProviders) return []; + if (Array.isArray(trustedProviders)) return trustedProviders.filter((v) => Boolean(v)); + return (await trustedProviders(request) ?? []).filter((v) => Boolean(v)); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/utils.mjs +function isLikelyEncrypted(token) { + if (token.startsWith("$ba$")) return true; + return token.length % 2 === 0 && /^[0-9a-f]+$/i.test(token); +} +function decryptOAuthToken(token, ctx) { + if (!token) return token; + if (ctx.options.account?.encryptOAuthTokens) { + if (!isLikelyEncrypted(token)) return token; + return symmetricDecrypt({ + key: ctx.secretConfig, + data: token + }); + } + return token; +} +function setTokenUtil(token, ctx) { + if (ctx.options.account?.encryptOAuthTokens && token) return symmetricEncrypt({ + key: ctx.secretConfig, + data: token + }); + return token; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/account.mjs +init_error2(); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/apple.mjs +init_error2(); + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/utils.mjs +function getOAuth2Tokens(data) { + const getDate2 = (seconds) => { + const now2 = /* @__PURE__ */ new Date(); + return new Date(now2.getTime() + seconds * 1e3); + }; + return { + tokenType: data.token_type, + accessToken: data.access_token, + refreshToken: data.refresh_token, + accessTokenExpiresAt: data.expires_in ? getDate2(data.expires_in) : void 0, + refreshTokenExpiresAt: data.refresh_token_expires_in ? getDate2(data.refresh_token_expires_in) : void 0, + scopes: data?.scope ? typeof data.scope === "string" ? data.scope.split(" ") : data.scope : [], + idToken: data.id_token, + raw: data + }; +} +async function generateCodeChallenge(codeVerifier) { + const data = new TextEncoder().encode(codeVerifier); + const hash2 = await crypto.subtle.digest("SHA-256", data); + return base64Url.encode(new Uint8Array(hash2), { padding: false }); +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/create-authorization-url.mjs +async function createAuthorizationURL({ id, options, authorizationEndpoint: authorizationEndpoint2, state, codeVerifier, scopes, claims, redirectURI, duration: duration3, prompt, accessType, responseType, display, loginHint, hd, responseMode, additionalParams, scopeJoiner }) { + options = typeof options === "function" ? await options() : options; + const url2 = new URL(options.authorizationEndpoint || authorizationEndpoint2); + url2.searchParams.set("response_type", responseType || "code"); + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + url2.searchParams.set("client_id", primaryClientId); + url2.searchParams.set("state", state); + if (scopes) url2.searchParams.set("scope", scopes.join(scopeJoiner || " ")); + url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); + duration3 && url2.searchParams.set("duration", duration3); + display && url2.searchParams.set("display", display); + loginHint && url2.searchParams.set("login_hint", loginHint); + prompt && url2.searchParams.set("prompt", prompt); + hd && url2.searchParams.set("hd", hd); + accessType && url2.searchParams.set("access_type", accessType); + responseMode && url2.searchParams.set("response_mode", responseMode); + if (codeVerifier) { + const codeChallenge = await generateCodeChallenge(codeVerifier); + url2.searchParams.set("code_challenge_method", "S256"); + url2.searchParams.set("code_challenge", codeChallenge); + } + if (claims) { + const claimsObj = claims.reduce((acc, claim) => { + acc[claim] = null; + return acc; + }, {}); + url2.searchParams.set("claims", JSON.stringify({ id_token: { + email: null, + email_verified: null, + ...claimsObj + } })); + } + if (additionalParams) Object.entries(additionalParams).forEach(([key, value]) => { + url2.searchParams.set(key, value); + }); + return url2; +} + +// ../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/dist/index.js +var __defProp4 = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp2 = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp2.call(b, prop)) + __defNormalProp2(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp2(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var BetterFetchError = class extends Error { + constructor(status, statusText, error49) { + super(statusText || status.toString(), { + cause: error49 + }); + this.status = status; + this.statusText = statusText; + this.error = error49; + Error.captureStackTrace(this, this.constructor); + } +}; +var initializePlugins = async (url2, options) => { + var _a30, _b2, _c, _d, _e, _f; + let opts = options || {}; + const hooks = { + onRequest: [options == null ? void 0 : options.onRequest], + onResponse: [options == null ? void 0 : options.onResponse], + onSuccess: [options == null ? void 0 : options.onSuccess], + onError: [options == null ? void 0 : options.onError], + onRetry: [options == null ? void 0 : options.onRetry] + }; + if (!options || !(options == null ? void 0 : options.plugins)) { + return { + url: url2, + options: opts, + hooks + }; + } + for (const plugin of (options == null ? void 0 : options.plugins) || []) { + if (plugin.init) { + const pluginRes = await ((_a30 = plugin.init) == null ? void 0 : _a30.call(plugin, url2.toString(), options)); + opts = pluginRes.options || opts; + url2 = pluginRes.url; + } + hooks.onRequest.push((_b2 = plugin.hooks) == null ? void 0 : _b2.onRequest); + hooks.onResponse.push((_c = plugin.hooks) == null ? void 0 : _c.onResponse); + hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess); + hooks.onError.push((_e = plugin.hooks) == null ? void 0 : _e.onError); + hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry); + } + return { + url: url2, + options: opts, + hooks + }; +}; +var LinearRetryStrategy = class { + constructor(options) { + this.options = options; + } + shouldAttemptRetry(attempt, response) { + if (this.options.shouldRetry) { + return Promise.resolve( + attempt < this.options.attempts && this.options.shouldRetry(response) + ); + } + return Promise.resolve(attempt < this.options.attempts); + } + getDelay() { + return this.options.delay; + } +}; +var ExponentialRetryStrategy = class { + constructor(options) { + this.options = options; + } + shouldAttemptRetry(attempt, response) { + if (this.options.shouldRetry) { + return Promise.resolve( + attempt < this.options.attempts && this.options.shouldRetry(response) + ); + } + return Promise.resolve(attempt < this.options.attempts); + } + getDelay(attempt) { + const delay = Math.min( + this.options.maxDelay, + this.options.baseDelay * 2 ** attempt + ); + return delay; + } +}; +function createRetryStrategy(options) { + if (typeof options === "number") { + return new LinearRetryStrategy({ + type: "linear", + attempts: options, + delay: 1e3 + }); + } + switch (options.type) { + case "linear": + return new LinearRetryStrategy(options); + case "exponential": + return new ExponentialRetryStrategy(options); + default: + throw new Error("Invalid retry strategy"); + } +} +var getAuthHeader = async (options) => { + const headers = {}; + const getValue = async (value) => typeof value === "function" ? await value() : value; + if (options == null ? void 0 : options.auth) { + if (options.auth.type === "Bearer") { + const token = await getValue(options.auth.token); + if (!token) { + return headers; + } + headers["authorization"] = `Bearer ${token}`; + } else if (options.auth.type === "Basic") { + const [username, password] = await Promise.all([ + getValue(options.auth.username), + getValue(options.auth.password) + ]); + if (!username || !password) { + return headers; + } + headers["authorization"] = `Basic ${btoa(`${username}:${password}`)}`; + } else if (options.auth.type === "Custom") { + const [prefix, value] = await Promise.all([ + getValue(options.auth.prefix), + getValue(options.auth.value) + ]); + if (!value) { + return headers; + } + headers["authorization"] = `${prefix != null ? prefix : ""} ${value}`; + } + } + return headers; +}; +var JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i; +function detectResponseType(request) { + const _contentType = request.headers.get("content-type"); + const textTypes = /* @__PURE__ */ new Set([ + "image/svg", + "application/xml", + "application/xhtml", + "application/html" + ]); + if (!_contentType) { + return "json"; + } + const contentType = _contentType.split(";").shift() || ""; + if (JSON_RE.test(contentType)) { + return "json"; + } + if (textTypes.has(contentType) || contentType.startsWith("text/")) { + return "text"; + } + return "blob"; +} +function isJSONParsable(value) { + try { + JSON.parse(value); + return true; + } catch (error49) { + return false; + } +} +function isJSONSerializable2(value) { + if (value === void 0) { + return false; + } + const t = typeof value; + if (t === "string" || t === "number" || t === "boolean" || t === null) { + return true; + } + if (t !== "object") { + return false; + } + if (Array.isArray(value)) { + return true; + } + if (value.buffer) { + return false; + } + return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; +} +function jsonParse(text) { + try { + return JSON.parse(text); + } catch (error49) { + return text; + } +} +function isFunction2(value) { + return typeof value === "function"; +} +function getFetch(options) { + if (options == null ? void 0 : options.customFetchImpl) { + return options.customFetchImpl; + } + if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch)) { + return globalThis.fetch; + } + if (typeof window !== "undefined" && isFunction2(window.fetch)) { + return window.fetch; + } + throw new Error("No fetch implementation found"); +} +async function getHeaders(opts) { + const headers = new Headers(opts == null ? void 0 : opts.headers); + const authHeader = await getAuthHeader(opts); + for (const [key, value] of Object.entries(authHeader || {})) { + headers.set(key, value); + } + if (!headers.has("content-type")) { + const t = detectContentType(opts == null ? void 0 : opts.body); + if (t) { + headers.set("content-type", t); + } + } + return headers; +} +function detectContentType(body) { + if (isJSONSerializable2(body)) { + return "application/json"; + } + return null; +} +function getBody2(options) { + if (!(options == null ? void 0 : options.body)) { + return null; + } + const headers = new Headers(options == null ? void 0 : options.headers); + if (isJSONSerializable2(options.body) && !headers.has("content-type")) { + for (const [key, value] of Object.entries(options == null ? void 0 : options.body)) { + if (value instanceof Date) { + options.body[key] = value.toISOString(); + } + } + return JSON.stringify(options.body); + } + if (headers.has("content-type") && headers.get("content-type") === "application/x-www-form-urlencoded") { + if (isJSONSerializable2(options.body)) { + return new URLSearchParams(options.body).toString(); + } + return options.body; + } + return options.body; +} +function getMethod(url2, options) { + var _a30; + if (options == null ? void 0 : options.method) { + return options.method.toUpperCase(); + } + if (url2.startsWith("@")) { + const pMethod = (_a30 = url2.split("@")[1]) == null ? void 0 : _a30.split("/")[0]; + if (!methods.includes(pMethod)) { + return (options == null ? void 0 : options.body) ? "POST" : "GET"; + } + return pMethod.toUpperCase(); + } + return (options == null ? void 0 : options.body) ? "POST" : "GET"; +} +function getTimeout(options, controller) { + let abortTimeout; + if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) { + abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout); + } + return { + abortTimeout, + clearTimeout: () => { + if (abortTimeout) { + clearTimeout(abortTimeout); + } + } + }; +} +var ValidationError2 = class _ValidationError extends Error { + constructor(issues, message2) { + super(message2 || JSON.stringify(issues, null, 2)); + this.issues = issues; + Object.setPrototypeOf(this, _ValidationError.prototype); + } +}; +async function parseStandardSchema(schema3, input) { + const result = await schema3["~standard"].validate(input); + if (result.issues) { + throw new ValidationError2(result.issues); + } + return result.value; +} +var methods = ["get", "post", "put", "patch", "delete"]; +function getURL2(url2, option) { + const { baseURL, params, query } = option || { + query: {}, + params: {}, + baseURL: "" + }; + let basePath = url2.startsWith("http") ? url2.split("/").slice(0, 3).join("/") : baseURL || ""; + if (url2.startsWith("@")) { + const m = url2.toString().split("@")[1].split("/")[0]; + if (methods.includes(m)) { + url2 = url2.replace(`@${m}/`, "/"); + } + } + if (!basePath.endsWith("/")) basePath += "/"; + let [path3, urlQuery] = url2.replace(basePath, "").split("?"); + const queryParams = new URLSearchParams(urlQuery); + for (const [key, value] of Object.entries(query || {})) { + if (value == null) continue; + let serializedValue; + if (typeof value === "string") { + serializedValue = value; + } else if (Array.isArray(value)) { + for (const val of value) { + queryParams.append(key, val); + } + continue; + } else { + serializedValue = JSON.stringify(value); + } + queryParams.set(key, serializedValue); + } + if (params) { + if (Array.isArray(params)) { + const paramPaths = path3.split("/").filter((p) => p.startsWith(":")); + for (const [index, key] of paramPaths.entries()) { + const value = params[index]; + path3 = path3.replace(key, value); + } + } else { + for (const [key, value] of Object.entries(params)) { + path3 = path3.replace(`:${key}`, String(value)); + } + } + } + path3 = path3.split("/").map(encodeURIComponent).join("/"); + if (path3.startsWith("/")) path3 = path3.slice(1); + let queryParamString = queryParams.toString(); + queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\+/g, "%20") : ""; + if (!basePath.startsWith("http")) { + return `${basePath}${path3}${queryParamString}`; + } + const _url3 = new URL(`${path3}${queryParamString}`, basePath); + return _url3; +} +var betterFetch = async (url2, options) => { + var _a30, _b2, _c, _d, _e, _f, _g, _h; + const { + hooks, + url: __url, + options: opts + } = await initializePlugins(url2, options); + const fetch2 = getFetch(opts); + const controller = new AbortController(); + const signal = (_a30 = opts.signal) != null ? _a30 : controller.signal; + const _url3 = getURL2(__url, opts); + const body = getBody2(opts); + const headers = await getHeaders(opts); + const method = getMethod(__url, opts); + let context = __spreadProps(__spreadValues({}, opts), { + url: _url3, + headers, + body, + method, + signal + }); + for (const onRequest of hooks.onRequest) { + if (onRequest) { + const res = await onRequest(context); + if (typeof res === "object" && res !== null) { + context = res; + } + } + } + if ("pipeTo" in context && typeof context.pipeTo === "function" || typeof ((_b2 = options == null ? void 0 : options.body) == null ? void 0 : _b2.pipe) === "function") { + if (!("duplex" in context)) { + context.duplex = "half"; + } + } + const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller); + let response = await fetch2(context.url, context); + clearTimeout2(); + const responseContext = { + response, + request: context + }; + for (const onResponse of hooks.onResponse) { + if (onResponse) { + const r = await onResponse(__spreadProps(__spreadValues({}, responseContext), { + response: ((_c = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c.cloneResponse) ? response.clone() : response + })); + if (r instanceof Response) { + response = r; + } else if (typeof r === "object" && r !== null) { + response = r.response; + } + } + } + if (response.ok) { + const hasBody = context.method !== "HEAD"; + if (!hasBody) { + return { + data: "", + error: null + }; + } + const responseType = detectResponseType(response); + const successContext = { + data: null, + response, + request: context + }; + if (responseType === "json" || responseType === "text") { + const text = await response.text(); + const parser2 = (_d = context.jsonParser) != null ? _d : jsonParse; + successContext.data = await parser2(text); + } else { + successContext.data = await response[responseType](); + } + if (context == null ? void 0 : context.output) { + if (context.output && !context.disableValidation) { + successContext.data = await parseStandardSchema( + context.output, + successContext.data + ); + } + } + for (const onSuccess of hooks.onSuccess) { + if (onSuccess) { + await onSuccess(__spreadProps(__spreadValues({}, successContext), { + response: ((_e = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e.cloneResponse) ? response.clone() : response + })); + } + } + if (options == null ? void 0 : options.throw) { + return successContext.data; + } + return { + data: successContext.data, + error: null + }; + } + const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse; + const responseText = await response.text(); + const isJSONResponse2 = isJSONParsable(responseText); + const errorObject = isJSONResponse2 ? await parser(responseText) : null; + const errorContext = { + response, + responseText, + request: context, + error: __spreadProps(__spreadValues({}, errorObject), { + status: response.status, + statusText: response.statusText + }) + }; + for (const onError of hooks.onError) { + if (onError) { + await onError(__spreadProps(__spreadValues({}, errorContext), { + response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response + })); + } + } + if (options == null ? void 0 : options.retry) { + const retryStrategy = createRetryStrategy(options.retry); + const _retryAttempt = (_h = options.retryAttempt) != null ? _h : 0; + if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) { + for (const onRetry of hooks.onRetry) { + if (onRetry) { + await onRetry(responseContext); + } + } + const delay = retryStrategy.getDelay(_retryAttempt); + await new Promise((resolve2) => setTimeout(resolve2, delay)); + return await betterFetch(url2, __spreadProps(__spreadValues({}, options), { + retryAttempt: _retryAttempt + 1 + })); + } + } + if (options == null ? void 0 : options.throw) { + throw new BetterFetchError( + response.status, + response.statusText, + isJSONResponse2 ? errorObject : responseText + ); + } + return { + data: null, + error: __spreadProps(__spreadValues({}, errorObject), { + status: response.status, + statusText: response.statusText + }) + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/refresh-access-token.mjs +function createRefreshAccessTokenRequest({ refreshToken: refreshToken2, options, authentication, extraParams, resource }) { + const body = new URLSearchParams(); + const headers = { + "content-type": "application/x-www-form-urlencoded", + accept: "application/json" + }; + body.set("grant_type", "refresh_token"); + body.set("refresh_token", refreshToken2); + if (authentication === "basic") { + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + if (primaryClientId) headers["authorization"] = "Basic " + base643.encode(`${primaryClientId}:${options.clientSecret ?? ""}`); + else headers["authorization"] = "Basic " + base643.encode(`:${options.clientSecret ?? ""}`); + } else { + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + body.set("client_id", primaryClientId); + if (options.clientSecret) body.set("client_secret", options.clientSecret); + } + if (resource) if (typeof resource === "string") body.append("resource", resource); + else for (const _resource of resource) body.append("resource", _resource); + if (extraParams) for (const [key, value] of Object.entries(extraParams)) body.set(key, value); + return { + body, + headers + }; +} +async function refreshAccessToken({ refreshToken: refreshToken2, options, tokenEndpoint: tokenEndpoint2, authentication, extraParams }) { + const { body, headers } = await createRefreshAccessTokenRequest({ + refreshToken: refreshToken2, + options, + authentication, + extraParams + }); + const { data, error: error49 } = await betterFetch(tokenEndpoint2, { + method: "POST", + body, + headers + }); + if (error49) throw error49; + const tokens = { + accessToken: data.access_token, + refreshToken: data.refresh_token, + tokenType: data.token_type, + scopes: data.scope?.split(" "), + idToken: data.id_token + }; + if (data.expires_in) { + const now2 = /* @__PURE__ */ new Date(); + tokens.accessTokenExpiresAt = new Date(now2.getTime() + data.expires_in * 1e3); + } + if (data.refresh_token_expires_in) { + const now2 = /* @__PURE__ */ new Date(); + tokens.refreshTokenExpiresAt = new Date(now2.getTime() + data.refresh_token_expires_in * 1e3); + } + return tokens; +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/validate-authorization-code.mjs +async function authorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) { + options = typeof options === "function" ? await options() : options; + return createAuthorizationCodeRequest({ + code, + codeVerifier, + redirectURI, + options, + authentication, + deviceId, + headers, + additionalParams, + resource + }); +} +function createAuthorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) { + const body = new URLSearchParams(); + const requestHeaders = { + "content-type": "application/x-www-form-urlencoded", + accept: "application/json", + ...headers + }; + body.set("grant_type", "authorization_code"); + body.set("code", code); + codeVerifier && body.set("code_verifier", codeVerifier); + options.clientKey && body.set("client_key", options.clientKey); + deviceId && body.set("device_id", deviceId); + body.set("redirect_uri", options.redirectURI || redirectURI); + if (resource) if (typeof resource === "string") body.append("resource", resource); + else for (const _resource of resource) body.append("resource", _resource); + if (authentication === "basic") { + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + requestHeaders["authorization"] = `Basic ${base643.encode(`${primaryClientId}:${options.clientSecret ?? ""}`)}`; + } else { + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + body.set("client_id", primaryClientId); + if (options.clientSecret) body.set("client_secret", options.clientSecret); + } + for (const [key, value] of Object.entries(additionalParams)) if (!body.has(key)) body.append(key, value); + return { + body, + headers: requestHeaders + }; +} +async function validateAuthorizationCode({ code, codeVerifier, redirectURI, options, tokenEndpoint: tokenEndpoint2, authentication, deviceId, headers, additionalParams = {}, resource }) { + const { body, headers: requestHeaders } = await authorizationCodeRequest({ + code, + codeVerifier, + redirectURI, + options, + authentication, + deviceId, + headers, + additionalParams, + resource + }); + const { data, error: error49 } = await betterFetch(tokenEndpoint2, { + method: "POST", + body, + headers: requestHeaders + }); + if (error49) throw error49; + return getOAuth2Tokens(data); +} + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/apple.mjs +var apple = (options) => { + const tokenEndpoint2 = "https://appleid.apple.com/auth/token"; + return { + id: "apple", + name: "Apple", + async createAuthorizationURL({ state, scopes, redirectURI }) { + const _scope = options.disableDefaultScope ? [] : ["email", "name"]; + if (options.scope) _scope.push(...options.scope); + if (scopes) _scope.push(...scopes); + return await createAuthorizationURL({ + id: "apple", + options, + authorizationEndpoint: "https://appleid.apple.com/auth/authorize", + scopes: _scope, + state, + redirectURI, + responseMode: "form_post", + responseType: "code id_token" + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + try { + const { kid, alg: jwtAlg } = decodeProtectedHeader(token); + if (!kid || !jwtAlg) return false; + const { payload: jwtClaims } = await jwtVerify(token, await getApplePublicKey(kid), { + algorithms: [jwtAlg], + issuer: "https://appleid.apple.com", + audience: options.audience && options.audience.length ? options.audience : options.appBundleIdentifier ? options.appBundleIdentifier : options.clientId, + maxTokenAge: "1h" + }); + ["email_verified", "is_private_email"].forEach((field) => { + if (jwtClaims[field] !== void 0) jwtClaims[field] = Boolean(jwtClaims[field]); + }); + if (nonce && jwtClaims.nonce !== nonce) return false; + return !!jwtClaims; + } catch { + return false; + } + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.idToken) return null; + const profile = decodeJwt(token.idToken); + if (!profile) return null; + let name; + if (token.user?.name) name = `${token.user.name.firstName || ""} ${token.user.name.lastName || ""}`.trim(); + else name = profile.name || ""; + const emailVerified = typeof profile.email_verified === "boolean" ? profile.email_verified : profile.email_verified === "true"; + const enrichedProfile = { + ...profile, + name + }; + const userMap = await options.mapProfileToUser?.(enrichedProfile); + return { + user: { + id: profile.sub, + name: enrichedProfile.name, + emailVerified, + email: profile.email, + ...userMap + }, + data: enrichedProfile + }; + }, + options + }; +}; +var getApplePublicKey = async (kid) => { + const { data } = await betterFetch(`https://appleid.apple.com/auth/keys`); + if (!data?.keys) throw new APIError2("BAD_REQUEST", { message: "Keys not found" }); + const jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) throw new Error(`JWK with kid ${kid} not found`); + return await importJWK(jwk, jwk.alg); +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/atlassian.mjs +init_logger(); +init_error2(); +var atlassian = (options) => { + const tokenEndpoint2 = "https://auth.atlassian.com/oauth/token"; + return { + id: "atlassian", + name: "Atlassian", + async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + if (!options.clientId || !options.clientSecret) { + logger.error("Client Id and Secret are required for Atlassian"); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Atlassian"); + const _scopes = options.disableDefaultScope ? [] : ["read:jira-user", "offline_access"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "atlassian", + options, + authorizationEndpoint: "https://auth.atlassian.com/authorize", + scopes: _scopes, + state, + codeVerifier, + redirectURI, + additionalParams: { audience: "api.atlassian.com" }, + prompt: options.prompt + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.accessToken) return null; + try { + const { data: profile } = await betterFetch("https://api.atlassian.com/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (!profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.account_id, + name: profile.name, + email: profile.email, + image: profile.picture, + emailVerified: false, + ...userMap + }, + data: profile + }; + } catch (error49) { + logger.error("Failed to fetch user info from Figma:", error49); + return null; + } + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/cognito.mjs +init_logger(); +init_error2(); +var cognito = (options) => { + if (!options.domain || !options.region || !options.userPoolId) { + logger.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."); + throw new BetterAuthError("DOMAIN_AND_REGION_REQUIRED"); + } + const cleanDomain = options.domain.replace(/^https?:\/\//, ""); + const authorizationEndpoint2 = `https://${cleanDomain}/oauth2/authorize`; + const tokenEndpoint2 = `https://${cleanDomain}/oauth2/token`; + const userInfoEndpoint = `https://${cleanDomain}/oauth2/userinfo`; + return { + id: "cognito", + name: "Cognito", + async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + if (!options.clientId) { + logger.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (options.requireClientSecret && !options.clientSecret) { + logger.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."); + throw new BetterAuthError("CLIENT_SECRET_REQUIRED"); + } + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + const url2 = await createAuthorizationURL({ + id: "cognito", + options: { ...options }, + authorizationEndpoint: authorizationEndpoint2, + scopes: _scopes, + state, + codeVerifier, + redirectURI, + prompt: options.prompt + }); + const scopeValue = url2.searchParams.get("scope"); + if (scopeValue) { + url2.searchParams.delete("scope"); + const encodedScope = encodeURIComponent(scopeValue); + const urlString = url2.toString(); + const separator = urlString.includes("?") ? "&" : "?"; + return new URL(`${urlString}${separator}scope=${encodedScope}`); + } + return url2; + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + try { + const { kid, alg: jwtAlg } = decodeProtectedHeader(token); + if (!kid || !jwtAlg) return false; + const publicKey = await getCognitoPublicKey(kid, options.region, options.userPoolId); + const expectedIssuer = `https://cognito-idp.${options.region}.amazonaws.com/${options.userPoolId}`; + const { payload: jwtClaims } = await jwtVerify(token, publicKey, { + algorithms: [jwtAlg], + issuer: expectedIssuer, + audience: options.clientId, + maxTokenAge: "1h" + }); + if (nonce && jwtClaims.nonce !== nonce) return false; + return true; + } catch (error49) { + logger.error("Failed to verify ID token:", error49); + return false; + } + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (token.idToken) try { + const profile = decodeJwt(token.idToken); + if (!profile) return null; + const name = profile.name || profile.given_name || profile.username || ""; + const enrichedProfile = { + ...profile, + name + }; + const userMap = await options.mapProfileToUser?.(enrichedProfile); + return { + user: { + id: profile.sub, + name: enrichedProfile.name, + email: profile.email, + image: profile.picture, + emailVerified: profile.email_verified, + ...userMap + }, + data: enrichedProfile + }; + } catch (error49) { + logger.error("Failed to decode ID token:", error49); + } + if (token.accessToken) try { + const { data: userInfo } = await betterFetch(userInfoEndpoint, { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (userInfo) { + const userMap = await options.mapProfileToUser?.(userInfo); + return { + user: { + id: userInfo.sub, + name: userInfo.name || userInfo.given_name || userInfo.username || "", + email: userInfo.email, + image: userInfo.picture, + emailVerified: userInfo.email_verified, + ...userMap + }, + data: userInfo + }; + } + } catch (error49) { + logger.error("Failed to fetch user info from Cognito:", error49); + } + return null; + }, + options + }; +}; +var getCognitoPublicKey = async (kid, region, userPoolId) => { + const COGNITO_JWKS_URI = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`; + try { + const { data } = await betterFetch(COGNITO_JWKS_URI); + if (!data?.keys) throw new APIError2("BAD_REQUEST", { message: "Keys not found" }); + const jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) throw new Error(`JWK with kid ${kid} not found`); + return await importJWK(jwk, jwk.alg); + } catch (error49) { + logger.error("Failed to fetch Cognito public key:", error49); + throw error49; + } +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/discord.mjs +var discord = (options) => { + const tokenEndpoint2 = "https://discord.com/api/oauth2/token"; + return { + id: "discord", + name: "Discord", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["identify", "email"]; + if (scopes) _scopes.push(...scopes); + if (options.scope) _scopes.push(...options.scope); + const permissionsParam = _scopes.includes("bot") && options.permissions !== void 0 ? `&permissions=${options.permissions}` : ""; + return new URL(`https://discord.com/api/oauth2/authorize?scope=${_scopes.join("+")}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state}&prompt=${options.prompt || "none"}${permissionsParam}`); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://discord.com/api/users/@me", { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error49) return null; + if (profile.avatar === null) profile.image_url = `https://cdn.discordapp.com/embed/avatars/${profile.discriminator === "0" ? Number(BigInt(profile.id) >> BigInt(22)) % 6 : parseInt(profile.discriminator) % 5}.png`; + else { + const format = profile.avatar.startsWith("a_") ? "gif" : "png"; + profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`; + } + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.global_name || profile.username || "", + email: profile.email, + emailVerified: profile.verified, + image: profile.image_url, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/dropbox.mjs +var dropbox = (options) => { + const tokenEndpoint2 = "https://api.dropboxapi.com/oauth2/token"; + return { + id: "dropbox", + name: "Dropbox", + createAuthorizationURL: async ({ state, scopes, codeVerifier, redirectURI }) => { + const _scopes = options.disableDefaultScope ? [] : ["account_info.read"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + const additionalParams = {}; + if (options.accessType) additionalParams.token_access_type = options.accessType; + return await createAuthorizationURL({ + id: "dropbox", + options, + authorizationEndpoint: "https://www.dropbox.com/oauth2/authorize", + scopes: _scopes, + state, + redirectURI, + codeVerifier, + additionalParams + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return await validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.dropboxapi.com/2/users/get_current_account", { + method: "POST", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.account_id, + name: profile.name?.display_name, + email: profile.email, + emailVerified: profile.email_verified || false, + image: profile.profile_photo_url, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/facebook.mjs +var facebook = (options) => { + return { + id: "facebook", + name: "Facebook", + async createAuthorizationURL({ state, scopes, redirectURI, loginHint }) { + const _scopes = options.disableDefaultScope ? [] : ["email", "public_profile"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "facebook", + options, + authorizationEndpoint: "https://www.facebook.com/v24.0/dialog/oauth", + scopes: _scopes, + state, + redirectURI, + loginHint, + additionalParams: options.configId ? { config_id: options.configId } : {} + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://graph.facebook.com/v24.0/oauth/access_token" + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + if (token.split(".").length === 3) try { + const { payload: jwtClaims } = await jwtVerify(token, createRemoteJWKSet(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")), { + algorithms: ["RS256"], + audience: options.clientId, + issuer: "https://www.facebook.com" + }); + if (nonce && jwtClaims.nonce !== nonce) return false; + return !!jwtClaims; + } catch { + return false; + } + return true; + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://graph.facebook.com/v24.0/oauth/access_token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (token.idToken && token.idToken.split(".").length === 3) { + const profile2 = decodeJwt(token.idToken); + const user = { + id: profile2.sub, + name: profile2.name, + email: profile2.email, + picture: { data: { + url: profile2.picture, + height: 100, + width: 100, + is_silhouette: false + } } + }; + const userMap2 = await options.mapProfileToUser?.({ + ...user, + email_verified: false + }); + return { + user: { + ...user, + emailVerified: false, + ...userMap2 + }, + data: profile2 + }; + } + const { data: profile, error: error49 } = await betterFetch("https://graph.facebook.com/me?fields=" + [ + "id", + "name", + "email", + "picture", + ...options?.fields || [] + ].join(","), { auth: { + type: "Bearer", + token: token.accessToken + } }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.name, + email: profile.email, + image: profile.picture.data.url, + emailVerified: profile.email_verified, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/figma.mjs +init_logger(); +init_error2(); +var figma = (options) => { + const tokenEndpoint2 = "https://api.figma.com/v1/oauth/token"; + return { + id: "figma", + name: "Figma", + async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + if (!options.clientId || !options.clientSecret) { + logger.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Figma"); + const _scopes = options.disableDefaultScope ? [] : ["current_user:read"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "figma", + options, + authorizationEndpoint: "https://www.figma.com/oauth", + scopes: _scopes, + state, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2, + authentication: "basic" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2, + authentication: "basic" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + try { + const { data: profile } = await betterFetch("https://api.figma.com/v1/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (!profile) { + logger.error("Failed to fetch user from Figma"); + return null; + } + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.handle, + email: profile.email, + image: profile.img_url, + emailVerified: false, + ...userMap + }, + data: profile + }; + } catch (error49) { + logger.error("Failed to fetch user info from Figma:", error49); + return null; + } + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/github.mjs +init_logger(); +var github = (options) => { + const tokenEndpoint2 = "https://github.com/login/oauth/access_token"; + return { + id: "github", + name: "GitHub", + createAuthorizationURL({ state, scopes, loginHint, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["read:user", "user:email"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "github", + options, + authorizationEndpoint: "https://github.com/login/oauth/authorize", + scopes: _scopes, + state, + codeVerifier, + redirectURI, + loginHint, + prompt: options.prompt + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + const { body, headers: requestHeaders } = createAuthorizationCodeRequest({ + code, + codeVerifier, + redirectURI, + options + }); + const { data, error: error49 } = await betterFetch(tokenEndpoint2, { + method: "POST", + body, + headers: requestHeaders + }); + if (error49) { + logger.error("GitHub OAuth token exchange failed:", error49); + return null; + } + if ("error" in data) { + logger.error("GitHub OAuth token exchange failed:", data); + return null; + } + return getOAuth2Tokens(data); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.github.com/user", { headers: { + "User-Agent": "better-auth", + authorization: `Bearer ${token.accessToken}` + } }); + if (error49) return null; + const { data: emails } = await betterFetch("https://api.github.com/user/emails", { headers: { + Authorization: `Bearer ${token.accessToken}`, + "User-Agent": "better-auth" + } }); + if (!profile.email && emails) profile.email = (emails.find((e) => e.primary) ?? emails[0])?.email; + const emailVerified = emails?.find((e) => e.email === profile.email)?.verified ?? false; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.name || profile.login || "", + email: profile.email, + image: profile.avatar_url, + emailVerified, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/gitlab.mjs +var cleanDoubleSlashes = (input = "") => { + return input.split("://").map((str) => str.replace(/\/{2,}/g, "/")).join("://"); +}; +var issuerToEndpoints = (issuer) => { + const baseUrl = issuer || "https://gitlab.com"; + return { + authorizationEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/authorize`), + tokenEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/token`), + userinfoEndpoint: cleanDoubleSlashes(`${baseUrl}/api/v4/user`) + }; +}; +var gitlab = (options) => { + const { authorizationEndpoint: authorizationEndpoint2, tokenEndpoint: tokenEndpoint2, userinfoEndpoint: userinfoEndpoint2 } = issuerToEndpoints(options.issuer); + const issuerId = "gitlab"; + return { + id: issuerId, + name: "Gitlab", + createAuthorizationURL: async ({ state, scopes, codeVerifier, loginHint, redirectURI }) => { + const _scopes = options.disableDefaultScope ? [] : ["read_user"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: issuerId, + options, + authorizationEndpoint: authorizationEndpoint2, + scopes: _scopes, + state, + redirectURI, + codeVerifier, + loginHint + }); + }, + validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + codeVerifier, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch(userinfoEndpoint2, { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error49 || profile.state !== "active" || profile.locked) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.name ?? profile.username ?? "", + email: profile.email, + image: profile.avatar_url, + emailVerified: profile.email_verified ?? false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/google.mjs +init_logger(); +init_error2(); +var google = (options) => { + return { + id: "google", + name: "Google", + async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, loginHint, display }) { + if (!options.clientId || !options.clientSecret) { + logger.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Google"); + const _scopes = options.disableDefaultScope ? [] : [ + "email", + "profile", + "openid" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "google", + options, + authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth", + scopes: _scopes, + state, + codeVerifier, + redirectURI, + prompt: options.prompt, + accessType: options.accessType, + display: display || options.display, + loginHint, + hd: options.hd, + additionalParams: { include_granted_scopes: "true" } + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://oauth2.googleapis.com/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://oauth2.googleapis.com/token" + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + try { + const { kid, alg: jwtAlg } = decodeProtectedHeader(token); + if (!kid || !jwtAlg) return false; + const { payload: jwtClaims } = await jwtVerify(token, await getGooglePublicKey(kid), { + algorithms: [jwtAlg], + issuer: ["https://accounts.google.com", "accounts.google.com"], + audience: options.clientId, + maxTokenAge: "1h" + }); + if (nonce && jwtClaims.nonce !== nonce) return false; + return true; + } catch { + return false; + } + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.idToken) return null; + const user = decodeJwt(token.idToken); + const userMap = await options.mapProfileToUser?.(user); + return { + user: { + id: user.sub, + name: user.name, + email: user.email, + image: user.picture, + emailVerified: user.email_verified, + ...userMap + }, + data: user + }; + }, + options + }; +}; +var getGooglePublicKey = async (kid) => { + const { data } = await betterFetch("https://www.googleapis.com/oauth2/v3/certs"); + if (!data?.keys) throw new APIError2("BAD_REQUEST", { message: "Keys not found" }); + const jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) throw new Error(`JWK with kid ${kid} not found`); + return await importJWK(jwk, jwk.alg); +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/huggingface.mjs +var huggingface = (options) => { + const tokenEndpoint2 = "https://huggingface.co/oauth/token"; + return { + id: "huggingface", + name: "Hugging Face", + createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "huggingface", + options, + authorizationEndpoint: "https://huggingface.co/oauth/authorize", + scopes: _scopes, + state, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://huggingface.co/oauth/userinfo", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.name || profile.preferred_username || "", + email: profile.email, + image: profile.picture, + emailVerified: profile.email_verified ?? false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/kakao.mjs +var kakao = (options) => { + const tokenEndpoint2 = "https://kauth.kakao.com/oauth/token"; + return { + id: "kakao", + name: "Kakao", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "account_email", + "profile_image", + "profile_nickname" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "kakao", + options, + authorizationEndpoint: "https://kauth.kakao.com/oauth/authorize", + scopes: _scopes, + state, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://kapi.kakao.com/v2/user/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (error49 || !profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + const account = profile.kakao_account || {}; + const kakaoProfile = account.profile || {}; + return { + user: { + id: String(profile.id), + name: kakaoProfile.nickname || account.name || "", + email: account.email, + image: kakaoProfile.profile_image_url || kakaoProfile.thumbnail_image_url, + emailVerified: !!account.is_email_valid && !!account.is_email_verified, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/kick.mjs +var kick = (options) => { + return { + id: "kick", + name: "Kick", + createAuthorizationURL({ state, scopes, redirectURI, codeVerifier }) { + const _scopes = options.disableDefaultScope ? [] : ["user:read"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "kick", + redirectURI, + options, + authorizationEndpoint: "https://id.kick.com/oauth/authorize", + scopes: _scopes, + codeVerifier, + state + }); + }, + async validateAuthorizationCode({ code, redirectURI, codeVerifier }) { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://id.kick.com/oauth/token", + codeVerifier + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://id.kick.com/oauth/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data, error: error49 } = await betterFetch("https://api.kick.com/public/v1/users", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error49) return null; + const profile = data.data[0]; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.user_id, + name: profile.name, + email: profile.email, + image: profile.profile_picture, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/line.mjs +var line = (options) => { + const authorizationEndpoint2 = "https://access.line.me/oauth2/v2.1/authorize"; + const tokenEndpoint2 = "https://api.line.me/oauth2/v2.1/token"; + const userInfoEndpoint = "https://api.line.me/oauth2/v2.1/userinfo"; + const verifyIdTokenEndpoint = "https://api.line.me/oauth2/v2.1/verify"; + return { + id: "line", + name: "LINE", + async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, loginHint }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "line", + options, + authorizationEndpoint: authorizationEndpoint2, + scopes: _scopes, + state, + codeVerifier, + redirectURI, + loginHint + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + const body = new URLSearchParams(); + body.set("id_token", token); + body.set("client_id", options.clientId); + if (nonce) body.set("nonce", nonce); + const { data, error: error49 } = await betterFetch(verifyIdTokenEndpoint, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body + }); + if (error49 || !data) return false; + if (data.aud !== options.clientId) return false; + if (data.nonce && data.nonce !== nonce) return false; + return true; + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + let profile = null; + if (token.idToken) try { + profile = decodeJwt(token.idToken); + } catch { + } + if (!profile) { + const { data } = await betterFetch(userInfoEndpoint, { headers: { authorization: `Bearer ${token.accessToken}` } }); + profile = data || null; + } + if (!profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + const id = profile.sub || profile.userId; + const name = profile.name || profile.displayName || ""; + const image = profile.picture || profile.pictureUrl || void 0; + return { + user: { + id, + name, + email: profile.email, + image, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/linear.mjs +var linear = (options) => { + const tokenEndpoint2 = "https://api.linear.app/oauth/token"; + return { + id: "linear", + name: "Linear", + createAuthorizationURL({ state, scopes, loginHint, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["read"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "linear", + options, + authorizationEndpoint: "https://linear.app/oauth/authorize", + scopes: _scopes, + state, + redirectURI, + loginHint + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.linear.app/graphql", { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token.accessToken}` + }, + body: JSON.stringify({ query: ` + query { + viewer { + id + name + email + avatarUrl + active + createdAt + updatedAt + } + } + ` }) + }); + if (error49 || !profile?.data?.viewer) return null; + const userData = profile.data.viewer; + const userMap = await options.mapProfileToUser?.(userData); + return { + user: { + id: profile.data.viewer.id, + name: profile.data.viewer.name, + email: profile.data.viewer.email, + image: profile.data.viewer.avatarUrl, + emailVerified: false, + ...userMap + }, + data: userData + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/linkedin.mjs +var linkedin = (options) => { + const authorizationEndpoint2 = "https://www.linkedin.com/oauth/v2/authorization"; + const tokenEndpoint2 = "https://www.linkedin.com/oauth/v2/accessToken"; + return { + id: "linkedin", + name: "Linkedin", + createAuthorizationURL: async ({ state, scopes, redirectURI, loginHint }) => { + const _scopes = options.disableDefaultScope ? [] : [ + "profile", + "email", + "openid" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "linkedin", + options, + authorizationEndpoint: authorizationEndpoint2, + scopes: _scopes, + state, + loginHint, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return await validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.linkedin.com/v2/userinfo", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.name, + email: profile.email, + emailVerified: profile.email_verified || false, + image: profile.picture, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/microsoft-entra-id.mjs +init_logger(); +init_error2(); +var microsoft = (options) => { + const tenant = options.tenantId || "common"; + const authority = options.authority || "https://login.microsoftonline.com"; + const authorizationEndpoint2 = `${authority}/${tenant}/oauth2/v2.0/authorize`; + const tokenEndpoint2 = `${authority}/${tenant}/oauth2/v2.0/token`; + return { + id: "microsoft", + name: "Microsoft EntraID", + createAuthorizationURL(data) { + const scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email", + "User.Read", + "offline_access" + ]; + if (options.scope) scopes.push(...options.scope); + if (data.scopes) scopes.push(...data.scopes); + return createAuthorizationURL({ + id: "microsoft", + options, + authorizationEndpoint: authorizationEndpoint2, + state: data.state, + codeVerifier: data.codeVerifier, + scopes, + redirectURI: data.redirectURI, + prompt: options.prompt, + loginHint: data.loginHint + }); + }, + validateAuthorizationCode({ code, codeVerifier, redirectURI }) { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + try { + const { kid, alg: jwtAlg } = decodeProtectedHeader(token); + if (!kid || !jwtAlg) return false; + const publicKey = await getMicrosoftPublicKey(kid, tenant, authority); + const verifyOptions = { + algorithms: [jwtAlg], + audience: options.clientId, + maxTokenAge: "1h" + }; + if (tenant !== "common" && tenant !== "organizations" && tenant !== "consumers") verifyOptions.issuer = `${authority}/${tenant}/v2.0`; + const { payload: jwtClaims } = await jwtVerify(token, publicKey, verifyOptions); + if (nonce && jwtClaims.nonce !== nonce) return false; + return true; + } catch (error49) { + logger.error("Failed to verify ID token:", error49); + return false; + } + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.idToken) return null; + const user = decodeJwt(token.idToken); + const profilePhotoSize = options.profilePhotoSize || 48; + await betterFetch(`https://graph.microsoft.com/v1.0/me/photos/${profilePhotoSize}x${profilePhotoSize}/$value`, { + headers: { Authorization: `Bearer ${token.accessToken}` }, + async onResponse(context) { + if (options.disableProfilePhoto || !context.response.ok) return; + try { + const pictureBuffer = await context.response.clone().arrayBuffer(); + user.picture = `data:image/jpeg;base64, ${base643.encode(pictureBuffer)}`; + } catch (e) { + logger.error(e && typeof e === "object" && "name" in e ? e.name : "", e); + } + } + }); + const userMap = await options.mapProfileToUser?.(user); + const emailVerified = user.email_verified !== void 0 ? user.email_verified : user.email && (user.verified_primary_email?.includes(user.email) || user.verified_secondary_email?.includes(user.email)) ? true : false; + return { + user: { + id: user.sub, + name: user.name, + email: user.email, + image: user.picture, + emailVerified, + ...userMap + }, + data: user + }; + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + const scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email", + "User.Read", + "offline_access" + ]; + if (options.scope) scopes.push(...options.scope); + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + extraParams: { scope: scopes.join(" ") }, + tokenEndpoint: tokenEndpoint2 + }); + }, + options + }; +}; +var getMicrosoftPublicKey = async (kid, tenant, authority) => { + const { data } = await betterFetch(`${authority}/${tenant}/discovery/v2.0/keys`); + if (!data?.keys) throw new APIError2("BAD_REQUEST", { message: "Keys not found" }); + const jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) throw new Error(`JWK with kid ${kid} not found`); + return await importJWK(jwk, jwk.alg); +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/naver.mjs +var naver = (options) => { + const tokenEndpoint2 = "https://nid.naver.com/oauth2.0/token"; + return { + id: "naver", + name: "Naver", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["profile", "email"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "naver", + options, + authorizationEndpoint: "https://nid.naver.com/oauth2.0/authorize", + scopes: _scopes, + state, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://openapi.naver.com/v1/nid/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (error49 || !profile || profile.resultcode !== "00") return null; + const userMap = await options.mapProfileToUser?.(profile); + const res = profile.response || {}; + return { + user: { + id: res.id, + name: res.name || res.nickname || "", + email: res.email, + image: res.profile_image, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/notion.mjs +var notion = (options) => { + const tokenEndpoint2 = "https://api.notion.com/v1/oauth/token"; + return { + id: "notion", + name: "Notion", + createAuthorizationURL({ state, scopes, loginHint, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : []; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "notion", + options, + authorizationEndpoint: "https://api.notion.com/v1/oauth/authorize", + scopes: _scopes, + state, + redirectURI, + loginHint, + additionalParams: { owner: "user" } + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2, + authentication: "basic" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.notion.com/v1/users/me", { headers: { + Authorization: `Bearer ${token.accessToken}`, + "Notion-Version": "2022-06-28" + } }); + if (error49 || !profile) return null; + const userProfile = profile.bot?.owner?.user; + if (!userProfile) return null; + const userMap = await options.mapProfileToUser?.(userProfile); + return { + user: { + id: userProfile.id, + name: userProfile.name || "", + email: userProfile.person?.email || null, + image: userProfile.avatar_url, + emailVerified: false, + ...userMap + }, + data: userProfile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/paybin.mjs +init_logger(); +init_error2(); +var paybin = (options) => { + const issuer = options.issuer || "https://idp.paybin.io"; + const authorizationEndpoint2 = `${issuer}/oauth2/authorize`; + const tokenEndpoint2 = `${issuer}/oauth2/token`; + return { + id: "paybin", + name: "Paybin", + async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, loginHint }) { + if (!options.clientId || !options.clientSecret) { + logger.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Paybin"); + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "email", + "profile" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "paybin", + options, + authorizationEndpoint: authorizationEndpoint2, + scopes: _scopes, + state, + codeVerifier, + redirectURI, + prompt: options.prompt, + loginHint + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.idToken) return null; + const user = decodeJwt(token.idToken); + const userMap = await options.mapProfileToUser?.(user); + return { + user: { + id: user.sub, + name: user.name || user.preferred_username || "", + email: user.email, + image: user.picture, + emailVerified: user.email_verified || false, + ...userMap + }, + data: user + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/paypal.mjs +init_logger(); +init_error2(); +var paypal = (options) => { + const isSandbox = (options.environment || "sandbox") === "sandbox"; + const authorizationEndpoint2 = isSandbox ? "https://www.sandbox.paypal.com/signin/authorize" : "https://www.paypal.com/signin/authorize"; + const tokenEndpoint2 = isSandbox ? "https://api-m.sandbox.paypal.com/v1/oauth2/token" : "https://api-m.paypal.com/v1/oauth2/token"; + const userInfoEndpoint = isSandbox ? "https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo" : "https://api-m.paypal.com/v1/identity/oauth2/userinfo"; + return { + id: "paypal", + name: "PayPal", + async createAuthorizationURL({ state, codeVerifier, redirectURI }) { + if (!options.clientId || !options.clientSecret) { + logger.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + return await createAuthorizationURL({ + id: "paypal", + options, + authorizationEndpoint: authorizationEndpoint2, + scopes: [], + state, + codeVerifier, + redirectURI, + prompt: options.prompt + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + const credentials = base643.encode(`${options.clientId}:${options.clientSecret}`); + try { + const response = await betterFetch(tokenEndpoint2, { + method: "POST", + headers: { + Authorization: `Basic ${credentials}`, + Accept: "application/json", + "Accept-Language": "en_US", + "Content-Type": "application/x-www-form-urlencoded" + }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: redirectURI + }).toString() + }); + if (!response.data) throw new BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN"); + const data = response.data; + return { + accessToken: data.access_token, + refreshToken: data.refresh_token, + accessTokenExpiresAt: data.expires_in ? new Date(Date.now() + data.expires_in * 1e3) : void 0, + idToken: data.id_token + }; + } catch (error49) { + logger.error("PayPal token exchange failed:", error49); + throw new BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN"); + } + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + const credentials = base643.encode(`${options.clientId}:${options.clientSecret}`); + try { + const response = await betterFetch(tokenEndpoint2, { + method: "POST", + headers: { + Authorization: `Basic ${credentials}`, + Accept: "application/json", + "Accept-Language": "en_US", + "Content-Type": "application/x-www-form-urlencoded" + }, + body: new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: refreshToken2 + }).toString() + }); + if (!response.data) throw new BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN"); + const data = response.data; + return { + accessToken: data.access_token, + refreshToken: data.refresh_token, + accessTokenExpiresAt: data.expires_in ? new Date(Date.now() + data.expires_in * 1e3) : void 0 + }; + } catch (error49) { + logger.error("PayPal token refresh failed:", error49); + throw new BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN"); + } + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + try { + return !!decodeJwt(token).sub; + } catch (error49) { + logger.error("Failed to verify PayPal ID token:", error49); + return false; + } + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.accessToken) { + logger.error("Access token is required to fetch PayPal user info"); + return null; + } + try { + const response = await betterFetch(`${userInfoEndpoint}?schema=paypalv1.1`, { headers: { + Authorization: `Bearer ${token.accessToken}`, + Accept: "application/json" + } }); + if (!response.data) { + logger.error("Failed to fetch user info from PayPal"); + return null; + } + const userInfo = response.data; + const userMap = await options.mapProfileToUser?.(userInfo); + return { + user: { + id: userInfo.user_id, + name: userInfo.name, + email: userInfo.email, + image: userInfo.picture, + emailVerified: userInfo.email_verified, + ...userMap + }, + data: userInfo + }; + } catch (error49) { + logger.error("Failed to fetch user info from PayPal:", error49); + return null; + } + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/polar.mjs +var polar = (options) => { + const tokenEndpoint2 = "https://api.polar.sh/v1/oauth2/token"; + return { + id: "polar", + name: "Polar", + createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "polar", + options, + authorizationEndpoint: "https://polar.sh/oauth2/authorize", + scopes: _scopes, + state, + codeVerifier, + redirectURI, + prompt: options.prompt + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.polar.sh/v1/oauth2/userinfo", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.public_name || profile.username || "", + email: profile.email, + image: profile.avatar_url, + emailVerified: profile.email_verified ?? false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/railway.mjs +var authorizationEndpoint = "https://backboard.railway.com/oauth/auth"; +var tokenEndpoint = "https://backboard.railway.com/oauth/token"; +var userinfoEndpoint = "https://backboard.railway.com/oauth/me"; +var railway = (options) => { + return { + id: "railway", + name: "Railway", + createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "email", + "profile" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "railway", + options, + authorizationEndpoint, + scopes: _scopes, + state, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint, + authentication: "basic" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint, + authentication: "basic" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch(userinfoEndpoint, { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error49 || !profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.name, + email: profile.email, + image: profile.picture, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/reddit.mjs +var reddit = (options) => { + return { + id: "reddit", + name: "Reddit", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["identity"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "reddit", + options, + authorizationEndpoint: "https://www.reddit.com/api/v1/authorize", + scopes: _scopes, + state, + redirectURI, + duration: options.duration + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + const body = new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: options.redirectURI || redirectURI + }); + const { data, error: error49 } = await betterFetch("https://www.reddit.com/api/v1/access_token", { + method: "POST", + headers: { + "content-type": "application/x-www-form-urlencoded", + accept: "text/plain", + "user-agent": "better-auth", + Authorization: `Basic ${base643.encode(`${options.clientId}:${options.clientSecret}`)}` + }, + body: body.toString() + }); + if (error49) throw error49; + return getOAuth2Tokens(data); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + authentication: "basic", + tokenEndpoint: "https://www.reddit.com/api/v1/access_token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://oauth.reddit.com/api/v1/me", { headers: { + Authorization: `Bearer ${token.accessToken}`, + "User-Agent": "better-auth" + } }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.name, + email: profile.oauth_client_id, + emailVerified: profile.has_verified_email, + image: profile.icon_img?.split("?")[0], + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/roblox.mjs +var roblox = (options) => { + const tokenEndpoint2 = "https://apis.roblox.com/oauth/v1/token"; + return { + id: "roblox", + name: "Roblox", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["openid", "profile"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${_scopes.join("+")}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state}&prompt=${options.prompt || "select_account consent"}`); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI: options.redirectURI || redirectURI, + options, + tokenEndpoint: tokenEndpoint2, + authentication: "post" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://apis.roblox.com/oauth/v1/userinfo", { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.nickname || profile.preferred_username || "", + image: profile.picture, + email: profile.preferred_username || null, + emailVerified: false, + ...userMap + }, + data: { ...profile } + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/salesforce.mjs +init_logger(); +init_error2(); +var salesforce = (options) => { + const isSandbox = (options.environment ?? "production") === "sandbox"; + const authorizationEndpoint2 = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/authorize` : isSandbox ? "https://test.salesforce.com/services/oauth2/authorize" : "https://login.salesforce.com/services/oauth2/authorize"; + const tokenEndpoint2 = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/token` : isSandbox ? "https://test.salesforce.com/services/oauth2/token" : "https://login.salesforce.com/services/oauth2/token"; + const userInfoEndpoint = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/userinfo` : isSandbox ? "https://test.salesforce.com/services/oauth2/userinfo" : "https://login.salesforce.com/services/oauth2/userinfo"; + return { + id: "salesforce", + name: "Salesforce", + async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + if (!options.clientId || !options.clientSecret) { + logger.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Salesforce"); + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "email", + "profile" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "salesforce", + options, + authorizationEndpoint: authorizationEndpoint2, + scopes: _scopes, + state, + codeVerifier, + redirectURI: options.redirectURI || redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI: options.redirectURI || redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + try { + const { data: user } = await betterFetch(userInfoEndpoint, { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (!user) { + logger.error("Failed to fetch user info from Salesforce"); + return null; + } + const userMap = await options.mapProfileToUser?.(user); + return { + user: { + id: user.user_id, + name: user.name, + email: user.email, + image: user.photos?.picture || user.photos?.thumbnail, + emailVerified: user.email_verified ?? false, + ...userMap + }, + data: user + }; + } catch (error49) { + logger.error("Failed to fetch user info from Salesforce:", error49); + return null; + } + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/slack.mjs +var slack = (options) => { + const tokenEndpoint2 = "https://slack.com/api/openid.connect.token"; + return { + id: "slack", + name: "Slack", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (scopes) _scopes.push(...scopes); + if (options.scope) _scopes.push(...options.scope); + const url2 = new URL("https://slack.com/openid/connect/authorize"); + url2.searchParams.set("scope", _scopes.join(" ")); + url2.searchParams.set("response_type", "code"); + url2.searchParams.set("client_id", options.clientId); + url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); + url2.searchParams.set("state", state); + return url2; + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://slack.com/api/openid.connect.userInfo", { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile["https://slack.com/user_id"], + name: profile.name || "", + email: profile.email, + emailVerified: profile.email_verified, + image: profile.picture || profile["https://slack.com/user_image_512"], + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/spotify.mjs +var spotify = (options) => { + const tokenEndpoint2 = "https://accounts.spotify.com/api/token"; + return { + id: "spotify", + name: "Spotify", + createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["user-read-email"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "spotify", + options, + authorizationEndpoint: "https://accounts.spotify.com/authorize", + scopes: _scopes, + state, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.spotify.com/v1/me", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.display_name, + email: profile.email, + image: profile.images[0]?.url, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/tiktok.mjs +var tiktok = (options) => { + const tokenEndpoint2 = "https://open.tiktokapis.com/v2/oauth/token/"; + return { + id: "tiktok", + name: "TikTok", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["user.info.profile"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${_scopes.join(",")}&response_type=code&client_key=${options.clientKey}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state}`); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI: options.redirectURI || redirectURI, + options: { + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { clientSecret: options.clientSecret }, + tokenEndpoint: tokenEndpoint2, + authentication: "post", + extraParams: { client_key: options.clientKey } + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch(`https://open.tiktokapis.com/v2/user/info/?fields=${[ + "open_id", + "avatar_large_url", + "display_name", + "username" + ].join(",")}`, { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error49) return null; + return { + user: { + email: profile.data.user.email || profile.data.user.username, + id: profile.data.user.open_id, + name: profile.data.user.display_name || profile.data.user.username || "", + image: profile.data.user.avatar_large_url, + emailVerified: false + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/twitch.mjs +init_logger(); +var twitch = (options) => { + const tokenEndpoint2 = "https://id.twitch.tv/oauth2/token"; + return { + id: "twitch", + name: "Twitch", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["user:read:email", "openid"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "twitch", + redirectURI, + options, + authorizationEndpoint: "https://id.twitch.tv/oauth2/authorize", + scopes: _scopes, + state, + claims: options.claims || [ + "email", + "email_verified", + "preferred_username", + "picture" + ] + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const idToken = token.idToken; + if (!idToken) { + logger.error("No idToken found in token"); + return null; + } + const profile = decodeJwt(idToken); + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.preferred_username, + email: profile.email, + image: profile.picture, + emailVerified: profile.email_verified, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/twitter.mjs +var twitter = (options) => { + const tokenEndpoint2 = "https://api.x.com/2/oauth2/token"; + return { + id: "twitter", + name: "Twitter", + createAuthorizationURL(data) { + const _scopes = options.disableDefaultScope ? [] : [ + "users.read", + "tweet.read", + "offline.access", + "users.email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (data.scopes) _scopes.push(...data.scopes); + return createAuthorizationURL({ + id: "twitter", + options, + authorizationEndpoint: "https://x.com/i/oauth2/authorize", + scopes: _scopes, + state: data.state, + codeVerifier: data.codeVerifier, + redirectURI: data.redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + authentication: "basic", + redirectURI, + options, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + authentication: "basic", + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: profileError } = await betterFetch("https://api.x.com/2/users/me?user.fields=profile_image_url", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (profileError) return null; + const { data: emailData, error: emailError } = await betterFetch("https://api.x.com/2/users/me?user.fields=confirmed_email", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + let emailVerified = false; + if (!emailError && emailData?.data?.confirmed_email) { + profile.data.email = emailData.data.confirmed_email; + emailVerified = true; + } + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.data.id, + name: profile.data.name, + email: profile.data.email || profile.data.username || null, + image: profile.data.profile_image_url, + emailVerified, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/vercel.mjs +init_error2(); +var vercel = (options) => { + return { + id: "vercel", + name: "Vercel", + createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Vercel"); + let _scopes = void 0; + if (options.scope !== void 0 || scopes !== void 0) { + _scopes = []; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + } + return createAuthorizationURL({ + id: "vercel", + options, + authorizationEndpoint: "https://vercel.com/oauth/authorize", + scopes: _scopes, + state, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://api.vercel.com/login/oauth/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.vercel.com/login/oauth/userinfo", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (error49 || !profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.name ?? profile.preferred_username ?? "", + email: profile.email, + image: profile.picture, + emailVerified: profile.email_verified ?? false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/vk.mjs +var vk = (options) => { + const tokenEndpoint2 = "https://id.vk.com/oauth2/auth"; + return { + id: "vk", + name: "VK", + async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["email", "phone"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "vk", + options, + authorizationEndpoint: "https://id.vk.com/authorize", + scopes: _scopes, + state, + redirectURI, + codeVerifier + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI, deviceId }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI: options.redirectURI || redirectURI, + options, + deviceId, + tokenEndpoint: tokenEndpoint2 + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: tokenEndpoint2 + }); + }, + async getUserInfo(data) { + if (options.getUserInfo) return options.getUserInfo(data); + if (!data.accessToken) return null; + const formBody = new URLSearchParams({ + access_token: data.accessToken, + client_id: options.clientId + }).toString(); + const { data: profile, error: error49 } = await betterFetch("https://id.vk.com/oauth2/user_info", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: formBody + }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + if (!profile.user.email && !userMap?.email) return null; + return { + user: { + id: profile.user.user_id, + first_name: profile.user.first_name, + last_name: profile.user.last_name, + email: profile.user.email, + image: profile.user.avatar, + emailVerified: false, + birthday: profile.user.birthday, + sex: profile.user.sex, + name: `${profile.user.first_name} ${profile.user.last_name}`, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/wechat.mjs +var wechat = (options) => { + return { + id: "wechat", + name: "WeChat", + createAuthorizationURL({ state, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["snsapi_login"]; + options.scope && _scopes.push(...options.scope); + scopes && _scopes.push(...scopes); + const url2 = new URL("https://open.weixin.qq.com/connect/qrconnect"); + url2.searchParams.set("scope", _scopes.join(",")); + url2.searchParams.set("response_type", "code"); + url2.searchParams.set("appid", options.clientId); + url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); + url2.searchParams.set("state", state); + url2.searchParams.set("lang", options.lang || "cn"); + url2.hash = "wechat_redirect"; + return url2; + }, + validateAuthorizationCode: async ({ code }) => { + const { data: tokenData, error: error49 } = await betterFetch("https://api.weixin.qq.com/sns/oauth2/access_token?" + new URLSearchParams({ + appid: options.clientId, + secret: options.clientSecret, + code, + grant_type: "authorization_code" + }).toString(), { method: "GET" }); + if (error49 || !tokenData || tokenData.errcode) throw new Error(`Failed to validate authorization code: ${tokenData?.errmsg || error49?.message || "Unknown error"}`); + return { + tokenType: "Bearer", + accessToken: tokenData.access_token, + refreshToken: tokenData.refresh_token, + accessTokenExpiresAt: new Date(Date.now() + tokenData.expires_in * 1e3), + scopes: tokenData.scope.split(","), + openid: tokenData.openid, + unionid: tokenData.unionid + }; + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + const { data: tokenData, error: error49 } = await betterFetch("https://api.weixin.qq.com/sns/oauth2/refresh_token?" + new URLSearchParams({ + appid: options.clientId, + grant_type: "refresh_token", + refresh_token: refreshToken2 + }).toString(), { method: "GET" }); + if (error49 || !tokenData || tokenData.errcode) throw new Error(`Failed to refresh access token: ${tokenData?.errmsg || error49?.message || "Unknown error"}`); + return { + tokenType: "Bearer", + accessToken: tokenData.access_token, + refreshToken: tokenData.refresh_token, + accessTokenExpiresAt: new Date(Date.now() + tokenData.expires_in * 1e3), + scopes: tokenData.scope.split(",") + }; + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const openid = token.openid; + if (!openid) return null; + const { data: profile, error: error49 } = await betterFetch("https://api.weixin.qq.com/sns/userinfo?" + new URLSearchParams({ + access_token: token.accessToken || "", + openid, + lang: "zh_CN" + }).toString(), { method: "GET" }); + if (error49 || !profile || profile.errcode) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.unionid || profile.openid || openid, + name: profile.nickname, + email: profile.email || null, + image: profile.headimgurl, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/zoom.mjs +var zoom = (userOptions) => { + const options = { + pkce: true, + ...userOptions + }; + return { + id: "zoom", + name: "Zoom", + createAuthorizationURL: async ({ state, redirectURI, codeVerifier }) => { + const params = new URLSearchParams({ + response_type: "code", + redirect_uri: options.redirectURI ? options.redirectURI : redirectURI, + client_id: options.clientId, + state + }); + if (options.pkce) { + const codeChallenge = await generateCodeChallenge(codeVerifier); + params.set("code_challenge_method", "S256"); + params.set("code_challenge", codeChallenge); + } + const url2 = new URL("https://zoom.us/oauth/authorize"); + url2.search = params.toString(); + return url2; + }, + validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => { + return validateAuthorizationCode({ + code, + redirectURI: options.redirectURI || redirectURI, + codeVerifier, + options, + tokenEndpoint: "https://zoom.us/oauth/token", + authentication: "post" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://zoom.us/oauth/token" + }), + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error49 } = await betterFetch("https://api.zoom.us/v2/users/me", { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error49) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.display_name, + image: profile.pic_url, + email: profile.email, + emailVerified: Boolean(profile.verified), + ...userMap + }, + data: { ...profile } + }; + } + }; +}; + +// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/index.mjs +init_zod(); +var socialProviders = { + apple, + atlassian, + cognito, + discord, + facebook, + figma, + github, + microsoft, + google, + huggingface, + slack, + spotify, + twitch, + twitter, + dropbox, + kick, + linear, + linkedin, + gitlab, + tiktok, + reddit, + roblox, + salesforce, + vk, + zoom, + notion, + kakao, + naver, + line, + paybin, + paypal, + polar, + railway, + vercel, + wechat +}; +var socialProviderList = Object.keys(socialProviders); +var SocialProviderListEnum = _enum2(socialProviderList).or(string2()); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/account.mjs +init_zod(); +var listUserAccounts = createAuthEndpoint("/list-accounts", { + method: "GET", + use: [sessionMiddleware], + metadata: { openapi: { + operationId: "listUserAccounts", + description: "List all accounts linked to the user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "array", + items: { + type: "object", + properties: { + id: { type: "string" }, + providerId: { type: "string" }, + createdAt: { + type: "string", + format: "date-time" + }, + updatedAt: { + type: "string", + format: "date-time" + }, + accountId: { type: "string" }, + userId: { type: "string" }, + scopes: { + type: "array", + items: { type: "string" } + } + }, + required: [ + "id", + "providerId", + "createdAt", + "updatedAt", + "accountId", + "userId", + "scopes" + ] + } + } } } + } } + } } +}, async (c) => { + const session = c.context.session; + const accounts2 = await c.context.internalAdapter.findAccounts(session.user.id); + return c.json(accounts2.map((a) => { + const { scope, ...parsed } = parseAccountOutput(c.context.options, a); + return { + ...parsed, + scopes: scope?.split(",") || [] + }; + })); +}); +var linkSocialAccount = createAuthEndpoint("/link-social", { + method: "POST", + requireHeaders: true, + body: object({ + callbackURL: string2().meta({ description: "The URL to redirect to after the user has signed in" }).optional(), + provider: SocialProviderListEnum, + idToken: object({ + token: string2(), + nonce: string2().optional(), + accessToken: string2().optional(), + refreshToken: string2().optional(), + scopes: array(string2()).optional() + }).optional(), + requestSignUp: boolean2().optional(), + scopes: array(string2()).meta({ description: "Additional scopes to request from the provider" }).optional(), + errorCallbackURL: string2().meta({ description: "The URL to redirect to if there is an error during the link process" }).optional(), + disableRedirect: boolean2().meta({ description: "Disable automatic redirection to the provider. Useful for handling the redirection yourself" }).optional(), + additionalData: record(string2(), any()).optional() + }), + use: [sessionMiddleware], + metadata: { openapi: { + description: "Link a social account to the user", + operationId: "linkSocialAccount", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + url: { + type: "string", + description: "The authorization URL to redirect the user to" + }, + redirect: { + type: "boolean", + description: "Indicates if the user should be redirected to the authorization URL" + }, + status: { type: "boolean" } + }, + required: ["redirect"] + } } } + } } + } } +}, async (c) => { + const session = c.context.session; + const provider = await getAwaitableValue(c.context.socialProviders, { value: c.body.provider }); + if (!provider) { + c.context.logger.error("Provider not found. Make sure to add the provider in your auth config", { provider: c.body.provider }); + throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.PROVIDER_NOT_FOUND); + } + if (c.body.idToken) { + if (!provider.verifyIdToken) { + c.context.logger.error("Provider does not support id token verification", { provider: c.body.provider }); + throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED); + } + const { token, nonce } = c.body.idToken; + if (!await provider.verifyIdToken(token, nonce)) { + c.context.logger.error("Invalid id token", { provider: c.body.provider }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_TOKEN); + } + const linkingUserInfo = await provider.getUserInfo({ + idToken: token, + accessToken: c.body.idToken.accessToken, + refreshToken: c.body.idToken.refreshToken + }); + if (!linkingUserInfo || !linkingUserInfo?.user) { + c.context.logger.error("Failed to get user info", { provider: c.body.provider }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO); + } + const linkingUserId = String(linkingUserInfo.user.id); + if (!linkingUserInfo.user.email) { + c.context.logger.error("User email not found", { provider: c.body.provider }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND); + } + if ((await c.context.internalAdapter.findAccounts(session.user.id)).find((a) => a.providerId === provider.id && a.accountId === linkingUserId)) return c.json({ + url: "", + status: true, + redirect: false + }); + if (!c.context.trustedProviders.includes(provider.id) && !linkingUserInfo.user.emailVerified || c.context.options.account?.accountLinking?.enabled === false) throw APIError2.from("UNAUTHORIZED", { + message: "Account not linked - linking not allowed", + code: "LINKING_NOT_ALLOWED" + }); + if (linkingUserInfo.user.email?.toLowerCase() !== session.user.email.toLowerCase() && c.context.options.account?.accountLinking?.allowDifferentEmails !== true) throw APIError2.from("UNAUTHORIZED", { + message: "Account not linked - different emails not allowed", + code: "LINKING_DIFFERENT_EMAILS_NOT_ALLOWED" + }); + try { + await c.context.internalAdapter.createAccount({ + userId: session.user.id, + providerId: provider.id, + accountId: linkingUserId, + accessToken: c.body.idToken.accessToken, + idToken: token, + refreshToken: c.body.idToken.refreshToken, + scope: c.body.idToken.scopes?.join(",") + }); + } catch (_e) { + throw APIError2.from("EXPECTATION_FAILED", { + message: "Account not linked - unable to create account", + code: "LINKING_FAILED" + }); + } + if (c.context.options.account?.accountLinking?.updateUserInfoOnLink === true) try { + await c.context.internalAdapter.updateUser(session.user.id, { + name: linkingUserInfo.user?.name, + image: linkingUserInfo.user?.image + }); + } catch (e) { + console.warn("Could not update user - " + e.toString()); + } + return c.json({ + url: "", + status: true, + redirect: false + }); + } + const state = await generateState(c, { + userId: session.user.id, + email: session.user.email + }, c.body.additionalData); + const url2 = await provider.createAuthorizationURL({ + state: state.state, + codeVerifier: state.codeVerifier, + redirectURI: `${c.context.baseURL}/callback/${provider.id}`, + scopes: c.body.scopes + }); + if (!c.body.disableRedirect) c.setHeader("Location", url2.toString()); + return c.json({ + url: url2.toString(), + redirect: !c.body.disableRedirect + }); +}); +var unlinkAccount = createAuthEndpoint("/unlink-account", { + method: "POST", + body: object({ + providerId: string2(), + accountId: string2().optional() + }), + use: [freshSessionMiddleware], + metadata: { openapi: { + description: "Unlink an account", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } } +}, async (ctx) => { + const { providerId, accountId } = ctx.body; + const accounts2 = await ctx.context.internalAdapter.findAccounts(ctx.context.session.user.id); + if (accounts2.length === 1 && !ctx.context.options.account?.accountLinking?.allowUnlinkingAll) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT); + const accountExist = accounts2.find((account) => accountId ? account.accountId === accountId && account.providerId === providerId : account.providerId === providerId); + if (!accountExist) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND); + await ctx.context.internalAdapter.deleteAccount(accountExist.id); + return ctx.json({ status: true }); +}); +var getAccessToken = createAuthEndpoint("/get-access-token", { + method: "POST", + body: object({ + providerId: string2().meta({ description: "The provider ID for the OAuth provider" }), + accountId: string2().meta({ description: "The account ID associated with the refresh token" }).optional(), + userId: string2().meta({ description: "The user ID associated with the account" }).optional() + }), + metadata: { openapi: { + description: "Get a valid access token, doing a refresh if needed", + responses: { + 200: { + description: "A Valid access token", + content: { "application/json": { schema: { + type: "object", + properties: { + tokenType: { type: "string" }, + idToken: { type: "string" }, + accessToken: { type: "string" }, + accessTokenExpiresAt: { + type: "string", + format: "date-time" + } + } + } } } + }, + 400: { description: "Invalid refresh token or provider configuration" } + } + } } +}, async (ctx) => { + const { providerId, accountId, userId } = ctx.body || {}; + const req = ctx.request; + const session = await getSessionFromCtx(ctx); + if (req && !session) throw ctx.error("UNAUTHORIZED"); + const resolvedUserId = session?.user?.id || userId; + if (!resolvedUserId) throw ctx.error("UNAUTHORIZED"); + const provider = await getAwaitableValue(ctx.context.socialProviders, { value: providerId }); + if (!provider) throw APIError2.from("BAD_REQUEST", { + message: `Provider ${providerId} is not supported.`, + code: "PROVIDER_NOT_SUPPORTED" + }); + const accountData = await getAccountCookie(ctx); + let account = void 0; + if (accountData && accountData.userId === resolvedUserId && providerId === accountData.providerId && (!accountId || accountData.accountId === accountId)) account = accountData; + else account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.accountId === accountId && acc.providerId === providerId : acc.providerId === providerId); + if (!account) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND); + try { + let newTokens = null; + const accessTokenExpired = account.accessTokenExpiresAt && new Date(account.accessTokenExpiresAt).getTime() - Date.now() < 5e3; + if (account.refreshToken && accessTokenExpired && provider.refreshAccessToken) { + const refreshToken2 = await decryptOAuthToken(account.refreshToken, ctx.context); + newTokens = await provider.refreshAccessToken(refreshToken2); + const updatedData = { + accessToken: await setTokenUtil(newTokens?.accessToken, ctx.context), + accessTokenExpiresAt: newTokens?.accessTokenExpiresAt, + refreshToken: newTokens?.refreshToken ? await setTokenUtil(newTokens.refreshToken, ctx.context) : account.refreshToken, + refreshTokenExpiresAt: newTokens?.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt, + idToken: newTokens?.idToken || account.idToken + }; + let updatedAccount = null; + if (account.id) updatedAccount = await ctx.context.internalAdapter.updateAccount(account.id, updatedData); + if (ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, { + ...account, + ...updatedAccount ?? updatedData + }); + } + const accessTokenExpiresAt = (() => { + if (newTokens?.accessTokenExpiresAt) { + if (typeof newTokens.accessTokenExpiresAt === "string") return new Date(newTokens.accessTokenExpiresAt); + return newTokens.accessTokenExpiresAt; + } + if (account.accessTokenExpiresAt) { + if (typeof account.accessTokenExpiresAt === "string") return new Date(account.accessTokenExpiresAt); + return account.accessTokenExpiresAt; + } + })(); + const tokens = { + accessToken: newTokens?.accessToken ?? await decryptOAuthToken(account.accessToken ?? "", ctx.context), + accessTokenExpiresAt, + scopes: account.scope?.split(",") ?? [], + idToken: newTokens?.idToken ?? account.idToken ?? void 0 + }; + return ctx.json(tokens); + } catch (_error) { + throw APIError2.from("BAD_REQUEST", { + message: "Failed to get a valid access token", + code: "FAILED_TO_GET_ACCESS_TOKEN" + }); + } +}); +var refreshToken = createAuthEndpoint("/refresh-token", { + method: "POST", + body: object({ + providerId: string2().meta({ description: "The provider ID for the OAuth provider" }), + accountId: string2().meta({ description: "The account ID associated with the refresh token" }).optional(), + userId: string2().meta({ description: "The user ID associated with the account" }).optional() + }), + metadata: { openapi: { + description: "Refresh the access token using a refresh token", + responses: { + 200: { + description: "Access token refreshed successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + tokenType: { type: "string" }, + idToken: { type: "string" }, + accessToken: { type: "string" }, + refreshToken: { type: "string" }, + accessTokenExpiresAt: { + type: "string", + format: "date-time" + }, + refreshTokenExpiresAt: { + type: "string", + format: "date-time" + } + } + } } } + }, + 400: { description: "Invalid refresh token or provider configuration" } + } + } } +}, async (ctx) => { + const { providerId, accountId, userId } = ctx.body; + const req = ctx.request; + const session = await getSessionFromCtx(ctx); + if (req && !session) throw ctx.error("UNAUTHORIZED"); + const resolvedUserId = session?.user?.id || userId; + if (!resolvedUserId) throw APIError2.from("BAD_REQUEST", { + message: `Either userId or session is required`, + code: "USER_ID_OR_SESSION_REQUIRED" + }); + const provider = await getAwaitableValue(ctx.context.socialProviders, { value: providerId }); + if (!provider) throw APIError2.from("BAD_REQUEST", { + message: `Provider ${providerId} is not supported.`, + code: "PROVIDER_NOT_SUPPORTED" + }); + if (!provider.refreshAccessToken) throw APIError2.from("BAD_REQUEST", { + message: `Provider ${providerId} does not support token refreshing.`, + code: "TOKEN_REFRESH_NOT_SUPPORTED" + }); + let account = void 0; + const accountData = await getAccountCookie(ctx); + if (accountData && accountData.userId === resolvedUserId && (!providerId || providerId === accountData?.providerId)) account = accountData; + else account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.accountId === accountId && acc.providerId === providerId : acc.providerId === providerId); + if (!account) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND); + let refreshToken2 = void 0; + if (accountData && providerId === accountData.providerId) refreshToken2 = accountData.refreshToken ?? void 0; + else refreshToken2 = account.refreshToken ?? void 0; + if (!refreshToken2) throw APIError2.from("BAD_REQUEST", { + message: "Refresh token not found", + code: "REFRESH_TOKEN_NOT_FOUND" + }); + try { + const decryptedRefreshToken = await decryptOAuthToken(refreshToken2, ctx.context); + const tokens = await provider.refreshAccessToken(decryptedRefreshToken); + const resolvedRefreshToken = tokens.refreshToken ? await setTokenUtil(tokens.refreshToken, ctx.context) : refreshToken2; + const resolvedRefreshTokenExpiresAt = tokens.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt; + if (account.id) { + const updateData = { + ...account || {}, + accessToken: await setTokenUtil(tokens.accessToken, ctx.context), + refreshToken: resolvedRefreshToken, + accessTokenExpiresAt: tokens.accessTokenExpiresAt, + refreshTokenExpiresAt: resolvedRefreshTokenExpiresAt, + scope: tokens.scopes?.join(",") || account.scope, + idToken: tokens.idToken || account.idToken + }; + await ctx.context.internalAdapter.updateAccount(account.id, updateData); + } + if (accountData && providerId === accountData.providerId && ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, { + ...accountData, + accessToken: await setTokenUtil(tokens.accessToken, ctx.context), + refreshToken: resolvedRefreshToken, + accessTokenExpiresAt: tokens.accessTokenExpiresAt, + refreshTokenExpiresAt: resolvedRefreshTokenExpiresAt, + scope: tokens.scopes?.join(",") || accountData.scope, + idToken: tokens.idToken || accountData.idToken + }); + return ctx.json({ + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken ?? decryptedRefreshToken, + accessTokenExpiresAt: tokens.accessTokenExpiresAt, + refreshTokenExpiresAt: resolvedRefreshTokenExpiresAt, + scope: tokens.scopes?.join(",") || account.scope, + idToken: tokens.idToken || account.idToken, + providerId: account.providerId, + accountId: account.accountId + }); + } catch (_error) { + throw APIError2.from("BAD_REQUEST", { + message: "Failed to refresh access token", + code: "FAILED_TO_REFRESH_ACCESS_TOKEN" + }); + } +}); +var accountInfoQuerySchema = optional(object({ accountId: string2().meta({ description: "The provider given account id for which to get the account info" }).optional() })); +var accountInfo = createAuthEndpoint("/account-info", { + method: "GET", + use: [sessionMiddleware], + metadata: { openapi: { + description: "Get the account info provided by the provider", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + user: { + type: "object", + properties: { + id: { type: "string" }, + name: { type: "string" }, + email: { type: "string" }, + image: { type: "string" }, + emailVerified: { type: "boolean" } + }, + required: ["id", "emailVerified"] + }, + data: { + type: "object", + properties: {}, + additionalProperties: true + } + }, + required: ["user", "data"], + additionalProperties: false + } } } + } } + } }, + query: accountInfoQuerySchema +}, async (ctx) => { + const providedAccountId = ctx.query?.accountId; + let account = void 0; + if (!providedAccountId) { + if (ctx.context.options.account?.storeAccountCookie) { + const accountData = await getAccountCookie(ctx); + if (accountData) account = accountData; + } + } else { + const accountData = await ctx.context.internalAdapter.findAccount(providedAccountId); + if (accountData) account = accountData; + } + if (!account || account.userId !== ctx.context.session.user.id) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND); + const provider = await getAwaitableValue(ctx.context.socialProviders, { value: account.providerId }); + if (!provider) throw APIError2.from("INTERNAL_SERVER_ERROR", { + message: `Provider account provider is ${account.providerId} but it is not configured`, + code: "PROVIDER_NOT_CONFIGURED" + }); + const tokens = await getAccessToken({ + ...ctx, + method: "POST", + body: { + accountId: account.accountId, + providerId: account.providerId + }, + returnHeaders: false, + returnStatus: false + }); + if (!tokens.accessToken) throw APIError2.from("BAD_REQUEST", { + message: "Access token not found", + code: "ACCESS_TOKEN_NOT_FOUND" + }); + const info2 = await provider.getUserInfo({ + ...tokens, + accessToken: tokens.accessToken + }); + return ctx.json(info2); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/email-verification.mjs +init_error2(); +init_zod(); +async function createEmailVerificationToken(secret, email3, updateTo, expiresIn = 3600, extraPayload) { + return await signJWT({ + email: email3.toLowerCase(), + updateTo, + ...extraPayload + }, secret, expiresIn); +} +async function sendVerificationEmailFn(ctx, user) { + if (!ctx.context.options.emailVerification?.sendVerificationEmail) { + ctx.context.logger.error("Verification email isn't enabled."); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED); + } + const token = await createEmailVerificationToken(ctx.context.secret, user.email, void 0, ctx.context.options.emailVerification?.expiresIn); + const callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent("/"); + const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user, + url: url2, + token + }, ctx.request)); +} +var sendVerificationEmail = createAuthEndpoint("/send-verification-email", { + method: "POST", + operationId: "sendVerificationEmail", + body: object({ + email: email2().meta({ description: "The email to send the verification email to" }), + callbackURL: string2().meta({ description: "The URL to use for email verification callback" }).optional() + }), + metadata: { openapi: { + operationId: "sendVerificationEmail", + description: "Send a verification email to the user", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + email: { + type: "string", + description: "The email to send the verification email to", + example: "user@example.com" + }, + callbackURL: { + type: "string", + description: "The URL to use for email verification callback", + example: "https://example.com/callback", + nullable: true + } + }, + required: ["email"] + } } } }, + responses: { + "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { + type: "boolean", + description: "Indicates if the email was sent successfully", + example: true + } } + } } } + }, + "400": { + description: "Bad Request", + content: { "application/json": { schema: { + type: "object", + properties: { message: { + type: "string", + description: "Error message", + example: "Verification email isn't enabled" + } } + } } } + } + } + } } +}, async (ctx) => { + if (!ctx.context.options.emailVerification?.sendVerificationEmail) { + ctx.context.logger.error("Verification email isn't enabled."); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED); + } + const { email: email3 } = ctx.body; + const session = await getSessionFromCtx(ctx); + if (!session) { + const user = await ctx.context.internalAdapter.findUserByEmail(email3); + if (!user || user.user.emailVerified) { + await createEmailVerificationToken(ctx.context.secret, email3, void 0, ctx.context.options.emailVerification?.expiresIn); + return ctx.json({ status: true }); + } + await sendVerificationEmailFn(ctx, user.user); + return ctx.json({ status: true }); + } + if (session?.user.email !== email3) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.EMAIL_MISMATCH); + if (session?.user.emailVerified) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.EMAIL_ALREADY_VERIFIED); + await sendVerificationEmailFn(ctx, session.user); + return ctx.json({ status: true }); +}); +var verifyEmail = createAuthEndpoint("/verify-email", { + method: "GET", + operationId: "verifyEmail", + query: object({ + token: string2().meta({ description: "The token to verify the email" }), + callbackURL: string2().meta({ description: "The URL to redirect to after email verification" }).optional() + }), + use: [originCheck((ctx) => ctx.query.callbackURL)], + metadata: { openapi: { + description: "Verify the email of the user", + parameters: [{ + name: "token", + in: "query", + description: "The token to verify the email", + required: true, + schema: { type: "string" } + }, { + name: "callbackURL", + in: "query", + description: "The URL to redirect to after email verification", + required: false, + schema: { type: "string" } + }], + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + user: { + type: "object", + $ref: "#/components/schemas/User" + }, + status: { + type: "boolean", + description: "Indicates if the email was verified successfully" + } + }, + required: ["user", "status"] + } } } + } } + } } +}, async (ctx) => { + function redirectOnError(error49) { + if (ctx.query.callbackURL) { + if (ctx.query.callbackURL.includes("?")) throw ctx.redirect(`${ctx.query.callbackURL}&error=${error49.code}`); + throw ctx.redirect(`${ctx.query.callbackURL}?error=${error49.code}`); + } + throw APIError2.from("UNAUTHORIZED", error49); + } + const { token } = ctx.query; + let jwt2; + try { + jwt2 = await jwtVerify(token, new TextEncoder().encode(ctx.context.secret), { algorithms: ["HS256"] }); + } catch (e) { + if (e instanceof JWTExpired) return redirectOnError(BASE_ERROR_CODES.TOKEN_EXPIRED); + return redirectOnError(BASE_ERROR_CODES.INVALID_TOKEN); + } + const parsed = object({ + email: email2(), + updateTo: string2().optional(), + requestType: string2().optional() + }).parse(jwt2.payload); + const user = await ctx.context.internalAdapter.findUserByEmail(parsed.email); + if (!user) return redirectOnError(BASE_ERROR_CODES.USER_NOT_FOUND); + if (parsed.updateTo) { + const session = await getSessionFromCtx(ctx); + if (session && session.user.email !== parsed.email) return redirectOnError(BASE_ERROR_CODES.INVALID_USER); + switch (parsed.requestType) { + case "change-email-confirmation": { + const newToken = await createEmailVerificationToken(ctx.context.secret, parsed.email, parsed.updateTo, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-verification" }); + const updateCallbackURL = ctx.query.callbackURL ? encodeURIComponent(ctx.query.callbackURL) : encodeURIComponent("/"); + const url2 = `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${updateCallbackURL}`; + if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: { + ...user.user, + email: parsed.updateTo + }, + url: url2, + token: newToken + }, ctx.request)); + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ status: true }); + } + case "change-email-verification": { + let activeSession = session; + if (!activeSession) { + const newSession = await ctx.context.internalAdapter.createSession(user.user.id); + if (!newSession) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); + activeSession = { + session: newSession, + user: user.user + }; + } + const updatedUser2 = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { + email: parsed.updateTo, + emailVerified: true + }); + if (ctx.context.options.emailVerification?.afterEmailVerification) await ctx.context.options.emailVerification.afterEmailVerification(updatedUser2, ctx.request); + await setSessionCookie(ctx, { + session: activeSession.session, + user: { + ...activeSession.user, + email: parsed.updateTo, + emailVerified: true + } + }); + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ + status: true, + user: parseUserOutput(ctx.context.options, updatedUser2) + }); + } + default: { + let activeSession = session; + if (!activeSession) { + const newSession = await ctx.context.internalAdapter.createSession(user.user.id); + if (!newSession) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); + activeSession = { + session: newSession, + user: user.user + }; + } + const updatedUser2 = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { + email: parsed.updateTo, + emailVerified: false + }); + const newToken = await createEmailVerificationToken(ctx.context.secret, parsed.updateTo); + const updateCallbackURL = ctx.query.callbackURL ? encodeURIComponent(ctx.query.callbackURL) : encodeURIComponent("/"); + if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: updatedUser2, + url: `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${updateCallbackURL}`, + token: newToken + }, ctx.request)); + await setSessionCookie(ctx, { + session: activeSession.session, + user: { + ...activeSession.user, + email: parsed.updateTo, + emailVerified: false + } + }); + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ + status: true, + user: parseUserOutput(ctx.context.options, updatedUser2) + }); + } + } + } + if (user.user.emailVerified) { + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ + status: true, + user: null + }); + } + if (ctx.context.options.emailVerification?.beforeEmailVerification) await ctx.context.options.emailVerification.beforeEmailVerification(user.user, ctx.request); + const updatedUser = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { emailVerified: true }); + if (ctx.context.options.emailVerification?.afterEmailVerification) await ctx.context.options.emailVerification.afterEmailVerification(updatedUser, ctx.request); + if (ctx.context.options.emailVerification?.autoSignInAfterVerification) { + const currentSession = await getSessionFromCtx(ctx); + if (!currentSession || currentSession.user.email !== parsed.email) { + const session = await ctx.context.internalAdapter.createSession(user.user.id); + if (!session) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); + await setSessionCookie(ctx, { + session, + user: { + ...user.user, + emailVerified: true + } + }); + } else await setSessionCookie(ctx, { + session: currentSession.session, + user: { + ...currentSession.user, + emailVerified: true + } + }); + } + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ + status: true, + user: null + }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/link-account.mjs +init_env(); +async function handleOAuthUserInfo(c, opts) { + const { userInfo, account, callbackURL, disableSignUp, overrideUserInfo } = opts; + const dbUser = await c.context.internalAdapter.findOAuthUser(userInfo.email.toLowerCase(), account.accountId, account.providerId).catch((e) => { + logger.error("Better auth was unable to query your database.\nError: ", e); + const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`; + throw c.redirect(`${errorURL}?error=internal_server_error`); + }); + let user = dbUser?.user; + const isRegister = !user; + if (dbUser) { + const linkedAccount = dbUser.linkedAccount ?? dbUser.accounts.find((acc) => acc.providerId === account.providerId && acc.accountId === account.accountId); + if (!linkedAccount) { + const accountLinking = c.context.options.account?.accountLinking; + if (!(opts.isTrustedProvider || c.context.trustedProviders.includes(account.providerId)) && !userInfo.emailVerified || accountLinking?.enabled === false || accountLinking?.disableImplicitLinking === true) { + if (isDevelopment()) logger.warn(`User already exist but account isn't linked to ${account.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`); + return { + error: "account not linked", + data: null + }; + } + try { + await c.context.internalAdapter.linkAccount({ + providerId: account.providerId, + accountId: userInfo.id.toString(), + userId: dbUser.user.id, + accessToken: await setTokenUtil(account.accessToken, c.context), + refreshToken: await setTokenUtil(account.refreshToken, c.context), + idToken: account.idToken, + accessTokenExpiresAt: account.accessTokenExpiresAt, + refreshTokenExpiresAt: account.refreshTokenExpiresAt, + scope: account.scope + }); + } catch (e) { + logger.error("Unable to link account", e); + return { + error: "unable to link account", + data: null + }; + } + if (userInfo.emailVerified && !dbUser.user.emailVerified && userInfo.email.toLowerCase() === dbUser.user.email) await c.context.internalAdapter.updateUser(dbUser.user.id, { emailVerified: true }); + } else { + const freshTokens = c.context.options.account?.updateAccountOnSignIn !== false ? Object.fromEntries(Object.entries({ + idToken: account.idToken, + accessToken: await setTokenUtil(account.accessToken, c.context), + refreshToken: await setTokenUtil(account.refreshToken, c.context), + accessTokenExpiresAt: account.accessTokenExpiresAt, + refreshTokenExpiresAt: account.refreshTokenExpiresAt, + scope: account.scope + }).filter(([_, value]) => value !== void 0)) : {}; + if (c.context.options.account?.storeAccountCookie) await setAccountCookie(c, { + ...linkedAccount, + ...freshTokens + }); + if (Object.keys(freshTokens).length > 0) await c.context.internalAdapter.updateAccount(linkedAccount.id, freshTokens); + if (userInfo.emailVerified && !dbUser.user.emailVerified && userInfo.email.toLowerCase() === dbUser.user.email) await c.context.internalAdapter.updateUser(dbUser.user.id, { emailVerified: true }); + } + if (overrideUserInfo) { + const { id: _, ...restUserInfo } = userInfo; + user = await c.context.internalAdapter.updateUser(dbUser.user.id, { + ...restUserInfo, + email: userInfo.email.toLowerCase(), + emailVerified: userInfo.email.toLowerCase() === dbUser.user.email ? dbUser.user.emailVerified || userInfo.emailVerified : userInfo.emailVerified + }); + } + } else { + if (disableSignUp) return { + error: "signup disabled", + data: null, + isRegister: false + }; + try { + const { id: _, ...restUserInfo } = userInfo; + const accountData = { + accessToken: await setTokenUtil(account.accessToken, c.context), + refreshToken: await setTokenUtil(account.refreshToken, c.context), + idToken: account.idToken, + accessTokenExpiresAt: account.accessTokenExpiresAt, + refreshTokenExpiresAt: account.refreshTokenExpiresAt, + scope: account.scope, + providerId: account.providerId, + accountId: userInfo.id.toString() + }; + const { user: createdUser, account: createdAccount } = await c.context.internalAdapter.createOAuthUser({ + ...restUserInfo, + email: userInfo.email.toLowerCase() + }, accountData); + user = createdUser; + if (c.context.options.account?.storeAccountCookie) await setAccountCookie(c, createdAccount); + if (!userInfo.emailVerified && user && c.context.options.emailVerification?.sendOnSignUp && c.context.options.emailVerification?.sendVerificationEmail) { + const token = await createEmailVerificationToken(c.context.secret, user.email, void 0, c.context.options.emailVerification?.expiresIn); + const url2 = `${c.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; + await c.context.runInBackgroundOrAwait(c.context.options.emailVerification.sendVerificationEmail({ + user, + url: url2, + token + }, c.request)); + } + } catch (e) { + logger.error(e); + if (isAPIError2(e)) return { + error: e.message, + data: null, + isRegister: false + }; + return { + error: "unable to create user", + data: null, + isRegister: false + }; + } + } + if (!user) return { + error: "unable to create user", + data: null, + isRegister: false + }; + const session = await c.context.internalAdapter.createSession(user.id); + if (!session) return { + error: "unable to create session", + data: null, + isRegister: false + }; + return { + data: { + session, + user + }, + error: null, + isRegister + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/callback.mjs +init_json(); +init_zod(); +var schema = object({ + code: string2().optional(), + error: string2().optional(), + device_id: string2().optional(), + error_description: string2().optional(), + state: string2().optional(), + user: string2().optional() +}); +var callbackOAuth = createAuthEndpoint("/callback/:id", { + method: ["GET", "POST"], + operationId: "handleOAuthCallback", + body: schema.optional(), + query: schema.optional(), + metadata: { + ...HIDE_METADATA, + allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"] + } +}, async (c) => { + let queryOrBody; + const defaultErrorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`; + if (c.method === "POST") { + const postData = c.body ? schema.parse(c.body) : {}; + const queryData = c.query ? schema.parse(c.query) : {}; + const mergedData = schema.parse({ + ...postData, + ...queryData + }); + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(mergedData)) if (value !== void 0 && value !== null) params.set(key, String(value)); + const redirectURL = `${c.context.baseURL}/callback/${c.params.id}?${params.toString()}`; + throw c.redirect(redirectURL); + } + try { + if (c.method === "GET") queryOrBody = schema.parse(c.query); + else if (c.method === "POST") queryOrBody = schema.parse(c.body); + else throw new Error("Unsupported method"); + } catch (e) { + c.context.logger.error("INVALID_CALLBACK_REQUEST", e); + throw c.redirect(`${defaultErrorURL}?error=invalid_callback_request`); + } + const { code, error: error49, state, error_description, device_id, user: userData } = queryOrBody; + if (!state) { + c.context.logger.error("State not found", error49); + const url2 = `${defaultErrorURL}${defaultErrorURL.includes("?") ? "&" : "?"}state=state_not_found`; + throw c.redirect(url2); + } + const { codeVerifier, callbackURL, link, errorURL, newUserURL, requestSignUp } = await parseState(c); + function redirectOnError(error50, description) { + const baseURL = errorURL ?? defaultErrorURL; + const params = new URLSearchParams({ error: error50 }); + if (description) params.set("error_description", description); + const url2 = `${baseURL}${baseURL.includes("?") ? "&" : "?"}${params.toString()}`; + throw c.redirect(url2); + } + if (error49) redirectOnError(error49, error_description); + if (!code) { + c.context.logger.error("Code not found"); + throw redirectOnError("no_code"); + } + const provider = await getAwaitableValue(c.context.socialProviders, { value: c.params.id }); + if (!provider) { + c.context.logger.error("Oauth provider with id", c.params.id, "not found"); + throw redirectOnError("oauth_provider_not_found"); + } + let tokens; + try { + tokens = await provider.validateAuthorizationCode({ + code, + codeVerifier, + deviceId: device_id, + redirectURI: `${c.context.baseURL}/callback/${provider.id}` + }); + } catch (e) { + c.context.logger.error("", e); + throw redirectOnError("invalid_code"); + } + if (!tokens) throw redirectOnError("invalid_code"); + const parsedUserData = userData ? safeJSONParse(userData) : null; + const userInfo = await provider.getUserInfo({ + ...tokens, + user: parsedUserData ?? void 0 + }).then((res) => res?.user); + if (!userInfo) { + c.context.logger.error("Unable to get user info"); + return redirectOnError("unable_to_get_user_info"); + } + if (!callbackURL) { + c.context.logger.error("No callback URL found"); + throw redirectOnError("no_callback_url"); + } + if (link) { + if (!c.context.trustedProviders.includes(provider.id) && !userInfo.emailVerified || c.context.options.account?.accountLinking?.enabled === false) { + c.context.logger.error("Unable to link account - untrusted provider"); + return redirectOnError("unable_to_link_account"); + } + if (userInfo.email?.toLowerCase() !== link.email.toLowerCase() && c.context.options.account?.accountLinking?.allowDifferentEmails !== true) return redirectOnError("email_doesn't_match"); + const existingAccount = await c.context.internalAdapter.findAccountByProviderId(String(userInfo.id), provider.id); + if (existingAccount) { + if (existingAccount.userId.toString() !== link.userId.toString()) return redirectOnError("account_already_linked_to_different_user"); + const updateData = Object.fromEntries(Object.entries({ + accessToken: await setTokenUtil(tokens.accessToken, c.context), + refreshToken: await setTokenUtil(tokens.refreshToken, c.context), + idToken: tokens.idToken, + accessTokenExpiresAt: tokens.accessTokenExpiresAt, + refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, + scope: tokens.scopes?.join(",") + }).filter(([_, value]) => value !== void 0)); + await c.context.internalAdapter.updateAccount(existingAccount.id, updateData); + } else if (!await c.context.internalAdapter.createAccount({ + userId: link.userId, + providerId: provider.id, + accountId: String(userInfo.id), + ...tokens, + accessToken: await setTokenUtil(tokens.accessToken, c.context), + refreshToken: await setTokenUtil(tokens.refreshToken, c.context), + scope: tokens.scopes?.join(",") + })) return redirectOnError("unable_to_link_account"); + let toRedirectTo2; + try { + toRedirectTo2 = callbackURL.toString(); + } catch { + toRedirectTo2 = callbackURL; + } + throw c.redirect(toRedirectTo2); + } + if (!userInfo.email) { + c.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."); + return redirectOnError("email_not_found"); + } + const accountData = { + providerId: provider.id, + accountId: String(userInfo.id), + ...tokens, + scope: tokens.scopes?.join(",") + }; + const result = await handleOAuthUserInfo(c, { + userInfo: { + ...userInfo, + id: String(userInfo.id), + email: userInfo.email, + name: userInfo.name || "" + }, + account: accountData, + callbackURL, + disableSignUp: provider.disableImplicitSignUp && !requestSignUp || provider.options?.disableSignUp, + overrideUserInfo: provider.options?.overrideUserInfoOnSignIn + }); + if (result.error) { + c.context.logger.error(result.error.split(" ").join("_")); + return redirectOnError(result.error.split(" ").join("_")); + } + const { session, user } = result.data; + await setSessionCookie(c, { + session, + user + }); + let toRedirectTo; + try { + toRedirectTo = (result.isRegister ? newUserURL || callbackURL : callbackURL).toString(); + } catch { + toRedirectTo = result.isRegister ? newUserURL || callbackURL : callbackURL; + } + throw c.redirect(toRedirectTo); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/error.mjs +init_env(); +function sanitize(input) { + return input.replace(//g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g, "&"); +} +var html = (options, code = "Unknown", description = null) => { + const custom2 = options.onAPIError?.customizeDefaultErrorPage; + return ` + + + + + Error + + + +
+${custom2?.disableBackgroundGrid ? "" : ` +
+
+`} + +
+ ${custom2?.disableCornerDecorations ? "" : ` + +
+
+ +
+
`} + +
+
+
+

+ ERROR +

+
+
+
+ +

+ Something went wrong +

+ +
+ + CODE: + + + ${sanitize(code)} + +
+ +

+ ${!description ? `We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find more information about the error here.` : description} +

+
+ + +
+
+ +`; +}; +var error48 = createAuthEndpoint("/error", { + method: "GET", + metadata: { + ...HIDE_METADATA, + openapi: { + description: "Displays an error page", + responses: { "200": { + description: "Success", + content: { "text/html": { schema: { + type: "string", + description: "The HTML content of the error page" + } } } + } } + } + } +}, async (c) => { + const url2 = new URL(c.request?.url || ""); + const unsanitizedCode = url2.searchParams.get("error") || "UNKNOWN"; + const unsanitizedDescription = url2.searchParams.get("error_description") || null; + const safeCode = /^[\'A-Za-z0-9_-]+$/.test(unsanitizedCode || "") ? unsanitizedCode : "UNKNOWN"; + const safeDescription = unsanitizedDescription ? sanitize(unsanitizedDescription) : null; + const queryParams = new URLSearchParams(); + queryParams.set("error", safeCode); + if (unsanitizedDescription) queryParams.set("error_description", unsanitizedDescription); + const options = c.context.options; + const errorURL = options.onAPIError?.errorURL; + if (errorURL) return new Response(null, { + status: 302, + headers: { Location: `${errorURL}${errorURL.includes("?") ? "&" : "?"}${queryParams.toString()}` } + }); + if (isProduction && !options.onAPIError?.customizeDefaultErrorPage) return new Response(null, { + status: 302, + headers: { Location: `/?${queryParams.toString()}` } + }); + return new Response(html(c.context.options, safeCode, safeDescription), { headers: { "Content-Type": "text/html" } }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/ok.mjs +var ok = createAuthEndpoint("/ok", { + method: "GET", + metadata: { + ...HIDE_METADATA, + openapi: { + description: "Check if the API is working", + responses: { "200": { + description: "API is working", + content: { "application/json": { schema: { + type: "object", + properties: { ok: { + type: "boolean", + description: "Indicates if the API is working" + } }, + required: ["ok"] + } } } + } } + } + } +}, async (ctx) => { + return ctx.json({ ok: true }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/password.mjs +init_error2(); +async function validatePassword(ctx, data) { + const credentialAccount = (await ctx.context.internalAdapter.findAccounts(data.userId))?.find((account) => account.providerId === "credential"); + const currentPassword = credentialAccount?.password; + if (!credentialAccount || !currentPassword) return false; + return await ctx.context.password.verify({ + hash: currentPassword, + password: data.password + }); +} +async function checkPassword(userId, c) { + const credentialAccount = (await c.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === "credential"); + const currentPassword = credentialAccount?.password; + const password = c.body.password; + if (!credentialAccount || !currentPassword || !password) { + if (password) await c.context.password.hash(password); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + } + if (!await c.context.password.verify({ + hash: currentPassword, + password + })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + return true; +} +async function shouldRequirePassword(ctx, userId, allowPasswordless) { + if (!allowPasswordless) return true; + const credentialAccount = (await ctx.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === "credential" && account.password); + return Boolean(credentialAccount); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/password.mjs +init_error2(); +init_id2(); +init_zod(); +function redirectError(ctx, callbackURL, query) { + const url2 = callbackURL ? new URL(callbackURL, ctx.baseURL) : new URL(`${ctx.baseURL}/error`); + if (query) Object.entries(query).forEach(([k, v]) => url2.searchParams.set(k, v)); + return url2.href; +} +function redirectCallback(ctx, callbackURL, query) { + const url2 = new URL(callbackURL, ctx.baseURL); + if (query) Object.entries(query).forEach(([k, v]) => url2.searchParams.set(k, v)); + return url2.href; +} +var requestPasswordReset = createAuthEndpoint("/request-password-reset", { + method: "POST", + body: object({ + email: email2().meta({ description: "The email address of the user to send a password reset email to" }), + redirectTo: string2().meta({ description: "The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN" }).optional() + }), + metadata: { openapi: { + operationId: "requestPasswordReset", + description: "Send a password reset email to the user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + status: { type: "boolean" }, + message: { type: "string" } + } + } } } + } } + } }, + use: [originCheck((ctx) => ctx.body.redirectTo)] +}, async (ctx) => { + if (!ctx.context.options.emailAndPassword?.sendResetPassword) { + ctx.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"); + throw APIError2.from("BAD_REQUEST", { + message: "Reset password isn't enabled", + code: "RESET_PASSWORD_DISABLED" + }); + } + const { email: email3, redirectTo } = ctx.body; + const user = await ctx.context.internalAdapter.findUserByEmail(email3, { includeAccounts: true }); + if (!user) { + generateId(24); + await ctx.context.internalAdapter.findVerificationValue("dummy-verification-token"); + ctx.context.logger.error("Reset Password: User not found", { email: email3 }); + return ctx.json({ + status: true, + message: "If this email exists in our system, check your email for the reset link" + }); + } + const expiresAt = getDate(ctx.context.options.emailAndPassword.resetPasswordTokenExpiresIn || 3600 * 1, "sec"); + const verificationToken = generateId(24); + await ctx.context.internalAdapter.createVerificationValue({ + value: user.user.id, + identifier: `reset-password:${verificationToken}`, + expiresAt + }); + const callbackURL = redirectTo ? encodeURIComponent(redirectTo) : ""; + const url2 = `${ctx.context.baseURL}/reset-password/${verificationToken}?callbackURL=${callbackURL}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.sendResetPassword({ + user: user.user, + url: url2, + token: verificationToken + }, ctx.request)); + return ctx.json({ + status: true, + message: "If this email exists in our system, check your email for the reset link" + }); +}); +var requestPasswordResetCallback = createAuthEndpoint("/reset-password/:token", { + method: "GET", + operationId: "forgetPasswordCallback", + query: object({ callbackURL: string2().meta({ description: "The URL to redirect the user to reset their password" }) }), + use: [originCheck((ctx) => ctx.query.callbackURL)], + metadata: { openapi: { + operationId: "resetPasswordCallback", + description: "Redirects the user to the callback URL with the token", + parameters: [{ + name: "token", + in: "path", + required: true, + description: "The token to reset the password", + schema: { type: "string" } + }, { + name: "callbackURL", + in: "query", + required: true, + description: "The URL to redirect the user to reset their password", + schema: { type: "string" } + }], + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { token: { type: "string" } } + } } } + } } + } } +}, async (ctx) => { + const { token } = ctx.params; + const { callbackURL } = ctx.query; + if (!token || !callbackURL) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: "INVALID_TOKEN" })); + const verification = await ctx.context.internalAdapter.findVerificationValue(`reset-password:${token}`); + if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: "INVALID_TOKEN" })); + throw ctx.redirect(redirectCallback(ctx.context, callbackURL, { token })); +}); +var resetPassword = createAuthEndpoint("/reset-password", { + method: "POST", + operationId: "resetPassword", + query: object({ token: string2().optional() }).optional(), + body: object({ + newPassword: string2().meta({ description: "The new password to set" }), + token: string2().meta({ description: "The token to reset the password" }).optional() + }), + metadata: { openapi: { + operationId: "resetPassword", + description: "Reset the password for a user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } } +}, async (ctx) => { + const token = ctx.body.token || ctx.query?.token; + if (!token) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_TOKEN); + const { newPassword } = ctx.body; + const minLength = ctx.context.password?.config.minPasswordLength; + const maxLength = ctx.context.password?.config.maxPasswordLength; + if (newPassword.length < minLength) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_SHORT); + if (newPassword.length > maxLength) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_LONG); + const id = `reset-password:${token}`; + const verification = await ctx.context.internalAdapter.findVerificationValue(id); + if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_TOKEN); + const userId = verification.value; + const hashedPassword = await ctx.context.password.hash(newPassword); + if (!(await ctx.context.internalAdapter.findAccounts(userId)).find((ac) => ac.providerId === "credential")) await ctx.context.internalAdapter.createAccount({ + userId, + providerId: "credential", + password: hashedPassword, + accountId: userId + }); + else await ctx.context.internalAdapter.updatePassword(userId, hashedPassword); + await ctx.context.internalAdapter.deleteVerificationByIdentifier(id); + if (ctx.context.options.emailAndPassword?.onPasswordReset) { + const user = await ctx.context.internalAdapter.findUserById(userId); + if (user) await ctx.context.options.emailAndPassword.onPasswordReset({ user }, ctx.request); + } + if (ctx.context.options.emailAndPassword?.revokeSessionsOnPasswordReset) await ctx.context.internalAdapter.deleteSessions(userId); + return ctx.json({ status: true }); +}); +var verifyPassword2 = createAuthEndpoint("/verify-password", { + method: "POST", + body: object({ password: string2().meta({ description: "The password to verify" }) }), + metadata: { + scope: "server", + openapi: { + operationId: "verifyPassword", + description: "Verify the current user's password", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } + }, + use: [sensitiveSessionMiddleware] +}, async (ctx) => { + const { password } = ctx.body; + const session = ctx.context.session; + if (!await validatePassword(ctx, { + password, + userId: session.user.id + })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + return ctx.json({ status: true }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-in.mjs +init_error2(); +init_zod(); +var socialSignInBodySchema = object({ + callbackURL: string2().meta({ description: "Callback URL to redirect to after the user has signed in" }).optional(), + newUserCallbackURL: string2().optional(), + errorCallbackURL: string2().meta({ description: "Callback URL to redirect to if an error happens" }).optional(), + provider: SocialProviderListEnum, + disableRedirect: boolean2().meta({ description: "Disable automatic redirection to the provider. Useful for handling the redirection yourself" }).optional(), + idToken: optional(object({ + token: string2().meta({ description: "ID token from the provider" }), + nonce: string2().meta({ description: "Nonce used to generate the token" }).optional(), + accessToken: string2().meta({ description: "Access token from the provider" }).optional(), + refreshToken: string2().meta({ description: "Refresh token from the provider" }).optional(), + expiresAt: number2().meta({ description: "Expiry date of the token" }).optional(), + user: object({ + name: object({ + firstName: string2().optional(), + lastName: string2().optional() + }).optional(), + email: string2().optional() + }).meta({ description: "The user object from the provider. Only available for some providers like Apple." }).optional() + })), + scopes: array(string2()).meta({ description: "Array of scopes to request from the provider. This will override the default scopes passed." }).optional(), + requestSignUp: boolean2().meta({ description: "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider" }).optional(), + loginHint: string2().meta({ description: "The login hint to use for the authorization code request" }).optional(), + additionalData: record(string2(), any()).optional().meta({ description: "Additional data to be passed through the OAuth flow" }) +}); +var signInSocial = () => createAuthEndpoint("/sign-in/social", { + method: "POST", + operationId: "socialSignIn", + body: socialSignInBodySchema, + metadata: { + $Infer: { + body: {}, + returned: {} + }, + openapi: { + description: "Sign in with a social provider", + operationId: "socialSignIn", + responses: { "200": { + description: "Success - Returns either session details or redirect URL", + content: { "application/json": { schema: { + type: "object", + description: "Session response when idToken is provided", + properties: { + token: { type: "string" }, + user: { + type: "object", + $ref: "#/components/schemas/User" + }, + url: { type: "string" }, + redirect: { + type: "boolean", + enum: [false] + } + }, + required: [ + "redirect", + "token", + "user" + ] + } } } + } } + } + } +}, async (c) => { + const provider = await getAwaitableValue(c.context.socialProviders, { value: c.body.provider }); + if (!provider) { + c.context.logger.error("Provider not found. Make sure to add the provider in your auth config", { provider: c.body.provider }); + throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.PROVIDER_NOT_FOUND); + } + if (c.body.idToken) { + if (!provider.verifyIdToken) { + c.context.logger.error("Provider does not support id token verification", { provider: c.body.provider }); + throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED); + } + const { token, nonce } = c.body.idToken; + if (!await provider.verifyIdToken(token, nonce)) { + c.context.logger.error("Invalid id token", { provider: c.body.provider }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_TOKEN); + } + const userInfo = await provider.getUserInfo({ + idToken: token, + accessToken: c.body.idToken.accessToken, + refreshToken: c.body.idToken.refreshToken, + user: c.body.idToken.user + }); + if (!userInfo || !userInfo?.user) { + c.context.logger.error("Failed to get user info", { provider: c.body.provider }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO); + } + if (!userInfo.user.email) { + c.context.logger.error("User email not found", { provider: c.body.provider }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND); + } + const data = await handleOAuthUserInfo(c, { + userInfo: { + ...userInfo.user, + email: userInfo.user.email, + id: String(userInfo.user.id), + name: userInfo.user.name || "", + image: userInfo.user.image, + emailVerified: userInfo.user.emailVerified || false + }, + account: { + providerId: provider.id, + accountId: String(userInfo.user.id), + accessToken: c.body.idToken.accessToken + }, + callbackURL: c.body.callbackURL, + disableSignUp: provider.disableImplicitSignUp && !c.body.requestSignUp || provider.disableSignUp + }); + if (data.error) throw APIError2.from("UNAUTHORIZED", { + message: data.error, + code: "OAUTH_LINK_ERROR" + }); + await setSessionCookie(c, data.data); + return c.json({ + redirect: false, + token: data.data.session.token, + url: void 0, + user: parseUserOutput(c.context.options, data.data.user) + }); + } + const { codeVerifier, state } = await generateState(c, void 0, c.body.additionalData); + const url2 = await provider.createAuthorizationURL({ + state, + codeVerifier, + redirectURI: `${c.context.baseURL}/callback/${provider.id}`, + scopes: c.body.scopes, + loginHint: c.body.loginHint + }); + if (!c.body.disableRedirect) c.setHeader("Location", url2.toString()); + return c.json({ + url: url2.toString(), + redirect: !c.body.disableRedirect + }); +}); +var signInEmail = () => createAuthEndpoint("/sign-in/email", { + method: "POST", + operationId: "signInEmail", + use: [formCsrfMiddleware], + body: object({ + email: string2().meta({ description: "Email of the user" }), + password: string2().meta({ description: "Password of the user" }), + callbackURL: string2().meta({ description: "Callback URL to use as a redirect for email verification" }).optional(), + rememberMe: boolean2().meta({ description: "If this is false, the session will not be remembered. Default is `true`." }).default(true).optional() + }), + metadata: { + allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"], + $Infer: { + body: {}, + returned: {} + }, + openapi: { + operationId: "signInEmail", + description: "Sign in with email and password", + responses: { "200": { + description: "Success - Returns either session details or redirect URL", + content: { "application/json": { schema: { + type: "object", + description: "Session response when idToken is provided", + properties: { + redirect: { + type: "boolean", + enum: [false] + }, + token: { + type: "string", + description: "Session token" + }, + url: { + type: "string", + nullable: true + }, + user: { + type: "object", + $ref: "#/components/schemas/User" + } + }, + required: [ + "redirect", + "token", + "user" + ] + } } } + } } + } + } +}, async (ctx) => { + if (!ctx.context.options?.emailAndPassword?.enabled) { + ctx.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"); + throw APIError2.from("BAD_REQUEST", { + code: "EMAIL_PASSWORD_DISABLED", + message: "Email and password is not enabled" + }); + } + const { email: email3, password } = ctx.body; + if (!email2().safeParse(email3).success) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_EMAIL); + const user = await ctx.context.internalAdapter.findUserByEmail(email3, { includeAccounts: true }); + if (!user) { + await ctx.context.password.hash(password); + ctx.context.logger.error("User not found", { email: email3 }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); + } + const credentialAccount = user.accounts.find((a) => a.providerId === "credential"); + if (!credentialAccount) { + await ctx.context.password.hash(password); + ctx.context.logger.error("Credential account not found", { email: email3 }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); + } + const currentPassword = credentialAccount?.password; + if (!currentPassword) { + await ctx.context.password.hash(password); + ctx.context.logger.error("Password not found", { email: email3 }); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); + } + if (!await ctx.context.password.verify({ + hash: currentPassword, + password + })) { + ctx.context.logger.error("Invalid password"); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); + } + if (ctx.context.options?.emailAndPassword?.requireEmailVerification && !user.user.emailVerified) { + if (!ctx.context.options?.emailVerification?.sendVerificationEmail) throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.EMAIL_NOT_VERIFIED); + if (ctx.context.options?.emailVerification?.sendOnSignIn) { + const token = await createEmailVerificationToken(ctx.context.secret, user.user.email, void 0, ctx.context.options.emailVerification?.expiresIn); + const callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent("/"); + const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: user.user, + url: url2, + token + }, ctx.request)); + } + throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.EMAIL_NOT_VERIFIED); + } + const session = await ctx.context.internalAdapter.createSession(user.user.id, ctx.body.rememberMe === false); + if (!session) { + ctx.context.logger.error("Failed to create session"); + throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); + } + await setSessionCookie(ctx, { + session, + user: user.user + }, ctx.body.rememberMe === false); + if (ctx.body.callbackURL) ctx.setHeader("Location", ctx.body.callbackURL); + return ctx.json({ + redirect: !!ctx.body.callbackURL, + token: session.token, + url: ctx.body.callbackURL, + user: parseUserOutput(ctx.context.options, user.user) + }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-out.mjs +var signOut = createAuthEndpoint("/sign-out", { + method: "POST", + operationId: "signOut", + requireHeaders: true, + metadata: { openapi: { + operationId: "signOut", + description: "Sign out the current user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { success: { type: "boolean" } } + } } } + } } + } } +}, async (ctx) => { + const sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret); + if (sessionCookieToken) try { + await ctx.context.internalAdapter.deleteSession(sessionCookieToken); + } catch (e) { + ctx.context.logger.error("Failed to delete session from database", e); + } + deleteSessionCookie(ctx); + return ctx.json({ success: true }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-up.mjs +init_env(); +init_error2(); +init_id2(); +init_zod(); +var signUpEmailBodySchema = object({ + name: string2(), + email: email2(), + password: string2().nonempty(), + image: string2().optional(), + callbackURL: string2().optional(), + rememberMe: boolean2().optional() +}).and(record(string2(), any())); +var signUpEmail = () => createAuthEndpoint("/sign-up/email", { + method: "POST", + operationId: "signUpWithEmailAndPassword", + use: [formCsrfMiddleware], + body: signUpEmailBodySchema, + metadata: { + allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"], + $Infer: { + body: {}, + returned: {} + }, + openapi: { + operationId: "signUpWithEmailAndPassword", + description: "Sign up a user using email and password", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the user" + }, + email: { + type: "string", + description: "The email of the user" + }, + password: { + type: "string", + description: "The password of the user" + }, + image: { + type: "string", + description: "The profile image URL of the user" + }, + callbackURL: { + type: "string", + description: "The URL to use for email verification callback" + }, + rememberMe: { + type: "boolean", + description: "If this is false, the session will not be remembered. Default is `true`." + } + }, + required: [ + "name", + "email", + "password" + ] + } } } }, + responses: { + "200": { + description: "Successfully created user", + content: { "application/json": { schema: { + type: "object", + properties: { + token: { + type: "string", + nullable: true, + description: "Authentication token for the session" + }, + user: { + type: "object", + properties: { + id: { + type: "string", + description: "The unique identifier of the user" + }, + email: { + type: "string", + format: "email", + description: "The email address of the user" + }, + name: { + type: "string", + description: "The name of the user" + }, + image: { + type: "string", + format: "uri", + nullable: true, + description: "The profile image URL of the user" + }, + emailVerified: { + type: "boolean", + description: "Whether the email has been verified" + }, + createdAt: { + type: "string", + format: "date-time", + description: "When the user was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "When the user was last updated" + } + }, + required: [ + "id", + "email", + "name", + "emailVerified", + "createdAt", + "updatedAt" + ] + } + }, + required: ["user"] + } } } + }, + "422": { + description: "Unprocessable Entity. User already exists or failed to create user.", + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } } + } + } + } + } +}, async (ctx) => { + return runWithTransaction(ctx.context.adapter, async () => { + if (!ctx.context.options.emailAndPassword?.enabled || ctx.context.options.emailAndPassword?.disableSignUp) throw APIError2.from("BAD_REQUEST", { + message: "Email and password sign up is not enabled", + code: "EMAIL_PASSWORD_SIGN_UP_DISABLED" + }); + const body = ctx.body; + const { name, email: email3, password, image, callbackURL: _callbackURL, rememberMe, ...rest } = body; + if (!email2().safeParse(email3).success) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_EMAIL); + if (!password || typeof password !== "string") throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + const minPasswordLength = ctx.context.password.config.minPasswordLength; + if (password.length < minPasswordLength) { + ctx.context.logger.error("Password is too short"); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_SHORT); + } + const maxPasswordLength = ctx.context.password.config.maxPasswordLength; + if (password.length > maxPasswordLength) { + ctx.context.logger.error("Password is too long"); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_LONG); + } + const shouldReturnGenericDuplicateResponse = ctx.context.options.emailAndPassword.requireEmailVerification; + const shouldSkipAutoSignIn = ctx.context.options.emailAndPassword.autoSignIn === false || shouldReturnGenericDuplicateResponse; + const additionalUserFields = parseUserInput(ctx.context.options, rest, "create"); + const normalizedEmail = email3.toLowerCase(); + const dbUser = await ctx.context.internalAdapter.findUserByEmail(normalizedEmail); + if (dbUser?.user) { + ctx.context.logger.info(`Sign-up attempt for existing email: ${email3}`); + if (shouldReturnGenericDuplicateResponse) { + await ctx.context.password.hash(password); + if (ctx.context.options.emailAndPassword?.onExistingUserSignUp) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.onExistingUserSignUp({ user: dbUser.user }, ctx.request)); + const now2 = /* @__PURE__ */ new Date(); + const generatedId = ctx.context.generateId({ model: "user" }) || generateId(); + const coreFields = { + name, + email: normalizedEmail, + emailVerified: false, + image: image || null, + createdAt: now2, + updatedAt: now2 + }; + const customSyntheticUser = ctx.context.options.emailAndPassword?.customSyntheticUser; + let syntheticUser; + if (customSyntheticUser) { + const additionalFieldKeys = Object.keys(ctx.context.options.user?.additionalFields ?? {}); + const additionalFields = {}; + for (const key of additionalFieldKeys) if (key in additionalUserFields) additionalFields[key] = additionalUserFields[key]; + syntheticUser = customSyntheticUser({ + coreFields, + additionalFields, + id: generatedId + }); + } else syntheticUser = { + ...coreFields, + ...additionalUserFields, + id: generatedId + }; + return ctx.json({ + token: null, + user: parseUserOutput(ctx.context.options, syntheticUser) + }); + } + throw APIError2.from("UNPROCESSABLE_ENTITY", BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL); + } + const hash2 = await ctx.context.password.hash(password); + let createdUser; + try { + createdUser = await ctx.context.internalAdapter.createUser({ + email: normalizedEmail, + name, + image, + ...additionalUserFields, + emailVerified: false + }); + if (!createdUser) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.FAILED_TO_CREATE_USER); + } catch (e) { + if (isDevelopment()) ctx.context.logger.error("Failed to create user", e); + if (isAPIError2(e)) throw e; + ctx.context.logger?.error("Failed to create user", e); + throw APIError2.from("UNPROCESSABLE_ENTITY", BASE_ERROR_CODES.FAILED_TO_CREATE_USER); + } + if (!createdUser) throw APIError2.from("UNPROCESSABLE_ENTITY", BASE_ERROR_CODES.FAILED_TO_CREATE_USER); + await ctx.context.internalAdapter.linkAccount({ + userId: createdUser.id, + providerId: "credential", + accountId: createdUser.id, + password: hash2 + }); + if (ctx.context.options.emailVerification?.sendOnSignUp ?? ctx.context.options.emailAndPassword.requireEmailVerification) { + const token = await createEmailVerificationToken(ctx.context.secret, createdUser.email, void 0, ctx.context.options.emailVerification?.expiresIn); + const callbackURL = body.callbackURL ? encodeURIComponent(body.callbackURL) : encodeURIComponent("/"); + const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; + if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: createdUser, + url: url2, + token + }, ctx.request)); + } + if (shouldSkipAutoSignIn) return ctx.json({ + token: null, + user: parseUserOutput(ctx.context.options, createdUser) + }); + const session = await ctx.context.internalAdapter.createSession(createdUser.id, rememberMe === false); + if (!session) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); + await setSessionCookie(ctx, { + session, + user: createdUser + }, rememberMe === false); + return ctx.json({ + token: session.token, + user: parseUserOutput(ctx.context.options, createdUser) + }); + }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/update-session.mjs +init_error2(); +init_zod(); +var updateSessionBodySchema = record(string2().meta({ description: "Field name must be a string" }), any()); +var updateSession = () => createAuthEndpoint("/update-session", { + method: "POST", + operationId: "updateSession", + body: updateSessionBodySchema, + use: [sessionMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + operationId: "updateSession", + description: "Update the current session", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { session: { + type: "object", + $ref: "#/components/schemas/Session" + } } + } } } + } } + } + } +}, async (ctx) => { + const body = ctx.body; + if (typeof body !== "object" || Array.isArray(body)) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT); + const session = ctx.context.session; + const additionalFields = parseSessionInput(ctx.context.options, body, "update"); + if (Object.keys(additionalFields).length === 0) throw APIError2.fromStatus("BAD_REQUEST", { message: "No fields to update" }); + const newSession = await ctx.context.internalAdapter.updateSession(session.session.token, { + ...additionalFields, + updatedAt: /* @__PURE__ */ new Date() + }) ?? { + ...session.session, + ...additionalFields, + updatedAt: /* @__PURE__ */ new Date() + }; + await setSessionCookie(ctx, { + session: newSession, + user: session.user + }); + return ctx.json({ session: parseSessionOutput(ctx.context.options, newSession) }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/update-user.mjs +init_error2(); +init_zod(); +var updateUserBodySchema = record(string2().meta({ description: "Field name must be a string" }), any()); +var updateUser = () => createAuthEndpoint("/update-user", { + method: "POST", + operationId: "updateUser", + body: updateUserBodySchema, + use: [sessionMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + operationId: "updateUser", + description: "Update the current user", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the user" + }, + image: { + type: "string", + description: "The image of the user", + nullable: true + } + } + } } } }, + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { user: { + type: "object", + $ref: "#/components/schemas/User" + } } + } } } + } } + } + } +}, async (ctx) => { + const body = ctx.body; + if (typeof body !== "object" || Array.isArray(body)) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT); + if (body.email) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED); + const { name, image, ...rest } = body; + const session = ctx.context.session; + const additionalFields = parseUserInput(ctx.context.options, rest, "update"); + if (image === void 0 && name === void 0 && Object.keys(additionalFields).length === 0) throw APIError2.fromStatus("BAD_REQUEST", { message: "No fields to update" }); + const updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { + name, + image, + ...additionalFields + }) ?? { + ...session.user, + ...name !== void 0 && { name }, + ...image !== void 0 && { image }, + ...additionalFields + }; + await setSessionCookie(ctx, { + session: session.session, + user: updatedUser + }); + return ctx.json({ status: true }); +}); +var changePassword = createAuthEndpoint("/change-password", { + method: "POST", + operationId: "changePassword", + body: object({ + newPassword: string2().meta({ description: "The new password to set" }), + currentPassword: string2().meta({ description: "The current password is required" }), + revokeOtherSessions: boolean2().meta({ description: "Must be a boolean value" }).optional() + }), + use: [sensitiveSessionMiddleware], + metadata: { openapi: { + operationId: "changePassword", + description: "Change the password of the user", + responses: { "200": { + description: "Password successfully changed", + content: { "application/json": { schema: { + type: "object", + properties: { + token: { + type: "string", + nullable: true, + description: "New session token if other sessions were revoked" + }, + user: { + type: "object", + properties: { + id: { + type: "string", + description: "The unique identifier of the user" + }, + email: { + type: "string", + format: "email", + description: "The email address of the user" + }, + name: { + type: "string", + description: "The name of the user" + }, + image: { + type: "string", + format: "uri", + nullable: true, + description: "The profile image URL of the user" + }, + emailVerified: { + type: "boolean", + description: "Whether the email has been verified" + }, + createdAt: { + type: "string", + format: "date-time", + description: "When the user was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "When the user was last updated" + } + }, + required: [ + "id", + "email", + "name", + "emailVerified", + "createdAt", + "updatedAt" + ] + } + }, + required: ["user"] + } } } + } } + } } +}, async (ctx) => { + const { newPassword, currentPassword, revokeOtherSessions: revokeOtherSessions2 } = ctx.body; + const session = ctx.context.session; + const minPasswordLength = ctx.context.password.config.minPasswordLength; + if (newPassword.length < minPasswordLength) { + ctx.context.logger.error("Password is too short"); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_SHORT); + } + const maxPasswordLength = ctx.context.password.config.maxPasswordLength; + if (newPassword.length > maxPasswordLength) { + ctx.context.logger.error("Password is too long"); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_LONG); + } + const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account2) => account2.providerId === "credential" && account2.password); + if (!account || !account.password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND); + const passwordHash = await ctx.context.password.hash(newPassword); + if (!await ctx.context.password.verify({ + hash: account.password, + password: currentPassword + })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + await ctx.context.internalAdapter.updateAccount(account.id, { password: passwordHash }); + let token = null; + if (revokeOtherSessions2) { + await ctx.context.internalAdapter.deleteSessions(session.user.id); + const newSession = await ctx.context.internalAdapter.createSession(session.user.id); + if (!newSession) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_GET_SESSION); + await setSessionCookie(ctx, { + session: newSession, + user: session.user + }); + token = newSession.token; + } + return ctx.json({ + token, + user: parseUserOutput(ctx.context.options, session.user) + }); +}); +var setPassword = createAuthEndpoint({ + method: "POST", + body: object({ newPassword: string2().meta({ description: "The new password to set is required" }) }), + use: [sensitiveSessionMiddleware] +}, async (ctx) => { + const { newPassword } = ctx.body; + const session = ctx.context.session; + const minPasswordLength = ctx.context.password.config.minPasswordLength; + if (newPassword.length < minPasswordLength) { + ctx.context.logger.error("Password is too short"); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_SHORT); + } + const maxPasswordLength = ctx.context.password.config.maxPasswordLength; + if (newPassword.length > maxPasswordLength) { + ctx.context.logger.error("Password is too long"); + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_LONG); + } + const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account2) => account2.providerId === "credential" && account2.password); + const passwordHash = await ctx.context.password.hash(newPassword); + if (!account) { + await ctx.context.internalAdapter.linkAccount({ + userId: session.user.id, + providerId: "credential", + accountId: session.user.id, + password: passwordHash + }); + return ctx.json({ status: true }); + } + throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_ALREADY_SET); +}); +var deleteUser = createAuthEndpoint("/delete-user", { + method: "POST", + use: [sensitiveSessionMiddleware], + body: object({ + callbackURL: string2().meta({ description: "The callback URL to redirect to after the user is deleted" }).optional(), + password: string2().meta({ description: "The password of the user is required to delete the user" }).optional(), + token: string2().meta({ description: "The token to delete the user is required" }).optional() + }), + metadata: { openapi: { + operationId: "deleteUser", + description: "Delete the user", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + callbackURL: { + type: "string", + description: "The callback URL to redirect to after the user is deleted" + }, + password: { + type: "string", + description: "The user's password. Required if session is not fresh" + }, + token: { + type: "string", + description: "The deletion verification token" + } + } + } } } }, + responses: { "200": { + description: "User deletion processed successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + success: { + type: "boolean", + description: "Indicates if the operation was successful" + }, + message: { + type: "string", + enum: ["User deleted", "Verification email sent"], + description: "Status message of the deletion process" + } + }, + required: ["success", "message"] + } } } + } } + } } +}, async (ctx) => { + if (!ctx.context.options.user?.deleteUser?.enabled) { + ctx.context.logger.error("Delete user is disabled. Enable it in the options"); + throw APIError2.fromStatus("NOT_FOUND"); + } + const session = ctx.context.session; + if (ctx.body.password) { + const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account2) => account2.providerId === "credential" && account2.password); + if (!account || !account.password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND); + if (!await ctx.context.password.verify({ + hash: account.password, + password: ctx.body.password + })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + } + if (ctx.body.token) { + await deleteUserCallback({ + ...ctx, + query: { token: ctx.body.token } + }); + return ctx.json({ + success: true, + message: "User deleted" + }); + } + if (ctx.context.options.user.deleteUser?.sendDeleteAccountVerification) { + const token = generateRandomString(32, "0-9", "a-z"); + await ctx.context.internalAdapter.createVerificationValue({ + value: session.user.id, + identifier: `delete-account-${token}`, + expiresAt: new Date(Date.now() + (ctx.context.options.user.deleteUser?.deleteTokenExpiresIn || 3600 * 24) * 1e3) + }); + const url2 = `${ctx.context.baseURL}/delete-user/callback?token=${token}&callbackURL=${encodeURIComponent(ctx.body.callbackURL || "/")}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.user.deleteUser.sendDeleteAccountVerification({ + user: session.user, + url: url2, + token + }, ctx.request)); + return ctx.json({ + success: true, + message: "Verification email sent" + }); + } + if (!ctx.body.password && ctx.context.sessionConfig.freshAge !== 0) { + const createdAt = new Date(session.session.createdAt).getTime(); + const freshAge = ctx.context.sessionConfig.freshAge * 1e3; + if (Date.now() - createdAt >= freshAge) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.SESSION_EXPIRED); + } + const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete; + if (beforeDelete) await beforeDelete(session.user, ctx.request); + await ctx.context.internalAdapter.deleteUser(session.user.id); + await ctx.context.internalAdapter.deleteSessions(session.user.id); + deleteSessionCookie(ctx); + const afterDelete = ctx.context.options.user.deleteUser?.afterDelete; + if (afterDelete) await afterDelete(session.user, ctx.request); + return ctx.json({ + success: true, + message: "User deleted" + }); +}); +var deleteUserCallback = createAuthEndpoint("/delete-user/callback", { + method: "GET", + query: object({ + token: string2().meta({ description: "The token to verify the deletion request" }), + callbackURL: string2().meta({ description: "The URL to redirect to after deletion" }).optional() + }), + use: [originCheck((ctx) => ctx.query.callbackURL)], + metadata: { openapi: { + description: "Callback to complete user deletion with verification token", + responses: { "200": { + description: "User successfully deleted", + content: { "application/json": { schema: { + type: "object", + properties: { + success: { + type: "boolean", + description: "Indicates if the deletion was successful" + }, + message: { + type: "string", + enum: ["User deleted"], + description: "Confirmation message" + } + }, + required: ["success", "message"] + } } } + } } + } } +}, async (ctx) => { + if (!ctx.context.options.user?.deleteUser?.enabled) { + ctx.context.logger.error("Delete user is disabled. Enable it in the options"); + throw APIError2.from("NOT_FOUND", { + message: "Not found", + code: "NOT_FOUND" + }); + } + const session = await getSessionFromCtx(ctx); + if (!session) throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO); + const token = await ctx.context.internalAdapter.findVerificationValue(`delete-account-${ctx.query.token}`); + if (!token || token.expiresAt < /* @__PURE__ */ new Date()) throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.INVALID_TOKEN); + if (token.value !== session.user.id) throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.INVALID_TOKEN); + const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete; + if (beforeDelete) await beforeDelete(session.user, ctx.request); + await ctx.context.internalAdapter.deleteUser(session.user.id); + await ctx.context.internalAdapter.deleteSessions(session.user.id); + await ctx.context.internalAdapter.deleteAccounts(session.user.id); + await ctx.context.internalAdapter.deleteVerificationByIdentifier(`delete-account-${ctx.query.token}`); + deleteSessionCookie(ctx); + const afterDelete = ctx.context.options.user.deleteUser?.afterDelete; + if (afterDelete) await afterDelete(session.user, ctx.request); + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL || "/"); + return ctx.json({ + success: true, + message: "User deleted" + }); +}); +var changeEmail = createAuthEndpoint("/change-email", { + method: "POST", + body: object({ + newEmail: email2().meta({ description: "The new email address to set must be a valid email address" }), + callbackURL: string2().meta({ description: "The URL to redirect to after email verification" }).optional() + }), + use: [sensitiveSessionMiddleware], + metadata: { openapi: { + operationId: "changeEmail", + responses: { "200": { + description: "Email change request processed successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + user: { + type: "object", + $ref: "#/components/schemas/User" + }, + status: { + type: "boolean", + description: "Indicates if the request was successful" + }, + message: { + type: "string", + enum: ["Email updated", "Verification email sent"], + description: "Status message of the email change process", + nullable: true + } + }, + required: ["status"] + } } } + } } + } } +}, async (ctx) => { + if (!ctx.context.options.user?.changeEmail?.enabled) { + ctx.context.logger.error("Change email is disabled."); + throw APIError2.fromStatus("BAD_REQUEST", { message: "Change email is disabled" }); + } + const newEmail = ctx.body.newEmail.toLowerCase(); + if (newEmail === ctx.context.session.user.email) { + ctx.context.logger.error("Email is the same"); + throw APIError2.fromStatus("BAD_REQUEST", { message: "Email is the same" }); + } + const canUpdateWithoutVerification = ctx.context.session.user.emailVerified !== true && ctx.context.options.user.changeEmail.updateEmailWithoutVerification; + const canSendConfirmation = ctx.context.session.user.emailVerified && ctx.context.options.user.changeEmail.sendChangeEmailConfirmation; + const canSendVerification = ctx.context.options.emailVerification?.sendVerificationEmail; + if (!canUpdateWithoutVerification && !canSendConfirmation && !canSendVerification) { + ctx.context.logger.error("Verification email isn't enabled."); + throw APIError2.fromStatus("BAD_REQUEST", { message: "Verification email isn't enabled" }); + } + if (await ctx.context.internalAdapter.findUserByEmail(newEmail)) { + await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn); + ctx.context.logger.info("Change email attempt for existing email"); + return ctx.json({ status: true }); + } + if (canUpdateWithoutVerification) { + await ctx.context.internalAdapter.updateUserByEmail(ctx.context.session.user.email, { email: newEmail }); + await setSessionCookie(ctx, { + session: ctx.context.session.session, + user: { + ...ctx.context.session.user, + email: newEmail + } + }); + if (canSendVerification) { + const token2 = await createEmailVerificationToken(ctx.context.secret, newEmail, void 0, ctx.context.options.emailVerification?.expiresIn); + const url3 = `${ctx.context.baseURL}/verify-email?token=${token2}&callbackURL=${ctx.body.callbackURL || "/"}`; + await ctx.context.runInBackgroundOrAwait(canSendVerification({ + user: { + ...ctx.context.session.user, + email: newEmail + }, + url: url3, + token: token2 + }, ctx.request)); + } + return ctx.json({ status: true }); + } + if (canSendConfirmation) { + const token2 = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-confirmation" }); + const url3 = `${ctx.context.baseURL}/verify-email?token=${token2}&callbackURL=${ctx.body.callbackURL || "/"}`; + await ctx.context.runInBackgroundOrAwait(canSendConfirmation({ + user: ctx.context.session.user, + newEmail, + url: url3, + token: token2 + }, ctx.request)); + return ctx.json({ status: true }); + } + if (!canSendVerification) { + ctx.context.logger.error("Verification email isn't enabled."); + throw APIError2.fromStatus("BAD_REQUEST", { message: "Verification email isn't enabled" }); + } + const token = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-verification" }); + const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || "/"}`; + await ctx.context.runInBackgroundOrAwait(canSendVerification({ + user: { + ...ctx.context.session.user, + email: newEmail + }, + url: url2, + token + }, ctx.request)); + return ctx.json({ status: true }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/to-auth-endpoints.mjs +init_env(); +init_error2(); +var defuReplaceArrays = createDefu((obj, key, value) => { + if (Array.isArray(obj[key]) && Array.isArray(value)) { + obj[key] = value; + return true; + } +}); +var hooksSourceWeakMap = /* @__PURE__ */ new WeakMap(); +function getOperationId(endpoint, key) { + if (!endpoint?.options) return key; + const opts = endpoint.options; + return opts.operationId ?? opts.metadata?.openapi?.operationId ?? key; +} +function toAuthEndpoints(endpoints, ctx) { + const api = {}; + for (const [key, endpoint] of Object.entries(endpoints)) { + api[key] = async (context) => { + const operationId = getOperationId(endpoint, key); + const endpointMethod = endpoint?.options?.method; + const defaultMethod = Array.isArray(endpointMethod) ? endpointMethod[0] : endpointMethod; + const run = async () => { + const authContext = await ctx; + const methodName = context?.method ?? context?.request?.method ?? defaultMethod ?? "?"; + const route = endpoint.path ?? "/:virtual"; + let internalContext = { + ...context, + context: { + ...authContext, + returned: void 0, + responseHeaders: void 0, + session: null + }, + path: endpoint.path, + headers: context?.headers ? new Headers(context?.headers) : void 0 + }; + const hasRequest = context?.request instanceof Request; + const shouldReturnResponse = context?.asResponse ?? hasRequest; + return withSpan(`${methodName} ${route}`, { + [ATTR_HTTP_ROUTE]: route, + [ATTR_OPERATION_ID]: operationId + }, async () => runWithEndpointContext(internalContext, async () => { + const { beforeHooks, afterHooks } = getHooks(authContext); + const before = await runBeforeHooks(internalContext, beforeHooks, endpoint, operationId); + if ("context" in before && before.context && typeof before.context === "object") { + const { headers, ...rest } = before.context; + if (headers) headers.forEach((value, key2) => { + internalContext.headers.set(key2, value); + }); + internalContext = defuReplaceArrays(rest, internalContext); + } else if (before) return shouldReturnResponse ? toResponse(before, { headers: context?.headers }) : context?.returnHeaders ? { + headers: context?.headers, + response: before + } : before; + internalContext.asResponse = false; + internalContext.returnHeaders = true; + internalContext.returnStatus = true; + const result = await runWithEndpointContext(internalContext, () => withSpan(`handler ${route}`, { + [ATTR_HTTP_ROUTE]: route, + [ATTR_OPERATION_ID]: operationId + }, () => endpoint(internalContext))).catch((e) => { + if (isAPIError2(e)) + return { + response: e, + status: e.statusCode, + headers: e.headers ? new Headers(e.headers) : null + }; + throw e; + }); + if (result && result instanceof Response) return result; + internalContext.context.returned = result.response; + internalContext.context.responseHeaders = result.headers; + const after = await runAfterHooks(internalContext, afterHooks, endpoint, operationId); + if (after.response) result.response = after.response; + if (isAPIError2(result.response) && shouldPublishLog(authContext.logger.level, "debug")) result.response.stack = result.response.errorStack; + if (isAPIError2(result.response) && !shouldReturnResponse) throw result.response; + return shouldReturnResponse ? toResponse(result.response, { + headers: result.headers, + status: result.status + }) : context?.returnHeaders ? context?.returnStatus ? { + headers: result.headers, + response: result.response, + status: result.status + } : { + headers: result.headers, + response: result.response + } : context?.returnStatus ? { + response: result.response, + status: result.status + } : result.response; + })); + }; + if (await hasRequestState()) return run(); + else return runWithRequestState(/* @__PURE__ */ new WeakMap(), run); + }; + api[key].path = endpoint.path; + api[key].options = endpoint.options; + } + return api; +} +async function runBeforeHooks(context, hooks, endpoint, operationId) { + let modifiedContext = {}; + for (const hook of hooks) { + let matched = false; + try { + matched = hook.matcher(context); + } catch (error49) { + const hookSource = hooksSourceWeakMap.get(hook.handler) ?? "unknown"; + context.context.logger.error(`An error occurred during ${hookSource} hook matcher execution:`, error49); + throw new APIError2("INTERNAL_SERVER_ERROR", { message: `An error occurred during hook matcher execution. Check the logs for more details.` }); + } + if (matched) { + const hookSource = hooksSourceWeakMap.get(hook.handler) ?? "unknown"; + const route = endpoint.path ?? "/:virtual"; + const result = await withSpan(`hook before ${route} ${hookSource}`, { + [ATTR_HOOK_TYPE]: "before", + [ATTR_HTTP_ROUTE]: route, + [ATTR_CONTEXT]: hookSource, + [ATTR_OPERATION_ID]: operationId + }, () => hook.handler({ + ...context, + returnHeaders: false + })).catch((e) => { + if (isAPIError2(e) && shouldPublishLog(context.context.logger.level, "debug")) e.stack = e.errorStack; + throw e; + }); + if (result && typeof result === "object") { + if ("context" in result && typeof result.context === "object") { + const { headers, ...rest } = result.context; + if (headers instanceof Headers) if (modifiedContext.headers) headers.forEach((value, key) => { + modifiedContext.headers?.set(key, value); + }); + else modifiedContext.headers = headers; + modifiedContext = defuReplaceArrays(rest, modifiedContext); + continue; + } + return result; + } + } + } + return { context: modifiedContext }; +} +async function runAfterHooks(context, hooks, endpoint, operationId) { + for (const hook of hooks) if (hook.matcher(context)) { + const hookSource = hooksSourceWeakMap.get(hook.handler) ?? "unknown"; + const route = endpoint.path ?? "/:virtual"; + const result = await withSpan(`hook after ${route} ${hookSource}`, { + [ATTR_HOOK_TYPE]: "after", + [ATTR_HTTP_ROUTE]: route, + [ATTR_CONTEXT]: hookSource, + [ATTR_OPERATION_ID]: operationId + }, () => hook.handler(context)).catch((e) => { + if (isAPIError2(e)) { + const headers = e[kAPIErrorHeaderSymbol]; + if (shouldPublishLog(context.context.logger.level, "debug")) e.stack = e.errorStack; + return { + response: e, + headers: headers ? headers : e.headers ? new Headers(e.headers) : null + }; + } + throw e; + }); + if (result.headers) result.headers.forEach((value, key) => { + if (!context.context.responseHeaders) context.context.responseHeaders = new Headers({ [key]: value }); + else if (key.toLowerCase() === "set-cookie") context.context.responseHeaders.append(key, value); + else context.context.responseHeaders.set(key, value); + }); + if (result.response) context.context.returned = result.response; + } + return { + response: context.context.returned, + headers: context.context.responseHeaders + }; +} +function getHooks(authContext) { + const plugins = authContext.options.plugins || []; + const beforeHooks = []; + const afterHooks = []; + const beforeHookHandler = authContext.options.hooks?.before; + if (beforeHookHandler) { + hooksSourceWeakMap.set(beforeHookHandler, "user"); + beforeHooks.push({ + matcher: () => true, + handler: beforeHookHandler + }); + } + const afterHookHandler = authContext.options.hooks?.after; + if (afterHookHandler) { + hooksSourceWeakMap.set(afterHookHandler, "user"); + afterHooks.push({ + matcher: () => true, + handler: afterHookHandler + }); + } + const pluginBeforeHooks = plugins.flatMap((plugin) => (plugin.hooks?.before ?? []).map((h) => { + hooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`); + return h; + })); + const pluginAfterHooks = plugins.flatMap((plugin) => (plugin.hooks?.after ?? []).map((h) => { + hooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`); + return h; + })); + if (pluginBeforeHooks.length) beforeHooks.push(...pluginBeforeHooks); + if (pluginAfterHooks.length) afterHooks.push(...pluginAfterHooks); + return { + beforeHooks, + afterHooks + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/index.mjs +init_env(); +init_error2(); +function checkEndpointConflicts(options, logger2) { + const endpointRegistry = /* @__PURE__ */ new Map(); + options.plugins?.forEach((plugin) => { + if (plugin.endpoints) { + for (const [key, endpoint] of Object.entries(plugin.endpoints)) if (endpoint && "path" in endpoint && typeof endpoint.path === "string") { + const path3 = endpoint.path; + let methods2 = []; + if (endpoint.options && "method" in endpoint.options) { + if (Array.isArray(endpoint.options.method)) methods2 = endpoint.options.method; + else if (typeof endpoint.options.method === "string") methods2 = [endpoint.options.method]; + } + if (methods2.length === 0) methods2 = ["*"]; + if (!endpointRegistry.has(path3)) endpointRegistry.set(path3, []); + endpointRegistry.get(path3).push({ + pluginId: plugin.id, + endpointKey: key, + methods: methods2 + }); + } + } + }); + const conflicts = []; + for (const [path3, entries] of endpointRegistry.entries()) if (entries.length > 1) { + const methodMap = /* @__PURE__ */ new Map(); + let hasConflict = false; + for (const entry of entries) for (const method of entry.methods) { + if (!methodMap.has(method)) methodMap.set(method, []); + methodMap.get(method).push(entry.pluginId); + if (methodMap.get(method).length > 1) hasConflict = true; + if (method === "*" && entries.length > 1) hasConflict = true; + else if (method !== "*" && methodMap.has("*")) hasConflict = true; + } + if (hasConflict) { + const uniquePlugins = [...new Set(entries.map((e) => e.pluginId))]; + const conflictingMethods = []; + for (const [method, plugins] of methodMap.entries()) if (plugins.length > 1 || method === "*" && entries.length > 1 || method !== "*" && methodMap.has("*")) conflictingMethods.push(method); + conflicts.push({ + path: path3, + plugins: uniquePlugins, + conflictingMethods + }); + } + } + if (conflicts.length > 0) { + const conflictMessages = conflicts.map((conflict) => ` - "${conflict.path}" [${conflict.conflictingMethods.join(", ")}] used by plugins: ${conflict.plugins.join(", ")}`).join("\n"); + logger2.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods: +${conflictMessages} + +To resolve this, you can: + 1. Use only one of the conflicting plugins + 2. Configure the plugins to use different paths (if supported) + 3. Ensure plugins use different HTTP methods for the same path +`); + } +} +function getEndpoints(ctx, options) { + const pluginEndpoints = options.plugins?.reduce((acc, plugin) => { + return { + ...acc, + ...plugin.endpoints + }; + }, {}) ?? {}; + const middlewares = options.plugins?.map((plugin) => plugin.middlewares?.map((m) => { + const middleware = async (context) => { + const authContext = await ctx; + return withSpan(`middleware ${m.path} ${plugin.id}`, { + [ATTR_HOOK_TYPE]: "middleware", + [ATTR_HTTP_ROUTE]: m.path, + [ATTR_CONTEXT]: `plugin:${plugin.id}` + }, () => m.middleware({ + ...context, + context: { + ...authContext, + ...context.context + } + })); + }; + middleware.options = m.middleware.options; + return { + path: m.path, + middleware + }; + })).filter((plugin) => plugin !== void 0).flat() || []; + return { + api: toAuthEndpoints({ + signInSocial: signInSocial(), + callbackOAuth, + getSession: getSession(), + signOut, + signUpEmail: signUpEmail(), + signInEmail: signInEmail(), + resetPassword, + verifyPassword: verifyPassword2, + verifyEmail, + sendVerificationEmail, + changeEmail, + changePassword, + setPassword, + updateSession: updateSession(), + updateUser: updateUser(), + deleteUser, + requestPasswordReset, + requestPasswordResetCallback, + listSessions: listSessions(), + revokeSession, + revokeSessions, + revokeOtherSessions, + linkSocialAccount, + listUserAccounts, + deleteUserCallback, + unlinkAccount, + refreshToken, + getAccessToken, + accountInfo, + ...pluginEndpoints, + ok, + error: error48 + }, ctx), + middlewares + }; +} +var router = (ctx, options) => { + const { api, middlewares } = getEndpoints(ctx, options); + const basePath = new URL(ctx.baseURL).pathname; + return createRouter$1(api, { + routerContext: ctx, + openapi: { disabled: true }, + basePath, + routerMiddleware: [{ + path: "/**", + middleware: originCheckMiddleware + }, ...middlewares], + allowedMediaTypes: ["application/json"], + skipTrailingSlashes: options.advanced?.skipTrailingSlashes ?? false, + async onRequest(req) { + const disabledPaths = ctx.options.disabledPaths || []; + const normalizedPath = normalizePathname(req.url, basePath); + if (disabledPaths.includes(normalizedPath)) return new Response("Not Found", { status: 404 }); + let currentRequest = req; + for (const plugin of ctx.options.plugins || []) if (plugin.onRequest) { + const response = await withSpan(`onRequest ${plugin.id}`, { + [ATTR_HOOK_TYPE]: "onRequest", + [ATTR_CONTEXT]: `plugin:${plugin.id}` + }, () => plugin.onRequest(currentRequest, ctx)); + if (response && "response" in response) return response.response; + if (response && "request" in response) currentRequest = response.request; + } + const rateLimitResponse2 = await onRequestRateLimit(currentRequest, ctx); + if (rateLimitResponse2) return rateLimitResponse2; + return currentRequest; + }, + async onResponse(res, req) { + await onResponseRateLimit(req, ctx); + for (const plugin of ctx.options.plugins || []) if (plugin.onResponse) { + const response = await withSpan(`onResponse ${plugin.id}`, { + [ATTR_HOOK_TYPE]: "onResponse", + [ATTR_CONTEXT]: `plugin:${plugin.id}`, + [ATTR_HTTP_RESPONSE_STATUS_CODE]: res.status + }, () => plugin.onResponse(res, ctx)); + if (response) return response.response; + } + return res; + }, + onError(e) { + if (isAPIError2(e) && e.status === "FOUND") return; + if (options.onAPIError?.throw) throw e; + if (options.onAPIError?.onError) { + options.onAPIError.onError(e, ctx); + return; + } + const optLogLevel = options.logger?.level; + const log = optLogLevel === "error" || optLogLevel === "warn" || optLogLevel === "debug" ? logger : void 0; + if (options.logger?.disabled !== true) { + if (e && typeof e === "object" && "message" in e && typeof e.message === "string") { + if (e.message.includes("no column") || e.message.includes("column") || e.message.includes("relation") || e.message.includes("table") || e.message.includes("does not exist")) { + ctx.logger?.error(e.message); + return; + } + } + if (isAPIError2(e)) { + if (e.status === "INTERNAL_SERVER_ERROR") ctx.logger.error(e.status, e); + log?.error(e.message); + } else ctx.logger?.error(e && typeof e === "object" && "name" in e ? e.name : "", e); + } + } + }); +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/adapter-base.mjs +init_env(); +async function getBaseAdapter(options, handleDirectDatabase) { + let adapter; + if (!options.database) { + const tables = getAuthTables(options); + const memoryDB = Object.keys(tables).reduce((acc, key) => { + acc[key] = []; + return acc; + }, {}); + const { memoryAdapter: memoryAdapter2 } = await Promise.resolve().then(() => (init_dist(), dist_exports)); + adapter = memoryAdapter2(memoryDB)(options); + } else if (typeof options.database === "function") adapter = options.database(options); + else adapter = await handleDirectDatabase(options); + if (!adapter.transaction) { + logger.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."); + adapter.transaction = async (cb) => { + return cb(adapter); + }; + } + return adapter; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/adapter-kysely.mjs +init_error2(); +async function getAdapter(options) { + return getBaseAdapter(options, async (opts) => { + const { createKyselyAdapter: createKyselyAdapter2 } = await Promise.resolve().then(() => (init_kysely_adapter(), kysely_adapter_exports)); + const { kysely, databaseType, transaction } = await createKyselyAdapter2(opts); + if (!kysely) throw new BetterAuthError("Failed to initialize database adapter"); + const { kyselyAdapter: kyselyAdapter2 } = await Promise.resolve().then(() => (init_kysely_adapter(), kysely_adapter_exports)); + return kyselyAdapter2(kysely, { + type: databaseType || "sqlite", + debugLogs: opts.database && "debugLogs" in opts.database ? opts.database.debugLogs : false, + transaction + })(opts); + }); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/get-schema.mjs +function getSchema(config4) { + const tables = getAuthTables(config4); + const schema3 = {}; + for (const key in tables) { + const table = tables[key]; + const fields = table.fields; + const actualFields = {}; + Object.entries(fields).forEach(([key2, field]) => { + actualFields[field.fieldName || key2] = field; + if (field.references) { + const refTable = tables[field.references.model]; + if (refTable) actualFields[field.fieldName || key2].references = { + ...field.references, + model: refTable.modelName, + field: field.references.field + }; + } + }); + if (schema3[table.modelName]) { + schema3[table.modelName].fields = { + ...schema3[table.modelName].fields, + ...actualFields + }; + continue; + } + schema3[table.modelName] = { + fields: actualFields, + order: table.order || Infinity + }; + } + return schema3; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/get-migration.mjs +init_env(); +init_dist2(); +init_adapter(); +init_esm3(); +var map2 = { + postgres: { + string: [ + "character varying", + "varchar", + "text", + "uuid" + ], + number: [ + "int4", + "integer", + "bigint", + "smallint", + "numeric", + "real", + "double precision" + ], + boolean: ["bool", "boolean"], + date: [ + "timestamptz", + "timestamp", + "date" + ], + json: ["json", "jsonb"] + }, + mysql: { + string: [ + "varchar", + "text", + "uuid" + ], + number: [ + "integer", + "int", + "bigint", + "smallint", + "decimal", + "float", + "double" + ], + boolean: ["boolean", "tinyint"], + date: [ + "timestamp", + "datetime", + "date" + ], + json: ["json"] + }, + sqlite: { + string: ["TEXT"], + number: ["INTEGER", "REAL"], + boolean: ["INTEGER", "BOOLEAN"], + date: ["DATE", "INTEGER"], + json: ["TEXT"] + }, + mssql: { + string: [ + "varchar", + "nvarchar", + "uniqueidentifier" + ], + number: [ + "int", + "bigint", + "smallint", + "decimal", + "float", + "double" + ], + boolean: ["bit", "smallint"], + date: [ + "datetime2", + "date", + "datetime" + ], + json: ["varchar", "nvarchar"] + } +}; +function matchType(columnDataType, fieldType, dbType) { + function normalize2(type) { + return type.toLowerCase().split("(")[0].trim(); + } + if (fieldType === "string[]" || fieldType === "number[]") return columnDataType.toLowerCase().includes("json"); + const types = map2[dbType]; + return (Array.isArray(fieldType) ? types["string"].map((t) => t.toLowerCase()) : types[fieldType].map((t) => t.toLowerCase())).includes(normalize2(columnDataType)); +} +async function getPostgresSchema(db) { + try { + const result = await sql`SHOW search_path`.execute(db); + const searchPath = result.rows[0]?.search_path ?? result.rows[0]?.searchPath; + if (searchPath) return searchPath.split(",").map((s) => s.trim()).map((s) => s.replace(/^["']|["']$/g, "")).filter((s) => !s.startsWith("$") && !s.startsWith("\\$"))[0] || "public"; + } catch { + } + return "public"; +} +async function getMigrations(config4) { + const betterAuthSchema = getSchema(config4); + const logger2 = createLogger2(config4.logger); + let { kysely: db, databaseType: dbType } = await createKyselyAdapter(config4); + if (!dbType) { + logger2.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."); + dbType = "sqlite"; + } + if (!db) { + logger2.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."); + process.exit(1); + } + let currentSchema = "public"; + if (dbType === "postgres") { + currentSchema = await getPostgresSchema(db); + logger2.debug(`PostgreSQL migration: Using schema '${currentSchema}' (from search_path)`); + try { + const schemaCheck = await sql` + SELECT schema_name + FROM information_schema.schemata + WHERE schema_name = ${currentSchema} + `.execute(db); + if (!(schemaCheck.rows[0]?.schema_name ?? schemaCheck.rows[0]?.schemaName)) logger2.warn(`Schema '${currentSchema}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`); + } catch (error49) { + logger2.debug(`Could not verify schema existence: ${error49 instanceof Error ? error49.message : String(error49)}`); + } + } + const allTableMetadata = await db.introspection.getTables(); + let tableMetadata = allTableMetadata; + if (dbType === "postgres") try { + const tablesInSchema = await sql` + SELECT table_name + FROM information_schema.tables + WHERE table_schema = ${currentSchema} + AND table_type = 'BASE TABLE' + `.execute(db); + const tableNamesInSchema = new Set(tablesInSchema.rows.map((row) => row.table_name ?? row.tableName)); + tableMetadata = allTableMetadata.filter((table) => table.schema === currentSchema && tableNamesInSchema.has(table.name)); + logger2.debug(`Found ${tableMetadata.length} table(s) in schema '${currentSchema}': ${tableMetadata.map((t) => t.name).join(", ") || "(none)"}`); + } catch (error49) { + logger2.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${error49 instanceof Error ? error49.message : String(error49)}`); + } + const toBeCreated = []; + const toBeAdded = []; + for (const [key, value] of Object.entries(betterAuthSchema)) { + const table = tableMetadata.find((t) => t.name === key); + if (!table) { + const tIndex = toBeCreated.findIndex((t) => t.table === key); + const tableData = { + table: key, + fields: value.fields, + order: value.order || Infinity + }; + const insertIndex = toBeCreated.findIndex((t) => (t.order || Infinity) > tableData.order); + if (insertIndex === -1) if (tIndex === -1) toBeCreated.push(tableData); + else toBeCreated[tIndex].fields = { + ...toBeCreated[tIndex].fields, + ...value.fields + }; + else toBeCreated.splice(insertIndex, 0, tableData); + continue; + } + const toBeAddedFields = {}; + for (const [fieldName, field] of Object.entries(value.fields)) { + const column = table.columns.find((c) => c.name === fieldName); + if (!column) { + toBeAddedFields[fieldName] = field; + continue; + } + if (matchType(column.dataType, field.type, dbType)) continue; + else logger2.warn(`Field ${fieldName} in table ${key} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`); + } + if (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({ + table: key, + fields: toBeAddedFields, + order: value.order || Infinity + }); + } + const migrations = []; + const useUUIDs = config4.advanced?.database?.generateId === "uuid"; + const useNumberId = config4.advanced?.database?.generateId === "serial"; + function getType(field, fieldName) { + const type = field.type; + const provider = dbType || "sqlite"; + const typeMap = { + string: { + sqlite: "text", + postgres: "text", + mysql: field.unique ? "varchar(255)" : field.references ? "varchar(36)" : field.sortable ? "varchar(255)" : field.index ? "varchar(255)" : "text", + mssql: field.unique || field.sortable ? "varchar(255)" : field.references ? "varchar(36)" : "varchar(8000)" + }, + boolean: { + sqlite: "integer", + postgres: "boolean", + mysql: "boolean", + mssql: "smallint" + }, + number: { + sqlite: field.bigint ? "bigint" : "integer", + postgres: field.bigint ? "bigint" : "integer", + mysql: field.bigint ? "bigint" : "integer", + mssql: field.bigint ? "bigint" : "integer" + }, + date: { + sqlite: "date", + postgres: "timestamptz", + mysql: "timestamp(3)", + mssql: sql`datetime2(3)` + }, + json: { + sqlite: "text", + postgres: "jsonb", + mysql: "json", + mssql: "varchar(8000)" + }, + id: { + postgres: useNumberId ? sql`integer GENERATED BY DEFAULT AS IDENTITY` : useUUIDs ? "uuid" : "text", + mysql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", + mssql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", + sqlite: useNumberId ? "integer" : "text" + }, + foreignKeyId: { + postgres: useNumberId ? "integer" : useUUIDs ? "uuid" : "text", + mysql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", + mssql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", + sqlite: useNumberId ? "integer" : "text" + }, + "string[]": { + sqlite: "text", + postgres: "jsonb", + mysql: "json", + mssql: "varchar(8000)" + }, + "number[]": { + sqlite: "text", + postgres: "jsonb", + mysql: "json", + mssql: "varchar(8000)" + } + }; + if (fieldName === "id" || field.references?.field === "id") { + if (fieldName === "id") return typeMap.id[provider]; + return typeMap.foreignKeyId[provider]; + } + if (Array.isArray(type)) return "text"; + if (!(type in typeMap)) throw new Error(`Unsupported field type '${String(type)}' for field '${fieldName}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`); + return typeMap[type][provider]; + } + const getModelName = initGetModelName({ + schema: getAuthTables(config4), + usePlural: false + }); + const getFieldName = initGetFieldName({ + schema: getAuthTables(config4), + usePlural: false + }); + function getReferencePath(model, field) { + try { + return `${getModelName(model)}.${getFieldName({ + model, + field + })}`; + } catch { + return `${model}.${field}`; + } + } + if (toBeAdded.length) for (const table of toBeAdded) for (const [fieldName, field] of Object.entries(table.fields)) { + const type = getType(field, fieldName); + const builder = db.schema.alterTable(table.table); + if (field.index) { + const indexName = `${table.table}_${fieldName}_${field.unique ? "uidx" : "idx"}`; + const indexBuilder = db.schema.createIndex(indexName).on(table.table).columns([fieldName]); + migrations.push(field.unique ? indexBuilder.unique() : indexBuilder); + } + const built = builder.addColumn(fieldName, type, (col) => { + col = field.required !== false ? col.notNull() : col; + if (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || "cascade"); + if (field.unique) col = col.unique(); + if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`); + else col = col.defaultTo(sql`CURRENT_TIMESTAMP`); + return col; + }); + migrations.push(built); + } + const toBeIndexed = []; + if (toBeCreated.length) for (const table of toBeCreated) { + const idType = getType({ type: useNumberId ? "number" : "string" }, "id"); + let dbT = db.schema.createTable(table.table).addColumn("id", idType, (col) => { + if (useNumberId) { + if (dbType === "postgres") return col.primaryKey().notNull(); + else if (dbType === "sqlite") return col.primaryKey().notNull(); + else if (dbType === "mssql") return col.identity().primaryKey().notNull(); + return col.autoIncrement().primaryKey().notNull(); + } + if (useUUIDs) { + if (dbType === "postgres") return col.primaryKey().defaultTo(sql`pg_catalog.gen_random_uuid()`).notNull(); + return col.primaryKey().notNull(); + } + return col.primaryKey().notNull(); + }); + for (const [fieldName, field] of Object.entries(table.fields)) { + const type = getType(field, fieldName); + dbT = dbT.addColumn(fieldName, type, (col) => { + col = field.required !== false ? col.notNull() : col; + if (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || "cascade"); + if (field.unique) col = col.unique(); + if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`); + else col = col.defaultTo(sql`CURRENT_TIMESTAMP`); + return col; + }); + if (field.index) { + const builder = db.schema.createIndex(`${table.table}_${fieldName}_${field.unique ? "uidx" : "idx"}`).on(table.table).columns([fieldName]); + toBeIndexed.push(field.unique ? builder.unique() : builder); + } + } + migrations.push(dbT); + } + if (toBeIndexed.length) for (const index of toBeIndexed) migrations.push(index); + async function runMigrations() { + for (const migration of migrations) await migration.execute(); + } + async function compileMigrations() { + return migrations.map((m) => m.compile().sql).join(";\n\n") + ";"; + } + return { + toBeCreated, + toBeAdded, + runMigrations, + compileMigrations + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/constants.mjs +var DEFAULT_SECRET = "better-auth-secret-12345678901234567890"; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/secret-utils.mjs +init_error2(); +function estimateEntropy(str) { + const unique2 = new Set(str).size; + if (unique2 === 0) return 0; + return Math.log2(Math.pow(unique2, str.length)); +} +function parseSecretsEnv(envValue) { + if (!envValue) return null; + return envValue.split(",").map((entry) => { + entry = entry.trim(); + const colonIdx = entry.indexOf(":"); + if (colonIdx === -1) throw new BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry: "${entry}". Expected format: ":"`); + const version3 = parseInt(entry.slice(0, colonIdx), 10); + if (!Number.isInteger(version3) || version3 < 0) throw new BetterAuthError(`Invalid version in BETTER_AUTH_SECRETS: "${entry.slice(0, colonIdx)}". Version must be a non-negative integer.`); + const value = entry.slice(colonIdx + 1).trim(); + if (!value) throw new BetterAuthError(`Empty secret value for version ${version3} in BETTER_AUTH_SECRETS.`); + return { + version: version3, + value + }; + }); +} +function validateSecretsArray(secrets, logger2) { + if (secrets.length === 0) throw new BetterAuthError("`secrets` array must contain at least one entry."); + const seen = /* @__PURE__ */ new Set(); + for (const s of secrets) { + const version3 = parseInt(String(s.version), 10); + if (!Number.isInteger(version3) || version3 < 0 || String(version3) !== String(s.version).trim()) throw new BetterAuthError(`Invalid version ${s.version} in \`secrets\`. Version must be a non-negative integer.`); + if (!s.value) throw new BetterAuthError(`Empty secret value for version ${version3} in \`secrets\`.`); + if (seen.has(version3)) throw new BetterAuthError(`Duplicate version ${version3} in \`secrets\`. Each version must be unique.`); + seen.add(version3); + } + const current = secrets[0]; + if (current.value.length < 32) logger2.warn(`[better-auth] Warning: the current secret (version ${current.version}) should be at least 32 characters long for adequate security.`); + if (estimateEntropy(current.value) < 120) logger2.warn("[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production."); +} +function buildSecretConfig(secrets, legacySecret) { + const keys = /* @__PURE__ */ new Map(); + for (const s of secrets) keys.set(parseInt(String(s.version), 10), s.value); + return { + keys, + currentVersion: parseInt(String(secrets[0].version), 10), + legacySecret: legacySecret && legacySecret !== "better-auth-secret-12345678901234567890" ? legacySecret : void 0 + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/create-context.mjs +init_env(); +init_error2(); +init_id2(); + +// ../../node_modules/.pnpm/@better-auth+telemetry@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-f_04cb191a006c1c341def4e42b17bd9b5/node_modules/@better-auth/telemetry/dist/node.mjs +init_env(); +import fs2 from "node:fs"; +import fsPromises from "node:fs/promises"; +import os from "node:os"; +import path2 from "node:path"; +init_random(); +async function getTelemetryAuthConfig(options, context) { + return { + database: context?.database, + adapter: context?.adapter, + emailVerification: { + sendVerificationEmail: !!options.emailVerification?.sendVerificationEmail, + sendOnSignUp: !!options.emailVerification?.sendOnSignUp, + sendOnSignIn: !!options.emailVerification?.sendOnSignIn, + autoSignInAfterVerification: !!options.emailVerification?.autoSignInAfterVerification, + expiresIn: options.emailVerification?.expiresIn, + beforeEmailVerification: !!options.emailVerification?.beforeEmailVerification, + afterEmailVerification: !!options.emailVerification?.afterEmailVerification + }, + emailAndPassword: { + enabled: !!options.emailAndPassword?.enabled, + disableSignUp: !!options.emailAndPassword?.disableSignUp, + requireEmailVerification: !!options.emailAndPassword?.requireEmailVerification, + maxPasswordLength: options.emailAndPassword?.maxPasswordLength, + minPasswordLength: options.emailAndPassword?.minPasswordLength, + sendResetPassword: !!options.emailAndPassword?.sendResetPassword, + resetPasswordTokenExpiresIn: options.emailAndPassword?.resetPasswordTokenExpiresIn, + onPasswordReset: !!options.emailAndPassword?.onPasswordReset, + password: { + hash: !!options.emailAndPassword?.password?.hash, + verify: !!options.emailAndPassword?.password?.verify + }, + autoSignIn: !!options.emailAndPassword?.autoSignIn, + revokeSessionsOnPasswordReset: !!options.emailAndPassword?.revokeSessionsOnPasswordReset + }, + socialProviders: await Promise.all(Object.keys(options.socialProviders || {}).map(async (key) => { + const p = options.socialProviders?.[key]; + if (!p) return {}; + const provider = typeof p === "function" ? await p() : p; + return { + id: key, + mapProfileToUser: !!provider.mapProfileToUser, + disableDefaultScope: !!provider.disableDefaultScope, + disableIdTokenSignIn: !!provider.disableIdTokenSignIn, + disableImplicitSignUp: provider.disableImplicitSignUp, + disableSignUp: provider.disableSignUp, + getUserInfo: !!provider.getUserInfo, + overrideUserInfoOnSignIn: !!provider.overrideUserInfoOnSignIn, + prompt: provider.prompt, + verifyIdToken: !!provider.verifyIdToken, + scope: provider.scope, + refreshAccessToken: !!provider.refreshAccessToken + }; + })), + plugins: options.plugins?.map((p) => p.id.toString()), + user: { + modelName: options.user?.modelName, + fields: options.user?.fields, + additionalFields: options.user?.additionalFields, + changeEmail: { + enabled: options.user?.changeEmail?.enabled, + sendChangeEmailConfirmation: !!options.user?.changeEmail?.sendChangeEmailConfirmation + } + }, + verification: { + modelName: options.verification?.modelName, + disableCleanup: options.verification?.disableCleanup, + fields: options.verification?.fields + }, + session: { + modelName: options.session?.modelName, + additionalFields: options.session?.additionalFields, + cookieCache: { + enabled: options.session?.cookieCache?.enabled, + maxAge: options.session?.cookieCache?.maxAge, + strategy: options.session?.cookieCache?.strategy + }, + disableSessionRefresh: options.session?.disableSessionRefresh, + expiresIn: options.session?.expiresIn, + fields: options.session?.fields, + freshAge: options.session?.freshAge, + preserveSessionInDatabase: options.session?.preserveSessionInDatabase, + storeSessionInDatabase: options.session?.storeSessionInDatabase, + updateAge: options.session?.updateAge + }, + account: { + modelName: options.account?.modelName, + fields: options.account?.fields, + encryptOAuthTokens: options.account?.encryptOAuthTokens, + updateAccountOnSignIn: options.account?.updateAccountOnSignIn, + accountLinking: { + enabled: options.account?.accountLinking?.enabled, + trustedProviders: options.account?.accountLinking?.trustedProviders, + updateUserInfoOnLink: options.account?.accountLinking?.updateUserInfoOnLink, + allowUnlinkingAll: options.account?.accountLinking?.allowUnlinkingAll + } + }, + hooks: { + after: !!options.hooks?.after, + before: !!options.hooks?.before + }, + secondaryStorage: !!options.secondaryStorage, + advanced: { + cookiePrefix: !!options.advanced?.cookiePrefix, + cookies: !!options.advanced?.cookies, + crossSubDomainCookies: { + domain: !!options.advanced?.crossSubDomainCookies?.domain, + enabled: options.advanced?.crossSubDomainCookies?.enabled, + additionalCookies: options.advanced?.crossSubDomainCookies?.additionalCookies + }, + database: { + generateId: options.advanced?.database?.generateId, + defaultFindManyLimit: options.advanced?.database?.defaultFindManyLimit + }, + useSecureCookies: options.advanced?.useSecureCookies, + ipAddress: { + disableIpTracking: options.advanced?.ipAddress?.disableIpTracking, + ipAddressHeaders: options.advanced?.ipAddress?.ipAddressHeaders + }, + disableCSRFCheck: options.advanced?.disableCSRFCheck, + cookieAttributes: { + expires: options.advanced?.defaultCookieAttributes?.expires, + secure: options.advanced?.defaultCookieAttributes?.secure, + sameSite: options.advanced?.defaultCookieAttributes?.sameSite, + domain: !!options.advanced?.defaultCookieAttributes?.domain, + path: options.advanced?.defaultCookieAttributes?.path, + httpOnly: options.advanced?.defaultCookieAttributes?.httpOnly + } + }, + trustedOrigins: options.trustedOrigins?.length, + rateLimit: { + storage: options.rateLimit?.storage, + modelName: options.rateLimit?.modelName, + window: options.rateLimit?.window, + customStorage: !!options.rateLimit?.customStorage, + enabled: options.rateLimit?.enabled, + max: options.rateLimit?.max + }, + onAPIError: { + errorURL: options.onAPIError?.errorURL, + onError: !!options.onAPIError?.onError, + throw: options.onAPIError?.throw + }, + logger: { + disabled: options.logger?.disabled, + level: options.logger?.level, + log: !!options.logger?.log + }, + databaseHooks: { + user: { + create: { + after: !!options.databaseHooks?.user?.create?.after, + before: !!options.databaseHooks?.user?.create?.before + }, + update: { + after: !!options.databaseHooks?.user?.update?.after, + before: !!options.databaseHooks?.user?.update?.before + } + }, + session: { + create: { + after: !!options.databaseHooks?.session?.create?.after, + before: !!options.databaseHooks?.session?.create?.before + }, + update: { + after: !!options.databaseHooks?.session?.update?.after, + before: !!options.databaseHooks?.session?.update?.before + } + }, + account: { + create: { + after: !!options.databaseHooks?.account?.create?.after, + before: !!options.databaseHooks?.account?.create?.before + }, + update: { + after: !!options.databaseHooks?.account?.update?.after, + before: !!options.databaseHooks?.account?.update?.before + } + }, + verification: { + create: { + after: !!options.databaseHooks?.verification?.create?.after, + before: !!options.databaseHooks?.verification?.create?.before + }, + update: { + after: !!options.databaseHooks?.verification?.update?.after, + before: !!options.databaseHooks?.verification?.update?.before + } + } + } + }; +} +function detectPackageManager() { + const userAgent = env.npm_config_user_agent; + if (!userAgent) return; + const pmSpec = userAgent.split(" ")[0]; + const separatorPos = pmSpec.lastIndexOf("/"); + const name = pmSpec.substring(0, separatorPos); + return { + name: name === "npminstall" ? "cnpm" : name, + version: pmSpec.substring(separatorPos + 1) + }; +} +function isCI() { + return env.CI !== "false" && ("BUILD_ID" in env || "BUILD_NUMBER" in env || "CI" in env || "CI_APP_ID" in env || "CI_BUILD_ID" in env || "CI_BUILD_NUMBER" in env || "CI_NAME" in env || "CONTINUOUS_INTEGRATION" in env || "RUN_ID" in env); +} +function detectRuntime() { + if (typeof Deno !== "undefined") return { + name: "deno", + version: Deno?.version?.deno ?? null + }; + if (typeof Bun !== "undefined") return { + name: "bun", + version: Bun?.version ?? null + }; + if (typeof process !== "undefined" && process?.versions?.node) return { + name: "node", + version: process.versions.node ?? null + }; + return { + name: "edge", + version: null + }; +} +function detectEnvironment() { + return getEnvVar("NODE_ENV") === "production" ? "production" : isCI() ? "ci" : isTest() ? "test" : "development"; +} +async function hashToBase64(data) { + const buffer = await createHash("SHA-256").digest(data); + return base643.encode(buffer); +} +var generateId2 = (size) => { + return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32); +}; +var packageJSONCache; +async function readRootPackageJson() { + if (packageJSONCache) return packageJSONCache; + try { + const cwd = process.cwd(); + if (!cwd) return void 0; + const raw2 = await fsPromises.readFile(path2.join(cwd, "package.json"), "utf-8"); + packageJSONCache = JSON.parse(raw2); + return packageJSONCache; + } catch { + } +} +async function getPackageVersion(pkg) { + if (packageJSONCache) return packageJSONCache.dependencies?.[pkg] || packageJSONCache.devDependencies?.[pkg] || packageJSONCache.peerDependencies?.[pkg]; + try { + const cwd = process.cwd(); + if (!cwd) throw new Error("no-cwd"); + const pkgJsonPath = path2.join(cwd, "node_modules", pkg, "package.json"); + const raw2 = await fsPromises.readFile(pkgJsonPath, "utf-8"); + return JSON.parse(raw2).version || await getVersionFromLocalPackageJson(pkg) || void 0; + } catch { + } + return getVersionFromLocalPackageJson(pkg); +} +async function getVersionFromLocalPackageJson(pkg) { + const json2 = await readRootPackageJson(); + if (!json2) return void 0; + return { + ...json2.dependencies, + ...json2.devDependencies, + ...json2.peerDependencies + }[pkg]; +} +async function getNameFromLocalPackageJson() { + return (await readRootPackageJson())?.name; +} +async function detectSystemInfo() { + try { + const cpus = os.cpus(); + return { + deploymentVendor: getVendor(), + systemPlatform: os.platform(), + systemRelease: os.release(), + systemArchitecture: os.arch(), + cpuCount: cpus.length, + cpuModel: cpus.length ? cpus[0].model : null, + cpuSpeed: cpus.length ? cpus[0].speed : null, + memory: os.totalmem(), + isWSL: await isWsl(), + isDocker: await isDocker(), + isTTY: process.stdout ? process.stdout.isTTY : null + }; + } catch { + return { + systemPlatform: null, + systemRelease: null, + systemArchitecture: null, + cpuCount: null, + cpuModel: null, + cpuSpeed: null, + memory: null, + isWSL: null, + isDocker: null, + isTTY: null + }; + } +} +function getVendor() { + const env2 = process.env; + const hasAny = (...keys) => keys.some((k) => Boolean(env2[k])); + if (hasAny("CF_PAGES", "CF_PAGES_URL", "CF_ACCOUNT_ID") || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") return "cloudflare"; + if (hasAny("VERCEL", "VERCEL_URL", "VERCEL_ENV")) return "vercel"; + if (hasAny("NETLIFY", "NETLIFY_URL")) return "netlify"; + if (hasAny("RENDER", "RENDER_URL", "RENDER_INTERNAL_HOSTNAME", "RENDER_SERVICE_ID")) return "render"; + if (hasAny("AWS_LAMBDA_FUNCTION_NAME", "AWS_EXECUTION_ENV", "LAMBDA_TASK_ROOT")) return "aws"; + if (hasAny("GOOGLE_CLOUD_FUNCTION_NAME", "GOOGLE_CLOUD_PROJECT", "GCP_PROJECT", "K_SERVICE")) return "gcp"; + if (hasAny("AZURE_FUNCTION_NAME", "FUNCTIONS_WORKER_RUNTIME", "WEBSITE_INSTANCE_ID", "WEBSITE_SITE_NAME")) return "azure"; + if (hasAny("DENO_DEPLOYMENT_ID", "DENO_REGION")) return "deno-deploy"; + if (hasAny("FLY_APP_NAME", "FLY_REGION", "FLY_ALLOC_ID")) return "fly-io"; + if (hasAny("RAILWAY_STATIC_URL", "RAILWAY_ENVIRONMENT_NAME")) return "railway"; + if (hasAny("DYNO", "HEROKU_APP_NAME")) return "heroku"; + if (hasAny("DO_DEPLOYMENT_ID", "DO_APP_NAME", "DIGITALOCEAN")) return "digitalocean"; + if (hasAny("KOYEB", "KOYEB_DEPLOYMENT_ID", "KOYEB_APP_NAME")) return "koyeb"; + return null; +} +var isDockerCached; +async function hasDockerEnv() { + try { + fs2.statSync("/.dockerenv"); + return true; + } catch { + return false; + } +} +async function hasDockerCGroup() { + try { + return fs2.readFileSync("/proc/self/cgroup", "utf8").includes("docker"); + } catch { + return false; + } +} +async function isDocker() { + if (isDockerCached === void 0) isDockerCached = await hasDockerEnv() || await hasDockerCGroup(); + return isDockerCached; +} +var isInsideContainerCached; +var hasContainerEnv = async () => { + try { + fs2.statSync("/run/.containerenv"); + return true; + } catch { + return false; + } +}; +async function isInsideContainer() { + if (isInsideContainerCached === void 0) isInsideContainerCached = await hasContainerEnv() || await isDocker(); + return isInsideContainerCached; +} +async function isWsl() { + try { + if (process.platform !== "linux") return false; + if (os.release().toLowerCase().includes("microsoft")) { + if (await isInsideContainer()) return false; + return true; + } + return fs2.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !await isInsideContainer() : false; + } catch { + return false; + } +} +var projectIdCached = null; +async function getProjectId(baseUrl) { + if (projectIdCached) return projectIdCached; + const projectName = await getNameFromLocalPackageJson(); + if (projectName) { + projectIdCached = await hashToBase64(baseUrl ? baseUrl + projectName : projectName); + return projectIdCached; + } + if (baseUrl) { + projectIdCached = await hashToBase64(baseUrl); + return projectIdCached; + } + projectIdCached = generateId2(32); + return projectIdCached; +} +async function detectDatabaseNode() { + for (const [pkg, name] of Object.entries({ + pg: "postgresql", + mysql: "mysql", + mariadb: "mariadb", + sqlite3: "sqlite", + "better-sqlite3": "sqlite", + "@prisma/client": "prisma", + mongoose: "mongodb", + mongodb: "mongodb", + "drizzle-orm": "drizzle" + })) { + const version3 = await getPackageVersion(pkg); + if (version3) return { + name, + version: version3 + }; + } +} +async function detectFrameworkNode() { + for (const [pkg, name] of Object.entries({ + next: "next", + nuxt: "nuxt", + "react-router": "react-router", + astro: "astro", + "@sveltejs/kit": "sveltekit", + "solid-start": "solid-start", + "tanstack-start": "tanstack-start", + hono: "hono", + express: "express", + elysia: "elysia", + expo: "expo" + })) { + const version3 = await getPackageVersion(pkg); + if (version3) return { + name, + version: version3 + }; + } +} +var noop2 = async function noop3() { +}; +async function createTelemetry(options, context) { + const debugEnabled = options.telemetry?.debug || getBooleanEnvVar("BETTER_AUTH_TELEMETRY_DEBUG", false); + const telemetryEndpoint = ENV.BETTER_AUTH_TELEMETRY_ENDPOINT; + if (!telemetryEndpoint && !context?.customTrack) return { publish: noop2 }; + const track = async (event) => { + if (context?.customTrack) await context.customTrack(event).catch(logger.error); + else if (telemetryEndpoint) if (debugEnabled) logger.info("telemetry event", JSON.stringify(event, null, 2)); + else await betterFetch(telemetryEndpoint, { + method: "POST", + body: event + }).catch(logger.error); + }; + const isEnabled = async () => { + const telemetryEnabled = options.telemetry?.enabled !== void 0 ? options.telemetry.enabled : false; + return (getBooleanEnvVar("BETTER_AUTH_TELEMETRY", false) || telemetryEnabled) && (context?.skipTestCheck || !isTest()); + }; + const enabled = await isEnabled(); + let anonymousId; + if (enabled) { + anonymousId = await getProjectId(typeof options.baseURL === "string" ? options.baseURL : void 0); + track({ + type: "init", + payload: { + config: await getTelemetryAuthConfig(options, context), + runtime: detectRuntime(), + database: await detectDatabaseNode(), + framework: await detectFrameworkNode(), + environment: detectEnvironment(), + systemInfo: await detectSystemInfo(), + packageManager: detectPackageManager() + }, + anonymousId + }); + } + return { publish: async (event) => { + if (!enabled) return; + if (!anonymousId) anonymousId = await getProjectId(typeof options.baseURL === "string" ? options.baseURL : void 0); + await track({ + type: event.type, + payload: event.payload, + anonymousId + }); + } }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/create-context.mjs +function estimateEntropy2(str) { + const unique2 = new Set(str).size; + if (unique2 === 0) return 0; + return Math.log2(Math.pow(unique2, str.length)); +} +function validateSecret(secret, logger2) { + const isDefaultSecret = secret === DEFAULT_SECRET; + if (isTest()) return; + if (isDefaultSecret && isProduction) throw new BetterAuthError("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config."); + if (!secret) throw new BetterAuthError("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret })."); + if (secret.length < 32) logger2.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with \`npx auth secret\` or \`openssl rand -base64 32\`.`); + if (estimateEntropy2(secret) < 120) logger2.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production."); +} +async function createAuthContext(adapter, options, getDatabaseType) { + if (!options.database) options = defu(options, { + session: { cookieCache: { + enabled: true, + strategy: "jwe", + refreshCache: true, + maxAge: options.session?.expiresIn || 3600 * 24 * 7 + } }, + account: { + storeStateStrategy: "cookie", + storeAccountCookie: true + } + }); + const plugins = options.plugins || []; + const internalPlugins = getInternalPlugins(options); + const logger2 = createLogger2(options.logger); + const isDynamicConfig = isDynamicBaseURLConfig(options.baseURL); + if (isDynamicBaseURLConfig(options.baseURL)) { + const { allowedHosts } = options.baseURL; + if (!allowedHosts || allowedHosts.length === 0) throw new BetterAuthError('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).'); + } + const baseURL = isDynamicConfig ? void 0 : getBaseURL(typeof options.baseURL === "string" ? options.baseURL : void 0, options.basePath); + if (!baseURL && !isDynamicConfig) logger2.warn(`[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_URL environment variable. Without this, callbacks and redirects may not work correctly.`); + if (adapter.id === "memory" && options.advanced?.database?.generateId === false) logger2.error(`[better-auth] Misconfiguration detected. +You are using the memory DB with generateId: false. +This will cause no id to be generated for any model. +Most of the features of Better Auth will not work correctly.`); + const secretsArray = options.secrets ?? parseSecretsEnv(env.BETTER_AUTH_SECRETS); + const legacySecret = options.secret || env.BETTER_AUTH_SECRET || env.AUTH_SECRET || ""; + let secret; + let secretConfig; + if (secretsArray) { + validateSecretsArray(secretsArray, logger2); + secret = secretsArray[0].value; + secretConfig = buildSecretConfig(secretsArray, legacySecret); + } else { + secret = legacySecret || "better-auth-secret-12345678901234567890"; + validateSecret(secret, logger2); + secretConfig = secret; + } + options = { + ...options, + secret, + baseURL: isDynamicConfig ? options.baseURL : baseURL ? new URL(baseURL).origin : "", + basePath: options.basePath || "/api/auth", + plugins: plugins.concat(internalPlugins) + }; + checkEndpointConflicts(options, logger2); + const cookies = getCookies(options); + const tables = getAuthTables(options); + const providers = (await Promise.all(Object.entries(options.socialProviders || {}).map(async ([key, originalConfig]) => { + const config4 = typeof originalConfig === "function" ? await originalConfig() : originalConfig; + if (config4 == null) return null; + if (config4.enabled === false) return null; + if (!config4.clientId) logger2.warn(`Social provider ${key} is missing clientId or clientSecret`); + const provider = socialProviders[key](config4); + provider.disableImplicitSignUp = config4.disableImplicitSignUp; + return provider; + }))).filter((x) => x !== null); + const generateIdFunc = ({ model, size }) => { + if (typeof options.advanced?.generateId === "function") return options.advanced.generateId({ + model, + size + }); + const dbGenerateId = options?.advanced?.database?.generateId; + if (typeof dbGenerateId === "function") return dbGenerateId({ + model, + size + }); + if (dbGenerateId === "uuid") return crypto.randomUUID(); + if (dbGenerateId === "serial" || dbGenerateId === false) return false; + return generateId(size); + }; + const { publish } = await createTelemetry(options, { + adapter: adapter.id, + database: typeof options.database === "function" ? "adapter" : getDatabaseType(options.database) + }); + const pluginIds = new Set(options.plugins.map((p) => p.id)); + const getPluginFn = (id) => options.plugins.find((p) => p.id === id) ?? null; + const hasPluginFn = (id) => pluginIds.has(id); + const trustedOrigins = await getTrustedOrigins(options); + const trustedProviders = await getTrustedProviders(options); + const ctx = { + appName: options.appName || "Better Auth", + baseURL: baseURL || "", + version: getBetterAuthVersion(), + socialProviders: providers, + options, + oauthConfig: { + storeStateStrategy: options.account?.storeStateStrategy || (options.database ? "database" : "cookie"), + skipStateCookieCheck: !!options.account?.skipStateCookieCheck + }, + tables, + trustedOrigins, + trustedProviders, + isTrustedOrigin(url2, settings) { + return this.trustedOrigins.some((origin) => matchesOriginPattern(url2, origin, settings)); + }, + sessionConfig: { + updateAge: options.session?.updateAge !== void 0 ? options.session.updateAge : 1440 * 60, + expiresIn: options.session?.expiresIn || 3600 * 24 * 7, + freshAge: options.session?.freshAge === void 0 ? 3600 * 24 : options.session.freshAge, + cookieRefreshCache: (() => { + const refreshCache = options.session?.cookieCache?.refreshCache; + const maxAge = options.session?.cookieCache?.maxAge || 300; + if ((!!options.database || !!options.secondaryStorage) && refreshCache) { + logger2.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` \u2014 remove it from your config to silence this warning."); + return false; + } + if (refreshCache === false || refreshCache === void 0) return false; + if (refreshCache === true) return { + enabled: true, + updateAge: Math.floor(maxAge * 0.2) + }; + return { + enabled: true, + updateAge: refreshCache.updateAge !== void 0 ? refreshCache.updateAge : Math.floor(maxAge * 0.2) + }; + })() + }, + secret, + secretConfig, + rateLimit: { + ...options.rateLimit, + enabled: options.rateLimit?.enabled ?? isProduction, + window: options.rateLimit?.window || 10, + max: options.rateLimit?.max || 100, + storage: options.rateLimit?.storage || (options.secondaryStorage ? "secondary-storage" : "memory") + }, + authCookies: cookies, + logger: logger2, + generateId: generateIdFunc, + session: null, + secondaryStorage: options.secondaryStorage, + password: { + hash: options.emailAndPassword?.password?.hash || hashPassword$1, + verify: options.emailAndPassword?.password?.verify || verifyPassword$1, + config: { + minPasswordLength: options.emailAndPassword?.minPasswordLength || 8, + maxPasswordLength: options.emailAndPassword?.maxPasswordLength || 128 + }, + checkPassword + }, + setNewSession(session) { + this.newSession = session; + }, + newSession: null, + adapter, + internalAdapter: createInternalAdapter(adapter, { + options, + logger: logger2, + hooks: options.databaseHooks ? [{ + source: "user", + hooks: options.databaseHooks + }] : [], + generateId: generateIdFunc + }), + createAuthCookie: createCookieGetter(options), + async runMigrations() { + throw new BetterAuthError("runMigrations will be set by the specific init implementation"); + }, + publishTelemetry: publish, + skipCSRFCheck: !!options.advanced?.disableCSRFCheck, + skipOriginCheck: options.advanced?.disableOriginCheck !== void 0 ? options.advanced.disableOriginCheck : isTest() ? true : false, + runInBackground: options.advanced?.backgroundTasks?.handler ?? ((p) => { + p.catch(() => { + }); + }), + async runInBackgroundOrAwait(promise2) { + try { + if (options.advanced?.backgroundTasks?.handler) { + if (promise2 instanceof Promise) options.advanced.backgroundTasks.handler(promise2.catch((e) => { + logger2.error("Failed to run background task:", e); + })); + } else await promise2; + } catch (e) { + logger2.error("Failed to run background task:", e); + } + }, + getPlugin: getPluginFn, + hasPlugin: hasPluginFn + }; + const initOrPromise = runPluginInit(ctx); + if (isPromise(initOrPromise)) await initOrPromise; + return ctx; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/init.mjs +init_error2(); +init_dist2(); +var init = async (options) => { + const adapter = await getAdapter(options); + const getDatabaseType = (database) => getKyselyDatabaseType(database) || "unknown"; + const ctx = await createAuthContext(adapter, options, getDatabaseType); + ctx.runMigrations = async function() { + if (!options.database || "updateMany" in options.database) throw new BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance."); + const { runMigrations } = await getMigrations(options); + await runMigrations(); + }; + return ctx; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/base.mjs +init_error2(); +var createBetterAuth = (options, initFn) => { + const authContext = initFn(options); + const { api } = getEndpoints(authContext, options); + return { + handler: async (request) => { + const ctx = await authContext; + const basePath = ctx.options.basePath || "/api/auth"; + let handlerCtx; + if (isDynamicBaseURLConfig(options.baseURL)) { + handlerCtx = Object.create(Object.getPrototypeOf(ctx), Object.getOwnPropertyDescriptors(ctx)); + const baseURL = resolveBaseURL(options.baseURL, basePath, request); + if (baseURL) { + handlerCtx.baseURL = baseURL; + handlerCtx.options = { + ...ctx.options, + baseURL: getOrigin(baseURL) || void 0 + }; + } else throw new BetterAuthError("Could not resolve base URL from request. Check your allowedHosts config."); + const trustedOriginOptions = { + ...handlerCtx.options, + baseURL: options.baseURL + }; + handlerCtx.trustedOrigins = await getTrustedOrigins(trustedOriginOptions, request); + if (options.advanced?.crossSubDomainCookies?.enabled) { + handlerCtx.authCookies = getCookies(handlerCtx.options); + handlerCtx.createAuthCookie = createCookieGetter(handlerCtx.options); + } + } else { + handlerCtx = ctx; + if (!ctx.options.baseURL) { + const baseURL = getBaseURL(void 0, basePath, request, void 0, ctx.options.advanced?.trustedProxyHeaders); + if (baseURL) { + ctx.baseURL = baseURL; + ctx.options.baseURL = getOrigin(ctx.baseURL) || void 0; + } else throw new BetterAuthError("Could not get base URL from request. Please provide a valid base URL."); + } + handlerCtx.trustedOrigins = await getTrustedOrigins(ctx.options, request); + } + handlerCtx.trustedProviders = await getTrustedProviders(handlerCtx.options, request); + const { handler } = router(handlerCtx, options); + return runWithAdapter(handlerCtx.adapter, () => handler(request)); + }, + api, + options, + $context: authContext, + $ERROR_CODES: { + ...options.plugins?.reduce((acc, plugin) => { + if (plugin.$ERROR_CODES) return { + ...acc, + ...plugin.$ERROR_CODES + }; + return acc; + }, {}), + ...BASE_ERROR_CODES + } + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/full.mjs +var betterAuth = (options) => { + return createBetterAuth(options, init); +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/index.mjs +init_env(); +init_error2(); +init_error_codes(); +init_id2(); +init_json(); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/client/parser.mjs +var PROTO_POLLUTION_PATTERNS = { + proto: /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/, + constructor: /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/, + protoShort: /"__proto__"\s*:/, + constructorShort: /"constructor"\s*:/ +}; +var JSON_SIGNATURE = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; +var SPECIAL_VALUES = { + true: true, + false: false, + null: null, + undefined: void 0, + nan: NaN, + infinity: Number.POSITIVE_INFINITY, + "-infinity": Number.NEGATIVE_INFINITY +}; +var ISO_DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/; +function isValidDate(date5) { + return date5 instanceof Date && !isNaN(date5.getTime()); +} +function parseISODate(value) { + const match2 = ISO_DATE_REGEX.exec(value); + if (!match2) return null; + const [, year2, month, day2, hour2, minute2, second, ms, offsetSign, offsetHour, offsetMinute] = match2; + const date5 = new Date(Date.UTC(parseInt(year2, 10), parseInt(month, 10) - 1, parseInt(day2, 10), parseInt(hour2, 10), parseInt(minute2, 10), parseInt(second, 10), ms ? parseInt(ms.padEnd(3, "0"), 10) : 0)); + if (offsetSign) { + const offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === "+" ? -1 : 1); + date5.setUTCMinutes(date5.getUTCMinutes() + offset); + } + return isValidDate(date5) ? date5 : null; +} +function betterJSONParse(value, options = {}) { + const { strict = false, warnings = false, reviver, parseDates = true } = options; + if (typeof value !== "string") return value; + const trimmed = value.trim(); + if (trimmed.length > 0 && trimmed[0] === '"' && trimmed.endsWith('"') && !trimmed.slice(1, -1).includes('"')) return trimmed.slice(1, -1); + const lowerValue = trimmed.toLowerCase(); + if (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) return SPECIAL_VALUES[lowerValue]; + if (!JSON_SIGNATURE.test(trimmed)) { + if (strict) throw new SyntaxError("[better-json] Invalid JSON"); + return value; + } + if (Object.entries(PROTO_POLLUTION_PATTERNS).some(([key, pattern]) => { + const matches = pattern.test(trimmed); + if (matches && warnings) console.warn(`[better-json] Detected potential prototype pollution attempt using ${key} pattern`); + return matches; + }) && strict) throw new Error("[better-json] Potential prototype pollution attempt detected"); + try { + const secureReviver = (key, value2) => { + if (key === "__proto__" || key === "constructor" && value2 && typeof value2 === "object" && "prototype" in value2) { + if (warnings) console.warn(`[better-json] Dropping "${key}" key to prevent prototype pollution`); + return; + } + if (parseDates && typeof value2 === "string") { + const date5 = parseISODate(value2); + if (date5) return date5; + } + return reviver ? reviver(key, value2) : value2; + }; + return JSON.parse(trimmed, secureReviver); + } catch (error49) { + if (strict) throw error49; + return value; + } +} +function parseJSON(value, options = { strict: true }) { + return betterJSONParse(value, options); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/adapter.mjs +init_error2(); +var getOrgAdapter = (context, options) => { + const baseAdapter = context.adapter; + const orgAdditionalFields = options?.schema?.organization?.additionalFields; + const memberAdditionalFields = options?.schema?.member?.additionalFields; + const invitationAdditionalFields = options?.schema?.invitation?.additionalFields; + const teamAdditionalFields = options?.schema?.team?.additionalFields; + return { + findOrganizationBySlug: async (slug) => { + return filterOutputFields(await (await getCurrentAdapter(baseAdapter)).findOne({ + model: "organization", + where: [{ + field: "slug", + value: slug + }] + }), orgAdditionalFields); + }, + createOrganization: async (data) => { + const organization2 = await (await getCurrentAdapter(baseAdapter)).create({ + model: "organization", + data: { + ...data.organization, + metadata: data.organization.metadata ? JSON.stringify(data.organization.metadata) : void 0 + }, + forceAllowId: true + }); + return filterOutputFields({ + ...organization2, + metadata: organization2.metadata && typeof organization2.metadata === "string" ? JSON.parse(organization2.metadata) : void 0 + }, orgAdditionalFields); + }, + findMemberByEmail: async (data) => { + const adapter = await getCurrentAdapter(baseAdapter); + const user = await adapter.findOne({ + model: "user", + where: [{ + field: "email", + value: data.email.toLowerCase() + }] + }); + if (!user) return null; + const member = await adapter.findOne({ + model: "member", + where: [{ + field: "organizationId", + value: data.organizationId + }, { + field: "userId", + value: user.id + }] + }); + if (!member) return null; + return { + ...member, + user: { + id: user.id, + name: user.name, + email: user.email, + image: user.image + } + }; + }, + listMembers: async (data) => { + const adapter = await getCurrentAdapter(baseAdapter); + const members = await Promise.all([adapter.findMany({ + model: "member", + where: [{ + field: "organizationId", + value: data.organizationId + }, ...data.filter?.field ? [{ + field: data.filter?.field, + value: data.filter?.value, + ...data.filter.operator ? { operator: data.filter.operator } : {} + }] : []], + limit: data.limit || (typeof options?.membershipLimit === "number" ? options.membershipLimit : 100) || 100, + offset: data.offset || 0, + sortBy: data.sortBy ? { + field: data.sortBy, + direction: data.sortOrder || "asc" + } : void 0 + }), adapter.count({ + model: "member", + where: [{ + field: "organizationId", + value: data.organizationId + }, ...data.filter?.field ? [{ + field: data.filter?.field, + value: data.filter?.value, + ...data.filter.operator ? { operator: data.filter.operator } : {} + }] : []] + })]); + const users = await adapter.findMany({ + model: "user", + where: [{ + field: "id", + value: members[0].map((member) => member.userId), + operator: "in" + }] + }); + return { + members: members[0].map((member) => { + const user = users.find((user2) => user2.id === member.userId); + if (!user) throw new BetterAuthError("Unexpected error: User not found for member"); + return { + ...member, + user: { + id: user.id, + name: user.name, + email: user.email, + image: user.image + } + }; + }), + total: members[1] + }; + }, + findMemberByOrgId: async (data) => { + const result = await (await getCurrentAdapter(baseAdapter)).findOne({ + model: "member", + where: [{ + field: "userId", + value: data.userId + }, { + field: "organizationId", + value: data.organizationId + }], + join: { user: true } + }); + if (!result || !result.user) return null; + const { user, ...member } = result; + return { + ...member, + user: { + id: user.id, + name: user.name, + email: user.email, + image: user.image + } + }; + }, + findMemberById: async (memberId) => { + const result = await (await getCurrentAdapter(baseAdapter)).findOne({ + model: "member", + where: [{ + field: "id", + value: memberId + }], + join: { user: true } + }); + if (!result) return null; + const { user, ...member } = result; + return { + ...member, + user: { + id: user.id, + name: user.name, + email: user.email, + image: user.image + } + }; + }, + createMember: async (data) => { + return await (await getCurrentAdapter(baseAdapter)).create({ + model: "member", + data: { + ...data, + createdAt: /* @__PURE__ */ new Date() + } + }); + }, + updateMember: async (memberId, role2) => { + return await (await getCurrentAdapter(baseAdapter)).update({ + model: "member", + where: [{ + field: "id", + value: memberId + }], + update: { role: role2 } + }); + }, + deleteMember: async ({ memberId, organizationId, userId: _userId }) => { + const adapter = await getCurrentAdapter(baseAdapter); + let userId; + if (!_userId) { + const member2 = await adapter.findOne({ + model: "member", + where: [{ + field: "id", + value: memberId + }] + }); + if (!member2) throw new BetterAuthError("Member not found"); + userId = member2.userId; + } else userId = _userId; + const member = await adapter.delete({ + model: "member", + where: [{ + field: "id", + value: memberId + }] + }); + if (options?.teams?.enabled) { + const teams = await adapter.findMany({ + model: "team", + where: [{ + field: "organizationId", + value: organizationId + }] + }); + await Promise.all(teams.map((team) => adapter.deleteMany({ + model: "teamMember", + where: [{ + field: "teamId", + value: team.id + }, { + field: "userId", + value: userId + }] + }))); + } + return member; + }, + updateOrganization: async (organizationId, data) => { + const organization2 = await (await getCurrentAdapter(baseAdapter)).update({ + model: "organization", + where: [{ + field: "id", + value: organizationId + }], + update: { + ...data, + metadata: typeof data.metadata === "object" ? JSON.stringify(data.metadata) : data.metadata + } + }); + if (!organization2) return null; + return filterOutputFields({ + ...organization2, + metadata: organization2.metadata ? parseJSON(organization2.metadata) : void 0 + }, orgAdditionalFields); + }, + deleteOrganization: async (organizationId) => { + const adapter = await getCurrentAdapter(baseAdapter); + await adapter.deleteMany({ + model: "member", + where: [{ + field: "organizationId", + value: organizationId + }] + }); + await adapter.deleteMany({ + model: "invitation", + where: [{ + field: "organizationId", + value: organizationId + }] + }); + await adapter.delete({ + model: "organization", + where: [{ + field: "id", + value: organizationId + }] + }); + return organizationId; + }, + setActiveOrganization: async (sessionToken, organizationId, ctx) => { + return await context.internalAdapter.updateSession(sessionToken, { activeOrganizationId: organizationId }); + }, + findOrganizationById: async (organizationId) => { + return filterOutputFields(await (await getCurrentAdapter(baseAdapter)).findOne({ + model: "organization", + where: [{ + field: "id", + value: organizationId + }] + }), orgAdditionalFields); + }, + checkMembership: async ({ userId, organizationId }) => { + return await (await getCurrentAdapter(baseAdapter)).findOne({ + model: "member", + where: [{ + field: "userId", + value: userId + }, { + field: "organizationId", + value: organizationId + }] + }); + }, + findFullOrganization: async ({ organizationId, isSlug, includeTeams, membersLimit }) => { + const adapter = await getCurrentAdapter(baseAdapter); + const result = await adapter.findOne({ + model: "organization", + where: [{ + field: isSlug ? "slug" : "id", + value: organizationId + }], + join: { + invitation: true, + member: membersLimit ? { limit: membersLimit } : true, + ...includeTeams ? { team: true } : {} + } + }); + if (!result) return null; + const { invitation: invitations, member: members, team: teams, ...org } = result; + const userIds = members.map((member) => member.userId); + const users = userIds.length > 0 ? await adapter.findMany({ + model: "user", + where: [{ + field: "id", + value: userIds, + operator: "in" + }], + limit: (typeof options?.membershipLimit === "number" ? options.membershipLimit : 100) || 100 + }) : []; + const userMap = new Map(users.map((user) => [user.id, user])); + const membersWithUsers = members.map((member) => { + const user = userMap.get(member.userId); + if (!user) throw new BetterAuthError("Unexpected error: User not found for member"); + return { + ...filterOutputFields(member, memberAdditionalFields), + user: { + id: user.id, + name: user.name, + email: user.email, + image: user.image + } + }; + }); + const filteredOrg = filterOutputFields(org, orgAdditionalFields); + const filteredInvitations = invitations.map((inv) => filterOutputFields(inv, invitationAdditionalFields)); + const filteredTeams = teams?.map((team) => filterOutputFields(team, teamAdditionalFields)); + return { + ...filteredOrg, + invitations: filteredInvitations, + members: membersWithUsers, + teams: filteredTeams + }; + }, + listOrganizations: async (userId) => { + const result = await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "member", + where: [{ + field: "userId", + value: userId + }], + join: { organization: true } + }); + if (!result || result.length === 0) return []; + return result.map((member) => filterOutputFields(member.organization, orgAdditionalFields)); + }, + createTeam: async (data) => { + return await (await getCurrentAdapter(baseAdapter)).create({ + model: "team", + data + }); + }, + findTeamById: async ({ teamId, organizationId, includeTeamMembers }) => { + const result = await (await getCurrentAdapter(baseAdapter)).findOne({ + model: "team", + where: [{ + field: "id", + value: teamId + }, ...organizationId ? [{ + field: "organizationId", + value: organizationId + }] : []], + join: { ...includeTeamMembers ? { teamMember: true } : {} } + }); + if (!result) return null; + const { teamMember, ...team } = result; + return { + ...team, + ...includeTeamMembers ? { members: teamMember } : {} + }; + }, + updateTeam: async (teamId, data) => { + const adapter = await getCurrentAdapter(baseAdapter); + if ("id" in data) data.id = void 0; + return await adapter.update({ + model: "team", + where: [{ + field: "id", + value: teamId + }], + update: { ...data } + }); + }, + deleteTeam: async (teamId) => { + const adapter = await getCurrentAdapter(baseAdapter); + await adapter.deleteMany({ + model: "teamMember", + where: [{ + field: "teamId", + value: teamId + }] + }); + return await adapter.delete({ + model: "team", + where: [{ + field: "id", + value: teamId + }] + }); + }, + listTeams: async (organizationId) => { + return await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "team", + where: [{ + field: "organizationId", + value: organizationId + }] + }); + }, + createTeamInvitation: async ({ email: email3, role: role2, teamId, organizationId, inviterId, expiresIn = 1e3 * 60 * 60 * 48 }) => { + const adapter = await getCurrentAdapter(baseAdapter); + const expiresAt = getDate(expiresIn); + return await adapter.create({ + model: "invitation", + data: { + email: email3, + role: role2, + organizationId, + teamId, + inviterId, + status: "pending", + expiresAt + } + }); + }, + setActiveTeam: async (sessionToken, teamId, ctx) => { + return await context.internalAdapter.updateSession(sessionToken, { activeTeamId: teamId }); + }, + listTeamMembers: async (data) => { + return await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "teamMember", + where: [{ + field: "teamId", + value: data.teamId + }] + }); + }, + countTeamMembers: async (data) => { + return await (await getCurrentAdapter(baseAdapter)).count({ + model: "teamMember", + where: [{ + field: "teamId", + value: data.teamId + }] + }); + }, + countMembers: async (data) => { + return await (await getCurrentAdapter(baseAdapter)).count({ + model: "member", + where: [{ + field: "organizationId", + value: data.organizationId + }] + }); + }, + listTeamsByUser: async (data) => { + return (await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "teamMember", + where: [{ + field: "userId", + value: data.userId + }], + join: { team: true } + })).map((result) => result.team); + }, + findTeamMember: async (data) => { + return await (await getCurrentAdapter(baseAdapter)).findOne({ + model: "teamMember", + where: [{ + field: "teamId", + value: data.teamId + }, { + field: "userId", + value: data.userId + }] + }); + }, + findOrCreateTeamMember: async (data) => { + const adapter = await getCurrentAdapter(baseAdapter); + const member = await adapter.findOne({ + model: "teamMember", + where: [{ + field: "teamId", + value: data.teamId + }, { + field: "userId", + value: data.userId + }] + }); + if (member) return member; + return await adapter.create({ + model: "teamMember", + data: { + teamId: data.teamId, + userId: data.userId, + createdAt: /* @__PURE__ */ new Date() + } + }); + }, + removeTeamMember: async (data) => { + await (await getCurrentAdapter(baseAdapter)).deleteMany({ + model: "teamMember", + where: [{ + field: "teamId", + value: data.teamId + }, { + field: "userId", + value: data.userId + }] + }); + }, + findInvitationsByTeamId: async (teamId) => { + return await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "invitation", + where: [{ + field: "teamId", + value: teamId + }] + }); + }, + listUserInvitations: async (email3) => { + return (await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "invitation", + where: [{ + field: "email", + value: email3.toLowerCase() + }], + join: { organization: true } + })).filter(Boolean).map(({ organization: organization2, ...inv }) => ({ + ...inv, + organizationName: organization2?.name + })); + }, + createInvitation: async ({ invitation, user }) => { + const adapter = await getCurrentAdapter(baseAdapter); + const expiresAt = getDate(options?.invitationExpiresIn || 3600 * 48, "sec"); + return await adapter.create({ + model: "invitation", + data: { + status: "pending", + expiresAt, + createdAt: /* @__PURE__ */ new Date(), + inviterId: user.id, + ...invitation, + teamId: invitation.teamIds.length > 0 ? invitation.teamIds.join(",") : null + } + }); + }, + findInvitationById: async (id) => { + return await (await getCurrentAdapter(baseAdapter)).findOne({ + model: "invitation", + where: [{ + field: "id", + value: id + }] + }); + }, + findPendingInvitation: async (data) => { + return (await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "invitation", + where: [ + { + field: "email", + value: data.email.toLowerCase() + }, + { + field: "organizationId", + value: data.organizationId + }, + { + field: "status", + value: "pending" + } + ] + })).filter((invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date()); + }, + findPendingInvitations: async (data) => { + return (await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "invitation", + where: [{ + field: "organizationId", + value: data.organizationId + }, { + field: "status", + value: "pending" + }] + })).filter((invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date()); + }, + listInvitations: async (data) => { + return await (await getCurrentAdapter(baseAdapter)).findMany({ + model: "invitation", + where: [{ + field: "organizationId", + value: data.organizationId + }] + }); + }, + updateInvitation: async (data) => { + return await (await getCurrentAdapter(baseAdapter)).update({ + model: "invitation", + where: [{ + field: "id", + value: data.invitationId + }], + update: { status: data.status } + }); + } + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/access/access.mjs +init_error2(); +function role(statements) { + return { + authorize(request, connector = "AND") { + let success2 = false; + for (const [requestedResource, requestedActions] of Object.entries(request)) { + const allowedActions = statements[requestedResource]; + if (!allowedActions) return { + success: false, + error: `You are not allowed to access resource: ${requestedResource}` + }; + if (Array.isArray(requestedActions)) success2 = requestedActions.every((requestedAction) => allowedActions.includes(requestedAction)); + else if (typeof requestedActions === "object") { + const actions = requestedActions; + if (actions.connector === "OR") success2 = actions.actions.some((requestedAction) => allowedActions.includes(requestedAction)); + else success2 = actions.actions.every((requestedAction) => allowedActions.includes(requestedAction)); + } else throw new BetterAuthError("Invalid access control request"); + if (success2 && connector === "OR") return { success: success2 }; + if (!success2 && connector === "AND") return { + success: false, + error: `unauthorized to access resource "${requestedResource}"` + }; + } + if (success2) return { success: success2 }; + return { + success: false, + error: "Not authorized" + }; + }, + statements + }; +} +function createAccessControl(s) { + return { + newRole(statements) { + return role(statements); + }, + statements: s + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/access/statement.mjs +var defaultStatements = { + organization: ["update", "delete"], + member: [ + "create", + "update", + "delete" + ], + invitation: ["create", "cancel"], + team: [ + "create", + "update", + "delete" + ], + ac: [ + "create", + "read", + "update", + "delete" + ] +}; +var defaultAc = createAccessControl(defaultStatements); +var adminAc = defaultAc.newRole({ + organization: ["update"], + invitation: ["create", "cancel"], + member: [ + "create", + "update", + "delete" + ], + team: [ + "create", + "update", + "delete" + ], + ac: [ + "create", + "read", + "update", + "delete" + ] +}); +var ownerAc = defaultAc.newRole({ + organization: ["update", "delete"], + member: [ + "create", + "update", + "delete" + ], + invitation: ["create", "cancel"], + team: [ + "create", + "update", + "delete" + ], + ac: [ + "create", + "read", + "update", + "delete" + ] +}); +var memberAc = defaultAc.newRole({ + organization: [], + member: [], + invitation: [], + team: [], + ac: ["read"] +}); +var defaultRoles = { + admin: adminAc, + owner: ownerAc, + member: memberAc +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/permission.mjs +var hasPermissionFn = (input, acRoles) => { + if (!input.permissions) return false; + const roles = input.role.split(","); + const creatorRole = input.options.creatorRole || "owner"; + const isCreator = roles.includes(creatorRole); + const allowCreatorsAllPermissions = input.allowCreatorAllPermissions || false; + if (isCreator && allowCreatorsAllPermissions) return true; + for (const role2 of roles) if (acRoles[role2]?.authorize(input.permissions)?.success) return true; + return false; +}; +var cacheAllRoles = /* @__PURE__ */ new Map(); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/has-permission.mjs +init_zod(); +var hasPermission = async (input, ctx) => { + let acRoles = { ...input.options.roles || defaultRoles }; + if (ctx && input.organizationId && input.options.dynamicAccessControl?.enabled && input.options.ac && !input.useMemoryCache) { + const roles = await ctx.context.adapter.findMany({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: input.organizationId + }] + }); + for (const { role: role2, permission: permissionsString } of roles) { + const result = record(string2(), array(string2())).safeParse(JSON.parse(permissionsString)); + if (!result.success) { + ctx.context.logger.error("[hasPermission] Invalid permissions for role " + role2, { permissions: JSON.parse(permissionsString) }); + throw new APIError2("INTERNAL_SERVER_ERROR", { message: "Invalid permissions for role " + role2 }); + } + const merged = { ...acRoles[role2]?.statements }; + for (const [key, actions] of Object.entries(result.data)) merged[key] = [.../* @__PURE__ */ new Set([...merged[key] ?? [], ...actions])]; + acRoles[role2] = input.options.ac.newRole(merged); + } + } + if (input.useMemoryCache) acRoles = cacheAllRoles.get(input.organizationId) || acRoles; + cacheAllRoles.set(input.organizationId, acRoles); + return hasPermissionFn(input, acRoles); +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/package.mjs +var version2 = "1.6.2"; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/version.mjs +var PACKAGE_VERSION = version2; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/error-codes.mjs +init_error_codes(); +var ORGANIZATION_ERROR_CODES = defineErrorCodes({ + YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION: "You are not allowed to create a new organization", + YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS: "You have reached the maximum number of organizations", + ORGANIZATION_ALREADY_EXISTS: "Organization already exists", + ORGANIZATION_SLUG_ALREADY_TAKEN: "Organization slug already taken", + ORGANIZATION_NOT_FOUND: "Organization not found", + USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION: "User is not a member of the organization", + YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION: "You are not allowed to update this organization", + YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION: "You are not allowed to delete this organization", + NO_ACTIVE_ORGANIZATION: "No active organization", + USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION: "User is already a member of this organization", + MEMBER_NOT_FOUND: "Member not found", + ROLE_NOT_FOUND: "Role not found", + YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM: "You are not allowed to create a new team", + TEAM_ALREADY_EXISTS: "Team already exists", + TEAM_NOT_FOUND: "Team not found", + YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER: "You cannot leave the organization as the only owner", + YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER: "You cannot leave the organization without an owner", + YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER: "You are not allowed to delete this member", + YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION: "You are not allowed to invite users to this organization", + USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION: "User is already invited to this organization", + INVITATION_NOT_FOUND: "Invitation not found", + YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION: "You are not the recipient of the invitation", + EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION: "Email verification required before accepting or rejecting invitation", + YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION: "You are not allowed to cancel this invitation", + INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION: "Inviter is no longer a member of the organization", + YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE: "You are not allowed to invite a user with this role", + FAILED_TO_RETRIEVE_INVITATION: "Failed to retrieve invitation", + YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS: "You have reached the maximum number of teams", + UNABLE_TO_REMOVE_LAST_TEAM: "Unable to remove last team", + YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER: "You are not allowed to update this member", + ORGANIZATION_MEMBERSHIP_LIMIT_REACHED: "Organization membership limit reached", + YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION: "You are not allowed to create teams in this organization", + YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION: "You are not allowed to delete teams in this organization", + YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM: "You are not allowed to update this team", + YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM: "You are not allowed to delete this team", + INVITATION_LIMIT_REACHED: "Invitation limit reached", + TEAM_MEMBER_LIMIT_REACHED: "Team member limit reached", + USER_IS_NOT_A_MEMBER_OF_THE_TEAM: "User is not a member of the team", + YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM: "You are not allowed to list the members of this team", + YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM: "You do not have an active team", + YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER: "You are not allowed to create a new member", + YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER: "You are not allowed to remove a team member", + YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION: "You are not allowed to access this organization as an owner", + YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION: "You are not a member of this organization", + MISSING_AC_INSTANCE: "Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information", + YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE: "You must be in an organization to create a role", + YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE: "You are not allowed to create a role", + YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE: "You are not allowed to update a role", + YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE: "You are not allowed to delete a role", + YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE: "You are not allowed to read a role", + YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE: "You are not allowed to list a role", + YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE: "You are not allowed to get a role", + TOO_MANY_ROLES: "This organization has too many roles", + INVALID_RESOURCE: "The provided permission includes an invalid resource", + ROLE_NAME_IS_ALREADY_TAKEN: "That role name is already taken", + CANNOT_DELETE_A_PRE_DEFINED_ROLE: "Cannot delete a pre-defined role", + ROLE_IS_ASSIGNED_TO_MEMBERS: "Cannot delete a role that is assigned to members. Please reassign the members to a different role first" +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/shim.mjs +var shimContext = (originalObject, newContext) => { + const shimmedObj = {}; + for (const [key, value] of Object.entries(originalObject)) { + shimmedObj[key] = (ctx) => { + return value({ + ...ctx, + context: { + ...newContext, + ...ctx.context + } + }); + }; + shimmedObj[key].path = value.path; + shimmedObj[key].method = value.method; + shimmedObj[key].options = value.options; + shimmedObj[key].headers = value.headers; + } + return shimmedObj; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/call.mjs +var orgMiddleware = createAuthMiddleware(async () => { + return {}; +}); +var orgSessionMiddleware = createAuthMiddleware({ use: [sessionMiddleware] }, async (ctx) => { + return { session: ctx.context.session }; +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/to-zod.mjs +init_zod(); +function toZodSchema({ fields, isClientSide }) { + const zodFields = Object.keys(fields).reduce((acc, key) => { + const field = fields[key]; + if (!field) return acc; + if (isClientSide && field.input === false) return acc; + let schema3; + if (field.type === "json") schema3 = json ? json() : any(); + else if (field.type === "string[]" || field.type === "number[]") schema3 = array(field.type === "string[]" ? string2() : number2()); + else if (Array.isArray(field.type)) schema3 = any(); + else schema3 = zod_exports[field.type](); + if (field?.required === false) schema3 = schema3.optional(); + if (!isClientSide && field?.returned === false) return acc; + return { + ...acc, + [key]: schema3 + }; + }, {}); + return object(zodFields); +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-access-control.mjs +init_error2(); +init_zod(); +var normalizeRoleName = (role2) => role2.toLowerCase(); +var DEFAULT_MAXIMUM_ROLES_PER_ORGANIZATION = Number.POSITIVE_INFINITY; +var getAdditionalFields = (options, shouldBePartial = false) => { + const additionalFields = options?.schema?.organizationRole?.additionalFields || {}; + if (shouldBePartial) for (const key in additionalFields) additionalFields[key].required = false; + return { + additionalFieldsSchema: toZodSchema({ + fields: additionalFields, + isClientSide: true + }), + $AdditionalFields: {}, + $ReturnAdditionalFields: {} + }; +}; +var baseCreateOrgRoleSchema = object({ + organizationId: string2().optional().meta({ description: "The id of the organization to create the role in. If not provided, the user's active organization will be used." }), + role: string2().meta({ description: "The name of the role to create" }), + permission: record(string2(), array(string2())).meta({ description: "The permission to assign to the role" }) +}); +var createOrgRole = (options) => { + const { additionalFieldsSchema, $AdditionalFields, $ReturnAdditionalFields } = getAdditionalFields(options, false); + return createAuthEndpoint("/organization/create-role", { + method: "POST", + body: baseCreateOrgRoleSchema.safeExtend({ additionalFields: object({ ...additionalFieldsSchema.shape }).optional() }), + metadata: { $Infer: { body: {} } }, + requireHeaders: true, + use: [orgSessionMiddleware] + }, async (ctx) => { + const { session, user } = ctx.context.session; + let roleName = ctx.body.role; + const permission = ctx.body.permission; + const additionalFields = ctx.body.additionalFields; + const ac = options.ac; + if (!ac) { + ctx.context.logger.error(`[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.`, ` +Please refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`); + throw APIError2.from("NOT_IMPLEMENTED", ORGANIZATION_ERROR_CODES.MISSING_AC_INSTANCE); + } + const organizationId = ctx.body.organizationId ?? session.activeOrganizationId; + if (!organizationId) { + ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to create a role. Either set an active org id, or pass an organizationId in the request body.`); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE); + } + roleName = normalizeRoleName(roleName); + await checkIfRoleNameIsTakenByPreDefinedRole({ + role: roleName, + organizationId, + options, + ctx + }); + const member = await ctx.context.adapter.findOne({ + model: "member", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, { + field: "userId", + value: user.id, + operator: "eq", + connector: "AND" + }] + }); + if (!member) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to create a role.`, { + userId: user.id, + organizationId + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); + } + if (!await hasPermission({ + options, + organizationId, + permissions: { ac: ["create"] }, + role: member.role + }, ctx)) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to create a role. If this is unexpected, please make sure the role associated to that member has the "ac" resource with the "create" permission.`, { + userId: user.id, + organizationId, + role: member.role + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE); + } + const maximumRolesPerOrganization = typeof options.dynamicAccessControl?.maximumRolesPerOrganization === "function" ? await options.dynamicAccessControl.maximumRolesPerOrganization(organizationId) : options.dynamicAccessControl?.maximumRolesPerOrganization ?? DEFAULT_MAXIMUM_ROLES_PER_ORGANIZATION; + const rolesInDB = await ctx.context.adapter.count({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }] + }); + if (rolesInDB >= maximumRolesPerOrganization) { + ctx.context.logger.error(`[Dynamic Access Control] Failed to create a new role, the organization has too many roles. Maximum allowed roles is ${maximumRolesPerOrganization}.`, { + organizationId, + maximumRolesPerOrganization, + rolesInDB + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TOO_MANY_ROLES); + } + await checkForInvalidResources({ + ac, + ctx, + permission + }); + await checkIfMemberHasPermission({ + ctx, + member, + options, + organizationId, + permissionRequired: permission, + user, + action: "create" + }); + await checkIfRoleNameIsTakenByRoleInDB({ + ctx, + organizationId, + role: roleName + }); + const newRole = ac.newRole(permission); + const data = { + ...await ctx.context.adapter.create({ + model: "organizationRole", + data: { + createdAt: /* @__PURE__ */ new Date(), + organizationId, + permission: JSON.stringify(permission), + role: roleName, + ...additionalFields + } + }), + permission + }; + return ctx.json({ + success: true, + roleData: data, + statements: newRole.statements + }); + }); +}; +var deleteOrgRoleBodySchema = object({ organizationId: string2().optional().meta({ description: "The id of the organization to create the role in. If not provided, the user's active organization will be used." }) }).and(union([object({ roleName: string2().nonempty().meta({ description: "The name of the role to delete" }) }), object({ roleId: string2().nonempty().meta({ description: "The id of the role to delete" }) })])); +var deleteOrgRole = (options) => { + return createAuthEndpoint("/organization/delete-role", { + method: "POST", + body: deleteOrgRoleBodySchema, + requireHeaders: true, + use: [orgSessionMiddleware], + metadata: { $Infer: { body: {} } } + }, async (ctx) => { + const { session, user } = ctx.context.session; + const organizationId = ctx.body.organizationId ?? session.activeOrganizationId; + if (!organizationId) { + ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to delete a role. Either set an active org id, or pass an organizationId in the request body.`); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + } + const member = await ctx.context.adapter.findOne({ + model: "member", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, { + field: "userId", + value: user.id, + operator: "eq", + connector: "AND" + }] + }); + if (!member) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to delete a role.`, { + userId: user.id, + organizationId + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); + } + if (!await hasPermission({ + options, + organizationId, + permissions: { ac: ["delete"] }, + role: member.role + }, ctx)) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to delete a role. If this is unexpected, please make sure the role associated to that member has the "ac" resource with the "delete" permission.`, { + userId: user.id, + organizationId, + role: member.role + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE); + } + if (ctx.body.roleName) { + const roleName = ctx.body.roleName; + const defaultRoles3 = options.roles ? Object.keys(options.roles) : [ + "owner", + "admin", + "member" + ]; + if (defaultRoles3.includes(roleName)) { + ctx.context.logger.error(`[Dynamic Access Control] Cannot delete a pre-defined role.`, { + roleName, + organizationId, + defaultRoles: defaultRoles3 + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.CANNOT_DELETE_A_PRE_DEFINED_ROLE); + } + } + let condition; + if (ctx.body.roleName) condition = { + field: "role", + value: ctx.body.roleName, + operator: "eq", + connector: "AND" + }; + else if (ctx.body.roleId) condition = { + field: "id", + value: ctx.body.roleId, + operator: "eq", + connector: "AND" + }; + else { + ctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request body.`); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); + } + const existingRoleInDB = await ctx.context.adapter.findOne({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, condition] + }); + if (!existingRoleInDB) { + ctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, { + ..."roleName" in ctx.body ? { roleName: ctx.body.roleName } : { roleId: ctx.body.roleId }, + organizationId + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); + } + existingRoleInDB.permission = JSON.parse(existingRoleInDB.permission); + const roleToDelete = existingRoleInDB.role; + if ((await ctx.context.adapter.findMany({ + model: "member", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, { + field: "role", + value: roleToDelete, + operator: "contains" + }] + })).find((member2) => { + return member2.role.split(",").map((r) => r.trim()).includes(roleToDelete); + })) { + ctx.context.logger.error(`[Dynamic Access Control] Cannot delete a role that is assigned to members.`, { + role: existingRoleInDB.role, + organizationId + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_IS_ASSIGNED_TO_MEMBERS); + } + await ctx.context.adapter.delete({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, condition] + }); + return ctx.json({ success: true }); + }); +}; +var listOrgRolesQuerySchema = object({ organizationId: string2().optional().meta({ description: "The id of the organization to list roles for. If not provided, the user's active organization will be used." }) }).optional(); +var listOrgRoles = (options) => { + const { $ReturnAdditionalFields } = getAdditionalFields(options, false); + return createAuthEndpoint("/organization/list-roles", { + method: "GET", + requireHeaders: true, + use: [orgSessionMiddleware], + query: listOrgRolesQuerySchema + }, async (ctx) => { + const { session, user } = ctx.context.session; + const organizationId = ctx.query?.organizationId ?? session.activeOrganizationId; + if (!organizationId) { + ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to list roles. Either set an active org id, or pass an organizationId in the request query.`); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + } + const member = await ctx.context.adapter.findOne({ + model: "member", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, { + field: "userId", + value: user.id, + operator: "eq", + connector: "AND" + }] + }); + if (!member) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to list roles.`, { + userId: user.id, + organizationId + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); + } + if (!await hasPermission({ + options, + organizationId, + permissions: { ac: ["read"] }, + role: member.role + }, ctx)) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to list roles.`, { + userId: user.id, + organizationId, + role: member.role + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE); + } + let roles = await ctx.context.adapter.findMany({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }] + }); + roles = roles.map((x) => ({ + ...x, + permission: JSON.parse(x.permission) + })); + return ctx.json(roles); + }); +}; +var getOrgRoleQuerySchema = object({ organizationId: string2().optional().meta({ description: "The id of the organization to read a role for. If not provided, the user's active organization will be used." }) }).and(union([object({ roleName: string2().nonempty().meta({ description: "The name of the role to read" }) }), object({ roleId: string2().nonempty().meta({ description: "The id of the role to read" }) })])).optional(); +var getOrgRole = (options) => { + const { $ReturnAdditionalFields } = getAdditionalFields(options, false); + return createAuthEndpoint("/organization/get-role", { + method: "GET", + requireHeaders: true, + use: [orgSessionMiddleware], + query: getOrgRoleQuerySchema, + metadata: { $Infer: { query: {} } } + }, async (ctx) => { + const { session, user } = ctx.context.session; + const organizationId = ctx.query?.organizationId ?? session.activeOrganizationId; + if (!organizationId) { + ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to read a role. Either set an active org id, or pass an organizationId in the request query.`); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + } + const member = await ctx.context.adapter.findOne({ + model: "member", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, { + field: "userId", + value: user.id, + operator: "eq", + connector: "AND" + }] + }); + if (!member) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to read a role.`, { + userId: user.id, + organizationId + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); + } + if (!await hasPermission({ + options, + organizationId, + permissions: { ac: ["read"] }, + role: member.role + }, ctx)) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to read a role.`, { + userId: user.id, + organizationId, + role: member.role + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE); + } + let condition; + if (ctx.query.roleName) condition = { + field: "role", + value: ctx.query.roleName, + operator: "eq", + connector: "AND" + }; + else if (ctx.query.roleId) condition = { + field: "id", + value: ctx.query.roleId, + operator: "eq", + connector: "AND" + }; + else { + ctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request query.`); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); + } + const role2 = await ctx.context.adapter.findOne({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, condition] + }); + if (!role2) { + ctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, { + ..."roleName" in ctx.query ? { roleName: ctx.query.roleName } : { roleId: ctx.query.roleId }, + organizationId + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); + } + role2.permission = JSON.parse(role2.permission); + return ctx.json(role2); + }); +}; +var roleNameOrIdSchema = union([object({ roleName: string2().nonempty().meta({ description: "The name of the role to update" }) }), object({ roleId: string2().nonempty().meta({ description: "The id of the role to update" }) })]); +var updateOrgRole = (options) => { + const { additionalFieldsSchema, $AdditionalFields, $ReturnAdditionalFields } = getAdditionalFields(options, true); + return createAuthEndpoint("/organization/update-role", { + method: "POST", + body: object({ + organizationId: string2().optional().meta({ description: "The id of the organization to update the role in. If not provided, the user's active organization will be used." }), + data: object({ + permission: record(string2(), array(string2())).optional().meta({ description: "The permission to update the role with" }), + roleName: string2().optional().meta({ description: "The name of the role to update" }), + ...additionalFieldsSchema.shape + }) + }).and(roleNameOrIdSchema), + metadata: { $Infer: { body: {} } }, + requireHeaders: true, + use: [orgSessionMiddleware] + }, async (ctx) => { + const { session, user } = ctx.context.session; + const ac = options.ac; + if (!ac) { + ctx.context.logger.error(`[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.`, ` +Please refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`); + throw APIError2.from("NOT_IMPLEMENTED", ORGANIZATION_ERROR_CODES.MISSING_AC_INSTANCE); + } + const organizationId = ctx.body.organizationId ?? session.activeOrganizationId; + if (!organizationId) { + ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to update a role. Either set an active org id, or pass an organizationId in the request body.`); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + } + const member = await ctx.context.adapter.findOne({ + model: "member", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, { + field: "userId", + value: user.id, + operator: "eq", + connector: "AND" + }] + }); + if (!member) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to update a role.`, { + userId: user.id, + organizationId + }); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); + } + if (!await hasPermission({ + options, + organizationId, + role: member.role, + permissions: { ac: ["update"] } + }, ctx)) { + ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to update a role.`); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE); + } + let condition; + if (ctx.body.roleName) condition = { + field: "role", + value: ctx.body.roleName, + operator: "eq", + connector: "AND" + }; + else if (ctx.body.roleId) condition = { + field: "id", + value: ctx.body.roleId, + operator: "eq", + connector: "AND" + }; + else { + ctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request body.`); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); + } + const role2 = await ctx.context.adapter.findOne({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, condition] + }); + if (!role2) { + ctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, { + ..."roleName" in ctx.body ? { roleName: ctx.body.roleName } : { roleId: ctx.body.roleId }, + organizationId + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); + } + role2.permission = role2.permission ? JSON.parse(role2.permission) : void 0; + const { permission: _, roleName: __, ...additionalFields } = ctx.body.data; + const updateData = { ...additionalFields }; + if (ctx.body.data.permission) { + const newPermission = ctx.body.data.permission; + await checkForInvalidResources({ + ac, + ctx, + permission: newPermission + }); + await checkIfMemberHasPermission({ + ctx, + member, + options, + organizationId, + permissionRequired: newPermission, + user, + action: "update" + }); + updateData.permission = newPermission; + } + if (ctx.body.data.roleName) { + let newRoleName = ctx.body.data.roleName; + newRoleName = normalizeRoleName(newRoleName); + await checkIfRoleNameIsTakenByPreDefinedRole({ + role: newRoleName, + organizationId, + options, + ctx + }); + await checkIfRoleNameIsTakenByRoleInDB({ + role: newRoleName, + organizationId, + ctx + }); + updateData.role = newRoleName; + } + const update = { + ...updateData, + ...updateData.permission ? { permission: JSON.stringify(updateData.permission) } : {} + }; + await ctx.context.adapter.update({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, condition], + update + }); + return ctx.json({ + success: true, + roleData: { + ...role2, + ...update, + permission: updateData.permission || role2.permission || null + } + }); + }); +}; +async function checkForInvalidResources({ ac, ctx, permission }) { + const validResources = Object.keys(ac.statements); + const providedResources = Object.keys(permission); + if (providedResources.some((r) => !validResources.includes(r))) { + ctx.context.logger.error(`[Dynamic Access Control] The provided permission includes an invalid resource.`, { + providedResources, + validResources + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVALID_RESOURCE); + } +} +async function checkIfMemberHasPermission({ ctx, permissionRequired: permission, options, organizationId, member, user, action }) { + const hasNecessaryPermissions = []; + const permissionEntries = Object.entries(permission); + for await (const [resource, permissions] of permissionEntries) for await (const perm of permissions) hasNecessaryPermissions.push({ + resource: { [resource]: [perm] }, + hasPermission: await hasPermission({ + options, + organizationId, + permissions: { [resource]: [perm] }, + useMemoryCache: true, + role: member.role + }, ctx) + }); + const missingPermissions = hasNecessaryPermissions.filter((x) => x.hasPermission === false).map((x) => { + const key = Object.keys(x.resource)[0]; + return `${key}:${x.resource[key][0]}`; + }); + if (missingPermissions.length > 0) { + ctx.context.logger.error(`[Dynamic Access Control] The user is missing permissions necessary to ${action} a role with those set of permissions. +`, { + userId: user.id, + organizationId, + role: member.role, + missingPermissions + }); + let error49; + if (action === "create") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE; + else if (action === "update") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE; + else if (action === "delete") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE; + else if (action === "read") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE; + else if (action === "list") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE; + else error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE; + throw APIError2.fromStatus("FORBIDDEN", { + message: error49.message, + code: error49.code, + missingPermissions + }); + } +} +async function checkIfRoleNameIsTakenByPreDefinedRole({ options, organizationId, role: role2, ctx }) { + const defaultRoles3 = options.roles ? Object.keys(options.roles) : [ + "owner", + "admin", + "member" + ]; + if (defaultRoles3.includes(role2)) { + ctx.context.logger.error(`[Dynamic Access Control] The role name "${role2}" is already taken by a pre-defined role.`, { + role: role2, + organizationId, + defaultRoles: defaultRoles3 + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NAME_IS_ALREADY_TAKEN); + } +} +async function checkIfRoleNameIsTakenByRoleInDB({ organizationId, role: role2, ctx }) { + if (await ctx.context.adapter.findOne({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId, + operator: "eq", + connector: "AND" + }, { + field: "role", + value: role2, + operator: "eq", + connector: "AND" + }] + })) { + ctx.context.logger.error(`[Dynamic Access Control] The role name "${role2}" is already taken by a role in the database.`, { + role: role2, + organizationId + }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NAME_IS_ALREADY_TAKEN); + } +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-invites.mjs +init_error2(); +init_zod(); +var baseInvitationSchema = object({ + email: string2().meta({ description: "The email address of the user to invite" }), + role: union([string2().meta({ description: "The role to assign to the user" }), array(string2().meta({ description: "The roles to assign to the user" }))]).meta({ description: 'The role(s) to assign to the user. It can be `admin`, `member`, owner. Eg: "member"' }), + organizationId: string2().meta({ description: "The organization ID to invite the user to" }).optional(), + resend: boolean2().meta({ description: "Resend the invitation email, if the user is already invited. Eg: true" }).optional(), + teamId: union([string2().meta({ description: "The team ID to invite the user to" }).optional(), array(string2()).meta({ description: "The team IDs to invite the user to" }).optional()]) +}); +var createInvitation = (option) => { + const additionalFieldsSchema = toZodSchema({ + fields: option?.schema?.invitation?.additionalFields || {}, + isClientSide: true + }); + return createAuthEndpoint("/organization/invite-member", { + method: "POST", + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware], + body: object({ + ...baseInvitationSchema.shape, + ...additionalFieldsSchema.shape + }), + metadata: { + $Infer: { body: {} }, + openapi: { + operationId: "createOrganizationInvitation", + description: "Create an invitation to an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + id: { type: "string" }, + email: { type: "string" }, + role: { type: "string" }, + organizationId: { type: "string" }, + inviterId: { type: "string" }, + status: { type: "string" }, + expiresAt: { type: "string" }, + createdAt: { type: "string" } + }, + required: [ + "id", + "email", + "role", + "organizationId", + "inviterId", + "status", + "expiresAt", + "createdAt" + ] + } } } + } } + } + } + }, async (ctx) => { + const session = ctx.context.session; + const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const email3 = ctx.body.email.toLowerCase(); + if (!email2().safeParse(email3).success) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_EMAIL); + const adapter = getOrgAdapter(ctx.context, option); + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + if (!await hasPermission({ + role: member.role, + options: ctx.context.orgOptions, + permissions: { invitation: ["create"] }, + organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION); + const creatorRole = ctx.context.orgOptions.creatorRole || "owner"; + const roles = parseRoles(ctx.body.role); + const rolesArray = roles.split(",").map((r) => r.trim()).filter(Boolean); + const defaults = Object.keys(defaultRoles); + const customRoles = Object.keys(ctx.context.orgOptions.roles || {}); + const validStaticRoles = /* @__PURE__ */ new Set([...defaults, ...customRoles]); + const unknownRoles = rolesArray.filter((role2) => !validStaticRoles.has(role2)); + if (unknownRoles.length > 0) if (ctx.context.orgOptions.dynamicAccessControl?.enabled) { + const foundRoleNames = (await ctx.context.adapter.findMany({ + model: "organizationRole", + where: [{ + field: "organizationId", + value: organizationId + }, { + field: "role", + value: unknownRoles, + operator: "in" + }] + })).map((r) => r.role); + const stillInvalid = unknownRoles.filter((r) => !foundRoleNames.includes(r)); + if (stillInvalid.length > 0) throw new APIError2("BAD_REQUEST", { message: `${ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND}: ${stillInvalid.join(", ")}` }); + } else throw new APIError2("BAD_REQUEST", { message: `${ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND}: ${unknownRoles.join(", ")}` }); + if (!member.role.split(",").map((r) => r.trim()).includes(creatorRole) && roles.split(",").includes(creatorRole)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE); + if (await adapter.findMemberByEmail({ + email: email3, + organizationId + })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION); + const alreadyInvited = await adapter.findPendingInvitation({ + email: email3, + organizationId + }); + if (alreadyInvited.length && !ctx.body.resend) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION); + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + if (alreadyInvited.length && ctx.body.resend) { + const existingInvitation = alreadyInvited[0]; + const newExpiresAt = getDate(ctx.context.orgOptions.invitationExpiresIn || 3600 * 48, "sec"); + await ctx.context.adapter.update({ + model: "invitation", + where: [{ + field: "id", + value: existingInvitation.id + }], + update: { expiresAt: newExpiresAt } + }); + const updatedInvitation = { + ...existingInvitation, + expiresAt: newExpiresAt + }; + if (ctx.context.orgOptions.sendInvitationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.orgOptions.sendInvitationEmail({ + id: updatedInvitation.id, + role: updatedInvitation.role, + email: updatedInvitation.email.toLowerCase(), + organization: organization2, + inviter: { + ...member, + user: session.user + }, + invitation: updatedInvitation + }, ctx.request)); + return ctx.json(updatedInvitation); + } + if (alreadyInvited.length && ctx.context.orgOptions.cancelPendingInvitationsOnReInvite) await adapter.updateInvitation({ + invitationId: alreadyInvited[0].id, + status: "canceled" + }); + const invitationLimit = typeof ctx.context.orgOptions.invitationLimit === "function" ? await ctx.context.orgOptions.invitationLimit({ + user: session.user, + organization: organization2, + member + }, ctx.context) : ctx.context.orgOptions.invitationLimit ?? 100; + if ((await adapter.findPendingInvitations({ organizationId })).length >= invitationLimit) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.INVITATION_LIMIT_REACHED); + if (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== "undefined" && "teamId" in ctx.body && ctx.body.teamId) { + const teamIds2 = typeof ctx.body.teamId === "string" ? [ctx.body.teamId] : ctx.body.teamId; + for (const teamId of teamIds2) { + const team = await adapter.findTeamById({ + teamId, + organizationId, + includeTeamMembers: true + }); + if (!team) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); + const maximumMembersPerTeam = typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === "function" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({ + teamId, + session, + organizationId + }) : ctx.context.orgOptions.teams.maximumMembersPerTeam; + if (team.members.length >= maximumMembersPerTeam) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED); + } + } + const teamIds = "teamId" in ctx.body ? typeof ctx.body.teamId === "string" ? [ctx.body.teamId] : ctx.body.teamId ?? [] : []; + const { email: _, role: __, organizationId: ___, resend: ____, ...additionalFields } = ctx.body; + let invitationData = { + role: roles, + email: email3, + organizationId, + teamIds, + ...additionalFields ? additionalFields : {} + }; + if (option?.organizationHooks?.beforeCreateInvitation) { + const response = await option?.organizationHooks.beforeCreateInvitation({ + invitation: { + ...invitationData, + inviterId: session.user.id, + teamId: teamIds.length > 0 ? teamIds[0] : void 0 + }, + inviter: session.user, + organization: organization2 + }); + if (response && typeof response === "object" && "data" in response) invitationData = { + ...invitationData, + ...response.data + }; + } + const invitation = await adapter.createInvitation({ + invitation: invitationData, + user: session.user + }); + if (ctx.context.orgOptions.sendInvitationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.orgOptions.sendInvitationEmail({ + id: invitation.id, + role: invitation.role, + email: invitation.email.toLowerCase(), + organization: organization2, + inviter: { + ...member, + user: session.user + }, + invitation + }, ctx.request)); + if (option?.organizationHooks?.afterCreateInvitation) await option?.organizationHooks.afterCreateInvitation({ + invitation, + inviter: session.user, + organization: organization2 + }); + return ctx.json(invitation); + }); +}; +var acceptInvitationBodySchema = object({ invitationId: string2().meta({ description: "The ID of the invitation to accept" }) }); +var acceptInvitation = (options) => createAuthEndpoint("/organization/accept-invitation", { + method: "POST", + body: acceptInvitationBodySchema, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware], + metadata: { openapi: { + description: "Accept an invitation to an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + invitation: { type: "object" }, + member: { type: "object" } + } + } } } + } } + } } +}, async (ctx) => { + const session = ctx.context.session; + const adapter = getOrgAdapter(ctx.context, options); + const invitation = await adapter.findInvitationById(ctx.body.invitationId); + if (!invitation || invitation.expiresAt < /* @__PURE__ */ new Date() || invitation.status !== "pending") throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND); + if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION); + if (ctx.context.orgOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION); + const membershipLimit = ctx.context.orgOptions?.membershipLimit || 100; + const membersCount = await adapter.countMembers({ organizationId: invitation.organizationId }); + const organization2 = await adapter.findOrganizationById(invitation.organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + if (membersCount >= (typeof membershipLimit === "number" ? membershipLimit : await membershipLimit(session.user, organization2))) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED); + if (options?.organizationHooks?.beforeAcceptInvitation) await options?.organizationHooks.beforeAcceptInvitation({ + invitation, + user: session.user, + organization: organization2 + }); + const acceptedI = await adapter.updateInvitation({ + invitationId: ctx.body.invitationId, + status: "accepted" + }); + if (!acceptedI) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.FAILED_TO_RETRIEVE_INVITATION); + if (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && "teamId" in acceptedI && acceptedI.teamId) { + const teamIds = acceptedI.teamId.split(","); + const onlyOne = teamIds.length === 1; + for (const teamId of teamIds) { + await adapter.findOrCreateTeamMember({ + teamId, + userId: session.user.id + }); + if (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== "undefined") { + if (await adapter.countTeamMembers({ teamId }) >= (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === "function" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({ + teamId, + session, + organizationId: invitation.organizationId + }) : ctx.context.orgOptions.teams.maximumMembersPerTeam)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED); + } + } + if (onlyOne) { + const teamId = teamIds[0]; + await setSessionCookie(ctx, { + session: await adapter.setActiveTeam(session.session.token, teamId, ctx), + user: session.user + }); + } + } + const member = await adapter.createMember({ + organizationId: invitation.organizationId, + userId: session.user.id, + role: invitation.role, + createdAt: /* @__PURE__ */ new Date() + }); + await adapter.setActiveOrganization(session.session.token, invitation.organizationId, ctx); + if (options?.organizationHooks?.afterAcceptInvitation) await options?.organizationHooks.afterAcceptInvitation({ + invitation: acceptedI, + member, + user: session.user, + organization: organization2 + }); + return ctx.json({ + invitation: acceptedI, + member + }); +}); +var rejectInvitationBodySchema = object({ invitationId: string2().meta({ description: "The ID of the invitation to reject" }) }); +var rejectInvitation = (options) => createAuthEndpoint("/organization/reject-invitation", { + method: "POST", + body: rejectInvitationBodySchema, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware], + metadata: { openapi: { + description: "Reject an invitation to an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + invitation: { type: "object" }, + member: { + type: "object", + nullable: true + } + } + } } } + } } + } } +}, async (ctx) => { + const session = ctx.context.session; + const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); + const invitation = await adapter.findInvitationById(ctx.body.invitationId); + if (!invitation || invitation.status !== "pending") throw APIError2.from("BAD_REQUEST", { + message: "Invitation not found!", + code: "INVITATION_NOT_FOUND" + }); + if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION); + if (ctx.context.orgOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION); + const organization2 = await adapter.findOrganizationById(invitation.organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + if (options?.organizationHooks?.beforeRejectInvitation) await options?.organizationHooks.beforeRejectInvitation({ + invitation, + user: session.user, + organization: organization2 + }); + const rejectedI = await adapter.updateInvitation({ + invitationId: ctx.body.invitationId, + status: "rejected" + }); + if (options?.organizationHooks?.afterRejectInvitation) await options?.organizationHooks.afterRejectInvitation({ + invitation: rejectedI || invitation, + user: session.user, + organization: organization2 + }); + return ctx.json({ + invitation: rejectedI, + member: null + }); +}); +var cancelInvitationBodySchema = object({ invitationId: string2().meta({ description: "The ID of the invitation to cancel" }) }); +var cancelInvitation = (options) => createAuthEndpoint("/organization/cancel-invitation", { + method: "POST", + body: cancelInvitationBodySchema, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware], + openapi: { + operationId: "cancelOrganizationInvitation", + description: "Cancel an invitation to an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { invitation: { type: "object" } } + } } } + } } + } +}, async (ctx) => { + const session = ctx.context.session; + const adapter = getOrgAdapter(ctx.context, options); + const invitation = await adapter.findInvitationById(ctx.body.invitationId); + if (!invitation) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND); + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId: invitation.organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + if (!await hasPermission({ + role: member.role, + options: ctx.context.orgOptions, + permissions: { invitation: ["cancel"] }, + organizationId: invitation.organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION); + const organization2 = await adapter.findOrganizationById(invitation.organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + if (options?.organizationHooks?.beforeCancelInvitation) await options?.organizationHooks.beforeCancelInvitation({ + invitation, + cancelledBy: session.user, + organization: organization2 + }); + const canceledI = await adapter.updateInvitation({ + invitationId: ctx.body.invitationId, + status: "canceled" + }); + if (options?.organizationHooks?.afterCancelInvitation) await options?.organizationHooks.afterCancelInvitation({ + invitation: canceledI || invitation, + cancelledBy: session.user, + organization: organization2 + }); + return ctx.json(canceledI); +}); +var getInvitationQuerySchema = object({ id: string2().meta({ description: "The ID of the invitation to get" }) }); +var getInvitation = (options) => createAuthEndpoint("/organization/get-invitation", { + method: "GET", + use: [orgMiddleware], + requireHeaders: true, + query: getInvitationQuerySchema, + metadata: { openapi: { + description: "Get an invitation by ID", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + id: { type: "string" }, + email: { type: "string" }, + role: { type: "string" }, + organizationId: { type: "string" }, + inviterId: { type: "string" }, + status: { type: "string" }, + expiresAt: { type: "string" }, + organizationName: { type: "string" }, + organizationSlug: { type: "string" }, + inviterEmail: { type: "string" } + }, + required: [ + "id", + "email", + "role", + "organizationId", + "inviterId", + "status", + "expiresAt", + "organizationName", + "organizationSlug", + "inviterEmail" + ] + } } } + } } + } } +}, async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session) throw APIError2.fromStatus("UNAUTHORIZED", { message: "Not authenticated" }); + const adapter = getOrgAdapter(ctx.context, options); + const invitation = await adapter.findInvitationById(ctx.query.id); + if (!invitation || invitation.status !== "pending" || invitation.expiresAt < /* @__PURE__ */ new Date()) throw APIError2.fromStatus("BAD_REQUEST", { message: "Invitation not found!" }); + if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION); + const organization2 = await adapter.findOrganizationById(invitation.organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const member = await adapter.findMemberByOrgId({ + userId: invitation.inviterId, + organizationId: invitation.organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION); + return ctx.json({ + ...invitation, + organizationName: organization2.name, + organizationSlug: organization2.slug, + inviterEmail: member.user.email + }); +}); +var listInvitationQuerySchema = object({ organizationId: string2().meta({ description: "The ID of the organization to list invitations for" }).optional() }).optional(); +var listInvitations = (options) => createAuthEndpoint("/organization/list-invitations", { + method: "GET", + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware], + query: listInvitationQuerySchema +}, async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session) throw APIError2.fromStatus("UNAUTHORIZED", { message: "Not authenticated" }); + const orgId = ctx.query?.organizationId || session.session.activeOrganizationId; + if (!orgId) throw APIError2.fromStatus("BAD_REQUEST", { message: "Organization ID is required" }); + const adapter = getOrgAdapter(ctx.context, options); + if (!await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId: orgId + })) throw APIError2.fromStatus("FORBIDDEN", { message: "You are not a member of this organization" }); + const invitations = await adapter.listInvitations({ organizationId: orgId }); + return ctx.json(invitations); +}); +var listUserInvitations = (options) => createAuthEndpoint("/organization/list-user-invitations", { + method: "GET", + use: [orgMiddleware], + query: object({ email: string2().meta({ description: "The email of the user to list invitations for. This only works for server side API calls." }).optional() }).optional(), + metadata: { openapi: { + description: "List all invitations a user has received", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "array", + items: { + type: "object", + properties: { + id: { type: "string" }, + email: { type: "string" }, + role: { type: "string" }, + organizationId: { type: "string" }, + organizationName: { type: "string" }, + inviterId: { + type: "string", + description: "The ID of the user who created the invitation" + }, + teamId: { + type: "string", + description: "The ID of the team associated with the invitation", + nullable: true + }, + status: { type: "string" }, + expiresAt: { type: "string" }, + createdAt: { type: "string" } + }, + required: [ + "id", + "email", + "role", + "organizationId", + "organizationName", + "inviterId", + "status", + "expiresAt", + "createdAt" + ] + } + } } } + } } + } } +}, async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (ctx.request && ctx.query?.email) throw APIError2.fromStatus("BAD_REQUEST", { message: "User email cannot be passed for client side API calls." }); + const userEmail = session?.user.email || ctx.query?.email; + if (!userEmail) throw APIError2.fromStatus("BAD_REQUEST", { message: "Missing session headers, or email query parameter." }); + const pendingInvitations = (await getOrgAdapter(ctx.context, options).listUserInvitations(userEmail)).filter((inv) => inv.status === "pending"); + return ctx.json(pendingInvitations); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-members.mjs +init_error2(); +init_adapter(); +init_zod(); +var baseMemberSchema = object({ + userId: coerce_exports.string().meta({ description: 'The user Id which represents the user to be added as a member. If `null` is provided, then it\'s expected to provide session headers. Eg: "user-id"' }), + role: union([string2(), array(string2())]).meta({ description: 'The role(s) to assign to the new member. Eg: ["admin", "sale"]' }), + organizationId: string2().meta({ description: `An optional organization ID to pass. If not provided, will default to the user's active organization. Eg: "org-id"` }).optional(), + teamId: string2().meta({ description: 'An optional team ID to add the member to. Eg: "team-id"' }).optional() +}); +var addMember = (option) => { + const additionalFieldsSchema = toZodSchema({ + fields: option?.schema?.member?.additionalFields || {}, + isClientSide: true + }); + return createAuthEndpoint({ + method: "POST", + body: object({ + ...baseMemberSchema.shape, + ...additionalFieldsSchema.shape + }), + use: [orgMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + operationId: "addOrganizationMember", + description: "Add a member to an organization" + } + } + }, async (ctx) => { + const session = ctx.body.userId ? await getSessionFromCtx(ctx).catch((e) => null) : null; + const orgId = ctx.body.organizationId || session?.session.activeOrganizationId; + if (!orgId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const teamId = "teamId" in ctx.body ? ctx.body.teamId : void 0; + if (teamId && !ctx.context.orgOptions.teams?.enabled) { + ctx.context.logger.error("Teams are not enabled"); + throw APIError2.fromStatus("BAD_REQUEST", { message: "Teams are not enabled" }); + } + const adapter = getOrgAdapter(ctx.context, option); + const user = await ctx.context.internalAdapter.findUserById(ctx.body.userId); + if (!user) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.USER_NOT_FOUND); + if (await adapter.findMemberByEmail({ + email: user.email, + organizationId: orgId + })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION); + if (teamId) { + const team = await adapter.findTeamById({ + teamId, + organizationId: orgId + }); + if (!team || team.organizationId !== orgId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); + } + const membershipLimit = ctx.context.orgOptions?.membershipLimit || 100; + const count = await adapter.countMembers({ organizationId: orgId }); + const organization2 = await adapter.findOrganizationById(orgId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + if (count >= (typeof membershipLimit === "number" ? membershipLimit : await membershipLimit(user, organization2))) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED); + const { role: _, userId: __, organizationId: ___, ...additionalFields } = ctx.body; + let memberData = { + organizationId: orgId, + userId: user.id, + role: parseRoles(ctx.body.role), + createdAt: /* @__PURE__ */ new Date(), + ...additionalFields ? additionalFields : {} + }; + if (option?.organizationHooks?.beforeAddMember) { + const response = await option?.organizationHooks.beforeAddMember({ + member: { + userId: user.id, + organizationId: orgId, + role: parseRoles(ctx.body.role), + ...additionalFields + }, + user, + organization: organization2 + }); + if (response && typeof response === "object" && "data" in response) memberData = { + ...memberData, + ...response.data + }; + } + const createdMember = await adapter.createMember(memberData); + if (teamId) await adapter.findOrCreateTeamMember({ + userId: user.id, + teamId + }); + if (option?.organizationHooks?.afterAddMember) await option?.organizationHooks.afterAddMember({ + member: createdMember, + user, + organization: organization2 + }); + return ctx.json(createdMember); + }); +}; +var removeMemberBodySchema = object({ + memberIdOrEmail: string2().meta({ description: "The ID or email of the member to remove" }), + organizationId: string2().meta({ description: 'The ID of the organization to remove the member from. If not provided, the active organization will be used. Eg: "org-id"' }).optional() +}); +var removeMember = (options) => createAuthEndpoint("/organization/remove-member", { + method: "POST", + body: removeMemberBodySchema, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware], + metadata: { openapi: { + description: "Remove a member from an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { member: { + type: "object", + properties: { + id: { type: "string" }, + userId: { type: "string" }, + organizationId: { type: "string" }, + role: { type: "string" } + }, + required: [ + "id", + "userId", + "organizationId", + "role" + ] + } }, + required: ["member"] + } } } + } } + } } +}, async (ctx) => { + const session = ctx.context.session; + const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const adapter = getOrgAdapter(ctx.context, options); + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + let toBeRemovedMember = null; + if (ctx.body.memberIdOrEmail.includes("@")) toBeRemovedMember = await adapter.findMemberByEmail({ + email: ctx.body.memberIdOrEmail, + organizationId + }); + else { + const result = await adapter.findMemberById(ctx.body.memberIdOrEmail); + if (!result) toBeRemovedMember = null; + else { + const { user: _user, ...member2 } = result; + toBeRemovedMember = member2; + } + } + if (!toBeRemovedMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + const roles = toBeRemovedMember.role.split(","); + const creatorRole = ctx.context.orgOptions?.creatorRole || "owner"; + if (roles.includes(creatorRole)) { + if (!member.role.split(",").map((r) => r.trim()).includes(creatorRole)) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER); + const { members } = await adapter.listMembers({ organizationId }); + if (members.filter((member2) => { + return member2.role.split(",").includes(creatorRole); + }).length <= 1) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER); + } + if (!await hasPermission({ + role: member.role, + options: ctx.context.orgOptions, + permissions: { member: ["delete"] }, + organizationId + }, ctx)) throw APIError2.from("UNAUTHORIZED", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER); + if (toBeRemovedMember?.organizationId !== organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const userBeingRemoved = await ctx.context.internalAdapter.findUserById(toBeRemovedMember.userId); + if (!userBeingRemoved) throw APIError2.fromStatus("BAD_REQUEST", { message: "User not found" }); + if (options?.organizationHooks?.beforeRemoveMember) await options?.organizationHooks.beforeRemoveMember({ + member: toBeRemovedMember, + user: userBeingRemoved, + organization: organization2 + }); + await adapter.deleteMember({ + memberId: toBeRemovedMember.id, + organizationId, + userId: toBeRemovedMember.userId + }); + if (session.user.id === toBeRemovedMember.userId && session.session.activeOrganizationId === toBeRemovedMember.organizationId) await adapter.setActiveOrganization(session.session.token, null, ctx); + if (options?.organizationHooks?.afterRemoveMember) await options?.organizationHooks.afterRemoveMember({ + member: toBeRemovedMember, + user: userBeingRemoved, + organization: organization2 + }); + return ctx.json({ member: toBeRemovedMember }); +}); +var updateMemberRoleBodySchema = object({ + role: union([string2(), array(string2())]).meta({ description: 'The new role to be applied. This can be a string or array of strings representing the roles. Eg: ["admin", "sale"]' }), + memberId: string2().meta({ description: 'The member id to apply the role update to. Eg: "member-id"' }), + organizationId: string2().meta({ description: 'An optional organization ID which the member is a part of to apply the role update. If not provided, you must provide session headers to get the active organization. Eg: "organization-id"' }).optional() +}); +var updateMemberRole = (option) => createAuthEndpoint("/organization/update-member-role", { + method: "POST", + body: updateMemberRoleBodySchema, + use: [orgMiddleware, orgSessionMiddleware], + requireHeaders: true, + metadata: { + $Infer: { body: {} }, + openapi: { + operationId: "updateOrganizationMemberRole", + description: "Update the role of a member in an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { member: { + type: "object", + properties: { + id: { type: "string" }, + userId: { type: "string" }, + organizationId: { type: "string" }, + role: { type: "string" } + }, + required: [ + "id", + "userId", + "organizationId", + "role" + ] + } }, + required: ["member"] + } } } + } } + } + } +}, async (ctx) => { + const session = ctx.context.session; + if (!ctx.body.role) throw APIError2.fromStatus("BAD_REQUEST"); + const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); + const roleToSet = Array.isArray(ctx.body.role) ? ctx.body.role : ctx.body.role ? [ctx.body.role] : []; + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + const toBeUpdatedMember = member.id !== ctx.body.memberId ? await adapter.findMemberById(ctx.body.memberId) : member; + if (!toBeUpdatedMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + if (!(toBeUpdatedMember.organizationId === organizationId)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER); + const creatorRole = ctx.context.orgOptions?.creatorRole || "owner"; + const updatingMemberRoles = member.role.split(","); + const isUpdatingCreator = toBeUpdatedMember.role.split(",").includes(creatorRole); + const updaterIsCreator = updatingMemberRoles.includes(creatorRole); + const isSettingCreatorRole = roleToSet.includes(creatorRole); + const memberIsUpdatingThemselves = member.id === toBeUpdatedMember.id; + if (isUpdatingCreator && !updaterIsCreator || isSettingCreatorRole && !updaterIsCreator) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER); + if (updaterIsCreator && memberIsUpdatingThemselves) { + if ((await ctx.context.adapter.findMany({ + model: "member", + where: [{ + field: "organizationId", + value: organizationId + }] + })).filter((member2) => { + return member2.role.split(",").includes(creatorRole); + }).length <= 1 && !isSettingCreatorRole) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER); + } + if (!await hasPermission({ + role: member.role, + options: ctx.context.orgOptions, + permissions: { member: ["update"] }, + allowCreatorAllPermissions: true, + organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER); + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const userBeingUpdated = await ctx.context.internalAdapter.findUserById(toBeUpdatedMember.userId); + if (!userBeingUpdated) throw APIError2.fromStatus("BAD_REQUEST", { message: "User not found" }); + const previousRole = toBeUpdatedMember.role; + const newRole = parseRoles(ctx.body.role); + if (option?.organizationHooks?.beforeUpdateMemberRole) { + const response = await option?.organizationHooks.beforeUpdateMemberRole({ + member: toBeUpdatedMember, + newRole, + user: userBeingUpdated, + organization: organization2 + }); + if (response && typeof response === "object" && "data" in response) { + const updatedMember2 = await adapter.updateMember(ctx.body.memberId, response.data.role || newRole); + if (!updatedMember2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + if (option?.organizationHooks?.afterUpdateMemberRole) await option?.organizationHooks.afterUpdateMemberRole({ + member: updatedMember2, + previousRole, + user: userBeingUpdated, + organization: organization2 + }); + return ctx.json(updatedMember2); + } + } + const updatedMember = await adapter.updateMember(ctx.body.memberId, newRole); + if (!updatedMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + if (option?.organizationHooks?.afterUpdateMemberRole) await option?.organizationHooks.afterUpdateMemberRole({ + member: updatedMember, + previousRole, + user: userBeingUpdated, + organization: organization2 + }); + return ctx.json(updatedMember); +}); +var getActiveMember = (options) => createAuthEndpoint("/organization/get-active-member", { + method: "GET", + use: [orgMiddleware, orgSessionMiddleware], + requireHeaders: true, + metadata: { openapi: { + description: "Get the member details of the active organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + id: { type: "string" }, + userId: { type: "string" }, + organizationId: { type: "string" }, + role: { type: "string" } + }, + required: [ + "id", + "userId", + "organizationId", + "role" + ] + } } } + } } + } } +}, async (ctx) => { + const session = ctx.context.session; + const organizationId = session.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const member = await getOrgAdapter(ctx.context, options).findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + return ctx.json(member); +}); +var leaveOrganizationBodySchema = object({ organizationId: string2().meta({ description: 'The organization Id for the member to leave. Eg: "organization-id"' }) }); +var leaveOrganization = (options) => createAuthEndpoint("/organization/leave", { + method: "POST", + body: leaveOrganizationBodySchema, + requireHeaders: true, + use: [sessionMiddleware, orgMiddleware] +}, async (ctx) => { + const session = ctx.context.session; + const adapter = getOrgAdapter(ctx.context, options); + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId: ctx.body.organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); + const creatorRole = ctx.context.orgOptions?.creatorRole || "owner"; + if (member.role.split(",").includes(creatorRole)) { + if ((await ctx.context.adapter.findMany({ + model: "member", + where: [{ + field: "organizationId", + value: ctx.body.organizationId + }] + })).filter((member2) => member2.role.split(",").includes(creatorRole)).length <= 1) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER); + } + await adapter.deleteMember({ + memberId: member.id, + organizationId: ctx.body.organizationId, + userId: session.user.id + }); + if (session.session.activeOrganizationId === ctx.body.organizationId) await adapter.setActiveOrganization(session.session.token, null, ctx); + return ctx.json(member); +}); +var listMembers = (options) => createAuthEndpoint("/organization/list-members", { + method: "GET", + query: object({ + limit: string2().meta({ description: "The number of users to return" }).or(number2()).optional(), + offset: string2().meta({ description: "The offset to start from" }).or(number2()).optional(), + sortBy: string2().meta({ description: "The field to sort by" }).optional(), + sortDirection: _enum2(["asc", "desc"]).meta({ description: "The direction to sort by" }).optional(), + filterField: string2().meta({ description: "The field to filter by" }).optional(), + filterValue: string2().meta({ description: "The value to filter by" }).or(number2()).or(boolean2()).or(array(string2())).or(array(number2())).optional(), + filterOperator: _enum2(whereOperators).meta({ description: "The operator to use for the filter" }).optional(), + organizationId: string2().meta({ description: `The organization ID to list members for. If not provided, will default to the user's active organization. Eg: "organization-id"` }).optional(), + organizationSlug: string2().meta({ description: `The organization slug to list members for. If not provided, will default to the user's active organization. Eg: "organization-slug"` }).optional() + }).optional(), + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware] +}, async (ctx) => { + const session = ctx.context.session; + let organizationId = ctx.query?.organizationId || session.session.activeOrganizationId; + const adapter = getOrgAdapter(ctx.context, options); + if (ctx.query?.organizationSlug) { + const organization2 = await adapter.findOrganizationBySlug(ctx.query?.organizationSlug); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + organizationId = organization2.id; + } + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + if (!await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + })) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); + const { members, total } = await adapter.listMembers({ + organizationId, + limit: ctx.query?.limit ? Number(ctx.query.limit) : void 0, + offset: ctx.query?.offset ? Number(ctx.query.offset) : void 0, + sortBy: ctx.query?.sortBy, + sortOrder: ctx.query?.sortDirection, + filter: ctx.query?.filterField ? { + field: ctx.query?.filterField, + operator: ctx.query.filterOperator, + value: ctx.query.filterValue + } : void 0 + }); + return ctx.json({ + members, + total + }); +}); +var getActiveMemberRoleQuerySchema = object({ + userId: string2().meta({ description: "The user ID to get the role for. If not provided, will default to the current user's" }).optional(), + organizationId: string2().meta({ description: `The organization ID to list members for. If not provided, will default to the user's active organization. Eg: "organization-id"` }).optional(), + organizationSlug: string2().meta({ description: `The organization slug to list members for. If not provided, will default to the user's active organization. Eg: "organization-slug"` }).optional() +}).optional(); +var getActiveMemberRole = (options) => createAuthEndpoint("/organization/get-active-member-role", { + method: "GET", + query: getActiveMemberRoleQuerySchema, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware] +}, async (ctx) => { + const session = ctx.context.session; + let organizationId = ctx.query?.organizationId || session.session.activeOrganizationId; + const adapter = getOrgAdapter(ctx.context, options); + if (ctx.query?.organizationSlug) { + const organization2 = await adapter.findOrganizationBySlug(ctx.query?.organizationSlug); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + organizationId = organization2.id; + } + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const isMember = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!isMember) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); + if (!ctx.query?.userId) return ctx.json({ role: isMember.role }); + const userIdToGetRole = ctx.query?.userId; + const member = await adapter.findMemberByOrgId({ + userId: userIdToGetRole, + organizationId + }); + if (!member) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); + return ctx.json({ role: member?.role }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-org.mjs +init_error2(); +init_zod(); +var baseOrganizationSchema = object({ + name: string2().min(1).meta({ description: "The name of the organization" }), + slug: string2().min(1).meta({ description: "The slug of the organization" }), + userId: coerce_exports.string().meta({ description: 'The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server. server-only. Eg: "user-id"' }).optional(), + logo: string2().meta({ description: "The logo of the organization" }).optional(), + metadata: record(string2(), any()).meta({ description: "The metadata of the organization" }).optional(), + keepCurrentActiveOrganization: boolean2().meta({ description: "Whether to keep the current active organization active after creating a new one. Eg: true" }).optional() +}); +var createOrganization = (options) => { + const additionalFieldsSchema = toZodSchema({ + fields: options?.schema?.organization?.additionalFields || {}, + isClientSide: true + }); + return createAuthEndpoint("/organization/create", { + method: "POST", + body: object({ + ...baseOrganizationSchema.shape, + ...additionalFieldsSchema.shape + }), + use: [orgMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + description: "Create an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + description: "The organization that was created", + $ref: "#/components/schemas/Organization" + } } } + } } + } + } + }, async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session && (ctx.request || ctx.headers)) throw APIError2.fromStatus("UNAUTHORIZED"); + let user = session?.user || null; + if (!user) { + if (!ctx.body.userId) throw APIError2.fromStatus("UNAUTHORIZED"); + user = await ctx.context.internalAdapter.findUserById(ctx.body.userId); + } + if (!user) throw APIError2.fromStatus("UNAUTHORIZED"); + const options2 = ctx.context.orgOptions; + const canCreateOrg = typeof options2?.allowUserToCreateOrganization === "function" ? await options2.allowUserToCreateOrganization(user) : options2?.allowUserToCreateOrganization === void 0 ? true : options2.allowUserToCreateOrganization; + const isSystemAction = !session && ctx.body.userId; + if (!canCreateOrg && !isSystemAction) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION); + const adapter = getOrgAdapter(ctx.context, options2); + const userOrganizations = await adapter.listOrganizations(user.id); + if (typeof options2.organizationLimit === "number" ? userOrganizations.length >= options2.organizationLimit : typeof options2.organizationLimit === "function" ? await options2.organizationLimit(user) : false) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS); + if (await adapter.findOrganizationBySlug(ctx.body.slug)) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_ALREADY_EXISTS); + let { keepCurrentActiveOrganization: _, userId: __, ...orgData } = ctx.body; + if (options2?.organizationHooks?.beforeCreateOrganization) { + const response = await options2?.organizationHooks.beforeCreateOrganization({ + organization: orgData, + user + }); + if (response && typeof response === "object" && "data" in response) orgData = { + ...ctx.body, + ...response.data + }; + } + const organization2 = await adapter.createOrganization({ organization: { + ...orgData, + createdAt: /* @__PURE__ */ new Date() + } }); + let member; + let teamMember = null; + let data = { + userId: user.id, + organizationId: organization2.id, + role: ctx.context.orgOptions.creatorRole || "owner" + }; + if (options2?.organizationHooks?.beforeAddMember) { + const response = await options2?.organizationHooks.beforeAddMember({ + member: { + userId: user.id, + organizationId: organization2.id, + role: ctx.context.orgOptions.creatorRole || "owner" + }, + user, + organization: organization2 + }); + if (response && typeof response === "object" && "data" in response) data = { + ...data, + ...response.data + }; + } + member = await adapter.createMember(data); + if (options2?.organizationHooks?.afterAddMember) await options2?.organizationHooks.afterAddMember({ + member, + user, + organization: organization2 + }); + if (options2?.teams?.enabled && options2.teams.defaultTeam?.enabled !== false) { + let teamData = { + organizationId: organization2.id, + name: `${organization2.name}`, + createdAt: /* @__PURE__ */ new Date() + }; + if (options2?.organizationHooks?.beforeCreateTeam) { + const response = await options2?.organizationHooks.beforeCreateTeam({ + team: { + organizationId: organization2.id, + name: `${organization2.name}` + }, + user, + organization: organization2 + }); + if (response && typeof response === "object" && "data" in response) teamData = { + ...teamData, + ...response.data + }; + } + const defaultTeam = await options2.teams.defaultTeam?.customCreateDefaultTeam?.(organization2, ctx) || await adapter.createTeam(teamData); + teamMember = await adapter.findOrCreateTeamMember({ + teamId: defaultTeam.id, + userId: user.id + }); + if (options2?.organizationHooks?.afterCreateTeam) await options2?.organizationHooks.afterCreateTeam({ + team: defaultTeam, + user, + organization: organization2 + }); + } + if (options2?.organizationHooks?.afterCreateOrganization) await options2?.organizationHooks.afterCreateOrganization({ + organization: organization2, + user, + member + }); + if (ctx.context.session && !ctx.body.keepCurrentActiveOrganization) await adapter.setActiveOrganization(ctx.context.session.session.token, organization2.id, ctx); + if (teamMember && ctx.context.session && !ctx.body.keepCurrentActiveOrganization) await adapter.setActiveTeam(ctx.context.session.session.token, teamMember.teamId, ctx); + return ctx.json({ + ...organization2, + metadata: organization2.metadata && typeof organization2.metadata === "string" ? JSON.parse(organization2.metadata) : organization2.metadata, + members: [member] + }); + }); +}; +var checkOrganizationSlugBodySchema = object({ slug: string2().meta({ description: 'The organization slug to check. Eg: "my-org"' }) }); +var checkOrganizationSlug = (options) => createAuthEndpoint("/organization/check-slug", { + method: "POST", + body: checkOrganizationSlugBodySchema, + use: [requestOnlySessionMiddleware, orgMiddleware] +}, async (ctx) => { + if (!await getOrgAdapter(ctx.context, options).findOrganizationBySlug(ctx.body.slug)) return ctx.json({ status: true }); + throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_SLUG_ALREADY_TAKEN); +}); +var baseUpdateOrganizationSchema = object({ + name: string2().min(1).meta({ description: "The name of the organization" }).optional(), + slug: string2().min(1).meta({ description: "The slug of the organization" }).optional(), + logo: string2().meta({ description: "The logo of the organization" }).optional(), + metadata: record(string2(), any()).meta({ description: "The metadata of the organization" }).optional() +}); +var updateOrganization = (options) => { + const additionalFieldsSchema = toZodSchema({ + fields: options?.schema?.organization?.additionalFields || {}, + isClientSide: true + }); + return createAuthEndpoint("/organization/update", { + method: "POST", + body: object({ + data: object({ + ...additionalFieldsSchema.shape, + ...baseUpdateOrganizationSchema.shape + }).partial(), + organizationId: string2().meta({ description: 'The organization ID. Eg: "org-id"' }).optional() + }), + requireHeaders: true, + use: [orgMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + description: "Update an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + description: "The updated organization", + $ref: "#/components/schemas/Organization" + } } } + } } + } + } + }, async (ctx) => { + const session = await ctx.context.getSession(ctx); + if (!session) throw APIError2.fromStatus("UNAUTHORIZED", { message: "User not found" }); + const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const adapter = getOrgAdapter(ctx.context, options); + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + if (!await hasPermission({ + permissions: { organization: ["update"] }, + role: member.role, + options: ctx.context.orgOptions, + organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION); + if (typeof ctx.body.data.slug === "string") { + const existingOrganization = await adapter.findOrganizationBySlug(ctx.body.data.slug); + if (existingOrganization && existingOrganization.id !== organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_SLUG_ALREADY_TAKEN); + } + if (options?.organizationHooks?.beforeUpdateOrganization) { + const response = await options.organizationHooks.beforeUpdateOrganization({ + organization: ctx.body.data, + user: session.user, + member + }); + if (response && typeof response === "object" && "data" in response) ctx.body.data = { + ...ctx.body.data, + ...response.data + }; + } + const updatedOrg = await adapter.updateOrganization(organizationId, ctx.body.data); + if (options?.organizationHooks?.afterUpdateOrganization) await options.organizationHooks.afterUpdateOrganization({ + organization: updatedOrg, + user: session.user, + member + }); + return ctx.json(updatedOrg); + }); +}; +var deleteOrganizationBodySchema = object({ organizationId: string2().meta({ description: "The organization id to delete" }) }); +var deleteOrganization = (options) => { + return createAuthEndpoint("/organization/delete", { + method: "POST", + body: deleteOrganizationBodySchema, + requireHeaders: true, + use: [orgMiddleware], + metadata: { openapi: { + description: "Delete an organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "string", + description: "The organization id that was deleted" + } } } + } } + } } + }, async (ctx) => { + if (ctx.context.orgOptions.disableOrganizationDeletion) throw APIError2.from("NOT_FOUND", { + message: "Organization deletion is disabled", + code: "ORGANIZATION_DELETION_DISABLED" + }); + const session = await ctx.context.getSession(ctx); + if (!session) throw APIError2.fromStatus("UNAUTHORIZED"); + const organizationId = ctx.body.organizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const adapter = getOrgAdapter(ctx.context, options); + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + if (!await hasPermission({ + role: member.role, + permissions: { organization: ["delete"] }, + organizationId, + options: ctx.context.orgOptions + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION); + if (organizationId === session.session.activeOrganizationId) + await adapter.setActiveOrganization(session.session.token, null, ctx); + const org = await adapter.findOrganizationById(organizationId); + if (!org) throw APIError2.fromStatus("BAD_REQUEST"); + if (options?.organizationHooks?.beforeDeleteOrganization) await options.organizationHooks.beforeDeleteOrganization({ + organization: org, + user: session.user + }); + await adapter.deleteOrganization(organizationId); + if (options?.organizationHooks?.afterDeleteOrganization) await options.organizationHooks.afterDeleteOrganization({ + organization: org, + user: session.user + }); + return ctx.json(org); + }); +}; +var getFullOrganizationQuerySchema = optional(object({ + organizationId: string2().meta({ description: "The organization id to get" }).optional(), + organizationSlug: string2().meta({ description: "The organization slug to get" }).optional(), + membersLimit: number2().or(string2().transform((val) => parseInt(val))).meta({ description: "The limit of members to get. By default, it uses the membershipLimit option." }).optional() +})); +var getFullOrganization = (options) => createAuthEndpoint("/organization/get-full-organization", { + method: "GET", + query: getFullOrganizationQuerySchema, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware], + metadata: { openapi: { + operationId: "getOrganization", + description: "Get the full organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + description: "The organization", + $ref: "#/components/schemas/Organization" + } } } + } } + } } +}, async (ctx) => { + const session = ctx.context.session; + const organizationId = ctx.query?.organizationSlug || ctx.query?.organizationId || session.session.activeOrganizationId; + if (!organizationId) return ctx.json(null, { status: 200 }); + const adapter = getOrgAdapter(ctx.context, options); + const organization2 = await adapter.findFullOrganization({ + organizationId, + isSlug: !!ctx.query?.organizationSlug, + includeTeams: ctx.context.orgOptions.teams?.enabled, + membersLimit: ctx.query?.membersLimit + }); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + if (!await adapter.checkMembership({ + userId: session.user.id, + organizationId: organization2.id + })) { + await adapter.setActiveOrganization(session.session.token, null, ctx); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + } + return ctx.json(organization2); +}); +var setActiveOrganizationBodySchema = object({ + organizationId: string2().meta({ description: 'The organization id to set as active. It can be null to unset the active organization. Eg: "org-id"' }).nullable().optional(), + organizationSlug: string2().meta({ description: 'The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided. Eg: "org-slug"' }).optional() +}); +var setActiveOrganization = (options) => { + return createAuthEndpoint("/organization/set-active", { + method: "POST", + body: setActiveOrganizationBodySchema, + use: [orgSessionMiddleware, orgMiddleware], + requireHeaders: true, + metadata: { openapi: { + operationId: "setActiveOrganization", + description: "Set the active organization", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + description: "The organization", + $ref: "#/components/schemas/Organization" + } } } + } } + } } + }, async (ctx) => { + const adapter = getOrgAdapter(ctx.context, options); + const session = ctx.context.session; + let organizationId = ctx.body.organizationId; + const organizationSlug = ctx.body.organizationSlug; + if (organizationId === null) { + if (!session.session.activeOrganizationId) return ctx.json(null); + await setSessionCookie(ctx, { + session: await adapter.setActiveOrganization(session.session.token, null, ctx), + user: session.user + }); + return ctx.json(null); + } + if (!organizationId && !organizationSlug) { + const sessionOrgId = session.session.activeOrganizationId; + if (!sessionOrgId) return ctx.json(null); + organizationId = sessionOrgId; + } + if (organizationSlug && !organizationId) { + const organization3 = await adapter.findOrganizationBySlug(organizationSlug); + if (!organization3) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + organizationId = organization3.id; + } + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + if (!await adapter.checkMembership({ + userId: session.user.id, + organizationId + })) { + await adapter.setActiveOrganization(session.session.token, null, ctx); + throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + } + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + await setSessionCookie(ctx, { + session: await adapter.setActiveOrganization(session.session.token, organization2.id, ctx), + user: session.user + }); + return ctx.json(organization2); + }); +}; +var listOrganizations = (options) => createAuthEndpoint("/organization/list", { + method: "GET", + use: [orgMiddleware, orgSessionMiddleware], + requireHeaders: true, + metadata: { openapi: { + description: "List all organizations", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "array", + items: { $ref: "#/components/schemas/Organization" } + } } } + } } + } } +}, async (ctx) => { + const organizations = await getOrgAdapter(ctx.context, options).listOrganizations(ctx.context.session.user.id); + return ctx.json(organizations); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/schema.mjs +init_id2(); +init_zod(); +var roleSchema = string2(); +var invitationStatus = _enum2([ + "pending", + "accepted", + "rejected", + "canceled" +]).default("pending"); +object({ + id: string2().default(generateId), + name: string2(), + slug: string2(), + logo: string2().nullish().optional(), + metadata: record(string2(), unknown()).or(string2().transform((v) => JSON.parse(v))).optional(), + createdAt: date3() +}); +object({ + id: string2().default(generateId), + organizationId: string2(), + userId: coerce_exports.string(), + role: roleSchema, + createdAt: date3().default(() => /* @__PURE__ */ new Date()) +}); +object({ + id: string2().default(generateId), + organizationId: string2(), + email: string2(), + role: roleSchema, + status: invitationStatus, + teamId: string2().nullish(), + inviterId: string2(), + expiresAt: date3(), + createdAt: date3().default(() => /* @__PURE__ */ new Date()) +}); +var teamSchema = object({ + id: string2().default(generateId), + name: string2().min(1), + organizationId: string2(), + createdAt: date3(), + updatedAt: date3().optional() +}); +object({ + id: string2().default(generateId), + teamId: string2(), + userId: string2(), + createdAt: date3().default(() => /* @__PURE__ */ new Date()) +}); +object({ + id: string2().default(generateId), + organizationId: string2(), + role: string2(), + permission: record(string2(), array(string2())), + createdAt: date3().default(() => /* @__PURE__ */ new Date()), + updatedAt: date3().optional() +}); +var defaultRoles2 = [ + "admin", + "member", + "owner" +]; +union([_enum2(defaultRoles2), array(_enum2(defaultRoles2))]); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-team.mjs +init_error2(); +init_zod(); +var teamBaseSchema = object({ + name: string2().meta({ description: 'The name of the team. Eg: "my-team"' }), + organizationId: string2().meta({ description: 'The organization ID which the team will be created in. Defaults to the active organization. Eg: "organization-id"' }).optional() +}); +var createTeam = (options) => { + const additionalFieldsSchema = toZodSchema({ + fields: options?.schema?.team?.additionalFields ?? {}, + isClientSide: true + }); + return createAuthEndpoint("/organization/create-team", { + method: "POST", + body: object({ + ...teamBaseSchema.shape, + ...additionalFieldsSchema.shape + }), + use: [orgMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + description: "Create a new team within an organization", + responses: { "200": { + description: "Team created successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + id: { + type: "string", + description: "Unique identifier of the created team" + }, + name: { + type: "string", + description: "Name of the team" + }, + organizationId: { + type: "string", + description: "ID of the organization the team belongs to" + }, + createdAt: { + type: "string", + format: "date-time", + description: "Timestamp when the team was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "Timestamp when the team was last updated" + } + }, + required: [ + "id", + "name", + "organizationId", + "createdAt", + "updatedAt" + ] + } } } + } } + } + } + }, async (ctx) => { + const session = await getSessionFromCtx(ctx); + const organizationId = ctx.body.organizationId || session?.session.activeOrganizationId; + if (!session && (ctx.request || ctx.headers)) throw APIError2.fromStatus("UNAUTHORIZED"); + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const adapter = getOrgAdapter(ctx.context, options); + if (session) { + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION); + if (!await hasPermission({ + role: member.role, + options: ctx.context.orgOptions, + permissions: { team: ["create"] }, + organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION); + } + const existingTeams = await adapter.listTeams(organizationId); + const maximum = typeof ctx.context.orgOptions.teams?.maximumTeams === "function" ? await ctx.context.orgOptions.teams?.maximumTeams({ + organizationId, + session + }, ctx) : ctx.context.orgOptions.teams?.maximumTeams; + if (maximum ? existingTeams.length >= maximum : false) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS); + const { name, organizationId: _, ...additionalFields } = ctx.body; + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + let teamData = { + name, + organizationId, + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...additionalFields + }; + if (options?.organizationHooks?.beforeCreateTeam) { + const response = await options?.organizationHooks.beforeCreateTeam({ + team: { + name, + organizationId, + ...additionalFields + }, + user: session?.user, + organization: organization2 + }); + if (response && typeof response === "object" && "data" in response) teamData = { + ...teamData, + ...response.data + }; + } + const createdTeam = await adapter.createTeam(teamData); + if (options?.organizationHooks?.afterCreateTeam) await options?.organizationHooks.afterCreateTeam({ + team: createdTeam, + user: session?.user, + organization: organization2 + }); + return ctx.json(createdTeam); + }); +}; +var removeTeamBodySchema = object({ + teamId: string2().meta({ description: `The team ID of the team to remove. Eg: "team-id"` }), + organizationId: string2().meta({ description: `The organization ID which the team falls under. If not provided, it will default to the user's active organization. Eg: "organization-id"` }).optional() +}); +var removeTeam = (options) => createAuthEndpoint("/organization/remove-team", { + method: "POST", + body: removeTeamBodySchema, + use: [orgMiddleware], + metadata: { openapi: { + description: "Remove a team from an organization", + responses: { "200": { + description: "Team removed successfully", + content: { "application/json": { schema: { + type: "object", + properties: { message: { + type: "string", + description: "Confirmation message indicating successful removal", + enum: ["Team removed successfully."] + } }, + required: ["message"] + } } } + } } + } } +}, async (ctx) => { + const session = await getSessionFromCtx(ctx); + const organizationId = ctx.body.organizationId || session?.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + if (!session && (ctx.request || ctx.headers)) throw APIError2.fromStatus("UNAUTHORIZED"); + const adapter = getOrgAdapter(ctx.context, options); + if (session) { + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member || session.session?.activeTeamId === ctx.body.teamId) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM); + if (!await hasPermission({ + role: member.role, + options: ctx.context.orgOptions, + permissions: { team: ["delete"] }, + organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION); + } + const team = await adapter.findTeamById({ + teamId: ctx.body.teamId, + organizationId + }); + if (!team || team.organizationId !== organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); + if (!ctx.context.orgOptions.teams?.allowRemovingAllTeams) { + if ((await adapter.listTeams(organizationId)).length <= 1) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.UNABLE_TO_REMOVE_LAST_TEAM); + } + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + if (options?.organizationHooks?.beforeDeleteTeam) await options?.organizationHooks.beforeDeleteTeam({ + team, + user: session?.user, + organization: organization2 + }); + await adapter.deleteTeam(team.id); + if (options?.organizationHooks?.afterDeleteTeam) await options?.organizationHooks.afterDeleteTeam({ + team, + user: session?.user, + organization: organization2 + }); + return ctx.json({ message: "Team removed successfully." }); +}); +var updateTeam = (options) => { + const additionalFieldsSchema = toZodSchema({ + fields: options?.schema?.team?.additionalFields ?? {}, + isClientSide: true + }); + return createAuthEndpoint("/organization/update-team", { + method: "POST", + body: object({ + teamId: string2().meta({ description: `The ID of the team to be updated. Eg: "team-id"` }), + data: object({ + ...teamSchema.shape, + ...additionalFieldsSchema.shape + }).partial() + }), + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + description: "Update an existing team in an organization", + responses: { "200": { + description: "Team updated successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + id: { + type: "string", + description: "Unique identifier of the updated team" + }, + name: { + type: "string", + description: "Updated name of the team" + }, + organizationId: { + type: "string", + description: "ID of the organization the team belongs to" + }, + createdAt: { + type: "string", + format: "date-time", + description: "Timestamp when the team was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "Timestamp when the team was last updated" + } + }, + required: [ + "id", + "name", + "organizationId", + "createdAt", + "updatedAt" + ] + } } } + } } + } + } + }, async (ctx) => { + const session = ctx.context.session; + const organizationId = ctx.body.data.organizationId || session.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const adapter = getOrgAdapter(ctx.context, options); + const member = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!member) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM); + if (!await hasPermission({ + role: member.role, + options: ctx.context.orgOptions, + permissions: { team: ["update"] }, + organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM); + const team = await adapter.findTeamById({ + teamId: ctx.body.teamId, + organizationId + }); + if (!team || team.organizationId !== organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); + const { name, organizationId: __, ...additionalFields } = ctx.body.data; + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const updates = { + name, + ...additionalFields + }; + if (options?.organizationHooks?.beforeUpdateTeam) { + const response = await options?.organizationHooks.beforeUpdateTeam({ + team, + updates, + user: session.user, + organization: organization2 + }); + if (response && typeof response === "object" && "data" in response) { + const modifiedUpdates = response.data; + const updatedTeam2 = await adapter.updateTeam(team.id, modifiedUpdates); + if (options?.organizationHooks?.afterUpdateTeam) await options?.organizationHooks.afterUpdateTeam({ + team: updatedTeam2, + user: session.user, + organization: organization2 + }); + return ctx.json(updatedTeam2); + } + } + const updatedTeam = await adapter.updateTeam(team.id, updates); + if (options?.organizationHooks?.afterUpdateTeam) await options?.organizationHooks.afterUpdateTeam({ + team: updatedTeam, + user: session.user, + organization: organization2 + }); + return ctx.json(updatedTeam); + }); +}; +var listOrganizationTeamsQuerySchema = optional(object({ organizationId: string2().meta({ description: `The organization ID which the teams are under to list. Defaults to the users active organization. Eg: "organization-id"` }).optional() })); +var listOrganizationTeams = (options) => createAuthEndpoint("/organization/list-teams", { + method: "GET", + query: listOrganizationTeamsQuerySchema, + metadata: { openapi: { + description: "List all teams in an organization", + responses: { "200": { + description: "Teams retrieved successfully", + content: { "application/json": { schema: { + type: "array", + items: { + type: "object", + properties: { + id: { + type: "string", + description: "Unique identifier of the team" + }, + name: { + type: "string", + description: "Name of the team" + }, + organizationId: { + type: "string", + description: "ID of the organization the team belongs to" + }, + createdAt: { + type: "string", + format: "date-time", + description: "Timestamp when the team was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "Timestamp when the team was last updated" + } + }, + required: [ + "id", + "name", + "organizationId", + "createdAt", + "updatedAt" + ] + }, + description: "Array of team objects within the organization" + } } } + } } + } }, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware] +}, async (ctx) => { + const session = ctx.context.session; + const organizationId = ctx.query?.organizationId || session?.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const adapter = getOrgAdapter(ctx.context, options); + if (!await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId: organizationId || "" + })) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION); + const teams = await adapter.listTeams(organizationId); + return ctx.json(teams); +}); +var setActiveTeamBodySchema = object({ teamId: string2().meta({ description: "The team id to set as active. It can be null to unset the active team" }).nullable().optional() }); +var setActiveTeam = (options) => createAuthEndpoint("/organization/set-active-team", { + method: "POST", + body: setActiveTeamBodySchema, + requireHeaders: true, + use: [orgSessionMiddleware, orgMiddleware], + metadata: { openapi: { + description: "Set the active team", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + description: "The team", + $ref: "#/components/schemas/Team" + } } } + } } + } } +}, async (ctx) => { + const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); + const session = ctx.context.session; + if (ctx.body.teamId === null) { + if (!session.session.activeTeamId) return ctx.json(null); + await setSessionCookie(ctx, { + session: await adapter.setActiveTeam(session.session.token, null, ctx), + user: session.user + }); + return ctx.json(null); + } + let teamId; + if (!ctx.body.teamId) { + const sessionTeamId = session.session.activeTeamId; + if (!sessionTeamId) return ctx.json(null); + else teamId = sessionTeamId; + } else teamId = ctx.body.teamId; + const team = await adapter.findTeamById({ teamId }); + if (!team) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); + if (!await adapter.findTeamMember({ + teamId, + userId: session.user.id + })) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM); + await setSessionCookie(ctx, { + session: await adapter.setActiveTeam(session.session.token, team.id, ctx), + user: session.user + }); + return ctx.json(team); +}); +var listUserTeams = (options) => createAuthEndpoint("/organization/list-user-teams", { + method: "GET", + metadata: { openapi: { + description: "List all teams that the current user is a part of.", + responses: { "200": { + description: "Teams retrieved successfully", + content: { "application/json": { schema: { + type: "array", + items: { + type: "object", + description: "The team", + $ref: "#/components/schemas/Team" + }, + description: "Array of team objects within the organization" + } } } + } } + } }, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware] +}, async (ctx) => { + const session = ctx.context.session; + const teams = await getOrgAdapter(ctx.context, ctx.context.orgOptions).listTeamsByUser({ userId: session.user.id }); + return ctx.json(teams); +}); +var listTeamMembersQuerySchema = optional(object({ teamId: string2().optional().meta({ description: "The team whose members we should return. If this is not provided the members of the current active team get returned." }) })); +var listTeamMembers = (options) => createAuthEndpoint("/organization/list-team-members", { + method: "GET", + query: listTeamMembersQuerySchema, + metadata: { openapi: { + description: "List the members of the given team.", + responses: { "200": { + description: "Teams retrieved successfully", + content: { "application/json": { schema: { + type: "array", + items: { + type: "object", + description: "The team member", + properties: { + id: { + type: "string", + description: "Unique identifier of the team member" + }, + userId: { + type: "string", + description: "The user ID of the team member" + }, + teamId: { + type: "string", + description: "The team ID of the team the team member is in" + }, + createdAt: { + type: "string", + format: "date-time", + description: "Timestamp when the team member was created" + } + }, + required: [ + "id", + "userId", + "teamId", + "createdAt" + ] + }, + description: "Array of team member objects within the team" + } } } + } } + } }, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware] +}, async (ctx) => { + const session = ctx.context.session; + const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); + const teamId = ctx.query?.teamId || session?.session.activeTeamId; + if (!teamId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM); + if (!await adapter.findTeamMember({ + userId: session.user.id, + teamId + })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM); + const members = await adapter.listTeamMembers({ teamId }); + return ctx.json(members); +}); +var addTeamMemberBodySchema = object({ + teamId: string2().meta({ description: "The team the user should be a member of." }), + userId: coerce_exports.string().meta({ description: "The user Id which represents the user to be added as a member." }), + organizationId: string2().meta({ description: "The organization ID which the team falls under. If not provided, it will default to the user's active organization." }).optional() +}); +var addTeamMember = (options) => createAuthEndpoint("/organization/add-team-member", { + method: "POST", + body: addTeamMemberBodySchema, + metadata: { openapi: { + description: "The newly created member", + responses: { "200": { + description: "Team member created successfully", + content: { "application/json": { schema: { + type: "object", + description: "The team member", + properties: { + id: { + type: "string", + description: "Unique identifier of the team member" + }, + userId: { + type: "string", + description: "The user ID of the team member" + }, + teamId: { + type: "string", + description: "The team ID of the team the team member is in" + }, + createdAt: { + type: "string", + format: "date-time", + description: "Timestamp when the team member was created" + } + }, + required: [ + "id", + "userId", + "teamId", + "createdAt" + ] + } } } + } } + } }, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware] +}, async (ctx) => { + const session = ctx.context.session; + const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); + const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const currentMember = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!currentMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + if (!await hasPermission({ + role: currentMember.role, + options: ctx.context.orgOptions, + permissions: { member: ["update"] }, + organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER); + if (!await adapter.findMemberByOrgId({ + userId: ctx.body.userId, + organizationId + })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + const team = await adapter.findTeamById({ + teamId: ctx.body.teamId, + organizationId + }); + if (!team) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const userBeingAdded = await ctx.context.internalAdapter.findUserById(ctx.body.userId); + if (!userBeingAdded) throw APIError2.fromStatus("BAD_REQUEST", { message: "User not found" }); + if (options?.organizationHooks?.beforeAddTeamMember) { + const response = await options?.organizationHooks.beforeAddTeamMember({ + teamMember: { + teamId: ctx.body.teamId, + userId: ctx.body.userId + }, + team, + user: userBeingAdded, + organization: organization2 + }); + if (response && typeof response === "object" && "data" in response) { + } + } + const teamMember = await adapter.findOrCreateTeamMember({ + teamId: ctx.body.teamId, + userId: ctx.body.userId + }); + if (options?.organizationHooks?.afterAddTeamMember) await options?.organizationHooks.afterAddTeamMember({ + teamMember, + team, + user: userBeingAdded, + organization: organization2 + }); + return ctx.json(teamMember); +}); +var removeTeamMemberBodySchema = object({ + teamId: string2().meta({ description: "The team the user should be removed from." }), + userId: coerce_exports.string().meta({ description: "The user which should be removed from the team." }), + organizationId: string2().meta({ description: "The organization ID which the team falls under. If not provided, it will default to the user's active organization." }).optional() +}); +var removeTeamMember = (options) => createAuthEndpoint("/organization/remove-team-member", { + method: "POST", + body: removeTeamMemberBodySchema, + metadata: { openapi: { + description: "Remove a member from a team", + responses: { "200": { + description: "Team member removed successfully", + content: { "application/json": { schema: { + type: "object", + properties: { message: { + type: "string", + description: "Confirmation message indicating successful removal", + enum: ["Team member removed successfully."] + } }, + required: ["message"] + } } } + } } + } }, + requireHeaders: true, + use: [orgMiddleware, orgSessionMiddleware] +}, async (ctx) => { + const session = ctx.context.session; + const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); + const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; + if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const currentMember = await adapter.findMemberByOrgId({ + userId: session.user.id, + organizationId + }); + if (!currentMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + if (!await hasPermission({ + role: currentMember.role, + options: ctx.context.orgOptions, + permissions: { member: ["delete"] }, + organizationId + }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER); + if (!await adapter.findMemberByOrgId({ + userId: ctx.body.userId, + organizationId + })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + const team = await adapter.findTeamById({ + teamId: ctx.body.teamId, + organizationId + }); + if (!team) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); + const organization2 = await adapter.findOrganizationById(organizationId); + if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); + const userBeingRemoved = await ctx.context.internalAdapter.findUserById(ctx.body.userId); + if (!userBeingRemoved) throw APIError2.fromStatus("BAD_REQUEST", { message: "User not found" }); + const teamMember = await adapter.findTeamMember({ + teamId: ctx.body.teamId, + userId: ctx.body.userId + }); + if (!teamMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM); + if (options?.organizationHooks?.beforeRemoveTeamMember) await options?.organizationHooks.beforeRemoveTeamMember({ + teamMember, + team, + user: userBeingRemoved, + organization: organization2 + }); + await adapter.removeTeamMember({ + teamId: ctx.body.teamId, + userId: ctx.body.userId + }); + if (options?.organizationHooks?.afterRemoveTeamMember) await options?.organizationHooks.afterRemoveTeamMember({ + teamMember, + team, + user: userBeingRemoved, + organization: organization2 + }); + return ctx.json({ message: "Team member removed successfully." }); +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/organization.mjs +init_error2(); +init_zod(); +function parseRoles(roles) { + return Array.isArray(roles) ? roles.join(",") : roles; +} +var createHasPermissionBodySchema = object({ organizationId: string2().optional() }).and(union([object({ + permission: record(string2(), array(string2())), + permissions: _undefined3() +}), object({ + permission: _undefined3(), + permissions: record(string2(), array(string2())) +})])); +var createHasPermission = (options) => { + return createAuthEndpoint("/organization/has-permission", { + method: "POST", + requireHeaders: true, + body: createHasPermissionBodySchema, + use: [orgSessionMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + description: "Check if the user has permission", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + permission: { + type: "object", + description: "The permission to check", + deprecated: true + }, + permissions: { + type: "object", + description: "The permission to check" + } + }, + required: ["permissions"] + } } } }, + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + error: { type: "string" }, + success: { type: "boolean" } + }, + required: ["success"] + } } } + } } + } + } + }, async (ctx) => { + const activeOrganizationId = ctx.body.organizationId || ctx.context.session.session.activeOrganizationId; + if (!activeOrganizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); + const member = await getOrgAdapter(ctx.context, options).findMemberByOrgId({ + userId: ctx.context.session.user.id, + organizationId: activeOrganizationId + }); + if (!member) throw APIError2.from("UNAUTHORIZED", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); + const result = await hasPermission({ + role: member.role, + options, + permissions: ctx.body.permissions, + organizationId: activeOrganizationId + }, ctx); + return ctx.json({ + error: null, + success: result + }); + }); +}; +function organization(options) { + const opts = options || {}; + let endpoints = { + createOrganization: createOrganization(opts), + updateOrganization: updateOrganization(opts), + deleteOrganization: deleteOrganization(opts), + setActiveOrganization: setActiveOrganization(opts), + getFullOrganization: getFullOrganization(opts), + listOrganizations: listOrganizations(opts), + createInvitation: createInvitation(opts), + cancelInvitation: cancelInvitation(opts), + acceptInvitation: acceptInvitation(opts), + getInvitation: getInvitation(opts), + rejectInvitation: rejectInvitation(opts), + listInvitations: listInvitations(opts), + getActiveMember: getActiveMember(opts), + checkOrganizationSlug: checkOrganizationSlug(opts), + addMember: addMember(opts), + removeMember: removeMember(opts), + updateMemberRole: updateMemberRole(opts), + leaveOrganization: leaveOrganization(opts), + listUserInvitations: listUserInvitations(opts), + listMembers: listMembers(opts), + getActiveMemberRole: getActiveMemberRole(opts) + }; + const teamSupport = opts.teams?.enabled; + const teamEndpoints = { + createTeam: createTeam(opts), + listOrganizationTeams: listOrganizationTeams(opts), + removeTeam: removeTeam(opts), + updateTeam: updateTeam(opts), + setActiveTeam: setActiveTeam(opts), + listUserTeams: listUserTeams(opts), + listTeamMembers: listTeamMembers(opts), + addTeamMember: addTeamMember(opts), + removeTeamMember: removeTeamMember(opts) + }; + if (teamSupport) endpoints = { + ...endpoints, + ...teamEndpoints + }; + const dynamicAccessControlEndpoints = { + createOrgRole: createOrgRole(opts), + deleteOrgRole: deleteOrgRole(opts), + listOrgRoles: listOrgRoles(opts), + getOrgRole: getOrgRole(opts), + updateOrgRole: updateOrgRole(opts) + }; + if (opts.dynamicAccessControl?.enabled) endpoints = { + ...endpoints, + ...dynamicAccessControlEndpoints + }; + const roles = { + ...defaultRoles, + ...opts.roles + }; + const teamSchema2 = teamSupport ? { + team: { + modelName: opts.schema?.team?.modelName, + fields: { + name: { + type: "string", + required: true, + fieldName: opts.schema?.team?.fields?.name + }, + organizationId: { + type: "string", + required: true, + references: { + model: "organization", + field: "id" + }, + fieldName: opts.schema?.team?.fields?.organizationId, + index: true + }, + createdAt: { + type: "date", + required: true, + fieldName: opts.schema?.team?.fields?.createdAt + }, + updatedAt: { + type: "date", + required: false, + fieldName: opts.schema?.team?.fields?.updatedAt, + onUpdate: () => /* @__PURE__ */ new Date() + }, + ...opts.schema?.team?.additionalFields || {} + } + }, + teamMember: { + modelName: opts.schema?.teamMember?.modelName, + fields: { + teamId: { + type: "string", + required: true, + references: { + model: "team", + field: "id" + }, + fieldName: opts.schema?.teamMember?.fields?.teamId, + index: true + }, + userId: { + type: "string", + required: true, + references: { + model: "user", + field: "id" + }, + fieldName: opts.schema?.teamMember?.fields?.userId, + index: true + }, + createdAt: { + type: "date", + required: false, + fieldName: opts.schema?.teamMember?.fields?.createdAt + } + } + } + } : {}; + const organizationRoleSchema = opts.dynamicAccessControl?.enabled ? { organizationRole: { + fields: { + organizationId: { + type: "string", + required: true, + references: { + model: "organization", + field: "id" + }, + fieldName: opts.schema?.organizationRole?.fields?.organizationId, + index: true + }, + role: { + type: "string", + required: true, + fieldName: opts.schema?.organizationRole?.fields?.role, + index: true + }, + permission: { + type: "string", + required: true, + fieldName: opts.schema?.organizationRole?.fields?.permission + }, + createdAt: { + type: "date", + required: true, + defaultValue: () => /* @__PURE__ */ new Date(), + fieldName: opts.schema?.organizationRole?.fields?.createdAt + }, + updatedAt: { + type: "date", + required: false, + fieldName: opts.schema?.organizationRole?.fields?.updatedAt, + onUpdate: () => /* @__PURE__ */ new Date() + }, + ...opts.schema?.organizationRole?.additionalFields || {} + }, + modelName: opts.schema?.organizationRole?.modelName + } } : {}; + const schema3 = { + organization: { + modelName: opts.schema?.organization?.modelName, + fields: { + name: { + type: "string", + required: true, + sortable: true, + fieldName: opts.schema?.organization?.fields?.name + }, + slug: { + type: "string", + required: true, + unique: true, + sortable: true, + fieldName: opts.schema?.organization?.fields?.slug, + index: true + }, + logo: { + type: "string", + required: false, + fieldName: opts.schema?.organization?.fields?.logo + }, + createdAt: { + type: "date", + required: true, + fieldName: opts.schema?.organization?.fields?.createdAt + }, + metadata: { + type: "string", + required: false, + fieldName: opts.schema?.organization?.fields?.metadata + }, + ...opts.schema?.organization?.additionalFields || {} + } + }, + ...organizationRoleSchema, + ...teamSchema2, + member: { + modelName: opts.schema?.member?.modelName, + fields: { + organizationId: { + type: "string", + required: true, + references: { + model: "organization", + field: "id" + }, + fieldName: opts.schema?.member?.fields?.organizationId, + index: true + }, + userId: { + type: "string", + required: true, + fieldName: opts.schema?.member?.fields?.userId, + references: { + model: "user", + field: "id" + }, + index: true + }, + role: { + type: "string", + required: true, + sortable: true, + defaultValue: "member", + fieldName: opts.schema?.member?.fields?.role + }, + createdAt: { + type: "date", + required: true, + fieldName: opts.schema?.member?.fields?.createdAt + }, + ...opts.schema?.member?.additionalFields || {} + } + }, + invitation: { + modelName: opts.schema?.invitation?.modelName, + fields: { + organizationId: { + type: "string", + required: true, + references: { + model: "organization", + field: "id" + }, + fieldName: opts.schema?.invitation?.fields?.organizationId, + index: true + }, + email: { + type: "string", + required: true, + sortable: true, + fieldName: opts.schema?.invitation?.fields?.email, + index: true + }, + role: { + type: "string", + required: false, + sortable: true, + fieldName: opts.schema?.invitation?.fields?.role + }, + ...teamSupport ? { teamId: { + type: "string", + required: false, + sortable: true, + fieldName: opts.schema?.invitation?.fields?.teamId + } } : {}, + status: { + type: "string", + required: true, + sortable: true, + defaultValue: "pending", + fieldName: opts.schema?.invitation?.fields?.status + }, + expiresAt: { + type: "date", + required: true, + fieldName: opts.schema?.invitation?.fields?.expiresAt + }, + createdAt: { + type: "date", + required: true, + fieldName: opts.schema?.invitation?.fields?.createdAt, + defaultValue: () => /* @__PURE__ */ new Date() + }, + inviterId: { + type: "string", + references: { + model: "user", + field: "id" + }, + fieldName: opts.schema?.invitation?.fields?.inviterId, + required: true + }, + ...opts.schema?.invitation?.additionalFields || {} + } + } + }; + return { + id: "organization", + version: PACKAGE_VERSION, + endpoints: { + ...shimContext(endpoints, { + orgOptions: opts, + roles, + getSession: async (context) => { + return await getSessionFromCtx(context); + } + }), + hasPermission: createHasPermission(opts) + }, + schema: { + ...schema3, + session: { fields: { + activeOrganizationId: { + type: "string", + required: false, + fieldName: opts.schema?.session?.fields?.activeOrganizationId + }, + ...teamSupport ? { activeTeamId: { + type: "string", + required: false, + fieldName: opts.schema?.session?.fields?.activeTeamId + } } : {} + } } + }, + $Infer: { + Organization: {}, + Invitation: {}, + Member: {}, + Team: teamSupport ? {} : {}, + TeamMember: teamSupport ? {} : {}, + ActiveOrganization: {} + }, + $ERROR_CODES: ORGANIZATION_ERROR_CODES, + options: opts + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/error-code.mjs +init_error_codes(); +var TWO_FACTOR_ERROR_CODES = defineErrorCodes({ + OTP_NOT_ENABLED: "OTP not enabled", + OTP_HAS_EXPIRED: "OTP has expired", + TOTP_NOT_ENABLED: "TOTP not enabled", + TWO_FACTOR_NOT_ENABLED: "Two factor isn't enabled", + BACKUP_CODES_NOT_ENABLED: "Backup codes aren't enabled", + INVALID_BACKUP_CODE: "Invalid backup code", + INVALID_CODE: "Invalid code", + TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: "Too many attempts. Please request a new code.", + INVALID_TWO_FACTOR_COOKIE: "Invalid two factor cookie" +}); + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/constant.mjs +var TWO_FACTOR_COOKIE_NAME = "two_factor"; +var TRUST_DEVICE_COOKIE_NAME = "trust_device"; +var TRUST_DEVICE_COOKIE_MAX_AGE = 720 * 60 * 60; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/verify-two-factor.mjs +init_error2(); +async function verifyTwoFactor(ctx) { + const invalid = (errorKey) => { + throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES[errorKey]); + }; + const session = await getSessionFromCtx(ctx); + if (!session) { + const twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME); + const signedTwoFactorCookie = await ctx.getSignedCookie(twoFactorCookie.name, ctx.context.secret); + if (!signedTwoFactorCookie) throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE); + const verificationToken = await ctx.context.internalAdapter.findVerificationValue(signedTwoFactorCookie); + if (!verificationToken) throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE); + const user = await ctx.context.internalAdapter.findUserById(verificationToken.value); + if (!user) throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE); + const dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); + return { + valid: async (ctx2) => { + const session2 = await ctx2.context.internalAdapter.createSession(verificationToken.value, !!dontRememberMe); + if (!session2) throw APIError2.from("INTERNAL_SERVER_ERROR", { + message: "failed to create session", + code: "FAILED_TO_CREATE_SESSION" + }); + await ctx2.context.internalAdapter.deleteVerificationByIdentifier(signedTwoFactorCookie); + await setSessionCookie(ctx2, { + session: session2, + user + }); + expireCookie(ctx2, twoFactorCookie); + if (ctx2.body.trustDevice) { + const maxAge = ctx2.context.getPlugin("two-factor").options?.trustDeviceMaxAge ?? 2592e3; + const trustDeviceCookie = ctx2.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge }); + const trustIdentifier = `trust-device-${generateRandomString(32)}`; + const token = await createHMAC("SHA-256", "base64urlnopad").sign(ctx2.context.secret, `${user.id}!${trustIdentifier}`); + await ctx2.context.internalAdapter.createVerificationValue({ + value: user.id, + identifier: trustIdentifier, + expiresAt: new Date(Date.now() + maxAge * 1e3) + }); + await ctx2.setSignedCookie(trustDeviceCookie.name, `${token}!${trustIdentifier}`, ctx2.context.secret, trustDeviceCookie.attributes); + expireCookie(ctx2, ctx2.context.authCookies.dontRememberToken); + } + return ctx2.json({ + token: session2.token, + user: parseUserOutput(ctx2.context.options, user) + }); + }, + invalid, + session: { + session: null, + user + }, + key: signedTwoFactorCookie + }; + } + return { + valid: async (ctx2) => { + return ctx2.json({ + token: session.session.token, + user: parseUserOutput(ctx2.context.options, session.user) + }); + }, + invalid, + session, + key: `${session.user.id}!${session.session.id}` + }; +} + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/backup-codes/index.mjs +init_error2(); +init_json(); +init_zod(); +function generateBackupCodesFn(options) { + return Array.from({ length: options?.amount ?? 10 }).fill(null).map(() => generateRandomString(options?.length ?? 10, "a-z", "0-9", "A-Z")).map((code) => `${code.slice(0, 5)}-${code.slice(5)}`); +} +async function generateBackupCodes(secret, options) { + const backupCodes = options?.customBackupCodesGenerate ? options.customBackupCodesGenerate() : generateBackupCodesFn(options); + if (options?.storeBackupCodes === "encrypted") return { + backupCodes, + encryptedBackupCodes: await symmetricEncrypt({ + data: JSON.stringify(backupCodes), + key: secret + }) + }; + if (typeof options?.storeBackupCodes === "object" && "encrypt" in options?.storeBackupCodes) return { + backupCodes, + encryptedBackupCodes: await options?.storeBackupCodes.encrypt(JSON.stringify(backupCodes)) + }; + return { + backupCodes, + encryptedBackupCodes: JSON.stringify(backupCodes) + }; +} +async function verifyBackupCode(data, key, options) { + const codes = await getBackupCodes(data.backupCodes, key, options); + if (!codes) return { + status: false, + updated: null + }; + return { + status: codes.includes(data.code), + updated: codes.filter((code) => code !== data.code) + }; +} +async function getBackupCodes(backupCodes, key, options) { + if (options?.storeBackupCodes === "encrypted") return safeJSONParse(await symmetricDecrypt({ + key, + data: backupCodes + })); + if (typeof options?.storeBackupCodes === "object" && "decrypt" in options?.storeBackupCodes) return safeJSONParse(await options?.storeBackupCodes.decrypt(backupCodes)); + return safeJSONParse(backupCodes); +} +var verifyBackupCodeBodySchema = object({ + code: string2().meta({ description: `A backup code to verify. Eg: "123456"` }), + disableSession: boolean2().meta({ description: "If true, the session cookie will not be set." }).optional(), + trustDevice: boolean2().meta({ description: "If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true" }).optional() +}); +var viewBackupCodesBodySchema = object({ userId: coerce_exports.string().meta({ description: `The user ID to view all backup codes. Eg: "user-id"` }) }); +var backupCode2fa = (opts) => { + const twoFactorTable = "twoFactor"; + const passwordSchema = string2().meta({ description: "The users password." }); + const generateBackupCodesBodySchema = opts.allowPasswordless ? object({ password: passwordSchema.optional() }) : object({ password: passwordSchema }); + return { + id: "backup_code", + version: PACKAGE_VERSION, + endpoints: { + verifyBackupCode: createAuthEndpoint("/two-factor/verify-backup-code", { + method: "POST", + body: verifyBackupCodeBodySchema, + metadata: { openapi: { + description: "Verify a backup code for two-factor authentication", + responses: { "200": { + description: "Backup code verified successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + user: { + type: "object", + properties: { + id: { + type: "string", + description: "Unique identifier of the user" + }, + email: { + type: "string", + format: "email", + nullable: true, + description: "User's email address" + }, + emailVerified: { + type: "boolean", + nullable: true, + description: "Whether the email is verified" + }, + name: { + type: "string", + nullable: true, + description: "User's name" + }, + image: { + type: "string", + format: "uri", + nullable: true, + description: "User's profile image URL" + }, + twoFactorEnabled: { + type: "boolean", + description: "Whether two-factor authentication is enabled for the user" + }, + createdAt: { + type: "string", + format: "date-time", + description: "Timestamp when the user was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "Timestamp when the user was last updated" + } + }, + required: [ + "id", + "twoFactorEnabled", + "createdAt", + "updatedAt" + ], + description: "The authenticated user object with two-factor details" + }, + session: { + type: "object", + properties: { + token: { + type: "string", + description: "Session token" + }, + userId: { + type: "string", + description: "ID of the user associated with the session" + }, + createdAt: { + type: "string", + format: "date-time", + description: "Timestamp when the session was created" + }, + expiresAt: { + type: "string", + format: "date-time", + description: "Timestamp when the session expires" + } + }, + required: [ + "token", + "userId", + "createdAt", + "expiresAt" + ], + description: "The current session object, included unless disableSession is true" + } + }, + required: ["user", "session"] + } } } + } } + } } + }, async (ctx) => { + const { session, valid } = await verifyTwoFactor(ctx); + const user = session.user; + const twoFactor2 = await ctx.context.adapter.findOne({ + model: twoFactorTable, + where: [{ + field: "userId", + value: user.id + }] + }); + if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED); + const validate = await verifyBackupCode({ + backupCodes: twoFactor2.backupCodes, + code: ctx.body.code + }, ctx.context.secretConfig, opts); + if (!validate.status) throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE); + const updatedBackupCodes = await symmetricEncrypt({ + key: ctx.context.secretConfig, + data: JSON.stringify(validate.updated) + }); + if (!await ctx.context.adapter.update({ + model: twoFactorTable, + update: { backupCodes: updatedBackupCodes }, + where: [{ + field: "id", + value: twoFactor2.id + }, { + field: "backupCodes", + value: twoFactor2.backupCodes + }] + })) throw APIError2.fromStatus("CONFLICT", { message: "Failed to verify backup code. Please try again." }); + if (!ctx.body.disableSession) return valid(ctx); + return ctx.json({ + token: session.session?.token, + user: parseUserOutput(ctx.context.options, session.user) + }); + }), + generateBackupCodes: createAuthEndpoint("/two-factor/generate-backup-codes", { + method: "POST", + body: generateBackupCodesBodySchema, + use: [sessionMiddleware], + metadata: { openapi: { + description: "Generate new backup codes for two-factor authentication", + responses: { "200": { + description: "Backup codes generated successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + status: { + type: "boolean", + description: "Indicates if the backup codes were generated successfully", + enum: [true] + }, + backupCodes: { + type: "array", + items: { type: "string" }, + description: "Array of generated backup codes in plain text" + } + }, + required: ["status", "backupCodes"] + } } } + } } + } } + }, async (ctx) => { + const user = ctx.context.session.user; + if (!user.twoFactorEnabled) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED); + if (await shouldRequirePassword(ctx, user.id, opts.allowPasswordless)) { + if (!ctx.body.password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + await ctx.context.password.checkPassword(user.id, ctx); + } + const twoFactor2 = await ctx.context.adapter.findOne({ + model: twoFactorTable, + where: [{ + field: "userId", + value: user.id + }] + }); + if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED); + const backupCodes = await generateBackupCodes(ctx.context.secretConfig, opts); + await ctx.context.adapter.update({ + model: twoFactorTable, + update: { backupCodes: backupCodes.encryptedBackupCodes }, + where: [{ + field: "id", + value: twoFactor2.id + }] + }); + return ctx.json({ + status: true, + backupCodes: backupCodes.backupCodes + }); + }), + viewBackupCodes: createAuthEndpoint({ + method: "POST", + body: viewBackupCodesBodySchema + }, async (ctx) => { + const twoFactor2 = await ctx.context.adapter.findOne({ + model: twoFactorTable, + where: [{ + field: "userId", + value: ctx.body.userId + }] + }); + if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED); + const decryptedBackupCodes = await getBackupCodes(twoFactor2.backupCodes, ctx.context.secretConfig, opts); + if (!decryptedBackupCodes) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE); + return ctx.json({ + status: true, + backupCodes: decryptedBackupCodes + }); + }) + } + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/utils.mjs +var defaultKeyHasher2 = async (token) => { + const hash2 = await createHash("SHA-256").digest(new TextEncoder().encode(token)); + return base64Url.encode(new Uint8Array(hash2), { padding: false }); +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/otp/index.mjs +init_error2(); +init_zod(); +var verifyOTPBodySchema = object({ + code: string2().meta({ description: 'The otp code to verify. Eg: "012345"' }), + trustDevice: boolean2().optional().meta({ description: "If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true" }) +}); +var send2FaOTPBodySchema = object({ trustDevice: boolean2().optional().meta({ description: "If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true" }) }).optional(); +var otp2fa = (options) => { + const opts = { + storeOTP: "plain", + digits: 6, + ...options, + period: (options?.period || 3) * 60 * 1e3 + }; + async function storeOTP(ctx, otp) { + if (opts.storeOTP === "hashed") return await defaultKeyHasher2(otp); + if (typeof opts.storeOTP === "object" && "hash" in opts.storeOTP) return await opts.storeOTP.hash(otp); + if (typeof opts.storeOTP === "object" && "encrypt" in opts.storeOTP) return await opts.storeOTP.encrypt(otp); + if (opts.storeOTP === "encrypted") return await symmetricEncrypt({ + key: ctx.context.secretConfig, + data: otp + }); + return otp; + } + async function decryptOrHashForComparison(ctx, storedOtp, userInput) { + if (opts.storeOTP === "hashed") return [storedOtp, await defaultKeyHasher2(userInput)]; + if (opts.storeOTP === "encrypted") return [await symmetricDecrypt({ + key: ctx.context.secretConfig, + data: storedOtp + }), userInput]; + if (typeof opts.storeOTP === "object" && "encrypt" in opts.storeOTP) return [await opts.storeOTP.decrypt(storedOtp), userInput]; + if (typeof opts.storeOTP === "object" && "hash" in opts.storeOTP) return [storedOtp, await opts.storeOTP.hash(userInput)]; + return [storedOtp, userInput]; + } + return { + id: "otp", + version: PACKAGE_VERSION, + endpoints: { + sendTwoFactorOTP: createAuthEndpoint("/two-factor/send-otp", { + method: "POST", + body: send2FaOTPBodySchema, + metadata: { openapi: { + summary: "Send two factor OTP", + description: "Send two factor OTP to the user", + responses: { 200: { + description: "Successful response", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } } + }, async (ctx) => { + if (!options || !options.sendOTP) { + ctx.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."); + throw APIError2.from("BAD_REQUEST", { + message: "otp isn't configured", + code: "OTP_NOT_CONFIGURED" + }); + } + const { session, key } = await verifyTwoFactor(ctx); + const code = generateRandomString(opts.digits, "0-9"); + const hashedCode = await storeOTP(ctx, code); + await ctx.context.internalAdapter.createVerificationValue({ + value: `${hashedCode}:0`, + identifier: `2fa-otp-${key}`, + expiresAt: new Date(Date.now() + opts.period) + }); + const sendOTPResult = options.sendOTP({ + user: session.user, + otp: code + }, ctx); + if (sendOTPResult instanceof Promise) await ctx.context.runInBackgroundOrAwait(sendOTPResult.catch((e) => { + ctx.context.logger.error("Failed to send two-factor OTP", e); + })); + return ctx.json({ status: true }); + }), + verifyTwoFactorOTP: createAuthEndpoint("/two-factor/verify-otp", { + method: "POST", + body: verifyOTPBodySchema, + metadata: { openapi: { + summary: "Verify two factor OTP", + description: "Verify two factor OTP", + responses: { "200": { + description: "Two-factor OTP verified successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + token: { + type: "string", + description: "Session token for the authenticated session" + }, + user: { + type: "object", + properties: { + id: { + type: "string", + description: "Unique identifier of the user" + }, + email: { + type: "string", + format: "email", + nullable: true, + description: "User's email address" + }, + emailVerified: { + type: "boolean", + nullable: true, + description: "Whether the email is verified" + }, + name: { + type: "string", + nullable: true, + description: "User's name" + }, + image: { + type: "string", + format: "uri", + nullable: true, + description: "User's profile image URL" + }, + createdAt: { + type: "string", + format: "date-time", + description: "Timestamp when the user was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "Timestamp when the user was last updated" + } + }, + required: [ + "id", + "createdAt", + "updatedAt" + ], + description: "The authenticated user object" + } + }, + required: ["token", "user"] + } } } + } } + } } + }, async (ctx) => { + const { session, key, valid, invalid } = await verifyTwoFactor(ctx); + const toCheckOtp = await ctx.context.internalAdapter.findVerificationValue(`2fa-otp-${key}`); + const [otp, counter] = toCheckOtp?.value?.split(":") ?? []; + if (!toCheckOtp || toCheckOtp.expiresAt < /* @__PURE__ */ new Date()) { + if (toCheckOtp) await ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`); + throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.OTP_HAS_EXPIRED); + } + const allowedAttempts = options?.allowedAttempts || 5; + if (parseInt(counter) >= allowedAttempts) { + await ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`); + throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE); + } + const [storedValue, inputValue] = await decryptOrHashForComparison(ctx, otp, ctx.body.code); + if (constantTimeEqual(new TextEncoder().encode(storedValue), new TextEncoder().encode(inputValue))) { + if (!session.user.twoFactorEnabled) { + if (!session.session) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); + const updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { twoFactorEnabled: true }); + const newSession = await ctx.context.internalAdapter.createSession(session.user.id, false, session.session); + await setSessionCookie(ctx, { + session: newSession, + user: updatedUser + }); + await ctx.context.internalAdapter.deleteSession(session.session.token); + return ctx.json({ + token: newSession.token, + user: parseUserOutput(ctx.context.options, updatedUser) + }); + } + return valid(ctx); + } else { + await ctx.context.internalAdapter.updateVerificationByIdentifier(`2fa-otp-${key}`, { value: `${otp}:${(parseInt(counter, 10) || 0) + 1}` }); + return invalid("INVALID_CODE"); + } + }) + } + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/schema.mjs +var schema2 = { + user: { fields: { twoFactorEnabled: { + type: "boolean", + required: false, + defaultValue: false, + input: false + } } }, + twoFactor: { fields: { + secret: { + type: "string", + required: true, + returned: false, + index: true + }, + backupCodes: { + type: "string", + required: true, + returned: false + }, + userId: { + type: "string", + required: true, + returned: false, + references: { + model: "user", + field: "id" + }, + index: true + }, + verified: { + type: "boolean", + required: false, + defaultValue: true, + input: false + } + } } +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/totp/index.mjs +init_error2(); +init_zod(); + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/base32.mjs +function getAlphabet2(hex4) { + return hex4 ? "0123456789ABCDEFGHIJKLMNOPQRSTUV" : "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; +} +function createDecodeMap(alphabet) { + const decodeMap = /* @__PURE__ */ new Map(); + for (let i = 0; i < alphabet.length; i++) { + decodeMap.set(alphabet[i], i); + } + return decodeMap; +} +function base32Encode(data, alphabet, padding) { + let result = ""; + let buffer = 0; + let shift = 0; + for (const byte of data) { + buffer = buffer << 8 | byte; + shift += 8; + while (shift >= 5) { + shift -= 5; + result += alphabet[buffer >> shift & 31]; + } + } + if (shift > 0) { + result += alphabet[buffer << 5 - shift & 31]; + } + if (padding) { + const padCount = (8 - result.length % 8) % 8; + result += "=".repeat(padCount); + } + return result; +} +function base32Decode(data, alphabet) { + const decodeMap = createDecodeMap(alphabet); + const result = []; + let buffer = 0; + let bitsCollected = 0; + for (const char of data) { + if (char === "=") + break; + const value = decodeMap.get(char); + if (value === void 0) { + throw new Error(`Invalid Base32 character: ${char}`); + } + buffer = buffer << 5 | value; + bitsCollected += 5; + while (bitsCollected >= 8) { + bitsCollected -= 8; + result.push(buffer >> bitsCollected & 255); + } + } + return Uint8Array.from(result); +} +var base32 = { + /** + * Encodes data into a Base32 string. + * @param data - The data to encode (ArrayBuffer, TypedArray, or string). + * @param options - Encoding options. + * @returns The Base32 encoded string. + */ + encode(data, options = {}) { + const alphabet = getAlphabet2(false); + const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data); + return base32Encode(buffer, alphabet, options.padding ?? true); + }, + /** + * Decodes a Base32 string into a Uint8Array. + * @param data - The Base32 encoded string or ArrayBuffer/TypedArray. + * @returns The decoded Uint8Array. + */ + decode(data) { + if (typeof data !== "string") { + data = new TextDecoder().decode(data); + } + const alphabet = getAlphabet2(false); + return base32Decode(data, alphabet); + } +}; + +// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/otp.mjs +var defaultPeriod = 30; +var defaultDigits = 6; +async function generateHOTP(secret, { + counter, + digits, + hash: hash2 = "SHA-1" +}) { + const _digits = digits ?? defaultDigits; + if (_digits < 1 || _digits > 8) { + throw new TypeError("Digits must be between 1 and 8"); + } + const buffer = new ArrayBuffer(8); + new DataView(buffer).setBigUint64(0, BigInt(counter), false); + const bytes = new Uint8Array(buffer); + const hmacResult = new Uint8Array(await createHMAC(hash2).sign(secret, bytes)); + const offset = hmacResult[hmacResult.length - 1] & 15; + const truncated = (hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255; + const otp = truncated % 10 ** _digits; + return otp.toString().padStart(_digits, "0"); +} +async function generateTOTP(secret, options) { + const digits = options?.digits ?? defaultDigits; + const period = options?.period ?? defaultPeriod; + const milliseconds = period * 1e3; + const counter = Math.floor(Date.now() / milliseconds); + return await generateHOTP(secret, { counter, digits, hash: options?.hash }); +} +async function verifyTOTP(otp, { + window: window2 = 1, + digits = defaultDigits, + secret, + period = defaultPeriod +}) { + const milliseconds = period * 1e3; + const counter = Math.floor(Date.now() / milliseconds); + for (let i = -window2; i <= window2; i++) { + const generatedOTP = await generateHOTP(secret, { + counter: counter + i, + digits + }); + if (otp === generatedOTP) { + return true; + } + } + return false; +} +function generateQRCode({ + issuer, + account, + secret, + digits = defaultDigits, + period = defaultPeriod +}) { + const encodedIssuer = encodeURIComponent(issuer); + const encodedAccountName = encodeURIComponent(account); + const baseURI = `otpauth://totp/${encodedIssuer}:${encodedAccountName}`; + const params = new URLSearchParams({ + secret: base32.encode(secret, { + padding: false + }), + issuer + }); + if (digits !== void 0) { + params.set("digits", digits.toString()); + } + if (period !== void 0) { + params.set("period", period.toString()); + } + return `${baseURI}?${params.toString()}`; +} +var createOTP = (secret, opts) => { + const digits = opts?.digits ?? defaultDigits; + const period = opts?.period ?? defaultPeriod; + return { + hotp: (counter) => generateHOTP(secret, { counter, digits }), + totp: () => generateTOTP(secret, { digits, period }), + verify: (otp, options) => verifyTOTP(otp, { secret, digits, period, ...options }), + url: (issuer, account) => generateQRCode({ issuer, account, secret, digits, period }) + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/totp/index.mjs +var generateTOTPBodySchema = object({ secret: string2().meta({ description: "The secret to generate the TOTP code" }) }); +var verifyTOTPBodySchema = object({ + code: string2().meta({ description: 'The otp code to verify. Eg: "012345"' }), + trustDevice: boolean2().meta({ description: "If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true" }).optional() +}); +var totp2fa = (options) => { + const opts = { + ...options, + digits: options?.digits || 6, + period: options?.period || 30 + }; + const passwordSchema = string2().meta({ description: "User password" }); + const getTOTPURIBodySchema = options?.allowPasswordless ? object({ password: passwordSchema.optional() }) : object({ password: passwordSchema }); + const twoFactorTable = "twoFactor"; + return { + id: "totp", + version: PACKAGE_VERSION, + endpoints: { + generateTOTP: createAuthEndpoint({ + method: "POST", + body: generateTOTPBodySchema, + metadata: { openapi: { + summary: "Generate TOTP code", + description: "Use this endpoint to generate a TOTP code", + responses: { 200: { + description: "Successful response", + content: { "application/json": { schema: { + type: "object", + properties: { code: { type: "string" } } + } } } + } } + } } + }, async (ctx) => { + if (options?.disable) { + ctx.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"); + throw APIError2.from("BAD_REQUEST", { + message: "totp isn't configured", + code: "TOTP_NOT_CONFIGURED" + }); + } + return { code: await createOTP(ctx.body.secret, { + period: opts.period, + digits: opts.digits + }).totp() }; + }), + getTOTPURI: createAuthEndpoint("/two-factor/get-totp-uri", { + method: "POST", + use: [sessionMiddleware], + body: getTOTPURIBodySchema, + metadata: { openapi: { + summary: "Get TOTP URI", + description: "Use this endpoint to get the TOTP URI", + responses: { 200: { + description: "Successful response", + content: { "application/json": { schema: { + type: "object", + properties: { totpURI: { type: "string" } } + } } } + } } + } } + }, async (ctx) => { + if (options?.disable) { + ctx.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"); + throw APIError2.from("BAD_REQUEST", { + message: "totp isn't configured", + code: "TOTP_NOT_CONFIGURED" + }); + } + const user = ctx.context.session.user; + const twoFactor2 = await ctx.context.adapter.findOne({ + model: twoFactorTable, + where: [{ + field: "userId", + value: user.id + }] + }); + if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED); + const secret = await symmetricDecrypt({ + key: ctx.context.secretConfig, + data: twoFactor2.secret + }); + if (await shouldRequirePassword(ctx, user.id, options?.allowPasswordless)) { + if (!ctx.body.password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + await ctx.context.password.checkPassword(user.id, ctx); + } + return { totpURI: createOTP(secret, { + digits: opts.digits, + period: opts.period + }).url(options?.issuer || ctx.context.appName, user.email) }; + }), + verifyTOTP: createAuthEndpoint("/two-factor/verify-totp", { + method: "POST", + body: verifyTOTPBodySchema, + metadata: { openapi: { + summary: "Verify two factor TOTP", + description: "Verify two factor TOTP", + responses: { 200: { + description: "Successful response", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } } + }, async (ctx) => { + if (options?.disable) { + ctx.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"); + throw APIError2.from("BAD_REQUEST", { + message: "totp isn't configured", + code: "TOTP_NOT_CONFIGURED" + }); + } + const { session, valid, invalid } = await verifyTwoFactor(ctx); + const user = session.user; + const isSignIn = !session.session; + const twoFactor2 = await ctx.context.adapter.findOne({ + model: twoFactorTable, + where: [{ + field: "userId", + value: user.id + }] + }); + if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED); + if (isSignIn && twoFactor2.verified === false) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED); + if (!await createOTP(await symmetricDecrypt({ + key: ctx.context.secretConfig, + data: twoFactor2.secret + }), { + period: opts.period, + digits: opts.digits + }).verify(ctx.body.code)) return invalid("INVALID_CODE"); + if (twoFactor2.verified !== true) { + if (!user.twoFactorEnabled) { + const activeSession = session.session; + const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: true }); + await setSessionCookie(ctx, { + session: await ctx.context.internalAdapter.createSession(user.id, false, activeSession), + user: updatedUser + }); + await ctx.context.internalAdapter.deleteSession(activeSession.token); + } + await ctx.context.adapter.update({ + model: twoFactorTable, + update: { verified: true }, + where: [{ + field: "id", + value: twoFactor2.id + }] + }); + } + return valid(ctx); + }) + } + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/index.mjs +init_error2(); +init_zod(); +var twoFactor = (options) => { + const opts = { twoFactorTable: "twoFactor" }; + const trustDeviceMaxAge = options?.trustDeviceMaxAge ?? 2592e3; + const allowPasswordless = options?.allowPasswordless; + const backupCodeOptions = { + storeBackupCodes: "encrypted", + ...options?.backupCodeOptions + }; + const totp = totp2fa({ + ...options?.totpOptions, + allowPasswordless: options?.totpOptions?.allowPasswordless ?? allowPasswordless + }); + const backupCode = backupCode2fa({ + ...backupCodeOptions, + allowPasswordless: options?.backupCodeOptions?.allowPasswordless ?? allowPasswordless + }); + const otp = otp2fa(options?.otpOptions); + const passwordSchema = string2().meta({ description: "User password" }); + const enableTwoFactorBodySchema = allowPasswordless ? object({ + password: passwordSchema.optional(), + issuer: string2().meta({ description: "Custom issuer for the TOTP URI" }).optional() + }) : object({ + password: passwordSchema, + issuer: string2().meta({ description: "Custom issuer for the TOTP URI" }).optional() + }); + const disableTwoFactorBodySchema = allowPasswordless ? object({ password: passwordSchema.optional() }) : object({ password: passwordSchema }); + return { + id: "two-factor", + version: PACKAGE_VERSION, + endpoints: { + ...totp.endpoints, + ...otp.endpoints, + ...backupCode.endpoints, + enableTwoFactor: createAuthEndpoint("/two-factor/enable", { + method: "POST", + body: enableTwoFactorBodySchema, + use: [sessionMiddleware], + metadata: { openapi: { + summary: "Enable two factor authentication", + description: "Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.", + responses: { 200: { + description: "Successful response", + content: { "application/json": { schema: { + type: "object", + properties: { + totpURI: { + type: "string", + description: "TOTP URI" + }, + backupCodes: { + type: "array", + items: { type: "string" }, + description: "Backup codes" + } + } + } } } + } } + } } + }, async (ctx) => { + const user = ctx.context.session.user; + const { password, issuer } = ctx.body; + if (await shouldRequirePassword(ctx, user.id, allowPasswordless)) { + if (!password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + if (!await validatePassword(ctx, { + password, + userId: user.id + })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + } + const secret = generateRandomString(32); + const encryptedSecret = await symmetricEncrypt({ + key: ctx.context.secretConfig, + data: secret + }); + const backupCodes = await generateBackupCodes(ctx.context.secretConfig, backupCodeOptions); + if (options?.skipVerificationOnEnable) { + const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: true }); + await setSessionCookie(ctx, { + session: await ctx.context.internalAdapter.createSession(updatedUser.id, false, ctx.context.session.session), + user: updatedUser + }); + await ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token); + } + const existingTwoFactor = await ctx.context.adapter.findOne({ + model: opts.twoFactorTable, + where: [{ + field: "userId", + value: user.id + }] + }); + await ctx.context.adapter.deleteMany({ + model: opts.twoFactorTable, + where: [{ + field: "userId", + value: user.id + }] + }); + await ctx.context.adapter.create({ + model: opts.twoFactorTable, + data: { + secret: encryptedSecret, + backupCodes: backupCodes.encryptedBackupCodes, + userId: user.id, + verified: existingTwoFactor != null && existingTwoFactor.verified !== false || !!options?.skipVerificationOnEnable + } + }); + const totpURI = createOTP(secret, { + digits: options?.totpOptions?.digits || 6, + period: options?.totpOptions?.period + }).url(issuer || options?.issuer || ctx.context.appName, user.email); + return ctx.json({ + totpURI, + backupCodes: backupCodes.backupCodes + }); + }), + disableTwoFactor: createAuthEndpoint("/two-factor/disable", { + method: "POST", + body: disableTwoFactorBodySchema, + use: [sessionMiddleware], + metadata: { openapi: { + summary: "Disable two factor authentication", + description: "Use this endpoint to disable two factor authentication.", + responses: { 200: { + description: "Successful response", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } } + }, async (ctx) => { + const user = ctx.context.session.user; + const { password } = ctx.body; + if (await shouldRequirePassword(ctx, user.id, allowPasswordless)) { + if (!password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + if (!await validatePassword(ctx, { + password, + userId: user.id + })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); + } + const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: false }); + await ctx.context.adapter.delete({ + model: opts.twoFactorTable, + where: [{ + field: "userId", + value: updatedUser.id + }] + }); + await setSessionCookie(ctx, { + session: await ctx.context.internalAdapter.createSession(updatedUser.id, false, ctx.context.session.session), + user: updatedUser + }); + await ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token); + const disableTrustCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge }); + const disableTrustValue = await ctx.getSignedCookie(disableTrustCookie.name, ctx.context.secret); + if (disableTrustValue) { + const [, trustId] = disableTrustValue.split("!"); + if (trustId) await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustId); + expireCookie(ctx, disableTrustCookie); + } + return ctx.json({ status: true }); + }) + }, + options, + hooks: { after: [{ + matcher(context) { + return context.path === "/sign-in/email" || context.path === "/sign-in/username" || context.path === "/sign-in/phone-number"; + }, + handler: createAuthMiddleware(async (ctx) => { + const data = ctx.context.newSession; + if (!data) return; + if (!data?.user.twoFactorEnabled) return; + const trustDeviceCookieAttrs = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge }); + const trustDeviceCookie = await ctx.getSignedCookie(trustDeviceCookieAttrs.name, ctx.context.secret); + if (trustDeviceCookie) { + const [token, trustIdentifier] = trustDeviceCookie.split("!"); + if (token && trustIdentifier) { + if (token === await createHMAC("SHA-256", "base64urlnopad").sign(ctx.context.secret, `${data.user.id}!${trustIdentifier}`)) { + const verificationRecord = await ctx.context.internalAdapter.findVerificationValue(trustIdentifier); + if (verificationRecord && verificationRecord.value === data.user.id && verificationRecord.expiresAt > /* @__PURE__ */ new Date()) { + await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustIdentifier); + const newTrustIdentifier = `trust-device-${generateRandomString(32)}`; + const newToken = await createHMAC("SHA-256", "base64urlnopad").sign(ctx.context.secret, `${data.user.id}!${newTrustIdentifier}`); + await ctx.context.internalAdapter.createVerificationValue({ + value: data.user.id, + identifier: newTrustIdentifier, + expiresAt: new Date(Date.now() + trustDeviceMaxAge * 1e3) + }); + const newTrustDeviceCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge }); + await ctx.setSignedCookie(newTrustDeviceCookie.name, `${newToken}!${newTrustIdentifier}`, ctx.context.secret, trustDeviceCookieAttrs.attributes); + return; + } + } + } + expireCookie(ctx, trustDeviceCookieAttrs); + } + deleteSessionCookie(ctx, true); + await ctx.context.internalAdapter.deleteSession(data.session.token); + const maxAge = options?.twoFactorCookieMaxAge ?? 600; + const twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME, { maxAge }); + const identifier = `2fa-${generateRandomString(20)}`; + await ctx.context.internalAdapter.createVerificationValue({ + value: data.user.id, + identifier, + expiresAt: new Date(Date.now() + maxAge * 1e3) + }); + await ctx.setSignedCookie(twoFactorCookie.name, identifier, ctx.context.secret, twoFactorCookie.attributes); + const twoFactorMethods = []; + if (!options?.totpOptions?.disable) { + const userTotpSecret = await ctx.context.adapter.findOne({ + model: opts.twoFactorTable, + where: [{ + field: "userId", + value: data.user.id + }] + }); + if (userTotpSecret && userTotpSecret.verified !== false) twoFactorMethods.push("totp"); + } + if (options?.otpOptions?.sendOTP) twoFactorMethods.push("otp"); + return ctx.json({ + twoFactorRedirect: true, + twoFactorMethods + }); + }) + }] }, + schema: mergeSchema(schema2, { + ...options?.schema, + twoFactor: { + ...options?.schema?.twoFactor, + ...options?.twoFactorTable ? { modelName: options.twoFactorTable } : {} + } + }), + rateLimit: [{ + pathMatcher(path3) { + return path3.startsWith("/two-factor/"); + }, + window: 10, + max: 3 + }], + $ERROR_CODES: TWO_FACTOR_ERROR_CODES + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/magic-link/utils.mjs +var defaultKeyHasher3 = async (otp) => { + const hash2 = await createHash("SHA-256").digest(new TextEncoder().encode(otp)); + return base64Url.encode(new Uint8Array(hash2), { padding: false }); +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/magic-link/index.mjs +init_zod(); +var signInMagicLinkBodySchema = object({ + email: email2().meta({ description: "Email address to send the magic link" }), + name: string2().meta({ description: 'User display name. Only used if the user is registering for the first time. Eg: "my-name"' }).optional(), + callbackURL: string2().meta({ description: "URL to redirect after magic link verification" }).optional(), + newUserCallbackURL: string2().meta({ description: "URL to redirect after new user signup. Only used if the user is registering for the first time." }).optional(), + errorCallbackURL: string2().meta({ description: "URL to redirect after error." }).optional(), + metadata: record(string2(), any()).meta({ description: "Additional metadata to pass to sendMagicLink." }).optional() +}); +var magicLinkVerifyQuerySchema = object({ + token: string2().meta({ description: "Verification token" }), + callbackURL: string2().meta({ description: 'URL to redirect after magic link verification, if not provided the user will be redirected to the root URL. Eg: "/dashboard"' }).optional(), + errorCallbackURL: string2().meta({ description: "URL to redirect after error." }).optional(), + newUserCallbackURL: string2().meta({ description: "URL to redirect after new user signup. Only used if the user is registering for the first time." }).optional() +}); +var magicLink = (options) => { + const opts = { + storeToken: "plain", + allowedAttempts: 1, + ...options + }; + async function storeToken(ctx, token) { + if (opts.storeToken === "hashed") return await defaultKeyHasher3(token); + if (typeof opts.storeToken === "object" && "type" in opts.storeToken && opts.storeToken.type === "custom-hasher") return await opts.storeToken.hash(token); + return token; + } + return { + id: "magic-link", + version: PACKAGE_VERSION, + endpoints: { + signInMagicLink: createAuthEndpoint("/sign-in/magic-link", { + method: "POST", + requireHeaders: true, + body: signInMagicLinkBodySchema, + metadata: { openapi: { + operationId: "signInWithMagicLink", + description: "Sign in with magic link", + responses: { 200: { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } } + }, async (ctx) => { + const { email: email3, metadata } = ctx.body; + const verificationToken = opts?.generateToken ? await opts.generateToken(email3) : generateRandomString(32, "a-z", "A-Z"); + const storedToken = await storeToken(ctx, verificationToken); + await ctx.context.internalAdapter.createVerificationValue({ + identifier: storedToken, + value: JSON.stringify({ + email: email3, + name: ctx.body.name, + attempt: 0 + }), + expiresAt: new Date(Date.now() + (opts.expiresIn || 300) * 1e3) + }); + const realBaseURL = new URL(ctx.context.baseURL); + const pathname = realBaseURL.pathname === "/" ? "" : realBaseURL.pathname; + const basePath = pathname ? "" : ctx.context.options.basePath || ""; + const url2 = new URL(`${pathname}${basePath}/magic-link/verify`, realBaseURL.origin); + url2.searchParams.set("token", verificationToken); + url2.searchParams.set("callbackURL", ctx.body.callbackURL || "/"); + if (ctx.body.newUserCallbackURL) url2.searchParams.set("newUserCallbackURL", ctx.body.newUserCallbackURL); + if (ctx.body.errorCallbackURL) url2.searchParams.set("errorCallbackURL", ctx.body.errorCallbackURL); + await options.sendMagicLink({ + email: email3, + url: url2.toString(), + token: verificationToken, + metadata + }, ctx); + return ctx.json({ status: true }); + }), + magicLinkVerify: createAuthEndpoint("/magic-link/verify", { + method: "GET", + query: magicLinkVerifyQuerySchema, + use: [ + originCheck((ctx) => { + return ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : "/"; + }), + originCheck((ctx) => { + return ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : "/"; + }), + originCheck((ctx) => { + return ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : "/"; + }) + ], + requireHeaders: true, + metadata: { openapi: { + operationId: "verifyMagicLink", + description: "Verify magic link", + responses: { 200: { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + session: { $ref: "#/components/schemas/Session" }, + user: { $ref: "#/components/schemas/User" } + } + } } } + } } + } } + }, async (ctx) => { + const token = ctx.query.token; + const callbackURL = new URL(ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : "/", ctx.context.baseURL).toString(); + const errorCallbackURL = new URL(ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : callbackURL, ctx.context.baseURL); + function redirectWithError(error49) { + errorCallbackURL.searchParams.set("error", error49); + throw ctx.redirect(errorCallbackURL.toString()); + } + const newUserCallbackURL = new URL(ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : callbackURL, ctx.context.baseURL).toString(); + const storedToken = await storeToken(ctx, token); + const tokenValue = await ctx.context.internalAdapter.findVerificationValue(storedToken); + if (!tokenValue) redirectWithError("INVALID_TOKEN"); + if (tokenValue.expiresAt < /* @__PURE__ */ new Date()) { + await ctx.context.internalAdapter.deleteVerificationByIdentifier(storedToken); + redirectWithError("EXPIRED_TOKEN"); + } + const { email: email3, name, attempt = 0 } = JSON.parse(tokenValue.value); + if (attempt >= opts.allowedAttempts) { + await ctx.context.internalAdapter.deleteVerificationByIdentifier(storedToken); + redirectWithError("ATTEMPTS_EXCEEDED"); + } + await ctx.context.internalAdapter.updateVerificationByIdentifier(storedToken, { value: JSON.stringify({ + email: email3, + name, + attempt: attempt + 1 + }) }); + let isNewUser = false; + let user = await ctx.context.internalAdapter.findUserByEmail(email3).then((res) => res?.user); + if (!user) if (!opts.disableSignUp) { + const newUser = await ctx.context.internalAdapter.createUser({ + email: email3, + emailVerified: true, + name: name || "" + }); + isNewUser = true; + user = newUser; + if (!user) redirectWithError("failed_to_create_user"); + } else redirectWithError("new_user_signup_disabled"); + if (!user.emailVerified) user = await ctx.context.internalAdapter.updateUser(user.id, { emailVerified: true }); + const session = await ctx.context.internalAdapter.createSession(user.id); + if (!session) redirectWithError("failed_to_create_session"); + await setSessionCookie(ctx, { + session, + user + }); + if (!ctx.query.callbackURL) return ctx.json({ + token: session.token, + user: parseUserOutput(ctx.context.options, user), + session: parseSessionOutput(ctx.context.options, session) + }); + if (isNewUser) throw ctx.redirect(newUserCallbackURL); + throw ctx.redirect(callbackURL); + }) + }, + rateLimit: [{ + pathMatcher(path3) { + return path3.startsWith("/sign-in/magic-link") || path3.startsWith("/magic-link/verify"); + }, + window: opts.rateLimit?.window || 60, + max: opts.rateLimit?.max || 5 + }], + options + }; +}; + +// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/index.mjs +init_adapter(); +init_adapter(); + +// ../../packages/plugins/plugin-auth/dist/index.mjs +init_data(); +init_data(); +init_data(); +init_data(); +init_data(); +init_data(); +init_data(); +init_data(); +init_data(); +init_data(); +init_data(); +init_data(); +var AUTH_MODEL_TO_PROTOCOL = { + user: SystemObjectName.USER, + session: SystemObjectName.SESSION, + account: SystemObjectName.ACCOUNT, + verification: SystemObjectName.VERIFICATION +}; +function convertWhere(where) { + const filter = {}; + for (const condition of where) { + const fieldName = condition.field; + if (condition.operator === "eq") { + filter[fieldName] = condition.value; + } else if (condition.operator === "ne") { + filter[fieldName] = { $ne: condition.value }; + } else if (condition.operator === "in") { + filter[fieldName] = { $in: condition.value }; + } else if (condition.operator === "gt") { + filter[fieldName] = { $gt: condition.value }; + } else if (condition.operator === "gte") { + filter[fieldName] = { $gte: condition.value }; + } else if (condition.operator === "lt") { + filter[fieldName] = { $lt: condition.value }; + } else if (condition.operator === "lte") { + filter[fieldName] = { $lte: condition.value }; + } else if (condition.operator === "contains") { + filter[fieldName] = { $regex: condition.value }; + } + } + return filter; +} +function createObjectQLAdapterFactory(dataEngine) { + return createAdapterFactory({ + config: { + adapterId: "objectql", + // ObjectQL natively supports these types — no extra conversion needed + supportsBooleans: true, + supportsDates: true, + supportsJSON: true + }, + adapter: () => ({ + create: async ({ model, data, select: _select }) => { + const result = await dataEngine.insert(model, data); + return result; + }, + findOne: async ({ model, where, select, join: _join }) => { + const filter = convertWhere(where); + const result = await dataEngine.findOne(model, { where: filter, fields: select }); + return result ? result : null; + }, + findMany: async ({ model, where, limit, offset, sortBy, join: _join }) => { + const filter = where ? convertWhere(where) : {}; + const orderBy = sortBy ? [{ field: sortBy.field, order: sortBy.direction }] : void 0; + const results = await dataEngine.find(model, { + where: filter, + limit: limit || 100, + offset, + orderBy + }); + return results; + }, + count: async ({ model, where }) => { + const filter = where ? convertWhere(where) : {}; + return await dataEngine.count(model, { where: filter }); + }, + update: async ({ model, where, update }) => { + const filter = convertWhere(where); + const record2 = await dataEngine.findOne(model, { where: filter }); + if (!record2) return null; + const result = await dataEngine.update(model, { ...update, id: record2.id }); + return result ? result : null; + }, + updateMany: async ({ model, where, update }) => { + const filter = convertWhere(where); + const records = await dataEngine.find(model, { where: filter }); + for (const record2 of records) { + await dataEngine.update(model, { ...update, id: record2.id }); + } + return records.length; + }, + delete: async ({ model, where }) => { + const filter = convertWhere(where); + const record2 = await dataEngine.findOne(model, { where: filter }); + if (!record2) return; + await dataEngine.delete(model, { where: { id: record2.id } }); + }, + deleteMany: async ({ model, where }) => { + const filter = convertWhere(where); + const records = await dataEngine.find(model, { where: filter }); + for (const record2 of records) { + await dataEngine.delete(model, { where: { id: record2.id } }); + } + return records.length; + } + }) + }); +} +var AUTH_USER_CONFIG = { + modelName: SystemObjectName.USER, + // 'sys_user' + fields: { + emailVerified: "email_verified", + createdAt: "created_at", + updatedAt: "updated_at" + } +}; +var AUTH_SESSION_CONFIG = { + modelName: SystemObjectName.SESSION, + // 'sys_session' + fields: { + userId: "user_id", + expiresAt: "expires_at", + createdAt: "created_at", + updatedAt: "updated_at", + ipAddress: "ip_address", + userAgent: "user_agent" + } +}; +var AUTH_ACCOUNT_CONFIG = { + modelName: SystemObjectName.ACCOUNT, + // 'sys_account' + fields: { + userId: "user_id", + providerId: "provider_id", + accountId: "account_id", + accessToken: "access_token", + refreshToken: "refresh_token", + idToken: "id_token", + accessTokenExpiresAt: "access_token_expires_at", + refreshTokenExpiresAt: "refresh_token_expires_at", + createdAt: "created_at", + updatedAt: "updated_at" + } +}; +var AUTH_VERIFICATION_CONFIG = { + modelName: SystemObjectName.VERIFICATION, + // 'sys_verification' + fields: { + expiresAt: "expires_at", + createdAt: "created_at", + updatedAt: "updated_at" + } +}; +var AUTH_ORGANIZATION_SCHEMA = { + modelName: SystemObjectName.ORGANIZATION, + // 'sys_organization' + fields: { + createdAt: "created_at", + updatedAt: "updated_at" + } +}; +var AUTH_MEMBER_SCHEMA = { + modelName: SystemObjectName.MEMBER, + // 'sys_member' + fields: { + organizationId: "organization_id", + userId: "user_id", + createdAt: "created_at" + } +}; +var AUTH_INVITATION_SCHEMA = { + modelName: SystemObjectName.INVITATION, + // 'sys_invitation' + fields: { + organizationId: "organization_id", + inviterId: "inviter_id", + expiresAt: "expires_at", + createdAt: "created_at", + teamId: "team_id" + } +}; +var AUTH_ORG_SESSION_FIELDS = { + activeOrganizationId: "active_organization_id", + activeTeamId: "active_team_id" +}; +var AUTH_TEAM_SCHEMA = { + modelName: SystemObjectName.TEAM, + // 'sys_team' + fields: { + organizationId: "organization_id", + createdAt: "created_at", + updatedAt: "updated_at" + } +}; +var AUTH_TEAM_MEMBER_SCHEMA = { + modelName: SystemObjectName.TEAM_MEMBER, + // 'sys_team_member' + fields: { + teamId: "team_id", + userId: "user_id", + createdAt: "created_at" + } +}; +var AUTH_TWO_FACTOR_SCHEMA = { + modelName: SystemObjectName.TWO_FACTOR, + // 'sys_two_factor' + fields: { + backupCodes: "backup_codes", + userId: "user_id" + } +}; +var AUTH_TWO_FACTOR_USER_FIELDS = { + twoFactorEnabled: "two_factor_enabled" +}; +function buildTwoFactorPluginSchema() { + return { + twoFactor: AUTH_TWO_FACTOR_SCHEMA, + user: { + fields: AUTH_TWO_FACTOR_USER_FIELDS + } + }; +} +function buildOrganizationPluginSchema() { + return { + organization: AUTH_ORGANIZATION_SCHEMA, + member: AUTH_MEMBER_SCHEMA, + invitation: AUTH_INVITATION_SCHEMA, + team: AUTH_TEAM_SCHEMA, + teamMember: AUTH_TEAM_MEMBER_SCHEMA, + session: { + fields: AUTH_ORG_SESSION_FIELDS + } + }; +} +var AuthManager = class { + constructor(config4) { + this.auth = null; + this.config = config4; + if (config4.authInstance) { + this.auth = config4.authInstance; + } + } + /** + * Get or create the better-auth instance (lazy initialization) + */ + getOrCreateAuth() { + if (!this.auth) { + this.auth = this.createAuthInstance(); + } + return this.auth; + } + /** + * Create a better-auth instance from configuration + */ + createAuthInstance() { + const betterAuthConfig = { + // Base configuration + secret: this.config.secret || this.generateSecret(), + baseURL: this.config.baseUrl || "http://localhost:3000", + basePath: this.config.basePath || "/api/v1/auth", + // Database adapter configuration + database: this.createDatabaseConfig(), + // Model/field mapping: camelCase (better-auth) → snake_case (ObjectStack) + // These declarations tell better-auth the actual table/column names used + // by ObjectStack's protocol layer, enabling automatic transformation via + // createAdapterFactory. + user: { + ...AUTH_USER_CONFIG + }, + account: { + ...AUTH_ACCOUNT_CONFIG + }, + verification: { + ...AUTH_VERIFICATION_CONFIG + }, + // Social / OAuth providers + ...this.config.socialProviders ? { socialProviders: this.config.socialProviders } : {}, + // Email and password configuration + emailAndPassword: { + enabled: this.config.emailAndPassword?.enabled ?? true, + ...this.config.emailAndPassword?.disableSignUp != null ? { disableSignUp: this.config.emailAndPassword.disableSignUp } : {}, + ...this.config.emailAndPassword?.requireEmailVerification != null ? { requireEmailVerification: this.config.emailAndPassword.requireEmailVerification } : {}, + ...this.config.emailAndPassword?.minPasswordLength != null ? { minPasswordLength: this.config.emailAndPassword.minPasswordLength } : {}, + ...this.config.emailAndPassword?.maxPasswordLength != null ? { maxPasswordLength: this.config.emailAndPassword.maxPasswordLength } : {}, + ...this.config.emailAndPassword?.resetPasswordTokenExpiresIn != null ? { resetPasswordTokenExpiresIn: this.config.emailAndPassword.resetPasswordTokenExpiresIn } : {}, + ...this.config.emailAndPassword?.autoSignIn != null ? { autoSignIn: this.config.emailAndPassword.autoSignIn } : {}, + ...this.config.emailAndPassword?.revokeSessionsOnPasswordReset != null ? { revokeSessionsOnPasswordReset: this.config.emailAndPassword.revokeSessionsOnPasswordReset } : {} + }, + // Email verification + ...this.config.emailVerification ? { + emailVerification: { + ...this.config.emailVerification.sendOnSignUp != null ? { sendOnSignUp: this.config.emailVerification.sendOnSignUp } : {}, + ...this.config.emailVerification.sendOnSignIn != null ? { sendOnSignIn: this.config.emailVerification.sendOnSignIn } : {}, + ...this.config.emailVerification.autoSignInAfterVerification != null ? { autoSignInAfterVerification: this.config.emailVerification.autoSignInAfterVerification } : {}, + ...this.config.emailVerification.expiresIn != null ? { expiresIn: this.config.emailVerification.expiresIn } : {} + } + } : {}, + // Session configuration + session: { + ...AUTH_SESSION_CONFIG, + expiresIn: this.config.session?.expiresIn || 60 * 60 * 24 * 7, + // 7 days default + updateAge: this.config.session?.updateAge || 60 * 60 * 24 + // 1 day default + }, + // better-auth plugins — registered based on AuthPluginConfig flags + plugins: this.buildPluginList(), + // Trusted origins for CSRF protection (supports wildcards like "https://*.example.com") + ...this.config.trustedOrigins?.length ? { trustedOrigins: this.config.trustedOrigins } : {}, + // Advanced options (cross-subdomain cookies, secure cookies, CSRF, etc.) + ...this.config.advanced ? { + advanced: { + ...this.config.advanced.crossSubDomainCookies ? { crossSubDomainCookies: this.config.advanced.crossSubDomainCookies } : {}, + ...this.config.advanced.useSecureCookies != null ? { useSecureCookies: this.config.advanced.useSecureCookies } : {}, + ...this.config.advanced.disableCSRFCheck != null ? { disableCSRFCheck: this.config.advanced.disableCSRFCheck } : {}, + ...this.config.advanced.cookiePrefix != null ? { cookiePrefix: this.config.advanced.cookiePrefix } : {} + } + } : {} + }; + return betterAuth(betterAuthConfig); + } + /** + * Build the list of better-auth plugins based on AuthPluginConfig flags. + * + * Each plugin that introduces its own database tables is configured with + * a `schema` option containing the appropriate snake_case field mappings, + * so that `createAdapterFactory` transforms them automatically. + */ + buildPluginList() { + const pluginConfig = this.config.plugins; + const plugins = []; + if (pluginConfig?.organization) { + plugins.push(organization({ + schema: buildOrganizationPluginSchema() + })); + } + if (pluginConfig?.twoFactor) { + plugins.push(twoFactor({ + schema: buildTwoFactorPluginSchema() + })); + } + if (pluginConfig?.magicLink) { + plugins.push(magicLink({ + sendMagicLink: async ({ email: email3, url: url2 }) => { + console.warn( + `[AuthManager] Magic-link requested for ${email3} but no sendMagicLink handler configured. URL: ${url2}` + ); + } + })); + } + return plugins; + } + /** + * Create database configuration using ObjectQL adapter + * + * better-auth resolves the `database` option as follows: + * - `undefined` → in-memory adapter + * - `typeof fn === "function"` → treated as `DBAdapterInstance`, called with `(options)` + * - otherwise → forwarded to Kysely adapter factory (pool/dialect) + * + * A raw `CustomAdapter` object would fall into the third branch and fail + * silently. We therefore wrap the ObjectQL adapter in a factory function + * so it is correctly recognised as a `DBAdapterInstance`. + */ + createDatabaseConfig() { + if (this.config.dataEngine) { + return createObjectQLAdapterFactory(this.config.dataEngine); + } + console.warn( + "\u26A0\uFE0F WARNING: No dataEngine provided to AuthManager! Using in-memory storage. This is NOT suitable for production. Please provide a dataEngine instance (e.g., ObjectQL) in AuthManagerOptions." + ); + return void 0; + } + /** + * Generate a secure secret if not provided + */ + generateSecret() { + const envSecret = process.env.AUTH_SECRET; + if (!envSecret) { + const fallbackSecret = "dev-secret-" + Date.now(); + console.warn( + "\u26A0\uFE0F WARNING: No AUTH_SECRET environment variable set! Using a temporary development secret. This is NOT secure for production use. Please set AUTH_SECRET in your environment variables." + ); + return fallbackSecret; + } + return envSecret; + } + /** + * Update the base URL at runtime. + * + * This **must** be called before the first request triggers lazy + * initialisation of the better-auth instance — typically from a + * `kernel:ready` hook where the actual server port is known. + * + * If the auth instance has already been created this is a no-op and + * a warning is emitted. + */ + setRuntimeBaseUrl(url2) { + if (this.auth) { + console.warn( + "[AuthManager] setRuntimeBaseUrl() called after the auth instance was already created \u2014 ignoring. Ensure this method is called before the first request." + ); + return; + } + this.config = { ...this.config, baseUrl: url2 }; + } + /** + * Get the underlying better-auth instance + * Useful for advanced use cases + */ + getAuthInstance() { + return this.getOrCreateAuth(); + } + /** + * Handle an authentication request + * Forwards the request directly to better-auth's universal handler + * + * better-auth catches internal errors (database / adapter / ORM) and + * returns a 500 Response instead of throwing. We therefore inspect the + * response status and log server errors so they are not silently swallowed. + * + * @param request - Web standard Request object + * @returns Web standard Response object + */ + async handleRequest(request) { + const auth = this.getOrCreateAuth(); + const response = await auth.handler(request); + if (response.status >= 500) { + try { + const body = await response.clone().text(); + console.error("[AuthManager] better-auth returned error:", response.status, body); + } catch { + console.error("[AuthManager] better-auth returned error:", response.status, "(unable to read body)"); + } + } + return response; + } + /** + * Get the better-auth API for programmatic access + * Use this for server-side operations (e.g., creating users, checking sessions) + */ + get api() { + return this.getOrCreateAuth().api; + } +}; +var SysUser = ObjectSchema3.create({ + namespace: "sys", + name: "user", + label: "User", + pluralLabel: "Users", + icon: "user", + isSystem: true, + description: "User accounts for authentication", + titleFormat: "{name} ({email})", + compactLayout: ["name", "email", "email_verified"], + fields: { + id: Field.text({ + label: "User ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + email: Field.email({ + label: "Email", + required: true, + searchable: true + }), + email_verified: Field.boolean({ + label: "Email Verified", + defaultValue: false + }), + name: Field.text({ + label: "Name", + required: true, + searchable: true, + maxLength: 255 + }), + image: Field.url({ + label: "Profile Image", + required: false + }) + }, + indexes: [ + { fields: ["email"], unique: true }, + { fields: ["created_at"], unique: false } + ], + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete"], + trash: true, + mru: true + }, + validations: [ + { + name: "email_unique", + type: "unique", + severity: "error", + message: "Email must be unique", + fields: ["email"], + caseSensitive: false + } + ] +}); +var SysSession = ObjectSchema3.create({ + namespace: "sys", + name: "session", + label: "Session", + pluralLabel: "Sessions", + icon: "key", + isSystem: true, + description: "Active user sessions", + titleFormat: "Session {token}", + compactLayout: ["user_id", "expires_at", "ip_address"], + fields: { + id: Field.text({ + label: "Session ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + user_id: Field.text({ + label: "User ID", + required: true + }), + expires_at: Field.datetime({ + label: "Expires At", + required: true + }), + token: Field.text({ + label: "Session Token", + required: true + }), + ip_address: Field.text({ + label: "IP Address", + required: false, + maxLength: 45 + // Support IPv6 + }), + user_agent: Field.textarea({ + label: "User Agent", + required: false + }) + }, + indexes: [ + { fields: ["token"], unique: true }, + { fields: ["user_id"], unique: false }, + { fields: ["expires_at"], unique: false } + ], + enable: { + trackHistory: false, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "list", "create", "delete"], + trash: false, + mru: false + } +}); +var SysAccount = ObjectSchema3.create({ + namespace: "sys", + name: "account", + label: "Account", + pluralLabel: "Accounts", + icon: "link", + isSystem: true, + description: "OAuth and authentication provider accounts", + titleFormat: "{provider_id} - {account_id}", + compactLayout: ["provider_id", "user_id", "account_id"], + fields: { + id: Field.text({ + label: "Account ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + provider_id: Field.text({ + label: "Provider ID", + required: true, + description: "OAuth provider identifier (google, github, etc.)" + }), + account_id: Field.text({ + label: "Provider Account ID", + required: true, + description: "User's ID in the provider's system" + }), + user_id: Field.text({ + label: "User ID", + required: true, + description: "Link to user table" + }), + access_token: Field.textarea({ + label: "Access Token", + required: false + }), + refresh_token: Field.textarea({ + label: "Refresh Token", + required: false + }), + id_token: Field.textarea({ + label: "ID Token", + required: false + }), + access_token_expires_at: Field.datetime({ + label: "Access Token Expires At", + required: false + }), + refresh_token_expires_at: Field.datetime({ + label: "Refresh Token Expires At", + required: false + }), + scope: Field.text({ + label: "OAuth Scope", + required: false + }), + password: Field.text({ + label: "Password Hash", + required: false, + description: "Hashed password for email/password provider" + }) + }, + indexes: [ + { fields: ["user_id"], unique: false }, + { fields: ["provider_id", "account_id"], unique: true } + ], + enable: { + trackHistory: false, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete"], + trash: true, + mru: false + } +}); +var SysVerification = ObjectSchema3.create({ + namespace: "sys", + name: "verification", + label: "Verification", + pluralLabel: "Verifications", + icon: "shield-check", + isSystem: true, + description: "Email and phone verification tokens", + titleFormat: "Verification for {identifier}", + compactLayout: ["identifier", "expires_at", "created_at"], + fields: { + id: Field.text({ + label: "Verification ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + value: Field.text({ + label: "Verification Token", + required: true, + description: "Token or code for verification" + }), + expires_at: Field.datetime({ + label: "Expires At", + required: true + }), + identifier: Field.text({ + label: "Identifier", + required: true, + description: "Email address or phone number" + }) + }, + indexes: [ + { fields: ["value"], unique: true }, + { fields: ["identifier"], unique: false }, + { fields: ["expires_at"], unique: false } + ], + enable: { + trackHistory: false, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "create", "delete"], + trash: false, + mru: false + } +}); +var SysOrganization = ObjectSchema3.create({ + namespace: "sys", + name: "organization", + label: "Organization", + pluralLabel: "Organizations", + icon: "building-2", + isSystem: true, + description: "Organizations for multi-tenant grouping", + titleFormat: "{name}", + compactLayout: ["name", "slug", "created_at"], + fields: { + id: Field.text({ + label: "Organization ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + name: Field.text({ + label: "Name", + required: true, + searchable: true, + maxLength: 255 + }), + slug: Field.text({ + label: "Slug", + required: false, + maxLength: 255, + description: "URL-friendly identifier" + }), + logo: Field.url({ + label: "Logo", + required: false + }), + metadata: Field.textarea({ + label: "Metadata", + required: false, + description: "JSON-serialized organization metadata" + }) + }, + indexes: [ + { fields: ["slug"], unique: true }, + { fields: ["name"] } + ], + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete"], + trash: true, + mru: true + } +}); +var SysMember = ObjectSchema3.create({ + namespace: "sys", + name: "member", + label: "Member", + pluralLabel: "Members", + icon: "user-check", + isSystem: true, + description: "Organization membership records", + titleFormat: "{user_id} in {organization_id}", + compactLayout: ["user_id", "organization_id", "role"], + fields: { + id: Field.text({ + label: "Member ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + organization_id: Field.text({ + label: "Organization ID", + required: true + }), + user_id: Field.text({ + label: "User ID", + required: true + }), + role: Field.text({ + label: "Role", + required: false, + description: "Member role within the organization (e.g. admin, member)", + maxLength: 100 + }) + }, + indexes: [ + { fields: ["organization_id", "user_id"], unique: true }, + { fields: ["user_id"] } + ], + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete"], + trash: false, + mru: false + } +}); +var SysInvitation = ObjectSchema3.create({ + namespace: "sys", + name: "invitation", + label: "Invitation", + pluralLabel: "Invitations", + icon: "mail", + isSystem: true, + description: "Organization invitations for user onboarding", + titleFormat: "Invitation to {organization_id}", + compactLayout: ["email", "organization_id", "status"], + fields: { + id: Field.text({ + label: "Invitation ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + organization_id: Field.text({ + label: "Organization ID", + required: true + }), + email: Field.email({ + label: "Email", + required: true, + description: "Email address of the invited user" + }), + role: Field.text({ + label: "Role", + required: false, + maxLength: 100, + description: "Role to assign upon acceptance" + }), + status: Field.select(["pending", "accepted", "rejected", "expired", "canceled"], { + label: "Status", + required: true, + defaultValue: "pending" + }), + inviter_id: Field.text({ + label: "Inviter ID", + required: true, + description: "User ID of the person who sent the invitation" + }), + expires_at: Field.datetime({ + label: "Expires At", + required: true + }), + team_id: Field.text({ + label: "Team ID", + required: false, + description: "Optional team to assign upon acceptance" + }) + }, + indexes: [ + { fields: ["organization_id"] }, + { fields: ["email"] }, + { fields: ["expires_at"] } + ], + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete"], + trash: false, + mru: false + } +}); +var SysTeam = ObjectSchema3.create({ + namespace: "sys", + name: "team", + label: "Team", + pluralLabel: "Teams", + icon: "users", + isSystem: true, + description: "Teams within organizations for fine-grained grouping", + titleFormat: "{name}", + compactLayout: ["name", "organization_id", "created_at"], + fields: { + id: Field.text({ + label: "Team ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + name: Field.text({ + label: "Name", + required: true, + searchable: true, + maxLength: 255 + }), + organization_id: Field.text({ + label: "Organization ID", + required: true + }) + }, + indexes: [ + { fields: ["organization_id"] }, + { fields: ["name", "organization_id"], unique: true } + ], + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete"], + trash: true, + mru: false + } +}); +var SysTeamMember = ObjectSchema3.create({ + namespace: "sys", + name: "team_member", + label: "Team Member", + pluralLabel: "Team Members", + icon: "user-plus", + isSystem: true, + description: "Team membership records linking users to teams", + titleFormat: "{user_id} in {team_id}", + compactLayout: ["user_id", "team_id", "created_at"], + fields: { + id: Field.text({ + label: "Team Member ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + team_id: Field.text({ + label: "Team ID", + required: true + }), + user_id: Field.text({ + label: "User ID", + required: true + }) + }, + indexes: [ + { fields: ["team_id", "user_id"], unique: true }, + { fields: ["user_id"] } + ], + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "list", "create", "delete"], + trash: false, + mru: false + } +}); +var SysApiKey = ObjectSchema3.create({ + namespace: "sys", + name: "api_key", + label: "API Key", + pluralLabel: "API Keys", + icon: "key-round", + isSystem: true, + description: "API keys for programmatic access", + titleFormat: "{name}", + compactLayout: ["name", "user_id", "expires_at"], + fields: { + id: Field.text({ + label: "API Key ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + name: Field.text({ + label: "Name", + required: true, + maxLength: 255, + description: "Human-readable label for the API key" + }), + key: Field.text({ + label: "Key", + required: true, + description: "Hashed API key value" + }), + prefix: Field.text({ + label: "Prefix", + required: false, + maxLength: 16, + description: 'Visible prefix for identifying the key (e.g., "osk_")' + }), + user_id: Field.text({ + label: "User ID", + required: true, + description: "Owner user of this API key" + }), + scopes: Field.textarea({ + label: "Scopes", + required: false, + description: "JSON array of permission scopes" + }), + expires_at: Field.datetime({ + label: "Expires At", + required: false + }), + last_used_at: Field.datetime({ + label: "Last Used At", + required: false + }), + revoked: Field.boolean({ + label: "Revoked", + defaultValue: false + }) + }, + indexes: [ + { fields: ["key"], unique: true }, + { fields: ["user_id"] }, + { fields: ["prefix"] } + ], + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete"], + trash: false, + mru: false + } +}); +var SysTwoFactor = ObjectSchema3.create({ + namespace: "sys", + name: "two_factor", + label: "Two Factor", + pluralLabel: "Two Factor Credentials", + icon: "smartphone", + isSystem: true, + description: "Two-factor authentication credentials", + titleFormat: "Two-factor for {user_id}", + compactLayout: ["user_id", "created_at"], + fields: { + id: Field.text({ + label: "Two Factor ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + user_id: Field.text({ + label: "User ID", + required: true + }), + secret: Field.text({ + label: "Secret", + required: true, + description: "TOTP secret key" + }), + backup_codes: Field.textarea({ + label: "Backup Codes", + required: false, + description: "JSON-serialized backup recovery codes" + }) + }, + indexes: [ + { fields: ["user_id"], unique: true } + ], + enable: { + trackHistory: false, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "create", "update", "delete"], + trash: false, + mru: false + } +}); +var SysUserPreference = ObjectSchema3.create({ + namespace: "sys", + name: "user_preference", + label: "User Preference", + pluralLabel: "User Preferences", + icon: "settings", + isSystem: true, + description: "Per-user key-value preferences (theme, locale, etc.)", + titleFormat: "{key}", + compactLayout: ["user_id", "key"], + fields: { + id: Field.text({ + label: "Preference ID", + required: true, + readonly: true + }), + created_at: Field.datetime({ + label: "Created At", + defaultValue: "NOW()", + readonly: true + }), + updated_at: Field.datetime({ + label: "Updated At", + defaultValue: "NOW()", + readonly: true + }), + user_id: Field.text({ + label: "User ID", + required: true, + maxLength: 255, + description: "Owner user of this preference" + }), + key: Field.text({ + label: "Key", + required: true, + maxLength: 255, + description: "Preference key (e.g., theme, locale, plugin.ai.auto_save)" + }), + value: Field.json({ + label: "Value", + description: "Preference value (any JSON-serializable type)" + }) + }, + indexes: [ + { fields: ["user_id", "key"], unique: true }, + { fields: ["user_id"], unique: false } + ], + enable: { + trackHistory: false, + searchable: false, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete"], + trash: false, + mru: false + } +}); +var AuthPlugin = class { + constructor(options = {}) { + this.name = "com.objectstack.auth"; + this.type = "standard"; + this.version = "1.0.0"; + this.dependencies = ["com.objectstack.engine.objectql"]; + this.authManager = null; + this.options = { + registerRoutes: true, + basePath: "/api/v1/auth", + ...options + }; + } + async init(ctx) { + ctx.logger.info("Initializing Auth Plugin..."); + if (!this.options.secret) { + throw new Error("AuthPlugin: secret is required"); + } + const dataEngine = ctx.getService("data"); + if (!dataEngine) { + ctx.logger.warn("No data engine service found - auth will use in-memory storage"); + } + this.authManager = new AuthManager({ + ...this.options, + dataEngine + }); + ctx.registerService("auth", this.authManager); + ctx.getService("manifest").register({ + id: "com.objectstack.system", + name: "System", + version: "1.0.0", + type: "plugin", + namespace: "sys", + objects: [ + SysUser, + SysSession, + SysAccount, + SysVerification, + SysOrganization, + SysMember, + SysInvitation, + SysTeam, + SysTeamMember, + SysApiKey, + SysTwoFactor, + SysUserPreference + ] + }); + try { + const setupNav = ctx.getService("setupNav"); + if (setupNav) { + setupNav.contribute({ + areaId: "area_administration", + items: [ + { id: "nav_users", type: "object", label: "Users", objectName: "user", icon: "users", order: 10 }, + { id: "nav_organizations", type: "object", label: "Organizations", objectName: "organization", icon: "building-2", order: 20 }, + { id: "nav_teams", type: "object", label: "Teams", objectName: "team", icon: "users-round", order: 30 }, + { id: "nav_api_keys", type: "object", label: "API Keys", objectName: "api_key", icon: "key", order: 40 }, + { id: "nav_sessions", type: "object", label: "Sessions", objectName: "session", icon: "monitor", order: 50 } + ] + }); + ctx.logger.info("Auth navigation items contributed to Setup App"); + } + } catch { + } + ctx.logger.info("Auth Plugin initialized successfully"); + } + async start(ctx) { + ctx.logger.info("Starting Auth Plugin..."); + if (!this.authManager) { + throw new Error("Auth manager not initialized"); + } + if (this.options.registerRoutes) { + ctx.hook("kernel:ready", async () => { + let httpServer = null; + try { + httpServer = ctx.getService("http-server"); + } catch { + } + if (httpServer) { + const serverWithPort = httpServer; + if (this.authManager && typeof serverWithPort.getPort === "function") { + const actualPort = serverWithPort.getPort(); + if (actualPort) { + const configuredUrl = this.options.baseUrl || "http://localhost:3000"; + const configuredOrigin = new URL(configuredUrl).origin; + const actualUrl = `http://localhost:${actualPort}`; + if (configuredOrigin !== actualUrl) { + this.authManager.setRuntimeBaseUrl(actualUrl); + ctx.logger.info( + `Auth baseUrl auto-updated to ${actualUrl} (configured: ${configuredUrl})` + ); + } + } + } + this.registerAuthRoutes(httpServer, ctx); + ctx.logger.info(`Auth routes registered at ${this.options.basePath}`); + } else { + ctx.logger.warn( + "No HTTP server available \u2014 auth routes not registered. Auth service is still available for MSW/mock environments via HttpDispatcher." + ); + } + }); + } + try { + const ql = ctx.getService("objectql"); + if (ql && typeof ql.registerMiddleware === "function") { + ql.registerMiddleware(async (opCtx, next) => { + if (opCtx.context?.userId || opCtx.context?.isSystem) { + return next(); + } + await next(); + }); + ctx.logger.info("Auth middleware registered on ObjectQL engine"); + } + } catch (_e) { + ctx.logger.debug("ObjectQL engine not available, skipping auth middleware registration"); + } + ctx.logger.info("Auth Plugin started successfully"); + } + async destroy() { + this.authManager = null; + } + /** + * Register authentication routes with HTTP server + * + * Uses better-auth's universal handler for all authentication requests. + * This forwards all requests under basePath to better-auth, which handles: + * - Email/password authentication + * - OAuth providers (Google, GitHub, etc.) + * - Session management + * - Password reset + * - Email verification + * - 2FA, passkeys, magic links (if enabled) + */ + registerAuthRoutes(httpServer, ctx) { + if (!this.authManager) return; + const basePath = this.options.basePath || "/api/v1/auth"; + if (!("getRawApp" in httpServer) || typeof httpServer.getRawApp !== "function") { + ctx.logger.error("HTTP server does not support getRawApp() - wildcard routing requires Hono server"); + throw new Error( + "AuthPlugin requires HonoServerPlugin for wildcard routing support. Please ensure HonoServerPlugin is loaded before AuthPlugin." + ); + } + const rawApp = httpServer.getRawApp(); + rawApp.all(`${basePath}/*`, async (c) => { + try { + const response = await this.authManager.handleRequest(c.req.raw); + if (response.status >= 500) { + try { + const body = await response.clone().text(); + ctx.logger.error("[AuthPlugin] better-auth returned server error", new Error(`HTTP ${response.status}: ${body}`)); + } catch { + ctx.logger.error("[AuthPlugin] better-auth returned server error", new Error(`HTTP ${response.status}: (unable to read body)`)); + } + } + return response; + } catch (error49) { + const err = error49 instanceof Error ? error49 : new Error(String(error49)); + ctx.logger.error("Auth request error:", err); + return new Response( + JSON.stringify({ + success: false, + error: err.message + }), + { + status: 500, + headers: { "Content-Type": "application/json" } + } + ); + } + }); + ctx.logger.info(`Auth routes registered: All requests under ${basePath}/* forwarded to better-auth`); + } +}; + +// ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.12/node_modules/@hono/node-server/dist/index.mjs +import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2"; +import { Http2ServerRequest } from "http2"; +import { Readable } from "stream"; +import crypto2 from "crypto"; +var RequestError = class extends Error { + constructor(message2, options) { + super(message2, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request2 = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ?? (options.duplex = "half"); + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url2, headers, incoming, abortController) => { + const init2 = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init2.method = "GET"; + const req = new Request2(url2, init2); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init2.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init2.body = new ReadableStream({ + async pull(controller) { + try { + reader || (reader = Readable.toWeb(incoming).getReader()); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error49) { + controller.error(error49); + } + } + }); + } else { + init2.body = Readable.toWeb(incoming); + } + } + return new Request2(url2, init2); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] || (this[headersKey] = newHeadersFromIncoming(this[incomingKey])); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] || (this[abortControllerKey] = new AbortController()); + return this[requestCache] || (this[requestCache] = newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + )); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { + value: function(depth, options, inspectFn) { + const props = { + method: this.method, + url: this.url, + headers: this.headers, + nativeRequest: this[requestCache] + }; + return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`; + } +}); +Object.setPrototypeOf(requestPrototype, Request2.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url22 = new URL(incomingUrl); + req[urlKey] = url22.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url2 = new URL(`${scheme}://${host}${incomingUrl}`); + if (url2.hostname.length !== host.length && url2.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url2.href; + return req; +}; +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var _body, _init, _a29; +var Response2 = (_a29 = class { + constructor(body, init2) { + __privateAdd(this, _body); + __privateAdd(this, _init); + let headers; + __privateSet(this, _body, body); + if (init2 instanceof _a29) { + const cachedGlobalResponse = init2[responseCache]; + if (cachedGlobalResponse) { + __privateSet(this, _init, cachedGlobalResponse); + this[getResponseCache](); + return; + } else { + __privateSet(this, _init, __privateGet(init2, _init)); + headers = new Headers(__privateGet(init2, _init).headers); + } + } else { + __privateSet(this, _init, init2); + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + ; + this[cacheKey] = [init2?.status || 200, body, headers || init2?.headers]; + } + } + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] || (this[responseCache] = new GlobalResponse(__privateGet(this, _body), __privateGet(this, _init))); + } + get headers() { + const cache3 = this[cacheKey]; + if (cache3) { + if (!(cache3[2] instanceof Headers)) { + cache3[2] = new Headers( + cache3[2] || { "content-type": "text/plain; charset=UTF-8" } + ); + } + return cache3[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}, _body = new WeakMap(), _init = new WeakMap(), _a29); +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), { + value: function(depth, options, inspectFn) { + const props = { + status: this.status, + headers: this.headers, + ok: this.ok, + nativeResponse: this[responseCache] + }; + return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`; + } +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error49) => { + reader.cancel(error49).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error49) { + if (error49) { + writable.destroy(error49); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ?? (res["content-type"] = "text/plain; charset=UTF-8"); + return res; +}; +var X_ALREADY_SENT = "x-hono-already-sent"; +if (typeof global.crypto === "undefined") { + global.crypto = crypto2; +} +var outgoingEnded = Symbol("outgoingEnded"); +var incomingDraining = Symbol("incomingDraining"); +var DRAIN_TIMEOUT_MS = 500; +var MAX_DRAIN_BYTES = 64 * 1024 * 1024; +var drainIncoming = (incoming) => { + const incomingWithDrainState = incoming; + if (incoming.destroyed || incomingWithDrainState[incomingDraining]) { + return; + } + incomingWithDrainState[incomingDraining] = true; + if (incoming instanceof Http2ServerRequest2) { + try { + ; + incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR); + } catch { + } + return; + } + let bytesRead = 0; + const cleanup = () => { + clearTimeout(timer); + incoming.off("data", onData); + incoming.off("end", cleanup); + incoming.off("error", cleanup); + }; + const forceClose = () => { + cleanup(); + const socket = incoming.socket; + if (socket && !socket.destroyed) { + socket.destroySoon(); + } + }; + const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS); + timer.unref?.(); + const onData = (chunk) => { + bytesRead += chunk.length; + if (bytesRead > MAX_DRAIN_BYTES) { + forceClose(); + } + }; + incoming.on("data", onData); + incoming.on("end", cleanup); + incoming.on("error", cleanup); + incoming.resume(); +}; +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + let hasContentLength = false; + if (!header) { + header = { "content-type": "text/plain; charset=UTF-8" }; + } else if (header instanceof Headers) { + hasContentLength = header.has("content-length"); + header = buildOutgoingHttpHeaders(header); + } else if (Array.isArray(header)) { + const headerObj = new Headers(header); + hasContentLength = headerObj.has("content-length"); + header = buildOutgoingHttpHeaders(headerObj); + } else { + for (const key in header) { + if (key.length === 14 && key.toLowerCase() === "content-length") { + hasContentLength = true; + break; + } + } + } + if (!hasContentLength) { + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise2 = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise2(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise || (currentReadPromise = reader.read()); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve2) => setTimeout(resolve2)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request2) { + Object.defineProperty(global, "Request", { + value: Request2 + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof Http2ServerRequest2) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + drainIncoming(incoming); + }); + } + }); + } + }; + } + outgoing.on("finish", () => { + if (!incomingEnded) { + drainIncoming(incoming); + } + }); + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + drainIncoming(incoming); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; + +// ../../packages/spec/dist/index.mjs +init_zod(); +var __defProp5 = Object.defineProperty; +var __export4 = (target, all) => { + for (var name in all) + __defProp5(target, name, { get: all[name], enumerable: true }); +}; +var shared_exports = {}; +__export4(shared_exports, { + AggregationFunctionEnum: () => AggregationFunctionEnum2, + AppNameSchema: () => AppNameSchema2, + BaseMetadataRecordSchema: () => BaseMetadataRecordSchema2, + CacheStrategyEnum: () => CacheStrategyEnum2, + CorsConfigSchema: () => CorsConfigSchema4, + EventNameSchema: () => EventNameSchema4, + FieldMappingSchema: () => FieldMappingSchema4, + FieldNameSchema: () => FieldNameSchema2, + FlowNameSchema: () => FlowNameSchema2, + HttpMethod: () => HttpMethod5, + HttpMethodSchema: () => HttpMethodSchema5, + HttpRequestSchema: () => HttpRequestSchema4, + IsolationLevelEnum: () => IsolationLevelEnum3, + MAP_SUPPORTED_FIELDS: () => MAP_SUPPORTED_FIELDS, + METADATA_ALIASES: () => METADATA_ALIASES, + MetadataFormatSchema: () => MetadataFormatSchema5, + MutationEventEnum: () => MutationEventEnum2, + ObjectNameSchema: () => ObjectNameSchema2, + PLURAL_TO_SINGULAR: () => PLURAL_TO_SINGULAR2, + RateLimitConfigSchema: () => RateLimitConfigSchema4, + RoleNameSchema: () => RoleNameSchema2, + SINGULAR_TO_PLURAL: () => SINGULAR_TO_PLURAL2, + SnakeCaseIdentifierSchema: () => SnakeCaseIdentifierSchema7, + SortDirectionEnum: () => SortDirectionEnum4, + SortItemSchema: () => SortItemSchema3, + StaticMountSchema: () => StaticMountSchema4, + SystemIdentifierSchema: () => SystemIdentifierSchema6, + TransformTypeSchema: () => TransformTypeSchema3, + ViewNameSchema: () => ViewNameSchema2, + findClosestMatches: () => findClosestMatches, + formatSuggestion: () => formatSuggestion, + formatZodError: () => formatZodError, + formatZodIssue: () => formatZodIssue, + levenshteinDistance: () => levenshteinDistance, + normalizeMetadataCollection: () => normalizeMetadataCollection, + normalizePluginMetadata: () => normalizePluginMetadata, + normalizeStackInput: () => normalizeStackInput, + objectStackErrorMap: () => objectStackErrorMap, + pluralToSingular: () => pluralToSingular2, + safeParsePretty: () => safeParsePretty, + singularToPlural: () => singularToPlural, + suggestFieldType: () => suggestFieldType +}); +var SystemIdentifierSchema6 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' +}).describe("System identifier (lowercase with underscores or dots)"); +var SnakeCaseIdentifierSchema7 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { + message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' +}).describe("Snake case identifier (lowercase with underscores only)"); +var EventNameSchema4 = external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { + message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' +}).describe("Event name (lowercase with dot notation for namespacing)"); +var TransformTypeSchema3 = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("constant"), + value: external_exports.unknown().describe("Constant value to use") + }).describe("Set a constant value"), + external_exports.object({ + type: external_exports.literal("cast"), + targetType: external_exports.enum(["string", "number", "boolean", "date"]).describe("Target data type") + }).describe("Cast to a specific data type"), + external_exports.object({ + type: external_exports.literal("lookup"), + table: external_exports.string().describe("Lookup table name"), + keyField: external_exports.string().describe("Field to match on"), + valueField: external_exports.string().describe("Field to retrieve") + }).describe("Lookup value from another table"), + external_exports.object({ + type: external_exports.literal("javascript"), + expression: external_exports.string().describe('JavaScript expression (e.g., "value.toUpperCase()")') + }).describe("Custom JavaScript transformation"), + external_exports.object({ + type: external_exports.literal("map"), + mappings: external_exports.record(external_exports.string(), external_exports.unknown()).describe('Value mappings (e.g., {"Active": "active"})') + }).describe("Map values using a dictionary") +]); +var FieldMappingSchema4 = external_exports.object({ + /** + * Source field name + */ + source: external_exports.string().describe("Source field name"), + /** + * Target field name (should be snake_case for ObjectStack) + */ + target: external_exports.string().describe("Target field name"), + /** + * Transformation to apply + */ + transform: TransformTypeSchema3.optional().describe("Transformation to apply"), + /** + * Default value if source is null/undefined + */ + defaultValue: external_exports.unknown().optional().describe("Default if source is null/undefined") +}); +var HttpMethod5 = external_exports.enum([ + "GET", + "POST", + "PUT", + "DELETE", + "PATCH", + "HEAD", + "OPTIONS" +]); +var HttpMethodSchema5 = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); +var HttpRequestSchema4 = external_exports.object({ + url: external_exports.string().describe("API endpoint URL"), + method: HttpMethodSchema5.optional().default("GET").describe("HTTP method"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), + body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") +}); +var CorsConfigSchema4 = external_exports.object({ + /** + * Enable CORS + */ + enabled: external_exports.boolean().default(true).describe("Enable CORS"), + /** + * Allowed origins (* for all) + */ + origins: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.string()) + ]).default("*").describe("Allowed origins (* for all)"), + /** + * Allowed HTTP methods + */ + methods: external_exports.array(HttpMethod5).optional().describe("Allowed HTTP methods"), + /** + * Allow credentials (cookies, authorization headers) + */ + credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), + /** + * Preflight cache duration in seconds + */ + maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") +}); +var RateLimitConfigSchema4 = external_exports.object({ + /** + * Enable rate limiting + */ + enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), + /** + * Time window in milliseconds + */ + windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), + /** + * Max requests per window + */ + maxRequests: external_exports.number().int().default(100).describe("Max requests per window") +}); +var StaticMountSchema4 = external_exports.object({ + /** + * URL path to serve from + */ + path: external_exports.string().describe("URL path to serve from"), + /** + * Physical directory to serve + */ + directory: external_exports.string().describe("Physical directory to serve"), + /** + * Cache-Control header value + */ + cacheControl: external_exports.string().optional().describe("Cache-Control header value") +}); +var AggregationFunctionEnum2 = external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "percentile", + "median", + "stddev", + "variance" +]).describe("Standard aggregation functions"); +var SortDirectionEnum4 = external_exports.enum(["asc", "desc"]).describe("Sort order direction"); +var SortItemSchema3 = external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + order: SortDirectionEnum4.describe("Sort direction") +}).describe("Sort field and direction pair"); +var MutationEventEnum2 = external_exports.enum([ + "insert", + "update", + "delete", + "upsert" +]).describe("Data mutation event types"); +var IsolationLevelEnum3 = external_exports.enum([ + "read_uncommitted", + "read_committed", + "repeatable_read", + "serializable", + "snapshot" +]).describe("Transaction isolation levels (snake_case standard)"); +var CacheStrategyEnum2 = external_exports.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy"); +var MetadataFormatSchema5 = external_exports.enum(["yaml", "json", "typescript", "javascript"]).describe("Metadata file format"); +var BaseMetadataRecordSchema2 = external_exports.object({ + id: external_exports.string().describe("Unique metadata record identifier"), + type: external_exports.string().describe('Metadata type (e.g. "object", "view", "flow")'), + name: SnakeCaseIdentifierSchema7.describe("Machine name (snake_case)"), + format: MetadataFormatSchema5.optional().describe("Source file format") +}).describe("Base metadata record fields shared across kernel and system"); +var ObjectNameSchema2 = SnakeCaseIdentifierSchema7.brand().describe("Branded object name (snake_case, no dots)"); +var FieldNameSchema2 = SnakeCaseIdentifierSchema7.brand().describe("Branded field name (snake_case, no dots)"); +var ViewNameSchema2 = SystemIdentifierSchema6.brand().describe("Branded view name (system identifier)"); +var AppNameSchema2 = SystemIdentifierSchema6.brand().describe("Branded app name (system identifier)"); +var FlowNameSchema2 = SystemIdentifierSchema6.brand().describe("Branded flow name (system identifier)"); +var RoleNameSchema2 = SystemIdentifierSchema6.brand().describe("Branded role name (system identifier)"); +var EncryptionAlgorithmSchema6 = external_exports.enum([ + "aes-256-gcm", + "aes-256-cbc", + "chacha20-poly1305" +]).describe("Supported encryption algorithm"); +var KeyManagementProviderSchema6 = external_exports.enum([ + "local", + "aws-kms", + "azure-key-vault", + "gcp-kms", + "hashicorp-vault" +]).describe("Key management service provider"); +var KeyRotationPolicySchema6 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), + frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), + retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), + autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") +}).describe("Policy for automatic encryption key rotation"); +var EncryptionConfigSchema6 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), + algorithm: EncryptionAlgorithmSchema6.default("aes-256-gcm").describe("Encryption algorithm"), + keyManagement: external_exports.object({ + provider: KeyManagementProviderSchema6.describe("Key management service provider"), + keyId: external_exports.string().optional().describe("Key identifier in the provider"), + rotationPolicy: KeyRotationPolicySchema6.optional().describe("Key rotation policy") + }).describe("Key management configuration"), + scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), + deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), + searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") +}).describe("Field-level encryption configuration"); +var FieldEncryptionSchema2 = external_exports.object({ + fieldName: external_exports.string().describe("Name of the field to encrypt"), + encryptionConfig: EncryptionConfigSchema6.describe("Encryption settings for this field"), + indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") +}).describe("Per-field encryption assignment"); +var MaskingStrategySchema6 = external_exports.enum([ + "redact", + // Complete redaction: **** + "partial", + // Partial masking: 138****5678 + "hash", + // Hash value: sha256(value) + "tokenize", + // Tokenization: token-12345 + "randomize", + // Randomize: generate random value + "nullify", + // Null value: null + "substitute" + // Substitute with dummy data +]).describe("Data masking strategy for PII protection"); +var MaskingRuleSchema6 = external_exports.object({ + field: external_exports.string().describe("Field name to apply masking to"), + strategy: MaskingStrategySchema6.describe("Masking strategy to use"), + pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), + preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), + preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), + roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), + exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") +}).describe("Masking rule for a single field"); +var MaskingConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable data masking"), + rules: external_exports.array(MaskingRuleSchema6).describe("List of field-level masking rules"), + auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") +}).describe("Top-level data masking configuration for PII protection"); +var FieldType6 = external_exports.enum([ + // Core Text + "text", + "textarea", + "email", + "url", + "phone", + "password", + // Rich Content + "markdown", + "html", + "richtext", + // Numbers + "number", + "currency", + "percent", + // Date & Time + "date", + "datetime", + "time", + // Logic + "boolean", + "toggle", + // Toggle is a distinct UI from checkbox + // Selection + "select", + // Single select dropdown + "multiselect", + // Multi select (often tags) + "radio", + // Radio group + "checkboxes", + // Checkbox group + // Relational + "lookup", + "master_detail", + // Dynamic reference + "tree", + // Hierarchical reference + // Media + "image", + "file", + "avatar", + "video", + "audio", + // Calculated / System + "formula", + "summary", + "autonumber", + // Enhanced Types + "location", + // GPS coordinates + "address", + // Structured address + "code", + // Code editor (JSON/SQL/JS) + "json", + // Structured JSON data + "color", + // Color picker + "rating", + // Star rating + "slider", + // Numeric slider + "signature", + // Digital signature + "qrcode", + // QR code / Barcode + "progress", + // Progress bar + "tags", + // Simple tag list + // AI/ML Types + "vector" + // Vector embeddings for AI/ML (semantic search, RAG) +]); +var SelectOptionSchema6 = external_exports.object({ + label: external_exports.string().describe("Display label (human-readable, any case allowed)"), + value: SystemIdentifierSchema6.describe("Stored value (lowercase machine identifier)"), + color: external_exports.string().optional().describe("Color code for badges/charts"), + default: external_exports.boolean().optional().describe("Is default option") +}); +var LocationCoordinatesSchema2 = external_exports.object({ + latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), + longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), + altitude: external_exports.number().optional().describe("Altitude in meters"), + accuracy: external_exports.number().optional().describe("Accuracy in meters") +}); +var CurrencyConfigSchema6 = external_exports.object({ + precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), + currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), + defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") +}); +var CurrencyValueSchema2 = external_exports.object({ + value: external_exports.number().describe("Monetary amount"), + currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") +}); +var AddressSchema2 = external_exports.object({ + street: external_exports.string().optional().describe("Street address"), + city: external_exports.string().optional().describe("City name"), + state: external_exports.string().optional().describe("State/Province"), + postalCode: external_exports.string().optional().describe("Postal/ZIP code"), + country: external_exports.string().optional().describe("Country name or code"), + countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), + formatted: external_exports.string().optional().describe("Formatted address string") +}); +var VectorConfigSchema6 = external_exports.object({ + dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), + distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), + normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), + indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), + indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") +}); +var FileAttachmentConfigSchema6 = external_exports.object({ + /** File Size Limits */ + minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), + maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), + /** File Type Restrictions */ + allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), + blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), + allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), + blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), + /** Virus Scanning */ + virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), + virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), + virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), + quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), + /** Storage Configuration */ + storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), + storageBucket: external_exports.string().optional().describe("Target bucket name"), + storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), + /** Image-Specific Validation */ + imageValidation: external_exports.object({ + minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), + maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), + minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), + maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), + aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), + generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), + thumbnailSizes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), + width: external_exports.number().min(1).describe("Thumbnail width in pixels"), + height: external_exports.number().min(1).describe("Thumbnail height in pixels"), + crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") + })).optional().describe("Thumbnail size configurations"), + preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), + autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") + }).optional().describe("Image-specific validation rules"), + /** Upload Behavior */ + allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), + allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), + allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), + requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), + /** Metadata Extraction */ + extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), + extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), + /** Versioning */ + versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), + maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), + /** Access Control */ + publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), + presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") +}).refine((data) => { + if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { + return false; + } + return true; +}, { + message: "minSize must be less than or equal to maxSize" +}).refine((data) => { + if (data.virusScanProvider !== void 0 && data.virusScan !== true) { + return false; + } + return true; +}, { + message: "virusScanProvider requires virusScan to be enabled" +}); +var DataQualityRulesSchema6 = external_exports.object({ + /** Enforce uniqueness constraint */ + uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), + /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ + completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), + /** Accuracy validation against authoritative source */ + accuracy: external_exports.object({ + source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), + threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") + }).optional().describe("Accuracy validation configuration") +}); +var ComputedFieldCacheSchema6 = external_exports.object({ + /** Enable caching for this computed field */ + enabled: external_exports.boolean().describe("Enable caching for computed field results"), + /** Time-to-live in seconds */ + ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), + /** Array of field paths that trigger cache invalidation when changed */ + invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') +}); +var FieldSchema5 = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), + label: external_exports.string().optional().describe("Human readable label"), + type: FieldType6.describe("Field Data Type"), + description: external_exports.string().optional().describe("Tooltip/Help text"), + format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), + /** Storage Layer Mapping */ + columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), + /** Database Constraints */ + required: external_exports.boolean().default(false).describe("Is required"), + searchable: external_exports.boolean().default(false).describe("Is searchable"), + multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), + unique: external_exports.boolean().default(false).describe("Is unique constraint"), + defaultValue: external_exports.unknown().optional().describe("Default value"), + /** Text/String Constraints */ + maxLength: external_exports.number().optional().describe("Max character length"), + minLength: external_exports.number().optional().describe("Min character length"), + /** Number Constraints */ + precision: external_exports.number().optional().describe("Total digits"), + scale: external_exports.number().optional().describe("Decimal places"), + min: external_exports.number().optional().describe("Minimum value"), + max: external_exports.number().optional().describe("Maximum value"), + /** Selection Options */ + options: external_exports.array(SelectOptionSchema6).optional().describe("Static options for select/multiselect"), + /** + * Relationship Config + * + * Used by `lookup` and `master_detail` field types to define cross-object references. + * The `reference` property is **required** for these types — it identifies the target + * object whose records this field links to. The engine uses `reference` during $expand + * post-processing to resolve foreign key IDs into full related objects via batch queries. + * + * For `master_detail` fields, the parent record controls the lifecycle of child records + * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. + */ + reference: external_exports.string().optional().describe( + "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." + ), + referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), + writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), + deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), + /** Calculation */ + expression: external_exports.string().optional().describe("Formula expression"), + summaryOperations: external_exports.object({ + object: external_exports.string().describe("Source child object name for roll-up"), + field: external_exports.string().describe("Field on child object to aggregate"), + function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") + }).optional().describe("Roll-up summary definition"), + /** Enhanced Field Type Configurations */ + // Code field config + language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), + theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), + lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), + // Rating field config + maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), + allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), + // Location field config + displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), + allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), + // Address field config + addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), + // Color field config + colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), + allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), + presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), + // Slider field config + step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), + showValue: external_exports.boolean().optional().describe("Display current value on slider"), + marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), + // QR Code / Barcode field config + // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' + // Runtime validation should enforce this constraint + barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), + qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), + displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), + allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), + // Currency field config + currencyConfig: CurrencyConfigSchema6.optional().describe("Configuration for currency field type"), + // Vector field config + vectorConfig: VectorConfigSchema6.optional().describe("Configuration for vector field type (AI/ML embeddings)"), + // File attachment field config + fileAttachmentConfig: FileAttachmentConfigSchema6.optional().describe("Configuration for file and attachment field types"), + /** Enhanced Security & Compliance */ + // Encryption configuration + encryptionConfig: EncryptionConfigSchema6.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), + // Data masking rules + maskingRule: MaskingRuleSchema6.optional().describe("Data masking rules for PII protection"), + // Audit trail + auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), + /** Field Dependencies & Relationships */ + // Field dependencies + dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), + /** Computed Field Optimization */ + // Computed field caching + cached: ComputedFieldCacheSchema6.optional().describe("Caching configuration for computed/formula fields"), + /** Data Quality & Governance */ + // Data quality rules + dataQuality: DataQualityRulesSchema6.optional().describe("Data quality validation and monitoring rules"), + /** Layout & Grouping */ + group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), + /** Conditional Requirements */ + conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), + /** Security & Visibility */ + hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), + readonly: external_exports.boolean().default(false).describe("Read-only in UI"), + sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), + inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), + trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), + caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), + autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), + /** Indexing */ + index: external_exports.boolean().default(false).describe("Create standard database index"), + externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") +}); +var Field2 = { + text: (config4 = {}) => ({ type: "text", ...config4 }), + textarea: (config4 = {}) => ({ type: "textarea", ...config4 }), + number: (config4 = {}) => ({ type: "number", ...config4 }), + boolean: (config4 = {}) => ({ type: "boolean", ...config4 }), + date: (config4 = {}) => ({ type: "date", ...config4 }), + datetime: (config4 = {}) => ({ type: "datetime", ...config4 }), + currency: (config4 = {}) => ({ type: "currency", ...config4 }), + percent: (config4 = {}) => ({ type: "percent", ...config4 }), + url: (config4 = {}) => ({ type: "url", ...config4 }), + email: (config4 = {}) => ({ type: "email", ...config4 }), + phone: (config4 = {}) => ({ type: "phone", ...config4 }), + image: (config4 = {}) => ({ type: "image", ...config4 }), + file: (config4 = {}) => ({ type: "file", ...config4 }), + avatar: (config4 = {}) => ({ type: "avatar", ...config4 }), + formula: (config4 = {}) => ({ type: "formula", ...config4 }), + summary: (config4 = {}) => ({ type: "summary", ...config4 }), + autonumber: (config4 = {}) => ({ type: "autonumber", ...config4 }), + markdown: (config4 = {}) => ({ type: "markdown", ...config4 }), + html: (config4 = {}) => ({ type: "html", ...config4 }), + password: (config4 = {}) => ({ type: "password", ...config4 }), + /** + * Select field helper with backward-compatible API + * + * Automatically converts option values to lowercase to enforce naming conventions. + * + * @example Old API (array first) - auto-converts to lowercase + * Field.select(['High', 'Low'], { label: 'Priority' }) + * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }] + * + * @example New API (config object) - enforces lowercase + * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' }) + * + * @example Multi-word values - converts to snake_case + * Field.select(['In Progress', 'Closed Won'], { label: 'Status' }) + * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }] + */ + select: (optionsOrConfig, config4) => { + const toSnakeCase = (str) => { + return str.toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, ""); + }; + let options; + let finalConfig; + if (Array.isArray(optionsOrConfig)) { + options = optionsOrConfig.map( + (o) => typeof o === "string" ? { label: o, value: toSnakeCase(o) } : { ...o, value: o.value.toLowerCase() } + // Ensure value is lowercase + ); + finalConfig = config4 || {}; + } else { + options = (optionsOrConfig.options || []).map( + (o) => typeof o === "string" ? { label: o, value: toSnakeCase(o) } : { ...o, value: o.value.toLowerCase() } + // Ensure value is lowercase + ); + const { options: _, ...restConfig } = optionsOrConfig; + finalConfig = restConfig; + } + return { type: "select", options, ...finalConfig }; + }, + lookup: (reference, config4 = {}) => ({ + type: "lookup", + reference, + ...config4 + }), + masterDetail: (reference, config4 = {}) => ({ + type: "master_detail", + reference, + ...config4 + }), + // Enhanced Field Type Helpers + location: (config4 = {}) => ({ + type: "location", + ...config4 + }), + address: (config4 = {}) => ({ + type: "address", + ...config4 + }), + richtext: (config4 = {}) => ({ + type: "richtext", + ...config4 + }), + code: (language, config4 = {}) => ({ + type: "code", + language, + ...config4 + }), + color: (config4 = {}) => ({ + type: "color", + ...config4 + }), + rating: (maxRating = 5, config4 = {}) => ({ + type: "rating", + maxRating, + ...config4 + }), + signature: (config4 = {}) => ({ + type: "signature", + ...config4 + }), + slider: (config4 = {}) => ({ + type: "slider", + ...config4 + }), + qrcode: (config4 = {}) => ({ + type: "qrcode", + ...config4 + }), + json: (config4 = {}) => ({ + type: "json", + ...config4 + }), + vector: (dimensions, config4 = {}) => ({ + type: "vector", + vectorConfig: { + dimensions, + distanceMetric: "cosine", + normalized: false, + indexed: true, + ...config4.vectorConfig + }, + ...config4 + }) +}; +function levenshteinDistance(a, b) { + const la = a.length; + const lb = b.length; + if (la === 0) return lb; + if (lb === 0) return la; + let prev = new Array(lb + 1); + let curr = new Array(lb + 1); + for (let j = 0; j <= lb; j++) { + prev[j] = j; + } + for (let i = 1; i <= la; i++) { + curr[0] = i; + for (let j = 1; j <= lb; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + curr[j] = Math.min( + prev[j] + 1, + // deletion + curr[j - 1] + 1, + // insertion + prev[j - 1] + cost + // substitution + ); + } + [prev, curr] = [curr, prev]; + } + return prev[lb]; +} +function findClosestMatches(input, candidates, maxDistance = 3, maxResults = 3) { + const normalized = input.toLowerCase().replace(/[-\s]/g, "_"); + const scored = candidates.map((candidate) => ({ + value: candidate, + distance: levenshteinDistance(normalized, candidate) + })).filter((s) => s.distance <= maxDistance && s.distance > 0).sort((a, b) => a.distance - b.distance); + return scored.slice(0, maxResults).map((s) => s.value); +} +var FIELD_TYPE_ALIASES = { + // Common alternative names + string: "text", + str: "text", + varchar: "text", + char: "text", + int: "number", + integer: "number", + float: "number", + double: "number", + decimal: "number", + numeric: "number", + bool: "boolean", + checkbox: "boolean", + check: "boolean", + date_time: "datetime", + timestamp: "datetime", + // Common typos + text_area: "textarea", + textarea_: "textarea", + textfield: "text", + dropdown: "select", + picklist: "select", + enum: "select", + multi_select: "multiselect", + multiselect_: "multiselect", + reference: "lookup", + ref: "lookup", + foreign_key: "lookup", + fk: "lookup", + relation: "lookup", + master: "master_detail", + richtext_: "richtext", + rich_text: "richtext", + upload: "file", + attachment: "file", + photo: "image", + picture: "image", + img: "image", + percent_: "percent", + percentage: "percent", + money: "currency", + price: "currency", + auto_number: "autonumber", + auto_increment: "autonumber", + sequence: "autonumber", + markdown_: "markdown", + md: "markdown", + barcode: "qrcode", + tag: "tags", + star: "rating", + stars: "rating", + geo: "location", + gps: "location", + coordinates: "location", + embed: "vector", + embedding: "vector", + embeddings: "vector" +}; +function suggestFieldType(input) { + const normalized = input.toLowerCase().replace(/[-\s]/g, "_"); + const alias = FIELD_TYPE_ALIASES[normalized]; + if (alias) { + return [alias]; + } + return findClosestMatches(normalized, FieldType6.options); +} +function formatSuggestion(suggestions) { + if (suggestions.length === 0) return ""; + if (suggestions.length === 1) return `Did you mean '${suggestions[0]}'?`; + return `Did you mean one of: ${suggestions.map((s) => `'${s}'`).join(", ")}?`; +} +var objectStackErrorMap = (issue2) => { + if (issue2.code === "invalid_value") { + const values = issue2.values; + const input = issue2.input; + const received = String(input ?? ""); + const options = values.map(String); + const fieldTypeOptions = FieldType6.options; + const isFieldTypeEnum = options.length > 10 && fieldTypeOptions.every((ft) => options.includes(ft)); + if (isFieldTypeEnum) { + const suggestions2 = suggestFieldType(received); + const suggestion2 = formatSuggestion(suggestions2); + const base2 = `Invalid field type '${received}'.`; + return { + message: suggestion2 ? `${base2} ${suggestion2}` : `${base2} Valid types: ${options.slice(0, 10).join(", ")}...` + }; + } + const suggestions = findClosestMatches(received, options); + const suggestion = formatSuggestion(suggestions); + const base = `Invalid value '${received}'.`; + return { + message: suggestion ? `${base} ${suggestion}` : `${base} Expected one of: ${options.join(", ")}.` + }; + } + if (issue2.code === "too_small") { + const origin = issue2.origin; + const minimum = issue2.minimum; + if (origin === "string") { + return { + message: `Must be at least ${minimum} character${minimum === 1 ? "" : "s"} long.` + }; + } + } + if (issue2.code === "too_big") { + const origin = issue2.origin; + const maximum = issue2.maximum; + if (origin === "string") { + return { + message: `Must be at most ${maximum} character${maximum === 1 ? "" : "s"} long.` + }; + } + } + if (issue2.code === "invalid_format") { + const format = issue2.format; + const input = issue2.input; + if (format === "regex" && input) { + const pathArr = issue2.path; + const pathStr = pathArr?.join(".") ?? ""; + if (pathStr.endsWith("name") || pathStr === "name") { + return { + message: `Invalid identifier '${input}'. Must be lowercase snake_case (e.g., 'my_object', 'task_name'). No uppercase, spaces, or hyphens allowed.` + }; + } + } + } + if (issue2.code === "invalid_type") { + const expected = issue2.expected; + const input = issue2.input; + if (input === void 0) { + const pathArr = issue2.path; + const field = pathArr?.[pathArr.length - 1] ?? ""; + return { + message: `Required property '${field}' is missing.` + }; + } + const receivedType = input === null ? "null" : typeof input; + return { + message: `Expected ${expected} but received ${receivedType}.` + }; + } + if (issue2.code === "unrecognized_keys") { + const keys = issue2.keys; + const keyStr = keys.join(", "); + return { + message: `Unrecognized key${keys.length > 1 ? "s" : ""}: ${keyStr}. Check for typos in property names.` + }; + } + return null; +}; +function formatZodIssue(issue2) { + const path3 = issue2.path.length > 0 ? issue2.path.join(".") : "(root)"; + return ` \u2717 ${path3}: ${issue2.message}`; +} +function formatZodError(error49, label) { + const count = error49.issues.length; + const header = label ? `${label} (${count} issue${count === 1 ? "" : "s"}):` : `Validation failed (${count} issue${count === 1 ? "" : "s"}):`; + const lines = error49.issues.map(formatZodIssue); + return `${header} + +${lines.join("\n")}`; +} +function safeParsePretty(schema3, data, label) { + const result = schema3.safeParse(data, { error: objectStackErrorMap }); + if (result.success) { + return { success: true, data: result.data }; + } + return { + success: false, + error: result.error, + formatted: formatZodError(result.error, label) + }; +} +var MAP_SUPPORTED_FIELDS = [ + "objects", + "apps", + "pages", + "dashboards", + "reports", + "actions", + "themes", + "workflows", + "approvals", + "flows", + "roles", + "permissions", + "sharingRules", + "policies", + "apis", + "webhooks", + "agents", + "ragPipelines", + "hooks", + "mappings", + "analyticsCubes", + "connectors", + "datasources" +]; +var PLURAL_TO_SINGULAR2 = { + objects: "object", + apps: "app", + pages: "page", + dashboards: "dashboard", + reports: "report", + actions: "action", + themes: "theme", + workflows: "workflow", + approvals: "approval", + flows: "flow", + roles: "role", + permissions: "permission", + profiles: "profile", + sharingRules: "sharingRule", + policies: "policy", + apis: "api", + webhooks: "webhook", + agents: "agent", + ragPipelines: "ragPipeline", + hooks: "hook", + mappings: "mapping", + analyticsCubes: "analyticsCube", + connectors: "connector", + datasources: "datasource", + views: "view" +}; +var SINGULAR_TO_PLURAL2 = Object.fromEntries( + Object.entries(PLURAL_TO_SINGULAR2).map(([plural, singular]) => [singular, plural]) +); +function pluralToSingular2(key) { + return PLURAL_TO_SINGULAR2[key] ?? key; +} +function singularToPlural(key) { + return SINGULAR_TO_PLURAL2[key] ?? key; +} +function normalizeMetadataCollection(value, keyField = "name") { + if (value == null || Array.isArray(value)) return value; + if (typeof value === "object") { + return Object.entries(value).map(([key, item]) => { + if (item && typeof item === "object" && !Array.isArray(item)) { + const obj = item; + if (!(keyField in obj) || obj[keyField] === void 0) { + return { ...obj, [keyField]: key }; + } + return obj; + } + return item; + }); + } + return value; +} +function normalizeStackInput(input) { + const result = { ...input }; + for (const field of MAP_SUPPORTED_FIELDS) { + if (field in result) { + result[field] = normalizeMetadataCollection(result[field]); + } + } + return result; +} +var METADATA_ALIASES = { + triggers: "hooks" +}; +function normalizePluginMetadata(metadata) { + const result = { ...metadata }; + for (const [alias, canonical] of Object.entries(METADATA_ALIASES)) { + if (alias in result) { + const aliasValue = normalizeMetadataCollection(result[alias]); + const canonicalValue = normalizeMetadataCollection(result[canonical]); + if (Array.isArray(aliasValue)) { + result[canonical] = Array.isArray(canonicalValue) ? [...canonicalValue, ...aliasValue] : aliasValue; + } + delete result[alias]; + } + } + for (const field of MAP_SUPPORTED_FIELDS) { + if (field in result) { + result[field] = normalizeMetadataCollection(result[field]); + } + } + if (Array.isArray(result.plugins)) { + result.plugins = result.plugins.map((p) => { + if (p && typeof p === "object" && !Array.isArray(p)) { + return normalizePluginMetadata(p); + } + return p; + }); + } + return result; +} +var data_exports2 = {}; +__export4(data_exports2, { + ALL_OPERATORS: () => ALL_OPERATORS2, + AddressSchema: () => AddressSchema2, + AggregationFunction: () => AggregationFunction3, + AggregationMetricType: () => AggregationMetricType3, + AggregationNodeSchema: () => AggregationNodeSchema3, + AggregationPipelineSchema: () => AggregationPipelineSchema2, + AggregationStageSchema: () => AggregationStageSchema2, + AnalyticsQuerySchema: () => AnalyticsQuerySchema3, + ApiMethod: () => ApiMethod4, + AsyncValidationSchema: () => AsyncValidationSchema4, + BaseEngineOptionsSchema: () => BaseEngineOptionsSchema2, + CDCConfigSchema: () => CDCConfigSchema4, + ComparisonOperatorSchema: () => ComparisonOperatorSchema2, + ComputedFieldCacheSchema: () => ComputedFieldCacheSchema6, + ConditionalValidationSchema: () => ConditionalValidationSchema4, + ConsistencyLevelSchema: () => ConsistencyLevelSchema2, + CrossFieldValidationSchema: () => CrossFieldValidationSchema4, + CubeJoinSchema: () => CubeJoinSchema3, + CubeSchema: () => CubeSchema3, + CurrencyConfigSchema: () => CurrencyConfigSchema6, + CurrencyValueSchema: () => CurrencyValueSchema2, + CustomValidatorSchema: () => CustomValidatorSchema4, + DataEngineAggregateOptionsSchema: () => DataEngineAggregateOptionsSchema2, + DataEngineAggregateRequestSchema: () => DataEngineAggregateRequestSchema2, + DataEngineBatchRequestSchema: () => DataEngineBatchRequestSchema2, + DataEngineContractSchema: () => DataEngineContractSchema2, + DataEngineCountOptionsSchema: () => DataEngineCountOptionsSchema2, + DataEngineCountRequestSchema: () => DataEngineCountRequestSchema2, + DataEngineDeleteOptionsSchema: () => DataEngineDeleteOptionsSchema2, + DataEngineDeleteRequestSchema: () => DataEngineDeleteRequestSchema2, + DataEngineExecuteRequestSchema: () => DataEngineExecuteRequestSchema2, + DataEngineFilterSchema: () => DataEngineFilterSchema2, + DataEngineFindOneRequestSchema: () => DataEngineFindOneRequestSchema2, + DataEngineFindRequestSchema: () => DataEngineFindRequestSchema2, + DataEngineInsertOptionsSchema: () => DataEngineInsertOptionsSchema2, + DataEngineInsertRequestSchema: () => DataEngineInsertRequestSchema2, + DataEngineQueryOptionsSchema: () => DataEngineQueryOptionsSchema2, + DataEngineRequestSchema: () => DataEngineRequestSchema2, + DataEngineSortSchema: () => DataEngineSortSchema2, + DataEngineUpdateOptionsSchema: () => DataEngineUpdateOptionsSchema2, + DataEngineUpdateRequestSchema: () => DataEngineUpdateRequestSchema2, + DataEngineVectorFindRequestSchema: () => DataEngineVectorFindRequestSchema2, + DataQualityRulesSchema: () => DataQualityRulesSchema6, + DataTypeMappingSchema: () => DataTypeMappingSchema2, + DatasetLoadResultSchema: () => DatasetLoadResultSchema2, + DatasetMode: () => DatasetMode4, + DatasetSchema: () => DatasetSchema4, + DatasourceCapabilities: () => DatasourceCapabilities2, + DatasourceSchema: () => DatasourceSchema2, + DimensionSchema: () => DimensionSchema3, + DimensionType: () => DimensionType3, + DocumentSchema: () => DocumentSchema2, + DocumentSchemaValidationSchema: () => DocumentSchemaValidationSchema2, + DocumentTemplateSchema: () => DocumentTemplateSchema2, + DocumentVersionSchema: () => DocumentVersionSchema2, + DriverCapabilitiesSchema: () => DriverCapabilitiesSchema2, + DriverConfigSchema: () => DriverConfigSchema2, + DriverDefinitionSchema: () => DriverDefinitionSchema2, + DriverInterfaceSchema: () => DriverInterfaceSchema2, + DriverOptionsSchema: () => DriverOptionsSchema2, + DriverType: () => DriverType2, + ESignatureConfigSchema: () => ESignatureConfigSchema2, + EngineAggregateOptionsSchema: () => EngineAggregateOptionsSchema2, + EngineCountOptionsSchema: () => EngineCountOptionsSchema2, + EngineDeleteOptionsSchema: () => EngineDeleteOptionsSchema2, + EngineQueryOptionsSchema: () => EngineQueryOptionsSchema2, + EngineUpdateOptionsSchema: () => EngineUpdateOptionsSchema2, + EqualityOperatorSchema: () => EqualityOperatorSchema2, + ExternalDataSourceSchema: () => ExternalDataSourceSchema2, + ExternalFieldMappingSchema: () => ExternalFieldMappingSchema2, + ExternalLookupSchema: () => ExternalLookupSchema2, + FILTER_OPERATORS: () => FILTER_OPERATORS2, + FeedActorSchema: () => FeedActorSchema4, + FeedFilterMode: () => FeedFilterMode3, + FeedItemSchema: () => FeedItemSchema3, + FeedItemType: () => FeedItemType4, + FeedVisibility: () => FeedVisibility4, + Field: () => Field2, + FieldChangeEntrySchema: () => FieldChangeEntrySchema4, + FieldMappingSchema: () => FieldMappingSchema22, + FieldNodeSchema: () => FieldNodeSchema3, + FieldOperatorsSchema: () => FieldOperatorsSchema4, + FieldReferenceSchema: () => FieldReferenceSchema4, + FieldSchema: () => FieldSchema5, + FieldType: () => FieldType6, + FileAttachmentConfigSchema: () => FileAttachmentConfigSchema6, + FilterConditionSchema: () => FilterConditionSchema4, + FormatValidationSchema: () => FormatValidationSchema4, + FullTextSearchSchema: () => FullTextSearchSchema3, + HookContextSchema: () => HookContextSchema2, + HookEvent: () => HookEvent2, + HookSchema: () => HookSchema2, + IndexSchema: () => IndexSchema4, + JSONValidationSchema: () => JSONValidationSchema4, + JoinNodeSchema: () => JoinNodeSchema3, + JoinStrategy: () => JoinStrategy3, + JoinType: () => JoinType3, + LOGICAL_OPERATORS: () => LOGICAL_OPERATORS2, + LocationCoordinatesSchema: () => LocationCoordinatesSchema2, + MappingSchema: () => MappingSchema2, + MentionSchema: () => MentionSchema4, + MetricSchema: () => MetricSchema3, + NoSQLDataTypeMappingSchema: () => NoSQLDataTypeMappingSchema2, + NoSQLDatabaseTypeSchema: () => NoSQLDatabaseTypeSchema2, + NoSQLDriverConfigSchema: () => NoSQLDriverConfigSchema2, + NoSQLIndexSchema: () => NoSQLIndexSchema2, + NoSQLIndexTypeSchema: () => NoSQLIndexTypeSchema2, + NoSQLOperationTypeSchema: () => NoSQLOperationTypeSchema2, + NoSQLQueryOptionsSchema: () => NoSQLQueryOptionsSchema2, + NoSQLTransactionOptionsSchema: () => NoSQLTransactionOptionsSchema2, + NormalizedFilterSchema: () => NormalizedFilterSchema4, + NotificationChannel: () => NotificationChannel3, + ObjectCapabilities: () => ObjectCapabilities4, + ObjectDependencyGraphSchema: () => ObjectDependencyGraphSchema2, + ObjectDependencyNodeSchema: () => ObjectDependencyNodeSchema2, + ObjectExtensionSchema: () => ObjectExtensionSchema2, + ObjectOwnershipEnum: () => ObjectOwnershipEnum2, + ObjectSchema: () => ObjectSchema4, + PartitioningConfigSchema: () => PartitioningConfigSchema4, + PoolConfigSchema: () => PoolConfigSchema2, + QueryFilterSchema: () => QueryFilterSchema2, + QuerySchema: () => QuerySchema3, + RangeOperatorSchema: () => RangeOperatorSchema2, + ReactionSchema: () => ReactionSchema4, + RecordSubscriptionSchema: () => RecordSubscriptionSchema3, + ReferenceResolutionErrorSchema: () => ReferenceResolutionErrorSchema2, + ReferenceResolutionSchema: () => ReferenceResolutionSchema2, + ReplicationConfigSchema: () => ReplicationConfigSchema2, + SQLDialectSchema: () => SQLDialectSchema2, + SQLDriverConfigSchema: () => SQLDriverConfigSchema2, + SQLiteAlterTableLimitations: () => SQLiteAlterTableLimitations2, + SQLiteDataTypeMappingDefaults: () => SQLiteDataTypeMappingDefaults2, + SSLConfigSchema: () => SSLConfigSchema2, + ScriptValidationSchema: () => ScriptValidationSchema4, + SearchConfigSchema: () => SearchConfigSchema5, + SeedLoaderConfigSchema: () => SeedLoaderConfigSchema2, + SeedLoaderRequestSchema: () => SeedLoaderRequestSchema2, + SeedLoaderResultSchema: () => SeedLoaderResultSchema2, + SelectOptionSchema: () => SelectOptionSchema6, + SetOperatorSchema: () => SetOperatorSchema2, + ShardingConfigSchema: () => ShardingConfigSchema2, + SoftDeleteConfigSchema: () => SoftDeleteConfigSchema4, + SortNodeSchema: () => SortNodeSchema3, + SpecialOperatorSchema: () => SpecialOperatorSchema2, + StateMachineValidationSchema: () => StateMachineValidationSchema4, + StringOperatorSchema: () => StringOperatorSchema2, + SubscriptionEventType: () => SubscriptionEventType3, + TenancyConfigSchema: () => TenancyConfigSchema4, + TenantDatabaseLifecycleSchema: () => TenantDatabaseLifecycleSchema2, + TenantResolverStrategySchema: () => TenantResolverStrategySchema2, + TimeUpdateInterval: () => TimeUpdateInterval3, + TransformType: () => TransformType2, + TursoGroupSchema: () => TursoGroupSchema2, + TursoMultiTenantConfigSchema: () => TursoMultiTenantConfigSchema2, + UniquenessValidationSchema: () => UniquenessValidationSchema4, + VALID_AST_OPERATORS: () => VALID_AST_OPERATORS2, + ValidationRuleSchema: () => ValidationRuleSchema4, + VectorConfigSchema: () => VectorConfigSchema6, + VersioningConfigSchema: () => VersioningConfigSchema4, + WindowFunction: () => WindowFunction3, + WindowFunctionNodeSchema: () => WindowFunctionNodeSchema3, + WindowSpecSchema: () => WindowSpecSchema3, + isFilterAST: () => isFilterAST2, + parseFilterAST: () => parseFilterAST2 +}); +var FieldReferenceSchema4 = external_exports.object({ + $field: external_exports.string().describe("Field Reference/Column Name") +}); +var EqualityOperatorSchema2 = external_exports.object({ + /** Equal to (default) - SQL: = | MongoDB: $eq */ + $eq: external_exports.any().optional(), + /** Not equal to - SQL: <> or != | MongoDB: $ne */ + $ne: external_exports.any().optional() +}); +var ComparisonOperatorSchema2 = external_exports.object({ + /** Greater than - SQL: > | MongoDB: $gt */ + $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), + /** Greater than or equal to - SQL: >= | MongoDB: $gte */ + $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), + /** Less than - SQL: < | MongoDB: $lt */ + $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), + /** Less than or equal to - SQL: <= | MongoDB: $lte */ + $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional() +}); +var SetOperatorSchema2 = external_exports.object({ + /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */ + $in: external_exports.array(external_exports.any()).optional(), + /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */ + $nin: external_exports.array(external_exports.any()).optional() +}); +var RangeOperatorSchema2 = external_exports.object({ + /** Between (inclusive) - takes [min, max] array */ + $between: external_exports.tuple([ + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]), + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]) + ]).optional() +}); +var StringOperatorSchema2 = external_exports.object({ + /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */ + $contains: external_exports.string().optional(), + /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */ + $notContains: external_exports.string().optional(), + /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */ + $startsWith: external_exports.string().optional(), + /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */ + $endsWith: external_exports.string().optional() +}); +var SpecialOperatorSchema2 = external_exports.object({ + /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */ + $null: external_exports.boolean().optional(), + /** Field exists check (primarily for NoSQL) - MongoDB: $exists */ + $exists: external_exports.boolean().optional() +}); +var FieldOperatorsSchema4 = external_exports.object({ + // Equality + $eq: external_exports.any().optional(), + $ne: external_exports.any().optional(), + // Comparison (numeric/date) + $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), + $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), + $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), + $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), + // Set & Range + $in: external_exports.array(external_exports.any()).optional(), + $nin: external_exports.array(external_exports.any()).optional(), + $between: external_exports.tuple([ + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]), + external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]) + ]).optional(), + // String-specific + $contains: external_exports.string().optional(), + $notContains: external_exports.string().optional(), + $startsWith: external_exports.string().optional(), + $endsWith: external_exports.string().optional(), + // Special + $null: external_exports.boolean().optional(), + $exists: external_exports.boolean().optional() +}); +var FilterConditionSchema4 = external_exports.lazy( + () => external_exports.record(external_exports.string(), external_exports.unknown()).and( + external_exports.object({ + $and: external_exports.array(FilterConditionSchema4).optional(), + $or: external_exports.array(FilterConditionSchema4).optional(), + $not: FilterConditionSchema4.optional() + }) + ) +); +var QueryFilterSchema2 = external_exports.object({ + where: FilterConditionSchema4.optional() +}); +var NormalizedFilterSchema4 = external_exports.lazy( + () => external_exports.object({ + $and: external_exports.array( + external_exports.union([ + // Field condition: { field: { $op: value } } + external_exports.record(external_exports.string(), FieldOperatorsSchema4), + // Nested logical group + NormalizedFilterSchema4 + ]) + ).optional(), + $or: external_exports.array( + external_exports.union([ + external_exports.record(external_exports.string(), FieldOperatorsSchema4), + NormalizedFilterSchema4 + ]) + ).optional(), + $not: external_exports.union([ + external_exports.record(external_exports.string(), FieldOperatorsSchema4), + NormalizedFilterSchema4 + ]).optional() + }) +); +var VALID_AST_OPERATORS2 = /* @__PURE__ */ new Set([ + "=", + "==", + "!=", + "<>", + ">", + ">=", + "<", + "<=", + "in", + "nin", + "not_in", + "contains", + "notcontains", + "not_contains", + "like", + "startswith", + "starts_with", + "endswith", + "ends_with", + "between", + "is_null", + "is_not_null" +]); +function isFilterAST2(filter) { + if (!Array.isArray(filter) || filter.length === 0) return false; + const first = filter[0]; + if (typeof first === "string") { + const lower = first.toLowerCase(); + if (lower === "and" || lower === "or") { + return filter.length >= 2 && filter.slice(1).every((child) => isFilterAST2(child)); + } + if (filter.length >= 2 && typeof filter[1] === "string") { + return VALID_AST_OPERATORS2.has(filter[1].toLowerCase()); + } + } + if (filter.every((item) => isFilterAST2(item))) { + return filter.length > 0; + } + return false; +} +var AST_OPERATOR_MAP2 = { + "=": "$eq", + "==": "$eq", + "!=": "$ne", + "<>": "$ne", + ">": "$gt", + ">=": "$gte", + "<": "$lt", + "<=": "$lte", + "in": "$in", + "nin": "$nin", + "not_in": "$nin", + "contains": "$contains", + "notcontains": "$notContains", + "not_contains": "$notContains", + "like": "$contains", + "startswith": "$startsWith", + "starts_with": "$startsWith", + "endswith": "$endsWith", + "ends_with": "$endsWith", + "between": "$between", + "is_null": "$null", + "is_not_null": "$null" +}; +function convertComparison2(node) { + const [field, operator, value] = node; + const op = operator.toLowerCase(); + if (op === "=" || op === "==") { + return { [field]: value }; + } + if (op === "is_null") { + return { [field]: { $null: true } }; + } + if (op === "is_not_null") { + return { [field]: { $null: false } }; + } + const mapped = AST_OPERATOR_MAP2[op]; + if (mapped) { + return { [field]: { [mapped]: value } }; + } + return { [field]: { [`$${op}`]: value } }; +} +function parseFilterAST2(filter) { + if (filter == null) return void 0; + if (!Array.isArray(filter)) return filter; + if (filter.length === 0) return void 0; + const first = filter[0]; + if (typeof first === "string" && (first.toLowerCase() === "and" || first.toLowerCase() === "or")) { + const logicOp = `$${first.toLowerCase()}`; + const children = filter.slice(1).map((child) => parseFilterAST2(child)).filter(Boolean); + if (children.length === 0) return void 0; + if (children.length === 1) return children[0]; + return { [logicOp]: children }; + } + if (filter.length >= 2 && typeof first === "string") { + return convertComparison2(filter); + } + if (filter.every((item) => Array.isArray(item))) { + const children = filter.map((child) => parseFilterAST2(child)).filter(Boolean); + if (children.length === 0) return void 0; + if (children.length === 1) return children[0]; + return { $and: children }; + } + return void 0; +} +var FILTER_OPERATORS2 = [ + // Equality + "$eq", + "$ne", + // Comparison + "$gt", + "$gte", + "$lt", + "$lte", + // Set & Range + "$in", + "$nin", + "$between", + // String + "$contains", + "$notContains", + "$startsWith", + "$endsWith", + // Special + "$null", + "$exists" +]; +var LOGICAL_OPERATORS2 = ["$and", "$or", "$not"]; +var ALL_OPERATORS2 = [...FILTER_OPERATORS2, ...LOGICAL_OPERATORS2]; +var SortNodeSchema3 = external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]).default("asc") +}); +var AggregationFunction3 = external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "array_agg", + "string_agg" +]); +var AggregationNodeSchema3 = external_exports.object({ + function: AggregationFunction3.describe("Aggregation function"), + field: external_exports.string().optional().describe("Field to aggregate (optional for COUNT(*))"), + alias: external_exports.string().describe("Result column alias"), + distinct: external_exports.boolean().optional().describe("Apply DISTINCT before aggregation"), + filter: FilterConditionSchema4.optional().describe("Filter/Condition to apply to the aggregation (FILTER WHERE clause)") +}); +var JoinType3 = external_exports.enum(["inner", "left", "right", "full"]); +var JoinStrategy3 = external_exports.enum(["auto", "database", "hash", "loop"]); +var JoinNodeSchema3 = external_exports.lazy( + () => external_exports.object({ + type: JoinType3.describe("Join type"), + strategy: JoinStrategy3.optional().describe("Execution strategy hint"), + object: external_exports.string().describe("Object/table to join"), + alias: external_exports.string().optional().describe("Table alias"), + on: FilterConditionSchema4.describe("Join condition"), + subquery: external_exports.lazy(() => QuerySchema3).optional().describe("Subquery instead of object") + }) +); +var WindowFunction3 = external_exports.enum([ + "row_number", + "rank", + "dense_rank", + "percent_rank", + "lag", + "lead", + "first_value", + "last_value", + "sum", + "avg", + "count", + "min", + "max" +]); +var WindowSpecSchema3 = external_exports.object({ + partitionBy: external_exports.array(external_exports.string()).optional().describe("PARTITION BY fields"), + orderBy: external_exports.array(SortNodeSchema3).optional().describe("ORDER BY specification"), + frame: external_exports.object({ + type: external_exports.enum(["rows", "range"]).optional(), + start: external_exports.string().optional().describe('Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")'), + end: external_exports.string().optional().describe('Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")') + }).optional().describe("Window frame specification") +}); +var WindowFunctionNodeSchema3 = external_exports.object({ + function: WindowFunction3.describe("Window function name"), + field: external_exports.string().optional().describe("Field to operate on (for aggregate window functions)"), + alias: external_exports.string().describe("Result column alias"), + over: WindowSpecSchema3.describe("Window specification (OVER clause)") +}); +var FieldNodeSchema3 = external_exports.lazy( + () => external_exports.union([ + external_exports.string(), + // Primitive field: "name" + external_exports.object({ + field: external_exports.string(), + // Relationship field: "owner" + fields: external_exports.array(FieldNodeSchema3).optional(), + // Nested select: ["name", "email"] + alias: external_exports.string().optional() + }) + ]) +); +var FullTextSearchSchema3 = external_exports.object({ + query: external_exports.string().describe("Search query text"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to search in (if not specified, searches all text fields)"), + fuzzy: external_exports.boolean().optional().default(false).describe("Enable fuzzy matching (tolerates typos)"), + operator: external_exports.enum(["and", "or"]).optional().default("or").describe("Logical operator between terms"), + boost: external_exports.record(external_exports.string(), external_exports.number()).optional().describe("Field-specific relevance boosting (field name -> boost factor)"), + minScore: external_exports.number().optional().describe("Minimum relevance score threshold"), + language: external_exports.string().optional().describe('Language for text analysis (e.g., "en", "zh", "es")'), + highlight: external_exports.boolean().optional().default(false).describe("Enable search result highlighting") +}); +var BaseQuerySchema3 = external_exports.object({ + /** Target Entity */ + object: external_exports.string().describe("Object name (e.g. account)"), + /** Select Clause */ + fields: external_exports.array(FieldNodeSchema3).optional().describe("Fields to retrieve"), + /** Where Clause (Filtering) */ + where: FilterConditionSchema4.optional().describe("Filtering criteria (WHERE)"), + /** Full-Text Search */ + search: FullTextSearchSchema3.optional().describe("Full-text search configuration ($search parameter)"), + /** Order By Clause (Sorting) */ + orderBy: external_exports.array(SortNodeSchema3).optional().describe("Sorting instructions (ORDER BY)"), + /** Pagination */ + limit: external_exports.number().optional().describe("Max records to return (LIMIT)"), + offset: external_exports.number().optional().describe("Records to skip (OFFSET)"), + top: external_exports.number().optional().describe("Alias for limit (OData compatibility)"), + cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Cursor for keyset pagination"), + /** Joins */ + joins: external_exports.array(JoinNodeSchema3).optional().describe("Explicit Table Joins"), + /** Aggregations */ + aggregations: external_exports.array(AggregationNodeSchema3).optional().describe("Aggregation functions"), + /** Group By Clause */ + groupBy: external_exports.array(external_exports.string()).optional().describe("GROUP BY fields"), + /** Having Clause */ + having: FilterConditionSchema4.optional().describe("HAVING clause for aggregation filtering"), + /** Window Functions */ + windowFunctions: external_exports.array(WindowFunctionNodeSchema3).optional().describe("Window functions with OVER clause"), + /** Subquery flag */ + distinct: external_exports.boolean().optional().describe("SELECT DISTINCT flag") +}); +var QuerySchema3 = BaseQuerySchema3.extend({ + expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema3)).optional().describe( + "Recursive relation loading map. Keys are lookup/master_detail field names; values are nested QueryAST objects that control select, filter, sort, and further expansion on the related object. The engine resolves expand via batch $in queries (driver-agnostic) with a default max depth of 3." + ) +}); +var BaseValidationSchema4 = external_exports.object({ + // Identification + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label for the rule listing"), + description: external_exports.string().optional().describe("Administrative notes explaining the business reason"), + // Execution Control + active: external_exports.boolean().default(true), + events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).default(["insert", "update"]).describe("Validation contexts"), + priority: external_exports.number().int().min(0).max(9999).default(100).describe("Execution priority (lower runs first, default: 100)"), + // Classification + tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g., "compliance", "billing")'), + // Feedback + severity: external_exports.enum(["error", "warning", "info"]).default("error"), + message: external_exports.string().describe("Error message to display to the user") +}); +var ScriptValidationSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("script"), + condition: external_exports.string().describe("Formula expression. If TRUE, validation fails. (e.g. amount < 0)") +}); +var UniquenessValidationSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("unique"), + fields: external_exports.array(external_exports.string()).describe("Fields that must be combined unique"), + scope: external_exports.string().optional().describe("Formula condition for scope (e.g. active = true)"), + caseSensitive: external_exports.boolean().default(true) +}); +var StateMachineValidationSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("state_machine"), + field: external_exports.string().describe("State field (e.g. status)"), + transitions: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).describe("Map of { OldState: [AllowedNewStates] }") +}); +var FormatValidationSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("format"), + field: external_exports.string(), + regex: external_exports.string().optional(), + format: external_exports.enum(["email", "url", "phone", "json"]).optional() +}); +var CrossFieldValidationSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("cross_field"), + condition: external_exports.string().describe('Formula expression comparing fields (e.g. "end_date > start_date")'), + fields: external_exports.array(external_exports.string()).describe("Fields involved in the validation") +}); +var JSONValidationSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("json_schema"), + field: external_exports.string().describe("JSON field to validate"), + schema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema object definition") +}); +var AsyncValidationSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("async"), + field: external_exports.string().describe("Field to validate"), + validatorUrl: external_exports.string().optional().describe("External API endpoint for validation"), + method: external_exports.enum(["GET", "POST"]).default("GET").describe("HTTP method for external call"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for the request"), + validatorFunction: external_exports.string().optional().describe("Reference to custom validator function"), + timeout: external_exports.number().optional().default(5e3).describe("Timeout in milliseconds"), + debounce: external_exports.number().optional().describe("Debounce delay in milliseconds"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional parameters to pass to validator") +}); +var CustomValidatorSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("custom"), + handler: external_exports.string().describe("Name of the custom validation function registered in the system"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the custom handler") +}); +var ValidationRuleSchema4 = external_exports.lazy( + () => external_exports.discriminatedUnion("type", [ + ScriptValidationSchema4, + UniquenessValidationSchema4, + StateMachineValidationSchema4, + FormatValidationSchema4, + CrossFieldValidationSchema4, + JSONValidationSchema4, + AsyncValidationSchema4, + CustomValidatorSchema4, + ConditionalValidationSchema4 + ]) +); +var ConditionalValidationSchema4 = BaseValidationSchema4.extend({ + type: external_exports.literal("conditional"), + when: external_exports.string().describe(`Condition formula (e.g. "type = 'enterprise'")`), + then: ValidationRuleSchema4.describe("Validation rule to apply when condition is true"), + otherwise: ValidationRuleSchema4.optional().describe("Validation rule to apply when condition is false") +}); +var ActionRefSchema4 = external_exports.union([ + external_exports.string().describe("Action Name"), + external_exports.object({ + type: external_exports.string(), + // e.g., 'xstate.assign', 'log', 'email' + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }) +]); +var GuardRefSchema4 = external_exports.union([ + external_exports.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'), + external_exports.object({ + type: external_exports.string(), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }) +]); +var TransitionSchema4 = external_exports.object({ + target: external_exports.string().optional().describe("Target State ID"), + cond: GuardRefSchema4.optional().describe("Condition (Guard) required to take this path"), + actions: external_exports.array(ActionRefSchema4).optional().describe("Actions to execute during transition"), + description: external_exports.string().optional().describe("Human readable description of this rule") +}); +var EventSchema2 = external_exports.object({ + type: external_exports.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'), + // Payload validation schema could go here if we want deep validation + schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Expected event payload structure") +}); +var StateNodeSchema4 = external_exports.lazy(() => external_exports.object({ + /** Type of state */ + type: external_exports.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"), + /** Entry/Exit Actions */ + entry: external_exports.array(ActionRefSchema4).optional().describe("Actions to run when entering this state"), + exit: external_exports.array(ActionRefSchema4).optional().describe("Actions to run when leaving this state"), + /** Transitions (Events) */ + on: external_exports.record(external_exports.string(), external_exports.union([ + external_exports.string(), + // Shorthand target + TransitionSchema4, + external_exports.array(TransitionSchema4) + ])).optional().describe("Map of Event Type -> Transition Definition"), + /** Always Transitions (Eventless) */ + always: external_exports.array(TransitionSchema4).optional(), + /** Nesting (Hierarchical States) */ + initial: external_exports.string().optional().describe("Initial child state (if compound)"), + states: external_exports.record(external_exports.string(), StateNodeSchema4).optional(), + /** Metadata for UI/AI */ + meta: external_exports.object({ + label: external_exports.string().optional(), + description: external_exports.string().optional(), + color: external_exports.string().optional(), + // For UI diagrams + // Instructions for AI Agent when in this state + aiInstructions: external_exports.string().optional().describe("Specific instructions for AI when in this state") + }).optional() +})); +var StateMachineSchema4 = external_exports.object({ + id: SnakeCaseIdentifierSchema7.describe("Unique Machine ID"), + description: external_exports.string().optional(), + /** Context (Memory) Schema */ + contextSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Zod Schema for the machine context/memory"), + /** Initial State */ + initial: external_exports.string().describe("Initial State ID"), + /** State Definitions */ + states: external_exports.record(external_exports.string(), StateNodeSchema4).describe("State Nodes"), + /** Global Listeners */ + on: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), TransitionSchema4, external_exports.array(TransitionSchema4)])).optional() +}); +var I18nObjectSchema2 = external_exports.object({ + /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ + key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), + /** Default value when translation is not available */ + defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), + /** Interpolation parameters for dynamic translations */ + params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") +}); +var I18nLabelSchema5 = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); +var AriaPropsSchema5 = external_exports.object({ + /** Accessible label for screen readers */ + ariaLabel: I18nLabelSchema5.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), + /** ID of element that describes this component */ + ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), + /** WAI-ARIA role override */ + role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') +}).describe("ARIA accessibility attributes"); +var PluralRuleSchema2 = external_exports.object({ + /** Translation key for the plural form */ + key: external_exports.string().describe("Translation key"), + /** Form for zero quantity */ + zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), + /** Form for singular (1) */ + one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), + /** Form for dual (2) — used in Arabic, Welsh, etc. */ + two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), + /** Form for few (2-4 in Slavic languages) */ + few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), + /** Form for many (5+ in Slavic languages) */ + many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), + /** Default/fallback form */ + other: external_exports.string().describe('Default plural form (e.g., "{count} items")') +}).describe("ICU plural rules for a translation key"); +var NumberFormatSchema5 = external_exports.object({ + style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), + currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), + unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), + minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), + maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), + useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") +}).describe("Number formatting rules"); +var DateFormatSchema5 = external_exports.object({ + dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), + timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), + timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), + hour12: external_exports.boolean().optional().describe("Use 12-hour format") +}).describe("Date/time formatting rules"); +var LocaleConfigSchema2 = external_exports.object({ + /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ + code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), + /** Ordered fallback chain for missing translations */ + fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), + /** Text direction */ + direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), + /** Default number formatting */ + numberFormat: NumberFormatSchema5.optional().describe("Default number formatting rules"), + /** Default date formatting */ + dateFormat: DateFormatSchema5.optional().describe("Default date/time formatting rules") +}).describe("Locale configuration"); +var ActionParamSchema5 = external_exports.object({ + name: external_exports.string(), + label: I18nLabelSchema5, + type: FieldType6, + required: external_exports.boolean().default(false), + options: external_exports.array(external_exports.object({ label: I18nLabelSchema5, value: external_exports.string() })).optional() +}); +var ActionType5 = external_exports.enum(["script", "url", "modal", "flow", "api"]); +var TARGET_REQUIRED_TYPES5 = new Set( + ActionType5.options.filter((t) => t !== "script") +); +var ActionSchema5 = external_exports.object({ + /** Machine name of the action */ + name: SnakeCaseIdentifierSchema7.describe("Machine name (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema5.describe("Display label"), + /** Target object this action belongs to (optional, snake_case) */ + objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Icon name"), + /** Where does this action appear? */ + locations: external_exports.array(external_exports.enum([ + "list_toolbar", + "list_item", + "record_header", + "record_more", + "record_related", + "global_nav" + ])).optional().describe("Locations where this action is visible"), + /** + * Visual Component Type + * Defaults to 'button' or 'menu_item' based on location, + * but can be overridden. + */ + component: external_exports.enum([ + "action:button", + // Standard Button + "action:icon", + // Icon only + "action:menu", + // Dropdown menu + "action:group" + // Button Group + ]).optional().describe("Visual component override"), + /** What type of interaction? */ + type: ActionType5.default("script").describe("Action functionality type"), + /** + * Payload / Target — the canonical binding for the action handler. + * Required for url, flow, modal, and api types. + * Recommended for script type. + */ + target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), + /** + * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. + */ + execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), + /** User Input Requirements */ + params: external_exports.array(ActionParamSchema5).optional().describe("Input parameters required from user"), + /** Visual Style */ + variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), + /** UX Behavior */ + confirmText: I18nLabelSchema5.optional().describe("Confirmation message before execution"), + successMessage: I18nLabelSchema5.optional().describe("Success message to show after execution"), + refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), + /** Access */ + visible: external_exports.string().optional().describe("Formula returning boolean"), + disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), + /** Keyboard Shortcut */ + shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), + /** Bulk Operations */ + bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), + /** Execution */ + timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}).transform((data) => { + if (data.execute && !data.target) { + return { ...data, target: data.execute }; + } + return data; +}).refine((data) => { + if (TARGET_REQUIRED_TYPES5.has(data.type) && !data.target) { + return false; + } + return true; +}, { + message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", + path: ["target"] +}); +var Action = { + create: (config4) => ActionSchema5.parse(config4) +}; +var ApiMethod4 = external_exports.enum([ + "get", + "list", + // Read + "create", + "update", + "delete", + // Write + "upsert", + // Idempotent Write + "bulk", + // Batch operations + "aggregate", + // Analytics (count, sum) + "history", + // Audit access + "search", + // Search access + "restore", + "purge", + // Trash management + "import", + "export" + // Data portability +]); +var ObjectCapabilities4 = external_exports.object({ + /** Enable history tracking (Audit Trail) */ + trackHistory: external_exports.boolean().default(false).describe("Enable field history tracking for audit compliance"), + /** Enable global search indexing */ + searchable: external_exports.boolean().default(true).describe("Index records for global search"), + /** Enable REST/GraphQL API access */ + apiEnabled: external_exports.boolean().default(true).describe("Expose object via automatic APIs"), + /** + * API Supported Operations + * Granular control over API exposure. + */ + apiMethods: external_exports.array(ApiMethod4).optional().describe("Whitelist of allowed API operations"), + /** Enable standard attachments/files engine */ + files: external_exports.boolean().default(false).describe("Enable file attachments and document management"), + /** Enable social collaboration (Comments, Mentions, Feeds) */ + feeds: external_exports.boolean().default(false).describe("Enable social feed, comments, and mentions (Chatter-like)"), + /** Enable standard Activity suite (Tasks, Calendars, Events) */ + activities: external_exports.boolean().default(false).describe("Enable standard tasks and events tracking"), + /** Enable Recycle Bin / Soft Delete */ + trash: external_exports.boolean().default(true).describe("Enable soft-delete with restore capability"), + /** Enable "Recently Viewed" tracking */ + mru: external_exports.boolean().default(true).describe("Track Most Recently Used (MRU) list for users"), + /** Allow cloning records */ + clone: external_exports.boolean().default(true).describe("Allow record deep cloning") +}); +var IndexSchema4 = external_exports.object({ + name: external_exports.string().optional().describe("Index name (auto-generated if not provided)"), + fields: external_exports.array(external_exports.string()).describe("Fields included in the index"), + type: external_exports.enum(["btree", "hash", "gin", "gist", "fulltext"]).optional().default("btree").describe("Index algorithm type"), + unique: external_exports.boolean().optional().default(false).describe("Whether the index enforces uniqueness"), + partial: external_exports.string().optional().describe("Partial index condition (SQL WHERE clause for conditional indexes)") +}); +var SearchConfigSchema5 = external_exports.object({ + fields: external_exports.array(external_exports.string()).describe("Fields to index for full-text search weighting"), + displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display in search result cards"), + filters: external_exports.array(external_exports.string()).optional().describe("Default filters for search results") +}); +var TenancyConfigSchema4 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable multi-tenancy for this object"), + strategy: external_exports.enum(["shared", "isolated", "hybrid"]).describe("Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)"), + tenantField: external_exports.string().default("tenant_id").describe("Field name for tenant identifier"), + crossTenantAccess: external_exports.boolean().default(false).describe("Allow cross-tenant data access (with explicit permission)") +}); +var SoftDeleteConfigSchema4 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable soft delete (trash/recycle bin)"), + field: external_exports.string().default("deleted_at").describe("Field name for soft delete timestamp"), + cascadeDelete: external_exports.boolean().default(false).describe("Cascade soft delete to related records") +}); +var VersioningConfigSchema4 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable record versioning"), + strategy: external_exports.enum(["snapshot", "delta", "event-sourcing"]).describe("Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)"), + retentionDays: external_exports.number().min(1).optional().describe("Number of days to retain old versions (undefined = infinite)"), + versionField: external_exports.string().default("version").describe("Field name for version number/timestamp") +}); +var PartitioningConfigSchema4 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable table partitioning"), + strategy: external_exports.enum(["range", "hash", "list"]).describe("Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)"), + key: external_exports.string().describe("Field name to partition by"), + interval: external_exports.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")') +}).refine((data) => { + if (data.strategy === "range" && !data.interval) { + return false; + } + return true; +}, { + message: 'interval is required when strategy is "range"' +}); +var CDCConfigSchema4 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable Change Data Capture"), + events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).describe("Event types to capture"), + destination: external_exports.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")') +}); +var ObjectSchemaBase4 = external_exports.object({ + /** + * Identity & Metadata + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine unique key (snake_case). Immutable."), + label: external_exports.string().optional().describe('Human readable singular label (e.g. "Account")'), + pluralLabel: external_exports.string().optional().describe('Human readable plural label (e.g. "Accounts")'), + description: external_exports.string().optional().describe("Developer documentation / description"), + icon: external_exports.string().optional().describe("Icon name (Lucide/Material) for UI representation"), + /** + * Namespace & Domain Classification + * + * Groups objects into logical domains for routing, permissions, and discovery. + * System objects use `'sys'`; business packages use their own namespace. + * + * When set, `tableName` is auto-derived as `{namespace}_{name}` by + * `ObjectSchema.create()` unless an explicit `tableName` is provided. + * + * Namespace must be a single lowercase word (no underscores or hyphens) + * to ensure clean auto-derivation of `{namespace}_{name}` table names. + * + * @example namespace: 'sys' → tableName defaults to 'sys_user' + * @example namespace: 'crm' → tableName defaults to 'crm_account' + */ + namespace: external_exports.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace \u2014 single lowercase word (e.g. "sys", "crm"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'), + /** + * Taxonomy & Organization + */ + tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'), + active: external_exports.boolean().optional().default(true).describe("Is the object active and usable"), + isSystem: external_exports.boolean().optional().default(false).describe("Is system object (protected from deletion)"), + abstract: external_exports.boolean().optional().default(false).describe("Is abstract base object (cannot be instantiated)"), + /** + * Storage & Virtualization + */ + datasource: external_exports.string().optional().default("default").describe('Target Datasource ID. "default" is the primary DB.'), + tableName: external_exports.string().optional().describe("Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set."), + /** + * Data Model + */ + fields: external_exports.record(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/, { + message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")' + }), FieldSchema5).describe("Field definitions map. Keys must be snake_case identifiers."), + indexes: external_exports.array(IndexSchema4).optional().describe("Database performance indexes"), + /** + * Advanced Data Management + */ + // Multi-tenancy configuration + tenancy: TenancyConfigSchema4.optional().describe("Multi-tenancy configuration for SaaS applications"), + // Soft delete configuration + softDelete: SoftDeleteConfigSchema4.optional().describe("Soft delete (trash/recycle bin) configuration"), + // Versioning configuration + versioning: VersioningConfigSchema4.optional().describe("Record versioning and history tracking configuration"), + // Partitioning strategy + partitioning: PartitioningConfigSchema4.optional().describe("Table partitioning configuration for performance"), + // Change Data Capture + cdc: CDCConfigSchema4.optional().describe("Change Data Capture (CDC) configuration for real-time data streaming"), + /** + * Logic & Validation (Co-located) + * Best Practice: Define rules close to data. + */ + validations: external_exports.array(ValidationRuleSchema4).optional().describe("Object-level validation rules"), + /** + * State Machine(s) + * Named record of state machines, where each key is a unique machine identifier. + * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status). + * + * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} } + */ + stateMachines: external_exports.record(external_exports.string(), StateMachineSchema4).optional().describe("Named state machines for parallel lifecycles (e.g., status, payment, approval)"), + /** + * Display & UI Hints (Data-Layer) + */ + displayNameField: external_exports.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'), + recordName: external_exports.object({ + type: external_exports.enum(["text", "autonumber"]).describe("Record name type: text (user-entered) or autonumber (system-generated)"), + displayFormat: external_exports.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'), + startNumber: external_exports.number().int().min(0).optional().describe("Starting number for autonumber (default: 1)") + }).optional().describe("Record name generation configuration (Salesforce pattern)"), + titleFormat: external_exports.string().optional().describe('Title expression (e.g. "{name} - {code}"). Overrides displayNameField.'), + compactLayout: external_exports.array(external_exports.string()).optional().describe("Primary fields for hover/cards/lookups"), + /** + * Search Engine Config + */ + search: SearchConfigSchema5.optional().describe("Search engine configuration"), + /** + * System Capabilities + */ + enable: ObjectCapabilities4.optional().describe("Enabled system features modules"), + /** Record Types */ + recordTypes: external_exports.array(external_exports.string()).optional().describe("Record type names for this object"), + /** Sharing Model */ + sharingModel: external_exports.enum(["private", "read", "read_write", "full"]).optional().describe("Default sharing model"), + /** Key Prefix */ + keyPrefix: external_exports.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'), + /** + * Object Actions + * + * Actions associated with this object. Populated automatically by `defineStack()` + * when top-level actions specify `objectName` matching this object. + * Can also be defined directly on the object. + * + * Aligns with Salesforce/ServiceNow patterns where actions are part of the + * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`) + * include the action list without requiring downstream merge. + */ + actions: external_exports.array(ActionSchema5).optional().describe("Actions associated with this object (auto-populated from top-level actions via objectName)") +}); +function snakeCaseToLabel4(name) { + return name.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); +} +var ObjectSchema4 = Object.assign(ObjectSchemaBase4, { + /** + * Type-safe factory for creating business object definitions. + * + * Enhancements over raw schema: + * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case). + * - **Validation**: Runs Zod `.parse()` to validate the config at creation time. + * + * @example + * ```ts + * const Task = ObjectSchema.create({ + * name: 'project_task', + * // label auto-generated as 'Project Task' + * fields: { + * subject: { type: 'text', label: 'Subject', required: true }, + * }, + * }); + * ``` + */ + create: (config4) => { + const withDefaults = { + ...config4, + label: config4.label ?? snakeCaseToLabel4(config4.name), + // Auto-derive tableName as {namespace}_{name} when namespace is set + tableName: config4.tableName ?? (config4.namespace ? `${config4.namespace}_${config4.name}` : void 0) + }; + return ObjectSchemaBase4.parse(withDefaults); + } +}); +var ObjectOwnershipEnum2 = external_exports.enum(["own", "extend"]); +var ObjectExtensionSchema2 = external_exports.object({ + /** The target object name (FQN) to extend */ + extend: external_exports.string().describe("Target object name (FQN) to extend"), + /** Fields to merge into the target object (additive) */ + fields: external_exports.record(external_exports.string(), FieldSchema5).optional().describe("Fields to add/override"), + /** Override label */ + label: external_exports.string().optional().describe("Override label for the extended object"), + /** Override plural label */ + pluralLabel: external_exports.string().optional().describe("Override plural label for the extended object"), + /** Override description */ + description: external_exports.string().optional().describe("Override description for the extended object"), + /** Additional validation rules to add */ + validations: external_exports.array(ValidationRuleSchema4).optional().describe("Additional validation rules to merge into the target object"), + /** Additional indexes to add */ + indexes: external_exports.array(IndexSchema4).optional().describe("Additional indexes to merge into the target object"), + /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ + priority: external_exports.number().int().min(0).max(999).default(200).describe("Merge priority (higher = applied later)") +}); +var HookEvent2 = external_exports.enum([ + // Read Operations + "beforeFind", + "afterFind", + "beforeFindOne", + "afterFindOne", + "beforeCount", + "afterCount", + "beforeAggregate", + "afterAggregate", + // Write Operations + "beforeInsert", + "afterInsert", + "beforeUpdate", + "afterUpdate", + "beforeDelete", + "afterDelete", + // Bulk Operations (Query-based) + "beforeUpdateMany", + "afterUpdateMany", + "beforeDeleteMany", + "afterDeleteMany" +]); +var HookSchema2 = external_exports.object({ + /** + * Unique identifier for the hook + * Required for debugging and overriding. + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Hook unique name (snake_case)"), + /** + * Human readable label + */ + label: external_exports.string().optional().describe("Description of what this hook does"), + /** + * Target Object(s) + * can be: + * - Single object: "account" + * - List of objects: ["account", "contact"] + * - Wildcard: "*" (All objects) + */ + object: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Target object(s)"), + /** + * Events to subscribe to + * Combinations of timing (before/after) and action (find/insert/update/delete/etc) + */ + events: external_exports.array(HookEvent2).describe("Lifecycle events"), + /** + * Handler Logic + * Reference to a registered function in the plugin system OR a direct function (runtime only). + */ + handler: external_exports.union([external_exports.string(), external_exports.function()]).optional().describe("Handler function name (string) or inline function reference"), + /** + * Execution Order + * Lower numbers run first. + * - System Hooks: 0-99 + * - App Hooks: 100-999 + * - User Hooks: 1000+ + */ + priority: external_exports.number().default(100).describe("Execution priority"), + /** + * Async / Background Execution + * If true, the hook runs in the background and does not block the transaction. + * Only applicable for 'after*' events. + * Default: false (Blocking) + */ + async: external_exports.boolean().default(false).describe("Run specifically as fire-and-forget"), + /** + * Declarative Condition + * Formula expression evaluated before the handler runs. + * If provided and evaluates to FALSE, the hook is skipped entirely. + * Useful for filtering by record data without writing handler code. + * + * @example "status = 'active' AND amount > 1000" + */ + condition: external_exports.string().optional().describe(`Formula expression; hook runs only when TRUE (e.g., "status = 'closed' AND amount > 1000")`), + /** + * Human-readable description + */ + description: external_exports.string().optional().describe("Human-readable description of what this hook does"), + /** + * Retry Policy + */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().default(3).describe("Maximum retry attempts on failure"), + backoffMs: external_exports.number().default(1e3).describe("Backoff delay between retries in milliseconds") + }).optional().describe("Retry policy for failed hook executions"), + /** + * Execution Timeout + */ + timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds before the hook is aborted"), + /** + * Error Policy + * What to do if the hook throws an exception? + * - abort: Rollback transaction (if blocking) + * - log: Log error and continue + */ + onError: external_exports.enum(["abort", "log"]).default("abort").describe("Error handling strategy") +}); +var HookContextSchema2 = external_exports.object({ + /** Tracing ID */ + id: external_exports.string().optional().describe("Unique execution ID for tracing"), + /** Target Object Name */ + object: external_exports.string(), + /** Current Lifecycle Event */ + event: HookEvent2, + /** + * Input Parameters (Mutable) + * Modify this to change the behavior of the operation. + * + * - find: { query: QueryAST, options: DriverOptions } + * - insert: { doc: Record, options: DriverOptions } + * - update: { id: ID, doc: Record, options: DriverOptions } + * - delete: { id: ID, options: DriverOptions } + * - updateMany: { query: QueryAST, doc: Record, options: DriverOptions } + * - deleteMany: { query: QueryAST, options: DriverOptions } + */ + input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Mutable input parameters"), + /** + * Operation Result (Mutable) + * Available in 'after*' events. Modify this to transform the output. + */ + result: external_exports.unknown().optional().describe("Operation result (After hooks only)"), + /** + * Data Snapshot + * The state of the record BEFORE the operation (for update/delete). + */ + previous: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record state before operation"), + /** + * Execution Session + * Contains authentication and tenancy information. + */ + session: external_exports.object({ + userId: external_exports.string().optional(), + tenantId: external_exports.string().optional(), + roles: external_exports.array(external_exports.string()).optional(), + accessToken: external_exports.string().optional() + }).optional().describe("Current session context"), + /** + * Transaction Handle + * If the operation is part of a transaction, use this handle for side-effects. + */ + transaction: external_exports.unknown().optional().describe("Database transaction handle"), + /** + * Engine Access + * Reference to the ObjectQL engine for performing side effects. + */ + ql: external_exports.unknown().describe("ObjectQL Engine Reference"), + /** + * Cross-Object API + * Provides a scoped data access interface for performing CRUD operations + * on other objects within hooks. Bound to the current execution context + * (userId, tenantId, transaction). + * + * Usage in hooks: + * const users = ctx.api.object('user'); + * const admin = await users.findOne({ filter: { role: 'admin' } }); + */ + api: external_exports.unknown().optional().describe("Cross-object data access (ScopedContext)"), + /** + * Current User Info + * Convenience shortcut for session.userId + additional user metadata. + * Populated by the engine when available. + */ + user: external_exports.object({ + id: external_exports.string().optional(), + name: external_exports.string().optional(), + email: external_exports.string().optional() + }).optional().describe("Current user info shortcut") +}); +var TransformType2 = external_exports.enum([ + "none", + // Direct copy + "constant", + // Use a hardcoded value + "lookup", + // Resolve FK (Name -> ID) + "split", + // "John Doe" -> ["John", "Doe"] + "join", + // ["John", "Doe"] -> "John Doe" + "javascript", + // Custom script (Review security!) + "map" + // Value mapping (e.g. "Active" -> "active") +]); +var FieldMappingSchema22 = external_exports.object({ + /** Source Column */ + source: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Source column header(s)"), + /** Target Field */ + target: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Target object field(s)"), + /** Transformation */ + transform: TransformType2.default("none"), + /** Configuration for transform */ + params: external_exports.object({ + // Constant + value: external_exports.unknown().optional(), + // Lookup + object: external_exports.string().optional(), + // Lookup Object + fromField: external_exports.string().optional(), + // Match on (e.g. "name") + toField: external_exports.string().optional(), + // Value to take (e.g. "id") + autoCreate: external_exports.boolean().optional(), + // Create if missing + // Map + valueMap: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + // { "Open": "draft" } + // Split/Join + separator: external_exports.string().optional() + }).optional() +}); +var MappingSchema2 = external_exports.object({ + /** Identity */ + name: SnakeCaseIdentifierSchema7.describe("Mapping unique name (lowercase snake_case)"), + label: external_exports.string().optional(), + /** Scope */ + sourceFormat: external_exports.enum(["csv", "json", "xml", "sql"]).default("csv"), + targetObject: external_exports.string().describe("Target Object Name"), + /** Column Mappings */ + fieldMapping: external_exports.array(FieldMappingSchema22), + /** Upsert Logic */ + mode: external_exports.enum(["insert", "update", "upsert"]).default("insert"), + upsertKey: external_exports.array(external_exports.string()).optional().describe("Fields to match for upsert (e.g. email)"), + /** Extract Logic (For Export) */ + extractQuery: QuerySchema3.optional().describe("Query to run for export only"), + /** Error Handling */ + errorPolicy: external_exports.enum(["skip", "abort", "retry"]).default("skip"), + batchSize: external_exports.number().default(1e3) +}); +var ExecutionContextSchema3 = external_exports.object({ + /** Current user ID (resolved from session) */ + userId: external_exports.string().optional(), + /** Current organization/tenant ID (resolved from session.activeOrganizationId) */ + tenantId: external_exports.string().optional(), + /** User role names (resolved from Member + Role) */ + roles: external_exports.array(external_exports.string()).default([]), + /** Aggregated permission names (resolved from PermissionSet) */ + permissions: external_exports.array(external_exports.string()).default([]), + /** Whether this is a system-level operation (bypasses permission checks) */ + isSystem: external_exports.boolean().default(false), + /** Raw access token (for external API call pass-through) */ + accessToken: external_exports.string().optional(), + /** Database transaction handle */ + transaction: external_exports.unknown().optional(), + /** Request trace ID (for distributed tracing) */ + traceId: external_exports.string().optional() +}); +var DataEngineFilterSchema2 = external_exports.union([ + external_exports.record(external_exports.string(), external_exports.unknown()), + FilterConditionSchema4 +]).describe("Data Engine query filter conditions"); +var DataEngineSortSchema2 = external_exports.union([ + external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])), + external_exports.record(external_exports.string(), external_exports.union([external_exports.literal(1), external_exports.literal(-1)])), + external_exports.array(SortNodeSchema3) +]).describe("Sort order definition"); +var BaseEngineOptionsSchema2 = external_exports.object({ + /** Execution context (identity, tenant, transaction) */ + context: ExecutionContextSchema3.optional() +}); +var EngineQueryOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** Filter conditions (WHERE) — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), + /** Fields to retrieve (SELECT) — standard QueryAST `fields` */ + fields: external_exports.array(FieldNodeSchema3).optional(), + /** Sorting instructions (ORDER BY) — standard QueryAST `orderBy` */ + orderBy: external_exports.array(SortNodeSchema3).optional(), + /** Max records to return (LIMIT) */ + limit: external_exports.number().optional(), + /** Records to skip (OFFSET) — standard QueryAST `offset` */ + offset: external_exports.number().optional(), + /** Alias for limit (OData compatibility) */ + top: external_exports.number().optional(), + /** Cursor for keyset pagination */ + cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** Full-text search configuration */ + search: FullTextSearchSchema3.optional(), + /** + * Recursive relation loading map (expand). + * + * Keys are lookup/master_detail field names; values are nested QueryAST + * objects that control select, filter, sort, and further expansion on + * the related object. The engine resolves expand via batch $in queries + * (driver-agnostic) with a default max depth of 3. + */ + expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema3)).optional(), + /** SELECT DISTINCT flag */ + distinct: external_exports.boolean().optional() +}).describe("QueryAST-aligned query options for IDataEngine.find() operations"); +var DataEngineQueryOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** @deprecated Use `where` (EngineQueryOptionsSchema) */ + filter: DataEngineFilterSchema2.optional(), + /** @deprecated Use `fields` (EngineQueryOptionsSchema) */ + select: external_exports.array(external_exports.string()).optional(), + /** @deprecated Use `orderBy` (EngineQueryOptionsSchema) */ + sort: DataEngineSortSchema2.optional(), + limit: external_exports.number().int().min(1).optional(), + /** @deprecated Use `offset` (EngineQueryOptionsSchema) */ + skip: external_exports.number().int().min(0).optional(), + top: external_exports.number().int().min(1).optional(), + /** @deprecated Use `expand` (EngineQueryOptionsSchema) */ + populate: external_exports.array(external_exports.string()).optional() +}).describe("Query options for IDataEngine.find() operations"); +var DataEngineInsertOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** + * Return the inserted record(s)? + * Some drivers support RETURNING clause for efficiency. + * Default: true + */ + returning: external_exports.boolean().default(true).optional() +}).describe("Options for DataEngine.insert operations"); +var EngineUpdateOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** Filter conditions to identify records to update — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), + /** Perform an upsert? If true, insert if not found. */ + upsert: external_exports.boolean().default(false).optional(), + /** Update multiple records? If false, only the first match is updated. Default: false */ + multi: external_exports.boolean().default(false).optional(), + /** Return the updated record(s)? Default: false (returns update count/status) */ + returning: external_exports.boolean().default(false).optional() +}).describe("QueryAST-aligned options for DataEngine.update operations"); +var DataEngineUpdateOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** @deprecated Use `where` (EngineUpdateOptionsSchema) */ + filter: DataEngineFilterSchema2.optional(), + upsert: external_exports.boolean().default(false).optional(), + multi: external_exports.boolean().default(false).optional(), + returning: external_exports.boolean().default(false).optional() +}).describe("Options for DataEngine.update operations"); +var EngineDeleteOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** Filter conditions to identify records to delete — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), + /** Delete multiple records? If false, only the first match is deleted. Default: false */ + multi: external_exports.boolean().default(false).optional() +}).describe("QueryAST-aligned options for DataEngine.delete operations"); +var DataEngineDeleteOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** @deprecated Use `where` (EngineDeleteOptionsSchema) */ + filter: DataEngineFilterSchema2.optional(), + multi: external_exports.boolean().default(false).optional() +}).describe("Options for DataEngine.delete operations"); +var EngineAggregateOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** Filter conditions (WHERE) — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), + /** Group By fields */ + groupBy: external_exports.array(external_exports.string()).optional(), + /** + * Aggregation definitions — uses standard AggregationNodeSchema (`function` key). + * e.g. [{ function: 'sum', field: 'amount', alias: 'total' }] + */ + aggregations: external_exports.array(AggregationNodeSchema3).optional() +}).describe("QueryAST-aligned options for DataEngine.aggregate operations"); +var DataEngineAggregateOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** @deprecated Use `where` (EngineAggregateOptionsSchema) */ + filter: DataEngineFilterSchema2.optional(), + groupBy: external_exports.array(external_exports.string()).optional(), + /** + * @deprecated Use `EngineAggregateOptionsSchema` with standard AggregationNodeSchema (`function` key). + */ + aggregations: external_exports.array(external_exports.object({ + field: external_exports.string(), + method: external_exports.enum(["count", "sum", "avg", "min", "max", "count_distinct"]), + alias: external_exports.string().optional() + })).optional() +}).describe("Options for DataEngine.aggregate operations"); +var EngineCountOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** Filter conditions — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional() +}).describe("QueryAST-aligned options for DataEngine.count operations"); +var DataEngineCountOptionsSchema2 = BaseEngineOptionsSchema2.extend({ + /** @deprecated Use `where` (EngineCountOptionsSchema) */ + filter: DataEngineFilterSchema2.optional() +}).describe("Options for DataEngine.count operations"); +var DataEngineContractSchema2 = external_exports.object({ + find: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineQueryOptionsSchema2.optional()])).output(external_exports.promise(external_exports.array(external_exports.unknown()))), + findOne: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineQueryOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())), + insert: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown()))]), DataEngineInsertOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())), + update: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), EngineUpdateOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())), + delete: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineDeleteOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())), + count: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineCountOptionsSchema2.optional()])).output(external_exports.promise(external_exports.number())), + aggregate: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineAggregateOptionsSchema2])).output(external_exports.promise(external_exports.array(external_exports.unknown()))) +}).describe("Standard Data Engine Contract"); +var RpcLegacyFilterMixin2 = { + /** @deprecated Use `where` */ + filter: DataEngineFilterSchema2.optional() +}; +var RpcQueryOptionsSchema2 = EngineQueryOptionsSchema2.extend({ + ...RpcLegacyFilterMixin2, + /** @deprecated Use `fields` */ + select: external_exports.array(external_exports.string()).optional(), + /** @deprecated Use `orderBy` */ + sort: DataEngineSortSchema2.optional(), + /** @deprecated Use `offset` */ + skip: external_exports.number().int().min(0).optional(), + /** @deprecated Use `expand` */ + populate: external_exports.array(external_exports.string()).optional() +}); +var DataEngineFindRequestSchema2 = external_exports.object({ + method: external_exports.literal("find"), + object: external_exports.string(), + query: RpcQueryOptionsSchema2.optional() +}); +var DataEngineFindOneRequestSchema2 = external_exports.object({ + method: external_exports.literal("findOne"), + object: external_exports.string(), + query: RpcQueryOptionsSchema2.optional() +}); +var DataEngineInsertRequestSchema2 = external_exports.object({ + method: external_exports.literal("insert"), + object: external_exports.string(), + data: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown()))]), + options: DataEngineInsertOptionsSchema2.optional() +}); +var DataEngineUpdateRequestSchema2 = external_exports.object({ + method: external_exports.literal("update"), + object: external_exports.string(), + data: external_exports.record(external_exports.string(), external_exports.unknown()), + id: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("ID for single update, or use where in options"), + options: EngineUpdateOptionsSchema2.extend(RpcLegacyFilterMixin2).optional() +}); +var DataEngineDeleteRequestSchema2 = external_exports.object({ + method: external_exports.literal("delete"), + object: external_exports.string(), + id: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("ID for single delete, or use where in options"), + options: EngineDeleteOptionsSchema2.extend(RpcLegacyFilterMixin2).optional() +}); +var DataEngineCountRequestSchema2 = external_exports.object({ + method: external_exports.literal("count"), + object: external_exports.string(), + query: EngineCountOptionsSchema2.extend(RpcLegacyFilterMixin2).optional() +}); +var DataEngineAggregateRequestSchema2 = external_exports.object({ + method: external_exports.literal("aggregate"), + object: external_exports.string(), + query: EngineAggregateOptionsSchema2.extend(RpcLegacyFilterMixin2) +}); +var DataEngineExecuteRequestSchema2 = external_exports.object({ + method: external_exports.literal("execute"), + /** The abstract command (string SQL, or JSON object) */ + command: external_exports.unknown(), + /** Optional options */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var DataEngineVectorFindRequestSchema2 = external_exports.object({ + method: external_exports.literal("vectorFind"), + object: external_exports.string(), + /** The vector embedding to search for */ + vector: external_exports.array(external_exports.number()), + /** Optional pre-filter (Metadata filtering) — standard QueryAST `where` */ + where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), + /** Fields to retrieve — standard QueryAST `fields` */ + fields: external_exports.array(external_exports.string()).optional(), + /** Number of results */ + limit: external_exports.number().int().default(5).optional(), + /** Minimum similarity score (0-1) or distance threshold */ + threshold: external_exports.number().optional() +}); +var DataEngineBatchRequestSchema2 = external_exports.object({ + method: external_exports.literal("batch"), + requests: external_exports.array(external_exports.discriminatedUnion("method", [ + DataEngineFindRequestSchema2, + DataEngineFindOneRequestSchema2, + DataEngineInsertRequestSchema2, + DataEngineUpdateRequestSchema2, + DataEngineDeleteRequestSchema2, + DataEngineCountRequestSchema2, + DataEngineAggregateRequestSchema2, + DataEngineExecuteRequestSchema2, + DataEngineVectorFindRequestSchema2 + ])), + /** + * Transaction Mode + * - true: All or nothing (Atomic) + * - false: Best effort, continue on error + */ + transaction: external_exports.boolean().default(true).optional() +}); +var DataEngineRequestSchema2 = external_exports.discriminatedUnion("method", [ + DataEngineFindRequestSchema2, + DataEngineFindOneRequestSchema2, + DataEngineInsertRequestSchema2, + DataEngineUpdateRequestSchema2, + DataEngineDeleteRequestSchema2, + DataEngineCountRequestSchema2, + DataEngineAggregateRequestSchema2, + DataEngineBatchRequestSchema2, + DataEngineExecuteRequestSchema2, + DataEngineVectorFindRequestSchema2 +]).describe("Virtual ObjectQL Request Protocol"); +var DriverOptionsSchema2 = external_exports.object({ + /** + * Transaction handle/identifier. + * If provided, the operation must run within this transaction. + */ + transaction: external_exports.unknown().optional().describe("Transaction handle"), + /** + * Operation timeout in milliseconds. + */ + timeout: external_exports.number().optional().describe("Timeout in ms"), + /** + * Whether to bypass cache and force a fresh read. + */ + skipCache: external_exports.boolean().optional().describe("Bypass cache"), + /** + * Distributed Tracing Context. + * Used for passing OpenTelemetry span context or request IDs for observability. + */ + traceContext: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("OpenTelemetry context or request ID"), + /** + * Tenant Identifier. + * For multi-tenant databases (row-level security or schema-per-tenant). + */ + tenantId: external_exports.string().optional().describe("Tenant Isolation identifier") +}); +var DriverCapabilitiesSchema2 = external_exports.object({ + // ============================================================================ + // Basic CRUD Operations + // ============================================================================ + /** + * Whether the driver supports create operations. + */ + create: external_exports.boolean().default(true).describe("Supports CREATE operations"), + /** + * Whether the driver supports read operations. + */ + read: external_exports.boolean().default(true).describe("Supports READ operations"), + /** + * Whether the driver supports update operations. + */ + update: external_exports.boolean().default(true).describe("Supports UPDATE operations"), + /** + * Whether the driver supports delete operations. + */ + delete: external_exports.boolean().default(true).describe("Supports DELETE operations"), + // ============================================================================ + // Bulk Operations + // ============================================================================ + /** + * Whether the driver supports bulk create operations. + */ + bulkCreate: external_exports.boolean().default(false).describe("Supports bulk CREATE operations"), + /** + * Whether the driver supports bulk update operations. + */ + bulkUpdate: external_exports.boolean().default(false).describe("Supports bulk UPDATE operations"), + /** + * Whether the driver supports bulk delete operations. + */ + bulkDelete: external_exports.boolean().default(false).describe("Supports bulk DELETE operations"), + // ============================================================================ + // Transaction & Connection Management + // ============================================================================ + /** + * Whether the driver supports database transactions. + * If true, beginTransaction, commit, and rollback must be implemented. + */ + transactions: external_exports.boolean().default(false).describe("Supports ACID transactions"), + /** + * Whether the driver supports savepoints within transactions. + */ + savepoints: external_exports.boolean().default(false).describe("Supports transaction savepoints"), + /** + * Supported transaction isolation levels. + */ + isolationLevels: external_exports.array(IsolationLevelEnum3).optional().describe("Supported isolation levels"), + // ============================================================================ + // Query Operations + // ============================================================================ + /** + * Whether the driver supports WHERE clause filters. + * If false, ObjectQL will fetch all records and filter in memory. + * + * Example: Memory driver might not support complex filter conditions. + */ + queryFilters: external_exports.boolean().default(true).describe("Supports WHERE clause filtering"), + /** + * Whether the driver supports aggregation functions (COUNT, SUM, AVG, etc.). + * If false, ObjectQL will compute aggregations in memory. + */ + queryAggregations: external_exports.boolean().default(false).describe("Supports GROUP BY and aggregation functions"), + /** + * Whether the driver supports ORDER BY sorting. + * If false, ObjectQL will sort results in memory. + */ + querySorting: external_exports.boolean().default(true).describe("Supports ORDER BY sorting"), + /** + * Whether the driver supports LIMIT/OFFSET pagination. + * If false, ObjectQL will fetch all records and paginate in memory. + */ + queryPagination: external_exports.boolean().default(true).describe("Supports LIMIT/OFFSET pagination"), + /** + * Whether the driver supports window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.). + * If false, ObjectQL will compute window functions in memory. + */ + queryWindowFunctions: external_exports.boolean().default(false).describe("Supports window functions with OVER clause"), + /** + * Whether the driver supports subqueries (nested SELECT statements). + * If false, ObjectQL will execute queries separately and combine results. + */ + querySubqueries: external_exports.boolean().default(false).describe("Supports subqueries"), + /** + * Whether the driver supports Common Table Expressions (WITH clause). + */ + queryCTE: external_exports.boolean().default(false).describe("Supports Common Table Expressions (WITH clause)"), + /** + * Whether the driver supports SQL-style joins. + * If false, ObjectQL will fetch related data separately and join in memory. + */ + joins: external_exports.boolean().default(false).describe("Supports SQL joins"), + // ============================================================================ + // Advanced Features + // ============================================================================ + /** + * Whether the driver supports full-text search. + * If true, text search queries can be pushed to the database. + */ + fullTextSearch: external_exports.boolean().default(false).describe("Supports full-text search"), + /** + * Whether the driver supports JSON querying capabilities. + */ + jsonQuery: external_exports.boolean().default(false).describe("Supports JSON field querying"), + /** + * Whether the driver supports geospatial queries. + */ + geospatialQuery: external_exports.boolean().default(false).describe("Supports geospatial queries"), + /** + * Whether the driver supports streaming large result sets. + */ + streaming: external_exports.boolean().default(false).describe("Supports result streaming (cursors/iterators)"), + /** + * Whether the driver supports JSON field types. + * If false, JSON data will be serialized as strings. + */ + jsonFields: external_exports.boolean().default(false).describe("Supports JSON field types"), + /** + * Whether the driver supports array field types. + * If false, arrays will be stored as JSON strings or in separate tables. + */ + arrayFields: external_exports.boolean().default(false).describe("Supports array field types"), + /** + * Whether the driver supports vector embeddings and similarity search. + * Required for RAG (Retrieval-Augmented Generation) and AI features. + */ + vectorSearch: external_exports.boolean().default(false).describe("Supports vector embeddings and similarity search"), + // ============================================================================ + // Schema Management + // ============================================================================ + /** + * Whether the driver supports automatic schema synchronization. + */ + schemaSync: external_exports.boolean().default(false).describe("Supports automatic schema synchronization"), + /** + * Whether the driver supports batching multiple schema sync operations + * into a single (or fewer) round-trips for the DDL phase. When true, + * the engine may call `syncSchemasBatch()` instead of calling + * `syncSchema()` per object, reducing network round-trips for remote drivers. + */ + batchSchemaSync: external_exports.boolean().default(false).describe("Supports batched schema sync to reduce schema DDL round-trips"), + /** + * Whether the driver supports database migrations. + */ + migrations: external_exports.boolean().default(false).describe("Supports database migrations"), + /** + * Whether the driver supports index management. + */ + indexes: external_exports.boolean().default(false).describe("Supports index creation and management"), + // ============================================================================ + // Performance & Optimization + // ============================================================================ + /** + * Whether the driver supports connection pooling. + */ + connectionPooling: external_exports.boolean().default(false).describe("Supports connection pooling"), + /** + * Whether the driver supports prepared statements. + */ + preparedStatements: external_exports.boolean().default(false).describe("Supports prepared statements (SQL injection prevention)"), + /** + * Whether the driver supports query result caching. + */ + queryCache: external_exports.boolean().default(false).describe("Supports query result caching") +}); +var DriverInterfaceSchema2 = external_exports.object({ + /** + * Driver name (e.g., 'postgresql', 'mongodb', 'rest_api'). + */ + name: external_exports.string().describe("Driver unique name"), + /** + * Driver version. + */ + version: external_exports.string().describe("Driver version"), + /** + * Capabilities descriptor. + */ + supports: DriverCapabilitiesSchema2, + // ============================================================================ + // Lifecycle Management + // ============================================================================ + /** + * Initialize connection pool or authenticate. + */ + connect: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.void())).describe("Establish connection"), + /** + * Close connections and cleanup resources. + */ + disconnect: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.void())).describe("Close connection"), + /** + * Check connection health. + * @returns true if healthy, false otherwise. + */ + checkHealth: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.boolean())).describe("Health check"), + /** + * Get Connection Pool Statistics. + * Useful for monitoring database load. + */ + getPoolStats: external_exports.function().input(external_exports.tuple([])).output(external_exports.object({ + total: external_exports.number(), + idle: external_exports.number(), + active: external_exports.number(), + waiting: external_exports.number() + }).optional()).optional().describe("Get connection pool statistics"), + // ============================================================================ + // Raw Execution (Escape Hatch) + // ============================================================================ + /** + * Execute a raw command/query native to the driver. + * Useful for complex reports, stored procedures, or DDL not covered by standard sync. + * + * @param command - The raw command (e.g., SQL string, shell command, or remote API payload). + * @param parameters - Optional array of bound parameters for safe execution (prevention of injection). + * @param options - Driver options (transaction context, timeout). + * @returns Promise resolving to the raw result from the driver. + * + * @example + * // SQL Driver + * await driver.execute('SELECT * FROM complex_view WHERE id = ?', [123]); + * + * // Mongo Driver + * await driver.execute({ aggregate: 'orders', pipeline: [...] }); + */ + execute: external_exports.function().input(external_exports.tuple([external_exports.unknown(), external_exports.array(external_exports.unknown()).optional(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())).describe("Execute raw command"), + // ============================================================================ + // CRUD Operations + // ============================================================================ + /** + * Find multiple records matching the structured query. + * Parsing the QueryAST is the responsibility of the driver implementation. + * + * @param object - The name of the object/table to query (e.g. 'account'). + * @param query - The structured QueryAST (filters, sorts, joins, pagination). + * @param options - Driver options. + * @returns Array of records. + * + * @example + * await driver.find('account', { + * filters: [['status', '=', 'active'], 'and', ['amount', '>', 500]], + * sort: [{ field: 'created_at', order: 'desc' }], + * top: 10 + * }); + * @returns Array of records. + * MUST return `id` as string. MUST NOT return implementation details like `_id`. + */ + find: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))).describe("Find records"), + /** + * Stream records matching the structured query. + * Optimized for large datasets to avoid memory overflow. + * + * @param object - The name of the object. + * @param query - The structured QueryAST. + * @param options - Driver options. + * @returns AsyncIterable/ReadableStream of records. + */ + findStream: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.unknown()).describe("Stream records (AsyncIterable)"), + /** + * Find a single record by query. + * Similar to find(), but returns only the first match or null. + * + * @param object - The name of the object. + * @param query - QueryAST. + * @param options - Driver options. + * @returns The record or null. + * MUST return `id` as string. MUST NOT return implementation details like `_id`. + */ + findOne: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()).nullable())).describe("Find one record"), + /** + * Create a new record. + * + * @param object - The object name. + * @param data - Key-value map of field data. + * @param options - Driver options. + * @returns The created record, including server-generated fields (id, created_at, etc.). + * MUST return `id` as string. MUST NOT return implementation details like `_id`. + */ + create: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Create record"), + /** + * Update an existing record by ID. + * + * @param object - The object name. + * @param id - The unique identifier of the record. + * @param data - The fields to update. + * @param options - Driver options. + * @returns The updated record. + * MUST return `id` as string. MUST NOT return implementation details like `_id`. + */ + update: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.string().or(external_exports.number()), external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Update record"), + /** + * Upsert (Update or Insert) a record. + * + * @param object - The object name. + * @param data - The data to upsert. + * @param conflictKeys - Fields to check for conflict (uniqueness). + * @param options - Driver options. + * @returns The created or updated record. + */ + upsert: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.string()).optional(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Upsert record"), + /** + * Delete a record by ID. + * + * @param object - The object name. + * @param id - The unique identifier of the record. + * @param options - Driver options. + * @returns True if deleted, false if not found. + */ + delete: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.string().or(external_exports.number()), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.boolean())).describe("Delete record"), + /** + * Count records matching a query. + * + * @param object - The object name. + * @param query - Optional filtering criteria. + * @param options - Driver options. + * @returns Total count. + */ + count: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3.optional(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.number())).describe("Count records"), + // ============================================================================ + // Bulk Operations + // ============================================================================ + /** + * Create multiple records in a single batch. + * Optimized for performance. + * + * @param object - The object name. + * @param dataArray - Array of record data. + * @returns Array of created records. + */ + bulkCreate: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))), + /** + * Update multiple records in a single batch. + * + * @param object - The object name. + * @param updates - Array of objects containing {id, data}. + * @returns Array of updated records. + */ + bulkUpdate: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.object({ id: external_exports.string().or(external_exports.number()), data: external_exports.record(external_exports.string(), external_exports.unknown()) })), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))), + /** + * Delete multiple records in a single batch. + * + * @param object - The object name. + * @param ids - Array of record IDs. + */ + bulkDelete: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.string().or(external_exports.number())), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.void())), + /** + * Update multiple records matching a query. + * Direct database push-down. DOES NOT trigger per-record hooks. + * + * @param object - The object name. + * @param query - The filtering criteria. + * @param data - The data to update. + * @returns Count of modified records. + */ + updateMany: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.number())).optional(), + /** + * Delete multiple records matching a query. + * Direct database push-down. DOES NOT trigger per-record hooks. + * + * @param object - The object name. + * @param query - The filtering criteria. + * @returns Count of deleted records. + */ + deleteMany: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.number())).optional(), + // ============================================================================ + // Transaction Management + // ============================================================================ + /** + * Begin a new database transaction. + * @param options - Isolation level and other settings. + * @returns A transaction handle to be passed to subsequent operations via `options.transaction`. + */ + beginTransaction: external_exports.function().input(external_exports.tuple([external_exports.object({ + isolationLevel: IsolationLevelEnum3.optional() + }).optional()])).output(external_exports.promise(external_exports.unknown())).describe("Start transaction"), + /** + * Commit the transaction. + * @param transaction - The transaction handle. + */ + commit: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.promise(external_exports.void())).describe("Commit transaction"), + /** + * Rollback the transaction. + * @param transaction - The transaction handle. + */ + rollback: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.promise(external_exports.void())).describe("Rollback transaction"), + // ============================================================================ + // Schema Management + // ============================================================================ + /** + * Synchronize the database schema with the Object definition. + * This is an idempotent operation: it should create tables if missing, + * add columns if missing, and update indexes. + * + * @param object - The object name. + * @param schema - The full Object Schema (fields, indexes, etc). + * @param options - Driver options. + */ + syncSchema: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.unknown(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.void())).describe("Sync object schema to DB"), + /** + * Batch-synchronize multiple object schemas with fewer round-trips. + * + * Drivers that advertise `supports.batchSchemaSync = true` MUST implement + * this method. The engine will call it once with every + * `{ object, schema }` pair instead of calling `syncSchema()` N times. + * + * @param schemas - Array of `{ object: string; schema: unknown }` pairs. + * @param options - Driver options. + */ + syncSchemasBatch: external_exports.function().input(external_exports.tuple([ + external_exports.array(external_exports.object({ object: external_exports.string(), schema: external_exports.unknown() })), + DriverOptionsSchema2.optional() + ])).output(external_exports.promise(external_exports.void())).optional().describe("Batch sync multiple schemas in one round-trip"), + /** + * Drop the underlying table or collection for an object. + * WARNING: Destructive operation. + * + * @param object - The object name. + */ + dropTable: external_exports.function().input(external_exports.tuple([external_exports.string(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.void())), + /** + * Analyze query performance. + * Returns execution plan without executing the query (where possible). + * + * @param object - The object name. + * @param query - The query to explain. + * @returns The execution plan details. + */ + explain: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())).optional() +}); +var PoolConfigSchema2 = external_exports.object({ + min: external_exports.number().min(0).default(2).describe("Minimum number of connections in pool"), + max: external_exports.number().min(1).default(10).describe("Maximum number of connections in pool"), + idleTimeoutMillis: external_exports.number().min(0).default(3e4).describe("Time in ms before idle connection is closed"), + connectionTimeoutMillis: external_exports.number().min(0).default(5e3).describe("Time in ms to wait for available connection") +}); +var DriverConfigSchema2 = external_exports.object({ + name: external_exports.string().describe("Driver instance name"), + type: external_exports.enum(["sql", "nosql", "cache", "search", "graph", "timeseries"]).describe("Driver type category"), + capabilities: DriverCapabilitiesSchema2.describe("Driver capability flags"), + connectionString: external_exports.string().optional().describe("Database connection string (driver-specific format)"), + poolConfig: PoolConfigSchema2.optional().describe("Connection pool configuration") +}); +var SQLDialectSchema2 = external_exports.enum([ + "postgresql", + "mysql", + "sqlite", + "mssql", + "oracle", + "mariadb" +]); +var DataTypeMappingSchema2 = external_exports.object({ + text: external_exports.string().describe("SQL type for text fields (e.g., VARCHAR, TEXT)"), + number: external_exports.string().describe("SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)"), + boolean: external_exports.string().describe("SQL type for boolean fields (e.g., BOOLEAN, BIT)"), + date: external_exports.string().describe("SQL type for date fields (e.g., DATE)"), + datetime: external_exports.string().describe("SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)"), + json: external_exports.string().optional().describe("SQL type for JSON fields (e.g., JSON, JSONB)"), + uuid: external_exports.string().optional().describe("SQL type for UUID fields (e.g., UUID, CHAR(36))"), + binary: external_exports.string().optional().describe("SQL type for binary fields (e.g., BLOB, BYTEA)") +}); +var SSLConfigSchema2 = external_exports.object({ + rejectUnauthorized: external_exports.boolean().default(true).describe("Reject connections with invalid certificates"), + ca: external_exports.string().optional().describe("CA certificate file path or content"), + cert: external_exports.string().optional().describe("Client certificate file path or content"), + key: external_exports.string().optional().describe("Client private key file path or content") +}).refine((data) => { + const hasCert = data.cert !== void 0; + const hasKey = data.key !== void 0; + return hasCert === hasKey; +}, { + message: "Client certificate (cert) and private key (key) must be provided together" +}); +var SQLDriverConfigSchema2 = DriverConfigSchema2.extend({ + type: external_exports.literal("sql").describe('Driver type must be "sql"'), + dialect: SQLDialectSchema2.describe("SQL database dialect"), + dataTypeMapping: DataTypeMappingSchema2.describe("SQL data type mapping configuration"), + ssl: external_exports.boolean().default(false).describe("Enable SSL/TLS connection"), + sslConfig: SSLConfigSchema2.optional().describe("SSL/TLS configuration (required when ssl is true)") +}).refine((data) => { + if (data.ssl && !data.sslConfig) { + return false; + } + return true; +}, { + message: "sslConfig is required when ssl is true" +}); +var SQLiteDataTypeMappingDefaults2 = { + text: "TEXT", + number: "REAL", + boolean: "INTEGER", + date: "TEXT", + datetime: "TEXT", + json: "TEXT", + uuid: "TEXT", + binary: "BLOB" +}; +var SQLiteAlterTableLimitations2 = { + /** SQLite supports ADD COLUMN */ + supportsAddColumn: true, + /** SQLite supports RENAME COLUMN (3.25.0+) */ + supportsRenameColumn: true, + /** SQLite supports DROP COLUMN (3.35.0+) */ + supportsDropColumn: true, + /** SQLite does NOT support MODIFY/ALTER COLUMN type */ + supportsModifyColumn: false, + /** SQLite does NOT support adding constraints to existing columns */ + supportsAddConstraint: false, + /** + * When an unsupported alteration is needed, the migration planner + * must use the 12-step table rebuild strategy: + * 1. CREATE new table with desired schema + * 2. Copy data from old table + * 3. DROP old table + * 4. RENAME new table to old name + */ + rebuildStrategy: "create_copy_drop_rename" +}; +var NoSQLDatabaseTypeSchema2 = external_exports.enum([ + "mongodb", + "couchdb", + "dynamodb", + "cassandra", + "redis", + "elasticsearch", + "neo4j", + "orientdb" +]); +var NoSQLOperationTypeSchema2 = external_exports.enum([ + "find", + // Query documents/records + "findOne", + // Get single document + "insert", + // Insert document + "update", + // Update document + "delete", + // Delete document + "aggregate", + // Aggregation pipeline + "mapReduce", + // MapReduce operation + "count", + // Count documents + "distinct", + // Get distinct values + "createIndex", + // Create index + "dropIndex" + // Drop index +]); +var ConsistencyLevelSchema2 = external_exports.enum([ + "all", + "quorum", + "one", + "local_quorum", + "each_quorum", + "eventual" +]); +var NoSQLIndexTypeSchema2 = external_exports.enum([ + "single", + // Single field index + "compound", + // Multiple fields index + "unique", + // Unique constraint + "text", + // Full-text search index + "geospatial", + // Geospatial index (2d, 2dsphere) + "hashed", + // Hashed index for sharding + "ttl", + // Time-to-live index (auto-deletion) + "sparse" + // Sparse index (only indexed documents with field) +]); +var ShardingConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable sharding"), + shardKey: external_exports.string().optional().describe("Field to use as shard key"), + shardingStrategy: external_exports.enum(["hash", "range", "zone"]).optional().describe("Sharding strategy"), + numShards: external_exports.number().int().positive().optional().describe("Number of shards") +}); +var ReplicationConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable replication"), + replicaSetName: external_exports.string().optional().describe("Replica set name"), + replicas: external_exports.number().int().positive().optional().describe("Number of replicas"), + readPreference: external_exports.enum(["primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"]).optional().describe("Read preference for replica set"), + writeConcern: external_exports.enum(["majority", "acknowledged", "unacknowledged"]).optional().describe("Write concern level") +}); +var DocumentSchemaValidationSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable schema validation"), + validationLevel: external_exports.enum(["strict", "moderate", "off"]).optional().describe("Validation strictness"), + validationAction: external_exports.enum(["error", "warn"]).optional().describe("Action on validation failure"), + jsonSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON Schema for validation") +}); +var NoSQLDataTypeMappingSchema2 = external_exports.object({ + text: external_exports.string().describe("NoSQL type for text fields"), + number: external_exports.string().describe("NoSQL type for number fields"), + boolean: external_exports.string().describe("NoSQL type for boolean fields"), + date: external_exports.string().describe("NoSQL type for date fields"), + datetime: external_exports.string().describe("NoSQL type for datetime fields"), + json: external_exports.string().optional().describe("NoSQL type for JSON/object fields"), + uuid: external_exports.string().optional().describe("NoSQL type for UUID fields"), + binary: external_exports.string().optional().describe("NoSQL type for binary fields"), + array: external_exports.string().optional().describe("NoSQL type for array fields"), + objectId: external_exports.string().optional().describe("NoSQL type for ObjectID fields (MongoDB)"), + geopoint: external_exports.string().optional().describe("NoSQL type for geospatial point fields") +}); +var NoSQLDriverConfigSchema2 = DriverConfigSchema2.extend({ + type: external_exports.literal("nosql").describe('Driver type must be "nosql"'), + databaseType: NoSQLDatabaseTypeSchema2.describe("Specific NoSQL database type"), + dataTypeMapping: NoSQLDataTypeMappingSchema2.describe("NoSQL data type mapping configuration"), + /** + * Consistency level for reads/writes + */ + consistency: ConsistencyLevelSchema2.optional().describe("Consistency level for operations"), + /** + * Replication configuration + */ + replication: ReplicationConfigSchema2.optional().describe("Replication configuration"), + /** + * Sharding configuration + */ + sharding: ShardingConfigSchema2.optional().describe("Sharding configuration"), + /** + * Schema validation rules (for document databases) + */ + schemaValidation: DocumentSchemaValidationSchema2.optional().describe("Document schema validation"), + /** + * AWS Region (for DynamoDB, DocumentDB, etc.) + */ + region: external_exports.string().optional().describe("AWS region (for managed NoSQL services)"), + /** + * AWS Access Key ID (for DynamoDB, DocumentDB, etc.) + */ + accessKeyId: external_exports.string().optional().describe("AWS access key ID"), + /** + * AWS Secret Access Key (for DynamoDB, DocumentDB, etc.) + */ + secretAccessKey: external_exports.string().optional().describe("AWS secret access key"), + /** + * Time-to-live (TTL) field name + * Automatically delete documents after a specified time + */ + ttlField: external_exports.string().optional().describe("Field name for TTL (auto-deletion)"), + /** + * Maximum document size in bytes + */ + maxDocumentSize: external_exports.number().int().positive().optional().describe("Maximum document size in bytes"), + /** + * Collection/Table name prefix + * Useful for multi-tenancy or environment isolation + */ + collectionPrefix: external_exports.string().optional().describe("Prefix for collection/table names") +}); +var NoSQLQueryOptionsSchema2 = external_exports.object({ + /** + * Consistency level for this query + */ + consistency: ConsistencyLevelSchema2.optional().describe("Consistency level override"), + /** + * Read from secondary replicas + */ + readFromSecondary: external_exports.boolean().optional().describe("Allow reading from secondary replicas"), + /** + * Projection (fields to include/exclude) + */ + projection: external_exports.record(external_exports.string(), external_exports.union([external_exports.literal(0), external_exports.literal(1)])).optional().describe("Field projection"), + /** + * Query timeout in milliseconds + */ + timeout: external_exports.number().int().positive().optional().describe("Query timeout (ms)"), + /** + * Use cursor for large result sets + */ + useCursor: external_exports.boolean().optional().describe("Use cursor instead of loading all results"), + /** + * Batch size for cursor iteration + */ + batchSize: external_exports.number().int().positive().optional().describe("Cursor batch size"), + /** + * Enable query profiling + */ + profile: external_exports.boolean().optional().describe("Enable query profiling"), + /** + * Use hinted index + */ + hint: external_exports.string().optional().describe("Index hint for query optimization") +}); +var AggregationStageSchema2 = external_exports.object({ + /** + * Stage operator (e.g., $match, $group, $sort, $project) + */ + operator: external_exports.string().describe("Aggregation operator (e.g., $match, $group, $sort)"), + /** + * Stage parameters/options + */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Stage-specific options") +}); +var AggregationPipelineSchema2 = external_exports.object({ + /** + * Collection/Table to aggregate + */ + collection: external_exports.string().describe("Collection/table name"), + /** + * Pipeline stages + */ + stages: external_exports.array(AggregationStageSchema2).describe("Aggregation pipeline stages"), + /** + * Additional options + */ + options: NoSQLQueryOptionsSchema2.optional().describe("Query options") +}); +var NoSQLIndexSchema2 = external_exports.object({ + /** + * Index name + */ + name: external_exports.string().describe("Index name"), + /** + * Index type + */ + type: NoSQLIndexTypeSchema2.describe("Index type"), + /** + * Fields to index + * For compound indexes, order matters + */ + fields: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name"), + order: external_exports.enum(["asc", "desc", "text", "2dsphere"]).optional().describe("Index order or type") + })).describe("Fields to index"), + /** + * Unique constraint + */ + unique: external_exports.boolean().default(false).describe("Enforce uniqueness"), + /** + * Sparse index (only index documents with the field) + */ + sparse: external_exports.boolean().default(false).describe("Sparse index"), + /** + * TTL in seconds (for TTL indexes) + */ + expireAfterSeconds: external_exports.number().int().positive().optional().describe("TTL in seconds"), + /** + * Partial index filter + */ + partialFilterExpression: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Partial index filter"), + /** + * Background index creation + */ + background: external_exports.boolean().default(false).describe("Create index in background") +}); +var NoSQLTransactionOptionsSchema2 = external_exports.object({ + /** + * Read concern level + */ + readConcern: external_exports.enum(["local", "majority", "linearizable", "snapshot"]).optional().describe("Read concern level"), + /** + * Write concern level + */ + writeConcern: external_exports.enum(["majority", "acknowledged", "unacknowledged"]).optional().describe("Write concern level"), + /** + * Read preference + */ + readPreference: external_exports.enum(["primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"]).optional().describe("Read preference"), + /** + * Transaction timeout in milliseconds + */ + maxCommitTimeMS: external_exports.number().int().positive().optional().describe("Transaction commit timeout (ms)") +}); +var DatasetMode4 = external_exports.enum([ + "insert", + // Try to insert, fail on duplicate + "update", + // Only update found records, ignore new + "upsert", + // Create new or Update existing (Standard) + "replace", + // Delete ALL records in object then insert (Dangerous - use for cache tables) + "ignore" + // Try to insert, silently skip duplicates +]); +var DatasetSchema4 = external_exports.object({ + /** + * Target Object + * The machine name of the object to populate. + */ + object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target Object Name"), + /** + * Idempotency Key (The "Upsert" Key) + * The field used to check if a record already exists. + * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'. + * Standard: 'id' is rarely used for portable seed data — prefer natural keys. + */ + externalId: external_exports.string().default("name").describe("Field match for uniqueness check"), + /** + * Import Strategy + */ + mode: DatasetMode4.default("upsert").describe("Conflict resolution strategy"), + /** + * Environment Scope + * - 'all': Always load + * - 'dev': Only for development/demo + * - 'test': Only for CI/CD tests + */ + env: external_exports.array(external_exports.enum(["prod", "dev", "test"])).default(["prod", "dev", "test"]).describe("Applicable environments"), + /** + * The Payload + * Array of raw JSON objects matching the Object Schema. + */ + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Data records") +}); +var ReferenceResolutionSchema2 = external_exports.object({ + /** The field name on the source object (e.g., 'account_id') */ + field: external_exports.string().describe("Source field name containing the reference value"), + /** The target object being referenced (e.g., 'account') */ + targetObject: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target object name (snake_case)"), + /** + * The field on the target object used to match the reference value. + * Defaults to the target object's externalId (usually 'name'). + */ + targetField: external_exports.string().default("name").describe("Field on target object used for matching"), + /** The field type that triggered this resolution (lookup or master_detail) */ + fieldType: external_exports.enum(["lookup", "master_detail"]).describe("Relationship field type") +}).describe("Describes how a field reference is resolved during seed loading"); +var ObjectDependencyNodeSchema2 = external_exports.object({ + /** Object machine name */ + object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Object name (snake_case)"), + /** + * Objects that this object depends on (via lookup/master_detail fields). + * These must be loaded before this object. + */ + dependsOn: external_exports.array(external_exports.string()).describe("Objects this object depends on"), + /** + * Field-level reference details for each dependency. + * Maps field name → reference resolution info. + */ + references: external_exports.array(ReferenceResolutionSchema2).describe("Field-level reference details") +}).describe("Object node in the seed data dependency graph"); +var ObjectDependencyGraphSchema2 = external_exports.object({ + /** All object nodes in the graph */ + nodes: external_exports.array(ObjectDependencyNodeSchema2).describe("All objects in the dependency graph"), + /** + * Topologically sorted object names for insertion order. + * Parent objects appear before child objects. + */ + insertOrder: external_exports.array(external_exports.string()).describe("Topologically sorted insert order"), + /** + * Circular dependency chains detected in the graph. + * Each chain is an array of object names forming a cycle. + * When present, the loader must use a multi-pass strategy. + * + * @example [['project', 'task', 'project']] + */ + circularDependencies: external_exports.array(external_exports.array(external_exports.string())).default([]).describe('Circular dependency chains (e.g., [["a", "b", "a"]])') +}).describe("Complete object dependency graph for seed data loading"); +var ReferenceResolutionErrorSchema2 = external_exports.object({ + /** The source object containing the broken reference */ + sourceObject: external_exports.string().describe("Object with the broken reference"), + /** The field containing the unresolved value */ + field: external_exports.string().describe("Field name with unresolved reference"), + /** The target object that was searched */ + targetObject: external_exports.string().describe("Target object searched for the reference"), + /** The externalId field used for matching on the target object */ + targetField: external_exports.string().describe("ExternalId field used for matching"), + /** The value that could not be resolved */ + attemptedValue: external_exports.unknown().describe("Value that failed to resolve"), + /** The index of the record in the dataset's records array */ + recordIndex: external_exports.number().int().min(0).describe("Index of the record in the dataset"), + /** Human-readable error message */ + message: external_exports.string().describe("Human-readable error description") +}).describe("Actionable error for a failed reference resolution"); +var SeedLoaderConfigSchema2 = external_exports.object({ + /** + * Dry-run mode: validate all references without writing data. + * Surfaces broken references before any mutations occur. + * @default false + */ + dryRun: external_exports.boolean().default(false).describe("Validate references without writing data"), + /** + * Whether to halt on the first reference resolution error. + * When false, collects all errors and continues loading. + * @default false + */ + haltOnError: external_exports.boolean().default(false).describe("Stop on first reference resolution error"), + /** + * Enable multi-pass loading for circular dependencies. + * Pass 1: Insert records with null for circular references. + * Pass 2: Update records to fill deferred references. + * @default true + */ + multiPass: external_exports.boolean().default(true).describe("Enable multi-pass loading for circular dependencies"), + /** + * Default dataset mode when not specified per-dataset. + * @default 'upsert' + */ + defaultMode: DatasetMode4.default("upsert").describe("Default conflict resolution strategy"), + /** + * Maximum number of records to process in a single batch. + * Controls memory usage for large datasets. + * @default 1000 + */ + batchSize: external_exports.number().int().min(1).default(1e3).describe("Maximum records per batch insert/upsert"), + /** + * Whether to wrap the entire load operation in a transaction. + * When true, all-or-nothing semantics apply. + * @default false + */ + transaction: external_exports.boolean().default(false).describe("Wrap entire load in a transaction (all-or-nothing)"), + /** + * Environment filter. Only datasets matching this environment are loaded. + * When not specified, all datasets are loaded regardless of env scope. + */ + env: external_exports.enum(["prod", "dev", "test"]).optional().describe("Only load datasets matching this environment") +}).describe("Seed data loader configuration"); +var DatasetLoadResultSchema2 = external_exports.object({ + /** Target object name */ + object: external_exports.string().describe("Object that was loaded"), + /** Import mode used */ + mode: DatasetMode4.describe("Import mode used"), + /** Number of records successfully inserted */ + inserted: external_exports.number().int().min(0).describe("Records inserted"), + /** Number of records successfully updated (upsert matched existing) */ + updated: external_exports.number().int().min(0).describe("Records updated"), + /** Number of records skipped (mode: ignore, or already exists) */ + skipped: external_exports.number().int().min(0).describe("Records skipped"), + /** Number of records with errors */ + errored: external_exports.number().int().min(0).describe("Records with errors"), + /** Total records in the dataset */ + total: external_exports.number().int().min(0).describe("Total records in dataset"), + /** Number of references resolved via externalId */ + referencesResolved: external_exports.number().int().min(0).describe("References resolved via externalId"), + /** Number of references deferred to pass 2 (circular dependencies) */ + referencesDeferred: external_exports.number().int().min(0).describe("References deferred to second pass"), + /** Reference resolution errors for this object */ + errors: external_exports.array(ReferenceResolutionErrorSchema2).default([]).describe("Reference resolution errors") +}).describe("Result of loading a single dataset"); +var SeedLoaderResultSchema2 = external_exports.object({ + /** Whether the overall load operation succeeded */ + success: external_exports.boolean().describe("Overall success status"), + /** Was this a dry-run (validation only, no writes)? */ + dryRun: external_exports.boolean().describe("Whether this was a dry-run"), + /** The dependency graph used for ordering */ + dependencyGraph: ObjectDependencyGraphSchema2.describe("Object dependency graph"), + /** Per-object load results, in the order they were processed */ + results: external_exports.array(DatasetLoadResultSchema2).describe("Per-object load results"), + /** All reference resolution errors across all objects */ + errors: external_exports.array(ReferenceResolutionErrorSchema2).describe("All reference resolution errors"), + /** Summary statistics */ + summary: external_exports.object({ + /** Total objects processed */ + objectsProcessed: external_exports.number().int().min(0).describe("Total objects processed"), + /** Total records across all objects */ + totalRecords: external_exports.number().int().min(0).describe("Total records across all objects"), + /** Total records inserted */ + totalInserted: external_exports.number().int().min(0).describe("Total records inserted"), + /** Total records updated */ + totalUpdated: external_exports.number().int().min(0).describe("Total records updated"), + /** Total records skipped */ + totalSkipped: external_exports.number().int().min(0).describe("Total records skipped"), + /** Total records with errors */ + totalErrored: external_exports.number().int().min(0).describe("Total records with errors"), + /** Total references resolved via externalId */ + totalReferencesResolved: external_exports.number().int().min(0).describe("Total references resolved"), + /** Total references deferred to second pass */ + totalReferencesDeferred: external_exports.number().int().min(0).describe("Total references deferred"), + /** Number of circular dependency chains detected */ + circularDependencyCount: external_exports.number().int().min(0).describe("Circular dependency chains detected"), + /** Duration of the load operation in milliseconds */ + durationMs: external_exports.number().min(0).describe("Load duration in milliseconds") + }).describe("Summary statistics") +}).describe("Complete seed loader result"); +var SeedLoaderRequestSchema2 = external_exports.object({ + /** Datasets to load */ + datasets: external_exports.array(DatasetSchema4).min(1).describe("Datasets to load"), + /** Loader configuration */ + config: external_exports.preprocess((val) => val ?? {}, SeedLoaderConfigSchema2).describe("Loader configuration") +}).describe("Seed loader request with datasets and configuration"); +var DocumentVersionSchema2 = external_exports.object({ + /** + * Sequential version number (increments with each new version) + */ + versionNumber: external_exports.number().describe("Version number"), + /** + * Timestamp when this version was created (Unix milliseconds) + */ + createdAt: external_exports.number().describe("Creation timestamp"), + /** + * User ID who created this version + */ + createdBy: external_exports.string().describe("Creator user ID"), + /** + * File size in bytes + */ + size: external_exports.number().describe("File size in bytes"), + /** + * Checksum/hash of the file content (for integrity verification) + */ + checksum: external_exports.string().describe("File checksum"), + /** + * URL to download this specific version + */ + downloadUrl: external_exports.string().url().describe("Download URL"), + /** + * Whether this is the latest version + * @default false + */ + isLatest: external_exports.boolean().optional().default(false).describe("Is latest version") +}); +var DocumentTemplateSchema2 = external_exports.object({ + /** + * Unique identifier for the template + */ + id: external_exports.string().describe("Template ID"), + /** + * Human-readable name of the template + */ + name: external_exports.string().describe("Template name"), + /** + * Optional description of the template's purpose + */ + description: external_exports.string().optional().describe("Template description"), + /** + * URL to the template file + */ + fileUrl: external_exports.string().url().describe("Template file URL"), + /** + * MIME type of the template file + */ + fileType: external_exports.string().describe("File MIME type"), + /** + * List of dynamic placeholders in the template + */ + placeholders: external_exports.array(external_exports.object({ + /** + * Placeholder identifier (used in template) + */ + key: external_exports.string().describe("Placeholder key"), + /** + * Human-readable label for the placeholder + */ + label: external_exports.string().describe("Placeholder label"), + /** + * Data type of the placeholder value + */ + type: external_exports.enum(["text", "number", "date", "image"]).describe("Placeholder type"), + /** + * Whether this placeholder must be filled + * @default false + */ + required: external_exports.boolean().optional().default(false).describe("Is required") + })).describe("Template placeholders") +}); +var ESignatureConfigSchema2 = external_exports.object({ + /** + * E-signature service provider + */ + provider: external_exports.enum(["docusign", "adobe-sign", "hellosign", "custom"]).describe("E-signature provider"), + /** + * Whether e-signature is enabled for this document + * @default false + */ + enabled: external_exports.boolean().optional().default(false).describe("E-signature enabled"), + /** + * List of signers in signing order + */ + signers: external_exports.array(external_exports.object({ + /** + * Signer's email address + */ + email: external_exports.string().email().describe("Signer email"), + /** + * Signer's full name + */ + name: external_exports.string().describe("Signer name"), + /** + * Signer's role in the document + */ + role: external_exports.string().describe("Signer role"), + /** + * Signing order (lower numbers sign first) + */ + order: external_exports.number().describe("Signing order") + })).describe("Document signers"), + /** + * Days until signature request expires + * @default 30 + */ + expirationDays: external_exports.number().optional().default(30).describe("Expiration days"), + /** + * Days between reminder emails + * @default 7 + */ + reminderDays: external_exports.number().optional().default(7).describe("Reminder interval days") +}); +var DocumentSchema2 = external_exports.object({ + /** + * Unique document identifier + */ + id: external_exports.string().describe("Document ID"), + /** + * Document name + */ + name: external_exports.string().describe("Document name"), + /** + * Optional document description + */ + description: external_exports.string().optional().describe("Document description"), + /** + * MIME type of the document + */ + fileType: external_exports.string().describe("File MIME type"), + /** + * File size in bytes + */ + fileSize: external_exports.number().describe("File size in bytes"), + /** + * Document category for organization + */ + category: external_exports.string().optional().describe("Document category"), + /** + * Tags for searchability and organization + */ + tags: external_exports.array(external_exports.string()).optional().describe("Document tags"), + /** + * Version control configuration + */ + versioning: external_exports.object({ + /** + * Whether versioning is enabled + */ + enabled: external_exports.boolean().describe("Versioning enabled"), + /** + * List of all document versions + */ + versions: external_exports.array(DocumentVersionSchema2).describe("Version history"), + /** + * Current major version number + */ + majorVersion: external_exports.number().describe("Major version"), + /** + * Current minor version number + */ + minorVersion: external_exports.number().describe("Minor version") + }).optional().describe("Version control"), + /** + * Template configuration (if document is generated from template) + */ + template: DocumentTemplateSchema2.optional().describe("Document template"), + /** + * E-signature configuration + */ + eSignature: ESignatureConfigSchema2.optional().describe("E-signature config"), + /** + * Access control settings + */ + access: external_exports.object({ + /** + * Whether document is publicly accessible + * @default false + */ + isPublic: external_exports.boolean().optional().default(false).describe("Public access"), + /** + * List of user/team IDs with access + */ + sharedWith: external_exports.array(external_exports.string()).optional().describe("Shared with"), + /** + * Timestamp when access expires (Unix milliseconds) + */ + expiresAt: external_exports.number().optional().describe("Access expiration") + }).optional().describe("Access control"), + /** + * Custom metadata fields + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") +}); +var ExternalDataSourceSchema2 = external_exports.object({ + /** + * Unique identifier for the external data source + */ + id: external_exports.string().describe("Data source ID"), + /** + * Human-readable name of the data source + */ + name: external_exports.string().describe("Data source name"), + /** + * Protocol type for connecting to the data source + */ + type: external_exports.enum(["odata", "rest-api", "graphql", "custom"]).describe("Protocol type"), + /** + * Base URL endpoint for the external system + */ + endpoint: external_exports.string().url().describe("API endpoint URL"), + /** + * Authentication configuration + */ + authentication: external_exports.object({ + /** + * Authentication method + */ + type: external_exports.enum(["oauth2", "api-key", "basic", "none"]).describe("Auth type"), + /** + * Authentication-specific configuration + * Structure varies based on auth type + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Auth configuration") + }).describe("Authentication") +}); +var ExternalFieldMappingSchema2 = FieldMappingSchema4.extend({ + /** + * Field data type + */ + type: external_exports.string().optional().describe("Field type"), + /** + * Whether the field is read-only + * @default true + */ + readonly: external_exports.boolean().optional().default(true).describe("Read-only field") +}); +var ExternalLookupSchema2 = external_exports.object({ + /** + * Name of the field that uses external lookup + */ + fieldName: external_exports.string().describe("Field name"), + /** + * External data source configuration + */ + dataSource: ExternalDataSourceSchema2.describe("External data source"), + /** + * Query configuration for fetching external data + */ + query: external_exports.object({ + /** + * API endpoint path (relative to base endpoint) + */ + endpoint: external_exports.string().describe("Query endpoint path"), + /** + * HTTP method for the query + * @default 'GET' + */ + method: external_exports.enum(["GET", "POST"]).optional().default("GET").describe("HTTP method"), + /** + * Query parameters or request body + */ + parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters") + }).describe("Query configuration"), + /** + * Mapping between external and local fields + */ + fieldMappings: external_exports.array(ExternalFieldMappingSchema2).describe("Field mappings"), + /** + * Cache configuration for external data + */ + caching: external_exports.object({ + /** + * Whether caching is enabled + * @default true + */ + enabled: external_exports.boolean().optional().default(true).describe("Cache enabled"), + /** + * Time-to-live in seconds + * @default 300 + */ + ttl: external_exports.number().optional().default(300).describe("Cache TTL (seconds)"), + /** + * Cache eviction strategy + * @default 'ttl' + */ + strategy: external_exports.enum(["lru", "lfu", "ttl"]).optional().default("ttl").describe("Cache strategy") + }).optional().describe("Caching configuration"), + /** + * Fallback behavior when external system is unavailable + */ + fallback: external_exports.object({ + /** + * Whether fallback is enabled + * @default true + */ + enabled: external_exports.boolean().optional().default(true).describe("Fallback enabled"), + /** + * Default value to use when external system fails + */ + defaultValue: external_exports.unknown().optional().describe("Default fallback value"), + /** + * Whether to show error message to user + * @default true + */ + showError: external_exports.boolean().optional().default(true).describe("Show error to user") + }).optional().describe("Fallback configuration"), + /** + * Rate limiting to prevent overwhelming external system + */ + rateLimit: external_exports.object({ + /** + * Maximum requests per second + */ + requestsPerSecond: external_exports.number().describe("Requests per second limit"), + /** + * Burst size for handling spikes + */ + burstSize: external_exports.number().optional().describe("Burst size") + }).optional().describe("Rate limiting"), + /** + * Retry configuration with exponential backoff + * + * @example + * ```json + * { + * "maxRetries": 3, + * "initialDelayMs": 1000, + * "maxDelayMs": 30000, + * "backoffMultiplier": 2, + * "retryableStatusCodes": [429, 500, 502, 503, 504] + * } + * ``` + */ + retry: external_exports.object({ + /** Maximum number of retry attempts */ + maxRetries: external_exports.number().min(0).default(3).describe("Maximum retry attempts"), + /** Initial delay before first retry (ms) */ + initialDelayMs: external_exports.number().default(1e3).describe("Initial retry delay in milliseconds"), + /** Maximum delay between retries (ms) */ + maxDelayMs: external_exports.number().default(3e4).describe("Maximum retry delay in milliseconds"), + /** Backoff multiplier for exponential backoff */ + backoffMultiplier: external_exports.number().default(2).describe("Exponential backoff multiplier"), + /** HTTP status codes that trigger a retry */ + retryableStatusCodes: external_exports.array(external_exports.number()).default([429, 500, 502, 503, 504]).describe("HTTP status codes that are retryable") + }).optional().describe("Retry configuration with exponential backoff"), + /** + * Request/response transformation pipeline + * + * Allows transforming request parameters and response data + * before they are processed by the external lookup system. + */ + transform: external_exports.object({ + /** Transform request parameters before sending */ + request: external_exports.object({ + /** Header transformations (key-value additions) */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Additional request headers"), + /** Query parameter transformations */ + queryParams: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Additional query parameters") + }).optional().describe("Request transformation"), + /** Transform response data after receiving */ + response: external_exports.object({ + /** JSONPath expression to extract data from response */ + dataPath: external_exports.string().optional().describe('JSONPath to extract data (e.g., "$.data.results")'), + /** JSONPath expression to extract total count for pagination */ + totalPath: external_exports.string().optional().describe('JSONPath to extract total count (e.g., "$.meta.total")') + }).optional().describe("Response transformation") + }).optional().describe("Request/response transformation pipeline"), + /** Pagination support for external data sources */ + pagination: external_exports.object({ + /** Pagination type */ + type: external_exports.enum(["offset", "cursor", "page"]).default("offset").describe("Pagination type"), + /** Page size */ + pageSize: external_exports.number().default(100).describe("Items per page"), + /** Maximum pages to fetch */ + maxPages: external_exports.number().optional().describe("Maximum number of pages to fetch") + }).optional().describe("Pagination configuration for external data") +}); +var DriverType2 = external_exports.string().describe("Underlying driver identifier"); +var DriverDefinitionSchema2 = external_exports.object({ + id: external_exports.string().describe('Unique driver identifier (e.g. "postgres")'), + label: external_exports.string().describe('Display label (e.g. "PostgreSQL")'), + description: external_exports.string().optional(), + icon: external_exports.string().optional(), + /** + * Configuration Schema (JSON Schema) + * Describes the structure of the `config` object needed for this driver. + * Used by the UI to generate the connection form. + */ + configSchema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema for connection configuration"), + /** + * Default Capabilities + * What this driver supports out-of-the-box. + */ + capabilities: external_exports.lazy(() => DatasourceCapabilities2).optional() +}); +var DatasourceCapabilities2 = external_exports.object({ + // ============================================================================ + // Transaction & Connection Management + // ============================================================================ + /** Can handle ACID transactions? */ + transactions: external_exports.boolean().default(false), + // ============================================================================ + // Query Operations + // ============================================================================ + /** Can execute WHERE clause filters natively? */ + queryFilters: external_exports.boolean().default(false), + /** Can perform aggregation (group by, sum, avg)? */ + queryAggregations: external_exports.boolean().default(false), + /** Can perform ORDER BY sorting? */ + querySorting: external_exports.boolean().default(false), + /** Can perform LIMIT/OFFSET pagination? */ + queryPagination: external_exports.boolean().default(false), + /** Can perform window functions? */ + queryWindowFunctions: external_exports.boolean().default(false), + /** Can perform subqueries? */ + querySubqueries: external_exports.boolean().default(false), + /** Can execute SQL-like joins natively? */ + joins: external_exports.boolean().default(false), + // ============================================================================ + // Advanced Features + // ============================================================================ + /** Can perform full-text search? */ + fullTextSearch: external_exports.boolean().default(false), + /** Is read-only? */ + readOnly: external_exports.boolean().default(false), + /** Is scheme-less (needs schema inference)? */ + dynamicSchema: external_exports.boolean().default(false) +}); +var DatasourceSchema2 = external_exports.object({ + /** Machine Name */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique datasource identifier"), + /** Human Label */ + label: external_exports.string().optional().describe("Display label"), + /** Driver */ + driver: DriverType2.describe("Underlying driver type"), + /** + * Connection Configuration + * Specific to the driver (e.g., host, port, user, password, bucket, etc.) + * Stored securely (passwords usually interpolated from ENV). + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Driver specific configuration"), + /** + * Connection Pool Configuration + * Standard connection pooling settings. + */ + pool: external_exports.object({ + min: external_exports.number().default(0).describe("Minimum connections"), + max: external_exports.number().default(10).describe("Maximum connections"), + idleTimeoutMillis: external_exports.number().default(3e4).describe("Idle timeout"), + connectionTimeoutMillis: external_exports.number().default(3e3).describe("Connection establishment timeout") + }).optional().describe("Connection pool settings"), + /** + * Read Replicas + * Optional list of duplicate configurations for read-only operations. + * Useful for scaling read throughput. + */ + readReplicas: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Read-only replica configurations"), + /** + * Capability Overrides + * Manually override what the driver claims to support. + */ + capabilities: DatasourceCapabilities2.optional().describe("Capability overrides"), + /** Health Check */ + healthCheck: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable health check endpoint"), + intervalMs: external_exports.number().default(3e4).describe("Health check interval in milliseconds"), + timeoutMs: external_exports.number().default(5e3).describe("Health check timeout in milliseconds") + }).optional().describe("Datasource health check configuration"), + /** SSL/TLS Configuration */ + ssl: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable SSL/TLS for database connection"), + rejectUnauthorized: external_exports.boolean().default(true).describe("Reject connections with invalid/self-signed certificates"), + ca: external_exports.string().optional().describe("CA certificate (PEM format or path to file)"), + cert: external_exports.string().optional().describe("Client certificate (PEM format or path to file)"), + key: external_exports.string().optional().describe("Client private key (PEM format or path to file)") + }).optional().describe("SSL/TLS configuration for secure database connections"), + /** Retry Policy */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().default(3).describe("Maximum number of retry attempts"), + baseDelayMs: external_exports.number().default(1e3).describe("Base delay between retries in milliseconds"), + maxDelayMs: external_exports.number().default(3e4).describe("Maximum delay between retries in milliseconds"), + backoffMultiplier: external_exports.number().default(2).describe("Exponential backoff multiplier") + }).optional().describe("Connection retry policy for transient failures"), + /** Description */ + description: external_exports.string().optional().describe("Internal description"), + /** Is enabled? */ + active: external_exports.boolean().default(true).describe("Is datasource enabled") +}); +var AggregationMetricType3 = external_exports.enum([ + "count", + "sum", + "avg", + "min", + "max", + "count_distinct", + "number", + // Custom SQL expression returning a number + "string", + // Custom SQL expression returning a string + "boolean" + // Custom SQL expression returning a boolean +]); +var DimensionType3 = external_exports.enum([ + "string", + "number", + "boolean", + "time", + "geo" +]); +var TimeUpdateInterval3 = external_exports.enum([ + "second", + "minute", + "hour", + "day", + "week", + "month", + "quarter", + "year" +]); +var MetricSchema3 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique metric ID"), + label: external_exports.string().describe("Human readable label"), + description: external_exports.string().optional(), + type: AggregationMetricType3, + /** Source Calculation */ + sql: external_exports.string().describe("SQL expression or field reference"), + /** Filtering for this specific metric (e.g. "Revenue from Premium Users") */ + filters: external_exports.array(external_exports.object({ + sql: external_exports.string() + })).optional(), + /** Format for display (e.g. "currency", "percent") */ + format: external_exports.string().optional() +}); +var DimensionSchema3 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique dimension ID"), + label: external_exports.string().describe("Human readable label"), + description: external_exports.string().optional(), + type: DimensionType3, + /** Source Column */ + sql: external_exports.string().describe("SQL expression or column reference"), + /** For Time Dimensions: Supported Granularities */ + granularities: external_exports.array(TimeUpdateInterval3).optional() +}); +var CubeJoinSchema3 = external_exports.object({ + name: external_exports.string().describe("Target cube name"), + relationship: external_exports.enum(["one_to_one", "one_to_many", "many_to_one"]).default("many_to_one"), + sql: external_exports.string().describe("Join condition (ON clause)") +}); +var CubeSchema3 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Cube name (snake_case)"), + title: external_exports.string().optional(), + description: external_exports.string().optional(), + /** Physical Data Source */ + sql: external_exports.string().describe("Base SQL statement or Table Name"), + /** Semantic Definitions */ + measures: external_exports.record(external_exports.string(), MetricSchema3).describe("Quantitative metrics"), + dimensions: external_exports.record(external_exports.string(), DimensionSchema3).describe("Qualitative attributes"), + /** Relationships */ + joins: external_exports.record(external_exports.string(), CubeJoinSchema3).optional(), + /** Pre-aggregations / Caching */ + refreshKey: external_exports.object({ + every: external_exports.string().optional(), + // e.g. "1 hour" + sql: external_exports.string().optional() + // SQL to check for data changes + }).optional(), + /** Access Control */ + public: external_exports.boolean().default(false) +}); +var AnalyticsQuerySchema3 = external_exports.object({ + cube: external_exports.string().optional().describe("Target cube name (optional when provided externally, e.g. in API request wrapper)"), + measures: external_exports.array(external_exports.string()).describe("List of metrics to calculate"), + dimensions: external_exports.array(external_exports.string()).optional().describe("List of dimensions to group by"), + filters: external_exports.array(external_exports.object({ + member: external_exports.string().describe("Dimension or Measure"), + operator: external_exports.enum(["equals", "notEquals", "contains", "notContains", "gt", "gte", "lt", "lte", "set", "notSet", "inDateRange"]), + values: external_exports.array(external_exports.string()).optional() + })).optional(), + timeDimensions: external_exports.array(external_exports.object({ + dimension: external_exports.string(), + granularity: TimeUpdateInterval3.optional(), + dateRange: external_exports.union([ + external_exports.string(), + // "Last 7 days" + external_exports.array(external_exports.string()) + // ["2023-01-01", "2023-01-31"] + ]).optional() + })).optional(), + order: external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])).optional(), + limit: external_exports.number().optional(), + offset: external_exports.number().optional(), + timezone: external_exports.string().optional().default("UTC") +}); +var FeedItemType4 = external_exports.enum([ + "comment", + "field_change", + "task", + "event", + "email", + "call", + "note", + "file", + "record_create", + "record_delete", + "approval", + "sharing", + "system" +]); +var MentionSchema4 = external_exports.object({ + type: external_exports.enum(["user", "team", "record"]).describe("Mention target type"), + id: external_exports.string().describe("Target ID"), + name: external_exports.string().describe("Display name for rendering"), + offset: external_exports.number().int().min(0).describe("Character offset in body text"), + length: external_exports.number().int().min(1).describe("Length of mention token in body text") +}); +var FieldChangeEntrySchema4 = external_exports.object({ + field: external_exports.string().describe("Field machine name"), + fieldLabel: external_exports.string().optional().describe("Field display label"), + oldValue: external_exports.unknown().optional().describe("Previous value"), + newValue: external_exports.unknown().optional().describe("New value"), + oldDisplayValue: external_exports.string().optional().describe("Human-readable old value"), + newDisplayValue: external_exports.string().optional().describe("Human-readable new value") +}); +var ReactionSchema4 = external_exports.object({ + emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")'), + userIds: external_exports.array(external_exports.string()).describe("Users who reacted"), + count: external_exports.number().int().min(1).describe("Total reaction count") +}); +var FeedActorSchema4 = external_exports.object({ + type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), + id: external_exports.string().describe("Actor ID"), + name: external_exports.string().optional().describe("Actor display name"), + avatarUrl: external_exports.string().url().optional().describe("Actor avatar URL"), + source: external_exports.string().optional().describe('Source application (e.g., "Omni", "API", "Studio")') +}); +var FeedVisibility4 = external_exports.enum(["public", "internal", "private"]); +var FeedItemSchema3 = external_exports.object({ + /** Unique identifier */ + id: external_exports.string().describe("Feed item ID"), + /** Feed item type */ + type: FeedItemType4.describe("Activity type"), + /** Target record reference */ + object: external_exports.string().describe('Object name (e.g., "account")'), + recordId: external_exports.string().describe("Record ID this feed item belongs to"), + /** Actor (who performed the action) */ + actor: FeedActorSchema4.describe("Who performed this action"), + /** Content (for comments/notes) */ + body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), + /** @Mentions */ + mentions: external_exports.array(MentionSchema4).optional().describe("Mentioned users/teams/records"), + /** Field changes (for field_change type) */ + changes: external_exports.array(FieldChangeEntrySchema4).optional().describe("Field-level changes"), + /** Reactions */ + reactions: external_exports.array(ReactionSchema4).optional().describe("Emoji reactions on this item"), + /** Reply threading */ + parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), + replyCount: external_exports.number().int().min(0).default(0).describe("Number of replies"), + /** Pin / Star */ + pinned: external_exports.boolean().default(false).describe("Whether the feed item is pinned to the top of the timeline"), + pinnedAt: external_exports.string().datetime().optional().describe("Timestamp when the item was pinned"), + pinnedBy: external_exports.string().optional().describe("User ID who pinned the item"), + starred: external_exports.boolean().default(false).describe("Whether the feed item is starred/bookmarked by the current user"), + starredAt: external_exports.string().datetime().optional().describe("Timestamp when the item was starred"), + /** Visibility */ + visibility: FeedVisibility4.default("public").describe("Visibility: public (all users), internal (team only), private (author + mentioned)"), + /** Timestamps */ + createdAt: external_exports.string().datetime().describe("Creation timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + editedAt: external_exports.string().datetime().optional().describe("When comment was last edited"), + isEdited: external_exports.boolean().default(false).describe("Whether comment has been edited") +}); +var FeedFilterMode3 = external_exports.enum([ + "all", + "comments_only", + "changes_only", + "tasks_only" +]); +var SubscriptionEventType3 = external_exports.enum([ + "comment", + "mention", + "field_change", + "task", + "approval", + "all" +]); +var NotificationChannel3 = external_exports.enum([ + "in_app", + "email", + "push", + "slack" +]); +var RecordSubscriptionSchema3 = external_exports.object({ + /** Target */ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + /** Subscriber */ + userId: external_exports.string().describe("Subscribing user ID"), + /** Events to subscribe to */ + events: external_exports.array(SubscriptionEventType3).default(["all"]).describe("Event types to receive notifications for"), + /** Notification channels */ + channels: external_exports.array(NotificationChannel3).default(["in_app"]).describe("Notification delivery channels"), + /** Active */ + active: external_exports.boolean().default(true).describe("Whether the subscription is active"), + /** Timestamps */ + createdAt: external_exports.string().datetime().describe("Subscription creation timestamp") +}); +var TenantResolverStrategySchema2 = external_exports.enum([ + "header", + // Resolve from X-Tenant-ID request header + "subdomain", + // Resolve from subdomain (e.g., acme.app.com → acme) + "path", + // Resolve from URL path segment (e.g., /api/acme/...) + "token", + // Resolve from JWT claim (e.g., tenant_id in access token) + "lookup" + // Resolve from control-plane database lookup +]).describe("Strategy for resolving tenant identity from request context"); +var TursoGroupSchema2 = external_exports.object({ + /** + * Group name identifier. + * Used to reference the group when creating new tenant databases. + */ + name: external_exports.string().min(1).describe("Turso database group name"), + /** + * Primary location for the group (Turso region code). + * Example: 'iad' (US East), 'lhr' (London), 'nrt' (Tokyo) + */ + primaryLocation: external_exports.string().min(2).describe("Primary Turso region code (e.g., iad, lhr, nrt)"), + /** + * Additional replica locations for read performance. + * Databases in this group will have read replicas in these regions. + */ + replicaLocations: external_exports.array(external_exports.string().min(2)).default([]).describe("Additional replica region codes"), + /** + * Schema database name within the group. + * When using multi-db schemas, this is the "parent" database + * whose schema is shared by all child (tenant) databases. + */ + schemaDatabase: external_exports.string().optional().describe("Schema database name for multi-db schemas") +}).describe("Turso database group configuration"); +var TenantDatabaseLifecycleSchema2 = external_exports.object({ + /** + * Hook executed when a new tenant is created. + * Defines how the tenant database is provisioned. + */ + onTenantCreate: external_exports.object({ + /** Whether to automatically create a Turso database */ + autoCreate: external_exports.boolean().default(true).describe("Auto-create database on tenant registration"), + /** Database group to create the database in */ + group: external_exports.string().optional().describe("Turso group for the new database"), + /** Whether to apply schema from the group schema database */ + applyGroupSchema: external_exports.boolean().default(true).describe("Apply shared schema from group"), + /** Seed data to populate on creation */ + seedData: external_exports.boolean().default(false).describe("Populate seed data on creation") + }).describe("Tenant creation hook"), + /** + * Hook executed when a tenant is deleted/destroyed. + */ + onTenantDelete: external_exports.object({ + /** Whether to destroy the database immediately or schedule for deletion */ + immediate: external_exports.boolean().default(false).describe("Destroy database immediately"), + /** Grace period in hours before permanent deletion (soft-delete) */ + gracePeriodHours: external_exports.number().int().min(0).default(72).describe("Grace period before permanent deletion"), + /** Whether to create a final backup before deletion */ + createBackup: external_exports.boolean().default(true).describe("Create backup before deletion") + }).describe("Tenant deletion hook"), + /** + * Hook executed when a tenant is suspended (e.g., unpaid, policy violation). + */ + onTenantSuspend: external_exports.object({ + /** Whether to revoke auth tokens on suspension */ + revokeTokens: external_exports.boolean().default(true).describe("Revoke auth tokens on suspension"), + /** Whether to set database to read-only mode */ + readOnly: external_exports.boolean().default(true).describe("Set database to read-only on suspension") + }).describe("Tenant suspension hook") +}).describe("Tenant database lifecycle hooks"); +var TursoMultiTenantConfigSchema2 = external_exports.object({ + /** + * Turso organization slug. + * Used for Platform API calls and URL construction. + */ + organizationSlug: external_exports.string().min(1).describe("Turso organization slug"), + /** + * URL template for constructing tenant database URLs. + * Use `{tenant_id}` as placeholder for the tenant identifier. + * + * Example: 'libsql://{tenant_id}-myorg.turso.io' + */ + urlTemplate: external_exports.string().min(1).describe("URL template with {tenant_id} placeholder"), + /** + * Group-level auth token for Turso Platform API operations. + * Used for database creation, deletion, and management. + * This token has full access to all databases in the group. + */ + groupAuthToken: external_exports.string().min(1).describe("Group-level auth token for platform operations"), + /** + * Strategy for resolving tenant identity from the request context. + */ + tenantResolverStrategy: TenantResolverStrategySchema2.default("token"), + /** + * Turso database group configuration. + */ + group: TursoGroupSchema2.optional().describe("Database group configuration"), + /** + * Lifecycle hooks for tenant database management. + */ + lifecycle: TenantDatabaseLifecycleSchema2.optional().describe("Lifecycle hooks"), + /** + * Maximum number of cached tenant database connections. + * Connections are evicted using LRU strategy when the limit is reached. + */ + maxCachedConnections: external_exports.number().int().min(1).default(100).describe("Max cached tenant connections (LRU)"), + /** + * Connection cache TTL in seconds. + * Cached connections are refreshed after this period. + */ + connectionCacheTTL: external_exports.number().int().min(0).default(300).describe("Connection cache TTL in seconds") +}).describe("Turso multi-tenant router configuration"); +var security_exports = {}; +__export4(security_exports, { + AuditPolicySchema: () => AuditPolicySchema, + CriteriaSharingRuleSchema: () => CriteriaSharingRuleSchema, + FieldPermissionSchema: () => FieldPermissionSchema2, + NetworkPolicySchema: () => NetworkPolicySchema, + OWDModel: () => OWDModel, + ObjectPermissionSchema: () => ObjectPermissionSchema2, + OwnerSharingRuleSchema: () => OwnerSharingRuleSchema, + PasswordPolicySchema: () => PasswordPolicySchema, + PermissionSetSchema: () => PermissionSetSchema2, + PolicySchema: () => PolicySchema, + RLS: () => RLS, + RLSAuditConfigSchema: () => RLSAuditConfigSchema2, + RLSAuditEventSchema: () => RLSAuditEventSchema, + RLSConfigSchema: () => RLSConfigSchema, + RLSEvaluationResultSchema: () => RLSEvaluationResultSchema, + RLSOperation: () => RLSOperation2, + RLSUserContextSchema: () => RLSUserContextSchema, + RowLevelSecurityPolicySchema: () => RowLevelSecurityPolicySchema2, + SessionPolicySchema: () => SessionPolicySchema, + ShareRecipientType: () => ShareRecipientType, + SharingLevel: () => SharingLevel, + SharingRuleSchema: () => SharingRuleSchema, + SharingRuleType: () => SharingRuleType, + TerritoryModelSchema: () => TerritoryModelSchema, + TerritorySchema: () => TerritorySchema, + TerritoryType: () => TerritoryType +}); +var RLSOperation2 = external_exports.enum(["select", "insert", "update", "delete", "all"]); +var RowLevelSecurityPolicySchema2 = external_exports.object({ + /** + * Unique identifier for this policy. + * Must be unique within the object. + * Use snake_case following ObjectStack naming conventions. + * + * @example "tenant_isolation", "owner_access", "manager_team_view" + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Policy unique identifier (snake_case)"), + /** + * Human-readable label for the policy. + * Used in admin UI and logs. + * + * @example "Multi-Tenant Data Isolation", "Owner-Based Access" + */ + label: external_exports.string().optional().describe("Human-readable policy label"), + /** + * Description explaining what this policy does and why. + * Helps with governance and compliance. + * + * @example "Ensures users can only access records from their own tenant organization" + */ + description: external_exports.string().optional().describe("Policy description and business justification"), + /** + * Target object (table) this policy applies to. + * Must reference a valid ObjectStack object name. + * + * @example "account", "opportunity", "contact", "custom_object" + */ + object: external_exports.string().describe("Target object name"), + /** + * Database operation(s) this policy applies to. + * + * - **select**: Controls read access (SELECT queries) + * - **insert**: Controls insert access (INSERT statements) + * - **update**: Controls update access (UPDATE statements) + * - **delete**: Controls delete access (DELETE statements) + * - **all**: Applies to all operations + * + * @example "select" - Most common, controls what users can view + * @example "all" - Apply same rule to all operations + */ + operation: RLSOperation2.describe("Database operation this policy applies to"), + /** + * USING clause - Filter condition for SELECT/UPDATE/DELETE. + * + * This is a SQL-like expression evaluated for each row. + * Only rows where this expression returns TRUE are accessible. + * + * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed). + * For SELECT/UPDATE/DELETE operations, USING is required. + * + * **Security Note**: RLS conditions are executed at the database level with + * parameterized queries. The implementation must use prepared statements + * to prevent SQL injection. Never concatenate user input directly into + * RLS conditions. + * + * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations + * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain + * semantic equivalence. + * + * Available context variables: + * - `current_user.id` - Current user's ID + * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext) + * - `current_user.role` - Current user's role + * - `current_user.department` - Current user's department + * - `current_user.*` - Any custom user field + * - `NOW()` - Current timestamp + * - `CURRENT_DATE` - Current date + * - `CURRENT_TIME` - Current time + * + * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`), + * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`). + * Implementations must handle this mapping. + * + * Supported operators: + * - Comparison: =, !=, <, >, <=, >=, <> (not equal) + * - Logical: AND, OR, NOT + * - NULL checks: IS NULL, IS NOT NULL + * - Set operations: IN, NOT IN + * - String: LIKE, NOT LIKE, ILIKE (case-insensitive) + * - Pattern matching: ~ (regex), !~ (not regex) + * - Subqueries: (SELECT ...) + * - Array operations: ANY, ALL + * + * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE) + * + * @example "tenant_id = current_user.tenant_id" + * @example "owner_id = current_user.id OR created_by = current_user.id" + * @example "department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)" + * @example "status = 'active' AND expiry_date > NOW()" + */ + using: external_exports.string().optional().describe("Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies."), + /** + * CHECK clause - Validation for INSERT/UPDATE operations. + * + * Similar to USING but applies to new/modified rows. + * Prevents users from creating/updating rows they wouldn't be able to see. + * + * **Default Behavior**: If not specified, implementations should use the + * USING clause as the CHECK clause. This ensures data integrity by preventing + * users from creating records they cannot view. + * + * Use cases: + * - Prevent cross-tenant data creation + * - Enforce mandatory field values + * - Validate data integrity rules + * - Restrict certain operations (e.g., only allow creating "draft" status) + * + * @example "tenant_id = current_user.tenant_id" + * @example "status IN ('draft', 'pending')" - Only allow certain statuses + * @example "created_by = current_user.id" - Must be the creator + */ + check: external_exports.string().optional().describe("Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)"), + /** + * Restrict this policy to specific roles. + * If specified, only users with these roles will have this policy applied. + * If omitted, policy applies to all users (except those with bypassRLS permission). + * + * Role names must match defined roles in the system. + * + * @example ["sales_rep", "account_manager"] + * @example ["employee"] - Apply to all employees + * @example ["guest"] - Special restrictions for guests + */ + roles: external_exports.array(external_exports.string()).optional().describe("Roles this policy applies to (omit for all roles)"), + /** + * Whether this policy is currently active. + * Disabled policies are not evaluated. + * Useful for temporary policy changes without deletion. + * + * @default true + */ + enabled: external_exports.boolean().default(true).describe("Whether this policy is active"), + /** + * Policy priority for conflict resolution. + * Higher numbers = higher priority. + * When multiple policies apply, the most permissive wins (OR logic). + * Priority is only used for ordering evaluation (performance). + * + * @default 0 + */ + priority: external_exports.number().int().default(0).describe("Policy evaluation priority (higher = evaluated first)"), + /** + * Tags for policy categorization and reporting. + * Useful for governance, compliance, and auditing. + * + * @example ["compliance", "gdpr", "pci"] + * @example ["multi-tenant", "security"] + */ + tags: external_exports.array(external_exports.string()).optional().describe("Policy categorization tags") +}).superRefine((data, ctx) => { + if (!data.using && !data.check) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: 'At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".' + }); + } +}); +var RLSAuditEventSchema = external_exports.object({ + /** ISO 8601 timestamp of the evaluation */ + timestamp: external_exports.string().describe("ISO 8601 timestamp of the evaluation"), + /** ID of the user whose access was evaluated */ + userId: external_exports.string().describe("User ID whose access was evaluated"), + /** Database operation being performed */ + operation: external_exports.enum(["select", "insert", "update", "delete"]).describe("Database operation being performed"), + /** Target object (table) name */ + object: external_exports.string().describe("Target object name"), + /** Name of the RLS policy evaluated */ + policyName: external_exports.string().describe("Name of the RLS policy evaluated"), + /** Whether access was granted */ + granted: external_exports.boolean().describe("Whether access was granted"), + /** Time taken to evaluate the policy in milliseconds */ + evaluationDurationMs: external_exports.number().describe("Policy evaluation duration in milliseconds"), + /** Which USING/CHECK clause matched */ + matchedCondition: external_exports.string().optional().describe("Which USING/CHECK clause matched"), + /** Number of rows affected by the operation */ + rowCount: external_exports.number().optional().describe("Number of rows affected"), + /** Additional metadata for the audit event */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional audit event metadata") +}); +var RLSAuditConfigSchema2 = external_exports.object({ + /** Enable RLS audit logging */ + enabled: external_exports.boolean().describe("Enable RLS audit logging"), + /** Which evaluations to log */ + logLevel: external_exports.enum(["all", "denied_only", "granted_only", "none"]).describe("Which evaluations to log"), + /** Where to send audit logs */ + destination: external_exports.enum(["system_log", "audit_trail", "external"]).describe("Audit log destination"), + /** Sampling rate for high-traffic environments (0-1) */ + sampleRate: external_exports.number().min(0).max(1).describe("Sampling rate (0-1) for high-traffic environments"), + /** Number of days to retain audit logs */ + retentionDays: external_exports.number().int().default(90).describe("Audit log retention period in days"), + /** Whether to include row data in audit logs (security-sensitive) */ + includeRowData: external_exports.boolean().default(false).describe("Include row data in audit logs (security-sensitive)"), + /** Alert when access is denied */ + alertOnDenied: external_exports.boolean().default(true).describe("Send alerts when access is denied") +}); +var RLSConfigSchema = external_exports.object({ + /** + * Global RLS enable/disable flag. + * When false, all RLS policies are ignored (use with caution!). + * + * @default true + */ + enabled: external_exports.boolean().default(true).describe("Enable RLS enforcement globally"), + /** + * Default behavior when no policies match. + * + * - **deny**: Deny access (secure default) + * - **allow**: Allow access (permissive mode, not recommended) + * + * @default "deny" + */ + defaultPolicy: external_exports.enum(["deny", "allow"]).default("deny").describe("Default action when no policies match"), + /** + * Whether to allow superusers to bypass RLS. + * Superusers include system administrators and service accounts. + * + * @default true + */ + allowSuperuserBypass: external_exports.boolean().default(true).describe("Allow superusers to bypass RLS"), + /** + * List of roles that can bypass RLS. + * Users with these roles see all records regardless of policies. + * + * @example ["system_admin", "data_auditor"] + */ + bypassRoles: external_exports.array(external_exports.string()).optional().describe("Roles that bypass RLS (see all data)"), + /** + * Whether to log RLS policy evaluations. + * Useful for debugging and auditing. + * Can impact performance if enabled globally. + * + * @default false + */ + logEvaluations: external_exports.boolean().default(false).describe("Log RLS policy evaluations for debugging"), + /** + * Cache RLS policy evaluation results. + * Can improve performance for frequently accessed records. + * Cache is invalidated when policies change or user context changes. + * + * @default true + */ + cacheResults: external_exports.boolean().default(true).describe("Cache RLS evaluation results"), + /** + * Cache TTL in seconds. + * How long to cache RLS evaluation results. + * + * @default 300 (5 minutes) + */ + cacheTtlSeconds: external_exports.number().int().positive().default(300).describe("Cache TTL in seconds"), + /** + * Performance optimization: Pre-fetch user context. + * Load user context once per request instead of per-query. + * + * @default true + */ + prefetchUserContext: external_exports.boolean().default(true).describe("Pre-fetch user context for performance"), + /** + * Audit logging configuration for RLS evaluations. + */ + audit: RLSAuditConfigSchema2.optional().describe("RLS audit logging configuration") +}); +var RLSUserContextSchema = external_exports.object({ + /** + * User ID + */ + id: external_exports.string().describe("User ID"), + /** + * User email + */ + email: external_exports.string().email().optional().describe("User email"), + /** + * Tenant/Organization ID + */ + tenantId: external_exports.string().optional().describe("Tenant/Organization ID"), + /** + * User role(s) + */ + role: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.string()) + ]).optional().describe("User role(s)"), + /** + * User department + */ + department: external_exports.string().optional().describe("User department"), + /** + * Additional custom attributes + * Can include any custom user fields for RLS evaluation + */ + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom user attributes") +}); +var RLSEvaluationResultSchema = external_exports.object({ + /** + * Policy name that was evaluated + */ + policyName: external_exports.string().describe("Policy name"), + /** + * Whether access was granted + */ + granted: external_exports.boolean().describe("Whether access was granted"), + /** + * Evaluation duration in milliseconds + */ + durationMs: external_exports.number().optional().describe("Evaluation duration in milliseconds"), + /** + * Error message if evaluation failed + */ + error: external_exports.string().optional().describe("Error message if evaluation failed"), + /** + * Evaluated USING clause result + */ + usingResult: external_exports.boolean().optional().describe("USING clause evaluation result"), + /** + * Evaluated CHECK clause result (for INSERT/UPDATE) + */ + checkResult: external_exports.boolean().optional().describe("CHECK clause evaluation result") +}); +var RLS = { + /** + * Create a simple owner-based policy + */ + ownerPolicy: (object2, ownerField = "owner_id") => ({ + name: `${object2}_owner_access`, + label: `Owner Access for ${object2}`, + object: object2, + operation: "all", + using: `${ownerField} = current_user.id`, + enabled: true, + priority: 0 + }), + /** + * Create a tenant isolation policy + */ + tenantPolicy: (object2, tenantField = "tenant_id") => ({ + name: `${object2}_tenant_isolation`, + label: `Tenant Isolation for ${object2}`, + object: object2, + operation: "all", + using: `${tenantField} = current_user.tenant_id`, + check: `${tenantField} = current_user.tenant_id`, + enabled: true, + priority: 0 + }), + /** + * Create a role-based policy + */ + rolePolicy: (object2, roles, condition) => ({ + name: `${object2}_${roles.join("_")}_access`, + label: `${roles.join(", ")} Access for ${object2}`, + object: object2, + operation: "select", + using: condition, + roles, + enabled: true, + priority: 0 + }), + /** + * Create a permissive policy (allow all for specific roles) + */ + allowAllPolicy: (object2, roles) => ({ + name: `${object2}_${roles.join("_")}_full_access`, + label: `Full Access for ${roles.join(", ")}`, + object: object2, + operation: "all", + using: "1 = 1", + // Always true + roles, + enabled: true, + priority: 0 + }) +}; +var ObjectPermissionSchema2 = external_exports.object({ + /** C: Create */ + allowCreate: external_exports.boolean().default(false).describe("Create permission"), + /** R: Read (Owned records or Shared records) */ + allowRead: external_exports.boolean().default(false).describe("Read permission"), + /** U: Edit (Owned records or Shared records) */ + allowEdit: external_exports.boolean().default(false).describe("Edit permission"), + /** D: Delete (Owned records or Shared records) */ + allowDelete: external_exports.boolean().default(false).describe("Delete permission"), + /** Lifecycle Operations */ + allowTransfer: external_exports.boolean().default(false).describe("Change record ownership"), + allowRestore: external_exports.boolean().default(false).describe("Restore from trash (Undelete)"), + allowPurge: external_exports.boolean().default(false).describe("Permanently delete (Hard Delete/GDPR)"), + /** + * View All Records: Super-user read access. + * Bypasses Sharing Rules and Ownership checks. + * Equivalent to Microsoft Dataverse "Organization" level read access. + */ + viewAllRecords: external_exports.boolean().default(false).describe("View All Data (Bypass Sharing)"), + /** + * Modify All Records: Super-user write access. + * Bypasses Sharing Rules and Ownership checks. + * Equivalent to Microsoft Dataverse "Organization" level write access. + */ + modifyAllRecords: external_exports.boolean().default(false).describe("Modify All Data (Bypass Sharing)") +}); +var FieldPermissionSchema2 = external_exports.object({ + /** Can see this field */ + readable: external_exports.boolean().default(true).describe("Field read access"), + /** Can edit this field */ + editable: external_exports.boolean().default(false).describe("Field edit access") +}); +var PermissionSetSchema2 = external_exports.object({ + /** Unique permission set name */ + name: SnakeCaseIdentifierSchema7.describe("Permission set unique name (lowercase snake_case)"), + /** Display label */ + label: external_exports.string().optional().describe("Display label"), + /** Is this a Profile? (Base set for a user) */ + isProfile: external_exports.boolean().default(false).describe("Whether this is a user profile"), + /** Object Permissions Map: -> permissions */ + objects: external_exports.record(external_exports.string(), ObjectPermissionSchema2).describe("Entity permissions"), + /** Field Permissions Map: . -> permissions */ + fields: external_exports.record(external_exports.string(), FieldPermissionSchema2).optional().describe("Field level security"), + /** System permissions (e.g., "manage_users") */ + systemPermissions: external_exports.array(external_exports.string()).optional().describe("System level capabilities"), + /** + * Tab/App Visibility Permissions (Salesforce Pattern) + * Controls which app tabs are visible, hidden, or set as default for this permission set. + * + * @example + * ```typescript + * tabPermissions: { + * 'app_crm': 'visible', + * 'app_admin': 'hidden', + * 'app_sales': 'default_on' + * } + * ``` + */ + tabPermissions: external_exports.record(external_exports.string(), external_exports.enum(["visible", "hidden", "default_on", "default_off"])).optional().describe("App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)"), + /** + * Row-Level Security Rules + * + * Row-level security policies that filter records based on user context. + * These rules are applied in addition to object-level permissions. + * + * Uses the canonical RLS protocol from rls.zod.ts for comprehensive + * row-level security features including PostgreSQL-style USING and CHECK clauses. + * + * @see {@link RowLevelSecurityPolicySchema} for full RLS specification + * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation + * + * @example Multi-tenant isolation + * ```typescript + * rls: [{ + * name: 'tenant_filter', + * object: 'account', + * operation: 'select', + * using: 'tenant_id = current_user.tenant_id' + * }] + * ``` + */ + rowLevelSecurity: external_exports.array(RowLevelSecurityPolicySchema2).optional().describe("Row-level security policies (see rls.zod.ts for full spec)"), + /** + * Context-Based Access Control Variables + * + * Custom context variables that can be referenced in RLS rules. + * These variables are evaluated at runtime based on the user's session. + * + * Common context variables: + * - `current_user.id` - Current user ID + * - `current_user.tenant_id` - User's tenant/organization ID + * - `current_user.department` - User's department + * - `current_user.role` - User's role + * - `current_user.region` - User's geographic region + * + * @example Custom context + * ```typescript + * contextVariables: { + * allowed_regions: ['US', 'EU'], + * access_level: 2, + * custom_attribute: 'value' + * } + * ``` + */ + contextVariables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Context variables for RLS evaluation") +}); +var OWDModel = external_exports.enum([ + "private", + // Only owner can see + "public_read", + // Everyone can see, owner can edit + "public_read_write", + // Everyone can see and edit + "controlled_by_parent" + // Access derived from parent record (Master-Detail) +]); +var SharingRuleType = external_exports.enum([ + "owner", + // Based on record ownership (Role Hierarchy) + "criteria" + // Based on field values (e.g. Status = 'Open') +]); +var SharingLevel = external_exports.enum([ + "read", + // Read Only + "edit", + // Read / Write + "full" + // Full Access (Transfer, Share, Delete) +]); +var ShareRecipientType = external_exports.enum([ + "user", + "group", + "role", + "role_and_subordinates", + "guest" + // for public sharing +]); +var BaseSharingRuleSchema = external_exports.object({ + // Identification + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label"), + description: external_exports.string().optional().describe("Administrative notes"), + // Scope + object: external_exports.string().describe("Target Object Name"), + active: external_exports.boolean().default(true), + // Access + accessLevel: SharingLevel.default("read"), + // Recipient (Whom to share with) + sharedWith: external_exports.object({ + type: ShareRecipientType, + value: external_exports.string().describe("ID or Code of the User/Group/Role") + }).describe("The recipient of the shared access") +}); +var CriteriaSharingRuleSchema = BaseSharingRuleSchema.extend({ + type: external_exports.literal("criteria"), + condition: external_exports.string().describe(`Formula condition (e.g. "department = 'Sales'")`) +}); +var OwnerSharingRuleSchema = BaseSharingRuleSchema.extend({ + type: external_exports.literal("owner"), + ownedBy: external_exports.object({ + type: ShareRecipientType, + value: external_exports.string() + }).describe("Source group/role whose records are being shared") +}); +var SharingRuleSchema = external_exports.discriminatedUnion("type", [ + CriteriaSharingRuleSchema, + OwnerSharingRuleSchema +]); +var TerritoryType = external_exports.enum([ + "geography", + // Region/Country/City + "industry", + // Vertical + "named_account", + // Key Accounts + "product_line" + // Product Specialty +]); +var TerritoryModelSchema = external_exports.object({ + name: external_exports.string().describe("Model Name (e.g. FY24 Planning)"), + state: external_exports.enum(["planning", "active", "archived"]).default("planning"), + startDate: external_exports.string().optional(), + endDate: external_exports.string().optional() +}); +var TerritorySchema = external_exports.object({ + /** Identity */ + name: SnakeCaseIdentifierSchema7.describe("Territory unique name (lowercase snake_case)"), + label: external_exports.string().describe('Territory Label (e.g. "West Coast")'), + /** Structure */ + modelId: external_exports.string().describe("Belongs to which Territory Model"), + parent: external_exports.string().optional().describe("Parent Territory"), + type: TerritoryType.default("geography"), + /** + * Assignment Rules (The "Magic") + * How do accounts automatically fall into this territory? + * e.g. "BillingCountry = 'US' AND BillingState = 'CA'" + */ + assignmentRule: external_exports.string().optional().describe("Criteria based assignment rule"), + /** + * User Assignment + * Users assigned to work this territory. + */ + assignedUsers: external_exports.array(external_exports.string()).optional(), + /** Access Level */ + accountAccess: external_exports.enum(["read", "edit"]).default("read"), + opportunityAccess: external_exports.enum(["read", "edit"]).default("read"), + caseAccess: external_exports.enum(["read", "edit"]).default("read") +}); +var PasswordPolicySchema = external_exports.object({ + minLength: external_exports.number().default(8), + requireUppercase: external_exports.boolean().default(true), + requireLowercase: external_exports.boolean().default(true), + requireNumbers: external_exports.boolean().default(true), + requireSymbols: external_exports.boolean().default(false), + expirationDays: external_exports.number().optional().describe("Force password change every X days"), + historyCount: external_exports.number().default(3).describe("Prevent reusing last X passwords") +}); +var NetworkPolicySchema = external_exports.object({ + trustedRanges: external_exports.array(external_exports.string()).describe("CIDR ranges allowed to access (e.g. 10.0.0.0/8)"), + blockUnknown: external_exports.boolean().default(false).describe("Block all IPs not in trusted ranges"), + vpnRequired: external_exports.boolean().default(false) +}); +var SessionPolicySchema = external_exports.object({ + idleTimeout: external_exports.number().default(30).describe("Minutes before idle session logout"), + absoluteTimeout: external_exports.number().default(480).describe("Max session duration (minutes)"), + forceMfa: external_exports.boolean().default(false).describe("Require 2FA for all users") +}); +var AuditPolicySchema = external_exports.object({ + logRetentionDays: external_exports.number().default(180), + sensitiveFields: external_exports.array(external_exports.string()).describe("Fields to redact in logs (e.g. password, ssn)"), + captureRead: external_exports.boolean().default(false).describe("Log read access (High volume!)") +}); +var PolicySchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Policy Name"), + password: PasswordPolicySchema.optional(), + network: NetworkPolicySchema.optional(), + session: SessionPolicySchema.optional(), + audit: AuditPolicySchema.optional(), + /** Assignment */ + isDefault: external_exports.boolean().default(false).describe("Apply to all users by default"), + assignedProfiles: external_exports.array(external_exports.string()).optional().describe("Apply to specific profiles") +}); +var ui_exports = {}; +__export4(ui_exports, { + AIChatWindowProps: () => AIChatWindowProps2, + Action: () => Action, + ActionNavItemSchema: () => ActionNavItemSchema3, + ActionParamSchema: () => ActionParamSchema5, + ActionSchema: () => ActionSchema5, + ActionType: () => ActionType5, + AddRecordConfigSchema: () => AddRecordConfigSchema3, + AnimationSchema: () => AnimationSchema2, + AnimationTriggerSchema: () => AnimationTriggerSchema2, + App: () => App2, + AppBrandingSchema: () => AppBrandingSchema3, + AppSchema: () => AppSchema3, + AppearanceConfigSchema: () => AppearanceConfigSchema3, + AriaPropsSchema: () => AriaPropsSchema5, + BlankPageLayoutItemSchema: () => BlankPageLayoutItemSchema2, + BlankPageLayoutSchema: () => BlankPageLayoutSchema2, + BorderRadiusSchema: () => BorderRadiusSchema2, + BreakpointColumnMapSchema: () => BreakpointColumnMapSchema3, + BreakpointName: () => BreakpointName3, + BreakpointOrderMapSchema: () => BreakpointOrderMapSchema3, + BreakpointsSchema: () => BreakpointsSchema2, + CalendarConfigSchema: () => CalendarConfigSchema3, + ChartAnnotationSchema: () => ChartAnnotationSchema2, + ChartAxisSchema: () => ChartAxisSchema2, + ChartConfigSchema: () => ChartConfigSchema2, + ChartInteractionSchema: () => ChartInteractionSchema2, + ChartSeriesSchema: () => ChartSeriesSchema2, + ChartTypeSchema: () => ChartTypeSchema2, + ColorPaletteSchema: () => ColorPaletteSchema2, + ColumnSummarySchema: () => ColumnSummarySchema3, + ComponentAnimationSchema: () => ComponentAnimationSchema2, + ComponentPropsMap: () => ComponentPropsMap2, + ConflictResolutionSchema: () => ConflictResolutionSchema2, + Dashboard: () => Dashboard, + DashboardHeaderActionSchema: () => DashboardHeaderActionSchema2, + DashboardHeaderSchema: () => DashboardHeaderSchema2, + DashboardNavItemSchema: () => DashboardNavItemSchema3, + DashboardSchema: () => DashboardSchema2, + DashboardWidgetSchema: () => DashboardWidgetSchema2, + DateFormatSchema: () => DateFormatSchema5, + DensityMode: () => DensityMode, + DensityModeSchema: () => DensityModeSchema2, + DndConfigSchema: () => DndConfigSchema2, + DragConstraintSchema: () => DragConstraintSchema2, + DragHandleSchema: () => DragHandleSchema2, + DragItemSchema: () => DragItemSchema2, + DropEffectSchema: () => DropEffectSchema2, + DropZoneSchema: () => DropZoneSchema2, + EasingFunctionSchema: () => EasingFunctionSchema2, + ElementButtonPropsSchema: () => ElementButtonPropsSchema2, + ElementDataSourceSchema: () => ElementDataSourceSchema2, + ElementFilterPropsSchema: () => ElementFilterPropsSchema2, + ElementFormPropsSchema: () => ElementFormPropsSchema2, + ElementImagePropsSchema: () => ElementImagePropsSchema2, + ElementNumberPropsSchema: () => ElementNumberPropsSchema2, + ElementRecordPickerPropsSchema: () => ElementRecordPickerPropsSchema2, + ElementTextPropsSchema: () => ElementTextPropsSchema2, + EmbedConfigSchema: () => EmbedConfigSchema3, + EvictionPolicySchema: () => EvictionPolicySchema2, + FieldWidgetPropsSchema: () => FieldWidgetPropsSchema2, + FocusManagementSchema: () => FocusManagementSchema2, + FocusTrapConfigSchema: () => FocusTrapConfigSchema2, + FormFieldSchema: () => FormFieldSchema3, + FormSectionSchema: () => FormSectionSchema3, + FormViewSchema: () => FormViewSchema3, + GalleryConfigSchema: () => GalleryConfigSchema3, + GanttConfigSchema: () => GanttConfigSchema3, + GestureConfigSchema: () => GestureConfigSchema2, + GestureTypeSchema: () => GestureTypeSchema2, + GlobalFilterOptionsFromSchema: () => GlobalFilterOptionsFromSchema2, + GlobalFilterSchema: () => GlobalFilterSchema2, + GroupNavItemSchema: () => GroupNavItemSchema3, + GroupingConfigSchema: () => GroupingConfigSchema3, + GroupingFieldSchema: () => GroupingFieldSchema3, + HttpMethodSchema: () => HttpMethodSchema5, + HttpRequestSchema: () => HttpRequestSchema4, + I18nLabelSchema: () => I18nLabelSchema5, + I18nObjectSchema: () => I18nObjectSchema2, + InterfacePageConfigSchema: () => InterfacePageConfigSchema2, + KanbanConfigSchema: () => KanbanConfigSchema3, + KeyboardNavigationConfigSchema: () => KeyboardNavigationConfigSchema2, + KeyboardShortcutSchema: () => KeyboardShortcutSchema2, + ListColumnSchema: () => ListColumnSchema3, + ListViewSchema: () => ListViewSchema3, + LocaleConfigSchema: () => LocaleConfigSchema2, + LongPressGestureConfigSchema: () => LongPressGestureConfigSchema2, + MotionConfigSchema: () => MotionConfigSchema2, + NavigationAreaSchema: () => NavigationAreaSchema3, + NavigationConfigSchema: () => NavigationConfigSchema3, + NavigationItemSchema: () => NavigationItemSchema3, + NavigationModeSchema: () => NavigationModeSchema3, + NotificationActionSchema: () => NotificationActionSchema2, + NotificationConfigSchema: () => NotificationConfigSchema3, + NotificationPositionSchema: () => NotificationPositionSchema2, + NotificationSchema: () => NotificationSchema3, + NotificationSeveritySchema: () => NotificationSeveritySchema2, + NotificationTypeSchema: () => NotificationTypeSchema2, + NumberFormatSchema: () => NumberFormatSchema5, + ObjectNavItemSchema: () => ObjectNavItemSchema3, + OfflineCacheConfigSchema: () => OfflineCacheConfigSchema2, + OfflineConfigSchema: () => OfflineConfigSchema2, + OfflineStrategySchema: () => OfflineStrategySchema2, + PageAccordionProps: () => PageAccordionProps2, + PageCardProps: () => PageCardProps2, + PageComponentSchema: () => PageComponentSchema2, + PageComponentType: () => PageComponentType2, + PageHeaderProps: () => PageHeaderProps2, + PageNavItemSchema: () => PageNavItemSchema3, + PageRegionSchema: () => PageRegionSchema2, + PageSchema: () => PageSchema2, + PageTabsProps: () => PageTabsProps2, + PageTransitionSchema: () => PageTransitionSchema2, + PageTypeSchema: () => PageTypeSchema2, + PageVariableSchema: () => PageVariableSchema2, + PaginationConfigSchema: () => PaginationConfigSchema3, + PerformanceConfigSchema: () => PerformanceConfigSchema3, + PersistStorageSchema: () => PersistStorageSchema2, + PinchGestureConfigSchema: () => PinchGestureConfigSchema2, + PluralRuleSchema: () => PluralRuleSchema2, + RecordActivityProps: () => RecordActivityProps2, + RecordChatterProps: () => RecordChatterProps2, + RecordDetailsProps: () => RecordDetailsProps2, + RecordHighlightsProps: () => RecordHighlightsProps2, + RecordPathProps: () => RecordPathProps2, + RecordRelatedListProps: () => RecordRelatedListProps2, + RecordReviewConfigSchema: () => RecordReviewConfigSchema2, + Report: () => Report, + ReportChartSchema: () => ReportChartSchema2, + ReportColumnSchema: () => ReportColumnSchema2, + ReportGroupingSchema: () => ReportGroupingSchema2, + ReportNavItemSchema: () => ReportNavItemSchema3, + ReportSchema: () => ReportSchema2, + ReportType: () => ReportType2, + ResponsiveConfigSchema: () => ResponsiveConfigSchema3, + RowColorConfigSchema: () => RowColorConfigSchema3, + RowHeightSchema: () => RowHeightSchema3, + SelectionConfigSchema: () => SelectionConfigSchema3, + ShadowSchema: () => ShadowSchema2, + SharingConfigSchema: () => SharingConfigSchema3, + SpacingSchema: () => SpacingSchema2, + SwipeDirectionSchema: () => SwipeDirectionSchema2, + SwipeGestureConfigSchema: () => SwipeGestureConfigSchema2, + SyncConfigSchema: () => SyncConfigSchema2, + ThemeMode: () => ThemeMode, + ThemeModeSchema: () => ThemeModeSchema2, + ThemeSchema: () => ThemeSchema2, + TimelineConfigSchema: () => TimelineConfigSchema3, + TouchInteractionSchema: () => TouchInteractionSchema2, + TouchTargetConfigSchema: () => TouchTargetConfigSchema2, + TransitionConfigSchema: () => TransitionConfigSchema2, + TransitionPresetSchema: () => TransitionPresetSchema2, + TypographySchema: () => TypographySchema2, + UrlNavItemSchema: () => UrlNavItemSchema3, + UserActionsConfigSchema: () => UserActionsConfigSchema3, + ViewDataSchema: () => ViewDataSchema3, + ViewFilterRuleSchema: () => ViewFilterRuleSchema3, + ViewSchema: () => ViewSchema3, + ViewSharingSchema: () => ViewSharingSchema3, + ViewTabSchema: () => ViewTabSchema3, + VisualizationTypeSchema: () => VisualizationTypeSchema3, + WcagContrastLevel: () => WcagContrastLevel, + WcagContrastLevelSchema: () => WcagContrastLevelSchema2, + WidgetActionTypeSchema: () => WidgetActionTypeSchema2, + WidgetColorVariantSchema: () => WidgetColorVariantSchema2, + WidgetEventSchema: () => WidgetEventSchema2, + WidgetLifecycleSchema: () => WidgetLifecycleSchema2, + WidgetManifestSchema: () => WidgetManifestSchema2, + WidgetMeasureSchema: () => WidgetMeasureSchema2, + WidgetPropertySchema: () => WidgetPropertySchema2, + WidgetSourceSchema: () => WidgetSourceSchema2, + ZIndexSchema: () => ZIndexSchema2, + defineApp: () => defineApp2, + defineView: () => defineView +}); +var ChartTypeSchema2 = external_exports.enum([ + // Comparison + "bar", + "horizontal-bar", + "column", + "grouped-bar", + "stacked-bar", + "bi-polar-bar", + // Trend + "line", + "area", + "stacked-area", + "step-line", + "spline", + // Distribution + "pie", + "donut", + "funnel", + "pyramid", + // Relationship + "scatter", + "bubble", + // Composition + "treemap", + "sunburst", + "sankey", + "word-cloud", + // Performance + "gauge", + "solid-gauge", + "metric", + "kpi", + "bullet", + // Geo + "choropleth", + "bubble-map", + "gl-map", + // Advanced + "heatmap", + "radar", + "waterfall", + "box-plot", + "violin", + "candlestick", + "stock", + // Tabular + "table", + "pivot" +]); +var ChartAxisSchema2 = external_exports.object({ + /** Data field to map to this axis */ + field: external_exports.string().describe("Data field key"), + /** Axis title */ + title: I18nLabelSchema5.optional().describe("Axis display title"), + /** Value formatting (d3-format or similar) */ + format: external_exports.string().optional().describe('Value format string (e.g., "$0,0.00")'), + /** Axis scale settings */ + min: external_exports.number().optional().describe("Minimum value"), + max: external_exports.number().optional().describe("Maximum value"), + stepSize: external_exports.number().optional().describe("Step size for ticks"), + /** Appearance */ + showGridLines: external_exports.boolean().default(true), + position: external_exports.enum(["left", "right", "top", "bottom"]).optional().describe("Axis position"), + /** Logarithmic scale */ + logarithmic: external_exports.boolean().default(false) +}); +var ChartSeriesSchema2 = external_exports.object({ + /** Field name for values */ + name: external_exports.string().describe("Field name or series identifier"), + /** Display label */ + label: I18nLabelSchema5.optional().describe("Series display label"), + /** Series type override (combo charts) */ + type: ChartTypeSchema2.optional().describe("Override chart type for this series"), + /** Specific color */ + color: external_exports.string().optional().describe("Series color (hex/rgb/token)"), + /** Stacking group */ + stack: external_exports.string().optional().describe("Stack identifier to group series"), + /** Axis binding */ + yAxis: external_exports.enum(["left", "right"]).default("left").describe("Bind to specific Y-Axis") +}); +var ChartAnnotationSchema2 = external_exports.object({ + type: external_exports.enum(["line", "region"]).default("line"), + axis: external_exports.enum(["x", "y"]).default("y"), + value: external_exports.union([external_exports.number(), external_exports.string()]).describe("Start value"), + endValue: external_exports.union([external_exports.number(), external_exports.string()]).optional().describe("End value for regions"), + color: external_exports.string().optional(), + label: I18nLabelSchema5.optional(), + style: external_exports.enum(["solid", "dashed", "dotted"]).default("dashed") +}); +var ChartInteractionSchema2 = external_exports.object({ + tooltips: external_exports.boolean().default(true), + zoom: external_exports.boolean().default(false), + brush: external_exports.boolean().default(false), + clickAction: external_exports.string().optional().describe("Action ID to trigger on click") +}); +var ChartConfigSchema2 = external_exports.object({ + /** Chart Type */ + type: ChartTypeSchema2, + /** Titles */ + title: I18nLabelSchema5.optional().describe("Chart title"), + subtitle: I18nLabelSchema5.optional().describe("Chart subtitle"), + description: I18nLabelSchema5.optional().describe("Accessibility description"), + /** Axes Mapping */ + xAxis: ChartAxisSchema2.optional().describe("X-Axis configuration"), + yAxis: external_exports.array(ChartAxisSchema2).optional().describe("Y-Axis configuration (support dual axis)"), + /** Series Configuration */ + series: external_exports.array(ChartSeriesSchema2).optional().describe("Defined series configuration"), + /** Appearance */ + colors: external_exports.array(external_exports.string()).optional().describe("Color palette"), + height: external_exports.number().optional().describe("Fixed height in pixels"), + /** Components */ + showLegend: external_exports.boolean().default(true).describe("Display legend"), + showDataLabels: external_exports.boolean().default(false).describe("Display data labels"), + /** Annotations & Reference Lines */ + annotations: external_exports.array(ChartAnnotationSchema2).optional(), + /** Interactions */ + interaction: ChartInteractionSchema2.optional(), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var BreakpointName3 = external_exports.enum(["xs", "sm", "md", "lg", "xl", "2xl"]); +var BreakpointColumnMapSchema3 = external_exports.object({ + xs: external_exports.number().min(1).max(12).optional(), + sm: external_exports.number().min(1).max(12).optional(), + md: external_exports.number().min(1).max(12).optional(), + lg: external_exports.number().min(1).max(12).optional(), + xl: external_exports.number().min(1).max(12).optional(), + "2xl": external_exports.number().min(1).max(12).optional() +}).describe("Grid columns per breakpoint (1-12)"); +var BreakpointOrderMapSchema3 = external_exports.object({ + xs: external_exports.number().optional(), + sm: external_exports.number().optional(), + md: external_exports.number().optional(), + lg: external_exports.number().optional(), + xl: external_exports.number().optional(), + "2xl": external_exports.number().optional() +}).describe("Display order per breakpoint"); +var ResponsiveConfigSchema3 = external_exports.object({ + /** Minimum breakpoint for visibility */ + breakpoint: BreakpointName3.optional().describe("Minimum breakpoint for visibility"), + /** Hide on specific breakpoints */ + hiddenOn: external_exports.array(BreakpointName3).optional().describe("Hide on these breakpoints"), + /** Grid columns per breakpoint (1-12 column grid) */ + columns: BreakpointColumnMapSchema3.optional().describe("Grid columns per breakpoint"), + /** Display order per breakpoint */ + order: BreakpointOrderMapSchema3.optional().describe("Display order per breakpoint") +}).describe("Responsive layout configuration"); +var PerformanceConfigSchema3 = external_exports.object({ + /** Enable lazy loading for this component */ + lazyLoad: external_exports.boolean().optional().describe("Enable lazy loading (defer rendering until visible)"), + /** Virtual scrolling configuration for large datasets */ + virtualScroll: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable virtual scrolling"), + itemHeight: external_exports.number().optional().describe("Fixed item height in pixels (for estimation)"), + overscan: external_exports.number().optional().describe("Number of extra items to render outside viewport") + }).optional().describe("Virtual scrolling configuration"), + /** Client-side caching strategy */ + cacheStrategy: external_exports.enum([ + "none", + "cache-first", + "network-first", + "stale-while-revalidate" + ]).optional().describe("Client-side data caching strategy"), + /** Enable data prefetching */ + prefetch: external_exports.boolean().optional().describe("Prefetch data before component is visible"), + /** Maximum number of items to render before pagination */ + pageSize: external_exports.number().optional().describe("Number of items per page for pagination"), + /** Debounce interval for user interactions (ms) */ + debounceMs: external_exports.number().optional().describe("Debounce interval for user interactions in milliseconds") +}).describe("Performance optimization configuration"); +var SharingConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable public sharing"), + publicLink: external_exports.string().optional().describe("Generated public share URL"), + password: external_exports.string().optional().describe("Password required to access shared link"), + allowedDomains: external_exports.array(external_exports.string()).optional().describe('Restrict access to specific email domains (e.g. ["example.com"])'), + expiresAt: external_exports.string().optional().describe("Expiration date/time in ISO 8601 format"), + allowAnonymous: external_exports.boolean().optional().default(false).describe("Allow access without authentication") +}); +var EmbedConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable iframe embedding"), + allowedOrigins: external_exports.array(external_exports.string()).optional().describe('Allowed iframe parent origins (e.g. ["https://example.com"])'), + width: external_exports.string().optional().default("100%").describe("Embed width (CSS value)"), + height: external_exports.string().optional().default("600px").describe("Embed height (CSS value)"), + showHeader: external_exports.boolean().optional().default(true).describe("Show interface header in embed"), + showNavigation: external_exports.boolean().optional().default(false).describe("Show navigation in embed"), + responsive: external_exports.boolean().optional().default(true).describe("Enable responsive resizing") +}); +var BaseNavItemSchema3 = external_exports.object({ + /** Unique identifier for the item */ + id: SnakeCaseIdentifierSchema7.describe("Unique identifier for this navigation item (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema5.describe("Display proper label"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Icon name"), + /** Sort order within the same level (lower numbers appear first) */ + order: external_exports.number().optional().describe("Sort order within the same level (lower = first)"), + /** Badge text or count displayed on the navigation item (e.g. "3", "New") */ + badge: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("Badge text or count displayed on the item"), + /** + * Visibility condition. + * Formula expression returning boolean. + * e.g. "user.is_admin || user.department == 'sales'" + */ + visible: external_exports.string().optional().describe("Visibility formula condition"), + /** Permissions required to see/access this navigation item */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this item") +}); +var ObjectNavItemSchema3 = BaseNavItemSchema3.extend({ + type: external_exports.literal("object"), + objectName: external_exports.string().describe("Target object name"), + viewName: external_exports.string().optional().describe('Default list view to open. Defaults to "all"') +}); +var DashboardNavItemSchema3 = BaseNavItemSchema3.extend({ + type: external_exports.literal("dashboard"), + dashboardName: external_exports.string().describe("Target dashboard name") +}); +var PageNavItemSchema3 = BaseNavItemSchema3.extend({ + type: external_exports.literal("page"), + pageName: external_exports.string().describe("Target custom page component name"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the page context") +}); +var UrlNavItemSchema3 = BaseNavItemSchema3.extend({ + type: external_exports.literal("url"), + url: external_exports.string().describe("Target external URL"), + target: external_exports.enum(["_self", "_blank"]).default("_self").describe("Link target window") +}); +var ReportNavItemSchema3 = BaseNavItemSchema3.extend({ + type: external_exports.literal("report"), + reportName: external_exports.string().describe("Target report name") +}); +var ActionNavItemSchema3 = BaseNavItemSchema3.extend({ + type: external_exports.literal("action"), + actionDef: external_exports.object({ + actionName: external_exports.string().describe("Action machine name to execute"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the action") + }).describe("Action definition to execute when clicked") +}); +var GroupNavItemSchema3 = BaseNavItemSchema3.extend({ + type: external_exports.literal("group"), + expanded: external_exports.boolean().default(false).describe("Default expansion state in sidebar") + // children property is added in the recursive definition below +}); +var NavigationItemSchema3 = external_exports.lazy( + () => external_exports.union([ + ObjectNavItemSchema3.extend({ + children: external_exports.array(NavigationItemSchema3).optional().describe("Child navigation items (e.g. specific views)") + }), + DashboardNavItemSchema3, + PageNavItemSchema3, + UrlNavItemSchema3, + ReportNavItemSchema3, + ActionNavItemSchema3, + GroupNavItemSchema3.extend({ + children: external_exports.array(NavigationItemSchema3).describe("Child navigation items") + }) + ]) +); +var AppBrandingSchema3 = external_exports.object({ + primaryColor: external_exports.string().optional().describe("Primary theme color hex code"), + logo: external_exports.string().optional().describe("Custom logo URL for this app"), + favicon: external_exports.string().optional().describe("Custom favicon URL for this app") +}); +var NavigationAreaSchema3 = external_exports.object({ + /** Unique area identifier */ + id: SnakeCaseIdentifierSchema7.describe("Unique area identifier (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema5.describe("Area display label"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("Area icon name"), + /** Sort order among areas (lower = first) */ + order: external_exports.number().optional().describe("Sort order among areas (lower = first)"), + /** Area description */ + description: I18nLabelSchema5.optional().describe("Area description"), + /** + * Visibility condition. + * Formula expression returning boolean. + */ + visible: external_exports.string().optional().describe("Visibility formula condition for this area"), + /** Permissions required to access this area */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this area"), + /** Navigation items within this area */ + navigation: external_exports.array(NavigationItemSchema3).describe("Navigation items within this area") +}); +var AppSchema3 = external_exports.object({ + /** Machine name (id) */ + name: SnakeCaseIdentifierSchema7.describe("App unique machine name (lowercase snake_case)"), + /** Display label */ + label: I18nLabelSchema5.describe("App display label"), + /** App version */ + version: external_exports.string().optional().describe("App version"), + /** Description */ + description: I18nLabelSchema5.optional().describe("App description"), + /** Icon name (Lucide) */ + icon: external_exports.string().optional().describe("App icon used in the App Launcher"), + /** Branding/Theming Configuration */ + branding: AppBrandingSchema3.optional().describe("App-specific branding"), + /** Application status */ + active: external_exports.boolean().optional().default(true).describe("Whether the app is enabled"), + /** Is this the default app for new users? */ + isDefault: external_exports.boolean().optional().default(false).describe("Is default app"), + /** + * Full Navigation Tree — supports unlimited nesting depth. + * Pages are referenced by name via `type: 'page'` items. + * Groups can contain other groups for arbitrary sidebar depth. + * + * For simple apps, use `navigation` directly. + * For enterprise apps with multiple business domains, use `areas` instead. + */ + navigation: external_exports.array(NavigationItemSchema3).optional().describe("Full navigation tree for the app sidebar"), + /** + * Navigation Areas — partitions navigation by business domain. + * Each area defines an independent navigation tree (e.g. Sales, Service, Settings). + * When areas are defined, they take precedence over the top-level `navigation` array. + * + * @example + * ```ts + * areas: [ + * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] }, + * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] }, + * ] + * ``` + */ + areas: external_exports.array(NavigationAreaSchema3).optional().describe("Navigation areas for partitioning navigation by business domain"), + /** + * App-level Home Page Override + * ID of the navigation item to act as the landing page. + * If not set, usually defaults to the first navigation item. + */ + homePageId: external_exports.string().optional().describe("ID of the navigation item to serve as landing page"), + /** + * Access Control + * List of permissions required to access this app. + * Modern replacement for role/profile based assignment. + * Example: ["app.access.crm"] + */ + requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this app"), + /** + * Package Components (For config file convenience) + * In a real monorepo these might be auto-discovered, but here we allow explicit registration. + */ + objects: external_exports.array(external_exports.unknown()).optional().describe("Objects belonging to this app"), + apis: external_exports.array(external_exports.unknown()).optional().describe("Custom APIs belonging to this app"), + /** Sharing configuration for public access */ + sharing: SharingConfigSchema3.optional().describe("Public sharing configuration"), + /** Embed configuration for iframe embedding */ + embed: EmbedConfigSchema3.optional().describe("Iframe embedding configuration"), + /** Mobile navigation mode */ + mobileNavigation: external_exports.object({ + mode: external_exports.enum(["drawer", "bottom_nav", "hamburger"]).default("drawer").describe("Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu"), + bottomNavItems: external_exports.array(external_exports.string()).optional().describe("Navigation item IDs to show in bottom nav (max 5)") + }).optional().describe("Mobile-specific navigation configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes for the application") +}); +var App2 = { + create: (config4) => AppSchema3.parse(config4) +}; +function defineApp2(config4) { + return AppSchema3.parse(config4); +} +var ViewDataSchema3 = external_exports.discriminatedUnion("provider", [ + external_exports.object({ + provider: external_exports.literal("object"), + object: external_exports.string().describe("Target object name") + }), + external_exports.object({ + provider: external_exports.literal("api"), + read: HttpRequestSchema4.optional().describe("Configuration for fetching data"), + write: HttpRequestSchema4.optional().describe("Configuration for submitting data (for forms/editable tables)") + }), + external_exports.object({ + provider: external_exports.literal("value"), + items: external_exports.array(external_exports.unknown()).describe("Static data array") + }) +]); +var ViewFilterRuleSchema3 = external_exports.object({ + /** Field name to filter on */ + field: external_exports.string().describe("Field name to filter on"), + /** Filter operator */ + operator: external_exports.string().describe("Filter operator (e.g. equals, not_equals, contains, this_quarter)"), + /** Filter value (optional for unary operators like is_null, this_quarter) */ + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Filter value") +}).describe("View filter rule"); +var ColumnSummarySchema3 = external_exports.enum([ + "none", + "count", + "count_empty", + "count_filled", + "count_unique", + "percent_empty", + "percent_filled", + "sum", + "avg", + "min", + "max" +]).describe("Aggregation function for column footer summary"); +var ListColumnSchema3 = external_exports.object({ + field: external_exports.string().describe("Field name (snake_case)"), + label: I18nLabelSchema5.optional().describe("Display label override"), + width: external_exports.number().positive().optional().describe("Column width in pixels"), + align: external_exports.enum(["left", "center", "right"]).optional().describe("Text alignment"), + hidden: external_exports.boolean().optional().describe("Hide column by default"), + sortable: external_exports.boolean().optional().describe("Allow sorting by this column"), + resizable: external_exports.boolean().optional().describe("Allow resizing this column"), + wrap: external_exports.boolean().optional().describe("Allow text wrapping"), + type: external_exports.string().optional().describe('Renderer type override (e.g., "currency", "date")'), + /** Pinning (Airtable-style frozen columns) */ + pinned: external_exports.enum(["left", "right"]).optional().describe("Pin/freeze column to left or right side"), + /** Column Footer Summary (Airtable-style aggregation) */ + summary: ColumnSummarySchema3.optional().describe("Footer aggregation function for this column"), + /** Interaction */ + link: external_exports.boolean().optional().describe("Functions as the primary navigation link (triggers View navigation)"), + action: external_exports.string().optional().describe("Registered Action ID to execute when clicked") +}); +var SelectionConfigSchema3 = external_exports.object({ + type: external_exports.enum(["none", "single", "multiple"]).default("none").describe("Selection mode") +}); +var PaginationConfigSchema3 = external_exports.object({ + pageSize: external_exports.number().int().positive().default(25).describe("Number of records per page"), + pageSizeOptions: external_exports.array(external_exports.number().int().positive()).optional().describe("Available page size options") +}); +var RowHeightSchema3 = external_exports.enum([ + "compact", + // Minimal padding, single line + "short", + // Reduced padding + "medium", + // Default padding + "tall", + // Extra padding, multi-line preview + "extra_tall" + // Maximum padding, rich content preview +]).describe("Row height / density setting for list view"); +var GroupingFieldSchema3 = external_exports.object({ + field: external_exports.string().describe("Field name to group by"), + order: external_exports.enum(["asc", "desc"]).default("asc").describe("Group sort order"), + collapsed: external_exports.boolean().default(false).describe("Collapse groups by default") +}); +var GroupingConfigSchema3 = external_exports.object({ + fields: external_exports.array(GroupingFieldSchema3).min(1).describe("Fields to group by (supports up to 3 levels)") +}).describe("Record grouping configuration"); +var GalleryConfigSchema3 = external_exports.object({ + coverField: external_exports.string().optional().describe("Attachment/image field to display as card cover"), + coverFit: external_exports.enum(["cover", "contain"]).default("cover").describe("Image fit mode for card cover"), + cardSize: external_exports.enum(["small", "medium", "large"]).default("medium").describe("Card size in gallery view"), + titleField: external_exports.string().optional().describe("Field to display as card title"), + visibleFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on card body") +}).describe("Gallery/card view configuration"); +var TimelineConfigSchema3 = external_exports.object({ + startDateField: external_exports.string().describe("Field for timeline item start date"), + endDateField: external_exports.string().optional().describe("Field for timeline item end date"), + titleField: external_exports.string().describe("Field to display as timeline item title"), + groupByField: external_exports.string().optional().describe("Field to group timeline rows"), + colorField: external_exports.string().optional().describe("Field to determine item color"), + scale: external_exports.enum(["hour", "day", "week", "month", "quarter", "year"]).default("week").describe("Default timeline scale") +}).describe("Timeline view configuration"); +var ViewSharingSchema3 = external_exports.object({ + type: external_exports.enum(["personal", "collaborative"]).default("collaborative").describe("View ownership type"), + lockedBy: external_exports.string().optional().describe("User who locked the view configuration") +}).describe("View sharing and access configuration"); +var RowColorConfigSchema3 = external_exports.object({ + field: external_exports.string().describe("Field to derive color from (typically a select/status field)"), + colors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Map of field value to color (hex/token)") +}).describe("Row color configuration based on field values"); +var VisualizationTypeSchema3 = external_exports.enum([ + "grid", + "kanban", + "gallery", + "calendar", + "timeline", + "gantt", + "map" +]).describe("Visualization type that users can switch to"); +var UserActionsConfigSchema3 = external_exports.object({ + sort: external_exports.boolean().default(true).describe("Allow users to sort records"), + search: external_exports.boolean().default(true).describe("Allow users to search records"), + filter: external_exports.boolean().default(true).describe("Allow users to filter records"), + rowHeight: external_exports.boolean().default(true).describe("Allow users to toggle row height/density"), + addRecordForm: external_exports.boolean().default(false).describe("Add records through a form instead of inline"), + buttons: external_exports.array(external_exports.string()).optional().describe("Custom action button IDs to show in the toolbar") +}).describe("User action toggles for the view toolbar"); +var AppearanceConfigSchema3 = external_exports.object({ + showDescription: external_exports.boolean().default(true).describe("Show the view description text"), + allowedVisualizations: external_exports.array(VisualizationTypeSchema3).optional().describe('Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])') +}).describe("Appearance and visualization configuration"); +var ViewTabSchema3 = external_exports.object({ + name: SnakeCaseIdentifierSchema7.describe("Tab identifier (snake_case)"), + label: I18nLabelSchema5.optional().describe("Display label"), + icon: external_exports.string().optional().describe("Tab icon name"), + view: external_exports.string().optional().describe("Referenced list view name from listViews"), + filter: external_exports.array(ViewFilterRuleSchema3).optional().describe("Tab-specific filter criteria"), + order: external_exports.number().int().min(0).optional().describe("Tab display order"), + pinned: external_exports.boolean().default(false).describe("Pin tab (cannot be removed by users)"), + isDefault: external_exports.boolean().default(false).describe("Set as the default active tab"), + visible: external_exports.boolean().default(true).describe("Tab visibility") +}).describe("Tab configuration for multi-tab view interface"); +var AddRecordConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Show the add record entry point"), + position: external_exports.enum(["top", "bottom", "both"]).default("bottom").describe("Position of the add record button"), + mode: external_exports.enum(["inline", "form", "modal"]).default("inline").describe("How to add a new record"), + formView: external_exports.string().optional().describe('Named form view to use when mode is "form" or "modal"') +}).describe("Add record entry point configuration"); +var KanbanConfigSchema3 = external_exports.object({ + groupByField: external_exports.string().describe("Field to group columns by (usually status/select)"), + summarizeField: external_exports.string().optional().describe("Field to sum at top of column (e.g. amount)"), + columns: external_exports.array(external_exports.string()).describe("Fields to show on cards") +}); +var CalendarConfigSchema3 = external_exports.object({ + startDateField: external_exports.string(), + endDateField: external_exports.string().optional(), + titleField: external_exports.string(), + colorField: external_exports.string().optional() +}); +var GanttConfigSchema3 = external_exports.object({ + startDateField: external_exports.string(), + endDateField: external_exports.string(), + titleField: external_exports.string(), + progressField: external_exports.string().optional(), + dependenciesField: external_exports.string().optional() +}); +var NavigationModeSchema3 = external_exports.enum([ + "page", + // Navigate to a new route (default) + "drawer", + // Open details in a side drawer/panel + "modal", + // Open details in a modal dialog + "split", + // Show details side-by-side with the list (master-detail) + "popover", + // Show details in a popover (lightweight) + "new_window", + // Open in new browser tab/window + "none" + // No navigation (read-only list) +]); +var NavigationConfigSchema3 = external_exports.object({ + mode: NavigationModeSchema3.default("page"), + /** Target View Config */ + view: external_exports.string().optional().describe('Name of the form view to use for details (e.g. "summary_view", "edit_form")'), + /** Interaction Triggers */ + preventNavigation: external_exports.boolean().default(false).describe("Disable standard navigation entirely"), + openNewTab: external_exports.boolean().default(false).describe("Force open in new tab (applies to page mode)"), + /** Dimensions (for modal/drawer) */ + width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Width of the drawer/modal (e.g. "600px", "50%")') +}); +var ListViewSchema3 = external_exports.object({ + name: SnakeCaseIdentifierSchema7.optional().describe("Internal view name (lowercase snake_case)"), + label: I18nLabelSchema5.optional(), + // Display label override (supports i18n) + type: external_exports.enum([ + "grid", + // Standard Data Table + "kanban", + // Board / Columns + "gallery", + // Card Deck / Masonry + "calendar", + // Monthly/Weekly/Daily + "timeline", + // Chronological Stream (Feed) + "gantt", + // Project Timeline + "map" + // Geospatial + ]).default("grid"), + /** Data Source Configuration */ + data: ViewDataSchema3.optional().describe('Data source configuration (defaults to "object" provider)'), + /** Shared Query Config */ + columns: external_exports.union([ + external_exports.array(external_exports.string()), + // Legacy: simple field names + external_exports.array(ListColumnSchema3) + // Enhanced: detailed column config + ]).describe("Fields to display as columns"), + filter: external_exports.array(ViewFilterRuleSchema3).optional().describe("Filter criteria (JSON Rules)"), + sort: external_exports.union([ + external_exports.string(), + //Legacy "field desc" + external_exports.array(external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]) + })) + ]).optional(), + /** Search & Filter */ + searchableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for search"), + filterableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for end-user filtering in the top bar"), + /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */ + quickFilters: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name to filter by"), + label: external_exports.string().optional().describe("Display label for the chip"), + operator: external_exports.enum(["equals", "not_equals", "contains", "in", "is_null", "is_not_null"]).default("equals").describe("Filter operator"), + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Preset filter value") + })).optional().describe("One-click filter chips for quick record filtering"), + /** Grid Features */ + resizable: external_exports.boolean().optional().describe("Enable column resizing"), + striped: external_exports.boolean().optional().describe("Striped row styling"), + bordered: external_exports.boolean().optional().describe("Show borders"), + /** Selection */ + selection: SelectionConfigSchema3.optional().describe("Row selection configuration"), + /** Navigation / Interaction */ + navigation: NavigationConfigSchema3.optional().describe("Configuration for item click navigation (page, drawer, modal, etc.)"), + /** Pagination */ + pagination: PaginationConfigSchema3.optional().describe("Pagination configuration"), + /** Type Specific Config */ + kanban: KanbanConfigSchema3.optional(), + calendar: CalendarConfigSchema3.optional(), + gantt: GanttConfigSchema3.optional(), + gallery: GalleryConfigSchema3.optional(), + timeline: TimelineConfigSchema3.optional(), + /** View Metadata (Airtable-style view management) */ + description: I18nLabelSchema5.optional().describe("View description for documentation/tooltips"), + sharing: ViewSharingSchema3.optional().describe("View sharing and access configuration"), + /** Row Height / Density (Airtable-style) */ + rowHeight: RowHeightSchema3.optional().describe("Row height / density setting"), + /** Record Grouping (Airtable-style) */ + grouping: GroupingConfigSchema3.optional().describe("Group records by one or more fields"), + /** Row Color (Airtable-style) */ + rowColor: RowColorConfigSchema3.optional().describe("Color rows based on field value"), + /** Field Visibility & Ordering per View (Airtable-style) */ + hiddenFields: external_exports.array(external_exports.string()).optional().describe("Fields to hide in this specific view"), + fieldOrder: external_exports.array(external_exports.string()).optional().describe("Explicit field display order for this view"), + /** Row & Bulk Actions */ + rowActions: external_exports.array(external_exports.string()).optional().describe("Actions available for individual row items"), + bulkActions: external_exports.array(external_exports.string()).optional().describe("Actions available when multiple rows are selected"), + /** Performance */ + virtualScroll: external_exports.boolean().optional().describe("Enable virtual scrolling for large datasets"), + /** Conditional Formatting */ + conditionalFormatting: external_exports.array(external_exports.object({ + condition: external_exports.string().describe("Condition expression to evaluate"), + style: external_exports.record(external_exports.string(), external_exports.string()).describe("CSS styles to apply when condition is true") + })).optional().describe("Conditional formatting rules for list rows"), + /** Inline Edit */ + inlineEdit: external_exports.boolean().optional().describe("Allow inline editing of records directly in the list view"), + /** Export */ + exportOptions: external_exports.array(external_exports.enum(["csv", "xlsx", "pdf", "json"])).optional().describe("Available export format options"), + /** User Actions (Airtable Interface parity) */ + userActions: UserActionsConfigSchema3.optional().describe("User action toggles for the view toolbar"), + /** Appearance (Airtable Interface parity) */ + appearance: AppearanceConfigSchema3.optional().describe("Appearance and visualization configuration"), + /** Tabs (Airtable Interface parity) */ + tabs: external_exports.array(ViewTabSchema3).optional().describe("Tab definitions for multi-tab view interface"), + /** Add Record (Airtable Interface parity) */ + addRecord: AddRecordConfigSchema3.optional().describe("Add record entry point configuration"), + /** Record Count Display (Airtable Interface parity) */ + showRecordCount: external_exports.boolean().optional().describe("Show record count at the bottom of the list"), + /** Advanced: Allow Printing (Airtable Interface parity) */ + allowPrinting: external_exports.boolean().optional().describe("Allow users to print the view"), + /** Empty State */ + emptyState: external_exports.object({ + title: I18nLabelSchema5.optional(), + message: I18nLabelSchema5.optional(), + icon: external_exports.string().optional() + }).optional().describe("Empty state configuration when no records found"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes for the list view"), + /** Responsive layout overrides per breakpoint */ + responsive: ResponsiveConfigSchema3.optional().describe("Responsive layout configuration"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema3.optional().describe("Performance optimization settings") +}); +var FormFieldSchema3 = external_exports.object({ + field: external_exports.string().describe("Field name (snake_case)"), + label: I18nLabelSchema5.optional().describe("Display label override"), + placeholder: I18nLabelSchema5.optional().describe("Placeholder text"), + helpText: I18nLabelSchema5.optional().describe("Help/hint text"), + readonly: external_exports.boolean().optional().describe("Read-only override"), + required: external_exports.boolean().optional().describe("Required override"), + hidden: external_exports.boolean().optional().describe("Hidden override"), + colSpan: external_exports.number().int().min(1).max(4).optional().describe("Column span in grid layout (1-4)"), + widget: external_exports.string().optional().describe("Custom widget/component name"), + dependsOn: external_exports.string().optional().describe("Parent field name for cascading"), + visibleOn: external_exports.string().optional().describe("Visibility condition expression") +}); +var FormSectionSchema3 = external_exports.object({ + label: I18nLabelSchema5.optional(), + collapsible: external_exports.boolean().default(false), + collapsed: external_exports.boolean().default(false), + columns: external_exports.enum(["1", "2", "3", "4"]).default("2").transform((val) => parseInt(val)), + fields: external_exports.array(external_exports.union([ + external_exports.string(), + // Legacy: simple field name + FormFieldSchema3 + // Enhanced: detailed field config + ])) +}); +var FormViewSchema3 = external_exports.object({ + type: external_exports.enum([ + "simple", + // Single column or sections + "tabbed", + // Tabs + "wizard", + // Step by step + "split", + // Master-Detail split + "drawer", + // Side panel + "modal" + // Dialog + ]).default("simple"), + /** Data Source Configuration */ + data: ViewDataSchema3.optional().describe('Data source configuration (defaults to "object" provider)'), + sections: external_exports.array(FormSectionSchema3).optional(), + // For simple layout + groups: external_exports.array(FormSectionSchema3).optional(), + // Legacy support -> alias to sections + /** Default Sort for Related Lists (e.g., sort child records by date) */ + defaultSort: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + order: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction") + })).optional().describe("Default sort order for related list views within this form"), + /** Public form sharing configuration */ + sharing: SharingConfigSchema3.optional().describe("Public sharing configuration for this form"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes for the form view") +}); +var ViewSchema3 = external_exports.object({ + list: ListViewSchema3.optional(), + // Default list view + form: FormViewSchema3.optional(), + // Default form view + listViews: external_exports.record(external_exports.string(), ListViewSchema3).optional().describe("Additional named list views"), + formViews: external_exports.record(external_exports.string(), FormViewSchema3).optional().describe("Additional named form views") +}); +function defineView(config4) { + return ViewSchema3.parse(config4); +} +var WidgetColorVariantSchema2 = external_exports.enum([ + "default", + "blue", + "teal", + "orange", + "purple", + "success", + "warning", + "danger" +]).describe("Widget color variant"); +var WidgetActionTypeSchema2 = external_exports.enum([ + "script", + "url", + "modal", + "flow", + "api" +]).describe("Widget action type"); +var DashboardHeaderActionSchema2 = external_exports.object({ + /** Action label */ + label: I18nLabelSchema5.describe("Action button label"), + /** Action URL or target */ + actionUrl: external_exports.string().describe("URL or target for the action"), + /** Action type */ + actionType: WidgetActionTypeSchema2.optional().describe("Type of action"), + /** Icon identifier */ + icon: external_exports.string().optional().describe("Icon identifier for the action button") +}).describe("Dashboard header action"); +var DashboardHeaderSchema2 = external_exports.object({ + /** Whether to show the dashboard title in the header */ + showTitle: external_exports.boolean().default(true).describe("Show dashboard title in header"), + /** Whether to show the dashboard description in the header */ + showDescription: external_exports.boolean().default(true).describe("Show dashboard description in header"), + /** Action buttons displayed in the header */ + actions: external_exports.array(DashboardHeaderActionSchema2).optional().describe("Header action buttons") +}).describe("Dashboard header configuration"); +var WidgetMeasureSchema2 = external_exports.object({ + /** Value field to aggregate */ + valueField: external_exports.string().describe("Field to aggregate"), + /** Aggregate function */ + aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).default("count").describe("Aggregate function"), + /** Display label for the measure */ + label: I18nLabelSchema5.optional().describe("Measure display label"), + /** Number format string (e.g., "$0,0.00", "0.0%") */ + format: external_exports.string().optional().describe("Number format string") +}).describe("Widget measure definition"); +var DashboardWidgetSchema2 = external_exports.object({ + /** Unique widget identifier (snake_case, used for targetWidgets references) */ + id: SnakeCaseIdentifierSchema7.describe("Unique widget identifier (snake_case)"), + /** Widget Title */ + title: I18nLabelSchema5.optional().describe("Widget title"), + /** Widget Description (displayed below the title) */ + description: I18nLabelSchema5.optional().describe("Widget description text below the header"), + /** Visualization Type */ + type: ChartTypeSchema2.default("metric").describe("Visualization type"), + /** Chart Configuration */ + chartConfig: ChartConfigSchema2.optional().describe("Chart visualization configuration"), + /** Color variant for the widget (e.g., KPI card accent color) */ + colorVariant: WidgetColorVariantSchema2.optional().describe("Widget color variant for theming"), + /** Action URL for the widget header action button */ + actionUrl: external_exports.string().optional().describe("URL or target for the widget action button"), + /** Action type for the widget header action button */ + actionType: WidgetActionTypeSchema2.optional().describe("Type of action for the widget action button"), + /** Icon for the widget header action button */ + actionIcon: external_exports.string().optional().describe("Icon identifier for the widget action button"), + /** Data Source Object */ + object: external_exports.string().optional().describe("Data source object name"), + /** Data Filter (MongoDB-style FilterCondition) */ + filter: FilterConditionSchema4.optional().describe("Data filter criteria"), + /** Category Field (X-Axis / Group By) */ + categoryField: external_exports.string().optional().describe("Field for grouping (X-Axis)"), + /** Value Field (Y-Axis) */ + valueField: external_exports.string().optional().describe("Field for values (Y-Axis)"), + /** Aggregate operation */ + aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).optional().default("count").describe("Aggregate function"), + /** Multi-measure definitions for pivot/matrix widgets */ + measures: external_exports.array(WidgetMeasureSchema2).optional().describe("Multiple measures for pivot/matrix analysis"), + /** + * Layout Position (React-Grid-Layout style) + * x: column (0-11) + * y: row + * w: width (1-12) + * h: height + */ + layout: external_exports.object({ + x: external_exports.number(), + y: external_exports.number(), + w: external_exports.number(), + h: external_exports.number() + }).describe("Grid layout position"), + /** Widget specific options (colors, legend, etc.) */ + options: external_exports.unknown().optional().describe("Widget specific configuration"), + /** Responsive layout overrides per breakpoint */ + responsive: ResponsiveConfigSchema3.optional().describe("Responsive layout configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var GlobalFilterOptionsFromSchema2 = external_exports.object({ + /** Source object name to fetch options from */ + object: external_exports.string().describe("Source object name"), + /** Field to use as option value */ + valueField: external_exports.string().describe("Field to use as option value"), + /** Field to use as option label */ + labelField: external_exports.string().describe("Field to use as option label"), + /** Optional filter to apply when fetching options */ + filter: FilterConditionSchema4.optional().describe("Filter to apply to source object") +}).describe("Dynamic filter options from object"); +var GlobalFilterSchema2 = external_exports.object({ + /** Field name to filter on */ + field: external_exports.string().describe("Field name to filter on"), + /** Display label for the filter */ + label: I18nLabelSchema5.optional().describe("Display label for the filter"), + /** Filter input type */ + type: external_exports.enum(["text", "select", "date", "number", "lookup"]).optional().describe("Filter input type"), + /** Static options for select/lookup filters */ + options: external_exports.array(external_exports.object({ + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).describe("Option value"), + label: I18nLabelSchema5 + })).optional().describe("Static filter options"), + /** Dynamic data binding for filter options */ + optionsFrom: GlobalFilterOptionsFromSchema2.optional().describe("Dynamic filter options from object"), + /** Default filter value */ + defaultValue: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Default filter value"), + /** Filter application scope */ + scope: external_exports.enum(["dashboard", "widget"]).default("dashboard").describe("Filter application scope"), + /** Widget IDs to apply this filter to (when scope is widget) */ + targetWidgets: external_exports.array(external_exports.string()).optional().describe("Widget IDs to apply this filter to") +}); +var DashboardSchema2 = external_exports.object({ + /** Machine name */ + name: SnakeCaseIdentifierSchema7.describe("Dashboard unique name"), + /** Display label */ + label: I18nLabelSchema5.describe("Dashboard label"), + /** Description */ + description: I18nLabelSchema5.optional().describe("Dashboard description"), + /** Structured header configuration */ + header: DashboardHeaderSchema2.optional().describe("Dashboard header configuration"), + /** Collection of widgets */ + widgets: external_exports.array(DashboardWidgetSchema2).describe("Widgets to display"), + /** Auto-refresh */ + refreshInterval: external_exports.number().optional().describe("Auto-refresh interval in seconds"), + /** Dashboard Date Range (Global time filter) */ + dateRange: external_exports.object({ + field: external_exports.string().optional().describe("Default date field name for time-based filtering"), + defaultRange: external_exports.enum(["today", "yesterday", "this_week", "last_week", "this_month", "last_month", "this_quarter", "last_quarter", "this_year", "last_year", "last_7_days", "last_30_days", "last_90_days", "custom"]).default("this_month").describe("Default date range preset"), + allowCustomRange: external_exports.boolean().default(true).describe("Allow users to pick a custom date range") + }).optional().describe("Global dashboard date range filter configuration"), + /** Global Filters */ + globalFilters: external_exports.array(GlobalFilterSchema2).optional().describe("Global filters that apply to all widgets in the dashboard"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema3.optional().describe("Performance optimization settings") +}); +var Dashboard = { + create: (config4) => DashboardSchema2.parse(config4) +}; +var ReportType2 = external_exports.enum([ + "tabular", + // Simple list + "summary", + // Grouped by row + "matrix", + // Grouped by row and column + "joined" + // Joined multiple blocks +]); +var ReportColumnSchema2 = external_exports.object({ + field: external_exports.string().describe("Field name"), + label: I18nLabelSchema5.optional().describe("Override label"), + aggregate: external_exports.enum(["sum", "avg", "max", "min", "count", "unique"]).optional().describe("Aggregation function"), + /** Responsive visibility/priority per breakpoint */ + responsive: ResponsiveConfigSchema3.optional().describe("Responsive visibility for this column") +}); +var ReportGroupingSchema2 = external_exports.object({ + field: external_exports.string().describe("Field to group by"), + sortOrder: external_exports.enum(["asc", "desc"]).default("asc"), + dateGranularity: external_exports.enum(["day", "week", "month", "quarter", "year"]).optional().describe("For date fields") +}); +var ReportChartSchema2 = ChartConfigSchema2.extend({ + /** Report-specific chart configuration */ + xAxis: external_exports.string().describe("Grouping field for X-Axis"), + yAxis: external_exports.string().describe("Summary field for Y-Axis"), + groupBy: external_exports.string().optional().describe("Additional grouping field") +}); +var ReportSchema2 = external_exports.object({ + /** Identity */ + name: SnakeCaseIdentifierSchema7.describe("Report unique name"), + label: I18nLabelSchema5.describe("Report label"), + description: I18nLabelSchema5.optional(), + /** Data Source */ + objectName: external_exports.string().describe("Primary object"), + /** Report Configuration */ + type: ReportType2.default("tabular").describe("Report format type"), + columns: external_exports.array(ReportColumnSchema2).describe("Columns to display"), + /** Grouping (for Summary/Matrix) */ + groupingsDown: external_exports.array(ReportGroupingSchema2).optional().describe("Row groupings"), + groupingsAcross: external_exports.array(ReportGroupingSchema2).optional().describe("Column groupings (Matrix only)"), + /** Filtering (MongoDB-style FilterCondition) */ + filter: FilterConditionSchema4.optional().describe("Filter criteria"), + /** Visualization */ + chart: ReportChartSchema2.optional().describe("Embedded chart configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema3.optional().describe("Performance optimization settings") +}); +var Report = { + create: (config4) => ReportSchema2.parse(config4) +}; +var PageRegionSchema2 = external_exports.object({ + name: external_exports.string().describe('Region name (e.g. "sidebar", "main", "header")'), + width: external_exports.enum(["small", "medium", "large", "full"]).optional(), + components: external_exports.array(external_exports.lazy(() => PageComponentSchema2)).describe("Components in this region") +}); +var PageComponentType2 = external_exports.enum([ + // Structure + "page:header", + "page:footer", + "page:sidebar", + "page:tabs", + "page:accordion", + "page:card", + "page:section", + // Record Context + "record:details", + "record:highlights", + "record:related_list", + "record:activity", + "record:chatter", + "record:path", + // Navigation + "app:launcher", + "nav:menu", + "nav:breadcrumb", + // Utility + "global:search", + "global:notifications", + "user:profile", + // AI + "ai:chat_window", + "ai:suggestion", + // Content Elements (Airtable Interface parity) + "element:text", + "element:number", + "element:image", + "element:divider", + // Interactive Elements (Phase B — Element Library) + "element:button", + "element:filter", + "element:form", + "element:record_picker" +]); +var ElementDataSourceSchema2 = external_exports.object({ + object: external_exports.string().describe("Object to query"), + view: external_exports.string().optional().describe("Named view to apply"), + filter: FilterConditionSchema4.optional().describe("Additional filter criteria"), + sort: external_exports.array(SortItemSchema3).optional().describe("Sort order"), + limit: external_exports.number().int().positive().optional().describe("Max records to display") +}); +var PageComponentSchema2 = external_exports.object({ + /** Definition */ + type: external_exports.union([ + PageComponentType2, + external_exports.string() + ]).describe("Component Type (Standard enum or custom string)"), + id: external_exports.string().optional().describe("Unique instance ID"), + /** Configuration */ + label: I18nLabelSchema5.optional(), + properties: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Component props passed to the widget. See component.zod.ts for schemas."), + /** + * Event Handlers + * Map event names to Action expressions. + * "onClick": "set_variable('userId', $event.id)" + * "onRowSelect": "navigate_to('page_detail', { id: $event.id })" + */ + events: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Event handlers map"), + /** Appearance */ + style: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Inline styles or utility classes"), + className: external_exports.string().optional().describe("CSS class names"), + /** Visibility Rule */ + visibility: external_exports.string().optional().describe("Visibility filter/formula"), + /** Per-element data binding, overrides page-level object context */ + dataSource: ElementDataSourceSchema2.optional().describe("Per-element data binding for multi-object pages"), + /** Responsive layout overrides per breakpoint */ + responsive: ResponsiveConfigSchema3.optional().describe("Responsive layout configuration"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var PageVariableSchema2 = external_exports.object({ + name: external_exports.string().describe("Variable name"), + type: external_exports.enum(["string", "number", "boolean", "object", "array", "record_id"]).default("string"), + defaultValue: external_exports.unknown().optional(), + /** Source element binding (e.g. element:record_picker writes to this variable) */ + source: external_exports.string().optional().describe("Component ID that writes to this variable") +}); +var BlankPageLayoutItemSchema2 = external_exports.object({ + componentId: external_exports.string().describe("Reference to a PageComponent.id in the page"), + x: external_exports.number().int().min(0).describe("Grid column position (0-based)"), + y: external_exports.number().int().min(0).describe("Grid row position (0-based)"), + width: external_exports.number().int().min(1).describe("Width in grid columns"), + height: external_exports.number().int().min(1).describe("Height in grid rows") +}); +var BlankPageLayoutSchema2 = external_exports.object({ + columns: external_exports.number().int().min(1).default(12).describe("Number of grid columns"), + rowHeight: external_exports.number().int().min(1).default(40).describe("Height of each grid row in pixels"), + gap: external_exports.number().int().min(0).default(8).describe("Gap between grid items in pixels"), + items: external_exports.array(BlankPageLayoutItemSchema2).describe("Positioned components on the canvas") +}); +var PageTypeSchema2 = external_exports.enum([ + // Platform page types (Salesforce FlexiPage style) + "record", + // Component-based record layout page with regions + "home", + // Platform-level home/landing page + "app", + // App-level page with navigation context + "utility", + // Floating utility panel (e.g. notes, phone dialer) + // Interface page types (Airtable Interface parity) + "dashboard", + // KPI summary with charts/metrics + "grid", + // Spreadsheet-like data table + "list", + // Record list with quick actions + "gallery", + // Card-based visual browsing + "kanban", + // Status-based board + "calendar", + // Date-based scheduling + "timeline", + // Gantt-like project timeline + "form", + // Data entry form + "record_detail", + // Auto-generated single record field display + "record_review", + // Sequential record review/approval + "overview", + // Interface-level navigation/landing hub + "blank" + // Free-form canvas for custom composition +]).describe("Page type \u2014 platform or interface page types"); +var RecordReviewConfigSchema2 = external_exports.object({ + object: external_exports.string().describe("Target object for review"), + filter: FilterConditionSchema4.optional().describe("Filter criteria for review queue"), + sort: external_exports.array(SortItemSchema3).optional().describe("Sort order for review queue"), + displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on the review page"), + actions: external_exports.array(external_exports.object({ + label: external_exports.string().describe("Action button label"), + type: external_exports.enum(["approve", "reject", "skip", "custom"]).describe("Action type"), + field: external_exports.string().optional().describe("Field to update on action"), + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Value to set on action"), + nextRecord: external_exports.boolean().optional().default(true).describe("Auto-advance to next record after action") + })).describe("Review actions"), + navigation: external_exports.enum(["sequential", "random", "filtered"]).optional().default("sequential").describe("Record navigation mode"), + showProgress: external_exports.boolean().optional().default(true).describe("Show review progress indicator") +}); +var InterfacePageConfigSchema2 = external_exports.object({ + /** Data binding */ + source: external_exports.string().optional().describe("Source object name for the page"), + levels: external_exports.number().int().min(1).optional().describe("Number of hierarchy levels to display"), + filterBy: external_exports.array(ViewFilterRuleSchema3).optional().describe("Page-level filter criteria"), + /** Appearance */ + appearance: AppearanceConfigSchema3.optional().describe("Appearance and visualization configuration"), + /** User filters */ + userFilters: external_exports.object({ + elements: external_exports.array(external_exports.enum(["grid", "gallery", "kanban"])).optional().describe("Visualization element types available in user filter bar"), + tabs: external_exports.array(ViewTabSchema3).optional().describe("User-configurable tabs") + }).optional().describe("User filter configuration"), + /** User actions */ + userActions: UserActionsConfigSchema3.optional().describe("User action toggles"), + /** Add record */ + addRecord: AddRecordConfigSchema3.optional().describe("Add record entry point configuration"), + /** Record count */ + showRecordCount: external_exports.boolean().optional().describe("Show record count at page bottom"), + /** Advanced */ + allowPrinting: external_exports.boolean().optional().describe("Allow users to print the page") +}).describe("Interface-level page configuration (Airtable parity)"); +var PageSchema2 = external_exports.object({ + name: SnakeCaseIdentifierSchema7.describe("Page unique name (lowercase snake_case)"), + label: I18nLabelSchema5, + description: I18nLabelSchema5.optional(), + /** Icon (used in interface navigation) */ + icon: external_exports.string().optional().describe("Page icon name"), + /** Page Type */ + type: PageTypeSchema2.default("record").describe("Page type"), + /** Page State Definitions */ + variables: external_exports.array(PageVariableSchema2).optional().describe("Local page state variables"), + /** Context */ + object: external_exports.string().optional().describe("Bound object (for Record pages)"), + /** Record Review Configuration (only for record_review pages) */ + recordReview: RecordReviewConfigSchema2.optional().describe('Record review configuration (required when type is "record_review")'), + /** Blank Page Layout (only for blank pages) */ + blankLayout: BlankPageLayoutSchema2.optional().describe('Free-form grid layout for blank pages (used when type is "blank")'), + /** Layout Template */ + template: external_exports.string().default("default").describe('Layout template name (e.g. "header-sidebar-main")'), + /** Regions & Content */ + regions: external_exports.array(PageRegionSchema2).describe("Defined regions with components"), + /** Activation */ + isDefault: external_exports.boolean().default(false), + assignedProfiles: external_exports.array(external_exports.string()).optional(), + /** Interface Page Configuration (Airtable Interface parity) */ + interfaceConfig: InterfacePageConfigSchema2.optional().describe("Interface-level page configuration (for Airtable-style interface pages)"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}).superRefine((data, ctx) => { + if (data.type === "record_review" && !data.recordReview) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: ["recordReview"], + message: 'recordReview is required when type is "record_review"' + }); + } + if (data.type === "blank" && !data.blankLayout) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: ["blankLayout"], + message: 'blankLayout is required when type is "blank"' + }); + } +}); +var WidgetLifecycleSchema2 = external_exports.object({ + /** + * Called when widget is mounted/rendered for the first time + * Use for initialization, setting up event listeners, loading data, etc. + * + * @example "initializeDatePicker(); loadOptions();" + */ + onMount: external_exports.string().optional().describe("Initialization code when widget mounts"), + /** + * Called when widget props change + * Receives previous props for comparison + * + * @example "if (prevProps.value !== props.value) { updateDisplay() }" + */ + onUpdate: external_exports.string().optional().describe("Code to run when props change"), + /** + * Called when widget is about to be removed from DOM + * Use for cleanup, removing event listeners, canceling timers, etc. + * + * @example "destroyDatePicker(); cancelPendingRequests();" + */ + onUnmount: external_exports.string().optional().describe("Cleanup code when widget unmounts"), + /** + * Custom validation logic for this widget + * Should return error message string if invalid, null/undefined if valid + * + * @example "return value && value.length >= 10 ? null : 'Minimum 10 characters'" + */ + onValidate: external_exports.string().optional().describe("Custom validation logic"), + /** + * Called when widget receives focus + * + * @example "highlightField(); logFocusEvent();" + */ + onFocus: external_exports.string().optional().describe("Code to run on focus"), + /** + * Called when widget loses focus + * + * @example "validateField(); saveFieldState();" + */ + onBlur: external_exports.string().optional().describe("Code to run on blur"), + /** + * Called on any error in the widget + * + * @example "logError(error); showErrorNotification();" + */ + onError: external_exports.string().optional().describe("Error handling code") +}); +var WidgetEventSchema2 = external_exports.object({ + /** + * Event name + * Should be lowercase, dash-separated for consistency + * + * @example "value-change", "item-selected", "search-complete" + */ + name: external_exports.string().describe("Event name"), + /** + * Event label for documentation + */ + label: I18nLabelSchema5.optional().describe("Human-readable event label"), + /** + * Event description + */ + description: I18nLabelSchema5.optional().describe("Event description and usage"), + /** + * Whether event bubbles up through the DOM hierarchy + * + * @default false + */ + bubbles: external_exports.boolean().default(false).describe("Whether event bubbles"), + /** + * Whether event can be cancelled + * + * @default false + */ + cancelable: external_exports.boolean().default(false).describe("Whether event is cancelable"), + /** + * Event payload schema + * Defines the data structure sent with the event + * + * @example { userId: 'string', timestamp: 'number' } + */ + payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event payload schema") +}); +var WidgetPropertySchema2 = external_exports.object({ + /** + * Property name + * Should be camelCase following ObjectStack conventions + */ + name: external_exports.string().describe("Property name (camelCase)"), + /** + * Property label for UI + */ + label: I18nLabelSchema5.optional().describe("Human-readable label"), + /** + * Property data type + * + * @example "string", "number", "boolean", "array", "object", "function" + */ + type: external_exports.enum(["string", "number", "boolean", "array", "object", "function", "any"]).describe("TypeScript type"), + /** + * Whether property is required + * + * @default false + */ + required: external_exports.boolean().default(false).describe("Whether property is required"), + /** + * Default value for the property + */ + default: external_exports.unknown().optional().describe("Default value"), + /** + * Property description + */ + description: I18nLabelSchema5.optional().describe("Property description"), + /** + * Property validation schema + * Can include min/max, regex, enum values, etc. + */ + validation: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation rules"), + /** + * Property category for grouping in UI + */ + category: external_exports.string().optional().describe("Property category") +}); +var WidgetSourceSchema2 = external_exports.discriminatedUnion("type", [ + // NPM Registry (standard) + external_exports.object({ + type: external_exports.literal("npm"), + packageName: external_exports.string().describe("NPM package name"), + version: external_exports.string().default("latest"), + exportName: external_exports.string().optional().describe("Named export (default: default)") + }), + // Module Federation (Remote) + external_exports.object({ + type: external_exports.literal("remote"), + url: external_exports.string().url().describe("Remote entry URL (.js)"), + moduleName: external_exports.string().describe("Exposed module name"), + scope: external_exports.string().describe("Remote scope name") + }), + // Inline Code (Simple scripts) + external_exports.object({ + type: external_exports.literal("inline"), + code: external_exports.string().describe("JavaScript code body") + }) +]); +var WidgetManifestSchema2 = external_exports.object({ + /** + * Widget identifier (snake_case) + */ + name: SnakeCaseIdentifierSchema7.describe("Widget identifier (snake_case)"), + /** + * Human-readable widget name + */ + label: I18nLabelSchema5.describe("Widget display name"), + /** + * Widget description + */ + description: I18nLabelSchema5.optional().describe("Widget description"), + /** + * Widget version (semver) + */ + version: external_exports.string().optional().describe("Widget version (semver)"), + /** + * Widget author/organization + */ + author: external_exports.string().optional().describe("Widget author"), + /** + * Icon name or URL + */ + icon: external_exports.string().optional().describe("Widget icon"), + /** + * Field types this widget supports + * + * @example ["text", "email", "url"] + */ + fieldTypes: external_exports.array(external_exports.string()).optional().describe("Supported field types"), + /** + * Widget category for organization + */ + category: external_exports.enum(["input", "display", "picker", "editor", "custom"]).default("custom").describe("Widget category"), + /** + * Widget lifecycle hooks + */ + lifecycle: WidgetLifecycleSchema2.optional().describe("Lifecycle hooks"), + /** + * Custom events this widget emits + */ + events: external_exports.array(WidgetEventSchema2).optional().describe("Custom events"), + /** + * Widget configuration properties + */ + properties: external_exports.array(WidgetPropertySchema2).optional().describe("Configuration properties"), + /** + * Widget implementation + * Defines how to load the widget code + */ + implementation: WidgetSourceSchema2.optional().describe("Widget implementation source"), + /** + * Widget dependencies + * External libraries or scripts needed + */ + dependencies: external_exports.array(external_exports.object({ + name: external_exports.string(), + version: external_exports.string().optional(), + url: external_exports.string().url().optional() + })).optional().describe("Widget dependencies"), + /** + * Widget screenshots for showcase + */ + screenshots: external_exports.array(external_exports.string().url()).optional().describe("Screenshot URLs"), + /** + * Widget documentation URL + */ + documentation: external_exports.string().url().optional().describe("Documentation URL"), + /** + * License information + */ + license: external_exports.string().optional().describe("License (SPDX identifier)"), + /** + * Tags for discovery + */ + tags: external_exports.array(external_exports.string()).optional().describe("Tags for categorization"), + /** ARIA accessibility attributes */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes"), + /** Performance optimization settings */ + performance: PerformanceConfigSchema3.optional().describe("Performance optimization settings") +}); +var FieldWidgetPropsSchema2 = external_exports.object({ + /** + * Current field value. + * Type depends on the field type (string, number, boolean, array, object, etc.) + */ + value: external_exports.unknown().describe("Current field value"), + /** + * Callback function to update the field value. + * Should be called when user interaction changes the value. + * + * @param newValue - The new value to set + */ + onChange: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.void()).describe("Callback to update field value"), + /** + * Whether the field is in read-only mode. + * When true, the widget should display the value but not allow editing. + */ + readonly: external_exports.boolean().default(false).describe("Read-only mode flag"), + /** + * Whether the field is required. + * Widget should indicate required state visually and validate accordingly. + */ + required: external_exports.boolean().default(false).describe("Required field flag"), + /** + * Validation error message to display. + * When present, widget should display the error in its UI. + */ + error: external_exports.string().optional().describe("Validation error message"), + /** + * Complete field definition from the schema. + * Contains metadata like type, constraints, options, etc. + */ + field: FieldSchema5.describe("Field schema definition"), + /** + * The complete record/document being edited. + * Useful for conditional logic and cross-field dependencies. + */ + record: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Complete record data"), + /** + * Custom options passed to the widget. + * Can contain widget-specific configuration like themes, behaviors, etc. + */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom widget options") +}); +var EmptyProps2 = external_exports.object({}); +var PageHeaderProps2 = external_exports.object({ + title: I18nLabelSchema5.describe("Page title"), + subtitle: I18nLabelSchema5.optional().describe("Page subtitle"), + icon: external_exports.string().optional().describe("Icon name"), + breadcrumb: external_exports.boolean().default(true).describe("Show breadcrumb"), + actions: external_exports.array(external_exports.string()).optional().describe("Action IDs to show in header"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var PageTabsProps2 = external_exports.object({ + type: external_exports.enum(["line", "card", "pill"]).default("line"), + position: external_exports.enum(["top", "left"]).default("top"), + items: external_exports.array(external_exports.object({ + label: I18nLabelSchema5, + icon: external_exports.string().optional(), + children: external_exports.array(external_exports.unknown()).describe("Child components") + })), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var PageCardProps2 = external_exports.object({ + title: I18nLabelSchema5.optional(), + bordered: external_exports.boolean().default(true), + actions: external_exports.array(external_exports.string()).optional(), + /** Slot for nested content in the Card body */ + body: external_exports.array(external_exports.unknown()).optional().describe("Card content components (slot)"), + /** Slot for footer content */ + footer: external_exports.array(external_exports.unknown()).optional().describe("Card footer components (slot)"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var RecordDetailsProps2 = external_exports.object({ + columns: external_exports.enum(["1", "2", "3", "4"]).default("2").describe("Number of columns for field layout (1-4)"), + layout: external_exports.enum(["auto", "custom"]).default("auto").describe("Layout mode: auto uses object compactLayout, custom uses explicit sections"), + sections: external_exports.array(external_exports.string()).optional().describe('Section IDs to show (required when layout is "custom")'), + fields: external_exports.array(external_exports.string()).optional().describe("Explicit field list to display (optional, overrides compactLayout)"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var RecordRelatedListProps2 = external_exports.object({ + objectName: external_exports.string().describe('Related object name (e.g., "task", "opportunity")'), + relationshipField: external_exports.string().describe('Field on related object that points to this record (e.g., "account_id")'), + columns: external_exports.array(external_exports.string()).describe("Fields to display in the related list"), + sort: external_exports.union([ + external_exports.string(), + external_exports.array(external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]) + })) + ]).optional().describe("Sort order for related records"), + limit: external_exports.number().int().positive().default(5).describe("Number of records to display initially"), + filter: external_exports.array(ViewFilterRuleSchema3).optional().describe("Additional filter criteria for related records"), + title: I18nLabelSchema5.optional().describe("Custom title for the related list"), + showViewAll: external_exports.boolean().default(true).describe('Show "View All" link to see all related records'), + actions: external_exports.array(external_exports.string()).optional().describe("Action IDs available for related records"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var RecordHighlightsProps2 = external_exports.object({ + fields: external_exports.array(external_exports.string()).min(1).max(7).describe("Key fields to highlight (1-7 fields max, typically displayed as prominent cards)"), + layout: external_exports.enum(["horizontal", "vertical"]).default("horizontal").describe("Layout orientation for highlight fields"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var RecordActivityProps2 = external_exports.object({ + /** Activity types to display (unified enum including comment, field_change, etc.) */ + types: external_exports.array(FeedItemType4).optional().describe("Feed item types to show (default: all)"), + /** Default filter mode (Airtable-style dropdown) */ + filterMode: FeedFilterMode3.default("all").describe("Default activity filter"), + /** Allow user to switch filter modes */ + showFilterToggle: external_exports.boolean().default(true).describe("Show filter dropdown in panel header"), + /** Pagination */ + limit: external_exports.number().int().positive().default(20).describe("Number of items to load per page"), + /** Show completed activities */ + showCompleted: external_exports.boolean().default(false).describe("Include completed activities"), + /** Merge field_change + comment in a unified timeline */ + unifiedTimeline: external_exports.boolean().default(true).describe("Mix field changes and comments in one timeline (Airtable style)"), + /** Show the comment input box at the bottom */ + showCommentInput: external_exports.boolean().default(true).describe('Show "Leave a comment" input at the bottom'), + /** Enable @mentions in comments */ + enableMentions: external_exports.boolean().default(true).describe("Enable @mentions in comments"), + /** Enable emoji reactions */ + enableReactions: external_exports.boolean().default(false).describe("Enable emoji reactions on feed items"), + /** Enable threaded replies */ + enableThreading: external_exports.boolean().default(false).describe("Enable threaded replies on comments"), + /** Show notification subscription toggle (bell icon) */ + showSubscriptionToggle: external_exports.boolean().default(true).describe("Show bell icon for record-level notification subscription"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var RecordChatterProps2 = external_exports.object({ + /** Panel position */ + position: external_exports.enum(["sidebar", "inline", "drawer"]).default("sidebar").describe("Where to render the chatter panel"), + /** Panel width (for sidebar/drawer) */ + width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Panel width (e.g., "350px", "30%")'), + /** Collapsible */ + collapsible: external_exports.boolean().default(true).describe("Whether the panel can be collapsed"), + /** Default collapsed state */ + defaultCollapsed: external_exports.boolean().default(false).describe("Whether the panel starts collapsed"), + /** Feed configuration (delegates to RecordActivityProps) */ + feed: RecordActivityProps2.optional().describe("Embedded activity feed configuration"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var RecordPathProps2 = external_exports.object({ + statusField: external_exports.string().describe("Field name representing the current status/stage"), + stages: external_exports.array(external_exports.object({ + value: external_exports.string(), + label: I18nLabelSchema5 + })).optional().describe("Explicit stage definitions (if not using field metadata)"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var PageAccordionProps2 = external_exports.object({ + items: external_exports.array(external_exports.object({ + label: I18nLabelSchema5, + icon: external_exports.string().optional(), + collapsed: external_exports.boolean().default(false), + children: external_exports.array(external_exports.unknown()).describe("Child components") + })), + allowMultiple: external_exports.boolean().default(false).describe("Allow multiple panels to be expanded simultaneously"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var AIChatWindowProps2 = external_exports.object({ + mode: external_exports.enum(["float", "sidebar", "inline"]).default("float").describe("Display mode for the chat window"), + agentId: external_exports.string().optional().describe("Specific AI agent to use"), + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Contextual data to pass to the AI"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var ElementTextPropsSchema2 = external_exports.object({ + content: external_exports.string().describe("Text or Markdown content"), + variant: external_exports.enum(["heading", "subheading", "body", "caption"]).optional().default("body").describe("Text style variant"), + align: external_exports.enum(["left", "center", "right"]).optional().default("left").describe("Text alignment"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var ElementNumberPropsSchema2 = external_exports.object({ + object: external_exports.string().describe("Source object"), + field: external_exports.string().optional().describe("Field to aggregate"), + aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).describe("Aggregation function"), + filter: FilterConditionSchema4.optional().describe("Filter criteria"), + format: external_exports.enum(["number", "currency", "percent"]).optional().describe("Number display format"), + prefix: external_exports.string().optional().describe('Prefix text (e.g. "$")'), + suffix: external_exports.string().optional().describe('Suffix text (e.g. "%")'), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var ElementImagePropsSchema2 = external_exports.object({ + src: external_exports.string().describe("Image URL or attachment field"), + alt: external_exports.string().optional().describe("Alt text for accessibility"), + fit: external_exports.enum(["cover", "contain", "fill"]).optional().default("cover").describe("Image object-fit mode"), + height: external_exports.number().optional().describe("Fixed height in pixels"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var ElementButtonPropsSchema2 = external_exports.object({ + label: I18nLabelSchema5.describe("Button display label"), + variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().default("primary").describe("Button visual variant"), + size: external_exports.enum(["small", "medium", "large"]).optional().default("medium").describe("Button size"), + icon: external_exports.string().optional().describe("Icon name (Lucide icon)"), + iconPosition: external_exports.enum(["left", "right"]).optional().default("left").describe("Icon position relative to label"), + disabled: external_exports.boolean().optional().default(false).describe("Disable the button"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var ElementFilterPropsSchema2 = external_exports.object({ + object: external_exports.string().describe("Object to filter"), + fields: external_exports.array(external_exports.string()).describe("Filterable field names"), + targetVariable: external_exports.string().optional().describe("Page variable to store filter state"), + layout: external_exports.enum(["inline", "dropdown", "sidebar"]).optional().default("inline").describe("Filter display layout"), + showSearch: external_exports.boolean().optional().default(true).describe("Show search input"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var ElementFormPropsSchema2 = external_exports.object({ + object: external_exports.string().describe("Object for the form"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to display (defaults to all editable fields)"), + mode: external_exports.enum(["create", "edit"]).optional().default("create").describe("Form mode"), + submitLabel: I18nLabelSchema5.optional().describe("Submit button label"), + onSubmit: external_exports.string().optional().describe("Action expression on form submit"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var ElementRecordPickerPropsSchema2 = external_exports.object({ + object: external_exports.string().describe("Object to pick records from"), + displayField: external_exports.string().describe("Field to display as the record label"), + searchFields: external_exports.array(external_exports.string()).optional().describe("Fields to search against"), + filter: FilterConditionSchema4.optional().describe("Filter criteria for available records"), + multiple: external_exports.boolean().optional().default(false).describe("Allow multiple record selection"), + targetVariable: external_exports.string().optional().describe("Page variable to bind selected record ID(s)"), + placeholder: I18nLabelSchema5.optional().describe("Placeholder text"), + /** ARIA accessibility */ + aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") +}); +var ComponentPropsMap2 = { + // Structure + "page:header": PageHeaderProps2, + "page:tabs": PageTabsProps2, + "page:card": PageCardProps2, + "page:footer": EmptyProps2, + "page:sidebar": EmptyProps2, + "page:accordion": PageAccordionProps2, + "page:section": EmptyProps2, + // Record + "record:details": RecordDetailsProps2, + "record:related_list": RecordRelatedListProps2, + "record:highlights": RecordHighlightsProps2, + "record:activity": RecordActivityProps2, + "record:chatter": RecordChatterProps2, + "record:path": RecordPathProps2, + // Navigation + "app:launcher": EmptyProps2, + "nav:menu": EmptyProps2, + "nav:breadcrumb": EmptyProps2, + // Utility + "global:search": EmptyProps2, + "global:notifications": EmptyProps2, + "user:profile": EmptyProps2, + // AI + "ai:chat_window": AIChatWindowProps2, + "ai:suggestion": external_exports.object({ context: external_exports.string().optional() }), + // Content Elements + "element:text": ElementTextPropsSchema2, + "element:number": ElementNumberPropsSchema2, + "element:image": ElementImagePropsSchema2, + "element:divider": EmptyProps2, + // Interactive Elements + "element:button": ElementButtonPropsSchema2, + "element:filter": ElementFilterPropsSchema2, + "element:form": ElementFormPropsSchema2, + "element:record_picker": ElementRecordPickerPropsSchema2 +}; +var TouchTargetConfigSchema2 = external_exports.object({ + minWidth: external_exports.number().default(44).describe("Minimum touch target width in pixels (WCAG 2.5.5: 44px)"), + minHeight: external_exports.number().default(44).describe("Minimum touch target height in pixels (WCAG 2.5.5: 44px)"), + padding: external_exports.number().optional().describe("Additional padding around touch target in pixels"), + hitSlop: external_exports.object({ + top: external_exports.number().optional().describe("Extra hit area above the element"), + right: external_exports.number().optional().describe("Extra hit area to the right of the element"), + bottom: external_exports.number().optional().describe("Extra hit area below the element"), + left: external_exports.number().optional().describe("Extra hit area to the left of the element") + }).optional().describe("Invisible hit area extension beyond the visible bounds") +}).describe("Touch target sizing configuration (WCAG accessible)"); +var GestureTypeSchema2 = external_exports.enum([ + "swipe", + "pinch", + "long_press", + "double_tap", + "drag", + "rotate", + "pan" +]).describe("Touch gesture type"); +var SwipeDirectionSchema2 = external_exports.enum(["up", "down", "left", "right"]); +var SwipeGestureConfigSchema2 = external_exports.object({ + direction: external_exports.array(SwipeDirectionSchema2).describe("Allowed swipe directions"), + threshold: external_exports.number().optional().describe("Minimum distance in pixels to recognize swipe"), + velocity: external_exports.number().optional().describe("Minimum velocity (px/ms) to trigger swipe") +}).describe("Swipe gesture recognition settings"); +var PinchGestureConfigSchema2 = external_exports.object({ + minScale: external_exports.number().optional().describe("Minimum scale factor (e.g., 0.5 for 50%)"), + maxScale: external_exports.number().optional().describe("Maximum scale factor (e.g., 3.0 for 300%)") +}).describe("Pinch/zoom gesture recognition settings"); +var LongPressGestureConfigSchema2 = external_exports.object({ + duration: external_exports.number().default(500).describe("Hold duration in milliseconds to trigger long press"), + moveTolerance: external_exports.number().optional().describe("Max movement in pixels allowed during press") +}).describe("Long press gesture recognition settings"); +var GestureConfigSchema2 = external_exports.object({ + type: GestureTypeSchema2.describe("Gesture type to configure"), + label: I18nLabelSchema5.optional().describe("Descriptive label for the gesture action"), + enabled: external_exports.boolean().default(true).describe("Whether this gesture is active"), + swipe: SwipeGestureConfigSchema2.optional().describe("Swipe gesture settings (when type is swipe)"), + pinch: PinchGestureConfigSchema2.optional().describe("Pinch gesture settings (when type is pinch)"), + longPress: LongPressGestureConfigSchema2.optional().describe("Long press settings (when type is long_press)") +}).describe("Per-gesture configuration"); +var TouchInteractionSchema2 = external_exports.object({ + gestures: external_exports.array(GestureConfigSchema2).optional().describe("Configured gesture recognizers"), + touchTarget: TouchTargetConfigSchema2.optional().describe("Touch target sizing and hit area"), + hapticFeedback: external_exports.boolean().optional().describe("Enable haptic feedback on touch interactions") +}).merge(AriaPropsSchema5.partial()).describe("Touch and gesture interaction configuration"); +var FocusTrapConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable focus trapping within this container"), + initialFocus: external_exports.string().optional().describe("CSS selector for the element to focus on activation"), + returnFocus: external_exports.boolean().default(true).describe("Return focus to trigger element on deactivation"), + escapeDeactivates: external_exports.boolean().default(true).describe("Allow Escape key to deactivate the focus trap") +}).describe("Focus trap configuration for modal-like containers"); +var KeyboardShortcutSchema2 = external_exports.object({ + key: external_exports.string().describe('Key combination (e.g., "Ctrl+S", "Alt+N", "Escape")'), + action: external_exports.string().describe("Action identifier to invoke when shortcut is triggered"), + description: I18nLabelSchema5.optional().describe("Human-readable description of what the shortcut does"), + scope: external_exports.enum(["global", "view", "form", "modal", "list"]).default("global").describe("Scope in which this shortcut is active") +}).describe("Keyboard shortcut binding"); +var FocusManagementSchema2 = external_exports.object({ + tabOrder: external_exports.enum(["auto", "manual"]).default("auto").describe("Tab order strategy: auto (DOM order) or manual (explicit tabIndex)"), + skipLinks: external_exports.boolean().default(false).describe("Provide skip-to-content navigation links"), + focusVisible: external_exports.boolean().default(true).describe("Show visible focus indicators for keyboard users"), + focusTrap: FocusTrapConfigSchema2.optional().describe("Focus trap settings"), + arrowNavigation: external_exports.boolean().default(false).describe("Enable arrow key navigation between focusable items") +}).describe("Focus and tab navigation management"); +var KeyboardNavigationConfigSchema2 = external_exports.object({ + shortcuts: external_exports.array(KeyboardShortcutSchema2).optional().describe("Registered keyboard shortcuts"), + focusManagement: FocusManagementSchema2.optional().describe("Focus and tab order management"), + rovingTabindex: external_exports.boolean().default(false).describe("Enable roving tabindex pattern for composite widgets") +}).merge(AriaPropsSchema5.partial()).describe("Keyboard navigation and shortcut configuration"); +var ColorPaletteSchema2 = external_exports.object({ + primary: external_exports.string().describe("Primary brand color (hex, rgb, or hsl)"), + secondary: external_exports.string().optional().describe("Secondary brand color"), + accent: external_exports.string().optional().describe("Accent color for highlights"), + success: external_exports.string().optional().describe("Success state color (default: green)"), + warning: external_exports.string().optional().describe("Warning state color (default: yellow)"), + error: external_exports.string().optional().describe("Error state color (default: red)"), + info: external_exports.string().optional().describe("Info state color (default: blue)"), + // Neutral colors + background: external_exports.string().optional().describe("Background color"), + surface: external_exports.string().optional().describe("Surface/card background color"), + text: external_exports.string().optional().describe("Primary text color"), + textSecondary: external_exports.string().optional().describe("Secondary text color"), + border: external_exports.string().optional().describe("Border color"), + disabled: external_exports.string().optional().describe("Disabled state color"), + // Color variants (shades) + primaryLight: external_exports.string().optional().describe("Lighter shade of primary"), + primaryDark: external_exports.string().optional().describe("Darker shade of primary"), + secondaryLight: external_exports.string().optional().describe("Lighter shade of secondary"), + secondaryDark: external_exports.string().optional().describe("Darker shade of secondary") +}); +var TypographySchema2 = external_exports.object({ + fontFamily: external_exports.object({ + base: external_exports.string().optional().describe("Base font family (default: system fonts)"), + heading: external_exports.string().optional().describe("Heading font family"), + mono: external_exports.string().optional().describe("Monospace font family for code") + }).optional(), + fontSize: external_exports.object({ + xs: external_exports.string().optional().describe("Extra small font size (e.g., 0.75rem)"), + sm: external_exports.string().optional().describe("Small font size (e.g., 0.875rem)"), + base: external_exports.string().optional().describe("Base font size (e.g., 1rem)"), + lg: external_exports.string().optional().describe("Large font size (e.g., 1.125rem)"), + xl: external_exports.string().optional().describe("Extra large font size (e.g., 1.25rem)"), + "2xl": external_exports.string().optional().describe("2X large font size (e.g., 1.5rem)"), + "3xl": external_exports.string().optional().describe("3X large font size (e.g., 1.875rem)"), + "4xl": external_exports.string().optional().describe("4X large font size (e.g., 2.25rem)") + }).optional(), + fontWeight: external_exports.object({ + light: external_exports.number().optional().describe("Light weight (default: 300)"), + normal: external_exports.number().optional().describe("Normal weight (default: 400)"), + medium: external_exports.number().optional().describe("Medium weight (default: 500)"), + semibold: external_exports.number().optional().describe("Semibold weight (default: 600)"), + bold: external_exports.number().optional().describe("Bold weight (default: 700)") + }).optional(), + lineHeight: external_exports.object({ + tight: external_exports.string().optional().describe("Tight line height (e.g., 1.25)"), + normal: external_exports.string().optional().describe("Normal line height (e.g., 1.5)"), + relaxed: external_exports.string().optional().describe("Relaxed line height (e.g., 1.75)"), + loose: external_exports.string().optional().describe("Loose line height (e.g., 2)") + }).optional(), + letterSpacing: external_exports.object({ + tighter: external_exports.string().optional().describe("Tighter letter spacing (e.g., -0.05em)"), + tight: external_exports.string().optional().describe("Tight letter spacing (e.g., -0.025em)"), + normal: external_exports.string().optional().describe("Normal letter spacing (e.g., 0)"), + wide: external_exports.string().optional().describe("Wide letter spacing (e.g., 0.025em)"), + wider: external_exports.string().optional().describe("Wider letter spacing (e.g., 0.05em)") + }).optional() +}); +var SpacingSchema2 = external_exports.object({ + "0": external_exports.string().optional().describe("0 spacing (0)"), + "1": external_exports.string().optional().describe("Spacing unit 1 (e.g., 0.25rem)"), + "2": external_exports.string().optional().describe("Spacing unit 2 (e.g., 0.5rem)"), + "3": external_exports.string().optional().describe("Spacing unit 3 (e.g., 0.75rem)"), + "4": external_exports.string().optional().describe("Spacing unit 4 (e.g., 1rem)"), + "5": external_exports.string().optional().describe("Spacing unit 5 (e.g., 1.25rem)"), + "6": external_exports.string().optional().describe("Spacing unit 6 (e.g., 1.5rem)"), + "8": external_exports.string().optional().describe("Spacing unit 8 (e.g., 2rem)"), + "10": external_exports.string().optional().describe("Spacing unit 10 (e.g., 2.5rem)"), + "12": external_exports.string().optional().describe("Spacing unit 12 (e.g., 3rem)"), + "16": external_exports.string().optional().describe("Spacing unit 16 (e.g., 4rem)"), + "20": external_exports.string().optional().describe("Spacing unit 20 (e.g., 5rem)"), + "24": external_exports.string().optional().describe("Spacing unit 24 (e.g., 6rem)") +}); +var BorderRadiusSchema2 = external_exports.object({ + none: external_exports.string().optional().describe("No border radius (0)"), + sm: external_exports.string().optional().describe("Small border radius (e.g., 0.125rem)"), + base: external_exports.string().optional().describe("Base border radius (e.g., 0.25rem)"), + md: external_exports.string().optional().describe("Medium border radius (e.g., 0.375rem)"), + lg: external_exports.string().optional().describe("Large border radius (e.g., 0.5rem)"), + xl: external_exports.string().optional().describe("Extra large border radius (e.g., 0.75rem)"), + "2xl": external_exports.string().optional().describe("2X large border radius (e.g., 1rem)"), + full: external_exports.string().optional().describe("Full border radius (50%)") +}); +var ShadowSchema2 = external_exports.object({ + none: external_exports.string().optional().describe("No shadow"), + sm: external_exports.string().optional().describe("Small shadow"), + base: external_exports.string().optional().describe("Base shadow"), + md: external_exports.string().optional().describe("Medium shadow"), + lg: external_exports.string().optional().describe("Large shadow"), + xl: external_exports.string().optional().describe("Extra large shadow"), + "2xl": external_exports.string().optional().describe("2X large shadow"), + inner: external_exports.string().optional().describe("Inner shadow (inset)") +}); +var BreakpointsSchema2 = external_exports.object({ + xs: external_exports.string().optional().describe("Extra small breakpoint (e.g., 480px)"), + sm: external_exports.string().optional().describe("Small breakpoint (e.g., 640px)"), + md: external_exports.string().optional().describe("Medium breakpoint (e.g., 768px)"), + lg: external_exports.string().optional().describe("Large breakpoint (e.g., 1024px)"), + xl: external_exports.string().optional().describe("Extra large breakpoint (e.g., 1280px)"), + "2xl": external_exports.string().optional().describe("2X large breakpoint (e.g., 1536px)") +}); +var AnimationSchema2 = external_exports.object({ + duration: external_exports.object({ + fast: external_exports.string().optional().describe("Fast animation (e.g., 150ms)"), + base: external_exports.string().optional().describe("Base animation (e.g., 300ms)"), + slow: external_exports.string().optional().describe("Slow animation (e.g., 500ms)") + }).optional(), + timing: external_exports.object({ + linear: external_exports.string().optional().describe("Linear timing function"), + ease: external_exports.string().optional().describe("Ease timing function"), + ease_in: external_exports.string().optional().describe("Ease-in timing function"), + ease_out: external_exports.string().optional().describe("Ease-out timing function"), + ease_in_out: external_exports.string().optional().describe("Ease-in-out timing function") + }).optional() +}); +var ZIndexSchema2 = external_exports.object({ + base: external_exports.number().optional().describe("Base z-index (e.g., 0)"), + dropdown: external_exports.number().optional().describe("Dropdown z-index (e.g., 1000)"), + sticky: external_exports.number().optional().describe("Sticky z-index (e.g., 1020)"), + fixed: external_exports.number().optional().describe("Fixed z-index (e.g., 1030)"), + modalBackdrop: external_exports.number().optional().describe("Modal backdrop z-index (e.g., 1040)"), + modal: external_exports.number().optional().describe("Modal z-index (e.g., 1050)"), + popover: external_exports.number().optional().describe("Popover z-index (e.g., 1060)"), + tooltip: external_exports.number().optional().describe("Tooltip z-index (e.g., 1070)") +}); +var ThemeModeSchema2 = external_exports.enum(["light", "dark", "auto"]); +var ThemeMode = ThemeModeSchema2; +var DensityModeSchema2 = external_exports.enum(["compact", "regular", "spacious"]); +var DensityMode = DensityModeSchema2; +var WcagContrastLevelSchema2 = external_exports.enum(["AA", "AAA"]); +var WcagContrastLevel = WcagContrastLevelSchema2; +var ThemeSchema2 = external_exports.object({ + name: SnakeCaseIdentifierSchema7.describe("Unique theme identifier (snake_case)"), + label: external_exports.string().describe("Human-readable theme name"), + description: external_exports.string().optional().describe("Theme description"), + /** Theme mode */ + mode: ThemeModeSchema2.default("light").describe("Theme mode (light, dark, or auto)"), + /** Color system */ + colors: ColorPaletteSchema2.describe("Color palette configuration"), + /** Typography */ + typography: TypographySchema2.optional().describe("Typography settings"), + /** Spacing */ + spacing: SpacingSchema2.optional().describe("Spacing scale"), + /** Border radius */ + borderRadius: BorderRadiusSchema2.optional().describe("Border radius scale"), + /** Shadows */ + shadows: ShadowSchema2.optional().describe("Box shadow effects"), + /** Breakpoints */ + breakpoints: BreakpointsSchema2.optional().describe("Responsive breakpoints"), + /** Animation */ + animation: AnimationSchema2.optional().describe("Animation settings"), + /** Z-Index */ + zIndex: ZIndexSchema2.optional().describe("Z-index scale for layering"), + /** Custom CSS variables */ + customVars: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom CSS variables (key-value pairs)"), + /** Logo */ + logo: external_exports.object({ + light: external_exports.string().optional().describe("Logo URL for light mode"), + dark: external_exports.string().optional().describe("Logo URL for dark mode"), + favicon: external_exports.string().optional().describe("Favicon URL") + }).optional().describe("Logo assets"), + /** Extends another theme */ + extends: external_exports.string().optional().describe("Base theme to extend from"), + /** Display density mode */ + density: DensityModeSchema2.optional().describe("Display density: compact, regular, or spacious"), + /** WCAG contrast level requirement */ + wcagContrast: WcagContrastLevelSchema2.optional().describe("WCAG color contrast level (AA or AAA)"), + /** Right-to-left language support */ + rtl: external_exports.boolean().optional().describe("Enable right-to-left layout direction"), + /** Touch target accessibility configuration */ + touchTarget: TouchTargetConfigSchema2.optional().describe("Touch target sizing defaults"), + /** Keyboard navigation and focus management */ + keyboardNavigation: FocusManagementSchema2.optional().describe("Keyboard focus management settings") +}); +var OfflineStrategySchema2 = external_exports.enum([ + "cache_first", + "network_first", + "stale_while_revalidate", + "network_only", + "cache_only" +]).describe("Data fetching strategy for offline/online transitions"); +var ConflictResolutionSchema2 = external_exports.enum([ + "client_wins", + "server_wins", + "manual", + "last_write_wins" +]).describe("How to resolve conflicts when syncing offline changes"); +var SyncConfigSchema2 = external_exports.object({ + strategy: OfflineStrategySchema2.default("network_first").describe("Sync fetch strategy"), + conflictResolution: ConflictResolutionSchema2.default("last_write_wins").describe("Conflict resolution policy"), + retryInterval: external_exports.number().optional().describe("Retry interval in milliseconds between sync attempts"), + maxRetries: external_exports.number().optional().describe("Maximum number of sync retry attempts"), + batchSize: external_exports.number().optional().describe("Number of mutations to sync per batch") +}).describe("Offline-to-online synchronization configuration"); +var PersistStorageSchema2 = external_exports.enum([ + "indexeddb", + "localstorage", + "sqlite" +]).describe("Client-side storage backend for offline cache"); +var EvictionPolicySchema2 = external_exports.enum([ + "lru", + "lfu", + "fifo" +]).describe("Cache eviction policy"); +var OfflineCacheConfigSchema2 = external_exports.object({ + maxSize: external_exports.number().optional().describe("Maximum cache size in bytes"), + ttl: external_exports.number().optional().describe("Time-to-live for cached entries in milliseconds"), + persistStorage: PersistStorageSchema2.default("indexeddb").describe("Storage backend"), + evictionPolicy: EvictionPolicySchema2.default("lru").describe("Cache eviction policy when full") +}).describe("Client-side offline cache configuration"); +var OfflineConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable offline support"), + strategy: OfflineStrategySchema2.default("network_first").describe("Default offline fetch strategy"), + cache: OfflineCacheConfigSchema2.optional().describe("Cache settings for offline data"), + sync: SyncConfigSchema2.optional().describe("Sync settings for offline mutations"), + offlineIndicator: external_exports.boolean().default(true).describe("Show a visual indicator when offline"), + offlineMessage: I18nLabelSchema5.optional().describe("Customizable offline status message shown to users"), + queueMaxSize: external_exports.number().optional().describe("Maximum number of queued offline mutations") +}).describe("Offline support configuration"); +var TransitionPresetSchema2 = external_exports.enum([ + "fade", + "slide_up", + "slide_down", + "slide_left", + "slide_right", + "scale", + "rotate", + "flip", + "none" +]).describe("Transition preset type"); +var EasingFunctionSchema2 = external_exports.enum([ + "linear", + "ease", + "ease_in", + "ease_out", + "ease_in_out", + "spring" +]).describe("Animation easing function"); +var TransitionConfigSchema2 = external_exports.object({ + preset: TransitionPresetSchema2.optional().describe("Transition preset to apply"), + duration: external_exports.number().optional().describe("Transition duration in milliseconds"), + easing: EasingFunctionSchema2.optional().describe("Easing function for the transition"), + delay: external_exports.number().optional().describe("Delay before transition starts in milliseconds"), + customKeyframes: external_exports.string().optional().describe("CSS @keyframes name for custom animations"), + themeToken: external_exports.string().optional().describe('Reference to a theme animation token (e.g. "animation.duration.fast")') +}).describe("Animation transition configuration"); +var AnimationTriggerSchema2 = external_exports.enum([ + "on_mount", + "on_unmount", + "on_hover", + "on_focus", + "on_click", + "on_scroll", + "on_visible" +]).describe("Event that triggers the animation"); +var ComponentAnimationSchema2 = external_exports.object({ + label: I18nLabelSchema5.optional().describe("Descriptive label for this animation configuration"), + enter: TransitionConfigSchema2.optional().describe("Enter/mount animation"), + exit: TransitionConfigSchema2.optional().describe("Exit/unmount animation"), + hover: TransitionConfigSchema2.optional().describe("Hover state animation"), + trigger: AnimationTriggerSchema2.optional().describe("When to trigger the animation"), + reducedMotion: external_exports.enum(["respect", "disable", "alternative"]).default("respect").describe("Accessibility: how to handle prefers-reduced-motion") +}).merge(AriaPropsSchema5.partial()).describe("Component-level animation configuration"); +var PageTransitionSchema2 = external_exports.object({ + type: TransitionPresetSchema2.default("fade").describe("Page transition type"), + duration: external_exports.number().default(300).describe("Transition duration in milliseconds"), + easing: EasingFunctionSchema2.default("ease_in_out").describe("Easing function for the transition"), + crossFade: external_exports.boolean().default(false).describe("Whether to cross-fade between pages") +}).describe("Page-level transition configuration"); +var MotionConfigSchema2 = external_exports.object({ + label: I18nLabelSchema5.optional().describe("Descriptive label for the motion configuration"), + defaultTransition: TransitionConfigSchema2.optional().describe("Default transition applied to all animations"), + pageTransitions: PageTransitionSchema2.optional().describe("Page navigation transition settings"), + componentAnimations: external_exports.record(external_exports.string(), ComponentAnimationSchema2).optional().describe("Component name to animation configuration mapping"), + reducedMotion: external_exports.boolean().default(false).describe("When true, respect prefers-reduced-motion and suppress animations globally"), + enabled: external_exports.boolean().default(true).describe("Enable or disable all animations globally") +}).describe("Top-level motion and animation design configuration"); +var NotificationTypeSchema2 = external_exports.enum([ + "toast", + "snackbar", + "banner", + "alert", + "inline" +]).describe("Notification presentation style"); +var NotificationSeveritySchema2 = external_exports.enum([ + "info", + "success", + "warning", + "error" +]).describe("Notification severity level"); +var NotificationPositionSchema2 = external_exports.enum([ + "top_left", + "top_center", + "top_right", + "bottom_left", + "bottom_center", + "bottom_right" +]).describe("Screen position for notification placement"); +var NotificationActionSchema2 = external_exports.object({ + label: I18nLabelSchema5.describe("Action button label"), + action: external_exports.string().describe("Action identifier to execute"), + variant: external_exports.enum(["primary", "secondary", "link"]).default("primary").describe("Button variant style") +}).describe("Notification action button"); +var NotificationSchema3 = external_exports.object({ + type: NotificationTypeSchema2.default("toast").describe("Notification presentation style"), + severity: NotificationSeveritySchema2.default("info").describe("Notification severity level"), + title: I18nLabelSchema5.optional().describe("Notification title"), + message: I18nLabelSchema5.describe("Notification message body"), + icon: external_exports.string().optional().describe("Icon name override"), + duration: external_exports.number().optional().describe("Auto-dismiss duration in ms, omit for persistent"), + dismissible: external_exports.boolean().default(true).describe("Allow user to dismiss the notification"), + actions: external_exports.array(NotificationActionSchema2).optional().describe("Action buttons"), + position: NotificationPositionSchema2.optional().describe("Override default position") +}).merge(AriaPropsSchema5.partial()).describe("Notification instance definition"); +var NotificationConfigSchema3 = external_exports.object({ + defaultPosition: NotificationPositionSchema2.default("top_right").describe("Default screen position for notifications"), + defaultDuration: external_exports.number().default(5e3).describe("Default auto-dismiss duration in ms"), + maxVisible: external_exports.number().default(5).describe("Maximum number of notifications visible at once"), + stackDirection: external_exports.enum(["up", "down"]).default("down").describe("Stack direction for multiple notifications"), + pauseOnHover: external_exports.boolean().default(true).describe("Pause auto-dismiss timer on hover") +}).describe("Global notification system configuration"); +var DragHandleSchema2 = external_exports.enum([ + "element", + "handle", + "grip_icon" +]).describe("Drag initiation method"); +var DropEffectSchema2 = external_exports.enum([ + "move", + "copy", + "link", + "none" +]).describe("Drop operation effect"); +var DragConstraintSchema2 = external_exports.object({ + axis: external_exports.enum(["x", "y", "both"]).default("both").describe("Constrain drag axis"), + bounds: external_exports.enum(["parent", "viewport", "none"]).default("none").describe("Constrain within bounds"), + grid: external_exports.tuple([external_exports.number(), external_exports.number()]).optional().describe("Snap to grid [x, y] in pixels") +}).describe("Drag movement constraints"); +var DropZoneSchema2 = external_exports.object({ + label: I18nLabelSchema5.optional().describe("Accessible label for the drop zone"), + accept: external_exports.array(external_exports.string()).describe("Accepted drag item types"), + maxItems: external_exports.number().optional().describe("Maximum items allowed in drop zone"), + highlightOnDragOver: external_exports.boolean().default(true).describe("Highlight drop zone when dragging over"), + dropEffect: DropEffectSchema2.default("move").describe("Visual effect on drop") +}).merge(AriaPropsSchema5.partial()).describe("Drop zone configuration"); +var DragItemSchema2 = external_exports.object({ + type: external_exports.string().describe("Drag item type identifier for matching with drop zones"), + label: I18nLabelSchema5.optional().describe("Accessible label describing the draggable item"), + handle: DragHandleSchema2.default("element").describe("How to initiate drag"), + constraint: DragConstraintSchema2.optional().describe("Drag movement constraints"), + preview: external_exports.enum(["element", "custom", "none"]).default("element").describe("Drag preview type"), + disabled: external_exports.boolean().default(false).describe("Disable dragging") +}).merge(AriaPropsSchema5.partial()).describe("Draggable item configuration"); +var DndConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable drag and drop"), + dragItem: DragItemSchema2.optional().describe("Configuration for draggable item"), + dropZone: DropZoneSchema2.optional().describe("Configuration for drop target"), + sortable: external_exports.boolean().default(false).describe("Enable sortable list behavior"), + autoScroll: external_exports.boolean().default(true).describe("Auto-scroll during drag near edges"), + touchDelay: external_exports.number().default(200).describe("Delay in ms before drag starts on touch devices") +}).describe("Drag and drop interaction configuration"); +var system_exports = {}; +__export4(system_exports, { + AccessControlConfigSchema: () => AccessControlConfigSchema3, + AddFieldOperation: () => AddFieldOperation2, + AdvancedAuthConfigSchema: () => AdvancedAuthConfigSchema2, + AnalyzerConfigSchema: () => AnalyzerConfigSchema2, + AppCompatibilityCheckSchema: () => AppCompatibilityCheckSchema2, + AppInstallRequestSchema: () => AppInstallRequestSchema2, + AppInstallResultSchema: () => AppInstallResultSchema2, + AppManifestSchema: () => AppManifestSchema2, + AppTranslationBundleSchema: () => AppTranslationBundleSchema2, + AuditConfigSchema: () => AuditConfigSchema2, + AuditEventActorSchema: () => AuditEventActorSchema2, + AuditEventChangeSchema: () => AuditEventChangeSchema2, + AuditEventFilterSchema: () => AuditEventFilterSchema2, + AuditEventSchema: () => AuditEventSchema2, + AuditEventSeverity: () => AuditEventSeverity2, + AuditEventTargetSchema: () => AuditEventTargetSchema2, + AuditEventType: () => AuditEventType2, + AuditFindingSchema: () => AuditFindingSchema2, + AuditFindingSeveritySchema: () => AuditFindingSeveritySchema2, + AuditFindingStatusSchema: () => AuditFindingStatusSchema2, + AuditLogConfigSchema: () => AuditLogConfigSchema2, + AuditRetentionPolicySchema: () => AuditRetentionPolicySchema2, + AuditScheduleSchema: () => AuditScheduleSchema2, + AuditStorageConfigSchema: () => AuditStorageConfigSchema2, + AuthConfigSchema: () => AuthConfigSchema2, + AuthPluginConfigSchema: () => AuthPluginConfigSchema2, + AuthProviderConfigSchema: () => AuthProviderConfigSchema2, + AwarenessEventSchema: () => AwarenessEventSchema2, + AwarenessSessionSchema: () => AwarenessSessionSchema2, + AwarenessUpdateSchema: () => AwarenessUpdateSchema2, + AwarenessUserStateSchema: () => AwarenessUserStateSchema2, + BackupConfigSchema: () => BackupConfigSchema2, + BackupRetentionSchema: () => BackupRetentionSchema2, + BackupStrategySchema: () => BackupStrategySchema2, + BatchProgressSchema: () => BatchProgressSchema2, + BatchTask: () => BatchTask2, + BatchTaskSchema: () => BatchTaskSchema2, + BucketConfigSchema: () => BucketConfigSchema3, + CRDTMergeResultSchema: () => CRDTMergeResultSchema2, + CRDTStateSchema: () => CRDTStateSchema2, + CRDTType: () => CRDTType2, + CacheAvalanchePreventionSchema: () => CacheAvalanchePreventionSchema2, + CacheConfigSchema: () => CacheConfigSchema2, + CacheConsistencySchema: () => CacheConsistencySchema2, + CacheInvalidationSchema: () => CacheInvalidationSchema2, + CacheStrategySchema: () => CacheStrategySchema2, + CacheTierSchema: () => CacheTierSchema2, + CacheWarmupSchema: () => CacheWarmupSchema2, + ChangeImpactSchema: () => ChangeImpactSchema2, + ChangePrioritySchema: () => ChangePrioritySchema2, + ChangeRequestSchema: () => ChangeRequestSchema2, + ChangeSetSchema: () => ChangeSetSchema2, + ChangeStatusSchema: () => ChangeStatusSchema2, + ChangeTypeSchema: () => ChangeTypeSchema2, + CollaborationMode: () => CollaborationMode2, + CollaborationSessionConfigSchema: () => CollaborationSessionConfigSchema2, + CollaborationSessionSchema: () => CollaborationSessionSchema2, + CollaborativeCursorSchema: () => CollaborativeCursorSchema2, + ComplianceAuditRequirementSchema: () => ComplianceAuditRequirementSchema2, + ComplianceConfigSchema: () => ComplianceConfigSchema2, + ComplianceEncryptionRequirementSchema: () => ComplianceEncryptionRequirementSchema2, + ComplianceFrameworkSchema: () => ComplianceFrameworkSchema2, + ConsoleDestinationConfigSchema: () => ConsoleDestinationConfigSchema2, + ConsumerConfigSchema: () => ConsumerConfigSchema2, + CoreServiceName: () => CoreServiceName3, + CounterOperationSchema: () => CounterOperationSchema2, + CoverageBreakdownEntrySchema: () => CoverageBreakdownEntrySchema3, + CreateObjectOperation: () => CreateObjectOperation2, + CronScheduleSchema: () => CronScheduleSchema2, + CursorColorPreset: () => CursorColorPreset2, + CursorSelectionSchema: () => CursorSelectionSchema2, + CursorStyleSchema: () => CursorStyleSchema2, + CursorUpdateSchema: () => CursorUpdateSchema2, + DEFAULT_SUSPICIOUS_ACTIVITY_RULES: () => DEFAULT_SUSPICIOUS_ACTIVITY_RULES, + DataClassificationPolicySchema: () => DataClassificationPolicySchema2, + DataClassificationSchema: () => DataClassificationSchema2, + DatabaseLevelIsolationStrategySchema: () => DatabaseLevelIsolationStrategySchema3, + DatabaseProviderSchema: () => DatabaseProviderSchema3, + DeadLetterQueueSchema: () => DeadLetterQueueSchema2, + DeleteObjectOperation: () => DeleteObjectOperation2, + DeployBundleSchema: () => DeployBundleSchema2, + DeployDiffSchema: () => DeployDiffSchema2, + DeployManifestSchema: () => DeployManifestSchema2, + DeployStatusEnum: () => DeployStatusEnum2, + DeployValidationIssueSchema: () => DeployValidationIssueSchema2, + DeployValidationResultSchema: () => DeployValidationResultSchema2, + DisasterRecoveryPlanSchema: () => DisasterRecoveryPlanSchema2, + DistributedCacheConfigSchema: () => DistributedCacheConfigSchema2, + EmailAndPasswordConfigSchema: () => EmailAndPasswordConfigSchema2, + EmailTemplateSchema: () => EmailTemplateSchema2, + EmailVerificationConfigSchema: () => EmailVerificationConfigSchema2, + EncryptionAlgorithmSchema: () => EncryptionAlgorithmSchema6, + EncryptionConfigSchema: () => EncryptionConfigSchema6, + ExecuteSqlOperation: () => ExecuteSqlOperation2, + ExtendedLogLevel: () => ExtendedLogLevel2, + ExternalServiceDestinationConfigSchema: () => ExternalServiceDestinationConfigSchema2, + FacetConfigSchema: () => FacetConfigSchema2, + FailoverConfigSchema: () => FailoverConfigSchema2, + FailoverModeSchema: () => FailoverModeSchema2, + FeatureSchema: () => FeatureSchema2, + FieldEncryptionSchema: () => FieldEncryptionSchema2, + FieldTranslationSchema: () => FieldTranslationSchema3, + FileDestinationConfigSchema: () => FileDestinationConfigSchema2, + FileMetadataSchema: () => FileMetadataSchema3, + GCounterSchema: () => GCounterSchema2, + GDPRConfigSchema: () => GDPRConfigSchema2, + HIPAAConfigSchema: () => HIPAAConfigSchema2, + HistogramBucketConfigSchema: () => HistogramBucketConfigSchema2, + HttpDestinationConfigSchema: () => HttpDestinationConfigSchema2, + HttpServerConfig: () => HttpServerConfig2, + HttpServerConfigSchema: () => HttpServerConfigSchema3, + InAppNotificationSchema: () => InAppNotificationSchema2, + IncidentCategorySchema: () => IncidentCategorySchema2, + IncidentNotificationMatrixSchema: () => IncidentNotificationMatrixSchema2, + IncidentNotificationRuleSchema: () => IncidentNotificationRuleSchema2, + IncidentResponsePhaseSchema: () => IncidentResponsePhaseSchema2, + IncidentResponsePolicySchema: () => IncidentResponsePolicySchema2, + IncidentSchema: () => IncidentSchema2, + IncidentSeveritySchema: () => IncidentSeveritySchema2, + IncidentStatusSchema: () => IncidentStatusSchema2, + IntervalScheduleSchema: () => IntervalScheduleSchema2, + JobExecutionSchema: () => JobExecutionSchema2, + JobExecutionStatus: () => JobExecutionStatus2, + JobSchema: () => JobSchema2, + KernelServiceMapSchema: () => KernelServiceMapSchema2, + KeyManagementProviderSchema: () => KeyManagementProviderSchema6, + KeyRotationPolicySchema: () => KeyRotationPolicySchema6, + LWWRegisterSchema: () => LWWRegisterSchema2, + LicenseMetricType: () => LicenseMetricType2, + LicenseSchema: () => LicenseSchema2, + LifecycleActionSchema: () => LifecycleActionSchema3, + LifecyclePolicyConfigSchema: () => LifecyclePolicyConfigSchema3, + LifecyclePolicyRuleSchema: () => LifecyclePolicyRuleSchema3, + LocaleSchema: () => LocaleSchema3, + LogDestinationSchema: () => LogDestinationSchema2, + LogDestinationType: () => LogDestinationType2, + LogEnrichmentConfigSchema: () => LogEnrichmentConfigSchema2, + LogEntrySchema: () => LogEntrySchema2, + LogFormat: () => LogFormat2, + LogLevel: () => LogLevel2, + LoggerConfigSchema: () => LoggerConfigSchema2, + LoggingConfigSchema: () => LoggingConfigSchema2, + MaskingConfigSchema: () => MaskingConfigSchema2, + MaskingRuleSchema: () => MaskingRuleSchema6, + MaskingStrategySchema: () => MaskingStrategySchema6, + MaskingVisibilityRuleSchema: () => MaskingVisibilityRuleSchema2, + MessageFormatSchema: () => MessageFormatSchema3, + MessageQueueConfigSchema: () => MessageQueueConfigSchema2, + MessageQueueProviderSchema: () => MessageQueueProviderSchema2, + MetadataCollectionInfoSchema: () => MetadataCollectionInfoSchema3, + MetadataDiffResultSchema: () => MetadataDiffResultSchema2, + MetadataExportOptionsSchema: () => MetadataExportOptionsSchema3, + MetadataFallbackStrategySchema: () => MetadataFallbackStrategySchema4, + MetadataFormatSchema: () => MetadataFormatSchema22, + MetadataHistoryQueryOptionsSchema: () => MetadataHistoryQueryOptionsSchema2, + MetadataHistoryQueryResultSchema: () => MetadataHistoryQueryResultSchema2, + MetadataHistoryRecordSchema: () => MetadataHistoryRecordSchema2, + MetadataHistoryRetentionPolicySchema: () => MetadataHistoryRetentionPolicySchema2, + MetadataImportOptionsSchema: () => MetadataImportOptionsSchema3, + MetadataLoadOptionsSchema: () => MetadataLoadOptionsSchema3, + MetadataLoadResultSchema: () => MetadataLoadResultSchema3, + MetadataLoaderContractSchema: () => MetadataLoaderContractSchema3, + MetadataManagerConfigSchema: () => MetadataManagerConfigSchema4, + MetadataRecordSchema: () => MetadataRecordSchema2, + MetadataSaveOptionsSchema: () => MetadataSaveOptionsSchema3, + MetadataSaveResultSchema: () => MetadataSaveResultSchema3, + MetadataScopeSchema: () => MetadataScopeSchema2, + MetadataSourceSchema: () => MetadataSourceSchema2, + MetadataStateSchema: () => MetadataStateSchema2, + MetadataStatsSchema: () => MetadataStatsSchema4, + MetadataWatchEventSchema: () => MetadataWatchEventSchema3, + MetricAggregationConfigSchema: () => MetricAggregationConfigSchema2, + MetricAggregationType: () => MetricAggregationType2, + MetricDataPointSchema: () => MetricDataPointSchema2, + MetricDefinitionSchema: () => MetricDefinitionSchema2, + MetricExportConfigSchema: () => MetricExportConfigSchema2, + MetricLabelsSchema: () => MetricLabelsSchema2, + MetricType: () => MetricType2, + MetricUnit: () => MetricUnit2, + MetricsConfigSchema: () => MetricsConfigSchema2, + MiddlewareConfig: () => MiddlewareConfig2, + MiddlewareConfigSchema: () => MiddlewareConfigSchema3, + MiddlewareType: () => MiddlewareType3, + MigrationDependencySchema: () => MigrationDependencySchema2, + MigrationOperationSchema: () => MigrationOperationSchema2, + MigrationPlanSchema: () => MigrationPlanSchema2, + MigrationStatementSchema: () => MigrationStatementSchema2, + ModifyFieldOperation: () => ModifyFieldOperation2, + MultipartUploadConfigSchema: () => MultipartUploadConfigSchema3, + MutualTLSConfigSchema: () => MutualTLSConfigSchema2, + NotificationChannelSchema: () => NotificationChannelSchema2, + NotificationConfigSchema: () => NotificationConfigSchema22, + ORSetElementSchema: () => ORSetElementSchema2, + ORSetSchema: () => ORSetSchema2, + OTComponentSchema: () => OTComponentSchema2, + OTOperationSchema: () => OTOperationSchema2, + OTOperationType: () => OTOperationType2, + OTTransformResultSchema: () => OTTransformResultSchema2, + ObjectMetadataSchema: () => ObjectMetadataSchema2, + ObjectStorageConfigSchema: () => ObjectStorageConfigSchema3, + ObjectTranslationDataSchema: () => ObjectTranslationDataSchema3, + ObjectTranslationNodeSchema: () => ObjectTranslationNodeSchema3, + OnceScheduleSchema: () => OnceScheduleSchema2, + OpenTelemetryCompatibilitySchema: () => OpenTelemetryCompatibilitySchema2, + OtelExporterType: () => OtelExporterType2, + PCIDSSConfigSchema: () => PCIDSSConfigSchema2, + PKG_CONVENTIONS: () => PKG_CONVENTIONS, + PNCounterSchema: () => PNCounterSchema2, + PackagePublishResultSchema: () => PackagePublishResultSchema2, + PlanSchema: () => PlanSchema2, + PresignedUrlConfigSchema: () => PresignedUrlConfigSchema2, + ProvisioningStepSchema: () => ProvisioningStepSchema2, + PushNotificationSchema: () => PushNotificationSchema2, + QueueConfig: () => QueueConfig2, + QueueConfigSchema: () => QueueConfigSchema2, + QuotaEnforcementResultSchema: () => QuotaEnforcementResultSchema2, + RPOSchema: () => RPOSchema2, + RTOSchema: () => RTOSchema2, + RegistryConfigSchema: () => RegistryConfigSchema2, + RegistrySyncPolicySchema: () => RegistrySyncPolicySchema2, + RegistryUpstreamSchema: () => RegistryUpstreamSchema2, + RemoveFieldOperation: () => RemoveFieldOperation2, + RenameObjectOperation: () => RenameObjectOperation2, + RetryPolicySchema: () => RetryPolicySchema2, + RollbackPlanSchema: () => RollbackPlanSchema2, + RouteHandlerMetadataSchema: () => RouteHandlerMetadataSchema2, + RowLevelIsolationStrategySchema: () => RowLevelIsolationStrategySchema3, + SMSTemplateSchema: () => SMSTemplateSchema2, + SamplingDecision: () => SamplingDecision2, + SamplingStrategyType: () => SamplingStrategyType2, + ScheduleSchema: () => ScheduleSchema2, + SchemaChangeSchema: () => SchemaChangeSchema2, + SchemaLevelIsolationStrategySchema: () => SchemaLevelIsolationStrategySchema3, + SearchConfigSchema: () => SearchConfigSchema22, + SearchIndexConfigSchema: () => SearchIndexConfigSchema2, + SearchProviderSchema: () => SearchProviderSchema2, + SecurityContextConfigSchema: () => SecurityContextConfigSchema2, + SecurityEventCorrelationSchema: () => SecurityEventCorrelationSchema2, + ServerCapabilitiesSchema: () => ServerCapabilitiesSchema2, + ServerEventSchema: () => ServerEventSchema2, + ServerEventType: () => ServerEventType3, + ServerStatusSchema: () => ServerStatusSchema2, + ServiceConfigSchema: () => ServiceConfigSchema2, + ServiceCriticalitySchema: () => ServiceCriticalitySchema3, + ServiceLevelIndicatorSchema: () => ServiceLevelIndicatorSchema2, + ServiceLevelObjectiveSchema: () => ServiceLevelObjectiveSchema2, + ServiceRequirementDef: () => ServiceRequirementDef2, + ServiceStatusSchema: () => ServiceStatusSchema2, + SocialProviderConfigSchema: () => SocialProviderConfigSchema2, + SpanAttributeValueSchema: () => SpanAttributeValueSchema2, + SpanAttributesSchema: () => SpanAttributesSchema2, + SpanEventSchema: () => SpanEventSchema2, + SpanKind: () => SpanKind2, + SpanLinkSchema: () => SpanLinkSchema2, + SpanSchema: () => SpanSchema2, + SpanStatus: () => SpanStatus2, + StorageAclSchema: () => StorageAclSchema3, + StorageClassSchema: () => StorageClassSchema3, + StorageConnectionSchema: () => StorageConnectionSchema3, + StorageNameMapping: () => StorageNameMapping, + StorageProviderSchema: () => StorageProviderSchema3, + StorageScopeSchema: () => StorageScopeSchema3, + StructuredLogEntrySchema: () => StructuredLogEntrySchema2, + SupplierAssessmentStatusSchema: () => SupplierAssessmentStatusSchema2, + SupplierRiskLevelSchema: () => SupplierRiskLevelSchema2, + SupplierSecurityAssessmentSchema: () => SupplierSecurityAssessmentSchema2, + SupplierSecurityPolicySchema: () => SupplierSecurityPolicySchema2, + SupplierSecurityRequirementSchema: () => SupplierSecurityRequirementSchema2, + SuspiciousActivityRuleSchema: () => SuspiciousActivityRuleSchema2, + SystemFieldName: () => SystemFieldName, + SystemObjectName: () => SystemObjectName2, + TASK_PRIORITY_VALUES: () => TASK_PRIORITY_VALUES, + TRANSLATE_PLACEHOLDER: () => TRANSLATE_PLACEHOLDER, + Task: () => Task2, + TaskExecutionResultSchema: () => TaskExecutionResultSchema2, + TaskPriority: () => TaskPriority2, + TaskRetryPolicySchema: () => TaskRetryPolicySchema2, + TaskSchema: () => TaskSchema2, + TaskStatus: () => TaskStatus2, + TenantConnectionConfigSchema: () => TenantConnectionConfigSchema3, + TenantIsolationConfigSchema: () => TenantIsolationConfigSchema2, + TenantIsolationLevel: () => TenantIsolationLevel3, + TenantPlanSchema: () => TenantPlanSchema2, + TenantProvisioningRequestSchema: () => TenantProvisioningRequestSchema2, + TenantProvisioningResultSchema: () => TenantProvisioningResultSchema2, + TenantProvisioningStatusEnum: () => TenantProvisioningStatusEnum2, + TenantQuotaSchema: () => TenantQuotaSchema3, + TenantRegionSchema: () => TenantRegionSchema2, + TenantSchema: () => TenantSchema2, + TenantSecurityPolicySchema: () => TenantSecurityPolicySchema2, + TenantUsageSchema: () => TenantUsageSchema2, + TextCRDTOperationSchema: () => TextCRDTOperationSchema2, + TextCRDTStateSchema: () => TextCRDTStateSchema2, + TimeSeriesDataPointSchema: () => TimeSeriesDataPointSchema2, + TimeSeriesSchema: () => TimeSeriesSchema2, + TopicConfigSchema: () => TopicConfigSchema2, + TraceContextPropagationSchema: () => TraceContextPropagationSchema2, + TraceContextSchema: () => TraceContextSchema2, + TraceFlagsSchema: () => TraceFlagsSchema2, + TracePropagationFormat: () => TracePropagationFormat2, + TraceSamplingConfigSchema: () => TraceSamplingConfigSchema2, + TraceStateSchema: () => TraceStateSchema2, + TracingConfigSchema: () => TracingConfigSchema2, + TrainingCategorySchema: () => TrainingCategorySchema2, + TrainingCompletionStatusSchema: () => TrainingCompletionStatusSchema2, + TrainingCourseSchema: () => TrainingCourseSchema2, + TrainingPlanSchema: () => TrainingPlanSchema2, + TrainingRecordSchema: () => TrainingRecordSchema2, + TranslationBundleSchema: () => TranslationBundleSchema2, + TranslationConfigSchema: () => TranslationConfigSchema2, + TranslationCoverageResultSchema: () => TranslationCoverageResultSchema2, + TranslationDataSchema: () => TranslationDataSchema3, + TranslationDiffItemSchema: () => TranslationDiffItemSchema3, + TranslationDiffStatusSchema: () => TranslationDiffStatusSchema3, + TranslationFileOrganizationSchema: () => TranslationFileOrganizationSchema3, + UserActivityStatus: () => UserActivityStatus2, + VectorClockSchema: () => VectorClockSchema2, + WorkerConfig: () => WorkerConfig2, + WorkerConfigSchema: () => WorkerConfigSchema2, + WorkerStatsSchema: () => WorkerStatsSchema2, + azureBlobStorageExample: () => azureBlobStorageExample2, + gcsStorageExample: () => gcsStorageExample2, + minioStorageExample: () => minioStorageExample2, + s3StorageExample: () => s3StorageExample2 +}); +var CacheStrategySchema2 = external_exports.enum([ + "lru", + // Least Recently Used + "lfu", + // Least Frequently Used + "fifo", + // First In First Out + "ttl", + // Time To Live only + "adaptive" + // Dynamic strategy selection +]).describe("Cache eviction strategy"); +var CacheTierSchema2 = external_exports.object({ + name: external_exports.string().describe("Unique cache tier name"), + type: external_exports.enum(["memory", "redis", "memcached", "cdn"]).describe("Cache backend type"), + maxSize: external_exports.number().optional().describe("Max size in MB"), + ttl: external_exports.number().default(300).describe("Default TTL in seconds"), + strategy: CacheStrategySchema2.default("lru").describe("Eviction strategy"), + warmup: external_exports.boolean().default(false).describe("Pre-populate cache on startup") +}).describe("Configuration for a single cache tier in the hierarchy"); +var CacheInvalidationSchema2 = external_exports.object({ + trigger: external_exports.enum(["create", "update", "delete", "manual"]).describe("Event that triggers invalidation"), + scope: external_exports.enum(["key", "pattern", "tag", "all"]).describe("Invalidation scope"), + pattern: external_exports.string().optional().describe("Key pattern for pattern-based invalidation"), + tags: external_exports.array(external_exports.string()).optional().describe("Cache tags to invalidate") +}).describe("Rule defining when and how cached entries are invalidated"); +var CacheConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable application-level caching"), + tiers: external_exports.array(CacheTierSchema2).describe("Ordered cache tier hierarchy"), + invalidation: external_exports.array(CacheInvalidationSchema2).describe("Cache invalidation rules"), + prefetch: external_exports.boolean().default(false).describe("Enable cache prefetching"), + compression: external_exports.boolean().default(false).describe("Enable data compression in cache"), + encryption: external_exports.boolean().default(false).describe("Enable encryption for cached data") +}).describe("Top-level application cache configuration"); +var CacheConsistencySchema2 = external_exports.enum([ + "write_through", + "write_behind", + "write_around", + "refresh_ahead" +]).describe("Distributed cache write consistency strategy"); +var CacheAvalanchePreventionSchema2 = external_exports.object({ + /** TTL jitter to stagger cache expiration */ + jitterTtl: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Add random jitter to TTL values"), + maxJitterSeconds: external_exports.number().default(60).describe("Maximum jitter added to TTL in seconds") + }).optional().describe("TTL jitter to prevent simultaneous expiration"), + /** Circuit breaker to protect backend under cache pressure */ + circuitBreaker: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable circuit breaker for backend protection"), + failureThreshold: external_exports.number().default(5).describe("Failures before circuit opens"), + resetTimeout: external_exports.number().default(30).describe("Seconds before half-open state") + }).optional().describe("Circuit breaker for backend protection"), + /** Cache lock to prevent thundering herd on key miss */ + lockout: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable cache locking for key regeneration"), + lockTimeoutMs: external_exports.number().default(5e3).describe("Maximum lock wait time in milliseconds") + }).optional().describe("Lock-based stampede prevention") +}).describe("Cache avalanche/stampede prevention configuration"); +var CacheWarmupSchema2 = external_exports.object({ + /** Enable cache warming */ + enabled: external_exports.boolean().default(false).describe("Enable cache warmup"), + /** Warmup strategy */ + strategy: external_exports.enum(["eager", "lazy", "scheduled"]).default("lazy").describe("Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)"), + /** Cron schedule for scheduled warmup */ + schedule: external_exports.string().optional().describe("Cron expression for scheduled warmup"), + /** Keys/patterns to warm up */ + patterns: external_exports.array(external_exports.string()).optional().describe('Key patterns to warm up (e.g., "user:*", "config:*")'), + /** Maximum concurrent warmup operations */ + concurrency: external_exports.number().default(10).describe("Maximum concurrent warmup operations") +}).describe("Cache warmup strategy"); +var DistributedCacheConfigSchema2 = CacheConfigSchema2.extend({ + /** Distributed write consistency strategy */ + consistency: CacheConsistencySchema2.optional().describe("Distributed cache consistency strategy"), + /** Avalanche/stampede prevention settings */ + avalanchePrevention: CacheAvalanchePreventionSchema2.optional().describe("Cache avalanche and stampede prevention"), + /** Cache warmup configuration */ + warmup: CacheWarmupSchema2.optional().describe("Cache warmup strategy") +}).describe("Distributed cache configuration with consistency and avalanche prevention"); +var BackupStrategySchema2 = external_exports.enum([ + "full", + "incremental", + "differential" +]).describe("Backup strategy type"); +var BackupRetentionSchema2 = external_exports.object({ + /** Number of days to retain backups */ + days: external_exports.number().min(1).describe("Retention period in days"), + /** Minimum number of backup copies to keep regardless of age */ + minCopies: external_exports.number().min(1).default(3).describe("Minimum backup copies to retain"), + /** Maximum number of backup copies */ + maxCopies: external_exports.number().optional().describe("Maximum backup copies to store") +}).describe("Backup retention policy"); +var BackupConfigSchema2 = external_exports.object({ + /** Backup strategy */ + strategy: BackupStrategySchema2.default("incremental").describe("Backup strategy"), + /** Cron schedule for automated backups */ + schedule: external_exports.string().optional().describe('Cron expression for backup schedule (e.g., "0 2 * * *")'), + /** Retention policy */ + retention: BackupRetentionSchema2.describe("Backup retention policy"), + /** Storage destination */ + destination: external_exports.object({ + type: external_exports.enum(["s3", "gcs", "azure_blob", "local"]).describe("Storage backend type"), + bucket: external_exports.string().optional().describe("Cloud storage bucket/container name"), + path: external_exports.string().optional().describe("Storage path prefix"), + region: external_exports.string().optional().describe("Cloud storage region") + }).describe("Backup storage destination"), + /** Encryption settings */ + encryption: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable backup encryption"), + algorithm: external_exports.enum(["AES-256-GCM", "AES-256-CBC", "ChaCha20-Poly1305"]).default("AES-256-GCM").describe("Encryption algorithm"), + keyId: external_exports.string().optional().describe("KMS key ID for encryption") + }).optional().describe("Backup encryption settings"), + /** Compression settings */ + compression: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable backup compression"), + algorithm: external_exports.enum(["gzip", "zstd", "lz4", "snappy"]).default("zstd").describe("Compression algorithm") + }).optional().describe("Backup compression settings"), + /** Verify backup integrity after creation */ + verifyAfterBackup: external_exports.boolean().default(true).describe("Verify backup integrity after creation") +}).describe("Backup configuration"); +var FailoverModeSchema2 = external_exports.enum([ + "active_passive", + "active_active", + "pilot_light", + "warm_standby" +]).describe("Failover mode"); +var FailoverConfigSchema2 = external_exports.object({ + /** Failover mode */ + mode: FailoverModeSchema2.default("active_passive").describe("Failover mode"), + /** Automatic failover enabled */ + autoFailover: external_exports.boolean().default(true).describe("Enable automatic failover"), + /** Health check interval in seconds */ + healthCheckInterval: external_exports.number().default(30).describe("Health check interval in seconds"), + /** Number of consecutive failures before triggering failover */ + failureThreshold: external_exports.number().default(3).describe("Consecutive failures before failover"), + /** Regions/zones for disaster recovery */ + regions: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Region identifier (e.g., "us-east-1", "eu-west-1")'), + role: external_exports.enum(["primary", "secondary", "witness"]).describe("Region role"), + endpoint: external_exports.string().optional().describe("Region endpoint URL"), + priority: external_exports.number().optional().describe("Failover priority (lower = higher priority)") + })).min(2).describe("Multi-region configuration (minimum 2 regions)"), + /** DNS failover configuration */ + dns: external_exports.object({ + ttl: external_exports.number().default(60).describe("DNS TTL in seconds for failover"), + provider: external_exports.enum(["route53", "cloudflare", "azure_dns", "custom"]).optional().describe("DNS provider for automatic failover") + }).optional().describe("DNS failover settings") +}).describe("Failover configuration"); +var RPOSchema2 = external_exports.object({ + /** RPO value */ + value: external_exports.number().min(0).describe("RPO value"), + /** RPO time unit */ + unit: external_exports.enum(["seconds", "minutes", "hours"]).default("minutes").describe("RPO time unit") +}).describe("Recovery Point Objective (maximum acceptable data loss)"); +var RTOSchema2 = external_exports.object({ + /** RTO value */ + value: external_exports.number().min(0).describe("RTO value"), + /** RTO time unit */ + unit: external_exports.enum(["seconds", "minutes", "hours"]).default("minutes").describe("RTO time unit") +}).describe("Recovery Time Objective (maximum acceptable downtime)"); +var DisasterRecoveryPlanSchema2 = external_exports.object({ + /** Enable disaster recovery */ + enabled: external_exports.boolean().default(false).describe("Enable disaster recovery plan"), + /** Recovery Point Objective */ + rpo: RPOSchema2.describe("Recovery Point Objective"), + /** Recovery Time Objective */ + rto: RTOSchema2.describe("Recovery Time Objective"), + /** Backup configuration */ + backup: BackupConfigSchema2.describe("Backup configuration"), + /** Failover configuration */ + failover: FailoverConfigSchema2.optional().describe("Multi-region failover configuration"), + /** Data replication settings */ + replication: external_exports.object({ + /** Replication mode */ + mode: external_exports.enum(["synchronous", "asynchronous", "semi_synchronous"]).default("asynchronous").describe("Data replication mode"), + /** Maximum replication lag allowed (seconds) */ + maxLagSeconds: external_exports.number().optional().describe("Maximum acceptable replication lag in seconds"), + /** Objects/tables to replicate (empty = all) */ + includeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to replicate (empty = all)"), + /** Objects/tables to exclude from replication */ + excludeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to exclude from replication") + }).optional().describe("Data replication settings"), + /** Automated recovery testing */ + testing: external_exports.object({ + /** Enable periodic DR testing */ + enabled: external_exports.boolean().default(false).describe("Enable automated DR testing"), + /** Cron schedule for DR tests */ + schedule: external_exports.string().optional().describe("Cron expression for DR test schedule"), + /** Notification channel for test results */ + notificationChannel: external_exports.string().optional().describe("Notification channel for DR test results") + }).optional().describe("Automated disaster recovery testing"), + /** Runbook URL for manual procedures */ + runbookUrl: external_exports.string().optional().describe("URL to disaster recovery runbook/playbook"), + /** Contact list for DR incidents */ + contacts: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Contact name"), + role: external_exports.string().describe('Contact role (e.g., "DBA", "SRE Lead")'), + email: external_exports.string().optional().describe("Contact email"), + phone: external_exports.string().optional().describe("Contact phone") + })).optional().describe("Emergency contact list for DR incidents") +}).describe("Complete disaster recovery plan configuration"); +var MessageQueueProviderSchema2 = external_exports.enum([ + "kafka", + "rabbitmq", + "aws-sqs", + "redis-pubsub", + "google-pubsub", + "azure-service-bus" +]).describe("Supported message queue backend provider"); +var TopicConfigSchema2 = external_exports.object({ + name: external_exports.string().describe("Topic name identifier"), + partitions: external_exports.number().default(1).describe("Number of partitions for parallel consumption"), + replicationFactor: external_exports.number().default(1).describe("Number of replicas for fault tolerance"), + retentionMs: external_exports.number().optional().describe("Message retention period in milliseconds"), + compressionType: external_exports.enum(["none", "gzip", "snappy", "lz4"]).default("none").describe("Message compression algorithm") +}).describe("Configuration for a message queue topic"); +var ConsumerConfigSchema2 = external_exports.object({ + groupId: external_exports.string().describe("Consumer group identifier"), + autoOffsetReset: external_exports.enum(["earliest", "latest"]).default("latest").describe("Where to start reading when no offset exists"), + enableAutoCommit: external_exports.boolean().default(true).describe("Automatically commit consumed offsets"), + maxPollRecords: external_exports.number().default(500).describe("Maximum records returned per poll") +}).describe("Consumer group configuration for topic consumption"); +var DeadLetterQueueSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable dead letter queue for failed messages"), + maxRetries: external_exports.number().default(3).describe("Maximum delivery attempts before sending to DLQ"), + queueName: external_exports.string().describe("Name of the dead letter queue") +}).describe("Dead letter queue configuration for unprocessable messages"); +var MessageQueueConfigSchema2 = external_exports.object({ + provider: MessageQueueProviderSchema2.describe("Message queue backend provider"), + topics: external_exports.array(TopicConfigSchema2).describe("List of topic configurations"), + consumers: external_exports.array(ConsumerConfigSchema2).optional().describe("Consumer group configurations"), + deadLetterQueue: DeadLetterQueueSchema2.optional().describe("Dead letter queue for failed messages"), + ssl: external_exports.boolean().default(false).describe("Enable SSL/TLS for broker connections"), + sasl: external_exports.object({ + mechanism: external_exports.enum(["plain", "scram-sha-256", "scram-sha-512"]).describe("SASL authentication mechanism"), + username: external_exports.string().describe("SASL username"), + password: external_exports.string().describe("SASL password") + }).optional().describe("SASL authentication configuration") +}).describe("Top-level message queue configuration"); +var StorageScopeSchema3 = external_exports.enum([ + "global", + // Global application-wide storage + "tenant", + // Tenant-scoped storage (multi-tenant apps) + "user", + // User-scoped storage + "session", + // Session-scoped storage (ephemeral) + "temp", + // Ephemeral, cleared on restart + "cache", + // Ephemeral, survives restarts, cleared on LRU/Expiration + "data", + // Persistent, backed up + "logs", + // Append-only, rotated + "config", + // Read-heavy, versioned + "public" + // Publicly accessible static assets +]).describe("Storage scope classification"); +var FileMetadataSchema3 = external_exports.object({ + path: external_exports.string().describe("File path"), + name: external_exports.string().describe("File name"), + size: external_exports.number().int().describe("File size in bytes"), + mimeType: external_exports.string().describe("MIME type"), + lastModified: external_exports.string().datetime().describe("Last modified timestamp"), + created: external_exports.string().datetime().describe("Creation timestamp"), + etag: external_exports.string().optional().describe("Entity tag") +}); +var StorageProviderSchema3 = external_exports.enum([ + "s3", + // Amazon S3 + "azure_blob", + // Azure Blob Storage + "gcs", + // Google Cloud Storage + "minio", + // MinIO (self-hosted S3-compatible) + "r2", + // Cloudflare R2 + "spaces", + // DigitalOcean Spaces + "wasabi", + // Wasabi Hot Cloud Storage + "backblaze", + // Backblaze B2 + "local" + // Local filesystem (development only) +]).describe("Storage provider type"); +var StorageAclSchema3 = external_exports.enum([ + "private", + // Owner has full control, no one else has access + "public_read", + // Owner has full control, everyone can read + "public_read_write", + // Owner has full control, everyone can read/write (not recommended) + "authenticated_read", + // Owner has full control, authenticated users can read + "bucket_owner_read", + // Object owner has full control, bucket owner can read + "bucket_owner_full_control" + // Both object and bucket owner have full control +]).describe("Storage access control level"); +var StorageClassSchema3 = external_exports.enum([ + "standard", + // Standard/hot storage for frequently accessed data + "intelligent", + // Intelligent tiering (auto-moves between hot/cool) + "infrequent_access", + // Infrequent access/cool storage + "glacier", + // Archive/cold storage (slower retrieval) + "deep_archive" + // Deep archive (cheapest, slowest retrieval) +]).describe("Storage class/tier for cost optimization"); +var LifecycleActionSchema3 = external_exports.enum([ + "transition", + // Move to different storage class + "delete", + // Delete the object + "abort" + // Abort incomplete multipart uploads +]).describe("Lifecycle policy action type"); +var ObjectMetadataSchema2 = external_exports.object({ + contentType: external_exports.string().describe("MIME type (e.g., image/jpeg, application/pdf)"), + contentLength: external_exports.number().min(0).describe("File size in bytes"), + contentEncoding: external_exports.string().optional().describe("Content encoding (e.g., gzip)"), + contentDisposition: external_exports.string().optional().describe("Content disposition header"), + contentLanguage: external_exports.string().optional().describe("Content language"), + cacheControl: external_exports.string().optional().describe("Cache control directives"), + etag: external_exports.string().optional().describe("Entity tag for versioning/caching"), + lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), + versionId: external_exports.string().optional().describe("Object version identifier"), + storageClass: StorageClassSchema3.optional().describe("Storage class/tier"), + encryption: external_exports.object({ + algorithm: external_exports.string().describe("Encryption algorithm (e.g., AES256, aws:kms)"), + keyId: external_exports.string().optional().describe("KMS key ID if using managed encryption") + }).optional().describe("Server-side encryption configuration"), + custom: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom user-defined metadata") +}); +var PresignedUrlConfigSchema2 = external_exports.object({ + operation: external_exports.enum(["get", "put", "delete", "head"]).describe("Allowed operation"), + expiresIn: external_exports.number().min(1).max(604800).describe("Expiration time in seconds (max 7 days)"), + contentType: external_exports.string().optional().describe("Required content type for PUT operations"), + maxSize: external_exports.number().min(0).optional().describe("Maximum file size in bytes for PUT operations"), + responseContentType: external_exports.string().optional().describe("Override content-type for GET operations"), + responseContentDisposition: external_exports.string().optional().describe("Override content-disposition for GET operations") +}); +var MultipartUploadConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable multipart uploads"), + partSize: external_exports.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe("Part size in bytes (min 5MB, max 5GB)"), + maxParts: external_exports.number().min(1).max(1e4).default(1e4).describe("Maximum number of parts (max 10,000)"), + threshold: external_exports.number().min(0).default(100 * 1024 * 1024).describe("File size threshold to trigger multipart upload (bytes)"), + maxConcurrent: external_exports.number().min(1).max(100).default(4).describe("Maximum concurrent part uploads"), + abortIncompleteAfterDays: external_exports.number().min(1).optional().describe("Auto-abort incomplete uploads after N days") +}); +var AccessControlConfigSchema3 = external_exports.object({ + acl: StorageAclSchema3.default("private").describe("Default access control level"), + allowedOrigins: external_exports.array(external_exports.string()).optional().describe("CORS allowed origins"), + allowedMethods: external_exports.array(external_exports.enum(["GET", "PUT", "POST", "DELETE", "HEAD"])).optional().describe("CORS allowed HTTP methods"), + allowedHeaders: external_exports.array(external_exports.string()).optional().describe("CORS allowed headers"), + exposeHeaders: external_exports.array(external_exports.string()).optional().describe("CORS exposed headers"), + maxAge: external_exports.number().min(0).optional().describe("CORS preflight cache duration in seconds"), + corsEnabled: external_exports.boolean().default(false).describe("Enable CORS configuration"), + publicAccess: external_exports.object({ + allowPublicRead: external_exports.boolean().default(false).describe("Allow public read access"), + allowPublicWrite: external_exports.boolean().default(false).describe("Allow public write access"), + allowPublicList: external_exports.boolean().default(false).describe("Allow public bucket listing") + }).optional().describe("Public access control"), + allowedIps: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses/CIDR blocks"), + blockedIps: external_exports.array(external_exports.string()).optional().describe("Blocked IP addresses/CIDR blocks") +}); +var LifecyclePolicyRuleSchema3 = external_exports.object({ + id: SystemIdentifierSchema6.describe("Rule identifier"), + enabled: external_exports.boolean().default(true).describe("Enable this rule"), + action: LifecycleActionSchema3.describe("Action to perform"), + prefix: external_exports.string().optional().describe('Object key prefix filter (e.g., "uploads/")'), + tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Object tag filters"), + daysAfterCreation: external_exports.number().min(0).optional().describe("Days after object creation"), + daysAfterModification: external_exports.number().min(0).optional().describe("Days after last modification"), + targetStorageClass: StorageClassSchema3.optional().describe("Target storage class for transition action") +}).refine((data) => { + if (data.action === "transition" && !data.targetStorageClass) { + return false; + } + return true; +}, { + message: 'targetStorageClass is required when action is "transition"' +}); +var LifecyclePolicyConfigSchema3 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable lifecycle policies"), + rules: external_exports.array(LifecyclePolicyRuleSchema3).default([]).describe("Lifecycle rules") +}); +var BucketConfigSchema3 = external_exports.object({ + name: SystemIdentifierSchema6.describe("Bucket identifier in ObjectStack (snake_case)"), + label: external_exports.string().describe("Display label"), + bucketName: external_exports.string().describe("Actual bucket/container name in storage provider"), + region: external_exports.string().optional().describe("Storage region (e.g., us-east-1, westus)"), + provider: StorageProviderSchema3.describe("Storage provider"), + endpoint: external_exports.string().optional().describe("Custom endpoint URL (for S3-compatible providers)"), + pathStyle: external_exports.boolean().default(false).describe("Use path-style URLs (for S3-compatible providers)"), + versioning: external_exports.boolean().default(false).describe("Enable object versioning"), + encryption: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable server-side encryption"), + algorithm: external_exports.enum(["AES256", "aws:kms", "azure:kms", "gcp:kms"]).default("AES256").describe("Encryption algorithm"), + kmsKeyId: external_exports.string().optional().describe("KMS key ID for managed encryption") + }).optional().describe("Server-side encryption configuration"), + accessControl: AccessControlConfigSchema3.optional().describe("Access control configuration"), + lifecyclePolicy: LifecyclePolicyConfigSchema3.optional().describe("Lifecycle policy configuration"), + multipartConfig: MultipartUploadConfigSchema3.optional().describe("Multipart upload configuration"), + tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Bucket tags for organization"), + description: external_exports.string().optional().describe("Bucket description"), + enabled: external_exports.boolean().default(true).describe("Enable this bucket") +}); +var StorageConnectionSchema3 = external_exports.object({ + // AWS S3 / MinIO + accessKeyId: external_exports.string().optional().describe("AWS access key ID or MinIO access key"), + secretAccessKey: external_exports.string().optional().describe("AWS secret access key or MinIO secret key"), + sessionToken: external_exports.string().optional().describe("AWS session token for temporary credentials"), + // Azure Blob Storage + accountName: external_exports.string().optional().describe("Azure storage account name"), + accountKey: external_exports.string().optional().describe("Azure storage account key"), + sasToken: external_exports.string().optional().describe("Azure SAS token"), + // Google Cloud Storage + projectId: external_exports.string().optional().describe("GCP project ID"), + credentials: external_exports.string().optional().describe("GCP service account credentials JSON"), + // Common + endpoint: external_exports.string().optional().describe("Custom endpoint URL"), + region: external_exports.string().optional().describe("Default region"), + useSSL: external_exports.boolean().default(true).describe("Use SSL/TLS for connections"), + timeout: external_exports.number().min(0).optional().describe("Connection timeout in milliseconds") +}); +var ObjectStorageConfigSchema3 = external_exports.object({ + name: SystemIdentifierSchema6.describe("Storage configuration identifier"), + label: external_exports.string().describe("Display label"), + provider: StorageProviderSchema3.describe("Primary storage provider"), + /** + * Storage scope + * Defines the lifecycle and access pattern for this storage + */ + scope: StorageScopeSchema3.optional().default("global").describe("Storage scope"), + connection: StorageConnectionSchema3.describe("Connection credentials"), + buckets: external_exports.array(BucketConfigSchema3).default([]).describe("Configured buckets"), + defaultBucket: external_exports.string().optional().describe("Default bucket name for operations"), + /** + * Base path or location + * For local/scoped storage configurations + */ + location: external_exports.string().optional().describe("Root path (local) or base location"), + /** + * Storage quota in bytes + */ + quota: external_exports.number().int().positive().optional().describe("Max size in bytes"), + /** + * Provider-specific options + */ + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration options"), + enabled: external_exports.boolean().default(true).describe("Enable this storage configuration"), + description: external_exports.string().optional().describe("Configuration description") +}); +var s3StorageExample2 = ObjectStorageConfigSchema3.parse({ + name: "aws_s3_storage", + label: "AWS S3 Production Storage", + provider: "s3", + connection: { + accessKeyId: "${AWS_ACCESS_KEY_ID}", + secretAccessKey: "${AWS_SECRET_ACCESS_KEY}", + region: "us-east-1" + }, + buckets: [ + { + name: "user_uploads", + label: "User Uploads", + bucketName: "my-app-user-uploads", + region: "us-east-1", + provider: "s3", + versioning: true, + encryption: { + enabled: true, + algorithm: "aws:kms", + kmsKeyId: "${AWS_KMS_KEY_ID}" + }, + accessControl: { + acl: "private", + corsEnabled: true, + allowedOrigins: ["https://app.example.com"], + allowedMethods: ["GET", "PUT", "POST"] + }, + lifecyclePolicy: { + enabled: true, + rules: [ + { + id: "archive_old_uploads", + enabled: true, + action: "transition", + daysAfterCreation: 90, + targetStorageClass: "glacier" + } + ] + }, + multipartConfig: { + enabled: true, + partSize: 10 * 1024 * 1024, + threshold: 100 * 1024 * 1024, + maxConcurrent: 4 + } + } + ], + defaultBucket: "user_uploads", + enabled: true +}); +var minioStorageExample2 = ObjectStorageConfigSchema3.parse({ + name: "minio_local", + label: "MinIO Local Storage", + provider: "minio", + connection: { + accessKeyId: "minioadmin", + secretAccessKey: "minioadmin", + endpoint: "http://localhost:9000", + useSSL: false + }, + buckets: [ + { + name: "development_files", + label: "Development Files", + bucketName: "dev-files", + provider: "minio", + endpoint: "http://localhost:9000", + pathStyle: true, + accessControl: { + acl: "private" + } + } + ], + defaultBucket: "development_files", + enabled: true +}); +var azureBlobStorageExample2 = ObjectStorageConfigSchema3.parse({ + name: "azure_blob_storage", + label: "Azure Blob Storage", + provider: "azure_blob", + connection: { + accountName: "mystorageaccount", + accountKey: "${AZURE_STORAGE_KEY}", + endpoint: "https://mystorageaccount.blob.core.windows.net" + }, + buckets: [ + { + name: "media_files", + label: "Media Files", + bucketName: "media", + provider: "azure_blob", + region: "eastus", + accessControl: { + acl: "public_read", + publicAccess: { + allowPublicRead: true, + allowPublicWrite: false, + allowPublicList: false + } + } + } + ], + defaultBucket: "media_files", + enabled: true +}); +var gcsStorageExample2 = ObjectStorageConfigSchema3.parse({ + name: "gcs_storage", + label: "Google Cloud Storage", + provider: "gcs", + connection: { + projectId: "my-gcp-project", + credentials: "${GCP_SERVICE_ACCOUNT_JSON}" + }, + buckets: [ + { + name: "backup_storage", + label: "Backup Storage", + bucketName: "my-app-backups", + region: "us-central1", + provider: "gcs", + lifecyclePolicy: { + enabled: true, + rules: [ + { + id: "delete_old_backups", + enabled: true, + action: "delete", + daysAfterCreation: 30 + } + ] + } + } + ], + defaultBucket: "backup_storage", + enabled: true +}); +var SearchProviderSchema2 = external_exports.enum([ + "elasticsearch", + "algolia", + "meilisearch", + "typesense", + "opensearch" +]).describe("Supported full-text search engine provider"); +var AnalyzerConfigSchema2 = external_exports.object({ + type: external_exports.enum(["standard", "simple", "whitespace", "keyword", "pattern", "language"]).describe("Text analyzer type"), + language: external_exports.string().optional().describe("Language for language-specific analysis"), + stopwords: external_exports.array(external_exports.string()).optional().describe("Custom stopwords to filter during analysis"), + customFilters: external_exports.array(external_exports.string()).optional().describe("Additional token filter names to apply") +}).describe("Text analyzer configuration for index tokenization and normalization"); +var SearchIndexConfigSchema2 = external_exports.object({ + indexName: external_exports.string().describe("Name of the search index"), + objectName: external_exports.string().describe("Source ObjectQL object"), + fields: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Field name to index"), + type: external_exports.enum(["text", "keyword", "number", "date", "boolean", "geo"]).describe("Index field data type"), + analyzer: external_exports.string().optional().describe("Named analyzer to use for this field"), + searchable: external_exports.boolean().default(true).describe("Include field in full-text search"), + filterable: external_exports.boolean().default(false).describe("Allow filtering on this field"), + sortable: external_exports.boolean().default(false).describe("Allow sorting by this field"), + boost: external_exports.number().default(1).describe("Relevance boost factor for this field") + })).describe("Fields to include in the search index"), + replicas: external_exports.number().default(1).describe("Number of index replicas for availability"), + shards: external_exports.number().default(1).describe("Number of index shards for distribution") +}).describe("Search index definition mapping an ObjectQL object to a search engine index"); +var FacetConfigSchema2 = external_exports.object({ + field: external_exports.string().describe("Field name to generate facets from"), + maxValues: external_exports.number().default(10).describe("Maximum number of facet values to return"), + sort: external_exports.enum(["count", "alpha"]).default("count").describe("Facet value sort order") +}).describe("Faceted search configuration for a single field"); +var SearchConfigSchema22 = external_exports.object({ + provider: SearchProviderSchema2.describe("Search engine backend provider"), + indexes: external_exports.array(SearchIndexConfigSchema2).describe("Search index definitions"), + analyzers: external_exports.record(external_exports.string(), AnalyzerConfigSchema2).optional().describe("Named text analyzer configurations"), + facets: external_exports.array(FacetConfigSchema2).optional().describe("Faceted search configurations"), + typoTolerance: external_exports.boolean().default(true).describe("Enable typo-tolerant search"), + synonyms: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional().describe("Synonym mappings for search expansion"), + ranking: external_exports.array(external_exports.enum(["typo", "geo", "words", "filters", "proximity", "attribute", "exact", "custom"])).optional().describe("Custom ranking rule order") +}).describe("Top-level full-text search engine configuration"); +var HttpServerConfigSchema3 = external_exports.object({ + /** + * Server port number + */ + port: external_exports.number().int().min(1).max(65535).default(3e3).describe("Port number to listen on"), + /** + * Server host address + */ + host: external_exports.string().default("0.0.0.0").describe("Host address to bind to"), + /** + * CORS configuration + */ + cors: CorsConfigSchema4.optional().describe("CORS configuration"), + /** + * Request handling options + */ + requestTimeout: external_exports.number().int().default(3e4).describe("Request timeout in milliseconds"), + bodyLimit: external_exports.string().default("10mb").describe("Maximum request body size"), + /** + * Compression settings + */ + compression: external_exports.boolean().default(true).describe("Enable response compression"), + /** + * Security headers + */ + security: external_exports.object({ + helmet: external_exports.boolean().default(true).describe("Enable security headers via helmet"), + rateLimit: RateLimitConfigSchema4.optional().describe("Global rate limiting configuration") + }).optional().describe("Security configuration"), + /** + * Static file serving + */ + static: external_exports.array(StaticMountSchema4).optional().describe("Static file serving configuration"), + /** + * Trust proxy settings + */ + trustProxy: external_exports.boolean().default(false).describe("Trust X-Forwarded-* headers") +}); +var RouteHandlerMetadataSchema2 = external_exports.object({ + /** + * HTTP method + */ + method: HttpMethod5.describe("HTTP method"), + /** + * URL path pattern (supports parameters like /api/users/:id) + */ + path: external_exports.string().describe("URL path pattern"), + /** + * Handler function name or identifier + */ + handler: external_exports.string().describe("Handler identifier or name"), + /** + * Route metadata + */ + metadata: external_exports.object({ + summary: external_exports.string().optional().describe("Route summary for documentation"), + description: external_exports.string().optional().describe("Route description"), + tags: external_exports.array(external_exports.string()).optional().describe("Tags for grouping"), + operationId: external_exports.string().optional().describe("Unique operation identifier") + }).optional(), + /** + * Security requirements + */ + security: external_exports.object({ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + rateLimit: external_exports.string().optional().describe("Rate limit policy override") + }).optional() +}); +var MiddlewareType3 = external_exports.enum([ + "authentication", + // Authentication middleware + "authorization", + // Authorization/permission checks + "logging", + // Request/response logging + "validation", + // Input validation + "transformation", + // Request/response transformation + "error", + // Error handling + "custom" + // Custom middleware +]); +var MiddlewareConfigSchema3 = external_exports.object({ + /** + * Middleware identifier + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Middleware name (snake_case)"), + /** + * Middleware type + */ + type: MiddlewareType3.describe("Middleware type"), + /** + * Enable/disable middleware + */ + enabled: external_exports.boolean().default(true).describe("Whether middleware is enabled"), + /** + * Execution order (lower numbers execute first) + */ + order: external_exports.number().int().default(100).describe("Execution order priority"), + /** + * Middleware-specific configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Middleware configuration object"), + /** + * Path patterns to apply middleware to + */ + paths: external_exports.object({ + include: external_exports.array(external_exports.string()).optional().describe("Include path patterns (glob)"), + exclude: external_exports.array(external_exports.string()).optional().describe("Exclude path patterns (glob)") + }).optional().describe("Path filtering") +}); +var ServerEventType3 = external_exports.enum([ + "starting", + // Server is starting + "started", + // Server has started and is listening + "stopping", + // Server is stopping + "stopped", + // Server has stopped + "request", + // Request received + "response", + // Response sent + "error" + // Error occurred +]); +var ServerEventSchema2 = external_exports.object({ + /** + * Event type + */ + type: ServerEventType3.describe("Event type"), + /** + * Timestamp + */ + timestamp: external_exports.string().datetime().describe("Event timestamp (ISO 8601)"), + /** + * Event payload + */ + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific data") +}); +var ServerCapabilitiesSchema2 = external_exports.object({ + /** + * Supported HTTP versions + */ + httpVersions: external_exports.array(external_exports.enum(["1.0", "1.1", "2.0", "3.0"])).default(["1.1"]).describe("Supported HTTP versions"), + /** + * WebSocket support + */ + websocket: external_exports.boolean().default(false).describe("WebSocket support"), + /** + * Server-Sent Events support + */ + sse: external_exports.boolean().default(false).describe("Server-Sent Events support"), + /** + * HTTP/2 Server Push + */ + serverPush: external_exports.boolean().default(false).describe("HTTP/2 Server Push support"), + /** + * Streaming support + */ + streaming: external_exports.boolean().default(true).describe("Response streaming support"), + /** + * Middleware support + */ + middleware: external_exports.boolean().default(true).describe("Middleware chain support"), + /** + * Route parameterization + */ + routeParams: external_exports.boolean().default(true).describe("URL parameter support (/users/:id)"), + /** + * Built-in compression + */ + compression: external_exports.boolean().default(true).describe("Built-in compression support") +}); +var ServerStatusSchema2 = external_exports.object({ + /** + * Server state + */ + state: external_exports.enum(["stopped", "starting", "running", "stopping", "error"]).describe("Current server state"), + /** + * Uptime in milliseconds + */ + uptime: external_exports.number().int().optional().describe("Server uptime in milliseconds"), + /** + * Server information + */ + server: external_exports.object({ + port: external_exports.number().int().describe("Listening port"), + host: external_exports.string().describe("Bound host"), + url: external_exports.string().optional().describe("Full server URL") + }).optional(), + /** + * Connection metrics + */ + connections: external_exports.object({ + active: external_exports.number().int().describe("Active connections"), + total: external_exports.number().int().describe("Total connections handled") + }).optional(), + /** + * Request metrics + */ + requests: external_exports.object({ + total: external_exports.number().int().describe("Total requests processed"), + success: external_exports.number().int().describe("Successful requests"), + errors: external_exports.number().int().describe("Failed requests") + }).optional() +}); +var HttpServerConfig2 = Object.assign(HttpServerConfigSchema3, { + create: (config4) => config4 +}); +var MiddlewareConfig2 = Object.assign(MiddlewareConfigSchema3, { + create: (config4) => config4 +}); +var AuditEventType2 = external_exports.enum([ + // Data Operations (CRUD) + "data.create", + // Record creation + "data.read", + // Record retrieval/viewing + "data.update", + // Record modification + "data.delete", + // Record deletion + "data.export", + // Data export operations + "data.import", + // Data import operations + "data.bulk_update", + // Bulk update operations + "data.bulk_delete", + // Bulk delete operations + // Authentication Events + "auth.login", + // Successful login + "auth.login_failed", + // Failed login attempt + "auth.logout", + // User logout + "auth.session_created", + // New session created + "auth.session_expired", + // Session expiration + "auth.password_reset", + // Password reset initiated + "auth.password_changed", + // Password successfully changed + "auth.email_verified", + // Email verification completed + "auth.mfa_enabled", + // Multi-factor auth enabled + "auth.mfa_disabled", + // Multi-factor auth disabled + "auth.account_locked", + // Account locked (too many failures) + "auth.account_unlocked", + // Account unlocked + // Authorization Events + "authz.permission_granted", + // Permission granted to user + "authz.permission_revoked", + // Permission revoked from user + "authz.role_assigned", + // Role assigned to user + "authz.role_removed", + // Role removed from user + "authz.role_created", + // New role created + "authz.role_updated", + // Role permissions modified + "authz.role_deleted", + // Role deleted + "authz.policy_created", + // Security policy created + "authz.policy_updated", + // Security policy updated + "authz.policy_deleted", + // Security policy deleted + // System Events + "system.config_changed", + // System configuration modified + "system.plugin_installed", + // Plugin installed + "system.plugin_uninstalled", + // Plugin uninstalled + "system.backup_created", + // Backup created + "system.backup_restored", + // Backup restored + "system.integration_added", + // External integration added + "system.integration_removed", + // External integration removed + // Security Events + "security.access_denied", + // Access denied (authorization failure) + "security.suspicious_activity", + // Suspicious activity detected + "security.data_breach", + // Potential data breach detected + "security.api_key_created", + // API key created + "security.api_key_revoked" + // API key revoked +]); +var AuditEventSeverity2 = external_exports.enum([ + "debug", + // Diagnostic information + "info", + // Informational events (normal operations) + "notice", + // Normal but significant events + "warning", + // Warning conditions + "error", + // Error conditions + "critical", + // Critical conditions requiring immediate attention + "alert", + // Action must be taken immediately + "emergency" + // System is unusable +]); +var AuditEventActorSchema2 = external_exports.object({ + /** + * Actor type (user, system, service, api_client, etc.) + */ + type: external_exports.enum(["user", "system", "service", "api_client", "integration"]).describe("Actor type"), + /** + * Unique identifier for the actor + */ + id: external_exports.string().describe("Actor identifier"), + /** + * Display name of the actor + */ + name: external_exports.string().optional().describe("Actor display name"), + /** + * Email address (for user actors) + */ + email: external_exports.string().email().optional().describe("Actor email address"), + /** + * IP address of the actor + */ + ipAddress: external_exports.string().optional().describe("Actor IP address"), + /** + * User agent string (for web/API requests) + */ + userAgent: external_exports.string().optional().describe("User agent string") +}); +var AuditEventTargetSchema2 = external_exports.object({ + /** + * Target type (e.g., 'object', 'record', 'user', 'role', 'config') + */ + type: external_exports.string().describe("Target type"), + /** + * Unique identifier for the target + */ + id: external_exports.string().describe("Target identifier"), + /** + * Display name of the target + */ + name: external_exports.string().optional().describe("Target display name"), + /** + * Additional metadata about the target + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Target metadata") +}); +var AuditEventChangeSchema2 = external_exports.object({ + /** + * Field/property that changed + */ + field: external_exports.string().describe("Changed field name"), + /** + * Value before the change + */ + oldValue: external_exports.unknown().optional().describe("Previous value"), + /** + * Value after the change + */ + newValue: external_exports.unknown().optional().describe("New value") +}); +var AuditEventSchema2 = external_exports.object({ + /** + * Unique identifier for this audit event + */ + id: external_exports.string().describe("Audit event ID"), + /** + * Type of event being audited + */ + eventType: AuditEventType2.describe("Event type"), + /** + * Severity level of the event + */ + severity: AuditEventSeverity2.default("info").describe("Event severity"), + /** + * Timestamp when the event occurred (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("Event timestamp"), + /** + * Who/what performed the action + */ + actor: AuditEventActorSchema2.describe("Event actor"), + /** + * What was acted upon + */ + target: AuditEventTargetSchema2.optional().describe("Event target"), + /** + * Human-readable description of the action + */ + description: external_exports.string().describe("Event description"), + /** + * Detailed changes (for update operations) + */ + changes: external_exports.array(AuditEventChangeSchema2).optional().describe("List of changes"), + /** + * Result of the action (success, failure, partial) + */ + result: external_exports.enum(["success", "failure", "partial"]).default("success").describe("Action result"), + /** + * Error message (if result is failure) + */ + errorMessage: external_exports.string().optional().describe("Error message"), + /** + * Tenant identifier (for multi-tenant systems) + */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** + * Request/trace ID for correlation + */ + requestId: external_exports.string().optional().describe("Request ID for tracing"), + /** + * Additional context and metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata"), + /** + * Geographic location (if available) + */ + location: external_exports.object({ + country: external_exports.string().optional(), + region: external_exports.string().optional(), + city: external_exports.string().optional() + }).optional().describe("Geographic location") +}); +var AuditRetentionPolicySchema2 = external_exports.object({ + /** + * Retention period in days + * Default: 180 days (GDPR 6-month requirement) + */ + retentionDays: external_exports.number().int().min(1).default(180).describe("Retention period in days"), + /** + * Whether to archive logs after retention period + * If true, logs are moved to cold storage; if false, they are deleted + */ + archiveAfterRetention: external_exports.boolean().default(true).describe("Archive logs after retention period"), + /** + * Archive storage configuration + */ + archiveStorage: external_exports.object({ + type: external_exports.enum(["s3", "gcs", "azure_blob", "filesystem"]).describe("Archive storage type"), + endpoint: external_exports.string().optional().describe("Storage endpoint URL"), + bucket: external_exports.string().optional().describe("Storage bucket/container name"), + path: external_exports.string().optional().describe("Storage path prefix"), + credentials: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage credentials") + }).optional().describe("Archive storage configuration"), + /** + * Event types that have different retention periods + * Overrides the default retentionDays for specific event types + */ + customRetention: external_exports.record(external_exports.string(), external_exports.number().int().positive()).optional().describe("Custom retention by event type"), + /** + * Minimum retention period for compliance + * Prevents accidental deletion below compliance requirements + */ + minimumRetentionDays: external_exports.number().int().positive().optional().describe("Minimum retention for compliance") +}); +var SuspiciousActivityRuleSchema2 = external_exports.object({ + /** + * Unique identifier for the rule + */ + id: external_exports.string().describe("Rule identifier"), + /** + * Rule name + */ + name: external_exports.string().describe("Rule name"), + /** + * Rule description + */ + description: external_exports.string().optional().describe("Rule description"), + /** + * Whether the rule is enabled + */ + enabled: external_exports.boolean().default(true).describe("Rule enabled status"), + /** + * Event types to monitor + */ + eventTypes: external_exports.array(AuditEventType2).describe("Event types to monitor"), + /** + * Detection condition + */ + condition: external_exports.object({ + /** + * Number of events that trigger the rule + */ + threshold: external_exports.number().int().positive().describe("Event threshold"), + /** + * Time window in seconds + */ + windowSeconds: external_exports.number().int().positive().describe("Time window in seconds"), + /** + * Grouping criteria (e.g., by actor.id, by ipAddress) + */ + groupBy: external_exports.array(external_exports.string()).optional().describe("Grouping criteria"), + /** + * Additional filters + */ + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional filters") + }).describe("Detection condition"), + /** + * Actions to take when rule is triggered + */ + actions: external_exports.array(external_exports.enum([ + "alert", + // Send alert notification + "lock_account", + // Lock the user account + "block_ip", + // Block the IP address + "require_mfa", + // Require multi-factor authentication + "log_critical", + // Log as critical event + "webhook" + // Call webhook + ])).describe("Actions to take"), + /** + * Severity level for triggered alerts + */ + alertSeverity: AuditEventSeverity2.default("warning").describe("Alert severity"), + /** + * Notification configuration + */ + notifications: external_exports.object({ + /** + * Email addresses to notify + */ + email: external_exports.array(external_exports.string().email()).optional().describe("Email recipients"), + /** + * Slack webhook URL + */ + slack: external_exports.string().url().optional().describe("Slack webhook URL"), + /** + * Custom webhook URL + */ + webhook: external_exports.string().url().optional().describe("Custom webhook URL") + }).optional().describe("Notification configuration") +}); +var AuditStorageConfigSchema2 = external_exports.object({ + /** + * Storage backend type + */ + type: external_exports.enum([ + "database", + // Store in database (PostgreSQL, MySQL, etc.) + "elasticsearch", + // Store in Elasticsearch + "mongodb", + // Store in MongoDB + "clickhouse", + // Store in ClickHouse (for analytics) + "s3", + // Store in S3-compatible storage + "gcs", + // Store in Google Cloud Storage + "azure_blob", + // Store in Azure Blob Storage + "custom" + // Custom storage implementation + ]).describe("Storage backend type"), + /** + * Connection string or configuration + */ + connectionString: external_exports.string().optional().describe("Connection string"), + /** + * Storage configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage-specific configuration"), + /** + * Whether to enable buffering/batching + */ + bufferEnabled: external_exports.boolean().default(true).describe("Enable buffering"), + /** + * Buffer size (number of events before flush) + */ + bufferSize: external_exports.number().int().positive().default(100).describe("Buffer size"), + /** + * Buffer flush interval in seconds + */ + flushIntervalSeconds: external_exports.number().int().positive().default(5).describe("Flush interval in seconds"), + /** + * Whether to compress stored data + */ + compression: external_exports.boolean().default(true).describe("Enable compression") +}); +var AuditEventFilterSchema2 = external_exports.object({ + /** + * Filter by event types + */ + eventTypes: external_exports.array(AuditEventType2).optional().describe("Event types to include"), + /** + * Filter by severity levels + */ + severities: external_exports.array(AuditEventSeverity2).optional().describe("Severity levels to include"), + /** + * Filter by actor ID + */ + actorId: external_exports.string().optional().describe("Actor identifier"), + /** + * Filter by tenant ID + */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** + * Filter by time range + */ + timeRange: external_exports.object({ + from: external_exports.string().datetime().describe("Start time"), + to: external_exports.string().datetime().describe("End time") + }).optional().describe("Time range filter"), + /** + * Filter by result status + */ + result: external_exports.enum(["success", "failure", "partial"]).optional().describe("Result status"), + /** + * Search query (full-text search) + */ + searchQuery: external_exports.string().optional().describe("Search query"), + /** + * Custom filters + */ + customFilters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom filters") +}); +var AuditConfigSchema2 = external_exports.object({ + /** + * Unique identifier for this audit configuration + * Must be in snake_case following ObjectStack conventions + * Maximum length: 64 characters + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), + /** + * Human-readable label + */ + label: external_exports.string().describe("Display label"), + /** + * Whether audit logging is enabled + */ + enabled: external_exports.boolean().default(true).describe("Enable audit logging"), + /** + * Event types to audit + * If not specified, all event types are audited + */ + eventTypes: external_exports.array(AuditEventType2).optional().describe("Event types to audit"), + /** + * Event types to exclude from auditing + */ + excludeEventTypes: external_exports.array(AuditEventType2).optional().describe("Event types to exclude"), + /** + * Minimum severity level to log + * Events below this level are not logged + */ + minimumSeverity: AuditEventSeverity2.default("info").describe("Minimum severity level"), + /** + * Storage configuration + */ + storage: AuditStorageConfigSchema2.describe("Storage configuration"), + /** + * Retention policy + */ + retentionPolicy: AuditRetentionPolicySchema2.optional().describe("Retention policy"), + /** + * Suspicious activity detection rules + */ + suspiciousActivityRules: external_exports.array(SuspiciousActivityRuleSchema2).default([]).describe("Suspicious activity rules"), + /** + * Whether to include sensitive data in audit logs + * If false, sensitive fields are redacted/masked + */ + includeSensitiveData: external_exports.boolean().default(false).describe("Include sensitive data"), + /** + * Fields to redact from audit logs + */ + redactFields: external_exports.array(external_exports.string()).default([ + "password", + "passwordHash", + "token", + "apiKey", + "secret", + "creditCard", + "ssn" + ]).describe("Fields to redact"), + /** + * Whether to log successful read operations + * Can be disabled to reduce log volume + */ + logReads: external_exports.boolean().default(false).describe("Log read operations"), + /** + * Sampling rate for read operations (0.0 to 1.0) + * Only applies if logReads is true + */ + readSamplingRate: external_exports.number().min(0).max(1).default(0.1).describe("Read sampling rate"), + /** + * Whether to log system/internal operations + */ + logSystemEvents: external_exports.boolean().default(true).describe("Log system events"), + /** + * Custom audit event handlers + * Note: Function handlers are for runtime configuration only and will not be serialized to JSON Schema + */ + customHandlers: external_exports.array(external_exports.object({ + eventType: AuditEventType2.describe("Event type to handle"), + handlerId: external_exports.string().describe("Unique identifier for the handler") + })).optional().describe("Custom event handler references"), + /** + * Compliance mode configuration + */ + compliance: external_exports.object({ + /** + * Compliance standards to enforce + */ + standards: external_exports.array(external_exports.enum([ + "sox", + // Sarbanes-Oxley Act + "hipaa", + // Health Insurance Portability and Accountability Act + "gdpr", + // General Data Protection Regulation + "pci_dss", + // Payment Card Industry Data Security Standard + "iso_27001", + // ISO/IEC 27001 + "fedramp" + // Federal Risk and Authorization Management Program + ])).optional().describe("Compliance standards"), + /** + * Whether to enforce immutable audit logs + */ + immutableLogs: external_exports.boolean().default(true).describe("Enforce immutable logs"), + /** + * Whether to require cryptographic signing + */ + requireSigning: external_exports.boolean().default(false).describe("Require log signing"), + /** + * Signing key configuration + */ + signingKey: external_exports.string().optional().describe("Signing key") + }).optional().describe("Compliance configuration") +}); +var DEFAULT_SUSPICIOUS_ACTIVITY_RULES = [ + { + id: "multiple_failed_logins", + name: "Multiple Failed Login Attempts", + description: "Detects multiple failed login attempts from the same user or IP", + enabled: true, + eventTypes: ["auth.login_failed"], + condition: { + threshold: 5, + windowSeconds: 600, + // 10 minutes + groupBy: ["actor.id", "actor.ipAddress"] + }, + actions: ["alert", "lock_account"], + alertSeverity: "warning" + }, + { + id: "bulk_data_export", + name: "Bulk Data Export", + description: "Detects large data export operations", + enabled: true, + eventTypes: ["data.export"], + condition: { + threshold: 3, + windowSeconds: 3600, + // 1 hour + groupBy: ["actor.id"] + }, + actions: ["alert", "log_critical"], + alertSeverity: "warning" + }, + { + id: "suspicious_permission_changes", + name: "Rapid Permission Changes", + description: "Detects rapid permission or role changes", + enabled: true, + eventTypes: ["authz.permission_granted", "authz.role_assigned"], + condition: { + threshold: 10, + windowSeconds: 300, + // 5 minutes + groupBy: ["actor.id"] + }, + actions: ["alert", "log_critical"], + alertSeverity: "critical" + }, + { + id: "after_hours_access", + name: "After Hours Access", + description: "Detects access during non-business hours", + enabled: false, + // Disabled by default, requires time zone configuration + eventTypes: ["auth.login"], + condition: { + threshold: 1, + windowSeconds: 86400 + // 24 hours + }, + actions: ["alert"], + alertSeverity: "notice" + } +]; +var LogLevel2 = external_exports.enum([ + "debug", + "info", + "warn", + "error", + "fatal", + "silent" +]).describe("Log severity level"); +var LogFormat2 = external_exports.enum([ + "json", + // Structured JSON for machine parsing + "text", + // Simple text format + "pretty" + // Colored human-readable output for CLI/console +]).describe("Log output format"); +var LoggerConfigSchema2 = external_exports.object({ + /** + * Logger name + */ + name: external_exports.string().optional().describe("Logger name identifier"), + /** + * Minimum level to log + */ + level: LogLevel2.optional().default("info"), + /** + * Output format + */ + format: LogFormat2.optional().default("json"), + /** + * Redact sensitive keys + */ + redact: external_exports.array(external_exports.string()).optional().default(["password", "token", "secret", "key"]).describe("Keys to redact from log context"), + /** + * Enable source location (file/line) + */ + sourceLocation: external_exports.boolean().optional().default(false).describe("Include file and line number"), + /** + * Log to file (optional) + */ + file: external_exports.string().optional().describe("Path to log file"), + /** + * Log rotation config (if file is set) + */ + rotation: external_exports.object({ + maxSize: external_exports.string().optional().default("10m"), + maxFiles: external_exports.number().optional().default(5) + }).optional() +}); +var LogEntrySchema2 = external_exports.object({ + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), + level: LogLevel2, + message: external_exports.string().describe("Log message"), + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Structured context data"), + error: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Error object if present"), + /** Tracing */ + traceId: external_exports.string().optional().describe("Distributed trace ID"), + spanId: external_exports.string().optional().describe("Span ID"), + /** Source */ + service: external_exports.string().optional().describe("Service name"), + component: external_exports.string().optional().describe("Component name (e.g. plugin id)") +}); +var ExtendedLogLevel2 = external_exports.enum([ + "trace", + // Very detailed debugging information + "debug", + // Debugging information + "info", + // Informational messages + "warn", + // Warning messages + "error", + // Error messages + "fatal" + // Fatal errors causing shutdown +]).describe("Extended log severity level"); +var LogDestinationType2 = external_exports.enum([ + "console", + // Standard output/error + "file", + // File system + "syslog", + // System logger + "elasticsearch", + // Elasticsearch + "cloudwatch", + // AWS CloudWatch + "stackdriver", + // Google Cloud Logging + "azure_monitor", + // Azure Monitor + "datadog", + // Datadog + "splunk", + // Splunk + "loki", + // Grafana Loki + "http", + // HTTP endpoint + "kafka", + // Apache Kafka + "redis", + // Redis streams + "custom" + // Custom implementation +]).describe("Log destination type"); +var ConsoleDestinationConfigSchema2 = external_exports.object({ + /** + * Output stream + */ + stream: external_exports.enum(["stdout", "stderr"]).optional().default("stdout"), + /** + * Enable colored output + */ + colors: external_exports.boolean().optional().default(true), + /** + * Pretty print JSON + */ + prettyPrint: external_exports.boolean().optional().default(false) +}).describe("Console destination configuration"); +var FileDestinationConfigSchema2 = external_exports.object({ + /** + * File path + */ + path: external_exports.string().describe("Log file path"), + /** + * Enable log rotation + */ + rotation: external_exports.object({ + /** + * Maximum file size before rotation (e.g., '10m', '100k', '1g') + */ + maxSize: external_exports.string().optional().default("10m"), + /** + * Maximum number of files to keep + */ + maxFiles: external_exports.number().int().positive().optional().default(5), + /** + * Compress rotated files + */ + compress: external_exports.boolean().optional().default(true), + /** + * Rotation interval (e.g., 'daily', 'weekly') + */ + interval: external_exports.enum(["hourly", "daily", "weekly", "monthly"]).optional() + }).optional(), + /** + * File encoding + */ + encoding: external_exports.string().optional().default("utf8"), + /** + * Append to existing file + */ + append: external_exports.boolean().optional().default(true) +}).describe("File destination configuration"); +var HttpDestinationConfigSchema2 = external_exports.object({ + /** + * HTTP endpoint URL + */ + url: external_exports.string().url().describe("HTTP endpoint URL"), + /** + * HTTP method + */ + method: external_exports.enum(["POST", "PUT"]).optional().default("POST"), + /** + * Headers to include + */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional(), + /** + * Authentication + */ + auth: external_exports.object({ + type: external_exports.enum(["basic", "bearer", "api_key"]).describe("Auth type"), + username: external_exports.string().optional(), + password: external_exports.string().optional(), + token: external_exports.string().optional(), + apiKey: external_exports.string().optional(), + apiKeyHeader: external_exports.string().optional().default("X-API-Key") + }).optional(), + /** + * Batch configuration + */ + batch: external_exports.object({ + /** + * Maximum batch size + */ + maxSize: external_exports.number().int().positive().optional().default(100), + /** + * Flush interval in milliseconds + */ + flushInterval: external_exports.number().int().positive().optional().default(5e3) + }).optional(), + /** + * Retry configuration + */ + retry: external_exports.object({ + /** + * Maximum retry attempts + */ + maxAttempts: external_exports.number().int().positive().optional().default(3), + /** + * Initial retry delay in milliseconds + */ + initialDelay: external_exports.number().int().positive().optional().default(1e3), + /** + * Backoff multiplier + */ + backoffMultiplier: external_exports.number().positive().optional().default(2) + }).optional(), + /** + * Timeout in milliseconds + */ + timeout: external_exports.number().int().positive().optional().default(3e4) +}).describe("HTTP destination configuration"); +var ExternalServiceDestinationConfigSchema2 = external_exports.object({ + /** + * Service-specific endpoint + */ + endpoint: external_exports.string().url().optional(), + /** + * Region (for cloud services) + */ + region: external_exports.string().optional(), + /** + * Credentials + */ + credentials: external_exports.object({ + accessKeyId: external_exports.string().optional(), + secretAccessKey: external_exports.string().optional(), + apiKey: external_exports.string().optional(), + projectId: external_exports.string().optional() + }).optional(), + /** + * Log group/stream/index name + */ + logGroup: external_exports.string().optional(), + logStream: external_exports.string().optional(), + index: external_exports.string().optional(), + /** + * Service-specific configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}).describe("External service destination configuration"); +var LogDestinationSchema2 = external_exports.object({ + /** + * Destination name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Destination name (snake_case)"), + /** + * Destination type + */ + type: LogDestinationType2.describe("Destination type"), + /** + * Minimum log level for this destination + */ + level: ExtendedLogLevel2.optional().default("info"), + /** + * Enabled flag + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Console configuration + */ + console: ConsoleDestinationConfigSchema2.optional(), + /** + * File configuration + */ + file: FileDestinationConfigSchema2.optional(), + /** + * HTTP configuration + */ + http: HttpDestinationConfigSchema2.optional(), + /** + * External service configuration + */ + externalService: ExternalServiceDestinationConfigSchema2.optional(), + /** + * Format for this destination + */ + format: external_exports.enum(["json", "text", "pretty"]).optional().default("json"), + /** + * Filter function reference (runtime only) + */ + filterId: external_exports.string().optional().describe("Filter function identifier") +}).describe("Log destination configuration"); +var LogEnrichmentConfigSchema2 = external_exports.object({ + /** + * Static fields to add to all logs + */ + staticFields: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Static fields added to every log"), + /** + * Dynamic field enrichers (runtime only) + * References to functions that add dynamic context + */ + dynamicEnrichers: external_exports.array(external_exports.string()).optional().describe("Dynamic enricher function IDs"), + /** + * Add hostname + */ + addHostname: external_exports.boolean().optional().default(true), + /** + * Add process ID + */ + addProcessId: external_exports.boolean().optional().default(true), + /** + * Add environment info + */ + addEnvironment: external_exports.boolean().optional().default(true), + /** + * Add timestamp in additional formats + */ + addTimestampFormats: external_exports.object({ + unix: external_exports.boolean().optional().default(false), + iso: external_exports.boolean().optional().default(true) + }).optional(), + /** + * Add caller information (file, line, function) + */ + addCaller: external_exports.boolean().optional().default(false), + /** + * Add correlation IDs + */ + addCorrelationIds: external_exports.boolean().optional().default(true) +}).describe("Log enrichment configuration"); +var StructuredLogEntrySchema2 = external_exports.object({ + /** + * Timestamp (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), + /** + * Log level + */ + level: ExtendedLogLevel2.describe("Log severity level"), + /** + * Log message + */ + message: external_exports.string().describe("Log message"), + /** + * Structured context data + */ + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Structured context"), + /** + * Error information + */ + error: external_exports.object({ + name: external_exports.string().optional(), + message: external_exports.string().optional(), + stack: external_exports.string().optional(), + code: external_exports.string().optional(), + details: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional().describe("Error details"), + /** + * Trace context + */ + trace: external_exports.object({ + traceId: external_exports.string().describe("Trace ID"), + spanId: external_exports.string().describe("Span ID"), + parentSpanId: external_exports.string().optional().describe("Parent span ID"), + traceFlags: external_exports.number().int().optional().describe("Trace flags") + }).optional().describe("Distributed tracing context"), + /** + * Source information + */ + source: external_exports.object({ + service: external_exports.string().optional().describe("Service name"), + component: external_exports.string().optional().describe("Component name"), + file: external_exports.string().optional().describe("Source file"), + line: external_exports.number().int().optional().describe("Line number"), + function: external_exports.string().optional().describe("Function name") + }).optional().describe("Source information"), + /** + * Host information + */ + host: external_exports.object({ + hostname: external_exports.string().optional(), + pid: external_exports.number().int().optional(), + ip: external_exports.string().optional() + }).optional().describe("Host information"), + /** + * Environment + */ + environment: external_exports.string().optional().describe("Environment (e.g., production, staging)"), + /** + * User information + */ + user: external_exports.object({ + id: external_exports.string().optional(), + username: external_exports.string().optional(), + email: external_exports.string().optional() + }).optional().describe("User context"), + /** + * Request information + */ + request: external_exports.object({ + id: external_exports.string().optional(), + method: external_exports.string().optional(), + path: external_exports.string().optional(), + userAgent: external_exports.string().optional(), + ip: external_exports.string().optional() + }).optional().describe("Request context"), + /** + * Custom labels/tags + */ + labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom labels"), + /** + * Additional metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata") +}).describe("Structured log entry"); +var LoggingConfigSchema2 = external_exports.object({ + /** + * Configuration name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Enable logging + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Global minimum log level + */ + level: ExtendedLogLevel2.optional().default("info"), + /** + * Default logger configuration + * Basic logger config for the kernel + */ + default: LoggerConfigSchema2.optional().describe("Default logger configuration"), + /** + * Named logger configurations + * Map of logger name to logger config for different components/modules + */ + loggers: external_exports.record(external_exports.string(), LoggerConfigSchema2).optional().describe("Named logger configurations"), + /** + * Log destinations + */ + destinations: external_exports.array(LogDestinationSchema2).describe("Log destinations"), + /** + * Log enrichment configuration + */ + enrichment: LogEnrichmentConfigSchema2.optional(), + /** + * Fields to redact from logs + */ + redact: external_exports.array(external_exports.string()).optional().default([ + "password", + "passwordHash", + "token", + "apiKey", + "secret", + "creditCard", + "ssn", + "authorization" + ]).describe("Fields to redact"), + /** + * Sampling configuration + */ + sampling: external_exports.object({ + /** + * Enable sampling + */ + enabled: external_exports.boolean().optional().default(false), + /** + * Sample rate (0.0 to 1.0) + */ + rate: external_exports.number().min(0).max(1).optional().default(1), + /** + * Sample rate by level + */ + rateByLevel: external_exports.record(external_exports.string(), external_exports.number().min(0).max(1)).optional() + }).optional(), + /** + * Buffer configuration + */ + buffer: external_exports.object({ + /** + * Enable buffering + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Buffer size + */ + size: external_exports.number().int().positive().optional().default(1e3), + /** + * Flush interval in milliseconds + */ + flushInterval: external_exports.number().int().positive().optional().default(1e3), + /** + * Flush on shutdown + */ + flushOnShutdown: external_exports.boolean().optional().default(true) + }).optional(), + /** + * Performance configuration + */ + performance: external_exports.object({ + /** + * Async logging + */ + async: external_exports.boolean().optional().default(true), + /** + * Worker threads for async logging + */ + workers: external_exports.number().int().positive().optional().default(1) + }).optional() +}).describe("Logging configuration"); +var MetricType2 = external_exports.enum([ + "counter", + // Monotonically increasing value + "gauge", + // Value that can go up and down + "histogram", + // Observations bucketed by configurable ranges + "summary" + // Observations with quantiles +]).describe("Metric type"); +var MetricUnit2 = external_exports.enum([ + // Time units + "nanoseconds", + "microseconds", + "milliseconds", + "seconds", + "minutes", + "hours", + "days", + // Size units + "bytes", + "kilobytes", + "megabytes", + "gigabytes", + "terabytes", + // Rate units + "requests_per_second", + "events_per_second", + "bytes_per_second", + // Percentage + "percent", + "ratio", + // Count + "count", + "operations", + // Custom + "custom" +]).describe("Metric unit"); +var MetricAggregationType2 = external_exports.enum([ + "sum", + // Sum of all values + "avg", + // Average of all values + "min", + // Minimum value + "max", + // Maximum value + "count", + // Count of observations + "p50", + // 50th percentile (median) + "p75", + // 75th percentile + "p90", + // 90th percentile + "p95", + // 95th percentile + "p99", + // 99th percentile + "p999", + // 99.9th percentile + "rate", + // Rate of change + "stddev" + // Standard deviation +]).describe("Metric aggregation type"); +var HistogramBucketConfigSchema2 = external_exports.object({ + /** + * Bucket type + */ + type: external_exports.enum(["linear", "exponential", "explicit"]).describe("Bucket type"), + /** + * Linear bucket configuration + */ + linear: external_exports.object({ + start: external_exports.number().describe("Start value"), + width: external_exports.number().positive().describe("Bucket width"), + count: external_exports.number().int().positive().describe("Number of buckets") + }).optional(), + /** + * Exponential bucket configuration + */ + exponential: external_exports.object({ + start: external_exports.number().positive().describe("Start value"), + factor: external_exports.number().positive().describe("Growth factor"), + count: external_exports.number().int().positive().describe("Number of buckets") + }).optional(), + /** + * Explicit bucket boundaries + */ + explicit: external_exports.object({ + boundaries: external_exports.array(external_exports.number()).describe("Bucket boundaries") + }).optional() +}).describe("Histogram bucket configuration"); +var MetricLabelsSchema2 = external_exports.record(external_exports.string(), external_exports.string()).describe("Metric labels"); +var MetricDefinitionSchema2 = external_exports.object({ + /** + * Metric name (snake_case) + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Metric name (snake_case)"), + /** + * Display label + */ + label: external_exports.string().optional().describe("Display label"), + /** + * Metric type + */ + type: MetricType2.describe("Metric type"), + /** + * Metric unit + */ + unit: MetricUnit2.optional().describe("Metric unit"), + /** + * Description + */ + description: external_exports.string().optional().describe("Metric description"), + /** + * Label names for this metric + */ + labelNames: external_exports.array(external_exports.string()).optional().default([]).describe("Label names"), + /** + * Histogram configuration (for histogram type) + */ + histogram: HistogramBucketConfigSchema2.optional(), + /** + * Summary configuration (for summary type) + */ + summary: external_exports.object({ + /** + * Quantiles to track + */ + quantiles: external_exports.array(external_exports.number().min(0).max(1)).optional().default([0.5, 0.9, 0.99]), + /** + * Max age of observations in seconds + */ + maxAge: external_exports.number().int().positive().optional().default(600), + /** + * Number of age buckets + */ + ageBuckets: external_exports.number().int().positive().optional().default(5) + }).optional(), + /** + * Enabled flag + */ + enabled: external_exports.boolean().optional().default(true) +}).describe("Metric definition"); +var MetricDataPointSchema2 = external_exports.object({ + /** + * Metric name + */ + name: external_exports.string().describe("Metric name"), + /** + * Metric type + */ + type: MetricType2.describe("Metric type"), + /** + * Timestamp (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("Observation timestamp"), + /** + * Value (for counter and gauge) + */ + value: external_exports.number().optional().describe("Metric value"), + /** + * Labels + */ + labels: MetricLabelsSchema2.optional().describe("Metric labels"), + /** + * Histogram data + */ + histogram: external_exports.object({ + count: external_exports.number().int().nonnegative().describe("Total count"), + sum: external_exports.number().describe("Sum of all values"), + buckets: external_exports.array(external_exports.object({ + upperBound: external_exports.number().describe("Upper bound of bucket"), + count: external_exports.number().int().nonnegative().describe("Count in bucket") + })).describe("Histogram buckets") + }).optional(), + /** + * Summary data + */ + summary: external_exports.object({ + count: external_exports.number().int().nonnegative().describe("Total count"), + sum: external_exports.number().describe("Sum of all values"), + quantiles: external_exports.array(external_exports.object({ + quantile: external_exports.number().min(0).max(1).describe("Quantile (0-1)"), + value: external_exports.number().describe("Quantile value") + })).describe("Summary quantiles") + }).optional() +}).describe("Metric data point"); +var TimeSeriesDataPointSchema2 = external_exports.object({ + /** + * Timestamp (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("Timestamp"), + /** + * Value + */ + value: external_exports.number().describe("Value"), + /** + * Labels/tags + */ + labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Labels") +}).describe("Time series data point"); +var TimeSeriesSchema2 = external_exports.object({ + /** + * Series name + */ + name: external_exports.string().describe("Series name"), + /** + * Series labels + */ + labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Series labels"), + /** + * Data points + */ + dataPoints: external_exports.array(TimeSeriesDataPointSchema2).describe("Data points"), + /** + * Start time + */ + startTime: external_exports.string().datetime().optional().describe("Start time"), + /** + * End time + */ + endTime: external_exports.string().datetime().optional().describe("End time") +}).describe("Time series"); +var MetricAggregationConfigSchema2 = external_exports.object({ + /** + * Aggregation type + */ + type: MetricAggregationType2.describe("Aggregation type"), + /** + * Time window for aggregation + */ + window: external_exports.object({ + /** + * Window size in seconds + */ + size: external_exports.number().int().positive().describe("Window size in seconds"), + /** + * Sliding window (true) or tumbling window (false) + */ + sliding: external_exports.boolean().optional().default(false), + /** + * Slide interval for sliding windows + */ + slideInterval: external_exports.number().int().positive().optional() + }).optional(), + /** + * Group by labels + */ + groupBy: external_exports.array(external_exports.string()).optional().describe("Group by label names"), + /** + * Filters + */ + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria") +}).describe("Metric aggregation configuration"); +var ServiceLevelIndicatorSchema2 = external_exports.object({ + /** + * SLI name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("SLI name (snake_case)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Description + */ + description: external_exports.string().optional().describe("SLI description"), + /** + * Metric name this SLI is based on + */ + metric: external_exports.string().describe("Base metric name"), + /** + * SLI type + */ + type: external_exports.enum([ + "availability", + // Percentage of successful requests + "latency", + // Response time percentile + "throughput", + // Requests per second + "error_rate", + // Error percentage + "saturation", + // Resource utilization + "custom" + // Custom calculation + ]).describe("SLI type"), + /** + * Success criteria + */ + successCriteria: external_exports.object({ + /** + * Threshold value + */ + threshold: external_exports.number().describe("Threshold value"), + /** + * Comparison operator + */ + operator: external_exports.enum(["lt", "lte", "gt", "gte", "eq"]).describe("Comparison operator"), + /** + * Percentile (for latency SLIs) + */ + percentile: external_exports.number().min(0).max(1).optional().describe("Percentile (0-1)") + }).describe("Success criteria"), + /** + * Measurement window + */ + window: external_exports.object({ + /** + * Window size in seconds + */ + size: external_exports.number().int().positive().describe("Window size in seconds"), + /** + * Rolling window (true) or calendar-aligned (false) + */ + rolling: external_exports.boolean().optional().default(true) + }).describe("Measurement window"), + /** + * Enabled flag + */ + enabled: external_exports.boolean().optional().default(true) +}).describe("Service Level Indicator"); +var ServiceLevelObjectiveSchema2 = external_exports.object({ + /** + * SLO name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("SLO name (snake_case)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Description + */ + description: external_exports.string().optional().describe("SLO description"), + /** + * SLI this SLO is based on + */ + sli: external_exports.string().describe("SLI name"), + /** + * Target percentage (0-100) + */ + target: external_exports.number().min(0).max(100).describe("Target percentage"), + /** + * Time period for SLO + */ + period: external_exports.object({ + /** + * Period type + */ + type: external_exports.enum(["rolling", "calendar"]).describe("Period type"), + /** + * Duration in seconds (for rolling) + */ + duration: external_exports.number().int().positive().optional().describe("Duration in seconds"), + /** + * Calendar period (for calendar) + */ + calendar: external_exports.enum(["daily", "weekly", "monthly", "quarterly", "yearly"]).optional() + }).describe("Time period"), + /** + * Error budget configuration + */ + errorBudget: external_exports.object({ + /** + * Auto-calculated budget (1 - target) + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Alert when budget consumed percentage exceeds threshold + */ + alertThreshold: external_exports.number().min(0).max(100).optional().default(80), + /** + * Burn rate alert windows + */ + burnRateWindows: external_exports.array(external_exports.object({ + /** + * Window size in seconds + */ + window: external_exports.number().int().positive().describe("Window size"), + /** + * Burn rate multiplier threshold + */ + threshold: external_exports.number().positive().describe("Burn rate threshold") + })).optional() + }).optional(), + /** + * Alert configuration + */ + alerts: external_exports.array(external_exports.object({ + /** + * Alert name + */ + name: external_exports.string().describe("Alert name"), + /** + * Severity + */ + severity: external_exports.enum(["info", "warning", "critical"]).describe("Alert severity"), + /** + * Condition + */ + condition: external_exports.object({ + type: external_exports.enum(["slo_breach", "error_budget", "burn_rate"]).describe("Condition type"), + threshold: external_exports.number().optional().describe("Threshold value") + }).describe("Alert condition") + })).optional().default([]), + /** + * Enabled flag + */ + enabled: external_exports.boolean().optional().default(true) +}).describe("Service Level Objective"); +var MetricExportConfigSchema2 = external_exports.object({ + /** + * Export type + */ + type: external_exports.enum([ + "prometheus", + // Prometheus exposition format + "openmetrics", + // OpenMetrics format + "graphite", + // Graphite plaintext protocol + "statsd", + // StatsD protocol + "influxdb", + // InfluxDB line protocol + "datadog", + // Datadog agent + "cloudwatch", + // AWS CloudWatch + "stackdriver", + // Google Cloud Monitoring + "azure_monitor", + // Azure Monitor + "http", + // HTTP push + "custom" + // Custom exporter + ]).describe("Export type"), + /** + * Endpoint configuration + */ + endpoint: external_exports.string().optional().describe("Export endpoint"), + /** + * Export interval in seconds + */ + interval: external_exports.number().int().positive().optional().default(60), + /** + * Batch configuration + */ + batch: external_exports.object({ + enabled: external_exports.boolean().optional().default(true), + size: external_exports.number().int().positive().optional().default(1e3) + }).optional(), + /** + * Authentication + */ + auth: external_exports.object({ + type: external_exports.enum(["none", "basic", "bearer", "api_key"]).describe("Auth type"), + username: external_exports.string().optional(), + password: external_exports.string().optional(), + token: external_exports.string().optional(), + apiKey: external_exports.string().optional() + }).optional(), + /** + * Additional configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional configuration") +}).describe("Metric export configuration"); +var MetricsConfigSchema2 = external_exports.object({ + /** + * Configuration name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Enable metrics collection + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Metric definitions + */ + metrics: external_exports.array(MetricDefinitionSchema2).optional().default([]), + /** + * Default labels applied to all metrics + */ + defaultLabels: MetricLabelsSchema2.optional().default({}), + /** + * Aggregation configurations + */ + aggregations: external_exports.array(MetricAggregationConfigSchema2).optional().default([]), + /** + * Service Level Indicators + */ + slis: external_exports.array(ServiceLevelIndicatorSchema2).optional().default([]), + /** + * Service Level Objectives + */ + slos: external_exports.array(ServiceLevelObjectiveSchema2).optional().default([]), + /** + * Export configurations + */ + exports: external_exports.array(MetricExportConfigSchema2).optional().default([]), + /** + * Collection interval in seconds + */ + collectionInterval: external_exports.number().int().positive().optional().default(15), + /** + * Retention configuration + */ + retention: external_exports.object({ + /** + * Retention period in seconds + */ + period: external_exports.number().int().positive().optional().default(604800), + // 7 days + /** + * Downsampling configuration + */ + downsampling: external_exports.array(external_exports.object({ + /** + * After this duration, downsample to this resolution + */ + afterSeconds: external_exports.number().int().positive().describe("Downsample after seconds"), + /** + * Resolution in seconds + */ + resolution: external_exports.number().int().positive().describe("Downsampled resolution") + })).optional() + }).optional(), + /** + * Cardinality limits + */ + cardinalityLimits: external_exports.object({ + /** + * Maximum unique label combinations per metric + */ + maxLabelCombinations: external_exports.number().int().positive().optional().default(1e4), + /** + * Action when limit exceeded + */ + onLimitExceeded: external_exports.enum(["drop", "sample", "alert"]).optional().default("alert") + }).optional() +}).describe("Metrics configuration"); +var TraceStateSchema2 = external_exports.object({ + /** + * Vendor-specific key-value pairs + */ + entries: external_exports.record(external_exports.string(), external_exports.string()).describe("Trace state entries") +}).describe("Trace state"); +var TraceFlagsSchema2 = external_exports.number().int().min(0).max(255).describe("Trace flags bitmap"); +var TraceContextSchema2 = external_exports.object({ + /** + * Trace ID (128-bit identifier, 32 hex chars) + */ + traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).describe("Trace ID (32 hex chars)"), + /** + * Span ID (64-bit identifier, 16 hex chars) + */ + spanId: external_exports.string().regex(/^[0-9a-f]{16}$/).describe("Span ID (16 hex chars)"), + /** + * Trace flags (8-bit) + */ + traceFlags: TraceFlagsSchema2.optional().default(1), + /** + * Trace state (vendor-specific) + */ + traceState: TraceStateSchema2.optional(), + /** + * Parent span ID + */ + parentSpanId: external_exports.string().regex(/^[0-9a-f]{16}$/).optional().describe("Parent span ID (16 hex chars)"), + /** + * Is sampled + */ + sampled: external_exports.boolean().optional().default(true), + /** + * Remote context (from incoming request) + */ + remote: external_exports.boolean().optional().default(false) +}).describe("Trace context (W3C Trace Context)"); +var SpanKind2 = external_exports.enum([ + "internal", + // Internal operation + "server", + // Server-side request handling + "client", + // Client-side request + "producer", + // Message producer + "consumer" + // Message consumer +]).describe("Span kind"); +var SpanStatus2 = external_exports.enum([ + "unset", + // Default status + "ok", + // Successful operation + "error" + // Error occurred +]).describe("Span status"); +var SpanAttributeValueSchema2 = external_exports.union([ + external_exports.string(), + external_exports.number(), + external_exports.boolean(), + external_exports.array(external_exports.string()), + external_exports.array(external_exports.number()), + external_exports.array(external_exports.boolean()) +]).describe("Span attribute value"); +var SpanAttributesSchema2 = external_exports.record(external_exports.string(), SpanAttributeValueSchema2).describe("Span attributes"); +var SpanEventSchema2 = external_exports.object({ + /** + * Event name + */ + name: external_exports.string().describe("Event name"), + /** + * Event timestamp (ISO 8601) + */ + timestamp: external_exports.string().datetime().describe("Event timestamp"), + /** + * Event attributes + */ + attributes: SpanAttributesSchema2.optional().describe("Event attributes") +}).describe("Span event"); +var SpanLinkSchema2 = external_exports.object({ + /** + * Linked trace context + */ + context: TraceContextSchema2.describe("Linked trace context"), + /** + * Link attributes + */ + attributes: SpanAttributesSchema2.optional().describe("Link attributes") +}).describe("Span link"); +var SpanSchema2 = external_exports.object({ + /** + * Trace context + */ + context: TraceContextSchema2.describe("Trace context"), + /** + * Span name + */ + name: external_exports.string().describe("Span name"), + /** + * Span kind + */ + kind: SpanKind2.optional().default("internal"), + /** + * Start time (ISO 8601) + */ + startTime: external_exports.string().datetime().describe("Span start time"), + /** + * End time (ISO 8601) + */ + endTime: external_exports.string().datetime().optional().describe("Span end time"), + /** + * Duration in milliseconds + */ + duration: external_exports.number().nonnegative().optional().describe("Duration in milliseconds"), + /** + * Span status + */ + status: external_exports.object({ + code: SpanStatus2.describe("Status code"), + message: external_exports.string().optional().describe("Status message") + }).optional(), + /** + * Span attributes + */ + attributes: SpanAttributesSchema2.optional().default({}), + /** + * Span events + */ + events: external_exports.array(SpanEventSchema2).optional().default([]), + /** + * Span links + */ + links: external_exports.array(SpanLinkSchema2).optional().default([]), + /** + * Resource attributes + */ + resource: SpanAttributesSchema2.optional().describe("Resource attributes"), + /** + * Instrumentation library + */ + instrumentationLibrary: external_exports.object({ + name: external_exports.string().describe("Library name"), + version: external_exports.string().optional().describe("Library version") + }).optional() +}).describe("OpenTelemetry span"); +var SamplingDecision2 = external_exports.enum([ + "drop", + // Do not record or export + "record_only", + // Record but do not export + "record_and_sample" + // Record and export +]).describe("Sampling decision"); +var SamplingStrategyType2 = external_exports.enum([ + "always_on", + // Always sample + "always_off", + // Never sample + "trace_id_ratio", + // Sample based on trace ID ratio + "rate_limiting", + // Rate-limited sampling + "parent_based", + // Respect parent span sampling decision + "probability", + // Probability-based sampling + "composite", + // Combine multiple strategies + "custom" + // Custom sampling logic +]).describe("Sampling strategy type"); +var TraceSamplingConfigSchema2 = external_exports.object({ + /** + * Sampling strategy type + */ + type: SamplingStrategyType2.describe("Sampling strategy"), + /** + * Sample ratio (0.0 to 1.0) for trace_id_ratio and probability strategies + */ + ratio: external_exports.number().min(0).max(1).optional().describe("Sample ratio (0-1)"), + /** + * Rate limit (traces per second) for rate_limiting strategy + */ + rateLimit: external_exports.number().positive().optional().describe("Traces per second"), + /** + * Parent-based configuration + */ + parentBased: external_exports.object({ + /** + * Sampler to use when parent is sampled + */ + whenParentSampled: SamplingStrategyType2.optional().default("always_on"), + /** + * Sampler to use when parent is not sampled + */ + whenParentNotSampled: SamplingStrategyType2.optional().default("always_off"), + /** + * Sampler to use when there is no parent (root span) + */ + root: SamplingStrategyType2.optional().default("trace_id_ratio"), + /** + * Root sampler ratio + */ + rootRatio: external_exports.number().min(0).max(1).optional().default(0.1) + }).optional(), + /** + * Composite sampling (multiple strategies) + */ + composite: external_exports.array(external_exports.object({ + strategy: SamplingStrategyType2.describe("Strategy type"), + ratio: external_exports.number().min(0).max(1).optional(), + condition: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Condition for this strategy") + })).optional(), + /** + * Sampling rules + */ + rules: external_exports.array(external_exports.object({ + /** + * Rule name + */ + name: external_exports.string().describe("Rule name"), + /** + * Match condition + */ + match: external_exports.object({ + /** + * Service name pattern + */ + service: external_exports.string().optional(), + /** + * Span name pattern (regex) + */ + spanName: external_exports.string().optional(), + /** + * Attribute filters + */ + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional(), + /** + * Sampling decision for matching spans + */ + decision: SamplingDecision2.describe("Sampling decision"), + /** + * Sample rate for this rule + */ + rate: external_exports.number().min(0).max(1).optional() + })).optional().default([]), + /** + * Custom sampler ID (for custom strategy) + */ + customSamplerId: external_exports.string().optional().describe("Custom sampler identifier") +}).describe("Trace sampling configuration"); +var TracePropagationFormat2 = external_exports.enum([ + "w3c", + // W3C Trace Context + "b3", + // Zipkin B3 (single header) + "b3_multi", + // Zipkin B3 (multi header) + "jaeger", + // Jaeger propagation + "xray", + // AWS X-Ray + "ottrace", + // OpenTracing + "custom" + // Custom format +]).describe("Trace propagation format"); +var TraceContextPropagationSchema2 = external_exports.object({ + /** + * Propagation formats (in priority order) + */ + formats: external_exports.array(TracePropagationFormat2).optional().default(["w3c"]), + /** + * Extract context from incoming requests + */ + extract: external_exports.boolean().optional().default(true), + /** + * Inject context into outgoing requests + */ + inject: external_exports.boolean().optional().default(true), + /** + * Custom header mappings + */ + headers: external_exports.object({ + /** + * Trace ID header name + */ + traceId: external_exports.string().optional(), + /** + * Span ID header name + */ + spanId: external_exports.string().optional(), + /** + * Trace flags header name + */ + traceFlags: external_exports.string().optional(), + /** + * Trace state header name + */ + traceState: external_exports.string().optional() + }).optional(), + /** + * Baggage propagation + */ + baggage: external_exports.object({ + /** + * Enable baggage propagation + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Maximum baggage size in bytes + */ + maxSize: external_exports.number().int().positive().optional().default(8192), + /** + * Allowed baggage keys (whitelist) + */ + allowedKeys: external_exports.array(external_exports.string()).optional() + }).optional() +}).describe("Trace context propagation"); +var OtelExporterType2 = external_exports.enum([ + "otlp_http", + // OTLP over HTTP + "otlp_grpc", + // OTLP over gRPC + "jaeger", + // Jaeger + "zipkin", + // Zipkin + "console", + // Console (for debugging) + "datadog", + // Datadog + "honeycomb", + // Honeycomb + "lightstep", + // Lightstep + "newrelic", + // New Relic + "custom" + // Custom exporter +]).describe("OpenTelemetry exporter type"); +var OpenTelemetryCompatibilitySchema2 = external_exports.object({ + /** + * OpenTelemetry SDK version + */ + sdkVersion: external_exports.string().optional().describe("OTel SDK version"), + /** + * Exporter configuration + */ + exporter: external_exports.object({ + /** + * Exporter type + */ + type: OtelExporterType2.describe("Exporter type"), + /** + * Endpoint URL + */ + endpoint: external_exports.string().url().optional().describe("Exporter endpoint"), + /** + * Protocol version + */ + protocol: external_exports.string().optional().describe("Protocol version"), + /** + * Headers + */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP headers"), + /** + * Timeout in milliseconds + */ + timeout: external_exports.number().int().positive().optional().default(1e4), + /** + * Compression + */ + compression: external_exports.enum(["none", "gzip"]).optional().default("none"), + /** + * Batch configuration + */ + batch: external_exports.object({ + /** + * Maximum batch size + */ + maxBatchSize: external_exports.number().int().positive().optional().default(512), + /** + * Maximum queue size + */ + maxQueueSize: external_exports.number().int().positive().optional().default(2048), + /** + * Export timeout in milliseconds + */ + exportTimeout: external_exports.number().int().positive().optional().default(3e4), + /** + * Scheduled delay in milliseconds + */ + scheduledDelay: external_exports.number().int().positive().optional().default(5e3) + }).optional() + }).describe("Exporter configuration"), + /** + * Resource attributes (service identification) + */ + resource: external_exports.object({ + /** + * Service name + */ + serviceName: external_exports.string().describe("Service name"), + /** + * Service version + */ + serviceVersion: external_exports.string().optional().describe("Service version"), + /** + * Service instance ID + */ + serviceInstanceId: external_exports.string().optional().describe("Service instance ID"), + /** + * Service namespace + */ + serviceNamespace: external_exports.string().optional().describe("Service namespace"), + /** + * Deployment environment + */ + deploymentEnvironment: external_exports.string().optional().describe("Deployment environment"), + /** + * Additional resource attributes + */ + attributes: SpanAttributesSchema2.optional().describe("Additional resource attributes") + }).describe("Resource attributes"), + /** + * Instrumentation configuration + */ + instrumentation: external_exports.object({ + /** + * Auto-instrumentation enabled + */ + autoInstrumentation: external_exports.boolean().optional().default(true), + /** + * Instrumentation libraries to enable + */ + libraries: external_exports.array(external_exports.string()).optional().describe("Enabled libraries"), + /** + * Instrumentation libraries to disable + */ + disabledLibraries: external_exports.array(external_exports.string()).optional().describe("Disabled libraries") + }).optional(), + /** + * Semantic conventions version + */ + semanticConventionsVersion: external_exports.string().optional().describe("Semantic conventions version") +}).describe("OpenTelemetry compatibility configuration"); +var TracingConfigSchema2 = external_exports.object({ + /** + * Configuration name + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), + /** + * Display label + */ + label: external_exports.string().describe("Display label"), + /** + * Enable tracing + */ + enabled: external_exports.boolean().optional().default(true), + /** + * Sampling configuration + */ + sampling: TraceSamplingConfigSchema2.optional().default({ type: "always_on", rules: [] }), + /** + * Context propagation + */ + propagation: TraceContextPropagationSchema2.optional().default({ formats: ["w3c"], extract: true, inject: true }), + /** + * OpenTelemetry configuration + */ + openTelemetry: OpenTelemetryCompatibilitySchema2.optional(), + /** + * Span limits + */ + spanLimits: external_exports.object({ + /** + * Maximum number of attributes per span + */ + maxAttributes: external_exports.number().int().positive().optional().default(128), + /** + * Maximum number of events per span + */ + maxEvents: external_exports.number().int().positive().optional().default(128), + /** + * Maximum number of links per span + */ + maxLinks: external_exports.number().int().positive().optional().default(128), + /** + * Maximum attribute value length + */ + maxAttributeValueLength: external_exports.number().int().positive().optional().default(4096) + }).optional(), + /** + * Trace ID generator + */ + traceIdGenerator: external_exports.enum(["random", "uuid", "custom"]).optional().default("random"), + /** + * Custom trace ID generator ID + */ + customTraceIdGeneratorId: external_exports.string().optional().describe("Custom generator identifier"), + /** + * Performance configuration + */ + performance: external_exports.object({ + /** + * Async span export + */ + asyncExport: external_exports.boolean().optional().default(true), + /** + * Background export interval in milliseconds + */ + exportInterval: external_exports.number().int().positive().optional().default(5e3) + }).optional() +}).describe("Tracing configuration"); +var DataClassificationSchema2 = external_exports.enum([ + "pii", + "phi", + "pci", + "financial", + "confidential", + "internal", + "public" +]).describe("Data classification level"); +var ComplianceFrameworkSchema2 = external_exports.enum([ + "gdpr", + "hipaa", + "sox", + "pci_dss", + "ccpa", + "iso27001" +]).describe("Compliance framework identifier"); +var ComplianceAuditRequirementSchema2 = external_exports.object({ + framework: ComplianceFrameworkSchema2.describe("Compliance framework identifier"), + requiredEvents: external_exports.array(external_exports.string()).describe('Audit event types required by this framework (e.g., "data.delete", "auth.login")'), + retentionDays: external_exports.number().min(1).describe("Minimum audit log retention period required by this framework (in days)"), + alertOnMissing: external_exports.boolean().default(true).describe("Raise alert if a required audit event is not being captured") +}).describe("Compliance framework audit event requirements"); +var ComplianceEncryptionRequirementSchema2 = external_exports.object({ + framework: ComplianceFrameworkSchema2.describe("Compliance framework identifier"), + dataClassifications: external_exports.array(DataClassificationSchema2).describe("Data classifications that must be encrypted under this framework"), + minimumAlgorithm: external_exports.enum(["aes-256-gcm", "aes-256-cbc", "chacha20-poly1305"]).default("aes-256-gcm").describe("Minimum encryption algorithm strength required"), + keyRotationMaxDays: external_exports.number().min(1).default(90).describe("Maximum key rotation interval required (in days)") +}).describe("Compliance framework encryption requirements"); +var MaskingVisibilityRuleSchema2 = external_exports.object({ + dataClassification: DataClassificationSchema2.describe("Data classification this rule applies to"), + defaultMasked: external_exports.boolean().default(true).describe("Whether data is masked by default"), + unmaskRoles: external_exports.array(external_exports.string()).optional().describe("Roles allowed to view unmasked data"), + auditUnmask: external_exports.boolean().default(true).describe("Log an audit event when data is unmasked"), + requireApproval: external_exports.boolean().default(false).describe("Require explicit approval before unmasking"), + approvalRoles: external_exports.array(external_exports.string()).optional().describe("Roles that can approve unmasking requests") +}).describe("Masking visibility and audit rule per data classification"); +var SecurityEventCorrelationSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable cross-subsystem security event correlation"), + correlationId: external_exports.boolean().default(true).describe("Inject a shared correlation ID into audit, encryption, and masking events"), + linkAuthToAudit: external_exports.boolean().default(true).describe("Link authentication events to subsequent data operation audit trails"), + linkEncryptionToAudit: external_exports.boolean().default(true).describe("Log encryption/decryption operations in the audit trail"), + linkMaskingToAudit: external_exports.boolean().default(true).describe("Log masking/unmasking operations in the audit trail") +}).describe("Cross-subsystem security event correlation configuration"); +var DataClassificationPolicySchema2 = external_exports.object({ + classification: DataClassificationSchema2.describe("Data classification level"), + requireEncryption: external_exports.boolean().default(false).describe("Encryption required for this classification"), + requireMasking: external_exports.boolean().default(false).describe("Masking required for this classification"), + requireAudit: external_exports.boolean().default(false).describe("Audit trail required for access to this classification"), + retentionDays: external_exports.number().optional().describe("Data retention limit in days (for compliance)") +}).describe("Security policy for a specific data classification level"); +var SecurityContextConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable unified security context governance"), + complianceAuditRequirements: external_exports.array(ComplianceAuditRequirementSchema2).optional().describe("Compliance-driven audit event requirements"), + complianceEncryptionRequirements: external_exports.array(ComplianceEncryptionRequirementSchema2).optional().describe("Compliance-driven encryption requirements by data classification"), + maskingVisibility: external_exports.array(MaskingVisibilityRuleSchema2).optional().describe("Masking visibility rules per data classification"), + dataClassifications: external_exports.array(DataClassificationPolicySchema2).optional().describe("Data classification policies for unified security enforcement"), + eventCorrelation: SecurityEventCorrelationSchema2.optional().describe("Cross-subsystem security event correlation settings"), + enforceOnWrite: external_exports.boolean().default(true).describe("Enforce encryption and masking requirements on data write operations"), + enforceOnRead: external_exports.boolean().default(true).describe("Enforce masking and audit requirements on data read operations"), + failOpen: external_exports.boolean().default(false).describe("When false (default), deny access if security context cannot be evaluated") +}).describe("Unified security context governance configuration"); +var ChangeTypeSchema2 = external_exports.enum([ + "standard", + // Pre-approved, low-risk changes + "normal", + // Requires standard approval process + "emergency", + // Fast-track approval for critical issues + "major" + // Requires CAB (Change Advisory Board) approval +]); +var ChangePrioritySchema2 = external_exports.enum([ + "critical", + "high", + "medium", + "low" +]); +var ChangeStatusSchema2 = external_exports.enum([ + "draft", + "submitted", + "in-review", + "approved", + "scheduled", + "in-progress", + "completed", + "failed", + "rolled-back", + "cancelled" +]); +var ChangeImpactSchema2 = external_exports.object({ + /** + * Overall impact level of the change + */ + level: external_exports.enum(["low", "medium", "high", "critical"]).describe("Impact level"), + /** + * List of systems affected by this change + */ + affectedSystems: external_exports.array(external_exports.string()).describe("Affected systems"), + /** + * Estimated number of users affected + */ + affectedUsers: external_exports.number().optional().describe("Affected user count"), + /** + * Downtime requirements + */ + downtime: external_exports.object({ + /** + * Whether downtime is required + */ + required: external_exports.boolean().describe("Downtime required"), + /** + * Duration of downtime in minutes + */ + durationMinutes: external_exports.number().optional().describe("Downtime duration") + }).optional().describe("Downtime information") +}); +var RollbackPlanSchema2 = external_exports.object({ + /** + * High-level description of the rollback approach + */ + description: external_exports.string().describe("Rollback description"), + /** + * Sequential steps to execute rollback + */ + steps: external_exports.array(external_exports.object({ + /** + * Step execution order + */ + order: external_exports.number().describe("Step order"), + /** + * Detailed description of this step + */ + description: external_exports.string().describe("Step description"), + /** + * Estimated time to complete this step + */ + estimatedMinutes: external_exports.number().describe("Estimated duration") + })).describe("Rollback steps"), + /** + * Testing procedure to verify successful rollback + */ + testProcedure: external_exports.string().optional().describe("Test procedure") +}); +var ChangeRequestSchema2 = external_exports.object({ + /** + * Unique change request identifier + */ + id: external_exports.string().describe("Change request ID"), + /** + * Short descriptive title of the change + */ + title: external_exports.string().describe("Change title"), + /** + * Detailed description of the change and its purpose + */ + description: external_exports.string().describe("Change description"), + /** + * Change classification type + */ + type: ChangeTypeSchema2.describe("Change type"), + /** + * Priority level for processing + */ + priority: ChangePrioritySchema2.describe("Change priority"), + /** + * Current status in the change lifecycle + */ + status: ChangeStatusSchema2.describe("Change status"), + /** + * User ID of the change requester + */ + requestedBy: external_exports.string().describe("Requester user ID"), + /** + * Timestamp when change was requested (Unix milliseconds) + */ + requestedAt: external_exports.number().describe("Request timestamp"), + /** + * Impact assessment of the change + */ + impact: ChangeImpactSchema2.describe("Impact assessment"), + /** + * Implementation plan and procedures + */ + implementation: external_exports.object({ + /** + * High-level implementation description + */ + description: external_exports.string().describe("Implementation description"), + /** + * Sequential implementation steps + */ + steps: external_exports.array(external_exports.object({ + /** + * Step execution order + */ + order: external_exports.number().describe("Step order"), + /** + * Detailed description of this step + */ + description: external_exports.string().describe("Step description"), + /** + * Estimated time to complete this step + */ + estimatedMinutes: external_exports.number().describe("Estimated duration") + })).describe("Implementation steps"), + /** + * Testing procedures to verify successful implementation + */ + testing: external_exports.string().optional().describe("Testing procedure") + }).describe("Implementation plan"), + /** + * Rollback plan in case of failure + */ + rollbackPlan: RollbackPlanSchema2.describe("Rollback plan"), + /** + * Change schedule and timing + */ + schedule: external_exports.object({ + /** + * Planned start time (Unix milliseconds) + */ + plannedStart: external_exports.number().describe("Planned start time"), + /** + * Planned end time (Unix milliseconds) + */ + plannedEnd: external_exports.number().describe("Planned end time"), + /** + * Actual start time (Unix milliseconds) + */ + actualStart: external_exports.number().optional().describe("Actual start time"), + /** + * Actual end time (Unix milliseconds) + */ + actualEnd: external_exports.number().optional().describe("Actual end time") + }).optional().describe("Schedule"), + /** + * Security impact assessment for the change (A.8.32) + */ + securityImpact: external_exports.object({ + /** + * Whether a security impact assessment has been performed + */ + assessed: external_exports.boolean().describe("Whether security impact has been assessed"), + /** + * Security risk level of this change + */ + riskLevel: external_exports.enum(["none", "low", "medium", "high", "critical"]).optional().describe("Security risk level"), + /** + * Data classifications affected by this change + */ + affectedDataClassifications: external_exports.array(DataClassificationSchema2).optional().describe("Affected data classifications"), + /** + * Whether the change requires security team approval + */ + requiresSecurityApproval: external_exports.boolean().default(false).describe("Whether security team approval is required"), + /** + * Security reviewer user ID + */ + reviewedBy: external_exports.string().optional().describe("Security reviewer user ID"), + /** + * Security review completion timestamp (Unix milliseconds) + */ + reviewedAt: external_exports.number().optional().describe("Security review timestamp"), + /** + * Security review notes or conditions + */ + reviewNotes: external_exports.string().optional().describe("Security review notes or conditions") + }).optional().describe("Security impact assessment per ISO 27001:2022 A.8.32"), + /** + * Approval workflow configuration + */ + approval: external_exports.object({ + /** + * Whether approval is required for this change + */ + required: external_exports.boolean().describe("Approval required"), + /** + * List of approvers and their approval status + */ + approvers: external_exports.array(external_exports.object({ + /** + * Approver user ID + */ + userId: external_exports.string().describe("Approver user ID"), + /** + * Timestamp when approval was granted (Unix milliseconds) + */ + approvedAt: external_exports.number().optional().describe("Approval timestamp"), + /** + * Comments from the approver + */ + comments: external_exports.string().optional().describe("Approver comments") + })).describe("Approvers") + }).optional().describe("Approval workflow"), + /** + * Supporting documentation and files + */ + attachments: external_exports.array(external_exports.object({ + /** + * Attachment file name + */ + name: external_exports.string().describe("Attachment name"), + /** + * URL to download the attachment + */ + url: external_exports.string().url().describe("Attachment URL") + })).optional().describe("Attachments"), + /** + * Custom metadata key-value pairs for extensibility + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") +}); +var AddFieldOperation2 = external_exports.object({ + type: external_exports.literal("add_field"), + objectName: external_exports.string().describe("Target object name"), + fieldName: external_exports.string().describe("Name of the field to add"), + field: FieldSchema5.describe("Full field definition to add") +}).describe("Add a new field to an existing object"); +var ModifyFieldOperation2 = external_exports.object({ + type: external_exports.literal("modify_field"), + objectName: external_exports.string().describe("Target object name"), + fieldName: external_exports.string().describe("Name of the field to modify"), + changes: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Partial field definition updates") +}).describe("Modify properties of an existing field"); +var RemoveFieldOperation2 = external_exports.object({ + type: external_exports.literal("remove_field"), + objectName: external_exports.string().describe("Target object name"), + fieldName: external_exports.string().describe("Name of the field to remove") +}).describe("Remove a field from an existing object"); +var CreateObjectOperation2 = external_exports.object({ + type: external_exports.literal("create_object"), + object: ObjectSchema4.describe("Full object definition to create") +}).describe("Create a new object"); +var RenameObjectOperation2 = external_exports.object({ + type: external_exports.literal("rename_object"), + oldName: external_exports.string().describe("Current object name"), + newName: external_exports.string().describe("New object name") +}).describe("Rename an existing object"); +var DeleteObjectOperation2 = external_exports.object({ + type: external_exports.literal("delete_object"), + objectName: external_exports.string().describe("Name of the object to delete") +}).describe("Delete an existing object"); +var ExecuteSqlOperation2 = external_exports.object({ + type: external_exports.literal("execute_sql"), + sql: external_exports.string().describe("Raw SQL statement to execute"), + description: external_exports.string().optional().describe("Human-readable description of the SQL") +}).describe("Execute a raw SQL statement"); +var MigrationOperationSchema2 = external_exports.discriminatedUnion("type", [ + AddFieldOperation2, + ModifyFieldOperation2, + RemoveFieldOperation2, + CreateObjectOperation2, + RenameObjectOperation2, + DeleteObjectOperation2, + ExecuteSqlOperation2 +]); +var MigrationDependencySchema2 = external_exports.object({ + migrationId: external_exports.string().describe("ID of the migration this depends on"), + package: external_exports.string().optional().describe("Package that owns the dependency migration") +}).describe("Dependency reference to another migration that must run first"); +var ChangeSetSchema2 = external_exports.object({ + id: external_exports.string().uuid().describe("Unique identifier for this change set"), + name: external_exports.string().describe("Human readable name for the migration"), + description: external_exports.string().optional().describe("Detailed description of what this migration does"), + author: external_exports.string().optional().describe("Author who created this migration"), + createdAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp when the migration was created"), + // Dependencies ensure migrations run in order + dependencies: external_exports.array(MigrationDependencySchema2).optional().describe("Migrations that must run before this one"), + // The actual atomic operations + operations: external_exports.array(MigrationOperationSchema2).describe("Ordered list of atomic migration operations"), + // Rollback operations (AI should generate these too) + rollback: external_exports.array(MigrationOperationSchema2).optional().describe("Operations to reverse this migration") +}).describe("A versioned set of atomic schema migration operations"); +var AuthProviderConfigSchema2 = external_exports.object({ + id: external_exports.string().describe("Provider ID (github, google)"), + clientId: external_exports.string().describe("OAuth Client ID"), + clientSecret: external_exports.string().describe("OAuth Client Secret"), + scope: external_exports.array(external_exports.string()).optional().describe("Requested permissions") +}); +var AuthPluginConfigSchema2 = external_exports.object({ + organization: external_exports.boolean().default(false).describe("Enable Organization/Teams support"), + twoFactor: external_exports.boolean().default(false).describe("Enable 2FA"), + passkeys: external_exports.boolean().default(false).describe("Enable Passkey support"), + magicLink: external_exports.boolean().default(false).describe("Enable Magic Link login") +}); +var MutualTLSConfigSchema2 = external_exports.object({ + /** Enable mutual TLS authentication */ + enabled: external_exports.boolean().default(false).describe("Enable mutual TLS authentication"), + /** Require client certificates for all connections */ + clientCertRequired: external_exports.boolean().default(false).describe("Require client certificates for all connections"), + /** PEM-encoded CA certificates or file paths for trust validation */ + trustedCAs: external_exports.array(external_exports.string()).describe("PEM-encoded CA certificates or file paths"), + /** Certificate Revocation List URL */ + crlUrl: external_exports.string().optional().describe("Certificate Revocation List (CRL) URL"), + /** Online Certificate Status Protocol URL */ + ocspUrl: external_exports.string().optional().describe("Online Certificate Status Protocol (OCSP) URL"), + /** Certificate validation strictness level */ + certificateValidation: external_exports.enum(["strict", "relaxed", "none"]).describe("Certificate validation strictness level"), + /** Allowed Common Names on client certificates */ + allowedCNs: external_exports.array(external_exports.string()).optional().describe("Allowed Common Names (CN) on client certificates"), + /** Allowed Organizational Units on client certificates */ + allowedOUs: external_exports.array(external_exports.string()).optional().describe("Allowed Organizational Units (OU) on client certificates"), + /** Certificate pinning configuration */ + pinning: external_exports.object({ + /** Enable certificate pinning */ + enabled: external_exports.boolean().describe("Enable certificate pinning"), + /** Array of pinned certificate hashes */ + pins: external_exports.array(external_exports.string()).describe("Pinned certificate hashes") + }).optional().describe("Certificate pinning configuration") +}); +var SocialProviderConfigSchema2 = external_exports.record( + external_exports.string(), + external_exports.object({ + clientId: external_exports.string().describe("OAuth Client ID"), + clientSecret: external_exports.string().describe("OAuth Client Secret"), + enabled: external_exports.boolean().optional().default(true).describe("Enable this provider"), + scope: external_exports.array(external_exports.string()).optional().describe("Additional OAuth scopes") + }).catchall(external_exports.unknown()) +).optional().describe( + "Social/OAuth provider map forwarded to better-auth socialProviders. Keys are provider ids (google, github, apple, \u2026)." +); +var EmailAndPasswordConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable email/password auth"), + disableSignUp: external_exports.boolean().optional().describe("Disable new user registration via email/password"), + requireEmailVerification: external_exports.boolean().optional().describe( + "Require email verification before creating a session" + ), + minPasswordLength: external_exports.number().optional().describe("Minimum password length (default 8)"), + maxPasswordLength: external_exports.number().optional().describe("Maximum password length (default 128)"), + resetPasswordTokenExpiresIn: external_exports.number().optional().describe( + "Reset-password token TTL in seconds (default 3600)" + ), + autoSignIn: external_exports.boolean().optional().describe("Auto sign-in after sign-up (default true)"), + revokeSessionsOnPasswordReset: external_exports.boolean().optional().describe( + "Revoke all other sessions on password reset" + ) +}).optional().describe("Email and password authentication options forwarded to better-auth"); +var EmailVerificationConfigSchema2 = external_exports.object({ + sendOnSignUp: external_exports.boolean().optional().describe( + "Automatically send verification email after sign-up" + ), + sendOnSignIn: external_exports.boolean().optional().describe( + "Send verification email on sign-in when not yet verified" + ), + autoSignInAfterVerification: external_exports.boolean().optional().describe( + "Auto sign-in the user after email verification" + ), + expiresIn: external_exports.number().optional().describe( + "Verification token TTL in seconds (default 3600)" + ) +}).optional().describe("Email verification options forwarded to better-auth"); +var AdvancedAuthConfigSchema2 = external_exports.object({ + crossSubDomainCookies: external_exports.object({ + enabled: external_exports.boolean().describe("Enable cross-subdomain cookies"), + additionalCookies: external_exports.array(external_exports.string()).optional().describe("Extra cookies shared across subdomains"), + domain: external_exports.string().optional().describe( + "Cookie domain override \u2014 defaults to root domain derived from baseUrl" + ) + }).optional().describe( + "Share auth cookies across subdomains (critical for *.example.com multi-tenant)" + ), + useSecureCookies: external_exports.boolean().optional().describe("Force Secure flag on cookies"), + disableCSRFCheck: external_exports.boolean().optional().describe( + "\u26A0 Disable CSRF check \u2014 security risk, use with caution" + ), + cookiePrefix: external_exports.string().optional().describe("Prefix for auth cookie names") +}).optional().describe("Advanced / low-level Better-Auth options"); +var AuthConfigSchema2 = external_exports.object({ + secret: external_exports.string().optional().describe("Encryption secret"), + baseUrl: external_exports.string().optional().describe("Base URL for auth routes"), + databaseUrl: external_exports.string().optional().describe("Database connection string"), + providers: external_exports.array(AuthProviderConfigSchema2).optional(), + plugins: AuthPluginConfigSchema2.optional(), + session: external_exports.object({ + expiresIn: external_exports.number().default(60 * 60 * 24 * 7).describe("Session duration in seconds"), + updateAge: external_exports.number().default(60 * 60 * 24).describe("Session update frequency") + }).optional(), + trustedOrigins: external_exports.array(external_exports.string()).optional().describe( + 'Trusted origins for CSRF protection. Supports wildcards (e.g. "https://*.example.com"). The baseUrl origin is always trusted implicitly.' + ), + socialProviders: SocialProviderConfigSchema2, + emailAndPassword: EmailAndPasswordConfigSchema2, + emailVerification: EmailVerificationConfigSchema2, + advanced: AdvancedAuthConfigSchema2, + mutualTls: MutualTLSConfigSchema2.optional().describe("Mutual TLS (mTLS) configuration") +}).catchall(external_exports.unknown()); +var GDPRConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable GDPR compliance controls"), + dataSubjectRights: external_exports.object({ + rightToAccess: external_exports.boolean().default(true).describe("Allow data subjects to access their data"), + rightToRectification: external_exports.boolean().default(true).describe("Allow data subjects to correct their data"), + rightToErasure: external_exports.boolean().default(true).describe("Allow data subjects to request deletion"), + rightToRestriction: external_exports.boolean().default(true).describe("Allow data subjects to restrict processing"), + rightToPortability: external_exports.boolean().default(true).describe("Allow data subjects to export their data"), + rightToObjection: external_exports.boolean().default(true).describe("Allow data subjects to object to processing") + }).describe("Data subject rights configuration per GDPR Articles 15-21"), + legalBasis: external_exports.enum([ + "consent", + "contract", + "legal-obligation", + "vital-interests", + "public-task", + "legitimate-interests" + ]).describe("Legal basis for data processing under GDPR Article 6"), + consentTracking: external_exports.boolean().default(true).describe("Track and record user consent"), + dataRetentionDays: external_exports.number().optional().describe("Maximum data retention period in days"), + dataProcessingAgreement: external_exports.string().optional().describe("URL or reference to the data processing agreement") +}).describe("GDPR (General Data Protection Regulation) compliance configuration"); +var HIPAAConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable HIPAA compliance controls"), + phi: external_exports.object({ + encryption: external_exports.boolean().default(true).describe("Encrypt Protected Health Information at rest"), + accessControl: external_exports.boolean().default(true).describe("Enforce role-based access to PHI"), + auditTrail: external_exports.boolean().default(true).describe("Log all PHI access events"), + backupAndRecovery: external_exports.boolean().default(true).describe("Enable PHI backup and disaster recovery") + }).describe("Protected Health Information safeguards"), + businessAssociateAgreement: external_exports.boolean().default(false).describe("BAA is in place with third-party processors") +}).describe("HIPAA (Health Insurance Portability and Accountability Act) compliance configuration"); +var PCIDSSConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().describe("Enable PCI-DSS compliance controls"), + level: external_exports.enum(["1", "2", "3", "4"]).describe("PCI-DSS compliance level (1 = highest)"), + cardDataFields: external_exports.array(external_exports.string()).describe("Field names containing cardholder data"), + tokenization: external_exports.boolean().default(true).describe("Replace card data with secure tokens"), + encryptionInTransit: external_exports.boolean().default(true).describe("Encrypt cardholder data during transmission"), + encryptionAtRest: external_exports.boolean().default(true).describe("Encrypt stored cardholder data") +}).describe("PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration"); +var AuditLogConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable audit logging"), + retentionDays: external_exports.number().default(365).describe("Number of days to retain audit logs"), + immutable: external_exports.boolean().default(true).describe("Prevent modification or deletion of audit logs"), + signLogs: external_exports.boolean().default(false).describe("Cryptographically sign log entries for tamper detection"), + events: external_exports.array(external_exports.enum([ + "create", + "read", + "update", + "delete", + "export", + "permission-change", + "login", + "logout", + "failed-login" + ])).describe("Event types to capture in the audit log") +}).describe("Audit log configuration for compliance and security monitoring"); +var AuditFindingSeveritySchema2 = external_exports.enum([ + "critical", + // Immediate remediation required + "major", + // Significant non-conformity + "minor", + // Minor non-conformity + "observation" + // Improvement opportunity +]); +var AuditFindingStatusSchema2 = external_exports.enum([ + "open", + // Finding identified, not yet addressed + "in_remediation", + // Remediation in progress + "remediated", + // Remediation completed, pending verification + "verified", + // Remediation verified and accepted + "accepted_risk", + // Risk accepted by management + "closed" + // Finding closed +]); +var AuditFindingSchema2 = external_exports.object({ + /** + * Unique finding identifier + */ + id: external_exports.string().describe("Unique finding identifier"), + /** + * Short descriptive title + */ + title: external_exports.string().describe("Finding title"), + /** + * Detailed description of the finding + */ + description: external_exports.string().describe("Finding description"), + /** + * Finding severity + */ + severity: AuditFindingSeveritySchema2.describe("Finding severity"), + /** + * Current status + */ + status: AuditFindingStatusSchema2.describe("Finding status"), + /** + * ISO 27001 control reference (e.g., "A.5.35", "A.8.15") + */ + controlReference: external_exports.string().optional().describe("ISO 27001 control reference"), + /** + * Compliance framework + */ + framework: ComplianceFrameworkSchema2.optional().describe("Related compliance framework"), + /** + * Timestamp when finding was identified (Unix milliseconds) + */ + identifiedAt: external_exports.number().describe("Identification timestamp"), + /** + * User or entity who identified the finding + */ + identifiedBy: external_exports.string().describe("Identifier (auditor name or system)"), + /** + * Planned remediation actions + */ + remediationPlan: external_exports.string().optional().describe("Remediation plan"), + /** + * Remediation deadline (Unix milliseconds) + */ + remediationDeadline: external_exports.number().optional().describe("Remediation deadline timestamp"), + /** + * Timestamp when remediation was verified (Unix milliseconds) + */ + verifiedAt: external_exports.number().optional().describe("Verification timestamp"), + /** + * Verifier name or role + */ + verifiedBy: external_exports.string().optional().describe("Verifier name or role"), + /** + * Notes or comments + */ + notes: external_exports.string().optional().describe("Additional notes") +}).describe("Audit finding with remediation tracking per ISO 27001:2022 A.5.35"); +var AuditScheduleSchema2 = external_exports.object({ + /** + * Unique audit schedule identifier + */ + id: external_exports.string().describe("Unique audit schedule identifier"), + /** + * Audit title or name + */ + title: external_exports.string().describe("Audit title"), + /** + * Scope of areas to audit + */ + scope: external_exports.array(external_exports.string()).describe("Audit scope areas"), + /** + * Target compliance framework + */ + framework: ComplianceFrameworkSchema2.describe("Target compliance framework"), + /** + * Scheduled audit date (Unix milliseconds) + */ + scheduledAt: external_exports.number().describe("Scheduled audit timestamp"), + /** + * Actual completion date (Unix milliseconds) + */ + completedAt: external_exports.number().optional().describe("Completion timestamp"), + /** + * Assessor name, team, or external firm + */ + assessor: external_exports.string().describe("Assessor or audit team"), + /** + * Whether this is an external (independent) audit + */ + isExternal: external_exports.boolean().default(false).describe("Whether this is an external audit"), + /** + * Recurrence interval in months (0 = one-time) + */ + recurrenceMonths: external_exports.number().default(0).describe("Recurrence interval in months (0 = one-time)"), + /** + * Findings from this audit + */ + findings: external_exports.array(AuditFindingSchema2).optional().describe("Audit findings") +}).describe("Audit schedule for independent security reviews per ISO 27001:2022 A.5.35"); +var ComplianceConfigSchema2 = external_exports.object({ + gdpr: GDPRConfigSchema2.optional().describe("GDPR compliance settings"), + hipaa: HIPAAConfigSchema2.optional().describe("HIPAA compliance settings"), + pciDss: PCIDSSConfigSchema2.optional().describe("PCI-DSS compliance settings"), + auditLog: AuditLogConfigSchema2.describe("Audit log configuration"), + auditSchedules: external_exports.array(AuditScheduleSchema2).optional().describe("Scheduled compliance audits (A.5.35)") +}).describe("Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance"); +var IncidentSeveritySchema2 = external_exports.enum([ + "critical", + // Immediate threat to business operations or data integrity + "high", + // Significant impact requiring urgent response + "medium", + // Moderate impact with controlled response timeline + "low" + // Minor impact with standard response procedures +]); +var IncidentCategorySchema2 = external_exports.enum([ + "data_breach", + // Unauthorized access or disclosure of data + "malware", + // Malicious software detection + "unauthorized_access", + // Unauthorized system or data access + "denial_of_service", + // Service availability attack + "social_engineering", + // Phishing, pretexting, or manipulation + "insider_threat", + // Threat originating from internal actors + "physical_security", + // Physical security breach + "configuration_error", + // Security misconfiguration + "vulnerability_exploit", + // Exploitation of known vulnerability + "policy_violation", + // Violation of security policies + "other" + // Other security incidents +]); +var IncidentStatusSchema2 = external_exports.enum([ + "reported", + // Initial report received + "triaged", + // Severity and category assessed + "investigating", + // Active investigation in progress + "containing", + // Containment measures being applied + "eradicating", + // Root cause being removed + "recovering", + // Systems being restored to normal + "resolved", + // Incident resolved + "closed" + // Post-incident review complete +]); +var IncidentResponsePhaseSchema2 = external_exports.object({ + /** + * Phase name identifier + */ + phase: external_exports.enum([ + "identification", + "containment", + "eradication", + "recovery", + "lessons_learned" + ]).describe("Response phase name"), + /** + * Phase description and objectives + */ + description: external_exports.string().describe("Phase description and objectives"), + /** + * Responsible team or role for this phase + */ + assignedTo: external_exports.string().describe("Responsible team or role"), + /** + * Target completion time in hours from incident start + */ + targetHours: external_exports.number().min(0).describe("Target completion time in hours"), + /** + * Actual completion timestamp (Unix milliseconds) + */ + completedAt: external_exports.number().optional().describe("Actual completion timestamp"), + /** + * Notes and findings during this phase + */ + notes: external_exports.string().optional().describe("Phase notes and findings") +}).describe("Incident response phase with timing and assignment"); +var IncidentNotificationRuleSchema2 = external_exports.object({ + /** + * Minimum severity level that triggers this notification + */ + severity: IncidentSeveritySchema2.describe("Minimum severity to trigger notification"), + /** + * Notification channels to use + */ + channels: external_exports.array(external_exports.enum([ + "email", + "sms", + "slack", + "pagerduty", + "webhook" + ])).describe("Notification channels"), + /** + * Roles or teams to notify + */ + recipients: external_exports.array(external_exports.string()).describe("Roles or teams to notify"), + /** + * Maximum time in minutes to send notification after incident detection + */ + withinMinutes: external_exports.number().min(1).describe("Notification deadline in minutes from detection"), + /** + * Whether to notify external regulators (for data breaches) + */ + notifyRegulators: external_exports.boolean().default(false).describe("Whether to notify regulatory authorities"), + /** + * Regulatory notification deadline in hours (e.g., GDPR 72h) + */ + regulatorDeadlineHours: external_exports.number().optional().describe("Regulatory notification deadline in hours") +}).describe("Incident notification rule per severity level"); +var IncidentNotificationMatrixSchema2 = external_exports.object({ + /** + * Notification rules ordered by severity + */ + rules: external_exports.array(IncidentNotificationRuleSchema2).describe("Notification rules by severity level"), + /** + * Default escalation timeout in minutes before auto-escalation + */ + escalationTimeoutMinutes: external_exports.number().default(30).describe("Auto-escalation timeout in minutes"), + /** + * Escalation chain: ordered list of roles to escalate to + */ + escalationChain: external_exports.array(external_exports.string()).default([]).describe("Ordered escalation chain of roles") +}).describe("Incident notification matrix with escalation policies"); +var IncidentSchema2 = external_exports.object({ + /** + * Unique incident identifier + */ + id: external_exports.string().describe("Unique incident identifier"), + /** + * Short descriptive title of the incident + */ + title: external_exports.string().describe("Incident title"), + /** + * Detailed description of the security event + */ + description: external_exports.string().describe("Detailed incident description"), + /** + * Severity classification + */ + severity: IncidentSeveritySchema2.describe("Incident severity level"), + /** + * Incident category / type + */ + category: IncidentCategorySchema2.describe("Incident category"), + /** + * Current status in the incident lifecycle + */ + status: IncidentStatusSchema2.describe("Current incident status"), + /** + * User or system that reported the incident + */ + reportedBy: external_exports.string().describe("Reporter user ID or system name"), + /** + * Timestamp when the incident was reported (Unix milliseconds) + */ + reportedAt: external_exports.number().describe("Report timestamp"), + /** + * Timestamp when the incident was detected (may differ from reported) + */ + detectedAt: external_exports.number().optional().describe("Detection timestamp"), + /** + * Timestamp when the incident was resolved + */ + resolvedAt: external_exports.number().optional().describe("Resolution timestamp"), + /** + * Systems affected by the incident + */ + affectedSystems: external_exports.array(external_exports.string()).describe("Affected systems"), + /** + * Data classifications affected (for data breach assessment) + */ + affectedDataClassifications: external_exports.array(DataClassificationSchema2).optional().describe("Affected data classifications"), + /** + * Structured response phases tracking + */ + responsePhases: external_exports.array(IncidentResponsePhaseSchema2).optional().describe("Incident response phases"), + /** + * Root cause analysis (completed post-incident) + */ + rootCause: external_exports.string().optional().describe("Root cause analysis"), + /** + * Corrective actions taken or planned + */ + correctiveActions: external_exports.array(external_exports.string()).optional().describe("Corrective actions taken or planned"), + /** + * Lessons learned from the incident (A.5.28) + */ + lessonsLearned: external_exports.string().optional().describe("Lessons learned from the incident"), + /** + * Related change request IDs (if changes resulted from incident) + */ + relatedChangeRequestIds: external_exports.array(external_exports.string()).optional().describe("Related change request IDs"), + /** + * Custom metadata for extensibility + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs") +}).describe("Security incident record per ISO 27001:2022 A.5.24\u2013A.5.28"); +var IncidentResponsePolicySchema2 = external_exports.object({ + /** + * Whether incident response is enabled + */ + enabled: external_exports.boolean().default(true).describe("Enable incident response management"), + /** + * Notification matrix configuration + */ + notificationMatrix: IncidentNotificationMatrixSchema2.describe("Notification and escalation matrix"), + /** + * Default response team or role + */ + defaultResponseTeam: external_exports.string().describe("Default incident response team or role"), + /** + * Maximum time in hours to begin initial triage + */ + triageDeadlineHours: external_exports.number().default(1).describe("Maximum hours to begin triage after detection"), + /** + * Whether to require post-incident review for all incidents + */ + requirePostIncidentReview: external_exports.boolean().default(true).describe("Require post-incident review for all incidents"), + /** + * Minimum severity level that requires regulatory notification + */ + regulatoryNotificationThreshold: IncidentSeveritySchema2.default("high").describe("Minimum severity requiring regulatory notification"), + /** + * Retention period for incident records in days + */ + retentionDays: external_exports.number().default(2555).describe("Incident record retention period in days (default ~7 years)") +}).describe("Organization-level incident response policy per ISO 27001:2022"); +var SupplierRiskLevelSchema2 = external_exports.enum([ + "critical", + // Direct access to sensitive data or core infrastructure + "high", + // Significant data processing or service dependency + "medium", + // Limited data access with moderate dependency + "low" + // Minimal data access and low service dependency +]); +var SupplierAssessmentStatusSchema2 = external_exports.enum([ + "pending", + // Assessment not yet started + "in_progress", + // Assessment currently underway + "completed", + // Assessment completed + "expired", + // Assessment past its validity period + "failed" + // Supplier did not meet security requirements +]); +var SupplierSecurityRequirementSchema2 = external_exports.object({ + /** + * Requirement identifier + */ + id: external_exports.string().describe("Requirement identifier"), + /** + * Requirement description + */ + description: external_exports.string().describe("Requirement description"), + /** + * ISO 27001 control reference (e.g., "A.5.19") + */ + controlReference: external_exports.string().optional().describe("ISO 27001 control reference"), + /** + * Whether this requirement is mandatory + */ + mandatory: external_exports.boolean().default(true).describe("Whether this requirement is mandatory"), + /** + * Compliance status + */ + compliant: external_exports.boolean().optional().describe("Whether the supplier meets this requirement"), + /** + * Evidence or notes for compliance assessment + */ + evidence: external_exports.string().optional().describe("Compliance evidence or assessment notes") +}).describe("Individual supplier security requirement"); +var SupplierSecurityAssessmentSchema2 = external_exports.object({ + /** + * Unique supplier identifier + */ + supplierId: external_exports.string().describe("Unique supplier identifier"), + /** + * Supplier name + */ + supplierName: external_exports.string().describe("Supplier display name"), + /** + * Risk classification + */ + riskLevel: SupplierRiskLevelSchema2.describe("Supplier risk classification"), + /** + * Assessment status + */ + status: SupplierAssessmentStatusSchema2.describe("Assessment status"), + /** + * User or team who performed the assessment + */ + assessedBy: external_exports.string().describe("Assessor user ID or team"), + /** + * Assessment completion timestamp (Unix milliseconds) + */ + assessedAt: external_exports.number().describe("Assessment timestamp"), + /** + * Assessment validity expiry (Unix milliseconds) + */ + validUntil: external_exports.number().describe("Assessment validity expiry timestamp"), + /** + * Security requirements assessed + */ + requirements: external_exports.array(SupplierSecurityRequirementSchema2).describe("Security requirements and their compliance status"), + /** + * Overall compliance result + */ + overallCompliant: external_exports.boolean().describe("Whether supplier meets all mandatory requirements"), + /** + * Data classifications shared with this supplier + */ + dataClassificationsShared: external_exports.array(DataClassificationSchema2).optional().describe("Data classifications shared with supplier"), + /** + * Services provided by the supplier + */ + servicesProvided: external_exports.array(external_exports.string()).optional().describe("Services provided by this supplier"), + /** + * Certifications held by the supplier + */ + certifications: external_exports.array(external_exports.string()).optional().describe("Supplier certifications (e.g., ISO 27001, SOC 2)"), + /** + * Remediation items for non-compliant requirements + */ + remediationItems: external_exports.array(external_exports.object({ + requirementId: external_exports.string().describe("Non-compliant requirement ID"), + action: external_exports.string().describe("Required remediation action"), + deadline: external_exports.number().describe("Remediation deadline timestamp"), + status: external_exports.enum(["pending", "in_progress", "completed"]).default("pending").describe("Remediation status") + })).optional().describe("Remediation items for non-compliant requirements"), + /** + * Custom metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs") +}).describe("Supplier security assessment record per ISO 27001:2022 A.5.19\u2013A.5.21"); +var SupplierSecurityPolicySchema2 = external_exports.object({ + /** + * Whether supplier security management is enabled + */ + enabled: external_exports.boolean().default(true).describe("Enable supplier security management"), + /** + * Reassessment interval in days + */ + reassessmentIntervalDays: external_exports.number().default(365).describe("Supplier reassessment interval in days"), + /** + * Whether to require supplier security assessment before onboarding + */ + requirePreOnboardingAssessment: external_exports.boolean().default(true).describe("Require security assessment before supplier onboarding"), + /** + * Minimum risk level that requires formal assessment + */ + formalAssessmentThreshold: SupplierRiskLevelSchema2.default("medium").describe("Minimum risk level requiring formal assessment"), + /** + * Whether to monitor supplier security changes (A.5.22) + */ + monitorChanges: external_exports.boolean().default(true).describe("Monitor supplier security posture changes"), + /** + * Required certifications for critical suppliers + */ + requiredCertifications: external_exports.array(external_exports.string()).default([]).describe("Required certifications for critical-risk suppliers") +}).describe("Organization-level supplier security management policy per ISO 27001:2022"); +var TrainingCategorySchema2 = external_exports.enum([ + "security_awareness", + // General security awareness + "data_protection", + // Data handling and privacy + "incident_response", + // Incident reporting and response + "access_control", + // Access management best practices + "phishing_awareness", + // Phishing and social engineering + "compliance", + // Regulatory compliance (GDPR, HIPAA, etc.) + "secure_development", + // Secure coding and development practices + "physical_security", + // Physical security awareness + "business_continuity", + // Business continuity and disaster recovery + "other" + // Other training categories +]); +var TrainingCompletionStatusSchema2 = external_exports.enum([ + "not_started", + // Training not yet begun + "in_progress", + // Training currently underway + "completed", + // Training completed successfully + "failed", + // Training assessment not passed + "expired" + // Training certification has expired +]); +var TrainingCourseSchema2 = external_exports.object({ + /** + * Unique course identifier + */ + id: external_exports.string().describe("Unique course identifier"), + /** + * Course title + */ + title: external_exports.string().describe("Course title"), + /** + * Course description and objectives + */ + description: external_exports.string().describe("Course description and learning objectives"), + /** + * Training category + */ + category: TrainingCategorySchema2.describe("Training category"), + /** + * Estimated duration in minutes + */ + durationMinutes: external_exports.number().min(1).describe("Estimated course duration in minutes"), + /** + * Whether this training is mandatory + */ + mandatory: external_exports.boolean().default(false).describe("Whether training is mandatory"), + /** + * Target roles or groups for this training + */ + targetRoles: external_exports.array(external_exports.string()).describe("Target roles or groups"), + /** + * Validity period in days before recertification is needed + */ + validityDays: external_exports.number().optional().describe("Certification validity period in days"), + /** + * Minimum passing score (percentage) for assessment + */ + passingScore: external_exports.number().min(0).max(100).optional().describe("Minimum passing score percentage"), + /** + * Course version for tracking content updates + */ + version: external_exports.string().optional().describe("Course content version") +}).describe("Security training course definition"); +var TrainingRecordSchema2 = external_exports.object({ + /** + * Reference to the course ID + */ + courseId: external_exports.string().describe("Training course identifier"), + /** + * User who completed (or is assigned) the training + */ + userId: external_exports.string().describe("User identifier"), + /** + * Completion status + */ + status: TrainingCompletionStatusSchema2.describe("Training completion status"), + /** + * Training assignment date (Unix milliseconds) + */ + assignedAt: external_exports.number().describe("Assignment timestamp"), + /** + * Training completion date (Unix milliseconds) + */ + completedAt: external_exports.number().optional().describe("Completion timestamp"), + /** + * Assessment score (percentage) + */ + score: external_exports.number().min(0).max(100).optional().describe("Assessment score percentage"), + /** + * Certification expiry date (Unix milliseconds) + */ + expiresAt: external_exports.number().optional().describe("Certification expiry timestamp"), + /** + * Notes or comments from instructor or system + */ + notes: external_exports.string().optional().describe("Training notes or comments") +}).describe("Individual training completion record"); +var TrainingPlanSchema2 = external_exports.object({ + /** + * Whether training management is enabled + */ + enabled: external_exports.boolean().default(true).describe("Enable training management"), + /** + * Training courses in the plan + */ + courses: external_exports.array(TrainingCourseSchema2).describe("Training courses"), + /** + * Default recertification interval in days + */ + recertificationIntervalDays: external_exports.number().default(365).describe("Default recertification interval in days"), + /** + * Whether to track training completion for compliance reporting + */ + trackCompletion: external_exports.boolean().default(true).describe("Track training completion for compliance"), + /** + * Grace period in days after expiry before non-compliance escalation + */ + gracePeriodDays: external_exports.number().default(30).describe("Grace period in days after certification expiry"), + /** + * Whether to send reminders for upcoming training deadlines + */ + sendReminders: external_exports.boolean().default(true).describe("Send reminders for upcoming training deadlines"), + /** + * Days before deadline to send first reminder + */ + reminderDaysBefore: external_exports.number().default(14).describe("Days before deadline to send first reminder") +}).describe("Organizational training plan per ISO 27001:2022 A.6.3"); +var CronScheduleSchema2 = external_exports.object({ + type: external_exports.literal("cron"), + expression: external_exports.string().describe('Cron expression (e.g., "0 0 * * *" for daily at midnight)'), + timezone: external_exports.string().optional().default("UTC").describe('Timezone for cron execution (e.g., "America/New_York")') +}); +var IntervalScheduleSchema2 = external_exports.object({ + type: external_exports.literal("interval"), + intervalMs: external_exports.number().int().positive().describe("Interval in milliseconds") +}); +var OnceScheduleSchema2 = external_exports.object({ + type: external_exports.literal("once"), + at: external_exports.string().datetime().describe("ISO 8601 datetime when to execute") +}); +var ScheduleSchema2 = external_exports.discriminatedUnion("type", [ + CronScheduleSchema2, + IntervalScheduleSchema2, + OnceScheduleSchema2 +]); +var RetryPolicySchema2 = external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum number of retry attempts"), + backoffMs: external_exports.number().int().positive().default(1e3).describe("Initial backoff delay in milliseconds"), + backoffMultiplier: external_exports.number().positive().default(2).describe("Multiplier for exponential backoff") +}); +var JobSchema2 = external_exports.object({ + id: external_exports.string().describe("Unique job identifier"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Job name (snake_case)"), + schedule: ScheduleSchema2.describe("Job schedule configuration"), + handler: external_exports.string().describe('Handler path (e.g. "path/to/file:functionName") or script ID'), + retryPolicy: RetryPolicySchema2.optional().describe("Retry policy configuration"), + timeout: external_exports.number().int().positive().optional().describe("Timeout in milliseconds"), + enabled: external_exports.boolean().default(true).describe("Whether the job is enabled") +}); +var JobExecutionStatus2 = external_exports.enum([ + "running", + "success", + "failed", + "timeout" +]); +var JobExecutionSchema2 = external_exports.object({ + jobId: external_exports.string().describe("Job identifier"), + startedAt: external_exports.string().datetime().describe("ISO 8601 datetime when execution started"), + completedAt: external_exports.string().datetime().optional().describe("ISO 8601 datetime when execution completed"), + status: JobExecutionStatus2.describe("Execution status"), + error: external_exports.string().optional().describe("Error message if failed"), + duration: external_exports.number().int().optional().describe("Execution duration in milliseconds") +}); +var TaskPriority2 = external_exports.enum([ + "critical", + // 0 - Must execute immediately + "high", + // 1 - Execute soon + "normal", + // 2 - Default priority + "low", + // 3 - Execute when resources available + "background" + // 4 - Execute during low-traffic periods +]); +var TASK_PRIORITY_VALUES = { + critical: 0, + high: 1, + normal: 2, + low: 3, + background: 4 +}; +var TaskStatus2 = external_exports.enum([ + "pending", + // Waiting to be processed + "queued", + // In queue, ready for worker + "processing", + // Currently being executed + "completed", + // Successfully completed + "failed", + // Failed (may retry) + "cancelled", + // Manually cancelled + "timeout", + // Exceeded execution timeout + "dead" + // Moved to dead letter queue +]); +var TaskRetryPolicySchema2 = external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retry attempts"), + backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy between retries"), + initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay in milliseconds"), + maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Maximum retry delay in milliseconds"), + backoffMultiplier: external_exports.number().positive().default(2).describe("Multiplier for exponential backoff") +}); +var TaskSchema2 = external_exports.object({ + /** + * Unique task identifier + */ + id: external_exports.string().describe("Unique task identifier"), + /** + * Task type (handler identifier) + */ + type: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Task type (snake_case)"), + /** + * Task payload data + */ + payload: external_exports.unknown().describe("Task payload data"), + /** + * Queue name + */ + queue: external_exports.string().default("default").describe("Queue name"), + /** + * Task priority + */ + priority: TaskPriority2.default("normal").describe("Task priority level"), + /** + * Retry policy + */ + retryPolicy: TaskRetryPolicySchema2.optional().describe("Retry policy configuration"), + /** + * Execution timeout in milliseconds + */ + timeoutMs: external_exports.number().int().positive().optional().describe("Task timeout in milliseconds"), + /** + * Scheduled execution time + */ + scheduledAt: external_exports.string().datetime().optional().describe("ISO 8601 datetime to execute task"), + /** + * Maximum execution attempts + */ + attempts: external_exports.number().int().min(0).default(0).describe("Number of execution attempts"), + /** + * Task status + */ + status: TaskStatus2.default("pending").describe("Current task status"), + /** + * Task metadata + */ + metadata: external_exports.object({ + createdAt: external_exports.string().datetime().optional().describe("When task was created"), + updatedAt: external_exports.string().datetime().optional().describe("Last update time"), + createdBy: external_exports.string().optional().describe("User who created task"), + tags: external_exports.array(external_exports.string()).optional().describe("Task tags for filtering") + }).optional().describe("Task metadata") +}); +var TaskExecutionResultSchema2 = external_exports.object({ + /** + * Task identifier + */ + taskId: external_exports.string().describe("Task identifier"), + /** + * Execution status + */ + status: TaskStatus2.describe("Execution status"), + /** + * Execution result data + */ + result: external_exports.unknown().optional().describe("Execution result data"), + /** + * Error information + */ + error: external_exports.object({ + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Error stack trace"), + code: external_exports.string().optional().describe("Error code") + }).optional().describe("Error details if failed"), + /** + * Execution duration + */ + durationMs: external_exports.number().int().optional().describe("Execution duration in milliseconds"), + /** + * Execution timestamps + */ + startedAt: external_exports.string().datetime().describe("When execution started"), + completedAt: external_exports.string().datetime().optional().describe("When execution completed"), + /** + * Retry information + */ + attempt: external_exports.number().int().min(1).describe("Attempt number (1-indexed)"), + willRetry: external_exports.boolean().describe("Whether task will be retried") +}); +var QueueConfigSchema2 = external_exports.object({ + /** + * Queue name + */ + name: external_exports.string().describe("Queue name (snake_case)"), + /** + * Maximum concurrent workers + */ + concurrency: external_exports.number().int().min(1).default(5).describe("Max concurrent task executions"), + /** + * Rate limiting + */ + rateLimit: external_exports.object({ + max: external_exports.number().int().positive().describe("Maximum tasks per duration"), + duration: external_exports.number().int().positive().describe("Duration in milliseconds") + }).optional().describe("Rate limit configuration"), + /** + * Default retry policy + */ + defaultRetryPolicy: TaskRetryPolicySchema2.optional().describe("Default retry policy for tasks"), + /** + * Dead letter queue + */ + deadLetterQueue: external_exports.string().optional().describe("Dead letter queue name"), + /** + * Queue priority + */ + priority: external_exports.number().int().min(0).default(0).describe("Queue priority (lower = higher priority)"), + /** + * Auto-scaling configuration + */ + autoScale: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable auto-scaling"), + minWorkers: external_exports.number().int().min(1).default(1).describe("Minimum workers"), + maxWorkers: external_exports.number().int().min(1).default(10).describe("Maximum workers"), + scaleUpThreshold: external_exports.number().int().positive().default(100).describe("Queue size to scale up"), + scaleDownThreshold: external_exports.number().int().min(0).default(10).describe("Queue size to scale down") + }).optional().describe("Auto-scaling configuration") +}); +var BatchTaskSchema2 = external_exports.object({ + /** + * Batch job identifier + */ + id: external_exports.string().describe("Unique batch job identifier"), + /** + * Task type for processing each item + */ + type: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Task type (snake_case)"), + /** + * Items to process + */ + items: external_exports.array(external_exports.unknown()).describe("Array of items to process"), + /** + * Batch size (items per task) + */ + batchSize: external_exports.number().int().min(1).default(100).describe("Number of items per batch"), + /** + * Queue name + */ + queue: external_exports.string().default("batch").describe("Queue for batch tasks"), + /** + * Priority + */ + priority: TaskPriority2.default("normal").describe("Batch task priority"), + /** + * Parallel processing + */ + parallel: external_exports.boolean().default(true).describe("Process batches in parallel"), + /** + * Stop on error + */ + stopOnError: external_exports.boolean().default(false).describe("Stop batch if any item fails"), + /** + * Progress callback + * + * Called after each batch completes to report progress. + * Invoked asynchronously and should not throw errors. + * If the callback throws, the error is logged but batch processing continues. + * + * @param progress - Object containing processed count, total count, and failed count + */ + onProgress: external_exports.function().input(external_exports.tuple([external_exports.object({ + processed: external_exports.number(), + total: external_exports.number(), + failed: external_exports.number() + })])).output(external_exports.void()).optional().describe("Progress callback function (called after each batch)") +}); +var BatchProgressSchema2 = external_exports.object({ + /** + * Batch job identifier + */ + batchId: external_exports.string().describe("Batch job identifier"), + /** + * Total items + */ + total: external_exports.number().int().min(0).describe("Total number of items"), + /** + * Processed items + */ + processed: external_exports.number().int().min(0).default(0).describe("Items processed"), + /** + * Successful items + */ + succeeded: external_exports.number().int().min(0).default(0).describe("Items succeeded"), + /** + * Failed items + */ + failed: external_exports.number().int().min(0).default(0).describe("Items failed"), + /** + * Progress percentage + */ + percentage: external_exports.number().min(0).max(100).describe("Progress percentage"), + /** + * Status + */ + status: external_exports.enum(["pending", "running", "completed", "failed", "cancelled"]).describe("Batch status"), + /** + * Timestamps + */ + startedAt: external_exports.string().datetime().optional().describe("When batch started"), + completedAt: external_exports.string().datetime().optional().describe("When batch completed") +}); +var WorkerConfigSchema2 = external_exports.object({ + /** + * Worker name + */ + name: external_exports.string().describe("Worker name"), + /** + * Queues to process + */ + queues: external_exports.array(external_exports.string()).min(1).describe("Queue names to process"), + /** + * Queue configurations + */ + queueConfigs: external_exports.array(QueueConfigSchema2).optional().describe("Queue configurations"), + /** + * Polling interval + */ + pollIntervalMs: external_exports.number().int().positive().default(1e3).describe("Queue polling interval in milliseconds"), + /** + * Visibility timeout + */ + visibilityTimeoutMs: external_exports.number().int().positive().default(3e4).describe("How long a task is invisible after being claimed"), + /** + * Task timeout + */ + defaultTimeoutMs: external_exports.number().int().positive().default(3e5).describe("Default task timeout in milliseconds"), + /** + * Graceful shutdown timeout + */ + shutdownTimeoutMs: external_exports.number().int().positive().default(3e4).describe("Graceful shutdown timeout in milliseconds"), + /** + * Task handlers + */ + handlers: external_exports.record(external_exports.string(), external_exports.function()).optional().describe("Task type handlers") +}); +var WorkerStatsSchema2 = external_exports.object({ + /** + * Worker name + */ + workerName: external_exports.string().describe("Worker name"), + /** + * Total tasks processed + */ + totalProcessed: external_exports.number().int().min(0).describe("Total tasks processed"), + /** + * Successful tasks + */ + succeeded: external_exports.number().int().min(0).describe("Successful tasks"), + /** + * Failed tasks + */ + failed: external_exports.number().int().min(0).describe("Failed tasks"), + /** + * Active tasks + */ + active: external_exports.number().int().min(0).describe("Currently active tasks"), + /** + * Average execution time + */ + avgExecutionMs: external_exports.number().min(0).optional().describe("Average execution time in milliseconds"), + /** + * Uptime + */ + uptimeMs: external_exports.number().int().min(0).describe("Worker uptime in milliseconds"), + /** + * Queue stats + */ + queues: external_exports.record(external_exports.string(), external_exports.object({ + pending: external_exports.number().int().min(0).describe("Pending tasks"), + active: external_exports.number().int().min(0).describe("Active tasks"), + completed: external_exports.number().int().min(0).describe("Completed tasks"), + failed: external_exports.number().int().min(0).describe("Failed tasks") + })).optional().describe("Per-queue statistics") +}); +var Task2 = Object.assign(TaskSchema2, { + create: (task) => task +}); +var QueueConfig2 = Object.assign(QueueConfigSchema2, { + create: (config4) => config4 +}); +var WorkerConfig2 = Object.assign(WorkerConfigSchema2, { + create: (config4) => config4 +}); +var BatchTask2 = Object.assign(BatchTaskSchema2, { + create: (batch) => batch +}); +var EmailTemplateSchema2 = external_exports.object({ + /** + * Unique identifier for the email template + */ + id: external_exports.string().describe("Template identifier"), + /** + * Email subject line (supports variable interpolation) + */ + subject: external_exports.string().describe("Email subject"), + /** + * Email body content + */ + body: external_exports.string().describe("Email body content"), + /** + * Content type of the email body + * @default 'html' + */ + bodyType: external_exports.enum(["text", "html", "markdown"]).optional().default("html").describe("Body content type"), + /** + * List of template variables for dynamic content + */ + variables: external_exports.array(external_exports.string()).optional().describe("Template variables"), + /** + * File attachments to include with the email + */ + attachments: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Attachment filename"), + url: external_exports.string().url().describe("Attachment URL") + })).optional().describe("Email attachments") +}); +var SMSTemplateSchema2 = external_exports.object({ + /** + * Unique identifier for the SMS template + */ + id: external_exports.string().describe("Template identifier"), + /** + * SMS message content (supports variable interpolation) + */ + message: external_exports.string().describe("SMS message content"), + /** + * Maximum character length for the SMS + * @default 160 + */ + maxLength: external_exports.number().optional().default(160).describe("Maximum message length"), + /** + * List of template variables for dynamic content + */ + variables: external_exports.array(external_exports.string()).optional().describe("Template variables") +}); +var PushNotificationSchema2 = external_exports.object({ + /** + * Notification title + */ + title: external_exports.string().describe("Notification title"), + /** + * Notification body text + */ + body: external_exports.string().describe("Notification body"), + /** + * Icon URL to display with notification + */ + icon: external_exports.string().url().optional().describe("Notification icon URL"), + /** + * Badge count to display on app icon + */ + badge: external_exports.number().optional().describe("Badge count"), + /** + * Custom data payload + */ + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom data"), + /** + * Action buttons for the notification + */ + actions: external_exports.array(external_exports.object({ + action: external_exports.string().describe("Action identifier"), + title: external_exports.string().describe("Action button title") + })).optional().describe("Notification actions") +}); +var InAppNotificationSchema2 = external_exports.object({ + /** + * Notification title + */ + title: external_exports.string().describe("Notification title"), + /** + * Notification message content + */ + message: external_exports.string().describe("Notification message"), + /** + * Notification severity type + */ + type: external_exports.enum(["info", "success", "warning", "error"]).describe("Notification type"), + /** + * Optional URL to navigate to when clicked + */ + actionUrl: external_exports.string().optional().describe("Action URL"), + /** + * Whether the notification can be dismissed by the user + * @default true + */ + dismissible: external_exports.boolean().optional().default(true).describe("User dismissible"), + /** + * Timestamp when notification expires (Unix milliseconds) + */ + expiresAt: external_exports.number().optional().describe("Expiration timestamp") +}); +var NotificationChannelSchema2 = external_exports.enum([ + "email", + "sms", + "push", + "in-app", + "slack", + "teams", + "webhook" +]); +var NotificationConfigSchema22 = external_exports.object({ + /** + * Unique identifier for this notification configuration + */ + id: external_exports.string().describe("Notification ID"), + /** + * Human-readable name for this notification + */ + name: external_exports.string().describe("Notification name"), + /** + * Delivery channel for the notification + */ + channel: NotificationChannelSchema2.describe("Notification channel"), + /** + * Notification template based on channel type + */ + template: external_exports.union([ + EmailTemplateSchema2, + SMSTemplateSchema2, + PushNotificationSchema2, + InAppNotificationSchema2 + ]).describe("Notification template"), + /** + * Recipient configuration + */ + recipients: external_exports.object({ + /** + * Primary recipients + */ + to: external_exports.array(external_exports.string()).describe("Primary recipients"), + /** + * CC recipients (email only) + */ + cc: external_exports.array(external_exports.string()).optional().describe("CC recipients"), + /** + * BCC recipients (email only) + */ + bcc: external_exports.array(external_exports.string()).optional().describe("BCC recipients") + }).describe("Recipients"), + /** + * Scheduling configuration + */ + schedule: external_exports.object({ + /** + * Scheduling type + */ + type: external_exports.enum(["immediate", "delayed", "scheduled"]).describe("Schedule type"), + /** + * Delay in milliseconds (for delayed type) + */ + delay: external_exports.number().optional().describe("Delay in milliseconds"), + /** + * Scheduled send time (Unix timestamp in milliseconds) + */ + scheduledAt: external_exports.number().optional().describe("Scheduled timestamp") + }).optional().describe("Scheduling"), + /** + * Retry policy for failed deliveries + */ + retryPolicy: external_exports.object({ + /** + * Enable automatic retries + * @default true + */ + enabled: external_exports.boolean().optional().default(true).describe("Enable retries"), + /** + * Maximum number of retry attempts + * @default 3 + */ + maxRetries: external_exports.number().optional().default(3).describe("Max retry attempts"), + /** + * Backoff strategy for retries + */ + backoffStrategy: external_exports.enum(["exponential", "linear", "fixed"]).describe("Backoff strategy") + }).optional().describe("Retry policy"), + /** + * Delivery tracking configuration + */ + tracking: external_exports.object({ + /** + * Track when emails are opened + * @default false + */ + trackOpens: external_exports.boolean().optional().default(false).describe("Track opens"), + /** + * Track when links are clicked + * @default false + */ + trackClicks: external_exports.boolean().optional().default(false).describe("Track clicks"), + /** + * Track delivery status + * @default true + */ + trackDelivery: external_exports.boolean().optional().default(true).describe("Track delivery") + }).optional().describe("Tracking configuration") +}); +var LocaleSchema3 = external_exports.string().describe("BCP-47 Language Tag (e.g. en-US, zh-CN)"); +var FieldTranslationSchema3 = external_exports.object({ + label: external_exports.string().optional().describe("Translated field label"), + help: external_exports.string().optional().describe("Translated help text"), + placeholder: external_exports.string().optional().describe("Translated placeholder text for form inputs"), + options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Option value to translated label map") +}).describe("Translation data for a single field"); +var ObjectTranslationDataSchema3 = external_exports.object({ + /** Translated singular label for the object */ + label: external_exports.string().describe("Translated singular label"), + /** Translated plural label for the object */ + pluralLabel: external_exports.string().optional().describe("Translated plural label"), + /** Field-level translations keyed by field name (snake_case) */ + fields: external_exports.record(external_exports.string(), FieldTranslationSchema3).optional().describe("Field-level translations") +}).describe("Translation data for a single object"); +var TranslationDataSchema3 = external_exports.object({ + /** Object translations */ + objects: external_exports.record(external_exports.string(), ObjectTranslationDataSchema3).optional().describe("Object translations keyed by object name"), + /** App/Menu translations */ + apps: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().describe("Translated app label"), + description: external_exports.string().optional().describe("Translated app description") + })).optional().describe("App translations keyed by app name"), + /** UI Messages */ + messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID"), + /** Validation Error Messages */ + validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%"})') +}).describe("Translation data for objects, apps, and UI messages"); +var TranslationBundleSchema2 = external_exports.record(LocaleSchema3, TranslationDataSchema3).describe("Map of locale codes to translation data"); +var TranslationFileOrganizationSchema3 = external_exports.enum([ + "bundled", + "per_locale", + "per_namespace" +]).describe("Translation file organization strategy"); +var MessageFormatSchema3 = external_exports.enum([ + "icu", + "simple" +]).describe("Message interpolation format: ICU MessageFormat or simple {variable} replacement"); +var TranslationConfigSchema2 = external_exports.object({ + /** Default locale for the application */ + defaultLocale: LocaleSchema3.describe('Default locale (e.g., "en")'), + /** Supported BCP-47 locale codes */ + supportedLocales: external_exports.array(LocaleSchema3).describe("Supported BCP-47 locale codes"), + /** Fallback locale when translation is not found */ + fallbackLocale: LocaleSchema3.optional().describe("Fallback locale code"), + /** How translation files are organized on disk */ + fileOrganization: TranslationFileOrganizationSchema3.default("per_locale").describe("File organization strategy"), + /** + * Message interpolation format. + * When set to `'icu'`, messages and validationMessages are expected to use + * ICU MessageFormat syntax (plurals, select, number/date skeletons). + * @default 'simple' + */ + messageFormat: MessageFormatSchema3.default("simple").describe("Message interpolation format (ICU MessageFormat or simple)"), + /** Load translations on demand instead of eagerly */ + lazyLoad: external_exports.boolean().default(false).describe("Load translations on demand"), + /** Cache loaded translations in memory */ + cache: external_exports.boolean().default(true).describe("Cache loaded translations") +}).describe("Internationalization configuration"); +var OptionTranslationMapSchema3 = external_exports.record(external_exports.string(), external_exports.string()).describe("Option value to translated label map"); +var ObjectTranslationNodeSchema3 = external_exports.object({ + /** Translated singular label */ + label: external_exports.string().describe("Translated singular label"), + /** Translated plural label */ + pluralLabel: external_exports.string().optional().describe("Translated plural label"), + /** Translated object description */ + description: external_exports.string().optional().describe("Translated object description"), + /** Translated help text shown in tooltips or guidance panels */ + helpText: external_exports.string().optional().describe("Translated help text for the object"), + /** Field-level translations keyed by field name (snake_case) */ + fields: external_exports.record(external_exports.string(), FieldTranslationSchema3).optional().describe("Field translations keyed by field name"), + /** + * Global picklist / select option overrides scoped to this object. + * Keyed by field name → { optionValue: translatedLabel }. + */ + _options: external_exports.record(external_exports.string(), OptionTranslationMapSchema3).optional().describe("Object-scoped picklist option translations keyed by field name"), + /** View translations keyed by view name */ + _views: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated view label"), + description: external_exports.string().optional().describe("Translated view description") + })).optional().describe("View translations keyed by view name"), + /** Section (form section / tab) translations keyed by section name */ + _sections: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated section label") + })).optional().describe("Section translations keyed by section name"), + /** Action translations keyed by action name */ + _actions: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated action label"), + confirmMessage: external_exports.string().optional().describe("Translated confirmation message") + })).optional().describe("Action translations keyed by action name"), + /** Notification message translations keyed by notification name */ + _notifications: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated notification title"), + body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") + })).optional().describe("Notification translations keyed by notification name"), + /** Error message translations keyed by error code */ + _errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Error message translations keyed by error code") +}).describe("Object-first aggregated translation node"); +var AppTranslationBundleSchema2 = external_exports.object({ + /** + * Bundle-level metadata. + * Provides locale-aware rendering hints such as text direction (bidi) + * and the canonical locale code this bundle represents. + */ + _meta: external_exports.object({ + /** BCP-47 locale code this bundle represents */ + locale: external_exports.string().optional().describe("BCP-47 locale code for this bundle"), + /** Text direction for the locale */ + direction: external_exports.enum(["ltr", "rtl"]).optional().describe("Text direction: left-to-right or right-to-left") + }).optional().describe("Bundle-level metadata (locale, bidi direction)"), + /** + * Namespace for plugin/extension isolation. + * When multiple plugins contribute translations, each should use a unique + * namespace to avoid key collisions (e.g. "crm", "helpdesk", "plugin-xyz"). + */ + namespace: external_exports.string().optional().describe("Namespace for plugin isolation to avoid translation key collisions"), + /** Object-first translations keyed by object name (snake_case) */ + o: external_exports.record(external_exports.string(), ObjectTranslationNodeSchema3).optional().describe("Object-first translations keyed by object name"), + /** Global picklist options not bound to any specific object */ + _globalOptions: external_exports.record(external_exports.string(), OptionTranslationMapSchema3).optional().describe("Global picklist option translations keyed by option set name"), + /** App-level translations */ + app: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().describe("Translated app label"), + description: external_exports.string().optional().describe("Translated app description") + })).optional().describe("App translations keyed by app name"), + /** Navigation menu translations */ + nav: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Navigation item translations keyed by nav item name"), + /** Dashboard translations keyed by dashboard name */ + dashboard: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated dashboard label"), + description: external_exports.string().optional().describe("Translated dashboard description") + })).optional().describe("Dashboard translations keyed by dashboard name"), + /** Report translations keyed by report name */ + reports: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().optional().describe("Translated report label"), + description: external_exports.string().optional().describe("Translated report description") + })).optional().describe("Report translations keyed by report name"), + /** Page translations keyed by page name */ + pages: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated page title"), + description: external_exports.string().optional().describe("Translated page description") + })).optional().describe("Page translations keyed by page name"), + /** UI message translations (supports ICU MessageFormat when enabled) */ + messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID (supports ICU MessageFormat)"), + /** Validation error message translations (supports ICU MessageFormat when enabled) */ + validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Validation error message translations keyed by rule name (supports ICU MessageFormat)"), + /** Global notification translations not bound to a specific object */ + notifications: external_exports.record(external_exports.string(), external_exports.object({ + title: external_exports.string().optional().describe("Translated notification title"), + body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") + })).optional().describe("Global notification translations keyed by notification name"), + /** Global error message translations not bound to a specific object */ + errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Global error message translations keyed by error code") +}).describe("Object-first application translation bundle for a single locale"); +var TranslationDiffStatusSchema3 = external_exports.enum([ + "missing", + "redundant", + "stale" +]).describe("Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)"); +var TranslationDiffItemSchema3 = external_exports.object({ + /** Dot-path translation key (e.g. "o.account.fields.website.label") */ + key: external_exports.string().describe("Dot-path translation key"), + /** Diff status */ + status: TranslationDiffStatusSchema3.describe("Diff status of this translation key"), + /** Object name if the key belongs to an object translation node */ + objectName: external_exports.string().optional().describe("Associated object name (snake_case)"), + /** Locale code */ + locale: external_exports.string().describe("BCP-47 locale code"), + /** + * Hash of the source metadata value at the time the translation was made. + * Used by CLI/Workbench to detect stale translations without a full diff. + */ + sourceHash: external_exports.string().optional().describe("Hash of source metadata for precise stale detection"), + /** + * AI-suggested translation text for missing or stale entries. + * Populated by AI translation hooks or TMS integrations. + */ + aiSuggested: external_exports.string().optional().describe("AI-suggested translation for this key"), + /** Confidence score (0-1) for the AI suggestion */ + aiConfidence: external_exports.number().min(0).max(1).optional().describe("AI suggestion confidence score (0\u20131)") +}).describe("A single translation diff item"); +var CoverageBreakdownEntrySchema3 = external_exports.object({ + /** Group category (e.g. "fields", "views", "actions", "messages") */ + group: external_exports.string().describe("Translation group category"), + /** Total translatable keys in this group */ + totalKeys: external_exports.number().int().nonnegative().describe("Total keys in this group"), + /** Number of translated keys in this group */ + translatedKeys: external_exports.number().int().nonnegative().describe("Translated keys in this group"), + /** Coverage percentage for this group */ + coveragePercent: external_exports.number().min(0).max(100).describe("Coverage percentage for this group") +}).describe("Coverage breakdown for a single translation group"); +var TranslationCoverageResultSchema2 = external_exports.object({ + /** BCP-47 locale code */ + locale: external_exports.string().describe("BCP-47 locale code"), + /** Optional object name scope */ + objectName: external_exports.string().optional().describe("Object name scope (omit for full bundle)"), + /** Total translatable keys derived from metadata */ + totalKeys: external_exports.number().int().nonnegative().describe("Total translatable keys from metadata"), + /** Number of keys that have a translation */ + translatedKeys: external_exports.number().int().nonnegative().describe("Number of translated keys"), + /** Number of missing translations */ + missingKeys: external_exports.number().int().nonnegative().describe("Number of missing translations"), + /** Number of redundant (orphaned) translations */ + redundantKeys: external_exports.number().int().nonnegative().describe("Number of redundant translations"), + /** Number of stale translations */ + staleKeys: external_exports.number().int().nonnegative().describe("Number of stale translations"), + /** Coverage percentage (0-100) */ + coveragePercent: external_exports.number().min(0).max(100).describe("Translation coverage percentage"), + /** Individual diff items */ + items: external_exports.array(TranslationDiffItemSchema3).describe("Detailed diff items"), + /** + * Per-group coverage breakdown for translation project management. + * Each entry represents a logical group (e.g. "fields", "views", "actions", + * "messages") with its own coverage statistics. + */ + breakdown: external_exports.array(CoverageBreakdownEntrySchema3).optional().describe("Per-group coverage breakdown") +}).describe("Aggregated translation coverage result"); +var TRANSLATE_PLACEHOLDER = "__TRANSLATE__"; +var OTOperationType2 = external_exports.enum([ + "insert", + // Insert characters at position + "delete", + // Delete characters at position + "retain" + // Keep characters (used for composing operations) +]); +var OTComponentSchema2 = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("insert"), + text: external_exports.string().describe("Text to insert"), + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Text formatting attributes (e.g., bold, italic)") + }), + external_exports.object({ + type: external_exports.literal("delete"), + count: external_exports.number().int().positive().describe("Number of characters to delete") + }), + external_exports.object({ + type: external_exports.literal("retain"), + count: external_exports.number().int().positive().describe("Number of characters to retain"), + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Attribute changes to apply") + }) +]); +var OTOperationSchema2 = external_exports.object({ + operationId: external_exports.string().uuid().describe("Unique operation identifier"), + documentId: external_exports.string().describe("Document identifier"), + userId: external_exports.string().describe("User who created the operation"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + components: external_exports.array(OTComponentSchema2).describe("Operation components"), + baseVersion: external_exports.number().int().nonnegative().describe("Document version this operation is based on"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when operation was created"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional operation metadata") +}); +var OTTransformResultSchema2 = external_exports.object({ + operation: OTOperationSchema2.describe("Transformed operation"), + transformed: external_exports.boolean().describe("Whether transformation was applied"), + conflicts: external_exports.array(external_exports.string()).optional().describe("Conflict descriptions if any") +}); +var CRDTType2 = external_exports.enum([ + "lww-register", + // Last-Write-Wins Register + "g-counter", + // Grow-only Counter + "pn-counter", + // Positive-Negative Counter + "g-set", + // Grow-only Set + "or-set", + // Observed-Remove Set + "lww-map", + // Last-Write-Wins Map + "text", + // CRDT-based Text (e.g., Yjs, Automerge) + "tree", + // CRDT-based Tree structure + "json" + // CRDT-based JSON (e.g., Automerge) +]); +var VectorClockSchema2 = external_exports.object({ + clock: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Map of replica ID to logical timestamp") +}); +var LWWRegisterSchema2 = external_exports.object({ + type: external_exports.literal("lww-register"), + value: external_exports.unknown().describe("Current register value"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of last write"), + replicaId: external_exports.string().describe("ID of replica that performed last write"), + vectorClock: VectorClockSchema2.optional().describe("Optional vector clock for causality tracking") +}); +var CounterOperationSchema2 = external_exports.object({ + replicaId: external_exports.string().describe("Replica identifier"), + delta: external_exports.number().int().describe("Change amount (positive for increment, negative for decrement)"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of operation") +}); +var GCounterSchema2 = external_exports.object({ + type: external_exports.literal("g-counter"), + counts: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Map of replica ID to count") +}); +var PNCounterSchema2 = external_exports.object({ + type: external_exports.literal("pn-counter"), + positive: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Positive increments per replica"), + negative: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Negative increments per replica") +}); +var ORSetElementSchema2 = external_exports.object({ + value: external_exports.unknown().describe("Element value"), + timestamp: external_exports.string().datetime().describe("Addition timestamp"), + replicaId: external_exports.string().describe("Replica that added the element"), + uid: external_exports.string().uuid().describe("Unique identifier for this addition"), + removed: external_exports.boolean().optional().default(false).describe("Whether element has been removed") +}); +var ORSetSchema2 = external_exports.object({ + type: external_exports.literal("or-set"), + elements: external_exports.array(ORSetElementSchema2).describe("Set elements with metadata") +}); +var TextCRDTOperationSchema2 = external_exports.object({ + operationId: external_exports.string().uuid().describe("Unique operation identifier"), + replicaId: external_exports.string().describe("Replica identifier"), + position: external_exports.number().int().nonnegative().describe("Position in document"), + insert: external_exports.string().optional().describe("Text to insert"), + delete: external_exports.number().int().positive().optional().describe("Number of characters to delete"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of operation"), + lamportTimestamp: external_exports.number().int().nonnegative().describe("Lamport timestamp for ordering") +}); +var TextCRDTStateSchema2 = external_exports.object({ + type: external_exports.literal("text"), + documentId: external_exports.string().describe("Document identifier"), + content: external_exports.string().describe("Current text content"), + operations: external_exports.array(TextCRDTOperationSchema2).describe("History of operations"), + lamportClock: external_exports.number().int().nonnegative().describe("Current Lamport clock value"), + vectorClock: VectorClockSchema2.describe("Vector clock for causality") +}); +var CRDTStateSchema2 = external_exports.discriminatedUnion("type", [ + LWWRegisterSchema2, + GCounterSchema2, + PNCounterSchema2, + ORSetSchema2, + TextCRDTStateSchema2 +]); +var CRDTMergeResultSchema2 = external_exports.object({ + state: CRDTStateSchema2.describe("Merged CRDT state"), + conflicts: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Conflict type"), + description: external_exports.string().describe("Conflict description"), + resolved: external_exports.boolean().describe("Whether conflict was automatically resolved") + })).optional().describe("Conflicts encountered during merge") +}); +var CursorColorPreset2 = external_exports.enum([ + "blue", + "green", + "red", + "yellow", + "purple", + "orange", + "pink", + "teal", + "indigo", + "cyan" +]); +var CursorStyleSchema2 = external_exports.object({ + color: external_exports.union([CursorColorPreset2, external_exports.string()]).describe("Cursor color (preset or custom hex)"), + opacity: external_exports.number().min(0).max(1).optional().default(1).describe("Cursor opacity (0-1)"), + label: external_exports.string().optional().describe("Label to display with cursor (usually username)"), + showLabel: external_exports.boolean().optional().default(true).describe("Whether to show label"), + pulseOnUpdate: external_exports.boolean().optional().default(true).describe("Whether to pulse when cursor moves") +}); +var CursorSelectionSchema2 = external_exports.object({ + anchor: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Anchor line number"), + column: external_exports.number().int().nonnegative().describe("Anchor column number") + }).describe("Selection anchor (start point)"), + focus: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Focus line number"), + column: external_exports.number().int().nonnegative().describe("Focus column number") + }).describe("Selection focus (end point)"), + direction: external_exports.enum(["forward", "backward"]).optional().describe("Selection direction") +}); +var CollaborativeCursorSchema2 = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + documentId: external_exports.string().describe("Document identifier"), + userName: external_exports.string().describe("Display name of user"), + position: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Cursor line number (0-indexed)"), + column: external_exports.number().int().nonnegative().describe("Cursor column number (0-indexed)") + }).describe("Current cursor position"), + selection: CursorSelectionSchema2.optional().describe("Current text selection"), + style: CursorStyleSchema2.describe("Visual style for this cursor"), + isTyping: external_exports.boolean().optional().default(false).describe("Whether user is currently typing"), + lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last cursor update"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional cursor metadata") +}); +var CursorUpdateSchema2 = external_exports.object({ + position: external_exports.object({ + line: external_exports.number().int().nonnegative(), + column: external_exports.number().int().nonnegative() + }).optional().describe("Updated cursor position"), + selection: CursorSelectionSchema2.optional().describe("Updated selection"), + isTyping: external_exports.boolean().optional().describe("Updated typing state"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") +}); +var UserActivityStatus2 = external_exports.enum([ + "active", + // User is actively editing + "idle", + // User is idle but connected + "viewing", + // User is viewing but not editing + "disconnected" + // User is disconnected +]); +var AwarenessUserStateSchema2 = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + userName: external_exports.string().describe("Display name"), + userAvatar: external_exports.string().optional().describe("User avatar URL"), + status: UserActivityStatus2.describe("Current activity status"), + currentDocument: external_exports.string().optional().describe("Document ID user is currently editing"), + currentView: external_exports.string().optional().describe("Current view/page user is on"), + lastActivity: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), + joinedAt: external_exports.string().datetime().describe("ISO 8601 datetime when user joined session"), + permissions: external_exports.array(external_exports.string()).optional().describe("User permissions in this session"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional user state metadata") +}); +var AwarenessSessionSchema2 = external_exports.object({ + sessionId: external_exports.string().uuid().describe("Session identifier"), + documentId: external_exports.string().optional().describe("Document ID this session is for"), + users: external_exports.array(AwarenessUserStateSchema2).describe("Active users in session"), + startedAt: external_exports.string().datetime().describe("ISO 8601 datetime when session started"), + lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last update"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Session metadata") +}); +var AwarenessUpdateSchema2 = external_exports.object({ + status: UserActivityStatus2.optional().describe("Updated status"), + currentDocument: external_exports.string().optional().describe("Updated current document"), + currentView: external_exports.string().optional().describe("Updated current view"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") +}); +var AwarenessEventSchema2 = external_exports.object({ + eventId: external_exports.string().uuid().describe("Event identifier"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + eventType: external_exports.enum([ + "user.joined", + "user.left", + "user.updated", + "session.created", + "session.ended" + ]).describe("Type of awareness event"), + userId: external_exports.string().optional().describe("User involved in event"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of event"), + payload: external_exports.unknown().describe("Event payload") +}); +var CollaborationMode2 = external_exports.enum([ + "ot", + // Operational Transformation + "crdt", + // CRDT-based + "lock", + // Pessimistic locking (turn-based) + "hybrid" + // Hybrid approach +]); +var CollaborationSessionConfigSchema2 = external_exports.object({ + mode: CollaborationMode2.describe("Collaboration mode to use"), + enableCursorSharing: external_exports.boolean().optional().default(true).describe("Enable cursor sharing"), + enablePresence: external_exports.boolean().optional().default(true).describe("Enable presence tracking"), + enableAwareness: external_exports.boolean().optional().default(true).describe("Enable awareness state"), + maxUsers: external_exports.number().int().positive().optional().describe("Maximum concurrent users"), + idleTimeout: external_exports.number().int().positive().optional().default(3e5).describe("Idle timeout in milliseconds"), + conflictResolution: external_exports.enum(["ot", "crdt", "manual"]).optional().default("ot").describe("Conflict resolution strategy"), + persistence: external_exports.boolean().optional().default(true).describe("Enable operation persistence"), + snapshot: external_exports.object({ + enabled: external_exports.boolean().describe("Enable periodic snapshots"), + interval: external_exports.number().int().positive().describe("Snapshot interval in milliseconds") + }).optional().describe("Snapshot configuration") +}); +var CollaborationSessionSchema2 = external_exports.object({ + sessionId: external_exports.string().uuid().describe("Session identifier"), + documentId: external_exports.string().describe("Document identifier"), + config: CollaborationSessionConfigSchema2.describe("Session configuration"), + users: external_exports.array(AwarenessUserStateSchema2).describe("Active users"), + cursors: external_exports.array(CollaborativeCursorSchema2).describe("Active cursors"), + version: external_exports.number().int().nonnegative().describe("Current document version"), + operations: external_exports.array(external_exports.union([OTOperationSchema2, TextCRDTOperationSchema2])).optional().describe("Recent operations"), + createdAt: external_exports.string().datetime().describe("ISO 8601 datetime when session was created"), + lastActivity: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), + status: external_exports.enum(["active", "idle", "ended"]).describe("Session status") +}); +var MetadataScopeSchema2 = external_exports.enum([ + "system", + // Defined in Code (Files). Read-only at runtime. Upgraded via deployment. + "platform", + // Defined in DB (Global). admin-configured. Overrides system. + "user" + // Defined in DB (Personal). User-configured. Overrides platform/system. +]); +var MetadataStateSchema2 = external_exports.enum([ + "draft", + // Work in progress, not active + "active", + // Live and running + "archived", + // Soft deleted + "deprecated" + // Running but flagged for removal +]); +var MetadataRecordSchema2 = external_exports.object({ + /** Primary Key (UUID) */ + id: external_exports.string(), + /** + * Machine Name + * The unique identifier used in code references (e.g. "account_list_view"). + */ + name: external_exports.string(), + /** + * Metadata Type + * e.g. "object", "view", "permission_set", "flow" + */ + type: external_exports.string(), + /** + * Namespace / Module + * Groups metadata into packages (e.g. "crm", "finance", "core"). + */ + namespace: external_exports.string().default("default"), + /** + * Package Ownership Reference + * Links this metadata record to the package that delivered it. + * When set, the record is "managed" by the package and should not be + * directly edited — customizations go through the overlay system. + * Null/undefined means the record was created independently (not from a package). + */ + packageId: external_exports.string().optional().describe("Package ID that owns/delivered this metadata"), + /** + * Managed By Indicator + * Determines who controls this metadata record's lifecycle. + * - "package": Delivered and upgraded by a plugin package (read-only base) + * - "platform": Created by platform admin via UI + * - "user": Created by end user + */ + managedBy: external_exports.enum(["package", "platform", "user"]).optional().describe("Who manages this metadata record lifecycle"), + /** + * Ownership differentiation + */ + scope: MetadataScopeSchema2.default("platform"), + /** + * The Payload + * Stores the actual configuration JSON. + * This field holds the value of `ViewSchema`, `ObjectSchema`, etc. + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()), + /** + * Extension / Merge Strategy + * If this record overrides a system record, how should it be applied? + */ + extends: external_exports.string().optional().describe("Name of the parent metadata to extend/override"), + strategy: external_exports.enum(["merge", "replace"]).default("merge"), + /** Owner (for user-scope items) */ + owner: external_exports.string().optional(), + /** State */ + state: MetadataStateSchema2.default("active"), + /** Tenant ID for multi-tenant isolation */ + tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant isolation"), + /** Version number for optimistic concurrency */ + version: external_exports.number().default(1).describe("Record version for optimistic concurrency control"), + /** Checksum for change detection */ + checksum: external_exports.string().optional().describe("Content checksum for change detection"), + /** Source origin marker */ + source: external_exports.enum(["filesystem", "database", "api", "migration"]).optional().describe("Origin of this metadata record"), + /** Classification tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Classification tags for filtering and grouping"), + /** Package Publishing */ + publishedDefinition: external_exports.unknown().optional().describe("Snapshot of the last published definition"), + publishedAt: external_exports.string().datetime().optional().describe("When this metadata was last published"), + publishedBy: external_exports.string().optional().describe("Who published this version"), + /** Audit */ + createdBy: external_exports.string().optional(), + createdAt: external_exports.string().datetime().optional().describe("Creation timestamp"), + updatedBy: external_exports.string().optional(), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp") +}); +var PackagePublishResultSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Whether the publish succeeded"), + packageId: external_exports.string().describe("The package ID that was published"), + version: external_exports.number().int().describe("New version number after publish"), + publishedAt: external_exports.string().datetime().describe("Publish timestamp"), + itemsPublished: external_exports.number().int().describe("Total metadata items published"), + validationErrors: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type that failed validation"), + name: external_exports.string().describe("Item name that failed validation"), + message: external_exports.string().describe("Validation error message") + })).optional().describe("Validation errors if publish failed") +}); +var MetadataFormatSchema22 = external_exports.enum([ + "json", + "yaml", + "yml", + "ts", + "js", + "typescript", + "javascript" + // Aliases +]); +var MetadataStatsSchema4 = external_exports.object({ + path: external_exports.string().optional(), + size: external_exports.number().optional(), + mtime: external_exports.string().datetime().optional(), + hash: external_exports.string().optional(), + etag: external_exports.string().optional(), + // Required by local cache + modifiedAt: external_exports.string().datetime().optional(), + // Alias for mtime + format: MetadataFormatSchema22.optional() + // Required for serialization +}); +var MetadataLoaderContractSchema3 = external_exports.object({ + name: external_exports.string(), + protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Loader protocol identifier"), + description: external_exports.string().optional(), + supportedFormats: external_exports.array(external_exports.string()).optional(), + supportsWatch: external_exports.boolean().optional(), + supportsWrite: external_exports.boolean().optional(), + supportsCache: external_exports.boolean().optional(), + capabilities: external_exports.object({ + read: external_exports.boolean().default(true), + write: external_exports.boolean().default(false), + watch: external_exports.boolean().default(false), + list: external_exports.boolean().default(true) + }) +}); +var MetadataLoadOptionsSchema3 = external_exports.object({ + scope: MetadataScopeSchema2.optional(), + namespace: external_exports.string().optional(), + raw: external_exports.boolean().optional().describe("Return raw file content instead of parsed JSON"), + cache: external_exports.boolean().optional(), + useCache: external_exports.boolean().optional(), + // Alias for cache + validate: external_exports.boolean().optional(), + ifNoneMatch: external_exports.string().optional(), + // For caching + recursive: external_exports.boolean().optional(), + limit: external_exports.number().optional(), + patterns: external_exports.array(external_exports.string()).optional(), + loader: external_exports.string().optional().describe("Specific loader to use (e.g. filesystem, database)") +}); +var MetadataLoadResultSchema3 = external_exports.object({ + data: external_exports.unknown(), + stats: MetadataStatsSchema4.optional(), + format: MetadataFormatSchema22.optional(), + source: external_exports.string().optional(), + // File path or URL + fromCache: external_exports.boolean().optional(), + etag: external_exports.string().optional(), + notModified: external_exports.boolean().optional(), + loadTime: external_exports.number().optional() +}); +var MetadataSaveOptionsSchema3 = external_exports.object({ + format: MetadataFormatSchema22.optional(), + create: external_exports.boolean().default(true), + overwrite: external_exports.boolean().default(true), + path: external_exports.string().optional(), + prettify: external_exports.boolean().optional(), + indent: external_exports.number().optional(), + sortKeys: external_exports.boolean().optional(), + backup: external_exports.boolean().optional(), + atomic: external_exports.boolean().optional(), + loader: external_exports.string().optional().describe("Specific loader to use (e.g. filesystem, database)") +}); +var MetadataSaveResultSchema3 = external_exports.object({ + success: external_exports.boolean(), + path: external_exports.string().optional(), + stats: MetadataStatsSchema4.optional(), + etag: external_exports.string().optional(), + size: external_exports.number().optional(), + saveTime: external_exports.number().optional(), + backupPath: external_exports.string().optional() +}); +var MetadataWatchEventSchema3 = external_exports.object({ + type: external_exports.enum(["add", "change", "unlink", "added", "changed", "deleted"]), + path: external_exports.string(), + name: external_exports.string().optional(), + stats: MetadataStatsSchema4.optional(), + metadataType: external_exports.string().optional(), + data: external_exports.unknown().optional(), + timestamp: external_exports.string().datetime().optional() +}); +var MetadataCollectionInfoSchema3 = external_exports.object({ + type: external_exports.string(), + count: external_exports.number(), + namespaces: external_exports.array(external_exports.string()) +}); +var MetadataExportOptionsSchema3 = external_exports.object({ + types: external_exports.array(external_exports.string()).optional(), + namespaces: external_exports.array(external_exports.string()).optional(), + output: external_exports.string().describe("Output directory or file"), + format: MetadataFormatSchema22.default("json") +}); +var MetadataImportOptionsSchema3 = external_exports.object({ + source: external_exports.string().describe("Input directory or file"), + strategy: external_exports.enum(["merge", "replace", "skip"]).default("merge"), + validate: external_exports.boolean().default(true) +}); +var MetadataFallbackStrategySchema4 = external_exports.enum([ + "filesystem", + // Fall back to filesystem-based loading + "memory", + // Fall back to in-memory storage + "none" + // No fallback — fail immediately +]); +var MetadataSourceSchema2 = external_exports.enum([ + "filesystem", + // Loaded from local files + "database", + // Loaded from database via datasource + "api", + // Loaded from remote API + "migration" + // Created during a migration process +]); +var MetadataManagerConfigSchema4 = external_exports.object({ + /** + * Datasource Name Reference + * References a DatasourceSchema.name (e.g. 'default'). + * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. + * When provided, metadata is persisted to a database table. + */ + datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), + /** + * Metadata Table Name + * The database table used for metadata storage when datasource is configured. + */ + tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), + /** + * Fallback Strategy + * Determines behavior when the primary datasource is unavailable. + */ + fallback: MetadataFallbackStrategySchema4.default("none").describe("Fallback strategy when datasource is unavailable"), + /** + * Root directory for metadata (for filesystem loaders) + */ + rootDir: external_exports.string().optional().describe("Root directory for filesystem-based metadata"), + /** + * Enabled serialization formats + */ + formats: external_exports.array(MetadataFormatSchema22).optional().describe("Enabled metadata formats"), + /** + * Enable file watching + */ + watch: external_exports.boolean().optional().describe("Enable file watching for filesystem loaders"), + /** + * Cache configuration + */ + cache: external_exports.boolean().optional().describe("Enable metadata caching"), + /** + * Watch options + */ + watchOptions: external_exports.object({ + ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), + persistent: external_exports.boolean().default(true).describe("Keep process running") + }).optional().describe("File watcher options") +}); +var MetadataHistoryRecordSchema2 = external_exports.object({ + /** Primary Key (UUID) */ + id: external_exports.string(), + /** Reference to the parent metadata record ID */ + metadataId: external_exports.string().describe("Foreign key to sys_metadata.id"), + /** + * Machine Name + * Denormalized from parent for easier querying. + */ + name: external_exports.string(), + /** + * Metadata Type + * Denormalized from parent for easier querying. + */ + type: external_exports.string(), + /** + * Version Number + * Snapshot of the metadata version at this point in history. + */ + version: external_exports.number().describe("Version number at this snapshot"), + /** + * Operation Type + * Indicates what kind of change triggered this history record. + */ + operationType: external_exports.enum(["create", "update", "publish", "revert", "delete"]).describe("Type of operation that created this history entry"), + /** + * Historical Metadata Snapshot + * Full JSON payload of the metadata definition at this version. + * May be stored as a raw JSON string in the history table, or as a parsed object + * in higher-level APIs. When `includeMetadata` is false, this field is null. + */ + metadata: external_exports.union([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown())]).nullable().optional().describe("Snapshot of metadata definition at this version (raw JSON string or parsed object)"), + /** + * Content Checksum + * SHA-256 checksum of the normalized metadata JSON for change detection. + */ + checksum: external_exports.string().describe("SHA-256 checksum of metadata content"), + /** + * Previous Checksum + * Checksum of the previous version for diff optimization. + */ + previousChecksum: external_exports.string().optional().describe("Checksum of the previous version"), + /** + * Change Note + * Human-readable description of what changed in this version. + */ + changeNote: external_exports.string().optional().describe("Description of changes made in this version"), + /** Tenant ID for multi-tenant isolation */ + tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant isolation"), + /** Audit: who made this change */ + recordedBy: external_exports.string().optional().describe("User who made this change"), + /** Audit: when was this version recorded */ + recordedAt: external_exports.string().datetime().describe("Timestamp when this version was recorded") +}); +var MetadataHistoryQueryOptionsSchema2 = external_exports.object({ + /** Limit number of history records returned */ + limit: external_exports.number().int().positive().optional().describe("Maximum number of history records to return"), + /** Offset for pagination */ + offset: external_exports.number().int().nonnegative().optional().describe("Number of records to skip"), + /** Only return versions after this timestamp */ + since: external_exports.string().datetime().optional().describe("Only return history after this timestamp"), + /** Only return versions before this timestamp */ + until: external_exports.string().datetime().optional().describe("Only return history before this timestamp"), + /** Filter by operation type */ + operationType: external_exports.enum(["create", "update", "publish", "revert", "delete"]).optional().describe("Filter by operation type"), + /** Include full metadata payload in results (default: true) */ + includeMetadata: external_exports.boolean().optional().default(true).describe("Include full metadata payload") +}); +var MetadataHistoryQueryResultSchema2 = external_exports.object({ + /** Array of history records */ + records: external_exports.array(MetadataHistoryRecordSchema2), + /** Total number of history records (for pagination) */ + total: external_exports.number().int().nonnegative(), + /** Whether there are more records available */ + hasMore: external_exports.boolean() +}); +var MetadataDiffResultSchema2 = external_exports.object({ + /** Metadata type */ + type: external_exports.string(), + /** Metadata name */ + name: external_exports.string(), + /** Version 1 (older) */ + version1: external_exports.number(), + /** Version 2 (newer) */ + version2: external_exports.number(), + /** Checksum of version 1 */ + checksum1: external_exports.string(), + /** Checksum of version 2 */ + checksum2: external_exports.string(), + /** Whether the versions are identical */ + identical: external_exports.boolean(), + /** JSON patch operations to transform v1 into v2 */ + patch: external_exports.array(external_exports.unknown()).optional().describe("JSON patch operations"), + /** Human-readable diff summary */ + summary: external_exports.string().optional().describe("Human-readable summary of changes") +}); +var MetadataHistoryRetentionPolicySchema2 = external_exports.object({ + /** Maximum number of versions to keep per metadata item */ + maxVersions: external_exports.number().int().positive().optional().describe("Maximum number of versions to retain"), + /** Maximum age of history records in days */ + maxAgeDays: external_exports.number().int().positive().optional().describe("Maximum age of history records in days"), + /** Whether to enable automatic cleanup */ + autoCleanup: external_exports.boolean().default(false).describe("Enable automatic cleanup of old history"), + /** Cleanup interval in hours */ + cleanupIntervalHours: external_exports.number().int().positive().default(24).describe("How often to run cleanup (in hours)") +}); +var CoreServiceName3 = external_exports.enum([ + // Core Data & Metadata + "metadata", + // Object/Field Definitions + "data", + // CRUD & Query Engine + "auth", + // Authentication & Identity + // Infrastructure + "file-storage", + // Storage Driver (Local/S3) + "search", + // Search Engine (Elastic/Meili) + "cache", + // Cache Driver (Redis/Memory) + "queue", + // Job Queue (BullMQ/Redis) + // Advanced Capabilities + "automation", + // Flow & Script Engine + "graphql", + // GraphQL API Engine + "analytics", + // BI & Semantic Layer + "realtime", + // WebSocket & PubSub + "job", + // Background Job Manager + "notification", + // Email/Push/SMS + "ai", + // AI Engine (NLQ, Chat, Suggest, Insights) + "i18n", + // Internationalization Service + "ui", + // UI Metadata Service (View CRUD) + "workflow" + // Workflow State Machine Engine +]); +var ServiceCriticalitySchema3 = external_exports.enum([ + "required", + // System fails to start if missing (Exit Code 1) + "core", + // System warns if missing, functionality degraded (Warn) + "optional" + // System ignores if missing, feature disabled (Info) +]); +var ServiceRequirementDef2 = { + // Required: The kernel cannot function without these + data: "required", + // Core: Highly recommended, defaults to in-memory / no-op if missing + metadata: "core", + auth: "core", + // Core: Highly recommended, defaults to in-memory / no-op if missing + cache: "core", + queue: "core", + job: "core", + i18n: "core", + // Optional: Add-on capabilities + "file-storage": "optional", + search: "optional", + automation: "optional", + graphql: "optional", + analytics: "optional", + realtime: "optional", + notification: "optional", + ai: "optional", + ui: "optional", + workflow: "optional" +}; +var ServiceStatusSchema2 = external_exports.object({ + name: CoreServiceName3, + enabled: external_exports.boolean(), + status: external_exports.enum(["running", "stopped", "degraded", "initializing"]), + version: external_exports.string().optional(), + provider: external_exports.string().optional().describe('Implementation provider (e.g. "s3" for storage)'), + features: external_exports.array(external_exports.string()).optional().describe("List of supported sub-features") +}); +var KernelServiceMapSchema2 = external_exports.record( + CoreServiceName3, + external_exports.unknown().describe("Service Instance implementing the protocol interface") +); +var ServiceConfigSchema2 = external_exports.object({ + id: external_exports.string(), + name: CoreServiceName3, + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var TenantIsolationLevel3 = external_exports.enum([ + "shared_schema", + // Shared DB, shared schema, row-level isolation (most economical) + "isolated_schema", + // Shared DB, separate schema per tenant (balanced) + "isolated_db" + // Separate database per tenant (maximum isolation) +]); +var DatabaseProviderSchema3 = external_exports.enum([ + "turso", + // Turso/libSQL (DB-per-Tenant, edge-native) + "postgres", + // PostgreSQL (traditional, self-hosted or managed) + "memory" + // In-memory (testing/development only) +]).describe("Database provider for tenant data"); +var TenantConnectionConfigSchema3 = external_exports.object({ + /** Database connection URL */ + url: external_exports.string().min(1).describe("Database connection URL"), + /** Authentication token (JWT for Turso, password for Postgres) */ + authToken: external_exports.string().optional().describe("Database auth token (encrypted at rest)"), + /** Turso database group name */ + group: external_exports.string().optional().describe("Turso database group name") +}).describe("Tenant database connection configuration"); +var TenantQuotaSchema3 = external_exports.object({ + /** + * Maximum number of users allowed for this tenant + */ + maxUsers: external_exports.number().int().positive().optional().describe("Maximum number of users"), + /** + * Maximum storage space in bytes + */ + maxStorage: external_exports.number().int().positive().optional().describe("Maximum storage in bytes"), + /** + * API rate limit (requests per minute) + */ + apiRateLimit: external_exports.number().int().positive().optional().describe("API requests per minute"), + /** + * Maximum number of custom objects the tenant can create + */ + maxObjects: external_exports.number().int().positive().optional().describe("Maximum number of custom objects"), + /** + * Maximum records per object/table + */ + maxRecordsPerObject: external_exports.number().int().positive().optional().describe("Maximum records per object"), + /** + * Maximum deployments allowed per day + */ + maxDeploymentsPerDay: external_exports.number().int().positive().optional().describe("Maximum deployments per day"), + /** + * Maximum storage in bytes + */ + maxStorageBytes: external_exports.number().int().positive().optional().describe("Maximum storage in bytes") +}); +var TenantUsageSchema2 = external_exports.object({ + /** Current number of custom objects */ + currentObjectCount: external_exports.number().int().min(0).default(0).describe("Current number of custom objects"), + /** Current total record count across all objects */ + currentRecordCount: external_exports.number().int().min(0).default(0).describe("Total records across all objects"), + /** Current storage usage in bytes */ + currentStorageBytes: external_exports.number().int().min(0).default(0).describe("Current storage usage in bytes"), + /** Deployments executed today */ + deploymentsToday: external_exports.number().int().min(0).default(0).describe("Deployments executed today"), + /** Current number of active users */ + currentUsers: external_exports.number().int().min(0).default(0).describe("Current number of active users"), + /** API requests in the current minute */ + apiRequestsThisMinute: external_exports.number().int().min(0).default(0).describe("API requests in the current minute"), + /** Last updated timestamp (ISO 8601) */ + lastUpdatedAt: external_exports.string().datetime().optional().describe("Last usage update time") +}).describe("Current tenant resource usage"); +var QuotaEnforcementResultSchema2 = external_exports.object({ + /** Whether the operation is allowed */ + allowed: external_exports.boolean().describe("Whether the operation is within quota"), + /** Quota that would be exceeded (if not allowed) */ + exceededQuota: external_exports.string().optional().describe("Name of the exceeded quota"), + /** Current usage value */ + currentUsage: external_exports.number().optional().describe("Current usage value"), + /** Quota limit value */ + limit: external_exports.number().optional().describe("Quota limit"), + /** Human-readable message */ + message: external_exports.string().optional().describe("Human-readable quota message") +}).describe("Quota enforcement check result"); +var TenantSchema2 = external_exports.object({ + /** + * Unique tenant identifier + */ + id: external_exports.string().describe("Unique tenant identifier"), + /** + * Tenant display name + */ + name: external_exports.string().describe("Tenant display name"), + /** + * Data isolation level + */ + isolationLevel: TenantIsolationLevel3, + /** + * Database provider for this tenant + */ + databaseProvider: DatabaseProviderSchema3.optional().describe("Database provider"), + /** + * Database connection configuration (encrypted at rest) + */ + connectionConfig: TenantConnectionConfigSchema3.optional().describe("Database connection config"), + /** + * Current provisioning status + */ + provisioningStatus: external_exports.enum([ + "provisioning", + "active", + "suspended", + "failed", + "destroying" + ]).optional().describe("Current provisioning lifecycle status"), + /** + * Tenant subscription plan + */ + plan: external_exports.enum(["free", "pro", "enterprise"]).optional().describe("Subscription plan"), + /** + * Custom configuration values + */ + customizations: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom configuration values"), + /** + * Resource quotas + */ + quotas: TenantQuotaSchema3.optional() +}); +var RowLevelIsolationStrategySchema3 = external_exports.object({ + strategy: external_exports.literal("shared_schema").describe("Row-level isolation strategy"), + /** + * Database configuration for row-level isolation + */ + database: external_exports.object({ + /** + * Whether to enable Row-Level Security (RLS) + */ + enableRLS: external_exports.boolean().default(true).describe("Enable PostgreSQL Row-Level Security"), + /** + * Tenant context setting method + */ + contextMethod: external_exports.enum([ + "session_variable", + // SET app.current_tenant = 'tenant_123' + "search_path", + // SET search_path = tenant_123, public + "application_name" + // SET application_name = 'tenant_123' + ]).default("session_variable").describe("How to set tenant context"), + /** + * Session variable name for tenant context + */ + contextVariable: external_exports.string().default("app.current_tenant").describe("Session variable name"), + /** + * Whether to validate tenant_id at application level + */ + applicationValidation: external_exports.boolean().default(true).describe("Application-level tenant validation") + }).optional().describe("Database configuration"), + /** + * Performance optimization settings + */ + performance: external_exports.object({ + /** + * Whether to use partial indexes for tenant_id + */ + usePartialIndexes: external_exports.boolean().default(true).describe("Use partial indexes per tenant"), + /** + * Whether to use table partitioning + */ + usePartitioning: external_exports.boolean().default(false).describe("Use table partitioning by tenant_id"), + /** + * Connection pool size per tenant + */ + poolSizePerTenant: external_exports.number().int().positive().optional().describe("Connection pool size per tenant") + }).optional().describe("Performance settings") +}); +var SchemaLevelIsolationStrategySchema3 = external_exports.object({ + strategy: external_exports.literal("isolated_schema").describe("Schema-level isolation strategy"), + /** + * Schema configuration + */ + schema: external_exports.object({ + /** + * Schema naming pattern + * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) + * The tenant_id will be sanitized before substitution to prevent SQL injection + */ + namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Schema naming pattern"), + /** + * Whether to include public schema in search_path + */ + includePublicSchema: external_exports.boolean().default(true).describe("Include public schema"), + /** + * Default schema for shared resources + */ + sharedSchema: external_exports.string().default("public").describe("Schema for shared resources"), + /** + * Whether to automatically create schema on tenant creation + */ + autoCreateSchema: external_exports.boolean().default(true).describe("Auto-create schema") + }).optional().describe("Schema configuration"), + /** + * Migration configuration + */ + migrations: external_exports.object({ + /** + * Migration strategy + */ + strategy: external_exports.enum([ + "parallel", + // Run migrations on all schemas in parallel + "sequential", + // Run migrations one schema at a time + "on_demand" + // Run migrations when tenant accesses system + ]).default("parallel").describe("Migration strategy"), + /** + * Maximum concurrent migrations + */ + maxConcurrent: external_exports.number().int().positive().default(10).describe("Max concurrent migrations"), + /** + * Whether to rollback on first failure + */ + rollbackOnError: external_exports.boolean().default(true).describe("Rollback on error") + }).optional().describe("Migration configuration"), + /** + * Performance optimization settings + */ + performance: external_exports.object({ + /** + * Whether to use connection pooling per schema + */ + poolPerSchema: external_exports.boolean().default(false).describe("Separate pool per schema"), + /** + * Schema cache TTL in seconds + */ + schemaCacheTTL: external_exports.number().int().positive().default(3600).describe("Schema cache TTL") + }).optional().describe("Performance settings") +}); +var DatabaseLevelIsolationStrategySchema3 = external_exports.object({ + strategy: external_exports.literal("isolated_db").describe("Database-level isolation strategy"), + /** + * Database configuration + */ + database: external_exports.object({ + /** + * Database naming pattern + * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) + * The tenant_id will be sanitized before substitution to prevent SQL injection + */ + namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Database naming pattern"), + /** + * Database server/cluster assignment strategy + */ + serverStrategy: external_exports.enum([ + "shared", + // All tenant databases on same server + "sharded", + // Tenant databases distributed across servers + "dedicated" + // Each tenant gets dedicated server (enterprise) + ]).default("shared").describe("Server assignment strategy"), + /** + * Whether to use separate credentials per tenant + */ + separateCredentials: external_exports.boolean().default(true).describe("Separate credentials per tenant"), + /** + * Whether to automatically create database on tenant creation + */ + autoCreateDatabase: external_exports.boolean().default(true).describe("Auto-create database") + }).optional().describe("Database configuration"), + /** + * Connection pooling configuration + */ + connectionPool: external_exports.object({ + /** + * Pool size per tenant database + */ + poolSize: external_exports.number().int().positive().default(10).describe("Connection pool size"), + /** + * Maximum number of tenant pools to keep active + */ + maxActivePools: external_exports.number().int().positive().default(100).describe("Max active pools"), + /** + * Idle pool timeout in seconds + */ + idleTimeout: external_exports.number().int().positive().default(300).describe("Idle pool timeout"), + /** + * Whether to use connection pooler (PgBouncer, etc.) + */ + usePooler: external_exports.boolean().default(true).describe("Use connection pooler") + }).optional().describe("Connection pool configuration"), + /** + * Backup and restore configuration + */ + backup: external_exports.object({ + /** + * Backup strategy per tenant + */ + strategy: external_exports.enum([ + "individual", + // Separate backup per tenant + "consolidated", + // Combined backup with all tenants + "on_demand" + // Backup only when requested + ]).default("individual").describe("Backup strategy"), + /** + * Backup frequency in hours + */ + frequencyHours: external_exports.number().int().positive().default(24).describe("Backup frequency"), + /** + * Retention period in days + */ + retentionDays: external_exports.number().int().positive().default(30).describe("Backup retention days") + }).optional().describe("Backup configuration"), + /** + * Encryption configuration + */ + encryption: external_exports.object({ + /** + * Whether to use per-tenant encryption keys + */ + perTenantKeys: external_exports.boolean().default(false).describe("Per-tenant encryption keys"), + /** + * Encryption algorithm + */ + algorithm: external_exports.string().default("AES-256-GCM").describe("Encryption algorithm"), + /** + * Key management service + */ + keyManagement: external_exports.enum(["aws_kms", "azure_key_vault", "gcp_kms", "hashicorp_vault", "custom"]).optional().describe("Key management service") + }).optional().describe("Encryption configuration") +}); +var TenantIsolationConfigSchema2 = external_exports.discriminatedUnion("strategy", [ + RowLevelIsolationStrategySchema3, + SchemaLevelIsolationStrategySchema3, + DatabaseLevelIsolationStrategySchema3 +]); +var TenantSecurityPolicySchema2 = external_exports.object({ + /** + * Encryption requirements + */ + encryption: external_exports.object({ + /** + * Require encryption at rest + */ + atRest: external_exports.boolean().default(true).describe("Require encryption at rest"), + /** + * Require encryption in transit + */ + inTransit: external_exports.boolean().default(true).describe("Require encryption in transit"), + /** + * Require field-level encryption for sensitive data + */ + fieldLevel: external_exports.boolean().default(false).describe("Require field-level encryption") + }).optional().describe("Encryption requirements"), + /** + * Access control requirements + */ + accessControl: external_exports.object({ + /** + * Require multi-factor authentication + */ + requireMFA: external_exports.boolean().default(false).describe("Require MFA"), + /** + * Require SSO/SAML authentication + */ + requireSSO: external_exports.boolean().default(false).describe("Require SSO"), + /** + * IP whitelist + */ + ipWhitelist: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses"), + /** + * Session timeout in seconds + */ + sessionTimeout: external_exports.number().int().positive().default(3600).describe("Session timeout") + }).optional().describe("Access control requirements"), + /** + * Audit and compliance requirements + */ + compliance: external_exports.object({ + /** + * Compliance standards to enforce + */ + standards: external_exports.array(external_exports.enum([ + "sox", + "hipaa", + "gdpr", + "pci_dss", + "iso_27001", + "fedramp" + ])).optional().describe("Compliance standards"), + /** + * Require audit logging for all operations + */ + requireAuditLog: external_exports.boolean().default(true).describe("Require audit logging"), + /** + * Audit log retention period in days + */ + auditRetentionDays: external_exports.number().int().positive().default(365).describe("Audit retention days"), + /** + * Data residency requirements + */ + dataResidency: external_exports.object({ + /** + * Required geographic region + */ + region: external_exports.string().optional().describe("Required region (e.g., US, EU, APAC)"), + /** + * Prohibited regions + */ + excludeRegions: external_exports.array(external_exports.string()).optional().describe("Prohibited regions") + }).optional().describe("Data residency requirements") + }).optional().describe("Compliance requirements") +}); +var LicenseMetricType2 = external_exports.enum([ + "boolean", + // Feature Flag (Enabled/Disabled) + "counter", + // Usage Count (e.g. API Calls, Records Created) - Accumulates + "gauge" + // Current Level (e.g. Storage Used, Users Active) - Point in time +]).describe("License metric type"); +var FeatureSchema2 = external_exports.object({ + code: external_exports.string().regex(/^[a-z_][a-z0-9_.]*$/).describe("Feature code (e.g. core.api_access)"), + label: external_exports.string(), + description: external_exports.string().optional(), + type: LicenseMetricType2.default("boolean"), + /** For counters/gauges */ + unit: external_exports.enum(["count", "bytes", "seconds", "percent"]).optional(), + /** Dependencies (e.g. 'audit_log' requires 'enterprise_tier') */ + requires: external_exports.array(external_exports.string()).optional() +}); +var PlanSchema2 = external_exports.object({ + code: external_exports.string().describe("Plan code (e.g. pro_v1)"), + label: external_exports.string(), + active: external_exports.boolean().default(true), + /** Feature Entitlements */ + features: external_exports.array(external_exports.string()).describe("List of enabled boolean features"), + /** Limit Quotas */ + limits: external_exports.record(external_exports.string(), external_exports.number()).describe("Map of metric codes to limit values (e.g. { storage_gb: 10 })"), + /** Pricing (Optional Metadata) */ + currency: external_exports.string().default("USD").optional(), + priceMonthly: external_exports.number().optional(), + priceYearly: external_exports.number().optional() +}); +var LicenseSchema2 = external_exports.object({ + /** Identity */ + spaceId: external_exports.string().describe("Target Space ID"), + planCode: external_exports.string(), + /** Validity */ + issuedAt: external_exports.string().datetime(), + expiresAt: external_exports.string().datetime().optional(), + // Null = Perpetual + /** Status */ + status: external_exports.enum(["active", "expired", "suspended", "trial"]), + /** Overrides (Specific to this space, exceeding the plan) */ + customFeatures: external_exports.array(external_exports.string()).optional(), + customLimits: external_exports.record(external_exports.string(), external_exports.number()).optional(), + /** Authorized Add-ons */ + plugins: external_exports.array(external_exports.string()).optional().describe("List of enabled plugin package IDs"), + /** Signature */ + signature: external_exports.string().optional().describe("Cryptographic signature of the license") +}); +var RegistrySyncPolicySchema2 = external_exports.enum([ + "manual", + // Manual synchronization only + "auto", + // Automatic synchronization + "proxy" + // Proxy requests to upstream without caching +]).describe("Registry synchronization strategy"); +var RegistryUpstreamSchema2 = external_exports.object({ + /** + * Upstream registry URL + */ + url: external_exports.string().url().describe("Upstream registry endpoint"), + /** + * Synchronization policy + */ + syncPolicy: RegistrySyncPolicySchema2.default("auto"), + /** + * Sync interval in seconds (for auto sync) + */ + syncInterval: external_exports.number().int().min(60).optional().describe("Auto-sync interval in seconds"), + /** + * Authentication credentials + */ + auth: external_exports.object({ + type: external_exports.enum(["none", "basic", "bearer", "api-key", "oauth2"]).default("none"), + username: external_exports.string().optional(), + password: external_exports.string().optional(), + token: external_exports.string().optional(), + apiKey: external_exports.string().optional() + }).optional(), + /** + * TLS/SSL configuration + */ + tls: external_exports.object({ + enabled: external_exports.boolean().default(true), + verifyCertificate: external_exports.boolean().default(true), + certificate: external_exports.string().optional(), + privateKey: external_exports.string().optional() + }).optional(), + /** + * Timeout settings + */ + timeout: external_exports.number().int().min(1e3).default(3e4).describe("Request timeout in milliseconds"), + /** + * Retry configuration + */ + retry: external_exports.object({ + maxAttempts: external_exports.number().int().min(0).default(3), + backoff: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential") + }).optional() +}); +var RegistryConfigSchema2 = external_exports.object({ + /** + * Registry type + */ + type: external_exports.enum([ + "public", + // Public marketplace (e.g., plugins.objectstack.com) + "private", + // Private enterprise registry + "hybrid" + // Hybrid with upstream federation + ]).describe("Registry deployment type"), + /** + * Upstream registries (for hybrid/private registries) + */ + upstream: external_exports.array(RegistryUpstreamSchema2).optional().describe("Upstream registries to sync from or proxy to"), + /** + * Scopes managed by this registry + */ + scope: external_exports.array(external_exports.string()).optional().describe("npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)"), + /** + * Default scope for new plugins + */ + defaultScope: external_exports.string().optional().describe("Default scope prefix for new plugins"), + /** + * Registry storage configuration + */ + storage: external_exports.object({ + /** + * Storage backend type + */ + backend: external_exports.enum(["local", "s3", "gcs", "azure-blob", "oss"]).default("local"), + /** + * Storage path or bucket name + */ + path: external_exports.string().optional(), + /** + * Credentials + */ + credentials: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional(), + /** + * Registry visibility + */ + visibility: external_exports.enum(["public", "private", "internal"]).default("private").describe("Who can access this registry"), + /** + * Access control + */ + accessControl: external_exports.object({ + /** + * Require authentication for read + */ + requireAuthForRead: external_exports.boolean().default(false), + /** + * Require authentication for write + */ + requireAuthForWrite: external_exports.boolean().default(true), + /** + * Allowed users/teams + */ + allowedPrincipals: external_exports.array(external_exports.string()).optional() + }).optional(), + /** + * Caching configuration + */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(true), + ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), + maxSize: external_exports.number().int().optional().describe("Maximum cache size in bytes") + }).optional(), + /** + * Mirroring configuration (for high availability) + */ + mirrors: external_exports.array(external_exports.object({ + url: external_exports.string().url(), + priority: external_exports.number().int().min(1).default(1) + })).optional().describe("Mirror registries for redundancy") +}); +var TenantProvisioningStatusEnum2 = external_exports.enum([ + "provisioning", + // Database creation in progress + "active", + // Fully provisioned and operational + "suspended", + // Temporarily disabled (billing, policy) + "failed", + // Provisioning failed (requires retry or manual intervention) + "destroying" + // Deletion in progress +]).describe("Tenant provisioning lifecycle status"); +var TenantPlanSchema2 = external_exports.enum([ + "free", + // Free tier with limited quotas + "pro", + // Professional tier with higher quotas + "enterprise" + // Enterprise tier with custom quotas and SLAs +]).describe("Tenant subscription plan"); +var TenantRegionSchema2 = external_exports.enum([ + "us-east", + // US East (Virginia) + "us-west", + // US West (Oregon) + "eu-west", + // EU West (Ireland) + "eu-central", + // EU Central (Frankfurt) + "ap-southeast", + // Asia Pacific (Singapore) + "ap-northeast" + // Asia Pacific (Tokyo) +]).describe("Available deployment region"); +var ProvisioningStepSchema2 = external_exports.object({ + /** Step identifier */ + name: external_exports.string().min(1).describe("Step name (e.g., create_database, sync_schema)"), + /** Step execution status */ + status: external_exports.enum(["pending", "running", "completed", "failed", "skipped"]).describe("Step status"), + /** When the step started (ISO 8601) */ + startedAt: external_exports.string().datetime().optional().describe("Step start time"), + /** When the step completed (ISO 8601) */ + completedAt: external_exports.string().datetime().optional().describe("Step completion time"), + /** Duration in milliseconds */ + durationMs: external_exports.number().int().min(0).optional().describe("Step duration in ms"), + /** Error message if the step failed */ + error: external_exports.string().optional().describe("Error message on failure") +}).describe("Individual provisioning step status"); +var TenantProvisioningRequestSchema2 = external_exports.object({ + /** Organization ID that owns this tenant */ + orgId: external_exports.string().min(1).describe("Organization ID"), + /** Requested subscription plan */ + plan: TenantPlanSchema2.default("free"), + /** Preferred deployment region */ + region: TenantRegionSchema2.default("us-east"), + /** Optional tenant display name */ + displayName: external_exports.string().optional().describe("Tenant display name"), + /** Optional initial admin user email */ + adminEmail: external_exports.string().email().optional().describe("Initial admin user email"), + /** Optional metadata to attach to the tenant */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata") +}).describe("Tenant provisioning request"); +var TenantProvisioningResultSchema2 = external_exports.object({ + /** Unique tenant identifier */ + tenantId: external_exports.string().min(1).describe("Provisioned tenant ID"), + /** Database connection URL (libsql:// or https://) */ + connectionUrl: external_exports.string().min(1).describe("Database connection URL"), + /** Current provisioning status */ + status: TenantProvisioningStatusEnum2, + /** Deployment region */ + region: TenantRegionSchema2, + /** Active subscription plan */ + plan: TenantPlanSchema2, + /** Provisioning pipeline steps with status */ + steps: external_exports.array(ProvisioningStepSchema2).default([]).describe("Pipeline step statuses"), + /** Total provisioning duration in milliseconds */ + totalDurationMs: external_exports.number().int().min(0).optional().describe("Total provisioning duration"), + /** Provisioned timestamp (ISO 8601) */ + provisionedAt: external_exports.string().datetime().optional().describe("Provisioning completion time"), + /** Error message if provisioning failed */ + error: external_exports.string().optional().describe("Error message on failure") +}).describe("Tenant provisioning result"); +var DeployStatusEnum2 = external_exports.enum([ + "validating", + // Zod schema validation in progress + "diffing", + // Comparing desired state vs current state + "migrating", + // Executing DDL statements + "registering", + // Updating metadata registry + "ready", + // Deployment complete and live + "failed", + // Deployment failed at some stage + "rolling_back" + // Rollback in progress +]).describe("Deployment lifecycle status"); +var SchemaChangeSchema2 = external_exports.object({ + /** Type of entity being changed */ + entityType: external_exports.enum(["object", "field", "index", "view", "flow", "permission"]).describe("Entity type"), + /** Name of the entity */ + entityName: external_exports.string().min(1).describe("Entity name"), + /** Parent entity name (e.g., object name for a field change) */ + parentEntity: external_exports.string().optional().describe("Parent entity name"), + /** Type of change */ + changeType: external_exports.enum(["added", "modified", "removed"]).describe("Change type"), + /** Previous value (for modified/removed) */ + oldValue: external_exports.unknown().optional().describe("Previous value"), + /** New value (for added/modified) */ + newValue: external_exports.unknown().optional().describe("New value") +}).describe("Individual schema change"); +var DeployDiffSchema2 = external_exports.object({ + /** List of all schema changes */ + changes: external_exports.array(SchemaChangeSchema2).default([]).describe("List of schema changes"), + /** Summary counts */ + summary: external_exports.object({ + added: external_exports.number().int().min(0).default(0).describe("Number of added entities"), + modified: external_exports.number().int().min(0).default(0).describe("Number of modified entities"), + removed: external_exports.number().int().min(0).default(0).describe("Number of removed entities") + }).describe("Change summary counts"), + /** Whether the diff contains breaking changes (e.g., column removal) */ + hasBreakingChanges: external_exports.boolean().default(false).describe("Whether diff contains breaking changes") +}).describe("Schema diff between current and desired state"); +var MigrationStatementSchema2 = external_exports.object({ + /** SQL DDL statement to execute */ + sql: external_exports.string().min(1).describe("SQL DDL statement"), + /** Whether this statement is reversible */ + reversible: external_exports.boolean().default(true).describe("Whether the statement can be reversed"), + /** Reverse SQL statement (for rollback) */ + rollbackSql: external_exports.string().optional().describe("Reverse SQL for rollback"), + /** Execution order (lower = earlier) */ + order: external_exports.number().int().min(0).describe("Execution order") +}).describe("Single DDL migration statement"); +var MigrationPlanSchema2 = external_exports.object({ + /** Ordered list of migration statements */ + statements: external_exports.array(MigrationStatementSchema2).default([]).describe("Ordered DDL statements"), + /** SQL dialect the statements are written for */ + dialect: external_exports.string().min(1).describe("Target SQL dialect"), + /** Whether the entire plan is reversible */ + reversible: external_exports.boolean().default(true).describe("Whether the plan can be fully rolled back"), + /** Estimated execution time in milliseconds */ + estimatedDurationMs: external_exports.number().int().min(0).optional().describe("Estimated execution time") +}).describe("Ordered migration plan"); +var DeployValidationIssueSchema2 = external_exports.object({ + /** Severity of the issue */ + severity: external_exports.enum(["error", "warning", "info"]).describe("Issue severity"), + /** Entity path where the issue was found */ + path: external_exports.string().describe("Entity path (e.g., objects.project_task.fields.name)"), + /** Human-readable issue description */ + message: external_exports.string().describe("Issue description"), + /** Zod error code if applicable */ + code: external_exports.string().optional().describe("Validation error code") +}).describe("Validation issue"); +var DeployValidationResultSchema2 = external_exports.object({ + /** Whether the bundle passed validation */ + valid: external_exports.boolean().describe("Whether the bundle is valid"), + /** List of validation issues */ + issues: external_exports.array(DeployValidationIssueSchema2).default([]).describe("Validation issues"), + /** Number of errors */ + errorCount: external_exports.number().int().min(0).default(0).describe("Number of errors"), + /** Number of warnings */ + warningCount: external_exports.number().int().min(0).default(0).describe("Number of warnings") +}).describe("Bundle validation result"); +var DeployManifestSchema2 = external_exports.object({ + /** Deployment version (semver) */ + version: external_exports.string().min(1).describe("Deployment version"), + /** SHA256 checksum of the bundle contents */ + checksum: external_exports.string().optional().describe("SHA256 checksum"), + /** Object definitions included in this deployment */ + objects: external_exports.array(external_exports.string()).default([]).describe("Object names included"), + /** View definitions included */ + views: external_exports.array(external_exports.string()).default([]).describe("View names included"), + /** Flow definitions included */ + flows: external_exports.array(external_exports.string()).default([]).describe("Flow names included"), + /** Permission definitions included */ + permissions: external_exports.array(external_exports.string()).default([]).describe("Permission names included"), + /** Timestamp of bundle creation (ISO 8601) */ + createdAt: external_exports.string().datetime().optional().describe("Bundle creation time") +}).describe("Deployment manifest"); +var DeployBundleSchema2 = external_exports.object({ + /** Bundle manifest with version and contents list */ + manifest: DeployManifestSchema2, + /** Object definitions (JSON-serialized ObjectStack objects) */ + objects: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Object definitions"), + /** View definitions */ + views: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("View definitions"), + /** Flow definitions */ + flows: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Flow definitions"), + /** Permission definitions */ + permissions: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Permission definitions"), + /** Seed data records to populate after schema migration */ + seedData: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Seed data records") +}).describe("Deploy bundle containing all metadata for deployment"); +var AppManifestSchema2 = external_exports.object({ + /** Unique app identifier (snake_case) */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("App identifier (snake_case)"), + /** Display label for the app */ + label: external_exports.string().min(1).describe("App display label"), + /** App version (semver) */ + version: external_exports.string().min(1).describe("App version (semver)"), + /** App description */ + description: external_exports.string().optional().describe("App description"), + /** Minimum kernel version required */ + minKernelVersion: external_exports.string().optional().describe("Minimum required kernel version"), + /** Object definitions provided by this app */ + objects: external_exports.array(external_exports.string()).default([]).describe("Object names provided"), + /** View definitions provided */ + views: external_exports.array(external_exports.string()).default([]).describe("View names provided"), + /** Flow definitions provided */ + flows: external_exports.array(external_exports.string()).default([]).describe("Flow names provided"), + /** Whether seed data is included */ + hasSeedData: external_exports.boolean().default(false).describe("Whether app includes seed data"), + /** Seed data records to populate on install */ + seedData: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Seed data records"), + /** App dependencies (other apps that must be installed first) */ + dependencies: external_exports.array(external_exports.string()).default([]).describe("Required app dependencies") +}).describe("App manifest for marketplace installation"); +var AppCompatibilityCheckSchema2 = external_exports.object({ + /** Whether the app is compatible with the current environment */ + compatible: external_exports.boolean().describe("Whether the app is compatible"), + /** Compatibility issues found */ + issues: external_exports.array(external_exports.object({ + /** Issue severity */ + severity: external_exports.enum(["error", "warning"]).describe("Issue severity"), + /** Issue description */ + message: external_exports.string().describe("Issue description"), + /** Issue category */ + category: external_exports.enum([ + "kernel_version", + // Kernel version mismatch + "object_conflict", + // Object name already exists + "dependency_missing", + // Required dependency not installed + "quota_exceeded" + // Tenant quota would be exceeded + ]).describe("Issue category") + })).default([]).describe("Compatibility issues") +}).describe("App compatibility check result"); +var AppInstallRequestSchema2 = external_exports.object({ + /** Target tenant ID */ + tenantId: external_exports.string().min(1).describe("Target tenant ID"), + /** App identifier to install */ + appId: external_exports.string().min(1).describe("App identifier"), + /** Optional configuration overrides */ + configOverrides: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Configuration overrides"), + /** Whether to skip seed data */ + skipSeedData: external_exports.boolean().default(false).describe("Skip seed data population") +}).describe("App install request"); +var AppInstallResultSchema2 = external_exports.object({ + /** Whether the installation succeeded */ + success: external_exports.boolean().describe("Whether installation succeeded"), + /** App identifier that was installed */ + appId: external_exports.string().describe("Installed app identifier"), + /** App version installed */ + version: external_exports.string().describe("Installed app version"), + /** Objects created or updated */ + installedObjects: external_exports.array(external_exports.string()).default([]).describe("Objects created/updated"), + /** Tables created in the database */ + createdTables: external_exports.array(external_exports.string()).default([]).describe("Database tables created"), + /** Number of seed records inserted */ + seededRecords: external_exports.number().int().min(0).default(0).describe("Seed records inserted"), + /** Installation duration in milliseconds */ + durationMs: external_exports.number().int().min(0).optional().describe("Installation duration"), + /** Error message if installation failed */ + error: external_exports.string().optional().describe("Error message on failure") +}).describe("App install result"); +var PKG_CONVENTIONS = { + /** + * Standard directories within ObjectStack packages. + * All packages MUST follow these conventions for the runtime to locate resources. + */ + DIRS: { + /** + * Location for schema definitions (Zod schemas, JSON schemas). + * Path: src/schemas + */ + SCHEMA: "src/schemas", + /** + * Location for server-side code and triggers. + * Path: src/server + */ + SERVER: "src/server", + /** + * Location for server-side trigger functions. + * Path: src/triggers + */ + TRIGGERS: "src/triggers", + /** + * Location for client-side code. + * Path: src/client + */ + CLIENT: "src/client", + /** + * Location for client-side page components. + * Path: src/client/pages + */ + PAGES: "src/client/pages", + /** + * Location for static assets (images, fonts, etc.). + * Path: assets + */ + ASSETS: "assets" + }, + /** + * Standard file names within ObjectStack packages. + */ + FILES: { + /** + * Package manifest configuration file. + * File: objectstack.config.ts + */ + MANIFEST: "objectstack.config.ts", + /** + * Main entry point for the package. + * File: src/index.ts + */ + ENTRY: "src/index.ts" + } +}; +var SystemObjectName2 = { + /** Authentication: user identity */ + USER: "sys_user", + /** Authentication: active session */ + SESSION: "sys_session", + /** Authentication: OAuth / credential account */ + ACCOUNT: "sys_account", + /** Authentication: email / phone verification */ + VERIFICATION: "sys_verification", + /** Authentication: organization (multi-org support) */ + ORGANIZATION: "sys_organization", + /** Authentication: organization member */ + MEMBER: "sys_member", + /** Authentication: organization invitation */ + INVITATION: "sys_invitation", + /** Authentication: team within an organization */ + TEAM: "sys_team", + /** Authentication: team membership */ + TEAM_MEMBER: "sys_team_member", + /** Authentication: API key for programmatic access */ + API_KEY: "sys_api_key", + /** Authentication: two-factor authentication credentials */ + TWO_FACTOR: "sys_two_factor", + /** Authentication: user preferences (theme, locale, etc.) */ + USER_PREFERENCE: "sys_user_preference", + /** Security: role definition for RBAC */ + ROLE: "sys_role", + /** Security: permission set grouping */ + PERMISSION_SET: "sys_permission_set", + /** Audit: system audit log */ + AUDIT_LOG: "sys_audit_log", + /** System metadata storage */ + METADATA: "sys_metadata", + /** Realtime: user presence state */ + PRESENCE: "sys_presence" +}; +var SystemFieldName = { + /** Primary key */ + ID: "id", + /** Record creation timestamp */ + CREATED_AT: "created_at", + /** Record last-updated timestamp */ + UPDATED_AT: "updated_at", + /** Record owner (lookup to user) */ + OWNER_ID: "owner_id", + /** Tenant isolation key */ + TENANT_ID: "tenant_id", + /** Foreign key to user on session / account objects */ + USER_ID: "user_id", + /** Soft-delete timestamp */ + DELETED_AT: "deleted_at" +}; +var StorageNameMapping = { + /** + * Resolve the physical table name for an object. + * Priority: explicit `tableName` → auto-derived `{namespace}_{name}` → `name`. + * + * @param object - Object definition (at minimum `{ name: string; namespace?: string; tableName?: string }`) + * @returns The physical table / collection name to use in storage operations. + */ + resolveTableName(object2) { + return object2.tableName ?? (object2.namespace ? `${object2.namespace}_${object2.name}` : object2.name); + }, + /** + * Resolve the physical column name for a field. + * Falls back to `fieldKey` when `columnName` is not set on the field. + * + * @param fieldKey - The protocol-level field key (snake_case identifier). + * @param field - Field definition (at minimum `{ columnName?: string }`). + * @returns The physical column name to use in storage operations. + */ + resolveColumnName(fieldKey, field) { + return field.columnName ?? fieldKey; + }, + /** + * Build a complete field-key → column-name map for an entire object. + * + * @param fields - The fields record from an ObjectSchema. + * @returns A record mapping every protocol field key to its physical column name. + */ + buildColumnMap(fields) { + const map3 = {}; + for (const key of Object.keys(fields)) { + map3[key] = fields[key].columnName ?? key; + } + return map3; + }, + /** + * Build a reverse column-name → field-key map for an entire object. + * Useful for translating storage-layer results back to protocol-level field keys. + * + * @param fields - The fields record from an ObjectSchema. + * @returns A record mapping every physical column name back to its protocol field key. + */ + buildReverseColumnMap(fields) { + const map3 = {}; + for (const key of Object.keys(fields)) { + const col = fields[key].columnName ?? key; + map3[col] = key; + } + return map3; + } +}; +var kernel_exports = {}; +__export4(kernel_exports, { + ActivationEventSchema: () => ActivationEventSchema2, + AdvancedPluginLifecycleConfigSchema: () => AdvancedPluginLifecycleConfigSchema2, + ArtifactChecksumSchema: () => ArtifactChecksumSchema3, + ArtifactFileEntrySchema: () => ArtifactFileEntrySchema3, + ArtifactSignatureSchema: () => ArtifactSignatureSchema3, + BreakingChangeSchema: () => BreakingChangeSchema2, + CLICommandContributionSchema: () => CLICommandContributionSchema2, + CORE_PLUGIN_TYPES: () => CORE_PLUGIN_TYPES3, + CapabilityConformanceLevelSchema: () => CapabilityConformanceLevelSchema3, + CompatibilityLevelSchema: () => CompatibilityLevelSchema2, + CompatibilityMatrixEntrySchema: () => CompatibilityMatrixEntrySchema2, + CustomizationOriginSchema: () => CustomizationOriginSchema2, + CustomizationPolicySchema: () => CustomizationPolicySchema3, + DEFAULT_METADATA_TYPE_REGISTRY: () => DEFAULT_METADATA_TYPE_REGISTRY, + DeadLetterQueueEntrySchema: () => DeadLetterQueueEntrySchema2, + DependencyConflictSchema: () => DependencyConflictSchema2, + DependencyGraphNodeSchema: () => DependencyGraphNodeSchema2, + DependencyGraphSchema: () => DependencyGraphSchema2, + DependencyResolutionResultSchema: () => DependencyResolutionResultSchema3, + DependencyStatusEnum: () => DependencyStatusEnum3, + DeprecationNoticeSchema: () => DeprecationNoticeSchema2, + DevFixtureConfigSchema: () => DevFixtureConfigSchema2, + DevPluginConfigSchema: () => DevPluginConfigSchema2, + DevPluginPreset: () => DevPluginPreset2, + DevServiceOverrideSchema: () => DevServiceOverrideSchema2, + DevToolsConfigSchema: () => DevToolsConfigSchema2, + DisablePackageRequestSchema: () => DisablePackageRequestSchema3, + DisablePackageResponseSchema: () => DisablePackageResponseSchema3, + DistributedStateConfigSchema: () => DistributedStateConfigSchema2, + DynamicLoadRequestSchema: () => DynamicLoadRequestSchema2, + DynamicLoadingConfigSchema: () => DynamicLoadingConfigSchema2, + DynamicPluginOperationSchema: () => DynamicPluginOperationSchema2, + DynamicPluginResultSchema: () => DynamicPluginResultSchema2, + DynamicUnloadRequestSchema: () => DynamicUnloadRequestSchema2, + EVENT_PRIORITY_VALUES: () => EVENT_PRIORITY_VALUES, + EnablePackageRequestSchema: () => EnablePackageRequestSchema3, + EnablePackageResponseSchema: () => EnablePackageResponseSchema3, + EventBusConfigSchema: () => EventBusConfigSchema2, + EventHandlerSchema: () => EventHandlerSchema2, + EventLogEntrySchema: () => EventLogEntrySchema2, + EventMessageQueueConfigSchema: () => EventMessageQueueConfigSchema2, + EventMetadataSchema: () => EventMetadataSchema2, + EventPersistenceSchema: () => EventPersistenceSchema2, + EventPhaseSchema: () => EventPhaseSchema2, + EventPriority: () => EventPriority2, + EventQueueConfigSchema: () => EventQueueConfigSchema2, + EventReplayConfigSchema: () => EventReplayConfigSchema2, + EventRouteSchema: () => EventRouteSchema2, + EventSchema: () => EventSchema22, + EventSourcingConfigSchema: () => EventSourcingConfigSchema2, + EventTypeDefinitionSchema: () => EventTypeDefinitionSchema2, + EventWebhookConfigSchema: () => EventWebhookConfigSchema2, + ExecutionContextSchema: () => ExecutionContextSchema3, + ExtensionPointSchema: () => ExtensionPointSchema3, + FeatureFlag: () => FeatureFlag2, + FeatureFlagSchema: () => FeatureFlagSchema2, + FeatureStrategy: () => FeatureStrategy2, + FieldChangeSchema: () => FieldChangeSchema3, + GetPackageRequestSchema: () => GetPackageRequestSchema3, + GetPackageResponseSchema: () => GetPackageResponseSchema3, + GracefulDegradationSchema: () => GracefulDegradationSchema2, + HealthStatusSchema: () => HealthStatusSchema2, + HookRegisteredEventSchema: () => HookRegisteredEventSchema2, + HookTriggeredEventSchema: () => HookTriggeredEventSchema2, + HotReloadConfigSchema: () => HotReloadConfigSchema2, + InstallPackageRequestSchema: () => InstallPackageRequestSchema3, + InstallPackageResponseSchema: () => InstallPackageResponseSchema3, + InstalledPackageSchema: () => InstalledPackageSchema3, + KernelContextSchema: () => KernelContextSchema2, + KernelEventBaseSchema: () => KernelEventBaseSchema2, + KernelReadyEventSchema: () => KernelReadyEventSchema2, + KernelSecurityPolicySchema: () => KernelSecurityPolicySchema2, + KernelSecurityScanResultSchema: () => KernelSecurityScanResultSchema2, + KernelSecurityVulnerabilitySchema: () => KernelSecurityVulnerabilitySchema2, + KernelShutdownEventSchema: () => KernelShutdownEventSchema2, + ListPackagesRequestSchema: () => ListPackagesRequestSchema3, + ListPackagesResponseSchema: () => ListPackagesResponseSchema3, + ManifestSchema: () => ManifestSchema3, + MergeConflictSchema: () => MergeConflictSchema3, + MergeResultSchema: () => MergeResultSchema2, + MergeStrategyConfigSchema: () => MergeStrategyConfigSchema3, + MetadataBulkRegisterRequestSchema: () => MetadataBulkRegisterRequestSchema3, + MetadataBulkResultSchema: () => MetadataBulkResultSchema3, + MetadataCategoryEnum: () => MetadataCategoryEnum3, + MetadataChangeTypeSchema: () => MetadataChangeTypeSchema3, + MetadataCollectionInfoSchema: () => MetadataCollectionInfoSchema22, + MetadataDependencySchema: () => MetadataDependencySchema3, + MetadataDiffItemSchema: () => MetadataDiffItemSchema3, + MetadataEventSchema: () => MetadataEventSchema3, + MetadataExportOptionsSchema: () => MetadataExportOptionsSchema22, + MetadataFallbackStrategySchema: () => MetadataFallbackStrategySchema22, + MetadataFormatSchema: () => MetadataFormatSchema32, + MetadataImportOptionsSchema: () => MetadataImportOptionsSchema22, + MetadataLoadOptionsSchema: () => MetadataLoadOptionsSchema22, + MetadataLoadResultSchema: () => MetadataLoadResultSchema22, + MetadataLoaderContractSchema: () => MetadataLoaderContractSchema22, + MetadataManagerConfigSchema: () => MetadataManagerConfigSchema22, + MetadataOverlaySchema: () => MetadataOverlaySchema3, + MetadataPluginConfigSchema: () => MetadataPluginConfigSchema3, + MetadataPluginManifestSchema: () => MetadataPluginManifestSchema2, + MetadataQueryResultSchema: () => MetadataQueryResultSchema3, + MetadataQuerySchema: () => MetadataQuerySchema3, + MetadataSaveOptionsSchema: () => MetadataSaveOptionsSchema22, + MetadataSaveResultSchema: () => MetadataSaveResultSchema22, + MetadataStatsSchema: () => MetadataStatsSchema22, + MetadataTypeRegistryEntrySchema: () => MetadataTypeRegistryEntrySchema3, + MetadataTypeSchema: () => MetadataTypeSchema3, + MetadataValidationResultSchema: () => MetadataValidationResultSchema3, + MetadataWatchEventSchema: () => MetadataWatchEventSchema22, + MultiVersionSupportSchema: () => MultiVersionSupportSchema2, + NamespaceConflictErrorSchema: () => NamespaceConflictErrorSchema2, + NamespaceRegistryEntrySchema: () => NamespaceRegistryEntrySchema2, + OclifPluginConfigSchema: () => OclifPluginConfigSchema2, + OpsDomainModuleSchema: () => OpsDomainModuleSchema2, + OpsFilePathSchema: () => OpsFilePathSchema2, + OpsPluginStructureSchema: () => OpsPluginStructureSchema2, + PackageArtifactSchema: () => PackageArtifactSchema3, + PackageDependencyConflictSchema: () => PackageDependencyConflictSchema2, + PackageDependencyResolutionResultSchema: () => PackageDependencyResolutionResultSchema2, + PackageDependencySchema: () => PackageDependencySchema2, + PackageStatusEnum: () => PackageStatusEnum3, + PermissionActionSchema: () => PermissionActionSchema2, + PermissionSchema: () => PermissionSchema2, + PermissionScopeSchema: () => PermissionScopeSchema2, + PermissionSetSchema: () => PermissionSetSchema22, + PluginBuildOptionsSchema: () => PluginBuildOptionsSchema2, + PluginBuildResultSchema: () => PluginBuildResultSchema2, + PluginCachingSchema: () => PluginCachingSchema3, + PluginCapabilityManifestSchema: () => PluginCapabilityManifestSchema3, + PluginCapabilitySchema: () => PluginCapabilitySchema3, + PluginCodeSplittingSchema: () => PluginCodeSplittingSchema3, + PluginCompatibilityMatrixSchema: () => PluginCompatibilityMatrixSchema2, + PluginContextSchema: () => PluginContextSchema2, + PluginDependencyResolutionResultSchema: () => PluginDependencyResolutionResultSchema2, + PluginDependencyResolutionSchema: () => PluginDependencyResolutionSchema3, + PluginDependencySchema: () => PluginDependencySchema3, + PluginDiscoveryConfigSchema: () => PluginDiscoveryConfigSchema2, + PluginDiscoverySourceSchema: () => PluginDiscoverySourceSchema2, + PluginDynamicImportSchema: () => PluginDynamicImportSchema3, + PluginErrorEventSchema: () => PluginErrorEventSchema2, + PluginEventBaseSchema: () => PluginEventBaseSchema2, + PluginHealthCheckSchema: () => PluginHealthCheckSchema2, + PluginHealthReportSchema: () => PluginHealthReportSchema2, + PluginHealthStatusSchema: () => PluginHealthStatusSchema2, + PluginHotReloadSchema: () => PluginHotReloadSchema3, + PluginInitializationSchema: () => PluginInitializationSchema3, + PluginInstallConfigSchema: () => PluginInstallConfigSchema2, + PluginInterfaceSchema: () => PluginInterfaceSchema3, + PluginLifecycleEventType: () => PluginLifecycleEventType2, + PluginLifecyclePhaseEventSchema: () => PluginLifecyclePhaseEventSchema2, + PluginLifecycleSchema: () => PluginLifecycleSchema3, + PluginLoadingConfigSchema: () => PluginLoadingConfigSchema3, + PluginLoadingEventSchema: () => PluginLoadingEventSchema2, + PluginLoadingStateSchema: () => PluginLoadingStateSchema2, + PluginLoadingStrategySchema: () => PluginLoadingStrategySchema3, + PluginMetadataSchema: () => PluginMetadataSchema2, + PluginPerformanceMonitoringSchema: () => PluginPerformanceMonitoringSchema3, + PluginPreloadConfigSchema: () => PluginPreloadConfigSchema3, + PluginProvenanceSchema: () => PluginProvenanceSchema2, + PluginPublishOptionsSchema: () => PluginPublishOptionsSchema2, + PluginPublishResultSchema: () => PluginPublishResultSchema2, + PluginQualityMetricsSchema: () => PluginQualityMetricsSchema2, + PluginRegisteredEventSchema: () => PluginRegisteredEventSchema2, + PluginRegistryEntrySchema: () => PluginRegistryEntrySchema2, + PluginSandboxingSchema: () => PluginSandboxingSchema3, + PluginSchema: () => PluginSchema2, + PluginSearchFiltersSchema: () => PluginSearchFiltersSchema2, + PluginSecurityManifestSchema: () => PluginSecurityManifestSchema2, + PluginSecurityProtocol: () => PluginSecurityProtocol, + PluginSourceSchema: () => PluginSourceSchema2, + PluginStartupResultSchema: () => PluginStartupResultSchema2, + PluginStateSnapshotSchema: () => PluginStateSnapshotSchema2, + PluginStatisticsSchema: () => PluginStatisticsSchema2, + PluginTrustLevelSchema: () => PluginTrustLevelSchema2, + PluginTrustScoreSchema: () => PluginTrustScoreSchema2, + PluginUpdateStrategySchema: () => PluginUpdateStrategySchema2, + PluginValidateOptionsSchema: () => PluginValidateOptionsSchema2, + PluginValidateResultSchema: () => PluginValidateResultSchema2, + PluginVendorSchema: () => PluginVendorSchema2, + PluginVersionMetadataSchema: () => PluginVersionMetadataSchema2, + PreviewModeConfigSchema: () => PreviewModeConfigSchema2, + ProtocolFeatureSchema: () => ProtocolFeatureSchema3, + ProtocolReferenceSchema: () => ProtocolReferenceSchema3, + ProtocolVersionSchema: () => ProtocolVersionSchema3, + RealTimeNotificationConfigSchema: () => RealTimeNotificationConfigSchema2, + RequiredActionSchema: () => RequiredActionSchema3, + ResolvedDependencySchema: () => ResolvedDependencySchema3, + ResourceTypeSchema: () => ResourceTypeSchema2, + RollbackPackageRequestSchema: () => RollbackPackageRequestSchema2, + RollbackPackageResponseSchema: () => RollbackPackageResponseSchema2, + RuntimeConfigSchema: () => RuntimeConfigSchema2, + RuntimeMode: () => RuntimeMode2, + SBOMEntrySchema: () => SBOMEntrySchema2, + SBOMSchema: () => SBOMSchema2, + SandboxConfigSchema: () => SandboxConfigSchema2, + ScopeConfigSchema: () => ScopeConfigSchema2, + ScopeInfoSchema: () => ScopeInfoSchema2, + SecurityPolicySchema: () => SecurityPolicySchema2, + SecurityScanResultSchema: () => SecurityScanResultSchema2, + SecurityVulnerabilitySchema: () => SecurityVulnerabilitySchema2, + SemanticVersionSchema: () => SemanticVersionSchema2, + ServiceFactoryRegistrationSchema: () => ServiceFactoryRegistrationSchema2, + ServiceMetadataSchema: () => ServiceMetadataSchema2, + ServiceRegisteredEventSchema: () => ServiceRegisteredEventSchema2, + ServiceRegistryConfigSchema: () => ServiceRegistryConfigSchema2, + ServiceScopeType: () => ServiceScopeType2, + ServiceUnregisteredEventSchema: () => ServiceUnregisteredEventSchema2, + StartupOptionsSchema: () => StartupOptionsSchema2, + StartupOrchestrationResultSchema: () => StartupOrchestrationResultSchema2, + TenantRuntimeContextSchema: () => TenantRuntimeContextSchema2, + UninstallPackageRequestSchema: () => UninstallPackageRequestSchema3, + UninstallPackageResponseSchema: () => UninstallPackageResponseSchema3, + UpgradeContextSchema: () => UpgradeContextSchema2, + UpgradeImpactLevelSchema: () => UpgradeImpactLevelSchema3, + UpgradePackageRequestSchema: () => UpgradePackageRequestSchema2, + UpgradePackageResponseSchema: () => UpgradePackageResponseSchema2, + UpgradePhaseSchema: () => UpgradePhaseSchema3, + UpgradePlanSchema: () => UpgradePlanSchema3, + UpgradeSnapshotSchema: () => UpgradeSnapshotSchema2, + ValidationErrorSchema: () => ValidationErrorSchema2, + ValidationFindingSchema: () => ValidationFindingSchema2, + ValidationResultSchema: () => ValidationResultSchema2, + ValidationSeverityEnum: () => ValidationSeverityEnum2, + ValidationWarningSchema: () => ValidationWarningSchema2, + VersionConstraintSchema: () => VersionConstraintSchema2, + VulnerabilitySeverity: () => VulnerabilitySeverity2 +}); +var CLICommandContributionSchema2 = external_exports.object({ + /** + * CLI command name. Must be a valid identifier: lowercase alphanumeric with hyphens. + * This becomes a top-level subcommand of the `os` CLI. + * + * @example "marketplace" + * @example "deploy" + * @example "cloud-sync" + */ + name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), + /** Brief description shown in `os --help` output. */ + description: external_exports.string().optional().describe("Command description for help text"), + /** + * Module path that exports the oclif Command class(es). + * Relative to the plugin package root. With oclif, this is typically + * auto-discovered from the `commands` directory, but can be specified + * for documentation or manifest purposes. + * + * @example "./dist/commands/marketplace.js" + * @example "./dist/commands" + */ + module: external_exports.string().optional().describe("Module path exporting oclif Command classes") +}); +var OclifPluginConfigSchema2 = external_exports.object({ + /** Command discovery configuration */ + commands: external_exports.object({ + /** Discovery strategy — typically "pattern" for file-based discovery */ + strategy: external_exports.enum(["pattern", "explicit", "single"]).optional().describe("Command discovery strategy"), + /** Directory path containing compiled command files */ + target: external_exports.string().optional().describe("Target directory for command files"), + /** Glob pattern for matching command files */ + glob: external_exports.string().optional().describe("Glob pattern for command file matching") + }).optional().describe("Command discovery configuration"), + /** Topic separator character (default: space) */ + topicSeparator: external_exports.string().optional().describe("Character separating topic and command names") +}).describe("oclif plugin configuration section"); +var MetadataCategoryEnum3 = external_exports.enum([ + "objects", + "views", + "pages", + "flows", + "dashboards", + "permissions", + "agents", + "reports", + "actions", + "translations", + "themes", + "datasets", + "apis", + "triggers", + "workflows" +]).describe("Metadata category within the artifact"); +var ArtifactFileEntrySchema3 = external_exports.object({ + /** Relative path within the artifact (e.g. "metadata/objects/account.object.json") */ + path: external_exports.string().describe("Relative file path within the artifact"), + /** File size in bytes */ + size: external_exports.number().int().nonnegative().describe("File size in bytes"), + /** Metadata category (if under metadata/) */ + category: MetadataCategoryEnum3.optional().describe("Metadata category this file belongs to") +}).describe("A single file entry within the artifact"); +var ArtifactChecksumSchema3 = external_exports.object({ + /** Hash algorithm used (default: SHA256) */ + algorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm used for checksums"), + /** Map of relative file paths to their hash values */ + files: external_exports.record(external_exports.string(), external_exports.string().regex(/^[a-f0-9]+$/)).describe("File path to hash value mapping") +}).describe("Checksum manifest for artifact integrity verification"); +var ArtifactSignatureSchema3 = external_exports.object({ + /** Signature algorithm */ + algorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).default("RSA-SHA256").describe("Signing algorithm used"), + /** Public key reference (URL or fingerprint) for verification */ + publicKeyRef: external_exports.string().describe("Public key reference (URL or fingerprint) for signature verification"), + /** Base64-encoded signature value */ + signature: external_exports.string().describe("Base64-encoded digital signature"), + /** Timestamp of when the artifact was signed */ + signedAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp of when the artifact was signed"), + /** Signer identity (publisher ID or email) */ + signedBy: external_exports.string().optional().describe("Identity of the signer (publisher ID or email)") +}).describe("Digital signature for artifact authenticity verification"); +var PackageArtifactSchema3 = external_exports.object({ + /** Artifact format version (for forward compatibility) */ + formatVersion: external_exports.string().regex(/^\d+\.\d+$/).default("1.0").describe('Artifact format version (e.g. "1.0")'), + /** Package ID from the manifest */ + packageId: external_exports.string().describe("Package identifier from manifest"), + /** Package version from the manifest */ + version: external_exports.string().describe("Package version from manifest"), + /** Artifact format */ + format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format of the artifact"), + /** Total artifact size in bytes */ + size: external_exports.number().int().positive().optional().describe("Total artifact file size in bytes"), + /** Build timestamp */ + builtAt: external_exports.string().datetime().describe("ISO 8601 timestamp of when the artifact was built"), + /** Build tool and version that produced this artifact */ + builtWith: external_exports.string().optional().describe('Build tool identifier (e.g. "os-cli@3.2.0")'), + /** File listing within the artifact */ + files: external_exports.array(ArtifactFileEntrySchema3).optional().describe("List of files contained in the artifact"), + /** Metadata categories present in the artifact */ + metadataCategories: external_exports.array(MetadataCategoryEnum3).optional().describe("Metadata categories included in this artifact"), + /** Integrity checksums for all files */ + checksums: ArtifactChecksumSchema3.optional().describe("SHA256 checksums for artifact integrity verification"), + /** Digital signature for authenticity */ + signature: ArtifactSignatureSchema3.optional().describe("Digital signature for artifact authenticity verification") +}).describe("Package artifact structure and metadata"); +var PluginBuildOptionsSchema2 = external_exports.object({ + /** Project root directory (defaults to cwd) */ + directory: external_exports.string().optional().describe("Project root directory (defaults to current working directory)"), + /** Output directory for the built artifact */ + outDir: external_exports.string().optional().describe("Output directory for the built artifact (defaults to ./dist)"), + /** Archive format */ + format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format for the artifact"), + /** Whether to sign the artifact */ + sign: external_exports.boolean().default(false).describe("Whether to digitally sign the artifact"), + /** Path to the private key for signing */ + privateKeyPath: external_exports.string().optional().describe("Path to RSA/ECDSA private key file for signing"), + /** Signing algorithm */ + signAlgorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).optional().describe("Signing algorithm to use"), + /** Checksum algorithm */ + checksumAlgorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm for file checksums"), + /** Whether to include seed data */ + includeData: external_exports.boolean().default(true).describe("Whether to include seed data in the artifact"), + /** Whether to include locale/translation files */ + includeLocales: external_exports.boolean().default(true).describe("Whether to include locale/translation files") +}).describe("Options for the os plugin build command"); +var PluginBuildResultSchema2 = external_exports.object({ + /** Whether the build succeeded */ + success: external_exports.boolean().describe("Whether the build succeeded"), + /** Path to the generated artifact file */ + artifactPath: external_exports.string().optional().describe("Absolute path to the generated artifact file"), + /** Artifact metadata (validated against PackageArtifactSchema) */ + artifact: PackageArtifactSchema3.optional().describe("Artifact metadata"), + /** Total file count in the artifact */ + fileCount: external_exports.number().int().min(0).optional().describe("Total number of files in the artifact"), + /** Total artifact size in bytes */ + size: external_exports.number().int().min(0).optional().describe("Total artifact size in bytes"), + /** Build duration in milliseconds */ + durationMs: external_exports.number().optional().describe("Build duration in milliseconds"), + /** Error message if build failed */ + errorMessage: external_exports.string().optional().describe("Error message if build failed"), + /** Warnings emitted during build */ + warnings: external_exports.array(external_exports.string()).optional().describe("Warnings emitted during build") +}).describe("Result of the os plugin build command"); +var ValidationSeverityEnum2 = external_exports.enum([ + "error", + // Must fix — artifact is invalid + "warning", + // Should fix — may cause issues + "info" + // Informational — suggestion +]).describe("Validation issue severity"); +var ValidationFindingSchema2 = external_exports.object({ + /** Finding severity */ + severity: ValidationSeverityEnum2.describe("Issue severity level"), + /** Rule or check that produced this finding */ + rule: external_exports.string().describe("Validation rule identifier"), + /** Human-readable message */ + message: external_exports.string().describe("Human-readable finding description"), + /** File path within the artifact (if applicable) */ + path: external_exports.string().optional().describe("Relative file path within the artifact") +}).describe("A single validation finding"); +var PluginValidateOptionsSchema2 = external_exports.object({ + /** Path to the .tgz artifact file to validate */ + artifactPath: external_exports.string().describe("Path to the artifact file to validate"), + /** Whether to verify the digital signature */ + verifySignature: external_exports.boolean().default(true).describe("Whether to verify the digital signature"), + /** Path to the public key for signature verification */ + publicKeyPath: external_exports.string().optional().describe("Path to the public key for signature verification"), + /** Whether to verify SHA256 checksums of all files */ + verifyChecksums: external_exports.boolean().default(true).describe("Whether to verify checksums of all files"), + /** Whether to validate metadata schema compliance */ + validateMetadata: external_exports.boolean().default(true).describe("Whether to validate metadata against schemas"), + /** Target platform version for compatibility check */ + platformVersion: external_exports.string().optional().describe("Platform version for compatibility verification") +}).describe("Options for the os plugin validate command"); +var PluginValidateResultSchema2 = external_exports.object({ + /** Whether the artifact is valid (no error-level findings) */ + valid: external_exports.boolean().describe("Whether the artifact passed validation"), + /** Artifact metadata extracted from the archive */ + artifact: PackageArtifactSchema3.optional().describe("Extracted artifact metadata"), + /** Checksum verification result */ + checksumVerification: external_exports.object({ + /** Whether all checksums match */ + passed: external_exports.boolean().describe("Whether all checksums match"), + /** Checksum details */ + checksums: ArtifactChecksumSchema3.optional().describe("Verified checksums"), + /** Files with mismatched checksums */ + mismatches: external_exports.array(external_exports.string()).optional().describe("Files with checksum mismatches") + }).optional().describe("Checksum verification result"), + /** Signature verification result */ + signatureVerification: external_exports.object({ + /** Whether the signature is valid */ + passed: external_exports.boolean().describe("Whether the signature is valid"), + /** Signature details */ + signature: ArtifactSignatureSchema3.optional().describe("Signature details"), + /** Reason for failure */ + failureReason: external_exports.string().optional().describe("Signature verification failure reason") + }).optional().describe("Signature verification result"), + /** Platform compatibility result */ + platformCompatibility: external_exports.object({ + /** Whether the artifact is compatible with the target platform */ + compatible: external_exports.boolean().describe("Whether artifact is compatible"), + /** Required platform version range */ + requiredRange: external_exports.string().optional().describe("Required platform version range"), + /** Target platform version checked against */ + targetVersion: external_exports.string().optional().describe("Target platform version") + }).optional().describe("Platform compatibility check result"), + /** All validation findings */ + findings: external_exports.array(ValidationFindingSchema2).describe("All validation findings"), + /** Counts by severity */ + summary: external_exports.object({ + errors: external_exports.number().int().min(0).describe("Error count"), + warnings: external_exports.number().int().min(0).describe("Warning count"), + infos: external_exports.number().int().min(0).describe("Info count") + }).optional().describe("Finding counts by severity") +}).describe("Result of the os plugin validate command"); +var PluginPublishOptionsSchema2 = external_exports.object({ + /** Path to the .tgz artifact file to publish */ + artifactPath: external_exports.string().describe("Path to the artifact file to publish"), + /** Marketplace API base URL */ + registryUrl: external_exports.string().url().optional().describe("Marketplace API base URL"), + /** Authentication token for the marketplace API */ + token: external_exports.string().optional().describe("Authentication token for marketplace API"), + /** Release notes for this version */ + releaseNotes: external_exports.string().optional().describe("Release notes for this version"), + /** Whether this is a pre-release */ + preRelease: external_exports.boolean().default(false).describe("Whether this is a pre-release version"), + /** Whether to skip validation before publishing */ + skipValidation: external_exports.boolean().default(false).describe("Whether to skip local validation before publish"), + /** Access level for the published package */ + access: external_exports.enum(["public", "restricted"]).default("public").describe("Package access level on the marketplace"), + /** Tags for categorization */ + tags: external_exports.array(external_exports.string()).optional().describe("Tags for marketplace categorization") +}).describe("Options for the os plugin publish command"); +var PluginPublishResultSchema2 = external_exports.object({ + /** Whether the publish succeeded */ + success: external_exports.boolean().describe("Whether the publish succeeded"), + /** Package ID that was published */ + packageId: external_exports.string().optional().describe("Published package identifier"), + /** Version that was published */ + version: external_exports.string().optional().describe("Published version string"), + /** Artifact reference in the marketplace */ + artifactUrl: external_exports.string().url().optional().describe("URL of the published artifact in the marketplace"), + /** SHA256 checksum of the uploaded artifact */ + sha256: external_exports.string().optional().describe("SHA256 checksum of the uploaded artifact"), + /** Submission ID for tracking the review process */ + submissionId: external_exports.string().optional().describe("Marketplace submission ID for review tracking"), + /** Error message if publish failed */ + errorMessage: external_exports.string().optional().describe("Error message if publish failed"), + /** Human-readable status message */ + message: external_exports.string().optional().describe("Human-readable status message") +}).describe("Result of the os plugin publish command"); +var RuntimeMode2 = external_exports.enum([ + "development", + // Hot-reload, verbose logging + "production", + // Optimized, strict security + "test", + // Mocked interfaces + "provisioning", + // Setup/Migration mode + "preview" + // Demo/preview mode — bypass auth, simulate admin identity +]).describe("Kernel operating mode"); +var PreviewModeConfigSchema2 = external_exports.object({ + /** + * Automatically log in as a simulated user on startup. + * When enabled, the frontend skips login/registration screens entirely. + */ + autoLogin: external_exports.boolean().default(true).describe("Auto-login as simulated user, skipping login/registration pages"), + /** + * Role of the simulated user. + * Determines the permission level of the auto-created preview session. + */ + simulatedRole: external_exports.enum(["admin", "user", "viewer"]).default("admin").describe("Permission role for the simulated preview user"), + /** + * Display name for the simulated user shown in the UI. + */ + simulatedUserName: external_exports.string().default("Preview User").describe("Display name for the simulated preview user"), + /** + * Whether the preview session is read-only. + * When true, all write operations (create, update, delete) are blocked. + */ + readOnly: external_exports.boolean().default(false).describe("Restrict the preview session to read-only operations"), + /** + * Session duration in seconds. After expiry the preview session ends. + * 0 means no expiration. + */ + expiresInSeconds: external_exports.number().int().min(0).default(0).describe("Preview session duration in seconds (0 = no expiration)"), + /** + * Optional banner message shown in the UI to indicate preview mode. + * Useful for marketplace demos so visitors know they are in a sandbox. + */ + bannerMessage: external_exports.string().optional().describe("Banner message displayed in the UI during preview mode") +}); +var KernelContextSchema2 = external_exports.object({ + /** + * Instance Identity + */ + instanceId: external_exports.string().uuid().describe("Unique UUID for this running kernel process"), + /** + * Environment Metadata + */ + mode: RuntimeMode2.default("production"), + version: external_exports.string().describe("Kernel version"), + appName: external_exports.string().optional().describe("Host application name"), + /** + * Paths + */ + cwd: external_exports.string().describe("Current working directory"), + workspaceRoot: external_exports.string().optional().describe("Workspace root if different from cwd"), + /** + * Telemetry + */ + startTime: external_exports.number().int().describe("Boot timestamp (ms)"), + /** + * Feature Flags (Global) + */ + features: external_exports.record(external_exports.string(), external_exports.boolean()).default({}).describe("Global feature toggles"), + /** + * Preview Mode Configuration. + * Only relevant when `mode` is `'preview'`. Configures auto-login, + * simulated identity, read-only restrictions, and UI banner. + */ + previewMode: PreviewModeConfigSchema2.optional().describe('Preview/demo mode configuration (used when mode is "preview")') +}); +var TenantRuntimeContextSchema2 = KernelContextSchema2.extend({ + /** Unique tenant identifier resolved from the current session */ + tenantId: external_exports.string().min(1).describe("Resolved tenant identifier"), + /** Tenant subscription plan */ + tenantPlan: external_exports.enum(["free", "pro", "enterprise"]).describe("Tenant subscription plan"), + /** Tenant deployment region */ + tenantRegion: external_exports.string().optional().describe("Tenant deployment region"), + /** Tenant database connection URL */ + tenantDbUrl: external_exports.string().min(1).describe("Tenant database connection URL"), + /** Optional tenant quotas for the current plan */ + tenantQuotas: TenantQuotaSchema3.optional().describe("Tenant resource quotas") +}).describe("Tenant-aware kernel runtime context"); +var DependencyStatusEnum3 = external_exports.enum([ + "satisfied", + // Already installed and version compatible + "needs_install", + // Not installed, needs to be installed + "needs_upgrade", + // Installed but version incompatible, needs upgrade + "conflict" + // Conflicts with another package's dependency +]).describe("Resolution status for a dependency"); +var ResolvedDependencySchema3 = external_exports.object({ + /** Package identifier of the dependency */ + packageId: external_exports.string().describe("Dependency package identifier"), + /** SemVer range required by the parent package */ + requiredRange: external_exports.string().describe('SemVer range required (e.g. "^2.0.0")'), + /** Actual version resolved (if available) */ + resolvedVersion: external_exports.string().optional().describe("Actual version resolved from registry"), + /** Currently installed version (if any) */ + installedVersion: external_exports.string().optional().describe("Currently installed version"), + /** Resolution status */ + status: DependencyStatusEnum3.describe("Resolution status"), + /** Conflict details (when status is "conflict") */ + conflictReason: external_exports.string().optional().describe("Explanation of the conflict") +}).describe("Resolution result for a single dependency"); +var RequiredActionSchema3 = external_exports.object({ + /** Type of action required */ + type: external_exports.enum(["install", "upgrade", "confirm_conflict"]).describe("Type of action required"), + /** Target package identifier */ + packageId: external_exports.string().describe("Target package identifier"), + /** Human-readable description of the action */ + description: external_exports.string().describe("Human-readable action description") +}).describe("Action required before installation can proceed"); +var DependencyResolutionResultSchema3 = external_exports.object({ + /** All dependencies and their resolution results */ + dependencies: external_exports.array(ResolvedDependencySchema3).describe("Resolution result for each dependency"), + /** Whether installation can proceed without conflicts */ + canProceed: external_exports.boolean().describe("Whether installation can proceed"), + /** Actions that require user confirmation or system execution */ + requiredActions: external_exports.array(RequiredActionSchema3).describe("Actions required before proceeding"), + /** Topologically sorted package IDs for installation order */ + installOrder: external_exports.array(external_exports.string()).describe("Topologically sorted package IDs for installation"), + /** Detected circular dependency chains */ + circularDependencies: external_exports.array(external_exports.array(external_exports.string())).optional().describe('Circular dependency chains detected (e.g. [["A", "B", "A"]])') +}).describe("Complete dependency resolution result"); +var DevServiceOverrideSchema2 = external_exports.object({ + /** Service identifier (e.g. 'auth', 'eventBus', 'fileStorage') */ + service: external_exports.string().min(1).describe("Target service identifier"), + /** Whether this service is enabled in dev mode */ + enabled: external_exports.boolean().default(true).describe("Enable or disable this service"), + /** + * Implementation strategy for the service in dev mode. + * - mock: Use a mock/stub that records calls (for assertions) + * - memory: Use a real but in-memory implementation (e.g. SQLite, Map) + * - stub: Use a static/no-op implementation + * - passthrough: Use the real production implementation (for integration testing) + */ + strategy: external_exports.enum(["mock", "memory", "stub", "passthrough"]).default("memory").describe("Implementation strategy for development"), + /** Optional per-service configuration (strategy-specific) */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Strategy-specific configuration for this service override") +}); +var DevFixtureConfigSchema2 = external_exports.object({ + /** Whether to load fixtures on startup */ + enabled: external_exports.boolean().default(true).describe("Load fixture data on startup"), + /** + * Glob patterns pointing to fixture files + * (e.g. `["./fixtures/*.json", "./test/data/*.yml"]`) + */ + paths: external_exports.array(external_exports.string()).optional().describe("Glob patterns for fixture files"), + /** Whether to reset data before loading fixtures */ + resetBeforeLoad: external_exports.boolean().default(true).describe("Clear existing data before loading fixtures"), + /** + * Environment tag filter – only load fixtures tagged for these environments. + * When omitted, all fixtures are loaded. + */ + envFilter: external_exports.array(external_exports.string()).optional().describe("Only load fixtures matching these environment tags") +}); +var DevToolsConfigSchema2 = external_exports.object({ + /** Enable hot-module replacement / live reload */ + hotReload: external_exports.boolean().default(true).describe("Enable HMR / live-reload"), + /** Enable request inspector UI for debugging HTTP traffic */ + requestInspector: external_exports.boolean().default(false).describe("Enable request inspector"), + /** Enable an in-browser database explorer */ + dbExplorer: external_exports.boolean().default(false).describe("Enable database explorer UI"), + /** Enable verbose logging across all services */ + verboseLogging: external_exports.boolean().default(true).describe("Enable verbose logging"), + /** Enable OpenAPI / Swagger documentation endpoint */ + apiDocs: external_exports.boolean().default(true).describe("Serve OpenAPI docs at /_dev/docs"), + /** Enable a mail catcher for outbound email (like MailHog) */ + mailCatcher: external_exports.boolean().default(false).describe("Capture outbound emails in dev") +}); +var DevPluginPreset2 = external_exports.enum([ + "minimal", + "standard", + "full" +]).describe("Predefined dev configuration profile"); +var DevPluginConfigSchema2 = external_exports.object({ + /** + * Configuration preset. + * When provided, services and tools are pre-configured for the selected + * profile. Individual `services` and `tools` settings override the preset. + * @default 'standard' + */ + preset: DevPluginPreset2.default("standard").describe("Base configuration preset"), + /** + * Per-service overrides. + * Keys are service names; values configure the dev strategy. + * Only services explicitly listed here override the preset defaults. + */ + services: external_exports.record( + external_exports.string().min(1), + DevServiceOverrideSchema2.omit({ service: true }) + ).optional().describe("Per-service dev overrides keyed by service name"), + /** Fixture / seed data configuration */ + fixtures: DevFixtureConfigSchema2.optional().describe("Fixture data loading configuration"), + /** Developer tooling configuration */ + tools: DevToolsConfigSchema2.optional().describe("Developer tooling settings"), + /** + * Port for the dev-tools UI dashboard. + * Serves a lightweight web dashboard for inspecting services, events, + * and request logs during development. + * @default 4400 + */ + port: external_exports.number().int().min(1).max(65535).default(4400).describe("Port for the dev-tools dashboard"), + /** + * Auto-open the dev-tools dashboard in the default browser on startup. + */ + open: external_exports.boolean().default(false).describe("Auto-open dev dashboard in browser"), + /** + * Seed a default admin user for development. + * When enabled, the dev plugin creates a pre-authenticated admin user + * so that developers can bypass login flows. + */ + seedAdminUser: external_exports.boolean().default(true).describe("Create a default admin user for development"), + /** + * Simulated latency (ms) to add to service calls. + * Helps developers build UIs that handle loading states correctly. + * Set to 0 to disable. + */ + simulatedLatency: external_exports.number().int().min(0).default(0).describe("Artificial latency (ms) added to service calls") +}); +var EventPriority2 = external_exports.enum([ + "critical", + // 0 - Process immediately, block if necessary + "high", + // 1 - Process soon, minimal delay + "normal", + // 2 - Default priority + "low", + // 3 - Process when resources available + "background" + // 4 - Process during idle time +]); +var EVENT_PRIORITY_VALUES = { + critical: 0, + high: 1, + normal: 2, + low: 3, + background: 4 +}; +var EventMetadataSchema2 = external_exports.object({ + source: external_exports.string().describe("Event source (e.g., plugin name, system component)"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when event was created"), + userId: external_exports.string().optional().describe("User who triggered the event"), + tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant systems"), + correlationId: external_exports.string().optional().describe("Correlation ID for event tracing"), + causationId: external_exports.string().optional().describe("ID of the event that caused this event"), + priority: EventPriority2.optional().default("normal").describe("Event priority") +}); +var EventTypeDefinitionSchema2 = external_exports.object({ + name: EventNameSchema4.describe("Event type name (lowercase with dots)"), + version: external_exports.string().default("1.0.0").describe("Event schema version"), + schema: external_exports.unknown().optional().describe("JSON Schema for event payload validation"), + description: external_exports.string().optional().describe("Event type description"), + deprecated: external_exports.boolean().optional().default(false).describe("Whether this event type is deprecated"), + tags: external_exports.array(external_exports.string()).optional().describe("Event type tags") +}); +var EventSchema22 = external_exports.object({ + /** + * Event identifier (for tracking and deduplication) + */ + id: external_exports.string().optional().describe("Unique event identifier"), + /** + * Event name + */ + name: EventNameSchema4.describe("Event name (lowercase with dots, e.g., user.created, order.paid)"), + /** + * Event payload + */ + payload: external_exports.unknown().describe("Event payload schema"), + /** + * Event metadata + */ + metadata: EventMetadataSchema2.describe("Event metadata") +}); +var EventHandlerSchema2 = external_exports.object({ + /** + * Handler identifier + */ + id: external_exports.string().optional().describe("Unique handler identifier"), + /** + * Event name pattern + */ + eventName: external_exports.string().describe("Name of event to handle (supports wildcards like user.*)"), + /** + * Handler function + */ + handler: external_exports.unknown().describe("Handler function"), + /** + * Execution priority + */ + priority: external_exports.number().int().default(0).describe("Execution priority (lower numbers execute first)"), + /** + * Async execution + */ + async: external_exports.boolean().default(true).describe("Execute in background (true) or block (false)"), + /** + * Retry configuration + */ + retry: external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retry attempts"), + backoffMs: external_exports.number().int().positive().default(1e3).describe("Initial backoff delay"), + backoffMultiplier: external_exports.number().positive().default(2).describe("Backoff multiplier") + }).optional().describe("Retry policy for failed handlers"), + /** + * Timeout + */ + timeoutMs: external_exports.number().int().positive().optional().describe("Handler timeout in milliseconds"), + /** + * Filter function + */ + filter: external_exports.unknown().optional().describe("Optional filter to determine if handler should execute") +}); +var EventRouteSchema2 = external_exports.object({ + from: external_exports.string().describe("Source event pattern (supports wildcards, e.g., user.* or *.created)"), + to: external_exports.array(external_exports.string()).describe("Target event names to route to"), + transform: external_exports.unknown().optional().describe("Optional function to transform payload") +}); +var EventPersistenceSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable event persistence"), + retention: external_exports.number().int().positive().describe("Days to retain persisted events"), + filter: external_exports.unknown().optional().describe("Optional filter function to select which events to persist"), + storage: external_exports.enum(["database", "file", "s3", "custom"]).default("database").describe("Storage backend for persisted events") +}); +var EventQueueConfigSchema2 = external_exports.object({ + /** + * Queue name + */ + name: external_exports.string().default("events").describe("Event queue name"), + /** + * Concurrency + */ + concurrency: external_exports.number().int().min(1).default(10).describe("Max concurrent event handlers"), + /** + * Retry policy + */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Max retries for failed events"), + backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy"), + initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay"), + maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Maximum retry delay") + }).optional().describe("Default retry policy for events"), + /** + * Dead letter queue + */ + deadLetterQueue: external_exports.string().optional().describe("Dead letter queue name for failed events"), + /** + * Enable priority processing + */ + priorityEnabled: external_exports.boolean().default(true).describe("Process events based on priority") +}); +var EventReplayConfigSchema2 = external_exports.object({ + /** + * Start timestamp + */ + fromTimestamp: external_exports.string().datetime().describe("Start timestamp for replay (ISO 8601)"), + /** + * End timestamp + */ + toTimestamp: external_exports.string().datetime().optional().describe("End timestamp for replay (ISO 8601)"), + /** + * Event types to replay + */ + eventTypes: external_exports.array(external_exports.string()).optional().describe("Event types to replay (empty = all)"), + /** + * Event filters + */ + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional filters for event selection"), + /** + * Replay speed multiplier + */ + speed: external_exports.number().positive().default(1).describe("Replay speed multiplier (1 = real-time)"), + /** + * Target handlers + */ + targetHandlers: external_exports.array(external_exports.string()).optional().describe("Handler IDs to execute (empty = all)") +}); +var EventSourcingConfigSchema2 = external_exports.object({ + /** + * Enable event sourcing + */ + enabled: external_exports.boolean().default(false).describe("Enable event sourcing"), + /** + * Snapshot interval + */ + snapshotInterval: external_exports.number().int().positive().default(100).describe("Create snapshot every N events"), + /** + * Snapshot retention + */ + snapshotRetention: external_exports.number().int().positive().default(10).describe("Number of snapshots to retain"), + /** + * Event retention + */ + retention: external_exports.number().int().positive().default(365).describe("Days to retain events"), + /** + * Aggregate types + */ + aggregateTypes: external_exports.array(external_exports.string()).optional().describe("Aggregate types to enable event sourcing for"), + /** + * Storage configuration + */ + storage: external_exports.object({ + type: external_exports.enum(["database", "file", "s3", "eventstore"]).default("database").describe("Storage backend"), + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage-specific options") + }).optional().describe("Event store configuration") +}); +var DeadLetterQueueEntrySchema2 = external_exports.object({ + /** + * Entry identifier + */ + id: external_exports.string().describe("Unique entry identifier"), + /** + * Original event + */ + event: EventSchema22.describe("Original event"), + /** + * Failure reason + */ + error: external_exports.object({ + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Error stack trace"), + code: external_exports.string().optional().describe("Error code") + }).describe("Failure details"), + /** + * Retry count + */ + retries: external_exports.number().int().min(0).describe("Number of retry attempts"), + /** + * Timestamps + */ + firstFailedAt: external_exports.string().datetime().describe("When event first failed"), + lastFailedAt: external_exports.string().datetime().describe("When event last failed"), + /** + * Handler that failed + */ + failedHandler: external_exports.string().optional().describe("Handler ID that failed") +}); +var EventLogEntrySchema2 = external_exports.object({ + /** + * Log entry ID + */ + id: external_exports.string().describe("Unique log entry identifier"), + /** + * Event + */ + event: EventSchema22.describe("The event"), + /** + * Status + */ + status: external_exports.enum(["pending", "processing", "completed", "failed"]).describe("Processing status"), + /** + * Handlers executed + */ + handlersExecuted: external_exports.array(external_exports.object({ + handlerId: external_exports.string().describe("Handler identifier"), + status: external_exports.enum(["success", "failed", "timeout"]).describe("Handler execution status"), + durationMs: external_exports.number().int().optional().describe("Execution duration"), + error: external_exports.string().optional().describe("Error message if failed") + })).optional().describe("Handlers that processed this event"), + /** + * Timestamps + */ + receivedAt: external_exports.string().datetime().describe("When event was received"), + processedAt: external_exports.string().datetime().optional().describe("When event was processed"), + /** + * Total duration + */ + totalDurationMs: external_exports.number().int().optional().describe("Total processing time") +}); +var EventWebhookConfigSchema2 = external_exports.object({ + /** + * Webhook identifier + */ + id: external_exports.string().optional().describe("Unique webhook identifier"), + /** + * Event pattern to match + */ + eventPattern: external_exports.string().describe("Event name pattern (supports wildcards)"), + /** + * Target URL + */ + url: external_exports.string().url().describe("Webhook endpoint URL"), + /** + * HTTP method + */ + method: external_exports.enum(["GET", "POST", "PUT", "PATCH"]).default("POST").describe("HTTP method"), + /** + * Headers + */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP headers"), + /** + * Authentication + */ + authentication: external_exports.object({ + type: external_exports.enum(["none", "bearer", "basic", "api-key"]).describe("Auth type"), + credentials: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Auth credentials") + }).optional().describe("Authentication configuration"), + /** + * Retry policy + */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().int().min(0).default(3).describe("Max retry attempts"), + backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential"), + initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay"), + maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Max retry delay") + }).optional().describe("Retry policy"), + /** + * Timeout + */ + timeoutMs: external_exports.number().int().positive().default(3e4).describe("Request timeout in milliseconds"), + /** + * Event transformation + */ + transform: external_exports.unknown().optional().describe("Transform event before sending"), + /** + * Enabled + */ + enabled: external_exports.boolean().default(true).describe("Whether webhook is enabled") +}); +var EventMessageQueueConfigSchema2 = external_exports.object({ + /** + * Provider + */ + provider: external_exports.enum(["kafka", "rabbitmq", "aws-sqs", "redis-pubsub", "google-pubsub", "azure-service-bus"]).describe("Message queue provider"), + /** + * Topic/Queue name + */ + topic: external_exports.string().describe("Topic or queue name"), + /** + * Event pattern + */ + eventPattern: external_exports.string().default("*").describe("Event name pattern to publish (supports wildcards)"), + /** + * Partition key + */ + partitionKey: external_exports.string().optional().describe('JSON path for partition key (e.g., "metadata.tenantId")'), + /** + * Message format + */ + format: external_exports.enum(["json", "avro", "protobuf"]).default("json").describe("Message serialization format"), + /** + * Include metadata + */ + includeMetadata: external_exports.boolean().default(true).describe("Include event metadata in message"), + /** + * Compression + */ + compression: external_exports.enum(["none", "gzip", "snappy", "lz4"]).default("none").describe("Message compression"), + /** + * Batch size + */ + batchSize: external_exports.number().int().min(1).default(1).describe("Batch size for publishing"), + /** + * Flush interval + */ + flushIntervalMs: external_exports.number().int().positive().default(1e3).describe("Flush interval for batching") +}); +var RealTimeNotificationConfigSchema2 = external_exports.object({ + /** + * Enable real-time notifications + */ + enabled: external_exports.boolean().default(true).describe("Enable real-time notifications"), + /** + * Protocol + */ + protocol: external_exports.enum(["websocket", "sse", "long-polling"]).default("websocket").describe("Real-time protocol"), + /** + * Event pattern + */ + eventPattern: external_exports.string().default("*").describe("Event pattern to broadcast"), + /** + * User-specific filtering + */ + userFilter: external_exports.boolean().default(true).describe("Filter events by user"), + /** + * Tenant-specific filtering + */ + tenantFilter: external_exports.boolean().default(true).describe("Filter events by tenant"), + /** + * Channels + */ + channels: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Channel name"), + eventPattern: external_exports.string().describe("Event pattern for channel"), + filter: external_exports.unknown().optional().describe("Additional filter function") + })).optional().describe("Named channels for event broadcasting"), + /** + * Rate limiting + */ + rateLimit: external_exports.object({ + maxEventsPerSecond: external_exports.number().int().positive().describe("Max events per second per client"), + windowMs: external_exports.number().int().positive().default(1e3).describe("Rate limit window") + }).optional().describe("Rate limiting configuration") +}); +var EventBusConfigSchema2 = external_exports.object({ + /** + * Event persistence + */ + persistence: EventPersistenceSchema2.optional().describe("Event persistence configuration"), + /** + * Event queue + */ + queue: EventQueueConfigSchema2.optional().describe("Event queue configuration"), + /** + * Event sourcing + */ + eventSourcing: EventSourcingConfigSchema2.optional().describe("Event sourcing configuration"), + /** + * Event replay + */ + replay: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable event replay capability") + }).optional().describe("Event replay configuration"), + /** + * Webhooks + */ + webhooks: external_exports.array(EventWebhookConfigSchema2).optional().describe("Webhook configurations"), + /** + * Message queue integration + */ + messageQueue: EventMessageQueueConfigSchema2.optional().describe("Message queue integration"), + /** + * Real-time notifications + */ + realtime: RealTimeNotificationConfigSchema2.optional().describe("Real-time notification configuration"), + /** + * Event type definitions + */ + eventTypes: external_exports.array(EventTypeDefinitionSchema2).optional().describe("Event type definitions"), + /** + * Global handlers + */ + handlers: external_exports.array(EventHandlerSchema2).optional().describe("Global event handlers") +}); +var FeatureStrategy2 = external_exports.enum([ + "boolean", + // Simple On/Off + "percentage", + // Gradual rollout (0-100%) + "user_list", + // Specific users + "group", + // Specific groups/roles + "custom" + // Custom constraint/script +]); +var FeatureFlagSchema2 = external_exports.object({ + name: SnakeCaseIdentifierSchema7.describe("Feature key (snake_case)"), + label: external_exports.string().optional().describe("Display label"), + description: external_exports.string().optional(), + /** Default state */ + enabled: external_exports.boolean().default(false).describe("Is globally enabled"), + /** Rollout Strategy */ + strategy: FeatureStrategy2.default("boolean"), + /** Strategy Configuration */ + conditions: external_exports.object({ + percentage: external_exports.number().min(0).max(100).optional(), + users: external_exports.array(external_exports.string()).optional(), + groups: external_exports.array(external_exports.string()).optional(), + expression: external_exports.string().optional().describe("Custom formula expression") + }).optional(), + /** Integration */ + environment: external_exports.enum(["dev", "staging", "prod", "all"]).default("all").describe("Environment validity"), + /** Expiration */ + expiresAt: external_exports.string().datetime().optional().describe("Feature flag expiration date") +}); +var FeatureFlag2 = Object.assign(FeatureFlagSchema2, { + create: (config4) => config4 +}); +var CapabilityConformanceLevelSchema3 = external_exports.enum([ + "full", + // Complete implementation of all protocol features + "partial", + // Subset implementation with specific features listed + "experimental", + // Unstable/preview implementation + "deprecated" + // Still supported but scheduled for removal +]).describe("Level of protocol conformance"); +var ProtocolVersionSchema3 = external_exports.object({ + major: external_exports.number().int().min(0), + minor: external_exports.number().int().min(0), + patch: external_exports.number().int().min(0) +}).describe("Semantic version of the protocol"); +var ProtocolReferenceSchema3 = external_exports.object({ + /** + * Protocol identifier using reverse domain notation. + * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major} + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+protocol\.[a-z][a-z0-9._]*\.v\d+$/).describe("Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)"), + /** + * Human-readable protocol name + */ + label: external_exports.string(), + /** + * Protocol version + */ + version: ProtocolVersionSchema3, + /** + * Detailed protocol specification URL or file reference + */ + specification: external_exports.string().optional().describe("URL or path to protocol specification"), + /** + * Brief description of what this protocol defines + */ + description: external_exports.string().optional() +}); +var ProtocolFeatureSchema3 = external_exports.object({ + name: external_exports.string().describe("Feature identifier within the protocol"), + enabled: external_exports.boolean().default(true), + description: external_exports.string().optional(), + sinceVersion: external_exports.string().optional().describe("Version when this feature was added"), + deprecatedSince: external_exports.string().optional().describe("Version when deprecated") +}); +var PluginCapabilitySchema3 = external_exports.object({ + /** + * The protocol being implemented + */ + protocol: ProtocolReferenceSchema3, + /** + * Conformance level + */ + conformance: CapabilityConformanceLevelSchema3.default("full"), + /** + * Specific features implemented (required if conformance is 'partial') + */ + implementedFeatures: external_exports.array(external_exports.string()).optional().describe("List of implemented feature names"), + /** + * Optional feature flags indicating advanced capabilities + */ + features: external_exports.array(ProtocolFeatureSchema3).optional(), + /** + * Custom metadata for vendor-specific information + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Testing/Certification status + */ + certified: external_exports.boolean().default(false).describe("Has passed official conformance tests"), + certificationDate: external_exports.string().datetime().optional() +}); +var PluginInterfaceSchema3 = external_exports.object({ + /** + * Unique interface identifier + * Format: {plugin-id}.interface.{name} + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+interface\.[a-z][a-z0-9._]+$/).describe("Unique interface identifier"), + /** + * Interface name + */ + name: external_exports.string(), + /** + * Description of what this interface provides + */ + description: external_exports.string().optional(), + /** + * Interface version + */ + version: ProtocolVersionSchema3, + /** + * Methods exposed by this interface + */ + methods: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Method name"), + description: external_exports.string().optional(), + parameters: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string().describe("Type notation (e.g., string, number, User)"), + required: external_exports.boolean().default(true), + description: external_exports.string().optional() + })).optional(), + returnType: external_exports.string().optional().describe("Return value type"), + async: external_exports.boolean().default(false).describe("Whether method returns a Promise") + })), + /** + * Events emitted by this interface + */ + events: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Event name"), + description: external_exports.string().optional(), + payload: external_exports.string().optional().describe("Event payload type") + })).optional(), + /** + * Stability level + */ + stability: external_exports.enum(["stable", "beta", "alpha", "experimental"]).default("stable") +}); +var PluginDependencySchema3 = external_exports.object({ + /** + * Plugin ID using reverse domain notation + */ + pluginId: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Required plugin identifier"), + /** + * Version constraint (supports semver ranges) + * Examples: "1.0.0", "^1.2.3", ">=2.0.0 <3.0.0" + */ + version: external_exports.string().describe("Semantic version constraint"), + /** + * Whether this dependency is optional + */ + optional: external_exports.boolean().default(false), + /** + * Reason for the dependency + */ + reason: external_exports.string().optional(), + /** + * Minimum required capabilities from the dependency + */ + requiredCapabilities: external_exports.array(external_exports.string()).optional().describe("Protocol IDs the dependency must support") +}); +var ExtensionPointSchema3 = external_exports.object({ + /** + * Extension point identifier + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+extension\.[a-z][a-z0-9._]+$/).describe("Unique extension point identifier"), + /** + * Extension point name + */ + name: external_exports.string(), + /** + * Description + */ + description: external_exports.string().optional(), + /** + * Type of extension point + */ + type: external_exports.enum([ + "action", + // Plugins can register executable actions + "hook", + // Plugins can listen to lifecycle events + "widget", + // Plugins can contribute UI widgets + "provider", + // Plugins can provide data/services + "transformer", + // Plugins can transform data + "validator", + // Plugins can validate data + "decorator" + // Plugins can enhance/wrap functionality + ]), + /** + * Expected interface contract for extensions + */ + contract: external_exports.object({ + input: external_exports.string().optional().describe("Input type/schema"), + output: external_exports.string().optional().describe("Output type/schema"), + signature: external_exports.string().optional().describe("Function signature if applicable") + }).optional(), + /** + * Cardinality + */ + cardinality: external_exports.enum(["single", "multiple"]).default("multiple").describe("Whether multiple extensions can register to this point") +}); +var PluginCapabilityManifestSchema3 = external_exports.object({ + /** + * Protocols this plugin implements + */ + implements: external_exports.array(PluginCapabilitySchema3).optional().describe("List of protocols this plugin conforms to"), + /** + * Interfaces this plugin exposes to other plugins + */ + provides: external_exports.array(PluginInterfaceSchema3).optional().describe("Services/APIs this plugin offers to others"), + /** + * Dependencies on other plugins + */ + requires: external_exports.array(PluginDependencySchema3).optional().describe("Required plugins and their capabilities"), + /** + * Extension points this plugin defines + */ + extensionPoints: external_exports.array(ExtensionPointSchema3).optional().describe("Points where other plugins can extend this plugin"), + /** + * Extensions this plugin contributes to other plugins + */ + extensions: external_exports.array(external_exports.object({ + targetPluginId: external_exports.string().describe("Plugin ID being extended"), + extensionPointId: external_exports.string().describe("Extension point identifier"), + implementation: external_exports.string().describe("Path to implementation module"), + priority: external_exports.number().int().default(100).describe("Registration priority (lower = higher priority)") + })).optional().describe("Extensions contributed to other plugins") +}); +var PluginLoadingStrategySchema3 = external_exports.enum([ + "eager", + // Load immediately during bootstrap (critical plugins) + "lazy", + // Load on first use (feature plugins) + "parallel", + // Load in parallel with other plugins + "deferred", + // Load after initial bootstrap complete + "on-demand" + // Load only when explicitly requested +]).describe("Plugin loading strategy"); +var PluginPreloadConfigSchema3 = external_exports.object({ + /** + * Enable preloading for this plugin + */ + enabled: external_exports.boolean().default(false), + /** + * Preload priority (lower = higher priority) + */ + priority: external_exports.number().int().min(0).default(100), + /** + * Resources to preload + */ + resources: external_exports.array(external_exports.enum([ + "metadata", + // Plugin manifest and metadata + "dependencies", + // Plugin dependencies + "assets", + // Static assets (icons, translations) + "code", + // JavaScript code chunks + "services" + // Service definitions + ])).optional(), + /** + * Conditions for preloading + */ + conditions: external_exports.object({ + /** + * Preload only on specific routes + */ + routes: external_exports.array(external_exports.string()).optional(), + /** + * Preload only for specific user roles + */ + roles: external_exports.array(external_exports.string()).optional(), + /** + * Preload based on device type + */ + deviceType: external_exports.array(external_exports.enum(["desktop", "mobile", "tablet"])).optional(), + /** + * Network connection quality threshold + */ + minNetworkSpeed: external_exports.enum(["slow-2g", "2g", "3g", "4g"]).optional() + }).optional() +}).describe("Plugin preloading configuration"); +var PluginCodeSplittingSchema3 = external_exports.object({ + /** + * Enable code splitting for this plugin + */ + enabled: external_exports.boolean().default(true), + /** + * Split strategy + */ + strategy: external_exports.enum([ + "route", + // Split by UI routes + "feature", + // Split by feature modules + "size", + // Split by bundle size threshold + "custom" + // Custom split points defined by plugin + ]).default("feature"), + /** + * Chunk naming strategy + */ + chunkNaming: external_exports.enum(["hashed", "named", "sequential"]).default("hashed"), + /** + * Maximum chunk size in KB + */ + maxChunkSize: external_exports.number().int().min(10).optional().describe("Max chunk size in KB"), + /** + * Shared dependencies optimization + */ + sharedDependencies: external_exports.object({ + enabled: external_exports.boolean().default(true), + /** + * Minimum times a module must be shared before extraction + */ + minChunks: external_exports.number().int().min(1).default(2) + }).optional() +}).describe("Plugin code splitting configuration"); +var PluginDynamicImportSchema3 = external_exports.object({ + /** + * Enable dynamic imports + */ + enabled: external_exports.boolean().default(true), + /** + * Import mode + */ + mode: external_exports.enum([ + "async", + // Asynchronous import (recommended) + "sync", + // Synchronous import (blocking) + "eager", + // Eager evaluation + "lazy" + // Lazy evaluation + ]).default("async"), + /** + * Prefetch strategy + */ + prefetch: external_exports.boolean().default(false).describe("Prefetch module in idle time"), + /** + * Preload strategy + */ + preload: external_exports.boolean().default(false).describe("Preload module in parallel with parent"), + /** + * Webpack magic comments support + */ + webpackChunkName: external_exports.string().optional().describe("Custom chunk name for webpack"), + /** + * Import timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4).describe("Dynamic import timeout (ms)"), + /** + * Retry configuration on import failure + */ + retry: external_exports.object({ + enabled: external_exports.boolean().default(true), + maxAttempts: external_exports.number().int().min(1).max(10).default(3), + backoffMs: external_exports.number().int().min(0).default(1e3).describe("Exponential backoff base delay") + }).optional() +}).describe("Plugin dynamic import configuration"); +var PluginInitializationSchema3 = external_exports.object({ + /** + * Initialization mode + */ + mode: external_exports.enum([ + "sync", + // Synchronous initialization + "async", + // Asynchronous initialization + "parallel", + // Parallel with other plugins + "sequential" + // Must complete before next plugin + ]).default("async"), + /** + * Initialization timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4), + /** + * Startup priority (lower = higher priority, earlier initialization) + */ + priority: external_exports.number().int().min(0).default(100), + /** + * Whether to continue bootstrap if this plugin fails + */ + critical: external_exports.boolean().default(false).describe("If true, kernel bootstrap fails if plugin fails"), + /** + * Retry configuration on initialization failure + */ + retry: external_exports.object({ + enabled: external_exports.boolean().default(false), + maxAttempts: external_exports.number().int().min(1).max(5).default(3), + backoffMs: external_exports.number().int().min(0).default(1e3) + }).optional(), + /** + * Health check interval for monitoring + */ + healthCheckInterval: external_exports.number().int().min(0).optional().describe("Health check interval in ms (0 = disabled)") +}).describe("Plugin initialization configuration"); +var PluginDependencyResolutionSchema3 = external_exports.object({ + /** + * Dependency resolution strategy + */ + strategy: external_exports.enum([ + "strict", + // Exact version match required + "compatible", + // Semver compatible versions (^) + "latest", + // Always use latest compatible + "pinned" + // Lock to specific version + ]).default("compatible"), + /** + * Peer dependency handling + */ + peerDependencies: external_exports.object({ + /** + * Whether to resolve peer dependencies + */ + resolve: external_exports.boolean().default(true), + /** + * Action on missing peer dependency + */ + onMissing: external_exports.enum(["error", "warn", "ignore"]).default("warn"), + /** + * Action on peer version mismatch + */ + onMismatch: external_exports.enum(["error", "warn", "ignore"]).default("warn") + }).optional(), + /** + * Optional dependency handling + */ + optionalDependencies: external_exports.object({ + /** + * Whether to attempt loading optional dependencies + */ + load: external_exports.boolean().default(true), + /** + * Action on optional dependency load failure + */ + onFailure: external_exports.enum(["warn", "ignore"]).default("warn") + }).optional(), + /** + * Conflict resolution + */ + conflictResolution: external_exports.enum([ + "fail", + // Fail on any version conflict + "latest", + // Use latest version + "oldest", + // Use oldest version + "manual" + // Require manual resolution + ]).default("latest"), + /** + * Circular dependency handling + */ + circularDependencies: external_exports.enum([ + "error", + // Throw error on circular dependency + "warn", + // Warn but continue + "allow" + // Allow circular dependencies + ]).default("warn") +}).describe("Plugin dependency resolution configuration"); +var PluginHotReloadSchema3 = external_exports.object({ + /** + * Enable hot reload + */ + enabled: external_exports.boolean().default(false), + /** + * Target environment for hot reload behavior + */ + environment: external_exports.enum([ + "development", + // Fast reload with relaxed safety (file watchers, no health validation) + "staging", + // Production-like reload with validation but relaxed rollback + "production" + // Full safety: health validation, rollback, connection draining + ]).default("development").describe("Target environment controlling safety level"), + /** + * Hot reload strategy + */ + strategy: external_exports.enum([ + "full", + // Full plugin reload (destroy and reinitialize) + "partial", + // Partial reload (update changed modules only) + "state-preserve" + // Preserve plugin state during reload + ]).default("full"), + /** + * Files to watch for changes + */ + watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to watch"), + /** + * Files to ignore + */ + ignorePatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to ignore"), + /** + * Debounce delay in milliseconds + */ + debounceMs: external_exports.number().int().min(0).default(300), + /** + * Whether to preserve state during reload + */ + preserveState: external_exports.boolean().default(false), + /** + * State serialization + */ + stateSerialization: external_exports.object({ + enabled: external_exports.boolean().default(false), + /** + * Path to state serialization handler + */ + handler: external_exports.string().optional() + }).optional(), + /** + * Hooks for hot reload lifecycle + */ + hooks: external_exports.object({ + beforeReload: external_exports.string().optional().describe("Function to call before reload"), + afterReload: external_exports.string().optional().describe("Function to call after reload"), + onError: external_exports.string().optional().describe("Function to call on reload error") + }).optional(), + /** + * Production safety configuration + * Applied when environment is 'staging' or 'production' + */ + productionSafety: external_exports.object({ + /** + * Validate plugin health before completing reload + */ + healthValidation: external_exports.boolean().default(true).describe("Run health checks after reload before accepting traffic"), + /** + * Automatically rollback to previous version on reload failure + */ + rollbackOnFailure: external_exports.boolean().default(true).describe("Auto-rollback if reloaded plugin fails health check"), + /** + * Maximum time to wait for health validation after reload (ms) + */ + healthTimeout: external_exports.number().int().min(1e3).default(3e4).describe("Health check timeout after reload in ms"), + /** + * Drain active connections before reload + */ + drainConnections: external_exports.boolean().default(true).describe("Gracefully drain active requests before reloading"), + /** + * Maximum time to wait for connection draining (ms) + */ + drainTimeout: external_exports.number().int().min(0).default(15e3).describe("Max wait time for connection draining in ms"), + /** + * Maximum number of concurrent plugin reloads + */ + maxConcurrentReloads: external_exports.number().int().min(1).default(1).describe("Limit concurrent reloads to prevent system instability"), + /** + * Minimum interval between reloads of the same plugin (ms) + */ + minReloadInterval: external_exports.number().int().min(1e3).default(5e3).describe("Cooldown period between reloads of the same plugin") + }).optional() +}).describe("Plugin hot reload configuration"); +var PluginCachingSchema3 = external_exports.object({ + /** + * Enable caching + */ + enabled: external_exports.boolean().default(true), + /** + * Cache storage type + */ + storage: external_exports.enum([ + "memory", + // In-memory cache (fastest, not persistent) + "disk", + // Disk cache (persistent) + "indexeddb", + // Browser IndexedDB (persistent, browser only) + "hybrid" + // Memory + Disk hybrid + ]).default("memory"), + /** + * Cache key strategy + */ + keyStrategy: external_exports.enum([ + "version", + // Cache by plugin version + "hash", + // Cache by content hash + "timestamp" + // Cache by last modified timestamp + ]).default("version"), + /** + * Cache TTL in seconds + */ + ttl: external_exports.number().int().min(0).optional().describe("Time to live in seconds (0 = infinite)"), + /** + * Maximum cache size in MB + */ + maxSize: external_exports.number().int().min(1).optional().describe("Max cache size in MB"), + /** + * Cache invalidation triggers + */ + invalidateOn: external_exports.array(external_exports.enum([ + "version-change", + "dependency-change", + "manual", + "error" + ])).optional(), + /** + * Compression + */ + compression: external_exports.object({ + enabled: external_exports.boolean().default(false), + algorithm: external_exports.enum(["gzip", "brotli", "deflate"]).default("gzip") + }).optional() +}).describe("Plugin caching configuration"); +var PluginSandboxingSchema3 = external_exports.object({ + /** + * Enable sandboxing + */ + enabled: external_exports.boolean().default(false), + /** + * Isolation scope - which plugins are subject to sandboxing + */ + scope: external_exports.enum([ + "automation-only", + // Sandbox automation/scripting plugins only (current behavior) + "untrusted-only", + // Sandbox plugins below a trust threshold + "all-plugins" + // Sandbox all plugins (maximum isolation) + ]).default("automation-only").describe("Which plugins are subject to isolation"), + /** + * Sandbox isolation level + */ + isolationLevel: external_exports.enum([ + "none", + // No isolation + "process", + // Separate process (Node.js worker threads) + "vm", + // VM context isolation + "iframe", + // iframe isolation (browser) + "web-worker" + // Web Worker (browser) + ]).default("none"), + /** + * Allowed capabilities + */ + allowedCapabilities: external_exports.array(external_exports.string()).optional().describe("List of allowed capability IDs"), + /** + * Resource quotas + */ + resourceQuotas: external_exports.object({ + /** + * Maximum memory usage in MB + */ + maxMemoryMB: external_exports.number().int().min(1).optional(), + /** + * Maximum CPU time in milliseconds + */ + maxCpuTimeMs: external_exports.number().int().min(100).optional(), + /** + * Maximum number of file descriptors + */ + maxFileDescriptors: external_exports.number().int().min(1).optional(), + /** + * Maximum network bandwidth in KB/s + */ + maxNetworkKBps: external_exports.number().int().min(1).optional() + }).optional(), + /** + * Permissions + */ + permissions: external_exports.object({ + /** + * Allowed API access + */ + allowedAPIs: external_exports.array(external_exports.string()).optional(), + /** + * Allowed file system paths + */ + allowedPaths: external_exports.array(external_exports.string()).optional(), + /** + * Allowed network endpoints + */ + allowedEndpoints: external_exports.array(external_exports.string()).optional(), + /** + * Allowed environment variables + */ + allowedEnvVars: external_exports.array(external_exports.string()).optional() + }).optional(), + /** + * Inter-Plugin Communication (IPC) configuration + * Enables isolated plugins to communicate with the kernel and other plugins + */ + ipc: external_exports.object({ + /** + * Enable IPC for sandboxed plugins + */ + enabled: external_exports.boolean().default(true).describe("Allow sandboxed plugins to communicate via IPC"), + /** + * IPC transport mechanism + */ + transport: external_exports.enum([ + "message-port", + // MessagePort (worker threads / Web Workers) + "unix-socket", + // Unix domain sockets (process isolation) + "tcp", + // TCP sockets (container isolation) + "memory" + // Shared memory channel (in-process VM) + ]).default("message-port").describe("IPC transport for cross-boundary communication"), + /** + * Maximum message size in bytes + */ + maxMessageSize: external_exports.number().int().min(1024).default(1048576).describe("Maximum IPC message size in bytes (default 1MB)"), + /** + * Message timeout in milliseconds + */ + timeout: external_exports.number().int().min(100).default(3e4).describe("IPC message response timeout in ms"), + /** + * Allowed service calls through IPC + */ + allowedServices: external_exports.array(external_exports.string()).optional().describe("Service names the sandboxed plugin may invoke via IPC") + }).optional() +}).describe("Plugin sandboxing configuration"); +var PluginPerformanceMonitoringSchema3 = external_exports.object({ + /** + * Enable performance monitoring + */ + enabled: external_exports.boolean().default(false), + /** + * Metrics to collect + */ + metrics: external_exports.array(external_exports.enum([ + "load-time", + "init-time", + "memory-usage", + "cpu-usage", + "api-calls", + "error-rate", + "cache-hit-rate" + ])).optional(), + /** + * Sampling rate (0-1, where 1 = 100%) + */ + samplingRate: external_exports.number().min(0).max(1).default(1), + /** + * Reporting interval in seconds + */ + reportingInterval: external_exports.number().int().min(1).default(60), + /** + * Performance budget thresholds + */ + budgets: external_exports.object({ + /** + * Maximum load time in milliseconds + */ + maxLoadTimeMs: external_exports.number().int().min(0).optional(), + /** + * Maximum init time in milliseconds + */ + maxInitTimeMs: external_exports.number().int().min(0).optional(), + /** + * Maximum memory usage in MB + */ + maxMemoryMB: external_exports.number().int().min(0).optional() + }).optional(), + /** + * Action on budget violation + */ + onBudgetViolation: external_exports.enum(["warn", "error", "ignore"]).default("warn") +}).describe("Plugin performance monitoring configuration"); +var PluginLoadingConfigSchema3 = external_exports.object({ + /** + * Loading strategy + */ + strategy: PluginLoadingStrategySchema3.default("lazy"), + /** + * Preloading configuration + */ + preload: PluginPreloadConfigSchema3.optional(), + /** + * Code splitting configuration + */ + codeSplitting: PluginCodeSplittingSchema3.optional(), + /** + * Dynamic import configuration + */ + dynamicImport: PluginDynamicImportSchema3.optional(), + /** + * Initialization configuration + */ + initialization: PluginInitializationSchema3.optional(), + /** + * Dependency resolution configuration + */ + dependencyResolution: PluginDependencyResolutionSchema3.optional(), + /** + * Hot reload configuration (development and production) + */ + hotReload: PluginHotReloadSchema3.optional(), + /** + * Caching configuration + */ + caching: PluginCachingSchema3.optional(), + /** + * Sandboxing configuration + */ + sandboxing: PluginSandboxingSchema3.optional(), + /** + * Performance monitoring + */ + monitoring: PluginPerformanceMonitoringSchema3.optional() +}).describe("Complete plugin loading configuration"); +var PluginLoadingEventSchema2 = external_exports.object({ + /** + * Event type + */ + type: external_exports.enum([ + "load-started", + "load-completed", + "load-failed", + "init-started", + "init-completed", + "init-failed", + "preload-started", + "preload-completed", + "cache-hit", + "cache-miss", + "hot-reload", + "dynamic-load", + // Plugin loaded at runtime + "dynamic-unload", + // Plugin unloaded at runtime + "dynamic-discover" + // Plugin discovered via registry + ]), + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Timestamp + */ + timestamp: external_exports.number().int().min(0), + /** + * Duration in milliseconds + */ + durationMs: external_exports.number().int().min(0).optional(), + /** + * Additional metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Error if event represents a failure + */ + error: external_exports.object({ + message: external_exports.string(), + code: external_exports.string().optional(), + stack: external_exports.string().optional() + }).optional() +}).describe("Plugin loading lifecycle event"); +var PluginLoadingStateSchema2 = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Current state + */ + state: external_exports.enum([ + "pending", + // Not yet loaded + "loading", + // Currently loading + "loaded", + // Code loaded, not initialized + "initializing", + // Currently initializing + "ready", + // Fully initialized and ready + "failed", + // Failed to load or initialize + "reloading", + // Hot reloading in progress + "unloading", + // Being unloaded at runtime + "unloaded" + // Successfully unloaded (dynamic loading) + ]), + /** + * Load progress (0-100) + */ + progress: external_exports.number().min(0).max(100).default(0), + /** + * Loading start time + */ + startedAt: external_exports.number().int().min(0).optional(), + /** + * Loading completion time + */ + completedAt: external_exports.number().int().min(0).optional(), + /** + * Last error + */ + lastError: external_exports.string().optional(), + /** + * Retry count + */ + retryCount: external_exports.number().int().min(0).default(0) +}).describe("Plugin loading state"); +var PluginContextSchema2 = external_exports.object({ + ql: external_exports.object({ + object: external_exports.function().describe("Get object handle for method chaining"), + query: external_exports.function().describe("Execute a query") + }).passthrough().describe("ObjectQL Engine Interface"), + os: external_exports.object({ + getCurrentUser: external_exports.function().describe("Get the current authenticated user"), + getConfig: external_exports.function().describe("Get platform configuration") + }).passthrough().describe("ObjectStack Kernel Interface"), + logger: external_exports.object({ + debug: external_exports.function().describe("Log debug message"), + info: external_exports.function().describe("Log info message"), + warn: external_exports.function().describe("Log warning message"), + error: external_exports.function().describe("Log error message") + }).passthrough().describe("Logger Interface"), + storage: external_exports.object({ + get: external_exports.function().describe("Get a value from storage"), + set: external_exports.function().describe("Set a value in storage"), + delete: external_exports.function().describe("Delete a value from storage") + }).passthrough().describe("Storage Interface"), + i18n: external_exports.object({ + t: external_exports.function().describe("Translate a key"), + getLocale: external_exports.function().describe("Get current locale") + }).passthrough().describe("Internationalization Interface"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()), + events: external_exports.record(external_exports.string(), external_exports.unknown()), + app: external_exports.object({ + router: external_exports.object({ + get: external_exports.function().describe("Register GET route handler"), + post: external_exports.function().describe("Register POST route handler"), + use: external_exports.function().describe("Register middleware") + }).passthrough() + }).passthrough().describe("App Framework Interface"), + drivers: external_exports.object({ + register: external_exports.function().describe("Register a driver") + }).passthrough().describe("Driver Registry") +}); +var UpgradeContextSchema2 = external_exports.object({ + /** Version before upgrade */ + previousVersion: external_exports.string().describe("Version before upgrade"), + /** Version after upgrade */ + newVersion: external_exports.string().describe("Version after upgrade"), + /** Whether this is a major version bump */ + isMajorUpgrade: external_exports.boolean().describe("Whether this is a major version bump"), + /** Metadata snapshot before upgrade (for migration logic) */ + previousMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Metadata snapshot before upgrade") +}).describe("Version migration context for onUpgrade hook"); +var PluginLifecycleSchema3 = external_exports.object({ + onInstall: external_exports.function().optional().describe("Called when plugin is installed"), + onEnable: external_exports.function().optional().describe("Called when plugin is enabled"), + onDisable: external_exports.function().optional().describe("Called when plugin is disabled"), + onUninstall: external_exports.function().optional().describe("Called when plugin is uninstalled"), + onUpgrade: external_exports.function().optional().describe("Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade") +}); +var CORE_PLUGIN_TYPES3 = [ + "ui", + // Frontend: Serves static assets/SPA (e.g. Console, Studio) + "driver", + // Connectivity: Database or Storage adapters (e.g. SQL, S3) + "server", + // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL) + "app", + // Business: Vertical Solution Bundle (Metadata + Logic) + "theme", + // Appearance: UI Overrides & CSS Variables + "agent", + // AI: Autonomous Agent & Tool Definitions + "objectql" + // Core: ObjectQL Engine Data Provider +]; +var PluginSchema2 = PluginLifecycleSchema3.extend({ + id: external_exports.string().min(1).optional().describe("Unique Plugin ID (e.g. com.example.crm)"), + type: external_exports.enum([ + "standard", + // Default: General purpose backend logic (Service, Hook, etc.) + ...CORE_PLUGIN_TYPES3 + ]).default("standard").optional().describe("Plugin Type categorization for runtime behavior"), + staticPath: external_exports.string().optional().describe('Absolute path to static assets (Required for type="ui-plugin")'), + slug: external_exports.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type="ui-plugin")'), + default: external_exports.boolean().optional().describe('Serve at root path (Only one "ui-plugin" can be default)'), + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic Version"), + description: external_exports.string().optional(), + author: external_exports.string().optional(), + homepage: external_exports.string().url().optional() +}); +var ManifestSchema3 = external_exports.object({ + /** + * Unique package identifier using reverse domain notation. + * Must be unique across the entire ecosystem. + * + * @example "com.steedos.crm" + * @example "org.apache.superset" + */ + id: external_exports.string().describe("Unique package identifier (reverse domain style)"), + /** + * Short namespace identifier for metadata scoping. + * Used as a prefix for objects and other metadata to prevent naming collisions + * across packages from different vendors. + * + * Rules: + * - 2-20 characters, lowercase letters, digits, and underscores only. + * - Must be unique within a running instance. + * - Platform-reserved namespaces (no prefix applied): "base", "system". + * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator). + * + * @example "crm" → objects become crm__account, crm__deal + * @example "todo" → objects become todo__task + * @example "base" → objects keep short name (platform reserved) + */ + namespace: external_exports.string().regex(/^[a-z][a-z0-9_]{1,19}$/, "Namespace must be 2-20 chars, lowercase alphanumeric + underscore").optional().describe('Short namespace identifier for metadata scoping (e.g. "crm", "todo")'), + /** + * Package version following semantic versioning (major.minor.patch). + * + * @example "1.0.0" + * @example "2.1.0-beta.1" + */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Package version (semantic versioning)"), + /** + * Type of the package in the ObjectStack ecosystem. + * - plugin: General-purpose functionality extension (Runtime: standard) + * - app: Business application package + * - driver: Connectivity adapter + * - server: Protocol gateway (Hono, GraphQL) + * - ui: Frontend package (Static/SPA) + * - theme: UI Theme + * - agent: AI Agent + * - module: Reusable code library/shared module + * - objectql: Core engine + * - adapter: Host adapter (Express, Fastify) + */ + type: external_exports.enum([ + "plugin", + ...CORE_PLUGIN_TYPES3, + "module", + "gateway", + // Deprecated: use 'server' + "adapter" + ]).describe("Type of package"), + /** + * Human-readable name of the package. + * Displayed in the UI for users. + * + * @example "Project Management" + */ + name: external_exports.string().describe("Human-readable package name"), + /** + * Brief description of the package functionality. + * Displayed in the marketplace and plugin manager. + */ + description: external_exports.string().optional().describe("Package description"), + /** + * Array of permission strings that the package requires. + * These form the "Scope" requested by the package at installation. + * + * @example ["system.user.read", "system.data.write"] + */ + permissions: external_exports.array(external_exports.string()).optional().describe("Array of required permission strings"), + /** + * Glob patterns specifying ObjectQL schemas files. + * Matches `*.object.yml` or `*.object.ts` files to load business objects. + * + * @example ["./src/objects/*.object.yml"] + */ + objects: external_exports.array(external_exports.string()).optional().describe("Glob patterns for ObjectQL schemas files"), + /** + * Defines system level DataSources. + * Matches `*.datasource.yml` files. + * + * @example ["./src/datasources/*.datasource.mongo.yml"] + */ + datasources: external_exports.array(external_exports.string()).optional().describe("Glob patterns for Datasource definitions"), + /** + * Package Dependencies. + * Map of package IDs to version requirements. + * + * @example { "@steedos/plugin-auth": "^2.0.0" } + */ + dependencies: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Package dependencies"), + /** + * Plugin Configuration Schema. + * Defines the settings this plugin exposes to the user via UI/ENV. + * Uses a simplified JSON Schema format. + * + * @example + * { + * "title": "Stripe Config", + * "properties": { + * "apiKey": { "type": "string", "secret": true }, + * "currency": { "type": "string", "default": "USD" } + * } + * } + */ + configuration: external_exports.object({ + title: external_exports.string().optional(), + properties: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["string", "number", "boolean", "array", "object"]).describe("Data type of the setting"), + default: external_exports.unknown().optional().describe("Default value"), + description: external_exports.string().optional().describe("Tooltip description"), + required: external_exports.boolean().optional().describe("Is this setting required?"), + secret: external_exports.boolean().optional().describe("If true, value is encrypted/masked (e.g. API Keys)"), + enum: external_exports.array(external_exports.string()).optional().describe("Allowed values for select inputs") + })).describe("Map of configuration keys to their definitions") + }).optional().describe("Plugin configuration settings"), + /** + * Contribution Points (VS Code Style). + * formalized way to extend the platform capabilities. + */ + contributes: external_exports.object({ + /** + * Register new Metadata Kinds (CRDs). + * Enables the system to parse and validate new file types. + * Example: Registering a BI plugin to handle *.report.ts + */ + kinds: external_exports.array(external_exports.object({ + id: external_exports.string().describe('The generic identifier of the kind (e.g., "sys.bi.report")'), + globs: external_exports.array(external_exports.string()).describe('File patterns to watch (e.g., ["**/*.report.ts"])'), + description: external_exports.string().optional().describe("Description of what this kind represents") + })).optional().describe("New Metadata Types to recognize"), + /** + * Register System Hooks. + * Declares that this plugin listens to specific system events. + */ + events: external_exports.array(external_exports.string()).optional().describe("Events this plugin listens to"), + /** + * Register UI Menus. + */ + menus: external_exports.record(external_exports.string(), external_exports.array(external_exports.object({ + id: external_exports.string(), + label: external_exports.string(), + command: external_exports.string().optional() + }))).optional().describe("UI Menu contributions"), + /** + * Register Custom Themes. + */ + themes: external_exports.array(external_exports.object({ + id: external_exports.string(), + label: external_exports.string(), + path: external_exports.string() + })).optional().describe("Theme contributions"), + /** + * Register Translations. + * Path to translation files (e.g. "locales/en.json"). + */ + translations: external_exports.array(external_exports.object({ + locale: external_exports.string(), + path: external_exports.string() + })).optional().describe("Translation resources"), + /** + * Register Server Actions. + * Invocable functions exposed to Flows or API. + */ + actions: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Unique action name"), + label: external_exports.string().optional(), + description: external_exports.string().optional(), + input: external_exports.unknown().optional().describe("Input validation schema"), + output: external_exports.unknown().optional().describe("Output schema") + })).optional().describe("Exposed server actions"), + /** + * Register Storage Drivers. + * Enables connecting to new types of datasources. + */ + drivers: external_exports.array(external_exports.object({ + id: external_exports.string().describe('Driver unique identifier (e.g. "postgres", "mongo")'), + label: external_exports.string().describe("Human readable name"), + description: external_exports.string().optional() + })).optional().describe("Driver contributions"), + /** + * Register Custom Field Types. + * Extends the data model with new widget types. + */ + fieldTypes: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Unique field type name (e.g. "vector")'), + label: external_exports.string().describe("Display label"), + description: external_exports.string().optional() + })).optional().describe("Field Type contributions"), + /** + * Register Custom Query Operators/Functions. + * Extends ObjectQL with new functions (e.g. distance()). + */ + functions: external_exports.array(external_exports.object({ + name: external_exports.string().describe('Function name (e.g. "distance")'), + description: external_exports.string().optional(), + args: external_exports.array(external_exports.string()).optional().describe("Argument types"), + returnType: external_exports.string().optional() + })).optional().describe("Query Function contributions"), + /** + * Register API Route Namespaces. + * Declares the API endpoints this plugin provides to the HttpDispatcher. + * The kernel routes matching prefixes to this plugin's handler. + * + * @example + * routes: [ + * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] } + * ] + */ + routes: external_exports.array(external_exports.object({ + /** URL path prefix (e.g. "/api/v1/ai") */ + prefix: external_exports.string().regex(/^\//).describe("API path prefix"), + /** Service name this plugin provides */ + service: external_exports.string().describe("Service name this plugin provides"), + /** Protocol method names implemented */ + methods: external_exports.array(external_exports.string()).optional().describe('Protocol method names implemented (e.g. ["aiNlq", "aiChat"])') + })).optional().describe("API route contributions to HttpDispatcher"), + /** + * Register CLI Commands. + * Allows plugins to extend the ObjectStack CLI with custom commands. + * Each command entry declares metadata; the actual Commander.js command + * is resolved at runtime by importing the plugin's module. + * + * The plugin package must export a `commands` array of Commander.js `Command` instances + * from its main entry point or from the path specified in `module`. + * + * @example + * ```yaml + * commands: + * - name: marketplace + * description: "Manage marketplace apps" + * module: "./cli" # optional, defaults to package main + * - name: deploy + * description: "Deploy to cloud" + * ``` + */ + commands: external_exports.array(external_exports.object({ + /** CLI command name (e.g., "marketplace", "deploy"). Must be a valid CLI identifier. */ + name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), + /** Brief description shown in `os --help` */ + description: external_exports.string().optional().describe("Command description for help text"), + /** + * Optional module path (relative to package root) that exports the Commander.js commands. + * If omitted, the CLI will import from the package's main entry point. + * The module must export a `commands` array of Commander.js `Command` instances, + * or a single `Command` instance as default export. + */ + module: external_exports.string().optional().describe("Module path exporting Commander.js commands") + })).optional().describe("CLI command contributions") + }).optional().describe("Platform contributions"), + /** + * Initial data seeding configuration. + * Defines default records to be inserted when the package is installed. + * + * Uses the standard DatasetSchema which supports idempotent upsert via + * `externalId`, environment scoping via `env`, and multiple conflict + * resolution modes. + * + * @deprecated Prefer using the top-level `data` field on the Stack Definition + * (defineStack({ data: [...] })) for better visibility and metadata registration. + * This field is retained for backward compatibility with manifest-only packages. + */ + data: external_exports.array(DatasetSchema4).optional().describe("Initial seed data (prefer top-level data field)"), + /** + * Plugin Capability Manifest. + * Declares protocols implemented, interfaces provided, dependencies, and extension points. + * This enables plugin interoperability and automatic discovery. + */ + capabilities: PluginCapabilityManifestSchema3.optional().describe("Plugin capability declarations for interoperability"), + /** + * Extension points contributed by this package. + * Allows packages to extend UI components, add functionality, etc. + */ + extensions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Extension points and contributions"), + /** + * Plugin Loading Configuration. + * Configures how the plugin is loaded, initialized, and managed at runtime. + * Includes strategies for lazy loading, code splitting, caching, and hot reload. + */ + loading: PluginLoadingConfigSchema3.optional().describe("Plugin loading and runtime behavior configuration"), + /** + * Platform Compatibility Requirements. + * Specifies the minimum ObjectStack platform version required to run this package. + * Used at install time to prevent incompatible packages from being installed. + * + * @example + * ```yaml + * engine: + * objectstack: ">=3.0.0" + * ``` + */ + engine: external_exports.object({ + /** ObjectStack platform version requirement (SemVer range) */ + objectstack: external_exports.string().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe('ObjectStack platform version requirement (SemVer range, e.g. ">=3.0.0")') + }).optional().describe("Platform compatibility requirements") +}); +var CustomizationOriginSchema2 = external_exports.enum([ + "package", + // Delivered by a plugin package (system layer, read-only) + "admin", + // Created/modified by platform admin via UI + "user", + // Created/modified by end user via UI + "migration", + // Created during data migration + "api" + // Created via API +]); +var FieldChangeSchema3 = external_exports.object({ + /** JSON path to the changed field (e.g. "fields.status.label") */ + path: external_exports.string().describe("JSON path to the changed field"), + /** Original value from the package (for diff/rollback) */ + originalValue: external_exports.unknown().optional().describe("Original value from the package"), + /** Current customized value */ + currentValue: external_exports.unknown().describe("Current customized value"), + /** Who made this change */ + changedBy: external_exports.string().optional().describe("User or admin who made this change"), + /** When this change was made */ + changedAt: external_exports.string().datetime().optional().describe("Timestamp of the change") +}); +var MetadataOverlaySchema3 = external_exports.object({ + /** Primary key */ + id: external_exports.string().describe("Overlay record ID (UUID)"), + /** The metadata type being customized (e.g. "object", "view", "flow") */ + baseType: external_exports.string().describe("Metadata type being customized"), + /** The metadata name being customized (e.g. "crm__account") */ + baseName: external_exports.string().describe("Metadata name being customized"), + /** Package that owns the base metadata (null for platform-created metadata) */ + packageId: external_exports.string().optional().describe("Package ID that delivered the base metadata"), + /** Package version when the customization was made (for upgrade diffing) */ + packageVersion: external_exports.string().optional().describe("Package version when overlay was created"), + /** Customization scope */ + scope: external_exports.enum(["platform", "user"]).default("platform").describe("Customization scope (platform=admin, user=personal)"), + /** Tenant ID for multi-tenant isolation */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** Owner user ID (for user-scope overlays) */ + owner: external_exports.string().optional().describe("Owner user ID for user-scope overlays"), + /** + * The overlay payload. + * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396). + * - To modify a field: include the field with its new value + * - To delete a field: set its value to null + * - Omitted fields remain unchanged from base + */ + patch: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Merge Patch payload (changed fields only)"), + /** + * Detailed change tracking for each modified field. + * Enables field-level conflict detection during upgrades. + */ + changes: external_exports.array(FieldChangeSchema3).optional().describe("Field-level change tracking for conflict detection"), + /** Whether this overlay is currently active */ + active: external_exports.boolean().default(true).describe("Whether this overlay is active"), + /** Audit timestamps */ + createdAt: external_exports.string().datetime().optional(), + createdBy: external_exports.string().optional(), + updatedAt: external_exports.string().datetime().optional(), + updatedBy: external_exports.string().optional() +}); +var MergeConflictSchema3 = external_exports.object({ + /** JSON path to the conflicting field */ + path: external_exports.string().describe("JSON path to the conflicting field"), + /** Value in the old package version */ + baseValue: external_exports.unknown().describe("Value in the old package version"), + /** Value in the new package version */ + incomingValue: external_exports.unknown().describe("Value in the new package version"), + /** Customer's customized value */ + customValue: external_exports.unknown().describe("Customer customized value"), + /** Suggested resolution strategy */ + suggestedResolution: external_exports.enum([ + "keep-custom", + // Keep customer's customization + "accept-incoming", + // Accept package update + "manual" + // Requires manual resolution + ]).describe("Suggested resolution strategy"), + /** Reason for the suggested resolution */ + reason: external_exports.string().optional().describe("Explanation for the suggested resolution") +}); +var MergeStrategyConfigSchema3 = external_exports.object({ + /** Default strategy when no field-level rule matches */ + defaultStrategy: external_exports.enum([ + "keep-custom", + // Preserve all customer customizations (safe) + "accept-incoming", + // Accept all package updates (overwrite) + "three-way-merge" + // Intelligent 3-way merge with conflict detection + ]).default("three-way-merge").describe("Default merge strategy"), + /** + * Field paths that should always accept incoming package updates. + * Use for fields that the package vendor considers "owned" and should not be customized. + * @example ["fields.*.type", "triggers.*"] + */ + alwaysAcceptIncoming: external_exports.array(external_exports.string()).optional().describe("Field paths that always accept package updates"), + /** + * Field paths where customer customizations always win. + * Use for UI-facing fields like labels, descriptions, help text. + * @example ["fields.*.label", "fields.*.helpText", "description"] + */ + alwaysKeepCustom: external_exports.array(external_exports.string()).optional().describe("Field paths where customer customizations always win"), + /** Whether to automatically resolve non-conflicting changes */ + autoResolveNonConflicting: external_exports.boolean().default(true).describe("Auto-resolve changes that do not conflict") +}); +var MergeResultSchema2 = external_exports.object({ + /** Whether the merge completed successfully (no unresolved conflicts) */ + success: external_exports.boolean().describe("Whether merge completed without unresolved conflicts"), + /** The merged metadata payload */ + mergedMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Merged metadata result"), + /** Updated overlay with remaining customizations */ + updatedOverlay: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated overlay after merge"), + /** List of conflicts that require manual resolution */ + conflicts: external_exports.array(MergeConflictSchema3).optional().describe("Unresolved merge conflicts"), + /** Summary of automatically resolved changes */ + autoResolved: external_exports.array(external_exports.object({ + path: external_exports.string(), + resolution: external_exports.string(), + description: external_exports.string().optional() + })).optional().describe("Summary of auto-resolved changes"), + /** Statistics */ + stats: external_exports.object({ + totalFields: external_exports.number().int().min(0).describe("Total fields evaluated"), + unchanged: external_exports.number().int().min(0).describe("Fields with no changes"), + autoResolved: external_exports.number().int().min(0).describe("Fields auto-resolved"), + conflicts: external_exports.number().int().min(0).describe("Fields with conflicts") + }).optional() +}); +var CustomizationPolicySchema3 = external_exports.object({ + /** Metadata type this policy applies to */ + metadataType: external_exports.string().describe('Metadata type (e.g. "object", "view")'), + /** Whether customization is allowed at all for this type */ + allowCustomization: external_exports.boolean().default(true), + /** + * Field paths that are locked (cannot be customized). + * @example ["name", "type", "fields.*.type"] + */ + lockedFields: external_exports.array(external_exports.string()).optional().describe("Field paths that cannot be customized"), + /** + * Field paths that are customizable. + * If specified, only these fields can be customized (whitelist mode). + * @example ["label", "description", "fields.*.label", "fields.*.helpText"] + */ + customizableFields: external_exports.array(external_exports.string()).optional().describe("Field paths that can be customized (whitelist)"), + /** + * Whether users can add new fields to package objects. + * When true, admins can extend package objects with custom fields. + */ + allowAddFields: external_exports.boolean().default(true).describe("Whether admins can add new fields to package objects"), + /** + * Whether users can delete package-delivered fields. + * Typically false — fields can only be hidden, not deleted. + */ + allowDeleteFields: external_exports.boolean().default(false).describe("Whether admins can delete package-delivered fields") +}); +var MetadataFormatSchema32 = external_exports.enum(["json", "yaml", "typescript", "javascript"]); +var MetadataStatsSchema22 = external_exports.object({ + /** + * Size of the metadata file in bytes + */ + size: external_exports.number().int().min(0).describe("File size in bytes"), + /** + * Last modification timestamp + */ + modifiedAt: external_exports.string().datetime().describe("Last modified date"), + /** + * ETag for cache validation + * Used for conditional requests (If-None-Match header) + */ + etag: external_exports.string().describe("Entity tag for cache validation"), + /** + * Serialization format + */ + format: MetadataFormatSchema32.describe("Serialization format"), + /** + * Full file path (if applicable) + */ + path: external_exports.string().optional().describe("File system path"), + /** + * Additional metadata provider-specific properties + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific metadata") +}); +var MetadataLoadOptionsSchema22 = external_exports.object({ + /** + * Glob patterns to match files + * Example: ["**\/*.object.ts", "**\/*.object.json"] + */ + patterns: external_exports.array(external_exports.string()).optional().describe("File glob patterns"), + /** + * If-None-Match header for conditional loading + * Only load if ETag doesn't match + */ + ifNoneMatch: external_exports.string().optional().describe("ETag for conditional request"), + /** + * If-Modified-Since header for conditional loading + */ + ifModifiedSince: external_exports.string().datetime().optional().describe("Only load if modified after this date"), + /** + * Whether to validate against Zod schema + */ + validate: external_exports.boolean().default(true).describe("Validate against schema"), + /** + * Whether to use cache if available + */ + useCache: external_exports.boolean().default(true).describe("Enable caching"), + /** + * Filter function (serialized as string) + * Example: "(item) => item.name.startsWith('sys_')" + */ + filter: external_exports.string().optional().describe("Filter predicate as string"), + /** + * Maximum number of items to load + */ + limit: external_exports.number().int().min(1).optional().describe("Maximum items to load"), + /** + * Recursively search subdirectories + */ + recursive: external_exports.boolean().default(true).describe("Search subdirectories") +}); +var MetadataSaveOptionsSchema22 = external_exports.object({ + /** + * Serialization format + */ + format: MetadataFormatSchema32.default("typescript").describe("Output format"), + /** + * Prettify output (formatted with indentation) + */ + prettify: external_exports.boolean().default(true).describe("Format with indentation"), + /** + * Indentation size (spaces) + */ + indent: external_exports.number().int().min(0).max(8).default(2).describe("Indentation spaces"), + /** + * Sort object keys alphabetically + */ + sortKeys: external_exports.boolean().default(false).describe("Sort object keys"), + /** + * Include default values in output + */ + includeDefaults: external_exports.boolean().default(false).describe("Include default values"), + /** + * Create backup before overwriting + */ + backup: external_exports.boolean().default(false).describe("Create backup file"), + /** + * Overwrite if exists + */ + overwrite: external_exports.boolean().default(true).describe("Overwrite existing file"), + /** + * Atomic write (write to temp file, then rename) + */ + atomic: external_exports.boolean().default(true).describe("Use atomic write operation"), + /** + * Custom file path (overrides default location) + */ + path: external_exports.string().optional().describe("Custom output path") +}); +var MetadataExportOptionsSchema22 = external_exports.object({ + /** + * Output file path + */ + output: external_exports.string().describe("Output file path"), + /** + * Export format + */ + format: MetadataFormatSchema32.default("json").describe("Export format"), + /** + * Filter predicate as string + */ + filter: external_exports.string().optional().describe("Filter items to export"), + /** + * Include statistics in export + */ + includeStats: external_exports.boolean().default(false).describe("Include metadata statistics"), + /** + * Compress output + */ + compress: external_exports.boolean().default(false).describe("Compress output (gzip)"), + /** + * Pretty print output + */ + prettify: external_exports.boolean().default(true).describe("Pretty print output") +}); +var MetadataImportOptionsSchema22 = external_exports.object({ + /** + * Conflict resolution strategy + */ + conflictResolution: external_exports.enum(["skip", "overwrite", "merge", "fail"]).default("merge").describe("How to handle existing items"), + /** + * Validate items against schema + */ + validate: external_exports.boolean().default(true).describe("Validate before import"), + /** + * Dry run (don't actually save) + */ + dryRun: external_exports.boolean().default(false).describe("Simulate import without saving"), + /** + * Continue on errors + */ + continueOnError: external_exports.boolean().default(false).describe("Continue if validation fails"), + /** + * Transform function (as string) + * Example: "(item) => ({ ...item, imported: true })" + */ + transform: external_exports.string().optional().describe("Transform items before import") +}); +var MetadataLoadResultSchema22 = external_exports.object({ + /** + * Loaded data + */ + data: external_exports.unknown().nullable().describe("Loaded metadata"), + /** + * Whether data came from cache (304 Not Modified) + */ + fromCache: external_exports.boolean().default(false).describe("Loaded from cache"), + /** + * Not modified (conditional request matched) + */ + notModified: external_exports.boolean().default(false).describe("Not modified since last request"), + /** + * ETag of loaded data + */ + etag: external_exports.string().optional().describe("Entity tag"), + /** + * Statistics about loaded data + */ + stats: MetadataStatsSchema22.optional().describe("Metadata statistics"), + /** + * Load time in milliseconds + */ + loadTime: external_exports.number().min(0).optional().describe("Load duration in ms") +}); +var MetadataSaveResultSchema22 = external_exports.object({ + /** + * Whether save was successful + */ + success: external_exports.boolean().describe("Save successful"), + /** + * Path where file was saved + */ + path: external_exports.string().describe("Output path"), + /** + * Generated ETag + */ + etag: external_exports.string().optional().describe("Generated entity tag"), + /** + * File size in bytes + */ + size: external_exports.number().int().min(0).optional().describe("File size"), + /** + * Save time in milliseconds + */ + saveTime: external_exports.number().min(0).optional().describe("Save duration in ms"), + /** + * Backup path (if created) + */ + backupPath: external_exports.string().optional().describe("Backup file path") +}); +var MetadataWatchEventSchema22 = external_exports.object({ + /** + * Event type + */ + type: external_exports.enum(["added", "changed", "deleted"]).describe("Event type"), + /** + * Metadata type (e.g., 'object', 'view', 'app') + */ + metadataType: external_exports.string().describe("Type of metadata"), + /** + * Item name/identifier + */ + name: external_exports.string().describe("Item identifier"), + /** + * Full file path + */ + path: external_exports.string().describe("File path"), + /** + * Loaded item data (for added/changed events) + */ + data: external_exports.unknown().optional().describe("Item data"), + /** + * Timestamp + */ + timestamp: external_exports.string().datetime().describe("Event timestamp") +}); +var MetadataCollectionInfoSchema22 = external_exports.object({ + /** + * Collection type (e.g., 'object', 'view', 'app') + */ + type: external_exports.string().describe("Collection type"), + /** + * Total items in collection + */ + count: external_exports.number().int().min(0).describe("Number of items"), + /** + * Formats found in collection + */ + formats: external_exports.array(MetadataFormatSchema32).describe("Formats in collection"), + /** + * Total size in bytes + */ + totalSize: external_exports.number().int().min(0).optional().describe("Total size in bytes"), + /** + * Last modified timestamp + */ + lastModified: external_exports.string().datetime().optional().describe("Last modification date"), + /** + * Collection location (path or URL) + */ + location: external_exports.string().optional().describe("Collection location") +}); +var MetadataLoaderContractSchema22 = external_exports.object({ + /** + * Loader name/identifier + */ + name: external_exports.string().describe("Loader identifier"), + /** + * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:') + */ + protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Protocol identifier"), + /** + * Detailed capabilities + */ + capabilities: external_exports.object({ + read: external_exports.boolean().default(true), + write: external_exports.boolean().default(false), + watch: external_exports.boolean().default(false), + list: external_exports.boolean().default(true) + }).describe("Loader capabilities"), + /** + * Supported formats + */ + supportedFormats: external_exports.array(MetadataFormatSchema32).describe("Supported formats"), + /** + * Whether loader supports watching for changes + */ + supportsWatch: external_exports.boolean().default(false).describe("Supports file watching"), + /** + * Whether loader supports saving + */ + supportsWrite: external_exports.boolean().default(true).describe("Supports write operations"), + /** + * Whether loader supports caching + */ + supportsCache: external_exports.boolean().default(true).describe("Supports caching") +}); +var MetadataFallbackStrategySchema22 = external_exports.enum([ + "filesystem", + // Fall back to filesystem-based loading + "memory", + // Fall back to in-memory storage + "none" + // No fallback — fail immediately +]); +var MetadataManagerConfigSchema22 = external_exports.object({ + /** + * Datasource Name Reference + * References a DatasourceSchema.name (e.g. 'default'). + * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. + */ + datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), + /** + * Metadata Table Name + * The database table used for metadata storage when datasource is configured. + */ + tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), + /** + * Fallback Strategy + * Determines behavior when the primary datasource is unavailable. + */ + fallback: MetadataFallbackStrategySchema22.default("none").describe("Fallback strategy when datasource is unavailable"), + /** + * Root directory for metadata (for filesystem loaders) + */ + rootDir: external_exports.string().optional().describe("Root directory path"), + /** + * Enabled serialization formats + */ + formats: external_exports.array(MetadataFormatSchema32).default(["typescript", "json", "yaml"]).describe("Enabled formats"), + /** + * Cache configuration + */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable caching"), + ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), + maxSize: external_exports.number().int().min(0).optional().describe("Max cache size in bytes") + }).optional().describe("Cache settings"), + /** + * Watch for file changes + */ + watch: external_exports.boolean().default(false).describe("Enable file watching"), + /** + * Watch options + */ + watchOptions: external_exports.object({ + ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), + persistent: external_exports.boolean().default(true).describe("Keep process running"), + ignoreInitial: external_exports.boolean().default(true).describe("Ignore initial add events") + }).optional().describe("File watcher options"), + /** + * Validation settings + */ + validation: external_exports.object({ + strict: external_exports.boolean().default(true).describe("Strict validation"), + throwOnError: external_exports.boolean().default(true).describe("Throw on validation error") + }).optional().describe("Validation settings"), + /** + * Loader-specific options + */ + loaderOptions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Loader-specific configuration") +}); +var MetadataTypeSchema3 = external_exports.enum([ + // Data Protocol + "object", + // Business entity definition (ObjectSchema) + "field", + // Standalone field definition (FieldSchema) + "trigger", + // Data-layer event triggers (TriggerSchema) + "validation", + // Validation rules (ValidationSchema) + "hook", + // Data hooks (HookSchema) + // UI Protocol + "view", + // List/form views (ViewSchema) + "page", + // Standalone pages (PageSchema) + "dashboard", + // Dashboard layouts (DashboardSchema) + "app", + // Application shell (AppSchema) + "action", + // UI/Server actions (ActionSchema) + "report", + // Report definitions (ReportSchema) + // Automation Protocol + "flow", + // Visual logic flows (FlowSchema) + "workflow", + // State machines (WorkflowSchema) + "approval", + // Approval processes (ApprovalSchema) + // System Protocol + "datasource", + // Data connections (DatasourceSchema) + "translation", + // i18n resources (TranslationSchema) + "router", + // API routes + "function", + // Serverless functions + "service", + // Service definitions + // Security Protocol + "permission", + // Permission sets (PermissionSetSchema) + "profile", + // User profiles (ProfileSchema) + "role", + // Security roles + // AI Protocol + "agent", + // AI agent definitions (AgentSchema) + "tool", + // AI tool definitions (ToolSchema) + "skill" + // AI skill definitions (SkillSchema) +]); +var MetadataTypeRegistryEntrySchema3 = external_exports.object({ + /** Metadata type identifier (e.g., 'object', 'view') */ + type: MetadataTypeSchema3.describe("Metadata type identifier"), + /** Human-readable label */ + label: external_exports.string().describe("Display label for the metadata type"), + /** Brief description */ + description: external_exports.string().optional().describe("Description of the metadata type"), + /** + * File glob patterns for this type. + * Used to discover metadata files on disk. + * @example ["**\/*.object.ts", "**\/*.object.yml"] + */ + filePatterns: external_exports.array(external_exports.string()).describe("Glob patterns to discover files of this type"), + /** + * Whether this type supports the customization overlay system. + * When true, platform/user overlays can be applied on top of package-delivered metadata. + */ + supportsOverlay: external_exports.boolean().default(true).describe("Whether overlay customization is supported"), + /** + * Whether metadata of this type can be created at runtime via API. + * Some types (e.g., 'object') may be restricted to deployment-only. + */ + allowRuntimeCreate: external_exports.boolean().default(true).describe("Allow runtime creation via API"), + /** + * Whether this type supports versioning. + * When true, changes are tracked with version history. + */ + supportsVersioning: external_exports.boolean().default(false).describe("Whether version history is tracked"), + /** + * Priority order for loading (lower = earlier). + * Objects load before views, views before dashboards. + */ + loadOrder: external_exports.number().int().min(0).default(100).describe("Loading priority (lower = earlier)"), + /** The domain this type belongs to */ + domain: external_exports.enum(["data", "ui", "automation", "system", "security", "ai"]).describe("Protocol domain") +}); +var MetadataQuerySchema3 = external_exports.object({ + /** Filter by metadata type(s) */ + types: external_exports.array(MetadataTypeSchema3).optional().describe("Filter by metadata types"), + /** Filter by namespace(s) */ + namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), + /** Filter by package ID */ + packageId: external_exports.string().optional().describe("Filter by owning package"), + /** Full-text search across name, label, description */ + search: external_exports.string().optional().describe("Full-text search query"), + /** Filter by scope */ + scope: external_exports.enum(["system", "platform", "user"]).optional().describe("Filter by scope"), + /** Filter by state */ + state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional().describe("Filter by lifecycle state"), + /** Filter by tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), + /** Sort field */ + sortBy: external_exports.enum(["name", "type", "updatedAt", "createdAt"]).default("name").describe("Sort field"), + /** Sort direction */ + sortOrder: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction"), + /** Pagination: page number (1-based) */ + page: external_exports.number().int().min(1).default(1).describe("Page number"), + /** Pagination: items per page */ + pageSize: external_exports.number().int().min(1).max(500).default(50).describe("Items per page") +}); +var MetadataQueryResultSchema3 = external_exports.object({ + /** Matched items */ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + namespace: external_exports.string().optional().describe("Namespace"), + label: external_exports.string().optional().describe("Display label"), + scope: external_exports.enum(["system", "platform", "user"]).optional(), + state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional(), + packageId: external_exports.string().optional(), + updatedAt: external_exports.string().datetime().optional() + })).describe("Matched metadata items"), + /** Total count (for pagination) */ + total: external_exports.number().int().min(0).describe("Total matching items"), + /** Current page */ + page: external_exports.number().int().min(1).describe("Current page"), + /** Page size */ + pageSize: external_exports.number().int().min(1).describe("Page size") +}); +var MetadataEventSchema3 = external_exports.object({ + /** Event type */ + event: external_exports.enum([ + "metadata.registered", + "metadata.updated", + "metadata.unregistered", + "metadata.validated", + "metadata.deployed", + "metadata.overlay.applied", + "metadata.overlay.removed", + "metadata.imported", + "metadata.exported" + ]).describe("Event type"), + /** Metadata type */ + metadataType: MetadataTypeSchema3.describe("Metadata type"), + /** Item name */ + name: external_exports.string().describe("Metadata item name"), + /** Namespace */ + namespace: external_exports.string().optional().describe("Namespace"), + /** Package ID (if package-managed) */ + packageId: external_exports.string().optional().describe("Owning package ID"), + /** Timestamp */ + timestamp: external_exports.string().datetime().describe("Event timestamp"), + /** Actor who caused the event */ + actor: external_exports.string().optional().describe("User or system that triggered the event"), + /** Additional event-specific payload */ + payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific payload") +}); +var MetadataValidationResultSchema3 = external_exports.object({ + /** Whether validation passed */ + valid: external_exports.boolean().describe("Whether the metadata is valid"), + /** Validation errors */ + errors: external_exports.array(external_exports.object({ + path: external_exports.string().describe("JSON path to the invalid field"), + message: external_exports.string().describe("Error description"), + code: external_exports.string().optional().describe("Error code") + })).optional().describe("Validation errors"), + /** Validation warnings (non-blocking) */ + warnings: external_exports.array(external_exports.object({ + path: external_exports.string().describe("JSON path to the field"), + message: external_exports.string().describe("Warning description") + })).optional().describe("Validation warnings") +}); +var MetadataPluginConfigSchema3 = external_exports.object({ + /** + * Storage configuration. + * References MetadataManagerConfigSchema for the underlying storage backend. + */ + storage: MetadataManagerConfigSchema22.describe("Storage backend configuration"), + /** + * Default customization policies per metadata type. + * Controls what parts of metadata can be customized by admins/users. + */ + customizationPolicies: external_exports.array(CustomizationPolicySchema3).optional().describe("Default customization policies per type"), + /** + * Merge strategy for package upgrades. + */ + mergeStrategy: MergeStrategyConfigSchema3.optional().describe("Merge strategy for package upgrades"), + /** + * Additional metadata type registrations. + * Used by plugins to register custom metadata types beyond the built-in set. + */ + additionalTypes: external_exports.array(MetadataTypeRegistryEntrySchema3.omit({ type: true }).extend({ + type: external_exports.string().describe("Custom metadata type identifier") + })).optional().describe("Additional custom metadata types"), + /** + * Enable metadata change events. + * When true, the plugin emits events on every metadata change. + */ + enableEvents: external_exports.boolean().default(true).describe("Emit metadata change events"), + /** + * Enable metadata validation on write operations. + * When true, all metadata is validated against its type schema before saving. + */ + validateOnWrite: external_exports.boolean().default(true).describe("Validate metadata on write"), + /** + * Enable metadata versioning. + * When true, changes to metadata are tracked with version history. + */ + enableVersioning: external_exports.boolean().default(false).describe("Track metadata version history"), + /** + * Maximum number of metadata items to keep in memory cache. + */ + cacheMaxItems: external_exports.number().int().min(0).default(1e4).describe("Max items in memory cache") +}); +var MetadataPluginManifestSchema2 = external_exports.object({ + /** Plugin identifier */ + id: external_exports.literal("com.objectstack.metadata").describe("Metadata plugin ID"), + /** Plugin name */ + name: external_exports.literal("ObjectStack Metadata Service").describe("Plugin name"), + /** Plugin version */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Plugin version"), + /** Plugin type */ + type: external_exports.literal("standard").describe("Plugin type"), + /** Plugin description */ + description: external_exports.string().default("Core metadata management service for ObjectStack platform").describe("Plugin description"), + /** + * Capabilities this plugin provides. + * The kernel uses this to route metadata requests to this plugin. + */ + capabilities: external_exports.object({ + /** Supports CRUD operations on metadata */ + crud: external_exports.boolean().default(true).describe("Supports metadata CRUD"), + /** Supports metadata query/search */ + query: external_exports.boolean().default(true).describe("Supports metadata query"), + /** Supports the overlay/customization system */ + overlay: external_exports.boolean().default(true).describe("Supports customization overlays"), + /** Supports file watching for hot reload */ + watch: external_exports.boolean().default(false).describe("Supports file watching"), + /** Supports bulk import/export */ + importExport: external_exports.boolean().default(true).describe("Supports import/export"), + /** Supports metadata validation */ + validation: external_exports.boolean().default(true).describe("Supports schema validation"), + /** Supports metadata versioning */ + versioning: external_exports.boolean().default(false).describe("Supports version history"), + /** Supports metadata events */ + events: external_exports.boolean().default(true).describe("Emits metadata events") + }).describe("Plugin capabilities"), + /** Plugin configuration */ + config: MetadataPluginConfigSchema3.optional().describe("Plugin configuration") +}); +var DEFAULT_METADATA_TYPE_REGISTRY = [ + // Data Protocol (load first) + { type: "object", label: "Object", filePatterns: ["**/*.object.ts", "**/*.object.yml", "**/*.object.json"], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 10, domain: "data" }, + { type: "field", label: "Field", filePatterns: ["**/*.field.ts", "**/*.field.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 20, domain: "data" }, + { type: "trigger", label: "Trigger", filePatterns: ["**/*.trigger.ts", "**/*.trigger.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: "data" }, + { type: "validation", label: "Validation Rule", filePatterns: ["**/*.validation.ts", "**/*.validation.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: "data" }, + { type: "hook", label: "Hook", filePatterns: ["**/*.hook.ts", "**/*.hook.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: "data" }, + // UI Protocol + { type: "view", label: "View", filePatterns: ["**/*.view.ts", "**/*.view.yml", "**/*.view.json"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: "ui" }, + { type: "page", label: "Page", filePatterns: ["**/*.page.ts", "**/*.page.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: "ui" }, + { type: "dashboard", label: "Dashboard", filePatterns: ["**/*.dashboard.ts", "**/*.dashboard.yml", "**/*.dashboard.json"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: "ui" }, + { type: "app", label: "Application", filePatterns: ["**/*.app.ts", "**/*.app.yml", "**/*.app.json"], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 70, domain: "ui" }, + { type: "action", label: "Action", filePatterns: ["**/*.action.ts", "**/*.action.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: "ui" }, + { type: "report", label: "Report", filePatterns: ["**/*.report.ts", "**/*.report.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: "ui" }, + // Automation Protocol + { type: "flow", label: "Flow", filePatterns: ["**/*.flow.ts", "**/*.flow.yml", "**/*.flow.json"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: "automation" }, + { type: "workflow", label: "Workflow", filePatterns: ["**/*.workflow.ts", "**/*.workflow.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: "automation" }, + { type: "approval", label: "Approval Process", filePatterns: ["**/*.approval.ts", "**/*.approval.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 80, domain: "automation" }, + // System Protocol + { type: "datasource", label: "Datasource", filePatterns: ["**/*.datasource.ts", "**/*.datasource.yml"], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 5, domain: "system" }, + { type: "translation", label: "Translation", filePatterns: ["**/*.translation.ts", "**/*.translation.yml", "**/*.translation.json"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 90, domain: "system" }, + { type: "router", label: "Router", filePatterns: ["**/*.router.ts"], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: "system" }, + { type: "function", label: "Function", filePatterns: ["**/*.function.ts"], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: "system" }, + { type: "service", label: "Service", filePatterns: ["**/*.service.ts"], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: "system" }, + // Security Protocol + { type: "permission", label: "Permission Set", filePatterns: ["**/*.permission.ts", "**/*.permission.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 15, domain: "security" }, + { type: "profile", label: "Profile", filePatterns: ["**/*.profile.ts", "**/*.profile.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: "security" }, + { type: "role", label: "Role", filePatterns: ["**/*.role.ts", "**/*.role.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: "security" }, + // AI Protocol + { type: "agent", label: "AI Agent", filePatterns: ["**/*.agent.ts", "**/*.agent.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 90, domain: "ai" }, + { type: "tool", label: "AI Tool", filePatterns: ["**/*.tool.ts", "**/*.tool.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 85, domain: "ai" }, + { type: "skill", label: "AI Skill", filePatterns: ["**/*.skill.ts", "**/*.skill.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 88, domain: "ai" } +]; +var MetadataBulkRegisterRequestSchema3 = external_exports.object({ + /** Items to register */ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), + namespace: external_exports.string().optional().describe("Namespace") + })).min(1).describe("Items to register"), + /** Continue on individual item failure */ + continueOnError: external_exports.boolean().default(false).describe("Continue if individual item fails"), + /** Validate items before registering */ + validate: external_exports.boolean().default(true).describe("Validate before register") +}); +var MetadataBulkResultSchema3 = external_exports.object({ + /** Total items processed */ + total: external_exports.number().int().min(0).describe("Total items processed"), + /** Successfully processed items */ + succeeded: external_exports.number().int().min(0).describe("Successfully processed"), + /** Failed items */ + failed: external_exports.number().int().min(0).describe("Failed items"), + /** Per-item error details */ + errors: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + error: external_exports.string().describe("Error message") + })).optional().describe("Per-item errors") +}); +var MetadataDependencySchema3 = external_exports.object({ + /** Source metadata type */ + sourceType: external_exports.string().describe("Dependent metadata type"), + /** Source metadata name */ + sourceName: external_exports.string().describe("Dependent metadata name"), + /** Target metadata type */ + targetType: external_exports.string().describe("Referenced metadata type"), + /** Target metadata name */ + targetName: external_exports.string().describe("Referenced metadata name"), + /** Dependency kind */ + kind: external_exports.enum(["reference", "extends", "includes", "triggers"]).describe("How the dependency is formed") +}); +var PackageStatusEnum3 = external_exports.enum([ + "installed", + // Successfully installed and enabled + "disabled", + // Installed but disabled (metadata not active) + "installing", + // Installation in progress + "upgrading", + // Upgrade in progress + "uninstalling", + // Removal in progress + "error" + // Installation or runtime error +]).describe("Package installation status"); +var InstalledPackageSchema3 = external_exports.object({ + /** + * The full package manifest (source of truth for package definition). + */ + manifest: ManifestSchema3.describe("Full package manifest"), + /** + * Current lifecycle status. + */ + status: PackageStatusEnum3.default("installed").describe("Package state: installed, disabled, installing, upgrading, uninstalling, or error"), + /** + * Whether the package is currently enabled (active). + * When disabled, the package's metadata is not loaded into the registry. + */ + enabled: external_exports.boolean().default(true).describe("Whether the package is currently enabled"), + /** + * ISO 8601 timestamp of when the package was installed. + */ + installedAt: external_exports.string().datetime().optional().describe("Installation timestamp"), + /** + * ISO 8601 timestamp of last update. + */ + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + /** + * The currently installed version string. + * Mirrors manifest.version for quick access without parsing the full manifest. + */ + installedVersion: external_exports.string().optional().describe("Currently installed version for quick access"), + /** + * The previously installed version (before last upgrade). + * Useful for rollback and upgrade tracking. + */ + previousVersion: external_exports.string().optional().describe("Version before the last upgrade"), + /** + * ISO 8601 timestamp of when the package was last enabled/disabled. + */ + statusChangedAt: external_exports.string().datetime().optional().describe("Status change timestamp"), + /** + * Error message if status is 'error'. + */ + errorMessage: external_exports.string().optional().describe("Error message when status is error"), + /** + * Configuration values set by the user for this package. + * Keys correspond to the package's `configuration.properties`. + */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided configuration settings"), + /** + * Upgrade history for this package. + * Records each version migration with status and optional log. + */ + upgradeHistory: external_exports.array(external_exports.object({ + /** Previous version before upgrade */ + fromVersion: external_exports.string().describe("Version before upgrade"), + /** New version after upgrade */ + toVersion: external_exports.string().describe("Version after upgrade"), + /** Timestamp of the upgrade */ + upgradedAt: external_exports.string().datetime().describe("Upgrade timestamp"), + /** Outcome of the upgrade */ + status: external_exports.enum(["success", "failed", "rolled_back"]).describe("Upgrade outcome"), + /** Migration log entries */ + migrationLog: external_exports.array(external_exports.string()).optional().describe("Migration step logs") + })).optional().describe("Version upgrade history"), + /** + * Namespaces registered by this package. + * Tracks which namespace prefixes are occupied by this package. + */ + registeredNamespaces: external_exports.array(external_exports.string()).optional().describe("Namespace prefixes registered by this package") +}).describe("Installed package with runtime lifecycle state"); +var NamespaceRegistryEntrySchema2 = external_exports.object({ + /** Namespace prefix */ + namespace: external_exports.string().describe("Namespace prefix"), + /** Package that owns this namespace */ + packageId: external_exports.string().describe("Owning package ID"), + /** Registration timestamp */ + registeredAt: external_exports.string().datetime().describe("Registration timestamp"), + /** Namespace status */ + status: external_exports.enum(["active", "disabled", "reserved"]).describe("Namespace status") +}).describe("Namespace ownership entry in the registry"); +var NamespaceConflictErrorSchema2 = external_exports.object({ + /** Error type discriminator */ + type: external_exports.literal("namespace_conflict").describe("Error type"), + /** Namespace that was requested */ + requestedNamespace: external_exports.string().describe("Requested namespace"), + /** ID of the package that already owns the namespace */ + conflictingPackageId: external_exports.string().describe("Conflicting package ID"), + /** Name of the conflicting package */ + conflictingPackageName: external_exports.string().describe("Conflicting package display name"), + /** Suggested alternative namespace */ + suggestion: external_exports.string().optional().describe("Suggested alternative namespace") +}).describe("Namespace collision error during installation"); +var ListPackagesRequestSchema3 = external_exports.object({ + /** Filter by status */ + status: PackageStatusEnum3.optional().describe("Filter by package status"), + /** Filter by package type */ + type: ManifestSchema3.shape.type.optional().describe("Filter by package type"), + /** Filter by enabled state */ + enabled: external_exports.boolean().optional().describe("Filter by enabled state") +}).describe("List packages request"); +var ListPackagesResponseSchema3 = external_exports.object({ + packages: external_exports.array(InstalledPackageSchema3).describe("List of installed packages"), + total: external_exports.number().describe("Total package count") +}).describe("List packages response"); +var GetPackageRequestSchema3 = external_exports.object({ + /** Package ID (reverse domain identifier from manifest) */ + id: external_exports.string().describe("Package identifier") +}).describe("Get package request"); +var GetPackageResponseSchema3 = external_exports.object({ + package: InstalledPackageSchema3.describe("Package details") +}).describe("Get package response"); +var InstallPackageRequestSchema3 = external_exports.object({ + /** The package manifest to install */ + manifest: ManifestSchema3.describe("Package manifest to install"), + /** Optional: user-provided settings at install time */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), + /** Whether to enable immediately after install (default: true) */ + enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), + /** + * Current platform version for compatibility checking. + * When provided, the system compares this against the package's + * `engine.objectstack` requirement to verify compatibility. + */ + platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification") +}).describe("Install package request"); +var InstallPackageResponseSchema3 = external_exports.object({ + package: InstalledPackageSchema3.describe("Installed package details"), + message: external_exports.string().optional().describe("Installation status message"), + /** Dependency resolution result (when dependencies were analyzed) */ + dependencyResolution: DependencyResolutionResultSchema3.optional().describe("Dependency resolution result from install analysis") +}).describe("Install package response"); +var UninstallPackageRequestSchema3 = external_exports.object({ + /** Package ID to uninstall */ + id: external_exports.string().describe("Package ID to uninstall") +}).describe("Uninstall package request"); +var UninstallPackageResponseSchema3 = external_exports.object({ + id: external_exports.string().describe("Uninstalled package ID"), + success: external_exports.boolean().describe("Whether uninstall succeeded"), + message: external_exports.string().optional().describe("Uninstall status message") +}).describe("Uninstall package response"); +var EnablePackageRequestSchema3 = external_exports.object({ + /** Package ID to enable */ + id: external_exports.string().describe("Package ID to enable") +}).describe("Enable package request"); +var EnablePackageResponseSchema3 = external_exports.object({ + package: InstalledPackageSchema3.describe("Enabled package details"), + message: external_exports.string().optional().describe("Enable status message") +}).describe("Enable package response"); +var DisablePackageRequestSchema3 = external_exports.object({ + /** Package ID to disable */ + id: external_exports.string().describe("Package ID to disable") +}).describe("Disable package request"); +var DisablePackageResponseSchema3 = external_exports.object({ + package: InstalledPackageSchema3.describe("Disabled package details"), + message: external_exports.string().optional().describe("Disable status message") +}).describe("Disable package response"); +var MetadataChangeTypeSchema3 = external_exports.enum([ + "added", + // New metadata item added in new version + "modified", + // Existing metadata item modified + "removed", + // Metadata item removed in new version + "renamed" + // Metadata item renamed +]).describe("Type of metadata change between package versions"); +var MetadataDiffItemSchema3 = external_exports.object({ + /** Metadata type (e.g. "object", "view", "flow") */ + type: external_exports.string().describe("Metadata type"), + /** Metadata name */ + name: external_exports.string().describe("Metadata name"), + /** Type of change */ + changeType: MetadataChangeTypeSchema3.describe("Category of metadata modification (added, modified, removed, or renamed)"), + /** Whether this change has potential conflicts with customizations */ + hasConflict: external_exports.boolean().default(false).describe("Whether this change may conflict with customizations"), + /** Human-readable summary of the change */ + summary: external_exports.string().optional().describe("Human-readable change summary"), + /** Previous name (for renames) */ + previousName: external_exports.string().optional().describe("Previous name if renamed") +}).describe("Single metadata change between package versions"); +var UpgradeImpactLevelSchema3 = external_exports.enum([ + "none", + // No impact, seamless upgrade + "low", + // Minor changes, no user action needed + "medium", + // Some changes that may affect workflows + "high", + // Significant changes, user review recommended + "critical" + // Breaking changes, manual intervention required +]).describe("Severity of upgrade impact"); +var UpgradePlanSchema3 = external_exports.object({ + /** Package being upgraded */ + packageId: external_exports.string().describe("Package identifier"), + /** Current installed version */ + fromVersion: external_exports.string().describe("Currently installed version"), + /** Target version to upgrade to */ + toVersion: external_exports.string().describe("Target upgrade version"), + /** Overall impact level */ + impactLevel: UpgradeImpactLevelSchema3.describe("Severity assessment from none (seamless) to critical (breaking changes)"), + /** List of all metadata changes between versions */ + changes: external_exports.array(MetadataDiffItemSchema3).describe("All metadata changes"), + /** Number of customer customizations that may be affected */ + affectedCustomizations: external_exports.number().int().min(0).default(0).describe("Count of customizations that may be affected"), + /** Whether any migration scripts need to run */ + requiresMigration: external_exports.boolean().default(false).describe("Whether data migration scripts are needed"), + /** Migration script paths (relative to package root) */ + migrationScripts: external_exports.array(external_exports.string()).optional().describe("Paths to migration scripts"), + /** Dependencies that also need upgrading */ + dependencyUpgrades: external_exports.array(external_exports.object({ + packageId: external_exports.string(), + fromVersion: external_exports.string(), + toVersion: external_exports.string() + })).optional().describe("Dependent packages that also need upgrading"), + /** Estimated upgrade duration in seconds */ + estimatedDuration: external_exports.number().int().min(0).optional().describe("Estimated upgrade duration in seconds"), + /** Human-readable summary */ + summary: external_exports.string().optional().describe("Human-readable upgrade summary") +}).describe("Upgrade analysis plan generated before execution"); +var UpgradeSnapshotSchema2 = external_exports.object({ + /** Snapshot ID (UUID) */ + id: external_exports.string().describe("Snapshot identifier"), + /** Package being upgraded */ + packageId: external_exports.string().describe("Package identifier"), + /** Version being upgraded from */ + fromVersion: external_exports.string().describe("Version before upgrade"), + /** Version being upgraded to */ + toVersion: external_exports.string().describe("Target upgrade version"), + /** Tenant ID */ + tenantId: external_exports.string().optional().describe("Tenant identifier"), + /** Complete manifest of the old package version */ + previousManifest: ManifestSchema3.describe("Complete manifest of the previous package version"), + /** + * Snapshot of all metadata records owned by this package. + * Stored as array of { type, name, metadata } tuples. + */ + metadataSnapshot: external_exports.array(external_exports.object({ + type: external_exports.string(), + name: external_exports.string(), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()) + })).describe("Snapshot of all package metadata"), + /** + * Snapshot of all customer customizations (overlays) for this package's metadata. + */ + customizationSnapshot: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Snapshot of customer customizations"), + /** When the snapshot was created */ + createdAt: external_exports.string().datetime().describe("Snapshot creation timestamp"), + /** Expiry time for snapshot cleanup */ + expiresAt: external_exports.string().datetime().optional().describe("Snapshot expiry timestamp") +}).describe("Pre-upgrade state snapshot for rollback capability"); +var UpgradePackageRequestSchema2 = external_exports.object({ + /** Package ID to upgrade */ + packageId: external_exports.string().describe("Package ID to upgrade"), + /** Target version (if omitted, upgrades to latest) */ + targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), + /** New manifest for the target version */ + manifest: ManifestSchema3.optional().describe("New manifest (if installing from local)"), + /** Whether to create a pre-upgrade snapshot */ + createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), + /** Merge strategy for handling customizations */ + mergeStrategy: external_exports.enum([ + "keep-custom", + "accept-incoming", + "three-way-merge" + ]).default("three-way-merge").describe("How to handle customer customizations"), + /** Whether to run in dry-run mode (preview only, no changes) */ + dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), + /** Whether to skip pre-upgrade validation */ + skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") +}).describe("Upgrade package request"); +var UpgradePhaseSchema3 = external_exports.enum([ + "pending", + // Upgrade requested but not started + "analyzing", + // Generating upgrade plan + "snapshot", + // Creating pre-upgrade snapshot + "executing", + // Applying metadata changes + "migrating", + // Running migration scripts + "validating", + // Post-upgrade validation + "completed", + // Upgrade completed successfully + "failed", + // Upgrade failed + "rolling-back", + // Rollback in progress + "rolled-back" + // Rollback completed +]).describe("Current phase of the upgrade process"); +var UpgradePackageResponseSchema2 = external_exports.object({ + /** Whether the upgrade was successful */ + success: external_exports.boolean().describe("Whether the upgrade succeeded"), + /** Current upgrade phase */ + phase: UpgradePhaseSchema3.describe("Current upgrade phase"), + /** The upgrade plan that was executed */ + plan: UpgradePlanSchema3.optional().describe("Upgrade plan"), + /** Snapshot ID for rollback */ + snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), + /** Merge conflicts that need manual resolution (if any) */ + conflicts: external_exports.array(external_exports.object({ + path: external_exports.string(), + baseValue: external_exports.unknown(), + incomingValue: external_exports.unknown(), + customValue: external_exports.unknown() + })).optional().describe("Unresolved merge conflicts"), + /** Error message (if failed) */ + errorMessage: external_exports.string().optional().describe("Error message if upgrade failed"), + /** Human-readable summary */ + message: external_exports.string().optional().describe("Human-readable status message") +}).describe("Upgrade package response"); +var RollbackPackageRequestSchema2 = external_exports.object({ + /** Package ID to rollback */ + packageId: external_exports.string().describe("Package ID to rollback"), + /** Snapshot ID to restore from */ + snapshotId: external_exports.string().describe("Snapshot ID to restore from"), + /** Whether to also rollback customizations */ + rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") +}).describe("Rollback package request"); +var RollbackPackageResponseSchema2 = external_exports.object({ + /** Whether the rollback was successful */ + success: external_exports.boolean().describe("Whether the rollback succeeded"), + /** Restored version */ + restoredVersion: external_exports.string().optional().describe("Version restored to"), + /** Message */ + message: external_exports.string().optional().describe("Rollback status message") +}).describe("Rollback package response"); +var PluginHealthStatusSchema2 = external_exports.enum([ + "healthy", + // Plugin is operating normally + "degraded", + // Plugin is operational but with reduced functionality + "unhealthy", + // Plugin has critical issues but still running + "failed", + // Plugin has failed and is not operational + "recovering", + // Plugin is in recovery process + "unknown" + // Health status cannot be determined +]).describe("Current health status of the plugin"); +var PluginHealthCheckSchema2 = external_exports.object({ + /** + * Health check interval in milliseconds + */ + interval: external_exports.number().int().min(1e3).default(3e4).describe("How often to perform health checks (default: 30s)"), + /** + * Timeout for health check in milliseconds + */ + timeout: external_exports.number().int().min(100).default(5e3).describe("Maximum time to wait for health check response"), + /** + * Number of consecutive failures before marking as unhealthy + */ + failureThreshold: external_exports.number().int().min(1).default(3).describe("Consecutive failures needed to mark unhealthy"), + /** + * Number of consecutive successes to recover from unhealthy state + */ + successThreshold: external_exports.number().int().min(1).default(1).describe("Consecutive successes needed to mark healthy"), + /** + * Custom health check function name or endpoint + */ + checkMethod: external_exports.string().optional().describe("Method name to call for health check"), + /** + * Enable automatic restart on failure + */ + autoRestart: external_exports.boolean().default(false).describe("Automatically restart plugin on health check failure"), + /** + * Maximum number of restart attempts + */ + maxRestartAttempts: external_exports.number().int().min(0).default(3).describe("Maximum restart attempts before giving up"), + /** + * Backoff strategy for restarts + */ + restartBackoff: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy for restart delays") +}); +var PluginHealthReportSchema2 = external_exports.object({ + /** + * Overall health status + */ + status: PluginHealthStatusSchema2, + /** + * Timestamp of the health check + */ + timestamp: external_exports.string().datetime(), + /** + * Human-readable message about health status + */ + message: external_exports.string().optional(), + /** + * Detailed metrics + */ + metrics: external_exports.object({ + uptime: external_exports.number().describe("Plugin uptime in milliseconds"), + memoryUsage: external_exports.number().optional().describe("Memory usage in bytes"), + cpuUsage: external_exports.number().optional().describe("CPU usage percentage"), + activeConnections: external_exports.number().optional().describe("Number of active connections"), + errorRate: external_exports.number().optional().describe("Error rate (errors per minute)"), + responseTime: external_exports.number().optional().describe("Average response time in ms") + }).partial().optional(), + /** + * List of checks performed + */ + checks: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Check name"), + status: external_exports.enum(["passed", "failed", "warning"]), + message: external_exports.string().optional(), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + })).optional(), + /** + * Dependencies health + */ + dependencies: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + status: PluginHealthStatusSchema2, + message: external_exports.string().optional() + })).optional() +}); +var DistributedStateConfigSchema2 = external_exports.object({ + /** + * Distributed cache provider + */ + provider: external_exports.enum(["redis", "etcd", "custom"]).describe("Distributed state backend provider"), + /** + * Connection URL or endpoints + */ + endpoints: external_exports.array(external_exports.string()).optional().describe("Backend connection endpoints"), + /** + * Key prefix for namespacing + */ + keyPrefix: external_exports.string().optional().describe('Prefix for all keys (e.g., "plugin:my-plugin:")'), + /** + * Time to live in seconds + */ + ttl: external_exports.number().int().min(0).optional().describe("State expiration time in seconds"), + /** + * Authentication configuration + */ + auth: external_exports.object({ + username: external_exports.string().optional(), + password: external_exports.string().optional(), + token: external_exports.string().optional(), + certificate: external_exports.string().optional() + }).optional(), + /** + * Replication settings + */ + replication: external_exports.object({ + enabled: external_exports.boolean().default(true), + minReplicas: external_exports.number().int().min(1).default(1) + }).optional(), + /** + * Custom provider configuration + */ + customConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration") +}); +var HotReloadConfigSchema2 = external_exports.object({ + /** + * Enable hot reload capability + */ + enabled: external_exports.boolean().default(false), + /** + * Watch file patterns for auto-reload + */ + watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns to watch for changes"), + /** + * Debounce delay before reloading (milliseconds) + */ + debounceDelay: external_exports.number().int().min(0).default(1e3).describe("Wait time after change detection before reload"), + /** + * Preserve plugin state during reload + */ + preserveState: external_exports.boolean().default(true).describe("Keep plugin state across reloads"), + /** + * State serialization strategy + */ + stateStrategy: external_exports.enum(["memory", "disk", "distributed", "none"]).default("memory").describe("How to preserve state during reload"), + /** + * Distributed state configuration (required when stateStrategy is "distributed") + */ + distributedConfig: DistributedStateConfigSchema2.optional().describe("Configuration for distributed state management"), + /** + * Graceful shutdown timeout + */ + shutdownTimeout: external_exports.number().int().min(0).default(3e4).describe("Maximum time to wait for graceful shutdown"), + /** + * Pre-reload hooks + */ + beforeReload: external_exports.array(external_exports.string()).optional().describe("Hook names to call before reload"), + /** + * Post-reload hooks + */ + afterReload: external_exports.array(external_exports.string()).optional().describe("Hook names to call after reload") +}); +var GracefulDegradationSchema2 = external_exports.object({ + /** + * Enable graceful degradation + */ + enabled: external_exports.boolean().default(true), + /** + * Fallback mode when dependencies fail + */ + fallbackMode: external_exports.enum([ + "minimal", + // Provide minimal functionality + "cached", + // Use cached data + "readonly", + // Allow read-only operations + "offline", + // Offline mode with local data + "disabled" + // Disable plugin functionality + ]).default("minimal"), + /** + * Critical dependencies that must be available + */ + criticalDependencies: external_exports.array(external_exports.string()).optional().describe("Plugin IDs that are required for operation"), + /** + * Optional dependencies that can fail + */ + optionalDependencies: external_exports.array(external_exports.string()).optional().describe("Plugin IDs that are nice to have but not required"), + /** + * Feature flags for degraded mode + */ + degradedFeatures: external_exports.array(external_exports.object({ + feature: external_exports.string().describe("Feature name"), + enabled: external_exports.boolean().describe("Whether feature is available in degraded mode"), + reason: external_exports.string().optional() + })).optional(), + /** + * Automatic recovery attempts + */ + autoRecovery: external_exports.object({ + enabled: external_exports.boolean().default(true), + retryInterval: external_exports.number().int().min(1e3).default(6e4).describe("Interval between recovery attempts (ms)"), + maxAttempts: external_exports.number().int().min(0).default(5).describe("Maximum recovery attempts before giving up") + }).optional() +}); +var PluginUpdateStrategySchema2 = external_exports.object({ + /** + * Update mode + */ + mode: external_exports.enum([ + "manual", + // Manual updates only + "automatic", + // Automatic updates + "scheduled", + // Scheduled update windows + "rolling" + // Rolling updates with zero downtime + ]).default("manual"), + /** + * Version constraints for automatic updates + */ + autoUpdateConstraints: external_exports.object({ + major: external_exports.boolean().default(false).describe("Allow major version updates"), + minor: external_exports.boolean().default(true).describe("Allow minor version updates"), + patch: external_exports.boolean().default(true).describe("Allow patch version updates") + }).optional(), + /** + * Update schedule (for scheduled mode) + */ + schedule: external_exports.object({ + /** + * Cron expression for update window + */ + cron: external_exports.string().optional(), + /** + * Timezone for schedule + */ + timezone: external_exports.string().default("UTC"), + /** + * Maintenance window duration in minutes + */ + maintenanceWindow: external_exports.number().int().min(1).default(60) + }).optional(), + /** + * Rollback configuration + */ + rollback: external_exports.object({ + enabled: external_exports.boolean().default(true), + /** + * Automatic rollback on failure + */ + automatic: external_exports.boolean().default(true), + /** + * Keep N previous versions for rollback + */ + keepVersions: external_exports.number().int().min(1).default(3), + /** + * Rollback timeout in milliseconds + */ + timeout: external_exports.number().int().min(1e3).default(3e4) + }).optional(), + /** + * Pre-update validation + */ + validation: external_exports.object({ + /** + * Run compatibility checks before update + */ + checkCompatibility: external_exports.boolean().default(true), + /** + * Run tests before applying update + */ + runTests: external_exports.boolean().default(false), + /** + * Test suite to run + */ + testSuite: external_exports.string().optional() + }).optional() +}); +var PluginStateSnapshotSchema2 = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Version at time of snapshot + */ + version: external_exports.string(), + /** + * Snapshot timestamp + */ + timestamp: external_exports.string().datetime(), + /** + * Serialized state data + */ + state: external_exports.record(external_exports.string(), external_exports.unknown()), + /** + * State metadata + */ + metadata: external_exports.object({ + checksum: external_exports.string().optional().describe("State checksum for verification"), + compressed: external_exports.boolean().default(false), + encryption: external_exports.string().optional().describe("Encryption algorithm if encrypted") + }).optional() +}); +var AdvancedPluginLifecycleConfigSchema2 = external_exports.object({ + /** + * Health monitoring configuration + */ + health: PluginHealthCheckSchema2.optional(), + /** + * Hot reload configuration + */ + hotReload: HotReloadConfigSchema2.optional(), + /** + * Graceful degradation configuration + */ + degradation: GracefulDegradationSchema2.optional(), + /** + * Update strategy + */ + updates: PluginUpdateStrategySchema2.optional(), + /** + * Resource limits + */ + resources: external_exports.object({ + maxMemory: external_exports.number().int().optional().describe("Maximum memory in bytes"), + maxCpu: external_exports.number().min(0).max(100).optional().describe("Maximum CPU percentage"), + maxConnections: external_exports.number().int().optional().describe("Maximum concurrent connections"), + timeout: external_exports.number().int().optional().describe("Operation timeout in milliseconds") + }).optional(), + /** + * Monitoring and observability + */ + observability: external_exports.object({ + enableMetrics: external_exports.boolean().default(true), + enableTracing: external_exports.boolean().default(true), + enableProfiling: external_exports.boolean().default(false), + metricsInterval: external_exports.number().int().min(1e3).default(6e4).describe("Metrics collection interval in ms") + }).optional() +}); +var EventPhaseSchema2 = external_exports.enum(["init", "start", "destroy"]).describe("Plugin lifecycle phase"); +var PluginEventBaseSchema2 = external_exports.object({ + /** + * Plugin name + */ + pluginName: external_exports.string().describe("Name of the plugin"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds when event occurred") +}); +var PluginRegisteredEventSchema2 = PluginEventBaseSchema2.extend({ + /** + * Plugin version (optional) + */ + version: external_exports.string().optional().describe("Plugin version") +}); +var PluginLifecyclePhaseEventSchema2 = PluginEventBaseSchema2.extend({ + /** + * Duration of the phase (milliseconds) + */ + duration: external_exports.number().min(0).optional().describe("Duration of the lifecycle phase in milliseconds"), + /** + * Lifecycle phase + */ + phase: EventPhaseSchema2.optional().describe("Lifecycle phase") +}); +var PluginErrorEventSchema2 = PluginEventBaseSchema2.extend({ + /** + * Error object + */ + error: external_exports.object({ + name: external_exports.string().describe("Error class name"), + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Stack trace"), + code: external_exports.string().optional().describe("Error code") + }).describe("Serializable error representation"), + /** + * Lifecycle phase where error occurred + */ + phase: EventPhaseSchema2.describe("Lifecycle phase where error occurred"), + /** + * Error message (for serialization) + */ + errorMessage: external_exports.string().optional().describe("Error message"), + /** + * Error stack trace (for debugging) + */ + errorStack: external_exports.string().optional().describe("Error stack trace") +}); +var ServiceRegisteredEventSchema2 = external_exports.object({ + /** + * Service name + */ + serviceName: external_exports.string().describe("Name of the registered service"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), + /** + * Service type (optional) + */ + serviceType: external_exports.string().optional().describe("Type or interface name of the service") +}); +var ServiceUnregisteredEventSchema2 = external_exports.object({ + /** + * Service name + */ + serviceName: external_exports.string().describe("Name of the unregistered service"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds") +}); +var HookRegisteredEventSchema2 = external_exports.object({ + /** + * Hook name + */ + hookName: external_exports.string().describe("Name of the hook"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), + /** + * Number of handlers registered for this hook + */ + handlerCount: external_exports.number().int().min(0).describe("Number of handlers registered for this hook") +}); +var HookTriggeredEventSchema2 = external_exports.object({ + /** + * Hook name + */ + hookName: external_exports.string().describe("Name of the hook"), + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), + /** + * Arguments passed to the hook + */ + args: external_exports.array(external_exports.unknown()).describe("Arguments passed to the hook handlers"), + /** + * Number of handlers that will handle this event + */ + handlerCount: external_exports.number().int().min(0).optional().describe("Number of handlers that will handle this event") +}); +var KernelEventBaseSchema2 = external_exports.object({ + /** + * Event timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds") +}); +var KernelReadyEventSchema2 = KernelEventBaseSchema2.extend({ + /** + * Total initialization duration (milliseconds) + */ + duration: external_exports.number().min(0).optional().describe("Total initialization duration in milliseconds"), + /** + * Number of plugins initialized + */ + pluginCount: external_exports.number().int().min(0).optional().describe("Number of plugins initialized") +}); +var KernelShutdownEventSchema2 = KernelEventBaseSchema2.extend({ + /** + * Shutdown reason (optional) + */ + reason: external_exports.string().optional().describe("Reason for kernel shutdown") +}); +var PluginLifecycleEventType2 = external_exports.enum([ + "kernel:ready", + "kernel:shutdown", + "kernel:before-init", + "kernel:after-init", + "plugin:registered", + "plugin:before-init", + "plugin:init", + "plugin:after-init", + "plugin:before-start", + "plugin:started", + "plugin:after-start", + "plugin:before-destroy", + "plugin:destroyed", + "plugin:after-destroy", + "plugin:error", + "service:registered", + "service:unregistered", + "hook:registered", + "hook:triggered" +]).describe("Plugin lifecycle event type"); +var DynamicPluginOperationSchema2 = external_exports.enum([ + "load", + // Load and initialize a plugin at runtime + "unload", + // Gracefully unload a running plugin + "reload", + // Unload then load (e.g., version upgrade) + "enable", + // Enable a loaded but disabled plugin + "disable" + // Disable a running plugin without unloading +]).describe("Runtime plugin operation type"); +var PluginSourceSchema2 = external_exports.object({ + /** + * Source type + */ + type: external_exports.enum([ + "npm", + // npm registry package + "local", + // Local filesystem path + "url", + // Remote URL (tarball or module) + "registry", + // ObjectStack plugin registry + "git" + // Git repository + ]).describe("Plugin source type"), + /** + * Source location (package name, path, URL, or git repo) + */ + location: external_exports.string().describe("Package name, file path, URL, or git repository"), + /** + * Version constraint (semver range) + */ + version: external_exports.string().optional().describe('Semver version range (e.g., "^1.0.0")'), + /** + * Integrity hash for verification + */ + integrity: external_exports.string().optional().describe('Subresource Integrity hash (e.g., "sha384-...")') +}).describe("Plugin source location for dynamic resolution"); +var ActivationEventSchema2 = external_exports.object({ + /** + * Event type + */ + type: external_exports.enum([ + "onCommand", + // Activate when a specific command is executed + "onRoute", + // Activate when a URL route is matched + "onObject", + // Activate when a specific object type is accessed + "onEvent", + // Activate when a system event fires + "onService", + // Activate when a service is requested + "onSchedule", + // Activate on a cron schedule + "onStartup" + // Activate immediately on kernel startup + ]).describe("Trigger type for lazy activation"), + /** + * Pattern to match (command name, route glob, object name, event pattern, etc.) + */ + pattern: external_exports.string().describe("Match pattern for the activation trigger") +}).describe("Lazy activation trigger for a dynamic plugin"); +var DynamicLoadRequestSchema2 = external_exports.object({ + /** + * Plugin identifier to load + */ + pluginId: external_exports.string().describe("Unique plugin identifier"), + /** + * Plugin source + */ + source: PluginSourceSchema2, + /** + * Activation events (if omitted, plugin activates immediately) + */ + activationEvents: external_exports.array(ActivationEventSchema2).optional().describe("Lazy activation triggers; if omitted plugin starts immediately"), + /** + * Configuration overrides for the plugin + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Runtime configuration overrides"), + /** + * Loading priority (lower = higher priority) + */ + priority: external_exports.number().int().min(0).default(100).describe("Loading priority (lower is higher)"), + /** + * Whether to enable sandboxing for this dynamically loaded plugin + */ + sandbox: external_exports.boolean().default(false).describe("Run in an isolated sandbox"), + /** + * Timeout for the load operation in milliseconds + */ + timeout: external_exports.number().int().min(1e3).default(6e4).describe("Maximum time to complete loading in ms") +}).describe("Request to dynamically load a plugin at runtime"); +var DynamicUnloadRequestSchema2 = external_exports.object({ + /** + * Plugin identifier to unload + */ + pluginId: external_exports.string().describe("Plugin to unload"), + /** + * Unload strategy + */ + strategy: external_exports.enum([ + "graceful", + // Wait for in-flight requests, then unload + "forceful", + // Unload immediately, cancel pending work + "drain" + // Stop accepting new work, finish existing, then unload + ]).default("graceful").describe("How to handle in-flight work during unload"), + /** + * Timeout for the unload operation in milliseconds + */ + timeout: external_exports.number().int().min(1e3).default(3e4).describe("Maximum time to complete unloading in ms"), + /** + * Whether to remove cached artifacts + */ + cleanupCache: external_exports.boolean().default(false).describe("Remove cached code and assets after unload"), + /** + * Action for dependents: plugins that depend on this one + */ + dependentAction: external_exports.enum([ + "cascade", + // Also unload dependent plugins + "warn", + // Warn about dependents but proceed + "block" + // Block unload if dependents exist + ]).default("block").describe("How to handle plugins that depend on this one") +}).describe("Request to dynamically unload a plugin at runtime"); +var DynamicPluginResultSchema2 = external_exports.object({ + /** + * Whether the operation succeeded + */ + success: external_exports.boolean(), + /** + * The operation that was performed + */ + operation: DynamicPluginOperationSchema2, + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Operation duration in milliseconds + */ + durationMs: external_exports.number().int().min(0).optional(), + /** + * Resulting plugin version (for load/reload) + */ + version: external_exports.string().optional(), + /** + * Error details if operation failed + */ + error: external_exports.object({ + code: external_exports.string().describe("Machine-readable error code"), + message: external_exports.string().describe("Human-readable error message"), + details: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional(), + /** + * Warnings (e.g., dependents affected) + */ + warnings: external_exports.array(external_exports.string()).optional() +}).describe("Result of a dynamic plugin operation"); +var PluginDiscoverySourceSchema2 = external_exports.object({ + /** + * Discovery source type + */ + type: external_exports.enum([ + "registry", + // ObjectStack plugin registry API + "npm", + // npm registry search + "directory", + // Local filesystem directory scan + "url" + // Remote manifest URL + ]).describe("Discovery source type"), + /** + * Source endpoint or path + */ + endpoint: external_exports.string().describe("Registry URL, directory path, or manifest URL"), + /** + * Polling interval in milliseconds (0 = manual only) + */ + pollInterval: external_exports.number().int().min(0).default(0).describe("How often to re-scan for new plugins (0 = manual)"), + /** + * Filter criteria for discovered plugins + */ + filter: external_exports.object({ + /** + * Only discover plugins matching these tags + */ + tags: external_exports.array(external_exports.string()).optional(), + /** + * Only discover plugins from these vendors + */ + vendors: external_exports.array(external_exports.string()).optional(), + /** + * Minimum trust level + */ + minTrustLevel: external_exports.enum(["verified", "trusted", "community", "untrusted"]).optional() + }).optional() +}).describe("Source for runtime plugin discovery"); +var PluginDiscoveryConfigSchema2 = external_exports.object({ + /** + * Enable runtime plugin discovery + */ + enabled: external_exports.boolean().default(false), + /** + * Discovery sources + */ + sources: external_exports.array(PluginDiscoverySourceSchema2).default([]), + /** + * Auto-load discovered plugins matching criteria + */ + autoLoad: external_exports.boolean().default(false).describe("Automatically load newly discovered plugins"), + /** + * Require approval before loading discovered plugins + */ + requireApproval: external_exports.boolean().default(true).describe("Require admin approval before loading discovered plugins") +}).describe("Runtime plugin discovery configuration"); +var DynamicLoadingConfigSchema2 = external_exports.object({ + /** + * Enable dynamic loading/unloading at runtime + */ + enabled: external_exports.boolean().default(false).describe("Enable runtime load/unload of plugins"), + /** + * Maximum number of dynamically loaded plugins + */ + maxDynamicPlugins: external_exports.number().int().min(1).default(50).describe("Upper limit on runtime-loaded plugins"), + /** + * Plugin discovery configuration + */ + discovery: PluginDiscoveryConfigSchema2.optional(), + /** + * Default sandbox policy for dynamically loaded plugins + */ + defaultSandbox: external_exports.boolean().default(true).describe("Sandbox dynamically loaded plugins by default"), + /** + * Allowed plugin sources (empty = all allowed) + */ + allowedSources: external_exports.array(external_exports.enum(["npm", "local", "url", "registry", "git"])).optional().describe("Restrict which source types are permitted"), + /** + * Require integrity verification for remote plugins + */ + requireIntegrity: external_exports.boolean().default(true).describe("Require integrity hash verification for remote sources"), + /** + * Global timeout for dynamic operations in milliseconds + */ + operationTimeout: external_exports.number().int().min(1e3).default(6e4).describe("Default timeout for load/unload operations in ms") +}).describe("Dynamic plugin loading subsystem configuration"); +var PermissionScopeSchema2 = external_exports.enum([ + "global", + // Applies to entire system + "tenant", + // Applies to specific tenant + "user", + // Applies to specific user + "resource", + // Applies to specific resource + "plugin" + // Applies within plugin boundaries +]).describe("Scope of permission application"); +var PermissionActionSchema2 = external_exports.enum([ + "create", + // Create new resources + "read", + // Read existing resources + "update", + // Update existing resources + "delete", + // Delete resources + "execute", + // Execute operations/functions + "manage", + // Full management rights + "configure", + // Configuration changes + "share", + // Share with others + "export", + // Export data + "import", + // Import data + "admin" + // Administrative access +]).describe("Type of action being permitted"); +var ResourceTypeSchema2 = external_exports.enum([ + "data.object", + // ObjectQL objects + "data.record", + // Individual records + "data.field", + // Specific fields + "ui.view", + // UI views + "ui.dashboard", + // Dashboards + "ui.report", + // Reports + "system.config", + // System configuration + "system.plugin", + // Other plugins + "system.api", + // API endpoints + "system.service", + // System services + "storage.file", + // File storage + "storage.database", + // Database access + "network.http", + // HTTP requests + "network.websocket", + // WebSocket connections + "process.spawn", + // Process spawning + "process.env" + // Environment variables +]).describe("Type of resource being accessed"); +var PermissionSchema2 = external_exports.object({ + /** + * Permission identifier + */ + id: external_exports.string().describe("Unique permission identifier"), + /** + * Resource type + */ + resource: ResourceTypeSchema2, + /** + * Allowed actions + */ + actions: external_exports.array(PermissionActionSchema2), + /** + * Permission scope + */ + scope: PermissionScopeSchema2.default("plugin"), + /** + * Resource filter + */ + filter: external_exports.object({ + /** + * Specific resource IDs + */ + resourceIds: external_exports.array(external_exports.string()).optional(), + /** + * Filter condition + */ + condition: external_exports.string().optional().describe("Filter expression (e.g., owner = currentUser)"), + /** + * Field-level access + */ + fields: external_exports.array(external_exports.string()).optional().describe("Allowed fields for data resources") + }).optional(), + /** + * Human-readable description + */ + description: external_exports.string(), + /** + * Whether this permission is required or optional + */ + required: external_exports.boolean().default(true), + /** + * Justification for permission + */ + justification: external_exports.string().optional().describe("Why this permission is needed") +}); +var PermissionSetSchema22 = external_exports.object({ + /** + * All permissions required by plugin + */ + permissions: external_exports.array(PermissionSchema2), + /** + * Permission groups for easier management + */ + groups: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Group name"), + description: external_exports.string(), + permissions: external_exports.array(external_exports.string()).describe("Permission IDs in this group") + })).optional(), + /** + * Default grant strategy + */ + defaultGrant: external_exports.enum([ + "prompt", + // Always prompt user + "allow", + // Allow by default + "deny", + // Deny by default + "inherit" + // Inherit from parent + ]).default("prompt") +}); +var RuntimeConfigSchema2 = external_exports.object({ + /** + * Runtime engine type + */ + engine: external_exports.enum([ + "v8-isolate", + // V8 isolate-based isolation (lightweight, fast) + "wasm", + // WebAssembly-based isolation (secure, portable) + "container", + // Container-based isolation (Docker, podman) + "process" + // Process-based isolation (traditional) + ]).default("v8-isolate").describe("Execution environment engine"), + /** + * Engine-specific configuration + */ + engineConfig: external_exports.object({ + /** + * WASM-specific settings (when engine is "wasm") + */ + wasm: external_exports.object({ + /** + * Maximum memory pages (64KB per page) + */ + maxMemoryPages: external_exports.number().int().min(1).max(65536).optional().describe("Maximum WASM memory pages (64KB each)"), + /** + * Instruction execution limit + */ + instructionLimit: external_exports.number().int().min(1).optional().describe("Maximum instructions before timeout"), + /** + * Enable SIMD instructions + */ + enableSimd: external_exports.boolean().default(false).describe("Enable WebAssembly SIMD support"), + /** + * Enable threads + */ + enableThreads: external_exports.boolean().default(false).describe("Enable WebAssembly threads"), + /** + * Enable bulk memory operations + */ + enableBulkMemory: external_exports.boolean().default(true).describe("Enable bulk memory operations") + }).optional(), + /** + * Container-specific settings (when engine is "container") + */ + container: external_exports.object({ + /** + * Container image + */ + image: external_exports.string().optional().describe("Container image to use"), + /** + * Container runtime + */ + runtime: external_exports.enum(["docker", "podman", "containerd"]).default("docker"), + /** + * Resource limits + */ + resources: external_exports.object({ + cpuLimit: external_exports.string().optional().describe('CPU limit (e.g., "0.5", "2")'), + memoryLimit: external_exports.string().optional().describe('Memory limit (e.g., "512m", "1g")') + }).optional(), + /** + * Network mode + */ + networkMode: external_exports.enum(["none", "bridge", "host"]).default("bridge") + }).optional(), + /** + * V8 Isolate-specific settings (when engine is "v8-isolate") + */ + v8Isolate: external_exports.object({ + /** + * Heap size limit in MB + */ + heapSizeMb: external_exports.number().int().min(1).optional(), + /** + * Enable snapshot + */ + enableSnapshot: external_exports.boolean().default(true) + }).optional() + }).optional(), + /** + * General resource limits (applies to all engines) + */ + resourceLimits: external_exports.object({ + /** + * Maximum memory in bytes + */ + maxMemory: external_exports.number().int().optional().describe("Maximum memory allocation"), + /** + * Maximum CPU percentage + */ + maxCpu: external_exports.number().min(0).max(100).optional().describe("Maximum CPU usage percentage"), + /** + * Execution timeout in milliseconds + */ + timeout: external_exports.number().int().min(0).optional().describe("Maximum execution time") + }).optional() +}); +var SandboxConfigSchema2 = external_exports.object({ + /** + * Enable sandboxing + */ + enabled: external_exports.boolean().default(true), + /** + * Sandboxing level + */ + level: external_exports.enum([ + "none", + // No sandboxing + "minimal", + // Basic isolation + "standard", + // Standard sandboxing + "strict", + // Strict isolation + "paranoid" + // Maximum isolation + ]).default("standard"), + /** + * Runtime environment configuration + */ + runtime: RuntimeConfigSchema2.optional().describe("Execution environment and isolation settings"), + /** + * File system access + */ + filesystem: external_exports.object({ + mode: external_exports.enum(["none", "readonly", "restricted", "full"]).default("restricted"), + allowedPaths: external_exports.array(external_exports.string()).optional().describe("Whitelisted paths"), + deniedPaths: external_exports.array(external_exports.string()).optional().describe("Blacklisted paths"), + maxFileSize: external_exports.number().int().optional().describe("Maximum file size in bytes") + }).optional(), + /** + * Network access + */ + network: external_exports.object({ + mode: external_exports.enum(["none", "local", "restricted", "full"]).default("restricted"), + allowedHosts: external_exports.array(external_exports.string()).optional().describe("Whitelisted hosts"), + deniedHosts: external_exports.array(external_exports.string()).optional().describe("Blacklisted hosts"), + allowedPorts: external_exports.array(external_exports.number()).optional().describe("Allowed port numbers"), + maxConnections: external_exports.number().int().optional() + }).optional(), + /** + * Process execution + */ + process: external_exports.object({ + allowSpawn: external_exports.boolean().default(false).describe("Allow spawning child processes"), + allowedCommands: external_exports.array(external_exports.string()).optional().describe("Whitelisted commands"), + timeout: external_exports.number().int().optional().describe("Process timeout in ms") + }).optional(), + /** + * Memory limits + */ + memory: external_exports.object({ + maxHeap: external_exports.number().int().optional().describe("Maximum heap size in bytes"), + maxStack: external_exports.number().int().optional().describe("Maximum stack size in bytes") + }).optional(), + /** + * CPU limits + */ + cpu: external_exports.object({ + maxCpuPercent: external_exports.number().min(0).max(100).optional(), + maxThreads: external_exports.number().int().optional() + }).optional(), + /** + * Environment variables + */ + environment: external_exports.object({ + mode: external_exports.enum(["none", "readonly", "restricted", "full"]).default("readonly"), + allowedVars: external_exports.array(external_exports.string()).optional(), + deniedVars: external_exports.array(external_exports.string()).optional() + }).optional() +}); +var KernelSecurityVulnerabilitySchema2 = external_exports.object({ + /** + * CVE identifier + */ + cve: external_exports.string().optional(), + /** + * Vulnerability identifier + */ + id: external_exports.string(), + /** + * Severity level + */ + severity: external_exports.enum(["critical", "high", "medium", "low", "info"]), + /** + * Category (e.g., SAST, DAST, Dependency) + */ + category: external_exports.string().optional(), + /** + * Title + */ + title: external_exports.string(), + /** + * Location of the vulnerability + */ + location: external_exports.string().optional(), + /** + * Remediation steps + */ + remediation: external_exports.string().optional(), + /** + * Description + */ + description: external_exports.string(), + /** + * Affected versions + */ + affectedVersions: external_exports.array(external_exports.string()), + /** + * Fixed in versions + */ + fixedIn: external_exports.array(external_exports.string()).optional(), + /** + * CVSS score + */ + cvssScore: external_exports.number().min(0).max(10).optional(), + /** + * Exploit availability + */ + exploitAvailable: external_exports.boolean().default(false), + /** + * Patch available + */ + patchAvailable: external_exports.boolean().default(false), + /** + * Workaround + */ + workaround: external_exports.string().optional(), + /** + * References + */ + references: external_exports.array(external_exports.string()).optional(), + /** + * Discovered date + */ + discoveredDate: external_exports.string().datetime().optional(), + /** + * Published date + */ + publishedDate: external_exports.string().datetime().optional() +}); +var KernelSecurityScanResultSchema2 = external_exports.object({ + /** + * Scan timestamp + */ + timestamp: external_exports.string().datetime(), + /** + * Scanner information + */ + scanner: external_exports.object({ + name: external_exports.string(), + version: external_exports.string() + }), + /** + * Overall status + */ + status: external_exports.enum(["passed", "failed", "warning"]), + /** + * Vulnerabilities found + */ + vulnerabilities: external_exports.array(KernelSecurityVulnerabilitySchema2).optional(), + /** + * Code quality issues + */ + codeIssues: external_exports.array(external_exports.object({ + severity: external_exports.enum(["error", "warning", "info"]), + type: external_exports.string().describe("Issue type (e.g., sql-injection, xss)"), + file: external_exports.string(), + line: external_exports.number().int().optional(), + message: external_exports.string(), + suggestion: external_exports.string().optional() + })).optional(), + /** + * Dependency vulnerabilities + */ + dependencyVulnerabilities: external_exports.array(external_exports.object({ + package: external_exports.string(), + version: external_exports.string(), + vulnerability: KernelSecurityVulnerabilitySchema2 + })).optional(), + /** + * License compliance + */ + licenseCompliance: external_exports.object({ + status: external_exports.enum(["compliant", "non-compliant", "unknown"]), + issues: external_exports.array(external_exports.object({ + package: external_exports.string(), + license: external_exports.string(), + reason: external_exports.string() + })).optional() + }).optional(), + /** + * Summary statistics + */ + summary: external_exports.object({ + totalVulnerabilities: external_exports.number().int(), + criticalCount: external_exports.number().int(), + highCount: external_exports.number().int(), + mediumCount: external_exports.number().int(), + lowCount: external_exports.number().int(), + infoCount: external_exports.number().int() + }) +}); +var KernelSecurityPolicySchema2 = external_exports.object({ + /** + * Content Security Policy + */ + csp: external_exports.object({ + directives: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional(), + reportOnly: external_exports.boolean().default(false) + }).optional(), + /** + * CORS policy + */ + cors: external_exports.object({ + allowedOrigins: external_exports.array(external_exports.string()), + allowedMethods: external_exports.array(external_exports.string()), + allowedHeaders: external_exports.array(external_exports.string()), + allowCredentials: external_exports.boolean().default(false), + maxAge: external_exports.number().int().optional() + }).optional(), + /** + * Rate limiting + */ + rateLimit: external_exports.object({ + enabled: external_exports.boolean().default(true), + maxRequests: external_exports.number().int(), + windowMs: external_exports.number().int().describe("Time window in milliseconds"), + strategy: external_exports.enum(["fixed", "sliding", "token-bucket"]).default("sliding") + }).optional(), + /** + * Authentication requirements + */ + authentication: external_exports.object({ + required: external_exports.boolean().default(true), + methods: external_exports.array(external_exports.enum(["jwt", "oauth2", "api-key", "session", "certificate"])), + tokenExpiration: external_exports.number().int().optional().describe("Token expiration in seconds") + }).optional(), + /** + * Encryption requirements + */ + encryption: external_exports.object({ + dataAtRest: external_exports.boolean().default(false).describe("Encrypt data at rest"), + dataInTransit: external_exports.boolean().default(true).describe("Enforce HTTPS/TLS"), + algorithm: external_exports.string().optional().describe("Encryption algorithm"), + minKeyLength: external_exports.number().int().optional().describe("Minimum key length in bits") + }).optional(), + /** + * Audit logging + */ + auditLog: external_exports.object({ + enabled: external_exports.boolean().default(true), + events: external_exports.array(external_exports.string()).optional().describe("Events to log"), + retention: external_exports.number().int().optional().describe("Log retention in days") + }).optional() +}); +var PluginTrustLevelSchema2 = external_exports.enum([ + "verified", + // Official/verified plugin + "trusted", + // Trusted third-party + "community", + // Community plugin + "untrusted", + // Unverified plugin + "blocked" + // Blocked/malicious +]).describe("Trust level of the plugin"); +var PluginSecurityManifestSchema2 = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Trust level + */ + trustLevel: PluginTrustLevelSchema2, + /** + * Required permissions + */ + permissions: PermissionSetSchema22, + /** + * Sandbox configuration + */ + sandbox: SandboxConfigSchema2, + /** + * Security policy + */ + policy: KernelSecurityPolicySchema2.optional(), + /** + * Security scan results + */ + scanResults: external_exports.array(KernelSecurityScanResultSchema2).optional(), + /** + * Known vulnerabilities + */ + vulnerabilities: external_exports.array(KernelSecurityVulnerabilitySchema2).optional(), + /** + * Code signing + */ + codeSigning: external_exports.object({ + signed: external_exports.boolean(), + signature: external_exports.string().optional(), + certificate: external_exports.string().optional(), + algorithm: external_exports.string().optional(), + timestamp: external_exports.string().datetime().optional() + }).optional(), + /** + * Security certifications + */ + certifications: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Certification name (e.g., SOC 2, ISO 27001)"), + issuer: external_exports.string(), + issuedDate: external_exports.string().datetime(), + expiryDate: external_exports.string().datetime().optional(), + certificateUrl: external_exports.string().url().optional() + })).optional(), + /** + * Security contact + */ + securityContact: external_exports.object({ + email: external_exports.string().email().optional(), + url: external_exports.string().url().optional(), + pgpKey: external_exports.string().optional() + }).optional(), + /** + * Vulnerability disclosure policy + */ + vulnerabilityDisclosure: external_exports.object({ + policyUrl: external_exports.string().url().optional(), + responseTime: external_exports.number().int().optional().describe("Expected response time in hours"), + bugBounty: external_exports.boolean().default(false) + }).optional() +}); +var SNAKE_CASE_REGEX2 = /^[a-z][a-z0-9_]*$/; +var OpsFilePathSchema2 = external_exports.string().describe("Validates a file path against OPS naming conventions").superRefine((path3, ctx) => { + if (!path3.startsWith("src/")) { + return; + } + const parts = path3.split("/"); + if (parts.length > 2) { + const domainDir = parts[1]; + if (!SNAKE_CASE_REGEX2.test(domainDir)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Domain directory '${domainDir}' must be lowercase snake_case` + }); + } + } + const filename = parts[parts.length - 1]; + if (filename === "index.ts" || filename === "main.ts") return; + if (!SNAKE_CASE_REGEX2.test(filename.split(".")[0])) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Filename '${filename}' base name must be lowercase snake_case` + }); + } +}); +var OpsDomainModuleSchema2 = external_exports.object({ + name: external_exports.string().regex(SNAKE_CASE_REGEX2).describe("Module name (snake_case)"), + files: external_exports.array(external_exports.string()).describe("List of files in this module"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") +}).describe("Scanned domain module representing a plugin folder").superRefine((module, ctx) => { + if (!module.files.includes("index.ts")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Module '${module.name}' is missing an 'index.ts' entry point.` + }); + } +}); +var OpsPluginStructureSchema2 = external_exports.object({ + root: external_exports.string().describe("Root directory path of the plugin project"), + files: external_exports.array(external_exports.string()).describe("List of all file paths relative to root"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") +}).describe("Full plugin project layout validated against OPS conventions").superRefine((project, ctx) => { + if (!project.files.includes("objectstack.config.ts")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "Missing 'objectstack.config.ts' configuration file." + }); + } + project.files.filter((f) => f.startsWith("src/")).forEach((file2) => { + const result = OpsFilePathSchema2.safeParse(file2); + if (!result.success) { + result.error.issues.forEach((issue2) => { + ctx.addIssue({ ...issue2, path: [file2] }); + }); + } + }); +}); +var ValidationErrorSchema2 = external_exports.object({ + /** + * Field that failed validation + */ + field: external_exports.string().describe("Field name that failed validation"), + /** + * Human-readable error message + */ + message: external_exports.string().describe("Human-readable error message"), + /** + * Machine-readable error code (optional) + */ + code: external_exports.string().optional().describe("Machine-readable error code") +}); +var ValidationWarningSchema2 = external_exports.object({ + /** + * Field with warning + */ + field: external_exports.string().describe("Field name with warning"), + /** + * Human-readable warning message + */ + message: external_exports.string().describe("Human-readable warning message"), + /** + * Machine-readable warning code (optional) + */ + code: external_exports.string().optional().describe("Machine-readable warning code") +}); +var ValidationResultSchema2 = external_exports.object({ + /** + * Whether validation passed + */ + valid: external_exports.boolean().describe("Whether the plugin passed validation"), + /** + * Validation errors (if any) + */ + errors: external_exports.array(ValidationErrorSchema2).optional().describe("Validation errors"), + /** + * Validation warnings (non-fatal issues) + */ + warnings: external_exports.array(ValidationWarningSchema2).optional().describe("Validation warnings") +}); +var PluginMetadataSchema2 = external_exports.object({ + /** + * Unique plugin identifier (snake_case) + */ + name: external_exports.string().min(1).describe("Unique plugin identifier"), + /** + * Plugin version (semver) + */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic version (e.g., 1.0.0)"), + /** + * Plugin dependencies (array of plugin names) + */ + dependencies: external_exports.array(external_exports.string()).optional().describe("Array of plugin names this plugin depends on"), + /** + * Plugin signature for cryptographic verification (optional) + */ + signature: external_exports.string().optional().describe("Cryptographic signature for plugin verification") + /** + * Additional plugin metadata + */ +}).passthrough().describe("Plugin metadata for validation"); +var SemanticVersionSchema2 = external_exports.object({ + major: external_exports.number().int().min(0).describe("Major version (breaking changes)"), + minor: external_exports.number().int().min(0).describe("Minor version (backward compatible features)"), + patch: external_exports.number().int().min(0).describe("Patch version (backward compatible fixes)"), + preRelease: external_exports.string().optional().describe("Pre-release identifier (alpha, beta, rc.1)"), + build: external_exports.string().optional().describe("Build metadata") +}).describe("Semantic version number"); +var VersionConstraintSchema2 = external_exports.union([ + external_exports.string().regex(/^[\d.]+$/).describe("Exact version: `1.2.3`"), + external_exports.string().regex(/^\^[\d.]+$/).describe("Compatible with: `^1.2.3` (`>=1.2.3 <2.0.0`)"), + external_exports.string().regex(/^~[\d.]+$/).describe("Approximately: `~1.2.3` (`>=1.2.3 <1.3.0`)"), + external_exports.string().regex(/^>=[\d.]+$/).describe("Greater than or equal: `>=1.2.3`"), + external_exports.string().regex(/^>[\d.]+$/).describe("Greater than: `>1.2.3`"), + external_exports.string().regex(/^<=[\d.]+$/).describe("Less than or equal: `<=1.2.3`"), + external_exports.string().regex(/^<[\d.]+$/).describe("Less than: `<1.2.3`"), + external_exports.string().regex(/^[\d.]+ - [\d.]+$/).describe("Range: `1.2.3 - 2.3.4`"), + external_exports.literal("*").describe("Any version"), + external_exports.literal("latest").describe("Latest stable version") +]); +var CompatibilityLevelSchema2 = external_exports.enum([ + "fully-compatible", + // 100% compatible, drop-in replacement + "backward-compatible", + // Backward compatible, new features added + "deprecated-compatible", + // Compatible but uses deprecated features + "breaking-changes", + // Breaking changes, migration required + "incompatible" + // Completely incompatible +]).describe("Compatibility level between versions"); +var BreakingChangeSchema2 = external_exports.object({ + /** + * Version where the change was introduced + */ + introducedIn: external_exports.string().describe("Version that introduced this breaking change"), + /** + * Type of breaking change + */ + type: external_exports.enum([ + "api-removed", + // API removed + "api-renamed", + // API renamed + "api-signature-changed", + // Function signature changed + "behavior-changed", + // Behavior changed + "dependency-changed", + // Dependency requirement changed + "configuration-changed", + // Configuration schema changed + "protocol-changed" + // Protocol implementation changed + ]), + /** + * What was changed + */ + description: external_exports.string(), + /** + * Migration guide + */ + migrationGuide: external_exports.string().optional().describe("How to migrate from old to new"), + /** + * Deprecated in version + */ + deprecatedIn: external_exports.string().optional().describe("Version where old API was deprecated"), + /** + * Will be removed in version + */ + removedIn: external_exports.string().optional().describe("Version where old API will be removed"), + /** + * Automated migration available + */ + automatedMigration: external_exports.boolean().default(false).describe("Whether automated migration tool is available"), + /** + * Impact severity + */ + severity: external_exports.enum(["critical", "major", "minor"]).describe("Impact severity") +}); +var DeprecationNoticeSchema2 = external_exports.object({ + /** + * Feature or API being deprecated + */ + feature: external_exports.string().describe("Deprecated feature identifier"), + /** + * Version when deprecated + */ + deprecatedIn: external_exports.string(), + /** + * Planned removal version + */ + removeIn: external_exports.string().optional(), + /** + * Reason for deprecation + */ + reason: external_exports.string(), + /** + * Recommended alternative + */ + alternative: external_exports.string().optional().describe("What to use instead"), + /** + * Migration path + */ + migrationPath: external_exports.string().optional().describe("How to migrate to alternative") +}); +var CompatibilityMatrixEntrySchema2 = external_exports.object({ + /** + * Source version + */ + from: external_exports.string().describe("Version being upgraded from"), + /** + * Target version + */ + to: external_exports.string().describe("Version being upgraded to"), + /** + * Compatibility level + */ + compatibility: CompatibilityLevelSchema2, + /** + * Breaking changes list + */ + breakingChanges: external_exports.array(BreakingChangeSchema2).optional(), + /** + * Migration required + */ + migrationRequired: external_exports.boolean().default(false), + /** + * Migration complexity + */ + migrationComplexity: external_exports.enum(["trivial", "simple", "moderate", "complex", "major"]).optional(), + /** + * Estimated migration time in hours + */ + estimatedMigrationTime: external_exports.number().optional(), + /** + * Migration script available + */ + migrationScript: external_exports.string().optional().describe("Path to migration script"), + /** + * Test coverage for migration + */ + testCoverage: external_exports.number().min(0).max(100).optional().describe("Percentage of migration covered by tests") +}); +var PluginCompatibilityMatrixSchema2 = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Current version + */ + currentVersion: external_exports.string(), + /** + * Compatibility entries + */ + compatibilityMatrix: external_exports.array(CompatibilityMatrixEntrySchema2), + /** + * Supported versions + */ + supportedVersions: external_exports.array(external_exports.object({ + version: external_exports.string(), + supported: external_exports.boolean(), + endOfLife: external_exports.string().datetime().optional().describe("End of support date"), + securitySupport: external_exports.boolean().default(false).describe("Still receives security updates") + })), + /** + * Minimum compatible version + */ + minimumCompatibleVersion: external_exports.string().optional().describe("Oldest version that can be directly upgraded") +}); +var DependencyConflictSchema2 = external_exports.object({ + /** + * Type of conflict + */ + type: external_exports.enum([ + "version-mismatch", + // Different versions required + "missing-dependency", + // Required dependency not found + "circular-dependency", + // Circular dependency detected + "incompatible-versions", + // Incompatible versions required by different plugins + "conflicting-interfaces" + // Plugins implement conflicting interfaces + ]), + /** + * Plugins involved in conflict + */ + plugins: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + version: external_exports.string(), + requirement: external_exports.string().optional().describe("What this plugin requires") + })), + /** + * Conflict description + */ + description: external_exports.string(), + /** + * Possible resolutions + */ + resolutions: external_exports.array(external_exports.object({ + strategy: external_exports.enum([ + "upgrade", + // Upgrade one or more plugins + "downgrade", + // Downgrade one or more plugins + "replace", + // Replace with alternative plugin + "disable", + // Disable conflicting plugin + "manual" + // Manual intervention required + ]), + description: external_exports.string(), + automaticResolution: external_exports.boolean().default(false), + riskLevel: external_exports.enum(["low", "medium", "high"]) + })).optional(), + /** + * Severity of conflict + */ + severity: external_exports.enum(["critical", "error", "warning", "info"]) +}); +var PluginDependencyResolutionResultSchema2 = external_exports.object({ + /** + * Resolution successful + */ + success: external_exports.boolean(), + /** + * Resolved plugin versions + */ + resolved: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + version: external_exports.string(), + resolvedVersion: external_exports.string() + })).optional(), + /** + * Conflicts found + */ + conflicts: external_exports.array(DependencyConflictSchema2).optional(), + /** + * Warnings + */ + warnings: external_exports.array(external_exports.string()).optional(), + /** + * Installation order (topologically sorted) + */ + installationOrder: external_exports.array(external_exports.string()).optional().describe("Plugin IDs in order they should be installed"), + /** + * Dependency graph + */ + dependencyGraph: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional().describe("Map of plugin ID to its dependencies") +}); +var MultiVersionSupportSchema2 = external_exports.object({ + /** + * Enable multi-version support + */ + enabled: external_exports.boolean().default(false), + /** + * Maximum concurrent versions + */ + maxConcurrentVersions: external_exports.number().int().min(1).default(2).describe("How many versions can run at the same time"), + /** + * Version selection strategy + */ + selectionStrategy: external_exports.enum([ + "latest", + // Always use latest version + "stable", + // Use latest stable version + "compatible", + // Use version compatible with dependencies + "pinned", + // Use pinned version + "canary", + // Use canary/preview version + "custom" + // Custom selection logic + ]).default("latest"), + /** + * Version routing rules + */ + routing: external_exports.array(external_exports.object({ + condition: external_exports.string().describe("Routing condition (e.g., tenant, user, feature flag)"), + version: external_exports.string().describe("Version to use when condition matches"), + priority: external_exports.number().int().default(100).describe("Rule priority") + })).optional(), + /** + * Gradual rollout configuration + */ + rollout: external_exports.object({ + enabled: external_exports.boolean().default(false), + strategy: external_exports.enum(["percentage", "blue-green", "canary"]), + percentage: external_exports.number().min(0).max(100).optional().describe("Percentage of traffic to new version"), + duration: external_exports.number().int().optional().describe("Rollout duration in milliseconds") + }).optional() +}); +var PluginVersionMetadataSchema2 = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Version number + */ + version: SemanticVersionSchema2, + /** + * Version string (computed) + */ + versionString: external_exports.string().describe("Full version string (e.g., 1.2.3-beta.1+build.123)"), + /** + * Release date + */ + releaseDate: external_exports.string().datetime(), + /** + * Release notes + */ + releaseNotes: external_exports.string().optional(), + /** + * Breaking changes + */ + breakingChanges: external_exports.array(BreakingChangeSchema2).optional(), + /** + * Deprecations + */ + deprecations: external_exports.array(DeprecationNoticeSchema2).optional(), + /** + * Compatibility matrix + */ + compatibilityMatrix: external_exports.array(CompatibilityMatrixEntrySchema2).optional(), + /** + * Security vulnerabilities fixed + */ + securityFixes: external_exports.array(external_exports.object({ + cve: external_exports.string().optional().describe("CVE identifier"), + severity: external_exports.enum(["critical", "high", "medium", "low"]), + description: external_exports.string(), + fixedIn: external_exports.string().describe("Version where vulnerability was fixed") + })).optional(), + /** + * Download statistics + */ + statistics: external_exports.object({ + downloads: external_exports.number().int().min(0).optional(), + installations: external_exports.number().int().min(0).optional(), + ratings: external_exports.number().min(0).max(5).optional() + }).optional(), + /** + * Support status + */ + support: external_exports.object({ + status: external_exports.enum(["active", "maintenance", "deprecated", "eol"]), + endOfLife: external_exports.string().datetime().optional(), + securitySupport: external_exports.boolean().default(true) + }) +}); +var ServiceScopeType2 = external_exports.enum([ + "singleton", + // Single instance shared across the application + "transient", + // New instance created each time + "scoped" + // Instance per scope (request, session, transaction, etc.) +]).describe("Service scope type"); +var ServiceMetadataSchema2 = external_exports.object({ + /** + * Service name (unique identifier) + */ + name: external_exports.string().min(1).describe("Unique service name identifier"), + /** + * Service scope type + */ + scope: ServiceScopeType2.optional().default("singleton").describe("Service scope type"), + /** + * Service type or interface name (optional) + */ + type: external_exports.string().optional().describe("Service type or interface name"), + /** + * Registration timestamp (Unix milliseconds) + */ + registeredAt: external_exports.number().int().optional().describe("Unix timestamp in milliseconds when service was registered"), + /** + * Additional metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional service-specific metadata") +}); +var ServiceRegistryConfigSchema2 = external_exports.object({ + /** + * Strict mode: throw errors on invalid operations + * @default true + */ + strictMode: external_exports.boolean().optional().default(true).describe("Throw errors on invalid operations (duplicate registration, service not found, etc.)"), + /** + * Allow overwriting existing services + * @default false + */ + allowOverwrite: external_exports.boolean().optional().default(false).describe("Allow overwriting existing service registrations"), + /** + * Enable logging for service operations + * @default false + */ + enableLogging: external_exports.boolean().optional().default(false).describe("Enable logging for service registration and retrieval"), + /** + * Custom scope types (beyond singleton, transient, scoped) + * @default ['singleton', 'transient', 'scoped'] + */ + scopeTypes: external_exports.array(external_exports.string()).optional().describe("Supported scope types"), + /** + * Maximum number of services (prevent memory leaks) + */ + maxServices: external_exports.number().int().min(1).optional().describe("Maximum number of services that can be registered") +}); +var ServiceFactoryRegistrationSchema2 = external_exports.object({ + /** + * Service name (unique identifier) + */ + name: external_exports.string().min(1).describe("Unique service name identifier"), + /** + * Service scope type + */ + scope: ServiceScopeType2.optional().default("singleton").describe("Service scope type"), + /** + * Factory type (sync or async) + */ + factoryType: external_exports.enum(["sync", "async"]).optional().default("sync").describe("Whether factory is synchronous or asynchronous"), + /** + * Whether this is a singleton (cache factory result) + */ + singleton: external_exports.boolean().optional().default(true).describe("Whether to cache the factory result (singleton pattern)") +}); +var ScopeConfigSchema2 = external_exports.object({ + /** + * Type of scope (request, session, transaction, etc.) + */ + scopeType: external_exports.string().describe("Type of scope"), + /** + * Scope identifier (optional, auto-generated if not provided) + */ + scopeId: external_exports.string().optional().describe("Unique scope identifier"), + /** + * Scope metadata (context information) + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Scope-specific context metadata") +}); +var ScopeInfoSchema2 = external_exports.object({ + /** + * Scope identifier + */ + scopeId: external_exports.string().describe("Unique scope identifier"), + /** + * Type of scope + */ + scopeType: external_exports.string().describe("Type of scope"), + /** + * Creation timestamp (Unix milliseconds) + */ + createdAt: external_exports.number().int().describe("Unix timestamp in milliseconds when scope was created"), + /** + * Number of services in this scope + */ + serviceCount: external_exports.number().int().min(0).optional().describe("Number of services registered in this scope"), + /** + * Scope metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Scope-specific context metadata") +}); +var StartupOptionsSchema2 = external_exports.object({ + /** + * Maximum time (ms) to wait for each plugin to start + * @default 30000 (30 seconds) + */ + timeout: external_exports.number().int().min(0).optional().default(3e4).describe("Maximum time in milliseconds to wait for each plugin to start"), + /** + * Whether to rollback (destroy) already-started plugins on failure + * @default true + */ + rollbackOnFailure: external_exports.boolean().optional().default(true).describe("Whether to rollback already-started plugins if any plugin fails"), + /** + * Whether to run health checks after startup + * @default false + */ + healthCheck: external_exports.boolean().optional().default(false).describe("Whether to run health checks after plugin startup"), + /** + * Whether to run plugins in parallel (if dependencies allow) + * @default false (sequential startup) + */ + parallel: external_exports.boolean().optional().default(false).describe("Whether to start plugins in parallel when dependencies allow"), + /** + * Custom context to pass to plugin lifecycle methods + */ + context: external_exports.unknown().optional().describe("Custom context object to pass to plugin lifecycle methods") +}); +var HealthStatusSchema2 = external_exports.object({ + /** + * Whether the plugin is healthy + */ + healthy: external_exports.boolean().describe("Whether the plugin is healthy"), + /** + * Health check timestamp (Unix milliseconds) + */ + timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds when health check was performed"), + /** + * Optional health details (plugin-specific) + */ + details: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Optional plugin-specific health details"), + /** + * Optional error message if unhealthy + */ + message: external_exports.string().optional().describe("Error message if plugin is unhealthy") +}); +var PluginStartupResultSchema2 = external_exports.object({ + /** + * Plugin that was started + */ + plugin: external_exports.object({ + name: external_exports.string(), + version: external_exports.string().optional() + }).passthrough().describe("Plugin metadata"), + /** + * Whether startup was successful + */ + success: external_exports.boolean().describe("Whether the plugin started successfully"), + /** + * Time taken to start (milliseconds) + */ + duration: external_exports.number().min(0).describe("Time taken to start the plugin in milliseconds"), + /** + * Error if startup failed + */ + error: external_exports.object({ + name: external_exports.string().describe("Error class name"), + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Stack trace"), + code: external_exports.string().optional().describe("Error code") + }).optional().describe("Serializable error representation if startup failed"), + /** + * Health status after startup (if healthCheck enabled) + */ + health: HealthStatusSchema2.optional().describe("Health status after startup if health check was enabled") +}); +var StartupOrchestrationResultSchema2 = external_exports.object({ + /** + * Individual plugin startup results + */ + results: external_exports.array(PluginStartupResultSchema2).describe("Startup results for each plugin"), + /** + * Total time taken for all plugins (milliseconds) + */ + totalDuration: external_exports.number().min(0).describe("Total time taken for all plugins in milliseconds"), + /** + * Whether all plugins started successfully + */ + allSuccessful: external_exports.boolean().describe("Whether all plugins started successfully"), + /** + * Plugins that were rolled back (if rollbackOnFailure was enabled) + */ + rolledBack: external_exports.array(external_exports.string()).optional().describe("Names of plugins that were rolled back") +}); +var PluginVendorSchema2 = external_exports.object({ + /** + * Vendor identifier (reverse domain notation) + * Example: "com.acme", "org.apache", "com.objectstack" + */ + id: external_exports.string().regex(/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)+$/).describe("Vendor identifier (reverse domain)"), + /** + * Vendor display name + */ + name: external_exports.string(), + /** + * Vendor website + */ + website: external_exports.string().url().optional(), + /** + * Contact email + */ + email: external_exports.string().email().optional(), + /** + * Verification status + */ + verified: external_exports.boolean().default(false).describe("Whether vendor is verified by ObjectStack"), + /** + * Trust level + */ + trustLevel: external_exports.enum(["official", "verified", "community", "unverified"]).default("unverified") +}); +var PluginQualityMetricsSchema2 = external_exports.object({ + /** + * Test coverage percentage + */ + testCoverage: external_exports.number().min(0).max(100).optional(), + /** + * Documentation score (0-100) + */ + documentationScore: external_exports.number().min(0).max(100).optional(), + /** + * Code quality score (0-100) + */ + codeQuality: external_exports.number().min(0).max(100).optional(), + /** + * Security scan status + */ + securityScan: external_exports.object({ + lastScanDate: external_exports.string().datetime().optional(), + vulnerabilities: external_exports.object({ + critical: external_exports.number().int().min(0).default(0), + high: external_exports.number().int().min(0).default(0), + medium: external_exports.number().int().min(0).default(0), + low: external_exports.number().int().min(0).default(0) + }).optional(), + passed: external_exports.boolean().default(false) + }).optional(), + /** + * Conformance test results + */ + conformanceTests: external_exports.array(external_exports.object({ + protocolId: external_exports.string().describe("Protocol being tested"), + passed: external_exports.boolean(), + totalTests: external_exports.number().int().min(0), + passedTests: external_exports.number().int().min(0), + lastRunDate: external_exports.string().datetime().optional() + })).optional() +}); +var PluginStatisticsSchema2 = external_exports.object({ + /** + * Total downloads + */ + downloads: external_exports.number().int().min(0).default(0), + /** + * Downloads in the last 30 days + */ + downloadsLastMonth: external_exports.number().int().min(0).default(0), + /** + * Number of active installations + */ + activeInstallations: external_exports.number().int().min(0).default(0), + /** + * User ratings + */ + ratings: external_exports.object({ + average: external_exports.number().min(0).max(5).default(0), + count: external_exports.number().int().min(0).default(0), + distribution: external_exports.object({ + "5": external_exports.number().int().min(0).default(0), + "4": external_exports.number().int().min(0).default(0), + "3": external_exports.number().int().min(0).default(0), + "2": external_exports.number().int().min(0).default(0), + "1": external_exports.number().int().min(0).default(0) + }).optional() + }).optional(), + /** + * GitHub stars (if open source) + */ + stars: external_exports.number().int().min(0).optional(), + /** + * Number of dependent plugins + */ + dependents: external_exports.number().int().min(0).default(0) +}); +var PluginRegistryEntrySchema2 = external_exports.object({ + /** + * Plugin identifier (must match manifest.id) + */ + id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Plugin identifier (reverse domain notation)"), + /** + * Current version + */ + version: external_exports.string().regex(/^\d+\.\d+\.\d+$/), + /** + * Plugin display name + */ + name: external_exports.string(), + /** + * Short description + */ + description: external_exports.string().optional(), + /** + * Detailed documentation/README + */ + readme: external_exports.string().optional(), + /** + * Plugin type/category + */ + category: external_exports.enum([ + "data", + // Data management, storage, databases + "integration", + // External service integrations + "ui", + // UI components and themes + "analytics", + // Analytics and reporting + "security", + // Security, auth, compliance + "automation", + // Workflows and automation + "ai", + // AI/ML capabilities + "utility", + // General utilities + "driver", + // Database/storage drivers + "gateway", + // API gateways + "adapter" + // Runtime adapters + ]).optional(), + /** + * Tags for categorization + */ + tags: external_exports.array(external_exports.string()).optional(), + /** + * Vendor information + */ + vendor: PluginVendorSchema2, + /** + * Capability manifest (what the plugin implements/provides) + */ + capabilities: PluginCapabilityManifestSchema3.optional(), + /** + * Compatibility information + */ + compatibility: external_exports.object({ + /** + * Minimum ObjectStack version required + */ + minObjectStackVersion: external_exports.string().optional(), + /** + * Maximum ObjectStack version supported + */ + maxObjectStackVersion: external_exports.string().optional(), + /** + * Node.js version requirement + */ + nodeVersion: external_exports.string().optional(), + /** + * Supported platforms + */ + platforms: external_exports.array(external_exports.enum(["linux", "darwin", "win32", "browser"])).optional() + }).optional(), + /** + * Links and resources + */ + links: external_exports.object({ + homepage: external_exports.string().url().optional(), + repository: external_exports.string().url().optional(), + documentation: external_exports.string().url().optional(), + bugs: external_exports.string().url().optional(), + changelog: external_exports.string().url().optional() + }).optional(), + /** + * Media assets + */ + media: external_exports.object({ + icon: external_exports.string().url().optional(), + logo: external_exports.string().url().optional(), + screenshots: external_exports.array(external_exports.string().url()).optional(), + video: external_exports.string().url().optional() + }).optional(), + /** + * Quality metrics + */ + quality: PluginQualityMetricsSchema2.optional(), + /** + * Usage statistics + */ + statistics: PluginStatisticsSchema2.optional(), + /** + * License information + */ + license: external_exports.string().optional().describe("SPDX license identifier"), + /** + * Pricing (if commercial) + */ + pricing: external_exports.object({ + model: external_exports.enum(["free", "freemium", "paid", "enterprise"]), + price: external_exports.number().min(0).optional(), + currency: external_exports.string().default("USD").optional(), + billingPeriod: external_exports.enum(["one-time", "monthly", "yearly"]).optional() + }).optional(), + /** + * Publication dates + */ + publishedAt: external_exports.string().datetime().optional(), + updatedAt: external_exports.string().datetime().optional(), + /** + * Deprecation status + */ + deprecated: external_exports.boolean().default(false), + deprecationMessage: external_exports.string().optional(), + replacedBy: external_exports.string().optional().describe("Plugin ID that replaces this one"), + /** + * Feature flags + */ + flags: external_exports.object({ + experimental: external_exports.boolean().default(false), + beta: external_exports.boolean().default(false), + featured: external_exports.boolean().default(false), + verified: external_exports.boolean().default(false) + }).optional() +}); +var PluginSearchFiltersSchema2 = external_exports.object({ + /** + * Search query + */ + query: external_exports.string().optional(), + /** + * Filter by category + */ + category: external_exports.array(external_exports.string()).optional(), + /** + * Filter by tags + */ + tags: external_exports.array(external_exports.string()).optional(), + /** + * Filter by vendor trust level + */ + trustLevel: external_exports.array(external_exports.enum(["official", "verified", "community", "unverified"])).optional(), + /** + * Filter by protocols implemented + */ + implementsProtocols: external_exports.array(external_exports.string()).optional(), + /** + * Filter by pricing model + */ + pricingModel: external_exports.array(external_exports.enum(["free", "freemium", "paid", "enterprise"])).optional(), + /** + * Minimum rating + */ + minRating: external_exports.number().min(0).max(5).optional(), + /** + * Sort options + */ + sortBy: external_exports.enum([ + "relevance", + "downloads", + "rating", + "updated", + "name" + ]).optional(), + /** + * Sort order + */ + sortOrder: external_exports.enum(["asc", "desc"]).default("desc").optional(), + /** + * Pagination + */ + page: external_exports.number().int().min(1).default(1).optional(), + limit: external_exports.number().int().min(1).max(100).default(20).optional() +}); +var PluginInstallConfigSchema2 = external_exports.object({ + /** + * Plugin identifier to install + */ + pluginId: external_exports.string(), + /** + * Version to install (supports semver ranges) + */ + version: external_exports.string().optional().describe("Defaults to latest"), + /** + * Plugin-specific configuration values + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Whether to auto-update + */ + autoUpdate: external_exports.boolean().default(false).optional(), + /** + * Installation options + */ + options: external_exports.object({ + /** + * Skip dependency installation + */ + skipDependencies: external_exports.boolean().default(false).optional(), + /** + * Force reinstall + */ + force: external_exports.boolean().default(false).optional(), + /** + * Installation target + */ + target: external_exports.enum(["system", "space", "user"]).default("space").optional() + }).optional() +}); +var VulnerabilitySeverity2 = external_exports.enum([ + "critical", + "high", + "medium", + "low", + "info" +]).describe("Severity level of a security vulnerability"); +var SecurityVulnerabilitySchema2 = external_exports.object({ + /** + * CVE identifier (if applicable) + */ + cve: external_exports.string().regex(/^CVE-\d{4}-\d+$/).optional().describe("CVE identifier"), + /** + * Vulnerability identifier (GHSA, SNYK, etc.) + */ + id: external_exports.string().describe("Vulnerability ID"), + /** + * Title + */ + title: external_exports.string().describe("Short title summarizing the vulnerability"), + /** + * Description + */ + description: external_exports.string().describe("Detailed description of the vulnerability"), + /** + * Severity + */ + severity: VulnerabilitySeverity2.describe("Severity level of this vulnerability"), + /** + * CVSS score (0-10) + */ + cvss: external_exports.number().min(0).max(10).optional().describe("CVSS score ranging from 0 to 10"), + /** + * Affected package + */ + package: external_exports.object({ + name: external_exports.string().describe("Name of the affected package"), + version: external_exports.string().describe("Version of the affected package"), + ecosystem: external_exports.string().optional().describe("Package ecosystem (e.g., npm, pip, maven)") + }).describe("Affected package information"), + /** + * Vulnerable version range + */ + vulnerableVersions: external_exports.string().describe("Semver range of vulnerable versions"), + /** + * Patched versions + */ + patchedVersions: external_exports.string().optional().describe("Semver range of patched versions"), + /** + * References + */ + references: external_exports.array(external_exports.object({ + type: external_exports.enum(["advisory", "article", "report", "web"]).describe("Type of reference source"), + url: external_exports.string().url().describe("URL of the reference") + })).default([]).describe("External references related to the vulnerability"), + /** + * CWE (Common Weakness Enumeration) + */ + cwe: external_exports.array(external_exports.string()).default([]).describe("CWE identifiers associated with this vulnerability"), + /** + * Published date + */ + publishedAt: external_exports.string().datetime().optional().describe("ISO 8601 date when the vulnerability was published"), + /** + * Mitigation advice + */ + mitigation: external_exports.string().optional().describe("Recommended steps to mitigate the vulnerability") +}).describe("A known security vulnerability in a package dependency"); +var SecurityScanResultSchema2 = external_exports.object({ + /** + * Scan identifier + */ + scanId: external_exports.string().uuid().describe("Unique identifier for this security scan"), + /** + * Plugin being scanned + */ + plugin: external_exports.object({ + id: external_exports.string().describe("Plugin identifier"), + version: external_exports.string().describe("Plugin version that was scanned") + }).describe("Plugin that was scanned"), + /** + * Scan timestamp + */ + scannedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the scan was performed"), + /** + * Scanner information + */ + scanner: external_exports.object({ + name: external_exports.string().describe("Scanner name (e.g., snyk, osv, trivy)"), + version: external_exports.string().describe("Version of the scanner tool") + }).describe("Information about the scanner tool used"), + /** + * Scan status + */ + status: external_exports.enum(["passed", "failed", "warning"]).describe("Overall result status of the security scan"), + /** + * Vulnerabilities found + */ + vulnerabilities: external_exports.array(SecurityVulnerabilitySchema2).describe("List of vulnerabilities discovered during the scan"), + /** + * Vulnerability summary + */ + summary: external_exports.object({ + critical: external_exports.number().int().min(0).default(0).describe("Count of critical severity vulnerabilities"), + high: external_exports.number().int().min(0).default(0).describe("Count of high severity vulnerabilities"), + medium: external_exports.number().int().min(0).default(0).describe("Count of medium severity vulnerabilities"), + low: external_exports.number().int().min(0).default(0).describe("Count of low severity vulnerabilities"), + info: external_exports.number().int().min(0).default(0).describe("Count of informational severity vulnerabilities"), + total: external_exports.number().int().min(0).default(0).describe("Total count of all vulnerabilities") + }).describe("Summary counts of vulnerabilities by severity"), + /** + * License compliance issues + */ + licenseIssues: external_exports.array(external_exports.object({ + package: external_exports.string().describe("Name of the package with a license issue"), + license: external_exports.string().describe("License identifier of the package"), + reason: external_exports.string().describe("Reason the license is flagged"), + severity: external_exports.enum(["error", "warning", "info"]).describe("Severity of the license compliance issue") + })).default([]).describe("License compliance issues found during the scan"), + /** + * Code quality issues + */ + codeQuality: external_exports.object({ + score: external_exports.number().min(0).max(100).optional().describe("Overall code quality score from 0 to 100"), + issues: external_exports.array(external_exports.object({ + type: external_exports.enum(["security", "quality", "style"]).describe("Category of the code quality issue"), + severity: external_exports.enum(["error", "warning", "info"]).describe("Severity of the code quality issue"), + message: external_exports.string().describe("Description of the code quality issue"), + file: external_exports.string().optional().describe("File path where the issue was found"), + line: external_exports.number().int().optional().describe("Line number where the issue was found") + })).default([]).describe("List of individual code quality issues") + }).optional().describe("Code quality analysis results"), + /** + * Next scan scheduled + */ + nextScanAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp for the next scheduled scan") +}).describe("Result of a security scan performed on a plugin"); +var SecurityPolicySchema2 = external_exports.object({ + /** + * Policy identifier + */ + id: external_exports.string().describe("Unique identifier for the security policy"), + /** + * Policy name + */ + name: external_exports.string().describe("Human-readable name of the security policy"), + /** + * Automatic scanning + */ + autoScan: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Whether automatic scanning is enabled"), + frequency: external_exports.enum(["on-publish", "daily", "weekly", "monthly"]).default("daily").describe("How often automatic scans are performed") + }).describe("Automatic security scanning configuration"), + /** + * Vulnerability thresholds + */ + thresholds: external_exports.object({ + /** + * Block plugin if critical vulnerabilities exceed this + */ + maxCritical: external_exports.number().int().min(0).default(0).describe("Maximum allowed critical vulnerabilities before blocking"), + /** + * Block plugin if high vulnerabilities exceed this + */ + maxHigh: external_exports.number().int().min(0).default(0).describe("Maximum allowed high vulnerabilities before blocking"), + /** + * Warn if medium vulnerabilities exceed this + */ + maxMedium: external_exports.number().int().min(0).default(5).describe("Maximum allowed medium vulnerabilities before warning") + }).describe("Vulnerability count thresholds for policy enforcement"), + /** + * Allowed licenses + */ + allowedLicenses: external_exports.array(external_exports.string()).default([ + "MIT", + "Apache-2.0", + "BSD-3-Clause", + "BSD-2-Clause", + "ISC" + ]).describe("List of SPDX license identifiers that are permitted"), + /** + * Prohibited licenses + */ + prohibitedLicenses: external_exports.array(external_exports.string()).default([ + "GPL-3.0", + "AGPL-3.0" + ]).describe("List of SPDX license identifiers that are prohibited"), + /** + * Code signing requirements + */ + codeSigning: external_exports.object({ + required: external_exports.boolean().default(false).describe("Whether code signing is required for plugins"), + allowedSigners: external_exports.array(external_exports.string()).default([]).describe("List of trusted signer identities") + }).optional().describe("Code signing requirements for plugin artifacts"), + /** + * Sandbox restrictions + */ + sandbox: external_exports.object({ + /** + * Restrict network access + */ + networkAccess: external_exports.enum(["none", "localhost", "allowlist", "all"]).default("all").describe("Level of network access granted to the plugin"), + /** + * Allowed network destinations (if allowlist) + */ + allowedDestinations: external_exports.array(external_exports.string()).default([]).describe("Permitted network destinations when using allowlist mode"), + /** + * File system access + */ + filesystemAccess: external_exports.enum(["none", "read-only", "temp-only", "full"]).default("full").describe("Level of file system access granted to the plugin"), + /** + * Maximum memory (MB) + */ + maxMemoryMB: external_exports.number().int().positive().optional().describe("Maximum memory allocation in megabytes"), + /** + * Maximum CPU time (seconds) + */ + maxCPUSeconds: external_exports.number().int().positive().optional().describe("Maximum CPU time allowed in seconds") + }).optional().describe("Sandbox restrictions for plugin execution") +}).describe("Security policy governing plugin scanning and enforcement"); +var PackageDependencySchema2 = external_exports.object({ + /** + * Package name/ID + */ + name: external_exports.string().describe("Package name or identifier"), + /** + * Version constraint (semver range) + */ + versionConstraint: external_exports.string().describe("Semver range (e.g., `^1.0.0`, `>=2.0.0 <3.0.0`)"), + /** + * Dependency type + */ + type: external_exports.enum(["required", "optional", "peer", "dev"]).default("required").describe("Category of the dependency relationship"), + /** + * Resolved version (filled during resolution) + */ + resolvedVersion: external_exports.string().optional().describe("Concrete version resolved during dependency resolution") +}).describe("A package dependency with its version constraint"); +var DependencyGraphNodeSchema2 = external_exports.object({ + /** + * Package identifier + */ + id: external_exports.string().describe("Unique identifier of the package"), + /** + * Package version + */ + version: external_exports.string().describe("Resolved version of the package"), + /** + * Dependencies of this package + */ + dependencies: external_exports.array(PackageDependencySchema2).default([]).describe("Dependencies required by this package"), + /** + * Depth in dependency tree + */ + depth: external_exports.number().int().min(0).describe("Depth level in the dependency tree (0 = root)"), + /** + * Whether this is a direct dependency + */ + isDirect: external_exports.boolean().describe("Whether this is a direct (top-level) dependency"), + /** + * Package metadata + */ + metadata: external_exports.object({ + name: external_exports.string().describe("Display name of the package"), + description: external_exports.string().optional().describe("Short description of the package"), + license: external_exports.string().optional().describe("SPDX license identifier of the package"), + homepage: external_exports.string().url().optional().describe("Homepage URL of the package") + }).optional().describe("Additional metadata about the package") +}).describe("A node in the dependency graph representing a resolved package"); +var DependencyGraphSchema2 = external_exports.object({ + /** + * Root package + */ + root: external_exports.object({ + id: external_exports.string().describe("Identifier of the root package"), + version: external_exports.string().describe("Version of the root package") + }).describe("Root package of the dependency graph"), + /** + * All nodes in the graph + */ + nodes: external_exports.array(DependencyGraphNodeSchema2).describe("All resolved package nodes in the dependency graph"), + /** + * Edges (dependency relationships) + */ + edges: external_exports.array(external_exports.object({ + from: external_exports.string().describe("Package ID"), + to: external_exports.string().describe("Package ID"), + constraint: external_exports.string().describe("Version constraint") + })).describe("Directed edges representing dependency relationships"), + /** + * Resolution statistics + */ + stats: external_exports.object({ + totalDependencies: external_exports.number().int().min(0).describe("Total number of resolved dependencies"), + directDependencies: external_exports.number().int().min(0).describe("Number of direct (top-level) dependencies"), + maxDepth: external_exports.number().int().min(0).describe("Maximum depth of the dependency tree") + }).describe("Summary statistics for the dependency graph") +}).describe("Complete dependency graph for a package and its transitive dependencies"); +var PackageDependencyConflictSchema2 = external_exports.object({ + /** + * Package with conflict + */ + package: external_exports.string().describe("Name of the package with conflicting version requirements"), + /** + * Conflicting versions + */ + conflicts: external_exports.array(external_exports.object({ + version: external_exports.string().describe("Conflicting version of the package"), + requestedBy: external_exports.array(external_exports.string()).describe("Packages that require this version"), + constraint: external_exports.string().describe("Semver constraint that produced this version requirement") + })).describe("List of conflicting version requirements"), + /** + * Suggested resolution + */ + resolution: external_exports.object({ + strategy: external_exports.enum(["pick-highest", "pick-lowest", "manual"]).describe("Strategy used to resolve the conflict"), + version: external_exports.string().optional().describe("Resolved version selected by the strategy"), + reason: external_exports.string().optional().describe("Explanation of why this resolution was chosen") + }).optional().describe("Suggested resolution for the conflict"), + /** + * Severity + */ + severity: external_exports.enum(["error", "warning", "info"]).describe("Severity level of the dependency conflict") +}).describe("A detected conflict between dependency version requirements"); +var PackageDependencyResolutionResultSchema2 = external_exports.object({ + /** + * Resolution status + */ + status: external_exports.enum(["success", "conflict", "error"]).describe("Overall status of the dependency resolution"), + /** + * Resolved dependency graph + */ + graph: DependencyGraphSchema2.optional().describe("Resolved dependency graph if resolution succeeded"), + /** + * Conflicts detected + */ + conflicts: external_exports.array(PackageDependencyConflictSchema2).default([]).describe("List of dependency conflicts detected during resolution"), + /** + * Errors encountered + */ + errors: external_exports.array(external_exports.object({ + package: external_exports.string().describe("Name of the package that caused the error"), + error: external_exports.string().describe("Error message describing what went wrong") + })).default([]).describe("Errors encountered during dependency resolution"), + /** + * Installation order (topological sort) + */ + installOrder: external_exports.array(external_exports.string()).default([]).describe("Topologically sorted list of package IDs for installation"), + /** + * Resolution time (ms) + */ + resolvedIn: external_exports.number().int().min(0).optional().describe("Time taken to resolve dependencies in milliseconds") +}).describe("Result of a dependency resolution process"); +var SBOMEntrySchema2 = external_exports.object({ + /** + * Component name + */ + name: external_exports.string().describe("Name of the software component"), + /** + * Component version + */ + version: external_exports.string().describe("Version of the software component"), + /** + * Package URL (purl) + */ + purl: external_exports.string().optional().describe("Package URL identifier"), + /** + * License + */ + license: external_exports.string().optional().describe("SPDX license identifier of the component"), + /** + * Hashes + */ + hashes: external_exports.object({ + sha256: external_exports.string().optional().describe("SHA-256 hash of the component artifact"), + sha512: external_exports.string().optional().describe("SHA-512 hash of the component artifact") + }).optional().describe("Cryptographic hashes for integrity verification"), + /** + * Supplier + */ + supplier: external_exports.object({ + name: external_exports.string().describe("Name of the component supplier"), + url: external_exports.string().url().optional().describe("URL of the component supplier") + }).optional().describe("Supplier information for the component"), + /** + * External references + */ + externalRefs: external_exports.array(external_exports.object({ + type: external_exports.enum(["website", "repository", "documentation", "issue-tracker"]).describe("Type of external reference"), + url: external_exports.string().url().describe("URL of the external reference") + })).default([]).describe("External references related to the component") +}).describe("A single entry in a Software Bill of Materials"); +var SBOMSchema2 = external_exports.object({ + /** + * SBOM format + */ + format: external_exports.enum(["spdx", "cyclonedx"]).default("cyclonedx").describe("SBOM standard format used"), + /** + * SBOM version + */ + version: external_exports.string().describe("Version of the SBOM specification"), + /** + * Plugin metadata + */ + plugin: external_exports.object({ + id: external_exports.string().describe("Plugin identifier"), + version: external_exports.string().describe("Plugin version"), + name: external_exports.string().describe("Human-readable plugin name") + }).describe("Metadata about the plugin this SBOM describes"), + /** + * Components (dependencies) + */ + components: external_exports.array(SBOMEntrySchema2).describe("List of software components included in the plugin"), + /** + * Generation timestamp + */ + generatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the SBOM was generated"), + /** + * Generator tool + */ + generator: external_exports.object({ + name: external_exports.string().describe("Name of the SBOM generator tool"), + version: external_exports.string().describe("Version of the SBOM generator tool") + }).optional().describe("Tool used to generate this SBOM") +}).describe("Software Bill of Materials for a plugin"); +var PluginProvenanceSchema2 = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string().describe("Unique identifier of the plugin"), + /** + * Plugin version + */ + version: external_exports.string().describe("Version of the plugin artifact"), + /** + * Build information + */ + build: external_exports.object({ + /** + * Build timestamp + */ + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the build was produced"), + /** + * Build environment + */ + environment: external_exports.object({ + os: external_exports.string().describe("Operating system used for the build"), + arch: external_exports.string().describe("CPU architecture used for the build"), + nodeVersion: external_exports.string().describe("Node.js version used for the build") + }).optional().describe("Environment details where the build was executed"), + /** + * Source repository + */ + source: external_exports.object({ + repository: external_exports.string().url().describe("URL of the source repository"), + commit: external_exports.string().regex(/^[a-f0-9]{40}$/).describe("Full SHA-1 commit hash of the source"), + branch: external_exports.string().optional().describe("Branch name the build was produced from"), + tag: external_exports.string().optional().describe("Git tag associated with the build") + }).optional().describe("Source repository information for the build"), + /** + * Builder identity + */ + builder: external_exports.object({ + name: external_exports.string().describe("Name of the person or system that produced the build"), + email: external_exports.string().email().optional().describe("Email address of the builder") + }).optional().describe("Identity of the builder who produced the artifact") + }).describe("Build provenance information"), + /** + * Artifact hashes + */ + artifacts: external_exports.array(external_exports.object({ + filename: external_exports.string().describe("Name of the artifact file"), + sha256: external_exports.string().describe("SHA-256 hash of the artifact"), + size: external_exports.number().int().positive().describe("Size of the artifact in bytes") + })).describe("List of build artifacts with integrity hashes"), + /** + * Signatures + */ + signatures: external_exports.array(external_exports.object({ + algorithm: external_exports.enum(["rsa", "ecdsa", "ed25519"]).describe("Cryptographic algorithm used for signing"), + publicKey: external_exports.string().describe("Public key used to verify the signature"), + signature: external_exports.string().describe("Digital signature value"), + signedBy: external_exports.string().describe("Identity of the signer"), + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the signature was created") + })).default([]).describe("Cryptographic signatures for the plugin artifact"), + /** + * Attestations + */ + attestations: external_exports.array(external_exports.object({ + type: external_exports.enum(["code-review", "security-scan", "test-results", "ci-build"]).describe("Type of attestation"), + status: external_exports.enum(["passed", "failed"]).describe("Result status of the attestation"), + url: external_exports.string().url().optional().describe("URL with details about the attestation"), + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the attestation was issued") + })).default([]).describe("Verification attestations for the plugin") +}).describe("Verifiable provenance and chain of custody for a plugin artifact"); +var PluginTrustScoreSchema2 = external_exports.object({ + /** + * Plugin identifier + */ + pluginId: external_exports.string().describe("Unique identifier of the plugin"), + /** + * Overall trust score (0-100) + */ + score: external_exports.number().min(0).max(100).describe("Overall trust score from 0 to 100"), + /** + * Score components + */ + components: external_exports.object({ + /** + * Vendor reputation (0-100) + */ + vendorReputation: external_exports.number().min(0).max(100).describe("Vendor reputation score from 0 to 100"), + /** + * Security scan results (0-100) + */ + securityScore: external_exports.number().min(0).max(100).describe("Security scan results score from 0 to 100"), + /** + * Code quality (0-100) + */ + codeQuality: external_exports.number().min(0).max(100).describe("Code quality score from 0 to 100"), + /** + * Community engagement (0-100) + */ + communityScore: external_exports.number().min(0).max(100).describe("Community engagement score from 0 to 100"), + /** + * Update frequency (0-100) + */ + maintenanceScore: external_exports.number().min(0).max(100).describe("Maintenance and update frequency score from 0 to 100") + }).describe("Individual score components contributing to the overall trust score"), + /** + * Trust level + */ + level: external_exports.enum(["verified", "trusted", "neutral", "untrusted", "blocked"]).describe("Computed trust level based on the overall score"), + /** + * Verification badges + */ + badges: external_exports.array(external_exports.enum([ + "official", + // Official ObjectStack plugin + "verified-vendor", + // Verified vendor + "security-scanned", + // Passed security scan + "code-signed", + // Digitally signed + "open-source", + // Open source + "popular" + // High downloads + ])).default([]).describe("Verification badges earned by the plugin"), + /** + * Last updated + */ + updatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the trust score was last updated") +}).describe("Trust score and verification status for a plugin"); +var PluginSecurityProtocol = { + VulnerabilitySeverity: VulnerabilitySeverity2, + SecurityVulnerability: SecurityVulnerabilitySchema2, + SecurityScanResult: SecurityScanResultSchema2, + SecurityPolicy: SecurityPolicySchema2, + PackageDependency: PackageDependencySchema2, + DependencyGraphNode: DependencyGraphNodeSchema2, + DependencyGraph: DependencyGraphSchema2, + DependencyConflict: PackageDependencyConflictSchema2, + DependencyResolutionResult: PackageDependencyResolutionResultSchema2, + SBOMEntry: SBOMEntrySchema2, + SBOM: SBOMSchema2, + PluginProvenance: PluginProvenanceSchema2, + PluginTrustScore: PluginTrustScoreSchema2 +}; +var cloud_exports = {}; +__export4(cloud_exports, { + AnalyticsTimeRangeSchema: () => AnalyticsTimeRangeSchema, + AppDiscoveryRequestSchema: () => AppDiscoveryRequestSchema, + AppDiscoveryResponseSchema: () => AppDiscoveryResponseSchema, + AppSubscriptionSchema: () => AppSubscriptionSchema, + ArtifactDownloadResponseSchema: () => ArtifactDownloadResponseSchema, + ArtifactReferenceSchema: () => ArtifactReferenceSchema2, + CreateListingRequestSchema: () => CreateListingRequestSchema, + CuratedCollectionSchema: () => CuratedCollectionSchema, + FeaturedListingSchema: () => FeaturedListingSchema, + InstalledAppSummarySchema: () => InstalledAppSummarySchema, + ListInstalledAppsRequestSchema: () => ListInstalledAppsRequestSchema, + ListInstalledAppsResponseSchema: () => ListInstalledAppsResponseSchema, + ListReviewsRequestSchema: () => ListReviewsRequestSchema, + ListReviewsResponseSchema: () => ListReviewsResponseSchema, + ListingActionRequestSchema: () => ListingActionRequestSchema, + ListingStatusSchema: () => ListingStatusSchema2, + MarketplaceCategorySchema: () => MarketplaceCategorySchema2, + MarketplaceHealthMetricsSchema: () => MarketplaceHealthMetricsSchema, + MarketplaceInstallRequestSchema: () => MarketplaceInstallRequestSchema, + MarketplaceInstallResponseSchema: () => MarketplaceInstallResponseSchema, + MarketplaceListingSchema: () => MarketplaceListingSchema2, + MarketplaceSearchRequestSchema: () => MarketplaceSearchRequestSchema, + MarketplaceSearchResponseSchema: () => MarketplaceSearchResponseSchema, + PackageSubmissionSchema: () => PackageSubmissionSchema, + PolicyActionSchema: () => PolicyActionSchema, + PolicyViolationTypeSchema: () => PolicyViolationTypeSchema, + PricingModelSchema: () => PricingModelSchema2, + PublisherProfileSchema: () => PublisherProfileSchema, + PublisherSchema: () => PublisherSchema, + PublisherVerificationSchema: () => PublisherVerificationSchema2, + PublishingAnalyticsRequestSchema: () => PublishingAnalyticsRequestSchema, + PublishingAnalyticsResponseSchema: () => PublishingAnalyticsResponseSchema, + RecommendationReasonSchema: () => RecommendationReasonSchema, + RecommendedAppSchema: () => RecommendedAppSchema, + RejectionReasonSchema: () => RejectionReasonSchema, + ReleaseChannelSchema: () => ReleaseChannelSchema, + ReviewCriterionSchema: () => ReviewCriterionSchema, + ReviewDecisionSchema: () => ReviewDecisionSchema, + ReviewModerationStatusSchema: () => ReviewModerationStatusSchema, + SubmissionReviewSchema: () => SubmissionReviewSchema, + SubmitReviewRequestSchema: () => SubmitReviewRequestSchema, + SubscriptionStatusSchema: () => SubscriptionStatusSchema, + TimeSeriesPointSchema: () => TimeSeriesPointSchema, + TrendingListingSchema: () => TrendingListingSchema, + UpdateListingRequestSchema: () => UpdateListingRequestSchema, + UserReviewSchema: () => UserReviewSchema, + VersionReleaseSchema: () => VersionReleaseSchema +}); +var PublisherVerificationSchema2 = external_exports.enum([ + "unverified", + // Not yet verified + "pending", + // Verification in progress + "verified", + // Identity verified by platform + "trusted", + // Trusted publisher (track record of quality) + "partner" + // Official platform partner +]).describe("Publisher verification status"); +var PublisherSchema = external_exports.object({ + /** Publisher unique identifier */ + id: external_exports.string().describe("Publisher ID"), + /** Display name */ + name: external_exports.string().describe("Publisher display name"), + /** Publisher type */ + type: external_exports.enum(["individual", "organization"]).describe("Publisher type"), + /** Verification status */ + verification: PublisherVerificationSchema2.default("unverified").describe("Publisher verification status"), + /** Contact email */ + email: external_exports.string().email().optional().describe("Contact email"), + /** Website URL */ + website: external_exports.string().url().optional().describe("Publisher website"), + /** Organization logo URL */ + logoUrl: external_exports.string().url().optional().describe("Publisher logo URL"), + /** Short description/bio */ + description: external_exports.string().optional().describe("Publisher description"), + /** Registration date */ + registeredAt: external_exports.string().datetime().optional().describe("Publisher registration timestamp") +}).describe("Developer or organization that publishes packages"); +var ArtifactReferenceSchema2 = external_exports.object({ + /** Artifact download URL */ + url: external_exports.string().url().describe("Artifact download URL"), + /** SHA256 integrity checksum */ + sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).describe("SHA256 checksum"), + /** File size in bytes */ + size: external_exports.number().int().positive().describe("Artifact size in bytes"), + /** Artifact format */ + format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Artifact format"), + /** Upload timestamp */ + uploadedAt: external_exports.string().datetime().describe("Upload timestamp") +}).describe("Reference to a downloadable package artifact"); +var ArtifactDownloadResponseSchema = external_exports.object({ + /** Pre-signed or direct download URL */ + downloadUrl: external_exports.string().url().describe("Artifact download URL (may be pre-signed)"), + /** SHA256 checksum for download verification */ + sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).describe("SHA256 checksum for verification"), + /** File size in bytes */ + size: external_exports.number().int().positive().describe("Artifact size in bytes"), + /** Artifact format */ + format: external_exports.enum(["tgz", "zip"]).describe("Artifact format"), + /** URL expiration time (for pre-signed URLs) */ + expiresAt: external_exports.string().datetime().optional().describe("URL expiration timestamp for pre-signed URLs") +}).describe("Artifact download response with integrity metadata"); +var MarketplaceCategorySchema2 = external_exports.enum([ + "crm", + // Customer Relationship Management + "erp", + // Enterprise Resource Planning + "hr", + // Human Resources + "finance", + // Finance & Accounting + "project", + // Project Management + "collaboration", + // Collaboration & Communication + "analytics", + // Analytics & Reporting + "integration", + // Integrations & Connectors + "automation", + // Automation & Workflows + "ai", + // AI & Machine Learning + "security", + // Security & Compliance + "developer-tools", + // Developer Tools + "ui-theme", + // UI Themes & Appearance + "storage", + // Storage & Drivers + "other" + // Other / Uncategorized +]).describe("Marketplace package category"); +var ListingStatusSchema2 = external_exports.enum([ + "draft", + // Not yet submitted + "submitted", + // Submitted for review + "in-review", + // Under review + "approved", + // Approved, ready to publish + "published", + // Live on marketplace + "rejected", + // Review rejected + "suspended", + // Suspended by platform (policy violation) + "deprecated", + // Deprecated by publisher + "unlisted" + // Available by direct link only +]).describe("Marketplace listing status"); +var PricingModelSchema2 = external_exports.enum([ + "free", + // Free to install + "freemium", + // Free with paid premium features + "paid", + // Requires purchase + "subscription", + // Recurring subscription + "usage-based", + // Pay per usage + "contact-sales" + // Enterprise pricing, contact for quote +]).describe("Package pricing model"); +var MarketplaceListingSchema2 = external_exports.object({ + /** Listing ID (matches package ID) */ + id: external_exports.string().describe("Listing ID (matches package manifest ID)"), + /** Package ID (reverse domain notation) */ + packageId: external_exports.string().describe("Package identifier"), + /** Publisher information */ + publisherId: external_exports.string().describe("Publisher ID"), + /** Current listing status */ + status: ListingStatusSchema2.default("draft").describe("Publication state: draft, published, under-review, suspended, deprecated, or unlisted"), + /** Display name */ + name: external_exports.string().describe("Display name"), + /** Tagline (short description for cards/search results) */ + tagline: external_exports.string().max(120).optional().describe("Short tagline (max 120 chars)"), + /** Full description (supports Markdown) */ + description: external_exports.string().optional().describe("Full description (Markdown)"), + /** Category */ + category: MarketplaceCategorySchema2.describe("Package category"), + /** Additional tags for search discovery */ + tags: external_exports.array(external_exports.string()).optional().describe("Search tags"), + /** Icon/logo URL */ + iconUrl: external_exports.string().url().optional().describe("Package icon URL"), + /** Screenshot URLs */ + screenshots: external_exports.array(external_exports.object({ + url: external_exports.string().url(), + caption: external_exports.string().optional() + })).optional().describe("Screenshots"), + /** Documentation URL */ + documentationUrl: external_exports.string().url().optional().describe("Documentation URL"), + /** Support URL */ + supportUrl: external_exports.string().url().optional().describe("Support URL"), + /** Source repository URL (if open source) */ + repositoryUrl: external_exports.string().url().optional().describe("Source repository URL"), + /** Pricing model */ + pricing: PricingModelSchema2.default("free").describe("Pricing model"), + /** Price in cents (if paid) */ + priceInCents: external_exports.number().int().min(0).optional().describe("Price in cents (e.g. 999 = $9.99)"), + /** Latest published version */ + latestVersion: external_exports.string().describe("Latest published version"), + /** Minimum platform version required */ + minPlatformVersion: external_exports.string().optional().describe("Minimum ObjectStack platform version"), + /** Available versions for installation */ + versions: external_exports.array(external_exports.object({ + version: external_exports.string().describe("Version string"), + releaseDate: external_exports.string().datetime().describe("Release date"), + releaseNotes: external_exports.string().optional().describe("Release notes"), + minPlatformVersion: external_exports.string().optional().describe("Minimum platform version"), + deprecated: external_exports.boolean().default(false).describe("Whether this version is deprecated"), + /** Artifact reference for this version */ + artifact: ArtifactReferenceSchema2.optional().describe("Downloadable artifact for this version") + })).optional().describe("Published versions"), + /** Aggregate statistics */ + stats: external_exports.object({ + totalInstalls: external_exports.number().int().min(0).default(0).describe("Total installs"), + activeInstalls: external_exports.number().int().min(0).default(0).describe("Active installs"), + averageRating: external_exports.number().min(0).max(5).optional().describe("Average user rating (0-5)"), + totalRatings: external_exports.number().int().min(0).default(0).describe("Total ratings count"), + totalReviews: external_exports.number().int().min(0).default(0).describe("Total reviews count") + }).optional().describe("Aggregate marketplace statistics"), + /** First published date */ + publishedAt: external_exports.string().datetime().optional().describe("First published timestamp"), + /** Last updated date */ + updatedAt: external_exports.string().datetime().optional().describe("Last updated timestamp") +}).describe("Public-facing package listing on the marketplace"); +var PackageSubmissionSchema = external_exports.object({ + /** Submission ID */ + id: external_exports.string().describe("Submission ID"), + /** Package ID */ + packageId: external_exports.string().describe("Package identifier"), + /** Version being submitted */ + version: external_exports.string().describe("Version being submitted"), + /** Publisher ID */ + publisherId: external_exports.string().describe("Publisher submitting"), + /** Submission status */ + status: external_exports.enum([ + "pending", + // Awaiting review + "scanning", + // Automated scan in progress + "in-review", + // Under manual review + "changes-requested", + // Reviewer requests changes + "approved", + // Approved for publishing + "rejected" + // Rejected + ]).default("pending").describe("Review status"), + /** + * Package artifact URL or reference. + * Points to the built package bundle for review. + */ + artifactUrl: external_exports.string().describe("Package artifact URL for review"), + /** Release notes for this version */ + releaseNotes: external_exports.string().optional().describe("Release notes for this version"), + /** Whether this is the first submission (new listing) vs version update */ + isNewListing: external_exports.boolean().default(false).describe("Whether this is a new listing submission"), + /** Automated scan results */ + scanResults: external_exports.object({ + /** Whether automated scan passed */ + passed: external_exports.boolean(), + /** Security scan score (0-100) */ + securityScore: external_exports.number().min(0).max(100).optional(), + /** Compatibility check passed */ + compatibilityCheck: external_exports.boolean().optional(), + /** Issues found during scan */ + issues: external_exports.array(external_exports.object({ + severity: external_exports.enum(["critical", "high", "medium", "low", "info"]), + message: external_exports.string(), + file: external_exports.string().optional(), + line: external_exports.number().optional() + })).optional() + }).optional().describe("Automated scan results"), + /** Reviewer notes (from platform reviewer) */ + reviewerNotes: external_exports.string().optional().describe("Notes from the platform reviewer"), + /** Submitted timestamp */ + submittedAt: external_exports.string().datetime().optional().describe("Submission timestamp"), + /** Review completed timestamp */ + reviewedAt: external_exports.string().datetime().optional().describe("Review completion timestamp") +}).describe("Developer submission of a package version for review"); +var MarketplaceSearchRequestSchema = external_exports.object({ + /** Search query string */ + query: external_exports.string().optional().describe("Full-text search query"), + /** Filter by category */ + category: MarketplaceCategorySchema2.optional().describe("Filter by category"), + /** Filter by tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), + /** Filter by pricing model */ + pricing: PricingModelSchema2.optional().describe("Filter by pricing model"), + /** Filter by publisher verification level */ + publisherVerification: PublisherVerificationSchema2.optional().describe("Filter by publisher verification level"), + /** Sort by */ + sortBy: external_exports.enum([ + "relevance", + // Best match (default for search) + "popularity", + // Most installs + "rating", + // Highest rated + "newest", + // Most recently published + "updated", + // Most recently updated + "name" + // Alphabetical + ]).default("relevance").describe("Sort field"), + /** Sort direction */ + sortDirection: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction"), + /** Pagination: page number */ + page: external_exports.number().int().min(1).default(1).describe("Page number"), + /** Pagination: items per page */ + pageSize: external_exports.number().int().min(1).max(100).default(20).describe("Items per page"), + /** Filter by minimum platform version compatibility */ + platformVersion: external_exports.string().optional().describe("Filter by platform version compatibility") +}).describe("Marketplace search request"); +var MarketplaceSearchResponseSchema = external_exports.object({ + /** Search results */ + items: external_exports.array(MarketplaceListingSchema2).describe("Search result listings"), + /** Total count (for pagination) */ + total: external_exports.number().int().min(0).describe("Total matching results"), + /** Current page */ + page: external_exports.number().int().min(1).describe("Current page number"), + /** Items per page */ + pageSize: external_exports.number().int().min(1).describe("Items per page"), + /** Facets for filtering */ + facets: external_exports.object({ + categories: external_exports.array(external_exports.object({ + category: MarketplaceCategorySchema2, + count: external_exports.number().int().min(0) + })).optional(), + pricing: external_exports.array(external_exports.object({ + model: PricingModelSchema2, + count: external_exports.number().int().min(0) + })).optional() + }).optional().describe("Aggregation facets for refining search") +}).describe("Marketplace search response"); +var MarketplaceInstallRequestSchema = external_exports.object({ + /** Listing ID to install */ + listingId: external_exports.string().describe("Marketplace listing ID"), + /** Specific version to install (defaults to latest) */ + version: external_exports.string().optional().describe("Version to install"), + /** License key (for paid packages) */ + licenseKey: external_exports.string().optional().describe("License key for paid packages"), + /** User-provided settings at install time */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), + /** Whether to enable immediately after install */ + enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), + /** Artifact reference (resolved from listing version, or provided directly) */ + artifactRef: ArtifactReferenceSchema2.optional().describe("Artifact reference for direct installation"), + /** Tenant ID */ + tenantId: external_exports.string().optional().describe("Tenant identifier") +}).describe("Install from marketplace request"); +var MarketplaceInstallResponseSchema = external_exports.object({ + /** Whether installation was successful */ + success: external_exports.boolean().describe("Whether installation succeeded"), + /** Installed package ID */ + packageId: external_exports.string().optional().describe("Installed package identifier"), + /** Installed version */ + version: external_exports.string().optional().describe("Installed version"), + /** Human-readable message */ + message: external_exports.string().optional().describe("Installation status message") +}).describe("Install from marketplace response"); +var PublisherProfileSchema = external_exports.object({ + /** Organization ID (references Identity.Organization.id) */ + organizationId: external_exports.string().describe("Identity Organization ID"), + /** Publisher ID (marketplace-assigned identifier) */ + publisherId: external_exports.string().describe("Marketplace publisher ID"), + /** Verification level (marketplace trust tier) */ + verification: PublisherVerificationSchema2.default("unverified"), + /** Accepted developer program agreement version */ + agreementVersion: external_exports.string().optional().describe("Accepted developer agreement version"), + /** Publisher-specific website (may differ from org) */ + website: external_exports.string().url().optional().describe("Publisher website"), + /** Publisher-specific support email */ + supportEmail: external_exports.string().email().optional().describe("Publisher support email"), + /** Registration timestamp (when org became a publisher) */ + registeredAt: external_exports.string().datetime() +}); +var ReleaseChannelSchema = external_exports.enum([ + "alpha", + // Early development, unstable + "beta", + // Feature-complete, testing phase + "rc", + // Release candidate, final testing + "stable" + // Production-ready, general availability +]); +var VersionReleaseSchema = external_exports.object({ + /** Semver version string */ + version: external_exports.string().describe("Semver version (e.g., 2.1.0-beta.1)"), + /** Release channel */ + channel: ReleaseChannelSchema.default("stable"), + /** Release notes (Markdown) */ + releaseNotes: external_exports.string().optional().describe("Release notes (Markdown)"), + /** Changelog entries (structured) */ + changelog: external_exports.array(external_exports.object({ + type: external_exports.enum(["added", "changed", "fixed", "removed", "deprecated", "security"]), + description: external_exports.string() + })).optional().describe("Structured changelog entries"), + /** Minimum platform version required */ + minPlatformVersion: external_exports.string().optional(), + /** Build artifact URL */ + artifactUrl: external_exports.string().optional().describe("Built package artifact URL"), + /** Artifact checksum (integrity) */ + artifactChecksum: external_exports.string().optional().describe("SHA-256 checksum"), + /** Whether this version is deprecated */ + deprecated: external_exports.boolean().default(false), + /** Deprecation message (if deprecated) */ + deprecationMessage: external_exports.string().optional(), + /** Release timestamp */ + releasedAt: external_exports.string().datetime().optional() +}); +var CreateListingRequestSchema = external_exports.object({ + /** Package ID (reverse domain, e.g., com.acme.crm) */ + packageId: external_exports.string().describe("Package identifier"), + /** Display name */ + name: external_exports.string().describe("App display name"), + /** Short tagline (max 120 chars) */ + tagline: external_exports.string().max(120).optional(), + /** Full description (Markdown) */ + description: external_exports.string().optional(), + /** Category */ + category: external_exports.string().describe("Marketplace category"), + /** Additional tags */ + tags: external_exports.array(external_exports.string()).optional(), + /** Icon URL */ + iconUrl: external_exports.string().url().optional(), + /** Screenshots */ + screenshots: external_exports.array(external_exports.object({ + url: external_exports.string().url(), + caption: external_exports.string().optional() + })).optional(), + /** Documentation URL */ + documentationUrl: external_exports.string().url().optional(), + /** Support URL */ + supportUrl: external_exports.string().url().optional(), + /** Source repository URL */ + repositoryUrl: external_exports.string().url().optional(), + /** Pricing model */ + pricing: external_exports.enum([ + "free", + "freemium", + "paid", + "subscription", + "usage-based", + "contact-sales" + ]).default("free"), + /** Price in cents (if paid) */ + priceInCents: external_exports.number().int().min(0).optional() +}); +var UpdateListingRequestSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string().describe("Listing ID to update"), + /** Updatable fields (all optional, partial update) */ + name: external_exports.string().optional(), + tagline: external_exports.string().max(120).optional(), + description: external_exports.string().optional(), + category: external_exports.string().optional(), + tags: external_exports.array(external_exports.string()).optional(), + iconUrl: external_exports.string().url().optional(), + screenshots: external_exports.array(external_exports.object({ + url: external_exports.string().url(), + caption: external_exports.string().optional() + })).optional(), + documentationUrl: external_exports.string().url().optional(), + supportUrl: external_exports.string().url().optional(), + repositoryUrl: external_exports.string().url().optional(), + pricing: external_exports.enum([ + "free", + "freemium", + "paid", + "subscription", + "usage-based", + "contact-sales" + ]).optional(), + priceInCents: external_exports.number().int().min(0).optional() +}); +var ListingActionRequestSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string().describe("Listing ID"), + /** Action to perform */ + action: external_exports.enum([ + "submit", + // Submit for review + "unlist", + // Remove from public search (keep accessible by direct link) + "deprecate", + // Mark as deprecated + "reactivate" + // Reactivate unlisted/deprecated listing + ]).describe("Action to perform on listing"), + /** Reason for action (e.g., deprecation message) */ + reason: external_exports.string().optional() +}); +var AnalyticsTimeRangeSchema = external_exports.enum([ + "last_7d", + "last_30d", + "last_90d", + "last_365d", + "all_time" +]); +var PublishingAnalyticsRequestSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string().describe("Listing to get analytics for"), + /** Time range */ + timeRange: AnalyticsTimeRangeSchema.default("last_30d"), + /** Metrics to include */ + metrics: external_exports.array(external_exports.enum([ + "installs", + // Install count over time + "uninstalls", + // Uninstall count over time + "active_installs", + // Active install trend + "ratings", + // Rating distribution + "revenue", + // Revenue (for paid apps) + "page_views" + // Listing page views + ])).optional().describe("Metrics to include (default: all)") +}); +var TimeSeriesPointSchema = external_exports.object({ + /** ISO date string (day granularity) */ + date: external_exports.string(), + /** Metric value */ + value: external_exports.number() +}); +var PublishingAnalyticsResponseSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string(), + /** Time range */ + timeRange: AnalyticsTimeRangeSchema, + /** Summary statistics */ + summary: external_exports.object({ + totalInstalls: external_exports.number().int().min(0), + activeInstalls: external_exports.number().int().min(0), + totalUninstalls: external_exports.number().int().min(0), + averageRating: external_exports.number().min(0).max(5).optional(), + totalRatings: external_exports.number().int().min(0), + totalRevenue: external_exports.number().min(0).optional().describe("Revenue in cents"), + pageViews: external_exports.number().int().min(0) + }), + /** Time series data by metric */ + timeSeries: external_exports.record(external_exports.string(), external_exports.array(TimeSeriesPointSchema)).optional().describe("Time series keyed by metric name"), + /** Rating distribution (1-5 stars) */ + ratingDistribution: external_exports.object({ + 1: external_exports.number().int().min(0).default(0), + 2: external_exports.number().int().min(0).default(0), + 3: external_exports.number().int().min(0).default(0), + 4: external_exports.number().int().min(0).default(0), + 5: external_exports.number().int().min(0).default(0) + }).optional() +}); +var ReviewCriterionSchema = external_exports.object({ + /** Criterion identifier */ + id: external_exports.string().describe("Criterion ID"), + /** Category of criterion */ + category: external_exports.enum([ + "security", + // Security best practices + "performance", + // Performance / resource usage + "quality", + // Code quality / best practices + "ux", + // User experience standards + "documentation", + // Documentation completeness + "policy", + // Policy compliance (no malware, GDPR, etc.) + "compatibility" + // Platform compatibility + ]), + /** Description of what to check */ + description: external_exports.string(), + /** Whether this criterion must pass for approval */ + required: external_exports.boolean().default(true), + /** Pass/fail result */ + passed: external_exports.boolean().optional(), + /** Reviewer notes for this criterion */ + notes: external_exports.string().optional() +}); +var ReviewDecisionSchema = external_exports.enum([ + "approved", + // Approved for publishing + "rejected", + // Rejected (with reasons) + "changes-requested" + // Needs changes before re-review +]); +var RejectionReasonSchema = external_exports.enum([ + "security-vulnerability", + // Security issues found + "policy-violation", + // Violates marketplace policy + "quality-below-standard", + // Does not meet quality bar + "misleading-metadata", + // Listing info doesn't match functionality + "incompatible", + // Incompatible with current platform + "duplicate", + // Duplicate of existing listing + "insufficient-documentation", + // Inadequate documentation + "other" + // Other reason (see notes) +]); +var SubmissionReviewSchema = external_exports.object({ + /** Review ID */ + id: external_exports.string().describe("Review ID"), + /** Submission ID being reviewed */ + submissionId: external_exports.string().describe("Submission being reviewed"), + /** Reviewer user ID */ + reviewerId: external_exports.string().describe("Platform reviewer ID"), + /** Review decision */ + decision: ReviewDecisionSchema.optional().describe("Final decision"), + /** Review criteria checklist */ + criteria: external_exports.array(ReviewCriterionSchema).optional().describe("Review checklist results"), + /** Rejection reasons (if rejected) */ + rejectionReasons: external_exports.array(RejectionReasonSchema).optional(), + /** Detailed feedback for the developer */ + feedback: external_exports.string().optional().describe("Detailed review feedback (Markdown)"), + /** Internal notes (not visible to developer) */ + internalNotes: external_exports.string().optional().describe("Internal reviewer notes"), + /** Review started timestamp */ + startedAt: external_exports.string().datetime().optional(), + /** Review completed timestamp */ + completedAt: external_exports.string().datetime().optional() +}); +var FeaturedListingSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string().describe("Featured listing ID"), + /** Featured position/priority (lower = higher priority) */ + priority: external_exports.number().int().min(0).default(0), + /** Featured banner image URL */ + bannerUrl: external_exports.string().url().optional(), + /** Featured reason / editorial note */ + editorialNote: external_exports.string().optional(), + /** Start date for featured period */ + startDate: external_exports.string().datetime(), + /** End date for featured period */ + endDate: external_exports.string().datetime().optional(), + /** Whether currently active */ + active: external_exports.boolean().default(true) +}); +var CuratedCollectionSchema = external_exports.object({ + /** Collection unique identifier */ + id: external_exports.string().describe("Collection ID"), + /** Collection display name */ + name: external_exports.string().describe("Collection name"), + /** Collection description */ + description: external_exports.string().optional(), + /** Cover image URL */ + coverImageUrl: external_exports.string().url().optional(), + /** Listing IDs in this collection (ordered) */ + listingIds: external_exports.array(external_exports.string()).min(1).describe("Ordered listing IDs"), + /** Whether publicly visible */ + published: external_exports.boolean().default(false), + /** Sort order for display among collections */ + sortOrder: external_exports.number().int().min(0).default(0), + /** Created by (admin user ID) */ + createdBy: external_exports.string().optional(), + /** Created at */ + createdAt: external_exports.string().datetime().optional(), + /** Updated at */ + updatedAt: external_exports.string().datetime().optional() +}); +var PolicyViolationTypeSchema = external_exports.enum([ + "malware", + // Malicious software + "data-harvesting", + // Unauthorized data collection + "spam", + // Spammy or misleading content + "copyright", + // Copyright/IP infringement + "inappropriate-content", + // Inappropriate or offensive content + "terms-of-service", + // General ToS violation + "security-risk", + // Unresolved critical security issues + "abandoned" + // Abandoned / no longer maintained +]); +var PolicyActionSchema = external_exports.object({ + /** Action ID */ + id: external_exports.string().describe("Action ID"), + /** Listing ID */ + listingId: external_exports.string().describe("Target listing ID"), + /** Violation type */ + violationType: PolicyViolationTypeSchema, + /** Action taken */ + action: external_exports.enum([ + "warning", + // Warning to publisher + "suspend", + // Temporarily suspend listing + "takedown", + // Permanently remove listing + "restrict" + // Restrict new installs (existing users keep access) + ]), + /** Detailed reason */ + reason: external_exports.string().describe("Explanation of the violation"), + /** Admin user who took the action */ + actionBy: external_exports.string().describe("Admin user ID"), + /** Timestamp */ + actionAt: external_exports.string().datetime(), + /** Resolution notes (if resolved) */ + resolution: external_exports.string().optional(), + /** Whether resolved */ + resolved: external_exports.boolean().default(false) +}); +var MarketplaceHealthMetricsSchema = external_exports.object({ + /** Total number of published listings */ + totalListings: external_exports.number().int().min(0), + /** Listings by status breakdown (partial — only non-zero statuses) */ + listingsByStatus: external_exports.record(external_exports.string(), external_exports.number().int().min(0)).optional(), + /** Listings by category breakdown (partial — only non-zero categories) */ + listingsByCategory: external_exports.record(external_exports.string(), external_exports.number().int().min(0)).optional(), + /** Total registered publishers */ + totalPublishers: external_exports.number().int().min(0), + /** Verified publishers count */ + verifiedPublishers: external_exports.number().int().min(0), + /** Total installs across all listings (all time) */ + totalInstalls: external_exports.number().int().min(0), + /** Average time from submission to review completion (hours) */ + averageReviewTime: external_exports.number().min(0).optional(), + /** Pending review queue size */ + pendingReviews: external_exports.number().int().min(0), + /** Listings by pricing model (partial — only non-zero models) */ + listingsByPricing: external_exports.record(external_exports.string(), external_exports.number().int().min(0)).optional(), + /** Snapshot timestamp */ + snapshotAt: external_exports.string().datetime() +}); +var TrendingListingSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string(), + /** Trending rank (1 = most trending) */ + rank: external_exports.number().int().min(1), + /** Trend score (computed from velocity of installs, ratings, page views) */ + trendScore: external_exports.number().min(0), + /** Install velocity (installs per day over measurement period) */ + installVelocity: external_exports.number().min(0), + /** Measurement period (e.g., "7d", "30d") */ + period: external_exports.string() +}); +var ReviewModerationStatusSchema = external_exports.enum([ + "pending", + // Awaiting moderation + "approved", + // Approved and visible + "flagged", + // Flagged for review + "rejected" + // Rejected (spam, inappropriate) +]); +var UserReviewSchema = external_exports.object({ + /** Review ID */ + id: external_exports.string().describe("Review ID"), + /** Listing ID being reviewed */ + listingId: external_exports.string().describe("Listing being reviewed"), + /** Reviewer user ID */ + userId: external_exports.string().describe("Review author user ID"), + /** Reviewer display name */ + displayName: external_exports.string().optional().describe("Reviewer display name"), + /** Star rating (1-5) */ + rating: external_exports.number().int().min(1).max(5).describe("Star rating (1-5)"), + /** Review title */ + title: external_exports.string().max(200).optional().describe("Review title"), + /** Review body text */ + body: external_exports.string().max(5e3).optional().describe("Review text"), + /** Version the reviewer is using */ + appVersion: external_exports.string().optional().describe("App version being reviewed"), + /** Moderation status */ + moderationStatus: ReviewModerationStatusSchema.default("pending"), + /** Number of "helpful" votes from other users */ + helpfulCount: external_exports.number().int().min(0).default(0), + /** Publisher's response to this review */ + publisherResponse: external_exports.object({ + body: external_exports.string(), + respondedAt: external_exports.string().datetime() + }).optional().describe("Publisher response to review"), + /** Submitted timestamp */ + submittedAt: external_exports.string().datetime(), + /** Updated timestamp */ + updatedAt: external_exports.string().datetime().optional() +}); +var SubmitReviewRequestSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string().describe("Listing to review"), + /** Star rating (1-5) */ + rating: external_exports.number().int().min(1).max(5).describe("Star rating"), + /** Review title */ + title: external_exports.string().max(200).optional(), + /** Review body */ + body: external_exports.string().max(5e3).optional() +}); +var ListReviewsRequestSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string().describe("Listing to get reviews for"), + /** Sort by */ + sortBy: external_exports.enum(["newest", "oldest", "highest", "lowest", "most-helpful"]).default("newest"), + /** Filter by rating */ + rating: external_exports.number().int().min(1).max(5).optional(), + /** Pagination */ + page: external_exports.number().int().min(1).default(1), + pageSize: external_exports.number().int().min(1).max(50).default(10) +}); +var ListReviewsResponseSchema = external_exports.object({ + /** Reviews */ + items: external_exports.array(UserReviewSchema), + /** Total count */ + total: external_exports.number().int().min(0), + /** Pagination */ + page: external_exports.number().int().min(1), + pageSize: external_exports.number().int().min(1), + /** Rating summary */ + ratingSummary: external_exports.object({ + averageRating: external_exports.number().min(0).max(5), + totalRatings: external_exports.number().int().min(0), + distribution: external_exports.object({ + 1: external_exports.number().int().min(0).default(0), + 2: external_exports.number().int().min(0).default(0), + 3: external_exports.number().int().min(0).default(0), + 4: external_exports.number().int().min(0).default(0), + 5: external_exports.number().int().min(0).default(0) + }) + }).optional() +}); +var RecommendationReasonSchema = external_exports.enum([ + "popular-in-category", + // Popular in your industry/category + "similar-users", + // Used by similar organizations + "complements-installed", + // Complements apps you already use + "trending", + // Currently trending + "new-release", + // Recently released / major update + "editor-pick" + // Editorial/curated recommendation +]); +var RecommendedAppSchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string(), + /** App name */ + name: external_exports.string(), + /** Short tagline */ + tagline: external_exports.string().optional(), + /** Icon URL */ + iconUrl: external_exports.string().url().optional(), + /** Category */ + category: MarketplaceCategorySchema2, + /** Pricing */ + pricing: PricingModelSchema2, + /** Average rating */ + averageRating: external_exports.number().min(0).max(5).optional(), + /** Active installs */ + activeInstalls: external_exports.number().int().min(0).optional(), + /** Why this is recommended */ + reason: RecommendationReasonSchema +}); +var AppDiscoveryRequestSchema = external_exports.object({ + /** Tenant ID for personalization */ + tenantId: external_exports.string().optional(), + /** Categories the customer is interested in */ + categories: external_exports.array(MarketplaceCategorySchema2).optional(), + /** Platform version for compatibility filtering */ + platformVersion: external_exports.string().optional(), + /** Max number of items per section */ + limit: external_exports.number().int().min(1).max(50).default(10) +}); +var AppDiscoveryResponseSchema = external_exports.object({ + /** Featured apps (editorial picks) */ + featured: external_exports.array(RecommendedAppSchema).optional(), + /** Personalized recommendations */ + recommended: external_exports.array(RecommendedAppSchema).optional(), + /** Trending apps */ + trending: external_exports.array(RecommendedAppSchema).optional(), + /** Recently added */ + newArrivals: external_exports.array(RecommendedAppSchema).optional(), + /** Curated collections */ + collections: external_exports.array(external_exports.object({ + id: external_exports.string(), + name: external_exports.string(), + description: external_exports.string().optional(), + coverImageUrl: external_exports.string().url().optional(), + apps: external_exports.array(RecommendedAppSchema) + })).optional() +}); +var SubscriptionStatusSchema = external_exports.enum([ + "active", + // Active and paid + "trialing", + // Free trial period + "past-due", + // Payment overdue + "cancelled", + // Cancelled (still active until period ends) + "expired" + // Expired / ended +]); +var AppSubscriptionSchema = external_exports.object({ + /** Subscription ID */ + id: external_exports.string().describe("Subscription ID"), + /** Listing ID */ + listingId: external_exports.string().describe("App listing ID"), + /** Tenant ID */ + tenantId: external_exports.string().describe("Customer tenant ID"), + /** Subscription status */ + status: SubscriptionStatusSchema, + /** License key */ + licenseKey: external_exports.string().optional(), + /** Plan/tier name (if multiple plans) */ + plan: external_exports.string().optional().describe("Subscription plan name"), + /** Billing cycle */ + billingCycle: external_exports.enum(["monthly", "annual"]).optional(), + /** Price per billing cycle (in cents) */ + priceInCents: external_exports.number().int().min(0).optional(), + /** Current period start */ + currentPeriodStart: external_exports.string().datetime().optional(), + /** Current period end */ + currentPeriodEnd: external_exports.string().datetime().optional(), + /** Trial end date (if trialing) */ + trialEndDate: external_exports.string().datetime().optional(), + /** Whether auto-renew is on */ + autoRenew: external_exports.boolean().default(true), + /** Created timestamp */ + createdAt: external_exports.string().datetime() +}); +var InstalledAppSummarySchema = external_exports.object({ + /** Listing ID */ + listingId: external_exports.string(), + /** Package ID */ + packageId: external_exports.string(), + /** Display name */ + name: external_exports.string(), + /** Icon URL */ + iconUrl: external_exports.string().url().optional(), + /** Installed version */ + installedVersion: external_exports.string(), + /** Latest available version */ + latestVersion: external_exports.string().optional(), + /** Whether an update is available */ + updateAvailable: external_exports.boolean().default(false), + /** Whether the app is currently enabled */ + enabled: external_exports.boolean().default(true), + /** Subscription status (for paid apps) */ + subscriptionStatus: SubscriptionStatusSchema.optional(), + /** Installed timestamp */ + installedAt: external_exports.string().datetime() +}); +var ListInstalledAppsRequestSchema = external_exports.object({ + /** Tenant ID */ + tenantId: external_exports.string().optional(), + /** Filter by enabled/disabled */ + enabled: external_exports.boolean().optional(), + /** Filter by update availability */ + updateAvailable: external_exports.boolean().optional(), + /** Sort by */ + sortBy: external_exports.enum(["name", "installed-date", "updated-date"]).default("name"), + /** Pagination */ + page: external_exports.number().int().min(1).default(1), + pageSize: external_exports.number().int().min(1).max(100).default(20) +}); +var ListInstalledAppsResponseSchema = external_exports.object({ + /** Installed apps */ + items: external_exports.array(InstalledAppSummarySchema), + /** Total count */ + total: external_exports.number().int().min(0), + /** Pagination */ + page: external_exports.number().int().min(1), + pageSize: external_exports.number().int().min(1) +}); +var qa_exports2 = {}; +__export4(qa_exports2, { + TestActionSchema: () => TestActionSchema, + TestActionTypeSchema: () => TestActionTypeSchema, + TestAssertionSchema: () => TestAssertionSchema, + TestAssertionTypeSchema: () => TestAssertionTypeSchema, + TestContextSchema: () => TestContextSchema, + TestScenarioSchema: () => TestScenarioSchema, + TestStepSchema: () => TestStepSchema, + TestSuiteSchema: () => TestSuiteSchema +}); +var TestContextSchema = external_exports.record(external_exports.string(), external_exports.unknown()).describe("Initial context or variables for the test"); +var TestActionTypeSchema = external_exports.enum([ + "create_record", + "update_record", + "delete_record", + "read_record", + "query_records", + "api_call", + "run_script", + "wait" + // Testing async processes +]).describe("Type of test action to perform"); +var TestActionSchema = external_exports.object({ + type: TestActionTypeSchema.describe("The action type to execute"), + target: external_exports.string().describe("Target Object, API Endpoint, or Function Name"), + payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Data to send or use"), + user: external_exports.string().optional().describe("Run as specific user/role for impersonation testing") +}).describe("A single test action to execute against the system"); +var TestAssertionTypeSchema = external_exports.enum([ + "equals", + "not_equals", + "contains", + "not_contains", + "is_null", + "not_null", + "gt", + "gte", + "lt", + "lte", + "error" + // Expecting an error +]).describe("Comparison operator for test assertions"); +var TestAssertionSchema = external_exports.object({ + field: external_exports.string().describe('Field path in the result to check (e.g. "body.data.0.status")'), + operator: TestAssertionTypeSchema.describe("Comparison operator to use"), + expectedValue: external_exports.unknown().describe("Expected value to compare against") +}).describe("A test assertion that validates the result of a test action"); +var TestStepSchema = external_exports.object({ + name: external_exports.string().describe("Step name for identification in test reports"), + description: external_exports.string().optional().describe("Human-readable description of what this step tests"), + action: TestActionSchema.describe("The action to execute in this step"), + assertions: external_exports.array(TestAssertionSchema).optional().describe("Assertions to validate after the action completes"), + // Capture outputs to variables for subsequent steps + capture: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Map result fields to context variables: { "newId": "body.id" }') +}).describe("A single step in a test scenario, consisting of an action and optional assertions"); +var TestScenarioSchema = external_exports.object({ + id: external_exports.string().describe("Unique scenario identifier"), + name: external_exports.string().describe("Scenario name for test reports"), + description: external_exports.string().optional().describe("Detailed description of the test scenario"), + tags: external_exports.array(external_exports.string()).optional().describe('Tags for filtering and categorization (e.g. "critical", "regression", "crm")'), + setup: external_exports.array(TestStepSchema).optional().describe("Steps to run before main test (preconditions)"), + steps: external_exports.array(TestStepSchema).describe("Main test sequence to execute"), + teardown: external_exports.array(TestStepSchema).optional().describe("Steps to cleanup after test execution"), + // Environment requirements + requires: external_exports.object({ + params: external_exports.array(external_exports.string()).optional().describe("Required environment variables or parameters"), + plugins: external_exports.array(external_exports.string()).optional().describe("Required plugins that must be loaded") + }).optional().describe("Environment requirements for this scenario") +}).describe("A complete test scenario with setup, execution steps, and teardown"); +var TestSuiteSchema = external_exports.object({ + name: external_exports.string().describe("Test suite name"), + scenarios: external_exports.array(TestScenarioSchema).describe("List of test scenarios in this suite") +}).describe("A collection of test scenarios grouped into a test suite"); +var identity_exports = {}; +__export4(identity_exports, { + AUTH_CONSTANTS: () => AUTH_CONSTANTS, + AUTH_ERROR_CODES: () => AUTH_ERROR_CODES, + AccountSchema: () => AccountSchema, + ApiKeySchema: () => ApiKeySchema, + InvitationSchema: () => InvitationSchema, + InvitationStatus: () => InvitationStatus, + MemberSchema: () => MemberSchema, + OrganizationSchema: () => OrganizationSchema, + RoleSchema: () => RoleSchema, + SCIM: () => SCIM, + SCIMAddressSchema: () => SCIMAddressSchema, + SCIMBulkOperationSchema: () => SCIMBulkOperationSchema, + SCIMBulkRequestSchema: () => SCIMBulkRequestSchema, + SCIMBulkResponseOperationSchema: () => SCIMBulkResponseOperationSchema, + SCIMBulkResponseSchema: () => SCIMBulkResponseSchema, + SCIMEmailSchema: () => SCIMEmailSchema, + SCIMEnterpriseUserSchema: () => SCIMEnterpriseUserSchema, + SCIMErrorSchema: () => SCIMErrorSchema, + SCIMGroupReferenceSchema: () => SCIMGroupReferenceSchema, + SCIMGroupSchema: () => SCIMGroupSchema, + SCIMListResponseSchema: () => SCIMListResponseSchema, + SCIMMemberReferenceSchema: () => SCIMMemberReferenceSchema, + SCIMMetaSchema: () => SCIMMetaSchema, + SCIMNameSchema: () => SCIMNameSchema, + SCIMPatchOperationSchema: () => SCIMPatchOperationSchema, + SCIMPatchRequestSchema: () => SCIMPatchRequestSchema, + SCIMPhoneNumberSchema: () => SCIMPhoneNumberSchema, + SCIMUserSchema: () => SCIMUserSchema, + SCIM_SCHEMAS: () => SCIM_SCHEMAS, + SessionSchema: () => SessionSchema2, + UserSchema: () => UserSchema, + VerificationTokenSchema: () => VerificationTokenSchema +}); +var UserSchema = external_exports.object({ + /** + * Unique user identifier + */ + id: external_exports.string().describe("Unique user identifier"), + /** + * User's email address (primary identifier) + */ + email: external_exports.string().email().describe("User email address"), + /** + * Email verification status + */ + emailVerified: external_exports.boolean().default(false).describe("Whether email is verified"), + /** + * User's display name + */ + name: external_exports.string().optional().describe("User display name"), + /** + * User's profile image URL + */ + image: external_exports.string().url().optional().describe("Profile image URL"), + /** + * Account creation timestamp + */ + createdAt: external_exports.string().datetime().describe("Account creation timestamp"), + /** + * Last update timestamp + */ + updatedAt: external_exports.string().datetime().describe("Last update timestamp") +}); +var AccountSchema = external_exports.object({ + /** + * Unique account identifier + */ + id: external_exports.string().describe("Unique account identifier"), + /** + * Associated user ID + */ + userId: external_exports.string().describe("Associated user ID"), + /** + * Account type/provider + */ + type: external_exports.enum([ + "oauth", + "oidc", + "email", + "credentials", + "saml", + "ldap" + ]).describe("Account type"), + /** + * Provider name (e.g., 'google', 'github', 'okta') + */ + provider: external_exports.string().describe("Provider name"), + /** + * Provider account ID + */ + providerAccountId: external_exports.string().describe("Provider account ID"), + /** + * OAuth refresh token + */ + refreshToken: external_exports.string().optional().describe("OAuth refresh token"), + /** + * OAuth access token + */ + accessToken: external_exports.string().optional().describe("OAuth access token"), + /** + * Token expiry timestamp + */ + expiresAt: external_exports.number().optional().describe("Token expiry timestamp (Unix)"), + /** + * OAuth token type + */ + tokenType: external_exports.string().optional().describe("OAuth token type"), + /** + * OAuth scope + */ + scope: external_exports.string().optional().describe("OAuth scope"), + /** + * OAuth ID token + */ + idToken: external_exports.string().optional().describe("OAuth ID token"), + /** + * Session state + */ + sessionState: external_exports.string().optional().describe("Session state"), + /** + * Account creation timestamp + */ + createdAt: external_exports.string().datetime().describe("Account creation timestamp"), + /** + * Last update timestamp + */ + updatedAt: external_exports.string().datetime().describe("Last update timestamp") +}); +var SessionSchema2 = external_exports.object({ + /** + * Unique session identifier + */ + id: external_exports.string().describe("Unique session identifier"), + /** + * Session token + */ + sessionToken: external_exports.string().describe("Session token"), + /** + * Associated user ID + */ + userId: external_exports.string().describe("Associated user ID"), + /** + * Active organization ID for this session + * Used for context switching in multi-tenant applications + */ + activeOrganizationId: external_exports.string().optional().describe("Active organization ID for context switching"), + /** + * Session expiry timestamp + */ + expires: external_exports.string().datetime().describe("Session expiry timestamp"), + /** + * Session creation timestamp + */ + createdAt: external_exports.string().datetime().describe("Session creation timestamp"), + /** + * Last update timestamp + */ + updatedAt: external_exports.string().datetime().describe("Last update timestamp"), + /** + * IP address of the session + */ + ipAddress: external_exports.string().optional().describe("IP address"), + /** + * User agent string + */ + userAgent: external_exports.string().optional().describe("User agent string"), + /** + * Device fingerprint + */ + fingerprint: external_exports.string().optional().describe("Device fingerprint") +}); +var VerificationTokenSchema = external_exports.object({ + /** + * Token identifier (email or phone) + */ + identifier: external_exports.string().describe("Token identifier (email or phone)"), + /** + * Verification token + */ + token: external_exports.string().describe("Verification token"), + /** + * Token expiry timestamp + */ + expires: external_exports.string().datetime().describe("Token expiry timestamp"), + /** + * Token creation timestamp + */ + createdAt: external_exports.string().datetime().describe("Token creation timestamp") +}); +var ApiKeySchema = external_exports.object({ + /** + * Unique API key identifier + */ + id: external_exports.string().describe("API key identifier"), + /** + * Human-readable name for the key + */ + name: external_exports.string().describe("API key display name"), + /** + * Key prefix (visible portion for identification, e.g., "os_pk_ab") + */ + start: external_exports.string().optional().describe("Key prefix for identification"), + /** + * Custom prefix for the key (e.g., "os_pk_") + */ + prefix: external_exports.string().optional().describe("Custom key prefix"), + /** + * User ID of the key owner + */ + userId: external_exports.string().describe("Owner user ID"), + /** + * Organization ID the key is scoped to (optional) + */ + organizationId: external_exports.string().optional().describe("Scoped organization ID"), + /** + * Key expiration timestamp (null = never expires) + */ + expiresAt: external_exports.string().datetime().optional().describe("Expiration timestamp"), + /** + * Creation timestamp + */ + createdAt: external_exports.string().datetime().describe("Creation timestamp"), + /** + * Last update timestamp + */ + updatedAt: external_exports.string().datetime().describe("Last update timestamp"), + /** + * Last used timestamp + */ + lastUsedAt: external_exports.string().datetime().optional().describe("Last used timestamp"), + /** + * Last refetch timestamp (for cached permission checks) + */ + lastRefetchAt: external_exports.string().datetime().optional().describe("Last refetch timestamp"), + /** + * Whether this key is enabled + */ + enabled: external_exports.boolean().default(true).describe("Whether the key is active"), + /** + * Rate limiting: enabled flag + */ + rateLimitEnabled: external_exports.boolean().optional().describe("Whether rate limiting is enabled"), + /** + * Rate limiting: time window in milliseconds + */ + rateLimitTimeWindow: external_exports.number().int().min(0).optional().describe("Rate limit window (ms)"), + /** + * Rate limiting: max requests per window + */ + rateLimitMax: external_exports.number().int().min(0).optional().describe("Max requests per window"), + /** + * Rate limiting: remaining requests in current window + */ + remaining: external_exports.number().int().min(0).optional().describe("Remaining requests"), + /** + * Permissions assigned to this key (granular access control) + */ + permissions: external_exports.record(external_exports.string(), external_exports.boolean()).optional().describe("Granular permission flags"), + /** + * Scopes assigned to this key (high-level access categories) + */ + scopes: external_exports.array(external_exports.string()).optional().describe("High-level access scopes"), + /** + * Custom metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") +}); +var AUTH_CONSTANTS = { + /** + * HTTP header key for authentication tokens + */ + HEADER_KEY: "Authorization", + /** + * Token prefix for Bearer authentication + */ + TOKEN_PREFIX: "Bearer ", + /** + * Cookie prefix for ObjectStack auth cookies + */ + COOKIE_PREFIX: "os_", + /** + * CSRF token header name + */ + CSRF_HEADER: "x-os-csrf-token", + /** + * Default session cookie name + */ + SESSION_COOKIE: "os_session_token", + /** + * Default CSRF cookie name + */ + CSRF_COOKIE: "os_csrf_token", + /** + * Refresh token cookie name + */ + REFRESH_TOKEN_COOKIE: "os_refresh_token" +}; +var AUTH_ERROR_CODES = { + INVALID_CREDENTIALS: "invalid_credentials", + INVALID_TOKEN: "invalid_token", + TOKEN_EXPIRED: "token_expired", + INSUFFICIENT_PERMISSIONS: "insufficient_permissions", + ACCOUNT_LOCKED: "account_locked", + ACCOUNT_NOT_VERIFIED: "account_not_verified", + TOO_MANY_REQUESTS: "too_many_requests", + INVALID_CSRF_TOKEN: "invalid_csrf_token", + SESSION_EXPIRED: "session_expired", + OAUTH_ERROR: "oauth_error", + PROVIDER_ERROR: "provider_error" +}; +var RoleSchema = external_exports.object({ + /** Identity */ + name: SnakeCaseIdentifierSchema7.describe("Unique role name (lowercase snake_case)"), + label: external_exports.string().describe("Display label (e.g. VP of Sales)"), + /** Hierarchy */ + parent: external_exports.string().optional().describe("Parent Role ID (Reports To)"), + /** Description */ + description: external_exports.string().optional() +}); +var OrganizationSchema = external_exports.object({ + /** + * Unique organization identifier + */ + id: external_exports.string().describe("Unique organization identifier"), + /** + * Organization name (display name) + */ + name: external_exports.string().describe("Organization display name"), + /** + * Organization slug (URL-friendly identifier) + * Must be unique across all organizations + */ + slug: external_exports.string().regex(/^[a-z0-9_-]+$/).describe("Unique URL-friendly slug (lowercase alphanumeric, hyphens, underscores)"), + /** + * Organization logo URL + */ + logo: external_exports.string().url().optional().describe("Organization logo URL"), + /** + * Custom metadata for the organization + * Can store additional configuration, settings, or custom fields + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata"), + /** + * Organization creation timestamp + */ + createdAt: external_exports.string().datetime().describe("Organization creation timestamp"), + /** + * Last update timestamp + */ + updatedAt: external_exports.string().datetime().describe("Last update timestamp") +}); +var MemberSchema = external_exports.object({ + /** + * Unique member identifier + */ + id: external_exports.string().describe("Unique member identifier"), + /** + * Organization ID this membership belongs to + */ + organizationId: external_exports.string().describe("Organization ID"), + /** + * User ID of the member + */ + userId: external_exports.string().describe("User ID"), + /** + * Member's role within the organization + * Common roles: 'owner', 'admin', 'member', 'guest' + * Can be customized per application + */ + role: external_exports.string().describe("Member role (e.g., owner, admin, member, guest)"), + /** + * Member creation timestamp + */ + createdAt: external_exports.string().datetime().describe("Member creation timestamp"), + /** + * Last update timestamp + */ + updatedAt: external_exports.string().datetime().describe("Last update timestamp") +}); +var InvitationStatus = external_exports.enum(["pending", "accepted", "rejected", "expired"]); +var InvitationSchema = external_exports.object({ + /** + * Unique invitation identifier + */ + id: external_exports.string().describe("Unique invitation identifier"), + /** + * Organization ID the invitation is for + */ + organizationId: external_exports.string().describe("Organization ID"), + /** + * Email address of the invitee + */ + email: external_exports.string().email().describe("Invitee email address"), + /** + * Role the invitee will receive upon accepting + * Common roles: 'admin', 'member', 'guest' + */ + role: external_exports.string().describe("Role to assign upon acceptance"), + /** + * Invitation status + */ + status: InvitationStatus.default("pending").describe("Invitation status"), + /** + * Invitation expiration timestamp + */ + expiresAt: external_exports.string().datetime().describe("Invitation expiry timestamp"), + /** + * User ID of the person who sent the invitation + */ + inviterId: external_exports.string().describe("User ID of the inviter"), + /** + * Invitation creation timestamp + */ + createdAt: external_exports.string().datetime().describe("Invitation creation timestamp"), + /** + * Last update timestamp + */ + updatedAt: external_exports.string().datetime().describe("Last update timestamp") +}); +var SCIM_SCHEMAS = { + USER: "urn:ietf:params:scim:schemas:core:2.0:User", + GROUP: "urn:ietf:params:scim:schemas:core:2.0:Group", + ENTERPRISE_USER: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User", + RESOURCE_TYPE: "urn:ietf:params:scim:schemas:core:2.0:ResourceType", + SERVICE_PROVIDER_CONFIG: "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig", + SCHEMA: "urn:ietf:params:scim:schemas:core:2.0:Schema", + LIST_RESPONSE: "urn:ietf:params:scim:api:messages:2.0:ListResponse", + PATCH_OP: "urn:ietf:params:scim:api:messages:2.0:PatchOp", + BULK_REQUEST: "urn:ietf:params:scim:api:messages:2.0:BulkRequest", + BULK_RESPONSE: "urn:ietf:params:scim:api:messages:2.0:BulkResponse", + ERROR: "urn:ietf:params:scim:api:messages:2.0:Error" +}; +var SCIMMetaSchema = external_exports.object({ + /** + * Resource type name + * @example "User", "Group" + */ + resourceType: external_exports.string().optional().describe("Resource type"), + /** + * Resource creation timestamp (ISO 8601) + */ + created: external_exports.string().datetime().optional().describe("Creation timestamp"), + /** + * Last modification timestamp (ISO 8601) + */ + lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), + /** + * Resource location URI + * Absolute URL to the resource + */ + location: external_exports.string().url().optional().describe("Resource location URI"), + /** + * Entity tag for optimistic concurrency control + * Used with If-Match header for conditional updates + */ + version: external_exports.string().optional().describe("Entity tag (ETag) for concurrency control") +}); +var SCIMNameSchema = external_exports.object({ + /** + * Full name formatted for display + * @example "Ms. Barbara Jane Jensen III" + */ + formatted: external_exports.string().optional().describe("Formatted full name"), + /** + * Family name (surname) + * @example "Jensen" + */ + familyName: external_exports.string().optional().describe("Family name (last name)"), + /** + * Given name (first name) + * @example "Barbara" + */ + givenName: external_exports.string().optional().describe("Given name (first name)"), + /** + * Middle name + * @example "Jane" + */ + middleName: external_exports.string().optional().describe("Middle name"), + /** + * Honorific prefix + * @example "Ms.", "Dr.", "Prof." + */ + honorificPrefix: external_exports.string().optional().describe("Honorific prefix (Mr., Ms., Dr.)"), + /** + * Honorific suffix + * @example "III", "Jr.", "Sr." + */ + honorificSuffix: external_exports.string().optional().describe("Honorific suffix (Jr., Sr.)") +}); +var SCIMEmailSchema = external_exports.object({ + /** + * Email address value + */ + value: external_exports.string().email().describe("Email address"), + /** + * Email type + * @example "work", "home", "other" + */ + type: external_exports.enum(["work", "home", "other"]).optional().describe("Email type"), + /** + * Display label for the email + */ + display: external_exports.string().optional().describe("Display label"), + /** + * Whether this is the primary email + */ + primary: external_exports.boolean().optional().default(false).describe("Primary email indicator") +}); +var SCIMPhoneNumberSchema = external_exports.object({ + /** + * Phone number value + * Format is not enforced to support international numbers + */ + value: external_exports.string().describe("Phone number"), + /** + * Phone type + */ + type: external_exports.enum(["work", "home", "mobile", "fax", "pager", "other"]).optional().describe("Phone number type"), + /** + * Display label for the phone number + */ + display: external_exports.string().optional().describe("Display label"), + /** + * Whether this is the primary phone + */ + primary: external_exports.boolean().optional().default(false).describe("Primary phone indicator") +}); +var SCIMAddressSchema = external_exports.object({ + /** + * Full mailing address formatted for display + */ + formatted: external_exports.string().optional().describe("Formatted address"), + /** + * Full street address + */ + streetAddress: external_exports.string().optional().describe("Street address"), + /** + * City or locality + */ + locality: external_exports.string().optional().describe("City/Locality"), + /** + * State or region + */ + region: external_exports.string().optional().describe("State/Region"), + /** + * Zip code or postal code + */ + postalCode: external_exports.string().optional().describe("Postal code"), + /** + * Country + */ + country: external_exports.string().optional().describe("Country"), + /** + * Address type + */ + type: external_exports.enum(["work", "home", "other"]).optional().describe("Address type"), + /** + * Whether this is the primary address + */ + primary: external_exports.boolean().optional().default(false).describe("Primary address indicator") +}); +var SCIMGroupReferenceSchema = external_exports.object({ + /** + * Group identifier + */ + value: external_exports.string().describe("Group ID"), + /** + * Direct reference to the group resource + */ + $ref: external_exports.string().url().optional().describe("URI reference to the group"), + /** + * Human-readable group name + */ + display: external_exports.string().optional().describe("Group display name"), + /** + * Type of group + */ + type: external_exports.enum(["direct", "indirect"]).optional().describe("Membership type") +}); +var SCIMEnterpriseUserSchema = external_exports.object({ + /** + * Employee number + */ + employeeNumber: external_exports.string().optional().describe("Employee number"), + /** + * Cost center + */ + costCenter: external_exports.string().optional().describe("Cost center"), + /** + * Organization unit + */ + organization: external_exports.string().optional().describe("Organization"), + /** + * Division + */ + division: external_exports.string().optional().describe("Division"), + /** + * Department + */ + department: external_exports.string().optional().describe("Department"), + /** + * Manager reference + */ + manager: external_exports.object({ + value: external_exports.string().describe("Manager ID"), + $ref: external_exports.string().url().optional().describe("Manager URI"), + displayName: external_exports.string().optional().describe("Manager name") + }).optional().describe("Manager reference") +}); +var SCIMUserSchema = external_exports.object({ + /** + * SCIM schema URIs + * Must include at minimum the core User schema URI + */ + schemas: external_exports.array(external_exports.string()).min(1).refine( + (schemas) => schemas.includes(SCIM_SCHEMAS.USER), + "Must include core User schema URI" + ).default([SCIM_SCHEMAS.USER]).describe("SCIM schema URIs (must include User schema)"), + /** + * Unique identifier + */ + id: external_exports.string().optional().describe("Unique resource identifier"), + /** + * External identifier + * Identifier from the provisioning client + */ + externalId: external_exports.string().optional().describe("External identifier from client system"), + /** + * Unique username + * REQUIRED for user creation + */ + userName: external_exports.string().describe("Unique username (REQUIRED)"), + /** + * Structured name + */ + name: SCIMNameSchema.optional().describe("Structured name components"), + /** + * Display name + */ + displayName: external_exports.string().optional().describe("Display name for UI"), + /** + * Nickname or casual name + */ + nickName: external_exports.string().optional().describe("Nickname"), + /** + * Profile URL + */ + profileUrl: external_exports.string().url().optional().describe("Profile page URL"), + /** + * Job title + */ + title: external_exports.string().optional().describe("Job title"), + /** + * User type (employee, contractor, etc.) + */ + userType: external_exports.string().optional().describe("User type (employee, contractor)"), + /** + * Preferred language (ISO 639-1) + */ + preferredLanguage: external_exports.string().optional().describe("Preferred language (ISO 639-1)"), + /** + * Locale (e.g., en-US) + */ + locale: external_exports.string().optional().describe("Locale (e.g., en-US)"), + /** + * Timezone (e.g., America/Los_Angeles) + */ + timezone: external_exports.string().optional().describe("Timezone"), + /** + * Account active status + */ + active: external_exports.boolean().optional().default(true).describe("Account active status"), + /** + * Password (write-only, never returned) + */ + password: external_exports.string().optional().describe("Password (write-only)"), + /** + * Email addresses (multi-valued) + */ + emails: external_exports.array(SCIMEmailSchema).optional().describe("Email addresses"), + /** + * Phone numbers (multi-valued) + */ + phoneNumbers: external_exports.array(SCIMPhoneNumberSchema).optional().describe("Phone numbers"), + /** + * Instant messaging addresses + */ + ims: external_exports.array(external_exports.object({ + value: external_exports.string(), + type: external_exports.string().optional(), + primary: external_exports.boolean().optional() + })).optional().describe("IM addresses"), + /** + * Photos (profile pictures) + */ + photos: external_exports.array(external_exports.object({ + value: external_exports.string().url(), + type: external_exports.enum(["photo", "thumbnail"]).optional(), + primary: external_exports.boolean().optional() + })).optional().describe("Photo URLs"), + /** + * Physical addresses + */ + addresses: external_exports.array(SCIMAddressSchema).optional().describe("Physical addresses"), + /** + * Group memberships + */ + groups: external_exports.array(SCIMGroupReferenceSchema).optional().describe("Group memberships"), + /** + * User entitlements + */ + entitlements: external_exports.array(external_exports.object({ + value: external_exports.string(), + type: external_exports.string().optional(), + primary: external_exports.boolean().optional() + })).optional().describe("Entitlements"), + /** + * User roles + */ + roles: external_exports.array(external_exports.object({ + value: external_exports.string(), + type: external_exports.string().optional(), + primary: external_exports.boolean().optional() + })).optional().describe("Roles"), + /** + * X509 certificates + */ + x509Certificates: external_exports.array(external_exports.object({ + value: external_exports.string(), + type: external_exports.string().optional(), + primary: external_exports.boolean().optional() + })).optional().describe("X509 certificates"), + /** + * Resource metadata + */ + meta: SCIMMetaSchema.optional().describe("Resource metadata"), + /** + * Enterprise user extension + * Only present when enterprise extension is used + */ + [SCIM_SCHEMAS.ENTERPRISE_USER]: SCIMEnterpriseUserSchema.optional().describe("Enterprise user attributes") +}).superRefine((data, ctx) => { + const hasEnterpriseExtension = data[SCIM_SCHEMAS.ENTERPRISE_USER] != null; + if (!hasEnterpriseExtension) { + return; + } + const schemas = data.schemas || []; + if (!schemas.includes(SCIM_SCHEMAS.ENTERPRISE_USER)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: ["schemas"], + message: `schemas must include "${SCIM_SCHEMAS.ENTERPRISE_USER}" when enterprise user extension attributes are present` + }); + } +}); +var SCIMMemberReferenceSchema = external_exports.object({ + /** + * Member identifier + */ + value: external_exports.string().describe("Member ID"), + /** + * Direct reference to the member resource + */ + $ref: external_exports.string().url().optional().describe("URI reference to the member"), + /** + * Member type (User or Group for nested groups) + */ + type: external_exports.enum(["User", "Group"]).optional().describe("Member type"), + /** + * Human-readable member name + */ + display: external_exports.string().optional().describe("Member display name") +}); +var SCIMGroupSchema = external_exports.object({ + /** + * SCIM schema URIs + * Must include at minimum the core Group schema URI + */ + schemas: external_exports.array(external_exports.string()).min(1).refine( + (schemas) => schemas.includes(SCIM_SCHEMAS.GROUP), + "Must include core Group schema URI" + ).default([SCIM_SCHEMAS.GROUP]).describe("SCIM schema URIs (must include Group schema)"), + /** + * Unique identifier + */ + id: external_exports.string().optional().describe("Unique resource identifier"), + /** + * External identifier + */ + externalId: external_exports.string().optional().describe("External identifier from client system"), + /** + * Group display name + * REQUIRED for group creation + */ + displayName: external_exports.string().describe("Group display name (REQUIRED)"), + /** + * Group members + */ + members: external_exports.array(SCIMMemberReferenceSchema).optional().describe("Group members"), + /** + * Resource metadata + */ + meta: SCIMMetaSchema.optional().describe("Resource metadata") +}); +var SCIMListResponseSchema = external_exports.object({ + /** + * SCIM schema URI + */ + schemas: external_exports.array(external_exports.string()).min(1).refine( + (schemas) => schemas.includes(SCIM_SCHEMAS.LIST_RESPONSE), + { message: `schemas must include ${SCIM_SCHEMAS.LIST_RESPONSE}` } + ).default([SCIM_SCHEMAS.LIST_RESPONSE]).describe("SCIM schema URIs"), + /** + * Total number of results matching the query + */ + totalResults: external_exports.number().int().min(0).describe("Total results count"), + /** + * Resources returned in this response + * Use SCIMListResponseOf for type-safe responses + */ + Resources: external_exports.array(external_exports.union([SCIMUserSchema, SCIMGroupSchema, external_exports.record(external_exports.string(), external_exports.unknown())])).describe("Resources array (Users, Groups, or custom resources)"), + /** + * 1-based index of the first result + */ + startIndex: external_exports.number().int().min(1).optional().describe("Start index (1-based)"), + /** + * Number of resources per page + */ + itemsPerPage: external_exports.number().int().min(0).optional().describe("Items per page") +}); +var SCIMErrorSchema = external_exports.object({ + /** + * SCIM schema URI + */ + schemas: external_exports.array(external_exports.string()).min(1).refine( + (schemas) => schemas.includes(SCIM_SCHEMAS.ERROR), + { message: `schemas must include ${SCIM_SCHEMAS.ERROR}` } + ).default([SCIM_SCHEMAS.ERROR]).describe("SCIM schema URIs"), + /** + * HTTP status code + */ + status: external_exports.number().int().min(400).max(599).describe("HTTP status code"), + /** + * SCIM error type + */ + scimType: external_exports.enum([ + "invalidFilter", + "tooMany", + "uniqueness", + "mutability", + "invalidSyntax", + "invalidPath", + "noTarget", + "invalidValue", + "invalidVers", + "sensitive" + ]).optional().describe("SCIM error type"), + /** + * Human-readable error description + */ + detail: external_exports.string().optional().describe("Error detail message") +}); +var SCIMPatchOperationSchema = external_exports.object({ + /** + * Operation type + */ + op: external_exports.enum(["add", "remove", "replace"]).describe("Operation type"), + /** + * Attribute path to modify + */ + path: external_exports.string().optional().describe("Attribute path (optional for add)"), + /** + * Value to set + */ + value: external_exports.unknown().optional().describe("Value to set") +}); +var SCIMPatchRequestSchema = external_exports.object({ + /** + * SCIM schema URI + */ + schemas: external_exports.array(external_exports.string()).min(1).refine( + (schemas) => schemas.includes(SCIM_SCHEMAS.PATCH_OP), + { message: "SCIM PATCH requests must include the PatchOp schema URI" } + ).default([SCIM_SCHEMAS.PATCH_OP]).describe("SCIM schema URIs"), + /** + * Array of patch operations + */ + Operations: external_exports.array(SCIMPatchOperationSchema).min(1).describe("Patch operations") +}); +var SCIM = { + /** + * Create a basic SCIM user + */ + user: (userName, email3, givenName, familyName) => ({ + schemas: [SCIM_SCHEMAS.USER], + userName, + emails: [{ value: email3, type: "work", primary: true }], + name: { + givenName, + familyName + }, + active: true + }), + /** + * Create a SCIM group + */ + group: (displayName, members) => ({ + schemas: [SCIM_SCHEMAS.GROUP], + displayName, + members: members || [] + }), + /** + * Create a list response + */ + listResponse: (resources, totalResults) => ({ + schemas: [SCIM_SCHEMAS.LIST_RESPONSE], + totalResults: totalResults ?? resources.length, + Resources: resources, + startIndex: 1, + itemsPerPage: resources.length + }), + /** + * Create an error response + */ + error: (status, detail, scimType) => ({ + schemas: [SCIM_SCHEMAS.ERROR], + status, + detail, + scimType + }) +}; +var SCIMBulkOperationSchema = external_exports.object({ + /** HTTP method for this operation */ + method: external_exports.enum(["POST", "PUT", "PATCH", "DELETE"]).describe("HTTP method for the bulk operation"), + /** Resource path (e.g. /Users, /Groups/{id}) */ + path: external_exports.string().describe("Resource endpoint path (e.g. /Users, /Groups/{id})"), + /** Client-assigned identifier for cross-referencing operations */ + bulkId: external_exports.string().optional().describe("Client-assigned ID for cross-referencing between operations"), + /** Request body for POST/PUT/PATCH operations */ + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Request body for POST/PUT/PATCH operations"), + /** ETag value for optimistic concurrency control */ + version: external_exports.string().optional().describe("ETag for optimistic concurrency control") +}); +var SCIMBulkRequestSchema = external_exports.object({ + /** SCIM schema URI for bulk request */ + schemas: external_exports.array(external_exports.literal(SCIM_SCHEMAS.BULK_REQUEST)).default([SCIM_SCHEMAS.BULK_REQUEST]).describe("SCIM schema URIs (BulkRequest)"), + /** Array of operations to execute */ + operations: external_exports.array(SCIMBulkOperationSchema).min(1).describe("Bulk operations to execute (minimum 1)"), + /** Stop processing after N errors */ + failOnErrors: external_exports.number().int().optional().describe("Stop processing after this many errors") +}); +var SCIMBulkResponseOperationSchema = external_exports.object({ + /** HTTP method that was executed */ + method: external_exports.enum(["POST", "PUT", "PATCH", "DELETE"]).describe("HTTP method that was executed"), + /** Client-assigned bulk operation ID */ + bulkId: external_exports.string().optional().describe("Client-assigned bulk operation ID"), + /** URL of the created/modified resource */ + location: external_exports.string().optional().describe("URL of the created or modified resource"), + /** HTTP status code as string */ + status: external_exports.string().describe('HTTP status code as string (e.g. "201", "400")'), + /** Response body, typically present for errors */ + response: external_exports.unknown().optional().describe("Response body (typically present for errors)") +}); +var SCIMBulkResponseSchema = external_exports.object({ + /** SCIM schema URI for bulk response */ + schemas: external_exports.array(external_exports.literal(SCIM_SCHEMAS.BULK_RESPONSE)).default([SCIM_SCHEMAS.BULK_RESPONSE]).describe("SCIM schema URIs (BulkResponse)"), + /** Array of operation results */ + operations: external_exports.array(SCIMBulkResponseOperationSchema).describe("Results for each bulk operation") +}); +var ai_exports = {}; +__export4(ai_exports, { + AICodeReviewResultSchema: () => AICodeReviewResultSchema, + AIKnowledgeSchema: () => AIKnowledgeSchema, + AIModelConfigSchema: () => AIModelConfigSchema, + AIOperationCostSchema: () => AIOperationCostSchema, + AIOpsAgentConfigSchema: () => AIOpsAgentConfigSchema, + AIOrchestrationExecutionResultSchema: () => AIOrchestrationExecutionResultSchema, + AIOrchestrationSchema: () => AIOrchestrationSchema, + AIOrchestrationTriggerSchema: () => AIOrchestrationTriggerSchema, + AITaskSchema: () => AITaskSchema, + AITaskTypeSchema: () => AITaskTypeSchema, + AIToolSchema: () => AIToolSchema, + AgentActionResultSchema: () => AgentActionResultSchema, + AgentActionSchema: () => AgentActionSchema, + AgentActionSequenceResultSchema: () => AgentActionSequenceResultSchema, + AgentActionSequenceSchema: () => AgentActionSequenceSchema, + AgentCommunicationProtocolSchema: () => AgentCommunicationProtocolSchema, + AgentGroupMemberSchema: () => AgentGroupMemberSchema, + AgentGroupRoleSchema: () => AgentGroupRoleSchema, + AgentSchema: () => AgentSchema, + AnomalyDetectionConfigSchema: () => AnomalyDetectionConfigSchema, + AutoScalingPolicySchema: () => AutoScalingPolicySchema, + BatchAIOrchestrationExecutionSchema: () => BatchAIOrchestrationExecutionSchema, + BillingPeriodSchema: () => BillingPeriodSchema, + BudgetLimitSchema: () => BudgetLimitSchema, + BudgetStatusSchema: () => BudgetStatusSchema, + BudgetTypeSchema: () => BudgetTypeSchema, + CICDPipelineConfigSchema: () => CICDPipelineConfigSchema, + ChunkingStrategySchema: () => ChunkingStrategySchema, + CodeContentSchema: () => CodeContentSchema, + CodeGenerationConfigSchema: () => CodeGenerationConfigSchema, + CodeGenerationRequestSchema: () => CodeGenerationRequestSchema, + CodeGenerationTargetSchema: () => CodeGenerationTargetSchema, + ComponentActionParamsSchema: () => ComponentActionParamsSchema, + ComponentActionTypeSchema: () => ComponentActionTypeSchema, + ComponentAgentActionSchema: () => ComponentAgentActionSchema, + ConversationAnalyticsSchema: () => ConversationAnalyticsSchema, + ConversationContextSchema: () => ConversationContextSchema, + ConversationMessageSchema: () => ConversationMessageSchema, + ConversationSessionSchema: () => ConversationSessionSchema, + ConversationSummarySchema: () => ConversationSummarySchema, + CostAlertSchema: () => CostAlertSchema, + CostAlertTypeSchema: () => CostAlertTypeSchema, + CostAnalyticsSchema: () => CostAnalyticsSchema, + CostBreakdownDimensionSchema: () => CostBreakdownDimensionSchema, + CostBreakdownEntrySchema: () => CostBreakdownEntrySchema, + CostEntrySchema: () => CostEntrySchema, + CostMetricTypeSchema: () => CostMetricTypeSchema, + CostOptimizationRecommendationSchema: () => CostOptimizationRecommendationSchema, + CostQueryFiltersSchema: () => CostQueryFiltersSchema, + CostReportSchema: () => CostReportSchema, + DataActionParamsSchema: () => DataActionParamsSchema, + DataActionTypeSchema: () => DataActionTypeSchema, + DataAgentActionSchema: () => DataAgentActionSchema, + DeploymentStrategySchema: () => DeploymentStrategySchema, + DevOpsAgentSchema: () => DevOpsAgentSchema, + DevOpsToolSchema: () => DevOpsToolSchema, + DevelopmentConfigSchema: () => DevelopmentConfigSchema, + DocumentChunkSchema: () => DocumentChunkSchema, + DocumentLoaderConfigSchema: () => DocumentLoaderConfigSchema, + DocumentMetadataSchema: () => DocumentMetadataSchema, + EmbeddingModelSchema: () => EmbeddingModelSchema, + EntitySchema: () => EntitySchema, + EvaluationMetricsSchema: () => EvaluationMetricsSchema, + FeedbackLoopSchema: () => FeedbackLoopSchema, + FieldSynonymConfigSchema: () => FieldSynonymConfigSchema, + FileContentSchema: () => FileContentSchema, + FilterExpressionSchema: () => FilterExpressionSchema, + FilterGroupSchema: () => FilterGroupSchema, + FormActionParamsSchema: () => FormActionParamsSchema, + FormActionTypeSchema: () => FormActionTypeSchema, + FormAgentActionSchema: () => FormAgentActionSchema, + FunctionCallSchema: () => FunctionCallSchema, + GeneratedCodeSchema: () => GeneratedCodeSchema, + GitHubIntegrationSchema: () => GitHubIntegrationSchema, + HyperparametersSchema: () => HyperparametersSchema, + ImageContentSchema: () => ImageContentSchema, + IntegrationConfigSchema: () => IntegrationConfigSchema, + IntentActionMappingSchema: () => IntentActionMappingSchema, + IssueSchema: () => IssueSchema, + MCPCapabilitySchema: () => MCPCapabilitySchema, + MCPClientConfigSchema: () => MCPClientConfigSchema, + MCPPromptArgumentSchema: () => MCPPromptArgumentSchema, + MCPPromptMessageSchema: () => MCPPromptMessageSchema, + MCPPromptRequestSchema: () => MCPPromptRequestSchema, + MCPPromptResponseSchema: () => MCPPromptResponseSchema, + MCPPromptSchema: () => MCPPromptSchema, + MCPResourceRequestSchema: () => MCPResourceRequestSchema, + MCPResourceResponseSchema: () => MCPResourceResponseSchema, + MCPResourceSchema: () => MCPResourceSchema, + MCPResourceTemplateSchema: () => MCPResourceTemplateSchema, + MCPResourceTypeSchema: () => MCPResourceTypeSchema, + MCPRootEntrySchema: () => MCPRootEntrySchema, + MCPRootsConfigSchema: () => MCPRootsConfigSchema, + MCPSamplingConfigSchema: () => MCPSamplingConfigSchema, + MCPServerConfigSchema: () => MCPServerConfigSchema, + MCPServerInfoSchema: () => MCPServerInfoSchema, + MCPStreamingConfigSchema: () => MCPStreamingConfigSchema, + MCPToolApprovalSchema: () => MCPToolApprovalSchema, + MCPToolCallRequestSchema: () => MCPToolCallRequestSchema, + MCPToolCallResponseSchema: () => MCPToolCallResponseSchema, + MCPToolParameterSchema: () => MCPToolParameterSchema, + MCPToolSchema: () => MCPToolSchema, + MCPTransportConfigSchema: () => MCPTransportConfigSchema, + MCPTransportTypeSchema: () => MCPTransportTypeSchema, + MessageContentSchema: () => MessageContentSchema, + MessageContentTypeSchema: () => MessageContentTypeSchema, + MessagePruningEventSchema: () => MessagePruningEventSchema, + MessageRoleSchema: () => MessageRoleSchema, + MetadataFilterSchema: () => MetadataFilterSchema, + MetadataSourceSchema: () => MetadataSourceSchema22, + ModelCapabilitySchema: () => ModelCapabilitySchema, + ModelConfigSchema: () => ModelConfigSchema, + ModelDriftSchema: () => ModelDriftSchema, + ModelFeatureSchema: () => ModelFeatureSchema, + ModelLimitsSchema: () => ModelLimitsSchema, + ModelPricingSchema: () => ModelPricingSchema, + ModelProviderSchema: () => ModelProviderSchema, + ModelRegistryEntrySchema: () => ModelRegistryEntrySchema, + ModelRegistrySchema: () => ModelRegistrySchema, + ModelSelectionCriteriaSchema: () => ModelSelectionCriteriaSchema, + MonitoringConfigSchema: () => MonitoringConfigSchema, + MultiAgentGroupSchema: () => MultiAgentGroupSchema, + NLQAnalyticsSchema: () => NLQAnalyticsSchema, + NLQFieldMappingSchema: () => NLQFieldMappingSchema, + NLQModelConfigSchema: () => NLQModelConfigSchema, + NLQParseResultSchema: () => NLQParseResultSchema, + NLQRequestSchema: () => NLQRequestSchema, + NLQResponseSchema: () => NLQResponseSchema, + NLQTrainingExampleSchema: () => NLQTrainingExampleSchema, + NavigationActionParamsSchema: () => NavigationActionParamsSchema, + NavigationActionTypeSchema: () => NavigationActionTypeSchema, + NavigationAgentActionSchema: () => NavigationAgentActionSchema, + PerformanceOptimizationSchema: () => PerformanceOptimizationSchema, + PipelineStageSchema: () => PipelineStageSchema, + PluginCompositionRequestSchema: () => PluginCompositionRequestSchema, + PluginCompositionResultSchema: () => PluginCompositionResultSchema, + PluginRecommendationRequestSchema: () => PluginRecommendationRequestSchema, + PluginRecommendationSchema: () => PluginRecommendationSchema, + PluginScaffoldingTemplateSchema: () => PluginScaffoldingTemplateSchema, + PostProcessingActionSchema: () => PostProcessingActionSchema, + PredictionRequestSchema: () => PredictionRequestSchema, + PredictionResultSchema: () => PredictionResultSchema, + PredictiveModelSchema: () => PredictiveModelSchema, + PredictiveModelTypeSchema: () => PredictiveModelTypeSchema, + PromptTemplateSchema: () => PromptTemplateSchema, + PromptVariableSchema: () => PromptVariableSchema, + QueryContextSchema: () => QueryContextSchema, + QueryIntentSchema: () => QueryIntentSchema, + QueryTemplateSchema: () => QueryTemplateSchema, + RAGPipelineConfigSchema: () => RAGPipelineConfigSchema, + RAGPipelineStatusSchema: () => RAGPipelineStatusSchema, + RAGQueryRequestSchema: () => RAGQueryRequestSchema, + RAGQueryResponseSchema: () => RAGQueryResponseSchema, + RerankingConfigSchema: () => RerankingConfigSchema, + ResolutionSchema: () => ResolutionSchema, + RetrievalStrategySchema: () => RetrievalStrategySchema, + RootCauseAnalysisRequestSchema: () => RootCauseAnalysisRequestSchema, + RootCauseAnalysisResultSchema: () => RootCauseAnalysisResultSchema, + SelfHealingActionSchema: () => SelfHealingActionSchema, + SelfHealingConfigSchema: () => SelfHealingConfigSchema, + SkillSchema: () => SkillSchema, + SkillTriggerConditionSchema: () => SkillTriggerConditionSchema, + StructuredOutputConfigSchema: () => StructuredOutputConfigSchema, + StructuredOutputFormatSchema: () => StructuredOutputFormatSchema, + TestingConfigSchema: () => TestingConfigSchema, + TextContentSchema: () => TextContentSchema, + TimeframeSchema: () => TimeframeSchema, + TokenBudgetConfigSchema: () => TokenBudgetConfigSchema, + TokenBudgetStrategySchema: () => TokenBudgetStrategySchema, + TokenUsageSchema: () => TokenUsageSchema, + TokenUsageStatsSchema: () => TokenUsageStatsSchema, + ToolCallSchema: () => ToolCallSchema, + ToolCategorySchema: () => ToolCategorySchema, + ToolSchema: () => ToolSchema, + TrainingConfigSchema: () => TrainingConfigSchema, + TransformPipelineStepSchema: () => TransformPipelineStepSchema, + TypedAgentActionSchema: () => TypedAgentActionSchema, + UIActionTypeSchema: () => UIActionTypeSchema, + VectorStoreConfigSchema: () => VectorStoreConfigSchema, + VectorStoreProviderSchema: () => VectorStoreProviderSchema, + VercelIntegrationSchema: () => VercelIntegrationSchema, + VersionManagementSchema: () => VersionManagementSchema, + ViewActionParamsSchema: () => ViewActionParamsSchema, + ViewActionTypeSchema: () => ViewActionTypeSchema, + ViewAgentActionSchema: () => ViewAgentActionSchema, + WorkflowActionParamsSchema: () => WorkflowActionParamsSchema, + WorkflowActionTypeSchema: () => WorkflowActionTypeSchema, + WorkflowAgentActionSchema: () => WorkflowAgentActionSchema, + WorkflowFieldConditionSchema: () => WorkflowFieldConditionSchema, + WorkflowScheduleSchema: () => WorkflowScheduleSchema, + defineAgent: () => defineAgent, + defineSkill: () => defineSkill, + defineTool: () => defineTool, + fullStackDevOpsAgentExample: () => fullStackDevOpsAgentExample +}); +var AIModelConfigSchema = external_exports.object({ + provider: external_exports.enum(["openai", "azure_openai", "anthropic", "local"]).default("openai"), + model: external_exports.string().describe("Model name (e.g. gpt-4, claude-3-opus)"), + temperature: external_exports.number().min(0).max(2).default(0.7), + maxTokens: external_exports.number().optional(), + topP: external_exports.number().optional() +}); +var AIToolSchema = external_exports.object({ + type: external_exports.enum(["action", "flow", "query", "vector_search"]), + name: external_exports.string().describe("Reference name (Action Name, Flow Name)"), + description: external_exports.string().optional().describe("Override description for the LLM") +}); +var AIKnowledgeSchema = external_exports.object({ + topics: external_exports.array(external_exports.string()).describe("Topics/Tags to recruit knowledge from"), + indexes: external_exports.array(external_exports.string()).describe("Vector Store Indexes") +}); +var StructuredOutputFormatSchema = external_exports.enum([ + "json_object", + "json_schema", + "regex", + "grammar", + "xml" +]).describe("Output format for structured agent responses"); +var TransformPipelineStepSchema = external_exports.enum([ + "trim", + "parse_json", + "validate", + "coerce_types" +]).describe("Post-processing step for structured output"); +var StructuredOutputConfigSchema = external_exports.object({ + /** Output format type */ + format: StructuredOutputFormatSchema.describe("Expected output format"), + /** JSON Schema definition for output validation */ + schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON Schema definition for output"), + /** Whether to enforce exact schema compliance */ + strict: external_exports.boolean().default(false).describe("Enforce exact schema compliance"), + /** Retry on validation failure */ + retryOnValidationFailure: external_exports.boolean().default(true).describe("Retry generation when output fails validation"), + /** Maximum retry attempts */ + maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retries on validation failure"), + /** Fallback format if primary format fails */ + fallbackFormat: StructuredOutputFormatSchema.optional().describe("Fallback format if primary format fails"), + /** Post-processing pipeline steps */ + transformPipeline: external_exports.array(TransformPipelineStepSchema).optional().describe("Post-processing steps applied to output") +}).describe("Structured output configuration for agent responses"); +var AgentSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Agent unique identifier"), + label: external_exports.string().describe("Agent display name"), + avatar: external_exports.string().optional(), + role: external_exports.string().describe('The persona/role (e.g. "Senior Support Engineer")'), + /** Cognition */ + instructions: external_exports.string().describe("System Prompt / Prime Directives"), + model: AIModelConfigSchema.optional(), + lifecycle: StateMachineSchema4.optional().describe("State machine defining the agent conversation follow and constraints"), + /** Capabilities — Skill-based (primary) */ + skills: external_exports.array(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/)).optional().describe("Skill names to attach (Agent\u2192Skill\u2192Tool architecture)"), + /** Capabilities — Direct tool references (fallback / legacy) */ + tools: external_exports.array(AIToolSchema).optional().describe("Direct tool references (legacy fallback)"), + /** Knowledge */ + knowledge: AIKnowledgeSchema.optional().describe("RAG access"), + /** Interface */ + active: external_exports.boolean().default(true), + access: external_exports.array(external_exports.string()).optional().describe("Who can chat with this agent"), + /** Permission profiles/roles required to use this agent */ + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions or roles"), + /** Multi-tenancy & Visibility */ + tenantId: external_exports.string().optional().describe("Tenant/Organization ID"), + visibility: external_exports.enum(["global", "organization", "private"]).default("organization"), + /** Autonomous Reasoning */ + planning: external_exports.object({ + /** Planning strategy for autonomous reasoning loops */ + strategy: external_exports.enum(["react", "plan_and_execute", "reflexion", "tree_of_thought"]).default("react").describe("Autonomous reasoning strategy"), + /** Maximum reasoning iterations before stopping */ + maxIterations: external_exports.number().int().min(1).max(100).default(10).describe("Maximum planning loop iterations"), + /** Whether the agent can revise its own plan mid-execution */ + allowReplan: external_exports.boolean().default(true).describe("Allow dynamic re-planning based on intermediate results") + }).optional().describe("Autonomous reasoning and planning configuration"), + /** Memory Management */ + memory: external_exports.object({ + /** Short-term (working) memory configuration */ + shortTerm: external_exports.object({ + /** Maximum number of recent messages to retain */ + maxMessages: external_exports.number().int().min(1).default(50).describe("Max recent messages in working memory"), + /** Maximum token budget for short-term context */ + maxTokens: external_exports.number().int().min(100).optional().describe("Max tokens for short-term context window") + }).optional().describe("Short-term / working memory"), + /** Long-term (persistent) memory configuration */ + longTerm: external_exports.object({ + /** Whether long-term memory is enabled */ + enabled: external_exports.boolean().default(false).describe("Enable long-term memory persistence"), + /** Storage backend for long-term memory */ + store: external_exports.enum(["vector", "database", "redis"]).default("vector").describe("Long-term memory storage backend"), + /** Maximum number of persisted memory entries */ + maxEntries: external_exports.number().int().min(1).optional().describe("Max entries in long-term memory") + }).optional().describe("Long-term / persistent memory"), + /** Reflection interval — how often the agent reflects on past actions */ + reflectionInterval: external_exports.number().int().min(1).optional().describe("Reflect every N interactions to improve behavior") + }).optional().describe("Agent memory management"), + /** Guardrails */ + guardrails: external_exports.object({ + /** Maximum tokens the agent may consume per invocation */ + maxTokensPerInvocation: external_exports.number().int().min(1).optional().describe("Token budget per single invocation"), + /** Maximum wall-clock time per invocation in seconds */ + maxExecutionTimeSec: external_exports.number().int().min(1).optional().describe("Max execution time in seconds"), + /** Topics or actions the agent must avoid */ + blockedTopics: external_exports.array(external_exports.string()).optional().describe("Forbidden topics or action names") + }).optional().describe("Safety guardrails for the agent"), + /** Structured Output */ + structuredOutput: StructuredOutputConfigSchema.optional().describe("Structured output format and validation configuration") +}); +function defineAgent(config4) { + return AgentSchema.parse(config4); +} +var ToolCategorySchema = external_exports.enum([ + "data", + // CRUD / query operations + "action", + // Side-effect actions (send email, create record) + "flow", + // Trigger a visual flow + "integration", + // External API / webhook calls + "vector_search", + // RAG / vector search + "analytics", + // Aggregation & reporting + "utility" + // Formatters, parsers, helpers +]).describe("Tool operational category"); +var ToolSchema = external_exports.object({ + /** Machine name (snake_case, globally unique) */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Tool unique identifier (snake_case)"), + /** Human-readable display name */ + label: external_exports.string().describe("Tool display name"), + /** Detailed description for LLM consumption (the model reads this to decide when to call the tool) */ + description: external_exports.string().describe("Tool description for LLM function calling"), + /** Operational category */ + category: ToolCategorySchema.optional().describe("Tool category for grouping and filtering"), + /** + * JSON Schema describing the tool input parameters. + * Must be a valid JSON Schema object. The AI model generates + * arguments conforming to this schema. + */ + parameters: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema for tool parameters"), + /** + * Optional JSON Schema for the tool output. + * Used for structured output validation and downstream tool chaining. + */ + outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON Schema for tool output"), + /** + * Associated object name (when the tool operates on a specific data object). + * @example 'support_case' + */ + objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object name (snake_case)"), + /** Whether the tool requires human confirmation before execution */ + requiresConfirmation: external_exports.boolean().default(false).describe("Require user confirmation before execution"), + /** Permission profiles/roles required to use this tool */ + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions or roles"), + /** Whether the tool is enabled */ + active: external_exports.boolean().default(true).describe("Whether the tool is enabled"), + /** Whether this is a platform built-in tool (vs. user-defined) */ + builtIn: external_exports.boolean().default(false).describe("Platform built-in tool flag") +}); +function defineTool(config4) { + return ToolSchema.parse(config4); +} +var SkillTriggerConditionSchema = external_exports.object({ + /** Condition field (e.g. 'objectName', 'userRole', 'channel') */ + field: external_exports.string().describe("Context field to evaluate"), + /** Comparison operator */ + operator: external_exports.enum(["eq", "neq", "in", "not_in", "contains"]).describe("Comparison operator"), + /** Expected value(s) */ + value: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Expected value or values") +}); +var SkillSchema = external_exports.object({ + /** Machine name (snake_case, globally unique) */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Skill unique identifier (snake_case)"), + /** Human-readable display name */ + label: external_exports.string().describe("Skill display name"), + /** Detailed description of the skill's purpose */ + description: external_exports.string().optional().describe("Skill description"), + /** + * Instructions injected into the system prompt when this skill is active. + * Guides the LLM on how and when to use the skill's tools. + */ + instructions: external_exports.string().optional().describe("LLM instructions when skill is active"), + /** + * References to tool names that belong to this skill. + * Tools must be registered as first-class metadata (type: 'tool'). + */ + tools: external_exports.array(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/)).describe("Tool names belonging to this skill"), + /** + * Natural language phrases that trigger skill activation. + * Used for intent matching and skill routing. + */ + triggerPhrases: external_exports.array(external_exports.string()).optional().describe("Phrases that activate this skill"), + /** + * Programmatic conditions for skill activation. + * Evaluated against the runtime context (object name, user role, etc.). + */ + triggerConditions: external_exports.array(SkillTriggerConditionSchema).optional().describe("Programmatic activation conditions"), + /** Permission profiles/roles required to use this skill */ + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions or roles"), + /** Whether the skill is enabled */ + active: external_exports.boolean().default(true).describe("Whether the skill is enabled") +}); +function defineSkill(config4) { + return SkillSchema.parse(config4); +} +var NavigationActionTypeSchema = external_exports.enum([ + "navigate_to_object_list", + // Navigate to object list view + "navigate_to_object_form", + // Navigate to object form (new/edit) + "navigate_to_record_detail", + // Navigate to specific record detail page + "navigate_to_dashboard", + // Navigate to dashboard + "navigate_to_report", + // Navigate to report view + "navigate_to_app", + // Switch to different app + "navigate_back", + // Go back to previous view + "navigate_home", + // Go to home page + "open_tab", + // Open new tab + "close_tab" + // Close current tab +]); +var ViewActionTypeSchema = external_exports.enum([ + "change_view_mode", + // Switch between list/kanban/calendar/gantt + "apply_filter", + // Apply filter to current view + "clear_filter", + // Clear filters + "apply_sort", + // Apply sorting + "change_grouping", + // Change grouping (for kanban/pivot) + "show_columns", + // Show/hide columns + "expand_record", + // Expand record in list + "collapse_record", + // Collapse record in list + "refresh_view", + // Refresh current view + "export_data" + // Export view data +]); +var FormActionTypeSchema = external_exports.enum([ + "create_record", + // Create new record (submit form) + "update_record", + // Update existing record + "delete_record", + // Delete record + "fill_field", + // Fill a specific form field + "clear_field", + // Clear a form field + "submit_form", + // Submit the form + "cancel_form", + // Cancel form editing + "validate_form", + // Validate form data + "save_draft" + // Save as draft +]); +var DataActionTypeSchema = external_exports.enum([ + "select_record", + // Select record(s) in list + "deselect_record", + // Deselect record(s) + "select_all", + // Select all records + "deselect_all", + // Deselect all records + "bulk_update", + // Bulk update selected records + "bulk_delete", + // Bulk delete selected records + "bulk_export" + // Bulk export selected records +]); +var WorkflowActionTypeSchema = external_exports.enum([ + "trigger_flow", + // Trigger a flow/workflow + "trigger_approval", + // Start approval process + "trigger_webhook", + // Trigger webhook + "run_report", + // Run a report + "send_email", + // Send email + "send_notification", + // Send notification + "schedule_task" + // Schedule a task +]); +var ComponentActionTypeSchema = external_exports.enum([ + "open_modal", + // Open modal dialog + "close_modal", + // Close modal dialog + "open_sidebar", + // Open sidebar panel + "close_sidebar", + // Close sidebar panel + "show_notification", + // Show toast/notification + "hide_notification", + // Hide notification + "open_dropdown", + // Open dropdown menu + "close_dropdown", + // Close dropdown menu + "toggle_section" + // Toggle collapsible section +]); +var UIActionTypeSchema = external_exports.union([ + NavigationActionTypeSchema, + ViewActionTypeSchema, + FormActionTypeSchema, + DataActionTypeSchema, + WorkflowActionTypeSchema, + ComponentActionTypeSchema +]); +var NavigationActionParamsSchema = external_exports.object({ + object: external_exports.string().optional().describe("Object name (for object-specific navigation)"), + recordId: external_exports.string().optional().describe("Record ID (for detail page)"), + viewType: external_exports.enum(["list", "form", "detail", "kanban", "calendar", "gantt"]).optional(), + dashboardId: external_exports.string().optional().describe("Dashboard ID"), + reportId: external_exports.string().optional().describe("Report ID"), + appName: external_exports.string().optional().describe("App name"), + mode: external_exports.enum(["new", "edit", "view"]).optional().describe("Form mode"), + openInNewTab: external_exports.boolean().optional().describe("Open in new tab") +}); +var ViewActionParamsSchema = external_exports.object({ + viewMode: external_exports.enum(["list", "kanban", "calendar", "gantt", "pivot"]).optional(), + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter conditions"), + sort: external_exports.array(external_exports.object({ + field: external_exports.string(), + order: external_exports.enum(["asc", "desc"]) + })).optional(), + groupBy: external_exports.string().optional().describe("Field to group by"), + columns: external_exports.array(external_exports.string()).optional().describe("Columns to show/hide"), + recordId: external_exports.string().optional().describe("Record to expand/collapse"), + exportFormat: external_exports.enum(["csv", "xlsx", "pdf", "json"]).optional() +}); +var FormActionParamsSchema = external_exports.object({ + object: external_exports.string().optional().describe("Object name"), + recordId: external_exports.string().optional().describe("Record ID (for edit/delete)"), + fieldValues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Field name-value pairs"), + fieldName: external_exports.string().optional().describe("Specific field to fill/clear"), + fieldValue: external_exports.unknown().optional().describe("Value to set"), + validateOnly: external_exports.boolean().optional().describe("Validate without saving") +}); +var DataActionParamsSchema = external_exports.object({ + recordIds: external_exports.array(external_exports.string()).optional().describe("Record IDs to select/operate on"), + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter for bulk operations"), + updateData: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Data for bulk update"), + exportFormat: external_exports.enum(["csv", "xlsx", "pdf", "json"]).optional() +}); +var WorkflowActionParamsSchema = external_exports.object({ + flowName: external_exports.string().optional().describe("Flow/workflow name"), + approvalProcessName: external_exports.string().optional().describe("Approval process name"), + webhookUrl: external_exports.string().optional().describe("Webhook URL"), + reportName: external_exports.string().optional().describe("Report name"), + emailTemplate: external_exports.string().optional().describe("Email template"), + recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients"), + subject: external_exports.string().optional().describe("Email subject"), + message: external_exports.string().optional().describe("Notification/email message"), + taskData: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Task creation data"), + scheduleTime: external_exports.string().optional().describe("Schedule time (ISO 8601)"), + contextData: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context data") +}); +var ComponentActionParamsSchema = external_exports.object({ + componentId: external_exports.string().optional().describe("Component ID"), + modalConfig: external_exports.object({ + title: external_exports.string().optional(), + content: external_exports.unknown().optional(), + size: external_exports.enum(["small", "medium", "large", "fullscreen"]).optional() + }).optional(), + notificationConfig: external_exports.object({ + type: external_exports.enum(["info", "success", "warning", "error"]).optional(), + message: external_exports.string(), + duration: external_exports.number().optional().describe("Duration in ms") + }).optional(), + sidebarConfig: external_exports.object({ + position: external_exports.enum(["left", "right"]).optional(), + width: external_exports.string().optional(), + content: external_exports.unknown().optional() + }).optional() +}); +var AgentActionSchema = external_exports.object({ + /** + * Action identifier (generated) + */ + id: external_exports.string().optional().describe("Unique action ID"), + /** + * Action type + */ + type: UIActionTypeSchema.describe("Type of UI action to perform"), + /** + * Action parameters (discriminated union based on type) + */ + params: external_exports.union([ + NavigationActionParamsSchema, + ViewActionParamsSchema, + FormActionParamsSchema, + DataActionParamsSchema, + WorkflowActionParamsSchema, + ComponentActionParamsSchema + ]).describe("Action-specific parameters"), + /** + * Confirmation requirement + */ + requireConfirmation: external_exports.boolean().default(false).describe("Require user confirmation before executing"), + /** + * Confirmation message + */ + confirmationMessage: external_exports.string().optional().describe("Message to show in confirmation dialog"), + /** + * Success message + */ + successMessage: external_exports.string().optional().describe("Message to show on success"), + /** + * Error handling + */ + onError: external_exports.enum(["retry", "skip", "abort"]).default("abort").describe("Error handling strategy"), + /** + * Execution metadata + */ + metadata: external_exports.object({ + intent: external_exports.string().optional().describe("Original user intent/query"), + confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), + agentName: external_exports.string().optional().describe("Agent that generated this action"), + timestamp: external_exports.string().datetime().optional().describe("Generation timestamp (ISO 8601)") + }).optional() +}); +var NavigationAgentActionSchema = AgentActionSchema.extend({ + type: NavigationActionTypeSchema, + params: NavigationActionParamsSchema +}); +var ViewAgentActionSchema = AgentActionSchema.extend({ + type: ViewActionTypeSchema, + params: ViewActionParamsSchema +}); +var FormAgentActionSchema = AgentActionSchema.extend({ + type: FormActionTypeSchema, + params: FormActionParamsSchema +}); +var DataAgentActionSchema = AgentActionSchema.extend({ + type: DataActionTypeSchema, + params: DataActionParamsSchema +}); +var WorkflowAgentActionSchema = AgentActionSchema.extend({ + type: WorkflowActionTypeSchema, + params: WorkflowActionParamsSchema +}); +var ComponentAgentActionSchema = AgentActionSchema.extend({ + type: ComponentActionTypeSchema, + params: ComponentActionParamsSchema +}); +var TypedAgentActionSchema = external_exports.union([ + NavigationAgentActionSchema, + ViewAgentActionSchema, + FormAgentActionSchema, + DataAgentActionSchema, + WorkflowAgentActionSchema, + ComponentAgentActionSchema +]); +var AgentActionSequenceSchema = external_exports.object({ + /** + * Sequence identifier + */ + id: external_exports.string().optional().describe("Unique sequence ID"), + /** + * Actions to execute + */ + actions: external_exports.array(AgentActionSchema).describe("Ordered list of actions"), + /** + * Execution mode + */ + mode: external_exports.enum(["sequential", "parallel"]).default("sequential").describe("Execution mode"), + /** + * Stop on first error + */ + stopOnError: external_exports.boolean().default(true).describe("Stop sequence on first error"), + /** + * Transaction mode (all-or-nothing) + */ + atomic: external_exports.boolean().default(false).describe("Transaction mode (all-or-nothing)"), + startTime: external_exports.string().datetime().optional().describe("Execution start time (ISO 8601)"), + endTime: external_exports.string().datetime().optional().describe("Execution end time (ISO 8601)"), + /** + * Metadata + */ + metadata: external_exports.object({ + intent: external_exports.string().optional().describe("Original user intent"), + confidence: external_exports.number().min(0).max(1).optional().describe("Overall confidence score"), + agentName: external_exports.string().optional().describe("Agent that generated this sequence") + }).optional() +}); +var AgentActionResultSchema = external_exports.object({ + /** + * Action ID + */ + actionId: external_exports.string().describe("ID of the executed action"), + /** + * Execution status + */ + status: external_exports.enum(["success", "error", "cancelled", "pending"]).describe("Execution status"), + /** + * Result data + */ + data: external_exports.unknown().optional().describe("Action result data"), + /** + * Error information + */ + error: external_exports.object({ + code: external_exports.string(), + message: external_exports.string(), + details: external_exports.unknown().optional() + }).optional().describe('Error details if status is "error"'), + /** + * Execution metadata + */ + metadata: external_exports.object({ + startTime: external_exports.string().optional().describe("Execution start time (ISO 8601)"), + endTime: external_exports.string().optional().describe("Execution end time (ISO 8601)"), + duration: external_exports.number().optional().describe("Execution duration in ms") + }).optional() +}); +var AgentActionSequenceResultSchema = external_exports.object({ + /** + * Sequence ID + */ + sequenceId: external_exports.string().describe("ID of the executed sequence"), + /** + * Overall status + */ + status: external_exports.enum(["success", "partial_success", "error", "cancelled"]).describe("Overall execution status"), + /** + * Individual action results + */ + results: external_exports.array(AgentActionResultSchema).describe("Results for each action"), + /** + * Summary + */ + summary: external_exports.object({ + total: external_exports.number().describe("Total number of actions"), + successful: external_exports.number().describe("Number of successful actions"), + failed: external_exports.number().describe("Number of failed actions"), + cancelled: external_exports.number().describe("Number of cancelled actions") + }), + /** + * Execution metadata + */ + metadata: external_exports.object({ + startTime: external_exports.string().optional(), + endTime: external_exports.string().optional(), + totalDuration: external_exports.number().optional().describe("Total execution time in ms") + }).optional() +}); +var IntentActionMappingSchema = external_exports.object({ + /** + * Intent pattern (regex or exact match) + */ + intent: external_exports.string().describe('Intent pattern (e.g., "open_new_record_form")'), + /** + * Intent examples (for training) + */ + examples: external_exports.array(external_exports.string()).optional().describe("Example user queries"), + /** + * Action template + */ + actionTemplate: AgentActionSchema.describe("Action to execute"), + /** + * Parameter extraction rules + */ + paramExtraction: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["entity", "slot", "context"]), + required: external_exports.boolean().default(false), + default: external_exports.unknown().optional() + })).optional().describe("Rules for extracting parameters from user input"), + /** + * Confidence threshold + */ + minConfidence: external_exports.number().min(0).max(1).default(0.7).describe("Minimum confidence to execute") +}); +var CodeGenerationTargetSchema = external_exports.enum([ + "frontend", + // Frontend UI components + "backend", + // Backend services + "api", + // API endpoints + "database", + // Database schemas + "tests", + // Test suites + "documentation", + // Documentation + "infrastructure" + // Infrastructure as code +]).describe("Code generation target"); +var CodeGenerationConfigSchema = external_exports.object({ + /** + * Enable code generation + */ + enabled: external_exports.boolean().optional().default(true).describe("Enable code generation"), + /** + * Generation targets + */ + targets: external_exports.array(CodeGenerationTargetSchema).describe("Code generation targets"), + /** + * Template repository + */ + templateRepo: external_exports.string().optional().describe("Template repository for scaffolding"), + /** + * Code style guide + */ + styleGuide: external_exports.string().optional().describe("Code style guide to follow"), + /** + * Include tests + */ + includeTests: external_exports.boolean().optional().default(true).describe("Generate tests with code"), + /** + * Include documentation + */ + includeDocumentation: external_exports.boolean().optional().default(true).describe("Generate documentation"), + /** + * Validation mode + */ + validationMode: external_exports.enum(["strict", "moderate", "permissive"]).optional().default("strict").describe("Code validation strictness") +}); +var TestingConfigSchema = external_exports.object({ + /** + * Enable automated testing + */ + enabled: external_exports.boolean().optional().default(true).describe("Enable automated testing"), + /** + * Test types to run + */ + testTypes: external_exports.array(external_exports.enum([ + "unit", + "integration", + "e2e", + "performance", + "security", + "accessibility" + ])).optional().default(["unit", "integration"]).describe("Types of tests to run"), + /** + * Minimum coverage threshold + */ + coverageThreshold: external_exports.number().min(0).max(100).optional().default(80).describe("Minimum test coverage percentage"), + /** + * Test framework + */ + framework: external_exports.string().optional().describe("Testing framework (e.g., vitest, jest, playwright)"), + /** + * Run tests before commit + */ + preCommitTests: external_exports.boolean().optional().default(true).describe("Run tests before committing"), + /** + * Auto-fix failing tests + */ + autoFix: external_exports.boolean().optional().default(false).describe("Attempt to auto-fix failing tests") +}); +var PipelineStageSchema = external_exports.object({ + /** + * Stage name + */ + name: external_exports.string().describe("Pipeline stage name"), + /** + * Stage type + */ + type: external_exports.enum([ + "build", + "test", + "lint", + "security_scan", + "deploy", + "smoke_test", + "rollback" + ]).describe("Stage type"), + /** + * Stage order + */ + order: external_exports.number().int().min(0).describe("Execution order"), + /** + * Run in parallel + */ + parallel: external_exports.boolean().optional().default(false).describe("Can run in parallel with other stages"), + /** + * Commands to execute + */ + commands: external_exports.array(external_exports.string()).describe("Commands to execute"), + /** + * Environment variables + */ + env: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Stage-specific environment variables"), + /** + * Timeout in seconds + */ + timeout: external_exports.number().int().min(60).optional().default(600).describe("Stage timeout in seconds"), + /** + * Retry on failure + */ + retryOnFailure: external_exports.boolean().optional().default(false).describe("Retry stage on failure"), + /** + * Max retry attempts + */ + maxRetries: external_exports.number().int().min(0).max(5).optional().default(0).describe("Maximum retry attempts") +}); +var CICDPipelineConfigSchema = external_exports.object({ + /** + * Pipeline name + */ + name: external_exports.string().describe("Pipeline name"), + /** + * Pipeline trigger + */ + trigger: external_exports.enum([ + "push", + "pull_request", + "release", + "schedule", + "manual" + ]).describe("Pipeline trigger"), + /** + * Branch filters + */ + branches: external_exports.array(external_exports.string()).optional().describe("Branches to run pipeline on"), + /** + * Pipeline stages + */ + stages: external_exports.array(PipelineStageSchema).describe("Pipeline stages"), + /** + * Enable notifications + */ + notifications: external_exports.object({ + onSuccess: external_exports.boolean().optional().default(false), + onFailure: external_exports.boolean().optional().default(true), + channels: external_exports.array(external_exports.string()).optional().describe("Notification channels (e.g., slack, email)") + }).optional().describe("Pipeline notifications") +}); +var VersionManagementSchema = external_exports.object({ + /** + * Versioning scheme + */ + scheme: external_exports.enum(["semver", "calver", "custom"]).optional().default("semver").describe("Versioning scheme"), + /** + * Auto-increment strategy + */ + autoIncrement: external_exports.enum(["major", "minor", "patch", "none"]).optional().default("patch").describe("Auto-increment strategy"), + /** + * Version prefix + */ + prefix: external_exports.string().optional().default("v").describe("Version tag prefix"), + /** + * Create changelog + */ + generateChangelog: external_exports.boolean().optional().default(true).describe("Generate changelog automatically"), + /** + * Changelog format + */ + changelogFormat: external_exports.enum(["conventional", "keepachangelog", "custom"]).optional().default("conventional").describe("Changelog format"), + /** + * Tag releases + */ + tagReleases: external_exports.boolean().optional().default(true).describe("Create Git tags for releases") +}); +var DeploymentStrategySchema = external_exports.object({ + /** + * Strategy type + */ + type: external_exports.enum([ + "rolling", + "blue_green", + "canary", + "recreate" + ]).optional().default("rolling").describe("Deployment strategy"), + /** + * Canary percentage (for canary deployments) + */ + canaryPercentage: external_exports.number().min(0).max(100).optional().default(10).describe("Canary deployment percentage"), + /** + * Health check URL + */ + healthCheckUrl: external_exports.string().optional().describe("Health check endpoint"), + /** + * Health check timeout + */ + healthCheckTimeout: external_exports.number().int().min(10).optional().default(60).describe("Health check timeout in seconds"), + /** + * Rollback on failure + */ + autoRollback: external_exports.boolean().optional().default(true).describe("Automatically rollback on failure"), + /** + * Smoke tests + */ + smokeTests: external_exports.array(external_exports.string()).optional().describe("Smoke test commands to run post-deployment") +}); +var MonitoringConfigSchema = external_exports.object({ + /** + * Enable monitoring + */ + enabled: external_exports.boolean().optional().default(true).describe("Enable monitoring"), + /** + * Metrics to track + */ + metrics: external_exports.array(external_exports.enum([ + "performance", + "errors", + "usage", + "availability", + "latency" + ])).optional().default(["performance", "errors", "availability"]).describe("Metrics to monitor"), + /** + * Alert thresholds + */ + alerts: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Alert name"), + metric: external_exports.string().describe("Metric to monitor"), + threshold: external_exports.number().describe("Alert threshold"), + severity: external_exports.enum(["info", "warning", "critical"]).describe("Alert severity") + })).optional().describe("Alert configurations"), + /** + * Monitoring integrations + */ + integrations: external_exports.array(external_exports.string()).optional().describe("Monitoring service integrations") +}); +var DevelopmentConfigSchema = external_exports.object({ + /** + * ObjectStack specification source + */ + specificationSource: external_exports.string().describe("Path to ObjectStack specification"), + /** + * Code generation configuration + */ + codeGeneration: CodeGenerationConfigSchema.describe("Code generation settings"), + /** + * Testing configuration + */ + testing: TestingConfigSchema.optional().describe("Testing configuration"), + /** + * Linting configuration + */ + linting: external_exports.object({ + enabled: external_exports.boolean().optional().default(true), + autoFix: external_exports.boolean().optional().default(true), + rules: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional().describe("Code linting configuration"), + /** + * Formatting configuration + */ + formatting: external_exports.object({ + enabled: external_exports.boolean().optional().default(true), + autoFormat: external_exports.boolean().optional().default(true), + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional().describe("Code formatting configuration") +}); +var GitHubIntegrationSchema = external_exports.object({ + /** + * GitHub connector reference + */ + connector: external_exports.string().describe("GitHub connector name"), + /** + * Repository configuration + */ + repository: external_exports.object({ + owner: external_exports.string().describe("Repository owner"), + name: external_exports.string().describe("Repository name") + }).describe("Repository configuration"), + /** + * Default branch for features + */ + featureBranch: external_exports.string().optional().default("develop").describe("Default feature branch"), + /** + * Pull request configuration + */ + pullRequest: external_exports.object({ + autoCreate: external_exports.boolean().optional().default(true).describe("Automatically create PRs"), + autoMerge: external_exports.boolean().optional().default(false).describe("Automatically merge PRs when checks pass"), + requireReviews: external_exports.boolean().optional().default(true).describe("Require reviews before merge"), + deleteBranchOnMerge: external_exports.boolean().optional().default(true).describe("Delete feature branch after merge") + }).optional().describe("Pull request settings") +}); +var VercelIntegrationSchema = external_exports.object({ + /** + * Vercel connector reference + */ + connector: external_exports.string().describe("Vercel connector name"), + /** + * Project name + */ + project: external_exports.string().describe("Vercel project name"), + /** + * Environment mapping + */ + environments: external_exports.object({ + production: external_exports.string().optional().default("main").describe("Production branch"), + preview: external_exports.array(external_exports.string()).optional().default(["develop", "feature/*"]).describe("Preview branches") + }).optional().describe("Environment mapping"), + /** + * Deployment configuration + */ + deployment: external_exports.object({ + autoDeployProduction: external_exports.boolean().optional().default(false).describe("Auto-deploy to production"), + autoDeployPreview: external_exports.boolean().optional().default(true).describe("Auto-deploy preview environments"), + requireApproval: external_exports.boolean().optional().default(true).describe("Require approval for production deployments") + }).optional().describe("Deployment settings") +}); +var IntegrationConfigSchema = external_exports.object({ + /** + * GitHub integration + */ + github: GitHubIntegrationSchema.describe("GitHub integration configuration"), + /** + * Vercel integration + */ + vercel: VercelIntegrationSchema.describe("Vercel integration configuration"), + /** + * Additional integrations + */ + additional: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional integration configurations") +}); +var DevOpsAgentSchema = AgentSchema.extend({ + /** + * Development configuration + */ + developmentConfig: DevelopmentConfigSchema.describe("Development configuration"), + /** + * CI/CD pipelines + */ + pipelines: external_exports.array(CICDPipelineConfigSchema).optional().describe("CI/CD pipelines"), + /** + * Version management + */ + versionManagement: VersionManagementSchema.optional().describe("Version management configuration"), + /** + * Deployment strategy + */ + deploymentStrategy: DeploymentStrategySchema.optional().describe("Deployment strategy"), + /** + * Monitoring configuration + */ + monitoring: MonitoringConfigSchema.optional().describe("Monitoring configuration"), + /** + * Integration configuration + */ + integrations: IntegrationConfigSchema.describe("Integration configurations"), + /** + * Self-iteration configuration + */ + selfIteration: external_exports.object({ + enabled: external_exports.boolean().optional().default(true).describe("Enable self-iteration"), + iterationFrequency: external_exports.string().optional().describe("Iteration frequency (cron expression)"), + optimizationGoals: external_exports.array(external_exports.enum([ + "performance", + "security", + "code_quality", + "test_coverage", + "documentation" + ])).optional().describe("Optimization goals"), + learningMode: external_exports.enum(["conservative", "balanced", "aggressive"]).optional().default("balanced").describe("Learning mode") + }).optional().describe("Self-iteration configuration") +}); +var DevOpsToolSchema = AIToolSchema.extend({ + type: external_exports.enum([ + "action", + "flow", + "query", + "vector_search", + // DevOps-specific tools + "git_operation", + "code_generation", + "test_execution", + "deployment", + "monitoring" + ]) +}); +var fullStackDevOpsAgentExample = { + name: "devops_automation_agent", + label: "DevOps Automation Agent", + visibility: "organization", + avatar: "/avatars/devops-bot.png", + role: "Senior Full-Stack DevOps Engineer", + instructions: `You are an autonomous DevOps agent specialized in enterprise management software development. + +Your responsibilities: +1. Generate code based on ObjectStack specifications +2. Write comprehensive tests for all generated code +3. Ensure code quality through linting and formatting +4. Manage Git workflow (commits, branches, PRs) +5. Deploy applications to Vercel +6. Monitor deployments and handle rollbacks +7. Continuously optimize and iterate on the codebase + +Guidelines: +- Follow ObjectStack naming conventions (camelCase for props, snake_case for names) +- Write clean, maintainable, well-documented code +- Ensure 80%+ test coverage +- Use conventional commit messages +- Create detailed PR descriptions +- Deploy only after all checks pass +- Monitor production deployments closely +- Learn from failures and optimize continuously + +Always prioritize code quality, security, and maintainability.`, + model: { + provider: "openai", + model: "gpt-4-turbo-preview", + temperature: 0.3, + maxTokens: 8192 + }, + tools: [ + { + type: "action", + name: "generate_from_spec", + description: "Generate code from ObjectStack specification" + }, + { + type: "action", + name: "run_tests", + description: "Execute test suites" + }, + { + type: "action", + name: "commit_and_push", + description: "Commit changes and push to GitHub" + }, + { + type: "action", + name: "create_pull_request", + description: "Create pull request on GitHub" + }, + { + type: "action", + name: "deploy_to_vercel", + description: "Deploy application to Vercel" + }, + { + type: "action", + name: "check_deployment_health", + description: "Check deployment health status" + }, + { + type: "action", + name: "rollback_deployment", + description: "Rollback to previous deployment" + } + ], + knowledge: { + topics: [ + "objectstack_protocol", + "typescript_best_practices", + "testing_strategies", + "ci_cd_patterns", + "deployment_strategies" + ], + indexes: ["devops_knowledge_base"] + }, + developmentConfig: { + specificationSource: "packages/spec", + codeGeneration: { + enabled: true, + targets: ["frontend", "backend", "api", "tests", "documentation"], + styleGuide: "objectstack", + includeTests: true, + includeDocumentation: true, + validationMode: "strict" + }, + testing: { + enabled: true, + testTypes: ["unit", "integration", "e2e"], + coverageThreshold: 80, + framework: "vitest", + preCommitTests: true, + autoFix: false + }, + linting: { + enabled: true, + autoFix: true + }, + formatting: { + enabled: true, + autoFormat: true + } + }, + pipelines: [ + { + name: "CI Pipeline", + trigger: "pull_request", + branches: ["main", "develop"], + stages: [ + { + name: "Install Dependencies", + type: "build", + order: 1, + commands: ["pnpm install"], + timeout: 300, + parallel: false, + retryOnFailure: false, + maxRetries: 0 + }, + { + name: "Lint", + type: "lint", + order: 2, + parallel: true, + commands: ["pnpm run lint"], + timeout: 180, + retryOnFailure: false, + maxRetries: 0 + }, + { + name: "Type Check", + type: "lint", + order: 2, + parallel: true, + commands: ["pnpm run type-check"], + timeout: 180, + retryOnFailure: false, + maxRetries: 0 + }, + { + name: "Test", + type: "test", + order: 3, + commands: ["pnpm run test:ci"], + timeout: 600, + parallel: false, + retryOnFailure: false, + maxRetries: 0 + }, + { + name: "Build", + type: "build", + order: 4, + commands: ["pnpm run build"], + timeout: 600, + parallel: false, + retryOnFailure: false, + maxRetries: 0 + }, + { + name: "Security Scan", + type: "security_scan", + order: 5, + commands: ["pnpm audit", "pnpm run security-scan"], + timeout: 300, + parallel: false, + retryOnFailure: false, + maxRetries: 0 + } + ] + }, + { + name: "CD Pipeline", + trigger: "push", + branches: ["main"], + stages: [ + { + name: "Deploy to Production", + type: "deploy", + order: 1, + commands: ["vercel deploy --prod"], + timeout: 600, + parallel: false, + retryOnFailure: false, + maxRetries: 0 + }, + { + name: "Smoke Tests", + type: "smoke_test", + order: 2, + commands: ["pnpm run test:smoke"], + timeout: 300, + parallel: false, + retryOnFailure: true, + maxRetries: 2 + } + ], + notifications: { + onSuccess: true, + onFailure: true, + channels: ["slack", "email"] + } + } + ], + versionManagement: { + scheme: "semver", + autoIncrement: "patch", + prefix: "v", + generateChangelog: true, + changelogFormat: "conventional", + tagReleases: true + }, + deploymentStrategy: { + type: "rolling", + healthCheckUrl: "/api/health", + healthCheckTimeout: 60, + autoRollback: true, + smokeTests: ["pnpm run test:smoke"], + canaryPercentage: 10 + }, + monitoring: { + enabled: true, + metrics: ["performance", "errors", "availability"], + alerts: [ + { + name: "High Error Rate", + metric: "error_rate", + threshold: 0.05, + severity: "critical" + }, + { + name: "Slow Response Time", + metric: "response_time", + threshold: 1e3, + severity: "warning" + } + ], + integrations: ["vercel", "datadog"] + }, + integrations: { + github: { + connector: "github_production", + repository: { + owner: "objectstack-ai", + name: "app" + }, + featureBranch: "develop", + pullRequest: { + autoCreate: true, + autoMerge: false, + requireReviews: true, + deleteBranchOnMerge: true + } + }, + vercel: { + connector: "vercel_production", + project: "objectstack-app", + environments: { + production: "main", + preview: ["develop", "feature/*"] + }, + deployment: { + autoDeployProduction: false, + autoDeployPreview: true, + requireApproval: true + } + } + }, + selfIteration: { + enabled: true, + iterationFrequency: "0 0 * * 0", + // Weekly on Sunday + optimizationGoals: ["code_quality", "test_coverage", "performance"], + learningMode: "balanced" + }, + active: true +}; +var CodeGenerationRequestSchema = external_exports.object({ + /** + * Natural language description of desired functionality + */ + description: external_exports.string().describe("What the plugin should do"), + /** + * Plugin type to generate + */ + pluginType: external_exports.enum([ + "driver", + // Data driver plugin + "app", + // Application plugin + "widget", + // UI widget + "integration", + // External integration + "automation", + // Automation/workflow + "analytics", + // Analytics plugin + "ai-agent", + // AI agent plugin + "custom" + // Custom plugin type + ]), + /** + * Output format for generated code + */ + outputFormat: external_exports.enum([ + "source-code", + // Generate TypeScript/JavaScript source code + "low-code-schema", + // Generate ObjectStack JSON/YAML schema definitions + "dsl" + // Generate domain-specific language definitions + ]).default("source-code").describe("Format of the generated output"), + /** + * Target programming language (for source-code format) + */ + language: external_exports.enum(["typescript", "javascript", "python"]).default("typescript"), + /** + * Framework preferences + */ + framework: external_exports.object({ + runtime: external_exports.enum(["node", "browser", "edge", "universal"]).optional(), + uiFramework: external_exports.enum(["react", "vue", "svelte", "none"]).optional(), + testing: external_exports.enum(["vitest", "jest", "mocha", "none"]).optional() + }).optional(), + /** + * Required capabilities + */ + capabilities: external_exports.array(external_exports.string()).optional().describe("Protocol IDs to implement"), + /** + * Dependencies + */ + dependencies: external_exports.array(external_exports.string()).optional().describe("Required plugin IDs"), + /** + * Example usage (helps AI understand intent) + */ + examples: external_exports.array(external_exports.object({ + input: external_exports.string(), + expectedOutput: external_exports.string(), + description: external_exports.string().optional() + })).optional(), + /** + * Code style preferences (for source-code format) + */ + style: external_exports.object({ + indentation: external_exports.enum(["tab", "2spaces", "4spaces"]).default("2spaces"), + quotes: external_exports.enum(["single", "double"]).default("single"), + semicolons: external_exports.boolean().default(true), + trailingComma: external_exports.boolean().default(true) + }).optional(), + /** + * Low-code schema preferences (for low-code-schema format) + */ + schemaOptions: external_exports.object({ + /** + * Schema format + */ + format: external_exports.enum(["json", "yaml", "typescript"]).default("typescript").describe("Output schema format"), + /** + * Include example data + */ + includeExamples: external_exports.boolean().default(true), + /** + * Validation strictness + */ + strictValidation: external_exports.boolean().default(true), + /** + * Generate UI definitions + */ + generateUI: external_exports.boolean().default(true).describe("Generate view, dashboard, and page definitions"), + /** + * Generate data models + */ + generateDataModels: external_exports.boolean().default(true).describe("Generate object and field definitions") + }).optional(), + /** + * Additional context + */ + context: external_exports.object({ + /** + * Existing code to extend + */ + existingCode: external_exports.string().optional(), + /** + * Related documentation URLs + */ + documentationUrls: external_exports.array(external_exports.string()).optional(), + /** + * Similar plugins for reference + */ + referencePlugins: external_exports.array(external_exports.string()).optional() + }).optional(), + /** + * Generation options + */ + options: external_exports.object({ + /** + * Include tests + */ + generateTests: external_exports.boolean().default(true), + /** + * Include documentation + */ + generateDocs: external_exports.boolean().default(true), + /** + * Include examples + */ + generateExamples: external_exports.boolean().default(true), + /** + * Code coverage target + */ + targetCoverage: external_exports.number().min(0).max(100).default(80), + /** + * Optimization level + */ + optimizationLevel: external_exports.enum(["none", "basic", "aggressive"]).default("basic") + }).optional() +}); +var GeneratedCodeSchema = external_exports.object({ + /** + * Output format used + */ + outputFormat: external_exports.enum(["source-code", "low-code-schema", "dsl"]), + /** + * Main plugin code (for source-code format) + */ + code: external_exports.string().optional(), + /** + * Language used (for source-code format) + */ + language: external_exports.string().optional(), + /** + * Low-code schema definitions (for low-code-schema format) + */ + schemas: external_exports.array(external_exports.object({ + type: external_exports.enum(["object", "view", "dashboard", "app", "workflow", "api", "page"]), + path: external_exports.string().describe("File path for the schema"), + content: external_exports.string().describe("Schema content (JSON/YAML/TypeScript)"), + description: external_exports.string().optional() + })).optional().describe("Generated low-code schema files"), + /** + * File structure + */ + files: external_exports.array(external_exports.object({ + path: external_exports.string(), + content: external_exports.string(), + description: external_exports.string().optional() + })), + /** + * Generated tests + */ + tests: external_exports.array(external_exports.object({ + path: external_exports.string(), + content: external_exports.string(), + coverage: external_exports.number().min(0).max(100).optional() + })).optional(), + /** + * Documentation + */ + documentation: external_exports.object({ + readme: external_exports.string().optional(), + api: external_exports.string().optional(), + usage: external_exports.string().optional() + }).optional(), + /** + * Package metadata + */ + package: external_exports.object({ + name: external_exports.string(), + version: external_exports.string(), + dependencies: external_exports.record(external_exports.string(), external_exports.string()).optional(), + devDependencies: external_exports.record(external_exports.string(), external_exports.string()).optional() + }).optional(), + /** + * Quality metrics + */ + quality: external_exports.object({ + complexity: external_exports.number().optional().describe("Cyclomatic complexity"), + maintainability: external_exports.number().min(0).max(100).optional(), + testCoverage: external_exports.number().min(0).max(100).optional(), + lintScore: external_exports.number().min(0).max(100).optional() + }).optional(), + /** + * AI confidence score + */ + confidence: external_exports.number().min(0).max(100).describe("AI confidence in generated code"), + /** + * Suggestions for improvement + */ + suggestions: external_exports.array(external_exports.string()).optional(), + /** + * Warnings or caveats + */ + warnings: external_exports.array(external_exports.string()).optional() +}); +var PluginScaffoldingTemplateSchema = external_exports.object({ + /** + * Template identifier + */ + id: external_exports.string(), + /** + * Template name + */ + name: external_exports.string(), + /** + * Description + */ + description: external_exports.string(), + /** + * Plugin type + */ + pluginType: external_exports.string(), + /** + * File structure + */ + structure: external_exports.array(external_exports.object({ + type: external_exports.enum(["file", "directory"]), + path: external_exports.string(), + template: external_exports.string().optional().describe("Template content with variables"), + optional: external_exports.boolean().default(false) + })), + /** + * Variables to be filled + */ + variables: external_exports.array(external_exports.object({ + name: external_exports.string(), + description: external_exports.string(), + type: external_exports.enum(["string", "number", "boolean", "array", "object"]), + required: external_exports.boolean().default(true), + default: external_exports.unknown().optional(), + validation: external_exports.string().optional().describe("Validation regex or rule") + })), + /** + * Post-scaffold scripts + */ + scripts: external_exports.array(external_exports.object({ + name: external_exports.string(), + command: external_exports.string(), + description: external_exports.string().optional(), + optional: external_exports.boolean().default(false) + })).optional() +}); +var AICodeReviewResultSchema = external_exports.object({ + /** + * Overall assessment + */ + assessment: external_exports.enum(["excellent", "good", "acceptable", "needs-improvement", "poor"]), + /** + * Overall score (0-100) + */ + score: external_exports.number().min(0).max(100), + /** + * Issues found + */ + issues: external_exports.array(external_exports.object({ + severity: external_exports.enum(["critical", "error", "warning", "info", "style"]), + category: external_exports.enum([ + "bug", + "security", + "performance", + "maintainability", + "style", + "documentation", + "testing", + "type-safety", + "best-practice" + ]), + file: external_exports.string(), + line: external_exports.number().int().optional(), + column: external_exports.number().int().optional(), + message: external_exports.string(), + suggestion: external_exports.string().optional(), + autoFixable: external_exports.boolean().default(false), + autoFix: external_exports.string().optional().describe("Automated fix code") + })), + /** + * Positive highlights + */ + highlights: external_exports.array(external_exports.object({ + category: external_exports.string(), + description: external_exports.string(), + file: external_exports.string().optional() + })).optional(), + /** + * Quality metrics + */ + metrics: external_exports.object({ + complexity: external_exports.number().optional(), + maintainability: external_exports.number().min(0).max(100).optional(), + testCoverage: external_exports.number().min(0).max(100).optional(), + duplicateCode: external_exports.number().min(0).max(100).optional(), + technicalDebt: external_exports.string().optional().describe("Estimated technical debt") + }).optional(), + /** + * Recommendations + */ + recommendations: external_exports.array(external_exports.object({ + priority: external_exports.enum(["high", "medium", "low"]), + title: external_exports.string(), + description: external_exports.string(), + effort: external_exports.enum(["trivial", "small", "medium", "large"]).optional() + })), + /** + * Security analysis + */ + security: external_exports.object({ + vulnerabilities: external_exports.array(external_exports.object({ + severity: external_exports.enum(["critical", "high", "medium", "low"]), + type: external_exports.string(), + description: external_exports.string(), + remediation: external_exports.string().optional() + })).optional(), + score: external_exports.number().min(0).max(100).optional() + }).optional() +}); +var PluginCompositionRequestSchema = external_exports.object({ + /** + * Desired outcome + */ + goal: external_exports.string().describe("What should the composed plugins achieve"), + /** + * Available plugins + */ + availablePlugins: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + version: external_exports.string(), + capabilities: external_exports.array(external_exports.string()).optional(), + description: external_exports.string().optional() + })), + /** + * Constraints + */ + constraints: external_exports.object({ + /** + * Maximum plugins to use + */ + maxPlugins: external_exports.number().int().min(1).optional(), + /** + * Required plugins + */ + requiredPlugins: external_exports.array(external_exports.string()).optional(), + /** + * Excluded plugins + */ + excludedPlugins: external_exports.array(external_exports.string()).optional(), + /** + * Performance requirements + */ + performance: external_exports.object({ + maxLatency: external_exports.number().optional().describe("Maximum latency in ms"), + maxMemory: external_exports.number().optional().describe("Maximum memory in bytes") + }).optional() + }).optional(), + /** + * Optimization criteria + */ + optimize: external_exports.enum([ + "performance", + "reliability", + "simplicity", + "cost", + "security" + ]).optional() +}); +var PluginCompositionResultSchema = external_exports.object({ + /** + * Selected plugins + */ + plugins: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + version: external_exports.string(), + role: external_exports.string().describe("Role in the composition"), + configuration: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + })), + /** + * Integration code + */ + integration: external_exports.object({ + /** + * Glue code to connect plugins + */ + code: external_exports.string(), + /** + * Configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Initialization order + */ + initOrder: external_exports.array(external_exports.string()) + }), + /** + * Data flow diagram + */ + dataFlow: external_exports.array(external_exports.object({ + from: external_exports.string(), + to: external_exports.string(), + data: external_exports.string().describe("Data type or description") + })), + /** + * Expected performance + */ + performance: external_exports.object({ + estimatedLatency: external_exports.number().optional().describe("Estimated latency in ms"), + estimatedMemory: external_exports.number().optional().describe("Estimated memory in bytes") + }).optional(), + /** + * Confidence score + */ + confidence: external_exports.number().min(0).max(100), + /** + * Alternative compositions + */ + alternatives: external_exports.array(external_exports.object({ + description: external_exports.string(), + plugins: external_exports.array(external_exports.string()), + tradeoffs: external_exports.string() + })).optional(), + /** + * Warnings and considerations + */ + warnings: external_exports.array(external_exports.string()).optional() +}); +var PluginRecommendationRequestSchema = external_exports.object({ + /** + * User context + */ + context: external_exports.object({ + /** + * Current plugins installed + */ + installedPlugins: external_exports.array(external_exports.string()).optional(), + /** + * User's industry + */ + industry: external_exports.string().optional(), + /** + * Use cases + */ + useCases: external_exports.array(external_exports.string()).optional(), + /** + * Team size + */ + teamSize: external_exports.number().int().optional(), + /** + * Budget constraints + */ + budget: external_exports.enum(["free", "low", "medium", "high", "unlimited"]).optional() + }), + /** + * Recommendation criteria + */ + criteria: external_exports.object({ + /** + * Prioritize by + */ + prioritize: external_exports.enum([ + "popularity", + "rating", + "compatibility", + "features", + "cost", + "support" + ]).optional(), + /** + * Only certified plugins + */ + certifiedOnly: external_exports.boolean().default(false), + /** + * Minimum rating + */ + minRating: external_exports.number().min(0).max(5).optional(), + /** + * Maximum results + */ + maxResults: external_exports.number().int().min(1).max(50).default(10) + }).optional() +}); +var PluginRecommendationSchema = external_exports.object({ + /** + * Recommended plugins + */ + recommendations: external_exports.array(external_exports.object({ + pluginId: external_exports.string(), + name: external_exports.string(), + description: external_exports.string(), + score: external_exports.number().min(0).max(100).describe("Relevance score"), + reasons: external_exports.array(external_exports.string()).describe("Why this plugin is recommended"), + benefits: external_exports.array(external_exports.string()), + considerations: external_exports.array(external_exports.string()).optional(), + alternatives: external_exports.array(external_exports.string()).optional(), + estimatedValue: external_exports.string().optional().describe("Expected value/ROI") + })), + /** + * Recommended combinations + */ + combinations: external_exports.array(external_exports.object({ + plugins: external_exports.array(external_exports.string()), + description: external_exports.string(), + synergies: external_exports.array(external_exports.string()).describe("How these plugins work well together"), + totalScore: external_exports.number().min(0).max(100) + })).optional(), + /** + * Learning path + */ + learningPath: external_exports.array(external_exports.object({ + step: external_exports.number().int(), + plugin: external_exports.string(), + reason: external_exports.string(), + resources: external_exports.array(external_exports.string()).optional() + })).optional() +}); +var AnomalyDetectionConfigSchema = external_exports.object({ + /** + * Enable anomaly detection + */ + enabled: external_exports.boolean().default(true), + /** + * Metrics to monitor + */ + metrics: external_exports.array(external_exports.enum([ + "cpu-usage", + "memory-usage", + "response-time", + "error-rate", + "throughput", + "latency", + "connection-count", + "queue-depth" + ])), + /** + * Detection algorithm + */ + algorithm: external_exports.enum([ + "statistical", + // Statistical thresholds + "machine-learning", + // ML-based detection + "heuristic", + // Rule-based heuristics + "hybrid" + // Combination of methods + ]).default("hybrid"), + /** + * Sensitivity level + */ + sensitivity: external_exports.enum(["low", "medium", "high"]).default("medium").describe("How aggressively to detect anomalies"), + /** + * Time window for analysis (seconds) + */ + timeWindow: external_exports.number().int().min(60).default(300).describe("Historical data window for anomaly detection"), + /** + * Confidence threshold (0-100) + */ + confidenceThreshold: external_exports.number().min(0).max(100).default(80).describe("Minimum confidence to flag as anomaly"), + /** + * Alert on detection + */ + alertOnDetection: external_exports.boolean().default(true) +}); +var SelfHealingActionSchema = external_exports.object({ + /** + * Action identifier + */ + id: external_exports.string(), + /** + * Action type + */ + type: external_exports.enum([ + "restart", + // Restart the plugin + "scale", + // Scale resources + "rollback", + // Rollback to previous version + "clear-cache", + // Clear caches + "adjust-config", + // Adjust configuration + "execute-script", + // Run custom script + "notify" + // Notify administrators + ]), + /** + * Trigger condition + */ + trigger: external_exports.object({ + /** + * Health status that triggers this action + */ + healthStatus: external_exports.array(PluginHealthStatusSchema2).optional(), + /** + * Anomaly types that trigger this action + */ + anomalyTypes: external_exports.array(external_exports.string()).optional(), + /** + * Error patterns that trigger this action + */ + errorPatterns: external_exports.array(external_exports.string()).optional(), + /** + * Custom condition expression + */ + customCondition: external_exports.string().optional().describe('Custom trigger condition (e.g., "errorRate > 0.1")') + }), + /** + * Action parameters + */ + parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** + * Maximum number of attempts + */ + maxAttempts: external_exports.number().int().min(1).default(3), + /** + * Cooldown period between attempts (seconds) + */ + cooldown: external_exports.number().int().min(0).default(60), + /** + * Timeout for action execution (seconds) + */ + timeout: external_exports.number().int().min(1).default(300), + /** + * Require manual approval + */ + requireApproval: external_exports.boolean().default(false), + /** + * Priority + */ + priority: external_exports.number().int().min(1).default(5).describe("Action priority (lower number = higher priority)") +}); +var SelfHealingConfigSchema = external_exports.object({ + /** + * Enable self-healing + */ + enabled: external_exports.boolean().default(true), + /** + * Healing strategy + */ + strategy: external_exports.enum([ + "conservative", + // Only safe, proven actions + "moderate", + // Balanced approach + "aggressive" + // Try more recovery options + ]).default("moderate"), + /** + * Recovery actions + */ + actions: external_exports.array(SelfHealingActionSchema), + /** + * Anomaly detection + */ + anomalyDetection: AnomalyDetectionConfigSchema.optional(), + /** + * Maximum concurrent healing operations + */ + maxConcurrentHealing: external_exports.number().int().min(1).default(1).describe("Maximum number of simultaneous healing attempts"), + /** + * Learning mode + */ + learning: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Learn from successful/failed healing attempts"), + feedbackLoop: external_exports.boolean().default(true).describe("Adjust strategy based on outcomes") + }).optional() +}); +var AutoScalingPolicySchema = external_exports.object({ + /** + * Enable auto-scaling + */ + enabled: external_exports.boolean().default(false), + /** + * Scaling metric + */ + metric: external_exports.enum([ + "cpu-usage", + "memory-usage", + "request-rate", + "response-time", + "queue-depth", + "custom" + ]), + /** + * Custom metric query (when metric is "custom") + */ + customMetric: external_exports.string().optional(), + /** + * Target value for the metric + */ + targetValue: external_exports.number().describe("Desired metric value (e.g., 70 for 70% CPU)"), + /** + * Scaling bounds + */ + bounds: external_exports.object({ + /** + * Minimum instances + */ + minInstances: external_exports.number().int().min(1).default(1), + /** + * Maximum instances + */ + maxInstances: external_exports.number().int().min(1).default(10), + /** + * Minimum resources per instance + */ + minResources: external_exports.object({ + cpu: external_exports.string().optional().describe('CPU limit (e.g., "0.5", "1")'), + memory: external_exports.string().optional().describe('Memory limit (e.g., "512Mi", "1Gi")') + }).optional(), + /** + * Maximum resources per instance + */ + maxResources: external_exports.object({ + cpu: external_exports.string().optional(), + memory: external_exports.string().optional() + }).optional() + }), + /** + * Scale up behavior + */ + scaleUp: external_exports.object({ + /** + * Threshold to trigger scale up + */ + threshold: external_exports.number().describe("Metric value that triggers scale up"), + /** + * Stabilization window (seconds) + */ + stabilizationWindow: external_exports.number().int().min(0).default(60).describe("How long metric must exceed threshold"), + /** + * Cooldown period (seconds) + */ + cooldown: external_exports.number().int().min(0).default(300).describe("Minimum time between scale-up operations"), + /** + * Step size + */ + stepSize: external_exports.number().int().min(1).default(1).describe("Number of instances to add") + }), + /** + * Scale down behavior + */ + scaleDown: external_exports.object({ + /** + * Threshold to trigger scale down + */ + threshold: external_exports.number().describe("Metric value that triggers scale down"), + /** + * Stabilization window (seconds) + */ + stabilizationWindow: external_exports.number().int().min(0).default(300).describe("How long metric must be below threshold"), + /** + * Cooldown period (seconds) + */ + cooldown: external_exports.number().int().min(0).default(600).describe("Minimum time between scale-down operations"), + /** + * Step size + */ + stepSize: external_exports.number().int().min(1).default(1).describe("Number of instances to remove") + }), + /** + * Predictive scaling + */ + predictive: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Use ML to predict future load"), + lookAhead: external_exports.number().int().min(60).default(300).describe("How far ahead to predict (seconds)"), + confidence: external_exports.number().min(0).max(100).default(80).describe("Minimum confidence for prediction-based scaling") + }).optional() +}); +var RootCauseAnalysisRequestSchema = external_exports.object({ + /** + * Incident identifier + */ + incidentId: external_exports.string(), + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Symptoms observed + */ + symptoms: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Symptom type"), + description: external_exports.string(), + severity: external_exports.enum(["low", "medium", "high", "critical"]), + timestamp: external_exports.string().datetime() + })), + /** + * Time range for analysis + */ + timeRange: external_exports.object({ + start: external_exports.string().datetime(), + end: external_exports.string().datetime() + }), + /** + * Include log analysis + */ + analyzeLogs: external_exports.boolean().default(true), + /** + * Include metric analysis + */ + analyzeMetrics: external_exports.boolean().default(true), + /** + * Include dependency analysis + */ + analyzeDependencies: external_exports.boolean().default(true), + /** + * Context information + */ + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var RootCauseAnalysisResultSchema = external_exports.object({ + /** + * Analysis identifier + */ + analysisId: external_exports.string(), + /** + * Incident identifier + */ + incidentId: external_exports.string(), + /** + * Identified root causes + */ + rootCauses: external_exports.array(external_exports.object({ + /** + * Cause identifier + */ + id: external_exports.string(), + /** + * Description + */ + description: external_exports.string(), + /** + * Confidence score (0-100) + */ + confidence: external_exports.number().min(0).max(100), + /** + * Category + */ + category: external_exports.enum([ + "code-defect", + "configuration", + "resource-exhaustion", + "dependency-failure", + "network-issue", + "data-corruption", + "security-breach", + "other" + ]), + /** + * Evidence + */ + evidence: external_exports.array(external_exports.object({ + type: external_exports.enum(["log", "metric", "trace", "event"]), + content: external_exports.string(), + timestamp: external_exports.string().datetime().optional() + })), + /** + * Impact assessment + */ + impact: external_exports.enum(["low", "medium", "high", "critical"]), + /** + * Recommended actions + */ + recommendations: external_exports.array(external_exports.string()) + })), + /** + * Contributing factors + */ + contributingFactors: external_exports.array(external_exports.object({ + description: external_exports.string(), + confidence: external_exports.number().min(0).max(100) + })).optional(), + /** + * Timeline of events + */ + timeline: external_exports.array(external_exports.object({ + timestamp: external_exports.string().datetime(), + event: external_exports.string(), + significance: external_exports.enum(["low", "medium", "high"]) + })).optional(), + /** + * Remediation plan + */ + remediation: external_exports.object({ + /** + * Immediate actions + */ + immediate: external_exports.array(external_exports.string()), + /** + * Short-term fixes + */ + shortTerm: external_exports.array(external_exports.string()), + /** + * Long-term improvements + */ + longTerm: external_exports.array(external_exports.string()) + }).optional(), + /** + * Overall confidence in analysis + */ + overallConfidence: external_exports.number().min(0).max(100), + /** + * Analysis timestamp + */ + timestamp: external_exports.string().datetime() +}); +var PerformanceOptimizationSchema = external_exports.object({ + /** + * Optimization identifier + */ + id: external_exports.string(), + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Optimization type + */ + type: external_exports.enum([ + "caching", + "query-optimization", + "resource-allocation", + "code-refactoring", + "architecture-change", + "configuration-tuning" + ]), + /** + * Description + */ + description: external_exports.string(), + /** + * Expected impact + */ + expectedImpact: external_exports.object({ + /** + * Performance improvement percentage + */ + performanceGain: external_exports.number().min(0).max(100).describe("Expected performance improvement (%)"), + /** + * Resource savings + */ + resourceSavings: external_exports.object({ + cpu: external_exports.number().optional().describe("CPU reduction (%)"), + memory: external_exports.number().optional().describe("Memory reduction (%)"), + network: external_exports.number().optional().describe("Network reduction (%)") + }).optional(), + /** + * Cost reduction + */ + costReduction: external_exports.number().optional().describe("Estimated cost reduction (%)") + }), + /** + * Implementation difficulty + */ + difficulty: external_exports.enum(["trivial", "easy", "moderate", "complex", "very-complex"]), + /** + * Implementation steps + */ + steps: external_exports.array(external_exports.string()), + /** + * Risks and considerations + */ + risks: external_exports.array(external_exports.string()).optional(), + /** + * Confidence score + */ + confidence: external_exports.number().min(0).max(100), + /** + * Priority + */ + priority: external_exports.enum(["low", "medium", "high", "critical"]) +}); +var AIOpsAgentConfigSchema = external_exports.object({ + /** + * Agent identifier + */ + agentId: external_exports.string(), + /** + * Plugin identifier + */ + pluginId: external_exports.string(), + /** + * Self-healing configuration + */ + selfHealing: SelfHealingConfigSchema.optional(), + /** + * Auto-scaling policies + */ + autoScaling: external_exports.array(AutoScalingPolicySchema).optional(), + /** + * Continuous monitoring + */ + monitoring: external_exports.object({ + enabled: external_exports.boolean().default(true), + interval: external_exports.number().int().min(1e3).default(6e4).describe("Monitoring interval in milliseconds"), + /** + * Metrics to collect + */ + metrics: external_exports.array(external_exports.string()).optional() + }).optional(), + /** + * Proactive optimization + */ + optimization: external_exports.object({ + enabled: external_exports.boolean().default(true), + /** + * Scan interval (seconds) + */ + scanInterval: external_exports.number().int().min(3600).default(86400).describe("How often to scan for optimization opportunities"), + /** + * Auto-apply optimizations + */ + autoApply: external_exports.boolean().default(false).describe("Automatically apply low-risk optimizations") + }).optional(), + /** + * Incident response + */ + incidentResponse: external_exports.object({ + enabled: external_exports.boolean().default(true), + /** + * Auto-trigger root cause analysis + */ + autoRCA: external_exports.boolean().default(true), + /** + * Notification channels + */ + notifications: external_exports.array(external_exports.object({ + channel: external_exports.enum(["email", "slack", "webhook", "sms"]), + config: external_exports.record(external_exports.string(), external_exports.unknown()) + })).optional() + }).optional() +}); +var ModelProviderSchema = external_exports.enum([ + "openai", + "azure_openai", + "anthropic", + "google", + "cohere", + "huggingface", + "local", + "custom" +]); +var ModelCapabilitySchema = external_exports.object({ + textGeneration: external_exports.boolean().optional().default(true).describe("Supports text generation"), + textEmbedding: external_exports.boolean().optional().default(false).describe("Supports text embedding"), + imageGeneration: external_exports.boolean().optional().default(false).describe("Supports image generation"), + imageUnderstanding: external_exports.boolean().optional().default(false).describe("Supports image understanding"), + functionCalling: external_exports.boolean().optional().default(false).describe("Supports function calling"), + codeGeneration: external_exports.boolean().optional().default(false).describe("Supports code generation"), + reasoning: external_exports.boolean().optional().default(false).describe("Supports advanced reasoning") +}); +var ModelLimitsSchema = external_exports.object({ + maxTokens: external_exports.number().int().positive().describe("Maximum tokens per request"), + contextWindow: external_exports.number().int().positive().describe("Context window size"), + maxOutputTokens: external_exports.number().int().positive().optional().describe("Maximum output tokens"), + rateLimit: external_exports.object({ + requestsPerMinute: external_exports.number().int().positive().optional(), + tokensPerMinute: external_exports.number().int().positive().optional() + }).optional() +}); +var ModelPricingSchema = external_exports.object({ + currency: external_exports.string().optional().default("USD"), + inputCostPer1kTokens: external_exports.number().optional().describe("Cost per 1K input tokens"), + outputCostPer1kTokens: external_exports.number().optional().describe("Cost per 1K output tokens"), + embeddingCostPer1kTokens: external_exports.number().optional().describe("Cost per 1K embedding tokens") +}); +var ModelConfigSchema = external_exports.object({ + /** Identity */ + id: external_exports.string().describe("Unique model identifier"), + name: external_exports.string().describe("Model display name"), + version: external_exports.string().describe('Model version (e.g., "gpt-4-turbo-2024-04-09")'), + provider: ModelProviderSchema, + /** Capabilities */ + capabilities: ModelCapabilitySchema, + limits: ModelLimitsSchema, + /** Pricing */ + pricing: ModelPricingSchema.optional(), + /** Configuration */ + endpoint: external_exports.string().url().optional().describe("Custom API endpoint"), + apiKey: external_exports.string().optional().describe("API key (Warning: Prefer secretRef)"), + secretRef: external_exports.string().optional().describe("Reference to stored secret (e.g. system:openai_api_key)"), + region: external_exports.string().optional().describe('Deployment region (e.g., "us-east-1")'), + /** Metadata */ + description: external_exports.string().optional(), + tags: external_exports.array(external_exports.string()).optional().describe("Tags for categorization"), + deprecated: external_exports.boolean().optional().default(false), + recommendedFor: external_exports.array(external_exports.string()).optional().describe("Use case recommendations") +}); +var PromptVariableSchema = external_exports.object({ + name: external_exports.string().describe('Variable name (e.g., "user_name", "context")'), + type: external_exports.enum(["string", "number", "boolean", "object", "array"]).default("string"), + required: external_exports.boolean().default(false), + defaultValue: external_exports.unknown().optional(), + description: external_exports.string().optional(), + validation: external_exports.object({ + minLength: external_exports.number().optional(), + maxLength: external_exports.number().optional(), + pattern: external_exports.string().optional(), + enum: external_exports.array(external_exports.unknown()).optional() + }).optional() +}); +var PromptTemplateSchema = external_exports.object({ + /** Identity */ + id: external_exports.string().describe("Unique template identifier"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Template name (snake_case)"), + label: external_exports.string().describe("Display name"), + /** Template Content */ + system: external_exports.string().optional().describe("System prompt"), + user: external_exports.string().describe("User prompt template with variables"), + assistant: external_exports.string().optional().describe("Assistant message prefix"), + /** Variables */ + variables: external_exports.array(PromptVariableSchema).optional().describe("Template variables"), + /** Model Configuration */ + modelId: external_exports.string().optional().describe("Recommended model ID"), + temperature: external_exports.number().min(0).max(2).optional(), + maxTokens: external_exports.number().optional(), + topP: external_exports.number().optional(), + frequencyPenalty: external_exports.number().optional(), + presencePenalty: external_exports.number().optional(), + stopSequences: external_exports.array(external_exports.string()).optional(), + /** Metadata */ + version: external_exports.string().optional().default("1.0.0"), + description: external_exports.string().optional(), + category: external_exports.string().optional().describe('Template category (e.g., "code_generation", "support")'), + tags: external_exports.array(external_exports.string()).optional(), + examples: external_exports.array(external_exports.object({ + input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Example variable values"), + output: external_exports.string().describe("Expected output") + })).optional() +}); +var ModelRegistryEntrySchema = external_exports.object({ + model: ModelConfigSchema, + status: external_exports.enum(["active", "deprecated", "experimental", "disabled"]).default("active"), + priority: external_exports.number().int().default(0).describe("Priority for model selection"), + fallbackModels: external_exports.array(external_exports.string()).optional().describe("Fallback model IDs"), + healthCheck: external_exports.object({ + enabled: external_exports.boolean().default(true), + intervalSeconds: external_exports.number().int().default(300), + lastChecked: external_exports.string().optional().describe("ISO timestamp"), + status: external_exports.enum(["healthy", "unhealthy", "unknown"]).default("unknown") + }).optional() +}); +var ModelRegistrySchema = external_exports.object({ + name: external_exports.string().describe("Registry name"), + models: external_exports.record(external_exports.string(), ModelRegistryEntrySchema).describe("Model entries by ID"), + promptTemplates: external_exports.record(external_exports.string(), PromptTemplateSchema).optional().describe("Prompt templates by name"), + defaultModel: external_exports.string().optional().describe("Default model ID"), + enableAutoFallback: external_exports.boolean().default(true).describe("Auto-fallback on errors") +}); +var ModelSelectionCriteriaSchema = external_exports.object({ + capabilities: external_exports.array(external_exports.string()).optional().describe("Required capabilities"), + maxCostPer1kTokens: external_exports.number().optional().describe("Maximum acceptable cost"), + minContextWindow: external_exports.number().optional().describe("Minimum context window size"), + provider: ModelProviderSchema.optional(), + tags: external_exports.array(external_exports.string()).optional(), + excludeDeprecated: external_exports.boolean().default(true) +}); +var MCPTransportTypeSchema = external_exports.enum([ + "stdio", + // Standard input/output (for local processes) + "http", + // HTTP REST API + "websocket", + // WebSocket bidirectional communication + "grpc" + // gRPC for high-performance communication +]); +var MCPTransportConfigSchema = external_exports.object({ + type: MCPTransportTypeSchema, + /** HTTP/WebSocket Configuration */ + url: external_exports.string().url().optional().describe("Server URL (for HTTP/WebSocket/gRPC)"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for requests"), + /** Authentication */ + auth: external_exports.object({ + type: external_exports.enum(["none", "bearer", "api_key", "oauth2", "custom"]).default("none"), + token: external_exports.string().optional().describe("Bearer token or API key"), + secretRef: external_exports.string().optional().describe("Reference to stored secret"), + headerName: external_exports.string().optional().describe("Custom auth header name") + }).optional(), + /** Connection Options */ + timeout: external_exports.number().int().positive().optional().default(3e4).describe("Request timeout in milliseconds"), + retryAttempts: external_exports.number().int().min(0).max(5).optional().default(3), + retryDelay: external_exports.number().int().positive().optional().default(1e3).describe("Delay between retries in milliseconds"), + /** STDIO Configuration */ + command: external_exports.string().optional().describe("Command to execute (for stdio transport)"), + args: external_exports.array(external_exports.string()).optional().describe("Command arguments"), + env: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Environment variables"), + workingDirectory: external_exports.string().optional().describe("Working directory for the process") +}); +var MCPResourceTypeSchema = external_exports.enum([ + "text", + // Plain text or markdown content + "json", + // Structured JSON data + "binary", + // Binary data (files, images, etc.) + "stream" + // Streaming data +]); +var MCPResourceSchema = external_exports.object({ + /** Identity */ + uri: external_exports.string().describe('Unique resource identifier (e.g., "objectstack://objects/account/ABC123")'), + name: external_exports.string().describe("Human-readable resource name"), + description: external_exports.string().optional().describe("Resource description for AI consumption"), + /** Resource Type */ + mimeType: external_exports.string().optional().describe('MIME type (e.g., "application/json", "text/plain")'), + resourceType: MCPResourceTypeSchema.default("json"), + /** Content */ + content: external_exports.unknown().optional().describe("Resource content (for static resources)"), + contentUrl: external_exports.string().url().optional().describe("URL to fetch content dynamically"), + /** Metadata */ + size: external_exports.number().int().nonnegative().optional().describe("Resource size in bytes"), + lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp (ISO 8601)"), + tags: external_exports.array(external_exports.string()).optional().describe("Tags for resource categorization"), + /** Access Control */ + permissions: external_exports.object({ + read: external_exports.boolean().default(true), + write: external_exports.boolean().default(false), + delete: external_exports.boolean().default(false) + }).optional(), + /** Caching */ + cacheable: external_exports.boolean().default(true).describe("Whether this resource can be cached"), + cacheMaxAge: external_exports.number().int().nonnegative().optional().describe("Cache max age in seconds") +}); +var MCPResourceTemplateSchema = external_exports.object({ + uriPattern: external_exports.string().describe('URI pattern with variables (e.g., "objectstack://objects/{objectName}/{recordId}")'), + name: external_exports.string().describe("Template name"), + description: external_exports.string().optional(), + /** Parameters */ + parameters: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Parameter name"), + type: external_exports.enum(["string", "number", "boolean"]).default("string"), + required: external_exports.boolean().default(true), + description: external_exports.string().optional(), + pattern: external_exports.string().optional().describe("Regex validation pattern"), + default: external_exports.unknown().optional() + })).describe("URI parameters"), + /** Generation Logic */ + handler: external_exports.string().optional().describe("Handler function name for dynamic generation"), + mimeType: external_exports.string().optional(), + resourceType: MCPResourceTypeSchema.default("json") +}); +var MCPToolParameterSchema = external_exports.object({ + name: external_exports.string().describe("Parameter name"), + type: external_exports.enum(["string", "number", "boolean", "object", "array"]), + description: external_exports.string().describe("Parameter description for AI consumption"), + required: external_exports.boolean().default(false), + default: external_exports.unknown().optional(), + /** Validation */ + enum: external_exports.array(external_exports.unknown()).optional().describe("Allowed values"), + pattern: external_exports.string().optional().describe("Regex validation pattern (for strings)"), + minimum: external_exports.number().optional().describe("Minimum value (for numbers)"), + maximum: external_exports.number().optional().describe("Maximum value (for numbers)"), + minLength: external_exports.number().int().nonnegative().optional().describe("Minimum length (for strings/arrays)"), + maxLength: external_exports.number().int().nonnegative().optional().describe("Maximum length (for strings/arrays)"), + /** Nested Schema */ + properties: external_exports.record(external_exports.string(), external_exports.lazy(() => MCPToolParameterSchema)).optional().describe("Properties for object types"), + items: external_exports.lazy(() => MCPToolParameterSchema).optional().describe("Item schema for array types") +}); +var MCPToolSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Tool function name (snake_case)"), + description: external_exports.string().describe("Tool description for AI consumption (be detailed and specific)"), + /** Parameters */ + parameters: external_exports.array(MCPToolParameterSchema).describe("Tool parameters"), + /** Return Type */ + returns: external_exports.object({ + type: external_exports.enum(["string", "number", "boolean", "object", "array", "void"]), + description: external_exports.string().optional(), + schema: MCPToolParameterSchema.optional().describe("Return value schema") + }).optional(), + /** Execution Configuration */ + handler: external_exports.string().describe("Handler function or endpoint reference"), + async: external_exports.boolean().default(true).describe("Whether the tool executes asynchronously"), + timeout: external_exports.number().int().positive().optional().describe("Execution timeout in milliseconds"), + /** Side Effects */ + sideEffects: external_exports.enum(["none", "read", "write", "delete"]).default("read").describe("Tool side effects"), + requiresConfirmation: external_exports.boolean().default(false).describe("Require user confirmation before execution"), + confirmationMessage: external_exports.string().optional(), + /** Examples */ + examples: external_exports.array(external_exports.object({ + description: external_exports.string(), + parameters: external_exports.record(external_exports.string(), external_exports.unknown()), + result: external_exports.unknown().optional() + })).optional().describe("Usage examples for AI learning"), + /** Metadata */ + category: external_exports.string().optional().describe('Tool category (e.g., "data", "workflow", "analytics")'), + tags: external_exports.array(external_exports.string()).optional(), + deprecated: external_exports.boolean().default(false), + version: external_exports.string().optional().default("1.0.0") +}); +var MCPPromptArgumentSchema = external_exports.object({ + name: external_exports.string().describe("Argument name"), + description: external_exports.string().optional(), + type: external_exports.enum(["string", "number", "boolean"]).default("string"), + required: external_exports.boolean().default(false), + default: external_exports.unknown().optional() +}); +var MCPPromptMessageSchema = external_exports.object({ + role: external_exports.enum(["system", "user", "assistant"]).describe("Message role"), + content: external_exports.string().describe("Message content (can include {{variable}} placeholders)") +}); +var MCPPromptSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Prompt template name (snake_case)"), + description: external_exports.string().optional().describe("Prompt description"), + /** Template */ + messages: external_exports.array(MCPPromptMessageSchema).describe("Prompt message sequence"), + /** Arguments */ + arguments: external_exports.array(MCPPromptArgumentSchema).optional().describe("Dynamic arguments for the prompt"), + /** Metadata */ + category: external_exports.string().optional(), + tags: external_exports.array(external_exports.string()).optional(), + version: external_exports.string().optional().default("1.0.0") +}); +var MCPStreamingConfigSchema = external_exports.object({ + /** Whether streaming is enabled */ + enabled: external_exports.boolean().describe("Enable streaming for MCP communication"), + /** Size of each streamed chunk in bytes */ + chunkSize: external_exports.number().int().positive().optional().describe("Size of each streamed chunk in bytes"), + /** Heartbeat interval to keep connection alive */ + heartbeatIntervalMs: external_exports.number().int().positive().optional().default(3e4).describe("Heartbeat interval in milliseconds"), + /** Backpressure handling strategy */ + backpressure: external_exports.enum(["drop", "buffer", "block"]).optional().describe("Backpressure handling strategy") +}).describe("Streaming configuration for MCP communication"); +var MCPToolApprovalSchema = external_exports.object({ + /** Whether tool execution requires approval */ + requireApproval: external_exports.boolean().default(false).describe("Require approval before tool execution"), + /** Strategy for handling approvals */ + approvalStrategy: external_exports.enum(["human_in_loop", "auto_approve", "policy_based"]).describe("Approval strategy for tool execution"), + /** Regex patterns matching tool names that require approval */ + dangerousToolPatterns: external_exports.array(external_exports.string()).optional().describe("Regex patterns for tools needing approval"), + /** Timeout in seconds for auto-approval */ + autoApproveTimeout: external_exports.number().int().positive().optional().describe("Auto-approve timeout in seconds") +}).describe("Tool approval configuration for MCP"); +var MCPSamplingConfigSchema = external_exports.object({ + /** Whether sampling is enabled */ + enabled: external_exports.boolean().describe("Enable LLM sampling"), + /** Maximum tokens to generate */ + maxTokens: external_exports.number().int().positive().describe("Maximum tokens to generate"), + /** Sampling temperature */ + temperature: external_exports.number().min(0).max(2).optional().describe("Sampling temperature"), + /** Stop sequences to end generation */ + stopSequences: external_exports.array(external_exports.string()).optional().describe("Stop sequences to end generation"), + /** Preferred model IDs in priority order */ + modelPreferences: external_exports.array(external_exports.string()).optional().describe("Preferred model IDs in priority order"), + /** System prompt for sampling context */ + systemPrompt: external_exports.string().optional().describe("System prompt for sampling context") +}).describe("Sampling configuration for MCP"); +var MCPRootEntrySchema = external_exports.object({ + /** Root URI */ + uri: external_exports.string().describe("Root URI (e.g., file:///path/to/project)"), + /** Human-readable name for the root */ + name: external_exports.string().optional().describe("Human-readable root name"), + /** Whether the root is read-only */ + readOnly: external_exports.boolean().optional().describe("Whether the root is read-only") +}).describe("A single root directory or resource"); +var MCPRootsConfigSchema = external_exports.object({ + /** Root directories/resources */ + roots: external_exports.array(MCPRootEntrySchema).describe("Root directories or resources available to the client"), + /** Watch roots for changes */ + watchForChanges: external_exports.boolean().default(false).describe("Watch root directories for filesystem changes"), + /** Notify server on root changes */ + notifyOnChange: external_exports.boolean().default(true).describe("Notify server when root contents change") +}).describe("Roots configuration for MCP client"); +var MCPCapabilitySchema = external_exports.object({ + resources: external_exports.boolean().default(false).describe("Supports resource listing and retrieval"), + resourceTemplates: external_exports.boolean().default(false).describe("Supports dynamic resource templates"), + tools: external_exports.boolean().default(false).describe("Supports tool/function calling"), + prompts: external_exports.boolean().default(false).describe("Supports prompt templates"), + sampling: external_exports.boolean().default(false).describe("Supports sampling from LLMs"), + logging: external_exports.boolean().default(false).describe("Supports logging and debugging") +}); +var MCPServerInfoSchema = external_exports.object({ + name: external_exports.string().describe("Server name"), + version: external_exports.string().describe("Server version (semver)"), + description: external_exports.string().optional(), + capabilities: MCPCapabilitySchema, + /** Protocol Version */ + protocolVersion: external_exports.string().default("2024-11-05").describe("MCP protocol version"), + /** Metadata */ + vendor: external_exports.string().optional().describe("Server vendor/provider"), + homepage: external_exports.string().url().optional().describe("Server homepage URL"), + documentation: external_exports.string().url().optional().describe("Documentation URL") +}); +var MCPServerConfigSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Server unique identifier (snake_case)"), + label: external_exports.string().describe("Display name"), + description: external_exports.string().optional(), + /** Server Info */ + serverInfo: MCPServerInfoSchema, + /** Transport */ + transport: MCPTransportConfigSchema, + /** Resources */ + resources: external_exports.array(MCPResourceSchema).optional().describe("Static resources"), + resourceTemplates: external_exports.array(MCPResourceTemplateSchema).optional().describe("Dynamic resource templates"), + /** Tools */ + tools: external_exports.array(MCPToolSchema).optional().describe("Available tools"), + /** Prompts */ + prompts: external_exports.array(MCPPromptSchema).optional().describe("Prompt templates"), + /** Lifecycle */ + autoStart: external_exports.boolean().default(false).describe("Auto-start server on system boot"), + restartOnFailure: external_exports.boolean().default(true).describe("Auto-restart on failure"), + healthCheck: external_exports.object({ + enabled: external_exports.boolean().default(true), + interval: external_exports.number().int().positive().default(6e4).describe("Health check interval in milliseconds"), + timeout: external_exports.number().int().positive().default(5e3).describe("Health check timeout in milliseconds"), + endpoint: external_exports.string().optional().describe("Health check endpoint (for HTTP servers)") + }).optional(), + /** Access Control */ + permissions: external_exports.object({ + allowedAgents: external_exports.array(external_exports.string()).optional().describe("Agent names allowed to use this server"), + allowedUsers: external_exports.array(external_exports.string()).optional().describe("User IDs allowed to use this server"), + requireAuth: external_exports.boolean().default(true) + }).optional(), + /** Rate Limiting */ + rateLimit: external_exports.object({ + enabled: external_exports.boolean().default(false), + requestsPerMinute: external_exports.number().int().positive().optional(), + requestsPerHour: external_exports.number().int().positive().optional(), + burstSize: external_exports.number().int().positive().optional() + }).optional(), + /** Metadata */ + tags: external_exports.array(external_exports.string()).optional(), + status: external_exports.enum(["active", "inactive", "maintenance", "deprecated"]).default("active"), + version: external_exports.string().optional().default("1.0.0"), + createdAt: external_exports.string().datetime().optional(), + updatedAt: external_exports.string().datetime().optional(), + /** Streaming */ + streaming: MCPStreamingConfigSchema.optional().describe("Streaming configuration"), + /** Tool Approval */ + toolApproval: MCPToolApprovalSchema.optional().describe("Tool approval configuration"), + /** Sampling */ + sampling: MCPSamplingConfigSchema.optional().describe("LLM sampling configuration") +}); +var MCPResourceRequestSchema = external_exports.object({ + uri: external_exports.string().describe("Resource URI to fetch"), + parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("URI template parameters") +}); +var MCPResourceResponseSchema = external_exports.object({ + resource: MCPResourceSchema, + content: external_exports.unknown().describe("Resource content") +}); +var MCPToolCallRequestSchema = external_exports.object({ + toolName: external_exports.string().describe("Tool to invoke"), + parameters: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Tool parameters"), + /** Execution Options */ + timeout: external_exports.number().int().positive().optional(), + confirmationProvided: external_exports.boolean().optional().describe("User confirmation for tools that require it"), + /** Context */ + context: external_exports.object({ + userId: external_exports.string().optional(), + sessionId: external_exports.string().optional(), + agentName: external_exports.string().optional(), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional() +}); +var MCPToolCallResponseSchema = external_exports.object({ + toolName: external_exports.string(), + status: external_exports.enum(["success", "error", "timeout", "cancelled"]), + /** Result */ + result: external_exports.unknown().optional().describe("Tool execution result"), + /** Error */ + error: external_exports.object({ + code: external_exports.string(), + message: external_exports.string(), + details: external_exports.unknown().optional() + }).optional(), + /** Metrics */ + executionTime: external_exports.number().nonnegative().optional().describe("Execution time in milliseconds"), + timestamp: external_exports.string().datetime().optional() +}); +var MCPPromptRequestSchema = external_exports.object({ + promptName: external_exports.string().describe("Prompt template to use"), + arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Prompt arguments") +}); +var MCPPromptResponseSchema = external_exports.object({ + promptName: external_exports.string(), + messages: external_exports.array(MCPPromptMessageSchema).describe("Rendered prompt messages") +}); +var MCPClientConfigSchema = external_exports.object({ + /** Server Connection */ + servers: external_exports.array(MCPServerConfigSchema).describe("MCP servers to connect to"), + /** Client Settings */ + defaultTimeout: external_exports.number().int().positive().default(3e4).describe("Default timeout for requests"), + enableCaching: external_exports.boolean().default(true).describe("Enable client-side caching"), + cacheMaxAge: external_exports.number().int().nonnegative().default(300).describe("Cache max age in seconds"), + /** Retry Logic */ + retryAttempts: external_exports.number().int().min(0).max(5).default(3), + retryDelay: external_exports.number().int().positive().default(1e3), + /** Logging */ + enableLogging: external_exports.boolean().default(true), + logLevel: external_exports.enum(["debug", "info", "warn", "error"]).default("info"), + /** Roots */ + roots: MCPRootsConfigSchema.optional().describe("Root directories/resources configuration") +}); +var TokenUsageSchema = external_exports.object({ + prompt: external_exports.number().int().nonnegative().describe("Input tokens"), + completion: external_exports.number().int().nonnegative().describe("Output tokens"), + total: external_exports.number().int().nonnegative().describe("Total tokens") +}); +var AIOperationCostSchema = external_exports.object({ + operationId: external_exports.string(), + operationType: external_exports.enum(["conversation", "orchestration", "prediction", "rag", "nlq"]), + agentName: external_exports.string().optional().describe("Agent that performed the operation"), + modelId: external_exports.string(), + tokens: TokenUsageSchema, + cost: external_exports.number().nonnegative().describe("Cost in USD"), + timestamp: external_exports.string().datetime(), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var CostMetricTypeSchema = external_exports.enum([ + "token", + // Cost per token + "request", + // Cost per API request + "character", + // Cost per character (e.g., TTS) + "second", + // Cost per second (e.g., speech) + "image", + // Cost per image + "embedding" + // Cost per embedding +]); +var BillingPeriodSchema = external_exports.enum([ + "hourly", + "daily", + "weekly", + "monthly", + "quarterly", + "yearly", + "custom" +]); +var CostEntrySchema = external_exports.object({ + /** Identity */ + id: external_exports.string().describe("Unique cost entry ID"), + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), + /** Request Details */ + modelId: external_exports.string().describe("AI model used"), + provider: external_exports.string().describe('AI provider (e.g., "openai", "anthropic")'), + operation: external_exports.string().describe('Operation type (e.g., "chat_completion", "embedding")'), + /** Usage Metrics - Standardized */ + tokens: TokenUsageSchema.optional().describe("Standardized token usage"), + requestCount: external_exports.number().int().positive().default(1), + /** Cost Calculation */ + promptCost: external_exports.number().nonnegative().optional().describe("Cost of prompt tokens"), + completionCost: external_exports.number().nonnegative().optional().describe("Cost of completion tokens"), + totalCost: external_exports.number().nonnegative().describe("Total cost in base currency"), + currency: external_exports.string().default("USD"), + /** Context */ + sessionId: external_exports.string().optional().describe("Conversation session ID"), + userId: external_exports.string().optional().describe("User who triggered the request"), + agentId: external_exports.string().optional().describe("AI agent ID"), + object: external_exports.string().optional().describe('Related object (e.g., "case", "project")'), + recordId: external_exports.string().optional().describe("Related record ID"), + /** Metadata */ + tags: external_exports.array(external_exports.string()).optional(), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var BudgetTypeSchema = external_exports.enum([ + "global", + // Organization-wide budget + "user", + // Per-user budget + "agent", + // Per-agent budget + "object", + // Per-object budget (e.g., per case) + "project", + // Per-project budget + "department" + // Per-department budget +]); +var BudgetLimitSchema = external_exports.object({ + /** Limit Configuration */ + type: BudgetTypeSchema, + scope: external_exports.string().optional().describe("Scope identifier (userId, agentId, etc.)"), + /** Limit Amount */ + maxCost: external_exports.number().nonnegative().describe("Maximum cost limit"), + currency: external_exports.string().default("USD"), + /** Period */ + period: BillingPeriodSchema, + customPeriodDays: external_exports.number().int().positive().optional().describe("Custom period in days"), + /** Soft Limits & Warnings */ + softLimit: external_exports.number().nonnegative().optional().describe("Soft limit for warnings"), + warnThresholds: external_exports.array(external_exports.number().min(0).max(1)).optional().describe("Warning thresholds (e.g., [0.5, 0.8, 0.95])"), + /** Enforcement */ + enforced: external_exports.boolean().default(true).describe("Block requests when exceeded"), + gracePeriodSeconds: external_exports.number().int().nonnegative().default(0).describe("Grace period after limit exceeded"), + /** Rollover */ + allowRollover: external_exports.boolean().default(false).describe("Allow unused budget to rollover"), + maxRolloverPercentage: external_exports.number().min(0).max(1).optional().describe("Max rollover as % of limit"), + /** Metadata */ + name: external_exports.string().optional().describe("Budget name"), + description: external_exports.string().optional(), + active: external_exports.boolean().default(true), + tags: external_exports.array(external_exports.string()).optional() +}); +var BudgetStatusSchema = external_exports.object({ + /** Budget Reference */ + budgetId: external_exports.string(), + type: BudgetTypeSchema, + scope: external_exports.string().optional(), + /** Current Period */ + periodStart: external_exports.string().datetime().describe("ISO 8601 timestamp"), + periodEnd: external_exports.string().datetime().describe("ISO 8601 timestamp"), + /** Usage */ + currentCost: external_exports.number().nonnegative().default(0), + maxCost: external_exports.number().nonnegative(), + currency: external_exports.string().default("USD"), + /** Status */ + percentageUsed: external_exports.number().nonnegative().describe("Usage as percentage (can exceed 1.0 if over budget)"), + remainingCost: external_exports.number().describe("Remaining budget (can be negative if exceeded)"), + isExceeded: external_exports.boolean().default(false), + isWarning: external_exports.boolean().default(false), + /** Projections */ + projectedCost: external_exports.number().nonnegative().optional().describe("Projected cost for period"), + projectedOverage: external_exports.number().nonnegative().optional().describe("Projected overage"), + /** Last Update */ + lastUpdated: external_exports.string().datetime().describe("ISO 8601 timestamp") +}); +var CostAlertTypeSchema = external_exports.enum([ + "threshold_warning", + // Warning threshold reached + "threshold_critical", + // Critical threshold reached + "limit_exceeded", + // Budget limit exceeded + "anomaly_detected", + // Unusual spending pattern + "projection_exceeded" + // Projected to exceed budget +]); +var CostAlertSchema = external_exports.object({ + /** Alert Details */ + id: external_exports.string(), + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), + type: CostAlertTypeSchema, + severity: external_exports.enum(["info", "warning", "critical"]), + /** Budget Context */ + budgetId: external_exports.string().optional(), + budgetType: BudgetTypeSchema.optional(), + scope: external_exports.string().optional(), + /** Alert Information */ + message: external_exports.string().describe("Alert message"), + currentCost: external_exports.number().nonnegative(), + maxCost: external_exports.number().nonnegative().optional(), + threshold: external_exports.number().min(0).max(1).optional(), + currency: external_exports.string().default("USD"), + /** Recommendations */ + recommendations: external_exports.array(external_exports.string()).optional(), + /** Status */ + acknowledged: external_exports.boolean().default(false), + acknowledgedBy: external_exports.string().optional(), + acknowledgedAt: external_exports.string().datetime().optional(), + resolved: external_exports.boolean().default(false), + /** Metadata */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var CostBreakdownDimensionSchema = external_exports.enum([ + "model", + "provider", + "user", + "agent", + "object", + "operation", + "date", + "hour", + "tag" +]); +var CostBreakdownEntrySchema = external_exports.object({ + dimension: CostBreakdownDimensionSchema, + value: external_exports.string().describe("Dimension value (e.g., model ID, user ID)"), + /** Metrics */ + totalCost: external_exports.number().nonnegative(), + requestCount: external_exports.number().int().nonnegative(), + totalTokens: external_exports.number().int().nonnegative().optional(), + /** Share */ + percentageOfTotal: external_exports.number().min(0).max(1), + /** Time Range */ + periodStart: external_exports.string().datetime().optional(), + periodEnd: external_exports.string().datetime().optional() +}); +var CostAnalyticsSchema = external_exports.object({ + /** Time Range */ + periodStart: external_exports.string().datetime().describe("ISO 8601 timestamp"), + periodEnd: external_exports.string().datetime().describe("ISO 8601 timestamp"), + /** Summary Metrics */ + totalCost: external_exports.number().nonnegative(), + totalRequests: external_exports.number().int().nonnegative(), + totalTokens: external_exports.number().int().nonnegative().optional(), + currency: external_exports.string().default("USD"), + /** Averages */ + averageCostPerRequest: external_exports.number().nonnegative(), + averageCostPerToken: external_exports.number().nonnegative().optional(), + averageRequestsPerDay: external_exports.number().nonnegative(), + /** Trends */ + costTrend: external_exports.enum(["increasing", "decreasing", "stable"]).optional(), + trendPercentage: external_exports.number().optional().describe("% change vs previous period"), + /** Breakdowns */ + byModel: external_exports.array(CostBreakdownEntrySchema).optional(), + byProvider: external_exports.array(CostBreakdownEntrySchema).optional(), + byUser: external_exports.array(CostBreakdownEntrySchema).optional(), + byAgent: external_exports.array(CostBreakdownEntrySchema).optional(), + byOperation: external_exports.array(CostBreakdownEntrySchema).optional(), + byDate: external_exports.array(CostBreakdownEntrySchema).optional(), + /** Top Consumers */ + topModels: external_exports.array(CostBreakdownEntrySchema).optional(), + topUsers: external_exports.array(CostBreakdownEntrySchema).optional(), + topAgents: external_exports.array(CostBreakdownEntrySchema).optional(), + /** Efficiency Metrics */ + tokensPerDollar: external_exports.number().nonnegative().optional(), + requestsPerDollar: external_exports.number().nonnegative().optional() +}); +var CostOptimizationRecommendationSchema = external_exports.object({ + /** Recommendation Details */ + id: external_exports.string(), + type: external_exports.enum([ + "switch_model", + "reduce_tokens", + "batch_requests", + "cache_results", + "adjust_parameters", + "limit_usage" + ]), + /** Impact */ + title: external_exports.string(), + description: external_exports.string(), + estimatedSavings: external_exports.number().nonnegative().optional(), + savingsPercentage: external_exports.number().min(0).max(1).optional(), + /** Implementation */ + priority: external_exports.enum(["low", "medium", "high"]), + effort: external_exports.enum(["low", "medium", "high"]), + actionable: external_exports.boolean().default(true), + actionSteps: external_exports.array(external_exports.string()).optional(), + /** Context */ + targetModel: external_exports.string().optional(), + alternativeModel: external_exports.string().optional(), + affectedUsers: external_exports.array(external_exports.string()).optional(), + /** Status */ + status: external_exports.enum(["pending", "accepted", "rejected", "implemented"]).default("pending"), + implementedAt: external_exports.string().datetime().optional() +}); +var CostReportSchema = external_exports.object({ + /** Report Metadata */ + id: external_exports.string(), + name: external_exports.string(), + generatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp"), + /** Time Range */ + periodStart: external_exports.string().datetime().describe("ISO 8601 timestamp"), + periodEnd: external_exports.string().datetime().describe("ISO 8601 timestamp"), + period: BillingPeriodSchema, + /** Analytics */ + analytics: CostAnalyticsSchema, + /** Budgets */ + budgets: external_exports.array(BudgetStatusSchema).optional(), + /** Alerts */ + alerts: external_exports.array(CostAlertSchema).optional(), + activeAlertCount: external_exports.number().int().nonnegative().default(0), + /** Recommendations */ + recommendations: external_exports.array(CostOptimizationRecommendationSchema).optional(), + /** Comparisons */ + previousPeriodCost: external_exports.number().nonnegative().optional(), + costChange: external_exports.number().optional().describe("Change vs previous period"), + costChangePercentage: external_exports.number().optional(), + /** Forecasting */ + forecastedCost: external_exports.number().nonnegative().optional(), + forecastedBudgetStatus: external_exports.enum(["under", "at", "over"]).optional(), + /** Export */ + format: external_exports.enum(["summary", "detailed", "executive"]).default("summary"), + currency: external_exports.string().default("USD") +}); +var CostQueryFiltersSchema = external_exports.object({ + /** Time Range */ + startDate: external_exports.string().datetime().optional().describe("ISO 8601 timestamp"), + endDate: external_exports.string().datetime().optional().describe("ISO 8601 timestamp"), + /** Dimensions */ + modelIds: external_exports.array(external_exports.string()).optional(), + providers: external_exports.array(external_exports.string()).optional(), + userIds: external_exports.array(external_exports.string()).optional(), + agentIds: external_exports.array(external_exports.string()).optional(), + operations: external_exports.array(external_exports.string()).optional(), + sessionIds: external_exports.array(external_exports.string()).optional(), + /** Cost Range */ + minCost: external_exports.number().nonnegative().optional(), + maxCost: external_exports.number().nonnegative().optional(), + /** Tags */ + tags: external_exports.array(external_exports.string()).optional(), + /** Aggregation */ + groupBy: external_exports.array(CostBreakdownDimensionSchema).optional(), + /** Sorting */ + orderBy: external_exports.enum(["timestamp", "cost", "tokens"]).optional().default("timestamp"), + orderDirection: external_exports.enum(["asc", "desc"]).optional().default("desc"), + /** Pagination */ + limit: external_exports.number().int().positive().optional(), + offset: external_exports.number().int().nonnegative().optional() +}); +var VectorStoreProviderSchema = external_exports.enum([ + "pinecone", + "weaviate", + "qdrant", + "milvus", + "chroma", + "pgvector", + "redis", + "opensearch", + "elasticsearch", + "custom" +]); +var EmbeddingModelSchema = external_exports.object({ + provider: external_exports.enum(["openai", "cohere", "huggingface", "azure_openai", "local", "custom"]), + model: external_exports.string().describe('Model name (e.g., "text-embedding-3-large")'), + dimensions: external_exports.number().int().positive().describe("Embedding vector dimensions"), + maxTokens: external_exports.number().int().positive().optional().describe("Maximum tokens per embedding"), + batchSize: external_exports.number().int().positive().optional().default(100).describe("Batch size for embedding"), + endpoint: external_exports.string().url().optional().describe("Custom endpoint URL"), + apiKey: external_exports.string().optional().describe("API key"), + secretRef: external_exports.string().optional().describe("Reference to stored secret") +}); +var ChunkingStrategySchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("fixed"), + chunkSize: external_exports.number().int().positive().describe("Fixed chunk size in tokens/chars"), + chunkOverlap: external_exports.number().int().min(0).default(0).describe("Overlap between chunks"), + unit: external_exports.enum(["tokens", "characters"]).default("tokens") + }), + external_exports.object({ + type: external_exports.literal("semantic"), + model: external_exports.string().optional().describe("Model for semantic chunking"), + minChunkSize: external_exports.number().int().positive().default(100), + maxChunkSize: external_exports.number().int().positive().default(1e3) + }), + external_exports.object({ + type: external_exports.literal("recursive"), + separators: external_exports.array(external_exports.string()).default(["\n\n", "\n", " ", ""]), + chunkSize: external_exports.number().int().positive(), + chunkOverlap: external_exports.number().int().min(0).default(0) + }), + external_exports.object({ + type: external_exports.literal("markdown"), + maxChunkSize: external_exports.number().int().positive().default(1e3), + respectHeaders: external_exports.boolean().default(true).describe("Keep headers with content"), + respectCodeBlocks: external_exports.boolean().default(true).describe("Keep code blocks intact") + }) +]); +var DocumentMetadataSchema = external_exports.object({ + source: external_exports.string().describe("Document source (file path, URL, etc.)"), + sourceType: external_exports.enum(["file", "url", "api", "database", "custom"]).optional(), + title: external_exports.string().optional(), + author: external_exports.string().optional().describe("Document author"), + createdAt: external_exports.string().datetime().optional().describe("ISO timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("ISO timestamp"), + tags: external_exports.array(external_exports.string()).optional(), + category: external_exports.string().optional(), + language: external_exports.string().optional().describe("Document language (ISO 639-1 code)"), + custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata fields") +}); +var DocumentChunkSchema = external_exports.object({ + id: external_exports.string().describe("Unique chunk identifier"), + content: external_exports.string().describe("Chunk text content"), + embedding: external_exports.array(external_exports.number()).optional().describe("Embedding vector"), + metadata: DocumentMetadataSchema, + chunkIndex: external_exports.number().int().min(0).describe("Chunk position in document"), + tokens: external_exports.number().int().optional().describe("Token count") +}); +var RetrievalStrategySchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("similarity"), + topK: external_exports.number().int().positive().default(5).describe("Number of results to retrieve"), + scoreThreshold: external_exports.number().min(0).max(1).optional().describe("Minimum similarity score") + }), + external_exports.object({ + type: external_exports.literal("mmr"), + topK: external_exports.number().int().positive().default(5), + fetchK: external_exports.number().int().positive().default(20).describe("Initial fetch size"), + lambda: external_exports.number().min(0).max(1).default(0.5).describe("Diversity vs relevance (0=diverse, 1=relevant)") + }), + external_exports.object({ + type: external_exports.literal("hybrid"), + topK: external_exports.number().int().positive().default(5), + vectorWeight: external_exports.number().min(0).max(1).default(0.7).describe("Weight for vector search"), + keywordWeight: external_exports.number().min(0).max(1).default(0.3).describe("Weight for keyword search") + }), + external_exports.object({ + type: external_exports.literal("parent_document"), + topK: external_exports.number().int().positive().default(5), + retrieveParent: external_exports.boolean().default(true).describe("Retrieve full parent document") + }) +]); +var RerankingConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false), + model: external_exports.string().optional().describe("Reranking model name"), + provider: external_exports.enum(["cohere", "huggingface", "custom"]).optional(), + topK: external_exports.number().int().positive().default(3).describe("Final number of results after reranking") +}); +var VectorStoreConfigSchema = external_exports.object({ + provider: VectorStoreProviderSchema, + indexName: external_exports.string().describe("Index/collection name"), + namespace: external_exports.string().optional().describe("Namespace for multi-tenancy"), + /** Connection */ + host: external_exports.string().optional().describe("Vector store host"), + port: external_exports.number().int().optional().describe("Vector store port"), + secretRef: external_exports.string().optional().describe("Reference to stored secret"), + apiKey: external_exports.string().optional().describe("API key or reference to secret"), + /** Configuration */ + dimensions: external_exports.number().int().positive().describe("Vector dimensions"), + metric: external_exports.enum(["cosine", "euclidean", "dotproduct"]).optional().default("cosine"), + /** Performance */ + batchSize: external_exports.number().int().positive().optional().default(100), + connectionPoolSize: external_exports.number().int().positive().optional().default(10), + timeout: external_exports.number().int().positive().optional().default(3e4).describe("Timeout in milliseconds") +}); +var DocumentLoaderConfigSchema = external_exports.object({ + type: external_exports.enum(["file", "directory", "url", "api", "database", "custom"]), + /** Source */ + source: external_exports.string().describe("Source path, URL, or identifier"), + /** File Types */ + fileTypes: external_exports.array(external_exports.string()).optional().describe('Accepted file extensions (e.g., [".pdf", ".md"])'), + /** Processing */ + recursive: external_exports.boolean().optional().default(false).describe("Process directories recursively"), + maxFileSize: external_exports.number().int().optional().describe("Maximum file size in bytes"), + excludePatterns: external_exports.array(external_exports.string()).optional().describe("Patterns to exclude"), + /** Text Extraction */ + extractImages: external_exports.boolean().optional().default(false).describe("Extract text from images (OCR)"), + extractTables: external_exports.boolean().optional().default(false).describe("Extract and format tables"), + /** Custom Loader */ + loaderConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom loader-specific config") +}); +var FilterExpressionSchema = external_exports.object({ + field: external_exports.string().describe("Metadata field to filter"), + operator: external_exports.enum(["eq", "neq", "gt", "gte", "lt", "lte", "in", "nin", "contains"]).default("eq"), + value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).describe("Filter value") +}); +var FilterGroupSchema = external_exports.object({ + logic: external_exports.enum(["and", "or"]).default("and"), + filters: external_exports.array(external_exports.union([FilterExpressionSchema, external_exports.lazy(() => FilterGroupSchema)])) +}); +var MetadataFilterSchema = external_exports.union([ + FilterExpressionSchema, + FilterGroupSchema, + // Legacy support for simple key-value map + external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))])) +]); +var RAGPipelineConfigSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Pipeline name (snake_case)"), + label: external_exports.string().describe("Display name"), + description: external_exports.string().optional(), + /** Components */ + embedding: EmbeddingModelSchema, + vectorStore: VectorStoreConfigSchema, + chunking: ChunkingStrategySchema, + retrieval: RetrievalStrategySchema, + reranking: RerankingConfigSchema.optional(), + /** Document Loading */ + loaders: external_exports.array(DocumentLoaderConfigSchema).optional().describe("Document loaders"), + /** Context Management */ + maxContextTokens: external_exports.number().int().positive().default(4e3).describe("Maximum tokens in context"), + contextWindow: external_exports.number().int().positive().optional().describe("LLM context window size"), + /** Metadata Filtering */ + metadataFilters: MetadataFilterSchema.optional().describe("Global filters for retrieval"), + /** Caching */ + enableCache: external_exports.boolean().default(true), + cacheTTL: external_exports.number().int().positive().default(3600).describe("Cache TTL in seconds"), + cacheInvalidationStrategy: external_exports.enum(["time_based", "manual", "on_update"]).default("time_based").optional() +}); +var RAGQueryRequestSchema = external_exports.object({ + query: external_exports.string().describe("User query"), + pipelineName: external_exports.string().describe("Pipeline to use"), + /** Override defaults */ + topK: external_exports.number().int().positive().optional(), + metadataFilters: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + /** Context */ + conversationHistory: external_exports.array(external_exports.object({ + role: external_exports.enum(["user", "assistant", "system"]), + content: external_exports.string() + })).optional(), + /** Options */ + includeMetadata: external_exports.boolean().default(true), + includeSources: external_exports.boolean().default(true) +}); +var RAGQueryResponseSchema = external_exports.object({ + query: external_exports.string(), + results: external_exports.array(external_exports.object({ + content: external_exports.string(), + score: external_exports.number(), + metadata: DocumentMetadataSchema.optional(), + chunkId: external_exports.string().optional() + })), + context: external_exports.string().describe("Assembled context for LLM"), + tokens: TokenUsageSchema.optional().describe("Token usage for this query"), + cost: external_exports.number().nonnegative().optional().describe("Cost for this query in USD"), + retrievalTime: external_exports.number().optional().describe("Retrieval time in milliseconds") +}); +var RAGPipelineStatusSchema = external_exports.object({ + name: external_exports.string(), + status: external_exports.enum(["active", "indexing", "error", "disabled"]), + documentsIndexed: external_exports.number().int().min(0), + lastIndexed: external_exports.string().datetime().optional().describe("ISO timestamp"), + errorMessage: external_exports.string().optional(), + health: external_exports.object({ + vectorStore: external_exports.enum(["healthy", "unhealthy", "unknown"]), + embeddingService: external_exports.enum(["healthy", "unhealthy", "unknown"]) + }).optional() +}); +var QueryIntentSchema = external_exports.enum([ + "select", + // Retrieve data (e.g., "show me all accounts") + "aggregate", + // Aggregation (e.g., "total revenue by region") + "filter", + // Filter data (e.g., "accounts created last month") + "sort", + // Sort data (e.g., "top 10 opportunities by value") + "compare", + // Compare values (e.g., "compare this quarter vs last quarter") + "trend", + // Analyze trends (e.g., "sales trend over time") + "insight", + // Generate insights (e.g., "what's unusual about this data") + "create", + // Create record (e.g., "create a new task") + "update", + // Update record (e.g., "mark this as complete") + "delete" + // Delete record (e.g., "remove this contact") +]); +var EntitySchema = external_exports.object({ + type: external_exports.enum(["object", "field", "value", "operator", "function", "timeframe"]), + text: external_exports.string().describe("Original text from query"), + value: external_exports.unknown().describe("Normalized value"), + confidence: external_exports.number().min(0).max(1).describe("Confidence score"), + span: external_exports.tuple([external_exports.number(), external_exports.number()]).optional().describe("Character span in query") +}); +var TimeframeSchema = external_exports.object({ + type: external_exports.enum(["absolute", "relative"]), + start: external_exports.string().optional().describe("Start date (ISO format)"), + end: external_exports.string().optional().describe("End date (ISO format)"), + relative: external_exports.object({ + unit: external_exports.enum(["hour", "day", "week", "month", "quarter", "year"]), + value: external_exports.number().int(), + direction: external_exports.enum(["past", "future", "current"]).default("past") + }).optional(), + text: external_exports.string().describe("Original timeframe text") +}); +var NLQFieldMappingSchema = external_exports.object({ + naturalLanguage: external_exports.string().describe('NL field name (e.g., "customer name")'), + objectField: external_exports.string().describe('Actual field name (e.g., "account.name")'), + object: external_exports.string().describe("Object name"), + field: external_exports.string().describe("Field name"), + confidence: external_exports.number().min(0).max(1) +}); +var QueryContextSchema = external_exports.object({ + /** User Information */ + userId: external_exports.string().optional(), + userRole: external_exports.string().optional(), + /** Current Context */ + currentObject: external_exports.string().optional().describe("Current object being viewed"), + currentRecordId: external_exports.string().optional().describe("Current record ID"), + /** Conversation History */ + conversationHistory: external_exports.array(external_exports.object({ + query: external_exports.string(), + timestamp: external_exports.string(), + intent: QueryIntentSchema.optional() + })).optional(), + /** Preferences */ + defaultLimit: external_exports.number().int().default(100), + timezone: external_exports.string().default("UTC"), + locale: external_exports.string().default("en-US") +}); +var NLQParseResultSchema = external_exports.object({ + /** Original Query */ + originalQuery: external_exports.string(), + /** Intent Detection */ + intent: QueryIntentSchema, + intentConfidence: external_exports.number().min(0).max(1), + /** Entity Recognition */ + entities: external_exports.array(EntitySchema), + /** Object & Field Resolution */ + targetObject: external_exports.string().optional().describe("Primary object to query"), + fields: external_exports.array(NLQFieldMappingSchema).optional(), + /** Temporal Information */ + timeframe: TimeframeSchema.optional(), + /** Query AST */ + ast: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Generated ObjectQL AST"), + /** Metadata */ + confidence: external_exports.number().min(0).max(1).describe("Overall confidence"), + ambiguities: external_exports.array(external_exports.object({ + type: external_exports.string(), + description: external_exports.string(), + suggestions: external_exports.array(external_exports.string()).optional() + })).optional().describe("Detected ambiguities requiring clarification"), + /** Alternative Interpretations */ + alternatives: external_exports.array(external_exports.object({ + interpretation: external_exports.string(), + confidence: external_exports.number(), + ast: external_exports.unknown() + })).optional() +}); +var NLQRequestSchema = external_exports.object({ + /** Query */ + query: external_exports.string().describe("Natural language query"), + /** Context */ + context: QueryContextSchema.optional(), + /** Options */ + includeAlternatives: external_exports.boolean().default(false).describe("Include alternative interpretations"), + maxAlternatives: external_exports.number().int().default(3), + minConfidence: external_exports.number().min(0).max(1).default(0.5).describe("Minimum confidence threshold"), + /** Execution */ + executeQuery: external_exports.boolean().default(false).describe("Execute query and return results"), + maxResults: external_exports.number().int().optional().describe("Maximum results to return") +}); +var NLQResponseSchema = external_exports.object({ + /** Parse Result */ + parseResult: NLQParseResultSchema, + /** Query Results (if executeQuery = true) */ + results: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Query results"), + totalCount: external_exports.number().int().optional(), + /** Execution Metadata */ + executionTime: external_exports.number().optional().describe("Execution time in milliseconds"), + needsClarification: external_exports.boolean().describe("Whether query needs clarification"), + /** Cost Tracking */ + tokens: TokenUsageSchema.optional().describe("Token usage for this query"), + cost: external_exports.number().nonnegative().optional().describe("Cost for this query in USD"), + /** Suggestions */ + suggestions: external_exports.array(external_exports.string()).optional().describe("Query refinement suggestions") +}); +var NLQTrainingExampleSchema = external_exports.object({ + /** Input */ + query: external_exports.string().describe("Natural language query"), + context: QueryContextSchema.optional(), + /** Expected Output */ + expectedIntent: QueryIntentSchema, + expectedObject: external_exports.string().optional(), + expectedAST: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Expected ObjectQL AST"), + /** Metadata */ + category: external_exports.string().optional().describe("Example category"), + tags: external_exports.array(external_exports.string()).optional(), + notes: external_exports.string().optional() +}); +var NLQModelConfigSchema = external_exports.object({ + /** Model */ + modelId: external_exports.string().describe("Model from registry"), + /** Prompt Engineering */ + systemPrompt: external_exports.string().optional().describe("System prompt override"), + includeSchema: external_exports.boolean().default(true).describe("Include object schema in prompt"), + includeExamples: external_exports.boolean().default(true).describe("Include examples in prompt"), + /** Intent Detection */ + enableIntentDetection: external_exports.boolean().default(true), + intentThreshold: external_exports.number().min(0).max(1).default(0.7), + /** Entity Recognition */ + enableEntityRecognition: external_exports.boolean().default(true), + entityRecognitionModel: external_exports.string().optional(), + /** Field Resolution */ + enableFuzzyMatching: external_exports.boolean().default(true).describe("Fuzzy match field names"), + fuzzyMatchThreshold: external_exports.number().min(0).max(1).default(0.8), + /** Temporal Processing */ + enableTimeframeDetection: external_exports.boolean().default(true), + defaultTimeframe: external_exports.string().optional().describe("Default timeframe if not specified"), + /** Performance */ + enableCaching: external_exports.boolean().default(true), + cacheTTL: external_exports.number().int().default(3600).describe("Cache TTL in seconds") +}); +var NLQAnalyticsSchema = external_exports.object({ + /** Query Metrics */ + totalQueries: external_exports.number().int(), + successfulQueries: external_exports.number().int(), + failedQueries: external_exports.number().int(), + averageConfidence: external_exports.number().min(0).max(1), + /** Intent Distribution */ + intentDistribution: external_exports.record(external_exports.string(), external_exports.number().int()).describe("Count by intent type"), + /** Common Patterns */ + topQueries: external_exports.array(external_exports.object({ + query: external_exports.string(), + count: external_exports.number().int(), + averageConfidence: external_exports.number() + })), + /** Performance */ + averageParseTime: external_exports.number().describe("Average parse time in milliseconds"), + averageExecutionTime: external_exports.number().optional(), + /** Issues */ + lowConfidenceQueries: external_exports.array(external_exports.object({ + query: external_exports.string(), + confidence: external_exports.number(), + timestamp: external_exports.string().datetime() + })), + /** Timeframe */ + startDate: external_exports.string().datetime().describe("ISO timestamp"), + endDate: external_exports.string().datetime().describe("ISO timestamp") +}); +var FieldSynonymConfigSchema = external_exports.object({ + object: external_exports.string().describe("Object name"), + field: external_exports.string().describe("Field name"), + synonyms: external_exports.array(external_exports.string()).describe("Natural language synonyms"), + examples: external_exports.array(external_exports.string()).optional().describe("Example queries using synonyms") +}); +var QueryTemplateSchema = external_exports.object({ + id: external_exports.string(), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Template name (snake_case)"), + label: external_exports.string(), + /** Template */ + pattern: external_exports.string().describe("Query pattern with placeholders"), + variables: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.enum(["object", "field", "value", "timeframe"]), + required: external_exports.boolean().default(false) + })), + /** Generated AST */ + astTemplate: external_exports.record(external_exports.string(), external_exports.unknown()).describe("AST template with variable placeholders"), + /** Metadata */ + category: external_exports.string().optional(), + examples: external_exports.array(external_exports.string()).optional(), + tags: external_exports.array(external_exports.string()).optional() +}); +var AIOrchestrationTriggerSchema = external_exports.enum([ + "record_created", + // When a new record is created + "record_updated", + // When a record is updated + "field_changed", + // When specific field(s) change + "scheduled", + // Time-based trigger (cron) + "manual", + // User-initiated trigger + "webhook", + // External system trigger + "batch" + // Batch processing trigger +]); +var AITaskTypeSchema = external_exports.enum([ + "classify", + // Categorize content into predefined classes + "extract", + // Extract structured data from unstructured content + "summarize", + // Generate concise summaries of text + "generate", + // Generate new content (text, code, etc.) + "predict", + // Make predictions based on historical data + "translate", + // Translate text between languages + "sentiment", + // Analyze sentiment (positive, negative, neutral) + "entity_recognition", + // Identify named entities (people, places, etc.) + "anomaly_detection", + // Detect outliers or unusual patterns + "recommendation" + // Recommend items or actions +]); +var AITaskSchema = external_exports.object({ + /** Task Identity */ + id: external_exports.string().optional().describe("Optional task ID for referencing"), + name: external_exports.string().describe("Human-readable task name"), + type: AITaskTypeSchema, + /** Model Configuration */ + model: external_exports.string().optional().describe("Model ID from registry (uses default if not specified)"), + promptTemplate: external_exports.string().optional().describe("Prompt template ID for this task"), + /** Input Configuration */ + inputFields: external_exports.array(external_exports.string()).describe('Source fields to process (e.g., ["description", "comments"])'), + inputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation schema for inputs"), + inputContext: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context for the AI model"), + /** Output Configuration */ + outputField: external_exports.string().describe("Target field to store the result"), + outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation schema for output"), + outputFormat: external_exports.enum(["text", "json", "number", "boolean", "array"]).optional().default("text"), + /** Classification-specific options */ + classes: external_exports.array(external_exports.string()).optional().describe("Valid classes for classification tasks"), + multiClass: external_exports.boolean().optional().default(false).describe("Allow multiple classes to be selected"), + /** Extraction-specific options */ + extractionSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON schema for structured extraction"), + /** Generation-specific options */ + maxLength: external_exports.number().optional().describe("Maximum length for generated content"), + temperature: external_exports.number().min(0).max(2).optional().describe("Model temperature override"), + /** Error Handling */ + fallbackValue: external_exports.unknown().optional().describe("Fallback value if AI task fails"), + retryAttempts: external_exports.number().int().min(0).max(5).optional().default(1), + /** Conditional Execution */ + condition: external_exports.string().optional().describe("Formula condition - task only runs if TRUE"), + /** Task Metadata */ + description: external_exports.string().optional(), + active: external_exports.boolean().optional().default(true) +}); +var WorkflowFieldConditionSchema = external_exports.object({ + field: external_exports.string().describe("Field name to monitor"), + operator: external_exports.enum(["changed", "changed_to", "changed_from", "is", "is_not"]).optional().default("changed"), + value: external_exports.unknown().optional().describe("Value to compare against (for changed_to/changed_from/is/is_not)") +}); +var WorkflowScheduleSchema = external_exports.object({ + type: external_exports.enum(["cron", "interval", "daily", "weekly", "monthly"]).default("cron"), + cron: external_exports.string().optional().describe('Cron expression (required if type is "cron")'), + interval: external_exports.number().optional().describe('Interval in minutes (required if type is "interval")'), + time: external_exports.string().optional().describe("Time of day for daily schedules (HH:MM format)"), + dayOfWeek: external_exports.number().int().min(0).max(6).optional().describe("Day of week for weekly (0=Sunday)"), + dayOfMonth: external_exports.number().int().min(1).max(31).optional().describe("Day of month for monthly"), + timezone: external_exports.string().optional().default("UTC") +}); +var PostProcessingActionSchema = external_exports.object({ + type: external_exports.enum(["field_update", "send_email", "create_record", "update_related", "trigger_flow", "webhook"]), + name: external_exports.string().describe("Action name"), + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Action-specific configuration"), + condition: external_exports.string().optional().describe("Execute only if condition is TRUE") +}); +var AIOrchestrationSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Orchestration unique identifier (snake_case)"), + label: external_exports.string().describe("Display name"), + description: external_exports.string().optional(), + /** Target Object */ + objectName: external_exports.string().describe("Target object for this orchestration"), + /** Trigger Configuration */ + trigger: AIOrchestrationTriggerSchema, + /** Trigger-specific configuration */ + fieldConditions: external_exports.array(WorkflowFieldConditionSchema).optional().describe("Fields to monitor (for field_changed trigger)"), + schedule: WorkflowScheduleSchema.optional().describe("Schedule configuration (for scheduled trigger)"), + webhookConfig: external_exports.object({ + secret: external_exports.string().optional().describe("Webhook verification secret"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Expected headers") + }).optional().describe("Webhook configuration (for webhook trigger)"), + /** Entry Criteria */ + entryCriteria: external_exports.string().optional().describe("Formula condition - workflow only runs if TRUE"), + /** AI Tasks */ + aiTasks: external_exports.array(AITaskSchema).describe("AI tasks to execute in sequence"), + /** Post-Processing */ + postActions: external_exports.array(PostProcessingActionSchema).optional().describe("Actions after AI tasks complete"), + /** Execution Options */ + executionMode: external_exports.enum(["sequential", "parallel"]).optional().default("sequential").describe("How to execute multiple AI tasks"), + stopOnError: external_exports.boolean().optional().default(false).describe("Stop workflow if any task fails"), + /** Performance & Limits */ + timeout: external_exports.number().optional().describe("Maximum execution time in seconds"), + priority: external_exports.enum(["low", "normal", "high", "critical"]).optional().default("normal"), + /** Monitoring & Logging */ + enableLogging: external_exports.boolean().optional().default(true), + enableMetrics: external_exports.boolean().optional().default(true), + notifyOnFailure: external_exports.array(external_exports.string()).optional().describe("User IDs to notify on failure"), + /** Status */ + active: external_exports.boolean().optional().default(true), + version: external_exports.string().optional().default("1.0.0"), + /** Metadata */ + tags: external_exports.array(external_exports.string()).optional(), + category: external_exports.string().optional().describe('Workflow category (e.g., "support", "sales", "hr")'), + owner: external_exports.string().optional().describe("User ID of workflow owner"), + createdAt: external_exports.string().datetime().optional().describe("ISO timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("ISO timestamp") +}); +var BatchAIOrchestrationExecutionSchema = external_exports.object({ + workflowName: external_exports.string().describe("Orchestration to execute"), + recordIds: external_exports.array(external_exports.string()).describe("Records to process"), + batchSize: external_exports.number().int().min(1).max(1e3).optional().default(10), + parallelism: external_exports.number().int().min(1).max(10).optional().default(3), + priority: external_exports.enum(["low", "normal", "high"]).optional().default("normal") +}); +var AIOrchestrationExecutionResultSchema = external_exports.object({ + workflowName: external_exports.string(), + recordId: external_exports.string(), + status: external_exports.enum(["success", "partial_success", "failed", "skipped"]), + executionTime: external_exports.number().describe("Execution time in milliseconds"), + tasksExecuted: external_exports.number().int().describe("Number of tasks executed"), + tasksSucceeded: external_exports.number().int().describe("Number of tasks succeeded"), + tasksFailed: external_exports.number().int().describe("Number of tasks failed"), + taskResults: external_exports.array(external_exports.object({ + taskId: external_exports.string().optional(), + taskName: external_exports.string(), + status: external_exports.enum(["success", "failed", "skipped"]), + output: external_exports.unknown().optional(), + error: external_exports.string().optional(), + executionTime: external_exports.number().optional().describe("Task execution time in milliseconds"), + modelUsed: external_exports.string().optional(), + tokensUsed: external_exports.number().optional() + })).optional(), + tokens: TokenUsageSchema.optional().describe("Total token usage for this execution"), + cost: external_exports.number().nonnegative().optional().describe("Total cost for this execution in USD"), + error: external_exports.string().optional(), + startedAt: external_exports.string().datetime().describe("ISO timestamp"), + completedAt: external_exports.string().datetime().optional().describe("ISO timestamp") +}); +var AgentCommunicationProtocolSchema = external_exports.enum([ + "message_passing", + // Direct message exchange between agents + "shared_memory", + // Agents read/write to a shared context store + "blackboard" + // Centralized workspace agents contribute to +]); +var AgentGroupRoleSchema = external_exports.enum([ + "coordinator", + // Orchestrates other agents and delegates tasks + "specialist", + // Domain expert performing specific tasks + "critic", + // Reviews and validates other agents' outputs + "executor" + // Carries out actions in the real world (APIs, DB writes) +]); +var AgentGroupMemberSchema = external_exports.object({ + /** Reference to agent name (must match an existing AgentSchema name) */ + agentId: external_exports.string().describe("Agent identifier (reference to AgentSchema.name)"), + /** Role this agent plays in the group */ + role: AgentGroupRoleSchema.describe("Agent role within the group"), + /** Capabilities / skills this agent contributes */ + capabilities: external_exports.array(external_exports.string()).optional().describe("List of capabilities this agent contributes"), + /** Dependencies on other agents in the group */ + dependencies: external_exports.array(external_exports.string()).optional().describe("Agent IDs this agent depends on for input"), + /** Priority order within the group (lower = higher priority) */ + priority: external_exports.number().int().min(0).optional().describe("Execution priority (0 = highest)") +}); +var MultiAgentGroupSchema = external_exports.object({ + /** Group identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Group unique identifier (snake_case)"), + label: external_exports.string().describe("Group display name"), + description: external_exports.string().optional(), + /** Orchestration strategy */ + strategy: external_exports.enum([ + "sequential", + // Agents execute one after another + "parallel", + // Agents execute concurrently + "debate", + // Agents propose, argue, and converge on a solution + "hierarchical", + // Coordinator delegates to specialists + "swarm" + // Agents self-organize dynamically + ]).describe("Multi-agent orchestration strategy"), + /** Agents in this group */ + agents: external_exports.array(AgentGroupMemberSchema).min(2).describe("Agent members (minimum 2)"), + /** Inter-agent communication */ + communication: external_exports.object({ + /** Communication protocol */ + protocol: AgentCommunicationProtocolSchema.describe("Inter-agent communication protocol"), + /** Message queue name (for message_passing) */ + messageQueue: external_exports.string().optional().describe("Message queue identifier for async communication"), + /** Maximum rounds of communication */ + maxRounds: external_exports.number().int().min(1).optional().describe("Maximum communication rounds before forced termination") + }).describe("Communication configuration"), + /** Conflict resolution strategy */ + conflictResolution: external_exports.enum([ + "voting", + // Majority vote decides + "priorityBased", + // Highest-priority agent decides + "consensusBased", + // All agents must agree + "coordinatorDecides" + // Coordinator agent has final say + ]).optional().describe("How conflicts between agents are resolved"), + /** Timeout for the entire group execution in seconds */ + timeout: external_exports.number().int().min(1).optional().describe("Maximum execution time in seconds for the group"), + /** Whether the group is active */ + active: external_exports.boolean().default(true).describe("Whether this agent group is active") +}); +var PredictiveModelTypeSchema = external_exports.enum([ + "classification", + // Binary or multi-class classification + "regression", + // Numerical prediction + "clustering", + // Unsupervised grouping + "forecasting", + // Time-series prediction + "anomaly_detection", + // Outlier detection + "recommendation", + // Item or action recommendation + "ranking" + // Ordering items by relevance +]); +var ModelFeatureSchema = external_exports.object({ + /** Feature Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Feature name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label"), + /** Data Source */ + field: external_exports.string().describe("Source field name"), + object: external_exports.string().optional().describe("Source object (if different from target)"), + /** Feature Type */ + dataType: external_exports.enum(["numeric", "categorical", "text", "datetime", "boolean"]).describe("Feature data type"), + /** Feature Engineering */ + transformation: external_exports.enum([ + "none", + "normalize", + // Normalize to 0-1 range + "standardize", + // Z-score standardization + "one_hot_encode", + // One-hot encoding for categorical + "label_encode", + // Label encoding for categorical + "log_transform", + // Logarithmic transformation + "binning", + // Discretize continuous values + "embedding" + // Text/categorical embedding + ]).optional().default("none"), + /** Configuration */ + required: external_exports.boolean().optional().default(true), + defaultValue: external_exports.unknown().optional(), + /** Metadata */ + description: external_exports.string().optional(), + importance: external_exports.number().optional().describe("Feature importance score (0-1)") +}); +var HyperparametersSchema = external_exports.object({ + /** General Parameters */ + learningRate: external_exports.number().optional().describe("Learning rate for training"), + epochs: external_exports.number().int().optional().describe("Number of training epochs"), + batchSize: external_exports.number().int().optional().describe("Training batch size"), + /** Tree-based Models (Random Forest, XGBoost, etc.) */ + maxDepth: external_exports.number().int().optional().describe("Maximum tree depth"), + numTrees: external_exports.number().int().optional().describe("Number of trees in ensemble"), + minSamplesSplit: external_exports.number().int().optional().describe("Minimum samples to split node"), + minSamplesLeaf: external_exports.number().int().optional().describe("Minimum samples in leaf node"), + /** Neural Networks */ + hiddenLayers: external_exports.array(external_exports.number().int()).optional().describe("Hidden layer sizes"), + activation: external_exports.string().optional().describe("Activation function"), + dropout: external_exports.number().optional().describe("Dropout rate"), + /** Regularization */ + l1Regularization: external_exports.number().optional().describe("L1 regularization strength"), + l2Regularization: external_exports.number().optional().describe("L2 regularization strength"), + /** Clustering */ + numClusters: external_exports.number().int().optional().describe("Number of clusters (k-means, etc.)"), + /** Time Series */ + seasonalPeriod: external_exports.number().int().optional().describe("Seasonal period for time series"), + forecastHorizon: external_exports.number().int().optional().describe("Number of periods to forecast"), + /** Additional custom parameters */ + custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Algorithm-specific parameters") +}); +var TrainingConfigSchema = external_exports.object({ + /** Data Split */ + trainingDataRatio: external_exports.number().min(0).max(1).optional().default(0.8).describe("Proportion of data for training"), + validationDataRatio: external_exports.number().min(0).max(1).optional().default(0.1).describe("Proportion for validation"), + testDataRatio: external_exports.number().min(0).max(1).optional().default(0.1).describe("Proportion for testing"), + /** Data Filtering */ + dataFilter: external_exports.string().optional().describe("Formula to filter training data"), + minRecords: external_exports.number().int().optional().default(100).describe("Minimum records required"), + maxRecords: external_exports.number().int().optional().describe("Maximum records to use"), + /** Training Strategy */ + strategy: external_exports.enum(["full", "incremental", "online", "transfer_learning"]).optional().default("full"), + crossValidation: external_exports.boolean().optional().default(true), + folds: external_exports.number().int().min(2).max(10).optional().default(5).describe("Cross-validation folds"), + /** Early Stopping */ + earlyStoppingEnabled: external_exports.boolean().optional().default(true), + earlyStoppingPatience: external_exports.number().int().optional().default(10).describe("Epochs without improvement before stopping"), + /** Resource Limits */ + maxTrainingTime: external_exports.number().optional().describe("Maximum training time in seconds"), + gpuEnabled: external_exports.boolean().optional().default(false), + /** Reproducibility */ + randomSeed: external_exports.number().int().optional().describe("Random seed for reproducibility") +}).superRefine((data, ctx) => { + if (data.trainingDataRatio && data.validationDataRatio && data.testDataRatio) { + const sum = data.trainingDataRatio + data.validationDataRatio + data.testDataRatio; + if (Math.abs(sum - 1) > 0.01) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Data split ratios must sum to 1. Current sum: ${sum}`, + path: ["trainingDataRatio"] + }); + } + } +}); +var EvaluationMetricsSchema = external_exports.object({ + /** Classification Metrics */ + accuracy: external_exports.number().optional(), + precision: external_exports.number().optional(), + recall: external_exports.number().optional(), + f1Score: external_exports.number().optional(), + auc: external_exports.number().optional().describe("Area Under ROC Curve"), + /** Regression Metrics */ + mse: external_exports.number().optional().describe("Mean Squared Error"), + rmse: external_exports.number().optional().describe("Root Mean Squared Error"), + mae: external_exports.number().optional().describe("Mean Absolute Error"), + r2Score: external_exports.number().optional().describe("R-squared score"), + /** Clustering Metrics */ + silhouetteScore: external_exports.number().optional(), + daviesBouldinIndex: external_exports.number().optional(), + /** Time Series Metrics */ + mape: external_exports.number().optional().describe("Mean Absolute Percentage Error"), + smape: external_exports.number().optional().describe("Symmetric MAPE"), + /** Additional Metrics */ + custom: external_exports.record(external_exports.string(), external_exports.number()).optional() +}); +var PredictiveModelSchema = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Model unique identifier (snake_case)"), + label: external_exports.string().describe("Model display name"), + description: external_exports.string().optional(), + /** Model Type */ + type: PredictiveModelTypeSchema, + algorithm: external_exports.string().optional().describe('Specific algorithm (e.g., "random_forest", "xgboost", "lstm")'), + /** Target Object & Field */ + objectName: external_exports.string().describe("Target object for predictions"), + target: external_exports.string().describe("Target field to predict"), + targetType: external_exports.enum(["numeric", "categorical", "binary"]).optional().describe("Target field type"), + /** Features */ + features: external_exports.array(ModelFeatureSchema).describe("Input features for the model"), + /** Hyperparameters */ + hyperparameters: HyperparametersSchema.optional(), + /** Training Configuration */ + training: TrainingConfigSchema.optional(), + /** Model Performance */ + metrics: EvaluationMetricsSchema.optional().describe("Evaluation metrics from last training"), + /** Deployment */ + deploymentStatus: external_exports.enum(["draft", "training", "trained", "deployed", "deprecated"]).optional().default("draft"), + version: external_exports.string().optional().default("1.0.0"), + /** Prediction Configuration */ + predictionField: external_exports.string().optional().describe("Field to store predictions"), + confidenceField: external_exports.string().optional().describe("Field to store confidence scores"), + updateTrigger: external_exports.enum(["on_create", "on_update", "manual", "scheduled"]).optional().default("on_create"), + /** Retraining */ + autoRetrain: external_exports.boolean().optional().default(false), + retrainSchedule: external_exports.string().optional().describe("Cron expression for auto-retraining"), + retrainThreshold: external_exports.number().optional().describe("Performance threshold to trigger retraining"), + /** Explainability */ + enableExplainability: external_exports.boolean().optional().default(false).describe("Generate feature importance & explanations"), + /** Monitoring */ + enableMonitoring: external_exports.boolean().optional().default(true), + alertOnDrift: external_exports.boolean().optional().default(true).describe("Alert when model drift is detected"), + /** Access Control */ + active: external_exports.boolean().optional().default(true), + owner: external_exports.string().optional().describe("User ID of model owner"), + permissions: external_exports.array(external_exports.string()).optional().describe("User/group IDs with access"), + /** Metadata */ + tags: external_exports.array(external_exports.string()).optional(), + category: external_exports.string().optional().describe('Model category (e.g., "sales", "marketing", "operations")'), + lastTrainedAt: external_exports.string().datetime().optional().describe("ISO timestamp"), + createdAt: external_exports.string().datetime().optional().describe("ISO timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("ISO timestamp") +}); +var PredictionRequestSchema = external_exports.object({ + modelName: external_exports.string().describe("Model to use for prediction"), + recordIds: external_exports.array(external_exports.string()).optional().describe("Specific records to predict (if not provided, uses all)"), + inputData: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Direct input data (alternative to recordIds)"), + returnConfidence: external_exports.boolean().optional().default(true), + returnExplanation: external_exports.boolean().optional().default(false) +}); +var PredictionResultSchema = external_exports.object({ + modelName: external_exports.string(), + modelVersion: external_exports.string(), + recordId: external_exports.string().optional(), + prediction: external_exports.unknown().describe("The predicted value"), + confidence: external_exports.number().optional().describe("Confidence score (0-1)"), + probabilities: external_exports.record(external_exports.string(), external_exports.number()).optional().describe("Class probabilities (for classification)"), + explanation: external_exports.object({ + topFeatures: external_exports.array(external_exports.object({ + feature: external_exports.string(), + importance: external_exports.number(), + value: external_exports.unknown() + })).optional(), + reasoning: external_exports.string().optional() + }).optional(), + tokens: TokenUsageSchema.optional().describe("Token usage for this prediction (if AI-powered)"), + cost: external_exports.number().nonnegative().optional().describe("Cost for this prediction in USD"), + metadata: external_exports.object({ + executionTime: external_exports.number().optional().describe("Execution time in milliseconds"), + timestamp: external_exports.string().datetime().optional().describe("ISO timestamp") + }).optional() +}); +var ModelDriftSchema = external_exports.object({ + modelName: external_exports.string(), + driftType: external_exports.enum(["feature_drift", "prediction_drift", "performance_drift"]), + severity: external_exports.enum(["low", "medium", "high", "critical"]), + detectedAt: external_exports.string().datetime().describe("ISO timestamp"), + metrics: external_exports.object({ + driftScore: external_exports.number().describe("Drift magnitude (0-1)"), + affectedFeatures: external_exports.array(external_exports.string()).optional(), + performanceChange: external_exports.number().optional().describe("Change in performance metric") + }), + recommendation: external_exports.string().optional(), + autoRetrainTriggered: external_exports.boolean().optional().default(false) +}); +var MessageRoleSchema = external_exports.enum([ + "system", + "user", + "assistant", + "function", + "tool" +]); +var MessageContentTypeSchema = external_exports.enum([ + "text", + "image", + "file", + "code", + "structured" +]); +var TextContentSchema = external_exports.object({ + type: external_exports.literal("text"), + text: external_exports.string().describe("Text content"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var ImageContentSchema = external_exports.object({ + type: external_exports.literal("image"), + imageUrl: external_exports.string().url().describe("Image URL"), + detail: external_exports.enum(["low", "high", "auto"]).optional().default("auto"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var FileContentSchema = external_exports.object({ + type: external_exports.literal("file"), + fileUrl: external_exports.string().url().describe("File attachment URL"), + mimeType: external_exports.string().describe("MIME type"), + fileName: external_exports.string().optional(), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var CodeContentSchema = external_exports.object({ + type: external_exports.literal("code"), + text: external_exports.string().describe("Code snippet"), + language: external_exports.string().optional().default("text"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var MessageContentSchema = external_exports.union([ + TextContentSchema, + ImageContentSchema, + FileContentSchema, + CodeContentSchema +]); +var FunctionCallSchema = external_exports.object({ + name: external_exports.string().describe("Function name"), + arguments: external_exports.string().describe("JSON string of function arguments"), + result: external_exports.string().optional().describe("Function execution result") +}); +var ToolCallSchema = external_exports.object({ + id: external_exports.string().describe("Tool call ID"), + type: external_exports.enum(["function"]).default("function"), + function: FunctionCallSchema +}); +var ConversationMessageSchema = external_exports.object({ + /** Identity */ + id: external_exports.string().describe("Unique message ID"), + timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), + /** Content */ + role: MessageRoleSchema, + content: external_exports.array(MessageContentSchema).describe("Message content (multimodal array)"), + /** Function/Tool Calls */ + functionCall: FunctionCallSchema.optional().describe("Legacy function call"), + toolCalls: external_exports.array(ToolCallSchema).optional().describe("Tool calls"), + toolCallId: external_exports.string().optional().describe("Tool call ID this message responds to"), + /** Metadata */ + name: external_exports.string().optional().describe("Name of the function/user"), + tokens: TokenUsageSchema.optional().describe("Token usage for this message"), + cost: external_exports.number().nonnegative().optional().describe("Cost for this message in USD"), + /** Context Management */ + pinned: external_exports.boolean().optional().default(false).describe("Prevent removal during pruning"), + importance: external_exports.number().min(0).max(1).optional().describe("Importance score for pruning"), + embedding: external_exports.array(external_exports.number()).optional().describe("Vector embedding for semantic search"), + /** Annotations */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var TokenBudgetStrategySchema = external_exports.enum([ + "fifo", + // First-in-first-out (oldest messages dropped) + "importance", + // Drop by importance score + "semantic", + // Keep semantically relevant messages + "sliding_window", + // Fixed window of recent messages + "summary" + // Summarize old context +]); +var TokenBudgetConfigSchema = external_exports.object({ + /** Budget Limits */ + maxTokens: external_exports.number().int().positive().describe("Maximum total tokens"), + maxPromptTokens: external_exports.number().int().positive().optional().describe("Max tokens for prompt"), + maxCompletionTokens: external_exports.number().int().positive().optional().describe("Max tokens for completion"), + /** Buffer & Reserves */ + reserveTokens: external_exports.number().int().nonnegative().default(500).describe("Reserve tokens for system messages"), + bufferPercentage: external_exports.number().min(0).max(1).default(0.1).describe("Buffer percentage (0.1 = 10%)"), + /** Pruning Strategy */ + strategy: TokenBudgetStrategySchema.default("sliding_window"), + /** Strategy-Specific Options */ + slidingWindowSize: external_exports.number().int().positive().optional().describe("Number of recent messages to keep"), + minImportanceScore: external_exports.number().min(0).max(1).optional().describe("Minimum importance to keep"), + semanticThreshold: external_exports.number().min(0).max(1).optional().describe("Semantic similarity threshold"), + /** Summarization */ + enableSummarization: external_exports.boolean().default(false).describe("Enable context summarization"), + summarizationThreshold: external_exports.number().int().positive().optional().describe("Trigger summarization at N tokens"), + summaryModel: external_exports.string().optional().describe("Model ID for summarization"), + /** Monitoring */ + warnThreshold: external_exports.number().min(0).max(1).default(0.8).describe("Warn at % of budget (0.8 = 80%)") +}); +var TokenUsageStatsSchema = external_exports.object({ + promptTokens: external_exports.number().int().nonnegative().default(0), + completionTokens: external_exports.number().int().nonnegative().default(0), + totalTokens: external_exports.number().int().nonnegative().default(0), + /** Budget Status */ + budgetLimit: external_exports.number().int().positive(), + budgetUsed: external_exports.number().int().nonnegative().default(0), + budgetRemaining: external_exports.number().int().nonnegative(), + budgetPercentage: external_exports.number().min(0).max(1).describe("Usage as percentage of budget"), + /** Message Stats */ + messageCount: external_exports.number().int().nonnegative().default(0), + prunedMessageCount: external_exports.number().int().nonnegative().default(0), + summarizedMessageCount: external_exports.number().int().nonnegative().default(0) +}); +var ConversationContextSchema = external_exports.object({ + /** Identity */ + sessionId: external_exports.string().describe("Conversation session ID"), + userId: external_exports.string().optional().describe("User identifier"), + agentId: external_exports.string().optional().describe("AI agent identifier"), + /** Context Data */ + object: external_exports.string().optional().describe('Related object (e.g., "case", "project")'), + recordId: external_exports.string().optional().describe("Related record ID"), + scope: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context scope"), + /** System Instructions */ + systemMessage: external_exports.string().optional().describe("System prompt/instructions"), + /** Metadata */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var ConversationSessionSchema = external_exports.object({ + /** Identity */ + id: external_exports.string().describe("Unique session ID"), + name: external_exports.string().optional().describe("Session name/title"), + /** Configuration */ + context: ConversationContextSchema, + modelId: external_exports.string().optional().describe("AI model ID"), + tokenBudget: TokenBudgetConfigSchema, + /** Messages */ + messages: external_exports.array(ConversationMessageSchema).default([]), + /** Token Tracking */ + tokens: TokenUsageStatsSchema.optional(), + totalTokens: TokenUsageSchema.optional().describe("Total tokens across all messages"), + totalCost: external_exports.number().nonnegative().optional().describe("Total cost for this session in USD"), + /** Session Status */ + status: external_exports.enum(["active", "paused", "completed", "archived"]).default("active"), + /** Timestamps */ + createdAt: external_exports.string().datetime().describe("ISO 8601 timestamp"), + updatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp"), + expiresAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() +}); +var ConversationSummarySchema = external_exports.object({ + /** Summary Content */ + summary: external_exports.string().describe("Conversation summary"), + keyPoints: external_exports.array(external_exports.string()).optional().describe("Key discussion points"), + /** Token Savings */ + originalTokens: external_exports.number().int().nonnegative().describe("Original token count"), + summaryTokens: external_exports.number().int().nonnegative().describe("Summary token count"), + tokensSaved: external_exports.number().int().nonnegative().describe("Tokens saved"), + /** Source Messages */ + messageRange: external_exports.object({ + startIndex: external_exports.number().int().nonnegative(), + endIndex: external_exports.number().int().nonnegative() + }).describe("Range of messages summarized"), + /** Metadata */ + generatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp"), + modelId: external_exports.string().optional().describe("Model used for summarization") +}); +var MessagePruningEventSchema = external_exports.object({ + /** Event Details */ + timestamp: external_exports.string().datetime().describe("Event timestamp"), + /** Pruned Messages */ + prunedMessages: external_exports.array(external_exports.object({ + messageId: external_exports.string(), + role: MessageRoleSchema, + tokens: external_exports.number().int().nonnegative(), + importance: external_exports.number().min(0).max(1).optional() + })), + /** Impact */ + tokensFreed: external_exports.number().int().nonnegative(), + messagesRemoved: external_exports.number().int().nonnegative(), + /** Post-Pruning State */ + remainingTokens: external_exports.number().int().nonnegative(), + remainingMessages: external_exports.number().int().nonnegative() +}); +var ConversationAnalyticsSchema = external_exports.object({ + /** Session Info */ + sessionId: external_exports.string(), + /** Message Statistics */ + totalMessages: external_exports.number().int().nonnegative(), + userMessages: external_exports.number().int().nonnegative(), + assistantMessages: external_exports.number().int().nonnegative(), + systemMessages: external_exports.number().int().nonnegative(), + /** Token Statistics */ + totalTokens: external_exports.number().int().nonnegative(), + averageTokensPerMessage: external_exports.number().nonnegative(), + peakTokenUsage: external_exports.number().int().nonnegative(), + /** Efficiency Metrics */ + pruningEvents: external_exports.number().int().nonnegative().default(0), + summarizationEvents: external_exports.number().int().nonnegative().default(0), + tokensSavedByPruning: external_exports.number().int().nonnegative().default(0), + tokensSavedBySummarization: external_exports.number().int().nonnegative().default(0), + /** Duration */ + duration: external_exports.number().nonnegative().optional().describe("Session duration in seconds"), + firstMessageAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp"), + lastMessageAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp") +}); +var MetadataSourceSchema22 = external_exports.object({ + file: external_exports.string().optional(), + line: external_exports.number().optional(), + column: external_exports.number().optional(), + // Logic references + package: external_exports.string().optional(), + object: external_exports.string().optional(), + field: external_exports.string().optional(), + component: external_exports.string().optional() + // specific UI component or flow node +}); +var IssueSchema = external_exports.object({ + id: external_exports.string(), + severity: external_exports.enum(["critical", "error", "warning", "info"]), + message: external_exports.string(), + stackTrace: external_exports.string().optional(), + timestamp: external_exports.string().datetime(), + userId: external_exports.string().optional(), + // Context snapshot + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + // The suspected metadata culprit + source: MetadataSourceSchema22.optional() +}); +var ResolutionSchema = external_exports.object({ + issueId: external_exports.string(), + reasoning: external_exports.string().describe("Explanation of why this fix is needed"), + confidence: external_exports.number().min(0).max(1), + // Actionable change to fix the issue + fix: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("metadata_change"), + changeSet: ChangeSetSchema2 + }), + external_exports.object({ + type: external_exports.literal("manual_intervention"), + instructions: external_exports.string() + }) + ]) +}); +var FeedbackLoopSchema = external_exports.object({ + issue: IssueSchema, + analysis: external_exports.string().optional().describe("AI analysis of the root cause"), + resolutions: external_exports.array(ResolutionSchema).optional(), + status: external_exports.enum(["open", "analyzing", "resolved", "ignored"]).default("open") +}); +var api_exports = {}; +__export4(api_exports, { + AckMessageSchema: () => AckMessageSchema2, + AddReactionRequestSchema: () => AddReactionRequestSchema2, + AddReactionResponseSchema: () => AddReactionResponseSchema2, + AiInsightsRequestSchema: () => AiInsightsRequestSchema2, + AiInsightsResponseSchema: () => AiInsightsResponseSchema2, + AiNlqRequestSchema: () => AiNlqRequestSchema2, + AiNlqResponseSchema: () => AiNlqResponseSchema2, + AiSuggestRequestSchema: () => AiSuggestRequestSchema2, + AiSuggestResponseSchema: () => AiSuggestResponseSchema2, + AnalyticsEndpoint: () => AnalyticsEndpoint2, + AnalyticsMetadataResponseSchema: () => AnalyticsMetadataResponseSchema2, + AnalyticsQueryRequestSchema: () => AnalyticsQueryRequestSchema2, + AnalyticsResultResponseSchema: () => AnalyticsResultResponseSchema2, + AnalyticsSqlResponseSchema: () => AnalyticsSqlResponseSchema2, + ApiChangelogEntrySchema: () => ApiChangelogEntrySchema2, + ApiDiscoveryQuerySchema: () => ApiDiscoveryQuerySchema2, + ApiDiscoveryResponseSchema: () => ApiDiscoveryResponseSchema2, + ApiDocumentationConfig: () => ApiDocumentationConfig2, + ApiDocumentationConfigSchema: () => ApiDocumentationConfigSchema2, + ApiEndpoint: () => ApiEndpoint2, + ApiEndpointRegistration: () => ApiEndpointRegistration2, + ApiEndpointRegistrationSchema: () => ApiEndpointRegistrationSchema2, + ApiEndpointSchema: () => ApiEndpointSchema2, + ApiErrorSchema: () => ApiErrorSchema2, + ApiMappingSchema: () => ApiMappingSchema2, + ApiMetadataSchema: () => ApiMetadataSchema2, + ApiParameterSchema: () => ApiParameterSchema2, + ApiProtocolType: () => ApiProtocolType2, + ApiRegistry: () => ApiRegistry2, + ApiRegistryEntry: () => ApiRegistryEntry2, + ApiRegistryEntrySchema: () => ApiRegistryEntrySchema2, + ApiRegistrySchema: () => ApiRegistrySchema2, + ApiResponseSchema: () => ApiResponseSchema2, + ApiRoutesSchema: () => ApiRoutesSchema2, + ApiTestCollection: () => ApiTestCollection2, + ApiTestCollectionSchema: () => ApiTestCollectionSchema2, + ApiTestRequestSchema: () => ApiTestRequestSchema2, + ApiTestingUiConfigSchema: () => ApiTestingUiConfigSchema2, + ApiTestingUiType: () => ApiTestingUiType2, + AppDefinitionResponseSchema: () => AppDefinitionResponseSchema2, + AuthEndpointAliases: () => AuthEndpointAliases2, + AuthEndpointPaths: () => AuthEndpointPaths2, + AuthEndpointSchema: () => AuthEndpointSchema2, + AuthProvider: () => AuthProvider2, + AutomationApiContracts: () => AutomationApiContracts, + AutomationApiErrorCode: () => AutomationApiErrorCode2, + AutomationFlowPathParamsSchema: () => AutomationFlowPathParamsSchema2, + AutomationRunPathParamsSchema: () => AutomationRunPathParamsSchema2, + AutomationTriggerRequestSchema: () => AutomationTriggerRequestSchema2, + AutomationTriggerResponseSchema: () => AutomationTriggerResponseSchema2, + BasePresenceSchema: () => BasePresenceSchema2, + BaseResponseSchema: () => BaseResponseSchema2, + BatchApiContracts: () => BatchApiContracts, + BatchConfigSchema: () => BatchConfigSchema2, + BatchDataRequestSchema: () => BatchDataRequestSchema2, + BatchDataResponseSchema: () => BatchDataResponseSchema, + BatchEndpointsConfigSchema: () => BatchEndpointsConfigSchema2, + BatchLoadingStrategySchema: () => BatchLoadingStrategySchema2, + BatchOperationResultSchema: () => BatchOperationResultSchema2, + BatchOperationType: () => BatchOperationType2, + BatchOptionsSchema: () => BatchOptionsSchema2, + BatchRecordSchema: () => BatchRecordSchema2, + BatchUpdateRequestSchema: () => BatchUpdateRequestSchema2, + BatchUpdateResponseSchema: () => BatchUpdateResponseSchema2, + BulkRequestSchema: () => BulkRequestSchema2, + BulkResponseSchema: () => BulkResponseSchema2, + CacheControlSchema: () => CacheControlSchema2, + CacheDirective: () => CacheDirective2, + CacheInvalidationRequestSchema: () => CacheInvalidationRequestSchema2, + CacheInvalidationResponseSchema: () => CacheInvalidationResponseSchema2, + CacheInvalidationTarget: () => CacheInvalidationTarget2, + CallbackSchema: () => CallbackSchema2, + ChangelogEntrySchema: () => ChangelogEntrySchema2, + CheckPermissionRequestSchema: () => CheckPermissionRequestSchema2, + CheckPermissionResponseSchema: () => CheckPermissionResponseSchema2, + CodeGenerationTemplateSchema: () => CodeGenerationTemplateSchema2, + CompleteChunkedUploadRequestSchema: () => CompleteChunkedUploadRequestSchema2, + CompleteChunkedUploadResponseSchema: () => CompleteChunkedUploadResponseSchema2, + CompleteUploadRequestSchema: () => CompleteUploadRequestSchema2, + ConceptListResponseSchema: () => ConceptListResponseSchema2, + ConflictResolutionStrategy: () => ConflictResolutionStrategy2, + CreateDataRequestSchema: () => CreateDataRequestSchema2, + CreateDataResponseSchema: () => CreateDataResponseSchema2, + CreateExportJobRequestSchema: () => CreateExportJobRequestSchema2, + CreateExportJobResponseSchema: () => CreateExportJobResponseSchema2, + CreateFeedItemRequestSchema: () => CreateFeedItemRequestSchema2, + CreateFeedItemResponseSchema: () => CreateFeedItemResponseSchema2, + CreateFlowRequestSchema: () => CreateFlowRequestSchema, + CreateFlowResponseSchema: () => CreateFlowResponseSchema2, + CreateManyDataRequestSchema: () => CreateManyDataRequestSchema2, + CreateManyDataResponseSchema: () => CreateManyDataResponseSchema2, + CreateRequestSchema: () => CreateRequestSchema2, + CreateViewRequestSchema: () => CreateViewRequestSchema2, + CreateViewResponseSchema: () => CreateViewResponseSchema2, + CrudEndpointPatternSchema: () => CrudEndpointPatternSchema2, + CrudEndpointsConfigSchema: () => CrudEndpointsConfigSchema2, + CrudOperation: () => CrudOperation2, + CursorMessageSchema: () => CursorMessageSchema2, + CursorPositionSchema: () => CursorPositionSchema2, + DEFAULT_AI_ROUTES: () => DEFAULT_AI_ROUTES, + DEFAULT_ANALYTICS_ROUTES: () => DEFAULT_ANALYTICS_ROUTES, + DEFAULT_AUTOMATION_ROUTES: () => DEFAULT_AUTOMATION_ROUTES, + DEFAULT_BATCH_ROUTES: () => DEFAULT_BATCH_ROUTES, + DEFAULT_DATA_CRUD_ROUTES: () => DEFAULT_DATA_CRUD_ROUTES, + DEFAULT_DISCOVERY_ROUTES: () => DEFAULT_DISCOVERY_ROUTES, + DEFAULT_DISPATCHER_ROUTES: () => DEFAULT_DISPATCHER_ROUTES, + DEFAULT_I18N_ROUTES: () => DEFAULT_I18N_ROUTES, + DEFAULT_METADATA_ROUTES: () => DEFAULT_METADATA_ROUTES, + DEFAULT_NOTIFICATION_ROUTES: () => DEFAULT_NOTIFICATION_ROUTES, + DEFAULT_PERMISSION_ROUTES: () => DEFAULT_PERMISSION_ROUTES, + DEFAULT_REALTIME_ROUTES: () => DEFAULT_REALTIME_ROUTES, + DEFAULT_VERSIONING_CONFIG: () => DEFAULT_VERSIONING_CONFIG, + DEFAULT_VIEW_ROUTES: () => DEFAULT_VIEW_ROUTES, + DEFAULT_WORKFLOW_ROUTES: () => DEFAULT_WORKFLOW_ROUTES, + DataEventSchema: () => DataEventSchema2, + DataEventType: () => DataEventType2, + DataLoaderConfigSchema: () => DataLoaderConfigSchema2, + DeduplicationStrategy: () => DeduplicationStrategy2, + DeleteDataRequestSchema: () => DeleteDataRequestSchema2, + DeleteDataResponseSchema: () => DeleteDataResponseSchema2, + DeleteFeedItemRequestSchema: () => DeleteFeedItemRequestSchema, + DeleteFeedItemResponseSchema: () => DeleteFeedItemResponseSchema2, + DeleteFlowRequestSchema: () => DeleteFlowRequestSchema, + DeleteFlowResponseSchema: () => DeleteFlowResponseSchema2, + DeleteManyDataRequestSchema: () => DeleteManyDataRequestSchema2, + DeleteManyDataResponseSchema: () => DeleteManyDataResponseSchema, + DeleteManyRequestSchema: () => DeleteManyRequestSchema2, + DeleteResponseSchema: () => DeleteResponseSchema2, + DeleteViewRequestSchema: () => DeleteViewRequestSchema2, + DeleteViewResponseSchema: () => DeleteViewResponseSchema2, + DisablePackageRequestSchema: () => DisablePackageRequestSchema3, + DisablePackageResponseSchema: () => DisablePackageResponseSchema3, + DiscoverySchema: () => DiscoverySchema2, + DispatcherConfigSchema: () => DispatcherConfigSchema2, + DispatcherErrorCode: () => DispatcherErrorCode2, + DispatcherErrorResponseSchema: () => DispatcherErrorResponseSchema2, + DispatcherRouteSchema: () => DispatcherRouteSchema2, + DocumentStateSchema: () => DocumentStateSchema2, + ETagSchema: () => ETagSchema2, + EditMessageSchema: () => EditMessageSchema2, + EditOperationSchema: () => EditOperationSchema2, + EditOperationType: () => EditOperationType2, + EnablePackageRequestSchema: () => EnablePackageRequestSchema3, + EnablePackageResponseSchema: () => EnablePackageResponseSchema3, + EndpointMapping: () => EndpointMapping2, + EndpointRegistrySchema: () => EndpointRegistrySchema2, + EnhancedApiErrorSchema: () => EnhancedApiErrorSchema2, + ErrorCategory: () => ErrorCategory2, + ErrorHandlingConfigSchema: () => ErrorHandlingConfigSchema2, + ErrorHttpStatusMap: () => ErrorHttpStatusMap, + ErrorMessageSchema: () => ErrorMessageSchema2, + ErrorResponseSchema: () => ErrorResponseSchema2, + EventFilterCondition: () => EventFilterCondition2, + EventFilterSchema: () => EventFilterSchema2, + EventMessageSchema: () => EventMessageSchema2, + EventPatternSchema: () => EventPatternSchema2, + EventSubscriptionSchema: () => EventSubscriptionSchema2, + ExportApiContracts: () => ExportApiContracts2, + ExportFormat: () => ExportFormat2, + ExportImportTemplateSchema: () => ExportImportTemplateSchema2, + ExportJobProgressSchema: () => ExportJobProgressSchema2, + ExportJobStatus: () => ExportJobStatus2, + ExportJobSummarySchema: () => ExportJobSummarySchema2, + ExportRequestSchema: () => ExportRequestSchema2, + FederationEntityKeySchema: () => FederationEntityKeySchema2, + FederationEntitySchema: () => FederationEntitySchema2, + FederationExternalFieldSchema: () => FederationExternalFieldSchema2, + FederationGatewaySchema: () => FederationGatewaySchema2, + FederationProvidesSchema: () => FederationProvidesSchema2, + FederationRequiresSchema: () => FederationRequiresSchema2, + FeedApiContracts: () => FeedApiContracts, + FeedApiErrorCode: () => FeedApiErrorCode2, + FeedItemPathParamsSchema: () => FeedItemPathParamsSchema2, + FeedListFilterType: () => FeedListFilterType2, + FeedPathParamsSchema: () => FeedPathParamsSchema2, + FeedUnsubscribeRequestSchema: () => FeedUnsubscribeRequestSchema, + FieldErrorSchema: () => FieldErrorSchema2, + FieldMappingEntrySchema: () => FieldMappingEntrySchema2, + FileTypeValidationSchema: () => FileTypeValidationSchema2, + FileUploadResponseSchema: () => FileUploadResponseSchema2, + FilterOperator: () => FilterOperator2, + FindDataRequestSchema: () => FindDataRequestSchema2, + FindDataResponseSchema: () => FindDataResponseSchema2, + FlowSummarySchema: () => FlowSummarySchema2, + GeneratedApiDocumentationSchema: () => GeneratedApiDocumentationSchema2, + GeneratedEndpointSchema: () => GeneratedEndpointSchema2, + GetAnalyticsMetaRequestSchema: () => GetAnalyticsMetaRequestSchema2, + GetChangelogRequestSchema: () => GetChangelogRequestSchema2, + GetChangelogResponseSchema: () => GetChangelogResponseSchema2, + GetDataRequestSchema: () => GetDataRequestSchema2, + GetDataResponseSchema: () => GetDataResponseSchema2, + GetDiscoveryRequestSchema: () => GetDiscoveryRequestSchema2, + GetDiscoveryResponseSchema: () => GetDiscoveryResponseSchema2, + GetEffectivePermissionsRequestSchema: () => GetEffectivePermissionsRequestSchema2, + GetEffectivePermissionsResponseSchema: () => GetEffectivePermissionsResponseSchema2, + GetExportJobDownloadRequestSchema: () => GetExportJobDownloadRequestSchema2, + GetExportJobDownloadResponseSchema: () => GetExportJobDownloadResponseSchema2, + GetFeedRequestSchema: () => GetFeedRequestSchema2, + GetFeedResponseSchema: () => GetFeedResponseSchema2, + GetFieldLabelsRequestSchema: () => GetFieldLabelsRequestSchema2, + GetFieldLabelsResponseSchema: () => GetFieldLabelsResponseSchema2, + GetFlowRequestSchema: () => GetFlowRequestSchema, + GetFlowResponseSchema: () => GetFlowResponseSchema2, + GetInstalledPackageRequestSchema: () => GetInstalledPackageRequestSchema, + GetInstalledPackageResponseSchema: () => GetInstalledPackageResponseSchema2, + GetLocalesRequestSchema: () => GetLocalesRequestSchema2, + GetLocalesResponseSchema: () => GetLocalesResponseSchema2, + GetMetaItemCachedRequestSchema: () => GetMetaItemCachedRequestSchema2, + GetMetaItemCachedResponseSchema: () => GetMetaItemCachedResponseSchema, + GetMetaItemRequestSchema: () => GetMetaItemRequestSchema2, + GetMetaItemResponseSchema: () => GetMetaItemResponseSchema2, + GetMetaItemsRequestSchema: () => GetMetaItemsRequestSchema2, + GetMetaItemsResponseSchema: () => GetMetaItemsResponseSchema2, + GetMetaTypesRequestSchema: () => GetMetaTypesRequestSchema2, + GetMetaTypesResponseSchema: () => GetMetaTypesResponseSchema2, + GetNotificationPreferencesRequestSchema: () => GetNotificationPreferencesRequestSchema2, + GetNotificationPreferencesResponseSchema: () => GetNotificationPreferencesResponseSchema2, + GetObjectPermissionsRequestSchema: () => GetObjectPermissionsRequestSchema2, + GetObjectPermissionsResponseSchema: () => GetObjectPermissionsResponseSchema2, + GetPackageRequestSchema: () => GetPackageRequestSchema3, + GetPackageResponseSchema: () => GetPackageResponseSchema3, + GetPresenceRequestSchema: () => GetPresenceRequestSchema2, + GetPresenceResponseSchema: () => GetPresenceResponseSchema2, + GetPresignedUrlRequestSchema: () => GetPresignedUrlRequestSchema2, + GetRunRequestSchema: () => GetRunRequestSchema, + GetRunResponseSchema: () => GetRunResponseSchema2, + GetTranslationsRequestSchema: () => GetTranslationsRequestSchema2, + GetTranslationsResponseSchema: () => GetTranslationsResponseSchema2, + GetUiViewRequestSchema: () => GetUiViewRequestSchema2, + GetUiViewResponseSchema: () => GetUiViewResponseSchema, + GetViewRequestSchema: () => GetViewRequestSchema2, + GetViewResponseSchema: () => GetViewResponseSchema2, + GetWorkflowConfigRequestSchema: () => GetWorkflowConfigRequestSchema2, + GetWorkflowConfigResponseSchema: () => GetWorkflowConfigResponseSchema2, + GetWorkflowStateRequestSchema: () => GetWorkflowStateRequestSchema2, + GetWorkflowStateResponseSchema: () => GetWorkflowStateResponseSchema2, + GraphQLConfig: () => GraphQLConfig2, + GraphQLConfigSchema: () => GraphQLConfigSchema2, + GraphQLDataLoaderConfigSchema: () => GraphQLDataLoaderConfigSchema2, + GraphQLDirectiveConfigSchema: () => GraphQLDirectiveConfigSchema2, + GraphQLDirectiveLocation: () => GraphQLDirectiveLocation2, + GraphQLMutationConfigSchema: () => GraphQLMutationConfigSchema2, + GraphQLPersistedQuerySchema: () => GraphQLPersistedQuerySchema2, + GraphQLQueryAdapterSchema: () => GraphQLQueryAdapterSchema2, + GraphQLQueryComplexitySchema: () => GraphQLQueryComplexitySchema2, + GraphQLQueryConfigSchema: () => GraphQLQueryConfigSchema2, + GraphQLQueryDepthLimitSchema: () => GraphQLQueryDepthLimitSchema2, + GraphQLRateLimitSchema: () => GraphQLRateLimitSchema2, + GraphQLResolverConfigSchema: () => GraphQLResolverConfigSchema2, + GraphQLScalarType: () => GraphQLScalarType2, + GraphQLSubscriptionConfigSchema: () => GraphQLSubscriptionConfigSchema2, + GraphQLTypeConfigSchema: () => GraphQLTypeConfigSchema2, + HandlerStatusSchema: () => HandlerStatusSchema2, + HttpFindQueryParamsSchema: () => HttpFindQueryParamsSchema2, + HttpMethod: () => HttpMethod5, + HttpStatusCode: () => HttpStatusCode2, + IdRequestSchema: () => IdRequestSchema2, + ImportValidationConfigSchema: () => ImportValidationConfigSchema2, + ImportValidationMode: () => ImportValidationMode2, + ImportValidationResultSchema: () => ImportValidationResultSchema2, + InitiateChunkedUploadRequestSchema: () => InitiateChunkedUploadRequestSchema2, + InitiateChunkedUploadResponseSchema: () => InitiateChunkedUploadResponseSchema2, + InstallPackageRequestSchema: () => InstallPackageRequestSchema3, + InstallPackageResponseSchema: () => InstallPackageResponseSchema3, + ListExportJobsRequestSchema: () => ListExportJobsRequestSchema2, + ListExportJobsResponseSchema: () => ListExportJobsResponseSchema2, + ListFlowsRequestSchema: () => ListFlowsRequestSchema2, + ListFlowsResponseSchema: () => ListFlowsResponseSchema2, + ListInstalledPackagesRequestSchema: () => ListInstalledPackagesRequestSchema2, + ListInstalledPackagesResponseSchema: () => ListInstalledPackagesResponseSchema2, + ListNotificationsRequestSchema: () => ListNotificationsRequestSchema2, + ListNotificationsResponseSchema: () => ListNotificationsResponseSchema2, + ListPackagesRequestSchema: () => ListPackagesRequestSchema3, + ListPackagesResponseSchema: () => ListPackagesResponseSchema3, + ListRecordResponseSchema: () => ListRecordResponseSchema2, + ListRunsRequestSchema: () => ListRunsRequestSchema2, + ListRunsResponseSchema: () => ListRunsResponseSchema2, + ListViewsRequestSchema: () => ListViewsRequestSchema2, + ListViewsResponseSchema: () => ListViewsResponseSchema2, + LoginRequestSchema: () => LoginRequestSchema2, + LoginType: () => LoginType2, + MarkAllNotificationsReadRequestSchema: () => MarkAllNotificationsReadRequestSchema2, + MarkAllNotificationsReadResponseSchema: () => MarkAllNotificationsReadResponseSchema2, + MarkNotificationsReadRequestSchema: () => MarkNotificationsReadRequestSchema2, + MarkNotificationsReadResponseSchema: () => MarkNotificationsReadResponseSchema2, + MetadataBulkRegisterRequestSchema: () => MetadataBulkRegisterRequestSchema22, + MetadataBulkResponseSchema: () => MetadataBulkResponseSchema2, + MetadataBulkUnregisterRequestSchema: () => MetadataBulkUnregisterRequestSchema2, + MetadataCacheApi: () => MetadataCacheApi, + MetadataCacheRequestSchema: () => MetadataCacheRequestSchema2, + MetadataCacheResponseSchema: () => MetadataCacheResponseSchema2, + MetadataDeleteResponseSchema: () => MetadataDeleteResponseSchema2, + MetadataDependenciesResponseSchema: () => MetadataDependenciesResponseSchema2, + MetadataDependentsResponseSchema: () => MetadataDependentsResponseSchema2, + MetadataEffectiveResponseSchema: () => MetadataEffectiveResponseSchema2, + MetadataEndpointsConfigSchema: () => MetadataEndpointsConfigSchema2, + MetadataEventSchema: () => MetadataEventSchema22, + MetadataEventType: () => MetadataEventType2, + MetadataExistsResponseSchema: () => MetadataExistsResponseSchema2, + MetadataExportRequestSchema: () => MetadataExportRequestSchema2, + MetadataExportResponseSchema: () => MetadataExportResponseSchema2, + MetadataImportRequestSchema: () => MetadataImportRequestSchema2, + MetadataImportResponseSchema: () => MetadataImportResponseSchema2, + MetadataItemResponseSchema: () => MetadataItemResponseSchema2, + MetadataListResponseSchema: () => MetadataListResponseSchema2, + MetadataNamesResponseSchema: () => MetadataNamesResponseSchema2, + MetadataOverlayResponseSchema: () => MetadataOverlayResponseSchema2, + MetadataOverlaySaveRequestSchema: () => MetadataOverlaySaveRequestSchema2, + MetadataQueryRequestSchema: () => MetadataQueryRequestSchema2, + MetadataQueryResponseSchema: () => MetadataQueryResponseSchema2, + MetadataRegisterRequestSchema: () => MetadataRegisterRequestSchema2, + MetadataTypeInfoResponseSchema: () => MetadataTypeInfoResponseSchema2, + MetadataTypesResponseSchema: () => MetadataTypesResponseSchema2, + MetadataValidateRequestSchema: () => MetadataValidateRequestSchema2, + MetadataValidateResponseSchema: () => MetadataValidateResponseSchema2, + ModificationResultSchema: () => ModificationResultSchema2, + NotificationPreferencesSchema: () => NotificationPreferencesSchema2, + NotificationSchema: () => NotificationSchema22, + OData: () => OData, + ODataConfigSchema: () => ODataConfigSchema2, + ODataErrorSchema: () => ODataErrorSchema2, + ODataFilterFunctionSchema: () => ODataFilterFunctionSchema2, + ODataFilterOperatorSchema: () => ODataFilterOperatorSchema2, + ODataMetadataSchema: () => ODataMetadataSchema2, + ODataQueryAdapterSchema: () => ODataQueryAdapterSchema2, + ODataQuerySchema: () => ODataQuerySchema2, + ODataResponseSchema: () => ODataResponseSchema2, + ObjectDefinitionResponseSchema: () => ObjectDefinitionResponseSchema2, + ObjectQLReferenceSchema: () => ObjectQLReferenceSchema2, + ObjectStackProtocolSchema: () => ObjectStackProtocolSchema2, + OpenApi31ExtensionsSchema: () => OpenApi31ExtensionsSchema2, + OpenApiGenerationConfigSchema: () => OpenApiGenerationConfigSchema2, + OpenApiSecuritySchemeSchema: () => OpenApiSecuritySchemeSchema2, + OpenApiServerSchema: () => OpenApiServerSchema2, + OpenApiSpec: () => OpenApiSpec2, + OpenApiSpecSchema: () => OpenApiSpecSchema2, + OperatorMappingSchema: () => OperatorMappingSchema2, + PackageApiContracts: () => PackageApiContracts, + PackageApiErrorCode: () => PackageApiErrorCode2, + PackageInstallRequestSchema: () => PackageInstallRequestSchema2, + PackageInstallResponseSchema: () => PackageInstallResponseSchema2, + PackagePathParamsSchema: () => PackagePathParamsSchema2, + PackageRollbackRequestSchema: () => PackageRollbackRequestSchema2, + PackageRollbackResponseSchema: () => PackageRollbackResponseSchema2, + PackageUpgradeRequestSchema: () => PackageUpgradeRequestSchema2, + PackageUpgradeResponseSchema: () => PackageUpgradeResponseSchema2, + PinFeedItemRequestSchema: () => PinFeedItemRequestSchema, + PinFeedItemResponseSchema: () => PinFeedItemResponseSchema2, + PingMessageSchema: () => PingMessageSchema2, + PongMessageSchema: () => PongMessageSchema2, + PresenceMessageSchema: () => PresenceMessageSchema2, + PresenceStateSchema: () => PresenceStateSchema2, + PresenceStatus: () => PresenceStatus2, + PresenceUpdateSchema: () => PresenceUpdateSchema2, + PresignedUrlResponseSchema: () => PresignedUrlResponseSchema2, + QueryAdapterConfigSchema: () => QueryAdapterConfigSchema2, + QueryAdapterTargetSchema: () => QueryAdapterTargetSchema2, + QueryOptimizationConfigSchema: () => QueryOptimizationConfigSchema2, + RealtimeConfigSchema: () => RealtimeConfigSchema2, + RealtimeConnectRequestSchema: () => RealtimeConnectRequestSchema2, + RealtimeConnectResponseSchema: () => RealtimeConnectResponseSchema2, + RealtimeDisconnectRequestSchema: () => RealtimeDisconnectRequestSchema2, + RealtimeDisconnectResponseSchema: () => RealtimeDisconnectResponseSchema2, + RealtimeEventSchema: () => RealtimeEventSchema2, + RealtimeEventType: () => RealtimeEventType2, + RealtimePresenceSchema: () => RealtimePresenceSchema2, + RealtimeRecordAction: () => RealtimeRecordAction2, + RealtimeSubscribeRequestSchema: () => RealtimeSubscribeRequestSchema2, + RealtimeSubscribeResponseSchema: () => RealtimeSubscribeResponseSchema2, + RealtimeUnsubscribeRequestSchema: () => RealtimeUnsubscribeRequestSchema2, + RealtimeUnsubscribeResponseSchema: () => RealtimeUnsubscribeResponseSchema2, + RecordDataSchema: () => RecordDataSchema2, + RefreshTokenRequestSchema: () => RefreshTokenRequestSchema2, + RegisterDeviceRequestSchema: () => RegisterDeviceRequestSchema2, + RegisterDeviceResponseSchema: () => RegisterDeviceResponseSchema2, + RegisterRequestSchema: () => RegisterRequestSchema2, + RemoveReactionRequestSchema: () => RemoveReactionRequestSchema2, + RemoveReactionResponseSchema: () => RemoveReactionResponseSchema2, + RequestValidationConfigSchema: () => RequestValidationConfigSchema2, + ResolveDependenciesRequestSchema: () => ResolveDependenciesRequestSchema2, + ResolveDependenciesResponseSchema: () => ResolveDependenciesResponseSchema2, + ResponseEnvelopeConfigSchema: () => ResponseEnvelopeConfigSchema2, + RestApiConfig: () => RestApiConfig2, + RestApiConfigSchema: () => RestApiConfigSchema2, + RestApiEndpointSchema: () => RestApiEndpointSchema2, + RestApiPluginConfig: () => RestApiPluginConfig2, + RestApiPluginConfigSchema: () => RestApiPluginConfigSchema2, + RestApiRouteCategory: () => RestApiRouteCategory2, + RestApiRouteRegistration: () => RestApiRouteRegistration2, + RestApiRouteRegistrationSchema: () => RestApiRouteRegistrationSchema2, + RestQueryAdapterSchema: () => RestQueryAdapterSchema2, + RestServerConfig: () => RestServerConfig2, + RestServerConfigSchema: () => RestServerConfigSchema2, + RetryStrategy: () => RetryStrategy2, + RouteCategory: () => RouteCategory2, + RouteCoverageEntrySchema: () => RouteCoverageEntrySchema2, + RouteCoverageReportSchema: () => RouteCoverageReportSchema2, + RouteDefinitionSchema: () => RouteDefinitionSchema2, + RouteGenerationConfigSchema: () => RouteGenerationConfigSchema2, + RouteHealthEntrySchema: () => RouteHealthEntrySchema2, + RouteHealthReportSchema: () => RouteHealthReportSchema2, + RouterConfigSchema: () => RouterConfigSchema2, + SaveMetaItemRequestSchema: () => SaveMetaItemRequestSchema2, + SaveMetaItemResponseSchema: () => SaveMetaItemResponseSchema2, + ScheduleExportRequestSchema: () => ScheduleExportRequestSchema2, + ScheduleExportResponseSchema: () => ScheduleExportResponseSchema2, + ScheduledExportSchema: () => ScheduledExportSchema2, + SchemaDefinition: () => SchemaDefinition2, + SearchFeedRequestSchema: () => SearchFeedRequestSchema2, + SearchFeedResponseSchema: () => SearchFeedResponseSchema2, + ServiceInfoSchema: () => ServiceInfoSchema2, + ServiceStatus: () => ServiceStatus2, + SessionResponseSchema: () => SessionResponseSchema2, + SessionSchema: () => SessionSchema22, + SessionUserSchema: () => SessionUserSchema2, + SetPresenceRequestSchema: () => SetPresenceRequestSchema2, + SetPresenceResponseSchema: () => SetPresenceResponseSchema2, + SimpleCursorPositionSchema: () => SimpleCursorPositionSchema2, + SimplePresenceStateSchema: () => SimplePresenceStateSchema2, + SingleRecordResponseSchema: () => SingleRecordResponseSchema2, + StandardApiContracts: () => StandardApiContracts2, + StandardErrorCode: () => StandardErrorCode2, + StarFeedItemRequestSchema: () => StarFeedItemRequestSchema, + StarFeedItemResponseSchema: () => StarFeedItemResponseSchema2, + StorageApiContracts: () => StorageApiContracts, + SubgraphConfigSchema: () => SubgraphConfigSchema2, + SubscribeMessageSchema: () => SubscribeMessageSchema2, + SubscribeRequestSchema: () => SubscribeRequestSchema2, + SubscribeResponseSchema: () => SubscribeResponseSchema2, + SubscriptionEventSchema: () => SubscriptionEventSchema2, + SubscriptionSchema: () => SubscriptionSchema2, + ToggleFlowRequestSchema: () => ToggleFlowRequestSchema2, + ToggleFlowResponseSchema: () => ToggleFlowResponseSchema2, + TransportProtocol: () => TransportProtocol2, + TriggerFlowRequestSchema: () => TriggerFlowRequestSchema2, + TriggerFlowResponseSchema: () => TriggerFlowResponseSchema2, + UninstallPackageApiRequestSchema: () => UninstallPackageApiRequestSchema, + UninstallPackageApiResponseSchema: () => UninstallPackageApiResponseSchema2, + UninstallPackageRequestSchema: () => UninstallPackageRequestSchema3, + UninstallPackageResponseSchema: () => UninstallPackageResponseSchema3, + UnpinFeedItemRequestSchema: () => UnpinFeedItemRequestSchema, + UnpinFeedItemResponseSchema: () => UnpinFeedItemResponseSchema2, + UnregisterDeviceRequestSchema: () => UnregisterDeviceRequestSchema2, + UnregisterDeviceResponseSchema: () => UnregisterDeviceResponseSchema2, + UnstarFeedItemRequestSchema: () => UnstarFeedItemRequestSchema, + UnstarFeedItemResponseSchema: () => UnstarFeedItemResponseSchema2, + UnsubscribeMessageSchema: () => UnsubscribeMessageSchema2, + UnsubscribeRequestSchema: () => UnsubscribeRequestSchema2, + UnsubscribeResponseSchema: () => UnsubscribeResponseSchema2, + UpdateDataRequestSchema: () => UpdateDataRequestSchema2, + UpdateDataResponseSchema: () => UpdateDataResponseSchema2, + UpdateFeedItemRequestSchema: () => UpdateFeedItemRequestSchema2, + UpdateFeedItemResponseSchema: () => UpdateFeedItemResponseSchema2, + UpdateFlowRequestSchema: () => UpdateFlowRequestSchema2, + UpdateFlowResponseSchema: () => UpdateFlowResponseSchema2, + UpdateManyDataRequestSchema: () => UpdateManyDataRequestSchema2, + UpdateManyDataResponseSchema: () => UpdateManyDataResponseSchema, + UpdateManyRequestSchema: () => UpdateManyRequestSchema2, + UpdateNotificationPreferencesRequestSchema: () => UpdateNotificationPreferencesRequestSchema2, + UpdateNotificationPreferencesResponseSchema: () => UpdateNotificationPreferencesResponseSchema2, + UpdateRequestSchema: () => UpdateRequestSchema2, + UpdateViewRequestSchema: () => UpdateViewRequestSchema2, + UpdateViewResponseSchema: () => UpdateViewResponseSchema2, + UploadArtifactRequestSchema: () => UploadArtifactRequestSchema2, + UploadArtifactResponseSchema: () => UploadArtifactResponseSchema2, + UploadChunkRequestSchema: () => UploadChunkRequestSchema2, + UploadChunkResponseSchema: () => UploadChunkResponseSchema2, + UploadProgressSchema: () => UploadProgressSchema2, + UserProfileResponseSchema: () => UserProfileResponseSchema2, + ValidationMode: () => ValidationMode2, + VersionDefinitionSchema: () => VersionDefinitionSchema2, + VersionNegotiationResponseSchema: () => VersionNegotiationResponseSchema2, + VersionStatus: () => VersionStatus2, + VersioningConfigSchema: () => VersioningConfigSchema23, + VersioningStrategy: () => VersioningStrategy2, + WebSocketConfigSchema: () => WebSocketConfigSchema2, + WebSocketEventSchema: () => WebSocketEventSchema2, + WebSocketMessageSchema: () => WebSocketMessageSchema2, + WebSocketMessageType: () => WebSocketMessageType2, + WebSocketPresenceStatus: () => WebSocketPresenceStatus2, + WebSocketServerConfigSchema: () => WebSocketServerConfigSchema2, + WebhookConfigSchema: () => WebhookConfigSchema2, + WebhookEventSchema: () => WebhookEventSchema2, + WellKnownCapabilitiesSchema: () => WellKnownCapabilitiesSchema2, + WorkflowApproveRequestSchema: () => WorkflowApproveRequestSchema2, + WorkflowApproveResponseSchema: () => WorkflowApproveResponseSchema2, + WorkflowRejectRequestSchema: () => WorkflowRejectRequestSchema2, + WorkflowRejectResponseSchema: () => WorkflowRejectResponseSchema2, + WorkflowStateSchema: () => WorkflowStateSchema2, + WorkflowTransitionRequestSchema: () => WorkflowTransitionRequestSchema2, + WorkflowTransitionResponseSchema: () => WorkflowTransitionResponseSchema2, + getAuthEndpointUrl: () => getAuthEndpointUrl, + getDefaultRouteRegistrations: () => getDefaultRouteRegistrations, + mapFieldTypeToGraphQL: () => mapFieldTypeToGraphQL +}); +var ApiErrorSchema2 = external_exports.object({ + code: external_exports.string().describe("Error code (e.g. validation_error)"), + message: external_exports.string().describe("Readable error message"), + category: external_exports.string().optional().describe("Error category (e.g. validation, authorization)"), + details: external_exports.unknown().optional().describe("Additional error context (e.g. field validation errors)"), + requestId: external_exports.string().optional().describe("Request ID for tracking") +}); +var BaseResponseSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Operation success status"), + error: ApiErrorSchema2.optional().describe("Error details if success is false"), + meta: external_exports.object({ + timestamp: external_exports.string(), + duration: external_exports.number().optional(), + requestId: external_exports.string().optional(), + traceId: external_exports.string().optional() + }).optional().describe("Response metadata") +}); +var RecordDataSchema2 = external_exports.record(external_exports.string(), external_exports.unknown()).describe("Key-value map of record data"); +var CreateRequestSchema2 = external_exports.object({ + data: RecordDataSchema2.describe("Record data to insert") +}); +var UpdateRequestSchema2 = external_exports.object({ + data: RecordDataSchema2.describe("Partial record data to update") +}); +var BulkRequestSchema2 = external_exports.object({ + records: external_exports.array(RecordDataSchema2).describe("Array of records to process"), + allOrNone: external_exports.boolean().default(true).describe("If true, rollback entire transaction on any failure") +}); +var ExportRequestSchema2 = external_exports.intersection( + QuerySchema3, + external_exports.object({ + format: external_exports.enum(["csv", "json", "xlsx"]).default("csv") + }) +); +var SingleRecordResponseSchema2 = BaseResponseSchema2.extend({ + data: RecordDataSchema2.describe("The requested or modified record") +}); +var ListRecordResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.array(RecordDataSchema2).describe("Array of matching records"), + pagination: external_exports.object({ + total: external_exports.number().optional().describe("Total matching records count"), + limit: external_exports.number().optional().describe("Page size"), + offset: external_exports.number().optional().describe("Page offset"), + cursor: external_exports.string().optional().describe("Cursor for next page"), + nextCursor: external_exports.string().optional().describe("Next cursor for pagination"), + hasMore: external_exports.boolean().describe("Are there more pages?") + }).describe("Pagination info") +}); +var IdRequestSchema2 = external_exports.object({ + id: external_exports.string().describe("Record ID") +}); +var ModificationResultSchema2 = external_exports.object({ + id: external_exports.string().optional().describe("Record ID if processed"), + success: external_exports.boolean(), + errors: external_exports.array(ApiErrorSchema2).optional(), + index: external_exports.number().optional().describe("Index in original request"), + data: external_exports.unknown().optional().describe("Result data (e.g. created record)") +}); +var BulkResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.array(ModificationResultSchema2).describe("Results for each item in the batch") +}); +var DeleteResponseSchema2 = BaseResponseSchema2.extend({ + id: external_exports.string().describe("ID of the deleted record") +}); +var StandardApiContracts2 = { + create: { + input: CreateRequestSchema2, + output: SingleRecordResponseSchema2 + }, + delete: { + input: IdRequestSchema2, + output: DeleteResponseSchema2 + }, + get: { + input: IdRequestSchema2, + output: SingleRecordResponseSchema2 + }, + update: { + input: UpdateRequestSchema2, + output: SingleRecordResponseSchema2 + }, + list: { + input: QuerySchema3, + output: ListRecordResponseSchema2 + }, + bulkCreate: { + input: BulkRequestSchema2, + output: BulkResponseSchema2 + }, + bulkUpdate: { + input: BulkRequestSchema2, + output: BulkResponseSchema2 + }, + bulkUpsert: { + input: BulkRequestSchema2, + output: BulkResponseSchema2 + }, + bulkDelete: { + input: external_exports.object({ ids: external_exports.array(external_exports.string()) }), + output: BulkResponseSchema2 + } +}; +var DataLoaderConfigSchema2 = external_exports.object({ + maxBatchSize: external_exports.number().int().default(100).describe("Maximum number of keys per batch load"), + batchScheduleFn: external_exports.enum(["microtask", "timeout", "manual"]).default("microtask").describe("Scheduling strategy for collecting batch keys"), + cacheEnabled: external_exports.boolean().default(true).describe("Enable per-request result caching"), + cacheKeyFn: external_exports.string().optional().describe("Name or identifier of the cache key function"), + cacheTtl: external_exports.number().min(0).optional().describe("Cache time-to-live in seconds (0 = no expiration)"), + coalesceRequests: external_exports.boolean().default(true).describe("Deduplicate identical requests within a batch window"), + maxConcurrency: external_exports.number().int().optional().describe("Maximum parallel batch requests") +}); +var BatchLoadingStrategySchema2 = external_exports.object({ + strategy: external_exports.enum(["dataloader", "windowed", "prefetch"]).describe("Batch loading strategy type"), + windowMs: external_exports.number().optional().describe("Collection window duration in milliseconds (for windowed strategy)"), + prefetchDepth: external_exports.number().int().optional().describe("Depth of relation prefetching (for prefetch strategy)"), + associationLoading: external_exports.enum(["lazy", "eager", "batch"]).default("batch").describe("How to load related associations") +}); +var QueryOptimizationConfigSchema2 = external_exports.object({ + preventNPlusOne: external_exports.boolean().describe("Enable N+1 query detection and prevention"), + dataLoader: DataLoaderConfigSchema2.optional().describe("DataLoader batch loading configuration"), + batchStrategy: BatchLoadingStrategySchema2.optional().describe("Batch loading strategy configuration"), + maxQueryDepth: external_exports.number().int().describe("Maximum depth for nested relation queries"), + queryComplexityLimit: external_exports.number().optional().describe("Maximum allowed query complexity score"), + enableQueryPlan: external_exports.boolean().default(false).describe("Log query execution plans for debugging") +}); +var ApiMappingSchema2 = external_exports.object({ + source: external_exports.string().describe("Source field/path"), + target: external_exports.string().describe("Target field/path"), + transform: external_exports.string().optional().describe("Transformation function name") +}); +var ApiEndpointSchema2 = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique endpoint ID"), + path: external_exports.string().regex(/^\//).describe("URL Path (e.g. /api/v1/customers)"), + method: HttpMethod5.describe("HTTP Method"), + /** Documentation */ + summary: external_exports.string().optional(), + description: external_exports.string().optional(), + /** Execution Logic */ + type: external_exports.enum(["flow", "script", "object_operation", "proxy"]).describe("Implementation type"), + target: external_exports.string().describe("Target Flow ID, Script Name, or Proxy URL"), + /** Logic Config */ + objectParams: external_exports.object({ + object: external_exports.string().optional(), + operation: external_exports.enum(["find", "get", "create", "update", "delete"]).optional() + }).optional().describe("For object_operation type"), + /** Data Transformation */ + inputMapping: external_exports.array(ApiMappingSchema2).optional().describe("Map Request Body to Internal Params"), + outputMapping: external_exports.array(ApiMappingSchema2).optional().describe("Map Internal Result to Response Body"), + /** Policies */ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + rateLimit: RateLimitConfigSchema4.optional().describe("Rate limiting policy"), + cacheTtl: external_exports.number().optional().describe("Response cache TTL in seconds") +}); +var ApiEndpoint2 = Object.assign(ApiEndpointSchema2, { + create: (config4) => config4 +}); +var ServiceStatus2 = external_exports.enum([ + "available", + "registered", + "unavailable", + "degraded", + "stub" +]).describe( + "available = fully operational, registered = route declared but handler unverified, unavailable = not installed, degraded = partial, stub = placeholder that returns 501" +); +var ServiceInfoSchema2 = external_exports.object({ + /** Whether the service is enabled and available */ + enabled: external_exports.boolean(), + /** Current operational status */ + status: ServiceStatus2, + /** + * Whether the HTTP handler for this service is confirmed to be mounted. + * + * Semantics: + * - `undefined` (omitted) = handler readiness is unknown / not yet verified. + * - `true` = handler is registered in the adapter / dispatcher (safe to call). + * - `false` = route is declared but no handler exists or only a stub is present + * — requests are expected to receive 501 Not Implemented. + * + * Clients SHOULD check this flag before displaying or invoking a service endpoint and may + * distinguish between "unknown" (omitted) and "known missing" (`false`). + */ + handlerReady: external_exports.boolean().optional().describe( + "Whether the HTTP handler is confirmed to be mounted. Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501)." + ), + /** Route path (only present if enabled) */ + route: external_exports.string().optional().describe("e.g. /api/v1/analytics"), + /** Implementation provider name */ + provider: external_exports.string().optional().describe('e.g. "objectql", "plugin-redis", "driver-memory"'), + /** Service version */ + version: external_exports.string().optional().describe('Semantic version of the service implementation (e.g. "3.0.6")'), + /** Human-readable reason if unavailable */ + message: external_exports.string().optional().describe('e.g. "Install plugin-workflow to enable"'), + /** Rate limit configuration for this service */ + rateLimit: external_exports.object({ + requestsPerMinute: external_exports.number().int().optional().describe("Maximum requests per minute"), + requestsPerHour: external_exports.number().int().optional().describe("Maximum requests per hour"), + burstLimit: external_exports.number().int().optional().describe("Maximum burst request count"), + retryAfterMs: external_exports.number().int().optional().describe("Suggested retry-after delay in milliseconds when rate-limited") + }).optional().describe("Rate limit and quota info for this service") +}); +var ApiRoutesSchema2 = external_exports.object({ + /** Base URL for Object CRUD (Data Protocol) */ + data: external_exports.string().describe("e.g. /api/v1/data"), + /** Base URL for Schema Definitions (Metadata Protocol) */ + metadata: external_exports.string().describe("e.g. /api/v1/meta"), + /** Base URL for API Discovery endpoint */ + discovery: external_exports.string().optional().describe("e.g. /api/v1/discovery"), + /** Base URL for UI Configurations (Views, Menus) */ + ui: external_exports.string().optional().describe("e.g. /api/v1/ui"), + /** Base URL for Authentication (plugin-provided) */ + auth: external_exports.string().optional().describe("e.g. /api/v1/auth"), + /** Base URL for Automation (Flows/Scripts) */ + automation: external_exports.string().optional().describe("e.g. /api/v1/automation"), + /** Base URL for File/Storage operations */ + storage: external_exports.string().optional().describe("e.g. /api/v1/storage"), + /** Base URL for Analytics/BI operations */ + analytics: external_exports.string().optional().describe("e.g. /api/v1/analytics"), + /** GraphQL Endpoint (if enabled) */ + graphql: external_exports.string().optional().describe("e.g. /graphql"), + /** Base URL for Package Management */ + packages: external_exports.string().optional().describe("e.g. /api/v1/packages"), + /** Base URL for Workflow Engine */ + workflow: external_exports.string().optional().describe("e.g. /api/v1/workflow"), + /** Base URL for Realtime (WebSocket/SSE) */ + realtime: external_exports.string().optional().describe("e.g. /api/v1/realtime"), + /** Base URL for Notification Service */ + notifications: external_exports.string().optional().describe("e.g. /api/v1/notifications"), + /** Base URL for AI Engine (NLQ, Chat, Suggest) */ + ai: external_exports.string().optional().describe("e.g. /api/v1/ai"), + /** Base URL for Internationalization */ + i18n: external_exports.string().optional().describe("e.g. /api/v1/i18n"), + /** Base URL for Feed / Chatter API */ + feed: external_exports.string().optional().describe("e.g. /api/v1/feed") +}); +var DiscoverySchema2 = external_exports.object({ + /** System Identity */ + name: external_exports.string(), + version: external_exports.string(), + environment: external_exports.enum(["production", "sandbox", "development"]), + /** Dynamic Routing — convenience shortcut for client routing */ + routes: ApiRoutesSchema2, + /** Localization Info (helping frontend init i18n) */ + locale: external_exports.object({ + default: external_exports.string(), + supported: external_exports.array(external_exports.string()), + timezone: external_exports.string() + }), + /** + * Per-service status map. + * This is the **single source of truth** for service availability. + * Clients use this to determine which features are available, + * show/hide UI elements, and display appropriate messages. + */ + services: external_exports.record(external_exports.string(), ServiceInfoSchema2).describe( + "Per-service availability map keyed by CoreServiceName" + ), + /** + * Hierarchical capability descriptors. + * Declares platform features so clients can adapt UI without probing individual services. + * Each key is a capability domain (e.g., "comments", "automation", "search"), + * and its value describes what sub-features are available. + */ + capabilities: external_exports.record(external_exports.string(), external_exports.object({ + enabled: external_exports.boolean().describe("Whether this capability is available"), + features: external_exports.record(external_exports.string(), external_exports.boolean()).optional().describe("Sub-feature flags within this capability"), + description: external_exports.string().optional().describe("Human-readable capability description") + })).optional().describe("Hierarchical capability descriptors for frontend intelligent adaptation"), + /** + * Schema discovery URLs for cross-ecosystem interoperability. + */ + schemaDiscovery: external_exports.object({ + openapi: external_exports.string().optional().describe('URL to OpenAPI (Swagger) specification (e.g., "/api/v1/openapi.json")'), + graphql: external_exports.string().optional().describe('URL to GraphQL schema endpoint (e.g., "/graphql")'), + jsonSchema: external_exports.string().optional().describe("URL to JSON Schema definitions") + }).optional().describe("Schema discovery endpoints for API toolchain integration"), + /** + * Custom metadata key-value pairs for extensibility + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") +}); +var WellKnownCapabilitiesSchema2 = external_exports.object({ + /** Whether the backend supports Feed / Chatter API */ + feed: external_exports.boolean().describe("Whether the backend supports Feed / Chatter API"), + /** Whether the backend supports comments (a subset of Feed) */ + comments: external_exports.boolean().describe("Whether the backend supports comments (a subset of Feed)"), + /** Whether the backend supports Automation CRUD (flows, triggers) */ + automation: external_exports.boolean().describe("Whether the backend supports Automation CRUD (flows, triggers)"), + /** Whether the backend supports cron scheduling */ + cron: external_exports.boolean().describe("Whether the backend supports cron scheduling"), + /** Whether the backend supports full-text search */ + search: external_exports.boolean().describe("Whether the backend supports full-text search"), + /** Whether the backend supports async export */ + export: external_exports.boolean().describe("Whether the backend supports async export"), + /** Whether the backend supports chunked (multipart) uploads */ + chunkedUpload: external_exports.boolean().describe("Whether the backend supports chunked (multipart) uploads") +}).describe("Well-known capability flags for frontend intelligent adaptation"); +var RouteHealthEntrySchema2 = external_exports.object({ + /** Route path (e.g. /api/v1/analytics) */ + route: external_exports.string().describe("Route path pattern"), + /** HTTP method */ + method: HttpMethod5.describe("HTTP method (GET, POST, etc.)"), + /** Target service name */ + service: external_exports.string().describe("Target service name"), + /** Whether the route is declared in discovery */ + declared: external_exports.boolean().describe("Whether the route is declared in discovery/metadata"), + /** Whether the handler is actually registered in the adapter/dispatcher */ + handlerRegistered: external_exports.boolean().describe("Whether the HTTP handler is registered"), + /** + * Health check result: + * - `pass` – Handler exists and responds (2xx/4xx — i.e., not 404/501/503) + * - `fail` – Handler returned 501 or 503 + * - `missing` – No handler registered (404) + * - `skip` – Health check was not performed + */ + healthStatus: external_exports.enum(["pass", "fail", "missing", "skip"]).describe( + "pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked" + ), + /** Optional diagnostic message */ + message: external_exports.string().optional().describe("Diagnostic message") +}); +var RouteHealthReportSchema2 = external_exports.object({ + /** ISO 8601 timestamp of when the report was generated */ + timestamp: external_exports.string().describe("ISO 8601 timestamp of report generation"), + /** Adapter name that generated the report (e.g. "hono", "express", "nextjs") */ + adapter: external_exports.string().describe("Adapter or runtime that produced this report"), + /** Total routes declared in discovery / dispatcher table */ + totalDeclared: external_exports.number().int().describe("Total routes declared in discovery"), + /** Routes with a confirmed handler registration */ + totalRegistered: external_exports.number().int().describe("Routes with confirmed handler"), + /** Routes missing a handler */ + totalMissing: external_exports.number().int().describe("Routes missing a handler"), + /** Per-route health entries */ + routes: external_exports.array(RouteHealthEntrySchema2).describe("Per-route health entries") +}); +var MetadataEventType2 = external_exports.enum([ + "metadata.object.created", + "metadata.object.updated", + "metadata.object.deleted", + "metadata.field.created", + "metadata.field.updated", + "metadata.field.deleted", + "metadata.view.created", + "metadata.view.updated", + "metadata.view.deleted", + "metadata.app.created", + "metadata.app.updated", + "metadata.app.deleted", + "metadata.agent.created", + "metadata.agent.updated", + "metadata.agent.deleted", + "metadata.tool.created", + "metadata.tool.updated", + "metadata.tool.deleted", + "metadata.flow.created", + "metadata.flow.updated", + "metadata.flow.deleted", + "metadata.action.created", + "metadata.action.updated", + "metadata.action.deleted", + "metadata.workflow.created", + "metadata.workflow.updated", + "metadata.workflow.deleted", + "metadata.dashboard.created", + "metadata.dashboard.updated", + "metadata.dashboard.deleted", + "metadata.report.created", + "metadata.report.updated", + "metadata.report.deleted", + "metadata.role.created", + "metadata.role.updated", + "metadata.role.deleted", + "metadata.permission.created", + "metadata.permission.updated", + "metadata.permission.deleted" +]); +var DataEventType2 = external_exports.enum([ + "data.record.created", + "data.record.updated", + "data.record.deleted", + "data.field.changed" +]); +var MetadataEventSchema22 = external_exports.object({ + /** Unique event identifier */ + id: external_exports.string().uuid().describe("Unique event identifier"), + /** Event type (metadata.{type}.{action}) */ + type: MetadataEventType2.describe("Event type"), + /** Metadata type (object, view, agent, tool, etc.) */ + metadataType: external_exports.string().describe("Metadata type (object, view, agent, etc.)"), + /** Metadata item name */ + name: external_exports.string().describe("Metadata item name"), + /** Package ID (if applicable) */ + packageId: external_exports.string().optional().describe("Package ID"), + /** Full definition (only for create/update events) */ + definition: external_exports.unknown().optional().describe("Full definition (create/update only)"), + /** User who triggered the event */ + userId: external_exports.string().optional().describe("User who triggered the event"), + /** Event timestamp (ISO 8601) */ + timestamp: external_exports.string().datetime().describe("Event timestamp") +}); +var DataEventSchema2 = external_exports.object({ + /** Unique event identifier */ + id: external_exports.string().uuid().describe("Unique event identifier"), + /** Event type (data.record.{action}) */ + type: DataEventType2.describe("Event type"), + /** Object name */ + object: external_exports.string().describe("Object name"), + /** Record ID */ + recordId: external_exports.string().describe("Record ID"), + /** Changed fields (update events only) */ + changes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Changed fields"), + /** Record before update (update events only) */ + before: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Before state"), + /** Record after update (create/update events) */ + after: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("After state"), + /** User who triggered the event */ + userId: external_exports.string().optional().describe("User who triggered the event"), + /** Event timestamp (ISO 8601) */ + timestamp: external_exports.string().datetime().describe("Event timestamp") +}); +var PresenceStatus2 = external_exports.enum([ + "online", + // User is actively connected + "away", + // User is idle/inactive + "busy", + // User is busy (do not disturb) + "offline" + // User is disconnected +]); +var RealtimeRecordAction2 = external_exports.enum([ + "created", + "updated", + "deleted" +]); +var BasePresenceSchema2 = external_exports.object({ + /** User identifier */ + userId: external_exports.string().describe("User identifier"), + /** Current presence status */ + status: PresenceStatus2.describe("Current presence status"), + /** Last activity timestamp */ + lastSeen: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), + /** Custom metadata */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom presence data (e.g., current page, custom status)") +}); +var TransportProtocol2 = external_exports.enum([ + "websocket", + // Full-duplex, low latency communication + "sse", + // Server-Sent Events, unidirectional push + "polling" + // Short polling, best compatibility +]); +var RealtimeEventType2 = external_exports.enum([ + "record.created", + "record.updated", + "record.deleted", + "field.changed" +]); +var SubscriptionEventSchema2 = external_exports.object({ + type: RealtimeEventType2.describe("Type of event to subscribe to"), + object: external_exports.string().optional().describe("Object name to subscribe to"), + filters: external_exports.unknown().optional().describe("Filter conditions") +}); +var SubscriptionSchema2 = external_exports.object({ + id: external_exports.string().uuid().describe("Unique subscription identifier"), + events: external_exports.array(SubscriptionEventSchema2).describe("Array of events to subscribe to"), + transport: TransportProtocol2.describe("Transport protocol to use"), + channel: external_exports.string().optional().describe("Optional channel name for grouping subscriptions") +}); +var RealtimePresenceSchema2 = BasePresenceSchema2; +var RealtimeEventSchema2 = external_exports.object({ + id: external_exports.string().uuid().describe("Unique event identifier"), + type: external_exports.string().describe("Event type (e.g., record.created, record.updated)"), + object: external_exports.string().optional().describe("Object name the event relates to"), + action: RealtimeRecordAction2.optional().describe("Action performed"), + payload: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Event payload data"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when event occurred"), + userId: external_exports.string().optional().describe("User who triggered the event"), + sessionId: external_exports.string().optional().describe("Session identifier") +}); +var RealtimeConfigSchema2 = external_exports.object({ + /** Enable realtime sync */ + enabled: external_exports.boolean().default(true).describe("Enable realtime synchronization"), + /** Transport protocol */ + transport: TransportProtocol2.default("websocket").describe("Transport protocol"), + /** Default subscriptions */ + subscriptions: external_exports.array(SubscriptionSchema2).optional().describe("Default subscriptions") +}).passthrough(); +var WebSocketMessageType2 = external_exports.enum([ + "subscribe", + // Client subscribes to events + "unsubscribe", + // Client unsubscribes from events + "event", + // Server sends event to client + "ping", + // Keepalive ping + "pong", + // Keepalive pong response + "ack", + // Acknowledgment of message receipt + "error", + // Error message + "presence", + // Presence update (user status) + "cursor", + // Cursor position update (collaborative editing) + "edit" + // Document edit operation (collaborative editing) +]); +var FilterOperator2 = external_exports.enum([ + "eq", + // Equal + "ne", + // Not equal + "gt", + // Greater than + "gte", + // Greater than or equal + "lt", + // Less than + "lte", + // Less than or equal + "in", + // In array + "nin", + // Not in array + "contains", + // String contains + "startsWith", + // String starts with + "endsWith", + // String ends with + "exists", + // Field exists + "regex" + // Regex match +]); +var EventFilterCondition2 = external_exports.object({ + field: external_exports.string().describe('Field path to filter on (supports dot notation, e.g., "user.email")'), + operator: FilterOperator2.describe("Comparison operator"), + value: external_exports.unknown().optional().describe('Value to compare against (not needed for "exists" operator)') +}); +var EventFilterSchema2 = external_exports.object({ + conditions: external_exports.array(EventFilterCondition2).optional().describe("Array of filter conditions"), + and: external_exports.lazy(() => external_exports.array(EventFilterSchema2)).optional().describe("AND logical combination of filters"), + or: external_exports.lazy(() => external_exports.array(EventFilterSchema2)).optional().describe("OR logical combination of filters"), + not: external_exports.lazy(() => EventFilterSchema2).optional().describe("NOT logical negation of filter") +}); +var EventPatternSchema2 = external_exports.string().min(1).regex(/^[a-z*][a-z0-9_.*]*$/, { + message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., "record.*", "*.created", "user.login")' +}).describe('Event pattern (supports wildcards like "record.*" or "*.created")'); +var EventSubscriptionSchema2 = external_exports.object({ + subscriptionId: external_exports.string().uuid().describe("Unique subscription identifier"), + events: external_exports.array(EventPatternSchema2).describe('Event patterns to subscribe to (supports wildcards, e.g., "record.*", "user.created")'), + objects: external_exports.array(external_exports.string()).optional().describe('Object names to filter events by (e.g., ["account", "contact"])'), + filters: EventFilterSchema2.optional().describe("Advanced filter conditions for event payloads"), + channels: external_exports.array(external_exports.string()).optional().describe("Channel names for scoped subscriptions") +}); +var UnsubscribeRequestSchema2 = external_exports.object({ + subscriptionId: external_exports.string().uuid().describe("Subscription ID to unsubscribe from") +}); +var WebSocketPresenceStatus2 = PresenceStatus2; +var PresenceStateSchema2 = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + sessionId: external_exports.string().uuid().describe("Unique session identifier"), + status: WebSocketPresenceStatus2.describe("Current presence status"), + lastSeen: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), + currentLocation: external_exports.string().optional().describe("Current page/route user is viewing"), + device: external_exports.enum(["desktop", "mobile", "tablet", "other"]).optional().describe("Device type"), + customStatus: external_exports.string().optional().describe("Custom user status message"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom presence data") +}); +var PresenceUpdateSchema2 = external_exports.object({ + status: WebSocketPresenceStatus2.optional().describe("Updated presence status"), + currentLocation: external_exports.string().optional().describe("Updated current location"), + customStatus: external_exports.string().optional().describe("Updated custom status message"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") +}); +var CursorPositionSchema2 = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + documentId: external_exports.string().describe("Document identifier being edited"), + position: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Line number (0-indexed)"), + column: external_exports.number().int().nonnegative().describe("Column number (0-indexed)") + }).optional().describe("Cursor position in document"), + selection: external_exports.object({ + start: external_exports.object({ + line: external_exports.number().int().nonnegative(), + column: external_exports.number().int().nonnegative() + }), + end: external_exports.object({ + line: external_exports.number().int().nonnegative(), + column: external_exports.number().int().nonnegative() + }) + }).optional().describe("Selection range (if text is selected)"), + color: external_exports.string().optional().describe("Cursor color for visual representation"), + userName: external_exports.string().optional().describe("Display name of user"), + lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last cursor update") +}); +var EditOperationType2 = external_exports.enum([ + "insert", + // Insert text at position + "delete", + // Delete text from range + "replace" + // Replace text in range +]); +var EditOperationSchema2 = external_exports.object({ + operationId: external_exports.string().uuid().describe("Unique operation identifier"), + documentId: external_exports.string().describe("Document identifier"), + userId: external_exports.string().describe("User who performed the edit"), + sessionId: external_exports.string().uuid().describe("Session identifier"), + type: EditOperationType2.describe("Type of edit operation"), + position: external_exports.object({ + line: external_exports.number().int().nonnegative().describe("Line number (0-indexed)"), + column: external_exports.number().int().nonnegative().describe("Column number (0-indexed)") + }).describe("Starting position of the operation"), + endPosition: external_exports.object({ + line: external_exports.number().int().nonnegative(), + column: external_exports.number().int().nonnegative() + }).optional().describe("Ending position (for delete/replace operations)"), + content: external_exports.string().optional().describe("Content to insert/replace"), + version: external_exports.number().int().nonnegative().describe("Document version before this operation"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when operation was created"), + baseOperationId: external_exports.string().uuid().optional().describe("Previous operation ID this builds upon (for OT)") +}); +var DocumentStateSchema2 = external_exports.object({ + documentId: external_exports.string().describe("Document identifier"), + version: external_exports.number().int().nonnegative().describe("Current document version"), + content: external_exports.string().describe("Current document content"), + lastModified: external_exports.string().datetime().describe("ISO 8601 datetime of last modification"), + activeSessions: external_exports.array(external_exports.string().uuid()).describe("Active editing session IDs"), + checksum: external_exports.string().optional().describe("Content checksum for integrity verification") +}); +var BaseWebSocketMessage2 = external_exports.object({ + messageId: external_exports.string().uuid().describe("Unique message identifier"), + type: WebSocketMessageType2.describe("Message type"), + timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when message was sent") +}); +var SubscribeMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("subscribe"), + subscription: EventSubscriptionSchema2.describe("Subscription configuration") +}); +var UnsubscribeMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("unsubscribe"), + request: UnsubscribeRequestSchema2.describe("Unsubscribe request") +}); +var EventMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("event"), + subscriptionId: external_exports.string().uuid().describe("Subscription ID this event belongs to"), + eventName: EventNameSchema4.describe("Event name"), + object: external_exports.string().optional().describe("Object name the event relates to"), + payload: external_exports.unknown().describe("Event payload data"), + userId: external_exports.string().optional().describe("User who triggered the event") +}); +var PresenceMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("presence"), + presence: PresenceStateSchema2.describe("Presence state") +}); +var CursorMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("cursor"), + cursor: CursorPositionSchema2.describe("Cursor position") +}); +var EditMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("edit"), + operation: EditOperationSchema2.describe("Edit operation") +}); +var AckMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("ack"), + ackMessageId: external_exports.string().uuid().describe("ID of the message being acknowledged"), + success: external_exports.boolean().describe("Whether the operation was successful"), + error: external_exports.string().optional().describe("Error message if operation failed") +}); +var ErrorMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("error"), + code: external_exports.string().describe("Error code"), + message: external_exports.string().describe("Error message"), + details: external_exports.unknown().optional().describe("Additional error details") +}); +var PingMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("ping") +}); +var PongMessageSchema2 = BaseWebSocketMessage2.extend({ + type: external_exports.literal("pong"), + pingMessageId: external_exports.string().uuid().optional().describe("ID of ping message being responded to") +}); +var WebSocketMessageSchema2 = external_exports.discriminatedUnion("type", [ + SubscribeMessageSchema2, + UnsubscribeMessageSchema2, + EventMessageSchema2, + PresenceMessageSchema2, + CursorMessageSchema2, + EditMessageSchema2, + AckMessageSchema2, + ErrorMessageSchema2, + PingMessageSchema2, + PongMessageSchema2 +]); +var WebSocketConfigSchema2 = external_exports.object({ + url: external_exports.string().url().describe("WebSocket server URL"), + protocols: external_exports.array(external_exports.string()).optional().describe("WebSocket sub-protocols"), + reconnect: external_exports.boolean().optional().default(true).describe("Enable automatic reconnection"), + reconnectInterval: external_exports.number().int().positive().optional().default(1e3).describe("Reconnection interval in milliseconds"), + maxReconnectAttempts: external_exports.number().int().positive().optional().default(5).describe("Maximum reconnection attempts"), + pingInterval: external_exports.number().int().positive().optional().default(3e4).describe("Ping interval in milliseconds"), + timeout: external_exports.number().int().positive().optional().default(5e3).describe("Message timeout in milliseconds"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for WebSocket handshake") +}); +var WebSocketEventSchema2 = external_exports.object({ + type: external_exports.enum([ + "subscribe", + // Client subscribes to channel + "unsubscribe", + // Client unsubscribes from channel + "data-change", + // Data modification event + "presence-update", + // User presence change + "cursor-update", + // Cursor position change (collaborative editing) + "error" + // Error message + ]).describe("Event type"), + channel: external_exports.string().describe('Channel identifier (e.g., "record.account.123", "user.456")'), + payload: external_exports.unknown().describe("Event payload data"), + timestamp: external_exports.number().describe("Unix timestamp in milliseconds") +}); +var SimplePresenceStateSchema2 = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + userName: external_exports.string().describe("User display name"), + status: external_exports.enum(["online", "away", "offline"]).describe("User presence status"), + lastSeen: external_exports.number().describe("Unix timestamp of last activity in milliseconds"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional presence metadata (e.g., current page, custom status)") +}); +var SimpleCursorPositionSchema2 = external_exports.object({ + userId: external_exports.string().describe("User identifier"), + recordId: external_exports.string().describe("Record identifier being edited"), + fieldName: external_exports.string().describe("Field name being edited"), + position: external_exports.number().describe("Cursor position (character offset from start)"), + selection: external_exports.object({ + start: external_exports.number().describe("Selection start position"), + end: external_exports.number().describe("Selection end position") + }).optional().describe("Text selection range (if text is selected)") +}); +var WebSocketServerConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable WebSocket server"), + path: external_exports.string().default("/ws").describe("WebSocket endpoint path"), + heartbeatInterval: external_exports.number().default(3e4).describe("Heartbeat interval in milliseconds"), + reconnectAttempts: external_exports.number().default(5).describe("Maximum reconnection attempts for clients"), + presence: external_exports.boolean().default(false).describe("Enable presence tracking"), + cursorSharing: external_exports.boolean().default(false).describe("Enable collaborative cursor sharing") +}); +var RouteCategory2 = external_exports.enum([ + "system", + // Health, Metrics, Info (No Auth usually) + "api", + // Business Logic API (Auth required) + "auth", + // Login/Callback endpoints + "static", + // Asset serving + "webhook", + // External callbacks + "plugin" + // Plugin extensions +]); +var RouteDefinitionSchema2 = external_exports.object({ + /** + * HTTP Method + */ + method: HttpMethod5, + /** + * URL Path Pattern (supports parameters like /user/:id) + */ + path: external_exports.string().describe("URL Path pattern"), + /** + * Route Type/Category + */ + category: RouteCategory2.default("api"), + /** + * Handler Identifier + * References an internal function or plugin action ID. + */ + handler: external_exports.string().describe("Unique handler identifier"), + /** + * Route specific metadata + */ + summary: external_exports.string().optional().describe("OpenAPI summary"), + description: external_exports.string().optional().describe("OpenAPI description"), + /** + * Security constraints + */ + public: external_exports.boolean().default(false).describe("Is publicly accessible"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + /** + * Performance hints + */ + timeout: external_exports.number().int().optional().describe("Execution timeout in ms"), + rateLimit: external_exports.string().optional().describe("Rate limit policy name") +}); +var RouterConfigSchema2 = external_exports.object({ + /** + * URL Prefix for all kernel routes + */ + basePath: external_exports.string().default("/api").describe("Global API prefix"), + /** + * Standard Protocol Mounts (Relative to basePath) + */ + mounts: external_exports.object({ + data: external_exports.string().default("/data").describe("Data Protocol (CRUD)"), + metadata: external_exports.string().default("/meta").describe("Metadata Protocol (Schemas)"), + auth: external_exports.string().default("/auth").describe("Auth Protocol"), + automation: external_exports.string().default("/automation").describe("Automation Protocol"), + storage: external_exports.string().default("/storage").describe("Storage Protocol"), + analytics: external_exports.string().default("/analytics").describe("Analytics Protocol"), + graphql: external_exports.string().default("/graphql").describe("GraphQL Endpoint"), + ui: external_exports.string().default("/ui").describe("UI Metadata Protocol (Views, Layouts)"), + workflow: external_exports.string().default("/workflow").describe("Workflow Engine Protocol"), + realtime: external_exports.string().default("/realtime").describe("Realtime/WebSocket Protocol"), + notifications: external_exports.string().default("/notifications").describe("Notification Protocol"), + ai: external_exports.string().default("/ai").describe("AI Engine Protocol (NLQ, Chat, Suggest)"), + i18n: external_exports.string().default("/i18n").describe("Internationalization Protocol"), + packages: external_exports.string().default("/packages").describe("Package Management Protocol") + }).default({ + data: "/data", + metadata: "/meta", + auth: "/auth", + automation: "/automation", + storage: "/storage", + analytics: "/analytics", + graphql: "/graphql", + ui: "/ui", + workflow: "/workflow", + realtime: "/realtime", + notifications: "/notifications", + ai: "/ai", + i18n: "/i18n", + packages: "/packages" + }), + // Defaults match standardized spec + /** + * Cross-Origin Resource Sharing + */ + cors: CorsConfigSchema4.optional(), + /** + * Static asset mounts + */ + staticMounts: external_exports.array(StaticMountSchema4).optional() +}); +var ODataQuerySchema2 = external_exports.object({ + /** + * $select - Select specific fields to return + * + * Comma-separated list of field names to include in the response. + * Reduces payload size and improves performance. + * + * @example "name,email,phone" + * @example "id,customer/name" - With navigation path + */ + $select: external_exports.union([ + external_exports.string(), + // "name,email" + external_exports.array(external_exports.string()) + // ["name", "email"] + ]).optional().describe("Fields to select"), + /** + * $filter - Filter results with conditions + * + * OData filter expression using comparison operators, logical operators, + * and functions. + * + * Comparison: eq, ne, lt, le, gt, ge + * Logical: and, or, not + * Functions: contains, startswith, endswith, length, indexof, substring, etc. + * + * @example "age gt 18" + * @example "country eq 'US' and revenue gt 100000" + * @example "contains(name, 'Smith')" + * @example "startswith(email, 'admin') and isActive eq true" + */ + $filter: external_exports.string().optional().describe("Filter expression (OData filter syntax)"), + /** + * $orderby - Sort results + * + * Comma-separated list of fields with optional asc/desc. + * Default is ascending. + * + * @example "name" + * @example "revenue desc" + * @example "country asc, revenue desc" + */ + $orderby: external_exports.union([ + external_exports.string(), + // "name desc" + external_exports.array(external_exports.string()) + // ["name desc", "email asc"] + ]).optional().describe("Sort order"), + /** + * $top - Limit number of results + * + * Maximum number of results to return. + * Equivalent to SQL LIMIT or FETCH FIRST. + * + * @example 10 + * @example 100 + */ + $top: external_exports.number().int().min(0).optional().describe("Max results to return"), + /** + * $skip - Skip results for pagination + * + * Number of results to skip before returning results. + * Equivalent to SQL OFFSET. + * + * @example 20 + * @example 100 + */ + $skip: external_exports.number().int().min(0).optional().describe("Results to skip"), + /** + * $expand - Include related entities (lookup/master_detail fields) + * + * Comma-separated list of navigation properties (relationship field names) to expand. + * Loads related data in the same request by resolving lookup and master_detail fields. + * The engine replaces foreign key IDs with full related objects via batch $in queries. + * Supports nested expand via OData parenthetical syntax. + * + * Behavior: + * - Only fields with `type: 'lookup'` or `type: 'master_detail'` and a valid `reference` are expanded. + * - Fields without a schema or reference definition are silently skipped (ID returned as-is). + * - Maximum expand depth defaults to 3 (configurable via QueryAdapterConfig). + * + * @example "orders" + * @example "customer,products" + * @example "orders($select=id,total)" - With nested query options + */ + $expand: external_exports.union([ + external_exports.string(), + // "orders" + external_exports.array(external_exports.string()) + // ["orders", "customer"] + ]).optional().describe("Navigation properties to expand (lookup/master_detail fields)"), + /** + * $count - Include total count + * + * When true, includes totalResults count in response. + * Useful for pagination UI. + * + * @example true + */ + $count: external_exports.boolean().optional().describe("Include total count"), + /** + * $search - Full-text search + * + * Free-text search expression. + * Search implementation is service-specific. + * + * @example "John Smith" + * @example "urgent AND support" + */ + $search: external_exports.string().optional().describe("Search expression"), + /** + * $format - Response format + * + * Preferred response format. + * + * @example "json" + * @example "xml" + */ + $format: external_exports.enum(["json", "xml", "atom"]).optional().describe("Response format"), + /** + * $apply - Data aggregation + * + * Aggregation transformations (groupby, aggregate, etc.) + * Part of OData aggregation extension. + * + * @example "groupby((country),aggregate(revenue with sum as totalRevenue))" + */ + $apply: external_exports.string().optional().describe("Aggregation expression") +}); +var ODataFilterOperatorSchema2 = external_exports.enum([ + // Comparison Operators + "eq", + // Equal to + "ne", + // Not equal to + "lt", + // Less than + "le", + // Less than or equal to + "gt", + // Greater than + "ge", + // Greater than or equal to + // Logical Operators + "and", + // Logical AND + "or", + // Logical OR + "not", + // Logical NOT + // Grouping + "(", + // Left parenthesis + ")", + // Right parenthesis + // Other + "in", + // Value in list + "has" + // Has flag (for enum flags) +]); +var ODataFilterFunctionSchema2 = external_exports.enum([ + // String Functions + "contains", + // contains(field, 'value') + "startswith", + // startswith(field, 'value') + "endswith", + // endswith(field, 'value') + "length", + // length(field) + "indexof", + // indexof(field, 'substring') + "substring", + // substring(field, start, length) + "tolower", + // tolower(field) + "toupper", + // toupper(field) + "trim", + // trim(field) + "concat", + // concat(field1, field2) + // Date/Time Functions + "year", + // year(dateField) + "month", + // month(dateField) + "day", + // day(dateField) + "hour", + // hour(datetimeField) + "minute", + // minute(datetimeField) + "second", + // second(datetimeField) + "date", + // date(datetimeField) + "time", + // time(datetimeField) + "now", + // now() + "maxdatetime", + // maxdatetime() + "mindatetime", + // mindatetime() + // Math Functions + "round", + // round(numField) + "floor", + // floor(numField) + "ceiling", + // ceiling(numField) + // Type Functions + "cast", + // cast(field, 'Edm.String') + "isof", + // isof(field, 'Type') + // Collection Functions + "any", + // collection/any(d:d/prop eq value) + "all" + // collection/all(d:d/prop eq value) +]); +var ODataResponseSchema2 = external_exports.object({ + /** + * OData context URL + * Describes the payload structure + */ + "@odata.context": external_exports.string().url().optional().describe("Metadata context URL"), + /** + * Total count (when $count=true) + */ + "@odata.count": external_exports.number().int().optional().describe("Total results count"), + /** + * Next link for pagination + */ + "@odata.nextLink": external_exports.string().url().optional().describe("Next page URL"), + /** + * Result array + */ + value: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Results array") +}); +var ODataErrorSchema2 = external_exports.object({ + error: external_exports.object({ + /** + * Error code + */ + code: external_exports.string().describe("Error code"), + /** + * Error message + */ + message: external_exports.string().describe("Error message"), + /** + * Target of the error (field name, etc.) + */ + target: external_exports.string().optional().describe("Error target"), + /** + * Additional error details + */ + details: external_exports.array(external_exports.object({ + code: external_exports.string(), + message: external_exports.string(), + target: external_exports.string().optional() + })).optional().describe("Error details"), + /** + * Inner error for debugging + */ + innererror: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Inner error details") + }) +}); +var ODataMetadataSchema2 = external_exports.object({ + /** + * Service namespace + */ + namespace: external_exports.string().describe("Service namespace"), + /** + * Entity types to expose + */ + entityTypes: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Entity type name"), + key: external_exports.array(external_exports.string()).describe("Key fields"), + properties: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string().describe("OData type (Edm.String, Edm.Int32, etc.)"), + nullable: external_exports.boolean().default(true) + })), + navigationProperties: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string(), + partner: external_exports.string().optional() + })).optional() + })).describe("Entity types"), + /** + * Entity sets + */ + entitySets: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Entity set name"), + entityType: external_exports.string().describe("Entity type") + })).describe("Entity sets") +}); +var OData = { + /** + * Build OData query URL + */ + buildUrl: (baseUrl, query) => { + const params = new URLSearchParams(); + if (query.$select) { + params.append("$select", Array.isArray(query.$select) ? query.$select.join(",") : query.$select); + } + if (query.$filter) { + params.append("$filter", query.$filter); + } + if (query.$orderby) { + params.append("$orderby", Array.isArray(query.$orderby) ? query.$orderby.join(",") : query.$orderby); + } + if (query.$top !== void 0) { + params.append("$top", query.$top.toString()); + } + if (query.$skip !== void 0) { + params.append("$skip", query.$skip.toString()); + } + if (query.$expand) { + params.append("$expand", Array.isArray(query.$expand) ? query.$expand.join(",") : query.$expand); + } + if (query.$count !== void 0) { + params.append("$count", query.$count.toString()); + } + if (query.$search) { + params.append("$search", query.$search); + } + if (query.$format) { + params.append("$format", query.$format); + } + if (query.$apply) { + params.append("$apply", query.$apply); + } + const queryString = params.toString(); + return queryString ? `${baseUrl}?${queryString}` : baseUrl; + }, + /** + * Create a simple filter expression + */ + filter: { + eq: (field, value) => `${field} eq ${typeof value === "string" ? `'${value}'` : value}`, + ne: (field, value) => `${field} ne ${typeof value === "string" ? `'${value}'` : value}`, + gt: (field, value) => `${field} gt ${value}`, + lt: (field, value) => `${field} lt ${value}`, + contains: (field, value) => `contains(${field}, '${value}')`, + and: (...expressions) => expressions.join(" and "), + or: (...expressions) => expressions.join(" or ") + } +}; +var ODataConfigSchema2 = external_exports.object({ + /** Enable OData endpoint */ + enabled: external_exports.boolean().default(true).describe("Enable OData API"), + /** OData endpoint path */ + path: external_exports.string().default("/odata").describe("OData endpoint path"), + /** Metadata configuration */ + metadata: ODataMetadataSchema2.optional().describe("OData metadata configuration") +}).passthrough(); +var GraphQLScalarType2 = external_exports.enum([ + // Built-in GraphQL Scalars + "ID", + "String", + "Int", + "Float", + "Boolean", + // Extended Scalars (common custom types) + "DateTime", + "Date", + "Time", + "JSON", + "JSONObject", + "Upload", + "URL", + "Email", + "PhoneNumber", + "Currency", + "Decimal", + "BigInt", + "Long", + "UUID", + "Base64", + "Void" +]); +var GraphQLTypeConfigSchema2 = external_exports.object({ + /** Type name in GraphQL schema */ + name: external_exports.string().describe("GraphQL type name (PascalCase recommended)"), + /** Source Object name */ + object: external_exports.string().describe("Source ObjectQL object name"), + /** Description for GraphQL schema documentation */ + description: external_exports.string().optional().describe("Type description"), + /** Fields to include/exclude */ + fields: external_exports.object({ + /** Include only these fields (allow list) */ + include: external_exports.array(external_exports.string()).optional().describe("Fields to include"), + /** Exclude these fields (deny list) */ + exclude: external_exports.array(external_exports.string()).optional().describe("Fields to exclude (e.g., sensitive fields)"), + /** Custom field mappings */ + mappings: external_exports.record(external_exports.string(), external_exports.object({ + graphqlName: external_exports.string().optional().describe("Custom GraphQL field name"), + graphqlType: external_exports.string().optional().describe("Override GraphQL type"), + description: external_exports.string().optional().describe("Field description"), + deprecationReason: external_exports.string().optional().describe("Why field is deprecated"), + nullable: external_exports.boolean().optional().describe("Override nullable") + })).optional().describe("Field-level customizations") + }).optional().describe("Field configuration"), + /** Interfaces this type implements */ + interfaces: external_exports.array(external_exports.string()).optional().describe("GraphQL interface names"), + /** Whether this is an interface definition */ + isInterface: external_exports.boolean().optional().default(false).describe("Define as GraphQL interface"), + /** Custom directives */ + directives: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Directive name"), + args: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Directive arguments") + })).optional().describe("GraphQL directives") +}); +var GraphQLQueryConfigSchema2 = external_exports.object({ + /** Query name */ + name: external_exports.string().describe("Query field name (camelCase recommended)"), + /** Source Object */ + object: external_exports.string().describe("Source ObjectQL object name"), + /** Query type: single record or list */ + type: external_exports.enum(["get", "list", "search"]).describe("Query type"), + /** Description */ + description: external_exports.string().optional().describe("Query description"), + /** Input arguments */ + args: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.string().describe('GraphQL type (e.g., "ID!", "String", "Int")'), + description: external_exports.string().optional().describe("Argument description"), + defaultValue: external_exports.unknown().optional().describe("Default value") + })).optional().describe("Query arguments"), + /** Filtering configuration */ + filtering: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Allow filtering"), + fields: external_exports.array(external_exports.string()).optional().describe("Filterable fields"), + operators: external_exports.array(external_exports.enum([ + "eq", + "ne", + "gt", + "gte", + "lt", + "lte", + "in", + "notIn", + "contains", + "startsWith", + "endsWith", + "isNull", + "isNotNull" + ])).optional().describe("Allowed filter operators") + }).optional().describe("Filtering capabilities"), + /** Sorting configuration */ + sorting: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Allow sorting"), + fields: external_exports.array(external_exports.string()).optional().describe("Sortable fields"), + defaultSort: external_exports.object({ + field: external_exports.string(), + direction: external_exports.enum(["ASC", "DESC"]) + }).optional().describe("Default sort order") + }).optional().describe("Sorting capabilities"), + /** Pagination configuration */ + pagination: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable pagination"), + type: external_exports.enum(["offset", "cursor", "relay"]).default("offset").describe("Pagination style"), + defaultLimit: external_exports.number().int().min(1).default(20).describe("Default page size"), + maxLimit: external_exports.number().int().min(1).default(100).describe("Maximum page size"), + cursors: external_exports.object({ + field: external_exports.string().default("id").describe("Field to use for cursor pagination") + }).optional() + }).optional().describe("Pagination configuration"), + /** Field selection */ + fields: external_exports.object({ + /** Always include these fields */ + required: external_exports.array(external_exports.string()).optional().describe("Required fields (always returned)"), + /** Allow selecting these fields */ + selectable: external_exports.array(external_exports.string()).optional().describe("Selectable fields") + }).optional().describe("Field selection configuration"), + /** Authorization */ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + /** Caching */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable caching"), + ttl: external_exports.number().int().min(0).optional().describe("Cache TTL in seconds"), + key: external_exports.string().optional().describe("Cache key template") + }).optional().describe("Query caching") +}); +var GraphQLMutationConfigSchema2 = external_exports.object({ + /** Mutation name */ + name: external_exports.string().describe("Mutation field name (camelCase recommended)"), + /** Source Object */ + object: external_exports.string().describe("Source ObjectQL object name"), + /** Mutation type */ + type: external_exports.enum(["create", "update", "delete", "upsert", "custom"]).describe("Mutation type"), + /** Description */ + description: external_exports.string().optional().describe("Mutation description"), + /** Input type configuration */ + input: external_exports.object({ + /** Input type name */ + typeName: external_exports.string().optional().describe("Custom input type name"), + /** Fields to include in input */ + fields: external_exports.object({ + include: external_exports.array(external_exports.string()).optional().describe("Fields to include"), + exclude: external_exports.array(external_exports.string()).optional().describe("Fields to exclude"), + required: external_exports.array(external_exports.string()).optional().describe("Required input fields") + }).optional().describe("Input field configuration"), + /** Validation */ + validation: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable input validation"), + rules: external_exports.array(external_exports.string()).optional().describe("Custom validation rules") + }).optional().describe("Input validation") + }).optional().describe("Input configuration"), + /** Return type configuration */ + output: external_exports.object({ + /** Type of output */ + type: external_exports.enum(["object", "payload", "boolean", "custom"]).default("object").describe("Output type"), + /** Include success/error envelope */ + includeEnvelope: external_exports.boolean().optional().default(false).describe("Wrap in success/error payload"), + /** Custom output type */ + customType: external_exports.string().optional().describe("Custom output type name") + }).optional().describe("Output configuration"), + /** Transaction handling */ + transaction: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Use database transaction"), + isolationLevel: external_exports.enum(["read_uncommitted", "read_committed", "repeatable_read", "serializable"]).optional().describe("Transaction isolation level") + }).optional().describe("Transaction configuration"), + /** Authorization */ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + /** Hooks */ + hooks: external_exports.object({ + before: external_exports.array(external_exports.string()).optional().describe("Pre-mutation hooks"), + after: external_exports.array(external_exports.string()).optional().describe("Post-mutation hooks") + }).optional().describe("Lifecycle hooks") +}); +var GraphQLSubscriptionConfigSchema2 = external_exports.object({ + /** Subscription name */ + name: external_exports.string().describe("Subscription field name (camelCase recommended)"), + /** Source Object */ + object: external_exports.string().describe("Source ObjectQL object name"), + /** Subscription trigger events */ + events: external_exports.array(external_exports.enum(["created", "updated", "deleted", "custom"])).describe("Events to subscribe to"), + /** Description */ + description: external_exports.string().optional().describe("Subscription description"), + /** Filtering */ + filter: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Allow filtering subscriptions"), + fields: external_exports.array(external_exports.string()).optional().describe("Filterable fields") + }).optional().describe("Subscription filtering"), + /** Payload configuration */ + payload: external_exports.object({ + /** Include the modified entity */ + includeEntity: external_exports.boolean().default(true).describe("Include entity in payload"), + /** Include previous values (for updates) */ + includePreviousValues: external_exports.boolean().optional().default(false).describe("Include previous field values"), + /** Include mutation metadata */ + includeMeta: external_exports.boolean().optional().default(true).describe("Include metadata (timestamp, user, etc.)") + }).optional().describe("Payload configuration"), + /** Authorization */ + authRequired: external_exports.boolean().default(true).describe("Require authentication"), + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), + /** Rate limiting for subscriptions */ + rateLimit: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable rate limiting"), + maxSubscriptionsPerUser: external_exports.number().int().min(1).default(10).describe("Max concurrent subscriptions per user"), + throttleMs: external_exports.number().int().min(0).optional().describe("Throttle interval in milliseconds") + }).optional().describe("Subscription rate limiting") +}); +var GraphQLResolverConfigSchema2 = external_exports.object({ + /** Field path (e.g., "Query.users", "Mutation.createUser") */ + path: external_exports.string().describe("Resolver path (Type.field)"), + /** Resolver implementation type */ + type: external_exports.enum(["datasource", "computed", "script", "proxy"]).describe("Resolver implementation type"), + /** Implementation details */ + implementation: external_exports.object({ + /** For datasource type */ + datasource: external_exports.string().optional().describe("Datasource ID"), + query: external_exports.string().optional().describe("Query/SQL to execute"), + /** For computed type */ + expression: external_exports.string().optional().describe("Computation expression"), + dependencies: external_exports.array(external_exports.string()).optional().describe("Dependent fields"), + /** For script type */ + script: external_exports.string().optional().describe("Script ID or inline code"), + /** For proxy type */ + url: external_exports.string().optional().describe("Proxy URL"), + method: external_exports.enum(["GET", "POST", "PUT", "DELETE"]).optional().describe("HTTP method") + }).optional().describe("Implementation configuration"), + /** Caching */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable resolver caching"), + ttl: external_exports.number().int().min(0).optional().describe("Cache TTL in seconds"), + keyArgs: external_exports.array(external_exports.string()).optional().describe("Arguments to include in cache key") + }).optional().describe("Resolver caching") +}); +var GraphQLDataLoaderConfigSchema2 = external_exports.object({ + /** Loader name */ + name: external_exports.string().describe("DataLoader name"), + /** Source Object or datasource */ + source: external_exports.string().describe("Source object or datasource"), + /** Batch function configuration */ + batchFunction: external_exports.object({ + /** Type of batch operation */ + type: external_exports.enum(["findByIds", "query", "script", "custom"]).describe("Batch function type"), + /** For findByIds */ + keyField: external_exports.string().optional().describe('Field to batch on (e.g., "id")'), + /** For query */ + query: external_exports.string().optional().describe("Query template"), + /** For script */ + script: external_exports.string().optional().describe("Script ID"), + /** Maximum batch size */ + maxBatchSize: external_exports.number().int().min(1).optional().default(100).describe("Maximum batch size") + }).describe("Batch function configuration"), + /** Caching */ + cache: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable per-request caching"), + /** Cache key function */ + keyFn: external_exports.string().optional().describe("Custom cache key function") + }).optional().describe("DataLoader caching"), + /** Options */ + options: external_exports.object({ + /** Batch multiple requests in single tick */ + batch: external_exports.boolean().default(true).describe("Enable batching"), + /** Cache loaded values */ + cache: external_exports.boolean().default(true).describe("Enable caching"), + /** Maximum cache size */ + maxCacheSize: external_exports.number().int().min(0).optional().describe("Max cache entries") + }).optional().describe("DataLoader options") +}); +var GraphQLDirectiveLocation2 = external_exports.enum([ + // Executable Directive Locations + "QUERY", + "MUTATION", + "SUBSCRIPTION", + "FIELD", + "FRAGMENT_DEFINITION", + "FRAGMENT_SPREAD", + "INLINE_FRAGMENT", + "VARIABLE_DEFINITION", + // Type System Directive Locations + "SCHEMA", + "SCALAR", + "OBJECT", + "FIELD_DEFINITION", + "ARGUMENT_DEFINITION", + "INTERFACE", + "UNION", + "ENUM", + "ENUM_VALUE", + "INPUT_OBJECT", + "INPUT_FIELD_DEFINITION" +]); +var GraphQLDirectiveConfigSchema2 = external_exports.object({ + /** Directive name */ + name: external_exports.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe("Directive name (camelCase)"), + /** Description */ + description: external_exports.string().optional().describe("Directive description"), + /** Where directive can be used */ + locations: external_exports.array(GraphQLDirectiveLocation2).describe("Directive locations"), + /** Arguments */ + args: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.string().describe("Argument type"), + description: external_exports.string().optional().describe("Argument description"), + defaultValue: external_exports.unknown().optional().describe("Default value") + })).optional().describe("Directive arguments"), + /** Is repeatable */ + repeatable: external_exports.boolean().optional().default(false).describe("Can be applied multiple times"), + /** Implementation */ + implementation: external_exports.object({ + /** Directive behavior type */ + type: external_exports.enum(["auth", "validation", "transform", "cache", "deprecation", "custom"]).describe("Directive type"), + /** Handler function */ + handler: external_exports.string().optional().describe("Handler function name or script") + }).optional().describe("Directive implementation") +}); +var GraphQLQueryDepthLimitSchema2 = external_exports.object({ + /** Enable depth limiting */ + enabled: external_exports.boolean().default(true).describe("Enable query depth limiting"), + /** Maximum allowed depth */ + maxDepth: external_exports.number().int().min(1).default(10).describe("Maximum query depth"), + /** Fields to ignore in depth calculation */ + ignoreFields: external_exports.array(external_exports.string()).optional().describe("Fields excluded from depth calculation"), + /** Callback on depth exceeded */ + onDepthExceeded: external_exports.enum(["reject", "log", "warn"]).default("reject").describe("Action when depth exceeded"), + /** Custom error message */ + errorMessage: external_exports.string().optional().describe("Custom error message for depth violations") +}); +var GraphQLQueryComplexitySchema2 = external_exports.object({ + /** Enable complexity limiting */ + enabled: external_exports.boolean().default(true).describe("Enable query complexity limiting"), + /** Maximum allowed complexity score */ + maxComplexity: external_exports.number().int().min(1).default(1e3).describe("Maximum query complexity"), + /** Default field complexity */ + defaultFieldComplexity: external_exports.number().int().min(0).default(1).describe("Default complexity per field"), + /** Field-specific complexity scores */ + fieldComplexity: external_exports.record(external_exports.string(), external_exports.union([ + external_exports.number().int().min(0), + external_exports.object({ + /** Base complexity */ + base: external_exports.number().int().min(0).describe("Base complexity"), + /** Multiplier based on arguments */ + multiplier: external_exports.string().optional().describe('Argument multiplier (e.g., "limit")'), + /** Custom complexity calculation */ + calculator: external_exports.string().optional().describe("Custom calculator function") + }) + ])).optional().describe("Per-field complexity configuration"), + /** List multiplier */ + listMultiplier: external_exports.number().min(0).default(10).describe("Multiplier for list fields"), + /** Callback on complexity exceeded */ + onComplexityExceeded: external_exports.enum(["reject", "log", "warn"]).default("reject").describe("Action when complexity exceeded"), + /** Custom error message */ + errorMessage: external_exports.string().optional().describe("Custom error message for complexity violations") +}); +var GraphQLRateLimitSchema2 = external_exports.object({ + /** Enable rate limiting */ + enabled: external_exports.boolean().default(true).describe("Enable rate limiting"), + /** Rate limit strategy */ + strategy: external_exports.enum(["token_bucket", "fixed_window", "sliding_window", "cost_based"]).default("token_bucket").describe("Rate limiting strategy"), + /** Global rate limits */ + global: external_exports.object({ + /** Requests per time window */ + maxRequests: external_exports.number().int().min(1).default(1e3).describe("Maximum requests per window"), + /** Time window in milliseconds */ + windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds") + }).optional().describe("Global rate limits"), + /** Per-user rate limits */ + perUser: external_exports.object({ + /** Requests per time window */ + maxRequests: external_exports.number().int().min(1).default(100).describe("Maximum requests per user per window"), + /** Time window in milliseconds */ + windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds") + }).optional().describe("Per-user rate limits"), + /** Cost-based rate limiting */ + costBased: external_exports.object({ + /** Enable cost-based limiting */ + enabled: external_exports.boolean().default(false).describe("Enable cost-based rate limiting"), + /** Maximum cost per time window */ + maxCost: external_exports.number().int().min(1).default(1e4).describe("Maximum cost per window"), + /** Time window in milliseconds */ + windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds"), + /** Use complexity as cost */ + useComplexityAsCost: external_exports.boolean().default(true).describe("Use query complexity as cost") + }).optional().describe("Cost-based rate limiting"), + /** Operation-specific limits */ + operations: external_exports.record(external_exports.string(), external_exports.object({ + maxRequests: external_exports.number().int().min(1).describe("Max requests for this operation"), + windowMs: external_exports.number().int().min(1e3).describe("Time window") + })).optional().describe("Per-operation rate limits"), + /** Callback on limit exceeded */ + onLimitExceeded: external_exports.enum(["reject", "queue", "log"]).default("reject").describe("Action when rate limit exceeded"), + /** Custom error message */ + errorMessage: external_exports.string().optional().describe("Custom error message for rate limit violations"), + /** Headers to include in response */ + includeHeaders: external_exports.boolean().default(true).describe("Include rate limit headers in response") +}); +var GraphQLPersistedQuerySchema2 = external_exports.object({ + /** Enable persisted queries */ + enabled: external_exports.boolean().default(false).describe("Enable persisted queries"), + /** Enforcement mode */ + mode: external_exports.enum(["optional", "required"]).default("optional").describe("Persisted query mode (optional: allow both, required: only persisted)"), + /** Query store configuration */ + store: external_exports.object({ + /** Store type */ + type: external_exports.enum(["memory", "redis", "database", "file"]).default("memory").describe("Query store type"), + /** Store connection string */ + connection: external_exports.string().optional().describe("Store connection string or path"), + /** TTL for cached queries */ + ttl: external_exports.number().int().min(0).optional().describe("TTL in seconds for stored queries") + }).optional().describe("Query store configuration"), + /** Automatic Persisted Queries (APQ) */ + apq: external_exports.object({ + /** Enable APQ */ + enabled: external_exports.boolean().default(true).describe("Enable Automatic Persisted Queries"), + /** Hash algorithm */ + hashAlgorithm: external_exports.enum(["sha256", "sha1", "md5"]).default("sha256").describe("Hash algorithm for query IDs"), + /** Cache control */ + cache: external_exports.object({ + /** Cache TTL */ + ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), + /** Max cache size */ + maxSize: external_exports.number().int().min(1).optional().describe("Maximum number of cached queries") + }).optional().describe("APQ cache configuration") + }).optional().describe("Automatic Persisted Queries configuration"), + /** Query allow list */ + allowlist: external_exports.object({ + /** Enable allow list mode */ + enabled: external_exports.boolean().default(false).describe("Enable query allow list (reject queries not in list)"), + /** Allowed query IDs */ + queries: external_exports.array(external_exports.object({ + id: external_exports.string().describe("Query ID or hash"), + operation: external_exports.string().optional().describe("Operation name"), + query: external_exports.string().optional().describe("Query string") + })).optional().describe("Allowed queries"), + /** External allow list source */ + source: external_exports.string().optional().describe("External allow list source (file path or URL)") + }).optional().describe("Query allow list configuration"), + /** Security */ + security: external_exports.object({ + /** Maximum query size */ + maxQuerySize: external_exports.number().int().min(1).optional().describe("Maximum query string size in bytes"), + /** Reject introspection in production */ + rejectIntrospection: external_exports.boolean().default(false).describe("Reject introspection queries") + }).optional().describe("Security configuration") +}); +var FederationEntityKeySchema2 = external_exports.object({ + /** Fields composing the key (e.g., "id" or "sku packageId") */ + fields: external_exports.string().describe("Selection set of fields composing the entity key"), + /** Whether this key can be used for resolution across subgraphs */ + resolvable: external_exports.boolean().optional().default(true).describe("Whether entities can be resolved from this subgraph") +}); +var FederationExternalFieldSchema2 = external_exports.object({ + /** Field name */ + field: external_exports.string().describe("Field name marked as external"), + /** The subgraph that owns this field */ + ownerSubgraph: external_exports.string().optional().describe("Subgraph that owns this field") +}); +var FederationRequiresSchema2 = external_exports.object({ + /** The field that has this requirement */ + field: external_exports.string().describe("Field with the requirement"), + /** Selection set of external fields required for resolution */ + fields: external_exports.string().describe('Selection set of required fields (e.g., "price weight")') +}); +var FederationProvidesSchema2 = external_exports.object({ + /** The field that provides additional data */ + field: external_exports.string().describe("Field that provides additional entity fields"), + /** Selection set of fields provided during resolution */ + fields: external_exports.string().describe('Selection set of provided fields (e.g., "name price")') +}); +var FederationEntitySchema2 = external_exports.object({ + /** Type/Object name */ + typeName: external_exports.string().describe("GraphQL type name for this entity"), + /** Entity keys (`@key` directive) */ + keys: external_exports.array(FederationEntityKeySchema2).min(1).describe("Entity key definitions"), + /** External fields (`@external`) */ + externalFields: external_exports.array(FederationExternalFieldSchema2).optional().describe("Fields owned by other subgraphs"), + /** Requires directives (`@requires`) */ + requires: external_exports.array(FederationRequiresSchema2).optional().describe("Required external fields for computed fields"), + /** Provides directives (`@provides`) */ + provides: external_exports.array(FederationProvidesSchema2).optional().describe("Fields provided during resolution"), + /** Whether this subgraph owns this entity */ + owner: external_exports.boolean().optional().default(false).describe("Whether this subgraph is the owner of this entity") +}); +var SubgraphConfigSchema2 = external_exports.object({ + /** Subgraph name */ + name: external_exports.string().describe("Unique subgraph identifier"), + /** Subgraph URL */ + url: external_exports.string().describe("Subgraph endpoint URL"), + /** Schema source */ + schemaSource: external_exports.enum(["introspection", "file", "registry"]).default("introspection").describe("How to obtain the subgraph schema"), + /** Schema file path (when schemaSource is "file") */ + schemaPath: external_exports.string().optional().describe("Path to schema file (SDL format)"), + /** Federated entities defined by this subgraph */ + entities: external_exports.array(FederationEntitySchema2).optional().describe("Entity definitions for this subgraph"), + /** Health check endpoint */ + healthCheck: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable health checking"), + path: external_exports.string().default("/health").describe("Health check endpoint path"), + intervalMs: external_exports.number().int().min(1e3).default(3e4).describe("Health check interval in milliseconds") + }).optional().describe("Subgraph health check configuration"), + /** Request headers to forward */ + forwardHeaders: external_exports.array(external_exports.string()).optional().describe("HTTP headers to forward to this subgraph") +}); +var FederationGatewaySchema2 = external_exports.object({ + /** Enable federation mode */ + enabled: external_exports.boolean().default(false).describe("Enable GraphQL Federation gateway mode"), + /** Federation specification version */ + version: external_exports.enum(["v1", "v2"]).default("v2").describe("Federation specification version"), + /** Registered subgraphs */ + subgraphs: external_exports.array(SubgraphConfigSchema2).describe("Subgraph configurations"), + /** Service discovery */ + serviceDiscovery: external_exports.object({ + /** Discovery mode */ + type: external_exports.enum(["static", "dns", "consul", "kubernetes"]).default("static").describe("Service discovery method"), + /** Poll interval for dynamic discovery */ + pollIntervalMs: external_exports.number().int().min(1e3).optional().describe("Discovery poll interval in milliseconds"), + /** Kubernetes namespace (when type is "kubernetes") */ + namespace: external_exports.string().optional().describe("Kubernetes namespace for subgraph discovery") + }).optional().describe("Service discovery configuration"), + /** Query planning */ + queryPlanning: external_exports.object({ + /** Execution strategy */ + strategy: external_exports.enum(["parallel", "sequential", "adaptive"]).default("parallel").describe("Query execution strategy across subgraphs"), + /** Maximum query depth across subgraphs */ + maxDepth: external_exports.number().int().min(1).optional().describe("Max query depth in federated execution"), + /** Dry-run mode for debugging query plans */ + dryRun: external_exports.boolean().optional().default(false).describe("Log query plans without executing") + }).optional().describe("Query planning configuration"), + /** Schema composition settings */ + composition: external_exports.object({ + /** How schema conflicts are resolved */ + conflictResolution: external_exports.enum(["error", "first_wins", "last_wins"]).default("error").describe("Strategy for resolving schema conflicts"), + /** Whether to validate composed schema */ + validate: external_exports.boolean().default(true).describe("Validate composed supergraph schema") + }).optional().describe("Schema composition configuration"), + /** Gateway-level error handling */ + errorHandling: external_exports.object({ + /** Whether to include subgraph names in errors */ + includeSubgraphName: external_exports.boolean().default(false).describe("Include subgraph name in error responses"), + /** Partial error behavior */ + partialErrors: external_exports.enum(["propagate", "nullify", "reject"]).default("propagate").describe("Behavior when a subgraph returns partial errors") + }).optional().describe("Error handling configuration") +}); +var GraphQLConfigSchema2 = external_exports.object({ + /** Enable GraphQL API */ + enabled: external_exports.boolean().default(true).describe("Enable GraphQL API"), + /** GraphQL endpoint path */ + path: external_exports.string().default("/graphql").describe("GraphQL endpoint path"), + /** GraphQL Playground */ + playground: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable GraphQL Playground"), + path: external_exports.string().default("/playground").describe("Playground path") + }).optional().describe("GraphQL Playground configuration"), + /** Schema generation */ + schema: external_exports.object({ + /** Auto-generate types from Objects */ + autoGenerateTypes: external_exports.boolean().default(true).describe("Auto-generate types from Objects"), + /** Type configurations */ + types: external_exports.array(GraphQLTypeConfigSchema2).optional().describe("Type configurations"), + /** Query configurations */ + queries: external_exports.array(GraphQLQueryConfigSchema2).optional().describe("Query configurations"), + /** Mutation configurations */ + mutations: external_exports.array(GraphQLMutationConfigSchema2).optional().describe("Mutation configurations"), + /** Subscription configurations */ + subscriptions: external_exports.array(GraphQLSubscriptionConfigSchema2).optional().describe("Subscription configurations"), + /** Custom resolvers */ + resolvers: external_exports.array(GraphQLResolverConfigSchema2).optional().describe("Custom resolver configurations"), + /** Custom directives */ + directives: external_exports.array(GraphQLDirectiveConfigSchema2).optional().describe("Custom directive configurations") + }).optional().describe("Schema generation configuration"), + /** DataLoader configurations */ + dataLoaders: external_exports.array(GraphQLDataLoaderConfigSchema2).optional().describe("DataLoader configurations"), + /** Security configuration */ + security: external_exports.object({ + /** Query depth limiting */ + depthLimit: GraphQLQueryDepthLimitSchema2.optional().describe("Query depth limiting"), + /** Query complexity */ + complexity: GraphQLQueryComplexitySchema2.optional().describe("Query complexity calculation"), + /** Rate limiting */ + rateLimit: GraphQLRateLimitSchema2.optional().describe("Rate limiting"), + /** Persisted queries */ + persistedQueries: GraphQLPersistedQuerySchema2.optional().describe("Persisted queries") + }).optional().describe("Security configuration"), + /** Federation configuration */ + federation: FederationGatewaySchema2.optional().describe("GraphQL Federation gateway configuration") +}); +var GraphQLConfig2 = Object.assign(GraphQLConfigSchema2, { + create: (config4) => config4 +}); +var mapFieldTypeToGraphQL = (fieldType) => { + const mapping = { + // Core Text + "text": "String", + "textarea": "String", + "email": "Email", + "url": "URL", + "phone": "PhoneNumber", + "password": "String", + // Rich Content + "markdown": "String", + "html": "String", + "richtext": "String", + // Numbers + "number": "Float", + "currency": "Currency", + "percent": "Float", + // Date & Time + "date": "Date", + "datetime": "DateTime", + "time": "Time", + // Logic + "boolean": "Boolean", + "toggle": "Boolean", + // Selection + "select": "String", + "multiselect": "[String]", + "radio": "String", + "checkboxes": "[String]", + // Relational + "lookup": "ID", + "master_detail": "ID", + "tree": "ID", + // Media + "image": "URL", + "file": "URL", + "avatar": "URL", + "video": "URL", + "audio": "URL", + // Calculated + "formula": "String", + "summary": "Float", + "autonumber": "String", + // Enhanced Types + "location": "JSONObject", + "address": "JSONObject", + "code": "String", + "json": "JSON", + "color": "String", + "rating": "Float", + "slider": "Float", + "signature": "String", + "qrcode": "String", + "progress": "Float", + "tags": "[String]", + // AI/ML + "vector": "[Float]" + }; + return mapping[fieldType] || "String"; +}; +var BatchOperationType2 = external_exports.enum([ + "create", + // Batch insert + "update", + // Batch update + "upsert", + // Batch upsert (insert or update based on external ID) + "delete" + // Batch delete +]); +var BatchRecordSchema2 = external_exports.object({ + id: external_exports.string().optional().describe("Record ID (required for update/delete)"), + data: RecordDataSchema2.optional().describe("Record data (required for create/update/upsert)"), + externalId: external_exports.string().optional().describe("External ID for upsert matching") +}); +var BatchOptionsSchema2 = external_exports.object({ + atomic: external_exports.boolean().optional().default(true).describe("If true, rollback entire batch on any failure (transaction mode)"), + returnRecords: external_exports.boolean().optional().default(false).describe("If true, return full record data in response"), + continueOnError: external_exports.boolean().optional().default(false).describe("If true (and atomic=false), continue processing remaining records after errors"), + validateOnly: external_exports.boolean().optional().default(false).describe("If true, validate records without persisting changes (dry-run mode)") +}); +var BatchUpdateRequestSchema2 = external_exports.object({ + operation: BatchOperationType2.describe("Type of batch operation"), + records: external_exports.array(BatchRecordSchema2).min(1).max(200).describe("Array of records to process (max 200 per batch)"), + options: BatchOptionsSchema2.optional().describe("Batch operation options") +}); +var UpdateManyRequestSchema2 = external_exports.object({ + records: external_exports.array(BatchRecordSchema2).min(1).max(200).describe("Array of records to update (max 200 per batch)"), + options: BatchOptionsSchema2.optional().describe("Update options") +}); +var BatchOperationResultSchema2 = external_exports.object({ + id: external_exports.string().optional().describe("Record ID if operation succeeded"), + success: external_exports.boolean().describe("Whether this record was processed successfully"), + errors: external_exports.array(ApiErrorSchema2).optional().describe("Array of errors if operation failed"), + data: RecordDataSchema2.optional().describe("Full record data (if returnRecords=true)"), + index: external_exports.number().optional().describe("Index of the record in the request array") +}); +var BatchUpdateResponseSchema2 = BaseResponseSchema2.extend({ + operation: BatchOperationType2.optional().describe("Operation type that was performed"), + total: external_exports.number().describe("Total number of records in the batch"), + succeeded: external_exports.number().describe("Number of records that succeeded"), + failed: external_exports.number().describe("Number of records that failed"), + results: external_exports.array(BatchOperationResultSchema2).describe("Detailed results for each record") +}); +var DeleteManyRequestSchema2 = external_exports.object({ + ids: external_exports.array(external_exports.string()).min(1).max(200).describe("Array of record IDs to delete (max 200)"), + options: BatchOptionsSchema2.optional().describe("Delete options") +}); +var BatchApiContracts = { + batchOperation: { + input: BatchUpdateRequestSchema2, + output: BatchUpdateResponseSchema2 + }, + updateMany: { + input: UpdateManyRequestSchema2, + output: BatchUpdateResponseSchema2 + }, + deleteMany: { + input: DeleteManyRequestSchema2, + output: BatchUpdateResponseSchema2 + } +}; +var BatchConfigSchema2 = external_exports.object({ + /** Enable batch operations */ + enabled: external_exports.boolean().default(true).describe("Enable batch operations"), + /** Maximum records per batch */ + maxRecordsPerBatch: external_exports.number().int().min(1).max(1e3).default(200).describe("Maximum records per batch"), + /** Default options */ + defaultOptions: BatchOptionsSchema2.optional().describe("Default batch options") +}).passthrough(); +var CacheDirective2 = external_exports.enum([ + "public", + // Cacheable by any cache + "private", + // Cacheable only by user-agent + "no-cache", + // Must revalidate with server + "no-store", + // Never cache + "must-revalidate", + // Must revalidate stale responses + "max-age" + // Maximum cache age in seconds +]); +var CacheControlSchema2 = external_exports.object({ + directives: external_exports.array(CacheDirective2).describe("Cache control directives"), + maxAge: external_exports.number().optional().describe("Maximum cache age in seconds"), + staleWhileRevalidate: external_exports.number().optional().describe("Allow serving stale content while revalidating (seconds)"), + staleIfError: external_exports.number().optional().describe("Allow serving stale content on error (seconds)") +}); +var ETagSchema2 = external_exports.object({ + value: external_exports.string().describe("ETag value (hash or version identifier)"), + weak: external_exports.boolean().optional().default(false).describe("Whether this is a weak ETag") +}); +var MetadataCacheRequestSchema2 = external_exports.object({ + ifNoneMatch: external_exports.string().optional().describe("ETag value for conditional request (If-None-Match header)"), + ifModifiedSince: external_exports.string().datetime().optional().describe("Timestamp for conditional request (If-Modified-Since header)"), + cacheControl: CacheControlSchema2.optional().describe("Client cache control preferences") +}); +var MetadataCacheResponseSchema2 = external_exports.object({ + data: external_exports.unknown().optional().describe("Metadata payload (omitted for 304 Not Modified)"), + etag: ETagSchema2.optional().describe("ETag for this resource version"), + lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), + cacheControl: CacheControlSchema2.optional().describe("Cache control directives"), + notModified: external_exports.boolean().optional().default(false).describe("True if resource has not been modified (304 response)"), + version: external_exports.string().optional().describe("Metadata version identifier") +}); +var CacheInvalidationTarget2 = external_exports.enum([ + "all", + // Invalidate all cached metadata + "object", + // Invalidate specific object metadata + "field", + // Invalidate specific field metadata + "permission", + // Invalidate permission metadata + "layout", + // Invalidate layout metadata + "custom" + // Custom invalidation pattern +]); +var CacheInvalidationRequestSchema2 = external_exports.object({ + target: CacheInvalidationTarget2.describe("What to invalidate"), + identifiers: external_exports.array(external_exports.string()).optional().describe("Specific resources to invalidate (e.g., object names)"), + cascade: external_exports.boolean().optional().default(false).describe("If true, invalidate dependent resources"), + pattern: external_exports.string().optional().describe("Pattern for custom invalidation (supports wildcards)") +}); +var CacheInvalidationResponseSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Whether invalidation succeeded"), + invalidated: external_exports.number().describe("Number of cache entries invalidated"), + targets: external_exports.array(external_exports.string()).optional().describe("List of invalidated resources") +}); +var MetadataCacheApi = { + getCached: { + input: MetadataCacheRequestSchema2, + output: MetadataCacheResponseSchema2 + }, + invalidate: { + input: CacheInvalidationRequestSchema2, + output: CacheInvalidationResponseSchema2 + } +}; +var ErrorCategory2 = external_exports.enum([ + "validation", + // Input validation errors (400) + "authentication", + // Authentication failures (401) + "authorization", + // Permission denied errors (403) + "not_found", + // Resource not found (404) + "conflict", + // Resource conflict (409) + "rate_limit", + // Rate limiting (429) + "server", + // Internal server errors (500) + "external", + // External service errors (502/503) + "maintenance" + // Planned maintenance (503) +]); +var StandardErrorCode2 = external_exports.enum([ + // Validation Errors (400) + "validation_error", + // Generic validation failure + "invalid_field", + // Invalid field value + "missing_required_field", + // Required field missing + "invalid_format", + // Field format invalid (e.g., email, date) + "value_too_long", + // Field value exceeds max length + "value_too_short", + // Field value below min length + "value_out_of_range", + // Numeric value out of range + "invalid_reference", + // Invalid foreign key reference + "duplicate_value", + // Unique constraint violation + "invalid_query", + // Malformed query syntax + "invalid_filter", + // Invalid filter expression + "invalid_sort", + // Invalid sort specification + "max_records_exceeded", + // Query would return too many records + // Authentication Errors (401) + "unauthenticated", + // No valid authentication provided + "invalid_credentials", + // Wrong username/password + "expired_token", + // Authentication token expired + "invalid_token", + // Authentication token invalid + "session_expired", + // User session expired + "mfa_required", + // Multi-factor authentication required + "email_not_verified", + // Email verification required + // Authorization Errors (403) + "permission_denied", + // User lacks required permission + "insufficient_privileges", + // Operation requires higher privileges + "field_not_accessible", + // Field-level security restriction + "record_not_accessible", + // Sharing rule restriction + "license_required", + // Feature requires license + "ip_restricted", + // IP address not allowed + "time_restricted", + // Access outside allowed time window + // Not Found Errors (404) + "resource_not_found", + // Generic resource not found + "object_not_found", + // Object/table not found + "record_not_found", + // Record with given ID not found + "field_not_found", + // Field not found in object + "endpoint_not_found", + // API endpoint not found + // Conflict Errors (409) + "resource_conflict", + // Generic resource conflict + "concurrent_modification", + // Record modified by another user + "delete_restricted", + // Cannot delete due to dependencies + "duplicate_record", + // Record already exists + "lock_conflict", + // Record is locked by another process + // Rate Limiting (429) + "rate_limit_exceeded", + // Too many requests + "quota_exceeded", + // API quota exceeded + "concurrent_limit_exceeded", + // Too many concurrent requests + // Server Errors (500) + "internal_error", + // Generic internal server error + "database_error", + // Database operation failed + "timeout", + // Operation timed out + "service_unavailable", + // Service temporarily unavailable + "not_implemented", + // Feature not yet implemented + // External Service Errors (502/503) + "external_service_error", + // External API call failed + "integration_error", + // Integration service error + "webhook_delivery_failed", + // Webhook delivery failed + // Batch Operation Errors + "batch_partial_failure", + // Batch operation partially succeeded + "batch_complete_failure", + // Batch operation completely failed + "transaction_failed" + // Transaction rolled back +]); +var ErrorHttpStatusMap = { + validation: 400, + authentication: 401, + authorization: 403, + not_found: 404, + conflict: 409, + rate_limit: 429, + server: 500, + external: 502, + maintenance: 503 +}; +var RetryStrategy2 = external_exports.enum([ + "no_retry", + // Do not retry (permanent failure) + "retry_immediate", + // Retry immediately + "retry_backoff", + // Retry with exponential backoff + "retry_after" + // Retry after specified delay +]); +var FieldErrorSchema2 = external_exports.object({ + field: external_exports.string().describe("Field path (supports dot notation)"), + code: StandardErrorCode2.describe("Error code for this field"), + message: external_exports.string().describe("Human-readable error message"), + value: external_exports.unknown().optional().describe("The invalid value that was provided"), + constraint: external_exports.unknown().optional().describe("The constraint that was violated (e.g., max length)") +}); +var EnhancedApiErrorSchema2 = external_exports.object({ + code: StandardErrorCode2.describe("Machine-readable error code"), + message: external_exports.string().describe("Human-readable error message"), + category: ErrorCategory2.optional().describe("Error category"), + httpStatus: external_exports.number().optional().describe("HTTP status code"), + retryable: external_exports.boolean().default(false).describe("Whether the request can be retried"), + retryStrategy: RetryStrategy2.optional().describe("Recommended retry strategy"), + retryAfter: external_exports.number().optional().describe("Seconds to wait before retrying"), + details: external_exports.unknown().optional().describe("Additional error context"), + fieldErrors: external_exports.array(FieldErrorSchema2).optional().describe("Field-specific validation errors"), + timestamp: external_exports.string().datetime().optional().describe("When the error occurred"), + requestId: external_exports.string().optional().describe("Request ID for tracking"), + traceId: external_exports.string().optional().describe("Distributed trace ID"), + documentation: external_exports.string().url().optional().describe("URL to error documentation"), + helpText: external_exports.string().optional().describe("Suggested actions to resolve the error") +}); +var ErrorResponseSchema2 = external_exports.object({ + success: external_exports.literal(false).describe("Always false for error responses"), + error: EnhancedApiErrorSchema2.describe("Error details"), + meta: external_exports.object({ + timestamp: external_exports.string().datetime().optional(), + requestId: external_exports.string().optional(), + traceId: external_exports.string().optional() + }).optional().describe("Response metadata") +}); +var WorkflowTriggerType2 = external_exports.enum([ + "on_create", + // When record is created + "on_update", + // When record is updated + "on_create_or_update", + // Both + "on_delete", + // When record is deleted + "schedule" + // Time-based (cron) +]); +var FieldUpdateActionSchema2 = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("field_update"), + field: external_exports.string().describe("Field to update"), + value: external_exports.unknown().describe("Value or Formula to set") +}); +var EmailAlertActionSchema2 = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("email_alert"), + template: external_exports.string().describe("Email template ID/DevName"), + recipients: external_exports.array(external_exports.string()).describe("List of recipient emails or user IDs") +}); +var ConnectorActionRefSchema2 = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("connector_action"), + connectorId: external_exports.string().describe("Target Connector ID (e.g. slack, twilio)"), + actionId: external_exports.string().describe("Target Action ID (e.g. send_message)"), + input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Input parameters matching the action schema") +}); +var HttpCallActionSchema2 = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("http_call"), + url: external_exports.string().describe("Target URL"), + method: external_exports.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).default("POST").describe("HTTP Method"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP Headers"), + body: external_exports.string().optional().describe("Request body (JSON or text)") +}); +var TaskCreationActionSchema2 = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("task_creation"), + taskObject: external_exports.string().describe('Task object name (e.g., "task", "project_task")'), + subject: external_exports.string().describe("Task subject/title"), + description: external_exports.string().optional().describe("Task description"), + assignedTo: external_exports.string().optional().describe("User ID or field reference for assignee"), + dueDate: external_exports.string().optional().describe("Due date (ISO string or formula)"), + priority: external_exports.string().optional().describe("Task priority"), + relatedTo: external_exports.string().optional().describe("Related record ID or field reference"), + additionalFields: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom fields") +}); +var PushNotificationActionSchema2 = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("push_notification"), + title: external_exports.string().describe("Notification title"), + body: external_exports.string().describe("Notification body text"), + recipients: external_exports.array(external_exports.string()).describe("User IDs or device tokens"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data payload"), + badge: external_exports.number().optional().describe("Badge count (iOS)"), + sound: external_exports.string().optional().describe("Notification sound"), + clickAction: external_exports.string().optional().describe("Action/URL when notification is clicked") +}); +var CustomScriptActionSchema2 = external_exports.object({ + name: external_exports.string().describe("Action name"), + type: external_exports.literal("custom_script"), + language: external_exports.enum(["javascript", "typescript", "python"]).default("javascript").describe("Script language"), + code: external_exports.string().describe("Script code to execute"), + timeout: external_exports.number().default(3e4).describe("Execution timeout in milliseconds"), + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context variables") +}); +var WorkflowActionSchema2 = external_exports.discriminatedUnion("type", [ + FieldUpdateActionSchema2, + EmailAlertActionSchema2, + HttpCallActionSchema2, + ConnectorActionRefSchema2, + TaskCreationActionSchema2, + PushNotificationActionSchema2, + CustomScriptActionSchema2 +]); +var TimeTriggerSchema2 = external_exports.object({ + id: external_exports.string().optional().describe("Unique identifier"), + /** Timing Logic */ + timeLength: external_exports.number().int().describe("Duration amount (e.g. 1, 30)"), + timeUnit: external_exports.enum(["minutes", "hours", "days"]).describe("Unit of time"), + /** Reference Point */ + offsetDirection: external_exports.enum(["before", "after"]).describe("Before or After the reference date"), + offsetFrom: external_exports.enum(["trigger_date", "date_field"]).describe("Basis for calculation"), + dateField: external_exports.string().optional().describe("Date field to calculate from (required if offsetFrom is date_field)"), + /** Actions */ + actions: external_exports.array(WorkflowActionSchema2).describe("Actions to execute at the scheduled time") +}); +var WorkflowRuleSchema2 = external_exports.object({ + /** Machine name */ + name: SnakeCaseIdentifierSchema7.describe("Unique workflow name (lowercase snake_case)"), + /** Target Object */ + objectName: external_exports.string().describe("Target Object"), + /** When to evaluate the rule */ + triggerType: WorkflowTriggerType2.describe("When to evaluate"), + /** + * Condition to start the workflow. + * If empty, runs on every trigger event. + */ + criteria: external_exports.string().optional().describe("Formula condition. If TRUE, actions execute."), + /** Actions to execute immediately */ + actions: external_exports.array(WorkflowActionSchema2).optional().describe("Immediate actions"), + /** + * Time-Dependent Actions + * Actions scheduled to run in the future. + */ + timeTriggers: external_exports.array(TimeTriggerSchema2).optional().describe("Scheduled actions relative to trigger or date field"), + /** Active status */ + active: external_exports.boolean().default(true).describe("Whether this workflow is active"), + /** Execution Order */ + executionOrder: external_exports.number().int().min(0).default(100).describe("Deterministic execution order when multiple workflows match (lower runs first)"), + /** Recursion Control */ + reevaluateOnChange: external_exports.boolean().default(false).describe("Re-evaluate rule if field updates change the record validity") +}); +var AutomationTriggerRequestSchema2 = external_exports.object({ + trigger: external_exports.string(), + payload: external_exports.record(external_exports.string(), external_exports.unknown()) +}); +var AutomationTriggerResponseSchema2 = external_exports.object({ + success: external_exports.boolean(), + jobId: external_exports.string().optional(), + result: external_exports.unknown().optional() +}); +var GetDiscoveryRequestSchema2 = external_exports.object({}); +var GetDiscoveryResponseSchema2 = DiscoverySchema2.partial().required({ version: true }).extend({ + /** @deprecated Use `name` instead. Kept for backward compatibility. */ + apiName: external_exports.string().optional().describe("API name (deprecated \u2014 use name)") +}); +var GetMetaTypesRequestSchema2 = external_exports.object({}); +var GetMetaTypesResponseSchema2 = external_exports.object({ + types: external_exports.array(external_exports.string()).describe('Available metadata type names (e.g., "object", "plugin", "view")') +}); +var GetMetaItemsRequestSchema2 = external_exports.object({ + type: external_exports.string().describe('Metadata type name (e.g., "object", "plugin")'), + packageId: external_exports.string().optional().describe("Optional package ID to filter items by") +}); +var GetMetaItemsResponseSchema2 = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + items: external_exports.array(external_exports.unknown()).describe("Array of metadata items") +}); +var GetMetaItemRequestSchema2 = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + name: external_exports.string().describe("Item name (snake_case identifier)"), + packageId: external_exports.string().optional().describe("Optional package ID to filter items by") +}); +var GetMetaItemResponseSchema2 = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + name: external_exports.string().describe("Item name"), + item: external_exports.unknown().describe("Metadata item definition") +}); +var SaveMetaItemRequestSchema2 = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + name: external_exports.string().describe("Item name"), + item: external_exports.unknown().describe("Metadata item definition") +}); +var SaveMetaItemResponseSchema2 = external_exports.object({ + success: external_exports.boolean(), + message: external_exports.string().optional() +}); +var GetMetaItemCachedRequestSchema2 = external_exports.object({ + type: external_exports.string().describe("Metadata type name"), + name: external_exports.string().describe("Item name"), + cacheRequest: MetadataCacheRequestSchema2.optional().describe("Cache validation parameters") +}); +var GetMetaItemCachedResponseSchema = MetadataCacheResponseSchema2; +var GetUiViewRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + type: external_exports.enum(["list", "form"]).describe("View type") +}); +var GetUiViewResponseSchema = ViewSchema3; +var FindDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe('The unique machine name of the object to query (e.g. "account").'), + query: QuerySchema3.optional().describe("Structured query definition (filter, sort, select, pagination).") +}); +var FindDataResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("The object name for the returned records."), + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("The list of matching records."), + total: external_exports.number().optional().describe("Total number of records matching the filter (if requested)."), + nextCursor: external_exports.string().optional().describe("Cursor for the next page of results (cursor-based pagination)."), + hasMore: external_exports.boolean().optional().describe("True if there are more records available (pagination).") +}); +var HttpFindQueryParamsSchema2 = external_exports.object({ + /** @canonical Singular form — the standard going forward. JSON string of filter expression or AST. */ + filter: external_exports.string().optional().describe("JSON-encoded filter expression (canonical, singular)."), + /** @deprecated Use `filter` (singular). Accepted for backward compatibility. */ + filters: external_exports.string().optional().describe("JSON-encoded filter expression (deprecated plural alias)."), + select: external_exports.string().optional().describe("Comma-separated list of fields to retrieve."), + sort: external_exports.string().optional().describe('Sort expression (e.g. "name asc,created_at desc" or "-created_at").'), + orderBy: external_exports.string().optional().describe("Alias for sort (OData compatibility)."), + top: external_exports.coerce.number().optional().describe("Max records to return (limit)."), + skip: external_exports.coerce.number().optional().describe("Records to skip (offset)."), + expand: external_exports.string().optional().describe( + "Comma-separated list of lookup/master_detail field names to expand. Resolved to populate array and passed to the engine for batch $in expansion." + ), + search: external_exports.string().optional().describe("Full-text search query."), + distinct: external_exports.coerce.boolean().optional().describe("SELECT DISTINCT flag."), + count: external_exports.coerce.boolean().optional().describe("Include total count in response.") +}); +var GetDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("The object name."), + id: external_exports.string().describe("The unique record identifier (primary key)."), + select: external_exports.array(external_exports.string()).optional().describe("Fields to include in the response (allowlisted query param)."), + expand: external_exports.array(external_exports.string()).optional().describe( + "Lookup/master_detail field names to expand. The engine resolves these via batch $in queries, replacing foreign key IDs with full objects." + ) +}); +var GetDataResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("The object name."), + id: external_exports.string().describe("The record ID."), + record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The complete record data.") +}); +var CreateDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("The object name."), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The dictionary of field values to insert.") +}); +var CreateDataResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("The object name."), + id: external_exports.string().describe("The ID of the newly created record."), + record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The created record, including server-generated fields (created_at, owner).") +}); +var UpdateDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("The object name."), + id: external_exports.string().describe("The ID of the record to update."), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The fields to update (partial update).") +}); +var UpdateDataResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + id: external_exports.string().describe("Updated record ID"), + record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Updated record") +}); +var DeleteDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + id: external_exports.string().describe("Record ID to delete") +}); +var DeleteDataResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + id: external_exports.string().describe("Deleted record ID"), + success: external_exports.boolean().describe("Whether deletion succeeded") +}); +var BatchDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + request: BatchUpdateRequestSchema2.describe("Batch operation request") +}); +var BatchDataResponseSchema = BatchUpdateResponseSchema2; +var CreateManyDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Array of records to create") +}); +var CreateManyDataResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Created records"), + count: external_exports.number().describe("Number of records created") +}); +var UpdateManyDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + records: external_exports.array(external_exports.object({ + id: external_exports.string().describe("Record ID"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Fields to update") + })).describe("Array of updates"), + options: BatchOptionsSchema2.optional().describe("Update options") +}); +var UpdateManyDataResponseSchema = BatchUpdateResponseSchema2; +var DeleteManyDataRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + ids: external_exports.array(external_exports.string()).describe("Array of record IDs to delete"), + options: BatchOptionsSchema2.optional().describe("Delete options") +}); +var DeleteManyDataResponseSchema = BatchUpdateResponseSchema2; +var ListViewsRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + type: external_exports.enum(["list", "form"]).optional().describe("Filter by view type") +}); +var ListViewsResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + views: external_exports.array(ViewSchema3).describe("Array of view definitions") +}); +var GetViewRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + viewId: external_exports.string().describe("View identifier") +}); +var GetViewResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + view: ViewSchema3.describe("View definition") +}); +var CreateViewRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + data: ViewSchema3.describe("View definition to create") +}); +var CreateViewResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + viewId: external_exports.string().describe("Created view identifier"), + view: ViewSchema3.describe("Created view definition") +}); +var UpdateViewRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + viewId: external_exports.string().describe("View identifier"), + data: ViewSchema3.partial().describe("Partial view data to update") +}); +var UpdateViewResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + viewId: external_exports.string().describe("Updated view identifier"), + view: ViewSchema3.describe("Updated view definition") +}); +var DeleteViewRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name (snake_case)"), + viewId: external_exports.string().describe("View identifier to delete") +}); +var DeleteViewResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + viewId: external_exports.string().describe("Deleted view identifier"), + success: external_exports.boolean().describe("Whether deletion succeeded") +}); +var CheckPermissionRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name to check permissions for"), + action: external_exports.enum(["create", "read", "edit", "delete", "transfer", "restore", "purge"]).describe("Action to check"), + recordId: external_exports.string().optional().describe("Specific record ID (for record-level checks)"), + field: external_exports.string().optional().describe("Specific field name (for field-level checks)") +}); +var CheckPermissionResponseSchema2 = external_exports.object({ + allowed: external_exports.boolean().describe("Whether the action is permitted"), + reason: external_exports.string().optional().describe("Reason if denied") +}); +var GetObjectPermissionsRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name to get permissions for") +}); +var GetObjectPermissionsResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + permissions: ObjectPermissionSchema2.describe("Object-level permissions"), + fieldPermissions: external_exports.record(external_exports.string(), FieldPermissionSchema2).optional().describe("Field-level permissions keyed by field name") +}); +var GetEffectivePermissionsRequestSchema2 = external_exports.object({}); +var GetEffectivePermissionsResponseSchema2 = external_exports.object({ + objects: external_exports.record(external_exports.string(), ObjectPermissionSchema2).describe("Effective object permissions keyed by object name"), + systemPermissions: external_exports.array(external_exports.string()).describe("Effective system-level permissions") +}); +var GetWorkflowConfigRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name to get workflow config for") +}); +var GetWorkflowConfigResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + workflows: external_exports.array(WorkflowRuleSchema2).describe("Active workflow rules for this object") +}); +var WorkflowStateSchema2 = external_exports.object({ + currentState: external_exports.string().describe("Current workflow state name"), + availableTransitions: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Transition name"), + targetState: external_exports.string().describe("Target state after transition"), + label: external_exports.string().optional().describe("Display label"), + requiresApproval: external_exports.boolean().default(false).describe("Whether transition requires approval") + })).describe("Available transitions from current state"), + history: external_exports.array(external_exports.object({ + fromState: external_exports.string().describe("Previous state"), + toState: external_exports.string().describe("New state"), + action: external_exports.string().describe("Action that triggered the transition"), + userId: external_exports.string().describe("User who performed the action"), + timestamp: external_exports.string().datetime().describe("When the transition occurred"), + comment: external_exports.string().optional().describe("Optional comment") + })).optional().describe("State transition history") +}); +var GetWorkflowStateRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID to get workflow state for") +}); +var GetWorkflowStateResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + state: WorkflowStateSchema2.describe("Current workflow state and available transitions") +}); +var WorkflowTransitionRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + transition: external_exports.string().describe("Transition name to execute"), + comment: external_exports.string().optional().describe("Optional comment for the transition"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data for the transition") +}); +var WorkflowTransitionResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + success: external_exports.boolean().describe("Whether the transition succeeded"), + state: WorkflowStateSchema2.describe("New workflow state after transition") +}); +var WorkflowApproveRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + comment: external_exports.string().optional().describe("Approval comment"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data") +}); +var WorkflowApproveResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + success: external_exports.boolean().describe("Whether the approval succeeded"), + state: WorkflowStateSchema2.describe("New workflow state after approval") +}); +var WorkflowRejectRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + reason: external_exports.string().describe("Rejection reason"), + comment: external_exports.string().optional().describe("Additional comment") +}); +var WorkflowRejectResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + success: external_exports.boolean().describe("Whether the rejection succeeded"), + state: WorkflowStateSchema2.describe("New workflow state after rejection") +}); +var RealtimeConnectRequestSchema2 = external_exports.object({ + transport: TransportProtocol2.optional().describe("Preferred transport protocol"), + channels: external_exports.array(external_exports.string()).optional().describe("Channels to subscribe to on connect"), + token: external_exports.string().optional().describe("Authentication token") +}); +var RealtimeConnectResponseSchema2 = external_exports.object({ + connectionId: external_exports.string().describe("Unique connection identifier"), + transport: TransportProtocol2.describe("Negotiated transport protocol"), + url: external_exports.string().optional().describe("WebSocket/SSE endpoint URL") +}); +var RealtimeDisconnectRequestSchema2 = external_exports.object({ + connectionId: external_exports.string().optional().describe("Connection ID to disconnect") +}); +var RealtimeDisconnectResponseSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Whether disconnection succeeded") +}); +var RealtimeSubscribeRequestSchema2 = external_exports.object({ + channel: external_exports.string().describe("Channel name to subscribe to"), + events: external_exports.array(external_exports.string()).optional().describe("Specific event types to listen for"), + filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event filter criteria") +}); +var RealtimeSubscribeResponseSchema2 = external_exports.object({ + subscriptionId: external_exports.string().describe("Unique subscription identifier"), + channel: external_exports.string().describe("Subscribed channel name") +}); +var RealtimeUnsubscribeRequestSchema2 = external_exports.object({ + subscriptionId: external_exports.string().describe("Subscription ID to cancel") +}); +var RealtimeUnsubscribeResponseSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Whether unsubscription succeeded") +}); +var SetPresenceRequestSchema2 = external_exports.object({ + channel: external_exports.string().describe("Channel to set presence in"), + state: RealtimePresenceSchema2.describe("Presence state to set") +}); +var SetPresenceResponseSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Whether presence was set") +}); +var GetPresenceRequestSchema2 = external_exports.object({ + channel: external_exports.string().describe("Channel to get presence for") +}); +var GetPresenceResponseSchema2 = external_exports.object({ + channel: external_exports.string().describe("Channel name"), + members: external_exports.array(RealtimePresenceSchema2).describe("Active members and their presence state") +}); +var RegisterDeviceRequestSchema2 = external_exports.object({ + token: external_exports.string().describe("Device push notification token"), + platform: external_exports.enum(["ios", "android", "web"]).describe("Device platform"), + deviceId: external_exports.string().optional().describe("Unique device identifier"), + name: external_exports.string().optional().describe("Device friendly name") +}); +var RegisterDeviceResponseSchema2 = external_exports.object({ + deviceId: external_exports.string().describe("Registered device ID"), + success: external_exports.boolean().describe("Whether registration succeeded") +}); +var UnregisterDeviceRequestSchema2 = external_exports.object({ + deviceId: external_exports.string().describe("Device ID to unregister") +}); +var UnregisterDeviceResponseSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Whether unregistration succeeded") +}); +var NotificationPreferencesSchema2 = external_exports.object({ + email: external_exports.boolean().default(true).describe("Receive email notifications"), + push: external_exports.boolean().default(true).describe("Receive push notifications"), + inApp: external_exports.boolean().default(true).describe("Receive in-app notifications"), + digest: external_exports.enum(["none", "daily", "weekly"]).default("none").describe("Email digest frequency"), + channels: external_exports.record(external_exports.string(), external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Whether this channel is enabled"), + email: external_exports.boolean().optional().describe("Override email setting"), + push: external_exports.boolean().optional().describe("Override push setting") + })).optional().describe("Per-channel notification preferences") +}); +var GetNotificationPreferencesRequestSchema2 = external_exports.object({}); +var GetNotificationPreferencesResponseSchema2 = external_exports.object({ + preferences: NotificationPreferencesSchema2.describe("Current notification preferences") +}); +var UpdateNotificationPreferencesRequestSchema2 = external_exports.object({ + preferences: NotificationPreferencesSchema2.partial().describe("Preferences to update") +}); +var UpdateNotificationPreferencesResponseSchema2 = external_exports.object({ + preferences: NotificationPreferencesSchema2.describe("Updated notification preferences") +}); +var NotificationSchema22 = external_exports.object({ + id: external_exports.string().describe("Notification ID"), + type: external_exports.string().describe("Notification type"), + title: external_exports.string().describe("Notification title"), + body: external_exports.string().describe("Notification body text"), + read: external_exports.boolean().default(false).describe("Whether notification has been read"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional notification data"), + actionUrl: external_exports.string().optional().describe("URL to navigate to when clicked"), + createdAt: external_exports.string().datetime().describe("When notification was created") +}); +var ListNotificationsRequestSchema2 = external_exports.object({ + read: external_exports.boolean().optional().describe("Filter by read status"), + type: external_exports.string().optional().describe("Filter by notification type"), + limit: external_exports.number().default(20).describe("Maximum number of notifications to return"), + cursor: external_exports.string().optional().describe("Pagination cursor") +}); +var ListNotificationsResponseSchema2 = external_exports.object({ + notifications: external_exports.array(NotificationSchema22).describe("List of notifications"), + unreadCount: external_exports.number().describe("Total number of unread notifications"), + cursor: external_exports.string().optional().describe("Next page cursor") +}); +var MarkNotificationsReadRequestSchema2 = external_exports.object({ + ids: external_exports.array(external_exports.string()).describe("Notification IDs to mark as read") +}); +var MarkNotificationsReadResponseSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Whether the operation succeeded"), + readCount: external_exports.number().describe("Number of notifications marked as read") +}); +var MarkAllNotificationsReadRequestSchema2 = external_exports.object({}); +var MarkAllNotificationsReadResponseSchema2 = external_exports.object({ + success: external_exports.boolean().describe("Whether the operation succeeded"), + readCount: external_exports.number().describe("Number of notifications marked as read") +}); +var AiNlqRequestSchema2 = external_exports.object({ + query: external_exports.string().describe("Natural language query string"), + object: external_exports.string().optional().describe("Target object context"), + conversationId: external_exports.string().optional().describe("Conversation ID for multi-turn queries") +}); +var AiNlqResponseSchema2 = external_exports.object({ + query: external_exports.unknown().describe("Generated structured query (AST)"), + explanation: external_exports.string().optional().describe("Human-readable explanation of the query"), + confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), + suggestions: external_exports.array(external_exports.string()).optional().describe("Suggested follow-up queries") +}); +var AiSuggestRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name for context"), + field: external_exports.string().optional().describe("Field to suggest values for"), + recordId: external_exports.string().optional().describe("Record ID for context"), + partial: external_exports.string().optional().describe("Partial input for completion") +}); +var AiSuggestResponseSchema2 = external_exports.object({ + suggestions: external_exports.array(external_exports.object({ + value: external_exports.unknown().describe("Suggested value"), + label: external_exports.string().describe("Display label"), + confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), + reason: external_exports.string().optional().describe("Reason for this suggestion") + })).describe("Suggested values") +}); +var AiInsightsRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name to analyze"), + recordId: external_exports.string().optional().describe("Specific record to analyze"), + type: external_exports.enum(["summary", "trends", "anomalies", "recommendations"]).optional().describe("Type of insight") +}); +var AiInsightsResponseSchema2 = external_exports.object({ + insights: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Insight type"), + title: external_exports.string().describe("Insight title"), + description: external_exports.string().describe("Detailed description"), + confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Supporting data") + })).describe("Generated insights") +}); +var GetLocalesRequestSchema2 = external_exports.object({}); +var GetLocalesResponseSchema2 = external_exports.object({ + locales: external_exports.array(external_exports.object({ + code: external_exports.string().describe("BCP-47 locale code (e.g., en-US, zh-CN)"), + label: external_exports.string().describe("Display name of the locale"), + isDefault: external_exports.boolean().default(false).describe("Whether this is the default locale") + })).describe("Available locales") +}); +var GetTranslationsRequestSchema2 = external_exports.object({ + locale: external_exports.string().describe("BCP-47 locale code"), + namespace: external_exports.string().optional().describe("Translation namespace (e.g., objects, apps, messages)"), + keys: external_exports.array(external_exports.string()).optional().describe("Specific translation keys to fetch") +}); +var GetTranslationsResponseSchema2 = external_exports.object({ + locale: external_exports.string().describe("Locale code"), + translations: TranslationDataSchema3.describe("Translation data") +}); +var GetFieldLabelsRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + locale: external_exports.string().describe("BCP-47 locale code") +}); +var GetFieldLabelsResponseSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name"), + locale: external_exports.string().describe("Locale code"), + labels: external_exports.record(external_exports.string(), external_exports.object({ + label: external_exports.string().describe("Translated field label"), + help: external_exports.string().optional().describe("Translated help text"), + options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Translated option labels") + })).describe("Field labels keyed by field name") +}); +var ObjectStackProtocolSchema2 = external_exports.object({ + // Discovery & Metadata + getDiscovery: external_exports.function().describe("Get API discovery information"), + getMetaTypes: external_exports.function().describe("Get available metadata types"), + getMetaItems: external_exports.function().describe("Get all items of a metadata type"), + getMetaItem: external_exports.function().describe("Get a specific metadata item"), + saveMetaItem: external_exports.function().describe("Save metadata item"), + getMetaItemCached: external_exports.function().describe("Get a metadata item with cache validation"), + getUiView: external_exports.function().describe("Get UI view definition"), + // Analytics Operations + analyticsQuery: external_exports.function().describe("Execute analytics query"), + getAnalyticsMeta: external_exports.function().describe("Get analytics metadata (cubes)"), + // Automation Operations + triggerAutomation: external_exports.function().describe("Trigger an automation flow or script"), + // Package Management Operations + listPackages: external_exports.function().describe("List installed packages with optional filters"), + getPackage: external_exports.function().describe("Get a specific installed package by ID"), + installPackage: external_exports.function().describe("Install a new package from manifest"), + uninstallPackage: external_exports.function().describe("Uninstall a package by ID"), + enablePackage: external_exports.function().describe("Enable a disabled package"), + disablePackage: external_exports.function().describe("Disable an installed package"), + // Data Operations + findData: external_exports.function().describe("Find data records"), + getData: external_exports.function().describe("Get single data record"), + createData: external_exports.function().describe("Create a data record"), + updateData: external_exports.function().describe("Update a data record"), + deleteData: external_exports.function().describe("Delete a data record"), + // Batch Operations + batchData: external_exports.function().describe("Perform batch operations"), + createManyData: external_exports.function().describe("Create multiple records"), + updateManyData: external_exports.function().describe("Update multiple records"), + deleteManyData: external_exports.function().describe("Delete multiple records"), + // View Management Operations + listViews: external_exports.function().describe("List views for an object"), + getView: external_exports.function().describe("Get a specific view"), + createView: external_exports.function().describe("Create a new view"), + updateView: external_exports.function().describe("Update an existing view"), + deleteView: external_exports.function().describe("Delete a view"), + // Permission Operations + checkPermission: external_exports.function().describe("Check if an action is permitted"), + getObjectPermissions: external_exports.function().describe("Get permissions for an object"), + getEffectivePermissions: external_exports.function().describe("Get effective permissions for current user"), + // Workflow Operations + getWorkflowConfig: external_exports.function().describe("Get workflow configuration for an object"), + getWorkflowState: external_exports.function().describe("Get workflow state for a record"), + workflowTransition: external_exports.function().describe("Execute a workflow state transition"), + workflowApprove: external_exports.function().describe("Approve a workflow step"), + workflowReject: external_exports.function().describe("Reject a workflow step"), + // Realtime Operations + realtimeConnect: external_exports.function().describe("Establish realtime connection"), + realtimeDisconnect: external_exports.function().describe("Close realtime connection"), + realtimeSubscribe: external_exports.function().describe("Subscribe to a realtime channel"), + realtimeUnsubscribe: external_exports.function().describe("Unsubscribe from a realtime channel"), + setPresence: external_exports.function().describe("Set user presence state"), + getPresence: external_exports.function().describe("Get channel presence information"), + // Notification Operations + registerDevice: external_exports.function().describe("Register a device for push notifications"), + unregisterDevice: external_exports.function().describe("Unregister a device"), + getNotificationPreferences: external_exports.function().describe("Get notification preferences"), + updateNotificationPreferences: external_exports.function().describe("Update notification preferences"), + listNotifications: external_exports.function().describe("List notifications"), + markNotificationsRead: external_exports.function().describe("Mark specific notifications as read"), + markAllNotificationsRead: external_exports.function().describe("Mark all notifications as read"), + // AI Operations + aiNlq: external_exports.function().describe("Natural language query"), + aiChat: external_exports.function().describe("AI chat interaction"), + aiSuggest: external_exports.function().describe("Get AI-powered suggestions"), + aiInsights: external_exports.function().describe("Get AI-generated insights"), + // i18n Operations + getLocales: external_exports.function().describe("Get available locales"), + getTranslations: external_exports.function().describe("Get translations for a locale"), + getFieldLabels: external_exports.function().describe("Get translated field labels for an object"), + // Feed Operations + listFeed: external_exports.function().describe("List feed items for a record"), + createFeedItem: external_exports.function().describe("Create a new feed item"), + updateFeedItem: external_exports.function().describe("Update an existing feed item"), + deleteFeedItem: external_exports.function().describe("Delete a feed item"), + addReaction: external_exports.function().describe("Add an emoji reaction to a feed item"), + removeReaction: external_exports.function().describe("Remove an emoji reaction from a feed item"), + pinFeedItem: external_exports.function().describe("Pin a feed item"), + unpinFeedItem: external_exports.function().describe("Unpin a feed item"), + starFeedItem: external_exports.function().describe("Star a feed item"), + unstarFeedItem: external_exports.function().describe("Unstar a feed item"), + searchFeed: external_exports.function().describe("Search feed items"), + getChangelog: external_exports.function().describe("Get field-level changelog for a record"), + feedSubscribe: external_exports.function().describe("Subscribe to record notifications"), + feedUnsubscribe: external_exports.function().describe("Unsubscribe from record notifications") +}); +var RestApiConfigSchema2 = external_exports.object({ + /** + * API version identifier + */ + version: external_exports.string().regex(/^[a-zA-Z0-9_\-\.]+$/).default("v1").describe("API version (e.g., v1, v2, 2024-01)"), + /** + * Base path for all API routes + */ + basePath: external_exports.string().default("/api").describe("Base URL path for API"), + /** + * Full API path (combines basePath and version) + */ + apiPath: external_exports.string().optional().describe("Full API path (defaults to {basePath}/{version})"), + /** + * Enable automatic CRUD endpoints + */ + enableCrud: external_exports.boolean().default(true).describe("Enable automatic CRUD endpoint generation"), + /** + * Enable metadata endpoints + */ + enableMetadata: external_exports.boolean().default(true).describe("Enable metadata API endpoints"), + /** + * Enable UI API endpoints + */ + enableUi: external_exports.boolean().default(true).describe("Enable UI API endpoints (Views, Menus, Layouts)"), + /** + * Enable batch operation endpoints + */ + enableBatch: external_exports.boolean().default(true).describe("Enable batch operation endpoints"), + /** + * Enable discovery endpoint + */ + enableDiscovery: external_exports.boolean().default(true).describe("Enable API discovery endpoint"), + /** + * API documentation configuration + */ + documentation: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable API documentation"), + title: external_exports.string().default("ObjectStack API").describe("API documentation title"), + description: external_exports.string().optional().describe("API description"), + version: external_exports.string().optional().describe("Documentation version"), + termsOfService: external_exports.string().optional().describe("Terms of service URL"), + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().optional(), + email: external_exports.string().optional() + }).optional(), + license: external_exports.object({ + name: external_exports.string(), + url: external_exports.string().optional() + }).optional() + }).optional().describe("OpenAPI/Swagger documentation config"), + /** + * Response format configuration + */ + responseFormat: external_exports.object({ + envelope: external_exports.boolean().default(true).describe("Wrap responses in standard envelope"), + includeMetadata: external_exports.boolean().default(true).describe("Include response metadata (timestamp, requestId)"), + includePagination: external_exports.boolean().default(true).describe("Include pagination info in list responses") + }).optional().describe("Response format options") +}); +var CrudOperation2 = external_exports.enum([ + "create", + // POST /api/v1/data/{object} + "read", + // GET /api/v1/data/{object}/:id + "update", + // PATCH /api/v1/data/{object}/:id + "delete", + // DELETE /api/v1/data/{object}/:id + "list" + // GET /api/v1/data/{object} +]); +var CrudEndpointPatternSchema2 = external_exports.object({ + /** + * HTTP method + */ + method: HttpMethod5.describe("HTTP method"), + /** + * URL path pattern (relative to API base) + */ + path: external_exports.string().describe("URL path pattern"), + /** + * Operation summary for documentation + */ + summary: external_exports.string().optional().describe("Operation summary"), + /** + * Operation description + */ + description: external_exports.string().optional().describe("Operation description") +}); +var CrudEndpointsConfigSchema2 = external_exports.object({ + /** + * Enable/disable specific CRUD operations + */ + operations: external_exports.object({ + create: external_exports.boolean().default(true).describe("Enable create operation"), + read: external_exports.boolean().default(true).describe("Enable read operation"), + update: external_exports.boolean().default(true).describe("Enable update operation"), + delete: external_exports.boolean().default(true).describe("Enable delete operation"), + list: external_exports.boolean().default(true).describe("Enable list operation") + }).optional().describe("Enable/disable operations"), + /** + * Custom endpoint patterns (override defaults) + */ + patterns: external_exports.record(CrudOperation2, CrudEndpointPatternSchema2.optional()).optional().describe("Custom URL patterns for operations"), + /** + * Path prefix for data operations + */ + dataPrefix: external_exports.string().default("/data").describe("URL prefix for data endpoints"), + /** + * Object name parameter style + */ + objectParamStyle: external_exports.enum(["path", "query"]).default("path").describe("How object name is passed (path param or query param)") +}); +var MetadataEndpointsConfigSchema2 = external_exports.object({ + /** + * Path prefix for metadata operations + */ + prefix: external_exports.string().default("/meta").describe("URL prefix for metadata endpoints"), + /** + * Enable HTTP caching for metadata + */ + enableCache: external_exports.boolean().default(true).describe("Enable HTTP cache headers (ETag, Last-Modified)"), + /** + * Cache TTL in seconds + */ + cacheTtl: external_exports.number().int().default(3600).describe("Cache TTL in seconds"), + /** + * Enable specific metadata endpoints + */ + endpoints: external_exports.object({ + types: external_exports.boolean().default(true).describe("GET /meta - List all metadata types"), + items: external_exports.boolean().default(true).describe("GET /meta/:type - List items of type"), + item: external_exports.boolean().default(true).describe("GET /meta/:type/:name - Get specific item"), + schema: external_exports.boolean().default(true).describe("GET /meta/:type/:name/schema - Get JSON schema") + }).optional().describe("Enable/disable specific endpoints") +}); +var BatchEndpointsConfigSchema2 = external_exports.object({ + /** + * Maximum batch size + */ + maxBatchSize: external_exports.number().int().min(1).max(1e3).default(200).describe("Maximum records per batch operation"), + /** + * Enable generic batch endpoint + */ + enableBatchEndpoint: external_exports.boolean().default(true).describe("Enable POST /data/:object/batch endpoint"), + /** + * Enable specific batch operations + */ + operations: external_exports.object({ + createMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/createMany"), + updateMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/updateMany"), + deleteMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/deleteMany"), + upsertMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/upsertMany") + }).optional().describe("Enable/disable specific batch operations"), + /** + * Transaction mode default + */ + defaultAtomic: external_exports.boolean().default(true).describe("Default atomic/transaction mode for batch operations") +}); +var RouteGenerationConfigSchema2 = external_exports.object({ + /** + * Objects to include (if empty, include all) + */ + includeObjects: external_exports.array(external_exports.string()).optional().describe("Specific objects to generate routes for (empty = all)"), + /** + * Objects to exclude + */ + excludeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to exclude from route generation"), + /** + * Object name transformations + */ + nameTransform: external_exports.enum(["none", "plural", "kebab-case", "camelCase"]).default("none").describe("Transform object names in URLs"), + /** + * Custom route overrides per object + */ + overrides: external_exports.record(external_exports.string(), external_exports.object({ + enabled: external_exports.boolean().optional().describe("Enable/disable routes for this object"), + basePath: external_exports.string().optional().describe("Custom base path"), + operations: external_exports.record(CrudOperation2, external_exports.boolean()).optional().describe("Enable/disable specific operations") + })).optional().describe("Per-object route customization") +}); +var WebhookEventSchema2 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Webhook event identifier (snake_case)"), + description: external_exports.string().describe("Human-readable event description"), + method: HttpMethod5.default("POST").describe("HTTP method for webhook delivery"), + payloadSchema: external_exports.string().describe("JSON Schema $ref for the webhook payload"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers to include in webhook delivery"), + security: external_exports.array( + external_exports.enum(["hmac_sha256", "basic", "bearer", "api_key"]) + ).describe("Supported authentication methods for webhook verification") +}); +var WebhookConfigSchema2 = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable webhook support"), + events: external_exports.array(WebhookEventSchema2).describe("Registered webhook events"), + deliveryConfig: external_exports.object({ + maxRetries: external_exports.number().int().default(3).describe("Maximum delivery retry attempts"), + retryIntervalMs: external_exports.number().int().default(5e3).describe("Milliseconds between retry attempts"), + timeoutMs: external_exports.number().int().default(3e4).describe("Delivery request timeout in milliseconds"), + signatureHeader: external_exports.string().default("X-Signature-256").describe("Header name for webhook signature") + }).describe("Webhook delivery configuration"), + registrationEndpoint: external_exports.string().default("/webhooks").describe("URL path for webhook registration") +}); +var CallbackSchema2 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Callback identifier (snake_case)"), + expression: external_exports.string().describe("Runtime expression (e.g., {$request.body#/callbackUrl})"), + method: HttpMethod5.describe("HTTP method for callback request"), + url: external_exports.string().describe("Callback URL template with runtime expressions") +}); +var OpenApi31ExtensionsSchema2 = external_exports.object({ + webhooks: external_exports.record(external_exports.string(), WebhookEventSchema2).optional().describe("OpenAPI 3.1 webhooks (top-level webhook definitions)"), + callbacks: external_exports.record(external_exports.string(), external_exports.array(CallbackSchema2)).optional().describe("OpenAPI 3.1 callbacks (async response definitions)"), + jsonSchemaDialect: external_exports.string().default("https://json-schema.org/draft/2020-12/schema").describe("JSON Schema dialect for schema definitions"), + pathItemReferences: external_exports.boolean().default(false).describe("Allow $ref in path items (OpenAPI 3.1 feature)") +}); +var RestServerConfigSchema2 = external_exports.object({ + /** + * API configuration + */ + api: RestApiConfigSchema2.optional().describe("REST API configuration"), + /** + * CRUD endpoints configuration + */ + crud: CrudEndpointsConfigSchema2.optional().describe("CRUD endpoints configuration"), + /** + * Metadata endpoints configuration + */ + metadata: MetadataEndpointsConfigSchema2.optional().describe("Metadata endpoints configuration"), + /** + * Batch endpoints configuration + */ + batch: BatchEndpointsConfigSchema2.optional().describe("Batch endpoints configuration"), + /** + * Route generation configuration + */ + routes: RouteGenerationConfigSchema2.optional().describe("Route generation configuration"), + /** + * OpenAPI 3.1 extensions (webhooks, callbacks) + */ + openApi31: OpenApi31ExtensionsSchema2.optional().describe("OpenAPI 3.1 extensions configuration") +}); +var GeneratedEndpointSchema2 = external_exports.object({ + /** + * Endpoint identifier + */ + id: external_exports.string().describe("Unique endpoint identifier"), + /** + * HTTP method + */ + method: HttpMethod5.describe("HTTP method"), + /** + * Full URL path + */ + path: external_exports.string().describe("Full URL path"), + /** + * Object this endpoint operates on + */ + object: external_exports.string().describe("Object name (snake_case)"), + /** + * Operation type + */ + operation: external_exports.union([CrudOperation2, external_exports.string()]).describe("Operation type"), + /** + * Handler reference + */ + handler: external_exports.string().describe("Handler function identifier"), + /** + * Endpoint metadata + */ + metadata: external_exports.object({ + summary: external_exports.string().optional(), + description: external_exports.string().optional(), + tags: external_exports.array(external_exports.string()).optional(), + deprecated: external_exports.boolean().optional() + }).optional() +}); +var EndpointRegistrySchema2 = external_exports.object({ + /** + * Generated endpoints + */ + endpoints: external_exports.array(GeneratedEndpointSchema2).describe("All generated endpoints"), + /** + * Total endpoint count + */ + total: external_exports.number().int().describe("Total number of endpoints"), + /** + * Endpoints by object + */ + byObject: external_exports.record(external_exports.string(), external_exports.array(GeneratedEndpointSchema2)).optional().describe("Endpoints grouped by object"), + /** + * Endpoints by operation + */ + byOperation: external_exports.record(external_exports.string(), external_exports.array(GeneratedEndpointSchema2)).optional().describe("Endpoints grouped by operation") +}); +var RestApiConfig2 = Object.assign(RestApiConfigSchema2, { + create: (config4) => config4 +}); +var RestServerConfig2 = Object.assign(RestServerConfigSchema2, { + create: (config4) => config4 +}); +var ApiProtocolType2 = external_exports.enum([ + "rest", + // RESTful API (CRUD operations) + "graphql", + // GraphQL API (flexible queries) + "odata", + // OData v4 API (enterprise integration) + "websocket", + // WebSocket API (real-time) + "file", + // File/Storage API (uploads/downloads) + "auth", + // Authentication/Authorization API + "metadata", + // Metadata/Schema API + "plugin", + // Plugin-registered custom API + "webhook", + // Webhook endpoints + "rpc" + // JSON-RPC or similar +]); +var HttpStatusCode2 = external_exports.union([ + external_exports.number().int().min(100).max(599), + external_exports.enum(["2xx", "3xx", "4xx", "5xx"]) + // Pattern matching +]); +var ObjectQLReferenceSchema2 = external_exports.object({ + /** Referenced object name (snake_case) */ + objectId: SnakeCaseIdentifierSchema7.describe("Object name to reference"), + /** Include only specific fields (optional) */ + includeFields: external_exports.array(external_exports.string()).optional().describe("Include only these fields in the schema"), + /** Exclude specific fields (optional) */ + excludeFields: external_exports.array(external_exports.string()).optional().describe("Exclude these fields from the schema"), + /** Include related objects via lookup fields */ + includeRelated: external_exports.array(external_exports.string()).optional().describe("Include related objects via lookup fields") +}); +var SchemaDefinition2 = external_exports.union([ + external_exports.unknown().describe("Static JSON Schema definition"), + external_exports.object({ + $ref: ObjectQLReferenceSchema2.describe("Dynamic reference to ObjectQL object") + }).describe("Dynamic ObjectQL reference") +]); +var ApiParameterSchema2 = external_exports.object({ + /** Parameter name */ + name: external_exports.string().describe("Parameter name"), + /** Parameter location */ + in: external_exports.enum(["path", "query", "header", "body", "cookie"]).describe("Parameter location"), + /** Parameter description */ + description: external_exports.string().optional().describe("Parameter description"), + /** Required flag */ + required: external_exports.boolean().default(false).describe("Whether parameter is required"), + /** Parameter type/schema - supports static or dynamic (ObjectQL) schemas */ + schema: external_exports.union([ + external_exports.object({ + type: external_exports.enum(["string", "number", "integer", "boolean", "array", "object"]).describe("Parameter type"), + format: external_exports.string().optional().describe("Format (e.g., date-time, email, uuid)"), + enum: external_exports.array(external_exports.unknown()).optional().describe("Allowed values"), + default: external_exports.unknown().optional().describe("Default value"), + items: external_exports.unknown().optional().describe("Array item schema"), + properties: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Object properties") + }).describe("Static JSON Schema"), + external_exports.object({ + $ref: ObjectQLReferenceSchema2 + }).describe("Dynamic ObjectQL reference") + ]).describe("Parameter schema definition"), + /** Example value */ + example: external_exports.unknown().optional().describe("Example value") +}); +var ApiResponseSchema2 = external_exports.object({ + /** HTTP status code */ + statusCode: HttpStatusCode2.describe("HTTP status code"), + /** Response description */ + description: external_exports.string().describe("Response description"), + /** Response content type */ + contentType: external_exports.string().default("application/json").describe("Response content type"), + /** Response schema - supports static or dynamic (ObjectQL) schemas */ + schema: external_exports.union([ + external_exports.unknown().describe("Static JSON Schema"), + external_exports.object({ + $ref: ObjectQLReferenceSchema2 + }).describe("Dynamic ObjectQL reference") + ]).optional().describe("Response body schema"), + /** Response headers */ + headers: external_exports.record(external_exports.string(), external_exports.object({ + description: external_exports.string().optional(), + schema: external_exports.unknown() + })).optional().describe("Response headers"), + /** Example response */ + example: external_exports.unknown().optional().describe("Example response") +}); +var ApiEndpointRegistrationSchema2 = external_exports.object({ + /** Unique endpoint identifier */ + id: external_exports.string().describe("Unique endpoint identifier"), + /** HTTP method (for HTTP-based APIs) */ + method: HttpMethod5.optional().describe("HTTP method"), + /** URL path pattern */ + path: external_exports.string().describe("URL path pattern"), + /** Short summary */ + summary: external_exports.string().optional().describe("Short endpoint summary"), + /** Detailed description */ + description: external_exports.string().optional().describe("Detailed endpoint description"), + /** Operation ID (OpenAPI) */ + operationId: external_exports.string().optional().describe("Unique operation identifier"), + /** Tags for grouping */ + tags: external_exports.array(external_exports.string()).optional().default([]).describe("Tags for categorization"), + /** Parameters */ + parameters: external_exports.array(ApiParameterSchema2).optional().default([]).describe("Endpoint parameters"), + /** Request body schema */ + requestBody: external_exports.object({ + description: external_exports.string().optional(), + required: external_exports.boolean().default(false), + contentType: external_exports.string().default("application/json"), + schema: external_exports.unknown().optional(), + example: external_exports.unknown().optional() + }).optional().describe("Request body specification"), + /** Response definitions */ + responses: external_exports.array(ApiResponseSchema2).optional().default([]).describe("Possible responses"), + /** Rate Limiting */ + rateLimit: RateLimitConfigSchema4.optional().describe("Endpoint specific rate limiting"), + /** Security Requirements */ + security: external_exports.array(external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))).optional().describe('Security requirements (e.g. [{"bearerAuth": []}])'), + /** + * Required Permissions (RBAC Integration) + * + * Array of permission names required to access this endpoint. + * The gateway layer automatically validates these permissions before + * allowing the request to proceed, eliminating the need for permission + * checks in individual API handlers. + * + * **Format:** `.` or system permission name + * + * **Object Permissions:** + * - `customer.read` - Read customer records + * - `customer.create` - Create customer records + * - `customer.edit` - Update customer records + * - `customer.delete` - Delete customer records + * - `customer.viewAll` - View all customer records (bypass sharing) + * - `customer.modifyAll` - Modify all customer records (bypass sharing) + * + * **System Permissions:** + * - `manage_users` - User management + * - `view_setup` - Access to system setup + * - `customize_application` - Modify metadata + * - `api_enabled` - API access + * + * @example Object-level permissions + * ```json + * { + * "requiredPermissions": ["customer.read"] + * } + * ``` + * + * @example Multiple permissions (ALL required) + * ```json + * { + * "requiredPermissions": ["customer.read", "account.read"] + * } + * ``` + * + * @example System permission + * ```json + * { + * "requiredPermissions": ["manage_users"] + * } + * ``` + * + * @see {@link file://../../permission/permission.zod.ts} for permission definitions + */ + requiredPermissions: external_exports.array(external_exports.string()).optional().default([]).describe('Required RBAC permissions (e.g., "customer.read", "manage_users")'), + /** + * Route Priority + * + * Priority level for route conflict resolution. Higher priority routes + * are registered first and take precedence when multiple routes match + * the same path pattern. + * + * **Default:** 100 (medium priority) + * **Range:** 0-1000 (higher = more important) + * + * **Use Cases:** + * - Core system APIs: 900-1000 + * - Plugin APIs: 100-500 + * - Custom/override APIs: 500-900 + * - Fallback routes: 0-100 + * + * @example High priority core endpoint + * ```json + * { + * "path": "/api/v1/data/:object/:id", + * "priority": 950 + * } + * ``` + * + * @example Medium priority plugin endpoint + * ```json + * { + * "path": "/api/v1/custom/action", + * "priority": 300 + * } + * ``` + */ + priority: external_exports.number().int().min(0).max(1e3).optional().default(100).describe("Route priority for conflict resolution (0-1000, higher = more important)"), + /** + * Protocol-Specific Configuration + * + * Allows plugins and custom APIs to define protocol-specific metadata + * that can be used for specialized handling or documentation generation. + * + * **Examples:** + * - gRPC: Service and method names + * - tRPC: Procedure type (query/mutation) + * - WebSocket: Event names and handlers + * - Custom protocols: Any metadata needed + * + * @example gRPC configuration + * ```json + * { + * "protocolConfig": { + * "subProtocol": "grpc", + * "serviceName": "CustomerService", + * "methodName": "GetCustomer", + * "streaming": false + * } + * } + * ``` + * + * @example tRPC configuration + * ```json + * { + * "protocolConfig": { + * "subProtocol": "trpc", + * "procedureType": "query", + * "router": "customer" + * } + * } + * ``` + * + * @example WebSocket configuration + * ```json + * { + * "protocolConfig": { + * "subProtocol": "websocket", + * "eventName": "customer.updated", + * "direction": "server-to-client" + * } + * } + * ``` + */ + protocolConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)"), + /** Deprecation flag */ + deprecated: external_exports.boolean().default(false).describe("Whether endpoint is deprecated"), + /** External documentation */ + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional().describe("External documentation link") +}); +var ApiMetadataSchema2 = external_exports.object({ + /** API owner/team */ + owner: external_exports.string().optional().describe("Owner team or person"), + /** API status */ + status: external_exports.enum(["active", "deprecated", "experimental", "beta"]).default("active").describe("API lifecycle status"), + /** Categorization tags */ + tags: external_exports.array(external_exports.string()).optional().default([]).describe("Classification tags"), + /** Plugin source (if plugin-registered) */ + pluginSource: external_exports.string().optional().describe("Source plugin name"), + /** Custom metadata */ + custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata fields") +}); +var ApiRegistryEntrySchema2 = external_exports.object({ + /** Unique API identifier */ + id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique API identifier (snake_case)"), + /** Human-readable name */ + name: external_exports.string().describe("API display name"), + /** API protocol type */ + type: ApiProtocolType2.describe("API protocol type"), + /** API version */ + version: external_exports.string().describe("API version (e.g., v1, 2024-01)"), + /** Base URL path */ + basePath: external_exports.string().describe("Base URL path for this API"), + /** API description */ + description: external_exports.string().optional().describe("API description"), + /** Endpoints in this API */ + endpoints: external_exports.array(ApiEndpointRegistrationSchema2).describe("Registered endpoints"), + /** OpenAPI/GraphQL/OData specific configuration */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Protocol-specific configuration"), + /** API metadata */ + metadata: ApiMetadataSchema2.optional().describe("Additional metadata"), + /** Terms of service URL */ + termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), + /** Contact information */ + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().url().optional(), + email: external_exports.string().email().optional() + }).optional().describe("Contact information"), + /** License information */ + license: external_exports.object({ + name: external_exports.string(), + url: external_exports.string().url().optional() + }).optional().describe("License information") +}); +var ConflictResolutionStrategy2 = external_exports.enum([ + "error", + // Throw error on conflict (safest, default) + "priority", + // Use priority field to resolve (highest priority wins) + "first-wins", + // First registered endpoint wins + "last-wins" + // Last registered endpoint wins (override mode) +]); +var ApiRegistrySchema2 = external_exports.object({ + /** Registry version */ + version: external_exports.string().describe("Registry version"), + /** + * Conflict Resolution Strategy + * + * Defines how to handle route conflicts when multiple endpoints + * register the same or overlapping URL patterns. + * + * **Strategies:** + * - `error`: Throw error on conflict (safest, prevents silent overwrites) + * - `priority`: Use endpoint priority field (highest priority wins) + * - `first-wins`: First registered endpoint wins (stable, predictable) + * - `last-wins`: Last registered endpoint wins (allows overrides) + * + * **Default:** `error` + * + * **Best Practices:** + * - Use `error` in production to catch configuration issues + * - Use `priority` when mixing core and plugin APIs + * - Use `last-wins` for development/testing overrides + * + * @example Prevent accidental conflicts + * ```json + * { + * "conflictResolution": "error" + * } + * ``` + * + * @example Allow plugin overrides with priority + * ```json + * { + * "conflictResolution": "priority" + * } + * ``` + */ + conflictResolution: ConflictResolutionStrategy2.optional().default("error").describe("Strategy for handling route conflicts"), + /** Registered APIs */ + apis: external_exports.array(ApiRegistryEntrySchema2).describe("All registered APIs"), + /** Total API count */ + totalApis: external_exports.number().int().describe("Total number of registered APIs"), + /** Total endpoint count across all APIs */ + totalEndpoints: external_exports.number().int().describe("Total number of endpoints"), + /** APIs grouped by type */ + byType: external_exports.record(ApiProtocolType2, external_exports.array(ApiRegistryEntrySchema2)).optional().describe("APIs grouped by protocol type"), + /** APIs grouped by status */ + byStatus: external_exports.record(external_exports.string(), external_exports.array(ApiRegistryEntrySchema2)).optional().describe("APIs grouped by status"), + /** Last updated timestamp */ + updatedAt: external_exports.string().datetime().optional().describe("Last registry update time") +}); +var ApiDiscoveryQuerySchema2 = external_exports.object({ + /** Filter by API type */ + type: ApiProtocolType2.optional().describe("Filter by API protocol type"), + /** Filter by tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags (ANY match)"), + /** Filter by status */ + status: external_exports.enum(["active", "deprecated", "experimental", "beta"]).optional().describe("Filter by lifecycle status"), + /** Filter by plugin source */ + pluginSource: external_exports.string().optional().describe("Filter by plugin name"), + /** Search in name/description */ + search: external_exports.string().optional().describe("Full-text search in name/description"), + /** Filter by version */ + version: external_exports.string().optional().describe("Filter by specific version") +}); +var ApiDiscoveryResponseSchema2 = external_exports.object({ + /** Matching APIs */ + apis: external_exports.array(ApiRegistryEntrySchema2).describe("Matching API entries"), + /** Total matches */ + total: external_exports.number().int().describe("Total matching APIs"), + /** Applied filters */ + filters: ApiDiscoveryQuerySchema2.optional().describe("Applied query filters") +}); +var ApiEndpointRegistration2 = Object.assign(ApiEndpointRegistrationSchema2, { + create: (config4) => config4 +}); +var ApiRegistryEntry2 = Object.assign(ApiRegistryEntrySchema2, { + create: (config4) => config4 +}); +var ApiRegistry2 = Object.assign(ApiRegistrySchema2, { + create: (config4) => config4 +}); +var OpenApiServerSchema2 = external_exports.object({ + /** Server URL */ + url: external_exports.string().url().describe("Server base URL"), + /** Server description */ + description: external_exports.string().optional().describe("Server description"), + /** Server variables */ + variables: external_exports.record(external_exports.string(), external_exports.object({ + default: external_exports.string(), + description: external_exports.string().optional(), + enum: external_exports.array(external_exports.string()).optional() + })).optional().describe("URL template variables") +}); +var OpenApiSecuritySchemeSchema2 = external_exports.object({ + /** Security scheme type */ + type: external_exports.enum(["apiKey", "http", "oauth2", "openIdConnect"]).describe("Security type"), + /** Scheme name */ + scheme: external_exports.string().optional().describe("HTTP auth scheme (bearer, basic, etc.)"), + /** Bearer format */ + bearerFormat: external_exports.string().optional().describe("Bearer token format (e.g., JWT)"), + /** API key name */ + name: external_exports.string().optional().describe("API key parameter name"), + /** API key location */ + in: external_exports.enum(["header", "query", "cookie"]).optional().describe("API key location"), + /** OAuth flows */ + flows: external_exports.object({ + implicit: external_exports.unknown().optional(), + password: external_exports.unknown().optional(), + clientCredentials: external_exports.unknown().optional(), + authorizationCode: external_exports.unknown().optional() + }).optional().describe("OAuth2 flows"), + /** OpenID Connect URL */ + openIdConnectUrl: external_exports.string().url().optional().describe("OpenID Connect discovery URL"), + /** Description */ + description: external_exports.string().optional().describe("Security scheme description") +}); +var OpenApiSpecSchema2 = external_exports.object({ + /** OpenAPI version */ + openapi: external_exports.string().default("3.0.0").describe("OpenAPI specification version"), + /** API information */ + info: external_exports.object({ + title: external_exports.string().describe("API title"), + version: external_exports.string().describe("API version"), + description: external_exports.string().optional().describe("API description"), + termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().url().optional(), + email: external_exports.string().email().optional() + }).optional(), + license: external_exports.object({ + name: external_exports.string(), + url: external_exports.string().url().optional() + }).optional() + }).describe("API metadata"), + /** Servers */ + servers: external_exports.array(OpenApiServerSchema2).optional().default([]).describe("API servers"), + /** API paths */ + paths: external_exports.record(external_exports.string(), external_exports.unknown()).describe("API paths and operations"), + /** Reusable components */ + components: external_exports.object({ + schemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + responses: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + examples: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + requestBodies: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + headers: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + securitySchemes: external_exports.record(external_exports.string(), OpenApiSecuritySchemeSchema2).optional(), + links: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), + callbacks: external_exports.record(external_exports.string(), external_exports.unknown()).optional() + }).optional().describe("Reusable components"), + /** Security requirements */ + security: external_exports.array(external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))).optional().describe("Global security requirements"), + /** Tags */ + tags: external_exports.array(external_exports.object({ + name: external_exports.string(), + description: external_exports.string().optional(), + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional() + })).optional().describe("Tag definitions"), + /** External documentation */ + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional().describe("External documentation") +}); +var ApiTestingUiType2 = external_exports.enum([ + "swagger-ui", + // Swagger UI + "redoc", + // Redoc + "rapidoc", + // RapiDoc + "stoplight", + // Stoplight Elements + "scalar", + // Scalar API Reference + "graphql-playground", + // GraphQL Playground + "graphiql", + // GraphiQL + "postman", + // Postman-like interface + "custom" + // Custom implementation +]); +var ApiTestingUiConfigSchema2 = external_exports.object({ + /** UI type */ + type: ApiTestingUiType2.describe("Testing UI implementation"), + /** UI path */ + path: external_exports.string().default("/api-docs").describe("URL path for documentation UI"), + /** UI theme */ + theme: external_exports.enum(["light", "dark", "auto"]).default("light").describe("UI color theme"), + /** Enable try-it-out feature */ + enableTryItOut: external_exports.boolean().default(true).describe("Enable interactive API testing"), + /** Enable filtering */ + enableFilter: external_exports.boolean().default(true).describe("Enable endpoint filtering"), + /** Enable CORS for testing */ + enableCors: external_exports.boolean().default(true).describe("Enable CORS for browser testing"), + /** Default expand depth for models */ + defaultModelsExpandDepth: external_exports.number().int().min(-1).default(1).describe("Default expand depth for schemas (-1 = fully expand)"), + /** Display request duration */ + displayRequestDuration: external_exports.boolean().default(true).describe("Show request duration"), + /** Syntax highlighting */ + syntaxHighlighting: external_exports.boolean().default(true).describe("Enable syntax highlighting"), + /** Custom CSS URL */ + customCssUrl: external_exports.string().url().optional().describe("Custom CSS stylesheet URL"), + /** Custom JavaScript URL */ + customJsUrl: external_exports.string().url().optional().describe("Custom JavaScript URL"), + /** Layout options */ + layout: external_exports.object({ + showExtensions: external_exports.boolean().default(false).describe("Show vendor extensions"), + showCommonExtensions: external_exports.boolean().default(false).describe("Show common extensions"), + deepLinking: external_exports.boolean().default(true).describe("Enable deep linking"), + displayOperationId: external_exports.boolean().default(false).describe("Display operation IDs"), + defaultModelRendering: external_exports.enum(["example", "model"]).default("example").describe("Default model rendering mode"), + defaultModelsExpandDepth: external_exports.number().int().default(1).describe("Models expand depth"), + defaultModelExpandDepth: external_exports.number().int().default(1).describe("Single model expand depth"), + docExpansion: external_exports.enum(["list", "full", "none"]).default("list").describe("Documentation expansion mode") + }).optional().describe("Layout configuration") +}); +var ApiTestRequestSchema2 = external_exports.object({ + /** Request name */ + name: external_exports.string().describe("Test request name"), + /** Request description */ + description: external_exports.string().optional().describe("Request description"), + /** HTTP method */ + method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]).describe("HTTP method"), + /** Request URL */ + url: external_exports.string().describe("Request URL (can include variables)"), + /** Request headers */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().default({}).describe("Request headers"), + /** Query parameters */ + queryParams: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().default({}).describe("Query parameters"), + /** Request body */ + body: external_exports.unknown().optional().describe("Request body"), + /** Environment variables */ + variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().default({}).describe("Template variables"), + /** Expected response */ + expectedResponse: external_exports.object({ + statusCode: external_exports.number().int(), + body: external_exports.unknown().optional() + }).optional().describe("Expected response for validation") +}); +var ApiTestCollectionSchema2 = external_exports.object({ + /** Collection name */ + name: external_exports.string().describe("Collection name"), + /** Collection description */ + description: external_exports.string().optional().describe("Collection description"), + /** Collection variables */ + variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().default({}).describe("Shared variables"), + /** Test requests */ + requests: external_exports.array(ApiTestRequestSchema2).describe("Test requests in this collection"), + /** Folders/grouping */ + folders: external_exports.array(external_exports.object({ + name: external_exports.string(), + description: external_exports.string().optional(), + requests: external_exports.array(ApiTestRequestSchema2) + })).optional().describe("Request folders for organization") +}); +var ApiChangelogEntrySchema2 = external_exports.object({ + /** Version */ + version: external_exports.string().describe("API version"), + /** Release date */ + date: external_exports.string().date().describe("Release date"), + /** Changes */ + changes: external_exports.object({ + added: external_exports.array(external_exports.string()).optional().default([]).describe("New features"), + changed: external_exports.array(external_exports.string()).optional().default([]).describe("Changes"), + deprecated: external_exports.array(external_exports.string()).optional().default([]).describe("Deprecations"), + removed: external_exports.array(external_exports.string()).optional().default([]).describe("Removed features"), + fixed: external_exports.array(external_exports.string()).optional().default([]).describe("Bug fixes"), + security: external_exports.array(external_exports.string()).optional().default([]).describe("Security fixes") + }).describe("Version changes"), + /** Migration guide */ + migrationGuide: external_exports.string().optional().describe("Migration guide URL or text") +}); +var CodeGenerationTemplateSchema2 = external_exports.object({ + /** Language/framework */ + language: external_exports.string().describe("Target language/framework (e.g., typescript, python, curl)"), + /** Template name */ + name: external_exports.string().describe("Template name"), + /** Template content */ + template: external_exports.string().describe("Code template with placeholders"), + /** Template variables */ + variables: external_exports.array(external_exports.string()).optional().describe("Required template variables") +}); +var ApiDocumentationConfigSchema2 = external_exports.object({ + /** Enable documentation */ + enabled: external_exports.boolean().default(true).describe("Enable API documentation"), + /** Documentation title */ + title: external_exports.string().default("API Documentation").describe("Documentation title"), + /** API version */ + version: external_exports.string().describe("API version"), + /** API description */ + description: external_exports.string().optional().describe("API description"), + /** Server configurations */ + servers: external_exports.array(OpenApiServerSchema2).optional().default([]).describe("API server URLs"), + /** UI configuration */ + ui: ApiTestingUiConfigSchema2.optional().describe("Testing UI configuration"), + /** Generate OpenAPI spec */ + generateOpenApi: external_exports.boolean().default(true).describe("Generate OpenAPI 3.0 specification"), + /** Generate test collections */ + generateTestCollections: external_exports.boolean().default(true).describe("Generate API test collections"), + /** Test collections */ + testCollections: external_exports.array(ApiTestCollectionSchema2).optional().default([]).describe("Predefined test collections"), + /** API changelog */ + changelog: external_exports.array(ApiChangelogEntrySchema2).optional().default([]).describe("API version changelog"), + /** Code generation templates */ + codeTemplates: external_exports.array(CodeGenerationTemplateSchema2).optional().default([]).describe("Code generation templates"), + /** Terms of service */ + termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), + /** Contact information */ + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().url().optional(), + email: external_exports.string().email().optional() + }).optional().describe("Contact information"), + /** License */ + license: external_exports.object({ + name: external_exports.string(), + url: external_exports.string().url().optional() + }).optional().describe("API license"), + /** External documentation */ + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional().describe("External documentation link"), + /** Security schemes */ + securitySchemes: external_exports.record(external_exports.string(), OpenApiSecuritySchemeSchema2).optional().describe("Security scheme definitions"), + /** Global tags */ + tags: external_exports.array(external_exports.object({ + name: external_exports.string(), + description: external_exports.string().optional(), + externalDocs: external_exports.object({ + description: external_exports.string().optional(), + url: external_exports.string().url() + }).optional() + })).optional().describe("Global tag definitions") +}); +var GeneratedApiDocumentationSchema2 = external_exports.object({ + /** OpenAPI specification */ + openApiSpec: OpenApiSpecSchema2.optional().describe("Generated OpenAPI specification"), + /** Test collections */ + testCollections: external_exports.array(ApiTestCollectionSchema2).optional().describe("Generated test collections"), + /** Markdown documentation */ + markdown: external_exports.string().optional().describe("Generated markdown documentation"), + /** HTML documentation */ + html: external_exports.string().optional().describe("Generated HTML documentation"), + /** Generation timestamp */ + generatedAt: external_exports.string().datetime().describe("Generation timestamp"), + /** Source APIs */ + sourceApis: external_exports.array(external_exports.string()).describe("Source API IDs used for generation") +}); +var ApiDocumentationConfig2 = Object.assign(ApiDocumentationConfigSchema2, { + create: (config4) => config4 +}); +var ApiTestCollection2 = Object.assign(ApiTestCollectionSchema2, { + create: (config4) => config4 +}); +var OpenApiSpec2 = Object.assign(OpenApiSpecSchema2, { + create: (config4) => config4 +}); +var AnalyticsEndpoint2 = external_exports.enum([ + "/api/v1/analytics/query", + // Execute analysis + "/api/v1/analytics/meta", + // Discover cubes/metrics + "/api/v1/analytics/sql" + // Dry-run SQL generation +]); +var AnalyticsQueryRequestSchema2 = external_exports.object({ + query: AnalyticsQuerySchema3.describe("The analytic query definition"), + cube: external_exports.string().describe("Target cube name"), + format: external_exports.enum(["json", "csv", "xlsx"]).default("json").describe("Response format") +}); +var AnalyticsResultResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + rows: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Result rows"), + fields: external_exports.array(external_exports.object({ + name: external_exports.string(), + type: external_exports.string() + })).describe("Column metadata"), + sql: external_exports.string().optional().describe("Executed SQL (if debug enabled)") + }) +}); +var GetAnalyticsMetaRequestSchema2 = external_exports.object({ + cube: external_exports.string().optional().describe("Optional cube name to filter") +}); +var AnalyticsMetadataResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + cubes: external_exports.array(CubeSchema3).describe("Available cubes") + }) +}); +var AnalyticsSqlResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + sql: external_exports.string(), + params: external_exports.array(external_exports.unknown()) + }) +}); +var VersioningStrategy2 = external_exports.enum([ + "urlPath", + "header", + "queryParam", + "dateBased" +]); +var VersionStatus2 = external_exports.enum([ + "preview", + "current", + "supported", + "deprecated", + "retired" +]); +var VersionDefinitionSchema2 = external_exports.object({ + /** Version identifier (e.g., "v1", "v2beta1", "2025-01-01") */ + version: external_exports.string().describe('Version identifier (e.g., "v1", "v2beta1", "2025-01-01")'), + /** Current lifecycle status */ + status: VersionStatus2.describe("Lifecycle status of this version"), + /** Date this version was released (ISO 8601 date) */ + releasedAt: external_exports.string().describe('Release date (ISO 8601, e.g., "2025-01-15")'), + /** Date this version was deprecated (ISO 8601 date) */ + deprecatedAt: external_exports.string().optional().describe("Deprecation date (ISO 8601). Only set for deprecated/retired versions"), + /** Date this version will be retired (ISO 8601 date) */ + sunsetAt: external_exports.string().optional().describe("Sunset date (ISO 8601). After this date, the version returns 410 Gone"), + /** URL to migration guide for moving to a newer version */ + migrationGuide: external_exports.string().url().optional().describe("URL to migration guide for upgrading from this version"), + /** Human-readable description of this version */ + description: external_exports.string().optional().describe("Human-readable description or release notes summary"), + /** Breaking changes introduced in or since this version */ + breakingChanges: external_exports.array(external_exports.string()).optional().describe("List of breaking changes (for preview/new versions)") +}); +var VersioningConfigSchema23 = external_exports.object({ + /** Versioning strategy */ + strategy: VersioningStrategy2.default("urlPath").describe("How the API version is specified by clients"), + /** Current (recommended) API version */ + current: external_exports.string().describe("The current/recommended API version identifier"), + /** Default version when none specified by client */ + default: external_exports.string().describe("Fallback version when client does not specify one"), + /** All available API versions */ + versions: external_exports.array(VersionDefinitionSchema2).min(1).describe("All available API versions with lifecycle metadata"), + /** Header name for header-based versioning */ + headerName: external_exports.string().default("ObjectStack-Version").describe("HTTP header name for version negotiation (header/dateBased strategies)"), + /** Query parameter name for queryParam strategy */ + queryParamName: external_exports.string().default("version").describe("Query parameter name for version specification (queryParam strategy)"), + /** URL prefix pattern for urlPath strategy */ + urlPrefix: external_exports.string().default("/api").describe("URL prefix before version segment (urlPath strategy)"), + /** Deprecation behavior */ + deprecation: external_exports.object({ + /** Include Deprecation header in responses for deprecated versions */ + warnHeader: external_exports.boolean().default(true).describe("Include Deprecation header (RFC 8594) in responses"), + /** Include Sunset header with retirement date */ + sunsetHeader: external_exports.boolean().default(true).describe("Include Sunset header (RFC 8594) with retirement date"), + /** Include Link header pointing to migration guide */ + linkHeader: external_exports.boolean().default(true).describe("Include Link header pointing to migration guide URL"), + /** Whether to reject requests to retired versions */ + rejectRetired: external_exports.boolean().default(true).describe("Return 410 Gone for retired API versions"), + /** Custom deprecation warning message */ + warningMessage: external_exports.string().optional().describe("Custom warning message for deprecated version responses") + }).optional().describe("Deprecation lifecycle behavior"), + /** Whether to include version info in discovery response */ + includeInDiscovery: external_exports.boolean().default(true).describe("Include version information in the API discovery endpoint") +}); +var VersionNegotiationResponseSchema2 = external_exports.object({ + /** The current/recommended version */ + current: external_exports.string().describe("Current recommended API version"), + /** The version the client requested (if any) */ + requested: external_exports.string().optional().describe("Version requested by the client"), + /** The version actually being used for this request */ + resolved: external_exports.string().describe("Resolved API version for this request"), + /** All supported (non-retired) version identifiers */ + supported: external_exports.array(external_exports.string()).describe("All supported version identifiers"), + /** Deprecated version identifiers (still functional but will be removed) */ + deprecated: external_exports.array(external_exports.string()).optional().describe("Deprecated version identifiers"), + /** Full version definitions (optional, for detailed clients) */ + versions: external_exports.array(VersionDefinitionSchema2).optional().describe("Full version definitions with lifecycle metadata") +}); +var DEFAULT_VERSIONING_CONFIG = { + strategy: "urlPath", + current: "v1", + default: "v1", + versions: [ + { + version: "v1", + status: "current", + releasedAt: "2025-01-15", + description: "ObjectStack API v1 \u2014 Initial stable release" + } + ], + deprecation: { + warnHeader: true, + sunsetHeader: true, + linkHeader: true, + rejectRetired: true + }, + includeInDiscovery: true +}; +var AuthProvider2 = external_exports.enum([ + "local", + "google", + "github", + "microsoft", + "ldap", + "saml" +]); +var SessionUserSchema2 = external_exports.object({ + id: external_exports.string().describe("User ID"), + email: external_exports.string().email().describe("Email address"), + emailVerified: external_exports.boolean().default(false).describe("Is email verified?"), + name: external_exports.string().describe("Display name"), + image: external_exports.string().optional().describe("Avatar URL"), + username: external_exports.string().optional().describe("Username (optional)"), + roles: external_exports.array(external_exports.string()).optional().default([]).describe("Assigned role IDs"), + tenantId: external_exports.string().optional().describe("Current tenant ID"), + language: external_exports.string().default("en").describe("Preferred language"), + timezone: external_exports.string().optional().describe("Preferred timezone"), + createdAt: external_exports.string().datetime().optional(), + updatedAt: external_exports.string().datetime().optional() +}); +var SessionSchema22 = external_exports.object({ + id: external_exports.string(), + expiresAt: external_exports.string().datetime(), + token: external_exports.string().optional(), + ipAddress: external_exports.string().optional(), + userAgent: external_exports.string().optional(), + userId: external_exports.string() +}); +var LoginType2 = external_exports.enum(["email", "username", "phone", "magic-link", "social"]); +var LoginRequestSchema2 = external_exports.object({ + type: LoginType2.default("email").describe("Login method"), + email: external_exports.string().email().optional().describe("Required for email/magic-link"), + username: external_exports.string().optional().describe("Required for username login"), + password: external_exports.string().optional().describe("Required for password login"), + provider: external_exports.string().optional().describe("Required for social (google, github)"), + redirectTo: external_exports.string().optional().describe("Redirect URL after successful login") +}); +var RegisterRequestSchema2 = external_exports.object({ + email: external_exports.string().email(), + password: external_exports.string(), + name: external_exports.string(), + image: external_exports.string().optional() +}); +var RefreshTokenRequestSchema2 = external_exports.object({ + refreshToken: external_exports.string().describe("Refresh token") +}); +var SessionResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + session: SessionSchema22.describe("Active Session Info"), + user: SessionUserSchema2.describe("Current User Details"), + token: external_exports.string().optional().describe("Bearer token if not using cookies") + }) +}); +var UserProfileResponseSchema2 = BaseResponseSchema2.extend({ + data: SessionUserSchema2 +}); +var AuthEndpointPaths2 = { + // Email/Password Authentication + signInEmail: "/sign-in/email", + signUpEmail: "/sign-up/email", + signOut: "/sign-out", + // Session Management + getSession: "/get-session", + // Password Management + forgetPassword: "/forget-password", + resetPassword: "/reset-password", + // Email Verification + sendVerificationEmail: "/send-verification-email", + verifyEmail: "/verify-email", + // OAuth (dynamic based on provider) + // authorize: '/authorize/:provider' + // callback: '/callback/:provider' + // 2FA (when enabled) + twoFactorEnable: "/two-factor/enable", + twoFactorVerify: "/two-factor/verify", + // Passkeys (when enabled) + passkeyRegister: "/passkey/register", + passkeyAuthenticate: "/passkey/authenticate", + // Magic Links (when enabled) + magicLinkSend: "/magic-link/send", + magicLinkVerify: "/magic-link/verify" +}; +var AuthEndpointSchema2 = external_exports.object({ + /** Sign in with email and password */ + signInEmail: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths2.signInEmail), + description: external_exports.literal("Sign in with email and password") + }), + /** Register new user with email and password */ + signUpEmail: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths2.signUpEmail), + description: external_exports.literal("Register new user with email and password") + }), + /** Sign out current user */ + signOut: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths2.signOut), + description: external_exports.literal("Sign out current user") + }), + /** Get current user session */ + getSession: external_exports.object({ + method: external_exports.literal("GET"), + path: external_exports.literal(AuthEndpointPaths2.getSession), + description: external_exports.literal("Get current user session") + }), + /** Request password reset email */ + forgetPassword: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths2.forgetPassword), + description: external_exports.literal("Request password reset email") + }), + /** Reset password with token */ + resetPassword: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths2.resetPassword), + description: external_exports.literal("Reset password with token") + }), + /** Send email verification */ + sendVerificationEmail: external_exports.object({ + method: external_exports.literal("POST"), + path: external_exports.literal(AuthEndpointPaths2.sendVerificationEmail), + description: external_exports.literal("Send email verification link") + }), + /** Verify email with token */ + verifyEmail: external_exports.object({ + method: external_exports.literal("GET"), + path: external_exports.literal(AuthEndpointPaths2.verifyEmail), + description: external_exports.literal("Verify email with token") + }) +}); +var AuthEndpointAliases2 = { + login: AuthEndpointPaths2.signInEmail, + register: AuthEndpointPaths2.signUpEmail, + logout: AuthEndpointPaths2.signOut, + me: AuthEndpointPaths2.getSession +}; +function getAuthEndpointUrl(basePath, endpoint) { + const cleanBase = basePath.replace(/\/$/, ""); + return `${cleanBase}${AuthEndpointPaths2[endpoint]}`; +} +var EndpointMapping2 = { + "/login": AuthEndpointPaths2.signInEmail, + "/register": AuthEndpointPaths2.signUpEmail, + "/logout": AuthEndpointPaths2.signOut, + "/me": AuthEndpointPaths2.getSession, + "/refresh": AuthEndpointPaths2.getSession + // Session refresh handled by better-auth automatically +}; +var GetPresignedUrlRequestSchema2 = external_exports.object({ + filename: external_exports.string().describe("Original filename"), + mimeType: external_exports.string().describe("File MIME type"), + size: external_exports.number().describe("File size in bytes"), + scope: external_exports.string().default("user").describe("Target storage scope (e.g. user, private, public)"), + bucket: external_exports.string().optional().describe("Specific bucket override (admin only)") +}); +var CompleteUploadRequestSchema2 = external_exports.object({ + fileId: external_exports.string().describe("File ID returned from presigned request"), + eTag: external_exports.string().optional().describe("S3 ETag verification") +}); +var PresignedUrlResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + uploadUrl: external_exports.string().describe("PUT/POST URL for direct upload"), + downloadUrl: external_exports.string().optional().describe("Public/Private preview URL"), + fileId: external_exports.string().describe("Temporary File ID"), + method: external_exports.enum(["PUT", "POST"]).describe("HTTP Method to use"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Required headers for upload"), + expiresIn: external_exports.number().describe("URL expiry in seconds") + }) +}); +var FileUploadResponseSchema2 = BaseResponseSchema2.extend({ + data: FileMetadataSchema3.describe("Uploaded file metadata") +}); +var FileTypeValidationSchema2 = external_exports.object({ + mode: external_exports.enum(["whitelist", "blacklist"]).describe("whitelist = only allow listed types, blacklist = block listed types"), + mimeTypes: external_exports.array(external_exports.string()).min(1).describe('List of MIME types to allow or block (e.g., "image/jpeg", "application/pdf")'), + extensions: external_exports.array(external_exports.string()).optional().describe('List of file extensions to allow or block (e.g., ".jpg", ".pdf")'), + maxFileSize: external_exports.number().int().min(1).optional().describe("Maximum file size in bytes"), + minFileSize: external_exports.number().int().min(0).optional().describe("Minimum file size in bytes (e.g., reject empty files)") +}); +var InitiateChunkedUploadRequestSchema2 = external_exports.object({ + filename: external_exports.string().describe("Original filename"), + mimeType: external_exports.string().describe("File MIME type"), + totalSize: external_exports.number().int().min(1).describe("Total file size in bytes"), + chunkSize: external_exports.number().int().min(5242880).default(5242880).describe("Size of each chunk in bytes (minimum 5MB per S3 spec)"), + scope: external_exports.string().default("user").describe("Target storage scope"), + bucket: external_exports.string().optional().describe("Specific bucket override (admin only)"), + metadata: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom metadata key-value pairs") +}); +var InitiateChunkedUploadResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + uploadId: external_exports.string().describe("Multipart upload session ID"), + resumeToken: external_exports.string().describe("Opaque token for resuming interrupted uploads"), + fileId: external_exports.string().describe("Assigned file ID"), + totalChunks: external_exports.number().int().min(1).describe("Expected number of chunks"), + chunkSize: external_exports.number().int().describe("Chunk size in bytes"), + expiresAt: external_exports.string().datetime().describe("Upload session expiration timestamp") + }) +}); +var UploadChunkRequestSchema2 = external_exports.object({ + uploadId: external_exports.string().describe("Multipart upload session ID"), + chunkIndex: external_exports.number().int().min(0).describe("Zero-based chunk index"), + resumeToken: external_exports.string().describe("Resume token from initiate response") +}); +var UploadChunkResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + chunkIndex: external_exports.number().int().describe("Chunk index that was uploaded"), + eTag: external_exports.string().describe("Chunk ETag for multipart completion"), + bytesReceived: external_exports.number().int().describe("Bytes received for this chunk") + }) +}); +var CompleteChunkedUploadRequestSchema2 = external_exports.object({ + uploadId: external_exports.string().describe("Multipart upload session ID"), + parts: external_exports.array(external_exports.object({ + chunkIndex: external_exports.number().int().describe("Chunk index"), + eTag: external_exports.string().describe("ETag returned from chunk upload") + })).min(1).describe("Ordered list of uploaded parts for assembly") +}); +var CompleteChunkedUploadResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + fileId: external_exports.string().describe("Final file ID"), + key: external_exports.string().describe("Storage key/path of the assembled file"), + size: external_exports.number().int().describe("Total file size in bytes"), + mimeType: external_exports.string().describe("File MIME type"), + eTag: external_exports.string().optional().describe("Final ETag of the assembled file"), + url: external_exports.string().optional().describe("Download URL for the assembled file") + }) +}); +var UploadProgressSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + uploadId: external_exports.string().describe("Multipart upload session ID"), + fileId: external_exports.string().describe("Assigned file ID"), + filename: external_exports.string().describe("Original filename"), + totalSize: external_exports.number().int().describe("Total file size in bytes"), + uploadedSize: external_exports.number().int().describe("Bytes uploaded so far"), + totalChunks: external_exports.number().int().describe("Total expected chunks"), + uploadedChunks: external_exports.number().int().describe("Number of chunks uploaded"), + percentComplete: external_exports.number().min(0).max(100).describe("Upload progress percentage"), + status: external_exports.enum(["in_progress", "completing", "completed", "failed", "expired"]).describe("Current upload session status"), + startedAt: external_exports.string().datetime().describe("Upload session start timestamp"), + expiresAt: external_exports.string().datetime().describe("Session expiration timestamp") + }) +}); +var StorageApiContracts = { + getPresignedUrl: { + method: "POST", + path: "/api/v1/storage/upload/presigned", + input: GetPresignedUrlRequestSchema2, + output: PresignedUrlResponseSchema2 + }, + completeUpload: { + method: "POST", + path: "/api/v1/storage/upload/complete", + input: CompleteUploadRequestSchema2, + output: FileUploadResponseSchema2 + }, + initiateChunkedUpload: { + method: "POST", + path: "/api/v1/storage/upload/chunked", + input: InitiateChunkedUploadRequestSchema2, + output: InitiateChunkedUploadResponseSchema2 + }, + uploadChunk: { + method: "PUT", + path: "/api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex", + input: UploadChunkRequestSchema2, + output: UploadChunkResponseSchema2 + }, + completeChunkedUpload: { + method: "POST", + path: "/api/v1/storage/upload/chunked/:uploadId/complete", + input: CompleteChunkedUploadRequestSchema2, + output: CompleteChunkedUploadResponseSchema2 + }, + getUploadProgress: { + method: "GET", + path: "/api/v1/storage/upload/chunked/:uploadId/progress", + output: UploadProgressSchema2 + } +}; +var ObjectDefinitionResponseSchema2 = BaseResponseSchema2.extend({ + data: ObjectSchema4.describe("Full Object Schema") +}); +var AppDefinitionResponseSchema2 = BaseResponseSchema2.extend({ + data: AppSchema3.describe("Full App Configuration") +}); +var ConceptListResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.array(external_exports.object({ + name: external_exports.string(), + label: external_exports.string(), + icon: external_exports.string().optional(), + description: external_exports.string().optional() + })).describe("List of available concepts (Objects, Apps, Flows)") +}); +var MetadataRegisterRequestSchema2 = external_exports.object({ + type: MetadataTypeSchema3.describe("Metadata type"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Item name (snake_case)"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), + namespace: external_exports.string().optional().describe("Optional namespace") +}); +var MetadataItemResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + definition: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata definition payload") + }).describe("Metadata item") +}); +var MetadataListResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Array of metadata definitions") +}); +var MetadataNamesResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.array(external_exports.string()).describe("Array of metadata item names") +}); +var MetadataExistsResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + exists: external_exports.boolean().describe("Whether the item exists") + }) +}); +var MetadataDeleteResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Deleted item name") + }) +}); +var MetadataQueryRequestSchema2 = MetadataQuerySchema3.describe( + "Metadata query with filtering, sorting, and pagination" +); +var MetadataQueryResponseSchema2 = BaseResponseSchema2.extend({ + data: MetadataQueryResultSchema3.describe("Paginated query result") +}); +var MetadataBulkRegisterRequestSchema22 = external_exports.object({ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name"), + data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload") + })).min(1).describe("Items to register"), + continueOnError: external_exports.boolean().default(false).describe("Continue on individual failure"), + validate: external_exports.boolean().default(true).describe("Validate before registering") +}); +var MetadataBulkUnregisterRequestSchema2 = external_exports.object({ + items: external_exports.array(external_exports.object({ + type: external_exports.string().describe("Metadata type"), + name: external_exports.string().describe("Item name") + })).min(1).describe("Items to unregister") +}); +var MetadataBulkResponseSchema2 = BaseResponseSchema2.extend({ + data: MetadataBulkResultSchema3.describe("Bulk operation result") +}); +var MetadataOverlayResponseSchema2 = BaseResponseSchema2.extend({ + data: MetadataOverlaySchema3.optional().describe("Overlay definition, undefined if none") +}); +var MetadataOverlaySaveRequestSchema2 = MetadataOverlaySchema3.describe( + "Overlay to save" +); +var MetadataEffectiveResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Effective metadata with all overlays applied") +}); +var MetadataExportRequestSchema2 = external_exports.object({ + types: external_exports.array(external_exports.string()).optional().describe("Filter by metadata types"), + namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), + format: external_exports.enum(["json", "yaml"]).default("json").describe("Export format") +}); +var MetadataExportResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.unknown().describe("Exported metadata bundle") +}); +var MetadataImportRequestSchema2 = external_exports.object({ + data: external_exports.unknown().describe("Metadata bundle to import"), + conflictResolution: external_exports.enum(["skip", "overwrite", "merge"]).default("skip").describe("Conflict resolution strategy"), + validate: external_exports.boolean().default(true).describe("Validate before import"), + dryRun: external_exports.boolean().default(false).describe("Dry run (no save)") +}); +var MetadataImportResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + total: external_exports.number().int().min(0), + imported: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + failed: external_exports.number().int().min(0), + errors: external_exports.array(external_exports.object({ + type: external_exports.string(), + name: external_exports.string(), + error: external_exports.string() + })).optional() + }).describe("Import result") +}); +var MetadataValidateRequestSchema2 = external_exports.object({ + type: external_exports.string().describe("Metadata type to validate against"), + data: external_exports.unknown().describe("Metadata payload to validate") +}); +var MetadataValidateResponseSchema2 = BaseResponseSchema2.extend({ + data: MetadataValidationResultSchema3.describe("Validation result") +}); +var MetadataTypesResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.array(external_exports.string()).describe("Registered metadata type identifiers") +}); +var MetadataTypeInfoResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + type: external_exports.string().describe("Metadata type identifier"), + label: external_exports.string().describe("Display label"), + description: external_exports.string().optional().describe("Description"), + filePatterns: external_exports.array(external_exports.string()).describe("File glob patterns"), + supportsOverlay: external_exports.boolean().describe("Overlay support"), + domain: external_exports.string().describe("Protocol domain") + }).optional().describe("Type info") +}); +var MetadataDependenciesResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.array(MetadataDependencySchema3).describe("Items this item depends on") +}); +var MetadataDependentsResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.array(MetadataDependencySchema3).describe("Items that depend on this item") +}); +var DispatcherRouteSchema2 = external_exports.object({ + /** + * URL path prefix for routing. + * Incoming requests matching this prefix are routed to the target service. + * Must start with '/'. + */ + prefix: external_exports.string().regex(/^\//).describe("URL path prefix for routing (e.g. /api/v1/data)"), + /** + * Target core service name. + * The service that handles requests matching this prefix. + */ + service: CoreServiceName3.describe("Target core service name"), + /** + * Whether requests to this route require authentication. + * Discovery endpoint is typically public; most others require auth. + * @default true + */ + authRequired: external_exports.boolean().default(true).describe("Whether authentication is required"), + /** + * Service criticality level. + * Determines behavior when the service is unavailable: + * - required: return 500 Internal Server Error + * - core: return 503 with degraded notice + * - optional: return 503 Service Unavailable + * @default 'optional' + */ + criticality: ServiceCriticalitySchema3.default("optional").describe("Service criticality level for unavailability handling"), + /** + * Required permissions for accessing this route namespace. + * Applied as a baseline before individual endpoint permission checks. + */ + permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions for this route namespace") +}); +var DispatcherConfigSchema2 = external_exports.object({ + /** + * Registered route mappings. + * Routes are matched by longest-prefix-first strategy. + */ + routes: external_exports.array(DispatcherRouteSchema2).describe("Route-to-service mappings"), + /** + * Behavior when no route matches the request. + * - 404: Return 404 Not Found (default) + * - proxy: Forward to a configured proxy target + * - custom: Delegate to a custom handler + * @default '404' + */ + fallback: external_exports.enum(["404", "proxy", "custom"]).default("404").describe("Behavior when no route matches"), + /** + * Proxy target URL for fallback: 'proxy' mode. + */ + proxyTarget: external_exports.string().url().optional().describe('Proxy target URL when fallback is "proxy"') +}); +var DEFAULT_DISPATCHER_ROUTES = [ + // Discovery (public) + { prefix: "/api/v1/discovery", service: "metadata", authRequired: false, criticality: "required" }, + // Health (public) + { prefix: "/api/v1/health", service: "metadata", authRequired: false, criticality: "required" }, + // Required Services + { prefix: "/api/v1/meta", service: "metadata", criticality: "required" }, + { prefix: "/api/v1/data", service: "data", criticality: "required" }, + { prefix: "/api/v1/auth", service: "auth", criticality: "required" }, + // Optional Services (plugin-provided) + { prefix: "/api/v1/packages", service: "metadata" }, + { prefix: "/api/v1/ui", service: "ui" }, + // @deprecated — use /api/v1/meta/view and /api/v1/meta/dashboard instead + { prefix: "/api/v1/workflow", service: "workflow" }, + { prefix: "/api/v1/analytics", service: "analytics" }, + { prefix: "/api/v1/automation", service: "automation" }, + { prefix: "/api/v1/storage", service: "file-storage" }, + { prefix: "/api/v1/feed", service: "data" }, + { prefix: "/api/v1/i18n", service: "i18n" }, + { prefix: "/api/v1/notifications", service: "notification" }, + { prefix: "/api/v1/realtime", service: "realtime" }, + { prefix: "/api/v1/ai", service: "ai" } +]; +var DispatcherErrorCode2 = external_exports.enum(["404", "405", "501", "503"]).describe( + "404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable" +); +var DispatcherErrorResponseSchema2 = external_exports.object({ + /** Always `false` for error responses */ + success: external_exports.literal(false), + error: external_exports.object({ + /** HTTP status code */ + code: external_exports.number().int().describe("HTTP status code (404, 405, 501, 503, \u2026)"), + /** Human-readable error message */ + message: external_exports.string().describe("Human-readable error message"), + /** + * Machine-readable error type for programmatic branching. + */ + type: external_exports.enum([ + "ROUTE_NOT_FOUND", + "METHOD_NOT_ALLOWED", + "NOT_IMPLEMENTED", + "SERVICE_UNAVAILABLE" + ]).optional().describe("Machine-readable error type"), + /** Route that was requested */ + route: external_exports.string().optional().describe("Requested route path"), + /** Service that the route maps to (if known) */ + service: external_exports.string().optional().describe("Target service name, if resolvable"), + /** Guidance for the developer */ + hint: external_exports.string().optional().describe('Actionable hint for the developer (e.g., "Install plugin-workflow")') + }) +}); +var RestApiRouteCategory2 = external_exports.enum([ + "discovery", + // API discovery and capabilities + "metadata", + // Metadata operations (objects, fields, views) + "data", + // Data CRUD operations + "batch", + // Batch/bulk operations + "permission", + // Permission/authorization checks + "analytics", + // Analytics and reporting + "automation", + // Automation triggers and flows + "workflow", + // Workflow state management + "ui", + // UI metadata (views, layouts) + "realtime", + // Realtime/WebSocket + "notification", + // Notification management + "ai", + // AI operations (NLQ, chat) + "i18n" + // Internationalization +]); +var HandlerStatusSchema2 = external_exports.enum(["implemented", "stub", "planned"]); +var RestApiEndpointSchema2 = external_exports.object({ + /** + * HTTP method + */ + method: HttpMethod5.describe("HTTP method for this endpoint"), + /** + * URL path pattern (supports parameters like :id) + */ + path: external_exports.string().describe("URL path pattern (e.g., /api/v1/data/:object/:id)"), + /** + * Handler reference (protocol method name) + */ + handler: external_exports.string().describe("Protocol method name or handler identifier"), + /** + * Route category + */ + category: RestApiRouteCategory2.describe("Route category"), + /** + * Whether endpoint is publicly accessible (no auth required) + */ + public: external_exports.boolean().default(false).describe("Is publicly accessible without authentication"), + /** + * Required permissions + */ + permissions: external_exports.array(external_exports.string()).optional().describe('Required permissions (e.g., ["data.read", "object.account.read"])'), + /** + * OpenAPI documentation metadata + */ + summary: external_exports.string().optional().describe("Short description for OpenAPI"), + description: external_exports.string().optional().describe("Detailed description for OpenAPI"), + tags: external_exports.array(external_exports.string()).optional().describe("OpenAPI tags for grouping"), + /** + * Request/Response schema references + */ + requestSchema: external_exports.string().optional().describe("Request schema name (for validation)"), + responseSchema: external_exports.string().optional().describe("Response schema name (for documentation)"), + /** + * Performance and reliability settings + */ + timeout: external_exports.number().int().optional().describe("Request timeout in milliseconds"), + rateLimit: external_exports.string().optional().describe("Rate limit policy name"), + cacheable: external_exports.boolean().default(false).describe("Whether response can be cached"), + cacheTtl: external_exports.number().int().optional().describe("Cache TTL in seconds"), + /** + * Handler implementation status. + * Tracks whether this endpoint has a real handler or is only declared. + * + * - `implemented` – A real handler is coded and registered. + * - `stub` – A placeholder handler exists that returns 501 Not Implemented. + * - `planned` – Declared in the protocol spec but not yet implemented. + * @default 'implemented' + */ + handlerStatus: HandlerStatusSchema2.optional().describe("Handler implementation status: implemented (default if omitted), stub, or planned") +}); +var RestApiRouteRegistrationSchema2 = external_exports.object({ + /** + * URL prefix for this route group (e.g., /api/v1/data) + */ + prefix: external_exports.string().regex(/^\//).describe("URL path prefix for this route group"), + /** + * Service name that handles these routes + */ + service: external_exports.string().describe("Core service name (metadata, data, auth, etc.)"), + /** + * Route category + */ + category: RestApiRouteCategory2.describe("Primary category for this route group"), + /** + * Protocol methods implemented + */ + methods: external_exports.array(external_exports.string()).optional().describe("Protocol method names implemented"), + /** + * Detailed endpoint definitions + */ + endpoints: external_exports.array(RestApiEndpointSchema2).optional().describe("Endpoint definitions"), + /** + * Middleware applied to all routes in this group + */ + middleware: external_exports.array(MiddlewareConfigSchema3).optional().describe("Middleware stack for this route group"), + /** + * Whether authentication is required for all routes + */ + authRequired: external_exports.boolean().default(true).describe("Whether authentication is required by default"), + /** + * OpenAPI documentation + */ + documentation: external_exports.object({ + title: external_exports.string().optional().describe("Route group title"), + description: external_exports.string().optional().describe("Route group description"), + tags: external_exports.array(external_exports.string()).optional().describe("OpenAPI tags") + }).optional().describe("Documentation metadata for this route group") +}); +var ValidationMode2 = external_exports.enum([ + "strict", + // Reject requests with validation errors (400 Bad Request) + "permissive", + // Log validation errors but allow request to proceed + "strip" + // Remove invalid fields and continue with valid data +]); +var RequestValidationConfigSchema2 = external_exports.object({ + /** + * Enable request validation + */ + enabled: external_exports.boolean().default(true).describe("Enable automatic request validation"), + /** + * Validation mode + */ + mode: ValidationMode2.default("strict").describe("How to handle validation errors"), + /** + * Validate request body + */ + validateBody: external_exports.boolean().default(true).describe("Validate request body against schema"), + /** + * Validate query parameters + */ + validateQuery: external_exports.boolean().default(true).describe("Validate query string parameters"), + /** + * Validate URL parameters + */ + validateParams: external_exports.boolean().default(true).describe("Validate URL path parameters"), + /** + * Validate request headers + */ + validateHeaders: external_exports.boolean().default(false).describe("Validate request headers"), + /** + * Include detailed field errors in response + */ + includeFieldErrors: external_exports.boolean().default(true).describe("Include field-level error details in response"), + /** + * Custom error message prefix + */ + errorPrefix: external_exports.string().optional().describe("Custom prefix for validation error messages"), + /** + * Schema registry reference + */ + schemaRegistry: external_exports.string().optional().describe("Schema registry name to use for validation") +}); +var ResponseEnvelopeConfigSchema2 = external_exports.object({ + /** + * Enable response envelope wrapping + */ + enabled: external_exports.boolean().default(true).describe("Enable automatic response envelope wrapping"), + /** + * Include metadata object + */ + includeMetadata: external_exports.boolean().default(true).describe("Include meta object in responses"), + /** + * Include timestamp in metadata + */ + includeTimestamp: external_exports.boolean().default(true).describe("Include timestamp in response metadata"), + /** + * Include request ID in metadata + */ + includeRequestId: external_exports.boolean().default(true).describe("Include requestId in response metadata"), + /** + * Include request duration in metadata + */ + includeDuration: external_exports.boolean().default(false).describe("Include request duration in ms"), + /** + * Include trace ID for distributed tracing + */ + includeTraceId: external_exports.boolean().default(false).describe("Include distributed traceId"), + /** + * Custom metadata fields + */ + customMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata fields to include"), + /** + * Whether to wrap already-wrapped responses + */ + skipIfWrapped: external_exports.boolean().default(true).describe("Skip wrapping if response already has success field") +}); +var ErrorHandlingConfigSchema2 = external_exports.object({ + /** + * Enable standardized error handling + */ + enabled: external_exports.boolean().default(true).describe("Enable standardized error handling"), + /** + * Include stack traces in error responses (dev only) + */ + includeStackTrace: external_exports.boolean().default(false).describe("Include stack traces in error responses"), + /** + * Log errors to logger + */ + logErrors: external_exports.boolean().default(true).describe("Log errors to system logger"), + /** + * Expose internal error details + */ + exposeInternalErrors: external_exports.boolean().default(false).describe("Expose internal error details in responses"), + /** + * Include request ID in errors + */ + includeRequestId: external_exports.boolean().default(true).describe("Include requestId in error responses"), + /** + * Include timestamp in errors + */ + includeTimestamp: external_exports.boolean().default(true).describe("Include timestamp in error responses"), + /** + * Include error documentation URLs + */ + includeDocumentation: external_exports.boolean().default(true).describe("Include documentation URLs for errors"), + /** + * Documentation base URL + */ + documentationBaseUrl: external_exports.string().url().optional().describe("Base URL for error documentation"), + /** + * Custom error messages by code + */ + customErrorMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom error messages by error code"), + /** + * Sensitive fields to redact from error details + */ + redactFields: external_exports.array(external_exports.string()).optional().describe("Field names to redact from error details") +}); +var OpenApiGenerationConfigSchema2 = external_exports.object({ + /** + * Enable OpenAPI generation + */ + enabled: external_exports.boolean().default(true).describe("Enable automatic OpenAPI documentation generation"), + /** + * OpenAPI specification version + */ + version: external_exports.enum(["3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.1.0"]).default("3.0.3").describe("OpenAPI specification version"), + /** + * API title + */ + title: external_exports.string().default("ObjectStack API").describe("API title"), + /** + * API description + */ + description: external_exports.string().optional().describe("API description"), + /** + * API version + */ + apiVersion: external_exports.string().default("1.0.0").describe("API version"), + /** + * Output path for OpenAPI spec + */ + outputPath: external_exports.string().default("/api/docs/openapi.json").describe("URL path to serve OpenAPI JSON"), + /** + * UI path for Swagger/Redoc + */ + uiPath: external_exports.string().default("/api/docs").describe("URL path to serve documentation UI"), + /** + * UI framework to use + */ + uiFramework: external_exports.enum(["swagger-ui", "redoc", "rapidoc", "elements"]).default("swagger-ui").describe("Documentation UI framework"), + /** + * Include internal/admin endpoints + */ + includeInternal: external_exports.boolean().default(false).describe("Include internal endpoints in documentation"), + /** + * Generate JSON schemas from Zod + */ + generateSchemas: external_exports.boolean().default(true).describe("Auto-generate schemas from Zod definitions"), + /** + * Include examples in documentation + */ + includeExamples: external_exports.boolean().default(true).describe("Include request/response examples"), + /** + * Server URLs + */ + servers: external_exports.array(external_exports.object({ + url: external_exports.string().describe("Server URL"), + description: external_exports.string().optional().describe("Server description") + })).optional().describe("Server URLs for API"), + /** + * Contact information + */ + contact: external_exports.object({ + name: external_exports.string().optional(), + url: external_exports.string().url().optional(), + email: external_exports.string().email().optional() + }).optional().describe("API contact information"), + /** + * License information + */ + license: external_exports.object({ + name: external_exports.string().describe("License name"), + url: external_exports.string().url().optional().describe("License URL") + }).optional().describe("API license information"), + /** + * Security schemes + */ + securitySchemes: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["apiKey", "http", "oauth2", "openIdConnect"]), + scheme: external_exports.string().optional(), + bearerFormat: external_exports.string().optional() + })).optional().describe("Security scheme definitions") +}); +var RestApiPluginConfigSchema2 = external_exports.object({ + /** + * Enable REST API plugin + */ + enabled: external_exports.boolean().default(true).describe("Enable REST API plugin"), + /** + * API base path + */ + basePath: external_exports.string().default("/api").describe("Base path for all API routes"), + /** + * API version + */ + version: external_exports.string().default("v1").describe("API version identifier"), + /** + * Route registrations + */ + routes: external_exports.array(RestApiRouteRegistrationSchema2).describe("Route registrations"), + /** + * Request validation configuration + */ + validation: RequestValidationConfigSchema2.optional().describe("Request validation configuration"), + /** + * Response envelope configuration + */ + responseEnvelope: ResponseEnvelopeConfigSchema2.optional().describe("Response envelope configuration"), + /** + * Error handling configuration + */ + errorHandling: ErrorHandlingConfigSchema2.optional().describe("Error handling configuration"), + /** + * OpenAPI documentation configuration + */ + openApi: OpenApiGenerationConfigSchema2.optional().describe("OpenAPI documentation configuration"), + /** + * Global middleware applied to all routes + */ + globalMiddleware: external_exports.array(MiddlewareConfigSchema3).optional().describe("Global middleware stack"), + /** + * CORS configuration + */ + cors: external_exports.object({ + enabled: external_exports.boolean().default(true), + origins: external_exports.array(external_exports.string()).optional(), + methods: external_exports.array(HttpMethod5).optional(), + credentials: external_exports.boolean().default(true) + }).optional().describe("CORS configuration"), + /** + * Performance settings + */ + performance: external_exports.object({ + enableCompression: external_exports.boolean().default(true).describe("Enable response compression"), + enableETag: external_exports.boolean().default(true).describe("Enable ETag generation"), + enableCaching: external_exports.boolean().default(true).describe("Enable HTTP caching"), + defaultCacheTtl: external_exports.number().int().default(300).describe("Default cache TTL in seconds") + }).optional().describe("Performance optimization settings") +}); +var DEFAULT_DISCOVERY_ROUTES = { + prefix: "/api/v1/discovery", + service: "metadata", + category: "discovery", + methods: ["getDiscovery"], + authRequired: false, + endpoints: [{ + method: "GET", + path: "", + handler: "getDiscovery", + category: "discovery", + public: true, + summary: "Get API discovery information", + description: "Returns API version, capabilities, and available routes", + tags: ["Discovery"], + responseSchema: "GetDiscoveryResponseSchema", + cacheable: true, + cacheTtl: 3600 + // Cache for 1 hour as discovery info rarely changes + }], + middleware: [ + { name: "response_envelope", type: "transformation", enabled: true, order: 100 } + ] +}; +var DEFAULT_METADATA_ROUTES = { + prefix: "/api/v1/meta", + service: "metadata", + category: "metadata", + methods: ["getMetaTypes", "getMetaItems", "getMetaItem", "saveMetaItem"], + authRequired: true, + endpoints: [ + { + method: "GET", + path: "", + handler: "getMetaTypes", + category: "metadata", + public: false, + summary: "List all metadata types", + description: "Returns available metadata types (object, field, view, etc.)", + tags: ["Metadata"], + responseSchema: "GetMetaTypesResponseSchema", + cacheable: true, + cacheTtl: 3600 + }, + { + method: "GET", + path: "/:type", + handler: "getMetaItems", + category: "metadata", + public: false, + summary: "List metadata items of a type", + description: "Returns all items of the specified metadata type", + tags: ["Metadata"], + responseSchema: "GetMetaItemsResponseSchema", + cacheable: true, + cacheTtl: 3600 + }, + { + method: "GET", + path: "/:type/:name", + handler: "getMetaItem", + category: "metadata", + public: false, + summary: "Get specific metadata item", + description: "Returns a specific metadata item by type and name", + tags: ["Metadata"], + requestSchema: "GetMetaItemRequestSchema", + responseSchema: "GetMetaItemResponseSchema", + cacheable: true, + cacheTtl: 3600 + }, + { + method: "PUT", + path: "/:type/:name", + handler: "saveMetaItem", + category: "metadata", + public: false, + summary: "Create or update metadata item", + description: "Creates or updates a metadata item", + tags: ["Metadata"], + requestSchema: "SaveMetaItemRequestSchema", + responseSchema: "SaveMetaItemResponseSchema", + permissions: ["metadata.write"], + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 } + ] +}; +var DEFAULT_DATA_CRUD_ROUTES = { + prefix: "/api/v1/data", + service: "data", + category: "data", + methods: ["findData", "getData", "createData", "updateData", "deleteData"], + authRequired: true, + endpoints: [ + { + method: "GET", + path: "/:object", + handler: "findData", + category: "data", + public: false, + summary: "Query records", + description: "Query records with filtering, sorting, and pagination", + tags: ["Data"], + requestSchema: "FindDataRequestSchema", + responseSchema: "ListRecordResponseSchema", + permissions: ["data.read"], + cacheable: false + }, + { + method: "GET", + path: "/:object/:id", + handler: "getData", + category: "data", + public: false, + summary: "Get record by ID", + description: "Retrieve a single record by its ID", + tags: ["Data"], + requestSchema: "IdRequestSchema", + responseSchema: "SingleRecordResponseSchema", + permissions: ["data.read"], + cacheable: false + }, + { + method: "POST", + path: "/:object", + handler: "createData", + category: "data", + public: false, + summary: "Create record", + description: "Create a new record", + tags: ["Data"], + requestSchema: "CreateRequestSchema", + responseSchema: "SingleRecordResponseSchema", + permissions: ["data.create"], + cacheable: false + }, + { + method: "PATCH", + path: "/:object/:id", + handler: "updateData", + category: "data", + public: false, + summary: "Update record", + description: "Update an existing record", + tags: ["Data"], + requestSchema: "UpdateRequestSchema", + responseSchema: "SingleRecordResponseSchema", + permissions: ["data.update"], + cacheable: false + }, + { + method: "DELETE", + path: "/:object/:id", + handler: "deleteData", + category: "data", + public: false, + summary: "Delete record", + description: "Delete a record by ID", + tags: ["Data"], + requestSchema: "IdRequestSchema", + responseSchema: "DeleteResponseSchema", + permissions: ["data.delete"], + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, + { name: "error_handler", type: "error", enabled: true, order: 200 } + ] +}; +var DEFAULT_BATCH_ROUTES = { + prefix: "/api/v1/data/:object", + service: "data", + category: "batch", + methods: ["batchData", "createManyData", "updateManyData", "deleteManyData"], + authRequired: true, + endpoints: [ + { + method: "POST", + path: "/batch", + handler: "batchData", + category: "batch", + public: false, + summary: "Batch operation", + description: "Execute a batch operation (create, update, upsert, delete)", + tags: ["Batch"], + requestSchema: "BatchUpdateRequestSchema", + responseSchema: "BatchUpdateResponseSchema", + permissions: ["data.batch"], + timeout: 6e4, + // 60 seconds for batch operations + cacheable: false + }, + { + method: "POST", + path: "/createMany", + handler: "createManyData", + category: "batch", + public: false, + summary: "Batch create", + description: "Create multiple records in a single operation", + tags: ["Batch"], + requestSchema: "CreateManyRequestSchema", + responseSchema: "BatchUpdateResponseSchema", + permissions: ["data.create", "data.batch"], + timeout: 6e4, + cacheable: false + }, + { + method: "POST", + path: "/updateMany", + handler: "updateManyData", + category: "batch", + public: false, + summary: "Batch update", + description: "Update multiple records in a single operation", + tags: ["Batch"], + requestSchema: "UpdateManyRequestSchema", + responseSchema: "BatchUpdateResponseSchema", + permissions: ["data.update", "data.batch"], + timeout: 6e4, + cacheable: false + }, + { + method: "POST", + path: "/deleteMany", + handler: "deleteManyData", + category: "batch", + public: false, + summary: "Batch delete", + description: "Delete multiple records in a single operation", + tags: ["Batch"], + requestSchema: "DeleteManyRequestSchema", + responseSchema: "BatchUpdateResponseSchema", + permissions: ["data.delete", "data.batch"], + timeout: 6e4, + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, + { name: "error_handler", type: "error", enabled: true, order: 200 } + ] +}; +var DEFAULT_PERMISSION_ROUTES = { + prefix: "/api/v1/auth", + service: "auth", + category: "permission", + methods: ["checkPermission", "getObjectPermissions", "getEffectivePermissions"], + authRequired: true, + endpoints: [ + { + method: "POST", + path: "/check", + handler: "checkPermission", + category: "permission", + public: false, + summary: "Check permission", + description: "Check if current user has a specific permission", + tags: ["Permission"], + requestSchema: "CheckPermissionRequestSchema", + responseSchema: "CheckPermissionResponseSchema", + cacheable: false + }, + { + method: "GET", + path: "/permissions/:object", + handler: "getObjectPermissions", + category: "permission", + public: false, + summary: "Get object permissions", + description: "Get all permissions for a specific object", + tags: ["Permission"], + responseSchema: "ObjectPermissionsResponseSchema", + cacheable: true, + cacheTtl: 300 + }, + { + method: "GET", + path: "/permissions/effective", + handler: "getEffectivePermissions", + category: "permission", + public: false, + summary: "Get effective permissions", + description: "Get all effective permissions for current user", + tags: ["Permission"], + responseSchema: "EffectivePermissionsResponseSchema", + cacheable: true, + cacheTtl: 300 + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 } + ] +}; +var DEFAULT_VIEW_ROUTES = { + prefix: "/api/v1/ui", + service: "ui", + category: "ui", + methods: ["listViews", "getView", "createView", "updateView", "deleteView"], + authRequired: true, + endpoints: [ + { + method: "GET", + path: "/views/:object", + handler: "listViews", + category: "ui", + public: false, + summary: "List views for an object", + description: "Returns all views (list, form) for the specified object", + tags: ["Views", "UI"], + responseSchema: "ListViewsResponseSchema", + cacheable: true, + cacheTtl: 1800 + }, + { + method: "GET", + path: "/views/:object/:viewId", + handler: "getView", + category: "ui", + public: false, + summary: "Get a specific view", + description: "Returns a specific view definition by object and view ID", + tags: ["Views", "UI"], + responseSchema: "GetViewResponseSchema", + cacheable: true, + cacheTtl: 1800 + }, + { + method: "POST", + path: "/views/:object", + handler: "createView", + category: "ui", + public: false, + summary: "Create a new view", + description: "Creates a new view definition for the specified object", + tags: ["Views", "UI"], + requestSchema: "CreateViewRequestSchema", + responseSchema: "CreateViewResponseSchema", + permissions: ["ui.view.create"], + cacheable: false + }, + { + method: "PATCH", + path: "/views/:object/:viewId", + handler: "updateView", + category: "ui", + public: false, + summary: "Update a view", + description: "Updates an existing view definition", + tags: ["Views", "UI"], + requestSchema: "UpdateViewRequestSchema", + responseSchema: "UpdateViewResponseSchema", + permissions: ["ui.view.update"], + cacheable: false + }, + { + method: "DELETE", + path: "/views/:object/:viewId", + handler: "deleteView", + category: "ui", + public: false, + summary: "Delete a view", + description: "Deletes a view definition", + tags: ["Views", "UI"], + responseSchema: "DeleteViewResponseSchema", + permissions: ["ui.view.delete"], + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 } + ] +}; +var DEFAULT_WORKFLOW_ROUTES = { + prefix: "/api/v1/workflow", + service: "workflow", + category: "workflow", + methods: ["getWorkflowConfig", "getWorkflowState", "workflowTransition", "workflowApprove", "workflowReject"], + authRequired: true, + endpoints: [ + { + method: "GET", + path: "/:object/config", + handler: "getWorkflowConfig", + category: "workflow", + public: false, + summary: "Get workflow configuration", + description: "Returns workflow rules and state machine configuration for an object", + tags: ["Workflow"], + responseSchema: "GetWorkflowConfigResponseSchema", + cacheable: true, + cacheTtl: 3600 + }, + { + method: "GET", + path: "/:object/:recordId/state", + handler: "getWorkflowState", + category: "workflow", + public: false, + summary: "Get workflow state", + description: "Returns current workflow state and available transitions for a record", + tags: ["Workflow"], + responseSchema: "GetWorkflowStateResponseSchema", + cacheable: false + }, + { + method: "POST", + path: "/:object/:recordId/transition", + handler: "workflowTransition", + category: "workflow", + public: false, + summary: "Execute workflow transition", + description: "Transitions a record to a new workflow state", + tags: ["Workflow"], + requestSchema: "WorkflowTransitionRequestSchema", + responseSchema: "WorkflowTransitionResponseSchema", + permissions: ["workflow.transition"], + cacheable: false + }, + { + method: "POST", + path: "/:object/:recordId/approve", + handler: "workflowApprove", + category: "workflow", + public: false, + summary: "Approve workflow step", + description: "Approves a pending workflow approval step", + tags: ["Workflow"], + requestSchema: "WorkflowApproveRequestSchema", + responseSchema: "WorkflowApproveResponseSchema", + permissions: ["workflow.approve"], + cacheable: false + }, + { + method: "POST", + path: "/:object/:recordId/reject", + handler: "workflowReject", + category: "workflow", + public: false, + summary: "Reject workflow step", + description: "Rejects a pending workflow approval step", + tags: ["Workflow"], + requestSchema: "WorkflowRejectRequestSchema", + responseSchema: "WorkflowRejectResponseSchema", + permissions: ["workflow.reject"], + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, + { name: "error_handler", type: "error", enabled: true, order: 200 } + ] +}; +var DEFAULT_REALTIME_ROUTES = { + prefix: "/api/v1/realtime", + service: "realtime", + category: "realtime", + methods: ["realtimeConnect", "realtimeDisconnect", "realtimeSubscribe", "realtimeUnsubscribe", "setPresence", "getPresence"], + authRequired: true, + endpoints: [ + { + method: "POST", + path: "/connect", + handler: "realtimeConnect", + category: "realtime", + public: false, + summary: "Establish realtime connection", + description: "Negotiates a realtime connection (WebSocket/SSE) and returns connection details", + tags: ["Realtime"], + requestSchema: "RealtimeConnectRequestSchema", + responseSchema: "RealtimeConnectResponseSchema", + cacheable: false + }, + { + method: "POST", + path: "/disconnect", + handler: "realtimeDisconnect", + category: "realtime", + public: false, + summary: "Close realtime connection", + description: "Closes an active realtime connection", + tags: ["Realtime"], + requestSchema: "RealtimeDisconnectRequestSchema", + responseSchema: "RealtimeDisconnectResponseSchema", + cacheable: false + }, + { + method: "POST", + path: "/subscribe", + handler: "realtimeSubscribe", + category: "realtime", + public: false, + summary: "Subscribe to channel", + description: "Subscribes to a realtime channel for receiving events", + tags: ["Realtime"], + requestSchema: "RealtimeSubscribeRequestSchema", + responseSchema: "RealtimeSubscribeResponseSchema", + cacheable: false + }, + { + method: "POST", + path: "/unsubscribe", + handler: "realtimeUnsubscribe", + category: "realtime", + public: false, + summary: "Unsubscribe from channel", + description: "Unsubscribes from a realtime channel", + tags: ["Realtime"], + requestSchema: "RealtimeUnsubscribeRequestSchema", + responseSchema: "RealtimeUnsubscribeResponseSchema", + cacheable: false + }, + { + method: "PUT", + path: "/presence/:channel", + handler: "setPresence", + category: "realtime", + public: false, + summary: "Set presence state", + description: "Sets the current user's presence state in a channel", + tags: ["Realtime"], + requestSchema: "SetPresenceRequestSchema", + responseSchema: "SetPresenceResponseSchema", + cacheable: false + }, + { + method: "GET", + path: "/presence/:channel", + handler: "getPresence", + category: "realtime", + public: false, + summary: "Get channel presence", + description: "Returns all active members and their presence state in a channel", + tags: ["Realtime"], + responseSchema: "GetPresenceResponseSchema", + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 } + ] +}; +var DEFAULT_NOTIFICATION_ROUTES = { + prefix: "/api/v1/notifications", + service: "notification", + category: "notification", + methods: [ + "registerDevice", + "unregisterDevice", + "getNotificationPreferences", + "updateNotificationPreferences", + "listNotifications", + "markNotificationsRead", + "markAllNotificationsRead" + ], + authRequired: true, + endpoints: [ + { + method: "POST", + path: "/devices", + handler: "registerDevice", + category: "notification", + public: false, + summary: "Register device for push notifications", + description: "Registers a device token for receiving push notifications", + tags: ["Notifications"], + requestSchema: "RegisterDeviceRequestSchema", + responseSchema: "RegisterDeviceResponseSchema", + cacheable: false + }, + { + method: "DELETE", + path: "/devices/:deviceId", + handler: "unregisterDevice", + category: "notification", + public: false, + summary: "Unregister device", + description: "Removes a device from push notification registration", + tags: ["Notifications"], + responseSchema: "UnregisterDeviceResponseSchema", + cacheable: false + }, + { + method: "GET", + path: "/preferences", + handler: "getNotificationPreferences", + category: "notification", + public: false, + summary: "Get notification preferences", + description: "Returns current user notification preferences", + tags: ["Notifications"], + responseSchema: "GetNotificationPreferencesResponseSchema", + cacheable: false + }, + { + method: "PATCH", + path: "/preferences", + handler: "updateNotificationPreferences", + category: "notification", + public: false, + summary: "Update notification preferences", + description: "Updates user notification preferences", + tags: ["Notifications"], + requestSchema: "UpdateNotificationPreferencesRequestSchema", + responseSchema: "UpdateNotificationPreferencesResponseSchema", + cacheable: false + }, + { + method: "GET", + path: "", + handler: "listNotifications", + category: "notification", + public: false, + summary: "List notifications", + description: "Returns paginated list of notifications for the current user", + tags: ["Notifications"], + responseSchema: "ListNotificationsResponseSchema", + cacheable: false + }, + { + method: "POST", + path: "/read", + handler: "markNotificationsRead", + category: "notification", + public: false, + summary: "Mark notifications as read", + description: "Marks specific notifications as read by their IDs", + tags: ["Notifications"], + requestSchema: "MarkNotificationsReadRequestSchema", + responseSchema: "MarkNotificationsReadResponseSchema", + cacheable: false + }, + { + method: "POST", + path: "/read/all", + handler: "markAllNotificationsRead", + category: "notification", + public: false, + summary: "Mark all notifications as read", + description: "Marks all notifications as read for the current user", + tags: ["Notifications"], + responseSchema: "MarkAllNotificationsReadResponseSchema", + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 } + ] +}; +var DEFAULT_AI_ROUTES = { + prefix: "/api/v1/ai", + service: "ai", + category: "ai", + methods: ["aiNlq", "aiSuggest", "aiInsights"], + authRequired: true, + endpoints: [ + { + method: "POST", + path: "/nlq", + handler: "aiNlq", + category: "ai", + public: false, + summary: "Natural language query", + description: "Converts a natural language query to a structured query AST", + tags: ["AI"], + requestSchema: "AiNlqRequestSchema", + responseSchema: "AiNlqResponseSchema", + timeout: 3e4, + cacheable: false + }, + // AI chat route removed — wire protocol aligned with Vercel AI SDK. + // The chat endpoint should use Vercel's `toDataStreamResponse()` directly. + { + method: "POST", + path: "/suggest", + handler: "aiSuggest", + category: "ai", + public: false, + summary: "Get AI-powered suggestions", + description: "Returns AI-generated field value suggestions based on context", + tags: ["AI"], + requestSchema: "AiSuggestRequestSchema", + responseSchema: "AiSuggestResponseSchema", + timeout: 15e3, + cacheable: false + }, + { + method: "POST", + path: "/insights", + handler: "aiInsights", + category: "ai", + public: false, + summary: "Get AI-generated insights", + description: "Returns AI-generated insights (summaries, trends, anomalies, recommendations)", + tags: ["AI"], + requestSchema: "AiInsightsRequestSchema", + responseSchema: "AiInsightsResponseSchema", + timeout: 6e4, + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, + { name: "error_handler", type: "error", enabled: true, order: 200 } + ] +}; +var DEFAULT_I18N_ROUTES = { + prefix: "/api/v1/i18n", + service: "i18n", + category: "i18n", + methods: ["getLocales", "getTranslations", "getFieldLabels"], + authRequired: true, + endpoints: [ + { + method: "GET", + path: "/locales", + handler: "getLocales", + category: "i18n", + public: false, + summary: "Get available locales", + description: "Returns all available locales with their metadata", + tags: ["i18n"], + responseSchema: "GetLocalesResponseSchema", + cacheable: true, + cacheTtl: 86400 + // 24 hours — locales change very rarely + }, + { + method: "GET", + path: "/translations/:locale", + handler: "getTranslations", + category: "i18n", + public: false, + summary: "Get translations for a locale", + description: "Returns translation strings for the specified locale and optional namespace", + tags: ["i18n"], + responseSchema: "GetTranslationsResponseSchema", + cacheable: true, + cacheTtl: 3600 + }, + { + method: "GET", + path: "/labels/:object/:locale", + handler: "getFieldLabels", + category: "i18n", + public: false, + summary: "Get translated field labels", + description: "Returns translated field labels, help text, and option labels for an object", + tags: ["i18n"], + responseSchema: "GetFieldLabelsResponseSchema", + cacheable: true, + cacheTtl: 3600 + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 } + ] +}; +var DEFAULT_ANALYTICS_ROUTES = { + prefix: "/api/v1/analytics", + service: "analytics", + category: "analytics", + methods: ["analyticsQuery", "getAnalyticsMeta"], + authRequired: true, + endpoints: [ + { + method: "POST", + path: "/query", + handler: "analyticsQuery", + category: "analytics", + public: false, + summary: "Execute analytics query", + description: "Executes a structured analytics query against the semantic layer", + tags: ["Analytics"], + requestSchema: "AnalyticsQueryRequestSchema", + responseSchema: "AnalyticsResultResponseSchema", + permissions: ["analytics.query"], + timeout: 12e4, + // 2 minutes for analytics queries + cacheable: false + }, + { + method: "GET", + path: "/meta", + handler: "getAnalyticsMeta", + category: "analytics", + public: false, + summary: "Get analytics metadata", + description: "Returns available cubes, dimensions, measures, and segments", + tags: ["Analytics"], + responseSchema: "AnalyticsMetadataResponseSchema", + cacheable: true, + cacheTtl: 3600 + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, + { name: "error_handler", type: "error", enabled: true, order: 200 } + ] +}; +var DEFAULT_AUTOMATION_ROUTES = { + prefix: "/api/v1/automation", + service: "automation", + category: "automation", + methods: ["triggerAutomation"], + authRequired: true, + endpoints: [ + { + method: "POST", + path: "/trigger", + handler: "triggerAutomation", + category: "automation", + public: false, + summary: "Trigger automation", + description: "Triggers an automation flow or script by name", + tags: ["Automation"], + requestSchema: "AutomationTriggerRequestSchema", + responseSchema: "AutomationTriggerResponseSchema", + permissions: ["automation.trigger"], + timeout: 12e4, + // 2 minutes for long-running automations + cacheable: false + } + ], + middleware: [ + { name: "auth", type: "authentication", enabled: true, order: 10 }, + { name: "validation", type: "validation", enabled: true, order: 20 }, + { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, + { name: "error_handler", type: "error", enabled: true, order: 200 } + ] +}; +var RestApiPluginConfig2 = Object.assign(RestApiPluginConfigSchema2, { + create: (config4) => config4 +}); +var RestApiRouteRegistration2 = Object.assign(RestApiRouteRegistrationSchema2, { + create: (registration) => registration +}); +function getDefaultRouteRegistrations() { + return [ + DEFAULT_DISCOVERY_ROUTES, + DEFAULT_METADATA_ROUTES, + DEFAULT_DATA_CRUD_ROUTES, + DEFAULT_BATCH_ROUTES, + DEFAULT_PERMISSION_ROUTES, + DEFAULT_VIEW_ROUTES, + DEFAULT_WORKFLOW_ROUTES, + DEFAULT_REALTIME_ROUTES, + DEFAULT_NOTIFICATION_ROUTES, + DEFAULT_AI_ROUTES, + DEFAULT_I18N_ROUTES, + DEFAULT_ANALYTICS_ROUTES, + DEFAULT_AUTOMATION_ROUTES + ]; +} +var RouteCoverageEntrySchema2 = external_exports.object({ + /** Full URL path of the endpoint */ + path: external_exports.string().describe("Full URL path (e.g. /api/v1/analytics/query)"), + /** HTTP method */ + method: HttpMethod5.describe("HTTP method (GET, POST, etc.)"), + /** Route category */ + category: RestApiRouteCategory2.describe("Route category"), + /** Handler implementation status */ + handlerStatus: HandlerStatusSchema2.describe("Handler status"), + /** Target service */ + service: external_exports.string().describe("Target service name"), + /** Whether the handler was successfully called during health check */ + healthCheckPassed: external_exports.boolean().optional().describe("Whether the health check probe succeeded") +}); +var RouteCoverageReportSchema2 = external_exports.object({ + /** ISO 8601 timestamp of report generation */ + timestamp: external_exports.string().describe("ISO 8601 timestamp"), + /** Adapter that generated the report */ + adapter: external_exports.string().describe('Adapter name (e.g. "hono", "express", "nextjs")'), + /** Summary counters */ + summary: external_exports.object({ + total: external_exports.number().int().describe("Total declared endpoints"), + implemented: external_exports.number().int().describe("Endpoints with real handlers"), + stub: external_exports.number().int().describe("Endpoints with stub handlers (501)"), + planned: external_exports.number().int().describe("Endpoints not yet implemented") + }), + /** Per-endpoint entries */ + entries: external_exports.array(RouteCoverageEntrySchema2).describe("Per-endpoint coverage entries") +}); +var QueryAdapterTargetSchema2 = external_exports.enum([ + "rest", + // REST API (?filter[field][op]=value) + "graphql", + // GraphQL (where: \{ field: \{ op: value \}\}) + "odata" + // OData ($filter=field op value) +]); +var OperatorMappingSchema2 = external_exports.object({ + /** Unified DSL operator (e.g., 'eq', 'gt', 'contains') */ + operator: external_exports.string().describe("Unified DSL operator"), + /** REST query parameter format (e.g., 'filter[{field}][{op}]') */ + rest: external_exports.string().optional().describe("REST query parameter template"), + /** GraphQL where clause format (e.g., '{field}: { {op}: $value }') */ + graphql: external_exports.string().optional().describe("GraphQL where clause template"), + /** OData $filter expression format (e.g., '{field} {op} {value}') */ + odata: external_exports.string().optional().describe("OData $filter expression template") +}); +var RestQueryAdapterSchema2 = external_exports.object({ + /** Filter parameter style */ + filterStyle: external_exports.enum([ + "bracket", + // ?filter[field][op]=value (JSON API style) + "dot", + // ?filter.field.op=value + "flat", + // ?field=value (simple equality) + "rsql" + // ?filter=field==value;field=gt=10 (RSQL / FIQL) + ]).default("bracket").describe("REST filter parameter encoding style"), + /** Pagination parameter names */ + pagination: external_exports.object({ + /** Page size parameter name */ + limitParam: external_exports.string().default("limit").describe("Page size parameter name"), + /** Offset parameter name */ + offsetParam: external_exports.string().default("offset").describe("Offset parameter name"), + /** Cursor parameter name (for cursor-based pagination) */ + cursorParam: external_exports.string().default("cursor").describe("Cursor parameter name"), + /** Page number parameter name (for page-based pagination) */ + pageParam: external_exports.string().default("page").describe("Page number parameter name") + }).optional().describe("Pagination parameter name mappings"), + /** Sort parameter name and format */ + sorting: external_exports.object({ + /** Sort parameter name */ + param: external_exports.string().default("sort").describe("Sort parameter name"), + /** Sort format */ + format: external_exports.enum([ + "comma", + // ?sort=field1,-field2 + "array", + // ?sort[]=field1&sort[]=-field2 + "pipe" + // ?sort=field1|asc,field2|desc + ]).default("comma").describe("Sort parameter encoding format") + }).optional().describe("Sort parameter mapping"), + /** Field selection parameter name */ + fieldsParam: external_exports.string().default("fields").describe("Field selection parameter name") +}); +var GraphQLQueryAdapterSchema2 = external_exports.object({ + /** Filter argument name in GraphQL queries */ + filterArgName: external_exports.string().default("where").describe("GraphQL filter argument name"), + /** Filter nesting style */ + filterStyle: external_exports.enum([ + "nested", + // where: { field: { op: value } } (Prisma style) + "flat", + // where: { field_op: value } (Hasura style) + "array" + // where: [{ field, op, value }] (Array of conditions) + ]).default("nested").describe("GraphQL filter nesting style"), + /** Pagination argument names */ + pagination: external_exports.object({ + limitArg: external_exports.string().default("limit").describe("Page size argument name"), + offsetArg: external_exports.string().default("offset").describe("Offset argument name"), + firstArg: external_exports.string().default("first").describe('Relay "first" argument name'), + afterArg: external_exports.string().default("after").describe('Relay "after" cursor argument name') + }).optional().describe("Pagination argument name mappings"), + /** Sort argument configuration */ + sorting: external_exports.object({ + argName: external_exports.string().default("orderBy").describe("Sort argument name"), + format: external_exports.enum([ + "enum", + // orderBy: { field: ASC } + "array" + // orderBy: [{ field: "name", direction: "ASC" }] + ]).default("enum").describe("Sort argument format") + }).optional().describe("Sort argument mapping") +}); +var ODataQueryAdapterSchema2 = external_exports.object({ + /** OData version */ + version: external_exports.enum(["v2", "v4"]).default("v4").describe("OData version"), + /** System query option prefixes */ + usePrefix: external_exports.boolean().default(true).describe("Use $ prefix for system query options ($filter vs filter)"), + /** String function support */ + stringFunctions: external_exports.array(external_exports.enum([ + "contains", + "startswith", + "endswith", + "tolower", + "toupper", + "trim", + "concat", + "substring", + "length" + ])).optional().describe("Supported OData string functions"), + /** Expand (nested resource) configuration */ + expand: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable $expand support"), + maxDepth: external_exports.number().int().min(1).default(3).describe("Maximum expand depth") + }).optional().describe("$expand configuration") +}); +var QueryAdapterConfigSchema2 = external_exports.object({ + /** Default operator mappings */ + operatorMappings: external_exports.array(OperatorMappingSchema2).optional().describe("Custom operator mappings"), + /** REST adapter configuration */ + rest: RestQueryAdapterSchema2.optional().describe("REST query adapter configuration"), + /** GraphQL adapter configuration */ + graphql: GraphQLQueryAdapterSchema2.optional().describe("GraphQL query adapter configuration"), + /** OData adapter configuration */ + odata: ODataQueryAdapterSchema2.optional().describe("OData query adapter configuration") +}); +var FeedPathParamsSchema2 = external_exports.object({ + object: external_exports.string().describe('Object name (e.g., "account")'), + recordId: external_exports.string().describe("Record ID") +}); +var FeedItemPathParamsSchema2 = FeedPathParamsSchema2.extend({ + feedId: external_exports.string().describe("Feed item ID") +}); +var FeedListFilterType2 = external_exports.enum([ + "all", + "comments_only", + "changes_only", + "tasks_only" +]); +var GetFeedRequestSchema2 = FeedPathParamsSchema2.extend({ + type: FeedListFilterType2.default("all").describe("Filter by feed item category"), + limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of items to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination (opaque string from previous response)") +}); +var GetFeedResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + items: external_exports.array(FeedItemSchema3).describe("Feed items in reverse chronological order"), + total: external_exports.number().int().optional().describe("Total feed items matching filter"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more items are available") + }) +}); +var CreateFeedItemRequestSchema2 = FeedPathParamsSchema2.extend({ + type: FeedItemType4.describe("Type of feed item to create"), + body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), + mentions: external_exports.array(MentionSchema4).optional().describe("Mentioned users, teams, or records"), + parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), + visibility: FeedVisibility4.default("public").describe("Visibility: public, internal, or private") +}); +var CreateFeedItemResponseSchema2 = BaseResponseSchema2.extend({ + data: FeedItemSchema3.describe("The created feed item") +}); +var UpdateFeedItemRequestSchema2 = FeedItemPathParamsSchema2.extend({ + body: external_exports.string().optional().describe("Updated rich text body"), + mentions: external_exports.array(MentionSchema4).optional().describe("Updated mentions"), + visibility: FeedVisibility4.optional().describe("Updated visibility") +}); +var UpdateFeedItemResponseSchema2 = BaseResponseSchema2.extend({ + data: FeedItemSchema3.describe("The updated feed item") +}); +var DeleteFeedItemRequestSchema = FeedItemPathParamsSchema2; +var DeleteFeedItemResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the deleted feed item") + }) +}); +var AddReactionRequestSchema2 = FeedItemPathParamsSchema2.extend({ + emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")') +}); +var AddReactionResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + reactions: external_exports.array(ReactionSchema4).describe("Updated reaction list for the feed item") + }) +}); +var RemoveReactionRequestSchema2 = FeedItemPathParamsSchema2.extend({ + emoji: external_exports.string().describe("Emoji character or shortcode to remove") +}); +var RemoveReactionResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + reactions: external_exports.array(ReactionSchema4).describe("Updated reaction list for the feed item") + }) +}); +var PinFeedItemRequestSchema = FeedItemPathParamsSchema2; +var PinFeedItemResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the pinned feed item"), + pinned: external_exports.boolean().describe("Whether the item is now pinned"), + pinnedAt: external_exports.string().datetime().describe("Timestamp when pinned") + }) +}); +var UnpinFeedItemRequestSchema = FeedItemPathParamsSchema2; +var UnpinFeedItemResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the unpinned feed item"), + pinned: external_exports.boolean().describe("Whether the item is now pinned (should be false)") + }) +}); +var StarFeedItemRequestSchema = FeedItemPathParamsSchema2; +var StarFeedItemResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the starred feed item"), + starred: external_exports.boolean().describe("Whether the item is now starred"), + starredAt: external_exports.string().datetime().describe("Timestamp when starred") + }) +}); +var UnstarFeedItemRequestSchema = FeedItemPathParamsSchema2; +var UnstarFeedItemResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + feedId: external_exports.string().describe("ID of the unstarred feed item"), + starred: external_exports.boolean().describe("Whether the item is now starred (should be false)") + }) +}); +var SearchFeedRequestSchema2 = FeedPathParamsSchema2.extend({ + query: external_exports.string().min(1).describe("Full-text search query against feed body content"), + type: FeedListFilterType2.optional().describe("Filter by feed item category"), + actorId: external_exports.string().optional().describe("Filter by actor user ID"), + dateFrom: external_exports.string().datetime().optional().describe("Filter feed items created after this timestamp"), + dateTo: external_exports.string().datetime().optional().describe("Filter feed items created before this timestamp"), + hasAttachments: external_exports.boolean().optional().describe("Filter for items with file attachments"), + pinnedOnly: external_exports.boolean().optional().describe("Return only pinned items"), + starredOnly: external_exports.boolean().optional().describe("Return only starred items"), + limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of items to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination") +}); +var SearchFeedResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + items: external_exports.array(FeedItemSchema3).describe("Matching feed items sorted by relevance"), + total: external_exports.number().int().optional().describe("Total matching items"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more items are available") + }) +}); +var GetChangelogRequestSchema2 = FeedPathParamsSchema2.extend({ + field: external_exports.string().optional().describe("Filter changelog to a specific field name"), + actorId: external_exports.string().optional().describe("Filter changelog by actor user ID"), + dateFrom: external_exports.string().datetime().optional().describe("Filter changes after this timestamp"), + dateTo: external_exports.string().datetime().optional().describe("Filter changes before this timestamp"), + limit: external_exports.number().int().min(1).max(200).default(50).describe("Maximum number of changelog entries to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination") +}); +var ChangelogEntrySchema2 = external_exports.object({ + id: external_exports.string().describe("Changelog entry ID"), + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + actor: external_exports.object({ + type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), + id: external_exports.string().describe("Actor ID"), + name: external_exports.string().optional().describe("Actor display name") + }).describe("Who made the change"), + changes: external_exports.array(FieldChangeEntrySchema4).min(1).describe("Field-level changes"), + timestamp: external_exports.string().datetime().describe("When the change occurred"), + source: external_exports.string().optional().describe('Change source (e.g., "API", "UI", "automation")') +}); +var GetChangelogResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + entries: external_exports.array(ChangelogEntrySchema2).describe("Changelog entries in reverse chronological order"), + total: external_exports.number().int().optional().describe("Total changelog entries matching filter"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more entries are available") + }) +}); +var SubscribeRequestSchema2 = FeedPathParamsSchema2.extend({ + events: external_exports.array(SubscriptionEventType3).default(["all"]).describe("Event types to subscribe to"), + channels: external_exports.array(NotificationChannel3).default(["in_app"]).describe("Notification delivery channels") +}); +var SubscribeResponseSchema2 = BaseResponseSchema2.extend({ + data: RecordSubscriptionSchema3.describe("The created or updated subscription") +}); +var FeedUnsubscribeRequestSchema = FeedPathParamsSchema2; +var UnsubscribeResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + object: external_exports.string().describe("Object name"), + recordId: external_exports.string().describe("Record ID"), + unsubscribed: external_exports.boolean().describe("Whether the user was unsubscribed") + }) +}); +var FeedApiErrorCode2 = external_exports.enum([ + "feed_item_not_found", + "feed_permission_denied", + "feed_item_not_editable", + "feed_invalid_parent", + "reaction_already_exists", + "reaction_not_found", + "subscription_already_exists", + "subscription_not_found", + "invalid_feed_type", + "feed_already_pinned", + "feed_not_pinned", + "feed_already_starred", + "feed_not_starred", + "feed_search_query_too_short" +]); +var FeedApiContracts = { + listFeed: { + method: "GET", + path: "/api/data/:object/:recordId/feed", + input: GetFeedRequestSchema2, + output: GetFeedResponseSchema2 + }, + createFeedItem: { + method: "POST", + path: "/api/data/:object/:recordId/feed", + input: CreateFeedItemRequestSchema2, + output: CreateFeedItemResponseSchema2 + }, + updateFeedItem: { + method: "PUT", + path: "/api/data/:object/:recordId/feed/:feedId", + input: UpdateFeedItemRequestSchema2, + output: UpdateFeedItemResponseSchema2 + }, + deleteFeedItem: { + method: "DELETE", + path: "/api/data/:object/:recordId/feed/:feedId", + input: DeleteFeedItemRequestSchema, + output: DeleteFeedItemResponseSchema2 + }, + addReaction: { + method: "POST", + path: "/api/data/:object/:recordId/feed/:feedId/reactions", + input: AddReactionRequestSchema2, + output: AddReactionResponseSchema2 + }, + removeReaction: { + method: "DELETE", + path: "/api/data/:object/:recordId/feed/:feedId/reactions/:emoji", + input: RemoveReactionRequestSchema2, + output: RemoveReactionResponseSchema2 + }, + pinFeedItem: { + method: "POST", + path: "/api/data/:object/:recordId/feed/:feedId/pin", + input: PinFeedItemRequestSchema, + output: PinFeedItemResponseSchema2 + }, + unpinFeedItem: { + method: "DELETE", + path: "/api/data/:object/:recordId/feed/:feedId/pin", + input: UnpinFeedItemRequestSchema, + output: UnpinFeedItemResponseSchema2 + }, + starFeedItem: { + method: "POST", + path: "/api/data/:object/:recordId/feed/:feedId/star", + input: StarFeedItemRequestSchema, + output: StarFeedItemResponseSchema2 + }, + unstarFeedItem: { + method: "DELETE", + path: "/api/data/:object/:recordId/feed/:feedId/star", + input: UnstarFeedItemRequestSchema, + output: UnstarFeedItemResponseSchema2 + }, + searchFeed: { + method: "GET", + path: "/api/data/:object/:recordId/feed/search", + input: SearchFeedRequestSchema2, + output: SearchFeedResponseSchema2 + }, + getChangelog: { + method: "GET", + path: "/api/data/:object/:recordId/changelog", + input: GetChangelogRequestSchema2, + output: GetChangelogResponseSchema2 + }, + subscribe: { + method: "POST", + path: "/api/data/:object/:recordId/subscribe", + input: SubscribeRequestSchema2, + output: SubscribeResponseSchema2 + }, + unsubscribe: { + method: "DELETE", + path: "/api/data/:object/:recordId/subscribe", + input: FeedUnsubscribeRequestSchema, + output: UnsubscribeResponseSchema2 + } +}; +var ExportFormat2 = external_exports.enum([ + "csv", + "json", + "jsonl", + "xlsx", + "parquet" +]); +var ExportJobStatus2 = external_exports.enum([ + "pending", + "processing", + "completed", + "failed", + "cancelled", + "expired" +]); +var CreateExportJobRequestSchema2 = external_exports.object({ + object: external_exports.string().describe("Object name to export"), + format: ExportFormat2.default("csv").describe("Export file format"), + fields: external_exports.array(external_exports.string()).optional().describe("Specific fields to include (omit for all fields)"), + filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria for records to export"), + sort: external_exports.array(external_exports.object({ + field: external_exports.string().describe("Field name to sort by"), + direction: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction") + })).optional().describe("Sort order for exported records"), + limit: external_exports.number().int().min(1).optional().describe("Maximum number of records to export"), + includeHeaders: external_exports.boolean().default(true).describe("Include header row (CSV/XLSX)"), + encoding: external_exports.string().default("utf-8").describe("Character encoding for the export file"), + templateId: external_exports.string().optional().describe("Export template ID for predefined field mappings") +}); +var CreateExportJobResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + jobId: external_exports.string().describe("Export job ID"), + status: ExportJobStatus2.describe("Initial job status"), + estimatedRecords: external_exports.number().int().optional().describe("Estimated total records"), + createdAt: external_exports.string().datetime().describe("Job creation timestamp") + }) +}); +var ExportJobProgressSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + jobId: external_exports.string().describe("Export job ID"), + status: ExportJobStatus2.describe("Current job status"), + format: ExportFormat2.describe("Export format"), + totalRecords: external_exports.number().int().optional().describe("Total records to export"), + processedRecords: external_exports.number().int().describe("Records processed so far"), + percentComplete: external_exports.number().min(0).max(100).describe("Export progress percentage"), + fileSize: external_exports.number().int().optional().describe("Current file size in bytes"), + downloadUrl: external_exports.string().optional().describe('Presigned download URL (available when status is "completed")'), + downloadExpiresAt: external_exports.string().datetime().optional().describe("Download URL expiration timestamp"), + error: external_exports.object({ + code: external_exports.string().describe("Error code"), + message: external_exports.string().describe("Error message") + }).optional().describe("Error details if job failed"), + startedAt: external_exports.string().datetime().optional().describe("Processing start timestamp"), + completedAt: external_exports.string().datetime().optional().describe("Completion timestamp") + }) +}); +var ImportValidationMode2 = external_exports.enum([ + "strict", + // Reject entire import on any validation error + "lenient", + // Skip invalid records, import valid ones + "dry_run" + // Validate all records without persisting +]); +var DeduplicationStrategy2 = external_exports.enum([ + "skip", + // Skip duplicates (keep existing) + "update", + // Update existing with import data + "create_new", + // Create new record even if duplicate + "fail" + // Fail the import if duplicates found +]); +var ImportValidationConfigSchema2 = external_exports.object({ + mode: ImportValidationMode2.default("strict").describe("Validation mode for the import"), + deduplication: external_exports.object({ + strategy: DeduplicationStrategy2.default("skip").describe("How to handle duplicate records"), + matchFields: external_exports.array(external_exports.string()).min(1).describe('Fields used to identify duplicates (e.g., "email", "external_id")') + }).optional().describe("Deduplication configuration"), + maxErrors: external_exports.number().int().min(1).default(100).describe("Maximum validation errors before aborting"), + trimWhitespace: external_exports.boolean().default(true).describe("Trim leading/trailing whitespace from string fields"), + dateFormat: external_exports.string().optional().describe('Expected date format in import data (e.g., "YYYY-MM-DD")'), + nullValues: external_exports.array(external_exports.string()).optional().describe('Strings to treat as null (e.g., ["", "N/A", "null"])') +}); +var ImportValidationResultSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + totalRecords: external_exports.number().int().describe("Total records in import file"), + validRecords: external_exports.number().int().describe("Records that passed validation"), + invalidRecords: external_exports.number().int().describe("Records that failed validation"), + duplicateRecords: external_exports.number().int().describe("Duplicate records detected"), + errors: external_exports.array(external_exports.object({ + row: external_exports.number().int().describe("Row number in the import file"), + field: external_exports.string().optional().describe("Field that failed validation"), + code: external_exports.string().describe("Validation error code"), + message: external_exports.string().describe("Validation error message") + })).describe("List of validation errors"), + preview: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Preview of first N valid records (for dry_run mode)") + }) +}); +var FieldMappingEntrySchema2 = external_exports.object({ + sourceField: external_exports.string().describe("Field name in the source data (import) or object (export)"), + targetField: external_exports.string().describe("Field name in the target object (import) or file column (export)"), + targetLabel: external_exports.string().optional().describe("Display label for the target column (export)"), + transform: external_exports.enum(["none", "uppercase", "lowercase", "trim", "date_format", "lookup"]).default("none").describe("Transformation to apply during mapping"), + defaultValue: external_exports.unknown().optional().describe("Default value if source field is null/empty"), + required: external_exports.boolean().default(false).describe("Whether this field is required (import validation)") +}); +var ExportImportTemplateSchema2 = external_exports.object({ + id: external_exports.string().optional().describe("Template ID (generated on save)"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Template machine name (snake_case)"), + label: external_exports.string().describe("Human-readable template label"), + description: external_exports.string().optional().describe("Template description"), + object: external_exports.string().describe("Target object name"), + direction: external_exports.enum(["import", "export", "bidirectional"]).describe("Template direction"), + format: ExportFormat2.optional().describe("Default file format for this template"), + mappings: external_exports.array(FieldMappingEntrySchema2).min(1).describe("Field mapping entries"), + createdAt: external_exports.string().datetime().optional().describe("Template creation timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + createdBy: external_exports.string().optional().describe("User who created the template") +}); +var ScheduledExportSchema2 = external_exports.object({ + id: external_exports.string().optional().describe("Scheduled export ID"), + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Schedule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label"), + object: external_exports.string().describe("Object name to export"), + format: ExportFormat2.default("csv").describe("Export file format"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to include"), + filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record filter criteria"), + templateId: external_exports.string().optional().describe("Export template ID for field mappings"), + schedule: external_exports.object({ + cronExpression: external_exports.string().describe("Cron expression for schedule"), + timezone: external_exports.string().default("UTC").describe("IANA timezone") + }).describe("Schedule timing configuration"), + delivery: external_exports.object({ + method: external_exports.enum(["email", "storage", "webhook"]).describe("How to deliver the export file"), + recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients (for email delivery)"), + storagePath: external_exports.string().optional().describe("Storage path (for storage delivery)"), + webhookUrl: external_exports.string().optional().describe("Webhook URL (for webhook delivery)") + }).describe("Export delivery configuration"), + enabled: external_exports.boolean().default(true).describe("Whether the scheduled export is active"), + lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp"), + nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution"), + createdAt: external_exports.string().datetime().optional().describe("Creation timestamp"), + createdBy: external_exports.string().optional().describe("User who created the schedule") +}); +var GetExportJobDownloadRequestSchema2 = external_exports.object({ + jobId: external_exports.string().describe("Export job ID") +}); +var GetExportJobDownloadResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + jobId: external_exports.string().describe("Export job ID"), + downloadUrl: external_exports.string().describe("Presigned download URL"), + fileName: external_exports.string().describe("Suggested file name"), + fileSize: external_exports.number().int().describe("File size in bytes"), + format: ExportFormat2.describe("Export file format"), + expiresAt: external_exports.string().datetime().describe("Download URL expiration timestamp"), + checksum: external_exports.string().optional().describe("File checksum (SHA-256)") + }) +}); +var ListExportJobsRequestSchema2 = external_exports.object({ + object: external_exports.string().optional().describe("Filter by object name"), + status: ExportJobStatus2.optional().describe("Filter by job status"), + limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of jobs to return"), + cursor: external_exports.string().optional().describe("Pagination cursor from a previous response") +}); +var ExportJobSummarySchema2 = external_exports.object({ + jobId: external_exports.string().describe("Export job ID"), + object: external_exports.string().describe("Object name that was exported"), + status: ExportJobStatus2.describe("Current job status"), + format: ExportFormat2.describe("Export file format"), + totalRecords: external_exports.number().int().optional().describe("Total records exported"), + fileSize: external_exports.number().int().optional().describe("File size in bytes"), + createdAt: external_exports.string().datetime().describe("Job creation timestamp"), + completedAt: external_exports.string().datetime().optional().describe("Completion timestamp"), + createdBy: external_exports.string().optional().describe("User who initiated the export") +}); +var ListExportJobsResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + jobs: external_exports.array(ExportJobSummarySchema2).describe("List of export jobs"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more jobs are available") + }) +}); +var ScheduleExportRequestSchema2 = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Schedule name (snake_case)"), + label: external_exports.string().optional().describe("Human-readable label"), + object: external_exports.string().describe("Object name to export"), + format: ExportFormat2.default("csv").describe("Export file format"), + fields: external_exports.array(external_exports.string()).optional().describe("Fields to include"), + filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record filter criteria"), + templateId: external_exports.string().optional().describe("Export template ID for field mappings"), + schedule: external_exports.object({ + cronExpression: external_exports.string().describe("Cron expression for schedule"), + timezone: external_exports.string().default("UTC").describe("IANA timezone") + }).describe("Schedule timing configuration"), + delivery: external_exports.object({ + method: external_exports.enum(["email", "storage", "webhook"]).describe("How to deliver the export file"), + recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients (for email delivery)"), + storagePath: external_exports.string().optional().describe("Storage path (for storage delivery)"), + webhookUrl: external_exports.string().optional().describe("Webhook URL (for webhook delivery)") + }).describe("Export delivery configuration") +}); +var ScheduleExportResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + id: external_exports.string().describe("Scheduled export ID"), + name: external_exports.string().describe("Schedule name"), + enabled: external_exports.boolean().describe("Whether the schedule is active"), + nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution"), + createdAt: external_exports.string().datetime().describe("Creation timestamp") + }) +}); +var ExportApiContracts2 = { + createExportJob: { + method: "POST", + path: "/api/v1/data/:object/export", + input: CreateExportJobRequestSchema2, + output: CreateExportJobResponseSchema2 + }, + getExportJobProgress: { + method: "GET", + path: "/api/v1/data/export/:jobId", + input: external_exports.object({ jobId: external_exports.string() }), + output: ExportJobProgressSchema2 + }, + getExportJobDownload: { + method: "GET", + path: "/api/v1/data/export/:jobId/download", + input: GetExportJobDownloadRequestSchema2, + output: GetExportJobDownloadResponseSchema2 + }, + listExportJobs: { + method: "GET", + path: "/api/v1/data/export", + input: ListExportJobsRequestSchema2, + output: ListExportJobsResponseSchema2 + }, + scheduleExport: { + method: "POST", + path: "/api/v1/data/export/schedules", + input: ScheduleExportRequestSchema2, + output: ScheduleExportResponseSchema2 + }, + cancelExportJob: { + method: "POST", + path: "/api/v1/data/export/:jobId/cancel", + input: external_exports.object({ jobId: external_exports.string() }), + output: BaseResponseSchema2 + } +}; +var FlowNodeAction2 = external_exports.enum([ + "start", + // Trigger + "end", + // Return/Stop + "decision", + // If/Else logic + "assignment", + // Set Variable + "loop", + // For Each + "create_record", + // CRUD: Create + "update_record", + // CRUD: Update + "delete_record", + // CRUD: Delete + "get_record", + // CRUD: Get/Query + "http_request", + // Webhook/API Call + "script", + // Custom Script (JS/TS) + "screen", + // Screen / User-Input Element + "wait", + // Delay/Sleep + "subflow", + // Call another flow + "connector_action", + // Zapier-style integration action + "parallel_gateway", + // BPMN Parallel Gateway — AND-split (all outgoing branches execute concurrently) + "join_gateway", + // BPMN Join Gateway — AND-join (waits for all incoming branches to complete) + "boundary_event" + // BPMN Boundary Event — attached to a host node for timer/error/signal interrupts +]); +var FlowVariableSchema2 = external_exports.object({ + name: external_exports.string().describe("Variable name"), + type: external_exports.string().describe("Data type (text, number, boolean, object, list)"), + isInput: external_exports.boolean().default(false).describe("Is input parameter"), + isOutput: external_exports.boolean().default(false).describe("Is output parameter") +}); +var FlowNodeSchema2 = external_exports.object({ + id: external_exports.string().describe("Node unique ID"), + type: FlowNodeAction2.describe("Action type"), + label: external_exports.string().describe("Node label"), + /** Node Configuration Options (Specific to type) */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Node configuration"), + /** + * Connector Action Configuration + * Used when type is 'connector_action' + */ + connectorConfig: external_exports.object({ + connectorId: external_exports.string(), + actionId: external_exports.string(), + input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Mapped inputs for the action") + }).optional(), + /** UI Position (for the canvas) */ + position: external_exports.object({ x: external_exports.number(), y: external_exports.number() }).optional(), + /** Node-level execution timeout */ + timeoutMs: external_exports.number().int().min(0).optional().describe("Maximum execution time for this node in milliseconds"), + /** Node input schema declaration for Studio form generation and runtime validation */ + inputSchema: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["string", "number", "boolean", "object", "array"]).describe("Parameter type"), + required: external_exports.boolean().default(false).describe("Whether the parameter is required"), + description: external_exports.string().optional().describe("Parameter description") + })).optional().describe("Input parameter schema for this node"), + /** Node output schema declaration */ + outputSchema: external_exports.record(external_exports.string(), external_exports.object({ + type: external_exports.enum(["string", "number", "boolean", "object", "array"]).describe("Output type"), + description: external_exports.string().optional().describe("Output description") + })).optional().describe("Output schema declaration for this node"), + /** + * Wait Event Configuration (for 'wait' nodes) + * Defines what external event or condition should resume the paused execution. + * Industry alignment: BPMN Intermediate Catch Events, Temporal Signals. + */ + waitEventConfig: external_exports.object({ + /** Type of event to wait for */ + eventType: external_exports.enum(["timer", "signal", "webhook", "manual", "condition"]).describe("What kind of event resumes the execution"), + /** Duration to wait (ISO 8601 duration or milliseconds) — for timer events */ + timerDuration: external_exports.string().optional().describe('ISO 8601 duration (e.g., "PT1H") or wait time for timer events'), + /** Signal name to listen for — for signal/webhook events */ + signalName: external_exports.string().optional().describe("Named signal or webhook event to wait for"), + /** Timeout before auto-failing or continuing — optional guard */ + timeoutMs: external_exports.number().int().min(0).optional().describe("Maximum wait time before timeout (ms)"), + /** Action to take on timeout */ + onTimeout: external_exports.enum(["fail", "continue"]).default("fail").describe("Behavior when the wait times out") + }).optional().describe("Configuration for wait node event resumption"), + /** + * Boundary Event Configuration (for 'boundary_event' nodes) + * Attaches an event handler to a host activity node (BPMN Boundary Event pattern). + * Industry alignment: BPMN Boundary Error/Timer/Signal Events. + */ + boundaryConfig: external_exports.object({ + /** ID of the host node this boundary event is attached to */ + attachedToNodeId: external_exports.string().describe("Host node ID this boundary event monitors"), + /** Type of boundary event */ + eventType: external_exports.enum(["error", "timer", "signal", "cancel"]).describe("Boundary event trigger type"), + /** Whether the boundary event interrupts the host activity */ + interrupting: external_exports.boolean().default(true).describe("If true, the host activity is cancelled when this event fires"), + /** Error code filter — only for error boundary events */ + errorCode: external_exports.string().optional().describe("Specific error code to catch (empty = catch all errors)"), + /** Timer duration — only for timer boundary events */ + timerDuration: external_exports.string().optional().describe("ISO 8601 duration for timer boundary events"), + /** Signal name — only for signal boundary events */ + signalName: external_exports.string().optional().describe("Named signal to catch") + }).optional().describe("Configuration for boundary events attached to host nodes") +}); +var FlowEdgeSchema2 = external_exports.object({ + id: external_exports.string().describe("Edge unique ID"), + source: external_exports.string().describe("Source Node ID"), + target: external_exports.string().describe("Target Node ID"), + /** Condition for this path (only for decision/branch nodes) */ + condition: external_exports.string().optional().describe("Expression returning boolean used for branching"), + type: external_exports.enum(["default", "fault", "conditional"]).default("default").describe("Connection type: default (normal flow), fault (error path), or conditional (expression-guarded)"), + label: external_exports.string().optional().describe("Label on the connector"), + /** + * Default Sequence Flow marker (BPMN Default Flow semantics). + * When true, this edge is taken when no sibling conditional edges match. + * Only meaningful on outgoing edges of decision/gateway nodes. + */ + isDefault: external_exports.boolean().default(false).describe("Marks this edge as the default path when no other conditions match") +}); +var FlowSchema2 = external_exports.object({ + /** Identity */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name"), + label: external_exports.string().describe("Flow label"), + description: external_exports.string().optional(), + /** Metadata & Versioning */ + version: external_exports.number().int().default(1).describe("Version number"), + status: external_exports.enum(["draft", "active", "obsolete", "invalid"]).default("draft").describe("Deployment status"), + template: external_exports.boolean().default(false).describe("Is logic template (Subflow)"), + /** Trigger Type */ + type: external_exports.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).describe("Flow type"), + /** Configuration Variables */ + variables: external_exports.array(FlowVariableSchema2).optional().describe("Flow variables"), + /** Graph Definition */ + nodes: external_exports.array(FlowNodeSchema2).describe("Flow nodes"), + edges: external_exports.array(FlowEdgeSchema2).describe("Flow connections"), + /** Execution Config */ + active: external_exports.boolean().default(false).describe("Is active (Deprecated: use status)"), + runAs: external_exports.enum(["system", "user"]).default("user").describe("Execution context"), + /** Error Handling Strategy */ + errorHandling: external_exports.object({ + strategy: external_exports.enum(["fail", "retry", "continue"]).default("fail").describe("How to handle node execution errors"), + maxRetries: external_exports.number().int().min(0).max(10).default(0).describe("Number of retry attempts (only for retry strategy)"), + retryDelayMs: external_exports.number().int().min(0).default(1e3).describe("Delay between retries in milliseconds"), + backoffMultiplier: external_exports.number().min(1).default(1).describe("Multiplier for exponential backoff between retries"), + maxRetryDelayMs: external_exports.number().int().min(0).default(3e4).describe("Maximum delay between retries in milliseconds"), + jitter: external_exports.boolean().default(false).describe("Add random jitter to retry delay to avoid thundering herd"), + fallbackNodeId: external_exports.string().optional().describe("Node ID to jump to on unrecoverable error") + }).optional().describe("Flow-level error handling configuration") +}); +function defineFlow(config4) { + return FlowSchema2.parse(config4); +} +var FlowVersionHistorySchema = external_exports.object({ + flowName: external_exports.string().describe("Flow machine name"), + version: external_exports.number().int().min(1).describe("Version number"), + definition: FlowSchema2.describe("Complete flow definition snapshot"), + createdAt: external_exports.string().datetime().describe("When this version was created"), + createdBy: external_exports.string().optional().describe("User who created this version"), + changeNote: external_exports.string().optional().describe("Description of what changed in this version") +}); +var ExecutionStatus2 = external_exports.enum([ + "pending", + // Queued, not yet started + "running", + // Currently executing + "paused", + // Paused at a wait/checkpoint node + "completed", + // Successfully finished + "failed", + // Terminated with error + "cancelled", + // Manually cancelled + "timed_out", + // Exceeded max execution time + "retrying" + // Failed and retrying +]); +var ExecutionStepLogSchema2 = external_exports.object({ + nodeId: external_exports.string().describe("Node ID that was executed"), + nodeType: external_exports.string().describe('Node action type (e.g., "decision", "http_request")'), + nodeLabel: external_exports.string().optional().describe("Human-readable node label"), + status: external_exports.enum(["success", "failure", "skipped"]).describe("Step execution result"), + startedAt: external_exports.string().datetime().describe("When the step started"), + completedAt: external_exports.string().datetime().optional().describe("When the step completed"), + durationMs: external_exports.number().int().min(0).optional().describe("Step execution duration in milliseconds"), + input: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Input data passed to the node"), + output: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Output data produced by the node"), + error: external_exports.object({ + code: external_exports.string().describe("Error code"), + message: external_exports.string().describe("Error message"), + stack: external_exports.string().optional().describe("Stack trace") + }).optional().describe("Error details if step failed"), + retryAttempt: external_exports.number().int().min(0).optional().describe("Retry attempt number (0 = first try)") +}); +var ExecutionLogSchema2 = external_exports.object({ + /** Unique execution ID */ + id: external_exports.string().describe("Execution instance ID"), + /** Flow reference */ + flowName: external_exports.string().describe("Machine name of the executed flow"), + flowVersion: external_exports.number().int().optional().describe("Version of the flow that was executed"), + /** Execution status */ + status: ExecutionStatus2.describe("Current execution status"), + /** Trigger context */ + trigger: external_exports.object({ + type: external_exports.string().describe('Trigger type (e.g., "record_change", "schedule", "api", "manual")'), + recordId: external_exports.string().optional().describe("Triggering record ID"), + object: external_exports.string().optional().describe("Triggering object name"), + userId: external_exports.string().optional().describe("User who triggered the execution"), + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional trigger context") + }).describe("What triggered this execution"), + /** Step-by-step execution history */ + steps: external_exports.array(ExecutionStepLogSchema2).describe("Ordered list of executed steps"), + /** Execution variables snapshot */ + variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Final state of flow variables"), + /** Timing */ + startedAt: external_exports.string().datetime().describe("Execution start timestamp"), + completedAt: external_exports.string().datetime().optional().describe("Execution completion timestamp"), + durationMs: external_exports.number().int().min(0).optional().describe("Total execution duration in milliseconds"), + /** Context */ + runAs: external_exports.enum(["system", "user"]).optional().describe("Execution context identity"), + tenantId: external_exports.string().optional().describe("Tenant ID for multi-tenant isolation") +}); +var ExecutionErrorSeverity2 = external_exports.enum([ + "warning", + // Non-fatal issue (e.g., deprecated node type) + "error", + // Node-level failure (may be retried) + "critical" + // Flow-level failure (execution terminated) +]); +var ExecutionErrorSchema = external_exports.object({ + id: external_exports.string().describe("Error record ID"), + executionId: external_exports.string().describe("Parent execution ID"), + nodeId: external_exports.string().optional().describe("Node where the error occurred"), + severity: ExecutionErrorSeverity2.describe("Error severity level"), + code: external_exports.string().describe("Machine-readable error code"), + message: external_exports.string().describe("Human-readable error message"), + stack: external_exports.string().optional().describe("Stack trace for debugging"), + context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional diagnostic context (input data, config snapshot)"), + timestamp: external_exports.string().datetime().describe("When the error occurred"), + retryable: external_exports.boolean().default(false).describe("Whether this error can be retried"), + resolvedAt: external_exports.string().datetime().optional().describe("When the error was resolved (e.g., after successful retry)") +}); +var CheckpointSchema = external_exports.object({ + /** Unique checkpoint ID */ + id: external_exports.string().describe("Checkpoint ID"), + /** Execution reference */ + executionId: external_exports.string().describe("Parent execution ID"), + flowName: external_exports.string().describe("Flow machine name"), + /** State snapshot */ + currentNodeId: external_exports.string().describe("Node ID where execution is paused"), + variables: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Flow variable state at checkpoint"), + completedNodeIds: external_exports.array(external_exports.string()).describe("List of node IDs already executed"), + /** Timing */ + createdAt: external_exports.string().datetime().describe("Checkpoint creation timestamp"), + expiresAt: external_exports.string().datetime().optional().describe("Checkpoint expiration (auto-cleanup)"), + /** Reason */ + reason: external_exports.enum(["wait", "screen_input", "approval", "error", "manual_pause", "parallel_join", "boundary_event"]).describe("Why the execution was checkpointed") +}); +var ConcurrencyPolicySchema = external_exports.object({ + /** Maximum concurrent executions of this flow */ + maxConcurrent: external_exports.number().int().min(1).default(1).describe("Maximum number of concurrent executions allowed"), + /** What to do when max concurrency is reached */ + onConflict: external_exports.enum(["queue", "reject", "cancel_existing"]).default("queue").describe("queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance"), + /** Lock scope for concurrency */ + lockScope: external_exports.enum(["global", "per_record", "per_user"]).default("global").describe("Scope of the concurrency lock"), + /** Queue timeout (only when onConflict is "queue") */ + queueTimeoutMs: external_exports.number().int().min(0).optional().describe("Maximum time to wait in queue before timing out (ms)") +}); +var ScheduleStateSchema = external_exports.object({ + /** Unique schedule ID */ + id: external_exports.string().describe("Schedule instance ID"), + /** Flow reference */ + flowName: external_exports.string().describe("Flow machine name"), + /** Schedule configuration */ + cronExpression: external_exports.string().describe('Cron expression (e.g., "0 9 * * MON-FRI")'), + timezone: external_exports.string().default("UTC").describe("IANA timezone for cron evaluation"), + /** Runtime state */ + status: external_exports.enum(["active", "paused", "disabled", "expired"]).default("active").describe("Current schedule status"), + nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution timestamp"), + lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp"), + lastExecutionId: external_exports.string().optional().describe("Execution ID of the last run"), + lastRunStatus: ExecutionStatus2.optional().describe("Status of the last run"), + /** Execution tracking */ + totalRuns: external_exports.number().int().min(0).default(0).describe("Total number of executions"), + consecutiveFailures: external_exports.number().int().min(0).default(0).describe("Consecutive failed executions"), + /** Bounds */ + startDate: external_exports.string().datetime().optional().describe("Schedule effective start date"), + endDate: external_exports.string().datetime().optional().describe("Schedule expiration date"), + maxRuns: external_exports.number().int().min(1).optional().describe("Maximum total executions before auto-disable"), + /** Metadata */ + createdAt: external_exports.string().datetime().describe("Schedule creation timestamp"), + updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), + createdBy: external_exports.string().optional().describe("User who created the schedule") +}); +var AutomationFlowPathParamsSchema2 = external_exports.object({ + name: external_exports.string().describe("Flow machine name (snake_case)") +}); +var AutomationRunPathParamsSchema2 = AutomationFlowPathParamsSchema2.extend({ + runId: external_exports.string().describe("Execution run ID") +}); +var ListFlowsRequestSchema2 = external_exports.object({ + status: external_exports.enum(["draft", "active", "obsolete", "invalid"]).optional().describe("Filter by flow status"), + type: external_exports.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).optional().describe("Filter by flow type"), + limit: external_exports.number().int().min(1).max(100).default(50).describe("Maximum number of flows to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination") +}); +var FlowSummarySchema2 = external_exports.object({ + name: external_exports.string().describe("Flow machine name"), + label: external_exports.string().describe("Flow display label"), + type: external_exports.string().describe("Flow type"), + status: external_exports.string().describe("Flow deployment status"), + version: external_exports.number().int().describe("Flow version number"), + enabled: external_exports.boolean().describe("Whether the flow is enabled for execution"), + nodeCount: external_exports.number().int().optional().describe("Number of nodes in the flow"), + lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp") +}); +var ListFlowsResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + flows: external_exports.array(FlowSummarySchema2).describe("Flow summaries"), + total: external_exports.number().int().optional().describe("Total matching flows"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more flows are available") + }) +}); +var GetFlowRequestSchema = AutomationFlowPathParamsSchema2; +var GetFlowResponseSchema2 = BaseResponseSchema2.extend({ + data: FlowSchema2.describe("Full flow definition") +}); +var CreateFlowRequestSchema = FlowSchema2; +var CreateFlowResponseSchema2 = BaseResponseSchema2.extend({ + data: FlowSchema2.describe("The created flow definition") +}); +var UpdateFlowRequestSchema2 = AutomationFlowPathParamsSchema2.extend({ + definition: FlowSchema2.partial().describe("Partial flow definition to update") +}); +var UpdateFlowResponseSchema2 = BaseResponseSchema2.extend({ + data: FlowSchema2.describe("The updated flow definition") +}); +var DeleteFlowRequestSchema = AutomationFlowPathParamsSchema2; +var DeleteFlowResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + name: external_exports.string().describe("Name of the deleted flow"), + deleted: external_exports.boolean().describe("Whether the flow was deleted") + }) +}); +var TriggerFlowRequestSchema2 = AutomationFlowPathParamsSchema2.extend({ + record: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record that triggered the automation"), + object: external_exports.string().optional().describe("Object name the record belongs to"), + event: external_exports.string().optional().describe("Trigger event type"), + userId: external_exports.string().optional().describe("User who triggered the automation"), + params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional contextual data") +}); +var TriggerFlowResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + success: external_exports.boolean().describe("Whether the automation completed successfully"), + output: external_exports.unknown().optional().describe("Output data from the automation"), + error: external_exports.string().optional().describe("Error message if execution failed"), + durationMs: external_exports.number().optional().describe("Execution duration in milliseconds") + }) +}); +var ToggleFlowRequestSchema2 = AutomationFlowPathParamsSchema2.extend({ + enabled: external_exports.boolean().describe("Whether to enable (true) or disable (false) the flow") +}); +var ToggleFlowResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + name: external_exports.string().describe("Flow name"), + enabled: external_exports.boolean().describe("New enabled state") + }) +}); +var ListRunsRequestSchema2 = AutomationFlowPathParamsSchema2.extend({ + status: external_exports.enum(["pending", "running", "paused", "completed", "failed", "cancelled", "timed_out", "retrying"]).optional().describe("Filter by execution status"), + limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of runs to return"), + cursor: external_exports.string().optional().describe("Cursor for pagination") +}); +var ListRunsResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + runs: external_exports.array(ExecutionLogSchema2).describe("Execution run logs"), + total: external_exports.number().int().optional().describe("Total matching runs"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more runs are available") + }) +}); +var GetRunRequestSchema = AutomationRunPathParamsSchema2; +var GetRunResponseSchema2 = BaseResponseSchema2.extend({ + data: ExecutionLogSchema2.describe("Full execution log with step details") +}); +var AutomationApiErrorCode2 = external_exports.enum([ + "flow_not_found", + "flow_already_exists", + "flow_validation_failed", + "flow_disabled", + "execution_not_found", + "execution_failed", + "execution_timeout", + "node_executor_not_found", + "concurrent_execution_limit" +]); +var AutomationApiContracts = { + listFlows: { + method: "GET", + path: "/api/automation", + input: ListFlowsRequestSchema2, + output: ListFlowsResponseSchema2 + }, + getFlow: { + method: "GET", + path: "/api/automation/:name", + input: GetFlowRequestSchema, + output: GetFlowResponseSchema2 + }, + createFlow: { + method: "POST", + path: "/api/automation", + input: CreateFlowRequestSchema, + output: CreateFlowResponseSchema2 + }, + updateFlow: { + method: "PUT", + path: "/api/automation/:name", + input: UpdateFlowRequestSchema2, + output: UpdateFlowResponseSchema2 + }, + deleteFlow: { + method: "DELETE", + path: "/api/automation/:name", + input: DeleteFlowRequestSchema, + output: DeleteFlowResponseSchema2 + }, + triggerFlow: { + method: "POST", + path: "/api/automation/:name/trigger", + input: TriggerFlowRequestSchema2, + output: TriggerFlowResponseSchema2 + }, + toggleFlow: { + method: "POST", + path: "/api/automation/:name/toggle", + input: ToggleFlowRequestSchema2, + output: ToggleFlowResponseSchema2 + }, + listRuns: { + method: "GET", + path: "/api/automation/:name/runs", + input: ListRunsRequestSchema2, + output: ListRunsResponseSchema2 + }, + getRun: { + method: "GET", + path: "/api/automation/:name/runs/:runId", + input: GetRunRequestSchema, + output: GetRunResponseSchema2 + } +}; +var PackagePathParamsSchema2 = external_exports.object({ + packageId: external_exports.string().describe("Package identifier") +}); +var ListInstalledPackagesRequestSchema2 = external_exports.object({ + /** Filter by package status */ + status: external_exports.enum(["installed", "disabled", "installing", "upgrading", "uninstalling", "error"]).optional().describe("Filter by package status"), + /** Filter by enabled state */ + enabled: external_exports.boolean().optional().describe("Filter by enabled state"), + /** Maximum number of packages to return */ + limit: external_exports.number().int().min(1).max(100).default(50).describe("Maximum number of packages to return"), + /** Cursor for pagination */ + cursor: external_exports.string().optional().describe("Cursor for pagination") +}).describe("List installed packages request"); +var ListInstalledPackagesResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + packages: external_exports.array(InstalledPackageSchema3).describe("Installed packages"), + total: external_exports.number().int().optional().describe("Total matching packages"), + nextCursor: external_exports.string().optional().describe("Cursor for the next page"), + hasMore: external_exports.boolean().describe("Whether more packages are available") + }) +}).describe("List installed packages response"); +var GetInstalledPackageRequestSchema = PackagePathParamsSchema2; +var GetInstalledPackageResponseSchema2 = BaseResponseSchema2.extend({ + data: InstalledPackageSchema3.describe("Installed package details") +}).describe("Get installed package response"); +var PackageInstallRequestSchema2 = external_exports.object({ + /** Package manifest to install */ + manifest: ManifestSchema3.describe("Package manifest to install"), + /** User-provided settings at install time */ + settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), + /** Whether to enable immediately after install */ + enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), + /** Current platform version for compatibility verification */ + platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification"), + /** Artifact reference for the package (if installing from marketplace) */ + artifactRef: ArtifactReferenceSchema2.optional().describe("Artifact reference for marketplace installation") +}).describe("Install package request"); +var PackageInstallResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + package: InstalledPackageSchema3.describe("Installed package details"), + dependencyResolution: DependencyResolutionResultSchema3.optional().describe("Dependency resolution result"), + namespaceConflicts: external_exports.array(external_exports.object({ + type: external_exports.literal("namespace_conflict").describe("Error type"), + requestedNamespace: external_exports.string().describe("Requested namespace"), + conflictingPackageId: external_exports.string().describe("Conflicting package ID"), + conflictingPackageName: external_exports.string().describe("Conflicting package name"), + suggestion: external_exports.string().optional().describe("Suggested alternative") + })).optional().describe("Namespace conflicts detected"), + message: external_exports.string().optional().describe("Installation status message") + }) +}).describe("Install package response"); +var PackageUpgradeRequestSchema2 = external_exports.object({ + /** Package ID to upgrade */ + packageId: external_exports.string().describe("Package ID to upgrade"), + /** Target version (defaults to latest) */ + targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), + /** New manifest for the target version */ + manifest: ManifestSchema3.optional().describe("New manifest for the target version"), + /** Whether to create a pre-upgrade snapshot */ + createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), + /** Merge strategy for handling customizations */ + mergeStrategy: external_exports.enum(["keep-custom", "accept-incoming", "three-way-merge"]).default("three-way-merge").describe("How to handle customer customizations"), + /** Preview upgrade without making changes */ + dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), + /** Skip pre-upgrade compatibility checks */ + skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") +}).describe("Upgrade package request"); +var PackageUpgradeResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + success: external_exports.boolean().describe("Whether the upgrade succeeded"), + phase: external_exports.string().describe("Current upgrade phase"), + plan: UpgradePlanSchema3.optional().describe("Upgrade plan that was executed"), + snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), + conflicts: external_exports.array(external_exports.object({ + path: external_exports.string().describe("Conflict path"), + baseValue: external_exports.unknown().describe("Base value"), + incomingValue: external_exports.unknown().describe("Incoming value"), + customValue: external_exports.unknown().describe("Custom value") + })).optional().describe("Unresolved merge conflicts"), + errorMessage: external_exports.string().optional().describe("Error message if failed"), + message: external_exports.string().optional().describe("Human-readable status message") + }) +}).describe("Upgrade package response"); +var ResolveDependenciesRequestSchema2 = external_exports.object({ + /** Package manifest whose dependencies to resolve */ + manifest: ManifestSchema3.describe("Package manifest to resolve dependencies for"), + /** Current platform version for compatibility checking */ + platformVersion: external_exports.string().optional().describe("Current platform version for compatibility filtering") +}).describe("Resolve dependencies request"); +var ResolveDependenciesResponseSchema2 = BaseResponseSchema2.extend({ + data: DependencyResolutionResultSchema3.describe("Dependency resolution result with topological sort") +}).describe("Resolve dependencies response"); +var UploadArtifactRequestSchema2 = external_exports.object({ + /** Artifact metadata */ + artifact: PackageArtifactSchema3.describe("Package artifact metadata"), + /** SHA256 checksum of the uploaded file (for verification) */ + sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).optional().describe("SHA256 checksum of the uploaded file"), + /** Publisher authentication token */ + token: external_exports.string().optional().describe("Publisher authentication token"), + /** Release notes for this version */ + releaseNotes: external_exports.string().optional().describe("Release notes for this version") +}).describe("Upload artifact request"); +var UploadArtifactResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + /** Whether the upload succeeded */ + success: external_exports.boolean().describe("Whether the upload succeeded"), + /** Artifact reference for the uploaded package */ + artifactRef: ArtifactReferenceSchema2.optional().describe("Artifact reference in the registry"), + /** Submission ID for review tracking */ + submissionId: external_exports.string().optional().describe("Marketplace submission ID for review tracking"), + /** Message */ + message: external_exports.string().optional().describe("Upload status message") + }) +}).describe("Upload artifact response"); +var PackageRollbackRequestSchema2 = PackagePathParamsSchema2.extend({ + /** Snapshot ID to restore from */ + snapshotId: external_exports.string().describe("Snapshot ID to restore from"), + /** Whether to also rollback customizations */ + rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") +}).describe("Rollback package request"); +var PackageRollbackResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + success: external_exports.boolean().describe("Whether the rollback succeeded"), + restoredVersion: external_exports.string().optional().describe("Restored version"), + message: external_exports.string().optional().describe("Rollback status message") + }) +}).describe("Rollback package response"); +var UninstallPackageApiRequestSchema = PackagePathParamsSchema2; +var UninstallPackageApiResponseSchema2 = BaseResponseSchema2.extend({ + data: external_exports.object({ + packageId: external_exports.string().describe("Uninstalled package ID"), + success: external_exports.boolean().describe("Whether uninstall succeeded"), + message: external_exports.string().optional().describe("Uninstall status message") + }) +}).describe("Uninstall package response"); +var PackageApiErrorCode2 = external_exports.enum([ + "package_not_found", + "package_already_installed", + "version_not_found", + "dependency_conflict", + "namespace_conflict", + "platform_incompatible", + "artifact_invalid", + "checksum_mismatch", + "signature_invalid", + "upgrade_failed", + "rollback_failed", + "snapshot_not_found", + "upload_failed" +]); +var PackageApiContracts = { + listPackages: { + method: "GET", + path: "/api/v1/packages", + input: ListInstalledPackagesRequestSchema2, + output: ListInstalledPackagesResponseSchema2 + }, + getPackage: { + method: "GET", + path: "/api/v1/packages/:packageId", + input: GetInstalledPackageRequestSchema, + output: GetInstalledPackageResponseSchema2 + }, + installPackage: { + method: "POST", + path: "/api/v1/packages/install", + input: PackageInstallRequestSchema2, + output: PackageInstallResponseSchema2 + }, + upgradePackage: { + method: "POST", + path: "/api/v1/packages/upgrade", + input: PackageUpgradeRequestSchema2, + output: PackageUpgradeResponseSchema2 + }, + resolveDependencies: { + method: "POST", + path: "/api/v1/packages/resolve-dependencies", + input: ResolveDependenciesRequestSchema2, + output: ResolveDependenciesResponseSchema2 + }, + uploadArtifact: { + method: "POST", + path: "/api/v1/packages/upload", + input: UploadArtifactRequestSchema2, + output: UploadArtifactResponseSchema2 + }, + rollbackPackage: { + method: "POST", + path: "/api/v1/packages/:packageId/rollback", + input: PackageRollbackRequestSchema2, + output: PackageRollbackResponseSchema2 + }, + uninstallPackage: { + method: "DELETE", + path: "/api/v1/packages/:packageId", + input: UninstallPackageApiRequestSchema, + output: UninstallPackageApiResponseSchema2 + } +}; +var automation_exports = {}; +__export4(automation_exports, { + ActionRefSchema: () => ActionRefSchema4, + ApprovalActionSchema: () => ApprovalActionSchema, + ApprovalActionType: () => ApprovalActionType, + ApprovalProcess: () => ApprovalProcess, + ApprovalProcessSchema: () => ApprovalProcessSchema, + ApprovalStepSchema: () => ApprovalStepSchema, + ApproverType: () => ApproverType, + AuthFieldSchema: () => AuthFieldSchema, + AuthenticationSchema: () => AuthenticationSchema, + AuthenticationTypeSchema: () => AuthenticationTypeSchema, + BUILT_IN_BPMN_MAPPINGS: () => BUILT_IN_BPMN_MAPPINGS, + BpmnDiagnosticSchema: () => BpmnDiagnosticSchema, + BpmnElementMappingSchema: () => BpmnElementMappingSchema, + BpmnExportOptionsSchema: () => BpmnExportOptionsSchema, + BpmnImportOptionsSchema: () => BpmnImportOptionsSchema, + BpmnInteropResultSchema: () => BpmnInteropResultSchema, + BpmnUnmappedStrategySchema: () => BpmnUnmappedStrategySchema, + BpmnVersionSchema: () => BpmnVersionSchema, + CheckpointSchema: () => CheckpointSchema, + ConcurrencyPolicySchema: () => ConcurrencyPolicySchema, + ConflictResolutionSchema: () => ConflictResolutionSchema22, + Connector: () => Connector, + ConnectorActionRefSchema: () => ConnectorActionRefSchema2, + ConnectorCategorySchema: () => ConnectorCategorySchema, + ConnectorInstanceSchema: () => ConnectorInstanceSchema, + ConnectorOperationSchema: () => ConnectorOperationSchema, + ConnectorSchema: () => ConnectorSchema, + ConnectorTriggerSchema: () => ConnectorTriggerSchema, + CustomScriptActionSchema: () => CustomScriptActionSchema2, + DataDestinationConfigSchema: () => DataDestinationConfigSchema, + DataSourceConfigSchema: () => DataSourceConfigSchema, + DataSyncConfigSchema: () => DataSyncConfigSchema, + ETL: () => ETL, + ETLDestinationSchema: () => ETLDestinationSchema, + ETLEndpointTypeSchema: () => ETLEndpointTypeSchema, + ETLPipelineRunSchema: () => ETLPipelineRunSchema, + ETLPipelineSchema: () => ETLPipelineSchema, + ETLRunStatusSchema: () => ETLRunStatusSchema, + ETLSourceSchema: () => ETLSourceSchema, + ETLSyncModeSchema: () => ETLSyncModeSchema, + ETLTransformationSchema: () => ETLTransformationSchema, + ETLTransformationTypeSchema: () => ETLTransformationTypeSchema, + EmailAlertActionSchema: () => EmailAlertActionSchema2, + EventSchema: () => EventSchema2, + ExecutionErrorSchema: () => ExecutionErrorSchema, + ExecutionErrorSeverity: () => ExecutionErrorSeverity2, + ExecutionLogSchema: () => ExecutionLogSchema2, + ExecutionStatus: () => ExecutionStatus2, + ExecutionStepLogSchema: () => ExecutionStepLogSchema2, + FieldUpdateActionSchema: () => FieldUpdateActionSchema2, + FlowEdgeSchema: () => FlowEdgeSchema2, + FlowNodeAction: () => FlowNodeAction2, + FlowNodeSchema: () => FlowNodeSchema2, + FlowSchema: () => FlowSchema2, + FlowVariableSchema: () => FlowVariableSchema2, + FlowVersionHistorySchema: () => FlowVersionHistorySchema, + GuardRefSchema: () => GuardRefSchema4, + HttpCallActionSchema: () => HttpCallActionSchema2, + NodeExecutorDescriptorSchema: () => NodeExecutorDescriptorSchema, + OAuth2ConfigSchema: () => OAuth2ConfigSchema, + OperationParameterSchema: () => OperationParameterSchema, + OperationTypeSchema: () => OperationTypeSchema, + PushNotificationActionSchema: () => PushNotificationActionSchema2, + ScheduleStateSchema: () => ScheduleStateSchema, + StateMachineSchema: () => StateMachineSchema4, + StateNodeSchema: () => StateNodeSchema4, + Sync: () => Sync, + SyncDirectionSchema: () => SyncDirectionSchema, + SyncExecutionResultSchema: () => SyncExecutionResultSchema, + SyncExecutionStatusSchema: () => SyncExecutionStatusSchema, + SyncModeSchema: () => SyncModeSchema, + TaskCreationActionSchema: () => TaskCreationActionSchema2, + TimeTriggerSchema: () => TimeTriggerSchema2, + TransitionSchema: () => TransitionSchema4, + WAIT_EXECUTOR_DESCRIPTOR: () => WAIT_EXECUTOR_DESCRIPTOR, + WaitEventTypeSchema: () => WaitEventTypeSchema, + WaitExecutorConfigSchema: () => WaitExecutorConfigSchema, + WaitResumePayloadSchema: () => WaitResumePayloadSchema, + WaitTimeoutBehaviorSchema: () => WaitTimeoutBehaviorSchema, + WebhookReceiverSchema: () => WebhookReceiverSchema, + WebhookSchema: () => WebhookSchema, + WebhookTriggerType: () => WebhookTriggerType, + WorkflowActionSchema: () => WorkflowActionSchema2, + WorkflowRuleSchema: () => WorkflowRuleSchema2, + WorkflowTriggerType: () => WorkflowTriggerType2, + defineFlow: () => defineFlow +}); +var WebhookTriggerType = external_exports.enum([ + "create", + "update", + "delete", + "undelete", + "api" + // Manually triggered +]); +var WebhookSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema7.describe("Webhook unique name (lowercase snake_case)"), + label: external_exports.string().optional().describe("Human-readable webhook label"), + /** Scope */ + object: external_exports.string().optional().describe("Object to listen to (optional for manual webhooks)"), + triggers: external_exports.array(WebhookTriggerType).optional().describe("Events that trigger execution"), + /** Target */ + url: external_exports.string().url().describe("External webhook endpoint URL"), + method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).default("POST").describe("HTTP method"), + /** Headers */ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), + /** Body/Payload */ + body: external_exports.unknown().optional().describe("Request body payload (if not using default record data)"), + /** Payload Configuration */ + payloadFields: external_exports.array(external_exports.string()).optional().describe("Fields to include. Empty = All"), + includeSession: external_exports.boolean().default(false).describe("Include user session info"), + /** Authentication */ + authentication: external_exports.object({ + type: external_exports.enum(["none", "bearer", "basic", "api-key"]).describe("Authentication type"), + credentials: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Authentication credentials") + }).optional().describe("Authentication configuration"), + /** Retry Policy */ + retryPolicy: external_exports.object({ + maxRetries: external_exports.number().int().min(0).max(10).default(3).describe("Maximum retry attempts"), + backoffStrategy: external_exports.enum(["exponential", "linear", "fixed"]).default("exponential").describe("Backoff strategy"), + initialDelayMs: external_exports.number().int().min(100).default(1e3).describe("Initial retry delay in milliseconds"), + maxDelayMs: external_exports.number().int().min(1e3).default(6e4).describe("Maximum retry delay in milliseconds") + }).optional().describe("Retry policy configuration"), + /** Timeout */ + timeoutMs: external_exports.number().int().min(1e3).max(3e5).default(3e4).describe("Request timeout in milliseconds"), + /** Security */ + secret: external_exports.string().optional().describe("Signing secret for HMAC signature verification"), + /** Status */ + isActive: external_exports.boolean().default(true).describe("Whether webhook is active"), + /** Metadata */ + description: external_exports.string().optional().describe("Webhook description"), + tags: external_exports.array(external_exports.string()).optional().describe("Tags for organization") +}); +var WebhookReceiverSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema7.describe("Webhook receiver unique name (lowercase snake_case)"), + path: external_exports.string().describe("URL Path (e.g. /webhooks/stripe)"), + /** Verification */ + verificationType: external_exports.enum(["none", "header_token", "hmac", "ip_whitelist"]).default("none"), + verificationParams: external_exports.object({ + header: external_exports.string().optional(), + secret: external_exports.string().optional(), + ips: external_exports.array(external_exports.string()).optional() + }).optional(), + /** Action */ + action: external_exports.enum(["trigger_flow", "script", "upsert_record"]).default("trigger_flow"), + target: external_exports.string().describe("Flow ID or Script name") +}); +var ApproverType = external_exports.enum([ + "user", + // Specific user(s) + "role", + // Users with specific role + "manager", + // Submitter's manager + "field", + // User ID defined in a record field + "queue" + // Data ownership queue +]); +var ApprovalActionType = external_exports.enum([ + "field_update", + "email_alert", + "webhook", + "script", + "connector_action" + // Added for Zapier-style integrations +]); +var ApprovalActionSchema = external_exports.object({ + type: ApprovalActionType, + name: external_exports.string().describe("Action name"), + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Action configuration"), + /** For connector actions */ + connectorId: external_exports.string().optional(), + actionId: external_exports.string().optional() +}); +var ApprovalStepSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema7.describe("Step machine name"), + label: external_exports.string().describe("Step display label"), + description: external_exports.string().optional(), + /** Entry criteria for this step */ + entryCriteria: external_exports.string().optional().describe("Formula expression to enter this step"), + /** Who can approve */ + approvers: external_exports.array(external_exports.object({ + type: ApproverType, + value: external_exports.string().describe("User ID, Role Name, or Field Name") + })).min(1).describe("List of allowed approvers"), + /** Approval Logic */ + behavior: external_exports.enum(["first_response", "unanimous"]).default("first_response").describe("How to handle multiple approvers"), + /** Rejection behavior */ + rejectionBehavior: external_exports.enum(["reject_process", "back_to_previous"]).default("reject_process").describe("What happens if rejected"), + /** Actions */ + onApprove: external_exports.array(ApprovalActionSchema).optional().describe("Actions on step approval"), + onReject: external_exports.array(ApprovalActionSchema).optional().describe("Actions on step rejection") +}); +var ApprovalProcessSchema = external_exports.object({ + name: SnakeCaseIdentifierSchema7.describe("Unique process name"), + label: external_exports.string().describe("Human readable label"), + object: external_exports.string().describe("Target Object Name"), + active: external_exports.boolean().default(false), + description: external_exports.string().optional(), + /** Entry Criteria for the entire process */ + entryCriteria: external_exports.string().optional().describe("Formula to allow submission"), + /** Record Locking */ + lockRecord: external_exports.boolean().default(true).describe("Lock record from editing during approval"), + /** Steps */ + steps: external_exports.array(ApprovalStepSchema).min(1).describe("Sequence of approval steps"), + /** Escalation Configuration (SLA-based auto-escalation) */ + escalation: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable SLA-based escalation"), + timeoutHours: external_exports.number().min(1).describe("Hours before escalation triggers"), + action: external_exports.enum(["reassign", "auto_approve", "auto_reject", "notify"]).default("notify").describe("Action to take on escalation timeout"), + escalateTo: external_exports.string().optional().describe("User ID, role, or manager level to escalate to"), + notifySubmitter: external_exports.boolean().default(true).describe("Notify the original submitter on escalation") + }).optional().describe("SLA escalation configuration for pending approval steps"), + /** Global Actions */ + onSubmit: external_exports.array(ApprovalActionSchema).optional().describe("Actions on initial submission"), + onFinalApprove: external_exports.array(ApprovalActionSchema).optional().describe("Actions on final approval"), + onFinalReject: external_exports.array(ApprovalActionSchema).optional().describe("Actions on final rejection"), + onRecall: external_exports.array(ApprovalActionSchema).optional().describe("Actions on recall") +}); +var ApprovalProcess = Object.assign(ApprovalProcessSchema, { + create: (config4) => config4 +}); +var ETLEndpointTypeSchema = external_exports.enum([ + "database", + // SQL/NoSQL databases + "api", + // REST/GraphQL APIs + "file", + // CSV, JSON, XML, Excel files + "stream", + // Kafka, RabbitMQ, Kinesis + "object", + // ObjectStack object + "warehouse", + // Data warehouse (Snowflake, BigQuery, Redshift) + "storage", + // S3, Azure Blob, Google Cloud Storage + "spreadsheet" + // Google Sheets, Excel Online +]); +var ETLSourceSchema = external_exports.object({ + /** + * Source type + */ + type: ETLEndpointTypeSchema.describe("Source type"), + /** + * Connector identifier + * References a registered connector + * + * @example "salesforce", "postgres", "mysql", "s3" + */ + connector: external_exports.string().optional().describe("Connector ID"), + /** + * Source-specific configuration + * Structure varies by source type + * + * @example For database: { table: 'customers', schema: 'public' } + * @example For API: { endpoint: '/api/users', method: 'GET' } + * @example For file: { path: 's3://bucket/data.csv', format: 'csv' } + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Source configuration"), + /** + * Incremental sync configuration + * Allows extracting only changed data + */ + incremental: external_exports.object({ + enabled: external_exports.boolean().default(false), + cursorField: external_exports.string().describe("Field to track progress (e.g., updated_at)"), + cursorValue: external_exports.unknown().optional().describe("Last processed value") + }).optional().describe("Incremental extraction config") +}); +var ETLDestinationSchema = external_exports.object({ + /** + * Destination type + */ + type: ETLEndpointTypeSchema.describe("Destination type"), + /** + * Connector identifier + */ + connector: external_exports.string().optional().describe("Connector ID"), + /** + * Destination-specific configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Destination configuration"), + /** + * Write mode + */ + writeMode: external_exports.enum([ + "append", + // Add new records + "overwrite", + // Replace all data + "upsert", + // Insert or update based on key + "merge" + // Smart merge based on business rules + ]).default("append").describe("How to write data"), + /** + * Primary key fields for upsert/merge + */ + primaryKey: external_exports.array(external_exports.string()).optional().describe("Primary key fields") +}); +var ETLTransformationTypeSchema = external_exports.enum([ + "map", + // Field mapping/renaming + "filter", + // Row filtering + "aggregate", + // Aggregation/grouping + "join", + // Joining with other data + "script", + // Custom JavaScript/Python script + "lookup", + // Enrich with lookup data + "split", + // Split one record into multiple + "merge", + // Merge multiple records into one + "normalize", + // Data normalization + "deduplicate" + // Remove duplicates +]); +var ETLTransformationSchema = external_exports.object({ + /** + * Transformation name + */ + name: external_exports.string().optional().describe("Transformation name"), + /** + * Transformation type + */ + type: ETLTransformationTypeSchema.describe("Transformation type"), + /** + * Transformation-specific configuration + * + * @example For map: { oldField: 'newField' } + * @example For filter: { condition: 'status == "active"' } + * @example For script: { language: 'javascript', code: '...' } + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Transformation config"), + /** + * Whether to continue on error + */ + continueOnError: external_exports.boolean().default(false).describe("Continue on error") +}); +var ETLSyncModeSchema = external_exports.enum([ + "full", + // Full refresh - extract all data every time + "incremental", + // Only extract changed data + "cdc" + // Change Data Capture - real-time streaming +]); +var ETLPipelineSchema = external_exports.object({ + /** + * Pipeline identifier (snake_case) + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Pipeline identifier (snake_case)"), + /** + * Human-readable pipeline name + */ + label: external_exports.string().optional().describe("Pipeline display name"), + /** + * Pipeline description + */ + description: external_exports.string().optional().describe("Pipeline description"), + /** + * Data source configuration + */ + source: ETLSourceSchema.describe("Data source"), + /** + * Data destination configuration + */ + destination: ETLDestinationSchema.describe("Data destination"), + /** + * Transformation steps + * Applied in order from source to destination + */ + transformations: external_exports.array(ETLTransformationSchema).optional().describe("Transformation pipeline"), + /** + * Sync mode + */ + syncMode: ETLSyncModeSchema.default("full").describe("Sync mode"), + /** + * Execution schedule (cron expression) + * + * @example "0 2 * * *" - Daily at 2 AM + * @example "0 *\/4 * * *" - Every 4 hours + * @example "0 0 * * 0" - Weekly on Sunday + */ + schedule: external_exports.string().optional().describe("Cron schedule expression"), + /** + * Whether pipeline is enabled + */ + enabled: external_exports.boolean().default(true).describe("Pipeline enabled status"), + /** + * Retry configuration for failed runs + */ + retry: external_exports.object({ + maxAttempts: external_exports.number().int().min(0).default(3).describe("Max retry attempts"), + backoffMs: external_exports.number().int().min(0).default(6e4).describe("Backoff in milliseconds") + }).optional().describe("Retry configuration"), + /** + * Notification configuration + */ + notifications: external_exports.object({ + onSuccess: external_exports.array(external_exports.string()).optional().describe("Email addresses for success notifications"), + onFailure: external_exports.array(external_exports.string()).optional().describe("Email addresses for failure notifications") + }).optional().describe("Notification settings"), + /** + * Pipeline tags for organization + */ + tags: external_exports.array(external_exports.string()).optional().describe("Pipeline tags"), + /** + * Custom metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") +}); +var ETLRunStatusSchema = external_exports.enum([ + "pending", + // Queued for execution + "running", + // Currently executing + "succeeded", + // Completed successfully + "failed", + // Failed with errors + "cancelled", + // Manually cancelled + "timeout" + // Timed out +]); +var ETLPipelineRunSchema = external_exports.object({ + /** + * Run ID + */ + id: external_exports.string().describe("Run identifier"), + /** + * Pipeline name + */ + pipelineName: external_exports.string().describe("Pipeline name"), + /** + * Run status + */ + status: ETLRunStatusSchema.describe("Run status"), + /** + * Start timestamp + */ + startedAt: external_exports.string().datetime().describe("Start time"), + /** + * End timestamp + */ + completedAt: external_exports.string().datetime().optional().describe("Completion time"), + /** + * Duration in milliseconds + */ + durationMs: external_exports.number().optional().describe("Duration in ms"), + /** + * Statistics + */ + stats: external_exports.object({ + recordsRead: external_exports.number().int().default(0).describe("Records extracted"), + recordsWritten: external_exports.number().int().default(0).describe("Records loaded"), + recordsErrored: external_exports.number().int().default(0).describe("Records with errors"), + bytesProcessed: external_exports.number().int().default(0).describe("Bytes processed") + }).optional().describe("Run statistics"), + /** + * Error information + */ + error: external_exports.object({ + message: external_exports.string().describe("Error message"), + code: external_exports.string().optional().describe("Error code"), + details: external_exports.unknown().optional().describe("Error details") + }).optional().describe("Error information"), + /** + * Execution logs + */ + logs: external_exports.array(external_exports.string()).optional().describe("Execution logs") +}); +var ETL = { + /** + * Create a simple database-to-database pipeline + */ + databaseSync: (params) => ({ + name: params.name, + source: { + type: "database", + config: { table: params.sourceTable } + }, + destination: { + type: "database", + config: { table: params.destTable }, + writeMode: "upsert" + }, + syncMode: "incremental", + schedule: params.schedule, + enabled: true + }), + /** + * Create an API to database pipeline + */ + apiToDatabase: (params) => ({ + name: params.name, + source: { + type: "api", + connector: params.apiConnector, + config: {} + }, + destination: { + type: "database", + config: { table: params.destTable }, + writeMode: "append" + }, + syncMode: "full", + schedule: params.schedule, + enabled: true + }) +}; +var ConnectorCategorySchema = external_exports.enum([ + "crm", + // Customer Relationship Management + "payment", + // Payment processors + "communication", + // Email, SMS, Chat + "storage", + // File storage + "analytics", + // Analytics platforms + "database", + // Databases + "marketing", + // Marketing automation + "accounting", + // Accounting software + "hr", + // Human resources + "productivity", + // Productivity tools + "ecommerce", + // E-commerce platforms + "support", + // Customer support + "devtools", + // Developer tools + "social", + // Social media + "other" + // Other category +]); +var AuthenticationTypeSchema = external_exports.enum([ + "none", + // No authentication + "apiKey", + // API key + "basic", + // Basic auth (username/password) + "bearer", + // Bearer token + "oauth1", + // OAuth 1.0 + "oauth2", + // OAuth 2.0 + "custom" + // Custom authentication +]); +var AuthFieldSchema = external_exports.object({ + /** + * Field name (machine name) + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Field name (snake_case)"), + /** + * Field label + */ + label: external_exports.string().describe("Field label"), + /** + * Field type + */ + type: external_exports.enum(["text", "password", "url", "select"]).default("text").describe("Field type"), + /** + * Field description + */ + description: external_exports.string().optional().describe("Field description"), + /** + * Whether field is required + */ + required: external_exports.boolean().default(true).describe("Required field"), + /** + * Default value + */ + default: external_exports.string().optional().describe("Default value"), + /** + * Options for select fields + */ + options: external_exports.array(external_exports.object({ + label: external_exports.string(), + value: external_exports.string() + })).optional().describe("Select field options"), + /** + * Placeholder text + */ + placeholder: external_exports.string().optional().describe("Placeholder text") +}); +var OAuth2ConfigSchema = external_exports.object({ + /** + * Authorization URL + */ + authorizationUrl: external_exports.string().url().describe("Authorization endpoint URL"), + /** + * Token URL + */ + tokenUrl: external_exports.string().url().describe("Token endpoint URL"), + /** + * Scopes to request + */ + scopes: external_exports.array(external_exports.string()).optional().describe("OAuth scopes"), + /** + * Client ID field name + */ + clientIdField: external_exports.string().default("client_id").describe("Client ID field name"), + /** + * Client secret field name + */ + clientSecretField: external_exports.string().default("client_secret").describe("Client secret field name") +}); +var AuthenticationSchema = external_exports.object({ + /** + * Authentication type + */ + type: AuthenticationTypeSchema.describe("Authentication type"), + /** + * Authentication fields + * Configuration fields needed for this auth type + */ + fields: external_exports.array(AuthFieldSchema).optional().describe("Authentication fields"), + /** + * OAuth 2.0 configuration (when type is oauth2) + */ + oauth2: OAuth2ConfigSchema.optional().describe("OAuth 2.0 configuration"), + /** + * Test authentication instructions + */ + test: external_exports.object({ + url: external_exports.string().optional().describe("Test endpoint URL"), + method: external_exports.enum(["GET", "POST", "PUT", "DELETE"]).default("GET").describe("HTTP method") + }).optional().describe("Authentication test configuration") +}); +var OperationTypeSchema = external_exports.enum([ + "read", + // Read/query data + "write", + // Create/update data + "delete", + // Delete data + "search", + // Search operation + "trigger", + // Webhook/polling trigger + "action" + // Custom action +]); +var OperationParameterSchema = external_exports.object({ + /** + * Parameter name + */ + name: external_exports.string().describe("Parameter name"), + /** + * Parameter label + */ + label: external_exports.string().describe("Parameter label"), + /** + * Parameter description + */ + description: external_exports.string().optional().describe("Parameter description"), + /** + * Parameter type + */ + type: external_exports.enum(["string", "number", "boolean", "array", "object", "date", "file"]).describe("Parameter type"), + /** + * Whether parameter is required + */ + required: external_exports.boolean().default(false).describe("Required parameter"), + /** + * Default value + */ + default: external_exports.unknown().optional().describe("Default value"), + /** + * Validation schema + */ + validation: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation rules"), + /** + * Dynamic options function + */ + dynamicOptions: external_exports.string().optional().describe("Function to load dynamic options") +}); +var ConnectorOperationSchema = external_exports.object({ + /** + * Operation identifier + */ + id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Operation ID (snake_case)"), + /** + * Operation name + */ + name: external_exports.string().describe("Operation name"), + /** + * Operation description + */ + description: external_exports.string().optional().describe("Operation description"), + /** + * Operation type + */ + type: OperationTypeSchema.describe("Operation type"), + /** + * Input parameters + */ + inputSchema: external_exports.array(OperationParameterSchema).optional().describe("Input parameters"), + /** + * Output schema + */ + outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Output schema"), + /** + * Sample output for documentation + */ + sampleOutput: external_exports.unknown().optional().describe("Sample output"), + /** + * Whether operation supports pagination + */ + supportsPagination: external_exports.boolean().default(false).describe("Supports pagination"), + /** + * Whether operation supports filtering + */ + supportsFiltering: external_exports.boolean().default(false).describe("Supports filtering") +}); +var ConnectorTriggerSchema = external_exports.object({ + /** + * Trigger identifier + */ + id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Trigger ID (snake_case)"), + /** + * Trigger name + */ + name: external_exports.string().describe("Trigger name"), + /** + * Trigger description + */ + description: external_exports.string().optional().describe("Trigger description"), + /** + * Trigger type + */ + type: external_exports.enum(["webhook", "polling", "stream"]).describe("Trigger mechanism"), + /** + * Trigger configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Trigger configuration"), + /** + * Output schema + */ + outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event payload schema"), + /** + * Polling interval (for polling triggers) + * In milliseconds + */ + pollingIntervalMs: external_exports.number().int().min(1e3).optional().describe("Polling interval in ms") +}); +var ConnectorSchema = external_exports.object({ + /** + * Connector identifier + * Must be globally unique + */ + id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Connector ID (snake_case)"), + /** + * Connector name + */ + name: external_exports.string().describe("Connector name"), + /** + * Connector description + */ + description: external_exports.string().optional().describe("Connector description"), + /** + * Connector version (semver) + */ + version: external_exports.string().optional().describe("Connector version"), + /** + * Connector icon URL or name + */ + icon: external_exports.string().optional().describe("Connector icon"), + /** + * Connector category + */ + category: ConnectorCategorySchema.describe("Connector category"), + /** + * Base URL for API calls + */ + baseUrl: external_exports.string().url().optional().describe("API base URL"), + /** + * Authentication configuration + */ + authentication: AuthenticationSchema.describe("Authentication config"), + /** + * Available operations + */ + operations: external_exports.array(ConnectorOperationSchema).optional().describe("Connector operations"), + /** + * Available triggers + */ + triggers: external_exports.array(ConnectorTriggerSchema).optional().describe("Connector triggers"), + /** + * Rate limiting information + */ + rateLimit: external_exports.object({ + requestsPerSecond: external_exports.number().optional().describe("Max requests per second"), + requestsPerMinute: external_exports.number().optional().describe("Max requests per minute"), + requestsPerHour: external_exports.number().optional().describe("Max requests per hour") + }).optional().describe("Rate limiting"), + /** + * Connector author + */ + author: external_exports.string().optional().describe("Connector author"), + /** + * Documentation URL + */ + documentation: external_exports.string().url().optional().describe("Documentation URL"), + /** + * Homepage URL + */ + homepage: external_exports.string().url().optional().describe("Homepage URL"), + /** + * License + */ + license: external_exports.string().optional().describe("License (SPDX identifier)"), + /** + * Tags for discovery + */ + tags: external_exports.array(external_exports.string()).optional().describe("Connector tags"), + /** + * Whether connector is verified/certified + */ + verified: external_exports.boolean().default(false).describe("Verified connector"), + /** + * Custom metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") +}); +var ConnectorInstanceSchema = external_exports.object({ + /** + * Instance ID + */ + id: external_exports.string().describe("Instance ID"), + /** + * Connector ID this instance uses + */ + connectorId: external_exports.string().describe("Connector ID"), + /** + * Instance name + */ + name: external_exports.string().describe("Instance name"), + /** + * Instance description + */ + description: external_exports.string().optional().describe("Instance description"), + /** + * Authentication credentials (encrypted) + */ + credentials: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Encrypted credentials"), + /** + * Additional configuration + */ + config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional config"), + /** + * Whether instance is active + */ + active: external_exports.boolean().default(true).describe("Instance active status"), + /** + * Created timestamp + */ + createdAt: external_exports.string().datetime().optional().describe("Creation time"), + /** + * Last tested timestamp + */ + lastTestedAt: external_exports.string().datetime().optional().describe("Last test time"), + /** + * Test status + */ + testStatus: external_exports.enum(["unknown", "success", "failed"]).default("unknown").describe("Connection test status") +}); +var Connector = { + /** + * Create a basic API key connector + */ + apiKey: (params) => ({ + id: params.id, + name: params.name, + category: params.category, + baseUrl: params.baseUrl, + authentication: { + type: "apiKey", + fields: [ + { + name: "api_key", + label: "API Key", + type: "password", + required: true + } + ] + }, + verified: false + }), + /** + * Create an OAuth 2.0 connector + */ + oauth2: (params) => ({ + id: params.id, + name: params.name, + category: params.category, + baseUrl: params.baseUrl, + authentication: { + type: "oauth2", + oauth2: { + authorizationUrl: params.authUrl, + tokenUrl: params.tokenUrl, + clientIdField: "client_id", + clientSecretField: "client_secret", + scopes: params.scopes + } + }, + verified: false + }) +}; +var SyncDirectionSchema = external_exports.enum([ + "push", + // ObjectStack -> External (one-way) + "pull", + // External -> ObjectStack (one-way) + "bidirectional" + // Both directions +]); +var SyncModeSchema = external_exports.enum([ + "full", + // Full refresh every time + "incremental", + // Only sync changed records + "realtime" + // Real-time streaming sync +]); +var ConflictResolutionSchema22 = external_exports.enum([ + "source_wins", + // Source system always wins + "destination_wins", + // Destination system always wins + "latest_wins", + // Most recently modified wins + "manual", + // Flag for manual resolution + "merge" + // Smart merge (custom logic) +]); +var DataSourceConfigSchema = external_exports.object({ + /** + * Source object name + * For ObjectStack objects + */ + object: external_exports.string().optional().describe("ObjectStack object name"), + /** + * Filter conditions + * Only sync records matching these filters + */ + filters: external_exports.unknown().optional().describe("Filter conditions"), + /** + * Fields to include + * If not specified, all fields are synced + */ + fields: external_exports.array(external_exports.string()).optional().describe("Fields to sync"), + /** + * External connector instance ID + * For external data sources + */ + connectorInstanceId: external_exports.string().optional().describe("Connector instance ID"), + /** + * External resource identifier + * e.g., Salesforce object name, database table, API endpoint + */ + externalResource: external_exports.string().optional().describe("External resource ID") +}); +var DataDestinationConfigSchema = external_exports.object({ + /** + * Destination object name + * For ObjectStack objects + */ + object: external_exports.string().optional().describe("ObjectStack object name"), + /** + * Connector instance ID + * For external destinations + */ + connectorInstanceId: external_exports.string().optional().describe("Connector instance ID"), + /** + * Operation to perform + */ + operation: external_exports.enum([ + "insert", + // Create new records only + "update", + // Update existing records only + "upsert", + // Insert or update based on key + "delete", + // Delete records + "sync" + // Full synchronization + ]).describe("Sync operation"), + /** + * Field mappings + * Maps source fields to destination fields + */ + mapping: external_exports.union([ + external_exports.record(external_exports.string(), external_exports.string()), + // Simple mapping: { sourceField: 'destField' } + external_exports.array(FieldMappingSchema4) + // Advanced mapping with transformations + ]).optional().describe("Field mappings"), + /** + * External resource identifier + */ + externalResource: external_exports.string().optional().describe("External resource ID"), + /** + * Match key for upsert operations + * Fields to use for matching existing records + */ + matchKey: external_exports.array(external_exports.string()).optional().describe("Match key fields") +}); +var DataSyncConfigSchema = external_exports.object({ + /** + * Sync configuration name (snake_case) + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Sync configuration name (snake_case)"), + /** + * Human-readable label + */ + label: external_exports.string().optional().describe("Sync display name"), + /** + * Description + */ + description: external_exports.string().optional().describe("Sync description"), + /** + * Source configuration + */ + source: DataSourceConfigSchema.describe("Data source"), + /** + * Destination configuration + */ + destination: DataDestinationConfigSchema.describe("Data destination"), + /** + * Sync direction + */ + direction: SyncDirectionSchema.default("push").describe("Sync direction"), + /** + * Sync mode + */ + syncMode: SyncModeSchema.default("incremental").describe("Sync mode"), + /** + * Conflict resolution strategy + */ + conflictResolution: ConflictResolutionSchema22.default("latest_wins").describe("Conflict resolution"), + /** + * Execution schedule (cron expression) + * For scheduled syncs + * + * @example "0 * * * *" - Hourly + * @example "*\/15 * * * *" - Every 15 minutes + */ + schedule: external_exports.string().optional().describe("Cron schedule"), + /** + * Whether sync is enabled + */ + enabled: external_exports.boolean().default(true).describe("Sync enabled"), + /** + * Change tracking field + * Field to track when records were last modified + * Used for incremental sync + * + * @example "updated_at", "modified_date" + */ + changeTrackingField: external_exports.string().optional().describe("Field for change tracking"), + /** + * Batch size + * Number of records to process per batch + */ + batchSize: external_exports.number().int().min(1).max(1e4).default(100).describe("Batch size for processing"), + /** + * Retry configuration + */ + retry: external_exports.object({ + maxAttempts: external_exports.number().int().min(0).default(3).describe("Max retries"), + backoffMs: external_exports.number().int().min(0).default(3e4).describe("Backoff duration") + }).optional().describe("Retry configuration"), + /** + * Pre-sync validation rules + */ + validation: external_exports.object({ + required: external_exports.array(external_exports.string()).optional().describe("Required fields"), + unique: external_exports.array(external_exports.string()).optional().describe("Unique constraint fields"), + custom: external_exports.array(external_exports.object({ + name: external_exports.string(), + condition: external_exports.string().describe("Validation condition"), + message: external_exports.string().describe("Error message") + })).optional().describe("Custom validation rules") + }).optional().describe("Validation rules"), + /** + * Error handling configuration + */ + errorHandling: external_exports.object({ + onValidationError: external_exports.enum(["skip", "fail", "log"]).default("skip"), + onSyncError: external_exports.enum(["skip", "fail", "retry"]).default("retry"), + notifyOnError: external_exports.array(external_exports.string()).optional().describe("Email notifications") + }).optional().describe("Error handling"), + /** + * Performance optimization + */ + optimization: external_exports.object({ + parallelBatches: external_exports.boolean().default(false).describe("Process batches in parallel"), + cacheEnabled: external_exports.boolean().default(true).describe("Enable caching"), + compressionEnabled: external_exports.boolean().default(false).describe("Enable compression") + }).optional().describe("Performance optimization"), + /** + * Audit and logging + */ + audit: external_exports.object({ + logLevel: external_exports.enum(["none", "error", "warn", "info", "debug"]).default("info"), + retainLogsForDays: external_exports.number().int().min(1).default(30), + trackChanges: external_exports.boolean().default(true).describe("Track all changes") + }).optional().describe("Audit configuration"), + /** + * Tags for organization + */ + tags: external_exports.array(external_exports.string()).optional().describe("Sync tags"), + /** + * Custom metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") +}); +var SyncExecutionStatusSchema = external_exports.enum([ + "pending", + // Queued + "running", + // Currently executing + "completed", + // Successfully completed + "partial", + // Completed with some errors + "failed", + // Failed + "cancelled" + // Manually cancelled +]); +var SyncExecutionResultSchema = external_exports.object({ + /** + * Execution ID + */ + id: external_exports.string().describe("Execution ID"), + /** + * Sync configuration name + */ + syncName: external_exports.string().describe("Sync name"), + /** + * Execution status + */ + status: SyncExecutionStatusSchema.describe("Execution status"), + /** + * Start timestamp + */ + startedAt: external_exports.string().datetime().describe("Start time"), + /** + * End timestamp + */ + completedAt: external_exports.string().datetime().optional().describe("Completion time"), + /** + * Duration in milliseconds + */ + durationMs: external_exports.number().optional().describe("Duration in ms"), + /** + * Statistics + */ + stats: external_exports.object({ + recordsProcessed: external_exports.number().int().default(0).describe("Total records processed"), + recordsInserted: external_exports.number().int().default(0).describe("Records inserted"), + recordsUpdated: external_exports.number().int().default(0).describe("Records updated"), + recordsDeleted: external_exports.number().int().default(0).describe("Records deleted"), + recordsSkipped: external_exports.number().int().default(0).describe("Records skipped"), + recordsErrored: external_exports.number().int().default(0).describe("Records with errors"), + conflictsDetected: external_exports.number().int().default(0).describe("Conflicts detected"), + conflictsResolved: external_exports.number().int().default(0).describe("Conflicts resolved") + }).optional().describe("Execution statistics"), + /** + * Errors encountered + */ + errors: external_exports.array(external_exports.object({ + recordId: external_exports.string().optional().describe("Record ID"), + field: external_exports.string().optional().describe("Field name"), + message: external_exports.string().describe("Error message"), + code: external_exports.string().optional().describe("Error code") + })).optional().describe("Errors"), + /** + * Execution logs + */ + logs: external_exports.array(external_exports.string()).optional().describe("Execution logs") +}); +var Sync = { + /** + * Create a simple object-to-object sync + */ + objectSync: (params) => ({ + name: params.name, + source: { + object: params.sourceObject + }, + destination: { + object: params.destObject, + operation: "upsert", + mapping: params.mapping + }, + direction: "push", + syncMode: "incremental", + conflictResolution: "latest_wins", + batchSize: 100, + schedule: params.schedule, + enabled: true + }), + /** + * Create a connector sync + */ + connectorSync: (params) => ({ + name: params.name, + source: { + object: params.sourceObject + }, + destination: { + connectorInstanceId: params.connectorInstanceId, + externalResource: params.externalResource, + operation: "upsert", + mapping: params.mapping + }, + direction: "push", + syncMode: "incremental", + conflictResolution: "latest_wins", + batchSize: 100, + schedule: params.schedule, + enabled: true + }), + /** + * Create a bidirectional sync + */ + bidirectionalSync: (params) => ({ + name: params.name, + source: { + object: params.object + }, + destination: { + connectorInstanceId: params.connectorInstanceId, + externalResource: params.externalResource, + operation: "sync", + mapping: params.mapping + }, + direction: "bidirectional", + syncMode: "incremental", + conflictResolution: "latest_wins", + batchSize: 100, + schedule: params.schedule, + enabled: true + }) +}; +var WaitEventTypeSchema = external_exports.enum([ + "timer", + // Resume after duration/datetime + "signal", + // Resume on named signal dispatch + "webhook", + // Resume on incoming webhook call + "manual", + // Resume by manual operator action + "condition" + // Resume when a data condition is met (polling) +]).describe("Wait event type determining how a paused flow is resumed"); +var WaitResumePayloadSchema = external_exports.object({ + /** The execution id of the paused flow */ + executionId: external_exports.string().describe("Execution ID of the paused flow"), + /** The checkpoint id being resumed */ + checkpointId: external_exports.string().describe("Checkpoint ID to resume from"), + /** The node id of the wait node being resumed */ + nodeId: external_exports.string().describe("Wait node ID being resumed"), + /** The event type that triggered the resume */ + eventType: WaitEventTypeSchema.describe("Event type that triggered resume"), + /** Signal name (for signal events) */ + signalName: external_exports.string().optional().describe("Signal name (when eventType is signal)"), + /** Webhook payload data (for webhook events) */ + webhookPayload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Webhook request payload (when eventType is webhook)"), + /** Who/what triggered the resume */ + resumedBy: external_exports.string().optional().describe("User ID or system identifier that triggered resume"), + /** Timestamp of the resume event */ + resumedAt: external_exports.string().datetime().describe("ISO 8601 timestamp of the resume event"), + /** Additional variables to merge into flow context on resume */ + variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Variables to merge into flow context upon resume") +}).describe("Payload for resuming a paused wait node"); +var WaitTimeoutBehaviorSchema = external_exports.enum([ + "fail", + // Mark execution as failed + "continue", + // Continue to next node (skip wait) + "fallback" + // Execute a fallback edge +]).describe("Behavior when a wait node exceeds its timeout"); +var WaitExecutorConfigSchema = external_exports.object({ + /** Default timeout for wait nodes without explicit timeout (ms) */ + defaultTimeoutMs: external_exports.number().int().min(0).default(864e5).describe("Default timeout in ms (default: 24 hours)"), + /** Default timeout behavior */ + defaultTimeoutBehavior: WaitTimeoutBehaviorSchema.default("fail").describe("Default behavior when wait timeout is exceeded"), + /** Polling interval for condition-based waits (ms) */ + conditionPollIntervalMs: external_exports.number().int().min(1e3).default(3e4).describe("Polling interval for condition waits in ms (default: 30s)"), + /** Maximum polling attempts for condition waits (0 = unlimited until timeout) */ + conditionMaxPolls: external_exports.number().int().min(0).default(0).describe("Max polling attempts for condition waits (0 = unlimited)"), + /** Webhook endpoint URL pattern (runtime fills in execution/node ids) */ + webhookUrlPattern: external_exports.string().default("/api/v1/automation/resume/{executionId}/{nodeId}").describe("URL pattern for webhook resume endpoints"), + /** Whether to persist checkpoints to durable storage */ + persistCheckpoints: external_exports.boolean().default(true).describe("Persist wait checkpoints to durable storage"), + /** Maximum concurrent paused executions (0 = unlimited) */ + maxPausedExecutions: external_exports.number().int().min(0).default(0).describe("Max concurrent paused executions (0 = unlimited)") +}).describe("Wait node executor plugin configuration"); +var NodeExecutorDescriptorSchema = external_exports.object({ + /** Unique executor identifier */ + id: external_exports.string().describe("Unique executor plugin identifier"), + /** Human-readable name */ + name: external_exports.string().describe("Display name"), + /** The FlowNodeAction types this executor handles */ + nodeTypes: external_exports.array(external_exports.string()).min(1).describe("FlowNodeAction types this executor handles"), + /** Executor plugin version (semver) */ + version: external_exports.string().describe("Plugin version (semver)"), + /** Description of the executor */ + description: external_exports.string().optional().describe("Executor description"), + /** Whether this executor supports async pause/resume */ + supportsPause: external_exports.boolean().default(false).describe("Whether the executor supports async pause/resume"), + /** Whether this executor supports cancellation mid-execution */ + supportsCancellation: external_exports.boolean().default(false).describe("Whether the executor supports mid-execution cancellation"), + /** Whether this executor supports retry on failure */ + supportsRetry: external_exports.boolean().default(true).describe("Whether the executor supports retry on failure"), + /** Executor-specific configuration schema (JSON Schema reference) */ + configSchemaRef: external_exports.string().optional().describe("JSON Schema $ref for executor-specific config") +}).describe("Node executor plugin descriptor"); +var WAIT_EXECUTOR_DESCRIPTOR = { + id: "objectstack:wait-executor", + name: "Wait Node Executor", + nodeTypes: ["wait"], + version: "1.0.0", + description: "Pauses flow execution and resumes on timer, signal, webhook, manual action, or condition events.", + supportsPause: true, + supportsCancellation: true, + supportsRetry: true +}; +var BpmnElementMappingSchema = external_exports.object({ + /** BPMN XML element type (e.g., "bpmn:parallelGateway", "bpmn:serviceTask") */ + bpmnType: external_exports.string().describe('BPMN XML element type (e.g., "bpmn:parallelGateway")'), + /** Corresponding ObjectStack FlowNodeAction */ + flowNodeAction: external_exports.string().describe("ObjectStack FlowNodeAction value"), + /** Whether this mapping is bidirectional (supports both import and export) */ + bidirectional: external_exports.boolean().default(true).describe("Whether the mapping supports both import and export"), + /** Notes about mapping limitations or special handling */ + notes: external_exports.string().optional().describe("Notes about mapping limitations") +}).describe("Mapping between BPMN XML element and ObjectStack FlowNodeAction"); +var BpmnUnmappedStrategySchema = external_exports.enum([ + "skip", + // Skip unmapped elements silently + "warn", + // Import with warnings + "error", + // Fail on unmapped elements + "comment" + // Import as annotation/comment nodes +]).describe("Strategy for unmapped BPMN elements during import"); +var BpmnImportOptionsSchema = external_exports.object({ + /** Strategy for unmapped BPMN elements */ + unmappedStrategy: BpmnUnmappedStrategySchema.default("warn").describe("How to handle unmapped BPMN elements"), + /** Custom element mappings (override or extend built-in mappings) */ + customMappings: external_exports.array(BpmnElementMappingSchema).optional().describe("Custom element mappings to override or extend defaults"), + /** Whether to import BPMN DI (diagram interchange) layout positions */ + importLayout: external_exports.boolean().default(true).describe("Import BPMN DI layout positions into canvas node coordinates"), + /** Whether to import BPMN documentation as node descriptions */ + importDocumentation: external_exports.boolean().default(true).describe("Import BPMN documentation elements as node descriptions"), + /** Target flow name (if not derived from BPMN process name) */ + flowName: external_exports.string().optional().describe("Override flow name (defaults to BPMN process name)"), + /** Whether to validate the imported flow against ObjectStack schema */ + validateAfterImport: external_exports.boolean().default(true).describe("Validate imported flow against FlowSchema after import") +}).describe("Options for importing BPMN 2.0 XML into an ObjectStack flow"); +var BpmnVersionSchema = external_exports.enum([ + "2.0", + // BPMN 2.0 (most common, default) + "2.0.2" + // BPMN 2.0.2 (latest revision) +]).describe("BPMN specification version for export"); +var BpmnExportOptionsSchema = external_exports.object({ + /** Target BPMN version */ + version: BpmnVersionSchema.default("2.0").describe("Target BPMN specification version"), + /** Whether to include BPMN DI (diagram interchange) layout data */ + includeLayout: external_exports.boolean().default(true).describe("Include BPMN DI layout data from canvas positions"), + /** Whether to include ObjectStack-specific extensions as BPMN extension elements */ + includeExtensions: external_exports.boolean().default(false).describe("Include ObjectStack extensions in BPMN extensionElements"), + /** Custom element mappings (override built-in for export) */ + customMappings: external_exports.array(BpmnElementMappingSchema).optional().describe("Custom element mappings for export"), + /** Whether to pretty-print the XML output */ + prettyPrint: external_exports.boolean().default(true).describe("Pretty-print XML output with indentation"), + /** XML namespace prefix for BPMN elements */ + namespacePrefix: external_exports.string().default("bpmn").describe("XML namespace prefix for BPMN elements") +}).describe("Options for exporting an ObjectStack flow as BPMN 2.0 XML"); +var BpmnDiagnosticSchema = external_exports.object({ + /** Severity level */ + severity: external_exports.enum(["info", "warning", "error"]).describe("Diagnostic severity"), + /** Human-readable message */ + message: external_exports.string().describe("Diagnostic message"), + /** BPMN element ID (if applicable) */ + bpmnElementId: external_exports.string().optional().describe("BPMN element ID related to this diagnostic"), + /** ObjectStack node ID (if applicable) */ + nodeId: external_exports.string().optional().describe("ObjectStack node ID related to this diagnostic") +}).describe("Diagnostic message from BPMN import/export"); +var BpmnInteropResultSchema = external_exports.object({ + /** Whether the operation completed successfully */ + success: external_exports.boolean().describe("Whether the operation completed successfully"), + /** Diagnostic messages (warnings, errors, info) */ + diagnostics: external_exports.array(BpmnDiagnosticSchema).default([]).describe("Diagnostic messages from the operation"), + /** Number of elements successfully mapped */ + mappedCount: external_exports.number().int().min(0).default(0).describe("Number of elements successfully mapped"), + /** Number of elements skipped or unmapped */ + unmappedCount: external_exports.number().int().min(0).default(0).describe("Number of elements that could not be mapped") +}).describe("Result of a BPMN import/export operation"); +var BUILT_IN_BPMN_MAPPINGS = [ + { bpmnType: "bpmn:startEvent", flowNodeAction: "start", bidirectional: true }, + { bpmnType: "bpmn:endEvent", flowNodeAction: "end", bidirectional: true }, + { bpmnType: "bpmn:exclusiveGateway", flowNodeAction: "decision", bidirectional: true }, + { bpmnType: "bpmn:parallelGateway", flowNodeAction: "parallel_gateway", bidirectional: true }, + { bpmnType: "bpmn:serviceTask", flowNodeAction: "http_request", bidirectional: true, notes: "Maps HTTP/connector tasks" }, + { bpmnType: "bpmn:scriptTask", flowNodeAction: "script", bidirectional: true }, + { bpmnType: "bpmn:userTask", flowNodeAction: "screen", bidirectional: true }, + { bpmnType: "bpmn:callActivity", flowNodeAction: "subflow", bidirectional: true }, + { bpmnType: "bpmn:intermediateCatchEvent", flowNodeAction: "wait", bidirectional: true, notes: "Timer/signal/message catch events" }, + { bpmnType: "bpmn:boundaryEvent", flowNodeAction: "boundary_event", bidirectional: true }, + { bpmnType: "bpmn:task", flowNodeAction: "assignment", bidirectional: true, notes: "Generic BPMN task maps to assignment" } +]; +var integration_exports = {}; +__export4(integration_exports, { + AckModeSchema: () => AckModeSchema, + ApiVersionConfigSchema: () => ApiVersionConfigSchema, + BuildConfigSchema: () => BuildConfigSchema, + CdcConfigSchema: () => CdcConfigSchema, + CircuitBreakerConfigSchema: () => CircuitBreakerConfigSchema, + ConflictResolutionSchema: () => ConflictResolutionSchema3, + ConnectorActionSchema: () => ConnectorActionSchema, + ConnectorHealthSchema: () => ConnectorHealthSchema, + ConnectorSchema: () => ConnectorSchema2, + ConnectorStatusSchema: () => ConnectorStatusSchema, + ConnectorTriggerSchema: () => ConnectorTriggerSchema2, + ConnectorTypeSchema: () => ConnectorTypeSchema, + ConsumerConfigSchema: () => ConsumerConfigSchema22, + DataSyncConfigSchema: () => DataSyncConfigSchema2, + DatabaseConnectorSchema: () => DatabaseConnectorSchema, + DatabasePoolConfigSchema: () => DatabasePoolConfigSchema, + DatabaseProviderSchema: () => DatabaseProviderSchema22, + DatabaseTableSchema: () => DatabaseTableSchema, + DeliveryGuaranteeSchema: () => DeliveryGuaranteeSchema, + DeploymentConfigSchema: () => DeploymentConfigSchema, + DlqConfigSchema: () => DlqConfigSchema, + DomainConfigSchema: () => DomainConfigSchema, + EdgeFunctionConfigSchema: () => EdgeFunctionConfigSchema, + EnvironmentVariablesSchema: () => EnvironmentVariablesSchema, + ErrorCategorySchema: () => ErrorCategorySchema, + ErrorMappingConfigSchema: () => ErrorMappingConfigSchema, + ErrorMappingRuleSchema: () => ErrorMappingRuleSchema, + FieldMappingSchema: () => FieldMappingSchema32, + FileAccessPatternSchema: () => FileAccessPatternSchema, + FileFilterConfigSchema: () => FileFilterConfigSchema, + FileMetadataConfigSchema: () => FileMetadataConfigSchema, + FileStorageConnectorSchema: () => FileStorageConnectorSchema, + FileStorageProviderSchema: () => FileStorageProviderSchema, + FileVersioningConfigSchema: () => FileVersioningConfigSchema, + GitHubActionsWorkflowSchema: () => GitHubActionsWorkflowSchema, + GitHubCommitConfigSchema: () => GitHubCommitConfigSchema, + GitHubConnectorSchema: () => GitHubConnectorSchema, + GitHubIssueTrackingSchema: () => GitHubIssueTrackingSchema, + GitHubProviderSchema: () => GitHubProviderSchema, + GitHubPullRequestConfigSchema: () => GitHubPullRequestConfigSchema, + GitHubReleaseConfigSchema: () => GitHubReleaseConfigSchema, + GitHubRepositorySchema: () => GitHubRepositorySchema, + GitRepositoryConfigSchema: () => GitRepositoryConfigSchema, + HealthCheckConfigSchema: () => HealthCheckConfigSchema, + MessageFormatSchema: () => MessageFormatSchema22, + MessageQueueConnectorSchema: () => MessageQueueConnectorSchema, + MessageQueueProviderSchema: () => MessageQueueProviderSchema22, + MultipartUploadConfigSchema: () => MultipartUploadConfigSchema22, + ProducerConfigSchema: () => ProducerConfigSchema, + RateLimitConfigSchema: () => RateLimitConfigSchema22, + RateLimitStrategySchema: () => RateLimitStrategySchema, + RetryConfigSchema: () => RetryConfigSchema, + RetryStrategySchema: () => RetryStrategySchema, + SaasConnectorSchema: () => SaasConnectorSchema, + SaasObjectTypeSchema: () => SaasObjectTypeSchema, + SaasProviderSchema: () => SaasProviderSchema, + SslConfigSchema: () => SslConfigSchema, + StorageBucketSchema: () => StorageBucketSchema, + SyncStrategySchema: () => SyncStrategySchema, + TopicQueueSchema: () => TopicQueueSchema, + VercelConnectorSchema: () => VercelConnectorSchema, + VercelFrameworkSchema: () => VercelFrameworkSchema, + VercelMonitoringSchema: () => VercelMonitoringSchema, + VercelProjectSchema: () => VercelProjectSchema, + VercelProviderSchema: () => VercelProviderSchema, + VercelTeamSchema: () => VercelTeamSchema, + WebhookConfigSchema: () => WebhookConfigSchema22, + WebhookEventSchema: () => WebhookEventSchema22, + WebhookSignatureAlgorithmSchema: () => WebhookSignatureAlgorithmSchema, + azureBlobConnectorExample: () => azureBlobConnectorExample, + githubEnterpriseConnectorExample: () => githubEnterpriseConnectorExample, + githubPublicConnectorExample: () => githubPublicConnectorExample, + googleDriveConnectorExample: () => googleDriveConnectorExample, + hubspotConnectorExample: () => hubspotConnectorExample, + kafkaConnectorExample: () => kafkaConnectorExample, + mongoConnectorExample: () => mongoConnectorExample, + postgresConnectorExample: () => postgresConnectorExample, + pubsubConnectorExample: () => pubsubConnectorExample, + rabbitmqConnectorExample: () => rabbitmqConnectorExample, + s3ConnectorExample: () => s3ConnectorExample, + salesforceConnectorExample: () => salesforceConnectorExample, + snowflakeConnectorExample: () => snowflakeConnectorExample, + sqsConnectorExample: () => sqsConnectorExample, + vercelNextJsConnectorExample: () => vercelNextJsConnectorExample, + vercelStaticSiteConnectorExample: () => vercelStaticSiteConnectorExample +}); +var ConnectorOAuth2Schema = external_exports.object({ + type: external_exports.literal("oauth2"), + authorizationUrl: external_exports.string().url().describe("OAuth2 authorization endpoint"), + tokenUrl: external_exports.string().url().describe("OAuth2 token endpoint"), + clientId: external_exports.string().describe("OAuth2 client ID"), + clientSecret: external_exports.string().describe("OAuth2 client secret (typically from ENV)"), + scopes: external_exports.array(external_exports.string()).optional().describe("Requested OAuth2 scopes"), + redirectUri: external_exports.string().url().optional().describe("OAuth2 redirect URI"), + refreshToken: external_exports.string().optional().describe("Refresh token for token renewal"), + tokenExpiry: external_exports.number().optional().describe("Token expiry timestamp") +}); +var ConnectorAPIKeySchema = external_exports.object({ + type: external_exports.literal("api-key"), + key: external_exports.string().describe("API key value"), + headerName: external_exports.string().default("X-API-Key").describe("HTTP header name for API key"), + paramName: external_exports.string().optional().describe("Query parameter name (alternative to header)") +}); +var ConnectorBasicAuthSchema = external_exports.object({ + type: external_exports.literal("basic"), + username: external_exports.string().describe("Username"), + password: external_exports.string().describe("Password") +}); +var ConnectorBearerAuthSchema = external_exports.object({ + type: external_exports.literal("bearer"), + token: external_exports.string().describe("Bearer token") +}); +var ConnectorNoAuthSchema = external_exports.object({ + type: external_exports.literal("none") +}); +var ConnectorAuthConfigSchema = external_exports.discriminatedUnion("type", [ + ConnectorOAuth2Schema, + ConnectorAPIKeySchema, + ConnectorBasicAuthSchema, + ConnectorBearerAuthSchema, + ConnectorNoAuthSchema +]); +var FieldMappingSchema32 = FieldMappingSchema4.extend({ + /** + * Data type mapping (connector-specific) + */ + dataType: external_exports.enum([ + "string", + "number", + "boolean", + "date", + "datetime", + "json", + "array" + ]).optional().describe("Target data type"), + /** + * Is this field required? + */ + required: external_exports.boolean().default(false).describe("Field is required"), + /** + * Bidirectional sync mode (connector-specific) + */ + syncMode: external_exports.enum([ + "read_only", + // Only sync from external to ObjectStack + "write_only", + // Only sync from ObjectStack to external + "bidirectional" + // Sync both ways + ]).default("bidirectional").describe("Sync mode") +}); +var SyncStrategySchema = external_exports.enum([ + "full", + // Full refresh (delete all and re-import) + "incremental", + // Only sync changes since last sync + "upsert", + // Insert new, update existing + "append_only" + // Only insert new records +]).describe("Synchronization strategy"); +var ConflictResolutionSchema3 = external_exports.enum([ + "source_wins", + // External system data takes precedence + "target_wins", + // ObjectStack data takes precedence + "latest_wins", + // Most recently modified wins + "manual" + // Flag for manual resolution +]).describe("Conflict resolution strategy"); +var DataSyncConfigSchema2 = external_exports.object({ + /** + * Sync strategy + */ + strategy: SyncStrategySchema.optional().default("incremental"), + /** + * Sync direction + */ + direction: external_exports.enum([ + "import", + // External → ObjectStack + "export", + // ObjectStack → External + "bidirectional" + // Both ways + ]).optional().default("import").describe("Sync direction"), + /** + * Sync frequency (cron expression) + */ + schedule: external_exports.string().optional().describe("Cron expression for scheduled sync"), + /** + * Enable real-time sync via webhooks + */ + realtimeSync: external_exports.boolean().optional().default(false).describe("Enable real-time sync"), + /** + * Field to track last sync timestamp + */ + timestampField: external_exports.string().optional().describe("Field to track last modification time"), + /** + * Conflict resolution strategy + */ + conflictResolution: ConflictResolutionSchema3.optional().default("latest_wins"), + /** + * Batch size for bulk operations + */ + batchSize: external_exports.number().min(1).max(1e4).optional().default(1e3).describe("Records per batch"), + /** + * Delete handling + */ + deleteMode: external_exports.enum([ + "hard_delete", + // Permanently delete + "soft_delete", + // Mark as deleted + "ignore" + // Don't sync deletions + ]).optional().default("soft_delete").describe("Delete handling mode"), + /** + * Filter criteria for selective sync + */ + filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria for selective sync") +}); +var WebhookEventSchema22 = external_exports.enum([ + "record.created", + "record.updated", + "record.deleted", + "sync.started", + "sync.completed", + "sync.failed", + "auth.expired", + "rate_limit.exceeded" +]).describe("Webhook event type"); +var WebhookSignatureAlgorithmSchema = external_exports.enum([ + "hmac_sha256", + "hmac_sha512", + "none" +]).describe("Webhook signature algorithm"); +var WebhookConfigSchema22 = WebhookSchema.extend({ + /** + * Events to listen for + * Connector-specific events like sync completion, auth expiry, etc. + */ + events: external_exports.array(WebhookEventSchema22).optional().describe("Connector events to subscribe to"), + /** + * Signature algorithm for webhook security + */ + signatureAlgorithm: WebhookSignatureAlgorithmSchema.optional().default("hmac_sha256") +}); +var RateLimitStrategySchema = external_exports.enum([ + "fixed_window", + // Fixed time window + "sliding_window", + // Sliding time window + "token_bucket", + // Token bucket algorithm + "leaky_bucket" + // Leaky bucket algorithm +]).describe("Rate limiting strategy"); +var RateLimitConfigSchema22 = external_exports.object({ + /** + * Rate limiting strategy + */ + strategy: RateLimitStrategySchema.optional().default("token_bucket"), + /** + * Maximum requests per window + */ + maxRequests: external_exports.number().min(1).describe("Maximum requests per window"), + /** + * Time window in seconds + */ + windowSeconds: external_exports.number().min(1).describe("Time window in seconds"), + /** + * Burst capacity (for token bucket) + */ + burstCapacity: external_exports.number().min(1).optional().describe("Burst capacity"), + /** + * Respect external system rate limits + */ + respectUpstreamLimits: external_exports.boolean().optional().default(true).describe("Respect external rate limit headers"), + /** + * Custom rate limit headers to check + */ + rateLimitHeaders: external_exports.object({ + remaining: external_exports.string().optional().default("X-RateLimit-Remaining").describe("Header for remaining requests"), + limit: external_exports.string().optional().default("X-RateLimit-Limit").describe("Header for rate limit"), + reset: external_exports.string().optional().default("X-RateLimit-Reset").describe("Header for reset time") + }).optional().describe("Custom rate limit headers") +}); +var RetryStrategySchema = external_exports.enum([ + "exponential_backoff", + "linear_backoff", + "fixed_delay", + "no_retry" +]).describe("Retry strategy"); +var RetryConfigSchema = external_exports.object({ + /** + * Retry strategy + */ + strategy: RetryStrategySchema.optional().default("exponential_backoff"), + /** + * Maximum retry attempts + */ + maxAttempts: external_exports.number().min(0).max(10).optional().default(3).describe("Maximum retry attempts"), + /** + * Initial delay in milliseconds + */ + initialDelayMs: external_exports.number().min(100).optional().default(1e3).describe("Initial retry delay in ms"), + /** + * Maximum delay in milliseconds + */ + maxDelayMs: external_exports.number().min(1e3).optional().default(6e4).describe("Maximum retry delay in ms"), + /** + * Backoff multiplier (for exponential backoff) + */ + backoffMultiplier: external_exports.number().min(1).optional().default(2).describe("Exponential backoff multiplier"), + /** + * HTTP status codes to retry + */ + retryableStatusCodes: external_exports.array(external_exports.number()).optional().default([408, 429, 500, 502, 503, 504]).describe("HTTP status codes to retry"), + /** + * Retry on network errors + */ + retryOnNetworkError: external_exports.boolean().optional().default(true).describe("Retry on network errors"), + /** + * Jitter to add randomness to retry delays + */ + jitter: external_exports.boolean().optional().default(true).describe("Add jitter to retry delays") +}); +var ErrorCategorySchema = external_exports.enum([ + "validation", + "authorization", + "not_found", + "conflict", + "rate_limit", + "timeout", + "server_error", + "integration_error" +]).describe("Standard error category"); +var ErrorMappingRuleSchema = external_exports.object({ + sourceCode: external_exports.union([external_exports.string(), external_exports.number()]).describe("External system error code"), + sourceMessage: external_exports.string().optional().describe("Pattern to match against error message"), + targetCode: external_exports.string().describe("ObjectStack standard error code"), + targetCategory: ErrorCategorySchema.describe("Error category"), + severity: external_exports.enum(["low", "medium", "high", "critical"]).describe("Error severity level"), + retryable: external_exports.boolean().describe("Whether the error is retryable"), + userMessage: external_exports.string().optional().describe("Human-readable message to show users") +}).describe("Error mapping rule"); +var ErrorMappingConfigSchema = external_exports.object({ + rules: external_exports.array(ErrorMappingRuleSchema).describe("Error mapping rules"), + defaultCategory: ErrorCategorySchema.optional().default("integration_error").describe("Default category for unmapped errors"), + unmappedBehavior: external_exports.enum(["passthrough", "generic_error", "throw"]).describe("What to do with unmapped errors"), + logUnmapped: external_exports.boolean().optional().default(true).describe("Log unmapped errors") +}).describe("Error mapping configuration"); +var HealthCheckConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable health checks"), + intervalMs: external_exports.number().optional().default(6e4).describe("Health check interval in milliseconds"), + timeoutMs: external_exports.number().optional().default(5e3).describe("Health check timeout in milliseconds"), + endpoint: external_exports.string().optional().describe("Health check endpoint path"), + method: external_exports.enum(["GET", "HEAD", "OPTIONS"]).optional().describe("HTTP method for health check"), + expectedStatus: external_exports.number().optional().default(200).describe("Expected HTTP status code"), + unhealthyThreshold: external_exports.number().optional().default(3).describe("Consecutive failures before marking unhealthy"), + healthyThreshold: external_exports.number().optional().default(1).describe("Consecutive successes before marking healthy") +}).describe("Health check configuration"); +var CircuitBreakerConfigSchema = external_exports.object({ + enabled: external_exports.boolean().describe("Enable circuit breaker"), + failureThreshold: external_exports.number().optional().default(5).describe("Failures before opening circuit"), + resetTimeoutMs: external_exports.number().optional().default(3e4).describe("Time in open state before half-open"), + halfOpenMaxRequests: external_exports.number().optional().default(1).describe("Requests allowed in half-open state"), + monitoringWindow: external_exports.number().optional().default(6e4).describe("Rolling window for failure count in ms"), + fallbackStrategy: external_exports.enum(["cache", "default_value", "error", "queue"]).optional().describe("Fallback strategy when circuit is open") +}).describe("Circuit breaker configuration"); +var ConnectorHealthSchema = external_exports.object({ + healthCheck: HealthCheckConfigSchema.optional().describe("Health check configuration"), + circuitBreaker: CircuitBreakerConfigSchema.optional().describe("Circuit breaker configuration") +}).describe("Connector health configuration"); +var ConnectorTypeSchema = external_exports.enum([ + "saas", + // SaaS application connector + "database", + // Database connector + "file_storage", + // File storage connector + "message_queue", + // Message queue connector + "api", + // Generic REST/GraphQL API + "custom" + // Custom connector +]).describe("Connector type"); +var ConnectorStatusSchema = external_exports.enum([ + "active", + // Connector is active and syncing + "inactive", + // Connector is configured but disabled + "error", + // Connector has errors + "configuring" + // Connector is being set up +]).describe("Connector status"); +var ConnectorActionSchema = external_exports.object({ + key: external_exports.string().describe("Action key (machine name)"), + label: external_exports.string().describe("Human readable label"), + description: external_exports.string().optional(), + inputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Input parameters schema (JSON Schema)"), + outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Output schema (JSON Schema)") +}); +var ConnectorTriggerSchema2 = external_exports.object({ + key: external_exports.string().describe("Trigger key"), + label: external_exports.string().describe("Trigger label"), + description: external_exports.string().optional(), + type: external_exports.enum(["polling", "webhook"]).describe("Trigger type"), + interval: external_exports.number().optional().describe("Polling interval in seconds") +}); +var ConnectorSchema2 = external_exports.object({ + /** + * Machine name (snake_case) + */ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique connector identifier"), + /** + * Human-readable label + */ + label: external_exports.string().describe("Display label"), + /** + * Connector type + */ + type: ConnectorTypeSchema.describe("Connector type"), + /** + * Description + */ + description: external_exports.string().optional().describe("Connector description"), + /** + * Icon identifier + */ + icon: external_exports.string().optional().describe("Icon identifier"), + /** + * Authentication configuration + */ + authentication: ConnectorAuthConfigSchema.describe("Authentication configuration"), + /** Zapier-style Capabilities */ + actions: external_exports.array(ConnectorActionSchema).optional(), + triggers: external_exports.array(ConnectorTriggerSchema2).optional(), + /** + * Data synchronization configuration + */ + syncConfig: DataSyncConfigSchema2.optional().describe("Data sync configuration"), + /** + * Field mappings + */ + fieldMappings: external_exports.array(FieldMappingSchema32).optional().describe("Field mapping rules"), + /** + * Webhook configuration + */ + webhooks: external_exports.array(WebhookConfigSchema22).optional().describe("Webhook configurations"), + /** + * Rate limiting configuration + */ + rateLimitConfig: RateLimitConfigSchema22.optional().describe("Rate limiting configuration"), + /** + * Retry configuration + */ + retryConfig: RetryConfigSchema.optional().describe("Retry configuration"), + /** + * Connection timeout in milliseconds + */ + connectionTimeoutMs: external_exports.number().min(1e3).max(3e5).optional().default(3e4).describe("Connection timeout in ms"), + /** + * Request timeout in milliseconds + */ + requestTimeoutMs: external_exports.number().min(1e3).max(3e5).optional().default(3e4).describe("Request timeout in ms"), + /** + * Connector status + */ + status: ConnectorStatusSchema.optional().default("inactive").describe("Connector status"), + /** + * Enable connector + */ + enabled: external_exports.boolean().optional().default(true).describe("Enable connector"), + /** + * Error mapping configuration + */ + errorMapping: ErrorMappingConfigSchema.optional().describe("Error mapping configuration"), + /** + * Health check and circuit breaker configuration + */ + health: ConnectorHealthSchema.optional().describe("Health and resilience configuration"), + /** + * Custom metadata + */ + metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom connector metadata") +}); +var SaasProviderSchema = external_exports.enum([ + "salesforce", + "hubspot", + "stripe", + "shopify", + "zendesk", + "intercom", + "mailchimp", + "slack", + "microsoft_dynamics", + "servicenow", + "netsuite", + "custom" +]).describe("SaaS provider type"); +var ApiVersionConfigSchema = external_exports.object({ + version: external_exports.string().describe('API version (e.g., "v2", "2023-10-01")'), + isDefault: external_exports.boolean().default(false).describe("Is this the default version"), + deprecationDate: external_exports.string().optional().describe("API version deprecation date (ISO 8601)"), + sunsetDate: external_exports.string().optional().describe("API version sunset date (ISO 8601)") +}); +var SaasObjectTypeSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Object type name (snake_case)"), + label: external_exports.string().describe("Display label"), + apiName: external_exports.string().describe("API name in external system"), + enabled: external_exports.boolean().default(true).describe("Enable sync for this object"), + supportsCreate: external_exports.boolean().default(true).describe("Supports record creation"), + supportsUpdate: external_exports.boolean().default(true).describe("Supports record updates"), + supportsDelete: external_exports.boolean().default(true).describe("Supports record deletion"), + fieldMappings: external_exports.array(FieldMappingSchema32).optional().describe("Object-specific field mappings") +}); +var SaasConnectorSchema = ConnectorSchema2.extend({ + type: external_exports.literal("saas"), + /** + * SaaS provider + */ + provider: SaasProviderSchema.describe("SaaS provider type"), + /** + * Base URL for API requests + */ + baseUrl: external_exports.string().url().describe("API base URL"), + /** + * API version configuration + */ + apiVersion: ApiVersionConfigSchema.optional().describe("API version configuration"), + /** + * Supported object types to sync + */ + objectTypes: external_exports.array(SaasObjectTypeSchema).describe("Syncable object types"), + /** + * OAuth-specific settings + */ + oauthSettings: external_exports.object({ + scopes: external_exports.array(external_exports.string()).describe("Required OAuth scopes"), + refreshTokenUrl: external_exports.string().url().optional().describe("Token refresh endpoint"), + revokeTokenUrl: external_exports.string().url().optional().describe("Token revocation endpoint"), + autoRefresh: external_exports.boolean().default(true).describe("Automatically refresh expired tokens") + }).optional().describe("OAuth-specific configuration"), + /** + * Pagination settings + */ + paginationConfig: external_exports.object({ + type: external_exports.enum(["cursor", "offset", "page"]).default("cursor").describe("Pagination type"), + defaultPageSize: external_exports.number().min(1).max(1e3).default(100).describe("Default page size"), + maxPageSize: external_exports.number().min(1).max(1e4).default(1e3).describe("Maximum page size") + }).optional().describe("Pagination configuration"), + /** + * Sandbox/test environment settings + */ + sandboxConfig: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Use sandbox environment"), + baseUrl: external_exports.string().url().optional().describe("Sandbox API base URL") + }).optional().describe("Sandbox environment configuration"), + /** + * Custom request headers + */ + customHeaders: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers for all requests") +}); +var salesforceConnectorExample = { + name: "salesforce_production", + label: "Salesforce Production", + type: "saas", + provider: "salesforce", + baseUrl: "https://example.my.salesforce.com", + apiVersion: { + version: "v59.0", + isDefault: true + }, + authentication: { + type: "oauth2", + clientId: "${SALESFORCE_CLIENT_ID}", + clientSecret: "${SALESFORCE_CLIENT_SECRET}", + authorizationUrl: "https://login.salesforce.com/services/oauth2/authorize", + tokenUrl: "https://login.salesforce.com/services/oauth2/token", + grantType: "authorization_code", + scopes: ["api", "refresh_token", "offline_access"] + }, + objectTypes: [ + { + name: "account", + label: "Account", + apiName: "Account", + enabled: true, + supportsCreate: true, + supportsUpdate: true, + supportsDelete: true + }, + { + name: "contact", + label: "Contact", + apiName: "Contact", + enabled: true, + supportsCreate: true, + supportsUpdate: true, + supportsDelete: true + } + ], + syncConfig: { + strategy: "incremental", + direction: "bidirectional", + schedule: "0 */6 * * *", + // Every 6 hours + realtimeSync: true, + conflictResolution: "latest_wins", + batchSize: 200, + deleteMode: "soft_delete" + }, + rateLimitConfig: { + strategy: "token_bucket", + maxRequests: 100, + windowSeconds: 20, + respectUpstreamLimits: true + }, + retryConfig: { + strategy: "exponential_backoff", + maxAttempts: 3, + initialDelayMs: 1e3, + maxDelayMs: 3e4, + backoffMultiplier: 2, + retryableStatusCodes: [408, 429, 500, 502, 503, 504], + retryOnNetworkError: true, + jitter: true + }, + status: "active", + enabled: true +}; +var hubspotConnectorExample = { + name: "hubspot_crm", + label: "HubSpot CRM", + type: "saas", + provider: "hubspot", + baseUrl: "https://api.hubapi.com", + authentication: { + type: "api_key", + apiKey: "${HUBSPOT_API_KEY}", + headerName: "Authorization" + }, + objectTypes: [ + { + name: "company", + label: "Company", + apiName: "companies", + enabled: true, + supportsCreate: true, + supportsUpdate: true, + supportsDelete: true + }, + { + name: "deal", + label: "Deal", + apiName: "deals", + enabled: true, + supportsCreate: true, + supportsUpdate: true, + supportsDelete: true + } + ], + syncConfig: { + strategy: "incremental", + direction: "import", + schedule: "0 */4 * * *", + // Every 4 hours + conflictResolution: "source_wins", + batchSize: 100 + }, + rateLimitConfig: { + strategy: "token_bucket", + maxRequests: 100, + windowSeconds: 10 + }, + status: "active", + enabled: true +}; +var DatabaseProviderSchema22 = external_exports.enum([ + "postgresql", + "mysql", + "mariadb", + "mssql", + "oracle", + "mongodb", + "redis", + "cassandra", + "snowflake", + "bigquery", + "redshift", + "custom" +]).describe("Database provider type"); +var DatabasePoolConfigSchema = external_exports.object({ + min: external_exports.number().min(0).default(2).describe("Minimum connections in pool"), + max: external_exports.number().min(1).default(10).describe("Maximum connections in pool"), + idleTimeoutMs: external_exports.number().min(1e3).default(3e4).describe("Idle connection timeout in ms"), + connectionTimeoutMs: external_exports.number().min(1e3).default(1e4).describe("Connection establishment timeout in ms"), + acquireTimeoutMs: external_exports.number().min(1e3).default(3e4).describe("Connection acquisition timeout in ms"), + evictionRunIntervalMs: external_exports.number().min(1e3).default(3e4).describe("Connection eviction check interval in ms"), + testOnBorrow: external_exports.boolean().default(true).describe("Test connection before use") +}); +var SslConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable SSL/TLS"), + rejectUnauthorized: external_exports.boolean().default(true).describe("Reject unauthorized certificates"), + ca: external_exports.string().optional().describe("Certificate Authority certificate"), + cert: external_exports.string().optional().describe("Client certificate"), + key: external_exports.string().optional().describe("Client private key") +}); +var CdcConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable CDC"), + method: external_exports.enum([ + "log_based", + // Transaction log parsing (e.g., PostgreSQL logical replication) + "trigger_based", + // Database triggers for change tracking + "query_based", + // Timestamp-based queries + "custom" + // Custom CDC implementation + ]).describe("CDC method"), + slotName: external_exports.string().optional().describe("Replication slot name (for log-based CDC)"), + publicationName: external_exports.string().optional().describe("Publication name (for PostgreSQL)"), + startPosition: external_exports.string().optional().describe("Starting position/LSN for CDC stream"), + batchSize: external_exports.number().min(1).max(1e4).default(1e3).describe("CDC batch size"), + pollIntervalMs: external_exports.number().min(100).default(1e3).describe("CDC polling interval in ms") +}); +var DatabaseTableSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Table name in ObjectStack (snake_case)"), + label: external_exports.string().describe("Display label"), + schema: external_exports.string().optional().describe("Database schema name"), + tableName: external_exports.string().describe("Actual table name in database"), + primaryKey: external_exports.string().describe("Primary key column"), + enabled: external_exports.boolean().default(true).describe("Enable sync for this table"), + fieldMappings: external_exports.array(FieldMappingSchema32).optional().describe("Table-specific field mappings"), + whereClause: external_exports.string().optional().describe("SQL WHERE clause for filtering") +}); +var DatabaseConnectorSchema = ConnectorSchema2.extend({ + type: external_exports.literal("database"), + /** + * Database provider + */ + provider: DatabaseProviderSchema22.describe("Database provider type"), + /** + * Connection configuration + */ + connectionConfig: external_exports.object({ + host: external_exports.string().describe("Database host"), + port: external_exports.number().min(1).max(65535).describe("Database port"), + database: external_exports.string().describe("Database name"), + username: external_exports.string().describe("Database username"), + password: external_exports.string().describe("Database password (typically from ENV)"), + options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Driver-specific connection options") + }).describe("Database connection configuration"), + /** + * Connection pool configuration + */ + poolConfig: DatabasePoolConfigSchema.optional().describe("Connection pool configuration"), + /** + * SSL/TLS configuration + */ + sslConfig: SslConfigSchema.optional().describe("SSL/TLS configuration"), + /** + * Tables to sync + */ + tables: external_exports.array(DatabaseTableSchema).describe("Tables to sync"), + /** + * Change Data Capture configuration + */ + cdcConfig: CdcConfigSchema.optional().describe("CDC configuration"), + /** + * Read replica configuration + */ + readReplicaConfig: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Use read replicas"), + hosts: external_exports.array(external_exports.object({ + host: external_exports.string().describe("Replica host"), + port: external_exports.number().min(1).max(65535).describe("Replica port"), + weight: external_exports.number().min(0).max(1).default(1).describe("Load balancing weight") + })).describe("Read replica hosts") + }).optional().describe("Read replica configuration"), + /** + * Query timeout + */ + queryTimeoutMs: external_exports.number().min(1e3).max(3e5).optional().default(3e4).describe("Query timeout in ms"), + /** + * Enable query logging + */ + enableQueryLogging: external_exports.boolean().optional().default(false).describe("Enable SQL query logging") +}); +var postgresConnectorExample = { + name: "postgres_production", + label: "Production PostgreSQL", + type: "database", + provider: "postgresql", + authentication: { + type: "basic", + username: "${DB_USERNAME}", + password: "${DB_PASSWORD}" + }, + connectionConfig: { + host: "db.example.com", + port: 5432, + database: "production", + username: "${DB_USERNAME}", + password: "${DB_PASSWORD}" + }, + poolConfig: { + min: 2, + max: 20, + idleTimeoutMs: 3e4, + connectionTimeoutMs: 1e4, + acquireTimeoutMs: 3e4, + evictionRunIntervalMs: 3e4, + testOnBorrow: true + }, + sslConfig: { + enabled: true, + rejectUnauthorized: true + }, + tables: [ + { + name: "customer", + label: "Customer", + schema: "public", + tableName: "customers", + primaryKey: "id", + enabled: true + }, + { + name: "order", + label: "Order", + schema: "public", + tableName: "orders", + primaryKey: "id", + enabled: true, + whereClause: "status != 'archived'" + } + ], + cdcConfig: { + enabled: true, + method: "log_based", + slotName: "objectstack_replication_slot", + publicationName: "objectstack_publication", + batchSize: 1e3, + pollIntervalMs: 1e3 + }, + syncConfig: { + strategy: "incremental", + direction: "bidirectional", + realtimeSync: true, + conflictResolution: "latest_wins", + batchSize: 1e3, + deleteMode: "soft_delete" + }, + status: "active", + enabled: true +}; +var mongoConnectorExample = { + name: "mongodb_analytics", + label: "MongoDB Analytics", + type: "database", + provider: "mongodb", + authentication: { + type: "basic", + username: "${MONGO_USERNAME}", + password: "${MONGO_PASSWORD}" + }, + connectionConfig: { + host: "mongodb.example.com", + port: 27017, + database: "analytics", + username: "${MONGO_USERNAME}", + password: "${MONGO_PASSWORD}", + options: { + authSource: "admin", + replicaSet: "rs0" + } + }, + tables: [ + { + name: "event", + label: "Event", + tableName: "events", + primaryKey: "id", + enabled: true + } + ], + cdcConfig: { + enabled: true, + method: "log_based", + batchSize: 1e3, + pollIntervalMs: 500 + }, + syncConfig: { + strategy: "incremental", + direction: "import", + batchSize: 1e3 + }, + status: "active", + enabled: true +}; +var snowflakeConnectorExample = { + name: "snowflake_warehouse", + label: "Snowflake Data Warehouse", + type: "database", + provider: "snowflake", + authentication: { + type: "basic", + username: "${SNOWFLAKE_USERNAME}", + password: "${SNOWFLAKE_PASSWORD}" + }, + connectionConfig: { + host: "account.snowflakecomputing.com", + port: 443, + database: "ANALYTICS_DB", + username: "${SNOWFLAKE_USERNAME}", + password: "${SNOWFLAKE_PASSWORD}", + options: { + warehouse: "COMPUTE_WH", + schema: "PUBLIC", + role: "ANALYST" + } + }, + tables: [ + { + name: "sales_summary", + label: "Sales Summary", + schema: "PUBLIC", + tableName: "SALES_SUMMARY", + primaryKey: "ID", + enabled: true + } + ], + syncConfig: { + strategy: "full", + direction: "import", + schedule: "0 2 * * *", + // Daily at 2 AM + batchSize: 5e3 + }, + queryTimeoutMs: 6e4, + status: "active", + enabled: true +}; +var FileStorageProviderSchema = external_exports.enum([ + "s3", + // Amazon S3 + "azure_blob", + // Azure Blob Storage + "gcs", + // Google Cloud Storage + "dropbox", + // Dropbox + "box", + // Box + "onedrive", + // Microsoft OneDrive + "google_drive", + // Google Drive + "sharepoint", + // SharePoint + "ftp", + // FTP/SFTP + "local", + // Local file system + "custom" + // Custom file storage +]).describe("File storage provider type"); +var FileAccessPatternSchema = external_exports.enum([ + "public_read", + // Public read access + "private", + // Private access + "authenticated_read", + // Requires authentication + "bucket_owner_read", + // Bucket owner has read access + "bucket_owner_full" + // Bucket owner has full control +]).describe("File access pattern"); +var FileMetadataConfigSchema = external_exports.object({ + extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata"), + metadataFields: external_exports.array(external_exports.enum([ + "content_type", + "file_size", + "last_modified", + "etag", + "checksum", + "creator", + "created_at", + "custom" + ])).optional().describe("Metadata fields to extract"), + customMetadata: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom metadata key-value pairs") +}); +var MultipartUploadConfigSchema22 = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable multipart uploads"), + partSize: external_exports.number().min(5 * 1024 * 1024).default(5 * 1024 * 1024).describe("Part size in bytes (min 5MB)"), + maxConcurrentParts: external_exports.number().min(1).max(10).default(5).describe("Maximum concurrent part uploads"), + threshold: external_exports.number().min(5 * 1024 * 1024).default(100 * 1024 * 1024).describe("File size threshold for multipart upload in bytes") +}); +var FileVersioningConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable file versioning"), + maxVersions: external_exports.number().min(1).max(100).optional().describe("Maximum versions to retain"), + retentionDays: external_exports.number().min(1).optional().describe("Version retention period in days") +}); +var FileFilterConfigSchema = external_exports.object({ + includePatterns: external_exports.array(external_exports.string()).optional().describe("File patterns to include (glob)"), + excludePatterns: external_exports.array(external_exports.string()).optional().describe("File patterns to exclude (glob)"), + minFileSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), + maxFileSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes"), + allowedExtensions: external_exports.array(external_exports.string()).optional().describe("Allowed file extensions"), + blockedExtensions: external_exports.array(external_exports.string()).optional().describe("Blocked file extensions") +}); +var StorageBucketSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Bucket identifier in ObjectStack (snake_case)"), + label: external_exports.string().describe("Display label"), + bucketName: external_exports.string().describe("Actual bucket/container name in storage system"), + region: external_exports.string().optional().describe("Storage region"), + enabled: external_exports.boolean().default(true).describe("Enable sync for this bucket"), + prefix: external_exports.string().optional().describe("Prefix/path within bucket"), + accessPattern: FileAccessPatternSchema.optional().describe("Access pattern"), + fileFilters: FileFilterConfigSchema.optional().describe("File filter configuration") +}); +var FileStorageConnectorSchema = ConnectorSchema2.extend({ + type: external_exports.literal("file_storage"), + /** + * File storage provider + */ + provider: FileStorageProviderSchema.describe("File storage provider type"), + /** + * Storage configuration + */ + storageConfig: external_exports.object({ + endpoint: external_exports.string().url().optional().describe("Custom endpoint URL"), + region: external_exports.string().optional().describe("Default region"), + pathStyle: external_exports.boolean().optional().default(false).describe("Use path-style URLs (for S3-compatible)") + }).optional().describe("Storage configuration"), + /** + * Buckets/containers to sync + */ + buckets: external_exports.array(StorageBucketSchema).describe("Buckets/containers to sync"), + /** + * File metadata configuration + */ + metadataConfig: FileMetadataConfigSchema.optional().describe("Metadata extraction configuration"), + /** + * Multipart upload configuration + */ + multipartConfig: MultipartUploadConfigSchema22.optional().describe("Multipart upload configuration"), + /** + * File versioning configuration + */ + versioningConfig: FileVersioningConfigSchema.optional().describe("File versioning configuration"), + /** + * Enable server-side encryption + */ + encryption: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable server-side encryption"), + algorithm: external_exports.enum(["AES256", "aws:kms", "custom"]).optional().describe("Encryption algorithm"), + kmsKeyId: external_exports.string().optional().describe("KMS key ID (for aws:kms)") + }).optional().describe("Encryption configuration"), + /** + * Lifecycle policy + */ + lifecyclePolicy: external_exports.object({ + enabled: external_exports.boolean().default(false).describe("Enable lifecycle policy"), + deleteAfterDays: external_exports.number().min(1).optional().describe("Delete files after N days"), + archiveAfterDays: external_exports.number().min(1).optional().describe("Archive files after N days") + }).optional().describe("Lifecycle policy"), + /** + * Content processing configuration + */ + contentProcessing: external_exports.object({ + extractText: external_exports.boolean().default(false).describe("Extract text from documents"), + generateThumbnails: external_exports.boolean().default(false).describe("Generate image thumbnails"), + thumbnailSizes: external_exports.array(external_exports.object({ + width: external_exports.number().min(1), + height: external_exports.number().min(1) + })).optional().describe("Thumbnail sizes"), + virusScan: external_exports.boolean().default(false).describe("Scan for viruses") + }).optional().describe("Content processing configuration"), + /** + * Download/upload buffer size + */ + bufferSize: external_exports.number().min(1024).default(64 * 1024).describe("Buffer size in bytes"), + /** + * Enable transfer acceleration (for supported providers) + */ + transferAcceleration: external_exports.boolean().default(false).describe("Enable transfer acceleration") +}); +var s3ConnectorExample = { + name: "s3_production_assets", + label: "Production S3 Assets", + type: "file_storage", + provider: "s3", + authentication: { + type: "api_key", + apiKey: "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}", + headerName: "Authorization" + }, + storageConfig: { + region: "us-east-1", + pathStyle: false + }, + buckets: [ + { + name: "product_images", + label: "Product Images", + bucketName: "my-company-product-images", + region: "us-east-1", + enabled: true, + prefix: "products/", + accessPattern: "public_read", + fileFilters: { + allowedExtensions: [".jpg", ".jpeg", ".png", ".webp"], + maxFileSize: 10 * 1024 * 1024 + // 10MB + } + }, + { + name: "customer_documents", + label: "Customer Documents", + bucketName: "my-company-customer-docs", + region: "us-east-1", + enabled: true, + accessPattern: "private", + fileFilters: { + allowedExtensions: [".pdf", ".docx", ".xlsx"], + maxFileSize: 50 * 1024 * 1024 + // 50MB + } + } + ], + metadataConfig: { + extractMetadata: true, + metadataFields: ["content_type", "file_size", "last_modified", "etag"] + }, + multipartConfig: { + enabled: true, + partSize: 5 * 1024 * 1024, + // 5MB + maxConcurrentParts: 5, + threshold: 100 * 1024 * 1024 + // 100MB + }, + versioningConfig: { + enabled: true, + maxVersions: 10 + }, + encryption: { + enabled: true, + algorithm: "aws:kms", + kmsKeyId: "${AWS_KMS_KEY_ID}" + }, + contentProcessing: { + extractText: true, + generateThumbnails: true, + thumbnailSizes: [ + { width: 150, height: 150 }, + { width: 300, height: 300 }, + { width: 600, height: 600 } + ], + virusScan: true + }, + syncConfig: { + strategy: "incremental", + direction: "bidirectional", + realtimeSync: true, + conflictResolution: "latest_wins", + batchSize: 100 + }, + transferAcceleration: true, + status: "active", + enabled: true +}; +var googleDriveConnectorExample = { + name: "google_drive_team", + label: "Google Drive Team Folder", + type: "file_storage", + provider: "google_drive", + authentication: { + type: "oauth2", + clientId: "${GOOGLE_CLIENT_ID}", + clientSecret: "${GOOGLE_CLIENT_SECRET}", + authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth", + tokenUrl: "https://oauth2.googleapis.com/token", + grantType: "authorization_code", + scopes: ["https://www.googleapis.com/auth/drive.file"] + }, + buckets: [ + { + name: "team_drive", + label: "Team Drive", + bucketName: "shared-team-drive", + enabled: true, + fileFilters: { + excludePatterns: ["*.tmp", "~$*"] + } + } + ], + metadataConfig: { + extractMetadata: true, + metadataFields: ["content_type", "file_size", "last_modified", "creator", "created_at"] + }, + versioningConfig: { + enabled: true, + maxVersions: 5 + }, + syncConfig: { + strategy: "incremental", + direction: "bidirectional", + realtimeSync: true, + conflictResolution: "latest_wins", + batchSize: 50 + }, + status: "active", + enabled: true +}; +var azureBlobConnectorExample = { + name: "azure_blob_storage", + label: "Azure Blob Storage", + type: "file_storage", + provider: "azure_blob", + authentication: { + type: "api_key", + apiKey: "${AZURE_STORAGE_ACCOUNT_KEY}", + headerName: "x-ms-blob-type" + }, + storageConfig: { + endpoint: "https://myaccount.blob.core.windows.net" + }, + buckets: [ + { + name: "archive_container", + label: "Archive Container", + bucketName: "archive", + enabled: true, + accessPattern: "private" + } + ], + metadataConfig: { + extractMetadata: true, + metadataFields: ["content_type", "file_size", "last_modified", "etag"] + }, + encryption: { + enabled: true, + algorithm: "AES256" + }, + lifecyclePolicy: { + enabled: true, + archiveAfterDays: 90, + deleteAfterDays: 365 + }, + syncConfig: { + strategy: "incremental", + direction: "import", + schedule: "0 1 * * *", + // Daily at 1 AM + batchSize: 200 + }, + status: "active", + enabled: true +}; +var MessageQueueProviderSchema22 = external_exports.enum([ + "rabbitmq", + // RabbitMQ + "kafka", + // Apache Kafka + "redis_pubsub", + // Redis Pub/Sub + "redis_streams", + // Redis Streams + "aws_sqs", + // Amazon SQS + "aws_sns", + // Amazon SNS + "google_pubsub", + // Google Cloud Pub/Sub + "azure_service_bus", + // Azure Service Bus + "azure_event_hubs", + // Azure Event Hubs + "nats", + // NATS + "pulsar", + // Apache Pulsar + "activemq", + // Apache ActiveMQ + "custom" + // Custom message queue +]).describe("Message queue provider type"); +var MessageFormatSchema22 = external_exports.enum([ + "json", + "xml", + "protobuf", + "avro", + "text", + "binary" +]).describe("Message format/serialization"); +var AckModeSchema = external_exports.enum([ + "auto", + // Auto-acknowledge + "manual", + // Manual acknowledge after processing + "client" + // Client-controlled acknowledge +]).describe("Message acknowledgment mode"); +var DeliveryGuaranteeSchema = external_exports.enum([ + "at_most_once", + // Fire and forget + "at_least_once", + // May deliver duplicates + "exactly_once" + // Guaranteed exactly once delivery +]).describe("Message delivery guarantee"); +var ConsumerConfigSchema22 = external_exports.object({ + enabled: external_exports.boolean().optional().default(true).describe("Enable consumer"), + consumerGroup: external_exports.string().optional().describe("Consumer group ID"), + concurrency: external_exports.number().min(1).max(100).optional().default(1).describe("Number of concurrent consumers"), + prefetchCount: external_exports.number().min(1).max(1e3).optional().default(10).describe("Prefetch count"), + ackMode: AckModeSchema.optional().default("manual"), + autoCommit: external_exports.boolean().optional().default(false).describe("Auto-commit offsets"), + autoCommitIntervalMs: external_exports.number().min(100).optional().default(5e3).describe("Auto-commit interval in ms"), + sessionTimeoutMs: external_exports.number().min(1e3).optional().default(3e4).describe("Session timeout in ms"), + rebalanceTimeoutMs: external_exports.number().min(1e3).optional().describe("Rebalance timeout in ms") +}); +var ProducerConfigSchema = external_exports.object({ + enabled: external_exports.boolean().optional().default(true).describe("Enable producer"), + acks: external_exports.enum(["0", "1", "all"]).optional().default("all").describe("Acknowledgment level"), + compressionType: external_exports.enum(["none", "gzip", "snappy", "lz4", "zstd"]).optional().default("none").describe("Compression type"), + batchSize: external_exports.number().min(1).optional().default(16384).describe("Batch size in bytes"), + lingerMs: external_exports.number().min(0).optional().default(0).describe("Linger time in ms"), + maxInFlightRequests: external_exports.number().min(1).optional().default(5).describe("Max in-flight requests"), + idempotence: external_exports.boolean().optional().default(true).describe("Enable idempotent producer"), + transactional: external_exports.boolean().optional().default(false).describe("Enable transactional producer"), + transactionTimeoutMs: external_exports.number().min(1e3).optional().describe("Transaction timeout in ms") +}); +var DlqConfigSchema = external_exports.object({ + enabled: external_exports.boolean().optional().default(false).describe("Enable DLQ"), + queueName: external_exports.string().describe("Dead letter queue/topic name"), + maxRetries: external_exports.number().min(0).max(100).optional().default(3).describe("Max retries before DLQ"), + retryDelayMs: external_exports.number().min(0).optional().default(6e4).describe("Retry delay in ms") +}); +var TopicQueueSchema = external_exports.object({ + name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Topic/queue identifier in ObjectStack (snake_case)"), + label: external_exports.string().describe("Display label"), + topicName: external_exports.string().describe("Actual topic/queue name in message queue system"), + enabled: external_exports.boolean().optional().default(true).describe("Enable sync for this topic/queue"), + /** + * Consumer or Producer + */ + mode: external_exports.enum(["consumer", "producer", "both"]).optional().default("both").describe("Consumer, producer, or both"), + /** + * Message format + */ + messageFormat: MessageFormatSchema22.optional().default("json"), + /** + * Partition/shard configuration + */ + partitions: external_exports.number().min(1).optional().describe("Number of partitions (for Kafka)"), + /** + * Replication factor + */ + replicationFactor: external_exports.number().min(1).optional().describe("Replication factor (for Kafka)"), + /** + * Consumer configuration + */ + consumerConfig: ConsumerConfigSchema22.optional().describe("Consumer-specific configuration"), + /** + * Producer configuration + */ + producerConfig: ProducerConfigSchema.optional().describe("Producer-specific configuration"), + /** + * Dead letter queue configuration + */ + dlqConfig: DlqConfigSchema.optional().describe("Dead letter queue configuration"), + /** + * Message routing key (for RabbitMQ) + */ + routingKey: external_exports.string().optional().describe("Routing key pattern"), + /** + * Message filter + */ + messageFilter: external_exports.object({ + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Filter by message headers"), + attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter by message attributes") + }).optional().describe("Message filter criteria") +}); +var MessageQueueConnectorSchema = ConnectorSchema2.extend({ + type: external_exports.literal("message_queue"), + /** + * Message queue provider + */ + provider: MessageQueueProviderSchema22.describe("Message queue provider type"), + /** + * Broker configuration + */ + brokerConfig: external_exports.object({ + brokers: external_exports.array(external_exports.string()).describe("Broker addresses (host:port)"), + clientId: external_exports.string().optional().describe("Client ID"), + connectionTimeoutMs: external_exports.number().min(1e3).optional().default(3e4).describe("Connection timeout in ms"), + requestTimeoutMs: external_exports.number().min(1e3).optional().default(3e4).describe("Request timeout in ms") + }).describe("Broker connection configuration"), + /** + * Topics/queues to sync + */ + topics: external_exports.array(TopicQueueSchema).describe("Topics/queues to sync"), + /** + * Delivery guarantee + */ + deliveryGuarantee: DeliveryGuaranteeSchema.optional().default("at_least_once"), + /** + * SSL/TLS configuration + */ + sslConfig: external_exports.object({ + enabled: external_exports.boolean().optional().default(false).describe("Enable SSL/TLS"), + rejectUnauthorized: external_exports.boolean().optional().default(true).describe("Reject unauthorized certificates"), + ca: external_exports.string().optional().describe("CA certificate"), + cert: external_exports.string().optional().describe("Client certificate"), + key: external_exports.string().optional().describe("Client private key") + }).optional().describe("SSL/TLS configuration"), + /** + * SASL authentication (for Kafka) + */ + saslConfig: external_exports.object({ + mechanism: external_exports.enum(["plain", "scram-sha-256", "scram-sha-512", "aws"]).describe("SASL mechanism"), + username: external_exports.string().optional().describe("SASL username"), + password: external_exports.string().optional().describe("SASL password") + }).optional().describe("SASL authentication configuration"), + /** + * Schema registry configuration (for Kafka/Avro) + */ + schemaRegistry: external_exports.object({ + url: external_exports.string().url().describe("Schema registry URL"), + auth: external_exports.object({ + username: external_exports.string().optional(), + password: external_exports.string().optional() + }).optional() + }).optional().describe("Schema registry configuration"), + /** + * Message ordering + */ + preserveOrder: external_exports.boolean().optional().default(true).describe("Preserve message ordering"), + /** + * Enable metrics + */ + enableMetrics: external_exports.boolean().optional().default(true).describe("Enable message queue metrics"), + /** + * Enable distributed tracing + */ + enableTracing: external_exports.boolean().optional().default(false).describe("Enable distributed tracing") +}); +var kafkaConnectorExample = { + name: "kafka_production", + label: "Production Kafka Cluster", + type: "message_queue", + provider: "kafka", + authentication: { + type: "none" + }, + brokerConfig: { + brokers: ["kafka-1.example.com:9092", "kafka-2.example.com:9092", "kafka-3.example.com:9092"], + clientId: "objectstack-client", + connectionTimeoutMs: 3e4, + requestTimeoutMs: 3e4 + }, + topics: [ + { + name: "order_events", + label: "Order Events", + topicName: "orders", + enabled: true, + mode: "consumer", + messageFormat: "json", + partitions: 10, + replicationFactor: 3, + consumerConfig: { + enabled: true, + consumerGroup: "objectstack-consumer-group", + concurrency: 5, + prefetchCount: 100, + ackMode: "manual", + autoCommit: false, + sessionTimeoutMs: 3e4 + }, + dlqConfig: { + enabled: true, + queueName: "orders-dlq", + maxRetries: 3, + retryDelayMs: 6e4 + } + }, + { + name: "user_activity", + label: "User Activity", + topicName: "user-activity", + enabled: true, + mode: "producer", + messageFormat: "json", + partitions: 5, + replicationFactor: 3, + producerConfig: { + enabled: true, + acks: "all", + compressionType: "snappy", + batchSize: 16384, + lingerMs: 10, + maxInFlightRequests: 5, + idempotence: true + } + } + ], + deliveryGuarantee: "at_least_once", + saslConfig: { + mechanism: "scram-sha-256", + username: "${KAFKA_USERNAME}", + password: "${KAFKA_PASSWORD}" + }, + sslConfig: { + enabled: true, + rejectUnauthorized: true + }, + preserveOrder: true, + enableMetrics: true, + enableTracing: true, + status: "active", + enabled: true +}; +var rabbitmqConnectorExample = { + name: "rabbitmq_events", + label: "RabbitMQ Event Bus", + type: "message_queue", + provider: "rabbitmq", + authentication: { + type: "basic", + username: "${RABBITMQ_USERNAME}", + password: "${RABBITMQ_PASSWORD}" + }, + brokerConfig: { + brokers: ["amqp://rabbitmq.example.com:5672"], + clientId: "objectstack-rabbitmq-client" + }, + topics: [ + { + name: "notifications", + label: "Notifications", + topicName: "notifications", + enabled: true, + mode: "both", + messageFormat: "json", + routingKey: "notification.*", + consumerConfig: { + enabled: true, + prefetchCount: 10, + ackMode: "manual" + }, + producerConfig: { + enabled: true + }, + dlqConfig: { + enabled: true, + queueName: "notifications-dlq", + maxRetries: 3, + retryDelayMs: 3e4 + } + } + ], + deliveryGuarantee: "at_least_once", + status: "active", + enabled: true +}; +var sqsConnectorExample = { + name: "aws_sqs_queue", + label: "AWS SQS Queue", + type: "message_queue", + provider: "aws_sqs", + authentication: { + type: "api_key", + apiKey: "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}", + headerName: "Authorization" + }, + brokerConfig: { + brokers: ["https://sqs.us-east-1.amazonaws.com"] + }, + topics: [ + { + name: "task_queue", + label: "Task Queue", + topicName: "task-queue", + enabled: true, + mode: "consumer", + messageFormat: "json", + consumerConfig: { + enabled: true, + concurrency: 10, + prefetchCount: 10, + ackMode: "manual" + }, + dlqConfig: { + enabled: true, + queueName: "task-queue-dlq", + maxRetries: 3, + retryDelayMs: 12e4 + } + } + ], + deliveryGuarantee: "at_least_once", + retryConfig: { + strategy: "exponential_backoff", + maxAttempts: 3, + initialDelayMs: 1e3, + maxDelayMs: 6e4, + backoffMultiplier: 2 + }, + status: "active", + enabled: true +}; +var pubsubConnectorExample = { + name: "gcp_pubsub", + label: "Google Cloud Pub/Sub", + type: "message_queue", + provider: "google_pubsub", + authentication: { + type: "oauth2", + clientId: "${GCP_CLIENT_ID}", + clientSecret: "${GCP_CLIENT_SECRET}", + authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth", + tokenUrl: "https://oauth2.googleapis.com/token", + grantType: "client_credentials", + scopes: ["https://www.googleapis.com/auth/pubsub"] + }, + brokerConfig: { + brokers: ["pubsub.googleapis.com"] + }, + topics: [ + { + name: "analytics_events", + label: "Analytics Events", + topicName: "projects/my-project/topics/analytics-events", + enabled: true, + mode: "both", + messageFormat: "json", + consumerConfig: { + enabled: true, + consumerGroup: "objectstack-subscription", + concurrency: 5, + prefetchCount: 100, + ackMode: "manual" + } + } + ], + deliveryGuarantee: "at_least_once", + enableMetrics: true, + status: "active", + enabled: true +}; +var GitHubProviderSchema = external_exports.enum([ + "github", + // GitHub.com + "github_enterprise" + // GitHub Enterprise Server +]).describe("GitHub provider type"); +var GitHubRepositorySchema = external_exports.object({ + /** + * Repository owner (organization or user) + */ + owner: external_exports.string().describe("Repository owner (organization or username)"), + /** + * Repository name + */ + name: external_exports.string().describe("Repository name"), + /** + * Default branch name + */ + defaultBranch: external_exports.string().optional().default("main").describe("Default branch name"), + /** + * Enable auto-merge for PRs + */ + autoMerge: external_exports.boolean().optional().default(false).describe("Enable auto-merge for pull requests"), + /** + * Branch protection rules + */ + branchProtection: external_exports.object({ + requiredReviewers: external_exports.number().int().min(0).optional().default(1).describe("Required number of reviewers"), + requireStatusChecks: external_exports.boolean().optional().default(true).describe("Require status checks to pass"), + enforceAdmins: external_exports.boolean().optional().default(false).describe("Enforce protections for admins"), + allowForcePushes: external_exports.boolean().optional().default(false).describe("Allow force pushes"), + allowDeletions: external_exports.boolean().optional().default(false).describe("Allow branch deletions") + }).optional().describe("Branch protection configuration"), + /** + * Repository topics/tags + */ + topics: external_exports.array(external_exports.string()).optional().describe("Repository topics") +}); +var GitHubCommitConfigSchema = external_exports.object({ + /** + * Commit author name + */ + authorName: external_exports.string().optional().describe("Commit author name"), + /** + * Commit author email + */ + authorEmail: external_exports.string().email().optional().describe("Commit author email"), + /** + * GPG sign commits + */ + signCommits: external_exports.boolean().optional().default(false).describe("Sign commits with GPG"), + /** + * Commit message template + */ + messageTemplate: external_exports.string().optional().describe("Commit message template"), + /** + * Conventional commits format + */ + useConventionalCommits: external_exports.boolean().optional().default(true).describe("Use conventional commits format") +}); +var GitHubPullRequestConfigSchema = external_exports.object({ + /** + * Default PR title template + */ + titleTemplate: external_exports.string().optional().describe("PR title template"), + /** + * Default PR body template + */ + bodyTemplate: external_exports.string().optional().describe("PR body template"), + /** + * Default reviewers + */ + defaultReviewers: external_exports.array(external_exports.string()).optional().describe("Default reviewers (usernames)"), + /** + * Default assignees + */ + defaultAssignees: external_exports.array(external_exports.string()).optional().describe("Default assignees (usernames)"), + /** + * Default labels + */ + defaultLabels: external_exports.array(external_exports.string()).optional().describe("Default labels"), + /** + * Enable draft PRs by default + */ + draftByDefault: external_exports.boolean().optional().default(false).describe("Create draft PRs by default"), + /** + * Auto-delete head branch after merge + */ + deleteHeadBranch: external_exports.boolean().optional().default(true).describe("Delete head branch after merge") +}); +var GitHubActionsWorkflowSchema = external_exports.object({ + /** + * Workflow name + */ + name: external_exports.string().describe("Workflow name"), + /** + * Workflow file path + */ + path: external_exports.string().describe("Workflow file path (e.g., .github/workflows/ci.yml)"), + /** + * Enable workflow + */ + enabled: external_exports.boolean().optional().default(true).describe("Enable workflow"), + /** + * Workflow triggers + */ + triggers: external_exports.array(external_exports.enum([ + "push", + "pull_request", + "release", + "schedule", + "workflow_dispatch", + "repository_dispatch" + ])).optional().describe("Workflow triggers"), + /** + * Environment variables + */ + env: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Environment variables"), + /** + * Secrets required + */ + secrets: external_exports.array(external_exports.string()).optional().describe("Required secrets") +}); +var GitHubReleaseConfigSchema = external_exports.object({ + /** + * Tag name pattern + */ + tagPattern: external_exports.string().optional().default("v*").describe("Tag name pattern (e.g., v*, release/*)"), + /** + * Use semantic versioning + */ + semanticVersioning: external_exports.boolean().optional().default(true).describe("Use semantic versioning"), + /** + * Generate release notes automatically + */ + autoReleaseNotes: external_exports.boolean().optional().default(true).describe("Generate release notes automatically"), + /** + * Release name template + */ + releaseNameTemplate: external_exports.string().optional().describe("Release name template"), + /** + * Pre-release pattern + */ + preReleasePattern: external_exports.string().optional().describe("Pre-release pattern (e.g., *-alpha, *-beta)"), + /** + * Create draft releases + */ + draftByDefault: external_exports.boolean().optional().default(false).describe("Create draft releases by default") +}); +var GitHubIssueTrackingSchema = external_exports.object({ + /** + * Enable issue tracking + */ + enabled: external_exports.boolean().optional().default(true).describe("Enable issue tracking"), + /** + * Default issue labels + */ + defaultLabels: external_exports.array(external_exports.string()).optional().describe("Default issue labels"), + /** + * Issue template paths + */ + templatePaths: external_exports.array(external_exports.string()).optional().describe("Issue template paths"), + /** + * Auto-assign issues + */ + autoAssign: external_exports.boolean().optional().default(false).describe("Auto-assign issues"), + /** + * Auto-close stale issues + */ + autoCloseStale: external_exports.object({ + enabled: external_exports.boolean().default(false), + daysBeforeStale: external_exports.number().int().min(1).optional().default(60), + daysBeforeClose: external_exports.number().int().min(1).optional().default(7), + staleLabel: external_exports.string().optional().default("stale") + }).optional().describe("Auto-close stale issues configuration") +}); +var GitHubConnectorSchema = ConnectorSchema2.extend({ + type: external_exports.literal("saas"), + /** + * GitHub provider type + */ + provider: GitHubProviderSchema.describe("GitHub provider"), + /** + * GitHub API base URL + */ + baseUrl: external_exports.string().url().optional().default("https://api.github.com").describe("GitHub API base URL"), + /** + * Repositories to integrate + */ + repositories: external_exports.array(GitHubRepositorySchema).describe("Repositories to manage"), + /** + * Commit configuration + */ + commitConfig: GitHubCommitConfigSchema.optional().describe("Commit configuration"), + /** + * Pull request configuration + */ + pullRequestConfig: GitHubPullRequestConfigSchema.optional().describe("Pull request configuration"), + /** + * GitHub Actions workflows + */ + workflows: external_exports.array(GitHubActionsWorkflowSchema).optional().describe("GitHub Actions workflows"), + /** + * Release configuration + */ + releaseConfig: GitHubReleaseConfigSchema.optional().describe("Release configuration"), + /** + * Issue tracking configuration + */ + issueTracking: GitHubIssueTrackingSchema.optional().describe("Issue tracking configuration"), + /** + * Enable webhooks + */ + enableWebhooks: external_exports.boolean().optional().default(true).describe("Enable GitHub webhooks"), + /** + * Webhook events to subscribe + */ + webhookEvents: external_exports.array(external_exports.enum([ + "push", + "pull_request", + "issues", + "issue_comment", + "release", + "workflow_run", + "deployment", + "deployment_status", + "check_run", + "check_suite", + "status" + ])).optional().describe("Webhook events to subscribe to") +}); +var githubPublicConnectorExample = { + name: "github_public", + label: "GitHub.com", + type: "saas", + provider: "github", + baseUrl: "https://api.github.com", + authentication: { + type: "oauth2", + clientId: "${GITHUB_CLIENT_ID}", + clientSecret: "${GITHUB_CLIENT_SECRET}", + authorizationUrl: "https://github.com/login/oauth/authorize", + tokenUrl: "https://github.com/login/oauth/access_token", + scopes: ["repo", "workflow", "write:packages"] + }, + repositories: [ + { + owner: "objectstack-ai", + name: "spec", + defaultBranch: "main", + autoMerge: false, + branchProtection: { + requiredReviewers: 1, + requireStatusChecks: true, + enforceAdmins: false, + allowForcePushes: false, + allowDeletions: false + }, + topics: ["objectstack", "low-code", "metadata-driven"] + } + ], + commitConfig: { + authorName: "ObjectStack Bot", + authorEmail: "bot@objectstack.ai", + signCommits: false, + useConventionalCommits: true + }, + pullRequestConfig: { + titleTemplate: "{{type}}: {{description}}", + defaultReviewers: ["team-lead"], + defaultLabels: ["automated", "ai-generated"], + draftByDefault: false, + deleteHeadBranch: true + }, + workflows: [ + { + name: "CI", + path: ".github/workflows/ci.yml", + enabled: true, + triggers: ["push", "pull_request"] + }, + { + name: "Release", + path: ".github/workflows/release.yml", + enabled: true, + triggers: ["release"] + } + ], + releaseConfig: { + tagPattern: "v*", + semanticVersioning: true, + autoReleaseNotes: true, + releaseNameTemplate: "Release {{version}}", + draftByDefault: false + }, + issueTracking: { + enabled: true, + defaultLabels: ["needs-triage"], + autoAssign: false, + autoCloseStale: { + enabled: true, + daysBeforeStale: 60, + daysBeforeClose: 7, + staleLabel: "stale" + } + }, + enableWebhooks: true, + webhookEvents: ["push", "pull_request", "release", "workflow_run"], + status: "active", + enabled: true +}; +var githubEnterpriseConnectorExample = { + name: "github_enterprise", + label: "GitHub Enterprise", + type: "saas", + provider: "github_enterprise", + baseUrl: "https://github.enterprise.com/api/v3", + authentication: { + type: "oauth2", + clientId: "${GITHUB_ENTERPRISE_CLIENT_ID}", + clientSecret: "${GITHUB_ENTERPRISE_CLIENT_SECRET}", + authorizationUrl: "https://github.enterprise.com/login/oauth/authorize", + tokenUrl: "https://github.enterprise.com/login/oauth/access_token", + scopes: ["repo", "admin:org", "workflow"] + }, + repositories: [ + { + owner: "enterprise-org", + name: "internal-app", + defaultBranch: "develop", + autoMerge: true, + branchProtection: { + requiredReviewers: 2, + requireStatusChecks: true, + enforceAdmins: true, + allowForcePushes: false, + allowDeletions: false + } + } + ], + commitConfig: { + authorName: "CI Bot", + authorEmail: "ci-bot@enterprise.com", + signCommits: true, + useConventionalCommits: true + }, + pullRequestConfig: { + titleTemplate: "[{{branch}}] {{description}}", + bodyTemplate: `## Changes + +{{changes}} + +## Testing + +{{testing}}`, + defaultReviewers: ["tech-lead", "security-team"], + defaultLabels: ["automated"], + draftByDefault: true, + deleteHeadBranch: true + }, + releaseConfig: { + tagPattern: "release/*", + semanticVersioning: true, + autoReleaseNotes: true, + preReleasePattern: "*-rc*", + draftByDefault: true + }, + status: "active", + enabled: true +}; +var VercelProviderSchema = external_exports.enum([ + "vercel" +]).describe("Vercel provider type"); +var VercelFrameworkSchema = external_exports.enum([ + "nextjs", + "react", + "vue", + "nuxtjs", + "gatsby", + "remix", + "astro", + "sveltekit", + "solid", + "angular", + "static", + "other" +]).describe("Frontend framework"); +var GitRepositoryConfigSchema = external_exports.object({ + /** + * Git provider type + */ + type: external_exports.enum(["github", "gitlab", "bitbucket"]).describe("Git provider"), + /** + * Repository identifier (owner/repo) + */ + repo: external_exports.string().describe("Repository identifier (e.g., owner/repo)"), + /** + * Production branch + */ + productionBranch: external_exports.string().optional().default("main").describe("Production branch name"), + /** + * Auto-deploy production branch + */ + autoDeployProduction: external_exports.boolean().optional().default(true).describe("Auto-deploy production branch"), + /** + * Auto-deploy preview branches + */ + autoDeployPreview: external_exports.boolean().optional().default(true).describe("Auto-deploy preview branches") +}); +var BuildConfigSchema = external_exports.object({ + /** + * Build command + */ + buildCommand: external_exports.string().optional().describe("Build command (e.g., npm run build)"), + /** + * Output directory + */ + outputDirectory: external_exports.string().optional().describe("Output directory (e.g., .next, dist)"), + /** + * Install command + */ + installCommand: external_exports.string().optional().describe("Install command (e.g., npm install, pnpm install)"), + /** + * Development command + */ + devCommand: external_exports.string().optional().describe("Development command (e.g., npm run dev)"), + /** + * Node.js version + */ + nodeVersion: external_exports.string().optional().describe("Node.js version (e.g., 18.x, 20.x)"), + /** + * Environment variables + */ + env: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Build environment variables") +}); +var DeploymentConfigSchema = external_exports.object({ + /** + * Enable automatic deployments + */ + autoDeployment: external_exports.boolean().optional().default(true).describe("Enable automatic deployments"), + /** + * Deployment regions + */ + regions: external_exports.array(external_exports.enum([ + "iad1", + // US East (Washington, D.C.) + "sfo1", + // US West (San Francisco) + "gru1", + // South America (São Paulo) + "lhr1", + // Europe West (London) + "fra1", + // Europe Central (Frankfurt) + "sin1", + // Asia (Singapore) + "syd1", + // Australia (Sydney) + "hnd1", + // Asia (Tokyo) + "icn1" + // Asia (Seoul) + ])).optional().describe("Deployment regions"), + /** + * Enable preview deployments + */ + enablePreview: external_exports.boolean().optional().default(true).describe("Enable preview deployments"), + /** + * Preview deployment comments on PRs + */ + previewComments: external_exports.boolean().optional().default(true).describe("Post preview URLs in PR comments"), + /** + * Production deployment protection + */ + productionProtection: external_exports.boolean().optional().default(true).describe("Require approval for production deployments"), + /** + * Deploy hooks + */ + deployHooks: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Hook name"), + url: external_exports.string().url().describe("Deploy hook URL"), + branch: external_exports.string().optional().describe("Target branch") + })).optional().describe("Deploy hooks") +}); +var DomainConfigSchema = external_exports.object({ + /** + * Domain name + */ + domain: external_exports.string().describe("Domain name (e.g., app.example.com)"), + /** + * Enable HTTPS redirect + */ + httpsRedirect: external_exports.boolean().optional().default(true).describe("Redirect HTTP to HTTPS"), + /** + * Custom SSL certificate + */ + customCertificate: external_exports.object({ + cert: external_exports.string().describe("SSL certificate"), + key: external_exports.string().describe("Private key"), + ca: external_exports.string().optional().describe("Certificate authority") + }).optional().describe("Custom SSL certificate"), + /** + * Git branch for this domain + */ + gitBranch: external_exports.string().optional().describe("Git branch to deploy to this domain") +}); +var EnvironmentVariablesSchema = external_exports.object({ + /** + * Variable name + */ + key: external_exports.string().describe("Environment variable name"), + /** + * Variable value + */ + value: external_exports.string().describe("Environment variable value"), + /** + * Target environments + */ + target: external_exports.array(external_exports.enum(["production", "preview", "development"])).describe("Target environments"), + /** + * Is secret (encrypted) + */ + isSecret: external_exports.boolean().optional().default(false).describe("Encrypt this variable"), + /** + * Git branch (for preview/development) + */ + gitBranch: external_exports.string().optional().describe("Specific git branch") +}); +var EdgeFunctionConfigSchema = external_exports.object({ + /** + * Function name + */ + name: external_exports.string().describe("Edge function name"), + /** + * Function path + */ + path: external_exports.string().describe("Function path (e.g., /api/*)"), + /** + * Regions to deploy + */ + regions: external_exports.array(external_exports.string()).optional().describe("Specific regions for this function"), + /** + * Memory limit (MB) + */ + memoryLimit: external_exports.number().int().min(128).max(3008).optional().default(1024).describe("Memory limit in MB"), + /** + * Timeout (seconds) + */ + timeout: external_exports.number().int().min(1).max(300).optional().default(10).describe("Timeout in seconds") +}); +var VercelProjectSchema = external_exports.object({ + /** + * Project name + */ + name: external_exports.string().describe("Vercel project name"), + /** + * Framework + */ + framework: VercelFrameworkSchema.optional().describe("Frontend framework"), + /** + * Git repository + */ + gitRepository: GitRepositoryConfigSchema.optional().describe("Git repository configuration"), + /** + * Build configuration + */ + buildConfig: BuildConfigSchema.optional().describe("Build configuration"), + /** + * Deployment configuration + */ + deploymentConfig: DeploymentConfigSchema.optional().describe("Deployment configuration"), + /** + * Custom domains + */ + domains: external_exports.array(DomainConfigSchema).optional().describe("Custom domains"), + /** + * Environment variables + */ + environmentVariables: external_exports.array(EnvironmentVariablesSchema).optional().describe("Environment variables"), + /** + * Edge functions + */ + edgeFunctions: external_exports.array(EdgeFunctionConfigSchema).optional().describe("Edge functions"), + /** + * Root directory + */ + rootDirectory: external_exports.string().optional().describe("Root directory (for monorepos)") +}); +var VercelMonitoringSchema = external_exports.object({ + /** + * Enable Web Analytics + */ + enableWebAnalytics: external_exports.boolean().optional().default(false).describe("Enable Vercel Web Analytics"), + /** + * Enable Speed Insights + */ + enableSpeedInsights: external_exports.boolean().optional().default(false).describe("Enable Vercel Speed Insights"), + /** + * Enable Log Drains + */ + logDrains: external_exports.array(external_exports.object({ + name: external_exports.string().describe("Log drain name"), + url: external_exports.string().url().describe("Log drain URL"), + headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers"), + sources: external_exports.array(external_exports.enum(["static", "lambda", "edge"])).optional().describe("Log sources") + })).optional().describe("Log drains configuration") +}); +var VercelTeamSchema = external_exports.object({ + /** + * Team ID or slug + */ + teamId: external_exports.string().optional().describe("Team ID or slug"), + /** + * Team name + */ + teamName: external_exports.string().optional().describe("Team name") +}); +var VercelConnectorSchema = ConnectorSchema2.extend({ + type: external_exports.literal("saas"), + /** + * Vercel provider + */ + provider: VercelProviderSchema.describe("Vercel provider"), + /** + * Vercel API base URL + */ + baseUrl: external_exports.string().url().optional().default("https://api.vercel.com").describe("Vercel API base URL"), + /** + * Team configuration + */ + team: VercelTeamSchema.optional().describe("Vercel team configuration"), + /** + * Projects to manage + */ + projects: external_exports.array(VercelProjectSchema).describe("Vercel projects"), + /** + * Monitoring configuration + */ + monitoring: VercelMonitoringSchema.optional().describe("Monitoring configuration"), + /** + * Enable webhooks + */ + enableWebhooks: external_exports.boolean().optional().default(true).describe("Enable Vercel webhooks"), + /** + * Webhook events to subscribe + */ + webhookEvents: external_exports.array(external_exports.enum([ + "deployment.created", + "deployment.succeeded", + "deployment.failed", + "deployment.ready", + "deployment.error", + "deployment.canceled", + "deployment-checks-completed", + "deployment-prepared", + "project.created", + "project.removed" + ])).optional().describe("Webhook events to subscribe to") +}); +var vercelNextJsConnectorExample = { + name: "vercel_production", + label: "Vercel Production", + type: "saas", + provider: "vercel", + baseUrl: "https://api.vercel.com", + authentication: { + type: "bearer", + token: "${VERCEL_TOKEN}" + }, + projects: [ + { + name: "objectstack-app", + framework: "nextjs", + gitRepository: { + type: "github", + repo: "objectstack-ai/app", + productionBranch: "main", + autoDeployProduction: true, + autoDeployPreview: true + }, + buildConfig: { + buildCommand: "npm run build", + outputDirectory: ".next", + installCommand: "npm ci", + devCommand: "npm run dev", + nodeVersion: "20.x", + env: { + NEXT_PUBLIC_API_URL: "https://api.objectstack.ai" + } + }, + deploymentConfig: { + autoDeployment: true, + regions: ["iad1", "sfo1", "fra1"], + enablePreview: true, + previewComments: true, + productionProtection: true + }, + domains: [ + { + domain: "app.objectstack.ai", + httpsRedirect: true, + gitBranch: "main" + }, + { + domain: "staging.objectstack.ai", + httpsRedirect: true, + gitBranch: "develop" + } + ], + environmentVariables: [ + { + key: "DATABASE_URL", + value: "${DATABASE_URL}", + target: ["production", "preview"], + isSecret: true + }, + { + key: "NEXT_PUBLIC_ANALYTICS_ID", + value: "UA-XXXXXXXX-X", + target: ["production"], + isSecret: false + } + ], + edgeFunctions: [ + { + name: "api-middleware", + path: "/api/*", + regions: ["iad1", "sfo1"], + memoryLimit: 1024, + timeout: 10 + } + ] + } + ], + monitoring: { + enableWebAnalytics: true, + enableSpeedInsights: true, + logDrains: [ + { + name: "datadog-logs", + url: "https://http-intake.logs.datadoghq.com/api/v2/logs", + headers: { + "DD-API-KEY": "${DATADOG_API_KEY}" + }, + sources: ["lambda", "edge"] + } + ] + }, + enableWebhooks: true, + webhookEvents: [ + "deployment.succeeded", + "deployment.failed", + "deployment.ready" + ], + status: "active", + enabled: true +}; +var vercelStaticSiteConnectorExample = { + name: "vercel_docs", + label: "Vercel Documentation", + type: "saas", + provider: "vercel", + baseUrl: "https://api.vercel.com", + authentication: { + type: "bearer", + token: "${VERCEL_TOKEN}" + }, + team: { + teamId: "team_xxxxxx", + teamName: "ObjectStack" + }, + projects: [ + { + name: "objectstack-docs", + framework: "static", + gitRepository: { + type: "github", + repo: "objectstack-ai/docs", + productionBranch: "main", + autoDeployProduction: true, + autoDeployPreview: true + }, + buildConfig: { + buildCommand: "npm run build", + outputDirectory: "dist", + installCommand: "npm ci", + nodeVersion: "18.x" + }, + deploymentConfig: { + autoDeployment: true, + regions: ["iad1", "lhr1", "sin1"], + enablePreview: true, + previewComments: true, + productionProtection: false + }, + domains: [ + { + domain: "docs.objectstack.ai", + httpsRedirect: true + } + ], + environmentVariables: [ + { + key: "ALGOLIA_APP_ID", + value: "${ALGOLIA_APP_ID}", + target: ["production", "preview"], + isSecret: false + }, + { + key: "ALGOLIA_API_KEY", + value: "${ALGOLIA_API_KEY}", + target: ["production", "preview"], + isSecret: true + } + ] + } + ], + monitoring: { + enableWebAnalytics: true, + enableSpeedInsights: false + }, + enableWebhooks: false, + status: "active", + enabled: true +}; +var studio_exports = {}; +__export4(studio_exports, { + ActionContributionSchema: () => ActionContributionSchema, + ActionLocationSchema: () => ActionLocationSchema, + ActivationEventSchema: () => ActivationEventSchema22, + BUILT_IN_NODE_DESCRIPTORS: () => BUILT_IN_NODE_DESCRIPTORS, + CanvasSnapSettingsSchema: () => CanvasSnapSettingsSchema, + CanvasZoomSettingsSchema: () => CanvasZoomSettingsSchema, + CommandContributionSchema: () => CommandContributionSchema, + ERDiagramConfigSchema: () => ERDiagramConfigSchema, + ERLayoutAlgorithmSchema: () => ERLayoutAlgorithmSchema, + ERNodeDisplaySchema: () => ERNodeDisplaySchema, + ElementPaletteItemSchema: () => ElementPaletteItemSchema, + FieldEditorConfigSchema: () => FieldEditorConfigSchema, + FieldGroupSchema: () => FieldGroupSchema, + FieldPropertySectionSchema: () => FieldPropertySectionSchema, + FlowBuilderConfigSchema: () => FlowBuilderConfigSchema, + FlowCanvasEdgeSchema: () => FlowCanvasEdgeSchema, + FlowCanvasEdgeStyleSchema: () => FlowCanvasEdgeStyleSchema, + FlowCanvasNodeSchema: () => FlowCanvasNodeSchema, + FlowLayoutAlgorithmSchema: () => FlowLayoutAlgorithmSchema, + FlowLayoutDirectionSchema: () => FlowLayoutDirectionSchema, + FlowNodeRenderDescriptorSchema: () => FlowNodeRenderDescriptorSchema, + FlowNodeShapeSchema: () => FlowNodeShapeSchema, + InterfaceBuilderConfigSchema: () => InterfaceBuilderConfigSchema, + MetadataIconContributionSchema: () => MetadataIconContributionSchema, + MetadataViewerContributionSchema: () => MetadataViewerContributionSchema, + ObjectDesignerConfigSchema: () => ObjectDesignerConfigSchema, + ObjectDesignerDefaultViewSchema: () => ObjectDesignerDefaultViewSchema, + ObjectFilterSchema: () => ObjectFilterSchema, + ObjectListDisplayModeSchema: () => ObjectListDisplayModeSchema, + ObjectManagerConfigSchema: () => ObjectManagerConfigSchema, + ObjectPreviewConfigSchema: () => ObjectPreviewConfigSchema, + ObjectPreviewTabSchema: () => ObjectPreviewTabSchema, + ObjectSortFieldSchema: () => ObjectSortFieldSchema, + PageBuilderConfigSchema: () => PageBuilderConfigSchema, + PanelContributionSchema: () => PanelContributionSchema, + PanelLocationSchema: () => PanelLocationSchema, + RelationshipDisplaySchema: () => RelationshipDisplaySchema, + RelationshipMapperConfigSchema: () => RelationshipMapperConfigSchema, + SidebarGroupContributionSchema: () => SidebarGroupContributionSchema, + StudioPluginContributionsSchema: () => StudioPluginContributionsSchema, + StudioPluginManifestSchema: () => StudioPluginManifestSchema, + ViewModeSchema: () => ViewModeSchema, + defineFlowBuilderConfig: () => defineFlowBuilderConfig, + defineObjectDesignerConfig: () => defineObjectDesignerConfig, + defineStudioPlugin: () => defineStudioPlugin +}); +var ViewModeSchema = external_exports.enum(["preview", "design", "code", "data"]); +var MetadataViewerContributionSchema = external_exports.object({ + /** Unique viewer ID (namespaced: `pluginId.viewerId`) */ + id: external_exports.string().describe("Unique viewer identifier"), + /** Metadata type(s) this viewer handles (e.g., "object", "flow", "agent") */ + metadataTypes: external_exports.array(external_exports.string()).min(1).describe("Metadata types this viewer can handle"), + /** Human-readable label shown in the view switcher */ + label: external_exports.string().describe("Viewer display label"), + /** Priority — highest-priority viewer becomes default. Built-in default = 0 */ + priority: external_exports.number().default(0).describe("Viewer priority (higher wins)"), + /** View modes this viewer supports */ + modes: external_exports.array(ViewModeSchema).default(["preview"]).describe("Supported view modes") +}); +var SidebarGroupContributionSchema = external_exports.object({ + /** Unique group key */ + key: external_exports.string().describe("Unique group key"), + /** Display label */ + label: external_exports.string().describe("Group display label"), + /** Lucide icon name (e.g., "database", "workflow") */ + icon: external_exports.string().optional().describe("Lucide icon name"), + /** Metadata types belonging to this group */ + metadataTypes: external_exports.array(external_exports.string()).describe("Metadata types in this group"), + /** Sort order — lower values appear first */ + order: external_exports.number().default(100).describe("Sort order (lower = higher)") +}); +var ActionLocationSchema = external_exports.enum(["toolbar", "contextMenu", "commandPalette"]); +var ActionContributionSchema = external_exports.object({ + /** Unique action ID */ + id: external_exports.string().describe("Unique action identifier"), + /** Display label */ + label: external_exports.string().describe("Action display label"), + /** Lucide icon name */ + icon: external_exports.string().optional().describe("Lucide icon name"), + /** Where this action appears */ + location: ActionLocationSchema.describe("UI location"), + /** Metadata types this action applies to (empty = all types) */ + metadataTypes: external_exports.array(external_exports.string()).default([]).describe("Applicable metadata types") +}); +var MetadataIconContributionSchema = external_exports.object({ + /** Metadata type this icon represents */ + metadataType: external_exports.string().describe("Metadata type"), + /** Human-readable label */ + label: external_exports.string().describe("Display label"), + /** Lucide icon name */ + icon: external_exports.string().describe("Lucide icon name") +}); +var PanelLocationSchema = external_exports.enum(["bottom", "right", "modal"]); +var PanelContributionSchema = external_exports.object({ + /** Unique panel ID */ + id: external_exports.string().describe("Unique panel identifier"), + /** Display label */ + label: external_exports.string().describe("Panel display label"), + /** Lucide icon name */ + icon: external_exports.string().optional().describe("Lucide icon name"), + /** Panel placement */ + location: PanelLocationSchema.default("bottom").describe("Panel location") +}); +var CommandContributionSchema = external_exports.object({ + /** Unique command ID (namespaced: `pluginId.commandName`) */ + id: external_exports.string().describe("Unique command identifier"), + /** Display label */ + label: external_exports.string().describe("Command display label"), + /** Keyboard shortcut (e.g., "Ctrl+Shift+P") */ + shortcut: external_exports.string().optional().describe("Keyboard shortcut"), + /** Lucide icon name */ + icon: external_exports.string().optional().describe("Lucide icon name") +}); +var StudioPluginContributionsSchema = external_exports.object({ + /** Metadata viewer/designer components */ + metadataViewers: external_exports.array(MetadataViewerContributionSchema).default([]), + /** Sidebar navigation groups */ + sidebarGroups: external_exports.array(SidebarGroupContributionSchema).default([]), + /** Toolbar / context menu / command palette actions */ + actions: external_exports.array(ActionContributionSchema).default([]), + /** Metadata type icons & labels */ + metadataIcons: external_exports.array(MetadataIconContributionSchema).default([]), + /** Auxiliary panels */ + panels: external_exports.array(PanelContributionSchema).default([]), + /** Command palette entries */ + commands: external_exports.array(CommandContributionSchema).default([]) +}); +var ActivationEventSchema22 = external_exports.string().describe("Activation event pattern"); +var StudioPluginManifestSchema = external_exports.object({ + /** + * Unique plugin ID using reverse-domain notation. + * @example "objectstack.object-designer" + */ + id: external_exports.string().regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)*$/).describe("Plugin ID (dot-separated lowercase)"), + /** Human-readable plugin name */ + name: external_exports.string().describe("Plugin display name"), + /** Semantic version */ + version: external_exports.string().default("0.0.1").describe("Plugin version"), + /** Plugin description */ + description: external_exports.string().optional().describe("Plugin description"), + /** Author name */ + author: external_exports.string().optional().describe("Author"), + /** Declarative contribution points */ + contributes: StudioPluginContributionsSchema.default({ + metadataViewers: [], + sidebarGroups: [], + actions: [], + metadataIcons: [], + panels: [], + commands: [] + }), + /** + * Activation events — when to load this plugin. + * Default `['*']` means eager activation. + */ + activationEvents: external_exports.array(ActivationEventSchema22).default(["*"]) +}); +function defineStudioPlugin(input) { + return StudioPluginManifestSchema.parse(input); +} +var FieldPropertySectionSchema = external_exports.object({ + /** Unique section key */ + key: external_exports.string().describe('Section key (e.g., "basics", "constraints", "security")'), + /** Display label */ + label: external_exports.string().describe("Section display label"), + /** Lucide icon name */ + icon: external_exports.string().optional().describe("Lucide icon name"), + /** Whether section is expanded by default */ + defaultExpanded: external_exports.boolean().default(true).describe("Whether section is expanded by default"), + /** Sort order — lower values appear first */ + order: external_exports.number().default(0).describe("Sort order (lower = higher)") +}); +var FieldGroupSchema = external_exports.object({ + /** Group key (matches field.group value) */ + key: external_exports.string().describe("Group key matching field.group values"), + /** Display label */ + label: external_exports.string().describe("Group display label"), + /** Lucide icon name */ + icon: external_exports.string().optional().describe("Lucide icon name"), + /** Whether group is expanded by default */ + defaultExpanded: external_exports.boolean().default(true).describe("Whether group is expanded by default"), + /** Sort order — lower values appear first */ + order: external_exports.number().default(0).describe("Sort order (lower = higher)") +}); +var FieldEditorConfigSchema = external_exports.object({ + /** Enable inline editing of field properties in the table */ + inlineEditing: external_exports.boolean().default(true).describe("Enable inline editing of field properties"), + /** Enable drag-and-drop field reordering */ + dragReorder: external_exports.boolean().default(true).describe("Enable drag-and-drop field reordering"), + /** Show field group headers for organizing fields */ + showFieldGroups: external_exports.boolean().default(true).describe("Show field group headers"), + /** Show the type-specific property panel on the right */ + showPropertyPanel: external_exports.boolean().default(true).describe("Show the right-side property panel"), + /** Default property panel sections to display */ + propertySections: external_exports.array(FieldPropertySectionSchema).default([ + { key: "basics", label: "Basic Properties", defaultExpanded: true, order: 0 }, + { key: "constraints", label: "Constraints & Validation", defaultExpanded: true, order: 10 }, + { key: "relationship", label: "Relationship Config", defaultExpanded: true, order: 20 }, + { key: "display", label: "Display & UI", defaultExpanded: false, order: 30 }, + { key: "security", label: "Security & Compliance", defaultExpanded: false, order: 40 }, + { key: "advanced", label: "Advanced", defaultExpanded: false, order: 50 } + ]).describe("Property panel section definitions"), + /** Field groups for organizing fields in the editor */ + fieldGroups: external_exports.array(FieldGroupSchema).default([]).describe("Field group definitions"), + /** Maximum fields before pagination kicks in */ + paginationThreshold: external_exports.number().default(50).describe("Number of fields before pagination is enabled"), + /** Enable batch field operations (add multiple fields at once) */ + batchOperations: external_exports.boolean().default(true).describe("Enable batch add/remove field operations"), + /** Show field usage statistics (views, formulas, relationships referencing this field) */ + showUsageStats: external_exports.boolean().default(false).describe("Show field usage statistics") +}); +var RelationshipDisplaySchema = external_exports.object({ + /** Relationship type to configure */ + type: external_exports.enum(["lookup", "master_detail", "tree"]).describe("Relationship type"), + /** Line style for this relationship type */ + lineStyle: external_exports.enum(["solid", "dashed", "dotted"]).default("solid").describe("Line style in diagrams"), + /** Line color (CSS color value) */ + color: external_exports.string().default("#94a3b8").describe("Line color (CSS value)"), + /** Highlighted color on hover/select */ + highlightColor: external_exports.string().default("#0891b2").describe("Highlighted color on hover/select"), + /** Cardinality label to display */ + cardinalityLabel: external_exports.string().default("1:N").describe('Cardinality label (e.g., "1:N", "1:1", "N:M")') +}); +var RelationshipMapperConfigSchema = external_exports.object({ + /** Enable visual relationship creation (drag from source to target) */ + visualCreation: external_exports.boolean().default(true).describe("Enable drag-to-create relationships"), + /** Show reverse relationships (child → parent) */ + showReverseRelationships: external_exports.boolean().default(true).describe("Show reverse/child-to-parent relationships"), + /** Show cascade delete warnings */ + showCascadeWarnings: external_exports.boolean().default(true).describe("Show cascade delete behavior warnings"), + /** Relationship display configuration by type */ + displayConfig: external_exports.array(RelationshipDisplaySchema).default([ + { type: "lookup", lineStyle: "dashed", color: "#0891b2", highlightColor: "#06b6d4", cardinalityLabel: "1:N" }, + { type: "master_detail", lineStyle: "solid", color: "#ea580c", highlightColor: "#f97316", cardinalityLabel: "1:N" }, + { type: "tree", lineStyle: "dotted", color: "#8b5cf6", highlightColor: "#a78bfa", cardinalityLabel: "1:N" } + ]).describe("Visual config per relationship type") +}); +var ERLayoutAlgorithmSchema = external_exports.enum([ + "force", + // Force-directed graph (natural clustering) + "hierarchy", + // Top-down hierarchy (master → detail) + "grid", + // Uniform grid layout + "circular" + // Circular arrangement +]).describe("ER diagram layout algorithm"); +var ERNodeDisplaySchema = external_exports.object({ + /** Show field list within the node */ + showFields: external_exports.boolean().default(true).describe("Show field list inside entity nodes"), + /** Maximum fields to show before collapsing (0 = no limit) */ + maxFieldsVisible: external_exports.number().default(8).describe('Max fields visible before "N more..." collapse'), + /** Show field types alongside field names */ + showFieldTypes: external_exports.boolean().default(true).describe("Show field type badges"), + /** Show required field indicators */ + showRequiredIndicator: external_exports.boolean().default(true).describe("Show required field indicators"), + /** Show record count on each node (requires data access) */ + showRecordCount: external_exports.boolean().default(false).describe("Show live record count on nodes"), + /** Show object icon */ + showIcon: external_exports.boolean().default(true).describe("Show object icon on node header"), + /** Show object description on hover tooltip */ + showDescription: external_exports.boolean().default(true).describe("Show description tooltip on hover") +}); +var ERDiagramConfigSchema = external_exports.object({ + /** Enable the ER diagram panel */ + enabled: external_exports.boolean().default(true).describe("Enable ER diagram panel"), + /** Default layout algorithm */ + layout: ERLayoutAlgorithmSchema.default("force").describe("Default layout algorithm"), + /** Node display options */ + nodeDisplay: ERNodeDisplaySchema.default({ + showFields: true, + maxFieldsVisible: 8, + showFieldTypes: true, + showRequiredIndicator: true, + showRecordCount: false, + showIcon: true, + showDescription: true + }).describe("Node display configuration"), + /** Show minimap for navigation */ + showMinimap: external_exports.boolean().default(true).describe("Show minimap for large diagrams"), + /** Enable zoom controls */ + zoomControls: external_exports.boolean().default(true).describe("Show zoom in/out/fit controls"), + /** Minimum zoom level */ + minZoom: external_exports.number().default(0.1).describe("Minimum zoom level"), + /** Maximum zoom level */ + maxZoom: external_exports.number().default(3).describe("Maximum zoom level"), + /** Show relationship labels (cardinality) on edges */ + showEdgeLabels: external_exports.boolean().default(true).describe("Show cardinality labels on relationship edges"), + /** Highlight connected entities on hover */ + highlightOnHover: external_exports.boolean().default(true).describe("Highlight connected entities on node hover"), + /** Click behavior: navigate to object designer */ + clickToNavigate: external_exports.boolean().default(true).describe("Click node to navigate to object detail"), + /** Enable drag-and-drop to create relationships */ + dragToConnect: external_exports.boolean().default(true).describe("Drag between nodes to create relationships"), + /** Filter to show only objects with relationships (hide orphans) */ + hideOrphans: external_exports.boolean().default(false).describe("Hide objects with no relationships"), + /** Auto-fit diagram to viewport on initial load */ + autoFit: external_exports.boolean().default(true).describe("Auto-fit diagram to viewport on load"), + /** Export diagram options */ + exportFormats: external_exports.array(external_exports.enum(["png", "svg", "json"])).default(["png", "svg"]).describe("Available export formats for diagram") +}); +var ObjectListDisplayModeSchema = external_exports.enum([ + "table", + // Traditional table with columns + "cards", + // Card grid (visual overview) + "tree" + // Hierarchical tree (grouped by package/namespace) +]).describe("Object list display mode"); +var ObjectSortFieldSchema = external_exports.enum([ + "name", + // Sort by API name + "label", + // Sort by display label + "fieldCount", + // Sort by number of fields + "updatedAt" + // Sort by last modified +]).describe("Object list sort field"); +var ObjectFilterSchema = external_exports.object({ + /** Filter by package/namespace */ + package: external_exports.string().optional().describe("Filter by owning package"), + /** Filter by tags */ + tags: external_exports.array(external_exports.string()).optional().describe("Filter by object tags"), + /** Show system objects */ + includeSystem: external_exports.boolean().default(true).describe("Include system-level objects"), + /** Show abstract objects */ + includeAbstract: external_exports.boolean().default(false).describe("Include abstract base objects"), + /** Show only objects with specific field types */ + hasFieldType: external_exports.string().optional().describe("Filter to objects containing a specific field type"), + /** Show only objects with relationships */ + hasRelationships: external_exports.boolean().optional().describe("Filter to objects with lookup/master_detail fields"), + /** Text search across name, label, description */ + searchQuery: external_exports.string().optional().describe("Free-text search across name, label, and description") +}); +var ObjectManagerConfigSchema = external_exports.object({ + /** Default display mode */ + defaultDisplayMode: ObjectListDisplayModeSchema.default("table").describe("Default list display mode"), + /** Default sort field */ + defaultSortField: ObjectSortFieldSchema.default("label").describe("Default sort field"), + /** Default sort direction */ + defaultSortDirection: external_exports.enum(["asc", "desc"]).default("asc").describe("Default sort direction"), + /** Default filters */ + defaultFilter: ObjectFilterSchema.default({ + includeSystem: true, + includeAbstract: false + }).describe("Default filter configuration"), + /** Show field count badge on each object row */ + showFieldCount: external_exports.boolean().default(true).describe("Show field count badge"), + /** Show relationship count badge */ + showRelationshipCount: external_exports.boolean().default(true).describe("Show relationship count badge"), + /** Show quick-preview tooltip with field list on hover */ + showQuickPreview: external_exports.boolean().default(true).describe("Show quick field preview tooltip on hover"), + /** Enable object comparison (diff two objects side-by-side) */ + enableComparison: external_exports.boolean().default(false).describe("Enable side-by-side object comparison"), + /** Show ER diagram toggle button in the toolbar */ + showERDiagramToggle: external_exports.boolean().default(true).describe("Show ER diagram toggle in toolbar"), + /** Show "Create Object" quick action */ + showCreateAction: external_exports.boolean().default(true).describe("Show create object action"), + /** Show object statistics summary bar (total objects, fields, relationships) */ + showStatsSummary: external_exports.boolean().default(true).describe("Show statistics summary bar") +}); +var ObjectPreviewTabSchema = external_exports.object({ + /** Tab key */ + key: external_exports.string().describe("Tab key"), + /** Tab display label */ + label: external_exports.string().describe("Tab display label"), + /** Lucide icon name */ + icon: external_exports.string().optional().describe("Lucide icon name"), + /** Whether this tab is enabled */ + enabled: external_exports.boolean().default(true).describe("Whether this tab is available"), + /** Sort order */ + order: external_exports.number().default(0).describe("Sort order (lower = higher)") +}); +var ObjectPreviewConfigSchema = external_exports.object({ + /** Tabs to show in the object detail view */ + tabs: external_exports.array(ObjectPreviewTabSchema).default([ + { key: "fields", label: "Fields", icon: "list", enabled: true, order: 0 }, + { key: "relationships", label: "Relationships", icon: "link", enabled: true, order: 10 }, + { key: "indexes", label: "Indexes", icon: "zap", enabled: true, order: 20 }, + { key: "validations", label: "Validations", icon: "shield-check", enabled: true, order: 30 }, + { key: "capabilities", label: "Capabilities", icon: "settings", enabled: true, order: 40 }, + { key: "data", label: "Data", icon: "table-2", enabled: true, order: 50 }, + { key: "api", label: "API", icon: "globe", enabled: true, order: 60 }, + { key: "code", label: "Code", icon: "code-2", enabled: true, order: 70 } + ]).describe("Object detail preview tabs"), + /** Default active tab */ + defaultTab: external_exports.string().default("fields").describe("Default active tab key"), + /** Show object header with summary info */ + showHeader: external_exports.boolean().default(true).describe("Show object summary header"), + /** Show breadcrumbs */ + showBreadcrumbs: external_exports.boolean().default(true).describe("Show navigation breadcrumbs") +}); +var ObjectDesignerDefaultViewSchema = external_exports.enum([ + "field-editor", + // Field table editor (default) + "relationship-mapper", + // Visual relationship view + "er-diagram", + // Full ER diagram + "object-manager" + // Object list/manager +]).describe("Default view when entering the Object Designer"); +var ObjectDesignerConfigSchema = external_exports.object({ + /** Default view when opening the designer */ + defaultView: ObjectDesignerDefaultViewSchema.default("field-editor").describe("Default view"), + /** Field editor configuration */ + fieldEditor: FieldEditorConfigSchema.default({ + inlineEditing: true, + dragReorder: true, + showFieldGroups: true, + showPropertyPanel: true, + propertySections: [ + { key: "basics", label: "Basic Properties", defaultExpanded: true, order: 0 }, + { key: "constraints", label: "Constraints & Validation", defaultExpanded: true, order: 10 }, + { key: "relationship", label: "Relationship Config", defaultExpanded: true, order: 20 }, + { key: "display", label: "Display & UI", defaultExpanded: false, order: 30 }, + { key: "security", label: "Security & Compliance", defaultExpanded: false, order: 40 }, + { key: "advanced", label: "Advanced", defaultExpanded: false, order: 50 } + ], + fieldGroups: [], + paginationThreshold: 50, + batchOperations: true, + showUsageStats: false + }).describe("Field editor configuration"), + /** Relationship mapper configuration */ + relationshipMapper: RelationshipMapperConfigSchema.default({ + visualCreation: true, + showReverseRelationships: true, + showCascadeWarnings: true, + displayConfig: [ + { type: "lookup", lineStyle: "dashed", color: "#0891b2", highlightColor: "#06b6d4", cardinalityLabel: "1:N" }, + { type: "master_detail", lineStyle: "solid", color: "#ea580c", highlightColor: "#f97316", cardinalityLabel: "1:N" }, + { type: "tree", lineStyle: "dotted", color: "#8b5cf6", highlightColor: "#a78bfa", cardinalityLabel: "1:N" } + ] + }).describe("Relationship mapper configuration"), + /** ER diagram configuration */ + erDiagram: ERDiagramConfigSchema.default({ + enabled: true, + layout: "force", + nodeDisplay: { + showFields: true, + maxFieldsVisible: 8, + showFieldTypes: true, + showRequiredIndicator: true, + showRecordCount: false, + showIcon: true, + showDescription: true + }, + showMinimap: true, + zoomControls: true, + minZoom: 0.1, + maxZoom: 3, + showEdgeLabels: true, + highlightOnHover: true, + clickToNavigate: true, + dragToConnect: true, + hideOrphans: false, + autoFit: true, + exportFormats: ["png", "svg"] + }).describe("ER diagram configuration"), + /** Object manager configuration */ + objectManager: ObjectManagerConfigSchema.default({ + defaultDisplayMode: "table", + defaultSortField: "label", + defaultSortDirection: "asc", + defaultFilter: { + includeSystem: true, + includeAbstract: false + }, + showFieldCount: true, + showRelationshipCount: true, + showQuickPreview: true, + enableComparison: false, + showERDiagramToggle: true, + showCreateAction: true, + showStatsSummary: true + }).describe("Object manager configuration"), + /** Object preview configuration */ + objectPreview: ObjectPreviewConfigSchema.default({ + tabs: [ + { key: "fields", label: "Fields", icon: "list", enabled: true, order: 0 }, + { key: "relationships", label: "Relationships", icon: "link", enabled: true, order: 10 }, + { key: "indexes", label: "Indexes", icon: "zap", enabled: true, order: 20 }, + { key: "validations", label: "Validations", icon: "shield-check", enabled: true, order: 30 }, + { key: "capabilities", label: "Capabilities", icon: "settings", enabled: true, order: 40 }, + { key: "data", label: "Data", icon: "table-2", enabled: true, order: 50 }, + { key: "api", label: "API", icon: "globe", enabled: true, order: 60 }, + { key: "code", label: "Code", icon: "code-2", enabled: true, order: 70 } + ], + defaultTab: "fields", + showHeader: true, + showBreadcrumbs: true + }).describe("Object preview configuration") +}); +function defineObjectDesignerConfig(input) { + return ObjectDesignerConfigSchema.parse(input); +} +var CanvasSnapSettingsSchema = external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable snap-to-grid"), + gridSize: external_exports.number().int().min(1).default(8).describe("Snap grid size in pixels"), + showGrid: external_exports.boolean().default(true).describe("Show grid overlay on canvas"), + showGuides: external_exports.boolean().default(true).describe("Show alignment guides when dragging") +}); +var CanvasZoomSettingsSchema = external_exports.object({ + min: external_exports.number().min(0.1).default(0.25).describe("Minimum zoom level"), + max: external_exports.number().max(10).default(3).describe("Maximum zoom level"), + default: external_exports.number().default(1).describe("Default zoom level"), + step: external_exports.number().default(0.1).describe("Zoom step increment") +}); +var ElementPaletteItemSchema = external_exports.object({ + type: external_exports.string().describe('Component type (e.g. "element:button", "element:text")'), + label: external_exports.string().describe("Display label in palette"), + icon: external_exports.string().optional().describe("Icon name for palette display"), + category: external_exports.enum(["content", "interactive", "data", "layout"]).describe("Palette category grouping"), + defaultWidth: external_exports.number().int().min(1).default(4).describe("Default width in grid columns"), + defaultHeight: external_exports.number().int().min(1).default(2).describe("Default height in grid rows") +}); +var PageBuilderConfigSchema = external_exports.object({ + snap: CanvasSnapSettingsSchema.optional().describe("Canvas snap settings"), + zoom: CanvasZoomSettingsSchema.optional().describe("Canvas zoom settings"), + palette: external_exports.array(ElementPaletteItemSchema).optional().describe("Custom element palette (defaults to all registered elements)"), + showLayerPanel: external_exports.boolean().default(true).describe("Show layer ordering panel"), + showPropertyPanel: external_exports.boolean().default(true).describe("Show property inspector panel"), + undoLimit: external_exports.number().int().min(1).default(50).describe("Maximum undo history steps") +}); +var InterfaceBuilderConfigSchema = PageBuilderConfigSchema; +var FlowNodeShapeSchema = external_exports.enum([ + "rounded_rect", + // Default activity shape (assignments, CRUD, HTTP, script, subflow) + "circle", + // Start / End events + "diamond", + // Decision (XOR gateway) + "parallelogram", + // Loop / iteration + "hexagon", + // Wait / timer event + "diamond_thick", + // Parallel gateway (AND-split) & Join gateway (AND-join) + "attached_circle", + // Boundary event (attached to host node) + "screen_rect" + // Screen / user-interaction node +]).describe("Visual shape for rendering a flow node on the canvas"); +var FlowNodeRenderDescriptorSchema = external_exports.object({ + /** The node action type this descriptor applies to */ + action: external_exports.string().describe('FlowNodeAction value (e.g., "parallel_gateway")'), + /** Visual shape on the canvas */ + shape: FlowNodeShapeSchema.describe("Shape to render"), + /** Lucide icon name displayed inside the node */ + icon: external_exports.string().describe("Lucide icon name"), + /** Default label shown on the node when no user label is set */ + defaultLabel: external_exports.string().describe("Default display label"), + /** Default width in canvas pixels */ + defaultWidth: external_exports.number().int().min(20).default(120).describe("Default width in pixels"), + /** Default height in canvas pixels */ + defaultHeight: external_exports.number().int().min(20).default(60).describe("Default height in pixels"), + /** CSS color for the node fill */ + fillColor: external_exports.string().default("#ffffff").describe("Node fill color (CSS value)"), + /** CSS color for the node border */ + borderColor: external_exports.string().default("#94a3b8").describe("Node border color (CSS value)"), + /** Whether this node type can have boundary events attached */ + allowBoundaryEvents: external_exports.boolean().default(false).describe("Whether boundary events can be attached to this node type"), + /** Category for palette grouping */ + paletteCategory: external_exports.enum(["event", "gateway", "activity", "data", "subflow"]).describe("Palette category for grouping") +}).describe("Visual render descriptor for a flow node type"); +var FlowCanvasNodeSchema = external_exports.object({ + /** Reference to the flow node id */ + nodeId: external_exports.string().describe("Corresponding FlowNode.id"), + /** X position on the canvas (pixels) */ + x: external_exports.number().describe("X position on canvas"), + /** Y position on the canvas (pixels) */ + y: external_exports.number().describe("Y position on canvas"), + /** Width override (pixels, optional — uses descriptor default) */ + width: external_exports.number().int().min(20).optional().describe("Width override in pixels"), + /** Height override (pixels, optional — uses descriptor default) */ + height: external_exports.number().int().min(20).optional().describe("Height override in pixels"), + /** Whether the node is collapsed (hides internal details) */ + collapsed: external_exports.boolean().default(false).describe("Whether the node is collapsed"), + /** Custom fill color override */ + fillColor: external_exports.string().optional().describe("Fill color override"), + /** Custom border color override */ + borderColor: external_exports.string().optional().describe("Border color override"), + /** User-defined comment/annotation visible on canvas */ + annotation: external_exports.string().optional().describe("User annotation displayed near the node") +}).describe("Canvas layout data for a flow node"); +var FlowCanvasEdgeStyleSchema = external_exports.enum([ + "solid", + // Normal sequence flow + "dashed", + // Default sequence flow (isDefault: true) + "dotted", + // Conditional edge + "bold" + // Fault / error edge +]).describe("Edge line style"); +var FlowCanvasEdgeSchema = external_exports.object({ + /** Reference to the flow edge id */ + edgeId: external_exports.string().describe("Corresponding FlowEdge.id"), + /** Line style */ + style: FlowCanvasEdgeStyleSchema.default("solid").describe("Line style"), + /** Line color (CSS value) */ + color: external_exports.string().default("#94a3b8").describe("Edge line color"), + /** Label position along the edge (0–1, 0.5 = midpoint) */ + labelPosition: external_exports.number().min(0).max(1).default(0.5).describe("Position of the condition label along the edge"), + /** Optional waypoints for routing the edge around nodes */ + waypoints: external_exports.array(external_exports.object({ + x: external_exports.number().describe("Waypoint X"), + y: external_exports.number().describe("Waypoint Y") + })).optional().describe("Manual waypoints for edge routing"), + /** Whether to show an animated flow indicator */ + animated: external_exports.boolean().default(false).describe("Show animated flow indicator") +}).describe("Canvas layout and visual data for a flow edge"); +var FlowLayoutAlgorithmSchema = external_exports.enum([ + "dagre", + // Directed acyclic graph layout (top-down or left-right) + "elk", + // Eclipse Layout Kernel (advanced hierarchical) + "force", + // Force-directed graph + "manual" + // User-positioned (no auto-layout) +]).describe("Auto-layout algorithm for the flow canvas"); +var FlowLayoutDirectionSchema = external_exports.enum([ + "TB", + // Top to bottom + "BT", + // Bottom to top + "LR", + // Left to right + "RL" + // Right to left +]).describe("Auto-layout direction"); +var FlowBuilderConfigSchema = external_exports.object({ + /** Canvas snap settings */ + snap: external_exports.object({ + enabled: external_exports.boolean().default(true).describe("Enable snap-to-grid"), + gridSize: external_exports.number().int().min(1).default(16).describe("Snap grid size in pixels"), + showGrid: external_exports.boolean().default(true).describe("Show grid overlay") + }).default({ enabled: true, gridSize: 16, showGrid: true }).describe("Canvas snap-to-grid settings"), + /** Canvas zoom settings */ + zoom: external_exports.object({ + min: external_exports.number().min(0.1).default(0.25).describe("Minimum zoom level"), + max: external_exports.number().max(10).default(3).describe("Maximum zoom level"), + default: external_exports.number().default(1).describe("Default zoom level"), + step: external_exports.number().default(0.1).describe("Zoom step") + }).default({ min: 0.25, max: 3, default: 1, step: 0.1 }).describe("Canvas zoom settings"), + /** Auto-layout algorithm */ + layoutAlgorithm: FlowLayoutAlgorithmSchema.default("dagre").describe("Default auto-layout algorithm"), + /** Auto-layout direction */ + layoutDirection: FlowLayoutDirectionSchema.default("TB").describe("Default auto-layout direction"), + /** Node render descriptors (override defaults per node type) */ + nodeDescriptors: external_exports.array(FlowNodeRenderDescriptorSchema).optional().describe("Custom node render descriptors (merged with built-in defaults)"), + /** Show minimap for navigation */ + showMinimap: external_exports.boolean().default(true).describe("Show minimap panel"), + /** Show the node property panel */ + showPropertyPanel: external_exports.boolean().default(true).describe("Show property panel"), + /** Show the node palette sidebar */ + showPalette: external_exports.boolean().default(true).describe("Show node palette sidebar"), + /** Maximum undo history steps */ + undoLimit: external_exports.number().int().min(1).default(50).describe("Maximum undo history steps"), + /** Enable edge animation during execution preview */ + animateExecution: external_exports.boolean().default(true).describe("Animate edges during execution preview"), + /** Connection validation — prevent invalid edges (e.g., duplicate, self-loop) */ + connectionValidation: external_exports.boolean().default(true).describe("Validate connections before creating edges") +}).describe("Studio Flow Builder configuration"); +var BUILT_IN_NODE_DESCRIPTORS = [ + { action: "start", shape: "circle", icon: "play", defaultLabel: "Start", defaultWidth: 60, defaultHeight: 60, fillColor: "#dcfce7", borderColor: "#16a34a", allowBoundaryEvents: false, paletteCategory: "event" }, + { action: "end", shape: "circle", icon: "square", defaultLabel: "End", defaultWidth: 60, defaultHeight: 60, fillColor: "#fee2e2", borderColor: "#dc2626", allowBoundaryEvents: false, paletteCategory: "event" }, + { action: "decision", shape: "diamond", icon: "git-branch", defaultLabel: "Decision", defaultWidth: 80, defaultHeight: 80, fillColor: "#fef9c3", borderColor: "#ca8a04", allowBoundaryEvents: false, paletteCategory: "gateway" }, + { action: "parallel_gateway", shape: "diamond_thick", icon: "git-fork", defaultLabel: "Parallel Gateway", defaultWidth: 80, defaultHeight: 80, fillColor: "#dbeafe", borderColor: "#2563eb", allowBoundaryEvents: false, paletteCategory: "gateway" }, + { action: "join_gateway", shape: "diamond_thick", icon: "git-merge", defaultLabel: "Join Gateway", defaultWidth: 80, defaultHeight: 80, fillColor: "#dbeafe", borderColor: "#2563eb", allowBoundaryEvents: false, paletteCategory: "gateway" }, + { action: "wait", shape: "hexagon", icon: "clock", defaultLabel: "Wait", defaultWidth: 100, defaultHeight: 60, fillColor: "#f3e8ff", borderColor: "#7c3aed", allowBoundaryEvents: true, paletteCategory: "event" }, + { action: "boundary_event", shape: "attached_circle", icon: "alert-circle", defaultLabel: "Boundary Event", defaultWidth: 40, defaultHeight: 40, fillColor: "#fff7ed", borderColor: "#ea580c", allowBoundaryEvents: false, paletteCategory: "event" }, + { action: "assignment", shape: "rounded_rect", icon: "pen-line", defaultLabel: "Assignment", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "activity" }, + { action: "create_record", shape: "rounded_rect", icon: "plus-circle", defaultLabel: "Create Record", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "data" }, + { action: "update_record", shape: "rounded_rect", icon: "edit", defaultLabel: "Update Record", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "data" }, + { action: "delete_record", shape: "rounded_rect", icon: "trash-2", defaultLabel: "Delete Record", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "data" }, + { action: "get_record", shape: "rounded_rect", icon: "search", defaultLabel: "Get Record", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "data" }, + { action: "http_request", shape: "rounded_rect", icon: "globe", defaultLabel: "HTTP Request", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "activity" }, + { action: "script", shape: "rounded_rect", icon: "code", defaultLabel: "Script", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "activity" }, + { action: "screen", shape: "screen_rect", icon: "monitor", defaultLabel: "Screen", defaultWidth: 140, defaultHeight: 80, fillColor: "#f0f9ff", borderColor: "#0284c7", allowBoundaryEvents: false, paletteCategory: "activity" }, + { action: "loop", shape: "parallelogram", icon: "repeat", defaultLabel: "Loop", defaultWidth: 120, defaultHeight: 60, fillColor: "#fef3c7", borderColor: "#d97706", allowBoundaryEvents: true, paletteCategory: "activity" }, + { action: "subflow", shape: "rounded_rect", icon: "layers", defaultLabel: "Subflow", defaultWidth: 140, defaultHeight: 70, fillColor: "#ede9fe", borderColor: "#7c3aed", allowBoundaryEvents: true, paletteCategory: "subflow" }, + { action: "connector_action", shape: "rounded_rect", icon: "plug", defaultLabel: "Connector", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "activity" } +]; +function defineFlowBuilderConfig(input) { + return FlowBuilderConfigSchema.parse(input); +} +var ObjectStackDefinitionSchema = external_exports.object({ + /** System Configuration */ + manifest: ManifestSchema3.optional().describe("Project Package Configuration"), + datasources: external_exports.array(DatasourceSchema2).optional().describe("External Data Connections"), + translations: external_exports.array(TranslationBundleSchema2).optional().describe("I18n Translation Bundles"), + i18n: TranslationConfigSchema2.optional().describe("Internationalization configuration"), + /** + * ObjectQL: Data Layer + * All business objects and entities. + */ + objects: external_exports.array(ObjectSchema4).optional().describe("Business Objects definition (owned by this package)"), + /** + * Object Extensions: fields/config to merge into objects owned by other packages. + * Use this instead of redefining an object when you want to add fields to + * an existing object from another package. + * + * @example + * ```ts + * objectExtensions: [{ + * extend: 'contact', + * fields: { sales_stage: Field.select([...]) }, + * }] + * ``` + */ + objectExtensions: external_exports.array(ObjectExtensionSchema2).optional().describe("Extensions to objects owned by other packages"), + /** + * ObjectUI: User Interface Layer + * Apps, Menus, Pages, and Visualizations. + */ + apps: external_exports.array(AppSchema3).optional().describe("Applications"), + views: external_exports.array(ViewSchema3).optional().describe("List Views"), + pages: external_exports.array(PageSchema2).optional().describe("Custom Pages"), + dashboards: external_exports.array(DashboardSchema2).optional().describe("Dashboards"), + reports: external_exports.array(ReportSchema2).optional().describe("Analytics Reports"), + actions: external_exports.array(ActionSchema5).optional().describe("Global and Object Actions"), + themes: external_exports.array(ThemeSchema2).optional().describe("UI Themes"), + /** + * ObjectFlow: Automation Layer + * Business logic, approvals, and workflows. + */ + workflows: external_exports.array(WorkflowRuleSchema2).optional().describe("Event-driven workflows"), + approvals: external_exports.array(ApprovalProcessSchema).optional().describe("Approval processes"), + flows: external_exports.array(FlowSchema2).optional().describe("Screen Flows"), + /** + * ObjectGuard: Security Layer + */ + roles: external_exports.array(RoleSchema).optional().describe("User Roles hierarchy"), + permissions: external_exports.array(PermissionSetSchema2).optional().describe("Permission Sets and Profiles"), + sharingRules: external_exports.array(SharingRuleSchema).optional().describe("Record Sharing Rules"), + policies: external_exports.array(PolicySchema).optional().describe("Security & Compliance Policies"), + /** + * ObjectAPI: API Layer + */ + apis: external_exports.array(ApiEndpointSchema2).optional().describe("API Endpoints"), + webhooks: external_exports.array(WebhookSchema).optional().describe("Outbound Webhooks"), + /** + * ObjectAI: Artificial Intelligence Layer + */ + agents: external_exports.array(AgentSchema).optional().describe("AI Agents and Assistants"), + ragPipelines: external_exports.array(RAGPipelineConfigSchema).optional().describe("RAG Pipelines"), + /** + * ObjectQL: Data Extensions + * Hooks, mappings, and analytics cubes. + */ + hooks: external_exports.array(HookSchema2).optional().describe("Object Lifecycle Hooks"), + mappings: external_exports.array(MappingSchema2).optional().describe("Data Import/Export Mappings"), + analyticsCubes: external_exports.array(CubeSchema3).optional().describe("Analytics Semantic Layer Cubes"), + /** + * Integration Protocol + */ + connectors: external_exports.array(ConnectorSchema2).optional().describe("External System Connectors"), + /** + * Data Seeding Protocol + * + * Declarative seed data for bootstrapping, demos, and testing. + * Each entry targets a specific object and provides records to load + * using the specified conflict resolution strategy. + * + * Uses the standard DatasetSchema which supports: + * - `externalId`: Idempotency key for upsert matching (default: 'name') + * - `mode`: Conflict resolution (upsert, insert, ignore, replace) + * - `env`: Environment scoping (prod, dev, test) + * + * @example + * ```ts + * data: [ + * { + * object: 'account', + * mode: 'upsert', + * externalId: 'name', + * records: [ + * { name: 'Acme Corp', type: 'customer', industry: 'technology' }, + * ] + * } + * ] + * ``` + */ + data: external_exports.array(DatasetSchema4).optional().describe("Seed Data / Fixtures for bootstrapping"), + /** + * Plugins: External Capabilities + * List of plugins to load. Can be a Manifest object, a package name string, or a Runtime Plugin instance. + */ + plugins: external_exports.array(external_exports.unknown()).optional().describe("Plugins to load"), + /** + * DevPlugins: Development Capabilities + * List of plugins to load ONLY in development environment. + * Equivalent to `devDependencies` in package.json. + * Useful for loading dev-tools, mock data generators, or referencing local sibling packages for debugging. + */ + devPlugins: external_exports.array(external_exports.union([ManifestSchema3, external_exports.string()])).optional().describe("Plugins to load only in development (CLI dev command)") +}); +function collectObjectNames(config4) { + const names = /* @__PURE__ */ new Set(); + if (config4.objects) { + for (const obj of config4.objects) { + names.add(obj.name); + } + } + return names; +} +function validateCrossReferences(config4) { + const errors = []; + const objectNames = collectObjectNames(config4); + if (objectNames.size === 0) return errors; + if (config4.workflows) { + for (const workflow of config4.workflows) { + if (workflow.objectName && !objectNames.has(workflow.objectName)) { + errors.push( + `Workflow '${workflow.name}' references object '${workflow.objectName}' which is not defined in objects.` + ); + } + } + } + if (config4.approvals) { + for (const approval of config4.approvals) { + if (approval.object && !objectNames.has(approval.object)) { + errors.push( + `Approval '${approval.name}' references object '${approval.object}' which is not defined in objects.` + ); + } + } + } + if (config4.hooks) { + for (const hook of config4.hooks) { + if (hook.object) { + const hookObjects = Array.isArray(hook.object) ? hook.object : [hook.object]; + for (const obj of hookObjects) { + if (!objectNames.has(obj)) { + errors.push( + `Hook '${hook.name}' references object '${obj}' which is not defined in objects.` + ); + } + } + } + } + } + if (config4.views) { + for (const [i, view] of config4.views.entries()) { + const checkViewData = (data, viewLabel) => { + if (data && typeof data === "object" && "provider" in data && "object" in data) { + const d = data; + if (d.provider === "object" && d.object && !objectNames.has(d.object)) { + errors.push( + `${viewLabel} references object '${d.object}' which is not defined in objects.` + ); + } + } + }; + if (view.list?.data) { + checkViewData(view.list.data, `View[${i}].list`); + } + if (view.form?.data) { + checkViewData(view.form.data, `View[${i}].form`); + } + } + } + if (config4.data) { + for (const dataset of config4.data) { + if (dataset.object && !objectNames.has(dataset.object)) { + errors.push( + `Seed data references object '${dataset.object}' which is not defined in objects.` + ); + } + } + } + if (config4.apps) { + const dashboardNames = /* @__PURE__ */ new Set(); + if (config4.dashboards) { + for (const d of config4.dashboards) { + dashboardNames.add(d.name); + } + } + const pageNames = /* @__PURE__ */ new Set(); + if (config4.pages) { + for (const p of config4.pages) { + pageNames.add(p.name); + } + } + const reportNames = /* @__PURE__ */ new Set(); + if (config4.reports) { + for (const r of config4.reports) { + reportNames.add(r.name); + } + } + for (const app of config4.apps) { + if (!app.navigation) continue; + const checkNavItems = (items, appName) => { + for (const item of items) { + if (!item || typeof item !== "object") continue; + const nav = item; + if (nav.type === "object" && typeof nav.objectName === "string" && !objectNames.has(nav.objectName)) { + errors.push( + `App '${appName}' navigation references object '${nav.objectName}' which is not defined in objects.` + ); + } + if (nav.type === "dashboard" && typeof nav.dashboardName === "string" && dashboardNames.size > 0 && !dashboardNames.has(nav.dashboardName)) { + errors.push( + `App '${appName}' navigation references dashboard '${nav.dashboardName}' which is not defined in dashboards.` + ); + } + if (nav.type === "page" && typeof nav.pageName === "string" && pageNames.size > 0 && !pageNames.has(nav.pageName)) { + errors.push( + `App '${appName}' navigation references page '${nav.pageName}' which is not defined in pages.` + ); + } + if (nav.type === "report" && typeof nav.reportName === "string" && reportNames.size > 0 && !reportNames.has(nav.reportName)) { + errors.push( + `App '${appName}' navigation references report '${nav.reportName}' which is not defined in reports.` + ); + } + if (nav.type === "group" && Array.isArray(nav.children)) { + checkNavItems(nav.children, appName); + } + } + }; + checkNavItems(app.navigation, app.name); + } + } + if (config4.actions) { + const flowNames = /* @__PURE__ */ new Set(); + if (config4.flows) { + for (const flow of config4.flows) { + flowNames.add(flow.name); + } + } + const pageNames = /* @__PURE__ */ new Set(); + if (config4.pages) { + for (const page of config4.pages) { + pageNames.add(page.name); + } + } + for (const action of config4.actions) { + if (action.type === "flow" && action.target && flowNames.size > 0 && !flowNames.has(action.target)) { + errors.push( + `Action '${action.name}' references flow '${action.target}' which is not defined in flows.` + ); + } + if (action.type === "modal" && action.target && pageNames.size > 0 && !pageNames.has(action.target)) { + errors.push( + `Action '${action.name}' references page '${action.target}' (via modal target) which is not defined in pages.` + ); + } + if (action.objectName && !objectNames.has(action.objectName)) { + errors.push( + `Action '${action.name}' references object '${action.objectName}' which is not defined in objects.` + ); + } + } + } + return errors; +} +function mergeActionsIntoObjects(config4) { + if (!config4.actions || !config4.objects || config4.objects.length === 0) { + return config4; + } + const actionsByObject = /* @__PURE__ */ new Map(); + for (const action of config4.actions) { + if (action.objectName) { + const list = actionsByObject.get(action.objectName) ?? []; + list.push(action); + actionsByObject.set(action.objectName, list); + } + } + if (actionsByObject.size === 0) return config4; + const newObjects = config4.objects.map((obj) => { + const objActions = actionsByObject.get(obj.name); + if (!objActions) return obj; + return { + ...obj, + actions: [...obj.actions ?? [], ...objActions] + }; + }); + return { ...config4, objects: newObjects }; +} +function defineStack(config4, options) { + const strict = options?.strict !== false; + const normalized = normalizeStackInput(config4); + if (!strict) { + return mergeActionsIntoObjects(normalized); + } + const result = ObjectStackDefinitionSchema.safeParse(normalized, { + error: objectStackErrorMap + }); + if (!result.success) { + throw new Error(formatZodError(result.error, "defineStack validation failed")); + } + const crossRefErrors = validateCrossReferences(result.data); + if (crossRefErrors.length > 0) { + const header = `defineStack cross-reference validation failed (${crossRefErrors.length} issue${crossRefErrors.length === 1 ? "" : "s"}):`; + const lines = crossRefErrors.map((e) => ` \u2717 ${e}`); + throw new Error(`${header} + +${lines.join("\n")}`); + } + return mergeActionsIntoObjects(result.data); +} +var ConflictStrategySchema = external_exports.enum(["error", "override", "merge"]); +var ComposeStacksOptionsSchema = external_exports.object({ + /** + * How to handle same-name objects across stacks. + * @default 'error' + */ + objectConflict: ConflictStrategySchema.default("error"), + /** + * Which manifest to keep when multiple stacks provide one. + * - `'first'` — Use the first manifest found. + * - `'last'` — Use the last manifest found (default). + * - A number — Use the manifest from the stack at the given index. + * @default 'last' + */ + manifest: external_exports.union([external_exports.enum(["first", "last"]), external_exports.number().int().min(0)]).default("last"), + /** + * Optional namespace prefix (reserved for Phase 2 — Marketplace isolation). + * When set, object names from this composition are prefixed for isolation. + */ + namespace: external_exports.string().optional() +}); +var ObjectQLCapabilitiesSchema = external_exports.object({ + /** Query Capabilities */ + queryFilters: external_exports.boolean().default(true).describe("Supports WHERE clause filtering"), + queryAggregations: external_exports.boolean().default(true).describe("Supports GROUP BY and aggregation functions"), + querySorting: external_exports.boolean().default(true).describe("Supports ORDER BY sorting"), + queryPagination: external_exports.boolean().default(true).describe("Supports LIMIT/OFFSET pagination"), + queryWindowFunctions: external_exports.boolean().default(false).describe("Supports window functions with OVER clause"), + querySubqueries: external_exports.boolean().default(false).describe("Supports subqueries"), + queryDistinct: external_exports.boolean().default(true).describe("Supports SELECT DISTINCT"), + queryHaving: external_exports.boolean().default(false).describe("Supports HAVING clause for aggregations"), + queryJoins: external_exports.boolean().default(false).describe("Supports SQL-style joins"), + /** Advanced Data Features */ + fullTextSearch: external_exports.boolean().default(false).describe("Supports full-text search"), + vectorSearch: external_exports.boolean().default(false).describe("Supports vector embeddings and similarity search for AI/RAG"), + geoSpatial: external_exports.boolean().default(false).describe("Supports geospatial queries and location fields"), + /** Field Type Support */ + jsonFields: external_exports.boolean().default(true).describe("Supports JSON field types"), + arrayFields: external_exports.boolean().default(false).describe("Supports array field types"), + /** Data Validation & Logic */ + validationRules: external_exports.boolean().default(true).describe("Supports validation rules"), + workflows: external_exports.boolean().default(true).describe("Supports workflow automation"), + triggers: external_exports.boolean().default(true).describe("Supports database triggers"), + formulas: external_exports.boolean().default(true).describe("Supports formula fields"), + /** Transaction & Performance */ + transactions: external_exports.boolean().default(true).describe("Supports database transactions"), + bulkOperations: external_exports.boolean().default(true).describe("Supports bulk create/update/delete"), + /** Driver Support */ + supportedDrivers: external_exports.array(external_exports.string()).optional().describe("Available database drivers (e.g., postgresql, mongodb, excel)") +}); +var ObjectUICapabilitiesSchema = external_exports.object({ + /** View Types */ + listView: external_exports.boolean().default(true).describe("Supports list/grid views"), + formView: external_exports.boolean().default(true).describe("Supports form views"), + kanbanView: external_exports.boolean().default(false).describe("Supports kanban board views"), + calendarView: external_exports.boolean().default(false).describe("Supports calendar views"), + ganttView: external_exports.boolean().default(false).describe("Supports Gantt chart views"), + /** Analytics & Reporting */ + dashboards: external_exports.boolean().default(true).describe("Supports dashboard creation"), + reports: external_exports.boolean().default(true).describe("Supports report generation"), + charts: external_exports.boolean().default(true).describe("Supports chart widgets"), + /** Customization */ + customPages: external_exports.boolean().default(true).describe("Supports custom page creation"), + customThemes: external_exports.boolean().default(false).describe("Supports custom theme creation"), + customComponents: external_exports.boolean().default(false).describe("Supports custom UI components/widgets"), + /** Actions & Interactions */ + customActions: external_exports.boolean().default(true).describe("Supports custom button actions"), + screenFlows: external_exports.boolean().default(false).describe("Supports interactive screen flows"), + /** Responsive & Accessibility */ + mobileOptimized: external_exports.boolean().default(false).describe("UI optimized for mobile devices"), + accessibility: external_exports.boolean().default(false).describe("WCAG accessibility support") +}); +var ObjectOSCapabilitiesSchema = external_exports.object({ + /** System Identity */ + version: external_exports.string().describe("ObjectOS Kernel Version"), + environment: external_exports.enum(["development", "test", "staging", "production"]), + /** API Surface */ + restApi: external_exports.boolean().default(true).describe("REST API available"), + graphqlApi: external_exports.boolean().default(false).describe("GraphQL API available"), + odataApi: external_exports.boolean().default(false).describe("OData API available"), + /** Real-time & Events */ + websockets: external_exports.boolean().default(false).describe("WebSocket support for real-time updates"), + serverSentEvents: external_exports.boolean().default(false).describe("Server-Sent Events support"), + eventBus: external_exports.boolean().default(false).describe("Internal event bus for pub/sub"), + /** Integration */ + webhooks: external_exports.boolean().default(true).describe("Outbound webhook support"), + apiContracts: external_exports.boolean().default(false).describe("API contract definitions"), + /** Security & Access Control */ + authentication: external_exports.boolean().default(true).describe("Authentication system"), + rbac: external_exports.boolean().default(true).describe("Role-Based Access Control"), + fieldLevelSecurity: external_exports.boolean().default(false).describe("Field-level permissions"), + rowLevelSecurity: external_exports.boolean().default(false).describe("Row-level security/sharing rules"), + /** Multi-tenancy */ + multiTenant: external_exports.boolean().default(false).describe("Multi-tenant architecture support"), + /** Platform Services */ + backgroundJobs: external_exports.boolean().default(false).describe("Background job scheduling"), + auditLogging: external_exports.boolean().default(false).describe("Audit trail logging"), + fileStorage: external_exports.boolean().default(true).describe("File upload and storage"), + /** Internationalization */ + i18n: external_exports.boolean().default(true).describe("Internationalization support"), + /** Plugin System */ + pluginSystem: external_exports.boolean().default(false).describe("Plugin/extension system"), + /** Active Features & Flags */ + features: external_exports.array(FeatureFlagSchema2).optional().describe("Active Feature Flags"), + /** Available APIs */ + apis: external_exports.array(ApiEndpointSchema2).optional().describe("Available System & Business APIs"), + network: external_exports.object({ + graphql: external_exports.boolean().default(false), + search: external_exports.boolean().default(false), + websockets: external_exports.boolean().default(false), + files: external_exports.boolean().default(true), + analytics: external_exports.boolean().default(false).describe("Is the Analytics/BI engine enabled?"), + ai: external_exports.boolean().default(false).describe("Is the AI engine enabled?"), + workflow: external_exports.boolean().default(false).describe("Is the Workflow engine enabled?"), + notifications: external_exports.boolean().default(false).describe("Is the Notification service enabled?"), + i18n: external_exports.boolean().default(false).describe("Is the i18n service enabled?") + }).optional().describe("Network Capabilities (GraphQL, WS, etc.)"), + /** Introspection */ + systemObjects: external_exports.array(external_exports.string()).optional().describe("List of globally available System Objects"), + /** Constraints (for AI Generation) */ + limits: external_exports.object({ + maxObjects: external_exports.number().optional(), + maxFieldsPerObject: external_exports.number().optional(), + maxRecordsPerQuery: external_exports.number().optional(), + apiRateLimit: external_exports.number().optional(), + fileUploadSizeLimit: external_exports.number().optional().describe("Max file size in bytes") + }).optional() +}); +var ObjectStackCapabilitiesSchema = external_exports.object({ + /** Data Layer Capabilities (ObjectQL) */ + data: ObjectQLCapabilitiesSchema.describe("Data Layer capabilities"), + /** User Interface Layer Capabilities (ObjectUI) */ + ui: ObjectUICapabilitiesSchema.describe("UI Layer capabilities"), + /** System/Runtime Layer Capabilities (ObjectOS) */ + system: ObjectOSCapabilitiesSchema.describe("System/Runtime Layer capabilities") +}); + +// ../app-crm/src/objects/index.ts +var objects_exports = {}; +__export(objects_exports, { + Account: () => Account, + Campaign: () => Campaign, + Case: () => Case, + Contact: () => Contact, + Contract: () => Contract, + Lead: () => Lead, + Opportunity: () => Opportunity, + Product: () => Product, + Quote: () => Quote, + Task: () => Task3 +}); + +// ../app-crm/src/objects/account.object.ts +init_data(); +var Account = ObjectSchema3.create({ + name: "account", + label: "Account", + pluralLabel: "Accounts", + icon: "building", + description: "Companies and organizations doing business with us", + titleFormat: "{account_number} - {name}", + compactLayout: ["account_number", "name", "type", "owner"], + fields: { + // AutoNumber field - Unique account identifier + account_number: Field.autonumber({ + label: "Account Number", + format: "ACC-{0000}" + }), + // Basic Information + name: Field.text({ + label: "Account Name", + required: true, + searchable: true, + maxLength: 255 + }), + // Select fields with custom options + type: Field.select({ + label: "Account Type", + options: [ + { label: "Prospect", value: "prospect", color: "#FFA500", default: true }, + { label: "Customer", value: "customer", color: "#00AA00" }, + { label: "Partner", value: "partner", color: "#0000FF" }, + { label: "Former Customer", value: "former", color: "#999999" } + ] + }), + industry: Field.select({ + label: "Industry", + options: [ + { label: "Technology", value: "technology" }, + { label: "Finance", value: "finance" }, + { label: "Healthcare", value: "healthcare" }, + { label: "Retail", value: "retail" }, + { label: "Manufacturing", value: "manufacturing" }, + { label: "Education", value: "education" } + ] + }), + // Number fields + annual_revenue: Field.currency({ + label: "Annual Revenue", + scale: 2, + min: 0 + }), + number_of_employees: Field.number({ + label: "Employees", + min: 0 + }), + // Contact Information + phone: Field.text({ + label: "Phone", + format: "phone" + }), + website: Field.url({ + label: "Website" + }), + // Structured Address field (new field type) + billing_address: Field.address({ + label: "Billing Address", + addressFormat: "international" + }), + // Office Location (new field type) + office_location: Field.location({ + label: "Office Location", + displayMap: true, + allowGeocoding: true + }), + // Relationship fields + owner: Field.lookup("user", { + label: "Account Owner", + required: true + }), + parent_account: Field.lookup("account", { + label: "Parent Account", + description: "Parent company in hierarchy" + }), + // Rich text field + description: Field.markdown({ + label: "Description" + }), + // Boolean field + is_active: Field.boolean({ + label: "Active", + defaultValue: true + }), + // Date field + last_activity_date: Field.date({ + label: "Last Activity Date", + readonly: true + }), + // Brand color (new field type) + brand_color: Field.color({ + label: "Brand Color", + colorFormat: "hex", + presetColors: ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF"] + }) + }, + // Database indexes for performance + indexes: [ + { fields: ["name"] }, + { fields: ["owner"] }, + { fields: ["type", "is_active"] } + ], + // Enable advanced features + enable: { + trackHistory: true, + // Track field changes + searchable: true, + // Include in global search + apiEnabled: true, + // Expose via REST/GraphQL + apiMethods: ["get", "list", "create", "update", "delete", "search", "export"], + // Whitelist allowed API operations + files: true, + // Allow file attachments + feeds: true, + // Enable activity feed/chatter (Chatter-like) + activities: true, + // Enable tasks and events tracking + trash: true, + // Recycle bin support + mru: true + // Track Most Recently Used + }, + // Validation Rules + validations: [ + { + name: "revenue_positive", + type: "script", + severity: "error", + message: "Annual Revenue must be positive", + condition: "annual_revenue < 0" + }, + { + name: "account_name_unique", + type: "unique", + severity: "error", + message: "Account name must be unique", + fields: ["name"], + caseSensitive: false + } + ], + // Workflow Rules + workflows: [ + { + name: "update_last_activity", + objectName: "account", + triggerType: "on_update", + criteria: "ISCHANGED(owner) OR ISCHANGED(type)", + actions: [ + { + name: "set_activity_date", + type: "field_update", + field: "last_activity_date", + value: "TODAY()" + } + ], + active: true + } + ] +}); + +// ../app-crm/src/objects/campaign.object.ts +init_data(); +var Campaign = ObjectSchema3.create({ + name: "campaign", + label: "Campaign", + pluralLabel: "Campaigns", + icon: "megaphone", + description: "Marketing campaigns and initiatives", + titleFormat: "{campaign_code} - {name}", + compactLayout: ["campaign_code", "name", "type", "status", "start_date"], + fields: { + // AutoNumber field + campaign_code: Field.autonumber({ + label: "Campaign Code", + format: "CPG-{0000}" + }), + // Basic Information + name: Field.text({ + label: "Campaign Name", + required: true, + searchable: true, + maxLength: 255 + }), + description: Field.markdown({ + label: "Description" + }), + // Type & Channel + type: Field.select({ + label: "Campaign Type", + options: [ + { label: "Email", value: "email", default: true }, + { label: "Webinar", value: "webinar" }, + { label: "Trade Show", value: "trade_show" }, + { label: "Conference", value: "conference" }, + { label: "Direct Mail", value: "direct_mail" }, + { label: "Social Media", value: "social_media" }, + { label: "Content Marketing", value: "content" }, + { label: "Partner Marketing", value: "partner" } + ] + }), + channel: Field.select({ + label: "Primary Channel", + options: [ + { label: "Digital", value: "digital" }, + { label: "Social", value: "social" }, + { label: "Email", value: "email" }, + { label: "Events", value: "events" }, + { label: "Partner", value: "partner" } + ] + }), + // Status + status: Field.select({ + label: "Status", + options: [ + { label: "Planning", value: "planning", color: "#999999", default: true }, + { label: "In Progress", value: "in_progress", color: "#FFA500" }, + { label: "Completed", value: "completed", color: "#00AA00" }, + { label: "Aborted", value: "aborted", color: "#FF0000" } + ], + required: true + }), + // Dates + start_date: Field.date({ + label: "Start Date", + required: true + }), + end_date: Field.date({ + label: "End Date", + required: true + }), + // Budget & ROI + budgeted_cost: Field.currency({ + label: "Budgeted Cost", + scale: 2, + min: 0 + }), + actual_cost: Field.currency({ + label: "Actual Cost", + scale: 2, + min: 0 + }), + expected_revenue: Field.currency({ + label: "Expected Revenue", + scale: 2, + min: 0 + }), + actual_revenue: Field.currency({ + label: "Actual Revenue", + scale: 2, + min: 0, + readonly: true + }), + // Metrics + target_size: Field.number({ + label: "Target Size", + description: "Target number of leads/contacts", + min: 0 + }), + num_sent: Field.number({ + label: "Number Sent", + min: 0, + readonly: true + }), + num_responses: Field.number({ + label: "Number of Responses", + min: 0, + readonly: true + }), + num_leads: Field.number({ + label: "Number of Leads", + min: 0, + readonly: true + }), + num_converted_leads: Field.number({ + label: "Converted Leads", + min: 0, + readonly: true + }), + num_opportunities: Field.number({ + label: "Opportunities Created", + min: 0, + readonly: true + }), + num_won_opportunities: Field.number({ + label: "Won Opportunities", + min: 0, + readonly: true + }), + // Calculated Metrics (Formula Fields) + response_rate: Field.formula({ + label: "Response Rate %", + expression: "IF(num_sent > 0, (num_responses / num_sent) * 100, 0)", + scale: 2 + }), + roi: Field.formula({ + label: "ROI %", + expression: "IF(actual_cost > 0, ((actual_revenue - actual_cost) / actual_cost) * 100, 0)", + scale: 2 + }), + // Relationships + parent_campaign: Field.lookup("campaign", { + label: "Parent Campaign", + description: "Parent campaign in hierarchy" + }), + owner: Field.lookup("user", { + label: "Campaign Owner", + required: true + }), + // Campaign Assets + landing_page_url: Field.url({ + label: "Landing Page" + }), + is_active: Field.boolean({ + label: "Active", + defaultValue: true + }) + }, + // Database indexes + indexes: [ + { fields: ["name"] }, + { fields: ["type"] }, + { fields: ["status"] }, + { fields: ["start_date"] }, + { fields: ["owner"] } + ], + // Enable advanced features + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete", "search", "export"], + files: true, + feeds: true, + activities: true, + trash: true, + mru: true + }, + // Validation Rules + validations: [ + { + name: "end_after_start", + type: "script", + severity: "error", + message: "End Date must be after Start Date", + condition: "end_date < start_date" + }, + { + name: "actual_cost_within_budget", + type: "script", + severity: "warning", + message: "Actual Cost exceeds Budgeted Cost", + condition: "actual_cost > budgeted_cost" + } + ], + // Workflow Rules + workflows: [ + { + name: "campaign_completion_check", + objectName: "campaign", + triggerType: "on_read", + criteria: 'end_date < TODAY() AND status = "in_progress"', + actions: [ + { + name: "mark_completed", + type: "field_update", + field: "status", + value: '"completed"' + } + ], + active: true + } + ] +}); + +// ../app-crm/src/objects/case.object.ts +init_data(); +var Case = ObjectSchema3.create({ + name: "case", + label: "Case", + pluralLabel: "Cases", + icon: "life-buoy", + description: "Customer support cases and service requests", + fields: { + // Case Information + case_number: Field.autonumber({ + label: "Case Number", + format: "CASE-{00000}" + }), + subject: Field.text({ + label: "Subject", + required: true, + searchable: true, + maxLength: 255 + }), + description: Field.markdown({ + label: "Description", + required: true + }), + // Relationships + account: Field.lookup("account", { + label: "Account" + }), + contact: Field.lookup("contact", { + label: "Contact", + required: true, + referenceFilters: ["account = {case.account}"] + }), + // Case Management + status: Field.select({ + label: "Status", + required: true, + options: [ + { label: "New", value: "new", color: "#808080", default: true }, + { label: "In Progress", value: "in_progress", color: "#FFA500" }, + { label: "Waiting on Customer", value: "waiting_customer", color: "#FFD700" }, + { label: "Waiting on Support", value: "waiting_support", color: "#4169E1" }, + { label: "Escalated", value: "escalated", color: "#FF0000" }, + { label: "Resolved", value: "resolved", color: "#00AA00" }, + { label: "Closed", value: "closed", color: "#006400" } + ] + }), + priority: Field.select({ + label: "Priority", + required: true, + options: [ + { label: "Low", value: "low", color: "#4169E1", default: true }, + { label: "Medium", value: "medium", color: "#FFA500" }, + { label: "High", value: "high", color: "#FF4500" }, + { label: "Critical", value: "critical", color: "#FF0000" } + ] + }), + type: Field.select({ + label: "Case Type", + options: [ + { label: "Question", value: "question" }, + { label: "Problem", value: "problem" }, + { label: "Feature Request", value: "feature_request" }, + { label: "Bug", value: "bug" } + ] + }), + origin: Field.select({ + label: "Case Origin", + options: [ + { label: "Email", value: "email" }, + { label: "Phone", value: "phone" }, + { label: "Web", value: "web" }, + { label: "Chat", value: "chat" }, + { label: "Social Media", value: "social_media" } + ] + }), + // Assignment + owner: Field.lookup("user", { + label: "Case Owner", + required: true + }), + // SLA and Metrics + created_date: Field.datetime({ + label: "Created Date", + readonly: true + }), + closed_date: Field.datetime({ + label: "Closed Date", + readonly: true + }), + first_response_date: Field.datetime({ + label: "First Response Date", + readonly: true + }), + resolution_time_hours: Field.number({ + label: "Resolution Time (Hours)", + readonly: true, + scale: 2 + }), + sla_due_date: Field.datetime({ + label: "SLA Due Date" + }), + is_sla_violated: Field.boolean({ + label: "SLA Violated", + defaultValue: false, + readonly: true + }), + // Escalation + is_escalated: Field.boolean({ + label: "Escalated", + defaultValue: false + }), + escalation_reason: Field.textarea({ + label: "Escalation Reason" + }), + // Related case + parent_case: Field.lookup("case", { + label: "Parent Case", + description: "Related parent case" + }), + // Resolution + resolution: Field.markdown({ + label: "Resolution" + }), + // Customer satisfaction + customer_rating: Field.rating(5, { + label: "Customer Satisfaction", + description: "Customer satisfaction rating (1-5 stars)" + }), + customer_feedback: Field.textarea({ + label: "Customer Feedback" + }), + // Customer signature (for case resolution acknowledgment) + customer_signature: Field.signature({ + label: "Customer Signature", + description: "Digital signature acknowledging case resolution" + }), + // Internal notes + internal_notes: Field.markdown({ + label: "Internal Notes", + description: "Internal notes not visible to customer" + }), + // Flags + is_closed: Field.boolean({ + label: "Is Closed", + defaultValue: false, + readonly: true + }) + }, + // Database indexes for performance + indexes: [ + { fields: ["case_number"], unique: true }, + { fields: ["account"] }, + { fields: ["owner"] }, + { fields: ["status"] }, + { fields: ["priority"] } + ], + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + files: true, + feeds: true, + // Enable social feed, comments, and mentions + activities: true, + // Enable tasks and events tracking + trash: true, + mru: true + // Track Most Recently Used + }, + titleFormat: "{case_number} - {subject}", + compactLayout: ["case_number", "subject", "account", "status", "priority"], + // Removed: list_views and form_views belong in UI configuration, not object definition + validations: [ + { + name: "resolution_required_for_closed", + type: "script", + severity: "error", + message: "Resolution is required when closing a case", + condition: 'status = "closed" AND ISBLANK(resolution)' + }, + { + name: "escalation_reason_required", + type: "script", + severity: "error", + message: "Escalation reason is required when escalating a case", + condition: "is_escalated = true AND ISBLANK(escalation_reason)" + }, + { + name: "case_status_progression", + type: "state_machine", + severity: "warning", + message: "Invalid status transition", + field: "status", + transitions: { + "new": ["in_progress", "waiting_customer", "closed"], + "in_progress": ["waiting_customer", "waiting_support", "escalated", "resolved"], + "waiting_customer": ["in_progress", "closed"], + "waiting_support": ["in_progress", "escalated"], + "escalated": ["in_progress", "resolved"], + "resolved": ["closed", "in_progress"], + // Can reopen + "closed": ["in_progress"] + // Can reopen + } + } + ], + workflows: [ + { + name: "set_closed_flag", + objectName: "case", + triggerType: "on_create_or_update", + criteria: "ISCHANGED(status)", + active: true, + actions: [ + { + name: "update_closed_flag", + type: "field_update", + field: "is_closed", + value: 'status = "closed"' + } + ] + }, + { + name: "set_closed_date", + objectName: "case", + triggerType: "on_update", + criteria: 'ISCHANGED(status) AND status = "closed"', + active: true, + actions: [ + { + name: "set_date", + type: "field_update", + field: "closed_date", + value: "NOW()" + } + ] + }, + { + name: "calculate_resolution_time", + objectName: "case", + triggerType: "on_update", + criteria: "ISCHANGED(closed_date) AND NOT(ISBLANK(closed_date))", + active: true, + actions: [ + { + name: "calc_time", + type: "field_update", + field: "resolution_time_hours", + value: "HOURS(created_date, closed_date)" + } + ] + }, + { + name: "notify_on_critical", + objectName: "case", + triggerType: "on_create_or_update", + criteria: 'priority = "critical"', + active: true, + actions: [ + { + name: "email_support_manager", + type: "email_alert", + template: "critical_case_alert", + recipients: ["support_manager@example.com"] + } + ] + }, + { + name: "notify_on_escalation", + objectName: "case", + triggerType: "on_update", + criteria: "ISCHANGED(is_escalated) AND is_escalated = true", + active: true, + actions: [ + { + name: "email_escalation_team", + type: "email_alert", + template: "case_escalation_alert", + recipients: ["escalation_team@example.com"] + } + ] + } + ] +}); + +// ../app-crm/src/objects/contact.object.ts +init_data(); +var Contact = ObjectSchema3.create({ + name: "contact", + label: "Contact", + pluralLabel: "Contacts", + icon: "user", + description: "People associated with accounts", + fields: { + // Name fields + salutation: Field.select({ + label: "Salutation", + options: [ + { label: "Mr.", value: "mr" }, + { label: "Ms.", value: "ms" }, + { label: "Mrs.", value: "mrs" }, + { label: "Dr.", value: "dr" }, + { label: "Prof.", value: "prof" } + ] + }), + first_name: Field.text({ + label: "First Name", + required: true, + searchable: true + }), + last_name: Field.text({ + label: "Last Name", + required: true, + searchable: true + }), + // Formula field - Full name + full_name: Field.formula({ + label: "Full Name", + expression: 'CONCAT(salutation, " ", first_name, " ", last_name)' + }), + // Relationship: Link to Account (Master-Detail) + account: Field.masterDetail("account", { + label: "Account", + required: true, + writeRequiresMasterRead: true, + deleteBehavior: "cascade" + // Delete contacts when account is deleted + }), + // Contact Information + email: Field.email({ + label: "Email", + required: true, + unique: true + }), + phone: Field.text({ + label: "Phone", + format: "phone" + }), + mobile: Field.text({ + label: "Mobile", + format: "phone" + }), + // Professional Information + title: Field.text({ + label: "Job Title" + }), + department: Field.select({ + label: "Department", + options: [ + { label: "Executive", value: "executive" }, + { label: "Sales", value: "sales" }, + { label: "Marketing", value: "marketing" }, + { label: "Engineering", value: "engineering" }, + { label: "Support", value: "support" }, + { label: "Finance", value: "finance" }, + { label: "HR", value: "hr" }, + { label: "Operations", value: "operations" } + ] + }), + // Relationship fields + reports_to: Field.lookup("contact", { + label: "Reports To", + description: "Direct manager/supervisor" + }), + owner: Field.lookup("user", { + label: "Contact Owner", + required: true + }), + // Mailing Address + mailing_street: Field.textarea({ label: "Mailing Street" }), + mailing_city: Field.text({ label: "Mailing City" }), + mailing_state: Field.text({ label: "Mailing State/Province" }), + mailing_postal_code: Field.text({ label: "Mailing Postal Code" }), + mailing_country: Field.text({ label: "Mailing Country" }), + // Additional Information + birthdate: Field.date({ + label: "Birthdate" + }), + lead_source: Field.select({ + label: "Lead Source", + options: [ + { label: "Web", value: "web" }, + { label: "Referral", value: "referral" }, + { label: "Event", value: "event" }, + { label: "Partner", value: "partner" }, + { label: "Advertisement", value: "advertisement" } + ] + }), + description: Field.markdown({ + label: "Description" + }), + // Flags + is_primary: Field.boolean({ + label: "Primary Contact", + defaultValue: false, + description: "Is this the main contact for the account?" + }), + do_not_call: Field.boolean({ + label: "Do Not Call", + defaultValue: false + }), + email_opt_out: Field.boolean({ + label: "Email Opt Out", + defaultValue: false + }), + // Avatar field + avatar: Field.avatar({ + label: "Profile Picture" + }) + }, + // Enable features + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + files: true, + feeds: true, + // Enable social feed, comments, and mentions + activities: true, + // Enable tasks and events tracking + trash: true, + mru: true + // Track Most Recently Used + }, + // Database indexes for performance + indexes: [ + { fields: ["account"] }, + { fields: ["email"], unique: true }, + { fields: ["owner"] }, + { fields: ["last_name", "first_name"] } + ], + // Display configuration + titleFormat: "{full_name}", + compactLayout: ["full_name", "email", "account", "phone"], + // Validation Rules + validations: [ + { + name: "email_required_for_opt_in", + type: "script", + severity: "error", + message: "Email is required when Email Opt Out is not checked", + condition: "email_opt_out = false AND ISBLANK(email)" + }, + { + name: "email_unique_per_account", + type: "unique", + severity: "error", + message: "Email must be unique within an account", + fields: ["email", "account"], + caseSensitive: false + } + ], + // Workflow Rules + workflows: [ + { + name: "welcome_email", + objectName: "contact", + triggerType: "on_create", + active: true, + actions: [ + { + name: "send_welcome", + type: "email_alert", + template: "contact_welcome", + recipients: ["{contact.email}"] + } + ] + } + ] +}); + +// ../app-crm/src/objects/contract.object.ts +init_data(); +var Contract = ObjectSchema3.create({ + name: "contract", + label: "Contract", + pluralLabel: "Contracts", + icon: "file-signature", + description: "Legal contracts and agreements", + titleFormat: "{contract_number} - {account.name}", + compactLayout: ["contract_number", "account", "status", "start_date", "end_date"], + fields: { + // AutoNumber field + contract_number: Field.autonumber({ + label: "Contract Number", + format: "CTR-{0000}" + }), + // Relationships + account: Field.lookup("account", { + label: "Account", + required: true + }), + contact: Field.lookup("contact", { + label: "Primary Contact", + required: true, + referenceFilters: [ + "account = {account}" + ] + }), + opportunity: Field.lookup("opportunity", { + label: "Related Opportunity", + referenceFilters: [ + "account = {account}" + ] + }), + owner: Field.lookup("user", { + label: "Contract Owner", + required: true + }), + // Status + status: Field.select({ + label: "Status", + options: [ + { label: "Draft", value: "draft", color: "#999999", default: true }, + { label: "In Approval", value: "in_approval", color: "#FFA500" }, + { label: "Activated", value: "activated", color: "#00AA00" }, + { label: "Expired", value: "expired", color: "#FF0000" }, + { label: "Terminated", value: "terminated", color: "#666666" } + ], + required: true + }), + // Contract Terms + contract_term_months: Field.number({ + label: "Contract Term (Months)", + required: true, + min: 1 + }), + start_date: Field.date({ + label: "Start Date", + required: true + }), + end_date: Field.date({ + label: "End Date", + required: true + }), + // Financial + contract_value: Field.currency({ + label: "Contract Value", + scale: 2, + min: 0, + required: true + }), + billing_frequency: Field.select({ + label: "Billing Frequency", + options: [ + { label: "Monthly", value: "monthly", default: true }, + { label: "Quarterly", value: "quarterly" }, + { label: "Annually", value: "annually" }, + { label: "One-time", value: "one_time" } + ] + }), + payment_terms: Field.select({ + label: "Payment Terms", + options: [ + { label: "Net 15", value: "net_15" }, + { label: "Net 30", value: "net_30", default: true }, + { label: "Net 60", value: "net_60" }, + { label: "Net 90", value: "net_90" } + ] + }), + // Renewal + auto_renewal: Field.boolean({ + label: "Auto Renewal", + defaultValue: false + }), + renewal_notice_days: Field.number({ + label: "Renewal Notice (Days)", + min: 0, + defaultValue: 30 + }), + // Legal + contract_type: Field.select({ + label: "Contract Type", + options: [ + { label: "Subscription", value: "subscription" }, + { label: "Service Agreement", value: "service" }, + { label: "License", value: "license" }, + { label: "Partnership", value: "partnership" }, + { label: "NDA", value: "nda" }, + { label: "MSA", value: "msa" } + ] + }), + signed_date: Field.date({ + label: "Signed Date" + }), + signed_by: Field.text({ + label: "Signed By", + maxLength: 255 + }), + document_url: Field.url({ + label: "Contract Document" + }), + // Terms & Conditions + special_terms: Field.markdown({ + label: "Special Terms" + }), + description: Field.markdown({ + label: "Description" + }), + // Billing Address + billing_address: Field.address({ + label: "Billing Address", + addressFormat: "international" + }) + }, + // Database indexes + indexes: [ + { fields: ["account"] }, + { fields: ["status"] }, + { fields: ["start_date"] }, + { fields: ["end_date"] }, + { fields: ["owner"] } + ], + // Enable advanced features + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete", "search", "export"], + files: true, + feeds: true, + activities: true, + trash: true, + mru: true + }, + // Validation Rules + validations: [ + { + name: "end_after_start", + type: "script", + severity: "error", + message: "End Date must be after Start Date", + condition: "end_date <= start_date" + }, + { + name: "valid_contract_term", + type: "script", + severity: "error", + message: "Contract Term must match date range", + condition: "MONTH_DIFF(end_date, start_date) != contract_term_months" + } + ], + // Workflow Rules + workflows: [ + { + name: "contract_expiration_check", + objectName: "contract", + triggerType: "scheduled", + schedule: "0 0 * * *", + // Daily at midnight + criteria: 'end_date <= TODAY() AND status = "activated"', + actions: [ + { + name: "mark_expired", + type: "field_update", + field: "status", + value: '"expired"' + }, + { + name: "notify_owner", + type: "email_alert", + template: "contract_expired", + recipients: ["{owner}"] + } + ], + active: true + }, + { + name: "renewal_reminder", + objectName: "contract", + triggerType: "scheduled", + schedule: "0 0 * * *", + // Daily at midnight + criteria: 'DAYS_UNTIL(end_date) <= renewal_notice_days AND status = "activated"', + actions: [ + { + name: "notify_renewal", + type: "email_alert", + template: "contract_renewal_reminder", + recipients: ["{owner}", "{account.owner}"] + } + ], + active: true + } + ] +}); + +// ../app-crm/src/objects/lead.object.ts +init_data(); + +// ../app-crm/src/objects/lead.state.ts +var LeadStateMachine = { + id: "lead_process", + initial: "new", + states: { + new: { + on: { + CONTACT: { target: "contacted", description: "Log initial contact" }, + DISQUALIFY: { target: "unqualified", description: "Mark as unqualified early" } + }, + meta: { + aiInstructions: "New lead. Verify email and phone before contacting. Do not change status until contact is made." + } + }, + contacted: { + on: { + QUALIFY: { target: "qualified", cond: "has_budget_and_authority" }, + DISQUALIFY: { target: "unqualified" } + }, + meta: { + aiInstructions: "Engage with the lead. Qualify by asking about budget, authority, need, and timeline (BANT)." + } + }, + qualified: { + on: { + CONVERT: { target: "converted", cond: "is_ready_to_buy" }, + DISQUALIFY: { target: "unqualified" } + }, + meta: { + aiInstructions: "Lead is qualified. Prepare for conversion to Deal/Opportunity. Check for existing accounts." + } + }, + unqualified: { + on: { + REOPEN: { target: "new", description: "Re-evaluate lead" } + }, + meta: { + aiInstructions: "Lead is dead. Do not contact unless new information surfaces." + } + }, + converted: { + type: "final", + meta: { + aiInstructions: "Lead is converted. No further actions allowed on this record." + } + } + } +}; + +// ../app-crm/src/objects/lead.object.ts +var Lead = ObjectSchema3.create({ + name: "lead", + label: "Lead", + pluralLabel: "Leads", + icon: "user-plus", + description: "Potential customers not yet qualified", + fields: { + // Personal Information + salutation: Field.select({ + label: "Salutation", + options: [ + { label: "Mr.", value: "mr" }, + { label: "Ms.", value: "ms" }, + { label: "Mrs.", value: "mrs" }, + { label: "Dr.", value: "dr" } + ] + }), + first_name: Field.text({ + label: "First Name", + required: true, + searchable: true + }), + last_name: Field.text({ + label: "Last Name", + required: true, + searchable: true + }), + full_name: Field.formula({ + label: "Full Name", + expression: 'CONCAT(salutation, " ", first_name, " ", last_name)' + }), + // Company Information + company: Field.text({ + label: "Company", + required: true, + searchable: true + }), + title: Field.text({ + label: "Job Title" + }), + industry: Field.select({ + label: "Industry", + options: [ + { label: "Technology", value: "technology" }, + { label: "Finance", value: "finance" }, + { label: "Healthcare", value: "healthcare" }, + { label: "Retail", value: "retail" }, + { label: "Manufacturing", value: "manufacturing" }, + { label: "Education", value: "education" } + ] + }), + // Contact Information + email: Field.email({ + label: "Email", + required: true, + unique: true + }), + phone: Field.text({ + label: "Phone", + format: "phone" + }), + mobile: Field.text({ + label: "Mobile", + format: "phone" + }), + website: Field.url({ + label: "Website" + }), + // Lead Qualification + status: Field.select({ + label: "Lead Status", + required: true, + options: [ + { label: "New", value: "new", color: "#808080", default: true }, + { label: "Contacted", value: "contacted", color: "#FFA500" }, + { label: "Qualified", value: "qualified", color: "#4169E1" }, + { label: "Unqualified", value: "unqualified", color: "#FF0000" }, + { label: "Converted", value: "converted", color: "#00AA00" } + ] + }), + rating: Field.rating(5, { + label: "Lead Score", + description: "Lead quality score (1-5 stars)", + allowHalf: true + }), + lead_source: Field.select({ + label: "Lead Source", + options: [ + { label: "Web", value: "web" }, + { label: "Referral", value: "referral" }, + { label: "Event", value: "event" }, + { label: "Partner", value: "partner" }, + { label: "Advertisement", value: "advertisement" }, + { label: "Cold Call", value: "cold_call" } + ] + }), + // Assignment + owner: Field.lookup("user", { + label: "Lead Owner", + required: true + }), + // Conversion tracking + is_converted: Field.boolean({ + label: "Converted", + defaultValue: false, + readonly: true + }), + converted_account: Field.lookup("account", { + label: "Converted Account", + readonly: true + }), + converted_contact: Field.lookup("contact", { + label: "Converted Contact", + readonly: true + }), + converted_opportunity: Field.lookup("opportunity", { + label: "Converted Opportunity", + readonly: true + }), + converted_date: Field.datetime({ + label: "Converted Date", + readonly: true + }), + // Address (using new address field type) + address: Field.address({ + label: "Address", + addressFormat: "international" + }), + // Additional Info + annual_revenue: Field.currency({ + label: "Annual Revenue", + scale: 2 + }), + number_of_employees: Field.number({ + label: "Number of Employees" + }), + description: Field.markdown({ + label: "Description" + }), + // Custom notes with rich text formatting + notes: Field.richtext({ + label: "Notes", + description: "Rich text notes with formatting" + }), + // Flags + do_not_call: Field.boolean({ + label: "Do Not Call", + defaultValue: false + }), + email_opt_out: Field.boolean({ + label: "Email Opt Out", + defaultValue: false + }) + }, + // Lifecycle State Machine(s) + // Enforces valid status transitions to prevent AI hallucinations + // Using `stateMachines` (plural) for future extensibility. + // For simple objects with one lifecycle, `stateMachine` (singular) is also supported. + stateMachines: { + lifecycle: LeadStateMachine + }, + // Database indexes for performance + indexes: [ + { fields: ["email"], unique: true }, + { fields: ["owner"] }, + { fields: ["status"] }, + { fields: ["company"] } + ], + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + files: true, + feeds: true, + // Enable social feed, comments, and mentions + activities: true, + // Enable tasks and events tracking + trash: true, + mru: true + // Track Most Recently Used + }, + titleFormat: "{full_name} - {company}", + compactLayout: ["full_name", "company", "email", "status", "owner"], + // Removed: list_views and form_views belong in UI configuration, not object definition + validations: [ + { + name: "email_required", + type: "script", + severity: "error", + message: "Email is required", + condition: "ISBLANK(email)" + }, + { + name: "cannot_edit_converted", + type: "script", + severity: "error", + message: "Cannot edit a converted lead", + condition: "is_converted = true AND ISCHANGED(company, email, first_name, last_name)" + } + ], + workflows: [ + { + name: "auto_qualify_high_score_leads", + objectName: "lead", + triggerType: "on_create_or_update", + criteria: 'rating >= 4 AND status = "new"', + active: true, + actions: [ + { + name: "set_status", + type: "field_update", + field: "status", + value: "contacted" + } + ] + }, + { + name: "notify_owner_on_high_score_lead", + objectName: "lead", + triggerType: "on_create_or_update", + criteria: "ISCHANGED(rating) AND rating >= 4.5", + active: true, + actions: [ + { + name: "email_owner", + type: "email_alert", + template: "high_score_lead_notification", + recipients: ["{owner.email}"] + } + ] + } + ] +}); + +// ../app-crm/src/objects/opportunity.object.ts +init_data(); + +// ../app-crm/src/objects/opportunity.state.ts +var OpportunityStateMachine = { + id: "opportunity_pipeline", + initial: "prospecting", + states: { + prospecting: { + on: { + QUALIFY: { target: "qualification", description: "Initial qualification passed" }, + LOSE: { target: "closed_lost", description: "Lost at prospecting stage" } + }, + meta: { + aiInstructions: "New opportunity. Identify decision makers and confirm budget exists before advancing." + } + }, + qualification: { + on: { + ANALYZE: { target: "needs_analysis", description: "Begin needs analysis" }, + LOSE: { target: "closed_lost", description: "Lost at qualification stage" } + }, + meta: { + aiInstructions: "Qualifying opportunity. Gather BANT (Budget, Authority, Need, Timeline) details." + } + }, + needs_analysis: { + on: { + PROPOSE: { target: "proposal", description: "Submit proposal" }, + LOSE: { target: "closed_lost", description: "Lost during needs analysis" } + }, + meta: { + aiInstructions: "Analyzing customer needs. Document requirements and pain points before proposing." + } + }, + proposal: { + on: { + NEGOTIATE: { target: "negotiation", description: "Enter negotiation" }, + LOSE: { target: "closed_lost", description: "Proposal rejected" } + }, + meta: { + aiInstructions: "Proposal submitted. Follow up on pricing and terms. Prepare for negotiation." + } + }, + negotiation: { + on: { + WIN: { target: "closed_won", description: "Deal won" }, + LOSE: { target: "closed_lost", description: "Lost in negotiation" } + }, + meta: { + aiInstructions: "In negotiation. Focus on closing. Escalate blockers to management if needed." + } + }, + closed_won: { + type: "final", + meta: { + aiInstructions: "Deal won. No further stage changes allowed. Trigger contract creation." + } + }, + closed_lost: { + type: "final", + meta: { + aiInstructions: "Deal lost. Record loss reason. No further stage changes allowed." + } + } + } +}; + +// ../app-crm/src/objects/opportunity.object.ts +var Opportunity = ObjectSchema3.create({ + name: "opportunity", + label: "Opportunity", + pluralLabel: "Opportunities", + icon: "dollar-sign", + description: "Sales opportunities and deals in the pipeline", + titleFormat: "{name} - {stage}", + compactLayout: ["name", "account", "amount", "stage", "owner"], + fields: { + // Basic Information + name: Field.text({ + label: "Opportunity Name", + required: true, + searchable: true + }), + // Relationships + account: Field.lookup("account", { + label: "Account", + required: true + }), + primary_contact: Field.lookup("contact", { + label: "Primary Contact", + referenceFilters: ["account = {opportunity.account}"] + // Filter contacts by account + }), + owner: Field.lookup("user", { + label: "Opportunity Owner", + required: true + }), + // Financial Information + amount: Field.currency({ + label: "Amount", + required: true, + scale: 2, + min: 0 + }), + expected_revenue: Field.currency({ + label: "Expected Revenue", + scale: 2, + readonly: true + // Calculated field + }), + // Sales Process + stage: Field.select({ + label: "Stage", + required: true, + options: [ + { label: "Prospecting", value: "prospecting", color: "#808080", default: true }, + { label: "Qualification", value: "qualification", color: "#FFA500" }, + { label: "Needs Analysis", value: "needs_analysis", color: "#FFD700" }, + { label: "Proposal", value: "proposal", color: "#4169E1" }, + { label: "Negotiation", value: "negotiation", color: "#9370DB" }, + { label: "Closed Won", value: "closed_won", color: "#00AA00" }, + { label: "Closed Lost", value: "closed_lost", color: "#FF0000" } + ] + }), + probability: Field.percent({ + label: "Probability (%)", + min: 0, + max: 100, + defaultValue: 10 + }), + // Important Dates + close_date: Field.date({ + label: "Close Date", + required: true + }), + created_date: Field.datetime({ + label: "Created Date", + readonly: true + }), + // Additional Classification + type: Field.select({ + label: "Opportunity Type", + options: [ + { label: "New Business", value: "new_business" }, + { label: "Existing Customer - Upgrade", value: "existing_upgrade" }, + { label: "Existing Customer - Renewal", value: "existing_renewal" }, + { label: "Existing Customer - Expansion", value: "existing_expansion" } + ] + }), + lead_source: Field.select({ + label: "Lead Source", + options: [ + { label: "Web", value: "web" }, + { label: "Referral", value: "referral" }, + { label: "Event", value: "event" }, + { label: "Partner", value: "partner" }, + { label: "Advertisement", value: "advertisement" }, + { label: "Cold Call", value: "cold_call" } + ] + }), + // Competitor Analysis + competitors: Field.select({ + label: "Competitors", + multiple: true, + options: [ + { label: "Competitor A", value: "competitor_a" }, + { label: "Competitor B", value: "competitor_b" }, + { label: "Competitor C", value: "competitor_c" } + ] + }), + // Campaign tracking + campaign: Field.lookup("campaign", { + label: "Campaign", + description: "Marketing campaign that generated this opportunity" + }), + // Sales cycle metrics + days_in_stage: Field.number({ + label: "Days in Current Stage", + readonly: true + }), + // Additional information + description: Field.markdown({ + label: "Description" + }), + next_step: Field.textarea({ + label: "Next Steps" + }), + // Flags + is_private: Field.boolean({ + label: "Private", + defaultValue: false + }), + forecast_category: Field.select({ + label: "Forecast Category", + options: [ + { label: "Pipeline", value: "pipeline" }, + { label: "Best Case", value: "best_case" }, + { label: "Commit", value: "commit" }, + { label: "Omitted", value: "omitted" }, + { label: "Closed", value: "closed" } + ] + }) + }, + // Database indexes for performance + indexes: [ + { fields: ["name"] }, + { fields: ["account"] }, + { fields: ["owner"] }, + { fields: ["stage"] }, + { fields: ["close_date"] } + ], + // Enable advanced features + enable: { + trackHistory: true, + // Critical for tracking stage changes + searchable: true, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete", "aggregate", "search"], + // Whitelist allowed API operations + files: true, + // Attach proposals, contracts + feeds: true, + // Team collaboration (Chatter-like) + activities: true, + // Enable tasks and events tracking + trash: true, + mru: true + // Track Most Recently Used + }, + // Removed: list_views and form_views belong in UI configuration, not object definition + // Lifecycle State Machine(s) + stateMachines: { + lifecycle: OpportunityStateMachine + }, + // Validation Rules + validations: [ + { + name: "close_date_future", + type: "script", + severity: "warning", + message: "Close date should not be in the past unless opportunity is closed", + condition: 'close_date < TODAY() AND stage != "closed_won" AND stage != "closed_lost"' + }, + { + name: "amount_positive", + type: "script", + severity: "error", + message: "Amount must be greater than zero", + condition: "amount <= 0" + } + ], + // Workflow Rules + workflows: [ + { + name: "update_probability_by_stage", + objectName: "opportunity", + triggerType: "on_create_or_update", + criteria: "ISCHANGED(stage)", + active: true, + actions: [ + { + name: "set_probability", + type: "field_update", + field: "probability", + value: `CASE(stage, + "prospecting", 10, + "qualification", 25, + "needs_analysis", 40, + "proposal", 60, + "negotiation", 80, + "closed_won", 100, + "closed_lost", 0, + probability + )` + }, + { + name: "set_forecast_category", + type: "field_update", + field: "forecast_category", + value: `CASE(stage, + "prospecting", "pipeline", + "qualification", "pipeline", + "needs_analysis", "best_case", + "proposal", "commit", + "negotiation", "commit", + "closed_won", "closed", + "closed_lost", "omitted", + forecast_category + )` + } + ] + }, + { + name: "calculate_expected_revenue", + objectName: "opportunity", + triggerType: "on_create_or_update", + criteria: "ISCHANGED(amount) OR ISCHANGED(probability)", + active: true, + actions: [ + { + name: "update_expected_revenue", + type: "field_update", + field: "expected_revenue", + value: "amount * (probability / 100)" + } + ] + }, + { + name: "notify_on_large_deal_won", + objectName: "opportunity", + triggerType: "on_update", + criteria: 'ISCHANGED(stage) AND stage = "closed_won" AND amount > 100000', + active: true, + actions: [ + { + name: "notify_management", + type: "email_alert", + template: "large_deal_won", + recipients: ["sales_management@example.com"] + } + ] + } + ] +}); + +// ../app-crm/src/objects/product.object.ts +init_data(); +var Product = ObjectSchema3.create({ + name: "product", + label: "Product", + pluralLabel: "Products", + icon: "box", + description: "Products and services offered by the company", + titleFormat: "{product_code} - {name}", + compactLayout: ["product_code", "name", "category", "is_active"], + fields: { + // AutoNumber field - Unique product identifier + product_code: Field.autonumber({ + label: "Product Code", + format: "PRD-{0000}" + }), + // Basic Information + name: Field.text({ + label: "Product Name", + required: true, + searchable: true, + maxLength: 255 + }), + description: Field.markdown({ + label: "Description" + }), + // Categorization + category: Field.select({ + label: "Category", + options: [ + { label: "Software", value: "software", default: true }, + { label: "Hardware", value: "hardware" }, + { label: "Service", value: "service" }, + { label: "Subscription", value: "subscription" }, + { label: "Support", value: "support" } + ] + }), + family: Field.select({ + label: "Product Family", + options: [ + { label: "Enterprise Solutions", value: "enterprise" }, + { label: "SMB Solutions", value: "smb" }, + { label: "Professional Services", value: "services" }, + { label: "Cloud Services", value: "cloud" } + ] + }), + // Pricing + list_price: Field.currency({ + label: "List Price", + scale: 2, + min: 0, + required: true + }), + cost: Field.currency({ + label: "Cost", + scale: 2, + min: 0 + }), + // SKU and Inventory + sku: Field.text({ + label: "SKU", + maxLength: 50, + unique: true + }), + quantity_on_hand: Field.number({ + label: "Quantity on Hand", + min: 0, + defaultValue: 0 + }), + reorder_point: Field.number({ + label: "Reorder Point", + min: 0 + }), + // Status + is_active: Field.boolean({ + label: "Active", + defaultValue: true + }), + is_taxable: Field.boolean({ + label: "Taxable", + defaultValue: true + }), + // Relationships + product_manager: Field.lookup("user", { + label: "Product Manager" + }), + // Images and Assets + image_url: Field.url({ + label: "Product Image" + }), + datasheet_url: Field.url({ + label: "Datasheet URL" + }) + }, + // Database indexes + indexes: [ + { fields: ["name"] }, + { fields: ["sku"], unique: true }, + { fields: ["category"] }, + { fields: ["is_active"] } + ], + // Enable advanced features + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete", "search"], + files: true, + feeds: true, + trash: true, + mru: true + }, + // Validation Rules + validations: [ + { + name: "price_positive", + type: "script", + severity: "error", + message: "List Price must be positive", + condition: "list_price < 0" + }, + { + name: "cost_less_than_price", + type: "script", + severity: "warning", + message: "Cost should be less than List Price", + condition: "cost >= list_price" + } + ] +}); + +// ../app-crm/src/objects/quote.object.ts +init_data(); +var Quote = ObjectSchema3.create({ + name: "quote", + label: "Quote", + pluralLabel: "Quotes", + icon: "file-text", + description: "Price quotes for customers", + titleFormat: "{quote_number} - {name}", + compactLayout: ["quote_number", "name", "account", "status", "total_price"], + fields: { + // AutoNumber field + quote_number: Field.autonumber({ + label: "Quote Number", + format: "QTE-{0000}" + }), + // Basic Information + name: Field.text({ + label: "Quote Name", + required: true, + searchable: true, + maxLength: 255 + }), + // Relationships + account: Field.lookup("account", { + label: "Account", + required: true + }), + contact: Field.lookup("contact", { + label: "Contact", + required: true, + referenceFilters: [ + "account = {account}" + ] + }), + opportunity: Field.lookup("opportunity", { + label: "Opportunity", + referenceFilters: [ + "account = {account}" + ] + }), + owner: Field.lookup("user", { + label: "Quote Owner", + required: true + }), + // Status + status: Field.select({ + label: "Status", + options: [ + { label: "Draft", value: "draft", color: "#999999", default: true }, + { label: "In Review", value: "in_review", color: "#FFA500" }, + { label: "Presented", value: "presented", color: "#4169E1" }, + { label: "Accepted", value: "accepted", color: "#00AA00" }, + { label: "Rejected", value: "rejected", color: "#FF0000" }, + { label: "Expired", value: "expired", color: "#666666" } + ], + required: true + }), + // Dates + quote_date: Field.date({ + label: "Quote Date", + required: true, + defaultValue: "TODAY()" + }), + expiration_date: Field.date({ + label: "Expiration Date", + required: true + }), + // Pricing + subtotal: Field.currency({ + label: "Subtotal", + scale: 2, + readonly: true + }), + discount: Field.percent({ + label: "Discount %", + scale: 2, + min: 0, + max: 100 + }), + discount_amount: Field.currency({ + label: "Discount Amount", + scale: 2, + readonly: true + }), + tax: Field.currency({ + label: "Tax", + scale: 2 + }), + shipping_handling: Field.currency({ + label: "Shipping & Handling", + scale: 2 + }), + total_price: Field.currency({ + label: "Total Price", + scale: 2, + readonly: true + }), + // Terms + payment_terms: Field.select({ + label: "Payment Terms", + options: [ + { label: "Net 15", value: "net_15" }, + { label: "Net 30", value: "net_30", default: true }, + { label: "Net 60", value: "net_60" }, + { label: "Net 90", value: "net_90" }, + { label: "Due on Receipt", value: "due_on_receipt" } + ] + }), + shipping_terms: Field.text({ + label: "Shipping Terms", + maxLength: 255 + }), + // Billing & Shipping Address + billing_address: Field.address({ + label: "Billing Address", + addressFormat: "international" + }), + shipping_address: Field.address({ + label: "Shipping Address", + addressFormat: "international" + }), + // Notes + description: Field.markdown({ + label: "Description" + }), + internal_notes: Field.textarea({ + label: "Internal Notes" + }) + }, + // Database indexes + indexes: [ + { fields: ["account"] }, + { fields: ["opportunity"] }, + { fields: ["owner"] }, + { fields: ["status"] }, + { fields: ["quote_date"] } + ], + // Enable advanced features + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + apiMethods: ["get", "list", "create", "update", "delete", "search", "export"], + files: true, + feeds: true, + activities: true, + trash: true, + mru: true + }, + // Validation Rules + validations: [ + { + name: "expiration_after_quote", + type: "script", + severity: "error", + message: "Expiration Date must be after Quote Date", + condition: "expiration_date <= quote_date" + }, + { + name: "valid_discount", + type: "script", + severity: "error", + message: "Discount cannot exceed 100%", + condition: "discount > 100" + } + ], + // Workflow Rules + workflows: [ + { + name: "quote_expired_check", + objectName: "quote", + triggerType: "on_read", + criteria: 'expiration_date < TODAY() AND status NOT IN ("accepted", "rejected", "expired")', + actions: [ + { + name: "mark_expired", + type: "field_update", + field: "status", + value: '"expired"' + } + ], + active: true + } + ] +}); + +// ../app-crm/src/objects/task.object.ts +init_data(); +var Task3 = ObjectSchema3.create({ + name: "task", + label: "Task", + pluralLabel: "Tasks", + icon: "check-square", + description: "Activities and to-do items", + fields: { + // Task Information + subject: Field.text({ + label: "Subject", + required: true, + searchable: true, + maxLength: 255 + }), + description: Field.markdown({ + label: "Description" + }), + // Task Management + status: Field.select({ + label: "Status", + required: true, + options: [ + { label: "Not Started", value: "not_started", color: "#808080", default: true }, + { label: "In Progress", value: "in_progress", color: "#FFA500" }, + { label: "Waiting", value: "waiting", color: "#FFD700" }, + { label: "Completed", value: "completed", color: "#00AA00" }, + { label: "Deferred", value: "deferred", color: "#999999" } + ] + }), + priority: Field.select({ + label: "Priority", + required: true, + options: [ + { label: "Low", value: "low", color: "#4169E1", default: true }, + { label: "Normal", value: "normal", color: "#00AA00" }, + { label: "High", value: "high", color: "#FFA500" }, + { label: "Urgent", value: "urgent", color: "#FF0000" } + ] + }), + type: Field.select({ + label: "Task Type", + options: [ + { label: "Call", value: "call" }, + { label: "Email", value: "email" }, + { label: "Meeting", value: "meeting" }, + { label: "Follow-up", value: "follow_up" }, + { label: "Demo", value: "demo" }, + { label: "Other", value: "other" } + ] + }), + // Dates + due_date: Field.date({ + label: "Due Date" + }), + reminder_date: Field.datetime({ + label: "Reminder Date/Time" + }), + completed_date: Field.datetime({ + label: "Completed Date", + readonly: true + }), + // Assignment + owner: Field.lookup("user", { + label: "Assigned To", + required: true + }), + // Related To (Polymorphic relationship - can link to multiple object types) + related_to_type: Field.select({ + label: "Related To Type", + options: [ + { label: "Account", value: "account" }, + { label: "Contact", value: "contact" }, + { label: "Opportunity", value: "opportunity" }, + { label: "Lead", value: "lead" }, + { label: "Case", value: "case" } + ] + }), + related_to_account: Field.lookup("account", { + label: "Related Account" + }), + related_to_contact: Field.lookup("contact", { + label: "Related Contact" + }), + related_to_opportunity: Field.lookup("opportunity", { + label: "Related Opportunity" + }), + related_to_lead: Field.lookup("lead", { + label: "Related Lead" + }), + related_to_case: Field.lookup("case", { + label: "Related Case" + }), + // Recurrence (for recurring tasks) + is_recurring: Field.boolean({ + label: "Recurring Task", + defaultValue: false + }), + recurrence_type: Field.select({ + label: "Recurrence Type", + options: [ + { label: "Daily", value: "daily" }, + { label: "Weekly", value: "weekly" }, + { label: "Monthly", value: "monthly" }, + { label: "Yearly", value: "yearly" } + ] + }), + recurrence_interval: Field.number({ + label: "Recurrence Interval", + defaultValue: 1, + min: 1 + }), + recurrence_end_date: Field.date({ + label: "Recurrence End Date" + }), + // Flags + is_completed: Field.boolean({ + label: "Is Completed", + defaultValue: false, + readonly: true + }), + is_overdue: Field.boolean({ + label: "Is Overdue", + defaultValue: false, + readonly: true + }), + // Progress + progress_percent: Field.percent({ + label: "Progress (%)", + min: 0, + max: 100, + defaultValue: 0 + }), + // Time tracking + estimated_hours: Field.number({ + label: "Estimated Hours", + scale: 2, + min: 0 + }), + actual_hours: Field.number({ + label: "Actual Hours", + scale: 2, + min: 0 + }) + }, + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + files: true, + feeds: true, + // Enable social feed, comments, and mentions + activities: true, + // Enable tasks and events tracking + trash: true, + mru: true + // Track Most Recently Used + }, + // Database indexes for performance + indexes: [ + { fields: ["status"] }, + { fields: ["priority"] }, + { fields: ["owner"] }, + { fields: ["due_date"] } + ], + titleFormat: "{subject}", + compactLayout: ["subject", "status", "priority", "due_date", "owner"], + // Removed: list_views and form_views belong in UI configuration, not object definition + validations: [ + { + name: "completed_date_required", + type: "script", + severity: "error", + message: "Completed date is required when status is Completed", + condition: 'status = "completed" AND ISBLANK(completed_date)' + }, + { + name: "recurrence_fields_required", + type: "script", + severity: "error", + message: "Recurrence type is required for recurring tasks", + condition: "is_recurring = true AND ISBLANK(recurrence_type)" + }, + { + name: "related_to_required", + type: "script", + severity: "warning", + message: "At least one related record should be selected", + condition: "ISBLANK(related_to_account) AND ISBLANK(related_to_contact) AND ISBLANK(related_to_opportunity) AND ISBLANK(related_to_lead) AND ISBLANK(related_to_case)" + } + ], + workflows: [ + { + name: "set_completed_flag", + objectName: "task", + triggerType: "on_create_or_update", + criteria: "ISCHANGED(status)", + active: true, + actions: [ + { + name: "update_completed_flag", + type: "field_update", + field: "is_completed", + value: 'status = "completed"' + } + ] + }, + { + name: "set_completed_date", + objectName: "task", + triggerType: "on_update", + criteria: 'ISCHANGED(status) AND status = "completed"', + active: true, + actions: [ + { + name: "set_date", + type: "field_update", + field: "completed_date", + value: "NOW()" + }, + { + name: "set_progress", + type: "field_update", + field: "progress_percent", + value: "100" + } + ] + }, + { + name: "check_overdue", + objectName: "task", + triggerType: "on_create_or_update", + criteria: "due_date < TODAY() AND is_completed = false", + active: true, + actions: [ + { + name: "set_overdue_flag", + type: "field_update", + field: "is_overdue", + value: "true" + } + ] + }, + { + name: "notify_on_urgent", + objectName: "task", + triggerType: "on_create_or_update", + criteria: 'priority = "urgent" AND is_completed = false', + active: true, + actions: [ + { + name: "email_owner", + type: "email_alert", + template: "urgent_task_alert", + recipients: ["{owner.email}"] + } + ] + } + ] +}); + +// ../app-crm/src/apis/index.ts +var apis_exports = {}; +__export(apis_exports, { + LeadConvertApi: () => LeadConvertApi, + PipelineStatsApi: () => PipelineStatsApi +}); + +// ../app-crm/src/apis/lead-convert.api.ts +var LeadConvertApi = ApiEndpoint.create({ + name: "lead_convert", + path: "/api/v1/crm/leads/convert", + method: "POST", + summary: "Convert Lead to Account/Contact", + type: "flow", + target: "flow_lead_conversion_v2", + inputMapping: [ + { source: "body.leadId", target: "leadRecordId" }, + { source: "body.ownerId", target: "newOwnerId" } + ] +}); + +// ../app-crm/src/apis/pipeline-stats.api.ts +var PipelineStatsApi = ApiEndpoint.create({ + name: "get_pipeline_stats", + path: "/api/v1/crm/stats/pipeline", + method: "GET", + summary: "Get Pipeline Statistics", + description: "Returns the total value of open opportunities grouped by stage", + type: "script", + target: "server/scripts/pipeline_stats.ts", + authRequired: true, + cacheTtl: 300 +}); + +// ../app-crm/src/actions/index.ts +var actions_exports = {}; +__export(actions_exports, { + CloneOpportunityAction: () => CloneOpportunityAction, + CloseCaseAction: () => CloseCaseAction, + ConvertLeadAction: () => ConvertLeadAction, + CreateCampaignAction: () => CreateCampaignAction, + EscalateCaseAction: () => EscalateCaseAction, + ExportToCsvAction: () => ExportToCsvAction, + LogCallAction: () => LogCallAction, + MarkPrimaryContactAction: () => MarkPrimaryContactAction, + MassUpdateStageAction: () => MassUpdateStageAction, + SendEmailAction: () => SendEmailAction +}); + +// ../app-crm/src/actions/case.actions.ts +var EscalateCaseAction = { + name: "escalate_case", + label: "Escalate Case", + objectName: "case", + icon: "alert-triangle", + type: "modal", + target: "escalate_case_modal", + locations: ["record_header", "list_item"], + visible: "is_escalated = false AND is_closed = false", + params: [ + { + name: "reason", + label: "Escalation Reason", + type: "textarea", + required: true + } + ], + confirmText: "This will escalate the case to the escalation team. Continue?", + successMessage: "Case escalated successfully!", + refreshAfter: true +}; +var CloseCaseAction = { + name: "close_case", + label: "Close Case", + objectName: "case", + icon: "check-circle", + type: "modal", + target: "close_case_modal", + locations: ["record_header"], + visible: "is_closed = false", + params: [ + { + name: "resolution", + label: "Resolution", + type: "textarea", + required: true + } + ], + confirmText: "Are you sure you want to close this case?", + successMessage: "Case closed successfully!", + refreshAfter: true +}; + +// ../app-crm/src/actions/contact.actions.ts +var MarkPrimaryContactAction = { + name: "mark_primary", + label: "Mark as Primary Contact", + objectName: "contact", + icon: "star", + type: "script", + target: "markAsPrimaryContact", + locations: ["record_header", "list_item"], + visible: "is_primary = false", + confirmText: "Mark this contact as the primary contact for the account?", + successMessage: "Contact marked as primary!", + refreshAfter: true +}; +var SendEmailAction = { + name: "send_email", + label: "Send Email", + objectName: "contact", + icon: "mail", + type: "modal", + target: "email_composer", + locations: ["record_header", "list_item"], + visible: "email_opt_out = false", + refreshAfter: false +}; + +// ../app-crm/src/actions/global.actions.ts +var LogCallAction = { + name: "log_call", + label: "Log a Call", + icon: "phone", + type: "modal", + target: "call_log_modal", + locations: ["record_header", "list_item", "record_related"], + params: [ + { + name: "subject", + label: "Call Subject", + type: "text", + required: true + }, + { + name: "duration", + label: "Duration (minutes)", + type: "number", + required: true + }, + { + name: "notes", + label: "Call Notes", + type: "textarea", + required: false + } + ], + successMessage: "Call logged successfully!", + refreshAfter: true +}; +var ExportToCsvAction = { + name: "export_csv", + label: "Export to CSV", + icon: "download", + type: "script", + target: "exportToCSV", + locations: ["list_toolbar"], + successMessage: "Export completed!", + refreshAfter: false +}; + +// ../app-crm/src/actions/lead.actions.ts +var ConvertLeadAction = { + name: "convert_lead", + label: "Convert Lead", + objectName: "lead", + icon: "arrow-right-circle", + type: "flow", + target: "lead_conversion", + locations: ["record_header", "list_item"], + visible: 'status = "qualified" AND is_converted = false', + confirmText: "Are you sure you want to convert this lead?", + successMessage: "Lead converted successfully!", + refreshAfter: true +}; +var CreateCampaignAction = { + name: "create_campaign", + label: "Add to Campaign", + objectName: "lead", + icon: "send", + type: "modal", + target: "add_to_campaign_modal", + locations: ["list_toolbar"], + params: [ + { + name: "campaign", + label: "Campaign", + type: "lookup", + required: true + } + ], + successMessage: "Leads added to campaign!", + refreshAfter: true +}; + +// ../app-crm/src/actions/opportunity.actions.ts +var CloneOpportunityAction = { + name: "clone_opportunity", + label: "Clone Opportunity", + objectName: "opportunity", + icon: "copy", + type: "script", + target: "cloneRecord", + locations: ["record_header", "record_more"], + successMessage: "Opportunity cloned successfully!", + refreshAfter: true +}; +var MassUpdateStageAction = { + name: "mass_update_stage", + label: "Update Stage", + objectName: "opportunity", + icon: "layers", + type: "modal", + target: "mass_update_stage_modal", + locations: ["list_toolbar"], + params: [ + { + name: "stage", + label: "New Stage", + type: "select", + required: true, + options: [ + { label: "Prospecting", value: "prospecting" }, + { label: "Qualification", value: "qualification" }, + { label: "Needs Analysis", value: "needs_analysis" }, + { label: "Proposal", value: "proposal" }, + { label: "Negotiation", value: "negotiation" }, + { label: "Closed Won", value: "closed_won" }, + { label: "Closed Lost", value: "closed_lost" } + ] + } + ], + successMessage: "Opportunities updated successfully!", + refreshAfter: true +}; + +// ../app-crm/src/dashboards/index.ts +var dashboards_exports = {}; +__export(dashboards_exports, { + ExecutiveDashboard: () => ExecutiveDashboard, + SalesDashboard: () => SalesDashboard, + ServiceDashboard: () => ServiceDashboard +}); + +// ../app-crm/src/dashboards/executive.dashboard.ts +var ExecutiveDashboard = { + name: "executive_dashboard", + label: "Executive Overview", + description: "High-level business metrics", + widgets: [ + // Row 1: Revenue Metrics + { + id: "total_revenue_ytd", + title: "Total Revenue (YTD)", + type: "metric", + object: "opportunity", + filter: { stage: "closed_won", close_date: { $gte: "{current_year_start}" } }, + valueField: "amount", + aggregate: "sum", + layout: { x: 0, y: 0, w: 3, h: 2 }, + options: { prefix: "$", color: "#00AA00" } + }, + { + id: "total_accounts", + title: "Total Accounts", + type: "metric", + object: "account", + filter: { is_active: true }, + aggregate: "count", + layout: { x: 3, y: 0, w: 3, h: 2 }, + options: { color: "#4169E1" } + }, + { + id: "total_contacts", + title: "Total Contacts", + type: "metric", + object: "contact", + aggregate: "count", + layout: { x: 6, y: 0, w: 3, h: 2 }, + options: { color: "#9370DB" } + }, + { + id: "total_leads", + title: "Total Leads", + type: "metric", + object: "lead", + filter: { is_converted: false }, + aggregate: "count", + layout: { x: 9, y: 0, w: 3, h: 2 }, + options: { color: "#FFA500" } + }, + // Row 2: Revenue Analysis + { + id: "revenue_by_industry", + title: "Revenue by Industry", + type: "bar", + object: "opportunity", + filter: { stage: "closed_won", close_date: { $gte: "{current_year_start}" } }, + categoryField: "account.industry", + valueField: "amount", + aggregate: "sum", + layout: { x: 0, y: 2, w: 6, h: 4 } + }, + { + id: "quarterly_revenue_trend", + title: "Quarterly Revenue Trend", + type: "line", + object: "opportunity", + filter: { stage: "closed_won", close_date: { $gte: "{last_4_quarters}" } }, + categoryField: "close_date", + valueField: "amount", + aggregate: "sum", + layout: { x: 6, y: 2, w: 6, h: 4 }, + options: { dateGranularity: "quarter" } + }, + // Row 3: Customer & Activity Metrics + { + id: "new_accounts_by_month", + title: "New Accounts by Month", + type: "bar", + object: "account", + filter: { created_date: { $gte: "{last_6_months}" } }, + categoryField: "created_date", + aggregate: "count", + layout: { x: 0, y: 6, w: 4, h: 4 }, + options: { dateGranularity: "month" } + }, + { + id: "lead_conversion_rate", + title: "Lead Conversion Rate", + type: "metric", + object: "lead", + valueField: "is_converted", + aggregate: "avg", + layout: { x: 4, y: 6, w: 4, h: 4 }, + options: { suffix: "%", color: "#00AA00" } + }, + { + id: "top_accounts_by_revenue", + title: "Top Accounts by Revenue", + type: "table", + object: "account", + aggregate: "count", + layout: { x: 8, y: 6, w: 4, h: 4 }, + options: { + columns: ["name", "annual_revenue", "type"], + sortBy: "annual_revenue", + sortOrder: "desc", + limit: 10 + } + } + ] +}; + +// ../app-crm/src/dashboards/sales.dashboard.ts +var SalesDashboard = { + name: "sales_dashboard", + label: "Sales Performance", + description: "Key sales metrics and pipeline overview", + widgets: [ + // Row 1: Key Metrics + { + id: "total_pipeline_value", + title: "Total Pipeline Value", + type: "metric", + object: "opportunity", + filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, + valueField: "amount", + aggregate: "sum", + layout: { x: 0, y: 0, w: 3, h: 2 }, + options: { prefix: "$", color: "#4169E1" } + }, + { + id: "closed_won_this_quarter", + title: "Closed Won This Quarter", + type: "metric", + object: "opportunity", + filter: { stage: "closed_won", close_date: { $gte: "{current_quarter_start}" } }, + valueField: "amount", + aggregate: "sum", + layout: { x: 3, y: 0, w: 3, h: 2 }, + options: { prefix: "$", color: "#00AA00" } + }, + { + id: "open_opportunities", + title: "Open Opportunities", + type: "metric", + object: "opportunity", + filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, + aggregate: "count", + layout: { x: 6, y: 0, w: 3, h: 2 }, + options: { color: "#FFA500" } + }, + { + id: "win_rate", + title: "Win Rate", + type: "metric", + object: "opportunity", + filter: { close_date: { $gte: "{current_quarter_start}" } }, + valueField: "stage", + aggregate: "count", + layout: { x: 9, y: 0, w: 3, h: 2 }, + options: { suffix: "%", color: "#9370DB" } + }, + // Row 2: Pipeline Analysis + { + id: "pipeline_by_stage", + title: "Pipeline by Stage", + type: "funnel", + object: "opportunity", + filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, + categoryField: "stage", + valueField: "amount", + aggregate: "sum", + layout: { x: 0, y: 2, w: 6, h: 4 }, + options: { showValues: true } + }, + { + id: "opportunities_by_owner", + title: "Opportunities by Owner", + type: "bar", + object: "opportunity", + filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, + categoryField: "owner", + valueField: "amount", + aggregate: "sum", + layout: { x: 6, y: 2, w: 6, h: 4 }, + options: { horizontal: true } + }, + // Row 3: Trends + { + id: "monthly_revenue_trend", + title: "Monthly Revenue Trend", + type: "line", + object: "opportunity", + filter: { stage: "closed_won", close_date: { $gte: "{last_12_months}" } }, + categoryField: "close_date", + valueField: "amount", + aggregate: "sum", + layout: { x: 0, y: 6, w: 8, h: 4 }, + options: { dateGranularity: "month", showTrend: true } + }, + { + id: "top_opportunities", + title: "Top Opportunities", + type: "table", + object: "opportunity", + filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, + aggregate: "count", + layout: { x: 8, y: 6, w: 4, h: 4 }, + options: { + columns: ["name", "amount", "stage", "close_date"], + sortBy: "amount", + sortOrder: "desc", + limit: 10 + } + } + ] +}; + +// ../app-crm/src/dashboards/service.dashboard.ts +var ServiceDashboard = { + name: "service_dashboard", + label: "Customer Service", + description: "Support case metrics and performance", + widgets: [ + // Row 1: Key Metrics + { + id: "open_cases", + title: "Open Cases", + type: "metric", + object: "case", + filter: { is_closed: false }, + aggregate: "count", + layout: { x: 0, y: 0, w: 3, h: 2 }, + options: { color: "#FFA500" } + }, + { + id: "critical_cases", + title: "Critical Cases", + type: "metric", + object: "case", + filter: { priority: "critical", is_closed: false }, + aggregate: "count", + layout: { x: 3, y: 0, w: 3, h: 2 }, + options: { color: "#FF0000" } + }, + { + id: "avg_resolution_time", + title: "Avg Resolution Time (hrs)", + type: "metric", + object: "case", + filter: { is_closed: true }, + valueField: "resolution_time_hours", + aggregate: "avg", + layout: { x: 6, y: 0, w: 3, h: 2 }, + options: { suffix: "h", color: "#4169E1" } + }, + { + id: "sla_violations", + title: "SLA Violations", + type: "metric", + object: "case", + filter: { is_sla_violated: true }, + aggregate: "count", + layout: { x: 9, y: 0, w: 3, h: 2 }, + options: { color: "#FF4500" } + }, + // Row 2: Case Distribution + { + id: "cases_by_status", + title: "Cases by Status", + type: "pie", + object: "case", + filter: { is_closed: false }, + categoryField: "status", + aggregate: "count", + layout: { x: 0, y: 2, w: 4, h: 4 }, + options: { showLegend: true } + }, + { + id: "cases_by_priority", + title: "Cases by Priority", + type: "pie", + object: "case", + filter: { is_closed: false }, + categoryField: "priority", + aggregate: "count", + layout: { x: 4, y: 2, w: 4, h: 4 }, + options: { showLegend: true } + }, + { + id: "cases_by_origin", + title: "Cases by Origin", + type: "bar", + object: "case", + categoryField: "origin", + aggregate: "count", + layout: { x: 8, y: 2, w: 4, h: 4 } + }, + // Row 3: Trends and Lists + { + id: "daily_case_volume", + title: "Daily Case Volume", + type: "line", + object: "case", + filter: { created_date: { $gte: "{last_30_days}" } }, + categoryField: "created_date", + aggregate: "count", + layout: { x: 0, y: 6, w: 8, h: 4 }, + options: { dateGranularity: "day" } + }, + { + id: "my_open_cases", + title: "My Open Cases", + type: "table", + object: "case", + filter: { owner: "{current_user}", is_closed: false }, + aggregate: "count", + layout: { x: 8, y: 6, w: 4, h: 4 }, + options: { + columns: ["case_number", "subject", "priority", "status"], + sortBy: "priority", + sortOrder: "desc", + limit: 10 + } + } + ] +}; + +// ../app-crm/src/reports/index.ts +var reports_exports = {}; +__export(reports_exports, { + AccountsByIndustryTypeReport: () => AccountsByIndustryTypeReport, + CasesByStatusPriorityReport: () => CasesByStatusPriorityReport, + ContactsByAccountReport: () => ContactsByAccountReport, + LeadsBySourceReport: () => LeadsBySourceReport, + OpportunitiesByStageReport: () => OpportunitiesByStageReport, + SlaPerformanceReport: () => SlaPerformanceReport, + TasksByOwnerReport: () => TasksByOwnerReport, + WonOpportunitiesByOwnerReport: () => WonOpportunitiesByOwnerReport +}); + +// ../app-crm/src/reports/account.report.ts +var AccountsByIndustryTypeReport = { + name: "accounts_by_industry_type", + label: "Accounts by Industry and Type", + description: "Matrix report showing accounts by industry and type", + objectName: "account", + type: "matrix", + columns: [ + { field: "name", aggregate: "count" }, + { field: "annual_revenue", aggregate: "sum" } + ], + groupingsDown: [{ field: "industry", sortOrder: "asc" }], + groupingsAcross: [{ field: "type", sortOrder: "asc" }], + filter: { is_active: true } +}; + +// ../app-crm/src/reports/case.report.ts +var CasesByStatusPriorityReport = { + name: "cases_by_status_priority", + label: "Cases by Status and Priority", + description: "Summary of cases by status and priority", + objectName: "case", + type: "summary", + columns: [ + { field: "case_number", label: "Case Number" }, + { field: "subject", label: "Subject" }, + { field: "account", label: "Account" }, + { field: "owner", label: "Owner" }, + { field: "resolution_time_hours", label: "Resolution Time", aggregate: "avg" } + ], + groupingsDown: [ + { field: "status", sortOrder: "asc" }, + { field: "priority", sortOrder: "desc" } + ], + chart: { type: "bar", title: "Cases by Status", showLegend: true, xAxis: "status", yAxis: "case_number" } +}; +var SlaPerformanceReport = { + name: "sla_performance", + label: "SLA Performance Report", + description: "Analysis of SLA compliance", + objectName: "case", + type: "summary", + columns: [ + { field: "case_number", aggregate: "count" }, + { field: "is_sla_violated", label: "SLA Violated", aggregate: "count" }, + { field: "resolution_time_hours", label: "Avg Resolution Time", aggregate: "avg" } + ], + groupingsDown: [{ field: "priority", sortOrder: "desc" }], + filter: { is_closed: true }, + chart: { type: "column", title: "SLA Violations by Priority", showLegend: false, xAxis: "priority", yAxis: "is_sla_violated" } +}; + +// ../app-crm/src/reports/contact.report.ts +var ContactsByAccountReport = { + name: "contacts_by_account", + label: "Contacts by Account", + description: "List of contacts grouped by account", + objectName: "contact", + type: "summary", + columns: [ + { field: "full_name", label: "Name" }, + { field: "title", label: "Title" }, + { field: "email", label: "Email" }, + { field: "phone", label: "Phone" }, + { field: "is_primary", label: "Primary Contact" } + ], + groupingsDown: [{ field: "account", sortOrder: "asc" }] +}; + +// ../app-crm/src/reports/lead.report.ts +var LeadsBySourceReport = { + name: "leads_by_source", + label: "Leads by Source and Status", + description: "Lead pipeline analysis", + objectName: "lead", + type: "summary", + columns: [ + { field: "full_name", label: "Name" }, + { field: "company", label: "Company" }, + { field: "rating", label: "Rating" } + ], + groupingsDown: [ + { field: "lead_source", sortOrder: "asc" }, + { field: "status", sortOrder: "asc" } + ], + filter: { is_converted: false }, + chart: { type: "pie", title: "Leads by Source", showLegend: true, xAxis: "lead_source", yAxis: "full_name" } +}; + +// ../app-crm/src/reports/opportunity.report.ts +var OpportunitiesByStageReport = { + name: "opportunities_by_stage", + label: "Opportunities by Stage", + description: "Summary of opportunities grouped by stage", + objectName: "opportunity", + type: "summary", + columns: [ + { field: "name", label: "Opportunity Name" }, + { field: "account", label: "Account" }, + { field: "amount", label: "Amount", aggregate: "sum" }, + { field: "close_date", label: "Close Date" }, + { field: "probability", label: "Probability", aggregate: "avg" } + ], + groupingsDown: [{ field: "stage", sortOrder: "asc" }], + filter: { stage: { $ne: "closed_lost" }, close_date: { $gte: "{current_year_start}" } }, + chart: { type: "bar", title: "Pipeline by Stage", showLegend: true, xAxis: "stage", yAxis: "amount" } +}; +var WonOpportunitiesByOwnerReport = { + name: "won_opportunities_by_owner", + label: "Won Opportunities by Owner", + description: "Closed won opportunities grouped by owner", + objectName: "opportunity", + type: "summary", + columns: [ + { field: "name", label: "Opportunity Name" }, + { field: "account", label: "Account" }, + { field: "amount", label: "Amount", aggregate: "sum" }, + { field: "close_date", label: "Close Date" } + ], + groupingsDown: [{ field: "owner", sortOrder: "desc" }], + filter: { stage: "closed_won" }, + chart: { type: "column", title: "Revenue by Sales Rep", showLegend: false, xAxis: "owner", yAxis: "amount" } +}; + +// ../app-crm/src/reports/task.report.ts +var TasksByOwnerReport = { + name: "tasks_by_owner", + label: "Tasks by Owner", + description: "Task summary by owner", + objectName: "task", + type: "summary", + columns: [ + { field: "subject", label: "Subject" }, + { field: "status", label: "Status" }, + { field: "priority", label: "Priority" }, + { field: "due_date", label: "Due Date" }, + { field: "actual_hours", label: "Hours", aggregate: "sum" } + ], + groupingsDown: [{ field: "owner", sortOrder: "asc" }], + filter: { is_completed: false } +}; + +// ../app-crm/src/flows/campaign-enrollment.flow.ts +var CampaignEnrollmentFlow = { + name: "campaign_enrollment", + label: "Enroll Leads in Campaign", + description: "Bulk enroll leads into marketing campaigns", + type: "schedule", + variables: [ + { name: "campaignId", type: "text", isInput: true, isOutput: false }, + { name: "leadStatus", type: "text", isInput: true, isOutput: false } + ], + nodes: [ + { id: "start", type: "start", label: "Start (Monday 9 AM)", config: { schedule: "0 9 * * 1" } }, + { + id: "get_campaign", + type: "get_record", + label: "Get Campaign", + config: { objectName: "campaign", filter: { id: "{campaignId}" }, outputVariable: "campaignRecord" } + }, + { + id: "query_leads", + type: "get_record", + label: "Find Eligible Leads", + config: { objectName: "lead", filter: { status: "{leadStatus}", is_converted: false, email: { $ne: null } }, limit: 1e3, outputVariable: "leadList" } + }, + { + id: "loop_leads", + type: "loop", + label: "Process Each Lead", + config: { collection: "{leadList}", iteratorVariable: "currentLead" } + }, + { + id: "create_campaign_member", + type: "create_record", + label: "Add to Campaign", + config: { + objectName: "campaign_member", + fields: { campaign: "{campaignId}", lead: "{currentLead.id}", status: "sent", added_date: "{NOW()}" } + } + }, + { + id: "update_campaign_stats", + type: "update_record", + label: "Update Campaign Stats", + config: { objectName: "campaign", filter: { id: "{campaignId}" }, fields: { num_sent: "{leadList.length}" } } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "get_campaign", type: "default" }, + { id: "e2", source: "get_campaign", target: "query_leads", type: "default" }, + { id: "e3", source: "query_leads", target: "loop_leads", type: "default" }, + { id: "e4", source: "loop_leads", target: "create_campaign_member", type: "default" }, + { id: "e5", source: "create_campaign_member", target: "update_campaign_stats", type: "default" }, + { id: "e6", source: "update_campaign_stats", target: "end", type: "default" } + ] +}; + +// ../app-crm/src/flows/case-escalation.flow.ts +var CaseEscalationFlow = { + name: "case_escalation", + label: "Case Escalation Process", + description: "Automatically escalate high-priority cases", + type: "record_change", + variables: [ + { name: "caseId", type: "text", isInput: true, isOutput: false } + ], + nodes: [ + { + id: "start", + type: "start", + label: "Start", + config: { objectName: "case", criteria: 'priority = "critical" OR (priority = "high" AND account.type = "customer")' } + }, + { + id: "get_case", + type: "get_record", + label: "Get Case Record", + config: { objectName: "case", filter: { id: "{caseId}" }, outputVariable: "caseRecord" } + }, + { + id: "assign_senior_agent", + type: "update_record", + label: "Assign to Senior Agent", + config: { + objectName: "case", + filter: { id: "{caseId}" }, + fields: { owner: "{caseRecord.owner.manager}", is_escalated: true, escalated_date: "{NOW()}" } + } + }, + { + id: "create_task", + type: "create_record", + label: "Create Follow-up Task", + config: { + objectName: "task", + fields: { + subject: "Follow up on escalated case: {caseRecord.case_number}", + related_to: "{caseId}", + owner: "{caseRecord.owner}", + priority: "high", + status: "not_started", + due_date: "{TODAY() + 1}" + } + } + }, + { + id: "notify_team", + type: "script", + label: "Notify Support Team", + config: { + actionType: "email", + template: "case_escalated", + recipients: ["{caseRecord.owner}", "{caseRecord.owner.manager}", "support-team@example.com"], + variables: { + caseNumber: "{caseRecord.case_number}", + priority: "{caseRecord.priority}", + accountName: "{caseRecord.account.name}" + } + } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "get_case", type: "default" }, + { id: "e2", source: "get_case", target: "assign_senior_agent", type: "default" }, + { id: "e3", source: "assign_senior_agent", target: "create_task", type: "default" }, + { id: "e4", source: "create_task", target: "notify_team", type: "default" }, + { id: "e5", source: "notify_team", target: "end", type: "default" } + ] +}; + +// ../app-crm/src/flows/lead-conversion.flow.ts +var LeadConversionFlow = { + name: "lead_conversion", + label: "Lead Conversion Process", + description: "Automated flow to convert qualified leads to accounts, contacts, and opportunities", + type: "screen", + variables: [ + { name: "leadId", type: "text", isInput: true, isOutput: false }, + { name: "createOpportunity", type: "boolean", isInput: true, isOutput: false }, + { name: "opportunityName", type: "text", isInput: true, isOutput: false }, + { name: "opportunityAmount", type: "text", isInput: true, isOutput: false } + ], + nodes: [ + { id: "start", type: "start", label: "Start", config: { objectName: "lead" } }, + { + id: "screen_1", + type: "screen", + label: "Conversion Details", + config: { + fields: [ + { name: "createOpportunity", label: "Create Opportunity?", type: "boolean", required: true }, + { name: "opportunityName", label: "Opportunity Name", type: "text", required: true, visibleWhen: "{createOpportunity} == true" }, + { name: "opportunityAmount", label: "Opportunity Amount", type: "currency", visibleWhen: "{createOpportunity} == true" } + ] + } + }, + { + id: "get_lead", + type: "get_record", + label: "Get Lead Record", + config: { objectName: "lead", filter: { id: "{leadId}" }, outputVariable: "leadRecord" } + }, + { + id: "create_account", + type: "create_record", + label: "Create Account", + config: { + objectName: "account", + fields: { + name: "{leadRecord.company}", + phone: "{leadRecord.phone}", + website: "{leadRecord.website}", + industry: "{leadRecord.industry}", + annual_revenue: "{leadRecord.annual_revenue}", + number_of_employees: "{leadRecord.number_of_employees}", + billing_address: "{leadRecord.address}", + owner: "{$User.Id}", + is_active: true + }, + outputVariable: "accountId" + } + }, + { + id: "create_contact", + type: "create_record", + label: "Create Contact", + config: { + objectName: "contact", + fields: { + first_name: "{leadRecord.first_name}", + last_name: "{leadRecord.last_name}", + email: "{leadRecord.email}", + phone: "{leadRecord.phone}", + title: "{leadRecord.title}", + account: "{accountId}", + is_primary: true, + owner: "{$User.Id}" + }, + outputVariable: "contactId" + } + }, + { + id: "decision_opportunity", + type: "decision", + label: "Create Opportunity?", + config: { condition: "{createOpportunity} == true" } + }, + { + id: "create_opportunity", + type: "create_record", + label: "Create Opportunity", + config: { + objectName: "opportunity", + fields: { + name: "{opportunityName}", + account: "{accountId}", + contact: "{contactId}", + amount: "{opportunityAmount}", + stage: "prospecting", + probability: 10, + lead_source: "{leadRecord.lead_source}", + close_date: "{TODAY() + 90}", + owner: "{$User.Id}" + }, + outputVariable: "opportunityId" + } + }, + { + id: "mark_converted", + type: "update_record", + label: "Mark Lead as Converted", + config: { + objectName: "lead", + filter: { id: "{leadId}" }, + fields: { + is_converted: true, + converted_date: "{NOW()}", + converted_account: "{accountId}", + converted_contact: "{contactId}", + converted_opportunity: "{opportunityId}" + } + } + }, + { + id: "send_notification", + type: "script", + label: "Send Confirmation Email", + config: { + actionType: "email", + template: "lead_converted_notification", + recipients: ["{$User.Email}"], + variables: { leadName: "{leadRecord.full_name}", accountName: "{accountId.name}", contactName: "{contactId.full_name}" } + } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "screen_1", type: "default" }, + { id: "e2", source: "screen_1", target: "get_lead", type: "default" }, + { id: "e3", source: "get_lead", target: "create_account", type: "default" }, + { id: "e4", source: "create_account", target: "create_contact", type: "default" }, + { id: "e5", source: "create_contact", target: "decision_opportunity", type: "default" }, + { id: "e6", source: "decision_opportunity", target: "create_opportunity", type: "default", condition: "{createOpportunity} == true", label: "Yes" }, + { id: "e7", source: "decision_opportunity", target: "mark_converted", type: "default", condition: "{createOpportunity} != true", label: "No" }, + { id: "e8", source: "create_opportunity", target: "mark_converted", type: "default" }, + { id: "e9", source: "mark_converted", target: "send_notification", type: "default" }, + { id: "e10", source: "send_notification", target: "end", type: "default" } + ] +}; + +// ../app-crm/src/flows/opportunity-approval.flow.ts +var OpportunityApprovalFlow = { + name: "opportunity_approval", + label: "Large Deal Approval", + description: "Approval process for opportunities over $100K", + type: "record_change", + variables: [ + { name: "opportunityId", type: "text", isInput: true, isOutput: false } + ], + nodes: [ + { + id: "start", + type: "start", + label: "Start", + config: { objectName: "opportunity", criteria: 'amount > 100000 AND stage = "proposal"' } + }, + { + id: "get_opportunity", + type: "get_record", + label: "Get Opportunity", + config: { objectName: "opportunity", filter: { id: "{opportunityId}" }, outputVariable: "oppRecord" } + }, + { + id: "approval_step_manager", + type: "connector_action", + label: "Sales Manager Approval", + config: { + actionType: "approval", + approver: "{oppRecord.owner.manager}", + emailTemplate: "opportunity_approval_request", + comments: "required" + } + }, + { + id: "decision_manager", + type: "decision", + label: "Manager Approved?", + config: { condition: '{approval_step_manager.result} == "approved"' } + }, + { + id: "approval_step_director", + type: "connector_action", + label: "Sales Director Approval", + config: { + actionType: "approval", + approver: "{oppRecord.owner.manager.manager}", + emailTemplate: "opportunity_approval_request" + } + }, + { + id: "decision_director", + type: "decision", + label: "Director Approved?", + config: { condition: '{approval_step_director.result} == "approved"' } + }, + { + id: "mark_approved", + type: "update_record", + label: "Mark as Approved", + config: { + objectName: "opportunity", + filter: { id: "{opportunityId}" }, + fields: { approval_status: "approved", approved_date: "{NOW()}" } + } + }, + { + id: "notify_approval", + type: "script", + label: "Send Approval Notification", + config: { actionType: "email", template: "opportunity_approved", recipients: ["{oppRecord.owner}"] } + }, + { + id: "notify_rejection", + type: "script", + label: "Send Rejection Notification", + config: { actionType: "email", template: "opportunity_rejected", recipients: ["{oppRecord.owner}"] } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "get_opportunity", type: "default" }, + { id: "e2", source: "get_opportunity", target: "approval_step_manager", type: "default" }, + { id: "e3", source: "approval_step_manager", target: "decision_manager", type: "default" }, + { id: "e4", source: "decision_manager", target: "approval_step_director", type: "default", condition: '{approval_step_manager.result} == "approved"', label: "Approved" }, + { id: "e5", source: "decision_manager", target: "notify_rejection", type: "default", condition: '{approval_step_manager.result} != "approved"', label: "Rejected" }, + { id: "e6", source: "approval_step_director", target: "decision_director", type: "default" }, + { id: "e7", source: "decision_director", target: "mark_approved", type: "default", condition: '{approval_step_director.result} == "approved"', label: "Approved" }, + { id: "e8", source: "decision_director", target: "notify_rejection", type: "default", condition: '{approval_step_director.result} != "approved"', label: "Rejected" }, + { id: "e9", source: "mark_approved", target: "notify_approval", type: "default" }, + { id: "e10", source: "notify_approval", target: "end", type: "default" }, + { id: "e11", source: "notify_rejection", target: "end", type: "default" } + ] +}; + +// ../app-crm/src/flows/quote-generation.flow.ts +var QuoteGenerationFlow = { + name: "quote_generation", + label: "Generate Quote from Opportunity", + description: "Create a quote based on opportunity details", + type: "screen", + variables: [ + { name: "opportunityId", type: "text", isInput: true, isOutput: false }, + { name: "quoteName", type: "text", isInput: true, isOutput: false }, + { name: "expirationDays", type: "number", isInput: true, isOutput: false }, + { name: "discount", type: "number", isInput: true, isOutput: false } + ], + nodes: [ + { id: "start", type: "start", label: "Start", config: { objectName: "opportunity" } }, + { + id: "screen_1", + type: "screen", + label: "Quote Details", + config: { + fields: [ + { name: "quoteName", label: "Quote Name", type: "text", required: true }, + { name: "expirationDays", label: "Valid For (Days)", type: "number", required: true, defaultValue: 30 }, + { name: "discount", label: "Discount %", type: "percent", defaultValue: 0 } + ] + } + }, + { + id: "get_opportunity", + type: "get_record", + label: "Get Opportunity", + config: { objectName: "opportunity", filter: { id: "{opportunityId}" }, outputVariable: "oppRecord" } + }, + { + id: "create_quote", + type: "create_record", + label: "Create Quote", + config: { + objectName: "quote", + fields: { + name: "{quoteName}", + opportunity: "{opportunityId}", + account: "{oppRecord.account}", + contact: "{oppRecord.contact}", + owner: "{$User.Id}", + status: "draft", + quote_date: "{TODAY()}", + expiration_date: "{TODAY() + expirationDays}", + subtotal: "{oppRecord.amount}", + discount: "{discount}", + discount_amount: "{oppRecord.amount * (discount / 100)}", + total_price: "{oppRecord.amount * (1 - discount / 100)}", + payment_terms: "net_30" + }, + outputVariable: "quoteId" + } + }, + { + id: "update_opportunity", + type: "update_record", + label: "Update Opportunity", + config: { + objectName: "opportunity", + filter: { id: "{opportunityId}" }, + fields: { stage: "proposal", last_activity_date: "{TODAY()}" } + } + }, + { + id: "notify_owner", + type: "script", + label: "Send Notification", + config: { + actionType: "email", + template: "quote_created", + recipients: ["{$User.Email}"], + variables: { quoteName: "{quoteName}", quoteId: "{quoteId}" } + } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "screen_1", type: "default" }, + { id: "e2", source: "screen_1", target: "get_opportunity", type: "default" }, + { id: "e3", source: "get_opportunity", target: "create_quote", type: "default" }, + { id: "e4", source: "create_quote", target: "update_opportunity", type: "default" }, + { id: "e5", source: "update_opportunity", target: "notify_owner", type: "default" }, + { id: "e6", source: "notify_owner", target: "end", type: "default" } + ] +}; + +// ../app-crm/src/flows/index.ts +var allFlows = [ + CampaignEnrollmentFlow, + CaseEscalationFlow, + LeadConversionFlow, + OpportunityApprovalFlow, + QuoteGenerationFlow +]; + +// ../app-crm/src/agents/email-campaign.agent.ts +var EmailCampaignAgent = { + name: "email_campaign", + label: "Email Campaign Agent", + role: "creator", + instructions: `You are an email marketing AI that creates and optimizes email campaigns. + +Your responsibilities: +1. Write compelling email copy +2. Optimize subject lines for open rates +3. Personalize content based on recipient data +4. A/B test different variations +5. Analyze campaign performance +6. Suggest improvements + +Follow email marketing best practices and maintain brand voice.`, + model: { provider: "anthropic", model: "claude-3-opus", temperature: 0.8, maxTokens: 2e3 }, + tools: [ + { type: "action", name: "generate_email_copy", description: "Generate email campaign copy" }, + { type: "action", name: "optimize_subject_line", description: "Optimize email subject line" }, + { type: "action", name: "personalize_content", description: "Personalize email content" } + ], + knowledge: { + topics: ["email_marketing", "brand_guidelines", "campaign_templates"], + indexes: ["sales_knowledge"] + } +}; + +// ../app-crm/src/agents/lead-enrichment.agent.ts +var LeadEnrichmentAgent = { + name: "lead_enrichment", + label: "Lead Enrichment Agent", + role: "worker", + instructions: `You are a lead enrichment AI that enhances lead records with additional data. + +Your responsibilities: +1. Look up company information from external databases +2. Enrich contact details (job title, LinkedIn, etc.) +3. Add firmographic data (industry, size, revenue) +4. Research company technology stack +5. Find social media profiles +6. Validate email addresses and phone numbers + +Always use reputable data sources and maintain data quality.`, + model: { provider: "openai", model: "gpt-3.5-turbo", temperature: 0.3, maxTokens: 1e3 }, + tools: [ + { type: "action", name: "lookup_company", description: "Look up company information" }, + { type: "action", name: "enrich_contact", description: "Enrich contact information" }, + { type: "action", name: "validate_email", description: "Validate email address" } + ], + knowledge: { + topics: ["lead_enrichment", "company_data"], + indexes: ["sales_knowledge"] + }, + triggers: [ + { type: "object_create", objectName: "lead" } + ], + schedule: { type: "cron", expression: "0 */4 * * *", timezone: "UTC" } +}; + +// ../app-crm/src/agents/revenue-intelligence.agent.ts +var RevenueIntelligenceAgent = { + name: "revenue_intelligence", + label: "Revenue Intelligence Agent", + role: "analyst", + instructions: `You are a revenue intelligence AI that analyzes sales data and provides insights. + +Your responsibilities: +1. Analyze pipeline health and quality +2. Identify at-risk deals +3. Forecast revenue with confidence intervals +4. Detect anomalies and trends +5. Suggest coaching opportunities +6. Generate executive summaries + +Use statistical analysis and machine learning to provide data-driven insights.`, + model: { provider: "openai", model: "gpt-4", temperature: 0.2, maxTokens: 3e3 }, + tools: [ + { type: "query", name: "analyze_pipeline", description: "Analyze sales pipeline health" }, + { type: "query", name: "identify_at_risk", description: "Identify at-risk opportunities" }, + { type: "query", name: "forecast_revenue", description: "Generate revenue forecast" } + ], + knowledge: { + topics: ["pipeline_analytics", "revenue_forecasting", "deal_risk"], + indexes: ["sales_knowledge"] + }, + schedule: { type: "cron", expression: "0 8 * * 1", timezone: "America/Los_Angeles" } +}; + +// ../app-crm/src/agents/sales.agent.ts +var SalesAssistantAgent = { + name: "sales_assistant", + label: "Sales Assistant", + role: "assistant", + instructions: `You are a sales assistant AI helping sales representatives manage their pipeline. + +Your responsibilities: +1. Qualify incoming leads based on BANT criteria (Budget, Authority, Need, Timeline) +2. Suggest next best actions for opportunities +3. Draft personalized email templates +4. Analyze win/loss patterns +5. Provide competitive intelligence +6. Generate sales forecasts + +Always be professional, data-driven, and focused on helping close deals.`, + model: { provider: "openai", model: "gpt-4", temperature: 0.7, maxTokens: 2e3 }, + tools: [ + { type: "action", name: "analyze_lead", description: "Analyze a lead and provide qualification score" }, + { type: "action", name: "suggest_next_action", description: "Suggest next best action for an opportunity" }, + { type: "action", name: "generate_email", description: "Generate a personalized email template" } + ], + knowledge: { + topics: ["sales_playbook", "product_catalog", "lead_qualification"], + indexes: ["sales_knowledge"] + }, + triggers: [ + { type: "object_create", objectName: "lead", condition: 'rating = "hot"' }, + { type: "object_update", objectName: "opportunity", condition: "ISCHANGED(stage)" } + ] +}; + +// ../app-crm/src/agents/service.agent.ts +var ServiceAgent = { + name: "service_agent", + label: "Customer Service Agent", + role: "assistant", + instructions: `You are a customer service AI agent helping support representatives resolve customer issues. + +Your responsibilities: +1. Triage incoming cases based on priority and category +2. Suggest relevant knowledge articles +3. Draft response templates +4. Escalate critical issues +5. Identify common problems and patterns +6. Recommend process improvements + +Always be empathetic, solution-focused, and customer-centric.`, + model: { provider: "openai", model: "gpt-4", temperature: 0.5, maxTokens: 1500 }, + tools: [ + { type: "action", name: "triage_case", description: "Analyze case and assign priority" }, + { type: "vector_search", name: "search_knowledge", description: "Search knowledge base for solutions" }, + { type: "action", name: "generate_response", description: "Generate customer response" } + ], + knowledge: { + topics: ["support_kb", "sla_policies", "case_resolution"], + indexes: ["support_knowledge"] + }, + triggers: [ + { type: "object_create", objectName: "case" }, + { type: "object_update", objectName: "case", condition: 'priority = "critical"' } + ] +}; + +// ../app-crm/src/agents/index.ts +var allAgents = [ + EmailCampaignAgent, + LeadEnrichmentAgent, + RevenueIntelligenceAgent, + SalesAssistantAgent, + ServiceAgent +]; + +// ../app-crm/src/rag/index.ts +var rag_exports = {}; +__export(rag_exports, { + CompetitiveIntelRAG: () => CompetitiveIntelRAG, + ProductInfoRAG: () => ProductInfoRAG, + SalesKnowledgeRAG: () => SalesKnowledgeRAG, + SupportKnowledgeRAG: () => SupportKnowledgeRAG +}); + +// ../app-crm/src/rag/competitive-intel.rag.ts +var CompetitiveIntelRAG = { + name: "competitive_intel", + label: "Competitive Intelligence Pipeline", + description: "RAG pipeline for competitive analysis and market insights", + embedding: { + provider: "openai", + model: "text-embedding-3-large", + dimensions: 1536 + }, + vectorStore: { + provider: "pgvector", + indexName: "competitive_index", + dimensions: 1536, + metric: "cosine" + }, + chunking: { + type: "semantic", + maxChunkSize: 1200 + }, + retrieval: { + type: "similarity", + topK: 7, + scoreThreshold: 0.65 + }, + reranking: { + enabled: true, + provider: "cohere", + model: "cohere-rerank", + topK: 5 + }, + loaders: [ + { type: "directory", source: "/knowledge/competitive", fileTypes: [".md"], recursive: true }, + { type: "directory", source: "/knowledge/market-research", fileTypes: [".pdf"], recursive: true } + ], + maxContextTokens: 5e3, + enableCache: true, + cacheTTL: 1800 +}; + +// ../app-crm/src/rag/product-info.rag.ts +var ProductInfoRAG = { + name: "product_info", + label: "Product Information Pipeline", + description: "RAG pipeline for product catalog and specifications", + embedding: { + provider: "openai", + model: "text-embedding-3-small", + dimensions: 768 + }, + vectorStore: { + provider: "pgvector", + indexName: "product_catalog_index", + dimensions: 768, + metric: "cosine" + }, + chunking: { + type: "semantic", + maxChunkSize: 800 + }, + retrieval: { + type: "hybrid", + topK: 8, + vectorWeight: 0.6, + keywordWeight: 0.4 + }, + loaders: [ + { type: "directory", source: "/knowledge/products", fileTypes: [".md", ".pdf"], recursive: true } + ], + maxContextTokens: 2e3, + enableCache: true, + cacheTTL: 3600 +}; + +// ../app-crm/src/rag/sales-knowledge.rag.ts +var SalesKnowledgeRAG = { + name: "sales_knowledge", + label: "Sales Knowledge Pipeline", + description: "RAG pipeline for sales team knowledge and best practices", + embedding: { + provider: "openai", + model: "text-embedding-3-large", + dimensions: 1536 + }, + vectorStore: { + provider: "pgvector", + indexName: "sales_playbook_index", + dimensions: 1536, + metric: "cosine" + }, + chunking: { + type: "semantic", + maxChunkSize: 1e3 + }, + retrieval: { + type: "hybrid", + topK: 10, + vectorWeight: 0.7, + keywordWeight: 0.3 + }, + reranking: { + enabled: true, + provider: "cohere", + model: "cohere-rerank", + topK: 5 + }, + loaders: [ + { type: "directory", source: "/knowledge/sales", fileTypes: [".md"], recursive: true }, + { type: "directory", source: "/knowledge/products", fileTypes: [".pdf"], recursive: true } + ], + maxContextTokens: 4e3, + enableCache: true, + cacheTTL: 3600 +}; + +// ../app-crm/src/rag/support-knowledge.rag.ts +var SupportKnowledgeRAG = { + name: "support_knowledge", + label: "Support Knowledge Pipeline", + description: "RAG pipeline for customer support knowledge base", + embedding: { + provider: "openai", + model: "text-embedding-3-small", + dimensions: 768 + }, + vectorStore: { + provider: "pgvector", + indexName: "support_kb_index", + dimensions: 768, + metric: "cosine" + }, + chunking: { + type: "fixed", + chunkSize: 512, + chunkOverlap: 100, + unit: "tokens" + }, + retrieval: { + type: "similarity", + topK: 5, + scoreThreshold: 0.75 + }, + loaders: [ + { type: "directory", source: "/knowledge/support", fileTypes: [".md"], recursive: true } + ], + maxContextTokens: 3e3, + enableCache: true, + cacheTTL: 3600 +}; + +// ../app-crm/src/profiles/index.ts +var profiles_exports = {}; +__export(profiles_exports, { + MarketingUserProfile: () => MarketingUserProfile, + SalesManagerProfile: () => SalesManagerProfile, + SalesRepProfile: () => SalesRepProfile, + ServiceAgentProfile: () => ServiceAgentProfile, + SystemAdminProfile: () => SystemAdminProfile +}); + +// ../app-crm/src/profiles/marketing-user.profile.ts +var MarketingUserProfile = { + name: "marketing_user", + label: "Marketing User", + isProfile: true, + objects: { + lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + account: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + opportunity: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false } + } +}; + +// ../app-crm/src/profiles/sales-manager.profile.ts +var SalesManagerProfile = { + name: "sales_manager", + label: "Sales Manager", + isProfile: true, + objects: { + lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + contract: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + product: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + case: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true } + } +}; + +// ../app-crm/src/profiles/sales-rep.profile.ts +var SalesRepProfile = { + name: "sales_rep", + label: "Sales Representative", + isProfile: true, + objects: { + lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + contract: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + product: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + campaign: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, + case: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: false, modifyAllRecords: false } + }, + fields: { + "account.annual_revenue": { readable: true, editable: false }, + "account.description": { readable: true, editable: true }, + "opportunity.amount": { readable: true, editable: true }, + "opportunity.probability": { readable: true, editable: true } + } +}; + +// ../app-crm/src/profiles/service-agent.profile.ts +var ServiceAgentProfile = { + name: "service_agent", + label: "Service Agent", + isProfile: true, + objects: { + lead: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + account: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + contact: { allowCreate: false, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + opportunity: { allowCreate: false, allowRead: false, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + case: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, + task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: false, modifyAllRecords: false }, + product: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false } + }, + fields: { + "case.is_sla_violated": { readable: true, editable: false }, + "case.resolution_time_hours": { readable: true, editable: false } + } +}; + +// ../app-crm/src/profiles/system-admin.profile.ts +var SystemAdminProfile = { + name: "system_admin", + label: "System Administrator", + isProfile: true, + objects: { + lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + contract: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + product: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + case: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true } + }, + systemPermissions: [ + "view_setup", + "manage_users", + "customize_application", + "view_all_data", + "modify_all_data", + "manage_profiles", + "manage_roles", + "manage_sharing" + ] +}; + +// ../app-crm/src/apps/index.ts +var apps_exports = {}; +__export(apps_exports, { + CrmApp: () => CrmApp +}); + +// ../app-crm/src/apps/crm.app.ts +var CrmApp = App.create({ + name: "crm_enterprise", + label: "Enterprise CRM", + icon: "briefcase", + branding: { + primaryColor: "#4169E1", + secondaryColor: "#00AA00", + logo: "/assets/crm-logo.png", + favicon: "/assets/crm-favicon.ico" + }, + navigation: [ + { + id: "group_sales", + type: "group", + label: "Sales", + icon: "chart-line", + children: [ + { id: "nav_lead", type: "object", objectName: "lead", label: "Leads", icon: "user-plus" }, + { id: "nav_account", type: "object", objectName: "account", label: "Accounts", icon: "building" }, + { id: "nav_contact", type: "object", objectName: "contact", label: "Contacts", icon: "user" }, + { id: "nav_opportunity", type: "object", objectName: "opportunity", label: "Opportunities", icon: "bullseye" }, + { id: "nav_quote", type: "object", objectName: "quote", label: "Quotes", icon: "file-invoice" }, + { id: "nav_contract", type: "object", objectName: "contract", label: "Contracts", icon: "file-signature" }, + { id: "nav_sales_dashboard", type: "dashboard", dashboardName: "sales_dashboard", label: "Sales Dashboard", icon: "chart-bar" } + ] + }, + { + id: "group_service", + type: "group", + label: "Service", + icon: "headset", + children: [ + { id: "nav_case", type: "object", objectName: "case", label: "Cases", icon: "life-ring" }, + { id: "nav_task", type: "object", objectName: "task", label: "Tasks", icon: "tasks" }, + { id: "nav_service_dashboard", type: "dashboard", dashboardName: "service_dashboard", label: "Service Dashboard", icon: "chart-pie" } + ] + }, + { + id: "group_marketing", + type: "group", + label: "Marketing", + icon: "megaphone", + children: [ + { id: "nav_campaign", type: "object", objectName: "campaign", label: "Campaigns", icon: "bullhorn" }, + { id: "nav_lead_marketing", type: "object", objectName: "lead", label: "Leads", icon: "user-plus" } + ] + }, + { + id: "group_products", + type: "group", + label: "Products", + icon: "box", + children: [ + { id: "nav_product", type: "object", objectName: "product", label: "Products", icon: "box-open" } + ] + }, + { + id: "group_analytics", + type: "group", + label: "Analytics", + icon: "chart-area", + children: [ + { id: "nav_exec_dashboard", type: "dashboard", dashboardName: "executive_dashboard", label: "Executive Dashboard", icon: "tachometer-alt" }, + { id: "nav_analytics_sales_db", type: "dashboard", dashboardName: "sales_dashboard", label: "Sales Analytics", icon: "chart-line" }, + { id: "nav_analytics_service_db", type: "dashboard", dashboardName: "service_dashboard", label: "Service Analytics", icon: "chart-pie" } + ] + } + ] +}); + +// ../app-crm/src/apps/crm_modern.app.ts +var CrmApp2 = defineApp({ + name: "crm", + label: "Sales CRM", + description: "Enterprise CRM with nested navigation tree", + icon: "briefcase", + branding: { + primaryColor: "#4169E1", + logo: "/assets/crm-logo.png", + favicon: "/assets/crm-favicon.ico" + }, + navigation: [ + // ── Sales Cloud ── + { + id: "grp_sales", + type: "group", + label: "Sales Cloud", + icon: "briefcase", + expanded: true, + children: [ + { id: "nav_pipeline", type: "page", label: "Pipeline", icon: "columns", pageName: "page_pipeline" }, + { id: "nav_accounts", type: "page", label: "Accounts", icon: "building", pageName: "page_accounts" }, + { id: "nav_leads", type: "page", label: "Leads", icon: "user-plus", pageName: "page_leads" }, + // Nested sub-group — impossible with the old Interface model + { + id: "grp_review", + type: "group", + label: "Lead Review", + icon: "clipboard-check", + expanded: false, + children: [ + { id: "nav_review_queue", type: "page", label: "Review Queue", icon: "check-square", pageName: "page_review_queue" }, + { id: "nav_qualified", type: "page", label: "Qualified", icon: "check-circle", pageName: "page_qualified" } + ] + } + ] + }, + // ── Analytics ── + { + id: "grp_analytics", + type: "group", + label: "Analytics", + icon: "chart-line", + expanded: false, + children: [ + { id: "nav_overview", type: "page", label: "Overview", icon: "gauge", pageName: "page_overview" }, + { id: "nav_pipeline_report", type: "page", label: "Pipeline Report", icon: "chart-bar", pageName: "page_pipeline_report" } + ] + }, + // ── Global Utility ── + { id: "nav_settings", type: "page", label: "Settings", icon: "settings", pageName: "admin_settings" }, + { id: "nav_help", type: "url", label: "Help", icon: "help-circle", url: "https://help.example.com", target: "_blank" } + ], + homePageId: "nav_pipeline", + requiredPermissions: ["app.access.crm"], + isDefault: true +}); + +// ../app-crm/src/translations/index.ts +var translations_exports = {}; +__export(translations_exports, { + CrmTranslations: () => CrmTranslations +}); + +// ../app-crm/src/translations/en.ts +var en = { + objects: { + account: { + label: "Account", + pluralLabel: "Accounts", + fields: { + account_number: { label: "Account Number" }, + name: { label: "Account Name", help: "Legal name of the company or organization" }, + type: { + label: "Type", + options: { prospect: "Prospect", customer: "Customer", partner: "Partner", former: "Former" } + }, + industry: { + label: "Industry", + options: { + technology: "Technology", + finance: "Finance", + healthcare: "Healthcare", + retail: "Retail", + manufacturing: "Manufacturing", + education: "Education" + } + }, + annual_revenue: { label: "Annual Revenue" }, + number_of_employees: { label: "Number of Employees" }, + phone: { label: "Phone" }, + website: { label: "Website" }, + billing_address: { label: "Billing Address" }, + office_location: { label: "Office Location" }, + owner: { label: "Account Owner" }, + parent_account: { label: "Parent Account" }, + description: { label: "Description" }, + is_active: { label: "Active" }, + last_activity_date: { label: "Last Activity Date" } + } + }, + contact: { + label: "Contact", + pluralLabel: "Contacts", + fields: { + salutation: { label: "Salutation" }, + first_name: { label: "First Name" }, + last_name: { label: "Last Name" }, + full_name: { label: "Full Name" }, + account: { label: "Account" }, + email: { label: "Email" }, + phone: { label: "Phone" }, + mobile: { label: "Mobile" }, + title: { label: "Title" }, + department: { + label: "Department", + options: { + Executive: "Executive", + Sales: "Sales", + Marketing: "Marketing", + Engineering: "Engineering", + Support: "Support", + Finance: "Finance", + HR: "Human Resources", + Operations: "Operations" + } + }, + owner: { label: "Contact Owner" }, + description: { label: "Description" }, + is_primary: { label: "Primary Contact" } + } + }, + lead: { + label: "Lead", + pluralLabel: "Leads", + fields: { + first_name: { label: "First Name" }, + last_name: { label: "Last Name" }, + company: { label: "Company" }, + title: { label: "Title" }, + email: { label: "Email" }, + phone: { label: "Phone" }, + status: { + label: "Status", + options: { + new: "New", + contacted: "Contacted", + qualified: "Qualified", + unqualified: "Unqualified", + converted: "Converted" + } + }, + lead_source: { + label: "Lead Source", + options: { + Web: "Web", + Referral: "Referral", + Event: "Event", + Partner: "Partner", + Advertisement: "Advertisement", + "Cold Call": "Cold Call" + } + }, + owner: { label: "Lead Owner" }, + is_converted: { label: "Converted" }, + description: { label: "Description" } + } + }, + opportunity: { + label: "Opportunity", + pluralLabel: "Opportunities", + fields: { + name: { label: "Opportunity Name" }, + account: { label: "Account" }, + primary_contact: { label: "Primary Contact" }, + owner: { label: "Opportunity Owner" }, + amount: { label: "Amount" }, + expected_revenue: { label: "Expected Revenue" }, + stage: { + label: "Stage", + options: { + prospecting: "Prospecting", + qualification: "Qualification", + needs_analysis: "Needs Analysis", + proposal: "Proposal", + negotiation: "Negotiation", + closed_won: "Closed Won", + closed_lost: "Closed Lost" + } + }, + probability: { label: "Probability (%)" }, + close_date: { label: "Close Date" }, + type: { + label: "Type", + options: { + "New Business": "New Business", + "Existing Customer - Upgrade": "Existing Customer - Upgrade", + "Existing Customer - Renewal": "Existing Customer - Renewal", + "Existing Customer - Expansion": "Existing Customer - Expansion" + } + }, + forecast_category: { + label: "Forecast Category", + options: { + Pipeline: "Pipeline", + "Best Case": "Best Case", + Commit: "Commit", + Omitted: "Omitted", + Closed: "Closed" + } + }, + description: { label: "Description" }, + next_step: { label: "Next Step" } + } + } + }, + apps: { + crm_enterprise: { + label: "Enterprise CRM", + description: "Customer relationship management for sales, service, and marketing" + } + }, + messages: { + "common.save": "Save", + "common.cancel": "Cancel", + "common.delete": "Delete", + "common.edit": "Edit", + "common.create": "Create", + "common.search": "Search", + "common.filter": "Filter", + "common.export": "Export", + "common.back": "Back", + "common.confirm": "Confirm", + "nav.sales": "Sales", + "nav.service": "Service", + "nav.marketing": "Marketing", + "nav.products": "Products", + "nav.analytics": "Analytics", + "success.saved": "Record saved successfully", + "success.converted": "Lead converted successfully", + "confirm.delete": "Are you sure you want to delete this record?", + "confirm.convert_lead": "Convert this lead to account, contact, and opportunity?", + "error.required": "This field is required", + "error.load_failed": "Failed to load data" + }, + validationMessages: { + amount_required_for_closed: "Amount is required when stage is Closed Won", + close_date_required: "Close date is required for opportunities", + discount_limit: "Discount cannot exceed 40%" + } +}; + +// ../app-crm/src/translations/zh-CN.ts +var zhCN = { + objects: { + account: { + label: "\u5BA2\u6237", + pluralLabel: "\u5BA2\u6237", + fields: { + account_number: { label: "\u5BA2\u6237\u7F16\u53F7" }, + name: { label: "\u5BA2\u6237\u540D\u79F0", help: "\u516C\u53F8\u6216\u7EC4\u7EC7\u7684\u6CD5\u5B9A\u540D\u79F0" }, + type: { + label: "\u7C7B\u578B", + options: { prospect: "\u6F5C\u5728\u5BA2\u6237", customer: "\u6B63\u5F0F\u5BA2\u6237", partner: "\u5408\u4F5C\u4F19\u4F34", former: "\u524D\u5BA2\u6237" } + }, + industry: { + label: "\u884C\u4E1A", + options: { + technology: "\u79D1\u6280", + finance: "\u91D1\u878D", + healthcare: "\u533B\u7597", + retail: "\u96F6\u552E", + manufacturing: "\u5236\u9020", + education: "\u6559\u80B2" + } + }, + annual_revenue: { label: "\u5E74\u8425\u6536" }, + number_of_employees: { label: "\u5458\u5DE5\u4EBA\u6570" }, + phone: { label: "\u7535\u8BDD" }, + website: { label: "\u7F51\u7AD9" }, + billing_address: { label: "\u8D26\u5355\u5730\u5740" }, + office_location: { label: "\u529E\u516C\u5730\u70B9" }, + owner: { label: "\u5BA2\u6237\u8D1F\u8D23\u4EBA" }, + parent_account: { label: "\u6BCD\u516C\u53F8" }, + description: { label: "\u63CF\u8FF0" }, + is_active: { label: "\u662F\u5426\u6D3B\u8DC3" }, + last_activity_date: { label: "\u6700\u8FD1\u6D3B\u52A8\u65E5\u671F" } + } + }, + contact: { + label: "\u8054\u7CFB\u4EBA", + pluralLabel: "\u8054\u7CFB\u4EBA", + fields: { + salutation: { label: "\u79F0\u8C13" }, + first_name: { label: "\u540D" }, + last_name: { label: "\u59D3" }, + full_name: { label: "\u5168\u540D" }, + account: { label: "\u6240\u5C5E\u5BA2\u6237" }, + email: { label: "\u90AE\u7BB1" }, + phone: { label: "\u7535\u8BDD" }, + mobile: { label: "\u624B\u673A" }, + title: { label: "\u804C\u4F4D" }, + department: { + label: "\u90E8\u95E8", + options: { + Executive: "\u7BA1\u7406\u5C42", + Sales: "\u9500\u552E\u90E8", + Marketing: "\u5E02\u573A\u90E8", + Engineering: "\u5DE5\u7A0B\u90E8", + Support: "\u652F\u6301\u90E8", + Finance: "\u8D22\u52A1\u90E8", + HR: "\u4EBA\u529B\u8D44\u6E90", + Operations: "\u8FD0\u8425\u90E8" + } + }, + owner: { label: "\u8054\u7CFB\u4EBA\u8D1F\u8D23\u4EBA" }, + description: { label: "\u63CF\u8FF0" }, + is_primary: { label: "\u4E3B\u8981\u8054\u7CFB\u4EBA" } + } + }, + lead: { + label: "\u7EBF\u7D22", + pluralLabel: "\u7EBF\u7D22", + fields: { + first_name: { label: "\u540D" }, + last_name: { label: "\u59D3" }, + company: { label: "\u516C\u53F8" }, + title: { label: "\u804C\u4F4D" }, + email: { label: "\u90AE\u7BB1" }, + phone: { label: "\u7535\u8BDD" }, + status: { + label: "\u72B6\u6001", + options: { + new: "\u65B0\u5EFA", + contacted: "\u5DF2\u8054\u7CFB", + qualified: "\u5DF2\u786E\u8BA4", + unqualified: "\u4E0D\u5408\u683C", + converted: "\u5DF2\u8F6C\u5316" + } + }, + lead_source: { + label: "\u7EBF\u7D22\u6765\u6E90", + options: { + Web: "\u7F51\u7AD9", + Referral: "\u63A8\u8350", + Event: "\u6D3B\u52A8", + Partner: "\u5408\u4F5C\u4F19\u4F34", + Advertisement: "\u5E7F\u544A", + "Cold Call": "\u964C\u751F\u62DC\u8BBF" + } + }, + owner: { label: "\u7EBF\u7D22\u8D1F\u8D23\u4EBA" }, + is_converted: { label: "\u5DF2\u8F6C\u5316" }, + description: { label: "\u63CF\u8FF0" } + } + }, + opportunity: { + label: "\u5546\u673A", + pluralLabel: "\u5546\u673A", + fields: { + name: { label: "\u5546\u673A\u540D\u79F0" }, + account: { label: "\u6240\u5C5E\u5BA2\u6237" }, + primary_contact: { label: "\u4E3B\u8981\u8054\u7CFB\u4EBA" }, + owner: { label: "\u5546\u673A\u8D1F\u8D23\u4EBA" }, + amount: { label: "\u91D1\u989D" }, + expected_revenue: { label: "\u9884\u671F\u6536\u5165" }, + stage: { + label: "\u9636\u6BB5", + options: { + prospecting: "\u5BFB\u627E\u5BA2\u6237", + qualification: "\u8D44\u683C\u5BA1\u67E5", + needs_analysis: "\u9700\u6C42\u5206\u6790", + proposal: "\u63D0\u6848", + negotiation: "\u8C08\u5224", + closed_won: "\u6210\u4EA4", + closed_lost: "\u5931\u8D25" + } + }, + probability: { label: "\u6210\u4EA4\u6982\u7387 (%)" }, + close_date: { label: "\u9884\u8BA1\u6210\u4EA4\u65E5\u671F" }, + type: { + label: "\u7C7B\u578B", + options: { + "New Business": "\u65B0\u4E1A\u52A1", + "Existing Customer - Upgrade": "\u8001\u5BA2\u6237\u5347\u7EA7", + "Existing Customer - Renewal": "\u8001\u5BA2\u6237\u7EED\u7EA6", + "Existing Customer - Expansion": "\u8001\u5BA2\u6237\u62D3\u5C55" + } + }, + forecast_category: { + label: "\u9884\u6D4B\u7C7B\u522B", + options: { + Pipeline: "\u7BA1\u9053", + "Best Case": "\u6700\u4F73\u60C5\u51B5", + Commit: "\u627F\u8BFA", + Omitted: "\u5DF2\u6392\u9664", + Closed: "\u5DF2\u5173\u95ED" + } + }, + description: { label: "\u63CF\u8FF0" }, + next_step: { label: "\u4E0B\u4E00\u6B65" } + } + } + }, + apps: { + crm_enterprise: { + label: "\u4F01\u4E1A CRM", + description: "\u6DB5\u76D6\u9500\u552E\u3001\u670D\u52A1\u548C\u5E02\u573A\u8425\u9500\u7684\u5BA2\u6237\u5173\u7CFB\u7BA1\u7406\u7CFB\u7EDF" + } + }, + messages: { + "common.save": "\u4FDD\u5B58", + "common.cancel": "\u53D6\u6D88", + "common.delete": "\u5220\u9664", + "common.edit": "\u7F16\u8F91", + "common.create": "\u65B0\u5EFA", + "common.search": "\u641C\u7D22", + "common.filter": "\u7B5B\u9009", + "common.export": "\u5BFC\u51FA", + "common.back": "\u8FD4\u56DE", + "common.confirm": "\u786E\u8BA4", + "nav.sales": "\u9500\u552E", + "nav.service": "\u670D\u52A1", + "nav.marketing": "\u8425\u9500", + "nav.products": "\u4EA7\u54C1", + "nav.analytics": "\u6570\u636E\u5206\u6790", + "success.saved": "\u8BB0\u5F55\u4FDD\u5B58\u6210\u529F", + "success.converted": "\u7EBF\u7D22\u8F6C\u5316\u6210\u529F", + "confirm.delete": "\u786E\u5B9A\u8981\u5220\u9664\u6B64\u8BB0\u5F55\u5417\uFF1F", + "confirm.convert_lead": "\u5C06\u6B64\u7EBF\u7D22\u8F6C\u5316\u4E3A\u5BA2\u6237\u3001\u8054\u7CFB\u4EBA\u548C\u5546\u673A\uFF1F", + "error.required": "\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879", + "error.load_failed": "\u6570\u636E\u52A0\u8F7D\u5931\u8D25" + }, + validationMessages: { + amount_required_for_closed: '\u9636\u6BB5\u4E3A"\u6210\u4EA4"\u65F6\uFF0C\u91D1\u989D\u4E3A\u5FC5\u586B\u9879', + close_date_required: "\u5546\u673A\u5FC5\u987B\u586B\u5199\u9884\u8BA1\u6210\u4EA4\u65E5\u671F", + discount_limit: "\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%" + } +}; + +// ../app-crm/src/translations/ja-JP.ts +var jaJP = { + objects: { + account: { + label: "\u53D6\u5F15\u5148", + pluralLabel: "\u53D6\u5F15\u5148", + fields: { + account_number: { label: "\u53D6\u5F15\u5148\u756A\u53F7" }, + name: { label: "\u53D6\u5F15\u5148\u540D", help: "\u4F1A\u793E\u307E\u305F\u306F\u7D44\u7E54\u306E\u6B63\u5F0F\u540D\u79F0" }, + type: { + label: "\u30BF\u30A4\u30D7", + options: { prospect: "\u898B\u8FBC\u307F\u5BA2", customer: "\u9867\u5BA2", partner: "\u30D1\u30FC\u30C8\u30CA\u30FC", former: "\u904E\u53BB\u306E\u53D6\u5F15\u5148" } + }, + industry: { + label: "\u696D\u7A2E", + options: { + technology: "\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC", + finance: "\u91D1\u878D", + healthcare: "\u30D8\u30EB\u30B9\u30B1\u30A2", + retail: "\u5C0F\u58F2", + manufacturing: "\u88FD\u9020", + education: "\u6559\u80B2" + } + }, + annual_revenue: { label: "\u5E74\u9593\u58F2\u4E0A" }, + number_of_employees: { label: "\u5F93\u696D\u54E1\u6570" }, + phone: { label: "\u96FB\u8A71\u756A\u53F7" }, + website: { label: "Web\u30B5\u30A4\u30C8" }, + billing_address: { label: "\u8ACB\u6C42\u5148\u4F4F\u6240" }, + office_location: { label: "\u30AA\u30D5\u30A3\u30B9\u6240\u5728\u5730" }, + owner: { label: "\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005" }, + parent_account: { label: "\u89AA\u53D6\u5F15\u5148" }, + description: { label: "\u8AAC\u660E" }, + is_active: { label: "\u6709\u52B9" }, + last_activity_date: { label: "\u6700\u7D42\u6D3B\u52D5\u65E5" } + } + }, + contact: { + label: "\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005", + pluralLabel: "\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005", + fields: { + salutation: { label: "\u656C\u79F0" }, + first_name: { label: "\u540D" }, + last_name: { label: "\u59D3" }, + full_name: { label: "\u6C0F\u540D" }, + account: { label: "\u53D6\u5F15\u5148" }, + email: { label: "\u30E1\u30FC\u30EB" }, + phone: { label: "\u96FB\u8A71" }, + mobile: { label: "\u643A\u5E2F\u96FB\u8A71" }, + title: { label: "\u5F79\u8077" }, + department: { + label: "\u90E8\u9580", + options: { + Executive: "\u7D4C\u55B6\u5C64", + Sales: "\u55B6\u696D\u90E8", + Marketing: "\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u90E8", + Engineering: "\u30A8\u30F3\u30B8\u30CB\u30A2\u30EA\u30F3\u30B0\u90E8", + Support: "\u30B5\u30DD\u30FC\u30C8\u90E8", + Finance: "\u7D4C\u7406\u90E8", + HR: "\u4EBA\u4E8B\u90E8", + Operations: "\u30AA\u30DA\u30EC\u30FC\u30B7\u30E7\u30F3\u90E8" + } + }, + owner: { label: "\u6240\u6709\u8005" }, + description: { label: "\u8AAC\u660E" }, + is_primary: { label: "\u4E3B\u62C5\u5F53\u8005" } + } + }, + lead: { + label: "\u30EA\u30FC\u30C9", + pluralLabel: "\u30EA\u30FC\u30C9", + fields: { + first_name: { label: "\u540D" }, + last_name: { label: "\u59D3" }, + company: { label: "\u4F1A\u793E\u540D" }, + title: { label: "\u5F79\u8077" }, + email: { label: "\u30E1\u30FC\u30EB" }, + phone: { label: "\u96FB\u8A71" }, + status: { + label: "\u30B9\u30C6\u30FC\u30BF\u30B9", + options: { + new: "\u65B0\u898F", + contacted: "\u30B3\u30F3\u30BF\u30AF\u30C8\u6E08\u307F", + qualified: "\u9069\u683C", + unqualified: "\u4E0D\u9069\u683C", + converted: "\u53D6\u5F15\u958B\u59CB\u6E08\u307F" + } + }, + lead_source: { + label: "\u30EA\u30FC\u30C9\u30BD\u30FC\u30B9", + options: { + Web: "Web", + Referral: "\u7D39\u4ECB", + Event: "\u30A4\u30D9\u30F3\u30C8", + Partner: "\u30D1\u30FC\u30C8\u30CA\u30FC", + Advertisement: "\u5E83\u544A", + "Cold Call": "\u30B3\u30FC\u30EB\u30C9\u30B3\u30FC\u30EB" + } + }, + owner: { label: "\u30EA\u30FC\u30C9\u6240\u6709\u8005" }, + is_converted: { label: "\u53D6\u5F15\u958B\u59CB\u6E08\u307F" }, + description: { label: "\u8AAC\u660E" } + } + }, + opportunity: { + label: "\u5546\u8AC7", + pluralLabel: "\u5546\u8AC7", + fields: { + name: { label: "\u5546\u8AC7\u540D" }, + account: { label: "\u53D6\u5F15\u5148" }, + primary_contact: { label: "\u4E3B\u62C5\u5F53\u8005" }, + owner: { label: "\u5546\u8AC7\u6240\u6709\u8005" }, + amount: { label: "\u91D1\u984D" }, + expected_revenue: { label: "\u671F\u5F85\u53CE\u76CA" }, + stage: { + label: "\u30D5\u30A7\u30FC\u30BA", + options: { + prospecting: "\u898B\u8FBC\u307F\u8ABF\u67FB", + qualification: "\u9078\u5B9A", + needs_analysis: "\u30CB\u30FC\u30BA\u5206\u6790", + proposal: "\u63D0\u6848", + negotiation: "\u4EA4\u6E09", + closed_won: "\u6210\u7ACB", + closed_lost: "\u4E0D\u6210\u7ACB" + } + }, + probability: { label: "\u78BA\u5EA6 (%)" }, + close_date: { label: "\u5B8C\u4E86\u4E88\u5B9A\u65E5" }, + type: { + label: "\u30BF\u30A4\u30D7", + options: { + "New Business": "\u65B0\u898F\u30D3\u30B8\u30CD\u30B9", + "Existing Customer - Upgrade": "\u65E2\u5B58\u9867\u5BA2 - \u30A2\u30C3\u30D7\u30B0\u30EC\u30FC\u30C9", + "Existing Customer - Renewal": "\u65E2\u5B58\u9867\u5BA2 - \u66F4\u65B0", + "Existing Customer - Expansion": "\u65E2\u5B58\u9867\u5BA2 - \u62E1\u5927" + } + }, + forecast_category: { + label: "\u58F2\u4E0A\u4E88\u6E2C\u30AB\u30C6\u30B4\u30EA", + options: { + Pipeline: "\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3", + "Best Case": "\u6700\u826F\u30B1\u30FC\u30B9", + Commit: "\u30B3\u30DF\u30C3\u30C8", + Omitted: "\u9664\u5916", + Closed: "\u5B8C\u4E86" + } + }, + description: { label: "\u8AAC\u660E" }, + next_step: { label: "\u6B21\u306E\u30B9\u30C6\u30C3\u30D7" } + } + } + }, + apps: { + crm_enterprise: { + label: "\u30A8\u30F3\u30BF\u30FC\u30D7\u30E9\u30A4\u30BA CRM", + description: "\u55B6\u696D\u30FB\u30B5\u30FC\u30D3\u30B9\u30FB\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u5411\u3051\u9867\u5BA2\u95A2\u4FC2\u7BA1\u7406\u30B7\u30B9\u30C6\u30E0" + } + }, + messages: { + "common.save": "\u4FDD\u5B58", + "common.cancel": "\u30AD\u30E3\u30F3\u30BB\u30EB", + "common.delete": "\u524A\u9664", + "common.edit": "\u7DE8\u96C6", + "common.create": "\u65B0\u898F\u4F5C\u6210", + "common.search": "\u691C\u7D22", + "common.filter": "\u30D5\u30A3\u30EB\u30BF\u30FC", + "common.export": "\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8", + "common.back": "\u623B\u308B", + "common.confirm": "\u78BA\u8A8D", + "nav.sales": "\u55B6\u696D", + "nav.service": "\u30B5\u30FC\u30D3\u30B9", + "nav.marketing": "\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0", + "nav.products": "\u88FD\u54C1", + "nav.analytics": "\u30A2\u30CA\u30EA\u30C6\u30A3\u30AF\u30B9", + "success.saved": "\u30EC\u30B3\u30FC\u30C9\u3092\u4FDD\u5B58\u3057\u307E\u3057\u305F", + "success.converted": "\u30EA\u30FC\u30C9\u3092\u53D6\u5F15\u958B\u59CB\u3057\u307E\u3057\u305F", + "confirm.delete": "\u3053\u306E\u30EC\u30B3\u30FC\u30C9\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F", + "confirm.convert_lead": "\u3053\u306E\u30EA\u30FC\u30C9\u3092\u53D6\u5F15\u5148\u30FB\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005\u30FB\u5546\u8AC7\u306B\u5909\u63DB\u3057\u307E\u3059\u304B\uFF1F", + "error.required": "\u3053\u306E\u9805\u76EE\u306F\u5FC5\u9808\u3067\u3059", + "error.load_failed": "\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F" + }, + validationMessages: { + amount_required_for_closed: "\u30D5\u30A7\u30FC\u30BA\u304C\u300C\u6210\u7ACB\u300D\u306E\u5834\u5408\u3001\u91D1\u984D\u306F\u5FC5\u9808\u3067\u3059", + close_date_required: "\u5546\u8AC7\u306B\u306F\u5B8C\u4E86\u4E88\u5B9A\u65E5\u304C\u5FC5\u8981\u3067\u3059", + discount_limit: "\u5272\u5F15\u306F40%\u3092\u8D85\u3048\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093" + } +}; + +// ../app-crm/src/translations/es-ES.ts +var esES = { + objects: { + account: { + label: "Cuenta", + pluralLabel: "Cuentas", + fields: { + account_number: { label: "N\xFAmero de Cuenta" }, + name: { label: "Nombre de Cuenta", help: "Nombre legal de la empresa u organizaci\xF3n" }, + type: { + label: "Tipo", + options: { prospect: "Prospecto", customer: "Cliente", partner: "Socio", former: "Anterior" } + }, + industry: { + label: "Industria", + options: { + technology: "Tecnolog\xEDa", + finance: "Finanzas", + healthcare: "Salud", + retail: "Comercio", + manufacturing: "Manufactura", + education: "Educaci\xF3n" + } + }, + annual_revenue: { label: "Ingresos Anuales" }, + number_of_employees: { label: "N\xFAmero de Empleados" }, + phone: { label: "Tel\xE9fono" }, + website: { label: "Sitio Web" }, + billing_address: { label: "Direcci\xF3n de Facturaci\xF3n" }, + office_location: { label: "Ubicaci\xF3n de Oficina" }, + owner: { label: "Propietario de Cuenta" }, + parent_account: { label: "Cuenta Matriz" }, + description: { label: "Descripci\xF3n" }, + is_active: { label: "Activo" }, + last_activity_date: { label: "Fecha de \xDAltima Actividad" } + } + }, + contact: { + label: "Contacto", + pluralLabel: "Contactos", + fields: { + salutation: { label: "T\xEDtulo" }, + first_name: { label: "Nombre" }, + last_name: { label: "Apellido" }, + full_name: { label: "Nombre Completo" }, + account: { label: "Cuenta" }, + email: { label: "Correo Electr\xF3nico" }, + phone: { label: "Tel\xE9fono" }, + mobile: { label: "M\xF3vil" }, + title: { label: "Cargo" }, + department: { + label: "Departamento", + options: { + Executive: "Ejecutivo", + Sales: "Ventas", + Marketing: "Marketing", + Engineering: "Ingenier\xEDa", + Support: "Soporte", + Finance: "Finanzas", + HR: "Recursos Humanos", + Operations: "Operaciones" + } + }, + owner: { label: "Propietario de Contacto" }, + description: { label: "Descripci\xF3n" }, + is_primary: { label: "Contacto Principal" } + } + }, + lead: { + label: "Prospecto", + pluralLabel: "Prospectos", + fields: { + first_name: { label: "Nombre" }, + last_name: { label: "Apellido" }, + company: { label: "Empresa" }, + title: { label: "Cargo" }, + email: { label: "Correo Electr\xF3nico" }, + phone: { label: "Tel\xE9fono" }, + status: { + label: "Estado", + options: { + new: "Nuevo", + contacted: "Contactado", + qualified: "Calificado", + unqualified: "No Calificado", + converted: "Convertido" + } + }, + lead_source: { + label: "Origen del Prospecto", + options: { + Web: "Web", + Referral: "Referencia", + Event: "Evento", + Partner: "Socio", + Advertisement: "Publicidad", + "Cold Call": "Llamada en Fr\xEDo" + } + }, + owner: { label: "Propietario" }, + is_converted: { label: "Convertido" }, + description: { label: "Descripci\xF3n" } + } + }, + opportunity: { + label: "Oportunidad", + pluralLabel: "Oportunidades", + fields: { + name: { label: "Nombre de Oportunidad" }, + account: { label: "Cuenta" }, + primary_contact: { label: "Contacto Principal" }, + owner: { label: "Propietario de Oportunidad" }, + amount: { label: "Monto" }, + expected_revenue: { label: "Ingreso Esperado" }, + stage: { + label: "Etapa", + options: { + prospecting: "Prospecci\xF3n", + qualification: "Calificaci\xF3n", + needs_analysis: "An\xE1lisis de Necesidades", + proposal: "Propuesta", + negotiation: "Negociaci\xF3n", + closed_won: "Cerrada Ganada", + closed_lost: "Cerrada Perdida" + } + }, + probability: { label: "Probabilidad (%)" }, + close_date: { label: "Fecha de Cierre" }, + type: { + label: "Tipo", + options: { + "New Business": "Nuevo Negocio", + "Existing Customer - Upgrade": "Cliente Existente - Mejora", + "Existing Customer - Renewal": "Cliente Existente - Renovaci\xF3n", + "Existing Customer - Expansion": "Cliente Existente - Expansi\xF3n" + } + }, + forecast_category: { + label: "Categor\xEDa de Pron\xF3stico", + options: { + Pipeline: "Pipeline", + "Best Case": "Mejor Caso", + Commit: "Compromiso", + Omitted: "Omitida", + Closed: "Cerrada" + } + }, + description: { label: "Descripci\xF3n" }, + next_step: { label: "Pr\xF3ximo Paso" } + } + } + }, + apps: { + crm_enterprise: { + label: "CRM Empresarial", + description: "Gesti\xF3n de relaciones con clientes para ventas, servicio y marketing" + } + }, + messages: { + "common.save": "Guardar", + "common.cancel": "Cancelar", + "common.delete": "Eliminar", + "common.edit": "Editar", + "common.create": "Crear", + "common.search": "Buscar", + "common.filter": "Filtrar", + "common.export": "Exportar", + "common.back": "Volver", + "common.confirm": "Confirmar", + "nav.sales": "Ventas", + "nav.service": "Servicio", + "nav.marketing": "Marketing", + "nav.products": "Productos", + "nav.analytics": "Anal\xEDtica", + "success.saved": "Registro guardado exitosamente", + "success.converted": "Prospecto convertido exitosamente", + "confirm.delete": "\xBFEst\xE1 seguro de que desea eliminar este registro?", + "confirm.convert_lead": "\xBFConvertir este prospecto en cuenta, contacto y oportunidad?", + "error.required": "Este campo es obligatorio", + "error.load_failed": "Error al cargar los datos" + }, + validationMessages: { + amount_required_for_closed: "El monto es obligatorio cuando la etapa es Cerrada Ganada", + close_date_required: "La fecha de cierre es obligatoria para las oportunidades", + discount_limit: "El descuento no puede superar el 40%" + } +}; + +// ../app-crm/src/translations/crm.translation.ts +var CrmTranslations = { + en, + "zh-CN": zhCN, + "ja-JP": jaJP, + "es-ES": esES +}; + +// ../app-crm/src/data/index.ts +var accounts = { + object: "account", + mode: "upsert", + externalId: "name", + records: [ + { + name: "Acme Corporation", + type: "customer", + industry: "technology", + annual_revenue: 5e6, + number_of_employees: 250, + phone: "+1-415-555-0100", + website: "https://acme.example.com" + }, + { + name: "Globex Industries", + type: "prospect", + industry: "manufacturing", + annual_revenue: 12e6, + number_of_employees: 800, + phone: "+1-312-555-0200", + website: "https://globex.example.com" + }, + { + name: "Initech Solutions", + type: "customer", + industry: "finance", + annual_revenue: 35e5, + number_of_employees: 150, + phone: "+1-212-555-0300", + website: "https://initech.example.com" + }, + { + name: "Stark Medical", + type: "partner", + industry: "healthcare", + annual_revenue: 8e6, + number_of_employees: 400, + phone: "+1-617-555-0400", + website: "https://starkmed.example.com" + }, + { + name: "Wayne Enterprises", + type: "customer", + industry: "technology", + annual_revenue: 25e6, + number_of_employees: 2e3, + phone: "+1-650-555-0500", + website: "https://wayne.example.com" + } + ] +}; +var contacts = { + object: "contact", + mode: "upsert", + externalId: "email", + records: [ + { + salutation: "Mr.", + first_name: "John", + last_name: "Smith", + email: "john.smith@acme.example.com", + phone: "+1-415-555-0101", + title: "VP of Engineering", + department: "Engineering" + }, + { + salutation: "Ms.", + first_name: "Sarah", + last_name: "Johnson", + email: "sarah.j@globex.example.com", + phone: "+1-312-555-0201", + title: "Chief Procurement Officer", + department: "Executive" + }, + { + salutation: "Dr.", + first_name: "Michael", + last_name: "Chen", + email: "mchen@initech.example.com", + phone: "+1-212-555-0301", + title: "Director of Operations", + department: "Operations" + }, + { + salutation: "Ms.", + first_name: "Emily", + last_name: "Davis", + email: "emily.d@starkmed.example.com", + phone: "+1-617-555-0401", + title: "Head of Partnerships", + department: "Sales" + }, + { + salutation: "Mr.", + first_name: "Robert", + last_name: "Wilson", + email: "rwilson@wayne.example.com", + phone: "+1-650-555-0501", + title: "CTO", + department: "Engineering" + } + ] +}; +var leads = { + object: "lead", + mode: "upsert", + externalId: "email", + records: [ + { + first_name: "Alice", + last_name: "Martinez", + company: "NextGen Retail", + email: "alice@nextgenretail.example.com", + phone: "+1-503-555-0600", + status: "new", + source: "website", + industry: "Retail" + }, + { + first_name: "David", + last_name: "Kim", + company: "EduTech Labs", + email: "dkim@edutechlabs.example.com", + phone: "+1-408-555-0700", + status: "contacted", + source: "referral", + industry: "Education" + }, + { + first_name: "Lisa", + last_name: "Thompson", + company: "CloudFirst Inc", + email: "lisa.t@cloudfirst.example.com", + phone: "+1-206-555-0800", + status: "qualified", + source: "trade_show", + industry: "Technology" + } + ] +}; +var opportunities = { + object: "opportunity", + mode: "upsert", + externalId: "name", + records: [ + { + name: "Acme Platform Upgrade", + amount: 15e4, + stage: "proposal", + probability: 60, + close_date: new Date(Date.now() + 864e5 * 30), + type: "existing_business", + forecast_category: "pipeline" + }, + { + name: "Globex Manufacturing Suite", + amount: 5e5, + stage: "qualification", + probability: 30, + close_date: new Date(Date.now() + 864e5 * 60), + type: "new_business", + forecast_category: "pipeline" + }, + { + name: "Wayne Enterprise License", + amount: 12e5, + stage: "negotiation", + probability: 75, + close_date: new Date(Date.now() + 864e5 * 14), + type: "new_business", + forecast_category: "commit" + }, + { + name: "Initech Cloud Migration", + amount: 8e4, + stage: "needs_analysis", + probability: 25, + close_date: new Date(Date.now() + 864e5 * 45), + type: "existing_business", + forecast_category: "best_case" + } + ] +}; +var products = { + object: "product", + mode: "upsert", + externalId: "name", + records: [ + { + name: "ObjectStack Platform", + category: "software", + family: "enterprise", + list_price: 5e4, + is_active: true + }, + { + name: "Cloud Hosting (Annual)", + category: "subscription", + family: "cloud", + list_price: 12e3, + is_active: true + }, + { + name: "Premium Support", + category: "support", + family: "services", + list_price: 25e3, + is_active: true + }, + { + name: "Implementation Services", + category: "service", + family: "services", + list_price: 75e3, + is_active: true + } + ] +}; +var tasks = { + object: "task", + mode: "upsert", + externalId: "subject", + records: [ + { + subject: "Follow up with Acme on proposal", + status: "not_started", + priority: "high", + due_date: new Date(Date.now() + 864e5 * 2) + }, + { + subject: "Schedule demo for Globex team", + status: "in_progress", + priority: "normal", + due_date: new Date(Date.now() + 864e5 * 5) + }, + { + subject: "Prepare contract for Wayne Enterprises", + status: "not_started", + priority: "urgent", + due_date: new Date(Date.now() + 864e5) + }, + { + subject: "Send welcome package to Stark Medical", + status: "completed", + priority: "low" + }, + { + subject: "Update CRM pipeline report", + status: "not_started", + priority: "normal", + due_date: new Date(Date.now() + 864e5 * 7) + } + ] +}; +var CrmSeedData = [ + accounts, + contacts, + leads, + opportunities, + products, + tasks +]; + +// ../app-crm/src/sharing/account.sharing.ts +var AccountTeamSharingRule = { + name: "account_team_sharing", + label: "Account Team Sharing", + object: "account", + type: "criteria", + condition: 'type = "customer" AND is_active = true', + accessLevel: "edit", + sharedWith: { type: "role", value: "sales_manager" } +}; +var TerritorySharingRules = [ + { + name: "north_america_territory", + label: "North America Territory", + object: "account", + type: "criteria", + condition: 'billing_country IN ("US", "CA", "MX")', + accessLevel: "edit", + sharedWith: { type: "role", value: "na_sales_team" } + }, + { + name: "europe_territory", + label: "Europe Territory", + object: "account", + type: "criteria", + condition: 'billing_country IN ("UK", "DE", "FR", "IT", "ES")', + accessLevel: "edit", + sharedWith: { type: "role", value: "eu_sales_team" } + } +]; + +// ../app-crm/src/sharing/case.sharing.ts +var CaseEscalationSharingRule = { + name: "case_escalation_sharing", + label: "Escalated Cases Sharing", + object: "case", + type: "criteria", + condition: 'priority = "critical" AND is_closed = false', + accessLevel: "edit", + sharedWith: { type: "role_and_subordinates", value: "service_manager" } +}; + +// ../app-crm/src/sharing/opportunity.sharing.ts +var OpportunitySalesSharingRule = { + name: "opportunity_sales_sharing", + label: "Opportunity Sales Team Sharing", + object: "opportunity", + type: "criteria", + condition: 'stage NOT IN ("closed_won", "closed_lost") AND amount >= 100000', + accessLevel: "read", + sharedWith: { type: "role_and_subordinates", value: "sales_director" } +}; + +// ../app-crm/src/sharing/role-hierarchy.ts +var RoleHierarchy = { + name: "crm_role_hierarchy", + label: "CRM Role Hierarchy", + roles: [ + { name: "executive", label: "Executive", parentRole: null }, + { name: "sales_director", label: "Sales Director", parentRole: "executive" }, + { name: "sales_manager", label: "Sales Manager", parentRole: "sales_director" }, + { name: "sales_rep", label: "Sales Representative", parentRole: "sales_manager" }, + { name: "service_director", label: "Service Director", parentRole: "executive" }, + { name: "service_manager", label: "Service Manager", parentRole: "service_director" }, + { name: "service_agent", label: "Service Agent", parentRole: "service_manager" }, + { name: "marketing_director", label: "Marketing Director", parentRole: "executive" }, + { name: "marketing_manager", label: "Marketing Manager", parentRole: "marketing_director" }, + { name: "marketing_user", label: "Marketing User", parentRole: "marketing_manager" } + ] +}; + +// ../app-crm/objectstack.config.ts +var objectstack_config_default = defineStack({ + manifest: { + id: "com.example.crm", + namespace: "crm", + version: "3.0.0", + type: "app", + name: "Enterprise CRM", + description: "Comprehensive enterprise CRM demonstrating all ObjectStack Protocol features including AI, security, and automation" + }, + // Auto-collected from barrel index files via Object.values() + objects: Object.values(objects_exports), + apis: Object.values(apis_exports), + actions: Object.values(actions_exports), + dashboards: Object.values(dashboards_exports), + reports: Object.values(reports_exports), + flows: allFlows, + agents: allAgents, + ragPipelines: Object.values(rag_exports), + permissions: Object.values(profiles_exports), + apps: Object.values(apps_exports), + // Seed Data (top-level, registered as metadata) + data: CrmSeedData, + // I18n Configuration — per-locale file organization + i18n: { + defaultLocale: "en", + supportedLocales: ["en", "zh-CN", "ja-JP", "es-ES"], + fallbackLocale: "en", + fileOrganization: "per_locale" + }, + // I18n Translation Bundles (en, zh-CN, ja-JP, es-ES) + translations: Object.values(translations_exports), + // Sharing & security + sharingRules: [ + AccountTeamSharingRule, + OpportunitySalesSharingRule, + CaseEscalationSharingRule, + ...TerritorySharingRules + ], + roles: RoleHierarchy.roles.map((r) => ({ + name: r.name, + label: r.label, + parent: r.parentRole ?? void 0 + })) +}); + +// ../app-todo/src/objects/index.ts +var objects_exports2 = {}; +__export(objects_exports2, { + Task: () => Task4 +}); + +// ../app-todo/src/objects/task.object.ts +init_data(); +var Task4 = ObjectSchema3.create({ + name: "task", + label: "Task", + pluralLabel: "Tasks", + icon: "check-square", + description: "Personal tasks and to-do items", + fields: { + // Task Information + subject: Field.text({ + label: "Subject", + required: true, + searchable: true, + maxLength: 255 + }), + description: Field.markdown({ + label: "Description" + }), + // Task Management + status: Field.select({ + label: "Status", + required: true, + options: [ + { label: "Not Started", value: "not_started", color: "#808080", default: true }, + { label: "In Progress", value: "in_progress", color: "#3B82F6" }, + { label: "Waiting", value: "waiting", color: "#F59E0B" }, + { label: "Completed", value: "completed", color: "#10B981" }, + { label: "Deferred", value: "deferred", color: "#6B7280" } + ] + }), + priority: Field.select({ + label: "Priority", + required: true, + options: [ + { label: "Low", value: "low", color: "#60A5FA", default: true }, + { label: "Normal", value: "normal", color: "#10B981" }, + { label: "High", value: "high", color: "#F59E0B" }, + { label: "Urgent", value: "urgent", color: "#EF4444" } + ] + }), + category: Field.select({ + label: "Category", + options: [ + { label: "Personal", value: "personal" }, + { label: "Work", value: "work" }, + { label: "Shopping", value: "shopping" }, + { label: "Health", value: "health" }, + { label: "Finance", value: "finance" }, + { label: "Other", value: "other" } + ] + }), + // Dates + due_date: Field.date({ + label: "Due Date" + }), + reminder_date: Field.datetime({ + label: "Reminder Date/Time" + }), + completed_date: Field.datetime({ + label: "Completed Date", + readonly: true + }), + // Assignment + owner: Field.lookup("user", { + label: "Assigned To", + required: true + }), + // Tags + tags: Field.select({ + label: "Tags", + multiple: true, + options: [ + { label: "Important", value: "important", color: "#EF4444" }, + { label: "Quick Win", value: "quick_win", color: "#10B981" }, + { label: "Blocked", value: "blocked", color: "#F59E0B" }, + { label: "Follow Up", value: "follow_up", color: "#3B82F6" }, + { label: "Review", value: "review", color: "#8B5CF6" } + ] + }), + // Recurrence + is_recurring: Field.boolean({ + label: "Recurring Task", + defaultValue: false + }), + recurrence_type: Field.select({ + label: "Recurrence Type", + options: [ + { label: "Daily", value: "daily" }, + { label: "Weekly", value: "weekly" }, + { label: "Monthly", value: "monthly" }, + { label: "Yearly", value: "yearly" } + ] + }), + recurrence_interval: Field.number({ + label: "Recurrence Interval", + defaultValue: 1, + min: 1 + }), + // Flags + is_completed: Field.boolean({ + label: "Is Completed", + defaultValue: false, + readonly: true + }), + is_overdue: Field.boolean({ + label: "Is Overdue", + defaultValue: false, + readonly: true + }), + // Progress + progress_percent: Field.percent({ + label: "Progress (%)", + min: 0, + max: 100, + defaultValue: 0 + }), + // Time Tracking + estimated_hours: Field.number({ + label: "Estimated Hours", + scale: 2, + min: 0 + }), + actual_hours: Field.number({ + label: "Actual Hours", + scale: 2, + min: 0 + }), + // Additional fields + notes: Field.richtext({ + label: "Notes", + description: "Rich text notes with formatting" + }), + category_color: Field.color({ + label: "Category Color", + colorFormat: "hex", + presetColors: ["#EF4444", "#F59E0B", "#10B981", "#3B82F6", "#8B5CF6"] + }) + }, + enable: { + trackHistory: true, + searchable: true, + apiEnabled: true, + files: true, + feeds: true, + activities: true, + trash: true, + mru: true + }, + // Database indexes for performance + indexes: [ + { fields: ["status"] }, + { fields: ["priority"] }, + { fields: ["owner"] }, + { fields: ["due_date"] }, + { fields: ["category"] } + ], + titleFormat: "{subject}", + compactLayout: ["subject", "status", "priority", "due_date", "owner"], + validations: [ + { + name: "completed_date_required", + type: "script", + severity: "error", + message: "Completed date is required when status is Completed", + condition: 'status = "completed" AND ISBLANK(completed_date)' + }, + { + name: "recurrence_fields_required", + type: "script", + severity: "error", + message: "Recurrence type is required for recurring tasks", + condition: "is_recurring = true AND ISBLANK(recurrence_type)" + } + ], + workflows: [ + { + name: "set_completed_flag", + objectName: "task", + triggerType: "on_create_or_update", + criteria: "ISCHANGED(status)", + active: true, + actions: [ + { + name: "update_completed_flag", + type: "field_update", + field: "is_completed", + value: 'status = "completed"' + } + ] + }, + { + name: "set_completed_date", + objectName: "task", + triggerType: "on_update", + criteria: 'ISCHANGED(status) AND status = "completed"', + active: true, + actions: [ + { + name: "set_date", + type: "field_update", + field: "completed_date", + value: "NOW()" + }, + { + name: "set_progress", + type: "field_update", + field: "progress_percent", + value: "100" + } + ] + }, + { + name: "check_overdue", + objectName: "task", + triggerType: "on_create_or_update", + criteria: "due_date < TODAY() AND is_completed = false", + active: true, + actions: [ + { + name: "set_overdue_flag", + type: "field_update", + field: "is_overdue", + value: "true" + } + ] + }, + { + name: "notify_on_urgent", + objectName: "task", + triggerType: "on_create_or_update", + criteria: 'priority = "urgent" AND is_completed = false', + active: true, + actions: [ + { + name: "email_owner", + type: "email_alert", + template: "urgent_task_alert", + recipients: ["{owner.email}"] + } + ] + } + ] +}); + +// ../app-todo/src/actions/index.ts +var actions_exports2 = {}; +__export(actions_exports2, { + CloneTaskAction: () => CloneTaskAction, + CompleteTaskAction: () => CompleteTaskAction, + DeferTaskAction: () => DeferTaskAction, + DeleteCompletedAction: () => DeleteCompletedAction, + ExportToCsvAction: () => ExportToCsvAction2, + MassCompleteTasksAction: () => MassCompleteTasksAction, + SetReminderAction: () => SetReminderAction, + StartTaskAction: () => StartTaskAction +}); + +// ../app-todo/src/actions/task.actions.ts +var CompleteTaskAction = { + name: "complete_task", + label: "Mark Complete", + objectName: "task", + icon: "check-circle", + type: "script", + target: "completeTask", + locations: ["record_header", "list_item"], + successMessage: "Task marked as complete!", + refreshAfter: true +}; +var StartTaskAction = { + name: "start_task", + label: "Start Task", + objectName: "task", + icon: "play-circle", + type: "script", + target: "startTask", + locations: ["record_header", "list_item"], + successMessage: "Task started!", + refreshAfter: true +}; +var DeferTaskAction = { + name: "defer_task", + label: "Defer Task", + objectName: "task", + icon: "clock", + type: "modal", + target: "defer_task_modal", + locations: ["record_header"], + params: [ + { + name: "new_due_date", + label: "New Due Date", + type: "date", + required: true + }, + { + name: "reason", + label: "Reason for Deferral", + type: "textarea", + required: false + } + ], + successMessage: "Task deferred successfully!", + refreshAfter: true +}; +var SetReminderAction = { + name: "set_reminder", + label: "Set Reminder", + objectName: "task", + icon: "bell", + type: "modal", + target: "set_reminder_modal", + locations: ["record_header", "list_item"], + params: [ + { + name: "reminder_date", + label: "Reminder Date/Time", + type: "datetime", + required: true + } + ], + successMessage: "Reminder set!", + refreshAfter: true +}; +var CloneTaskAction = { + name: "clone_task", + label: "Clone Task", + objectName: "task", + icon: "copy", + type: "script", + target: "cloneTask", + locations: ["record_header"], + successMessage: "Task cloned successfully!", + refreshAfter: true +}; +var MassCompleteTasksAction = { + name: "mass_complete", + label: "Complete Selected", + objectName: "task", + icon: "check-square", + type: "script", + target: "massCompleteTasks", + locations: ["list_toolbar"], + successMessage: "Selected tasks marked as complete!", + refreshAfter: true +}; +var DeleteCompletedAction = { + name: "delete_completed", + label: "Delete Completed", + objectName: "task", + icon: "trash-2", + type: "script", + target: "deleteCompletedTasks", + locations: ["list_toolbar"], + successMessage: "Completed tasks deleted!", + refreshAfter: true +}; +var ExportToCsvAction2 = { + name: "export_csv", + label: "Export to CSV", + objectName: "task", + icon: "download", + type: "script", + target: "exportTasksToCSV", + locations: ["list_toolbar"], + successMessage: "Export completed!", + refreshAfter: false +}; + +// ../app-todo/src/dashboards/index.ts +var dashboards_exports2 = {}; +__export(dashboards_exports2, { + TaskDashboard: () => TaskDashboard +}); + +// ../app-todo/src/dashboards/task.dashboard.ts +var TaskDashboard = { + name: "task_dashboard", + label: "Task Overview", + description: "Key task metrics and productivity overview", + widgets: [ + // Row 1: Key Metrics + { + id: "total_tasks", + title: "Total Tasks", + type: "metric", + object: "task", + aggregate: "count", + layout: { x: 0, y: 0, w: 3, h: 2 }, + options: { color: "#3B82F6" } + }, + { + id: "completed_today", + title: "Completed Today", + type: "metric", + object: "task", + filter: { is_completed: true, completed_date: { $gte: "{today_start}" } }, + aggregate: "count", + layout: { x: 3, y: 0, w: 3, h: 2 }, + options: { color: "#10B981" } + }, + { + id: "overdue_tasks", + title: "Overdue Tasks", + type: "metric", + object: "task", + filter: { is_overdue: true, is_completed: false }, + aggregate: "count", + layout: { x: 6, y: 0, w: 3, h: 2 }, + options: { color: "#EF4444" } + }, + { + id: "completion_rate", + title: "Completion Rate", + type: "metric", + object: "task", + filter: { created_date: { $gte: "{current_week_start}" } }, + valueField: "is_completed", + aggregate: "count", + layout: { x: 9, y: 0, w: 3, h: 2 }, + options: { suffix: "%", color: "#8B5CF6" } + }, + // Row 2: Task Distribution + { + id: "tasks_by_status", + title: "Tasks by Status", + type: "pie", + object: "task", + filter: { is_completed: false }, + categoryField: "status", + aggregate: "count", + layout: { x: 0, y: 2, w: 6, h: 4 }, + options: { showLegend: true } + }, + { + id: "tasks_by_priority", + title: "Tasks by Priority", + type: "bar", + object: "task", + filter: { is_completed: false }, + categoryField: "priority", + aggregate: "count", + layout: { x: 6, y: 2, w: 6, h: 4 }, + options: { horizontal: true } + }, + // Row 3: Trends + { + id: "weekly_task_completion", + title: "Weekly Task Completion", + type: "line", + object: "task", + filter: { is_completed: true, completed_date: { $gte: "{last_4_weeks}" } }, + categoryField: "completed_date", + aggregate: "count", + layout: { x: 0, y: 6, w: 8, h: 4 }, + options: { showDataLabels: true } + }, + { + id: "tasks_by_category", + title: "Tasks by Category", + type: "donut", + object: "task", + filter: { is_completed: false }, + categoryField: "category", + aggregate: "count", + layout: { x: 8, y: 6, w: 4, h: 4 }, + options: { showLegend: true } + }, + // Row 4: Tables + { + id: "overdue_tasks_table", + title: "Overdue Tasks", + type: "table", + object: "task", + filter: { is_overdue: true, is_completed: false }, + aggregate: "count", + layout: { x: 0, y: 10, w: 6, h: 4 } + }, + { + id: "due_today", + title: "Due Today", + type: "table", + object: "task", + filter: { due_date: "{today}", is_completed: false }, + aggregate: "count", + layout: { x: 6, y: 10, w: 6, h: 4 } + } + ] +}; + +// ../app-todo/src/reports/index.ts +var reports_exports2 = {}; +__export(reports_exports2, { + CompletedTasksReport: () => CompletedTasksReport, + OverdueTasksReport: () => OverdueTasksReport, + TasksByOwnerReport: () => TasksByOwnerReport2, + TasksByPriorityReport: () => TasksByPriorityReport, + TasksByStatusReport: () => TasksByStatusReport, + TimeTrackingReport: () => TimeTrackingReport +}); + +// ../app-todo/src/reports/task.report.ts +var TasksByStatusReport = { + name: "tasks_by_status", + label: "Tasks by Status", + description: "Summary of tasks grouped by status", + objectName: "task", + type: "summary", + columns: [ + { field: "subject", label: "Subject" }, + { field: "priority", label: "Priority" }, + { field: "due_date", label: "Due Date" }, + { field: "owner", label: "Assigned To" } + ], + groupingsDown: [{ field: "status", sortOrder: "asc" }] +}; +var TasksByPriorityReport = { + name: "tasks_by_priority", + label: "Tasks by Priority", + description: "Summary of tasks grouped by priority level", + objectName: "task", + type: "summary", + columns: [ + { field: "subject", label: "Subject" }, + { field: "status", label: "Status" }, + { field: "due_date", label: "Due Date" }, + { field: "category", label: "Category" } + ], + groupingsDown: [{ field: "priority", sortOrder: "desc" }], + filter: { is_completed: false } +}; +var TasksByOwnerReport2 = { + name: "tasks_by_owner", + label: "Tasks by Owner", + description: "Task summary by assignee", + objectName: "task", + type: "summary", + columns: [ + { field: "subject", label: "Subject" }, + { field: "status", label: "Status" }, + { field: "priority", label: "Priority" }, + { field: "due_date", label: "Due Date" }, + { field: "estimated_hours", label: "Est. Hours", aggregate: "sum" }, + { field: "actual_hours", label: "Actual Hours", aggregate: "sum" } + ], + groupingsDown: [{ field: "owner", sortOrder: "asc" }], + filter: { is_completed: false } +}; +var OverdueTasksReport = { + name: "overdue_tasks", + label: "Overdue Tasks", + description: "All overdue tasks that need attention", + objectName: "task", + type: "tabular", + columns: [ + { field: "subject", label: "Subject" }, + { field: "due_date", label: "Due Date" }, + { field: "priority", label: "Priority" }, + { field: "owner", label: "Assigned To" }, + { field: "category", label: "Category" } + ], + filter: { is_overdue: true, is_completed: false } +}; +var CompletedTasksReport = { + name: "completed_tasks", + label: "Completed Tasks", + description: "All completed tasks with time tracking", + objectName: "task", + type: "summary", + columns: [ + { field: "subject", label: "Subject" }, + { field: "completed_date", label: "Completed Date" }, + { field: "estimated_hours", label: "Est. Hours", aggregate: "sum" }, + { field: "actual_hours", label: "Actual Hours", aggregate: "sum" } + ], + groupingsDown: [{ field: "category", sortOrder: "asc" }], + filter: { is_completed: true } +}; +var TimeTrackingReport = { + name: "time_tracking", + label: "Time Tracking Report", + description: "Estimated vs actual hours analysis", + objectName: "task", + type: "matrix", + columns: [ + { field: "estimated_hours", label: "Estimated Hours", aggregate: "sum" }, + { field: "actual_hours", label: "Actual Hours", aggregate: "sum" } + ], + groupingsDown: [{ field: "owner", sortOrder: "asc" }], + groupingsAcross: [{ field: "category", sortOrder: "asc" }], + filter: { is_completed: true } +}; + +// ../app-todo/src/flows/task.flow.ts +var TaskReminderFlow = { + name: "task_reminder", + label: "Task Reminder Notification", + description: "Automated flow to send reminders for tasks approaching their due date", + type: "schedule", + variables: [ + { name: "tasksToRemind", type: "record_collection", isInput: false, isOutput: false } + ], + nodes: [ + { id: "start", type: "start", label: "Start (Daily 8 AM)", config: { schedule: "0 8 * * *", objectName: "task" } }, + { + id: "get_upcoming_tasks", + type: "get_record", + label: "Get Tasks Due Tomorrow", + config: { objectName: "task", filter: { due_date: "{tomorrow}", is_completed: false }, outputVariable: "tasksToRemind", getAll: true } + }, + { + id: "loop_tasks", + type: "loop", + label: "Loop Through Tasks", + config: { collection: "{tasksToRemind}", iteratorVariable: "currentTask" } + }, + { + id: "send_reminder", + type: "script", + label: "Send Reminder Email", + config: { + actionType: "email", + inputs: { + to: "{currentTask.owner.email}", + subject: "Task Due Tomorrow: {currentTask.subject}", + template: "task_reminder_email", + data: { taskSubject: "{currentTask.subject}", dueDate: "{currentTask.due_date}", priority: "{currentTask.priority}" } + } + } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "get_upcoming_tasks", type: "default" }, + { id: "e2", source: "get_upcoming_tasks", target: "loop_tasks", type: "default" }, + { id: "e3", source: "loop_tasks", target: "send_reminder", type: "default" }, + { id: "e4", source: "send_reminder", target: "end", type: "default" } + ] +}; +var OverdueEscalationFlow = { + name: "overdue_escalation", + label: "Overdue Task Escalation", + description: "Escalates tasks that have been overdue for more than 3 days", + type: "schedule", + variables: [ + { name: "overdueTasks", type: "record_collection", isInput: false, isOutput: false } + ], + nodes: [ + { id: "start", type: "start", label: "Start (Daily 9 AM)", config: { schedule: "0 9 * * *", objectName: "task" } }, + { + id: "get_overdue_tasks", + type: "get_record", + label: "Get Severely Overdue Tasks", + config: { + objectName: "task", + filter: { due_date: { $lt: "{3_days_ago}" }, is_completed: false, is_overdue: true }, + outputVariable: "overdueTasks", + getAll: true + } + }, + { + id: "loop_overdue", + type: "loop", + label: "Loop Through Overdue Tasks", + config: { collection: "{overdueTasks}", iteratorVariable: "currentTask" } + }, + { + id: "update_priority", + type: "update_record", + label: "Escalate Priority", + config: { + objectName: "task", + filter: { id: "{currentTask.id}" }, + fields: { priority: "urgent", tags: ["important", "follow_up"] } + } + }, + { + id: "notify_owner", + type: "script", + label: "Notify Task Owner", + config: { + actionType: "email", + inputs: { + to: "{currentTask.owner.email}", + subject: "URGENT: Task Overdue - {currentTask.subject}", + template: "overdue_escalation_email", + data: { taskSubject: "{currentTask.subject}", dueDate: "{currentTask.due_date}", daysOverdue: "{currentTask.days_overdue}" } + } + } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "get_overdue_tasks", type: "default" }, + { id: "e2", source: "get_overdue_tasks", target: "loop_overdue", type: "default" }, + { id: "e3", source: "loop_overdue", target: "update_priority", type: "default" }, + { id: "e4", source: "update_priority", target: "notify_owner", type: "default" }, + { id: "e5", source: "notify_owner", target: "end", type: "default" } + ] +}; +var TaskCompletionFlow = { + name: "task_completion", + label: "Task Completion Process", + description: "Flow triggered when a task is marked as complete", + type: "record_change", + variables: [ + { name: "taskId", type: "text", isInput: true, isOutput: false }, + { name: "completedTask", type: "record", isInput: false, isOutput: false } + ], + nodes: [ + { id: "start", type: "start", label: "Start", config: { objectName: "task", triggerCondition: 'ISCHANGED(status) AND status = "completed"' } }, + { + id: "get_task", + type: "get_record", + label: "Get Completed Task", + config: { objectName: "task", filter: { id: "{taskId}" }, outputVariable: "completedTask" } + }, + { + id: "check_recurring", + type: "decision", + label: "Is Recurring Task?", + config: { condition: "{completedTask.is_recurring} == true" } + }, + { + id: "create_next_task", + type: "create_record", + label: "Create Next Recurring Task", + config: { + objectName: "task", + fields: { + subject: "{completedTask.subject}", + description: "{completedTask.description}", + priority: "{completedTask.priority}", + category: "{completedTask.category}", + owner: "{completedTask.owner}", + is_recurring: true, + recurrence_type: "{completedTask.recurrence_type}", + recurrence_interval: "{completedTask.recurrence_interval}", + due_date: 'DATEADD({completedTask.due_date}, {completedTask.recurrence_interval}, "{completedTask.recurrence_type}")', + status: "not_started", + is_completed: false + }, + outputVariable: "newTaskId" + } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "get_task", type: "default" }, + { id: "e2", source: "get_task", target: "check_recurring", type: "default" }, + { id: "e3", source: "check_recurring", target: "create_next_task", type: "default", condition: "{completedTask.is_recurring} == true", label: "Yes" }, + { id: "e4", source: "check_recurring", target: "end", type: "default", condition: "{completedTask.is_recurring} != true", label: "No" }, + { id: "e5", source: "create_next_task", target: "end", type: "default" } + ] +}; +var QuickAddTaskFlow = { + name: "quick_add_task", + label: "Quick Add Task", + description: "Screen flow for quickly creating a new task", + type: "screen", + variables: [ + { name: "subject", type: "text", isInput: true, isOutput: false }, + { name: "priority", type: "text", isInput: true, isOutput: false }, + { name: "dueDate", type: "date", isInput: true, isOutput: false }, + { name: "newTaskId", type: "text", isInput: false, isOutput: true } + ], + nodes: [ + { id: "start", type: "start", label: "Start" }, + { + id: "screen_1", + type: "screen", + label: "Task Details", + config: { + fields: [ + { name: "subject", label: "Task Subject", type: "text", required: true }, + { name: "priority", label: "Priority", type: "select", options: ["low", "normal", "high", "urgent"], defaultValue: "normal" }, + { name: "dueDate", label: "Due Date", type: "date", required: false }, + { name: "category", label: "Category", type: "select", options: ["personal", "work", "shopping", "health", "finance", "other"] } + ] + } + }, + { + id: "create_task", + type: "create_record", + label: "Create Task", + config: { + objectName: "task", + fields: { subject: "{subject}", priority: "{priority}", due_date: "{dueDate}", category: "{category}", status: "not_started", owner: "{$User.Id}" }, + outputVariable: "newTaskId" + } + }, + { + id: "success_screen", + type: "screen", + label: "Success", + config: { + message: 'Task "{subject}" created successfully!', + buttons: [ + { label: "Create Another", action: "restart" }, + { label: "View Task", action: "navigate", target: "/task/{newTaskId}" }, + { label: "Done", action: "finish" } + ] + } + }, + { id: "end", type: "end", label: "End" } + ], + edges: [ + { id: "e1", source: "start", target: "screen_1", type: "default" }, + { id: "e2", source: "screen_1", target: "create_task", type: "default" }, + { id: "e3", source: "create_task", target: "success_screen", type: "default" }, + { id: "e4", source: "success_screen", target: "end", type: "default" } + ] +}; + +// ../app-todo/src/flows/index.ts +var allFlows2 = [ + TaskReminderFlow, + OverdueEscalationFlow, + TaskCompletionFlow, + QuickAddTaskFlow +]; + +// ../app-todo/src/apps/index.ts +var apps_exports2 = {}; +__export(apps_exports2, { + TodoApp: () => TodoApp +}); + +// ../app-todo/src/apps/todo.app.ts +var TodoApp = App.create({ + name: "todo_app", + label: "Todo Manager", + icon: "check-square", + branding: { + primaryColor: "#10B981", + secondaryColor: "#3B82F6", + logo: "/assets/todo-logo.png", + favicon: "/assets/todo-favicon.ico" + }, + navigation: [ + { + id: "group_tasks", + type: "group", + label: "Tasks", + icon: "check-square", + children: [ + { id: "nav_all_tasks", type: "object", objectName: "task", label: "All Tasks", icon: "list" }, + { id: "nav_my_tasks", type: "object", objectName: "task", label: "My Tasks", icon: "user-check" }, + { id: "nav_overdue", type: "object", objectName: "task", label: "Overdue", icon: "alert-circle" }, + { id: "nav_today", type: "object", objectName: "task", label: "Due Today", icon: "calendar" }, + { id: "nav_upcoming", type: "object", objectName: "task", label: "Upcoming", icon: "calendar-plus" } + ] + }, + { + id: "group_analytics", + type: "group", + label: "Analytics", + icon: "chart-bar", + children: [ + { id: "nav_dashboard", type: "dashboard", dashboardName: "task_dashboard", label: "Dashboard", icon: "layout-dashboard" } + ] + } + ] +}); + +// ../app-todo/src/translations/index.ts +var translations_exports2 = {}; +__export(translations_exports2, { + TodoTranslations: () => TodoTranslations +}); + +// ../app-todo/src/translations/en.ts +var en2 = { + objects: { + task: { + label: "Task", + pluralLabel: "Tasks", + fields: { + subject: { label: "Subject", help: "Brief title of the task" }, + description: { label: "Description" }, + status: { + label: "Status", + options: { + not_started: "Not Started", + in_progress: "In Progress", + waiting: "Waiting", + completed: "Completed", + deferred: "Deferred" + } + }, + priority: { + label: "Priority", + options: { + low: "Low", + normal: "Normal", + high: "High", + urgent: "Urgent" + } + }, + category: { + label: "Category", + options: { + personal: "Personal", + work: "Work", + shopping: "Shopping", + health: "Health", + finance: "Finance", + other: "Other" + } + }, + due_date: { label: "Due Date" }, + reminder_date: { label: "Reminder Date/Time" }, + completed_date: { label: "Completed Date" }, + owner: { label: "Assigned To" }, + tags: { + label: "Tags", + options: { + important: "Important", + quick_win: "Quick Win", + blocked: "Blocked", + follow_up: "Follow Up", + review: "Review" + } + }, + is_recurring: { label: "Recurring Task" }, + recurrence_type: { + label: "Recurrence Type", + options: { + daily: "Daily", + weekly: "Weekly", + monthly: "Monthly", + yearly: "Yearly" + } + }, + recurrence_interval: { label: "Recurrence Interval" }, + is_completed: { label: "Is Completed" }, + is_overdue: { label: "Is Overdue" }, + progress_percent: { label: "Progress (%)" }, + estimated_hours: { label: "Estimated Hours" }, + actual_hours: { label: "Actual Hours" }, + notes: { label: "Notes" }, + category_color: { label: "Category Color" } + } + } + }, + apps: { + todo_app: { + label: "Todo Manager", + description: "Personal task management application" + } + }, + messages: { + "common.save": "Save", + "common.cancel": "Cancel", + "common.delete": "Delete", + "common.edit": "Edit", + "common.create": "Create", + "common.search": "Search", + "common.filter": "Filter", + "common.sort": "Sort", + "common.refresh": "Refresh", + "common.export": "Export", + "common.back": "Back", + "common.confirm": "Confirm", + "success.saved": "Successfully saved", + "success.deleted": "Successfully deleted", + "success.completed": "Task marked as completed", + "confirm.delete": "Are you sure you want to delete this task?", + "confirm.complete": "Mark this task as completed?", + "error.required": "This field is required", + "error.load_failed": "Failed to load data" + }, + validationMessages: { + completed_date_required: "Completed date is required when status is Completed", + recurrence_fields_required: "Recurrence type is required for recurring tasks" + } +}; + +// ../app-todo/src/translations/zh-CN.ts +var zhCN2 = { + objects: { + task: { + label: "\u4EFB\u52A1", + pluralLabel: "\u4EFB\u52A1", + fields: { + subject: { label: "\u4E3B\u9898", help: "\u4EFB\u52A1\u7684\u7B80\u8981\u6807\u9898" }, + description: { label: "\u63CF\u8FF0" }, + status: { + label: "\u72B6\u6001", + options: { + not_started: "\u672A\u5F00\u59CB", + in_progress: "\u8FDB\u884C\u4E2D", + waiting: "\u7B49\u5F85\u4E2D", + completed: "\u5DF2\u5B8C\u6210", + deferred: "\u5DF2\u63A8\u8FDF" + } + }, + priority: { + label: "\u4F18\u5148\u7EA7", + options: { + low: "\u4F4E", + normal: "\u666E\u901A", + high: "\u9AD8", + urgent: "\u7D27\u6025" + } + }, + category: { + label: "\u5206\u7C7B", + options: { + personal: "\u4E2A\u4EBA", + work: "\u5DE5\u4F5C", + shopping: "\u8D2D\u7269", + health: "\u5065\u5EB7", + finance: "\u8D22\u52A1", + other: "\u5176\u4ED6" + } + }, + due_date: { label: "\u622A\u6B62\u65E5\u671F" }, + reminder_date: { label: "\u63D0\u9192\u65E5\u671F/\u65F6\u95F4" }, + completed_date: { label: "\u5B8C\u6210\u65E5\u671F" }, + owner: { label: "\u8D1F\u8D23\u4EBA" }, + tags: { + label: "\u6807\u7B7E", + options: { + important: "\u91CD\u8981", + quick_win: "\u901F\u80DC", + blocked: "\u53D7\u963B", + follow_up: "\u5F85\u8DDF\u8FDB", + review: "\u5F85\u5BA1\u6838" + } + }, + is_recurring: { label: "\u5468\u671F\u6027\u4EFB\u52A1" }, + recurrence_type: { + label: "\u91CD\u590D\u7C7B\u578B", + options: { + daily: "\u6BCF\u5929", + weekly: "\u6BCF\u5468", + monthly: "\u6BCF\u6708", + yearly: "\u6BCF\u5E74" + } + }, + recurrence_interval: { label: "\u91CD\u590D\u95F4\u9694" }, + is_completed: { label: "\u662F\u5426\u5B8C\u6210" }, + is_overdue: { label: "\u662F\u5426\u903E\u671F" }, + progress_percent: { label: "\u8FDB\u5EA6 (%)" }, + estimated_hours: { label: "\u9884\u4F30\u5DE5\u65F6" }, + actual_hours: { label: "\u5B9E\u9645\u5DE5\u65F6" }, + notes: { label: "\u5907\u6CE8" }, + category_color: { label: "\u5206\u7C7B\u989C\u8272" } + } + } + }, + apps: { + todo_app: { + label: "\u5F85\u529E\u7BA1\u7406", + description: "\u4E2A\u4EBA\u4EFB\u52A1\u7BA1\u7406\u5E94\u7528" + } + }, + messages: { + "common.save": "\u4FDD\u5B58", + "common.cancel": "\u53D6\u6D88", + "common.delete": "\u5220\u9664", + "common.edit": "\u7F16\u8F91", + "common.create": "\u65B0\u5EFA", + "common.search": "\u641C\u7D22", + "common.filter": "\u7B5B\u9009", + "common.sort": "\u6392\u5E8F", + "common.refresh": "\u5237\u65B0", + "common.export": "\u5BFC\u51FA", + "common.back": "\u8FD4\u56DE", + "common.confirm": "\u786E\u8BA4", + "success.saved": "\u4FDD\u5B58\u6210\u529F", + "success.deleted": "\u5220\u9664\u6210\u529F", + "success.completed": "\u4EFB\u52A1\u5DF2\u6807\u8BB0\u4E3A\u5B8C\u6210", + "confirm.delete": "\u786E\u5B9A\u8981\u5220\u9664\u6B64\u4EFB\u52A1\u5417\uFF1F", + "confirm.complete": "\u786E\u5B9A\u5C06\u6B64\u4EFB\u52A1\u6807\u8BB0\u4E3A\u5B8C\u6210\uFF1F", + "error.required": "\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879", + "error.load_failed": "\u6570\u636E\u52A0\u8F7D\u5931\u8D25" + }, + validationMessages: { + completed_date_required: '\u72B6\u6001\u4E3A"\u5DF2\u5B8C\u6210"\u65F6\uFF0C\u5B8C\u6210\u65E5\u671F\u4E3A\u5FC5\u586B\u9879', + recurrence_fields_required: "\u5468\u671F\u6027\u4EFB\u52A1\u5FC5\u987B\u6307\u5B9A\u91CD\u590D\u7C7B\u578B" + } +}; + +// ../app-todo/src/translations/ja-JP.ts +var jaJP2 = { + objects: { + task: { + label: "\u30BF\u30B9\u30AF", + pluralLabel: "\u30BF\u30B9\u30AF", + fields: { + subject: { label: "\u4EF6\u540D", help: "\u30BF\u30B9\u30AF\u306E\u7C21\u5358\u306A\u30BF\u30A4\u30C8\u30EB" }, + description: { label: "\u8AAC\u660E" }, + status: { + label: "\u30B9\u30C6\u30FC\u30BF\u30B9", + options: { + not_started: "\u672A\u7740\u624B", + in_progress: "\u9032\u884C\u4E2D", + waiting: "\u5F85\u6A5F\u4E2D", + completed: "\u5B8C\u4E86", + deferred: "\u5EF6\u671F" + } + }, + priority: { + label: "\u512A\u5148\u5EA6", + options: { + low: "\u4F4E", + normal: "\u901A\u5E38", + high: "\u9AD8", + urgent: "\u7DCA\u6025" + } + }, + category: { + label: "\u30AB\u30C6\u30B4\u30EA", + options: { + personal: "\u500B\u4EBA", + work: "\u4ED5\u4E8B", + shopping: "\u8CB7\u3044\u7269", + health: "\u5065\u5EB7", + finance: "\u8CA1\u52D9", + other: "\u305D\u306E\u4ED6" + } + }, + due_date: { label: "\u671F\u65E5" }, + reminder_date: { label: "\u30EA\u30DE\u30A4\u30F3\u30C0\u30FC\u65E5\u6642" }, + completed_date: { label: "\u5B8C\u4E86\u65E5" }, + owner: { label: "\u62C5\u5F53\u8005" }, + tags: { + label: "\u30BF\u30B0", + options: { + important: "\u91CD\u8981", + quick_win: "\u30AF\u30A4\u30C3\u30AF\u30A6\u30A3\u30F3", + blocked: "\u30D6\u30ED\u30C3\u30AF\u4E2D", + follow_up: "\u30D5\u30A9\u30ED\u30FC\u30A2\u30C3\u30D7", + review: "\u30EC\u30D3\u30E5\u30FC" + } + }, + is_recurring: { label: "\u7E70\u308A\u8FD4\u3057\u30BF\u30B9\u30AF" }, + recurrence_type: { + label: "\u7E70\u308A\u8FD4\u3057\u30BF\u30A4\u30D7", + options: { + daily: "\u6BCE\u65E5", + weekly: "\u6BCE\u9031", + monthly: "\u6BCE\u6708", + yearly: "\u6BCE\u5E74" + } + }, + recurrence_interval: { label: "\u7E70\u308A\u8FD4\u3057\u9593\u9694" }, + is_completed: { label: "\u5B8C\u4E86\u6E08\u307F" }, + is_overdue: { label: "\u671F\u9650\u8D85\u904E" }, + progress_percent: { label: "\u9032\u6357\u7387 (%)" }, + estimated_hours: { label: "\u898B\u7A4D\u6642\u9593" }, + actual_hours: { label: "\u5B9F\u7E3E\u6642\u9593" }, + notes: { label: "\u30E1\u30E2" }, + category_color: { label: "\u30AB\u30C6\u30B4\u30EA\u8272" } + } + } + }, + apps: { + todo_app: { + label: "ToDo \u30DE\u30CD\u30FC\u30B8\u30E3\u30FC", + description: "\u500B\u4EBA\u30BF\u30B9\u30AF\u7BA1\u7406\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3" + } + }, + messages: { + "common.save": "\u4FDD\u5B58", + "common.cancel": "\u30AD\u30E3\u30F3\u30BB\u30EB", + "common.delete": "\u524A\u9664", + "common.edit": "\u7DE8\u96C6", + "common.create": "\u65B0\u898F\u4F5C\u6210", + "common.search": "\u691C\u7D22", + "common.filter": "\u30D5\u30A3\u30EB\u30BF\u30FC", + "common.sort": "\u4E26\u3079\u66FF\u3048", + "common.refresh": "\u66F4\u65B0", + "common.export": "\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8", + "common.back": "\u623B\u308B", + "common.confirm": "\u78BA\u8A8D", + "success.saved": "\u4FDD\u5B58\u3057\u307E\u3057\u305F", + "success.deleted": "\u524A\u9664\u3057\u307E\u3057\u305F", + "success.completed": "\u30BF\u30B9\u30AF\u3092\u5B8C\u4E86\u306B\u3057\u307E\u3057\u305F", + "confirm.delete": "\u3053\u306E\u30BF\u30B9\u30AF\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F", + "confirm.complete": "\u3053\u306E\u30BF\u30B9\u30AF\u3092\u5B8C\u4E86\u306B\u3057\u307E\u3059\u304B\uFF1F", + "error.required": "\u3053\u306E\u9805\u76EE\u306F\u5FC5\u9808\u3067\u3059", + "error.load_failed": "\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F" + }, + validationMessages: { + completed_date_required: "\u30B9\u30C6\u30FC\u30BF\u30B9\u304C\u300C\u5B8C\u4E86\u300D\u306E\u5834\u5408\u3001\u5B8C\u4E86\u65E5\u306F\u5FC5\u9808\u3067\u3059", + recurrence_fields_required: "\u7E70\u308A\u8FD4\u3057\u30BF\u30B9\u30AF\u306B\u306F\u7E70\u308A\u8FD4\u3057\u30BF\u30A4\u30D7\u304C\u5FC5\u8981\u3067\u3059" + } +}; + +// ../app-todo/src/translations/todo.translation.ts +var TodoTranslations = { + en: en2, + "zh-CN": zhCN2, + "ja-JP": jaJP2 +}; + +// ../app-todo/objectstack.config.ts +var objectstack_config_default2 = defineStack({ + manifest: { + id: "com.example.todo", + namespace: "todo", + version: "2.0.0", + type: "app", + name: "Todo Manager", + description: "A comprehensive Todo app demonstrating ObjectStack Protocol features including automation, dashboards, and reports" + }, + // Seed Data (top-level, registered as metadata) + data: [ + { + object: "task", + mode: "upsert", + externalId: "subject", + records: [ + { subject: "Learn ObjectStack", status: "completed", priority: "high", category: "work" }, + { subject: "Build a cool app", status: "in_progress", priority: "normal", category: "work", due_date: new Date(Date.now() + 864e5 * 3) }, + { subject: "Review PR #102", status: "completed", priority: "high", category: "work" }, + { subject: "Write Documentation", status: "not_started", priority: "normal", category: "work", due_date: new Date(Date.now() + 864e5) }, + { subject: "Fix Server bug", status: "waiting", priority: "urgent", category: "work" }, + { subject: "Buy groceries", status: "not_started", priority: "low", category: "shopping", due_date: /* @__PURE__ */ new Date() }, + { subject: "Schedule dentist appointment", status: "not_started", priority: "normal", category: "health", due_date: new Date(Date.now() + 864e5 * 7) }, + { subject: "Pay utility bills", status: "not_started", priority: "high", category: "finance", due_date: new Date(Date.now() + 864e5 * 2) } + ] + } + ], + // Auto-collected from barrel index files via Object.values() + objects: Object.values(objects_exports2), + actions: Object.values(actions_exports2), + dashboards: Object.values(dashboards_exports2), + reports: Object.values(reports_exports2), + flows: allFlows2, + apps: Object.values(apps_exports2), + // I18n Configuration — per-locale file organization + i18n: { + defaultLocale: "en", + supportedLocales: ["en", "zh-CN", "ja-JP"], + fallbackLocale: "en", + fileOrganization: "per_locale" + }, + // I18n Translation Bundles (en, zh-CN, ja-JP) + translations: Object.values(translations_exports2) +}); + +// ../plugin-bi/objectstack.config.ts +var objectstack_config_default3 = defineStack({ + manifest: { + id: "com.example.bi", + namespace: "bi", + version: "1.0.0", + type: "plugin", + name: "BI Plugin", + description: "Business Intelligence dashboards and analytics" + }, + // Placeholder - no objects or dashboards yet + objects: [], + dashboards: [] +}); + +// server/index.ts +var _kernel = null; +var _app = null; +var _bootPromise = null; +async function ensureKernel() { + if (_kernel) return _kernel; + if (_bootPromise) return _bootPromise; + _bootPromise = (async () => { + console.log("[Vercel] Booting ObjectStack Kernel (app-host)..."); + try { + const kernel = new ObjectKernel(); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new DriverPlugin(new InMemoryDriver())); + const vercelUrl = process.env.VERCEL_PROJECT_PRODUCTION_URL ? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` : process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : "http://localhost:3000"; + await kernel.use(new AuthPlugin({ + secret: process.env.AUTH_SECRET || "dev-secret-please-change-in-production-min-32-chars", + baseUrl: vercelUrl + })); + await kernel.use(new AppPlugin(objectstack_config_default)); + await kernel.use(new AppPlugin(objectstack_config_default2)); + await kernel.use(new AppPlugin(objectstack_config_default3)); + await kernel.bootstrap(); + _kernel = kernel; + console.log("[Vercel] Kernel ready."); + return kernel; + } catch (err) { + _bootPromise = null; + console.error("[Vercel] Kernel boot failed:", err?.message || err); + throw err; + } + })(); + return _bootPromise; +} +async function ensureApp() { + if (_app) return _app; + const kernel = await ensureKernel(); + _app = createHonoApp({ kernel, prefix: "/api/v1" }); + return _app; +} +function extractBody(incoming, method, contentType) { + if (method === "GET" || method === "HEAD" || method === "OPTIONS") return null; + if (incoming.rawBody != null) { + return incoming.rawBody; + } + if (incoming.body != null) { + if (typeof incoming.body === "string") return incoming.body; + if (contentType?.includes("application/json")) return JSON.stringify(incoming.body); + return String(incoming.body); + } + return null; +} +function resolvePublicUrl(requestUrl, incoming) { + if (!incoming) return requestUrl; + const fwdProto = incoming.headers?.["x-forwarded-proto"]; + const rawProto = Array.isArray(fwdProto) ? fwdProto[0] : fwdProto; + const proto = rawProto === "https" || rawProto === "http" ? rawProto : void 0; + if (proto === "https" && requestUrl.startsWith("http:")) { + return requestUrl.replace(/^http:/, "https:"); + } + return requestUrl; +} +var index_default = getRequestListener(async (request, env2) => { + let app; + try { + app = await ensureApp(); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + console.error("[Vercel] Handler error \u2014 bootstrap did not complete:", message2); + return new Response( + JSON.stringify({ + success: false, + error: { + message: "Service Unavailable \u2014 kernel bootstrap failed.", + code: 503 + } + }), + { status: 503, headers: { "content-type": "application/json" } } + ); + } + const method = request.method.toUpperCase(); + const incoming = env2?.incoming; + const url2 = resolvePublicUrl(request.url, incoming); + console.log(`[Vercel] ${method} ${url2}`); + if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && incoming) { + const contentType = incoming.headers?.["content-type"]; + const contentTypeStr = Array.isArray(contentType) ? contentType[0] : contentType; + const body = extractBody(incoming, method, contentTypeStr); + if (body != null) { + return await app.fetch( + new Request(url2, { method, headers: request.headers, body }) + ); + } + } + return await app.fetch( + new Request(url2, { method, headers: request.headers }) + ); +}); +var config3 = { + memory: 1024, + maxDuration: 60 +}; +export { + config3 as config, + index_default as default +}; +/*! Bundled license information: + +@noble/ciphers/utils.js: + (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *) +*/ +//# sourceMappingURL=_handler.js.map diff --git a/examples/app-host/api/_handler.js.map b/examples/app-host/api/_handler.js.map new file mode 100644 index 000000000..7e3a3855a --- /dev/null +++ b/examples/app-host/api/_handler.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js", "../../../packages/spec/src/data/filter.zod.ts", "../../../packages/spec/src/data/query.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/data/validation.zod.ts", "../../../packages/spec/src/automation/state-machine.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/data/object.zod.ts", "../../../packages/spec/src/data/hook.zod.ts", "../../../packages/spec/src/data/mapping.zod.ts", "../../../packages/spec/src/kernel/execution-context.zod.ts", "../../../packages/spec/src/data/data-engine.zod.ts", "../../../packages/spec/src/shared/enums.zod.ts", "../../../packages/spec/src/data/driver.zod.ts", "../../../packages/spec/src/data/driver-sql.zod.ts", "../../../packages/spec/src/data/driver-nosql.zod.ts", "../../../packages/spec/src/data/dataset.zod.ts", "../../../packages/spec/src/data/seed-loader.zod.ts", "../../../packages/spec/src/data/document.zod.ts", "../../../packages/spec/src/shared/mapping.zod.ts", "../../../packages/spec/src/data/external-lookup.zod.ts", "../../../packages/spec/src/data/datasource.zod.ts", "../../../packages/spec/src/data/analytics.zod.ts", "../../../packages/spec/src/data/feed.zod.ts", "../../../packages/spec/src/data/subscription.zod.ts", "../../../packages/spec/src/data/driver/turso-multi-tenant.zod.ts", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_hash.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/lazy.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/aggregator.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/push.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/accumulator.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/addToSet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/avg.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sort.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottomN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottom.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/count.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covariancePop.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covarianceSamp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/first.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/firstN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/last.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/lastN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/max.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/maxN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/percentile.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/median.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/mergeObjects.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/min.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/minN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevPop.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevSamp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/sum.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/topN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/top.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/abs.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/add.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ceil.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/divide.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/exp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/floor.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ln.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log10.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/mod.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/multiply.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/pow.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/round.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sigmoid.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sqrt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/subtract.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/trunc.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayElemAt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayToObject.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/concatArrays.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/filter.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/first.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/firstN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/in.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/indexOfArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/isArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/last.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/lastN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/map.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/maxN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/minN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/range.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reduce.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reverseArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/size.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/slice.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/sortArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/zip.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitAnd.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitNot.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitOr.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitXor.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/and.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/not.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/or.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/cmp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/limit.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/documents.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/project.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/skip.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/cursor.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/query.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/_predicates.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/eq.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gte.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lte.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/ne.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/cond.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/ifNull.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/switch.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/function.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateAdd.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateDiff.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromParts.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromString.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateSubtract.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToParts.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToString.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateTrunc.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfMonth.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfWeek.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfYear.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/hour.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoDayOfWeek.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeek.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeekYear.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/millisecond.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/minute.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/month.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/second.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/week.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/year.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/literal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/median.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/getField.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/rand.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/sampleRate.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/mergeObjects.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/objectToArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/setField.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/unsetField.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/percentile.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/allElementsTrue.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/anyElementTrue.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setDifference.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setEquals.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIntersection.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIsSubset.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setUnion.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/concat.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/indexOfBytes.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/ltrim.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFind.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFindAll.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexMatch.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceAll.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceOne.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/rtrim.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/split.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strcasecmp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenBytes.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenCP.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrBytes.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substr.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrCP.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toBool.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDate.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDouble.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toInt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toLong.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toString.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/convert.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/isNumber.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDecimal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/type.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toLower.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toUpper.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/trim.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/toHashedIndexKey.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acos.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acosh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asin.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asinh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan2.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atanh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cos.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cosh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/degreesToRadians.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/radiansToDegrees.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sin.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sinh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tan.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tanh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/let.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/addFields.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucket.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucketAuto.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/count.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/densify.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/facet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/linearFill.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/locf.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/group.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/setWindowFields.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/fill.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/lookup.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/graphLookup.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/match.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/merge.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/out.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/redact.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceRoot.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceWith.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sample.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/set.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sortByCount.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unionWith.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unset.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unwind.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/elemMatch.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/slice.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/all.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/elemMatch.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/size.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllClear.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllSet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnyClear.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnySet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/eq.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gte.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/in.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lte.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/ne.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/nin.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/exists.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/type.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/expr.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/jsonSchema.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/mod.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/regex.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/where.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/and.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/or.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/nor.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/not.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/denseRank.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/derivative.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/documentNumber.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/expMovingAvg.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/integral.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/minMaxScaler.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/rank.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/shift.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/addToSet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/bit.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/currentDate.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/inc.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/max.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/min.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/mul.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pop.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pull.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pullAll.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/push.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/set.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/rename.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/unset.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/updater.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/index.js", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/env-impl.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/color-depth.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/logger.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/index.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/error-codes.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/codes.mjs", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/error.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/index.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/random.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/get-tables.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/json.mjs", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/trace/SemanticAttributes.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/trace/index.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/resource/SemanticResourceAttributes.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/resource/index.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/stable_attributes.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/stable_metrics.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/stable_events.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/index.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/attributes.mjs", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/platform/node/globalThis.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/platform/node/index.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/platform/index.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/version.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/internal/semver.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/internal/global-utils.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/diag/types.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/api/diag.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/context/context.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/context/NoopContextManager.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/api/context.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/trace_flags.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/invalid-span-constants.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/NonRecordingSpan.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/context-utils.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/spancontext-utils.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/NoopTracer.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/ProxyTracer.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/NoopTracerProvider.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/ProxyTracerProvider.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/status.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/api/trace.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace-api.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/index.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/tracer.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/id.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/utils.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/factory.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/index.mjs", "../../../node_modules/.pnpm/@better-auth+memory-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_9b6e7edc5b5cf527f9fdae30e619266b/node_modules/@better-auth/memory-adapter/dist/index.mjs", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/string.mjs", "../../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/bun-sqlite-dialect-na--YwnN.mjs", "../../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/node-sqlite-dialect.mjs", "../../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/d1-sqlite-dialect-C2B7YsIT.mjs", "../../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs", "../../../packages/spec/src/system/cache.zod.ts", "../../../packages/spec/src/system/disaster-recovery.zod.ts", "../../../packages/spec/src/system/message-queue.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/system/object-storage.zod.ts", "../../../packages/spec/src/system/search-engine.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/system/http-server.zod.ts", "../../../packages/spec/src/system/audit.zod.ts", "../../../packages/spec/src/system/logging.zod.ts", "../../../packages/spec/src/system/metrics.zod.ts", "../../../packages/spec/src/system/tracing.zod.ts", "../../../packages/spec/src/system/security-context.zod.ts", "../../../packages/spec/src/system/change-management.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/data/validation.zod.ts", "../../../packages/spec/src/automation/state-machine.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/data/object.zod.ts", "../../../packages/spec/src/system/migration.zod.ts", "../../../packages/spec/src/system/auth-config.zod.ts", "../../../packages/spec/src/system/compliance.zod.ts", "../../../packages/spec/src/system/incident-response.zod.ts", "../../../packages/spec/src/system/supplier-security.zod.ts", "../../../packages/spec/src/system/training.zod.ts", "../../../packages/spec/src/system/job.zod.ts", "../../../packages/spec/src/system/worker.zod.ts", "../../../packages/spec/src/system/notification.zod.ts", "../../../packages/spec/src/system/translation.zod.ts", "../../../packages/spec/src/system/translation-skeleton.ts", "../../../packages/spec/src/system/collaboration.zod.ts", "../../../packages/spec/src/system/metadata-persistence.zod.ts", "../../../packages/spec/src/system/core-services.zod.ts", "../../../packages/spec/src/system/tenant.zod.ts", "../../../packages/spec/src/system/license.zod.ts", "../../../packages/spec/src/system/registry-config.zod.ts", "../../../packages/spec/src/system/provisioning.zod.ts", "../../../packages/spec/src/system/deploy-bundle.zod.ts", "../../../packages/spec/src/system/app-install.zod.ts", "../../../packages/spec/src/system/constants/paths.ts", "../../../packages/spec/src/system/constants/system-names.ts", "../../../packages/core/src/kernel-base.ts", "../../../packages/core/src/utils/env.ts", "../../../packages/core/src/logger.ts", "../../../packages/core/src/kernel.ts", "../../../packages/core/src/security/plugin-config-validator.ts", "../../../packages/core/src/plugin-loader.ts", "../../../packages/core/src/fallbacks/memory-cache.ts", "../../../packages/core/src/fallbacks/memory-queue.ts", "../../../packages/core/src/fallbacks/memory-job.ts", "../../../packages/core/src/fallbacks/memory-i18n.ts", "../../../packages/core/src/fallbacks/memory-metadata.ts", "../../../packages/core/src/fallbacks/index.ts", "../../../packages/core/src/lite-kernel.ts", "../../../packages/core/src/api-registry.ts", "../../../packages/core/src/api-registry-plugin.ts", "../../../packages/core/src/qa/index.ts", "../../../packages/core/src/qa/runner.ts", "../../../packages/core/src/qa/http-adapter.ts", "../../../packages/core/src/security/plugin-signature-verifier.ts", "../../../packages/core/src/security/plugin-permission-enforcer.ts", "../../../packages/core/src/security/permission-manager.ts", "../../../packages/core/src/security/sandbox-runtime.ts", "../../../packages/core/src/security/security-scanner.ts", "../../../packages/core/src/health-monitor.ts", "../../../packages/core/src/hot-reload.ts", "../../../packages/core/src/dependency-resolver.ts", "../../../packages/core/src/namespace-resolver.ts", "../../../packages/core/src/package-manager.ts", "../../../packages/spec/src/data/filter.zod.ts", "../../../packages/spec/src/data/query.zod.ts", "../../../packages/spec/src/api/contract.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/api/endpoint.zod.ts", "../../../packages/spec/src/api/discovery.zod.ts", "../../../packages/spec/src/api/events.zod.ts", "../../../packages/spec/src/api/realtime-shared.zod.ts", "../../../packages/spec/src/api/realtime.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/api/websocket.zod.ts", "../../../packages/spec/src/api/router.zod.ts", "../../../packages/spec/src/api/odata.zod.ts", "../../../packages/spec/src/api/graphql.zod.ts", "../../../packages/spec/src/api/batch.zod.ts", "../../../packages/spec/src/api/http-cache.zod.ts", "../../../packages/spec/src/api/errors.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/sharing.zod.ts", "../../../packages/spec/src/ui/responsive.zod.ts", "../../../packages/spec/src/ui/view.zod.ts", "../../../packages/spec/src/security/rls.zod.ts", "../../../packages/spec/src/security/permission.zod.ts", "../../../packages/spec/src/automation/workflow.zod.ts", "../../../packages/spec/src/system/translation.zod.ts", "../../../packages/spec/src/kernel/plugin-capability.zod.ts", "../../../packages/spec/src/kernel/plugin-loading.zod.ts", "../../../packages/spec/src/kernel/plugin.zod.ts", "../../../packages/spec/src/data/dataset.zod.ts", "../../../packages/spec/src/kernel/manifest.zod.ts", "../../../packages/spec/src/kernel/dependency-resolution.zod.ts", "../../../packages/spec/src/kernel/package-registry.zod.ts", "../../../packages/spec/src/api/protocol.zod.ts", "../../../packages/spec/src/api/rest-server.zod.ts", "../../../packages/spec/src/api/registry.zod.ts", "../../../packages/spec/src/api/documentation.zod.ts", "../../../packages/spec/src/data/analytics.zod.ts", "../../../packages/spec/src/api/analytics.zod.ts", "../../../packages/spec/src/api/versioning.zod.ts", "../../../packages/spec/src/api/auth.zod.ts", "../../../packages/spec/src/api/auth-endpoints.zod.ts", "../../../packages/spec/src/system/object-storage.zod.ts", "../../../packages/spec/src/api/storage.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/data/validation.zod.ts", "../../../packages/spec/src/automation/state-machine.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/data/object.zod.ts", "../../../packages/spec/src/ui/app.zod.ts", "../../../packages/spec/src/kernel/metadata-loader.zod.ts", "../../../packages/spec/src/kernel/metadata-customization.zod.ts", "../../../packages/spec/src/kernel/metadata-plugin.zod.ts", "../../../packages/spec/src/api/metadata.zod.ts", "../../../packages/spec/src/system/core-services.zod.ts", "../../../packages/spec/src/api/dispatcher.zod.ts", "../../../packages/spec/src/system/http-server.zod.ts", "../../../packages/spec/src/api/plugin-rest-api.zod.ts", "../../../packages/spec/src/api/query-adapter.zod.ts", "../../../packages/spec/src/data/feed.zod.ts", "../../../packages/spec/src/data/subscription.zod.ts", "../../../packages/spec/src/api/feed-api.zod.ts", "../../../packages/spec/src/api/export.zod.ts", "../../../packages/spec/src/automation/flow.zod.ts", "../../../packages/spec/src/automation/execution.zod.ts", "../../../packages/spec/src/api/automation-api.zod.ts", "../../../packages/spec/src/kernel/package-upgrade.zod.ts", "../../../packages/spec/src/kernel/package-artifact.zod.ts", "../../../packages/spec/src/cloud/marketplace.zod.ts", "../../../packages/spec/src/api/package-api.zod.ts", "../../../packages/runtime/src/index.ts", "../../../packages/runtime/src/runtime.ts", "../../../packages/runtime/src/driver-plugin.ts", "../../../packages/runtime/src/seed-loader.ts", "../../../packages/runtime/src/app-plugin.ts", "../../../packages/runtime/src/http-dispatcher.ts", "../../../packages/runtime/src/dispatcher-plugin.ts", "../../../packages/runtime/src/http-server.ts", "../../../packages/runtime/src/middleware.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/shared/mapping.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/shared/enums.zod.ts", "../../../packages/spec/src/shared/metadata-types.zod.ts", "../../../packages/spec/src/shared/branded-types.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/shared/suggestions.zod.ts", "../../../packages/spec/src/shared/error-map.zod.ts", "../../../packages/spec/src/shared/metadata-collection.zod.ts", "../../../packages/objectql/src/registry.ts", "../../../packages/objectql/src/protocol.ts", "../../../packages/objectql/src/engine.ts", "../../../packages/objectql/src/metadata-facade.ts", "../../../packages/objectql/src/plugin.ts", "../../../packages/objectql/src/kernel-factory.ts", "../../../packages/objectql/src/util.ts", "../../../packages/spec/src/kernel/cli-extension.zod.ts", "../../../packages/spec/src/kernel/package-artifact.zod.ts", "../../../packages/spec/src/kernel/cli-plugin-commands.zod.ts", "../../../packages/spec/src/system/tenant.zod.ts", "../../../packages/spec/src/kernel/context.zod.ts", "../../../packages/spec/src/kernel/dependency-resolution.zod.ts", "../../../packages/spec/src/kernel/dev-plugin.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/kernel/events/core.zod.ts", "../../../packages/spec/src/kernel/events/handlers.zod.ts", "../../../packages/spec/src/kernel/events/queue.zod.ts", "../../../packages/spec/src/kernel/events/dlq.zod.ts", "../../../packages/spec/src/kernel/events/integrations.zod.ts", "../../../packages/spec/src/kernel/events/bus.zod.ts", "../../../packages/spec/src/kernel/feature.zod.ts", "../../../packages/spec/src/kernel/plugin-capability.zod.ts", "../../../packages/spec/src/kernel/plugin-loading.zod.ts", "../../../packages/spec/src/kernel/plugin.zod.ts", "../../../packages/spec/src/data/dataset.zod.ts", "../../../packages/spec/src/kernel/manifest.zod.ts", "../../../packages/spec/src/kernel/metadata-customization.zod.ts", "../../../packages/spec/src/kernel/metadata-loader.zod.ts", "../../../packages/spec/src/kernel/metadata-plugin.zod.ts", "../../../packages/spec/src/kernel/package-registry.zod.ts", "../../../packages/spec/src/kernel/package-upgrade.zod.ts", "../../../packages/spec/src/kernel/plugin-lifecycle-advanced.zod.ts", "../../../packages/spec/src/kernel/plugin-lifecycle-events.zod.ts", "../../../packages/spec/src/kernel/plugin-runtime.zod.ts", "../../../packages/spec/src/kernel/plugin-security-advanced.zod.ts", "../../../packages/spec/src/kernel/plugin-structure.zod.ts", "../../../packages/spec/src/kernel/plugin-validator.zod.ts", "../../../packages/spec/src/kernel/plugin-versioning.zod.ts", "../../../packages/spec/src/kernel/service-registry.zod.ts", "../../../packages/spec/src/kernel/startup-orchestrator.zod.ts", "../../../packages/spec/src/kernel/plugin-registry.zod.ts", "../../../packages/spec/src/kernel/plugin-security.zod.ts", "../../../packages/spec/src/kernel/execution-context.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/chart.zod.ts", "../../../packages/spec/src/ui/responsive.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/ui/sharing.zod.ts", "../../../packages/spec/src/ui/app.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/ui/view.zod.ts", "../../../packages/spec/src/data/filter.zod.ts", "../../../packages/spec/src/ui/dashboard.zod.ts", "../../../packages/spec/src/ui/report.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/shared/enums.zod.ts", "../../../packages/spec/src/ui/page.zod.ts", "../../../packages/spec/src/ui/widget.zod.ts", "../../../packages/spec/src/data/feed.zod.ts", "../../../packages/spec/src/ui/component.zod.ts", "../../../packages/spec/src/ui/touch.zod.ts", "../../../packages/spec/src/ui/keyboard.zod.ts", "../../../packages/spec/src/ui/theme.zod.ts", "../../../packages/spec/src/ui/offline.zod.ts", "../../../packages/spec/src/ui/animation.zod.ts", "../../../packages/spec/src/ui/notification.zod.ts", "../../../packages/spec/src/ui/dnd.zod.ts", "../../../packages/plugins/driver-memory/src/persistence/local-storage-adapter.ts", "../../../packages/plugins/driver-memory/src/persistence/file-adapter.ts", "../../../packages/plugins/driver-memory/src/memory-driver.ts", "../../../packages/plugins/driver-memory/src/memory-matcher.ts", "../../../packages/plugins/driver-memory/src/index.ts", "../../../packages/plugins/driver-memory/src/memory-analytics.ts", "../../../packages/plugins/driver-memory/src/in-memory-strategy.ts", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/compose.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/request/constants.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/body.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/url.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/request.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/html.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/context.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/constants.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/hono-base.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/matcher.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/node.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/trie.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/router.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/smart-router/router.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/trie-router/node.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/trie-router/router.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/hono.js", "../../../packages/adapters/hono/src/index.ts", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/wildcard.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/url.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/random.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/buffer.mjs", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/hkdf.ts", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_md.ts", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/sha2.ts", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/jwt.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/password.node.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/password.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/base64.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/index.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hash.mjs", "../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/utils.ts", "../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/_arx.ts", "../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/_poly1305.ts", "../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/chacha.ts", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/date.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/schema.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/db.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-promise.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/session-store.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/time.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/cookie-utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/index.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/binary.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hex.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hmac.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/state.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/global.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/async_hooks/index.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/endpoint-context.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/request-state.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/transaction.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/state/oauth.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/state.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/hide-metadata.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-api-error.mjs", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/index.mjs", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/utils.ts", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/crypto.ts", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/cookies.ts", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/validator.ts", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/openapi.ts", "../../../node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/router.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/api/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/trusted-origins.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/middlewares/origin-check.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/url.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/deprecate.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/get-request-ip.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/ip.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/rate-limiter/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/state/should-session-refresh.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/session.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/verification-token-storage.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/with-hooks.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/internal-adapter.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/helpers.mjs", "../../../node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/account.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/apple.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/utils.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/create-authorization-url.mjs", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/error.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/plugins.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/retry.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/auth.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/utils.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/create-fetch/schema.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/create-fetch/index.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/url.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/fetch.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/refresh-access-token.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/validate-authorization-code.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/atlassian.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/cognito.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/discord.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/dropbox.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/facebook.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/figma.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/github.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/gitlab.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/google.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/huggingface.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/kakao.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/kick.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/line.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/linear.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/linkedin.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/microsoft-entra-id.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/naver.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/notion.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/paybin.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/paypal.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/polar.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/railway.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/reddit.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/roblox.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/salesforce.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/slack.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/spotify.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/tiktok.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/twitch.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/twitter.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/vercel.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/vk.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/wechat.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/zoom.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/email-verification.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/link-account.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/callback.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/error.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/ok.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/password.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/password.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-in.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-out.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-up.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/update-session.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/update-user.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/to-auth-endpoints.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/adapter-base.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/adapter-kysely.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/get-schema.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/get-migration.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/constants.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/secret-utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/create-context.mjs", "../../../node_modules/.pnpm/@better-auth+telemetry@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-f_04cb191a006c1c341def4e42b17bd9b5/node_modules/@better-auth/telemetry/dist/node.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/init.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/base.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/full.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/client/parser.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/adapter.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/access/access.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/access/statement.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/permission.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/has-permission.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/package.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/version.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/error-codes.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/shim.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/call.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/to-zod.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-access-control.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-invites.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-members.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-org.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/schema.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-team.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/organization.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/error-code.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/constant.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/verify-two-factor.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/backup-codes/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/otp/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/schema.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/totp/index.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/base32.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/otp.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/magic-link/utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/magic-link/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/index.mjs", "../../../packages/plugins/plugin-auth/src/auth-manager.ts", "../../../packages/plugins/plugin-auth/src/objectql-adapter.ts", "../../../packages/plugins/plugin-auth/src/auth-schema-config.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-user.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-session.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-account.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-verification.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-organization.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-member.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-invitation.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-team.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-team-member.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-api-key.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-two-factor.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-user-preference.object.ts", "../../../packages/plugins/plugin-auth/src/auth-plugin.ts", "../../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.12/node_modules/@hono/node-server/dist/index.mjs", "../../../packages/spec/src/shared/index.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/shared/mapping.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/shared/enums.zod.ts", "../../../packages/spec/src/shared/metadata-types.zod.ts", "../../../packages/spec/src/shared/branded-types.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/shared/suggestions.zod.ts", "../../../packages/spec/src/shared/error-map.zod.ts", "../../../packages/spec/src/shared/metadata-collection.zod.ts", "../../../packages/spec/src/data/index.ts", "../../../packages/spec/src/data/filter.zod.ts", "../../../packages/spec/src/data/query.zod.ts", "../../../packages/spec/src/data/validation.zod.ts", "../../../packages/spec/src/automation/state-machine.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/data/object.zod.ts", "../../../packages/spec/src/data/hook.zod.ts", "../../../packages/spec/src/data/mapping.zod.ts", "../../../packages/spec/src/kernel/execution-context.zod.ts", "../../../packages/spec/src/data/data-engine.zod.ts", "../../../packages/spec/src/data/driver.zod.ts", "../../../packages/spec/src/data/driver-sql.zod.ts", "../../../packages/spec/src/data/driver-nosql.zod.ts", "../../../packages/spec/src/data/dataset.zod.ts", "../../../packages/spec/src/data/seed-loader.zod.ts", "../../../packages/spec/src/data/document.zod.ts", "../../../packages/spec/src/data/external-lookup.zod.ts", "../../../packages/spec/src/data/datasource.zod.ts", "../../../packages/spec/src/data/analytics.zod.ts", "../../../packages/spec/src/data/feed.zod.ts", "../../../packages/spec/src/data/subscription.zod.ts", "../../../packages/spec/src/data/driver/turso-multi-tenant.zod.ts", "../../../packages/spec/src/security/index.ts", "../../../packages/spec/src/security/rls.zod.ts", "../../../packages/spec/src/security/permission.zod.ts", "../../../packages/spec/src/security/sharing.zod.ts", "../../../packages/spec/src/security/territory.zod.ts", "../../../packages/spec/src/security/policy.zod.ts", "../../../packages/spec/src/ui/index.ts", "../../../packages/spec/src/ui/chart.zod.ts", "../../../packages/spec/src/ui/responsive.zod.ts", "../../../packages/spec/src/ui/sharing.zod.ts", "../../../packages/spec/src/ui/app.zod.ts", "../../../packages/spec/src/ui/view.zod.ts", "../../../packages/spec/src/ui/dashboard.zod.ts", "../../../packages/spec/src/ui/report.zod.ts", "../../../packages/spec/src/ui/page.zod.ts", "../../../packages/spec/src/ui/widget.zod.ts", "../../../packages/spec/src/ui/component.zod.ts", "../../../packages/spec/src/ui/touch.zod.ts", "../../../packages/spec/src/ui/keyboard.zod.ts", "../../../packages/spec/src/ui/theme.zod.ts", "../../../packages/spec/src/ui/offline.zod.ts", "../../../packages/spec/src/ui/animation.zod.ts", "../../../packages/spec/src/ui/notification.zod.ts", "../../../packages/spec/src/ui/dnd.zod.ts", "../../../packages/spec/src/system/index.ts", "../../../packages/spec/src/system/cache.zod.ts", "../../../packages/spec/src/system/disaster-recovery.zod.ts", "../../../packages/spec/src/system/message-queue.zod.ts", "../../../packages/spec/src/system/object-storage.zod.ts", "../../../packages/spec/src/system/search-engine.zod.ts", "../../../packages/spec/src/system/http-server.zod.ts", "../../../packages/spec/src/system/audit.zod.ts", "../../../packages/spec/src/system/logging.zod.ts", "../../../packages/spec/src/system/metrics.zod.ts", "../../../packages/spec/src/system/tracing.zod.ts", "../../../packages/spec/src/system/security-context.zod.ts", "../../../packages/spec/src/system/change-management.zod.ts", "../../../packages/spec/src/system/migration.zod.ts", "../../../packages/spec/src/system/auth-config.zod.ts", "../../../packages/spec/src/system/compliance.zod.ts", "../../../packages/spec/src/system/incident-response.zod.ts", "../../../packages/spec/src/system/supplier-security.zod.ts", "../../../packages/spec/src/system/training.zod.ts", "../../../packages/spec/src/system/job.zod.ts", "../../../packages/spec/src/system/worker.zod.ts", "../../../packages/spec/src/system/notification.zod.ts", "../../../packages/spec/src/system/translation.zod.ts", "../../../packages/spec/src/system/translation-skeleton.ts", "../../../packages/spec/src/system/collaboration.zod.ts", "../../../packages/spec/src/system/metadata-persistence.zod.ts", "../../../packages/spec/src/system/core-services.zod.ts", "../../../packages/spec/src/system/tenant.zod.ts", "../../../packages/spec/src/system/license.zod.ts", "../../../packages/spec/src/system/registry-config.zod.ts", "../../../packages/spec/src/system/provisioning.zod.ts", "../../../packages/spec/src/system/deploy-bundle.zod.ts", "../../../packages/spec/src/system/app-install.zod.ts", "../../../packages/spec/src/system/constants/paths.ts", "../../../packages/spec/src/system/constants/system-names.ts", "../../../packages/spec/src/kernel/index.ts", "../../../packages/spec/src/kernel/cli-extension.zod.ts", "../../../packages/spec/src/kernel/package-artifact.zod.ts", "../../../packages/spec/src/kernel/cli-plugin-commands.zod.ts", "../../../packages/spec/src/kernel/context.zod.ts", "../../../packages/spec/src/kernel/dependency-resolution.zod.ts", "../../../packages/spec/src/kernel/dev-plugin.zod.ts", "../../../packages/spec/src/kernel/events/core.zod.ts", "../../../packages/spec/src/kernel/events/handlers.zod.ts", "../../../packages/spec/src/kernel/events/queue.zod.ts", "../../../packages/spec/src/kernel/events/dlq.zod.ts", "../../../packages/spec/src/kernel/events/integrations.zod.ts", "../../../packages/spec/src/kernel/events/bus.zod.ts", "../../../packages/spec/src/kernel/feature.zod.ts", "../../../packages/spec/src/kernel/plugin-capability.zod.ts", "../../../packages/spec/src/kernel/plugin-loading.zod.ts", "../../../packages/spec/src/kernel/plugin.zod.ts", "../../../packages/spec/src/kernel/manifest.zod.ts", "../../../packages/spec/src/kernel/metadata-customization.zod.ts", "../../../packages/spec/src/kernel/metadata-loader.zod.ts", "../../../packages/spec/src/kernel/metadata-plugin.zod.ts", "../../../packages/spec/src/kernel/package-registry.zod.ts", "../../../packages/spec/src/kernel/package-upgrade.zod.ts", "../../../packages/spec/src/kernel/plugin-lifecycle-advanced.zod.ts", "../../../packages/spec/src/kernel/plugin-lifecycle-events.zod.ts", "../../../packages/spec/src/kernel/plugin-runtime.zod.ts", "../../../packages/spec/src/kernel/plugin-security-advanced.zod.ts", "../../../packages/spec/src/kernel/plugin-structure.zod.ts", "../../../packages/spec/src/kernel/plugin-validator.zod.ts", "../../../packages/spec/src/kernel/plugin-versioning.zod.ts", "../../../packages/spec/src/kernel/service-registry.zod.ts", "../../../packages/spec/src/kernel/startup-orchestrator.zod.ts", "../../../packages/spec/src/kernel/plugin-registry.zod.ts", "../../../packages/spec/src/kernel/plugin-security.zod.ts", "../../../packages/spec/src/cloud/index.ts", "../../../packages/spec/src/cloud/marketplace.zod.ts", "../../../packages/spec/src/cloud/developer-portal.zod.ts", "../../../packages/spec/src/cloud/marketplace-admin.zod.ts", "../../../packages/spec/src/cloud/app-store.zod.ts", "../../../packages/spec/src/qa/index.ts", "../../../packages/spec/src/qa/testing.zod.ts", "../../../packages/spec/src/identity/index.ts", "../../../packages/spec/src/identity/identity.zod.ts", "../../../packages/spec/src/identity/protocol.ts", "../../../packages/spec/src/identity/role.zod.ts", "../../../packages/spec/src/identity/organization.zod.ts", "../../../packages/spec/src/identity/scim.zod.ts", "../../../packages/spec/src/ai/index.ts", "../../../packages/spec/src/ai/agent.zod.ts", "../../../packages/spec/src/ai/tool.zod.ts", "../../../packages/spec/src/ai/skill.zod.ts", "../../../packages/spec/src/ai/agent-action.zod.ts", "../../../packages/spec/src/ai/devops-agent.zod.ts", "../../../packages/spec/src/ai/plugin-development.zod.ts", "../../../packages/spec/src/ai/runtime-ops.zod.ts", "../../../packages/spec/src/ai/model-registry.zod.ts", "../../../packages/spec/src/ai/mcp.zod.ts", "../../../packages/spec/src/ai/cost.zod.ts", "../../../packages/spec/src/ai/rag-pipeline.zod.ts", "../../../packages/spec/src/ai/nlq.zod.ts", "../../../packages/spec/src/ai/orchestration.zod.ts", "../../../packages/spec/src/ai/predictive.zod.ts", "../../../packages/spec/src/ai/conversation.zod.ts", "../../../packages/spec/src/ai/feedback-loop.zod.ts", "../../../packages/spec/src/api/index.ts", "../../../packages/spec/src/api/contract.zod.ts", "../../../packages/spec/src/api/endpoint.zod.ts", "../../../packages/spec/src/api/discovery.zod.ts", "../../../packages/spec/src/api/events.zod.ts", "../../../packages/spec/src/api/realtime-shared.zod.ts", "../../../packages/spec/src/api/realtime.zod.ts", "../../../packages/spec/src/api/websocket.zod.ts", "../../../packages/spec/src/api/router.zod.ts", "../../../packages/spec/src/api/odata.zod.ts", "../../../packages/spec/src/api/graphql.zod.ts", "../../../packages/spec/src/api/batch.zod.ts", "../../../packages/spec/src/api/http-cache.zod.ts", "../../../packages/spec/src/api/errors.zod.ts", "../../../packages/spec/src/automation/workflow.zod.ts", "../../../packages/spec/src/api/protocol.zod.ts", "../../../packages/spec/src/api/rest-server.zod.ts", "../../../packages/spec/src/api/registry.zod.ts", "../../../packages/spec/src/api/documentation.zod.ts", "../../../packages/spec/src/api/analytics.zod.ts", "../../../packages/spec/src/api/versioning.zod.ts", "../../../packages/spec/src/api/auth.zod.ts", "../../../packages/spec/src/api/auth-endpoints.zod.ts", "../../../packages/spec/src/api/storage.zod.ts", "../../../packages/spec/src/api/metadata.zod.ts", "../../../packages/spec/src/api/dispatcher.zod.ts", "../../../packages/spec/src/api/plugin-rest-api.zod.ts", "../../../packages/spec/src/api/query-adapter.zod.ts", "../../../packages/spec/src/api/feed-api.zod.ts", "../../../packages/spec/src/api/export.zod.ts", "../../../packages/spec/src/automation/flow.zod.ts", "../../../packages/spec/src/automation/execution.zod.ts", "../../../packages/spec/src/api/automation-api.zod.ts", "../../../packages/spec/src/api/package-api.zod.ts", "../../../packages/spec/src/automation/index.ts", "../../../packages/spec/src/automation/webhook.zod.ts", "../../../packages/spec/src/automation/approval.zod.ts", "../../../packages/spec/src/automation/etl.zod.ts", "../../../packages/spec/src/automation/trigger-registry.zod.ts", "../../../packages/spec/src/automation/sync.zod.ts", "../../../packages/spec/src/automation/node-executor.zod.ts", "../../../packages/spec/src/automation/bpmn-interop.zod.ts", "../../../packages/spec/src/integration/index.ts", "../../../packages/spec/src/shared/connector-auth.zod.ts", "../../../packages/spec/src/integration/connector.zod.ts", "../../../packages/spec/src/integration/connector/saas.zod.ts", "../../../packages/spec/src/integration/connector/database.zod.ts", "../../../packages/spec/src/integration/connector/file-storage.zod.ts", "../../../packages/spec/src/integration/connector/message-queue.zod.ts", "../../../packages/spec/src/integration/connector/github.zod.ts", "../../../packages/spec/src/integration/connector/vercel.zod.ts", "../../../packages/spec/src/contracts/index.ts", "../../../packages/spec/src/studio/index.ts", "../../../packages/spec/src/studio/plugin.zod.ts", "../../../packages/spec/src/studio/object-designer.zod.ts", "../../../packages/spec/src/studio/page-builder.zod.ts", "../../../packages/spec/src/studio/flow-builder.zod.ts", "../../../packages/spec/src/stack.zod.ts", "../../app-crm/src/objects/index.ts", "../../app-crm/src/objects/account.object.ts", "../../app-crm/src/objects/campaign.object.ts", "../../app-crm/src/objects/case.object.ts", "../../app-crm/src/objects/contact.object.ts", "../../app-crm/src/objects/contract.object.ts", "../../app-crm/src/objects/lead.object.ts", "../../app-crm/src/objects/lead.state.ts", "../../app-crm/src/objects/opportunity.object.ts", "../../app-crm/src/objects/opportunity.state.ts", "../../app-crm/src/objects/product.object.ts", "../../app-crm/src/objects/quote.object.ts", "../../app-crm/src/objects/task.object.ts", "../../app-crm/src/apis/index.ts", "../../app-crm/src/apis/lead-convert.api.ts", "../../app-crm/src/apis/pipeline-stats.api.ts", "../../app-crm/src/actions/index.ts", "../../app-crm/src/actions/case.actions.ts", "../../app-crm/src/actions/contact.actions.ts", "../../app-crm/src/actions/global.actions.ts", "../../app-crm/src/actions/lead.actions.ts", "../../app-crm/src/actions/opportunity.actions.ts", "../../app-crm/src/dashboards/index.ts", "../../app-crm/src/dashboards/executive.dashboard.ts", "../../app-crm/src/dashboards/sales.dashboard.ts", "../../app-crm/src/dashboards/service.dashboard.ts", "../../app-crm/src/reports/index.ts", "../../app-crm/src/reports/account.report.ts", "../../app-crm/src/reports/case.report.ts", "../../app-crm/src/reports/contact.report.ts", "../../app-crm/src/reports/lead.report.ts", "../../app-crm/src/reports/opportunity.report.ts", "../../app-crm/src/reports/task.report.ts", "../../app-crm/src/flows/campaign-enrollment.flow.ts", "../../app-crm/src/flows/case-escalation.flow.ts", "../../app-crm/src/flows/lead-conversion.flow.ts", "../../app-crm/src/flows/opportunity-approval.flow.ts", "../../app-crm/src/flows/quote-generation.flow.ts", "../../app-crm/src/flows/index.ts", "../../app-crm/src/agents/email-campaign.agent.ts", "../../app-crm/src/agents/lead-enrichment.agent.ts", "../../app-crm/src/agents/revenue-intelligence.agent.ts", "../../app-crm/src/agents/sales.agent.ts", "../../app-crm/src/agents/service.agent.ts", "../../app-crm/src/agents/index.ts", "../../app-crm/src/rag/index.ts", "../../app-crm/src/rag/competitive-intel.rag.ts", "../../app-crm/src/rag/product-info.rag.ts", "../../app-crm/src/rag/sales-knowledge.rag.ts", "../../app-crm/src/rag/support-knowledge.rag.ts", "../../app-crm/src/profiles/index.ts", "../../app-crm/src/profiles/marketing-user.profile.ts", "../../app-crm/src/profiles/sales-manager.profile.ts", "../../app-crm/src/profiles/sales-rep.profile.ts", "../../app-crm/src/profiles/service-agent.profile.ts", "../../app-crm/src/profiles/system-admin.profile.ts", "../../app-crm/src/apps/index.ts", "../../app-crm/src/apps/crm.app.ts", "../../app-crm/src/apps/crm_modern.app.ts", "../../app-crm/src/translations/index.ts", "../../app-crm/src/translations/en.ts", "../../app-crm/src/translations/zh-CN.ts", "../../app-crm/src/translations/ja-JP.ts", "../../app-crm/src/translations/es-ES.ts", "../../app-crm/src/translations/crm.translation.ts", "../../app-crm/src/data/index.ts", "../../app-crm/src/sharing/account.sharing.ts", "../../app-crm/src/sharing/case.sharing.ts", "../../app-crm/src/sharing/opportunity.sharing.ts", "../../app-crm/src/sharing/role-hierarchy.ts", "../../app-crm/objectstack.config.ts", "../../app-todo/src/objects/index.ts", "../../app-todo/src/objects/task.object.ts", "../../app-todo/src/actions/index.ts", "../../app-todo/src/actions/task.actions.ts", "../../app-todo/src/dashboards/index.ts", "../../app-todo/src/dashboards/task.dashboard.ts", "../../app-todo/src/reports/index.ts", "../../app-todo/src/reports/task.report.ts", "../../app-todo/src/flows/task.flow.ts", "../../app-todo/src/flows/index.ts", "../../app-todo/src/apps/index.ts", "../../app-todo/src/apps/todo.app.ts", "../../app-todo/src/translations/index.ts", "../../app-todo/src/translations/en.ts", "../../app-todo/src/translations/zh-CN.ts", "../../app-todo/src/translations/ja-JP.ts", "../../app-todo/src/translations/todo.translation.ts", "../../app-todo/objectstack.config.ts", "../../plugin-bi/objectstack.config.ts", "../server/index.ts"], + "sourcesContent": ["/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n", "// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n", "import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * \u2716 Expected number, received string at \"username\n * favoriteNumbers[0]\n * \u2716 Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`\u2716 ${issue.message}`);\n if (issue.path?.length)\n lines.push(` \u2192 at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n", "import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n", "import * as util from \"./util.js\";\nexport const cuid = /^[cC][^\\s-]{8,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){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}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n", "// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n", "export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n", "export const version = {\n major: 4,\n minor: 3,\n patch: 6,\n};\n", "import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalOut) {\n if (result.issues.length) {\n // For optional-out schemas, ignore errors on absent keys\n if (isOptionalOut && !(key in input)) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalOut) {\n // For optional-out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig\n ? { code: \"too_big\", maximum: items.length, inclusive: true }\n : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (result.issues.length && input === undefined) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u062D\u0631\u0641\", verb: \"\u0623\u0646 \u064A\u062D\u0648\u064A\" },\n file: { unit: \"\u0628\u0627\u064A\u062A\", verb: \"\u0623\u0646 \u064A\u062D\u0648\u064A\" },\n array: { unit: \"\u0639\u0646\u0635\u0631\", verb: \"\u0623\u0646 \u064A\u062D\u0648\u064A\" },\n set: { unit: \"\u0639\u0646\u0635\u0631\", verb: \"\u0623\u0646 \u064A\u062D\u0648\u064A\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0645\u062F\u062E\u0644\",\n email: \"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A\",\n url: \"\u0631\u0627\u0628\u0637\",\n emoji: \"\u0625\u064A\u0645\u0648\u062C\u064A\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO\",\n date: \"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO\",\n time: \"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO\",\n duration: \"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO\",\n ipv4: \"\u0639\u0646\u0648\u0627\u0646 IPv4\",\n ipv6: \"\u0639\u0646\u0648\u0627\u0646 IPv6\",\n cidrv4: \"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4\",\n cidrv6: \"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6\",\n base64: \"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded\",\n base64url: \"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded\",\n json_string: \"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON\",\n e164: \"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0645\u062F\u062E\u0644\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;\n }\n return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue.origin ?? \"\u0627\u0644\u0642\u064A\u0645\u0629\"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"\u0639\u0646\u0635\u0631\"}`;\n return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue.origin ?? \"\u0627\u0644\u0642\u064A\u0645\u0629\"} ${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 \"${issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;\n }\n case \"not_multiple_of\":\n return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u0645\u0639\u0631\u0641${issue.keys.length > 1 ? \"\u0627\u062A\" : \"\"} \u063A\u0631\u064A\u0628${issue.keys.length > 1 ? \"\u0629\" : \"\"}: ${util.joinValues(issue.keys, \"\u060C \")}`;\n case \"invalid_key\":\n return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue.origin}`;\n case \"invalid_union\":\n return \"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\";\n case \"invalid_element\":\n return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue.origin}`;\n default:\n return \"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\";\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"simvol\", verb: \"olmal\u0131d\u0131r\" },\n file: { unit: \"bayt\", verb: \"olmal\u0131d\u0131r\" },\n array: { unit: \"element\", verb: \"olmal\u0131d\u0131r\" },\n set: { unit: \"element\", verb: \"olmal\u0131d\u0131r\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Yanl\u0131\u015F d\u0259y\u0259r: g\u00F6zl\u0259nil\u0259n instanceof ${issue.expected}, daxil olan ${received}`;\n }\n return `Yanl\u0131\u015F d\u0259y\u0259r: g\u00F6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Yanl\u0131\u015F d\u0259y\u0259r: g\u00F6zl\u0259nil\u0259n ${util.stringifyPrimitive(issue.values[0])}`;\n return `Yanl\u0131\u015F se\u00E7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u00C7ox b\u00F6y\u00FCk: g\u00F6zl\u0259nil\u0259n ${issue.origin ?? \"d\u0259y\u0259r\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"element\"}`;\n return `\u00C7ox b\u00F6y\u00FCk: g\u00F6zl\u0259nil\u0259n ${issue.origin ?? \"d\u0259y\u0259r\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u00C7ox ki\u00E7ik: g\u00F6zl\u0259nil\u0259n ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n return `\u00C7ox ki\u00E7ik: g\u00F6zl\u0259nil\u0259n ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Yanl\u0131\u015F m\u0259tn: \"${_issue.prefix}\" il\u0259 ba\u015Flamal\u0131d\u0131r`;\n if (_issue.format === \"ends_with\")\n return `Yanl\u0131\u015F m\u0259tn: \"${_issue.suffix}\" il\u0259 bitm\u0259lidir`;\n if (_issue.format === \"includes\")\n return `Yanl\u0131\u015F m\u0259tn: \"${_issue.includes}\" daxil olmal\u0131d\u0131r`;\n if (_issue.format === \"regex\")\n return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;\n return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Yanl\u0131\u015F \u0259d\u0259d: ${issue.divisor} il\u0259 b\u00F6l\u00FCn\u0259 bil\u0259n olmal\u0131d\u0131r`;\n case \"unrecognized_keys\":\n return `Tan\u0131nmayan a\u00E7ar${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} daxilind\u0259 yanl\u0131\u015F a\u00E7ar`;\n case \"invalid_union\":\n return \"Yanl\u0131\u015F d\u0259y\u0259r\";\n case \"invalid_element\":\n return `${issue.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;\n default:\n return `Yanl\u0131\u015F d\u0259y\u0259r`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nfunction getBelarusianPlural(count, one, few, many) {\n const absCount = Math.abs(count);\n const lastDigit = absCount % 10;\n const lastTwoDigits = absCount % 100;\n if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {\n return many;\n }\n if (lastDigit === 1) {\n return one;\n }\n if (lastDigit >= 2 && lastDigit <= 4) {\n return few;\n }\n return many;\n}\nconst error = () => {\n const Sizable = {\n string: {\n unit: {\n one: \"\u0441\u0456\u043C\u0432\u0430\u043B\",\n few: \"\u0441\u0456\u043C\u0432\u0430\u043B\u044B\",\n many: \"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E\",\n },\n verb: \"\u043C\u0435\u0446\u044C\",\n },\n array: {\n unit: {\n one: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\",\n few: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B\",\n many: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E\",\n },\n verb: \"\u043C\u0435\u0446\u044C\",\n },\n set: {\n unit: {\n one: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\",\n few: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B\",\n many: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E\",\n },\n verb: \"\u043C\u0435\u0446\u044C\",\n },\n file: {\n unit: {\n one: \"\u0431\u0430\u0439\u0442\",\n few: \"\u0431\u0430\u0439\u0442\u044B\",\n many: \"\u0431\u0430\u0439\u0442\u0430\u045E\",\n },\n verb: \"\u043C\u0435\u0446\u044C\",\n },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0443\u0432\u043E\u0434\",\n email: \"email \u0430\u0434\u0440\u0430\u0441\",\n url: \"URL\",\n emoji: \"\u044D\u043C\u043E\u0434\u0437\u0456\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441\",\n date: \"ISO \u0434\u0430\u0442\u0430\",\n time: \"ISO \u0447\u0430\u0441\",\n duration: \"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C\",\n ipv4: \"IPv4 \u0430\u0434\u0440\u0430\u0441\",\n ipv6: \"IPv6 \u0430\u0434\u0440\u0430\u0441\",\n cidrv4: \"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D\",\n cidrv6: \"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D\",\n base64: \"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64\",\n base64url: \"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url\",\n json_string: \"JSON \u0440\u0430\u0434\u043E\u043A\",\n e164: \"\u043D\u0443\u043C\u0430\u0440 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0443\u0432\u043E\u0434\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u043B\u0456\u043A\",\n array: \"\u043C\u0430\u0441\u0456\u045E\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;\n }\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const maxValue = Number(issue.maximum);\n const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435\"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`;\n }\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435\"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const minValue = Number(issue.minimum);\n const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`;\n }\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue.keys.length > 1 ? \"\u043A\u043B\u044E\u0447\u044B\" : \"\u043A\u043B\u044E\u0447\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434\";\n case \"invalid_element\":\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue.origin}`;\n default:\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0441\u0438\u043C\u0432\u043E\u043B\u0430\", verb: \"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430\" },\n file: { unit: \"\u0431\u0430\u0439\u0442\u0430\", verb: \"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430\" },\n array: { unit: \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430\", verb: \"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430\" },\n set: { unit: \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430\", verb: \"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0432\u0445\u043E\u0434\",\n email: \"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441\",\n url: \"URL\",\n emoji: \"\u0435\u043C\u043E\u0434\u0436\u0438\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0432\u0440\u0435\u043C\u0435\",\n date: \"ISO \u0434\u0430\u0442\u0430\",\n time: \"ISO \u0432\u0440\u0435\u043C\u0435\",\n duration: \"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442\",\n ipv4: \"IPv4 \u0430\u0434\u0440\u0435\u0441\",\n ipv6: \"IPv6 \u0430\u0434\u0440\u0435\u0441\",\n cidrv4: \"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\",\n cidrv6: \"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\",\n base64: \"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437\",\n base64url: \"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437\",\n json_string: \"JSON \u043D\u0438\u0437\",\n e164: \"E.164 \u043D\u043E\u043C\u0435\u0440\",\n jwt: \"JWT\",\n template_literal: \"\u0432\u0445\u043E\u0434\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0447\u0438\u0441\u043B\u043E\",\n array: \"\u043C\u0430\u0441\u0438\u0432\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;\n }\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue.origin ?? \"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442\"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430\"}`;\n return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue.origin ?? \"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442\"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`;\n let invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D\";\n if (_issue.format === \"emoji\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E\";\n if (_issue.format === \"datetime\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E\";\n if (_issue.format === \"date\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430\";\n if (_issue.format === \"time\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E\";\n if (_issue.format === \"duration\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430\";\n return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue.keys.length > 1 ? \"\u0438\" : \"\"} \u043A\u043B\u044E\u0447${issue.keys.length > 1 ? \"\u043E\u0432\u0435\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434\";\n case \"invalid_element\":\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue.origin}`;\n default:\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"car\u00E0cters\", verb: \"contenir\" },\n file: { unit: \"bytes\", verb: \"contenir\" },\n array: { unit: \"elements\", verb: \"contenir\" },\n set: { unit: \"elements\", verb: \"contenir\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"entrada\",\n email: \"adre\u00E7a electr\u00F2nica\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"data i hora ISO\",\n date: \"data ISO\",\n time: \"hora ISO\",\n duration: \"durada ISO\",\n ipv4: \"adre\u00E7a IPv4\",\n ipv6: \"adre\u00E7a IPv6\",\n cidrv4: \"rang IPv4\",\n cidrv6: \"rang IPv6\",\n base64: \"cadena codificada en base64\",\n base64url: \"cadena codificada en base64url\",\n json_string: \"cadena JSON\",\n e164: \"n\u00FAmero E.164\",\n jwt: \"JWT\",\n template_literal: \"entrada\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Tipus inv\u00E0lid: s'esperava instanceof ${issue.expected}, s'ha rebut ${received}`;\n }\n return `Tipus inv\u00E0lid: s'esperava ${expected}, s'ha rebut ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Valor inv\u00E0lid: s'esperava ${util.stringifyPrimitive(issue.values[0])}`;\n return `Opci\u00F3 inv\u00E0lida: s'esperava una de ${util.joinValues(issue.values, \" o \")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"com a m\u00E0xim\" : \"menys de\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Massa gran: s'esperava que ${issue.origin ?? \"el valor\"} contingu\u00E9s ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Massa gran: s'esperava que ${issue.origin ?? \"el valor\"} fos ${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"com a m\u00EDnim\" : \"m\u00E9s de\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Massa petit: s'esperava que ${issue.origin} contingu\u00E9s ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Format inv\u00E0lid: ha de comen\u00E7ar amb \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Format inv\u00E0lid: ha d'acabar amb \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Format inv\u00E0lid: ha d'incloure \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Format inv\u00E0lid: ha de coincidir amb el patr\u00F3 ${_issue.pattern}`;\n return `Format inv\u00E0lid per a ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `N\u00FAmero inv\u00E0lid: ha de ser m\u00FAltiple de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Clau${issue.keys.length > 1 ? \"s\" : \"\"} no reconeguda${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Clau inv\u00E0lida a ${issue.origin}`;\n case \"invalid_union\":\n return \"Entrada inv\u00E0lida\"; // Could also be \"Tipus d'uni\u00F3 inv\u00E0lid\" but \"Entrada inv\u00E0lida\" is more general\n case \"invalid_element\":\n return `Element inv\u00E0lid a ${issue.origin}`;\n default:\n return `Entrada inv\u00E0lida`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"znak\u016F\", verb: \"m\u00EDt\" },\n file: { unit: \"bajt\u016F\", verb: \"m\u00EDt\" },\n array: { unit: \"prvk\u016F\", verb: \"m\u00EDt\" },\n set: { unit: \"prvk\u016F\", verb: \"m\u00EDt\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"regul\u00E1rn\u00ED v\u00FDraz\",\n email: \"e-mailov\u00E1 adresa\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"datum a \u010Das ve form\u00E1tu ISO\",\n date: \"datum ve form\u00E1tu ISO\",\n time: \"\u010Das ve form\u00E1tu ISO\",\n duration: \"doba trv\u00E1n\u00ED ISO\",\n ipv4: \"IPv4 adresa\",\n ipv6: \"IPv6 adresa\",\n cidrv4: \"rozsah IPv4\",\n cidrv6: \"rozsah IPv6\",\n base64: \"\u0159et\u011Bzec zak\u00F3dovan\u00FD ve form\u00E1tu base64\",\n base64url: \"\u0159et\u011Bzec zak\u00F3dovan\u00FD ve form\u00E1tu base64url\",\n json_string: \"\u0159et\u011Bzec ve form\u00E1tu JSON\",\n e164: \"\u010D\u00EDslo E.164\",\n jwt: \"JWT\",\n template_literal: \"vstup\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u010D\u00EDslo\",\n string: \"\u0159et\u011Bzec\",\n function: \"funkce\",\n array: \"pole\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Neplatn\u00FD vstup: o\u010Dek\u00E1v\u00E1no instanceof ${issue.expected}, obdr\u017Eeno ${received}`;\n }\n return `Neplatn\u00FD vstup: o\u010Dek\u00E1v\u00E1no ${expected}, obdr\u017Eeno ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Neplatn\u00FD vstup: o\u010Dek\u00E1v\u00E1no ${util.stringifyPrimitive(issue.values[0])}`;\n return `Neplatn\u00E1 mo\u017Enost: o\u010Dek\u00E1v\u00E1na jedna z hodnot ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Hodnota je p\u0159\u00EDli\u0161 velk\u00E1: ${issue.origin ?? \"hodnota\"} mus\u00ED m\u00EDt ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"prvk\u016F\"}`;\n }\n return `Hodnota je p\u0159\u00EDli\u0161 velk\u00E1: ${issue.origin ?? \"hodnota\"} mus\u00ED b\u00FDt ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Hodnota je p\u0159\u00EDli\u0161 mal\u00E1: ${issue.origin ?? \"hodnota\"} mus\u00ED m\u00EDt ${adj}${issue.minimum.toString()} ${sizing.unit ?? \"prvk\u016F\"}`;\n }\n return `Hodnota je p\u0159\u00EDli\u0161 mal\u00E1: ${issue.origin ?? \"hodnota\"} mus\u00ED b\u00FDt ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Neplatn\u00FD \u0159et\u011Bzec: mus\u00ED za\u010D\u00EDnat na \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Neplatn\u00FD \u0159et\u011Bzec: mus\u00ED kon\u010Dit na \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Neplatn\u00FD \u0159et\u011Bzec: mus\u00ED obsahovat \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Neplatn\u00FD \u0159et\u011Bzec: mus\u00ED odpov\u00EDdat vzoru ${_issue.pattern}`;\n return `Neplatn\u00FD form\u00E1t ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Neplatn\u00E9 \u010D\u00EDslo: mus\u00ED b\u00FDt n\u00E1sobkem ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Nezn\u00E1m\u00E9 kl\u00ED\u010De: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Neplatn\u00FD kl\u00ED\u010D v ${issue.origin}`;\n case \"invalid_union\":\n return \"Neplatn\u00FD vstup\";\n case \"invalid_element\":\n return `Neplatn\u00E1 hodnota v ${issue.origin}`;\n default:\n return `Neplatn\u00FD vstup`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"tegn\", verb: \"havde\" },\n file: { unit: \"bytes\", verb: \"havde\" },\n array: { unit: \"elementer\", verb: \"indeholdt\" },\n set: { unit: \"elementer\", verb: \"indeholdt\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"e-mailadresse\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO dato- og klokkesl\u00E6t\",\n date: \"ISO-dato\",\n time: \"ISO-klokkesl\u00E6t\",\n duration: \"ISO-varighed\",\n ipv4: \"IPv4-omr\u00E5de\",\n ipv6: \"IPv6-omr\u00E5de\",\n cidrv4: \"IPv4-spektrum\",\n cidrv6: \"IPv6-spektrum\",\n base64: \"base64-kodet streng\",\n base64url: \"base64url-kodet streng\",\n json_string: \"JSON-streng\",\n e164: \"E.164-nummer\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n string: \"streng\",\n number: \"tal\",\n boolean: \"boolean\",\n array: \"liste\",\n object: \"objekt\",\n set: \"s\u00E6t\",\n file: \"fil\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ugyldigt input: forventede instanceof ${issue.expected}, fik ${received}`;\n }\n return `Ugyldigt input: forventede ${expected}, fik ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ugyldig v\u00E6rdi: forventede ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ugyldigt valg: forventede en af f\u00F8lgende ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n if (sizing)\n return `For stor: forventede ${origin ?? \"value\"} ${sizing.verb} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"elementer\"}`;\n return `For stor: forventede ${origin ?? \"value\"} havde ${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n if (sizing) {\n return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `For lille: forventede ${origin} havde ${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Ugyldig streng: skal starte med \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Ugyldig streng: skal ende med \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Ugyldig streng: skal indeholde \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Ugyldig streng: skal matche m\u00F8nsteret ${_issue.pattern}`;\n return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ugyldigt tal: skal v\u00E6re deleligt med ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Ukendte n\u00F8gler\" : \"Ukendt n\u00F8gle\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ugyldig n\u00F8gle i ${issue.origin}`;\n case \"invalid_union\":\n return \"Ugyldigt input: matcher ingen af de tilladte typer\";\n case \"invalid_element\":\n return `Ugyldig v\u00E6rdi i ${issue.origin}`;\n default:\n return `Ugyldigt input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"Zeichen\", verb: \"zu haben\" },\n file: { unit: \"Bytes\", verb: \"zu haben\" },\n array: { unit: \"Elemente\", verb: \"zu haben\" },\n set: { unit: \"Elemente\", verb: \"zu haben\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"Eingabe\",\n email: \"E-Mail-Adresse\",\n url: \"URL\",\n emoji: \"Emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO-Datum und -Uhrzeit\",\n date: \"ISO-Datum\",\n time: \"ISO-Uhrzeit\",\n duration: \"ISO-Dauer\",\n ipv4: \"IPv4-Adresse\",\n ipv6: \"IPv6-Adresse\",\n cidrv4: \"IPv4-Bereich\",\n cidrv6: \"IPv6-Bereich\",\n base64: \"Base64-codierter String\",\n base64url: \"Base64-URL-codierter String\",\n json_string: \"JSON-String\",\n e164: \"E.164-Nummer\",\n jwt: \"JWT\",\n template_literal: \"Eingabe\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"Zahl\",\n array: \"Array\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ung\u00FCltige Eingabe: erwartet instanceof ${issue.expected}, erhalten ${received}`;\n }\n return `Ung\u00FCltige Eingabe: erwartet ${expected}, erhalten ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ung\u00FCltige Eingabe: erwartet ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ung\u00FCltige Option: erwartet eine von ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Zu gro\u00DF: erwartet, dass ${issue.origin ?? \"Wert\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"Elemente\"} hat`;\n return `Zu gro\u00DF: erwartet, dass ${issue.origin ?? \"Wert\"} ${adj}${issue.maximum.toString()} ist`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`;\n }\n return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Ung\u00FCltiger String: muss mit \"${_issue.prefix}\" beginnen`;\n if (_issue.format === \"ends_with\")\n return `Ung\u00FCltiger String: muss mit \"${_issue.suffix}\" enden`;\n if (_issue.format === \"includes\")\n return `Ung\u00FCltiger String: muss \"${_issue.includes}\" enthalten`;\n if (_issue.format === \"regex\")\n return `Ung\u00FCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;\n return `Ung\u00FCltig: ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ung\u00FCltige Zahl: muss ein Vielfaches von ${issue.divisor} sein`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Unbekannte Schl\u00FCssel\" : \"Unbekannter Schl\u00FCssel\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ung\u00FCltiger Schl\u00FCssel in ${issue.origin}`;\n case \"invalid_union\":\n return \"Ung\u00FCltige Eingabe\";\n case \"invalid_element\":\n return `Ung\u00FCltiger Wert in ${issue.origin}`;\n default:\n return `Ung\u00FCltige Eingabe`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"karaktrojn\", verb: \"havi\" },\n file: { unit: \"bajtojn\", verb: \"havi\" },\n array: { unit: \"elementojn\", verb: \"havi\" },\n set: { unit: \"elementojn\", verb: \"havi\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"enigo\",\n email: \"retadreso\",\n url: \"URL\",\n emoji: \"emo\u011Dio\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO-datotempo\",\n date: \"ISO-dato\",\n time: \"ISO-tempo\",\n duration: \"ISO-da\u016Dro\",\n ipv4: \"IPv4-adreso\",\n ipv6: \"IPv6-adreso\",\n cidrv4: \"IPv4-rango\",\n cidrv6: \"IPv6-rango\",\n base64: \"64-ume kodita karaktraro\",\n base64url: \"URL-64-ume kodita karaktraro\",\n json_string: \"JSON-karaktraro\",\n e164: \"E.164-nombro\",\n jwt: \"JWT\",\n template_literal: \"enigo\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"nombro\",\n array: \"tabelo\",\n null: \"senvalora\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Nevalida enigo: atendi\u011Dis instanceof ${issue.expected}, ricevi\u011Dis ${received}`;\n }\n return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Nevalida enigo: atendi\u011Dis ${util.stringifyPrimitive(issue.values[0])}`;\n return `Nevalida opcio: atendi\u011Dis unu el ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Tro granda: atendi\u011Dis ke ${issue.origin ?? \"valoro\"} havu ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementojn\"}`;\n return `Tro granda: atendi\u011Dis ke ${issue.origin ?? \"valoro\"} havu ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Tro malgranda: atendi\u011Dis ke ${issue.origin} havu ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Tro malgranda: atendi\u011Dis ke ${issue.origin} estu ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Nevalida karaktraro: devas komenci\u011Di per \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Nevalida karaktraro: devas fini\u011Di per \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Nevalida karaktraro: devas inkluzivi \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;\n return `Nevalida ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Nevalida nombro: devas esti oblo de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Nekonata${issue.keys.length > 1 ? \"j\" : \"\"} \u015Dlosilo${issue.keys.length > 1 ? \"j\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Nevalida \u015Dlosilo en ${issue.origin}`;\n case \"invalid_union\":\n return \"Nevalida enigo\";\n case \"invalid_element\":\n return `Nevalida valoro en ${issue.origin}`;\n default:\n return `Nevalida enigo`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caracteres\", verb: \"tener\" },\n file: { unit: \"bytes\", verb: \"tener\" },\n array: { unit: \"elementos\", verb: \"tener\" },\n set: { unit: \"elementos\", verb: \"tener\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"entrada\",\n email: \"direcci\u00F3n de correo electr\u00F3nico\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"fecha y hora ISO\",\n date: \"fecha ISO\",\n time: \"hora ISO\",\n duration: \"duraci\u00F3n ISO\",\n ipv4: \"direcci\u00F3n IPv4\",\n ipv6: \"direcci\u00F3n IPv6\",\n cidrv4: \"rango IPv4\",\n cidrv6: \"rango IPv6\",\n base64: \"cadena codificada en base64\",\n base64url: \"URL codificada en base64\",\n json_string: \"cadena JSON\",\n e164: \"n\u00FAmero E.164\",\n jwt: \"JWT\",\n template_literal: \"entrada\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n string: \"texto\",\n number: \"n\u00FAmero\",\n boolean: \"booleano\",\n array: \"arreglo\",\n object: \"objeto\",\n set: \"conjunto\",\n file: \"archivo\",\n date: \"fecha\",\n bigint: \"n\u00FAmero grande\",\n symbol: \"s\u00EDmbolo\",\n undefined: \"indefinido\",\n null: \"nulo\",\n function: \"funci\u00F3n\",\n map: \"mapa\",\n record: \"registro\",\n tuple: \"tupla\",\n enum: \"enumeraci\u00F3n\",\n union: \"uni\u00F3n\",\n literal: \"literal\",\n promise: \"promesa\",\n void: \"vac\u00EDo\",\n never: \"nunca\",\n unknown: \"desconocido\",\n any: \"cualquiera\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Entrada inv\u00E1lida: se esperaba instanceof ${issue.expected}, recibido ${received}`;\n }\n return `Entrada inv\u00E1lida: se esperaba ${expected}, recibido ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Entrada inv\u00E1lida: se esperaba ${util.stringifyPrimitive(issue.values[0])}`;\n return `Opci\u00F3n inv\u00E1lida: se esperaba una de ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n if (sizing)\n return `Demasiado grande: se esperaba que ${origin ?? \"valor\"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementos\"}`;\n return `Demasiado grande: se esperaba que ${origin ?? \"valor\"} fuera ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n if (sizing) {\n return `Demasiado peque\u00F1o: se esperaba que ${origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Demasiado peque\u00F1o: se esperaba que ${origin} fuera ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Cadena inv\u00E1lida: debe comenzar con \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Cadena inv\u00E1lida: debe terminar en \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Cadena inv\u00E1lida: debe incluir \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Cadena inv\u00E1lida: debe coincidir con el patr\u00F3n ${_issue.pattern}`;\n return `Inv\u00E1lido ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `N\u00FAmero inv\u00E1lido: debe ser m\u00FAltiplo de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Llave${issue.keys.length > 1 ? \"s\" : \"\"} desconocida${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Llave inv\u00E1lida en ${TypeDictionary[issue.origin] ?? issue.origin}`;\n case \"invalid_union\":\n return \"Entrada inv\u00E1lida\";\n case \"invalid_element\":\n return `Valor inv\u00E1lido en ${TypeDictionary[issue.origin] ?? issue.origin}`;\n default:\n return `Entrada inv\u00E1lida`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631\", verb: \"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F\" },\n file: { unit: \"\u0628\u0627\u06CC\u062A\", verb: \"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F\" },\n array: { unit: \"\u0622\u06CC\u062A\u0645\", verb: \"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F\" },\n set: { unit: \"\u0622\u06CC\u062A\u0645\", verb: \"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0648\u0631\u0648\u062F\u06CC\",\n email: \"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644\",\n url: \"URL\",\n emoji: \"\u0627\u06CC\u0645\u0648\u062C\u06CC\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648\",\n date: \"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648\",\n time: \"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648\",\n duration: \"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648\",\n ipv4: \"IPv4 \u0622\u062F\u0631\u0633\",\n ipv6: \"IPv6 \u0622\u062F\u0631\u0633\",\n cidrv4: \"IPv4 \u062F\u0627\u0645\u0646\u0647\",\n cidrv6: \"IPv6 \u062F\u0627\u0645\u0646\u0647\",\n base64: \"base64-encoded \u0631\u0634\u062A\u0647\",\n base64url: \"base64url-encoded \u0631\u0634\u062A\u0647\",\n json_string: \"JSON \u0631\u0634\u062A\u0647\",\n e164: \"E.164 \u0639\u062F\u062F\",\n jwt: \"JWT\",\n template_literal: \"\u0648\u0631\u0648\u062F\u06CC\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0639\u062F\u062F\",\n array: \"\u0622\u0631\u0627\u06CC\u0647\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;\n }\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1) {\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${util.stringifyPrimitive(issue.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;\n }\n return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${util.joinValues(issue.values, \"|\")} \u0645\u06CC\u200C\u0628\u0648\u062F`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue.origin ?? \"\u0645\u0642\u062F\u0627\u0631\"} \u0628\u0627\u06CC\u062F ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0639\u0646\u0635\u0631\"} \u0628\u0627\u0634\u062F`;\n }\n return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue.origin ?? \"\u0645\u0642\u062F\u0627\u0631\"} \u0628\u0627\u06CC\u062F ${adj}${issue.maximum.toString()} \u0628\u0627\u0634\u062F`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue.origin} \u0628\u0627\u06CC\u062F ${adj}${issue.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;\n }\n return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue.origin} \u0628\u0627\u06CC\u062F ${adj}${issue.minimum.toString()} \u0628\u0627\u0634\u062F`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \"${_issue.prefix}\" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;\n }\n if (_issue.format === \"ends_with\") {\n return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \"${_issue.suffix}\" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;\n }\n if (_issue.format === \"includes\") {\n return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 \"${_issue.includes}\" \u0628\u0627\u0634\u062F`;\n }\n if (_issue.format === \"regex\") {\n return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;\n }\n return `${FormatDictionary[_issue.format] ?? issue.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;\n }\n case \"not_multiple_of\":\n return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue.divisor} \u0628\u0627\u0634\u062F`;\n case \"unrecognized_keys\":\n return `\u06A9\u0644\u06CC\u062F${issue.keys.length > 1 ? \"\u0647\u0627\u06CC\" : \"\"} \u0646\u0627\u0634\u0646\u0627\u0633: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue.origin}`;\n case \"invalid_union\":\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;\n case \"invalid_element\":\n return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue.origin}`;\n default:\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"merkki\u00E4\", subject: \"merkkijonon\" },\n file: { unit: \"tavua\", subject: \"tiedoston\" },\n array: { unit: \"alkiota\", subject: \"listan\" },\n set: { unit: \"alkiota\", subject: \"joukon\" },\n number: { unit: \"\", subject: \"luvun\" },\n bigint: { unit: \"\", subject: \"suuren kokonaisluvun\" },\n int: { unit: \"\", subject: \"kokonaisluvun\" },\n date: { unit: \"\", subject: \"p\u00E4iv\u00E4m\u00E4\u00E4r\u00E4n\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"s\u00E4\u00E4nn\u00F6llinen lauseke\",\n email: \"s\u00E4hk\u00F6postiosoite\",\n url: \"URL-osoite\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO-aikaleima\",\n date: \"ISO-p\u00E4iv\u00E4m\u00E4\u00E4r\u00E4\",\n time: \"ISO-aika\",\n duration: \"ISO-kesto\",\n ipv4: \"IPv4-osoite\",\n ipv6: \"IPv6-osoite\",\n cidrv4: \"IPv4-alue\",\n cidrv6: \"IPv6-alue\",\n base64: \"base64-koodattu merkkijono\",\n base64url: \"base64url-koodattu merkkijono\",\n json_string: \"JSON-merkkijono\",\n e164: \"E.164-luku\",\n jwt: \"JWT\",\n template_literal: \"templaattimerkkijono\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Virheellinen tyyppi: odotettiin instanceof ${issue.expected}, oli ${received}`;\n }\n return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Virheellinen sy\u00F6te: t\u00E4ytyy olla ${util.stringifyPrimitive(issue.values[0])}`;\n return `Virheellinen valinta: t\u00E4ytyy olla yksi seuraavista: ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Liian suuri: ${sizing.subject} t\u00E4ytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim();\n }\n return `Liian suuri: arvon t\u00E4ytyy olla ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Liian pieni: ${sizing.subject} t\u00E4ytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim();\n }\n return `Liian pieni: arvon t\u00E4ytyy olla ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Virheellinen sy\u00F6te: t\u00E4ytyy alkaa \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Virheellinen sy\u00F6te: t\u00E4ytyy loppua \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Virheellinen sy\u00F6te: t\u00E4ytyy sis\u00E4lt\u00E4\u00E4 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\") {\n return `Virheellinen sy\u00F6te: t\u00E4ytyy vastata s\u00E4\u00E4nn\u00F6llist\u00E4 lauseketta ${_issue.pattern}`;\n }\n return `Virheellinen ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Virheellinen luku: t\u00E4ytyy olla luvun ${issue.divisor} monikerta`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Tuntemattomat avaimet\" : \"Tuntematon avain\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return \"Virheellinen avain tietueessa\";\n case \"invalid_union\":\n return \"Virheellinen unioni\";\n case \"invalid_element\":\n return \"Virheellinen arvo joukossa\";\n default:\n return `Virheellinen sy\u00F6te`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caract\u00E8res\", verb: \"avoir\" },\n file: { unit: \"octets\", verb: \"avoir\" },\n array: { unit: \"\u00E9l\u00E9ments\", verb: \"avoir\" },\n set: { unit: \"\u00E9l\u00E9ments\", verb: \"avoir\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"entr\u00E9e\",\n email: \"adresse e-mail\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"date et heure ISO\",\n date: \"date ISO\",\n time: \"heure ISO\",\n duration: \"dur\u00E9e ISO\",\n ipv4: \"adresse IPv4\",\n ipv6: \"adresse IPv6\",\n cidrv4: \"plage IPv4\",\n cidrv6: \"plage IPv6\",\n base64: \"cha\u00EEne encod\u00E9e en base64\",\n base64url: \"cha\u00EEne encod\u00E9e en base64url\",\n json_string: \"cha\u00EEne JSON\",\n e164: \"num\u00E9ro E.164\",\n jwt: \"JWT\",\n template_literal: \"entr\u00E9e\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"nombre\",\n array: \"tableau\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Entr\u00E9e invalide : instanceof ${issue.expected} attendu, ${received} re\u00E7u`;\n }\n return `Entr\u00E9e invalide : ${expected} attendu, ${received} re\u00E7u`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Entr\u00E9e invalide : ${util.stringifyPrimitive(issue.values[0])} attendu`;\n return `Option invalide : une valeur parmi ${util.joinValues(issue.values, \"|\")} attendue`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Trop grand : ${issue.origin ?? \"valeur\"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u00E9l\u00E9ment(s)\"}`;\n return `Trop grand : ${issue.origin ?? \"valeur\"} doit \u00EAtre ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Trop petit : ${issue.origin} doit \u00EAtre ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Cha\u00EEne invalide : doit commencer par \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Cha\u00EEne invalide : doit se terminer par \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Cha\u00EEne invalide : doit inclure \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Cha\u00EEne invalide : doit correspondre au mod\u00E8le ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} invalide`;\n }\n case \"not_multiple_of\":\n return `Nombre invalide : doit \u00EAtre un multiple de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Cl\u00E9${issue.keys.length > 1 ? \"s\" : \"\"} non reconnue${issue.keys.length > 1 ? \"s\" : \"\"} : ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Cl\u00E9 invalide dans ${issue.origin}`;\n case \"invalid_union\":\n return \"Entr\u00E9e invalide\";\n case \"invalid_element\":\n return `Valeur invalide dans ${issue.origin}`;\n default:\n return `Entr\u00E9e invalide`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caract\u00E8res\", verb: \"avoir\" },\n file: { unit: \"octets\", verb: \"avoir\" },\n array: { unit: \"\u00E9l\u00E9ments\", verb: \"avoir\" },\n set: { unit: \"\u00E9l\u00E9ments\", verb: \"avoir\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"entr\u00E9e\",\n email: \"adresse courriel\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"date-heure ISO\",\n date: \"date ISO\",\n time: \"heure ISO\",\n duration: \"dur\u00E9e ISO\",\n ipv4: \"adresse IPv4\",\n ipv6: \"adresse IPv6\",\n cidrv4: \"plage IPv4\",\n cidrv6: \"plage IPv6\",\n base64: \"cha\u00EEne encod\u00E9e en base64\",\n base64url: \"cha\u00EEne encod\u00E9e en base64url\",\n json_string: \"cha\u00EEne JSON\",\n e164: \"num\u00E9ro E.164\",\n jwt: \"JWT\",\n template_literal: \"entr\u00E9e\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Entr\u00E9e invalide : attendu instanceof ${issue.expected}, re\u00E7u ${received}`;\n }\n return `Entr\u00E9e invalide : attendu ${expected}, re\u00E7u ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Entr\u00E9e invalide : attendu ${util.stringifyPrimitive(issue.values[0])}`;\n return `Option invalide : attendu l'une des valeurs suivantes ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"\u2264\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Trop grand : attendu que ${issue.origin ?? \"la valeur\"} ait ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n return `Trop grand : attendu que ${issue.origin ?? \"la valeur\"} soit ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"\u2265\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Trop petit : attendu que ${issue.origin} ait ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Trop petit : attendu que ${issue.origin} soit ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Cha\u00EEne invalide : doit commencer par \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Cha\u00EEne invalide : doit se terminer par \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Cha\u00EEne invalide : doit inclure \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Cha\u00EEne invalide : doit correspondre au motif ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} invalide`;\n }\n case \"not_multiple_of\":\n return `Nombre invalide : doit \u00EAtre un multiple de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Cl\u00E9${issue.keys.length > 1 ? \"s\" : \"\"} non reconnue${issue.keys.length > 1 ? \"s\" : \"\"} : ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Cl\u00E9 invalide dans ${issue.origin}`;\n case \"invalid_union\":\n return \"Entr\u00E9e invalide\";\n case \"invalid_element\":\n return `Valeur invalide dans ${issue.origin}`;\n default:\n return `Entr\u00E9e invalide`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n // Hebrew labels + grammatical gender\n const TypeNames = {\n string: { label: \"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA\", gender: \"f\" },\n number: { label: \"\u05DE\u05E1\u05E4\u05E8\", gender: \"m\" },\n boolean: { label: \"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9\", gender: \"m\" },\n bigint: { label: \"BigInt\", gender: \"m\" },\n date: { label: \"\u05EA\u05D0\u05E8\u05D9\u05DA\", gender: \"m\" },\n array: { label: \"\u05DE\u05E2\u05E8\u05DA\", gender: \"m\" },\n object: { label: \"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8\", gender: \"m\" },\n null: { label: \"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)\", gender: \"m\" },\n undefined: { label: \"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)\", gender: \"m\" },\n symbol: { label: \"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)\", gender: \"m\" },\n function: { label: \"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4\", gender: \"f\" },\n map: { label: \"\u05DE\u05E4\u05D4 (Map)\", gender: \"f\" },\n set: { label: \"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)\", gender: \"f\" },\n file: { label: \"\u05E7\u05D5\u05D1\u05E5\", gender: \"m\" },\n promise: { label: \"Promise\", gender: \"m\" },\n NaN: { label: \"NaN\", gender: \"m\" },\n unknown: { label: \"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2\", gender: \"m\" },\n value: { label: \"\u05E2\u05E8\u05DA\", gender: \"m\" },\n };\n // Sizing units for size-related messages + localized origin labels\n const Sizable = {\n string: { unit: \"\u05EA\u05D5\u05D5\u05D9\u05DD\", shortLabel: \"\u05E7\u05E6\u05E8\", longLabel: \"\u05D0\u05E8\u05D5\u05DA\" },\n file: { unit: \"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD\", shortLabel: \"\u05E7\u05D8\u05DF\", longLabel: \"\u05D2\u05D3\u05D5\u05DC\" },\n array: { unit: \"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD\", shortLabel: \"\u05E7\u05D8\u05DF\", longLabel: \"\u05D2\u05D3\u05D5\u05DC\" },\n set: { unit: \"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD\", shortLabel: \"\u05E7\u05D8\u05DF\", longLabel: \"\u05D2\u05D3\u05D5\u05DC\" },\n number: { unit: \"\", shortLabel: \"\u05E7\u05D8\u05DF\", longLabel: \"\u05D2\u05D3\u05D5\u05DC\" }, // no unit\n };\n // Helpers \u2014 labels, articles, and verbs\n const typeEntry = (t) => (t ? TypeNames[t] : undefined);\n const typeLabel = (t) => {\n const e = typeEntry(t);\n if (e)\n return e.label;\n // fallback: show raw string if unknown\n return t ?? TypeNames.unknown.label;\n };\n const withDefinite = (t) => `\u05D4${typeLabel(t)}`;\n const verbFor = (t) => {\n const e = typeEntry(t);\n const gender = e?.gender ?? \"m\";\n return gender === \"f\" ? \"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA\" : \"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA\";\n };\n const getSizing = (origin) => {\n if (!origin)\n return null;\n return Sizable[origin] ?? null;\n };\n const FormatDictionary = {\n regex: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n email: { label: \"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC\", gender: \"f\" },\n url: { label: \"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA\", gender: \"f\" },\n emoji: { label: \"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9\", gender: \"m\" },\n uuid: { label: \"UUID\", gender: \"m\" },\n nanoid: { label: \"nanoid\", gender: \"m\" },\n guid: { label: \"GUID\", gender: \"m\" },\n cuid: { label: \"cuid\", gender: \"m\" },\n cuid2: { label: \"cuid2\", gender: \"m\" },\n ulid: { label: \"ULID\", gender: \"m\" },\n xid: { label: \"XID\", gender: \"m\" },\n ksuid: { label: \"KSUID\", gender: \"m\" },\n datetime: { label: \"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO\", gender: \"m\" },\n date: { label: \"\u05EA\u05D0\u05E8\u05D9\u05DA ISO\", gender: \"m\" },\n time: { label: \"\u05D6\u05DE\u05DF ISO\", gender: \"m\" },\n duration: { label: \"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO\", gender: \"m\" },\n ipv4: { label: \"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4\", gender: \"f\" },\n ipv6: { label: \"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6\", gender: \"f\" },\n cidrv4: { label: \"\u05D8\u05D5\u05D5\u05D7 IPv4\", gender: \"m\" },\n cidrv6: { label: \"\u05D8\u05D5\u05D5\u05D7 IPv6\", gender: \"m\" },\n base64: { label: \"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64\", gender: \"f\" },\n base64url: { label: \"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA\", gender: \"f\" },\n json_string: { label: \"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON\", gender: \"f\" },\n e164: { label: \"\u05DE\u05E1\u05E4\u05E8 E.164\", gender: \"m\" },\n jwt: { label: \"JWT\", gender: \"m\" },\n ends_with: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n includes: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n lowercase: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n starts_with: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n uppercase: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n // Expected type: show without definite article for clearer Hebrew\n const expectedKey = issue.expected;\n const expected = TypeDictionary[expectedKey ?? \"\"] ?? typeLabel(expectedKey);\n // Received: show localized label if known, otherwise constructor/raw\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;\n }\n return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;\n }\n case \"invalid_value\": {\n if (issue.values.length === 1) {\n return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${util.stringifyPrimitive(issue.values[0])}`;\n }\n // Join values with proper Hebrew formatting\n const stringified = issue.values.map((v) => util.stringifyPrimitive(v));\n if (issue.values.length === 2) {\n return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`;\n }\n // For 3+ values: \"a\", \"b\" \u05D0\u05D5 \"c\"\n const lastValue = stringified[stringified.length - 1];\n const restValues = stringified.slice(0, -1).join(\", \");\n return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`;\n }\n case \"too_big\": {\n const sizing = getSizing(issue.origin);\n const subject = withDefinite(issue.origin ?? \"value\");\n if (issue.origin === \"string\") {\n // Special handling for strings - more natural Hebrew\n return `${sizing?.longLabel ?? \"\u05D0\u05E8\u05D5\u05DA\"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue.maximum.toString()} ${sizing?.unit ?? \"\"} ${issue.inclusive ? \"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA\" : \"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8\"}`.trim();\n }\n if (issue.origin === \"number\") {\n // Natural Hebrew for numbers\n const comparison = issue.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue.maximum}`;\n return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;\n }\n if (issue.origin === \"array\" || issue.origin === \"set\") {\n // Natural Hebrew for arrays and sets\n const verb = issue.origin === \"set\" ? \"\u05E6\u05E8\u05D9\u05DB\u05D4\" : \"\u05E6\u05E8\u05D9\u05DA\";\n const comparison = issue.inclusive\n ? `${issue.maximum} ${sizing?.unit ?? \"\"} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`\n : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue.maximum} ${sizing?.unit ?? \"\"}`;\n return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();\n }\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const be = verbFor(issue.origin ?? \"value\");\n if (sizing?.unit) {\n return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n }\n return `${sizing?.longLabel ?? \"\u05D2\u05D3\u05D5\u05DC\"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const sizing = getSizing(issue.origin);\n const subject = withDefinite(issue.origin ?? \"value\");\n if (issue.origin === \"string\") {\n // Special handling for strings - more natural Hebrew\n return `${sizing?.shortLabel ?? \"\u05E7\u05E6\u05E8\"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue.minimum.toString()} ${sizing?.unit ?? \"\"} ${issue.inclusive ? \"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8\" : \"\u05DC\u05E4\u05D7\u05D5\u05EA\"}`.trim();\n }\n if (issue.origin === \"number\") {\n // Natural Hebrew for numbers\n const comparison = issue.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue.minimum}`;\n return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;\n }\n if (issue.origin === \"array\" || issue.origin === \"set\") {\n // Natural Hebrew for arrays and sets\n const verb = issue.origin === \"set\" ? \"\u05E6\u05E8\u05D9\u05DB\u05D4\" : \"\u05E6\u05E8\u05D9\u05DA\";\n // Special case for singular (minimum === 1)\n if (issue.minimum === 1 && issue.inclusive) {\n const singularPhrase = issue.origin === \"set\" ? \"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3\" : \"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3\";\n return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`;\n }\n const comparison = issue.inclusive\n ? `${issue.minimum} ${sizing?.unit ?? \"\"} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`\n : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue.minimum} ${sizing?.unit ?? \"\"}`;\n return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();\n }\n const adj = issue.inclusive ? \">=\" : \">\";\n const be = verbFor(issue.origin ?? \"value\");\n if (sizing?.unit) {\n return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `${sizing?.shortLabel ?? \"\u05E7\u05D8\u05DF\"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n // These apply to strings \u2014 use feminine grammar + \u05D4\u05F3 \u05D4\u05D9\u05D3\u05D9\u05E2\u05D4\n if (_issue.format === \"starts_with\")\n return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;\n // Handle gender agreement for formats\n const nounEntry = FormatDictionary[_issue.format];\n const noun = nounEntry?.label ?? _issue.format;\n const gender = nounEntry?.gender ?? \"m\";\n const adjective = gender === \"f\" ? \"\u05EA\u05E7\u05D9\u05E0\u05D4\" : \"\u05EA\u05E7\u05D9\u05DF\";\n return `${noun} \u05DC\u05D0 ${adjective}`;\n }\n case \"not_multiple_of\":\n return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u05DE\u05E4\u05EA\u05D7${issue.keys.length > 1 ? \"\u05D5\u05EA\" : \"\"} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue.keys.length > 1 ? \"\u05D9\u05DD\" : \"\u05D4\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\": {\n return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`;\n }\n case \"invalid_union\":\n return \"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF\";\n case \"invalid_element\": {\n const place = withDefinite(issue.origin ?? \"array\");\n return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`;\n }\n default:\n return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"karakter\", verb: \"legyen\" },\n file: { unit: \"byte\", verb: \"legyen\" },\n array: { unit: \"elem\", verb: \"legyen\" },\n set: { unit: \"elem\", verb: \"legyen\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"bemenet\",\n email: \"email c\u00EDm\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO id\u0151b\u00E9lyeg\",\n date: \"ISO d\u00E1tum\",\n time: \"ISO id\u0151\",\n duration: \"ISO id\u0151intervallum\",\n ipv4: \"IPv4 c\u00EDm\",\n ipv6: \"IPv6 c\u00EDm\",\n cidrv4: \"IPv4 tartom\u00E1ny\",\n cidrv6: \"IPv6 tartom\u00E1ny\",\n base64: \"base64-k\u00F3dolt string\",\n base64url: \"base64url-k\u00F3dolt string\",\n json_string: \"JSON string\",\n e164: \"E.164 sz\u00E1m\",\n jwt: \"JWT\",\n template_literal: \"bemenet\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"sz\u00E1m\",\n array: \"t\u00F6mb\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u00C9rv\u00E9nytelen bemenet: a v\u00E1rt \u00E9rt\u00E9k instanceof ${issue.expected}, a kapott \u00E9rt\u00E9k ${received}`;\n }\n return `\u00C9rv\u00E9nytelen bemenet: a v\u00E1rt \u00E9rt\u00E9k ${expected}, a kapott \u00E9rt\u00E9k ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u00C9rv\u00E9nytelen bemenet: a v\u00E1rt \u00E9rt\u00E9k ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u00C9rv\u00E9nytelen opci\u00F3: valamelyik \u00E9rt\u00E9k v\u00E1rt ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `T\u00FAl nagy: ${issue.origin ?? \"\u00E9rt\u00E9k\"} m\u00E9rete t\u00FAl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elem\"}`;\n return `T\u00FAl nagy: a bemeneti \u00E9rt\u00E9k ${issue.origin ?? \"\u00E9rt\u00E9k\"} t\u00FAl nagy: ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `T\u00FAl kicsi: a bemeneti \u00E9rt\u00E9k ${issue.origin} m\u00E9rete t\u00FAl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `T\u00FAl kicsi: a bemeneti \u00E9rt\u00E9k ${issue.origin} t\u00FAl kicsi ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u00C9rv\u00E9nytelen string: \"${_issue.prefix}\" \u00E9rt\u00E9kkel kell kezd\u0151dnie`;\n if (_issue.format === \"ends_with\")\n return `\u00C9rv\u00E9nytelen string: \"${_issue.suffix}\" \u00E9rt\u00E9kkel kell v\u00E9gz\u0151dnie`;\n if (_issue.format === \"includes\")\n return `\u00C9rv\u00E9nytelen string: \"${_issue.includes}\" \u00E9rt\u00E9ket kell tartalmaznia`;\n if (_issue.format === \"regex\")\n return `\u00C9rv\u00E9nytelen string: ${_issue.pattern} mint\u00E1nak kell megfelelnie`;\n return `\u00C9rv\u00E9nytelen ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u00C9rv\u00E9nytelen sz\u00E1m: ${issue.divisor} t\u00F6bbsz\u00F6r\u00F6s\u00E9nek kell lennie`;\n case \"unrecognized_keys\":\n return `Ismeretlen kulcs${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u00C9rv\u00E9nytelen kulcs ${issue.origin}`;\n case \"invalid_union\":\n return \"\u00C9rv\u00E9nytelen bemenet\";\n case \"invalid_element\":\n return `\u00C9rv\u00E9nytelen \u00E9rt\u00E9k: ${issue.origin}`;\n default:\n return `\u00C9rv\u00E9nytelen bemenet`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nfunction getArmenianPlural(count, one, many) {\n return Math.abs(count) === 1 ? one : many;\n}\nfunction withDefiniteArticle(word) {\n if (!word)\n return \"\";\n const vowels = [\"\u0561\", \"\u0565\", \"\u0568\", \"\u056B\", \"\u0578\", \"\u0578\u0582\", \"\u0585\"];\n const lastChar = word[word.length - 1];\n return word + (vowels.includes(lastChar) ? \"\u0576\" : \"\u0568\");\n}\nconst error = () => {\n const Sizable = {\n string: {\n unit: {\n one: \"\u0576\u0577\u0561\u0576\",\n many: \"\u0576\u0577\u0561\u0576\u0576\u0565\u0580\",\n },\n verb: \"\u0578\u0582\u0576\u0565\u0576\u0561\u056C\",\n },\n file: {\n unit: {\n one: \"\u0562\u0561\u0575\u0569\",\n many: \"\u0562\u0561\u0575\u0569\u0565\u0580\",\n },\n verb: \"\u0578\u0582\u0576\u0565\u0576\u0561\u056C\",\n },\n array: {\n unit: {\n one: \"\u057F\u0561\u0580\u0580\",\n many: \"\u057F\u0561\u0580\u0580\u0565\u0580\",\n },\n verb: \"\u0578\u0582\u0576\u0565\u0576\u0561\u056C\",\n },\n set: {\n unit: {\n one: \"\u057F\u0561\u0580\u0580\",\n many: \"\u057F\u0561\u0580\u0580\u0565\u0580\",\n },\n verb: \"\u0578\u0582\u0576\u0565\u0576\u0561\u056C\",\n },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0574\u0578\u0582\u057F\u0584\",\n email: \"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565\",\n url: \"URL\",\n emoji: \"\u0567\u0574\u0578\u057B\u056B\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574\",\n date: \"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E\",\n time: \"ISO \u056A\u0561\u0574\",\n duration: \"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576\",\n ipv4: \"IPv4 \u0570\u0561\u057D\u0581\u0565\",\n ipv6: \"IPv6 \u0570\u0561\u057D\u0581\u0565\",\n cidrv4: \"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584\",\n cidrv6: \"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584\",\n base64: \"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572\",\n base64url: \"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572\",\n json_string: \"JSON \u057F\u0578\u0572\",\n e164: \"E.164 \u0570\u0561\u0574\u0561\u0580\",\n jwt: \"JWT\",\n template_literal: \"\u0574\u0578\u0582\u057F\u0584\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0569\u056B\u057E\",\n array: \"\u0566\u0561\u0576\u0563\u057E\u0561\u056E\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;\n }\n return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${util.stringifyPrimitive(issue.values[1])}`;\n return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const maxValue = Number(issue.maximum);\n const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);\n return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue.origin ?? \"\u0561\u0580\u056A\u0565\u0584\")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue.maximum.toString()} ${unit}`;\n }\n return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue.origin ?? \"\u0561\u0580\u056A\u0565\u0584\")} \u056C\u056B\u0576\u056B ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const minValue = Number(issue.minimum);\n const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);\n return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue.minimum.toString()} ${unit}`;\n }\n return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue.origin)} \u056C\u056B\u0576\u056B ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B \"${_issue.prefix}\"-\u0578\u057E`;\n if (_issue.format === \"ends_with\")\n return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B \"${_issue.suffix}\"-\u0578\u057E`;\n if (_issue.format === \"includes\")\n return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;\n return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue.divisor}-\u056B`;\n case \"unrecognized_keys\":\n return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue.keys.length > 1 ? \"\u0576\u0565\u0580\" : \"\"}. ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue.origin)}-\u0578\u0582\u0574`;\n case \"invalid_union\":\n return \"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\";\n case \"invalid_element\":\n return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue.origin)}-\u0578\u0582\u0574`;\n default:\n return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"karakter\", verb: \"memiliki\" },\n file: { unit: \"byte\", verb: \"memiliki\" },\n array: { unit: \"item\", verb: \"memiliki\" },\n set: { unit: \"item\", verb: \"memiliki\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"alamat email\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"tanggal dan waktu format ISO\",\n date: \"tanggal format ISO\",\n time: \"jam format ISO\",\n duration: \"durasi format ISO\",\n ipv4: \"alamat IPv4\",\n ipv6: \"alamat IPv6\",\n cidrv4: \"rentang alamat IPv4\",\n cidrv6: \"rentang alamat IPv6\",\n base64: \"string dengan enkode base64\",\n base64url: \"string dengan enkode base64url\",\n json_string: \"string JSON\",\n e164: \"angka E.164\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Input tidak valid: diharapkan instanceof ${issue.expected}, diterima ${received}`;\n }\n return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Input tidak valid: diharapkan ${util.stringifyPrimitive(issue.values[0])}`;\n return `Pilihan tidak valid: diharapkan salah satu dari ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Terlalu besar: diharapkan ${issue.origin ?? \"value\"} memiliki ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elemen\"}`;\n return `Terlalu besar: diharapkan ${issue.origin ?? \"value\"} menjadi ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Terlalu kecil: diharapkan ${issue.origin} memiliki ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Terlalu kecil: diharapkan ${issue.origin} menjadi ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `String tidak valid: harus dimulai dengan \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `String tidak valid: harus berakhir dengan \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `String tidak valid: harus menyertakan \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `String tidak valid: harus sesuai pola ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} tidak valid`;\n }\n case \"not_multiple_of\":\n return `Angka tidak valid: harus kelipatan dari ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Kunci tidak dikenali ${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Kunci tidak valid di ${issue.origin}`;\n case \"invalid_union\":\n return \"Input tidak valid\";\n case \"invalid_element\":\n return `Nilai tidak valid di ${issue.origin}`;\n default:\n return `Input tidak valid`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"stafi\", verb: \"a\u00F0 hafa\" },\n file: { unit: \"b\u00E6ti\", verb: \"a\u00F0 hafa\" },\n array: { unit: \"hluti\", verb: \"a\u00F0 hafa\" },\n set: { unit: \"hluti\", verb: \"a\u00F0 hafa\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"gildi\",\n email: \"netfang\",\n url: \"vefsl\u00F3\u00F0\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO dagsetning og t\u00EDmi\",\n date: \"ISO dagsetning\",\n time: \"ISO t\u00EDmi\",\n duration: \"ISO t\u00EDmalengd\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded strengur\",\n base64url: \"base64url-encoded strengur\",\n json_string: \"JSON strengur\",\n e164: \"E.164 t\u00F6lugildi\",\n jwt: \"JWT\",\n template_literal: \"gildi\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"n\u00FAmer\",\n array: \"fylki\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Rangt gildi: \u00DE\u00FA sl\u00F3st inn ${received} \u00FEar sem \u00E1 a\u00F0 vera instanceof ${issue.expected}`;\n }\n return `Rangt gildi: \u00DE\u00FA sl\u00F3st inn ${received} \u00FEar sem \u00E1 a\u00F0 vera ${expected}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Rangt gildi: gert r\u00E1\u00F0 fyrir ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u00D3gilt val: m\u00E1 vera eitt af eftirfarandi ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Of st\u00F3rt: gert er r\u00E1\u00F0 fyrir a\u00F0 ${issue.origin ?? \"gildi\"} hafi ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"hluti\"}`;\n return `Of st\u00F3rt: gert er r\u00E1\u00F0 fyrir a\u00F0 ${issue.origin ?? \"gildi\"} s\u00E9 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Of l\u00EDti\u00F0: gert er r\u00E1\u00F0 fyrir a\u00F0 ${issue.origin} hafi ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Of l\u00EDti\u00F0: gert er r\u00E1\u00F0 fyrir a\u00F0 ${issue.origin} s\u00E9 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u00D3gildur strengur: ver\u00F0ur a\u00F0 byrja \u00E1 \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u00D3gildur strengur: ver\u00F0ur a\u00F0 enda \u00E1 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u00D3gildur strengur: ver\u00F0ur a\u00F0 innihalda \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u00D3gildur strengur: ver\u00F0ur a\u00F0 fylgja mynstri ${_issue.pattern}`;\n return `Rangt ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `R\u00F6ng tala: ver\u00F0ur a\u00F0 vera margfeldi af ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u00D3\u00FEekkt ${issue.keys.length > 1 ? \"ir lyklar\" : \"ur lykill\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Rangur lykill \u00ED ${issue.origin}`;\n case \"invalid_union\":\n return \"Rangt gildi\";\n case \"invalid_element\":\n return `Rangt gildi \u00ED ${issue.origin}`;\n default:\n return `Rangt gildi`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caratteri\", verb: \"avere\" },\n file: { unit: \"byte\", verb: \"avere\" },\n array: { unit: \"elementi\", verb: \"avere\" },\n set: { unit: \"elementi\", verb: \"avere\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"indirizzo email\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"data e ora ISO\",\n date: \"data ISO\",\n time: \"ora ISO\",\n duration: \"durata ISO\",\n ipv4: \"indirizzo IPv4\",\n ipv6: \"indirizzo IPv6\",\n cidrv4: \"intervallo IPv4\",\n cidrv6: \"intervallo IPv6\",\n base64: \"stringa codificata in base64\",\n base64url: \"URL codificata in base64\",\n json_string: \"stringa JSON\",\n e164: \"numero E.164\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"numero\",\n array: \"vettore\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Input non valido: atteso instanceof ${issue.expected}, ricevuto ${received}`;\n }\n return `Input non valido: atteso ${expected}, ricevuto ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`;\n return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Troppo grande: ${issue.origin ?? \"valore\"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementi\"}`;\n return `Troppo grande: ${issue.origin ?? \"valore\"} deve essere ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Stringa non valida: deve iniziare con \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Stringa non valida: deve terminare con \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Stringa non valida: deve includere \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Chiav${issue.keys.length > 1 ? \"i\" : \"e\"} non riconosciut${issue.keys.length > 1 ? \"e\" : \"a\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Chiave non valida in ${issue.origin}`;\n case \"invalid_union\":\n return \"Input non valido\";\n case \"invalid_element\":\n return `Valore non valido in ${issue.origin}`;\n default:\n return `Input non valido`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u6587\u5B57\", verb: \"\u3067\u3042\u308B\" },\n file: { unit: \"\u30D0\u30A4\u30C8\", verb: \"\u3067\u3042\u308B\" },\n array: { unit: \"\u8981\u7D20\", verb: \"\u3067\u3042\u308B\" },\n set: { unit: \"\u8981\u7D20\", verb: \"\u3067\u3042\u308B\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u5165\u529B\u5024\",\n email: \"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9\",\n url: \"URL\",\n emoji: \"\u7D75\u6587\u5B57\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO\u65E5\u6642\",\n date: \"ISO\u65E5\u4ED8\",\n time: \"ISO\u6642\u523B\",\n duration: \"ISO\u671F\u9593\",\n ipv4: \"IPv4\u30A2\u30C9\u30EC\u30B9\",\n ipv6: \"IPv6\u30A2\u30C9\u30EC\u30B9\",\n cidrv4: \"IPv4\u7BC4\u56F2\",\n cidrv6: \"IPv6\u7BC4\u56F2\",\n base64: \"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217\",\n base64url: \"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217\",\n json_string: \"JSON\u6587\u5B57\u5217\",\n e164: \"E.164\u756A\u53F7\",\n jwt: \"JWT\",\n template_literal: \"\u5165\u529B\u5024\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u6570\u5024\",\n array: \"\u914D\u5217\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;\n }\n return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u7121\u52B9\u306A\u5165\u529B: ${util.stringifyPrimitive(issue.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;\n return `\u7121\u52B9\u306A\u9078\u629E: ${util.joinValues(issue.values, \"\u3001\")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"\u4EE5\u4E0B\u3067\u3042\u308B\" : \"\u3088\u308A\u5C0F\u3055\u3044\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue.origin ?? \"\u5024\"}\u306F${issue.maximum.toString()}${sizing.unit ?? \"\u8981\u7D20\"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue.origin ?? \"\u5024\"}\u306F${issue.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"\u4EE5\u4E0A\u3067\u3042\u308B\" : \"\u3088\u308A\u5927\u304D\u3044\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue.origin}\u306F${issue.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue.origin}\u306F${issue.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \"${_issue.prefix}\"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n if (_issue.format === \"ends_with\")\n return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \"${_issue.suffix}\"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n if (_issue.format === \"includes\")\n return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \"${_issue.includes}\"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n if (_issue.format === \"regex\")\n return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u7121\u52B9\u306A\u6570\u5024: ${issue.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n case \"unrecognized_keys\":\n return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue.keys.length > 1 ? \"\u7FA4\" : \"\"}: ${util.joinValues(issue.keys, \"\u3001\")}`;\n case \"invalid_key\":\n return `${issue.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;\n case \"invalid_union\":\n return \"\u7121\u52B9\u306A\u5165\u529B\";\n case \"invalid_element\":\n return `${issue.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;\n default:\n return `\u7121\u52B9\u306A\u5165\u529B`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD\", verb: \"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1\" },\n file: { unit: \"\u10D1\u10D0\u10D8\u10E2\u10D8\", verb: \"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1\" },\n array: { unit: \"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8\", verb: \"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1\" },\n set: { unit: \"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8\", verb: \"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0\",\n email: \"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8\",\n url: \"URL\",\n emoji: \"\u10D4\u10DB\u10DD\u10EF\u10D8\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD\",\n date: \"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8\",\n time: \"\u10D3\u10E0\u10DD\",\n duration: \"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0\",\n ipv4: \"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8\",\n ipv6: \"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8\",\n cidrv4: \"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8\",\n cidrv6: \"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8\",\n base64: \"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8\",\n base64url: \"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8\",\n json_string: \"JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8\",\n e164: \"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8\",\n jwt: \"JWT\",\n template_literal: \"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8\",\n string: \"\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8\",\n boolean: \"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8\",\n function: \"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0\",\n array: \"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;\n }\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${util.joinValues(issue.values, \"|\")}-\u10D3\u10D0\u10DC`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue.origin ?? \"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue.origin ?? \"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0\"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \"${_issue.prefix}\"-\u10D8\u10D7`;\n }\n if (_issue.format === \"ends_with\")\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \"${_issue.suffix}\"-\u10D8\u10D7`;\n if (_issue.format === \"includes\")\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 \"${_issue.includes}\"-\u10E1`;\n if (_issue.format === \"regex\")\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`;\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;\n case \"unrecognized_keys\":\n return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue.keys.length > 1 ? \"\u10D4\u10D1\u10D8\" : \"\u10D8\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue.origin}-\u10E8\u10D8`;\n case \"invalid_union\":\n return \"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0\";\n case \"invalid_element\":\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue.origin}-\u10E8\u10D8`;\n default:\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A\", verb: \"\u1782\u17BD\u179A\u1798\u17B6\u1793\" },\n file: { unit: \"\u1794\u17C3\", verb: \"\u1782\u17BD\u179A\u1798\u17B6\u1793\" },\n array: { unit: \"\u1792\u17B6\u178F\u17BB\", verb: \"\u1782\u17BD\u179A\u1798\u17B6\u1793\" },\n set: { unit: \"\u1792\u17B6\u178F\u17BB\", verb: \"\u1782\u17BD\u179A\u1798\u17B6\u1793\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\",\n email: \"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B\",\n url: \"URL\",\n emoji: \"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO\",\n date: \"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO\",\n time: \"\u1798\u17C9\u17C4\u1784 ISO\",\n duration: \"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO\",\n ipv4: \"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4\",\n ipv6: \"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6\",\n cidrv4: \"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4\",\n cidrv6: \"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6\",\n base64: \"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64\",\n base64url: \"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url\",\n json_string: \"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON\",\n e164: \"\u179B\u17C1\u1781 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u179B\u17C1\u1781\",\n array: \"\u17A2\u17B6\u179A\u17C1 (Array)\",\n null: \"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;\n }\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue.origin ?? \"\u178F\u1798\u17D2\u179B\u17C3\"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"\u1792\u17B6\u178F\u17BB\"}`;\n return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue.origin ?? \"\u178F\u1798\u17D2\u179B\u17C3\"} ${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue.origin} ${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;\n return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue.origin}`;\n case \"invalid_union\":\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;\n case \"invalid_element\":\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue.origin}`;\n default:\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import km from \"./km.js\";\n/** @deprecated Use `km` instead. */\nexport default function () {\n return km();\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\uBB38\uC790\", verb: \"to have\" },\n file: { unit: \"\uBC14\uC774\uD2B8\", verb: \"to have\" },\n array: { unit: \"\uAC1C\", verb: \"to have\" },\n set: { unit: \"\uAC1C\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\uC785\uB825\",\n email: \"\uC774\uBA54\uC77C \uC8FC\uC18C\",\n url: \"URL\",\n emoji: \"\uC774\uBAA8\uC9C0\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \uB0A0\uC9DC\uC2DC\uAC04\",\n date: \"ISO \uB0A0\uC9DC\",\n time: \"ISO \uC2DC\uAC04\",\n duration: \"ISO \uAE30\uAC04\",\n ipv4: \"IPv4 \uC8FC\uC18C\",\n ipv6: \"IPv6 \uC8FC\uC18C\",\n cidrv4: \"IPv4 \uBC94\uC704\",\n cidrv6: \"IPv6 \uBC94\uC704\",\n base64: \"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4\",\n base64url: \"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4\",\n json_string: \"JSON \uBB38\uC790\uC5F4\",\n e164: \"E.164 \uBC88\uD638\",\n jwt: \"JWT\",\n template_literal: \"\uC785\uB825\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;\n }\n return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${util.stringifyPrimitive(issue.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;\n return `\uC798\uBABB\uB41C \uC635\uC158: ${util.joinValues(issue.values, \"\uB610\uB294 \")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"\uC774\uD558\" : \"\uBBF8\uB9CC\";\n const suffix = adj === \"\uBBF8\uB9CC\" ? \"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4\" : \"\uC5EC\uC57C \uD569\uB2C8\uB2E4\";\n const sizing = getSizing(issue.origin);\n const unit = sizing?.unit ?? \"\uC694\uC18C\";\n if (sizing)\n return `${issue.origin ?? \"\uAC12\"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue.maximum.toString()}${unit} ${adj}${suffix}`;\n return `${issue.origin ?? \"\uAC12\"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue.maximum.toString()} ${adj}${suffix}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"\uC774\uC0C1\" : \"\uCD08\uACFC\";\n const suffix = adj === \"\uC774\uC0C1\" ? \"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4\" : \"\uC5EC\uC57C \uD569\uB2C8\uB2E4\";\n const sizing = getSizing(issue.origin);\n const unit = sizing?.unit ?? \"\uC694\uC18C\";\n if (sizing) {\n return `${issue.origin ?? \"\uAC12\"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue.minimum.toString()}${unit} ${adj}${suffix}`;\n }\n return `${issue.origin ?? \"\uAC12\"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue.minimum.toString()} ${adj}${suffix}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \"${_issue.prefix}\"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;\n }\n if (_issue.format === \"ends_with\")\n return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \"${_issue.suffix}\"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;\n if (_issue.format === \"includes\")\n return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \"${_issue.includes}\"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;\n if (_issue.format === \"regex\")\n return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;\n return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;\n case \"unrecognized_keys\":\n return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\uC798\uBABB\uB41C \uD0A4: ${issue.origin}`;\n case \"invalid_union\":\n return `\uC798\uBABB\uB41C \uC785\uB825`;\n case \"invalid_element\":\n return `\uC798\uBABB\uB41C \uAC12: ${issue.origin}`;\n default:\n return `\uC798\uBABB\uB41C \uC785\uB825`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst capitalizeFirstCharacter = (text) => {\n return text.charAt(0).toUpperCase() + text.slice(1);\n};\nfunction getUnitTypeFromNumber(number) {\n const abs = Math.abs(number);\n const last = abs % 10;\n const last2 = abs % 100;\n if ((last2 >= 11 && last2 <= 19) || last === 0)\n return \"many\";\n if (last === 1)\n return \"one\";\n return \"few\";\n}\nconst error = () => {\n const Sizable = {\n string: {\n unit: {\n one: \"simbolis\",\n few: \"simboliai\",\n many: \"simboli\u0173\",\n },\n verb: {\n smaller: {\n inclusive: \"turi b\u016Bti ne ilgesn\u0117 kaip\",\n notInclusive: \"turi b\u016Bti trumpesn\u0117 kaip\",\n },\n bigger: {\n inclusive: \"turi b\u016Bti ne trumpesn\u0117 kaip\",\n notInclusive: \"turi b\u016Bti ilgesn\u0117 kaip\",\n },\n },\n },\n file: {\n unit: {\n one: \"baitas\",\n few: \"baitai\",\n many: \"bait\u0173\",\n },\n verb: {\n smaller: {\n inclusive: \"turi b\u016Bti ne didesnis kaip\",\n notInclusive: \"turi b\u016Bti ma\u017Eesnis kaip\",\n },\n bigger: {\n inclusive: \"turi b\u016Bti ne ma\u017Eesnis kaip\",\n notInclusive: \"turi b\u016Bti didesnis kaip\",\n },\n },\n },\n array: {\n unit: {\n one: \"element\u0105\",\n few: \"elementus\",\n many: \"element\u0173\",\n },\n verb: {\n smaller: {\n inclusive: \"turi tur\u0117ti ne daugiau kaip\",\n notInclusive: \"turi tur\u0117ti ma\u017Eiau kaip\",\n },\n bigger: {\n inclusive: \"turi tur\u0117ti ne ma\u017Eiau kaip\",\n notInclusive: \"turi tur\u0117ti daugiau kaip\",\n },\n },\n },\n set: {\n unit: {\n one: \"element\u0105\",\n few: \"elementus\",\n many: \"element\u0173\",\n },\n verb: {\n smaller: {\n inclusive: \"turi tur\u0117ti ne daugiau kaip\",\n notInclusive: \"turi tur\u0117ti ma\u017Eiau kaip\",\n },\n bigger: {\n inclusive: \"turi tur\u0117ti ne ma\u017Eiau kaip\",\n notInclusive: \"turi tur\u0117ti daugiau kaip\",\n },\n },\n },\n };\n function getSizing(origin, unitType, inclusive, targetShouldBe) {\n const result = Sizable[origin] ?? null;\n if (result === null)\n return result;\n return {\n unit: result.unit[unitType],\n verb: result.verb[targetShouldBe][inclusive ? \"inclusive\" : \"notInclusive\"],\n };\n }\n const FormatDictionary = {\n regex: \"\u012Fvestis\",\n email: \"el. pa\u0161to adresas\",\n url: \"URL\",\n emoji: \"jaustukas\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO data ir laikas\",\n date: \"ISO data\",\n time: \"ISO laikas\",\n duration: \"ISO trukm\u0117\",\n ipv4: \"IPv4 adresas\",\n ipv6: \"IPv6 adresas\",\n cidrv4: \"IPv4 tinklo prefiksas (CIDR)\",\n cidrv6: \"IPv6 tinklo prefiksas (CIDR)\",\n base64: \"base64 u\u017Ekoduota eilut\u0117\",\n base64url: \"base64url u\u017Ekoduota eilut\u0117\",\n json_string: \"JSON eilut\u0117\",\n e164: \"E.164 numeris\",\n jwt: \"JWT\",\n template_literal: \"\u012Fvestis\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"skai\u010Dius\",\n bigint: \"sveikasis skai\u010Dius\",\n string: \"eilut\u0117\",\n boolean: \"login\u0117 reik\u0161m\u0117\",\n undefined: \"neapibr\u0117\u017Eta reik\u0161m\u0117\",\n function: \"funkcija\",\n symbol: \"simbolis\",\n array: \"masyvas\",\n object: \"objektas\",\n null: \"nulin\u0117 reik\u0161m\u0117\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue.expected}`;\n }\n return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Privalo b\u016Bti ${util.stringifyPrimitive(issue.values[0])}`;\n return `Privalo b\u016Bti vienas i\u0161 ${util.joinValues(issue.values, \"|\")} pasirinkim\u0173`;\n case \"too_big\": {\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.maximum)), issue.inclusive ?? false, \"smaller\");\n if (sizing?.verb)\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} ${sizing.verb} ${issue.maximum.toString()} ${sizing.unit ?? \"element\u0173\"}`;\n const adj = issue.inclusive ? \"ne didesnis kaip\" : \"ma\u017Eesnis kaip\";\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} turi b\u016Bti ${adj} ${issue.maximum.toString()} ${sizing?.unit}`;\n }\n case \"too_small\": {\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.minimum)), issue.inclusive ?? false, \"bigger\");\n if (sizing?.verb)\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} ${sizing.verb} ${issue.minimum.toString()} ${sizing.unit ?? \"element\u0173\"}`;\n const adj = issue.inclusive ? \"ne ma\u017Eesnis kaip\" : \"didesnis kaip\";\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} turi b\u016Bti ${adj} ${issue.minimum.toString()} ${sizing?.unit}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Eilut\u0117 privalo prasid\u0117ti \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Eilut\u0117 privalo pasibaigti \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Eilut\u0117 privalo \u012Ftraukti \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Eilut\u0117 privalo atitikti ${_issue.pattern}`;\n return `Neteisingas ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Skai\u010Dius privalo b\u016Bti ${issue.divisor} kartotinis.`;\n case \"unrecognized_keys\":\n return `Neatpa\u017Eint${issue.keys.length > 1 ? \"i\" : \"as\"} rakt${issue.keys.length > 1 ? \"ai\" : \"as\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return \"Rastas klaidingas raktas\";\n case \"invalid_union\":\n return \"Klaidinga \u012Fvestis\";\n case \"invalid_element\": {\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} turi klaiding\u0105 \u012Fvest\u012F`;\n }\n default:\n return \"Klaidinga \u012Fvestis\";\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0437\u043D\u0430\u0446\u0438\", verb: \"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442\" },\n file: { unit: \"\u0431\u0430\u0458\u0442\u0438\", verb: \"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442\" },\n array: { unit: \"\u0441\u0442\u0430\u0432\u043A\u0438\", verb: \"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442\" },\n set: { unit: \"\u0441\u0442\u0430\u0432\u043A\u0438\", verb: \"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0432\u043D\u0435\u0441\",\n email: \"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430\",\n url: \"URL\",\n emoji: \"\u0435\u043C\u043E\u045F\u0438\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435\",\n date: \"ISO \u0434\u0430\u0442\u0443\u043C\",\n time: \"ISO \u0432\u0440\u0435\u043C\u0435\",\n duration: \"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435\",\n ipv4: \"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430\",\n ipv6: \"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430\",\n cidrv4: \"IPv4 \u043E\u043F\u0441\u0435\u0433\",\n cidrv6: \"IPv6 \u043E\u043F\u0441\u0435\u0433\",\n base64: \"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430\",\n base64url: \"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430\",\n json_string: \"JSON \u043D\u0438\u0437\u0430\",\n e164: \"E.164 \u0431\u0440\u043E\u0458\",\n jwt: \"JWT\",\n template_literal: \"\u0432\u043D\u0435\u0441\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0431\u0440\u043E\u0458\",\n array: \"\u043D\u0438\u0437\u0430\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;\n }\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue.origin ?? \"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430\"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438\"}`;\n return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue.origin ?? \"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430\"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438\" : \"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue.origin}`;\n case \"invalid_union\":\n return \"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441\";\n case \"invalid_element\":\n return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue.origin}`;\n default:\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"aksara\", verb: \"mempunyai\" },\n file: { unit: \"bait\", verb: \"mempunyai\" },\n array: { unit: \"elemen\", verb: \"mempunyai\" },\n set: { unit: \"elemen\", verb: \"mempunyai\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"alamat e-mel\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"tarikh masa ISO\",\n date: \"tarikh ISO\",\n time: \"masa ISO\",\n duration: \"tempoh ISO\",\n ipv4: \"alamat IPv4\",\n ipv6: \"alamat IPv6\",\n cidrv4: \"julat IPv4\",\n cidrv6: \"julat IPv6\",\n base64: \"string dikodkan base64\",\n base64url: \"string dikodkan base64url\",\n json_string: \"string JSON\",\n e164: \"nombor E.164\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"nombor\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Input tidak sah: dijangka instanceof ${issue.expected}, diterima ${received}`;\n }\n return `Input tidak sah: dijangka ${expected}, diterima ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Input tidak sah: dijangka ${util.stringifyPrimitive(issue.values[0])}`;\n return `Pilihan tidak sah: dijangka salah satu daripada ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Terlalu besar: dijangka ${issue.origin ?? \"nilai\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elemen\"}`;\n return `Terlalu besar: dijangka ${issue.origin ?? \"nilai\"} adalah ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `String tidak sah: mesti bermula dengan \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `String tidak sah: mesti berakhir dengan \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `String tidak sah: mesti mengandungi \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} tidak sah`;\n }\n case \"not_multiple_of\":\n return `Nombor tidak sah: perlu gandaan ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Kunci tidak dikenali: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Kunci tidak sah dalam ${issue.origin}`;\n case \"invalid_union\":\n return \"Input tidak sah\";\n case \"invalid_element\":\n return `Nilai tidak sah dalam ${issue.origin}`;\n default:\n return `Input tidak sah`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"tekens\", verb: \"heeft\" },\n file: { unit: \"bytes\", verb: \"heeft\" },\n array: { unit: \"elementen\", verb: \"heeft\" },\n set: { unit: \"elementen\", verb: \"heeft\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"invoer\",\n email: \"emailadres\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datum en tijd\",\n date: \"ISO datum\",\n time: \"ISO tijd\",\n duration: \"ISO duur\",\n ipv4: \"IPv4-adres\",\n ipv6: \"IPv6-adres\",\n cidrv4: \"IPv4-bereik\",\n cidrv6: \"IPv6-bereik\",\n base64: \"base64-gecodeerde tekst\",\n base64url: \"base64 URL-gecodeerde tekst\",\n json_string: \"JSON string\",\n e164: \"E.164-nummer\",\n jwt: \"JWT\",\n template_literal: \"invoer\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"getal\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ongeldige invoer: verwacht instanceof ${issue.expected}, ontving ${received}`;\n }\n return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ongeldige invoer: verwacht ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ongeldige optie: verwacht \u00E9\u00E9n van ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n const longName = issue.origin === \"date\" ? \"laat\" : issue.origin === \"string\" ? \"lang\" : \"groot\";\n if (sizing)\n return `Te ${longName}: verwacht dat ${issue.origin ?? \"waarde\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementen\"} ${sizing.verb}`;\n return `Te ${longName}: verwacht dat ${issue.origin ?? \"waarde\"} ${adj}${issue.maximum.toString()} is`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n const shortName = issue.origin === \"date\" ? \"vroeg\" : issue.origin === \"string\" ? \"kort\" : \"klein\";\n if (sizing) {\n return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;\n }\n return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Ongeldige tekst: moet met \"${_issue.prefix}\" beginnen`;\n }\n if (_issue.format === \"ends_with\")\n return `Ongeldige tekst: moet op \"${_issue.suffix}\" eindigen`;\n if (_issue.format === \"includes\")\n return `Ongeldige tekst: moet \"${_issue.includes}\" bevatten`;\n if (_issue.format === \"regex\")\n return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;\n return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`;\n case \"unrecognized_keys\":\n return `Onbekende key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ongeldige key in ${issue.origin}`;\n case \"invalid_union\":\n return \"Ongeldige invoer\";\n case \"invalid_element\":\n return `Ongeldige waarde in ${issue.origin}`;\n default:\n return `Ongeldige invoer`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"tegn\", verb: \"\u00E5 ha\" },\n file: { unit: \"bytes\", verb: \"\u00E5 ha\" },\n array: { unit: \"elementer\", verb: \"\u00E5 inneholde\" },\n set: { unit: \"elementer\", verb: \"\u00E5 inneholde\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"e-postadresse\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO dato- og klokkeslett\",\n date: \"ISO-dato\",\n time: \"ISO-klokkeslett\",\n duration: \"ISO-varighet\",\n ipv4: \"IPv4-omr\u00E5de\",\n ipv6: \"IPv6-omr\u00E5de\",\n cidrv4: \"IPv4-spekter\",\n cidrv6: \"IPv6-spekter\",\n base64: \"base64-enkodet streng\",\n base64url: \"base64url-enkodet streng\",\n json_string: \"JSON-streng\",\n e164: \"E.164-nummer\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"tall\",\n array: \"liste\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ugyldig input: forventet instanceof ${issue.expected}, fikk ${received}`;\n }\n return `Ugyldig input: forventet ${expected}, fikk ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ugyldig verdi: forventet ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ugyldig valg: forventet en av ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `For stor(t): forventet ${issue.origin ?? \"value\"} til \u00E5 ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementer\"}`;\n return `For stor(t): forventet ${issue.origin ?? \"value\"} til \u00E5 ha ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `For lite(n): forventet ${issue.origin} til \u00E5 ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `For lite(n): forventet ${issue.origin} til \u00E5 ha ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Ugyldig streng: m\u00E5 starte med \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Ugyldig streng: m\u00E5 ende med \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Ugyldig streng: m\u00E5 inneholde \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Ugyldig streng: m\u00E5 matche m\u00F8nsteret ${_issue.pattern}`;\n return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ugyldig tall: m\u00E5 v\u00E6re et multiplum av ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Ukjente n\u00F8kler\" : \"Ukjent n\u00F8kkel\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ugyldig n\u00F8kkel i ${issue.origin}`;\n case \"invalid_union\":\n return \"Ugyldig input\";\n case \"invalid_element\":\n return `Ugyldig verdi i ${issue.origin}`;\n default:\n return `Ugyldig input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"harf\", verb: \"olmal\u0131d\u0131r\" },\n file: { unit: \"bayt\", verb: \"olmal\u0131d\u0131r\" },\n array: { unit: \"unsur\", verb: \"olmal\u0131d\u0131r\" },\n set: { unit: \"unsur\", verb: \"olmal\u0131d\u0131r\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"giren\",\n email: \"epostag\u00E2h\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO heng\u00E2m\u0131\",\n date: \"ISO tarihi\",\n time: \"ISO zaman\u0131\",\n duration: \"ISO m\u00FCddeti\",\n ipv4: \"IPv4 ni\u015F\u00E2n\u0131\",\n ipv6: \"IPv6 ni\u015F\u00E2n\u0131\",\n cidrv4: \"IPv4 menzili\",\n cidrv6: \"IPv6 menzili\",\n base64: \"base64-\u015Fifreli metin\",\n base64url: \"base64url-\u015Fifreli metin\",\n json_string: \"JSON metin\",\n e164: \"E.164 say\u0131s\u0131\",\n jwt: \"JWT\",\n template_literal: \"giren\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"numara\",\n array: \"saf\",\n null: \"gayb\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `F\u00E2sit giren: umulan instanceof ${issue.expected}, al\u0131nan ${received}`;\n }\n return `F\u00E2sit giren: umulan ${expected}, al\u0131nan ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `F\u00E2sit giren: umulan ${util.stringifyPrimitive(issue.values[0])}`;\n return `F\u00E2sit tercih: m\u00FBteberler ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Fazla b\u00FCy\u00FCk: ${issue.origin ?? \"value\"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"} sahip olmal\u0131yd\u0131.`;\n return `Fazla b\u00FCy\u00FCk: ${issue.origin ?? \"value\"}, ${adj}${issue.maximum.toString()} olmal\u0131yd\u0131.`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Fazla k\u00FC\u00E7\u00FCk: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;\n }\n return `Fazla k\u00FC\u00E7\u00FCk: ${issue.origin}, ${adj}${issue.minimum.toString()} olmal\u0131yd\u0131.`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `F\u00E2sit metin: \"${_issue.prefix}\" ile ba\u015Flamal\u0131.`;\n if (_issue.format === \"ends_with\")\n return `F\u00E2sit metin: \"${_issue.suffix}\" ile bitmeli.`;\n if (_issue.format === \"includes\")\n return `F\u00E2sit metin: \"${_issue.includes}\" ihtiv\u00E2 etmeli.`;\n if (_issue.format === \"regex\")\n return `F\u00E2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;\n return `F\u00E2sit ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `F\u00E2sit say\u0131: ${issue.divisor} kat\u0131 olmal\u0131yd\u0131.`;\n case \"unrecognized_keys\":\n return `Tan\u0131nmayan anahtar ${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} i\u00E7in tan\u0131nmayan anahtar var.`;\n case \"invalid_union\":\n return \"Giren tan\u0131namad\u0131.\";\n case \"invalid_element\":\n return `${issue.origin} i\u00E7in tan\u0131nmayan k\u0131ymet var.`;\n default:\n return `K\u0131ymet tan\u0131namad\u0131.`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u062A\u0648\u06A9\u064A\", verb: \"\u0648\u0644\u0631\u064A\" },\n file: { unit: \"\u0628\u0627\u06CC\u067C\u0633\", verb: \"\u0648\u0644\u0631\u064A\" },\n array: { unit: \"\u062A\u0648\u06A9\u064A\", verb: \"\u0648\u0644\u0631\u064A\" },\n set: { unit: \"\u062A\u0648\u06A9\u064A\", verb: \"\u0648\u0644\u0631\u064A\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0648\u0631\u0648\u062F\u064A\",\n email: \"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9\",\n url: \"\u06CC\u0648 \u0622\u0631 \u0627\u0644\",\n emoji: \"\u0627\u06CC\u0645\u0648\u062C\u064A\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A\",\n date: \"\u0646\u06D0\u067C\u0647\",\n time: \"\u0648\u062E\u062A\",\n duration: \"\u0645\u0648\u062F\u0647\",\n ipv4: \"\u062F IPv4 \u067E\u062A\u0647\",\n ipv6: \"\u062F IPv6 \u067E\u062A\u0647\",\n cidrv4: \"\u062F IPv4 \u0633\u0627\u062D\u0647\",\n cidrv6: \"\u062F IPv6 \u0633\u0627\u062D\u0647\",\n base64: \"base64-encoded \u0645\u062A\u0646\",\n base64url: \"base64url-encoded \u0645\u062A\u0646\",\n json_string: \"JSON \u0645\u062A\u0646\",\n e164: \"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647\",\n jwt: \"JWT\",\n template_literal: \"\u0648\u0631\u0648\u062F\u064A\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0639\u062F\u062F\",\n array: \"\u0627\u0631\u06D0\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;\n }\n return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1) {\n return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${util.stringifyPrimitive(issue.values[0])} \u0648\u0627\u06CC`;\n }\n return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${util.joinValues(issue.values, \"|\")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue.origin ?? \"\u0627\u0631\u0632\u069A\u062A\"} \u0628\u0627\u06CC\u062F ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0639\u0646\u0635\u0631\u0648\u0646\u0647\"} \u0648\u0644\u0631\u064A`;\n }\n return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue.origin ?? \"\u0627\u0631\u0632\u069A\u062A\"} \u0628\u0627\u06CC\u062F ${adj}${issue.maximum.toString()} \u0648\u064A`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue.origin} \u0628\u0627\u06CC\u062F ${adj}${issue.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;\n }\n return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue.origin} \u0628\u0627\u06CC\u062F ${adj}${issue.minimum.toString()} \u0648\u064A`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F \"${_issue.prefix}\" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;\n }\n if (_issue.format === \"ends_with\") {\n return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F \"${_issue.suffix}\" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;\n }\n if (_issue.format === \"includes\") {\n return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \"${_issue.includes}\" \u0648\u0644\u0631\u064A`;\n }\n if (_issue.format === \"regex\") {\n return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;\n }\n return `${FormatDictionary[_issue.format] ?? issue.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;\n }\n case \"not_multiple_of\":\n return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;\n case \"unrecognized_keys\":\n return `\u0646\u0627\u0633\u0645 ${issue.keys.length > 1 ? \"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647\" : \"\u06A9\u0644\u06CC\u0689\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue.origin} \u06A9\u06D0`;\n case \"invalid_union\":\n return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;\n case \"invalid_element\":\n return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue.origin} \u06A9\u06D0`;\n default:\n return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"znak\u00F3w\", verb: \"mie\u0107\" },\n file: { unit: \"bajt\u00F3w\", verb: \"mie\u0107\" },\n array: { unit: \"element\u00F3w\", verb: \"mie\u0107\" },\n set: { unit: \"element\u00F3w\", verb: \"mie\u0107\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"wyra\u017Cenie\",\n email: \"adres email\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"data i godzina w formacie ISO\",\n date: \"data w formacie ISO\",\n time: \"godzina w formacie ISO\",\n duration: \"czas trwania ISO\",\n ipv4: \"adres IPv4\",\n ipv6: \"adres IPv6\",\n cidrv4: \"zakres IPv4\",\n cidrv6: \"zakres IPv6\",\n base64: \"ci\u0105g znak\u00F3w zakodowany w formacie base64\",\n base64url: \"ci\u0105g znak\u00F3w zakodowany w formacie base64url\",\n json_string: \"ci\u0105g znak\u00F3w w formacie JSON\",\n e164: \"liczba E.164\",\n jwt: \"JWT\",\n template_literal: \"wej\u015Bcie\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"liczba\",\n array: \"tablica\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue.expected}, otrzymano ${received}`;\n }\n return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${util.stringifyPrimitive(issue.values[0])}`;\n return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue.origin ?? \"warto\u015B\u0107\"} b\u0119dzie mie\u0107 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"element\u00F3w\"}`;\n }\n return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue.origin ?? \"warto\u015B\u0107\"} b\u0119dzie wynosi\u0107 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue.origin ?? \"warto\u015B\u0107\"} b\u0119dzie mie\u0107 ${adj}${issue.minimum.toString()} ${sizing.unit ?? \"element\u00F3w\"}`;\n }\n return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue.origin ?? \"warto\u015B\u0107\"} b\u0119dzie wynosi\u0107 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Nieprawid\u0142owy ci\u0105g znak\u00F3w: musi zaczyna\u0107 si\u0119 od \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Nieprawid\u0142owy ci\u0105g znak\u00F3w: musi ko\u0144czy\u0107 si\u0119 na \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Nieprawid\u0142owy ci\u0105g znak\u00F3w: musi zawiera\u0107 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Nieprawid\u0142owy ci\u0105g znak\u00F3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;\n return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Nierozpoznane klucze${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Nieprawid\u0142owy klucz w ${issue.origin}`;\n case \"invalid_union\":\n return \"Nieprawid\u0142owe dane wej\u015Bciowe\";\n case \"invalid_element\":\n return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue.origin}`;\n default:\n return `Nieprawid\u0142owe dane wej\u015Bciowe`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caracteres\", verb: \"ter\" },\n file: { unit: \"bytes\", verb: \"ter\" },\n array: { unit: \"itens\", verb: \"ter\" },\n set: { unit: \"itens\", verb: \"ter\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"padr\u00E3o\",\n email: \"endere\u00E7o de e-mail\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"data e hora ISO\",\n date: \"data ISO\",\n time: \"hora ISO\",\n duration: \"dura\u00E7\u00E3o ISO\",\n ipv4: \"endere\u00E7o IPv4\",\n ipv6: \"endere\u00E7o IPv6\",\n cidrv4: \"faixa de IPv4\",\n cidrv6: \"faixa de IPv6\",\n base64: \"texto codificado em base64\",\n base64url: \"URL codificada em base64\",\n json_string: \"texto JSON\",\n e164: \"n\u00FAmero E.164\",\n jwt: \"JWT\",\n template_literal: \"entrada\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"n\u00FAmero\",\n null: \"nulo\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Tipo inv\u00E1lido: esperado instanceof ${issue.expected}, recebido ${received}`;\n }\n return `Tipo inv\u00E1lido: esperado ${expected}, recebido ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Entrada inv\u00E1lida: esperado ${util.stringifyPrimitive(issue.values[0])}`;\n return `Op\u00E7\u00E3o inv\u00E1lida: esperada uma das ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Muito grande: esperado que ${issue.origin ?? \"valor\"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementos\"}`;\n return `Muito grande: esperado que ${issue.origin ?? \"valor\"} fosse ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Texto inv\u00E1lido: deve come\u00E7ar com \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Texto inv\u00E1lido: deve terminar com \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Texto inv\u00E1lido: deve incluir \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Texto inv\u00E1lido: deve corresponder ao padr\u00E3o ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} inv\u00E1lido`;\n }\n case \"not_multiple_of\":\n return `N\u00FAmero inv\u00E1lido: deve ser m\u00FAltiplo de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Chave${issue.keys.length > 1 ? \"s\" : \"\"} desconhecida${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Chave inv\u00E1lida em ${issue.origin}`;\n case \"invalid_union\":\n return \"Entrada inv\u00E1lida\";\n case \"invalid_element\":\n return `Valor inv\u00E1lido em ${issue.origin}`;\n default:\n return `Campo inv\u00E1lido`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nfunction getRussianPlural(count, one, few, many) {\n const absCount = Math.abs(count);\n const lastDigit = absCount % 10;\n const lastTwoDigits = absCount % 100;\n if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {\n return many;\n }\n if (lastDigit === 1) {\n return one;\n }\n if (lastDigit >= 2 && lastDigit <= 4) {\n return few;\n }\n return many;\n}\nconst error = () => {\n const Sizable = {\n string: {\n unit: {\n one: \"\u0441\u0438\u043C\u0432\u043E\u043B\",\n few: \"\u0441\u0438\u043C\u0432\u043E\u043B\u0430\",\n many: \"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432\",\n },\n verb: \"\u0438\u043C\u0435\u0442\u044C\",\n },\n file: {\n unit: {\n one: \"\u0431\u0430\u0439\u0442\",\n few: \"\u0431\u0430\u0439\u0442\u0430\",\n many: \"\u0431\u0430\u0439\u0442\",\n },\n verb: \"\u0438\u043C\u0435\u0442\u044C\",\n },\n array: {\n unit: {\n one: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\",\n few: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\",\n many: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\",\n },\n verb: \"\u0438\u043C\u0435\u0442\u044C\",\n },\n set: {\n unit: {\n one: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\",\n few: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\",\n many: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\",\n },\n verb: \"\u0438\u043C\u0435\u0442\u044C\",\n },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0432\u0432\u043E\u0434\",\n email: \"email \u0430\u0434\u0440\u0435\u0441\",\n url: \"URL\",\n emoji: \"\u044D\u043C\u043E\u0434\u0437\u0438\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F\",\n date: \"ISO \u0434\u0430\u0442\u0430\",\n time: \"ISO \u0432\u0440\u0435\u043C\u044F\",\n duration: \"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C\",\n ipv4: \"IPv4 \u0430\u0434\u0440\u0435\u0441\",\n ipv6: \"IPv6 \u0430\u0434\u0440\u0435\u0441\",\n cidrv4: \"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\",\n cidrv6: \"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\",\n base64: \"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64\",\n base64url: \"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url\",\n json_string: \"JSON \u0441\u0442\u0440\u043E\u043A\u0430\",\n e164: \"\u043D\u043E\u043C\u0435\u0440 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0432\u0432\u043E\u0434\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0447\u0438\u0441\u043B\u043E\",\n array: \"\u043C\u0430\u0441\u0441\u0438\u0432\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;\n }\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const maxValue = Number(issue.maximum);\n const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue.maximum.toString()} ${unit}`;\n }\n return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const minValue = Number(issue.minimum);\n const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue.minimum.toString()} ${unit}`;\n }\n return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue.keys.length > 1 ? \"\u044B\u0435\" : \"\u044B\u0439\"} \u043A\u043B\u044E\u0447${issue.keys.length > 1 ? \"\u0438\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435\";\n case \"invalid_element\":\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue.origin}`;\n default:\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"znakov\", verb: \"imeti\" },\n file: { unit: \"bajtov\", verb: \"imeti\" },\n array: { unit: \"elementov\", verb: \"imeti\" },\n set: { unit: \"elementov\", verb: \"imeti\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"vnos\",\n email: \"e-po\u0161tni naslov\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datum in \u010Das\",\n date: \"ISO datum\",\n time: \"ISO \u010Das\",\n duration: \"ISO trajanje\",\n ipv4: \"IPv4 naslov\",\n ipv6: \"IPv6 naslov\",\n cidrv4: \"obseg IPv4\",\n cidrv6: \"obseg IPv6\",\n base64: \"base64 kodiran niz\",\n base64url: \"base64url kodiran niz\",\n json_string: \"JSON niz\",\n e164: \"E.164 \u0161tevilka\",\n jwt: \"JWT\",\n template_literal: \"vnos\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0161tevilo\",\n array: \"tabela\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue.expected}, prejeto ${received}`;\n }\n return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Neveljaven vnos: pri\u010Dakovano ${util.stringifyPrimitive(issue.values[0])}`;\n return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Preveliko: pri\u010Dakovano, da bo ${issue.origin ?? \"vrednost\"} imelo ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementov\"}`;\n return `Preveliko: pri\u010Dakovano, da bo ${issue.origin ?? \"vrednost\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Premajhno: pri\u010Dakovano, da bo ${issue.origin} imelo ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Premajhno: pri\u010Dakovano, da bo ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Neveljaven niz: mora se za\u010Deti z \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Neveljaven niz: mora se kon\u010Dati z \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Neveljaven niz: mora vsebovati \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;\n return `Neveljaven ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Neprepoznan${issue.keys.length > 1 ? \"i klju\u010Di\" : \" klju\u010D\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Neveljaven klju\u010D v ${issue.origin}`;\n case \"invalid_union\":\n return \"Neveljaven vnos\";\n case \"invalid_element\":\n return `Neveljavna vrednost v ${issue.origin}`;\n default:\n return \"Neveljaven vnos\";\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"tecken\", verb: \"att ha\" },\n file: { unit: \"bytes\", verb: \"att ha\" },\n array: { unit: \"objekt\", verb: \"att inneh\u00E5lla\" },\n set: { unit: \"objekt\", verb: \"att inneh\u00E5lla\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"regulj\u00E4rt uttryck\",\n email: \"e-postadress\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO-datum och tid\",\n date: \"ISO-datum\",\n time: \"ISO-tid\",\n duration: \"ISO-varaktighet\",\n ipv4: \"IPv4-intervall\",\n ipv6: \"IPv6-intervall\",\n cidrv4: \"IPv4-spektrum\",\n cidrv6: \"IPv6-spektrum\",\n base64: \"base64-kodad str\u00E4ng\",\n base64url: \"base64url-kodad str\u00E4ng\",\n json_string: \"JSON-str\u00E4ng\",\n e164: \"E.164-nummer\",\n jwt: \"JWT\",\n template_literal: \"mall-literal\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"antal\",\n array: \"lista\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ogiltig inmatning: f\u00F6rv\u00E4ntat instanceof ${issue.expected}, fick ${received}`;\n }\n return `Ogiltig inmatning: f\u00F6rv\u00E4ntat ${expected}, fick ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ogiltig inmatning: f\u00F6rv\u00E4ntat ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ogiltigt val: f\u00F6rv\u00E4ntade en av ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `F\u00F6r stor(t): f\u00F6rv\u00E4ntade ${issue.origin ?? \"v\u00E4rdet\"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"element\"}`;\n }\n return `F\u00F6r stor(t): f\u00F6rv\u00E4ntat ${issue.origin ?? \"v\u00E4rdet\"} att ha ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `F\u00F6r lite(t): f\u00F6rv\u00E4ntade ${issue.origin ?? \"v\u00E4rdet\"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `F\u00F6r lite(t): f\u00F6rv\u00E4ntade ${issue.origin ?? \"v\u00E4rdet\"} att ha ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Ogiltig str\u00E4ng: m\u00E5ste b\u00F6rja med \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Ogiltig str\u00E4ng: m\u00E5ste sluta med \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Ogiltig str\u00E4ng: m\u00E5ste inneh\u00E5lla \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Ogiltig str\u00E4ng: m\u00E5ste matcha m\u00F6nstret \"${_issue.pattern}\"`;\n return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ogiltigt tal: m\u00E5ste vara en multipel av ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Ok\u00E4nda nycklar\" : \"Ok\u00E4nd nyckel\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ogiltig nyckel i ${issue.origin ?? \"v\u00E4rdet\"}`;\n case \"invalid_union\":\n return \"Ogiltig input\";\n case \"invalid_element\":\n return `Ogiltigt v\u00E4rde i ${issue.origin ?? \"v\u00E4rdet\"}`;\n default:\n return `Ogiltig input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD\", verb: \"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD\" },\n file: { unit: \"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD\", verb: \"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD\" },\n array: { unit: \"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD\", verb: \"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD\" },\n set: { unit: \"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD\", verb: \"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1\",\n email: \"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD\",\n date: \"ISO \u0BA4\u0BC7\u0BA4\u0BBF\",\n time: \"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD\",\n duration: \"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1\",\n ipv4: \"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF\",\n ipv6: \"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF\",\n cidrv4: \"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1\",\n cidrv6: \"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1\",\n base64: \"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD\",\n base64url: \"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD\",\n json_string: \"JSON \u0B9A\u0BB0\u0BAE\u0BCD\",\n e164: \"E.164 \u0B8E\u0BA3\u0BCD\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0B8E\u0BA3\u0BCD\",\n array: \"\u0B85\u0BA3\u0BBF\",\n null: \"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;\n }\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${util.joinValues(issue.values, \"|\")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue.origin ?? \"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD\"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n }\n return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue.origin ?? \"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1\"} ${adj}${issue.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; //\n }\n return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue.origin} ${adj}${issue.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: \"${_issue.prefix}\" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n if (_issue.format === \"ends_with\")\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: \"${_issue.suffix}\" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n if (_issue.format === \"includes\")\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: \"${_issue.includes}\" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n if (_issue.format === \"regex\")\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n case \"unrecognized_keys\":\n return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue.keys.length > 1 ? \"\u0B95\u0BB3\u0BCD\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;\n case \"invalid_union\":\n return \"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1\";\n case \"invalid_element\":\n return `${issue.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;\n default:\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\", verb: \"\u0E04\u0E27\u0E23\u0E21\u0E35\" },\n file: { unit: \"\u0E44\u0E1A\u0E15\u0E4C\", verb: \"\u0E04\u0E27\u0E23\u0E21\u0E35\" },\n array: { unit: \"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\", verb: \"\u0E04\u0E27\u0E23\u0E21\u0E35\" },\n set: { unit: \"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\", verb: \"\u0E04\u0E27\u0E23\u0E21\u0E35\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19\",\n email: \"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25\",\n url: \"URL\",\n emoji: \"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO\",\n date: \"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO\",\n time: \"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO\",\n duration: \"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO\",\n ipv4: \"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4\",\n ipv6: \"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6\",\n cidrv4: \"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4\",\n cidrv6: \"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6\",\n base64: \"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64\",\n base64url: \"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL\",\n json_string: \"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON\",\n e164: \"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)\",\n jwt: \"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT\",\n template_literal: \"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\",\n array: \"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)\",\n null: \"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;\n }\n return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19\" : \"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue.origin ?? \"\u0E04\u0E48\u0E32\"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\"}`;\n return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue.origin ?? \"\u0E04\u0E48\u0E32\"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22\" : \"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 \"${_issue.includes}\" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;\n if (_issue.format === \"regex\")\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;\n case \"unrecognized_keys\":\n return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49\";\n case \"invalid_element\":\n return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue.origin}`;\n default:\n return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"karakter\", verb: \"olmal\u0131\" },\n file: { unit: \"bayt\", verb: \"olmal\u0131\" },\n array: { unit: \"\u00F6\u011Fe\", verb: \"olmal\u0131\" },\n set: { unit: \"\u00F6\u011Fe\", verb: \"olmal\u0131\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"girdi\",\n email: \"e-posta adresi\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO tarih ve saat\",\n date: \"ISO tarih\",\n time: \"ISO saat\",\n duration: \"ISO s\u00FCre\",\n ipv4: \"IPv4 adresi\",\n ipv6: \"IPv6 adresi\",\n cidrv4: \"IPv4 aral\u0131\u011F\u0131\",\n cidrv6: \"IPv6 aral\u0131\u011F\u0131\",\n base64: \"base64 ile \u015Fifrelenmi\u015F metin\",\n base64url: \"base64url ile \u015Fifrelenmi\u015F metin\",\n json_string: \"JSON dizesi\",\n e164: \"E.164 say\u0131s\u0131\",\n jwt: \"JWT\",\n template_literal: \"\u015Eablon dizesi\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ge\u00E7ersiz de\u011Fer: beklenen instanceof ${issue.expected}, al\u0131nan ${received}`;\n }\n return `Ge\u00E7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ge\u00E7ersiz de\u011Fer: beklenen ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ge\u00E7ersiz se\u00E7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u00C7ok b\u00FCy\u00FCk: beklenen ${issue.origin ?? \"de\u011Fer\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u00F6\u011Fe\"}`;\n return `\u00C7ok b\u00FCy\u00FCk: beklenen ${issue.origin ?? \"de\u011Fer\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u00C7ok k\u00FC\u00E7\u00FCk: beklenen ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n return `\u00C7ok k\u00FC\u00E7\u00FCk: beklenen ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Ge\u00E7ersiz metin: \"${_issue.prefix}\" ile ba\u015Flamal\u0131`;\n if (_issue.format === \"ends_with\")\n return `Ge\u00E7ersiz metin: \"${_issue.suffix}\" ile bitmeli`;\n if (_issue.format === \"includes\")\n return `Ge\u00E7ersiz metin: \"${_issue.includes}\" i\u00E7ermeli`;\n if (_issue.format === \"regex\")\n return `Ge\u00E7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;\n return `Ge\u00E7ersiz ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ge\u00E7ersiz say\u0131: ${issue.divisor} ile tam b\u00F6l\u00FCnebilmeli`;\n case \"unrecognized_keys\":\n return `Tan\u0131nmayan anahtar${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} i\u00E7inde ge\u00E7ersiz anahtar`;\n case \"invalid_union\":\n return \"Ge\u00E7ersiz de\u011Fer\";\n case \"invalid_element\":\n return `${issue.origin} i\u00E7inde ge\u00E7ersiz de\u011Fer`;\n default:\n return `Ge\u00E7ersiz de\u011Fer`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432\", verb: \"\u043C\u0430\u0442\u0438\u043C\u0435\" },\n file: { unit: \"\u0431\u0430\u0439\u0442\u0456\u0432\", verb: \"\u043C\u0430\u0442\u0438\u043C\u0435\" },\n array: { unit: \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432\", verb: \"\u043C\u0430\u0442\u0438\u043C\u0435\" },\n set: { unit: \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432\", verb: \"\u043C\u0430\u0442\u0438\u043C\u0435\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456\",\n email: \"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438\",\n url: \"URL\",\n emoji: \"\u0435\u043C\u043E\u0434\u0437\u0456\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO\",\n date: \"\u0434\u0430\u0442\u0430 ISO\",\n time: \"\u0447\u0430\u0441 ISO\",\n duration: \"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO\",\n ipv4: \"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4\",\n ipv6: \"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6\",\n cidrv4: \"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4\",\n cidrv6: \"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6\",\n base64: \"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64\",\n base64url: \"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url\",\n json_string: \"\u0440\u044F\u0434\u043E\u043A JSON\",\n e164: \"\u043D\u043E\u043C\u0435\u0440 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0447\u0438\u0441\u043B\u043E\",\n array: \"\u043C\u0430\u0441\u0438\u0432\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;\n }\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432\"}`;\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F\"} \u0431\u0443\u0434\u0435 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue.origin} \u0431\u0443\u0434\u0435 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue.keys.length > 1 ? \"\u0456\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456\";\n case \"invalid_element\":\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue.origin}`;\n default:\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import uk from \"./uk.js\";\n/** @deprecated Use `uk` instead. */\nexport default function () {\n return uk();\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u062D\u0631\u0648\u0641\", verb: \"\u06C1\u0648\u0646\u0627\" },\n file: { unit: \"\u0628\u0627\u0626\u0679\u0633\", verb: \"\u06C1\u0648\u0646\u0627\" },\n array: { unit: \"\u0622\u0626\u0679\u0645\u0632\", verb: \"\u06C1\u0648\u0646\u0627\" },\n set: { unit: \"\u0622\u0626\u0679\u0645\u0632\", verb: \"\u06C1\u0648\u0646\u0627\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0627\u0646 \u067E\u0679\",\n email: \"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633\",\n url: \"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644\",\n emoji: \"\u0627\u06CC\u0645\u0648\u062C\u06CC\",\n uuid: \"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n uuidv4: \"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4\",\n uuidv6: \"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6\",\n nanoid: \"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n guid: \"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n cuid: \"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n cuid2: \"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2\",\n ulid: \"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC\",\n xid: \"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC\",\n ksuid: \"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n datetime: \"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645\",\n date: \"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E\",\n time: \"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A\",\n duration: \"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A\",\n ipv4: \"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633\",\n ipv6: \"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633\",\n cidrv4: \"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C\",\n cidrv6: \"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C\",\n base64: \"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF\",\n base64url: \"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF\",\n json_string: \"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF\",\n e164: \"\u0627\u06CC 164 \u0646\u0645\u0628\u0631\",\n jwt: \"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC\",\n template_literal: \"\u0627\u0646 \u067E\u0679\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0646\u0645\u0628\u0631\",\n array: \"\u0622\u0631\u06D2\",\n null: \"\u0646\u0644\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;\n }\n return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${util.stringifyPrimitive(issue.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;\n return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${util.joinValues(issue.values, \"|\")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue.origin ?? \"\u0648\u06CC\u0644\u06CC\u0648\"} \u06A9\u06D2 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0639\u0646\u0627\u0635\u0631\"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;\n return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue.origin ?? \"\u0648\u06CC\u0644\u06CC\u0648\"} \u06A9\u0627 ${adj}${issue.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue.origin} \u06A9\u06D2 ${adj}${issue.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;\n }\n return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue.origin} \u06A9\u0627 ${adj}${issue.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \"${_issue.prefix}\" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n }\n if (_issue.format === \"ends_with\")\n return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \"${_issue.suffix}\" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n if (_issue.format === \"includes\")\n return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \"${_issue.includes}\" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n if (_issue.format === \"regex\")\n return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n case \"unrecognized_keys\":\n return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue.keys.length > 1 ? \"\u0632\" : \"\"}: ${util.joinValues(issue.keys, \"\u060C \")}`;\n case \"invalid_key\":\n return `${issue.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;\n case \"invalid_union\":\n return \"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679\";\n case \"invalid_element\":\n return `${issue.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;\n default:\n return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"belgi\", verb: \"bo\u2018lishi kerak\" },\n file: { unit: \"bayt\", verb: \"bo\u2018lishi kerak\" },\n array: { unit: \"element\", verb: \"bo\u2018lishi kerak\" },\n set: { unit: \"element\", verb: \"bo\u2018lishi kerak\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"kirish\",\n email: \"elektron pochta manzili\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO sana va vaqti\",\n date: \"ISO sana\",\n time: \"ISO vaqt\",\n duration: \"ISO davomiylik\",\n ipv4: \"IPv4 manzil\",\n ipv6: \"IPv6 manzil\",\n mac: \"MAC manzil\",\n cidrv4: \"IPv4 diapazon\",\n cidrv6: \"IPv6 diapazon\",\n base64: \"base64 kodlangan satr\",\n base64url: \"base64url kodlangan satr\",\n json_string: \"JSON satr\",\n e164: \"E.164 raqam\",\n jwt: \"JWT\",\n template_literal: \"kirish\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"raqam\",\n array: \"massiv\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue.expected}, qabul qilingan ${received}`;\n }\n return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Noto\u2018g\u2018ri kirish: kutilgan ${util.stringifyPrimitive(issue.values[0])}`;\n return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Juda katta: kutilgan ${issue.origin ?? \"qiymat\"} ${adj}${issue.maximum.toString()} ${sizing.unit} ${sizing.verb}`;\n return `Juda katta: kutilgan ${issue.origin ?? \"qiymat\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;\n }\n return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Noto\u2018g\u2018ri satr: \"${_issue.prefix}\" bilan boshlanishi kerak`;\n if (_issue.format === \"ends_with\")\n return `Noto\u2018g\u2018ri satr: \"${_issue.suffix}\" bilan tugashi kerak`;\n if (_issue.format === \"includes\")\n return `Noto\u2018g\u2018ri satr: \"${_issue.includes}\" ni o\u2018z ichiga olishi kerak`;\n if (_issue.format === \"regex\")\n return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;\n return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Noto\u2018g\u2018ri raqam: ${issue.divisor} ning karralisi bo\u2018lishi kerak`;\n case \"unrecognized_keys\":\n return `Noma\u2019lum kalit${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} dagi kalit noto\u2018g\u2018ri`;\n case \"invalid_union\":\n return \"Noto\u2018g\u2018ri kirish\";\n case \"invalid_element\":\n return `${issue.origin} da noto\u2018g\u2018ri qiymat`;\n default:\n return `Noto\u2018g\u2018ri kirish`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"k\u00FD t\u1EF1\", verb: \"c\u00F3\" },\n file: { unit: \"byte\", verb: \"c\u00F3\" },\n array: { unit: \"ph\u1EA7n t\u1EED\", verb: \"c\u00F3\" },\n set: { unit: \"ph\u1EA7n t\u1EED\", verb: \"c\u00F3\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0111\u1EA7u v\u00E0o\",\n email: \"\u0111\u1ECBa ch\u1EC9 email\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ng\u00E0y gi\u1EDD ISO\",\n date: \"ng\u00E0y ISO\",\n time: \"gi\u1EDD ISO\",\n duration: \"kho\u1EA3ng th\u1EDDi gian ISO\",\n ipv4: \"\u0111\u1ECBa ch\u1EC9 IPv4\",\n ipv6: \"\u0111\u1ECBa ch\u1EC9 IPv6\",\n cidrv4: \"d\u1EA3i IPv4\",\n cidrv6: \"d\u1EA3i IPv6\",\n base64: \"chu\u1ED7i m\u00E3 h\u00F3a base64\",\n base64url: \"chu\u1ED7i m\u00E3 h\u00F3a base64url\",\n json_string: \"chu\u1ED7i JSON\",\n e164: \"s\u1ED1 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0111\u1EA7u v\u00E0o\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"s\u1ED1\",\n array: \"m\u1EA3ng\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;\n }\n return `\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${util.stringifyPrimitive(issue.values[0])}`;\n return `T\u00F9y ch\u1ECDn kh\u00F4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\u00E1c gi\u00E1 tr\u1ECB ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Qu\u00E1 l\u1EDBn: mong \u0111\u1EE3i ${issue.origin ?? \"gi\u00E1 tr\u1ECB\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"ph\u1EA7n t\u1EED\"}`;\n return `Qu\u00E1 l\u1EDBn: mong \u0111\u1EE3i ${issue.origin ?? \"gi\u00E1 tr\u1ECB\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Qu\u00E1 nh\u1ECF: mong \u0111\u1EE3i ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Qu\u00E1 nh\u1ECF: mong \u0111\u1EE3i ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Chu\u1ED7i kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Chu\u1ED7i kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\u00FAc b\u1EB1ng \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Chu\u1ED7i kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Chu\u1ED7i kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} kh\u00F4ng h\u1EE3p l\u1EC7`;\n }\n case \"not_multiple_of\":\n return `S\u1ED1 kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\u00E0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Kh\u00F3a kh\u00F4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Kh\u00F3a kh\u00F4ng h\u1EE3p l\u1EC7 trong ${issue.origin}`;\n case \"invalid_union\":\n return \"\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7\";\n case \"invalid_element\":\n return `Gi\u00E1 tr\u1ECB kh\u00F4ng h\u1EE3p l\u1EC7 trong ${issue.origin}`;\n default:\n return `\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u5B57\u7B26\", verb: \"\u5305\u542B\" },\n file: { unit: \"\u5B57\u8282\", verb: \"\u5305\u542B\" },\n array: { unit: \"\u9879\", verb: \"\u5305\u542B\" },\n set: { unit: \"\u9879\", verb: \"\u5305\u542B\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u8F93\u5165\",\n email: \"\u7535\u5B50\u90AE\u4EF6\",\n url: \"URL\",\n emoji: \"\u8868\u60C5\u7B26\u53F7\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO\u65E5\u671F\u65F6\u95F4\",\n date: \"ISO\u65E5\u671F\",\n time: \"ISO\u65F6\u95F4\",\n duration: \"ISO\u65F6\u957F\",\n ipv4: \"IPv4\u5730\u5740\",\n ipv6: \"IPv6\u5730\u5740\",\n cidrv4: \"IPv4\u7F51\u6BB5\",\n cidrv6: \"IPv6\u7F51\u6BB5\",\n base64: \"base64\u7F16\u7801\u5B57\u7B26\u4E32\",\n base64url: \"base64url\u7F16\u7801\u5B57\u7B26\u4E32\",\n json_string: \"JSON\u5B57\u7B26\u4E32\",\n e164: \"E.164\u53F7\u7801\",\n jwt: \"JWT\",\n template_literal: \"\u8F93\u5165\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u6570\u5B57\",\n array: \"\u6570\u7EC4\",\n null: \"\u7A7A\u503C(null)\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;\n }\n return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue.origin ?? \"\u503C\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u4E2A\u5143\u7D20\"}`;\n return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue.origin ?? \"\u503C\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 \"${_issue.prefix}\" \u5F00\u5934`;\n if (_issue.format === \"ends_with\")\n return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 \"${_issue.suffix}\" \u7ED3\u5C3E`;\n if (_issue.format === \"includes\")\n return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;\n return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue.divisor} \u7684\u500D\u6570`;\n case \"unrecognized_keys\":\n return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;\n case \"invalid_union\":\n return \"\u65E0\u6548\u8F93\u5165\";\n case \"invalid_element\":\n return `${issue.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;\n default:\n return `\u65E0\u6548\u8F93\u5165`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u5B57\u5143\", verb: \"\u64C1\u6709\" },\n file: { unit: \"\u4F4D\u5143\u7D44\", verb: \"\u64C1\u6709\" },\n array: { unit: \"\u9805\u76EE\", verb: \"\u64C1\u6709\" },\n set: { unit: \"\u9805\u76EE\", verb: \"\u64C1\u6709\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u8F38\u5165\",\n email: \"\u90F5\u4EF6\u5730\u5740\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u65E5\u671F\u6642\u9593\",\n date: \"ISO \u65E5\u671F\",\n time: \"ISO \u6642\u9593\",\n duration: \"ISO \u671F\u9593\",\n ipv4: \"IPv4 \u4F4D\u5740\",\n ipv6: \"IPv6 \u4F4D\u5740\",\n cidrv4: \"IPv4 \u7BC4\u570D\",\n cidrv6: \"IPv6 \u7BC4\u570D\",\n base64: \"base64 \u7DE8\u78BC\u5B57\u4E32\",\n base64url: \"base64url \u7DE8\u78BC\u5B57\u4E32\",\n json_string: \"JSON \u5B57\u4E32\",\n e164: \"E.164 \u6578\u503C\",\n jwt: \"JWT\",\n template_literal: \"\u8F38\u5165\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue.expected}\uFF0C\u4F46\u6536\u5230 ${received}`;\n }\n return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue.origin ?? \"\u503C\"} \u61C9\u70BA ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u500B\u5143\u7D20\"}`;\n return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue.origin ?? \"\u503C\"} \u61C9\u70BA ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue.origin} \u61C9\u70BA ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue.origin} \u61C9\u70BA ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 \"${_issue.prefix}\" \u958B\u982D`;\n }\n if (_issue.format === \"ends_with\")\n return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 \"${_issue.suffix}\" \u7D50\u5C3E`;\n if (_issue.format === \"includes\")\n return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;\n return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue.divisor} \u7684\u500D\u6578`;\n case \"unrecognized_keys\":\n return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue.keys.length > 1 ? \"\u5011\" : \"\"}\uFF1A${util.joinValues(issue.keys, \"\u3001\")}`;\n case \"invalid_key\":\n return `${issue.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;\n case \"invalid_union\":\n return \"\u7121\u6548\u7684\u8F38\u5165\u503C\";\n case \"invalid_element\":\n return `${issue.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;\n default:\n return `\u7121\u6548\u7684\u8F38\u5165\u503C`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u00E0mi\", verb: \"n\u00ED\" },\n file: { unit: \"bytes\", verb: \"n\u00ED\" },\n array: { unit: \"nkan\", verb: \"n\u00ED\" },\n set: { unit: \"nkan\", verb: \"n\u00ED\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u1EB9\u0300r\u1ECD \u00ECb\u00E1w\u1ECDl\u00E9\",\n email: \"\u00E0d\u00EDr\u1EB9\u0301s\u00EC \u00ECm\u1EB9\u0301l\u00EC\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u00E0k\u00F3k\u00F2 ISO\",\n date: \"\u1ECDj\u1ECD\u0301 ISO\",\n time: \"\u00E0k\u00F3k\u00F2 ISO\",\n duration: \"\u00E0k\u00F3k\u00F2 t\u00F3 p\u00E9 ISO\",\n ipv4: \"\u00E0d\u00EDr\u1EB9\u0301s\u00EC IPv4\",\n ipv6: \"\u00E0d\u00EDr\u1EB9\u0301s\u00EC IPv6\",\n cidrv4: \"\u00E0gb\u00E8gb\u00E8 IPv4\",\n cidrv6: \"\u00E0gb\u00E8gb\u00E8 IPv6\",\n base64: \"\u1ECD\u0300r\u1ECD\u0300 t\u00ED a k\u1ECD\u0301 n\u00ED base64\",\n base64url: \"\u1ECD\u0300r\u1ECD\u0300 base64url\",\n json_string: \"\u1ECD\u0300r\u1ECD\u0300 JSON\",\n e164: \"n\u1ECD\u0301mb\u00E0 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u1EB9\u0300r\u1ECD \u00ECb\u00E1w\u1ECDl\u00E9\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"n\u1ECD\u0301mb\u00E0\",\n array: \"akop\u1ECD\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e: a n\u00ED l\u00E1ti fi instanceof ${issue.expected}, \u00E0m\u1ECD\u0300 a r\u00ED ${received}`;\n }\n return `\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e: a n\u00ED l\u00E1ti fi ${expected}, \u00E0m\u1ECD\u0300 a r\u00ED ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e: a n\u00ED l\u00E1ti fi ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u00C0\u1E63\u00E0y\u00E0n a\u1E63\u00EC\u1E63e: yan \u1ECD\u0300kan l\u00E1ra ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `T\u00F3 p\u1ECD\u0300 j\u00F9: a n\u00ED l\u00E1ti j\u1EB9\u0301 p\u00E9 ${issue.origin ?? \"iye\"} ${sizing.verb} ${adj}${issue.maximum} ${sizing.unit}`;\n return `T\u00F3 p\u1ECD\u0300 j\u00F9: a n\u00ED l\u00E1ti j\u1EB9\u0301 ${adj}${issue.maximum}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `K\u00E9r\u00E9 ju: a n\u00ED l\u00E1ti j\u1EB9\u0301 p\u00E9 ${issue.origin} ${sizing.verb} ${adj}${issue.minimum} ${sizing.unit}`;\n return `K\u00E9r\u00E9 ju: a n\u00ED l\u00E1ti j\u1EB9\u0301 ${adj}${issue.minimum}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\u00FA \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\u00ED p\u1EB9\u0300l\u00FA \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\u00ED \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u00E1 \u00E0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`;\n return `A\u1E63\u00EC\u1E63e: ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `N\u1ECD\u0301mb\u00E0 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \u00E8y\u00E0 p\u00EDp\u00EDn ti ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `B\u1ECDt\u00ECn\u00EC \u00E0\u00ECm\u1ECD\u0300: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `B\u1ECDt\u00ECn\u00EC a\u1E63\u00EC\u1E63e n\u00EDn\u00FA ${issue.origin}`;\n case \"invalid_union\":\n return \"\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e\";\n case \"invalid_element\":\n return `Iye a\u1E63\u00EC\u1E63e n\u00EDn\u00FA ${issue.origin}`;\n default:\n return \"\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e\";\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "export { default as ar } from \"./ar.js\";\nexport { default as az } from \"./az.js\";\nexport { default as be } from \"./be.js\";\nexport { default as bg } from \"./bg.js\";\nexport { default as ca } from \"./ca.js\";\nexport { default as cs } from \"./cs.js\";\nexport { default as da } from \"./da.js\";\nexport { default as de } from \"./de.js\";\nexport { default as en } from \"./en.js\";\nexport { default as eo } from \"./eo.js\";\nexport { default as es } from \"./es.js\";\nexport { default as fa } from \"./fa.js\";\nexport { default as fi } from \"./fi.js\";\nexport { default as fr } from \"./fr.js\";\nexport { default as frCA } from \"./fr-CA.js\";\nexport { default as he } from \"./he.js\";\nexport { default as hu } from \"./hu.js\";\nexport { default as hy } from \"./hy.js\";\nexport { default as id } from \"./id.js\";\nexport { default as is } from \"./is.js\";\nexport { default as it } from \"./it.js\";\nexport { default as ja } from \"./ja.js\";\nexport { default as ka } from \"./ka.js\";\nexport { default as kh } from \"./kh.js\";\nexport { default as km } from \"./km.js\";\nexport { default as ko } from \"./ko.js\";\nexport { default as lt } from \"./lt.js\";\nexport { default as mk } from \"./mk.js\";\nexport { default as ms } from \"./ms.js\";\nexport { default as nl } from \"./nl.js\";\nexport { default as no } from \"./no.js\";\nexport { default as ota } from \"./ota.js\";\nexport { default as ps } from \"./ps.js\";\nexport { default as pl } from \"./pl.js\";\nexport { default as pt } from \"./pt.js\";\nexport { default as ru } from \"./ru.js\";\nexport { default as sl } from \"./sl.js\";\nexport { default as sv } from \"./sv.js\";\nexport { default as ta } from \"./ta.js\";\nexport { default as th } from \"./th.js\";\nexport { default as tr } from \"./tr.js\";\nexport { default as ua } from \"./ua.js\";\nexport { default as uk } from \"./uk.js\";\nexport { default as ur } from \"./ur.js\";\nexport { default as uz } from \"./uz.js\";\nexport { default as vi } from \"./vi.js\";\nexport { default as zhCN } from \"./zh-CN.js\";\nexport { default as zhTW } from \"./zh-TW.js\";\nexport { default as yo } from \"./yo.js\";\n", "var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n", "import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n", "import { globalRegistry } from \"./registries.js\";\n// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && result.schema._prefault)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n", "import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, { ...params, path: [...params.path, \"items\"] });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n", "import { allProcessors } from \"./json-schema-processors.js\";\nimport { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\n/**\n * Legacy class-based interface for JSON Schema generation.\n * This class wraps the new functional implementation to provide backward compatibility.\n *\n * @deprecated Use the `toJSONSchema` function instead for new code.\n *\n * @example\n * ```typescript\n * // Legacy usage (still supported)\n * const gen = new JSONSchemaGenerator({ target: \"draft-07\" });\n * gen.process(schema);\n * const result = gen.emit(schema);\n *\n * // Preferred modern usage\n * const result = toJSONSchema(schema, { target: \"draft-07\" });\n * ```\n */\nexport class JSONSchemaGenerator {\n /** @deprecated Access via ctx instead */\n get metadataRegistry() {\n return this.ctx.metadataRegistry;\n }\n /** @deprecated Access via ctx instead */\n get target() {\n return this.ctx.target;\n }\n /** @deprecated Access via ctx instead */\n get unrepresentable() {\n return this.ctx.unrepresentable;\n }\n /** @deprecated Access via ctx instead */\n get override() {\n return this.ctx.override;\n }\n /** @deprecated Access via ctx instead */\n get io() {\n return this.ctx.io;\n }\n /** @deprecated Access via ctx instead */\n get counter() {\n return this.ctx.counter;\n }\n set counter(value) {\n this.ctx.counter = value;\n }\n /** @deprecated Access via ctx instead */\n get seen() {\n return this.ctx.seen;\n }\n constructor(params) {\n // Normalize target for internal context\n let normalizedTarget = params?.target ?? \"draft-2020-12\";\n if (normalizedTarget === \"draft-4\")\n normalizedTarget = \"draft-04\";\n if (normalizedTarget === \"draft-7\")\n normalizedTarget = \"draft-07\";\n this.ctx = initializeContext({\n processors: allProcessors,\n target: normalizedTarget,\n ...(params?.metadata && { metadata: params.metadata }),\n ...(params?.unrepresentable && { unrepresentable: params.unrepresentable }),\n ...(params?.override && { override: params.override }),\n ...(params?.io && { io: params.io }),\n });\n }\n /**\n * Process a schema to prepare it for JSON Schema generation.\n * This must be called before emit().\n */\n process(schema, _params = { path: [], schemaPath: [] }) {\n return process(schema, this.ctx, _params);\n }\n /**\n * Emit the final JSON Schema after processing.\n * Must call process() first.\n */\n emit(schema, _params) {\n // Apply emit params to the context\n if (_params) {\n if (_params.cycles)\n this.ctx.cycles = _params.cycles;\n if (_params.reused)\n this.ctx.reused = _params.reused;\n if (_params.external)\n this.ctx.external = _params.external;\n }\n extractDefs(this.ctx, schema);\n const result = finalize(this.ctx, schema);\n // Strip ~standard property to match old implementation's return type\n const { \"~standard\": _, ...plainResult } = result;\n return plainResult;\n }\n}\n", "export {};\n", "export * from \"./core.js\";\nexport * from \"./parse.js\";\nexport * from \"./errors.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./versions.js\";\nexport * as util from \"./util.js\";\nexport * as regexes from \"./regexes.js\";\nexport * as locales from \"../locales/index.js\";\nexport * from \"./registries.js\";\nexport * from \"./doc.js\";\nexport * from \"./api.js\";\nexport * from \"./to-json-schema.js\";\nexport { toJSONSchema } from \"./json-schema-processors.js\";\nexport { JSONSchemaGenerator } from \"./json-schema-generator.js\";\nexport * as JSONSchema from \"./json-schema.js\";\n", "export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, } from \"../core/index.js\";\n", "import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n", "import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n", "import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n", "import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // base methods\n inst.check = (...checks) => {\n return inst.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), {\n parent: true,\n });\n };\n inst.with = inst.check;\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n // encoding/decoding\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.exactOptional = () => exactOptional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n inst.apply = (fn) => fn(inst);\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n inst.slugify = () => inst.check(checks.slugify());\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: /^https?$/,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.safeExtend = (incoming) => {\n return util.safeExtend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn) {\n return core._superRefine(fn);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n", "// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n", "import { globalRegistry } from \"../core/registries.js\";\nimport * as _checks from \"./checks.js\";\nimport * as _iso from \"./iso.js\";\nimport * as _schemas from \"./schemas.js\";\n// Local z object to avoid circular dependency with ../index.js\nconst z = {\n ..._schemas,\n ..._checks,\n iso: _iso,\n};\n// Keys that are recognized and handled by the conversion logic\nconst RECOGNIZED_KEYS = new Set([\n // Schema identification\n \"$schema\",\n \"$ref\",\n \"$defs\",\n \"definitions\",\n // Core schema keywords\n \"$id\",\n \"id\",\n \"$comment\",\n \"$anchor\",\n \"$vocabulary\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n // Type\n \"type\",\n \"enum\",\n \"const\",\n // Composition\n \"anyOf\",\n \"oneOf\",\n \"allOf\",\n \"not\",\n // Object\n \"properties\",\n \"required\",\n \"additionalProperties\",\n \"patternProperties\",\n \"propertyNames\",\n \"minProperties\",\n \"maxProperties\",\n // Array\n \"items\",\n \"prefixItems\",\n \"additionalItems\",\n \"minItems\",\n \"maxItems\",\n \"uniqueItems\",\n \"contains\",\n \"minContains\",\n \"maxContains\",\n // String\n \"minLength\",\n \"maxLength\",\n \"pattern\",\n \"format\",\n // Number\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n // Already handled metadata\n \"description\",\n \"default\",\n // Content\n \"contentEncoding\",\n \"contentMediaType\",\n \"contentSchema\",\n // Unsupported (error-throwing)\n \"unevaluatedItems\",\n \"unevaluatedProperties\",\n \"if\",\n \"then\",\n \"else\",\n \"dependentSchemas\",\n \"dependentRequired\",\n // OpenAPI\n \"nullable\",\n \"readOnly\",\n]);\nfunction detectVersion(schema, defaultTarget) {\n const $schema = schema.$schema;\n if ($schema === \"https://json-schema.org/draft/2020-12/schema\") {\n return \"draft-2020-12\";\n }\n if ($schema === \"http://json-schema.org/draft-07/schema#\") {\n return \"draft-7\";\n }\n if ($schema === \"http://json-schema.org/draft-04/schema#\") {\n return \"draft-4\";\n }\n // Use defaultTarget if provided, otherwise default to draft-2020-12\n return defaultTarget ?? \"draft-2020-12\";\n}\nfunction resolveRef(ref, ctx) {\n if (!ref.startsWith(\"#\")) {\n throw new Error(\"External $ref is not supported, only local refs (#/...) are allowed\");\n }\n const path = ref.slice(1).split(\"/\").filter(Boolean);\n // Handle root reference \"#\"\n if (path.length === 0) {\n return ctx.rootSchema;\n }\n const defsKey = ctx.version === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (path[0] === defsKey) {\n const key = path[1];\n if (!key || !ctx.defs[key]) {\n throw new Error(`Reference not found: ${ref}`);\n }\n return ctx.defs[key];\n }\n throw new Error(`Reference not found: ${ref}`);\n}\nfunction convertBaseSchema(schema, ctx) {\n // Handle unsupported features\n if (schema.not !== undefined) {\n // Special case: { not: {} } represents never\n if (typeof schema.not === \"object\" && Object.keys(schema.not).length === 0) {\n return z.never();\n }\n throw new Error(\"not is not supported in Zod (except { not: {} } for never)\");\n }\n if (schema.unevaluatedItems !== undefined) {\n throw new Error(\"unevaluatedItems is not supported\");\n }\n if (schema.unevaluatedProperties !== undefined) {\n throw new Error(\"unevaluatedProperties is not supported\");\n }\n if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {\n throw new Error(\"Conditional schemas (if/then/else) are not supported\");\n }\n if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {\n throw new Error(\"dependentSchemas and dependentRequired are not supported\");\n }\n // Handle $ref\n if (schema.$ref) {\n const refPath = schema.$ref;\n if (ctx.refs.has(refPath)) {\n return ctx.refs.get(refPath);\n }\n if (ctx.processing.has(refPath)) {\n // Circular reference - use lazy\n return z.lazy(() => {\n if (!ctx.refs.has(refPath)) {\n throw new Error(`Circular reference not resolved: ${refPath}`);\n }\n return ctx.refs.get(refPath);\n });\n }\n ctx.processing.add(refPath);\n const resolved = resolveRef(refPath, ctx);\n const zodSchema = convertSchema(resolved, ctx);\n ctx.refs.set(refPath, zodSchema);\n ctx.processing.delete(refPath);\n return zodSchema;\n }\n // Handle enum\n if (schema.enum !== undefined) {\n const enumValues = schema.enum;\n // Special case: OpenAPI 3.0 null representation { type: \"string\", nullable: true, enum: [null] }\n if (ctx.version === \"openapi-3.0\" &&\n schema.nullable === true &&\n enumValues.length === 1 &&\n enumValues[0] === null) {\n return z.null();\n }\n if (enumValues.length === 0) {\n return z.never();\n }\n if (enumValues.length === 1) {\n return z.literal(enumValues[0]);\n }\n // Check if all values are strings\n if (enumValues.every((v) => typeof v === \"string\")) {\n return z.enum(enumValues);\n }\n // Mixed types - use union of literals\n const literalSchemas = enumValues.map((v) => z.literal(v));\n if (literalSchemas.length < 2) {\n return literalSchemas[0];\n }\n return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);\n }\n // Handle const\n if (schema.const !== undefined) {\n return z.literal(schema.const);\n }\n // Handle type\n const type = schema.type;\n if (Array.isArray(type)) {\n // Expand type array into anyOf union\n const typeSchemas = type.map((t) => {\n const typeSchema = { ...schema, type: t };\n return convertBaseSchema(typeSchema, ctx);\n });\n if (typeSchemas.length === 0) {\n return z.never();\n }\n if (typeSchemas.length === 1) {\n return typeSchemas[0];\n }\n return z.union(typeSchemas);\n }\n if (!type) {\n // No type specified - empty schema (any)\n return z.any();\n }\n let zodSchema;\n switch (type) {\n case \"string\": {\n let stringSchema = z.string();\n // Apply format using .check() with Zod format functions\n if (schema.format) {\n const format = schema.format;\n // Map common formats to Zod check functions\n if (format === \"email\") {\n stringSchema = stringSchema.check(z.email());\n }\n else if (format === \"uri\" || format === \"uri-reference\") {\n stringSchema = stringSchema.check(z.url());\n }\n else if (format === \"uuid\" || format === \"guid\") {\n stringSchema = stringSchema.check(z.uuid());\n }\n else if (format === \"date-time\") {\n stringSchema = stringSchema.check(z.iso.datetime());\n }\n else if (format === \"date\") {\n stringSchema = stringSchema.check(z.iso.date());\n }\n else if (format === \"time\") {\n stringSchema = stringSchema.check(z.iso.time());\n }\n else if (format === \"duration\") {\n stringSchema = stringSchema.check(z.iso.duration());\n }\n else if (format === \"ipv4\") {\n stringSchema = stringSchema.check(z.ipv4());\n }\n else if (format === \"ipv6\") {\n stringSchema = stringSchema.check(z.ipv6());\n }\n else if (format === \"mac\") {\n stringSchema = stringSchema.check(z.mac());\n }\n else if (format === \"cidr\") {\n stringSchema = stringSchema.check(z.cidrv4());\n }\n else if (format === \"cidr-v6\") {\n stringSchema = stringSchema.check(z.cidrv6());\n }\n else if (format === \"base64\") {\n stringSchema = stringSchema.check(z.base64());\n }\n else if (format === \"base64url\") {\n stringSchema = stringSchema.check(z.base64url());\n }\n else if (format === \"e164\") {\n stringSchema = stringSchema.check(z.e164());\n }\n else if (format === \"jwt\") {\n stringSchema = stringSchema.check(z.jwt());\n }\n else if (format === \"emoji\") {\n stringSchema = stringSchema.check(z.emoji());\n }\n else if (format === \"nanoid\") {\n stringSchema = stringSchema.check(z.nanoid());\n }\n else if (format === \"cuid\") {\n stringSchema = stringSchema.check(z.cuid());\n }\n else if (format === \"cuid2\") {\n stringSchema = stringSchema.check(z.cuid2());\n }\n else if (format === \"ulid\") {\n stringSchema = stringSchema.check(z.ulid());\n }\n else if (format === \"xid\") {\n stringSchema = stringSchema.check(z.xid());\n }\n else if (format === \"ksuid\") {\n stringSchema = stringSchema.check(z.ksuid());\n }\n // Note: json-string format is not currently supported by Zod\n // Custom formats are ignored - keep as plain string\n }\n // Apply constraints\n if (typeof schema.minLength === \"number\") {\n stringSchema = stringSchema.min(schema.minLength);\n }\n if (typeof schema.maxLength === \"number\") {\n stringSchema = stringSchema.max(schema.maxLength);\n }\n if (schema.pattern) {\n // JSON Schema patterns are not implicitly anchored (match anywhere in string)\n stringSchema = stringSchema.regex(new RegExp(schema.pattern));\n }\n zodSchema = stringSchema;\n break;\n }\n case \"number\":\n case \"integer\": {\n let numberSchema = type === \"integer\" ? z.number().int() : z.number();\n // Apply constraints\n if (typeof schema.minimum === \"number\") {\n numberSchema = numberSchema.min(schema.minimum);\n }\n if (typeof schema.maximum === \"number\") {\n numberSchema = numberSchema.max(schema.maximum);\n }\n if (typeof schema.exclusiveMinimum === \"number\") {\n numberSchema = numberSchema.gt(schema.exclusiveMinimum);\n }\n else if (schema.exclusiveMinimum === true && typeof schema.minimum === \"number\") {\n numberSchema = numberSchema.gt(schema.minimum);\n }\n if (typeof schema.exclusiveMaximum === \"number\") {\n numberSchema = numberSchema.lt(schema.exclusiveMaximum);\n }\n else if (schema.exclusiveMaximum === true && typeof schema.maximum === \"number\") {\n numberSchema = numberSchema.lt(schema.maximum);\n }\n if (typeof schema.multipleOf === \"number\") {\n numberSchema = numberSchema.multipleOf(schema.multipleOf);\n }\n zodSchema = numberSchema;\n break;\n }\n case \"boolean\": {\n zodSchema = z.boolean();\n break;\n }\n case \"null\": {\n zodSchema = z.null();\n break;\n }\n case \"object\": {\n const shape = {};\n const properties = schema.properties || {};\n const requiredSet = new Set(schema.required || []);\n // Convert properties - mark optional ones\n for (const [key, propSchema] of Object.entries(properties)) {\n const propZodSchema = convertSchema(propSchema, ctx);\n // If not in required array, make it optional\n shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();\n }\n // Handle propertyNames\n if (schema.propertyNames) {\n const keySchema = convertSchema(schema.propertyNames, ctx);\n const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === \"object\"\n ? convertSchema(schema.additionalProperties, ctx)\n : z.any();\n // Case A: No properties (pure record)\n if (Object.keys(shape).length === 0) {\n zodSchema = z.record(keySchema, valueSchema);\n break;\n }\n // Case B: With properties (intersection of object and looseRecord)\n const objectSchema = z.object(shape).passthrough();\n const recordSchema = z.looseRecord(keySchema, valueSchema);\n zodSchema = z.intersection(objectSchema, recordSchema);\n break;\n }\n // Handle patternProperties\n if (schema.patternProperties) {\n // patternProperties: keys matching pattern must satisfy corresponding schema\n // Use loose records so non-matching keys pass through\n const patternProps = schema.patternProperties;\n const patternKeys = Object.keys(patternProps);\n const looseRecords = [];\n for (const pattern of patternKeys) {\n const patternValue = convertSchema(patternProps[pattern], ctx);\n const keySchema = z.string().regex(new RegExp(pattern));\n looseRecords.push(z.looseRecord(keySchema, patternValue));\n }\n // Build intersection: object schema + all pattern property records\n const schemasToIntersect = [];\n if (Object.keys(shape).length > 0) {\n // Use passthrough so patternProperties can validate additional keys\n schemasToIntersect.push(z.object(shape).passthrough());\n }\n schemasToIntersect.push(...looseRecords);\n if (schemasToIntersect.length === 0) {\n zodSchema = z.object({}).passthrough();\n }\n else if (schemasToIntersect.length === 1) {\n zodSchema = schemasToIntersect[0];\n }\n else {\n // Chain intersections: (A & B) & C & D ...\n let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);\n for (let i = 2; i < schemasToIntersect.length; i++) {\n result = z.intersection(result, schemasToIntersect[i]);\n }\n zodSchema = result;\n }\n break;\n }\n // Handle additionalProperties\n // In JSON Schema, additionalProperties defaults to true (allow any extra properties)\n // In Zod, objects strip unknown keys by default, so we need to handle this explicitly\n const objectSchema = z.object(shape);\n if (schema.additionalProperties === false) {\n // Strict mode - no extra properties allowed\n zodSchema = objectSchema.strict();\n }\n else if (typeof schema.additionalProperties === \"object\") {\n // Extra properties must match the specified schema\n zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));\n }\n else {\n // additionalProperties is true or undefined - allow any extra properties (passthrough)\n zodSchema = objectSchema.passthrough();\n }\n break;\n }\n case \"array\": {\n // TODO: uniqueItems is not supported\n // TODO: contains/minContains/maxContains are not supported\n // Check if this is a tuple (prefixItems or items as array)\n const prefixItems = schema.prefixItems;\n const items = schema.items;\n if (prefixItems && Array.isArray(prefixItems)) {\n // Tuple with prefixItems (draft-2020-12)\n const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));\n const rest = items && typeof items === \"object\" && !Array.isArray(items)\n ? convertSchema(items, ctx)\n : undefined;\n if (rest) {\n zodSchema = z.tuple(tupleItems).rest(rest);\n }\n else {\n zodSchema = z.tuple(tupleItems);\n }\n // Apply minItems/maxItems constraints to tuples\n if (typeof schema.minItems === \"number\") {\n zodSchema = zodSchema.check(z.minLength(schema.minItems));\n }\n if (typeof schema.maxItems === \"number\") {\n zodSchema = zodSchema.check(z.maxLength(schema.maxItems));\n }\n }\n else if (Array.isArray(items)) {\n // Tuple with items array (draft-7)\n const tupleItems = items.map((item) => convertSchema(item, ctx));\n const rest = schema.additionalItems && typeof schema.additionalItems === \"object\"\n ? convertSchema(schema.additionalItems, ctx)\n : undefined; // additionalItems: false means no rest, handled by default tuple behavior\n if (rest) {\n zodSchema = z.tuple(tupleItems).rest(rest);\n }\n else {\n zodSchema = z.tuple(tupleItems);\n }\n // Apply minItems/maxItems constraints to tuples\n if (typeof schema.minItems === \"number\") {\n zodSchema = zodSchema.check(z.minLength(schema.minItems));\n }\n if (typeof schema.maxItems === \"number\") {\n zodSchema = zodSchema.check(z.maxLength(schema.maxItems));\n }\n }\n else if (items !== undefined) {\n // Regular array\n const element = convertSchema(items, ctx);\n let arraySchema = z.array(element);\n // Apply constraints\n if (typeof schema.minItems === \"number\") {\n arraySchema = arraySchema.min(schema.minItems);\n }\n if (typeof schema.maxItems === \"number\") {\n arraySchema = arraySchema.max(schema.maxItems);\n }\n zodSchema = arraySchema;\n }\n else {\n // No items specified - array of any\n zodSchema = z.array(z.any());\n }\n break;\n }\n default:\n throw new Error(`Unsupported type: ${type}`);\n }\n // Apply metadata\n if (schema.description) {\n zodSchema = zodSchema.describe(schema.description);\n }\n if (schema.default !== undefined) {\n zodSchema = zodSchema.default(schema.default);\n }\n return zodSchema;\n}\nfunction convertSchema(schema, ctx) {\n if (typeof schema === \"boolean\") {\n return schema ? z.any() : z.never();\n }\n // Convert base schema first (ignoring composition keywords)\n let baseSchema = convertBaseSchema(schema, ctx);\n const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;\n // Process composition keywords LAST (they can appear together)\n // Handle anyOf - wrap base schema with union\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n const options = schema.anyOf.map((s) => convertSchema(s, ctx));\n const anyOfUnion = z.union(options);\n baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;\n }\n // Handle oneOf - exclusive union (exactly one must match)\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n const options = schema.oneOf.map((s) => convertSchema(s, ctx));\n const oneOfUnion = z.xor(options);\n baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;\n }\n // Handle allOf - wrap base schema with intersection\n if (schema.allOf && Array.isArray(schema.allOf)) {\n if (schema.allOf.length === 0) {\n baseSchema = hasExplicitType ? baseSchema : z.any();\n }\n else {\n let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);\n const startIdx = hasExplicitType ? 0 : 1;\n for (let i = startIdx; i < schema.allOf.length; i++) {\n result = z.intersection(result, convertSchema(schema.allOf[i], ctx));\n }\n baseSchema = result;\n }\n }\n // Handle nullable (OpenAPI 3.0)\n if (schema.nullable === true && ctx.version === \"openapi-3.0\") {\n baseSchema = z.nullable(baseSchema);\n }\n // Handle readOnly\n if (schema.readOnly === true) {\n baseSchema = z.readonly(baseSchema);\n }\n // Collect metadata: core schema keywords and unrecognized keys\n const extraMeta = {};\n // Core schema keywords that should be captured as metadata\n const coreMetadataKeys = [\"$id\", \"id\", \"$comment\", \"$anchor\", \"$vocabulary\", \"$dynamicRef\", \"$dynamicAnchor\"];\n for (const key of coreMetadataKeys) {\n if (key in schema) {\n extraMeta[key] = schema[key];\n }\n }\n // Content keywords - store as metadata\n const contentMetadataKeys = [\"contentEncoding\", \"contentMediaType\", \"contentSchema\"];\n for (const key of contentMetadataKeys) {\n if (key in schema) {\n extraMeta[key] = schema[key];\n }\n }\n // Unrecognized keys (custom metadata)\n for (const key of Object.keys(schema)) {\n if (!RECOGNIZED_KEYS.has(key)) {\n extraMeta[key] = schema[key];\n }\n }\n if (Object.keys(extraMeta).length > 0) {\n ctx.registry.add(baseSchema, extraMeta);\n }\n return baseSchema;\n}\n/**\n * Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */\nexport function fromJSONSchema(schema, params) {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? z.any() : z.never();\n }\n const version = detectVersion(schema, params?.defaultTarget);\n const defs = (schema.$defs || schema.definitions || {});\n const ctx = {\n version,\n defs,\n refs: new Map(),\n processing: new Set(),\n rootSchema: schema,\n registry: params?.registry ?? globalRegistry,\n };\n return convertSchema(schema, ctx);\n}\n", "import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n", "export * as core from \"../core/index.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./errors.js\";\nexport * from \"./parse.js\";\nexport * from \"./compat.js\";\n// zod-specified\nimport { config } from \"../core/index.js\";\nimport en from \"../locales/en.js\";\nconfig(en());\nexport { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from \"../core/index.js\";\nexport { toJSONSchema } from \"../core/json-schema-processors.js\";\nexport { fromJSONSchema } from \"./from-json-schema.js\";\nexport * as locales from \"../locales/index.js\";\n// iso\n// must be exported from top-level\n// https://github.com/colinhacks/zod/issues/4491\nexport { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from \"./iso.js\";\nexport * as iso from \"./iso.js\";\nexport * as coerce from \"./coerce.js\";\n", "import * as z from \"./v4/classic/external.js\";\nexport * from \"./v4/classic/external.js\";\nexport { z };\nexport default z;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Query DSL Specification\n * \n * Based on industry best practices from:\n * - Prisma ORM\n * - Strapi CMS\n * - TypeORM\n * - LoopBack Framework\n * \n * Version: 1.0.0\n * Status: Draft\n * \n * Objective: Define a JSON-based, database-agnostic query syntax standard\n * for data filtering interactions between frontend and backend APIs.\n * \n * Design Principles:\n * 1. Declarative: Frontend describes \"what data to get\", not \"how to query\"\n * 2. Database Agnostic: Syntax contains no database-specific directives\n * 3. Type Safe: Structure can be statically inferred by TypeScript\n * 4. Convention over Configuration: Implicit syntax for common queries\n */\n\n/**\n * Field Reference\n * Represents a reference to another field/column instead of a literal value.\n * Used for joins (ON clause) and cross-field comparisons.\n * \n * @example\n * // user.id = order.owner_id\n * { \"$eq\": { \"$field\": \"order.owner_id\" } }\n */\nexport const FieldReferenceSchema = z.object({\n $field: z.string().describe('Field Reference/Column Name')\n});\n\nexport type FieldReference = z.infer;\n\n// ============================================================================\n// 3.1 Comparison Operators\n// ============================================================================\n\n/**\n * Comparison operators for equality and inequality checks.\n * Supported data types: Any\n */\nexport const EqualityOperatorSchema = z.object({\n /** Equal to (default) - SQL: = | MongoDB: $eq */\n $eq: z.any().optional(),\n \n /** Not equal to - SQL: <> or != | MongoDB: $ne */\n $ne: z.any().optional(),\n});\n\n/**\n * Comparison operators for numeric and date comparisons.\n * Supported data types: Number, Date\n */\nexport const ComparisonOperatorSchema = z.object({\n /** Greater than - SQL: > | MongoDB: $gt */\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Greater than or equal to - SQL: >= | MongoDB: $gte */\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than - SQL: < | MongoDB: $lt */\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than or equal to - SQL: <= | MongoDB: $lte */\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n});\n\n// ============================================================================\n// 3.2 Set & Range Operators\n// ============================================================================\n\n/**\n * Set operators for membership checks.\n */\nexport const SetOperatorSchema = z.object({\n /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */\n $in: z.array(z.any()).optional(),\n \n /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */\n $nin: z.array(z.any()).optional(),\n});\n\n/**\n * Range operator for interval checks (closed interval).\n * SQL: BETWEEN ? AND ? | MongoDB: $gte AND $lte\n */\nexport const RangeOperatorSchema = z.object({\n /** Between (inclusive) - takes [min, max] array */\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n});\n\n// ============================================================================\n// 3.3 String-Specific Operators\n// ============================================================================\n\n/**\n * String pattern matching operators.\n * Note: Case sensitivity should be handled at backend level.\n */\nexport const StringOperatorSchema = z.object({\n /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */\n $contains: z.string().optional(),\n \n /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */\n $notContains: z.string().optional(),\n \n /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */\n $startsWith: z.string().optional(),\n \n /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */\n $endsWith: z.string().optional(),\n});\n\n// ============================================================================\n// 3.5 Special Operators\n// ============================================================================\n\n/**\n * Special check operators for null and existence.\n */\nexport const SpecialOperatorSchema = z.object({\n /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */\n $null: z.boolean().optional(),\n \n /** Field exists check (primarily for NoSQL) - MongoDB: $exists */\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// Combined Field Operators\n// ============================================================================\n\n/**\n * All field-level operators combined.\n * These can be applied to individual fields in a filter.\n */\nexport const FieldOperatorsSchema = z.object({\n // Equality\n $eq: z.any().optional(),\n $ne: z.any().optional(),\n \n // Comparison (numeric/date)\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n // Set & Range\n $in: z.array(z.any()).optional(),\n $nin: z.array(z.any()).optional(),\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n \n // String-specific\n $contains: z.string().optional(),\n $notContains: z.string().optional(),\n $startsWith: z.string().optional(),\n $endsWith: z.string().optional(),\n \n // Special\n $null: z.boolean().optional(),\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// 3.4 Logical Operators & Recursive Filter Structure\n// ============================================================================\n\n/**\n * Recursive filter type that supports:\n * 1. Implicit equality: { field: value }\n * 2. Explicit operators: { field: { $op: value } }\n * 3. Logical combinations: { $and: [...], $or: [...], $not: {...} }\n * 4. Nested relations: { relation: { field: value } }\n */\nexport type FilterCondition = {\n [key: string]: \n | any // Implicit equality: key: value\n | z.infer // Explicit operators: key: { $op: value }\n | FilterCondition; // Nested relation: key: { nested: ... }\n} & {\n /** Logical AND - combines all conditions that must be true */\n $and?: FilterCondition[];\n \n /** Logical OR - at least one condition must be true */\n $or?: FilterCondition[];\n \n /** Logical NOT - negates the condition */\n $not?: FilterCondition;\n};\n\n/**\n * Zod schema for recursive filter validation.\n * Uses z.lazy() to handle recursive structure.\n */\nexport const FilterConditionSchema: z.ZodType = z.lazy(() =>\n z.record(z.string(), z.unknown()).and(\n z.object({\n $and: z.array(FilterConditionSchema).optional(),\n $or: z.array(FilterConditionSchema).optional(),\n $not: FilterConditionSchema.optional(),\n })\n )\n);\n\n// ============================================================================\n// Query Filter Wrapper\n// ============================================================================\n\n/**\n * Top-level query filter wrapper.\n * This is typically used as the \"where\" clause in a query.\n * \n * @example\n * ```typescript\n * const filter: QueryFilter = {\n * where: {\n * status: \"active\", // Implicit equality\n * age: { $gte: 18 }, // Explicit operator\n * $or: [ // Logical combination\n * { role: \"admin\" },\n * { email: { $contains: \"@company.com\" } }\n * ],\n * profile: { // Nested relation\n * verified: true\n * }\n * }\n * }\n * ```\n */\nexport const QueryFilterSchema = z.object({\n where: FilterConditionSchema.optional(),\n});\n\n// ============================================================================\n// TypeScript Type Exports\n// ============================================================================\n\n/**\n * Type-safe filter operators for use in TypeScript.\n * \n * @example\n * ```typescript\n * type UserFilter = Filter;\n * \n * const filter: UserFilter = {\n * age: { $gte: 18 },\n * email: { $contains: \"@example.com\" }\n * };\n * ```\n */\nexport type Filter = {\n [K in keyof T]?: \n | T[K] // Implicit equality\n | {\n $eq?: T[K];\n $ne?: T[K];\n $gt?: T[K] extends number | Date ? T[K] : never;\n $gte?: T[K] extends number | Date ? T[K] : never;\n $lt?: T[K] extends number | Date ? T[K] : never;\n $lte?: T[K] extends number | Date ? T[K] : never;\n $in?: T[K][];\n $nin?: T[K][];\n $between?: T[K] extends number | Date ? [T[K], T[K]] : never;\n $contains?: T[K] extends string ? string : never;\n $notContains?: T[K] extends string ? string : never;\n $startsWith?: T[K] extends string ? string : never;\n $endsWith?: T[K] extends string ? string : never;\n $null?: boolean;\n $exists?: boolean;\n }\n | (T[K] extends object ? Filter : never); // Nested relation\n} & {\n $and?: Filter[];\n $or?: Filter[];\n $not?: Filter;\n};\n\n/**\n * Scalar types supported by the filter system.\n */\nexport type Scalar = string | number | boolean | Date | null;\n\n// Export inferred types\nexport type FieldOperators = z.infer;\nexport type QueryFilter = z.infer;\n\n// ============================================================================\n// Normalization Utilities (Internal Representation)\n// ============================================================================\n\n/**\n * Normalized filter AST structure.\n * This is the internal representation after converting all syntactic sugar\n * to explicit operators.\n * \n * Stage 1: Normalization Pass\n * Input: { age: 18, role: \"admin\" }\n * Output: { $and: [{ age: { $eq: 18 } }, { role: { $eq: \"admin\" } }] }\n * \n * This simplifies adapter implementation by providing a consistent structure.\n */\nexport const NormalizedFilterSchema: z.ZodType = z.lazy(() => \n z.object({\n $and: z.array(\n z.union([\n // Field condition: { field: { $op: value } }\n z.record(z.string(), FieldOperatorsSchema),\n // Nested logical group\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $or: z.array(\n z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $not: z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ]).optional(),\n })\n);\n\nexport type NormalizedFilter = z.infer;\n\n// ============================================================================\n// AST Array Format Detection & Validation\n// ============================================================================\n\n/**\n * Set of valid AST comparison operators (case-insensitive).\n * Used by `isFilterAST()` to validate AST structure beyond `Array.isArray`.\n */\nexport const VALID_AST_OPERATORS = new Set([\n '=', '==', '!=', '<>', '>', '>=', '<', '<=',\n 'in', 'nin', 'not_in',\n 'contains', 'notcontains', 'not_contains', 'like',\n 'startswith', 'starts_with',\n 'endswith', 'ends_with',\n 'between',\n 'is_null', 'is_not_null',\n]);\n\n/**\n * Detect whether a value is a valid Filter AST array structure.\n *\n * A valid AST is one of:\n * - Comparison node: `[field: string, operator: string, value: unknown]` where operator is a known operator\n * - Logical node: `[\"and\" | \"or\", ...children]` where children are valid AST nodes\n * - Legacy flat array: `[[cond], [cond], ...]` where all elements are sub-arrays (each a valid AST node)\n *\n * This replaces the naïve `Array.isArray(filter)` check, preventing accidental\n * misidentification of arbitrary arrays as filter ASTs.\n *\n * @example\n * isFilterAST([\"status\", \"=\", \"active\"]) // true\n * isFilterAST([\"and\", [\"a\", \"=\", 1], [\"b\", \">\", 2]]) // true\n * isFilterAST([[\"a\", \"=\", 1], [\"b\", \"=\", 2]]) // true (legacy)\n * isFilterAST([1, 2, 3]) // false\n * isFilterAST(\"not an array\") // false\n * isFilterAST({ status: \"active\" }) // false\n */\nexport function isFilterAST(filter: unknown): boolean {\n if (!Array.isArray(filter) || filter.length === 0) return false;\n\n const first = filter[0];\n\n // Logical node: [\"and\", ...] or [\"or\", ...]\n if (typeof first === 'string') {\n const lower = first.toLowerCase();\n if (lower === 'and' || lower === 'or') {\n return filter.length >= 2 && filter.slice(1).every((child: unknown) => isFilterAST(child));\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof filter[1] === 'string') {\n return VALID_AST_OPERATORS.has(filter[1].toLowerCase());\n }\n }\n\n // Legacy flat array: [[cond], [cond], ...]\n if (filter.every((item: unknown) => isFilterAST(item))) {\n return filter.length > 0;\n }\n\n return false;\n}\n\n// ============================================================================\n// AST Array → FilterCondition Conversion\n// ============================================================================\n\n/**\n * Operator mapping from AST infix operators to FilterCondition `$`-prefixed operators.\n */\nconst AST_OPERATOR_MAP: Record = {\n '=': '$eq',\n '==': '$eq',\n '!=': '$ne',\n '<>': '$ne',\n '>': '$gt',\n '>=': '$gte',\n '<': '$lt',\n '<=': '$lte',\n 'in': '$in',\n 'nin': '$nin',\n 'not_in': '$nin',\n 'contains': '$contains',\n 'notcontains': '$notContains',\n 'not_contains': '$notContains',\n 'like': '$contains',\n 'startswith': '$startsWith',\n 'starts_with': '$startsWith',\n 'endswith': '$endsWith',\n 'ends_with': '$endsWith',\n 'between': '$between',\n 'is_null': '$null',\n 'is_not_null': '$null',\n};\n\n/**\n * Convert a single AST comparison node `[field, operator, value]` to a FilterCondition object.\n */\nfunction convertComparison(node: [string, string, unknown]): FilterCondition {\n const [field, operator, value] = node;\n const op = operator.toLowerCase();\n\n // Special case: equality shorthand\n if (op === '=' || op === '==') {\n return { [field]: value } as FilterCondition;\n }\n\n // Null check operators\n if (op === 'is_null') {\n return { [field]: { $null: true } } as FilterCondition;\n }\n if (op === 'is_not_null') {\n return { [field]: { $null: false } } as FilterCondition;\n }\n\n const mapped = AST_OPERATOR_MAP[op];\n if (mapped) {\n return { [field]: { [mapped]: value } } as FilterCondition;\n }\n\n // Fallback: use the operator as-is with $ prefix\n return { [field]: { [`$${op}`]: value } } as FilterCondition;\n}\n\n/**\n * Parse a filter from AST array format to FilterCondition object format.\n *\n * The AST array format is used by the ObjectUI client and the `FilterBuilder`:\n * - Comparison: `[field, operator, value]` → `{ field: value }` or `{ field: { $op: value } }`\n * - Logical AND: `[\"and\", cond1, cond2, ...]` → `{ $and: [...] }`\n * - Logical OR: `[\"or\", cond1, cond2, ...]` → `{ $or: [...] }`\n *\n * If the input is already a FilterCondition object (not an array), it is returned as-is.\n * If the input is `null` or `undefined`, it is returned as-is.\n *\n * @example\n * // Simple condition\n * parseFilterAST([\"status\", \"=\", \"active\"])\n * // → { status: \"active\" }\n *\n * @example\n * // Compound AND\n * parseFilterAST([\"and\", [\"priority\", \"=\", \"high\"], [\"status\", \"=\", \"active\"]])\n * // → { $and: [{ priority: \"high\" }, { status: \"active\" }] }\n *\n * @example\n * // Object passthrough\n * parseFilterAST({ status: \"active\" })\n * // → { status: \"active\" }\n */\nexport function parseFilterAST(filter: unknown): FilterCondition | undefined {\n if (filter == null) return undefined;\n if (!Array.isArray(filter)) return filter as FilterCondition;\n if (filter.length === 0) return undefined;\n\n const first = filter[0];\n\n // Logical node: [\"and\", cond1, cond2, ...] or [\"or\", cond1, cond2, ...]\n if (typeof first === 'string' && (first.toLowerCase() === 'and' || first.toLowerCase() === 'or')) {\n const logicOp = `$${first.toLowerCase()}` as '$and' | '$or';\n const children = filter.slice(1).map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { [logicOp]: children } as FilterCondition;\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof first === 'string') {\n return convertComparison(filter as [string, string, unknown]);\n }\n\n // Legacy flat array: [[field, op, val], [field, op, val], ...]\n // All elements are sub-arrays → treat as implicit AND\n if (filter.every((item: unknown) => Array.isArray(item))) {\n const children = filter.map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { $and: children } as FilterCondition;\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Constants & Metadata\n// ============================================================================\n\n/**\n * All supported operator keys.\n * Useful for validation and parsing.\n */\nexport const FILTER_OPERATORS = [\n // Equality\n '$eq', '$ne',\n // Comparison\n '$gt', '$gte', '$lt', '$lte',\n // Set & Range\n '$in', '$nin', '$between',\n // String\n '$contains', '$notContains', '$startsWith', '$endsWith',\n // Special\n '$null', '$exists',\n] as const;\n\n/**\n * Logical operator keys.\n */\nexport const LOGICAL_OPERATORS = ['$and', '$or', '$not'] as const;\n\n/**\n * All operator keys (field + logical).\n */\nexport const ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS] as const;\n\nexport type FilterOperatorKey = typeof FILTER_OPERATORS[number];\nexport type LogicalOperatorKey = typeof LOGICAL_OPERATORS[number];\nexport type OperatorKey = typeof ALL_OPERATORS[number];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\n\n/**\n * Sort Node\n * Represents \"Order By\".\n */\nexport const SortNodeSchema = z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc']).default('asc')\n});\n\n/**\n * Aggregation Function Enum\n * Standard aggregation functions for data analysis.\n * \n * Supported Functions:\n * - **count**: Count rows (SQL: COUNT(*) or COUNT(field))\n * - **sum**: Sum numeric values (SQL: SUM(field))\n * - **avg**: Average numeric values (SQL: AVG(field))\n * - **min**: Minimum value (SQL: MIN(field))\n * - **max**: Maximum value (SQL: MAX(field))\n * - **count_distinct**: Count unique values (SQL: COUNT(DISTINCT field))\n * - **array_agg**: Aggregate values into array (SQL: ARRAY_AGG(field))\n * - **string_agg**: Concatenate values (SQL: STRING_AGG(field, delimiter))\n * \n * Performance Considerations:\n * - COUNT(*) is typically faster than COUNT(field) as it doesn't check for nulls\n * - COUNT DISTINCT may require additional memory for tracking unique values\n * - Window aggregates (with OVER clause) can be more efficient than subqueries\n * - Large GROUP BY operations benefit from proper indexing on grouped fields\n * \n * @example\n * // SQL: SELECT region, SUM(amount) FROM sales GROUP BY region\n * {\n * object: 'sales',\n * fields: ['region'],\n * aggregations: [\n * { function: 'sum', field: 'amount', alias: 'total_sales' }\n * ],\n * groupBy: ['region']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT COUNT(Id) FROM Account\n * {\n * object: 'account',\n * aggregations: [\n * { function: 'count', alias: 'total_accounts' }\n * ]\n * }\n */\nexport const AggregationFunction = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'array_agg', 'string_agg'\n]);\n\n/**\n * Aggregation Node\n * Represents an aggregated field with function.\n * \n * Aggregations summarize data across groups of rows (GROUP BY).\n * Used with `groupBy` to create analytical queries.\n * \n * @example\n * // SQL: SELECT customer_id, COUNT(*), SUM(amount) FROM orders GROUP BY customer_id\n * {\n * object: 'order',\n * fields: ['customer_id'],\n * aggregations: [\n * { function: 'count', alias: 'order_count' },\n * { function: 'sum', field: 'amount', alias: 'total_amount' }\n * ],\n * groupBy: ['customer_id']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT LeadSource, COUNT(Id) FROM Lead GROUP BY LeadSource\n * {\n * object: 'lead',\n * fields: ['lead_source'],\n * aggregations: [\n * { function: 'count', alias: 'lead_count' }\n * ],\n * groupBy: ['lead_source']\n * }\n */\nexport const AggregationNodeSchema = z.object({\n function: AggregationFunction.describe('Aggregation function'),\n field: z.string().optional().describe('Field to aggregate (optional for COUNT(*))'),\n alias: z.string().describe('Result column alias'),\n distinct: z.boolean().optional().describe('Apply DISTINCT before aggregation'),\n filter: FilterConditionSchema.optional().describe('Filter/Condition to apply to the aggregation (FILTER WHERE clause)'),\n});\n\n/**\n * Join Type Enum\n * Standard SQL join types for combining tables.\n * \n * Join Types:\n * - **inner**: Returns only matching rows from both tables (SQL: INNER JOIN)\n * - **left**: Returns all rows from left table, matching rows from right (SQL: LEFT JOIN)\n * - **right**: Returns all rows from right table, matching rows from left (SQL: RIGHT JOIN)\n * - **full**: Returns all rows from both tables (SQL: FULL OUTER JOIN)\n * \n * @example\n * // SQL: SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * on: ['order.customer_id', '=', 'customer.id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL-style: Find all customers and their orders (if any)\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * on: ['customer.id', '=', 'order.customer_id']\n * }\n * ]\n * }\n */\nexport const JoinType = z.enum(['inner', 'left', 'right', 'full']);\n\n/**\n * Join Execution Strategy\n * Hints to the query engine on how to execute the join.\n * \n * Strategies:\n * - **auto**: Engine decides best strategy (Default).\n * - **database**: Push down join to the database (Requires same datasource).\n * - **hash**: Load both sets into memory and hash join (Cross-datasource, memory intensive).\n * - **loop**: Nested loop lookup (N+1 safe version). (Good for small right-side lookups).\n */\nexport const JoinStrategy = z.enum(['auto', 'database', 'hash', 'loop']);\n\n/**\n * Join Node\n * Represents table joins for combining data from multiple objects.\n * \n * Joins connect related data across multiple tables using ON conditions.\n * Supports both direct object joins and subquery joins.\n * \n * @example\n * // SQL: SELECT o.*, c.name FROM orders o INNER JOIN customers c ON o.customer_id = c.id\n * {\n * object: 'order',\n * fields: ['id', 'amount'],\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Multi-table join\n * // SELECT * FROM orders o\n * // INNER JOIN customers c ON o.customer_id = c.id\n * // LEFT JOIN shipments s ON o.id = s.order_id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * },\n * {\n * type: 'left',\n * object: 'shipment',\n * alias: 's',\n * on: ['order.id', '=', 's.order_id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT Name, (SELECT LastName FROM Contacts) FROM Account\n * {\n * object: 'account',\n * fields: ['name'],\n * joins: [\n * {\n * type: 'left',\n * object: 'contact',\n * on: ['account.id', '=', 'contact.account_id']\n * }\n * ]\n * }\n * \n * @example\n * // Subquery Join: Join with a filtered/aggregated dataset\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * alias: 'high_value_orders',\n * on: ['customer.id', '=', 'high_value_orders.customer_id'],\n * subquery: {\n * object: 'order',\n * fields: ['customer_id', 'total'],\n * filters: ['total', '>', 1000]\n * }\n * }\n * ]\n * }\n */\nexport const JoinNodeSchema: z.ZodType = z.lazy(() => \n z.object({\n type: JoinType.describe('Join type'),\n strategy: JoinStrategy.optional().describe('Execution strategy hint'),\n object: z.string().describe('Object/table to join'),\n alias: z.string().optional().describe('Table alias'),\n on: FilterConditionSchema.describe('Join condition'),\n subquery: z.lazy(() => QuerySchema).optional().describe('Subquery instead of object'),\n })\n);\n\n/**\n * Window Function Enum\n * Advanced analytical functions for row-based calculations.\n * \n * Window Functions:\n * - **row_number**: Sequential number within partition (SQL: ROW_NUMBER() OVER (...))\n * - **rank**: Rank with gaps for ties (SQL: RANK() OVER (...))\n * - **dense_rank**: Rank without gaps (SQL: DENSE_RANK() OVER (...))\n * - **percent_rank**: Relative rank as percentage (SQL: PERCENT_RANK() OVER (...))\n * - **lag**: Access previous row value (SQL: LAG(field) OVER (...))\n * - **lead**: Access next row value (SQL: LEAD(field) OVER (...))\n * - **first_value**: First value in window (SQL: FIRST_VALUE(field) OVER (...))\n * - **last_value**: Last value in window (SQL: LAST_VALUE(field) OVER (...))\n * - **sum/avg/count/min/max**: Aggregates over window (SQL: SUM(field) OVER (...))\n * \n * @example\n * // SQL: SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) as rank\n * // FROM orders\n * {\n * object: 'order',\n * fields: ['id', 'customer_id', 'amount'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'rank',\n * over: {\n * partitionBy: ['customer_id'],\n * orderBy: [{ field: 'amount', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Running total with SUM() OVER (...)\n * {\n * object: 'transaction',\n * fields: ['date', 'amount'],\n * windowFunctions: [\n * {\n * function: 'sum',\n * field: 'amount',\n * alias: 'running_total',\n * over: {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: 'UNBOUNDED PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunction = z.enum([\n 'row_number', 'rank', 'dense_rank', 'percent_rank',\n 'lag', 'lead', 'first_value', 'last_value',\n 'sum', 'avg', 'count', 'min', 'max'\n]);\n\n/**\n * Window Specification\n * Defines PARTITION BY and ORDER BY for window functions.\n * \n * Window specifications control how window functions compute values:\n * - **partitionBy**: Divide rows into groups (like GROUP BY but without collapsing rows)\n * - **orderBy**: Define order for ranking and offset functions\n * - **frame**: Specify which rows to include in aggregate calculations\n * \n * @example\n * // Partition by department, order by salary\n * {\n * partitionBy: ['department'],\n * orderBy: [{ field: 'salary', order: 'desc' }]\n * }\n * \n * @example\n * // Moving average with frame specification\n * {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: '6 PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n */\nexport const WindowSpecSchema = z.object({\n partitionBy: z.array(z.string()).optional().describe('PARTITION BY fields'),\n orderBy: z.array(SortNodeSchema).optional().describe('ORDER BY specification'),\n frame: z.object({\n type: z.enum(['rows', 'range']).optional(),\n start: z.string().optional().describe('Frame start (e.g., \"UNBOUNDED PRECEDING\", \"1 PRECEDING\")'),\n end: z.string().optional().describe('Frame end (e.g., \"CURRENT ROW\", \"1 FOLLOWING\")'),\n }).optional().describe('Window frame specification'),\n});\n\n/**\n * Window Function Node\n * Represents window function with OVER clause.\n * \n * Window functions perform calculations across a set of rows related to the current row,\n * without collapsing the result set (unlike GROUP BY aggregations).\n * \n * @example\n * // SQL: Top 3 products per category\n * // SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as rank\n * // FROM products\n * {\n * object: 'product',\n * fields: ['name', 'category', 'sales'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'category_rank',\n * over: {\n * partitionBy: ['category'],\n * orderBy: [{ field: 'sales', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Year-over-year comparison with LAG\n * {\n * object: 'monthly_sales',\n * fields: ['month', 'revenue'],\n * windowFunctions: [\n * {\n * function: 'lag',\n * field: 'revenue',\n * alias: 'prev_year_revenue',\n * over: {\n * orderBy: [{ field: 'month', order: 'asc' }]\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunctionNodeSchema = z.object({\n function: WindowFunction.describe('Window function name'),\n field: z.string().optional().describe('Field to operate on (for aggregate window functions)'),\n alias: z.string().describe('Result column alias'),\n over: WindowSpecSchema.describe('Window specification (OVER clause)'),\n});\n\n/**\n * Field Selection Node\n * Represents \"Select\" attributes, including joins.\n */\nexport const FieldNodeSchema: z.ZodType = z.lazy(() => \n z.union([\n z.string(), // Primitive field: \"name\"\n z.object({\n field: z.string(), // Relationship field: \"owner\"\n fields: z.array(FieldNodeSchema).optional(), // Nested select: [\"name\", \"email\"]\n alias: z.string().optional()\n })\n ])\n);\n\n/**\n * Full-Text Search Configuration\n * Defines full-text search parameters for text queries.\n * \n * Supports:\n * - Multi-field search\n * - Relevance scoring\n * - Fuzzy matching\n * - Language-specific analyzers\n * \n * @example\n * {\n * query: \"John Smith\",\n * fields: [\"name\", \"email\", \"description\"],\n * fuzzy: true,\n * boost: { \"name\": 2.0, \"email\": 1.5 }\n * }\n */\nexport const FullTextSearchSchema = z.object({\n query: z.string().describe('Search query text'),\n fields: z.array(z.string()).optional().describe('Fields to search in (if not specified, searches all text fields)'),\n fuzzy: z.boolean().optional().default(false).describe('Enable fuzzy matching (tolerates typos)'),\n operator: z.enum(['and', 'or']).optional().default('or').describe('Logical operator between terms'),\n boost: z.record(z.string(), z.number()).optional().describe('Field-specific relevance boosting (field name -> boost factor)'),\n minScore: z.number().optional().describe('Minimum relevance score threshold'),\n language: z.string().optional().describe('Language for text analysis (e.g., \"en\", \"zh\", \"es\")'),\n highlight: z.boolean().optional().default(false).describe('Enable search result highlighting'),\n});\n\nexport type FullTextSearch = z.infer;\n\n/**\n * Query AST Schema\n * The universal data retrieval contract defined in `ast-structure.mdx`.\n * \n * This schema represents ObjectQL - a universal query language that abstracts\n * SQL, NoSQL, and SaaS APIs into a single unified interface.\n * \n * Updates (v2):\n * - Aligned with modern ORM standards (Prisma/TypeORM)\n * - Added `cursor` based pagination support\n * - Renamed `top`/`skip` to `limit`/`offset`\n * - Unified filtering syntax with `FilterConditionSchema`\n * \n * Updates (v3):\n * - Added `search` parameter for full-text search (P2 requirement)\n * \n * @example\n * // Simple query: SELECT name, email FROM account WHERE status = 'active'\n * {\n * object: 'account',\n * fields: ['name', 'email'],\n * where: { status: 'active' }\n * }\n * \n * @example\n * // Pagination with Limit/Offset\n * {\n * object: 'post',\n * where: { published: true },\n * orderBy: [{ field: 'created_at', order: 'desc' }],\n * limit: 20,\n * offset: 40\n * }\n * \n * @example\n * // Full-text search\n * {\n * object: 'article',\n * search: {\n * query: \"machine learning\",\n * fields: [\"title\", \"content\"],\n * fuzzy: true,\n * boost: { \"title\": 2.0 }\n * },\n * limit: 10\n * }\n */\nconst BaseQuerySchema = z.object({\n /** Target Entity */\n object: z.string().describe('Object name (e.g. account)'),\n \n /** Select Clause */\n fields: z.array(FieldNodeSchema).optional().describe('Fields to retrieve'),\n \n /** Where Clause (Filtering) */\n where: FilterConditionSchema.optional().describe('Filtering criteria (WHERE)'),\n \n /** Full-Text Search */\n search: FullTextSearchSchema.optional().describe('Full-text search configuration ($search parameter)'),\n \n /** Order By Clause (Sorting) */\n orderBy: z.array(SortNodeSchema).optional().describe('Sorting instructions (ORDER BY)'),\n \n /** Pagination */\n limit: z.number().optional().describe('Max records to return (LIMIT)'),\n offset: z.number().optional().describe('Records to skip (OFFSET)'),\n top: z.number().optional().describe('Alias for limit (OData compatibility)'),\n cursor: z.record(z.string(), z.unknown()).optional().describe('Cursor for keyset pagination'),\n \n /** Joins */\n joins: z.array(JoinNodeSchema).optional().describe('Explicit Table Joins'),\n \n /** Aggregations */\n aggregations: z.array(AggregationNodeSchema).optional().describe('Aggregation functions'),\n \n /** Group By Clause */\n groupBy: z.array(z.string()).optional().describe('GROUP BY fields'),\n \n /** Having Clause */\n having: FilterConditionSchema.optional().describe('HAVING clause for aggregation filtering'),\n \n /** Window Functions */\n windowFunctions: z.array(WindowFunctionNodeSchema).optional().describe('Window functions with OVER clause'),\n \n /** Subquery flag */\n distinct: z.boolean().optional().describe('SELECT DISTINCT flag'),\n});\n\n/**\n * QueryAST — Abstract Syntax Tree for data queries.\n *\n * The `expand` property enables recursive loading of related records through\n * lookup and master_detail fields. Each key is a relationship field name; the\n * value is a nested QueryAST that can further filter, select, sort, and expand\n * the related records (up to a default max depth of 3).\n *\n * @example\n * ```ts\n * const ast: QueryAST = {\n * object: 'task',\n * fields: ['title', 'assignee'],\n * expand: {\n * assignee: { object: 'user', fields: ['name', 'email'] },\n * project: {\n * object: 'project',\n * expand: { org: { object: 'org' } } // nested expand\n * }\n * }\n * };\n * ```\n */\nexport type QueryAST = z.infer & {\n expand?: Record;\n};\n\nexport type QueryInput = z.input & {\n expand?: Record;\n};\n\nexport const QuerySchema: z.ZodType = BaseQuerySchema.extend({\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional().describe(\n 'Recursive relation loading map. Keys are lookup/master_detail field names; '\n + 'values are nested QueryAST objects that control select, filter, sort, and '\n + 'further expansion on the related object. The engine resolves expand via '\n + 'batch $in queries (driver-agnostic) with a default max depth of 3.'\n ),\n});\n\nexport type SortNode = z.infer;\nexport type AggregationNode = z.infer;\nexport type JoinNode = z.infer;\nexport type WindowFunctionNode = z.infer;\nexport type WindowSpec = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # ObjectStack Validation Protocol\n * \n * This module defines the validation schema protocol for ObjectStack, providing a comprehensive\n * type-safe validation system similar to Salesforce's validation rules but with enhanced capabilities.\n * \n * ## Overview\n * \n * Validation rules are applied at the data layer to ensure data integrity and enforce business logic.\n * The system supports multiple validation types:\n * \n * 1. **Script Validation**: Formula-based validation using expressions\n * 2. **Uniqueness Validation**: Enforce unique constraints across fields\n * 3. **State Machine Validation**: Control allowed state transitions\n * 4. **Format Validation**: Validate field formats (email, URL, regex, etc.)\n * 5. **Cross-Field Validation**: Validate relationships between multiple fields\n * 6. **Async Validation**: Remote validation via API calls\n * 7. **Custom Validation**: User-defined validation functions\n * 8. **Conditional Validation**: Apply validations based on conditions\n * \n * ## Salesforce Comparison\n * \n * ObjectStack validation rules are inspired by Salesforce validation rules but enhanced:\n * - Salesforce: Formula-based validation with `Error Condition Formula`\n * - ObjectStack: Multiple validation types with composable rules\n * \n * Example Salesforce validation rule:\n * ```\n * Rule Name: Discount_Cannot_Exceed_40_Percent\n * Error Condition Formula: Discount_Percent__c > 0.40\n * Error Message: Discount cannot exceed 40%.\n * ```\n * \n * Equivalent ObjectStack rule:\n * ```typescript\n * {\n * type: 'script',\n * name: 'discount_cannot_exceed_40_percent',\n * condition: 'discount_percent > 0.40',\n * message: 'Discount cannot exceed 40%',\n * severity: 'error'\n * }\n * ```\n */\n\n/**\n * Base Validation Rule\n * \n * All validation rules extend from this base schema with common properties.\n * \n * ## Industry Standard Enhancements\n * - **Label/Description**: Essential for governance in large systems with thousands of rules.\n * - **Events**: granular control over validation timing (Context-aware validation).\n * - **Tags**: categorization for reporting and management.\n */\nconst BaseValidationSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label for the rule listing'),\n description: z.string().optional().describe('Administrative notes explaining the business reason'),\n \n // Execution Control\n active: z.boolean().default(true),\n events: z.array(z.enum(['insert', 'update', 'delete'])).default(['insert', 'update']).describe('Validation contexts'),\n priority: z.number().int().min(0).max(9999).default(100).describe('Execution priority (lower runs first, default: 100)'),\n \n // Classification\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g., \"compliance\", \"billing\")'),\n \n // Feedback\n severity: z.enum(['error', 'warning', 'info']).default('error'),\n message: z.string().describe('Error message to display to the user'),\n});\n\n/**\n * 1. Script/Expression Validation\n * Generic formula-based validation.\n */\nexport const ScriptValidationSchema = BaseValidationSchema.extend({\n type: z.literal('script'),\n condition: z.string().describe('Formula expression. If TRUE, validation fails. (e.g. amount < 0)'),\n});\n\n/**\n * 2. Uniqueness Validation\n * specialized optimized check for unique constraints.\n */\nexport const UniquenessValidationSchema = BaseValidationSchema.extend({\n type: z.literal('unique'),\n fields: z.array(z.string()).describe('Fields that must be combined unique'),\n scope: z.string().optional().describe('Formula condition for scope (e.g. active = true)'),\n caseSensitive: z.boolean().default(true),\n});\n\n/**\n * 3. State Machine Validation\n * State transition logic.\n */\nexport const StateMachineValidationSchema = BaseValidationSchema.extend({\n type: z.literal('state_machine'),\n field: z.string().describe('State field (e.g. status)'),\n transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'),\n});\n\n/**\n * 4. Value Format Validation\n * Regex or specialized formats.\n */\nexport const FormatValidationSchema = BaseValidationSchema.extend({\n type: z.literal('format'),\n field: z.string(),\n regex: z.string().optional(),\n format: z.enum(['email', 'url', 'phone', 'json']).optional(),\n});\n\n/**\n * 5. Cross-Field Validation\n * Validates relationships between multiple fields.\n * \n * ## Use Cases\n * - Date range validations (end_date > start_date)\n * - Amount comparisons (discount < total)\n * - Complex business rules involving multiple fields\n * \n * ## Salesforce Examples\n * \n * ### Example 1: Close Date Must Be In Current or Future Month\n * **Salesforce Formula:**\n * ```\n * MONTH(CloseDate) < MONTH(TODAY()) ||\n * YEAR(CloseDate) < YEAR(TODAY())\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'close_date_future',\n * condition: 'MONTH(close_date) >= MONTH(TODAY()) AND YEAR(close_date) >= YEAR(TODAY())',\n * fields: ['close_date'],\n * message: 'Close Date must be in the current or a future month'\n * }\n * ```\n * \n * ### Example 2: Discount Validation\n * **Salesforce Formula:**\n * ```\n * Discount__c > (Amount__c * 0.40)\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'discount_limit',\n * condition: 'discount > (amount * 0.40)',\n * fields: ['discount', 'amount'],\n * message: 'Discount cannot exceed 40% of the amount'\n * }\n * ```\n * \n * ### Example 3: Opportunity Must Have Products\n * **Salesforce Formula:**\n * ```\n * ISBLANK(Products__c) && ISPICKVAL(StageName, \"Closed Won\")\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'products_required_for_won',\n * condition: 'products = null AND stage = \"closed_won\"',\n * fields: ['products', 'stage'],\n * message: 'Opportunity must have products to be marked as Closed Won'\n * }\n * ```\n */\nexport const CrossFieldValidationSchema = BaseValidationSchema.extend({\n type: z.literal('cross_field'),\n condition: z.string().describe('Formula expression comparing fields (e.g. \"end_date > start_date\")'),\n fields: z.array(z.string()).describe('Fields involved in the validation'),\n});\n\n/**\n * 6. JSON Structure Validation\n * Validates JSON fields against a JSON Schema.\n * \n * ## Use Cases\n * - Validating configuration objects stored in JSON fields\n * - Enforcing API payload structures\n * - Complex nested data validation\n */\nexport const JSONValidationSchema = BaseValidationSchema.extend({\n type: z.literal('json_schema'),\n field: z.string().describe('JSON field to validate'),\n schema: z.record(z.string(), z.unknown()).describe('JSON Schema object definition'),\n});\n\n/**\n * 7. Async Validation\n * Remote validation via API call or database query.\n * \n * ## Use Cases\n * \n * ### 1. Email Uniqueness Check\n * Check if an email address is already registered in the system.\n * ```typescript\n * {\n * type: 'async',\n * name: 'unique_email',\n * field: 'email',\n * validatorUrl: '/api/users/check-email',\n * message: 'This email address is already registered',\n * debounce: 500, // Wait 500ms after user stops typing\n * timeout: 3000\n * }\n * ```\n * \n * ### 2. Username Availability\n * Verify username is available before form submission.\n * ```typescript\n * {\n * type: 'async',\n * name: 'username_available',\n * field: 'username',\n * validatorUrl: '/api/users/check-username',\n * message: 'This username is already taken',\n * debounce: 300,\n * timeout: 2000\n * }\n * ```\n * \n * ### 3. Tax ID Validation\n * Validate tax ID with government API (e.g., IRS, HMRC).\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_tax_id',\n * field: 'tax_id',\n * validatorFunction: 'validateTaxIdWithIRS',\n * message: 'Invalid Tax ID number',\n * timeout: 10000, // Government APIs may be slow\n * params: { country: 'US', format: 'EIN' }\n * }\n * ```\n * \n * ### 4. Credit Card Validation\n * Verify credit card with payment gateway without charging.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_card',\n * field: 'card_number',\n * validatorUrl: 'https://api.stripe.com/v1/tokens/validate',\n * message: 'Invalid credit card number',\n * timeout: 5000,\n * params: { \n * mode: 'validate_only',\n * checkFunds: false \n * }\n * }\n * ```\n * \n * ### 5. Address Validation\n * Validate and standardize addresses using geocoding services.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_address',\n * field: 'street_address',\n * validatorFunction: 'validateAddressWithGoogleMaps',\n * message: 'Unable to verify address',\n * timeout: 4000,\n * params: {\n * includeFields: ['city', 'state', 'zip'],\n * strictMode: true,\n * country: 'US'\n * }\n * }\n * ```\n * \n * ### 6. Domain Name Availability\n * Check if domain name is available for registration.\n * ```typescript\n * {\n * type: 'async',\n * name: 'domain_available',\n * field: 'domain_name',\n * validatorUrl: '/api/domains/check-availability',\n * message: 'This domain is already taken or reserved',\n * debounce: 500,\n * timeout: 2000\n * }\n * ```\n * \n * ### 7. Coupon Code Validation\n * Verify coupon code is valid and not expired.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_coupon',\n * field: 'coupon_code',\n * validatorUrl: '/api/coupons/validate',\n * message: 'Invalid or expired coupon code',\n * timeout: 2000,\n * params: {\n * checkExpiration: true,\n * checkUsageLimit: true,\n * userId: '{{current_user_id}}'\n * }\n * }\n * ```\n */\nexport const AsyncValidationSchema = BaseValidationSchema.extend({\n type: z.literal('async'),\n field: z.string().describe('Field to validate'),\n validatorUrl: z.string().optional().describe('External API endpoint for validation'),\n method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method for external call'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for the request'),\n validatorFunction: z.string().optional().describe('Reference to custom validator function'),\n timeout: z.number().optional().default(5000).describe('Timeout in milliseconds'),\n debounce: z.number().optional().describe('Debounce delay in milliseconds'),\n params: z.record(z.string(), z.unknown()).optional().describe('Additional parameters to pass to validator'),\n});\n\n/**\n * 8. Custom Validator Function\n * User-defined validation logic with code reference.\n */\nexport const CustomValidatorSchema = BaseValidationSchema.extend({\n type: z.literal('custom'),\n handler: z.string().describe('Name of the custom validation function registered in the system'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the custom handler'),\n});\n\n/**\n * 9. Master Validation Rule Schema\n */\n/** Base type for validation rules - used for z.lazy() recursive type annotation */\nexport interface BaseValidationRuleShape {\n type: string;\n name: string;\n message: string;\n label?: string;\n description?: string;\n active?: boolean;\n events?: ('insert' | 'update' | 'delete')[];\n priority?: number;\n tags?: string[];\n severity?: 'error' | 'warning' | 'info';\n [key: string]: unknown;\n}\n\nexport const ValidationRuleSchema: z.ZodType = z.lazy(() =>\n z.discriminatedUnion('type', [\n ScriptValidationSchema,\n UniquenessValidationSchema,\n StateMachineValidationSchema,\n FormatValidationSchema,\n CrossFieldValidationSchema,\n JSONValidationSchema,\n AsyncValidationSchema,\n CustomValidatorSchema,\n ConditionalValidationSchema,\n ])\n);\n\n/**\n * 8. Conditional Validation\n * Validation that only applies when a condition is met.\n * \n * ## Overview\n * Conditional validations follow the pattern: \"Validate X only if Y is true\"\n * This allows for context-aware validation rules that adapt to different scenarios.\n * \n * ## Use Cases\n * \n * ### 1. Validate Based on Record Type\n * Apply different validation rules based on the type of record.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_approval_required',\n * when: 'account_type = \"enterprise\"',\n * message: 'Enterprise validation',\n * then: {\n * type: 'script',\n * name: 'require_approval',\n * message: 'Enterprise accounts require manager approval',\n * condition: 'approval_status = null'\n * }\n * }\n * ```\n * \n * ### 2. Conditional Field Requirements\n * Require certain fields only when specific conditions are met.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'shipping_address_when_required',\n * when: 'requires_shipping = true',\n * message: 'Shipping validation',\n * then: {\n * type: 'script',\n * name: 'shipping_address_required',\n * message: 'Shipping address is required for physical products',\n * condition: 'shipping_address = null OR shipping_address = \"\"'\n * }\n * }\n * ```\n * \n * ### 3. Amount-Based Validation\n * Apply different rules based on transaction amount.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'high_value_approval',\n * when: 'order_total > 10000',\n * message: 'High value order validation',\n * then: {\n * type: 'script',\n * name: 'manager_approval_required',\n * message: 'Orders over $10,000 require manager approval',\n * condition: 'manager_approval_id = null'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'standard_validation',\n * message: 'Payment method is required',\n * condition: 'payment_method = null'\n * }\n * }\n * ```\n * \n * ### 4. Regional Compliance\n * Apply region-specific validation rules.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'regional_compliance',\n * when: 'region = \"EU\"',\n * message: 'EU compliance validation',\n * then: {\n * type: 'script',\n * name: 'gdpr_consent',\n * message: 'GDPR consent is required for EU customers',\n * condition: 'gdpr_consent_given = false'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'tos_acceptance',\n * message: 'Terms of Service acceptance required',\n * condition: 'tos_accepted = false'\n * }\n * }\n * ```\n * \n * ### 5. Nested Conditional Validation\n * Create complex validation logic with nested conditions.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'country_state_validation',\n * when: 'country = \"US\"',\n * message: 'US-specific validation',\n * then: {\n * type: 'conditional',\n * name: 'california_validation',\n * when: 'state = \"CA\"',\n * message: 'California-specific validation',\n * then: {\n * type: 'script',\n * name: 'ca_tax_id_required',\n * message: 'California requires a valid tax ID',\n * condition: 'tax_id = null OR NOT(REGEX(tax_id, \"^\\\\d{2}-\\\\d{7}$\"))'\n * }\n * }\n * }\n * ```\n * \n * ### 6. Tax Validation for Taxable Items\n * Only validate tax fields when the item is taxable.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'tax_field_validation',\n * when: 'is_taxable = true',\n * message: 'Tax validation',\n * then: {\n * type: 'script',\n * name: 'tax_code_required',\n * message: 'Tax code is required for taxable items',\n * condition: 'tax_code = null OR tax_code = \"\"'\n * }\n * }\n * ```\n * \n * ### 7. Role-Based Validation\n * Apply validation based on user role.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'role_based_approval_limit',\n * when: 'user_role = \"manager\"',\n * message: 'Manager approval limits',\n * then: {\n * type: 'script',\n * name: 'manager_limit',\n * message: 'Managers can approve up to $50,000',\n * condition: 'approval_amount > 50000'\n * }\n * }\n * ```\n * \n * ## Salesforce Pattern Comparison\n * \n * Salesforce doesn't have explicit \"conditional validation\" rules but achieves similar\n * behavior using formula logic. ObjectStack makes this pattern explicit and composable.\n * \n * **Salesforce Approach:**\n * ```\n * IF(\n * ISPICKVAL(Type, \"Enterprise\"),\n * AND(Amount > 100000, ISBLANK(Approval__c)),\n * FALSE\n * )\n * ```\n * \n * **ObjectStack Approach:**\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_high_value',\n * when: 'type = \"enterprise\"',\n * then: {\n * type: 'cross_field',\n * name: 'amount_approval',\n * condition: 'amount > 100000 AND approval = null',\n * fields: ['amount', 'approval']\n * }\n * }\n * ```\n */\nexport const ConditionalValidationSchema = BaseValidationSchema.extend({\n type: z.literal('conditional'),\n when: z.string().describe('Condition formula (e.g. \"type = \\'enterprise\\'\")'),\n then: ValidationRuleSchema.describe('Validation rule to apply when condition is true'),\n otherwise: ValidationRuleSchema.optional().describe('Validation rule to apply when condition is false'),\n});\n\nexport type ValidationRule = z.infer;\nexport type ScriptValidation = z.infer;\nexport type UniquenessValidation = z.infer;\nexport type StateMachineValidation = z.infer;\nexport type FormatValidation = z.infer;\nexport type CrossFieldValidation = z.infer;\nexport type JSONValidation = z.infer;\nexport type AsyncValidation = z.infer;\nexport type CustomValidation = z.infer;\nexport type ConditionalValidation = z.infer;", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * XState-inspired State Machine Protocol\n * Used to define strict business logic constraints and lifecycle management.\n * Prevent AI \"hallucinations\" by enforcing valid valid transitions.\n */\n\n// --- Primitives ---\n\n/**\n * References a named action (side effect)\n * Can be a script, a webhook, or a field update.\n */\nexport const ActionRefSchema = z.union([\n z.string().describe('Action Name'),\n z.object({\n type: z.string(), // e.g., 'xstate.assign', 'log', 'email'\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n/**\n * References a named condition (guard)\n * Must evaluate to true for the transition to occur.\n */\nexport const GuardRefSchema = z.union([\n z.string().describe('Guard Name (e.g., \"isManager\", \"amountGT1000\")'),\n z.object({\n type: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n// --- Core Structure ---\n\n/**\n * State Transition Definition\n * \"When EVENT happens, if GUARD is true, go to TARGET and run ACTIONS\"\n */\nexport const TransitionSchema = z.object({\n target: z.string().optional().describe('Target State ID'),\n cond: GuardRefSchema.optional().describe('Condition (Guard) required to take this path'),\n actions: z.array(ActionRefSchema).optional().describe('Actions to execute during transition'),\n description: z.string().optional().describe('Human readable description of this rule'),\n});\n\n/**\n * Event Definition (Signals)\n */\nexport const EventSchema = z.object({\n type: z.string().describe('Event Type (e.g. \"APPROVE\", \"REJECT\", \"Submit\")'),\n // Payload validation schema could go here if we want deep validation\n schema: z.record(z.string(), z.unknown()).optional().describe('Expected event payload structure'),\n});\n\nexport type ActionRef = z.infer;\nexport type Transition = z.infer;\n\nexport type StateNodeConfig = {\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n entry?: ActionRef[];\n exit?: ActionRef[];\n on?: Record;\n always?: Transition[];\n initial?: string;\n states?: Record;\n meta?: {\n label?: string;\n description?: string;\n color?: string;\n aiInstructions?: string;\n };\n};\n\n/**\n * State Node Definition\n */\nexport const StateNodeSchema: z.ZodType = z.lazy(() => z.object({\n /** Type of state */\n type: z.enum(['atomic', 'compound', 'parallel', 'final', 'history']).default('atomic'),\n \n /** Entry/Exit Actions */\n entry: z.array(ActionRefSchema).optional().describe('Actions to run when entering this state'),\n exit: z.array(ActionRefSchema).optional().describe('Actions to run when leaving this state'),\n \n /** Transitions (Events) */\n on: z.record(z.string(), z.union([\n z.string(), // Shorthand target\n TransitionSchema, \n z.array(TransitionSchema)\n ])).optional().describe('Map of Event Type -> Transition Definition'),\n \n /** Always Transitions (Eventless) */\n always: z.array(TransitionSchema).optional(),\n\n /** Nesting (Hierarchical States) */\n initial: z.string().optional().describe('Initial child state (if compound)'),\n states: z.record(z.string(), StateNodeSchema).optional(),\n \n /** Metadata for UI/AI */\n meta: z.object({\n label: z.string().optional(),\n description: z.string().optional(),\n color: z.string().optional(), // For UI diagrams\n // Instructions for AI Agent when in this state\n aiInstructions: z.string().optional().describe('Specific instructions for AI when in this state'),\n }).optional(),\n}));\n\n/**\n * Top-Level State Machine Definition\n */\nexport const StateMachineSchema = z.object({\n id: SnakeCaseIdentifierSchema.describe('Unique Machine ID'),\n description: z.string().optional(),\n \n /** Context (Memory) Schema */\n contextSchema: z.record(z.string(), z.unknown()).optional().describe('Zod Schema for the machine context/memory'),\n \n /** Initial State */\n initial: z.string().describe('Initial State ID'),\n \n /** State Definitions */\n states: z.record(z.string(), StateNodeSchema).describe('State Nodes'),\n \n /** Global Listeners */\n on: z.record(z.string(), z.union([z.string(), TransitionSchema, z.array(TransitionSchema)])).optional(),\n});\n\nexport type StateMachineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from './field.zod';\nimport { ValidationRuleSchema } from './validation.zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\nimport { ActionSchema } from '../ui/action.zod';\n\n/**\n * API Operations Enum\n */\nexport const ApiMethod = z.enum([\n 'get', 'list', // Read\n 'create', 'update', 'delete', // Write\n 'upsert', // Idempotent Write\n 'bulk', // Batch operations\n 'aggregate', // Analytics (count, sum)\n 'history', // Audit access\n 'search', // Search access\n 'restore', 'purge', // Trash management\n 'import', 'export', // Data portability\n]);\nexport type ApiMethod = z.infer;\n\n/**\n * Capability Flags\n * Defines what system features are enabled for this object.\n * \n * Optimized based on industry standards (Salesforce, ServiceNow):\n * - Added `activities` (Tasks/Events)\n * - Added `mru` (Recent Items)\n * - Added `feeds` (Social/Chatter)\n * - Grouped API permissions\n * \n * @example\n * {\n * trackHistory: true,\n * searchable: true,\n * apiEnabled: true,\n * files: true\n * }\n */\nexport const ObjectCapabilities = z.object({\n /** Enable history tracking (Audit Trail) */\n trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),\n \n /** Enable global search indexing */\n searchable: z.boolean().default(true).describe('Index records for global search'),\n \n /** Enable REST/GraphQL API access */\n apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),\n\n /** \n * API Supported Operations\n * Granular control over API exposure.\n */\n apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),\n \n /** Enable standard attachments/files engine */\n files: z.boolean().default(false).describe('Enable file attachments and document management'),\n \n /** Enable social collaboration (Comments, Mentions, Feeds) */\n feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),\n \n /** Enable standard Activity suite (Tasks, Calendars, Events) */\n activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),\n \n /** Enable Recycle Bin / Soft Delete */\n trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),\n\n /** Enable \"Recently Viewed\" tracking */\n mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),\n \n /** Allow cloning records */\n clone: z.boolean().default(true).describe('Allow record deep cloning'),\n});\n\n/**\n * Schema for database indexes.\n * Enhanced with additional index types and configuration options\n * \n * @example\n * {\n * name: \"idx_account_name\",\n * fields: [\"name\"],\n * type: \"btree\",\n * unique: true\n * }\n */\nexport const IndexSchema = z.object({\n name: z.string().optional().describe('Index name (auto-generated if not provided)'),\n fields: z.array(z.string()).describe('Fields included in the index'),\n type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),\n unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),\n partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),\n});\n\n/**\n * Search Configuration\n * Defines how this object behaves in search results.\n * \n * @example\n * {\n * fields: [\"name\", \"email\", \"phone\"],\n * displayFields: [\"name\", \"title\"],\n * filters: [\"status = 'active'\"]\n * }\n */\nexport const SearchConfigSchema = z.object({\n fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),\n displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),\n filters: z.array(z.string()).optional().describe('Default filters for search results'),\n});\n\n/**\n * Multi-Tenancy Configuration Schema\n * Configures tenant isolation strategy for SaaS applications\n * \n * @example Shared database with tenant_id isolation\n * {\n * enabled: true,\n * strategy: 'shared',\n * tenantField: 'tenant_id',\n * crossTenantAccess: false\n * }\n */\nexport const TenancyConfigSchema = z.object({\n enabled: z.boolean().describe('Enable multi-tenancy for this object'),\n strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),\n tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),\n crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),\n});\n\n/**\n * Soft Delete Configuration Schema\n * Implements recycle bin / trash functionality\n * \n * @example Standard soft delete with cascade\n * {\n * enabled: true,\n * field: 'deleted_at',\n * cascadeDelete: true\n * }\n */\nexport const SoftDeleteConfigSchema = z.object({\n enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),\n field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),\n cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),\n});\n\n/**\n * Versioning Configuration Schema\n * Implements record versioning and history tracking\n * \n * @example Snapshot versioning with 90-day retention\n * {\n * enabled: true,\n * strategy: 'snapshot',\n * retentionDays: 90,\n * versionField: 'version'\n * }\n */\nexport const VersioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable record versioning'),\n strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),\n retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),\n versionField: z.string().default('version').describe('Field name for version number/timestamp'),\n});\n\n/**\n * Partitioning Strategy Schema\n * Configures table partitioning for performance at scale\n * \n * @example Range partitioning by date (monthly)\n * {\n * enabled: true,\n * strategy: 'range',\n * key: 'created_at',\n * interval: '1 month'\n * }\n */\nexport const PartitioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable table partitioning'),\n strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),\n key: z.string().describe('Field name to partition by'),\n interval: z.string().optional().describe('Partition interval for range strategy (e.g., \"1 month\", \"1 year\")'),\n}).refine((data) => {\n // If strategy is 'range', interval must be provided\n if (data.strategy === 'range' && !data.interval) {\n return false;\n }\n return true;\n}, {\n message: 'interval is required when strategy is \"range\"',\n});\n\n/**\n * Change Data Capture (CDC) Configuration Schema\n * Enables real-time data streaming to external systems\n * \n * @example Stream all changes to Kafka\n * {\n * enabled: true,\n * events: ['insert', 'update', 'delete'],\n * destination: 'kafka://events.objectstack'\n * }\n */\nexport const CDCConfigSchema = z.object({\n enabled: z.boolean().describe('Enable Change Data Capture'),\n events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),\n destination: z.string().describe('Destination endpoint (e.g., \"kafka://topic\", \"webhook://url\")'),\n});\n\n/**\n * Base Object Schema Definition\n * \n * The Blueprint of a Business Object.\n * Represents a table, a collection, or a virtual entity.\n * \n * @example\n * ```yaml\n * name: project_task\n * label: Project Task\n * icon: task\n * fields:\n * project:\n * type: lookup\n * reference: project\n * status:\n * type: select\n * options: [todo, in_progress, done]\n * enable:\n * trackHistory: true\n * files: true\n * ```\n */\nconst ObjectSchemaBase = z.object({\n /** \n * Identity & Metadata \n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),\n label: z.string().optional().describe('Human readable singular label (e.g. \"Account\")'),\n pluralLabel: z.string().optional().describe('Human readable plural label (e.g. \"Accounts\")'),\n description: z.string().optional().describe('Developer documentation / description'),\n icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),\n \n /**\n * Namespace & Domain Classification\n * \n * Groups objects into logical domains for routing, permissions, and discovery.\n * System objects use `'sys'`; business packages use their own namespace.\n * \n * When set, `tableName` is auto-derived as `{namespace}_{name}` by\n * `ObjectSchema.create()` unless an explicit `tableName` is provided.\n * \n * Namespace must be a single lowercase word (no underscores or hyphens)\n * to ensure clean auto-derivation of `{namespace}_{name}` table names.\n * \n * @example namespace: 'sys' → tableName defaults to 'sys_user'\n * @example namespace: 'crm' → tableName defaults to 'crm_account'\n */\n namespace: z.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace — single lowercase word (e.g. \"sys\", \"crm\"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'),\n\n /**\n * Taxonomy & Organization\n */\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g. \"sales\", \"system\", \"reference\")'),\n active: z.boolean().optional().default(true).describe('Is the object active and usable'),\n isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),\n abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),\n\n /** \n * Storage & Virtualization \n */\n datasource: z.string().optional().default('default').describe('Target Datasource ID. \"default\" is the primary DB.'),\n tableName: z.string().optional().describe('Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set.'),\n \n /** \n * Data Model \n */\n fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {\n message: 'Field names must be lowercase snake_case (e.g., \"first_name\", \"company\", \"annual_revenue\")',\n }), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),\n indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),\n \n /**\n * Advanced Data Management\n */\n \n // Multi-tenancy configuration\n tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),\n \n // Soft delete configuration\n softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),\n \n // Versioning configuration\n versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),\n \n // Partitioning strategy\n partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),\n \n // Change Data Capture\n cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),\n \n /**\n * Logic & Validation (Co-located)\n * Best Practice: Define rules close to data.\n */\n validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),\n \n /**\n * State Machine(s)\n * Named record of state machines, where each key is a unique machine identifier.\n * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).\n * \n * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }\n */\n stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),\n\n /** \n * Display & UI Hints (Data-Layer)\n */\n displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., \"name\", \"title\"). Defaults to \"name\" if present.'),\n recordName: z.object({\n type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),\n displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., \"CASE-{0000}\", \"INV-{YYYY}-{0000}\")'),\n startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),\n }).optional().describe('Record name generation configuration (Salesforce pattern)'),\n titleFormat: z.string().optional().describe('Title expression (e.g. \"{name} - {code}\"). Overrides displayNameField.'),\n compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),\n \n /** \n * Search Engine Config \n */\n search: SearchConfigSchema.optional().describe('Search engine configuration'),\n \n /** \n * System Capabilities \n */\n enable: ObjectCapabilities.optional().describe('Enabled system features modules'),\n\n /** Record Types */\n recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),\n\n /** Sharing Model */\n sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),\n\n /** Key Prefix */\n keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., \"001\" for Account)'),\n\n /**\n * Object Actions\n * \n * Actions associated with this object. Populated automatically by `defineStack()`\n * when top-level actions specify `objectName` matching this object.\n * Can also be defined directly on the object.\n * \n * Aligns with Salesforce/ServiceNow patterns where actions are part of the\n * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)\n * include the action list without requiring downstream merge.\n */\n actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),\n});\n\n/**\n * Converts a snake_case name to a human-readable Title Case label.\n * @example snakeCaseToLabel('project_task') → 'Project Task'\n */\nfunction snakeCaseToLabel(name: string): string {\n return name\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n}\n\n/**\n * Enhanced ObjectSchema with Factory\n */\nexport const ObjectSchema = Object.assign(ObjectSchemaBase, {\n /**\n * Type-safe factory for creating business object definitions.\n * \n * Enhancements over raw schema:\n * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).\n * - **Validation**: Runs Zod `.parse()` to validate the config at creation time.\n * \n * @example\n * ```ts\n * const Task = ObjectSchema.create({\n * name: 'project_task',\n * // label auto-generated as 'Project Task'\n * fields: {\n * subject: { type: 'text', label: 'Subject', required: true },\n * },\n * });\n * ```\n */\n create: >(config: T): Omit & Pick => {\n const withDefaults = {\n ...config,\n label: config.label ?? snakeCaseToLabel(config.name),\n // Auto-derive tableName as {namespace}_{name} when namespace is set\n tableName: config.tableName ?? (config.namespace ? `${config.namespace}_${config.name}` : undefined),\n };\n return ObjectSchemaBase.parse(withDefaults) as Omit & Pick;\n },\n});\n\nexport type ServiceObject = z.infer;\nexport type ServiceObjectInput = z.input;\nexport type ObjectCapabilities = z.infer;\nexport type ObjectIndex = z.infer;\nexport type TenancyConfig = z.infer;\nexport type SoftDeleteConfig = z.infer;\nexport type VersioningConfig = z.infer;\nexport type PartitioningConfig = z.infer;\nexport type CDCConfig = z.infer;\n\n// =================================================================\n// Object Ownership Model\n// =================================================================\n\n/**\n * How a package relates to an object it references.\n * \n * - `own`: This package is the original author/owner of the object.\n * Only one package may own a given object name. The owner defines\n * the base schema (table name, primary key, core fields).\n * \n * - `extend`: This package adds fields, views, or actions to an\n * existing object owned by another package. Multiple packages\n * may extend the same object. Extensions are merged at boot time.\n * \n * Follows Salesforce/ServiceNow patterns:\n * object name = database table name, globally unique, no namespace prefix.\n */\nexport const ObjectOwnershipEnum = z.enum(['own', 'extend']);\nexport type ObjectOwnership = z.infer;\n\n/**\n * Object Extension Entry — used in `objectExtensions` array.\n * Declares fields/config to merge into an existing object owned by another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact', // target object FQN\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\nexport const ObjectExtensionSchema = z.object({\n /** The target object name (FQN) to extend */\n extend: z.string().describe('Target object name (FQN) to extend'),\n \n /** Fields to merge into the target object (additive) */\n fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),\n \n /** Override label */\n label: z.string().optional().describe('Override label for the extended object'),\n \n /** Override plural label */\n pluralLabel: z.string().optional().describe('Override plural label for the extended object'),\n \n /** Override description */\n description: z.string().optional().describe('Override description for the extended object'),\n \n /** Additional validation rules to add */\n validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),\n \n /** Additional indexes to add */\n indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),\n \n /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */\n priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),\n});\n\nexport type ObjectExtension = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Hook Lifecycle Events\n * Defines the interception points in the ObjectQL execution pipeline.\n */\nexport const HookEvent = z.enum([\n // Read Operations\n 'beforeFind', 'afterFind',\n 'beforeFindOne', 'afterFindOne',\n 'beforeCount', 'afterCount',\n 'beforeAggregate', 'afterAggregate',\n\n // Write Operations\n 'beforeInsert', 'afterInsert',\n 'beforeUpdate', 'afterUpdate',\n 'beforeDelete', 'afterDelete',\n \n // Bulk Operations (Query-based)\n 'beforeUpdateMany', 'afterUpdateMany',\n 'beforeDeleteMany', 'afterDeleteMany',\n]);\n\n/**\n * Hook Definition Schema\n * \n * Hooks serve as the \"Logic Layer\" in ObjectStack, allowing developers to \n * inject custom code during the data access lifecycle.\n * \n * Use cases:\n * - Data Enrichment (Default values, Calculated fields)\n * - Validation (Complex business rules)\n * - Side Effects (Sending emails, Syncing to external systems)\n * - Security (Filtering data based on context)\n */\nexport const HookSchema = z.object({\n /**\n * Unique identifier for the hook\n * Required for debugging and overriding.\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Hook unique name (snake_case)'),\n\n /**\n * Human readable label\n */\n label: z.string().optional().describe('Description of what this hook does'),\n\n /**\n * Target Object(s)\n * can be:\n * - Single object: \"account\"\n * - List of objects: [\"account\", \"contact\"]\n * - Wildcard: \"*\" (All objects)\n */\n object: z.union([z.string(), z.array(z.string())]).describe('Target object(s)'),\n\n /**\n * Events to subscribe to\n * Combinations of timing (before/after) and action (find/insert/update/delete/etc)\n */\n events: z.array(HookEvent).describe('Lifecycle events'),\n\n /**\n * Handler Logic\n * Reference to a registered function in the plugin system OR a direct function (runtime only).\n */\n handler: z.union([z.string(), z.function()]).optional().describe('Handler function name (string) or inline function reference'),\n\n /**\n * Execution Order\n * Lower numbers run first.\n * - System Hooks: 0-99\n * - App Hooks: 100-999\n * - User Hooks: 1000+\n */\n priority: z.number().default(100).describe('Execution priority'),\n\n /**\n * Async / Background Execution\n * If true, the hook runs in the background and does not block the transaction.\n * Only applicable for 'after*' events.\n * Default: false (Blocking)\n */\n async: z.boolean().default(false).describe('Run specifically as fire-and-forget'),\n\n /**\n * Declarative Condition\n * Formula expression evaluated before the handler runs.\n * If provided and evaluates to FALSE, the hook is skipped entirely.\n * Useful for filtering by record data without writing handler code.\n * \n * @example \"status = 'active' AND amount > 1000\"\n */\n condition: z.string().optional().describe('Formula expression; hook runs only when TRUE (e.g., \"status = \\'closed\\' AND amount > 1000\")'),\n\n /**\n * Human-readable description\n */\n description: z.string().optional().describe('Human-readable description of what this hook does'),\n\n /**\n * Retry Policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().default(3).describe('Maximum retry attempts on failure'),\n backoffMs: z.number().default(1000).describe('Backoff delay between retries in milliseconds'),\n }).optional().describe('Retry policy for failed hook executions'),\n\n /**\n * Execution Timeout\n */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds before the hook is aborted'),\n\n /**\n * Error Policy\n * What to do if the hook throws an exception?\n * - abort: Rollback transaction (if blocking)\n * - log: Log error and continue\n */\n onError: z.enum(['abort', 'log']).default('abort').describe('Error handling strategy'),\n});\n\n/**\n * Hook Runtime Context\n * Defines what is available to the hook handler during execution.\n * \n * Best Practices:\n * - **Immutability**: `object`, `event`, `id` are immutable.\n * - **Mutability**: `input` and `result` are mutable to allow transformation.\n * - **Encapsulation**: `session` isolates auth info; `transaction` ensures atomicity.\n */\nexport const HookContextSchema = z.object({\n /** Tracing ID */\n id: z.string().optional().describe('Unique execution ID for tracing'),\n\n /** Target Object Name */\n object: z.string(),\n \n /** Current Lifecycle Event */\n event: HookEvent,\n\n /** \n * Input Parameters (Mutable)\n * Modify this to change the behavior of the operation.\n * \n * - find: { query: QueryAST, options: DriverOptions }\n * - insert: { doc: Record, options: DriverOptions }\n * - update: { id: ID, doc: Record, options: DriverOptions }\n * - delete: { id: ID, options: DriverOptions }\n * - updateMany: { query: QueryAST, doc: Record, options: DriverOptions }\n * - deleteMany: { query: QueryAST, options: DriverOptions }\n */\n input: z.record(z.string(), z.unknown()).describe('Mutable input parameters'),\n\n /** \n * Operation Result (Mutable)\n * Available in 'after*' events. Modify this to transform the output.\n */\n result: z.unknown().optional().describe('Operation result (After hooks only)'),\n\n /**\n * Data Snapshot\n * The state of the record BEFORE the operation (for update/delete).\n */\n previous: z.record(z.string(), z.unknown()).optional().describe('Record state before operation'),\n\n /**\n * Execution Session\n * Contains authentication and tenancy information.\n */\n session: z.object({\n userId: z.string().optional(),\n tenantId: z.string().optional(),\n roles: z.array(z.string()).optional(),\n accessToken: z.string().optional(),\n }).optional().describe('Current session context'),\n \n /**\n * Transaction Handle\n * If the operation is part of a transaction, use this handle for side-effects.\n */\n transaction: z.unknown().optional().describe('Database transaction handle'),\n\n /**\n * Engine Access\n * Reference to the ObjectQL engine for performing side effects.\n */\n ql: z.unknown().describe('ObjectQL Engine Reference'),\n\n /**\n * Cross-Object API\n * Provides a scoped data access interface for performing CRUD operations\n * on other objects within hooks. Bound to the current execution context\n * (userId, tenantId, transaction).\n *\n * Usage in hooks:\n * const users = ctx.api.object('user');\n * const admin = await users.findOne({ filter: { role: 'admin' } });\n */\n api: z.unknown().optional().describe('Cross-object data access (ScopedContext)'),\n\n /**\n * Current User Info\n * Convenience shortcut for session.userId + additional user metadata.\n * Populated by the engine when available.\n */\n user: z.object({\n id: z.string().optional(),\n name: z.string().optional(),\n email: z.string().optional(),\n }).optional().describe('Current user info shortcut'),\n});\n\nexport type Hook = z.input;\nexport type ResolvedHook = z.output;\nexport type HookEventType = z.infer;\nexport type HookContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { QuerySchema } from './query.zod';\n\n/**\n * Transformation Logic\n * Built-in helpers for converting data during import.\n */\nexport const TransformType = z.enum([\n 'none', // Direct copy\n 'constant', // Use a hardcoded value\n 'lookup', // Resolve FK (Name -> ID)\n 'split', // \"John Doe\" -> [\"John\", \"Doe\"]\n 'join', // [\"John\", \"Doe\"] -> \"John Doe\"\n 'javascript', // Custom script (Review security!)\n 'map' // Value mapping (e.g. \"Active\" -> \"active\")\n]);\n\n/**\n * Field Mapping Item\n */\nexport const FieldMappingSchema = z.object({\n /** Source Column */\n source: z.union([z.string(), z.array(z.string())]).describe('Source column header(s)'),\n \n /** Target Field */\n target: z.union([z.string(), z.array(z.string())]).describe('Target object field(s)'),\n \n /** Transformation */\n transform: TransformType.default('none'),\n \n /** Configuration for transform */\n params: z.object({\n // Constant\n value: z.unknown().optional(),\n \n // Lookup\n object: z.string().optional(), // Lookup Object\n fromField: z.string().optional(), // Match on (e.g. \"name\")\n toField: z.string().optional(), // Value to take (e.g. \"id\")\n autoCreate: z.boolean().optional(), // Create if missing\n \n // Map\n valueMap: z.record(z.string(), z.unknown()).optional(), // { \"Open\": \"draft\" }\n \n // Split/Join\n separator: z.string().optional()\n }).optional()\n});\n\n/**\n * Data Mapping Schema\n * Defines a reusable data mapping configuration for ETL operations.\n * \n * **NAMING CONVENTION:**\n * Mapping names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good mapping names\n * - 'salesforce_to_crm'\n * - 'csv_import_contacts'\n * - 'api_sync_orders'\n * \n * @example Bad mapping names (will be rejected)\n * - 'SalesforceToCRM' (PascalCase)\n * - 'CSV Import' (spaces)\n */\nexport const MappingSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Mapping unique name (lowercase snake_case)'),\n label: z.string().optional(),\n \n /** Scope */\n sourceFormat: z.enum(['csv', 'json', 'xml', 'sql']).default('csv'),\n targetObject: z.string().describe('Target Object Name'),\n \n /** Column Mappings */\n fieldMapping: z.array(FieldMappingSchema),\n \n /** Upsert Logic */\n mode: z.enum(['insert', 'update', 'upsert']).default('insert'),\n upsertKey: z.array(z.string()).optional().describe('Fields to match for upsert (e.g. email)'),\n \n /** Extract Logic (For Export) */\n extractQuery: QuerySchema.optional().describe('Query to run for export only'),\n \n /** Error Handling */\n errorPolicy: z.enum(['skip', 'abort', 'retry']).default('skip'),\n batchSize: z.number().default(1000)\n});\n\nexport type Mapping = z.infer;\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Execution Context Schema\n * \n * Defines the runtime context that flows from HTTP request → data operations.\n * This is the \"identity + environment\" envelope that every data operation can carry.\n * \n * Design:\n * - All fields are optional for backward compatibility\n * - `isSystem` bypasses permission checks (for internal/migration operations)\n * - `transaction` carries the database transaction handle for atomicity\n * - `traceId` enables distributed tracing across microservices\n * \n * Usage:\n * engine.find('account', { context: { userId: '...', tenantId: '...' } })\n */\nexport const ExecutionContextSchema = z.object({\n /** Current user ID (resolved from session) */\n userId: z.string().optional(),\n \n /** Current organization/tenant ID (resolved from session.activeOrganizationId) */\n tenantId: z.string().optional(),\n \n /** User role names (resolved from Member + Role) */\n roles: z.array(z.string()).default([]),\n \n /** Aggregated permission names (resolved from PermissionSet) */\n permissions: z.array(z.string()).default([]),\n \n /** Whether this is a system-level operation (bypasses permission checks) */\n isSystem: z.boolean().default(false),\n \n /** Raw access token (for external API call pass-through) */\n accessToken: z.string().optional(),\n \n /** Database transaction handle */\n transaction: z.unknown().optional(),\n \n /** Request trace ID (for distributed tracing) */\n traceId: z.string().optional(),\n});\n\nexport type ExecutionContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\nimport { SortNodeSchema, QuerySchema, FullTextSearchSchema, FieldNodeSchema, AggregationNodeSchema } from './query.zod';\nimport { ExecutionContextSchema } from '../kernel/execution-context.zod';\n\n/**\n * Data Engine Protocol\n * \n * Defines the standard interface for data persistence engines in ObjectStack.\n * This protocol abstracts the underlying storage mechanism (SQL, NoSQL, API, Memory),\n * allowing the ObjectQL engine to execute standardized CRUD and Aggregation operations\n * regardless of where the data resides.\n * \n * The Data Engine acts as the \"Driver\" layer in the Hexagonal Architecture.\n */\n\n// ==========================================================================\n// 1. Shared Definitions\n// ==========================================================================\n\n/**\n * Data Engine Query filter conditions\n * Supports simple key-value map or complex Logic/Field expressions (DSL)\n */\nexport const DataEngineFilterSchema = z.union([\n z.record(z.string(), z.unknown()),\n FilterConditionSchema\n]).describe('Data Engine query filter conditions');\n\n/**\n * Sort order definition\n * Supports:\n * - { name: 'asc' }\n * - { name: 1 }\n * - [{ field: 'name', order: 'asc' }]\n */\nexport const DataEngineSortSchema = z.union([\n z.record(z.string(), z.enum(['asc', 'desc'])), \n z.record(z.string(), z.union([z.literal(1), z.literal(-1)])),\n z.array(SortNodeSchema)\n]).describe('Sort order definition');\n\n// ==========================================================================\n// 1b. Base Engine Options (shared context)\n// ==========================================================================\n\n/**\n * Base Engine Options\n * \n * All Data Engine operation options extend this schema to carry\n * an optional ExecutionContext for identity, tenant, and transaction propagation.\n */\nexport const BaseEngineOptionsSchema = z.object({\n /** Execution context (identity, tenant, transaction) */\n context: ExecutionContextSchema.optional(),\n});\n\n// ==========================================================================\n// 2. method: FIND (QueryAST-aligned)\n// ==========================================================================\n\n/**\n * Engine Query Options — QueryAST-aligned parameters for IDataEngine.find/findOne.\n * \n * Uses standard QueryAST field names (where/fields/orderBy/limit/offset/expand)\n * so that no mechanical translation is needed between the Engine and Driver layers.\n * \n * @example\n * ```ts\n * engine.find('account', {\n * where: { status: 'active' },\n * fields: ['id', 'name', 'email'],\n * orderBy: [{ field: 'name', order: 'asc' }],\n * limit: 10,\n * offset: 20,\n * expand: { owner: { object: 'user', fields: ['name'] } },\n * });\n * ```\n */\nexport const EngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions (WHERE) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n\n /** Fields to retrieve (SELECT) — standard QueryAST `fields` */\n fields: z.array(FieldNodeSchema).optional(),\n\n /** Sorting instructions (ORDER BY) — standard QueryAST `orderBy` */\n orderBy: z.array(SortNodeSchema).optional(),\n\n /** Max records to return (LIMIT) */\n limit: z.number().optional(),\n\n /** Records to skip (OFFSET) — standard QueryAST `offset` */\n offset: z.number().optional(),\n\n /** Alias for limit (OData compatibility) */\n top: z.number().optional(),\n\n /** Cursor for keyset pagination */\n cursor: z.record(z.string(), z.unknown()).optional(),\n\n /** Full-text search configuration */\n search: FullTextSearchSchema.optional(),\n\n /**\n * Recursive relation loading map (expand).\n * \n * Keys are lookup/master_detail field names; values are nested QueryAST\n * objects that control select, filter, sort, and further expansion on\n * the related object. The engine resolves expand via batch $in queries\n * (driver-agnostic) with a default max depth of 3.\n */\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional(),\n\n /** SELECT DISTINCT flag */\n distinct: z.boolean().optional(),\n}).describe('QueryAST-aligned query options for IDataEngine.find() operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineQueryOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineQueryOptionsSchema` instead.\n * This schema uses legacy parameter names (filter/select/sort/skip/populate)\n * that require mechanical translation to QueryAST. Migrate to the\n * QueryAST-aligned `EngineQueryOptionsSchema` (where/fields/orderBy/offset/expand).\n */\nexport const DataEngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineQueryOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n /** @deprecated Use `fields` (EngineQueryOptionsSchema) */\n select: z.array(z.string()).optional(),\n /** @deprecated Use `orderBy` (EngineQueryOptionsSchema) */\n sort: DataEngineSortSchema.optional(),\n limit: z.number().int().min(1).optional(),\n /** @deprecated Use `offset` (EngineQueryOptionsSchema) */\n skip: z.number().int().min(0).optional(),\n top: z.number().int().min(1).optional(),\n /** @deprecated Use `expand` (EngineQueryOptionsSchema) */\n populate: z.array(z.string()).optional(),\n}).describe('Query options for IDataEngine.find() operations');\n\n// ==========================================================================\n// 3. method: INSERT\n// ==========================================================================\n\nexport const DataEngineInsertOptionsSchema = BaseEngineOptionsSchema.extend({\n /** \n * Return the inserted record(s)? \n * Some drivers support RETURNING clause for efficiency.\n * Default: true\n */\n returning: z.boolean().default(true).optional(),\n}).describe('Options for DataEngine.insert operations');\n\n// ==========================================================================\n// 4. method: UPDATE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions to identify records to update — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Perform an upsert? If true, insert if not found. */\n upsert: z.boolean().default(false).optional(),\n /** Update multiple records? If false, only the first match is updated. Default: false */\n multi: z.boolean().default(false).optional(),\n /** Return the updated record(s)? Default: false (returns update count/status) */\n returning: z.boolean().default(false).optional(),\n}).describe('QueryAST-aligned options for DataEngine.update operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineUpdateOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineUpdateOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineUpdateOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n upsert: z.boolean().default(false).optional(),\n multi: z.boolean().default(false).optional(),\n returning: z.boolean().default(false).optional(),\n}).describe('Options for DataEngine.update operations');\n\n// ==========================================================================\n// 5. method: DELETE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions to identify records to delete — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Delete multiple records? If false, only the first match is deleted. Default: false */\n multi: z.boolean().default(false).optional(),\n}).describe('QueryAST-aligned options for DataEngine.delete operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineDeleteOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineDeleteOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineDeleteOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n multi: z.boolean().default(false).optional(),\n}).describe('Options for DataEngine.delete operations');\n\n// ==========================================================================\n// 6. method: AGGREGATE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions (WHERE) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Group By fields */\n groupBy: z.array(z.string()).optional(),\n /** \n * Aggregation definitions — uses standard AggregationNodeSchema (`function` key).\n * e.g. [{ function: 'sum', field: 'amount', alias: 'total' }]\n */\n aggregations: z.array(AggregationNodeSchema).optional(),\n}).describe('QueryAST-aligned options for DataEngine.aggregate operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineAggregateOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineAggregateOptionsSchema` instead.\n * Migrate `filter` → `where`, aggregation `method` → `function`.\n */\nexport const DataEngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineAggregateOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n groupBy: z.array(z.string()).optional(),\n /** \n * @deprecated Use `EngineAggregateOptionsSchema` with standard AggregationNodeSchema (`function` key).\n */\n aggregations: z.array(z.object({\n field: z.string(),\n method: z.enum(['count', 'sum', 'avg', 'min', 'max', 'count_distinct']),\n alias: z.string().optional()\n })).optional(),\n}).describe('Options for DataEngine.aggregate operations');\n\n// ==========================================================================\n// 7. method: COUNT (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineCountOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n}).describe('QueryAST-aligned options for DataEngine.count operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineCountOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineCountOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineCountOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineCountOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n}).describe('Options for DataEngine.count operations');\n\n// ==========================================================================\n// 8. Definition (Contract)\n// ==========================================================================\n\nexport const DataEngineContractSchema = z.object({\n find: z.function()\n .input(z.tuple([z.string(), EngineQueryOptionsSchema.optional()]))\n .output(z.promise(z.array(z.unknown()))),\n \n findOne: z.function()\n .input(z.tuple([z.string(), EngineQueryOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n insert: z.function()\n .input(z.tuple([z.string(), z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]), DataEngineInsertOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n update: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), EngineUpdateOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n delete: z.function()\n .input(z.tuple([z.string(), EngineDeleteOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n count: z.function()\n .input(z.tuple([z.string(), EngineCountOptionsSchema.optional()]))\n .output(z.promise(z.number())),\n \n aggregate: z.function()\n .input(z.tuple([z.string(), EngineAggregateOptionsSchema]))\n .output(z.promise(z.array(z.unknown())))\n}).describe('Standard Data Engine Contract');\n\n// ==========================================================================\n// 9. Virtualization & RPC Protocol\n// ==========================================================================\n\n/**\n * Data Engine RPC Request (Virtual ObjectQL)\n * \n * This schema defines the serialized format for executing Data Engine operations\n * via HTTP, Message Queue, or Plugin boundaries.\n * \n * It enables \"Virtual Data Engines\" where the implementation resides in a \n * separate microservice or plugin.\n */\n\n/**\n * RPC backward-compatibility mixin — shared `@deprecated filter` field.\n * When both `filter` and `where` are present, the protocol/engine ignores\n * `filter` in favor of `where`; only one should be provided.\n */\nconst RpcLegacyFilterMixin = {\n /** @deprecated Use `where` */\n filter: DataEngineFilterSchema.optional(),\n};\n\n/**\n * RPC query options that accept BOTH new (where/fields/orderBy) and\n * legacy (filter/select/sort/skip/populate) parameter names.\n * \n * **Precedence:** When both legacy and new keys are present for the same\n * concern, the protocol normalizer uses the new key (`where` > `filter`,\n * `fields` > `select`, `orderBy` > `sort`, `offset` > `skip`,\n * `expand` > `populate`). Callers should not mix vocabularies.\n */\nconst RpcQueryOptionsSchema = EngineQueryOptionsSchema.extend({\n ...RpcLegacyFilterMixin,\n /** @deprecated Use `fields` */\n select: z.array(z.string()).optional(),\n /** @deprecated Use `orderBy` */\n sort: DataEngineSortSchema.optional(),\n /** @deprecated Use `offset` */\n skip: z.number().int().min(0).optional(),\n /** @deprecated Use `expand` */\n populate: z.array(z.string()).optional(),\n});\n\nexport const DataEngineFindRequestSchema = z.object({\n method: z.literal('find'),\n object: z.string(),\n query: RpcQueryOptionsSchema.optional()\n});\n\nexport const DataEngineFindOneRequestSchema = z.object({\n method: z.literal('findOne'),\n object: z.string(),\n query: RpcQueryOptionsSchema.optional()\n});\n\nexport const DataEngineInsertRequestSchema = z.object({\n method: z.literal('insert'),\n object: z.string(),\n data: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]),\n options: DataEngineInsertOptionsSchema.optional()\n});\n\nexport const DataEngineUpdateRequestSchema = z.object({\n method: z.literal('update'),\n object: z.string(),\n data: z.record(z.string(), z.unknown()),\n id: z.union([z.string(), z.number()]).optional().describe('ID for single update, or use where in options'),\n options: EngineUpdateOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineDeleteRequestSchema = z.object({\n method: z.literal('delete'),\n object: z.string(),\n id: z.union([z.string(), z.number()]).optional().describe('ID for single delete, or use where in options'),\n options: EngineDeleteOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineCountRequestSchema = z.object({\n method: z.literal('count'),\n object: z.string(),\n query: EngineCountOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineAggregateRequestSchema = z.object({\n method: z.literal('aggregate'),\n object: z.string(),\n query: EngineAggregateOptionsSchema.extend(RpcLegacyFilterMixin)\n});\n\n/**\n * Data Engine Execute Request (Raw Command)\n * Execute a raw command/query native to the driver (e.g. SQL, Shell, Remote API).\n */\nexport const DataEngineExecuteRequestSchema = z.object({\n method: z.literal('execute'),\n /** The abstract command (string SQL, or JSON object) */\n command: z.unknown(),\n /** Optional options */\n options: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Data Engine Vector Find Request (AI/RAG)\n * Perform a similarity search using vector embeddings.\n */\nexport const DataEngineVectorFindRequestSchema = z.object({\n method: z.literal('vectorFind'),\n object: z.string(),\n /** The vector embedding to search for */\n vector: z.array(z.number()),\n /** Optional pre-filter (Metadata filtering) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Fields to retrieve — standard QueryAST `fields` */\n fields: z.array(z.string()).optional(),\n /** Number of results */\n limit: z.number().int().default(5).optional(),\n /** Minimum similarity score (0-1) or distance threshold */\n threshold: z.number().optional()\n});\n\n/**\n * Data Engine Batch Request\n * Execute multiple operations in a single transaction/request efficiently.\n */\nexport const DataEngineBatchRequestSchema = z.object({\n method: z.literal('batch'),\n requests: z.array(z.discriminatedUnion('method', [\n DataEngineFindRequestSchema,\n DataEngineFindOneRequestSchema,\n DataEngineInsertRequestSchema,\n DataEngineUpdateRequestSchema,\n DataEngineDeleteRequestSchema,\n DataEngineCountRequestSchema,\n DataEngineAggregateRequestSchema,\n DataEngineExecuteRequestSchema,\n DataEngineVectorFindRequestSchema\n ])),\n /** \n * Transaction Mode\n * - true: All or nothing (Atomic)\n * - false: Best effort, continue on error\n */\n transaction: z.boolean().default(true).optional()\n});\n\n/**\n * Unified Data Engine Request Union\n * Use this to validate any incoming \"Virtual ObjectQL\" request.\n */\nexport const DataEngineRequestSchema = z.discriminatedUnion('method', [\n DataEngineFindRequestSchema,\n DataEngineFindOneRequestSchema,\n DataEngineInsertRequestSchema,\n DataEngineUpdateRequestSchema,\n DataEngineDeleteRequestSchema,\n DataEngineCountRequestSchema,\n DataEngineAggregateRequestSchema,\n DataEngineBatchRequestSchema,\n DataEngineExecuteRequestSchema,\n DataEngineVectorFindRequestSchema\n]).describe('Virtual ObjectQL Request Protocol');\n\n// ==========================================================================\n// 10. Type Exports\n// ==========================================================================\n\n// --- New: QueryAST-aligned types (preferred) ---\nexport type EngineQueryOptions = z.infer;\nexport type EngineUpdateOptions = z.infer;\nexport type EngineDeleteOptions = z.infer;\nexport type EngineAggregateOptions = z.infer;\nexport type EngineCountOptions = z.infer;\n\n// --- Legacy: deprecated types (kept for backward compatibility) ---\nexport type DataEngineFilter = z.infer;\n/** @deprecated Use standard `SortNode[]` from QueryAST instead. */\nexport type DataEngineSort = z.infer;\nexport type BaseEngineOptions = z.infer;\n/** @deprecated Use `EngineQueryOptions` instead. */\nexport type DataEngineQueryOptions = z.infer;\nexport type DataEngineInsertOptions = z.infer;\n/** @deprecated Use `EngineUpdateOptions` instead. */\nexport type DataEngineUpdateOptions = z.infer;\n/** @deprecated Use `EngineDeleteOptions` instead. */\nexport type DataEngineDeleteOptions = z.infer;\n/** @deprecated Use `EngineAggregateOptions` instead. */\nexport type DataEngineAggregateOptions = z.infer;\n/** @deprecated Use `EngineCountOptions` instead. */\nexport type DataEngineCountOptions = z.infer;\nexport type DataEngineRequest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Shared Enumerations\n// ============================================================================\n\n/** Aggregation functions used across query, data-engine, analytics, field */\nexport const AggregationFunctionEnum = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'percentile', 'median', 'stddev', 'variance',\n]).describe('Standard aggregation functions');\nexport type AggregationFunction = z.infer;\n\n/** Sort direction used across query, data-engine, analytics */\nexport const SortDirectionEnum = z.enum(['asc', 'desc'])\n .describe('Sort order direction');\nexport type SortDirection = z.infer;\n\n/** Reusable sort item — field + direction pair used across views, data sources, filters */\nexport const SortItemSchema = z.object({\n field: z.string().describe('Field name to sort by'),\n order: SortDirectionEnum.describe('Sort direction'),\n}).describe('Sort field and direction pair');\nexport type SortItem = z.infer;\n\n/** CRUD mutation events used across hook, validation, object CDC */\nexport const MutationEventEnum = z.enum([\n 'insert', 'update', 'delete', 'upsert',\n]).describe('Data mutation event types');\nexport type MutationEvent = z.infer;\n\n/** Database isolation levels — unified format */\nexport const IsolationLevelEnum = z.enum([\n 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable', 'snapshot',\n]).describe('Transaction isolation levels (snake_case standard)');\nexport type IsolationLevel = z.infer;\n\n/** Cache eviction strategies */\nexport const CacheStrategyEnum = z.enum(['lru', 'lfu', 'ttl', 'fifo'])\n .describe('Cache eviction strategy');\nexport type CacheStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { QuerySchema } from '../data/query.zod';\nimport { IsolationLevelEnum } from '../shared/enums.zod';\n\n/**\n * Common Driver Options\n * Passed to most driver methods to control behavior (transactions, timeouts, etc.)\n */\nexport const DriverOptionsSchema = z.object({\n /**\n * Transaction handle/identifier.\n * If provided, the operation must run within this transaction.\n */\n transaction: z.unknown().optional().describe('Transaction handle'),\n\n /**\n * Operation timeout in milliseconds.\n */\n timeout: z.number().optional().describe('Timeout in ms'),\n\n /**\n * Whether to bypass cache and force a fresh read.\n */\n skipCache: z.boolean().optional().describe('Bypass cache'),\n\n /**\n * Distributed Tracing Context.\n * Used for passing OpenTelemetry span context or request IDs for observability.\n */\n traceContext: z.record(z.string(), z.string()).optional().describe('OpenTelemetry context or request ID'),\n\n /**\n * Tenant Identifier.\n * For multi-tenant databases (row-level security or schema-per-tenant).\n */\n tenantId: z.string().optional().describe('Tenant Isolation identifier'),\n});\n\n/**\n * Driver Capabilities Schema\n * \n * Defines what features a database driver supports.\n * This allows ObjectQL to adapt its behavior based on underlying database capabilities.\n * Enhanced with granular capability flags for better feature detection.\n */\nexport const DriverCapabilitiesSchema = z.object({\n // ============================================================================\n // Basic CRUD Operations\n // ============================================================================\n \n /**\n * Whether the driver supports create operations.\n */\n create: z.boolean().default(true).describe('Supports CREATE operations'),\n \n /**\n * Whether the driver supports read operations.\n */\n read: z.boolean().default(true).describe('Supports READ operations'),\n \n /**\n * Whether the driver supports update operations.\n */\n update: z.boolean().default(true).describe('Supports UPDATE operations'),\n \n /**\n * Whether the driver supports delete operations.\n */\n delete: z.boolean().default(true).describe('Supports DELETE operations'),\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n \n /**\n * Whether the driver supports bulk create operations.\n */\n bulkCreate: z.boolean().default(false).describe('Supports bulk CREATE operations'),\n \n /**\n * Whether the driver supports bulk update operations.\n */\n bulkUpdate: z.boolean().default(false).describe('Supports bulk UPDATE operations'),\n \n /**\n * Whether the driver supports bulk delete operations.\n */\n bulkDelete: z.boolean().default(false).describe('Supports bulk DELETE operations'),\n\n // ============================================================================\n // Transaction & Connection Management\n // ============================================================================\n \n /**\n * Whether the driver supports database transactions.\n * If true, beginTransaction, commit, and rollback must be implemented.\n */\n transactions: z.boolean().default(false).describe('Supports ACID transactions'),\n \n /**\n * Whether the driver supports savepoints within transactions.\n */\n savepoints: z.boolean().default(false).describe('Supports transaction savepoints'),\n \n /**\n * Supported transaction isolation levels.\n */\n isolationLevels: z.array(IsolationLevelEnum).optional().describe('Supported isolation levels'),\n\n // ============================================================================\n // Query Operations\n // ============================================================================\n \n /**\n * Whether the driver supports WHERE clause filters.\n * If false, ObjectQL will fetch all records and filter in memory.\n * \n * Example: Memory driver might not support complex filter conditions.\n */\n queryFilters: z.boolean().default(true).describe('Supports WHERE clause filtering'),\n\n /**\n * Whether the driver supports aggregation functions (COUNT, SUM, AVG, etc.).\n * If false, ObjectQL will compute aggregations in memory.\n */\n queryAggregations: z.boolean().default(false).describe('Supports GROUP BY and aggregation functions'),\n\n /**\n * Whether the driver supports ORDER BY sorting.\n * If false, ObjectQL will sort results in memory.\n */\n querySorting: z.boolean().default(true).describe('Supports ORDER BY sorting'),\n\n /**\n * Whether the driver supports LIMIT/OFFSET pagination.\n * If false, ObjectQL will fetch all records and paginate in memory.\n */\n queryPagination: z.boolean().default(true).describe('Supports LIMIT/OFFSET pagination'),\n\n /**\n * Whether the driver supports window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.).\n * If false, ObjectQL will compute window functions in memory.\n */\n queryWindowFunctions: z.boolean().default(false).describe('Supports window functions with OVER clause'),\n\n /**\n * Whether the driver supports subqueries (nested SELECT statements).\n * If false, ObjectQL will execute queries separately and combine results.\n */\n querySubqueries: z.boolean().default(false).describe('Supports subqueries'),\n \n /**\n * Whether the driver supports Common Table Expressions (WITH clause).\n */\n queryCTE: z.boolean().default(false).describe('Supports Common Table Expressions (WITH clause)'),\n\n /**\n * Whether the driver supports SQL-style joins.\n * If false, ObjectQL will fetch related data separately and join in memory.\n */\n joins: z.boolean().default(false).describe('Supports SQL joins'),\n\n // ============================================================================\n // Advanced Features\n // ============================================================================\n \n /**\n * Whether the driver supports full-text search.\n * If true, text search queries can be pushed to the database.\n */\n fullTextSearch: z.boolean().default(false).describe('Supports full-text search'),\n \n /**\n * Whether the driver supports JSON querying capabilities.\n */\n jsonQuery: z.boolean().default(false).describe('Supports JSON field querying'),\n \n /**\n * Whether the driver supports geospatial queries.\n */\n geospatialQuery: z.boolean().default(false).describe('Supports geospatial queries'),\n \n /**\n * Whether the driver supports streaming large result sets.\n */\n streaming: z.boolean().default(false).describe('Supports result streaming (cursors/iterators)'),\n\n /**\n * Whether the driver supports JSON field types.\n * If false, JSON data will be serialized as strings.\n */\n jsonFields: z.boolean().default(false).describe('Supports JSON field types'),\n\n /**\n * Whether the driver supports array field types.\n * If false, arrays will be stored as JSON strings or in separate tables.\n */\n arrayFields: z.boolean().default(false).describe('Supports array field types'),\n\n /**\n * Whether the driver supports vector embeddings and similarity search.\n * Required for RAG (Retrieval-Augmented Generation) and AI features.\n */\n vectorSearch: z.boolean().default(false).describe('Supports vector embeddings and similarity search'),\n\n // ============================================================================\n // Schema Management\n // ============================================================================\n \n /**\n * Whether the driver supports automatic schema synchronization.\n */\n schemaSync: z.boolean().default(false).describe('Supports automatic schema synchronization'),\n\n /**\n * Whether the driver supports batching multiple schema sync operations\n * into a single (or fewer) round-trips for the DDL phase. When true,\n * the engine may call `syncSchemasBatch()` instead of calling\n * `syncSchema()` per object, reducing network round-trips for remote drivers.\n */\n batchSchemaSync: z.boolean().default(false).describe('Supports batched schema sync to reduce schema DDL round-trips'),\n \n /**\n * Whether the driver supports database migrations.\n */\n migrations: z.boolean().default(false).describe('Supports database migrations'),\n \n /**\n * Whether the driver supports index management.\n */\n indexes: z.boolean().default(false).describe('Supports index creation and management'),\n\n // ============================================================================\n // Performance & Optimization\n // ============================================================================\n \n /**\n * Whether the driver supports connection pooling.\n */\n connectionPooling: z.boolean().default(false).describe('Supports connection pooling'),\n \n /**\n * Whether the driver supports prepared statements.\n */\n preparedStatements: z.boolean().default(false).describe('Supports prepared statements (SQL injection prevention)'),\n \n /**\n * Whether the driver supports query result caching.\n */\n queryCache: z.boolean().default(false).describe('Supports query result caching'),\n});\n\n/**\n * Unified Database Driver Interface\n * \n * This is the contract that all storage adapters (Postgres, Mongo, Excel, Salesforce) must implement.\n * It abstracts the underlying engine, enabling ObjectStack to be \"Database Agnostic\".\n */\nexport const DriverInterfaceSchema = z.object({\n /**\n * Driver name (e.g., 'postgresql', 'mongodb', 'rest_api').\n */\n name: z.string().describe('Driver unique name'),\n\n /**\n * Driver version.\n */\n version: z.string().describe('Driver version'),\n\n /**\n * Capabilities descriptor.\n */\n supports: DriverCapabilitiesSchema,\n\n // ============================================================================\n // Lifecycle Management\n // ============================================================================\n\n /**\n * Initialize connection pool or authenticate.\n */\n connect: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.void()))\n .describe('Establish connection'),\n\n /**\n * Close connections and cleanup resources.\n */\n disconnect: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.void()))\n .describe('Close connection'),\n\n /**\n * Check connection health.\n * @returns true if healthy, false otherwise.\n */\n checkHealth: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.boolean()))\n .describe('Health check'),\n \n /**\n * Get Connection Pool Statistics.\n * Useful for monitoring database load.\n */\n getPoolStats: z.function()\n .input(z.tuple([]))\n .output(z.object({\n total: z.number(),\n idle: z.number(),\n active: z.number(),\n waiting: z.number(),\n }).optional())\n .optional()\n .describe('Get connection pool statistics'),\n\n // ============================================================================\n // Raw Execution (Escape Hatch)\n // ============================================================================\n\n /**\n * Execute a raw command/query native to the driver.\n * Useful for complex reports, stored procedures, or DDL not covered by standard sync.\n * \n * @param command - The raw command (e.g., SQL string, shell command, or remote API payload).\n * @param parameters - Optional array of bound parameters for safe execution (prevention of injection).\n * @param options - Driver options (transaction context, timeout).\n * @returns Promise resolving to the raw result from the driver.\n * \n * @example\n * // SQL Driver\n * await driver.execute('SELECT * FROM complex_view WHERE id = ?', [123]);\n * \n * // Mongo Driver\n * await driver.execute({ aggregate: 'orders', pipeline: [...] });\n */\n execute: z.function()\n .input(z.tuple([z.unknown(), z.array(z.unknown()).optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.unknown()))\n .describe('Execute raw command'),\n\n // ============================================================================\n // CRUD Operations\n // ============================================================================\n\n /**\n * Find multiple records matching the structured query.\n * Parsing the QueryAST is the responsibility of the driver implementation.\n * \n * @param object - The name of the object/table to query (e.g. 'account').\n * @param query - The structured QueryAST (filters, sorts, joins, pagination).\n * @param options - Driver options.\n * @returns Array of records.\n * \n * @example\n * await driver.find('account', {\n * filters: [['status', '=', 'active'], 'and', ['amount', '>', 500]],\n * sort: [{ field: 'created_at', order: 'desc' }],\n * top: 10\n * });\n * @returns Array of records.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n find: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown()))))\n .describe('Find records'),\n\n /**\n * Stream records matching the structured query.\n * Optimized for large datasets to avoid memory overflow.\n * \n * @param object - The name of the object.\n * @param query - The structured QueryAST.\n * @param options - Driver options.\n * @returns AsyncIterable/ReadableStream of records.\n */\n findStream: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.unknown())\n .describe('Stream records (AsyncIterable)'),\n\n /**\n * Find a single record by query.\n * Similar to find(), but returns only the first match or null.\n * \n * @param object - The name of the object.\n * @param query - QueryAST.\n * @param options - Driver options.\n * @returns The record or null.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n findOne: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown()).nullable()))\n .describe('Find one record'),\n\n /**\n * Create a new record.\n * \n * @param object - The object name.\n * @param data - Key-value map of field data.\n * @param options - Driver options.\n * @returns The created record, including server-generated fields (id, created_at, etc.).\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n create: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Create record'),\n\n /**\n * Update an existing record by ID.\n * \n * @param object - The object name.\n * @param id - The unique identifier of the record.\n * @param data - The fields to update.\n * @param options - Driver options.\n * @returns The updated record.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n update: z.function()\n .input(z.tuple([z.string(), z.string().or(z.number()), z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Update record'),\n\n /**\n * Upsert (Update or Insert) a record.\n * \n * @param object - The object name.\n * @param data - The data to upsert.\n * @param conflictKeys - Fields to check for conflict (uniqueness).\n * @param options - Driver options.\n * @returns The created or updated record.\n */\n upsert: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), z.array(z.string()).optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Upsert record'),\n\n /**\n * Delete a record by ID.\n * \n * @param object - The object name.\n * @param id - The unique identifier of the record.\n * @param options - Driver options.\n * @returns True if deleted, false if not found.\n */\n delete: z.function()\n .input(z.tuple([z.string(), z.string().or(z.number()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.boolean()))\n .describe('Delete record'),\n\n /**\n * Count records matching a query.\n * \n * @param object - The object name.\n * @param query - Optional filtering criteria.\n * @param options - Driver options.\n * @returns Total count.\n */\n count: z.function()\n .input(z.tuple([z.string(), QuerySchema.optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .describe('Count records'),\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n\n /**\n * Create multiple records in a single batch.\n * Optimized for performance.\n * \n * @param object - The object name.\n * @param dataArray - Array of record data.\n * @returns Array of created records.\n */\n bulkCreate: z.function()\n .input(z.tuple([z.string(), z.array(z.record(z.string(), z.unknown())), DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown())))),\n\n /**\n * Update multiple records in a single batch.\n * \n * @param object - The object name.\n * @param updates - Array of objects containing {id, data}.\n * @returns Array of updated records.\n */\n bulkUpdate: z.function()\n .input(z.tuple([z.string(), z.array(z.object({ id: z.string().or(z.number()), data: z.record(z.string(), z.unknown()) })), DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown())))),\n\n /**\n * Delete multiple records in a single batch.\n * \n * @param object - The object name.\n * @param ids - Array of record IDs.\n */\n bulkDelete: z.function()\n .input(z.tuple([z.string(), z.array(z.string().or(z.number())), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void())),\n\n /**\n * Update multiple records matching a query.\n * Direct database push-down. DOES NOT trigger per-record hooks.\n * \n * @param object - The object name.\n * @param query - The filtering criteria.\n * @param data - The data to update.\n * @returns Count of modified records.\n */\n updateMany: z.function()\n .input(z.tuple([z.string(), QuerySchema, z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .optional(),\n\n /**\n * Delete multiple records matching a query.\n * Direct database push-down. DOES NOT trigger per-record hooks.\n * \n * @param object - The object name.\n * @param query - The filtering criteria.\n * @returns Count of deleted records.\n */\n deleteMany: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .optional(),\n\n // ============================================================================\n // Transaction Management\n // ============================================================================\n\n /**\n * Begin a new database transaction.\n * @param options - Isolation level and other settings.\n * @returns A transaction handle to be passed to subsequent operations via `options.transaction`.\n */\n beginTransaction: z.function()\n .input(z.tuple([z.object({\n isolationLevel: IsolationLevelEnum.optional()\n }).optional()]))\n .output(z.promise(z.unknown()))\n .describe('Start transaction'),\n\n /**\n * Commit the transaction.\n * @param transaction - The transaction handle.\n */\n commit: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.promise(z.void()))\n .describe('Commit transaction'),\n\n /**\n * Rollback the transaction.\n * @param transaction - The transaction handle.\n */\n rollback: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.promise(z.void()))\n .describe('Rollback transaction'),\n\n // ============================================================================\n // Schema Management\n // ============================================================================\n\n /**\n * Synchronize the database schema with the Object definition.\n * This is an idempotent operation: it should create tables if missing, \n * add columns if missing, and update indexes.\n * \n * @param object - The object name.\n * @param schema - The full Object Schema (fields, indexes, etc).\n * @param options - Driver options.\n */\n syncSchema: z.function()\n .input(z.tuple([z.string(), z.unknown(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void()))\n .describe('Sync object schema to DB'),\n\n /**\n * Batch-synchronize multiple object schemas with fewer round-trips.\n *\n * Drivers that advertise `supports.batchSchemaSync = true` MUST implement\n * this method. The engine will call it once with every\n * `{ object, schema }` pair instead of calling `syncSchema()` N times.\n *\n * @param schemas - Array of `{ object: string; schema: unknown }` pairs.\n * @param options - Driver options.\n */\n syncSchemasBatch: z.function()\n .input(z.tuple([\n z.array(z.object({ object: z.string(), schema: z.unknown() })),\n DriverOptionsSchema.optional(),\n ]))\n .output(z.promise(z.void()))\n .optional()\n .describe('Batch sync multiple schemas in one round-trip'),\n \n /**\n * Drop the underlying table or collection for an object.\n * WARNING: Destructive operation.\n * \n * @param object - The object name.\n */\n dropTable: z.function()\n .input(z.tuple([z.string(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void())),\n\n /**\n * Analyze query performance.\n * Returns execution plan without executing the query (where possible).\n * \n * @param object - The object name.\n * @param query - The query to explain.\n * @returns The execution plan details.\n */\n explain: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.unknown()))\n .optional(),\n});\n\n/**\n * Connection Pool Configuration Schema\n * Manages database connection pooling for performance\n */\nexport const PoolConfigSchema = z.object({\n min: z.number().min(0).default(2).describe('Minimum number of connections in pool'),\n max: z.number().min(1).default(10).describe('Maximum number of connections in pool'),\n idleTimeoutMillis: z.number().min(0).default(30000).describe('Time in ms before idle connection is closed'),\n connectionTimeoutMillis: z.number().min(0).default(5000).describe('Time in ms to wait for available connection'),\n});\n\n/**\n * Driver Configuration Schema\n * Base configuration for database drivers\n */\nexport const DriverConfigSchema = z.object({\n name: z.string().describe('Driver instance name'),\n type: z.enum(['sql', 'nosql', 'cache', 'search', 'graph', 'timeseries']).describe('Driver type category'),\n capabilities: DriverCapabilitiesSchema.describe('Driver capability flags'),\n connectionString: z.string().optional().describe('Database connection string (driver-specific format)'),\n poolConfig: PoolConfigSchema.optional().describe('Connection pool configuration'),\n});\n\n/**\n * TypeScript types\n */\nexport type DriverOptions = z.infer;\nexport type DriverCapabilities = z.infer;\nexport type DriverInterface = z.infer;\nexport type DriverConfig = z.infer;\nexport type PoolConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DriverConfigSchema } from './driver.zod';\n\n/**\n * SQL Dialect Enumeration\n * Supported SQL database dialects\n */\nexport const SQLDialectSchema = z.enum([\n 'postgresql',\n 'mysql',\n 'sqlite',\n 'mssql',\n 'oracle',\n 'mariadb',\n]);\n\nexport type SQLDialect = z.infer;\n\n/**\n * Data Type Mapping Schema\n * Maps ObjectStack field types to SQL-specific data types\n * \n * @example PostgreSQL data type mapping\n * {\n * text: 'VARCHAR(255)',\n * number: 'NUMERIC',\n * boolean: 'BOOLEAN',\n * date: 'DATE',\n * datetime: 'TIMESTAMP',\n * json: 'JSONB',\n * uuid: 'UUID',\n * binary: 'BYTEA'\n * }\n */\nexport const DataTypeMappingSchema = z.object({\n text: z.string().describe('SQL type for text fields (e.g., VARCHAR, TEXT)'),\n number: z.string().describe('SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)'),\n boolean: z.string().describe('SQL type for boolean fields (e.g., BOOLEAN, BIT)'),\n date: z.string().describe('SQL type for date fields (e.g., DATE)'),\n datetime: z.string().describe('SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)'),\n json: z.string().optional().describe('SQL type for JSON fields (e.g., JSON, JSONB)'),\n uuid: z.string().optional().describe('SQL type for UUID fields (e.g., UUID, CHAR(36))'),\n binary: z.string().optional().describe('SQL type for binary fields (e.g., BLOB, BYTEA)'),\n});\n\nexport type DataTypeMapping = z.infer;\n\n/**\n * SSL Configuration Schema\n * SSL/TLS connection configuration for secure database connections\n * \n * @example PostgreSQL SSL configuration\n * {\n * rejectUnauthorized: true,\n * ca: '/path/to/ca-cert.pem',\n * cert: '/path/to/client-cert.pem',\n * key: '/path/to/client-key.pem'\n * }\n */\nexport const SSLConfigSchema = z.object({\n rejectUnauthorized: z.boolean().default(true).describe('Reject connections with invalid certificates'),\n ca: z.string().optional().describe('CA certificate file path or content'),\n cert: z.string().optional().describe('Client certificate file path or content'),\n key: z.string().optional().describe('Client private key file path or content'),\n}).refine((data) => {\n // If cert is provided, key must also be provided, and vice versa\n const hasCert = data.cert !== undefined;\n const hasKey = data.key !== undefined;\n return hasCert === hasKey;\n}, {\n message: 'Client certificate (cert) and private key (key) must be provided together',\n});\n\nexport type SSLConfig = z.infer;\n\n/**\n * SQL Driver Configuration Schema\n * Extended driver configuration specific to SQL databases\n * \n * @example PostgreSQL driver configuration\n * {\n * name: 'primary-db',\n * type: 'sql',\n * dialect: 'postgresql',\n * connectionString: 'postgresql://user:pass@localhost:5432/mydb',\n * dataTypeMapping: {\n * text: 'VARCHAR(255)',\n * number: 'NUMERIC',\n * boolean: 'BOOLEAN',\n * date: 'DATE',\n * datetime: 'TIMESTAMP',\n * json: 'JSONB',\n * uuid: 'UUID',\n * binary: 'BYTEA'\n * },\n * ssl: true,\n * sslConfig: {\n * rejectUnauthorized: true,\n * ca: '/etc/ssl/certs/ca.pem'\n * },\n * poolConfig: {\n * min: 2,\n * max: 10,\n * idleTimeoutMillis: 30000,\n * connectionTimeoutMillis: 5000\n * },\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: true,\n * bulkDelete: true,\n * transactions: true,\n * savepoints: true,\n * isolationLevels: ['read-committed', 'repeatable-read', 'serializable'],\n * queryFilters: true,\n * queryAggregations: true,\n * querySorting: true,\n * queryPagination: true,\n * queryWindowFunctions: true,\n * querySubqueries: true,\n * queryCTE: true,\n * joins: true,\n * fullTextSearch: true,\n * jsonQuery: true,\n * geospatialQuery: false,\n * streaming: true,\n * jsonFields: true,\n * arrayFields: true,\n * vectorSearch: true,\n * schemaSync: true,\n * migrations: true,\n * indexes: true,\n * connectionPooling: true,\n * preparedStatements: true,\n * queryCache: false\n * }\n * }\n */\nexport const SQLDriverConfigSchema = DriverConfigSchema.extend({\n type: z.literal('sql').describe('Driver type must be \"sql\"'),\n dialect: SQLDialectSchema.describe('SQL database dialect'),\n dataTypeMapping: DataTypeMappingSchema.describe('SQL data type mapping configuration'),\n ssl: z.boolean().default(false).describe('Enable SSL/TLS connection'),\n sslConfig: SSLConfigSchema.optional().describe('SSL/TLS configuration (required when ssl is true)'),\n}).refine((data) => {\n // If ssl is enabled, sslConfig must be provided\n if (data.ssl && !data.sslConfig) {\n return false;\n }\n return true;\n}, {\n message: 'sslConfig is required when ssl is true',\n});\n\nexport type SQLDriverConfig = z.infer;\n\n// ==========================================================================\n// SQLite-Specific Constants\n// ==========================================================================\n\n/**\n * Default data type mappings for SQLite/libSQL dialect.\n *\n * SQLite uses a simplified type system with type affinity:\n * - TEXT: strings, dates, UUIDs\n * - REAL: floating-point numbers\n * - INTEGER: integers, booleans\n * - BLOB: binary data\n *\n * @see https://www.sqlite.org/datatype3.html\n */\nexport const SQLiteDataTypeMappingDefaults: DataTypeMapping = {\n text: 'TEXT',\n number: 'REAL',\n boolean: 'INTEGER',\n date: 'TEXT',\n datetime: 'TEXT',\n json: 'TEXT',\n uuid: 'TEXT',\n binary: 'BLOB',\n};\n\n/**\n * SQLite ALTER TABLE Limitations.\n *\n * SQLite has limited ALTER TABLE support compared to other SQL databases.\n * This constant documents the known limitations that affect migration planning.\n * The schema diff service must use the \"table rebuild\" strategy for operations\n * that SQLite cannot perform natively.\n *\n * @see https://www.sqlite.org/lang_altertable.html\n */\nexport const SQLiteAlterTableLimitations = {\n /** SQLite supports ADD COLUMN */\n supportsAddColumn: true,\n /** SQLite supports RENAME COLUMN (3.25.0+) */\n supportsRenameColumn: true,\n /** SQLite supports DROP COLUMN (3.35.0+) */\n supportsDropColumn: true,\n /** SQLite does NOT support MODIFY/ALTER COLUMN type */\n supportsModifyColumn: false,\n /** SQLite does NOT support adding constraints to existing columns */\n supportsAddConstraint: false,\n /**\n * When an unsupported alteration is needed, the migration planner\n * must use the 12-step table rebuild strategy:\n * 1. CREATE new table with desired schema\n * 2. Copy data from old table\n * 3. DROP old table\n * 4. RENAME new table to old name\n */\n rebuildStrategy: 'create_copy_drop_rename',\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DriverConfigSchema } from './driver.zod';\n\n/**\n * NoSQL Database Type Enumeration\n * Supported NoSQL database types\n */\nexport const NoSQLDatabaseTypeSchema = z.enum([\n 'mongodb',\n 'couchdb',\n 'dynamodb',\n 'cassandra',\n 'redis',\n 'elasticsearch',\n 'neo4j',\n 'orientdb',\n]);\n\nexport type NoSQLDatabaseType = z.infer;\n\n/**\n * NoSQL Query Operation Types\n * Different types of operations supported by NoSQL databases\n */\nexport const NoSQLOperationTypeSchema = z.enum([\n 'find', // Query documents/records\n 'findOne', // Get single document\n 'insert', // Insert document\n 'update', // Update document\n 'delete', // Delete document\n 'aggregate', // Aggregation pipeline\n 'mapReduce', // MapReduce operation\n 'count', // Count documents\n 'distinct', // Get distinct values\n 'createIndex', // Create index\n 'dropIndex', // Drop index\n]);\n\nexport type NoSQLOperationType = z.infer;\n\n/**\n * NoSQL Consistency Level\n * Consistency guarantees for distributed NoSQL databases\n * \n * Consistency levels (from strongest to weakest):\n * - **all**: All replicas must respond (strongest consistency, lowest availability)\n * - **quorum**: Majority of replicas must respond (balanced)\n * - **one**: Any single replica responds (weakest consistency, highest availability)\n * - **local_quorum**: Majority of replicas in local datacenter\n * - **each_quorum**: Quorum of replicas in each datacenter\n * - **eventual**: Eventual consistency (highest availability, weakest consistency)\n */\nexport const ConsistencyLevelSchema = z.enum([\n 'all',\n 'quorum',\n 'one',\n 'local_quorum',\n 'each_quorum',\n 'eventual',\n]);\n\nexport type ConsistencyLevel = z.infer;\n\n/**\n * NoSQL Index Type\n * Types of indexes supported by NoSQL databases\n */\nexport const NoSQLIndexTypeSchema = z.enum([\n 'single', // Single field index\n 'compound', // Multiple fields index\n 'unique', // Unique constraint\n 'text', // Full-text search index\n 'geospatial', // Geospatial index (2d, 2dsphere)\n 'hashed', // Hashed index for sharding\n 'ttl', // Time-to-live index (auto-deletion)\n 'sparse', // Sparse index (only indexed documents with field)\n]);\n\nexport type NoSQLIndexType = z.infer;\n\n/**\n * NoSQL Sharding Configuration\n * Configuration for horizontal partitioning across multiple nodes\n */\nexport const ShardingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable sharding'),\n shardKey: z.string().optional().describe('Field to use as shard key'),\n shardingStrategy: z.enum(['hash', 'range', 'zone']).optional().describe('Sharding strategy'),\n numShards: z.number().int().positive().optional().describe('Number of shards'),\n});\n\nexport type ShardingConfig = z.infer;\n\n/**\n * NoSQL Replication Configuration\n * Configuration for data replication across nodes\n */\nexport const ReplicationConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable replication'),\n replicaSetName: z.string().optional().describe('Replica set name'),\n replicas: z.number().int().positive().optional().describe('Number of replicas'),\n readPreference: z.enum(['primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'])\n .optional()\n .describe('Read preference for replica set'),\n writeConcern: z.enum(['majority', 'acknowledged', 'unacknowledged'])\n .optional()\n .describe('Write concern level'),\n});\n\nexport type ReplicationConfig = z.infer;\n\n/**\n * Document Schema Validation\n * Schema validation rules for document-based NoSQL databases\n */\nexport const DocumentSchemaValidationSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable schema validation'),\n validationLevel: z.enum(['strict', 'moderate', 'off']).optional().describe('Validation strictness'),\n validationAction: z.enum(['error', 'warn']).optional().describe('Action on validation failure'),\n jsonSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for validation'),\n});\n\nexport type DocumentSchemaValidation = z.infer;\n\n/**\n * NoSQL Data Type Mapping Schema\n * Maps ObjectStack field types to NoSQL-specific data types\n * \n * @example MongoDB data type mapping\n * {\n * text: 'string',\n * number: 'double',\n * boolean: 'bool',\n * date: 'date',\n * datetime: 'date',\n * json: 'object',\n * uuid: 'string',\n * binary: 'binData',\n * array: 'array',\n * objectId: 'objectId'\n * }\n */\nexport const NoSQLDataTypeMappingSchema = z.object({\n text: z.string().describe('NoSQL type for text fields'),\n number: z.string().describe('NoSQL type for number fields'),\n boolean: z.string().describe('NoSQL type for boolean fields'),\n date: z.string().describe('NoSQL type for date fields'),\n datetime: z.string().describe('NoSQL type for datetime fields'),\n json: z.string().optional().describe('NoSQL type for JSON/object fields'),\n uuid: z.string().optional().describe('NoSQL type for UUID fields'),\n binary: z.string().optional().describe('NoSQL type for binary fields'),\n array: z.string().optional().describe('NoSQL type for array fields'),\n objectId: z.string().optional().describe('NoSQL type for ObjectID fields (MongoDB)'),\n geopoint: z.string().optional().describe('NoSQL type for geospatial point fields'),\n});\n\nexport type NoSQLDataTypeMapping = z.infer;\n\n/**\n * NoSQL Driver Configuration Schema\n * Extended driver configuration specific to NoSQL databases\n * \n * @example MongoDB driver configuration\n * {\n * name: 'primary-mongo',\n * type: 'nosql',\n * databaseType: 'mongodb',\n * connectionString: 'mongodb://user:pass@localhost:27017/mydb',\n * dataTypeMapping: {\n * text: 'string',\n * number: 'double',\n * boolean: 'bool',\n * date: 'date',\n * datetime: 'date',\n * json: 'object',\n * uuid: 'string',\n * binary: 'binData',\n * array: 'array',\n * objectId: 'objectId'\n * },\n * consistency: 'quorum',\n * replication: {\n * enabled: true,\n * replicaSetName: 'rs0',\n * replicas: 3,\n * readPreference: 'primaryPreferred',\n * writeConcern: 'majority'\n * },\n * sharding: {\n * enabled: true,\n * shardKey: '_id',\n * shardingStrategy: 'hash',\n * numShards: 4\n * },\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: true,\n * bulkDelete: true,\n * transactions: true,\n * savepoints: false,\n * queryFilters: true,\n * queryAggregations: true,\n * querySorting: true,\n * queryPagination: true,\n * queryWindowFunctions: false,\n * querySubqueries: false,\n * queryCTE: false,\n * joins: false,\n * fullTextSearch: true,\n * jsonQuery: true,\n * geospatialQuery: true,\n * streaming: true,\n * jsonFields: true,\n * arrayFields: true,\n * vectorSearch: false,\n * schemaSync: true,\n * migrations: false,\n * indexes: true,\n * connectionPooling: true,\n * preparedStatements: false,\n * queryCache: false\n * }\n * }\n * \n * @example DynamoDB driver configuration\n * {\n * name: 'dynamodb-main',\n * type: 'nosql',\n * databaseType: 'dynamodb',\n * region: 'us-east-1',\n * accessKeyId: 'AKIAIOSFODNN7EXAMPLE',\n * secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n * consistency: 'eventual',\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: false,\n * bulkDelete: false,\n * transactions: true,\n * queryFilters: true,\n * queryAggregations: false,\n * querySorting: true,\n * queryPagination: true,\n * fullTextSearch: false,\n * jsonQuery: true,\n * indexes: true\n * }\n * }\n */\nexport const NoSQLDriverConfigSchema = DriverConfigSchema.extend({\n type: z.literal('nosql').describe('Driver type must be \"nosql\"'),\n databaseType: NoSQLDatabaseTypeSchema.describe('Specific NoSQL database type'),\n dataTypeMapping: NoSQLDataTypeMappingSchema.describe('NoSQL data type mapping configuration'),\n \n /**\n * Consistency level for reads/writes\n */\n consistency: ConsistencyLevelSchema.optional().describe('Consistency level for operations'),\n \n /**\n * Replication configuration\n */\n replication: ReplicationConfigSchema.optional().describe('Replication configuration'),\n \n /**\n * Sharding configuration\n */\n sharding: ShardingConfigSchema.optional().describe('Sharding configuration'),\n \n /**\n * Schema validation rules (for document databases)\n */\n schemaValidation: DocumentSchemaValidationSchema.optional().describe('Document schema validation'),\n \n /**\n * AWS Region (for DynamoDB, DocumentDB, etc.)\n */\n region: z.string().optional().describe('AWS region (for managed NoSQL services)'),\n \n /**\n * AWS Access Key ID (for DynamoDB, DocumentDB, etc.)\n */\n accessKeyId: z.string().optional().describe('AWS access key ID'),\n \n /**\n * AWS Secret Access Key (for DynamoDB, DocumentDB, etc.)\n */\n secretAccessKey: z.string().optional().describe('AWS secret access key'),\n \n /**\n * Time-to-live (TTL) field name\n * Automatically delete documents after a specified time\n */\n ttlField: z.string().optional().describe('Field name for TTL (auto-deletion)'),\n \n /**\n * Maximum document size in bytes\n */\n maxDocumentSize: z.number().int().positive().optional().describe('Maximum document size in bytes'),\n \n /**\n * Collection/Table name prefix\n * Useful for multi-tenancy or environment isolation\n */\n collectionPrefix: z.string().optional().describe('Prefix for collection/table names'),\n});\n\nexport type NoSQLDriverConfig = z.infer;\n\n/**\n * NoSQL Query Options\n * Additional options for NoSQL queries\n */\nexport const NoSQLQueryOptionsSchema = z.object({\n /**\n * Consistency level for this query\n */\n consistency: ConsistencyLevelSchema.optional().describe('Consistency level override'),\n \n /**\n * Read from secondary replicas\n */\n readFromSecondary: z.boolean().optional().describe('Allow reading from secondary replicas'),\n \n /**\n * Projection (fields to include/exclude)\n */\n projection: z.record(z.string(), z.union([z.literal(0), z.literal(1)])).optional().describe('Field projection'),\n \n /**\n * Query timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().describe('Query timeout (ms)'),\n \n /**\n * Use cursor for large result sets\n */\n useCursor: z.boolean().optional().describe('Use cursor instead of loading all results'),\n \n /**\n * Batch size for cursor iteration\n */\n batchSize: z.number().int().positive().optional().describe('Cursor batch size'),\n \n /**\n * Enable query profiling\n */\n profile: z.boolean().optional().describe('Enable query profiling'),\n \n /**\n * Use hinted index\n */\n hint: z.string().optional().describe('Index hint for query optimization'),\n});\n\nexport type NoSQLQueryOptions = z.infer;\n\n/**\n * NoSQL Aggregation Pipeline Stage\n * Represents a single stage in an aggregation pipeline (MongoDB-style)\n */\nexport const AggregationStageSchema = z.object({\n /**\n * Stage operator (e.g., $match, $group, $sort, $project)\n */\n operator: z.string().describe('Aggregation operator (e.g., $match, $group, $sort)'),\n \n /**\n * Stage parameters/options\n */\n options: z.record(z.string(), z.unknown()).describe('Stage-specific options'),\n});\n\nexport type AggregationStage = z.infer;\n\n/**\n * NoSQL Aggregation Pipeline\n * Sequence of aggregation stages for complex data transformations\n */\nexport const AggregationPipelineSchema = z.object({\n /**\n * Collection/Table to aggregate\n */\n collection: z.string().describe('Collection/table name'),\n \n /**\n * Pipeline stages\n */\n stages: z.array(AggregationStageSchema).describe('Aggregation pipeline stages'),\n \n /**\n * Additional options\n */\n options: NoSQLQueryOptionsSchema.optional().describe('Query options'),\n});\n\nexport type AggregationPipeline = z.infer;\n\n/**\n * NoSQL Index Definition\n * Definition for creating indexes in NoSQL databases\n */\nexport const NoSQLIndexSchema = z.object({\n /**\n * Index name\n */\n name: z.string().describe('Index name'),\n \n /**\n * Index type\n */\n type: NoSQLIndexTypeSchema.describe('Index type'),\n \n /**\n * Fields to index\n * For compound indexes, order matters\n */\n fields: z.array(z.object({\n field: z.string().describe('Field name'),\n order: z.enum(['asc', 'desc', 'text', '2dsphere']).optional().describe('Index order or type'),\n })).describe('Fields to index'),\n \n /**\n * Unique constraint\n */\n unique: z.boolean().default(false).describe('Enforce uniqueness'),\n \n /**\n * Sparse index (only index documents with the field)\n */\n sparse: z.boolean().default(false).describe('Sparse index'),\n \n /**\n * TTL in seconds (for TTL indexes)\n */\n expireAfterSeconds: z.number().int().positive().optional().describe('TTL in seconds'),\n \n /**\n * Partial index filter\n */\n partialFilterExpression: z.record(z.string(), z.unknown()).optional().describe('Partial index filter'),\n \n /**\n * Background index creation\n */\n background: z.boolean().default(false).describe('Create index in background'),\n});\n\nexport type NoSQLIndex = z.infer;\n\n/**\n * NoSQL Transaction Options\n * Options for NoSQL transactions (where supported)\n */\nexport const NoSQLTransactionOptionsSchema = z.object({\n /**\n * Read concern level\n */\n readConcern: z.enum(['local', 'majority', 'linearizable', 'snapshot']).optional().describe('Read concern level'),\n \n /**\n * Write concern level\n */\n writeConcern: z.enum(['majority', 'acknowledged', 'unacknowledged']).optional().describe('Write concern level'),\n \n /**\n * Read preference\n */\n readPreference: z.enum(['primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'])\n .optional()\n .describe('Read preference'),\n \n /**\n * Transaction timeout in milliseconds\n */\n maxCommitTimeMS: z.number().int().positive().optional().describe('Transaction commit timeout (ms)'),\n});\n\nexport type NoSQLTransactionOptions = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data Import Strategy\n * Defines how the engine handles existing records.\n */\nexport const DatasetMode = z.enum([\n 'insert', // Try to insert, fail on duplicate\n 'update', // Only update found records, ignore new\n 'upsert', // Create new or Update existing (Standard)\n 'replace', // Delete ALL records in object then insert (Dangerous - use for cache tables)\n 'ignore' // Try to insert, silently skip duplicates\n]);\n\n/**\n * Dataset Schema (Seed Data / Fixtures)\n * \n * Standardized format for transporting data.\n * Used for:\n * 1. System Bootstrapping (Admin accounts, Standard Roles)\n * 2. Reference Data (Countries, Currencies)\n * 3. Demo/Test Data\n */\nexport const DatasetSchema = z.object({\n /** \n * Target Object \n * The machine name of the object to populate.\n */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target Object Name'),\n\n /** \n * Idempotency Key (The \"Upsert\" Key)\n * The field used to check if a record already exists.\n * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'.\n * Standard: 'id' is rarely used for portable seed data — prefer natural keys.\n */\n externalId: z.string().default('name').describe('Field match for uniqueness check'),\n\n /** \n * Import Strategy\n */\n mode: DatasetMode.default('upsert').describe('Conflict resolution strategy'),\n\n /**\n * Environment Scope\n * - 'all': Always load\n * - 'dev': Only for development/demo\n * - 'test': Only for CI/CD tests\n */\n env: z.array(z.enum(['prod', 'dev', 'test'])).default(['prod', 'dev', 'test']).describe('Applicable environments'),\n\n /** \n * The Payload\n * Array of raw JSON objects matching the Object Schema.\n */\n records: z.array(z.record(z.string(), z.unknown())).describe('Data records'),\n});\n\n/** Parsed/output type — all defaults are applied (env, mode, externalId always present) */\nexport type Dataset = z.infer;\n\n/** Input type — fields with defaults (env, mode, externalId) are optional */\nexport type DatasetInput = z.input;\n\nexport type DatasetImportMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DatasetSchema, DatasetMode } from './dataset.zod';\n\n/**\n * # Seed Loader Protocol\n *\n * Defines the schemas for metadata-driven seed data loading with automatic\n * relationship resolution, dependency ordering, and multi-pass insertion.\n *\n * ## Architecture Alignment\n * - **Salesforce Data Loader**: External ID-based upsert with relationship resolution\n * - **ServiceNow**: Sys ID and display value mapping during import\n * - **Airtable**: Linked record resolution via display names\n *\n * ## Loading Flow\n * ```\n * 1. Build object dependency graph from field metadata (lookup/master_detail)\n * 2. Topological sort → determine insert order (parents before children)\n * 3. Pass 1: Insert/upsert records, resolve references via externalId\n * 4. Pass 2: Fill deferred references (circular/delayed dependencies)\n * 5. Validate & report unresolved references\n * 6. Return structured result with per-object stats\n * ```\n */\n\n// ==========================================================================\n// 1. Reference Resolution\n// ==========================================================================\n\n/**\n * Describes how a single field reference should be resolved during seed loading.\n *\n * When a lookup/master_detail field value is not an internal ID, the loader\n * attempts to match it against the target object's externalId field.\n */\nexport const ReferenceResolutionSchema = z.object({\n /** The field name on the source object (e.g., 'account_id') */\n field: z.string().describe('Source field name containing the reference value'),\n\n /** The target object being referenced (e.g., 'account') */\n targetObject: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target object name (snake_case)'),\n\n /**\n * The field on the target object used to match the reference value.\n * Defaults to the target object's externalId (usually 'name').\n */\n targetField: z.string().default('name').describe('Field on target object used for matching'),\n\n /** The field type that triggered this resolution (lookup or master_detail) */\n fieldType: z.enum(['lookup', 'master_detail']).describe('Relationship field type'),\n}).describe('Describes how a field reference is resolved during seed loading');\n\nexport type ReferenceResolution = z.infer;\n\n// ==========================================================================\n// 2. Object Dependency Node\n// ==========================================================================\n\n/**\n * Represents a single object in the dependency graph.\n * Built from object metadata by inspecting lookup/master_detail fields.\n */\nexport const ObjectDependencyNodeSchema = z.object({\n /** Object machine name */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Object name (snake_case)'),\n\n /**\n * Objects that this object depends on (via lookup/master_detail fields).\n * These must be loaded before this object.\n */\n dependsOn: z.array(z.string()).describe('Objects this object depends on'),\n\n /**\n * Field-level reference details for each dependency.\n * Maps field name → reference resolution info.\n */\n references: z.array(ReferenceResolutionSchema).describe('Field-level reference details'),\n}).describe('Object node in the seed data dependency graph');\n\nexport type ObjectDependencyNode = z.infer;\n\n// ==========================================================================\n// 3. Object Dependency Graph\n// ==========================================================================\n\n/**\n * The complete object dependency graph for seed data loading.\n * Used to determine topological insert order and detect circular dependencies.\n */\nexport const ObjectDependencyGraphSchema = z.object({\n /** All object nodes in the graph */\n nodes: z.array(ObjectDependencyNodeSchema).describe('All objects in the dependency graph'),\n\n /**\n * Topologically sorted object names for insertion order.\n * Parent objects appear before child objects.\n */\n insertOrder: z.array(z.string()).describe('Topologically sorted insert order'),\n\n /**\n * Circular dependency chains detected in the graph.\n * Each chain is an array of object names forming a cycle.\n * When present, the loader must use a multi-pass strategy.\n *\n * @example [['project', 'task', 'project']]\n */\n circularDependencies: z.array(z.array(z.string())).default([])\n .describe('Circular dependency chains (e.g., [[\"a\", \"b\", \"a\"]])'),\n}).describe('Complete object dependency graph for seed data loading');\n\nexport type ObjectDependencyGraph = z.infer;\n\n// ==========================================================================\n// 4. Reference Resolution Error\n// ==========================================================================\n\n/**\n * Actionable error for a failed reference resolution.\n * Provides all context needed to diagnose and fix the broken reference.\n *\n * Aligns with Salesforce Data Loader error reporting patterns:\n * field name, target object, attempted value, and reason.\n */\nexport const ReferenceResolutionErrorSchema = z.object({\n /** The source object containing the broken reference */\n sourceObject: z.string().describe('Object with the broken reference'),\n\n /** The field containing the unresolved value */\n field: z.string().describe('Field name with unresolved reference'),\n\n /** The target object that was searched */\n targetObject: z.string().describe('Target object searched for the reference'),\n\n /** The externalId field used for matching on the target object */\n targetField: z.string().describe('ExternalId field used for matching'),\n\n /** The value that could not be resolved */\n attemptedValue: z.unknown().describe('Value that failed to resolve'),\n\n /** The index of the record in the dataset's records array */\n recordIndex: z.number().int().min(0).describe('Index of the record in the dataset'),\n\n /** Human-readable error message */\n message: z.string().describe('Human-readable error description'),\n}).describe('Actionable error for a failed reference resolution');\n\nexport type ReferenceResolutionError = z.infer;\n\n// ==========================================================================\n// 5. Seed Loader Configuration\n// ==========================================================================\n\n/**\n * Configuration for the seed data loader.\n * Controls behavior for reference resolution, error handling, and validation.\n */\nexport const SeedLoaderConfigSchema = z.object({\n /**\n * Dry-run mode: validate all references without writing data.\n * Surfaces broken references before any mutations occur.\n * @default false\n */\n dryRun: z.boolean().default(false)\n .describe('Validate references without writing data'),\n\n /**\n * Whether to halt on the first reference resolution error.\n * When false, collects all errors and continues loading.\n * @default false\n */\n haltOnError: z.boolean().default(false)\n .describe('Stop on first reference resolution error'),\n\n /**\n * Enable multi-pass loading for circular dependencies.\n * Pass 1: Insert records with null for circular references.\n * Pass 2: Update records to fill deferred references.\n * @default true\n */\n multiPass: z.boolean().default(true)\n .describe('Enable multi-pass loading for circular dependencies'),\n\n /**\n * Default dataset mode when not specified per-dataset.\n * @default 'upsert'\n */\n defaultMode: DatasetMode.default('upsert')\n .describe('Default conflict resolution strategy'),\n\n /**\n * Maximum number of records to process in a single batch.\n * Controls memory usage for large datasets.\n * @default 1000\n */\n batchSize: z.number().int().min(1).default(1000)\n .describe('Maximum records per batch insert/upsert'),\n\n /**\n * Whether to wrap the entire load operation in a transaction.\n * When true, all-or-nothing semantics apply.\n * @default false\n */\n transaction: z.boolean().default(false)\n .describe('Wrap entire load in a transaction (all-or-nothing)'),\n\n /**\n * Environment filter. Only datasets matching this environment are loaded.\n * When not specified, all datasets are loaded regardless of env scope.\n */\n env: z.enum(['prod', 'dev', 'test']).optional()\n .describe('Only load datasets matching this environment'),\n}).describe('Seed data loader configuration');\n\nexport type SeedLoaderConfig = z.infer;\n\n/** Input type — all fields with defaults are optional */\nexport type SeedLoaderConfigInput = z.input;\n\n// ==========================================================================\n// 6. Per-Object Load Result\n// ==========================================================================\n\n/**\n * Result of loading a single object's dataset.\n */\nexport const DatasetLoadResultSchema = z.object({\n /** Target object name */\n object: z.string().describe('Object that was loaded'),\n\n /** Import mode used */\n mode: DatasetMode.describe('Import mode used'),\n\n /** Number of records successfully inserted */\n inserted: z.number().int().min(0).describe('Records inserted'),\n\n /** Number of records successfully updated (upsert matched existing) */\n updated: z.number().int().min(0).describe('Records updated'),\n\n /** Number of records skipped (mode: ignore, or already exists) */\n skipped: z.number().int().min(0).describe('Records skipped'),\n\n /** Number of records with errors */\n errored: z.number().int().min(0).describe('Records with errors'),\n\n /** Total records in the dataset */\n total: z.number().int().min(0).describe('Total records in dataset'),\n\n /** Number of references resolved via externalId */\n referencesResolved: z.number().int().min(0).describe('References resolved via externalId'),\n\n /** Number of references deferred to pass 2 (circular dependencies) */\n referencesDeferred: z.number().int().min(0).describe('References deferred to second pass'),\n\n /** Reference resolution errors for this object */\n errors: z.array(ReferenceResolutionErrorSchema).default([])\n .describe('Reference resolution errors'),\n}).describe('Result of loading a single dataset');\n\nexport type DatasetLoadResult = z.infer;\n\n// ==========================================================================\n// 7. Seed Loader Result\n// ==========================================================================\n\n/**\n * Complete result of a seed loading operation.\n * Aggregates all per-object results and provides summary statistics.\n */\nexport const SeedLoaderResultSchema = z.object({\n /** Whether the overall load operation succeeded */\n success: z.boolean().describe('Overall success status'),\n\n /** Was this a dry-run (validation only, no writes)? */\n dryRun: z.boolean().describe('Whether this was a dry-run'),\n\n /** The dependency graph used for ordering */\n dependencyGraph: ObjectDependencyGraphSchema.describe('Object dependency graph'),\n\n /** Per-object load results, in the order they were processed */\n results: z.array(DatasetLoadResultSchema).describe('Per-object load results'),\n\n /** All reference resolution errors across all objects */\n errors: z.array(ReferenceResolutionErrorSchema).describe('All reference resolution errors'),\n\n /** Summary statistics */\n summary: z.object({\n /** Total objects processed */\n objectsProcessed: z.number().int().min(0).describe('Total objects processed'),\n\n /** Total records across all objects */\n totalRecords: z.number().int().min(0).describe('Total records across all objects'),\n\n /** Total records inserted */\n totalInserted: z.number().int().min(0).describe('Total records inserted'),\n\n /** Total records updated */\n totalUpdated: z.number().int().min(0).describe('Total records updated'),\n\n /** Total records skipped */\n totalSkipped: z.number().int().min(0).describe('Total records skipped'),\n\n /** Total records with errors */\n totalErrored: z.number().int().min(0).describe('Total records with errors'),\n\n /** Total references resolved via externalId */\n totalReferencesResolved: z.number().int().min(0).describe('Total references resolved'),\n\n /** Total references deferred to second pass */\n totalReferencesDeferred: z.number().int().min(0).describe('Total references deferred'),\n\n /** Number of circular dependency chains detected */\n circularDependencyCount: z.number().int().min(0).describe('Circular dependency chains detected'),\n\n /** Duration of the load operation in milliseconds */\n durationMs: z.number().min(0).describe('Load duration in milliseconds'),\n }).describe('Summary statistics'),\n}).describe('Complete seed loader result');\n\nexport type SeedLoaderResult = z.infer;\n\n// ==========================================================================\n// 8. Seed Loader Request\n// ==========================================================================\n\n/**\n * Input request for the seed loader.\n * Combines datasets with loader configuration.\n */\nexport const SeedLoaderRequestSchema = z.object({\n /** Datasets to load */\n datasets: z.array(DatasetSchema).min(1).describe('Datasets to load'),\n\n /** Loader configuration */\n config: z.preprocess((val) => val ?? {}, SeedLoaderConfigSchema).describe('Loader configuration'),\n}).describe('Seed loader request with datasets and configuration');\n\nexport type SeedLoaderRequest = z.infer;\n\n/** Input type — config defaults are optional */\nexport type SeedLoaderRequestInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Document Version Schema\n * \n * Represents a single version of a document in a version-controlled system.\n * Each version is immutable and maintains its own metadata and download URL.\n * \n * @example\n * ```json\n * {\n * \"versionNumber\": 2,\n * \"createdAt\": 1704067200000,\n * \"createdBy\": \"user_123\",\n * \"size\": 2048576,\n * \"checksum\": \"a1b2c3d4e5f6\",\n * \"downloadUrl\": \"https://storage.example.com/docs/v2/file.pdf\",\n * \"isLatest\": true\n * }\n * ```\n */\nexport const DocumentVersionSchema = z.object({\n /**\n * Sequential version number (increments with each new version)\n */\n versionNumber: z.number().describe('Version number'),\n\n /**\n * Timestamp when this version was created (Unix milliseconds)\n */\n createdAt: z.number().describe('Creation timestamp'),\n\n /**\n * User ID who created this version\n */\n createdBy: z.string().describe('Creator user ID'),\n\n /**\n * File size in bytes\n */\n size: z.number().describe('File size in bytes'),\n\n /**\n * Checksum/hash of the file content (for integrity verification)\n */\n checksum: z.string().describe('File checksum'),\n\n /**\n * URL to download this specific version\n */\n downloadUrl: z.string().url().describe('Download URL'),\n\n /**\n * Whether this is the latest version\n * @default false\n */\n isLatest: z.boolean().optional().default(false).describe('Is latest version'),\n});\n\n/**\n * Document Template Schema\n * \n * Defines a reusable document template with dynamic placeholders.\n * Templates can be used to generate documents with variable content.\n * \n * @example\n * ```json\n * {\n * \"id\": \"contract-template\",\n * \"name\": \"Service Agreement\",\n * \"description\": \"Standard service agreement template\",\n * \"fileUrl\": \"https://example.com/templates/contract.docx\",\n * \"fileType\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n * \"placeholders\": [\n * {\n * \"key\": \"client_name\",\n * \"label\": \"Client Name\",\n * \"type\": \"text\",\n * \"required\": true\n * },\n * {\n * \"key\": \"contract_date\",\n * \"label\": \"Contract Date\",\n * \"type\": \"date\",\n * \"required\": true\n * }\n * ]\n * }\n * ```\n */\nexport const DocumentTemplateSchema = z.object({\n /**\n * Unique identifier for the template\n */\n id: z.string().describe('Template ID'),\n\n /**\n * Human-readable name of the template\n */\n name: z.string().describe('Template name'),\n\n /**\n * Optional description of the template's purpose\n */\n description: z.string().optional().describe('Template description'),\n\n /**\n * URL to the template file\n */\n fileUrl: z.string().url().describe('Template file URL'),\n\n /**\n * MIME type of the template file\n */\n fileType: z.string().describe('File MIME type'),\n\n /**\n * List of dynamic placeholders in the template\n */\n placeholders: z.array(z.object({\n /**\n * Placeholder identifier (used in template)\n */\n key: z.string().describe('Placeholder key'),\n\n /**\n * Human-readable label for the placeholder\n */\n label: z.string().describe('Placeholder label'),\n\n /**\n * Data type of the placeholder value\n */\n type: z.enum(['text', 'number', 'date', 'image']).describe('Placeholder type'),\n\n /**\n * Whether this placeholder must be filled\n * @default false\n */\n required: z.boolean().optional().default(false).describe('Is required'),\n })).describe('Template placeholders'),\n});\n\n/**\n * E-Signature Configuration Schema\n * \n * Configuration for electronic signature workflows.\n * Supports integration with popular e-signature providers.\n * \n * @example\n * ```json\n * {\n * \"provider\": \"docusign\",\n * \"enabled\": true,\n * \"signers\": [\n * {\n * \"email\": \"client@example.com\",\n * \"name\": \"John Doe\",\n * \"role\": \"Client\",\n * \"order\": 1\n * },\n * {\n * \"email\": \"manager@example.com\",\n * \"name\": \"Jane Smith\",\n * \"role\": \"Manager\",\n * \"order\": 2\n * }\n * ],\n * \"expirationDays\": 30,\n * \"reminderDays\": 7\n * }\n * ```\n */\nexport const ESignatureConfigSchema = z.object({\n /**\n * E-signature service provider\n */\n provider: z.enum(['docusign', 'adobe-sign', 'hellosign', 'custom']).describe('E-signature provider'),\n\n /**\n * Whether e-signature is enabled for this document\n * @default false\n */\n enabled: z.boolean().optional().default(false).describe('E-signature enabled'),\n\n /**\n * List of signers in signing order\n */\n signers: z.array(z.object({\n /**\n * Signer's email address\n */\n email: z.string().email().describe('Signer email'),\n\n /**\n * Signer's full name\n */\n name: z.string().describe('Signer name'),\n\n /**\n * Signer's role in the document\n */\n role: z.string().describe('Signer role'),\n\n /**\n * Signing order (lower numbers sign first)\n */\n order: z.number().describe('Signing order'),\n })).describe('Document signers'),\n\n /**\n * Days until signature request expires\n * @default 30\n */\n expirationDays: z.number().optional().default(30).describe('Expiration days'),\n\n /**\n * Days between reminder emails\n * @default 7\n */\n reminderDays: z.number().optional().default(7).describe('Reminder interval days'),\n});\n\n/**\n * Document Schema\n * \n * Comprehensive document management protocol supporting versioning,\n * templates, e-signatures, and access control.\n * \n * @example\n * ```json\n * {\n * \"id\": \"doc_123\",\n * \"name\": \"Service Agreement 2024\",\n * \"description\": \"Annual service agreement\",\n * \"fileType\": \"application/pdf\",\n * \"fileSize\": 1048576,\n * \"category\": \"contracts\",\n * \"tags\": [\"legal\", \"2024\", \"services\"],\n * \"versioning\": {\n * \"enabled\": true,\n * \"versions\": [\n * {\n * \"versionNumber\": 1,\n * \"createdAt\": 1704067200000,\n * \"createdBy\": \"user_123\",\n * \"size\": 1048576,\n * \"checksum\": \"abc123\",\n * \"downloadUrl\": \"https://example.com/docs/v1.pdf\",\n * \"isLatest\": true\n * }\n * ],\n * \"majorVersion\": 1,\n * \"minorVersion\": 0\n * },\n * \"access\": {\n * \"isPublic\": false,\n * \"sharedWith\": [\"user_456\", \"team_789\"],\n * \"expiresAt\": 1735689600000\n * },\n * \"metadata\": {\n * \"author\": \"John Doe\",\n * \"department\": \"Legal\"\n * }\n * }\n * ```\n */\nexport const DocumentSchema = z.object({\n /**\n * Unique document identifier\n */\n id: z.string().describe('Document ID'),\n\n /**\n * Document name\n */\n name: z.string().describe('Document name'),\n\n /**\n * Optional document description\n */\n description: z.string().optional().describe('Document description'),\n\n /**\n * MIME type of the document\n */\n fileType: z.string().describe('File MIME type'),\n\n /**\n * File size in bytes\n */\n fileSize: z.number().describe('File size in bytes'),\n\n /**\n * Document category for organization\n */\n category: z.string().optional().describe('Document category'),\n\n /**\n * Tags for searchability and organization\n */\n tags: z.array(z.string()).optional().describe('Document tags'),\n\n /**\n * Version control configuration\n */\n versioning: z.object({\n /**\n * Whether versioning is enabled\n */\n enabled: z.boolean().describe('Versioning enabled'),\n\n /**\n * List of all document versions\n */\n versions: z.array(DocumentVersionSchema).describe('Version history'),\n\n /**\n * Current major version number\n */\n majorVersion: z.number().describe('Major version'),\n\n /**\n * Current minor version number\n */\n minorVersion: z.number().describe('Minor version'),\n }).optional().describe('Version control'),\n\n /**\n * Template configuration (if document is generated from template)\n */\n template: DocumentTemplateSchema.optional().describe('Document template'),\n\n /**\n * E-signature configuration\n */\n eSignature: ESignatureConfigSchema.optional().describe('E-signature config'),\n\n /**\n * Access control settings\n */\n access: z.object({\n /**\n * Whether document is publicly accessible\n * @default false\n */\n isPublic: z.boolean().optional().default(false).describe('Public access'),\n\n /**\n * List of user/team IDs with access\n */\n sharedWith: z.array(z.string()).optional().describe('Shared with'),\n\n /**\n * Timestamp when access expires (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Access expiration'),\n }).optional().describe('Access control'),\n\n /**\n * Custom metadata fields\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\n// Type exports\nexport type Document = z.infer;\nexport type DocumentVersion = z.infer;\nexport type DocumentTemplate = z.infer;\nexport type ESignatureConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Base Field Mapping Protocol\n * \n * Shared by: ETL, Sync, Connector, External Lookup\n * \n * This module provides the canonical field mapping schema used across\n * ObjectStack for data transformation and synchronization.\n * \n * **Use Cases:**\n * - ETL pipelines (data/mapping.zod.ts)\n * - Data synchronization (automation/sync.zod.ts)\n * - Integration connectors (integration/connector.zod.ts)\n * - External lookups (data/external-lookup.zod.ts)\n * \n * @example Basic field mapping\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'external_user_id',\n * target: 'user_id',\n * };\n * ```\n * \n * @example With transformation\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'user_name',\n * target: 'name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: 'Unknown'\n * };\n * ```\n */\n\n/**\n * Transform Type Schema\n * \n * Defines the type of transformation to apply to a field value.\n * Implementations can extend this for domain-specific transforms.\n */\nexport const TransformTypeSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('constant'),\n value: z.unknown().describe('Constant value to use'),\n }).describe('Set a constant value'),\n \n z.object({\n type: z.literal('cast'),\n targetType: z.enum(['string', 'number', 'boolean', 'date']).describe('Target data type'),\n }).describe('Cast to a specific data type'),\n \n z.object({\n type: z.literal('lookup'),\n table: z.string().describe('Lookup table name'),\n keyField: z.string().describe('Field to match on'),\n valueField: z.string().describe('Field to retrieve'),\n }).describe('Lookup value from another table'),\n \n z.object({\n type: z.literal('javascript'),\n expression: z.string().describe('JavaScript expression (e.g., \"value.toUpperCase()\")'),\n }).describe('Custom JavaScript transformation'),\n \n z.object({\n type: z.literal('map'),\n mappings: z.record(z.string(), z.unknown()).describe('Value mappings (e.g., {\"Active\": \"active\"})'),\n }).describe('Map values using a dictionary'),\n]);\n\nexport type TransformType = z.infer;\n\n/**\n * Field Mapping Schema\n * \n * Base schema for mapping fields between source and target systems.\n * \n * **NAMING CONVENTION:**\n * - source: Field name in the source system\n * - target: Field name in the target system (should be snake_case for ObjectStack)\n * \n * @example\n * ```typescript\n * {\n * source: 'FirstName',\n * target: 'first_name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: ''\n * }\n * ```\n */\nexport const FieldMappingSchema = z.object({\n /**\n * Source field name\n */\n source: z.string().describe('Source field name'),\n \n /**\n * Target field name (should be snake_case for ObjectStack)\n */\n target: z.string().describe('Target field name'),\n \n /**\n * Transformation to apply\n */\n transform: TransformTypeSchema.optional().describe('Transformation to apply'),\n \n /**\n * Default value if source is null/undefined\n */\n defaultValue: z.unknown().optional().describe('Default if source is null/undefined'),\n});\n\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldMappingSchema as BaseFieldMappingSchema } from '../shared/mapping.zod';\n\n/**\n * External Data Source Schema\n * \n * Configuration for connecting to external data systems.\n * Similar to Salesforce External Objects for real-time data integration.\n * \n * @example\n * ```json\n * {\n * \"id\": \"salesforce-accounts\",\n * \"name\": \"Salesforce Account Data\",\n * \"type\": \"rest-api\",\n * \"endpoint\": \"https://api.salesforce.com/services/data/v58.0\",\n * \"authentication\": {\n * \"type\": \"oauth2\",\n * \"config\": {\n * \"clientId\": \"...\",\n * \"clientSecret\": \"...\",\n * \"tokenUrl\": \"https://login.salesforce.com/services/oauth2/token\"\n * }\n * }\n * }\n * ```\n */\nexport const ExternalDataSourceSchema = z.object({\n /**\n * Unique identifier for the external data source\n */\n id: z.string().describe('Data source ID'),\n\n /**\n * Human-readable name of the data source\n */\n name: z.string().describe('Data source name'),\n\n /**\n * Protocol type for connecting to the data source\n */\n type: z.enum(['odata', 'rest-api', 'graphql', 'custom']).describe('Protocol type'),\n\n /**\n * Base URL endpoint for the external system\n */\n endpoint: z.string().url().describe('API endpoint URL'),\n\n /**\n * Authentication configuration\n */\n authentication: z.object({\n /**\n * Authentication method\n */\n type: z.enum(['oauth2', 'api-key', 'basic', 'none']).describe('Auth type'),\n\n /**\n * Authentication-specific configuration\n * Structure varies based on auth type\n */\n config: z.record(z.string(), z.unknown()).describe('Auth configuration'),\n }).describe('Authentication'),\n});\n\n/**\n * Field Mapping Schema for External Lookups\n * \n * Extends the base field mapping with external lookup specific features.\n * Uses the canonical field mapping protocol from shared/mapping.zod.ts.\n * \n * @see {@link BaseFieldMappingSchema} for the base field mapping schema\n * \n * @example\n * ```json\n * {\n * \"source\": \"AccountName\",\n * \"target\": \"name\",\n * \"readonly\": true\n * }\n * ```\n */\nexport const ExternalFieldMappingSchema = BaseFieldMappingSchema.extend({\n /**\n * Field data type\n */\n type: z.string().optional().describe('Field type'),\n\n /**\n * Whether the field is read-only\n * @default true\n */\n readonly: z.boolean().optional().default(true).describe('Read-only field'),\n});\n\n/**\n * External Lookup Schema\n * \n * Real-time data lookup protocol for external systems.\n * Enables querying external data sources without replication.\n * Inspired by Salesforce External Objects and OData protocols.\n * \n * @example\n * ```json\n * {\n * \"fieldName\": \"external_account\",\n * \"dataSource\": {\n * \"id\": \"salesforce-api\",\n * \"name\": \"Salesforce\",\n * \"type\": \"rest-api\",\n * \"endpoint\": \"https://api.salesforce.com/services/data/v58.0\",\n * \"authentication\": {\n * \"type\": \"oauth2\",\n * \"config\": {\"clientId\": \"...\"}\n * }\n * },\n * \"query\": {\n * \"endpoint\": \"/sobjects/Account\",\n * \"method\": \"GET\",\n * \"parameters\": {\"limit\": 100}\n * },\n * \"fieldMappings\": [\n * {\n * \"externalField\": \"Name\",\n * \"localField\": \"account_name\",\n * \"type\": \"text\",\n * \"readonly\": true\n * }\n * ],\n * \"caching\": {\n * \"enabled\": true,\n * \"ttl\": 300,\n * \"strategy\": \"ttl\"\n * },\n * \"fallback\": {\n * \"enabled\": true,\n * \"showError\": true\n * },\n * \"rateLimit\": {\n * \"requestsPerSecond\": 10,\n * \"burstSize\": 20\n * }\n * }\n * ```\n */\nexport const ExternalLookupSchema = z.object({\n /**\n * Name of the field that uses external lookup\n */\n fieldName: z.string().describe('Field name'),\n\n /**\n * External data source configuration\n */\n dataSource: ExternalDataSourceSchema.describe('External data source'),\n\n /**\n * Query configuration for fetching external data\n */\n query: z.object({\n /**\n * API endpoint path (relative to base endpoint)\n */\n endpoint: z.string().describe('Query endpoint path'),\n\n /**\n * HTTP method for the query\n * @default 'GET'\n */\n method: z.enum(['GET', 'POST']).optional().default('GET').describe('HTTP method'),\n\n /**\n * Query parameters or request body\n */\n parameters: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n }).describe('Query configuration'),\n\n /**\n * Mapping between external and local fields\n */\n fieldMappings: z.array(ExternalFieldMappingSchema).describe('Field mappings'),\n\n /**\n * Cache configuration for external data\n */\n caching: z.object({\n /**\n * Whether caching is enabled\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Cache enabled'),\n\n /**\n * Time-to-live in seconds\n * @default 300\n */\n ttl: z.number().optional().default(300).describe('Cache TTL (seconds)'),\n\n /**\n * Cache eviction strategy\n * @default 'ttl'\n */\n strategy: z.enum(['lru', 'lfu', 'ttl']).optional().default('ttl').describe('Cache strategy'),\n }).optional().describe('Caching configuration'),\n\n /**\n * Fallback behavior when external system is unavailable\n */\n fallback: z.object({\n /**\n * Whether fallback is enabled\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Fallback enabled'),\n\n /**\n * Default value to use when external system fails\n */\n defaultValue: z.unknown().optional().describe('Default fallback value'),\n\n /**\n * Whether to show error message to user\n * @default true\n */\n showError: z.boolean().optional().default(true).describe('Show error to user'),\n }).optional().describe('Fallback configuration'),\n\n /**\n * Rate limiting to prevent overwhelming external system\n */\n rateLimit: z.object({\n /**\n * Maximum requests per second\n */\n requestsPerSecond: z.number().describe('Requests per second limit'),\n\n /**\n * Burst size for handling spikes\n */\n burstSize: z.number().optional().describe('Burst size'),\n }).optional().describe('Rate limiting'),\n\n /**\n * Retry configuration with exponential backoff\n *\n * @example\n * ```json\n * {\n * \"maxRetries\": 3,\n * \"initialDelayMs\": 1000,\n * \"maxDelayMs\": 30000,\n * \"backoffMultiplier\": 2,\n * \"retryableStatusCodes\": [429, 500, 502, 503, 504]\n * }\n * ```\n */\n retry: z.object({\n /** Maximum number of retry attempts */\n maxRetries: z.number().min(0).default(3).describe('Maximum retry attempts'),\n /** Initial delay before first retry (ms) */\n initialDelayMs: z.number().default(1000).describe('Initial retry delay in milliseconds'),\n /** Maximum delay between retries (ms) */\n maxDelayMs: z.number().default(30000).describe('Maximum retry delay in milliseconds'),\n /** Backoff multiplier for exponential backoff */\n backoffMultiplier: z.number().default(2).describe('Exponential backoff multiplier'),\n /** HTTP status codes that trigger a retry */\n retryableStatusCodes: z.array(z.number()).default([429, 500, 502, 503, 504])\n .describe('HTTP status codes that are retryable'),\n }).optional().describe('Retry configuration with exponential backoff'),\n\n /**\n * Request/response transformation pipeline\n *\n * Allows transforming request parameters and response data\n * before they are processed by the external lookup system.\n */\n transform: z.object({\n /** Transform request parameters before sending */\n request: z.object({\n /** Header transformations (key-value additions) */\n headers: z.record(z.string(), z.string()).optional().describe('Additional request headers'),\n /** Query parameter transformations */\n queryParams: z.record(z.string(), z.string()).optional().describe('Additional query parameters'),\n }).optional().describe('Request transformation'),\n /** Transform response data after receiving */\n response: z.object({\n /** JSONPath expression to extract data from response */\n dataPath: z.string().optional().describe('JSONPath to extract data (e.g., \"$.data.results\")'),\n /** JSONPath expression to extract total count for pagination */\n totalPath: z.string().optional().describe('JSONPath to extract total count (e.g., \"$.meta.total\")'),\n }).optional().describe('Response transformation'),\n }).optional().describe('Request/response transformation pipeline'),\n\n /** Pagination support for external data sources */\n pagination: z.object({\n /** Pagination type */\n type: z.enum(['offset', 'cursor', 'page']).default('offset').describe('Pagination type'),\n /** Page size */\n pageSize: z.number().default(100).describe('Items per page'),\n /** Maximum pages to fetch */\n maxPages: z.number().optional().describe('Maximum number of pages to fetch'),\n }).optional().describe('Pagination configuration for external data'),\n});\n\n// Type exports\nexport type ExternalLookup = z.infer;\nexport type ExternalDataSource = z.infer;\nexport type ExternalFieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n\n/**\n * Driver Identifier\n * Can be a built-in driver or a plugin-contributed driver (e.g., \"com.vendor.snowflake\").\n */\nexport const DriverType = z.string().describe('Underlying driver identifier');\n\n/**\n * Driver Definition Schema\n * Metadata describing a Database Driver.\n * Plugins use this to register new connectivity options.\n */\nexport const DriverDefinitionSchema = z.object({\n id: z.string().describe('Unique driver identifier (e.g. \"postgres\")'),\n label: z.string().describe('Display label (e.g. \"PostgreSQL\")'),\n description: z.string().optional(),\n icon: z.string().optional(),\n \n /**\n * Configuration Schema (JSON Schema)\n * Describes the structure of the `config` object needed for this driver.\n * Used by the UI to generate the connection form.\n */\n configSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for connection configuration'),\n \n /**\n * Default Capabilities\n * What this driver supports out-of-the-box.\n */\n capabilities: z.lazy(() => DatasourceCapabilities).optional(),\n});\n\n/**\n * Datasource Capabilities Schema\n * Declares what this datasource naturally supports.\n * The ObjectQL engine uses this to determine what logic to push down\n * and what to compute in memory.\n */\nexport const DatasourceCapabilities = z.object({\n // ============================================================================\n // Transaction & Connection Management\n // ============================================================================\n \n /** Can handle ACID transactions? */\n transactions: z.boolean().default(false),\n \n // ============================================================================\n // Query Operations\n // ============================================================================\n \n /** Can execute WHERE clause filters natively? */\n queryFilters: z.boolean().default(false),\n \n /** Can perform aggregation (group by, sum, avg)? */\n queryAggregations: z.boolean().default(false),\n \n /** Can perform ORDER BY sorting? */\n querySorting: z.boolean().default(false),\n \n /** Can perform LIMIT/OFFSET pagination? */\n queryPagination: z.boolean().default(false),\n \n /** Can perform window functions? */\n queryWindowFunctions: z.boolean().default(false),\n \n /** Can perform subqueries? */\n querySubqueries: z.boolean().default(false),\n \n /** Can execute SQL-like joins natively? */\n joins: z.boolean().default(false),\n \n // ============================================================================\n // Advanced Features\n // ============================================================================\n \n /** Can perform full-text search? */\n fullTextSearch: z.boolean().default(false),\n \n /** Is read-only? */\n readOnly: z.boolean().default(false),\n \n /** Is scheme-less (needs schema inference)? */\n dynamicSchema: z.boolean().default(false),\n});\n\n/**\n * Datasource Schema\n * Represents a connection to an external data store.\n */\nexport const DatasourceSchema = z.object({\n /** Machine Name */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique datasource identifier'),\n \n /** Human Label */\n label: z.string().optional().describe('Display label'),\n \n /** Driver */\n driver: DriverType.describe('Underlying driver type'),\n \n /** \n * Connection Configuration \n * Specific to the driver (e.g., host, port, user, password, bucket, etc.)\n * Stored securely (passwords usually interpolated from ENV).\n */\n config: z.record(z.string(), z.unknown()).describe('Driver specific configuration'),\n \n /**\n * Connection Pool Configuration\n * Standard connection pooling settings.\n */\n pool: z.object({\n min: z.number().default(0).describe('Minimum connections'),\n max: z.number().default(10).describe('Maximum connections'),\n idleTimeoutMillis: z.number().default(30000).describe('Idle timeout'),\n connectionTimeoutMillis: z.number().default(3000).describe('Connection establishment timeout'),\n }).optional().describe('Connection pool settings'),\n\n /**\n * Read Replicas\n * Optional list of duplicate configurations for read-only operations.\n * Useful for scaling read throughput.\n */\n readReplicas: z.array(z.record(z.string(), z.unknown())).optional().describe('Read-only replica configurations'),\n\n /**\n * Capability Overrides\n * Manually override what the driver claims to support.\n */\n capabilities: DatasourceCapabilities.optional().describe('Capability overrides'),\n \n /** Health Check */\n healthCheck: z.object({\n enabled: z.boolean().default(true).describe('Enable health check endpoint'),\n intervalMs: z.number().default(30000).describe('Health check interval in milliseconds'),\n timeoutMs: z.number().default(5000).describe('Health check timeout in milliseconds'),\n }).optional().describe('Datasource health check configuration'),\n\n /** SSL/TLS Configuration */\n ssl: z.object({\n enabled: z.boolean().default(false).describe('Enable SSL/TLS for database connection'),\n rejectUnauthorized: z.boolean().default(true).describe('Reject connections with invalid/self-signed certificates'),\n ca: z.string().optional().describe('CA certificate (PEM format or path to file)'),\n cert: z.string().optional().describe('Client certificate (PEM format or path to file)'),\n key: z.string().optional().describe('Client private key (PEM format or path to file)'),\n }).optional().describe('SSL/TLS configuration for secure database connections'),\n\n /** Retry Policy */\n retryPolicy: z.object({\n maxRetries: z.number().default(3).describe('Maximum number of retry attempts'),\n baseDelayMs: z.number().default(1000).describe('Base delay between retries in milliseconds'),\n maxDelayMs: z.number().default(30000).describe('Maximum delay between retries in milliseconds'),\n backoffMultiplier: z.number().default(2).describe('Exponential backoff multiplier'),\n }).optional().describe('Connection retry policy for transient failures'),\n\n /** Description */\n description: z.string().optional().describe('Internal description'),\n \n /** Is enabled? */\n active: z.boolean().default(true).describe('Is datasource enabled'),\n});\n\nexport type Datasource = z.infer;\nexport type DatasourceCapabilitiesType = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Analytics/Semantic Layer Protocol\n * \n * Defines the \"Business Logic\" for data analysis.\n * Inspired by Cube.dev, LookML, and dbt MetricFlow.\n * \n * This layer decouples the \"Physical Data\" (Tables/Columns) from the \n * \"Business Data\" (Metrics/Dimensions).\n */\n\n/**\n * Aggregation Metric Type\n * The mathematical operation to perform on a metric.\n */\nexport const AggregationMetricType = z.enum([\n 'count', \n 'sum', \n 'avg', \n 'min', \n 'max', \n 'count_distinct', \n 'number', // Custom SQL expression returning a number\n 'string', // Custom SQL expression returning a string\n 'boolean' // Custom SQL expression returning a boolean\n]);\n\n/**\n * Dimension Type\n * The nature of the grouping field.\n */\nexport const DimensionType = z.enum([\n 'string', \n 'number', \n 'boolean', \n 'time', \n 'geo'\n]);\n\n/**\n * Time Interval for Time Dimensions\n */\nexport const TimeUpdateInterval = z.enum([\n 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'\n]);\n\n/**\n * Metric Schema\n * A quantitative measurement (e.g., \"Total Revenue\", \"Average Order Value\").\n */\nexport const MetricSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique metric ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: AggregationMetricType,\n \n /** Source Calculation */\n sql: z.string().describe('SQL expression or field reference'),\n \n /** Filtering for this specific metric (e.g. \"Revenue from Premium Users\") */\n filters: z.array(z.object({\n sql: z.string()\n })).optional(),\n \n /** Format for display (e.g. \"currency\", \"percent\") */\n format: z.string().optional(),\n});\n\n/**\n * Dimension Schema\n * A categorical attribute to group by (e.g., \"Product Category\", \"Order Date\").\n */\nexport const DimensionSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique dimension ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: DimensionType,\n \n /** Source Column */\n sql: z.string().describe('SQL expression or column reference'),\n \n /** For Time Dimensions: Supported Granularities */\n granularities: z.array(TimeUpdateInterval).optional(),\n});\n\n/**\n * Join Schema\n * Defines how this cube relates to others.\n */\nexport const CubeJoinSchema = z.object({\n name: z.string().describe('Target cube name'),\n relationship: z.enum(['one_to_one', 'one_to_many', 'many_to_one']).default('many_to_one'),\n sql: z.string().describe('Join condition (ON clause)'),\n});\n\n/**\n * Cube Schema\n * A logical data model representing a business entity or process for analysis.\n * Maps physical tables to business metrics and dimensions.\n */\nexport const CubeSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Cube name (snake_case)'),\n title: z.string().optional(),\n description: z.string().optional(),\n \n /** Physical Data Source */\n sql: z.string().describe('Base SQL statement or Table Name'),\n \n /** Semantic Definitions */\n measures: z.record(z.string(), MetricSchema).describe('Quantitative metrics'),\n dimensions: z.record(z.string(), DimensionSchema).describe('Qualitative attributes'),\n \n /** Relationships */\n joins: z.record(z.string(), CubeJoinSchema).optional(),\n \n /** Pre-aggregations / Caching */\n refreshKey: z.object({\n every: z.string().optional(), // e.g. \"1 hour\"\n sql: z.string().optional(), // SQL to check for data changes\n }).optional(),\n \n /** Access Control */\n public: z.boolean().default(false),\n});\n\n/**\n * Analytics Query Schema\n * The request format for the Analytics API.\n */\nexport const AnalyticsQuerySchema = z.object({\n cube: z.string().optional().describe('Target cube name (optional when provided externally, e.g. in API request wrapper)'),\n measures: z.array(z.string()).describe('List of metrics to calculate'),\n dimensions: z.array(z.string()).optional().describe('List of dimensions to group by'),\n \n filters: z.array(z.object({\n member: z.string().describe('Dimension or Measure'),\n operator: z.enum(['equals', 'notEquals', 'contains', 'notContains', 'gt', 'gte', 'lt', 'lte', 'set', 'notSet', 'inDateRange']),\n values: z.array(z.string()).optional(),\n })).optional(),\n \n timeDimensions: z.array(z.object({\n dimension: z.string(),\n granularity: TimeUpdateInterval.optional(),\n dateRange: z.union([\n z.string(), // \"Last 7 days\"\n z.array(z.string()) // [\"2023-01-01\", \"2023-01-31\"]\n ]).optional(),\n })).optional(),\n \n order: z.record(z.string(), z.enum(['asc', 'desc'])).optional(),\n \n limit: z.number().optional(),\n offset: z.number().optional(),\n \n timezone: z.string().optional().default('UTC'),\n});\n\nexport type Metric = z.infer;\nexport type Dimension = z.infer;\nexport type CubeJoin = z.infer;\nexport type Cube = z.infer;\nexport type AnalyticsQuery = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Feed Item Type\n * Unified activity types for the record timeline.\n * Covers comments, field changes, tasks, events, and system activities.\n */\nexport const FeedItemType = z.enum([\n 'comment',\n 'field_change',\n 'task',\n 'event',\n 'email',\n 'call',\n 'note',\n 'file',\n 'record_create',\n 'record_delete',\n 'approval',\n 'sharing',\n 'system',\n]);\nexport type FeedItemType = z.infer;\n\n/**\n * Mention Schema\n * Represents an @mention within comment body text.\n */\nexport const MentionSchema = z.object({\n type: z.enum(['user', 'team', 'record']).describe('Mention target type'),\n id: z.string().describe('Target ID'),\n name: z.string().describe('Display name for rendering'),\n offset: z.number().int().min(0).describe('Character offset in body text'),\n length: z.number().int().min(1).describe('Length of mention token in body text'),\n});\nexport type Mention = z.infer;\n\n/**\n * Field Change Entry Schema\n * Represents a single field-level change within a field_change feed item.\n */\nexport const FieldChangeEntrySchema = z.object({\n field: z.string().describe('Field machine name'),\n fieldLabel: z.string().optional().describe('Field display label'),\n oldValue: z.unknown().optional().describe('Previous value'),\n newValue: z.unknown().optional().describe('New value'),\n oldDisplayValue: z.string().optional().describe('Human-readable old value'),\n newDisplayValue: z.string().optional().describe('Human-readable new value'),\n});\nexport type FieldChangeEntry = z.infer;\n\n/**\n * Reaction Schema\n * Represents an emoji reaction on a feed item.\n */\nexport const ReactionSchema = z.object({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n userIds: z.array(z.string()).describe('Users who reacted'),\n count: z.number().int().min(1).describe('Total reaction count'),\n});\nexport type Reaction = z.infer;\n\n/**\n * Feed Actor Schema\n * Represents the actor who performed the action.\n */\nexport const FeedActorSchema = z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n avatarUrl: z.string().url().optional().describe('Actor avatar URL'),\n source: z.string().optional().describe('Source application (e.g., \"Omni\", \"API\", \"Studio\")'),\n});\nexport type FeedActor = z.infer;\n\n/**\n * Feed Item Visibility\n */\nexport const FeedVisibility = z.enum(['public', 'internal', 'private']);\nexport type FeedVisibility = z.infer;\n\n/**\n * Feed Item Schema\n * A single entry in the unified activity timeline.\n *\n * @example Comment\n * {\n * id: 'feed_001',\n * type: 'comment',\n * object: 'account',\n * recordId: 'rec_123',\n * body: 'Great progress! @jane.doe can you follow up?',\n * mentions: [{ type: 'user', id: 'user_123', name: 'Jane Doe', offset: 17, length: 9 }],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:30:00Z',\n * }\n *\n * @example Field Change\n * {\n * id: 'feed_002',\n * type: 'field_change',\n * object: 'account',\n * recordId: 'rec_123',\n * changes: [\n * { field: 'status', oldDisplayValue: 'New', newDisplayValue: 'Active' },\n * { field: 'region', oldDisplayValue: '', newDisplayValue: 'Asia-Pacific' },\n * ],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:25:00Z',\n * }\n */\nexport const FeedItemSchema = z.object({\n /** Unique identifier */\n id: z.string().describe('Feed item ID'),\n\n /** Feed item type */\n type: FeedItemType.describe('Activity type'),\n\n /** Target record reference */\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID this feed item belongs to'),\n\n /** Actor (who performed the action) */\n actor: FeedActorSchema.describe('Who performed this action'),\n\n /** Content (for comments/notes) */\n body: z.string().optional().describe('Rich text body (Markdown supported)'),\n\n /** @Mentions */\n mentions: z.array(MentionSchema).optional().describe('Mentioned users/teams/records'),\n\n /** Field changes (for field_change type) */\n changes: z.array(FieldChangeEntrySchema).optional().describe('Field-level changes'),\n\n /** Reactions */\n reactions: z.array(ReactionSchema).optional().describe('Emoji reactions on this item'),\n\n /** Reply threading */\n parentId: z.string().optional().describe('Parent feed item ID for threaded replies'),\n replyCount: z.number().int().min(0).default(0).describe('Number of replies'),\n\n /** Pin / Star */\n pinned: z.boolean().default(false).describe('Whether the feed item is pinned to the top of the timeline'),\n pinnedAt: z.string().datetime().optional().describe('Timestamp when the item was pinned'),\n pinnedBy: z.string().optional().describe('User ID who pinned the item'),\n starred: z.boolean().default(false).describe('Whether the feed item is starred/bookmarked by the current user'),\n starredAt: z.string().datetime().optional().describe('Timestamp when the item was starred'),\n\n /** Visibility */\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public (all users), internal (team only), private (author + mentioned)'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n editedAt: z.string().datetime().optional().describe('When comment was last edited'),\n isEdited: z.boolean().default(false).describe('Whether comment has been edited'),\n});\nexport type FeedItem = z.infer;\n\n/**\n * Feed Filter Mode\n * Controls which feed item types to display in the timeline.\n */\nexport const FeedFilterMode = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\nexport type FeedFilterMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Subscription Event Type\n * Event types that can be subscribed to for record-level notifications.\n */\nexport const SubscriptionEventType = z.enum([\n 'comment',\n 'mention',\n 'field_change',\n 'task',\n 'approval',\n 'all',\n]);\nexport type SubscriptionEventType = z.infer;\n\n/**\n * Notification Channel\n * Delivery channels for record subscription notifications.\n */\nexport const NotificationChannel = z.enum([\n 'in_app',\n 'email',\n 'push',\n 'slack',\n]);\nexport type NotificationChannel = z.infer;\n\n/**\n * Record Subscription Schema\n * Defines a user's subscription to record-level notifications.\n * Enables Airtable-style bell icon for record change notifications.\n */\nexport const RecordSubscriptionSchema = z.object({\n /** Target */\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n\n /** Subscriber */\n userId: z.string().describe('Subscribing user ID'),\n\n /** Events to subscribe to */\n events: z.array(SubscriptionEventType)\n .default(['all'])\n .describe('Event types to receive notifications for'),\n\n /** Notification channels */\n channels: z.array(NotificationChannel)\n .default(['in_app'])\n .describe('Notification delivery channels'),\n\n /** Active */\n active: z.boolean().default(true).describe('Whether the subscription is active'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Subscription creation timestamp'),\n});\nexport type RecordSubscription = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Turso Multi-Tenant Router Schema\n *\n * Defines the configuration for Turso DB-per-Tenant architectures where each\n * tenant receives an independent Turso/libSQL database. The router resolves\n * the correct database URL and auth token per request based on the current\n * tenant context.\n *\n * Architecture: Shared Compute + Isolated Data\n * - Serverless functions are shared across tenants\n * - Each tenant has a physically isolated Turso database\n * - Turso Platform API manages database lifecycle (create/delete/suspend)\n *\n * @see https://docs.turso.tech/features/multi-db-schemas\n */\n\n// ==========================================================================\n// 1. Tenant Resolver Strategy\n// ==========================================================================\n\n/**\n * Strategy for resolving which tenant database to connect to.\n */\nexport const TenantResolverStrategySchema = z.enum([\n 'header', // Resolve from X-Tenant-ID request header\n 'subdomain', // Resolve from subdomain (e.g., acme.app.com → acme)\n 'path', // Resolve from URL path segment (e.g., /api/acme/...)\n 'token', // Resolve from JWT claim (e.g., tenant_id in access token)\n 'lookup', // Resolve from control-plane database lookup\n]).describe('Strategy for resolving tenant identity from request context');\n\nexport type TenantResolverStrategy = z.infer;\n\n// ==========================================================================\n// 2. Turso Group Configuration\n// ==========================================================================\n\n/**\n * Turso Database Group Configuration.\n * Groups allow databases to share schema and be managed as a unit.\n * All databases in a group are deployed to the same set of locations.\n *\n * @see https://docs.turso.tech/features/multi-db-schemas\n */\nexport const TursoGroupSchema = z.object({\n /**\n * Group name identifier.\n * Used to reference the group when creating new tenant databases.\n */\n name: z.string().min(1).describe('Turso database group name'),\n\n /**\n * Primary location for the group (Turso region code).\n * Example: 'iad' (US East), 'lhr' (London), 'nrt' (Tokyo)\n */\n primaryLocation: z.string().min(2).describe('Primary Turso region code (e.g., iad, lhr, nrt)'),\n\n /**\n * Additional replica locations for read performance.\n * Databases in this group will have read replicas in these regions.\n */\n replicaLocations: z.array(z.string().min(2)).default([]).describe('Additional replica region codes'),\n\n /**\n * Schema database name within the group.\n * When using multi-db schemas, this is the \"parent\" database\n * whose schema is shared by all child (tenant) databases.\n */\n schemaDatabase: z.string().optional().describe('Schema database name for multi-db schemas'),\n}).describe('Turso database group configuration');\n\nexport type TursoGroup = z.infer;\n\n// ==========================================================================\n// 3. Tenant Database Lifecycle Hooks\n// ==========================================================================\n\n/**\n * Database Lifecycle Hook Schema.\n * Defines what happens at each tenant lifecycle event.\n */\nexport const TenantDatabaseLifecycleSchema = z.object({\n /**\n * Hook executed when a new tenant is created.\n * Defines how the tenant database is provisioned.\n */\n onTenantCreate: z.object({\n /** Whether to automatically create a Turso database */\n autoCreate: z.boolean().default(true).describe('Auto-create database on tenant registration'),\n\n /** Database group to create the database in */\n group: z.string().optional().describe('Turso group for the new database'),\n\n /** Whether to apply schema from the group schema database */\n applyGroupSchema: z.boolean().default(true).describe('Apply shared schema from group'),\n\n /** Seed data to populate on creation */\n seedData: z.boolean().default(false).describe('Populate seed data on creation'),\n }).describe('Tenant creation hook'),\n\n /**\n * Hook executed when a tenant is deleted/destroyed.\n */\n onTenantDelete: z.object({\n /** Whether to destroy the database immediately or schedule for deletion */\n immediate: z.boolean().default(false).describe('Destroy database immediately'),\n\n /** Grace period in hours before permanent deletion (soft-delete) */\n gracePeriodHours: z.number().int().min(0).default(72).describe('Grace period before permanent deletion'),\n\n /** Whether to create a final backup before deletion */\n createBackup: z.boolean().default(true).describe('Create backup before deletion'),\n }).describe('Tenant deletion hook'),\n\n /**\n * Hook executed when a tenant is suspended (e.g., unpaid, policy violation).\n */\n onTenantSuspend: z.object({\n /** Whether to revoke auth tokens on suspension */\n revokeTokens: z.boolean().default(true).describe('Revoke auth tokens on suspension'),\n\n /** Whether to set database to read-only mode */\n readOnly: z.boolean().default(true).describe('Set database to read-only on suspension'),\n }).describe('Tenant suspension hook'),\n}).describe('Tenant database lifecycle hooks');\n\nexport type TenantDatabaseLifecycle = z.infer;\n\n// ==========================================================================\n// 4. Multi-Tenant Router Configuration\n// ==========================================================================\n\n/**\n * Turso Multi-Tenant Configuration Schema.\n *\n * Configures the DB-per-Tenant router that resolves the correct Turso\n * database for each request. Works with the Turso Platform API to manage\n * database lifecycle.\n *\n * @example\n * ```ts\n * const config = TursoMultiTenantConfigSchema.parse({\n * organizationSlug: 'myorg',\n * urlTemplate: 'libsql://{tenant_id}-myorg.turso.io',\n * groupAuthToken: process.env.TURSO_GROUP_AUTH_TOKEN,\n * tenantResolverStrategy: 'token',\n * group: {\n * name: 'production',\n * primaryLocation: 'iad',\n * replicaLocations: ['lhr', 'nrt'],\n * schemaDatabase: 'schema-db',\n * },\n * lifecycle: {\n * onTenantCreate: { autoCreate: true, applyGroupSchema: true },\n * onTenantDelete: { gracePeriodHours: 168 },\n * onTenantSuspend: { revokeTokens: true },\n * },\n * });\n * ```\n */\nexport const TursoMultiTenantConfigSchema = z.object({\n /**\n * Turso organization slug.\n * Used for Platform API calls and URL construction.\n */\n organizationSlug: z.string().min(1).describe('Turso organization slug'),\n\n /**\n * URL template for constructing tenant database URLs.\n * Use `{tenant_id}` as placeholder for the tenant identifier.\n *\n * Example: 'libsql://{tenant_id}-myorg.turso.io'\n */\n urlTemplate: z.string().min(1).describe('URL template with {tenant_id} placeholder'),\n\n /**\n * Group-level auth token for Turso Platform API operations.\n * Used for database creation, deletion, and management.\n * This token has full access to all databases in the group.\n */\n groupAuthToken: z.string().min(1).describe('Group-level auth token for platform operations'),\n\n /**\n * Strategy for resolving tenant identity from the request context.\n */\n tenantResolverStrategy: TenantResolverStrategySchema.default('token'),\n\n /**\n * Turso database group configuration.\n */\n group: TursoGroupSchema.optional().describe('Database group configuration'),\n\n /**\n * Lifecycle hooks for tenant database management.\n */\n lifecycle: TenantDatabaseLifecycleSchema.optional().describe('Lifecycle hooks'),\n\n /**\n * Maximum number of cached tenant database connections.\n * Connections are evicted using LRU strategy when the limit is reached.\n */\n maxCachedConnections: z.number().int().min(1).default(100).describe('Max cached tenant connections (LRU)'),\n\n /**\n * Connection cache TTL in seconds.\n * Cached connections are refreshed after this period.\n */\n connectionCacheTTL: z.number().int().min(0).default(300).describe('Connection cache TTL in seconds'),\n}).describe('Turso multi-tenant router configuration');\n\nexport type TursoMultiTenantConfig = z.infer;\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar hash_exports = {};\n__export(hash_exports, {\n hashCode: () => hashCode\n});\nmodule.exports = __toCommonJS(hash_exports);\nconst MULTIPLIER = 16777619;\nfunction mix(h, x) {\n return h * MULTIPLIER ^ x >>> 0;\n}\nfunction hashNumber(n) {\n if (Number.isNaN(n)) return 2143289344;\n if (!Number.isFinite(n)) return n > 0 ? 2139095040 : 4286578688;\n const intPart = Math.trunc(n);\n const frac = n - intPart;\n let h = intPart | 0;\n if (frac !== 0) {\n const scaled = Math.floor(frac * 4294967296);\n h = mix(h, scaled | 0);\n }\n return h >>> 0;\n}\nfunction hashString(str) {\n let h = 0;\n for (let i = 0; i < str.length; i++) {\n h = mix(h, str.charCodeAt(i));\n }\n return h >>> 0;\n}\nfunction hashBigInt(b) {\n let h = 0;\n const isNegative = b < 0n;\n let x = isNegative ? -b : b;\n if (x === 0n) {\n h = mix(h, 0);\n } else {\n while (x > 0n) {\n const byte = Number(x & 0xffn);\n h = mix(h, byte);\n x >>= 8n;\n }\n }\n return mix(h, +isNegative) >>> 0;\n}\nfunction hashFunction(fn) {\n let h = hashString((fn.name || \"\") + fn.toString());\n h = mix(h, fn.length);\n return h >>> 0;\n}\nfunction hashBytes(bytes) {\n let h = 0;\n for (let i = 0; i < bytes.length; i++) {\n h = mix(h, bytes[i]);\n }\n return h >>> 0;\n}\nfunction hashTypedArray(view) {\n let h = hashString(view.constructor.name);\n const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n h = mix(h, hashBytes(bytes));\n return h >>> 0;\n}\nfunction hashArray(arr, seen) {\n if (seen.has(arr)) return 13 /* Cycle */;\n seen.add(arr);\n let h = 1;\n for (let i = 0; i < arr.length; i++) {\n h = mix(h, internalHash(arr[i], seen));\n }\n seen.delete(arr);\n return h >>> 0;\n}\nfunction hashObject(obj, seen) {\n if (seen.has(obj)) return 13 /* Cycle */;\n seen.add(obj);\n const keys = Object.keys(obj).sort();\n let h = hashString(obj?.constructor?.name);\n for (const k of keys) {\n h = mix(h, hashString(k));\n h = mix(h, internalHash(obj[k], seen));\n }\n seen.delete(obj);\n return h >>> 0;\n}\nconst BOOLEAN_HASH = [3735928559, 305441741].map((b) => mix(3 /* Boolean */, b));\nconst NULL_HASH = mix(1 /* Null */, 0);\nconst UNDEF_HASH = mix(2 /* Undefined */, 0);\nfunction internalHash(value, seen) {\n if (value === null) return NULL_HASH;\n const t = typeof value;\n switch (t) {\n case \"undefined\":\n return UNDEF_HASH;\n case \"boolean\":\n return BOOLEAN_HASH[+value];\n case \"number\":\n return mix(4 /* Number */, hashNumber(value));\n case \"string\":\n return mix(5 /* String */, hashString(value));\n case \"bigint\":\n return mix(6 /* BigInt */, hashBigInt(value));\n case \"function\":\n return mix(7 /* Function */, hashFunction(value));\n default: {\n if (ArrayBuffer.isView(value) && !(value instanceof DataView))\n return mix(12 /* TypedArray */, hashTypedArray(value));\n if (value instanceof Date)\n return mix(10 /* Date */, hashNumber(value.getTime()));\n if (value instanceof RegExp) {\n const h = hashString(value.source);\n return mix(11 /* RegExp */, mix(h, hashString(value.flags)));\n }\n if (Array.isArray(value)) return mix(8 /* Array */, hashArray(value, seen));\n return mix(\n 9 /* Object */,\n hashObject(value, seen)\n );\n }\n }\n}\nfunction hashCode(value) {\n return internalHash(value, /* @__PURE__ */ new WeakSet()) >>> 0;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n hashCode\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n HashMap: () => HashMap,\n MISSING: () => MISSING,\n MingoError: () => MingoError,\n PathValidator: () => PathValidator,\n assert: () => assert,\n cloneDeep: () => cloneDeep,\n compare: () => compare,\n ensureArray: () => ensureArray,\n filterMissing: () => filterMissing,\n findInsertIndex: () => findInsertIndex,\n flatten: () => flatten,\n groupBy: () => groupBy,\n has: () => has,\n hashCode: () => import_hash2.hashCode,\n intersection: () => intersection,\n isArray: () => isArray,\n isBoolean: () => isBoolean,\n isDate: () => isDate,\n isEmpty: () => isEmpty,\n isEqual: () => isEqual,\n isFunction: () => isFunction,\n isInteger: () => isInteger,\n isNil: () => isNil,\n isNumber: () => isNumber,\n isObject: () => isObject,\n isObjectLike: () => isObjectLike,\n isOperator: () => isOperator,\n isPrimitive: () => isPrimitive,\n isRegExp: () => isRegExp,\n isString: () => isString,\n isSymbol: () => isSymbol,\n normalize: () => normalize,\n removeValue: () => removeValue,\n resolve: () => resolve,\n resolveGraph: () => resolveGraph,\n setValue: () => setValue,\n simpleCmp: () => simpleCmp,\n truthy: () => truthy,\n typeOf: () => typeOf,\n unique: () => unique,\n walk: () => walk\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_hash = require(\"./_hash\");\nvar import_hash2 = require(\"./_hash\");\nclass MingoError extends Error {\n}\nconst MISSING = /* @__PURE__ */ Symbol(\"missing\");\nconst ERR_CYCLE_FOUND = \"mingo: cycle detected while processing object/array\";\nconst isPrimitive = (v) => typeof v !== \"object\" && typeof v !== \"function\" || v === null;\nconst isScalar = (v) => isPrimitive(v) || isDate(v) || isRegExp(v);\nconst SORT_ORDER = {\n undefined: 1,\n null: 2,\n number: 3,\n string: 4,\n symbol: 5,\n object: 6,\n array: 7,\n arraybuffer: 8,\n boolean: 9,\n date: 10,\n regexp: 11,\n function: 12\n};\nconst simpleCmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;\nconst typedArraysCmp = (a, b) => {\n const bytesA = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n const bytesB = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n const size = Math.min(bytesA.length, bytesB.length);\n for (let i = 0; i < size; i++) {\n const order = simpleCmp(bytesA[i], bytesB[i]);\n if (order !== 0) return order;\n }\n return simpleCmp(bytesA.length, bytesB.length);\n};\nfunction mingoCmp(a, b, descendArray = false) {\n if (a === MISSING) a = void 0;\n if (b === MISSING) b = void 0;\n if (a === b || Object.is(a, b)) return 0;\n const typeA = typeOf(a);\n const typeB = typeOf(b);\n let neq = 0;\n if (typeA === typeB) {\n switch (typeA) {\n case \"number\":\n case \"string\":\n case \"boolean\":\n return simpleCmp(a, b);\n case \"date\":\n return simpleCmp(+a, +b);\n case \"regexp\":\n if (neq = simpleCmp(a.source, b.source))\n return neq;\n return simpleCmp(a.flags, b.flags);\n case \"arraybuffer\":\n return typedArraysCmp(a, b);\n case \"array\": {\n const xs = a.slice().sort(mingoCmp);\n const ys = b.slice().sort(mingoCmp);\n const size = Math.min(xs.length, ys.length);\n for (let i = 0; i < size; i++)\n if (neq = mingoCmp(xs[i], ys[i])) return neq;\n return simpleCmp(xs.length, ys.length);\n }\n default: {\n if (typeA !== \"object\") {\n const isSameType = a?.constructor === b?.constructor;\n if (isSameType && hasCustomString(a))\n return simpleCmp(a.toString(), b.toString());\n if (neq = simpleCmp(a?.constructor?.name, b?.constructor?.name))\n return neq;\n }\n const keysA = Object.keys(a).sort();\n const keysB = Object.keys(b).sort();\n if (neq = mingoCmp(keysA, keysB)) return neq;\n for (const k of keysA)\n if (neq = mingoCmp(a[k], b[k]))\n return neq;\n return 0;\n }\n }\n }\n if (typeA == \"undefined\") return -1;\n if (typeB == \"undefined\") return 1;\n if (descendArray) {\n if (typeA == \"array\") {\n const xs = a;\n if (!xs.length) return -1;\n const sorted = xs.slice().sort(mingoCmp);\n neq = 1;\n for (const v of sorted)\n if ((neq = Math.min(neq, mingoCmp(v, b))) < 0) return neq;\n return neq;\n }\n if (typeB == \"array\") {\n const ys = b;\n if (!ys.length) return 1;\n const sorted = ys.slice().sort(mingoCmp);\n neq = -1;\n for (const v of sorted)\n if ((neq = Math.max(neq, mingoCmp(a, v))) > 0) return neq;\n return neq;\n }\n }\n const orderA = SORT_ORDER[typeA] ?? Number.MAX_VALUE;\n const orderB = SORT_ORDER[typeB] ?? Number.MAX_VALUE;\n return orderA !== orderB ? simpleCmp(orderA, orderB) : simpleCmp(typeA, typeB);\n}\nconst compare = (a, b) => mingoCmp(a, b, true);\nconst hasCustomString = (o) => o !== null && o !== void 0 && o[\"toString\"] !== Object.prototype.toString;\nfunction isEqual(a, b) {\n if (a === b || Object.is(a, b)) return true;\n if (a === null || b === null) return false;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return false;\n if (a.constructor !== b?.constructor) return false;\n if (isDate(a)) return isDate(b) && +a === +b;\n if (isRegExp(a))\n return isRegExp(b) && a.source === b.source && a.flags === b.flags;\n if (isArray(a) && isArray(b)) {\n return a.length === b.length && a.every((v, i) => isEqual(v, b[i]));\n }\n if (a?.constructor !== Object && hasCustomString(a)) {\n return a?.toString() === b?.toString();\n }\n const objA = a;\n const objB = b;\n const keysA = Object.keys(objA);\n const keysB = Object.keys(objB);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => has(objB, k) && isEqual(objA[k], objB[k]));\n}\nclass HashMap extends Map {\n // maps the hashcode to key set\n #keyMap = /* @__PURE__ */ new Map();\n // returns a tuple of [, ]. Expects an object key.\n #unpack = (key) => {\n const hash = (0, import_hash.hashCode)(key);\n const items = this.#keyMap.get(hash) ?? [];\n return [items.find((k) => isEqual(k, key)), hash];\n };\n constructor() {\n super();\n }\n /**\n * Returns a new {@link HashMap} object.\n * @param fn An optional custom hash function\n */\n static init() {\n return new HashMap();\n }\n clear() {\n super.clear();\n this.#keyMap.clear();\n }\n /**\n * @returns true if an element in the Map existed and has been removed, or false if the element does not exist.\n */\n delete(key) {\n if (isPrimitive(key)) return super.delete(key);\n const [masterKey, hash] = this.#unpack(key);\n if (!super.delete(masterKey)) return false;\n this.#keyMap.set(\n hash,\n this.#keyMap.get(hash).filter((k) => !isEqual(k, masterKey))\n );\n return true;\n }\n /**\n * Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.\n * @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.\n */\n get(key) {\n if (isPrimitive(key)) return super.get(key);\n const [masterKey, _] = this.#unpack(key);\n return super.get(masterKey);\n }\n /**\n * @returns boolean indicating whether an element with the specified key exists or not.\n */\n has(key) {\n if (isPrimitive(key)) return super.has(key);\n const [masterKey, _] = this.#unpack(key);\n return super.has(masterKey);\n }\n /**\n * Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.\n */\n set(key, value) {\n if (isPrimitive(key)) return super.set(key, value);\n const [masterKey, hash] = this.#unpack(key);\n if (super.has(masterKey)) {\n super.set(masterKey, value);\n } else {\n super.set(key, value);\n const keys = this.#keyMap.get(hash) || [];\n keys.push(key);\n this.#keyMap.set(hash, keys);\n }\n return this;\n }\n /**\n * @returns the number of elements in the Map.\n */\n get size() {\n return super.size;\n }\n}\nfunction assert(condition, msg) {\n if (!condition) throw new MingoError(msg);\n}\nfunction typeOf(v) {\n const t = typeof v;\n switch (t) {\n case \"number\":\n case \"string\":\n case \"boolean\":\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n return t;\n }\n if (v === null) return \"null\";\n if (isArray(v)) return \"array\";\n if (isDate(v)) return \"date\";\n if (isRegExp(v)) return \"regexp\";\n if (isTypedArray(v)) return \"arraybuffer\";\n if (v?.constructor === Object) return \"object\";\n return v?.constructor?.name?.toLowerCase() ?? \"object\";\n}\nconst isBoolean = (v) => typeof v === \"boolean\";\nconst isString = (v) => typeof v === \"string\";\nconst isSymbol = (v) => typeof v === \"symbol\";\nconst isNumber = (v) => !Number.isNaN(v) && typeof v === \"number\";\nconst isInteger = Number.isInteger;\nconst isArray = Array.isArray;\nconst isObject = (v) => typeOf(v) === \"object\";\nconst isObjectLike = (v) => !isPrimitive(v);\nconst isDate = (v) => v instanceof Date;\nconst isRegExp = (v) => v instanceof RegExp;\nconst isFunction = (v) => typeof v === \"function\";\nconst isNil = (v) => v === null || v === void 0;\nconst truthy = (arg, strict = true) => !!arg || strict && arg === \"\";\nconst isEmpty = (x) => isNil(x) || isString(x) && !x || isArray(x) && x.length === 0 || isObject(x) && Object.keys(x).length === 0;\nconst ensureArray = (x) => isArray(x) ? x : [x];\nconst has = (obj, ...props) => !!obj && props.every((p) => Object.prototype.hasOwnProperty.call(obj, p));\nconst isTypedArray = (v) => typeof ArrayBuffer !== \"undefined\" && ArrayBuffer.isView(v);\nconst cloneDeep = (v, refs) => {\n if (isNil(v) || isBoolean(v) || isNumber(v) || isString(v)) return v;\n if (isDate(v)) return new Date(v);\n if (isRegExp(v)) return new RegExp(v);\n if (isTypedArray(v)) {\n const ctor = v.constructor;\n return new ctor(v);\n }\n if (!(refs instanceof WeakSet)) refs = /* @__PURE__ */ new WeakSet();\n if (refs.has(v)) throw new Error(ERR_CYCLE_FOUND);\n refs.add(v);\n try {\n if (isArray(v)) {\n const arr = new Array(v.length);\n for (let i = 0; i < v.length; i++) arr[i] = cloneDeep(v[i], refs);\n return arr;\n }\n if (isObject(v)) {\n const obj = {};\n for (const k of Object.keys(v)) obj[k] = cloneDeep(v[k], refs);\n return obj;\n }\n } finally {\n refs.delete(v);\n }\n return v;\n};\nfunction intersection(input) {\n if (input.length === 0) return [];\n if (input.length === 1) return input[0].slice();\n for (const arr of input) if (arr.length === 0) return [];\n const maps = [HashMap.init(), HashMap.init()];\n let index = 0;\n for (const v of input[input.length - 1]) maps[0].set(v, true);\n for (let i = input.length - 2; i >= 0; i--) {\n for (let j = 0; j < input[i].length; j++) {\n const v = input[i][j];\n if (maps[index].has(v)) maps[index ^ 1].set(v, true);\n }\n if (maps[index ^ 1].size === 0) return [];\n maps[index].clear();\n index = index ^ 1;\n }\n return Array.from(maps[index].keys());\n}\nfunction flatten(xs, depth = 1) {\n const arr = new Array();\n function flatten2(ys, n) {\n for (let i = 0, len = ys.length; i < len; i++) {\n if (isArray(ys[i]) && (n > 0 || n < 0)) {\n flatten2(ys[i], Math.max(-1, n - 1));\n } else {\n arr.push(ys[i]);\n }\n }\n }\n flatten2(xs, depth);\n return arr;\n}\nfunction unique(input) {\n const m = HashMap.init();\n for (const v of input) m.set(v, true);\n return Array.from(m.keys());\n}\nfunction groupBy(collection, keyFunc) {\n if (collection.length < 1) return /* @__PURE__ */ new Map();\n const result = HashMap.init();\n for (let i = 0; i < collection.length; i++) {\n const obj = collection[i];\n const key = keyFunc(obj, i) ?? null;\n let a = result.get(key);\n if (!a) {\n a = [obj];\n result.set(key, a);\n } else {\n a.push(obj);\n }\n }\n return result;\n}\nfunction getValue(obj, key) {\n return isObjectLike(obj) ? obj[key] : void 0;\n}\nfunction unwrap(arr, depth) {\n if (depth < 1) return arr;\n while (depth-- && arr.length === 1 && isArray(arr[0])) arr = arr[0];\n return arr;\n}\nfunction resolve(obj, selector, options) {\n if (isScalar(obj)) return obj;\n const path = options?.pathArray ?? selector.split(\".\");\n if (path.length === 1 && !isArray(obj)) {\n return getValue(obj, path[0]);\n }\n if (path.length === 2 && !isArray(obj)) {\n const first = getValue(obj, path[0]);\n if (first == null) return void 0;\n if (!isArray(first)) return getValue(first, path[1]);\n }\n let depth = 0;\n function resolve2(o, path2) {\n let value = o;\n for (let i = 0; i < path2.length; i++) {\n const field = path2[i];\n const isText = !DIGITS_RE.test(field);\n if (isText && isArray(value)) {\n if (i === 0 && depth > 0) break;\n depth += 1;\n const subpath = path2.slice(i);\n value = value.reduce((acc, item) => {\n const v = resolve2(item, subpath);\n if (v !== void 0) acc.push(v);\n return acc;\n }, []);\n break;\n } else {\n value = getValue(value, field);\n }\n if (value === void 0) break;\n }\n return value;\n }\n const res = resolve2(obj, path);\n return isArray(res) && options?.unwrapArray ? unwrap(res, depth) : res;\n}\nfunction resolveGraph(obj, selector, options) {\n const sep = selector.indexOf(\".\");\n const key = sep == -1 ? selector : selector.substring(0, sep);\n const next = selector.substring(sep + 1);\n const hasNext = sep != -1;\n if (isArray(obj)) {\n const isIndex = /^\\d+$/.test(key);\n const arr = isIndex && options?.preserveIndex ? obj.slice() : [];\n if (isIndex) {\n const index = parseInt(key);\n let value2 = getValue(obj, index);\n if (hasNext) {\n value2 = resolveGraph(value2, next, options);\n }\n if (options?.preserveIndex) {\n arr[index] = value2;\n } else {\n arr.push(value2);\n }\n } else {\n for (const item of obj) {\n const value2 = resolveGraph(item, selector, options);\n if (options?.preserveMissing) {\n arr.push(value2 == void 0 ? MISSING : value2);\n } else if (value2 != void 0 || options?.preserveIndex) {\n arr.push(value2);\n }\n }\n }\n return arr;\n }\n const res = options?.preserveKeys ? { ...obj } : {};\n let value = getValue(obj, key);\n if (hasNext) {\n value = resolveGraph(value, next, options);\n }\n if (value === void 0) return void 0;\n res[key] = value;\n return res;\n}\nfunction filterMissing(obj) {\n if (isArray(obj)) {\n for (let i = obj.length - 1; i >= 0; i--) {\n if (obj[i] === MISSING) {\n obj.splice(i, 1);\n } else {\n filterMissing(obj[i]);\n }\n }\n } else if (isObject(obj)) {\n for (const k of Object.keys(obj)) {\n if (has(obj, k)) {\n filterMissing(obj[k]);\n }\n }\n }\n}\nconst DIGITS_RE = /^\\d+$/;\nfunction walk(obj, selector, fn, options) {\n const names = selector.split(\".\");\n const key = names[0];\n const next = names.slice(1).join(\".\");\n if (names.length === 1) {\n if (isObject(obj) || isArray(obj) && DIGITS_RE.test(key)) {\n fn(obj, key);\n }\n } else {\n if (options?.buildGraph && isNil(obj[key])) {\n obj[key] = {};\n }\n const item = obj[key];\n if (!item) return;\n const isNextArrayIndex = !!(names.length > 1 && DIGITS_RE.test(names[1]));\n if (isArray(item) && options?.descendArray && !isNextArrayIndex) {\n item.forEach(((e) => walk(e, next, fn, options)));\n } else {\n walk(item, next, fn, options);\n }\n }\n}\nfunction setValue(obj, selector, value) {\n walk(obj, selector, (item, key) => item[key] = value, {\n buildGraph: true\n });\n}\nfunction removeValue(obj, selector, options) {\n walk(\n obj,\n selector,\n ((item, key) => {\n if (isArray(item)) {\n item.splice(parseInt(key), 1);\n } else if (isObject(item)) {\n delete item[key];\n }\n }),\n options\n );\n}\nconst isOperator = (name) => !!name && name[0] === \"$\" && /^\\$[a-zA-Z0-9_]+$/.test(name);\nfunction normalize(expr) {\n if (isScalar(expr)) {\n return isRegExp(expr) ? { $regex: expr } : { $eq: expr };\n }\n if (isObjectLike(expr)) {\n if (!Object.keys(expr).some(isOperator)) return { $eq: expr };\n if (isObject(expr) && has(expr, \"$regex\")) {\n const newExpr = { ...expr };\n newExpr[\"$regex\"] = new RegExp(\n expr[\"$regex\"],\n expr[\"$options\"]\n );\n delete newExpr[\"$options\"];\n return newExpr;\n }\n }\n return expr;\n}\nfunction findInsertIndex(sorted, item, comparator = compare) {\n let lo = 0;\n let hi = sorted.length - 1;\n while (lo <= hi) {\n const mid = Math.round(lo + (hi - lo) / 2);\n if (comparator(item, sorted[mid]) < 0) {\n hi = mid - 1;\n } else if (comparator(item, sorted[mid]) > 0) {\n lo = mid + 1;\n } else {\n return mid;\n }\n }\n return lo;\n}\nclass PathValidator {\n constructor() {\n this.root = {\n children: /* @__PURE__ */ new Map(),\n isTerminal: false\n };\n }\n add(selector) {\n const parts = selector.split(\".\");\n let current = this.root;\n for (const part of parts) {\n if (current.isTerminal) return false;\n if (!current.children.has(part)) {\n current.children.set(part, {\n children: /* @__PURE__ */ new Map(),\n isTerminal: false\n });\n }\n current = current.children.get(part);\n }\n if (current.isTerminal || current.children.size) return false;\n return current.isTerminal = true;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n HashMap,\n MISSING,\n MingoError,\n PathValidator,\n assert,\n cloneDeep,\n compare,\n ensureArray,\n filterMissing,\n findInsertIndex,\n flatten,\n groupBy,\n has,\n hashCode,\n intersection,\n isArray,\n isBoolean,\n isDate,\n isEmpty,\n isEqual,\n isFunction,\n isInteger,\n isNil,\n isNumber,\n isObject,\n isObjectLike,\n isOperator,\n isPrimitive,\n isRegExp,\n isString,\n isSymbol,\n normalize,\n removeValue,\n resolve,\n resolveGraph,\n setValue,\n simpleCmp,\n truthy,\n typeOf,\n unique,\n walk\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar util_exports = {};\n__export(util_exports, {\n HashMap: () => import_internal.HashMap,\n MingoError: () => import_internal.MingoError,\n assert: () => import_internal.assert,\n cloneDeep: () => import_internal.cloneDeep,\n compare: () => import_internal.compare,\n ensureArray: () => import_internal.ensureArray,\n findInsertIndex: () => import_internal.findInsertIndex,\n flatten: () => import_internal.flatten,\n groupBy: () => import_internal.groupBy,\n has: () => import_internal.has,\n hashCode: () => import_internal.hashCode,\n intersection: () => import_internal.intersection,\n isArray: () => import_internal.isArray,\n isBoolean: () => import_internal.isBoolean,\n isDate: () => import_internal.isDate,\n isEmpty: () => import_internal.isEmpty,\n isEqual: () => import_internal.isEqual,\n isFunction: () => import_internal.isFunction,\n isInteger: () => import_internal.isInteger,\n isNil: () => import_internal.isNil,\n isNumber: () => import_internal.isNumber,\n isObject: () => import_internal.isObject,\n isObjectLike: () => import_internal.isObjectLike,\n isOperator: () => import_internal.isOperator,\n isRegExp: () => import_internal.isRegExp,\n isString: () => import_internal.isString,\n isSymbol: () => import_internal.isSymbol,\n normalize: () => import_internal.normalize,\n removeValue: () => import_internal.removeValue,\n resolve: () => import_internal.resolve,\n setValue: () => import_internal.setValue,\n typeOf: () => import_internal.typeOf,\n unique: () => import_internal.unique\n});\nmodule.exports = __toCommonJS(util_exports);\nvar import_internal = require(\"./_internal\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n HashMap,\n MingoError,\n assert,\n cloneDeep,\n compare,\n ensureArray,\n findInsertIndex,\n flatten,\n groupBy,\n has,\n hashCode,\n intersection,\n isArray,\n isBoolean,\n isDate,\n isEmpty,\n isEqual,\n isFunction,\n isInteger,\n isNil,\n isNumber,\n isObject,\n isObjectLike,\n isOperator,\n isRegExp,\n isString,\n isSymbol,\n normalize,\n removeValue,\n resolve,\n setValue,\n typeOf,\n unique\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n ComputeOptions: () => ComputeOptions,\n Context: () => Context,\n OpType: () => OpType,\n ProcessingMode: () => ProcessingMode,\n computeValue: () => computeValue,\n evalExpr: () => evalExpr\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../util\");\nvar ProcessingMode = /* @__PURE__ */ ((ProcessingMode2) => {\n ProcessingMode2[ProcessingMode2[\"CLONE_OFF\"] = 0] = \"CLONE_OFF\";\n ProcessingMode2[ProcessingMode2[\"CLONE_INPUT\"] = 1] = \"CLONE_INPUT\";\n ProcessingMode2[ProcessingMode2[\"CLONE_OUTPUT\"] = 2] = \"CLONE_OUTPUT\";\n ProcessingMode2[ProcessingMode2[\"CLONE_ALL\"] = 3] = \"CLONE_ALL\";\n return ProcessingMode2;\n})(ProcessingMode || {});\nclass ComputeOptions {\n constructor(options, locals) {\n this.options = options;\n this.#locals = locals ? { ...locals } : {};\n }\n #locals;\n /**\n * Initializes a new instance of the `ComputeOptions` class with the provided options.\n *\n * @param options - A partial set of options to configure the `ComputeOptions` instance.\n * If an instance of `ComputeOptions` is provided, its internal options and locals are used.\n * @returns A new `ComputeOptions` instance configured with the provided options and root.\n */\n static init(options) {\n return options instanceof ComputeOptions ? new ComputeOptions(options.options, options.#locals) : new ComputeOptions({\n idKey: \"_id\",\n scriptEnabled: true,\n useStrictMode: true,\n failOnError: true,\n processingMode: 0 /* CLONE_OFF */,\n ...options,\n context: options?.context ? Context.from(options?.context) : Context.init()\n });\n }\n update(locals) {\n Object.assign(this.#locals, locals, {\n // DO NOT override timestamp\n timestamp: this.#locals.timestamp,\n // merge variables.\n variables: { ...this.#locals?.variables, ...locals?.variables }\n });\n return this;\n }\n get local() {\n return this.#locals;\n }\n get now() {\n let timestamp = this.#locals.timestamp ?? 0;\n if (!timestamp) {\n timestamp = Date.now();\n Object.assign(this.#locals, { timestamp });\n }\n return new Date(timestamp);\n }\n get idKey() {\n return this.options.idKey;\n }\n get collation() {\n return this.options?.collation;\n }\n get processingMode() {\n return this.options?.processingMode;\n }\n get useStrictMode() {\n return this.options?.useStrictMode;\n }\n get scriptEnabled() {\n return this.options?.scriptEnabled;\n }\n get failOnError() {\n return this.options?.failOnError;\n }\n get collectionResolver() {\n return this.options?.collectionResolver;\n }\n get jsonSchemaValidator() {\n return this.options?.jsonSchemaValidator;\n }\n get variables() {\n return this.options?.variables;\n }\n get context() {\n return this.options?.context;\n }\n}\nvar OpType = /* @__PURE__ */ ((OpType2) => {\n OpType2[\"ACCUMULATOR\"] = \"accumulator\";\n OpType2[\"EXPRESSION\"] = \"expression\";\n OpType2[\"PIPELINE\"] = \"pipeline\";\n OpType2[\"PROJECTION\"] = \"projection\";\n OpType2[\"QUERY\"] = \"query\";\n OpType2[\"WINDOW\"] = \"window\";\n return OpType2;\n})(OpType || {});\nclass Context {\n #operators;\n constructor() {\n this.#operators = {\n [\"accumulator\" /* ACCUMULATOR */]: {},\n [\"expression\" /* EXPRESSION */]: {},\n [\"pipeline\" /* PIPELINE */]: {},\n [\"projection\" /* PROJECTION */]: {},\n [\"query\" /* QUERY */]: {},\n [\"window\" /* WINDOW */]: {}\n };\n }\n static init(ops = {}) {\n const ctx = new Context();\n for (const type of Object.keys(ops)) {\n ctx.#operators[type] = { ...ops[type] };\n }\n return ctx;\n }\n /** Returns a new context with the operators from the provided contexts merged left to right. */\n static from(...ctx) {\n if (ctx.length === 1) return Context.init(ctx[0].#operators);\n const newCtx = new Context();\n for (const context of ctx) {\n for (const type of Object.values(OpType)) {\n newCtx.addOps(type, context.#operators[type]);\n }\n }\n return newCtx;\n }\n addOps(type, operators) {\n this.#operators[type] = Object.assign({}, operators, this.#operators[type]);\n return this;\n }\n getOperator(type, name) {\n return this.#operators[type][name] ?? null;\n }\n addAccumulatorOps(ops) {\n return this.addOps(\"accumulator\" /* ACCUMULATOR */, ops);\n }\n addExpressionOps(ops) {\n return this.addOps(\"expression\" /* EXPRESSION */, ops);\n }\n addQueryOps(ops) {\n return this.addOps(\"query\" /* QUERY */, ops);\n }\n addPipelineOps(ops) {\n return this.addOps(\"pipeline\" /* PIPELINE */, ops);\n }\n addProjectionOps(ops) {\n return this.addOps(\"projection\" /* PROJECTION */, ops);\n }\n addWindowOps(ops) {\n return this.addOps(\"window\" /* WINDOW */, ops);\n }\n}\nfunction computeValue(obj, expr, operator, options) {\n return evalExpr(obj, { [operator]: expr }, options);\n}\nfunction evalExpr(obj, expr, options) {\n const copts = !(options instanceof ComputeOptions) || (0, import_util.isNil)(options.local.root) ? ComputeOptions.init(options).update({ root: obj }) : options;\n return computeExpression(obj, expr, copts);\n}\nconst SYSTEM_VARS = /* @__PURE__ */ new Set([\"$$ROOT\", \"$$CURRENT\", \"$$REMOVE\", \"$$NOW\"]);\nfunction computeExpression(obj, expr, options) {\n if ((0, import_util.isString)(expr) && expr.length > 0 && expr[0] === \"$\") {\n if (expr === \"$$KEEP\" || expr === \"$$PRUNE\" || expr === \"$$DESCEND\")\n return expr;\n let ctx = options.local.root;\n const arr = expr.split(\".\");\n const dotIdx = expr.indexOf(\".\");\n const prefix = dotIdx === -1 ? expr : expr.substring(0, dotIdx);\n if (SYSTEM_VARS.has(arr[0])) {\n switch (prefix) {\n case \"$$ROOT\":\n break;\n case \"$$CURRENT\":\n ctx = obj;\n break;\n case \"$$REMOVE\":\n ctx = void 0;\n break;\n case \"$$NOW\":\n ctx = new Date(options.now);\n break;\n }\n expr = dotIdx === -1 ? \"\" : expr.substring(dotIdx + 1);\n } else if (prefix.length >= 2 && prefix[1] === \"$\") {\n ctx = Object.assign(\n {},\n // global vars\n options.variables,\n // current item is added before local variables because the binding may be changed.\n { this: obj },\n // local vars\n options?.local?.variables\n );\n const name = prefix.substring(2);\n (0, import_util.assert)((0, import_util.has)(ctx, name), `Use of undefined variable: ${name}`);\n expr = expr.substring(2);\n } else {\n expr = expr.substring(1);\n }\n return expr === \"\" ? ctx : (0, import_util.resolve)(ctx, expr);\n }\n if ((0, import_util.isArray)(expr)) {\n return expr.map((item) => computeExpression(obj, item, options));\n }\n if ((0, import_util.isObject)(expr)) {\n const keys = Object.keys(expr);\n if ((0, import_util.isOperator)(keys[0])) {\n (0, import_util.assert)(keys.length === 1, \"Expression must contain a single operator.\");\n return computeOperator(obj, expr[keys[0]], keys[0], options);\n }\n const result = {};\n for (let i = 0; i < keys.length; i++) {\n result[keys[i]] = computeExpression(obj, expr[keys[i]], options);\n }\n return result;\n }\n return expr;\n}\nfunction computeOperator(obj, expr, operator, options) {\n const context = options.context;\n const fn = context.getOperator(\"expression\" /* EXPRESSION */, operator);\n if (fn) return fn(obj, expr, options);\n const accFn = context.getOperator(\"accumulator\" /* ACCUMULATOR */, operator);\n (0, import_util.assert)(!!accFn, `accumulator '${operator}' is not registered.`);\n if (!(0, import_util.isArray)(obj)) {\n obj = computeExpression(obj, expr, options);\n expr = null;\n }\n (0, import_util.assert)((0, import_util.isArray)(obj), `arguments must resolve to array for ${operator}.`);\n return accFn(obj, expr, options);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ComputeOptions,\n Context,\n OpType,\n ProcessingMode,\n computeValue,\n evalExpr\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lazy_exports = {};\n__export(lazy_exports, {\n Iterator: () => Iterator,\n Lazy: () => Lazy,\n concat: () => concat\n});\nmodule.exports = __toCommonJS(lazy_exports);\nvar import_util = require(\"./util\");\nfunction Lazy(source) {\n return new Iterator(source);\n}\nfunction concat(...iterators) {\n let index = 0;\n return Lazy(() => {\n while (index < iterators.length) {\n const o = iterators[index].next();\n if (!o.done) return o;\n index++;\n }\n return { done: true, value: void 0 };\n });\n}\nfunction isGenerator(o) {\n return !!o && typeof o === \"object\" && typeof o?.next === \"function\";\n}\nfunction isIterable(o) {\n return !!o && (typeof o === \"object\" || typeof o === \"function\") && typeof o[Symbol.iterator] === \"function\";\n}\nclass Iterator {\n #iteratees = [];\n #buffer = [];\n #getNext;\n #done = false;\n constructor(source) {\n let iter;\n if (isIterable(source))\n iter = source[Symbol.iterator]();\n else if (isGenerator(source)) iter = source;\n else if (typeof source === \"function\") iter = { next: source };\n else\n (0, import_util.assert)(0, \"mingo: iterator requires an iterable, generator or function\");\n let index = -1;\n this.#getNext = () => {\n while (true) {\n let { value, done } = iter.next();\n if (done) return { done };\n let ok = true;\n index++;\n for (let i = 0; i < this.#iteratees.length; i++) {\n const { op, fn } = this.#iteratees[i];\n const res = fn(value, index);\n if (op === \"map\") {\n value = res;\n } else if (!res) {\n ok = false;\n break;\n }\n }\n if (ok) return { value, done };\n }\n };\n }\n /**\n * Add an iteratee to this lazy sequence\n */\n push(op, fn) {\n this.#iteratees.push({ op, fn });\n return this;\n }\n next() {\n return this.#getNext();\n }\n // Iteratees methods\n /**\n * Transform each item in the sequence to a new value\n * @param {Function} f\n */\n map(f) {\n return this.push(\"map\", f);\n }\n /**\n * Select only items matching the given predicate\n * @param {Function} f\n */\n filter(f) {\n return this.push(\"filter\", f);\n }\n /**\n * Take given numbe for values from sequence\n * @param {Number} n A number greater than 0\n */\n take(n) {\n (0, import_util.assert)(n >= 0, \"value must be a non-negative integer\");\n return this.filter((_) => n-- > 0);\n }\n /**\n * Drop a number of values from the sequence\n * @param {Number} n Number of items to drop greater than 0\n */\n drop(n) {\n (0, import_util.assert)(n >= 0, \"value must be a non-negative integer\");\n return this.filter((_) => n-- <= 0);\n }\n // Transformations\n /**\n * Returns a new lazy object with results of the transformation\n * The entire sequence is realized.\n *\n * @param {Callback} f Tranform function of type (Array) => (Any)\n */\n transform(f) {\n const self = this;\n let iter;\n return Lazy(() => {\n if (!iter) iter = f(self.collect());\n return iter.next();\n });\n }\n /**\n * Retrieves all remaining values from the lazy evaluation and returns them as an array.\n * This method processes the underlying iterator until it is exhausted, storing the results\n * in an internal buffer to ensure subsequent calls return the same data.\n */\n collect() {\n while (!this.#done) {\n const { done, value } = this.#getNext();\n if (!done) this.#buffer.push(value);\n this.#done = done;\n }\n return this.#buffer;\n }\n /**\n * Execute the callback for each value.\n * @param f The callback function.\n */\n each(f) {\n for (let o = this.next(); o.done !== true; o = this.next()) f(o.value);\n }\n /**\n * Returns the reduction of sequence according the reducing function\n *\n * @param f The reducing function\n * @param initialValue The initial value\n */\n reduce(f, initialValue) {\n let o = this.next();\n if (initialValue === void 0 && !o.done) {\n initialValue = o.value;\n o = this.next();\n }\n while (!o.done) {\n initialValue = f(initialValue, o.value);\n o = this.next();\n }\n return initialValue;\n }\n /**\n * Returns the number of matched items in the sequence.\n * The stream is realized and buffered for later retrieval with {@link collect}.\n */\n size() {\n return this.collect().length;\n }\n [Symbol.iterator]() {\n return this;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Iterator,\n Lazy,\n concat\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar aggregator_exports = {};\n__export(aggregator_exports, {\n Aggregator: () => Aggregator\n});\nmodule.exports = __toCommonJS(aggregator_exports);\nvar import_internal = require(\"./core/_internal\");\nvar import_lazy = require(\"./lazy\");\nvar import_util = require(\"./util\");\nclass Aggregator {\n #pipeline;\n #options;\n /**\n * Creates an instance of the Aggregator class.\n *\n * @param pipeline - An array of objects representing the aggregation pipeline stages.\n * @param options - Optional configuration settings for the aggregator.\n */\n constructor(pipeline, options) {\n this.#pipeline = pipeline;\n this.#options = import_internal.ComputeOptions.init(options);\n }\n /**\n * Processes a collection through an aggregation pipeline and returns an iterator\n * for the transformed results.\n *\n * @param collection - The input collection to process. This can be any source\n * that implements the `Source` interface.\n * @param options - Optional configuration for processing. If not provided, the\n * default options of the aggregator instance will be used.\n * @returns An iterator that yields the results of the aggregation pipeline.\n *\n * @throws Will throw an error if:\n * - A pipeline stage contains more than one operator.\n * - The `$documents` operator is not the first stage in the pipeline.\n * - An unregistered pipeline operator is encountered.\n */\n stream(collection, options) {\n let iter = (0, import_lazy.Lazy)(collection);\n const opts = options ?? this.#options;\n const mode = opts.processingMode;\n if (mode & import_internal.ProcessingMode.CLONE_INPUT) iter.map((o) => (0, import_util.cloneDeep)(o));\n iter = this.#pipeline.map((stage, i) => {\n const keys = Object.keys(stage);\n (0, import_util.assert)(\n keys.length === 1,\n `aggregation stage must have single operator, got ${keys.toString()}.`\n );\n const name = keys[0];\n (0, import_util.assert)(\n name !== \"$documents\" || i == 0,\n \"$documents must be first stage in pipeline.\"\n );\n const op = opts.context.getOperator(import_internal.OpType.PIPELINE, name);\n (0, import_util.assert)(!!op, `unregistered pipeline operator ${name}.`);\n return [op, stage[name]];\n }).reduce((acc, [op, expr]) => op(acc, expr, opts), iter);\n if (mode & import_internal.ProcessingMode.CLONE_OUTPUT) iter.map((o) => (0, import_util.cloneDeep)(o));\n return iter;\n }\n /**\n * Executes the aggregation pipeline on the provided collection and returns the resulting array.\n *\n * @template T - The type of the objects in the resulting array.\n * @param collection - The input data source to run the aggregation on.\n * @param options - Optional settings to customize the aggregation behavior.\n * @returns An array of objects of type `T` resulting from the aggregation.\n */\n run(collection, options) {\n return this.stream(collection, options).collect();\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Aggregator\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar push_exports = {};\n__export(push_exports, {\n $push: () => $push\n});\nmodule.exports = __toCommonJS(push_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nconst $push = (coll, expr, options) => {\n if ((0, import_util.isNil)(expr)) return coll;\n const copts = import_internal.ComputeOptions.init(options);\n const result = new Array(coll.length);\n for (let i = 0; i < coll.length; i++) {\n const root = coll[i];\n result[i] = (0, import_internal.evalExpr)(root, expr, copts.update({ root })) ?? null;\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $push\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar accumulator_exports = {};\n__export(accumulator_exports, {\n $accumulator: () => $accumulator\n});\nmodule.exports = __toCommonJS(accumulator_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $accumulator = (coll, expr, options) => {\n (0, import_util.assert)(\n options.scriptEnabled,\n \"$accumulator requires 'scriptEnabled' option to be true\"\n );\n const copts = import_internal.ComputeOptions.init(options);\n const input = expr;\n const initArgs = (0, import_internal.evalExpr)(\n copts?.local?.groupId,\n input.initArgs || [],\n copts.update({ root: copts?.local?.groupId })\n );\n const args = (0, import_push.$push)(coll, input.accumulateArgs, copts);\n for (let i = 0; i < args.length; i++) {\n for (let j = 0; j < args[i].length; j++) {\n args[i][j] = args[i][j] ?? null;\n }\n }\n const initialValue = input.init.apply(null, initArgs);\n const f = input.accumulate;\n let result = initialValue;\n for (let i = 0; i < args.length; i++) {\n result = f.apply(null, [result, ...args[i]]);\n }\n if (input.finalize) result = input.finalize.call(null, result);\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $accumulator\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar addToSet_exports = {};\n__export(addToSet_exports, {\n $addToSet: () => $addToSet\n});\nmodule.exports = __toCommonJS(addToSet_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $addToSet = (coll, expr, options) => (0, import_util.unique)((0, import_push.$push)(coll, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $addToSet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar avg_exports = {};\n__export(avg_exports, {\n $avg: () => $avg\n});\nmodule.exports = __toCommonJS(avg_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $avg = (coll, expr, options) => {\n const data = (0, import_push.$push)(coll, expr, options).filter(import_util.isNumber);\n if (data.length === 0) return null;\n const sum = data.reduce((acc, n) => acc + n, 0);\n return sum / data.length;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $avg\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sort_exports = {};\n__export(sort_exports, {\n $sort: () => $sort\n});\nmodule.exports = __toCommonJS(sort_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $sort(coll, sortKeys, options) {\n (0, import_util.assert)(\n (0, import_util.isObject)(sortKeys) && Object.keys(sortKeys).length > 0,\n \"$sort specification is invalid\"\n );\n let cmp = import_util.compare;\n const collationSpec = options.collation;\n if ((0, import_util.isObject)(collationSpec) && (0, import_util.isString)(collationSpec.locale)) {\n cmp = collationComparator(collationSpec);\n }\n return coll.transform((coll2) => {\n const modifiers = Object.keys(sortKeys);\n for (const key of modifiers.reverse()) {\n const groups = (0, import_util.groupBy)(coll2, (obj) => (0, import_util.resolve)(obj, key));\n const sortedKeys = Array.from(groups.keys());\n let nativeSorted = false;\n if (cmp === import_util.compare) {\n let t_str = true;\n let t_num = true;\n for (const v of sortedKeys) {\n t_str &&= (0, import_util.isString)(v);\n t_num &&= (0, import_util.isNumber)(v);\n if (!t_str && !t_num) break;\n }\n nativeSorted = t_str || t_num;\n if (t_str) sortedKeys.sort();\n else if (t_num) {\n const numbers = new Float64Array(sortedKeys).sort();\n for (let i2 = 0; i2 < numbers.length; i2++) {\n sortedKeys[i2] = numbers[i2];\n }\n }\n }\n if (!nativeSorted) sortedKeys.sort(cmp);\n if (sortKeys[key] === -1) sortedKeys.reverse();\n let i = 0;\n for (const k of sortedKeys) for (const v of groups.get(k)) coll2[i++] = v;\n (0, import_util.assert)(i == coll2.length, \"bug: counter must match collection size.\");\n }\n return (0, import_lazy.Lazy)(coll2);\n });\n}\nconst COLLATION_STRENGTH = {\n // Only strings that differ in base letters compare as unequal. Examples: a \u2260 b, a = \u00E1, a = A.\n 1: \"base\",\n // Only strings that differ in base letters or accents and other diacritic marks compare as unequal.\n // Examples: a \u2260 b, a \u2260 \u00E1, a = A.\n 2: \"accent\",\n // Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal.\n // Other differences may also be taken into consideration. Examples: a \u2260 b, a \u2260 \u00E1, a \u2260 A\n 3: \"variant\"\n // case - Only strings that differ in base letters or case compare as unequal. Examples: a \u2260 b, a = \u00E1, a \u2260 A.\n};\nfunction collationComparator(spec) {\n const localeOpt = {\n sensitivity: COLLATION_STRENGTH[spec.strength || 3],\n caseFirst: spec.caseFirst === \"off\" ? \"false\" : spec.caseFirst,\n numeric: spec.numericOrdering || false,\n ignorePunctuation: spec.alternate === \"shifted\"\n };\n if (spec.caseLevel === true) {\n if (localeOpt.sensitivity === \"base\") localeOpt.sensitivity = \"case\";\n if (localeOpt.sensitivity === \"accent\") localeOpt.sensitivity = \"variant\";\n }\n const collator = new Intl.Collator(spec.locale, localeOpt);\n return (a, b) => (0, import_util.isString)(a) && (0, import_util.isString)(b) ? collator.compare(a, b) : (0, import_util.compare)(a, b);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sort\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bottomN_exports = {};\n__export(bottomN_exports, {\n $bottomN: () => $bottomN\n});\nmodule.exports = __toCommonJS(bottomN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_sort = require(\"../pipeline/sort\");\nvar import_push = require(\"./push\");\nconst $bottomN = (coll, expr, options) => {\n const copts = options;\n const args = expr;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, args.n, copts);\n const result = (0, import_sort.$sort)((0, import_lazy.Lazy)(coll), args.sortBy, options).collect();\n const m = result.length;\n return (0, import_push.$push)(m <= n ? result : result.slice(m - n), args.output, copts);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bottomN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bottom_exports = {};\n__export(bottom_exports, {\n $bottom: () => $bottom\n});\nmodule.exports = __toCommonJS(bottom_exports);\nvar import_bottomN = require(\"./bottomN\");\nconst $bottom = (coll, expr, options) => {\n return (0, import_bottomN.$bottomN)(coll, { ...expr, n: 1 }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bottom\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar count_exports = {};\n__export(count_exports, {\n $count: () => $count\n});\nmodule.exports = __toCommonJS(count_exports);\nconst $count = (coll, _expr, _opts) => coll.length;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $count\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n covariance: () => covariance,\n stddev: () => stddev\n});\nmodule.exports = __toCommonJS(internal_exports);\nfunction stddev(data, sampled = true) {\n const sum = data.reduce((acc, n) => acc + n, 0);\n const N = Math.max(data.length, 1);\n const avg = sum / N;\n return Math.sqrt(\n data.reduce((acc, n) => acc + Math.pow(n - avg, 2), 0) / (N - Number(sampled))\n );\n}\nfunction covariance(dataset, sampled = true) {\n if (dataset.length < 2) return sampled ? null : 0;\n let meanX = 0;\n let meanY = 0;\n for (const [x, y] of dataset) {\n meanX += x;\n meanY += y;\n }\n meanX /= dataset.length;\n meanY /= dataset.length;\n let result = 0;\n for (const [x, y] of dataset) {\n result += (x - meanX) * (y - meanY);\n }\n return result / (dataset.length - Number(sampled));\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n covariance,\n stddev\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar covariancePop_exports = {};\n__export(covariancePop_exports, {\n $covariancePop: () => $covariancePop\n});\nmodule.exports = __toCommonJS(covariancePop_exports);\nvar import_internal = require(\"./_internal\");\nvar import_push = require(\"./push\");\nconst $covariancePop = (coll, expr, options) => (0, import_internal.covariance)((0, import_push.$push)(coll, expr, options), false);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $covariancePop\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar covarianceSamp_exports = {};\n__export(covarianceSamp_exports, {\n $covarianceSamp: () => $covarianceSamp\n});\nmodule.exports = __toCommonJS(covarianceSamp_exports);\nvar import_internal = require(\"./_internal\");\nvar import_push = require(\"./push\");\nconst $covarianceSamp = (coll, expr, options) => (0, import_internal.covariance)((0, import_push.$push)(coll, expr, options), true);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $covarianceSamp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar first_exports = {};\n__export(first_exports, {\n $first: () => $first\n});\nmodule.exports = __toCommonJS(first_exports);\nvar import_internal = require(\"../../core/_internal\");\nconst $first = (coll, expr, options) => {\n const obj = coll[0];\n const copts = import_internal.ComputeOptions.init(options).update({ root: obj });\n return (0, import_internal.evalExpr)(obj, expr, copts) ?? null;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $first\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n ARR_OPTS: () => ARR_OPTS,\n INT_OPTS: () => INT_OPTS,\n errExpectArray: () => errExpectArray,\n errExpectNumber: () => errExpectNumber,\n errExpectObject: () => errExpectObject,\n errExpectString: () => errExpectString,\n errInvalidArgs: () => errInvalidArgs\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../../util\");\nconst INT_OPTS = {\n int: { int: true },\n // (-\u221E, \u221E)\n pos: { min: 1, int: true },\n // [1, \u221E]\n index: { min: 0, int: true },\n // [0, \u221E]\n nzero: { min: 0, max: 0, int: true }\n // non-zero\n};\nconst ARR_OPTS = {\n int: { type: \"integers\" },\n obj: { type: \"objects\" }\n};\nfunction errInvalidArgs(failOnError, message) {\n (0, import_util.assert)(!failOnError, message);\n return null;\n}\nfunction errExpectObject(failOnError, prefix) {\n const msg = `${prefix} expression must resolve to object`;\n (0, import_util.assert)(!failOnError, msg);\n return null;\n}\nfunction errExpectString(failOnError, prefix) {\n const msg = `${prefix} expression must resolve to string`;\n (0, import_util.assert)(!failOnError, msg);\n return null;\n}\nfunction errExpectNumber(failOnError, name, opts) {\n const type = opts?.int ? \"integer\" : \"number\";\n const min = opts?.min ?? -Infinity;\n const max = opts?.max ?? Infinity;\n let msg;\n if (min === 0 && max === 0) {\n msg = `${name} expression must resolve to non-zero ${type}`;\n } else if (min === 0 && max === Infinity) {\n msg = `${name} expression must resolve to non-negative ${type}`;\n } else if (min !== -Infinity && max !== Infinity) {\n msg = `${name} expression must resolve to ${type} in range [${min}, ${max}]`;\n } else if (min > 0) {\n msg = `${name} expression must resolve to positive ${type}`;\n } else {\n msg = `${name} expression must resolve to ${type}`;\n }\n (0, import_util.assert)(!failOnError, msg);\n return null;\n}\nfunction errExpectArray(failOnError, prefix, opts) {\n let suffix = \"array\";\n if (!(0, import_util.isNil)(opts?.size) && opts?.size >= 0)\n suffix = opts.size === 0 ? \"non-zero array\" : `array(${opts.size})`;\n if (opts?.type) suffix = `array of ${opts.type}`;\n const msg = `${prefix} expression must resolve to ${suffix}`;\n (0, import_util.assert)(!failOnError, msg);\n return null;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ARR_OPTS,\n INT_OPTS,\n errExpectArray,\n errExpectNumber,\n errExpectObject,\n errExpectString,\n errInvalidArgs\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar firstN_exports = {};\n__export(firstN_exports, {\n $firstN: () => $firstN\n});\nmodule.exports = __toCommonJS(firstN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $firstN = (coll, expr, options) => {\n const foe = options.failOnError;\n const copts = options;\n const m = coll.length;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts);\n if (!(0, import_util.isInteger)(n) || n < 1)\n return (0, import_internal2.errExpectNumber)(foe, \"$firstN 'n'\", import_internal2.INT_OPTS.pos);\n return (0, import_push.$push)(m <= n ? coll : coll.slice(0, n), expr.input, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $firstN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar last_exports = {};\n__export(last_exports, {\n $last: () => $last\n});\nmodule.exports = __toCommonJS(last_exports);\nvar import_internal = require(\"../../core/_internal\");\nconst $last = (coll, expr, options) => {\n const obj = coll[coll.length - 1];\n const copts = import_internal.ComputeOptions.init(options).update({ root: obj });\n return (0, import_internal.evalExpr)(obj, expr, copts) ?? null;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $last\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lastN_exports = {};\n__export(lastN_exports, {\n $lastN: () => $lastN\n});\nmodule.exports = __toCommonJS(lastN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $lastN = (coll, expr, options) => {\n const copts = options;\n const m = coll.length;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts);\n const foe = options.failOnError;\n if (!(0, import_util.isInteger)(n) || n < 1) {\n return (0, import_internal2.errExpectNumber)(foe, \"$lastN 'n'\", import_internal2.INT_OPTS.pos);\n }\n return (0, import_push.$push)(m <= n ? coll : coll.slice(m - n), expr.input, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lastN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar max_exports = {};\n__export(max_exports, {\n $max: () => $max\n});\nmodule.exports = __toCommonJS(max_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $max = (coll, expr, options) => {\n const items = (0, import_push.$push)(coll, expr, options).filter((v) => !(0, import_util.isNil)(v));\n if (!items.length) return null;\n return items.reduce((r, v) => (0, import_util.compare)(r, v) >= 0 ? r : v);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $max\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar maxN_exports = {};\n__export(maxN_exports, {\n $maxN: () => $maxN\n});\nmodule.exports = __toCommonJS(maxN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $maxN = (coll, expr, options) => {\n const copts = options;\n const m = coll.length;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts);\n if (!(0, import_util.isInteger)(n) || n < 1) {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$maxN 'n'\", import_internal2.INT_OPTS.pos);\n }\n const arr = (0, import_push.$push)(coll, expr.input, options).filter((o) => !(0, import_util.isNil)(o));\n arr.sort((a, b) => -1 * (0, import_util.compare)(a, b));\n return m <= n ? arr : arr.slice(0, n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $maxN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar percentile_exports = {};\n__export(percentile_exports, {\n $percentile: () => $percentile\n});\nmodule.exports = __toCommonJS(percentile_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $percentile = (coll, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"p\") && (0, import_util.isArray)(expr.p),\n \"$percentile expects object { input, p }\"\n );\n const X = (0, import_push.$push)(coll, expr.input, options).filter(import_util.isNumber).sort();\n const centiles = (0, import_push.$push)(expr.p, \"$$CURRENT\", options);\n const method = expr.method || \"approximate\";\n for (const n of centiles) {\n if (!(0, import_util.isNumber)(n) || n < 0 || n > 1) {\n return (0, import_internal.errInvalidArgs)(\n options.failOnError,\n \"$percentile 'p' must resolve to array of numbers between [0.0, 1.0]\"\n );\n }\n }\n return centiles.map((p) => {\n const r = p * (X.length - 1) + 1;\n const ri = Math.floor(r);\n const result = r === ri ? X[r - 1] : X[ri - 1] + r % 1 * (X[ri] - X[ri - 1]);\n switch (method) {\n case \"exact\":\n return result;\n case \"approximate\": {\n const i = (0, import_util.findInsertIndex)(X, result);\n return i / X.length >= p ? X[Math.max(i - 1, 0)] : X[i];\n }\n }\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $percentile\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar median_exports = {};\n__export(median_exports, {\n $median: () => $median\n});\nmodule.exports = __toCommonJS(median_exports);\nvar import_percentile = require(\"./percentile\");\nconst $median = (coll, expr, options) => (0, import_percentile.$percentile)(coll, { ...expr, p: [0.5] }, options)?.pop();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $median\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mergeObjects_exports = {};\n__export(mergeObjects_exports, {\n $mergeObjects: () => $mergeObjects\n});\nmodule.exports = __toCommonJS(mergeObjects_exports);\nvar import_util = require(\"../../util\");\nconst $mergeObjects = (coll, _expr, _options) => {\n const acc = {};\n for (const o of coll) {\n if ((0, import_util.isNil)(o)) continue;\n for (const k of Object.keys(o)) {\n if (o[k] !== void 0) acc[k] = o[k];\n }\n }\n return acc;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mergeObjects\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar min_exports = {};\n__export(min_exports, {\n $min: () => $min\n});\nmodule.exports = __toCommonJS(min_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $min = (coll, expr, options) => {\n const items = (0, import_push.$push)(coll, expr, options).filter((v) => !(0, import_util.isNil)(v));\n if (!items.length) return null;\n return items.reduce((r, v) => (0, import_util.compare)(r, v) <= 0 ? r : v);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $min\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar minN_exports = {};\n__export(minN_exports, {\n $minN: () => $minN\n});\nmodule.exports = __toCommonJS(minN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $minN = (coll, expr, options) => {\n const copts = options;\n const m = coll.length;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts);\n if (!(0, import_util.isInteger)(n) || n < 1) {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$minN 'n'\", import_internal2.INT_OPTS.pos);\n }\n const arr = (0, import_push.$push)(coll, expr.input, options).filter((o) => !(0, import_util.isNil)(o));\n arr.sort(import_util.compare);\n return m <= n ? arr : arr.slice(0, n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $minN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar stdDevPop_exports = {};\n__export(stdDevPop_exports, {\n $stdDevPop: () => $stdDevPop\n});\nmodule.exports = __toCommonJS(stdDevPop_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nvar import_push = require(\"./push\");\nconst $stdDevPop = (coll, expr, options) => (0, import_internal.stddev)((0, import_push.$push)(coll, expr, options).filter(import_util.isNumber), false);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $stdDevPop\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar stdDevSamp_exports = {};\n__export(stdDevSamp_exports, {\n $stdDevSamp: () => $stdDevSamp\n});\nmodule.exports = __toCommonJS(stdDevSamp_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nvar import_push = require(\"./push\");\nconst $stdDevSamp = (coll, expr, options) => (0, import_internal.stddev)((0, import_push.$push)(coll, expr, options).filter(import_util.isNumber), true);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $stdDevSamp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sum_exports = {};\n__export(sum_exports, {\n $sum: () => $sum\n});\nmodule.exports = __toCommonJS(sum_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $sum = (coll, expr, options) => {\n if ((0, import_util.isNumber)(expr)) return coll.length * expr;\n const nums = (0, import_push.$push)(coll, expr, options).filter(import_util.isNumber);\n return nums.reduce((r, n) => r + n, 0);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sum\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar topN_exports = {};\n__export(topN_exports, {\n $topN: () => $topN\n});\nmodule.exports = __toCommonJS(topN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_sort = require(\"../pipeline/sort\");\nvar import_push = require(\"./push\");\nconst $topN = (coll, expr, options) => {\n const copts = options;\n const { n, sortBy } = (0, import_internal.evalExpr)(copts?.local?.groupId, expr, copts);\n const result = (0, import_sort.$sort)((0, import_lazy.Lazy)(coll), sortBy, options).take(n).collect();\n return (0, import_push.$push)(result, expr.output, copts);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $topN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar top_exports = {};\n__export(top_exports, {\n $top: () => $top\n});\nmodule.exports = __toCommonJS(top_exports);\nvar import_topN = require(\"./topN\");\nconst $top = (coll, expr, options) => (0, import_topN.$topN)(coll, { ...expr, n: 1 }, options);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $top\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar accumulator_exports = {};\nmodule.exports = __toCommonJS(accumulator_exports);\n__reExport(accumulator_exports, require(\"./accumulator\"), module.exports);\n__reExport(accumulator_exports, require(\"./addToSet\"), module.exports);\n__reExport(accumulator_exports, require(\"./avg\"), module.exports);\n__reExport(accumulator_exports, require(\"./bottom\"), module.exports);\n__reExport(accumulator_exports, require(\"./bottomN\"), module.exports);\n__reExport(accumulator_exports, require(\"./count\"), module.exports);\n__reExport(accumulator_exports, require(\"./covariancePop\"), module.exports);\n__reExport(accumulator_exports, require(\"./covarianceSamp\"), module.exports);\n__reExport(accumulator_exports, require(\"./first\"), module.exports);\n__reExport(accumulator_exports, require(\"./firstN\"), module.exports);\n__reExport(accumulator_exports, require(\"./last\"), module.exports);\n__reExport(accumulator_exports, require(\"./lastN\"), module.exports);\n__reExport(accumulator_exports, require(\"./max\"), module.exports);\n__reExport(accumulator_exports, require(\"./maxN\"), module.exports);\n__reExport(accumulator_exports, require(\"./median\"), module.exports);\n__reExport(accumulator_exports, require(\"./mergeObjects\"), module.exports);\n__reExport(accumulator_exports, require(\"./min\"), module.exports);\n__reExport(accumulator_exports, require(\"./minN\"), module.exports);\n__reExport(accumulator_exports, require(\"./percentile\"), module.exports);\n__reExport(accumulator_exports, require(\"./push\"), module.exports);\n__reExport(accumulator_exports, require(\"./stdDevPop\"), module.exports);\n__reExport(accumulator_exports, require(\"./stdDevSamp\"), module.exports);\n__reExport(accumulator_exports, require(\"./sum\"), module.exports);\n__reExport(accumulator_exports, require(\"./top\"), module.exports);\n__reExport(accumulator_exports, require(\"./topN\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./accumulator\"),\n ...require(\"./addToSet\"),\n ...require(\"./avg\"),\n ...require(\"./bottom\"),\n ...require(\"./bottomN\"),\n ...require(\"./count\"),\n ...require(\"./covariancePop\"),\n ...require(\"./covarianceSamp\"),\n ...require(\"./first\"),\n ...require(\"./firstN\"),\n ...require(\"./last\"),\n ...require(\"./lastN\"),\n ...require(\"./max\"),\n ...require(\"./maxN\"),\n ...require(\"./median\"),\n ...require(\"./mergeObjects\"),\n ...require(\"./min\"),\n ...require(\"./minN\"),\n ...require(\"./percentile\"),\n ...require(\"./push\"),\n ...require(\"./stdDevPop\"),\n ...require(\"./stdDevSamp\"),\n ...require(\"./sum\"),\n ...require(\"./top\"),\n ...require(\"./topN\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar abs_exports = {};\n__export(abs_exports, {\n $abs: () => $abs\n});\nmodule.exports = __toCommonJS(abs_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $abs = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\")\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$abs\");\n return Math.abs(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $abs\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar add_exports = {};\n__export(add_exports, {\n $add: () => $add\n});\nmodule.exports = __toCommonJS(add_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst err = \"$add expression must resolve to array of numbers.\";\nconst $add = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const failOnError = options.failOnError;\n let dateFound = false;\n let result = 0;\n if (!(0, import_util.isArray)(args)) return (0, import_internal2.errInvalidArgs)(failOnError, err);\n for (const n of args) {\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n === \"number\") {\n result += n;\n } else if ((0, import_util.isDate)(n)) {\n if (dateFound) {\n return (0, import_internal2.errInvalidArgs)(failOnError, \"$add must only have one date\");\n }\n dateFound = true;\n result += +n;\n } else {\n return (0, import_internal2.errInvalidArgs)(failOnError, err);\n }\n }\n return dateFound ? new Date(result) : result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $add\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ceil_exports = {};\n__export(ceil_exports, {\n $ceil: () => $ceil\n});\nmodule.exports = __toCommonJS(ceil_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $ceil = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\")\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$ceil\");\n return Math.ceil(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ceil\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar divide_exports = {};\n__export(divide_exports, {\n $divide: () => $divide\n});\nmodule.exports = __toCommonJS(divide_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $divide = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$divide expects array(2)\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let t_num = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n t_num &&= (0, import_util.isNumber)(v);\n }\n if (!t_num) {\n return (0, import_internal2.errExpectArray)(foe, \"$divide\", {\n size: 2,\n type: \"number\"\n });\n }\n if (args[1] === 0)\n return (0, import_internal2.errInvalidArgs)(foe, \"$divide cannot divide by zero\");\n return args[0] / args[1];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $divide\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar exp_exports = {};\n__export(exp_exports, {\n $exp: () => $exp\n});\nmodule.exports = __toCommonJS(exp_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $exp = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\") {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$exp\");\n }\n return Math.exp(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $exp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar floor_exports = {};\n__export(floor_exports, {\n $floor: () => $floor\n});\nmodule.exports = __toCommonJS(floor_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $floor = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\") {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$floor\");\n }\n return Math.floor(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $floor\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ln_exports = {};\n__export(ln_exports, {\n $ln: () => $ln\n});\nmodule.exports = __toCommonJS(ln_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $ln = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\") {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$ln\");\n }\n return Math.log(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ln\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar log_exports = {};\n__export(log_exports, {\n $log: () => $log\n});\nmodule.exports = __toCommonJS(log_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $log = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isArray)(args) && args.length == 2) {\n let t_num = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n t_num &&= typeof v === \"number\";\n }\n if (t_num) return Math.log10(args[0]) / Math.log10(args[1]);\n }\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$log\", {\n size: 2,\n type: \"number\"\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $log\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar log10_exports = {};\n__export(log10_exports, {\n $log10: () => $log10\n});\nmodule.exports = __toCommonJS(log10_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $log10 = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n === \"number\") return Math.log10(n);\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$log10\");\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $log10\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mod_exports = {};\n__export(mod_exports, {\n $mod: () => $mod\n});\nmodule.exports = __toCommonJS(mod_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $mod = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n let invalid = !(0, import_util.isArray)(args) || args.length != 2;\n invalid ||= !args.every((v) => typeof v === \"number\");\n if (invalid)\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$mod\", {\n size: 2,\n type: \"number\"\n });\n return args[0] % args[1];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mod\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar multiply_exports = {};\n__export(multiply_exports, {\n $multiply: () => $multiply\n});\nmodule.exports = __toCommonJS(multiply_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $multiply = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$multiply expects array\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if (args.some(import_util.isNil)) return null;\n let res = 1;\n for (const n of args) {\n if (!(0, import_util.isNumber)(n))\n return (0, import_internal2.errExpectArray)(foe, \"$multiply\", { type: \"number\" });\n res *= n;\n }\n return res;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $multiply\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pow_exports = {};\n__export(pow_exports, {\n $pow: () => $pow\n});\nmodule.exports = __toCommonJS(pow_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $pow = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, \"$pow expects array(2)\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let t_num = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n t_num &&= (0, import_util.isNumber)(v);\n }\n if (!t_num) {\n return (0, import_internal2.errExpectArray)(foe, \"$pow\", {\n size: 2,\n type: \"number\"\n });\n }\n if (args[0] === 0 && args[1] < 0)\n (0, import_internal2.errInvalidArgs)(foe, \"$pow cannot raise 0 to a negative exponent\");\n return Math.pow(args[0], args[1]);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $pow\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n truncate: () => truncate\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../../../util\");\nvar import_internal = require(\"../_internal\");\nfunction truncate(num, precision, opts) {\n const { name, roundOff, failOnError } = opts;\n if ((0, import_util.isNil)(num)) return null;\n if (Number.isNaN(num) || Math.abs(num) === Infinity) return num;\n if (!(0, import_util.isNumber)(num)) {\n return (0, import_internal.errExpectNumber)(failOnError, `${name} arg1 `);\n }\n if (!(0, import_util.isInteger)(precision) || precision < -20 || precision > 100) {\n return (0, import_internal.errExpectNumber)(failOnError, `${name} arg2 `, {\n min: -20,\n max: 100,\n int: true\n });\n }\n const sign = Math.abs(num) === num ? 1 : -1;\n num = Math.abs(num);\n let result = Math.trunc(num);\n const decimals = parseFloat((num - result).toFixed(Math.abs(precision) + 1));\n if (precision === 0) {\n const firstDigit = Math.trunc(10 * decimals);\n if (roundOff && ((result & 1) === 1 && firstDigit >= 5 || firstDigit > 5)) {\n result++;\n }\n } else if (precision > 0) {\n const offset = Math.pow(10, precision);\n let remainder = Math.trunc(decimals * offset);\n const lastDigit = Math.trunc(decimals * offset * 10) % 10;\n if (roundOff && lastDigit > 5) {\n remainder += 1;\n }\n result = (result * offset + remainder) / offset;\n } else if (precision < 0) {\n const offset = Math.pow(10, -1 * precision);\n let excess = result % offset;\n result = Math.max(0, result - excess);\n if (roundOff && sign === -1) {\n while (excess > 10) {\n excess -= excess / 10;\n }\n if (result > 0 && excess >= 5) {\n result += offset;\n }\n }\n }\n return result * sign;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n truncate\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar round_exports = {};\n__export(round_exports, {\n $round: () => $round\n});\nmodule.exports = __toCommonJS(round_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst $round = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$round expects array(2)\");\n const [n, precision] = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_internal2.truncate)(n, precision ?? 0, {\n name: \"$round\",\n roundOff: true,\n failOnError: options.failOnError\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $round\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sigmoid_exports = {};\n__export(sigmoid_exports, {\n $sigmoid: () => $sigmoid\n});\nmodule.exports = __toCommonJS(sigmoid_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst PRECISION = 1e10;\nconst $sigmoid = (obj, expr, options) => {\n if ((0, import_util.isNil)(expr)) return null;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const { input, onNull } = (0, import_util.isObject)(args) ? args : { input: args };\n if ((0, import_util.isNil)(input)) return (0, import_util.isNumber)(onNull) ? onNull : null;\n if ((0, import_util.isNumber)(input)) {\n const result = 1 / (1 + Math.exp(-input));\n return Math.round(result * PRECISION) / PRECISION;\n }\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$sigmoid\");\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sigmoid\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sqrt_exports = {};\n__export(sqrt_exports, {\n $sqrt: () => $sqrt\n});\nmodule.exports = __toCommonJS(sqrt_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $sqrt = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n const skip = !options.failOnError;\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\" || n < 0) {\n (0, import_util.assert)(skip, \"$sqrt expression must resolve to non-negative number.\");\n return null;\n }\n return Math.sqrt(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sqrt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar subtract_exports = {};\n__export(subtract_exports, {\n $subtract: () => $subtract\n});\nmodule.exports = __toCommonJS(subtract_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $subtract = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$subtract expects array(2)\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (args.some(import_util.isNil)) return null;\n const foe = options.failOnError;\n const [a, b] = args;\n if ((0, import_util.isDate)(a) && (0, import_util.isNumber)(b)) return new Date(+a - Math.round(b));\n if ((0, import_util.isDate)(a) && (0, import_util.isDate)(b)) return +a - +b;\n if (args.every((v) => typeof v === \"number\")) return a - b;\n if ((0, import_util.isNumber)(a) && (0, import_util.isDate)(b)) {\n return (0, import_internal2.errInvalidArgs)(foe, \"$subtract cannot subtract date from number\");\n }\n return (0, import_internal2.errExpectArray)(foe, \"$subtract\", {\n size: 2,\n type: \"number|date\"\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $subtract\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar trunc_exports = {};\n__export(trunc_exports, {\n $trunc: () => $trunc\n});\nmodule.exports = __toCommonJS(trunc_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst $trunc = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$trunc expects array(2)\");\n const [n, precision] = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_internal2.truncate)(n, precision ?? 0, {\n name: \"$trunc\",\n roundOff: false,\n failOnError: options.failOnError\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $trunc\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar arithmetic_exports = {};\nmodule.exports = __toCommonJS(arithmetic_exports);\n__reExport(arithmetic_exports, require(\"./abs\"), module.exports);\n__reExport(arithmetic_exports, require(\"./add\"), module.exports);\n__reExport(arithmetic_exports, require(\"./ceil\"), module.exports);\n__reExport(arithmetic_exports, require(\"./divide\"), module.exports);\n__reExport(arithmetic_exports, require(\"./exp\"), module.exports);\n__reExport(arithmetic_exports, require(\"./floor\"), module.exports);\n__reExport(arithmetic_exports, require(\"./ln\"), module.exports);\n__reExport(arithmetic_exports, require(\"./log\"), module.exports);\n__reExport(arithmetic_exports, require(\"./log10\"), module.exports);\n__reExport(arithmetic_exports, require(\"./mod\"), module.exports);\n__reExport(arithmetic_exports, require(\"./multiply\"), module.exports);\n__reExport(arithmetic_exports, require(\"./pow\"), module.exports);\n__reExport(arithmetic_exports, require(\"./round\"), module.exports);\n__reExport(arithmetic_exports, require(\"./sigmoid\"), module.exports);\n__reExport(arithmetic_exports, require(\"./sqrt\"), module.exports);\n__reExport(arithmetic_exports, require(\"./subtract\"), module.exports);\n__reExport(arithmetic_exports, require(\"./trunc\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./abs\"),\n ...require(\"./add\"),\n ...require(\"./ceil\"),\n ...require(\"./divide\"),\n ...require(\"./exp\"),\n ...require(\"./floor\"),\n ...require(\"./ln\"),\n ...require(\"./log\"),\n ...require(\"./log10\"),\n ...require(\"./mod\"),\n ...require(\"./multiply\"),\n ...require(\"./pow\"),\n ...require(\"./round\"),\n ...require(\"./sigmoid\"),\n ...require(\"./sqrt\"),\n ...require(\"./subtract\"),\n ...require(\"./trunc\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar arrayElemAt_exports = {};\n__export(arrayElemAt_exports, {\n $arrayElemAt: () => $arrayElemAt\n});\nmodule.exports = __toCommonJS(arrayElemAt_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$arrayElemAt\";\nconst $arrayElemAt = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, `${OP} expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (args.some(import_util.isNil)) return null;\n const foe = options.failOnError;\n const [arr, index] = args;\n if (!(0, import_util.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, `${OP} arg1 `);\n if (!(0, import_util.isInteger)(index))\n return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `, import_internal2.INT_OPTS.int);\n if (index < 0 && Math.abs(index) <= arr.length) {\n return arr[(index + arr.length) % arr.length];\n } else if (index >= 0 && index < arr.length) {\n return arr[index];\n }\n return void 0;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $arrayElemAt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar arrayToObject_exports = {};\n__export(arrayToObject_exports, {\n $arrayToObject: () => $arrayToObject\n});\nmodule.exports = __toCommonJS(arrayToObject_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst ERR_OPTS = {\n generic: { type: \"key-value pairs\" },\n array: { type: \"[k,v]\" },\n object: { type: \"{k,v}\" }\n};\nconst $arrayToObject = (obj, expr, options) => {\n const foe = options.failOnError;\n const arr = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr))\n return (0, import_internal2.errExpectArray)(foe, \"$arrayToObject\", ERR_OPTS.generic);\n let tag = 0;\n const newObj = {};\n for (const item of arr) {\n if ((0, import_util.isArray)(item)) {\n const val = (0, import_util.flatten)(item);\n if (!tag) tag = 1;\n if (tag !== 1) {\n return (0, import_internal2.errExpectArray)(foe, \"$arrayToObject\", ERR_OPTS.object);\n }\n const [k, v] = val;\n newObj[k] = v;\n } else if ((0, import_util.isObject)(item) && (0, import_util.has)(item, \"k\", \"v\")) {\n if (!tag) tag = 2;\n if (tag !== 2) {\n return (0, import_internal2.errExpectArray)(foe, \"$arrayToObject\", ERR_OPTS.array);\n }\n const { k, v } = item;\n newObj[k] = v;\n } else {\n return (0, import_internal2.errExpectArray)(foe, \"$arrayToObject\", ERR_OPTS.generic);\n }\n }\n return newObj;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $arrayToObject\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar concatArrays_exports = {};\n__export(concatArrays_exports, {\n $concatArrays: () => $concatArrays\n});\nmodule.exports = __toCommonJS(concatArrays_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $concatArrays = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if ((0, import_util.isNil)(args)) return null;\n if (!(0, import_util.isArray)(args)) return (0, import_internal2.errExpectArray)(foe, \"$concatArrays\");\n let size = 0;\n for (const arr of args) {\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, \"$concatArrays\");\n size += arr.length;\n }\n const result = new Array(size);\n let i = 0;\n for (const arr of args) for (const item of arr) result[i++] = item;\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $concatArrays\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar filter_exports = {};\n__export(filter_exports, {\n $filter: () => $filter\n});\nmodule.exports = __toCommonJS(filter_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $filter = (obj, expr, options) => {\n (0, import_internal2.assert)(\n (0, import_internal2.isObject)(expr) && (0, import_internal2.has)(expr, \"input\", \"cond\"),\n \"$filter expects object { input, as, cond, limit }\"\n );\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n const foe = options.failOnError;\n if ((0, import_internal2.isNil)(input)) return null;\n if (!(0, import_internal2.isArray)(input)) return (0, import_internal3.errExpectArray)(foe, \"$filter 'input'\");\n const limit = expr.limit ?? Math.max(input.length, 1);\n if (!(0, import_internal2.isInteger)(limit) || limit < 1)\n return (0, import_internal3.errExpectNumber)(foe, \"$filter 'limit'\", { min: 1, int: true });\n if (input.length === 0) return [];\n const copts = import_internal.ComputeOptions.init(options);\n const k = expr?.as || \"this\";\n const locals = { variables: {} };\n const res = [];\n for (let i = 0, j = 0; i < input.length && j < limit; i++) {\n locals.variables[k] = input[i];\n const cond = (0, import_internal.evalExpr)(obj, expr.cond, copts.update(locals));\n if ((0, import_internal2.truthy)(cond, options.useStrictMode)) {\n res.push(input[i]);\n j++;\n }\n }\n return res;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $filter\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar first_exports = {};\n__export(first_exports, {\n $first: () => $first\n});\nmodule.exports = __toCommonJS(first_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_first = require(\"../../accumulator/first\");\nvar import_internal2 = require(\"../_internal\");\nconst $first = (obj, expr, options) => {\n if ((0, import_util.isArray)(obj)) return (0, import_first.$first)(obj, expr, options);\n const arr = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr)) {\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$first\");\n }\n return (0, import_util.flatten)(arr)[0];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $first\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar firstN_exports = {};\n__export(firstN_exports, {\n $firstN: () => $firstN\n});\nmodule.exports = __toCommonJS(firstN_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_firstN = require(\"../../accumulator/firstN\");\nvar import_internal2 = require(\"../_internal\");\nconst $firstN = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"n\"),\n \"$firstN expects object { input, n }\"\n );\n if ((0, import_util.isArray)(obj)) return (0, import_firstN.$firstN)(obj, expr, options);\n const { input, n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$firstN 'input'\");\n return (0, import_firstN.$firstN)(input, { n, input: \"$$this\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $firstN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar in_exports = {};\n__export(in_exports, {\n $in: () => $in\n});\nmodule.exports = __toCommonJS(in_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $in = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, \"$in expects array(2)\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const [item, arr] = args;\n if (!(0, import_util.isArray)(arr))\n return (0, import_internal2.errInvalidArgs)(options.failOnError, \"$in arg2 \");\n for (const v of arr) if ((0, import_util.isEqual)(v, item)) return true;\n return false;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $in\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar indexOfArray_exports = {};\n__export(indexOfArray_exports, {\n $indexOfArray: () => $indexOfArray\n});\nmodule.exports = __toCommonJS(indexOfArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst OP = \"$indexOfArray\";\nconst $indexOfArray = (obj, expr, options) => {\n (0, import_internal2.assert)(\n (0, import_internal2.isArray)(expr) && expr.length > 1 && expr.length < 5,\n `${OP} expects array(4)`\n );\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n const arr = args[0];\n if ((0, import_internal2.isNil)(arr)) return null;\n if (!(0, import_internal2.isArray)(arr)) return (0, import_internal3.errExpectArray)(foe, `${OP} arg1 `);\n const search = args[1];\n const start = args[2] ?? 0;\n const end = args[3] ?? arr.length;\n if (!(0, import_internal2.isInteger)(start) || start < 0)\n return (0, import_internal3.errExpectNumber)(foe, `${OP} arg3 `, import_internal3.INT_OPTS.pos);\n if (!(0, import_internal2.isInteger)(end) || end < 0)\n return (0, import_internal3.errExpectNumber)(foe, `${OP} arg4 `, import_internal3.INT_OPTS.pos);\n if (start > end) return -1;\n const input = start > 0 || end < arr.length ? arr.slice(start, end) : arr;\n return input.findIndex((v) => (0, import_internal2.isEqual)(v, search)) + start;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $indexOfArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isArray_exports = {};\n__export(isArray_exports, {\n $isArray: () => $isArray\n});\nmodule.exports = __toCommonJS(isArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $isArray = (obj, expr, options) => {\n let input = expr;\n if ((0, import_util.isArray)(expr)) {\n (0, import_util.assert)(expr.length === 1, \"$isArray expects array(1)\");\n input = expr[0];\n }\n return (0, import_util.isArray)((0, import_internal.evalExpr)(obj, input, options));\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar last_exports = {};\n__export(last_exports, {\n $last: () => $last\n});\nmodule.exports = __toCommonJS(last_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_last = require(\"../../accumulator/last\");\nvar import_internal2 = require(\"../_internal\");\nconst $last = (obj, expr, options) => {\n if ((0, import_util.isArray)(obj)) return (0, import_last.$last)(obj, expr, options);\n const arr = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr) || arr.length === 0) {\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$last\", { size: 0 });\n }\n return (0, import_util.flatten)(arr)[arr.length - 1];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $last\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lastN_exports = {};\n__export(lastN_exports, {\n $lastN: () => $lastN\n});\nmodule.exports = __toCommonJS(lastN_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_lastN = require(\"../../accumulator/lastN\");\nvar import_internal2 = require(\"../_internal\");\nconst $lastN = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"n\"),\n \"$lastN expects object { input, n }\"\n );\n if ((0, import_util.isArray)(obj)) return (0, import_lastN.$lastN)(obj, expr, options);\n const { input, n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input)) {\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$lastN 'input'\");\n }\n return (0, import_lastN.$lastN)(input, { n, input: \"$$this\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lastN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar map_exports = {};\n__export(map_exports, {\n $map: () => $map\n});\nmodule.exports = __toCommonJS(map_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $map = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"in\"),\n \"$map expects object { input, as, in }\"\n );\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n const foe = options.failOnError;\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input)) return (0, import_internal2.errExpectArray)(foe, \"$map 'input'\");\n if (!(0, import_util.isNil)(expr.as) && !(0, import_util.isString)(expr.as))\n return (0, import_internal2.errExpectString)(foe, \"$map 'as'\");\n const copts = import_internal.ComputeOptions.init(options);\n const k = expr.as || \"this\";\n const locals = { variables: {} };\n return input.map((o) => {\n locals.variables[k] = o;\n return (0, import_internal.evalExpr)(obj, expr.in, copts.update(locals));\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $map\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar maxN_exports = {};\n__export(maxN_exports, {\n $maxN: () => $maxN\n});\nmodule.exports = __toCommonJS(maxN_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_maxN = require(\"../../accumulator/maxN\");\nvar import_internal2 = require(\"../_internal\");\nconst $maxN = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"n\"),\n \"$maxN expects object { input, n }\"\n );\n if ((0, import_util.isArray)(obj)) return (0, import_maxN.$maxN)(obj, expr, options);\n const { input, n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$maxN 'input'\");\n return (0, import_maxN.$maxN)(input, { n, input: \"$$this\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $maxN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar minN_exports = {};\n__export(minN_exports, {\n $minN: () => $minN\n});\nmodule.exports = __toCommonJS(minN_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_minN = require(\"../../accumulator/minN\");\nvar import_internal2 = require(\"../_internal\");\nconst $minN = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"n\"),\n \"$minN expects object { input, n }\"\n );\n if ((0, import_util.isArray)(obj)) return (0, import_minN.$minN)(obj, expr, options);\n const { input, n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$minN 'input'\");\n return (0, import_minN.$minN)(input, { n, input: \"$$this\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $minN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar range_exports = {};\n__export(range_exports, {\n $range: () => $range\n});\nmodule.exports = __toCommonJS(range_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $range = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isArray)(expr) && expr.length > 1 && expr.length < 4,\n \"$range expects array(3)\"\n );\n const [start, end, arg3] = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n const step = arg3 ?? 1;\n if (!(0, import_util.isInteger)(start))\n return (0, import_internal2.errExpectNumber)(foe, `$range arg1 `, import_internal2.INT_OPTS.int);\n if (!(0, import_util.isInteger)(end))\n return (0, import_internal2.errExpectNumber)(foe, `$range arg2 `, import_internal2.INT_OPTS.int);\n if (!(0, import_util.isInteger)(step) || step === 0)\n return (0, import_internal2.errExpectNumber)(foe, `$range arg3 `, import_internal2.INT_OPTS.nzero);\n const result = new Array();\n let counter = start;\n while (counter < end && step > 0 || counter > end && step < 0) {\n result.push(counter);\n counter += step;\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $range\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar reduce_exports = {};\n__export(reduce_exports, {\n $reduce: () => $reduce\n});\nmodule.exports = __toCommonJS(reduce_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nfunction $reduce(obj, expr, options) {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"initialValue\", \"in\"),\n \"$reduce expects object { input, initialValue, in }\"\n );\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n const initialValue = (0, import_internal.evalExpr)(obj, expr.initialValue, options);\n const inExpr = expr[\"in\"];\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$reduce 'input'\");\n const copts = import_internal.ComputeOptions.init(options);\n const locals = { variables: { value: null } };\n let result = initialValue;\n for (let i = 0; i < input.length; i++) {\n locals.variables.value = result;\n result = (0, import_internal.evalExpr)(input[i], inExpr, copts.update(locals));\n }\n return result;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $reduce\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar reverseArray_exports = {};\n__export(reverseArray_exports, {\n $reverseArray: () => $reverseArray\n});\nmodule.exports = __toCommonJS(reverseArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $reverseArray = (obj, expr, options) => {\n const arr = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$reverseArray\");\n return arr.slice().reverse();\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $reverseArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar size_exports = {};\n__export(size_exports, {\n $size: () => $size\n});\nmodule.exports = __toCommonJS(size_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $size = (obj, expr, options) => {\n const value = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(value)) return null;\n return (0, import_util.isArray)(value) ? value.length : (0, import_internal2.errExpectNumber)(options.failOnError, \"$size\");\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $size\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar slice_exports = {};\n__export(slice_exports, {\n $slice: () => $slice\n});\nmodule.exports = __toCommonJS(slice_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $slice = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isArray)(expr) && expr.length > 1 && expr.length < 4,\n \"$slice expects array(3)\"\n );\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const arr = args[0];\n let skip = args[1];\n let limit = args[2];\n if (!(0, import_util.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, \"$slice arg1 \");\n if (!(0, import_util.isInteger)(skip))\n return (0, import_internal2.errExpectNumber)(foe, \"$slice arg2 \", import_internal2.INT_OPTS.int);\n if (!(0, import_util.isNil)(limit) && !(0, import_util.isInteger)(limit))\n return (0, import_internal2.errExpectNumber)(foe, \"$slice arg3 \", import_internal2.INT_OPTS.int);\n if ((0, import_util.isNil)(limit)) {\n if (skip < 0) {\n skip = Math.max(0, arr.length + skip);\n } else {\n limit = skip;\n skip = 0;\n }\n } else {\n if (skip < 0) {\n skip = Math.max(0, arr.length + skip);\n }\n if (limit < 1) {\n return (0, import_internal2.errExpectNumber)(foe, \"$slice arg3 \", import_internal2.INT_OPTS.pos);\n }\n limit += skip;\n }\n return arr.slice(skip, limit);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $slice\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sortArray_exports = {};\n__export(sortArray_exports, {\n $sortArray: () => $sortArray\n});\nmodule.exports = __toCommonJS(sortArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_lazy = require(\"../../../lazy\");\nvar import_util = require(\"../../../util\");\nvar import_sort = require(\"../../pipeline/sort\");\nvar import_internal2 = require(\"../_internal\");\nconst $sortArray = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && \"input\" in expr && \"sortBy\" in expr,\n \"$sortArray expects object { input, sortBy }\"\n );\n const { input, sortBy } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$sortArray 'input'\");\n if ((0, import_util.isObject)(sortBy)) {\n return (0, import_sort.$sort)((0, import_lazy.Lazy)(input), sortBy, options).collect();\n }\n const result = input.slice().sort(import_util.compare);\n if (sortBy === -1) result.reverse();\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sortArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar zip_exports = {};\n__export(zip_exports, {\n $zip: () => $zip\n});\nmodule.exports = __toCommonJS(zip_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $zip = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"inputs\"),\n \"$zip received invalid arguments\"\n );\n const inputs = (0, import_internal.evalExpr)(obj, expr.inputs, options);\n const defaults = (0, import_internal.evalExpr)(obj, expr.defaults, options) ?? [];\n const useLongestLength = expr.useLongestLength ?? false;\n const foe = options.failOnError;\n if ((0, import_util.isNil)(inputs)) return null;\n if (!(0, import_util.isArray)(inputs)) return (0, import_internal2.errExpectArray)(foe, \"$zip 'inputs'\");\n let invalid = 0;\n for (const elem of inputs) {\n if ((0, import_util.isNil)(elem)) return null;\n if (!(0, import_util.isArray)(elem)) invalid++;\n }\n if (invalid) return (0, import_internal2.errExpectArray)(foe, \"$zip elements of 'inputs'\");\n if (!(0, import_util.isBoolean)(useLongestLength))\n (0, import_internal2.errInvalidArgs)(foe, \"$zip 'useLongestLength' must be boolean\");\n if ((0, import_util.isArray)(defaults) && defaults.length > 0) {\n (0, import_util.assert)(\n useLongestLength && defaults.length === inputs.length,\n \"$zip 'useLongestLength' must be set to true to use 'defaults'\"\n );\n }\n let zipCount = 0;\n for (const arr of inputs) {\n zipCount = useLongestLength ? Math.max(zipCount, arr.length) : Math.min(zipCount || arr.length, arr.length);\n }\n const result = [];\n for (let i = 0; i < zipCount; i++) {\n const temp = inputs.map((val, index) => {\n return (0, import_util.isNil)(val[i]) ? defaults[index] ?? null : val[i];\n });\n result.push(temp);\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $zip\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar array_exports = {};\nmodule.exports = __toCommonJS(array_exports);\n__reExport(array_exports, require(\"./arrayElemAt\"), module.exports);\n__reExport(array_exports, require(\"./arrayToObject\"), module.exports);\n__reExport(array_exports, require(\"./concatArrays\"), module.exports);\n__reExport(array_exports, require(\"./filter\"), module.exports);\n__reExport(array_exports, require(\"./first\"), module.exports);\n__reExport(array_exports, require(\"./firstN\"), module.exports);\n__reExport(array_exports, require(\"./in\"), module.exports);\n__reExport(array_exports, require(\"./indexOfArray\"), module.exports);\n__reExport(array_exports, require(\"./isArray\"), module.exports);\n__reExport(array_exports, require(\"./last\"), module.exports);\n__reExport(array_exports, require(\"./lastN\"), module.exports);\n__reExport(array_exports, require(\"./map\"), module.exports);\n__reExport(array_exports, require(\"./maxN\"), module.exports);\n__reExport(array_exports, require(\"./minN\"), module.exports);\n__reExport(array_exports, require(\"./range\"), module.exports);\n__reExport(array_exports, require(\"./reduce\"), module.exports);\n__reExport(array_exports, require(\"./reverseArray\"), module.exports);\n__reExport(array_exports, require(\"./size\"), module.exports);\n__reExport(array_exports, require(\"./slice\"), module.exports);\n__reExport(array_exports, require(\"./sortArray\"), module.exports);\n__reExport(array_exports, require(\"./zip\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./arrayElemAt\"),\n ...require(\"./arrayToObject\"),\n ...require(\"./concatArrays\"),\n ...require(\"./filter\"),\n ...require(\"./first\"),\n ...require(\"./firstN\"),\n ...require(\"./in\"),\n ...require(\"./indexOfArray\"),\n ...require(\"./isArray\"),\n ...require(\"./last\"),\n ...require(\"./lastN\"),\n ...require(\"./map\"),\n ...require(\"./maxN\"),\n ...require(\"./minN\"),\n ...require(\"./range\"),\n ...require(\"./reduce\"),\n ...require(\"./reverseArray\"),\n ...require(\"./size\"),\n ...require(\"./slice\"),\n ...require(\"./sortArray\"),\n ...require(\"./zip\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n processBitwise: () => processBitwise\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nfunction processBitwise(obj, expr, options, operator, fn) {\n (0, import_util.assert)((0, import_util.isArray)(expr), `${operator} expects array as argument`);\n const nums = (0, import_internal.evalExpr)(obj, expr, options);\n let t_num = true;\n for (const v of nums) {\n if ((0, import_util.isNil)(v)) return null;\n t_num &&= (0, import_util.isInteger)(v);\n }\n if (t_num) return fn(nums);\n return (0, import_internal2.errInvalidArgs)(\n options.failOnError,\n `${operator} array elements must resolve to integers`\n );\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n processBitwise\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitAnd_exports = {};\n__export(bitAnd_exports, {\n $bitAnd: () => $bitAnd\n});\nmodule.exports = __toCommonJS(bitAnd_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitAnd = (obj, expr, options) => (0, import_internal.processBitwise)(\n obj,\n expr,\n options,\n \"$bitAnd\",\n (nums) => nums.reduce((a, b) => a & b, -1)\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitAnd\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitNot_exports = {};\n__export(bitNot_exports, {\n $bitNot: () => $bitNot\n});\nmodule.exports = __toCommonJS(bitNot_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $bitNot = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (!(0, import_util.isInteger)(n))\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$bitNot\", import_internal2.INT_OPTS.int);\n return ~n;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitNot\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitOr_exports = {};\n__export(bitOr_exports, {\n $bitOr: () => $bitOr\n});\nmodule.exports = __toCommonJS(bitOr_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitOr = (obj, expr, options) => (0, import_internal.processBitwise)(\n obj,\n expr,\n options,\n \"$bitOr\",\n (nums) => nums.reduce((a, b) => a | b, 0)\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitOr\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitXor_exports = {};\n__export(bitXor_exports, {\n $bitXor: () => $bitXor\n});\nmodule.exports = __toCommonJS(bitXor_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitXor = (obj, expr, options) => (0, import_internal.processBitwise)(\n obj,\n expr,\n options,\n \"$bitXor\",\n (nums) => nums.reduce((a, b) => a ^ b, 0)\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitXor\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitwise_exports = {};\nmodule.exports = __toCommonJS(bitwise_exports);\n__reExport(bitwise_exports, require(\"./bitAnd\"), module.exports);\n__reExport(bitwise_exports, require(\"./bitNot\"), module.exports);\n__reExport(bitwise_exports, require(\"./bitOr\"), module.exports);\n__reExport(bitwise_exports, require(\"./bitXor\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./bitAnd\"),\n ...require(\"./bitNot\"),\n ...require(\"./bitOr\"),\n ...require(\"./bitXor\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar and_exports = {};\n__export(and_exports, {\n $and: () => $and\n});\nmodule.exports = __toCommonJS(and_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nconst $and = (obj, expr, options) => {\n (0, import_internal2.assert)((0, import_internal2.isArray)(expr), \"$and expects array\");\n const mode = options.useStrictMode;\n return expr.every((e) => (0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, e, options), mode));\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $and\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar not_exports = {};\n__export(not_exports, {\n $not: () => $not\n});\nmodule.exports = __toCommonJS(not_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $not = (obj, expr, options) => {\n const booleanExpr = (0, import_util.ensureArray)(expr);\n if (booleanExpr.length === 0) return false;\n if (booleanExpr.length > 1)\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$not\", { size: 1 });\n return !(0, import_internal.evalExpr)(obj, booleanExpr[0], options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $not\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar or_exports = {};\n__export(or_exports, {\n $or: () => $or\n});\nmodule.exports = __toCommonJS(or_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nconst $or = (obj, expr, options) => {\n (0, import_internal2.assert)((0, import_internal2.isArray)(expr), \"$or expects array of expressions\");\n const strict = options.useStrictMode;\n for (const v of expr)\n if ((0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, v, options), strict)) return true;\n return false;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $or\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar boolean_exports = {};\nmodule.exports = __toCommonJS(boolean_exports);\n__reExport(boolean_exports, require(\"./and\"), module.exports);\n__reExport(boolean_exports, require(\"./not\"), module.exports);\n__reExport(boolean_exports, require(\"./or\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./and\"),\n ...require(\"./not\"),\n ...require(\"./or\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cmp_exports = {};\n__export(cmp_exports, {\n $cmp: () => $cmp\n});\nmodule.exports = __toCommonJS(cmp_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $cmp = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, \"$cmp expects array(2)\");\n const [a, b] = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_util.compare)(a, b);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $cmp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar limit_exports = {};\n__export(limit_exports, {\n $limit: () => $limit\n});\nmodule.exports = __toCommonJS(limit_exports);\nfunction $limit(coll, expr, _options) {\n return coll.take(expr);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $limit\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar documents_exports = {};\n__export(documents_exports, {\n $documents: () => $documents\n});\nmodule.exports = __toCommonJS(documents_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $documents(_, expr, options) {\n const docs = (0, import_internal.evalExpr)(null, expr, options);\n (0, import_util.assert)((0, import_util.isArray)(docs), \"$documents expression must resolve to an array.\");\n const iter = (0, import_lazy.Lazy)(docs);\n const mode = options.processingMode;\n return mode & import_internal.ProcessingMode.CLONE_ALL ? iter.map((o) => (0, import_util.cloneDeep)(o)) : iter;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $documents\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n filterDocumentsStage: () => filterDocumentsStage,\n resolveCollection: () => resolveCollection,\n validateProjection: () => validateProjection\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"../../util/_internal\");\nvar import_documents = require(\"./documents\");\nconst EMPTY = (0, import_lazy.Lazy)([]);\nfunction filterDocumentsStage(pipeline, options) {\n if (!pipeline) return {};\n const docs = pipeline[0]?.$documents;\n if (!docs) return { pipeline };\n return {\n documents: (0, import_documents.$documents)(EMPTY, docs, options).collect(),\n pipeline: pipeline.slice(1)\n };\n}\nfunction validateProjection(expr, options, isRoot = true) {\n const res = {\n exclusions: [],\n inclusions: [],\n positional: 0\n };\n const keys = Object.keys(expr);\n (0, import_internal.assert)(keys.length, \"Invalid empty sub-projection\");\n const idKey = options?.idKey;\n let idKeyExcluded = false;\n for (const k of keys) {\n if (k.startsWith(\"$\")) {\n (0, import_internal.assert)(\n !isRoot && keys.length === 1,\n `FieldPath field names may not start with '$', given '${k}'.`\n );\n return res;\n }\n if (k.endsWith(\".$\")) res.positional++;\n const v = expr[k];\n if (v === false || (0, import_util.isNumber)(v) && v === 0) {\n if (k === idKey) {\n idKeyExcluded = true;\n } else res.exclusions.push(k);\n } else if (!(0, import_util.isObject)(v)) {\n res.inclusions.push(k);\n } else {\n const meta = validateProjection(v, options, false);\n if (!meta.inclusions.length && !meta.exclusions.length) {\n if (!res.inclusions.includes(k)) res.inclusions.push(k);\n } else {\n for (const n of meta.exclusions) res.exclusions.push(`${k}.${n}`);\n for (const n of meta.inclusions) res.inclusions.push(`${k}.${n}`);\n }\n res.positional += meta.positional;\n }\n (0, import_internal.assert)(\n !(res.exclusions.length && res.inclusions.length),\n \"Cannot do exclusion and inclusion in projection.\"\n );\n (0, import_internal.assert)(\n res.positional <= 1,\n \"Cannot specify more than one positional projection.\"\n );\n }\n if (idKeyExcluded) {\n res.exclusions.push(idKey);\n }\n if (isRoot) {\n const p = new import_internal.PathValidator();\n for (const k of res.exclusions) (0, import_internal.assert)(p.add(k), `Path collision at ${k}.`);\n for (const k of res.inclusions) (0, import_internal.assert)(p.add(k), `Path collision at ${k}.`);\n res.exclusions.sort();\n res.inclusions.sort();\n }\n return res;\n}\nfunction resolveCollection(op, expr, options) {\n if ((0, import_internal.isString)(expr)) {\n (0, import_internal.assert)(\n options.collectionResolver,\n `${op} requires 'collectionResolver' option to resolve named collection`\n );\n }\n const coll = (0, import_internal.isString)(expr) ? options.collectionResolver(expr) : expr;\n (0, import_internal.assert)((0, import_internal.isArray)(coll), `${op} could not resolve input collection`);\n return coll;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n filterDocumentsStage,\n resolveCollection,\n validateProjection\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar project_exports = {};\n__export(project_exports, {\n $project: () => $project\n});\nmodule.exports = __toCommonJS(project_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_internal2 = require(\"../../util/_internal\");\nvar import_internal3 = require(\"./_internal\");\nconst OP = \"$project\";\nfunction $project(coll, expr, options) {\n if ((0, import_internal2.isEmpty)(expr)) return coll;\n const meta = (0, import_internal3.validateProjection)(expr, options);\n const handler = createHandler(expr, import_internal.ComputeOptions.init(options), meta);\n return coll.map(handler);\n}\nfunction createHandler(expr, options, meta) {\n const idKey = options.idKey;\n const { exclusions, inclusions } = meta;\n const handlers = {};\n const resolveOpts = {\n preserveMissing: true\n };\n for (const k of exclusions) {\n handlers[k] = (t, _) => {\n (0, import_internal2.removeValue)(t, k, { descendArray: true });\n };\n }\n for (const selector of inclusions) {\n const v = (0, import_internal2.resolve)(expr, selector) ?? expr[selector];\n if (selector.endsWith(\".$\") && v === 1) {\n const cond = options?.local?.condition ?? {};\n (0, import_internal2.assert)(cond, `${OP}: positional operator '.$' requires array condition.`);\n const field = selector.slice(0, -2);\n handlers[field] = getPositionalFilter(field, cond, options);\n continue;\n }\n if ((0, import_internal2.isArray)(v)) {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const newVal = v.map((e) => (0, import_internal.evalExpr)(o, e, options) ?? null);\n (0, import_internal2.setValue)(t, selector, newVal);\n };\n } else if ((0, import_internal2.isNumber)(v) || v === true) {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const extractedVal = (0, import_internal2.resolveGraph)(o, selector, resolveOpts);\n mergeInto(t, extractedVal);\n };\n } else if (!(0, import_internal2.isObject)(v)) {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const newVal = (0, import_internal.evalExpr)(o, v, options);\n (0, import_internal2.setValue)(t, selector, newVal);\n };\n } else {\n const opKeys = Object.keys(v);\n (0, import_internal2.assert)(\n opKeys.length === 1 && (0, import_internal2.isOperator)(opKeys[0]),\n \"Not a valid operator\"\n );\n const operator = opKeys[0];\n const opExpr = v[operator];\n const fn = options.context.getOperator(import_internal.OpType.PROJECTION, operator);\n const foundSlice = operator === \"$slice\";\n if (!fn || foundSlice && !(0, import_internal2.ensureArray)(opExpr).every(import_internal2.isNumber)) {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const newval = (0, import_internal.evalExpr)(o, v, options);\n (0, import_internal2.setValue)(t, selector, newval);\n };\n } else {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const newval = fn(o, opExpr, selector, options);\n (0, import_internal2.setValue)(t, selector, newval);\n };\n }\n }\n }\n const onlyIdKeyExcluded = exclusions.length === 1 && exclusions.includes(idKey);\n const noIdKeyExcluded = !exclusions.includes(idKey);\n const noInclusions = !inclusions.length;\n const allKeysIncluded = noInclusions && onlyIdKeyExcluded || noInclusions && exclusions.length && !onlyIdKeyExcluded;\n return (o) => {\n const newObj = {};\n if (allKeysIncluded) Object.assign(newObj, o);\n for (const k in handlers) {\n handlers[k](newObj, o);\n }\n if (!noInclusions) (0, import_internal2.filterMissing)(newObj);\n if (noIdKeyExcluded && !(0, import_internal2.has)(newObj, idKey) && (0, import_internal2.has)(o, idKey)) {\n newObj[idKey] = (0, import_internal2.resolve)(o, idKey);\n }\n return newObj;\n };\n}\nconst findMatches = (o, key, leaf, pred) => {\n let arr = (0, import_internal2.resolve)(o, key);\n if (!(0, import_internal2.isArray)(arr)) arr = (0, import_internal2.resolve)(arr, leaf);\n (0, import_internal2.assert)((0, import_internal2.isArray)(arr), `${OP}: field '${key}' must resolve to array`);\n const matches = [];\n for (let i = 0; i < arr.length; i++) {\n if (pred({ [leaf]: [arr[i]] })) matches.push(i);\n }\n return matches;\n};\nconst complement = (p) => ((e) => !p(e));\nconst COMPOUND_OPS = { $and: 1, $or: 1, $nor: 1 };\nfunction getPositionalFilter(field, condition, options) {\n const stack = Object.entries(condition).slice();\n const selectors = {\n $and: [],\n $or: []\n };\n for (let i = 0; i < stack.length; i++) {\n const [key, val, op] = stack[i];\n if (key === field || key.startsWith(field + \".\")) {\n const normalizedExpr = (0, import_internal2.normalize)(val);\n const operator = Object.keys(normalizedExpr)[0];\n const expr = normalizedExpr[operator];\n const fn = options.context.getOperator(\n import_internal.OpType.QUERY,\n operator\n );\n const leaf2 = key.substring(key.lastIndexOf(\".\") + 1);\n const pred = fn(leaf2, expr, options);\n if (!op || op === \"$and\") {\n selectors.$and.push([key, pred, leaf2]);\n } else if (op === \"$nor\") {\n selectors.$and.push([key, complement(pred), leaf2]);\n } else if (op === \"$or\") {\n selectors.$or.push([key, pred, leaf2]);\n }\n } else if ((0, import_internal2.isOperator)(key)) {\n (0, import_internal2.assert)(\n !!COMPOUND_OPS[key],\n `${OP}: '${key}' is not allowed in this context`\n );\n for (const item of val) {\n for (const k of Object.keys(item)) stack.push([k, item[k], key]);\n }\n }\n }\n const sep = field.lastIndexOf(\".\");\n const parent = field.substring(0, sep) || field;\n const leaf = field.substring(sep + 1);\n return (t, o) => {\n const matches = [];\n for (const [key, pred, leaf2] of selectors.$and) {\n matches.push(findMatches(o, key, leaf2, pred));\n }\n if (selectors.$or.length) {\n const orMatches = [];\n for (const [key, pred, leaf2] of selectors.$or) {\n orMatches.push(...findMatches(o, key, leaf2, pred));\n }\n matches.push((0, import_internal2.unique)(orMatches));\n }\n const i = (0, import_internal2.intersection)(matches).sort()[0];\n let first = (0, import_internal2.resolve)(o, field)[i];\n if (parent != leaf && !(0, import_internal2.isObject)(first)) {\n first = { [leaf]: first };\n }\n (0, import_internal2.setValue)(t, parent, [first]);\n };\n}\nfunction mergeInto(target, input) {\n if (target === import_internal2.MISSING || (0, import_internal2.isNil)(target)) return input;\n if ((0, import_internal2.isNil)(input)) return target;\n const out = target;\n const src = input;\n for (const k of Object.keys(input)) {\n out[k] = mergeInto(out[k], src[k]);\n }\n return out;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $project\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar skip_exports = {};\n__export(skip_exports, {\n $skip: () => $skip\n});\nmodule.exports = __toCommonJS(skip_exports);\nvar import_util = require(\"../../util\");\nfunction $skip(coll, expr, _options) {\n (0, import_util.assert)(expr >= 0, \"$skip value must be a non-negative integer\");\n return coll.drop(expr);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $skip\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cursor_exports = {};\n__export(cursor_exports, {\n Cursor: () => Cursor\n});\nmodule.exports = __toCommonJS(cursor_exports);\nvar import_internal = require(\"./core/_internal\");\nvar import_lazy = require(\"./lazy\");\nvar import_limit = require(\"./operators/pipeline/limit\");\nvar import_project = require(\"./operators/pipeline/project\");\nvar import_skip = require(\"./operators/pipeline/skip\");\nvar import_sort = require(\"./operators/pipeline/sort\");\nvar import_util = require(\"./util\");\nconst OPERATORS = { $sort: import_sort.$sort, $skip: import_skip.$skip, $limit: import_limit.$limit };\nclass Cursor {\n #source;\n #predicate;\n #projection;\n #options;\n #operators = {};\n #result = null;\n #buffer = [];\n /**\n * Creates an instance of the Cursor class.\n *\n * @param source - The source of data to be iterated over.\n * @param predicate - A function or condition to filter the data.\n * @param projection - An object specifying the fields to include or exclude in the result.\n * @param options - Optional settings to customize the behavior of the cursor.\n */\n constructor(source, predicate, projection, options) {\n this.#source = source;\n this.#predicate = predicate;\n this.#projection = projection;\n this.#options = options;\n }\n /** Returns the iterator from running the query */\n fetch() {\n if (this.#result) return this.#result;\n this.#result = (0, import_lazy.Lazy)(this.#source).filter(this.#predicate);\n const mode = this.#options.processingMode;\n if (mode & import_internal.ProcessingMode.CLONE_INPUT) this.#result.map((o) => (0, import_util.cloneDeep)(o));\n for (const op of Object.keys(OPERATORS)) {\n if ((0, import_util.has)(this.#operators, op)) {\n const f = OPERATORS[op];\n this.#result = f(this.#result, this.#operators[op], this.#options);\n }\n }\n if (Object.keys(this.#projection).length) {\n this.#result = (0, import_project.$project)(this.#result, this.#projection, this.#options);\n }\n if (mode & import_internal.ProcessingMode.CLONE_OUTPUT) this.#result.map((o) => (0, import_util.cloneDeep)(o));\n return this.#result;\n }\n /** Returns an iterator with the buffered data included */\n fetchAll() {\n const buffered = (0, import_lazy.Lazy)(Array.from(this.#buffer));\n this.#buffer.length = 0;\n return (0, import_lazy.concat)(buffered, this.fetch());\n }\n /**\n * Return remaining objects in the cursor as an array. This method exhausts the cursor\n * @returns {Array}\n */\n all() {\n return this.fetchAll().collect();\n }\n /**\n * Returns a cursor that begins returning results only after passing or skipping a number of documents.\n * @param {Number} n the number of results to skip.\n * @return {Cursor} Returns the cursor, so you can chain this call.\n */\n skip(n) {\n this.#operators[\"$skip\"] = n;\n return this;\n }\n /**\n * Limits the number of items returned by the cursor.\n *\n * @param n - The maximum number of items to return.\n * @returns The current cursor instance for chaining.\n */\n limit(n) {\n this.#operators[\"$limit\"] = n;\n return this;\n }\n /**\n * Returns results ordered according to a sort specification.\n * @param {AnyObject} modifier an object of key and values specifying the sort order. 1 for ascending and -1 for descending\n * @return {Cursor} Returns the cursor, so you can chain this call.\n */\n sort(modifier) {\n this.#operators[\"$sort\"] = modifier;\n return this;\n }\n /**\n * Sets the collation options for the cursor.\n * Collation allows users to specify language-specific rules for string comparison,\n * such as case sensitivity and accent marks.\n *\n * @param spec - The collation specification to apply.\n * @returns The current cursor instance for chaining.\n */\n collation(spec) {\n this.#options = { ...this.#options, collation: spec };\n return this;\n }\n /**\n * Retrieves the next item in the cursor.\n */\n next() {\n if (this.#buffer.length > 0) {\n return this.#buffer.pop();\n }\n const o = this.fetch().next();\n if (o.done) return void 0;\n return o.value;\n }\n /**\n * Determines if there are more elements available in the cursor.\n *\n * @returns {boolean} `true` if there are more elements to iterate over, otherwise `false`.\n */\n hasNext() {\n if (this.#buffer.length > 0) return true;\n const o = this.fetch().next();\n if (o.done) return false;\n this.#buffer.push(o.value);\n return true;\n }\n /**\n * Returns an iterator for the cursor, allowing it to be used in `for...of` loops.\n * The iterator fetches all the results from the cursor.\n *\n * @returns {Iterator} An iterator over the fetched results.\n */\n [Symbol.iterator]() {\n return this.fetchAll();\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Cursor\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar query_exports = {};\n__export(query_exports, {\n Query: () => Query\n});\nmodule.exports = __toCommonJS(query_exports);\nvar import_internal = require(\"./core/_internal\");\nvar import_cursor = require(\"./cursor\");\nvar import_util = require(\"./util\");\nconst TOP_LEVEL_OPS = /* @__PURE__ */ new Set([\"$and\", \"$or\", \"$nor\", \"$expr\", \"$jsonSchema\"]);\nclass Query {\n #compiled;\n #condition;\n #options;\n /**\n * Creates an instance of the query with the specified condition and options.\n * This object is preloaded with all query and projection operators.\n *\n * @param condition - The query condition object used to define the criteria for matching documents.\n * @param options - Optional configuration settings to customize the query behavior.\n */\n constructor(condition, options) {\n this.#condition = (0, import_util.cloneDeep)(condition);\n this.#options = import_internal.ComputeOptions.init(options).update({\n condition\n });\n this.#compiled = [];\n this.compile();\n }\n compile() {\n (0, import_util.assert)(\n (0, import_util.isObject)(this.#condition),\n `query criteria must be an object: ${JSON.stringify(this.#condition)}`\n );\n const whereOperator = {};\n for (const field of Object.keys(this.#condition)) {\n const expr = this.#condition[field];\n if (\"$where\" === field) {\n (0, import_util.assert)(\n this.#options.scriptEnabled,\n \"$where operator requires 'scriptEnabled' option to be true.\"\n );\n Object.assign(whereOperator, { field, expr });\n } else if (TOP_LEVEL_OPS.has(field)) {\n this.processOperator(field, field, expr);\n } else {\n (0, import_util.assert)(!(0, import_util.isOperator)(field), `unknown top level operator: ${field}`);\n const normalizedExpr = (0, import_util.normalize)(expr);\n for (const operator of Object.keys(normalizedExpr)) {\n this.processOperator(field, operator, normalizedExpr[operator]);\n }\n }\n if (whereOperator.field) {\n this.processOperator(\n whereOperator.field,\n whereOperator.field,\n whereOperator.expr\n );\n }\n }\n }\n processOperator(field, operator, value) {\n const fn = this.#options.context.getOperator(\n import_internal.OpType.QUERY,\n operator\n );\n (0, import_util.assert)(!!fn, `unknown query operator ${operator}`);\n this.#compiled.push(fn(field, value, this.#options));\n }\n /**\n * Tests whether the given object satisfies all compiled predicates.\n *\n * @template T - The type of the object to test.\n * @param obj - The object to be tested against the compiled predicates.\n * @returns `true` if the object satisfies all predicates, otherwise `false`.\n */\n test(obj) {\n return this.#compiled.every((p) => p(obj));\n }\n /**\n * Returns a cursor for iterating over the items in the given collection that match the query criteria.\n *\n * @typeParam T - The type of the items in the resulting cursor.\n * @param collection - The source collection to search through.\n * @param projection - An optional object specifying fields to include or exclude\n * in the returned items.\n * @returns A `Cursor` instance for iterating over the matching items.\n */\n find(collection, projection) {\n return new import_cursor.Cursor(\n collection,\n (o) => this.test(o),\n projection || {},\n this.#options\n );\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Query\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar predicates_exports = {};\n__export(predicates_exports, {\n $all: () => $all,\n $elemMatch: () => $elemMatch,\n $eq: () => $eq,\n $gt: () => $gt,\n $gte: () => $gte,\n $in: () => $in,\n $lt: () => $lt,\n $lte: () => $lte,\n $mod: () => $mod,\n $ne: () => $ne,\n $nin: () => $nin,\n $regex: () => $regex,\n $size: () => $size,\n $type: () => $type,\n processExpression: () => processExpression,\n processQuery: () => processQuery\n});\nmodule.exports = __toCommonJS(predicates_exports);\nvar import_internal = require(\"../core/_internal\");\nvar import_query = require(\"../query\");\nvar import_internal2 = require(\"../util/_internal\");\nfunction elemMatchPredicate(criteria, options) {\n let format = (x) => x;\n let wrap = true;\n for (const k of Object.keys(criteria)) {\n wrap &&= (0, import_internal2.isOperator)(k) && \"$and\" !== k && \"$or\" !== k && \"$nor\" !== k;\n if (!wrap) break;\n }\n if (wrap) {\n criteria = { field: criteria };\n format = (x) => ({ field: x });\n }\n const q = new import_query.Query(criteria, options);\n return (v) => q.test(format(v));\n}\nfunction processQuery(selector, value, options, predicate) {\n const pathArray = selector.split(\".\");\n const depth = Math.max(1, pathArray.length - 1);\n const copts = import_internal.ComputeOptions.init(options).update({ depth });\n const opts = { unwrapArray: true, pathArray };\n if (predicate === $elemMatch) {\n value = elemMatchPredicate(value, options);\n }\n return (o) => {\n const lhs = (0, import_internal2.resolve)(o, selector, opts);\n return predicate(lhs, value, copts);\n };\n}\nfunction processExpression(obj, expr, options, predicate) {\n (0, import_internal2.assert)(\n (0, import_internal2.isArray)(expr) && expr.length === 2,\n `${predicate.name} expects array(2)`\n );\n const [lhs, rhs] = (0, import_internal.evalExpr)(obj, expr, options);\n return predicate(lhs, rhs, options);\n}\nfunction $eq(a, b, options) {\n if ((0, import_internal2.isEqual)(a, b)) return true;\n if ((0, import_internal2.isNil)(a) && (0, import_internal2.isNil)(b)) return true;\n if ((0, import_internal2.isArray)(a)) {\n const depth = options?.local?.depth ?? 1;\n return a.some((v) => (0, import_internal2.isEqual)(v, b)) || (0, import_internal2.flatten)(a, depth).some((v) => (0, import_internal2.isEqual)(v, b));\n }\n return false;\n}\nfunction $ne(a, b, options) {\n return !$eq(a, b, options);\n}\nfunction $in(a, b, _options) {\n if ((0, import_internal2.isNil)(a)) return b.some((v) => v === null);\n return (0, import_internal2.intersection)([(0, import_internal2.ensureArray)(a), b]).length > 0;\n}\nfunction $nin(a, b, options) {\n return !$in(a, b, options);\n}\nfunction $lt(a, b, _options) {\n return compare(a, b, (x, y) => (0, import_internal2.compare)(x, y) < 0);\n}\nfunction $lte(a, b, _options) {\n return compare(a, b, (x, y) => (0, import_internal2.compare)(x, y) <= 0);\n}\nfunction $gt(a, b, _options) {\n return compare(a, b, (x, y) => (0, import_internal2.compare)(x, y) > 0);\n}\nfunction $gte(a, b, _options) {\n return compare(a, b, (x, y) => (0, import_internal2.compare)(x, y) >= 0);\n}\nfunction $mod(a, b, _options) {\n return (0, import_internal2.ensureArray)(a).some(\n ((x) => b.length === 2 && x % b[0] === b[1])\n );\n}\nfunction $regex(a, b, options) {\n const lhs = (0, import_internal2.ensureArray)(a);\n const match = (x) => (0, import_internal2.isString)(x) && (0, import_internal2.truthy)(b.exec(x), options?.useStrictMode);\n return lhs.some(match) || (0, import_internal2.flatten)(lhs, 1).some(match);\n}\nfunction $all(values, rhs, options) {\n if (!(0, import_internal2.isArray)(values) || !(0, import_internal2.isArray)(rhs) || !values.length || !rhs.length) {\n return false;\n }\n let matched = true;\n for (const expr of rhs) {\n if (!matched) break;\n if ((0, import_internal2.isObject)(expr) && Object.keys(expr)[0] === \"$elemMatch\") {\n const criteria = expr[\"$elemMatch\"];\n const pred = elemMatchPredicate(criteria, options);\n matched = $elemMatch(values, pred, options);\n } else if ((0, import_internal2.isRegExp)(expr)) {\n matched = values.some((s) => (0, import_internal2.isString)(s) && expr.test(s));\n } else {\n matched = values.some((v) => (0, import_internal2.isEqual)(expr, v));\n }\n }\n return matched;\n}\nfunction $size(a, b, _options) {\n return Array.isArray(a) && a.length === b;\n}\nfunction $elemMatch(a, b, _options) {\n if ((0, import_internal2.isArray)(a) && !(0, import_internal2.isEmpty)(a)) {\n for (let i = 0, len = a.length; i < len; i++) if (b(a[i])) return true;\n }\n return false;\n}\nconst isNull = (a) => a === null;\nconst compareFuncs = {\n array: import_internal2.isArray,\n boolean: import_internal2.isBoolean,\n bool: import_internal2.isBoolean,\n date: import_internal2.isDate,\n number: import_internal2.isNumber,\n int: import_internal2.isNumber,\n long: import_internal2.isNumber,\n double: import_internal2.isNumber,\n decimal: import_internal2.isNumber,\n null: isNull,\n object: import_internal2.isObject,\n regexp: import_internal2.isRegExp,\n regex: import_internal2.isRegExp,\n string: import_internal2.isString,\n // added for completeness\n undefined: import_internal2.isNil,\n // deprecated\n // Mongo identifiers\n 1: import_internal2.isNumber,\n //double\n 2: import_internal2.isString,\n 3: import_internal2.isObject,\n 4: import_internal2.isArray,\n 6: import_internal2.isNil,\n // deprecated\n 8: import_internal2.isBoolean,\n 9: import_internal2.isDate,\n 10: isNull,\n 11: import_internal2.isRegExp,\n 16: import_internal2.isNumber,\n //int\n 18: import_internal2.isNumber,\n //long\n 19: import_internal2.isNumber\n //decimal\n};\nfunction compareType(a, b, _) {\n const f = compareFuncs[b];\n return f ? f(a) : false;\n}\nfunction $type(a, b, options) {\n return (0, import_internal2.isArray)(b) ? b.findIndex((t) => compareType(a, t, options)) >= 0 : compareType(a, b, options);\n}\nfunction compare(a, b, f) {\n for (const v of (0, import_internal2.ensureArray)(a)) {\n if ((0, import_internal2.typeOf)(v) === (0, import_internal2.typeOf)(b) && f(v, b)) return true;\n }\n return false;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $all,\n $elemMatch,\n $eq,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $mod,\n $ne,\n $nin,\n $regex,\n $size,\n $type,\n processExpression,\n processQuery\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar eq_exports = {};\n__export(eq_exports, {\n $eq: () => $eq\n});\nmodule.exports = __toCommonJS(eq_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $eq = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$eq);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $eq\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar gt_exports = {};\n__export(gt_exports, {\n $gt: () => $gt\n});\nmodule.exports = __toCommonJS(gt_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $gt = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$gt);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $gt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar gte_exports = {};\n__export(gte_exports, {\n $gte: () => $gte\n});\nmodule.exports = __toCommonJS(gte_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $gte = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$gte);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $gte\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lt_exports = {};\n__export(lt_exports, {\n $lt: () => $lt\n});\nmodule.exports = __toCommonJS(lt_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $lt = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$lt);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lte_exports = {};\n__export(lte_exports, {\n $lte: () => $lte\n});\nmodule.exports = __toCommonJS(lte_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $lte = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$lte);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lte\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ne_exports = {};\n__export(ne_exports, {\n $ne: () => $ne\n});\nmodule.exports = __toCommonJS(ne_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $ne = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$ne);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ne\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar comparison_exports = {};\nmodule.exports = __toCommonJS(comparison_exports);\n__reExport(comparison_exports, require(\"./cmp\"), module.exports);\n__reExport(comparison_exports, require(\"./eq\"), module.exports);\n__reExport(comparison_exports, require(\"./gt\"), module.exports);\n__reExport(comparison_exports, require(\"./gte\"), module.exports);\n__reExport(comparison_exports, require(\"./lt\"), module.exports);\n__reExport(comparison_exports, require(\"./lte\"), module.exports);\n__reExport(comparison_exports, require(\"./ne\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./cmp\"),\n ...require(\"./eq\"),\n ...require(\"./gt\"),\n ...require(\"./gte\"),\n ...require(\"./lt\"),\n ...require(\"./lte\"),\n ...require(\"./ne\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cond_exports = {};\n__export(cond_exports, {\n $cond: () => $cond\n});\nmodule.exports = __toCommonJS(cond_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nconst err = \"$cond expects array(3) or object with 'if-then-else' expressions\";\nconst $cond = (obj, expr, options) => {\n let ifExpr;\n let thenExpr;\n let elseExpr;\n if ((0, import_internal2.isArray)(expr)) {\n (0, import_internal2.assert)(expr.length === 3, err);\n ifExpr = expr[0];\n thenExpr = expr[1];\n elseExpr = expr[2];\n } else {\n (0, import_internal2.assert)((0, import_internal2.isObject)(expr), err);\n ifExpr = expr.if;\n thenExpr = expr.then;\n elseExpr = expr.else;\n }\n const condition = (0, import_internal2.truthy)(\n (0, import_internal.evalExpr)(obj, ifExpr, options),\n options.useStrictMode\n );\n return (0, import_internal.evalExpr)(obj, condition ? thenExpr : elseExpr, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $cond\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ifNull_exports = {};\n__export(ifNull_exports, {\n $ifNull: () => $ifNull\n});\nmodule.exports = __toCommonJS(ifNull_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $ifNull = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$ifNull expects an array\");\n let val = void 0;\n for (const input of expr) {\n val = (0, import_internal.evalExpr)(obj, input, options);\n if (!(0, import_util.isNil)(val)) return val;\n }\n return val;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ifNull\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar switch_exports = {};\n__export(switch_exports, {\n $switch: () => $switch\n});\nmodule.exports = __toCommonJS(switch_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nconst $switch = (obj, expr, options) => {\n (0, import_internal2.assert)((0, import_internal2.isObject)(expr), \"$switch received invalid arguments\");\n for (const { case: caseExpr, then } of expr.branches) {\n const condition = (0, import_internal2.truthy)(\n (0, import_internal.evalExpr)(obj, caseExpr, options),\n options.useStrictMode\n );\n if (condition) return (0, import_internal.evalExpr)(obj, then, options);\n }\n return (0, import_internal.evalExpr)(obj, expr.default, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $switch\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar conditional_exports = {};\nmodule.exports = __toCommonJS(conditional_exports);\n__reExport(conditional_exports, require(\"./cond\"), module.exports);\n__reExport(conditional_exports, require(\"./ifNull\"), module.exports);\n__reExport(conditional_exports, require(\"./switch\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./cond\"),\n ...require(\"./ifNull\"),\n ...require(\"./switch\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar function_exports = {};\n__export(function_exports, {\n $function: () => $function\n});\nmodule.exports = __toCommonJS(function_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $function = (obj, expr, options) => {\n (0, import_util.assert)(\n options.scriptEnabled,\n \"$function requires 'scriptEnabled' option to be true\"\n );\n const fn = (0, import_internal.evalExpr)(obj, expr, options);\n return fn.body.apply(null, fn.args);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $function\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar custom_exports = {};\nmodule.exports = __toCommonJS(custom_exports);\n__reExport(custom_exports, require(\"./function\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./function\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n DATE_FORMAT: () => DATE_FORMAT,\n DATE_FORMAT_SEP_RE: () => DATE_FORMAT_SEP_RE,\n DATE_FORMAT_SYM_RE: () => DATE_FORMAT_SYM_RE,\n DATE_PART_INTERVAL: () => DATE_PART_INTERVAL,\n DATE_SYM_TABLE: () => DATE_SYM_TABLE,\n DAYS_PER_WEEK: () => DAYS_PER_WEEK,\n LEAP_YEAR_REF_POINT: () => LEAP_YEAR_REF_POINT,\n MINUTES_PER_HOUR: () => MINUTES_PER_HOUR,\n MONTHS: () => MONTHS,\n TIMEUNIT_IN_MILLIS: () => TIMEUNIT_IN_MILLIS,\n TIME_UNITS: () => TIME_UNITS,\n adjustDate: () => adjustDate,\n computeDate: () => computeDate,\n dateAdd: () => dateAdd,\n dateDiffDay: () => dateDiffDay,\n dateDiffHour: () => dateDiffHour,\n dateDiffMonth: () => dateDiffMonth,\n dateDiffQuarter: () => dateDiffQuarter,\n dateDiffWeek: () => dateDiffWeek,\n dateDiffYear: () => dateDiffYear,\n dayOfYear: () => dayOfYear,\n daysBetweenYears: () => daysBetweenYears,\n formatTimezone: () => formatTimezone,\n isDST: () => isDST,\n isLeapYear: () => isLeapYear,\n isoWeek: () => isoWeek,\n isoWeekYear: () => isoWeekYear,\n isoWeekday: () => isoWeekday,\n padDigits: () => padDigits,\n parseTimezone: () => parseTimezone,\n weekOfYear: () => weekOfYear\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst TIME_UNITS = [\n \"year\",\n \"quarter\",\n \"month\",\n \"week\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"millisecond\"\n];\nconst ISO_WEEKDAYS = {\n mon: 1,\n tue: 2,\n wed: 3,\n thu: 4,\n fri: 5,\n sat: 6,\n sun: 7\n};\nconst LEAP_YEAR_REF_POINT = -1e9;\nconst DAYS_PER_WEEK = 7;\nconst isLeapYear = (y) => (y & 3) == 0 && (y % 100 != 0 || y % 400 == 0);\nfunction isDST(date) {\n const jan = new Date(date.getFullYear(), 0, 1).getTimezoneOffset();\n const jul = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();\n return Math.max(jan, jul) !== date.getTimezoneOffset();\n}\nconst DAYS_IN_YEAR = [\n 365,\n 366\n /*leap*/\n];\nconst YEAR_DAYS_OFFSET = [\n [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],\n [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]\n /*leap*/\n];\nconst dayOfYear = (d) => YEAR_DAYS_OFFSET[+isLeapYear(d.getUTCFullYear())][d.getUTCMonth()] + d.getUTCDate();\nconst isoWeekday = (date, startOfWeek) => {\n const dow = date.getUTCDay() || 7;\n const name = startOfWeek.toLowerCase().substring(0, 3);\n return (dow - ISO_WEEKDAYS[name] + DAYS_PER_WEEK) % DAYS_PER_WEEK;\n};\nconst p = (y) => (y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400)) % 7;\nconst weeks = (y) => 52 + Number(p(y) == 4 || p(y - 1) == 3);\nfunction isoWeek(d) {\n const dow = d.getUTCDay() || 7;\n const w = Math.floor((10 + dayOfYear(d) - dow) / 7);\n if (w < 1) return weeks(d.getUTCFullYear() - 1);\n if (w > weeks(d.getUTCFullYear())) return 1;\n return w;\n}\nfunction weekOfYear(d) {\n const result = isoWeek(d);\n if (d.getUTCDay() > 0 && d.getUTCDate() == 1 && d.getUTCMonth() == 0)\n return 0;\n if (d.getUTCDay() == 0) return result + 1;\n return result;\n}\nfunction isoWeekYear(d) {\n return d.getUTCFullYear() - Number(d.getUTCMonth() === 0 && d.getUTCDate() == 1 && d.getUTCDay() < 1);\n}\nconst MINUTES_PER_HOUR = 60;\nconst TIMEUNIT_IN_MILLIS = {\n week: 6048e5,\n day: 864e5,\n hour: 36e5,\n minute: 6e4,\n second: 1e3,\n millisecond: 1\n};\nconst DATE_FORMAT = \"%Y-%m-%dT%H:%M:%S.%LZ\";\nconst DATE_PART_INTERVAL = [\n [\"year\", 0, 9999],\n [\"month\", 1, 12],\n [\"day\", 1, 31],\n [\"hour\", 0, 23],\n [\"minute\", 0, 59],\n [\"second\", 0, 59],\n [\"millisecond\", 0, 999]\n];\nconst MONTHS = {\n jan: 1,\n feb: 2,\n mar: 3,\n apr: 4,\n may: 5,\n jun: 6,\n jul: 7,\n aug: 8,\n sep: 9,\n oct: 10,\n nov: 11,\n dec: 12\n};\nconst DATE_SYM_TABLE = {\n \"%b\": {\n name: \"abbr_month\",\n padding: 3,\n re: /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i\n },\n \"%B\": {\n name: \"full_month\",\n padding: 0,\n re: /(January|February|March|April|May|June|July|August|September|October|November|December)/i\n },\n \"%Y\": { name: \"year\", padding: 4, re: /([0-9]{4})/ },\n \"%G\": { name: \"year\", padding: 4, re: /([0-9]{4})/ },\n \"%m\": { name: \"month\", padding: 2, re: /(0[1-9]|1[012])/ },\n \"%d\": { name: \"day\", padding: 2, re: /(0[1-9]|[12][0-9]|3[01])/ },\n \"%j\": {\n name: \"day_of_year\",\n padding: 3,\n re: /(0[0-9][1-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-6])/\n },\n \"%H\": { name: \"hour\", padding: 2, re: /([01][0-9]|2[0-3])/ },\n \"%M\": { name: \"minute\", padding: 2, re: /([0-5][0-9])/ },\n \"%S\": { name: \"second\", padding: 2, re: /([0-5][0-9]|60)/ },\n \"%L\": { name: \"millisecond\", padding: 3, re: /([0-9]{3})/ },\n \"%w\": { name: \"day_of_week\", padding: 1, re: /([0-6])/ },\n \"%u\": { name: \"day_of_week_iso\", padding: 1, re: /([1-7])/ },\n \"%U\": { name: \"week_of_year\", padding: 2, re: /([1-4][0-9]?|5[0-3]?)/ },\n \"%V\": { name: \"week_of_year_iso\", padding: 2, re: /([1-4][0-9]?|5[0-3]?)/ },\n \"%z\": {\n name: \"timezone\",\n padding: 2,\n re: /(([+-][01][0-9]|2[0-3]):?([0-5][0-9])?)/\n },\n \"%Z\": { name: \"minute_offset\", padding: 3, re: /([+-][0-9]{3})/ },\n \"%%\": { name: \"percent_literal\", padding: 1, re: /%%/ }\n};\nconst DATE_FORMAT_SYM_RE = /(%[bBYGmdjHMSLwuUVzZ%])/g;\nconst DATE_FORMAT_SEP_RE = /%[bBYGmdjHMSLwuUVzZ%]/;\nconst TIMEZONE_RE = /^[a-zA-Z_]+\\/[a-zA-Z_]+$/;\nfunction parseTimezone(timeZone, date) {\n if (timeZone === void 0) return 0;\n if (TIMEZONE_RE.test(timeZone)) {\n const utcDate = new Date(date.toLocaleString(\"en-US\", { timeZone: \"UTC\" }));\n const tzDate = new Date(date.toLocaleString(\"en-US\", { timeZone }));\n return Math.round((tzDate.getTime() - utcDate.getTime()) / 6e4);\n }\n const match = DATE_SYM_TABLE[\"%z\"].re.exec(timeZone) ?? [];\n (0, import_util.assert)(!!match, `timezone '${timeZone}' is invalid or not supported.`);\n const hr = parseInt(match[2]) || 0;\n const min = parseInt(match[3]) || 0;\n return (Math.abs(hr * MINUTES_PER_HOUR) + min) * (hr < 0 ? -1 : 1);\n}\nfunction formatTimezone(minuteOffset) {\n return (minuteOffset < 0 ? \"-\" : \"+\") + padDigits(Math.abs(Math.floor(minuteOffset / MINUTES_PER_HOUR)), 2) + padDigits(Math.abs(minuteOffset) % MINUTES_PER_HOUR, 2);\n}\nfunction adjustDate(d, minuteOffset) {\n d.setUTCMinutes(d.getUTCMinutes() + minuteOffset);\n}\nfunction computeDate(obj, expr, options) {\n if ((0, import_util.isDate)(obj)) return obj;\n const d = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isDate)(d)) return new Date(d);\n if ((0, import_util.isNumber)(d)) return new Date(d * 1e3);\n (0, import_util.assert)(!!d?.date, `cannot convert ${JSON.stringify(expr)} to date`);\n const date = (0, import_util.isDate)(d.date) ? new Date(d.date) : new Date(d.date * 1e3);\n if (d.timezone) adjustDate(date, parseTimezone(d.timezone, date));\n return date;\n}\nfunction padDigits(n, digits) {\n return new Array(Math.max(digits - String(n).length + 1, 0)).join(\"0\") + n.toString();\n}\nconst leapYearsSinceReferencePoint = (year) => {\n const yearsSinceReferencePoint = year - LEAP_YEAR_REF_POINT;\n return Math.trunc(yearsSinceReferencePoint / 4) - Math.trunc(yearsSinceReferencePoint / 100) + Math.trunc(yearsSinceReferencePoint / 400);\n};\nfunction daysBetweenYears(startYear, endYear) {\n return Math.trunc(\n leapYearsSinceReferencePoint(endYear - 1) - leapYearsSinceReferencePoint(startYear - 1) + (endYear - startYear) * DAYS_IN_YEAR[0]\n );\n}\nconst dateDiffYear = (start, end) => end.getUTCFullYear() - start.getUTCFullYear();\nconst dateDiffMonth = (start, end) => end.getUTCMonth() - start.getUTCMonth() + dateDiffYear(start, end) * 12;\nconst dateDiffQuarter = (start, end) => {\n const a = Math.trunc(start.getUTCMonth() / 3);\n const b = Math.trunc(end.getUTCMonth() / 3);\n return b - a + dateDiffYear(start, end) * 4;\n};\nconst dateDiffDay = (start, end) => dayOfYear(end) - dayOfYear(start) + daysBetweenYears(start.getUTCFullYear(), end.getUTCFullYear());\nconst dateDiffWeek = (start, end, startOfWeek) => {\n const wk = (startOfWeek || \"sun\").substring(0, 3);\n return Math.trunc(\n (dateDiffDay(start, end) + isoWeekday(start, wk) - isoWeekday(end, wk)) / DAYS_PER_WEEK\n );\n};\nconst dateDiffHour = (start, end) => end.getUTCHours() - start.getUTCHours() + dateDiffDay(start, end) * 24;\nconst addMonth = (d, amount) => {\n const m = d.getUTCMonth() + amount;\n const yearOffset = Math.floor(m / 12);\n if (m < 0) {\n const month = m % 12 + 12;\n d.setUTCFullYear(d.getUTCFullYear() + yearOffset, month, d.getUTCDate());\n } else {\n d.setUTCFullYear(d.getUTCFullYear() + yearOffset, m % 12, d.getUTCDate());\n }\n};\nconst dateAdd = (date, unit, amount, _timezone) => {\n const d = new Date(date);\n switch (unit) {\n case \"year\":\n d.setUTCFullYear(d.getUTCFullYear() + amount);\n break;\n case \"quarter\":\n addMonth(d, 3 * amount);\n break;\n case \"month\":\n addMonth(d, amount);\n break;\n default:\n d.setTime(d.getTime() + TIMEUNIT_IN_MILLIS[unit] * amount);\n }\n return d;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n DATE_FORMAT,\n DATE_FORMAT_SEP_RE,\n DATE_FORMAT_SYM_RE,\n DATE_PART_INTERVAL,\n DATE_SYM_TABLE,\n DAYS_PER_WEEK,\n LEAP_YEAR_REF_POINT,\n MINUTES_PER_HOUR,\n MONTHS,\n TIMEUNIT_IN_MILLIS,\n TIME_UNITS,\n adjustDate,\n computeDate,\n dateAdd,\n dateDiffDay,\n dateDiffHour,\n dateDiffMonth,\n dateDiffQuarter,\n dateDiffWeek,\n dateDiffYear,\n dayOfYear,\n daysBetweenYears,\n formatTimezone,\n isDST,\n isLeapYear,\n isoWeek,\n isoWeekYear,\n isoWeekday,\n padDigits,\n parseTimezone,\n weekOfYear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateAdd_exports = {};\n__export(dateAdd_exports, {\n $dateAdd: () => $dateAdd\n});\nmodule.exports = __toCommonJS(dateAdd_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst $dateAdd = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_internal2.dateAdd)(args.startDate, args.unit, args.amount, args.timezone);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateAdd\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateDiff_exports = {};\n__export(dateDiff_exports, {\n $dateDiff: () => $dateDiff\n});\nmodule.exports = __toCommonJS(dateDiff_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst $dateDiff = (obj, expr, options) => {\n const { startDate, endDate, unit, timezone, startOfWeek } = (0, import_internal.evalExpr)(\n obj,\n expr,\n options\n );\n const d1 = new Date(startDate);\n const d2 = new Date(endDate);\n (0, import_internal2.adjustDate)(d1, (0, import_internal2.parseTimezone)(timezone, d1));\n (0, import_internal2.adjustDate)(d2, (0, import_internal2.parseTimezone)(timezone, d2));\n switch (unit) {\n case \"year\":\n return (0, import_internal2.dateDiffYear)(d1, d2);\n case \"quarter\":\n return (0, import_internal2.dateDiffQuarter)(d1, d2);\n case \"month\":\n return (0, import_internal2.dateDiffMonth)(d1, d2);\n case \"week\":\n return (0, import_internal2.dateDiffWeek)(d1, d2, startOfWeek);\n case \"day\":\n return (0, import_internal2.dateDiffDay)(d1, d2);\n case \"hour\":\n return (0, import_internal2.dateDiffHour)(d1, d2);\n case \"minute\":\n d1.setUTCSeconds(0);\n d1.setUTCMilliseconds(0);\n d2.setUTCSeconds(0);\n d2.setUTCMilliseconds(0);\n return Math.round(\n (d2.getTime() - d1.getTime()) / import_internal2.TIMEUNIT_IN_MILLIS[unit]\n );\n default:\n return Math.round(\n (d2.getTime() - d1.getTime()) / import_internal2.TIMEUNIT_IN_MILLIS[unit]\n );\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateDiff\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateFromParts_exports = {};\n__export(dateFromParts_exports, {\n $dateFromParts: () => $dateFromParts\n});\nmodule.exports = __toCommonJS(dateFromParts_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst getDaysInMonth = (date) => {\n return date.month == 2 && (0, import_internal2.isLeapYear)(date.year) ? 29 : DAYS_IN_MONTH[date.month - 1];\n};\nconst $dateFromParts = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const minuteOffset = (0, import_internal2.parseTimezone)(args.timezone, /* @__PURE__ */ new Date());\n for (let i = import_internal2.DATE_PART_INTERVAL.length - 1, remainder = 0; i >= 0; i--) {\n const datePartInterval = import_internal2.DATE_PART_INTERVAL[i];\n const k = datePartInterval[0];\n const min = datePartInterval[1];\n const max = datePartInterval[2];\n let part = (args[k] || 0) + remainder;\n remainder = 0;\n const limit = max + 1;\n if (k == \"hour\") part += Math.floor(minuteOffset / import_internal2.MINUTES_PER_HOUR) * -1;\n if (k == \"minute\") part += minuteOffset % import_internal2.MINUTES_PER_HOUR * -1;\n if (part < min) {\n const delta = min - part;\n remainder = -1 * Math.ceil(delta / limit);\n part = limit - delta % limit;\n } else if (part > max) {\n part += min;\n remainder = Math.trunc(part / limit);\n part %= limit;\n }\n args[k] = part;\n }\n args.day = Math.min(args.day, getDaysInMonth(args));\n return new Date(\n Date.UTC(\n args.year,\n args.month - 1,\n args.day,\n args.hour,\n args.minute,\n args.second,\n args.millisecond\n )\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateFromParts\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateFromString_exports = {};\n__export(dateFromString_exports, {\n $dateFromString: () => $dateFromString\n});\nmodule.exports = __toCommonJS(dateFromString_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nfunction tzLetterOffset(c) {\n if (c === \"Z\") return 0;\n if (c >= \"A\" && c < \"N\") return c.charCodeAt(0) - 64;\n return 77 - c.charCodeAt(0);\n}\nconst regexStrip = (s) => s.replace(/^\\//, \"\").replace(/\\/$/, \"\").replace(/\\/i/, \"\");\nconst REGEX_SPECIAL_CHARS = [\"^\", \".\", \"-\", \"*\", \"?\", \"$\"];\nfunction regexQuote(s) {\n for (const c of REGEX_SPECIAL_CHARS) s = s.replace(c, `\\\\${c}`);\n return s;\n}\nfunction $dateFromString(obj, expr, options) {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const format = args.format || import_internal2.DATE_FORMAT;\n const onNull = args.onNull || null;\n let dateString = args.dateString;\n if ((0, import_util.isNil)(dateString)) return onNull;\n const separators = format.split(import_internal2.DATE_FORMAT_SEP_RE);\n separators.reverse();\n const matches = format.match(import_internal2.DATE_FORMAT_SYM_RE);\n const dateParts = {};\n let expectedPattern = \"\";\n for (let i = 0, len = matches.length; i < len; i++) {\n const formatSpecifier = matches[i];\n const props = import_internal2.DATE_SYM_TABLE[formatSpecifier];\n if ((0, import_util.isObject)(props)) {\n const m2 = props.re.exec(dateString);\n const delimiter = separators.pop() || \"\";\n if (m2 !== null) {\n dateParts[props.name] = /^\\d+$/.exec(m2[0]) ? parseInt(m2[0]) : m2[0];\n dateString = dateString.substring(m2.index + m2[0].length + 1);\n expectedPattern += regexQuote(delimiter) + regexStrip(props.re.toString());\n } else {\n dateParts[props.name] = null;\n }\n }\n }\n if ((0, import_util.isNil)(dateParts.month)) {\n const abbrMonth = (dateParts.full_month?.slice(0, 3) ?? dateParts.abbr_month ?? \"\").toLowerCase();\n if (import_internal2.MONTHS[abbrMonth]) {\n dateParts.month = import_internal2.MONTHS[abbrMonth];\n }\n }\n if ((0, import_util.isNil)(dateParts.year) || (0, import_util.isNil)(dateParts.month) || (0, import_util.isNil)(dateParts.day) || !new RegExp(\"^\" + expectedPattern + \"[A-Z]?$\").test(args.dateString)) {\n return args.onError;\n }\n const m = args.dateString.match(/([A-Z])$/);\n (0, import_util.assert)(\n // only one of in-date timeone or timezone argument but not both.\n !(m && args.timezone),\n `$dateFromString: you cannot pass in a date/time string with time zone information ('${m && m[0]}') together with a timezone argument`\n );\n const minuteOffset = m ? tzLetterOffset(m[0]) * import_internal2.MINUTES_PER_HOUR : (0, import_internal2.parseTimezone)(args.timezone, /* @__PURE__ */ new Date());\n const d = new Date(\n Date.UTC(dateParts.year, dateParts.month - 1, dateParts.day, 0, 0, 0)\n );\n if (!(0, import_util.isNil)(dateParts.hour)) d.setUTCHours(dateParts.hour);\n if (!(0, import_util.isNil)(dateParts.minute)) d.setUTCMinutes(dateParts.minute);\n if (!(0, import_util.isNil)(dateParts.second)) d.setUTCSeconds(dateParts.second);\n if (!(0, import_util.isNil)(dateParts.millisecond))\n d.setUTCMilliseconds(dateParts.millisecond);\n (0, import_internal2.adjustDate)(d, -minuteOffset);\n return d;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateFromString\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateSubtract_exports = {};\n__export(dateSubtract_exports, {\n $dateSubtract: () => $dateSubtract\n});\nmodule.exports = __toCommonJS(dateSubtract_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst $dateSubtract = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_internal2.dateAdd)(args.startDate, args.unit, -args.amount, args.timezone);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateSubtract\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateToParts_exports = {};\n__export(dateToParts_exports, {\n $dateToParts: () => $dateToParts\n});\nmodule.exports = __toCommonJS(dateToParts_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst $dateToParts = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const d = new Date(args.date);\n (0, import_internal2.adjustDate)(d, (0, import_internal2.parseTimezone)(args.timezone, d));\n const timePart = {\n hour: d.getUTCHours(),\n minute: d.getUTCMinutes(),\n second: d.getUTCSeconds(),\n millisecond: d.getUTCMilliseconds()\n };\n if (args.iso8601 == true) {\n return Object.assign(timePart, {\n isoWeekYear: (0, import_internal2.isoWeekYear)(d),\n isoWeek: (0, import_internal2.isoWeek)(d),\n isoDayOfWeek: d.getUTCDay() || 7\n });\n }\n return Object.assign(timePart, {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate()\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateToParts\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateToString_exports = {};\n__export(dateToString_exports, {\n $dateToString: () => $dateToString\n});\nmodule.exports = __toCommonJS(dateToString_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst DATE_FUNCTIONS = {\n \"%Y\": (d) => d.getUTCFullYear(),\n //year\n \"%G\": (d) => d.getUTCFullYear(),\n //year\n \"%m\": (d) => d.getUTCMonth() + 1,\n //month\n \"%d\": (d) => d.getUTCDate(),\n //dayOfMonth\n \"%H\": (d) => d.getUTCHours(),\n //hour\n \"%M\": (d) => d.getUTCMinutes(),\n //minutes\n \"%S\": (d) => d.getUTCSeconds(),\n //seconds\n \"%L\": (d) => d.getUTCMilliseconds(),\n //milliseconds\n \"%u\": (d) => d.getUTCDay() || 7,\n //isoDayOfWeek\n \"%U\": import_internal2.weekOfYear,\n \"%V\": import_internal2.isoWeek,\n \"%j\": import_internal2.dayOfYear,\n \"%w\": (d) => d.getUTCDay()\n //dayOfWeek\n};\nconst $dateToString = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(args.onNull)) args.onNull = null;\n if ((0, import_util.isNil)(args.date)) return args.onNull;\n const date = (0, import_internal2.computeDate)(obj, args.date, options);\n let format = args.format ?? import_internal2.DATE_FORMAT;\n const minuteOffset = (0, import_internal2.parseTimezone)(args.timezone, date);\n const matches = format.match(import_internal2.DATE_FORMAT_SYM_RE);\n if (!matches) return format;\n (0, import_internal2.adjustDate)(date, minuteOffset);\n for (let i = 0, len = matches.length; i < len; i++) {\n const formatSpec = matches[i];\n (0, import_util.assert)(\n formatSpec in import_internal2.DATE_SYM_TABLE,\n `$dateToString: invalid format specifier ${formatSpec}`\n );\n const { name, padding } = import_internal2.DATE_SYM_TABLE[formatSpec];\n const fn = DATE_FUNCTIONS[formatSpec];\n let value = \"\";\n if (fn) {\n value = (0, import_internal2.padDigits)(fn(date), padding);\n } else {\n switch (name) {\n case \"timezone\":\n value = (0, import_internal2.formatTimezone)(minuteOffset);\n break;\n case \"minute_offset\":\n value = minuteOffset.toString();\n break;\n case \"abbr_month\":\n case \"full_month\": {\n const format2 = name.startsWith(\"abbr\") ? \"short\" : \"long\";\n value = date.toLocaleString(\"en-US\", { month: format2 });\n break;\n }\n }\n }\n format = format.replace(formatSpec, value);\n }\n return format;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateToString\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateTrunc_exports = {};\n__export(dateTrunc_exports, {\n $dateTrunc: () => $dateTrunc\n});\nmodule.exports = __toCommonJS(dateTrunc_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst REF_DATE_MILLIS = 9466848e5;\nconst distanceToBinLowerBound = (value, binSize) => {\n let remainder = value % binSize;\n if (remainder < 0) {\n remainder += binSize;\n }\n return remainder;\n};\nconst DATE_DIFF_FN = {\n day: import_internal2.dateDiffDay,\n month: import_internal2.dateDiffMonth,\n quarter: import_internal2.dateDiffQuarter,\n year: import_internal2.dateDiffYear\n};\nconst DAYS_OF_WEEK_RE = /(mon(day)?|tue(sday)?|wed(nesday)?|thu(rsday)?|fri(day)?|sat(urday)?|sun(day)?)/i;\nconst $dateTrunc = (obj, expr, options) => {\n const {\n date,\n unit,\n binSize: optBinSize,\n timezone,\n startOfWeek: optStartOfWeek\n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(date) || (0, import_util.isNil)(unit)) return null;\n const startOfWeek = (optStartOfWeek ?? \"sun\").toLowerCase().substring(0, 3);\n (0, import_util.assert)(\n (0, import_util.isDate)(date),\n \"$dateTrunc: 'date' must resolve to a valid Date object.\"\n );\n (0, import_util.assert)(import_internal2.TIME_UNITS.includes(unit), \"$dateTrunc: unit is invalid.\");\n (0, import_util.assert)(\n unit != \"week\" || DAYS_OF_WEEK_RE.test(startOfWeek),\n `$dateTrunc: startOfWeek '${startOfWeek}' is not a valid.`\n );\n (0, import_util.assert)(\n (0, import_util.isNil)(optBinSize) || optBinSize > 0,\n \"$dateTrunc requires 'binSize' to be greater than 0, but got value 0.\"\n );\n const binSize = optBinSize ?? 1;\n switch (unit) {\n case \"millisecond\":\n case \"second\":\n case \"minute\":\n case \"hour\": {\n const binSizeMillis = binSize * import_internal2.TIMEUNIT_IN_MILLIS[unit];\n const shiftedDate = date.getTime() - REF_DATE_MILLIS;\n return new Date(\n date.getTime() - distanceToBinLowerBound(shiftedDate, binSizeMillis)\n );\n }\n default: {\n (0, import_util.assert)(binSize <= 1e11, \"dateTrunc unsupported binSize value\");\n const d = new Date(date);\n const refPointDate = new Date(REF_DATE_MILLIS);\n let distanceFromRefPoint = 0;\n if (unit == \"week\") {\n const refPointDayOfWeek = (0, import_internal2.isoWeekday)(refPointDate, startOfWeek);\n const daysToAdjustBy = (import_internal2.DAYS_PER_WEEK - refPointDayOfWeek) % import_internal2.DAYS_PER_WEEK;\n refPointDate.setTime(\n refPointDate.getTime() + daysToAdjustBy * import_internal2.TIMEUNIT_IN_MILLIS.day\n );\n distanceFromRefPoint = (0, import_internal2.dateDiffWeek)(refPointDate, d, startOfWeek);\n } else {\n distanceFromRefPoint = DATE_DIFF_FN[unit](refPointDate, d);\n }\n const binLowerBoundFromRefPoint = distanceFromRefPoint - distanceToBinLowerBound(distanceFromRefPoint, binSize);\n const newDate = (0, import_internal2.dateAdd)(\n refPointDate,\n unit,\n binLowerBoundFromRefPoint,\n timezone\n );\n const minuteOffset = (0, import_internal2.parseTimezone)(timezone, newDate);\n (0, import_internal2.adjustDate)(newDate, -minuteOffset);\n return newDate;\n }\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateTrunc\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dayOfMonth_exports = {};\n__export(dayOfMonth_exports, {\n $dayOfMonth: () => $dayOfMonth\n});\nmodule.exports = __toCommonJS(dayOfMonth_exports);\nvar import_internal = require(\"./_internal\");\nconst $dayOfMonth = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDate();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dayOfMonth\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dayOfWeek_exports = {};\n__export(dayOfWeek_exports, {\n $dayOfWeek: () => $dayOfWeek\n});\nmodule.exports = __toCommonJS(dayOfWeek_exports);\nvar import_internal = require(\"./_internal\");\nconst $dayOfWeek = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDay() + 1;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dayOfWeek\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dayOfYear_exports = {};\n__export(dayOfYear_exports, {\n $dayOfYear: () => $dayOfYear\n});\nmodule.exports = __toCommonJS(dayOfYear_exports);\nvar import_internal = require(\"./_internal\");\nconst $dayOfYear = (obj, expr, options) => (0, import_internal.dayOfYear)((0, import_internal.computeDate)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dayOfYear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar hour_exports = {};\n__export(hour_exports, {\n $hour: () => $hour\n});\nmodule.exports = __toCommonJS(hour_exports);\nvar import_internal = require(\"./_internal\");\nconst $hour = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCHours();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $hour\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isoDayOfWeek_exports = {};\n__export(isoDayOfWeek_exports, {\n $isoDayOfWeek: () => $isoDayOfWeek\n});\nmodule.exports = __toCommonJS(isoDayOfWeek_exports);\nvar import_internal = require(\"./_internal\");\nconst $isoDayOfWeek = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDay() || 7;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isoDayOfWeek\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isoWeek_exports = {};\n__export(isoWeek_exports, {\n $isoWeek: () => $isoWeek\n});\nmodule.exports = __toCommonJS(isoWeek_exports);\nvar import_internal = require(\"./_internal\");\nconst $isoWeek = (obj, expr, options) => (0, import_internal.isoWeek)((0, import_internal.computeDate)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isoWeek\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isoWeekYear_exports = {};\n__export(isoWeekYear_exports, {\n $isoWeekYear: () => $isoWeekYear\n});\nmodule.exports = __toCommonJS(isoWeekYear_exports);\nvar import_internal = require(\"./_internal\");\nconst $isoWeekYear = (obj, expr, options) => (0, import_internal.isoWeekYear)((0, import_internal.computeDate)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isoWeekYear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar millisecond_exports = {};\n__export(millisecond_exports, {\n $millisecond: () => $millisecond\n});\nmodule.exports = __toCommonJS(millisecond_exports);\nvar import_internal = require(\"./_internal\");\nconst $millisecond = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMilliseconds();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $millisecond\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar minute_exports = {};\n__export(minute_exports, {\n $minute: () => $minute\n});\nmodule.exports = __toCommonJS(minute_exports);\nvar import_internal = require(\"./_internal\");\nconst $minute = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMinutes();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $minute\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar month_exports = {};\n__export(month_exports, {\n $month: () => $month\n});\nmodule.exports = __toCommonJS(month_exports);\nvar import_internal = require(\"./_internal\");\nconst $month = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMonth() + 1;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $month\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar second_exports = {};\n__export(second_exports, {\n $second: () => $second\n});\nmodule.exports = __toCommonJS(second_exports);\nvar import_internal = require(\"./_internal\");\nconst $second = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCSeconds();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $second\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar week_exports = {};\n__export(week_exports, {\n $week: () => $week\n});\nmodule.exports = __toCommonJS(week_exports);\nvar import_internal = require(\"./_internal\");\nconst $week = (obj, expr, options) => (0, import_internal.weekOfYear)((0, import_internal.computeDate)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $week\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar year_exports = {};\n__export(year_exports, {\n $year: () => $year\n});\nmodule.exports = __toCommonJS(year_exports);\nvar import_internal = require(\"./_internal\");\nconst $year = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCFullYear();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $year\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar date_exports = {};\nmodule.exports = __toCommonJS(date_exports);\n__reExport(date_exports, require(\"./dateAdd\"), module.exports);\n__reExport(date_exports, require(\"./dateDiff\"), module.exports);\n__reExport(date_exports, require(\"./dateFromParts\"), module.exports);\n__reExport(date_exports, require(\"./dateFromString\"), module.exports);\n__reExport(date_exports, require(\"./dateSubtract\"), module.exports);\n__reExport(date_exports, require(\"./dateToParts\"), module.exports);\n__reExport(date_exports, require(\"./dateToString\"), module.exports);\n__reExport(date_exports, require(\"./dateTrunc\"), module.exports);\n__reExport(date_exports, require(\"./dayOfMonth\"), module.exports);\n__reExport(date_exports, require(\"./dayOfWeek\"), module.exports);\n__reExport(date_exports, require(\"./dayOfYear\"), module.exports);\n__reExport(date_exports, require(\"./hour\"), module.exports);\n__reExport(date_exports, require(\"./isoDayOfWeek\"), module.exports);\n__reExport(date_exports, require(\"./isoWeek\"), module.exports);\n__reExport(date_exports, require(\"./isoWeekYear\"), module.exports);\n__reExport(date_exports, require(\"./millisecond\"), module.exports);\n__reExport(date_exports, require(\"./minute\"), module.exports);\n__reExport(date_exports, require(\"./month\"), module.exports);\n__reExport(date_exports, require(\"./second\"), module.exports);\n__reExport(date_exports, require(\"./week\"), module.exports);\n__reExport(date_exports, require(\"./year\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./dateAdd\"),\n ...require(\"./dateDiff\"),\n ...require(\"./dateFromParts\"),\n ...require(\"./dateFromString\"),\n ...require(\"./dateSubtract\"),\n ...require(\"./dateToParts\"),\n ...require(\"./dateToString\"),\n ...require(\"./dateTrunc\"),\n ...require(\"./dayOfMonth\"),\n ...require(\"./dayOfWeek\"),\n ...require(\"./dayOfYear\"),\n ...require(\"./hour\"),\n ...require(\"./isoDayOfWeek\"),\n ...require(\"./isoWeek\"),\n ...require(\"./isoWeekYear\"),\n ...require(\"./millisecond\"),\n ...require(\"./minute\"),\n ...require(\"./month\"),\n ...require(\"./second\"),\n ...require(\"./week\"),\n ...require(\"./year\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar literal_exports = {};\n__export(literal_exports, {\n $literal: () => $literal\n});\nmodule.exports = __toCommonJS(literal_exports);\nconst $literal = (_obj, expr, _options) => expr;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $literal\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar median_exports = {};\n__export(median_exports, {\n $median: () => $median\n});\nmodule.exports = __toCommonJS(median_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_median = require(\"../accumulator/median\");\nconst $median = (obj, expr, options) => {\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n return (0, import_median.$median)(input, { input: \"$$CURRENT\", method: expr.method }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $median\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar getField_exports = {};\n__export(getField_exports, {\n $getField: () => $getField\n});\nmodule.exports = __toCommonJS(getField_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $getField = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const { field, input } = (0, import_util.isString)(args) ? { field: args, input: obj } : { field: args.field, input: args.input ?? obj };\n return input[field];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $getField\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar rand_exports = {};\n__export(rand_exports, {\n $rand: () => $rand\n});\nmodule.exports = __toCommonJS(rand_exports);\nconst $rand = (_obj, _expr, _options) => Math.random();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $rand\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sampleRate_exports = {};\n__export(sampleRate_exports, {\n $sampleRate: () => $sampleRate\n});\nmodule.exports = __toCommonJS(sampleRate_exports);\nvar import_internal = require(\"../../../core/_internal\");\nconst $sampleRate = (obj, expr, options) => Math.random() <= (0, import_internal.evalExpr)(obj, expr, options);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sampleRate\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar misc_exports = {};\nmodule.exports = __toCommonJS(misc_exports);\n__reExport(misc_exports, require(\"./getField\"), module.exports);\n__reExport(misc_exports, require(\"./rand\"), module.exports);\n__reExport(misc_exports, require(\"./sampleRate\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./getField\"),\n ...require(\"./rand\"),\n ...require(\"./sampleRate\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mergeObjects_exports = {};\n__export(mergeObjects_exports, {\n $mergeObjects: () => $mergeObjects\n});\nmodule.exports = __toCommonJS(mergeObjects_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_mergeObjects = require(\"../../accumulator/mergeObjects\");\nvar import_internal2 = require(\"../_internal\");\nconst $mergeObjects = (obj, expr, options) => {\n const docs = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(docs)) return {};\n if (!(0, import_util.isArray)(docs))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$mergeObjects\", import_internal2.ARR_OPTS.obj);\n return (0, import_mergeObjects.$mergeObjects)(docs, expr, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mergeObjects\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar objectToArray_exports = {};\n__export(objectToArray_exports, {\n $objectToArray: () => $objectToArray\n});\nmodule.exports = __toCommonJS(objectToArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $objectToArray = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(val)) return null;\n if (!(0, import_util.isObject)(val))\n return (0, import_internal2.errExpectObject)(options.failOnError, \"$objectToArray\");\n const keys = Object.keys(val);\n const result = new Array(keys.length);\n let i = 0;\n for (const k of keys) {\n result[i++] = { k, v: val[k] };\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $objectToArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setField_exports = {};\n__export(setField_exports, {\n $setField: () => $setField\n});\nmodule.exports = __toCommonJS(setField_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$setField\";\nconst $setField = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"field\", \"value\"),\n \"$setField expects object { input, field, value }\"\n );\n const { input, field, value } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n const foe = options.failOnError;\n if (!(0, import_util.isObject)(input)) return (0, import_internal2.errExpectObject)(foe, `${OP} 'input'`);\n if (!(0, import_util.isString)(field)) return (0, import_internal2.errExpectString)(foe, `${OP} 'field'`);\n const newObj = { ...input };\n if (expr.value == \"$$REMOVE\") {\n delete newObj[field];\n } else {\n newObj[field] = value;\n }\n return newObj;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setField\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unsetField_exports = {};\n__export(unsetField_exports, {\n $unsetField: () => $unsetField\n});\nmodule.exports = __toCommonJS(unsetField_exports);\nvar import_setField = require(\"./setField\");\nconst $unsetField = (obj, expr, options) => {\n return (0, import_setField.$setField)(obj, { ...expr, value: \"$$REMOVE\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unsetField\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar object_exports = {};\nmodule.exports = __toCommonJS(object_exports);\n__reExport(object_exports, require(\"./mergeObjects\"), module.exports);\n__reExport(object_exports, require(\"./objectToArray\"), module.exports);\n__reExport(object_exports, require(\"./setField\"), module.exports);\n__reExport(object_exports, require(\"./unsetField\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./mergeObjects\"),\n ...require(\"./objectToArray\"),\n ...require(\"./setField\"),\n ...require(\"./unsetField\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar percentile_exports = {};\n__export(percentile_exports, {\n $percentile: () => $percentile\n});\nmodule.exports = __toCommonJS(percentile_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_percentile = require(\"../accumulator/percentile\");\nconst $percentile = (obj, expr, options) => {\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n return (0, import_percentile.$percentile)(\n input,\n { ...expr, input: \"$$CURRENT\" },\n options\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $percentile\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar allElementsTrue_exports = {};\n__export(allElementsTrue_exports, {\n $allElementsTrue: () => $allElementsTrue\n});\nmodule.exports = __toCommonJS(allElementsTrue_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $allElementsTrue = (obj, expr, options) => {\n if ((0, import_internal2.isArray)(expr)) {\n if (expr.length === 0) return true;\n (0, import_internal2.assert)(expr.length === 1, \"$allElementsTrue expects array(1)\");\n expr = expr[0];\n }\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_internal2.isArray)(args)) return (0, import_internal3.errExpectArray)(foe, `$allElementsTrue argument`);\n for (const v of args) if (!(0, import_internal2.truthy)(v, options.useStrictMode)) return false;\n return true;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $allElementsTrue\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar anyElementTrue_exports = {};\n__export(anyElementTrue_exports, {\n $anyElementTrue: () => $anyElementTrue\n});\nmodule.exports = __toCommonJS(anyElementTrue_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $anyElementTrue = (obj, expr, options) => {\n if ((0, import_internal2.isArray)(expr)) {\n if (expr.length === 0) return false;\n (0, import_internal2.assert)(expr.length === 1, \"$anyElementTrue expects array(1)\");\n expr = expr[0];\n }\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_internal2.isArray)(args)) return (0, import_internal3.errExpectArray)(foe, `$anyElementTrue argument`);\n for (const v of args) if ((0, import_internal2.truthy)(v, options.useStrictMode)) return true;\n return false;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $anyElementTrue\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setDifference_exports = {};\n__export(setDifference_exports, {\n $setDifference: () => $setDifference\n});\nmodule.exports = __toCommonJS(setDifference_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$setDifference\";\nconst $setDifference = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length == 2, `${OP} expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let ok = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n ok &&= (0, import_util.isArray)(v);\n }\n if (!ok) return (0, import_internal2.errExpectArray)(foe, `${OP} arguments`);\n const m = import_util.HashMap.init();\n for (const v of args[0]) m.set(v, true);\n for (const v of args[1]) m.delete(v);\n return Array.from(m.keys());\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setDifference\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setEquals_exports = {};\n__export(setEquals_exports, {\n $setEquals: () => $setEquals\n});\nmodule.exports = __toCommonJS(setEquals_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $setEquals = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$setEquals expects array\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if (!args.every(import_util.isArray)) return (0, import_internal2.errExpectArray)(foe, \"$setEquals arguments\");\n const map = import_util.HashMap.init();\n const first = args[0];\n for (let i = 0; i < first.length; i++) map.set(first[i], i);\n for (let i = 1; i < args.length; i++) {\n const arr = args[i];\n const set = /* @__PURE__ */ new Set();\n for (let j = 0; j < arr.length; j++) {\n const n = map.get(arr[j]) ?? -1;\n if (n === -1) return false;\n set.add(n);\n }\n if (set.size !== map.size) return false;\n }\n return true;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setEquals\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setIntersection_exports = {};\n__export(setIntersection_exports, {\n $setIntersection: () => $setIntersection\n});\nmodule.exports = __toCommonJS(setIntersection_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$setIntersection\";\nconst $setIntersection = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), `${OP} expects array`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let ok = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n ok &&= (0, import_util.isArray)(v);\n }\n if (!ok) return (0, import_internal2.errExpectArray)(foe, `${OP} arguments`);\n return (0, import_util.intersection)(args);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setIntersection\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setIsSubset_exports = {};\n__export(setIsSubset_exports, {\n $setIsSubset: () => $setIsSubset\n});\nmodule.exports = __toCommonJS(setIsSubset_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$setIsSubset\";\nconst $setIsSubset = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, `${OP} expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (!args.every(import_util.isArray))\n return (0, import_internal2.errExpectArray)(options.failOnError, `${OP} arguments`);\n const [first, second] = args;\n const map = import_util.HashMap.init();\n for (const v of second) map.set(v, 0);\n for (const v of first) if (!map.has(v)) return false;\n return true;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setIsSubset\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setUnion_exports = {};\n__export(setUnion_exports, {\n $setUnion: () => $setUnion\n});\nmodule.exports = __toCommonJS(setUnion_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $setUnion = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if ((0, import_util.isNil)(args)) return null;\n if (!(0, import_util.isArray)(args)) return (0, import_internal2.errExpectArray)(foe, \"$setUnion\");\n if ((0, import_util.isArray)(expr)) {\n if (!args.every(import_util.isArray)) return (0, import_internal2.errExpectArray)(foe, \"$setUnion arguments\");\n return (0, import_util.unique)((0, import_util.flatten)(args));\n }\n return (0, import_util.unique)(args);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setUnion\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar set_exports = {};\nmodule.exports = __toCommonJS(set_exports);\n__reExport(set_exports, require(\"./allElementsTrue\"), module.exports);\n__reExport(set_exports, require(\"./anyElementTrue\"), module.exports);\n__reExport(set_exports, require(\"./setDifference\"), module.exports);\n__reExport(set_exports, require(\"./setEquals\"), module.exports);\n__reExport(set_exports, require(\"./setIntersection\"), module.exports);\n__reExport(set_exports, require(\"./setIsSubset\"), module.exports);\n__reExport(set_exports, require(\"./setUnion\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./allElementsTrue\"),\n ...require(\"./anyElementTrue\"),\n ...require(\"./setDifference\"),\n ...require(\"./setEquals\"),\n ...require(\"./setIntersection\"),\n ...require(\"./setIsSubset\"),\n ...require(\"./setUnion\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar concat_exports = {};\n__export(concat_exports, {\n $concat: () => $concat\n});\nmodule.exports = __toCommonJS(concat_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $concat = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$concat expects array\");\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n let ok = true;\n for (const s of args) {\n if ((0, import_util.isNil)(s)) return null;\n ok &&= (0, import_util.isString)(s);\n }\n if (!ok) return (0, import_internal2.errExpectArray)(foe, \"$concat\", { type: \"string\" });\n return args.join(\"\");\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $concat\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar indexOfBytes_exports = {};\n__export(indexOfBytes_exports, {\n $indexOfBytes: () => $indexOfBytes\n});\nmodule.exports = __toCommonJS(indexOfBytes_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst OP = \"$indexOfBytes\";\nconst $indexOfBytes = (obj, expr, options) => {\n (0, import_internal2.assert)(\n (0, import_internal2.isArray)(expr) && expr.length > 1 && expr.length < 5,\n `${OP} expects array(4)`\n );\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n const str = args[0];\n if ((0, import_internal2.isNil)(str)) return null;\n if (!(0, import_internal2.isString)(str)) return (0, import_internal3.errExpectString)(foe, `${OP} arg1 `);\n const search = args[1];\n if (!(0, import_internal2.isString)(search)) return (0, import_internal3.errExpectString)(foe, `${OP} arg2 `);\n const start = args[2] ?? 0;\n const end = args[3] ?? str.length;\n if (!(0, import_internal2.isInteger)(start) || start < 0)\n return (0, import_internal3.errExpectNumber)(foe, `${OP} arg3 `, import_internal3.INT_OPTS.index);\n if (!(0, import_internal2.isInteger)(end) || end < 0)\n return (0, import_internal3.errExpectNumber)(foe, `${OP} arg4 `, import_internal3.INT_OPTS.index);\n if (start > end) return -1;\n const index = str.substring(start, end).indexOf(search);\n return index > -1 ? index + start : index;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $indexOfBytes\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n regexSearch: () => regexSearch,\n trimString: () => trimString\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst WHITESPACE_CHARS = [\n 0,\n // '\\0' Null character\n 32,\n // ' ', Space\n 9,\n // '\\t' Horizontal tab\n 10,\n // '\\n' Line feed/new line\n 11,\n // '\\v' Vertical tab\n 12,\n // '\\f' Form feed\n 13,\n // '\\r' Carriage return\n 160,\n // Non-breaking space\n 5760,\n // Ogham space mark\n 8192,\n // En quad\n 8193,\n // Em quad\n 8194,\n // En space\n 8195,\n // Em space\n 8196,\n // Three-per-em space\n 8197,\n // Four-per-em space\n 8198,\n // Six-per-em space\n 8199,\n // Figure space\n 8200,\n // Punctuation space\n 8201,\n // Thin space\n 8202\n // Hair space\n];\nfunction trimString(obj, expr, options, trimOpts) {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n const s = val.input;\n if ((0, import_util.isNil)(s)) return null;\n const codepoints = (0, import_util.isNil)(val.chars) ? WHITESPACE_CHARS : val.chars.split(\"\").map((c) => c.codePointAt(0));\n let i = 0;\n let j = s.length - 1;\n while (trimOpts.left && i <= j && codepoints.indexOf(s[i].codePointAt(0)) !== -1)\n i++;\n while (trimOpts.right && i <= j && codepoints.indexOf(s[j].codePointAt(0)) !== -1)\n j--;\n return s.substring(i, j + 1);\n}\nfunction regexSearch(obj, expr, options, reOpts) {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_util.isString)(val.input)) return [];\n const regexOptions = val.options;\n if (regexOptions) {\n (0, import_util.assert)(\n regexOptions.indexOf(\"x\") === -1,\n \"extended capability option 'x' not supported\"\n );\n (0, import_util.assert)(regexOptions.indexOf(\"g\") === -1, \"global option 'g' not supported\");\n }\n let input = val.input;\n const re = new RegExp(val.regex, regexOptions);\n let m;\n const matches = new Array();\n let offset = 0;\n while (m = re.exec(input)) {\n const result = {\n match: m[0],\n idx: m.index + offset,\n captures: []\n };\n for (let i = 1; i < m.length; i++) result.captures.push(m[i] || null);\n matches.push(result);\n if (!reOpts.global) break;\n offset = m.index + m[0].length;\n input = input.substring(offset);\n }\n return matches;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n regexSearch,\n trimString\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ltrim_exports = {};\n__export(ltrim_exports, {\n $ltrim: () => $ltrim\n});\nmodule.exports = __toCommonJS(ltrim_exports);\nvar import_internal = require(\"./_internal\");\nconst $ltrim = (obj, expr, options) => {\n return (0, import_internal.trimString)(obj, expr, options, { left: true, right: false });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ltrim\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar regexFind_exports = {};\n__export(regexFind_exports, {\n $regexFind: () => $regexFind\n});\nmodule.exports = __toCommonJS(regexFind_exports);\nvar import_util = require(\"../../../util\");\nvar import_internal = require(\"./_internal\");\nconst $regexFind = (obj, expr, options) => {\n const result = (0, import_internal.regexSearch)(obj, expr, options, { global: false });\n return (0, import_util.isArray)(result) && result.length > 0 ? result[0] : null;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $regexFind\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar regexFindAll_exports = {};\n__export(regexFindAll_exports, {\n $regexFindAll: () => $regexFindAll\n});\nmodule.exports = __toCommonJS(regexFindAll_exports);\nvar import_internal = require(\"./_internal\");\nconst $regexFindAll = (obj, expr, options) => {\n return (0, import_internal.regexSearch)(obj, expr, options, { global: true });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $regexFindAll\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar regexMatch_exports = {};\n__export(regexMatch_exports, {\n $regexMatch: () => $regexMatch\n});\nmodule.exports = __toCommonJS(regexMatch_exports);\nvar import_internal = require(\"./_internal\");\nconst $regexMatch = (obj, expr, options) => {\n return (0, import_internal.regexSearch)(obj, expr, options, { global: false })?.length != 0;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $regexMatch\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar replaceAll_exports = {};\n__export(replaceAll_exports, {\n $replaceAll: () => $replaceAll\n});\nmodule.exports = __toCommonJS(replaceAll_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$replaceAll\";\nconst $replaceAll = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isObject)(expr), `${OP} expects an object argument`);\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const { input, find, replacement } = args;\n if ((0, import_util.isNil)(input) || (0, import_util.isNil)(find) || (0, import_util.isNil)(replacement)) return null;\n if (!(0, import_util.isString)(input)) return (0, import_internal2.errExpectString)(foe, `${OP} 'input'`);\n if (!(0, import_util.isString)(find)) return (0, import_internal2.errExpectString)(foe, `${OP} 'find'`);\n if (!(0, import_util.isString)(replacement))\n return (0, import_internal2.errExpectString)(foe, `${OP} 'replacement'`);\n return input.replace(new RegExp(find, \"g\"), replacement);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $replaceAll\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar replaceOne_exports = {};\n__export(replaceOne_exports, {\n $replaceOne: () => $replaceOne\n});\nmodule.exports = __toCommonJS(replaceOne_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$replaceOne\";\nconst $replaceOne = (obj, expr, options) => {\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const { input, find, replacement } = args;\n if ((0, import_util.isNil)(input) || (0, import_util.isNil)(find) || (0, import_util.isNil)(replacement)) return null;\n if (!(0, import_util.isString)(input)) return (0, import_internal2.errExpectString)(foe, `${OP} 'input'`);\n if (!(0, import_util.isString)(find)) return (0, import_internal2.errExpectString)(foe, `${OP} 'find'`);\n if (!(0, import_util.isString)(replacement))\n return (0, import_internal2.errExpectString)(foe, `${OP} 'replacement'`);\n return args.input.replace(args.find, args.replacement);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $replaceOne\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar rtrim_exports = {};\n__export(rtrim_exports, {\n $rtrim: () => $rtrim\n});\nmodule.exports = __toCommonJS(rtrim_exports);\nvar import_internal = require(\"./_internal\");\nconst $rtrim = (obj, expr, options) => {\n return (0, import_internal.trimString)(obj, expr, options, { left: false, right: true });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $rtrim\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar split_exports = {};\n__export(split_exports, {\n $split: () => $split\n});\nmodule.exports = __toCommonJS(split_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $split = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, `$split expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if ((0, import_util.isNil)(args[0])) return null;\n if (!args.every(import_util.isString))\n return (0, import_internal2.errExpectArray)(foe, `$split `, { size: 2, type: \"string\" });\n return args[0].split(args[1]);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $split\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar strcasecmp_exports = {};\n__export(strcasecmp_exports, {\n $strcasecmp: () => $strcasecmp\n});\nmodule.exports = __toCommonJS(strcasecmp_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $strcasecmp = (obj, expr, options) => {\n (0, import_internal2.assert)((0, import_util.isArray)(expr) && expr.length === 2, `$strcasecmp expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let t_nil = true;\n let t_str = true;\n for (const v of args) {\n t_nil &&= (0, import_util.isNil)(v);\n t_str &&= (0, import_util.isString)(v);\n }\n if (t_nil) return 0;\n if (!t_str)\n return (0, import_internal3.errExpectArray)(foe, `$strcasecmp arguments`, { type: \"string\" });\n return (0, import_internal2.simpleCmp)(args[0].toLowerCase(), args[1].toLowerCase());\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $strcasecmp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar strLenBytes_exports = {};\n__export(strLenBytes_exports, {\n $strLenBytes: () => $strLenBytes\n});\nmodule.exports = __toCommonJS(strLenBytes_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $strLenBytes = (obj, expr, options) => {\n const s = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_util.isString)(s)) return (0, import_internal2.errExpectString)(options.failOnError, \"$strLenBytes\");\n return ~-encodeURI(s).split(/%..|./).length;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $strLenBytes\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar strLenCP_exports = {};\n__export(strLenCP_exports, {\n $strLenCP: () => $strLenCP\n});\nmodule.exports = __toCommonJS(strLenCP_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $strLenCP = (obj, expr, options) => {\n const s = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_util.isString)(s)) return (0, import_internal2.errExpectString)(options.failOnError, \"$strLenCP\");\n return s.length;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $strLenCP\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar substrBytes_exports = {};\n__export(substrBytes_exports, {\n $substrBytes: () => $substrBytes\n});\nmodule.exports = __toCommonJS(substrBytes_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$substrBytes\";\nconst $substrBytes = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 3, `${OP} expects array(3)`);\n const [s, index, count] = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n const nil = (0, import_util.isNil)(s);\n if (!nil && !(0, import_util.isString)(s)) return (0, import_internal2.errExpectString)(foe, `${OP} arg1 `);\n if (!(0, import_util.isInteger)(index) || index < 0)\n return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `, import_internal2.INT_OPTS.index);\n if (!(0, import_util.isInteger)(count) || count < 0)\n return (0, import_internal2.errExpectNumber)(foe, `${OP} arg3 `, import_internal2.INT_OPTS.index);\n if (nil) return \"\";\n let utf8Pos = 0;\n let start16 = null;\n let end16 = null;\n const err = `${OP} UTF-8 boundary falls inside a continuation byte`;\n for (let i = 0; i < s.length; ) {\n const cp = s.codePointAt(i);\n if (cp === void 0)\n return (0, import_internal2.errInvalidArgs)(foe, `${OP} byte index out of range`);\n const utf8Len = cp < 128 ? 1 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;\n const utf16Len = cp > 65535 ? 2 : 1;\n if (start16 === null) {\n if (index > utf8Pos && index < utf8Pos + utf8Len)\n return (0, import_internal2.errInvalidArgs)(foe, err);\n if (utf8Pos === index) {\n start16 = i;\n }\n }\n const endByte = index + count;\n if (start16 !== null && end16 === null) {\n if (endByte > utf8Pos && endByte < utf8Pos + utf8Len)\n return (0, import_internal2.errInvalidArgs)(foe, err);\n if (utf8Pos === endByte) {\n end16 = i;\n break;\n }\n }\n utf8Pos += utf8Len;\n i += utf16Len;\n }\n if (start16 === null) {\n if (index === utf8Pos) return \"\";\n return (0, import_internal2.errInvalidArgs)(foe, `${OP} byte index out of range`);\n }\n if (end16 === null) {\n const endByte = index + count;\n if (endByte !== utf8Pos)\n return (0, import_internal2.errInvalidArgs)(foe, `${OP} count extends beyond UTF-8 length`);\n end16 = s.length;\n }\n return s.slice(start16, end16);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $substrBytes\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar substr_exports = {};\n__export(substr_exports, {\n $substr: () => $substr\n});\nmodule.exports = __toCommonJS(substr_exports);\nvar import_substrBytes = require(\"./substrBytes\");\nconst $substr = import_substrBytes.$substrBytes;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $substr\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar substrCP_exports = {};\n__export(substrCP_exports, {\n $substrCP: () => $substrCP\n});\nmodule.exports = __toCommonJS(substrCP_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$substrCP\";\nconst $substrCP = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 3, `${OP} expects array(3)`);\n const [s, index, count] = (0, import_internal.evalExpr)(obj, expr, options);\n const nil = (0, import_util.isNil)(s);\n const foe = options.failOnError;\n if (!nil && !(0, import_util.isString)(s)) return (0, import_internal2.errExpectString)(foe, `${OP} arg1 `);\n if (!(0, import_util.isInteger)(index)) return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `);\n if (!(0, import_util.isInteger)(count)) return (0, import_internal2.errExpectNumber)(foe, `${OP} arg3 `);\n if (nil) return \"\";\n if (index < 0) return \"\";\n if (count < 0) return s.substring(index);\n return s.substring(index, index + count);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $substrCP\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toBool_exports = {};\n__export(toBool_exports, {\n $toBool: () => $toBool\n});\nmodule.exports = __toCommonJS(toBool_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $toBool = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(val)) return null;\n if ((0, import_util.isString)(val)) return true;\n return Boolean(val);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toBool\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toDate_exports = {};\n__export(toDate_exports, {\n $toDate: () => $toDate\n});\nmodule.exports = __toCommonJS(toDate_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $toDate = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isDate)(val)) return val;\n if ((0, import_util.isNil)(val)) return null;\n const d = new Date(val);\n (0, import_util.assert)(!isNaN(d.getTime()), `cannot convert '${val}' to date`);\n return d;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toDate\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toDouble_exports = {};\n__export(toDouble_exports, {\n $toDouble: () => $toDouble\n});\nmodule.exports = __toCommonJS(toDouble_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $toDouble = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(val)) return null;\n if ((0, import_util.isDate)(val)) return val.getTime();\n if (val === true) return 1;\n if (val === false) return 0;\n const n = Number(val);\n (0, import_util.assert)((0, import_util.isNumber)(n), `cannot convert '${val}' to double/decimal`);\n return n;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toDouble\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n MAX_INT: () => MAX_INT,\n MAX_LONG: () => MAX_LONG,\n MIN_INT: () => MIN_INT,\n MIN_LONG: () => MIN_LONG,\n toInteger: () => toInteger\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst MAX_INT = 2147483647;\nconst MIN_INT = -2147483648;\nconst MAX_LONG = 9007199254740991;\nconst MIN_LONG = -9007199254740991;\nfunction toInteger(obj, expr, options, min, max) {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if (val === true) return 1;\n if (val === false) return 0;\n if ((0, import_util.isNil)(val)) return null;\n if ((0, import_util.isDate)(val)) return val.getTime();\n const n = Number(val);\n (0, import_util.assert)(\n (0, import_util.isNumber)(n) && n >= min && n <= max && (!(0, import_util.isString)(val) || n.toString().indexOf(\".\") === -1),\n `cannot convert '${val}' to ${max == MAX_INT ? \"int\" : \"long\"}`\n );\n return Math.trunc(n);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n MAX_INT,\n MAX_LONG,\n MIN_INT,\n MIN_LONG,\n toInteger\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toInt_exports = {};\n__export(toInt_exports, {\n $toInt: () => $toInt\n});\nmodule.exports = __toCommonJS(toInt_exports);\nvar import_internal = require(\"./_internal\");\nconst $toInt = (obj, expr, options) => (0, import_internal.toInteger)(obj, expr, options, import_internal.MIN_INT, import_internal.MAX_INT);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toInt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toLong_exports = {};\n__export(toLong_exports, {\n $toLong: () => $toLong\n});\nmodule.exports = __toCommonJS(toLong_exports);\nvar import_internal = require(\"./_internal\");\nconst $toLong = (obj, expr, options) => (0, import_internal.toInteger)(obj, expr, options, import_internal.MIN_LONG, import_internal.MAX_LONG);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toLong\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toString_exports = {};\n__export(toString_exports, {\n $toString: () => $toString\n});\nmodule.exports = __toCommonJS(toString_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $toString = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_internal2.isNil)(val)) return null;\n if ((0, import_internal2.isDate)(val)) return val.toISOString();\n if ((0, import_internal2.isPrimitive)(val) || (0, import_internal2.isRegExp)(val)) return String(val);\n return (0, import_internal3.errInvalidArgs)(\n options.failOnError,\n \"$toString cannot convert from object to string\"\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toString\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar convert_exports = {};\n__export(convert_exports, {\n $convert: () => $convert\n});\nmodule.exports = __toCommonJS(convert_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nvar import_toBool = require(\"./toBool\");\nvar import_toDate = require(\"./toDate\");\nvar import_toDouble = require(\"./toDouble\");\nvar import_toInt = require(\"./toInt\");\nvar import_toLong = require(\"./toLong\");\nvar import_toString = require(\"./toString\");\nconst $convert = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"to\"),\n \"$convert expects object { input, to, onError, onNull }\"\n );\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n if ((0, import_util.isNil)(input)) return (0, import_internal.evalExpr)(obj, expr.onNull, options) ?? null;\n const toExpr = (0, import_internal.evalExpr)(obj, expr.to, options);\n try {\n switch (toExpr) {\n case 2:\n case \"string\":\n return (0, import_toString.$toString)(obj, input, options);\n case 8:\n case \"boolean\":\n case \"bool\":\n return (0, import_toBool.$toBool)(obj, input, options);\n case 9:\n case \"date\":\n return (0, import_toDate.$toDate)(obj, input, options);\n case 1:\n case 19:\n case \"double\":\n case \"decimal\":\n case \"number\":\n return (0, import_toDouble.$toDouble)(obj, input, options);\n case 16:\n case \"int\":\n return (0, import_toInt.$toInt)(obj, input, options);\n case 18:\n case \"long\":\n return (0, import_toLong.$toLong)(obj, input, options);\n }\n } catch {\n }\n if (expr.onError === void 0)\n return (0, import_internal2.errInvalidArgs)(\n options.failOnError,\n `$convert cannot convert from object to ${expr.to} with no onError value`\n );\n return (0, import_internal.evalExpr)(obj, expr.onError, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $convert\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isNumber_exports = {};\n__export(isNumber_exports, {\n $isNumber: () => $isNumber\n});\nmodule.exports = __toCommonJS(isNumber_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $isNumber = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_util.isNumber)(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isNumber\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toDecimal_exports = {};\n__export(toDecimal_exports, {\n $toDecimal: () => $toDecimal\n});\nmodule.exports = __toCommonJS(toDecimal_exports);\nvar import_toDouble = require(\"./toDouble\");\nconst $toDecimal = import_toDouble.$toDouble;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toDecimal\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar type_exports = {};\n__export(type_exports, {\n $type: () => $type\n});\nmodule.exports = __toCommonJS(type_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst $type = (obj, expr, options) => {\n const v = (0, import_internal.evalExpr)(obj, expr, options);\n if (options.useStrictMode) {\n if (v === void 0) return \"missing\";\n if (v === true || v === false) return \"bool\";\n if ((0, import_util.isNumber)(v)) {\n if (v % 1 != 0) return \"double\";\n return v >= import_internal2.MIN_INT && v <= import_internal2.MAX_INT ? \"int\" : \"long\";\n }\n if ((0, import_util.isRegExp)(v)) return \"regex\";\n }\n return (0, import_util.typeOf)(v);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $type\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar type_exports = {};\nmodule.exports = __toCommonJS(type_exports);\n__reExport(type_exports, require(\"./convert\"), module.exports);\n__reExport(type_exports, require(\"./isNumber\"), module.exports);\n__reExport(type_exports, require(\"./toBool\"), module.exports);\n__reExport(type_exports, require(\"./toDate\"), module.exports);\n__reExport(type_exports, require(\"./toDecimal\"), module.exports);\n__reExport(type_exports, require(\"./toDouble\"), module.exports);\n__reExport(type_exports, require(\"./toInt\"), module.exports);\n__reExport(type_exports, require(\"./toLong\"), module.exports);\n__reExport(type_exports, require(\"./toString\"), module.exports);\n__reExport(type_exports, require(\"./type\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./convert\"),\n ...require(\"./isNumber\"),\n ...require(\"./toBool\"),\n ...require(\"./toDate\"),\n ...require(\"./toDecimal\"),\n ...require(\"./toDouble\"),\n ...require(\"./toInt\"),\n ...require(\"./toLong\"),\n ...require(\"./toString\"),\n ...require(\"./type\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toLower_exports = {};\n__export(toLower_exports, {\n $toLower: () => $toLower\n});\nmodule.exports = __toCommonJS(toLower_exports);\nvar import_internal = require(\"../../../util/_internal\");\nvar import_type = require(\"../type\");\nconst $toLower = (obj, expr, options) => {\n if ((0, import_internal.isArray)(expr) && expr.length === 1) expr = expr[0];\n const s = (0, import_type.$toString)(obj, expr, options);\n return s === null ? s : s.toLowerCase();\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toLower\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toUpper_exports = {};\n__export(toUpper_exports, {\n $toUpper: () => $toUpper\n});\nmodule.exports = __toCommonJS(toUpper_exports);\nvar import_util = require(\"../../../util\");\nvar import_type = require(\"../type\");\nconst $toUpper = (obj, expr, options) => {\n if ((0, import_util.isArray)(expr) && expr.length === 1) expr = expr[0];\n const s = (0, import_type.$toString)(obj, expr, options);\n return s === null ? s : s.toUpperCase();\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toUpper\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar trim_exports = {};\n__export(trim_exports, {\n $trim: () => $trim\n});\nmodule.exports = __toCommonJS(trim_exports);\nvar import_internal = require(\"./_internal\");\nconst $trim = (obj, expr, options) => {\n return (0, import_internal.trimString)(obj, expr, options, { left: true, right: true });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $trim\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar string_exports = {};\nmodule.exports = __toCommonJS(string_exports);\n__reExport(string_exports, require(\"./concat\"), module.exports);\n__reExport(string_exports, require(\"./indexOfBytes\"), module.exports);\n__reExport(string_exports, require(\"./ltrim\"), module.exports);\n__reExport(string_exports, require(\"./regexFind\"), module.exports);\n__reExport(string_exports, require(\"./regexFindAll\"), module.exports);\n__reExport(string_exports, require(\"./regexMatch\"), module.exports);\n__reExport(string_exports, require(\"./replaceAll\"), module.exports);\n__reExport(string_exports, require(\"./replaceOne\"), module.exports);\n__reExport(string_exports, require(\"./rtrim\"), module.exports);\n__reExport(string_exports, require(\"./split\"), module.exports);\n__reExport(string_exports, require(\"./strcasecmp\"), module.exports);\n__reExport(string_exports, require(\"./strLenBytes\"), module.exports);\n__reExport(string_exports, require(\"./strLenCP\"), module.exports);\n__reExport(string_exports, require(\"./substr\"), module.exports);\n__reExport(string_exports, require(\"./substrBytes\"), module.exports);\n__reExport(string_exports, require(\"./substrCP\"), module.exports);\n__reExport(string_exports, require(\"./toLower\"), module.exports);\n__reExport(string_exports, require(\"./toUpper\"), module.exports);\n__reExport(string_exports, require(\"./trim\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./concat\"),\n ...require(\"./indexOfBytes\"),\n ...require(\"./ltrim\"),\n ...require(\"./regexFind\"),\n ...require(\"./regexFindAll\"),\n ...require(\"./regexMatch\"),\n ...require(\"./replaceAll\"),\n ...require(\"./replaceOne\"),\n ...require(\"./rtrim\"),\n ...require(\"./split\"),\n ...require(\"./strcasecmp\"),\n ...require(\"./strLenBytes\"),\n ...require(\"./strLenCP\"),\n ...require(\"./substr\"),\n ...require(\"./substrBytes\"),\n ...require(\"./substrCP\"),\n ...require(\"./toLower\"),\n ...require(\"./toUpper\"),\n ...require(\"./trim\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toHashedIndexKey_exports = {};\n__export(toHashedIndexKey_exports, {\n $toHashedIndexKey: () => $toHashedIndexKey\n});\nmodule.exports = __toCommonJS(toHashedIndexKey_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nconst $toHashedIndexKey = (obj, expr, options) => (0, import_util.hashCode)((0, import_internal.evalExpr)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toHashedIndexKey\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n processOperator: () => processOperator\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nfunction processOperator(obj, expr, options, fn, fixedPoints) {\n const fp = {\n undefined: null,\n null: null,\n NaN: NaN,\n Infinity: new Error(),\n \"-Infinity\": new Error(),\n ...fixedPoints\n };\n const foe = options.failOnError;\n const op = fn.name;\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if (n in fp) {\n const res = fp[n];\n if (res instanceof Error)\n return (0, import_internal2.errExpectNumber)(foe, `$${op} invalid input '${n}'`);\n return res;\n }\n if (!(0, import_util.isNumber)(n)) return (0, import_internal2.errExpectNumber)(foe, `$${op}`);\n return fn(n);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n processOperator\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar acos_exports = {};\n__export(acos_exports, {\n $acos: () => $acos\n});\nmodule.exports = __toCommonJS(acos_exports);\nvar import_internal = require(\"./_internal\");\nconst $acos = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.acos, {\n Infinity: Infinity,\n 0: new Error()\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $acos\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar acosh_exports = {};\n__export(acosh_exports, {\n $acosh: () => $acosh\n});\nmodule.exports = __toCommonJS(acosh_exports);\nvar import_internal = require(\"./_internal\");\nconst $acosh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.acosh, {\n Infinity: Infinity,\n 0: new Error()\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $acosh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar asin_exports = {};\n__export(asin_exports, {\n $asin: () => $asin\n});\nmodule.exports = __toCommonJS(asin_exports);\nvar import_internal = require(\"./_internal\");\nconst $asin = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.asin);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $asin\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar asinh_exports = {};\n__export(asinh_exports, {\n $asinh: () => $asinh\n});\nmodule.exports = __toCommonJS(asinh_exports);\nvar import_internal = require(\"./_internal\");\nconst $asinh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.asinh, {\n Infinity: Infinity,\n \"-Infinity\": -Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $asinh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar atan_exports = {};\n__export(atan_exports, {\n $atan: () => $atan\n});\nmodule.exports = __toCommonJS(atan_exports);\nvar import_internal = require(\"./_internal\");\nconst $atan = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.atan);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $atan\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar atan2_exports = {};\n__export(atan2_exports, {\n $atan2: () => $atan2\n});\nmodule.exports = __toCommonJS(atan2_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $atan2 = (obj, expr, options) => {\n const [y, x] = (0, import_internal.evalExpr)(obj, expr, options);\n if (isNaN(y) || (0, import_util.isNil)(y)) return y;\n if (isNaN(x) || (0, import_util.isNil)(x)) return x;\n return Math.atan2(y, x);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $atan2\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar atanh_exports = {};\n__export(atanh_exports, {\n $atanh: () => $atanh\n});\nmodule.exports = __toCommonJS(atanh_exports);\nvar import_internal = require(\"./_internal\");\nconst $atanh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.atanh, {\n 1: Infinity,\n \"-1\": -Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $atanh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cos_exports = {};\n__export(cos_exports, {\n $cos: () => $cos\n});\nmodule.exports = __toCommonJS(cos_exports);\nvar import_internal = require(\"./_internal\");\nconst $cos = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.cos);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $cos\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cosh_exports = {};\n__export(cosh_exports, {\n $cosh: () => $cosh\n});\nmodule.exports = __toCommonJS(cosh_exports);\nvar import_internal = require(\"./_internal\");\nconst $cosh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.cosh, {\n \"-Infinity\": Infinity,\n Infinity: Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $cosh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar degreesToRadians_exports = {};\n__export(degreesToRadians_exports, {\n $degreesToRadians: () => $degreesToRadians\n});\nmodule.exports = __toCommonJS(degreesToRadians_exports);\nvar import_internal = require(\"./_internal\");\nconst degreesToRadians = (n) => n * (Math.PI / 180);\nconst $degreesToRadians = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, degreesToRadians, {\n Infinity: Infinity,\n \"-Infinity\": Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $degreesToRadians\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar radiansToDegrees_exports = {};\n__export(radiansToDegrees_exports, {\n $radiansToDegrees: () => $radiansToDegrees\n});\nmodule.exports = __toCommonJS(radiansToDegrees_exports);\nvar import_internal = require(\"./_internal\");\nconst radiansToDegrees = (n) => n * (180 / Math.PI);\nconst $radiansToDegrees = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, radiansToDegrees, {\n Infinity: Infinity,\n \"-Infinity\": Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $radiansToDegrees\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sin_exports = {};\n__export(sin_exports, {\n $sin: () => $sin\n});\nmodule.exports = __toCommonJS(sin_exports);\nvar import_internal = require(\"./_internal\");\nconst $sin = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.sin);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sin\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sinh_exports = {};\n__export(sinh_exports, {\n $sinh: () => $sinh\n});\nmodule.exports = __toCommonJS(sinh_exports);\nvar import_internal = require(\"./_internal\");\nconst $sinh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.sinh, {\n \"-Infinity\": -Infinity,\n Infinity: Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sinh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar tan_exports = {};\n__export(tan_exports, {\n $tan: () => $tan\n});\nmodule.exports = __toCommonJS(tan_exports);\nvar import_internal = require(\"./_internal\");\nconst $tan = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.tan);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $tan\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar tanh_exports = {};\n__export(tanh_exports, {\n $tanh: () => $tanh\n});\nmodule.exports = __toCommonJS(tanh_exports);\nvar import_internal = require(\"./_internal\");\nconst $tanh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.tanh, {\n Infinity: 1,\n \"-Infinity\": -1\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $tanh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar trignometry_exports = {};\nmodule.exports = __toCommonJS(trignometry_exports);\n__reExport(trignometry_exports, require(\"./acos\"), module.exports);\n__reExport(trignometry_exports, require(\"./acosh\"), module.exports);\n__reExport(trignometry_exports, require(\"./asin\"), module.exports);\n__reExport(trignometry_exports, require(\"./asinh\"), module.exports);\n__reExport(trignometry_exports, require(\"./atan\"), module.exports);\n__reExport(trignometry_exports, require(\"./atan2\"), module.exports);\n__reExport(trignometry_exports, require(\"./atanh\"), module.exports);\n__reExport(trignometry_exports, require(\"./cos\"), module.exports);\n__reExport(trignometry_exports, require(\"./cosh\"), module.exports);\n__reExport(trignometry_exports, require(\"./degreesToRadians\"), module.exports);\n__reExport(trignometry_exports, require(\"./radiansToDegrees\"), module.exports);\n__reExport(trignometry_exports, require(\"./sin\"), module.exports);\n__reExport(trignometry_exports, require(\"./sinh\"), module.exports);\n__reExport(trignometry_exports, require(\"./tan\"), module.exports);\n__reExport(trignometry_exports, require(\"./tanh\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./acos\"),\n ...require(\"./acosh\"),\n ...require(\"./asin\"),\n ...require(\"./asinh\"),\n ...require(\"./atan\"),\n ...require(\"./atan2\"),\n ...require(\"./atanh\"),\n ...require(\"./cos\"),\n ...require(\"./cosh\"),\n ...require(\"./degreesToRadians\"),\n ...require(\"./radiansToDegrees\"),\n ...require(\"./sin\"),\n ...require(\"./sinh\"),\n ...require(\"./tan\"),\n ...require(\"./tanh\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar let_exports = {};\n__export(let_exports, {\n $let: () => $let\n});\nmodule.exports = __toCommonJS(let_exports);\nvar import_internal = require(\"../../../core/_internal\");\nconst $let = (obj, expr, options) => {\n const variables = {};\n for (const key of Object.keys(expr.vars)) {\n variables[key] = (0, import_internal.evalExpr)(obj, expr.vars[key], options);\n }\n return (0, import_internal.evalExpr)(\n obj,\n expr.in,\n import_internal.ComputeOptions.init(options).update({ variables })\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $let\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar variable_exports = {};\nmodule.exports = __toCommonJS(variable_exports);\n__reExport(variable_exports, require(\"./let\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./let\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar expression_exports = {};\nmodule.exports = __toCommonJS(expression_exports);\n__reExport(expression_exports, require(\"./arithmetic\"), module.exports);\n__reExport(expression_exports, require(\"./array\"), module.exports);\n__reExport(expression_exports, require(\"./bitwise\"), module.exports);\n__reExport(expression_exports, require(\"./boolean\"), module.exports);\n__reExport(expression_exports, require(\"./comparison\"), module.exports);\n__reExport(expression_exports, require(\"./conditional\"), module.exports);\n__reExport(expression_exports, require(\"./custom\"), module.exports);\n__reExport(expression_exports, require(\"./date\"), module.exports);\n__reExport(expression_exports, require(\"./literal\"), module.exports);\n__reExport(expression_exports, require(\"./median\"), module.exports);\n__reExport(expression_exports, require(\"./misc\"), module.exports);\n__reExport(expression_exports, require(\"./object\"), module.exports);\n__reExport(expression_exports, require(\"./percentile\"), module.exports);\n__reExport(expression_exports, require(\"./set\"), module.exports);\n__reExport(expression_exports, require(\"./string\"), module.exports);\n__reExport(expression_exports, require(\"./toHashedIndexKey\"), module.exports);\n__reExport(expression_exports, require(\"./trignometry\"), module.exports);\n__reExport(expression_exports, require(\"./type\"), module.exports);\n__reExport(expression_exports, require(\"./variable\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./arithmetic\"),\n ...require(\"./array\"),\n ...require(\"./bitwise\"),\n ...require(\"./boolean\"),\n ...require(\"./comparison\"),\n ...require(\"./conditional\"),\n ...require(\"./custom\"),\n ...require(\"./date\"),\n ...require(\"./literal\"),\n ...require(\"./median\"),\n ...require(\"./misc\"),\n ...require(\"./object\"),\n ...require(\"./percentile\"),\n ...require(\"./set\"),\n ...require(\"./string\"),\n ...require(\"./toHashedIndexKey\"),\n ...require(\"./trignometry\"),\n ...require(\"./type\"),\n ...require(\"./variable\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar addFields_exports = {};\n__export(addFields_exports, {\n $addFields: () => $addFields\n});\nmodule.exports = __toCommonJS(addFields_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nfunction $addFields(coll, expr, options) {\n const newFields = Object.keys(expr);\n if (newFields.length === 0) return coll;\n return coll.map((obj) => {\n const newObj = { ...obj };\n for (const field of newFields) {\n const newValue = (0, import_internal.evalExpr)(obj, expr[field], options);\n if (newValue !== void 0) {\n (0, import_util.setValue)(newObj, field, newValue);\n } else {\n (0, import_util.removeValue)(newObj, field);\n }\n }\n return newObj;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $addFields\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bucket_exports = {};\n__export(bucket_exports, {\n $bucket: () => $bucket\n});\nmodule.exports = __toCommonJS(bucket_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $bucket(coll, expr, options) {\n const bounds = expr.boundaries.slice();\n const defaultKey = expr.default;\n const lower = bounds[0];\n const upper = bounds[bounds.length - 1];\n const outputExpr = expr.output || { count: { $sum: 1 } };\n (0, import_util.assert)(bounds.length > 1, \"$bucket: must specify at least two boundaries.\");\n const isValid = bounds.every(\n (v, i) => i === 0 || (0, import_util.typeOf)(v) === (0, import_util.typeOf)(bounds[i - 1]) && (0, import_util.compare)(v, bounds[i - 1]) > 0\n );\n (0, import_util.assert)(\n isValid,\n `$bucket: bounds must be of same type and in ascending order`\n );\n (0, import_util.assert)(\n (0, import_util.isNil)(defaultKey) || (0, import_util.typeOf)(defaultKey) !== (0, import_util.typeOf)(lower) || (0, import_util.compare)(defaultKey, upper) >= 0 || (0, import_util.compare)(defaultKey, lower) < 0,\n \"$bucket: 'default' expression must be out of boundaries range\"\n );\n const createBuckets = () => {\n const buckets = /* @__PURE__ */ new Map();\n for (let i = 0; i < bounds.length - 1; i++) {\n buckets.set(bounds[i], []);\n }\n if (!(0, import_util.isNil)(defaultKey)) buckets.set(defaultKey, []);\n coll.each((obj) => {\n const key = (0, import_internal.evalExpr)(obj, expr.groupBy, options);\n if ((0, import_util.isNil)(key) || (0, import_util.compare)(key, lower) < 0 || (0, import_util.compare)(key, upper) >= 0) {\n (0, import_util.assert)(\n !(0, import_util.isNil)(defaultKey),\n \"$bucket require a default for out of range values\"\n );\n buckets.get(defaultKey)?.push(obj);\n } else {\n (0, import_util.assert)(\n (0, import_util.compare)(key, lower) >= 0 && (0, import_util.compare)(key, upper) < 0,\n \"$bucket 'groupBy' expression must resolve to a value in range of boundaries\"\n );\n const index = (0, import_util.findInsertIndex)(bounds, key);\n const boundKey = bounds[Math.max(0, index - 1)];\n buckets.get(boundKey)?.push(obj);\n }\n });\n bounds.pop();\n if (!(0, import_util.isNil)(defaultKey)) {\n if (buckets.get(defaultKey)?.length) bounds.push(defaultKey);\n else buckets.delete(defaultKey);\n }\n (0, import_util.assert)(\n buckets.size === bounds.length,\n \"bounds and groups must be of equal size.\"\n );\n return (0, import_lazy.Lazy)(bounds).map((key) => {\n return {\n ...(0, import_internal.evalExpr)(buckets.get(key), outputExpr, options),\n _id: key\n };\n });\n };\n let iterator;\n return (0, import_lazy.Lazy)(() => {\n if (!iterator) iterator = createBuckets();\n return iterator.next();\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bucket\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bucketAuto_exports = {};\n__export(bucketAuto_exports, {\n $bucketAuto: () => $bucketAuto\n});\nmodule.exports = __toCommonJS(bucketAuto_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $bucketAuto(coll, expr, options) {\n const {\n buckets: bucketCount,\n groupBy: groupByExpr,\n output: optOutputExpr,\n // Available only if the all groupBy values are numeric and none of them are NaN.\n granularity\n } = expr;\n const outputExpr = optOutputExpr ?? { count: { $sum: 1 } };\n (0, import_util.assert)(\n bucketCount > 0,\n `$bucketAuto: 'buckets' field must be greater than 0, but found: ${bucketCount}`\n );\n if (granularity) {\n (0, import_util.assert)(\n /^(POWERSOF2|1-2-5|E(6|12|24|48|96|192)|R(5|10|20|40|80))$/.test(\n granularity\n ),\n `$bucketAuto: invalid granularity '${granularity}'.`\n );\n }\n const keyMap = /* @__PURE__ */ new Map();\n const setKey = !granularity ? (o, k) => keyMap.set(o, k) : (_, _2) => {\n };\n const sorted = coll.map((o) => {\n const k = (0, import_internal.evalExpr)(o, groupByExpr, options) ?? null;\n (0, import_util.assert)(\n !granularity || (0, import_util.isNumber)(k),\n \"$bucketAuto: groupBy values must be numeric when granularity is specified.\"\n );\n setKey(o, k ?? null);\n return [k ?? null, o];\n }).collect();\n sorted.sort((x, y) => {\n if ((0, import_util.isNil)(x[0])) return -1;\n if ((0, import_util.isNil)(y[0])) return 1;\n return (0, import_util.compare)(x[0], y[0]);\n });\n let getNext;\n if (!granularity) {\n getNext = granularityDefault(sorted, bucketCount, keyMap);\n } else if (granularity == \"POWERSOF2\") {\n getNext = granularityPowerOfTwo(\n sorted,\n bucketCount\n );\n } else {\n getNext = granularityPreferredSeries(\n sorted,\n bucketCount,\n granularity\n );\n }\n let terminate = false;\n return (0, import_lazy.Lazy)(() => {\n if (terminate) return { done: true };\n const { min, max, bucket, done } = getNext();\n terminate = done;\n const outFields = (0, import_internal.evalExpr)(bucket, outputExpr, options);\n for (const k of Object.keys(outFields)) {\n const v = outFields[k];\n if ((0, import_util.isArray)(v)) outFields[k] = v.filter((v2) => !(0, import_util.isNil)(v2));\n }\n return {\n done: false,\n value: {\n ...outFields,\n _id: { min, max }\n }\n };\n });\n}\nfunction granularityDefault(sorted, bucketCount, keyMap) {\n const size = sorted.length;\n const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount));\n let index = 0;\n let nBuckets = 0;\n return () => {\n const isLastBucket = ++nBuckets == bucketCount;\n const bucket = new Array();\n while (index < size && (isLastBucket || bucket.length < approxBucketSize || index > 0 && (0, import_util.isEqual)(sorted[index - 1][0], sorted[index][0]))) {\n bucket.push(sorted[index++][1]);\n }\n const min = keyMap.get(bucket[0]);\n let max;\n if (index < size) {\n max = sorted[index][0];\n } else {\n max = keyMap.get(bucket[bucket.length - 1]);\n }\n (0, import_util.assert)(\n (0, import_util.isNil)(max) || (0, import_util.isNil)(min) || (0, import_util.compare)(min, max) <= 0,\n `error: $bucketAuto boundary must be in order.`\n );\n return {\n min,\n max,\n bucket,\n done: index >= size\n };\n };\n}\nfunction granularityPowerOfTwo(sorted, bucketCount) {\n const size = sorted.length;\n const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount));\n const roundUp2 = (n) => n === 0 ? 0 : 2 ** (Math.floor(Math.log2(n)) + 1);\n let index = 0;\n let min = 0;\n let max = 0;\n return () => {\n const bucket = new Array();\n const boundValue = roundUp2(max);\n min = index > 0 ? max : 0;\n while (bucket.length < approxBucketSize && index < size && (max === 0 || sorted[index][0] < boundValue)) {\n bucket.push(sorted[index++][1]);\n }\n max = max == 0 ? roundUp2(sorted[index - 1][0]) : boundValue;\n while (index < size && sorted[index][0] < max) {\n bucket.push(sorted[index++][1]);\n }\n return {\n min,\n max,\n bucket,\n done: index >= size\n };\n };\n}\nconst PREFERRED_NUMBERS = {\n // \"Least rounded\" Renard number series, taken from Wikipedia page on preferred\n // numbers: https://en.wikipedia.org/wiki/Preferred_number#Renard_numbers\n R5: [10, 16, 25, 40, 63],\n R10: [100, 125, 160, 200, 250, 315, 400, 500, 630, 800],\n R20: [\n 100,\n 112,\n 125,\n 140,\n 160,\n 180,\n 200,\n 224,\n 250,\n 280,\n 315,\n 355,\n 400,\n 450,\n 500,\n 560,\n 630,\n 710,\n 800,\n 900\n ],\n R40: [\n 100,\n 106,\n 112,\n 118,\n 125,\n 132,\n 140,\n 150,\n 160,\n 170,\n 180,\n 190,\n 200,\n 212,\n 224,\n 236,\n 250,\n 265,\n 280,\n 300,\n 315,\n 355,\n 375,\n 400,\n 425,\n 450,\n 475,\n 500,\n 530,\n 560,\n 600,\n 630,\n 670,\n 710,\n 750,\n 800,\n 850,\n 900,\n 950\n ],\n R80: [\n 103,\n 109,\n 115,\n 122,\n 128,\n 136,\n 145,\n 155,\n 165,\n 175,\n 185,\n 195,\n 206,\n 218,\n 230,\n 243,\n 258,\n 272,\n 290,\n 307,\n 325,\n 345,\n 365,\n 387,\n 412,\n 437,\n 462,\n 487,\n 515,\n 545,\n 575,\n 615,\n 650,\n 690,\n 730,\n 775,\n 825,\n 875,\n 925,\n 975\n ],\n // https://en.wikipedia.org/wiki/Preferred_number#1-2-5_series\n \"1-2-5\": [10, 20, 50],\n // E series, taken from Wikipedia page on preferred numbers:\n // https://en.wikipedia.org/wiki/Preferred_number#E_series\n E6: [10, 15, 22, 33, 47, 68],\n E12: [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82],\n E24: [\n 10,\n 11,\n 12,\n 13,\n 15,\n 16,\n 18,\n 20,\n 22,\n 24,\n 27,\n 30,\n 33,\n 36,\n 39,\n 43,\n 47,\n 51,\n 56,\n 62,\n 68,\n 75,\n 82,\n 91\n ],\n E48: [\n 100,\n 105,\n 110,\n 115,\n 121,\n 127,\n 133,\n 140,\n 147,\n 154,\n 162,\n 169,\n 178,\n 187,\n 196,\n 205,\n 215,\n 226,\n 237,\n 249,\n 261,\n 274,\n 287,\n 301,\n 316,\n 332,\n 348,\n 365,\n 383,\n 402,\n 422,\n 442,\n 464,\n 487,\n 511,\n 536,\n 562,\n 590,\n 619,\n 649,\n 681,\n 715,\n 750,\n 787,\n 825,\n 866,\n 909,\n 953\n ],\n E96: [\n 100,\n 102,\n 105,\n 107,\n 110,\n 113,\n 115,\n 118,\n 121,\n 124,\n 127,\n 130,\n 133,\n 137,\n 140,\n 143,\n 147,\n 150,\n 154,\n 158,\n 162,\n 165,\n 169,\n 174,\n 178,\n 182,\n 187,\n 191,\n 196,\n 200,\n 205,\n 210,\n 215,\n 221,\n 226,\n 232,\n 237,\n 243,\n 249,\n 255,\n 261,\n 267,\n 274,\n 280,\n 287,\n 294,\n 301,\n 309,\n 316,\n 324,\n 332,\n 340,\n 348,\n 357,\n 365,\n 374,\n 383,\n 392,\n 402,\n 412,\n 422,\n 432,\n 442,\n 453,\n 464,\n 475,\n 487,\n 499,\n 511,\n 523,\n 536,\n 549,\n 562,\n 576,\n 590,\n 604,\n 619,\n 634,\n 649,\n 665,\n 681,\n 698,\n 715,\n 732,\n 750,\n 768,\n 787,\n 806,\n 825,\n 845,\n 866,\n 887,\n 909,\n 931,\n 953,\n 976\n ],\n E192: [\n 100,\n 101,\n 102,\n 104,\n 105,\n 106,\n 107,\n 109,\n 110,\n 111,\n 113,\n 114,\n 115,\n 117,\n 118,\n 120,\n 121,\n 123,\n 124,\n 126,\n 127,\n 129,\n 130,\n 132,\n 133,\n 135,\n 137,\n 138,\n 140,\n 142,\n 143,\n 145,\n 147,\n 149,\n 150,\n 152,\n 154,\n 156,\n 158,\n 160,\n 162,\n 164,\n 165,\n 167,\n 169,\n 172,\n 174,\n 176,\n 178,\n 180,\n 182,\n 184,\n 187,\n 189,\n 191,\n 193,\n 196,\n 198,\n 200,\n 203,\n 205,\n 208,\n 210,\n 213,\n 215,\n 218,\n 221,\n 223,\n 226,\n 229,\n 232,\n 234,\n 237,\n 240,\n 243,\n 246,\n 249,\n 252,\n 255,\n 258,\n 261,\n 264,\n 267,\n 271,\n 274,\n 277,\n 280,\n 284,\n 287,\n 291,\n 294,\n 298,\n 301,\n 305,\n 309,\n 312,\n 316,\n 320,\n 324,\n 328,\n 332,\n 336,\n 340,\n 344,\n 348,\n 352,\n 357,\n 361,\n 365,\n 370,\n 374,\n 379,\n 383,\n 388,\n 392,\n 397,\n 402,\n 407,\n 412,\n 417,\n 422,\n 427,\n 432,\n 437,\n 442,\n 448,\n 453,\n 459,\n 464,\n 470,\n 475,\n 481,\n 487,\n 493,\n 499,\n 505,\n 511,\n 517,\n 523,\n 530,\n 536,\n 542,\n 549,\n 556,\n 562,\n 569,\n 576,\n 583,\n 590,\n 597,\n 604,\n 612,\n 619,\n 626,\n 634,\n 642,\n 649,\n 657,\n 665,\n 673,\n 681,\n 690,\n 698,\n 706,\n 715,\n 723,\n 732,\n 741,\n 750,\n 759,\n 768,\n 777,\n 787,\n 796,\n 806,\n 816,\n 825,\n 835,\n 845,\n 856,\n 866,\n 876,\n 887,\n 898,\n 909,\n 920,\n 931,\n 942,\n 953,\n 965,\n 976,\n 988\n ]\n};\nconst roundUp = (n, granularity) => {\n if (n == 0) return 0;\n const series = PREFERRED_NUMBERS[granularity];\n const first = series[0];\n const last = series[series.length - 1];\n let multiplier = 1;\n while (n >= last * multiplier) {\n multiplier *= 10;\n }\n let previousMin = 0;\n while (n < first * multiplier) {\n previousMin = first * multiplier;\n multiplier /= 10;\n if (n >= last * multiplier) {\n return previousMin;\n }\n }\n (0, import_util.assert)(\n n >= first * multiplier && n < last * multiplier,\n \"$bucketAuto: number out of range of series.\"\n );\n const i = (0, import_util.findInsertIndex)(series, n, (a, b) => {\n b *= multiplier;\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n });\n const seriesNumber = series[i] * multiplier;\n return n == seriesNumber ? series[i + 1] * multiplier : seriesNumber;\n};\nfunction granularityPreferredSeries(sorted, bucketCount, granularity) {\n const size = sorted.length;\n const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount));\n let index = 0;\n let nBuckets = 0;\n let min = 0;\n let max = 0;\n return () => {\n const isLastBucket = ++nBuckets == bucketCount;\n const bucket = new Array();\n min = index > 0 ? max : 0;\n while (index < size && (isLastBucket || bucket.length < approxBucketSize)) {\n bucket.push(sorted[index++][1]);\n }\n max = roundUp(sorted[index - 1][0], granularity);\n const nItems = bucket.length;\n while (index < size && (isLastBucket || sorted[index][0] < max)) {\n bucket.push(sorted[index++][1]);\n }\n if (nItems != bucket.length) {\n max = roundUp(sorted[index - 1][0], granularity);\n }\n (0, import_util.assert)(min < max, `$bucketAuto: ${min} < ${max}.`);\n return { min, max, bucket, done: index >= size };\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bucketAuto\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar count_exports = {};\n__export(count_exports, {\n $count: () => $count\n});\nmodule.exports = __toCommonJS(count_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $count(coll, expr, _options) {\n (0, import_util.assert)(\n (0, import_util.isString)(expr) && expr.trim().length > 0 && !expr.includes(\".\") && expr[0] !== \"$\",\n \"$count expression must evaluate to valid field name\"\n );\n let i = 0;\n return (0, import_lazy.Lazy)(() => {\n if (i++ == 0) return { value: { [expr]: coll.size() }, done: false };\n return { done: true };\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $count\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar densify_exports = {};\n__export(densify_exports, {\n $densify: () => $densify\n});\nmodule.exports = __toCommonJS(densify_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"../expression/date/_internal\");\nvar import_dateAdd = require(\"../expression/date/dateAdd\");\nvar import_sort = require(\"./sort\");\nconst OP = \"$densify\";\nfunction $densify(coll, expr, options) {\n const { step, bounds, unit } = expr.range;\n if (unit) {\n (0, import_util.assert)(\n import_internal.TIME_UNITS.includes(unit),\n `${OP} 'range.unit' value is not supported.`\n );\n (0, import_util.assert)(\n (0, import_util.isInteger)(step) && step > 0,\n `${OP} 'range.step' must resolve to integer if 'range.unit' is specified.`\n );\n } else {\n (0, import_util.assert)((0, import_util.isNumber)(step), `${OP} 'range.step' must resolve to number.`);\n }\n if ((0, import_util.isArray)(bounds)) {\n (0, import_util.assert)(\n !!bounds && bounds.length === 2,\n `${OP} 'range.bounds' must have exactly two elements.`\n );\n (0, import_util.assert)(\n (bounds.every(import_util.isNumber) || bounds.every(import_util.isDate)) && bounds[0] < bounds[1],\n `${OP} 'range.bounds' must be ordered lower then upper.`\n );\n if (unit) {\n (0, import_util.assert)(\n bounds.every(import_util.isDate),\n `${OP} 'range.bounds' must be dates if 'range.unit' is specified.`\n );\n }\n }\n if (expr.partitionByFields) {\n (0, import_util.assert)(\n (0, import_util.isArray)(expr.partitionByFields),\n `${OP} 'partitionByFields' must resolve to array of strings.`\n );\n }\n const partitionByFields = expr.partitionByFields ?? [];\n coll = (0, import_sort.$sort)(coll, { [expr.field]: 1 }, options);\n const computeNextValue = (value) => {\n return (0, import_util.isNumber)(value) ? value + step : (0, import_dateAdd.$dateAdd)({}, { startDate: value, unit, amount: step }, options);\n };\n const isValidUnit = !!unit && import_internal.TIME_UNITS.includes(unit);\n const getFieldValue = (o) => {\n const v = (0, import_util.resolve)(o, expr.field);\n (0, import_util.assert)(\n (0, import_util.isNil)(v) || (0, import_util.isDate)(v) && isValidUnit || (0, import_util.isNumber)(v) && !isValidUnit,\n `${OP} Densify field type must be numeric with 'unit' unspecified, or a date with 'unit' specified.`\n );\n return v;\n };\n const peekItem = new Array();\n const nilFieldsIterator = (0, import_lazy.Lazy)(() => {\n const item = coll.next();\n const fieldValue = getFieldValue(item.value);\n if ((0, import_util.isNil)(fieldValue)) return item;\n peekItem.push(item);\n return { done: true };\n });\n const nextDensifyValueMap = import_util.HashMap.init();\n const [lower, upper] = (0, import_util.isArray)(bounds) ? bounds : [bounds, bounds];\n let maxFieldValue;\n const updateMaxFieldValue = (value) => {\n maxFieldValue = maxFieldValue === void 0 || maxFieldValue < value ? value : maxFieldValue;\n };\n const rootKey = [];\n const densifyIterator = (0, import_lazy.Lazy)(() => {\n const item = peekItem.pop() || coll.next();\n if (item.done) return item;\n let partitionKey = rootKey;\n if ((0, import_util.isArray)(partitionByFields)) {\n partitionKey = partitionByFields.map(\n (k) => (0, import_util.resolve)(item.value, k)\n );\n (0, import_util.assert)(\n partitionKey.every(import_util.isString),\n \"$densify: Partition fields must evaluate to string values.\"\n );\n }\n (0, import_util.assert)((0, import_util.isObject)(item.value), \"$densify: collection must contain documents\");\n const itemValue = getFieldValue(item.value);\n if (!nextDensifyValueMap.has(partitionKey)) {\n if (lower == \"full\") {\n if (!nextDensifyValueMap.has(rootKey)) {\n nextDensifyValueMap.set(rootKey, itemValue);\n }\n nextDensifyValueMap.set(\n partitionKey,\n nextDensifyValueMap.get(rootKey)\n );\n } else if (lower == \"partition\") {\n nextDensifyValueMap.set(partitionKey, itemValue);\n } else {\n nextDensifyValueMap.set(partitionKey, lower);\n }\n }\n const densifyValue = nextDensifyValueMap.get(partitionKey);\n if (\n // current item field value is lower than current densify value.\n itemValue <= densifyValue || // range value equals or exceeds upper bound\n upper != \"full\" && upper != \"partition\" && densifyValue >= upper\n ) {\n if (densifyValue <= itemValue) {\n nextDensifyValueMap.set(partitionKey, computeNextValue(densifyValue));\n }\n updateMaxFieldValue(itemValue);\n return item;\n }\n nextDensifyValueMap.set(partitionKey, computeNextValue(densifyValue));\n updateMaxFieldValue(densifyValue);\n const denseObj = { [expr.field]: densifyValue };\n if (partitionKey) {\n for (let i = 0; i < partitionKey.length; i++) {\n denseObj[partitionByFields[i]] = partitionKey[i];\n }\n }\n peekItem.push(item);\n return { done: false, value: denseObj };\n });\n if (lower !== \"full\") return (0, import_lazy.concat)(nilFieldsIterator, densifyIterator);\n let paritionIndex = -1;\n let partitionKeysSet;\n const fullBoundsIterator = (0, import_lazy.Lazy)(() => {\n if (paritionIndex === -1) {\n const fullDensifyValue = nextDensifyValueMap.get(rootKey);\n nextDensifyValueMap.delete(rootKey);\n partitionKeysSet = Array.from(nextDensifyValueMap.keys());\n if (partitionKeysSet.length === 0) {\n partitionKeysSet.push(rootKey);\n nextDensifyValueMap.set(rootKey, fullDensifyValue);\n }\n paritionIndex++;\n }\n do {\n const partitionKey = partitionKeysSet[paritionIndex];\n const partitionMaxValue = nextDensifyValueMap.get(partitionKey);\n if (partitionMaxValue < maxFieldValue) {\n nextDensifyValueMap.set(\n partitionKey,\n computeNextValue(partitionMaxValue)\n );\n const denseObj = { [expr.field]: partitionMaxValue };\n for (let i = 0; i < partitionKey.length; i++) {\n denseObj[partitionByFields[i]] = partitionKey[i];\n }\n return { done: false, value: denseObj };\n }\n paritionIndex++;\n } while (paritionIndex < partitionKeysSet.length);\n return { done: true };\n });\n return (0, import_lazy.concat)(nilFieldsIterator, densifyIterator, fullBoundsIterator);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $densify\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar facet_exports = {};\n__export(facet_exports, {\n $facet: () => $facet\n});\nmodule.exports = __toCommonJS(facet_exports);\nvar import_aggregator = require(\"../../aggregator\");\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nfunction $facet(coll, expr, options) {\n if (!(options.processingMode & import_internal.ProcessingMode.CLONE_INPUT)) {\n options = {\n ...import_internal.ComputeOptions.init(options).options,\n processingMode: import_internal.ProcessingMode.CLONE_INPUT\n };\n }\n return coll.transform((arr) => {\n const o = {};\n for (const k of Object.keys(expr)) {\n o[k] = new import_aggregator.Aggregator(expr[k], options).run(arr);\n }\n return (0, import_lazy.Lazy)([o]);\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $facet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n cached: () => cached,\n rank: () => rank,\n withMemo: () => withMemo\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nconst memo = /* @__PURE__ */ new WeakMap();\nconst cached = (xs) => memo.has(xs);\nfunction withMemo(collection, expr, initialize, fn) {\n if (!memo.has(collection)) {\n memo.set(collection, {});\n }\n const data = memo.get(collection);\n if (!(expr.field in data)) {\n data[expr.field] = initialize();\n }\n let ok = false;\n try {\n const res = fn(data[expr.field]);\n ok = true;\n return res;\n } finally {\n if (!ok) {\n memo.delete(collection);\n } else if (expr.documentNumber === collection.length) {\n delete data[expr.field];\n if (Object.keys(data).length === 0) memo.delete(collection);\n }\n }\n}\nfunction rank(_, collection, expr, options, dense) {\n return withMemo(\n collection,\n expr,\n () => {\n const sortKey = \"$\" + Object.keys(expr.parentExpr.sortBy)[0];\n const values = (0, import_push.$push)(collection, sortKey, options);\n const groups = (0, import_util.groupBy)(\n values,\n ((_2, n) => values[n])\n );\n let i = 0;\n let offset = 0;\n for (const key of groups.keys()) {\n const len = groups.get(key).length;\n groups.set(key, [i++, offset]);\n offset += len;\n }\n return { values, groups };\n },\n ({ values, groups }) => {\n if (groups.size == collection.length) return expr.documentNumber;\n const current = values[expr.documentNumber - 1];\n const [i, n] = groups.get(current);\n return (dense ? i : n) + 1;\n }\n );\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n cached,\n rank,\n withMemo\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar linearFill_exports = {};\n__export(linearFill_exports, {\n $linearFill: () => $linearFill\n});\nmodule.exports = __toCommonJS(linearFill_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"./_internal\");\nconst interpolate = (x1, y1, x2, y2, x) => y1 + (x - x1) * ((y2 - y1) / (x2 - x1));\nconst $linearFill = (_, coll, expr, options) => {\n return (0, import_internal.withMemo)(\n coll,\n expr,\n () => {\n const sortKey = \"$\" + Object.keys(expr.parentExpr.sortBy)[0];\n const points = (0, import_push.$push)(coll, [sortKey, expr.inputExpr], options).filter((([\n x,\n _2\n ]) => (0, import_util.isNumber)(+x)));\n let lindex = -1;\n let rindex = 0;\n while (rindex < points.length) {\n while (lindex + 1 < points.length && (0, import_util.isNumber)(points[lindex + 1][1])) {\n lindex++;\n rindex = lindex;\n }\n while (rindex + 1 < points.length && !(0, import_util.isNumber)(points[rindex + 1][1])) {\n rindex++;\n }\n if (rindex + 1 >= points.length) break;\n rindex++;\n while (lindex + 1 < rindex) {\n points[lindex + 1][1] = interpolate(\n points[lindex][0],\n points[lindex][1],\n points[rindex][0],\n points[rindex][1],\n points[lindex + 1][0]\n );\n lindex++;\n }\n lindex = rindex;\n }\n return points.map(([_2, y]) => y);\n },\n (values) => values[expr.documentNumber - 1]\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $linearFill\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar locf_exports = {};\n__export(locf_exports, {\n $locf: () => $locf\n});\nmodule.exports = __toCommonJS(locf_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"./_internal\");\nconst $locf = (_, coll, expr, options) => {\n return (0, import_internal.withMemo)(\n coll,\n expr,\n () => {\n const values = (0, import_push.$push)(coll, expr.inputExpr, options);\n for (let i = 1; i < values.length; i++) {\n if ((0, import_util.isNil)(values[i])) values[i] = values[i - 1];\n }\n return values;\n },\n (series) => series[expr.documentNumber - 1]\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $locf\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar group_exports = {};\n__export(group_exports, {\n $group: () => $group\n});\nmodule.exports = __toCommonJS(group_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nconst ID_KEY = \"_id\";\nfunction $group(coll, expr, options) {\n (0, import_util.assert)((0, import_util.has)(expr, ID_KEY), \"$group specification must include an '_id'\");\n const idExpr = expr[ID_KEY];\n const copts = import_internal.ComputeOptions.init(options);\n const newFields = Object.keys(expr).filter((k) => k != ID_KEY);\n return coll.transform((items) => {\n const partitions = (0, import_util.groupBy)(items, (obj) => (0, import_internal.evalExpr)(obj, idExpr, options));\n let i = -1;\n const partitionKeys = Array.from(partitions.keys());\n return (0, import_lazy.Lazy)(() => {\n if (++i === partitions.size) return { done: true };\n const groupId = partitionKeys[i];\n const obj = {};\n if (groupId !== void 0) {\n obj[ID_KEY] = groupId;\n }\n for (const key of newFields) {\n obj[key] = (0, import_internal.evalExpr)(\n partitions.get(groupId),\n expr[key],\n copts.update({ root: null, groupId })\n );\n }\n return { value: obj, done: false };\n });\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $group\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setWindowFields_exports = {};\n__export(setWindowFields_exports, {\n $setWindowFields: () => $setWindowFields\n});\nmodule.exports = __toCommonJS(setWindowFields_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_function = require(\"../expression/custom/function\");\nvar import_dateAdd = require(\"../expression/date/dateAdd\");\nvar import_addFields = require(\"./addFields\");\nvar import_group = require(\"./group\");\nvar import_sort = require(\"./sort\");\nconst SORT_REQUIRED_OPS = [\n \"$denseRank\",\n \"$documentNumber\",\n \"$first\",\n \"$last\",\n \"$linearFill\",\n \"$rank\",\n \"$shift\"\n];\nconst WINDOW_UNBOUNDED_OPS = [\n \"$denseRank\",\n \"$expMovingAvg\",\n \"$linearFill\",\n \"$locf\",\n \"$rank\",\n \"$shift\"\n];\nconst isUnbounded = (window) => {\n const boundary = window?.documents || window?.range;\n return !boundary || boundary[0] === \"unbounded\" && boundary[1] === \"unbounded\";\n};\nconst OP = \"$setWindowFields\";\nfunction $setWindowFields(coll, expr, options) {\n options = import_internal.ComputeOptions.init(options);\n options.context.addExpressionOps({ $function: import_function.$function });\n const operators = {};\n const outputFields = Object.keys(expr.output);\n for (const field of outputFields) {\n const outputExpr = expr.output[field];\n const keys = Object.keys(outputExpr);\n const op = keys.find(import_util.isOperator);\n const context = options.context;\n (0, import_util.assert)(\n op && (!!context.getOperator(import_internal.OpType.WINDOW, op) || !!context.getOperator(import_internal.OpType.ACCUMULATOR, op)),\n `${OP} '${op}' is not a valid window operator`\n );\n (0, import_util.assert)(\n keys.length > 0 && keys.length <= 2 && (keys.length == 1 || keys.includes(\"window\")),\n `${OP} 'output' option should have a single window operator.`\n );\n if (outputExpr?.window) {\n const { documents, range } = outputExpr.window;\n (0, import_util.assert)(\n (+!!documents ^ +!!range) === 1,\n \"'window' option supports only one of 'documents' or 'range'.\"\n );\n }\n operators[field] = op;\n }\n if (expr.sortBy) {\n coll = (0, import_sort.$sort)(coll, expr.sortBy, options);\n }\n coll = (0, import_group.$group)(\n coll,\n {\n _id: expr.partitionBy,\n items: { $push: \"$$CURRENT\" }\n },\n options\n );\n return coll.transform((partitions) => {\n const iterators = [];\n const outputConfig = [];\n for (const field of outputFields) {\n const outputExpr = expr.output[field];\n const op = operators[field];\n const config = {\n operatorName: op,\n func: {\n left: options.context.getOperator(import_internal.OpType.ACCUMULATOR, op),\n right: options.context.getOperator(import_internal.OpType.WINDOW, op)\n },\n args: outputExpr[op],\n field,\n window: outputExpr.window\n };\n const unbounded = isUnbounded(config.window);\n if (unbounded == false || SORT_REQUIRED_OPS.includes(op)) {\n const suffix = unbounded ? `'${op}'` : \"bounded window operations\";\n (0, import_util.assert)(expr.sortBy, `${OP} 'sortBy' is required for ${suffix}.`);\n }\n (0, import_util.assert)(\n unbounded || !WINDOW_UNBOUNDED_OPS.includes(op),\n `${OP} cannot use bounded window for operator '${op}'.`\n );\n outputConfig.push(config);\n }\n for (const group of partitions) {\n const items = group.items;\n let iterator = (0, import_lazy.Lazy)(items);\n const windowResultMap = {};\n for (const config of outputConfig) {\n const { func, args, field, window } = config;\n const makeResultFunc = (getItemsFn) => {\n let index = -1;\n return (obj) => {\n ++index;\n if (func.left) {\n return func.left(getItemsFn(obj, index), args, options);\n } else if (func.right) {\n return func.right(\n obj,\n getItemsFn(obj, index),\n {\n parentExpr: expr,\n inputExpr: args,\n documentNumber: index + 1,\n field\n },\n // must use raw options only since it operates over a collection.\n options\n );\n }\n };\n };\n if (window) {\n const { documents, range, unit } = window;\n const boundary = documents || range;\n if (!isUnbounded(window)) {\n const [begin, end] = boundary;\n const toBeginIndex = (currentIndex) => {\n if (begin == \"current\") return currentIndex;\n if (begin == \"unbounded\") return 0;\n return Math.max(begin + currentIndex, 0);\n };\n const toEndIndex = (currentIndex) => {\n if (end == \"current\") return currentIndex + 1;\n if (end == \"unbounded\") return items.length;\n return end + currentIndex + 1;\n };\n const getItems = (current, index) => {\n if (!!documents || boundary?.every(import_util.isString)) {\n return items.slice(toBeginIndex(index), toEndIndex(index));\n }\n const sortKey = Object.keys(expr.sortBy)[0];\n let lower;\n let upper;\n if (unit) {\n const startDate = new Date(current[sortKey]);\n const getTime = (amount) => {\n const addExpr = { startDate, unit, amount };\n const d = (0, import_dateAdd.$dateAdd)(current, addExpr, options);\n return d.getTime();\n };\n lower = (0, import_util.isNumber)(begin) ? getTime(begin) : -Infinity;\n upper = (0, import_util.isNumber)(end) ? getTime(end) : Infinity;\n } else {\n const currentValue = current[sortKey];\n lower = (0, import_util.isNumber)(begin) ? currentValue + begin : -Infinity;\n upper = (0, import_util.isNumber)(end) ? currentValue + end : Infinity;\n }\n let i = begin == \"current\" ? index : 0;\n const sliceEnd = end == \"current\" ? index + 1 : items.length;\n const array = new Array();\n while (i < sliceEnd) {\n const o = items[i++];\n const n = +o[sortKey];\n if (n >= lower && n <= upper) array.push(o);\n }\n return array;\n };\n windowResultMap[field] = makeResultFunc(getItems);\n }\n }\n if (!windowResultMap[field]) {\n windowResultMap[field] = makeResultFunc((_) => items);\n }\n iterator = (0, import_addFields.$addFields)(\n iterator,\n {\n [field]: {\n $function: {\n body: (obj) => windowResultMap[field](obj),\n args: [\"$$CURRENT\"]\n }\n }\n },\n options\n );\n }\n iterators.push(iterator);\n }\n return (0, import_lazy.concat)(...iterators);\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setWindowFields\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar fill_exports = {};\n__export(fill_exports, {\n $fill: () => $fill\n});\nmodule.exports = __toCommonJS(fill_exports);\nvar import_util = require(\"../../util\");\nvar import_ifNull = require(\"../expression/conditional/ifNull\");\nvar import_linearFill = require(\"../window/linearFill\");\nvar import_locf = require(\"../window/locf\");\nvar import_addFields = require(\"./addFields\");\nvar import_setWindowFields = require(\"./setWindowFields\");\nconst FILL_METHODS = { locf: \"$locf\", linear: \"$linearFill\" };\nfunction $fill(coll, expr, options) {\n (0, import_util.assert)(!expr.sortBy || (0, import_util.isObject)(expr.sortBy), \"sortBy must be an object.\");\n (0, import_util.assert)(\n !!expr.sortBy || Object.values(expr.output).every((m) => (0, import_util.has)(m, \"value\")),\n \"sortBy required if any output field specifies a 'method'.\"\n );\n (0, import_util.assert)(\n !(expr.partitionBy && expr.partitionByFields),\n \"specify either partitionBy or partitionByFields.\"\n );\n (0, import_util.assert)(\n !expr.partitionByFields || expr?.partitionByFields?.every((s) => s[0] !== \"$\"),\n \"fields in partitionByFields cannot begin with '$'.\"\n );\n options.context.addExpressionOps({ $ifNull: import_ifNull.$ifNull });\n options.context.addWindowOps({ $locf: import_locf.$locf, $linearFill: import_linearFill.$linearFill });\n const partitionExpr = expr.partitionBy || expr?.partitionByFields?.map((s) => \"$\" + s);\n const valueExpr = {};\n const methodExpr = {};\n for (const k of Object.keys(expr.output)) {\n const m = expr.output[k];\n if ((0, import_util.has)(m, \"value\")) {\n const out = m;\n valueExpr[k] = { $ifNull: [`$$CURRENT.${k}`, out.value] };\n } else {\n const out = m;\n const fillOp = FILL_METHODS[out.method];\n (0, import_util.assert)(!!fillOp, `invalid fill method '${out.method}'.`);\n methodExpr[k] = { [fillOp]: \"$\" + k };\n }\n }\n if (Object.keys(methodExpr).length > 0) {\n coll = (0, import_setWindowFields.$setWindowFields)(\n coll,\n {\n sortBy: expr.sortBy || {},\n partitionBy: partitionExpr,\n output: methodExpr\n },\n options\n );\n }\n if (Object.keys(valueExpr).length > 0) {\n coll = (0, import_addFields.$addFields)(coll, valueExpr, options);\n }\n return coll;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $fill\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lookup_exports = {};\n__export(lookup_exports, {\n $lookup: () => $lookup\n});\nmodule.exports = __toCommonJS(lookup_exports);\nvar import_aggregator = require(\"../../aggregator\");\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"./_internal\");\nfunction $lookup(coll, expr, options) {\n const { let: letExpr, foreignField, localField } = expr;\n let lookupEq = (_) => [true, []];\n let joinColl = (0, import_util.isString)(expr.from) ? (0, import_internal2.resolveCollection)(\"$lookup\", expr.from, options) : expr.from;\n const { documents, pipeline } = (0, import_internal2.filterDocumentsStage)(\n expr.pipeline ?? [],\n options\n );\n (0, import_util.assert)(\n !joinColl !== !documents,\n \"$lookup: must specify single join input with `expr.from` or `expr.pipeline`.\"\n );\n joinColl = joinColl ?? documents;\n (0, import_util.assert)(\n (0, import_util.isArray)(joinColl),\n \"$lookup: join collection must resolve to an array.\"\n );\n if (foreignField && localField) {\n const map = import_util.HashMap.init();\n for (const doc of joinColl) {\n for (const v of (0, import_util.ensureArray)((0, import_util.resolve)(doc, foreignField) ?? null)) {\n const xs = map.get(v);\n const arr = xs ?? [];\n arr.push(doc);\n if (arr !== xs) map.set(v, arr);\n }\n }\n lookupEq = (o) => {\n const local = (0, import_util.resolve)(o, localField) ?? null;\n if ((0, import_util.isArray)(local)) {\n if (pipeline?.length) {\n return [local.some((v) => map.has(v)), []];\n }\n const result2 = Array.from(new Set((0, import_util.flatten)(local.map((v) => map.get(v)))));\n return [result2.length > 0, result2];\n }\n const result = map.get(local) ?? null;\n return [result !== null, result ?? []];\n };\n if (pipeline?.length === 0) {\n return coll.map((obj) => {\n return { ...obj, [expr.as]: lookupEq(obj).pop() };\n });\n }\n }\n const agg = new import_aggregator.Aggregator(pipeline ?? [], options);\n const opts = import_internal.ComputeOptions.init(options);\n return coll.map((obj) => {\n const vars = (0, import_internal.evalExpr)(obj, letExpr, options);\n opts.update({ root: null, variables: vars });\n const [ok, res] = lookupEq(obj);\n return { ...obj, [expr.as]: ok ? agg.run(joinColl, opts) : res };\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lookup\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar graphLookup_exports = {};\n__export(graphLookup_exports, {\n $graphLookup: () => $graphLookup\n});\nmodule.exports = __toCommonJS(graphLookup_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"./_internal\");\nvar import_lookup = require(\"./lookup\");\nfunction $graphLookup(coll, expr, options) {\n const fromColl = (0, import_internal2.resolveCollection)(\"$graphLookup\", expr.from, options);\n (0, import_util.assert)(\n (0, import_util.isArray)(fromColl),\n \"$graphLookup: expression 'from' must resolve to array\"\n );\n const {\n connectFromField,\n connectToField,\n as: asField,\n maxDepth,\n depthField,\n restrictSearchWithMatch: matchExpr\n } = expr;\n const pipelineExpr = matchExpr ? { pipeline: [{ $match: matchExpr }] } : {};\n return coll.map((obj) => {\n const matchObj = {};\n (0, import_util.setValue)(\n matchObj,\n connectFromField,\n (0, import_internal.evalExpr)(obj, expr.startWith, options)\n );\n let matches = [matchObj];\n let i = -1;\n const map = import_util.HashMap.init();\n do {\n i++;\n matches = (0, import_util.flatten)(\n (0, import_lookup.$lookup)(\n (0, import_lazy.Lazy)(matches),\n {\n from: fromColl,\n localField: connectFromField,\n foreignField: connectToField,\n as: asField,\n ...pipelineExpr\n },\n options\n ).map((o) => o[asField]).collect()\n );\n const oldSize = map.size;\n for (const k of matches) map.set(k, map.get(k) ?? i);\n if (oldSize == map.size) break;\n } while ((0, import_util.isNil)(maxDepth) || i < maxDepth);\n const result = new Array(map.size);\n let n = 0;\n for (const [k, v] of map.entries()) {\n result[n++] = Object.assign(depthField ? { [depthField]: v } : {}, k);\n }\n return { ...obj, [asField]: result };\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $graphLookup\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar match_exports = {};\n__export(match_exports, {\n $match: () => $match\n});\nmodule.exports = __toCommonJS(match_exports);\nvar import_query = require(\"../../query\");\nfunction $match(coll, expr, options) {\n const q = new import_query.Query(expr, options);\n return coll.filter((o) => q.test(o));\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $match\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar merge_exports = {};\n__export(merge_exports, {\n $merge: () => $merge\n});\nmodule.exports = __toCommonJS(merge_exports);\nvar import_aggregator = require(\"../../aggregator\");\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_expression = require(\"../expression\");\nvar import_internal2 = require(\"./_internal\");\nfunction $merge(coll, expr, options) {\n const output = (0, import_internal2.resolveCollection)(\"$merge\", expr.into, options);\n (0, import_util.assert)((0, import_util.isArray)(output), `$merge: expression 'into' must resolve to an array`);\n const onField = expr.on || options.idKey;\n const getHash = (0, import_util.isString)(onField) ? (o) => (0, import_util.hashCode)((0, import_util.resolve)(o, onField)) : (o) => (0, import_util.hashCode)(onField.map((s) => (0, import_util.resolve)(o, s)));\n const map = import_util.HashMap.init();\n for (let i = 0; i < output.length; i++) {\n const obj = output[i];\n const k = getHash(obj);\n (0, import_util.assert)(\n !map.has(k),\n \"$merge: 'into' collection must have unique entries for the 'on' field.\"\n );\n map.set(k, [obj, i]);\n }\n const copts = import_internal.ComputeOptions.init(options);\n return coll.map((o) => {\n const k = getHash(o);\n if (map.has(k)) {\n const [target, i] = map.get(k);\n const variables = (0, import_internal.evalExpr)(\n target,\n expr.let || { new: \"$$ROOT\" },\n // 'root' is the item from the iteration.\n copts.update({ root: o })\n );\n if ((0, import_util.isArray)(expr.whenMatched)) {\n const aggregator = new import_aggregator.Aggregator(\n expr.whenMatched,\n copts.update({ root: null, variables })\n );\n output[i] = aggregator.run([target])[0];\n } else {\n switch (expr.whenMatched) {\n case \"replace\":\n output[i] = o;\n break;\n case \"fail\":\n throw new import_util.MingoError(\n \"$merge: failed due to matching as specified by 'whenMatched' option.\"\n );\n case \"keepExisting\":\n break;\n case \"merge\":\n default:\n output[i] = (0, import_expression.$mergeObjects)(\n target,\n [target, o],\n // 'root' is the item from the iteration.\n copts.update({ root: o, variables })\n );\n break;\n }\n }\n } else {\n switch (expr.whenNotMatched) {\n case \"discard\":\n break;\n case \"fail\":\n throw new import_util.MingoError(\n \"$merge: failed due to matching as specified by 'whenMatched' option.\"\n );\n case \"insert\":\n default:\n output.push(o);\n break;\n }\n }\n return o;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $merge\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar out_exports = {};\n__export(out_exports, {\n $out: () => $out\n});\nmodule.exports = __toCommonJS(out_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $out(coll, expr, options) {\n const out = (0, import_internal.resolveCollection)(\"$out\", expr, options);\n (0, import_util.assert)((0, import_util.isArray)(out), `$out: expression must resolve to an array`);\n return coll.map((o) => {\n out.push((0, import_util.cloneDeep)(o));\n return o;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $out\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar redact_exports = {};\n__export(redact_exports, {\n $redact: () => $redact\n});\nmodule.exports = __toCommonJS(redact_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nfunction $redact(coll, expr, options) {\n const copts = import_internal.ComputeOptions.init(options);\n return coll.map(\n (root) => redact(root, expr, copts.update({ root }))\n );\n}\nfunction redact(obj, expr, options) {\n const action = (0, import_internal.evalExpr)(obj, expr, options);\n switch (action) {\n case \"$$KEEP\":\n return obj;\n case \"$$PRUNE\":\n return void 0;\n case \"$$DESCEND\": {\n if (!(0, import_util.has)(expr, \"$cond\")) return obj;\n const output = {};\n for (const key of Object.keys(obj)) {\n const value = obj[key];\n if ((0, import_util.isArray)(value)) {\n const res = new Array();\n for (let elem of value) {\n if ((0, import_util.isObject)(elem)) {\n elem = redact(elem, expr, options.update({ root: elem }));\n }\n if (!(0, import_util.isNil)(elem)) res.push(elem);\n }\n output[key] = res;\n } else if ((0, import_util.isObject)(value)) {\n const res = redact(\n value,\n expr,\n options.update({ root: value })\n );\n if (!(0, import_util.isNil)(res)) output[key] = res;\n } else {\n output[key] = value;\n }\n }\n return output;\n }\n default:\n return action;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $redact\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar replaceRoot_exports = {};\n__export(replaceRoot_exports, {\n $replaceRoot: () => $replaceRoot\n});\nmodule.exports = __toCommonJS(replaceRoot_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nfunction $replaceRoot(coll, expr, options) {\n return coll.map((obj) => {\n obj = (0, import_internal.evalExpr)(obj, expr.newRoot, options);\n (0, import_util.assert)((0, import_util.isObject)(obj), \"$replaceRoot expression must return an object\");\n return obj;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $replaceRoot\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar replaceWith_exports = {};\n__export(replaceWith_exports, {\n $replaceWith: () => $replaceWith\n});\nmodule.exports = __toCommonJS(replaceWith_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nfunction $replaceWith(coll, expr, options) {\n return coll.map((obj) => {\n obj = (0, import_internal.evalExpr)(obj, expr, options);\n (0, import_util.assert)((0, import_util.isObject)(obj), \"$replaceWith expression must return an object\");\n return obj;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $replaceWith\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sample_exports = {};\n__export(sample_exports, {\n $sample: () => $sample\n});\nmodule.exports = __toCommonJS(sample_exports);\nvar import_lazy = require(\"../../lazy\");\nfunction $sample(coll, expr, _options) {\n return coll.transform((xs) => {\n const len = xs.length;\n let i = -1;\n return (0, import_lazy.Lazy)(() => {\n if (++i === expr.size) return { done: true };\n const n = Math.floor(Math.random() * len);\n return { value: xs[n], done: false };\n });\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sample\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar set_exports = {};\n__export(set_exports, {\n $set: () => $set\n});\nmodule.exports = __toCommonJS(set_exports);\nvar import_addFields = require(\"./addFields\");\nconst $set = import_addFields.$addFields;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $set\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sortByCount_exports = {};\n__export(sortByCount_exports, {\n $sortByCount: () => $sortByCount\n});\nmodule.exports = __toCommonJS(sortByCount_exports);\nvar import_group = require(\"./group\");\nvar import_sort = require(\"./sort\");\nfunction $sortByCount(coll, expr, options) {\n return (0, import_sort.$sort)(\n (0, import_group.$group)(coll, { _id: expr, count: { $sum: 1 } }, options),\n { count: -1 },\n options\n );\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sortByCount\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unionWith_exports = {};\n__export(unionWith_exports, {\n $unionWith: () => $unionWith\n});\nmodule.exports = __toCommonJS(unionWith_exports);\nvar import_aggregator = require(\"../../aggregator\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $unionWith(collection, expr, options) {\n const { coll: inputColl, pipeline: stages } = (0, import_util.isString)(expr) || (0, import_util.isArray)(expr) ? { coll: expr } : expr;\n const docsFromInput = (0, import_util.isString)(inputColl) ? (0, import_internal.resolveCollection)(\"$unionWith\", inputColl, options) : inputColl;\n const { documents, pipeline } = (0, import_internal.filterDocumentsStage)(stages, options);\n (0, import_util.assert)(\n docsFromInput || documents,\n \"$unionWith must specify single collection input with `expr.coll` or `expr.pipeline`.\"\n );\n const xs = docsFromInput ?? documents;\n return (0, import_lazy.concat)(\n collection,\n pipeline ? new import_aggregator.Aggregator(pipeline, options).stream(xs) : (0, import_lazy.Lazy)(xs)\n );\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unionWith\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unset_exports = {};\n__export(unset_exports, {\n $unset: () => $unset\n});\nmodule.exports = __toCommonJS(unset_exports);\nvar import_util = require(\"../../util\");\nvar import_project = require(\"./project\");\nfunction $unset(coll, expr, options) {\n expr = (0, import_util.ensureArray)(expr);\n const doc = {};\n for (const k of expr) doc[k] = 0;\n return (0, import_project.$project)(coll, doc, options);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unset\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unwind_exports = {};\n__export(unwind_exports, {\n $unwind: () => $unwind\n});\nmodule.exports = __toCommonJS(unwind_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_internal = require(\"../../util/_internal\");\nfunction $unwind(coll, expr, _options) {\n if ((0, import_internal.isString)(expr)) expr = { path: expr };\n const path = expr.path;\n const field = path.substring(1);\n const includeArrayIndex = expr?.includeArrayIndex || false;\n const preserveNullAndEmptyArrays = expr.preserveNullAndEmptyArrays || false;\n const format = (o, i) => {\n if (includeArrayIndex !== false) o[includeArrayIndex] = i;\n return o;\n };\n let value;\n return (0, import_lazy.Lazy)(() => {\n for (; ; ) {\n if (value instanceof import_lazy.Iterator) {\n const tmp = value.next();\n if (!tmp.done) return tmp;\n }\n const wrapper = coll.next();\n if (wrapper.done) return wrapper;\n const obj = wrapper.value;\n value = (0, import_internal.resolve)(obj, field);\n if ((0, import_internal.isArray)(value)) {\n if (value.length === 0 && preserveNullAndEmptyArrays === true) {\n value = null;\n (0, import_internal.removeValue)(obj, field);\n return { value: format(obj, null), done: false };\n } else {\n value = (0, import_lazy.Lazy)(value).map(((item, i) => {\n const newObj = (0, import_internal.resolveGraph)(obj, field, {\n preserveKeys: true\n });\n (0, import_internal.setValue)(newObj, field, item);\n return format(newObj, i);\n }));\n }\n } else if (!(0, import_internal.isEmpty)(value) || preserveNullAndEmptyArrays === true) {\n return { value: format(obj, null), done: false };\n }\n }\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unwind\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pipeline_exports = {};\nmodule.exports = __toCommonJS(pipeline_exports);\n__reExport(pipeline_exports, require(\"./addFields\"), module.exports);\n__reExport(pipeline_exports, require(\"./bucket\"), module.exports);\n__reExport(pipeline_exports, require(\"./bucketAuto\"), module.exports);\n__reExport(pipeline_exports, require(\"./count\"), module.exports);\n__reExport(pipeline_exports, require(\"./densify\"), module.exports);\n__reExport(pipeline_exports, require(\"./documents\"), module.exports);\n__reExport(pipeline_exports, require(\"./facet\"), module.exports);\n__reExport(pipeline_exports, require(\"./fill\"), module.exports);\n__reExport(pipeline_exports, require(\"./graphLookup\"), module.exports);\n__reExport(pipeline_exports, require(\"./group\"), module.exports);\n__reExport(pipeline_exports, require(\"./limit\"), module.exports);\n__reExport(pipeline_exports, require(\"./lookup\"), module.exports);\n__reExport(pipeline_exports, require(\"./match\"), module.exports);\n__reExport(pipeline_exports, require(\"./merge\"), module.exports);\n__reExport(pipeline_exports, require(\"./out\"), module.exports);\n__reExport(pipeline_exports, require(\"./project\"), module.exports);\n__reExport(pipeline_exports, require(\"./redact\"), module.exports);\n__reExport(pipeline_exports, require(\"./replaceRoot\"), module.exports);\n__reExport(pipeline_exports, require(\"./replaceWith\"), module.exports);\n__reExport(pipeline_exports, require(\"./sample\"), module.exports);\n__reExport(pipeline_exports, require(\"./set\"), module.exports);\n__reExport(pipeline_exports, require(\"./setWindowFields\"), module.exports);\n__reExport(pipeline_exports, require(\"./skip\"), module.exports);\n__reExport(pipeline_exports, require(\"./sort\"), module.exports);\n__reExport(pipeline_exports, require(\"./sortByCount\"), module.exports);\n__reExport(pipeline_exports, require(\"./unionWith\"), module.exports);\n__reExport(pipeline_exports, require(\"./unset\"), module.exports);\n__reExport(pipeline_exports, require(\"./unwind\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./addFields\"),\n ...require(\"./bucket\"),\n ...require(\"./bucketAuto\"),\n ...require(\"./count\"),\n ...require(\"./densify\"),\n ...require(\"./documents\"),\n ...require(\"./facet\"),\n ...require(\"./fill\"),\n ...require(\"./graphLookup\"),\n ...require(\"./group\"),\n ...require(\"./limit\"),\n ...require(\"./lookup\"),\n ...require(\"./match\"),\n ...require(\"./merge\"),\n ...require(\"./out\"),\n ...require(\"./project\"),\n ...require(\"./redact\"),\n ...require(\"./replaceRoot\"),\n ...require(\"./replaceWith\"),\n ...require(\"./sample\"),\n ...require(\"./set\"),\n ...require(\"./setWindowFields\"),\n ...require(\"./skip\"),\n ...require(\"./sort\"),\n ...require(\"./sortByCount\"),\n ...require(\"./unionWith\"),\n ...require(\"./unset\"),\n ...require(\"./unwind\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar elemMatch_exports = {};\n__export(elemMatch_exports, {\n $elemMatch: () => $elemMatch\n});\nmodule.exports = __toCommonJS(elemMatch_exports);\nvar import_query = require(\"../../query\");\nvar import_util = require(\"../../util\");\nconst $elemMatch = (obj, expr, field, options) => {\n const arr = (0, import_util.resolve)(obj, field);\n const query = new import_query.Query(expr, options);\n if (!(0, import_util.isArray)(arr)) return void 0;\n const result = [];\n for (let i = 0; i < arr.length; i++) {\n if (query.test(arr[i])) {\n if (options.useStrictMode) return [arr[i]];\n result.push(arr[i]);\n }\n }\n return result.length > 0 ? result : void 0;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $elemMatch\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar slice_exports = {};\n__export(slice_exports, {\n $slice: () => $slice\n});\nmodule.exports = __toCommonJS(slice_exports);\nvar import_util = require(\"../../util\");\nvar import_slice = require(\"../expression/array/slice\");\nconst $slice = (obj, expr, field, options) => {\n const xs = (0, import_util.resolve)(obj, field);\n if (!(0, import_util.isArray)(xs)) return xs;\n return (0, import_slice.$slice)(\n obj,\n (0, import_util.isArray)(expr) ? [xs, ...expr] : [xs, expr],\n options\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $slice\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar projection_exports = {};\nmodule.exports = __toCommonJS(projection_exports);\n__reExport(projection_exports, require(\"./elemMatch\"), module.exports);\n__reExport(projection_exports, require(\"./slice\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./elemMatch\"),\n ...require(\"./slice\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar all_exports = {};\n__export(all_exports, {\n $all: () => $all\n});\nmodule.exports = __toCommonJS(all_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $all = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$all);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $all\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar elemMatch_exports = {};\n__export(elemMatch_exports, {\n $elemMatch: () => $elemMatch\n});\nmodule.exports = __toCommonJS(elemMatch_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $elemMatch = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$elemMatch);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $elemMatch\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar size_exports = {};\n__export(size_exports, {\n $size: () => $size\n});\nmodule.exports = __toCommonJS(size_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $size = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$size);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $size\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar array_exports = {};\nmodule.exports = __toCommonJS(array_exports);\n__reExport(array_exports, require(\"./all\"), module.exports);\n__reExport(array_exports, require(\"./elemMatch\"), module.exports);\n__reExport(array_exports, require(\"./size\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./all\"),\n ...require(\"./elemMatch\"),\n ...require(\"./size\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n processBitwiseQuery: () => processBitwiseQuery\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../../../util\");\nvar import_predicates = require(\"../../_predicates\");\nconst processBitwiseQuery = (selector, value, predicate) => {\n return (0, import_predicates.processQuery)(\n selector,\n value,\n null,\n (value2, mask) => {\n let b = 0;\n if ((0, import_util.isArray)(mask)) {\n for (const n of mask) b = b | 1 << n;\n } else {\n b = mask;\n }\n return predicate(value2 & b, b);\n }\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n processBitwiseQuery\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitsAllClear_exports = {};\n__export(bitsAllClear_exports, {\n $bitsAllClear: () => $bitsAllClear\n});\nmodule.exports = __toCommonJS(bitsAllClear_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitsAllClear = (selector, value, _options) => (0, import_internal.processBitwiseQuery)(selector, value, (result, _) => result == 0);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAllClear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitsAllSet_exports = {};\n__export(bitsAllSet_exports, {\n $bitsAllSet: () => $bitsAllSet\n});\nmodule.exports = __toCommonJS(bitsAllSet_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitsAllSet = (selector, value, _options) => (0, import_internal.processBitwiseQuery)(selector, value, (result, mask) => result == mask);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAllSet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitsAnyClear_exports = {};\n__export(bitsAnyClear_exports, {\n $bitsAnyClear: () => $bitsAnyClear\n});\nmodule.exports = __toCommonJS(bitsAnyClear_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitsAnyClear = (selector, value, _options) => (0, import_internal.processBitwiseQuery)(selector, value, (result, mask) => result < mask);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAnyClear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitsAnySet_exports = {};\n__export(bitsAnySet_exports, {\n $bitsAnySet: () => $bitsAnySet\n});\nmodule.exports = __toCommonJS(bitsAnySet_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitsAnySet = (selector, value, _options) => (0, import_internal.processBitwiseQuery)(selector, value, (result, _) => result > 0);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAnySet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitwise_exports = {};\n__export(bitwise_exports, {\n $bitsAllClear: () => import_bitsAllClear.$bitsAllClear,\n $bitsAllSet: () => import_bitsAllSet.$bitsAllSet,\n $bitsAnyClear: () => import_bitsAnyClear.$bitsAnyClear,\n $bitsAnySet: () => import_bitsAnySet.$bitsAnySet\n});\nmodule.exports = __toCommonJS(bitwise_exports);\nvar import_bitsAllClear = require(\"./bitsAllClear\");\nvar import_bitsAllSet = require(\"./bitsAllSet\");\nvar import_bitsAnyClear = require(\"./bitsAnyClear\");\nvar import_bitsAnySet = require(\"./bitsAnySet\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAllClear,\n $bitsAllSet,\n $bitsAnyClear,\n $bitsAnySet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar eq_exports = {};\n__export(eq_exports, {\n $eq: () => $eq\n});\nmodule.exports = __toCommonJS(eq_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $eq = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$eq);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $eq\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar gt_exports = {};\n__export(gt_exports, {\n $gt: () => $gt\n});\nmodule.exports = __toCommonJS(gt_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $gt = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$gt);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $gt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar gte_exports = {};\n__export(gte_exports, {\n $gte: () => $gte\n});\nmodule.exports = __toCommonJS(gte_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $gte = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$gte);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $gte\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar in_exports = {};\n__export(in_exports, {\n $in: () => $in\n});\nmodule.exports = __toCommonJS(in_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $in = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$in);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $in\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lt_exports = {};\n__export(lt_exports, {\n $lt: () => $lt\n});\nmodule.exports = __toCommonJS(lt_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $lt = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$lt);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lte_exports = {};\n__export(lte_exports, {\n $lte: () => $lte\n});\nmodule.exports = __toCommonJS(lte_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $lte = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$lte);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lte\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ne_exports = {};\n__export(ne_exports, {\n $ne: () => $ne\n});\nmodule.exports = __toCommonJS(ne_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $ne = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$ne);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ne\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar nin_exports = {};\n__export(nin_exports, {\n $nin: () => $nin\n});\nmodule.exports = __toCommonJS(nin_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $nin = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$nin);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $nin\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar comparison_exports = {};\n__export(comparison_exports, {\n $eq: () => import_eq.$eq,\n $gt: () => import_gt.$gt,\n $gte: () => import_gte.$gte,\n $in: () => import_in.$in,\n $lt: () => import_lt.$lt,\n $lte: () => import_lte.$lte,\n $ne: () => import_ne.$ne,\n $nin: () => import_nin.$nin\n});\nmodule.exports = __toCommonJS(comparison_exports);\nvar import_eq = require(\"./eq\");\nvar import_gt = require(\"./gt\");\nvar import_gte = require(\"./gte\");\nvar import_in = require(\"./in\");\nvar import_lt = require(\"./lt\");\nvar import_lte = require(\"./lte\");\nvar import_ne = require(\"./ne\");\nvar import_nin = require(\"./nin\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $eq,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar exists_exports = {};\n__export(exists_exports, {\n $exists: () => $exists\n});\nmodule.exports = __toCommonJS(exists_exports);\nvar import_internal = require(\"../../../util/_internal\");\nconst $exists = (selector, value, _options) => {\n const nested = selector.includes(\".\");\n const b = !!value;\n if (!nested || selector.match(/\\.\\d+$/)) {\n const opts2 = { pathArray: selector.split(\".\") };\n return (o) => (0, import_internal.resolve)(o, selector, opts2) !== void 0 === b;\n }\n const parentSelector = selector.substring(0, selector.lastIndexOf(\".\"));\n const opts = { pathArray: parentSelector.split(\".\"), preserveIndex: true };\n return (o) => {\n const path = (0, import_internal.resolveGraph)(o, selector, opts);\n const val = (0, import_internal.resolve)(path, parentSelector, opts);\n return (0, import_internal.isArray)(val) ? val.some((v) => v !== void 0) === b : val !== void 0 === b;\n };\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $exists\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar type_exports = {};\n__export(type_exports, {\n $type: () => $type\n});\nmodule.exports = __toCommonJS(type_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $type = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$type);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $type\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar element_exports = {};\nmodule.exports = __toCommonJS(element_exports);\n__reExport(element_exports, require(\"./exists\"), module.exports);\n__reExport(element_exports, require(\"./type\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./exists\"),\n ...require(\"./type\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar expr_exports = {};\n__export(expr_exports, {\n $expr: () => $expr\n});\nmodule.exports = __toCommonJS(expr_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nfunction $expr(_, expr, options) {\n return (obj) => (0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, expr, options), options.useStrictMode);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $expr\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar jsonSchema_exports = {};\n__export(jsonSchema_exports, {\n $jsonSchema: () => $jsonSchema\n});\nmodule.exports = __toCommonJS(jsonSchema_exports);\nvar import_util = require(\"../../../util\");\nfunction $jsonSchema(_, schema, options) {\n (0, import_util.assert)(\n !!options?.jsonSchemaValidator,\n \"$jsonSchema requires 'jsonSchemaValidator' option to be defined.\"\n );\n const validate = options.jsonSchemaValidator(schema);\n return (obj) => validate(obj);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $jsonSchema\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mod_exports = {};\n__export(mod_exports, {\n $mod: () => $mod\n});\nmodule.exports = __toCommonJS(mod_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $mod = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$mod);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mod\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar regex_exports = {};\n__export(regex_exports, {\n $regex: () => $regex\n});\nmodule.exports = __toCommonJS(regex_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $regex = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$regex);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $regex\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar where_exports = {};\n__export(where_exports, {\n $where: () => $where\n});\nmodule.exports = __toCommonJS(where_exports);\nvar import_internal = require(\"../../../util/_internal\");\nfunction $where(_, rhs, opts) {\n (0, import_internal.assert)(\n opts.scriptEnabled,\n \"$where requires 'scriptEnabled' option to be true\"\n );\n const f = rhs;\n (0, import_internal.assert)((0, import_internal.isFunction)(f), \"$where only accepts a Function objects\");\n return (obj) => (0, import_internal.truthy)(f.call(obj), opts?.useStrictMode);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $where\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar evaluation_exports = {};\nmodule.exports = __toCommonJS(evaluation_exports);\n__reExport(evaluation_exports, require(\"./expr\"), module.exports);\n__reExport(evaluation_exports, require(\"./jsonSchema\"), module.exports);\n__reExport(evaluation_exports, require(\"./mod\"), module.exports);\n__reExport(evaluation_exports, require(\"./regex\"), module.exports);\n__reExport(evaluation_exports, require(\"./where\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./expr\"),\n ...require(\"./jsonSchema\"),\n ...require(\"./mod\"),\n ...require(\"./regex\"),\n ...require(\"./where\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar and_exports = {};\n__export(and_exports, {\n $and: () => $and\n});\nmodule.exports = __toCommonJS(and_exports);\nvar import_query = require(\"../../../query\");\nvar import_util = require(\"../../../util\");\nconst $and = (_, rhs, options) => {\n (0, import_util.assert)((0, import_util.isArray)(rhs), \"$and expects value to be an Array.\");\n const queries = rhs.map((expr) => new import_query.Query(expr, options));\n return (obj) => queries.every((q) => q.test(obj));\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $and\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar or_exports = {};\n__export(or_exports, {\n $or: () => $or\n});\nmodule.exports = __toCommonJS(or_exports);\nvar import_query = require(\"../../../query\");\nvar import_util = require(\"../../../util\");\nfunction $or(_, rhs, options) {\n (0, import_util.assert)((0, import_util.isArray)(rhs), \"Invalid expression. $or expects value to be an Array\");\n const queries = rhs.map((expr) => new import_query.Query(expr, options));\n return (obj) => queries.some((q) => q.test(obj));\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $or\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar nor_exports = {};\n__export(nor_exports, {\n $nor: () => $nor\n});\nmodule.exports = __toCommonJS(nor_exports);\nvar import_util = require(\"../../../util\");\nvar import_or = require(\"./or\");\nfunction $nor(_, rhs, options) {\n (0, import_util.assert)(\n (0, import_util.isArray)(rhs),\n \"Invalid expression. $nor expects value to be an array.\"\n );\n const f = (0, import_or.$or)(\"$or\", rhs, options);\n return (obj) => !f(obj);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $nor\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar not_exports = {};\n__export(not_exports, {\n $not: () => $not\n});\nmodule.exports = __toCommonJS(not_exports);\nvar import_query = require(\"../../../query\");\nvar import_util = require(\"../../../util\");\nfunction $not(selector, rhs, options) {\n const criteria = {};\n criteria[selector] = (0, import_util.normalize)(rhs);\n const query = new import_query.Query(criteria, options);\n return (obj) => !query.test(obj);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $not\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar logical_exports = {};\nmodule.exports = __toCommonJS(logical_exports);\n__reExport(logical_exports, require(\"./and\"), module.exports);\n__reExport(logical_exports, require(\"./nor\"), module.exports);\n__reExport(logical_exports, require(\"./not\"), module.exports);\n__reExport(logical_exports, require(\"./or\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./and\"),\n ...require(\"./nor\"),\n ...require(\"./not\"),\n ...require(\"./or\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar query_exports = {};\nmodule.exports = __toCommonJS(query_exports);\n__reExport(query_exports, require(\"./array\"), module.exports);\n__reExport(query_exports, require(\"./bitwise\"), module.exports);\n__reExport(query_exports, require(\"./comparison\"), module.exports);\n__reExport(query_exports, require(\"./element\"), module.exports);\n__reExport(query_exports, require(\"./evaluation\"), module.exports);\n__reExport(query_exports, require(\"./logical\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./array\"),\n ...require(\"./bitwise\"),\n ...require(\"./comparison\"),\n ...require(\"./element\"),\n ...require(\"./evaluation\"),\n ...require(\"./logical\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar denseRank_exports = {};\n__export(denseRank_exports, {\n $denseRank: () => $denseRank\n});\nmodule.exports = __toCommonJS(denseRank_exports);\nvar import_internal = require(\"./_internal\");\nconst $denseRank = (obj, coll, expr, options) => (0, import_internal.rank)(\n obj,\n coll,\n expr,\n options,\n true\n /*dense*/\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $denseRank\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar derivative_exports = {};\n__export(derivative_exports, {\n $derivative: () => $derivative\n});\nmodule.exports = __toCommonJS(derivative_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"../expression/date/_internal\");\nconst $derivative = (_, coll, expr, options) => {\n if (coll.length < 2) return null;\n const { input, unit } = expr.inputExpr;\n const sortKey = \"$\" + Object.keys(expr.parentExpr.sortBy)[0];\n const values = [coll[0], coll[coll.length - 1]];\n const points = (0, import_push.$push)(values, [sortKey, input], options).filter(\n (([x, y]) => (0, import_util.isNumber)(+x) && (0, import_util.isNumber)(+y))\n );\n (0, import_util.assert)(points.length === 2, \"$derivative arguments must resolve to numeric\");\n const [[x1, y1], [x2, y2]] = points;\n const deltaX = (x2 - x1) / import_internal.TIMEUNIT_IN_MILLIS[unit ?? \"millisecond\"];\n return (y2 - y1) / deltaX;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $derivative\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar documentNumber_exports = {};\n__export(documentNumber_exports, {\n $documentNumber: () => $documentNumber\n});\nmodule.exports = __toCommonJS(documentNumber_exports);\nconst $documentNumber = (_obj, _coll, expr, _options) => expr.documentNumber;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $documentNumber\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar expMovingAvg_exports = {};\n__export(expMovingAvg_exports, {\n $expMovingAvg: () => $expMovingAvg\n});\nmodule.exports = __toCommonJS(expMovingAvg_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"./_internal\");\nconst $expMovingAvg = (_, coll, expr, options) => {\n const { input, N, alpha } = expr.inputExpr;\n (0, import_util.assert)(\n !(N && alpha),\n `$expMovingAvg: must provide either 'N' or 'alpha' field.`\n );\n (0, import_util.assert)(\n !N || (0, import_util.isNumber)(N) && N > 0,\n `$expMovingAvg: 'N' must be greater than zero. Got ${N}.`\n );\n (0, import_util.assert)(\n !alpha || (0, import_util.isNumber)(alpha) && alpha > 0 && alpha < 1,\n `$expMovingAvg: 'alpha' must be between 0 and 1 (exclusive), found alpha: ${alpha}`\n );\n return (0, import_internal.withMemo)(\n coll,\n expr,\n () => {\n const weight = N != void 0 ? 2 / (N + 1) : alpha;\n const values = (0, import_push.$push)(coll, input, options);\n for (let i = 0; i < values.length; i++) {\n if (i === 0) {\n if (!(0, import_util.isNumber)(values[i])) values[i] = null;\n continue;\n }\n if (!(0, import_util.isNumber)(values[i])) {\n values[i] = values[i - 1];\n continue;\n }\n if (!(0, import_util.isNumber)(values[i - 1])) continue;\n values[i] = values[i] * weight + values[i - 1] * (1 - weight);\n }\n return values;\n },\n (series) => series[expr.documentNumber - 1]\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $expMovingAvg\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar integral_exports = {};\n__export(integral_exports, {\n $integral: () => $integral\n});\nmodule.exports = __toCommonJS(integral_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"../expression/date/_internal\");\nconst $integral = (_, coll, expr, options) => {\n const { input, unit } = expr.inputExpr;\n const sortKey = \"$\" + Object.keys(expr.parentExpr.sortBy)[0];\n const points = (0, import_push.$push)(coll, [sortKey, input], options).filter(\n (([x, y]) => (0, import_util.isNumber)(+x) && (0, import_util.isNumber)(+y))\n );\n const size = points.length;\n (0, import_util.assert)(coll.length === size, \"$integral expects an array of numeric values\");\n let result = 0;\n for (let k = 1; k < size; k++) {\n const [x1, y1] = points[k - 1];\n const [x2, y2] = points[k];\n const deltaX = (x2 - x1) / import_internal.TIMEUNIT_IN_MILLIS[unit ?? \"millisecond\"];\n result += 0.5 * (y1 + y2) * deltaX;\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $integral\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar minMaxScaler_exports = {};\n__export(minMaxScaler_exports, {\n $minMaxScaler: () => $minMaxScaler\n});\nmodule.exports = __toCommonJS(minMaxScaler_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"./_internal\");\nconst $minMaxScaler = (_, coll, expr, options) => {\n return (0, import_internal.withMemo)(\n coll,\n expr,\n () => {\n const args = expr.inputExpr;\n const min = args.min || 0;\n const max = args.max || 1;\n const nums = (0, import_push.$push)(\n coll,\n args.input || expr.inputExpr,\n options\n );\n (0, import_util.assert)(\n (0, import_util.isArray)(nums) && nums.length > 0 && nums.every(import_util.isNumber),\n \"$minMaxScaler: input must be a numeric array\"\n );\n let rmin = nums[0];\n let rmax = nums[0];\n for (const n of nums) {\n if (n < rmin) rmin = n;\n else if (n > rmax) rmax = n;\n }\n const scale = max - min;\n const range = rmax - rmin;\n (0, import_util.assert)(range !== 0, \"$minMaxScaler: input range must not be zero\");\n return {\n min,\n scale,\n rmin,\n range,\n nums\n };\n },\n (data) => {\n const { min, rmin, scale, range, nums } = data;\n return (nums[expr.documentNumber - 1] - rmin) / range * scale + min;\n }\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $minMaxScaler\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar rank_exports = {};\n__export(rank_exports, {\n $rank: () => $rank\n});\nmodule.exports = __toCommonJS(rank_exports);\nvar import_internal = require(\"./_internal\");\nconst $rank = (obj, coll, expr, options) => (0, import_internal.rank)(\n obj,\n coll,\n expr,\n options,\n false\n /*dense*/\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $rank\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar shift_exports = {};\n__export(shift_exports, {\n $shift: () => $shift\n});\nmodule.exports = __toCommonJS(shift_exports);\nvar import_internal = require(\"../../core/_internal\");\nconst $shift = (obj, coll, expr, options) => {\n const input = expr.inputExpr;\n const shiftedIndex = expr.documentNumber - 1 + input.by;\n if (shiftedIndex < 0 || shiftedIndex > coll.length - 1) {\n return (0, import_internal.evalExpr)(obj, input.default, options) ?? null;\n }\n return (0, import_internal.evalExpr)(coll[shiftedIndex], input.output, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $shift\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar window_exports = {};\nmodule.exports = __toCommonJS(window_exports);\n__reExport(window_exports, require(\"./denseRank\"), module.exports);\n__reExport(window_exports, require(\"./derivative\"), module.exports);\n__reExport(window_exports, require(\"./documentNumber\"), module.exports);\n__reExport(window_exports, require(\"./expMovingAvg\"), module.exports);\n__reExport(window_exports, require(\"./integral\"), module.exports);\n__reExport(window_exports, require(\"./linearFill\"), module.exports);\n__reExport(window_exports, require(\"./locf\"), module.exports);\n__reExport(window_exports, require(\"./minMaxScaler\"), module.exports);\n__reExport(window_exports, require(\"./rank\"), module.exports);\n__reExport(window_exports, require(\"./shift\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./denseRank\"),\n ...require(\"./derivative\"),\n ...require(\"./documentNumber\"),\n ...require(\"./expMovingAvg\"),\n ...require(\"./integral\"),\n ...require(\"./linearFill\"),\n ...require(\"./locf\"),\n ...require(\"./minMaxScaler\"),\n ...require(\"./rank\"),\n ...require(\"./shift\")\n});\n", "var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n DEFAULT_OPTIONS: () => DEFAULT_OPTIONS,\n applyUpdate: () => applyUpdate,\n buildParams: () => buildParams,\n clone: () => clone,\n walkExpression: () => walkExpression\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar booleanOperators = __toESM(require(\"../../operators/expression/boolean\"));\nvar comparisonOperators = __toESM(require(\"../../operators/expression/comparison\"));\nvar queryOperators = __toESM(require(\"../../operators/query\"));\nvar import_query = require(\"../../query\");\nvar import_internal2 = require(\"../../util/_internal\");\nconst DEFAULT_OPTIONS = import_internal.ComputeOptions.init({\n context: import_internal.Context.init().addQueryOps(queryOperators).addExpressionOps(booleanOperators).addExpressionOps(comparisonOperators)\n}).update({ updateConfig: { cloneMode: \"copy\" } });\nconst clone = (val, opts) => {\n const mode = opts?.local?.updateConfig?.cloneMode;\n switch (mode) {\n case \"deep\":\n return (0, import_internal2.cloneDeep)(val);\n case \"copy\": {\n if ((0, import_internal2.isDate)(val)) return new Date(val);\n if ((0, import_internal2.isArray)(val)) return val.slice();\n if ((0, import_internal2.isObject)(val)) return Object.assign({}, val);\n if ((0, import_internal2.isRegExp)(val)) return new RegExp(val);\n return val;\n }\n }\n return val;\n};\nconst FIRST_ONLY = \"$\";\nconst ARRAY_WIDE = \"$[]\";\nconst applyUpdate = (o, n, q, f, opts) => {\n const { selector, position: c, next } = n;\n if (!c) {\n let b = false;\n const g = (u, k) => b = Boolean(f(u, k)) || b;\n (0, import_internal2.walk)(o, selector, g, opts);\n return b;\n }\n const arr = (0, import_internal2.resolve)(o, selector);\n if (!(0, import_internal2.isArray)(arr) || !arr.length) return false;\n if (c === FIRST_ONLY) {\n const i = arr.findIndex((e) => q[selector].test({ [selector]: [e] }));\n (0, import_internal2.assert)(i > -1, \"BUG: positional operator found no match for \" + selector);\n return next ? applyUpdate(arr[i], next, q, f, opts) : f(arr, i);\n }\n return arr.map((e, i) => {\n if (c !== ARRAY_WIDE && q[c] && !q[c].test({ [c]: [e] })) return false;\n return next ? applyUpdate(e, next, q, f, opts) : f(arr, i);\n }).some((v) => !!v);\n};\nconst ERR_MISSING_FIELD = \"You must include the array field for '.$' as part of the query document.\";\nconst ERR_IMMUTABLE_FIELD = (path, idKey) => `Performing an update on the path '${path}' would modify the immutable field '${idKey}'.`;\nfunction walkExpression(expr, arrayFilters, options, callback) {\n const opts = options;\n const params = opts.local.updateParams ?? buildParams([expr], arrayFilters, opts);\n const modified = [];\n for (const key of Object.keys(expr)) {\n const { node, queries } = params[key];\n if (callback(expr[key], node, queries)) modified.push(node.selector);\n }\n return modified.sort();\n}\nfunction buildParams(exprList, arrayFilters, options) {\n const params = {};\n arrayFilters ||= [];\n const filterIndexMap = arrayFilters.reduce(\n (res, filter) => {\n for (const k of Object.keys(filter)) {\n const parent = k.split(\".\")[0];\n if (res[parent]) {\n res[parent][k] = filter[k];\n } else {\n res[parent] = { [k]: filter[k] };\n }\n }\n return res;\n },\n {}\n );\n let { condition } = options.local;\n condition = condition ?? {};\n const queryKeys = Object.keys(condition);\n const conflictDetector = new import_internal2.PathValidator();\n for (const expr of exprList) {\n for (const selector of Object.keys(expr)) {\n const identifiers = [];\n const node = selector.includes(\"$\") ? { selector: \"\" } : { selector };\n if (!node.selector) {\n selector.split(\".\").reduce((n, v) => {\n if (v === FIRST_ONLY || v === ARRAY_WIDE) {\n n.position = v;\n } else if (v.startsWith(\"$[\") && v.endsWith(\"]\")) {\n const id = v.slice(2, -1);\n (0, import_internal2.assert)(\n /^[a-z]+\\w*$/.test(id),\n `The filter must begin with a lowercase letter and contain only alphanumeric characters. '${v}' is invalid.`\n );\n identifiers.push(id);\n n.position = id;\n } else if (!n.selector) {\n n.selector = v;\n } else if (!n.position) {\n n.selector += \".\" + v;\n } else {\n n.next = { selector: v };\n return n.next;\n }\n return n;\n }, node);\n }\n const queries = {};\n if (identifiers.length) {\n const filters = {};\n for (const v of identifiers) filters[v] = filterIndexMap[v];\n for (const k of Object.keys(filters)) {\n queries[k] = new import_query.Query(filters[k], options);\n }\n }\n if (node.position === FIRST_ONLY) {\n const field = node.selector;\n (0, import_internal2.assert)(queryKeys && queryKeys.length, ERR_MISSING_FIELD);\n const matches = queryKeys.filter(\n (k2) => k2 === field || k2.startsWith(field + \".\")\n );\n (0, import_internal2.assert)(matches.length === 1, ERR_MISSING_FIELD);\n const k = matches[0];\n queries[field] = new import_query.Query({ [k]: condition[k] }, options);\n }\n const idKey = options.idKey;\n (0, import_internal2.assert)(\n node.selector !== idKey && !node.selector.startsWith(`${idKey}.`),\n ERR_IMMUTABLE_FIELD(node.selector, idKey)\n );\n (0, import_internal2.assert)(\n conflictDetector.add(node.selector),\n `updating the path '${node.selector}' would create a conflict at '${node.selector}'`\n );\n params[selector] = { node, queries };\n }\n }\n return params;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n DEFAULT_OPTIONS,\n applyUpdate,\n buildParams,\n clone,\n walkExpression\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar addToSet_exports = {};\n__export(addToSet_exports, {\n $addToSet: () => $addToSet\n});\nmodule.exports = __toCommonJS(addToSet_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $addToSet(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n const args = { $each: [val] };\n if ((0, import_util.isObject)(val) && (0, import_util.has)(val, \"$each\")) {\n Object.assign(args, val);\n }\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n const prev = o[k];\n if ((0, import_util.isArray)(prev)) {\n const set = (0, import_util.unique)(prev.concat(args.$each));\n if (set.length === prev.length) return false;\n o[k] = (0, import_internal.clone)(set, options);\n } else if (prev === void 0) {\n o[k] = (0, import_internal.clone)(args.$each, options);\n } else {\n return false;\n }\n return true;\n },\n { buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $addToSet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bit_exports = {};\n__export(bit_exports, {\n $bit: () => $bit\n});\nmodule.exports = __toCommonJS(bit_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nconst BIT_OPS = [\"and\", \"or\", \"xor\"];\nfunction $bit(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n for (const vals of Object.values(expr)) {\n (0, import_util.assert)((0, import_util.isObject)(vals), `$bit operator expression must be an object.`);\n const op = Object.keys(vals);\n (0, import_util.assert)(\n op.length === 1 && BIT_OPS.includes(op[0]),\n `$bit spec is invalid '${op[0]}'. Must be one of 'and', 'or', or 'xor'.`\n );\n (0, import_util.assert)(\n (0, import_util.isNumber)(vals[op[0]]),\n `$bit expression value must be a number. Got ${typeof vals[op[0]]}`\n );\n }\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n const op = Object.keys(val);\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n let n = o[k];\n const v = val[op[0]];\n if (n !== void 0 && !((0, import_util.isNumber)(n) && (0, import_util.isNumber)(v))) return false;\n n = n || 0;\n switch (op[0]) {\n case \"and\":\n return (o[k] = n & v) !== n;\n case \"or\":\n return (o[k] = n | v) !== n;\n case \"xor\":\n return (o[k] = n ^ v) !== n;\n }\n },\n { buildGraph: true }\n );\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bit\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar currentDate_exports = {};\n__export(currentDate_exports, {\n $currentDate: () => $currentDate\n});\nmodule.exports = __toCommonJS(currentDate_exports);\nvar import_internal = require(\"./_internal\");\nfunction $currentDate(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n o[k] = val === true || val.$type === \"date\" ? options.now : options.now.getTime();\n return true;\n },\n { buildGraph: true }\n );\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $currentDate\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar inc_exports = {};\n__export(inc_exports, {\n $inc: () => $inc\n});\nmodule.exports = __toCommonJS(inc_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $inc(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n if ((0, import_util.isNumber)(o[k]) || o[k] === void 0) {\n o[k] ||= 0;\n o[k] += val;\n return true;\n }\n return false;\n },\n { buildGraph: true }\n );\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $inc\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar max_exports = {};\n__export(max_exports, {\n $max: () => $max\n});\nmodule.exports = __toCommonJS(max_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $max(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n if ((0, import_util.compare)(o[k], val) > -1) return false;\n o[k] = val;\n return true;\n },\n { buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $max\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar min_exports = {};\n__export(min_exports, {\n $min: () => $min\n});\nmodule.exports = __toCommonJS(min_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $min(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n if ((0, import_util.compare)(o[k], val) < 1) return false;\n o[k] = val;\n return true;\n },\n { buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $min\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mul_exports = {};\n__export(mul_exports, {\n $mul: () => $mul\n});\nmodule.exports = __toCommonJS(mul_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $mul(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n const prev = o[k];\n if ((0, import_util.isNumber)(o[k])) o[k] = o[k] * val;\n else if (o[k] === void 0) o[k] = 0;\n return o[k] !== prev;\n },\n { buildGraph: true }\n );\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mul\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pop_exports = {};\n__export(pop_exports, {\n $pop: () => $pop\n});\nmodule.exports = __toCommonJS(pop_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $pop(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => {\n const arr = o[k];\n if (!(0, import_util.isArray)(arr) || !arr.length) return false;\n if (val === -1) arr.splice(0, 1);\n else arr.pop();\n return true;\n });\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $pop\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pull_exports = {};\n__export(pull_exports, {\n $pull: () => $pull\n});\nmodule.exports = __toCommonJS(pull_exports);\nvar import_query = require(\"../../query\");\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $pull(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n const wrap = !(0, import_util.isObject)(val) || Object.keys(val).some(import_util.isOperator);\n const query = new import_query.Query(wrap ? { k: val } : val, options);\n const pred = wrap ? (v) => query.test({ k: v }) : (v) => query.test(v);\n return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => {\n const prev = o[k];\n if (!(0, import_util.isArray)(prev) || !prev.length) return false;\n const curr = new Array();\n let ok = false;\n for (const v of prev) {\n const b = pred(v);\n if (!b) curr.push(v);\n ok ||= b;\n }\n if (!ok) return false;\n o[k] = curr;\n return true;\n });\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $pull\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pullAll_exports = {};\n__export(pullAll_exports, {\n $pullAll: () => $pullAll\n});\nmodule.exports = __toCommonJS(pullAll_exports);\nvar import_internal = require(\"./_internal\");\nvar import_pull = require(\"./pull\");\nfunction $pullAll(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n const pullExpr = {};\n for (const k of Object.keys(expr)) {\n pullExpr[k] = { $in: expr[k] };\n }\n return (0, import_pull.$pull)(pullExpr, arrayFilters, options);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $pullAll\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar push_exports = {};\n__export(push_exports, {\n $push: () => $push\n});\nmodule.exports = __toCommonJS(push_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nconst MODIFIERS = [\"$each\", \"$slice\", \"$sort\", \"$position\"];\nfunction $push(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n const args = {\n $each: [val]\n };\n if ((0, import_util.isObject)(val) && MODIFIERS.some((m) => (0, import_util.has)(val, m))) {\n Object.assign(args, val);\n }\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n const arr = o[k];\n if (!(0, import_util.isArray)(arr)) {\n if (arr === void 0) {\n o[k] = (0, import_internal.clone)(args.$each, options);\n return true;\n }\n return false;\n }\n const prev = arr.slice(0, args.$slice || arr.length);\n const oldsize = arr.length;\n const pos = (0, import_util.isNumber)(args.$position) ? args.$position : arr.length;\n arr.splice(pos, 0, ...(0, import_internal.clone)(args.$each, options));\n if (args.$sort) {\n const sortKey = (0, import_util.isObject)(args.$sort) ? Object.keys(args.$sort)[0] : \"\";\n const order = !sortKey ? args.$sort : args.$sort[sortKey];\n const f = !sortKey ? (a) => a : (a) => (0, import_util.resolve)(a, sortKey);\n arr.sort((a, b) => order * (0, import_util.compare)(f(a), f(b)));\n }\n if ((0, import_util.isNumber)(args.$slice)) {\n if (args.$slice < 0) arr.splice(0, arr.length + args.$slice);\n else arr.splice(args.$slice);\n }\n return oldsize != arr.length || !(0, import_util.isEqual)(prev, arr);\n },\n { descendArray: true, buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $push\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar set_exports = {};\n__export(set_exports, {\n $set: () => $set\n});\nmodule.exports = __toCommonJS(set_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $set(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n if ((0, import_util.isEqual)(o[k], val)) return false;\n o[k] = (0, import_internal.clone)(val, options);\n return true;\n },\n { buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $set\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar rename_exports = {};\n__export(rename_exports, {\n $rename: () => $rename\n});\nmodule.exports = __toCommonJS(rename_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nvar import_set = require(\"./set\");\nconst isIdPath = (path, idKey) => path === idKey || path.startsWith(`${idKey}.`);\nfunction $rename(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n const idKey = options.idKey;\n for (const target of Object.values(expr)) {\n (0, import_util.assert)(\n !isIdPath(target, idKey),\n `Performing an update on the path '${target}' would modify the immutable field '${idKey}'.`\n );\n }\n return (obj) => {\n const res = [];\n const changed = (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => {\n if (!(0, import_util.has)(o, k)) return false;\n Array.prototype.push.apply(\n res,\n (0, import_set.$set)({ [val]: o[k] }, arrayFilters, options)(obj)\n );\n delete o[k];\n return true;\n });\n }\n );\n return Array.from(new Set(changed.concat(res)));\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $rename\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unset_exports = {};\n__export(unset_exports, {\n $unset: () => $unset\n});\nmodule.exports = __toCommonJS(unset_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $unset(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (_, node, queries) => {\n return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => {\n if (!(0, import_util.has)(o, k)) return false;\n const prev = o[k];\n if ((0, import_util.isArray)(o)) o[k] = null;\n else delete o[k];\n return !(0, import_util.isEqual)(prev, o[k]);\n });\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unset\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar update_exports = {};\nmodule.exports = __toCommonJS(update_exports);\n__reExport(update_exports, require(\"./addToSet\"), module.exports);\n__reExport(update_exports, require(\"./bit\"), module.exports);\n__reExport(update_exports, require(\"./currentDate\"), module.exports);\n__reExport(update_exports, require(\"./inc\"), module.exports);\n__reExport(update_exports, require(\"./max\"), module.exports);\n__reExport(update_exports, require(\"./min\"), module.exports);\n__reExport(update_exports, require(\"./mul\"), module.exports);\n__reExport(update_exports, require(\"./pop\"), module.exports);\n__reExport(update_exports, require(\"./pull\"), module.exports);\n__reExport(update_exports, require(\"./pullAll\"), module.exports);\n__reExport(update_exports, require(\"./push\"), module.exports);\n__reExport(update_exports, require(\"./rename\"), module.exports);\n__reExport(update_exports, require(\"./set\"), module.exports);\n__reExport(update_exports, require(\"./unset\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./addToSet\"),\n ...require(\"./bit\"),\n ...require(\"./currentDate\"),\n ...require(\"./inc\"),\n ...require(\"./max\"),\n ...require(\"./min\"),\n ...require(\"./mul\"),\n ...require(\"./pop\"),\n ...require(\"./pull\"),\n ...require(\"./pullAll\"),\n ...require(\"./push\"),\n ...require(\"./rename\"),\n ...require(\"./set\"),\n ...require(\"./unset\")\n});\n", "var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar updater_exports = {};\n__export(updater_exports, {\n update: () => update,\n updateMany: () => updateMany,\n updateOne: () => updateOne\n});\nmodule.exports = __toCommonJS(updater_exports);\nvar import_internal = require(\"./core/_internal\");\nvar import_lazy = require(\"./lazy\");\nvar booleanOperators = __toESM(require(\"./operators/expression/boolean\"));\nvar comparisonOperators = __toESM(require(\"./operators/expression/comparison\"));\nvar import_addFields = require(\"./operators/pipeline/addFields\");\nvar import_project = require(\"./operators/pipeline/project\");\nvar import_replaceRoot = require(\"./operators/pipeline/replaceRoot\");\nvar import_replaceWith = require(\"./operators/pipeline/replaceWith\");\nvar import_set = require(\"./operators/pipeline/set\");\nvar import_sort = require(\"./operators/pipeline/sort\");\nvar import_unset = require(\"./operators/pipeline/unset\");\nvar queryOperators = __toESM(require(\"./operators/query\"));\nvar updateOperators = __toESM(require(\"./operators/update\"));\nvar import_internal2 = require(\"./operators/update/_internal\");\nvar import_query = require(\"./query\");\nvar import_internal3 = require(\"./util/_internal\");\nconst UPDATE_OPERATORS = updateOperators;\nconst PIPELINE_OPERATORS = {\n $addFields: import_addFields.$addFields,\n $set: import_set.$set,\n $project: import_project.$project,\n $unset: import_unset.$unset,\n $replaceRoot: import_replaceRoot.$replaceRoot,\n $replaceWith: import_replaceWith.$replaceWith\n};\nfunction update(obj, modifier, arrayFilters, condition, options) {\n const docs = [obj];\n const res = updateOne(\n docs,\n condition || {},\n modifier,\n { arrayFilters, cloneMode: options?.cloneMode ?? \"copy\" },\n options?.queryOptions\n );\n return res.modifiedFields ?? [];\n}\nfunction updateMany(documents, condition, modifier, updateConfig = {}, options) {\n const { modifiedCount, matchedCount } = updateDocuments(\n documents,\n condition,\n modifier,\n updateConfig,\n options\n );\n return { modifiedCount, matchedCount };\n}\nfunction updateOne(documents, condition, modifier, updateConfig = {}, options) {\n return updateDocuments(documents, condition, modifier, updateConfig, {\n ...options,\n firstOnly: true\n });\n}\nfunction updateDocuments(documents, condition, modifier, updateConfig = {}, options) {\n options ||= {};\n const firstOnly = options?.firstOnly ?? false;\n const opts = import_internal.ComputeOptions.init({\n ...options,\n collation: Object.assign({}, options?.collation, updateConfig?.collation)\n }).update({\n condition,\n updateConfig: { cloneMode: \"copy\", ...updateConfig },\n variables: updateConfig.let,\n updateParams: {}\n });\n opts.context.addExpressionOps(booleanOperators).addExpressionOps(comparisonOperators).addQueryOps(queryOperators).addPipelineOps(PIPELINE_OPERATORS);\n const filterExists = Object.keys(condition).length > 0;\n const matchedDocs = /* @__PURE__ */ new Map();\n let docsIter = (0, import_lazy.Lazy)(documents);\n if (filterExists) {\n const query = new import_query.Query(condition, opts);\n docsIter = docsIter.filter((o, i) => {\n if (query.test(o)) {\n matchedDocs.set(o, i);\n return true;\n }\n return false;\n });\n }\n let modifiedIndex = -1;\n if (firstOnly) {\n const indexes = /* @__PURE__ */ new Map();\n if (updateConfig.sort) {\n if (!filterExists) {\n docsIter = docsIter.map((o, i) => {\n indexes.set(o, i);\n return o;\n });\n }\n docsIter = (0, import_sort.$sort)(docsIter, updateConfig.sort, opts);\n }\n docsIter = docsIter.take(1);\n const firstDoc = docsIter.collect()[0];\n modifiedIndex = matchedDocs.get(firstDoc) ?? indexes.get(firstDoc) ?? 0;\n }\n const foundDocs = docsIter.collect();\n if (foundDocs.length === 0) return { matchedCount: 0, modifiedCount: 0 };\n if ((0, import_internal3.isArray)(modifier)) {\n const indexes = firstOnly ? [modifiedIndex] : Array.from(matchedDocs.values());\n const hashes = indexes.length ? indexes.map((i) => (0, import_internal3.hashCode)(documents[i])) : foundDocs.map((o) => (0, import_internal3.hashCode)(o));\n const output2 = { matchedCount: hashes.length, modifiedCount: 0 };\n const oldFirstDoc = firstOnly ? (0, import_internal3.cloneDeep)(documents[indexes[0]]) : void 0;\n let updateIter = (0, import_lazy.Lazy)(foundDocs);\n for (const stage of modifier) {\n const [op, expr] = Object.entries(stage)[0];\n const pipelineOp = PIPELINE_OPERATORS[op];\n (0, import_internal3.assert)(pipelineOp, `Unknown pipeline operator: '${op}'.`);\n updateIter = pipelineOp(updateIter, expr, opts);\n }\n const matches = updateIter.collect();\n if (indexes.length) {\n (0, import_internal3.assert)(\n indexes.length === matches.length,\n \"bug: indexes and result size must match.\"\n );\n for (let i = 0; i < indexes.length; i++) {\n if ((0, import_internal3.hashCode)(matches[i]) !== hashes[i]) {\n documents[indexes[i]] = matches[i];\n output2.modifiedCount++;\n }\n }\n } else {\n for (let i = 0; i < documents.length; i++) {\n if ((0, import_internal3.hashCode)(matches[i]) !== hashes[i]) {\n documents[i] = matches[i];\n output2.modifiedCount++;\n }\n }\n }\n if (firstOnly && output2.modifiedCount && oldFirstDoc) {\n const newDoc = documents[indexes[0]];\n const modifiedFields2 = getModifiedFields(\n modifier,\n oldFirstDoc,\n newDoc\n );\n (0, import_internal3.assert)(modifiedFields2.length, \"bug: failed to retrieve modified fields\");\n Object.assign(output2, { modifiedFields: modifiedFields2, modifiedIndex });\n }\n return output2;\n }\n const unknownOp = Object.keys(modifier).find((op) => !UPDATE_OPERATORS[op]);\n (0, import_internal3.assert)(!unknownOp, `Unknown update operator: '${unknownOp}'.`);\n const arrayFilters = updateConfig?.arrayFilters ?? [];\n opts.update({\n updateParams: (0, import_internal2.buildParams)(\n Object.values(modifier),\n arrayFilters,\n opts\n )\n });\n const matchedCount = foundDocs.length;\n const output = { matchedCount, modifiedCount: 0 };\n const modifiedFields = [];\n const fns = [];\n for (const op of Object.keys(modifier)) {\n const fn = UPDATE_OPERATORS[op];\n const expr = modifier[op];\n fns.push(fn(expr, arrayFilters, opts));\n }\n for (const doc of foundDocs) {\n let modified = false;\n for (const mutate of fns) {\n const fields = mutate(doc);\n if (fields.length) {\n modified = true;\n if (firstOnly) Array.prototype.push.apply(modifiedFields, fields);\n }\n }\n output.modifiedCount += +modified;\n }\n if (firstOnly && modifiedFields.length) {\n modifiedFields.sort();\n Object.assign(output, { modifiedFields, modifiedIndex });\n }\n return output;\n}\nfunction getModifiedFields(pipeline, oldDoc, newDoc) {\n const stageFields = [];\n for (const stage of pipeline) {\n const op = Object.keys(stage)[0];\n const expr = stage[op];\n switch (op) {\n case \"$addFields\":\n case \"$set\":\n case \"$project\":\n case \"$replaceWith\":\n stageFields.push(...Object.keys(expr));\n break;\n case \"$unset\":\n stageFields.push(...(0, import_internal3.ensureArray)(expr));\n break;\n case \"$replaceRoot\":\n stageFields.length = 0;\n stageFields.push(\n ...Object.keys(expr?.newRoot)\n );\n break;\n }\n }\n const stageFieldsSet = new Set(stageFields.sort());\n const pathValidator = new import_internal3.PathValidator();\n const modifiedFields = [];\n for (const key of stageFieldsSet) {\n if (pathValidator.add(key) && !(0, import_internal3.isEqual)((0, import_internal3.resolve)(newDoc, key), (0, import_internal3.resolve)(oldDoc, key))) {\n modifiedFields.push(key);\n }\n }\n for (const key of Object.keys(oldDoc)) {\n if (stageFieldsSet.has(key)) continue;\n if (!pathValidator.add(key) || !(0, import_internal3.isEqual)(newDoc[key], oldDoc[key])) {\n modifiedFields.push(key);\n }\n }\n const topLevelValidator = new import_internal3.PathValidator();\n return modifiedFields.sort().filter((key) => topLevelValidator.add(key));\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n update,\n updateMany,\n updateOne\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar core_exports = {};\n__export(core_exports, {\n Context: () => import_internal.Context,\n OpType: () => import_internal.OpType,\n ProcessingMode: () => import_internal.ProcessingMode,\n computeValue: () => import_internal.computeValue,\n evalExpr: () => import_internal.evalExpr\n});\nmodule.exports = __toCommonJS(core_exports);\nvar import_internal = require(\"./_internal\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Context,\n OpType,\n ProcessingMode,\n computeValue,\n evalExpr\n});\n", "var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar index_exports = {};\n__export(index_exports, {\n Aggregator: () => Aggregator,\n Context: () => import_core.Context,\n ProcessingMode: () => import_core.ProcessingMode,\n Query: () => Query,\n aggregate: () => aggregate,\n default: () => index_default,\n find: () => find,\n update: () => update,\n updateMany: () => updateMany,\n updateOne: () => updateOne\n});\nmodule.exports = __toCommonJS(index_exports);\nvar import_aggregator = require(\"./aggregator\");\nvar import_internal = require(\"./core/_internal\");\nvar accumulatorOperators = __toESM(require(\"./operators/accumulator\"));\nvar expressionOperators = __toESM(require(\"./operators/expression\"));\nvar pipelineOperators = __toESM(require(\"./operators/pipeline\"));\nvar projectionOperators = __toESM(require(\"./operators/projection\"));\nvar queryOperators = __toESM(require(\"./operators/query\"));\nvar windowOperators = __toESM(require(\"./operators/window\"));\nvar import_query = require(\"./query\");\nvar updater = __toESM(require(\"./updater\"));\nvar import_core = require(\"./core\");\nconst CONTEXT = import_internal.Context.init({\n accumulator: accumulatorOperators,\n expression: expressionOperators,\n pipeline: pipelineOperators,\n projection: projectionOperators,\n query: queryOperators,\n window: windowOperators\n});\nconst makeOpts = (options) => Object.assign({\n ...options,\n context: options?.context ? import_internal.Context.from(CONTEXT, options?.context) : CONTEXT\n});\nclass Query extends import_query.Query {\n constructor(condition, options) {\n super(condition, makeOpts(options));\n }\n}\nclass Aggregator extends import_aggregator.Aggregator {\n constructor(pipeline, options) {\n super(pipeline, makeOpts(options));\n }\n}\nfunction find(collection, condition, projection, options) {\n return new Query(condition, makeOpts(options)).find(\n collection,\n projection\n );\n}\nfunction aggregate(collection, pipeline, options) {\n return new Aggregator(pipeline, makeOpts(options)).run(collection);\n}\nfunction update(obj, modifier, arrayFilters, condition, options) {\n return updater.update(obj, modifier, arrayFilters, condition, {\n cloneMode: options?.cloneMode,\n queryOptions: makeOpts(options?.queryOptions)\n });\n}\nfunction updateMany(documents, condition, modifer, updateConfig = {}, options) {\n return updater.updateMany(\n documents,\n condition,\n modifer,\n updateConfig,\n makeOpts(options)\n );\n}\nfunction updateOne(documents, condition, modifier, updateConfig = {}, options) {\n return updater.updateOne(\n documents,\n condition,\n modifier,\n updateConfig,\n makeOpts(options)\n );\n}\nvar index_default = {\n Aggregator,\n Context: import_internal.Context,\n ProcessingMode: import_internal.ProcessingMode,\n Query,\n aggregate,\n find,\n update,\n updateMany,\n updateOne\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Aggregator,\n Context,\n ProcessingMode,\n Query,\n aggregate,\n find,\n update,\n updateMany,\n updateOne\n});\n", "//#region src/env/env-impl.ts\nconst _envShim = Object.create(null);\nconst _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis);\nconst env = new Proxy(_envShim, {\n\tget(_, prop) {\n\t\treturn _getEnv()[prop] ?? _envShim[prop];\n\t},\n\thas(_, prop) {\n\t\treturn prop in _getEnv() || prop in _envShim;\n\t},\n\tset(_, prop, value) {\n\t\tconst env = _getEnv(true);\n\t\tenv[prop] = value;\n\t\treturn true;\n\t},\n\tdeleteProperty(_, prop) {\n\t\tif (!prop) return false;\n\t\tconst env = _getEnv(true);\n\t\tdelete env[prop];\n\t\treturn true;\n\t},\n\townKeys() {\n\t\tconst env = _getEnv(true);\n\t\treturn Object.keys(env);\n\t}\n});\nfunction toBoolean(val) {\n\treturn val ? val !== \"false\" : false;\n}\nconst nodeENV = typeof process !== \"undefined\" && process.env && process.env.NODE_ENV || \"\";\n/** Detect if `NODE_ENV` environment variable is `production` */\nconst isProduction = nodeENV === \"production\";\n/** Detect if `NODE_ENV` environment variable is `dev` or `development` */\nconst isDevelopment = () => nodeENV === \"dev\" || nodeENV === \"development\";\n/** Detect if `NODE_ENV` environment variable is `test` */\nconst isTest = () => nodeENV === \"test\" || toBoolean(env.TEST);\n/**\n* Get environment variable with fallback\n*/\nfunction getEnvVar(key, fallback) {\n\tif (typeof process !== \"undefined\" && process.env) return process.env[key] ?? fallback;\n\tif (typeof Deno !== \"undefined\") return Deno.env.get(key) ?? fallback;\n\tif (typeof Bun !== \"undefined\") return Bun.env[key] ?? fallback;\n\treturn fallback;\n}\n/**\n* Get boolean environment variable\n*/\nfunction getBooleanEnvVar(key, fallback = true) {\n\tconst value = getEnvVar(key);\n\tif (!value) return fallback;\n\treturn value !== \"0\" && value.toLowerCase() !== \"false\" && value !== \"\";\n}\n/**\n* Common environment variables used in Better Auth\n*/\nconst ENV = Object.freeze({\n\tget BETTER_AUTH_SECRET() {\n\t\treturn getEnvVar(\"BETTER_AUTH_SECRET\");\n\t},\n\tget AUTH_SECRET() {\n\t\treturn getEnvVar(\"AUTH_SECRET\");\n\t},\n\tget BETTER_AUTH_TELEMETRY() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY\");\n\t},\n\tget BETTER_AUTH_TELEMETRY_ID() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY_ID\");\n\t},\n\tget NODE_ENV() {\n\t\treturn getEnvVar(\"NODE_ENV\", \"development\");\n\t},\n\tget PACKAGE_VERSION() {\n\t\treturn getEnvVar(\"PACKAGE_VERSION\", \"0.0.0\");\n\t},\n\tget BETTER_AUTH_TELEMETRY_ENDPOINT() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY_ENDPOINT\", \"\");\n\t}\n});\n//#endregion\nexport { ENV, env, getBooleanEnvVar, getEnvVar, isDevelopment, isProduction, isTest, nodeENV };\n", "import { env, getEnvVar } from \"./env-impl.mjs\";\n//#region src/env/color-depth.ts\nconst COLORS_2 = 1;\nconst COLORS_16 = 4;\nconst COLORS_256 = 8;\nconst COLORS_16m = 24;\nconst TERM_ENVS = {\n\teterm: COLORS_16,\n\tcons25: COLORS_16,\n\tconsole: COLORS_16,\n\tcygwin: COLORS_16,\n\tdtterm: COLORS_16,\n\tgnome: COLORS_16,\n\thurd: COLORS_16,\n\tjfbterm: COLORS_16,\n\tkonsole: COLORS_16,\n\tkterm: COLORS_16,\n\tmlterm: COLORS_16,\n\tmosh: COLORS_16m,\n\tputty: COLORS_16,\n\tst: COLORS_16,\n\t\"rxvt-unicode-24bit\": COLORS_16m,\n\tterminator: COLORS_16m,\n\t\"xterm-kitty\": COLORS_16m\n};\nconst CI_ENVS_MAP = new Map(Object.entries({\n\tAPPVEYOR: COLORS_256,\n\tBUILDKITE: COLORS_256,\n\tCIRCLECI: COLORS_16m,\n\tDRONE: COLORS_256,\n\tGITEA_ACTIONS: COLORS_16m,\n\tGITHUB_ACTIONS: COLORS_16m,\n\tGITLAB_CI: COLORS_256,\n\tTRAVIS: COLORS_256\n}));\nconst TERM_ENVS_REG_EXP = [\n\t/ansi/,\n\t/color/,\n\t/linux/,\n\t/direct/,\n\t/^con[0-9]*x[0-9]/,\n\t/^rxvt/,\n\t/^screen/,\n\t/^xterm/,\n\t/^vt100/,\n\t/^vt220/\n];\nfunction getColorDepth() {\n\tif (getEnvVar(\"FORCE_COLOR\") !== void 0) switch (getEnvVar(\"FORCE_COLOR\")) {\n\t\tcase \"\":\n\t\tcase \"1\":\n\t\tcase \"true\": return COLORS_16;\n\t\tcase \"2\": return COLORS_256;\n\t\tcase \"3\": return COLORS_16m;\n\t\tdefault: return COLORS_2;\n\t}\n\tif (getEnvVar(\"NODE_DISABLE_COLORS\") !== void 0 && getEnvVar(\"NODE_DISABLE_COLORS\") !== \"\" || getEnvVar(\"NO_COLOR\") !== void 0 && getEnvVar(\"NO_COLOR\") !== \"\" || getEnvVar(\"TERM\") === \"dumb\") return COLORS_2;\n\tif (getEnvVar(\"TMUX\")) return COLORS_16m;\n\tif (\"TF_BUILD\" in env && \"AGENT_NAME\" in env) return COLORS_16;\n\tif (\"CI\" in env) {\n\t\tfor (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors;\n\t\tif (getEnvVar(\"CI_NAME\") === \"codeship\") return COLORS_256;\n\t\treturn COLORS_2;\n\t}\n\tif (\"TEAMCITY_VERSION\" in env) return /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.exec(getEnvVar(\"TEAMCITY_VERSION\")) !== null ? COLORS_16 : COLORS_2;\n\tswitch (getEnvVar(\"TERM_PROGRAM\")) {\n\t\tcase \"iTerm.app\":\n\t\t\tif (!getEnvVar(\"TERM_PROGRAM_VERSION\") || /^[0-2]\\./.exec(getEnvVar(\"TERM_PROGRAM_VERSION\")) !== null) return COLORS_256;\n\t\t\treturn COLORS_16m;\n\t\tcase \"HyperTerm\":\n\t\tcase \"MacTerm\": return COLORS_16m;\n\t\tcase \"Apple_Terminal\": return COLORS_256;\n\t}\n\tif (getEnvVar(\"COLORTERM\") === \"truecolor\" || getEnvVar(\"COLORTERM\") === \"24bit\") return COLORS_16m;\n\tif (getEnvVar(\"TERM\")) {\n\t\tif (/truecolor/.exec(getEnvVar(\"TERM\")) !== null) return COLORS_16m;\n\t\tif (/^xterm-256/.exec(getEnvVar(\"TERM\")) !== null) return COLORS_256;\n\t\tconst termEnv = getEnvVar(\"TERM\").toLowerCase();\n\t\tif (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv];\n\t\tif (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16;\n\t}\n\tif (getEnvVar(\"COLORTERM\")) return COLORS_16;\n\treturn COLORS_2;\n}\n//#endregion\nexport { getColorDepth };\n", "import { getColorDepth } from \"./color-depth.mjs\";\n//#region src/env/logger.ts\nconst TTY_COLORS = {\n\treset: \"\\x1B[0m\",\n\tbright: \"\\x1B[1m\",\n\tdim: \"\\x1B[2m\",\n\tundim: \"\\x1B[22m\",\n\tunderscore: \"\\x1B[4m\",\n\tblink: \"\\x1B[5m\",\n\treverse: \"\\x1B[7m\",\n\thidden: \"\\x1B[8m\",\n\tfg: {\n\t\tblack: \"\\x1B[30m\",\n\t\tred: \"\\x1B[31m\",\n\t\tgreen: \"\\x1B[32m\",\n\t\tyellow: \"\\x1B[33m\",\n\t\tblue: \"\\x1B[34m\",\n\t\tmagenta: \"\\x1B[35m\",\n\t\tcyan: \"\\x1B[36m\",\n\t\twhite: \"\\x1B[37m\"\n\t},\n\tbg: {\n\t\tblack: \"\\x1B[40m\",\n\t\tred: \"\\x1B[41m\",\n\t\tgreen: \"\\x1B[42m\",\n\t\tyellow: \"\\x1B[43m\",\n\t\tblue: \"\\x1B[44m\",\n\t\tmagenta: \"\\x1B[45m\",\n\t\tcyan: \"\\x1B[46m\",\n\t\twhite: \"\\x1B[47m\"\n\t}\n};\nconst levels = [\n\t\"debug\",\n\t\"info\",\n\t\"success\",\n\t\"warn\",\n\t\"error\"\n];\nfunction shouldPublishLog(currentLogLevel, logLevel) {\n\treturn levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel);\n}\nconst levelColors = {\n\tinfo: TTY_COLORS.fg.blue,\n\tsuccess: TTY_COLORS.fg.green,\n\twarn: TTY_COLORS.fg.yellow,\n\terror: TTY_COLORS.fg.red,\n\tdebug: TTY_COLORS.fg.magenta\n};\nconst formatMessage = (level, message, colorsEnabled) => {\n\tconst timestamp = (/* @__PURE__ */ new Date()).toISOString();\n\tif (colorsEnabled) return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message}`;\n\treturn `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message}`;\n};\nconst createLogger = (options) => {\n\tconst enabled = options?.disabled !== true;\n\tconst logLevel = options?.level ?? \"warn\";\n\tconst colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1;\n\tconst LogFunc = (level, message, args = []) => {\n\t\tif (!enabled || !shouldPublishLog(logLevel, level)) return;\n\t\tconst formattedMessage = formatMessage(level, message, colorsEnabled);\n\t\tif (!options || typeof options.log !== \"function\") {\n\t\t\tif (level === \"error\") console.error(formattedMessage, ...args);\n\t\t\telse if (level === \"warn\") console.warn(formattedMessage, ...args);\n\t\t\telse console.log(formattedMessage, ...args);\n\t\t\treturn;\n\t\t}\n\t\toptions.log(level === \"success\" ? \"info\" : level, message, ...args);\n\t};\n\treturn {\n\t\t...Object.fromEntries(levels.map((level) => [level, (...[message, ...args]) => LogFunc(level, message, args)])),\n\t\tget level() {\n\t\t\treturn logLevel;\n\t\t}\n\t};\n};\nconst logger = createLogger();\n//#endregion\nexport { TTY_COLORS, createLogger, levels, logger, shouldPublishLog };\n", "import { ENV, env, getBooleanEnvVar, getEnvVar, isDevelopment, isProduction, isTest, nodeENV } from \"./env-impl.mjs\";\nimport { getColorDepth } from \"./color-depth.mjs\";\nimport { TTY_COLORS, createLogger, levels, logger, shouldPublishLog } from \"./logger.mjs\";\nexport { ENV, TTY_COLORS, createLogger, env, getBooleanEnvVar, getColorDepth, getEnvVar, isDevelopment, isProduction, isTest, levels, logger, nodeENV, shouldPublishLog };\n", "//#region src/utils/error-codes.ts\nfunction defineErrorCodes(codes) {\n\treturn Object.fromEntries(Object.entries(codes).map(([key, value]) => [key, {\n\t\tcode: key,\n\t\tmessage: value,\n\t\ttoString: () => key\n\t}]));\n}\n//#endregion\nexport { defineErrorCodes };\n", "import { defineErrorCodes } from \"../utils/error-codes.mjs\";\n//#region src/error/codes.ts\nconst BASE_ERROR_CODES = defineErrorCodes({\n\tUSER_NOT_FOUND: \"User not found\",\n\tFAILED_TO_CREATE_USER: \"Failed to create user\",\n\tFAILED_TO_CREATE_SESSION: \"Failed to create session\",\n\tFAILED_TO_UPDATE_USER: \"Failed to update user\",\n\tFAILED_TO_GET_SESSION: \"Failed to get session\",\n\tINVALID_PASSWORD: \"Invalid password\",\n\tINVALID_EMAIL: \"Invalid email\",\n\tINVALID_EMAIL_OR_PASSWORD: \"Invalid email or password\",\n\tINVALID_USER: \"Invalid user\",\n\tSOCIAL_ACCOUNT_ALREADY_LINKED: \"Social account already linked\",\n\tPROVIDER_NOT_FOUND: \"Provider not found\",\n\tINVALID_TOKEN: \"Invalid token\",\n\tTOKEN_EXPIRED: \"Token expired\",\n\tID_TOKEN_NOT_SUPPORTED: \"id_token not supported\",\n\tFAILED_TO_GET_USER_INFO: \"Failed to get user info\",\n\tUSER_EMAIL_NOT_FOUND: \"User email not found\",\n\tEMAIL_NOT_VERIFIED: \"Email not verified\",\n\tPASSWORD_TOO_SHORT: \"Password too short\",\n\tPASSWORD_TOO_LONG: \"Password too long\",\n\tUSER_ALREADY_EXISTS: \"User already exists.\",\n\tUSER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: \"User already exists. Use another email.\",\n\tEMAIL_CAN_NOT_BE_UPDATED: \"Email can not be updated\",\n\tCREDENTIAL_ACCOUNT_NOT_FOUND: \"Credential account not found\",\n\tSESSION_EXPIRED: \"Session expired. Re-authenticate to perform this action.\",\n\tFAILED_TO_UNLINK_LAST_ACCOUNT: \"You can't unlink your last account\",\n\tACCOUNT_NOT_FOUND: \"Account not found\",\n\tUSER_ALREADY_HAS_PASSWORD: \"User already has a password. Provide that to delete the account.\",\n\tCROSS_SITE_NAVIGATION_LOGIN_BLOCKED: \"Cross-site navigation login blocked. This request appears to be a CSRF attack.\",\n\tVERIFICATION_EMAIL_NOT_ENABLED: \"Verification email isn't enabled\",\n\tEMAIL_ALREADY_VERIFIED: \"Email is already verified\",\n\tEMAIL_MISMATCH: \"Email mismatch\",\n\tSESSION_NOT_FRESH: \"Session is not fresh\",\n\tLINKED_ACCOUNT_ALREADY_EXISTS: \"Linked account already exists\",\n\tINVALID_ORIGIN: \"Invalid origin\",\n\tINVALID_CALLBACK_URL: \"Invalid callbackURL\",\n\tINVALID_REDIRECT_URL: \"Invalid redirectURL\",\n\tINVALID_ERROR_CALLBACK_URL: \"Invalid errorCallbackURL\",\n\tINVALID_NEW_USER_CALLBACK_URL: \"Invalid newUserCallbackURL\",\n\tMISSING_OR_NULL_ORIGIN: \"Missing or null Origin\",\n\tCALLBACK_URL_REQUIRED: \"callbackURL is required\",\n\tFAILED_TO_CREATE_VERIFICATION: \"Unable to create verification\",\n\tFIELD_NOT_ALLOWED: \"Field not allowed to be set\",\n\tASYNC_VALIDATION_NOT_SUPPORTED: \"Async validation is not supported\",\n\tVALIDATION_ERROR: \"Validation Error\",\n\tMISSING_FIELD: \"Field is required\",\n\tMETHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED: \"POST method requires deferSessionRefresh to be enabled in session config\",\n\tBODY_MUST_BE_AN_OBJECT: \"Body must be an object\",\n\tPASSWORD_ALREADY_SET: \"User already has a password set\"\n});\n//#endregion\nexport { BASE_ERROR_CODES };\n", "import type { StandardSchemaV1 } from \"./standard-schema\";\n// https://github.com/nodejs/node/blob/360f7cc7867b43344aac00564286b895e15f21d7/lib/internal/errors.js#L246C1-L261C2\nfunction isErrorStackTraceLimitWritable() {\n\tconst desc = Object.getOwnPropertyDescriptor(Error, \"stackTraceLimit\");\n\tif (desc === undefined) {\n\t\treturn Object.isExtensible(Error);\n\t}\n\n\treturn Object.prototype.hasOwnProperty.call(desc, \"writable\")\n\t\t? desc.writable\n\t\t: desc.set !== undefined;\n}\n\n/**\n * Hide internal stack frames from the error stack trace.\n */\nexport function hideInternalStackFrames(stack: string): string {\n\tconst lines = stack.split(\"\\n at \");\n\tif (lines.length <= 1) {\n\t\treturn stack;\n\t}\n\tlines.splice(1, 1);\n\treturn lines.join(\"\\n at \");\n}\n\n// https://github.com/nodejs/node/blob/360f7cc7867b43344aac00564286b895e15f21d7/lib/internal/errors.js#L411-L432\n/**\n * Creates a custom error class that hides stack frames.\n */\nexport function makeErrorForHideStackFrame<\n\tB extends new (\n\t\t...args: any[]\n\t) => Error,\n>(\n\tBase: B,\n\tclazz: any,\n): {\n\tnew (\n\t\t...args: ConstructorParameters\n\t): InstanceType & { errorStack: string | undefined };\n} {\n\tclass HideStackFramesError extends Base {\n\t\t#hiddenStack: string | undefined;\n\n\t\tconstructor(...args: any[]) {\n\t\t\tif (isErrorStackTraceLimitWritable()) {\n\t\t\t\tconst limit = Error.stackTraceLimit;\n\t\t\t\tError.stackTraceLimit = 0;\n\t\t\t\tsuper(...args);\n\t\t\t\tError.stackTraceLimit = limit;\n\t\t\t} else {\n\t\t\t\tsuper(...args);\n\t\t\t}\n\t\t\tconst stack = new Error().stack;\n\t\t\tif (stack) {\n\t\t\t\tthis.#hiddenStack = hideInternalStackFrames(\n\t\t\t\t\tstack.replace(/^Error/, this.name),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// use `getter` here to avoid the stack trace being captured by loggers\n\t\tget errorStack() {\n\t\t\treturn this.#hiddenStack;\n\t\t}\n\t}\n\n\t// This is a workaround for wpt tests that expect that the error\n\t// constructor has a `name` property of the base class.\n\tObject.defineProperty(HideStackFramesError.prototype, \"constructor\", {\n\t\tget() {\n\t\t\treturn clazz;\n\t\t},\n\t\tenumerable: false,\n\t\tconfigurable: true,\n\t});\n\n\treturn HideStackFramesError as any;\n}\n\nexport const statusCodes = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n\nexport type Status =\n\t| 100\n\t| 101\n\t| 102\n\t| 103\n\t| 200\n\t| 201\n\t| 202\n\t| 203\n\t| 204\n\t| 205\n\t| 206\n\t| 207\n\t| 208\n\t| 226\n\t| 300\n\t| 301\n\t| 302\n\t| 303\n\t| 304\n\t| 305\n\t| 306\n\t| 307\n\t| 308\n\t| 400\n\t| 401\n\t| 402\n\t| 403\n\t| 404\n\t| 405\n\t| 406\n\t| 407\n\t| 408\n\t| 409\n\t| 410\n\t| 411\n\t| 412\n\t| 413\n\t| 414\n\t| 415\n\t| 416\n\t| 417\n\t| 418\n\t| 421\n\t| 422\n\t| 423\n\t| 424\n\t| 425\n\t| 426\n\t| 428\n\t| 429\n\t| 431\n\t| 451\n\t| 500\n\t| 501\n\t| 502\n\t| 503\n\t| 504\n\t| 505\n\t| 506\n\t| 507\n\t| 508\n\t| 510\n\t| 511;\n\nclass InternalAPIError extends Error {\n\tconstructor(\n\t\tpublic status: keyof typeof statusCodes | Status = \"INTERNAL_SERVER_ERROR\",\n\t\tpublic body:\n\t\t\t| ({\n\t\t\t\t\tmessage?: string;\n\t\t\t\t\tcode?: string;\n\t\t\t\t\tcause?: unknown;\n\t\t\t } & Record)\n\t\t\t| undefined = undefined,\n\t\tpublic headers: HeadersInit = {},\n\t\tpublic statusCode = typeof status === \"number\"\n\t\t\t? status\n\t\t\t: statusCodes[status],\n\t) {\n\t\tsuper(\n\t\t\tbody?.message,\n\t\t\tbody?.cause\n\t\t\t\t? {\n\t\t\t\t\t\tcause: body.cause,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t);\n\t\tthis.name = \"APIError\";\n\t\tthis.status = status;\n\t\tthis.headers = headers;\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body;\n\t}\n}\n\nexport class ValidationError extends InternalAPIError {\n\tconstructor(\n\t\tpublic message: string,\n\t\tpublic issues: readonly StandardSchemaV1.Issue[],\n\t) {\n\t\tsuper(400, {\n\t\t\tmessage: message,\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t});\n\n\t\tthis.issues = issues;\n\t}\n}\n\nexport class BetterCallError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"BetterCallError\";\n\t}\n}\n\nexport const kAPIErrorHeaderSymbol = Symbol.for(\n\t\"better-call:api-error-headers\",\n);\n\nexport type APIError = InstanceType;\nexport const APIError = makeErrorForHideStackFrame(InternalAPIError, Error);\n", "import { BASE_ERROR_CODES } from \"./codes.mjs\";\nimport { APIError as APIError$1 } from \"better-call/error\";\n//#region src/error/index.ts\nvar BetterAuthError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"BetterAuthError\";\n\t\tthis.message = message;\n\t\tthis.stack = \"\";\n\t}\n};\nvar APIError = class APIError extends APIError$1 {\n\tconstructor(...args) {\n\t\tsuper(...args);\n\t}\n\tstatic fromStatus(status, body) {\n\t\treturn new APIError(status, body);\n\t}\n\tstatic from(status, error) {\n\t\treturn new APIError(status, {\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code\n\t\t});\n\t}\n};\n//#endregion\nexport { APIError, BASE_ERROR_CODES, BetterAuthError };\n", "function expandAlphabet(alphabet) {\n switch (alphabet) {\n case \"a-z\":\n return \"abcdefghijklmnopqrstuvwxyz\";\n case \"A-Z\":\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n case \"0-9\":\n return \"0123456789\";\n case \"-_\":\n return \"-_\";\n default:\n throw new Error(`Unsupported alphabet: ${alphabet}`);\n }\n}\nfunction createRandomStringGenerator(...baseAlphabets) {\n const baseCharSet = baseAlphabets.map(expandAlphabet).join(\"\");\n if (baseCharSet.length === 0) {\n throw new Error(\n \"No valid characters provided for random string generation.\"\n );\n }\n const baseCharSetLength = baseCharSet.length;\n return (length, ...alphabets) => {\n if (length <= 0) {\n throw new Error(\"Length must be a positive integer.\");\n }\n let charSet = baseCharSet;\n let charSetLength = baseCharSetLength;\n if (alphabets.length > 0) {\n charSet = alphabets.map(expandAlphabet).join(\"\");\n charSetLength = charSet.length;\n }\n const maxValid = Math.floor(256 / charSetLength) * charSetLength;\n const buf = new Uint8Array(length * 2);\n const bufLength = buf.length;\n let result = \"\";\n let bufIndex = bufLength;\n let rand;\n while (result.length < length) {\n if (bufIndex >= bufLength) {\n crypto.getRandomValues(buf);\n bufIndex = 0;\n }\n rand = buf[bufIndex++];\n if (rand < maxValid) {\n result += charSet[rand % charSetLength];\n }\n }\n return result;\n };\n}\n\nexport { createRandomStringGenerator };\n", "//#region src/db/get-tables.ts\nconst getAuthTables = (options) => {\n\tconst pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => {\n\t\tconst schema = plugin.schema;\n\t\tif (!schema) return acc;\n\t\tfor (const [key, value] of Object.entries(schema)) acc[key] = {\n\t\t\tfields: {\n\t\t\t\t...acc[key]?.fields,\n\t\t\t\t...value.fields\n\t\t\t},\n\t\t\tmodelName: value.modelName || key\n\t\t};\n\t\treturn acc;\n\t}, {});\n\tconst shouldAddRateLimitTable = options.rateLimit?.storage === \"database\";\n\tconst rateLimitTable = { rateLimit: {\n\t\tmodelName: options.rateLimit?.modelName || \"rateLimit\",\n\t\tfields: {\n\t\t\tkey: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tunique: true,\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.rateLimit?.fields?.key || \"key\"\n\t\t\t},\n\t\t\tcount: {\n\t\t\t\ttype: \"number\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.rateLimit?.fields?.count || \"count\"\n\t\t\t},\n\t\t\tlastRequest: {\n\t\t\t\ttype: \"number\",\n\t\t\t\tbigint: true,\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.rateLimit?.fields?.lastRequest || \"lastRequest\",\n\t\t\t\tdefaultValue: () => Date.now()\n\t\t\t}\n\t\t}\n\t} };\n\tconst { user, session, account, verification, ...pluginTables } = pluginSchema;\n\tconst verificationTable = { verification: {\n\t\tmodelName: options.verification?.modelName || \"verification\",\n\t\tfields: {\n\t\t\tidentifier: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.verification?.fields?.identifier || \"identifier\",\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tvalue: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.verification?.fields?.value || \"value\"\n\t\t\t},\n\t\t\texpiresAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.verification?.fields?.expiresAt || \"expiresAt\"\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\tfieldName: options.verification?.fields?.createdAt || \"createdAt\"\n\t\t\t},\n\t\t\tupdatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date(),\n\t\t\t\tfieldName: options.verification?.fields?.updatedAt || \"updatedAt\"\n\t\t\t},\n\t\t\t...verification?.fields,\n\t\t\t...options.verification?.additionalFields\n\t\t},\n\t\torder: 4\n\t} };\n\tconst sessionTable = { session: {\n\t\tmodelName: options.session?.modelName || \"session\",\n\t\tfields: {\n\t\t\texpiresAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.session?.fields?.expiresAt || \"expiresAt\"\n\t\t\t},\n\t\t\ttoken: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.session?.fields?.token || \"token\",\n\t\t\t\tunique: true\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.session?.fields?.createdAt || \"createdAt\",\n\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date()\n\t\t\t},\n\t\t\tupdatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.session?.fields?.updatedAt || \"updatedAt\",\n\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date()\n\t\t\t},\n\t\t\tipAddress: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\tfieldName: options.session?.fields?.ipAddress || \"ipAddress\"\n\t\t\t},\n\t\t\tuserAgent: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\tfieldName: options.session?.fields?.userAgent || \"userAgent\"\n\t\t\t},\n\t\t\tuserId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tfieldName: options.session?.fields?.userId || \"userId\",\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: options.user?.modelName || \"user\",\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tonDelete: \"cascade\"\n\t\t\t\t},\n\t\t\t\trequired: true,\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\t...session?.fields,\n\t\t\t...options.session?.additionalFields\n\t\t},\n\t\torder: 2\n\t} };\n\treturn {\n\t\tuser: {\n\t\t\tmodelName: options.user?.modelName || \"user\",\n\t\t\tfields: {\n\t\t\t\tname: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.name || \"name\",\n\t\t\t\t\tsortable: true\n\t\t\t\t},\n\t\t\t\temail: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tunique: true,\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.email || \"email\",\n\t\t\t\t\tsortable: true\n\t\t\t\t},\n\t\t\t\temailVerified: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdefaultValue: false,\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.emailVerified || \"emailVerified\",\n\t\t\t\t\tinput: false\n\t\t\t\t},\n\t\t\t\timage: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: options.user?.fields?.image || \"image\"\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.createdAt || \"createdAt\"\n\t\t\t\t},\n\t\t\t\tupdatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date(),\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.updatedAt || \"updatedAt\"\n\t\t\t\t},\n\t\t\t\t...user?.fields,\n\t\t\t\t...options.user?.additionalFields\n\t\t\t},\n\t\t\torder: 1\n\t\t},\n\t\t...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {},\n\t\taccount: {\n\t\t\tmodelName: options.account?.modelName || \"account\",\n\t\t\tfields: {\n\t\t\t\taccountId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.accountId || \"accountId\"\n\t\t\t\t},\n\t\t\t\tproviderId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.providerId || \"providerId\"\n\t\t\t\t},\n\t\t\t\tuserId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: options.user?.modelName || \"user\",\n\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\tonDelete: \"cascade\"\n\t\t\t\t\t},\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.userId || \"userId\",\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\taccessToken: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.accessToken || \"accessToken\"\n\t\t\t\t},\n\t\t\t\trefreshToken: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.refreshToken || \"refreshToken\"\n\t\t\t\t},\n\t\t\t\tidToken: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.idToken || \"idToken\"\n\t\t\t\t},\n\t\t\t\taccessTokenExpiresAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.accessTokenExpiresAt || \"accessTokenExpiresAt\"\n\t\t\t\t},\n\t\t\t\trefreshTokenExpiresAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.refreshTokenExpiresAt || \"refreshTokenExpiresAt\"\n\t\t\t\t},\n\t\t\t\tscope: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: options.account?.fields?.scope || \"scope\"\n\t\t\t\t},\n\t\t\t\tpassword: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.password || \"password\"\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.createdAt || \"createdAt\",\n\t\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date()\n\t\t\t\t},\n\t\t\t\tupdatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.updatedAt || \"updatedAt\",\n\t\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date()\n\t\t\t\t},\n\t\t\t\t...account?.fields,\n\t\t\t\t...options.account?.additionalFields\n\t\t\t},\n\t\t\torder: 3\n\t\t},\n\t\t...!options.secondaryStorage || options.verification?.storeInDatabase ? verificationTable : {},\n\t\t...pluginTables,\n\t\t...shouldAddRateLimitTable ? rateLimitTable : {}\n\t};\n};\n//#endregion\nexport { getAuthTables };\n", "import { logger } from \"../env/logger.mjs\";\n//#region src/utils/json.ts\nconst iso8601Regex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/;\nfunction reviveDate(value) {\n\tif (typeof value === \"string\" && iso8601Regex.test(value)) {\n\t\tconst date = new Date(value);\n\t\tif (!isNaN(date.getTime())) return date;\n\t}\n\treturn value;\n}\n/**\n* Recursively walk a pre-parsed object and convert ISO 8601 date strings\n* to Date instances. This handles the case where a Redis client (or similar)\n* returns already-parsed JSON objects whose date fields are still strings.\n*/\nfunction reviveDates(value) {\n\tif (value === null || value === void 0) return value;\n\tif (typeof value === \"string\") return reviveDate(value);\n\tif (value instanceof Date) return value;\n\tif (Array.isArray(value)) return value.map(reviveDates);\n\tif (typeof value === \"object\") {\n\t\tconst result = {};\n\t\tfor (const key of Object.keys(value)) result[key] = reviveDates(value[key]);\n\t\treturn result;\n\t}\n\treturn value;\n}\nfunction safeJSONParse(data) {\n\ttry {\n\t\tif (typeof data !== \"string\") {\n\t\t\tif (data === null || data === void 0) return null;\n\t\t\treturn reviveDates(data);\n\t\t}\n\t\treturn JSON.parse(data, (_, value) => reviveDate(value));\n\t} catch (e) {\n\t\tlogger.error(\"Error parsing JSON\", { error: e });\n\t\treturn null;\n\t}\n}\n//#endregion\nexport { safeJSONParse };\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createConstMap } from '../internal/utils';\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------\n// Constant values for SemanticAttributes\n//----------------------------------------------------------------------------------------------------------\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_AWS_LAMBDA_INVOKED_ARN = 'aws.lambda.invoked_arn';\nconst TMP_DB_SYSTEM = 'db.system';\nconst TMP_DB_CONNECTION_STRING = 'db.connection_string';\nconst TMP_DB_USER = 'db.user';\nconst TMP_DB_JDBC_DRIVER_CLASSNAME = 'db.jdbc.driver_classname';\nconst TMP_DB_NAME = 'db.name';\nconst TMP_DB_STATEMENT = 'db.statement';\nconst TMP_DB_OPERATION = 'db.operation';\nconst TMP_DB_MSSQL_INSTANCE_NAME = 'db.mssql.instance_name';\nconst TMP_DB_CASSANDRA_KEYSPACE = 'db.cassandra.keyspace';\nconst TMP_DB_CASSANDRA_PAGE_SIZE = 'db.cassandra.page_size';\nconst TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = 'db.cassandra.consistency_level';\nconst TMP_DB_CASSANDRA_TABLE = 'db.cassandra.table';\nconst TMP_DB_CASSANDRA_IDEMPOTENCE = 'db.cassandra.idempotence';\nconst TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT =\n 'db.cassandra.speculative_execution_count';\nconst TMP_DB_CASSANDRA_COORDINATOR_ID = 'db.cassandra.coordinator.id';\nconst TMP_DB_CASSANDRA_COORDINATOR_DC = 'db.cassandra.coordinator.dc';\nconst TMP_DB_HBASE_NAMESPACE = 'db.hbase.namespace';\nconst TMP_DB_REDIS_DATABASE_INDEX = 'db.redis.database_index';\nconst TMP_DB_MONGODB_COLLECTION = 'db.mongodb.collection';\nconst TMP_DB_SQL_TABLE = 'db.sql.table';\nconst TMP_EXCEPTION_TYPE = 'exception.type';\nconst TMP_EXCEPTION_MESSAGE = 'exception.message';\nconst TMP_EXCEPTION_STACKTRACE = 'exception.stacktrace';\nconst TMP_EXCEPTION_ESCAPED = 'exception.escaped';\nconst TMP_FAAS_TRIGGER = 'faas.trigger';\nconst TMP_FAAS_EXECUTION = 'faas.execution';\nconst TMP_FAAS_DOCUMENT_COLLECTION = 'faas.document.collection';\nconst TMP_FAAS_DOCUMENT_OPERATION = 'faas.document.operation';\nconst TMP_FAAS_DOCUMENT_TIME = 'faas.document.time';\nconst TMP_FAAS_DOCUMENT_NAME = 'faas.document.name';\nconst TMP_FAAS_TIME = 'faas.time';\nconst TMP_FAAS_CRON = 'faas.cron';\nconst TMP_FAAS_COLDSTART = 'faas.coldstart';\nconst TMP_FAAS_INVOKED_NAME = 'faas.invoked_name';\nconst TMP_FAAS_INVOKED_PROVIDER = 'faas.invoked_provider';\nconst TMP_FAAS_INVOKED_REGION = 'faas.invoked_region';\nconst TMP_NET_TRANSPORT = 'net.transport';\nconst TMP_NET_PEER_IP = 'net.peer.ip';\nconst TMP_NET_PEER_PORT = 'net.peer.port';\nconst TMP_NET_PEER_NAME = 'net.peer.name';\nconst TMP_NET_HOST_IP = 'net.host.ip';\nconst TMP_NET_HOST_PORT = 'net.host.port';\nconst TMP_NET_HOST_NAME = 'net.host.name';\nconst TMP_NET_HOST_CONNECTION_TYPE = 'net.host.connection.type';\nconst TMP_NET_HOST_CONNECTION_SUBTYPE = 'net.host.connection.subtype';\nconst TMP_NET_HOST_CARRIER_NAME = 'net.host.carrier.name';\nconst TMP_NET_HOST_CARRIER_MCC = 'net.host.carrier.mcc';\nconst TMP_NET_HOST_CARRIER_MNC = 'net.host.carrier.mnc';\nconst TMP_NET_HOST_CARRIER_ICC = 'net.host.carrier.icc';\nconst TMP_PEER_SERVICE = 'peer.service';\nconst TMP_ENDUSER_ID = 'enduser.id';\nconst TMP_ENDUSER_ROLE = 'enduser.role';\nconst TMP_ENDUSER_SCOPE = 'enduser.scope';\nconst TMP_THREAD_ID = 'thread.id';\nconst TMP_THREAD_NAME = 'thread.name';\nconst TMP_CODE_FUNCTION = 'code.function';\nconst TMP_CODE_NAMESPACE = 'code.namespace';\nconst TMP_CODE_FILEPATH = 'code.filepath';\nconst TMP_CODE_LINENO = 'code.lineno';\nconst TMP_HTTP_METHOD = 'http.method';\nconst TMP_HTTP_URL = 'http.url';\nconst TMP_HTTP_TARGET = 'http.target';\nconst TMP_HTTP_HOST = 'http.host';\nconst TMP_HTTP_SCHEME = 'http.scheme';\nconst TMP_HTTP_STATUS_CODE = 'http.status_code';\nconst TMP_HTTP_FLAVOR = 'http.flavor';\nconst TMP_HTTP_USER_AGENT = 'http.user_agent';\nconst TMP_HTTP_REQUEST_CONTENT_LENGTH = 'http.request_content_length';\nconst TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED =\n 'http.request_content_length_uncompressed';\nconst TMP_HTTP_RESPONSE_CONTENT_LENGTH = 'http.response_content_length';\nconst TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED =\n 'http.response_content_length_uncompressed';\nconst TMP_HTTP_SERVER_NAME = 'http.server_name';\nconst TMP_HTTP_ROUTE = 'http.route';\nconst TMP_HTTP_CLIENT_IP = 'http.client_ip';\nconst TMP_AWS_DYNAMODB_TABLE_NAMES = 'aws.dynamodb.table_names';\nconst TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = 'aws.dynamodb.consumed_capacity';\nconst TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS =\n 'aws.dynamodb.item_collection_metrics';\nconst TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY =\n 'aws.dynamodb.provisioned_read_capacity';\nconst TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY =\n 'aws.dynamodb.provisioned_write_capacity';\nconst TMP_AWS_DYNAMODB_CONSISTENT_READ = 'aws.dynamodb.consistent_read';\nconst TMP_AWS_DYNAMODB_PROJECTION = 'aws.dynamodb.projection';\nconst TMP_AWS_DYNAMODB_LIMIT = 'aws.dynamodb.limit';\nconst TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = 'aws.dynamodb.attributes_to_get';\nconst TMP_AWS_DYNAMODB_INDEX_NAME = 'aws.dynamodb.index_name';\nconst TMP_AWS_DYNAMODB_SELECT = 'aws.dynamodb.select';\nconst TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES =\n 'aws.dynamodb.global_secondary_indexes';\nconst TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES =\n 'aws.dynamodb.local_secondary_indexes';\nconst TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE =\n 'aws.dynamodb.exclusive_start_table';\nconst TMP_AWS_DYNAMODB_TABLE_COUNT = 'aws.dynamodb.table_count';\nconst TMP_AWS_DYNAMODB_SCAN_FORWARD = 'aws.dynamodb.scan_forward';\nconst TMP_AWS_DYNAMODB_SEGMENT = 'aws.dynamodb.segment';\nconst TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = 'aws.dynamodb.total_segments';\nconst TMP_AWS_DYNAMODB_COUNT = 'aws.dynamodb.count';\nconst TMP_AWS_DYNAMODB_SCANNED_COUNT = 'aws.dynamodb.scanned_count';\nconst TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS =\n 'aws.dynamodb.attribute_definitions';\nconst TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES =\n 'aws.dynamodb.global_secondary_index_updates';\nconst TMP_MESSAGING_SYSTEM = 'messaging.system';\nconst TMP_MESSAGING_DESTINATION = 'messaging.destination';\nconst TMP_MESSAGING_DESTINATION_KIND = 'messaging.destination_kind';\nconst TMP_MESSAGING_TEMP_DESTINATION = 'messaging.temp_destination';\nconst TMP_MESSAGING_PROTOCOL = 'messaging.protocol';\nconst TMP_MESSAGING_PROTOCOL_VERSION = 'messaging.protocol_version';\nconst TMP_MESSAGING_URL = 'messaging.url';\nconst TMP_MESSAGING_MESSAGE_ID = 'messaging.message_id';\nconst TMP_MESSAGING_CONVERSATION_ID = 'messaging.conversation_id';\nconst TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES =\n 'messaging.message_payload_size_bytes';\nconst TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES =\n 'messaging.message_payload_compressed_size_bytes';\nconst TMP_MESSAGING_OPERATION = 'messaging.operation';\nconst TMP_MESSAGING_CONSUMER_ID = 'messaging.consumer_id';\nconst TMP_MESSAGING_RABBITMQ_ROUTING_KEY = 'messaging.rabbitmq.routing_key';\nconst TMP_MESSAGING_KAFKA_MESSAGE_KEY = 'messaging.kafka.message_key';\nconst TMP_MESSAGING_KAFKA_CONSUMER_GROUP = 'messaging.kafka.consumer_group';\nconst TMP_MESSAGING_KAFKA_CLIENT_ID = 'messaging.kafka.client_id';\nconst TMP_MESSAGING_KAFKA_PARTITION = 'messaging.kafka.partition';\nconst TMP_MESSAGING_KAFKA_TOMBSTONE = 'messaging.kafka.tombstone';\nconst TMP_RPC_SYSTEM = 'rpc.system';\nconst TMP_RPC_SERVICE = 'rpc.service';\nconst TMP_RPC_METHOD = 'rpc.method';\nconst TMP_RPC_GRPC_STATUS_CODE = 'rpc.grpc.status_code';\nconst TMP_RPC_JSONRPC_VERSION = 'rpc.jsonrpc.version';\nconst TMP_RPC_JSONRPC_REQUEST_ID = 'rpc.jsonrpc.request_id';\nconst TMP_RPC_JSONRPC_ERROR_CODE = 'rpc.jsonrpc.error_code';\nconst TMP_RPC_JSONRPC_ERROR_MESSAGE = 'rpc.jsonrpc.error_message';\nconst TMP_MESSAGE_TYPE = 'message.type';\nconst TMP_MESSAGE_ID = 'message.id';\nconst TMP_MESSAGE_COMPRESSED_SIZE = 'message.compressed_size';\nconst TMP_MESSAGE_UNCOMPRESSED_SIZE = 'message.uncompressed_size';\n\n/**\n * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable).\n *\n * Note: This may be different from `faas.id` if an alias is involved.\n *\n * @deprecated Use ATTR_AWS_LAMBDA_INVOKED_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use ATTR_DB_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM;\n\n/**\n * The connection string used to connect to the database. It is recommended to remove embedded credentials.\n *\n * @deprecated Use ATTR_DB_CONNECTION_STRING in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING;\n\n/**\n * Username for accessing the database.\n *\n * @deprecated Use ATTR_DB_USER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_USER = TMP_DB_USER;\n\n/**\n * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect.\n *\n * @deprecated Use ATTR_DB_JDBC_DRIVER_CLASSNAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME;\n\n/**\n * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails).\n *\n * Note: In some SQL databases, the database name to be used is called "schema name".\n *\n * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_NAME = TMP_DB_NAME;\n\n/**\n * The database statement being executed.\n *\n * Note: The value may be sanitized to exclude sensitive information.\n *\n * @deprecated Use ATTR_DB_STATEMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT;\n\n/**\n * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword.\n *\n * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted.\n *\n * @deprecated Use ATTR_DB_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_OPERATION = TMP_DB_OPERATION;\n\n/**\n * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance.\n *\n * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard).\n *\n * @deprecated Use ATTR_DB_MSSQL_INSTANCE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME;\n\n/**\n * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute.\n *\n * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE;\n\n/**\n * The fetch size used for paging, i.e. how many rows will be returned at once.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_PAGE_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL =\n TMP_DB_CASSANDRA_CONSISTENCY_LEVEL;\n\n/**\n * The name of the primary table that the operation is acting upon, including the schema name (if applicable).\n *\n * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE;\n\n/**\n * Whether or not the query is idempotent.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_IDEMPOTENCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE;\n\n/**\n * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT =\n TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT;\n\n/**\n * The ID of the coordinating node for a query.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_COORDINATOR_ID =\n TMP_DB_CASSANDRA_COORDINATOR_ID;\n\n/**\n * The data center of the coordinating node for a query.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_DC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_COORDINATOR_DC =\n TMP_DB_CASSANDRA_COORDINATOR_DC;\n\n/**\n * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute.\n *\n * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE;\n\n/**\n * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute.\n *\n * @deprecated Use ATTR_DB_REDIS_DATABASE_INDEX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX;\n\n/**\n * The collection being accessed within the database stated in `db.name`.\n *\n * @deprecated Use ATTR_DB_MONGODB_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION;\n\n/**\n * The name of the primary table that the operation is acting upon, including the schema name (if applicable).\n *\n * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set.\n *\n * @deprecated Use ATTR_DB_SQL_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @deprecated Use ATTR_EXCEPTION_TYPE.\n */\nexport const SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE;\n\n/**\n * The exception message.\n *\n * @deprecated Use ATTR_EXCEPTION_MESSAGE.\n */\nexport const SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @deprecated Use ATTR_EXCEPTION_STACKTRACE.\n */\nexport const SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE;\n\n/**\n* SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span.\n*\n* Note: An exception is considered to have escaped (or left) the scope of a span,\nif that span is ended while the exception is still logically "in flight".\nThis may be actually "in flight" in some languages (e.g. if the exception\nis passed to a Context manager's `__exit__` method in Python) but will\nusually be caught at the point of recording the exception in most languages.\n\nIt is usually not possible to determine at the point where an exception is thrown\nwhether it will escape the scope of a span.\nHowever, it is trivial to know that an exception\nwill escape, if one checks for an active exception just before ending the span,\nas done in the [example above](#exception-end-example).\n\nIt follows that an exception may still escape the scope of the span\neven if the `exception.escaped` attribute was not set or set to false,\nsince the event might have been recorded at a time where it was not\nclear whether the exception will escape.\n*\n* @deprecated Use ATTR_EXCEPTION_ESCAPED.\n*/\nexport const SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use ATTR_FAAS_TRIGGER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER;\n\n/**\n * The execution ID of the current function execution.\n *\n * @deprecated Use ATTR_FAAS_INVOCATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION;\n\n/**\n * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name.\n *\n * @deprecated Use ATTR_FAAS_DOCUMENT_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION;\n\n/**\n * Describes the type of the operation that was performed on the data.\n *\n * @deprecated Use ATTR_FAAS_DOCUMENT_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION;\n\n/**\n * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime).\n *\n * @deprecated Use ATTR_FAAS_DOCUMENT_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME;\n\n/**\n * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name.\n *\n * @deprecated Use ATTR_FAAS_DOCUMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME;\n\n/**\n * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime).\n *\n * @deprecated Use ATTR_FAAS_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_TIME = TMP_FAAS_TIME;\n\n/**\n * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm).\n *\n * @deprecated Use ATTR_FAAS_CRON in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_CRON = TMP_FAAS_CRON;\n\n/**\n * A boolean that is true if the serverless function is executed for the first time (aka cold-start).\n *\n * @deprecated Use ATTR_FAAS_COLDSTART in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART;\n\n/**\n * The name of the invoked function.\n *\n * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function.\n *\n * @deprecated Use ATTR_FAAS_INVOKED_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME;\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use ATTR_FAAS_INVOKED_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER;\n\n/**\n * The cloud region of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function.\n *\n * @deprecated Use ATTR_FAAS_INVOKED_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use ATTR_NET_TRANSPORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT;\n\n/**\n * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6).\n *\n * @deprecated Use ATTR_NET_PEER_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP;\n\n/**\n * Remote port number.\n *\n * @deprecated Use ATTR_NET_PEER_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT;\n\n/**\n * Remote hostname or similar, see note below.\n *\n * @deprecated Use ATTR_NET_PEER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME;\n\n/**\n * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host.\n *\n * @deprecated Use ATTR_NET_HOST_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP;\n\n/**\n * Like `net.peer.port` but for the host port.\n *\n * @deprecated Use ATTR_NET_HOST_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT;\n\n/**\n * Local hostname or similar, see note below.\n *\n * @deprecated Use ATTR_NET_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use ATTR_NETWORK_CONNECTION_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use ATTR_NETWORK_CONNECTION_SUBTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CONNECTION_SUBTYPE =\n TMP_NET_HOST_CONNECTION_SUBTYPE;\n\n/**\n * The name of the mobile carrier.\n *\n * @deprecated Use ATTR_NETWORK_CARRIER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME;\n\n/**\n * The mobile carrier country code.\n *\n * @deprecated Use ATTR_NETWORK_CARRIER_MCC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC;\n\n/**\n * The mobile carrier network code.\n *\n * @deprecated Use ATTR_NETWORK_CARRIER_MNC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC;\n\n/**\n * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network.\n *\n * @deprecated Use ATTR_NETWORK_CARRIER_ICC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC;\n\n/**\n * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any.\n *\n * @deprecated Use ATTR_PEER_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE;\n\n/**\n * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system.\n *\n * @deprecated Use ATTR_ENDUSER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID;\n\n/**\n * Actual/assumed role the client is making the request under extracted from token or application security context.\n *\n * @deprecated Use ATTR_ENDUSER_ROLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE;\n\n/**\n * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html).\n *\n * @deprecated Use ATTR_ENDUSER_SCOPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE;\n\n/**\n * Current "managed" thread ID (as opposed to OS thread ID).\n *\n * @deprecated Use ATTR_THREAD_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_THREAD_ID = TMP_THREAD_ID;\n\n/**\n * Current thread name.\n *\n * @deprecated Use ATTR_THREAD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_THREAD_NAME = TMP_THREAD_NAME;\n\n/**\n * The method or function name, or equivalent (usually rightmost part of the code unit's name).\n *\n * @deprecated Use ATTR_CODE_FUNCTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION;\n\n/**\n * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit.\n *\n * @deprecated Use ATTR_CODE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path).\n *\n * @deprecated Use ATTR_CODE_FILEPATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH;\n\n/**\n * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`.\n *\n * @deprecated Use ATTR_CODE_LINENO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_CODE_LINENO = TMP_CODE_LINENO;\n\n/**\n * HTTP request method.\n *\n * @deprecated Use ATTR_HTTP_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD;\n\n/**\n * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless.\n *\n * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`.\n *\n * @deprecated Use ATTR_HTTP_URL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_URL = TMP_HTTP_URL;\n\n/**\n * The full request target as passed in a HTTP request line or equivalent.\n *\n * @deprecated Use ATTR_HTTP_TARGET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET;\n\n/**\n * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note.\n *\n * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set.\n *\n * @deprecated Use ATTR_HTTP_HOST in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_HOST = TMP_HTTP_HOST;\n\n/**\n * The URI scheme identifying the used protocol.\n *\n * @deprecated Use ATTR_HTTP_SCHEME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @deprecated Use ATTR_HTTP_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use ATTR_HTTP_FLAVOR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR;\n\n/**\n * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client.\n *\n * @deprecated Use ATTR_HTTP_USER_AGENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT;\n\n/**\n * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size.\n *\n * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH =\n TMP_HTTP_REQUEST_CONTENT_LENGTH;\n\n/**\n * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used.\n *\n * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED =\n TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED;\n\n/**\n * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size.\n *\n * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH =\n TMP_HTTP_RESPONSE_CONTENT_LENGTH;\n\n/**\n * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used.\n *\n * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED =\n TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED;\n\n/**\n * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead).\n *\n * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available.\n *\n * @deprecated Use ATTR_HTTP_SERVER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME;\n\n/**\n * The matched route (path template).\n *\n * @deprecated Use ATTR_HTTP_ROUTE.\n */\nexport const SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE;\n\n/**\n* The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)).\n*\n* Note: This is not necessarily the same as `net.peer.ip`, which would\nidentify the network-level peer, which may be a proxy.\n\nThis attribute should be set when a source of information different\nfrom the one used for `net.peer.ip`, is available even if that other\nsource just confirms the same value as `net.peer.ip`.\nRationale: For `net.peer.ip`, one typically does not know if it\ncomes from a proxy, reverse proxy, or the actual client. Setting\n`http.client_ip` when it's the same as `net.peer.ip` means that\none is at least somewhat confident that the address is not that of\nthe closest proxy.\n*\n* @deprecated Use ATTR_HTTP_CLIENT_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n*/\nexport const SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP;\n\n/**\n * The keys in the `RequestItems` object field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES;\n\n/**\n * The JSON-serialized value of each item in the `ConsumedCapacity` response field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY =\n TMP_AWS_DYNAMODB_CONSUMED_CAPACITY;\n\n/**\n * The JSON-serialized value of the `ItemCollectionMetrics` response field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS =\n TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS;\n\n/**\n * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY =\n TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY;\n\n/**\n * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY =\n TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY;\n\n/**\n * The value of the `ConsistentRead` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_CONSISTENT_READ in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ =\n TMP_AWS_DYNAMODB_CONSISTENT_READ;\n\n/**\n * The value of the `ProjectionExpression` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_PROJECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION;\n\n/**\n * The value of the `Limit` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_LIMIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT;\n\n/**\n * The value of the `AttributesToGet` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTES_TO_GET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET =\n TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET;\n\n/**\n * The value of the `IndexName` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_INDEX_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME;\n\n/**\n * The value of the `Select` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_SELECT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT;\n\n/**\n * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES =\n TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES;\n\n/**\n * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES =\n TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES;\n\n/**\n * The value of the `ExclusiveStartTableName` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE =\n TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE;\n\n/**\n * The the number of items in the `TableNames` response parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT;\n\n/**\n * The value of the `ScanIndexForward` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_SCAN_FORWARD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD;\n\n/**\n * The value of the `Segment` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_SEGMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT;\n\n/**\n * The value of the `TotalSegments` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS =\n TMP_AWS_DYNAMODB_TOTAL_SEGMENTS;\n\n/**\n * The value of the `Count` response parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT;\n\n/**\n * The value of the `ScannedCount` response parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_SCANNED_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT =\n TMP_AWS_DYNAMODB_SCANNED_COUNT;\n\n/**\n * The JSON-serialized value of each item in the `AttributeDefinitions` request field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS =\n TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS;\n\n/**\n * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES =\n TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES;\n\n/**\n * A string identifying the messaging system.\n *\n * @deprecated Use ATTR_MESSAGING_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM;\n\n/**\n * The message destination name. This might be equal to the span name but is required nevertheless.\n *\n * @deprecated Use ATTR_MESSAGING_DESTINATION_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION;\n\n/**\n * The kind of message destination.\n *\n * @deprecated Removed in semconv v1.20.0.\n */\nexport const SEMATTRS_MESSAGING_DESTINATION_KIND =\n TMP_MESSAGING_DESTINATION_KIND;\n\n/**\n * A boolean that is true if the message destination is temporary.\n *\n * @deprecated Use ATTR_MESSAGING_DESTINATION_TEMPORARY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_TEMP_DESTINATION =\n TMP_MESSAGING_TEMP_DESTINATION;\n\n/**\n * The name of the transport protocol.\n *\n * @deprecated Use ATTR_NETWORK_PROTOCOL_NAME.\n */\nexport const SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL;\n\n/**\n * The version of the transport protocol.\n *\n * @deprecated Use ATTR_NETWORK_PROTOCOL_VERSION.\n */\nexport const SEMATTRS_MESSAGING_PROTOCOL_VERSION =\n TMP_MESSAGING_PROTOCOL_VERSION;\n\n/**\n * Connection string.\n *\n * @deprecated Removed in semconv v1.17.0.\n */\nexport const SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL;\n\n/**\n * A value used by the messaging system as an identifier for the message, represented as a string.\n *\n * @deprecated Use ATTR_MESSAGING_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID;\n\n/**\n * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID".\n *\n * @deprecated Use ATTR_MESSAGING_MESSAGE_CONVERSATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID;\n\n/**\n * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported.\n *\n * @deprecated Use ATTR_MESSAGING_MESSAGE_BODY_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES =\n TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES;\n\n/**\n * The compressed size of the message payload in bytes.\n *\n * @deprecated Removed in semconv v1.22.0.\n */\nexport const SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES =\n TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES;\n\n/**\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n *\n * @deprecated Use ATTR_MESSAGING_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION;\n\n/**\n * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message.\n *\n * @deprecated Removed in semconv v1.21.0.\n */\nexport const SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID;\n\n/**\n * RabbitMQ message routing key.\n *\n * @deprecated Use ATTR_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY =\n TMP_MESSAGING_RABBITMQ_ROUTING_KEY;\n\n/**\n * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set.\n *\n * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value.\n *\n * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY =\n TMP_MESSAGING_KAFKA_MESSAGE_KEY;\n\n/**\n * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers.\n *\n * @deprecated Use ATTR_MESSAGING_KAFKA_CONSUMER_GROUP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP =\n TMP_MESSAGING_KAFKA_CONSUMER_GROUP;\n\n/**\n * Client Id for the Consumer or Producer that is handling the message.\n *\n * @deprecated Use ATTR_MESSAGING_CLIENT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID;\n\n/**\n * Partition the message is sent to.\n *\n * @deprecated Use ATTR_MESSAGING_KAFKA_DESTINATION_PARTITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION;\n\n/**\n * A boolean that is true if the message is a tombstone.\n *\n * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE;\n\n/**\n * A string identifying the remoting system.\n *\n * @deprecated Use ATTR_RPC_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM;\n\n/**\n * The full (logical) name of the service being called, including its package name, if applicable.\n *\n * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side).\n *\n * @deprecated Use ATTR_RPC_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE;\n\n/**\n * The name of the (logical) method being called, must be equal to the $method part in the span name.\n *\n * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side).\n *\n * @deprecated Use ATTR_RPC_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_METHOD = TMP_RPC_METHOD;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use ATTR_RPC_GRPC_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE;\n\n/**\n * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted.\n *\n * @deprecated Use ATTR_RPC_JSONRPC_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION;\n\n/**\n * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification.\n *\n * @deprecated Use ATTR_RPC_JSONRPC_REQUEST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID;\n\n/**\n * `error.code` property of response if it is an error response.\n *\n * @deprecated Use ATTR_RPC_JSONRPC_ERROR_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE;\n\n/**\n * `error.message` property of response if it is an error response.\n *\n * @deprecated Use ATTR_RPC_JSONRPC_ERROR_MESSAGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE;\n\n/**\n * Whether this is a received or sent message.\n *\n * @deprecated Use ATTR_MESSAGE_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE;\n\n/**\n * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message.\n *\n * Note: This way we guarantee that the values will be consistent between different implementations.\n *\n * @deprecated Use ATTR_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID;\n\n/**\n * Compressed size of the message in bytes.\n *\n * @deprecated Use ATTR_MESSAGE_COMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE;\n\n/**\n * Uncompressed size of the message in bytes.\n *\n * @deprecated Use ATTR_MESSAGE_UNCOMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE;\n\n/**\n * Definition of available values for SemanticAttributes\n * This type is used for backward compatibility, you should use the individual exported\n * constants SemanticAttributes_XXXXX rather than the exported constant map. As any single reference\n * to a constant map value will result in all strings being included into your bundle.\n * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification.\n */\nexport type SemanticAttributes = {\n /**\n * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable).\n *\n * Note: This may be different from `faas.id` if an alias is involved.\n */\n AWS_LAMBDA_INVOKED_ARN: 'aws.lambda.invoked_arn';\n\n /**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n */\n DB_SYSTEM: 'db.system';\n\n /**\n * The connection string used to connect to the database. It is recommended to remove embedded credentials.\n */\n DB_CONNECTION_STRING: 'db.connection_string';\n\n /**\n * Username for accessing the database.\n */\n DB_USER: 'db.user';\n\n /**\n * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect.\n */\n DB_JDBC_DRIVER_CLASSNAME: 'db.jdbc.driver_classname';\n\n /**\n * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails).\n *\n * Note: In some SQL databases, the database name to be used is called "schema name".\n */\n DB_NAME: 'db.name';\n\n /**\n * The database statement being executed.\n *\n * Note: The value may be sanitized to exclude sensitive information.\n */\n DB_STATEMENT: 'db.statement';\n\n /**\n * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword.\n *\n * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted.\n */\n DB_OPERATION: 'db.operation';\n\n /**\n * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance.\n *\n * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard).\n */\n DB_MSSQL_INSTANCE_NAME: 'db.mssql.instance_name';\n\n /**\n * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute.\n */\n DB_CASSANDRA_KEYSPACE: 'db.cassandra.keyspace';\n\n /**\n * The fetch size used for paging, i.e. how many rows will be returned at once.\n */\n DB_CASSANDRA_PAGE_SIZE: 'db.cassandra.page_size';\n\n /**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n */\n DB_CASSANDRA_CONSISTENCY_LEVEL: 'db.cassandra.consistency_level';\n\n /**\n * The name of the primary table that the operation is acting upon, including the schema name (if applicable).\n *\n * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set.\n */\n DB_CASSANDRA_TABLE: 'db.cassandra.table';\n\n /**\n * Whether or not the query is idempotent.\n */\n DB_CASSANDRA_IDEMPOTENCE: 'db.cassandra.idempotence';\n\n /**\n * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively.\n */\n DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT: 'db.cassandra.speculative_execution_count';\n\n /**\n * The ID of the coordinating node for a query.\n */\n DB_CASSANDRA_COORDINATOR_ID: 'db.cassandra.coordinator.id';\n\n /**\n * The data center of the coordinating node for a query.\n */\n DB_CASSANDRA_COORDINATOR_DC: 'db.cassandra.coordinator.dc';\n\n /**\n * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute.\n */\n DB_HBASE_NAMESPACE: 'db.hbase.namespace';\n\n /**\n * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute.\n */\n DB_REDIS_DATABASE_INDEX: 'db.redis.database_index';\n\n /**\n * The collection being accessed within the database stated in `db.name`.\n */\n DB_MONGODB_COLLECTION: 'db.mongodb.collection';\n\n /**\n * The name of the primary table that the operation is acting upon, including the schema name (if applicable).\n *\n * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set.\n */\n DB_SQL_TABLE: 'db.sql.table';\n\n /**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n */\n EXCEPTION_TYPE: 'exception.type';\n\n /**\n * The exception message.\n */\n EXCEPTION_MESSAGE: 'exception.message';\n\n /**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n */\n EXCEPTION_STACKTRACE: 'exception.stacktrace';\n\n /**\n * SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span.\n *\n * Note: An exception is considered to have escaped (or left) the scope of a span,\nif that span is ended while the exception is still logically "in flight".\nThis may be actually "in flight" in some languages (e.g. if the exception\nis passed to a Context manager's `__exit__` method in Python) but will\nusually be caught at the point of recording the exception in most languages.\n\nIt is usually not possible to determine at the point where an exception is thrown\nwhether it will escape the scope of a span.\nHowever, it is trivial to know that an exception\nwill escape, if one checks for an active exception just before ending the span,\nas done in the [example above](#exception-end-example).\n\nIt follows that an exception may still escape the scope of the span\neven if the `exception.escaped` attribute was not set or set to false,\nsince the event might have been recorded at a time where it was not\nclear whether the exception will escape.\n */\n EXCEPTION_ESCAPED: 'exception.escaped';\n\n /**\n * Type of the trigger on which the function is executed.\n */\n FAAS_TRIGGER: 'faas.trigger';\n\n /**\n * The execution ID of the current function execution.\n */\n FAAS_EXECUTION: 'faas.execution';\n\n /**\n * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name.\n */\n FAAS_DOCUMENT_COLLECTION: 'faas.document.collection';\n\n /**\n * Describes the type of the operation that was performed on the data.\n */\n FAAS_DOCUMENT_OPERATION: 'faas.document.operation';\n\n /**\n * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime).\n */\n FAAS_DOCUMENT_TIME: 'faas.document.time';\n\n /**\n * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name.\n */\n FAAS_DOCUMENT_NAME: 'faas.document.name';\n\n /**\n * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime).\n */\n FAAS_TIME: 'faas.time';\n\n /**\n * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm).\n */\n FAAS_CRON: 'faas.cron';\n\n /**\n * A boolean that is true if the serverless function is executed for the first time (aka cold-start).\n */\n FAAS_COLDSTART: 'faas.coldstart';\n\n /**\n * The name of the invoked function.\n *\n * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function.\n */\n FAAS_INVOKED_NAME: 'faas.invoked_name';\n\n /**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n */\n FAAS_INVOKED_PROVIDER: 'faas.invoked_provider';\n\n /**\n * The cloud region of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function.\n */\n FAAS_INVOKED_REGION: 'faas.invoked_region';\n\n /**\n * Transport protocol used. See note below.\n */\n NET_TRANSPORT: 'net.transport';\n\n /**\n * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6).\n */\n NET_PEER_IP: 'net.peer.ip';\n\n /**\n * Remote port number.\n */\n NET_PEER_PORT: 'net.peer.port';\n\n /**\n * Remote hostname or similar, see note below.\n */\n NET_PEER_NAME: 'net.peer.name';\n\n /**\n * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host.\n */\n NET_HOST_IP: 'net.host.ip';\n\n /**\n * Like `net.peer.port` but for the host port.\n */\n NET_HOST_PORT: 'net.host.port';\n\n /**\n * Local hostname or similar, see note below.\n */\n NET_HOST_NAME: 'net.host.name';\n\n /**\n * The internet connection type currently being used by the host.\n */\n NET_HOST_CONNECTION_TYPE: 'net.host.connection.type';\n\n /**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n */\n NET_HOST_CONNECTION_SUBTYPE: 'net.host.connection.subtype';\n\n /**\n * The name of the mobile carrier.\n */\n NET_HOST_CARRIER_NAME: 'net.host.carrier.name';\n\n /**\n * The mobile carrier country code.\n */\n NET_HOST_CARRIER_MCC: 'net.host.carrier.mcc';\n\n /**\n * The mobile carrier network code.\n */\n NET_HOST_CARRIER_MNC: 'net.host.carrier.mnc';\n\n /**\n * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network.\n */\n NET_HOST_CARRIER_ICC: 'net.host.carrier.icc';\n\n /**\n * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any.\n */\n PEER_SERVICE: 'peer.service';\n\n /**\n * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system.\n */\n ENDUSER_ID: 'enduser.id';\n\n /**\n * Actual/assumed role the client is making the request under extracted from token or application security context.\n */\n ENDUSER_ROLE: 'enduser.role';\n\n /**\n * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html).\n */\n ENDUSER_SCOPE: 'enduser.scope';\n\n /**\n * Current "managed" thread ID (as opposed to OS thread ID).\n */\n THREAD_ID: 'thread.id';\n\n /**\n * Current thread name.\n */\n THREAD_NAME: 'thread.name';\n\n /**\n * The method or function name, or equivalent (usually rightmost part of the code unit's name).\n */\n CODE_FUNCTION: 'code.function';\n\n /**\n * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit.\n */\n CODE_NAMESPACE: 'code.namespace';\n\n /**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path).\n */\n CODE_FILEPATH: 'code.filepath';\n\n /**\n * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`.\n */\n CODE_LINENO: 'code.lineno';\n\n /**\n * HTTP request method.\n */\n HTTP_METHOD: 'http.method';\n\n /**\n * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless.\n *\n * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`.\n */\n HTTP_URL: 'http.url';\n\n /**\n * The full request target as passed in a HTTP request line or equivalent.\n */\n HTTP_TARGET: 'http.target';\n\n /**\n * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note.\n *\n * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set.\n */\n HTTP_HOST: 'http.host';\n\n /**\n * The URI scheme identifying the used protocol.\n */\n HTTP_SCHEME: 'http.scheme';\n\n /**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n */\n HTTP_STATUS_CODE: 'http.status_code';\n\n /**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n */\n HTTP_FLAVOR: 'http.flavor';\n\n /**\n * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client.\n */\n HTTP_USER_AGENT: 'http.user_agent';\n\n /**\n * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size.\n */\n HTTP_REQUEST_CONTENT_LENGTH: 'http.request_content_length';\n\n /**\n * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used.\n */\n HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED: 'http.request_content_length_uncompressed';\n\n /**\n * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size.\n */\n HTTP_RESPONSE_CONTENT_LENGTH: 'http.response_content_length';\n\n /**\n * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used.\n */\n HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED: 'http.response_content_length_uncompressed';\n\n /**\n * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead).\n *\n * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available.\n */\n HTTP_SERVER_NAME: 'http.server_name';\n\n /**\n * The matched route (path template).\n */\n HTTP_ROUTE: 'http.route';\n\n /**\n * The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)).\n *\n * Note: This is not necessarily the same as `net.peer.ip`, which would\nidentify the network-level peer, which may be a proxy.\n\nThis attribute should be set when a source of information different\nfrom the one used for `net.peer.ip`, is available even if that other\nsource just confirms the same value as `net.peer.ip`.\nRationale: For `net.peer.ip`, one typically does not know if it\ncomes from a proxy, reverse proxy, or the actual client. Setting\n`http.client_ip` when it's the same as `net.peer.ip` means that\none is at least somewhat confident that the address is not that of\nthe closest proxy.\n */\n HTTP_CLIENT_IP: 'http.client_ip';\n\n /**\n * The keys in the `RequestItems` object field.\n */\n AWS_DYNAMODB_TABLE_NAMES: 'aws.dynamodb.table_names';\n\n /**\n * The JSON-serialized value of each item in the `ConsumedCapacity` response field.\n */\n AWS_DYNAMODB_CONSUMED_CAPACITY: 'aws.dynamodb.consumed_capacity';\n\n /**\n * The JSON-serialized value of the `ItemCollectionMetrics` response field.\n */\n AWS_DYNAMODB_ITEM_COLLECTION_METRICS: 'aws.dynamodb.item_collection_metrics';\n\n /**\n * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter.\n */\n AWS_DYNAMODB_PROVISIONED_READ_CAPACITY: 'aws.dynamodb.provisioned_read_capacity';\n\n /**\n * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter.\n */\n AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY: 'aws.dynamodb.provisioned_write_capacity';\n\n /**\n * The value of the `ConsistentRead` request parameter.\n */\n AWS_DYNAMODB_CONSISTENT_READ: 'aws.dynamodb.consistent_read';\n\n /**\n * The value of the `ProjectionExpression` request parameter.\n */\n AWS_DYNAMODB_PROJECTION: 'aws.dynamodb.projection';\n\n /**\n * The value of the `Limit` request parameter.\n */\n AWS_DYNAMODB_LIMIT: 'aws.dynamodb.limit';\n\n /**\n * The value of the `AttributesToGet` request parameter.\n */\n AWS_DYNAMODB_ATTRIBUTES_TO_GET: 'aws.dynamodb.attributes_to_get';\n\n /**\n * The value of the `IndexName` request parameter.\n */\n AWS_DYNAMODB_INDEX_NAME: 'aws.dynamodb.index_name';\n\n /**\n * The value of the `Select` request parameter.\n */\n AWS_DYNAMODB_SELECT: 'aws.dynamodb.select';\n\n /**\n * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field.\n */\n AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES: 'aws.dynamodb.global_secondary_indexes';\n\n /**\n * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field.\n */\n AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES: 'aws.dynamodb.local_secondary_indexes';\n\n /**\n * The value of the `ExclusiveStartTableName` request parameter.\n */\n AWS_DYNAMODB_EXCLUSIVE_START_TABLE: 'aws.dynamodb.exclusive_start_table';\n\n /**\n * The the number of items in the `TableNames` response parameter.\n */\n AWS_DYNAMODB_TABLE_COUNT: 'aws.dynamodb.table_count';\n\n /**\n * The value of the `ScanIndexForward` request parameter.\n */\n AWS_DYNAMODB_SCAN_FORWARD: 'aws.dynamodb.scan_forward';\n\n /**\n * The value of the `Segment` request parameter.\n */\n AWS_DYNAMODB_SEGMENT: 'aws.dynamodb.segment';\n\n /**\n * The value of the `TotalSegments` request parameter.\n */\n AWS_DYNAMODB_TOTAL_SEGMENTS: 'aws.dynamodb.total_segments';\n\n /**\n * The value of the `Count` response parameter.\n */\n AWS_DYNAMODB_COUNT: 'aws.dynamodb.count';\n\n /**\n * The value of the `ScannedCount` response parameter.\n */\n AWS_DYNAMODB_SCANNED_COUNT: 'aws.dynamodb.scanned_count';\n\n /**\n * The JSON-serialized value of each item in the `AttributeDefinitions` request field.\n */\n AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS: 'aws.dynamodb.attribute_definitions';\n\n /**\n * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field.\n */\n AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES: 'aws.dynamodb.global_secondary_index_updates';\n\n /**\n * A string identifying the messaging system.\n */\n MESSAGING_SYSTEM: 'messaging.system';\n\n /**\n * The message destination name. This might be equal to the span name but is required nevertheless.\n */\n MESSAGING_DESTINATION: 'messaging.destination';\n\n /**\n * The kind of message destination.\n */\n MESSAGING_DESTINATION_KIND: 'messaging.destination_kind';\n\n /**\n * A boolean that is true if the message destination is temporary.\n */\n MESSAGING_TEMP_DESTINATION: 'messaging.temp_destination';\n\n /**\n * The name of the transport protocol.\n */\n MESSAGING_PROTOCOL: 'messaging.protocol';\n\n /**\n * The version of the transport protocol.\n */\n MESSAGING_PROTOCOL_VERSION: 'messaging.protocol_version';\n\n /**\n * Connection string.\n */\n MESSAGING_URL: 'messaging.url';\n\n /**\n * A value used by the messaging system as an identifier for the message, represented as a string.\n */\n MESSAGING_MESSAGE_ID: 'messaging.message_id';\n\n /**\n * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID".\n */\n MESSAGING_CONVERSATION_ID: 'messaging.conversation_id';\n\n /**\n * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported.\n */\n MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES: 'messaging.message_payload_size_bytes';\n\n /**\n * The compressed size of the message payload in bytes.\n */\n MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES: 'messaging.message_payload_compressed_size_bytes';\n\n /**\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n */\n MESSAGING_OPERATION: 'messaging.operation';\n\n /**\n * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message.\n */\n MESSAGING_CONSUMER_ID: 'messaging.consumer_id';\n\n /**\n * RabbitMQ message routing key.\n */\n MESSAGING_RABBITMQ_ROUTING_KEY: 'messaging.rabbitmq.routing_key';\n\n /**\n * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set.\n *\n * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value.\n */\n MESSAGING_KAFKA_MESSAGE_KEY: 'messaging.kafka.message_key';\n\n /**\n * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers.\n */\n MESSAGING_KAFKA_CONSUMER_GROUP: 'messaging.kafka.consumer_group';\n\n /**\n * Client Id for the Consumer or Producer that is handling the message.\n */\n MESSAGING_KAFKA_CLIENT_ID: 'messaging.kafka.client_id';\n\n /**\n * Partition the message is sent to.\n */\n MESSAGING_KAFKA_PARTITION: 'messaging.kafka.partition';\n\n /**\n * A boolean that is true if the message is a tombstone.\n */\n MESSAGING_KAFKA_TOMBSTONE: 'messaging.kafka.tombstone';\n\n /**\n * A string identifying the remoting system.\n */\n RPC_SYSTEM: 'rpc.system';\n\n /**\n * The full (logical) name of the service being called, including its package name, if applicable.\n *\n * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side).\n */\n RPC_SERVICE: 'rpc.service';\n\n /**\n * The name of the (logical) method being called, must be equal to the $method part in the span name.\n *\n * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side).\n */\n RPC_METHOD: 'rpc.method';\n\n /**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n */\n RPC_GRPC_STATUS_CODE: 'rpc.grpc.status_code';\n\n /**\n * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted.\n */\n RPC_JSONRPC_VERSION: 'rpc.jsonrpc.version';\n\n /**\n * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification.\n */\n RPC_JSONRPC_REQUEST_ID: 'rpc.jsonrpc.request_id';\n\n /**\n * `error.code` property of response if it is an error response.\n */\n RPC_JSONRPC_ERROR_CODE: 'rpc.jsonrpc.error_code';\n\n /**\n * `error.message` property of response if it is an error response.\n */\n RPC_JSONRPC_ERROR_MESSAGE: 'rpc.jsonrpc.error_message';\n\n /**\n * Whether this is a received or sent message.\n */\n MESSAGE_TYPE: 'message.type';\n\n /**\n * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message.\n *\n * Note: This way we guarantee that the values will be consistent between different implementations.\n */\n MESSAGE_ID: 'message.id';\n\n /**\n * Compressed size of the message in bytes.\n */\n MESSAGE_COMPRESSED_SIZE: 'message.compressed_size';\n\n /**\n * Uncompressed size of the message in bytes.\n */\n MESSAGE_UNCOMPRESSED_SIZE: 'message.uncompressed_size';\n};\n\n/**\n * Create exported Value Map for SemanticAttributes values\n * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification\n */\nexport const SemanticAttributes: SemanticAttributes =\n /*#__PURE__*/ createConstMap([\n TMP_AWS_LAMBDA_INVOKED_ARN,\n TMP_DB_SYSTEM,\n TMP_DB_CONNECTION_STRING,\n TMP_DB_USER,\n TMP_DB_JDBC_DRIVER_CLASSNAME,\n TMP_DB_NAME,\n TMP_DB_STATEMENT,\n TMP_DB_OPERATION,\n TMP_DB_MSSQL_INSTANCE_NAME,\n TMP_DB_CASSANDRA_KEYSPACE,\n TMP_DB_CASSANDRA_PAGE_SIZE,\n TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,\n TMP_DB_CASSANDRA_TABLE,\n TMP_DB_CASSANDRA_IDEMPOTENCE,\n TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,\n TMP_DB_CASSANDRA_COORDINATOR_ID,\n TMP_DB_CASSANDRA_COORDINATOR_DC,\n TMP_DB_HBASE_NAMESPACE,\n TMP_DB_REDIS_DATABASE_INDEX,\n TMP_DB_MONGODB_COLLECTION,\n TMP_DB_SQL_TABLE,\n TMP_EXCEPTION_TYPE,\n TMP_EXCEPTION_MESSAGE,\n TMP_EXCEPTION_STACKTRACE,\n TMP_EXCEPTION_ESCAPED,\n TMP_FAAS_TRIGGER,\n TMP_FAAS_EXECUTION,\n TMP_FAAS_DOCUMENT_COLLECTION,\n TMP_FAAS_DOCUMENT_OPERATION,\n TMP_FAAS_DOCUMENT_TIME,\n TMP_FAAS_DOCUMENT_NAME,\n TMP_FAAS_TIME,\n TMP_FAAS_CRON,\n TMP_FAAS_COLDSTART,\n TMP_FAAS_INVOKED_NAME,\n TMP_FAAS_INVOKED_PROVIDER,\n TMP_FAAS_INVOKED_REGION,\n TMP_NET_TRANSPORT,\n TMP_NET_PEER_IP,\n TMP_NET_PEER_PORT,\n TMP_NET_PEER_NAME,\n TMP_NET_HOST_IP,\n TMP_NET_HOST_PORT,\n TMP_NET_HOST_NAME,\n TMP_NET_HOST_CONNECTION_TYPE,\n TMP_NET_HOST_CONNECTION_SUBTYPE,\n TMP_NET_HOST_CARRIER_NAME,\n TMP_NET_HOST_CARRIER_MCC,\n TMP_NET_HOST_CARRIER_MNC,\n TMP_NET_HOST_CARRIER_ICC,\n TMP_PEER_SERVICE,\n TMP_ENDUSER_ID,\n TMP_ENDUSER_ROLE,\n TMP_ENDUSER_SCOPE,\n TMP_THREAD_ID,\n TMP_THREAD_NAME,\n TMP_CODE_FUNCTION,\n TMP_CODE_NAMESPACE,\n TMP_CODE_FILEPATH,\n TMP_CODE_LINENO,\n TMP_HTTP_METHOD,\n TMP_HTTP_URL,\n TMP_HTTP_TARGET,\n TMP_HTTP_HOST,\n TMP_HTTP_SCHEME,\n TMP_HTTP_STATUS_CODE,\n TMP_HTTP_FLAVOR,\n TMP_HTTP_USER_AGENT,\n TMP_HTTP_REQUEST_CONTENT_LENGTH,\n TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,\n TMP_HTTP_RESPONSE_CONTENT_LENGTH,\n TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,\n TMP_HTTP_SERVER_NAME,\n TMP_HTTP_ROUTE,\n TMP_HTTP_CLIENT_IP,\n TMP_AWS_DYNAMODB_TABLE_NAMES,\n TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,\n TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,\n TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,\n TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,\n TMP_AWS_DYNAMODB_CONSISTENT_READ,\n TMP_AWS_DYNAMODB_PROJECTION,\n TMP_AWS_DYNAMODB_LIMIT,\n TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,\n TMP_AWS_DYNAMODB_INDEX_NAME,\n TMP_AWS_DYNAMODB_SELECT,\n TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,\n TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,\n TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,\n TMP_AWS_DYNAMODB_TABLE_COUNT,\n TMP_AWS_DYNAMODB_SCAN_FORWARD,\n TMP_AWS_DYNAMODB_SEGMENT,\n TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,\n TMP_AWS_DYNAMODB_COUNT,\n TMP_AWS_DYNAMODB_SCANNED_COUNT,\n TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,\n TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,\n TMP_MESSAGING_SYSTEM,\n TMP_MESSAGING_DESTINATION,\n TMP_MESSAGING_DESTINATION_KIND,\n TMP_MESSAGING_TEMP_DESTINATION,\n TMP_MESSAGING_PROTOCOL,\n TMP_MESSAGING_PROTOCOL_VERSION,\n TMP_MESSAGING_URL,\n TMP_MESSAGING_MESSAGE_ID,\n TMP_MESSAGING_CONVERSATION_ID,\n TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,\n TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,\n TMP_MESSAGING_OPERATION,\n TMP_MESSAGING_CONSUMER_ID,\n TMP_MESSAGING_RABBITMQ_ROUTING_KEY,\n TMP_MESSAGING_KAFKA_MESSAGE_KEY,\n TMP_MESSAGING_KAFKA_CONSUMER_GROUP,\n TMP_MESSAGING_KAFKA_CLIENT_ID,\n TMP_MESSAGING_KAFKA_PARTITION,\n TMP_MESSAGING_KAFKA_TOMBSTONE,\n TMP_RPC_SYSTEM,\n TMP_RPC_SERVICE,\n TMP_RPC_METHOD,\n TMP_RPC_GRPC_STATUS_CODE,\n TMP_RPC_JSONRPC_VERSION,\n TMP_RPC_JSONRPC_REQUEST_ID,\n TMP_RPC_JSONRPC_ERROR_CODE,\n TMP_RPC_JSONRPC_ERROR_MESSAGE,\n TMP_MESSAGE_TYPE,\n TMP_MESSAGE_ID,\n TMP_MESSAGE_COMPRESSED_SIZE,\n TMP_MESSAGE_UNCOMPRESSED_SIZE,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for DbSystemValues enum definition\n *\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_DBSYSTEMVALUES_OTHER_SQL = 'other_sql';\nconst TMP_DBSYSTEMVALUES_MSSQL = 'mssql';\nconst TMP_DBSYSTEMVALUES_MYSQL = 'mysql';\nconst TMP_DBSYSTEMVALUES_ORACLE = 'oracle';\nconst TMP_DBSYSTEMVALUES_DB2 = 'db2';\nconst TMP_DBSYSTEMVALUES_POSTGRESQL = 'postgresql';\nconst TMP_DBSYSTEMVALUES_REDSHIFT = 'redshift';\nconst TMP_DBSYSTEMVALUES_HIVE = 'hive';\nconst TMP_DBSYSTEMVALUES_CLOUDSCAPE = 'cloudscape';\nconst TMP_DBSYSTEMVALUES_HSQLDB = 'hsqldb';\nconst TMP_DBSYSTEMVALUES_PROGRESS = 'progress';\nconst TMP_DBSYSTEMVALUES_MAXDB = 'maxdb';\nconst TMP_DBSYSTEMVALUES_HANADB = 'hanadb';\nconst TMP_DBSYSTEMVALUES_INGRES = 'ingres';\nconst TMP_DBSYSTEMVALUES_FIRSTSQL = 'firstsql';\nconst TMP_DBSYSTEMVALUES_EDB = 'edb';\nconst TMP_DBSYSTEMVALUES_CACHE = 'cache';\nconst TMP_DBSYSTEMVALUES_ADABAS = 'adabas';\nconst TMP_DBSYSTEMVALUES_FIREBIRD = 'firebird';\nconst TMP_DBSYSTEMVALUES_DERBY = 'derby';\nconst TMP_DBSYSTEMVALUES_FILEMAKER = 'filemaker';\nconst TMP_DBSYSTEMVALUES_INFORMIX = 'informix';\nconst TMP_DBSYSTEMVALUES_INSTANTDB = 'instantdb';\nconst TMP_DBSYSTEMVALUES_INTERBASE = 'interbase';\nconst TMP_DBSYSTEMVALUES_MARIADB = 'mariadb';\nconst TMP_DBSYSTEMVALUES_NETEZZA = 'netezza';\nconst TMP_DBSYSTEMVALUES_PERVASIVE = 'pervasive';\nconst TMP_DBSYSTEMVALUES_POINTBASE = 'pointbase';\nconst TMP_DBSYSTEMVALUES_SQLITE = 'sqlite';\nconst TMP_DBSYSTEMVALUES_SYBASE = 'sybase';\nconst TMP_DBSYSTEMVALUES_TERADATA = 'teradata';\nconst TMP_DBSYSTEMVALUES_VERTICA = 'vertica';\nconst TMP_DBSYSTEMVALUES_H2 = 'h2';\nconst TMP_DBSYSTEMVALUES_COLDFUSION = 'coldfusion';\nconst TMP_DBSYSTEMVALUES_CASSANDRA = 'cassandra';\nconst TMP_DBSYSTEMVALUES_HBASE = 'hbase';\nconst TMP_DBSYSTEMVALUES_MONGODB = 'mongodb';\nconst TMP_DBSYSTEMVALUES_REDIS = 'redis';\nconst TMP_DBSYSTEMVALUES_COUCHBASE = 'couchbase';\nconst TMP_DBSYSTEMVALUES_COUCHDB = 'couchdb';\nconst TMP_DBSYSTEMVALUES_COSMOSDB = 'cosmosdb';\nconst TMP_DBSYSTEMVALUES_DYNAMODB = 'dynamodb';\nconst TMP_DBSYSTEMVALUES_NEO4J = 'neo4j';\nconst TMP_DBSYSTEMVALUES_GEODE = 'geode';\nconst TMP_DBSYSTEMVALUES_ELASTICSEARCH = 'elasticsearch';\nconst TMP_DBSYSTEMVALUES_MEMCACHED = 'memcached';\nconst TMP_DBSYSTEMVALUES_COCKROACHDB = 'cockroachdb';\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_OTHER_SQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MSSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MYSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_ORACLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_DB2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_POSTGRESQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_REDSHIFT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_HIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_CLOUDSCAPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_HSQLDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_PROGRESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MAXDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_HANADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_INGRES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_FIRSTSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_EDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_CACHE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_ADABAS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_FIREBIRD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_DERBY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_FILEMAKER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_INFORMIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_INSTANTDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_INTERBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MARIADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_NETEZZA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_PERVASIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_POINTBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_SQLITE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_SYBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_TERADATA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_VERTICA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_H2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COLDFUSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_CASSANDRA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_HBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MONGODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_REDIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COUCHBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COUCHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COSMOSDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_DYNAMODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_NEO4J in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_GEODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_ELASTICSEARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MEMCACHED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COCKROACHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB;\n\n/**\n * Identifies the Values for DbSystemValues enum definition\n *\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification.\n */\nexport type DbSystemValues = {\n /** Some other SQL database. Fallback only. See notes. */\n OTHER_SQL: 'other_sql';\n\n /** Microsoft SQL Server. */\n MSSQL: 'mssql';\n\n /** MySQL. */\n MYSQL: 'mysql';\n\n /** Oracle Database. */\n ORACLE: 'oracle';\n\n /** IBM Db2. */\n DB2: 'db2';\n\n /** PostgreSQL. */\n POSTGRESQL: 'postgresql';\n\n /** Amazon Redshift. */\n REDSHIFT: 'redshift';\n\n /** Apache Hive. */\n HIVE: 'hive';\n\n /** Cloudscape. */\n CLOUDSCAPE: 'cloudscape';\n\n /** HyperSQL DataBase. */\n HSQLDB: 'hsqldb';\n\n /** Progress Database. */\n PROGRESS: 'progress';\n\n /** SAP MaxDB. */\n MAXDB: 'maxdb';\n\n /** SAP HANA. */\n HANADB: 'hanadb';\n\n /** Ingres. */\n INGRES: 'ingres';\n\n /** FirstSQL. */\n FIRSTSQL: 'firstsql';\n\n /** EnterpriseDB. */\n EDB: 'edb';\n\n /** InterSystems Caché. */\n CACHE: 'cache';\n\n /** Adabas (Adaptable Database System). */\n ADABAS: 'adabas';\n\n /** Firebird. */\n FIREBIRD: 'firebird';\n\n /** Apache Derby. */\n DERBY: 'derby';\n\n /** FileMaker. */\n FILEMAKER: 'filemaker';\n\n /** Informix. */\n INFORMIX: 'informix';\n\n /** InstantDB. */\n INSTANTDB: 'instantdb';\n\n /** InterBase. */\n INTERBASE: 'interbase';\n\n /** MariaDB. */\n MARIADB: 'mariadb';\n\n /** Netezza. */\n NETEZZA: 'netezza';\n\n /** Pervasive PSQL. */\n PERVASIVE: 'pervasive';\n\n /** PointBase. */\n POINTBASE: 'pointbase';\n\n /** SQLite. */\n SQLITE: 'sqlite';\n\n /** Sybase. */\n SYBASE: 'sybase';\n\n /** Teradata. */\n TERADATA: 'teradata';\n\n /** Vertica. */\n VERTICA: 'vertica';\n\n /** H2. */\n H2: 'h2';\n\n /** ColdFusion IMQ. */\n COLDFUSION: 'coldfusion';\n\n /** Apache Cassandra. */\n CASSANDRA: 'cassandra';\n\n /** Apache HBase. */\n HBASE: 'hbase';\n\n /** MongoDB. */\n MONGODB: 'mongodb';\n\n /** Redis. */\n REDIS: 'redis';\n\n /** Couchbase. */\n COUCHBASE: 'couchbase';\n\n /** CouchDB. */\n COUCHDB: 'couchdb';\n\n /** Microsoft Azure Cosmos DB. */\n COSMOSDB: 'cosmosdb';\n\n /** Amazon DynamoDB. */\n DYNAMODB: 'dynamodb';\n\n /** Neo4j. */\n NEO4J: 'neo4j';\n\n /** Apache Geode. */\n GEODE: 'geode';\n\n /** Elasticsearch. */\n ELASTICSEARCH: 'elasticsearch';\n\n /** Memcached. */\n MEMCACHED: 'memcached';\n\n /** CockroachDB. */\n COCKROACHDB: 'cockroachdb';\n};\n\n/**\n * The constant map of values for DbSystemValues.\n * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification.\n */\nexport const DbSystemValues: DbSystemValues =\n /*#__PURE__*/ createConstMap([\n TMP_DBSYSTEMVALUES_OTHER_SQL,\n TMP_DBSYSTEMVALUES_MSSQL,\n TMP_DBSYSTEMVALUES_MYSQL,\n TMP_DBSYSTEMVALUES_ORACLE,\n TMP_DBSYSTEMVALUES_DB2,\n TMP_DBSYSTEMVALUES_POSTGRESQL,\n TMP_DBSYSTEMVALUES_REDSHIFT,\n TMP_DBSYSTEMVALUES_HIVE,\n TMP_DBSYSTEMVALUES_CLOUDSCAPE,\n TMP_DBSYSTEMVALUES_HSQLDB,\n TMP_DBSYSTEMVALUES_PROGRESS,\n TMP_DBSYSTEMVALUES_MAXDB,\n TMP_DBSYSTEMVALUES_HANADB,\n TMP_DBSYSTEMVALUES_INGRES,\n TMP_DBSYSTEMVALUES_FIRSTSQL,\n TMP_DBSYSTEMVALUES_EDB,\n TMP_DBSYSTEMVALUES_CACHE,\n TMP_DBSYSTEMVALUES_ADABAS,\n TMP_DBSYSTEMVALUES_FIREBIRD,\n TMP_DBSYSTEMVALUES_DERBY,\n TMP_DBSYSTEMVALUES_FILEMAKER,\n TMP_DBSYSTEMVALUES_INFORMIX,\n TMP_DBSYSTEMVALUES_INSTANTDB,\n TMP_DBSYSTEMVALUES_INTERBASE,\n TMP_DBSYSTEMVALUES_MARIADB,\n TMP_DBSYSTEMVALUES_NETEZZA,\n TMP_DBSYSTEMVALUES_PERVASIVE,\n TMP_DBSYSTEMVALUES_POINTBASE,\n TMP_DBSYSTEMVALUES_SQLITE,\n TMP_DBSYSTEMVALUES_SYBASE,\n TMP_DBSYSTEMVALUES_TERADATA,\n TMP_DBSYSTEMVALUES_VERTICA,\n TMP_DBSYSTEMVALUES_H2,\n TMP_DBSYSTEMVALUES_COLDFUSION,\n TMP_DBSYSTEMVALUES_CASSANDRA,\n TMP_DBSYSTEMVALUES_HBASE,\n TMP_DBSYSTEMVALUES_MONGODB,\n TMP_DBSYSTEMVALUES_REDIS,\n TMP_DBSYSTEMVALUES_COUCHBASE,\n TMP_DBSYSTEMVALUES_COUCHDB,\n TMP_DBSYSTEMVALUES_COSMOSDB,\n TMP_DBSYSTEMVALUES_DYNAMODB,\n TMP_DBSYSTEMVALUES_NEO4J,\n TMP_DBSYSTEMVALUES_GEODE,\n TMP_DBSYSTEMVALUES_ELASTICSEARCH,\n TMP_DBSYSTEMVALUES_MEMCACHED,\n TMP_DBSYSTEMVALUES_COCKROACHDB,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for DbCassandraConsistencyLevelValues enum definition\n *\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = 'all';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = 'each_quorum';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = 'quorum';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = 'local_quorum';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = 'one';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = 'two';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = 'three';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = 'local_one';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = 'any';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = 'serial';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = 'local_serial';\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ALL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_ALL =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_EACH_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_ONE =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_TWO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_TWO =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_THREE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_THREE =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ANY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_ANY =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL;\n\n/**\n * Identifies the Values for DbCassandraConsistencyLevelValues enum definition\n *\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification.\n */\nexport type DbCassandraConsistencyLevelValues = {\n /** all. */\n ALL: 'all';\n\n /** each_quorum. */\n EACH_QUORUM: 'each_quorum';\n\n /** quorum. */\n QUORUM: 'quorum';\n\n /** local_quorum. */\n LOCAL_QUORUM: 'local_quorum';\n\n /** one. */\n ONE: 'one';\n\n /** two. */\n TWO: 'two';\n\n /** three. */\n THREE: 'three';\n\n /** local_one. */\n LOCAL_ONE: 'local_one';\n\n /** any. */\n ANY: 'any';\n\n /** serial. */\n SERIAL: 'serial';\n\n /** local_serial. */\n LOCAL_SERIAL: 'local_serial';\n};\n\n/**\n * The constant map of values for DbCassandraConsistencyLevelValues.\n * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification.\n */\nexport const DbCassandraConsistencyLevelValues: DbCassandraConsistencyLevelValues =\n /*#__PURE__*/ createConstMap([\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for FaasTriggerValues enum definition\n *\n * Type of the trigger on which the function is executed.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_FAASTRIGGERVALUES_DATASOURCE = 'datasource';\nconst TMP_FAASTRIGGERVALUES_HTTP = 'http';\nconst TMP_FAASTRIGGERVALUES_PUBSUB = 'pubsub';\nconst TMP_FAASTRIGGERVALUES_TIMER = 'timer';\nconst TMP_FAASTRIGGERVALUES_OTHER = 'other';\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_DATASOURCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_HTTP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_PUBSUB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_TIMER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER;\n\n/**\n * Identifies the Values for FaasTriggerValues enum definition\n *\n * Type of the trigger on which the function is executed.\n * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification.\n */\nexport type FaasTriggerValues = {\n /** A response to some data source operation such as a database or filesystem read/write. */\n DATASOURCE: 'datasource';\n\n /** To provide an answer to an inbound HTTP request. */\n HTTP: 'http';\n\n /** A function is set to be executed when messages are sent to a messaging system. */\n PUBSUB: 'pubsub';\n\n /** A function is scheduled to be executed regularly. */\n TIMER: 'timer';\n\n /** If none of the others apply. */\n OTHER: 'other';\n};\n\n/**\n * The constant map of values for FaasTriggerValues.\n * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification.\n */\nexport const FaasTriggerValues: FaasTriggerValues =\n /*#__PURE__*/ createConstMap([\n TMP_FAASTRIGGERVALUES_DATASOURCE,\n TMP_FAASTRIGGERVALUES_HTTP,\n TMP_FAASTRIGGERVALUES_PUBSUB,\n TMP_FAASTRIGGERVALUES_TIMER,\n TMP_FAASTRIGGERVALUES_OTHER,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for FaasDocumentOperationValues enum definition\n *\n * Describes the type of the operation that was performed on the data.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = 'insert';\nconst TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = 'edit';\nconst TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = 'delete';\n\n/**\n * Describes the type of the operation that was performed on the data.\n *\n * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_INSERT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASDOCUMENTOPERATIONVALUES_INSERT =\n TMP_FAASDOCUMENTOPERATIONVALUES_INSERT;\n\n/**\n * Describes the type of the operation that was performed on the data.\n *\n * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_EDIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASDOCUMENTOPERATIONVALUES_EDIT =\n TMP_FAASDOCUMENTOPERATIONVALUES_EDIT;\n\n/**\n * Describes the type of the operation that was performed on the data.\n *\n * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_DELETE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASDOCUMENTOPERATIONVALUES_DELETE =\n TMP_FAASDOCUMENTOPERATIONVALUES_DELETE;\n\n/**\n * Identifies the Values for FaasDocumentOperationValues enum definition\n *\n * Describes the type of the operation that was performed on the data.\n * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification.\n */\nexport type FaasDocumentOperationValues = {\n /** When a new object is created. */\n INSERT: 'insert';\n\n /** When an object is modified. */\n EDIT: 'edit';\n\n /** When an object is deleted. */\n DELETE: 'delete';\n};\n\n/**\n * The constant map of values for FaasDocumentOperationValues.\n * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification.\n */\nexport const FaasDocumentOperationValues: FaasDocumentOperationValues =\n /*#__PURE__*/ createConstMap([\n TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,\n TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,\n TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for FaasInvokedProviderValues enum definition\n *\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud';\nconst TMP_FAASINVOKEDPROVIDERVALUES_AWS = 'aws';\nconst TMP_FAASINVOKEDPROVIDERVALUES_AZURE = 'azure';\nconst TMP_FAASINVOKEDPROVIDERVALUES_GCP = 'gcp';\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD =\n TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD;\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS;\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASINVOKEDPROVIDERVALUES_AZURE =\n TMP_FAASINVOKEDPROVIDERVALUES_AZURE;\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP;\n\n/**\n * Identifies the Values for FaasInvokedProviderValues enum definition\n *\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification.\n */\nexport type FaasInvokedProviderValues = {\n /** Alibaba Cloud. */\n ALIBABA_CLOUD: 'alibaba_cloud';\n\n /** Amazon Web Services. */\n AWS: 'aws';\n\n /** Microsoft Azure. */\n AZURE: 'azure';\n\n /** Google Cloud Platform. */\n GCP: 'gcp';\n};\n\n/**\n * The constant map of values for FaasInvokedProviderValues.\n * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification.\n */\nexport const FaasInvokedProviderValues: FaasInvokedProviderValues =\n /*#__PURE__*/ createConstMap([\n TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,\n TMP_FAASINVOKEDPROVIDERVALUES_AWS,\n TMP_FAASINVOKEDPROVIDERVALUES_AZURE,\n TMP_FAASINVOKEDPROVIDERVALUES_GCP,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for NetTransportValues enum definition\n *\n * Transport protocol used. See note below.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_NETTRANSPORTVALUES_IP_TCP = 'ip_tcp';\nconst TMP_NETTRANSPORTVALUES_IP_UDP = 'ip_udp';\nconst TMP_NETTRANSPORTVALUES_IP = 'ip';\nconst TMP_NETTRANSPORTVALUES_UNIX = 'unix';\nconst TMP_NETTRANSPORTVALUES_PIPE = 'pipe';\nconst TMP_NETTRANSPORTVALUES_INPROC = 'inproc';\nconst TMP_NETTRANSPORTVALUES_OTHER = 'other';\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_IP_TCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_IP_UDP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Removed in v1.21.0.\n */\nexport const NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Removed in v1.21.0.\n */\nexport const NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_PIPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_INPROC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER;\n\n/**\n * Identifies the Values for NetTransportValues enum definition\n *\n * Transport protocol used. See note below.\n * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification.\n */\nexport type NetTransportValues = {\n /** ip_tcp. */\n IP_TCP: 'ip_tcp';\n\n /** ip_udp. */\n IP_UDP: 'ip_udp';\n\n /** Another IP-based protocol. */\n IP: 'ip';\n\n /** Unix Domain socket. See below. */\n UNIX: 'unix';\n\n /** Named or anonymous pipe. See note below. */\n PIPE: 'pipe';\n\n /** In-process communication. */\n INPROC: 'inproc';\n\n /** Something else (non IP-based). */\n OTHER: 'other';\n};\n\n/**\n * The constant map of values for NetTransportValues.\n * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification.\n */\nexport const NetTransportValues: NetTransportValues =\n /*#__PURE__*/ createConstMap([\n TMP_NETTRANSPORTVALUES_IP_TCP,\n TMP_NETTRANSPORTVALUES_IP_UDP,\n TMP_NETTRANSPORTVALUES_IP,\n TMP_NETTRANSPORTVALUES_UNIX,\n TMP_NETTRANSPORTVALUES_PIPE,\n TMP_NETTRANSPORTVALUES_INPROC,\n TMP_NETTRANSPORTVALUES_OTHER,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for NetHostConnectionTypeValues enum definition\n *\n * The internet connection type currently being used by the host.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = 'wifi';\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = 'wired';\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = 'cell';\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = 'unavailable';\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = 'unknown';\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIFI in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_WIFI =\n TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIRED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_WIRED =\n TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_CELL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_CELL =\n TMP_NETHOSTCONNECTIONTYPEVALUES_CELL;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE =\n TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_UNKNOWN =\n TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN;\n\n/**\n * Identifies the Values for NetHostConnectionTypeValues enum definition\n *\n * The internet connection type currently being used by the host.\n * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification.\n */\nexport type NetHostConnectionTypeValues = {\n /** wifi. */\n WIFI: 'wifi';\n\n /** wired. */\n WIRED: 'wired';\n\n /** cell. */\n CELL: 'cell';\n\n /** unavailable. */\n UNAVAILABLE: 'unavailable';\n\n /** unknown. */\n UNKNOWN: 'unknown';\n};\n\n/**\n * The constant map of values for NetHostConnectionTypeValues.\n * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification.\n */\nexport const NetHostConnectionTypeValues: NetHostConnectionTypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,\n TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,\n TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,\n TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,\n TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for NetHostConnectionSubtypeValues enum definition\n *\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = 'gprs';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = 'edge';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = 'umts';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = 'cdma';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = 'evdo_0';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = 'evdo_a';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = 'cdma2000_1xrtt';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = 'hsdpa';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = 'hsupa';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = 'hspa';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = 'iden';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = 'evdo_b';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = 'lte';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = 'ehrpd';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = 'hspap';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = 'gsm';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = 'td_scdma';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = 'iwlan';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = 'nr';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = 'nrnsa';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = 'lte_ca';\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GPRS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_GPRS =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EDGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EDGE =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_UMTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_UMTS =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_CDMA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_A in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA2000_1XRTT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSDPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSUPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_HSPA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IDEN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_IDEN =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_B in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_LTE =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EHRPD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPAP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GSM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_GSM =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_TD_SCDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IWLAN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_NR =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NRNSA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE_CA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA;\n\n/**\n * Identifies the Values for NetHostConnectionSubtypeValues enum definition\n *\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification.\n */\nexport type NetHostConnectionSubtypeValues = {\n /** GPRS. */\n GPRS: 'gprs';\n\n /** EDGE. */\n EDGE: 'edge';\n\n /** UMTS. */\n UMTS: 'umts';\n\n /** CDMA. */\n CDMA: 'cdma';\n\n /** EVDO Rel. 0. */\n EVDO_0: 'evdo_0';\n\n /** EVDO Rev. A. */\n EVDO_A: 'evdo_a';\n\n /** CDMA2000 1XRTT. */\n CDMA2000_1XRTT: 'cdma2000_1xrtt';\n\n /** HSDPA. */\n HSDPA: 'hsdpa';\n\n /** HSUPA. */\n HSUPA: 'hsupa';\n\n /** HSPA. */\n HSPA: 'hspa';\n\n /** IDEN. */\n IDEN: 'iden';\n\n /** EVDO Rev. B. */\n EVDO_B: 'evdo_b';\n\n /** LTE. */\n LTE: 'lte';\n\n /** EHRPD. */\n EHRPD: 'ehrpd';\n\n /** HSPAP. */\n HSPAP: 'hspap';\n\n /** GSM. */\n GSM: 'gsm';\n\n /** TD-SCDMA. */\n TD_SCDMA: 'td_scdma';\n\n /** IWLAN. */\n IWLAN: 'iwlan';\n\n /** 5G NR (New Radio). */\n NR: 'nr';\n\n /** 5G NRNSA (New Radio Non-Standalone). */\n NRNSA: 'nrnsa';\n\n /** LTE CA. */\n LTE_CA: 'lte_ca';\n};\n\n/**\n * The constant map of values for NetHostConnectionSubtypeValues.\n * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification.\n */\nexport const NetHostConnectionSubtypeValues: NetHostConnectionSubtypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for HttpFlavorValues enum definition\n *\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_HTTPFLAVORVALUES_HTTP_1_0 = '1.0';\nconst TMP_HTTPFLAVORVALUES_HTTP_1_1 = '1.1';\nconst TMP_HTTPFLAVORVALUES_HTTP_2_0 = '2.0';\nconst TMP_HTTPFLAVORVALUES_SPDY = 'SPDY';\nconst TMP_HTTPFLAVORVALUES_QUIC = 'QUIC';\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_1 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_2_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_SPDY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_QUIC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC;\n\n/**\n * Identifies the Values for HttpFlavorValues enum definition\n *\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification.\n */\nexport type HttpFlavorValues = {\n /** HTTP 1.0. */\n HTTP_1_0: '1.0';\n\n /** HTTP 1.1. */\n HTTP_1_1: '1.1';\n\n /** HTTP 2. */\n HTTP_2_0: '2.0';\n\n /** SPDY protocol. */\n SPDY: 'SPDY';\n\n /** QUIC protocol. */\n QUIC: 'QUIC';\n};\n\n/**\n * The constant map of values for HttpFlavorValues.\n * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification.\n */\nexport const HttpFlavorValues: HttpFlavorValues = {\n HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0,\n HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1,\n HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0,\n SPDY: TMP_HTTPFLAVORVALUES_SPDY,\n QUIC: TMP_HTTPFLAVORVALUES_QUIC,\n};\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for MessagingDestinationKindValues enum definition\n *\n * The kind of message destination.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = 'queue';\nconst TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = 'topic';\n\n/**\n * The kind of message destination.\n *\n * @deprecated Removed in semconv v1.20.0.\n */\nexport const MESSAGINGDESTINATIONKINDVALUES_QUEUE =\n TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE;\n\n/**\n * The kind of message destination.\n *\n * @deprecated Removed in semconv v1.20.0.\n */\nexport const MESSAGINGDESTINATIONKINDVALUES_TOPIC =\n TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC;\n\n/**\n * Identifies the Values for MessagingDestinationKindValues enum definition\n *\n * The kind of message destination.\n * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification.\n */\nexport type MessagingDestinationKindValues = {\n /** A message sent to a queue. */\n QUEUE: 'queue';\n\n /** A message sent to a topic. */\n TOPIC: 'topic';\n};\n\n/**\n * The constant map of values for MessagingDestinationKindValues.\n * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification.\n */\nexport const MessagingDestinationKindValues: MessagingDestinationKindValues =\n /*#__PURE__*/ createConstMap([\n TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,\n TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for MessagingOperationValues enum definition\n *\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_MESSAGINGOPERATIONVALUES_RECEIVE = 'receive';\nconst TMP_MESSAGINGOPERATIONVALUES_PROCESS = 'process';\n\n/**\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n *\n * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_RECEIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const MESSAGINGOPERATIONVALUES_RECEIVE =\n TMP_MESSAGINGOPERATIONVALUES_RECEIVE;\n\n/**\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n *\n * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_PROCESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const MESSAGINGOPERATIONVALUES_PROCESS =\n TMP_MESSAGINGOPERATIONVALUES_PROCESS;\n\n/**\n * Identifies the Values for MessagingOperationValues enum definition\n *\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification.\n */\nexport type MessagingOperationValues = {\n /** receive. */\n RECEIVE: 'receive';\n\n /** process. */\n PROCESS: 'process';\n};\n\n/**\n * The constant map of values for MessagingOperationValues.\n * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification.\n */\nexport const MessagingOperationValues: MessagingOperationValues =\n /*#__PURE__*/ createConstMap([\n TMP_MESSAGINGOPERATIONVALUES_RECEIVE,\n TMP_MESSAGINGOPERATIONVALUES_PROCESS,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for RpcGrpcStatusCodeValues enum definition\n *\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_RPCGRPCSTATUSCODEVALUES_OK = 0;\nconst TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1;\nconst TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2;\nconst TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3;\nconst TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4;\nconst TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5;\nconst TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6;\nconst TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7;\nconst TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8;\nconst TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9;\nconst TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10;\nconst TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11;\nconst TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12;\nconst TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13;\nconst TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14;\nconst TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15;\nconst TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_CANCELLED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_CANCELLED =\n TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_UNKNOWN =\n TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INVALID_ARGUMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT =\n TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DEADLINE_EXCEEDED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED =\n TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_NOT_FOUND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_NOT_FOUND =\n TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ALREADY_EXISTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS =\n TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_PERMISSION_DENIED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED =\n TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_RESOURCE_EXHAUSTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED =\n TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_FAILED_PRECONDITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION =\n TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ABORTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_ABORTED =\n TMP_RPCGRPCSTATUSCODEVALUES_ABORTED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OUT_OF_RANGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE =\n TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNIMPLEMENTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED =\n TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INTERNAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_INTERNAL =\n TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_UNAVAILABLE =\n TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DATA_LOSS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_DATA_LOSS =\n TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAUTHENTICATED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED =\n TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED;\n\n/**\n * Identifies the Values for RpcGrpcStatusCodeValues enum definition\n *\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification.\n */\nexport type RpcGrpcStatusCodeValues = {\n /** OK. */\n OK: 0;\n\n /** CANCELLED. */\n CANCELLED: 1;\n\n /** UNKNOWN. */\n UNKNOWN: 2;\n\n /** INVALID_ARGUMENT. */\n INVALID_ARGUMENT: 3;\n\n /** DEADLINE_EXCEEDED. */\n DEADLINE_EXCEEDED: 4;\n\n /** NOT_FOUND. */\n NOT_FOUND: 5;\n\n /** ALREADY_EXISTS. */\n ALREADY_EXISTS: 6;\n\n /** PERMISSION_DENIED. */\n PERMISSION_DENIED: 7;\n\n /** RESOURCE_EXHAUSTED. */\n RESOURCE_EXHAUSTED: 8;\n\n /** FAILED_PRECONDITION. */\n FAILED_PRECONDITION: 9;\n\n /** ABORTED. */\n ABORTED: 10;\n\n /** OUT_OF_RANGE. */\n OUT_OF_RANGE: 11;\n\n /** UNIMPLEMENTED. */\n UNIMPLEMENTED: 12;\n\n /** INTERNAL. */\n INTERNAL: 13;\n\n /** UNAVAILABLE. */\n UNAVAILABLE: 14;\n\n /** DATA_LOSS. */\n DATA_LOSS: 15;\n\n /** UNAUTHENTICATED. */\n UNAUTHENTICATED: 16;\n};\n\n/**\n * The constant map of values for RpcGrpcStatusCodeValues.\n * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification.\n */\nexport const RpcGrpcStatusCodeValues: RpcGrpcStatusCodeValues = {\n OK: TMP_RPCGRPCSTATUSCODEVALUES_OK,\n CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,\n UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,\n INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,\n DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,\n NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,\n ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,\n PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,\n RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,\n FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,\n ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,\n OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,\n UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,\n INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,\n UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,\n DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,\n UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,\n};\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for MessageTypeValues enum definition\n *\n * Whether this is a received or sent message.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_MESSAGETYPEVALUES_SENT = 'SENT';\nconst TMP_MESSAGETYPEVALUES_RECEIVED = 'RECEIVED';\n\n/**\n * Whether this is a received or sent message.\n *\n * @deprecated Use MESSAGE_TYPE_VALUE_SENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT;\n\n/**\n * Whether this is a received or sent message.\n *\n * @deprecated Use MESSAGE_TYPE_VALUE_RECEIVED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED;\n\n/**\n * Identifies the Values for MessageTypeValues enum definition\n *\n * Whether this is a received or sent message.\n * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification.\n */\nexport type MessageTypeValues = {\n /** sent. */\n SENT: 'SENT';\n\n /** received. */\n RECEIVED: 'RECEIVED';\n};\n\n/**\n * The constant map of values for MessageTypeValues.\n * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification.\n */\nexport const MessageTypeValues: MessageTypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_MESSAGETYPEVALUES_SENT,\n TMP_MESSAGETYPEVALUES_RECEIVED,\n ]);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable no-restricted-syntax --\n * These re-exports are only of constants, only one-level deep at this point,\n * and should not cause problems for tree-shakers.\n */\nexport * from './SemanticAttributes';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createConstMap } from '../internal/utils';\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------\n// Constant values for SemanticResourceAttributes\n//----------------------------------------------------------------------------------------------------------\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_CLOUD_PROVIDER = 'cloud.provider';\nconst TMP_CLOUD_ACCOUNT_ID = 'cloud.account.id';\nconst TMP_CLOUD_REGION = 'cloud.region';\nconst TMP_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone';\nconst TMP_CLOUD_PLATFORM = 'cloud.platform';\nconst TMP_AWS_ECS_CONTAINER_ARN = 'aws.ecs.container.arn';\nconst TMP_AWS_ECS_CLUSTER_ARN = 'aws.ecs.cluster.arn';\nconst TMP_AWS_ECS_LAUNCHTYPE = 'aws.ecs.launchtype';\nconst TMP_AWS_ECS_TASK_ARN = 'aws.ecs.task.arn';\nconst TMP_AWS_ECS_TASK_FAMILY = 'aws.ecs.task.family';\nconst TMP_AWS_ECS_TASK_REVISION = 'aws.ecs.task.revision';\nconst TMP_AWS_EKS_CLUSTER_ARN = 'aws.eks.cluster.arn';\nconst TMP_AWS_LOG_GROUP_NAMES = 'aws.log.group.names';\nconst TMP_AWS_LOG_GROUP_ARNS = 'aws.log.group.arns';\nconst TMP_AWS_LOG_STREAM_NAMES = 'aws.log.stream.names';\nconst TMP_AWS_LOG_STREAM_ARNS = 'aws.log.stream.arns';\nconst TMP_CONTAINER_NAME = 'container.name';\nconst TMP_CONTAINER_ID = 'container.id';\nconst TMP_CONTAINER_RUNTIME = 'container.runtime';\nconst TMP_CONTAINER_IMAGE_NAME = 'container.image.name';\nconst TMP_CONTAINER_IMAGE_TAG = 'container.image.tag';\nconst TMP_DEPLOYMENT_ENVIRONMENT = 'deployment.environment';\nconst TMP_DEVICE_ID = 'device.id';\nconst TMP_DEVICE_MODEL_IDENTIFIER = 'device.model.identifier';\nconst TMP_DEVICE_MODEL_NAME = 'device.model.name';\nconst TMP_FAAS_NAME = 'faas.name';\nconst TMP_FAAS_ID = 'faas.id';\nconst TMP_FAAS_VERSION = 'faas.version';\nconst TMP_FAAS_INSTANCE = 'faas.instance';\nconst TMP_FAAS_MAX_MEMORY = 'faas.max_memory';\nconst TMP_HOST_ID = 'host.id';\nconst TMP_HOST_NAME = 'host.name';\nconst TMP_HOST_TYPE = 'host.type';\nconst TMP_HOST_ARCH = 'host.arch';\nconst TMP_HOST_IMAGE_NAME = 'host.image.name';\nconst TMP_HOST_IMAGE_ID = 'host.image.id';\nconst TMP_HOST_IMAGE_VERSION = 'host.image.version';\nconst TMP_K8S_CLUSTER_NAME = 'k8s.cluster.name';\nconst TMP_K8S_NODE_NAME = 'k8s.node.name';\nconst TMP_K8S_NODE_UID = 'k8s.node.uid';\nconst TMP_K8S_NAMESPACE_NAME = 'k8s.namespace.name';\nconst TMP_K8S_POD_UID = 'k8s.pod.uid';\nconst TMP_K8S_POD_NAME = 'k8s.pod.name';\nconst TMP_K8S_CONTAINER_NAME = 'k8s.container.name';\nconst TMP_K8S_REPLICASET_UID = 'k8s.replicaset.uid';\nconst TMP_K8S_REPLICASET_NAME = 'k8s.replicaset.name';\nconst TMP_K8S_DEPLOYMENT_UID = 'k8s.deployment.uid';\nconst TMP_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name';\nconst TMP_K8S_STATEFULSET_UID = 'k8s.statefulset.uid';\nconst TMP_K8S_STATEFULSET_NAME = 'k8s.statefulset.name';\nconst TMP_K8S_DAEMONSET_UID = 'k8s.daemonset.uid';\nconst TMP_K8S_DAEMONSET_NAME = 'k8s.daemonset.name';\nconst TMP_K8S_JOB_UID = 'k8s.job.uid';\nconst TMP_K8S_JOB_NAME = 'k8s.job.name';\nconst TMP_K8S_CRONJOB_UID = 'k8s.cronjob.uid';\nconst TMP_K8S_CRONJOB_NAME = 'k8s.cronjob.name';\nconst TMP_OS_TYPE = 'os.type';\nconst TMP_OS_DESCRIPTION = 'os.description';\nconst TMP_OS_NAME = 'os.name';\nconst TMP_OS_VERSION = 'os.version';\nconst TMP_PROCESS_PID = 'process.pid';\nconst TMP_PROCESS_EXECUTABLE_NAME = 'process.executable.name';\nconst TMP_PROCESS_EXECUTABLE_PATH = 'process.executable.path';\nconst TMP_PROCESS_COMMAND = 'process.command';\nconst TMP_PROCESS_COMMAND_LINE = 'process.command_line';\nconst TMP_PROCESS_COMMAND_ARGS = 'process.command_args';\nconst TMP_PROCESS_OWNER = 'process.owner';\nconst TMP_PROCESS_RUNTIME_NAME = 'process.runtime.name';\nconst TMP_PROCESS_RUNTIME_VERSION = 'process.runtime.version';\nconst TMP_PROCESS_RUNTIME_DESCRIPTION = 'process.runtime.description';\nconst TMP_SERVICE_NAME = 'service.name';\nconst TMP_SERVICE_NAMESPACE = 'service.namespace';\nconst TMP_SERVICE_INSTANCE_ID = 'service.instance.id';\nconst TMP_SERVICE_VERSION = 'service.version';\nconst TMP_TELEMETRY_SDK_NAME = 'telemetry.sdk.name';\nconst TMP_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language';\nconst TMP_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version';\nconst TMP_TELEMETRY_AUTO_VERSION = 'telemetry.auto.version';\nconst TMP_WEBENGINE_NAME = 'webengine.name';\nconst TMP_WEBENGINE_VERSION = 'webengine.version';\nconst TMP_WEBENGINE_DESCRIPTION = 'webengine.description';\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use ATTR_CLOUD_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER;\n\n/**\n * The cloud account ID the resource is assigned to.\n *\n * @deprecated Use ATTR_CLOUD_ACCOUNT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID;\n\n/**\n * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations).\n *\n * @deprecated Use ATTR_CLOUD_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION;\n\n/**\n * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running.\n *\n * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud.\n *\n * @deprecated Use ATTR_CLOUD_AVAILABILITY_ZONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use ATTR_CLOUD_PLATFORM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM;\n\n/**\n * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html).\n *\n * @deprecated Use ATTR_AWS_ECS_CONTAINER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN;\n\n/**\n * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html).\n *\n * @deprecated Use ATTR_AWS_ECS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN;\n\n/**\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n *\n * @deprecated Use ATTR_AWS_ECS_LAUNCHTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE;\n\n/**\n * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html).\n *\n * @deprecated Use ATTR_AWS_ECS_TASK_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN;\n\n/**\n * The task definition family this task definition is a member of.\n *\n * @deprecated Use ATTR_AWS_ECS_TASK_FAMILY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY;\n\n/**\n * The revision for this task definition.\n *\n * @deprecated Use ATTR_AWS_ECS_TASK_REVISION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION;\n\n/**\n * The ARN of an EKS cluster.\n *\n * @deprecated Use ATTR_AWS_EKS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN;\n\n/**\n * The name(s) of the AWS log group(s) an application is writing to.\n *\n * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group.\n *\n * @deprecated Use ATTR_AWS_LOG_GROUP_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES;\n\n/**\n * The Amazon Resource Name(s) (ARN) of the AWS log group(s).\n *\n * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format).\n *\n * @deprecated Use ATTR_AWS_LOG_GROUP_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS;\n\n/**\n * The name(s) of the AWS log stream(s) an application is writing to.\n *\n * @deprecated Use ATTR_AWS_LOG_STREAM_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES;\n\n/**\n * The ARN(s) of the AWS log stream(s).\n *\n * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream.\n *\n * @deprecated Use ATTR_AWS_LOG_STREAM_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS;\n\n/**\n * Container name.\n *\n * @deprecated Use ATTR_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME;\n\n/**\n * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated.\n *\n * @deprecated Use ATTR_CONTAINER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID;\n\n/**\n * The container runtime managing this container.\n *\n * @deprecated Use ATTR_CONTAINER_RUNTIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME;\n\n/**\n * Name of the image the container was built on.\n *\n * @deprecated Use ATTR_CONTAINER_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME;\n\n/**\n * Container image tag.\n *\n * @deprecated Use ATTR_CONTAINER_IMAGE_TAGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG;\n\n/**\n * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier).\n *\n * @deprecated Use ATTR_DEPLOYMENT_ENVIRONMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT;\n\n/**\n * A unique identifier representing the device.\n *\n * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence.\n *\n * @deprecated Use ATTR_DEVICE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID;\n\n/**\n * The model identifier for the device.\n *\n * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device.\n *\n * @deprecated Use ATTR_DEVICE_MODEL_IDENTIFIER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER;\n\n/**\n * The marketing name for the device model.\n *\n * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative.\n *\n * @deprecated Use ATTR_DEVICE_MODEL_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME;\n\n/**\n * The name of the single function that this runtime instance executes.\n *\n * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes).\n *\n * @deprecated Use ATTR_FAAS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME;\n\n/**\n* The unique ID of the single function that this runtime instance executes.\n*\n* Note: Depending on the cloud provider, use:\n\n* **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html).\nTake care not to use the "invoked ARN" directly but replace any\n[alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple\ndifferent aliases.\n* **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names)\n* **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id).\n\nOn some providers, it may not be possible to determine the full ID at startup,\nwhich is why this field cannot be made required. For example, on AWS the account ID\npart of the ARN is not available without calling another AWS API\nwhich may be deemed too slow for a short-running lambda function.\nAs an alternative, consider setting `faas.id` as a span attribute instead.\n*\n* @deprecated Use ATTR_CLOUD_RESOURCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n*/\nexport const SEMRESATTRS_FAAS_ID = TMP_FAAS_ID;\n\n/**\n* The immutable version of the function being executed.\n*\n* Note: Depending on the cloud provider and platform, use:\n\n* **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html)\n (an integer represented as a decimal string).\n* **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions)\n (i.e., the function name plus the revision suffix).\n* **Google Cloud Functions:** The value of the\n [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically).\n* **Azure Functions:** Not applicable. Do not set this attribute.\n*\n* @deprecated Use ATTR_FAAS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n*/\nexport const SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION;\n\n/**\n * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version.\n *\n * Note: * **AWS Lambda:** Use the (full) log stream name.\n *\n * @deprecated Use ATTR_FAAS_INSTANCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE;\n\n/**\n * The amount of memory available to the serverless function in MiB.\n *\n * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information.\n *\n * @deprecated Use ATTR_FAAS_MAX_MEMORY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY;\n\n/**\n * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider.\n *\n * @deprecated Use ATTR_HOST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_ID = TMP_HOST_ID;\n\n/**\n * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user.\n *\n * @deprecated Use ATTR_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_NAME = TMP_HOST_NAME;\n\n/**\n * Type of host. For Cloud, this must be the machine type.\n *\n * @deprecated Use ATTR_HOST_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use ATTR_HOST_ARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH;\n\n/**\n * Name of the VM image or OS install the host was instantiated from.\n *\n * @deprecated Use ATTR_HOST_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME;\n\n/**\n * VM image ID. For Cloud, this value is from the provider.\n *\n * @deprecated Use ATTR_HOST_IMAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID;\n\n/**\n * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes).\n *\n * @deprecated Use ATTR_HOST_IMAGE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION;\n\n/**\n * The name of the cluster.\n *\n * @deprecated Use ATTR_K8S_CLUSTER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME;\n\n/**\n * The name of the Node.\n *\n * @deprecated Use ATTR_K8S_NODE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME;\n\n/**\n * The UID of the Node.\n *\n * @deprecated Use ATTR_K8S_NODE_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID;\n\n/**\n * The name of the namespace that the pod is running in.\n *\n * @deprecated Use ATTR_K8S_NAMESPACE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME;\n\n/**\n * The UID of the Pod.\n *\n * @deprecated Use ATTR_K8S_POD_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID;\n\n/**\n * The name of the Pod.\n *\n * @deprecated Use ATTR_K8S_POD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME;\n\n/**\n * The name of the Container in a Pod template.\n *\n * @deprecated Use ATTR_K8S_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME;\n\n/**\n * The UID of the ReplicaSet.\n *\n * @deprecated Use ATTR_K8S_REPLICASET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID;\n\n/**\n * The name of the ReplicaSet.\n *\n * @deprecated Use ATTR_K8S_REPLICASET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME;\n\n/**\n * The UID of the Deployment.\n *\n * @deprecated Use ATTR_K8S_DEPLOYMENT_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID;\n\n/**\n * The name of the Deployment.\n *\n * @deprecated Use ATTR_K8S_DEPLOYMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME;\n\n/**\n * The UID of the StatefulSet.\n *\n * @deprecated Use ATTR_K8S_STATEFULSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID;\n\n/**\n * The name of the StatefulSet.\n *\n * @deprecated Use ATTR_K8S_STATEFULSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME;\n\n/**\n * The UID of the DaemonSet.\n *\n * @deprecated Use ATTR_K8S_DAEMONSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID;\n\n/**\n * The name of the DaemonSet.\n *\n * @deprecated Use ATTR_K8S_DAEMONSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME;\n\n/**\n * The UID of the Job.\n *\n * @deprecated Use ATTR_K8S_JOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID;\n\n/**\n * The name of the Job.\n *\n * @deprecated Use ATTR_K8S_JOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME;\n\n/**\n * The UID of the CronJob.\n *\n * @deprecated Use ATTR_K8S_CRONJOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID;\n\n/**\n * The name of the CronJob.\n *\n * @deprecated Use ATTR_K8S_CRONJOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME;\n\n/**\n * The operating system type.\n *\n * @deprecated Use ATTR_OS_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_OS_TYPE = TMP_OS_TYPE;\n\n/**\n * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands.\n *\n * @deprecated Use ATTR_OS_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION;\n\n/**\n * Human readable operating system name.\n *\n * @deprecated Use ATTR_OS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_OS_NAME = TMP_OS_NAME;\n\n/**\n * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes).\n *\n * @deprecated Use ATTR_OS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_OS_VERSION = TMP_OS_VERSION;\n\n/**\n * Process identifier (PID).\n *\n * @deprecated Use ATTR_PROCESS_PID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID;\n\n/**\n * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`.\n *\n * @deprecated Use ATTR_PROCESS_EXECUTABLE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME;\n\n/**\n * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`.\n *\n * @deprecated Use ATTR_PROCESS_EXECUTABLE_PATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH;\n\n/**\n * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`.\n *\n * @deprecated Use ATTR_PROCESS_COMMAND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND;\n\n/**\n * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead.\n *\n * @deprecated Use ATTR_PROCESS_COMMAND_LINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE;\n\n/**\n * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`.\n *\n * @deprecated Use ATTR_PROCESS_COMMAND_ARGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS;\n\n/**\n * The username of the user that owns the process.\n *\n * @deprecated Use ATTR_PROCESS_OWNER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER;\n\n/**\n * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler.\n *\n * @deprecated Use ATTR_PROCESS_RUNTIME_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME;\n\n/**\n * The version of the runtime of this process, as returned by the runtime without modification.\n *\n * @deprecated Use ATTR_PROCESS_RUNTIME_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION;\n\n/**\n * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment.\n *\n * @deprecated Use ATTR_PROCESS_RUNTIME_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION =\n TMP_PROCESS_RUNTIME_DESCRIPTION;\n\n/**\n * Logical name of the service.\n *\n * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`.\n *\n * @deprecated Use ATTR_SERVICE_NAME.\n */\nexport const SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME;\n\n/**\n * A namespace for `service.name`.\n *\n * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n *\n * @deprecated Use ATTR_SERVICE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE;\n\n/**\n * The string ID of the service instance.\n *\n * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations).\n *\n * @deprecated Use ATTR_SERVICE_INSTANCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID;\n\n/**\n * The version string of the service API or implementation.\n *\n * @deprecated Use ATTR_SERVICE_VERSION.\n */\nexport const SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @deprecated Use ATTR_TELEMETRY_SDK_NAME.\n */\nexport const SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use ATTR_TELEMETRY_SDK_LANGUAGE.\n */\nexport const SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @deprecated Use ATTR_TELEMETRY_SDK_VERSION.\n */\nexport const SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION;\n\n/**\n * The version string of the auto instrumentation agent, if used.\n *\n * @deprecated Use ATTR_TELEMETRY_DISTRO_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION;\n\n/**\n * The name of the web engine.\n *\n * @deprecated Use ATTR_WEBENGINE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME;\n\n/**\n * The version of the web engine.\n *\n * @deprecated Use ATTR_WEBENGINE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION;\n\n/**\n * Additional description of the web engine (e.g. detailed version and edition information).\n *\n * @deprecated Use ATTR_WEBENGINE_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION;\n\n/**\n * Definition of available values for SemanticResourceAttributes\n * This type is used for backward compatibility, you should use the individual exported\n * constants SemanticResourceAttributes_XXXXX rather than the exported constant map. As any single reference\n * to a constant map value will result in all strings being included into your bundle.\n * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification.\n */\nexport type SemanticResourceAttributes = {\n /**\n * Name of the cloud provider.\n */\n CLOUD_PROVIDER: 'cloud.provider';\n\n /**\n * The cloud account ID the resource is assigned to.\n */\n CLOUD_ACCOUNT_ID: 'cloud.account.id';\n\n /**\n * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations).\n */\n CLOUD_REGION: 'cloud.region';\n\n /**\n * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running.\n *\n * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud.\n */\n CLOUD_AVAILABILITY_ZONE: 'cloud.availability_zone';\n\n /**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n */\n CLOUD_PLATFORM: 'cloud.platform';\n\n /**\n * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html).\n */\n AWS_ECS_CONTAINER_ARN: 'aws.ecs.container.arn';\n\n /**\n * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html).\n */\n AWS_ECS_CLUSTER_ARN: 'aws.ecs.cluster.arn';\n\n /**\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n */\n AWS_ECS_LAUNCHTYPE: 'aws.ecs.launchtype';\n\n /**\n * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html).\n */\n AWS_ECS_TASK_ARN: 'aws.ecs.task.arn';\n\n /**\n * The task definition family this task definition is a member of.\n */\n AWS_ECS_TASK_FAMILY: 'aws.ecs.task.family';\n\n /**\n * The revision for this task definition.\n */\n AWS_ECS_TASK_REVISION: 'aws.ecs.task.revision';\n\n /**\n * The ARN of an EKS cluster.\n */\n AWS_EKS_CLUSTER_ARN: 'aws.eks.cluster.arn';\n\n /**\n * The name(s) of the AWS log group(s) an application is writing to.\n *\n * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group.\n */\n AWS_LOG_GROUP_NAMES: 'aws.log.group.names';\n\n /**\n * The Amazon Resource Name(s) (ARN) of the AWS log group(s).\n *\n * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format).\n */\n AWS_LOG_GROUP_ARNS: 'aws.log.group.arns';\n\n /**\n * The name(s) of the AWS log stream(s) an application is writing to.\n */\n AWS_LOG_STREAM_NAMES: 'aws.log.stream.names';\n\n /**\n * The ARN(s) of the AWS log stream(s).\n *\n * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream.\n */\n AWS_LOG_STREAM_ARNS: 'aws.log.stream.arns';\n\n /**\n * Container name.\n */\n CONTAINER_NAME: 'container.name';\n\n /**\n * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated.\n */\n CONTAINER_ID: 'container.id';\n\n /**\n * The container runtime managing this container.\n */\n CONTAINER_RUNTIME: 'container.runtime';\n\n /**\n * Name of the image the container was built on.\n */\n CONTAINER_IMAGE_NAME: 'container.image.name';\n\n /**\n * Container image tag.\n */\n CONTAINER_IMAGE_TAG: 'container.image.tag';\n\n /**\n * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier).\n */\n DEPLOYMENT_ENVIRONMENT: 'deployment.environment';\n\n /**\n * A unique identifier representing the device.\n *\n * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence.\n */\n DEVICE_ID: 'device.id';\n\n /**\n * The model identifier for the device.\n *\n * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device.\n */\n DEVICE_MODEL_IDENTIFIER: 'device.model.identifier';\n\n /**\n * The marketing name for the device model.\n *\n * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative.\n */\n DEVICE_MODEL_NAME: 'device.model.name';\n\n /**\n * The name of the single function that this runtime instance executes.\n *\n * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes).\n */\n FAAS_NAME: 'faas.name';\n\n /**\n * The unique ID of the single function that this runtime instance executes.\n *\n * Note: Depending on the cloud provider, use:\n\n* **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html).\nTake care not to use the "invoked ARN" directly but replace any\n[alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple\ndifferent aliases.\n* **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names)\n* **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id).\n\nOn some providers, it may not be possible to determine the full ID at startup,\nwhich is why this field cannot be made required. For example, on AWS the account ID\npart of the ARN is not available without calling another AWS API\nwhich may be deemed too slow for a short-running lambda function.\nAs an alternative, consider setting `faas.id` as a span attribute instead.\n */\n FAAS_ID: 'faas.id';\n\n /**\n * The immutable version of the function being executed.\n *\n * Note: Depending on the cloud provider and platform, use:\n\n* **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html)\n (an integer represented as a decimal string).\n* **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions)\n (i.e., the function name plus the revision suffix).\n* **Google Cloud Functions:** The value of the\n [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically).\n* **Azure Functions:** Not applicable. Do not set this attribute.\n */\n FAAS_VERSION: 'faas.version';\n\n /**\n * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version.\n *\n * Note: * **AWS Lambda:** Use the (full) log stream name.\n */\n FAAS_INSTANCE: 'faas.instance';\n\n /**\n * The amount of memory available to the serverless function in MiB.\n *\n * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information.\n */\n FAAS_MAX_MEMORY: 'faas.max_memory';\n\n /**\n * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider.\n */\n HOST_ID: 'host.id';\n\n /**\n * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user.\n */\n HOST_NAME: 'host.name';\n\n /**\n * Type of host. For Cloud, this must be the machine type.\n */\n HOST_TYPE: 'host.type';\n\n /**\n * The CPU architecture the host system is running on.\n */\n HOST_ARCH: 'host.arch';\n\n /**\n * Name of the VM image or OS install the host was instantiated from.\n */\n HOST_IMAGE_NAME: 'host.image.name';\n\n /**\n * VM image ID. For Cloud, this value is from the provider.\n */\n HOST_IMAGE_ID: 'host.image.id';\n\n /**\n * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes).\n */\n HOST_IMAGE_VERSION: 'host.image.version';\n\n /**\n * The name of the cluster.\n */\n K8S_CLUSTER_NAME: 'k8s.cluster.name';\n\n /**\n * The name of the Node.\n */\n K8S_NODE_NAME: 'k8s.node.name';\n\n /**\n * The UID of the Node.\n */\n K8S_NODE_UID: 'k8s.node.uid';\n\n /**\n * The name of the namespace that the pod is running in.\n */\n K8S_NAMESPACE_NAME: 'k8s.namespace.name';\n\n /**\n * The UID of the Pod.\n */\n K8S_POD_UID: 'k8s.pod.uid';\n\n /**\n * The name of the Pod.\n */\n K8S_POD_NAME: 'k8s.pod.name';\n\n /**\n * The name of the Container in a Pod template.\n */\n K8S_CONTAINER_NAME: 'k8s.container.name';\n\n /**\n * The UID of the ReplicaSet.\n */\n K8S_REPLICASET_UID: 'k8s.replicaset.uid';\n\n /**\n * The name of the ReplicaSet.\n */\n K8S_REPLICASET_NAME: 'k8s.replicaset.name';\n\n /**\n * The UID of the Deployment.\n */\n K8S_DEPLOYMENT_UID: 'k8s.deployment.uid';\n\n /**\n * The name of the Deployment.\n */\n K8S_DEPLOYMENT_NAME: 'k8s.deployment.name';\n\n /**\n * The UID of the StatefulSet.\n */\n K8S_STATEFULSET_UID: 'k8s.statefulset.uid';\n\n /**\n * The name of the StatefulSet.\n */\n K8S_STATEFULSET_NAME: 'k8s.statefulset.name';\n\n /**\n * The UID of the DaemonSet.\n */\n K8S_DAEMONSET_UID: 'k8s.daemonset.uid';\n\n /**\n * The name of the DaemonSet.\n */\n K8S_DAEMONSET_NAME: 'k8s.daemonset.name';\n\n /**\n * The UID of the Job.\n */\n K8S_JOB_UID: 'k8s.job.uid';\n\n /**\n * The name of the Job.\n */\n K8S_JOB_NAME: 'k8s.job.name';\n\n /**\n * The UID of the CronJob.\n */\n K8S_CRONJOB_UID: 'k8s.cronjob.uid';\n\n /**\n * The name of the CronJob.\n */\n K8S_CRONJOB_NAME: 'k8s.cronjob.name';\n\n /**\n * The operating system type.\n */\n OS_TYPE: 'os.type';\n\n /**\n * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands.\n */\n OS_DESCRIPTION: 'os.description';\n\n /**\n * Human readable operating system name.\n */\n OS_NAME: 'os.name';\n\n /**\n * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes).\n */\n OS_VERSION: 'os.version';\n\n /**\n * Process identifier (PID).\n */\n PROCESS_PID: 'process.pid';\n\n /**\n * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`.\n */\n PROCESS_EXECUTABLE_NAME: 'process.executable.name';\n\n /**\n * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`.\n */\n PROCESS_EXECUTABLE_PATH: 'process.executable.path';\n\n /**\n * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`.\n */\n PROCESS_COMMAND: 'process.command';\n\n /**\n * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead.\n */\n PROCESS_COMMAND_LINE: 'process.command_line';\n\n /**\n * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`.\n */\n PROCESS_COMMAND_ARGS: 'process.command_args';\n\n /**\n * The username of the user that owns the process.\n */\n PROCESS_OWNER: 'process.owner';\n\n /**\n * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler.\n */\n PROCESS_RUNTIME_NAME: 'process.runtime.name';\n\n /**\n * The version of the runtime of this process, as returned by the runtime without modification.\n */\n PROCESS_RUNTIME_VERSION: 'process.runtime.version';\n\n /**\n * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment.\n */\n PROCESS_RUNTIME_DESCRIPTION: 'process.runtime.description';\n\n /**\n * Logical name of the service.\n *\n * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`.\n */\n SERVICE_NAME: 'service.name';\n\n /**\n * A namespace for `service.name`.\n *\n * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\n SERVICE_NAMESPACE: 'service.namespace';\n\n /**\n * The string ID of the service instance.\n *\n * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations).\n */\n SERVICE_INSTANCE_ID: 'service.instance.id';\n\n /**\n * The version string of the service API or implementation.\n */\n SERVICE_VERSION: 'service.version';\n\n /**\n * The name of the telemetry SDK as defined above.\n */\n TELEMETRY_SDK_NAME: 'telemetry.sdk.name';\n\n /**\n * The language of the telemetry SDK.\n */\n TELEMETRY_SDK_LANGUAGE: 'telemetry.sdk.language';\n\n /**\n * The version string of the telemetry SDK.\n */\n TELEMETRY_SDK_VERSION: 'telemetry.sdk.version';\n\n /**\n * The version string of the auto instrumentation agent, if used.\n */\n TELEMETRY_AUTO_VERSION: 'telemetry.auto.version';\n\n /**\n * The name of the web engine.\n */\n WEBENGINE_NAME: 'webengine.name';\n\n /**\n * The version of the web engine.\n */\n WEBENGINE_VERSION: 'webengine.version';\n\n /**\n * Additional description of the web engine (e.g. detailed version and edition information).\n */\n WEBENGINE_DESCRIPTION: 'webengine.description';\n};\n\n/**\n * Create exported Value Map for SemanticResourceAttributes values\n * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification\n */\nexport const SemanticResourceAttributes: SemanticResourceAttributes =\n /*#__PURE__*/ createConstMap([\n TMP_CLOUD_PROVIDER,\n TMP_CLOUD_ACCOUNT_ID,\n TMP_CLOUD_REGION,\n TMP_CLOUD_AVAILABILITY_ZONE,\n TMP_CLOUD_PLATFORM,\n TMP_AWS_ECS_CONTAINER_ARN,\n TMP_AWS_ECS_CLUSTER_ARN,\n TMP_AWS_ECS_LAUNCHTYPE,\n TMP_AWS_ECS_TASK_ARN,\n TMP_AWS_ECS_TASK_FAMILY,\n TMP_AWS_ECS_TASK_REVISION,\n TMP_AWS_EKS_CLUSTER_ARN,\n TMP_AWS_LOG_GROUP_NAMES,\n TMP_AWS_LOG_GROUP_ARNS,\n TMP_AWS_LOG_STREAM_NAMES,\n TMP_AWS_LOG_STREAM_ARNS,\n TMP_CONTAINER_NAME,\n TMP_CONTAINER_ID,\n TMP_CONTAINER_RUNTIME,\n TMP_CONTAINER_IMAGE_NAME,\n TMP_CONTAINER_IMAGE_TAG,\n TMP_DEPLOYMENT_ENVIRONMENT,\n TMP_DEVICE_ID,\n TMP_DEVICE_MODEL_IDENTIFIER,\n TMP_DEVICE_MODEL_NAME,\n TMP_FAAS_NAME,\n TMP_FAAS_ID,\n TMP_FAAS_VERSION,\n TMP_FAAS_INSTANCE,\n TMP_FAAS_MAX_MEMORY,\n TMP_HOST_ID,\n TMP_HOST_NAME,\n TMP_HOST_TYPE,\n TMP_HOST_ARCH,\n TMP_HOST_IMAGE_NAME,\n TMP_HOST_IMAGE_ID,\n TMP_HOST_IMAGE_VERSION,\n TMP_K8S_CLUSTER_NAME,\n TMP_K8S_NODE_NAME,\n TMP_K8S_NODE_UID,\n TMP_K8S_NAMESPACE_NAME,\n TMP_K8S_POD_UID,\n TMP_K8S_POD_NAME,\n TMP_K8S_CONTAINER_NAME,\n TMP_K8S_REPLICASET_UID,\n TMP_K8S_REPLICASET_NAME,\n TMP_K8S_DEPLOYMENT_UID,\n TMP_K8S_DEPLOYMENT_NAME,\n TMP_K8S_STATEFULSET_UID,\n TMP_K8S_STATEFULSET_NAME,\n TMP_K8S_DAEMONSET_UID,\n TMP_K8S_DAEMONSET_NAME,\n TMP_K8S_JOB_UID,\n TMP_K8S_JOB_NAME,\n TMP_K8S_CRONJOB_UID,\n TMP_K8S_CRONJOB_NAME,\n TMP_OS_TYPE,\n TMP_OS_DESCRIPTION,\n TMP_OS_NAME,\n TMP_OS_VERSION,\n TMP_PROCESS_PID,\n TMP_PROCESS_EXECUTABLE_NAME,\n TMP_PROCESS_EXECUTABLE_PATH,\n TMP_PROCESS_COMMAND,\n TMP_PROCESS_COMMAND_LINE,\n TMP_PROCESS_COMMAND_ARGS,\n TMP_PROCESS_OWNER,\n TMP_PROCESS_RUNTIME_NAME,\n TMP_PROCESS_RUNTIME_VERSION,\n TMP_PROCESS_RUNTIME_DESCRIPTION,\n TMP_SERVICE_NAME,\n TMP_SERVICE_NAMESPACE,\n TMP_SERVICE_INSTANCE_ID,\n TMP_SERVICE_VERSION,\n TMP_TELEMETRY_SDK_NAME,\n TMP_TELEMETRY_SDK_LANGUAGE,\n TMP_TELEMETRY_SDK_VERSION,\n TMP_TELEMETRY_AUTO_VERSION,\n TMP_WEBENGINE_NAME,\n TMP_WEBENGINE_VERSION,\n TMP_WEBENGINE_DESCRIPTION,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for CloudProviderValues enum definition\n *\n * Name of the cloud provider.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud';\nconst TMP_CLOUDPROVIDERVALUES_AWS = 'aws';\nconst TMP_CLOUDPROVIDERVALUES_AZURE = 'azure';\nconst TMP_CLOUDPROVIDERVALUES_GCP = 'gcp';\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use CLOUD_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPROVIDERVALUES_ALIBABA_CLOUD =\n TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD;\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use CLOUD_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS;\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use CLOUD_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE;\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use CLOUD_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP;\n\n/**\n * Identifies the Values for CloudProviderValues enum definition\n *\n * Name of the cloud provider.\n * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification.\n */\nexport type CloudProviderValues = {\n /** Alibaba Cloud. */\n ALIBABA_CLOUD: 'alibaba_cloud';\n\n /** Amazon Web Services. */\n AWS: 'aws';\n\n /** Microsoft Azure. */\n AZURE: 'azure';\n\n /** Google Cloud Platform. */\n GCP: 'gcp';\n};\n\n/**\n * The constant map of values for CloudProviderValues.\n * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification.\n */\nexport const CloudProviderValues: CloudProviderValues =\n /*#__PURE__*/ createConstMap([\n TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,\n TMP_CLOUDPROVIDERVALUES_AWS,\n TMP_CLOUDPROVIDERVALUES_AZURE,\n TMP_CLOUDPROVIDERVALUES_GCP,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for CloudPlatformValues enum definition\n *\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = 'alibaba_cloud_ecs';\nconst TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = 'alibaba_cloud_fc';\nconst TMP_CLOUDPLATFORMVALUES_AWS_EC2 = 'aws_ec2';\nconst TMP_CLOUDPLATFORMVALUES_AWS_ECS = 'aws_ecs';\nconst TMP_CLOUDPLATFORMVALUES_AWS_EKS = 'aws_eks';\nconst TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = 'aws_lambda';\nconst TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = 'aws_elastic_beanstalk';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_VM = 'azure_vm';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES =\n 'azure_container_instances';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_AKS = 'azure_aks';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = 'azure_functions';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = 'azure_app_service';\nconst TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = 'gcp_compute_engine';\nconst TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = 'gcp_cloud_run';\nconst TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = 'gcp_kubernetes_engine';\nconst TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = 'gcp_cloud_functions';\nconst TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = 'gcp_app_engine';\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS =\n TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_FC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC =\n TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_LAMBDA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_LAMBDA =\n TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ELASTIC_BEANSTALK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK =\n TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_VM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_CONTAINER_INSTANCES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES =\n TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_AKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_FUNCTIONS =\n TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_APP_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_APP_SERVICE =\n TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_COMPUTE_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE =\n TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_RUN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_CLOUD_RUN =\n TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_KUBERNETES_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE =\n TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS =\n TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_APP_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_APP_ENGINE =\n TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE;\n\n/**\n * Identifies the Values for CloudPlatformValues enum definition\n *\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification.\n */\nexport type CloudPlatformValues = {\n /** Alibaba Cloud Elastic Compute Service. */\n ALIBABA_CLOUD_ECS: 'alibaba_cloud_ecs';\n\n /** Alibaba Cloud Function Compute. */\n ALIBABA_CLOUD_FC: 'alibaba_cloud_fc';\n\n /** AWS Elastic Compute Cloud. */\n AWS_EC2: 'aws_ec2';\n\n /** AWS Elastic Container Service. */\n AWS_ECS: 'aws_ecs';\n\n /** AWS Elastic Kubernetes Service. */\n AWS_EKS: 'aws_eks';\n\n /** AWS Lambda. */\n AWS_LAMBDA: 'aws_lambda';\n\n /** AWS Elastic Beanstalk. */\n AWS_ELASTIC_BEANSTALK: 'aws_elastic_beanstalk';\n\n /** Azure Virtual Machines. */\n AZURE_VM: 'azure_vm';\n\n /** Azure Container Instances. */\n AZURE_CONTAINER_INSTANCES: 'azure_container_instances';\n\n /** Azure Kubernetes Service. */\n AZURE_AKS: 'azure_aks';\n\n /** Azure Functions. */\n AZURE_FUNCTIONS: 'azure_functions';\n\n /** Azure App Service. */\n AZURE_APP_SERVICE: 'azure_app_service';\n\n /** Google Cloud Compute Engine (GCE). */\n GCP_COMPUTE_ENGINE: 'gcp_compute_engine';\n\n /** Google Cloud Run. */\n GCP_CLOUD_RUN: 'gcp_cloud_run';\n\n /** Google Cloud Kubernetes Engine (GKE). */\n GCP_KUBERNETES_ENGINE: 'gcp_kubernetes_engine';\n\n /** Google Cloud Functions (GCF). */\n GCP_CLOUD_FUNCTIONS: 'gcp_cloud_functions';\n\n /** Google Cloud App Engine (GAE). */\n GCP_APP_ENGINE: 'gcp_app_engine';\n};\n\n/**\n * The constant map of values for CloudPlatformValues.\n * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification.\n */\nexport const CloudPlatformValues: CloudPlatformValues =\n /*#__PURE__*/ createConstMap([\n TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,\n TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,\n TMP_CLOUDPLATFORMVALUES_AWS_EC2,\n TMP_CLOUDPLATFORMVALUES_AWS_ECS,\n TMP_CLOUDPLATFORMVALUES_AWS_EKS,\n TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,\n TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,\n TMP_CLOUDPLATFORMVALUES_AZURE_VM,\n TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,\n TMP_CLOUDPLATFORMVALUES_AZURE_AKS,\n TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,\n TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,\n TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,\n TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,\n TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,\n TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,\n TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for AwsEcsLaunchtypeValues enum definition\n *\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_AWSECSLAUNCHTYPEVALUES_EC2 = 'ec2';\nconst TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = 'fargate';\n\n/**\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n *\n * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2;\n\n/**\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n *\n * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_FARGATE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const AWSECSLAUNCHTYPEVALUES_FARGATE =\n TMP_AWSECSLAUNCHTYPEVALUES_FARGATE;\n\n/**\n * Identifies the Values for AwsEcsLaunchtypeValues enum definition\n *\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification.\n */\nexport type AwsEcsLaunchtypeValues = {\n /** ec2. */\n EC2: 'ec2';\n\n /** fargate. */\n FARGATE: 'fargate';\n};\n\n/**\n * The constant map of values for AwsEcsLaunchtypeValues.\n * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification.\n */\nexport const AwsEcsLaunchtypeValues: AwsEcsLaunchtypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_AWSECSLAUNCHTYPEVALUES_EC2,\n TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for HostArchValues enum definition\n *\n * The CPU architecture the host system is running on.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_HOSTARCHVALUES_AMD64 = 'amd64';\nconst TMP_HOSTARCHVALUES_ARM32 = 'arm32';\nconst TMP_HOSTARCHVALUES_ARM64 = 'arm64';\nconst TMP_HOSTARCHVALUES_IA64 = 'ia64';\nconst TMP_HOSTARCHVALUES_PPC32 = 'ppc32';\nconst TMP_HOSTARCHVALUES_PPC64 = 'ppc64';\nconst TMP_HOSTARCHVALUES_X86 = 'x86';\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_AMD64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_ARM32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_ARM64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_IA64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_PPC32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_PPC64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_X86 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86;\n\n/**\n * Identifies the Values for HostArchValues enum definition\n *\n * The CPU architecture the host system is running on.\n * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification.\n */\nexport type HostArchValues = {\n /** AMD64. */\n AMD64: 'amd64';\n\n /** ARM32. */\n ARM32: 'arm32';\n\n /** ARM64. */\n ARM64: 'arm64';\n\n /** Itanium. */\n IA64: 'ia64';\n\n /** 32-bit PowerPC. */\n PPC32: 'ppc32';\n\n /** 64-bit PowerPC. */\n PPC64: 'ppc64';\n\n /** 32-bit x86. */\n X86: 'x86';\n};\n\n/**\n * The constant map of values for HostArchValues.\n * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification.\n */\nexport const HostArchValues: HostArchValues =\n /*#__PURE__*/ createConstMap([\n TMP_HOSTARCHVALUES_AMD64,\n TMP_HOSTARCHVALUES_ARM32,\n TMP_HOSTARCHVALUES_ARM64,\n TMP_HOSTARCHVALUES_IA64,\n TMP_HOSTARCHVALUES_PPC32,\n TMP_HOSTARCHVALUES_PPC64,\n TMP_HOSTARCHVALUES_X86,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for OsTypeValues enum definition\n *\n * The operating system type.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_OSTYPEVALUES_WINDOWS = 'windows';\nconst TMP_OSTYPEVALUES_LINUX = 'linux';\nconst TMP_OSTYPEVALUES_DARWIN = 'darwin';\nconst TMP_OSTYPEVALUES_FREEBSD = 'freebsd';\nconst TMP_OSTYPEVALUES_NETBSD = 'netbsd';\nconst TMP_OSTYPEVALUES_OPENBSD = 'openbsd';\nconst TMP_OSTYPEVALUES_DRAGONFLYBSD = 'dragonflybsd';\nconst TMP_OSTYPEVALUES_HPUX = 'hpux';\nconst TMP_OSTYPEVALUES_AIX = 'aix';\nconst TMP_OSTYPEVALUES_SOLARIS = 'solaris';\nconst TMP_OSTYPEVALUES_Z_OS = 'z_os';\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_WINDOWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_LINUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_DARWIN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_FREEBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_NETBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_OPENBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_DRAGONFLYBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_HPUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_AIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_SOLARIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_Z_OS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS;\n\n/**\n * Identifies the Values for OsTypeValues enum definition\n *\n * The operating system type.\n * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification.\n */\nexport type OsTypeValues = {\n /** Microsoft Windows. */\n WINDOWS: 'windows';\n\n /** Linux. */\n LINUX: 'linux';\n\n /** Apple Darwin. */\n DARWIN: 'darwin';\n\n /** FreeBSD. */\n FREEBSD: 'freebsd';\n\n /** NetBSD. */\n NETBSD: 'netbsd';\n\n /** OpenBSD. */\n OPENBSD: 'openbsd';\n\n /** DragonFly BSD. */\n DRAGONFLYBSD: 'dragonflybsd';\n\n /** HP-UX (Hewlett Packard Unix). */\n HPUX: 'hpux';\n\n /** AIX (Advanced Interactive eXecutive). */\n AIX: 'aix';\n\n /** Oracle Solaris. */\n SOLARIS: 'solaris';\n\n /** IBM z/OS. */\n Z_OS: 'z_os';\n};\n\n/**\n * The constant map of values for OsTypeValues.\n * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification.\n */\nexport const OsTypeValues: OsTypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_OSTYPEVALUES_WINDOWS,\n TMP_OSTYPEVALUES_LINUX,\n TMP_OSTYPEVALUES_DARWIN,\n TMP_OSTYPEVALUES_FREEBSD,\n TMP_OSTYPEVALUES_NETBSD,\n TMP_OSTYPEVALUES_OPENBSD,\n TMP_OSTYPEVALUES_DRAGONFLYBSD,\n TMP_OSTYPEVALUES_HPUX,\n TMP_OSTYPEVALUES_AIX,\n TMP_OSTYPEVALUES_SOLARIS,\n TMP_OSTYPEVALUES_Z_OS,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for TelemetrySdkLanguageValues enum definition\n *\n * The language of the telemetry SDK.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = 'cpp';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = 'dotnet';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = 'erlang';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_GO = 'go';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = 'java';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = 'nodejs';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = 'php';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = 'python';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = 'ruby';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = 'webjs';\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_CPP.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_CPP =\n TMP_TELEMETRYSDKLANGUAGEVALUES_CPP;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_DOTNET =\n TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_ERLANG =\n TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_GO.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_JAVA.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_JAVA =\n TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_NODEJS =\n TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PHP.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_PHP =\n TMP_TELEMETRYSDKLANGUAGEVALUES_PHP;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_PYTHON =\n TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_RUBY.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_RUBY =\n TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_WEBJS =\n TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS;\n\n/**\n * Identifies the Values for TelemetrySdkLanguageValues enum definition\n *\n * The language of the telemetry SDK.\n * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification.\n */\nexport type TelemetrySdkLanguageValues = {\n /** cpp. */\n CPP: 'cpp';\n\n /** dotnet. */\n DOTNET: 'dotnet';\n\n /** erlang. */\n ERLANG: 'erlang';\n\n /** go. */\n GO: 'go';\n\n /** java. */\n JAVA: 'java';\n\n /** nodejs. */\n NODEJS: 'nodejs';\n\n /** php. */\n PHP: 'php';\n\n /** python. */\n PYTHON: 'python';\n\n /** ruby. */\n RUBY: 'ruby';\n\n /** webjs. */\n WEBJS: 'webjs';\n};\n\n/**\n * The constant map of values for TelemetrySdkLanguageValues.\n * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification.\n */\nexport const TelemetrySdkLanguageValues: TelemetrySdkLanguageValues =\n /*#__PURE__*/ createConstMap([\n TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,\n TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,\n TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,\n TMP_TELEMETRYSDKLANGUAGEVALUES_GO,\n TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,\n TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,\n TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,\n TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,\n TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,\n TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,\n ]);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable no-restricted-syntax --\n * These re-exports are only of constants, only one-level deep at this point,\n * and should not cause problems for tree-shakers.\n */\nexport * from './SemanticResourceAttributes';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result' as const;\n\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\" as const;\n\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\" as const;\n\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\" as const;\n\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\" as const;\n\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type' as const;\n\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy' as const;\n\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result' as const;\n\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\" as const;\n\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\" as const;\n\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\" as const;\n\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\" as const;\n\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled' as const;\n\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback' as const;\n\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status' as const;\n\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\" as const;\n\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\" as const;\n\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated' as const;\n\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address' as const;\n\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port' as const;\n\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number' as const;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path' as const;\n\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n * - Java method: `com.example.MyHttpService.serveRequest`\n * - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n * - PHP function: `GuzzleHttp\\Client::transfer`\n * - Go function: `github.com/my/repo/pkg.foo.func5`\n * - Elixir: `OpenTelemetry.Ctx.new`\n * - Erlang: `opentelemetry_ctx:new`\n * - Rust: `playground::my_module::my_cool_func`\n * - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name' as const;\n\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace' as const;\n\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name' as const;\n\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace' as const;\n\n/**\n * The number of queries included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size' as const;\n\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name' as const;\n\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query)\n * section.\n *\n * For batch operations, if the individual operations are known to have the same query summary\n * then that query summary **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary' as const;\n\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text' as const;\n\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code' as const;\n\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name' as const;\n\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name' as const;\n\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\" as const;\n\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\" as const;\n\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\" as const;\n\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\" as const;\n\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation' as const;\n\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\" as const;\n\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\" as const;\n\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\" as const;\n\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\" as const;\n\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\" as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped' as const;\n\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n *\n * @note > [!WARNING]\n *\n * > This attribute may contain sensitive information.\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace' as const;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type' as const;\n\n/**\n * HTTP request headers, `` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n * attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key: string) => `http.request.header.${key}`;\n\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods.\n *\n *\n * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property\n * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or\n * `.instrumentation/development.general.http.server`.\n *\n * In either case, this list **MUST** be a full override of the default known methods,\n * it is not a list of known methods in addition to the defaults.\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\" as const;\n\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\" as const;\n\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\" as const;\n\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\" as const;\n\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\" as const;\n\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\" as const;\n\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\" as const;\n\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\" as const;\n\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\" as const;\n\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original' as const;\n\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count' as const;\n\n/**\n * HTTP response headers, `` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n * attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key: string) => `http.response.header.${key}`;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code' as const;\n\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route' as const;\n\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action' as const;\n\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name' as const;\n\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name' as const;\n\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type' as const;\n\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\" as const;\n\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\" as const;\n\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon' as const;\n\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state' as const;\n\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\" as const;\n\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\" as const;\n\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\" as const;\n\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\" as const;\n\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\" as const;\n\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\" as const;\n\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address' as const;\n\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port' as const;\n\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address' as const;\n\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port' as const;\n\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name' as const;\n\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version' as const;\n\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport' as const;\n\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\" as const;\n\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\" as const;\n\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\" as const;\n\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\" as const;\n\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\" as const;\n\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type' as const;\n\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\" as const;\n\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\" as const;\n\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name' as const;\n\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version' as const;\n\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code' as const;\n\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\" as const;\n\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\" as const;\n\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description' as const;\n\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address' as const;\n\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port' as const;\n\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id' as const;\n\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`.\n */\nexport const ATTR_SERVICE_NAME = 'service.name' as const;\n\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace' as const;\n\n/**\n * The version string of the service component. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version' as const;\n\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status' as const;\n\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\" as const;\n\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\" as const;\n\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\" as const;\n\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport' as const;\n\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\" as const;\n\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\" as const;\n\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\" as const;\n\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language' as const;\n\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\" as const;\n\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\" as const;\n\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\" as const;\n\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\" as const;\n\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\" as const;\n\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\" as const;\n\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\" as const;\n\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\" as const;\n\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\" as const;\n\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\" as const;\n\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\" as const;\n\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\" as const;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name' as const;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version' as const;\n\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment' as const;\n\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full' as const;\n\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path' as const;\n\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query' as const;\n\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme' as const;\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original' as const;\n\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/register/stable/metrics.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * Number of exceptions caught by exception handling middleware.\n *\n * @note Meter name: `Microsoft.AspNetCore.Diagnostics`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = 'aspnetcore.diagnostics.exceptions' as const;\n\n/**\n * Number of requests that are currently active on the server that hold a rate limiting lease.\n *\n * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = 'aspnetcore.rate_limiting.active_request_leases' as const;\n\n/**\n * Number of requests that are currently queued, waiting to acquire a rate limiting lease.\n *\n * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = 'aspnetcore.rate_limiting.queued_requests' as const;\n\n/**\n * The time the request spent in a queue waiting to acquire a rate limiting lease.\n *\n * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = 'aspnetcore.rate_limiting.request.time_in_queue' as const;\n\n/**\n * The duration of rate limiting lease held by requests on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = 'aspnetcore.rate_limiting.request_lease.duration' as const;\n\n/**\n * Number of requests that tried to acquire a rate limiting lease.\n *\n * @note Requests could be:\n *\n * - Rejected by global or endpoint rate limiting policies\n * - Canceled while waiting for the lease.\n *\n * Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = 'aspnetcore.rate_limiting.requests' as const;\n\n/**\n * Number of requests that were attempted to be matched to an endpoint.\n *\n * @note Meter name: `Microsoft.AspNetCore.Routing`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = 'aspnetcore.routing.match_attempts' as const;\n\n/**\n * Duration of database client operations.\n *\n * @note Batch operations **SHOULD** be recorded as a single operation.\n */\nexport const METRIC_DB_CLIENT_OPERATION_DURATION = 'db.client.operation.duration' as const;\n\n/**\n * The number of .NET assemblies that are currently loaded.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`AppDomain.CurrentDomain.GetAssemblies().Length`](https://learn.microsoft.com/dotnet/api/system.appdomain.getassemblies).\n */\nexport const METRIC_DOTNET_ASSEMBLY_COUNT = 'dotnet.assembly.count' as const;\n\n/**\n * The number of exceptions that have been thrown in managed code.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as counting calls to [`AppDomain.CurrentDomain.FirstChanceException`](https://learn.microsoft.com/dotnet/api/system.appdomain.firstchanceexception).\n */\nexport const METRIC_DOTNET_EXCEPTIONS = 'dotnet.exceptions' as const;\n\n/**\n * The number of garbage collections that have occurred since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric uses the [`GC.CollectionCount(int generation)`](https://learn.microsoft.com/dotnet/api/system.gc.collectioncount) API to calculate exclusive collections per generation.\n */\nexport const METRIC_DOTNET_GC_COLLECTIONS = 'dotnet.gc.collections' as const;\n\n/**\n * The *approximate* number of bytes allocated on the managed GC heap since the process has started. The returned value does not include any native allocations.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetTotalAllocatedBytes()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalallocatedbytes).\n */\nexport const METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = 'dotnet.gc.heap.total_allocated' as const;\n\n/**\n * The heap fragmentation, as observed during the latest garbage collection.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.FragmentationAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.fragmentationafterbytes).\n */\nexport const METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = 'dotnet.gc.last_collection.heap.fragmentation.size' as const;\n\n/**\n * The managed GC heap size (including fragmentation), as observed during the latest garbage collection.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.SizeAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.sizeafterbytes).\n */\nexport const METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = 'dotnet.gc.last_collection.heap.size' as const;\n\n/**\n * The amount of committed virtual memory in use by the .NET GC, as observed during the latest garbage collection.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetGCMemoryInfo().TotalCommittedBytes`](https://learn.microsoft.com/dotnet/api/system.gcmemoryinfo.totalcommittedbytes). Committed virtual memory may be larger than the heap size because it includes both memory for storing existing objects (the heap size) and some extra memory that is ready to handle newly allocated objects in the future.\n */\nexport const METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = 'dotnet.gc.last_collection.memory.committed_size' as const;\n\n/**\n * The total amount of time paused in GC since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetTotalPauseDuration()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalpauseduration).\n */\nexport const METRIC_DOTNET_GC_PAUSE_TIME = 'dotnet.gc.pause.time' as const;\n\n/**\n * The amount of time the JIT compiler has spent compiling methods since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`JitInfo.GetCompilationTime()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompilationtime).\n */\nexport const METRIC_DOTNET_JIT_COMPILATION_TIME = 'dotnet.jit.compilation.time' as const;\n\n/**\n * Count of bytes of intermediate language that have been compiled since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`JitInfo.GetCompiledILBytes()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledilbytes).\n */\nexport const METRIC_DOTNET_JIT_COMPILED_IL_SIZE = 'dotnet.jit.compiled_il.size' as const;\n\n/**\n * The number of times the JIT compiler (re)compiled methods since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`JitInfo.GetCompiledMethodCount()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledmethodcount).\n */\nexport const METRIC_DOTNET_JIT_COMPILED_METHODS = 'dotnet.jit.compiled_methods' as const;\n\n/**\n * The number of times there was contention when trying to acquire a monitor lock since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`Monitor.LockContentionCount`](https://learn.microsoft.com/dotnet/api/system.threading.monitor.lockcontentioncount).\n */\nexport const METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = 'dotnet.monitor.lock_contentions' as const;\n\n/**\n * The number of processors available to the process.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as accessing [`Environment.ProcessorCount`](https://learn.microsoft.com/dotnet/api/system.environment.processorcount).\n */\nexport const METRIC_DOTNET_PROCESS_CPU_COUNT = 'dotnet.process.cpu.count' as const;\n\n/**\n * CPU time used by the process.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as accessing the corresponding processor time properties on [`System.Diagnostics.Process`](https://learn.microsoft.com/dotnet/api/system.diagnostics.process).\n */\nexport const METRIC_DOTNET_PROCESS_CPU_TIME = 'dotnet.process.cpu.time' as const;\n\n/**\n * The number of bytes of physical memory mapped to the process context.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`Environment.WorkingSet`](https://learn.microsoft.com/dotnet/api/system.environment.workingset).\n */\nexport const METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = 'dotnet.process.memory.working_set' as const;\n\n/**\n * The number of work items that are currently queued to be processed by the thread pool.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`ThreadPool.PendingWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.pendingworkitemcount).\n */\nexport const METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = 'dotnet.thread_pool.queue.length' as const;\n\n/**\n * The number of thread pool threads that currently exist.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`ThreadPool.ThreadCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.threadcount).\n */\nexport const METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = 'dotnet.thread_pool.thread.count' as const;\n\n/**\n * The number of work items that the thread pool has completed since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`ThreadPool.CompletedWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.completedworkitemcount).\n */\nexport const METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = 'dotnet.thread_pool.work_item.count' as const;\n\n/**\n * The number of timer instances that are currently active.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`Timer.ActiveCount`](https://learn.microsoft.com/dotnet/api/system.threading.timer.activecount).\n */\nexport const METRIC_DOTNET_TIMER_COUNT = 'dotnet.timer.count' as const;\n\n/**\n * Duration of HTTP client requests.\n */\nexport const METRIC_HTTP_CLIENT_REQUEST_DURATION = 'http.client.request.duration' as const;\n\n/**\n * Duration of HTTP server requests.\n */\nexport const METRIC_HTTP_SERVER_REQUEST_DURATION = 'http.server.request.duration' as const;\n\n/**\n * Number of classes currently loaded.\n */\nexport const METRIC_JVM_CLASS_COUNT = 'jvm.class.count' as const;\n\n/**\n * Number of classes loaded since JVM start.\n */\nexport const METRIC_JVM_CLASS_LOADED = 'jvm.class.loaded' as const;\n\n/**\n * Number of classes unloaded since JVM start.\n */\nexport const METRIC_JVM_CLASS_UNLOADED = 'jvm.class.unloaded' as const;\n\n/**\n * Number of processors available to the Java virtual machine.\n */\nexport const METRIC_JVM_CPU_COUNT = 'jvm.cpu.count' as const;\n\n/**\n * Recent CPU utilization for the process as reported by the JVM.\n *\n * @note The value range is [0.0,1.0]. This utilization is not defined as being for the specific interval since last measurement (unlike `system.cpu.utilization`). [Reference](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()).\n */\nexport const METRIC_JVM_CPU_RECENT_UTILIZATION = 'jvm.cpu.recent_utilization' as const;\n\n/**\n * CPU time used by the process as reported by the JVM.\n */\nexport const METRIC_JVM_CPU_TIME = 'jvm.cpu.time' as const;\n\n/**\n * Duration of JVM garbage collection actions.\n */\nexport const METRIC_JVM_GC_DURATION = 'jvm.gc.duration' as const;\n\n/**\n * Measure of memory committed.\n */\nexport const METRIC_JVM_MEMORY_COMMITTED = 'jvm.memory.committed' as const;\n\n/**\n * Measure of max obtainable memory.\n */\nexport const METRIC_JVM_MEMORY_LIMIT = 'jvm.memory.limit' as const;\n\n/**\n * Measure of memory used.\n */\nexport const METRIC_JVM_MEMORY_USED = 'jvm.memory.used' as const;\n\n/**\n * Measure of memory used, as measured after the most recent garbage collection event on this pool.\n */\nexport const METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = 'jvm.memory.used_after_last_gc' as const;\n\n/**\n * Number of executing platform threads.\n */\nexport const METRIC_JVM_THREAD_COUNT = 'jvm.thread.count' as const;\n\n/**\n * Number of connections that are currently active on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_ACTIVE_CONNECTIONS = 'kestrel.active_connections' as const;\n\n/**\n * Number of TLS handshakes that are currently in progress on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = 'kestrel.active_tls_handshakes' as const;\n\n/**\n * The duration of connections on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_CONNECTION_DURATION = 'kestrel.connection.duration' as const;\n\n/**\n * Number of connections that are currently queued and are waiting to start.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_QUEUED_CONNECTIONS = 'kestrel.queued_connections' as const;\n\n/**\n * Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_QUEUED_REQUESTS = 'kestrel.queued_requests' as const;\n\n/**\n * Number of connections rejected by the server.\n *\n * @note Connections are rejected when the currently active count exceeds the value configured with `MaxConcurrentConnections`.\n * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_REJECTED_CONNECTIONS = 'kestrel.rejected_connections' as const;\n\n/**\n * The duration of TLS handshakes on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_TLS_HANDSHAKE_DURATION = 'kestrel.tls_handshake.duration' as const;\n\n/**\n * Number of connections that are currently upgraded (WebSockets). .\n *\n * @note The counter only tracks HTTP/1.1 connections.\n *\n * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_UPGRADED_CONNECTIONS = 'kestrel.upgraded_connections' as const;\n\n/**\n * Number of connections that are currently active on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = 'signalr.server.active_connections' as const;\n\n/**\n * The duration of connections on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_SIGNALR_SERVER_CONNECTION_DURATION = 'signalr.server.connection.duration' as const;\n\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//-----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/ts-stable/events.ts.j2\n//-----------------------------------------------------------------------------------------------------------\n\n/**\n * This event describes a single exception.\n */\nexport const EVENT_EXCEPTION = 'exception' as const;\n\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable no-restricted-syntax --\n * These re-exports are only of constants, only two-levels deep, and\n * should not cause problems for tree-shakers.\n */\n\n// Deprecated. These are kept around for compatibility purposes\nexport * from './trace';\nexport * from './resource';\n\n// Use these instead\nexport * from './stable_attributes';\nexport * from './stable_metrics';\nexport * from './stable_events';\n", "import { ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE } from \"@opentelemetry/semantic-conventions\";\n//#region src/instrumentation/attributes.ts\n/** Operation identifier (e.g. getSession, signUpWithEmailAndPassword). Uses endpoint operationId when set, otherwise the endpoint key. */\nconst ATTR_OPERATION_ID = \"better_auth.operation_id\";\n/** Hook type (e.g. before, after, create.before). */\nconst ATTR_HOOK_TYPE = \"better_auth.hook.type\";\n/** Execution context (e.g. user, plugin:id). */\nconst ATTR_CONTEXT = \"better_auth.context\";\n//#endregion\nexport { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID };\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './node';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set([ownVersion]);\n const rejectedVersions = new Set();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters));\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with ReturnType>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return fn.call(thisArg, ...args);\n }\n\n bind(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum TraceFlags {\n /** Represents no flag set. */\n NONE = 0x0,\n /** Bit to represent whether trace is sampled in trace flags. */\n SAMPLED = 0x1 << 0,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\nexport const INVALID_SPANID = '0000000000000000';\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n traceId: INVALID_TRACEID,\n spanId: INVALID_SPANID,\n traceFlags: TraceFlags.NONE,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nexport class NonRecordingSpan implements Span {\n constructor(\n private readonly _spanContext: SpanContext = INVALID_SPAN_CONTEXT\n ) {}\n\n // Returns a SpanContext.\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n // By default does nothing\n setAttribute(_key: string, _value: unknown): this {\n return this;\n }\n\n // By default does nothing\n setAttributes(_attributes: SpanAttributes): this {\n return this;\n }\n\n // By default does nothing\n addEvent(_name: string, _attributes?: SpanAttributes): this {\n return this;\n }\n\n addLink(_link: Link): this {\n return this;\n }\n\n addLinks(_links: Link[]): this {\n return this;\n }\n\n // By default does nothing\n setStatus(_status: SpanStatus): this {\n return this;\n }\n\n // By default does nothing\n updateName(_name: string): this {\n return this;\n }\n\n // By default does nothing\n end(_endTime?: TimeInput): void {}\n\n // isRecording always returns false for NonRecordingSpan.\n isRecording(): boolean {\n return false;\n }\n\n // By default does nothing\n recordException(_exception: Exception, _time?: TimeInput): void {}\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n\n/**\n * span key\n */\nconst SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context: Context): Span | undefined {\n return (context.getValue(SPAN_KEY) as Span) || undefined;\n}\n\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan(): Span | undefined {\n return getSpan(ContextAPI.getInstance().active());\n}\n\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context: Context, span: Span): Context {\n return context.setValue(SPAN_KEY, span);\n}\n\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context: Context): Context {\n return context.deleteValue(SPAN_KEY);\n}\n\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(\n context: Context,\n spanContext: SpanContext\n): Context {\n return setSpan(context, new NonRecordingSpan(spanContext));\n}\n\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context: Context): SpanContext | undefined {\n return getSpan(context)?.spanContext();\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\n\nconst VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nconst VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\n\nexport function isValidTraceId(traceId: string): boolean {\n return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\n\nexport function isValidSpanId(spanId: string): boolean {\n return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext: SpanContext): boolean {\n return (\n isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)\n );\n}\n\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext: SpanContext): Span {\n return new NonRecordingSpan(spanContext);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { Context } from '../context/types';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { isSpanContextValid } from './spancontext-utils';\nimport { SpanOptions } from './SpanOptions';\nimport { SpanContext } from './span_context';\nimport { Tracer } from './tracer';\n\nconst contextApi = ContextAPI.getInstance();\n\n/**\n * No-op implementations of {@link Tracer}.\n */\nexport class NoopTracer implements Tracer {\n // startSpan starts a noop span.\n startSpan(\n name: string,\n options?: SpanOptions,\n context = contextApi.active()\n ): Span {\n const root = Boolean(options?.root);\n if (root) {\n return new NonRecordingSpan();\n }\n\n const parentFromContext = context && getSpanContext(context);\n\n if (\n isSpanContext(parentFromContext) &&\n isSpanContextValid(parentFromContext)\n ) {\n return new NonRecordingSpan(parentFromContext);\n } else {\n return new NonRecordingSpan();\n }\n }\n\n startActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n ctx: Context | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n arg2?: F | SpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType | undefined {\n let opts: SpanOptions | undefined;\n let ctx: Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as SpanOptions | undefined;\n ctx = arg3 as Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? contextApi.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = setSpan(parentContext, span);\n\n return contextApi.with(contextWithSpanSet, fn, undefined, span);\n }\n}\n\nfunction isSpanContext(spanContext: any): spanContext is SpanContext {\n return (\n typeof spanContext === 'object' &&\n typeof spanContext['spanId'] === 'string' &&\n typeof spanContext['traceId'] === 'string' &&\n typeof spanContext['traceFlags'] === 'number'\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { NoopTracer } from './NoopTracer';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER = new NoopTracer();\n\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nexport class ProxyTracer implements Tracer {\n // When a real implementation is provided, this will be it\n private _delegate?: Tracer;\n\n constructor(\n private _provider: TracerDelegator,\n public readonly name: string,\n public readonly version?: string,\n public readonly options?: TracerOptions\n ) {}\n\n startSpan(name: string, options?: SpanOptions, context?: Context): Span {\n return this._getTracer().startSpan(name, options, context);\n }\n\n startActiveSpan unknown>(\n _name: string,\n _options: F | SpanOptions,\n _context?: F | Context,\n _fn?: F\n ): ReturnType {\n const tracer = this._getTracer();\n return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n }\n\n /**\n * Try to get a tracer from the proxy tracer provider.\n * If the proxy tracer provider has no delegate, return a noop tracer.\n */\n private _getTracer() {\n if (this._delegate) {\n return this._delegate;\n }\n\n const tracer = this._provider.getDelegateTracer(\n this.name,\n this.version,\n this.options\n );\n\n if (!tracer) {\n return NOOP_TRACER;\n }\n\n this._delegate = tracer;\n return this._delegate;\n }\n}\n\nexport interface TracerDelegator {\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopTracer } from './NoopTracer';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\nimport { TracerProvider } from './tracer_provider';\n\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nexport class NoopTracerProvider implements TracerProvider {\n getTracer(\n _name?: string,\n _version?: string,\n _options?: TracerOptions\n ): Tracer {\n return new NoopTracer();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerProvider } from './tracer_provider';\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n * When a delegate is set, traces are provided from the delegate.\n * When a delegate is set after tracers have already been provided,\n * all tracers already provided will use the provided delegate implementation.\n */\nexport class ProxyTracerProvider implements TracerProvider {\n private _delegate?: TracerProvider;\n\n /**\n * Get a {@link ProxyTracer}\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer {\n return (\n this.getDelegateTracer(name, version, options) ??\n new ProxyTracer(this, name, version, options)\n );\n }\n\n getDelegate(): TracerProvider {\n return this._delegate ?? NOOP_TRACER_PROVIDER;\n }\n\n /**\n * Set the delegate tracer provider\n */\n setDelegate(delegate: TracerProvider) {\n this._delegate = delegate;\n }\n\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined {\n return this._delegate?.getTracer(name, version, options);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport {\n isSpanContextValid,\n wrapSpanContext,\n} from '../trace/spancontext-utils';\nimport { Tracer } from '../trace/tracer';\nimport { TracerProvider } from '../trace/tracer_provider';\nimport {\n deleteSpan,\n getActiveSpan,\n getSpan,\n getSpanContext,\n setSpan,\n setSpanContext,\n} from '../trace/context-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'trace';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nexport class TraceAPI {\n private static _instance?: TraceAPI;\n\n private _proxyTracerProvider = new ProxyTracerProvider();\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Trace API */\n public static getInstance(): TraceAPI {\n if (!this._instance) {\n this._instance = new TraceAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global tracer.\n *\n * @returns true if the tracer provider was successfully registered, else false\n */\n public setGlobalTracerProvider(provider: TracerProvider): boolean {\n const success = registerGlobal(\n API_NAME,\n this._proxyTracerProvider,\n DiagAPI.instance()\n );\n if (success) {\n this._proxyTracerProvider.setDelegate(provider);\n }\n return success;\n }\n\n /**\n * Returns the global tracer provider.\n */\n public getTracerProvider(): TracerProvider {\n return getGlobal(API_NAME) || this._proxyTracerProvider;\n }\n\n /**\n * Returns a tracer from the global tracer provider.\n */\n public getTracer(name: string, version?: string): Tracer {\n return this.getTracerProvider().getTracer(name, version);\n }\n\n /** Remove the global tracer provider */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n this._proxyTracerProvider = new ProxyTracerProvider();\n }\n\n public wrapSpanContext = wrapSpanContext;\n\n public isSpanContextValid = isSpanContextValid;\n\n public deleteSpan = deleteSpan;\n\n public getSpan = getSpan;\n\n public getActiveSpan = getActiveSpan;\n\n public getSpanContext = getSpanContext;\n\n public setSpan = setSpan;\n\n public setSpanContext = setSpanContext;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport const trace = TraceAPI.getInstance();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types';\nexport { baggageEntryMetadataFromString } from './baggage/utils';\nexport { Exception } from './common/Exception';\nexport { HrTime, TimeInput } from './common/Time';\nexport { Attributes, AttributeValue } from './common/Attributes';\n\n// Context APIs\nexport { createContextKey, ROOT_CONTEXT } from './context/context';\nexport { Context, ContextManager } from './context/types';\nexport type { ContextAPI } from './api/context';\n\n// Diag APIs\nexport { DiagConsoleLogger } from './diag/consoleLogger';\nexport {\n DiagLogFunction,\n DiagLogger,\n DiagLogLevel,\n ComponentLoggerOptions,\n DiagLoggerOptions,\n} from './diag/types';\nexport type { DiagAPI } from './api/diag';\n\n// Metrics APIs\nexport { createNoopMeter } from './metrics/NoopMeter';\nexport { MeterOptions, Meter } from './metrics/Meter';\nexport { MeterProvider } from './metrics/MeterProvider';\nexport {\n ValueType,\n Counter,\n Gauge,\n Histogram,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n BatchObservableCallback,\n MetricAdvice,\n MetricAttributes,\n MetricAttributeValue,\n ObservableCallback,\n} from './metrics/Metric';\nexport {\n BatchObservableResult,\n ObservableResult,\n} from './metrics/ObservableResult';\nexport type { MetricsAPI } from './api/metrics';\n\n// Propagation APIs\nexport {\n TextMapPropagator,\n TextMapSetter,\n TextMapGetter,\n defaultTextMapGetter,\n defaultTextMapSetter,\n} from './propagation/TextMapPropagator';\nexport type { PropagationAPI } from './api/propagation';\n\n// Trace APIs\nexport { SpanAttributes, SpanAttributeValue } from './trace/attributes';\nexport { Link } from './trace/link';\nexport { ProxyTracer, TracerDelegator } from './trace/ProxyTracer';\nexport { ProxyTracerProvider } from './trace/ProxyTracerProvider';\nexport { Sampler } from './trace/Sampler';\nexport { SamplingDecision, SamplingResult } from './trace/SamplingResult';\nexport { SpanContext } from './trace/span_context';\nexport { SpanKind } from './trace/span_kind';\nexport { Span } from './trace/span';\nexport { SpanOptions } from './trace/SpanOptions';\nexport { SpanStatus, SpanStatusCode } from './trace/status';\nexport { TraceFlags } from './trace/trace_flags';\nexport { TraceState } from './trace/trace_state';\nexport { createTraceState } from './trace/internal/utils';\nexport { TracerProvider } from './trace/tracer_provider';\nexport { Tracer } from './trace/tracer';\nexport { TracerOptions } from './trace/tracer_options';\nexport {\n isSpanContextValid,\n isValidTraceId,\n isValidSpanId,\n} from './trace/spancontext-utils';\nexport {\n INVALID_SPANID,\n INVALID_TRACEID,\n INVALID_SPAN_CONTEXT,\n} from './trace/invalid-span-constants';\nexport type { TraceAPI } from './api/trace';\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { context } from './context-api';\nimport { diag } from './diag-api';\nimport { metrics } from './metrics-api';\nimport { propagation } from './propagation-api';\nimport { trace } from './trace-api';\n\n// Named export.\nexport { context, diag, metrics, propagation, trace };\n// Default export.\nexport default {\n context,\n diag,\n metrics,\n propagation,\n trace,\n};\n", "import { ATTR_HTTP_RESPONSE_STATUS_CODE } from \"./attributes.mjs\";\nimport { SpanStatusCode, trace } from \"@opentelemetry/api\";\n//#region src/instrumentation/tracer.ts\nconst tracer = trace.getTracer(\"better-auth\", \"1.6.2\");\n/**\n* Better-auth uses `throw ctx.redirect(url)` for flow control (e.g. OAuth\n* callbacks). These are APIErrors with 3xx status codes and should not be\n* recorded as span errors.\n*/\nfunction isRedirectError(err) {\n\tif (err != null && typeof err === \"object\" && \"name\" in err && err.name === \"APIError\" && \"statusCode\" in err) {\n\t\tconst status = err.statusCode;\n\t\treturn status >= 300 && status < 400;\n\t}\n\treturn false;\n}\nfunction endSpanWithError(span, err) {\n\tif (isRedirectError(err)) {\n\t\tspan.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, err.statusCode);\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t} else {\n\t\tspan.recordException(err);\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: String(err?.message ?? err)\n\t\t});\n\t}\n\tspan.end();\n}\nfunction withSpan(name, attributes, fn) {\n\treturn tracer.startActiveSpan(name, { attributes }, (span) => {\n\t\ttry {\n\t\t\tconst result = fn();\n\t\t\tif (result instanceof Promise) return result.then((value) => {\n\t\t\t\tspan.end();\n\t\t\t\treturn value;\n\t\t\t}).catch((err) => {\n\t\t\t\tendSpanWithError(span, err);\n\t\t\t\tthrow err;\n\t\t\t});\n\t\t\tspan.end();\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tendSpanWithError(span, err);\n\t\t\tthrow err;\n\t\t}\n\t});\n}\n//#endregion\nexport { withSpan };\n", "import { createRandomStringGenerator } from \"@better-auth/utils/random\";\n//#region src/utils/id.ts\nconst generateId = (size) => {\n\treturn createRandomStringGenerator(\"a-z\", \"A-Z\", \"0-9\")(size || 32);\n};\n//#endregion\nexport { generateId };\n", "import { BetterAuthError } from \"../../error/index.mjs\";\n//#region src/db/adapter/get-default-model-name.ts\nconst initGetDefaultModelName = ({ usePlural, schema }) => {\n\t/**\n\t* This function helps us get the default model name from the schema defined by devs.\n\t* Often times, the user will be using the `modelName` which could had been customized by the users.\n\t* This function helps us get the actual model name useful to match against the schema. (eg: schema[model])\n\t*\n\t* If it's still unclear what this does:\n\t*\n\t* 1. User can define a custom modelName.\n\t* 2. When using a custom modelName, doing something like `schema[model]` will not work.\n\t* 3. Using this function helps us get the actual model name based on the user's defined custom modelName.\n\t*/\n\tconst getDefaultModelName = (model) => {\n\t\tif (usePlural && model.charAt(model.length - 1) === \"s\") {\n\t\t\tconst pluralessModel = model.slice(0, -1);\n\t\t\tlet m = schema[pluralessModel] ? pluralessModel : void 0;\n\t\t\tif (!m) m = Object.entries(schema).find(([_, f]) => f.modelName === pluralessModel)?.[0];\n\t\t\tif (m) return m;\n\t\t}\n\t\tlet m = schema[model] ? model : void 0;\n\t\tif (!m) m = Object.entries(schema).find(([_, f]) => f.modelName === model)?.[0];\n\t\tif (!m) throw new BetterAuthError(`Model \"${model}\" not found in schema`);\n\t\treturn m;\n\t};\n\treturn getDefaultModelName;\n};\n//#endregion\nexport { initGetDefaultModelName };\n", "import { BetterAuthError } from \"../../error/index.mjs\";\nimport { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\n//#region src/db/adapter/get-default-field-name.ts\nconst initGetDefaultFieldName = ({ schema, usePlural }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tschema,\n\t\tusePlural\n\t});\n\t/**\n\t* This function helps us get the default field name from the schema defined by devs.\n\t* Often times, the user will be using the `fieldName` which could had been customized by the users.\n\t* This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field])\n\t*\n\t* If it's still unclear what this does:\n\t*\n\t* 1. User can define a custom fieldName.\n\t* 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work.\n\t*/\n\tconst getDefaultFieldName = ({ field, model: unsafeModel }) => {\n\t\tif (field === \"id\" || field === \"_id\") return \"id\";\n\t\tconst model = getDefaultModelName(unsafeModel);\n\t\tlet f = schema[model]?.fields[field];\n\t\tif (!f) {\n\t\t\tconst result = Object.entries(schema[model].fields).find(([_, f]) => f.fieldName === field);\n\t\t\tif (result) {\n\t\t\t\tf = result[1];\n\t\t\t\tfield = result[0];\n\t\t\t}\n\t\t}\n\t\tif (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`);\n\t\treturn field;\n\t};\n\treturn getDefaultFieldName;\n};\n//#endregion\nexport { initGetDefaultFieldName };\n", "import { logger } from \"../../env/logger.mjs\";\nimport { generateId } from \"../../utils/id.mjs\";\nimport { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\n//#region src/db/adapter/get-id-field.ts\nconst initGetIdField = ({ usePlural, schema, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tusePlural,\n\t\tschema\n\t});\n\tconst idField = ({ customModelName, forceAllowId }) => {\n\t\tconst useNumberId = options.advanced?.database?.generateId === \"serial\";\n\t\tconst useUUIDs = options.advanced?.database?.generateId === \"uuid\";\n\t\tconst shouldGenerateId = (() => {\n\t\t\tif (disableIdGeneration) return false;\n\t\t\telse if (useNumberId && !forceAllowId) return false;\n\t\t\telse if (useUUIDs) return !supportsUUIDs;\n\t\t\telse return true;\n\t\t})();\n\t\tconst model = getDefaultModelName(customModelName ?? \"id\");\n\t\treturn {\n\t\t\ttype: useNumberId ? \"number\" : \"string\",\n\t\t\trequired: shouldGenerateId ? true : false,\n\t\t\t...shouldGenerateId ? { defaultValue() {\n\t\t\t\tif (disableIdGeneration) return void 0;\n\t\t\t\tconst generateId$1 = options.advanced?.database?.generateId;\n\t\t\t\tif (generateId$1 === false || generateId$1 === \"serial\") return void 0;\n\t\t\t\tif (typeof generateId$1 === \"function\") return generateId$1({ model });\n\t\t\t\tif (generateId$1 === \"uuid\") return crypto.randomUUID();\n\t\t\t\tif (customIdGenerator) return customIdGenerator({ model });\n\t\t\t\treturn generateId();\n\t\t\t} } : {},\n\t\t\ttransform: {\n\t\t\t\tinput: (value) => {\n\t\t\t\t\tif (!value) return void 0;\n\t\t\t\t\tif (useNumberId) {\n\t\t\t\t\t\tconst numberValue = Number(value);\n\t\t\t\t\t\tif (isNaN(numberValue)) return;\n\t\t\t\t\t\treturn numberValue;\n\t\t\t\t\t}\n\t\t\t\t\tif (useUUIDs) {\n\t\t\t\t\t\tif (shouldGenerateId && !forceAllowId) return value;\n\t\t\t\t\t\tif (disableIdGeneration) return void 0;\n\t\t\t\t\t\tif (supportsUUIDs) return void 0;\n\t\t\t\t\t\tif (forceAllowId && typeof value === \"string\") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst stack = (/* @__PURE__ */ new Error()).stack?.split(\"\\n\").filter((_, i) => i !== 1).join(\"\\n\").replace(\"Error:\", \"\");\n\t\t\t\t\t\t\tlogger.warn(\"[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.\", stack);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof value !== \"string\" && !supportsUUIDs) return crypto.randomUUID();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\treturn value;\n\t\t\t\t},\n\t\t\t\toutput: (value) => {\n\t\t\t\t\tif (!value) return void 0;\n\t\t\t\t\treturn String(value);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t};\n\treturn idField;\n};\n//#endregion\nexport { initGetIdField };\n", "import { BetterAuthError } from \"../../error/index.mjs\";\nimport { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\nimport { initGetDefaultFieldName } from \"./get-default-field-name.mjs\";\nimport { initGetIdField } from \"./get-id-field.mjs\";\n//#region src/db/adapter/get-field-attributes.ts\nconst initGetFieldAttributes = ({ usePlural, schema, options, customIdGenerator, disableIdGeneration }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tusePlural,\n\t\tschema\n\t});\n\tconst getDefaultFieldName = initGetDefaultFieldName({\n\t\tusePlural,\n\t\tschema\n\t});\n\tconst idField = initGetIdField({\n\t\tusePlural,\n\t\tschema,\n\t\toptions,\n\t\tcustomIdGenerator,\n\t\tdisableIdGeneration\n\t});\n\tconst getFieldAttributes = ({ model, field }) => {\n\t\tconst defaultModelName = getDefaultModelName(model);\n\t\tconst defaultFieldName = getDefaultFieldName({\n\t\t\tfield,\n\t\t\tmodel: defaultModelName\n\t\t});\n\t\tconst fields = schema[defaultModelName].fields;\n\t\tfields.id = idField({ customModelName: defaultModelName });\n\t\tconst fieldAttributes = fields[defaultFieldName];\n\t\tif (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`);\n\t\treturn fieldAttributes;\n\t};\n\treturn getFieldAttributes;\n};\n//#endregion\nexport { initGetFieldAttributes };\n", "import { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\nimport { initGetDefaultFieldName } from \"./get-default-field-name.mjs\";\n//#region src/db/adapter/get-field-name.ts\nconst initGetFieldName = ({ schema, usePlural }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tschema,\n\t\tusePlural\n\t});\n\tconst getDefaultFieldName = initGetDefaultFieldName({\n\t\tschema,\n\t\tusePlural\n\t});\n\t/**\n\t* Get the field name which is expected to be saved in the database based on the user's schema.\n\t*\n\t* This function is useful if you need to save the field name to the database.\n\t*\n\t* For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema.\n\t*/\n\tfunction getFieldName({ model: modelName, field: fieldName }) {\n\t\tconst model = getDefaultModelName(modelName);\n\t\tconst field = getDefaultFieldName({\n\t\t\tmodel,\n\t\t\tfield: fieldName\n\t\t});\n\t\treturn schema[model]?.fields[field]?.fieldName || field;\n\t}\n\treturn getFieldName;\n};\n//#endregion\nexport { initGetFieldName };\n", "import { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\n//#region src/db/adapter/get-model-name.ts\nconst initGetModelName = ({ usePlural, schema }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tschema,\n\t\tusePlural\n\t});\n\t/**\n\t* Users can overwrite the default model of some tables. This function helps find the correct model name.\n\t* Furthermore, if the user passes `usePlural` as true in their adapter config,\n\t* then we should return the model name ending with an `s`.\n\t*/\n\tconst getModelName = (model) => {\n\t\tconst defaultModelKey = getDefaultModelName(model);\n\t\tif (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName;\n\t\treturn usePlural ? `${model}s` : model;\n\t};\n\treturn getModelName;\n};\n//#endregion\nexport { initGetModelName };\n", "//#region src/db/adapter/utils.ts\nfunction withApplyDefault(value, field, action) {\n\tif (action === \"update\") {\n\t\tif (value === void 0 && field.onUpdate !== void 0) {\n\t\t\tif (typeof field.onUpdate === \"function\") return field.onUpdate();\n\t\t\treturn field.onUpdate;\n\t\t}\n\t\treturn value;\n\t}\n\tif (action === \"create\") {\n\t\tif (value === void 0 || field.required === true && value === null) {\n\t\t\tif (field.defaultValue !== void 0) {\n\t\t\t\tif (typeof field.defaultValue === \"function\") return field.defaultValue();\n\t\t\t\treturn field.defaultValue;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n}\nfunction isObject(item) {\n\treturn item !== null && typeof item === \"object\" && !Array.isArray(item);\n}\nfunction deepmerge(target, source) {\n\tif (Array.isArray(target) && Array.isArray(source)) return [...target, ...source];\n\telse if (isObject(target) && isObject(source)) {\n\t\tconst result = { ...target };\n\t\tfor (const [key, value] of Object.entries(source)) {\n\t\t\tif (value === void 0) continue;\n\t\t\tif (key in target) result[key] = deepmerge(target[key], value);\n\t\t\telse result[key] = value;\n\t\t}\n\t\treturn result;\n\t}\n\treturn source;\n}\n//#endregion\nexport { deepmerge, withApplyDefault };\n", "import { getAuthTables } from \"../get-tables.mjs\";\nimport { getColorDepth } from \"../../env/color-depth.mjs\";\nimport { TTY_COLORS, createLogger } from \"../../env/logger.mjs\";\nimport { BetterAuthError } from \"../../error/index.mjs\";\nimport { ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME } from \"../../instrumentation/attributes.mjs\";\nimport { withSpan } from \"../../instrumentation/tracer.mjs\";\nimport { safeJSONParse } from \"../../utils/json.mjs\";\nimport { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\nimport { initGetDefaultFieldName } from \"./get-default-field-name.mjs\";\nimport { initGetIdField } from \"./get-id-field.mjs\";\nimport { initGetFieldAttributes } from \"./get-field-attributes.mjs\";\nimport { initGetFieldName } from \"./get-field-name.mjs\";\nimport { initGetModelName } from \"./get-model-name.mjs\";\nimport { withApplyDefault } from \"./utils.mjs\";\n//#region src/db/adapter/factory.ts\nlet debugLogs = [];\nlet transactionId = -1;\nconst createAsIsTransaction = (adapter) => (fn) => fn(adapter);\nconst createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => {\n\tconst uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15);\n\tconst config = {\n\t\t...cfg,\n\t\tsupportsBooleans: cfg.supportsBooleans ?? true,\n\t\tsupportsDates: cfg.supportsDates ?? true,\n\t\tsupportsJSON: cfg.supportsJSON ?? false,\n\t\tadapterName: cfg.adapterName ?? cfg.adapterId,\n\t\tsupportsNumericIds: cfg.supportsNumericIds ?? true,\n\t\tsupportsUUIDs: cfg.supportsUUIDs ?? false,\n\t\tsupportsArrays: cfg.supportsArrays ?? false,\n\t\ttransaction: cfg.transaction ?? false,\n\t\tdisableTransformInput: cfg.disableTransformInput ?? false,\n\t\tdisableTransformOutput: cfg.disableTransformOutput ?? false,\n\t\tdisableTransformJoin: cfg.disableTransformJoin ?? false\n\t};\n\tif (options.advanced?.database?.generateId === \"serial\" && config.supportsNumericIds === false) throw new BetterAuthError(`[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable \"useNumberId\" in your config.`);\n\tconst schema = getAuthTables(options);\n\tconst debugLog = (...args) => {\n\t\tif (config.debugLogs === true || typeof config.debugLogs === \"object\") {\n\t\t\tconst logger = createLogger({ level: \"info\" });\n\t\t\tif (typeof config.debugLogs === \"object\" && \"isRunningAdapterTests\" in config.debugLogs) {\n\t\t\t\tif (config.debugLogs.isRunningAdapterTests) {\n\t\t\t\t\targs.shift();\n\t\t\t\t\tdebugLogs.push({\n\t\t\t\t\t\tinstance: uniqueAdapterFactoryInstanceId,\n\t\t\t\t\t\targs\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (typeof config.debugLogs === \"object\" && config.debugLogs.logCondition && !config.debugLogs.logCondition?.()) return;\n\t\t\tif (typeof args[0] === \"object\" && \"method\" in args[0]) {\n\t\t\t\tconst method = args.shift().method;\n\t\t\t\tif (typeof config.debugLogs === \"object\") {\n\t\t\t\t\tif (method === \"create\" && !config.debugLogs.create) return;\n\t\t\t\t\telse if (method === \"update\" && !config.debugLogs.update) return;\n\t\t\t\t\telse if (method === \"updateMany\" && !config.debugLogs.updateMany) return;\n\t\t\t\t\telse if (method === \"findOne\" && !config.debugLogs.findOne) return;\n\t\t\t\t\telse if (method === \"findMany\" && !config.debugLogs.findMany) return;\n\t\t\t\t\telse if (method === \"delete\" && !config.debugLogs.delete) return;\n\t\t\t\t\telse if (method === \"deleteMany\" && !config.debugLogs.deleteMany) return;\n\t\t\t\t\telse if (method === \"count\" && !config.debugLogs.count) return;\n\t\t\t\t}\n\t\t\t\tlogger.info(`[${config.adapterName}]`, ...args);\n\t\t\t} else logger.info(`[${config.adapterName}]`, ...args);\n\t\t}\n\t};\n\tconst logger = createLogger(options.logger);\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tusePlural: config.usePlural,\n\t\tschema\n\t});\n\tconst getDefaultFieldName = initGetDefaultFieldName({\n\t\tusePlural: config.usePlural,\n\t\tschema\n\t});\n\tconst getModelName = initGetModelName({\n\t\tusePlural: config.usePlural,\n\t\tschema\n\t});\n\tconst getFieldName = initGetFieldName({\n\t\tschema,\n\t\tusePlural: config.usePlural\n\t});\n\tconst idField = initGetIdField({\n\t\tschema,\n\t\toptions,\n\t\tusePlural: config.usePlural,\n\t\tdisableIdGeneration: config.disableIdGeneration,\n\t\tcustomIdGenerator: config.customIdGenerator,\n\t\tsupportsUUIDs: config.supportsUUIDs\n\t});\n\tconst getFieldAttributes = initGetFieldAttributes({\n\t\tschema,\n\t\toptions,\n\t\tusePlural: config.usePlural,\n\t\tdisableIdGeneration: config.disableIdGeneration,\n\t\tcustomIdGenerator: config.customIdGenerator\n\t});\n\tconst transformInput = async (data, defaultModelName, action, forceAllowId) => {\n\t\tconst transformedData = {};\n\t\tconst fields = schema[defaultModelName].fields;\n\t\tconst newMappedKeys = config.mapKeysTransformInput ?? {};\n\t\tconst useNumberId = options.advanced?.database?.generateId === \"serial\";\n\t\tfields.id = idField({\n\t\t\tcustomModelName: defaultModelName,\n\t\t\tforceAllowId: forceAllowId && \"id\" in data\n\t\t});\n\t\tfor (const field in fields) {\n\t\t\tlet value = data[field];\n\t\t\tconst fieldAttributes = fields[field];\n\t\t\tconst newFieldName = newMappedKeys[field] || fields[field].fieldName || field;\n\t\t\tif (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === \"update\" && fieldAttributes.onUpdate) || action === \"update\" && !fieldAttributes.onUpdate)) continue;\n\t\t\tif (fieldAttributes && fieldAttributes.type === \"date\" && !(value instanceof Date) && typeof value === \"string\") try {\n\t\t\t\tvalue = new Date(value);\n\t\t\t} catch {\n\t\t\t\tlogger.error(\"[Adapter Factory] Failed to convert string to date\", {\n\t\t\t\t\tvalue,\n\t\t\t\t\tfield\n\t\t\t\t});\n\t\t\t}\n\t\t\tlet newValue = withApplyDefault(value, fieldAttributes, action);\n\t\t\tif (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue);\n\t\t\tif (fieldAttributes.references?.field === \"id\" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null);\n\t\t\telse newValue = newValue !== null ? Number(newValue) : null;\n\t\t\telse if (config.supportsJSON === false && typeof newValue === \"object\" && fieldAttributes.type === \"json\") newValue = JSON.stringify(newValue);\n\t\t\telse if (config.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === \"string[]\" || fieldAttributes.type === \"number[]\")) newValue = JSON.stringify(newValue);\n\t\t\telse if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === \"date\") newValue = newValue.toISOString();\n\t\t\telse if (config.supportsBooleans === false && typeof newValue === \"boolean\") newValue = newValue ? 1 : 0;\n\t\t\tif (config.customTransformInput) newValue = config.customTransformInput({\n\t\t\t\tdata: newValue,\n\t\t\t\taction,\n\t\t\t\tfield: newFieldName,\n\t\t\t\tfieldAttributes,\n\t\t\t\tmodel: getModelName(defaultModelName),\n\t\t\t\tschema,\n\t\t\t\toptions\n\t\t\t});\n\t\t\tif (newValue !== void 0) transformedData[newFieldName] = newValue;\n\t\t}\n\t\treturn transformedData;\n\t};\n\tconst transformOutput = async (data, unsafe_model, select = [], join) => {\n\t\tconst transformSingleOutput = async (data, unsafe_model, select = []) => {\n\t\t\tif (!data) return null;\n\t\t\tconst newMappedKeys = config.mapKeysTransformOutput ?? {};\n\t\t\tconst transformedData = {};\n\t\t\tconst tableSchema = schema[getDefaultModelName(unsafe_model)].fields;\n\t\t\tconst idKey = Object.entries(newMappedKeys).find(([_, v]) => v === \"id\")?.[0];\n\t\t\ttableSchema[idKey ?? \"id\"] = { type: options.advanced?.database?.generateId === \"serial\" ? \"number\" : \"string\" };\n\t\t\tfor (const key in tableSchema) {\n\t\t\t\tif (select.length && !select.includes(key)) continue;\n\t\t\t\tconst field = tableSchema[key];\n\t\t\t\tif (field) {\n\t\t\t\t\tconst originalKey = field.fieldName || key;\n\t\t\t\t\tlet newValue = data[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey];\n\t\t\t\t\tif (field.transform?.output) newValue = await field.transform.output(newValue);\n\t\t\t\t\tconst newFieldName = newMappedKeys[key] || key;\n\t\t\t\t\tif (originalKey === \"id\" || field.references?.field === \"id\") {\n\t\t\t\t\t\tif (typeof newValue !== \"undefined\" && newValue !== null) newValue = String(newValue);\n\t\t\t\t\t} else if (config.supportsJSON === false && typeof newValue === \"string\" && field.type === \"json\") newValue = safeJSONParse(newValue);\n\t\t\t\t\telse if (config.supportsArrays === false && typeof newValue === \"string\" && (field.type === \"string[]\" || field.type === \"number[]\")) newValue = safeJSONParse(newValue);\n\t\t\t\t\telse if (config.supportsDates === false && typeof newValue === \"string\" && field.type === \"date\") newValue = new Date(newValue);\n\t\t\t\t\telse if (config.supportsBooleans === false && typeof newValue === \"number\" && field.type === \"boolean\") newValue = newValue === 1;\n\t\t\t\t\tif (config.customTransformOutput) newValue = config.customTransformOutput({\n\t\t\t\t\t\tdata: newValue,\n\t\t\t\t\t\tfield: newFieldName,\n\t\t\t\t\t\tfieldAttributes: field,\n\t\t\t\t\t\tselect,\n\t\t\t\t\t\tmodel: getModelName(unsafe_model),\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\toptions\n\t\t\t\t\t});\n\t\t\t\t\ttransformedData[newFieldName] = newValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn transformedData;\n\t\t};\n\t\tif (!join || Object.keys(join).length === 0) return await transformSingleOutput(data, unsafe_model, select);\n\t\tunsafe_model = getDefaultModelName(unsafe_model);\n\t\tconst transformedData = await transformSingleOutput(data, unsafe_model, select);\n\t\tconst requiredModels = Object.entries(join).map(([model, joinConfig]) => ({\n\t\t\tmodelName: getModelName(model),\n\t\t\tdefaultModelName: getDefaultModelName(model),\n\t\t\tjoinConfig\n\t\t}));\n\t\tif (!data) return null;\n\t\tfor (const { modelName, defaultModelName, joinConfig } of requiredModels) {\n\t\t\tlet joinedData = await (async () => {\n\t\t\t\tif (options.experimental?.joins) return data[modelName];\n\t\t\t\telse return await handleFallbackJoin({\n\t\t\t\t\tbaseModel: unsafe_model,\n\t\t\t\t\tbaseData: transformedData,\n\t\t\t\t\tjoinModel: modelName,\n\t\t\t\t\tspecificJoinConfig: joinConfig\n\t\t\t\t});\n\t\t\t})();\n\t\t\tif (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === \"one-to-one\" ? null : [];\n\t\t\tif (joinConfig.relation === \"one-to-many\" && !Array.isArray(joinedData)) joinedData = [joinedData];\n\t\t\tconst transformed = [];\n\t\t\tif (Array.isArray(joinedData)) for (const item of joinedData) {\n\t\t\t\tconst transformedItem = await transformSingleOutput(item, modelName, []);\n\t\t\t\ttransformed.push(transformedItem);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst transformedItem = await transformSingleOutput(joinedData, modelName, []);\n\t\t\t\ttransformed.push(transformedItem);\n\t\t\t}\n\t\t\ttransformedData[defaultModelName] = (joinConfig.relation === \"one-to-one\" ? transformed[0] : transformed) ?? null;\n\t\t}\n\t\treturn transformedData;\n\t};\n\tconst transformWhereClause = ({ model, where, action }) => {\n\t\tif (!where) return void 0;\n\t\tconst newMappedKeys = config.mapKeysTransformInput ?? {};\n\t\treturn where.map((w) => {\n\t\t\tconst { field: unsafe_field, value, operator = \"eq\", connector = \"AND\", mode = \"sensitive\" } = w;\n\t\t\tif (operator === \"in\") {\n\t\t\t\tif (!Array.isArray(value)) throw new BetterAuthError(\"Value must be an array\");\n\t\t\t}\n\t\t\tlet newValue = value;\n\t\t\tconst defaultModelName = getDefaultModelName(model);\n\t\t\tconst defaultFieldName = getDefaultFieldName({\n\t\t\t\tfield: unsafe_field,\n\t\t\t\tmodel\n\t\t\t});\n\t\t\tconst fieldName = newMappedKeys[defaultFieldName] || getFieldName({\n\t\t\t\tfield: defaultFieldName,\n\t\t\t\tmodel: defaultModelName\n\t\t\t});\n\t\t\tconst fieldAttr = getFieldAttributes({\n\t\t\t\tfield: defaultFieldName,\n\t\t\t\tmodel: defaultModelName\n\t\t\t});\n\t\t\tconst useNumberId = options.advanced?.database?.generateId === \"serial\";\n\t\t\tif (defaultFieldName === \"id\" || fieldAttr.references?.field === \"id\") {\n\t\t\t\tif (useNumberId) if (Array.isArray(value)) newValue = value.map(Number);\n\t\t\t\telse newValue = Number(value);\n\t\t\t}\n\t\t\tif (fieldAttr.type === \"date\" && value instanceof Date && !config.supportsDates) newValue = value.toISOString();\n\t\t\tif (fieldAttr.type === \"boolean\" && typeof newValue === \"string\") newValue = newValue === \"true\";\n\t\t\tif (fieldAttr.type === \"number\") {\n\t\t\t\tif (typeof newValue === \"string\" && newValue.trim() !== \"\") {\n\t\t\t\t\tconst parsed = Number(newValue);\n\t\t\t\t\tif (!Number.isNaN(parsed)) newValue = parsed;\n\t\t\t\t} else if (Array.isArray(newValue)) {\n\t\t\t\t\tconst parsed = newValue.map((v) => typeof v === \"string\" && v.trim() !== \"\" ? Number(v) : NaN);\n\t\t\t\t\tif (parsed.every((n) => !Number.isNaN(n))) newValue = parsed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (fieldAttr.type === \"boolean\" && typeof newValue === \"boolean\" && !config.supportsBooleans) newValue = newValue ? 1 : 0;\n\t\t\tif (fieldAttr.type === \"json\" && typeof value === \"object\" && !config.supportsJSON) try {\n\t\t\t\tnewValue = JSON.stringify(value);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error });\n\t\t\t}\n\t\t\tif (config.customTransformInput) newValue = config.customTransformInput({\n\t\t\t\tdata: newValue,\n\t\t\t\tfieldAttributes: fieldAttr,\n\t\t\t\tfield: fieldName,\n\t\t\t\tmodel: getModelName(model),\n\t\t\t\tschema,\n\t\t\t\toptions,\n\t\t\t\taction\n\t\t\t});\n\t\t\treturn {\n\t\t\t\toperator,\n\t\t\t\tconnector,\n\t\t\t\tfield: fieldName,\n\t\t\t\tvalue: newValue,\n\t\t\t\tmode\n\t\t\t};\n\t\t});\n\t};\n\tconst transformJoinClause = (baseModel, unsanitizedJoin, select) => {\n\t\tif (!unsanitizedJoin) return void 0;\n\t\tif (Object.keys(unsanitizedJoin).length === 0) return void 0;\n\t\tconst transformedJoin = {};\n\t\tfor (const [model, join] of Object.entries(unsanitizedJoin)) {\n\t\t\tif (!join) continue;\n\t\t\tconst defaultModelName = getDefaultModelName(model);\n\t\t\tconst defaultBaseModelName = getDefaultModelName(baseModel);\n\t\t\tlet foreignKeys = Object.entries(schema[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName);\n\t\t\tlet isForwardJoin = true;\n\t\t\tif (!foreignKeys.length) {\n\t\t\t\tforeignKeys = Object.entries(schema[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName);\n\t\t\t\tisForwardJoin = false;\n\t\t\t}\n\t\t\tif (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`);\n\t\t\telse if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`);\n\t\t\tconst [foreignKey, foreignKeyAttributes] = foreignKeys[0];\n\t\t\tif (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`);\n\t\t\tlet from;\n\t\t\tlet to;\n\t\t\tlet requiredSelectField;\n\t\t\tif (isForwardJoin) {\n\t\t\t\trequiredSelectField = foreignKeyAttributes.references.field;\n\t\t\t\tfrom = getFieldName({\n\t\t\t\t\tmodel: baseModel,\n\t\t\t\t\tfield: requiredSelectField\n\t\t\t\t});\n\t\t\t\tto = getFieldName({\n\t\t\t\t\tmodel,\n\t\t\t\t\tfield: foreignKey\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\trequiredSelectField = foreignKey;\n\t\t\t\tfrom = getFieldName({\n\t\t\t\t\tmodel: baseModel,\n\t\t\t\t\tfield: requiredSelectField\n\t\t\t\t});\n\t\t\t\tto = getFieldName({\n\t\t\t\t\tmodel,\n\t\t\t\t\tfield: foreignKeyAttributes.references.field\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (select && !select.includes(requiredSelectField)) select.push(requiredSelectField);\n\t\t\tconst isUnique = to === \"id\" ? true : foreignKeyAttributes.unique ?? false;\n\t\t\tlet limit = options.advanced?.database?.defaultFindManyLimit ?? 100;\n\t\t\tif (isUnique) limit = 1;\n\t\t\telse if (typeof join === \"object\" && typeof join.limit === \"number\") limit = join.limit;\n\t\t\ttransformedJoin[getModelName(model)] = {\n\t\t\t\ton: {\n\t\t\t\t\tfrom,\n\t\t\t\t\tto\n\t\t\t\t},\n\t\t\t\tlimit,\n\t\t\t\trelation: isUnique ? \"one-to-one\" : \"one-to-many\"\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tjoin: transformedJoin,\n\t\t\tselect\n\t\t};\n\t};\n\t/**\n\t* Handle joins by making separate queries and combining results (fallback for adapters that don't support native joins).\n\t*/\n\tconst handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => {\n\t\tif (!baseData) return baseData;\n\t\tconst modelName = getModelName(joinModel);\n\t\tconst field = joinConfig.on.to;\n\t\tconst value = baseData[getDefaultFieldName({\n\t\t\tfield: joinConfig.on.from,\n\t\t\tmodel: baseModel\n\t\t})];\n\t\tif (value === null || value === void 0) return joinConfig.relation === \"one-to-one\" ? null : [];\n\t\tlet result;\n\t\tconst where = transformWhereClause({\n\t\t\tmodel: modelName,\n\t\t\twhere: [{\n\t\t\t\tfield,\n\t\t\t\tvalue,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}],\n\t\t\taction: \"findOne\"\n\t\t});\n\t\ttry {\n\t\t\tif (joinConfig.relation === \"one-to-one\") result = await withSpan(`db findOne ${modelName}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"findOne\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: modelName\n\t\t\t}, () => adapterInstance.findOne({\n\t\t\t\tmodel: modelName,\n\t\t\t\twhere\n\t\t\t}));\n\t\t\telse {\n\t\t\t\tconst limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;\n\t\t\t\tresult = await withSpan(`db findMany ${modelName}`, {\n\t\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"findMany\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: modelName\n\t\t\t\t}, () => adapterInstance.findMany({\n\t\t\t\t\tmodel: modelName,\n\t\t\t\t\twhere,\n\t\t\t\t\tlimit\n\t\t\t\t}));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Failed to query fallback join for model ${modelName}:`, {\n\t\t\t\twhere,\n\t\t\t\tlimit: joinConfig.limit\n\t\t\t});\n\t\t\tconsole.error(error);\n\t\t\tthrow error;\n\t\t}\n\t\treturn result;\n\t};\n\tconst adapterInstance = customAdapter({\n\t\toptions,\n\t\tschema,\n\t\tdebugLog,\n\t\tgetFieldName,\n\t\tgetModelName,\n\t\tgetDefaultModelName,\n\t\tgetDefaultFieldName,\n\t\tgetFieldAttributes,\n\t\ttransformInput,\n\t\ttransformOutput,\n\t\ttransformWhereClause\n\t});\n\tlet lazyLoadTransaction = null;\n\tconst adapter = {\n\t\ttransaction: async (cb) => {\n\t\t\tif (!lazyLoadTransaction) if (!config.transaction) lazyLoadTransaction = createAsIsTransaction(adapter);\n\t\t\telse {\n\t\t\t\tlogger.debug(`[${config.adapterName}] - Using provided transaction implementation.`);\n\t\t\t\tlazyLoadTransaction = config.transaction;\n\t\t\t}\n\t\t\treturn lazyLoadTransaction(cb);\n\t\t},\n\t\tcreate: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tif (\"id\" in unsafeData && typeof unsafeData.id !== \"undefined\" && !forceAllowId) {\n\t\t\t\tlogger.warn(`[${config.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \\`forceAllowId\\` parameter. The id will be ignored.`);\n\t\t\t\tconst stack = (/* @__PURE__ */ new Error()).stack?.split(\"\\n\").filter((_, i) => i !== 1).join(\"\\n\").replace(\"Error:\", \"Create method with `id` being called at:\");\n\t\t\t\tconsole.log(stack);\n\t\t\t\tunsafeData.id = void 0;\n\t\t\t}\n\t\t\tdebugLog({ method: \"create\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod(\"create\")} ${formatAction(\"Unsafe Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: unsafeData\n\t\t\t});\n\t\t\tlet data = unsafeData;\n\t\t\tif (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, \"create\", forceAllowId);\n\t\t\tdebugLog({ method: \"create\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod(\"create\")} ${formatAction(\"Parsed Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata\n\t\t\t});\n\t\t\tconst res = await withSpan(`db create ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"create\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.create({\n\t\t\t\tdata,\n\t\t\t\tmodel\n\t\t\t}));\n\t\t\tdebugLog({ method: \"create\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod(\"create\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tres\n\t\t\t});\n\t\t\tlet transformed = res;\n\t\t\tif (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0);\n\t\t\tdebugLog({ method: \"create\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod(\"create\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: transformed\n\t\t\t});\n\t\t\treturn transformed;\n\t\t},\n\t\tupdate: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"update\"\n\t\t\t});\n\t\t\tdebugLog({ method: \"update\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod(\"update\")} ${formatAction(\"Unsafe Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: unsafeData\n\t\t\t});\n\t\t\tlet data = unsafeData;\n\t\t\tif (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, \"update\");\n\t\t\tdebugLog({ method: \"update\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod(\"update\")} ${formatAction(\"Parsed Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata\n\t\t\t});\n\t\t\tconst res = await withSpan(`db update ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"update\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.update({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tupdate: data\n\t\t\t}));\n\t\t\tdebugLog({ method: \"update\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod(\"update\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\tlet transformed = res;\n\t\t\tif (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0);\n\t\t\tdebugLog({ method: \"update\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod(\"update\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: transformed\n\t\t\t});\n\t\t\treturn transformed;\n\t\t},\n\t\tupdateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"updateMany\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tdebugLog({ method: \"updateMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod(\"updateMany\")} ${formatAction(\"Unsafe Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: unsafeData\n\t\t\t});\n\t\t\tlet data = unsafeData;\n\t\t\tif (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, \"update\");\n\t\t\tdebugLog({ method: \"updateMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod(\"updateMany\")} ${formatAction(\"Parsed Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata\n\t\t\t});\n\t\t\tconst updatedCount = await withSpan(`db updateMany ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"updateMany\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.updateMany({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tupdate: data\n\t\t\t}));\n\t\t\tdebugLog({ method: \"updateMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod(\"updateMany\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: updatedCount\n\t\t\t});\n\t\t\tdebugLog({ method: \"updateMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod(\"updateMany\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: updatedCount\n\t\t\t});\n\t\t\treturn updatedCount;\n\t\t},\n\t\tfindOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"findOne\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tlet join;\n\t\t\tlet passJoinToAdapter = true;\n\t\t\tif (!config.disableTransformJoin) {\n\t\t\t\tconst result = transformJoinClause(unsafeModel, unsafeJoin, select);\n\t\t\t\tif (result) {\n\t\t\t\t\tjoin = result.join;\n\t\t\t\t\tselect = result.select;\n\t\t\t\t}\n\t\t\t\tif (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false;\n\t\t\t} else join = unsafeJoin;\n\t\t\tdebugLog({ method: \"findOne\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod(\"findOne\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tselect,\n\t\t\t\tjoin\n\t\t\t});\n\t\t\tconst res = await withSpan(`db findOne ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"findOne\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.findOne({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tselect,\n\t\t\t\tjoin: passJoinToAdapter ? join : void 0\n\t\t\t}));\n\t\t\tdebugLog({ method: \"findOne\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod(\"findOne\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\tlet transformed = res;\n\t\t\tif (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join);\n\t\t\tdebugLog({ method: \"findOne\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod(\"findOne\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: transformed\n\t\t\t});\n\t\t\treturn transformed;\n\t\t},\n\t\tfindMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, select, sortBy, offset, join: unsafeJoin }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"findMany\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tlet join;\n\t\t\tlet passJoinToAdapter = true;\n\t\t\tif (!config.disableTransformJoin) {\n\t\t\t\tconst result = transformJoinClause(unsafeModel, unsafeJoin, select);\n\t\t\t\tif (result) {\n\t\t\t\t\tjoin = result.join;\n\t\t\t\t\tselect = result.select;\n\t\t\t\t}\n\t\t\t\tif (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false;\n\t\t\t} else join = unsafeJoin;\n\t\t\tdebugLog({ method: \"findMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod(\"findMany\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\tsortBy,\n\t\t\t\toffset,\n\t\t\t\tjoin\n\t\t\t});\n\t\t\tconst res = await withSpan(`db findMany ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"findMany\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.findMany({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\tselect,\n\t\t\t\tsortBy,\n\t\t\t\toffset,\n\t\t\t\tjoin: passJoinToAdapter ? join : void 0\n\t\t\t}));\n\t\t\tdebugLog({ method: \"findMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod(\"findMany\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\tlet transformed = res;\n\t\t\tif (!config.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => {\n\t\t\t\treturn await transformOutput(r, unsafeModel, void 0, join);\n\t\t\t}));\n\t\t\tdebugLog({ method: \"findMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod(\"findMany\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: transformed\n\t\t\t});\n\t\t\treturn transformed;\n\t\t},\n\t\tdelete: async ({ model: unsafeModel, where: unsafeWhere }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"delete\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tdebugLog({ method: \"delete\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod(\"delete\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t});\n\t\t\tawait withSpan(`db delete ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"delete\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.delete({\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t}));\n\t\t\tdebugLog({ method: \"delete\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod(\"delete\")} ${formatAction(\"DB Result\")}:`, { model });\n\t\t},\n\t\tdeleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"deleteMany\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tdebugLog({ method: \"deleteMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod(\"deleteMany\")} ${formatAction(\"DeleteMany\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t});\n\t\t\tconst res = await withSpan(`db deleteMany ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"deleteMany\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.deleteMany({\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t}));\n\t\t\tdebugLog({ method: \"deleteMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod(\"deleteMany\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\treturn res;\n\t\t},\n\t\tcount: async ({ model: unsafeModel, where: unsafeWhere }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"count\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tdebugLog({ method: \"count\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod(\"count\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t});\n\t\t\tconst res = await withSpan(`db count ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"count\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.count({\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t}));\n\t\t\tdebugLog({ method: \"count\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod(\"count\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\treturn res;\n\t\t},\n\t\tcreateSchema: adapterInstance.createSchema ? async (_, file) => {\n\t\t\tconst tables = getAuthTables(options);\n\t\t\tif (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session;\n\t\t\treturn adapterInstance.createSchema({\n\t\t\t\tfile,\n\t\t\t\ttables\n\t\t\t});\n\t\t} : void 0,\n\t\toptions: {\n\t\t\tadapterConfig: config,\n\t\t\t...adapterInstance.options ?? {}\n\t\t},\n\t\tid: config.adapterId,\n\t\t...config.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: {\n\t\t\tresetDebugLogs() {\n\t\t\t\tdebugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId);\n\t\t\t},\n\t\t\tprintDebugLogs() {\n\t\t\t\tconst separator = `\u2500`.repeat(80);\n\t\t\t\tconst logs = debugLogs.filter((log) => log.instance === uniqueAdapterFactoryInstanceId);\n\t\t\t\tif (logs.length === 0) return;\n\t\t\t\tconst log = logs.reverse().map((log) => {\n\t\t\t\t\tlog.args[0] = `\\n${log.args[0]}`;\n\t\t\t\t\treturn [...log.args, \"\\n\"];\n\t\t\t\t}).reduce((prev, curr) => {\n\t\t\t\t\treturn [...curr, ...prev];\n\t\t\t\t}, [`\\n${separator}`]);\n\t\t\t\tconsole.log(...log);\n\t\t\t}\n\t\t} } : {}\n\t};\n\treturn adapter;\n};\nfunction formatTransactionId(transactionId) {\n\tif (getColorDepth() < 8) return `#${transactionId}`;\n\treturn `${TTY_COLORS.fg.magenta}#${transactionId}${TTY_COLORS.reset}`;\n}\nfunction formatStep(step, total) {\n\treturn `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`;\n}\nfunction formatMethod(method) {\n\treturn `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`;\n}\nfunction formatAction(action) {\n\treturn `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`;\n}\n//#endregion\nexport { createAdapterFactory };\n", "import { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\nimport { initGetDefaultFieldName } from \"./get-default-field-name.mjs\";\nimport { initGetIdField } from \"./get-id-field.mjs\";\nimport { initGetFieldAttributes } from \"./get-field-attributes.mjs\";\nimport { initGetFieldName } from \"./get-field-name.mjs\";\nimport { initGetModelName } from \"./get-model-name.mjs\";\nimport { deepmerge, withApplyDefault } from \"./utils.mjs\";\nimport { createAdapterFactory } from \"./factory.mjs\";\n//#region src/db/adapter/index.ts\nconst whereOperators = [\n\t\"eq\",\n\t\"ne\",\n\t\"lt\",\n\t\"lte\",\n\t\"gt\",\n\t\"gte\",\n\t\"in\",\n\t\"not_in\",\n\t\"contains\",\n\t\"starts_with\",\n\t\"ends_with\"\n];\n//#endregion\nexport { createAdapterFactory, deepmerge, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName, whereOperators, withApplyDefault };\n", "import { createAdapterFactory } from \"@better-auth/core/db/adapter\";\nimport { logger } from \"@better-auth/core/env\";\n//#region src/query-builders.ts\n/**\n* Case-insensitive in-memory comparison helpers.\n* Used when evaluating where clauses in the memory adapter.\n*/\nfunction insensitiveCompare(a, b) {\n\tif (typeof a === \"string\" && typeof b === \"string\") return a.toLowerCase() === b.toLowerCase();\n\treturn a === b;\n}\nfunction insensitiveIn(recordVal, values) {\n\tif (typeof recordVal !== \"string\") return values.includes(recordVal);\n\treturn values.some((v) => typeof v === \"string\" && recordVal.toLowerCase() === v.toLowerCase());\n}\nfunction insensitiveNotIn(recordVal, values) {\n\treturn !insensitiveIn(recordVal, values);\n}\nfunction insensitiveContains(recordVal, value) {\n\tif (typeof recordVal !== \"string\" || typeof value !== \"string\") return false;\n\treturn recordVal.toLowerCase().includes(value.toLowerCase());\n}\nfunction insensitiveStartsWith(recordVal, value) {\n\tif (typeof recordVal !== \"string\" || typeof value !== \"string\") return false;\n\treturn recordVal.toLowerCase().startsWith(value.toLowerCase());\n}\nfunction insensitiveEndsWith(recordVal, value) {\n\tif (typeof recordVal !== \"string\" || typeof value !== \"string\") return false;\n\treturn recordVal.toLowerCase().endsWith(value.toLowerCase());\n}\n//#endregion\n//#region src/memory-adapter.ts\nconst memoryAdapter = (db, config) => {\n\tlet lazyOptions = null;\n\tconst adapterCreator = createAdapterFactory({\n\t\tconfig: {\n\t\t\tadapterId: \"memory\",\n\t\t\tadapterName: \"Memory Adapter\",\n\t\t\tusePlural: false,\n\t\t\tdebugLogs: config?.debugLogs || false,\n\t\t\tsupportsArrays: true,\n\t\t\tcustomTransformInput(props) {\n\t\t\t\tif (props.options.advanced?.database?.generateId === \"serial\" && props.field === \"id\" && props.action === \"create\") return db[props.model].length + 1;\n\t\t\t\treturn props.data;\n\t\t\t},\n\t\t\ttransaction: async (cb) => {\n\t\t\t\tconst clone = structuredClone(db);\n\t\t\t\ttry {\n\t\t\t\t\treturn await cb(adapterCreator(lazyOptions));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tObject.keys(db).forEach((key) => {\n\t\t\t\t\t\tdb[key] = clone[key];\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tadapter: ({ getFieldName, getDefaultFieldName, options, getModelName }) => {\n\t\t\tconst applySortToRecords = (records, sortBy, model) => {\n\t\t\t\tif (!sortBy) return records;\n\t\t\t\treturn records.sort((a, b) => {\n\t\t\t\t\tconst field = getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield: sortBy.field\n\t\t\t\t\t});\n\t\t\t\t\tconst aValue = a[field];\n\t\t\t\t\tconst bValue = b[field];\n\t\t\t\t\tlet comparison = 0;\n\t\t\t\t\tif (aValue == null && bValue == null) comparison = 0;\n\t\t\t\t\telse if (aValue == null) comparison = -1;\n\t\t\t\t\telse if (bValue == null) comparison = 1;\n\t\t\t\t\telse if (typeof aValue === \"string\" && typeof bValue === \"string\") comparison = aValue.localeCompare(bValue);\n\t\t\t\t\telse if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime();\n\t\t\t\t\telse if (typeof aValue === \"number\" && typeof bValue === \"number\") comparison = aValue - bValue;\n\t\t\t\t\telse if (typeof aValue === \"boolean\" && typeof bValue === \"boolean\") comparison = aValue === bValue ? 0 : aValue ? 1 : -1;\n\t\t\t\t\telse comparison = String(aValue).localeCompare(String(bValue));\n\t\t\t\t\treturn sortBy.direction === \"asc\" ? comparison : -comparison;\n\t\t\t\t});\n\t\t\t};\n\t\t\tfunction convertWhereClause(where, model, join, select) {\n\t\t\t\tconst baseRecords = (() => {\n\t\t\t\t\tconst table = db[model];\n\t\t\t\t\tif (!table) {\n\t\t\t\t\t\tlogger.error(`[MemoryAdapter] Model ${model} not found in the DB`, Object.keys(db));\n\t\t\t\t\t\tthrow new Error(`Model ${model} not found`);\n\t\t\t\t\t}\n\t\t\t\t\tconst evalClause = (record, clause) => {\n\t\t\t\t\t\tconst { field, value, operator, mode = \"sensitive\" } = clause;\n\t\t\t\t\t\tconst isInsensitive = mode === \"insensitive\" && (typeof value === \"string\" || Array.isArray(value) && value.every((v) => typeof v === \"string\"));\n\t\t\t\t\t\tswitch (operator) {\n\t\t\t\t\t\t\tcase \"in\":\n\t\t\t\t\t\t\t\tif (!Array.isArray(value)) throw new Error(\"Value must be an array\");\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveIn(record[field], value);\n\t\t\t\t\t\t\t\treturn value.includes(record[field]);\n\t\t\t\t\t\t\tcase \"not_in\":\n\t\t\t\t\t\t\t\tif (!Array.isArray(value)) throw new Error(\"Value must be an array\");\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveNotIn(record[field], value);\n\t\t\t\t\t\t\t\treturn !value.includes(record[field]);\n\t\t\t\t\t\t\tcase \"contains\":\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveContains(record[field], value);\n\t\t\t\t\t\t\t\treturn record[field]?.includes(value);\n\t\t\t\t\t\t\tcase \"starts_with\":\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveStartsWith(record[field], value);\n\t\t\t\t\t\t\t\treturn record[field].startsWith(value);\n\t\t\t\t\t\t\tcase \"ends_with\":\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveEndsWith(record[field], value);\n\t\t\t\t\t\t\t\treturn record[field].endsWith(value);\n\t\t\t\t\t\t\tcase \"ne\": return isInsensitive ? !insensitiveCompare(record[field], value) : record[field] !== value;\n\t\t\t\t\t\t\tcase \"gt\": return value != null && Boolean(record[field] > value);\n\t\t\t\t\t\t\tcase \"gte\": return value != null && Boolean(record[field] >= value);\n\t\t\t\t\t\t\tcase \"lt\": return value != null && Boolean(record[field] < value);\n\t\t\t\t\t\t\tcase \"lte\": return value != null && Boolean(record[field] <= value);\n\t\t\t\t\t\t\tdefault: return isInsensitive ? insensitiveCompare(record[field], value) : record[field] === value;\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\tlet records = table.filter((record) => {\n\t\t\t\t\t\tif (!where.length || where.length === 0) return true;\n\t\t\t\t\t\tlet result = evalClause(record, where[0]);\n\t\t\t\t\t\tfor (const clause of where) {\n\t\t\t\t\t\t\tconst clauseResult = evalClause(record, clause);\n\t\t\t\t\t\t\tif (clause.connector === \"OR\") result = result || clauseResult;\n\t\t\t\t\t\t\telse result = result && clauseResult;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t});\n\t\t\t\t\tif (select?.length && select.length > 0) records = records.map((record) => Object.fromEntries(Object.entries(record).filter(([key]) => select.includes(getDefaultFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield: key\n\t\t\t\t\t})))));\n\t\t\t\t\treturn records;\n\t\t\t\t})();\n\t\t\t\tif (!join) return baseRecords;\n\t\t\t\tconst grouped = /* @__PURE__ */ new Map();\n\t\t\t\tconst seenIds = /* @__PURE__ */ new Map();\n\t\t\t\tfor (const baseRecord of baseRecords) {\n\t\t\t\t\tconst baseId = String(baseRecord.id);\n\t\t\t\t\tif (!grouped.has(baseId)) {\n\t\t\t\t\t\tconst nested = { ...baseRecord };\n\t\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\t\tif (joinAttr.relation === \"one-to-one\") nested[joinModelName] = null;\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tnested[joinModelName] = [];\n\t\t\t\t\t\t\t\tseenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgrouped.set(baseId, nested);\n\t\t\t\t\t}\n\t\t\t\t\tconst nestedEntry = grouped.get(baseId);\n\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\tconst joinTable = db[joinModelName];\n\t\t\t\t\t\tif (!joinTable) {\n\t\t\t\t\t\t\tlogger.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db));\n\t\t\t\t\t\t\tthrow new Error(`JoinOption model ${joinModelName} not found`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]);\n\t\t\t\t\t\tif (joinAttr.relation === \"one-to-one\") nestedEntry[joinModelName] = matchingRecords[0] || null;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst seenSet = seenIds.get(`${baseId}-${joinModel}`);\n\t\t\t\t\t\t\tconst limit = joinAttr.limit ?? 100;\n\t\t\t\t\t\t\tlet count = 0;\n\t\t\t\t\t\t\tfor (const matchingRecord of matchingRecords) {\n\t\t\t\t\t\t\t\tif (count >= limit) break;\n\t\t\t\t\t\t\t\tif (!seenSet.has(matchingRecord.id)) {\n\t\t\t\t\t\t\t\t\tnestedEntry[joinModelName].push(matchingRecord);\n\t\t\t\t\t\t\t\t\tseenSet.add(matchingRecord.id);\n\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn Array.from(grouped.values());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcreate: async ({ model, data }) => {\n\t\t\t\t\tif (options.advanced?.database?.generateId === \"serial\") data.id = db[getModelName(model)].length + 1;\n\t\t\t\t\tif (!db[model]) db[model] = [];\n\t\t\t\t\tdb[model].push(data);\n\t\t\t\t\treturn data;\n\t\t\t\t},\n\t\t\t\tfindOne: async ({ model, where, select, join }) => {\n\t\t\t\t\tconst res = convertWhereClause(where, model, join, select);\n\t\t\t\t\tif (join) {\n\t\t\t\t\t\tconst resArray = res;\n\t\t\t\t\t\tif (!resArray.length) return null;\n\t\t\t\t\t\treturn resArray[0];\n\t\t\t\t\t}\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t},\n\t\t\t\tfindMany: async ({ model, where, sortBy, limit, select, offset, join }) => {\n\t\t\t\t\tconst res = convertWhereClause(where || [], model, join, select);\n\t\t\t\t\tif (join) {\n\t\t\t\t\t\tconst resArray = res;\n\t\t\t\t\t\tif (!resArray.length) return [];\n\t\t\t\t\t\tapplySortToRecords(resArray, sortBy, model);\n\t\t\t\t\t\tlet paginatedRecords = resArray;\n\t\t\t\t\t\tif (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset);\n\t\t\t\t\t\tif (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit);\n\t\t\t\t\t\treturn paginatedRecords;\n\t\t\t\t\t}\n\t\t\t\t\tlet table = applySortToRecords(res, sortBy, model);\n\t\t\t\t\tif (offset !== void 0) table = table.slice(offset);\n\t\t\t\t\tif (limit !== void 0) table = table.slice(0, limit);\n\t\t\t\t\treturn table || [];\n\t\t\t\t},\n\t\t\t\tcount: async ({ model, where }) => {\n\t\t\t\t\tif (where) return convertWhereClause(where, model).length;\n\t\t\t\t\treturn db[model].length;\n\t\t\t\t},\n\t\t\t\tupdate: async ({ model, where, update }) => {\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tres.forEach((record) => {\n\t\t\t\t\t\tObject.assign(record, update);\n\t\t\t\t\t});\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t},\n\t\t\t\tdelete: async ({ model, where }) => {\n\t\t\t\t\tconst table = db[model];\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tdb[model] = table.filter((record) => !res.includes(record));\n\t\t\t\t},\n\t\t\t\tdeleteMany: async ({ model, where }) => {\n\t\t\t\t\tconst table = db[model];\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tlet count = 0;\n\t\t\t\t\tdb[model] = table.filter((record) => {\n\t\t\t\t\t\tif (res.includes(record)) {\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn !res.includes(record);\n\t\t\t\t\t});\n\t\t\t\t\treturn count;\n\t\t\t\t},\n\t\t\t\tupdateMany({ model, where, update }) {\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tres.forEach((record) => {\n\t\t\t\t\t\tObject.assign(record, update);\n\t\t\t\t\t});\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n\treturn (options) => {\n\t\tlazyOptions = options;\n\t\treturn adapterCreator(options);\n\t};\n};\n//#endregion\nexport { memoryAdapter };\n", "/// \nexport function isEmpty(obj) {\n if (Array.isArray(obj) || isString(obj) || isBuffer(obj)) {\n return obj.length === 0;\n }\n else if (obj) {\n return Object.keys(obj).length === 0;\n }\n return false;\n}\nexport function isUndefined(obj) {\n return typeof obj === 'undefined' || obj === undefined;\n}\nexport function isString(obj) {\n return typeof obj === 'string';\n}\nexport function isNumber(obj) {\n return typeof obj === 'number';\n}\nexport function isBoolean(obj) {\n return typeof obj === 'boolean';\n}\nexport function isNull(obj) {\n return obj === null;\n}\nexport function isDate(obj) {\n return obj instanceof Date;\n}\nexport function isBigInt(obj) {\n return typeof obj === 'bigint';\n}\n// Don't change the returnd type to `obj is Buffer` to not create a\n// hard dependency to node.\nexport function isBuffer(obj) {\n return typeof Buffer !== 'undefined' && Buffer.isBuffer(obj);\n}\nexport function isFunction(obj) {\n return typeof obj === 'function';\n}\nexport function isObject(obj) {\n return typeof obj === 'object' && obj !== null;\n}\nexport function isArrayBufferOrView(obj) {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\nexport function isPlainObject(obj) {\n if (!isObject(obj) || getTag(obj) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(obj) === null) {\n return true;\n }\n let proto = obj;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(obj) === proto;\n}\nexport function getLast(arr) {\n return arr[arr.length - 1];\n}\nexport function freeze(obj) {\n return Object.freeze(obj);\n}\nexport function asArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return [arg];\n }\n}\nexport function asReadonlyArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return freeze([arg]);\n }\n}\nexport function isReadonlyArray(arg) {\n return Array.isArray(arg);\n}\nexport function noop(obj) {\n return obj;\n}\nexport function compare(obj1, obj2) {\n if (isReadonlyArray(obj1) && isReadonlyArray(obj2)) {\n return compareArrays(obj1, obj2);\n }\n else if (isObject(obj1) && isObject(obj2)) {\n return compareObjects(obj1, obj2);\n }\n return obj1 === obj2;\n}\nfunction compareArrays(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n for (let i = 0; i < arr1.length; ++i) {\n if (!compare(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nfunction compareObjects(obj1, obj2) {\n if (isBuffer(obj1) && isBuffer(obj2)) {\n return compareBuffers(obj1, obj2);\n }\n else if (isDate(obj1) && isDate(obj2)) {\n return compareDates(obj1, obj2);\n }\n return compareGenericObjects(obj1, obj2);\n}\nfunction compareBuffers(buf1, buf2) {\n return Buffer.compare(buf1, buf2) === 0;\n}\nfunction compareDates(date1, date2) {\n return date1.getTime() === date2.getTime();\n}\nfunction compareGenericObjects(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) {\n return false;\n }\n for (const key of keys1) {\n if (!compare(obj1[key], obj2[key])) {\n return false;\n }\n }\n return true;\n}\nconst toString = Object.prototype.toString;\nfunction getTag(value) {\n if (value == null) {\n return value === undefined ? '[object Undefined]' : '[object Null]';\n }\n return toString.call(value);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AlterTableNode = freeze({\n is(node) {\n return node.kind === 'AlterTableNode';\n },\n create(table) {\n return freeze({\n kind: 'AlterTableNode',\n table,\n });\n },\n cloneWithTableProps(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n cloneWithColumnAlteration(node, columnAlteration) {\n return freeze({\n ...node,\n columnAlterations: node.columnAlterations\n ? [...node.columnAlterations, columnAlteration]\n : [columnAlteration],\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const IdentifierNode = freeze({\n is(node) {\n return node.kind === 'IdentifierNode';\n },\n create(name) {\n return freeze({\n kind: 'IdentifierNode',\n name,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CreateIndexNode = freeze({\n is(node) {\n return node.kind === 'CreateIndexNode';\n },\n create(name) {\n return freeze({\n kind: 'CreateIndexNode',\n name: IdentifierNode.create(name),\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n cloneWithColumns(node, columns) {\n return freeze({\n ...node,\n columns: [...(node.columns || []), ...columns],\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CreateSchemaNode = freeze({\n is(node) {\n return node.kind === 'CreateSchemaNode';\n },\n create(schema, params) {\n return freeze({\n kind: 'CreateSchemaNode',\n schema: IdentifierNode.create(schema),\n ...params,\n });\n },\n cloneWith(createSchema, params) {\n return freeze({\n ...createSchema,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nexport const ON_COMMIT_ACTIONS = ['preserve rows', 'delete rows', 'drop'];\n/**\n * @internal\n */\nexport const CreateTableNode = freeze({\n is(node) {\n return node.kind === 'CreateTableNode';\n },\n create(table) {\n return freeze({\n kind: 'CreateTableNode',\n table,\n columns: freeze([]),\n });\n },\n cloneWithColumn(createTable, column) {\n return freeze({\n ...createTable,\n columns: freeze([...createTable.columns, column]),\n });\n },\n cloneWithConstraint(createTable, constraint) {\n return freeze({\n ...createTable,\n constraints: createTable.constraints\n ? freeze([...createTable.constraints, constraint])\n : freeze([constraint]),\n });\n },\n cloneWithFrontModifier(createTable, modifier) {\n return freeze({\n ...createTable,\n frontModifiers: createTable.frontModifiers\n ? freeze([...createTable.frontModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWithEndModifier(createTable, modifier) {\n return freeze({\n ...createTable,\n endModifiers: createTable.endModifiers\n ? freeze([...createTable.endModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWith(createTable, params) {\n return freeze({\n ...createTable,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const SchemableIdentifierNode = freeze({\n is(node) {\n return node.kind === 'SchemableIdentifierNode';\n },\n create(identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n identifier: IdentifierNode.create(identifier),\n });\n },\n createWithSchema(schema, identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n schema: IdentifierNode.create(schema),\n identifier: IdentifierNode.create(identifier),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const DropIndexNode = freeze({\n is(node) {\n return node.kind === 'DropIndexNode';\n },\n create(name, params) {\n return freeze({\n kind: 'DropIndexNode',\n name: SchemableIdentifierNode.create(name),\n ...params,\n });\n },\n cloneWith(dropIndex, props) {\n return freeze({\n ...dropIndex,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const DropSchemaNode = freeze({\n is(node) {\n return node.kind === 'DropSchemaNode';\n },\n create(schema, params) {\n return freeze({\n kind: 'DropSchemaNode',\n schema: IdentifierNode.create(schema),\n ...params,\n });\n },\n cloneWith(dropSchema, params) {\n return freeze({\n ...dropSchema,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const DropTableNode = freeze({\n is(node) {\n return node.kind === 'DropTableNode';\n },\n create(table, params) {\n return freeze({\n kind: 'DropTableNode',\n table,\n ...params,\n });\n },\n cloneWith(dropIndex, params) {\n return freeze({\n ...dropIndex,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AliasNode = freeze({\n is(node) {\n return node.kind === 'AliasNode';\n },\n create(node, alias) {\n return freeze({\n kind: 'AliasNode',\n node,\n alias,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const TableNode = freeze({\n is(node) {\n return node.kind === 'TableNode';\n },\n create(table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.create(table),\n });\n },\n createWithSchema(schema, table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.createWithSchema(schema, table),\n });\n },\n});\n", "/// \nimport { isFunction, isObject } from '../util/object-utils.js';\nexport function isOperationNodeSource(obj) {\n return isObject(obj) && isFunction(obj.toOperationNode);\n}\n", "/// \nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport function isExpression(obj) {\n return isObject(obj) && 'expressionType' in obj && isOperationNodeSource(obj);\n}\nexport function isAliasedExpression(obj) {\n return (isObject(obj) &&\n 'expression' in obj &&\n isString(obj.alias) &&\n isOperationNodeSource(obj));\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectModifierNode = freeze({\n is(node) {\n return node.kind === 'SelectModifierNode';\n },\n create(modifier, of) {\n return freeze({\n kind: 'SelectModifierNode',\n modifier,\n of,\n });\n },\n createWithExpression(modifier) {\n return freeze({\n kind: 'SelectModifierNode',\n rawModifier: modifier,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AndNode = freeze({\n is(node) {\n return node.kind === 'AndNode';\n },\n create(left, right) {\n return freeze({\n kind: 'AndNode',\n left,\n right,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrNode = freeze({\n is(node) {\n return node.kind === 'OrNode';\n },\n create(left, right) {\n return freeze({\n kind: 'OrNode',\n left,\n right,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const OnNode = freeze({\n is(node) {\n return node.kind === 'OnNode';\n },\n create(filter) {\n return freeze({\n kind: 'OnNode',\n on: filter,\n });\n },\n cloneWithOperation(onNode, operator, operation) {\n return freeze({\n ...onNode,\n on: operator === 'And'\n ? AndNode.create(onNode.on, operation)\n : OrNode.create(onNode.on, operation),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { OnNode } from './on-node.js';\n/**\n * @internal\n */\nexport const JoinNode = freeze({\n is(node) {\n return node.kind === 'JoinNode';\n },\n create(joinType, table) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: undefined,\n });\n },\n createWithOn(joinType, table, on) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: OnNode.create(on),\n });\n },\n cloneWithOn(joinNode, operation) {\n return freeze({\n ...joinNode,\n on: joinNode.on\n ? OnNode.cloneWithOperation(joinNode.on, 'And', operation)\n : OnNode.create(operation),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const BinaryOperationNode = freeze({\n is(node) {\n return node.kind === 'BinaryOperationNode';\n },\n create(leftOperand, operator, rightOperand) {\n return freeze({\n kind: 'BinaryOperationNode',\n leftOperand,\n operator,\n rightOperand,\n });\n },\n});\n", "/// \nimport { freeze, isString } from '../util/object-utils.js';\nexport const COMPARISON_OPERATORS = [\n '=',\n '==',\n '!=',\n '<>',\n '>',\n '>=',\n '<',\n '<=',\n 'in',\n 'not in',\n 'is',\n 'is not',\n 'like',\n 'not like',\n 'match',\n 'ilike',\n 'not ilike',\n '@>',\n '<@',\n '^@',\n '&&',\n '?',\n '?&',\n '?|',\n '!<',\n '!>',\n '<=>',\n '!~',\n '~',\n '~*',\n '!~*',\n '@@',\n '@@@',\n '!!',\n '<->',\n 'regexp',\n 'is distinct from',\n 'is not distinct from',\n];\nexport const ARITHMETIC_OPERATORS = [\n '+',\n '-',\n '*',\n '/',\n '%',\n '^',\n '&',\n '|',\n '#',\n '<<',\n '>>',\n];\nexport const JSON_OPERATORS = ['->', '->>'];\nexport const BINARY_OPERATORS = [\n ...COMPARISON_OPERATORS,\n ...ARITHMETIC_OPERATORS,\n '&&',\n '||',\n];\nexport const UNARY_FILTER_OPERATORS = ['exists', 'not exists'];\nexport const UNARY_OPERATORS = ['not', '-', ...UNARY_FILTER_OPERATORS];\nexport const OPERATORS = [\n ...BINARY_OPERATORS,\n ...JSON_OPERATORS,\n ...UNARY_OPERATORS,\n 'between',\n 'between symmetric',\n];\n/**\n * @internal\n */\nexport const OperatorNode = freeze({\n is(node) {\n return node.kind === 'OperatorNode';\n },\n create(operator) {\n return freeze({\n kind: 'OperatorNode',\n operator,\n });\n },\n});\nexport function isOperator(op) {\n return isString(op) && OPERATORS.includes(op);\n}\nexport function isBinaryOperator(op) {\n return isString(op) && BINARY_OPERATORS.includes(op);\n}\nexport function isComparisonOperator(op) {\n return isString(op) && COMPARISON_OPERATORS.includes(op);\n}\nexport function isArithmeticOperator(op) {\n return isString(op) && ARITHMETIC_OPERATORS.includes(op);\n}\nexport function isJSONOperator(op) {\n return isString(op) && JSON_OPERATORS.includes(op);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const ColumnNode = freeze({\n is(node) {\n return node.kind === 'ColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'ColumnNode',\n column: IdentifierNode.create(column),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectAllNode = freeze({\n is(node) {\n return node.kind === 'SelectAllNode';\n },\n create() {\n return freeze({\n kind: 'SelectAllNode',\n });\n },\n});\n", "/// \nimport { SelectAllNode } from './select-all-node.js';\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReferenceNode = freeze({\n is(node) {\n return node.kind === 'ReferenceNode';\n },\n create(column, table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column,\n });\n },\n createSelectAll(table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column: SelectAllNode.create(),\n });\n },\n});\n", "/// \nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseSimpleReferenceExpression } from '../parser/reference-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicReferenceBuilder {\n #dynamicReference;\n get dynamicReference() {\n return this.#dynamicReference;\n }\n /**\n * @private\n *\n * This needs to be here just so that the typings work. Without this\n * the generated .d.ts file contains no reference to the type param R\n * which causes this type to be equal to DynamicReferenceBuilder with\n * any R.\n */\n get refType() {\n return undefined;\n }\n constructor(reference) {\n this.#dynamicReference = reference;\n }\n toOperationNode() {\n return parseSimpleReferenceExpression(this.#dynamicReference);\n }\n}\nexport function isDynamicReferenceBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.dynamicReference));\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByItemNode = freeze({\n is(node) {\n return node.kind === 'OrderByItemNode';\n },\n create(orderBy, direction) {\n return freeze({\n kind: 'OrderByItemNode',\n orderBy,\n direction,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const RawNode = freeze({\n is(node) {\n return node.kind === 'RawNode';\n },\n create(sqlFragments, parameters) {\n return freeze({\n kind: 'RawNode',\n sqlFragments: freeze(sqlFragments),\n parameters: freeze(parameters),\n });\n },\n createWithSql(sql) {\n return RawNode.create([sql], []);\n },\n createWithChild(child) {\n return RawNode.create(['', ''], [child]);\n },\n createWithChildren(children) {\n return RawNode.create(new Array(children.length + 1).fill(''), children);\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CollateNode = freeze({\n is(node) {\n return node.kind === 'CollateNode';\n },\n create(collation) {\n return freeze({\n kind: 'CollateNode',\n collation: IdentifierNode.create(collation),\n });\n },\n});\n", "/// \nimport { CollateNode } from '../operation-node/collate-node.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OrderByItemBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds `desc` to the `order by` item.\n *\n * See {@link asc} for the opposite.\n */\n desc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('desc'),\n }),\n });\n }\n /**\n * Adds `asc` to the `order by` item.\n *\n * See {@link desc} for the opposite.\n */\n asc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('asc'),\n }),\n });\n }\n /**\n * Adds `nulls last` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsFirst} for the opposite.\n */\n nullsLast() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'last' }),\n });\n }\n /**\n * Adds `nulls first` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsLast} for the opposite.\n */\n nullsFirst() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'first' }),\n });\n }\n /**\n * Adds `collate ` to the `order by` item.\n */\n collate(collation) {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n collation: CollateNode.create(collation),\n }),\n });\n }\n toOperationNode() {\n return this.#props.node;\n }\n}\n", "/// \nconst LOGGED_MESSAGES = new Set();\n/**\n * Use for system-level logging, such as deprecation messages.\n * Logs a message and ensures it won't be logged again.\n */\nexport function logOnce(message) {\n if (LOGGED_MESSAGES.has(message)) {\n return;\n }\n LOGGED_MESSAGES.add(message);\n console.log(message);\n}\n", "/// \nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { isExpression } from '../expression/expression.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { OrderByItemBuilder } from '../query-builder/order-by-item-builder.js';\nimport { logOnce } from '../util/log-once.js';\nimport { isExpressionOrFactory, parseExpression, } from './expression-parser.js';\nimport { parseStringReference, } from './reference-parser.js';\nexport function isOrderByDirection(thing) {\n return thing === 'asc' || thing === 'desc';\n}\nexport function parseOrderBy(args) {\n if (args.length === 2) {\n return [parseOrderByItem(args[0], args[1])];\n }\n if (args.length === 1) {\n const [orderBy] = args;\n if (Array.isArray(orderBy)) {\n logOnce('orderBy(array) is deprecated, use multiple orderBy calls instead.');\n return orderBy.map((item) => parseOrderByItem(item));\n }\n return [parseOrderByItem(orderBy)];\n }\n throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`);\n}\nexport function parseOrderByItem(expr, modifiers) {\n const parsedRef = parseOrderByExpression(expr);\n if (OrderByItemNode.is(parsedRef)) {\n if (modifiers) {\n throw new Error('Cannot specify direction twice!');\n }\n return parsedRef;\n }\n return parseOrderByWithModifiers(parsedRef, modifiers);\n}\nfunction parseOrderByExpression(expr) {\n if (isExpressionOrFactory(expr)) {\n return parseExpression(expr);\n }\n if (isDynamicReferenceBuilder(expr)) {\n return expr.toOperationNode();\n }\n const [ref, direction] = expr.split(' ');\n if (direction) {\n logOnce(\"`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead.\");\n return parseOrderByWithModifiers(parseStringReference(ref), direction);\n }\n return parseStringReference(expr);\n}\nfunction parseOrderByWithModifiers(expr, modifiers) {\n if (typeof modifiers === 'string') {\n if (!isOrderByDirection(modifiers)) {\n throw new Error(`Invalid order by direction: ${modifiers}`);\n }\n return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers));\n }\n if (isExpression(modifiers)) {\n logOnce(\"`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead.\");\n return OrderByItemNode.create(expr, modifiers.toOperationNode());\n }\n const node = OrderByItemNode.create(expr);\n if (!modifiers) {\n return node;\n }\n return modifiers(new OrderByItemBuilder({ node })).toOperationNode();\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONReferenceNode = freeze({\n is(node) {\n return node.kind === 'JSONReferenceNode';\n },\n create(reference, traversal) {\n return freeze({\n kind: 'JSONReferenceNode',\n reference,\n traversal,\n });\n },\n cloneWithTraversal(node, traversal) {\n return freeze({\n ...node,\n traversal,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONOperatorChainNode = freeze({\n is(node) {\n return node.kind === 'JSONOperatorChainNode';\n },\n create(operator) {\n return freeze({\n kind: 'JSONOperatorChainNode',\n operator,\n values: freeze([]),\n });\n },\n cloneWithValue(node, value) {\n return freeze({\n ...node,\n values: freeze([...node.values, value]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathNode = freeze({\n is(node) {\n return node.kind === 'JSONPathNode';\n },\n create(inOperator) {\n return freeze({\n kind: 'JSONPathNode',\n inOperator,\n pathLegs: freeze([]),\n });\n },\n cloneWithLeg(jsonPathNode, pathLeg) {\n return freeze({\n ...jsonPathNode,\n pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg]),\n });\n },\n});\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ReferenceNode } from '../operation-node/reference-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOrderByDirection, parseOrderBy, } from './order-by-parser.js';\nimport { OperatorNode, isJSONOperator, } from '../operation-node/operator-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nexport function parseSimpleReferenceExpression(exp) {\n if (isString(exp)) {\n return parseStringReference(exp);\n }\n return exp.toOperationNode();\n}\nexport function parseReferenceExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return arg.map((it) => parseReferenceExpression(it));\n }\n else {\n return [parseReferenceExpression(arg)];\n }\n}\nexport function parseReferenceExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return parseSimpleReferenceExpression(exp);\n}\nexport function parseJSONReference(ref, op) {\n const referenceNode = parseStringReference(ref);\n if (isJSONOperator(op)) {\n return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op)));\n }\n const opWithoutLastChar = op.slice(0, -1);\n if (isJSONOperator(opWithoutLastChar)) {\n return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar)));\n }\n throw new Error(`Invalid JSON operator: ${op}`);\n}\nexport function parseStringReference(ref) {\n const COLUMN_SEPARATOR = '.';\n if (!ref.includes(COLUMN_SEPARATOR)) {\n return ReferenceNode.create(ColumnNode.create(ref));\n }\n const parts = ref.split(COLUMN_SEPARATOR).map(trim);\n if (parts.length === 3) {\n return parseStringReferenceWithTableAndSchema(parts);\n }\n if (parts.length === 2) {\n return parseStringReferenceWithTable(parts);\n }\n throw new Error(`invalid column reference ${ref}`);\n}\nexport function parseAliasedStringReference(ref) {\n const ALIAS_SEPARATOR = ' as ';\n if (ref.includes(ALIAS_SEPARATOR)) {\n const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias));\n }\n else {\n return parseStringReference(ref);\n }\n}\nexport function parseColumnName(column) {\n return ColumnNode.create(column);\n}\nexport function parseOrderedColumnName(column) {\n const ORDER_SEPARATOR = ' ';\n if (column.includes(ORDER_SEPARATOR)) {\n const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim);\n if (!isOrderByDirection(order)) {\n throw new Error(`invalid order direction \"${order}\" next to \"${columnName}\"`);\n }\n return parseOrderBy([columnName, order])[0];\n }\n else {\n return parseColumnName(column);\n }\n}\nfunction parseStringReferenceWithTableAndSchema(parts) {\n const [schema, table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema, table));\n}\nfunction parseStringReferenceWithTable(parts) {\n const [table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table));\n}\nfunction trim(str) {\n return str.trim();\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PrimitiveValueListNode = freeze({\n is(node) {\n return node.kind === 'PrimitiveValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'PrimitiveValueListNode',\n values: freeze([...values]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueListNode = freeze({\n is(node) {\n return node.kind === 'ValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'ValueListNode',\n values: freeze(values),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueNode = freeze({\n is(node) {\n return node.kind === 'ValueNode';\n },\n create(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n });\n },\n createImmediate(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n immediate: true,\n });\n },\n});\n", "/// \nimport { PrimitiveValueListNode } from '../operation-node/primitive-value-list-node.js';\nimport { ValueListNode } from '../operation-node/value-list-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { isBoolean, isNull, isNumber, isReadonlyArray, } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nexport function parseValueExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return parseValueExpressionList(arg);\n }\n return parseValueExpression(arg);\n}\nexport function parseValueExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return ValueNode.create(exp);\n}\nexport function isSafeImmediateValue(value) {\n return isNumber(value) || isBoolean(value) || isNull(value);\n}\nexport function parseSafeImmediateValue(value) {\n if (!isSafeImmediateValue(value)) {\n throw new Error(`unsafe immediate value ${JSON.stringify(value)}`);\n }\n return ValueNode.createImmediate(value);\n}\nfunction parseValueExpressionList(arg) {\n if (arg.some(isExpressionOrFactory)) {\n return ValueListNode.create(arg.map((it) => parseValueExpression(it)));\n }\n return PrimitiveValueListNode.create(arg);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ParensNode = freeze({\n is(node) {\n return node.kind === 'ParensNode';\n },\n create(node) {\n return freeze({\n kind: 'ParensNode',\n node,\n });\n },\n});\n", "/// \nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { isBoolean, isNull, isString, isUndefined, } from '../util/object-utils.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { OperatorNode, OPERATORS, } from '../operation-node/operator-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nimport { parseValueExpression, parseValueExpressionOrList, } from './value-parser.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { OrNode } from '../operation-node/or-node.js';\nexport function parseValueBinaryOperationOrExpression(args) {\n if (args.length === 3) {\n return parseValueBinaryOperation(args[0], args[1], args[2]);\n }\n else if (args.length === 1) {\n return parseValueExpression(args[0]);\n }\n throw new Error(`invalid arguments: ${JSON.stringify(args)}`);\n}\nexport function parseValueBinaryOperation(left, operator, right) {\n if (isIsOperator(operator) && needsIsOperator(right)) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right));\n }\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right));\n}\nexport function parseReferentialBinaryOperation(left, operator, right) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right));\n}\nexport function parseFilterObject(obj, combinator) {\n return parseFilterList(Object.entries(obj)\n .filter(([, v]) => !isUndefined(v))\n .map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? 'is' : '=', v)), combinator);\n}\nexport function parseFilterList(list, combinator, withParens = true) {\n const combine = combinator === 'and' ? AndNode.create : OrNode.create;\n if (list.length === 0) {\n return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create('='), ValueNode.createImmediate(combinator === 'and' ? 1 : 0));\n }\n let node = toOperationNode(list[0]);\n for (let i = 1; i < list.length; ++i) {\n node = combine(node, toOperationNode(list[i]));\n }\n if (list.length > 1 && withParens) {\n return ParensNode.create(node);\n }\n return node;\n}\nfunction isIsOperator(operator) {\n return operator === 'is' || operator === 'is not';\n}\nfunction needsIsOperator(value) {\n return isNull(value) || isBoolean(value);\n}\nfunction parseOperator(operator) {\n if (isString(operator) && OPERATORS.includes(operator)) {\n return OperatorNode.create(operator);\n }\n if (isOperationNodeSource(operator)) {\n return operator.toOperationNode();\n }\n throw new Error(`invalid operator ${JSON.stringify(operator)}`);\n}\nfunction toOperationNode(nodeOrSource) {\n return isOperationNodeSource(nodeOrSource)\n ? nodeOrSource.toOperationNode()\n : nodeOrSource;\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByNode = freeze({\n is(node) {\n return node.kind === 'OrderByNode';\n },\n create(items) {\n return freeze({\n kind: 'OrderByNode',\n items: freeze([...items]),\n });\n },\n cloneWithItems(orderBy, items) {\n return freeze({\n ...orderBy,\n items: freeze([...orderBy.items, ...items]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByNode = freeze({\n is(node) {\n return node.kind === 'PartitionByNode';\n },\n create(items) {\n return freeze({\n kind: 'PartitionByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(partitionBy, items) {\n return freeze({\n ...partitionBy,\n items: freeze([...partitionBy.items, ...items]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { OrderByNode } from './order-by-node.js';\nimport { PartitionByNode } from './partition-by-node.js';\n/**\n * @internal\n */\nexport const OverNode = freeze({\n is(node) {\n return node.kind === 'OverNode';\n },\n create() {\n return freeze({\n kind: 'OverNode',\n });\n },\n cloneWithOrderByItems(overNode, items) {\n return freeze({\n ...overNode,\n orderBy: overNode.orderBy\n ? OrderByNode.cloneWithItems(overNode.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithPartitionByItems(overNode, items) {\n return freeze({\n ...overNode,\n partitionBy: overNode.partitionBy\n ? PartitionByNode.cloneWithItems(overNode.partitionBy, items)\n : PartitionByNode.create(items),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FromNode = freeze({\n is(node) {\n return node.kind === 'FromNode';\n },\n create(froms) {\n return freeze({\n kind: 'FromNode',\n froms: freeze(froms),\n });\n },\n cloneWithFroms(from, froms) {\n return freeze({\n ...from,\n froms: freeze([...from.froms, ...froms]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByNode = freeze({\n is(node) {\n return node.kind === 'GroupByNode';\n },\n create(items) {\n return freeze({\n kind: 'GroupByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(groupBy, items) {\n return freeze({\n ...groupBy,\n items: freeze([...groupBy.items, ...items]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const HavingNode = freeze({\n is(node) {\n return node.kind === 'HavingNode';\n },\n create(filter) {\n return freeze({\n kind: 'HavingNode',\n having: filter,\n });\n },\n cloneWithOperation(havingNode, operator, operation) {\n return freeze({\n ...havingNode,\n having: operator === 'And'\n ? AndNode.create(havingNode.having, operation)\n : OrNode.create(havingNode.having, operation),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const InsertQueryNode = freeze({\n is(node) {\n return node.kind === 'InsertQueryNode';\n },\n create(into, withNode, replace) {\n return freeze({\n kind: 'InsertQueryNode',\n into,\n ...(withNode && { with: withNode }),\n replace,\n });\n },\n createWithoutInto() {\n return freeze({\n kind: 'InsertQueryNode',\n });\n },\n cloneWith(insertQuery, props) {\n return freeze({\n ...insertQuery,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ListNode = freeze({\n is(node) {\n return node.kind === 'ListNode';\n },\n create(items) {\n return freeze({\n kind: 'ListNode',\n items: freeze(items),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { ListNode } from './list-node.js';\n/**\n * @internal\n */\nexport const UpdateQueryNode = freeze({\n is(node) {\n return node.kind === 'UpdateQueryNode';\n },\n create(tables, withNode) {\n return freeze({\n kind: 'UpdateQueryNode',\n // For backwards compatibility, use the raw table node when there's only one table\n // and don't rename the property to something like `tables`.\n table: tables.length === 1 ? tables[0] : ListNode.create(tables),\n ...(withNode && { with: withNode }),\n });\n },\n createWithoutTable() {\n return freeze({\n kind: 'UpdateQueryNode',\n });\n },\n cloneWithFromItems(updateQuery, fromItems) {\n return freeze({\n ...updateQuery,\n from: updateQuery.from\n ? FromNode.cloneWithFroms(updateQuery.from, fromItems)\n : FromNode.create(fromItems),\n });\n },\n cloneWithUpdates(updateQuery, updates) {\n return freeze({\n ...updateQuery,\n updates: updateQuery.updates\n ? freeze([...updateQuery.updates, ...updates])\n : updates,\n });\n },\n cloneWithLimit(updateQuery, limit) {\n return freeze({\n ...updateQuery,\n limit,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UsingNode = freeze({\n is(node) {\n return node.kind === 'UsingNode';\n },\n create(tables) {\n return freeze({\n kind: 'UsingNode',\n tables: freeze(tables),\n });\n },\n cloneWithTables(using, tables) {\n return freeze({\n ...using,\n tables: freeze([...using.tables, ...tables]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { UsingNode } from './using-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const DeleteQueryNode = freeze({\n is(node) {\n return node.kind === 'DeleteQueryNode';\n },\n create(fromItems, withNode) {\n return freeze({\n kind: 'DeleteQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithLimit(deleteNode, limit) {\n return freeze({\n ...deleteNode,\n limit,\n });\n },\n cloneWithoutLimit(deleteNode) {\n return freeze({\n ...deleteNode,\n limit: undefined,\n });\n },\n cloneWithUsing(deleteNode, tables) {\n return freeze({\n ...deleteNode,\n using: deleteNode.using !== undefined\n ? UsingNode.cloneWithTables(deleteNode.using, tables)\n : UsingNode.create(tables),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const WhereNode = freeze({\n is(node) {\n return node.kind === 'WhereNode';\n },\n create(filter) {\n return freeze({\n kind: 'WhereNode',\n where: filter,\n });\n },\n cloneWithOperation(whereNode, operator, operation) {\n return freeze({\n ...whereNode,\n where: operator === 'And'\n ? AndNode.create(whereNode.where, operation)\n : OrNode.create(whereNode.where, operation),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReturningNode = freeze({\n is(node) {\n return node.kind === 'ReturningNode';\n },\n create(selections) {\n return freeze({\n kind: 'ReturningNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(returning, selections) {\n return freeze({\n ...returning,\n selections: returning.selections\n ? freeze([...returning.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ExplainNode = freeze({\n is(node) {\n return node.kind === 'ExplainNode';\n },\n create(format, options) {\n return freeze({\n kind: 'ExplainNode',\n format,\n options,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const WhenNode = freeze({\n is(node) {\n return node.kind === 'WhenNode';\n },\n create(condition) {\n return freeze({\n kind: 'WhenNode',\n condition,\n });\n },\n cloneWithResult(whenNode, result) {\n return freeze({\n ...whenNode,\n result,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const MergeQueryNode = freeze({\n is(node) {\n return node.kind === 'MergeQueryNode';\n },\n create(into, withNode) {\n return freeze({\n kind: 'MergeQueryNode',\n into,\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithUsing(mergeNode, using) {\n return freeze({\n ...mergeNode,\n using,\n });\n },\n cloneWithWhen(mergeNode, when) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([...mergeNode.whens, when])\n : freeze([when]),\n });\n },\n cloneWithThen(mergeNode, then) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([\n ...mergeNode.whens.slice(0, -1),\n WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then),\n ])\n : undefined,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OutputNode = freeze({\n is(node) {\n return node.kind === 'OutputNode';\n },\n create(selections) {\n return freeze({\n kind: 'OutputNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(output, selections) {\n return freeze({\n ...output,\n selections: output.selections\n ? freeze([...output.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n", "/// \nimport { InsertQueryNode } from './insert-query-node.js';\nimport { SelectQueryNode } from './select-query-node.js';\nimport { UpdateQueryNode } from './update-query-node.js';\nimport { DeleteQueryNode } from './delete-query-node.js';\nimport { WhereNode } from './where-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { ReturningNode } from './returning-node.js';\nimport { ExplainNode } from './explain-node.js';\nimport { MergeQueryNode } from './merge-query-node.js';\nimport { OutputNode } from './output-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const QueryNode = freeze({\n is(node) {\n return (SelectQueryNode.is(node) ||\n InsertQueryNode.is(node) ||\n UpdateQueryNode.is(node) ||\n DeleteQueryNode.is(node) ||\n MergeQueryNode.is(node));\n },\n cloneWithEndModifier(node, modifier) {\n return freeze({\n ...node,\n endModifiers: node.endModifiers\n ? freeze([...node.endModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWithWhere(node, operation) {\n return freeze({\n ...node,\n where: node.where\n ? WhereNode.cloneWithOperation(node.where, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithJoin(node, join) {\n return freeze({\n ...node,\n joins: node.joins ? freeze([...node.joins, join]) : freeze([join]),\n });\n },\n cloneWithReturning(node, selections) {\n return freeze({\n ...node,\n returning: node.returning\n ? ReturningNode.cloneWithSelections(node.returning, selections)\n : ReturningNode.create(selections),\n });\n },\n cloneWithoutReturning(node) {\n return freeze({\n ...node,\n returning: undefined,\n });\n },\n cloneWithoutWhere(node) {\n return freeze({\n ...node,\n where: undefined,\n });\n },\n cloneWithExplain(node, format, options) {\n return freeze({\n ...node,\n explain: ExplainNode.create(format, options?.toOperationNode()),\n });\n },\n cloneWithTop(node, top) {\n return freeze({\n ...node,\n top,\n });\n },\n cloneWithOutput(node, selections) {\n return freeze({\n ...node,\n output: node.output\n ? OutputNode.cloneWithSelections(node.output, selections)\n : OutputNode.create(selections),\n });\n },\n cloneWithOrderByItems(node, items) {\n return freeze({\n ...node,\n orderBy: node.orderBy\n ? OrderByNode.cloneWithItems(node.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithoutOrderBy(node) {\n return freeze({\n ...node,\n orderBy: undefined,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { GroupByNode } from './group-by-node.js';\nimport { HavingNode } from './having-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const SelectQueryNode = freeze({\n is(node) {\n return node.kind === 'SelectQueryNode';\n },\n create(withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n ...(withNode && { with: withNode }),\n });\n },\n createFrom(fromItems, withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithSelections(select, selections) {\n return freeze({\n ...select,\n selections: select.selections\n ? freeze([...select.selections, ...selections])\n : freeze(selections),\n });\n },\n cloneWithDistinctOn(select, expressions) {\n return freeze({\n ...select,\n distinctOn: select.distinctOn\n ? freeze([...select.distinctOn, ...expressions])\n : freeze(expressions),\n });\n },\n cloneWithFrontModifier(select, modifier) {\n return freeze({\n ...select,\n frontModifiers: select.frontModifiers\n ? freeze([...select.frontModifiers, modifier])\n : freeze([modifier]),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n cloneWithGroupByItems(selectNode, items) {\n return freeze({\n ...selectNode,\n groupBy: selectNode.groupBy\n ? GroupByNode.cloneWithItems(selectNode.groupBy, items)\n : GroupByNode.create(items),\n });\n },\n cloneWithLimit(selectNode, limit) {\n return freeze({\n ...selectNode,\n limit,\n });\n },\n cloneWithOffset(selectNode, offset) {\n return freeze({\n ...selectNode,\n offset,\n });\n },\n cloneWithFetch(selectNode, fetch) {\n return freeze({\n ...selectNode,\n fetch,\n });\n },\n cloneWithHaving(selectNode, operation) {\n return freeze({\n ...selectNode,\n having: selectNode.having\n ? HavingNode.cloneWithOperation(selectNode.having, 'And', operation)\n : HavingNode.create(operation),\n });\n },\n cloneWithSetOperations(selectNode, setOperations) {\n return freeze({\n ...selectNode,\n setOperations: selectNode.setOperations\n ? freeze([...selectNode.setOperations, ...setOperations])\n : freeze([...setOperations]),\n });\n },\n cloneWithoutSelections(select) {\n return freeze({\n ...select,\n selections: [],\n });\n },\n cloneWithoutLimit(select) {\n return freeze({\n ...select,\n limit: undefined,\n });\n },\n cloneWithoutOffset(select) {\n return freeze({\n ...select,\n offset: undefined,\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithoutGroupBy(select) {\n return freeze({\n ...select,\n groupBy: undefined,\n });\n },\n});\n", "/// \nimport { JoinNode } from '../operation-node/join-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class JoinBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n on(...args) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Just like {@link WhereInterface.whereRef} but adds an item to the join's\n * `on` clause instead.\n *\n * See {@link WhereInterface.whereRef} for documentation and examples.\n */\n onRef(lhs, op, rhs) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds `on true`.\n */\n onTrue() {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql('true')),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.joinNode;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByItemNode = freeze({\n is(node) {\n return node.kind === 'PartitionByItemNode';\n },\n create(partitionBy) {\n return freeze({\n kind: 'PartitionByItemNode',\n partitionBy,\n });\n },\n});\n", "/// \nimport { PartitionByItemNode } from '../operation-node/partition-by-item-node.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parsePartitionBy(partitionBy) {\n return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create);\n}\n", "/// \nimport { OverNode } from '../operation-node/over-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { parsePartitionBy, } from '../parser/partition-by-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OverBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n orderBy(...args) {\n return new OverBuilder({\n overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new OverBuilder({\n overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode),\n });\n }\n partitionBy(partitionBy) {\n return new OverBuilder({\n overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy)),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.overNode;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ReferenceNode } from './reference-node.js';\nimport { SelectAllNode } from './select-all-node.js';\n/**\n * @internal\n */\nexport const SelectionNode = freeze({\n is(node) {\n return node.kind === 'SelectionNode';\n },\n create(selection) {\n return freeze({\n kind: 'SelectionNode',\n selection: selection,\n });\n },\n createSelectAll() {\n return freeze({\n kind: 'SelectionNode',\n selection: SelectAllNode.create(),\n });\n },\n createSelectAllFromTable(table) {\n return freeze({\n kind: 'SelectionNode',\n selection: ReferenceNode.createSelectAll(table),\n });\n },\n});\n", "/// \nimport { isFunction, isReadonlyArray, isString } from '../util/object-utils.js';\nimport { SelectionNode } from '../operation-node/selection-node.js';\nimport { parseAliasedStringReference } from './reference-parser.js';\nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { parseTable } from './table-parser.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nexport function parseSelectArg(selection) {\n if (isFunction(selection)) {\n return parseSelectArg(selection(expressionBuilder()));\n }\n else if (isReadonlyArray(selection)) {\n return selection.map((it) => parseSelectExpression(it));\n }\n else {\n return [parseSelectExpression(selection)];\n }\n}\nfunction parseSelectExpression(selection) {\n if (isString(selection)) {\n return SelectionNode.create(parseAliasedStringReference(selection));\n }\n else if (isDynamicReferenceBuilder(selection)) {\n return SelectionNode.create(selection.toOperationNode());\n }\n else {\n return SelectionNode.create(parseAliasedExpression(selection));\n }\n}\nexport function parseSelectAll(table) {\n if (!table) {\n return [SelectionNode.createSelectAll()];\n }\n else if (Array.isArray(table)) {\n return table.map(parseSelectAllArg);\n }\n else {\n return [parseSelectAllArg(table)];\n }\n}\nfunction parseSelectAllArg(table) {\n if (isString(table)) {\n return SelectionNode.createSelectAllFromTable(parseTable(table));\n }\n throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValuesNode = freeze({\n is(node) {\n return node.kind === 'ValuesNode';\n },\n create(values) {\n return freeze({\n kind: 'ValuesNode',\n values: freeze(values),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const DefaultInsertValueNode = freeze({\n is(node) {\n return node.kind === 'DefaultInsertValueNode';\n },\n create() {\n return freeze({\n kind: 'DefaultInsertValueNode',\n });\n },\n});\n", "/// \nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { PrimitiveValueListNode } from '../operation-node/primitive-value-list-node.js';\nimport { ValueListNode } from '../operation-node/value-list-node.js';\nimport { freeze, isFunction, isReadonlyArray, isUndefined, } from '../util/object-utils.js';\nimport { parseValueExpression } from './value-parser.js';\nimport { ValuesNode } from '../operation-node/values-node.js';\nimport { isExpressionOrFactory } from './expression-parser.js';\nimport { DefaultInsertValueNode } from '../operation-node/default-insert-value-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nexport function parseInsertExpression(arg) {\n const objectOrList = isFunction(arg) ? arg(expressionBuilder()) : arg;\n const list = isReadonlyArray(objectOrList)\n ? objectOrList\n : freeze([objectOrList]);\n return parseInsertColumnsAndValues(list);\n}\nfunction parseInsertColumnsAndValues(rows) {\n const columns = parseColumnNamesAndIndexes(rows);\n return [\n freeze([...columns.keys()].map(ColumnNode.create)),\n ValuesNode.create(rows.map((row) => parseRowValues(row, columns))),\n ];\n}\nfunction parseColumnNamesAndIndexes(rows) {\n const columns = new Map();\n for (const row of rows) {\n const cols = Object.keys(row);\n for (const col of cols) {\n if (!columns.has(col) && row[col] !== undefined) {\n columns.set(col, columns.size);\n }\n }\n }\n return columns;\n}\nfunction parseRowValues(row, columns) {\n const rowColumns = Object.keys(row);\n const rowValues = Array.from({\n length: columns.size,\n });\n let hasUndefinedOrComplexColumns = false;\n let indexedRowColumns = rowColumns.length;\n for (const col of rowColumns) {\n const columnIdx = columns.get(col);\n if (isUndefined(columnIdx)) {\n indexedRowColumns--;\n continue;\n }\n const value = row[col];\n if (isUndefined(value) || isExpressionOrFactory(value)) {\n hasUndefinedOrComplexColumns = true;\n }\n rowValues[columnIdx] = value;\n }\n const hasMissingColumns = indexedRowColumns < columns.size;\n if (hasMissingColumns || hasUndefinedOrComplexColumns) {\n const defaultValue = DefaultInsertValueNode.create();\n return ValueListNode.create(rowValues.map((it) => isUndefined(it) ? defaultValue : parseValueExpression(it)));\n }\n return PrimitiveValueListNode.create(rowValues);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ColumnUpdateNode = freeze({\n is(node) {\n return node.kind === 'ColumnUpdateNode';\n },\n create(column, value) {\n return freeze({\n kind: 'ColumnUpdateNode',\n column,\n value,\n });\n },\n});\n", "/// \nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ColumnUpdateNode } from '../operation-node/column-update-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { parseValueExpression } from './value-parser.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nexport function parseUpdate(...args) {\n if (args.length === 2) {\n return [\n ColumnUpdateNode.create(parseReferenceExpression(args[0]), parseValueExpression(args[1])),\n ];\n }\n return parseUpdateObjectExpression(args[0]);\n}\nexport function parseUpdateObjectExpression(update) {\n const updateObj = isFunction(update) ? update(expressionBuilder()) : update;\n return Object.entries(updateObj)\n .filter(([_, value]) => value !== undefined)\n .map(([key, value]) => {\n return ColumnUpdateNode.create(ColumnNode.create(key), parseValueExpression(value));\n });\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OnDuplicateKeyNode = freeze({\n is(node) {\n return node.kind === 'OnDuplicateKeyNode';\n },\n create(updates) {\n return freeze({\n kind: 'OnDuplicateKeyNode',\n updates,\n });\n },\n});\n", "/// \n/**\n * The result of an insert query.\n *\n * If the table has an auto incrementing primary key {@link insertId} will hold\n * the generated id on dialects that support it. For example PostgreSQL doesn't\n * return the id by default and {@link insertId} is undefined. On PostgreSQL you\n * need to use {@link ReturningInterface.returning} or {@link ReturningInterface.returningAll}\n * to get out the inserted id.\n *\n * {@link numInsertedOrUpdatedRows} holds the number of (actually) inserted rows.\n * On MySQL, updated rows are counted twice when using `on duplicate key update`.\n *\n * ### Examples\n *\n * ```ts\n * import type { NewPerson } from 'type-editor' // imaginary module\n *\n * async function insertPerson(person: NewPerson) {\n * const result = await db\n * .insertInto('person')\n * .values(person)\n * .executeTakeFirstOrThrow()\n *\n * console.log(result.insertId) // relevant on MySQL\n * console.log(result.numInsertedOrUpdatedRows) // always relevant\n * }\n * ```\n */\nexport class InsertResult {\n /**\n * The auto incrementing primary key of the inserted row.\n *\n * This property can be undefined when the query contains an `on conflict`\n * clause that makes the query succeed even when nothing gets inserted.\n *\n * This property is always undefined on dialects like PostgreSQL that\n * don't return the inserted id by default. On those dialects you need\n * to use the {@link ReturningInterface.returning | returning} method.\n */\n insertId;\n /**\n * Affected rows count.\n */\n numInsertedOrUpdatedRows;\n constructor(insertId, numInsertedOrUpdatedRows) {\n this.insertId = insertId;\n this.numInsertedOrUpdatedRows = numInsertedOrUpdatedRows;\n }\n}\n", "/// \nexport class NoResultError extends Error {\n /**\n * The operation node tree of the query that was executed.\n */\n node;\n constructor(node) {\n super('no result');\n this.node = node;\n }\n}\nexport function isNoResultErrorConstructor(fn) {\n return Object.prototype.hasOwnProperty.call(fn, 'prototype');\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { WhereNode } from './where-node.js';\n/**\n * @internal\n */\nexport const OnConflictNode = freeze({\n is(node) {\n return node.kind === 'OnConflictNode';\n },\n create() {\n return freeze({\n kind: 'OnConflictNode',\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n cloneWithIndexWhere(node, operation) {\n return freeze({\n ...node,\n indexWhere: node.indexWhere\n ? WhereNode.cloneWithOperation(node.indexWhere, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithIndexOrWhere(node, operation) {\n return freeze({\n ...node,\n indexWhere: node.indexWhere\n ? WhereNode.cloneWithOperation(node.indexWhere, 'Or', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithUpdateWhere(node, operation) {\n return freeze({\n ...node,\n updateWhere: node.updateWhere\n ? WhereNode.cloneWithOperation(node.updateWhere, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithUpdateOrWhere(node, operation) {\n return freeze({\n ...node,\n updateWhere: node.updateWhere\n ? WhereNode.cloneWithOperation(node.updateWhere, 'Or', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithoutIndexWhere(node) {\n return freeze({\n ...node,\n indexWhere: undefined,\n });\n },\n cloneWithoutUpdateWhere(node) {\n return freeze({\n ...node,\n updateWhere: undefined,\n });\n },\n});\n", "/// \nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { OnConflictNode } from '../operation-node/on-conflict-node.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { parseUpdateObjectExpression, } from '../parser/update-set-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OnConflictBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Specify a single column as the conflict target.\n *\n * Also see the {@link columns}, {@link constraint} and {@link expression}\n * methods for alternative ways to specify the conflict target.\n */\n column(column) {\n const columnNode = ColumnNode.create(column);\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n columns: this.#props.onConflictNode.columns\n ? freeze([...this.#props.onConflictNode.columns, columnNode])\n : freeze([columnNode]),\n }),\n });\n }\n /**\n * Specify a list of columns as the conflict target.\n *\n * Also see the {@link column}, {@link constraint} and {@link expression}\n * methods for alternative ways to specify the conflict target.\n */\n columns(columns) {\n const columnNodes = columns.map(ColumnNode.create);\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n columns: this.#props.onConflictNode.columns\n ? freeze([...this.#props.onConflictNode.columns, ...columnNodes])\n : freeze(columnNodes),\n }),\n });\n }\n /**\n * Specify a specific constraint by name as the conflict target.\n *\n * Also see the {@link column}, {@link columns} and {@link expression}\n * methods for alternative ways to specify the conflict target.\n */\n constraint(constraintName) {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n constraint: IdentifierNode.create(constraintName),\n }),\n });\n }\n /**\n * Specify an expression as the conflict target.\n *\n * This can be used if the unique index is an expression index.\n *\n * Also see the {@link column}, {@link columns} and {@link constraint}\n * methods for alternative ways to specify the conflict target.\n */\n expression(expression) {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n indexExpression: expression.toOperationNode(),\n }),\n });\n }\n where(...args) {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n clearWhere() {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithoutIndexWhere(this.#props.onConflictNode),\n });\n }\n /**\n * Adds the \"do nothing\" conflict action.\n *\n * ### Examples\n *\n * ```ts\n * const id = 1\n * const first_name = 'John'\n *\n * await db\n * .insertInto('person')\n * .values({\u00A0first_name, id })\n * .onConflict((oc) => oc\n * .column('id')\n * .doNothing()\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"id\")\n * values ($1, $2)\n * on conflict (\"id\") do nothing\n * ```\n */\n doNothing() {\n return new OnConflictDoNothingBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n doNothing: true,\n }),\n });\n }\n /**\n * Adds the \"do update set\" conflict action.\n *\n * ### Examples\n *\n * ```ts\n * const id = 1\n * const first_name = 'John'\n *\n * await db\n * .insertInto('person')\n * .values({\u00A0first_name, id })\n * .onConflict((oc) => oc\n * .column('id')\n * .doUpdateSet({ first_name })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"id\")\n * values ($1, $2)\n * on conflict (\"id\")\n * do update set \"first_name\" = $3\n * ```\n *\n * In the next example we use the `ref` method to reference\n * columns of the virtual table `excluded` in a type-safe way\n * to create an upsert operation:\n *\n * ```ts\n * import type { NewPerson } from 'type-editor' // imaginary module\n *\n * async function upsertPerson(person: NewPerson): Promise {\n * await db.insertInto('person')\n * .values(person)\n * .onConflict((oc) => oc\n * .column('id')\n * .doUpdateSet((eb) => ({\n * first_name: eb.ref('excluded.first_name'),\n * last_name: eb.ref('excluded.last_name')\n * })\n * )\n * )\n * .execute()\n * }\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\")\n * values ($1, $2)\n * on conflict (\"id\")\n * do update set\n * \"first_name\" = excluded.\"first_name\",\n * \"last_name\" = excluded.\"last_name\"\n * ```\n */\n doUpdateSet(update) {\n return new OnConflictUpdateBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n updates: parseUpdateObjectExpression(update),\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n}\nexport class OnConflictDoNothingBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n toOperationNode() {\n return this.#props.onConflictNode;\n }\n}\nexport class OnConflictUpdateBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n where(...args) {\n return new OnConflictUpdateBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Specify a where condition for the update operation.\n *\n * See {@link WhereInterface.whereRef} for more info.\n */\n whereRef(lhs, op, rhs) {\n return new OnConflictUpdateBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n clearWhere() {\n return new OnConflictUpdateBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithoutUpdateWhere(this.#props.onConflictNode),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.onConflictNode;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TopNode = freeze({\n is(node) {\n return node.kind === 'TopNode';\n },\n create(expression, modifiers) {\n return freeze({\n kind: 'TopNode',\n expression,\n modifiers,\n });\n },\n});\n", "/// \nimport { TopNode } from '../operation-node/top-node.js';\nimport { isBigInt, isNumber, isUndefined } from '../util/object-utils.js';\nexport function parseTop(expression, modifiers) {\n if (!isNumber(expression) && !isBigInt(expression)) {\n throw new Error(`Invalid top expression: ${expression}`);\n }\n if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) {\n throw new Error(`Invalid top modifiers: ${modifiers}`);\n }\n return TopNode.create(expression, modifiers);\n}\nfunction isTopModifiers(modifiers) {\n return (modifiers === 'percent' ||\n modifiers === 'with ties' ||\n modifiers === 'percent with ties');\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrActionNode = freeze({\n is(node) {\n return node.kind === 'OrActionNode';\n },\n create(action) {\n return freeze({\n kind: 'OrActionNode',\n action,\n });\n },\n});\n", "/// \nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { parseInsertExpression, } from '../parser/insert-values-parser.js';\nimport { InsertQueryNode } from '../operation-node/insert-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseUpdateObjectExpression, } from '../parser/update-set-parser.js';\nimport { freeze } from '../util/object-utils.js';\nimport { OnDuplicateKeyNode } from '../operation-node/on-duplicate-key-node.js';\nimport { InsertResult } from './insert-result.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { parseExpression, } from '../parser/expression-parser.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { OnConflictBuilder, } from './on-conflict-builder.js';\nimport { OnConflictNode } from '../operation-node/on-conflict-node.js';\nimport { parseTop } from '../parser/top-parser.js';\nimport { OrActionNode } from '../operation-node/or-action-node.js';\nexport class InsertQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Sets the values to insert for an {@link Kysely.insertInto | insert} query.\n *\n * This method takes an object whose keys are column names and values are\n * values to insert. In addition to the column's type, the values can be\n * raw {@link sql} snippets or select queries.\n *\n * You must provide all fields you haven't explicitly marked as nullable\n * or optional using {@link Generated} or {@link ColumnType}.\n *\n * The return value of an `insert` query is an instance of {@link InsertResult}. The\n * {@link InsertResult.insertId | insertId} field holds the auto incremented primary\n * key if the database returned one.\n *\n * On PostgreSQL and some other dialects, you need to call `returning` to get\n * something out of the query.\n *\n * Also see the {@link expression} method for inserting the result of a select\n * query or any other expression.\n *\n * ### Examples\n *\n * \n *\n * Insert a single row:\n *\n * ```ts\n * const result = await db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40\n * })\n * .executeTakeFirst()\n *\n * // `insertId` is only available on dialects that\n * // automatically return the id of the inserted row\n * // such as MySQL and SQLite. On PostgreSQL, for example,\n * // you need to add a `returning` clause to the query to\n * // get anything out. See the \"returning data\" example.\n * console.log(result.insertId)\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert into `person` (`first_name`, `last_name`, `age`) values (?, ?, ?)\n * ```\n *\n * \n *\n * On dialects that support it (for example PostgreSQL) you can insert multiple\n * rows by providing an array. Note that the return value is once again very\n * dialect-specific. Some databases may only return the id of the *last* inserted\n * row and some return nothing at all unless you call `returning`.\n *\n * ```ts\n * await db\n * .insertInto('person')\n * .values([{\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * }, {\n * first_name: 'Arnold',\n * last_name: 'Schwarzenegger',\n * age: 70,\n * }])\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\", \"age\") values (($1, $2, $3), ($4, $5, $6))\n * ```\n *\n * \n *\n * On supported dialects like PostgreSQL you need to chain `returning` to the query to get\n * the inserted row's columns (or any other expression) as the return value. `returning`\n * works just like `select`. Refer to `select` method's examples and documentation for\n * more info.\n *\n * ```ts\n * const result = await db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * })\n * .returning(['id', 'first_name as name'])\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\", \"age\") values ($1, $2, $3) returning \"id\", \"first_name\" as \"name\"\n * ```\n *\n * \n *\n * In addition to primitives, the values can also be arbitrary expressions.\n * You can build the expressions by using a callback and calling the methods\n * on the expression builder passed to it:\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * const ani = \"Ani\"\n * const ston = \"ston\"\n *\n * const result = await db\n * .insertInto('person')\n * .values(({ ref, selectFrom, fn }) => ({\n * first_name: 'Jennifer',\n * last_name: sql`concat(${ani}, ${ston})`,\n * middle_name: ref('first_name'),\n * age: selectFrom('person')\n * .select(fn.avg('age').as('avg_age')),\n * }))\n * .executeTakeFirst()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\n * \"first_name\",\n * \"last_name\",\n * \"middle_name\",\n * \"age\"\n * )\n * values (\n * $1,\n * concat($2, $3),\n * \"first_name\",\n * (select avg(\"age\") as \"avg_age\" from \"person\")\n * )\n * ```\n *\n * You can also use the callback version of subqueries or raw expressions:\n *\n * ```ts\n * await db.with('jennifer', (db) => db\n * .selectFrom('person')\n * .where('first_name', '=', 'Jennifer')\n * .select(['id', 'first_name', 'gender'])\n * .limit(1)\n * ).insertInto('pet').values((eb) => ({\n * owner_id: eb.selectFrom('jennifer').select('id'),\n * name: eb.selectFrom('jennifer').select('first_name'),\n * species: 'cat',\n * }))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * with \"jennifer\" as (\n * select \"id\", \"first_name\", \"gender\"\n * from \"person\"\n * where \"first_name\" = $1\n * limit $2\n * )\n * insert into \"pet\" (\"owner_id\", \"name\", \"species\")\n * values (\n * (select \"id\" from \"jennifer\"),\n * (select \"first_name\" from \"jennifer\"),\n * $3\n * )\n * ```\n */\n values(insert) {\n const [columns, values] = parseInsertExpression(insert);\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n columns,\n values,\n }),\n });\n }\n /**\n * Sets the columns to insert.\n *\n * The {@link values} method sets both the columns and the values and this method\n * is not needed. But if you are using the {@link expression} method, you can use\n * this method to set the columns to insert.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .columns(['first_name'])\n * .expression((eb) => eb.selectFrom('pet').select('pet.name'))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\")\n * select \"pet\".\"name\" from \"pet\"\n * ```\n */\n columns(columns) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n columns: freeze(columns.map(ColumnNode.create)),\n }),\n });\n }\n /**\n * Insert an arbitrary expression. For example the result of a select query.\n *\n * ### Examples\n *\n * \n *\n * You can create an `INSERT INTO SELECT FROM` query using the `expression` method.\n * This API doesn't follow our WYSIWYG principles and might be a bit difficult to\n * remember. The reasons for this design stem from implementation difficulties.\n *\n * ```ts\n * const result = await db.insertInto('person')\n * .columns(['first_name', 'last_name', 'age'])\n * .expression((eb) => eb\n * .selectFrom('pet')\n * .select((eb) => [\n * 'pet.name',\n * eb.val('Petson').as('last_name'),\n * eb.lit(7).as('age'),\n * ])\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\", \"age\")\n * select \"pet\".\"name\", $1 as \"last_name\", 7 as \"age from \"pet\"\n * ```\n */\n expression(expression) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n values: parseExpression(expression),\n }),\n });\n }\n /**\n * Creates an `insert into \"person\" default values` query.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .defaultValues()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" default values\n * ```\n */\n defaultValues() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n defaultValues: true,\n }),\n });\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.insertInto('person')\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * })\n * .modifyEnd(sql`-- This is a comment`)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert into `person` (\"first_name\", \"last_name\", \"gender\")\n * values (?, ?, ?) -- This is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * Changes an `insert into` query to an `insert ignore into` query.\n *\n * This is only supported by some dialects like MySQL.\n *\n * To avoid a footgun, when invoked with the SQLite dialect, this method will\n * be handled like {@link orIgnore}. See also, {@link orAbort}, {@link orFail},\n * {@link orReplace}, and {@link orRollback}.\n *\n * If you use the ignore modifier, ignorable errors that occur while executing the\n * insert statement are ignored. For example, without ignore, a row that duplicates\n * an existing unique index or primary key value in the table causes a duplicate-key\n * error and the statement is aborted. With ignore, the row is discarded and no error\n * occurs.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .ignore()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or ignore into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n ignore() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('ignore'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or ignore into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * To avoid a footgun, when invoked with the MySQL dialect, this method will\n * be handled like {@link ignore}.\n *\n * See also, {@link orAbort}, {@link orFail}, {@link orReplace}, and {@link orRollback}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orIgnore()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or ignore into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)\n * ```\n */\n orIgnore() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('ignore'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or abort into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * See also, {@link orIgnore}, {@link orFail}, {@link orReplace}, and {@link orRollback}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orAbort()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or abort into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n orAbort() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('abort'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or fail into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * See also, {@link orIgnore}, {@link orAbort}, {@link orReplace}, and {@link orRollback}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orFail()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or fail into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n orFail() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('fail'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or replace into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * You can also use {@link Kysely.replaceInto} to achieve the same result.\n *\n * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orRollback}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orReplace()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or replace into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n orReplace() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('replace'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or rollback into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orReplace}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orRollback()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or rollback into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n orRollback() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('rollback'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert top into` query.\n *\n * `top` clause is only supported by some dialects like MS SQL Server.\n *\n * ### Examples\n *\n * Insert the first 5 rows:\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.insertInto('person')\n * .top(5)\n * .columns(['first_name', 'gender'])\n * .expression(\n * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')])\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * insert top(5) into \"person\" (\"first_name\", \"gender\") select \"name\", 'other' as \"gender\" from \"pet\"\n * ```\n *\n * Insert the first 50 percent of rows:\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.insertInto('person')\n * .top(50, 'percent')\n * .columns(['first_name', 'gender'])\n * .expression(\n * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')])\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * insert top(50) percent into \"person\" (\"first_name\", \"gender\") select \"name\", 'other' as \"gender\" from \"pet\"\n * ```\n */\n top(expression, modifiers) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n /**\n * Adds an `on conflict` clause to the query.\n *\n * `on conflict` is only supported by some dialects like PostgreSQL and SQLite. On MySQL\n * you can use {@link ignore} and {@link onDuplicateKeyUpdate} to achieve similar results.\n *\n * ### Examples\n *\n * ```ts\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .column('name')\n * .doUpdateSet({ species: 'hamster' })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict (\"name\")\n * do update set \"species\" = $4\n * ```\n *\n * You can provide the name of the constraint instead of a column name:\n *\n * ```ts\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .constraint('pet_name_key')\n * .doUpdateSet({ species: 'hamster' })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict on constraint \"pet_name_key\"\n * do update set \"species\" = $4\n * ```\n *\n * You can also specify an expression as the conflict target in case\n * the unique index is an expression index:\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .expression(sql`lower(name)`)\n * .doUpdateSet({ species: 'hamster' })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict (lower(name))\n * do update set \"species\" = $4\n * ```\n *\n * You can add a filter for the update statement like this:\n *\n * ```ts\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .column('name')\n * .doUpdateSet({ species: 'hamster' })\n * .where('excluded.name', '!=', 'Catto')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict (\"name\")\n * do update set \"species\" = $4\n * where \"excluded\".\"name\" != $5\n * ```\n *\n * You can create an `on conflict do nothing` clauses like this:\n *\n * ```ts\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .column('name')\n * .doNothing()\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict (\"name\") do nothing\n * ```\n *\n * You can refer to the columns of the virtual `excluded` table\n * in a type-safe way using a callback and the `ref` method of\n * `ExpressionBuilder`:\n *\n * ```ts\n * await db.insertInto('person')\n * .values({\n * id: 1,\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * })\n * .onConflict(oc => oc\n * .column('id')\n * .doUpdateSet({\n * first_name: (eb) => eb.ref('excluded.first_name'),\n * last_name: (eb) => eb.ref('excluded.last_name')\n * })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"id\", \"first_name\", \"last_name\", \"gender\")\n * values ($1, $2, $3, $4)\n * on conflict (\"id\")\n * do update set\n * \"first_name\" = \"excluded\".\"first_name\",\n * \"last_name\" = \"excluded\".\"last_name\"\n * ```\n */\n onConflict(callback) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n onConflict: callback(new OnConflictBuilder({\n onConflictNode: OnConflictNode.create(),\n })).toOperationNode(),\n }),\n });\n }\n /**\n * Adds `on duplicate key update` to the query.\n *\n * If you specify `on duplicate key update`, and a row is inserted that would cause\n * a duplicate value in a unique index or primary key, an update of the old row occurs.\n *\n * This is only implemented by some dialects like MySQL. On most dialects you should\n * use {@link onConflict} instead.\n *\n * ### Examples\n *\n * ```ts\n * await db\n * .insertInto('person')\n * .values({\n * id: 1,\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * })\n * .onDuplicateKeyUpdate({ updated_at: new Date().toISOString() })\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert into `person` (`id`, `first_name`, `last_name`, `gender`)\n * values (?, ?, ?, ?)\n * on duplicate key update `updated_at` = ?\n * ```\n */\n onDuplicateKeyUpdate(update) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n onDuplicateKey: OnDuplicateKeyNode.create(parseUpdateObjectExpression(update)),\n }),\n });\n }\n returning(selection) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n returningAll() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll()),\n });\n }\n output(args) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n /**\n * Clears all `returning` clauses from the query.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .values({ first_name: 'James', last_name: 'Smith', gender: 'male' })\n * .returning(['first_name'])\n * .clearReturning()\n * .execute()\n * ```\n *\n * The generated SQL(PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\", \"gender\") values ($1, $2, $3)\n * ```\n */\n clearReturning() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n *\n * If you want to conditionally call a method on `this`, see\n * the {@link $if} method.\n *\n * ### Examples\n *\n * The next example uses a helper function `log` to log a query:\n *\n * ```ts\n * import type { Compilable } from 'kysely'\n *\n * function log(qb: T): T {\n * console.log(qb.compile())\n * return qb\n * }\n *\n * await db.insertInto('person')\n * .values({ first_name: 'John', last_name: 'Doe', gender: 'male' })\n * .$call(log)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n /**\n * Call `func(this)` if `condition` is true.\n *\n * This method is especially handy with optional selects. Any `returning` or `returningAll`\n * method calls add columns as optional fields to the output type when called inside\n * the `func` callback. This is because we can't know if those selections were actually\n * made before running the code.\n *\n * You can also call any other methods inside the callback.\n *\n * ### Examples\n *\n * ```ts\n * import type { NewPerson } from 'type-editor' // imaginary module\n *\n * async function insertPerson(values: NewPerson, returnLastName: boolean) {\n * return await db\n * .insertInto('person')\n * .values(values)\n * .returning(['id', 'first_name'])\n * .$if(returnLastName, (qb) => qb.returning('last_name'))\n * .executeTakeFirstOrThrow()\n * }\n * ```\n *\n * Any selections added inside the `if` callback will be added as optional fields to the\n * output type since we can't know if the selections were actually made before running\n * the code. In the example above the return type of the `insertPerson` function is:\n *\n * ```ts\n * Promise<{\n * id: number\n * first_name: string\n * last_name?: string\n * }>\n * ```\n */\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new InsertQueryBuilder({\n ...this.#props,\n });\n }\n /**\n * Change the output type of the query.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `InsertQueryBuilder` with a new output type.\n */\n $castTo() {\n return new InsertQueryBuilder(this.#props);\n }\n /**\n * Narrows (parts of) the output type of the query.\n *\n * Kysely tries to be as type-safe as possible, but in some cases we have to make\n * compromises for better maintainability and compilation performance. At present,\n * Kysely doesn't narrow the output type of the query based on {@link values} input\n * when using {@link returning} or {@link returningAll}.\n *\n * This utility method is very useful for these situations, as it removes unncessary\n * runtime assertion/guard code. Its input type is limited to the output type\n * of the query, so you can't add a column that doesn't exist, or change a column's\n * type to something that doesn't exist in its union type.\n *\n * ### Examples\n *\n * Turn this code:\n *\n * ```ts\n * import type { Person } from 'type-editor' // imaginary module\n *\n * const person = await db.insertInto('person')\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * nullable_column: 'hell yeah!'\n * })\n * .returningAll()\n * .executeTakeFirstOrThrow()\n *\n * if (isWithNoNullValue(person)) {\n * functionThatExpectsPersonWithNonNullValue(person)\n * }\n *\n * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {\n * return person.nullable_column != null\n * }\n * ```\n *\n * Into this:\n *\n * ```ts\n * import type { NotNull } from 'kysely'\n *\n * const person = await db.insertInto('person')\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * nullable_column: 'hell yeah!'\n * })\n * .returningAll()\n * .$narrowType<{ nullable_column: NotNull }>()\n * .executeTakeFirstOrThrow()\n *\n * functionThatExpectsPersonWithNonNullValue(person)\n * ```\n */\n $narrowType() {\n return new InsertQueryBuilder(this.#props);\n }\n /**\n * Asserts that query's output row type equals the given type `T`.\n *\n * This method can be used to simplify excessively complex types to make TypeScript happy\n * and much faster.\n *\n * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much\n * for TypeScript and you get errors like this:\n *\n * ```\n * error TS2589: Type instantiation is excessively deep and possibly infinite.\n * ```\n *\n * In these case you can often use this method to help TypeScript a little bit. When you use this\n * method to assert the output type of a query, Kysely can drop the complex output type that\n * consists of multiple nested helper types and replace it with the simple asserted type.\n *\n * Using this method doesn't reduce type safety at all. You have to pass in a type that is\n * structurally equal to the current type.\n *\n * ### Examples\n *\n * ```ts\n * import type { NewPerson, NewPet, Species } from 'type-editor' // imaginary module\n *\n * async function insertPersonAndPet(person: NewPerson, pet: Omit) {\n * return await db\n * .with('new_person', (qb) => qb\n * .insertInto('person')\n * .values(person)\n * .returning('id')\n * .$assertType<{ id: number }>()\n * )\n * .with('new_pet', (qb) => qb\n * .insertInto('pet')\n * .values((eb) => ({\n * owner_id: eb.selectFrom('new_person').select('id'),\n * ...pet\n * }))\n * .returning(['name as pet_name', 'species'])\n * .$assertType<{ pet_name: string, species: Species }>()\n * )\n * .selectFrom(['new_person', 'new_pet'])\n * .selectAll()\n * .executeTakeFirstOrThrow()\n * }\n * ```\n */\n $assertType() {\n return new InsertQueryBuilder(this.#props);\n }\n /**\n * Returns a copy of this InsertQueryBuilder instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new InsertQueryBuilder({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n /**\n * Executes the query and returns an array of rows.\n *\n * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.\n */\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n const { adapter } = this.#props.executor;\n const query = compiledQuery.query;\n if ((query.returning && adapter.supportsReturning) ||\n (query.output && adapter.supportsOutput)) {\n return result.rows;\n }\n return [\n new InsertResult(result.insertId, result.numAffectedRows ?? BigInt(0)),\n ];\n }\n /**\n * Executes the query and returns the first result or undefined if\n * the query returned no result.\n */\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n /**\n * Executes the query and returns the first result or throws if\n * the query returned no result.\n *\n * By default an instance of {@link NoResultError} is thrown, but you can\n * provide a custom error class, or callback as the only argument to throw a different\n * error.\n */\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n", "/// \nexport class DeleteResult {\n numDeletedRows;\n constructor(numDeletedRows) {\n this.numDeletedRows = numDeletedRows;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const LimitNode = freeze({\n is(node) {\n return node.kind === 'LimitNode';\n },\n create(limit) {\n return freeze({\n kind: 'LimitNode',\n limit,\n });\n },\n});\n", "/// \nvar _a;\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTableExpressionOrList, } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { DeleteResult } from './delete-result.js';\nimport { DeleteQueryNode } from '../operation-node/delete-query-node.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nexport class DeleteQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n /**\n * Changes a `delete from` query into a `delete top from` query.\n *\n * `top` clause is only supported by some dialects like MS SQL Server.\n *\n * ### Examples\n *\n * Delete the first 5 rows:\n *\n * ```ts\n * await db\n * .deleteFrom('person')\n * .top(5)\n * .where('age', '>', 18)\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * delete top(5) from \"person\" where \"age\" > @1\n * ```\n *\n * Delete the first 50% of rows:\n *\n * ```ts\n * await db\n * .deleteFrom('person')\n * .top(50, 'percent')\n * .where('age', '>', 18)\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * delete top(50) percent from \"person\" where \"age\" > @1\n * ```\n */\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n using(tables) {\n return new _a({\n ...this.#props,\n queryNode: DeleteQueryNode.cloneWithUsing(this.#props.queryNode, parseTableExpressionOrList(tables)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n returning(selection) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n returningAll(table) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n output(args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n /**\n * Clears all `returning` clauses from the query.\n *\n * ### Examples\n *\n * ```ts\n * await db.deleteFrom('pet')\n * .returningAll()\n * .where('name', '=', 'Max')\n * .clearReturning()\n * .execute()\n * ```\n *\n * The generated SQL(PostgreSQL):\n *\n * ```sql\n * delete from \"pet\" where \"name\" = \"Max\"\n * ```\n */\n clearReturning() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode),\n });\n }\n /**\n * Clears the `limit` clause from the query.\n *\n * ### Examples\n *\n * ```ts\n * await db.deleteFrom('pet')\n * .returningAll()\n * .where('name', '=', 'Max')\n * .limit(5)\n * .clearLimit()\n * .execute()\n * ```\n *\n * The generated SQL(PostgreSQL):\n *\n * ```sql\n * delete from \"pet\" where \"name\" = \"Max\" returning *\n * ```\n */\n clearLimit() {\n return new _a({\n ...this.#props,\n queryNode: DeleteQueryNode.cloneWithoutLimit(this.#props.queryNode),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n /**\n * Adds a limit clause to the query.\n *\n * A limit clause in a delete query is only supported by some dialects\n * like MySQL.\n *\n * ### Examples\n *\n * Delete 5 oldest items in a table:\n *\n * ```ts\n * await db\n * .deleteFrom('pet')\n * .orderBy('created_at')\n * .limit(5)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * delete from `pet` order by `created_at` limit ?\n * ```\n */\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: DeleteQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.deleteFrom('person')\n * .where('first_name', '=', 'John')\n * .modifyEnd(sql`-- This is a comment`)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * delete from `person`\n * where `first_name` = \"John\" -- This is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n *\n * If you want to conditionally call a method on `this`, see\n * the {@link $if} method.\n *\n * ### Examples\n *\n * The next example uses a helper function `log` to log a query:\n *\n * ```ts\n * import type { Compilable } from 'kysely'\n *\n * function log(qb: T): T {\n * console.log(qb.compile())\n * return qb\n * }\n *\n * await db.deleteFrom('person')\n * .$call(log)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n /**\n * Call `func(this)` if `condition` is true.\n *\n * This method is especially handy with optional selects. Any `returning` or `returningAll`\n * method calls add columns as optional fields to the output type when called inside\n * the `func` callback. This is because we can't know if those selections were actually\n * made before running the code.\n *\n * You can also call any other methods inside the callback.\n *\n * ### Examples\n *\n * ```ts\n * async function deletePerson(id: number, returnLastName: boolean) {\n * return await db\n * .deleteFrom('person')\n * .where('id', '=', id)\n * .returning(['id', 'first_name'])\n * .$if(returnLastName, (qb) => qb.returning('last_name'))\n * .executeTakeFirstOrThrow()\n * }\n * ```\n *\n * Any selections added inside the `if` callback will be added as optional fields to the\n * output type since we can't know if the selections were actually made before running\n * the code. In the example above the return type of the `deletePerson` function is:\n *\n * ```ts\n * Promise<{\n * id: number\n * first_name: string\n * last_name?: string\n * }>\n * ```\n */\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n /**\n * Change the output type of the query.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `DeleteQueryBuilder` with a new output type.\n */\n $castTo() {\n return new _a(this.#props);\n }\n /**\n * Narrows (parts of) the output type of the query.\n *\n * Kysely tries to be as type-safe as possible, but in some cases we have to make\n * compromises for better maintainability and compilation performance. At present,\n * Kysely doesn't narrow the output type of the query when using {@link where} and {@link returning} or {@link returningAll}.\n *\n * This utility method is very useful for these situations, as it removes unncessary\n * runtime assertion/guard code. Its input type is limited to the output type\n * of the query, so you can't add a column that doesn't exist, or change a column's\n * type to something that doesn't exist in its union type.\n *\n * ### Examples\n *\n * Turn this code:\n *\n * ```ts\n * import type { Person } from 'type-editor' // imaginary module\n *\n * const person = await db.deleteFrom('person')\n * .where('id', '=', 3)\n * .where('nullable_column', 'is not', null)\n * .returningAll()\n * .executeTakeFirstOrThrow()\n *\n * if (isWithNoNullValue(person)) {\n * functionThatExpectsPersonWithNonNullValue(person)\n * }\n *\n * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {\n * return person.nullable_column != null\n * }\n * ```\n *\n * Into this:\n *\n * ```ts\n * import type { NotNull } from 'kysely'\n *\n * const person = await db.deleteFrom('person')\n * .where('id', '=', 3)\n * .where('nullable_column', 'is not', null)\n * .returningAll()\n * .$narrowType<{ nullable_column: NotNull }>()\n * .executeTakeFirstOrThrow()\n *\n * functionThatExpectsPersonWithNonNullValue(person)\n * ```\n */\n $narrowType() {\n return new _a(this.#props);\n }\n /**\n * Asserts that query's output row type equals the given type `T`.\n *\n * This method can be used to simplify excessively complex types to make TypeScript happy\n * and much faster.\n *\n * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much\n * for TypeScript and you get errors like this:\n *\n * ```\n * error TS2589: Type instantiation is excessively deep and possibly infinite.\n * ```\n *\n * In these case you can often use this method to help TypeScript a little bit. When you use this\n * method to assert the output type of a query, Kysely can drop the complex output type that\n * consists of multiple nested helper types and replace it with the simple asserted type.\n *\n * Using this method doesn't reduce type safety at all. You have to pass in a type that is\n * structurally equal to the current type.\n *\n * ### Examples\n *\n * ```ts\n * import type { Species } from 'type-editor' // imaginary module\n *\n * async function deletePersonAndPets(personId: number) {\n * return await db\n * .with('deleted_person', (qb) => qb\n * .deleteFrom('person')\n * .where('id', '=', personId)\n * .returning('first_name')\n * .$assertType<{ first_name: string }>()\n * )\n * .with('deleted_pets', (qb) => qb\n * .deleteFrom('pet')\n * .where('owner_id', '=', personId)\n * .returning(['name as pet_name', 'species'])\n * .$assertType<{ pet_name: string, species: Species }>()\n * )\n * .selectFrom(['deleted_person', 'deleted_pets'])\n * .selectAll()\n * .execute()\n * }\n * ```\n */\n $assertType() {\n return new _a(this.#props);\n }\n /**\n * Returns a copy of this DeleteQueryBuilder instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n /**\n * Executes the query and returns an array of rows.\n *\n * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.\n */\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n const { adapter } = this.#props.executor;\n const query = compiledQuery.query;\n if ((query.returning && adapter.supportsReturning) ||\n (query.output && adapter.supportsOutput)) {\n return result.rows;\n }\n return [new DeleteResult(result.numAffectedRows ?? BigInt(0))];\n }\n /**\n * Executes the query and returns the first result or undefined if\n * the query returned no result.\n */\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n /**\n * Executes the query and returns the first result or throws if\n * the query returned no result.\n *\n * By default an instance of {@link NoResultError} is thrown, but you can\n * provide a custom error class, or callback as the only argument to throw a different\n * error.\n */\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = DeleteQueryBuilder;\n", "/// \nexport class UpdateResult {\n /**\n * The number of rows the update query updated (even if not changed).\n */\n numUpdatedRows;\n /**\n * The number of rows the update query changed.\n *\n * This is **optional** and only supported in dialects such as MySQL.\n * You would probably use {@link numUpdatedRows} in most cases.\n */\n numChangedRows;\n constructor(numUpdatedRows, numChangedRows) {\n this.numUpdatedRows = numUpdatedRows;\n this.numChangedRows = numChangedRows;\n }\n}\n", "/// \nvar _a;\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTableExpressionOrList, } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { UpdateQueryNode } from '../operation-node/update-query-node.js';\nimport { parseUpdate, } from '../parser/update-set-parser.js';\nimport { freeze } from '../util/object-utils.js';\nimport { UpdateResult } from './update-result.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { parseTop } from '../parser/top-parser.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nexport class UpdateQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n /**\n * Changes an `update` query into a `update top` query.\n *\n * `top` clause is only supported by some dialects like MS SQL Server.\n *\n * ### Examples\n *\n * Update the first row:\n *\n * ```ts\n * await db.updateTable('person')\n * .top(1)\n * .set({ first_name: 'Foo' })\n * .where('age', '>', 18)\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * update top(1) \"person\" set \"first_name\" = @1 where \"age\" > @2\n * ```\n *\n * Update the 50% first rows:\n *\n * ```ts\n * await db.updateTable('person')\n * .top(50, 'percent')\n * .set({ first_name: 'Foo' })\n * .where('age', '>', 18)\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * update top(50) percent \"person\" set \"first_name\" = @1 where \"age\" > @2\n * ```\n */\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n from(from) {\n return new _a({\n ...this.#props,\n queryNode: UpdateQueryNode.cloneWithFromItems(this.#props.queryNode, parseTableExpressionOrList(from)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n /**\n * Adds a limit clause to the update query for supported databases, such as MySQL.\n *\n * ### Examples\n *\n * Update the first 2 rows in the 'person' table:\n *\n * ```ts\n * await db\n * .updateTable('person')\n * .set({ first_name: 'Foo' })\n * .limit(2)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * update `person` set `first_name` = ? limit ?\n * ```\n */\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: UpdateQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n set(...args) {\n return new _a({\n ...this.#props,\n queryNode: UpdateQueryNode.cloneWithUpdates(this.#props.queryNode, parseUpdate(...args)),\n });\n }\n returning(selection) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n returningAll(table) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n output(args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.updateTable('person')\n * .set({ age: 39 })\n * .where('first_name', '=', 'John')\n * .modifyEnd(sql.raw('-- This is a comment'))\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * update `person`\n * set `age` = 39\n * where `first_name` = \"John\" -- This is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * Clears all `returning` clauses from the query.\n *\n * ### Examples\n *\n * ```ts\n * db.updateTable('person')\n * .returningAll()\n * .set({ age: 39 })\n * .where('first_name', '=', 'John')\n * .clearReturning()\n * ```\n *\n * The generated SQL(PostgreSQL):\n *\n * ```sql\n * update \"person\" set \"age\" = 39 where \"first_name\" = \"John\"\n * ```\n */\n clearReturning() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n *\n * If you want to conditionally call a method on `this`, see\n * the {@link $if} method.\n *\n * ### Examples\n *\n * The next example uses a helper function `log` to log a query:\n *\n * ```ts\n * import type { Compilable } from 'kysely'\n * import type { PersonUpdate } from 'type-editor' // imaginary module\n *\n * function log(qb: T): T {\n * console.log(qb.compile())\n * return qb\n * }\n *\n * const values = {\n * first_name: 'John',\n * } satisfies PersonUpdate\n *\n * db.updateTable('person')\n * .set(values)\n * .$call(log)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n /**\n * Call `func(this)` if `condition` is true.\n *\n * This method is especially handy with optional selects. Any `returning` or `returningAll`\n * method calls add columns as optional fields to the output type when called inside\n * the `func` callback. This is because we can't know if those selections were actually\n * made before running the code.\n *\n * You can also call any other methods inside the callback.\n *\n * ### Examples\n *\n * ```ts\n * import type { PersonUpdate } from 'type-editor' // imaginary module\n *\n * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {\n * return await db\n * .updateTable('person')\n * .set(updates)\n * .where('id', '=', id)\n * .returning(['id', 'first_name'])\n * .$if(returnLastName, (qb) => qb.returning('last_name'))\n * .executeTakeFirstOrThrow()\n * }\n * ```\n *\n * Any selections added inside the `if` callback will be added as optional fields to the\n * output type since we can't know if the selections were actually made before running\n * the code. In the example above the return type of the `updatePerson` function is:\n *\n * ```ts\n * Promise<{\n * id: number\n * first_name: string\n * last_name?: string\n * }>\n * ```\n */\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n /**\n * Change the output type of the query.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `UpdateQueryBuilder` with a new output type.\n */\n $castTo() {\n return new _a(this.#props);\n }\n /**\n * Narrows (parts of) the output type of the query.\n *\n * Kysely tries to be as type-safe as possible, but in some cases we have to make\n * compromises for better maintainability and compilation performance. At present,\n * Kysely doesn't narrow the output type of the query based on {@link set} input\n * when using {@link where} and/or {@link returning} or {@link returningAll}.\n *\n * This utility method is very useful for these situations, as it removes unncessary\n * runtime assertion/guard code. Its input type is limited to the output type\n * of the query, so you can't add a column that doesn't exist, or change a column's\n * type to something that doesn't exist in its union type.\n *\n * ### Examples\n *\n * Turn this code:\n *\n * ```ts\n * import type { Person } from 'type-editor' // imaginary module\n *\n * const id = 1\n * const now = new Date().toISOString()\n *\n * const person = await db.updateTable('person')\n * .set({ deleted_at: now })\n * .where('id', '=', id)\n * .where('nullable_column', 'is not', null)\n * .returningAll()\n * .executeTakeFirstOrThrow()\n *\n * if (isWithNoNullValue(person)) {\n * functionThatExpectsPersonWithNonNullValue(person)\n * }\n *\n * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {\n * return person.nullable_column != null\n * }\n * ```\n *\n * Into this:\n *\n * ```ts\n * import type { NotNull } from 'kysely'\n *\n * const id = 1\n * const now = new Date().toISOString()\n *\n * const person = await db.updateTable('person')\n * .set({ deleted_at: now })\n * .where('id', '=', id)\n * .where('nullable_column', 'is not', null)\n * .returningAll()\n * .$narrowType<{ deleted_at: Date; nullable_column: NotNull }>()\n * .executeTakeFirstOrThrow()\n *\n * functionThatExpectsPersonWithNonNullValue(person)\n * ```\n */\n $narrowType() {\n return new _a(this.#props);\n }\n /**\n * Asserts that query's output row type equals the given type `T`.\n *\n * This method can be used to simplify excessively complex types to make TypeScript happy\n * and much faster.\n *\n * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much\n * for TypeScript and you get errors like this:\n *\n * ```\n * error TS2589: Type instantiation is excessively deep and possibly infinite.\n * ```\n *\n * In these case you can often use this method to help TypeScript a little bit. When you use this\n * method to assert the output type of a query, Kysely can drop the complex output type that\n * consists of multiple nested helper types and replace it with the simple asserted type.\n *\n * Using this method doesn't reduce type safety at all. You have to pass in a type that is\n * structurally equal to the current type.\n *\n * ### Examples\n *\n * ```ts\n * import type { PersonUpdate, PetUpdate, Species } from 'type-editor' // imaginary module\n *\n * const person = {\n * id: 1,\n * gender: 'other',\n * } satisfies PersonUpdate\n *\n * const pet = {\n * name: 'Fluffy',\n * } satisfies PetUpdate\n *\n * const result = await db\n * .with('updated_person', (qb) => qb\n * .updateTable('person')\n * .set(person)\n * .where('id', '=', person.id)\n * .returning('first_name')\n * .$assertType<{ first_name: string }>()\n * )\n * .with('updated_pet', (qb) => qb\n * .updateTable('pet')\n * .set(pet)\n * .where('owner_id', '=', person.id)\n * .returning(['name as pet_name', 'species'])\n * .$assertType<{ pet_name: string, species: Species }>()\n * )\n * .selectFrom(['updated_person', 'updated_pet'])\n * .selectAll()\n * .executeTakeFirstOrThrow()\n * ```\n */\n $assertType() {\n return new _a(this.#props);\n }\n /**\n * Returns a copy of this UpdateQueryBuilder instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n /**\n * Executes the query and returns an array of rows.\n *\n * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.\n */\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n const { adapter } = this.#props.executor;\n const query = compiledQuery.query;\n if ((query.returning && adapter.supportsReturning) ||\n (query.output && adapter.supportsOutput)) {\n return result.rows;\n }\n return [\n new UpdateResult(result.numAffectedRows ?? BigInt(0), result.numChangedRows),\n ];\n }\n /**\n * Executes the query and returns the first result or undefined if\n * the query returned no result.\n */\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n /**\n * Executes the query and returns the first result or throws if\n * the query returned no result.\n *\n * By default an instance of {@link NoResultError} is thrown, but you can\n * provide a custom error class, or callback as the only argument to throw a different\n * error.\n */\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = UpdateQueryBuilder;\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\nimport { TableNode } from './table-node.js';\n/**\n * @internal\n */\nexport const CommonTableExpressionNameNode = freeze({\n is(node) {\n return node.kind === 'CommonTableExpressionNameNode';\n },\n create(tableName, columnNames) {\n return freeze({\n kind: 'CommonTableExpressionNameNode',\n table: TableNode.create(tableName),\n columns: columnNames\n ? freeze(columnNames.map(ColumnNode.create))\n : undefined,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const CommonTableExpressionNode = freeze({\n is(node) {\n return node.kind === 'CommonTableExpressionNode';\n },\n create(name, expression) {\n return freeze({\n kind: 'CommonTableExpressionNode',\n name,\n expression,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { CommonTableExpressionNode } from '../operation-node/common-table-expression-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class CTEBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Makes the common table expression materialized.\n */\n materialized() {\n return new CTEBuilder({\n ...this.#props,\n node: CommonTableExpressionNode.cloneWith(this.#props.node, {\n materialized: true,\n }),\n });\n }\n /**\n * Makes the common table expression not materialized.\n */\n notMaterialized() {\n return new CTEBuilder({\n ...this.#props,\n node: CommonTableExpressionNode.cloneWith(this.#props.node, {\n materialized: false,\n }),\n });\n }\n toOperationNode() {\n return this.#props.node;\n }\n}\n", "/// \nimport { CommonTableExpressionNameNode } from '../operation-node/common-table-expression-name-node.js';\nimport { createQueryCreator } from './parse-utils.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { CTEBuilder, } from '../query-builder/cte-builder.js';\nimport { CommonTableExpressionNode } from '../operation-node/common-table-expression-node.js';\nexport function parseCommonTableExpression(nameOrBuilderCallback, expression) {\n const expressionNode = expression(createQueryCreator()).toOperationNode();\n if (isFunction(nameOrBuilderCallback)) {\n return nameOrBuilderCallback(cteBuilderFactory(expressionNode)).toOperationNode();\n }\n return CommonTableExpressionNode.create(parseCommonTableExpressionName(nameOrBuilderCallback), expressionNode);\n}\nfunction cteBuilderFactory(expressionNode) {\n return (name) => {\n return new CTEBuilder({\n node: CommonTableExpressionNode.create(parseCommonTableExpressionName(name), expressionNode),\n });\n };\n}\nfunction parseCommonTableExpressionName(name) {\n if (name.includes('(')) {\n const parts = name.split(/[\\(\\)]/);\n const table = parts[0];\n const columns = parts[1].split(',').map((it) => it.trim());\n return CommonTableExpressionNameNode.create(table, columns);\n }\n else {\n return CommonTableExpressionNameNode.create(name);\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const WithNode = freeze({\n is(node) {\n return node.kind === 'WithNode';\n },\n create(expression, params) {\n return freeze({\n kind: 'WithNode',\n expressions: freeze([expression]),\n ...params,\n });\n },\n cloneWithExpression(withNode, expression) {\n return freeze({\n ...withNode,\n expressions: freeze([...withNode.expressions, expression]),\n });\n },\n});\n", "/// \nconst CHARS = [\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n 'a',\n 'b',\n 'c',\n 'd',\n 'e',\n 'f',\n 'g',\n 'h',\n 'i',\n 'j',\n 'k',\n 'l',\n 'm',\n 'n',\n 'o',\n 'p',\n 'q',\n 'r',\n 's',\n 't',\n 'u',\n 'v',\n 'w',\n 'x',\n 'y',\n 'z',\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n];\nexport function randomString(length) {\n let chars = '';\n for (let i = 0; i < length; ++i) {\n chars += randomChar();\n }\n return chars;\n}\nfunction randomChar() {\n return CHARS[~~(Math.random() * CHARS.length)];\n}\n", "/// \nimport { randomString } from './random-string.js';\nexport function createQueryId() {\n return new LazyQueryId();\n}\nclass LazyQueryId {\n #queryId;\n get queryId() {\n if (this.#queryId === undefined) {\n this.#queryId = randomString(8);\n }\n return this.#queryId;\n }\n}\n", "/// \n/**\n * Helper function to check listed properties according to given type. Check if all properties has been used when object is initialised.\n *\n * Example use:\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n *\n * // propB has to be mentioned even it is optional. It still should be initialized with undefined.\n * const a: SomeType = requireAllProps({ propA: \"value A\", propB: undefined });\n *\n * // checked type is implicit for variable.\n * const b = requireAllProps({ propA: \"value A\", propB: undefined });\n * ```\n *\n * Wrong use of this helper:\n *\n * 1. Omit checked type - all checked properties will be expect as of type never\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * // const z: SomeType = requireAllProps({ propC: \"no type will work\" }); // Property 'propA' is missing in type '{ propC: string; }' but required in type 'SomeType'.\n * ```\n *\n * 2. Apply to spreaded object - there is no way how to check in compile time if spreaded object contains all properties\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * const y: SomeType = { propA: \"\" }; // valid object according to SomeType declaration\n * // const x = requireAllProps({ ...y }); // Argument of type '{ propA: string; propB?: number; }' is not assignable to parameter of type 'AllProps'.\n * ```\n *\n * @param obj object to check if all properties has been used\n * @returns untouched obj parameter is returned\n */\nexport function requireAllProps(obj) {\n return obj;\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { requireAllProps } from '../util/require-all-props.js';\n/**\n * Transforms an operation node tree into another one.\n *\n * Kysely queries are expressed internally as a tree of objects (operation nodes).\n * `OperationNodeTransformer` takes such a tree as its input and returns a\n * transformed deep copy of it. By default the `OperationNodeTransformer`\n * does nothing. You need to override one or more methods to make it do\n * something.\n *\n * There's a method for each node type. For example if you'd like to convert\n * each identifier (table name, column name, alias etc.) from camelCase to\n * snake_case, you'd do something like this:\n *\n * ```ts\n * import { type IdentifierNode, OperationNodeTransformer } from 'kysely'\n * import snakeCase from 'lodash/snakeCase'\n *\n * class CamelCaseTransformer extends OperationNodeTransformer {\n * override transformIdentifier(node: IdentifierNode): IdentifierNode {\n * node = super.transformIdentifier(node)\n *\n * return {\n * ...node,\n * name: snakeCase(node.name),\n * }\n * }\n * }\n *\n * const transformer = new CamelCaseTransformer()\n *\n * const query = db.selectFrom('person').select(['first_name', 'last_name'])\n *\n * const tree = transformer.transformNode(query.toOperationNode())\n * ```\n */\nexport class OperationNodeTransformer {\n nodeStack = [];\n #transformers = freeze({\n AliasNode: this.transformAlias.bind(this),\n ColumnNode: this.transformColumn.bind(this),\n IdentifierNode: this.transformIdentifier.bind(this),\n SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this),\n RawNode: this.transformRaw.bind(this),\n ReferenceNode: this.transformReference.bind(this),\n SelectQueryNode: this.transformSelectQuery.bind(this),\n SelectionNode: this.transformSelection.bind(this),\n TableNode: this.transformTable.bind(this),\n FromNode: this.transformFrom.bind(this),\n SelectAllNode: this.transformSelectAll.bind(this),\n AndNode: this.transformAnd.bind(this),\n OrNode: this.transformOr.bind(this),\n ValueNode: this.transformValue.bind(this),\n ValueListNode: this.transformValueList.bind(this),\n PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this),\n ParensNode: this.transformParens.bind(this),\n JoinNode: this.transformJoin.bind(this),\n OperatorNode: this.transformOperator.bind(this),\n WhereNode: this.transformWhere.bind(this),\n InsertQueryNode: this.transformInsertQuery.bind(this),\n DeleteQueryNode: this.transformDeleteQuery.bind(this),\n ReturningNode: this.transformReturning.bind(this),\n CreateTableNode: this.transformCreateTable.bind(this),\n AddColumnNode: this.transformAddColumn.bind(this),\n ColumnDefinitionNode: this.transformColumnDefinition.bind(this),\n DropTableNode: this.transformDropTable.bind(this),\n DataTypeNode: this.transformDataType.bind(this),\n OrderByNode: this.transformOrderBy.bind(this),\n OrderByItemNode: this.transformOrderByItem.bind(this),\n GroupByNode: this.transformGroupBy.bind(this),\n GroupByItemNode: this.transformGroupByItem.bind(this),\n UpdateQueryNode: this.transformUpdateQuery.bind(this),\n ColumnUpdateNode: this.transformColumnUpdate.bind(this),\n LimitNode: this.transformLimit.bind(this),\n OffsetNode: this.transformOffset.bind(this),\n OnConflictNode: this.transformOnConflict.bind(this),\n OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this),\n CreateIndexNode: this.transformCreateIndex.bind(this),\n DropIndexNode: this.transformDropIndex.bind(this),\n ListNode: this.transformList.bind(this),\n PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this),\n UniqueConstraintNode: this.transformUniqueConstraint.bind(this),\n ReferencesNode: this.transformReferences.bind(this),\n CheckConstraintNode: this.transformCheckConstraint.bind(this),\n WithNode: this.transformWith.bind(this),\n CommonTableExpressionNode: this.transformCommonTableExpression.bind(this),\n CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this),\n HavingNode: this.transformHaving.bind(this),\n CreateSchemaNode: this.transformCreateSchema.bind(this),\n DropSchemaNode: this.transformDropSchema.bind(this),\n AlterTableNode: this.transformAlterTable.bind(this),\n DropColumnNode: this.transformDropColumn.bind(this),\n RenameColumnNode: this.transformRenameColumn.bind(this),\n AlterColumnNode: this.transformAlterColumn.bind(this),\n ModifyColumnNode: this.transformModifyColumn.bind(this),\n AddConstraintNode: this.transformAddConstraint.bind(this),\n DropConstraintNode: this.transformDropConstraint.bind(this),\n RenameConstraintNode: this.transformRenameConstraint.bind(this),\n ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this),\n CreateViewNode: this.transformCreateView.bind(this),\n RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this),\n DropViewNode: this.transformDropView.bind(this),\n GeneratedNode: this.transformGenerated.bind(this),\n DefaultValueNode: this.transformDefaultValue.bind(this),\n OnNode: this.transformOn.bind(this),\n ValuesNode: this.transformValues.bind(this),\n SelectModifierNode: this.transformSelectModifier.bind(this),\n CreateTypeNode: this.transformCreateType.bind(this),\n DropTypeNode: this.transformDropType.bind(this),\n ExplainNode: this.transformExplain.bind(this),\n DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this),\n AggregateFunctionNode: this.transformAggregateFunction.bind(this),\n OverNode: this.transformOver.bind(this),\n PartitionByNode: this.transformPartitionBy.bind(this),\n PartitionByItemNode: this.transformPartitionByItem.bind(this),\n SetOperationNode: this.transformSetOperation.bind(this),\n BinaryOperationNode: this.transformBinaryOperation.bind(this),\n UnaryOperationNode: this.transformUnaryOperation.bind(this),\n UsingNode: this.transformUsing.bind(this),\n FunctionNode: this.transformFunction.bind(this),\n CaseNode: this.transformCase.bind(this),\n WhenNode: this.transformWhen.bind(this),\n JSONReferenceNode: this.transformJSONReference.bind(this),\n JSONPathNode: this.transformJSONPath.bind(this),\n JSONPathLegNode: this.transformJSONPathLeg.bind(this),\n JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this),\n TupleNode: this.transformTuple.bind(this),\n MergeQueryNode: this.transformMergeQuery.bind(this),\n MatchedNode: this.transformMatched.bind(this),\n AddIndexNode: this.transformAddIndex.bind(this),\n CastNode: this.transformCast.bind(this),\n FetchNode: this.transformFetch.bind(this),\n TopNode: this.transformTop.bind(this),\n OutputNode: this.transformOutput.bind(this),\n OrActionNode: this.transformOrAction.bind(this),\n CollateNode: this.transformCollate.bind(this),\n });\n transformNode(node, queryId) {\n if (!node) {\n return node;\n }\n this.nodeStack.push(node);\n const out = this.transformNodeImpl(node, queryId);\n this.nodeStack.pop();\n return freeze(out);\n }\n transformNodeImpl(node, queryId) {\n return this.#transformers[node.kind](node, queryId);\n }\n transformNodeList(list, queryId) {\n if (!list) {\n return list;\n }\n return freeze(list.map((node) => this.transformNode(node, queryId)));\n }\n transformSelectQuery(node, queryId) {\n return requireAllProps({\n kind: 'SelectQueryNode',\n from: this.transformNode(node.from, queryId),\n selections: this.transformNodeList(node.selections, queryId),\n distinctOn: this.transformNodeList(node.distinctOn, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n groupBy: this.transformNode(node.groupBy, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n where: this.transformNode(node.where, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n limit: this.transformNode(node.limit, queryId),\n offset: this.transformNode(node.offset, queryId),\n with: this.transformNode(node.with, queryId),\n having: this.transformNode(node.having, queryId),\n explain: this.transformNode(node.explain, queryId),\n setOperations: this.transformNodeList(node.setOperations, queryId),\n fetch: this.transformNode(node.fetch, queryId),\n top: this.transformNode(node.top, queryId),\n });\n }\n transformSelection(node, queryId) {\n return requireAllProps({\n kind: 'SelectionNode',\n selection: this.transformNode(node.selection, queryId),\n });\n }\n transformColumn(node, queryId) {\n return requireAllProps({\n kind: 'ColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAlias(node, queryId) {\n return requireAllProps({\n kind: 'AliasNode',\n node: this.transformNode(node.node, queryId),\n alias: this.transformNode(node.alias, queryId),\n });\n }\n transformTable(node, queryId) {\n return requireAllProps({\n kind: 'TableNode',\n table: this.transformNode(node.table, queryId),\n });\n }\n transformFrom(node, queryId) {\n return requireAllProps({\n kind: 'FromNode',\n froms: this.transformNodeList(node.froms, queryId),\n });\n }\n transformReference(node, queryId) {\n return requireAllProps({\n kind: 'ReferenceNode',\n column: this.transformNode(node.column, queryId),\n table: this.transformNode(node.table, queryId),\n });\n }\n transformAnd(node, queryId) {\n return requireAllProps({\n kind: 'AndNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformOr(node, queryId) {\n return requireAllProps({\n kind: 'OrNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformValueList(node, queryId) {\n return requireAllProps({\n kind: 'ValueListNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformParens(node, queryId) {\n return requireAllProps({\n kind: 'ParensNode',\n node: this.transformNode(node.node, queryId),\n });\n }\n transformJoin(node, queryId) {\n return requireAllProps({\n kind: 'JoinNode',\n joinType: node.joinType,\n table: this.transformNode(node.table, queryId),\n on: this.transformNode(node.on, queryId),\n });\n }\n transformRaw(node, queryId) {\n return requireAllProps({\n kind: 'RawNode',\n sqlFragments: freeze([...node.sqlFragments]),\n parameters: this.transformNodeList(node.parameters, queryId),\n });\n }\n transformWhere(node, queryId) {\n return requireAllProps({\n kind: 'WhereNode',\n where: this.transformNode(node.where, queryId),\n });\n }\n transformInsertQuery(node, queryId) {\n return requireAllProps({\n kind: 'InsertQueryNode',\n into: this.transformNode(node.into, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n values: this.transformNode(node.values, queryId),\n returning: this.transformNode(node.returning, queryId),\n onConflict: this.transformNode(node.onConflict, queryId),\n onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n ignore: node.ignore,\n orAction: this.transformNode(node.orAction, queryId),\n replace: node.replace,\n explain: this.transformNode(node.explain, queryId),\n defaultValues: node.defaultValues,\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformValues(node, queryId) {\n return requireAllProps({\n kind: 'ValuesNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformDeleteQuery(node, queryId) {\n return requireAllProps({\n kind: 'DeleteQueryNode',\n from: this.transformNode(node.from, queryId),\n using: this.transformNode(node.using, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n limit: this.transformNode(node.limit, queryId),\n explain: this.transformNode(node.explain, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformReturning(node, queryId) {\n return requireAllProps({\n kind: 'ReturningNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformCreateTable(node, queryId) {\n return requireAllProps({\n kind: 'CreateTableNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n constraints: this.transformNodeList(node.constraints, queryId),\n temporary: node.temporary,\n ifNotExists: node.ifNotExists,\n onCommit: node.onCommit,\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n selectQuery: this.transformNode(node.selectQuery, queryId),\n });\n }\n transformColumnDefinition(node, queryId) {\n return requireAllProps({\n kind: 'ColumnDefinitionNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n references: this.transformNode(node.references, queryId),\n primaryKey: node.primaryKey,\n autoIncrement: node.autoIncrement,\n unique: node.unique,\n notNull: node.notNull,\n unsigned: node.unsigned,\n defaultTo: this.transformNode(node.defaultTo, queryId),\n check: this.transformNode(node.check, queryId),\n generated: this.transformNode(node.generated, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n identity: node.identity,\n ifNotExists: node.ifNotExists,\n });\n }\n transformAddColumn(node, queryId) {\n return requireAllProps({\n kind: 'AddColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformDropTable(node, queryId) {\n return requireAllProps({\n kind: 'DropTableNode',\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformOrderBy(node, queryId) {\n return requireAllProps({\n kind: 'OrderByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformOrderByItem(node, queryId) {\n return requireAllProps({\n kind: 'OrderByItemNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n direction: this.transformNode(node.direction, queryId),\n collation: this.transformNode(node.collation, queryId),\n nulls: node.nulls,\n });\n }\n transformGroupBy(node, queryId) {\n return requireAllProps({\n kind: 'GroupByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformGroupByItem(node, queryId) {\n return requireAllProps({\n kind: 'GroupByItemNode',\n groupBy: this.transformNode(node.groupBy, queryId),\n });\n }\n transformUpdateQuery(node, queryId) {\n return requireAllProps({\n kind: 'UpdateQueryNode',\n table: this.transformNode(node.table, queryId),\n from: this.transformNode(node.from, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n explain: this.transformNode(node.explain, queryId),\n limit: this.transformNode(node.limit, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n });\n }\n transformColumnUpdate(node, queryId) {\n return requireAllProps({\n kind: 'ColumnUpdateNode',\n column: this.transformNode(node.column, queryId),\n value: this.transformNode(node.value, queryId),\n });\n }\n transformLimit(node, queryId) {\n return requireAllProps({\n kind: 'LimitNode',\n limit: this.transformNode(node.limit, queryId),\n });\n }\n transformOffset(node, queryId) {\n return requireAllProps({\n kind: 'OffsetNode',\n offset: this.transformNode(node.offset, queryId),\n });\n }\n transformOnConflict(node, queryId) {\n return requireAllProps({\n kind: 'OnConflictNode',\n columns: this.transformNodeList(node.columns, queryId),\n constraint: this.transformNode(node.constraint, queryId),\n indexExpression: this.transformNode(node.indexExpression, queryId),\n indexWhere: this.transformNode(node.indexWhere, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n updateWhere: this.transformNode(node.updateWhere, queryId),\n doNothing: node.doNothing,\n });\n }\n transformOnDuplicateKey(node, queryId) {\n return requireAllProps({\n kind: 'OnDuplicateKeyNode',\n updates: this.transformNodeList(node.updates, queryId),\n });\n }\n transformCreateIndex(node, queryId) {\n return requireAllProps({\n kind: 'CreateIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n where: this.transformNode(node.where, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n });\n }\n transformList(node, queryId) {\n return requireAllProps({\n kind: 'ListNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformDropIndex(node, queryId) {\n return requireAllProps({\n kind: 'DropIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformPrimaryKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'PrimaryKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformUniqueConstraint(node, queryId) {\n return requireAllProps({\n kind: 'UniqueConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformForeignKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'ForeignKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n references: this.transformNode(node.references, queryId),\n name: this.transformNode(node.name, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformSetOperation(node, queryId) {\n return requireAllProps({\n kind: 'SetOperationNode',\n operator: node.operator,\n expression: this.transformNode(node.expression, queryId),\n all: node.all,\n });\n }\n transformReferences(node, queryId) {\n return requireAllProps({\n kind: 'ReferencesNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n });\n }\n transformCheckConstraint(node, queryId) {\n return requireAllProps({\n kind: 'CheckConstraintNode',\n expression: this.transformNode(node.expression, queryId),\n name: this.transformNode(node.name, queryId),\n });\n }\n transformWith(node, queryId) {\n return requireAllProps({\n kind: 'WithNode',\n expressions: this.transformNodeList(node.expressions, queryId),\n recursive: node.recursive,\n });\n }\n transformCommonTableExpression(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNode',\n name: this.transformNode(node.name, queryId),\n materialized: node.materialized,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformCommonTableExpressionName(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNameNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n });\n }\n transformHaving(node, queryId) {\n return requireAllProps({\n kind: 'HavingNode',\n having: this.transformNode(node.having, queryId),\n });\n }\n transformCreateSchema(node, queryId) {\n return requireAllProps({\n kind: 'CreateSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformDropSchema(node, queryId) {\n return requireAllProps({\n kind: 'DropSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformAlterTable(node, queryId) {\n return requireAllProps({\n kind: 'AlterTableNode',\n table: this.transformNode(node.table, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n setSchema: this.transformNode(node.setSchema, queryId),\n columnAlterations: this.transformNodeList(node.columnAlterations, queryId),\n addConstraint: this.transformNode(node.addConstraint, queryId),\n dropConstraint: this.transformNode(node.dropConstraint, queryId),\n renameConstraint: this.transformNode(node.renameConstraint, queryId),\n addIndex: this.transformNode(node.addIndex, queryId),\n dropIndex: this.transformNode(node.dropIndex, queryId),\n });\n }\n transformDropColumn(node, queryId) {\n return requireAllProps({\n kind: 'DropColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformRenameColumn(node, queryId) {\n return requireAllProps({\n kind: 'RenameColumnNode',\n column: this.transformNode(node.column, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n });\n }\n transformAlterColumn(node, queryId) {\n return requireAllProps({\n kind: 'AlterColumnNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId),\n setDefault: this.transformNode(node.setDefault, queryId),\n dropDefault: node.dropDefault,\n setNotNull: node.setNotNull,\n dropNotNull: node.dropNotNull,\n });\n }\n transformModifyColumn(node, queryId) {\n return requireAllProps({\n kind: 'ModifyColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAddConstraint(node, queryId) {\n return requireAllProps({\n kind: 'AddConstraintNode',\n constraint: this.transformNode(node.constraint, queryId),\n });\n }\n transformDropConstraint(node, queryId) {\n return requireAllProps({\n kind: 'DropConstraintNode',\n constraintName: this.transformNode(node.constraintName, queryId),\n ifExists: node.ifExists,\n modifier: node.modifier,\n });\n }\n transformRenameConstraint(node, queryId) {\n return requireAllProps({\n kind: 'RenameConstraintNode',\n oldName: this.transformNode(node.oldName, queryId),\n newName: this.transformNode(node.newName, queryId),\n });\n }\n transformCreateView(node, queryId) {\n return requireAllProps({\n kind: 'CreateViewNode',\n name: this.transformNode(node.name, queryId),\n temporary: node.temporary,\n orReplace: node.orReplace,\n ifNotExists: node.ifNotExists,\n materialized: node.materialized,\n columns: this.transformNodeList(node.columns, queryId),\n as: this.transformNode(node.as, queryId),\n });\n }\n transformRefreshMaterializedView(node, queryId) {\n return requireAllProps({\n kind: 'RefreshMaterializedViewNode',\n name: this.transformNode(node.name, queryId),\n concurrently: node.concurrently,\n withNoData: node.withNoData,\n });\n }\n transformDropView(node, queryId) {\n return requireAllProps({\n kind: 'DropViewNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n materialized: node.materialized,\n cascade: node.cascade,\n });\n }\n transformGenerated(node, queryId) {\n return requireAllProps({\n kind: 'GeneratedNode',\n byDefault: node.byDefault,\n always: node.always,\n identity: node.identity,\n stored: node.stored,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformDefaultValue(node, queryId) {\n return requireAllProps({\n kind: 'DefaultValueNode',\n defaultValue: this.transformNode(node.defaultValue, queryId),\n });\n }\n transformOn(node, queryId) {\n return requireAllProps({\n kind: 'OnNode',\n on: this.transformNode(node.on, queryId),\n });\n }\n transformSelectModifier(node, queryId) {\n return requireAllProps({\n kind: 'SelectModifierNode',\n modifier: node.modifier,\n rawModifier: this.transformNode(node.rawModifier, queryId),\n of: this.transformNodeList(node.of, queryId),\n });\n }\n transformCreateType(node, queryId) {\n return requireAllProps({\n kind: 'CreateTypeNode',\n name: this.transformNode(node.name, queryId),\n enum: this.transformNode(node.enum, queryId),\n });\n }\n transformDropType(node, queryId) {\n return requireAllProps({\n kind: 'DropTypeNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n });\n }\n transformExplain(node, queryId) {\n return requireAllProps({\n kind: 'ExplainNode',\n format: node.format,\n options: this.transformNode(node.options, queryId),\n });\n }\n transformSchemableIdentifier(node, queryId) {\n return requireAllProps({\n kind: 'SchemableIdentifierNode',\n schema: this.transformNode(node.schema, queryId),\n identifier: this.transformNode(node.identifier, queryId),\n });\n }\n transformAggregateFunction(node, queryId) {\n return requireAllProps({\n kind: 'AggregateFunctionNode',\n func: node.func,\n aggregated: this.transformNodeList(node.aggregated, queryId),\n distinct: node.distinct,\n orderBy: this.transformNode(node.orderBy, queryId),\n withinGroup: this.transformNode(node.withinGroup, queryId),\n filter: this.transformNode(node.filter, queryId),\n over: this.transformNode(node.over, queryId),\n });\n }\n transformOver(node, queryId) {\n return requireAllProps({\n kind: 'OverNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformPartitionBy(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformPartitionByItem(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByItemNode',\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformBinaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'BinaryOperationNode',\n leftOperand: this.transformNode(node.leftOperand, queryId),\n operator: this.transformNode(node.operator, queryId),\n rightOperand: this.transformNode(node.rightOperand, queryId),\n });\n }\n transformUnaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'UnaryOperationNode',\n operator: this.transformNode(node.operator, queryId),\n operand: this.transformNode(node.operand, queryId),\n });\n }\n transformUsing(node, queryId) {\n return requireAllProps({\n kind: 'UsingNode',\n tables: this.transformNodeList(node.tables, queryId),\n });\n }\n transformFunction(node, queryId) {\n return requireAllProps({\n kind: 'FunctionNode',\n func: node.func,\n arguments: this.transformNodeList(node.arguments, queryId),\n });\n }\n transformCase(node, queryId) {\n return requireAllProps({\n kind: 'CaseNode',\n value: this.transformNode(node.value, queryId),\n when: this.transformNodeList(node.when, queryId),\n else: this.transformNode(node.else, queryId),\n isStatement: node.isStatement,\n });\n }\n transformWhen(node, queryId) {\n return requireAllProps({\n kind: 'WhenNode',\n condition: this.transformNode(node.condition, queryId),\n result: this.transformNode(node.result, queryId),\n });\n }\n transformJSONReference(node, queryId) {\n return requireAllProps({\n kind: 'JSONReferenceNode',\n reference: this.transformNode(node.reference, queryId),\n traversal: this.transformNode(node.traversal, queryId),\n });\n }\n transformJSONPath(node, queryId) {\n return requireAllProps({\n kind: 'JSONPathNode',\n inOperator: this.transformNode(node.inOperator, queryId),\n pathLegs: this.transformNodeList(node.pathLegs, queryId),\n });\n }\n transformJSONPathLeg(node, _queryId) {\n return requireAllProps({\n kind: 'JSONPathLegNode',\n type: node.type,\n value: node.value,\n });\n }\n transformJSONOperatorChain(node, queryId) {\n return requireAllProps({\n kind: 'JSONOperatorChainNode',\n operator: this.transformNode(node.operator, queryId),\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformTuple(node, queryId) {\n return requireAllProps({\n kind: 'TupleNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformMergeQuery(node, queryId) {\n return requireAllProps({\n kind: 'MergeQueryNode',\n into: this.transformNode(node.into, queryId),\n using: this.transformNode(node.using, queryId),\n whens: this.transformNodeList(node.whens, queryId),\n with: this.transformNode(node.with, queryId),\n top: this.transformNode(node.top, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n output: this.transformNode(node.output, queryId),\n returning: this.transformNode(node.returning, queryId),\n });\n }\n transformMatched(node, _queryId) {\n return requireAllProps({\n kind: 'MatchedNode',\n not: node.not,\n bySource: node.bySource,\n });\n }\n transformAddIndex(node, queryId) {\n return requireAllProps({\n kind: 'AddIndexNode',\n name: this.transformNode(node.name, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformCast(node, queryId) {\n return requireAllProps({\n kind: 'CastNode',\n expression: this.transformNode(node.expression, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n });\n }\n transformFetch(node, queryId) {\n return requireAllProps({\n kind: 'FetchNode',\n rowCount: this.transformNode(node.rowCount, queryId),\n modifier: node.modifier,\n });\n }\n transformTop(node, _queryId) {\n return requireAllProps({\n kind: 'TopNode',\n expression: node.expression,\n modifiers: node.modifiers,\n });\n }\n transformOutput(node, queryId) {\n return requireAllProps({\n kind: 'OutputNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformDataType(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformSelectAll(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformIdentifier(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformPrimitiveValueList(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOperator(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformDefaultInsertValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOrAction(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformCollate(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n}\n", "/// \nimport { AliasNode } from '../../operation-node/alias-node.js';\nimport { IdentifierNode } from '../../operation-node/identifier-node.js';\nimport { JoinNode } from '../../operation-node/join-node.js';\nimport { ListNode } from '../../operation-node/list-node.js';\nimport { OperationNodeTransformer } from '../../operation-node/operation-node-transformer.js';\nimport { SchemableIdentifierNode } from '../../operation-node/schemable-identifier-node.js';\nimport { TableNode } from '../../operation-node/table-node.js';\nimport { UsingNode } from '../../operation-node/using-node.js';\nimport { freeze } from '../../util/object-utils.js';\n// This object exist only so that we get a type error when a new RootOperationNode\n// is added. If you get a type error here, make sure to add the new root node and\n// handle it correctly in the transformer.\n//\n// DO NOT REFACTOR THIS EVEN IF IT SEEMS USELESS TO YOU!\nconst ROOT_OPERATION_NODES = freeze({\n AlterTableNode: true,\n CreateIndexNode: true,\n CreateSchemaNode: true,\n CreateTableNode: true,\n CreateTypeNode: true,\n CreateViewNode: true,\n RefreshMaterializedViewNode: true,\n DeleteQueryNode: true,\n DropIndexNode: true,\n DropSchemaNode: true,\n DropTableNode: true,\n DropTypeNode: true,\n DropViewNode: true,\n InsertQueryNode: true,\n RawNode: true,\n SelectQueryNode: true,\n UpdateQueryNode: true,\n MergeQueryNode: true,\n});\nconst SCHEMALESS_FUNCTIONS = {\n json_agg: true,\n to_json: true,\n};\nexport class WithSchemaTransformer extends OperationNodeTransformer {\n #schema;\n #schemableIds = new Set();\n #ctes = new Set();\n constructor(schema) {\n super();\n this.#schema = schema;\n }\n transformNodeImpl(node, queryId) {\n if (!this.#isRootOperationNode(node)) {\n return super.transformNodeImpl(node, queryId);\n }\n const ctes = this.#collectCTEs(node);\n for (const cte of ctes) {\n this.#ctes.add(cte);\n }\n const tables = this.#collectSchemableIds(node);\n for (const table of tables) {\n this.#schemableIds.add(table);\n }\n const transformed = super.transformNodeImpl(node, queryId);\n for (const table of tables) {\n this.#schemableIds.delete(table);\n }\n for (const cte of ctes) {\n this.#ctes.delete(cte);\n }\n return transformed;\n }\n transformSchemableIdentifier(node, queryId) {\n const transformed = super.transformSchemableIdentifier(node, queryId);\n if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) {\n return transformed;\n }\n return {\n ...transformed,\n schema: IdentifierNode.create(this.#schema),\n };\n }\n transformReferences(node, queryId) {\n const transformed = super.transformReferences(node, queryId);\n if (transformed.table.table.schema) {\n return transformed;\n }\n return {\n ...transformed,\n table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name),\n };\n }\n transformAggregateFunction(node, queryId) {\n return {\n ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId),\n aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, 'aggregated'),\n };\n }\n transformFunction(node, queryId) {\n return {\n ...super.transformFunction({ ...node, arguments: [] }, queryId),\n arguments: this.#transformTableArgsWithoutSchemas(node, queryId, 'arguments'),\n };\n }\n transformSelectModifier(node, queryId) {\n return {\n ...super.transformSelectModifier({ ...node, of: undefined }, queryId),\n of: node.of?.map((item) => TableNode.is(item) && !item.table.schema\n ? {\n ...item,\n table: this.transformIdentifier(item.table.identifier, queryId),\n }\n : this.transformNode(item, queryId)),\n };\n }\n #transformTableArgsWithoutSchemas(node, queryId, argsKey) {\n return SCHEMALESS_FUNCTIONS[node.func]\n ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema\n ? this.transformNode(arg, queryId)\n : {\n ...arg,\n table: this.transformIdentifier(arg.table.identifier, queryId),\n })\n : this.transformNodeList(node[argsKey], queryId);\n }\n #isRootOperationNode(node) {\n return node.kind in ROOT_OPERATION_NODES;\n }\n #collectSchemableIds(node) {\n const schemableIds = new Set();\n if ('name' in node && node.name && SchemableIdentifierNode.is(node.name)) {\n this.#collectSchemableId(node.name, schemableIds);\n }\n if ('from' in node && node.from) {\n for (const from of node.from.froms) {\n this.#collectSchemableIdsFromTableExpr(from, schemableIds);\n }\n }\n if ('into' in node && node.into) {\n this.#collectSchemableIdsFromTableExpr(node.into, schemableIds);\n }\n if ('table' in node && node.table) {\n this.#collectSchemableIdsFromTableExpr(node.table, schemableIds);\n }\n if ('joins' in node && node.joins) {\n for (const join of node.joins) {\n this.#collectSchemableIdsFromTableExpr(join.table, schemableIds);\n }\n }\n if ('using' in node && node.using) {\n if (JoinNode.is(node.using)) {\n this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds);\n }\n else {\n this.#collectSchemableIdsFromTableExpr(node.using, schemableIds);\n }\n }\n return schemableIds;\n }\n #collectCTEs(node) {\n const ctes = new Set();\n if ('with' in node && node.with) {\n this.#collectCTEIds(node.with, ctes);\n }\n return ctes;\n }\n #collectSchemableIdsFromTableExpr(node, schemableIds) {\n if (TableNode.is(node)) {\n return this.#collectSchemableId(node.table, schemableIds);\n }\n if (AliasNode.is(node) && TableNode.is(node.node)) {\n return this.#collectSchemableId(node.node.table, schemableIds);\n }\n if (ListNode.is(node)) {\n for (const table of node.items) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n if (UsingNode.is(node)) {\n for (const table of node.tables) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n }\n #collectSchemableId(node, schemableIds) {\n const id = node.identifier.name;\n if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) {\n schemableIds.add(id);\n }\n }\n #collectCTEIds(node, ctes) {\n for (const expr of node.expressions) {\n const cteId = expr.name.table.table.identifier.name;\n if (!this.#ctes.has(cteId)) {\n ctes.add(cteId);\n }\n }\n }\n}\n", "/// \nimport { WithSchemaTransformer } from './with-schema-transformer.js';\nexport class WithSchemaPlugin {\n #transformer;\n constructor(schema) {\n this.#transformer = new WithSchemaTransformer(schema);\n }\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n return args.result;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const MatchedNode = freeze({\n is(node) {\n return node.kind === 'MatchedNode';\n },\n create(not, bySource = false) {\n return freeze({\n kind: 'MatchedNode',\n not,\n bySource,\n });\n },\n});\n", "/// \nimport { MatchedNode } from '../operation-node/matched-node.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { isString } from '../util/object-utils.js';\nimport { parseFilterList, parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from './binary-operation-parser.js';\nexport function parseMergeWhen(type, args, refRight) {\n return WhenNode.create(parseFilterList([\n MatchedNode.create(!type.isMatched, type.bySource),\n ...(args && args.length > 0\n ? [\n args.length === 3 && refRight\n ? parseReferentialBinaryOperation(args[0], args[1], args[2])\n : parseValueBinaryOperationOrExpression(args),\n ]\n : []),\n ], 'and', false));\n}\nexport function parseMergeThen(result) {\n if (isString(result)) {\n return RawNode.create([result], []);\n }\n if (isOperationNodeSource(result)) {\n return result.toOperationNode();\n }\n return result;\n}\n", "/// \nexport class Deferred {\n #promise;\n #resolve;\n #reject;\n constructor() {\n this.#promise = new Promise((resolve, reject) => {\n this.#reject = reject;\n this.#resolve = resolve;\n });\n }\n get promise() {\n return this.#promise;\n }\n resolve = (value) => {\n if (this.#resolve) {\n this.#resolve(value);\n }\n };\n reject = (reason) => {\n if (this.#reject) {\n this.#reject(reason);\n }\n };\n}\n", "/// \nimport { Deferred } from './deferred.js';\nimport { freeze } from './object-utils.js';\nexport async function provideControlledConnection(connectionProvider) {\n const connectionDefer = new Deferred();\n const connectionReleaseDefer = new Deferred();\n connectionProvider\n .provideConnection(async (connection) => {\n connectionDefer.resolve(connection);\n return await connectionReleaseDefer.promise;\n })\n .catch((ex) => connectionDefer.reject(ex));\n // Create composite of the connection and the release method instead of\n // modifying the connection or creating a new nesting `DatabaseConnection`.\n // This way we don't accidentally override any methods of 3rd party\n // connections and don't return wrapped connections to drivers that\n // expect a certain specific connection class.\n return freeze({\n connection: await connectionDefer.promise,\n release: connectionReleaseDefer.resolve,\n });\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { provideControlledConnection } from '../util/provide-controlled-connection.js';\nimport { logOnce } from '../util/log-once.js';\nconst NO_PLUGINS = freeze([]);\nexport class QueryExecutorBase {\n #plugins;\n constructor(plugins = NO_PLUGINS) {\n this.#plugins = plugins;\n }\n get plugins() {\n return this.#plugins;\n }\n transformQuery(node, queryId) {\n for (const plugin of this.#plugins) {\n const transformedNode = plugin.transformQuery({ node, queryId });\n // We need to do a runtime check here. There is no good way\n // to write types that enforce this constraint.\n if (transformedNode.kind === node.kind) {\n node = transformedNode;\n }\n else {\n throw new Error([\n `KyselyPlugin.transformQuery must return a node`,\n `of the same kind that was given to it.`,\n `The plugin was given a ${node.kind}`,\n `but it returned a ${transformedNode.kind}`,\n ].join(' '));\n }\n }\n return node;\n }\n async executeQuery(compiledQuery) {\n return await this.provideConnection(async (connection) => {\n const result = await connection.executeQuery(compiledQuery);\n if ('numUpdatedOrDeletedRows' in result) {\n logOnce('kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.');\n }\n return await this.#transformResult(result, compiledQuery.queryId);\n });\n }\n async *stream(compiledQuery, chunkSize) {\n const { connection, release } = await provideControlledConnection(this);\n try {\n for await (const result of connection.streamQuery(compiledQuery, chunkSize)) {\n yield await this.#transformResult(result, compiledQuery.queryId);\n }\n }\n finally {\n release();\n }\n }\n async #transformResult(result, queryId) {\n for (const plugin of this.#plugins) {\n result = await plugin.transformResult({ result, queryId });\n }\n return result;\n }\n}\n", "/// \nimport { QueryExecutorBase } from './query-executor-base.js';\n/**\n * A {@link QueryExecutor} subclass that can be used when you don't\n * have a {@link QueryCompiler}, {@link ConnectionProvider} or any\n * other needed things to actually execute queries.\n */\nexport class NoopQueryExecutor extends QueryExecutorBase {\n get adapter() {\n throw new Error('this query cannot be compiled to SQL');\n }\n compileQuery() {\n throw new Error('this query cannot be compiled to SQL');\n }\n provideConnection() {\n throw new Error('this query cannot be executed');\n }\n withConnectionProvider() {\n throw new Error('this query cannot have a connection provider');\n }\n withPlugin(plugin) {\n return new NoopQueryExecutor([...this.plugins, plugin]);\n }\n withPlugins(plugins) {\n return new NoopQueryExecutor([...this.plugins, ...plugins]);\n }\n withPluginAtFront(plugin) {\n return new NoopQueryExecutor([plugin, ...this.plugins]);\n }\n withoutPlugins() {\n return new NoopQueryExecutor([]);\n }\n}\nexport const NOOP_QUERY_EXECUTOR = new NoopQueryExecutor();\n", "/// \nexport class MergeResult {\n numChangedRows;\n constructor(numChangedRows) {\n this.numChangedRows = numChangedRows;\n }\n}\n", "/// \nimport { InsertQueryNode } from '../operation-node/insert-query-node.js';\nimport { MergeQueryNode } from '../operation-node/merge-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { UpdateQueryNode } from '../operation-node/update-query-node.js';\nimport { parseInsertExpression, } from '../parser/insert-values-parser.js';\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseMergeThen, parseMergeWhen } from '../parser/merge-parser.js';\nimport { parseSelectAll, parseSelectArg, } from '../parser/select-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { freeze } from '../util/object-utils.js';\nimport { MergeResult } from './merge-result.js';\nimport { NoResultError, isNoResultErrorConstructor, } from './no-result-error.js';\nimport { UpdateQueryBuilder } from './update-query-builder.js';\nexport class MergeQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db\n * .mergeInto('person')\n * .using('pet', 'pet.owner_id', 'person.id')\n * .whenMatched()\n * .thenDelete()\n * .modifyEnd(sql.raw('-- this is a comment'))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\" using \"pet\" on \"pet\".\"owner_id\" = \"person\".\"id\" when matched then delete -- this is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * Changes a `merge into` query to an `merge top into` query.\n *\n * `top` clause is only supported by some dialects like MS SQL Server.\n *\n * ### Examples\n *\n * Affect 5 matched rows at most:\n *\n * ```ts\n * await db.mergeInto('person')\n * .top(5)\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDelete()\n * .execute()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * merge top(5) into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * delete\n * ```\n *\n * Affect 50% of matched rows:\n *\n * ```ts\n * await db.mergeInto('person')\n * .top(50, 'percent')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDelete()\n * .execute()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * merge top(50) percent into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * delete\n * ```\n */\n top(expression, modifiers) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n using(...args) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithUsing(this.#props.queryNode, parseJoin('Using', args)),\n });\n }\n returning(args) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n returningAll(table) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n output(args) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n}\nexport class WheneableMergeQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db\n * .mergeInto('person')\n * .using('pet', 'pet.owner_id', 'person.id')\n * .whenMatched()\n * .thenDelete()\n * .modifyEnd(sql.raw('-- this is a comment'))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\" using \"pet\" on \"pet\".\"owner_id\" = \"person\".\"id\" when matched then delete -- this is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * See {@link MergeQueryBuilder.top}.\n */\n top(expression, modifiers) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n /**\n * Adds a simple `when matched` clause to the query.\n *\n * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}.\n *\n * For a simple `when not matched` clause, see {@link whenNotMatched}.\n *\n * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDelete()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * delete\n * ```\n */\n whenMatched() {\n return this.#whenMatched([]);\n }\n whenMatchedAnd(...args) {\n return this.#whenMatched(args);\n }\n /**\n * Adds the `when matched` clause to the query with an `and` condition. But unlike\n * {@link whenMatchedAnd}, this method accepts a column reference as the 3rd argument.\n *\n * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation\n * for that method for more examples.\n */\n whenMatchedAndRef(lhs, op, rhs) {\n return this.#whenMatched([lhs, op, rhs], true);\n }\n #whenMatched(args, refRight) {\n return new MatchedThenableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: true }, args, refRight)),\n });\n }\n /**\n * Adds a simple `when not matched` clause to the query.\n *\n * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}.\n *\n * For a simple `when matched` clause, see {@link whenMatched}.\n *\n * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenNotMatched()\n * .thenInsertValues({\n * first_name: 'John',\n * last_name: 'Doe',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when not matched then\n * insert (\"first_name\", \"last_name\") values ($1, $2)\n * ```\n */\n whenNotMatched() {\n return this.#whenNotMatched([]);\n }\n whenNotMatchedAnd(...args) {\n return this.#whenNotMatched(args);\n }\n /**\n * Adds the `when not matched` clause to the query with an `and` condition. But unlike\n * {@link whenNotMatchedAnd}, this method accepts a column reference as the 3rd argument.\n *\n * Unlike {@link whenMatchedAndRef}, you cannot reference columns from the target table.\n *\n * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation\n * for that method for more examples.\n */\n whenNotMatchedAndRef(lhs, op, rhs) {\n return this.#whenNotMatched([lhs, op, rhs], true);\n }\n /**\n * Adds a simple `when not matched by source` clause to the query.\n *\n * Supported in MS SQL Server.\n *\n * Similar to {@link whenNotMatched}, but returns a {@link MatchedThenableMergeQueryBuilder}.\n */\n whenNotMatchedBySource() {\n return this.#whenNotMatched([], false, true);\n }\n whenNotMatchedBySourceAnd(...args) {\n return this.#whenNotMatched(args, false, true);\n }\n /**\n * Adds the `when not matched by source` clause to the query with an `and` condition.\n *\n * Similar to {@link whenNotMatchedAndRef}, but you can reference columns from\n * the target table, and not from source table and returns a {@link MatchedThenableMergeQueryBuilder}.\n */\n whenNotMatchedBySourceAndRef(lhs, op, rhs) {\n return this.#whenNotMatched([lhs, op, rhs], true, true);\n }\n returning(args) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n returningAll(table) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n output(args) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n #whenNotMatched(args, refRight = false, bySource = false) {\n const props = {\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: false, bySource }, args, refRight)),\n };\n const Builder = bySource\n ? MatchedThenableMergeQueryBuilder\n : NotMatchedThenableMergeQueryBuilder;\n return new Builder(props);\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n *\n * If you want to conditionally call a method on `this`, see\n * the {@link $if} method.\n *\n * ### Examples\n *\n * The next example uses a helper function `log` to log a query:\n *\n * ```ts\n * import type { Compilable } from 'kysely'\n *\n * function log(qb: T): T {\n * console.log(qb.compile())\n * return qb\n * }\n *\n * await db.updateTable('person')\n * .set({ first_name: 'John' })\n * .$call(log)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n /**\n * Call `func(this)` if `condition` is true.\n *\n * This method is especially handy with optional selects. Any `returning` or `returningAll`\n * method calls add columns as optional fields to the output type when called inside\n * the `func` callback. This is because we can't know if those selections were actually\n * made before running the code.\n *\n * You can also call any other methods inside the callback.\n *\n * ### Examples\n *\n * ```ts\n * import type { PersonUpdate } from 'type-editor' // imaginary module\n *\n * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {\n * return await db\n * .updateTable('person')\n * .set(updates)\n * .where('id', '=', id)\n * .returning(['id', 'first_name'])\n * .$if(returnLastName, (qb) => qb.returning('last_name'))\n * .executeTakeFirstOrThrow()\n * }\n * ```\n *\n * Any selections added inside the `if` callback will be added as optional fields to the\n * output type since we can't know if the selections were actually made before running\n * the code. In the example above the return type of the `updatePerson` function is:\n *\n * ```ts\n * Promise<{\n * id: number\n * first_name: string\n * last_name?: string\n * }>\n * ```\n */\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n /**\n * Executes the query and returns an array of rows.\n *\n * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.\n */\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n const { adapter } = this.#props.executor;\n const query = compiledQuery.query;\n if ((query.returning && adapter.supportsReturning) ||\n (query.output && adapter.supportsOutput)) {\n return result.rows;\n }\n return [new MergeResult(result.numAffectedRows)];\n }\n /**\n * Executes the query and returns the first result or undefined if\n * the query returned no result.\n */\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n /**\n * Executes the query and returns the first result or throws if\n * the query returned no result.\n *\n * By default an instance of {@link NoResultError} is thrown, but you can\n * provide a custom error class, or callback as the only argument to throw a different\n * error.\n */\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n}\nexport class MatchedThenableMergeQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Performs the `delete` action.\n *\n * To perform the `do nothing` action, see {@link thenDoNothing}.\n *\n * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDelete()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * delete\n * ```\n */\n thenDelete() {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen('delete')),\n });\n }\n /**\n * Performs the `do nothing` action.\n *\n * This is supported in PostgreSQL.\n *\n * To perform the `delete` action, see {@link thenDelete}.\n *\n * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDoNothing()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * do nothing\n * ```\n */\n thenDoNothing() {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen('do nothing')),\n });\n }\n /**\n * Perform an `update` operation with a full-fledged {@link UpdateQueryBuilder}.\n * This is handy when multiple `set` invocations are needed.\n *\n * For a shorthand version of this method, see {@link thenUpdateSet}.\n *\n * To perform the `delete` action, see {@link thenDelete}.\n *\n * To perform the `do nothing` action, see {@link thenDoNothing}.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenUpdate((ub) => ub\n * .set(sql`metadata['has_pets']`, 'Y')\n * .set({\n * updated_at: new Date().toISOString(),\n * })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * update set metadata['has_pets'] = $1, \"updated_at\" = $2\n * ```\n */\n thenUpdate(set) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(set(new UpdateQueryBuilder({\n queryId: this.#props.queryId,\n executor: NOOP_QUERY_EXECUTOR,\n queryNode: UpdateQueryNode.createWithoutTable(),\n })))),\n });\n }\n thenUpdateSet(...args) {\n // @ts-ignore not sure how to type this so it won't complain about set(...args).\n return this.thenUpdate((ub) => ub.set(...args));\n }\n}\nexport class NotMatchedThenableMergeQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Performs the `do nothing` action.\n *\n * This is supported in PostgreSQL.\n *\n * To perform the `insert` action, see {@link thenInsertValues}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenNotMatched()\n * .thenDoNothing()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when not matched then\n * do nothing\n * ```\n */\n thenDoNothing() {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen('do nothing')),\n });\n }\n thenInsertValues(insert) {\n const [columns, values] = parseInsertExpression(insert);\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(), {\n columns,\n values,\n }))),\n });\n }\n}\n", "/// \nimport { createSelectQueryBuilder, } from './query-builder/select-query-builder.js';\nimport { InsertQueryBuilder } from './query-builder/insert-query-builder.js';\nimport { DeleteQueryBuilder } from './query-builder/delete-query-builder.js';\nimport { UpdateQueryBuilder } from './query-builder/update-query-builder.js';\nimport { DeleteQueryNode } from './operation-node/delete-query-node.js';\nimport { InsertQueryNode } from './operation-node/insert-query-node.js';\nimport { SelectQueryNode } from './operation-node/select-query-node.js';\nimport { UpdateQueryNode } from './operation-node/update-query-node.js';\nimport { parseTable, parseTableExpressionOrList, parseAliasedTable, } from './parser/table-parser.js';\nimport { parseCommonTableExpression, } from './parser/with-parser.js';\nimport { WithNode } from './operation-node/with-node.js';\nimport { createQueryId } from './util/query-id.js';\nimport { WithSchemaPlugin } from './plugin/with-schema/with-schema-plugin.js';\nimport { freeze } from './util/object-utils.js';\nimport { parseSelectArg, } from './parser/select-parser.js';\nimport { MergeQueryBuilder } from './query-builder/merge-query-builder.js';\nimport { MergeQueryNode } from './operation-node/merge-query-node.js';\nexport class QueryCreator {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Creates a `select` query builder for the given table or tables.\n *\n * The tables passed to this method are built as the query's `from` clause.\n *\n * ### Examples\n *\n * Create a select query for one table:\n *\n * ```ts\n * db.selectFrom('person').selectAll()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select * from \"person\"\n * ```\n *\n * Create a select query for one table with an alias:\n *\n * ```ts\n * const persons = await db.selectFrom('person as p')\n * .select(['p.id', 'first_name'])\n * .execute()\n *\n * console.log(persons[0].id)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"p\".\"id\", \"first_name\" from \"person\" as \"p\"\n * ```\n *\n * Create a select query from a subquery:\n *\n * ```ts\n * const persons = await db.selectFrom(\n * (eb) => eb.selectFrom('person').select('person.id as identifier').as('p')\n * )\n * .select('p.identifier')\n * .execute()\n *\n * console.log(persons[0].identifier)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"p\".\"identifier\",\n * from (\n * select \"person\".\"id\" as \"identifier\" from \"person\"\n * ) as p\n * ```\n *\n * Create a select query from raw sql:\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * const items = await db\n * .selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q'))\n * .select('q.one')\n * .execute()\n *\n * console.log(items[0].one)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"q\".\"one\",\n * from (\n * select 1 as one\n * ) as q\n * ```\n *\n * When you use the `sql` tag you need to also provide the result type of the\n * raw snippet / query so that Kysely can figure out what columns are\n * available for the rest of the query.\n *\n * The `selectFrom` method also accepts an array for multiple tables. All\n * the above examples can also be used in an array.\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * const items = await db.selectFrom([\n * 'person as p',\n * db.selectFrom('pet').select('pet.species').as('a'),\n * sql<{ one: number }>`(select 1 as one)`.as('q')\n * ])\n * .select(['p.id', 'a.species', 'q.one'])\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"p\".id, \"a\".\"species\", \"q\".\"one\"\n * from\n * \"person\" as \"p\",\n * (select \"pet\".\"species\" from \"pet\") as a,\n * (select 1 as one) as \"q\"\n * ```\n */\n selectFrom(from) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(from), this.#props.withNode),\n });\n }\n selectNoFrom(selection) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: SelectQueryNode.cloneWithSelections(SelectQueryNode.create(this.#props.withNode), parseSelectArg(selection)),\n });\n }\n /**\n * Creates an insert query.\n *\n * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}\n * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of\n * the inserted row if the db returned one.\n *\n * See the {@link InsertQueryBuilder.values | values} method for more info and examples. Also see\n * the {@link ReturningInterface.returning | returning} method for a way to return columns\n * on supported databases like PostgreSQL.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston'\n * })\n * .executeTakeFirst()\n *\n * console.log(result.insertId)\n * ```\n *\n * Some databases like PostgreSQL support the `returning` method:\n *\n * ```ts\n * const { id } = await db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston'\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n * ```\n */\n insertInto(table) {\n return new InsertQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode),\n });\n }\n /**\n * Creates a \"replace into\" query.\n *\n * This is only supported by some dialects like MySQL or SQLite.\n *\n * Similar to MySQL's {@link InsertQueryBuilder.onDuplicateKeyUpdate} that deletes\n * and inserts values on collision instead of updating existing rows.\n *\n * An alias of SQLite's {@link InsertQueryBuilder.orReplace}.\n *\n * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}\n * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of\n * the inserted row if the db returned one.\n *\n * See the {@link InsertQueryBuilder.values | values} method for more info and examples.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .replaceInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston'\n * })\n * .executeTakeFirstOrThrow()\n *\n * console.log(result.insertId)\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * replace into `person` (`first_name`, `last_name`) values (?, ?)\n * ```\n */\n replaceInto(table) {\n return new InsertQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode, true),\n });\n }\n /**\n * Creates a delete query.\n *\n * See the {@link DeleteQueryBuilder.where} method for examples on how to specify\n * a where clause for the delete operation.\n *\n * The return value of the query is an instance of {@link DeleteResult}.\n *\n * ### Examples\n *\n * \n *\n * Delete a single row:\n *\n * ```ts\n * const result = await db\n * .deleteFrom('person')\n * .where('person.id', '=', 1)\n * .executeTakeFirst()\n *\n * console.log(result.numDeletedRows)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * delete from \"person\" where \"person\".\"id\" = $1\n * ```\n *\n * Some databases such as MySQL support deleting from multiple tables:\n *\n * ```ts\n * const result = await db\n * .deleteFrom(['person', 'pet'])\n * .using('person')\n * .innerJoin('pet', 'pet.owner_id', 'person.id')\n * .where('person.id', '=', 1)\n * .executeTakeFirst()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * delete from `person`, `pet`\n * using `person`\n * inner join `pet` on `pet`.`owner_id` = `person`.`id`\n * where `person`.`id` = ?\n * ```\n */\n deleteFrom(from) {\n return new DeleteQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: DeleteQueryNode.create(parseTableExpressionOrList(from), this.#props.withNode),\n });\n }\n /**\n * Creates an update query.\n *\n * See the {@link UpdateQueryBuilder.where} method for examples on how to specify\n * a where clause for the update operation.\n *\n * See the {@link UpdateQueryBuilder.set} method for examples on how to\n * specify the updates.\n *\n * The return value of the query is an {@link UpdateResult}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .updateTable('person')\n * .set({ first_name: 'Jennifer' })\n * .where('person.id', '=', 1)\n * .executeTakeFirst()\n *\n * console.log(result.numUpdatedRows)\n * ```\n */\n updateTable(tables) {\n return new UpdateQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: UpdateQueryNode.create(parseTableExpressionOrList(tables), this.#props.withNode),\n });\n }\n /**\n * Creates a merge query.\n *\n * The return value of the query is a {@link MergeResult}.\n *\n * See the {@link MergeQueryBuilder.using} method for examples on how to specify\n * the other table.\n *\n * ### Examples\n *\n * \n *\n * Update a target column based on the existence of a source row:\n *\n * ```ts\n * const result = await db\n * .mergeInto('person as target')\n * .using('pet as source', 'source.owner_id', 'target.id')\n * .whenMatchedAnd('target.has_pets', '!=', 'Y')\n * .thenUpdateSet({ has_pets: 'Y' })\n * .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y')\n * .thenUpdateSet({ has_pets: 'N' })\n * .executeTakeFirstOrThrow()\n *\n * console.log(result.numChangedRows)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\"\n * on \"pet\".\"owner_id\" = \"person\".\"id\"\n * when matched and \"has_pets\" != $1\n * then update set \"has_pets\" = $2\n * when not matched by source and \"has_pets\" = $3\n * then update set \"has_pets\" = $4\n * ```\n *\n * \n *\n * Merge new entries from a temporary changes table:\n *\n * ```ts\n * const result = await db\n * .mergeInto('wine as target')\n * .using(\n * 'wine_stock_change as source',\n * 'source.wine_name',\n * 'target.name',\n * )\n * .whenNotMatchedAnd('source.stock_delta', '>', 0)\n * .thenInsertValues(({ ref }) => ({\n * name: ref('source.wine_name'),\n * stock: ref('source.stock_delta'),\n * }))\n * .whenMatchedAnd(\n * (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')),\n * '>',\n * 0,\n * )\n * .thenUpdateSet('stock', (eb) =>\n * eb('target.stock', '+', eb.ref('source.stock_delta')),\n * )\n * .whenMatched()\n * .thenDelete()\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"wine\" as \"target\"\n * using \"wine_stock_change\" as \"source\"\n * on \"source\".\"wine_name\" = \"target\".\"name\"\n * when not matched and \"source\".\"stock_delta\" > $1\n * then insert (\"name\", \"stock\") values (\"source\".\"wine_name\", \"source\".\"stock_delta\")\n * when matched and \"target\".\"stock\" + \"source\".\"stock_delta\" > $2\n * then update set \"stock\" = \"target\".\"stock\" + \"source\".\"stock_delta\"\n * when matched\n * then delete\n * ```\n */\n mergeInto(targetTable) {\n return new MergeQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: MergeQueryNode.create(parseAliasedTable(targetTable), this.#props.withNode),\n });\n }\n /**\n * Creates a `with` query (Common Table Expression).\n *\n * ### Examples\n *\n * \n *\n * Common table expressions (CTE) are a great way to modularize complex queries.\n * Essentially they allow you to run multiple separate queries within a\n * single roundtrip to the DB.\n *\n * Since CTEs are a part of the main query, query optimizers inside DB\n * engines are able to optimize the overall query. For example, postgres\n * is able to inline the CTEs inside the using queries if it decides it's\n * faster.\n *\n * ```ts\n * const result = await db\n * // Create a CTE called `jennifers` that selects all\n * // persons named 'Jennifer'.\n * .with('jennifers', (db) => db\n * .selectFrom('person')\n * .where('first_name', '=', 'Jennifer')\n * .select(['id', 'age'])\n * )\n * // Select all rows from the `jennifers` CTE and\n * // further filter it.\n * .with('adult_jennifers', (db) => db\n * .selectFrom('jennifers')\n * .where('age', '>', 18)\n * .select(['id', 'age'])\n * )\n * // Finally select all adult jennifers that are\n * // also younger than 60.\n * .selectFrom('adult_jennifers')\n * .where('age', '<', 60)\n * .selectAll()\n * .execute()\n * ```\n *\n * \n *\n * Some databases like postgres also allow you to run other queries than selects\n * in CTEs. On these databases CTEs are extremely powerful:\n *\n * ```ts\n * const result = await db\n * .with('new_person', (db) => db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * age: 35,\n * })\n * .returning('id')\n * )\n * .with('new_pet', (db) => db\n * .insertInto('pet')\n * .values({\n * name: 'Doggo',\n * species: 'dog',\n * is_favorite: true,\n * // Use the id of the person we just inserted.\n * owner_id: db\n * .selectFrom('new_person')\n * .select('id')\n * })\n * .returning('id')\n * )\n * .selectFrom(['new_person', 'new_pet'])\n * .select([\n * 'new_person.id as person_id',\n * 'new_pet.id as pet_id'\n * ])\n * .execute()\n * ```\n *\n * The CTE name can optionally specify column names in addition to\n * a name. In that case Kysely requires the expression to retun\n * rows with the same columns.\n *\n * ```ts\n * await db\n * .with('jennifers(id, age)', (db) => db\n * .selectFrom('person')\n * .where('first_name', '=', 'Jennifer')\n * // This is ok since we return columns with the same\n * // names as specified by `jennifers(id, age)`.\n * .select(['id', 'age'])\n * )\n * .selectFrom('jennifers')\n * .selectAll()\n * .execute()\n * ```\n *\n * The first argument can also be a callback. The callback is passed\n * a `CTEBuilder` instance that can be used to configure the CTE:\n *\n * ```ts\n * await db\n * .with(\n * (cte) => cte('jennifers').materialized(),\n * (db) => db\n * .selectFrom('person')\n * .where('first_name', '=', 'Jennifer')\n * .select(['id', 'age'])\n * )\n * .selectFrom('jennifers')\n * .selectAll()\n * .execute()\n * ```\n */\n with(nameOrBuilder, expression) {\n const cte = parseCommonTableExpression(nameOrBuilder, expression);\n return new QueryCreator({\n ...this.#props,\n withNode: this.#props.withNode\n ? WithNode.cloneWithExpression(this.#props.withNode, cte)\n : WithNode.create(cte),\n });\n }\n /**\n * Creates a recursive `with` query (Common Table Expression).\n *\n * Note that recursiveness is a property of the whole `with` statement.\n * You cannot have recursive and non-recursive CTEs in a same `with` statement.\n * Therefore the recursiveness is determined by the **first** `with` or\n * `withRecusive` call you make.\n *\n * See the {@link with} method for examples and more documentation.\n */\n withRecursive(nameOrBuilder, expression) {\n const cte = parseCommonTableExpression(nameOrBuilder, expression);\n return new QueryCreator({\n ...this.#props,\n withNode: this.#props.withNode\n ? WithNode.cloneWithExpression(this.#props.withNode, cte)\n : WithNode.create(cte, { recursive: true }),\n });\n }\n /**\n * Returns a copy of this query creator instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new QueryCreator({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n /**\n * Returns a copy of this query creator instance without any plugins.\n */\n withoutPlugins() {\n return new QueryCreator({\n ...this.#props,\n executor: this.#props.executor.withoutPlugins(),\n });\n }\n /**\n * Sets the schema to be used for all table references that don't explicitly\n * specify a schema.\n *\n * This only affects the query created through the builder returned from\n * this method and doesn't modify the `db` instance.\n *\n * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0007-schemas.md)\n * for a more detailed explanation.\n *\n * ### Examples\n *\n * ```\n * await db\n * .withSchema('mammals')\n * .selectFrom('pet')\n * .selectAll()\n * .innerJoin('public.person', 'public.person.id', 'pet.owner_id')\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select * from \"mammals\".\"pet\"\n * inner join \"public\".\"person\"\n * on \"public\".\"person\".\"id\" = \"mammals\".\"pet\".\"owner_id\"\n * ```\n *\n * `withSchema` is smart enough to not add schema for aliases,\n * common table expressions or other places where the schema\n * doesn't belong to:\n *\n * ```\n * await db\n * .withSchema('mammals')\n * .selectFrom('pet as p')\n * .select('p.name')\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"p\".\"name\" from \"mammals\".\"pet\" as \"p\"\n * ```\n */\n withSchema(schema) {\n return new QueryCreator({\n ...this.#props,\n executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema)),\n });\n }\n}\n", "/// \nimport { JoinNode } from '../operation-node/join-node.js';\nimport { OverNode } from '../operation-node/over-node.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { JoinBuilder } from '../query-builder/join-builder.js';\nimport { OverBuilder } from '../query-builder/over-builder.js';\nimport { createSelectQueryBuilder as newSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { QueryCreator } from '../query-creator.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { parseTableExpression, parseTableExpressionOrList, } from './table-parser.js';\nexport function createSelectQueryBuilder() {\n return newSelectQueryBuilder({\n queryId: createQueryId(),\n executor: NOOP_QUERY_EXECUTOR,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList([])),\n });\n}\nexport function createQueryCreator() {\n return new QueryCreator({\n executor: NOOP_QUERY_EXECUTOR,\n });\n}\nexport function createJoinBuilder(joinType, table) {\n return new JoinBuilder({\n joinNode: JoinNode.create(joinType, parseTableExpression(table)),\n });\n}\nexport function createOverBuilder() {\n return new OverBuilder({\n overNode: OverNode.create(),\n });\n}\n", "/// \nimport { JoinNode } from '../operation-node/join-node.js';\nimport { parseReferentialBinaryOperation } from './binary-operation-parser.js';\nimport { createJoinBuilder } from './parse-utils.js';\nimport { parseTableExpression, } from './table-parser.js';\nexport function parseJoin(joinType, args) {\n if (args.length === 3) {\n return parseSingleOnJoin(joinType, args[0], args[1], args[2]);\n }\n else if (args.length === 2) {\n return parseCallbackJoin(joinType, args[0], args[1]);\n }\n else if (args.length === 1) {\n return parseOnlessJoin(joinType, args[0]);\n }\n else {\n throw new Error('not implemented');\n }\n}\nfunction parseCallbackJoin(joinType, from, callback) {\n return callback(createJoinBuilder(joinType, from)).toOperationNode();\n}\nfunction parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) {\n return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, '=', rhsColumn));\n}\nfunction parseOnlessJoin(joinType, from) {\n return JoinNode.create(joinType, parseTableExpression(from));\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OffsetNode = freeze({\n is(node) {\n return node.kind === 'OffsetNode';\n },\n create(offset) {\n return freeze({\n kind: 'OffsetNode',\n offset,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByItemNode = freeze({\n is(node) {\n return node.kind === 'GroupByItemNode';\n },\n create(groupBy) {\n return freeze({\n kind: 'GroupByItemNode',\n groupBy,\n });\n },\n});\n", "/// \nimport { GroupByItemNode } from '../operation-node/group-by-item-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parseGroupBy(groupBy) {\n groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy;\n return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SetOperationNode = freeze({\n is(node) {\n return node.kind === 'SetOperationNode';\n },\n create(operator, expression, all) {\n return freeze({\n kind: 'SetOperationNode',\n operator,\n expression,\n all,\n });\n },\n});\n", "/// \nimport { createExpressionBuilder, } from '../expression/expression-builder.js';\nimport { SetOperationNode, } from '../operation-node/set-operation-node.js';\nimport { isFunction, isReadonlyArray } from '../util/object-utils.js';\nimport { parseExpression } from './expression-parser.js';\nexport function parseSetOperations(operator, expression, all) {\n if (isFunction(expression)) {\n expression = expression(createExpressionBuilder());\n }\n if (!isReadonlyArray(expression)) {\n expression = [expression];\n }\n return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all));\n}\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { OrNode } from '../operation-node/or-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nexport class ExpressionWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `ExpressionWrapper` with a new output type.\n */\n $castTo() {\n return new ExpressionWrapper(this.#node);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new ExpressionWrapper(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedExpressionWrapper {\n #expr;\n #alias;\n constructor(expr, alias) {\n this.#expr = expr;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#expr;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\nexport class OrWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `OrWrapper` with a new output type.\n */\n $castTo() {\n return new OrWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\nexport class AndWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AndWrapper` with a new output type.\n */\n $castTo() {\n return new AndWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ValueNode } from './value-node.js';\n/**\n * @internal\n */\nexport const FetchNode = freeze({\n is(node) {\n return node.kind === 'FetchNode';\n },\n create(rowCount, modifier) {\n return {\n kind: 'FetchNode',\n rowCount: ValueNode.create(rowCount),\n modifier,\n };\n },\n});\n", "/// \nimport { FetchNode } from '../operation-node/fetch-node.js';\nimport { isBigInt, isNumber } from '../util/object-utils.js';\nexport function parseFetch(rowCount, modifier) {\n if (!isNumber(rowCount) && !isBigInt(rowCount)) {\n throw new Error(`Invalid fetch row count: ${rowCount}`);\n }\n if (!isFetchModifier(modifier)) {\n throw new Error(`Invalid fetch modifier: ${modifier}`);\n }\n return FetchNode.create(rowCount, modifier);\n}\nfunction isFetchModifier(value) {\n return value === 'only' || value === 'with ties';\n}\n", "/// \nvar _a;\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { SelectModifierNode } from '../operation-node/select-modifier-node.js';\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { OffsetNode } from '../operation-node/offset-node.js';\nimport { asArray, freeze } from '../util/object-utils.js';\nimport { parseGroupBy } from '../parser/group-by-parser.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { parseSetOperations, } from '../parser/set-operation-parser.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { parseFetch } from '../parser/fetch-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nclass SelectQueryBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isSelectQueryBuilder() {\n return true;\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n having(...args) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n havingRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n select(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n distinctOn(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection)),\n });\n }\n modifyFront(modifier) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n distinct() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create('Distinct')),\n });\n }\n forUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forKeyShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForKeyShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forNoKeyUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForNoKeyUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n skipLocked() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('SkipLocked')),\n });\n }\n noWait() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('NoWait')),\n });\n }\n selectAll(table) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n crossJoin(...args) {\n return this.#join('CrossJoin', args);\n }\n innerJoinLateral(...args) {\n return this.#join('LateralInnerJoin', args);\n }\n leftJoinLateral(...args) {\n return this.#join('LateralLeftJoin', args);\n }\n crossJoinLateral(...args) {\n return this.#join('LateralCrossJoin', args);\n }\n crossApply(...args) {\n return this.#join('CrossApply', args);\n }\n outerApply(...args) {\n return this.#join('OuterApply', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n groupBy(groupBy) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy)),\n });\n }\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n offset(offset) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset))),\n });\n }\n fetch(rowCount, modifier = 'only') {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier)),\n });\n }\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n union(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, false)),\n });\n }\n unionAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, true)),\n });\n }\n intersect(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, false)),\n });\n }\n intersectAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, true)),\n });\n }\n except(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, false)),\n });\n }\n exceptAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, true)),\n });\n }\n as(alias) {\n return new AliasedSelectQueryBuilderImpl(this, alias);\n }\n clearSelect() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n clearLimit() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode),\n });\n }\n clearOffset() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n clearGroupBy() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode),\n });\n }\n $call(func) {\n return func(this);\n }\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n $castTo() {\n return new _a(this.#props);\n }\n $narrowType() {\n return new _a(this.#props);\n }\n $assertType() {\n return new _a(this.#props);\n }\n $asTuple() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n $asScalar() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n return result.rows;\n }\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = SelectQueryBuilderImpl;\nexport function createSelectQueryBuilder(props) {\n return new SelectQueryBuilderImpl(props);\n}\n/**\n * {@link SelectQueryBuilder} with an alias. The result of calling {@link SelectQueryBuilder.as}.\n */\nclass AliasedSelectQueryBuilderImpl {\n #queryBuilder;\n #alias;\n constructor(queryBuilder, alias) {\n this.#queryBuilder = queryBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#queryBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get isAliasedSelectQueryBuilder() {\n return true;\n }\n toOperationNode() {\n return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { WhereNode } from './where-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const AggregateFunctionNode = freeze({\n is(node) {\n return node.kind === 'AggregateFunctionNode';\n },\n create(aggregateFunction, aggregated = []) {\n return freeze({\n kind: 'AggregateFunctionNode',\n func: aggregateFunction,\n aggregated,\n });\n },\n cloneWithDistinct(aggregateFunctionNode) {\n return freeze({\n ...aggregateFunctionNode,\n distinct: true,\n });\n },\n cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) {\n const prop = withinGroup ? 'withinGroup' : 'orderBy';\n return freeze({\n ...aggregateFunctionNode,\n [prop]: aggregateFunctionNode[prop]\n ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems)\n : OrderByNode.create(orderItems),\n });\n },\n cloneWithFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'And', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOrFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'Or', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOver(aggregateFunctionNode, over) {\n return freeze({\n ...aggregateFunctionNode,\n over,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FunctionNode = freeze({\n is(node) {\n return node.kind === 'FunctionNode';\n },\n create(func, args) {\n return freeze({\n kind: 'FunctionNode',\n func,\n arguments: args,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { createOverBuilder } from '../parser/parse-utils.js';\nimport { parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nexport class AggregateFunctionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n /**\n * Returns an aliased version of the function.\n *\n * In addition to slapping `as \"the_alias\"` to the end of the SQL,\n * this method also provides strict typing:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.count('id').as('person_count')\n * )\n * .executeTakeFirstOrThrow()\n *\n * // `person_count: number` field exists in the result type.\n * console.log(result.person_count)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(\"id\") as \"person_count\"\n * from \"person\"\n * ```\n */\n as(alias) {\n return new AliasedAggregateFunctionBuilder(this, alias);\n }\n /**\n * Adds a `distinct` clause inside the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) =>\n * eb.fn.count('first_name').distinct().as('first_name_count')\n * )\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(distinct \"first_name\") as \"first_name_count\"\n * from \"person\"\n * ```\n */\n distinct() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode),\n });\n }\n orderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode),\n });\n }\n withinGroupOrderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true),\n });\n }\n filterWhere(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Adds a `filter` clause with a nested `where` clause after the function, where\n * both sides of the operator are references to columns.\n *\n * Similar to {@link WhereInterface}'s `whereRef` method.\n *\n * ### Examples\n *\n * Count people with same first and last names versus general public:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) => [\n * eb.fn\n * .count('id')\n * .filterWhereRef('first_name', '=', 'last_name')\n * .as('repeat_name_count'),\n * eb.fn.count('id').as('total_count'),\n * ])\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select\n * count(\"id\") filter(where \"first_name\" = \"last_name\") as \"repeat_name_count\",\n * count(\"id\") as \"total_count\"\n * from \"person\"\n * ```\n */\n filterWhereRef(lhs, op, rhs) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds an `over` clause (window functions) after the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg('age').over().as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over() as \"average_age\"\n * from \"person\"\n * ```\n *\n * Also supports passing a callback that returns an over builder,\n * allowing to add partition by and sort by clauses inside over.\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg('age').over(\n * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc')\n * ).as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over(partition by \"last_name\" order by \"first_name\" asc) as \"average_age\"\n * from \"person\"\n * ```\n */\n over(over) {\n const builder = createOverBuilder();\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n /**\n * Casts the expression to the given type.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AggregateFunctionBuilder` with a new output type.\n */\n $castTo() {\n return new AggregateFunctionBuilder(this.#props);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new AggregateFunctionBuilder(this.#props);\n }\n toOperationNode() {\n return this.#props.aggregateFunctionNode;\n }\n}\n/**\n * {@link AggregateFunctionBuilder} with an alias. The result of calling {@link AggregateFunctionBuilder.as}.\n */\nexport class AliasedAggregateFunctionBuilder {\n #aggregateFunctionBuilder;\n #alias;\n constructor(aggregateFunctionBuilder, alias) {\n this.#aggregateFunctionBuilder = aggregateFunctionBuilder;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#aggregateFunctionBuilder;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n", "/// \nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { FunctionNode } from '../operation-node/function-node.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { parseSelectAll } from '../parser/select-parser.js';\nimport { AggregateFunctionBuilder } from './aggregate-function-builder.js';\nimport { isString } from '../util/object-utils.js';\nimport { parseTable } from '../parser/table-parser.js';\nexport function createFunctionModule() {\n const fn = (name, args) => {\n return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? [])));\n };\n const agg = (name, args) => {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : undefined),\n });\n };\n return Object.assign(fn, {\n agg,\n avg(column) {\n return agg('avg', [column]);\n },\n coalesce(...values) {\n return fn('coalesce', values);\n },\n count(column) {\n return agg('count', [column]);\n },\n countAll(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('count', parseSelectAll(table)),\n });\n },\n max(column) {\n return agg('max', [column]);\n },\n min(column) {\n return agg('min', [column]);\n },\n sum(column) {\n return agg('sum', [column]);\n },\n any(column) {\n return fn('any', [column]);\n },\n jsonAgg(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('json_agg', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]),\n });\n },\n toJson(table) {\n return new ExpressionWrapper(FunctionNode.create('to_json', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]));\n },\n });\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UnaryOperationNode = freeze({\n is(node) {\n return node.kind === 'UnaryOperationNode';\n },\n create(operator, operand) {\n return freeze({\n kind: 'UnaryOperationNode',\n operator,\n operand,\n });\n },\n});\n", "/// \nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { UnaryOperationNode } from '../operation-node/unary-operation-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nexport function parseExists(operand) {\n return parseUnaryOperation('exists', operand);\n}\nexport function parseNotExists(operand) {\n return parseUnaryOperation('not exists', operand);\n}\nexport function parseUnaryOperation(operator, operand) {\n return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand));\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const CaseNode = freeze({\n is(node) {\n return node.kind === 'CaseNode';\n },\n create(value) {\n return freeze({\n kind: 'CaseNode',\n value,\n });\n },\n cloneWithWhen(caseNode, when) {\n return freeze({\n ...caseNode,\n when: freeze(caseNode.when ? [...caseNode.when, when] : [when]),\n });\n },\n cloneWithThen(caseNode, then) {\n return freeze({\n ...caseNode,\n when: caseNode.when\n ? freeze([\n ...caseNode.when.slice(0, -1),\n WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then),\n ])\n : undefined,\n });\n },\n cloneWith(caseNode, props) {\n return freeze({\n ...caseNode,\n ...props,\n });\n },\n});\n", "/// \nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { freeze } from '../util/object-utils.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { isSafeImmediateValue, parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nexport class CaseBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n}\nexport class CaseThenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n then(valueExpression) {\n return new CaseWhenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression)),\n });\n }\n}\nexport class CaseWhenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n else(valueExpression) {\n return new CaseEndBuilder({\n ...this.#props,\n node: CaseNode.cloneWith(this.#props.node, {\n else: isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression),\n }),\n });\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\nexport class CaseEndBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathLegNode = freeze({\n is(node) {\n return node.kind === 'JSONPathLegNode';\n },\n create(type, value) {\n return freeze({\n kind: 'JSONPathLegNode',\n type,\n value,\n });\n },\n});\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathLegNode, } from '../operation-node/json-path-leg-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nexport class JSONPathBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Access an element of a JSON array in a specific location.\n *\n * Since there's no guarantee an element exists in the given array location, the\n * resulting type is always nullable. If you're sure the element exists, you\n * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely.\n *\n * See also {@link key} to access properties of JSON objects.\n *\n * ### Examples\n *\n * ```ts\n * await db.selectFrom('person')\n * .select(eb =>\n * eb.ref('nicknames', '->').at(0).as('primary_nickname')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"nicknames\"->0 as \"primary_nickname\" from \"person\"\n *```\n *\n * Combined with {@link key}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('experience', '->').at(0).key('role').as('first_role')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"experience\"->0->'role' as \"first_role\" from \"person\"\n * ```\n *\n * You can use `'last'` to access the last element of the array in MySQL:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->$').at('last').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `nicknames`->'$[last]' as `last_nickname` from `person`\n * ```\n *\n * Or `'#-1'` in SQLite:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select \"nicknames\"->>'$[#-1]' as `last_nickname` from `person`\n * ```\n */\n at(index) {\n return this.#createBuilderWithPathLeg('ArrayLocation', index);\n }\n /**\n * Access a property of a JSON object.\n *\n * If a field is optional, the resulting type will be nullable.\n *\n * See also {@link at} to access elements of JSON arrays.\n *\n * ### Examples\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('address', '->').key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"address\"->'city' as \"city\" from \"person\"\n * ```\n *\n * Going deeper:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->$').key('website').key('url').as('website_url')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `profile`->'$.website.url' as `website_url` from `person`\n * ```\n *\n * Combined with {@link at}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"profile\"->'addresses'->0->'city' as \"city\" from \"person\"\n * ```\n */\n key(key) {\n return this.#createBuilderWithPathLeg('Member', key);\n }\n #createBuilderWithPathLeg(legType, value) {\n if (JSONReferenceNode.is(this.#node)) {\n return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal)\n ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value))\n : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value))));\n }\n return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value)));\n }\n}\nexport class TraversedJSONPathBuilder extends JSONPathBuilder {\n #node;\n constructor(node) {\n super(node);\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedJSONPathBuilder(this, alias);\n }\n /**\n * Change the output type of the json path.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `JSONPathBuilder` with a new output type.\n */\n $castTo() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n $notNull() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedJSONPathBuilder {\n #jsonPath;\n #alias;\n constructor(jsonPath, alias) {\n this.#jsonPath = jsonPath;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#jsonPath;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TupleNode = freeze({\n is(node) {\n return node.kind === 'TupleNode';\n },\n create(values) {\n return freeze({\n kind: 'TupleNode',\n values: freeze(values),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nconst SIMPLE_COLUMN_DATA_TYPES = [\n 'varchar',\n 'char',\n 'text',\n 'integer',\n 'int2',\n 'int4',\n 'int8',\n 'smallint',\n 'bigint',\n 'boolean',\n 'real',\n 'double precision',\n 'float4',\n 'float8',\n 'decimal',\n 'numeric',\n 'binary',\n 'bytea',\n 'date',\n 'datetime',\n 'time',\n 'timetz',\n 'timestamp',\n 'timestamptz',\n 'serial',\n 'bigserial',\n 'uuid',\n 'json',\n 'jsonb',\n 'blob',\n 'varbinary',\n 'int4range',\n 'int4multirange',\n 'int8range',\n 'int8multirange',\n 'numrange',\n 'nummultirange',\n 'tsrange',\n 'tsmultirange',\n 'tstzrange',\n 'tstzmultirange',\n 'daterange',\n 'datemultirange',\n];\nconst COLUMN_DATA_TYPE_REGEX = [\n /^varchar\\(\\d+\\)$/,\n /^char\\(\\d+\\)$/,\n /^decimal\\(\\d+, \\d+\\)$/,\n /^numeric\\(\\d+, \\d+\\)$/,\n /^binary\\(\\d+\\)$/,\n /^datetime\\(\\d+\\)$/,\n /^time\\(\\d+\\)$/,\n /^timetz\\(\\d+\\)$/,\n /^timestamp\\(\\d+\\)$/,\n /^timestamptz\\(\\d+\\)$/,\n /^varbinary\\(\\d+\\)$/,\n];\n/**\n * @internal\n */\nexport const DataTypeNode = freeze({\n is(node) {\n return node.kind === 'DataTypeNode';\n },\n create(dataType) {\n return freeze({\n kind: 'DataTypeNode',\n dataType,\n });\n },\n});\nexport function isColumnDataType(dataType) {\n if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) {\n return true;\n }\n if (COLUMN_DATA_TYPE_REGEX.some((r) => r.test(dataType))) {\n return true;\n }\n return false;\n}\n", "/// \nimport { DataTypeNode, isColumnDataType, } from '../operation-node/data-type-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nexport function parseDataTypeExpression(dataType) {\n if (isOperationNodeSource(dataType)) {\n return dataType.toOperationNode();\n }\n if (isColumnDataType(dataType)) {\n return DataTypeNode.create(dataType);\n }\n throw new Error(`invalid column data type ${JSON.stringify(dataType)}`);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const CastNode = freeze({\n is(node) {\n return node.kind === 'CastNode';\n },\n create(expression, dataType) {\n return freeze({\n kind: 'CastNode',\n expression,\n dataType,\n });\n },\n});\n", "/// \nimport { createSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { parseTableExpressionOrList, parseTable, } from '../parser/table-parser.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createFunctionModule, } from '../query-builder/function-module.js';\nimport { parseJSONReference, parseReferenceExpression, parseStringReference, } from '../parser/reference-parser.js';\nimport { parseFilterList, parseFilterObject, parseValueBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { ExpressionWrapper } from './expression-wrapper.js';\nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { parseUnaryOperation } from '../parser/unary-operation-parser.js';\nimport { parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { CaseBuilder } from '../query-builder/case-builder.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { isReadonlyArray, isUndefined } from '../util/object-utils.js';\nimport { JSONPathBuilder } from '../query-builder/json-path-builder.js';\nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { TupleNode } from '../operation-node/tuple-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { CastNode } from '../operation-node/cast-node.js';\nexport function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) {\n function binary(lhs, op, rhs) {\n return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs));\n }\n function unary(op, expr) {\n return new ExpressionWrapper(parseUnaryOperation(op, expr));\n }\n const eb = Object.assign(binary, {\n fn: undefined,\n eb: undefined,\n selectFrom(table) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)),\n });\n },\n case(reference) {\n return new CaseBuilder({\n node: CaseNode.create(isUndefined(reference)\n ? undefined\n : parseReferenceExpression(reference)),\n });\n },\n ref(reference, op) {\n if (isUndefined(op)) {\n return new ExpressionWrapper(parseStringReference(reference));\n }\n return new JSONPathBuilder(parseJSONReference(reference, op));\n },\n jsonPath() {\n return new JSONPathBuilder(JSONPathNode.create());\n },\n table(table) {\n return new ExpressionWrapper(parseTable(table));\n },\n val(value) {\n return new ExpressionWrapper(parseValueExpression(value));\n },\n refTuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression)));\n },\n tuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression)));\n },\n lit(value) {\n return new ExpressionWrapper(parseSafeImmediateValue(value));\n },\n unary,\n not(expr) {\n return unary('not', expr);\n },\n exists(expr) {\n return unary('exists', expr);\n },\n neg(expr) {\n return unary('-', expr);\n },\n between(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n betweenSymmetric(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between symmetric'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n and(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'and'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'and'));\n },\n or(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'or'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'or'));\n },\n parens(...args) {\n const node = parseValueBinaryOperationOrExpression(args);\n if (ParensNode.is(node)) {\n // No double wrapping.\n return new ExpressionWrapper(node);\n }\n else {\n return new ExpressionWrapper(ParensNode.create(node));\n }\n },\n cast(expr, dataType) {\n return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType)));\n },\n withSchema(schema) {\n return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema)));\n },\n });\n eb.fn = createFunctionModule();\n eb.eb = eb;\n return eb;\n}\nexport function expressionBuilder(_) {\n return createExpressionBuilder();\n}\n", "/// \nimport { isAliasedExpression, isExpression, } from '../expression/expression.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nexport function parseExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid expression: ${JSON.stringify(exp)}`);\n}\nexport function parseAliasedExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`);\n}\nexport function isExpressionOrFactory(obj) {\n return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj);\n}\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicTableBuilder {\n #table;\n get table() {\n return this.#table;\n }\n constructor(table) {\n this.#table = table;\n }\n as(alias) {\n return new AliasedDynamicTableBuilder(this.#table, alias);\n }\n}\nexport class AliasedDynamicTableBuilder {\n #table;\n #alias;\n get table() {\n return this.#table;\n }\n get alias() {\n return this.#alias;\n }\n constructor(table, alias) {\n this.#table = table;\n this.#alias = alias;\n }\n toOperationNode() {\n return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias));\n }\n}\nexport function isAliasedDynamicTableBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.table) &&\n isString(obj.alias));\n}\n", "/// \nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isAliasedDynamicTableBuilder, } from '../dynamic/dynamic-table-builder.js';\nexport function parseTableExpressionOrList(table) {\n if (isReadonlyArray(table)) {\n return table.map((it) => parseTableExpression(it));\n }\n else {\n return [parseTableExpression(table)];\n }\n}\nexport function parseTableExpression(table) {\n if (isString(table)) {\n return parseAliasedTable(table);\n }\n else if (isAliasedDynamicTableBuilder(table)) {\n return table.toOperationNode();\n }\n else {\n return parseAliasedExpression(table);\n }\n}\nexport function parseAliasedTable(from) {\n const ALIAS_SEPARATOR = ' as ';\n if (from.includes(ALIAS_SEPARATOR)) {\n const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseTable(table), IdentifierNode.create(alias));\n }\n else {\n return parseTable(from);\n }\n}\nexport function parseTable(from) {\n const SCHEMA_SEPARATOR = '.';\n if (from.includes(SCHEMA_SEPARATOR)) {\n const [schema, table] = from.split(SCHEMA_SEPARATOR).map(trim);\n return TableNode.createWithSchema(schema, table);\n }\n else {\n return TableNode.create(from);\n }\n}\nfunction trim(str) {\n return str.trim();\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AddColumnNode = freeze({\n is(node) {\n return node.kind === 'AddColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'AddColumnNode',\n column,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\n/**\n * @internal\n */\nexport const ColumnDefinitionNode = freeze({\n is(node) {\n return node.kind === 'ColumnDefinitionNode';\n },\n create(column, dataType) {\n return freeze({\n kind: 'ColumnDefinitionNode',\n column: ColumnNode.create(column),\n dataType,\n });\n },\n cloneWithFrontModifier(node, modifier) {\n return freeze({\n ...node,\n frontModifiers: node.frontModifiers\n ? freeze([...node.frontModifiers, modifier])\n : [modifier],\n });\n },\n cloneWithEndModifier(node, modifier) {\n return freeze({\n ...node,\n endModifiers: node.endModifiers\n ? freeze([...node.endModifiers, modifier])\n : [modifier],\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\n/**\n * @internal\n */\nexport const DropColumnNode = freeze({\n is(node) {\n return node.kind === 'DropColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'DropColumnNode',\n column: ColumnNode.create(column),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\n/**\n * @internal\n */\nexport const RenameColumnNode = freeze({\n is(node) {\n return node.kind === 'RenameColumnNode';\n },\n create(column, newColumn) {\n return freeze({\n kind: 'RenameColumnNode',\n column: ColumnNode.create(column),\n renameTo: ColumnNode.create(newColumn),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CheckConstraintNode = freeze({\n is(node) {\n return node.kind === 'CheckConstraintNode';\n },\n create(expression, constraintName) {\n return freeze({\n kind: 'CheckConstraintNode',\n expression,\n name: constraintName\n ? IdentifierNode.create(constraintName)\n : undefined,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nexport const ON_MODIFY_FOREIGN_ACTIONS = [\n 'no action',\n 'restrict',\n 'cascade',\n 'set null',\n 'set default',\n];\n/**\n * @internal\n */\nexport const ReferencesNode = freeze({\n is(node) {\n return node.kind === 'ReferencesNode';\n },\n create(table, columns) {\n return freeze({\n kind: 'ReferencesNode',\n table,\n columns: freeze([...columns]),\n });\n },\n cloneWithOnDelete(references, onDelete) {\n return freeze({\n ...references,\n onDelete,\n });\n },\n cloneWithOnUpdate(references, onUpdate) {\n return freeze({\n ...references,\n onUpdate,\n });\n },\n});\n", "/// \nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nexport function parseDefaultValueExpression(value) {\n return isOperationNodeSource(value)\n ? value.toOperationNode()\n : ValueNode.createImmediate(value);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GeneratedNode = freeze({\n is(node) {\n return node.kind === 'GeneratedNode';\n },\n create(params) {\n return freeze({\n kind: 'GeneratedNode',\n ...params,\n });\n },\n createWithExpression(expression) {\n return freeze({\n kind: 'GeneratedNode',\n always: true,\n expression,\n });\n },\n cloneWith(node, params) {\n return freeze({\n ...node,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const DefaultValueNode = freeze({\n is(node) {\n return node.kind === 'DefaultValueNode';\n },\n create(defaultValue) {\n return freeze({\n kind: 'DefaultValueNode',\n defaultValue,\n });\n },\n});\n", "/// \nimport { ON_MODIFY_FOREIGN_ACTIONS, } from '../operation-node/references-node.js';\nexport function parseOnModifyForeignAction(action) {\n if (ON_MODIFY_FOREIGN_ACTIONS.includes(action)) {\n return action;\n }\n throw new Error(`invalid OnModifyForeignAction ${action}`);\n}\n", "/// \nimport { CheckConstraintNode } from '../operation-node/check-constraint-node.js';\nimport { ReferencesNode, } from '../operation-node/references-node.js';\nimport { SelectAllNode } from '../operation-node/select-all-node.js';\nimport { parseStringReference } from '../parser/reference-parser.js';\nimport { ColumnDefinitionNode } from '../operation-node/column-definition-node.js';\nimport { parseDefaultValueExpression, } from '../parser/default-value-parser.js';\nimport { GeneratedNode } from '../operation-node/generated-node.js';\nimport { DefaultValueNode } from '../operation-node/default-value-node.js';\nimport { parseOnModifyForeignAction } from '../parser/on-modify-action-parser.js';\nexport class ColumnDefinitionBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Adds `auto_increment` or `autoincrement` to the column definition\n * depending on the dialect.\n *\n * Some dialects like PostgreSQL don't support this. On PostgreSQL\n * you can use the `serial` or `bigserial` data type instead.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.autoIncrement().primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key auto_increment\n * )\n * ```\n */\n autoIncrement() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { autoIncrement: true }));\n }\n /**\n * Makes the column an identity column.\n *\n * This only works on some dialects like MS SQL Server (MSSQL).\n *\n * For PostgreSQL's `generated always as identity` use {@link generatedAlwaysAsIdentity}.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.identity().primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (MSSQL):\n *\n * ```sql\n * create table \"person\" (\n * \"id\" integer identity primary key\n * )\n * ```\n */\n identity() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { identity: true }));\n }\n /**\n * Makes the column the primary key.\n *\n * If you want to specify a composite primary key use the\n * {@link CreateTableBuilder.addPrimaryKeyConstraint} method.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key\n * )\n */\n primaryKey() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { primaryKey: true }));\n }\n /**\n * Adds a foreign key constraint for the column.\n *\n * If your database engine doesn't support foreign key constraints in the\n * column definition (like MySQL 5) you need to call the table level\n * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('owner_id', 'integer', (col) => col.references('person.id'))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"pet\" (\n * \"owner_id\" integer references \"person\" (\"id\")\n * )\n * ```\n */\n references(ref) {\n const references = parseStringReference(ref);\n if (!references.table || SelectAllNode.is(references.column)) {\n throw new Error(`invalid call references('${ref}'). The reference must have format table.column or schema.table.column`);\n }\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n references: ReferencesNode.create(references.table, [\n references.column,\n ]),\n }));\n }\n /**\n * Adds an `on delete` constraint for the foreign key column.\n *\n * If your database engine doesn't support foreign key constraints in the\n * column definition (like MySQL 5) you need to call the table level\n * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn(\n * 'owner_id',\n * 'integer',\n * (col) => col.references('person.id').onDelete('cascade')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"pet\" (\n * \"owner_id\" integer references \"person\" (\"id\") on delete cascade\n * )\n * ```\n */\n onDelete(onDelete) {\n if (!this.#node.references) {\n throw new Error('on delete constraint can only be added for foreign keys');\n }\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n references: ReferencesNode.cloneWithOnDelete(this.#node.references, parseOnModifyForeignAction(onDelete)),\n }));\n }\n /**\n * Adds an `on update` constraint for the foreign key column.\n *\n * If your database engine doesn't support foreign key constraints in the\n * column definition (like MySQL 5) you need to call the table level\n * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn(\n * 'owner_id',\n * 'integer',\n * (col) => col.references('person.id').onUpdate('cascade')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"pet\" (\n * \"owner_id\" integer references \"person\" (\"id\") on update cascade\n * )\n * ```\n */\n onUpdate(onUpdate) {\n if (!this.#node.references) {\n throw new Error('on update constraint can only be added for foreign keys');\n }\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n references: ReferencesNode.cloneWithOnUpdate(this.#node.references, parseOnModifyForeignAction(onUpdate)),\n }));\n }\n /**\n * Adds a unique constraint for the column.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('email', 'varchar(255)', col => col.unique())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `email` varchar(255) unique\n * )\n * ```\n */\n unique() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unique: true }));\n }\n /**\n * Adds a `not null` constraint for the column.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('first_name', 'varchar(255)', col => col.notNull())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `first_name` varchar(255) not null\n * )\n * ```\n */\n notNull() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { notNull: true }));\n }\n /**\n * Adds a `unsigned` modifier for the column.\n *\n * This only works on some dialects like MySQL.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('age', 'integer', col => col.unsigned())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `age` integer unsigned\n * )\n * ```\n */\n unsigned() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unsigned: true }));\n }\n /**\n * Adds a default value constraint for the column.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('number_of_legs', 'integer', (col) => col.defaultTo(4))\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `pet` (\n * `number_of_legs` integer default 4\n * )\n * ```\n *\n * Values passed to `defaultTo` are interpreted as value literals by default. You can define\n * an arbitrary SQL expression using the {@link sql} template tag:\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('pet')\n * .addColumn(\n * 'created_at',\n * 'timestamp',\n * (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`)\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `pet` (\n * `created_at` timestamp default CURRENT_TIMESTAMP\n * )\n * ```\n */\n defaultTo(value) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n defaultTo: DefaultValueNode.create(parseDefaultValueExpression(value)),\n }));\n }\n /**\n * Adds a check constraint for the column.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('pet')\n * .addColumn('number_of_legs', 'integer', (col) =>\n * col.check(sql`number_of_legs < 5`)\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `pet` (\n * `number_of_legs` integer check (number_of_legs < 5)\n * )\n * ```\n */\n check(expression) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n check: CheckConstraintNode.create(expression.toOperationNode()),\n }));\n }\n /**\n * Makes the column a generated column using a `generated always as` statement.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('full_name', 'varchar(255)',\n * (col) => col.generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`)\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name))\n * )\n * ```\n */\n generatedAlwaysAs(expression) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n generated: GeneratedNode.createWithExpression(expression.toOperationNode()),\n }));\n }\n /**\n * Adds the `generated always as identity` specifier.\n *\n * This only works on some dialects like PostgreSQL.\n *\n * For MS SQL Server (MSSQL)'s identity column use {@link identity}.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.generatedAlwaysAsIdentity().primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"person\" (\n * \"id\" integer generated always as identity primary key\n * )\n * ```\n */\n generatedAlwaysAsIdentity() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n generated: GeneratedNode.create({ identity: true, always: true }),\n }));\n }\n /**\n * Adds the `generated by default as identity` specifier on supported dialects.\n *\n * This only works on some dialects like PostgreSQL.\n *\n * For MS SQL Server (MSSQL)'s identity column use {@link identity}.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.generatedByDefaultAsIdentity().primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"person\" (\n * \"id\" integer generated by default as identity primary key\n * )\n * ```\n */\n generatedByDefaultAsIdentity() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n generated: GeneratedNode.create({ identity: true, byDefault: true }),\n }));\n }\n /**\n * Makes a generated column stored instead of virtual. This method can only\n * be used with {@link generatedAlwaysAs}\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('full_name', 'varchar(255)', (col) => col\n * .generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`)\n * .stored()\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) stored\n * )\n * ```\n */\n stored() {\n if (!this.#node.generated) {\n throw new Error('stored() can only be called after generatedAlwaysAs');\n }\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n generated: GeneratedNode.cloneWith(this.#node.generated, {\n stored: true,\n }),\n }));\n }\n /**\n * This can be used to add any additional SQL right after the column's data type.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn(\n * 'first_name',\n * 'varchar(36)',\n * (col) => col.modifyFront(sql`collate utf8mb4_general_ci`).notNull()\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key,\n * `first_name` varchar(36) collate utf8mb4_general_ci not null\n * )\n * ```\n */\n modifyFront(modifier) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(this.#node, modifier.toOperationNode()));\n }\n /**\n * Adds `nulls not distinct` specifier.\n * Should be used with `unique` constraint.\n *\n * This only works on some dialects like PostgreSQL.\n *\n * ### Examples\n *\n * ```ts\n * db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn('first_name', 'varchar(30)', col => col.unique().nullsNotDistinct())\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"person\" (\n * \"id\" integer primary key,\n * \"first_name\" varchar(30) unique nulls not distinct\n * )\n * ```\n */\n nullsNotDistinct() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { nullsNotDistinct: true }));\n }\n /**\n * Adds `if not exists` specifier. This only works for PostgreSQL.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .addColumn('email', 'varchar(255)', col => col.unique().ifNotExists())\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * alter table \"person\" add column if not exists \"email\" varchar(255) unique\n * ```\n */\n ifNotExists() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { ifNotExists: true }));\n }\n /**\n * This can be used to add any additional SQL to the end of the column definition.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn(\n * 'age',\n * 'integer',\n * col => col.unsigned()\n * .notNull()\n * .modifyEnd(sql`comment ${sql.lit('it is not polite to ask a woman her age')}`)\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key,\n * `age` integer unsigned not null comment 'it is not polite to ask a woman her age'\n * )\n * ```\n */\n modifyEnd(modifier) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(this.#node, modifier.toOperationNode()));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ModifyColumnNode = freeze({\n is(node) {\n return node.kind === 'ModifyColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'ModifyColumnNode',\n column,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\nimport { ReferencesNode, } from './references-node.js';\n/**\n * @internal\n */\nexport const ForeignKeyConstraintNode = freeze({\n is(node) {\n return node.kind === 'ForeignKeyConstraintNode';\n },\n create(sourceColumns, targetTable, targetColumns, constraintName) {\n return freeze({\n kind: 'ForeignKeyConstraintNode',\n columns: sourceColumns,\n references: ReferencesNode.create(targetTable, targetColumns),\n name: constraintName\n ? IdentifierNode.create(constraintName)\n : undefined,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js';\nimport { parseOnModifyForeignAction } from '../parser/on-modify-action-parser.js';\nexport class ForeignKeyConstraintBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n onDelete(onDelete) {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {\n onDelete: parseOnModifyForeignAction(onDelete),\n }));\n }\n onUpdate(onUpdate) {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {\n onUpdate: parseOnModifyForeignAction(onUpdate),\n }));\n }\n deferrable() {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: true }));\n }\n notDeferrable() {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: false }));\n }\n initiallyDeferred() {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: true,\n }));\n }\n initiallyImmediate() {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: false,\n }));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AddConstraintNode = freeze({\n is(node) {\n return node.kind === 'AddConstraintNode';\n },\n create(constraint) {\n return freeze({\n kind: 'AddConstraintNode',\n constraint,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const UniqueConstraintNode = freeze({\n is(node) {\n return node.kind === 'UniqueConstraintNode';\n },\n create(columns, constraintName, nullsNotDistinct) {\n return freeze({\n kind: 'UniqueConstraintNode',\n columns: freeze(columns.map(ColumnNode.create)),\n name: constraintName\n ? IdentifierNode.create(constraintName)\n : undefined,\n nullsNotDistinct,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const DropConstraintNode = freeze({\n is(node) {\n return node.kind === 'DropConstraintNode';\n },\n create(constraintName) {\n return freeze({\n kind: 'DropConstraintNode',\n constraintName: IdentifierNode.create(constraintName),\n });\n },\n cloneWith(dropConstraint, props) {\n return freeze({\n ...dropConstraint,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\n/**\n * @internal\n */\nexport const AlterColumnNode = freeze({\n is(node) {\n return node.kind === 'AlterColumnNode';\n },\n create(column, prop, value) {\n return freeze({\n kind: 'AlterColumnNode',\n column: ColumnNode.create(column),\n [prop]: value,\n });\n },\n});\n", "/// \nimport { AlterColumnNode } from '../operation-node/alter-column-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { parseDefaultValueExpression, } from '../parser/default-value-parser.js';\nexport class AlterColumnBuilder {\n #column;\n constructor(column) {\n this.#column = column;\n }\n setDataType(dataType) {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'dataType', parseDataTypeExpression(dataType)));\n }\n setDefault(value) {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'setDefault', parseDefaultValueExpression(value)));\n }\n dropDefault() {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'dropDefault', true));\n }\n setNotNull() {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'setNotNull', true));\n }\n dropNotNull() {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'dropNotNull', true));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n}\n/**\n * Allows us to force consumers to do exactly one alteration to a column.\n *\n * One cannot do no alterations:\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * // .execute() // Property 'execute' does not exist on type 'AlteredColumnBuilder'.\n * ```\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * // .alterColumn('age', (ac) => ac) // Type 'AlterColumnBuilder' is not assignable to type 'AlteredColumnBuilder'.\n * // .execute()\n * ```\n *\n * One cannot do multiple alterations:\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * // .alterColumn('age', (ac) => ac.dropNotNull().setNotNull()) // Property 'setNotNull' does not exist on type 'AlteredColumnBuilder'.\n * // .execute()\n * ```\n *\n * Which would now throw a compilation error, instead of a runtime error.\n */\nexport class AlteredColumnBuilder {\n #alterColumnNode;\n constructor(alterColumnNode) {\n this.#alterColumnNode = alterColumnNode;\n }\n toOperationNode() {\n return this.#alterColumnNode;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nexport class AlterTableExecutor {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { AddConstraintNode } from '../operation-node/add-constraint-node.js';\nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class AlterTableAddForeignKeyConstraintBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n onDelete(onDelete) {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.onDelete(onDelete),\n });\n }\n onUpdate(onUpdate) {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.onUpdate(onUpdate),\n });\n }\n deferrable() {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.deferrable(),\n });\n }\n notDeferrable() {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.notDeferrable(),\n });\n }\n initiallyDeferred() {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.initiallyDeferred(),\n });\n }\n initiallyImmediate() {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.initiallyImmediate(),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(AlterTableNode.cloneWithTableProps(this.#props.node, {\n addConstraint: AddConstraintNode.create(this.#props.constraintBuilder.toOperationNode()),\n }), this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { DropConstraintNode } from '../operation-node/drop-constraint-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class AlterTableDropConstraintBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifExists() {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {\n ifExists: true,\n }),\n }),\n });\n }\n cascade() {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {\n modifier: 'cascade',\n }),\n }),\n });\n }\n restrict() {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {\n modifier: 'restrict',\n }),\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const PrimaryKeyConstraintNode = freeze({\n is(node) {\n return node.kind === 'PrimaryKeyConstraintNode';\n },\n create(columns, constraintName) {\n return freeze({\n kind: 'PrimaryKeyConstraintNode',\n columns: freeze(columns.map(ColumnNode.create)),\n name: constraintName\n ? IdentifierNode.create(constraintName)\n : undefined,\n });\n },\n cloneWith(node, props) {\n return freeze({ ...node, ...props });\n },\n});\n/**\n * Backwards compatibility for a typo in the codebase.\n *\n * @deprecated Use {@link PrimaryKeyConstraintNode} instead.\n */\nexport const PrimaryConstraintNode = PrimaryKeyConstraintNode;\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const AddIndexNode = freeze({\n is(node) {\n return node.kind === 'AddIndexNode';\n },\n create(name) {\n return freeze({\n kind: 'AddIndexNode',\n name: IdentifierNode.create(name),\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n cloneWithColumns(node, columns) {\n return freeze({\n ...node,\n columns: [...(node.columns || []), ...columns],\n });\n },\n});\n", "/// \nimport { AddIndexNode } from '../operation-node/add-index-node.js';\nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseOrderedColumnName, } from '../parser/reference-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class AlterTableAddIndexBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Makes the index unique.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .addIndex('person_first_name_index')\n * .unique()\n * .column('email')\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add unique index `person_first_name_index` (`email`)\n * ```\n */\n unique() {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, {\n unique: true,\n }),\n }),\n });\n }\n /**\n * Adds a column to the index.\n *\n * Also see {@link columns} for adding multiple columns at once or {@link expression}\n * for specifying an arbitrary expression.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .addIndex('person_first_name_and_age_index')\n * .column('first_name')\n * .column('age desc')\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc)\n * ```\n */\n column(column) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [\n parseOrderedColumnName(column),\n ]),\n }),\n });\n }\n /**\n * Specifies a list of columns for the index.\n *\n * Also see {@link column} for adding a single column or {@link expression} for\n * specifying an arbitrary expression.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .addIndex('person_first_name_and_age_index')\n * .columns(['first_name', 'age desc'])\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc)\n * ```\n */\n columns(columns) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, columns.map(parseOrderedColumnName)),\n }),\n });\n }\n /**\n * Specifies an arbitrary expression for the index.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .alterTable('person')\n * .addIndex('person_first_name_index')\n * .expression(sql`(first_name < 'Sami')`)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add index `person_first_name_index` ((first_name < 'Sami'))\n * ```\n */\n expression(expression) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [\n expression.toOperationNode(),\n ]),\n }),\n });\n }\n using(indexType) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, {\n using: RawNode.createWithSql(indexType),\n }),\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { UniqueConstraintNode } from '../operation-node/unique-constraint-node.js';\nexport class UniqueConstraintNodeBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Adds `nulls not distinct` to the unique constraint definition\n *\n * Supported by PostgreSQL dialect only\n */\n nullsNotDistinct() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { nullsNotDistinct: true }));\n }\n deferrable() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: true }));\n }\n notDeferrable() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: false }));\n }\n initiallyDeferred() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: true,\n }));\n }\n initiallyImmediate() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: false,\n }));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nimport { PrimaryKeyConstraintNode } from '../operation-node/primary-key-constraint-node.js';\nexport class PrimaryKeyConstraintBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n deferrable() {\n return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: true }));\n }\n notDeferrable() {\n return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: false }));\n }\n initiallyDeferred() {\n return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: true,\n }));\n }\n initiallyImmediate() {\n return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: false,\n }));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nexport class CheckConstraintBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const RenameConstraintNode = freeze({\n is(node) {\n return node.kind === 'RenameConstraintNode';\n },\n create(oldName, newName) {\n return freeze({\n kind: 'RenameConstraintNode',\n oldName: IdentifierNode.create(oldName),\n newName: IdentifierNode.create(newName),\n });\n },\n});\n", "/// \nimport { AddColumnNode } from '../operation-node/add-column-node.js';\nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { ColumnDefinitionNode } from '../operation-node/column-definition-node.js';\nimport { DropColumnNode } from '../operation-node/drop-column-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { RenameColumnNode } from '../operation-node/rename-column-node.js';\nimport { freeze, noop } from '../util/object-utils.js';\nimport { ColumnDefinitionBuilder, } from './column-definition-builder.js';\nimport { ModifyColumnNode } from '../operation-node/modify-column-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { ForeignKeyConstraintBuilder, } from './foreign-key-constraint-builder.js';\nimport { AddConstraintNode } from '../operation-node/add-constraint-node.js';\nimport { UniqueConstraintNode } from '../operation-node/unique-constraint-node.js';\nimport { CheckConstraintNode } from '../operation-node/check-constraint-node.js';\nimport { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { DropConstraintNode } from '../operation-node/drop-constraint-node.js';\nimport { AlterColumnBuilder, } from './alter-column-builder.js';\nimport { AlterTableExecutor } from './alter-table-executor.js';\nimport { AlterTableAddForeignKeyConstraintBuilder } from './alter-table-add-foreign-key-constraint-builder.js';\nimport { AlterTableDropConstraintBuilder } from './alter-table-drop-constraint-builder.js';\nimport { PrimaryKeyConstraintNode } from '../operation-node/primary-key-constraint-node.js';\nimport { DropIndexNode } from '../operation-node/drop-index-node.js';\nimport { AddIndexNode } from '../operation-node/add-index-node.js';\nimport { AlterTableAddIndexBuilder } from './alter-table-add-index-builder.js';\nimport { UniqueConstraintNodeBuilder, } from './unique-constraint-builder.js';\nimport { PrimaryKeyConstraintBuilder, } from './primary-key-constraint-builder.js';\nimport { CheckConstraintBuilder, } from './check-constraint-builder.js';\nimport { RenameConstraintNode } from '../operation-node/rename-constraint-node.js';\n/**\n * This builder can be used to create a `alter table` query.\n */\nexport class AlterTableBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n renameTo(newTableName) {\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n renameTo: parseTable(newTableName),\n }),\n });\n }\n setSchema(newSchema) {\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n setSchema: IdentifierNode.create(newSchema),\n }),\n });\n }\n alterColumn(column, alteration) {\n const builder = alteration(new AlterColumnBuilder(column));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode()),\n });\n }\n dropColumn(column) {\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column)),\n });\n }\n renameColumn(column, newColumn) {\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn)),\n });\n }\n addColumn(columnName, dataType, build = noop) {\n const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode())),\n });\n }\n modifyColumn(columnName, dataType, build = noop) {\n const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode())),\n });\n }\n /**\n * See {@link CreateTableBuilder.addUniqueConstraint}\n */\n addUniqueConstraint(constraintName, columns, build = noop) {\n const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName)));\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addConstraint: AddConstraintNode.create(uniqueConstraintBuilder.toOperationNode()),\n }),\n });\n }\n /**\n * See {@link CreateTableBuilder.addCheckConstraint}\n */\n addCheckConstraint(constraintName, checkExpression, build = noop) {\n const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName)));\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()),\n }),\n });\n }\n /**\n * See {@link CreateTableBuilder.addForeignKeyConstraint}\n *\n * Unlike {@link CreateTableBuilder.addForeignKeyConstraint} this method returns\n * the constraint builder and doesn't take a callback as the last argument. This\n * is because you can only add one column per `ALTER TABLE` query.\n */\n addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) {\n const constraintBuilder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName)));\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder,\n });\n }\n /**\n * See {@link CreateTableBuilder.addPrimaryKeyConstraint}\n */\n addPrimaryKeyConstraint(constraintName, columns, build = noop) {\n const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName)));\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()),\n }),\n });\n }\n dropConstraint(constraintName) {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropConstraint: DropConstraintNode.create(constraintName),\n }),\n });\n }\n renameConstraint(oldName, newName) {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n renameConstraint: RenameConstraintNode.create(oldName, newName),\n }),\n });\n }\n /**\n * This can be used to add index to table.\n *\n * ### Examples\n *\n * ```ts\n * db.schema.alterTable('person')\n * .addIndex('person_email_index')\n * .column('email')\n * .unique()\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add unique index `person_email_index` (`email`)\n * ```\n */\n addIndex(indexName) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.create(indexName),\n }),\n });\n }\n /**\n * This can be used to drop index from table.\n *\n * ### Examples\n *\n * ```ts\n * db.schema.alterTable('person')\n * .dropIndex('person_email_index')\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` drop index `test_first_name_index`\n * ```\n */\n dropIndex(indexName) {\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropIndex: DropIndexNode.create(indexName),\n }),\n });\n }\n /**\n * Calls the given function passing `this` as the only argument.\n *\n * See {@link CreateTableBuilder.$call}\n */\n $call(func) {\n return func(this);\n }\n}\nexport class AlterTableColumnAlteringBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n alterColumn(column, alteration) {\n const builder = alteration(new AlterColumnBuilder(column));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode()),\n });\n }\n dropColumn(column) {\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column)),\n });\n }\n renameColumn(column, newColumn) {\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn)),\n });\n }\n addColumn(columnName, dataType, build = noop) {\n const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode())),\n });\n }\n modifyColumn(columnName, dataType, build = noop) {\n const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode())),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { OperationNodeTransformer } from '../../operation-node/operation-node-transformer.js';\nimport { ValueListNode } from '../../operation-node/value-list-node.js';\nimport { ValueNode } from '../../operation-node/value-node.js';\n/**\n * Transforms all ValueNodes to immediate.\n *\n * WARNING! This should never be part of the public API. Users should never use this.\n * This is an internal helper.\n *\n * @internal\n */\nexport class ImmediateValueTransformer extends OperationNodeTransformer {\n transformPrimitiveValueList(node) {\n return ValueListNode.create(node.values.map(ValueNode.createImmediate));\n }\n transformValue(node) {\n return ValueNode.createImmediate(node.value);\n }\n}\n", "/// \nimport { CreateIndexNode, } from '../operation-node/create-index-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseOrderedColumnName, } from '../parser/reference-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { freeze } from '../util/object-utils.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { ImmediateValueTransformer } from '../plugin/immediate-value/immediate-value-transformer.js';\nexport class CreateIndexBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds the \"if not exists\" modifier.\n *\n * If the index already exists, no error is thrown if this method has been called.\n */\n ifNotExists() {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n ifNotExists: true,\n }),\n });\n }\n /**\n * Makes the index unique.\n */\n unique() {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n unique: true,\n }),\n });\n }\n /**\n * Adds `nulls not distinct` specifier to index.\n * This only works on some dialects like PostgreSQL.\n *\n * ### Examples\n *\n * ```ts\n * db.schema.createIndex('person_first_name_index')\n * .on('person')\n * .column('first_name')\n * .nullsNotDistinct()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create index \"person_first_name_index\"\n * on \"test\" (\"first_name\")\n * nulls not distinct;\n * ```\n */\n nullsNotDistinct() {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n nullsNotDistinct: true,\n }),\n });\n }\n /**\n * Specifies the table for the index.\n */\n on(table) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n table: parseTable(table),\n }),\n });\n }\n /**\n * Adds a column to the index.\n *\n * Also see {@link columns} for adding multiple columns at once or {@link expression}\n * for specifying an arbitrary expression.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createIndex('person_first_name_and_age_index')\n * .on('person')\n * .column('first_name')\n * .column('age desc')\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create index \"person_first_name_and_age_index\" on \"person\" (\"first_name\", \"age\" desc)\n * ```\n */\n column(column) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWithColumns(this.#props.node, [\n parseOrderedColumnName(column),\n ]),\n });\n }\n /**\n * Specifies a list of columns for the index.\n *\n * Also see {@link column} for adding a single column or {@link expression} for\n * specifying an arbitrary expression.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createIndex('person_first_name_and_age_index')\n * .on('person')\n * .columns(['first_name', 'age desc'])\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create index \"person_first_name_and_age_index\" on \"person\" (\"first_name\", \"age\" desc)\n * ```\n */\n columns(columns) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWithColumns(this.#props.node, columns.map(parseOrderedColumnName)),\n });\n }\n /**\n * Specifies an arbitrary expression for the index.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createIndex('person_first_name_index')\n * .on('person')\n * .expression(sql`first_name COLLATE \"fi_FI\"`)\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create index \"person_first_name_index\" on \"person\" (first_name COLLATE \"fi_FI\")\n * ```\n */\n expression(expression) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWithColumns(this.#props.node, [\n expression.toOperationNode(),\n ]),\n });\n }\n using(indexType) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n using: RawNode.createWithSql(indexType),\n }),\n });\n }\n where(...args) {\n const transformer = new ImmediateValueTransformer();\n return new CreateIndexBuilder({\n ...this.#props,\n node: QueryNode.cloneWithWhere(this.#props.node, transformer.transformNode(parseValueBinaryOperationOrExpression(args), this.#props.queryId)),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { CreateSchemaNode } from '../operation-node/create-schema-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class CreateSchemaBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifNotExists() {\n return new CreateSchemaBuilder({\n ...this.#props,\n node: CreateSchemaNode.cloneWith(this.#props.node, { ifNotExists: true }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { ON_COMMIT_ACTIONS, } from '../operation-node/create-table-node.js';\nexport function parseOnCommitAction(action) {\n if (ON_COMMIT_ACTIONS.includes(action)) {\n return action;\n }\n throw new Error(`invalid OnCommitAction ${action}`);\n}\n", "/// \nimport { ColumnDefinitionNode } from '../operation-node/column-definition-node.js';\nimport { CreateTableNode, } from '../operation-node/create-table-node.js';\nimport { ColumnDefinitionBuilder } from './column-definition-builder.js';\nimport { freeze, noop } from '../util/object-utils.js';\nimport { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ForeignKeyConstraintBuilder, } from './foreign-key-constraint-builder.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { PrimaryKeyConstraintNode } from '../operation-node/primary-key-constraint-node.js';\nimport { UniqueConstraintNode } from '../operation-node/unique-constraint-node.js';\nimport { CheckConstraintNode } from '../operation-node/check-constraint-node.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseOnCommitAction } from '../parser/on-commit-action-parse.js';\nimport { UniqueConstraintNodeBuilder, } from './unique-constraint-builder.js';\nimport { parseExpression } from '../parser/expression-parser.js';\nimport { PrimaryKeyConstraintBuilder, } from './primary-key-constraint-builder.js';\nimport { CheckConstraintBuilder, } from './check-constraint-builder.js';\n/**\n * This builder can be used to create a `create table` query.\n */\nexport class CreateTableBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds the \"temporary\" modifier.\n *\n * Use this to create a temporary table.\n */\n temporary() {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWith(this.#props.node, {\n temporary: true,\n }),\n });\n }\n /**\n * Adds an \"on commit\" statement.\n *\n * This can be used in conjunction with temporary tables on supported databases\n * like PostgreSQL.\n */\n onCommit(onCommit) {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWith(this.#props.node, {\n onCommit: parseOnCommitAction(onCommit),\n }),\n });\n }\n /**\n * Adds the \"if not exists\" modifier.\n *\n * If the table already exists, no error is thrown if this method has been called.\n */\n ifNotExists() {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWith(this.#props.node, {\n ifNotExists: true,\n }),\n });\n }\n /**\n * Adds a column to the table.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', (col) => col.autoIncrement().primaryKey())\n * .addColumn('first_name', 'varchar(50)', (col) => col.notNull())\n * .addColumn('last_name', 'varchar(255)')\n * .addColumn('bank_balance', 'numeric(8, 2)')\n * // You can specify any data type using the `sql` tag if the types\n * // don't include it.\n * .addColumn('data', sql`any_type_here`)\n * .addColumn('parent_id', 'integer', (col) =>\n * col.references('person.id').onDelete('cascade')\n * )\n * ```\n *\n * With this method, it's once again good to remember that Kysely just builds the\n * query and doesn't provide the same API for all databases. For example, some\n * databases like older MySQL don't support the `references` statement in the\n * column definition. Instead foreign key constraints need to be defined in the\n * `create table` query. See the next example:\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', (col) => col.primaryKey())\n * .addColumn('parent_id', 'integer')\n * .addForeignKeyConstraint(\n * 'person_parent_id_fk',\n * ['parent_id'],\n * 'person',\n * ['id'],\n * (cb) => cb.onDelete('cascade')\n * )\n * .execute()\n * ```\n *\n * Another good example is that PostgreSQL doesn't support the `auto_increment`\n * keyword and you need to define an autoincrementing column for example using\n * `serial`:\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'serial', (col) => col.primaryKey())\n * .execute()\n * ```\n */\n addColumn(columnName, dataType, build = noop) {\n const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithColumn(this.#props.node, columnBuilder.toOperationNode()),\n });\n }\n /**\n * Adds a primary key constraint for one or more columns.\n *\n * The constraint name can be anything you want, but it must be unique\n * across the whole database.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('first_name', 'varchar(64)')\n * .addColumn('last_name', 'varchar(64)')\n * .addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name'])\n * .execute()\n * ```\n */\n addPrimaryKeyConstraint(constraintName, columns, build = noop) {\n const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName)));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode()),\n });\n }\n /**\n * Adds a unique constraint for one or more columns.\n *\n * The constraint name can be anything you want, but it must be unique\n * across the whole database.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('first_name', 'varchar(64)')\n * .addColumn('last_name', 'varchar(64)')\n * .addUniqueConstraint(\n * 'first_name_last_name_unique',\n * ['first_name', 'last_name']\n * )\n * .execute()\n * ```\n *\n * In dialects such as PostgreSQL you can specify `nulls not distinct` as follows:\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('first_name', 'varchar(64)')\n * .addColumn('last_name', 'varchar(64)')\n * .addUniqueConstraint(\n * 'first_name_last_name_unique',\n * ['first_name', 'last_name'],\n * (cb) => cb.nullsNotDistinct()\n * )\n * .execute()\n * ```\n */\n addUniqueConstraint(constraintName, columns, build = noop) {\n const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName)));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithConstraint(this.#props.node, uniqueConstraintBuilder.toOperationNode()),\n });\n }\n /**\n * Adds a check constraint.\n *\n * The constraint name can be anything you want, but it must be unique\n * across the whole database.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('animal')\n * .addColumn('number_of_legs', 'integer')\n * .addCheckConstraint('check_legs', sql`number_of_legs < 5`)\n * .execute()\n * ```\n */\n addCheckConstraint(constraintName, checkExpression, build = noop) {\n const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName)));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode()),\n });\n }\n /**\n * Adds a foreign key constraint.\n *\n * The constraint name can be anything you want, but it must be unique\n * across the whole database.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('owner_id', 'integer')\n * .addForeignKeyConstraint(\n * 'owner_id_foreign',\n * ['owner_id'],\n * 'person',\n * ['id'],\n * )\n * .execute()\n * ```\n *\n * Add constraint for multiple columns:\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('owner_id1', 'integer')\n * .addColumn('owner_id2', 'integer')\n * .addForeignKeyConstraint(\n * 'owner_id_foreign',\n * ['owner_id1', 'owner_id2'],\n * 'person',\n * ['id1', 'id2'],\n * (cb) => cb.onDelete('cascade')\n * )\n * .execute()\n * ```\n */\n addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) {\n const builder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName)));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithConstraint(this.#props.node, builder.toOperationNode()),\n });\n }\n /**\n * This can be used to add any additional SQL to the front of the query __after__ the `create` keyword.\n *\n * Also see {@link temporary}.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .modifyFront(sql`global temporary`)\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn('first_name', 'varchar(64)', col => col.notNull())\n * .addColumn('last_name', 'varchar(64)', col => col.notNull())\n * .execute()\n * ```\n *\n * The generated SQL (Postgres):\n *\n * ```sql\n * create global temporary table \"person\" (\n * \"id\" integer primary key,\n * \"first_name\" varchar(64) not null,\n * \"last_name\" varchar(64) not null\n * )\n * ```\n */\n modifyFront(modifier) {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithFrontModifier(this.#props.node, modifier.toOperationNode()),\n });\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * Also see {@link onCommit}.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn('first_name', 'varchar(64)', col => col.notNull())\n * .addColumn('last_name', 'varchar(64)', col => col.notNull())\n * .modifyEnd(sql`collate utf8_unicode_ci`)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key,\n * `first_name` varchar(64) not null,\n * `last_name` varchar(64) not null\n * ) collate utf8_unicode_ci\n * ```\n */\n modifyEnd(modifier) {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithEndModifier(this.#props.node, modifier.toOperationNode()),\n });\n }\n /**\n * Allows to create table from `select` query.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('copy')\n * .temporary()\n * .as(db.selectFrom('person').select(['first_name', 'last_name']))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create temporary table \"copy\" as\n * select \"first_name\", \"last_name\" from \"person\"\n * ```\n */\n as(expression) {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWith(this.#props.node, {\n selectQuery: parseExpression(expression),\n }),\n });\n }\n /**\n * Calls the given function passing `this` as the only argument.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('test')\n * .$call((builder) => builder.addColumn('id', 'integer'))\n * .execute()\n * ```\n *\n * This is useful for creating reusable functions that can be called with a builder.\n *\n * ```ts\n * import { type CreateTableBuilder, sql } from 'kysely'\n *\n * const addDefaultColumns = (ctb: CreateTableBuilder) => {\n * return ctb\n * .addColumn('id', 'integer', (col) => col.notNull())\n * .addColumn('created_at', 'date', (col) =>\n * col.notNull().defaultTo(sql`now()`)\n * )\n * .addColumn('updated_at', 'date', (col) =>\n * col.notNull().defaultTo(sql`now()`)\n * )\n * }\n *\n * await db.schema\n * .createTable('test')\n * .$call(addDefaultColumns)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { DropIndexNode } from '../operation-node/drop-index-node.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class DropIndexBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Specifies the table the index was created for. This is not needed\n * in all dialects.\n */\n on(table) {\n return new DropIndexBuilder({\n ...this.#props,\n node: DropIndexNode.cloneWith(this.#props.node, {\n table: parseTable(table),\n }),\n });\n }\n ifExists() {\n return new DropIndexBuilder({\n ...this.#props,\n node: DropIndexNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n cascade() {\n return new DropIndexBuilder({\n ...this.#props,\n node: DropIndexNode.cloneWith(this.#props.node, {\n cascade: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { DropSchemaNode } from '../operation-node/drop-schema-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class DropSchemaBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifExists() {\n return new DropSchemaBuilder({\n ...this.#props,\n node: DropSchemaNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n cascade() {\n return new DropSchemaBuilder({\n ...this.#props,\n node: DropSchemaNode.cloneWith(this.#props.node, {\n cascade: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { DropTableNode } from '../operation-node/drop-table-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class DropTableBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifExists() {\n return new DropTableBuilder({\n ...this.#props,\n node: DropTableNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n cascade() {\n return new DropTableBuilder({\n ...this.#props,\n node: DropTableNode.cloneWith(this.#props.node, {\n cascade: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const CreateViewNode = freeze({\n is(node) {\n return node.kind === 'CreateViewNode';\n },\n create(name) {\n return freeze({\n kind: 'CreateViewNode',\n name: SchemableIdentifierNode.create(name),\n });\n },\n cloneWith(createView, params) {\n return freeze({\n ...createView,\n ...params,\n });\n },\n});\n", "/// \nimport { ImmediateValueTransformer } from './immediate-value-transformer.js';\n/**\n * Transforms all ValueNodes to immediate.\n *\n * WARNING! This should never be part of the public API. Users should never use this.\n * This is an internal helper.\n *\n * @internal\n */\nexport class ImmediateValuePlugin {\n #transformer = new ImmediateValueTransformer();\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n transformResult(args) {\n return Promise.resolve(args.result);\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { CreateViewNode } from '../operation-node/create-view-node.js';\nimport { parseColumnName } from '../parser/reference-parser.js';\nimport { ImmediateValuePlugin } from '../plugin/immediate-value/immediate-value-plugin.js';\nexport class CreateViewBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds the \"temporary\" modifier.\n *\n * Use this to create a temporary view.\n */\n temporary() {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n temporary: true,\n }),\n });\n }\n materialized() {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n materialized: true,\n }),\n });\n }\n /**\n * Only implemented on some dialects like SQLite. On most dialects, use {@link orReplace}.\n */\n ifNotExists() {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n ifNotExists: true,\n }),\n });\n }\n orReplace() {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n orReplace: true,\n }),\n });\n }\n columns(columns) {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n columns: columns.map(parseColumnName),\n }),\n });\n }\n /**\n * Sets the select query or a `values` statement that creates the view.\n *\n * WARNING!\n * Some dialects don't support parameterized queries in DDL statements and therefore\n * the query or raw {@link sql } expression passed here is interpolated into a single\n * string opening an SQL injection vulnerability. DO NOT pass unchecked user input\n * into the query or raw expression passed to this method!\n */\n as(query) {\n const queryNode = query\n .withPlugin(new ImmediateValuePlugin())\n .toOperationNode();\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n as: queryNode,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const DropViewNode = freeze({\n is(node) {\n return node.kind === 'DropViewNode';\n },\n create(name) {\n return freeze({\n kind: 'DropViewNode',\n name: SchemableIdentifierNode.create(name),\n });\n },\n cloneWith(dropView, params) {\n return freeze({\n ...dropView,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { DropViewNode } from '../operation-node/drop-view-node.js';\nexport class DropViewBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n materialized() {\n return new DropViewBuilder({\n ...this.#props,\n node: DropViewNode.cloneWith(this.#props.node, {\n materialized: true,\n }),\n });\n }\n ifExists() {\n return new DropViewBuilder({\n ...this.#props,\n node: DropViewNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n cascade() {\n return new DropViewBuilder({\n ...this.#props,\n node: DropViewNode.cloneWith(this.#props.node, {\n cascade: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ValueListNode } from './value-list-node.js';\nimport { ValueNode } from './value-node.js';\n/**\n * @internal\n */\nexport const CreateTypeNode = freeze({\n is(node) {\n return node.kind === 'CreateTypeNode';\n },\n create(name) {\n return freeze({\n kind: 'CreateTypeNode',\n name,\n });\n },\n cloneWithEnum(createType, values) {\n return freeze({\n ...createType,\n enum: ValueListNode.create(values.map(ValueNode.createImmediate)),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { CreateTypeNode } from '../operation-node/create-type-node.js';\nexport class CreateTypeBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n /**\n * Creates an anum type.\n *\n * ### Examples\n *\n * ```ts\n * db.schema.createType('species').asEnum(['cat', 'dog', 'frog'])\n * ```\n */\n asEnum(values) {\n return new CreateTypeBuilder({\n ...this.#props,\n node: CreateTypeNode.cloneWithEnum(this.#props.node, values),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const DropTypeNode = freeze({\n is(node) {\n return node.kind === 'DropTypeNode';\n },\n create(name) {\n return freeze({\n kind: 'DropTypeNode',\n name,\n });\n },\n cloneWith(dropType, params) {\n return freeze({\n ...dropType,\n ...params,\n });\n },\n});\n", "/// \nimport { DropTypeNode } from '../operation-node/drop-type-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class DropTypeBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifExists() {\n return new DropTypeBuilder({\n ...this.#props,\n node: DropTypeNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { SchemableIdentifierNode } from '../operation-node/schemable-identifier-node.js';\nexport function parseSchemableIdentifier(id) {\n const SCHEMA_SEPARATOR = '.';\n if (id.includes(SCHEMA_SEPARATOR)) {\n const parts = id.split(SCHEMA_SEPARATOR).map(trim);\n if (parts.length === 2) {\n return SchemableIdentifierNode.createWithSchema(parts[0], parts[1]);\n }\n else {\n throw new Error(`invalid schemable identifier ${id}`);\n }\n }\n else {\n return SchemableIdentifierNode.create(id);\n }\n}\nfunction trim(str) {\n return str.trim();\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const RefreshMaterializedViewNode = freeze({\n is(node) {\n return node.kind === 'RefreshMaterializedViewNode';\n },\n create(name) {\n return freeze({\n kind: 'RefreshMaterializedViewNode',\n name: SchemableIdentifierNode.create(name),\n });\n },\n cloneWith(createView, params) {\n return freeze({\n ...createView,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { RefreshMaterializedViewNode } from '../operation-node/refresh-materialized-view-node.js';\nexport class RefreshMaterializedViewBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds the \"concurrently\" modifier.\n *\n * Use this to refresh the view without locking out concurrent selects on the materialized view.\n *\n * WARNING!\n * This cannot be used with the \"with no data\" modifier.\n */\n concurrently() {\n return new RefreshMaterializedViewBuilder({\n ...this.#props,\n node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {\n concurrently: true,\n withNoData: false,\n }),\n });\n }\n /**\n * Adds the \"with data\" modifier.\n *\n * If specified (or defaults) the backing query is executed to provide the new data, and the materialized view is left in a scannable state\n */\n withData() {\n return new RefreshMaterializedViewBuilder({\n ...this.#props,\n node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {\n withNoData: false,\n }),\n });\n }\n /**\n * Adds the \"with no data\" modifier.\n *\n * If specified, no new data is generated and the materialized view is left in an unscannable state.\n *\n * WARNING!\n * This cannot be used with the \"concurrently\" modifier.\n */\n withNoData() {\n return new RefreshMaterializedViewBuilder({\n ...this.#props,\n node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {\n withNoData: true,\n concurrently: false,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { CreateIndexNode } from '../operation-node/create-index-node.js';\nimport { CreateSchemaNode } from '../operation-node/create-schema-node.js';\nimport { CreateTableNode } from '../operation-node/create-table-node.js';\nimport { DropIndexNode } from '../operation-node/drop-index-node.js';\nimport { DropSchemaNode } from '../operation-node/drop-schema-node.js';\nimport { DropTableNode } from '../operation-node/drop-table-node.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { AlterTableBuilder } from './alter-table-builder.js';\nimport { CreateIndexBuilder } from './create-index-builder.js';\nimport { CreateSchemaBuilder } from './create-schema-builder.js';\nimport { CreateTableBuilder } from './create-table-builder.js';\nimport { DropIndexBuilder } from './drop-index-builder.js';\nimport { DropSchemaBuilder } from './drop-schema-builder.js';\nimport { DropTableBuilder } from './drop-table-builder.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { CreateViewBuilder } from './create-view-builder.js';\nimport { CreateViewNode } from '../operation-node/create-view-node.js';\nimport { DropViewBuilder } from './drop-view-builder.js';\nimport { DropViewNode } from '../operation-node/drop-view-node.js';\nimport { CreateTypeBuilder } from './create-type-builder.js';\nimport { DropTypeBuilder } from './drop-type-builder.js';\nimport { CreateTypeNode } from '../operation-node/create-type-node.js';\nimport { DropTypeNode } from '../operation-node/drop-type-node.js';\nimport { parseSchemableIdentifier } from '../parser/identifier-parser.js';\nimport { RefreshMaterializedViewBuilder } from './refresh-materialized-view-builder.js';\nimport { RefreshMaterializedViewNode } from '../operation-node/refresh-materialized-view-node.js';\n/**\n * Provides methods for building database schema.\n */\nexport class SchemaModule {\n #executor;\n constructor(executor) {\n this.#executor = executor;\n }\n /**\n * Create a new table.\n *\n * ### Examples\n *\n * This example creates a new table with columns `id`, `first_name`,\n * `last_name` and `gender`:\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())\n * .addColumn('first_name', 'varchar', col => col.notNull())\n * .addColumn('last_name', 'varchar', col => col.notNull())\n * .addColumn('gender', 'varchar')\n * .execute()\n * ```\n *\n * This example creates a table with a foreign key. Not all database\n * engines support column-level foreign key constraint definitions.\n * For example if you are using MySQL 5.X see the next example after\n * this one.\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())\n * .addColumn('owner_id', 'integer', col => col\n * .references('person.id')\n * .onDelete('cascade')\n * )\n * .execute()\n * ```\n *\n * This example adds a foreign key constraint for a columns just\n * like the previous example, but using a table-level statement.\n * On MySQL 5.X you need to define foreign key constraints like\n * this:\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())\n * .addColumn('owner_id', 'integer')\n * .addForeignKeyConstraint(\n * 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'],\n * (constraint) => constraint.onDelete('cascade')\n * )\n * .execute()\n * ```\n */\n createTable(table) {\n return new CreateTableBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateTableNode.create(parseTable(table)),\n });\n }\n /**\n * Drop a table.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropTable('person')\n * .execute()\n * ```\n */\n dropTable(table) {\n return new DropTableBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropTableNode.create(parseTable(table)),\n });\n }\n /**\n * Create a new index.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createIndex('person_full_name_unique_index')\n * .on('person')\n * .columns(['first_name', 'last_name'])\n * .execute()\n * ```\n */\n createIndex(indexName) {\n return new CreateIndexBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateIndexNode.create(indexName),\n });\n }\n /**\n * Drop an index.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropIndex('person_full_name_unique_index')\n * .execute()\n * ```\n */\n dropIndex(indexName) {\n return new DropIndexBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropIndexNode.create(indexName),\n });\n }\n /**\n * Create a new schema.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createSchema('some_schema')\n * .execute()\n * ```\n */\n createSchema(schema) {\n return new CreateSchemaBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateSchemaNode.create(schema),\n });\n }\n /**\n * Drop a schema.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropSchema('some_schema')\n * .execute()\n * ```\n */\n dropSchema(schema) {\n return new DropSchemaBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropSchemaNode.create(schema),\n });\n }\n /**\n * Alter a table.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .alterColumn('first_name', (ac) => ac.setDataType('text'))\n * .execute()\n * ```\n */\n alterTable(table) {\n return new AlterTableBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: AlterTableNode.create(parseTable(table)),\n });\n }\n /**\n * Create a new view.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createView('dogs')\n * .orReplace()\n * .as(db.selectFrom('pet').selectAll().where('species', '=', 'dog'))\n * .execute()\n * ```\n */\n createView(viewName) {\n return new CreateViewBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateViewNode.create(viewName),\n });\n }\n /**\n * Refresh a materialized view.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .refreshMaterializedView('my_view')\n * .concurrently()\n * .execute()\n * ```\n */\n refreshMaterializedView(viewName) {\n return new RefreshMaterializedViewBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: RefreshMaterializedViewNode.create(viewName),\n });\n }\n /**\n * Drop a view.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropView('dogs')\n * .ifExists()\n * .execute()\n * ```\n */\n dropView(viewName) {\n return new DropViewBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropViewNode.create(viewName),\n });\n }\n /**\n * Create a new type.\n *\n * Only some dialects like PostgreSQL have user-defined types.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createType('species')\n * .asEnum(['dog', 'cat', 'frog'])\n * .execute()\n * ```\n */\n createType(typeName) {\n return new CreateTypeBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateTypeNode.create(parseSchemableIdentifier(typeName)),\n });\n }\n /**\n * Drop a type.\n *\n * Only some dialects like PostgreSQL have user-defined types.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropType('species')\n * .ifExists()\n * .execute()\n * ```\n */\n dropType(typeName) {\n return new DropTypeBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropTypeNode.create(parseSchemableIdentifier(typeName)),\n });\n }\n /**\n * Returns a copy of this schema module with the given plugin installed.\n */\n withPlugin(plugin) {\n return new SchemaModule(this.#executor.withPlugin(plugin));\n }\n /**\n * Returns a copy of this schema module without any plugins.\n */\n withoutPlugins() {\n return new SchemaModule(this.#executor.withoutPlugins());\n }\n /**\n * See {@link QueryCreator.withSchema}\n */\n withSchema(schema) {\n return new SchemaModule(this.#executor.withPluginAtFront(new WithSchemaPlugin(schema)));\n }\n}\n", "/// \nimport { DynamicReferenceBuilder } from './dynamic-reference-builder.js';\nimport { DynamicTableBuilder } from './dynamic-table-builder.js';\nexport class DynamicModule {\n /**\n * Creates a dynamic reference to a column that is not know at compile time.\n *\n * Kysely is built in a way that by default you can't refer to tables or columns\n * that are not actually visible in the current query and context. This is all\n * done by TypeScript at compile time, which means that you need to know the\n * columns and tables at compile time. This is not always the case of course.\n *\n * This method is meant to be used in those cases where the column names\n * come from the user input or are not otherwise known at compile time.\n *\n * WARNING! Unlike values, column names are not escaped by the database engine\n * or Kysely and if you pass in unchecked column names using this method, you\n * create an SQL injection vulnerability. Always __always__ validate the user\n * input before passing it to this method.\n *\n * There are couple of examples below for some use cases, but you can pass\n * `ref` to other methods as well. If the types allow you to pass a `ref`\n * value to some place, it should work.\n *\n * ### Examples\n *\n * Filter by a column not know at compile time:\n *\n * ```ts\n * async function someQuery(filterColumn: string, filterValue: string) {\n * const { ref } = db.dynamic\n *\n * return await db\n * .selectFrom('person')\n * .selectAll()\n * .where(ref(filterColumn), '=', filterValue)\n * .execute()\n * }\n *\n * someQuery('first_name', 'Arnold')\n * someQuery('person.last_name', 'Aniston')\n * ```\n *\n * Order by a column not know at compile time:\n *\n * ```ts\n * async function someQuery(orderBy: string) {\n * const { ref } = db.dynamic\n *\n * return await db\n * .selectFrom('person')\n * .select('person.first_name as fn')\n * .orderBy(ref(orderBy))\n * .execute()\n * }\n *\n * someQuery('fn')\n * ```\n *\n * In this example we add selections dynamically:\n *\n * ```ts\n * const { ref } = db.dynamic\n *\n * // Some column name provided by the user. Value not known at compile time.\n * const columnFromUserInput: PossibleColumns = 'birthdate';\n *\n * // A type that lists all possible values `columnFromUserInput` can have.\n * // You can use `keyof Person` if any column of an interface is allowed.\n * type PossibleColumns = 'last_name' | 'first_name' | 'birthdate'\n *\n * const [person] = await db.selectFrom('person')\n * .select([\n * ref(columnFromUserInput),\n * 'id'\n * ])\n * .execute()\n *\n * // The resulting type contains all `PossibleColumns` as optional fields\n * // because we cannot know which field was actually selected before\n * // running the code.\n * const lastName: string | null | undefined = person?.last_name\n * const firstName: string | undefined = person?.first_name\n * const birthDate: Date | null | undefined = person?.birthdate\n *\n * // The result type also contains the compile time selection `id`.\n * person?.id\n * ```\n */\n ref(reference) {\n return new DynamicReferenceBuilder(reference);\n }\n /**\n * Creates a table reference to a table that's not fully known at compile time.\n *\n * The type `T` is allowed to be a union of multiple tables.\n *\n * \n *\n * A generic type-safe helper function for finding a row by a column value:\n *\n * ```ts\n * import { SelectType } from 'kysely'\n * import { Database } from 'type-editor'\n *\n * async function getRowByColumn<\n * T extends keyof Database,\n * C extends keyof Database[T] & string,\n * V extends SelectType,\n * >(t: T, c: C, v: V) {\n * // We need to use the dynamic module since the table name\n * // is not known at compile time.\n * const { table, ref } = db.dynamic\n *\n * return await db\n * .selectFrom(table(t).as('t'))\n * .selectAll()\n * .where(ref(c), '=', v)\n * .orderBy('t.id')\n * .executeTakeFirstOrThrow()\n * }\n *\n * const person = await getRowByColumn('person', 'first_name', 'Arnold')\n * ```\n */\n table(table) {\n return new DynamicTableBuilder(table);\n }\n}\n", "/// \nexport class DefaultConnectionProvider {\n #driver;\n constructor(driver) {\n this.#driver = driver;\n }\n async provideConnection(consumer) {\n const connection = await this.#driver.acquireConnection();\n try {\n return await consumer(connection);\n }\n finally {\n await this.#driver.releaseConnection(connection);\n }\n }\n}\n", "/// \nimport { QueryExecutorBase } from './query-executor-base.js';\nexport class DefaultQueryExecutor extends QueryExecutorBase {\n #compiler;\n #adapter;\n #connectionProvider;\n constructor(compiler, adapter, connectionProvider, plugins = []) {\n super(plugins);\n this.#compiler = compiler;\n this.#adapter = adapter;\n this.#connectionProvider = connectionProvider;\n }\n get adapter() {\n return this.#adapter;\n }\n compileQuery(node, queryId) {\n return this.#compiler.compileQuery(node, queryId);\n }\n provideConnection(consumer) {\n return this.#connectionProvider.provideConnection(consumer);\n }\n withPlugins(plugins) {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, ...plugins]);\n }\n withPlugin(plugin) {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, plugin]);\n }\n withPluginAtFront(plugin) {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [plugin, ...this.plugins]);\n }\n withConnectionProvider(connectionProvider) {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, connectionProvider, [...this.plugins]);\n }\n withoutPlugins() {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, []);\n }\n}\n", "/// \nimport { isFunction } from './object-utils.js';\nexport function performanceNow() {\n if (typeof performance !== 'undefined' && isFunction(performance.now)) {\n return performance.now();\n }\n else {\n return Date.now();\n }\n}\n", "/// \nimport { performanceNow } from '../util/performance-now.js';\n/**\n * A small wrapper around {@link Driver} that makes sure the driver is\n * initialized before it is used, only initialized and destroyed\n * once etc.\n */\nexport class RuntimeDriver {\n #driver;\n #log;\n #initPromise;\n #initDone;\n #destroyPromise;\n #connections = new WeakSet();\n constructor(driver, log) {\n this.#initDone = false;\n this.#driver = driver;\n this.#log = log;\n }\n async init() {\n if (this.#destroyPromise) {\n throw new Error('driver has already been destroyed');\n }\n if (!this.#initPromise) {\n this.#initPromise = this.#driver\n .init()\n .then(() => {\n this.#initDone = true;\n })\n .catch((err) => {\n this.#initPromise = undefined;\n return Promise.reject(err);\n });\n }\n await this.#initPromise;\n }\n async acquireConnection() {\n if (this.#destroyPromise) {\n throw new Error('driver has already been destroyed');\n }\n if (!this.#initDone) {\n await this.init();\n }\n const connection = await this.#driver.acquireConnection();\n if (!this.#connections.has(connection)) {\n if (this.#needsLogging()) {\n this.#addLogging(connection);\n }\n this.#connections.add(connection);\n }\n return connection;\n }\n async releaseConnection(connection) {\n await this.#driver.releaseConnection(connection);\n }\n beginTransaction(connection, settings) {\n return this.#driver.beginTransaction(connection, settings);\n }\n commitTransaction(connection) {\n return this.#driver.commitTransaction(connection);\n }\n rollbackTransaction(connection) {\n return this.#driver.rollbackTransaction(connection);\n }\n savepoint(connection, savepointName, compileQuery) {\n if (this.#driver.savepoint) {\n return this.#driver.savepoint(connection, savepointName, compileQuery);\n }\n throw new Error('The `savepoint` method is not supported by this driver');\n }\n rollbackToSavepoint(connection, savepointName, compileQuery) {\n if (this.#driver.rollbackToSavepoint) {\n return this.#driver.rollbackToSavepoint(connection, savepointName, compileQuery);\n }\n throw new Error('The `rollbackToSavepoint` method is not supported by this driver');\n }\n releaseSavepoint(connection, savepointName, compileQuery) {\n if (this.#driver.releaseSavepoint) {\n return this.#driver.releaseSavepoint(connection, savepointName, compileQuery);\n }\n throw new Error('The `releaseSavepoint` method is not supported by this driver');\n }\n async destroy() {\n if (!this.#initPromise) {\n return;\n }\n await this.#initPromise;\n if (!this.#destroyPromise) {\n this.#destroyPromise = this.#driver.destroy().catch((err) => {\n this.#destroyPromise = undefined;\n return Promise.reject(err);\n });\n }\n await this.#destroyPromise;\n }\n #needsLogging() {\n return (this.#log.isLevelEnabled('query') || this.#log.isLevelEnabled('error'));\n }\n // This method monkey patches the database connection's executeQuery method\n // by adding logging code around it. Monkey patching is not pretty, but it's\n // the best option in this case.\n #addLogging(connection) {\n const executeQuery = connection.executeQuery;\n const streamQuery = connection.streamQuery;\n const dis = this;\n connection.executeQuery = async (compiledQuery) => {\n let caughtError;\n const startTime = performanceNow();\n try {\n return await executeQuery.call(connection, compiledQuery);\n }\n catch (error) {\n caughtError = error;\n await dis.#logError(error, compiledQuery, startTime);\n throw error;\n }\n finally {\n if (!caughtError) {\n await dis.#logQuery(compiledQuery, startTime);\n }\n }\n };\n connection.streamQuery = async function* (compiledQuery, chunkSize) {\n let caughtError;\n const startTime = performanceNow();\n try {\n for await (const result of streamQuery.call(connection, compiledQuery, chunkSize)) {\n yield result;\n }\n }\n catch (error) {\n caughtError = error;\n await dis.#logError(error, compiledQuery, startTime);\n throw error;\n }\n finally {\n if (!caughtError) {\n await dis.#logQuery(compiledQuery, startTime, true);\n }\n }\n };\n }\n async #logError(error, compiledQuery, startTime) {\n await this.#log.error(() => ({\n level: 'error',\n error,\n query: compiledQuery,\n queryDurationMillis: this.#calculateDurationMillis(startTime),\n }));\n }\n async #logQuery(compiledQuery, startTime, isStream = false) {\n await this.#log.query(() => ({\n level: 'query',\n isStream,\n query: compiledQuery,\n queryDurationMillis: this.#calculateDurationMillis(startTime),\n }));\n }\n #calculateDurationMillis(startTime) {\n return performanceNow() - startTime;\n }\n}\n", "/// \nconst ignoreError = () => { };\nexport class SingleConnectionProvider {\n #connection;\n #runningPromise;\n constructor(connection) {\n this.#connection = connection;\n }\n async provideConnection(consumer) {\n while (this.#runningPromise) {\n await this.#runningPromise.catch(ignoreError);\n }\n // `#runningPromise` must be set to undefined before it's\n // resolved or rejected. Otherwise the while loop above\n // will misbehave.\n this.#runningPromise = this.#run(consumer).finally(() => {\n this.#runningPromise = undefined;\n });\n return this.#runningPromise;\n }\n // Run the runner in an async function to make sure it doesn't\n // throw synchronous errors.\n async #run(runner) {\n return await runner(this.#connection);\n }\n}\n", "/// \nexport const TRANSACTION_ACCESS_MODES = ['read only', 'read write'];\nexport const TRANSACTION_ISOLATION_LEVELS = [\n 'read uncommitted',\n 'read committed',\n 'repeatable read',\n 'serializable',\n 'snapshot',\n];\nexport function validateTransactionSettings(settings) {\n if (settings.accessMode &&\n !TRANSACTION_ACCESS_MODES.includes(settings.accessMode)) {\n throw new Error(`invalid transaction access mode ${settings.accessMode}`);\n }\n if (settings.isolationLevel &&\n !TRANSACTION_ISOLATION_LEVELS.includes(settings.isolationLevel)) {\n throw new Error(`invalid transaction isolation level ${settings.isolationLevel}`);\n }\n}\n", "/// \nimport { freeze, isFunction } from './object-utils.js';\nconst logLevels = ['query', 'error'];\nexport const LOG_LEVELS = freeze(logLevels);\nexport class Log {\n #levels;\n #logger;\n constructor(config) {\n if (isFunction(config)) {\n this.#logger = config;\n this.#levels = freeze({\n query: true,\n error: true,\n });\n }\n else {\n this.#logger = defaultLogger;\n this.#levels = freeze({\n query: config.includes('query'),\n error: config.includes('error'),\n });\n }\n }\n isLevelEnabled(level) {\n return this.#levels[level];\n }\n async query(getEvent) {\n if (this.#levels.query) {\n await this.#logger(getEvent());\n }\n }\n async error(getEvent) {\n if (this.#levels.error) {\n await this.#logger(getEvent());\n }\n }\n}\nfunction defaultLogger(event) {\n if (event.level === 'query') {\n const prefix = `kysely:query:${event.isStream ? 'stream:' : ''}`;\n console.log(`${prefix} ${event.query.sql}`);\n console.log(`${prefix} duration: ${event.queryDurationMillis.toFixed(1)}ms`);\n }\n else if (event.level === 'error') {\n if (event.error instanceof Error) {\n console.error(`kysely:error: ${event.error.stack ?? event.error.message}`);\n }\n else {\n console.error(`kysely:error: ${JSON.stringify({\n error: event.error,\n query: event.query.sql,\n queryDurationMillis: event.queryDurationMillis,\n })}`);\n }\n }\n}\n", "/// \nimport { isFunction, isObject } from './object-utils.js';\nexport function isCompilable(value) {\n return isObject(value) && isFunction(value.compile);\n}\n", "/// \nimport { SchemaModule } from './schema/schema.js';\nimport { DynamicModule } from './dynamic/dynamic.js';\nimport { DefaultConnectionProvider } from './driver/default-connection-provider.js';\nimport { QueryCreator } from './query-creator.js';\nimport { DefaultQueryExecutor } from './query-executor/default-query-executor.js';\nimport { freeze, isObject, isUndefined } from './util/object-utils.js';\nimport { RuntimeDriver } from './driver/runtime-driver.js';\nimport { SingleConnectionProvider } from './driver/single-connection-provider.js';\nimport { validateTransactionSettings, } from './driver/driver.js';\nimport { createFunctionModule, } from './query-builder/function-module.js';\nimport { Log } from './util/log.js';\nimport { createQueryId } from './util/query-id.js';\nimport { isCompilable } from './util/compilable.js';\nimport { CaseBuilder } from './query-builder/case-builder.js';\nimport { CaseNode } from './operation-node/case-node.js';\nimport { parseExpression } from './parser/expression-parser.js';\nimport { WithSchemaPlugin } from './plugin/with-schema/with-schema-plugin.js';\nimport { provideControlledConnection, } from './util/provide-controlled-connection.js';\nimport { logOnce } from './util/log-once.js';\n// @ts-ignore\nSymbol.asyncDispose ??= Symbol('Symbol.asyncDispose');\n/**\n * The main Kysely class.\n *\n * You should create one instance of `Kysely` per database using the {@link Kysely}\n * constructor. Each `Kysely` instance maintains its own connection pool.\n *\n * ### Examples\n *\n * This example assumes your database has a \"person\" table:\n *\n * ```ts\n * import * as Sqlite from 'better-sqlite3'\n * import {\u00A0type Generated, Kysely, SqliteDialect } from 'kysely'\n *\n * interface Database {\n * person: {\n * id: Generated\n * first_name: string\n * last_name: string | null\n * }\n * }\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * })\n * })\n * ```\n *\n * @typeParam DB - The database interface type. Keys of this type must be table names\n * in the database and values must be interfaces that describe the rows in those\n * tables. See the examples above.\n */\nexport class Kysely extends QueryCreator {\n #props;\n constructor(args) {\n let superProps;\n let props;\n if (isKyselyProps(args)) {\n superProps = { executor: args.executor };\n props = { ...args };\n }\n else {\n const dialect = args.dialect;\n const driver = dialect.createDriver();\n const compiler = dialect.createQueryCompiler();\n const adapter = dialect.createAdapter();\n const log = new Log(args.log ?? []);\n const runtimeDriver = new RuntimeDriver(driver, log);\n const connectionProvider = new DefaultConnectionProvider(runtimeDriver);\n const executor = new DefaultQueryExecutor(compiler, adapter, connectionProvider, args.plugins ?? []);\n superProps = { executor };\n props = {\n config: args,\n executor,\n dialect,\n driver: runtimeDriver,\n };\n }\n super(superProps);\n this.#props = freeze(props);\n }\n /**\n * Returns the {@link SchemaModule} module for building database schema.\n */\n get schema() {\n return new SchemaModule(this.#props.executor);\n }\n /**\n * Returns a the {@link DynamicModule} module.\n *\n * The {@link DynamicModule} module can be used to bypass strict typing and\n * passing in dynamic values for the queries.\n */\n get dynamic() {\n return new DynamicModule();\n }\n /**\n * Returns a {@link DatabaseIntrospector | database introspector}.\n */\n get introspection() {\n return this.#props.dialect.createIntrospector(this.withoutPlugins());\n }\n case(value) {\n return new CaseBuilder({\n node: CaseNode.create(isUndefined(value) ? undefined : parseExpression(value)),\n });\n }\n /**\n * Returns a {@link FunctionModule} that can be used to write somewhat type-safe function\n * calls.\n *\n * ```ts\n * const { count } = db.fn\n *\n * await db.selectFrom('person')\n * .innerJoin('pet', 'pet.owner_id', 'person.id')\n * .select([\n * 'id',\n * count('pet.id').as('person_count'),\n * ])\n * .groupBy('person.id')\n * .having(count('pet.id'), '>', 10)\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"person\".\"id\", count(\"pet\".\"id\") as \"person_count\"\n * from \"person\"\n * inner join \"pet\" on \"pet\".\"owner_id\" = \"person\".\"id\"\n * group by \"person\".\"id\"\n * having count(\"pet\".\"id\") > $1\n * ```\n *\n * Why \"somewhat\" type-safe? Because the function calls are not bound to the\n * current query context. They allow you to reference columns and tables that\n * are not in the current query. E.g. remove the `innerJoin` from the previous\n * query and TypeScript won't even complain.\n *\n * If you want to make the function calls fully type-safe, you can use the\n * {@link ExpressionBuilder.fn} getter for a query context-aware, stricter {@link FunctionModule}.\n *\n * ```ts\n * await db.selectFrom('person')\n * .innerJoin('pet', 'pet.owner_id', 'person.id')\n * .select((eb) => [\n * 'person.id',\n * eb.fn.count('pet.id').as('pet_count')\n * ])\n * .groupBy('person.id')\n * .having((eb) => eb.fn.count('pet.id'), '>', 10)\n * .execute()\n * ```\n */\n get fn() {\n return createFunctionModule();\n }\n /**\n * Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction.\n *\n * The returned {@link TransactionBuilder} can be used to configure the transaction. The\n * {@link TransactionBuilder.execute} method can then be called to run the transaction.\n * {@link TransactionBuilder.execute} takes a function that is run inside the\n * transaction. If the function throws an exception,\n * 1. the exception is caught,\n * 2. the transaction is rolled back, and\n * 3. the exception is thrown again.\n * Otherwise the transaction is committed.\n *\n * The callback function passed to the {@link TransactionBuilder.execute | execute}\n * method gets the transaction object as its only argument. The transaction is\n * of type {@link Transaction} which inherits {@link Kysely}. Any query\n * started through the transaction object is executed inside the transaction.\n *\n * To run a controlled transaction, allowing you to commit and rollback manually,\n * use {@link startTransaction} instead.\n *\n * ### Examples\n *\n * \n *\n * This example inserts two rows in a transaction. If an exception is thrown inside\n * the callback passed to the `execute` method,\n * 1. the exception is caught,\n * 2. the transaction is rolled back, and\n * 3. the exception is thrown again.\n * Otherwise the transaction is committed.\n *\n * ```ts\n * const catto = await db.transaction().execute(async (trx) => {\n * const jennifer = await trx.insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n *\n * return await trx.insertInto('pet')\n * .values({\n * owner_id: jennifer.id,\n * name: 'Catto',\n * species: 'cat',\n * is_favorite: false,\n * })\n * .returningAll()\n * .executeTakeFirst()\n * })\n * ```\n *\n * Setting the isolation level:\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n *\n * await db\n * .transaction()\n * .setIsolationLevel('serializable')\n * .execute(async (trx) => {\n * await doStuff(trx)\n * })\n *\n * async function doStuff(kysely: typeof db) {\n * // ...\n * }\n * ```\n */\n transaction() {\n return new TransactionBuilder({ ...this.#props });\n }\n /**\n * Creates a {@link ControlledTransactionBuilder} that can be used to run queries inside a controlled transaction.\n *\n * The returned {@link ControlledTransactionBuilder} can be used to configure the transaction.\n * The {@link ControlledTransactionBuilder.execute} method can then be called\n * to start the transaction and return a {@link ControlledTransaction}.\n *\n * A {@link ControlledTransaction} allows you to commit and rollback manually,\n * execute savepoint commands. It extends {@link Transaction} which extends {@link Kysely},\n * so you can run queries inside the transaction. Once the transaction is committed,\n * or rolled back, it can't be used anymore - all queries will throw an error.\n * This is to prevent accidentally running queries outside the transaction - where\n * atomicity is not guaranteed anymore.\n *\n * ### Examples\n *\n * \n *\n * A controlled transaction allows you to commit and rollback manually, execute\n * savepoint commands, and queries in general.\n *\n * In this example we start a transaction, use it to insert two rows and then commit\n * the transaction. If an error is thrown, we catch it and rollback the transaction.\n *\n * ```ts\n * const trx = await db.startTransaction().execute()\n *\n * try {\n * const jennifer = await trx.insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n *\n * const catto = await trx.insertInto('pet')\n * .values({\n * owner_id: jennifer.id,\n * name: 'Catto',\n * species: 'cat',\n * is_favorite: false,\n * })\n * .returningAll()\n * .executeTakeFirstOrThrow()\n *\n * await trx.commit().execute()\n *\n * // ...\n * } catch (error) {\n * await trx.rollback().execute()\n * }\n * ```\n *\n * \n *\n * A controlled transaction allows you to commit and rollback manually, execute\n * savepoint commands, and queries in general.\n *\n * In this example we start a transaction, insert a person, create a savepoint,\n * try inserting a toy and a pet, and if an error is thrown, we rollback to the\n * savepoint. Eventually we release the savepoint, insert an audit record and\n * commit the transaction. If an error is thrown, we catch it and rollback the\n * transaction.\n *\n * ```ts\n * const trx = await db.startTransaction().execute()\n *\n * try {\n * const jennifer = await trx\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n *\n * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()\n *\n * try {\n * const catto = await trxAfterJennifer\n * .insertInto('pet')\n * .values({\n * owner_id: jennifer.id,\n * name: 'Catto',\n * species: 'cat',\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n *\n * await trxAfterJennifer\n * .insertInto('toy')\n * .values({ name: 'Bone', price: 1.99, pet_id: catto.id })\n * .execute()\n * } catch (error) {\n * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()\n * }\n *\n * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute()\n *\n * await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute()\n *\n * await trx.commit().execute()\n * } catch (error) {\n * await trx.rollback().execute()\n * }\n * ```\n */\n startTransaction() {\n return new ControlledTransactionBuilder({ ...this.#props });\n }\n /**\n * Provides a kysely instance bound to a single database connection.\n *\n * ### Examples\n *\n * ```ts\n * await db\n * .connection()\n * .execute(async (db) => {\n * // `db` is an instance of `Kysely` that's bound to a single\n * // database connection. All queries executed through `db` use\n * // the same connection.\n * await doStuff(db)\n * })\n *\n * async function doStuff(kysely: typeof db) {\n * // ...\n * }\n * ```\n */\n connection() {\n return new ConnectionBuilder({ ...this.#props });\n }\n /**\n * Returns a copy of this Kysely instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new Kysely({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n /**\n * Returns a copy of this Kysely instance without any plugins.\n */\n withoutPlugins() {\n return new Kysely({\n ...this.#props,\n executor: this.#props.executor.withoutPlugins(),\n });\n }\n /**\n * @override\n */\n withSchema(schema) {\n return new Kysely({\n ...this.#props,\n executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema)),\n });\n }\n /**\n * Returns a copy of this Kysely instance with tables added to its\n * database type.\n *\n * This method only modifies the types and doesn't affect any of the\n * executed queries in any way.\n *\n * ### Examples\n *\n * The following example adds and uses a temporary table:\n *\n * ```ts\n * await db.schema\n * .createTable('temp_table')\n * .temporary()\n * .addColumn('some_column', 'integer')\n * .execute()\n *\n * const tempDb = db.withTables<{\n * temp_table: {\n * some_column: number\n * }\n * }>()\n *\n * await tempDb\n * .insertInto('temp_table')\n * .values({ some_column: 100 })\n * .execute()\n * ```\n */\n withTables() {\n return new Kysely({ ...this.#props });\n }\n /**\n * Releases all resources and disconnects from the database.\n *\n * You need to call this when you are done using the `Kysely` instance.\n */\n async destroy() {\n await this.#props.driver.destroy();\n }\n /**\n * Returns true if this `Kysely` instance is a transaction.\n *\n * You can also use `db instanceof Transaction`.\n */\n get isTransaction() {\n return false;\n }\n /**\n * @internal\n * @private\n */\n getExecutor() {\n return this.#props.executor;\n }\n /**\n * Executes a given compiled query or query builder.\n *\n * See {@link https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0004-splitting-query-building-and-execution.md#execute-compiled-queries splitting build, compile and execute code recipe} for more information.\n */\n executeQuery(query, \n // TODO: remove this in the future. deprecated in 0.28.x\n queryId) {\n if (queryId !== undefined) {\n logOnce('Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.');\n }\n const compiledQuery = isCompilable(query) ? query.compile() : query;\n return this.getExecutor().executeQuery(compiledQuery);\n }\n async [Symbol.asyncDispose]() {\n await this.destroy();\n }\n}\nexport class Transaction extends Kysely {\n #props;\n constructor(props) {\n super(props);\n this.#props = props;\n }\n // The return type is `true` instead of `boolean` to make Kysely\n // unassignable to Transaction while allowing assignment the\n // other way around.\n get isTransaction() {\n return true;\n }\n transaction() {\n throw new Error('calling the transaction method for a Transaction is not supported');\n }\n connection() {\n throw new Error('calling the connection method for a Transaction is not supported');\n }\n async destroy() {\n throw new Error('calling the destroy method for a Transaction is not supported');\n }\n withPlugin(plugin) {\n return new Transaction({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n withoutPlugins() {\n return new Transaction({\n ...this.#props,\n executor: this.#props.executor.withoutPlugins(),\n });\n }\n withSchema(schema) {\n return new Transaction({\n ...this.#props,\n executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema)),\n });\n }\n withTables() {\n return new Transaction({ ...this.#props });\n }\n}\nexport function isKyselyProps(obj) {\n return (isObject(obj) &&\n isObject(obj.config) &&\n isObject(obj.driver) &&\n isObject(obj.executor) &&\n isObject(obj.dialect));\n}\nexport class ConnectionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n async execute(callback) {\n return this.#props.executor.provideConnection(async (connection) => {\n const executor = this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection));\n const db = new Kysely({\n ...this.#props,\n executor,\n });\n return await callback(db);\n });\n }\n}\nexport class TransactionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n setAccessMode(accessMode) {\n return new TransactionBuilder({\n ...this.#props,\n accessMode,\n });\n }\n setIsolationLevel(isolationLevel) {\n return new TransactionBuilder({\n ...this.#props,\n isolationLevel,\n });\n }\n async execute(callback) {\n const { isolationLevel, accessMode, ...kyselyProps } = this.#props;\n const settings = { isolationLevel, accessMode };\n validateTransactionSettings(settings);\n return this.#props.executor.provideConnection(async (connection) => {\n const state = { isCommitted: false, isRolledBack: false };\n const executor = new NotCommittedOrRolledBackAssertingExecutor(this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection)), state);\n const transaction = new Transaction({\n ...kyselyProps,\n executor,\n });\n let transactionBegun = false;\n try {\n await this.#props.driver.beginTransaction(connection, settings);\n transactionBegun = true;\n const result = await callback(transaction);\n await this.#props.driver.commitTransaction(connection);\n state.isCommitted = true;\n return result;\n }\n catch (error) {\n if (transactionBegun) {\n await this.#props.driver.rollbackTransaction(connection);\n state.isRolledBack = true;\n }\n throw error;\n }\n });\n }\n}\nexport class ControlledTransactionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n setAccessMode(accessMode) {\n return new ControlledTransactionBuilder({\n ...this.#props,\n accessMode,\n });\n }\n setIsolationLevel(isolationLevel) {\n return new ControlledTransactionBuilder({\n ...this.#props,\n isolationLevel,\n });\n }\n async execute() {\n const { isolationLevel, accessMode, ...props } = this.#props;\n const settings = { isolationLevel, accessMode };\n validateTransactionSettings(settings);\n const connection = await provideControlledConnection(this.#props.executor);\n await this.#props.driver.beginTransaction(connection.connection, settings);\n return new ControlledTransaction({\n ...props,\n connection,\n executor: this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection.connection)),\n });\n }\n}\nexport class ControlledTransaction extends Transaction {\n #props;\n #compileQuery;\n #state;\n constructor(props) {\n const state = { isCommitted: false, isRolledBack: false };\n props = {\n ...props,\n executor: new NotCommittedOrRolledBackAssertingExecutor(props.executor, state),\n };\n const { connection, ...transactionProps } = props;\n super(transactionProps);\n this.#props = freeze(props);\n this.#state = state;\n const queryId = createQueryId();\n this.#compileQuery = (node) => props.executor.compileQuery(node, queryId);\n }\n get isCommitted() {\n return this.#state.isCommitted;\n }\n get isRolledBack() {\n return this.#state.isRolledBack;\n }\n /**\n * Commits the transaction.\n *\n * See {@link rollback}.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * try {\n * await doSomething(trx)\n *\n * await trx.commit().execute()\n * } catch (error) {\n * await trx.rollback().execute()\n * }\n *\n * async function doSomething(kysely: Kysely) {}\n * ```\n */\n commit() {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.commitTransaction(this.#props.connection.connection);\n this.#state.isCommitted = true;\n this.#props.connection.release();\n });\n }\n /**\n * Rolls back the transaction.\n *\n * See {@link commit} and {@link rollbackToSavepoint}.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * try {\n * await doSomething(trx)\n *\n * await trx.commit().execute()\n * } catch (error) {\n * await trx.rollback().execute()\n * }\n *\n * async function doSomething(kysely: Kysely) {}\n * ```\n */\n rollback() {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.rollbackTransaction(this.#props.connection.connection);\n this.#state.isRolledBack = true;\n this.#props.connection.release();\n });\n }\n /**\n * Creates a savepoint with a given name.\n *\n * See {@link rollbackToSavepoint} and {@link releaseSavepoint}.\n *\n * For a type-safe experience, you should use the returned instance from now on.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * await insertJennifer(trx)\n *\n * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()\n *\n * try {\n * await doSomething(trxAfterJennifer)\n * } catch (error) {\n * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()\n * }\n *\n * async function insertJennifer(kysely: Kysely) {}\n * async function doSomething(kysely: Kysely) {}\n * ```\n */\n savepoint(savepointName) {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.savepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);\n return new ControlledTransaction({ ...this.#props });\n });\n }\n /**\n * Rolls back to a savepoint with a given name.\n *\n * See {@link savepoint} and {@link releaseSavepoint}.\n *\n * You must use the same instance returned by {@link savepoint}, or\n * escape the type-check by using `as any`.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * await insertJennifer(trx)\n *\n * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()\n *\n * try {\n * await doSomething(trxAfterJennifer)\n * } catch (error) {\n * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()\n * }\n *\n * async function insertJennifer(kysely: Kysely) {}\n * async function doSomething(kysely: Kysely) {}\n * ```\n */\n rollbackToSavepoint(savepointName) {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.rollbackToSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);\n return new ControlledTransaction({ ...this.#props });\n });\n }\n /**\n * Releases a savepoint with a given name.\n *\n * See {@link savepoint} and {@link rollbackToSavepoint}.\n *\n * You must use the same instance returned by {@link savepoint}, or\n * escape the type-check by using `as any`.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * await insertJennifer(trx)\n *\n * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()\n *\n * try {\n * await doSomething(trxAfterJennifer)\n * } catch (error) {\n * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()\n * }\n *\n * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute()\n *\n * await doSomethingElse(trx)\n *\n * async function insertJennifer(kysely: Kysely) {}\n * async function doSomething(kysely: Kysely) {}\n * async function doSomethingElse(kysely: Kysely) {}\n * ```\n */\n releaseSavepoint(savepointName) {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.releaseSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);\n return new ControlledTransaction({ ...this.#props });\n });\n }\n withPlugin(plugin) {\n return new ControlledTransaction({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n withoutPlugins() {\n return new ControlledTransaction({\n ...this.#props,\n executor: this.#props.executor.withoutPlugins(),\n });\n }\n withSchema(schema) {\n return new ControlledTransaction({\n ...this.#props,\n executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema)),\n });\n }\n withTables() {\n return new ControlledTransaction({ ...this.#props });\n }\n}\nexport class Command {\n #cb;\n constructor(cb) {\n this.#cb = cb;\n }\n /**\n * Executes the command.\n */\n async execute() {\n return await this.#cb();\n }\n}\nfunction assertNotCommittedOrRolledBack(state) {\n if (state.isCommitted) {\n throw new Error('Transaction is already committed');\n }\n if (state.isRolledBack) {\n throw new Error('Transaction is already rolled back');\n }\n}\n/**\n * An executor wrapper that asserts that the transaction state is not committed\n * or rolled back when a query is executed.\n *\n * @internal\n */\nclass NotCommittedOrRolledBackAssertingExecutor {\n #executor;\n #state;\n constructor(executor, state) {\n if (executor instanceof NotCommittedOrRolledBackAssertingExecutor) {\n this.#executor = executor.#executor;\n }\n else {\n this.#executor = executor;\n }\n this.#state = state;\n }\n get adapter() {\n return this.#executor.adapter;\n }\n get plugins() {\n return this.#executor.plugins;\n }\n transformQuery(node, queryId) {\n return this.#executor.transformQuery(node, queryId);\n }\n compileQuery(node, queryId) {\n return this.#executor.compileQuery(node, queryId);\n }\n provideConnection(consumer) {\n return this.#executor.provideConnection(consumer);\n }\n executeQuery(compiledQuery) {\n assertNotCommittedOrRolledBack(this.#state);\n return this.#executor.executeQuery(compiledQuery);\n }\n stream(compiledQuery, chunkSize) {\n assertNotCommittedOrRolledBack(this.#state);\n return this.#executor.stream(compiledQuery, chunkSize);\n }\n withConnectionProvider(connectionProvider) {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withConnectionProvider(connectionProvider), this.#state);\n }\n withPlugin(plugin) {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugin(plugin), this.#state);\n }\n withPlugins(plugins) {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugins(plugins), this.#state);\n }\n withPluginAtFront(plugin) {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPluginAtFront(plugin), this.#state);\n }\n withoutPlugins() {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withoutPlugins(), this.#state);\n }\n}\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nclass RawBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isRawBuilder() {\n return true;\n }\n as(alias) {\n return new AliasedRawBuilderImpl(this, alias);\n }\n $castTo() {\n return new RawBuilderImpl({ ...this.#props });\n }\n $notNull() {\n return new RawBuilderImpl(this.#props);\n }\n withPlugin(plugin) {\n return new RawBuilderImpl({\n ...this.#props,\n plugins: this.#props.plugins !== undefined\n ? freeze([...this.#props.plugins, plugin])\n : freeze([plugin]),\n });\n }\n toOperationNode() {\n return this.#toOperationNode(this.#getExecutor());\n }\n compile(executorProvider) {\n return this.#compile(this.#getExecutor(executorProvider));\n }\n async execute(executorProvider) {\n const executor = this.#getExecutor(executorProvider);\n return executor.executeQuery(this.#compile(executor));\n }\n #getExecutor(executorProvider) {\n const executor = executorProvider !== undefined\n ? executorProvider.getExecutor()\n : NOOP_QUERY_EXECUTOR;\n return this.#props.plugins !== undefined\n ? executor.withPlugins(this.#props.plugins)\n : executor;\n }\n #toOperationNode(executor) {\n return executor.transformQuery(this.#props.rawNode, this.#props.queryId);\n }\n #compile(executor) {\n return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId);\n }\n}\nexport function createRawBuilder(props) {\n return new RawBuilderImpl(props);\n}\nclass AliasedRawBuilderImpl {\n #rawBuilder;\n #alias;\n constructor(rawBuilder, alias) {\n this.#rawBuilder = rawBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#rawBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get rawBuilder() {\n return this.#rawBuilder;\n }\n toOperationNode() {\n return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n", "/// \nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { parseStringReference } from '../parser/reference-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseValueExpression } from '../parser/value-parser.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createRawBuilder } from './raw-builder.js';\nexport const sql = Object.assign((sqlFragments, ...parameters) => {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []),\n });\n}, {\n ref(columnReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseStringReference(columnReference)),\n });\n },\n val(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseValueExpression(value)),\n });\n },\n value(value) {\n return this.val(value);\n },\n table(tableReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseTable(tableReference)),\n });\n },\n id(...ids) {\n const fragments = new Array(ids.length + 1).fill('.');\n fragments[0] = '';\n fragments[fragments.length - 1] = '';\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)),\n });\n },\n lit(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)),\n });\n },\n literal(value) {\n return this.lit(value);\n },\n raw(sql) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithSql(sql),\n });\n },\n join(array, separator = sql `, `) {\n const nodes = new Array(Math.max(2 * array.length - 1, 0));\n const sep = separator.toOperationNode();\n for (let i = 0; i < array.length; ++i) {\n nodes[2 * i] = parseParameter(array[i]);\n if (i !== array.length - 1) {\n nodes[2 * i + 1] = sep;\n }\n }\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChildren(nodes),\n });\n },\n});\nfunction parseParameter(param) {\n if (isOperationNodeSource(param)) {\n return param.toOperationNode();\n }\n return parseValueExpression(param);\n}\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nimport { freeze } from '../util/object-utils.js';\nexport class OperationNodeVisitor {\n nodeStack = [];\n get parentNode() {\n return this.nodeStack[this.nodeStack.length - 2];\n }\n #visitors = freeze({\n AliasNode: this.visitAlias.bind(this),\n ColumnNode: this.visitColumn.bind(this),\n IdentifierNode: this.visitIdentifier.bind(this),\n SchemableIdentifierNode: this.visitSchemableIdentifier.bind(this),\n RawNode: this.visitRaw.bind(this),\n ReferenceNode: this.visitReference.bind(this),\n SelectQueryNode: this.visitSelectQuery.bind(this),\n SelectionNode: this.visitSelection.bind(this),\n TableNode: this.visitTable.bind(this),\n FromNode: this.visitFrom.bind(this),\n SelectAllNode: this.visitSelectAll.bind(this),\n AndNode: this.visitAnd.bind(this),\n OrNode: this.visitOr.bind(this),\n ValueNode: this.visitValue.bind(this),\n ValueListNode: this.visitValueList.bind(this),\n PrimitiveValueListNode: this.visitPrimitiveValueList.bind(this),\n ParensNode: this.visitParens.bind(this),\n JoinNode: this.visitJoin.bind(this),\n OperatorNode: this.visitOperator.bind(this),\n WhereNode: this.visitWhere.bind(this),\n InsertQueryNode: this.visitInsertQuery.bind(this),\n DeleteQueryNode: this.visitDeleteQuery.bind(this),\n ReturningNode: this.visitReturning.bind(this),\n CreateTableNode: this.visitCreateTable.bind(this),\n AddColumnNode: this.visitAddColumn.bind(this),\n ColumnDefinitionNode: this.visitColumnDefinition.bind(this),\n DropTableNode: this.visitDropTable.bind(this),\n DataTypeNode: this.visitDataType.bind(this),\n OrderByNode: this.visitOrderBy.bind(this),\n OrderByItemNode: this.visitOrderByItem.bind(this),\n GroupByNode: this.visitGroupBy.bind(this),\n GroupByItemNode: this.visitGroupByItem.bind(this),\n UpdateQueryNode: this.visitUpdateQuery.bind(this),\n ColumnUpdateNode: this.visitColumnUpdate.bind(this),\n LimitNode: this.visitLimit.bind(this),\n OffsetNode: this.visitOffset.bind(this),\n OnConflictNode: this.visitOnConflict.bind(this),\n OnDuplicateKeyNode: this.visitOnDuplicateKey.bind(this),\n CreateIndexNode: this.visitCreateIndex.bind(this),\n DropIndexNode: this.visitDropIndex.bind(this),\n ListNode: this.visitList.bind(this),\n PrimaryKeyConstraintNode: this.visitPrimaryKeyConstraint.bind(this),\n UniqueConstraintNode: this.visitUniqueConstraint.bind(this),\n ReferencesNode: this.visitReferences.bind(this),\n CheckConstraintNode: this.visitCheckConstraint.bind(this),\n WithNode: this.visitWith.bind(this),\n CommonTableExpressionNode: this.visitCommonTableExpression.bind(this),\n CommonTableExpressionNameNode: this.visitCommonTableExpressionName.bind(this),\n HavingNode: this.visitHaving.bind(this),\n CreateSchemaNode: this.visitCreateSchema.bind(this),\n DropSchemaNode: this.visitDropSchema.bind(this),\n AlterTableNode: this.visitAlterTable.bind(this),\n DropColumnNode: this.visitDropColumn.bind(this),\n RenameColumnNode: this.visitRenameColumn.bind(this),\n AlterColumnNode: this.visitAlterColumn.bind(this),\n ModifyColumnNode: this.visitModifyColumn.bind(this),\n AddConstraintNode: this.visitAddConstraint.bind(this),\n DropConstraintNode: this.visitDropConstraint.bind(this),\n RenameConstraintNode: this.visitRenameConstraint.bind(this),\n ForeignKeyConstraintNode: this.visitForeignKeyConstraint.bind(this),\n CreateViewNode: this.visitCreateView.bind(this),\n RefreshMaterializedViewNode: this.visitRefreshMaterializedView.bind(this),\n DropViewNode: this.visitDropView.bind(this),\n GeneratedNode: this.visitGenerated.bind(this),\n DefaultValueNode: this.visitDefaultValue.bind(this),\n OnNode: this.visitOn.bind(this),\n ValuesNode: this.visitValues.bind(this),\n SelectModifierNode: this.visitSelectModifier.bind(this),\n CreateTypeNode: this.visitCreateType.bind(this),\n DropTypeNode: this.visitDropType.bind(this),\n ExplainNode: this.visitExplain.bind(this),\n DefaultInsertValueNode: this.visitDefaultInsertValue.bind(this),\n AggregateFunctionNode: this.visitAggregateFunction.bind(this),\n OverNode: this.visitOver.bind(this),\n PartitionByNode: this.visitPartitionBy.bind(this),\n PartitionByItemNode: this.visitPartitionByItem.bind(this),\n SetOperationNode: this.visitSetOperation.bind(this),\n BinaryOperationNode: this.visitBinaryOperation.bind(this),\n UnaryOperationNode: this.visitUnaryOperation.bind(this),\n UsingNode: this.visitUsing.bind(this),\n FunctionNode: this.visitFunction.bind(this),\n CaseNode: this.visitCase.bind(this),\n WhenNode: this.visitWhen.bind(this),\n JSONReferenceNode: this.visitJSONReference.bind(this),\n JSONPathNode: this.visitJSONPath.bind(this),\n JSONPathLegNode: this.visitJSONPathLeg.bind(this),\n JSONOperatorChainNode: this.visitJSONOperatorChain.bind(this),\n TupleNode: this.visitTuple.bind(this),\n MergeQueryNode: this.visitMergeQuery.bind(this),\n MatchedNode: this.visitMatched.bind(this),\n AddIndexNode: this.visitAddIndex.bind(this),\n CastNode: this.visitCast.bind(this),\n FetchNode: this.visitFetch.bind(this),\n TopNode: this.visitTop.bind(this),\n OutputNode: this.visitOutput.bind(this),\n OrActionNode: this.visitOrAction.bind(this),\n CollateNode: this.visitCollate.bind(this),\n });\n visitNode = (node) => {\n this.nodeStack.push(node);\n this.#visitors[node.kind](node);\n this.nodeStack.pop();\n };\n}\n", "/// \nimport { CreateTableNode } from '../operation-node/create-table-node.js';\nimport { InsertQueryNode } from '../operation-node/insert-query-node.js';\nimport { OperationNodeVisitor } from '../operation-node/operation-node-visitor.js';\nimport { OperatorNode } from '../operation-node/operator-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze, isString, isNumber, isBoolean, isNull, isDate, isBigInt, } from '../util/object-utils.js';\nimport { CreateViewNode } from '../operation-node/create-view-node.js';\nimport { SetOperationNode } from '../operation-node/set-operation-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { logOnce } from '../util/log-once.js';\nconst LIT_WRAP_REGEX = /'/g;\nexport class DefaultQueryCompiler extends OperationNodeVisitor {\n #sql = '';\n #parameters = [];\n get numParameters() {\n return this.#parameters.length;\n }\n compileQuery(node, queryId) {\n this.#sql = '';\n this.#parameters = [];\n this.nodeStack.splice(0, this.nodeStack.length);\n this.visitNode(node);\n return freeze({\n query: node,\n queryId,\n sql: this.getSql(),\n parameters: [...this.#parameters],\n });\n }\n getSql() {\n return this.#sql;\n }\n visitSelectQuery(node) {\n const wrapInParens = this.parentNode !== undefined &&\n !ParensNode.is(this.parentNode) &&\n !InsertQueryNode.is(this.parentNode) &&\n !CreateTableNode.is(this.parentNode) &&\n !CreateViewNode.is(this.parentNode) &&\n !SetOperationNode.is(this.parentNode);\n if (this.parentNode === undefined && node.explain) {\n this.visitNode(node.explain);\n this.append(' ');\n }\n if (wrapInParens) {\n this.append('(');\n }\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append('select');\n if (node.distinctOn) {\n this.append(' ');\n this.compileDistinctOn(node.distinctOn);\n }\n if (node.frontModifiers?.length) {\n this.append(' ');\n this.compileList(node.frontModifiers, ' ');\n }\n if (node.top) {\n this.append(' ');\n this.visitNode(node.top);\n }\n if (node.selections) {\n this.append(' ');\n this.compileList(node.selections);\n }\n if (node.from) {\n this.append(' ');\n this.visitNode(node.from);\n }\n if (node.joins) {\n this.append(' ');\n this.compileList(node.joins, ' ');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n if (node.groupBy) {\n this.append(' ');\n this.visitNode(node.groupBy);\n }\n if (node.having) {\n this.append(' ');\n this.visitNode(node.having);\n }\n if (node.setOperations) {\n this.append(' ');\n this.compileList(node.setOperations, ' ');\n }\n if (node.orderBy) {\n this.append(' ');\n this.visitNode(node.orderBy);\n }\n if (node.limit) {\n this.append(' ');\n this.visitNode(node.limit);\n }\n if (node.offset) {\n this.append(' ');\n this.visitNode(node.offset);\n }\n if (node.fetch) {\n this.append(' ');\n this.visitNode(node.fetch);\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(this.sortSelectModifiers([...node.endModifiers]), ' ');\n }\n if (wrapInParens) {\n this.append(')');\n }\n }\n visitFrom(node) {\n this.append('from ');\n this.compileList(node.froms);\n }\n visitSelection(node) {\n this.visitNode(node.selection);\n }\n visitColumn(node) {\n this.visitNode(node.column);\n }\n compileDistinctOn(expressions) {\n this.append('distinct on (');\n this.compileList(expressions);\n this.append(')');\n }\n compileList(nodes, separator = ', ') {\n const lastIndex = nodes.length - 1;\n for (let i = 0; i <= lastIndex; i++) {\n this.visitNode(nodes[i]);\n if (i < lastIndex) {\n this.append(separator);\n }\n }\n }\n visitWhere(node) {\n this.append('where ');\n this.visitNode(node.where);\n }\n visitHaving(node) {\n this.append('having ');\n this.visitNode(node.having);\n }\n visitInsertQuery(node) {\n const wrapInParens = this.parentNode !== undefined &&\n !ParensNode.is(this.parentNode) &&\n !RawNode.is(this.parentNode) &&\n !WhenNode.is(this.parentNode);\n if (this.parentNode === undefined && node.explain) {\n this.visitNode(node.explain);\n this.append(' ');\n }\n if (wrapInParens) {\n this.append('(');\n }\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append(node.replace ? 'replace' : 'insert');\n // TODO: remove in 0.29.\n if (node.ignore) {\n logOnce('`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead.');\n this.append(' ignore');\n }\n if (node.orAction) {\n this.append(' ');\n this.visitNode(node.orAction);\n }\n if (node.top) {\n this.append(' ');\n this.visitNode(node.top);\n }\n if (node.into) {\n this.append(' into ');\n this.visitNode(node.into);\n }\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n if (node.output) {\n this.append(' ');\n this.visitNode(node.output);\n }\n if (node.values) {\n this.append(' ');\n this.visitNode(node.values);\n }\n if (node.defaultValues) {\n this.append(' ');\n this.append('default values');\n }\n if (node.onConflict) {\n this.append(' ');\n this.visitNode(node.onConflict);\n }\n if (node.onDuplicateKey) {\n this.append(' ');\n this.visitNode(node.onDuplicateKey);\n }\n if (node.returning) {\n this.append(' ');\n this.visitNode(node.returning);\n }\n if (wrapInParens) {\n this.append(')');\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n visitValues(node) {\n this.append('values ');\n this.compileList(node.values);\n }\n visitDeleteQuery(node) {\n const wrapInParens = this.parentNode !== undefined &&\n !ParensNode.is(this.parentNode) &&\n !RawNode.is(this.parentNode);\n if (this.parentNode === undefined && node.explain) {\n this.visitNode(node.explain);\n this.append(' ');\n }\n if (wrapInParens) {\n this.append('(');\n }\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append('delete ');\n if (node.top) {\n this.visitNode(node.top);\n this.append(' ');\n }\n this.visitNode(node.from);\n if (node.output) {\n this.append(' ');\n this.visitNode(node.output);\n }\n if (node.using) {\n this.append(' ');\n this.visitNode(node.using);\n }\n if (node.joins) {\n this.append(' ');\n this.compileList(node.joins, ' ');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n if (node.orderBy) {\n this.append(' ');\n this.visitNode(node.orderBy);\n }\n if (node.limit) {\n this.append(' ');\n this.visitNode(node.limit);\n }\n if (node.returning) {\n this.append(' ');\n this.visitNode(node.returning);\n }\n if (wrapInParens) {\n this.append(')');\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n visitReturning(node) {\n this.append('returning ');\n this.compileList(node.selections);\n }\n visitAlias(node) {\n this.visitNode(node.node);\n this.append(' as ');\n this.visitNode(node.alias);\n }\n visitReference(node) {\n if (node.table) {\n this.visitNode(node.table);\n this.append('.');\n }\n this.visitNode(node.column);\n }\n visitSelectAll(_) {\n this.append('*');\n }\n visitIdentifier(node) {\n this.append(this.getLeftIdentifierWrapper());\n this.compileUnwrappedIdentifier(node);\n this.append(this.getRightIdentifierWrapper());\n }\n compileUnwrappedIdentifier(node) {\n if (!isString(node.name)) {\n throw new Error('a non-string identifier was passed to compileUnwrappedIdentifier.');\n }\n this.append(this.sanitizeIdentifier(node.name));\n }\n visitAnd(node) {\n this.visitNode(node.left);\n this.append(' and ');\n this.visitNode(node.right);\n }\n visitOr(node) {\n this.visitNode(node.left);\n this.append(' or ');\n this.visitNode(node.right);\n }\n visitValue(node) {\n if (node.immediate) {\n this.appendImmediateValue(node.value);\n }\n else {\n this.appendValue(node.value);\n }\n }\n visitValueList(node) {\n this.append('(');\n this.compileList(node.values);\n this.append(')');\n }\n visitTuple(node) {\n this.append('(');\n this.compileList(node.values);\n this.append(')');\n }\n visitPrimitiveValueList(node) {\n this.append('(');\n const { values } = node;\n for (let i = 0; i < values.length; ++i) {\n this.appendValue(values[i]);\n if (i !== values.length - 1) {\n this.append(', ');\n }\n }\n this.append(')');\n }\n visitParens(node) {\n this.append('(');\n this.visitNode(node.node);\n this.append(')');\n }\n visitJoin(node) {\n this.append(JOIN_TYPE_SQL[node.joinType]);\n this.append(' ');\n this.visitNode(node.table);\n if (node.on) {\n this.append(' ');\n this.visitNode(node.on);\n }\n }\n visitOn(node) {\n this.append('on ');\n this.visitNode(node.on);\n }\n visitRaw(node) {\n const { sqlFragments, parameters: params } = node;\n for (let i = 0; i < sqlFragments.length; ++i) {\n this.append(sqlFragments[i]);\n if (params.length > i) {\n this.visitNode(params[i]);\n }\n }\n }\n visitOperator(node) {\n this.append(node.operator);\n }\n visitTable(node) {\n this.visitNode(node.table);\n }\n visitSchemableIdentifier(node) {\n if (node.schema) {\n this.visitNode(node.schema);\n this.append('.');\n }\n this.visitNode(node.identifier);\n }\n visitCreateTable(node) {\n this.append('create ');\n if (node.frontModifiers?.length) {\n this.compileList(node.frontModifiers, ' ');\n this.append(' ');\n }\n if (node.temporary) {\n this.append('temporary ');\n }\n this.append('table ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.table);\n if (!node.selectQuery) {\n this.append(' (');\n this.compileList([...node.columns, ...(node.constraints ?? [])]);\n this.append(')');\n }\n if (node.onCommit) {\n this.append(' on commit ');\n this.append(node.onCommit);\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n if (node.selectQuery) {\n this.append(' as ');\n this.visitNode(node.selectQuery);\n }\n }\n visitColumnDefinition(node) {\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.column);\n this.append(' ');\n this.visitNode(node.dataType);\n if (node.unsigned) {\n this.append(' unsigned');\n }\n if (node.frontModifiers && node.frontModifiers.length > 0) {\n this.append(' ');\n this.compileList(node.frontModifiers, ' ');\n }\n if (node.generated) {\n this.append(' ');\n this.visitNode(node.generated);\n }\n if (node.identity) {\n this.append(' identity');\n }\n if (node.defaultTo) {\n this.append(' ');\n this.visitNode(node.defaultTo);\n }\n if (node.notNull) {\n this.append(' not null');\n }\n if (node.unique) {\n this.append(' unique');\n }\n if (node.nullsNotDistinct) {\n this.append(' nulls not distinct');\n }\n if (node.primaryKey) {\n this.append(' primary key');\n }\n if (node.autoIncrement) {\n this.append(' ');\n this.append(this.getAutoIncrement());\n }\n if (node.references) {\n this.append(' ');\n this.visitNode(node.references);\n }\n if (node.check) {\n this.append(' ');\n this.visitNode(node.check);\n }\n if (node.endModifiers && node.endModifiers.length > 0) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n getAutoIncrement() {\n return 'auto_increment';\n }\n visitReferences(node) {\n this.append('references ');\n this.visitNode(node.table);\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n if (node.onDelete) {\n this.append(' on delete ');\n this.append(node.onDelete);\n }\n if (node.onUpdate) {\n this.append(' on update ');\n this.append(node.onUpdate);\n }\n }\n visitDropTable(node) {\n this.append('drop table ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.table);\n if (node.cascade) {\n this.append(' cascade');\n }\n }\n visitDataType(node) {\n this.append(node.dataType);\n }\n visitOrderBy(node) {\n this.append('order by ');\n this.compileList(node.items);\n }\n visitOrderByItem(node) {\n this.visitNode(node.orderBy);\n if (node.collation) {\n this.append(' ');\n this.visitNode(node.collation);\n }\n if (node.direction) {\n this.append(' ');\n this.visitNode(node.direction);\n }\n if (node.nulls) {\n this.append(' nulls ');\n this.append(node.nulls);\n }\n }\n visitGroupBy(node) {\n this.append('group by ');\n this.compileList(node.items);\n }\n visitGroupByItem(node) {\n this.visitNode(node.groupBy);\n }\n visitUpdateQuery(node) {\n const wrapInParens = this.parentNode !== undefined &&\n !ParensNode.is(this.parentNode) &&\n !RawNode.is(this.parentNode) &&\n !WhenNode.is(this.parentNode);\n if (this.parentNode === undefined && node.explain) {\n this.visitNode(node.explain);\n this.append(' ');\n }\n if (wrapInParens) {\n this.append('(');\n }\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append('update ');\n if (node.top) {\n this.visitNode(node.top);\n this.append(' ');\n }\n if (node.table) {\n this.visitNode(node.table);\n this.append(' ');\n }\n this.append('set ');\n if (node.updates) {\n this.compileList(node.updates);\n }\n if (node.output) {\n this.append(' ');\n this.visitNode(node.output);\n }\n if (node.from) {\n this.append(' ');\n this.visitNode(node.from);\n }\n if (node.joins) {\n if (!node.from) {\n throw new Error(\"Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins\");\n }\n this.append(' ');\n this.compileList(node.joins, ' ');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n if (node.returning) {\n this.append(' ');\n this.visitNode(node.returning);\n }\n if (node.orderBy) {\n this.append(' ');\n this.visitNode(node.orderBy);\n }\n if (node.limit) {\n this.append(' ');\n this.visitNode(node.limit);\n }\n if (wrapInParens) {\n this.append(')');\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n visitColumnUpdate(node) {\n this.visitNode(node.column);\n this.append(' = ');\n this.visitNode(node.value);\n }\n visitLimit(node) {\n this.append('limit ');\n this.visitNode(node.limit);\n }\n visitOffset(node) {\n this.append('offset ');\n this.visitNode(node.offset);\n }\n visitOnConflict(node) {\n this.append('on conflict');\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n else if (node.constraint) {\n this.append(' on constraint ');\n this.visitNode(node.constraint);\n }\n else if (node.indexExpression) {\n this.append(' (');\n this.visitNode(node.indexExpression);\n this.append(')');\n }\n if (node.indexWhere) {\n this.append(' ');\n this.visitNode(node.indexWhere);\n }\n if (node.doNothing === true) {\n this.append(' do nothing');\n }\n else if (node.updates) {\n this.append(' do update set ');\n this.compileList(node.updates);\n if (node.updateWhere) {\n this.append(' ');\n this.visitNode(node.updateWhere);\n }\n }\n }\n visitOnDuplicateKey(node) {\n this.append('on duplicate key update ');\n this.compileList(node.updates);\n }\n visitCreateIndex(node) {\n this.append('create ');\n if (node.unique) {\n this.append('unique ');\n }\n this.append('index ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.name);\n if (node.table) {\n this.append(' on ');\n this.visitNode(node.table);\n }\n if (node.using) {\n this.append(' using ');\n this.visitNode(node.using);\n }\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n if (node.nullsNotDistinct) {\n this.append(' nulls not distinct');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n }\n visitDropIndex(node) {\n this.append('drop index ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.name);\n if (node.table) {\n this.append(' on ');\n this.visitNode(node.table);\n }\n if (node.cascade) {\n this.append(' cascade');\n }\n }\n visitCreateSchema(node) {\n this.append('create schema ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.schema);\n }\n visitDropSchema(node) {\n this.append('drop schema ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.schema);\n if (node.cascade) {\n this.append(' cascade');\n }\n }\n visitPrimaryKeyConstraint(node) {\n if (node.name) {\n this.append('constraint ');\n this.visitNode(node.name);\n this.append(' ');\n }\n this.append('primary key (');\n this.compileList(node.columns);\n this.append(')');\n this.buildDeferrable(node);\n }\n buildDeferrable(node) {\n if (node.deferrable !== undefined) {\n if (node.deferrable) {\n this.append(' deferrable');\n }\n else {\n this.append(' not deferrable');\n }\n }\n if (node.initiallyDeferred !== undefined) {\n if (node.initiallyDeferred) {\n this.append(' initially deferred');\n }\n else {\n this.append(' initially immediate');\n }\n }\n }\n visitUniqueConstraint(node) {\n if (node.name) {\n this.append('constraint ');\n this.visitNode(node.name);\n this.append(' ');\n }\n this.append('unique');\n if (node.nullsNotDistinct) {\n this.append(' nulls not distinct');\n }\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n this.buildDeferrable(node);\n }\n visitCheckConstraint(node) {\n if (node.name) {\n this.append('constraint ');\n this.visitNode(node.name);\n this.append(' ');\n }\n this.append('check (');\n this.visitNode(node.expression);\n this.append(')');\n }\n visitForeignKeyConstraint(node) {\n if (node.name) {\n this.append('constraint ');\n this.visitNode(node.name);\n this.append(' ');\n }\n this.append('foreign key (');\n this.compileList(node.columns);\n this.append(') ');\n this.visitNode(node.references);\n if (node.onDelete) {\n this.append(' on delete ');\n this.append(node.onDelete);\n }\n if (node.onUpdate) {\n this.append(' on update ');\n this.append(node.onUpdate);\n }\n this.buildDeferrable(node);\n }\n visitList(node) {\n this.compileList(node.items);\n }\n visitWith(node) {\n this.append('with ');\n if (node.recursive) {\n this.append('recursive ');\n }\n this.compileList(node.expressions);\n }\n visitCommonTableExpression(node) {\n this.visitNode(node.name);\n this.append(' as ');\n if (isBoolean(node.materialized)) {\n if (!node.materialized) {\n this.append('not ');\n }\n this.append('materialized ');\n }\n this.visitNode(node.expression);\n }\n visitCommonTableExpressionName(node) {\n this.visitNode(node.table);\n if (node.columns) {\n this.append('(');\n this.compileList(node.columns);\n this.append(')');\n }\n }\n visitAlterTable(node) {\n this.append('alter table ');\n this.visitNode(node.table);\n this.append(' ');\n if (node.renameTo) {\n this.append('rename to ');\n this.visitNode(node.renameTo);\n }\n if (node.setSchema) {\n this.append('set schema ');\n this.visitNode(node.setSchema);\n }\n if (node.addConstraint) {\n this.visitNode(node.addConstraint);\n }\n if (node.dropConstraint) {\n this.visitNode(node.dropConstraint);\n }\n if (node.renameConstraint) {\n this.visitNode(node.renameConstraint);\n }\n if (node.columnAlterations) {\n this.compileColumnAlterations(node.columnAlterations);\n }\n if (node.addIndex) {\n this.visitNode(node.addIndex);\n }\n if (node.dropIndex) {\n this.visitNode(node.dropIndex);\n }\n }\n visitAddColumn(node) {\n this.append('add column ');\n this.visitNode(node.column);\n }\n visitRenameColumn(node) {\n this.append('rename column ');\n this.visitNode(node.column);\n this.append(' to ');\n this.visitNode(node.renameTo);\n }\n visitDropColumn(node) {\n this.append('drop column ');\n this.visitNode(node.column);\n }\n visitAlterColumn(node) {\n this.append('alter column ');\n this.visitNode(node.column);\n this.append(' ');\n if (node.dataType) {\n if (this.announcesNewColumnDataType()) {\n this.append('type ');\n }\n this.visitNode(node.dataType);\n if (node.dataTypeExpression) {\n this.append('using ');\n this.visitNode(node.dataTypeExpression);\n }\n }\n if (node.setDefault) {\n this.append('set default ');\n this.visitNode(node.setDefault);\n }\n if (node.dropDefault) {\n this.append('drop default');\n }\n if (node.setNotNull) {\n this.append('set not null');\n }\n if (node.dropNotNull) {\n this.append('drop not null');\n }\n }\n visitModifyColumn(node) {\n this.append('modify column ');\n this.visitNode(node.column);\n }\n visitAddConstraint(node) {\n this.append('add ');\n this.visitNode(node.constraint);\n }\n visitDropConstraint(node) {\n this.append('drop constraint ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.constraintName);\n if (node.modifier === 'cascade') {\n this.append(' cascade');\n }\n else if (node.modifier === 'restrict') {\n this.append(' restrict');\n }\n }\n visitRenameConstraint(node) {\n this.append('rename constraint ');\n this.visitNode(node.oldName);\n this.append(' to ');\n this.visitNode(node.newName);\n }\n visitSetOperation(node) {\n this.append(node.operator);\n this.append(' ');\n if (node.all) {\n this.append('all ');\n }\n this.visitNode(node.expression);\n }\n visitCreateView(node) {\n this.append('create ');\n if (node.orReplace) {\n this.append('or replace ');\n }\n if (node.materialized) {\n this.append('materialized ');\n }\n if (node.temporary) {\n this.append('temporary ');\n }\n this.append('view ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.name);\n this.append(' ');\n if (node.columns) {\n this.append('(');\n this.compileList(node.columns);\n this.append(') ');\n }\n if (node.as) {\n this.append('as ');\n this.visitNode(node.as);\n }\n }\n visitRefreshMaterializedView(node) {\n this.append('refresh materialized view ');\n if (node.concurrently) {\n this.append('concurrently ');\n }\n this.visitNode(node.name);\n if (node.withNoData) {\n this.append(' with no data');\n }\n else {\n this.append(' with data');\n }\n }\n visitDropView(node) {\n this.append('drop ');\n if (node.materialized) {\n this.append('materialized ');\n }\n this.append('view ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.name);\n if (node.cascade) {\n this.append(' cascade');\n }\n }\n visitGenerated(node) {\n this.append('generated ');\n if (node.always) {\n this.append('always ');\n }\n if (node.byDefault) {\n this.append('by default ');\n }\n this.append('as ');\n if (node.identity) {\n this.append('identity');\n }\n if (node.expression) {\n this.append('(');\n this.visitNode(node.expression);\n this.append(')');\n }\n if (node.stored) {\n this.append(' stored');\n }\n }\n visitDefaultValue(node) {\n this.append('default ');\n this.visitNode(node.defaultValue);\n }\n visitSelectModifier(node) {\n if (node.rawModifier) {\n this.visitNode(node.rawModifier);\n }\n else {\n this.append(SELECT_MODIFIER_SQL[node.modifier]);\n }\n if (node.of) {\n this.append(' of ');\n this.compileList(node.of, ', ');\n }\n }\n visitCreateType(node) {\n this.append('create type ');\n this.visitNode(node.name);\n if (node.enum) {\n this.append(' as enum ');\n this.visitNode(node.enum);\n }\n }\n visitDropType(node) {\n this.append('drop type ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.name);\n }\n visitExplain(node) {\n this.append('explain');\n if (node.options || node.format) {\n this.append(' ');\n this.append(this.getLeftExplainOptionsWrapper());\n if (node.options) {\n this.visitNode(node.options);\n if (node.format) {\n this.append(this.getExplainOptionsDelimiter());\n }\n }\n if (node.format) {\n this.append('format');\n this.append(this.getExplainOptionAssignment());\n this.append(node.format);\n }\n this.append(this.getRightExplainOptionsWrapper());\n }\n }\n visitDefaultInsertValue(_) {\n this.append('default');\n }\n visitAggregateFunction(node) {\n this.append(node.func);\n this.append('(');\n if (node.distinct) {\n this.append('distinct ');\n }\n this.compileList(node.aggregated);\n if (node.orderBy) {\n this.append(' ');\n this.visitNode(node.orderBy);\n }\n this.append(')');\n if (node.withinGroup) {\n this.append(' within group (');\n this.visitNode(node.withinGroup);\n this.append(')');\n }\n if (node.filter) {\n this.append(' filter(');\n this.visitNode(node.filter);\n this.append(')');\n }\n if (node.over) {\n this.append(' ');\n this.visitNode(node.over);\n }\n }\n visitOver(node) {\n this.append('over(');\n if (node.partitionBy) {\n this.visitNode(node.partitionBy);\n if (node.orderBy) {\n this.append(' ');\n }\n }\n if (node.orderBy) {\n this.visitNode(node.orderBy);\n }\n this.append(')');\n }\n visitPartitionBy(node) {\n this.append('partition by ');\n this.compileList(node.items);\n }\n visitPartitionByItem(node) {\n this.visitNode(node.partitionBy);\n }\n visitBinaryOperation(node) {\n this.visitNode(node.leftOperand);\n this.append(' ');\n this.visitNode(node.operator);\n this.append(' ');\n this.visitNode(node.rightOperand);\n }\n visitUnaryOperation(node) {\n this.visitNode(node.operator);\n if (!this.isMinusOperator(node.operator)) {\n this.append(' ');\n }\n this.visitNode(node.operand);\n }\n isMinusOperator(node) {\n return OperatorNode.is(node) && node.operator === '-';\n }\n visitUsing(node) {\n this.append('using ');\n this.compileList(node.tables);\n }\n visitFunction(node) {\n this.append(node.func);\n this.append('(');\n this.compileList(node.arguments);\n this.append(')');\n }\n visitCase(node) {\n this.append('case');\n if (node.value) {\n this.append(' ');\n this.visitNode(node.value);\n }\n if (node.when) {\n this.append(' ');\n this.compileList(node.when, ' ');\n }\n if (node.else) {\n this.append(' else ');\n this.visitNode(node.else);\n }\n this.append(' end');\n if (node.isStatement) {\n this.append(' case');\n }\n }\n visitWhen(node) {\n this.append('when ');\n this.visitNode(node.condition);\n if (node.result) {\n this.append(' then ');\n this.visitNode(node.result);\n }\n }\n visitJSONReference(node) {\n this.visitNode(node.reference);\n this.visitNode(node.traversal);\n }\n visitJSONPath(node) {\n if (node.inOperator) {\n this.visitNode(node.inOperator);\n }\n this.append(\"'$\");\n for (const pathLeg of node.pathLegs) {\n this.visitNode(pathLeg);\n }\n this.append(\"'\");\n }\n visitJSONPathLeg(node) {\n const isArrayLocation = node.type === 'ArrayLocation';\n this.append(isArrayLocation ? '[' : '.');\n this.append(typeof node.value === 'string'\n ? this.sanitizeStringLiteral(node.value)\n : String(node.value));\n if (isArrayLocation) {\n this.append(']');\n }\n }\n visitJSONOperatorChain(node) {\n for (let i = 0, len = node.values.length; i < len; i++) {\n if (i === len - 1) {\n this.visitNode(node.operator);\n }\n else {\n this.append('->');\n }\n this.visitNode(node.values[i]);\n }\n }\n visitMergeQuery(node) {\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append('merge ');\n if (node.top) {\n this.visitNode(node.top);\n this.append(' ');\n }\n this.append('into ');\n this.visitNode(node.into);\n if (node.using) {\n this.append(' ');\n this.visitNode(node.using);\n }\n if (node.whens) {\n this.append(' ');\n this.compileList(node.whens, ' ');\n }\n if (node.returning) {\n this.append(' ');\n this.visitNode(node.returning);\n }\n if (node.output) {\n this.append(' ');\n this.visitNode(node.output);\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n visitMatched(node) {\n if (node.not) {\n this.append('not ');\n }\n this.append('matched');\n if (node.bySource) {\n this.append(' by source');\n }\n }\n visitAddIndex(node) {\n this.append('add ');\n if (node.unique) {\n this.append('unique ');\n }\n this.append('index ');\n this.visitNode(node.name);\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n if (node.using) {\n this.append(' using ');\n this.visitNode(node.using);\n }\n }\n visitCast(node) {\n this.append('cast(');\n this.visitNode(node.expression);\n this.append(' as ');\n this.visitNode(node.dataType);\n this.append(')');\n }\n visitFetch(node) {\n this.append('fetch next ');\n this.visitNode(node.rowCount);\n this.append(` rows ${node.modifier}`);\n }\n visitOutput(node) {\n this.append('output ');\n this.compileList(node.selections);\n }\n visitTop(node) {\n this.append(`top(${node.expression})`);\n if (node.modifiers) {\n this.append(` ${node.modifiers}`);\n }\n }\n visitOrAction(node) {\n this.append(node.action);\n }\n visitCollate(node) {\n this.append('collate ');\n this.visitNode(node.collation);\n }\n append(str) {\n this.#sql += str;\n }\n appendValue(parameter) {\n this.addParameter(parameter);\n this.append(this.getCurrentParameterPlaceholder());\n }\n getLeftIdentifierWrapper() {\n return '\"';\n }\n getRightIdentifierWrapper() {\n return '\"';\n }\n getCurrentParameterPlaceholder() {\n return '$' + this.numParameters;\n }\n getLeftExplainOptionsWrapper() {\n return '(';\n }\n getExplainOptionAssignment() {\n return ' ';\n }\n getExplainOptionsDelimiter() {\n return ', ';\n }\n getRightExplainOptionsWrapper() {\n return ')';\n }\n sanitizeIdentifier(identifier) {\n const leftWrap = this.getLeftIdentifierWrapper();\n const rightWrap = this.getRightIdentifierWrapper();\n let sanitized = '';\n for (const c of identifier) {\n sanitized += c;\n if (c === leftWrap) {\n sanitized += leftWrap;\n }\n else if (c === rightWrap) {\n sanitized += rightWrap;\n }\n }\n return sanitized;\n }\n sanitizeStringLiteral(value) {\n return value.replace(LIT_WRAP_REGEX, \"''\");\n }\n addParameter(parameter) {\n this.#parameters.push(parameter);\n }\n appendImmediateValue(value) {\n if (isString(value)) {\n this.appendStringLiteral(value);\n }\n else if (isNumber(value) || isBoolean(value) || isBigInt(value)) {\n this.append(value.toString());\n }\n else if (isNull(value)) {\n this.append('null');\n }\n else if (isDate(value)) {\n this.appendImmediateValue(value.toISOString());\n }\n else {\n throw new Error(`invalid immediate value ${value}`);\n }\n }\n appendStringLiteral(value) {\n this.append(\"'\");\n this.append(this.sanitizeStringLiteral(value));\n this.append(\"'\");\n }\n sortSelectModifiers(arr) {\n arr.sort((left, right) => left.modifier && right.modifier\n ? SELECT_MODIFIER_PRIORITY[left.modifier] -\n SELECT_MODIFIER_PRIORITY[right.modifier]\n : 1);\n return freeze(arr);\n }\n compileColumnAlterations(columnAlterations) {\n this.compileList(columnAlterations);\n }\n /**\n * controls whether the dialect adds a \"type\" keyword before a column's new data\n * type in an ALTER TABLE statement.\n */\n announcesNewColumnDataType() {\n return true;\n }\n}\nconst SELECT_MODIFIER_SQL = freeze({\n ForKeyShare: 'for key share',\n ForNoKeyUpdate: 'for no key update',\n ForUpdate: 'for update',\n ForShare: 'for share',\n NoWait: 'nowait',\n SkipLocked: 'skip locked',\n Distinct: 'distinct',\n});\nconst SELECT_MODIFIER_PRIORITY = freeze({\n ForKeyShare: 1,\n ForNoKeyUpdate: 1,\n ForUpdate: 1,\n ForShare: 1,\n NoWait: 2,\n SkipLocked: 2,\n Distinct: 0,\n});\nconst JOIN_TYPE_SQL = freeze({\n InnerJoin: 'inner join',\n LeftJoin: 'left join',\n RightJoin: 'right join',\n FullJoin: 'full join',\n CrossJoin: 'cross join',\n LateralInnerJoin: 'inner join lateral',\n LateralLeftJoin: 'left join lateral',\n LateralCrossJoin: 'cross join lateral',\n OuterApply: 'outer apply',\n CrossApply: 'cross apply',\n Using: 'using',\n});\n", "/// \nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { createQueryId } from '../util/query-id.js';\nexport const CompiledQuery = freeze({\n raw(sql, parameters = []) {\n return freeze({\n sql,\n query: RawNode.createWithSql(sql),\n parameters: freeze(parameters),\n queryId: createQueryId(),\n });\n },\n});\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \n/**\n * A driver that does absolutely nothing.\n *\n * You can use this to create Kysely instances solely for building queries\n *\n * ### Examples\n *\n * This example creates a Kysely instance for building postgres queries:\n *\n * ```ts\n * import {\n * DummyDriver,\n * Kysely,\n * PostgresAdapter,\n * PostgresIntrospector,\n * PostgresQueryCompiler\n * } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: {\n * createAdapter: () => new PostgresAdapter(),\n * createDriver: () => new DummyDriver(),\n * createIntrospector: (db: Kysely) => new PostgresIntrospector(db),\n * createQueryCompiler: () => new PostgresQueryCompiler(),\n * },\n * })\n * ```\n *\n * You can use it to build a query and compile it to SQL but trying to\n * execute the query will throw an error.\n *\n * ```ts\n * const { sql } = db.selectFrom('person').selectAll().compile()\n * console.log(sql) // select * from \"person\"\n * ```\n */\nexport class DummyDriver {\n async init() {\n // Nothing to do here.\n }\n async acquireConnection() {\n return new DummyConnection();\n }\n async beginTransaction() {\n // Nothing to do here.\n }\n async commitTransaction() {\n // Nothing to do here.\n }\n async rollbackTransaction() {\n // Nothing to do here.\n }\n async releaseConnection() {\n // Nothing to do here.\n }\n async destroy() {\n // Nothing to do here.\n }\n async releaseSavepoint() {\n // Nothing to do here.\n }\n async rollbackToSavepoint() {\n // Nothing to do here.\n }\n async savepoint() {\n // Nothing to do here.\n }\n}\nclass DummyConnection {\n async executeQuery() {\n return {\n rows: [],\n };\n }\n async *streamQuery() {\n // Nothing to do here.\n }\n}\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \n/**\n * A basic implementation of `DialectAdapter` with sensible default values.\n * Third-party dialects can extend this instead of implementing the `DialectAdapter`\n * interface from scratch. That way all new settings will get default values when\n * they are added and there will be less breaking changes.\n */\nexport class DialectAdapterBase {\n get supportsCreateIfNotExists() {\n return true;\n }\n get supportsTransactionalDdl() {\n return false;\n }\n get supportsReturning() {\n return false;\n }\n get supportsOutput() {\n return false;\n }\n}\n", "/// \nexport {};\n", "/// \nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nexport function parseSavepointCommand(command, savepointName) {\n return RawNode.createWithChildren([\n RawNode.createWithSql(`${command} `),\n IdentifierNode.create(savepointName), // ensures savepointName gets sanitized\n ]);\n}\n", "/// \nimport { SelectQueryNode } from '../../operation-node/select-query-node.js';\nimport { parseSavepointCommand } from '../../parser/savepoint-parser.js';\nimport { CompiledQuery } from '../../query-compiler/compiled-query.js';\nimport { freeze, isFunction } from '../../util/object-utils.js';\nimport { createQueryId } from '../../util/query-id.js';\nexport class SqliteDriver {\n #config;\n #connectionMutex = new ConnectionMutex();\n #db;\n #connection;\n constructor(config) {\n this.#config = freeze({ ...config });\n }\n async init() {\n this.#db = isFunction(this.#config.database)\n ? await this.#config.database()\n : this.#config.database;\n this.#connection = new SqliteConnection(this.#db);\n if (this.#config.onCreateConnection) {\n await this.#config.onCreateConnection(this.#connection);\n }\n }\n async acquireConnection() {\n // SQLite only has one single connection. We use a mutex here to wait\n // until the single connection has been released.\n await this.#connectionMutex.lock();\n return this.#connection;\n }\n async beginTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('begin'));\n }\n async commitTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('commit'));\n }\n async rollbackTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('rollback'));\n }\n async savepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('savepoint', savepointName), createQueryId()));\n }\n async rollbackToSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('rollback to', savepointName), createQueryId()));\n }\n async releaseSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('release', savepointName), createQueryId()));\n }\n async releaseConnection() {\n this.#connectionMutex.unlock();\n }\n async destroy() {\n this.#db?.close();\n }\n}\nclass SqliteConnection {\n #db;\n constructor(db) {\n this.#db = db;\n }\n executeQuery(compiledQuery) {\n const { sql, parameters } = compiledQuery;\n const stmt = this.#db.prepare(sql);\n if (stmt.reader) {\n return Promise.resolve({\n rows: stmt.all(parameters),\n });\n }\n const { changes, lastInsertRowid } = stmt.run(parameters);\n return Promise.resolve({\n numAffectedRows: changes !== undefined && changes !== null ? BigInt(changes) : undefined,\n insertId: lastInsertRowid !== undefined && lastInsertRowid !== null\n ? BigInt(lastInsertRowid)\n : undefined,\n rows: [],\n });\n }\n async *streamQuery(compiledQuery, _chunkSize) {\n const { sql, parameters, query } = compiledQuery;\n const stmt = this.#db.prepare(sql);\n if (SelectQueryNode.is(query)) {\n const iter = stmt.iterate(parameters);\n for (const row of iter) {\n yield {\n rows: [row],\n };\n }\n }\n else {\n throw new Error('Sqlite driver only supports streaming of select queries');\n }\n }\n}\nclass ConnectionMutex {\n #promise;\n #resolve;\n async lock() {\n while (this.#promise) {\n await this.#promise;\n }\n this.#promise = new Promise((resolve) => {\n this.#resolve = resolve;\n });\n }\n unlock() {\n const resolve = this.#resolve;\n this.#promise = undefined;\n this.#resolve = undefined;\n resolve?.();\n }\n}\n", "/// \nimport { DefaultQueryCompiler } from '../../query-compiler/default-query-compiler.js';\nconst ID_WRAP_REGEX = /\"/g;\nexport class SqliteQueryCompiler extends DefaultQueryCompiler {\n visitOrAction(node) {\n this.append('or ');\n this.append(node.action);\n }\n getCurrentParameterPlaceholder() {\n return '?';\n }\n getLeftExplainOptionsWrapper() {\n return '';\n }\n getRightExplainOptionsWrapper() {\n return '';\n }\n getLeftIdentifierWrapper() {\n return '\"';\n }\n getRightIdentifierWrapper() {\n return '\"';\n }\n getAutoIncrement() {\n return 'autoincrement';\n }\n sanitizeIdentifier(identifier) {\n return identifier.replace(ID_WRAP_REGEX, '\"\"');\n }\n visitDefaultInsertValue(_) {\n // sqlite doesn't support the `default` keyword in inserts.\n this.append('null');\n }\n}\n", "/// \nimport { NoopPlugin } from '../plugin/noop-plugin.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { freeze, getLast, isObject } from '../util/object-utils.js';\nexport const DEFAULT_MIGRATION_TABLE = 'kysely_migration';\nexport const DEFAULT_MIGRATION_LOCK_TABLE = 'kysely_migration_lock';\nexport const DEFAULT_ALLOW_UNORDERED_MIGRATIONS = false;\nexport const MIGRATION_LOCK_ID = 'migration_lock';\nexport const NO_MIGRATIONS = freeze({ __noMigrations__: true });\n/**\n * A class for running migrations.\n *\n * ### Example\n *\n * This example uses the {@link FileMigrationProvider} that reads migrations\n * files from a single folder. You can easily implement your own\n * {@link MigrationProvider} if you want to provide migrations some\n * other way.\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import * as Sqlite from 'better-sqlite3'\n * import {\n * FileMigrationProvider,\n * Kysely,\n * Migrator,\n * SqliteDialect\n * } from 'kysely'\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: Sqlite(':memory:')\n * })\n * })\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n * ```\n */\nexport class Migrator {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Returns a {@link MigrationInfo} object for each migration.\n *\n * The returned array is sorted by migration name.\n */\n async getMigrations() {\n const tableExists = await this.#doesTableExist(this.#migrationTable);\n const executedMigrations = tableExists\n ? await this.#props.db\n .withPlugin(this.#schemaPlugin)\n .selectFrom(this.#migrationTable)\n .select(['name', 'timestamp'])\n .$narrowType()\n .execute()\n : [];\n const migrations = await this.#resolveMigrations();\n return migrations.map(({ name, ...migration }) => {\n const executed = executedMigrations.find((it) => it.name === name);\n return {\n name,\n migration,\n executedAt: executed ? new Date(executed.timestamp) : undefined,\n };\n });\n }\n /**\n * Runs all migrations that have not yet been run.\n *\n * This method returns a {@link MigrationResultSet} instance and _never_ throws.\n * {@link MigrationResultSet.error} holds the error if something went wrong.\n * {@link MigrationResultSet.results} contains information about which migrations\n * were executed and which failed. See the examples below.\n *\n * This method goes through all possible migrations provided by the provider and runs the\n * ones whose names come alphabetically after the last migration that has been run. If the\n * list of executed migrations doesn't match the beginning of the list of possible migrations\n * an error is returned.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import * as Sqlite from 'better-sqlite3'\n * import { FileMigrationProvider, Migrator } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * const { error, results } = await migrator.migrateToLatest()\n *\n * results?.forEach((it) => {\n * if (it.status === 'Success') {\n * console.log(`migration \"${it.migrationName}\" was executed successfully`)\n * } else if (it.status === 'Error') {\n * console.error(`failed to execute migration \"${it.migrationName}\"`)\n * }\n * })\n *\n * if (error) {\n * console.error('failed to run `migrateToLatest`')\n * console.error(error)\n * }\n * ```\n */\n async migrateToLatest() {\n return this.#migrate(() => ({ direction: 'Up', step: Infinity }));\n }\n /**\n * Migrate up/down to a specific migration.\n *\n * This method returns a {@link MigrationResultSet} instance and _never_ throws.\n * {@link MigrationResultSet.error} holds the error if something went wrong.\n * {@link MigrationResultSet.results} contains information about which migrations\n * were executed and which failed.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import { FileMigrationProvider, Migrator } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * await migrator.migrateTo('some_migration')\n * ```\n *\n * If you specify the name of the first migration, this method migrates\n * down to the first migration, but doesn't run the `down` method of\n * the first migration. In case you want to migrate all the way down,\n * you can use a special constant `NO_MIGRATIONS`:\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import { FileMigrationProvider, Migrator, NO_MIGRATIONS } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * await migrator.migrateTo(NO_MIGRATIONS)\n * ```\n */\n async migrateTo(targetMigrationName) {\n return this.#migrate(({ migrations, executedMigrations, pendingMigrations, }) => {\n if (isObject(targetMigrationName) &&\n targetMigrationName.__noMigrations__ === true) {\n return { direction: 'Down', step: Infinity };\n }\n if (!migrations.find((m) => m.name === targetMigrationName)) {\n throw new Error(`migration \"${targetMigrationName}\" doesn't exist`);\n }\n const executedIndex = executedMigrations.indexOf(targetMigrationName);\n const pendingIndex = pendingMigrations.findIndex((m) => m.name === targetMigrationName);\n if (executedIndex !== -1) {\n return {\n direction: 'Down',\n step: executedMigrations.length - executedIndex - 1,\n };\n }\n else if (pendingIndex !== -1) {\n return { direction: 'Up', step: pendingIndex + 1 };\n }\n else {\n throw new Error(`migration \"${targetMigrationName}\" isn't executed or pending`);\n }\n });\n }\n /**\n * Migrate one step up.\n *\n * This method returns a {@link MigrationResultSet} instance and _never_ throws.\n * {@link MigrationResultSet.error} holds the error if something went wrong.\n * {@link MigrationResultSet.results} contains information about which migrations\n * were executed and which failed.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import { FileMigrationProvider, Migrator } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * await migrator.migrateUp()\n * ```\n */\n async migrateUp() {\n return this.#migrate(() => ({ direction: 'Up', step: 1 }));\n }\n /**\n * Migrate one step down.\n *\n * This method returns a {@link MigrationResultSet} instance and _never_ throws.\n * {@link MigrationResultSet.error} holds the error if something went wrong.\n * {@link MigrationResultSet.results} contains information about which migrations\n * were executed and which failed.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import { FileMigrationProvider, Migrator } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * await migrator.migrateDown()\n * ```\n */\n async migrateDown() {\n return this.#migrate(() => ({ direction: 'Down', step: 1 }));\n }\n async #migrate(getMigrationDirectionAndStep) {\n try {\n await this.#ensureMigrationTableSchemaExists();\n await this.#ensureMigrationTableExists();\n await this.#ensureMigrationLockTableExists();\n await this.#ensureLockRowExists();\n return await this.#runMigrations(getMigrationDirectionAndStep);\n }\n catch (error) {\n if (error instanceof MigrationResultSetError) {\n return error.resultSet;\n }\n return { error };\n }\n }\n get #migrationTableSchema() {\n return this.#props.migrationTableSchema;\n }\n get #migrationTable() {\n return this.#props.migrationTableName ?? DEFAULT_MIGRATION_TABLE;\n }\n get #migrationLockTable() {\n return this.#props.migrationLockTableName ?? DEFAULT_MIGRATION_LOCK_TABLE;\n }\n get #allowUnorderedMigrations() {\n return (this.#props.allowUnorderedMigrations ?? DEFAULT_ALLOW_UNORDERED_MIGRATIONS);\n }\n get #schemaPlugin() {\n if (this.#migrationTableSchema) {\n return new WithSchemaPlugin(this.#migrationTableSchema);\n }\n return new NoopPlugin();\n }\n async #ensureMigrationTableSchemaExists() {\n if (!this.#migrationTableSchema) {\n // Use default schema. Nothing to do.\n return;\n }\n const schemaExists = await this.#doesSchemaExist();\n if (schemaExists) {\n return;\n }\n try {\n await this.#createIfNotExists(this.#props.db.schema.createSchema(this.#migrationTableSchema));\n }\n catch (error) {\n const schemaExists = await this.#doesSchemaExist();\n // At least on PostgreSQL, `if not exists` doesn't guarantee the `create schema`\n // query doesn't throw if the schema already exits. That's why we check if\n // the schema exist here and ignore the error if it does.\n if (!schemaExists) {\n throw error;\n }\n }\n }\n async #ensureMigrationTableExists() {\n const tableExists = await this.#doesTableExist(this.#migrationTable);\n if (tableExists) {\n return;\n }\n try {\n await this.#createIfNotExists(this.#props.db.schema\n .withPlugin(this.#schemaPlugin)\n .createTable(this.#migrationTable)\n .addColumn('name', 'varchar(255)', (col) => col.notNull().primaryKey())\n // The migration run time as ISO string. This is not a real date type as we\n // can't know which data type is supported by all future dialects.\n .addColumn('timestamp', 'varchar(255)', (col) => col.notNull()));\n }\n catch (error) {\n const tableExists = await this.#doesTableExist(this.#migrationTable);\n // At least on PostgreSQL, `if not exists` doesn't guarantee the `create table`\n // query doesn't throw if the table already exits. That's why we check if\n // the table exist here and ignore the error if it does.\n if (!tableExists) {\n throw error;\n }\n }\n }\n async #ensureMigrationLockTableExists() {\n const tableExists = await this.#doesTableExist(this.#migrationLockTable);\n if (tableExists) {\n return;\n }\n try {\n await this.#createIfNotExists(this.#props.db.schema\n .withPlugin(this.#schemaPlugin)\n .createTable(this.#migrationLockTable)\n .addColumn('id', 'varchar(255)', (col) => col.notNull().primaryKey())\n .addColumn('is_locked', 'integer', (col) => col.notNull().defaultTo(0)));\n }\n catch (error) {\n const tableExists = await this.#doesTableExist(this.#migrationLockTable);\n // At least on PostgreSQL, `if not exists` doesn't guarantee the `create table`\n // query doesn't throw if the table already exits. That's why we check if\n // the table exist here and ignore the error if it does.\n if (!tableExists) {\n throw error;\n }\n }\n }\n async #ensureLockRowExists() {\n const lockRowExists = await this.#doesLockRowExists();\n if (lockRowExists) {\n return;\n }\n try {\n await this.#props.db\n .withPlugin(this.#schemaPlugin)\n .insertInto(this.#migrationLockTable)\n .values({ id: MIGRATION_LOCK_ID, is_locked: 0 })\n .execute();\n }\n catch (error) {\n const lockRowExists = await this.#doesLockRowExists();\n if (!lockRowExists) {\n throw error;\n }\n }\n }\n async #doesSchemaExist() {\n const schemas = await this.#props.db.introspection.getSchemas();\n return schemas.some((it) => it.name === this.#migrationTableSchema);\n }\n async #doesTableExist(tableName) {\n const schema = this.#migrationTableSchema;\n const tables = await this.#props.db.introspection.getTables({\n withInternalKyselyTables: true,\n });\n return tables.some((it) => it.name === tableName && (!schema || it.schema === schema));\n }\n async #doesLockRowExists() {\n const lockRow = await this.#props.db\n .withPlugin(this.#schemaPlugin)\n .selectFrom(this.#migrationLockTable)\n .where('id', '=', MIGRATION_LOCK_ID)\n .select('id')\n .executeTakeFirst();\n return !!lockRow;\n }\n async #runMigrations(getMigrationDirectionAndStep) {\n const adapter = this.#props.db.getExecutor().adapter;\n const lockOptions = freeze({\n lockTable: this.#props.migrationLockTableName ?? DEFAULT_MIGRATION_LOCK_TABLE,\n lockRowId: MIGRATION_LOCK_ID,\n lockTableSchema: this.#props.migrationTableSchema,\n });\n const run = async (db) => {\n try {\n await adapter.acquireMigrationLock(db, lockOptions);\n const state = await this.#getState(db);\n if (state.migrations.length === 0) {\n return { results: [] };\n }\n const { direction, step } = getMigrationDirectionAndStep(state);\n if (step <= 0) {\n return { results: [] };\n }\n if (direction === 'Down') {\n return await this.#migrateDown(db, state, step);\n }\n else if (direction === 'Up') {\n return await this.#migrateUp(db, state, step);\n }\n return { results: [] };\n }\n finally {\n await adapter.releaseMigrationLock(db, lockOptions);\n }\n };\n if (adapter.supportsTransactionalDdl && !this.#props.disableTransactions) {\n return this.#props.db.transaction().execute(run);\n }\n else {\n return this.#props.db.connection().execute(run);\n }\n }\n async #getState(db) {\n const migrations = await this.#resolveMigrations();\n const executedMigrations = await this.#getExecutedMigrations(db);\n this.#ensureNoMissingMigrations(migrations, executedMigrations);\n if (!this.#allowUnorderedMigrations) {\n this.#ensureMigrationsInOrder(migrations, executedMigrations);\n }\n const pendingMigrations = this.#getPendingMigrations(migrations, executedMigrations);\n return freeze({\n migrations,\n executedMigrations,\n lastMigration: getLast(executedMigrations),\n pendingMigrations,\n });\n }\n #getPendingMigrations(migrations, executedMigrations) {\n return migrations.filter((migration) => {\n return !executedMigrations.includes(migration.name);\n });\n }\n async #resolveMigrations() {\n const allMigrations = await this.#props.provider.getMigrations();\n return Object.keys(allMigrations)\n .sort()\n .map((name) => ({\n ...allMigrations[name],\n name,\n }));\n }\n async #getExecutedMigrations(db) {\n const executedMigrations = await db\n .withPlugin(this.#schemaPlugin)\n .selectFrom(this.#migrationTable)\n .select(['name', 'timestamp'])\n .$narrowType()\n .execute();\n const nameComparator = this.#props.nameComparator || ((a, b) => a.localeCompare(b));\n return (executedMigrations\n // https://github.com/kysely-org/kysely/issues/843\n .sort((a, b) => {\n if (a.timestamp === b.timestamp) {\n return nameComparator(a.name, b.name);\n }\n return (new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());\n })\n .map((it) => it.name));\n }\n #ensureNoMissingMigrations(migrations, executedMigrations) {\n // Ensure all executed migrations exist in the `migrations` list.\n for (const executed of executedMigrations) {\n if (!migrations.some((it) => it.name === executed)) {\n throw new Error(`corrupted migrations: previously executed migration ${executed} is missing`);\n }\n }\n }\n #ensureMigrationsInOrder(migrations, executedMigrations) {\n // Ensure the executed migrations are the first ones in the migration list.\n for (let i = 0; i < executedMigrations.length; ++i) {\n if (migrations[i].name !== executedMigrations[i]) {\n throw new Error(`corrupted migrations: expected previously executed migration ${executedMigrations[i]} to be at index ${i} but ${migrations[i].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`);\n }\n }\n }\n async #migrateDown(db, state, step) {\n const migrationsToRollback = state.executedMigrations\n .slice()\n .reverse()\n .slice(0, step)\n .map((name) => {\n return state.migrations.find((it) => it.name === name);\n });\n const results = migrationsToRollback.map((migration) => {\n return {\n migrationName: migration.name,\n direction: 'Down',\n status: 'NotExecuted',\n };\n });\n for (let i = 0; i < results.length; ++i) {\n const migration = migrationsToRollback[i];\n try {\n if (migration.down) {\n await migration.down(db);\n await db\n .withPlugin(this.#schemaPlugin)\n .deleteFrom(this.#migrationTable)\n .where('name', '=', migration.name)\n .execute();\n results[i] = {\n migrationName: migration.name,\n direction: 'Down',\n status: 'Success',\n };\n }\n }\n catch (error) {\n results[i] = {\n migrationName: migration.name,\n direction: 'Down',\n status: 'Error',\n };\n throw new MigrationResultSetError({\n error,\n results,\n });\n }\n }\n return { results };\n }\n async #migrateUp(db, state, step) {\n const migrationsToRun = state.pendingMigrations.slice(0, step);\n const results = migrationsToRun.map((migration) => {\n return {\n migrationName: migration.name,\n direction: 'Up',\n status: 'NotExecuted',\n };\n });\n for (let i = 0; i < results.length; i++) {\n const migration = state.pendingMigrations[i];\n try {\n await migration.up(db);\n await db\n .withPlugin(this.#schemaPlugin)\n .insertInto(this.#migrationTable)\n .values({\n name: migration.name,\n timestamp: new Date().toISOString(),\n })\n .execute();\n results[i] = {\n migrationName: migration.name,\n direction: 'Up',\n status: 'Success',\n };\n }\n catch (error) {\n results[i] = {\n migrationName: migration.name,\n direction: 'Up',\n status: 'Error',\n };\n throw new MigrationResultSetError({\n error,\n results,\n });\n }\n }\n return { results };\n }\n async #createIfNotExists(qb) {\n if (this.#props.db.getExecutor().adapter.supportsCreateIfNotExists) {\n qb = qb.ifNotExists();\n }\n await qb.execute();\n }\n}\nclass MigrationResultSetError extends Error {\n #resultSet;\n constructor(result) {\n super();\n this.#resultSet = result;\n }\n get resultSet() {\n return this.#resultSet;\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';\nimport { sql } from '../../raw-builder/sql.js';\nexport class SqliteIntrospector {\n #db;\n constructor(db) {\n this.#db = db;\n }\n async getSchemas() {\n // Sqlite doesn't support schemas.\n return [];\n }\n async getTables(options = { withInternalKyselyTables: false }) {\n return await this.#getTableMetadata(options);\n }\n async getMetadata(options) {\n return {\n tables: await this.getTables(options),\n };\n }\n #tablesQuery(qb, options) {\n let tablesQuery = qb\n .selectFrom('sqlite_master')\n .where('type', 'in', ['table', 'view'])\n .where('name', 'not like', 'sqlite_%')\n .select(['name', 'sql', 'type'])\n .orderBy('name');\n if (!options.withInternalKyselyTables) {\n tablesQuery = tablesQuery\n .where('name', '!=', DEFAULT_MIGRATION_TABLE)\n .where('name', '!=', DEFAULT_MIGRATION_LOCK_TABLE);\n }\n return tablesQuery;\n }\n async #getTableMetadata(options) {\n const tablesResult = await this.#tablesQuery(this.#db, options).execute();\n const tableMetadata = await this.#db\n .with('table_list', (qb) => this.#tablesQuery(qb, options))\n .selectFrom([\n 'table_list as tl',\n sql `pragma_table_info(tl.name)`.as('p'),\n ])\n .select([\n 'tl.name as table',\n 'p.cid',\n 'p.name',\n 'p.type',\n 'p.notnull',\n 'p.dflt_value',\n 'p.pk',\n ])\n .orderBy('tl.name')\n .orderBy('p.cid')\n .execute();\n const columnsByTable = {};\n for (const row of tableMetadata) {\n columnsByTable[row.table] ??= [];\n columnsByTable[row.table].push(row);\n }\n return tablesResult.map(({ name, sql, type }) => {\n // // Try to find the name of the column that has `autoincrement` \uD83E\uDD26\n let autoIncrementCol = sql\n ?.split(/[\\(\\),]/)\n ?.find((it) => it.toLowerCase().includes('autoincrement'))\n ?.trimStart()\n ?.split(/\\s+/)?.[0]\n ?.replace(/[\"`]/g, '');\n const columns = columnsByTable[name] ?? [];\n // Otherwise, check for an INTEGER PRIMARY KEY\n // https://www.sqlite.org/autoinc.html\n if (!autoIncrementCol) {\n const pkCols = columns.filter((r) => r.pk > 0);\n if (pkCols.length === 1 && pkCols[0].type.toLowerCase() === 'integer') {\n autoIncrementCol = pkCols[0].name;\n }\n }\n return {\n name: name,\n isView: type === 'view',\n columns: columns.map((col) => ({\n name: col.name,\n dataType: col.type,\n isNullable: !col.notnull,\n isAutoIncrementing: col.name === autoIncrementCol,\n hasDefaultValue: col.dflt_value != null,\n comment: undefined,\n })),\n };\n });\n }\n}\n", "/// \nimport { DialectAdapterBase } from '../dialect-adapter-base.js';\nexport class SqliteAdapter extends DialectAdapterBase {\n get supportsTransactionalDdl() {\n return false;\n }\n get supportsReturning() {\n return true;\n }\n async acquireMigrationLock(_db, _opt) {\n // SQLite only has one connection that's reserved by the migration system\n // for the whole time between acquireMigrationLock and releaseMigrationLock.\n // We don't need to do anything here.\n }\n async releaseMigrationLock(_db, _opt) {\n // SQLite only has one connection that's reserved by the migration system\n // for the whole time between acquireMigrationLock and releaseMigrationLock.\n // We don't need to do anything here.\n }\n}\n", "/// \nimport { SqliteDriver } from './sqlite-driver.js';\nimport { SqliteQueryCompiler } from './sqlite-query-compiler.js';\nimport { SqliteIntrospector } from './sqlite-introspector.js';\nimport { SqliteAdapter } from './sqlite-adapter.js';\nimport { freeze } from '../../util/object-utils.js';\n/**\n * SQLite dialect that uses the [better-sqlite3](https://github.com/JoshuaWise/better-sqlite3) library.\n *\n * The constructor takes an instance of {@link SqliteDialectConfig}.\n *\n * ```ts\n * import Database from 'better-sqlite3'\n *\n * new SqliteDialect({\n * database: new Database('db.sqlite')\n * })\n * ```\n *\n * If you want the pool to only be created once it's first used, `database`\n * can be a function:\n *\n * ```ts\n * import Database from 'better-sqlite3'\n *\n * new SqliteDialect({\n * database: async () => new Database('db.sqlite')\n * })\n * ```\n */\nexport class SqliteDialect {\n #config;\n constructor(config) {\n this.#config = freeze({ ...config });\n }\n createDriver() {\n return new SqliteDriver(this.#config);\n }\n createQueryCompiler() {\n return new SqliteQueryCompiler();\n }\n createAdapter() {\n return new SqliteAdapter();\n }\n createIntrospector(db) {\n return new SqliteIntrospector(db);\n }\n}\n", "/// \nexport {};\n", "/// \nimport { DefaultQueryCompiler } from '../../query-compiler/default-query-compiler.js';\nconst ID_WRAP_REGEX = /\"/g;\nexport class PostgresQueryCompiler extends DefaultQueryCompiler {\n sanitizeIdentifier(identifier) {\n return identifier.replace(ID_WRAP_REGEX, '\"\"');\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';\nimport { freeze } from '../../util/object-utils.js';\nimport { sql } from '../../raw-builder/sql.js';\nexport class PostgresIntrospector {\n #db;\n constructor(db) {\n this.#db = db;\n }\n async getSchemas() {\n let rawSchemas = await this.#db\n .selectFrom('pg_catalog.pg_namespace')\n .select('nspname')\n .$castTo()\n .execute();\n return rawSchemas.map((it) => ({ name: it.nspname }));\n }\n async getTables(options = { withInternalKyselyTables: false }) {\n let query = this.#db\n // column\n .selectFrom('pg_catalog.pg_attribute as a')\n // table\n .innerJoin('pg_catalog.pg_class as c', 'a.attrelid', 'c.oid')\n // table schema\n .innerJoin('pg_catalog.pg_namespace as ns', 'c.relnamespace', 'ns.oid')\n // column data type\n .innerJoin('pg_catalog.pg_type as typ', 'a.atttypid', 'typ.oid')\n // column data type schema\n .innerJoin('pg_catalog.pg_namespace as dtns', 'typ.typnamespace', 'dtns.oid')\n .select([\n 'a.attname as column',\n 'a.attnotnull as not_null',\n 'a.atthasdef as has_default',\n 'c.relname as table',\n 'c.relkind as table_type',\n 'ns.nspname as schema',\n 'typ.typname as type',\n 'dtns.nspname as type_schema',\n sql `col_description(a.attrelid, a.attnum)`.as('column_description'),\n sql `pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as('auto_incrementing'),\n ])\n .where('c.relkind', 'in', [\n 'r' /*regular table*/,\n 'v' /*view*/,\n 'p' /*partitioned table*/,\n ])\n .where('ns.nspname', '!~', '^pg_')\n .where('ns.nspname', '!=', 'information_schema')\n // Filter out internal cockroachdb schema\n .where('ns.nspname', '!=', 'crdb_internal')\n // Only schemas where we are allowed access\n .where(sql `has_schema_privilege(ns.nspname, 'USAGE')`)\n // No system columns\n .where('a.attnum', '>=', 0)\n .where('a.attisdropped', '!=', true)\n .orderBy('ns.nspname')\n .orderBy('c.relname')\n .orderBy('a.attnum')\n .$castTo();\n if (!options.withInternalKyselyTables) {\n query = query\n .where('c.relname', '!=', DEFAULT_MIGRATION_TABLE)\n .where('c.relname', '!=', DEFAULT_MIGRATION_LOCK_TABLE);\n }\n const rawColumns = await query.execute();\n return this.#parseTableMetadata(rawColumns);\n }\n async getMetadata(options) {\n return {\n tables: await this.getTables(options),\n };\n }\n #parseTableMetadata(columns) {\n const tableDictionary = new Map();\n for (let i = 0, len = columns.length; i < len; i++) {\n const column = columns[i];\n const { schema, table } = column;\n const tableKey = `schema:${schema};table:${table}`;\n if (!tableDictionary.has(tableKey)) {\n tableDictionary.set(tableKey, freeze({\n columns: [],\n isView: column.table_type === 'v',\n name: table,\n schema,\n }));\n }\n tableDictionary.get(tableKey).columns.push(freeze({\n comment: column.column_description ?? undefined,\n dataType: column.type,\n dataTypeSchema: column.type_schema,\n hasDefaultValue: column.has_default,\n isAutoIncrementing: column.auto_incrementing !== null,\n isNullable: !column.not_null,\n name: column.column,\n }));\n }\n return Array.from(tableDictionary.values());\n }\n}\n", "/// \nimport { sql } from '../../raw-builder/sql.js';\nimport { DialectAdapterBase } from '../dialect-adapter-base.js';\n// Random id for our transaction lock.\nconst LOCK_ID = BigInt('3853314791062309107');\nexport class PostgresAdapter extends DialectAdapterBase {\n get supportsTransactionalDdl() {\n return true;\n }\n get supportsReturning() {\n return true;\n }\n async acquireMigrationLock(db, _opt) {\n // Acquire a transaction level advisory lock.\n await sql `select pg_advisory_xact_lock(${sql.lit(LOCK_ID)})`.execute(db);\n }\n async releaseMigrationLock(_db, _opt) {\n // Nothing to do here. `pg_advisory_xact_lock` is automatically released at the\n // end of the transaction and since `supportsTransactionalDdl` true, we know\n // the `db` instance passed to acquireMigrationLock is actually a transaction.\n }\n}\n", "/// \nimport { isObject, isString } from './object-utils.js';\nexport function extendStackTrace(err, stackError) {\n if (isStackHolder(err) && stackError.stack) {\n // Remove the first line that just says `Error`.\n const stackExtension = stackError.stack.split('\\n').slice(1).join('\\n');\n err.stack += `\\n${stackExtension}`;\n return err;\n }\n return err;\n}\nfunction isStackHolder(obj) {\n return isObject(obj) && isString(obj.stack);\n}\n", "/// \nimport { parseSavepointCommand } from '../../parser/savepoint-parser.js';\nimport { CompiledQuery } from '../../query-compiler/compiled-query.js';\nimport { isFunction, isObject, freeze } from '../../util/object-utils.js';\nimport { createQueryId } from '../../util/query-id.js';\nimport { extendStackTrace } from '../../util/stack-trace-utils.js';\nconst PRIVATE_RELEASE_METHOD = Symbol();\nexport class MysqlDriver {\n #config;\n #connections = new WeakMap();\n #pool;\n constructor(configOrPool) {\n this.#config = freeze({ ...configOrPool });\n }\n async init() {\n this.#pool = isFunction(this.#config.pool)\n ? await this.#config.pool()\n : this.#config.pool;\n }\n async acquireConnection() {\n const rawConnection = await this.#acquireConnection();\n let connection = this.#connections.get(rawConnection);\n if (!connection) {\n connection = new MysqlConnection(rawConnection);\n this.#connections.set(rawConnection, connection);\n // The driver must take care of calling `onCreateConnection` when a new\n // connection is created. The `mysql2` module doesn't provide an async hook\n // for the connection creation. We need to call the method explicitly.\n if (this.#config?.onCreateConnection) {\n await this.#config.onCreateConnection(connection);\n }\n }\n if (this.#config?.onReserveConnection) {\n await this.#config.onReserveConnection(connection);\n }\n return connection;\n }\n async #acquireConnection() {\n return new Promise((resolve, reject) => {\n this.#pool.getConnection(async (err, rawConnection) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(rawConnection);\n }\n });\n });\n }\n async beginTransaction(connection, settings) {\n if (settings.isolationLevel || settings.accessMode) {\n const parts = [];\n if (settings.isolationLevel) {\n parts.push(`isolation level ${settings.isolationLevel}`);\n }\n if (settings.accessMode) {\n parts.push(settings.accessMode);\n }\n const sql = `set transaction ${parts.join(', ')}`;\n // On MySQL this sets the isolation level of the next transaction.\n await connection.executeQuery(CompiledQuery.raw(sql));\n }\n await connection.executeQuery(CompiledQuery.raw('begin'));\n }\n async commitTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('commit'));\n }\n async rollbackTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('rollback'));\n }\n async savepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('savepoint', savepointName), createQueryId()));\n }\n async rollbackToSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('rollback to', savepointName), createQueryId()));\n }\n async releaseSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('release savepoint', savepointName), createQueryId()));\n }\n async releaseConnection(connection) {\n connection[PRIVATE_RELEASE_METHOD]();\n }\n async destroy() {\n return new Promise((resolve, reject) => {\n this.#pool.end((err) => {\n if (err) {\n reject(err);\n }\n else {\n resolve();\n }\n });\n });\n }\n}\nfunction isOkPacket(obj) {\n return isObject(obj) && 'insertId' in obj && 'affectedRows' in obj;\n}\nclass MysqlConnection {\n #rawConnection;\n constructor(rawConnection) {\n this.#rawConnection = rawConnection;\n }\n async executeQuery(compiledQuery) {\n try {\n const result = await this.#executeQuery(compiledQuery);\n if (isOkPacket(result)) {\n const { insertId, affectedRows, changedRows } = result;\n return {\n insertId: insertId !== undefined &&\n insertId !== null &&\n insertId.toString() !== '0'\n ? BigInt(insertId)\n : undefined,\n numAffectedRows: affectedRows !== undefined && affectedRows !== null\n ? BigInt(affectedRows)\n : undefined,\n numChangedRows: changedRows !== undefined && changedRows !== null\n ? BigInt(changedRows)\n : undefined,\n rows: [],\n };\n }\n else if (Array.isArray(result)) {\n return {\n rows: result,\n };\n }\n return {\n rows: [],\n };\n }\n catch (err) {\n throw extendStackTrace(err, new Error());\n }\n }\n #executeQuery(compiledQuery) {\n return new Promise((resolve, reject) => {\n this.#rawConnection.query(compiledQuery.sql, compiledQuery.parameters, (err, result) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(result);\n }\n });\n });\n }\n async *streamQuery(compiledQuery, _chunkSize) {\n const stream = this.#rawConnection\n .query(compiledQuery.sql, compiledQuery.parameters)\n .stream({\n objectMode: true,\n });\n try {\n for await (const row of stream) {\n yield {\n rows: [row],\n };\n }\n }\n catch (ex) {\n if (ex &&\n typeof ex === 'object' &&\n 'code' in ex &&\n // @ts-ignore\n ex.code === 'ERR_STREAM_PREMATURE_CLOSE') {\n // Most likely because of https://github.com/mysqljs/mysql/blob/master/lib/protocol/sequences/Query.js#L220\n return;\n }\n throw ex;\n }\n }\n [PRIVATE_RELEASE_METHOD]() {\n this.#rawConnection.release();\n }\n}\n", "/// \nimport { DefaultQueryCompiler } from '../../query-compiler/default-query-compiler.js';\nconst LITERAL_ESCAPE_REGEX = /\\\\|'/g;\nconst ID_WRAP_REGEX = /`/g;\nexport class MysqlQueryCompiler extends DefaultQueryCompiler {\n getCurrentParameterPlaceholder() {\n return '?';\n }\n getLeftExplainOptionsWrapper() {\n return '';\n }\n getExplainOptionAssignment() {\n return '=';\n }\n getExplainOptionsDelimiter() {\n return ' ';\n }\n getRightExplainOptionsWrapper() {\n return '';\n }\n getLeftIdentifierWrapper() {\n return ID_WRAP_REGEX.source;\n }\n getRightIdentifierWrapper() {\n return ID_WRAP_REGEX.source;\n }\n sanitizeIdentifier(identifier) {\n return identifier.replace(ID_WRAP_REGEX, '``');\n }\n /**\n * MySQL requires escaping backslashes in string literals when using the\n * default NO_BACKSLASH_ESCAPES=OFF mode. Without this, a backslash\n * followed by a quote (\\') can break out of the string literal.\n *\n * @see https://dev.mysql.com/doc/refman/9.6/en/string-literals.html\n */\n sanitizeStringLiteral(value) {\n return value.replace(LITERAL_ESCAPE_REGEX, (char) => char === '\\\\' ? '\\\\\\\\' : \"''\");\n }\n visitCreateIndex(node) {\n this.append('create ');\n if (node.unique) {\n this.append('unique ');\n }\n this.append('index ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.name);\n if (node.using) {\n this.append(' using ');\n this.visitNode(node.using);\n }\n if (node.table) {\n this.append(' on ');\n this.visitNode(node.table);\n }\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';\nimport { freeze } from '../../util/object-utils.js';\nimport { sql } from '../../raw-builder/sql.js';\nexport class MysqlIntrospector {\n #db;\n constructor(db) {\n this.#db = db;\n }\n async getSchemas() {\n let rawSchemas = await this.#db\n .selectFrom('information_schema.schemata')\n .select('schema_name')\n .$castTo()\n .execute();\n return rawSchemas.map((it) => ({ name: it.SCHEMA_NAME }));\n }\n async getTables(options = { withInternalKyselyTables: false }) {\n let query = this.#db\n .selectFrom('information_schema.columns as columns')\n .innerJoin('information_schema.tables as tables', (b) => b\n .onRef('columns.TABLE_CATALOG', '=', 'tables.TABLE_CATALOG')\n .onRef('columns.TABLE_SCHEMA', '=', 'tables.TABLE_SCHEMA')\n .onRef('columns.TABLE_NAME', '=', 'tables.TABLE_NAME'))\n .select([\n 'columns.COLUMN_NAME',\n 'columns.COLUMN_DEFAULT',\n 'columns.TABLE_NAME',\n 'columns.TABLE_SCHEMA',\n 'tables.TABLE_TYPE',\n 'columns.IS_NULLABLE',\n 'columns.DATA_TYPE',\n 'columns.EXTRA',\n 'columns.COLUMN_COMMENT',\n ])\n .where('columns.TABLE_SCHEMA', '=', sql `database()`)\n .orderBy('columns.TABLE_NAME')\n .orderBy('columns.ORDINAL_POSITION')\n .$castTo();\n if (!options.withInternalKyselyTables) {\n query = query\n .where('columns.TABLE_NAME', '!=', DEFAULT_MIGRATION_TABLE)\n .where('columns.TABLE_NAME', '!=', DEFAULT_MIGRATION_LOCK_TABLE);\n }\n const rawColumns = await query.execute();\n return this.#parseTableMetadata(rawColumns);\n }\n async getMetadata(options) {\n return {\n tables: await this.getTables(options),\n };\n }\n #parseTableMetadata(columns) {\n return columns.reduce((tables, it) => {\n let table = tables.find((tbl) => tbl.name === it.TABLE_NAME);\n if (!table) {\n table = freeze({\n name: it.TABLE_NAME,\n isView: it.TABLE_TYPE === 'VIEW',\n schema: it.TABLE_SCHEMA,\n columns: [],\n });\n tables.push(table);\n }\n table.columns.push(freeze({\n name: it.COLUMN_NAME,\n dataType: it.DATA_TYPE,\n isNullable: it.IS_NULLABLE === 'YES',\n isAutoIncrementing: it.EXTRA.toLowerCase().includes('auto_increment'),\n hasDefaultValue: it.COLUMN_DEFAULT !== null,\n comment: it.COLUMN_COMMENT === '' ? undefined : it.COLUMN_COMMENT,\n }));\n return tables;\n }, []);\n }\n}\n", "/// \nimport { sql } from '../../raw-builder/sql.js';\nimport { DialectAdapterBase } from '../dialect-adapter-base.js';\nconst LOCK_ID = 'ea586330-2c93-47c8-908d-981d9d270f9d';\nconst LOCK_TIMEOUT_SECONDS = 60 * 60;\nexport class MysqlAdapter extends DialectAdapterBase {\n get supportsTransactionalDdl() {\n return false;\n }\n get supportsReturning() {\n return false;\n }\n async acquireMigrationLock(db, _opt) {\n // Kysely uses a single connection to run the migrations. Because of that, we\n // can take a lock using `get_lock`. Locks acquired using `get_lock` get\n // released when the connection is destroyed (session ends) or when the lock\n // is released using `release_lock`. This way we know that the lock is either\n // released by us after successfull or failed migrations OR it's released by\n // MySQL if the process gets killed for some reason.\n await sql `select get_lock(${sql.lit(LOCK_ID)}, ${sql.lit(LOCK_TIMEOUT_SECONDS)})`.execute(db);\n }\n async releaseMigrationLock(db, _opt) {\n await sql `select release_lock(${sql.lit(LOCK_ID)})`.execute(db);\n }\n}\n", "/// \nimport { MysqlDriver } from './mysql-driver.js';\nimport { MysqlQueryCompiler } from './mysql-query-compiler.js';\nimport { MysqlIntrospector } from './mysql-introspector.js';\nimport { MysqlAdapter } from './mysql-adapter.js';\n/**\n * MySQL dialect that uses the [mysql2](https://github.com/sidorares/node-mysql2#readme) library.\n *\n * The constructor takes an instance of {@link MysqlDialectConfig}.\n *\n * ```ts\n * import { createPool } from 'mysql2'\n *\n * new MysqlDialect({\n * pool: createPool({\n * database: 'some_db',\n * host: 'localhost',\n * })\n * })\n * ```\n *\n * If you want the pool to only be created once it's first used, `pool`\n * can be a function:\n *\n * ```ts\n * import { createPool } from 'mysql2'\n *\n * new MysqlDialect({\n * pool: async () => createPool({\n * database: 'some_db',\n * host: 'localhost',\n * })\n * })\n * ```\n */\nexport class MysqlDialect {\n #config;\n constructor(config) {\n this.#config = config;\n }\n createDriver() {\n return new MysqlDriver(this.#config);\n }\n createQueryCompiler() {\n return new MysqlQueryCompiler();\n }\n createAdapter() {\n return new MysqlAdapter();\n }\n createIntrospector(db) {\n return new MysqlIntrospector(db);\n }\n}\n", "/// \nexport {};\n", "/// \nimport { parseSavepointCommand } from '../../parser/savepoint-parser.js';\nimport { CompiledQuery } from '../../query-compiler/compiled-query.js';\nimport { isFunction, freeze } from '../../util/object-utils.js';\nimport { createQueryId } from '../../util/query-id.js';\nimport { extendStackTrace } from '../../util/stack-trace-utils.js';\nconst PRIVATE_RELEASE_METHOD = Symbol();\nexport class PostgresDriver {\n #config;\n #connections = new WeakMap();\n #pool;\n constructor(config) {\n this.#config = freeze({ ...config });\n }\n async init() {\n this.#pool = isFunction(this.#config.pool)\n ? await this.#config.pool()\n : this.#config.pool;\n }\n async acquireConnection() {\n const client = await this.#pool.connect();\n let connection = this.#connections.get(client);\n if (!connection) {\n connection = new PostgresConnection(client, {\n cursor: this.#config.cursor ?? null,\n });\n this.#connections.set(client, connection);\n // The driver must take care of calling `onCreateConnection` when a new\n // connection is created. The `pg` module doesn't provide an async hook\n // for the connection creation. We need to call the method explicitly.\n if (this.#config.onCreateConnection) {\n await this.#config.onCreateConnection(connection);\n }\n }\n if (this.#config.onReserveConnection) {\n await this.#config.onReserveConnection(connection);\n }\n return connection;\n }\n async beginTransaction(connection, settings) {\n if (settings.isolationLevel || settings.accessMode) {\n let sql = 'start transaction';\n if (settings.isolationLevel) {\n sql += ` isolation level ${settings.isolationLevel}`;\n }\n if (settings.accessMode) {\n sql += ` ${settings.accessMode}`;\n }\n await connection.executeQuery(CompiledQuery.raw(sql));\n }\n else {\n await connection.executeQuery(CompiledQuery.raw('begin'));\n }\n }\n async commitTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('commit'));\n }\n async rollbackTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('rollback'));\n }\n async savepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('savepoint', savepointName), createQueryId()));\n }\n async rollbackToSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('rollback to', savepointName), createQueryId()));\n }\n async releaseSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('release', savepointName), createQueryId()));\n }\n async releaseConnection(connection) {\n connection[PRIVATE_RELEASE_METHOD]();\n }\n async destroy() {\n if (this.#pool) {\n const pool = this.#pool;\n this.#pool = undefined;\n await pool.end();\n }\n }\n}\nclass PostgresConnection {\n #client;\n #options;\n constructor(client, options) {\n this.#client = client;\n this.#options = options;\n }\n async executeQuery(compiledQuery) {\n try {\n const { command, rowCount, rows } = await this.#client.query(compiledQuery.sql, [...compiledQuery.parameters]);\n return {\n numAffectedRows: command === 'INSERT' ||\n command === 'UPDATE' ||\n command === 'DELETE' ||\n command === 'MERGE'\n ? BigInt(rowCount)\n : undefined,\n rows: rows ?? [],\n };\n }\n catch (err) {\n throw extendStackTrace(err, new Error());\n }\n }\n async *streamQuery(compiledQuery, chunkSize) {\n if (!this.#options.cursor) {\n throw new Error(\"'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.\");\n }\n if (!Number.isInteger(chunkSize) || chunkSize <= 0) {\n throw new Error('chunkSize must be a positive integer');\n }\n const cursor = this.#client.query(new this.#options.cursor(compiledQuery.sql, compiledQuery.parameters.slice()));\n try {\n while (true) {\n const rows = await cursor.read(chunkSize);\n if (rows.length === 0) {\n break;\n }\n yield {\n rows,\n };\n }\n }\n finally {\n await cursor.close();\n }\n }\n [PRIVATE_RELEASE_METHOD]() {\n this.#client.release();\n }\n}\n", "/// \nexport {};\n", "/// \nimport { PostgresDriver } from './postgres-driver.js';\nimport { PostgresIntrospector } from './postgres-introspector.js';\nimport { PostgresQueryCompiler } from './postgres-query-compiler.js';\nimport { PostgresAdapter } from './postgres-adapter.js';\n/**\n * PostgreSQL dialect that uses the [pg](https://node-postgres.com/) library.\n *\n * The constructor takes an instance of {@link PostgresDialectConfig}.\n *\n * ```ts\n * import {\u00A0Pool } from 'pg'\n *\n * new PostgresDialect({\n * pool: new Pool({\n * database: 'some_db',\n * host: 'localhost',\n * })\n * })\n * ```\n *\n * If you want the pool to only be created once it's first used, `pool`\n * can be a function:\n *\n * ```ts\n * import {\u00A0Pool } from 'pg'\n *\n * new PostgresDialect({\n * pool: async () => new Pool({\n * database: 'some_db',\n * host: 'localhost',\n * })\n * })\n * ```\n */\nexport class PostgresDialect {\n #config;\n constructor(config) {\n this.#config = config;\n }\n createDriver() {\n return new PostgresDriver(this.#config);\n }\n createQueryCompiler() {\n return new PostgresQueryCompiler();\n }\n createAdapter() {\n return new PostgresAdapter();\n }\n createIntrospector(db) {\n return new PostgresIntrospector(db);\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_TABLE } from '../../migration/migrator.js';\nimport { sql } from '../../raw-builder/sql.js';\nimport { DialectAdapterBase } from '../dialect-adapter-base.js';\nexport class MssqlAdapter extends DialectAdapterBase {\n get supportsCreateIfNotExists() {\n return false;\n }\n get supportsTransactionalDdl() {\n return true;\n }\n get supportsOutput() {\n return true;\n }\n async acquireMigrationLock(db) {\n // Acquire a transaction-level exclusive lock on the migrations table.\n // https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-getapplock-transact-sql?view=sql-server-ver16\n await sql `exec sp_getapplock @DbPrincipal = ${sql.lit('dbo')}, @Resource = ${sql.lit(DEFAULT_MIGRATION_TABLE)}, @LockMode = ${sql.lit('Exclusive')}`.execute(db);\n }\n async releaseMigrationLock() {\n // Nothing to do here. `sp_getapplock` is automatically released at the\n // end of the transaction and since `supportsTransactionalDdl` true, we know\n // the `db` instance passed to acquireMigrationLock is actually a transaction.\n }\n}\n", "/// \nexport {};\n", "/// \nimport { freeze, isBigInt, isBoolean, isBuffer, isDate, isNull, isNumber, isString, isUndefined, } from '../../util/object-utils.js';\nimport { CompiledQuery } from '../../query-compiler/compiled-query.js';\nimport { extendStackTrace } from '../../util/stack-trace-utils.js';\nimport { randomString } from '../../util/random-string.js';\nimport { Deferred } from '../../util/deferred.js';\nconst PRIVATE_RESET_METHOD = Symbol();\nconst PRIVATE_DESTROY_METHOD = Symbol();\nconst PRIVATE_VALIDATE_METHOD = Symbol();\nexport class MssqlDriver {\n #config;\n #pool;\n constructor(config) {\n this.#config = freeze({ ...config });\n const { tarn, tedious, validateConnections } = this.#config;\n const { validateConnections: deprecatedValidateConnections, ...poolOptions } = tarn.options;\n this.#pool = new tarn.Pool({\n ...poolOptions,\n create: async () => {\n const connection = await tedious.connectionFactory();\n return await new MssqlConnection(connection, tedious).connect();\n },\n destroy: async (connection) => {\n await connection[PRIVATE_DESTROY_METHOD]();\n },\n // @ts-ignore `tarn` accepts a function that returns a promise here, but\n // the types are not aligned and it type errors.\n validate: validateConnections === false ||\n deprecatedValidateConnections === false\n ? undefined\n : (connection) => connection[PRIVATE_VALIDATE_METHOD](),\n });\n }\n async init() {\n // noop\n }\n async acquireConnection() {\n return await this.#pool.acquire().promise;\n }\n async beginTransaction(connection, settings) {\n await connection.beginTransaction(settings);\n }\n async commitTransaction(connection) {\n await connection.commitTransaction();\n }\n async rollbackTransaction(connection) {\n await connection.rollbackTransaction();\n }\n async savepoint(connection, savepointName) {\n await connection.savepoint(savepointName);\n }\n async rollbackToSavepoint(connection, savepointName) {\n await connection.rollbackTransaction(savepointName);\n }\n async releaseConnection(connection) {\n if (this.#config.resetConnectionsOnRelease ||\n this.#config.tedious.resetConnectionOnRelease) {\n await connection[PRIVATE_RESET_METHOD]();\n }\n this.#pool.release(connection);\n }\n async destroy() {\n await this.#pool.destroy();\n }\n}\nclass MssqlConnection {\n #connection;\n #hasSocketError;\n #tedious;\n constructor(connection, tedious) {\n this.#connection = connection;\n this.#hasSocketError = false;\n this.#tedious = tedious;\n }\n async beginTransaction(settings) {\n const { isolationLevel } = settings;\n await new Promise((resolve, reject) => this.#connection.beginTransaction((error) => {\n if (error)\n reject(error);\n else\n resolve(undefined);\n }, isolationLevel ? randomString(8) : undefined, isolationLevel\n ? this.#getTediousIsolationLevel(isolationLevel)\n : undefined));\n }\n async commitTransaction() {\n await new Promise((resolve, reject) => this.#connection.commitTransaction((error) => {\n if (error)\n reject(error);\n else\n resolve(undefined);\n }));\n }\n async connect() {\n const { promise: waitForConnected, reject, resolve } = new Deferred();\n this.#connection.connect((error) => {\n if (error) {\n return reject(error);\n }\n resolve();\n });\n this.#connection.on('error', (error) => {\n if (error instanceof Error &&\n 'code' in error &&\n error.code === 'ESOCKET') {\n this.#hasSocketError = true;\n }\n console.error(error);\n reject(error);\n });\n function endListener() {\n reject(new Error('The connection ended without ever completing the connection'));\n }\n this.#connection.once('end', endListener);\n await waitForConnected;\n this.#connection.off('end', endListener);\n return this;\n }\n async executeQuery(compiledQuery) {\n try {\n const deferred = new Deferred();\n const request = new MssqlRequest({\n compiledQuery,\n tedious: this.#tedious,\n onDone: deferred,\n });\n this.#connection.execSql(request.request);\n const { rowCount, rows } = await deferred.promise;\n return {\n numAffectedRows: rowCount !== undefined ? BigInt(rowCount) : undefined,\n rows,\n };\n }\n catch (err) {\n throw extendStackTrace(err, new Error());\n }\n }\n async rollbackTransaction(savepointName) {\n await new Promise((resolve, reject) => this.#connection.rollbackTransaction((error) => {\n if (error)\n reject(error);\n else\n resolve(undefined);\n }, savepointName));\n }\n async savepoint(savepointName) {\n await new Promise((resolve, reject) => this.#connection.saveTransaction((error) => {\n if (error)\n reject(error);\n else\n resolve(undefined);\n }, savepointName));\n }\n async *streamQuery(compiledQuery, chunkSize) {\n if (!Number.isInteger(chunkSize) || chunkSize <= 0) {\n throw new Error('chunkSize must be a positive integer');\n }\n const request = new MssqlRequest({\n compiledQuery,\n streamChunkSize: chunkSize,\n tedious: this.#tedious,\n });\n this.#connection.execSql(request.request);\n try {\n while (true) {\n const rows = await request.readChunk();\n if (rows.length === 0) {\n break;\n }\n yield { rows };\n if (rows.length < chunkSize) {\n break;\n }\n }\n }\n finally {\n await this.#cancelRequest(request);\n }\n }\n #getTediousIsolationLevel(isolationLevel) {\n const { ISOLATION_LEVEL } = this.#tedious;\n const mapper = {\n 'read committed': ISOLATION_LEVEL.READ_COMMITTED,\n 'read uncommitted': ISOLATION_LEVEL.READ_UNCOMMITTED,\n 'repeatable read': ISOLATION_LEVEL.REPEATABLE_READ,\n serializable: ISOLATION_LEVEL.SERIALIZABLE,\n snapshot: ISOLATION_LEVEL.SNAPSHOT,\n };\n const tediousIsolationLevel = mapper[isolationLevel];\n if (tediousIsolationLevel === undefined) {\n throw new Error(`Unknown isolation level: ${isolationLevel}`);\n }\n return tediousIsolationLevel;\n }\n #cancelRequest(request) {\n return new Promise((resolve) => {\n request.request.once('requestCompleted', resolve);\n const wasCanceled = this.#connection.cancel();\n if (!wasCanceled) {\n request.request.off('requestCompleted', resolve);\n resolve();\n }\n });\n }\n [PRIVATE_DESTROY_METHOD]() {\n if ('closed' in this.#connection && this.#connection.closed) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n this.#connection.once('end', resolve);\n this.#connection.close();\n });\n }\n async [PRIVATE_RESET_METHOD]() {\n await new Promise((resolve, reject) => {\n this.#connection.reset((error) => {\n if (error) {\n return reject(error);\n }\n resolve();\n });\n });\n }\n async [PRIVATE_VALIDATE_METHOD]() {\n if (this.#hasSocketError || this.#isConnectionClosed()) {\n return false;\n }\n try {\n const deferred = new Deferred();\n const request = new MssqlRequest({\n compiledQuery: CompiledQuery.raw('select 1'),\n onDone: deferred,\n tedious: this.#tedious,\n });\n this.#connection.execSql(request.request);\n await deferred.promise;\n return true;\n }\n catch {\n return false;\n }\n }\n #isConnectionClosed() {\n return 'closed' in this.#connection && Boolean(this.#connection.closed);\n }\n}\nclass MssqlRequest {\n #request;\n #rows;\n #streamChunkSize;\n #subscribers;\n #tedious;\n #rowCount;\n constructor(props) {\n const { compiledQuery, onDone, streamChunkSize, tedious } = props;\n this.#rows = [];\n this.#streamChunkSize = streamChunkSize;\n this.#subscribers = {};\n this.#tedious = tedious;\n if (onDone) {\n const subscriptionKey = 'onDone';\n this.#subscribers[subscriptionKey] = (event, error) => {\n if (event === 'chunkReady') {\n return;\n }\n delete this.#subscribers[subscriptionKey];\n if (event === 'error') {\n return onDone.reject(error);\n }\n onDone.resolve({\n rowCount: this.#rowCount,\n rows: this.#rows,\n });\n };\n }\n this.#request = new this.#tedious.Request(compiledQuery.sql, (err, rowCount) => {\n if (err) {\n return Object.values(this.#subscribers).forEach((subscriber) => subscriber('error', err instanceof AggregateError ? err.errors : err));\n }\n this.#rowCount = rowCount;\n });\n this.#addParametersToRequest(compiledQuery.parameters);\n this.#attachListeners();\n }\n get request() {\n return this.#request;\n }\n readChunk() {\n const subscriptionKey = this.readChunk.name;\n return new Promise((resolve, reject) => {\n this.#subscribers[subscriptionKey] = (event, error) => {\n delete this.#subscribers[subscriptionKey];\n if (event === 'error') {\n return reject(error);\n }\n resolve(this.#rows.splice(0, this.#streamChunkSize));\n };\n this.#request.resume();\n });\n }\n #addParametersToRequest(parameters) {\n for (let i = 0; i < parameters.length; i++) {\n const parameter = parameters[i];\n this.#request.addParameter(String(i + 1), this.#getTediousDataType(parameter), parameter);\n }\n }\n #attachListeners() {\n const pauseAndEmitChunkReady = this.#streamChunkSize\n ? () => {\n if (this.#streamChunkSize <= this.#rows.length) {\n this.#request.pause();\n Object.values(this.#subscribers).forEach((subscriber) => subscriber('chunkReady'));\n }\n }\n : () => { };\n const rowListener = (columns) => {\n const row = {};\n for (const column of columns) {\n row[column.metadata.colName] = column.value;\n }\n this.#rows.push(row);\n pauseAndEmitChunkReady();\n };\n this.#request.on('row', rowListener);\n this.#request.once('requestCompleted', () => {\n Object.values(this.#subscribers).forEach((subscriber) => subscriber('completed'));\n this.#request.off('row', rowListener);\n });\n }\n #getTediousDataType(value) {\n if (isNull(value) || isUndefined(value) || isString(value)) {\n return this.#tedious.TYPES.NVarChar;\n }\n if (isBigInt(value) || (isNumber(value) && value % 1 === 0)) {\n if (value < -2147483648 || value > 2147483647) {\n return this.#tedious.TYPES.BigInt;\n }\n else {\n return this.#tedious.TYPES.Int;\n }\n }\n if (isNumber(value)) {\n return this.#tedious.TYPES.Float;\n }\n if (isBoolean(value)) {\n return this.#tedious.TYPES.Bit;\n }\n if (isDate(value)) {\n return this.#tedious.TYPES.DateTime;\n }\n if (isBuffer(value)) {\n return this.#tedious.TYPES.VarBinary;\n }\n return this.#tedious.TYPES.NVarChar;\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';\nimport { freeze } from '../../util/object-utils.js';\nexport class MssqlIntrospector {\n #db;\n constructor(db) {\n this.#db = db;\n }\n async getSchemas() {\n return await this.#db.selectFrom('sys.schemas').select('name').execute();\n }\n async getTables(options = { withInternalKyselyTables: false }) {\n const rawColumns = await this.#db\n .selectFrom('sys.tables as tables')\n .leftJoin('sys.schemas as table_schemas', 'table_schemas.schema_id', 'tables.schema_id')\n .innerJoin('sys.columns as columns', 'columns.object_id', 'tables.object_id')\n .innerJoin('sys.types as types', 'types.user_type_id', 'columns.user_type_id')\n .leftJoin('sys.schemas as type_schemas', 'type_schemas.schema_id', 'types.schema_id')\n .leftJoin('sys.extended_properties as comments', (join) => join\n .onRef('comments.major_id', '=', 'tables.object_id')\n .onRef('comments.minor_id', '=', 'columns.column_id')\n .on('comments.name', '=', 'MS_Description'))\n .$if(!options.withInternalKyselyTables, (qb) => qb\n .where('tables.name', '!=', DEFAULT_MIGRATION_TABLE)\n .where('tables.name', '!=', DEFAULT_MIGRATION_LOCK_TABLE))\n .select([\n 'tables.name as table_name',\n (eb) => eb\n .ref('tables.type')\n .$castTo()\n .as('table_type'),\n 'table_schemas.name as table_schema_name',\n 'columns.default_object_id as column_default_object_id',\n 'columns.generated_always_type_desc as column_generated_always_type',\n 'columns.is_computed as column_is_computed',\n 'columns.is_identity as column_is_identity',\n 'columns.is_nullable as column_is_nullable',\n 'columns.is_rowguidcol as column_is_rowguidcol',\n 'columns.name as column_name',\n 'types.is_nullable as type_is_nullable',\n 'types.name as type_name',\n 'type_schemas.name as type_schema_name',\n 'comments.value as column_comment',\n ])\n .unionAll(this.#db\n .selectFrom('sys.views as views')\n .leftJoin('sys.schemas as view_schemas', 'view_schemas.schema_id', 'views.schema_id')\n .innerJoin('sys.columns as columns', 'columns.object_id', 'views.object_id')\n .innerJoin('sys.types as types', 'types.user_type_id', 'columns.user_type_id')\n .leftJoin('sys.schemas as type_schemas', 'type_schemas.schema_id', 'types.schema_id')\n .leftJoin('sys.extended_properties as comments', (join) => join\n .onRef('comments.major_id', '=', 'views.object_id')\n .onRef('comments.minor_id', '=', 'columns.column_id')\n .on('comments.name', '=', 'MS_Description'))\n .select([\n 'views.name as table_name',\n 'views.type as table_type',\n 'view_schemas.name as table_schema_name',\n 'columns.default_object_id as column_default_object_id',\n 'columns.generated_always_type_desc as column_generated_always_type',\n 'columns.is_computed as column_is_computed',\n 'columns.is_identity as column_is_identity',\n 'columns.is_nullable as column_is_nullable',\n 'columns.is_rowguidcol as column_is_rowguidcol',\n 'columns.name as column_name',\n 'types.is_nullable as type_is_nullable',\n 'types.name as type_name',\n 'type_schemas.name as type_schema_name',\n 'comments.value as column_comment',\n ]))\n .orderBy('table_schema_name')\n .orderBy('table_name')\n .orderBy('column_name')\n .execute();\n const tableDictionary = {};\n for (const rawColumn of rawColumns) {\n const key = `${rawColumn.table_schema_name}.${rawColumn.table_name}`;\n const table = (tableDictionary[key] =\n tableDictionary[key] ||\n freeze({\n columns: [],\n isView: rawColumn.table_type === 'V ',\n name: rawColumn.table_name,\n schema: rawColumn.table_schema_name ?? undefined,\n }));\n table.columns.push(freeze({\n dataType: rawColumn.type_name,\n dataTypeSchema: rawColumn.type_schema_name ?? undefined,\n hasDefaultValue: rawColumn.column_default_object_id > 0 ||\n rawColumn.column_generated_always_type !== 'NOT_APPLICABLE' ||\n rawColumn.column_is_identity ||\n rawColumn.column_is_computed ||\n rawColumn.column_is_rowguidcol,\n isAutoIncrementing: rawColumn.column_is_identity,\n isNullable: rawColumn.column_is_nullable && rawColumn.type_is_nullable,\n name: rawColumn.column_name,\n comment: rawColumn.column_comment ?? undefined,\n }));\n }\n return Object.values(tableDictionary);\n }\n async getMetadata(options) {\n return {\n tables: await this.getTables(options),\n };\n }\n}\n", "/// \nimport { DefaultQueryCompiler } from '../../query-compiler/default-query-compiler.js';\nconst COLLATION_CHAR_REGEX = /^[a-z0-9_]$/i;\nexport class MssqlQueryCompiler extends DefaultQueryCompiler {\n getCurrentParameterPlaceholder() {\n return `@${this.numParameters}`;\n }\n visitOffset(node) {\n super.visitOffset(node);\n this.append(' rows');\n }\n // mssql allows multi-column alterations in a single statement,\n // but you can only use the command keyword/s once.\n // it also doesn't support multiple kinds of commands in the same\n // alter table statement, but we compile that anyway for the sake\n // of WYSIWYG.\n compileColumnAlterations(columnAlterations) {\n const nodesByKind = {};\n for (const columnAlteration of columnAlterations) {\n if (!nodesByKind[columnAlteration.kind]) {\n nodesByKind[columnAlteration.kind] = [];\n }\n nodesByKind[columnAlteration.kind].push(columnAlteration);\n }\n let first = true;\n if (nodesByKind.AddColumnNode) {\n this.append('add ');\n this.compileList(nodesByKind.AddColumnNode);\n first = false;\n }\n // multiple of these are not really supported by mssql,\n // but for the sake of WYSIWYG.\n if (nodesByKind.AlterColumnNode) {\n if (!first)\n this.append(', ');\n this.compileList(nodesByKind.AlterColumnNode);\n }\n if (nodesByKind.DropColumnNode) {\n if (!first)\n this.append(', ');\n this.append('drop column ');\n this.compileList(nodesByKind.DropColumnNode);\n }\n // not really supported by mssql, but for the sake of WYSIWYG.\n if (nodesByKind.ModifyColumnNode) {\n if (!first)\n this.append(', ');\n this.compileList(nodesByKind.ModifyColumnNode);\n }\n // not really supported by mssql, but for the sake of WYSIWYG.\n if (nodesByKind.RenameColumnNode) {\n if (!first)\n this.append(', ');\n this.compileList(nodesByKind.RenameColumnNode);\n }\n }\n visitAddColumn(node) {\n this.visitNode(node.column);\n }\n visitDropColumn(node) {\n this.visitNode(node.column);\n }\n visitMergeQuery(node) {\n super.visitMergeQuery(node);\n this.append(';');\n }\n visitCollate(node) {\n this.append('collate ');\n const { name } = node.collation;\n for (const char of name) {\n if (!COLLATION_CHAR_REGEX.test(char)) {\n throw new Error(`Invalid collation: ${name}`);\n }\n }\n this.append(name);\n }\n announcesNewColumnDataType() {\n return false;\n }\n}\n", "/// \nimport { MssqlAdapter } from './mssql-adapter.js';\nimport { MssqlDriver } from './mssql-driver.js';\nimport { MssqlIntrospector } from './mssql-introspector.js';\nimport { MssqlQueryCompiler } from './mssql-query-compiler.js';\n/**\n * MS SQL Server dialect that uses the [tedious](https://tediousjs.github.io/tedious)\n * library.\n *\n * The constructor takes an instance of {@link MssqlDialectConfig}.\n *\n * ```ts\n * import * as Tedious from 'tedious'\n * import * as Tarn from 'tarn'\n *\n * const dialect = new MssqlDialect({\n * tarn: {\n * ...Tarn,\n * options: {\n * min: 0,\n * max: 10,\n * },\n * },\n * tedious: {\n * ...Tedious,\n * connectionFactory: () => new Tedious.Connection({\n * authentication: {\n * options: {\n * password: 'password',\n * userName: 'username',\n * },\n * type: 'default',\n * },\n * options: {\n * database: 'some_db',\n * port: 1433,\n * trustServerCertificate: true,\n * },\n * server: 'localhost',\n * }),\n * },\n * })\n * ```\n */\nexport class MssqlDialect {\n #config;\n constructor(config) {\n this.#config = config;\n }\n createDriver() {\n return new MssqlDriver(this.#config);\n }\n createQueryCompiler() {\n return new MssqlQueryCompiler();\n }\n createAdapter() {\n return new MssqlAdapter();\n }\n createIntrospector(db) {\n return new MssqlIntrospector(db);\n }\n}\n", "/// \nexport {};\n", "/// \nimport { isFunction, isObject } from '../util/object-utils.js';\n/**\n * Reads all migrations from a folder in node.js.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n *\n * new FileMigrationProvider({\n * fs,\n * path,\n * migrationFolder: 'path/to/migrations/folder'\n * })\n * ```\n */\nexport class FileMigrationProvider {\n #props;\n constructor(props) {\n this.#props = props;\n }\n async getMigrations() {\n const migrations = {};\n const files = await this.#props.fs.readdir(this.#props.migrationFolder);\n for (const fileName of files) {\n if (fileName.endsWith('.js') ||\n (fileName.endsWith('.ts') && !fileName.endsWith('.d.ts')) ||\n fileName.endsWith('.mjs') ||\n (fileName.endsWith('.mts') && !fileName.endsWith('.d.mts'))) {\n const migration = await import(\n /* webpackIgnore: true */ this.#props.path.join(this.#props.migrationFolder, fileName));\n const migrationKey = fileName.substring(0, fileName.lastIndexOf('.'));\n // Handle esModuleInterop export's `default` prop...\n if (isMigration(migration?.default)) {\n migrations[migrationKey] = migration.default;\n }\n else if (isMigration(migration)) {\n migrations[migrationKey] = migration;\n }\n }\n }\n return migrations;\n }\n}\nfunction isMigration(obj) {\n return isObject(obj) && isFunction(obj.up);\n}\n", "/// \nexport {};\n", "/// \nimport { isPlainObject } from '../../util/object-utils.js';\nimport { SnakeCaseTransformer } from './camel-case-transformer.js';\nimport { createCamelCaseMapper, createSnakeCaseMapper, } from './camel-case.js';\n/**\n * A plugin that converts snake_case identifiers in the database into\n * camelCase in the JavaScript side.\n *\n * For example let's assume we have a table called `person_table`\n * with columns `first_name` and `last_name` in the database. When\n * using `CamelCasePlugin` we would setup Kysely like this:\n *\n * ```ts\n * import * as Sqlite from 'better-sqlite3'\n * import { CamelCasePlugin, Kysely, SqliteDialect } from 'kysely'\n *\n * interface CamelCasedDatabase {\n * userMetadata: {\n * firstName: string\n * lastName: string\n * }\n * }\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [new CamelCasePlugin()],\n * })\n *\n * const person = await db.selectFrom('userMetadata')\n * .where('firstName', '=', 'Arnold')\n * .select(['firstName', 'lastName'])\n * .executeTakeFirst()\n *\n * if (person) {\n * console.log(person.firstName)\n * }\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select \"first_name\", \"last_name\" from \"user_metadata\" where \"first_name\" = ?\n * ```\n *\n * As you can see from the example, __everything__ needs to be defined\n * in camelCase in the TypeScript code: table names, columns, schemas,\n * __everything__. When using the `CamelCasePlugin` Kysely works as if\n * the database was defined in camelCase.\n *\n * There are various options you can give to the plugin to modify\n * the way identifiers are converted. See {@link CamelCasePluginOptions}.\n * If those options are not enough, you can override this plugin's\n * `snakeCase` and `camelCase` methods to make the conversion exactly\n * the way you like:\n *\n * ```ts\n * class MyCamelCasePlugin extends CamelCasePlugin {\n * protected override snakeCase(str: string): string {\n * // ...\n *\n * return str\n * }\n *\n * protected override camelCase(str: string): string {\n * // ...\n *\n * return str\n * }\n * }\n * ```\n */\nexport class CamelCasePlugin {\n opt;\n #camelCase;\n #snakeCase;\n #snakeCaseTransformer;\n constructor(opt = {}) {\n this.opt = opt;\n this.#camelCase = createCamelCaseMapper(opt);\n this.#snakeCase = createSnakeCaseMapper(opt);\n this.#snakeCaseTransformer = new SnakeCaseTransformer(this.snakeCase.bind(this));\n }\n transformQuery(args) {\n return this.#snakeCaseTransformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n if (args.result.rows && Array.isArray(args.result.rows)) {\n return {\n ...args.result,\n rows: args.result.rows.map((row) => this.mapRow(row)),\n };\n }\n return args.result;\n }\n mapRow(row) {\n return Object.keys(row).reduce((obj, key) => {\n let value = row[key];\n if (Array.isArray(value)) {\n value = value.map((it) => (canMap(it, this.opt) ? this.mapRow(it) : it));\n }\n else if (canMap(value, this.opt)) {\n value = this.mapRow(value);\n }\n obj[this.camelCase(key)] = value;\n return obj;\n }, {});\n }\n snakeCase(str) {\n return this.#snakeCase(str);\n }\n camelCase(str) {\n return this.#camelCase(str);\n }\n}\nfunction canMap(obj, opt) {\n return isPlainObject(obj) && !opt?.maintainNestedObjectKeys;\n}\n", "/// \nimport { DeduplicateJoinsTransformer } from './deduplicate-joins-transformer.js';\n/**\n * Plugin that removes duplicate joins from queries.\n *\n * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0008-deduplicate-joins.md)\n */\nexport class DeduplicateJoinsPlugin {\n #transformer = new DeduplicateJoinsTransformer();\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n transformResult(args) {\n return Promise.resolve(args.result);\n }\n}\n", "/// \nimport { isPlainObject, isString } from '../../util/object-utils.js';\n/**\n * Parses JSON strings in query results into JSON objects.\n *\n * This plugin can be useful with dialects that don't automatically parse\n * JSON into objects and arrays but return JSON strings instead.\n *\n * To apply this plugin globally, pass an instance of it to the `plugins` option\n * when creating a new `Kysely` instance:\n *\n * ```ts\n * import * as Sqlite from 'better-sqlite3'\n * import { Kysely, ParseJSONResultsPlugin, SqliteDialect } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [new ParseJSONResultsPlugin()],\n * })\n * ```\n *\n * To apply this plugin to a single query:\n *\n * ```ts\n * import { ParseJSONResultsPlugin } from 'kysely'\n * import { jsonArrayFrom } from 'kysely/helpers/sqlite'\n *\n * const result = await db\n * .selectFrom('person')\n * .select((eb) => [\n * 'id',\n * 'first_name',\n * 'last_name',\n * jsonArrayFrom(\n * eb.selectFrom('pet')\n * .whereRef('owner_id', '=', 'person.id')\n * .select(['name', 'species'])\n * ).as('pets')\n * ])\n * .withPlugin(new ParseJSONResultsPlugin())\n * .execute()\n * ```\n */\nexport class ParseJSONResultsPlugin {\n opt;\n #objectStrategy;\n constructor(opt = {}) {\n this.opt = opt;\n this.#objectStrategy = opt.objectStrategy || 'in-place';\n }\n // noop\n transformQuery(args) {\n return args.node;\n }\n async transformResult(args) {\n return {\n ...args.result,\n rows: parseArray(args.result.rows, this.#objectStrategy),\n };\n }\n}\nfunction parseArray(arr, objectStrategy) {\n const target = objectStrategy === 'create' ? new Array(arr.length) : arr;\n for (let i = 0; i < arr.length; ++i) {\n target[i] = parse(arr[i], objectStrategy);\n }\n return target;\n}\nfunction parse(obj, objectStrategy) {\n if (isString(obj)) {\n return parseString(obj);\n }\n if (Array.isArray(obj)) {\n return parseArray(obj, objectStrategy);\n }\n if (isPlainObject(obj)) {\n return parseObject(obj, objectStrategy);\n }\n return obj;\n}\nfunction parseString(str) {\n if (maybeJson(str)) {\n try {\n return parse(JSON.parse(str), 'in-place');\n }\n catch (err) {\n // this catch block is intentionally empty.\n }\n }\n return str;\n}\nfunction maybeJson(value) {\n return value.match(/^[\\[\\{]/) != null;\n}\nfunction parseObject(obj, objectStrategy) {\n const target = objectStrategy === 'create' ? {} : obj;\n for (const key in obj) {\n target[key] = parse(obj[key], objectStrategy);\n }\n return target;\n}\n", "/// \nimport { HandleEmptyInListsTransformer } from './handle-empty-in-lists-transformer.js';\n/**\n * A plugin that allows handling `in ()` and `not in ()` expressions.\n *\n * These expressions are invalid SQL syntax for many databases, and result in runtime\n * database errors.\n *\n * The workarounds used by other libraries always involve modifying the query under\n * the hood, which is not aligned with Kysely's philosophy of WYSIWYG. We recommend manually checking\n * for empty arrays before passing them as arguments to `in` and `not in` expressions\n * instead, but understand that this can be cumbersome. Hence we're going with an\n * opt-in approach where you can choose if and how to handle these cases. We do\n * not want to make this the default behavior, as it can lead to unexpected behavior.\n * Use it at your own risk. Test it. Make sure it works as expected for you.\n *\n * Using this plugin also allows you to throw an error (thus avoiding unnecessary\n * requests to the database) or print a warning in these cases.\n *\n * ### Examples\n *\n * The following strategy replaces the `in`/`not in` expression with a noncontingent\n * expression. A contradiction (falsy) `1 = 0` for `in`, and a tautology (truthy) `1 = 1` for `not in`),\n * similarily to how {@link https://github.com/knex/knex/blob/176151d8048b2a7feeb89a3d649a5580786d4f4e/docs/src/guide/query-builder.md#L1763 | Knex.js},\n * {@link https://github.com/prisma/prisma-engines/blob/99168c54187178484dae45d9478aa40cfd1866d2/quaint/src/visitor.rs#L804-L823 | PrismaORM},\n * {@link https://github.com/laravel/framework/blob/8.x/src/Illuminate/Database/Query/Grammars/Grammar.php#L284-L291 | Laravel},\n * {@link https://docs.sqlalchemy.org/en/13/core/engines.html#sqlalchemy.create_engine.params.empty_in_strategy | SQLAlchemy}\n * handle this.\n *\n * ```ts\n * import Sqlite from 'better-sqlite3'\n * import {\n * HandleEmptyInListsPlugin,\n * Kysely,\n * replaceWithNoncontingentExpression,\n * SqliteDialect,\n * } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [\n * new HandleEmptyInListsPlugin({\n * strategy: replaceWithNoncontingentExpression\n * })\n * ],\n * })\n *\n * const results = await db\n * .selectFrom('person')\n * .where('id', 'in', [])\n * .where('first_name', 'not in', [])\n * .selectAll()\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select * from \"person\" where 1 = 0 and 1 = 1\n * ```\n *\n * The following strategy does the following:\n *\n * When `in`, pushes a `null` value into the empty list resulting in `in (null)`,\n * similiarly to how {@link https://github.com/typeorm/typeorm/blob/0280cdc451c35ef73c830eb1191c95d34f6ce06e/src/query-builder/QueryBuilder.ts#L919-L922 | TypeORM}\n * and {@link https://github.com/sequelize/sequelize/blob/0f2891c6897e12bf9bf56df344aae5b698f58c7d/packages/core/src/abstract-dialect/where-sql-builder.ts#L368-L379 | Sequelize}\n * handle `in ()`. `in (null)` is logically the equivalent of `= null`, which returns\n * `null`, which is a falsy expression in most SQL databases. We recommend NOT\n * using this strategy if you plan to use `in` in `select`, `returning`, or `output`\n * clauses, as the return type differs from the `SqlBool` default type for comparisons.\n *\n * When `not in`, casts the left operand as `char` and pushes a unique value into\n * the empty list resulting in `cast({{lhs}} as char) not in ({{VALUE}})`. Casting\n * is required to avoid database errors with non-string values.\n *\n * ```ts\n * import Sqlite from 'better-sqlite3'\n * import {\n * HandleEmptyInListsPlugin,\n * Kysely,\n * pushValueIntoList,\n * SqliteDialect\n * } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [\n * new HandleEmptyInListsPlugin({\n * strategy: pushValueIntoList('__kysely_no_values_were_provided__') // choose a unique value for not in. has to be something with zero chance being in the data.\n * })\n * ],\n * })\n *\n * const results = await db\n * .selectFrom('person')\n * .where('id', 'in', [])\n * .where('first_name', 'not in', [])\n * .selectAll()\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select * from \"person\" where \"id\" in (null) and cast(\"first_name\" as char) not in ('__kysely_no_values_were_provided__')\n * ```\n *\n * The following custom strategy throws an error when an empty list is encountered\n * to avoid unnecessary requests to the database:\n *\n * ```ts\n * import Sqlite from 'better-sqlite3'\n * import {\n * HandleEmptyInListsPlugin,\n * Kysely,\n * SqliteDialect\n * } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [\n * new HandleEmptyInListsPlugin({\n * strategy: () => {\n * throw new Error('Empty in/not-in is not allowed')\n * }\n * })\n * ],\n * })\n *\n * const results = await db\n * .selectFrom('person')\n * .where('id', 'in', [])\n * .selectAll()\n * .execute() // throws an error with 'Empty in/not-in is not allowed' message!\n * ```\n */\nexport class HandleEmptyInListsPlugin {\n opt;\n #transformer;\n constructor(opt) {\n this.opt = opt;\n this.#transformer = new HandleEmptyInListsTransformer(opt.strategy);\n }\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n return args.result;\n }\n}\n", "/// \nimport { BinaryOperationNode } from '../../operation-node/binary-operation-node.js';\nimport { CastNode } from '../../operation-node/cast-node.js';\nimport { DataTypeNode } from '../../operation-node/data-type-node.js';\nimport { OperatorNode } from '../../operation-node/operator-node.js';\nimport { ValueListNode } from '../../operation-node/value-list-node.js';\nimport { ValueNode } from '../../operation-node/value-node.js';\nimport { freeze } from '../../util/object-utils.js';\nlet contradiction;\nlet eq;\nlet one;\nlet tautology;\n/**\n * Replaces the `in`/`not in` expression with a noncontingent expression (always true or always\n * false) depending on the original operator.\n *\n * This is how Knex.js, PrismaORM, Laravel, and SQLAlchemy handle `in ()` and `not in ()`.\n *\n * See {@link pushValueIntoList} for an alternative strategy.\n */\nexport function replaceWithNoncontingentExpression(node) {\n const _one = (one ||= ValueNode.createImmediate(1));\n const _eq = (eq ||= OperatorNode.create('='));\n if (node.operator.operator === 'in') {\n return (contradiction ||= BinaryOperationNode.create(_one, _eq, ValueNode.createImmediate(0)));\n }\n return (tautology ||= BinaryOperationNode.create(_one, _eq, _one));\n}\nlet char;\nlet listNull;\nlet listVal;\n/**\n * When `in`, pushes a `null` value into the list resulting in `in (null)`. This\n * is how TypeORM and Sequelize handle `in ()`. `in (null)` is logically the equivalent\n * of `= null`, which returns `null`, which is a falsy expression in most SQL databases.\n * We recommend NOT using this strategy if you plan to use `in` in `select`, `returning`,\n * or `output` clauses, as the return type differs from the `SqlBool` default type.\n *\n * When `not in`, casts the left operand as `char` and pushes a literal value into\n * the list resulting in `cast({{lhs}} as char) not in ({{VALUE}})`. Casting\n * is required to avoid database errors with non-string columns.\n *\n * See {@link replaceWithNoncontingentExpression} for an alternative strategy.\n */\nexport function pushValueIntoList(uniqueNotInLiteral) {\n return function pushValueIntoList(node) {\n if (node.operator.operator === 'in') {\n return freeze({\n ...node,\n rightOperand: (listNull ||= ValueListNode.create([\n ValueNode.createImmediate(null),\n ])),\n });\n }\n return freeze({\n ...node,\n leftOperand: CastNode.create(node.leftOperand, (char ||= DataTypeNode.create('char'))),\n rightOperand: (listVal ||= ValueListNode.create([\n ValueNode.createImmediate(uniqueNotInLiteral),\n ])),\n });\n };\n}\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \n/**\n * @module\n * @mergeModuleWith \n */\nexport * from './kysely.js';\nexport * from './query-creator.js';\nexport * from './expression/expression.js';\nexport { expressionBuilder, } from './expression/expression-builder.js';\nexport * from './expression/expression-wrapper.js';\nexport * from './query-builder/where-interface.js';\nexport * from './query-builder/returning-interface.js';\nexport * from './query-builder/output-interface.js';\nexport * from './query-builder/having-interface.js';\nexport * from './query-builder/order-by-interface.js';\nexport * from './query-builder/select-query-builder.js';\nexport * from './query-builder/insert-query-builder.js';\nexport * from './query-builder/update-query-builder.js';\nexport * from './query-builder/delete-query-builder.js';\nexport * from './query-builder/no-result-error.js';\nexport * from './query-builder/join-builder.js';\nexport * from './query-builder/function-module.js';\nexport * from './query-builder/insert-result.js';\nexport * from './query-builder/delete-result.js';\nexport * from './query-builder/update-result.js';\nexport * from './query-builder/on-conflict-builder.js';\nexport * from './query-builder/aggregate-function-builder.js';\nexport * from './query-builder/case-builder.js';\nexport * from './query-builder/json-path-builder.js';\nexport * from './query-builder/merge-query-builder.js';\nexport * from './query-builder/merge-result.js';\nexport * from './query-builder/order-by-item-builder.js';\nexport * from './raw-builder/raw-builder.js';\nexport * from './raw-builder/sql.js';\nexport * from './query-executor/query-executor.js';\nexport * from './query-executor/default-query-executor.js';\nexport * from './query-executor/noop-query-executor.js';\nexport * from './query-executor/query-executor-provider.js';\nexport * from './query-compiler/default-query-compiler.js';\nexport * from './query-compiler/compiled-query.js';\nexport * from './schema/schema.js';\nexport * from './schema/create-table-builder.js';\nexport * from './schema/create-type-builder.js';\nexport * from './schema/drop-table-builder.js';\nexport * from './schema/drop-type-builder.js';\nexport * from './schema/create-index-builder.js';\nexport * from './schema/drop-index-builder.js';\nexport * from './schema/create-schema-builder.js';\nexport * from './schema/drop-schema-builder.js';\nexport * from './schema/column-definition-builder.js';\nexport * from './schema/foreign-key-constraint-builder.js';\nexport * from './schema/alter-table-builder.js';\nexport * from './schema/create-view-builder.js';\nexport * from './schema/refresh-materialized-view-builder.js';\nexport * from './schema/drop-view-builder.js';\nexport * from './schema/alter-column-builder.js';\nexport * from './dynamic/dynamic.js';\nexport * from './dynamic/dynamic-reference-builder.js';\nexport * from './dynamic/dynamic-table-builder.js';\nexport * from './driver/driver.js';\nexport * from './driver/database-connection.js';\nexport * from './driver/connection-provider.js';\nexport * from './driver/default-connection-provider.js';\nexport * from './driver/single-connection-provider.js';\nexport * from './driver/dummy-driver.js';\nexport * from './dialect/dialect.js';\nexport * from './dialect/dialect-adapter.js';\nexport * from './dialect/dialect-adapter-base.js';\nexport * from './dialect/database-introspector.js';\nexport * from './dialect/sqlite/sqlite-dialect.js';\nexport * from './dialect/sqlite/sqlite-dialect-config.js';\nexport * from './dialect/sqlite/sqlite-driver.js';\nexport * from './dialect/postgres/postgres-query-compiler.js';\nexport * from './dialect/postgres/postgres-introspector.js';\nexport * from './dialect/postgres/postgres-adapter.js';\nexport * from './dialect/mysql/mysql-dialect.js';\nexport * from './dialect/mysql/mysql-dialect-config.js';\nexport * from './dialect/mysql/mysql-driver.js';\nexport * from './dialect/mysql/mysql-query-compiler.js';\nexport * from './dialect/mysql/mysql-introspector.js';\nexport * from './dialect/mysql/mysql-adapter.js';\nexport * from './dialect/postgres/postgres-driver.js';\nexport * from './dialect/postgres/postgres-dialect-config.js';\nexport * from './dialect/postgres/postgres-dialect.js';\nexport * from './dialect/sqlite/sqlite-query-compiler.js';\nexport * from './dialect/sqlite/sqlite-introspector.js';\nexport * from './dialect/sqlite/sqlite-adapter.js';\nexport * from './dialect/mssql/mssql-adapter.js';\nexport * from './dialect/mssql/mssql-dialect-config.js';\nexport * from './dialect/mssql/mssql-dialect.js';\nexport * from './dialect/mssql/mssql-driver.js';\nexport * from './dialect/mssql/mssql-introspector.js';\nexport * from './dialect/mssql/mssql-query-compiler.js';\nexport * from './query-compiler/default-query-compiler.js';\nexport * from './query-compiler/query-compiler.js';\nexport * from './migration/migrator.js';\nexport * from './migration/file-migration-provider.js';\nexport * from './plugin/kysely-plugin.js';\nexport * from './plugin/camel-case/camel-case-plugin.js';\nexport * from './plugin/deduplicate-joins/deduplicate-joins-plugin.js';\nexport * from './plugin/with-schema/with-schema-plugin.js';\nexport * from './plugin/parse-json-results/parse-json-results-plugin.js';\nexport * from './plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js';\nexport * from './plugin/handle-empty-in-lists/handle-empty-in-lists.js';\nexport * from './operation-node/add-column-node.js';\nexport * from './operation-node/add-constraint-node.js';\nexport * from './operation-node/add-index-node.js';\nexport * from './operation-node/aggregate-function-node.js';\nexport * from './operation-node/alias-node.js';\nexport * from './operation-node/alter-column-node.js';\nexport * from './operation-node/alter-table-node.js';\nexport * from './operation-node/and-node.js';\nexport * from './operation-node/binary-operation-node.js';\nexport * from './operation-node/case-node.js';\nexport * from './operation-node/cast-node.js';\nexport * from './operation-node/check-constraint-node.js';\nexport * from './operation-node/collate-node.js';\nexport * from './operation-node/column-definition-node.js';\nexport * from './operation-node/column-node.js';\nexport * from './operation-node/column-update-node.js';\nexport * from './operation-node/common-table-expression-name-node.js';\nexport * from './operation-node/common-table-expression-node.js';\nexport * from './operation-node/constraint-node.js';\nexport * from './operation-node/create-index-node.js';\nexport * from './operation-node/create-schema-node.js';\nexport * from './operation-node/create-table-node.js';\nexport * from './operation-node/create-type-node.js';\nexport * from './operation-node/create-view-node.js';\nexport * from './operation-node/refresh-materialized-view-node.js';\nexport * from './operation-node/data-type-node.js';\nexport * from './operation-node/default-insert-value-node.js';\nexport * from './operation-node/default-value-node.js';\nexport * from './operation-node/delete-query-node.js';\nexport * from './operation-node/drop-column-node.js';\nexport * from './operation-node/drop-constraint-node.js';\nexport * from './operation-node/drop-index-node.js';\nexport * from './operation-node/drop-schema-node.js';\nexport * from './operation-node/drop-table-node.js';\nexport * from './operation-node/drop-type-node.js';\nexport * from './operation-node/drop-view-node.js';\nexport * from './operation-node/explain-node.js';\nexport * from './operation-node/fetch-node.js';\nexport * from './operation-node/foreign-key-constraint-node.js';\nexport * from './operation-node/from-node.js';\nexport * from './operation-node/function-node.js';\nexport * from './operation-node/generated-node.js';\nexport * from './operation-node/group-by-item-node.js';\nexport * from './operation-node/group-by-node.js';\nexport * from './operation-node/having-node.js';\nexport * from './operation-node/identifier-node.js';\nexport * from './operation-node/insert-query-node.js';\nexport * from './operation-node/join-node.js';\nexport * from './operation-node/json-operator-chain-node.js';\nexport * from './operation-node/json-path-leg-node.js';\nexport * from './operation-node/json-path-node.js';\nexport * from './operation-node/json-reference-node.js';\nexport * from './operation-node/limit-node.js';\nexport * from './operation-node/list-node.js';\nexport * from './operation-node/matched-node.js';\nexport * from './operation-node/merge-query-node.js';\nexport * from './operation-node/modify-column-node.js';\nexport * from './operation-node/offset-node.js';\nexport * from './operation-node/on-conflict-node.js';\nexport * from './operation-node/on-duplicate-key-node.js';\nexport * from './operation-node/on-node.js';\nexport * from './operation-node/operation-node-source.js';\nexport * from './operation-node/operation-node-transformer.js';\nexport * from './operation-node/operation-node-visitor.js';\nexport * from './operation-node/operation-node.js';\nexport * from './operation-node/operator-node.js';\nexport * from './operation-node/or-action-node.js';\nexport * from './operation-node/or-node.js';\nexport * from './operation-node/order-by-item-node.js';\nexport * from './operation-node/order-by-node.js';\nexport * from './operation-node/output-node.js';\nexport * from './operation-node/over-node.js';\nexport * from './operation-node/parens-node.js';\nexport * from './operation-node/partition-by-item-node.js';\nexport * from './operation-node/partition-by-node.js';\nexport * from './operation-node/primary-key-constraint-node.js';\nexport * from './operation-node/primitive-value-list-node.js';\nexport * from './operation-node/query-node.js';\nexport * from './operation-node/raw-node.js';\nexport * from './operation-node/reference-node.js';\nexport * from './operation-node/references-node.js';\nexport * from './operation-node/rename-column-node.js';\nexport * from './operation-node/rename-constraint-node.js';\nexport * from './operation-node/returning-node.js';\nexport * from './operation-node/schemable-identifier-node.js';\nexport * from './operation-node/select-all-node.js';\nexport * from './operation-node/select-modifier-node.js';\nexport * from './operation-node/select-query-node.js';\nexport * from './operation-node/selection-node.js';\nexport * from './operation-node/set-operation-node.js';\nexport * from './operation-node/simple-reference-expression-node.js';\nexport * from './operation-node/table-node.js';\nexport * from './operation-node/top-node.js';\nexport * from './operation-node/tuple-node.js';\nexport * from './operation-node/unary-operation-node.js';\nexport * from './operation-node/unique-constraint-node.js';\nexport * from './operation-node/update-query-node.js';\nexport * from './operation-node/using-node.js';\nexport * from './operation-node/value-list-node.js';\nexport * from './operation-node/value-node.js';\nexport * from './operation-node/values-node.js';\nexport * from './operation-node/when-node.js';\nexport * from './operation-node/where-node.js';\nexport * from './operation-node/with-node.js';\nexport * from './util/column-type.js';\nexport * from './util/compilable.js';\nexport * from './util/explainable.js';\nexport * from './util/streamable.js';\nexport * from './util/log.js';\nexport * from './util/infer-result.js';\nexport { logOnce } from './util/log-once.js';\nexport { createQueryId } from './util/query-id.js';\n", "//#region src/utils/string.ts\nfunction capitalizeFirstLetter(str) {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n//#endregion\nexport { capitalizeFirstLetter };\n", "import { CompiledQuery, DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, DefaultQueryCompiler, sql } from \"kysely\";\n//#region src/bun-sqlite-dialect.ts\nvar BunSqliteAdapter = class {\n\tget supportsCreateIfNotExists() {\n\t\treturn true;\n\t}\n\tget supportsTransactionalDdl() {\n\t\treturn false;\n\t}\n\tget supportsReturning() {\n\t\treturn true;\n\t}\n\tasync acquireMigrationLock() {}\n\tasync releaseMigrationLock() {}\n\tget supportsOutput() {\n\t\treturn true;\n\t}\n};\nvar BunSqliteDriver = class {\n\t#config;\n\t#connectionMutex = new ConnectionMutex();\n\t#db;\n\t#connection;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tasync init() {\n\t\tthis.#db = this.#config.database;\n\t\tthis.#connection = new BunSqliteConnection(this.#db);\n\t\tif (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);\n\t}\n\tasync acquireConnection() {\n\t\tawait this.#connectionMutex.lock();\n\t\treturn this.#connection;\n\t}\n\tasync beginTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"begin\"));\n\t}\n\tasync commitTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"commit\"));\n\t}\n\tasync rollbackTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"rollback\"));\n\t}\n\tasync releaseConnection() {\n\t\tthis.#connectionMutex.unlock();\n\t}\n\tasync destroy() {\n\t\tthis.#db?.close();\n\t}\n};\nvar BunSqliteConnection = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\texecuteQuery(compiledQuery) {\n\t\tconst { sql, parameters } = compiledQuery;\n\t\tconst stmt = this.#db.prepare(sql);\n\t\treturn Promise.resolve({ rows: stmt.all(parameters) });\n\t}\n\tasync *streamQuery() {\n\t\tthrow new Error(\"Streaming query is not supported by SQLite driver.\");\n\t}\n};\nvar ConnectionMutex = class {\n\t#promise;\n\t#resolve;\n\tasync lock() {\n\t\twhile (this.#promise !== void 0) await this.#promise;\n\t\tthis.#promise = new Promise((resolve) => {\n\t\t\tthis.#resolve = resolve;\n\t\t});\n\t}\n\tunlock() {\n\t\tconst resolve = this.#resolve;\n\t\tthis.#promise = void 0;\n\t\tthis.#resolve = void 0;\n\t\tresolve?.();\n\t}\n};\nvar BunSqliteIntrospector = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\tasync getSchemas() {\n\t\treturn [];\n\t}\n\tasync getTables(options = { withInternalKyselyTables: false }) {\n\t\tlet query = this.#db.selectFrom(\"sqlite_schema\").where(\"type\", \"=\", \"table\").where(\"name\", \"not like\", \"sqlite_%\").select(\"name\").$castTo();\n\t\tif (!options.withInternalKyselyTables) query = query.where(\"name\", \"!=\", DEFAULT_MIGRATION_TABLE).where(\"name\", \"!=\", DEFAULT_MIGRATION_LOCK_TABLE);\n\t\tconst tables = await query.execute();\n\t\treturn Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));\n\t}\n\tasync getMetadata(options) {\n\t\treturn { tables: await this.getTables(options) };\n\t}\n\tasync #getTableMetadata(table) {\n\t\tconst db = this.#db;\n\t\tconst autoIncrementCol = (await db.selectFrom(\"sqlite_master\").where(\"name\", \"=\", table).select(\"sql\").$castTo().execute())[0]?.sql?.split(/[\\(\\),]/)?.find((it) => it.toLowerCase().includes(\"autoincrement\"))?.split(/\\s+/)?.[0]?.replace(/[\"`]/g, \"\");\n\t\treturn {\n\t\t\tname: table,\n\t\t\tcolumns: (await db.selectFrom(sql`pragma_table_info(${table})`.as(\"table_info\")).select([\n\t\t\t\t\"name\",\n\t\t\t\t\"type\",\n\t\t\t\t\"notnull\",\n\t\t\t\t\"dflt_value\"\n\t\t\t]).execute()).map((col) => ({\n\t\t\t\tname: col.name,\n\t\t\t\tdataType: col.type,\n\t\t\t\tisNullable: !col.notnull,\n\t\t\t\tisAutoIncrementing: col.name === autoIncrementCol,\n\t\t\t\thasDefaultValue: col.dflt_value != null\n\t\t\t})),\n\t\t\tisView: true\n\t\t};\n\t}\n};\nvar BunSqliteQueryCompiler = class extends DefaultQueryCompiler {\n\tgetCurrentParameterPlaceholder() {\n\t\treturn \"?\";\n\t}\n\tgetLeftIdentifierWrapper() {\n\t\treturn \"\\\"\";\n\t}\n\tgetRightIdentifierWrapper() {\n\t\treturn \"\\\"\";\n\t}\n\tgetAutoIncrement() {\n\t\treturn \"autoincrement\";\n\t}\n};\nvar BunSqliteDialect = class {\n\t#config;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tcreateDriver() {\n\t\treturn new BunSqliteDriver(this.#config);\n\t}\n\tcreateQueryCompiler() {\n\t\treturn new BunSqliteQueryCompiler();\n\t}\n\tcreateAdapter() {\n\t\treturn new BunSqliteAdapter();\n\t}\n\tcreateIntrospector(db) {\n\t\treturn new BunSqliteIntrospector(db);\n\t}\n};\n//#endregion\nexport { BunSqliteDialect };\n", "import { CompiledQuery, DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, DefaultQueryCompiler, sql } from \"kysely\";\n//#region src/node-sqlite-dialect.ts\nvar NodeSqliteAdapter = class {\n\tget supportsCreateIfNotExists() {\n\t\treturn true;\n\t}\n\tget supportsTransactionalDdl() {\n\t\treturn false;\n\t}\n\tget supportsReturning() {\n\t\treturn true;\n\t}\n\tasync acquireMigrationLock() {}\n\tasync releaseMigrationLock() {}\n\tget supportsOutput() {\n\t\treturn true;\n\t}\n};\nvar NodeSqliteDriver = class {\n\t#config;\n\t#connectionMutex = new ConnectionMutex();\n\t#db;\n\t#connection;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tasync init() {\n\t\tthis.#db = this.#config.database;\n\t\tthis.#connection = new NodeSqliteConnection(this.#db);\n\t\tif (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);\n\t}\n\tasync acquireConnection() {\n\t\tawait this.#connectionMutex.lock();\n\t\treturn this.#connection;\n\t}\n\tasync beginTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"begin\"));\n\t}\n\tasync commitTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"commit\"));\n\t}\n\tasync rollbackTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"rollback\"));\n\t}\n\tasync releaseConnection() {\n\t\tthis.#connectionMutex.unlock();\n\t}\n\tasync destroy() {\n\t\tthis.#db?.close();\n\t}\n};\nvar NodeSqliteConnection = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\texecuteQuery(compiledQuery) {\n\t\tconst { sql, parameters } = compiledQuery;\n\t\tconst rows = this.#db.prepare(sql).all(...parameters);\n\t\treturn Promise.resolve({ rows });\n\t}\n\tasync *streamQuery() {\n\t\tthrow new Error(\"Streaming query is not supported by SQLite driver.\");\n\t}\n};\nvar ConnectionMutex = class {\n\t#promise;\n\t#resolve;\n\tasync lock() {\n\t\twhile (this.#promise !== void 0) await this.#promise;\n\t\tthis.#promise = new Promise((resolve) => {\n\t\t\tthis.#resolve = resolve;\n\t\t});\n\t}\n\tunlock() {\n\t\tconst resolve = this.#resolve;\n\t\tthis.#promise = void 0;\n\t\tthis.#resolve = void 0;\n\t\tresolve?.();\n\t}\n};\nvar NodeSqliteIntrospector = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\tasync getSchemas() {\n\t\treturn [];\n\t}\n\tasync getTables(options = { withInternalKyselyTables: false }) {\n\t\tlet query = this.#db.selectFrom(\"sqlite_schema\").where(\"type\", \"=\", \"table\").where(\"name\", \"not like\", \"sqlite_%\").select(\"name\").$castTo();\n\t\tif (!options.withInternalKyselyTables) query = query.where(\"name\", \"!=\", DEFAULT_MIGRATION_TABLE).where(\"name\", \"!=\", DEFAULT_MIGRATION_LOCK_TABLE);\n\t\tconst tables = await query.execute();\n\t\treturn Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));\n\t}\n\tasync getMetadata(options) {\n\t\treturn { tables: await this.getTables(options) };\n\t}\n\tasync #getTableMetadata(table) {\n\t\tconst db = this.#db;\n\t\tconst autoIncrementCol = (await db.selectFrom(\"sqlite_master\").where(\"name\", \"=\", table).select(\"sql\").$castTo().execute())[0]?.sql?.split(/[\\(\\),]/)?.find((it) => it.toLowerCase().includes(\"autoincrement\"))?.split(/\\s+/)?.[0]?.replace(/[\"`]/g, \"\");\n\t\treturn {\n\t\t\tname: table,\n\t\t\tcolumns: (await db.selectFrom(sql`pragma_table_info(${table})`.as(\"table_info\")).select([\n\t\t\t\t\"name\",\n\t\t\t\t\"type\",\n\t\t\t\t\"notnull\",\n\t\t\t\t\"dflt_value\"\n\t\t\t]).execute()).map((col) => ({\n\t\t\t\tname: col.name,\n\t\t\t\tdataType: col.type,\n\t\t\t\tisNullable: !col.notnull,\n\t\t\t\tisAutoIncrementing: col.name === autoIncrementCol,\n\t\t\t\thasDefaultValue: col.dflt_value != null\n\t\t\t})),\n\t\t\tisView: true\n\t\t};\n\t}\n};\nvar NodeSqliteQueryCompiler = class extends DefaultQueryCompiler {\n\tgetCurrentParameterPlaceholder() {\n\t\treturn \"?\";\n\t}\n\tgetLeftIdentifierWrapper() {\n\t\treturn \"\\\"\";\n\t}\n\tgetRightIdentifierWrapper() {\n\t\treturn \"\\\"\";\n\t}\n\tgetAutoIncrement() {\n\t\treturn \"autoincrement\";\n\t}\n};\nvar NodeSqliteDialect = class {\n\t#config;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tcreateDriver() {\n\t\treturn new NodeSqliteDriver(this.#config);\n\t}\n\tcreateQueryCompiler() {\n\t\treturn new NodeSqliteQueryCompiler();\n\t}\n\tcreateAdapter() {\n\t\treturn new NodeSqliteAdapter();\n\t}\n\tcreateIntrospector(db) {\n\t\treturn new NodeSqliteIntrospector(db);\n\t}\n};\n//#endregion\nexport { NodeSqliteDialect };\n", "import { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, SqliteAdapter, SqliteQueryCompiler } from \"kysely\";\n//#region src/d1-sqlite-dialect.ts\nvar D1SqliteAdapter = class extends SqliteAdapter {};\nvar D1SqliteDriver = class {\n\t#config;\n\t#connection;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tasync init() {\n\t\tthis.#connection = new D1SqliteConnection(this.#config.database);\n\t\tif (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);\n\t}\n\tasync acquireConnection() {\n\t\treturn this.#connection;\n\t}\n\tasync beginTransaction() {\n\t\tthrow new Error(\"D1 does not support interactive transactions. Use the D1 batch() API instead.\");\n\t}\n\tasync commitTransaction() {\n\t\tthrow new Error(\"D1 does not support interactive transactions. Use the D1 batch() API instead.\");\n\t}\n\tasync rollbackTransaction() {\n\t\tthrow new Error(\"D1 does not support interactive transactions. Use the D1 batch() API instead.\");\n\t}\n\tasync releaseConnection() {}\n\tasync destroy() {}\n};\nvar D1SqliteConnection = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\tasync executeQuery(compiledQuery) {\n\t\tconst results = await this.#db.prepare(compiledQuery.sql).bind(...compiledQuery.parameters).all();\n\t\tconst numAffectedRows = results.meta.changes != null ? BigInt(results.meta.changes) : void 0;\n\t\treturn {\n\t\t\tinsertId: results.meta.last_row_id === void 0 || results.meta.last_row_id === null ? void 0 : BigInt(results.meta.last_row_id),\n\t\t\trows: results?.results || [],\n\t\t\tnumAffectedRows\n\t\t};\n\t}\n\tasync *streamQuery() {\n\t\tthrow new Error(\"D1 does not support streaming queries.\");\n\t}\n};\nvar D1SqliteIntrospector = class {\n\t#db;\n\t#d1;\n\tconstructor(db, d1) {\n\t\tthis.#db = db;\n\t\tthis.#d1 = d1;\n\t}\n\tasync getSchemas() {\n\t\treturn [];\n\t}\n\tasync getTables(options = { withInternalKyselyTables: false }) {\n\t\tlet query = this.#db.selectFrom(\"sqlite_master\").where(\"type\", \"in\", [\"table\", \"view\"]).where(\"name\", \"not like\", \"sqlite_%\").where(\"name\", \"not like\", \"_cf_%\").select([\n\t\t\t\"name\",\n\t\t\t\"type\",\n\t\t\t\"sql\"\n\t\t]).$castTo();\n\t\tif (!options.withInternalKyselyTables) query = query.where(\"name\", \"!=\", DEFAULT_MIGRATION_TABLE).where(\"name\", \"!=\", DEFAULT_MIGRATION_LOCK_TABLE);\n\t\tconst tables = await query.execute();\n\t\tif (tables.length === 0) return [];\n\t\tconst statements = tables.map((table) => this.#d1.prepare(\"SELECT * FROM pragma_table_info(?)\").bind(table.name));\n\t\tconst batchResults = await this.#d1.batch(statements);\n\t\treturn tables.map((table, index) => {\n\t\t\tconst columnInfo = batchResults[index]?.results ?? [];\n\t\t\tlet autoIncrementCol = table.sql?.split(/[(),]/)?.find((it) => it.toLowerCase().includes(\"autoincrement\"))?.split(/\\s+/)?.filter(Boolean)?.[0]?.replace(/[\"`]/g, \"\");\n\t\t\tif (!autoIncrementCol) {\n\t\t\t\tconst pkCols = columnInfo.filter((r) => r.pk > 0);\n\t\t\t\tconst singlePk = pkCols.length === 1 ? pkCols[0] : void 0;\n\t\t\t\tif (singlePk && singlePk.type.toLowerCase() === \"integer\") autoIncrementCol = singlePk.name;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tname: table.name,\n\t\t\t\tisView: table.type === \"view\",\n\t\t\t\tcolumns: columnInfo.map((col) => ({\n\t\t\t\t\tname: col.name,\n\t\t\t\t\tdataType: col.type,\n\t\t\t\t\tisNullable: !col.notnull,\n\t\t\t\t\tisAutoIncrementing: col.name === autoIncrementCol,\n\t\t\t\t\thasDefaultValue: col.dflt_value != null\n\t\t\t\t}))\n\t\t\t};\n\t\t});\n\t}\n\tasync getMetadata(options) {\n\t\treturn { tables: await this.getTables(options) };\n\t}\n};\nvar D1SqliteQueryCompiler = class extends SqliteQueryCompiler {};\nvar D1SqliteDialect = class {\n\t#config;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tcreateDriver() {\n\t\treturn new D1SqliteDriver(this.#config);\n\t}\n\tcreateQueryCompiler() {\n\t\treturn new D1SqliteQueryCompiler();\n\t}\n\tcreateAdapter() {\n\t\treturn new D1SqliteAdapter();\n\t}\n\tcreateIntrospector(db) {\n\t\treturn new D1SqliteIntrospector(db, this.#config.database);\n\t}\n};\n//#endregion\nexport { D1SqliteDialect };\n", "import { Kysely, MssqlDialect, MysqlDialect, PostgresDialect, SqliteDialect, sql } from \"kysely\";\nimport { createAdapterFactory } from \"@better-auth/core/db/adapter\";\nimport { capitalizeFirstLetter } from \"@better-auth/core/utils/string\";\n//#region src/dialect.ts\nfunction getKyselyDatabaseType(db) {\n\tif (!db) return null;\n\tif (\"dialect\" in db) return getKyselyDatabaseType(db.dialect);\n\tif (\"createDriver\" in db) {\n\t\tif (db instanceof SqliteDialect) return \"sqlite\";\n\t\tif (db instanceof MysqlDialect) return \"mysql\";\n\t\tif (db instanceof PostgresDialect) return \"postgres\";\n\t\tif (db instanceof MssqlDialect) return \"mssql\";\n\t}\n\tif (\"aggregate\" in db) return \"sqlite\";\n\tif (\"getConnection\" in db) return \"mysql\";\n\tif (\"connect\" in db) return \"postgres\";\n\tif (\"fileControl\" in db) return \"sqlite\";\n\tif (\"open\" in db && \"close\" in db && \"prepare\" in db) return \"sqlite\";\n\tif (\"batch\" in db && \"exec\" in db && \"prepare\" in db) return \"sqlite\";\n\treturn null;\n}\nconst createKyselyAdapter = async (config) => {\n\tconst db = config.database;\n\tif (!db) return {\n\t\tkysely: null,\n\t\tdatabaseType: null,\n\t\ttransaction: void 0\n\t};\n\tif (\"db\" in db) return {\n\t\tkysely: db.db,\n\t\tdatabaseType: db.type,\n\t\ttransaction: db.transaction\n\t};\n\tif (\"dialect\" in db) return {\n\t\tkysely: new Kysely({ dialect: db.dialect }),\n\t\tdatabaseType: db.type,\n\t\ttransaction: db.transaction\n\t};\n\tlet dialect = void 0;\n\tconst databaseType = getKyselyDatabaseType(db);\n\tif (\"createDriver\" in db) dialect = db;\n\tif (\"aggregate\" in db && !(\"createSession\" in db)) dialect = new SqliteDialect({ database: db });\n\tif (\"getConnection\" in db) dialect = new MysqlDialect(db);\n\tif (\"connect\" in db) dialect = new PostgresDialect({ pool: db });\n\tif (\"fileControl\" in db) {\n\t\tconst { BunSqliteDialect } = await import(\"./bun-sqlite-dialect-na--YwnN.mjs\");\n\t\tdialect = new BunSqliteDialect({ database: db });\n\t}\n\tif (\"createSession\" in db) {\n\t\tlet DatabaseSync = void 0;\n\t\ttry {\n\t\t\tconst nodeSqlite = \"node:sqlite\";\n\t\t\t({DatabaseSync} = await import(\n\t\t\t\t/* @vite-ignore */\n\t\t\t\t/* webpackIgnore: true */\n\t\t\t\tnodeSqlite\n));\n\t\t} catch (error) {\n\t\t\tif (error !== null && typeof error === \"object\" && \"code\" in error && error.code !== \"ERR_UNKNOWN_BUILTIN_MODULE\") throw error;\n\t\t}\n\t\tif (DatabaseSync && db instanceof DatabaseSync) {\n\t\t\tconst { NodeSqliteDialect } = await import(\"./node-sqlite-dialect.mjs\");\n\t\t\tdialect = new NodeSqliteDialect({ database: db });\n\t\t}\n\t}\n\tif (\"batch\" in db && \"exec\" in db && \"prepare\" in db) {\n\t\tconst { D1SqliteDialect } = await import(\"./d1-sqlite-dialect-C2B7YsIT.mjs\");\n\t\tdialect = new D1SqliteDialect({ database: db });\n\t}\n\treturn {\n\t\tkysely: dialect ? new Kysely({ dialect }) : null,\n\t\tdatabaseType,\n\t\ttransaction: void 0\n\t};\n};\n//#endregion\n//#region src/query-builders.ts\n/**\n* Case-insensitive ILIKE/LIKE for pattern matching.\n* Uses ILIKE on PostgreSQL, LOWER()+LIKE on MySQL/SQLite/MSSQL.\n*/\nfunction insensitiveIlike(columnRef, pattern, dbType) {\n\treturn dbType === \"postgres\" ? sql`${sql.ref(columnRef)} ILIKE ${pattern}` : sql`LOWER(${sql.ref(columnRef)}) LIKE LOWER(${pattern})`;\n}\n/**\n* Case-insensitive IN for string arrays.\n* Returns { lhs, values } for use with eb(lhs, \"in\", values).\n*/\nfunction insensitiveIn(columnRef, values) {\n\treturn {\n\t\tlhs: sql`LOWER(${sql.ref(columnRef)})`,\n\t\tvalues: values.map((v) => v.toLowerCase())\n\t};\n}\n/**\n* Case-insensitive NOT IN for string arrays.\n*/\nfunction insensitiveNotIn(columnRef, values) {\n\treturn {\n\t\tlhs: sql`LOWER(${sql.ref(columnRef)})`,\n\t\tvalues: values.map((v) => v.toLowerCase())\n\t};\n}\n/**\n* Case-insensitive equality for strings.\n* Returns { lhs, value } for use with eb(lhs, \"=\", value).\n*/\nfunction insensitiveEq(columnRef, value) {\n\treturn {\n\t\tlhs: sql`LOWER(${sql.ref(columnRef)})`,\n\t\tvalue: value.toLowerCase()\n\t};\n}\n/**\n* Case-insensitive inequality for strings.\n*/\nfunction insensitiveNe(columnRef, value) {\n\treturn {\n\t\tlhs: sql`LOWER(${sql.ref(columnRef)})`,\n\t\tvalue: value.toLowerCase()\n\t};\n}\n//#endregion\n//#region src/kysely-adapter.ts\nconst kyselyAdapter = (db, config) => {\n\tlet lazyOptions = null;\n\tconst createCustomAdapter = (db) => {\n\t\treturn ({ getFieldName, schema, getDefaultFieldName, getDefaultModelName, getFieldAttributes, getModelName }) => {\n\t\t\tconst selectAllJoins = (join) => {\n\t\t\t\tconst allSelects = [];\n\t\t\t\tconst allSelectsStr = [];\n\t\t\t\tif (join) for (const [joinModel, _] of Object.entries(join)) {\n\t\t\t\t\tconst fields = schema[getDefaultModelName(joinModel)]?.fields;\n\t\t\t\t\tconst [_joinModelSchema, joinModelName] = joinModel.includes(\".\") ? joinModel.split(\".\") : [void 0, joinModel];\n\t\t\t\t\tif (!fields) continue;\n\t\t\t\t\tfields.id = { type: \"string\" };\n\t\t\t\t\tfor (const [field, fieldAttr] of Object.entries(fields)) {\n\t\t\t\t\t\tallSelects.push(sql`${sql.ref(`join_${joinModelName}`)}.${sql.ref(fieldAttr.fieldName || field)} as ${sql.ref(`_joined_${joinModelName}_${fieldAttr.fieldName || field}`)}`);\n\t\t\t\t\t\tallSelectsStr.push({\n\t\t\t\t\t\t\tjoinModel,\n\t\t\t\t\t\t\tjoinModelRef: joinModelName,\n\t\t\t\t\t\t\tfieldName: fieldAttr.fieldName || field\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tallSelectsStr,\n\t\t\t\t\tallSelects\n\t\t\t\t};\n\t\t\t};\n\t\t\tconst withReturning = async (values, builder, model, where) => {\n\t\t\t\tlet res;\n\t\t\t\tif (config?.type === \"mysql\") {\n\t\t\t\t\tawait builder.execute();\n\t\t\t\t\tconst field = values.id ? \"id\" : where.length > 0 && where[0]?.field ? where[0].field : \"id\";\n\t\t\t\t\tif (!values.id && where.length === 0) {\n\t\t\t\t\t\tres = await db.selectFrom(model).selectAll().orderBy(getFieldName({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tfield\n\t\t\t\t\t\t}), \"desc\").limit(1).executeTakeFirst();\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tconst value = values[field] !== void 0 ? values[field] : where[0]?.value;\n\t\t\t\t\tres = await db.selectFrom(model).selectAll().orderBy(getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield\n\t\t\t\t\t}), \"desc\").where(getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield\n\t\t\t\t\t}), value === null ? \"is\" : \"=\", value).limit(1).executeTakeFirst();\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tif (config?.type === \"mssql\") {\n\t\t\t\t\tres = await builder.outputAll(\"inserted\").executeTakeFirst();\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tres = await builder.returningAll().executeTakeFirst();\n\t\t\t\treturn res;\n\t\t\t};\n\t\t\tfunction convertWhereClause(model, w) {\n\t\t\t\tif (!w) return {\n\t\t\t\t\tand: null,\n\t\t\t\t\tor: null\n\t\t\t\t};\n\t\t\t\tconst conditions = {\n\t\t\t\t\tand: [],\n\t\t\t\t\tor: []\n\t\t\t\t};\n\t\t\t\tw.forEach((condition) => {\n\t\t\t\t\tconst { field: _field, value: _value, operator = \"eq\", connector = \"AND\", mode = \"sensitive\" } = condition;\n\t\t\t\t\tconst value = _value;\n\t\t\t\t\tconst field = getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield: _field\n\t\t\t\t\t});\n\t\t\t\t\tconst isInsensitive = mode === \"insensitive\" && (typeof value === \"string\" || Array.isArray(value) && value.every((v) => typeof v === \"string\"));\n\t\t\t\t\tconst expr = (eb) => {\n\t\t\t\t\t\tconst f = `${model}.${field}`;\n\t\t\t\t\t\tif (operator.toLowerCase() === \"in\") {\n\t\t\t\t\t\t\tif (isInsensitive) {\n\t\t\t\t\t\t\t\tconst { lhs, values } = insensitiveIn(f, Array.isArray(value) ? value : [value]);\n\t\t\t\t\t\t\t\treturn eb(lhs, \"in\", values);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn eb(f, \"in\", Array.isArray(value) ? value : [value]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator.toLowerCase() === \"not_in\") {\n\t\t\t\t\t\t\tif (isInsensitive) {\n\t\t\t\t\t\t\t\tconst { lhs, values } = insensitiveNotIn(f, Array.isArray(value) ? value : [value]);\n\t\t\t\t\t\t\t\treturn eb(lhs, \"not in\", values);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn eb(f, \"not in\", Array.isArray(value) ? value : [value]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"contains\") {\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") return insensitiveIlike(f, `%${value}%`, config?.type);\n\t\t\t\t\t\t\treturn eb(f, \"like\", `%${value}%`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"starts_with\") {\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") return insensitiveIlike(f, `${value}%`, config?.type);\n\t\t\t\t\t\t\treturn eb(f, \"like\", `${value}%`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"ends_with\") {\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") return insensitiveIlike(f, `%${value}`, config?.type);\n\t\t\t\t\t\t\treturn eb(f, \"like\", `%${value}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"eq\") {\n\t\t\t\t\t\t\tif (value === null) return eb(f, \"is\", null);\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") {\n\t\t\t\t\t\t\t\tconst { lhs, value: v } = insensitiveEq(f, value);\n\t\t\t\t\t\t\t\treturn eb(lhs, \"=\", v);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn eb(f, \"=\", value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"ne\") {\n\t\t\t\t\t\t\tif (value === null) return eb(f, \"is not\", null);\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") {\n\t\t\t\t\t\t\t\tconst { lhs, value: v } = insensitiveNe(f, value);\n\t\t\t\t\t\t\t\treturn eb(lhs, \"<>\", v);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn eb(f, \"<>\", value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"gt\") return eb(f, \">\", value);\n\t\t\t\t\t\tif (operator === \"gte\") return eb(f, \">=\", value);\n\t\t\t\t\t\tif (operator === \"lt\") return eb(f, \"<\", value);\n\t\t\t\t\t\tif (operator === \"lte\") return eb(f, \"<=\", value);\n\t\t\t\t\t\treturn eb(f, operator, value);\n\t\t\t\t\t};\n\t\t\t\t\tif (connector === \"OR\") conditions.or.push(expr);\n\t\t\t\t\telse conditions.and.push(expr);\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tand: conditions.and.length ? conditions.and : null,\n\t\t\t\t\tor: conditions.or.length ? conditions.or : null\n\t\t\t\t};\n\t\t\t}\n\t\t\tfunction processJoinedResults(rows, joinConfig, allSelectsStr) {\n\t\t\t\tif (!joinConfig || !rows.length) return rows;\n\t\t\t\tconst groupedByMainId = /* @__PURE__ */ new Map();\n\t\t\t\tfor (const currentRow of rows) {\n\t\t\t\t\tconst mainModelFields = {};\n\t\t\t\t\tconst joinedModelFields = {};\n\t\t\t\t\tfor (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[getModelName(joinModel)] = {};\n\t\t\t\t\tfor (const [key, value] of Object.entries(currentRow)) {\n\t\t\t\t\t\tconst keyStr = String(key);\n\t\t\t\t\t\tlet assigned = false;\n\t\t\t\t\t\tfor (const { joinModel, fieldName, joinModelRef } of allSelectsStr) if (keyStr === `_joined_${joinModelRef}_${fieldName}` || keyStr === `_Joined${capitalizeFirstLetter(joinModelRef)}${capitalizeFirstLetter(fieldName)}`) {\n\t\t\t\t\t\t\tjoinedModelFields[getModelName(joinModel)][getFieldName({\n\t\t\t\t\t\t\t\tmodel: joinModel,\n\t\t\t\t\t\t\t\tfield: fieldName\n\t\t\t\t\t\t\t})] = value;\n\t\t\t\t\t\t\tassigned = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!assigned) mainModelFields[key] = value;\n\t\t\t\t\t}\n\t\t\t\t\tconst mainId = mainModelFields.id;\n\t\t\t\t\tif (!mainId) continue;\n\t\t\t\t\tif (!groupedByMainId.has(mainId)) {\n\t\t\t\t\t\tconst entry = { ...mainModelFields };\n\t\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry[getModelName(joinModel)] = joinAttr.relation === \"one-to-one\" ? null : [];\n\t\t\t\t\t\tgroupedByMainId.set(mainId, entry);\n\t\t\t\t\t}\n\t\t\t\t\tconst entry = groupedByMainId.get(mainId);\n\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(joinConfig)) {\n\t\t\t\t\t\tconst isUnique = joinAttr.relation === \"one-to-one\";\n\t\t\t\t\t\tconst limit = joinAttr.limit ?? 100;\n\t\t\t\t\t\tconst joinedObj = joinedModelFields[getModelName(joinModel)];\n\t\t\t\t\t\tconst hasData = joinedObj && Object.keys(joinedObj).length > 0 && Object.values(joinedObj).some((value) => value !== null && value !== void 0);\n\t\t\t\t\t\tif (isUnique) entry[getModelName(joinModel)] = hasData ? joinedObj : null;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\t\tif (Array.isArray(entry[joinModelName]) && hasData) {\n\t\t\t\t\t\t\t\tif (entry[joinModelName].length >= limit) continue;\n\t\t\t\t\t\t\t\tconst idFieldName = getFieldName({\n\t\t\t\t\t\t\t\t\tmodel: joinModel,\n\t\t\t\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst joinedId = joinedObj[idFieldName];\n\t\t\t\t\t\t\t\tif (joinedId) {\n\t\t\t\t\t\t\t\t\tif (!entry[joinModelName].some((item) => item[idFieldName] === joinedId) && entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj);\n\t\t\t\t\t\t\t\t} else if (entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst result = Array.from(groupedByMainId.values());\n\t\t\t\tfor (const entry of result) for (const [joinModel, joinAttr] of Object.entries(joinConfig)) if (joinAttr.relation !== \"one-to-one\") {\n\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\tif (Array.isArray(entry[joinModelName])) {\n\t\t\t\t\t\tconst limit = joinAttr.limit ?? 100;\n\t\t\t\t\t\tif (entry[joinModelName].length > limit) entry[joinModelName] = entry[joinModelName].slice(0, limit);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tasync create({ data, model }) {\n\t\t\t\t\treturn await withReturning(data, db.insertInto(model).values(data), model, []);\n\t\t\t\t},\n\t\t\t\tasync findOne({ model, where, select, join }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.selectFrom((eb) => {\n\t\t\t\t\t\tlet b = eb.selectFrom(model);\n\t\t\t\t\t\tif (and) b = b.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\t\tif (or) b = b.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\t\tif (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tfield\n\t\t\t\t\t\t})));\n\t\t\t\t\t\telse b = b.selectAll();\n\t\t\t\t\t\treturn b.as(\"primary\");\n\t\t\t\t\t}).selectAll(\"primary\");\n\t\t\t\t\tif (join) for (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\tconst [_joinModelSchema, joinModelName] = joinModel.includes(\".\") ? joinModel.split(\".\") : [void 0, joinModel];\n\t\t\t\t\t\tquery = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join) => join.onRef(`join_${joinModelName}.${joinAttr.on.to}`, \"=\", `primary.${joinAttr.on.from}`));\n\t\t\t\t\t}\n\t\t\t\t\tconst { allSelectsStr, allSelects } = selectAllJoins(join);\n\t\t\t\t\tquery = query.select(allSelects);\n\t\t\t\t\tconst res = await query.execute();\n\t\t\t\t\tif (!res || !Array.isArray(res) || res.length === 0) return null;\n\t\t\t\t\tconst row = res[0];\n\t\t\t\t\tif (join) return processJoinedResults(res, join, allSelectsStr)[0];\n\t\t\t\t\treturn row;\n\t\t\t\t},\n\t\t\t\tasync findMany({ model, where, limit, select, offset, sortBy, join }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.selectFrom((eb) => {\n\t\t\t\t\t\tlet b = eb.selectFrom(model);\n\t\t\t\t\t\tif (config?.type === \"mssql\") {\n\t\t\t\t\t\t\tif (offset !== void 0) {\n\t\t\t\t\t\t\t\tif (!sortBy) b = b.orderBy(getFieldName({\n\t\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\tb = b.offset(offset).fetch(limit || 100);\n\t\t\t\t\t\t\t} else if (limit !== void 0) b = b.top(limit);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (limit !== void 0) b = b.limit(limit);\n\t\t\t\t\t\t\tif (offset !== void 0) b = b.offset(offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (sortBy?.field) b = b.orderBy(`${getFieldName({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tfield: sortBy.field\n\t\t\t\t\t\t})}`, sortBy.direction);\n\t\t\t\t\t\tif (and) b = b.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\t\tif (or) b = b.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\t\tif (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tfield\n\t\t\t\t\t\t})));\n\t\t\t\t\t\telse b = b.selectAll();\n\t\t\t\t\t\treturn b.as(\"primary\");\n\t\t\t\t\t}).selectAll(\"primary\");\n\t\t\t\t\tif (join) for (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\tconst [_joinModelSchema, joinModelName] = joinModel.includes(\".\") ? joinModel.split(\".\") : [void 0, joinModel];\n\t\t\t\t\t\tquery = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join) => join.onRef(`join_${joinModelName}.${joinAttr.on.to}`, \"=\", `primary.${joinAttr.on.from}`));\n\t\t\t\t\t}\n\t\t\t\t\tconst { allSelectsStr, allSelects } = selectAllJoins(join);\n\t\t\t\t\tquery = query.select(allSelects);\n\t\t\t\t\tif (sortBy?.field) query = query.orderBy(`${getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield: sortBy.field\n\t\t\t\t\t})}`, sortBy.direction);\n\t\t\t\t\tconst res = await query.execute();\n\t\t\t\t\tif (!res) return [];\n\t\t\t\t\tif (join) return processJoinedResults(res, join, allSelectsStr);\n\t\t\t\t\treturn res;\n\t\t\t\t},\n\t\t\t\tasync update({ model, where, update: values }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.updateTable(model).set(values);\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\treturn await withReturning(values, query, model, where);\n\t\t\t\t},\n\t\t\t\tasync updateMany({ model, where, update: values }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.updateTable(model).set(values);\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\tconst res = (await query.executeTakeFirst()).numUpdatedRows;\n\t\t\t\t\treturn res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res);\n\t\t\t\t},\n\t\t\t\tasync count({ model, where }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.selectFrom(model).select(db.fn.count(\"id\").as(\"count\"));\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\tconst res = await query.execute();\n\t\t\t\t\tif (typeof res[0].count === \"number\") return res[0].count;\n\t\t\t\t\tif (typeof res[0].count === \"bigint\") return Number(res[0].count);\n\t\t\t\t\treturn parseInt(res[0].count);\n\t\t\t\t},\n\t\t\t\tasync delete({ model, where }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.deleteFrom(model);\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\tawait query.execute();\n\t\t\t\t},\n\t\t\t\tasync deleteMany({ model, where }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.deleteFrom(model);\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\tconst res = (await query.executeTakeFirst()).numDeletedRows;\n\t\t\t\t\treturn res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res);\n\t\t\t\t},\n\t\t\t\toptions: config\n\t\t\t};\n\t\t};\n\t};\n\tlet adapterOptions = null;\n\tadapterOptions = {\n\t\tconfig: {\n\t\t\tadapterId: \"kysely\",\n\t\t\tadapterName: \"Kysely Adapter\",\n\t\t\tusePlural: config?.usePlural,\n\t\t\tdebugLogs: config?.debugLogs,\n\t\t\tsupportsBooleans: config?.type === \"sqlite\" || config?.type === \"mssql\" || config?.type === \"mysql\" || !config?.type ? false : true,\n\t\t\tsupportsDates: config?.type === \"sqlite\" || config?.type === \"mssql\" || !config?.type ? false : true,\n\t\t\tsupportsJSON: config?.type === \"postgres\" ? true : false,\n\t\t\tsupportsArrays: false,\n\t\t\tsupportsUUIDs: config?.type === \"postgres\" ? true : false,\n\t\t\ttransaction: config?.transaction ? (cb) => db.transaction().execute((trx) => {\n\t\t\t\treturn cb(createAdapterFactory({\n\t\t\t\t\tconfig: adapterOptions.config,\n\t\t\t\t\tadapter: createCustomAdapter(trx)\n\t\t\t\t})(lazyOptions));\n\t\t\t}) : false\n\t\t},\n\t\tadapter: createCustomAdapter(db)\n\t};\n\tconst adapter = createAdapterFactory(adapterOptions);\n\treturn (options) => {\n\t\tlazyOptions = options;\n\t\treturn adapter(options);\n\t};\n};\n//#endregion\nexport { createKyselyAdapter, getKyselyDatabaseType, kyselyAdapter };\n", "export * from \"@better-auth/kysely-adapter\";\nexport {};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Application-Level Cache Protocol\n * \n * Multi-tier caching strategy for application data.\n * Supports Memory, Redis, Memcached, and CDN.\n * \n * ## Caching in ObjectStack\n * \n * **Application Cache (`system/cache.zod.ts`) - This File**\n * - **Purpose**: Cache computed data, query results, aggregations\n * - **Technologies**: Redis, Memcached, in-memory LRU\n * - **Configuration**: TTL, eviction policies, cache warming\n * - **Use case**: Cache expensive database queries, computed values\n * - **Scope**: Application layer, server-side data storage\n * \n * **HTTP Cache (`api/http-cache.zod.ts`)**\n * - **Purpose**: Cache API responses at HTTP protocol level\n * - **Technologies**: HTTP headers (ETag, Last-Modified, Cache-Control), CDN\n * - **Configuration**: Cache-Control headers, validation tokens\n * - **Use case**: Reduce API response time for repeated metadata requests\n * - **Scope**: HTTP layer, client-server communication\n * \n * @see ../../api/http-cache.zod.ts for HTTP-level caching\n */\nexport const CacheStrategySchema = z.enum([\n 'lru', // Least Recently Used\n 'lfu', // Least Frequently Used\n 'fifo', // First In First Out\n 'ttl', // Time To Live only\n 'adaptive', // Dynamic strategy selection\n]).describe('Cache eviction strategy');\n\nexport type CacheStrategy = z.infer;\n\nexport const CacheTierSchema = z.object({\n name: z.string().describe('Unique cache tier name'),\n type: z.enum(['memory', 'redis', 'memcached', 'cdn']).describe('Cache backend type'),\n maxSize: z.number().optional().describe('Max size in MB'),\n ttl: z.number().default(300).describe('Default TTL in seconds'),\n strategy: CacheStrategySchema.default('lru').describe('Eviction strategy'),\n warmup: z.boolean().default(false).describe('Pre-populate cache on startup'),\n}).describe('Configuration for a single cache tier in the hierarchy');\n\nexport type CacheTier = z.infer;\nexport type CacheTierInput = z.input;\n\nexport const CacheInvalidationSchema = z.object({\n trigger: z.enum(['create', 'update', 'delete', 'manual']).describe('Event that triggers invalidation'),\n scope: z.enum(['key', 'pattern', 'tag', 'all']).describe('Invalidation scope'),\n pattern: z.string().optional().describe('Key pattern for pattern-based invalidation'),\n tags: z.array(z.string()).optional().describe('Cache tags to invalidate'),\n}).describe('Rule defining when and how cached entries are invalidated');\n\nexport type CacheInvalidation = z.infer;\n\nexport const CacheConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable application-level caching'),\n tiers: z.array(CacheTierSchema).describe('Ordered cache tier hierarchy'),\n invalidation: z.array(CacheInvalidationSchema).describe('Cache invalidation rules'),\n prefetch: z.boolean().default(false).describe('Enable cache prefetching'),\n compression: z.boolean().default(false).describe('Enable data compression in cache'),\n encryption: z.boolean().default(false).describe('Enable encryption for cached data'),\n}).describe('Top-level application cache configuration');\n\nexport type CacheConfig = z.infer;\nexport type CacheConfigInput = z.input;\n\n/**\n * Distributed Cache Consistency Schema\n *\n * Defines write strategies for distributed cache consistency.\n *\n * - **write_through**: Write to cache and backend simultaneously\n * - **write_behind**: Write to cache first, async persist to backend\n * - **write_around**: Write to backend only, cache on next read\n * - **refresh_ahead**: Proactively refresh expiring entries before TTL\n */\nexport const CacheConsistencySchema = z.enum([\n 'write_through',\n 'write_behind',\n 'write_around',\n 'refresh_ahead',\n]).describe('Distributed cache write consistency strategy');\n\nexport type CacheConsistency = z.infer;\n\n/**\n * Cache Avalanche Prevention Schema\n *\n * Strategies to prevent cache stampede/avalanche when many keys expire simultaneously.\n *\n * @example\n * ```typescript\n * const prevention: CacheAvalanchePrevention = {\n * jitterTtl: { enabled: true, maxJitterSeconds: 60 },\n * circuitBreaker: { enabled: true, failureThreshold: 5, resetTimeout: 30 },\n * lockout: { enabled: true, lockTimeoutMs: 5000 },\n * };\n * ```\n */\nexport const CacheAvalanchePreventionSchema = z.object({\n /** TTL jitter to stagger cache expiration */\n jitterTtl: z.object({\n enabled: z.boolean().default(false).describe('Add random jitter to TTL values'),\n maxJitterSeconds: z.number().default(60).describe('Maximum jitter added to TTL in seconds'),\n }).optional().describe('TTL jitter to prevent simultaneous expiration'),\n\n /** Circuit breaker to protect backend under cache pressure */\n circuitBreaker: z.object({\n enabled: z.boolean().default(false).describe('Enable circuit breaker for backend protection'),\n failureThreshold: z.number().default(5).describe('Failures before circuit opens'),\n resetTimeout: z.number().default(30).describe('Seconds before half-open state'),\n }).optional().describe('Circuit breaker for backend protection'),\n\n /** Cache lock to prevent thundering herd on key miss */\n lockout: z.object({\n enabled: z.boolean().default(false).describe('Enable cache locking for key regeneration'),\n lockTimeoutMs: z.number().default(5000).describe('Maximum lock wait time in milliseconds'),\n }).optional().describe('Lock-based stampede prevention'),\n}).describe('Cache avalanche/stampede prevention configuration');\n\nexport type CacheAvalanchePrevention = z.infer;\n\n/**\n * Cache Warmup Strategy Schema\n *\n * Defines how cache is pre-populated on startup or after cache flush.\n */\nexport const CacheWarmupSchema = z.object({\n /** Enable cache warming */\n enabled: z.boolean().default(false).describe('Enable cache warmup'),\n /** Warmup strategy */\n strategy: z.enum(['eager', 'lazy', 'scheduled']).default('lazy')\n .describe('Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)'),\n /** Cron schedule for scheduled warmup */\n schedule: z.string().optional().describe('Cron expression for scheduled warmup'),\n /** Keys/patterns to warm up */\n patterns: z.array(z.string()).optional().describe('Key patterns to warm up (e.g., \"user:*\", \"config:*\")'),\n /** Maximum concurrent warmup operations */\n concurrency: z.number().default(10).describe('Maximum concurrent warmup operations'),\n}).describe('Cache warmup strategy');\n\nexport type CacheWarmup = z.infer;\n\n/**\n * Distributed Cache Configuration Schema\n *\n * Extended cache configuration for distributed multi-node deployments.\n * Adds consistency strategies, avalanche prevention, and warmup policies.\n *\n * @example\n * ```typescript\n * const distributedCache: DistributedCacheConfig = {\n * enabled: true,\n * tiers: [\n * { name: 'l1', type: 'memory', maxSize: 100, ttl: 60, strategy: 'lru' },\n * { name: 'l2', type: 'redis', maxSize: 1000, ttl: 300, strategy: 'lru' },\n * ],\n * invalidation: [\n * { trigger: 'update', scope: 'key' },\n * ],\n * consistency: 'write_through',\n * avalanchePrevention: {\n * jitterTtl: { enabled: true, maxJitterSeconds: 30 },\n * circuitBreaker: { enabled: true, failureThreshold: 5 },\n * },\n * warmup: { enabled: true, strategy: 'eager', patterns: ['config:*'] },\n * };\n * ```\n */\nexport const DistributedCacheConfigSchema = CacheConfigSchema.extend({\n /** Distributed write consistency strategy */\n consistency: CacheConsistencySchema.optional().describe('Distributed cache consistency strategy'),\n /** Avalanche/stampede prevention settings */\n avalanchePrevention: CacheAvalanchePreventionSchema.optional()\n .describe('Cache avalanche and stampede prevention'),\n /** Cache warmup configuration */\n warmup: CacheWarmupSchema.optional().describe('Cache warmup strategy'),\n}).describe('Distributed cache configuration with consistency and avalanche prevention');\n\nexport type DistributedCacheConfig = z.infer;\nexport type DistributedCacheConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Backup Strategy Schema\n *\n * Defines backup methods for disaster recovery.\n *\n * - **full**: Complete snapshot of all data\n * - **incremental**: Only changes since last backup\n * - **differential**: All changes since last full backup\n *\n * @example\n * ```typescript\n * const backup: BackupConfig = {\n * strategy: 'incremental',\n * schedule: '0 2 * * *',\n * retention: { days: 30, minCopies: 3 },\n * encryption: { enabled: true, algorithm: 'AES-256-GCM' },\n * };\n * ```\n */\nexport const BackupStrategySchema = z.enum([\n 'full',\n 'incremental',\n 'differential',\n]).describe('Backup strategy type');\n\nexport type BackupStrategy = z.infer;\n\n/**\n * Backup Retention Policy Schema\n */\nexport const BackupRetentionSchema = z.object({\n /** Number of days to retain backups */\n days: z.number().min(1).describe('Retention period in days'),\n /** Minimum number of backup copies to keep regardless of age */\n minCopies: z.number().min(1).default(3).describe('Minimum backup copies to retain'),\n /** Maximum number of backup copies */\n maxCopies: z.number().optional().describe('Maximum backup copies to store'),\n}).describe('Backup retention policy');\n\nexport type BackupRetention = z.infer;\n\n/**\n * Backup Configuration Schema\n */\nexport const BackupConfigSchema = z.object({\n /** Backup strategy */\n strategy: BackupStrategySchema.default('incremental').describe('Backup strategy'),\n /** Cron schedule for automated backups */\n schedule: z.string().optional().describe('Cron expression for backup schedule (e.g., \"0 2 * * *\")'),\n /** Retention policy */\n retention: BackupRetentionSchema.describe('Backup retention policy'),\n /** Storage destination */\n destination: z.object({\n type: z.enum(['s3', 'gcs', 'azure_blob', 'local']).describe('Storage backend type'),\n bucket: z.string().optional().describe('Cloud storage bucket/container name'),\n path: z.string().optional().describe('Storage path prefix'),\n region: z.string().optional().describe('Cloud storage region'),\n }).describe('Backup storage destination'),\n /** Encryption settings */\n encryption: z.object({\n enabled: z.boolean().default(true).describe('Enable backup encryption'),\n algorithm: z.enum(['AES-256-GCM', 'AES-256-CBC', 'ChaCha20-Poly1305']).default('AES-256-GCM')\n .describe('Encryption algorithm'),\n keyId: z.string().optional().describe('KMS key ID for encryption'),\n }).optional().describe('Backup encryption settings'),\n /** Compression settings */\n compression: z.object({\n enabled: z.boolean().default(true).describe('Enable backup compression'),\n algorithm: z.enum(['gzip', 'zstd', 'lz4', 'snappy']).default('zstd').describe('Compression algorithm'),\n }).optional().describe('Backup compression settings'),\n /** Verify backup integrity after creation */\n verifyAfterBackup: z.boolean().default(true).describe('Verify backup integrity after creation'),\n}).describe('Backup configuration');\n\nexport type BackupConfig = z.infer;\nexport type BackupConfigInput = z.input;\n\n/**\n * Failover Mode Schema\n *\n * Defines how traffic is routed between primary and secondary systems.\n *\n * - **active_passive**: Secondary is standby, activated on primary failure\n * - **active_active**: Both primary and secondary handle traffic\n * - **pilot_light**: Minimal secondary with quick scale-up capability\n * - **warm_standby**: Reduced-capacity secondary, faster failover than pilot light\n */\nexport const FailoverModeSchema = z.enum([\n 'active_passive',\n 'active_active',\n 'pilot_light',\n 'warm_standby',\n]).describe('Failover mode');\n\nexport type FailoverMode = z.infer;\n\n/**\n * Failover Configuration Schema\n */\nexport const FailoverConfigSchema = z.object({\n /** Failover mode */\n mode: FailoverModeSchema.default('active_passive').describe('Failover mode'),\n /** Automatic failover enabled */\n autoFailover: z.boolean().default(true).describe('Enable automatic failover'),\n /** Health check interval in seconds */\n healthCheckInterval: z.number().default(30).describe('Health check interval in seconds'),\n /** Number of consecutive failures before triggering failover */\n failureThreshold: z.number().default(3).describe('Consecutive failures before failover'),\n /** Regions/zones for disaster recovery */\n regions: z.array(z.object({\n name: z.string().describe('Region identifier (e.g., \"us-east-1\", \"eu-west-1\")'),\n role: z.enum(['primary', 'secondary', 'witness']).describe('Region role'),\n endpoint: z.string().optional().describe('Region endpoint URL'),\n priority: z.number().optional().describe('Failover priority (lower = higher priority)'),\n })).min(2).describe('Multi-region configuration (minimum 2 regions)'),\n /** DNS failover configuration */\n dns: z.object({\n ttl: z.number().default(60).describe('DNS TTL in seconds for failover'),\n provider: z.enum(['route53', 'cloudflare', 'azure_dns', 'custom']).optional()\n .describe('DNS provider for automatic failover'),\n }).optional().describe('DNS failover settings'),\n}).describe('Failover configuration');\n\nexport type FailoverConfig = z.infer;\nexport type FailoverConfigInput = z.input;\n\n/**\n * Recovery Point Objective (RPO) Schema\n *\n * Maximum acceptable amount of data loss measured in time.\n */\nexport const RPOSchema = z.object({\n /** RPO value */\n value: z.number().min(0).describe('RPO value'),\n /** RPO time unit */\n unit: z.enum(['seconds', 'minutes', 'hours']).default('minutes').describe('RPO time unit'),\n}).describe('Recovery Point Objective (maximum acceptable data loss)');\n\nexport type RPO = z.infer;\n\n/**\n * Recovery Time Objective (RTO) Schema\n *\n * Maximum acceptable time to restore service after a disaster.\n */\nexport const RTOSchema = z.object({\n /** RTO value */\n value: z.number().min(0).describe('RTO value'),\n /** RTO time unit */\n unit: z.enum(['seconds', 'minutes', 'hours']).default('minutes').describe('RTO time unit'),\n}).describe('Recovery Time Objective (maximum acceptable downtime)');\n\nexport type RTO = z.infer;\n\n/**\n * Disaster Recovery Plan Schema\n *\n * Complete disaster recovery configuration for an ObjectStack deployment.\n * Covers backup, failover, replication, and recovery objectives.\n *\n * Aligned with industry standards:\n * - ISO 22301 (Business Continuity Management)\n * - AWS Well-Architected Framework (Reliability Pillar)\n *\n * @example\n * ```typescript\n * const drPlan: DisasterRecoveryPlan = {\n * enabled: true,\n * rpo: { value: 15, unit: 'minutes' },\n * rto: { value: 1, unit: 'hours' },\n * backup: {\n * strategy: 'incremental',\n * schedule: '0 0/6 * * *',\n * retention: { days: 90, minCopies: 5 },\n * destination: { type: 's3', bucket: 'backup-bucket', region: 'us-east-1' },\n * },\n * failover: {\n * mode: 'active_passive',\n * autoFailover: true,\n * healthCheckInterval: 30,\n * failureThreshold: 3,\n * regions: [\n * { name: 'us-east-1', role: 'primary' },\n * { name: 'us-west-2', role: 'secondary' },\n * ],\n * },\n * };\n * ```\n */\nexport const DisasterRecoveryPlanSchema = z.object({\n /** Enable disaster recovery */\n enabled: z.boolean().default(false).describe('Enable disaster recovery plan'),\n\n /** Recovery Point Objective */\n rpo: RPOSchema.describe('Recovery Point Objective'),\n\n /** Recovery Time Objective */\n rto: RTOSchema.describe('Recovery Time Objective'),\n\n /** Backup configuration */\n backup: BackupConfigSchema.describe('Backup configuration'),\n\n /** Failover configuration */\n failover: FailoverConfigSchema.optional().describe('Multi-region failover configuration'),\n\n /** Data replication settings */\n replication: z.object({\n /** Replication mode */\n mode: z.enum(['synchronous', 'asynchronous', 'semi_synchronous']).default('asynchronous')\n .describe('Data replication mode'),\n /** Maximum replication lag allowed (seconds) */\n maxLagSeconds: z.number().optional().describe('Maximum acceptable replication lag in seconds'),\n /** Objects/tables to replicate (empty = all) */\n includeObjects: z.array(z.string()).optional().describe('Objects to replicate (empty = all)'),\n /** Objects/tables to exclude from replication */\n excludeObjects: z.array(z.string()).optional().describe('Objects to exclude from replication'),\n }).optional().describe('Data replication settings'),\n\n /** Automated recovery testing */\n testing: z.object({\n /** Enable periodic DR testing */\n enabled: z.boolean().default(false).describe('Enable automated DR testing'),\n /** Cron schedule for DR tests */\n schedule: z.string().optional().describe('Cron expression for DR test schedule'),\n /** Notification channel for test results */\n notificationChannel: z.string().optional().describe('Notification channel for DR test results'),\n }).optional().describe('Automated disaster recovery testing'),\n\n /** Runbook URL for manual procedures */\n runbookUrl: z.string().optional().describe('URL to disaster recovery runbook/playbook'),\n\n /** Contact list for DR incidents */\n contacts: z.array(z.object({\n name: z.string().describe('Contact name'),\n role: z.string().describe('Contact role (e.g., \"DBA\", \"SRE Lead\")'),\n email: z.string().optional().describe('Contact email'),\n phone: z.string().optional().describe('Contact phone'),\n })).optional().describe('Emergency contact list for DR incidents'),\n}).describe('Complete disaster recovery plan configuration');\n\nexport type DisasterRecoveryPlan = z.infer;\nexport type DisasterRecoveryPlanInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Message queue protocol for async communication\n * Supports Kafka, RabbitMQ, AWS SQS, Redis Pub/Sub\n */\nexport const MessageQueueProviderSchema = z.enum([\n 'kafka',\n 'rabbitmq',\n 'aws-sqs',\n 'redis-pubsub',\n 'google-pubsub',\n 'azure-service-bus',\n]).describe('Supported message queue backend provider');\n\nexport type MessageQueueProvider = z.infer;\n\nexport const TopicConfigSchema = z.object({\n name: z.string().describe('Topic name identifier'),\n partitions: z.number().default(1).describe('Number of partitions for parallel consumption'),\n replicationFactor: z.number().default(1).describe('Number of replicas for fault tolerance'),\n retentionMs: z.number().optional().describe('Message retention period in milliseconds'),\n compressionType: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression algorithm'),\n}).describe('Configuration for a message queue topic');\n\nexport type TopicConfig = z.infer;\n\nexport const ConsumerConfigSchema = z.object({\n groupId: z.string().describe('Consumer group identifier'),\n autoOffsetReset: z.enum(['earliest', 'latest']).default('latest').describe('Where to start reading when no offset exists'),\n enableAutoCommit: z.boolean().default(true).describe('Automatically commit consumed offsets'),\n maxPollRecords: z.number().default(500).describe('Maximum records returned per poll'),\n}).describe('Consumer group configuration for topic consumption');\n\nexport type ConsumerConfig = z.infer;\n\nexport const DeadLetterQueueSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable dead letter queue for failed messages'),\n maxRetries: z.number().default(3).describe('Maximum delivery attempts before sending to DLQ'),\n queueName: z.string().describe('Name of the dead letter queue'),\n}).describe('Dead letter queue configuration for unprocessable messages');\n\nexport type DeadLetterQueue = z.infer;\n\nexport const MessageQueueConfigSchema = z.object({\n provider: MessageQueueProviderSchema.describe('Message queue backend provider'),\n topics: z.array(TopicConfigSchema).describe('List of topic configurations'),\n consumers: z.array(ConsumerConfigSchema).optional().describe('Consumer group configurations'),\n deadLetterQueue: DeadLetterQueueSchema.optional().describe('Dead letter queue for failed messages'),\n ssl: z.boolean().default(false).describe('Enable SSL/TLS for broker connections'),\n sasl: z.object({\n mechanism: z.enum(['plain', 'scram-sha-256', 'scram-sha-512']).describe('SASL authentication mechanism'),\n username: z.string().describe('SASL username'),\n password: z.string().describe('SASL password'),\n }).optional().describe('SASL authentication configuration'),\n}).describe('Top-level message queue configuration');\n\nexport type MessageQueueConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Object Storage Protocol\n * \n * Unified storage protocol that combines:\n * - Object storage systems (S3, Azure Blob, GCS, MinIO)\n * - Scoped storage configuration (temp, cache, data, logs, config, public)\n * - Multi-cloud storage providers\n * - Bucket/container configuration\n * - Access control and permissions\n * - Lifecycle policies for data retention\n * - Presigned URLs for secure direct access\n * - Multipart uploads for large files\n */\n\n// ============================================================================\n// Storage Scope Protocol (formerly from scoped-storage.zod.ts)\n// ============================================================================\n\n/**\n * Storage Scope Enum\n * Defines the lifecycle and persistence guarantee of the storage area.\n */\nexport const StorageScopeSchema = z.enum([\n 'global', // Global application-wide storage\n 'tenant', // Tenant-scoped storage (multi-tenant apps)\n 'user', // User-scoped storage\n 'session', // Session-scoped storage (ephemeral)\n 'temp', // Ephemeral, cleared on restart\n 'cache', // Ephemeral, survives restarts, cleared on LRU/Expiration\n 'data', // Persistent, backed up\n 'logs', // Append-only, rotated\n 'config', // Read-heavy, versioned\n 'public' // Publicly accessible static assets\n]).describe('Storage scope classification');\n\nexport type StorageScope = z.infer;\n\n/**\n * File Metadata Schema\n * Standardized file attribute structure\n */\nexport const FileMetadataSchema = z.object({\n path: z.string().describe('File path'),\n name: z.string().describe('File name'),\n size: z.number().int().describe('File size in bytes'),\n mimeType: z.string().describe('MIME type'),\n lastModified: z.string().datetime().describe('Last modified timestamp'),\n created: z.string().datetime().describe('Creation timestamp'),\n etag: z.string().optional().describe('Entity tag'),\n});\n\nexport type FileMetadata = z.infer;\n\n// ============================================================================\n// Enums\n// ============================================================================\n\n/**\n * Storage Provider Types\n * \n * Supported cloud and self-hosted object storage providers.\n */\nexport const StorageProviderSchema = z.enum([\n 's3', // Amazon S3\n 'azure_blob', // Azure Blob Storage\n 'gcs', // Google Cloud Storage\n 'minio', // MinIO (self-hosted S3-compatible)\n 'r2', // Cloudflare R2\n 'spaces', // DigitalOcean Spaces\n 'wasabi', // Wasabi Hot Cloud Storage\n 'backblaze', // Backblaze B2\n 'local', // Local filesystem (development only)\n]).describe('Storage provider type');\n\nexport type StorageProvider = z.infer;\n\n/**\n * Storage Access Control List (ACL)\n * \n * Predefined access control configurations for objects and buckets.\n */\nexport const StorageAclSchema = z.enum([\n 'private', // Owner has full control, no one else has access\n 'public_read', // Owner has full control, everyone can read\n 'public_read_write', // Owner has full control, everyone can read/write (not recommended)\n 'authenticated_read', // Owner has full control, authenticated users can read\n 'bucket_owner_read', // Object owner has full control, bucket owner can read\n 'bucket_owner_full_control', // Both object and bucket owner have full control\n]).describe('Storage access control level');\n\nexport type StorageAcl = z.infer;\n\n/**\n * Storage Class / Tier\n * \n * Different storage tiers for cost optimization.\n * Maps to provider-specific storage classes.\n */\nexport const StorageClassSchema = z.enum([\n 'standard', // Standard/hot storage for frequently accessed data\n 'intelligent', // Intelligent tiering (auto-moves between hot/cool)\n 'infrequent_access', // Infrequent access/cool storage\n 'glacier', // Archive/cold storage (slower retrieval)\n 'deep_archive', // Deep archive (cheapest, slowest retrieval)\n]).describe('Storage class/tier for cost optimization');\n\nexport type StorageClass = z.infer;\n\n/**\n * Lifecycle Transition Action\n */\nexport const LifecycleActionSchema = z.enum([\n 'transition', // Move to different storage class\n 'delete', // Delete the object\n 'abort', // Abort incomplete multipart uploads\n]).describe('Lifecycle policy action type');\n\nexport type LifecycleAction = z.infer;\n\n// ============================================================================\n// Configuration Schemas\n// ============================================================================\n\n/**\n * Object Metadata Schema\n * \n * Standard and custom metadata attached to stored objects.\n * \n * @example\n * {\n * contentType: 'image/jpeg',\n * contentLength: 1024000,\n * etag: '\"abc123\"',\n * lastModified: new Date('2024-01-01'),\n * custom: {\n * uploadedBy: 'user123',\n * department: 'marketing'\n * }\n * }\n */\nexport const ObjectMetadataSchema = z.object({\n contentType: z.string().describe('MIME type (e.g., image/jpeg, application/pdf)'),\n contentLength: z.number().min(0).describe('File size in bytes'),\n contentEncoding: z.string().optional().describe('Content encoding (e.g., gzip)'),\n contentDisposition: z.string().optional().describe('Content disposition header'),\n contentLanguage: z.string().optional().describe('Content language'),\n cacheControl: z.string().optional().describe('Cache control directives'),\n etag: z.string().optional().describe('Entity tag for versioning/caching'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n versionId: z.string().optional().describe('Object version identifier'),\n storageClass: StorageClassSchema.optional().describe('Storage class/tier'),\n encryption: z.object({\n algorithm: z.string().describe('Encryption algorithm (e.g., AES256, aws:kms)'),\n keyId: z.string().optional().describe('KMS key ID if using managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n custom: z.record(z.string(), z.string()).optional().describe('Custom user-defined metadata'),\n});\n\nexport type ObjectMetadata = z.infer;\n\n/**\n * Presigned URL Configuration\n * \n * Configuration for generating temporary URLs for direct access to objects.\n * Useful for secure file uploads/downloads without exposing credentials.\n * \n * @example\n * // Generate download URL valid for 1 hour\n * {\n * operation: 'get',\n * expiresIn: 3600,\n * contentType: 'image/jpeg'\n * }\n * \n * @example\n * // Generate upload URL valid for 15 minutes with size limit\n * {\n * operation: 'put',\n * expiresIn: 900,\n * contentType: 'application/pdf',\n * maxSize: 10485760\n * }\n */\nexport const PresignedUrlConfigSchema = z.object({\n operation: z.enum(['get', 'put', 'delete', 'head']).describe('Allowed operation'),\n expiresIn: z.number().min(1).max(604800).describe('Expiration time in seconds (max 7 days)'),\n contentType: z.string().optional().describe('Required content type for PUT operations'),\n maxSize: z.number().min(0).optional().describe('Maximum file size in bytes for PUT operations'),\n responseContentType: z.string().optional().describe('Override content-type for GET operations'),\n responseContentDisposition: z.string().optional().describe('Override content-disposition for GET operations'),\n});\n\nexport type PresignedUrlConfig = z.infer;\n\n/**\n * Multipart Upload Configuration\n * \n * Configuration for chunked uploads of large files.\n * Enables resumable uploads and parallel transfer.\n * \n * @example\n * // Enable multipart for files > 100MB with 10MB chunks\n * {\n * enabled: true,\n * partSize: 10485760,\n * maxParts: 10000,\n * threshold: 104857600,\n * maxConcurrent: 4\n * }\n */\nexport const MultipartUploadConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable multipart uploads'),\n partSize: z.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe('Part size in bytes (min 5MB, max 5GB)'),\n maxParts: z.number().min(1).max(10000).default(10000).describe('Maximum number of parts (max 10,000)'),\n threshold: z.number().min(0).default(100 * 1024 * 1024).describe('File size threshold to trigger multipart upload (bytes)'),\n maxConcurrent: z.number().min(1).max(100).default(4).describe('Maximum concurrent part uploads'),\n abortIncompleteAfterDays: z.number().min(1).optional().describe('Auto-abort incomplete uploads after N days'),\n});\n\nexport type MultipartUploadConfig = z.infer;\n\n/**\n * Access Control Configuration\n * \n * Fine-grained access control for buckets and objects.\n * \n * @example\n * {\n * acl: 'private',\n * allowedOrigins: ['https://app.example.com'],\n * allowedMethods: ['GET', 'PUT'],\n * corsEnabled: true,\n * publicAccess: {\n * allowPublicRead: false,\n * allowPublicWrite: false\n * }\n * }\n */\nexport const AccessControlConfigSchema = z.object({\n acl: StorageAclSchema.default('private').describe('Default access control level'),\n allowedOrigins: z.array(z.string()).optional().describe('CORS allowed origins'),\n allowedMethods: z.array(z.enum(['GET', 'PUT', 'POST', 'DELETE', 'HEAD'])).optional().describe('CORS allowed HTTP methods'),\n allowedHeaders: z.array(z.string()).optional().describe('CORS allowed headers'),\n exposeHeaders: z.array(z.string()).optional().describe('CORS exposed headers'),\n maxAge: z.number().min(0).optional().describe('CORS preflight cache duration in seconds'),\n corsEnabled: z.boolean().default(false).describe('Enable CORS configuration'),\n publicAccess: z.object({\n allowPublicRead: z.boolean().default(false).describe('Allow public read access'),\n allowPublicWrite: z.boolean().default(false).describe('Allow public write access'),\n allowPublicList: z.boolean().default(false).describe('Allow public bucket listing'),\n }).optional().describe('Public access control'),\n allowedIps: z.array(z.string()).optional().describe('Allowed IP addresses/CIDR blocks'),\n blockedIps: z.array(z.string()).optional().describe('Blocked IP addresses/CIDR blocks'),\n});\n\nexport type AccessControlConfig = z.infer;\n\n/**\n * Lifecycle Policy Rule\n * \n * Individual rule for automatic object lifecycle management.\n * \n * @example\n * // Transition to infrequent access after 30 days\n * {\n * id: 'move_to_ia',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 30,\n * targetStorageClass: 'infrequent_access'\n * }\n * \n * @example\n * // Delete objects after 365 days\n * {\n * id: 'delete_old',\n * enabled: true,\n * action: 'delete',\n * daysAfterCreation: 365\n * }\n */\nexport const LifecyclePolicyRuleSchema = z.object({\n id: SystemIdentifierSchema.describe('Rule identifier'),\n enabled: z.boolean().default(true).describe('Enable this rule'),\n action: LifecycleActionSchema.describe('Action to perform'),\n prefix: z.string().optional().describe('Object key prefix filter (e.g., \"uploads/\")'),\n tags: z.record(z.string(), z.string()).optional().describe('Object tag filters'),\n daysAfterCreation: z.number().min(0).optional().describe('Days after object creation'),\n daysAfterModification: z.number().min(0).optional().describe('Days after last modification'),\n targetStorageClass: StorageClassSchema.optional().describe('Target storage class for transition action'),\n}).refine((data) => {\n // Validate that transition action has targetStorageClass\n if (data.action === 'transition' && !data.targetStorageClass) {\n return false;\n }\n return true;\n}, {\n message: 'targetStorageClass is required when action is \"transition\"',\n});\n\nexport type LifecyclePolicyRule = z.infer;\n\n/**\n * Lifecycle Policy Configuration\n * \n * Collection of lifecycle rules for automatic data management.\n * \n * @example\n * {\n * enabled: true,\n * rules: [\n * {\n * id: 'archive_old_files',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 90,\n * targetStorageClass: 'glacier'\n * },\n * {\n * id: 'delete_temp_files',\n * enabled: true,\n * action: 'delete',\n * prefix: 'temp/',\n * daysAfterCreation: 7\n * }\n * ]\n * }\n */\nexport const LifecyclePolicyConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable lifecycle policies'),\n rules: z.array(LifecyclePolicyRuleSchema).default([]).describe('Lifecycle rules'),\n});\n\nexport type LifecyclePolicyConfig = z.infer;\n\n/**\n * Bucket Configuration Schema\n * \n * Comprehensive configuration for a storage bucket/container.\n * \n * @example\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'my-app-uploads',\n * region: 'us-east-1',\n * provider: 's3',\n * versioning: true,\n * accessControl: {\n * acl: 'private',\n * corsEnabled: true,\n * allowedOrigins: ['https://app.example.com']\n * },\n * multipartConfig: {\n * enabled: true,\n * threshold: 104857600\n * }\n * }\n */\nexport const BucketConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Bucket identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n bucketName: z.string().describe('Actual bucket/container name in storage provider'),\n region: z.string().optional().describe('Storage region (e.g., us-east-1, westus)'),\n provider: StorageProviderSchema.describe('Storage provider'),\n endpoint: z.string().optional().describe('Custom endpoint URL (for S3-compatible providers)'),\n pathStyle: z.boolean().default(false).describe('Use path-style URLs (for S3-compatible providers)'),\n \n versioning: z.boolean().default(false).describe('Enable object versioning'),\n encryption: z.object({\n enabled: z.boolean().default(false).describe('Enable server-side encryption'),\n algorithm: z.enum(['AES256', 'aws:kms', 'azure:kms', 'gcp:kms']).default('AES256').describe('Encryption algorithm'),\n kmsKeyId: z.string().optional().describe('KMS key ID for managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n \n accessControl: AccessControlConfigSchema.optional().describe('Access control configuration'),\n lifecyclePolicy: LifecyclePolicyConfigSchema.optional().describe('Lifecycle policy configuration'),\n multipartConfig: MultipartUploadConfigSchema.optional().describe('Multipart upload configuration'),\n \n tags: z.record(z.string(), z.string()).optional().describe('Bucket tags for organization'),\n description: z.string().optional().describe('Bucket description'),\n enabled: z.boolean().default(true).describe('Enable this bucket'),\n});\n\nexport type BucketConfig = z.infer;\n\n/**\n * Storage Connection Configuration\n * \n * Provider-specific connection credentials and settings.\n * \n * @example S3\n * {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * sessionToken: '${AWS_SESSION_TOKEN}',\n * region: 'us-east-1'\n * }\n * \n * @example Azure\n * {\n * accountName: 'mystorageaccount',\n * accountKey: '${AZURE_STORAGE_KEY}',\n * endpoint: 'https://mystorageaccount.blob.core.windows.net'\n * }\n */\nexport const StorageConnectionSchema = z.object({\n // AWS S3 / MinIO\n accessKeyId: z.string().optional().describe('AWS access key ID or MinIO access key'),\n secretAccessKey: z.string().optional().describe('AWS secret access key or MinIO secret key'),\n sessionToken: z.string().optional().describe('AWS session token for temporary credentials'),\n \n // Azure Blob Storage\n accountName: z.string().optional().describe('Azure storage account name'),\n accountKey: z.string().optional().describe('Azure storage account key'),\n sasToken: z.string().optional().describe('Azure SAS token'),\n \n // Google Cloud Storage\n projectId: z.string().optional().describe('GCP project ID'),\n credentials: z.string().optional().describe('GCP service account credentials JSON'),\n \n // Common\n endpoint: z.string().optional().describe('Custom endpoint URL'),\n region: z.string().optional().describe('Default region'),\n useSSL: z.boolean().default(true).describe('Use SSL/TLS for connections'),\n timeout: z.number().min(0).optional().describe('Connection timeout in milliseconds'),\n});\n\nexport type StorageConnection = z.infer;\n\n/**\n * Object Storage Configuration\n * \n * Complete object storage system configuration.\n * \n * @example\n * {\n * name: 'production_storage',\n * label: 'Production File Storage',\n * provider: 's3',\n * scope: 'global',\n * connection: {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * region: 'us-east-1'\n * },\n * buckets: [\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'prod-uploads',\n * provider: 's3',\n * region: 'us-east-1'\n * }\n * ],\n * defaultBucket: 'user_uploads'\n * }\n */\nexport const ObjectStorageConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Storage configuration identifier'),\n label: z.string().describe('Display label'),\n provider: StorageProviderSchema.describe('Primary storage provider'),\n \n /**\n * Storage scope\n * Defines the lifecycle and access pattern for this storage\n */\n scope: StorageScopeSchema.optional().default('global').describe('Storage scope'),\n \n connection: StorageConnectionSchema.describe('Connection credentials'),\n buckets: z.array(BucketConfigSchema).default([]).describe('Configured buckets'),\n defaultBucket: z.string().optional().describe('Default bucket name for operations'),\n \n /**\n * Base path or location\n * For local/scoped storage configurations\n */\n location: z.string().optional().describe('Root path (local) or base location'),\n \n /**\n * Storage quota in bytes\n */\n quota: z.number().int().positive().optional().describe('Max size in bytes'),\n \n /**\n * Provider-specific options\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Provider-specific configuration options'),\n \n enabled: z.boolean().default(true).describe('Enable this storage configuration'),\n description: z.string().optional().describe('Configuration description'),\n});\n\nexport type ObjectStorageConfig = z.infer;\n\n// ============================================================================\n// Helper Examples\n// ============================================================================\n\n/**\n * Example: AWS S3 Configuration\n */\nexport const s3StorageExample = ObjectStorageConfigSchema.parse({\n name: 'aws_s3_storage',\n label: 'AWS S3 Production Storage',\n provider: 's3',\n connection: {\n accessKeyId: '${AWS_ACCESS_KEY_ID}',\n secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n region: 'us-east-1',\n },\n buckets: [\n {\n name: 'user_uploads',\n label: 'User Uploads',\n bucketName: 'my-app-user-uploads',\n region: 'us-east-1',\n provider: 's3',\n versioning: true,\n encryption: {\n enabled: true,\n algorithm: 'aws:kms',\n kmsKeyId: '${AWS_KMS_KEY_ID}',\n },\n accessControl: {\n acl: 'private',\n corsEnabled: true,\n allowedOrigins: ['https://app.example.com'],\n allowedMethods: ['GET', 'PUT', 'POST'],\n },\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'archive_old_uploads',\n enabled: true,\n action: 'transition',\n daysAfterCreation: 90,\n targetStorageClass: 'glacier',\n },\n ],\n },\n multipartConfig: {\n enabled: true,\n partSize: 10 * 1024 * 1024,\n threshold: 100 * 1024 * 1024,\n maxConcurrent: 4,\n },\n },\n ],\n defaultBucket: 'user_uploads',\n enabled: true,\n});\n\n/**\n * Example: MinIO Configuration\n */\nexport const minioStorageExample = ObjectStorageConfigSchema.parse({\n name: 'minio_local',\n label: 'MinIO Local Storage',\n provider: 'minio',\n connection: {\n accessKeyId: 'minioadmin',\n secretAccessKey: 'minioadmin',\n endpoint: 'http://localhost:9000',\n useSSL: false,\n },\n buckets: [\n {\n name: 'development_files',\n label: 'Development Files',\n bucketName: 'dev-files',\n provider: 'minio',\n endpoint: 'http://localhost:9000',\n pathStyle: true,\n accessControl: {\n acl: 'private',\n },\n },\n ],\n defaultBucket: 'development_files',\n enabled: true,\n});\n\n/**\n * Example: Azure Blob Storage Configuration\n */\nexport const azureBlobStorageExample = ObjectStorageConfigSchema.parse({\n name: 'azure_blob_storage',\n label: 'Azure Blob Storage',\n provider: 'azure_blob',\n connection: {\n accountName: 'mystorageaccount',\n accountKey: '${AZURE_STORAGE_KEY}',\n endpoint: 'https://mystorageaccount.blob.core.windows.net',\n },\n buckets: [\n {\n name: 'media_files',\n label: 'Media Files',\n bucketName: 'media',\n provider: 'azure_blob',\n region: 'eastus',\n accessControl: {\n acl: 'public_read',\n publicAccess: {\n allowPublicRead: true,\n allowPublicWrite: false,\n allowPublicList: false,\n },\n },\n },\n ],\n defaultBucket: 'media_files',\n enabled: true,\n});\n\n/**\n * Example: Google Cloud Storage Configuration\n */\nexport const gcsStorageExample = ObjectStorageConfigSchema.parse({\n name: 'gcs_storage',\n label: 'Google Cloud Storage',\n provider: 'gcs',\n connection: {\n projectId: 'my-gcp-project',\n credentials: '${GCP_SERVICE_ACCOUNT_JSON}',\n },\n buckets: [\n {\n name: 'backup_storage',\n label: 'Backup Storage',\n bucketName: 'my-app-backups',\n region: 'us-central1',\n provider: 'gcs',\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'delete_old_backups',\n enabled: true,\n action: 'delete',\n daysAfterCreation: 30,\n },\n ],\n },\n },\n ],\n defaultBucket: 'backup_storage',\n enabled: true,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Full-text search protocol\n * Supports Elasticsearch, Algolia, Meilisearch, Typesense\n */\nexport const SearchProviderSchema = z.enum([\n 'elasticsearch',\n 'algolia',\n 'meilisearch',\n 'typesense',\n 'opensearch',\n]).describe('Supported full-text search engine provider');\n\nexport type SearchProvider = z.infer;\n\nexport const AnalyzerConfigSchema = z.object({\n type: z.enum(['standard', 'simple', 'whitespace', 'keyword', 'pattern', 'language']).describe('Text analyzer type'),\n language: z.string().optional().describe('Language for language-specific analysis'),\n stopwords: z.array(z.string()).optional().describe('Custom stopwords to filter during analysis'),\n customFilters: z.array(z.string()).optional().describe('Additional token filter names to apply'),\n}).describe('Text analyzer configuration for index tokenization and normalization');\n\nexport type AnalyzerConfig = z.infer;\n\nexport const SearchIndexConfigSchema = z.object({\n indexName: z.string().describe('Name of the search index'),\n objectName: z.string().describe('Source ObjectQL object'),\n fields: z.array(z.object({\n name: z.string().describe('Field name to index'),\n type: z.enum(['text', 'keyword', 'number', 'date', 'boolean', 'geo']).describe('Index field data type'),\n analyzer: z.string().optional().describe('Named analyzer to use for this field'),\n searchable: z.boolean().default(true).describe('Include field in full-text search'),\n filterable: z.boolean().default(false).describe('Allow filtering on this field'),\n sortable: z.boolean().default(false).describe('Allow sorting by this field'),\n boost: z.number().default(1).describe('Relevance boost factor for this field'),\n })).describe('Fields to include in the search index'),\n replicas: z.number().default(1).describe('Number of index replicas for availability'),\n shards: z.number().default(1).describe('Number of index shards for distribution'),\n}).describe('Search index definition mapping an ObjectQL object to a search engine index');\n\nexport type SearchIndexConfig = z.infer;\n\nexport const FacetConfigSchema = z.object({\n field: z.string().describe('Field name to generate facets from'),\n maxValues: z.number().default(10).describe('Maximum number of facet values to return'),\n sort: z.enum(['count', 'alpha']).default('count').describe('Facet value sort order'),\n}).describe('Faceted search configuration for a single field');\n\nexport type FacetConfig = z.infer;\n\nexport const SearchConfigSchema = z.object({\n provider: SearchProviderSchema.describe('Search engine backend provider'),\n indexes: z.array(SearchIndexConfigSchema).describe('Search index definitions'),\n analyzers: z.record(z.string(), AnalyzerConfigSchema).optional().describe('Named text analyzer configurations'),\n facets: z.array(FacetConfigSchema).optional().describe('Faceted search configurations'),\n typoTolerance: z.boolean().default(true).describe('Enable typo-tolerant search'),\n synonyms: z.record(z.string(), z.array(z.string())).optional().describe('Synonym mappings for search expansion'),\n ranking: z.array(z.enum(['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom'])).optional().describe('Custom ranking rule order'),\n}).describe('Top-level full-text search engine configuration');\n\nexport type SearchConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, CorsConfigSchema, RateLimitConfigSchema, StaticMountSchema } from '../shared/http.zod';\n\n/**\n * HTTP Server Protocol\n * \n * Defines the runtime HTTP server configuration and capabilities.\n * Provides abstractions for HTTP server implementations (Express, Fastify, Hono, etc.)\n * \n * Architecture alignment:\n * - Kubernetes: Service and Ingress resources\n * - AWS: API Gateway configuration\n * - Spring Boot: Application properties\n */\n\n// ==========================================\n// Server Configuration\n// ==========================================\n\n/**\n * HTTP Server Configuration Schema\n * Core configuration for HTTP server instances\n * \n * @example\n * {\n * \"port\": 3000,\n * \"host\": \"0.0.0.0\",\n * \"cors\": {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\"]\n * },\n * \"compression\": true,\n * \"requestTimeout\": 30000\n * }\n */\nexport const HttpServerConfigSchema = z.object({\n /**\n * Server port number\n */\n port: z.number().int().min(1).max(65535).default(3000).describe('Port number to listen on'),\n \n /**\n * Server host address\n */\n host: z.string().default('0.0.0.0').describe('Host address to bind to'),\n \n /**\n * CORS configuration\n */\n cors: CorsConfigSchema.optional().describe('CORS configuration'),\n \n /**\n * Request handling options\n */\n requestTimeout: z.number().int().default(30000).describe('Request timeout in milliseconds'),\n bodyLimit: z.string().default('10mb').describe('Maximum request body size'),\n \n /**\n * Compression settings\n */\n compression: z.boolean().default(true).describe('Enable response compression'),\n \n /**\n * Security headers\n */\n security: z.object({\n helmet: z.boolean().default(true).describe('Enable security headers via helmet'),\n rateLimit: RateLimitConfigSchema.optional().describe('Global rate limiting configuration'),\n }).optional().describe('Security configuration'),\n \n /**\n * Static file serving\n */\n static: z.array(StaticMountSchema).optional().describe('Static file serving configuration'),\n \n /**\n * Trust proxy settings\n */\n trustProxy: z.boolean().default(false).describe('Trust X-Forwarded-* headers'),\n});\n\nexport type HttpServerConfig = z.infer;\nexport type HttpServerConfigInput = z.input;\n\n// ==========================================\n// Route Registration\n// ==========================================\n\n/**\n * Route Handler Metadata Schema\n * Metadata for route handlers used in registration\n */\nexport const RouteHandlerMetadataSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (supports parameters like /api/users/:id)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Handler function name or identifier\n */\n handler: z.string().describe('Handler identifier or name'),\n \n /**\n * Route metadata\n */\n metadata: z.object({\n summary: z.string().optional().describe('Route summary for documentation'),\n description: z.string().optional().describe('Route description'),\n tags: z.array(z.string()).optional().describe('Tags for grouping'),\n operationId: z.string().optional().describe('Unique operation identifier'),\n }).optional(),\n \n /**\n * Security requirements\n */\n security: z.object({\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n rateLimit: z.string().optional().describe('Rate limit policy override'),\n }).optional(),\n});\n\nexport type RouteHandlerMetadata = z.infer;\nexport type RouteHandlerMetadataInput = z.input;\n\n// ==========================================\n// Middleware Configuration\n// ==========================================\n\n/**\n * Middleware Type Enum\n */\nexport const MiddlewareType = z.enum([\n 'authentication', // Authentication middleware\n 'authorization', // Authorization/permission checks\n 'logging', // Request/response logging\n 'validation', // Input validation\n 'transformation', // Request/response transformation\n 'error', // Error handling\n 'custom', // Custom middleware\n]);\n\nexport type MiddlewareType = z.infer;\n\n/**\n * Middleware Configuration Schema\n * Defines middleware execution order and configuration\n * \n * @example\n * {\n * \"name\": \"auth_middleware\",\n * \"type\": \"authentication\",\n * \"enabled\": true,\n * \"order\": 10,\n * \"config\": {\n * \"jwtSecret\": \"secret\",\n * \"excludePaths\": [\"/health\", \"/metrics\"]\n * }\n * }\n */\nexport const MiddlewareConfigSchema = z.object({\n /**\n * Middleware identifier\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Middleware name (snake_case)'),\n \n /**\n * Middleware type\n */\n type: MiddlewareType.describe('Middleware type'),\n \n /**\n * Enable/disable middleware\n */\n enabled: z.boolean().default(true).describe('Whether middleware is enabled'),\n \n /**\n * Execution order (lower numbers execute first)\n */\n order: z.number().int().default(100).describe('Execution order priority'),\n \n /**\n * Middleware-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Middleware configuration object'),\n \n /**\n * Path patterns to apply middleware to\n */\n paths: z.object({\n include: z.array(z.string()).optional().describe('Include path patterns (glob)'),\n exclude: z.array(z.string()).optional().describe('Exclude path patterns (glob)'),\n }).optional().describe('Path filtering'),\n});\n\nexport type MiddlewareConfig = z.infer;\nexport type MiddlewareConfigInput = z.input;\n\n// ==========================================\n// Server Lifecycle Events\n// ==========================================\n\n/**\n * Server Event Type Enum\n */\nexport const ServerEventType = z.enum([\n 'starting', // Server is starting\n 'started', // Server has started and is listening\n 'stopping', // Server is stopping\n 'stopped', // Server has stopped\n 'request', // Request received\n 'response', // Response sent\n 'error', // Error occurred\n]);\n\nexport type ServerEventType = z.infer;\n\n/**\n * Server Event Schema\n * Events emitted by the HTTP server during lifecycle\n */\nexport const ServerEventSchema = z.object({\n /**\n * Event type\n */\n type: ServerEventType.describe('Event type'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp (ISO 8601)'),\n \n /**\n * Event payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Event-specific data'),\n});\n\nexport type ServerEvent = z.infer;\n\n// ==========================================\n// Server Capability Declaration\n// ==========================================\n\n/**\n * Server Capabilities Schema\n * Declares what features a server implementation supports\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Supported HTTP versions\n */\n httpVersions: z.array(z.enum(['1.0', '1.1', '2.0', '3.0'])).default(['1.1']).describe('Supported HTTP versions'),\n \n /**\n * WebSocket support\n */\n websocket: z.boolean().default(false).describe('WebSocket support'),\n \n /**\n * Server-Sent Events support\n */\n sse: z.boolean().default(false).describe('Server-Sent Events support'),\n \n /**\n * HTTP/2 Server Push\n */\n serverPush: z.boolean().default(false).describe('HTTP/2 Server Push support'),\n \n /**\n * Streaming support\n */\n streaming: z.boolean().default(true).describe('Response streaming support'),\n \n /**\n * Middleware support\n */\n middleware: z.boolean().default(true).describe('Middleware chain support'),\n \n /**\n * Route parameterization\n */\n routeParams: z.boolean().default(true).describe('URL parameter support (/users/:id)'),\n \n /**\n * Built-in compression\n */\n compression: z.boolean().default(true).describe('Built-in compression support'),\n});\n\nexport type ServerCapabilities = z.infer;\nexport type ServerCapabilitiesInput = z.input;\n\n// ==========================================\n// Server Status & Metrics\n// ==========================================\n\n/**\n * Server Status Schema\n * Current operational status of the server\n */\nexport const ServerStatusSchema = z.object({\n /**\n * Server state\n */\n state: z.enum(['stopped', 'starting', 'running', 'stopping', 'error']).describe('Current server state'),\n \n /**\n * Uptime in milliseconds\n */\n uptime: z.number().int().optional().describe('Server uptime in milliseconds'),\n \n /**\n * Server information\n */\n server: z.object({\n port: z.number().int().describe('Listening port'),\n host: z.string().describe('Bound host'),\n url: z.string().optional().describe('Full server URL'),\n }).optional(),\n \n /**\n * Connection metrics\n */\n connections: z.object({\n active: z.number().int().describe('Active connections'),\n total: z.number().int().describe('Total connections handled'),\n }).optional(),\n \n /**\n * Request metrics\n */\n requests: z.object({\n total: z.number().int().describe('Total requests processed'),\n success: z.number().int().describe('Successful requests'),\n errors: z.number().int().describe('Failed requests'),\n }).optional(),\n});\n\nexport type ServerStatus = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create HTTP server configuration\n */\nexport const HttpServerConfig = Object.assign(HttpServerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create middleware configuration\n */\nexport const MiddlewareConfig = Object.assign(MiddlewareConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Audit Log Architecture\n * \n * Comprehensive audit logging system for compliance and security.\n * Supports SOX, HIPAA, GDPR, and other regulatory requirements.\n * \n * Features:\n * - Records all CRUD operations on data\n * - Tracks authentication events (login, logout, password reset)\n * - Monitors authorization changes (permissions, roles)\n * - Configurable retention policies (180-day GDPR requirement)\n * - Suspicious activity detection and alerting\n */\n\n/**\n * Audit Event Type Enum\n * Categorizes different types of auditable events in the system\n */\nexport const AuditEventType = z.enum([\n // Data Operations (CRUD)\n 'data.create', // Record creation\n 'data.read', // Record retrieval/viewing\n 'data.update', // Record modification\n 'data.delete', // Record deletion\n 'data.export', // Data export operations\n 'data.import', // Data import operations\n 'data.bulk_update', // Bulk update operations\n 'data.bulk_delete', // Bulk delete operations\n \n // Authentication Events\n 'auth.login', // Successful login\n 'auth.login_failed', // Failed login attempt\n 'auth.logout', // User logout\n 'auth.session_created', // New session created\n 'auth.session_expired', // Session expiration\n 'auth.password_reset', // Password reset initiated\n 'auth.password_changed', // Password successfully changed\n 'auth.email_verified', // Email verification completed\n 'auth.mfa_enabled', // Multi-factor auth enabled\n 'auth.mfa_disabled', // Multi-factor auth disabled\n 'auth.account_locked', // Account locked (too many failures)\n 'auth.account_unlocked', // Account unlocked\n \n // Authorization Events\n 'authz.permission_granted', // Permission granted to user\n 'authz.permission_revoked', // Permission revoked from user\n 'authz.role_assigned', // Role assigned to user\n 'authz.role_removed', // Role removed from user\n 'authz.role_created', // New role created\n 'authz.role_updated', // Role permissions modified\n 'authz.role_deleted', // Role deleted\n 'authz.policy_created', // Security policy created\n 'authz.policy_updated', // Security policy updated\n 'authz.policy_deleted', // Security policy deleted\n \n // System Events\n 'system.config_changed', // System configuration modified\n 'system.plugin_installed', // Plugin installed\n 'system.plugin_uninstalled', // Plugin uninstalled\n 'system.backup_created', // Backup created\n 'system.backup_restored', // Backup restored\n 'system.integration_added', // External integration added\n 'system.integration_removed',// External integration removed\n \n // Security Events\n 'security.access_denied', // Access denied (authorization failure)\n 'security.suspicious_activity', // Suspicious activity detected\n 'security.data_breach', // Potential data breach detected\n 'security.api_key_created', // API key created\n 'security.api_key_revoked', // API key revoked\n]);\n\nexport type AuditEventType = z.infer;\n\n/**\n * Audit Event Severity Level\n * Indicates the importance/criticality of an audit event\n */\nexport const AuditEventSeverity = z.enum([\n 'debug', // Diagnostic information\n 'info', // Informational events (normal operations)\n 'notice', // Normal but significant events\n 'warning', // Warning conditions\n 'error', // Error conditions\n 'critical', // Critical conditions requiring immediate attention\n 'alert', // Action must be taken immediately\n 'emergency', // System is unusable\n]);\n\nexport type AuditEventSeverity = z.infer;\n\n/**\n * Audit Event Actor Schema\n * Identifies who/what performed the action\n */\nexport const AuditEventActorSchema = z.object({\n /**\n * Actor type (user, system, service, api_client, etc.)\n */\n type: z.enum(['user', 'system', 'service', 'api_client', 'integration']).describe('Actor type'),\n \n /**\n * Unique identifier for the actor\n */\n id: z.string().describe('Actor identifier'),\n \n /**\n * Display name of the actor\n */\n name: z.string().optional().describe('Actor display name'),\n \n /**\n * Email address (for user actors)\n */\n email: z.string().email().optional().describe('Actor email address'),\n \n /**\n * IP address of the actor\n */\n ipAddress: z.string().optional().describe('Actor IP address'),\n \n /**\n * User agent string (for web/API requests)\n */\n userAgent: z.string().optional().describe('User agent string'),\n});\n\nexport type AuditEventActor = z.infer;\n\n/**\n * Audit Event Target Schema\n * Identifies what was acted upon\n */\nexport const AuditEventTargetSchema = z.object({\n /**\n * Target type (e.g., 'object', 'record', 'user', 'role', 'config')\n */\n type: z.string().describe('Target type'),\n \n /**\n * Unique identifier for the target\n */\n id: z.string().describe('Target identifier'),\n \n /**\n * Display name of the target\n */\n name: z.string().optional().describe('Target display name'),\n \n /**\n * Additional metadata about the target\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Target metadata'),\n});\n\nexport type AuditEventTarget = z.infer;\n\n/**\n * Audit Event Change Schema\n * Describes what changed (for update operations)\n */\nexport const AuditEventChangeSchema = z.object({\n /**\n * Field/property that changed\n */\n field: z.string().describe('Changed field name'),\n \n /**\n * Value before the change\n */\n oldValue: z.unknown().optional().describe('Previous value'),\n \n /**\n * Value after the change\n */\n newValue: z.unknown().optional().describe('New value'),\n});\n\nexport type AuditEventChange = z.infer;\n\n/**\n * Audit Event Schema\n * Complete audit event record\n */\nexport const AuditEventSchema = z.object({\n /**\n * Unique identifier for this audit event\n */\n id: z.string().describe('Audit event ID'),\n \n /**\n * Type of event being audited\n */\n eventType: AuditEventType.describe('Event type'),\n \n /**\n * Severity level of the event\n */\n severity: AuditEventSeverity.default('info').describe('Event severity'),\n \n /**\n * Timestamp when the event occurred (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n \n /**\n * Who/what performed the action\n */\n actor: AuditEventActorSchema.describe('Event actor'),\n \n /**\n * What was acted upon\n */\n target: AuditEventTargetSchema.optional().describe('Event target'),\n \n /**\n * Human-readable description of the action\n */\n description: z.string().describe('Event description'),\n \n /**\n * Detailed changes (for update operations)\n */\n changes: z.array(AuditEventChangeSchema).optional().describe('List of changes'),\n \n /**\n * Result of the action (success, failure, partial)\n */\n result: z.enum(['success', 'failure', 'partial']).default('success').describe('Action result'),\n \n /**\n * Error message (if result is failure)\n */\n errorMessage: z.string().optional().describe('Error message'),\n \n /**\n * Tenant identifier (for multi-tenant systems)\n */\n tenantId: z.string().optional().describe('Tenant identifier'),\n \n /**\n * Request/trace ID for correlation\n */\n requestId: z.string().optional().describe('Request ID for tracing'),\n \n /**\n * Additional context and metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n \n /**\n * Geographic location (if available)\n */\n location: z.object({\n country: z.string().optional(),\n region: z.string().optional(),\n city: z.string().optional(),\n }).optional().describe('Geographic location'),\n});\n\nexport type AuditEvent = z.infer;\n\n/**\n * Audit Retention Policy Schema\n * Defines how long audit logs are retained\n */\nexport const AuditRetentionPolicySchema = z.object({\n /**\n * Retention period in days\n * Default: 180 days (GDPR 6-month requirement)\n */\n retentionDays: z.number().int().min(1).default(180).describe('Retention period in days'),\n \n /**\n * Whether to archive logs after retention period\n * If true, logs are moved to cold storage; if false, they are deleted\n */\n archiveAfterRetention: z.boolean().default(true).describe('Archive logs after retention period'),\n \n /**\n * Archive storage configuration\n */\n archiveStorage: z.object({\n type: z.enum(['s3', 'gcs', 'azure_blob', 'filesystem']).describe('Archive storage type'),\n endpoint: z.string().optional().describe('Storage endpoint URL'),\n bucket: z.string().optional().describe('Storage bucket/container name'),\n path: z.string().optional().describe('Storage path prefix'),\n credentials: z.record(z.string(), z.unknown()).optional().describe('Storage credentials'),\n }).optional().describe('Archive storage configuration'),\n \n /**\n * Event types that have different retention periods\n * Overrides the default retentionDays for specific event types\n */\n customRetention: z.record(z.string(), z.number().int().positive()).optional().describe('Custom retention by event type'),\n \n /**\n * Minimum retention period for compliance\n * Prevents accidental deletion below compliance requirements\n */\n minimumRetentionDays: z.number().int().positive().optional().describe('Minimum retention for compliance'),\n});\n\nexport type AuditRetentionPolicy = z.infer;\n\n/**\n * Suspicious Activity Rule Schema\n * Defines rules for detecting suspicious activities\n */\nexport const SuspiciousActivityRuleSchema = z.object({\n /**\n * Unique identifier for the rule\n */\n id: z.string().describe('Rule identifier'),\n \n /**\n * Rule name\n */\n name: z.string().describe('Rule name'),\n \n /**\n * Rule description\n */\n description: z.string().optional().describe('Rule description'),\n \n /**\n * Whether the rule is enabled\n */\n enabled: z.boolean().default(true).describe('Rule enabled status'),\n \n /**\n * Event types to monitor\n */\n eventTypes: z.array(AuditEventType).describe('Event types to monitor'),\n \n /**\n * Detection condition\n */\n condition: z.object({\n /**\n * Number of events that trigger the rule\n */\n threshold: z.number().int().positive().describe('Event threshold'),\n \n /**\n * Time window in seconds\n */\n windowSeconds: z.number().int().positive().describe('Time window in seconds'),\n \n /**\n * Grouping criteria (e.g., by actor.id, by ipAddress)\n */\n groupBy: z.array(z.string()).optional().describe('Grouping criteria'),\n \n /**\n * Additional filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters'),\n }).describe('Detection condition'),\n \n /**\n * Actions to take when rule is triggered\n */\n actions: z.array(z.enum([\n 'alert', // Send alert notification\n 'lock_account', // Lock the user account\n 'block_ip', // Block the IP address\n 'require_mfa', // Require multi-factor authentication\n 'log_critical', // Log as critical event\n 'webhook', // Call webhook\n ])).describe('Actions to take'),\n \n /**\n * Severity level for triggered alerts\n */\n alertSeverity: AuditEventSeverity.default('warning').describe('Alert severity'),\n \n /**\n * Notification configuration\n */\n notifications: z.object({\n /**\n * Email addresses to notify\n */\n email: z.array(z.string().email()).optional().describe('Email recipients'),\n \n /**\n * Slack webhook URL\n */\n slack: z.string().url().optional().describe('Slack webhook URL'),\n \n /**\n * Custom webhook URL\n */\n webhook: z.string().url().optional().describe('Custom webhook URL'),\n }).optional().describe('Notification configuration'),\n});\n\nexport type SuspiciousActivityRule = z.infer;\n\n/**\n * Audit Log Storage Configuration\n * Defines where and how audit logs are stored\n */\nexport const AuditStorageConfigSchema = z.object({\n /**\n * Storage backend type\n */\n type: z.enum([\n 'database', // Store in database (PostgreSQL, MySQL, etc.)\n 'elasticsearch', // Store in Elasticsearch\n 'mongodb', // Store in MongoDB\n 'clickhouse', // Store in ClickHouse (for analytics)\n 's3', // Store in S3-compatible storage\n 'gcs', // Store in Google Cloud Storage\n 'azure_blob', // Store in Azure Blob Storage\n 'custom', // Custom storage implementation\n ]).describe('Storage backend type'),\n \n /**\n * Connection string or configuration\n */\n connectionString: z.string().optional().describe('Connection string'),\n \n /**\n * Storage configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Storage-specific configuration'),\n \n /**\n * Whether to enable buffering/batching\n */\n bufferEnabled: z.boolean().default(true).describe('Enable buffering'),\n \n /**\n * Buffer size (number of events before flush)\n */\n bufferSize: z.number().int().positive().default(100).describe('Buffer size'),\n \n /**\n * Buffer flush interval in seconds\n */\n flushIntervalSeconds: z.number().int().positive().default(5).describe('Flush interval in seconds'),\n \n /**\n * Whether to compress stored data\n */\n compression: z.boolean().default(true).describe('Enable compression'),\n});\n\nexport type AuditStorageConfig = z.infer;\n\n/**\n * Audit Event Filter Schema\n * Defines filters for querying audit events\n */\nexport const AuditEventFilterSchema = z.object({\n /**\n * Filter by event types\n */\n eventTypes: z.array(AuditEventType).optional().describe('Event types to include'),\n \n /**\n * Filter by severity levels\n */\n severities: z.array(AuditEventSeverity).optional().describe('Severity levels to include'),\n \n /**\n * Filter by actor ID\n */\n actorId: z.string().optional().describe('Actor identifier'),\n \n /**\n * Filter by tenant ID\n */\n tenantId: z.string().optional().describe('Tenant identifier'),\n \n /**\n * Filter by time range\n */\n timeRange: z.object({\n from: z.string().datetime().describe('Start time'),\n to: z.string().datetime().describe('End time'),\n }).optional().describe('Time range filter'),\n \n /**\n * Filter by result status\n */\n result: z.enum(['success', 'failure', 'partial']).optional().describe('Result status'),\n \n /**\n * Search query (full-text search)\n */\n searchQuery: z.string().optional().describe('Search query'),\n \n /**\n * Custom filters\n */\n customFilters: z.record(z.string(), z.unknown()).optional().describe('Custom filters'),\n});\n\nexport type AuditEventFilter = z.infer;\n\n/**\n * Complete Audit Configuration Schema\n * Main configuration for the audit system\n */\nexport const AuditConfigSchema = z.object({\n /**\n * Unique identifier for this audit configuration\n * Must be in snake_case following ObjectStack conventions\n * Maximum length: 64 characters\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n \n /**\n * Human-readable label\n */\n label: z.string().describe('Display label'),\n \n /**\n * Whether audit logging is enabled\n */\n enabled: z.boolean().default(true).describe('Enable audit logging'),\n \n /**\n * Event types to audit\n * If not specified, all event types are audited\n */\n eventTypes: z.array(AuditEventType).optional().describe('Event types to audit'),\n \n /**\n * Event types to exclude from auditing\n */\n excludeEventTypes: z.array(AuditEventType).optional().describe('Event types to exclude'),\n \n /**\n * Minimum severity level to log\n * Events below this level are not logged\n */\n minimumSeverity: AuditEventSeverity.default('info').describe('Minimum severity level'),\n \n /**\n * Storage configuration\n */\n storage: AuditStorageConfigSchema.describe('Storage configuration'),\n \n /**\n * Retention policy\n */\n retentionPolicy: AuditRetentionPolicySchema.optional().describe('Retention policy'),\n \n /**\n * Suspicious activity detection rules\n */\n suspiciousActivityRules: z.array(SuspiciousActivityRuleSchema).default([]).describe('Suspicious activity rules'),\n \n /**\n * Whether to include sensitive data in audit logs\n * If false, sensitive fields are redacted/masked\n */\n includeSensitiveData: z.boolean().default(false).describe('Include sensitive data'),\n \n /**\n * Fields to redact from audit logs\n */\n redactFields: z.array(z.string()).default([\n 'password',\n 'passwordHash',\n 'token',\n 'apiKey',\n 'secret',\n 'creditCard',\n 'ssn',\n ]).describe('Fields to redact'),\n \n /**\n * Whether to log successful read operations\n * Can be disabled to reduce log volume\n */\n logReads: z.boolean().default(false).describe('Log read operations'),\n \n /**\n * Sampling rate for read operations (0.0 to 1.0)\n * Only applies if logReads is true\n */\n readSamplingRate: z.number().min(0).max(1).default(0.1).describe('Read sampling rate'),\n \n /**\n * Whether to log system/internal operations\n */\n logSystemEvents: z.boolean().default(true).describe('Log system events'),\n \n /**\n * Custom audit event handlers\n * Note: Function handlers are for runtime configuration only and will not be serialized to JSON Schema\n */\n customHandlers: z.array(z.object({\n eventType: AuditEventType.describe('Event type to handle'),\n handlerId: z.string().describe('Unique identifier for the handler'),\n })).optional().describe('Custom event handler references'),\n \n /**\n * Compliance mode configuration\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox', // Sarbanes-Oxley Act\n 'hipaa', // Health Insurance Portability and Accountability Act\n 'gdpr', // General Data Protection Regulation\n 'pci_dss', // Payment Card Industry Data Security Standard\n 'iso_27001',// ISO/IEC 27001\n 'fedramp', // Federal Risk and Authorization Management Program\n ])).optional().describe('Compliance standards'),\n \n /**\n * Whether to enforce immutable audit logs\n */\n immutableLogs: z.boolean().default(true).describe('Enforce immutable logs'),\n \n /**\n * Whether to require cryptographic signing\n */\n requireSigning: z.boolean().default(false).describe('Require log signing'),\n \n /**\n * Signing key configuration\n */\n signingKey: z.string().optional().describe('Signing key'),\n }).optional().describe('Compliance configuration'),\n});\n\nexport type AuditConfig = z.infer;\n\n/**\n * Default suspicious activity rules\n * Common security patterns to detect\n */\nexport const DEFAULT_SUSPICIOUS_ACTIVITY_RULES: SuspiciousActivityRule[] = [\n {\n id: 'multiple_failed_logins',\n name: 'Multiple Failed Login Attempts',\n description: 'Detects multiple failed login attempts from the same user or IP',\n enabled: true,\n eventTypes: ['auth.login_failed'],\n condition: {\n threshold: 5,\n windowSeconds: 600, // 10 minutes\n groupBy: ['actor.id', 'actor.ipAddress'],\n },\n actions: ['alert', 'lock_account'],\n alertSeverity: 'warning',\n },\n {\n id: 'bulk_data_export',\n name: 'Bulk Data Export',\n description: 'Detects large data export operations',\n enabled: true,\n eventTypes: ['data.export'],\n condition: {\n threshold: 3,\n windowSeconds: 3600, // 1 hour\n groupBy: ['actor.id'],\n },\n actions: ['alert', 'log_critical'],\n alertSeverity: 'warning',\n },\n {\n id: 'suspicious_permission_changes',\n name: 'Rapid Permission Changes',\n description: 'Detects rapid permission or role changes',\n enabled: true,\n eventTypes: ['authz.permission_granted', 'authz.role_assigned'],\n condition: {\n threshold: 10,\n windowSeconds: 300, // 5 minutes\n groupBy: ['actor.id'],\n },\n actions: ['alert', 'log_critical'],\n alertSeverity: 'critical',\n },\n {\n id: 'after_hours_access',\n name: 'After Hours Access',\n description: 'Detects access during non-business hours',\n enabled: false, // Disabled by default, requires time zone configuration\n eventTypes: ['auth.login'],\n condition: {\n threshold: 1,\n windowSeconds: 86400, // 24 hours\n },\n actions: ['alert'],\n alertSeverity: 'notice',\n },\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Logging Protocol - Comprehensive Observability Logging\n * \n * Unified logging protocol that combines:\n * - Basic kernel logging (LoggerConfig)\n * - Enterprise-grade features (LoggingConfig)\n * - Multiple log destinations (file, console, external services)\n * - Structured logging with enrichment\n * - Log aggregation and forwarding\n * - Integration with external log management systems\n */\n\n// ============================================================================\n// Basic Logger Protocol (formerly from logger.zod.ts)\n// ============================================================================\n\n/**\n * Log Level Enum\n * Standard RFC 5424 severity levels (simplified)\n */\nexport const LogLevel = z.enum([\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'fatal',\n 'silent'\n]).describe('Log severity level');\n\nexport type LogLevel = z.infer;\n\n/**\n * Log Format Enum\n */\nexport const LogFormat = z.enum([\n 'json', // Structured JSON for machine parsing\n 'text', // Simple text format\n 'pretty' // Colored human-readable output for CLI/console\n]).describe('Log output format');\n\nexport type LogFormat = z.infer;\n\n/**\n * Logger Configuration Schema\n * Configuration for the Kernel's internal logger\n */\nexport const LoggerConfigSchema = z.object({\n /**\n * Logger name\n */\n name: z.string().optional().describe('Logger name identifier'),\n\n /**\n * Minimum level to log\n */\n level: LogLevel.optional().default('info'),\n\n /**\n * Output format\n */\n format: LogFormat.optional().default('json'),\n\n /**\n * Redact sensitive keys\n */\n redact: z.array(z.string()).optional().default(['password', 'token', 'secret', 'key'])\n .describe('Keys to redact from log context'),\n\n /**\n * Enable source location (file/line)\n */\n sourceLocation: z.boolean().optional().default(false)\n .describe('Include file and line number'),\n\n /**\n * Log to file (optional)\n */\n file: z.string().optional().describe('Path to log file'),\n\n /**\n * Log rotation config (if file is set)\n */\n rotation: z.object({\n maxSize: z.string().optional().default('10m'),\n maxFiles: z.number().optional().default(5)\n }).optional()\n});\n\nexport type LoggerConfig = z.infer;\n\n/**\n * Log Entry Schema\n * The shape of a structured log record\n */\nexport const LogEntrySchema = z.object({\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n level: LogLevel,\n message: z.string().describe('Log message'),\n context: z.record(z.string(), z.unknown()).optional().describe('Structured context data'),\n error: z.record(z.string(), z.unknown()).optional().describe('Error object if present'),\n \n /** Tracing */\n traceId: z.string().optional().describe('Distributed trace ID'),\n spanId: z.string().optional().describe('Span ID'),\n \n /** Source */\n service: z.string().optional().describe('Service name'),\n component: z.string().optional().describe('Component name (e.g. plugin id)'),\n});\n\nexport type LogEntry = z.infer;\n\n// ============================================================================\n// Extended Logging Protocol (enterprise features)\n// ============================================================================\n\n/**\n * Extended Log Level Enum\n * Standard RFC 5424 severity levels with trace\n */\nexport const ExtendedLogLevel = z.enum([\n 'trace', // Very detailed debugging information\n 'debug', // Debugging information\n 'info', // Informational messages\n 'warn', // Warning messages\n 'error', // Error messages\n 'fatal', // Fatal errors causing shutdown\n]).describe('Extended log severity level');\n\nexport type ExtendedLogLevel = z.infer;\n\n/**\n * Log Destination Type Enum\n * Where logs can be sent\n */\nexport const LogDestinationType = z.enum([\n 'console', // Standard output/error\n 'file', // File system\n 'syslog', // System logger\n 'elasticsearch', // Elasticsearch\n 'cloudwatch', // AWS CloudWatch\n 'stackdriver', // Google Cloud Logging\n 'azure_monitor', // Azure Monitor\n 'datadog', // Datadog\n 'splunk', // Splunk\n 'loki', // Grafana Loki\n 'http', // HTTP endpoint\n 'kafka', // Apache Kafka\n 'redis', // Redis streams\n 'custom', // Custom implementation\n]).describe('Log destination type');\n\nexport type LogDestinationType = z.infer;\n\n/**\n * Console Destination Configuration\n */\nexport const ConsoleDestinationConfigSchema = z.object({\n /**\n * Output stream\n */\n stream: z.enum(['stdout', 'stderr']).optional().default('stdout'),\n\n /**\n * Enable colored output\n */\n colors: z.boolean().optional().default(true),\n\n /**\n * Pretty print JSON\n */\n prettyPrint: z.boolean().optional().default(false),\n}).describe('Console destination configuration');\n\nexport type ConsoleDestinationConfig = z.infer;\n\n/**\n * File Destination Configuration\n */\nexport const FileDestinationConfigSchema = z.object({\n /**\n * File path\n */\n path: z.string().describe('Log file path'),\n\n /**\n * Enable log rotation\n */\n rotation: z.object({\n /**\n * Maximum file size before rotation (e.g., '10m', '100k', '1g')\n */\n maxSize: z.string().optional().default('10m'),\n\n /**\n * Maximum number of files to keep\n */\n maxFiles: z.number().int().positive().optional().default(5),\n\n /**\n * Compress rotated files\n */\n compress: z.boolean().optional().default(true),\n\n /**\n * Rotation interval (e.g., 'daily', 'weekly')\n */\n interval: z.enum(['hourly', 'daily', 'weekly', 'monthly']).optional(),\n }).optional(),\n\n /**\n * File encoding\n */\n encoding: z.string().optional().default('utf8'),\n\n /**\n * Append to existing file\n */\n append: z.boolean().optional().default(true),\n}).describe('File destination configuration');\n\nexport type FileDestinationConfig = z.infer;\n\n/**\n * HTTP Destination Configuration\n */\nexport const HttpDestinationConfigSchema = z.object({\n /**\n * HTTP endpoint URL\n */\n url: z.string().url().describe('HTTP endpoint URL'),\n\n /**\n * HTTP method\n */\n method: z.enum(['POST', 'PUT']).optional().default('POST'),\n\n /**\n * Headers to include\n */\n headers: z.record(z.string(), z.string()).optional(),\n\n /**\n * Authentication\n */\n auth: z.object({\n type: z.enum(['basic', 'bearer', 'api_key']).describe('Auth type'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n apiKeyHeader: z.string().optional().default('X-API-Key'),\n }).optional(),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n /**\n * Maximum batch size\n */\n maxSize: z.number().int().positive().optional().default(100),\n\n /**\n * Flush interval in milliseconds\n */\n flushInterval: z.number().int().positive().optional().default(5000),\n }).optional(),\n\n /**\n * Retry configuration\n */\n retry: z.object({\n /**\n * Maximum retry attempts\n */\n maxAttempts: z.number().int().positive().optional().default(3),\n\n /**\n * Initial retry delay in milliseconds\n */\n initialDelay: z.number().int().positive().optional().default(1000),\n\n /**\n * Backoff multiplier\n */\n backoffMultiplier: z.number().positive().optional().default(2),\n }).optional(),\n\n /**\n * Timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().default(30000),\n}).describe('HTTP destination configuration');\n\nexport type HttpDestinationConfig = z.infer;\n\n/**\n * External Service Destination Configuration\n * Generic configuration for cloud logging services\n */\nexport const ExternalServiceDestinationConfigSchema = z.object({\n /**\n * Service-specific endpoint\n */\n endpoint: z.string().url().optional(),\n\n /**\n * Region (for cloud services)\n */\n region: z.string().optional(),\n\n /**\n * Credentials\n */\n credentials: z.object({\n accessKeyId: z.string().optional(),\n secretAccessKey: z.string().optional(),\n apiKey: z.string().optional(),\n projectId: z.string().optional(),\n }).optional(),\n\n /**\n * Log group/stream/index name\n */\n logGroup: z.string().optional(),\n logStream: z.string().optional(),\n index: z.string().optional(),\n\n /**\n * Service-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional(),\n}).describe('External service destination configuration');\n\nexport type ExternalServiceDestinationConfig = z.infer;\n\n/**\n * Log Destination Schema\n * Configuration for a single log destination\n */\nexport const LogDestinationSchema = z.object({\n /**\n * Destination name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Destination name (snake_case)'),\n\n /**\n * Destination type\n */\n type: LogDestinationType.describe('Destination type'),\n\n /**\n * Minimum log level for this destination\n */\n level: ExtendedLogLevel.optional().default('info'),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Console configuration\n */\n console: ConsoleDestinationConfigSchema.optional(),\n\n /**\n * File configuration\n */\n file: FileDestinationConfigSchema.optional(),\n\n /**\n * HTTP configuration\n */\n http: HttpDestinationConfigSchema.optional(),\n\n /**\n * External service configuration\n */\n externalService: ExternalServiceDestinationConfigSchema.optional(),\n\n /**\n * Format for this destination\n */\n format: z.enum(['json', 'text', 'pretty']).optional().default('json'),\n\n /**\n * Filter function reference (runtime only)\n */\n filterId: z.string().optional().describe('Filter function identifier'),\n}).describe('Log destination configuration');\n\nexport type LogDestination = z.infer;\n\n/**\n * Log Enrichment Configuration\n * Add contextual data to all log entries\n */\nexport const LogEnrichmentConfigSchema = z.object({\n /**\n * Static fields to add to all logs\n */\n staticFields: z.record(z.string(), z.unknown()).optional().describe('Static fields added to every log'),\n\n /**\n * Dynamic field enrichers (runtime only)\n * References to functions that add dynamic context\n */\n dynamicEnrichers: z.array(z.string()).optional().describe('Dynamic enricher function IDs'),\n\n /**\n * Add hostname\n */\n addHostname: z.boolean().optional().default(true),\n\n /**\n * Add process ID\n */\n addProcessId: z.boolean().optional().default(true),\n\n /**\n * Add environment info\n */\n addEnvironment: z.boolean().optional().default(true),\n\n /**\n * Add timestamp in additional formats\n */\n addTimestampFormats: z.object({\n unix: z.boolean().optional().default(false),\n iso: z.boolean().optional().default(true),\n }).optional(),\n\n /**\n * Add caller information (file, line, function)\n */\n addCaller: z.boolean().optional().default(false),\n\n /**\n * Add correlation IDs\n */\n addCorrelationIds: z.boolean().optional().default(true),\n}).describe('Log enrichment configuration');\n\nexport type LogEnrichmentConfig = z.infer;\n\n/**\n * Structured Log Entry Schema\n * Enhanced structured log record with enrichment\n */\nexport const StructuredLogEntrySchema = z.object({\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n\n /**\n * Log level\n */\n level: ExtendedLogLevel.describe('Log severity level'),\n\n /**\n * Log message\n */\n message: z.string().describe('Log message'),\n\n /**\n * Structured context data\n */\n context: z.record(z.string(), z.unknown()).optional().describe('Structured context'),\n\n /**\n * Error information\n */\n error: z.object({\n name: z.string().optional(),\n message: z.string().optional(),\n stack: z.string().optional(),\n code: z.string().optional(),\n details: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Error details'),\n\n /**\n * Trace context\n */\n trace: z.object({\n traceId: z.string().describe('Trace ID'),\n spanId: z.string().describe('Span ID'),\n parentSpanId: z.string().optional().describe('Parent span ID'),\n traceFlags: z.number().int().optional().describe('Trace flags'),\n }).optional().describe('Distributed tracing context'),\n\n /**\n * Source information\n */\n source: z.object({\n service: z.string().optional().describe('Service name'),\n component: z.string().optional().describe('Component name'),\n file: z.string().optional().describe('Source file'),\n line: z.number().int().optional().describe('Line number'),\n function: z.string().optional().describe('Function name'),\n }).optional().describe('Source information'),\n\n /**\n * Host information\n */\n host: z.object({\n hostname: z.string().optional(),\n pid: z.number().int().optional(),\n ip: z.string().optional(),\n }).optional().describe('Host information'),\n\n /**\n * Environment\n */\n environment: z.string().optional().describe('Environment (e.g., production, staging)'),\n\n /**\n * User information\n */\n user: z.object({\n id: z.string().optional(),\n username: z.string().optional(),\n email: z.string().optional(),\n }).optional().describe('User context'),\n\n /**\n * Request information\n */\n request: z.object({\n id: z.string().optional(),\n method: z.string().optional(),\n path: z.string().optional(),\n userAgent: z.string().optional(),\n ip: z.string().optional(),\n }).optional().describe('Request context'),\n\n /**\n * Custom labels/tags\n */\n labels: z.record(z.string(), z.string()).optional().describe('Custom labels'),\n\n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n}).describe('Structured log entry');\n\nexport type StructuredLogEntry = z.infer;\n\n/**\n * Logging Configuration Schema\n * Main configuration for the logging system\n */\nexport const LoggingConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable logging\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Global minimum log level\n */\n level: ExtendedLogLevel.optional().default('info'),\n\n /**\n * Default logger configuration\n * Basic logger config for the kernel\n */\n default: LoggerConfigSchema.optional().describe('Default logger configuration'),\n\n /**\n * Named logger configurations\n * Map of logger name to logger config for different components/modules\n */\n loggers: z.record(z.string(), LoggerConfigSchema).optional().describe('Named logger configurations'),\n\n /**\n * Log destinations\n */\n destinations: z.array(LogDestinationSchema).describe('Log destinations'),\n\n /**\n * Log enrichment configuration\n */\n enrichment: LogEnrichmentConfigSchema.optional(),\n\n /**\n * Fields to redact from logs\n */\n redact: z.array(z.string()).optional().default([\n 'password',\n 'passwordHash',\n 'token',\n 'apiKey',\n 'secret',\n 'creditCard',\n 'ssn',\n 'authorization',\n ]).describe('Fields to redact'),\n\n /**\n * Sampling configuration\n */\n sampling: z.object({\n /**\n * Enable sampling\n */\n enabled: z.boolean().optional().default(false),\n\n /**\n * Sample rate (0.0 to 1.0)\n */\n rate: z.number().min(0).max(1).optional().default(1.0),\n\n /**\n * Sample rate by level\n */\n rateByLevel: z.record(z.string(), z.number().min(0).max(1)).optional(),\n }).optional(),\n\n /**\n * Buffer configuration\n */\n buffer: z.object({\n /**\n * Enable buffering\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Buffer size\n */\n size: z.number().int().positive().optional().default(1000),\n\n /**\n * Flush interval in milliseconds\n */\n flushInterval: z.number().int().positive().optional().default(1000),\n\n /**\n * Flush on shutdown\n */\n flushOnShutdown: z.boolean().optional().default(true),\n }).optional(),\n\n /**\n * Performance configuration\n */\n performance: z.object({\n /**\n * Async logging\n */\n async: z.boolean().optional().default(true),\n\n /**\n * Worker threads for async logging\n */\n workers: z.number().int().positive().optional().default(1),\n }).optional(),\n}).describe('Logging configuration');\n\nexport type LoggingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metrics Protocol - Performance and Operational Metrics\n * \n * Comprehensive metrics collection and monitoring:\n * - Counter, Gauge, Histogram, Summary metric types\n * - Time-series data collection\n * - SLI/SLO definitions\n * - Metric aggregation and export\n * - Integration with monitoring systems (Prometheus, etc.)\n */\n\n/**\n * Metric Type Enum\n * Standard Prometheus metric types\n */\nexport const MetricType = z.enum([\n 'counter', // Monotonically increasing value\n 'gauge', // Value that can go up and down\n 'histogram', // Observations bucketed by configurable ranges\n 'summary', // Observations with quantiles\n]).describe('Metric type');\n\nexport type MetricType = z.infer;\n\n/**\n * Metric Unit Enum\n * Standard units for metrics\n */\nexport const MetricUnit = z.enum([\n // Time units\n 'nanoseconds',\n 'microseconds',\n 'milliseconds',\n 'seconds',\n 'minutes',\n 'hours',\n 'days',\n\n // Size units\n 'bytes',\n 'kilobytes',\n 'megabytes',\n 'gigabytes',\n 'terabytes',\n\n // Rate units\n 'requests_per_second',\n 'events_per_second',\n 'bytes_per_second',\n\n // Percentage\n 'percent',\n 'ratio',\n\n // Count\n 'count',\n 'operations',\n\n // Custom\n 'custom',\n]).describe('Metric unit');\n\nexport type MetricUnit = z.infer;\n\n/**\n * Metric Aggregation Type\n */\nexport const MetricAggregationType = z.enum([\n 'sum', // Sum of all values\n 'avg', // Average of all values\n 'min', // Minimum value\n 'max', // Maximum value\n 'count', // Count of observations\n 'p50', // 50th percentile (median)\n 'p75', // 75th percentile\n 'p90', // 90th percentile\n 'p95', // 95th percentile\n 'p99', // 99th percentile\n 'p999', // 99.9th percentile\n 'rate', // Rate of change\n 'stddev', // Standard deviation\n]).describe('Metric aggregation type');\n\nexport type MetricAggregationType = z.infer;\n\n/**\n * Histogram Bucket Configuration\n */\nexport const HistogramBucketConfigSchema = z.object({\n /**\n * Bucket type\n */\n type: z.enum(['linear', 'exponential', 'explicit']).describe('Bucket type'),\n\n /**\n * Linear bucket configuration\n */\n linear: z.object({\n start: z.number().describe('Start value'),\n width: z.number().positive().describe('Bucket width'),\n count: z.number().int().positive().describe('Number of buckets'),\n }).optional(),\n\n /**\n * Exponential bucket configuration\n */\n exponential: z.object({\n start: z.number().positive().describe('Start value'),\n factor: z.number().positive().describe('Growth factor'),\n count: z.number().int().positive().describe('Number of buckets'),\n }).optional(),\n\n /**\n * Explicit bucket boundaries\n */\n explicit: z.object({\n boundaries: z.array(z.number()).describe('Bucket boundaries'),\n }).optional(),\n}).describe('Histogram bucket configuration');\n\nexport type HistogramBucketConfig = z.infer;\n\n/**\n * Metric Labels Schema\n * Key-value pairs for metric dimensions\n */\nexport const MetricLabelsSchema = z.record(z.string(), z.string()).describe('Metric labels');\n\nexport type MetricLabels = z.infer;\n\n/**\n * Metric Definition Schema\n */\nexport const MetricDefinitionSchema = z.object({\n /**\n * Metric name (snake_case)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Metric name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().optional().describe('Display label'),\n\n /**\n * Metric type\n */\n type: MetricType.describe('Metric type'),\n\n /**\n * Metric unit\n */\n unit: MetricUnit.optional().describe('Metric unit'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('Metric description'),\n\n /**\n * Label names for this metric\n */\n labelNames: z.array(z.string()).optional().default([]).describe('Label names'),\n\n /**\n * Histogram configuration (for histogram type)\n */\n histogram: HistogramBucketConfigSchema.optional(),\n\n /**\n * Summary configuration (for summary type)\n */\n summary: z.object({\n /**\n * Quantiles to track\n */\n quantiles: z.array(z.number().min(0).max(1)).optional().default([0.5, 0.9, 0.99]),\n\n /**\n * Max age of observations in seconds\n */\n maxAge: z.number().int().positive().optional().default(600),\n\n /**\n * Number of age buckets\n */\n ageBuckets: z.number().int().positive().optional().default(5),\n }).optional(),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Metric definition');\n\nexport type MetricDefinition = z.infer;\n\n/**\n * Metric Data Point Schema\n * A single metric observation\n */\nexport const MetricDataPointSchema = z.object({\n /**\n * Metric name\n */\n name: z.string().describe('Metric name'),\n\n /**\n * Metric type\n */\n type: MetricType.describe('Metric type'),\n\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Observation timestamp'),\n\n /**\n * Value (for counter and gauge)\n */\n value: z.number().optional().describe('Metric value'),\n\n /**\n * Labels\n */\n labels: MetricLabelsSchema.optional().describe('Metric labels'),\n\n /**\n * Histogram data\n */\n histogram: z.object({\n count: z.number().int().nonnegative().describe('Total count'),\n sum: z.number().describe('Sum of all values'),\n buckets: z.array(z.object({\n upperBound: z.number().describe('Upper bound of bucket'),\n count: z.number().int().nonnegative().describe('Count in bucket'),\n })).describe('Histogram buckets'),\n }).optional(),\n\n /**\n * Summary data\n */\n summary: z.object({\n count: z.number().int().nonnegative().describe('Total count'),\n sum: z.number().describe('Sum of all values'),\n quantiles: z.array(z.object({\n quantile: z.number().min(0).max(1).describe('Quantile (0-1)'),\n value: z.number().describe('Quantile value'),\n })).describe('Summary quantiles'),\n }).optional(),\n}).describe('Metric data point');\n\nexport type MetricDataPoint = z.infer;\n\n/**\n * Time Series Data Point Schema\n */\nexport const TimeSeriesDataPointSchema = z.object({\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Timestamp'),\n\n /**\n * Value\n */\n value: z.number().describe('Value'),\n\n /**\n * Labels/tags\n */\n labels: z.record(z.string(), z.string()).optional().describe('Labels'),\n}).describe('Time series data point');\n\nexport type TimeSeriesDataPoint = z.infer;\n\n/**\n * Time Series Schema\n */\nexport const TimeSeriesSchema = z.object({\n /**\n * Series name\n */\n name: z.string().describe('Series name'),\n\n /**\n * Series labels\n */\n labels: z.record(z.string(), z.string()).optional().describe('Series labels'),\n\n /**\n * Data points\n */\n dataPoints: z.array(TimeSeriesDataPointSchema).describe('Data points'),\n\n /**\n * Start time\n */\n startTime: z.string().datetime().optional().describe('Start time'),\n\n /**\n * End time\n */\n endTime: z.string().datetime().optional().describe('End time'),\n}).describe('Time series');\n\nexport type TimeSeries = z.infer;\n\n/**\n * Metric Aggregation Configuration\n */\nexport const MetricAggregationConfigSchema = z.object({\n /**\n * Aggregation type\n */\n type: MetricAggregationType.describe('Aggregation type'),\n\n /**\n * Time window for aggregation\n */\n window: z.object({\n /**\n * Window size in seconds\n */\n size: z.number().int().positive().describe('Window size in seconds'),\n\n /**\n * Sliding window (true) or tumbling window (false)\n */\n sliding: z.boolean().optional().default(false),\n\n /**\n * Slide interval for sliding windows\n */\n slideInterval: z.number().int().positive().optional(),\n }).optional(),\n\n /**\n * Group by labels\n */\n groupBy: z.array(z.string()).optional().describe('Group by label names'),\n\n /**\n * Filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter criteria'),\n}).describe('Metric aggregation configuration');\n\nexport type MetricAggregationConfig = z.infer;\n\n/**\n * Service Level Indicator (SLI) Schema\n */\nexport const ServiceLevelIndicatorSchema = z.object({\n /**\n * SLI name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('SLI name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('SLI description'),\n\n /**\n * Metric name this SLI is based on\n */\n metric: z.string().describe('Base metric name'),\n\n /**\n * SLI type\n */\n type: z.enum([\n 'availability', // Percentage of successful requests\n 'latency', // Response time percentile\n 'throughput', // Requests per second\n 'error_rate', // Error percentage\n 'saturation', // Resource utilization\n 'custom', // Custom calculation\n ]).describe('SLI type'),\n\n /**\n * Success criteria\n */\n successCriteria: z.object({\n /**\n * Threshold value\n */\n threshold: z.number().describe('Threshold value'),\n\n /**\n * Comparison operator\n */\n operator: z.enum(['lt', 'lte', 'gt', 'gte', 'eq']).describe('Comparison operator'),\n\n /**\n * Percentile (for latency SLIs)\n */\n percentile: z.number().min(0).max(1).optional().describe('Percentile (0-1)'),\n }).describe('Success criteria'),\n\n /**\n * Measurement window\n */\n window: z.object({\n /**\n * Window size in seconds\n */\n size: z.number().int().positive().describe('Window size in seconds'),\n\n /**\n * Rolling window (true) or calendar-aligned (false)\n */\n rolling: z.boolean().optional().default(true),\n }).describe('Measurement window'),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Service Level Indicator');\n\nexport type ServiceLevelIndicator = z.infer;\n\n/**\n * Service Level Objective (SLO) Schema\n */\nexport const ServiceLevelObjectiveSchema = z.object({\n /**\n * SLO name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('SLO name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('SLO description'),\n\n /**\n * SLI this SLO is based on\n */\n sli: z.string().describe('SLI name'),\n\n /**\n * Target percentage (0-100)\n */\n target: z.number().min(0).max(100).describe('Target percentage'),\n\n /**\n * Time period for SLO\n */\n period: z.object({\n /**\n * Period type\n */\n type: z.enum(['rolling', 'calendar']).describe('Period type'),\n\n /**\n * Duration in seconds (for rolling)\n */\n duration: z.number().int().positive().optional().describe('Duration in seconds'),\n\n /**\n * Calendar period (for calendar)\n */\n calendar: z.enum(['daily', 'weekly', 'monthly', 'quarterly', 'yearly']).optional(),\n }).describe('Time period'),\n\n /**\n * Error budget configuration\n */\n errorBudget: z.object({\n /**\n * Auto-calculated budget (1 - target)\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Alert when budget consumed percentage exceeds threshold\n */\n alertThreshold: z.number().min(0).max(100).optional().default(80),\n\n /**\n * Burn rate alert windows\n */\n burnRateWindows: z.array(z.object({\n /**\n * Window size in seconds\n */\n window: z.number().int().positive().describe('Window size'),\n\n /**\n * Burn rate multiplier threshold\n */\n threshold: z.number().positive().describe('Burn rate threshold'),\n })).optional(),\n }).optional(),\n\n /**\n * Alert configuration\n */\n alerts: z.array(z.object({\n /**\n * Alert name\n */\n name: z.string().describe('Alert name'),\n\n /**\n * Severity\n */\n severity: z.enum(['info', 'warning', 'critical']).describe('Alert severity'),\n\n /**\n * Condition\n */\n condition: z.object({\n type: z.enum(['slo_breach', 'error_budget', 'burn_rate']).describe('Condition type'),\n threshold: z.number().optional().describe('Threshold value'),\n }).describe('Alert condition'),\n })).optional().default([]),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Service Level Objective');\n\nexport type ServiceLevelObjective = z.infer;\n\n/**\n * Metric Export Configuration\n */\nexport const MetricExportConfigSchema = z.object({\n /**\n * Export type\n */\n type: z.enum([\n 'prometheus', // Prometheus exposition format\n 'openmetrics', // OpenMetrics format\n 'graphite', // Graphite plaintext protocol\n 'statsd', // StatsD protocol\n 'influxdb', // InfluxDB line protocol\n 'datadog', // Datadog agent\n 'cloudwatch', // AWS CloudWatch\n 'stackdriver', // Google Cloud Monitoring\n 'azure_monitor', // Azure Monitor\n 'http', // HTTP push\n 'custom', // Custom exporter\n ]).describe('Export type'),\n\n /**\n * Endpoint configuration\n */\n endpoint: z.string().optional().describe('Export endpoint'),\n\n /**\n * Export interval in seconds\n */\n interval: z.number().int().positive().optional().default(60),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n enabled: z.boolean().optional().default(true),\n size: z.number().int().positive().optional().default(1000),\n }).optional(),\n\n /**\n * Authentication\n */\n auth: z.object({\n type: z.enum(['none', 'basic', 'bearer', 'api_key']).describe('Auth type'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n }).optional(),\n\n /**\n * Additional configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Additional configuration'),\n}).describe('Metric export configuration');\n\nexport type MetricExportConfig = z.infer;\n\n/**\n * Metrics Configuration Schema\n */\nexport const MetricsConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable metrics collection\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Metric definitions\n */\n metrics: z.array(MetricDefinitionSchema).optional().default([]),\n\n /**\n * Default labels applied to all metrics\n */\n defaultLabels: MetricLabelsSchema.optional().default({}),\n\n /**\n * Aggregation configurations\n */\n aggregations: z.array(MetricAggregationConfigSchema).optional().default([]),\n\n /**\n * Service Level Indicators\n */\n slis: z.array(ServiceLevelIndicatorSchema).optional().default([]),\n\n /**\n * Service Level Objectives\n */\n slos: z.array(ServiceLevelObjectiveSchema).optional().default([]),\n\n /**\n * Export configurations\n */\n exports: z.array(MetricExportConfigSchema).optional().default([]),\n\n /**\n * Collection interval in seconds\n */\n collectionInterval: z.number().int().positive().optional().default(15),\n\n /**\n * Retention configuration\n */\n retention: z.object({\n /**\n * Retention period in seconds\n */\n period: z.number().int().positive().optional().default(604800), // 7 days\n\n /**\n * Downsampling configuration\n */\n downsampling: z.array(z.object({\n /**\n * After this duration, downsample to this resolution\n */\n afterSeconds: z.number().int().positive().describe('Downsample after seconds'),\n\n /**\n * Resolution in seconds\n */\n resolution: z.number().int().positive().describe('Downsampled resolution'),\n })).optional(),\n }).optional(),\n\n /**\n * Cardinality limits\n */\n cardinalityLimits: z.object({\n /**\n * Maximum unique label combinations per metric\n */\n maxLabelCombinations: z.number().int().positive().optional().default(10000),\n\n /**\n * Action when limit exceeded\n */\n onLimitExceeded: z.enum(['drop', 'sample', 'alert']).optional().default('alert'),\n }).optional(),\n}).describe('Metrics configuration');\n\nexport type MetricsConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tracing Protocol - Distributed Tracing & Observability\n * \n * Comprehensive distributed tracing based on OpenTelemetry standards:\n * - Trace context propagation\n * - Span creation and management\n * - Sampling strategies\n * - Integration with tracing backends (Jaeger, Zipkin, etc.)\n * - W3C Trace Context standard compliance\n */\n\n/**\n * Trace State Schema\n * W3C Trace Context tracestate header\n */\nexport const TraceStateSchema = z.object({\n /**\n * Vendor-specific key-value pairs\n */\n entries: z.record(z.string(), z.string()).describe('Trace state entries'),\n}).describe('Trace state');\n\nexport type TraceState = z.infer;\n\n/**\n * Trace Flags Enum\n * W3C Trace Context trace flags\n */\nexport const TraceFlagsSchema = z.number().int().min(0).max(255).describe('Trace flags bitmap');\n\nexport type TraceFlags = z.infer;\n\n/**\n * Trace Context Schema\n * W3C Trace Context standard\n */\nexport const TraceContextSchema = z.object({\n /**\n * Trace ID (128-bit identifier, 32 hex chars)\n */\n traceId: z.string()\n .regex(/^[0-9a-f]{32}$/)\n .describe('Trace ID (32 hex chars)'),\n\n /**\n * Span ID (64-bit identifier, 16 hex chars)\n */\n spanId: z.string()\n .regex(/^[0-9a-f]{16}$/)\n .describe('Span ID (16 hex chars)'),\n\n /**\n * Trace flags (8-bit)\n */\n traceFlags: TraceFlagsSchema.optional().default(1),\n\n /**\n * Trace state (vendor-specific)\n */\n traceState: TraceStateSchema.optional(),\n\n /**\n * Parent span ID\n */\n parentSpanId: z.string()\n .regex(/^[0-9a-f]{16}$/)\n .optional()\n .describe('Parent span ID (16 hex chars)'),\n\n /**\n * Is sampled\n */\n sampled: z.boolean().optional().default(true),\n\n /**\n * Remote context (from incoming request)\n */\n remote: z.boolean().optional().default(false),\n}).describe('Trace context (W3C Trace Context)');\n\nexport type TraceContext = z.infer;\n\n/**\n * Span Kind Enum\n * OpenTelemetry span kinds\n */\nexport const SpanKind = z.enum([\n 'internal', // Internal operation\n 'server', // Server-side request handling\n 'client', // Client-side request\n 'producer', // Message producer\n 'consumer', // Message consumer\n]).describe('Span kind');\n\nexport type SpanKind = z.infer;\n\n/**\n * Span Status Enum\n * OpenTelemetry span status\n */\nexport const SpanStatus = z.enum([\n 'unset', // Default status\n 'ok', // Successful operation\n 'error', // Error occurred\n]).describe('Span status');\n\nexport type SpanStatus = z.infer;\n\n/**\n * Span Attribute Value Schema\n */\nexport const SpanAttributeValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.array(z.string()),\n z.array(z.number()),\n z.array(z.boolean()),\n]).describe('Span attribute value');\n\nexport type SpanAttributeValue = z.infer;\n\n/**\n * Span Attributes Schema\n * OpenTelemetry semantic conventions\n */\nexport const SpanAttributesSchema = z.record(z.string(), SpanAttributeValueSchema).describe('Span attributes');\n\nexport type SpanAttributes = z.infer;\n\n/**\n * Span Event Schema\n */\nexport const SpanEventSchema = z.object({\n /**\n * Event name\n */\n name: z.string().describe('Event name'),\n\n /**\n * Event timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /**\n * Event attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Event attributes'),\n}).describe('Span event');\n\nexport type SpanEvent = z.infer;\n\n/**\n * Span Link Schema\n * Links to other spans\n */\nexport const SpanLinkSchema = z.object({\n /**\n * Linked trace context\n */\n context: TraceContextSchema.describe('Linked trace context'),\n\n /**\n * Link attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Link attributes'),\n}).describe('Span link');\n\nexport type SpanLink = z.infer;\n\n/**\n * Span Schema\n * OpenTelemetry span representation\n */\nexport const SpanSchema = z.object({\n /**\n * Trace context\n */\n context: TraceContextSchema.describe('Trace context'),\n\n /**\n * Span name\n */\n name: z.string().describe('Span name'),\n\n /**\n * Span kind\n */\n kind: SpanKind.optional().default('internal'),\n\n /**\n * Start time (ISO 8601)\n */\n startTime: z.string().datetime().describe('Span start time'),\n\n /**\n * End time (ISO 8601)\n */\n endTime: z.string().datetime().optional().describe('Span end time'),\n\n /**\n * Duration in milliseconds\n */\n duration: z.number().nonnegative().optional().describe('Duration in milliseconds'),\n\n /**\n * Span status\n */\n status: z.object({\n code: SpanStatus.describe('Status code'),\n message: z.string().optional().describe('Status message'),\n }).optional(),\n\n /**\n * Span attributes\n */\n attributes: SpanAttributesSchema.optional().default({}),\n\n /**\n * Span events\n */\n events: z.array(SpanEventSchema).optional().default([]),\n\n /**\n * Span links\n */\n links: z.array(SpanLinkSchema).optional().default([]),\n\n /**\n * Resource attributes\n */\n resource: SpanAttributesSchema.optional().describe('Resource attributes'),\n\n /**\n * Instrumentation library\n */\n instrumentationLibrary: z.object({\n name: z.string().describe('Library name'),\n version: z.string().optional().describe('Library version'),\n }).optional(),\n}).describe('OpenTelemetry span');\n\nexport type Span = z.infer;\n\n/**\n * Sampling Decision Enum\n */\nexport const SamplingDecision = z.enum([\n 'drop', // Do not record or export\n 'record_only', // Record but do not export\n 'record_and_sample', // Record and export\n]).describe('Sampling decision');\n\nexport type SamplingDecision = z.infer;\n\n/**\n * Sampling Strategy Type Enum\n */\nexport const SamplingStrategyType = z.enum([\n 'always_on', // Always sample\n 'always_off', // Never sample\n 'trace_id_ratio', // Sample based on trace ID ratio\n 'rate_limiting', // Rate-limited sampling\n 'parent_based', // Respect parent span sampling decision\n 'probability', // Probability-based sampling\n 'composite', // Combine multiple strategies\n 'custom', // Custom sampling logic\n]).describe('Sampling strategy type');\n\nexport type SamplingStrategyType = z.infer;\n\n/**\n * Trace Sampling Configuration Schema\n */\nexport const TraceSamplingConfigSchema = z.object({\n /**\n * Sampling strategy type\n */\n type: SamplingStrategyType.describe('Sampling strategy'),\n\n /**\n * Sample ratio (0.0 to 1.0) for trace_id_ratio and probability strategies\n */\n ratio: z.number().min(0).max(1).optional().describe('Sample ratio (0-1)'),\n\n /**\n * Rate limit (traces per second) for rate_limiting strategy\n */\n rateLimit: z.number().positive().optional().describe('Traces per second'),\n\n /**\n * Parent-based configuration\n */\n parentBased: z.object({\n /**\n * Sampler to use when parent is sampled\n */\n whenParentSampled: SamplingStrategyType.optional().default('always_on'),\n\n /**\n * Sampler to use when parent is not sampled\n */\n whenParentNotSampled: SamplingStrategyType.optional().default('always_off'),\n\n /**\n * Sampler to use when there is no parent (root span)\n */\n root: SamplingStrategyType.optional().default('trace_id_ratio'),\n\n /**\n * Root sampler ratio\n */\n rootRatio: z.number().min(0).max(1).optional().default(0.1),\n }).optional(),\n\n /**\n * Composite sampling (multiple strategies)\n */\n composite: z.array(z.object({\n strategy: SamplingStrategyType.describe('Strategy type'),\n ratio: z.number().min(0).max(1).optional(),\n condition: z.record(z.string(), z.unknown()).optional().describe('Condition for this strategy'),\n })).optional(),\n\n /**\n * Sampling rules\n */\n rules: z.array(z.object({\n /**\n * Rule name\n */\n name: z.string().describe('Rule name'),\n\n /**\n * Match condition\n */\n match: z.object({\n /**\n * Service name pattern\n */\n service: z.string().optional(),\n\n /**\n * Span name pattern (regex)\n */\n spanName: z.string().optional(),\n\n /**\n * Attribute filters\n */\n attributes: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n\n /**\n * Sampling decision for matching spans\n */\n decision: SamplingDecision.describe('Sampling decision'),\n\n /**\n * Sample rate for this rule\n */\n rate: z.number().min(0).max(1).optional(),\n })).optional().default([]),\n\n /**\n * Custom sampler ID (for custom strategy)\n */\n customSamplerId: z.string().optional().describe('Custom sampler identifier'),\n}).describe('Trace sampling configuration');\n\nexport type TraceSamplingConfig = z.infer;\n\n/**\n * Trace Context Propagation Format Enum\n */\nexport const TracePropagationFormat = z.enum([\n 'w3c', // W3C Trace Context\n 'b3', // Zipkin B3 (single header)\n 'b3_multi', // Zipkin B3 (multi header)\n 'jaeger', // Jaeger propagation\n 'xray', // AWS X-Ray\n 'ottrace', // OpenTracing\n 'custom', // Custom format\n]).describe('Trace propagation format');\n\nexport type TracePropagationFormat = z.infer;\n\n/**\n * Trace Context Propagation Schema\n */\nexport const TraceContextPropagationSchema = z.object({\n /**\n * Propagation formats (in priority order)\n */\n formats: z.array(TracePropagationFormat).optional().default(['w3c']),\n\n /**\n * Extract context from incoming requests\n */\n extract: z.boolean().optional().default(true),\n\n /**\n * Inject context into outgoing requests\n */\n inject: z.boolean().optional().default(true),\n\n /**\n * Custom header mappings\n */\n headers: z.object({\n /**\n * Trace ID header name\n */\n traceId: z.string().optional(),\n\n /**\n * Span ID header name\n */\n spanId: z.string().optional(),\n\n /**\n * Trace flags header name\n */\n traceFlags: z.string().optional(),\n\n /**\n * Trace state header name\n */\n traceState: z.string().optional(),\n }).optional(),\n\n /**\n * Baggage propagation\n */\n baggage: z.object({\n /**\n * Enable baggage propagation\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Maximum baggage size in bytes\n */\n maxSize: z.number().int().positive().optional().default(8192),\n\n /**\n * Allowed baggage keys (whitelist)\n */\n allowedKeys: z.array(z.string()).optional(),\n }).optional(),\n}).describe('Trace context propagation');\n\nexport type TraceContextPropagation = z.infer;\n\n/**\n * OpenTelemetry Exporter Type Enum\n */\nexport const OtelExporterType = z.enum([\n 'otlp_http', // OTLP over HTTP\n 'otlp_grpc', // OTLP over gRPC\n 'jaeger', // Jaeger\n 'zipkin', // Zipkin\n 'console', // Console (for debugging)\n 'datadog', // Datadog\n 'honeycomb', // Honeycomb\n 'lightstep', // Lightstep\n 'newrelic', // New Relic\n 'custom', // Custom exporter\n]).describe('OpenTelemetry exporter type');\n\nexport type OtelExporterType = z.infer;\n\n/**\n * OpenTelemetry Compatibility Schema\n */\nexport const OpenTelemetryCompatibilitySchema = z.object({\n /**\n * OpenTelemetry SDK version\n */\n sdkVersion: z.string().optional().describe('OTel SDK version'),\n\n /**\n * Exporter configuration\n */\n exporter: z.object({\n /**\n * Exporter type\n */\n type: OtelExporterType.describe('Exporter type'),\n\n /**\n * Endpoint URL\n */\n endpoint: z.string().url().optional().describe('Exporter endpoint'),\n\n /**\n * Protocol version\n */\n protocol: z.string().optional().describe('Protocol version'),\n\n /**\n * Headers\n */\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n\n /**\n * Timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().default(10000),\n\n /**\n * Compression\n */\n compression: z.enum(['none', 'gzip']).optional().default('none'),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n /**\n * Maximum batch size\n */\n maxBatchSize: z.number().int().positive().optional().default(512),\n\n /**\n * Maximum queue size\n */\n maxQueueSize: z.number().int().positive().optional().default(2048),\n\n /**\n * Export timeout in milliseconds\n */\n exportTimeout: z.number().int().positive().optional().default(30000),\n\n /**\n * Scheduled delay in milliseconds\n */\n scheduledDelay: z.number().int().positive().optional().default(5000),\n }).optional(),\n }).describe('Exporter configuration'),\n\n /**\n * Resource attributes (service identification)\n */\n resource: z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Service name'),\n\n /**\n * Service version\n */\n serviceVersion: z.string().optional().describe('Service version'),\n\n /**\n * Service instance ID\n */\n serviceInstanceId: z.string().optional().describe('Service instance ID'),\n\n /**\n * Service namespace\n */\n serviceNamespace: z.string().optional().describe('Service namespace'),\n\n /**\n * Deployment environment\n */\n deploymentEnvironment: z.string().optional().describe('Deployment environment'),\n\n /**\n * Additional resource attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Additional resource attributes'),\n }).describe('Resource attributes'),\n\n /**\n * Instrumentation configuration\n */\n instrumentation: z.object({\n /**\n * Auto-instrumentation enabled\n */\n autoInstrumentation: z.boolean().optional().default(true),\n\n /**\n * Instrumentation libraries to enable\n */\n libraries: z.array(z.string()).optional().describe('Enabled libraries'),\n\n /**\n * Instrumentation libraries to disable\n */\n disabledLibraries: z.array(z.string()).optional().describe('Disabled libraries'),\n }).optional(),\n\n /**\n * Semantic conventions version\n */\n semanticConventionsVersion: z.string().optional().describe('Semantic conventions version'),\n}).describe('OpenTelemetry compatibility configuration');\n\nexport type OpenTelemetryCompatibility = z.infer;\n\n/**\n * Tracing Configuration Schema\n */\nexport const TracingConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable tracing\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Sampling configuration\n */\n sampling: TraceSamplingConfigSchema.optional().default({ type: 'always_on', rules: [] }),\n\n /**\n * Context propagation\n */\n propagation: TraceContextPropagationSchema.optional().default({ formats: ['w3c'], extract: true, inject: true }),\n\n /**\n * OpenTelemetry configuration\n */\n openTelemetry: OpenTelemetryCompatibilitySchema.optional(),\n\n /**\n * Span limits\n */\n spanLimits: z.object({\n /**\n * Maximum number of attributes per span\n */\n maxAttributes: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum number of events per span\n */\n maxEvents: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum number of links per span\n */\n maxLinks: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum attribute value length\n */\n maxAttributeValueLength: z.number().int().positive().optional().default(4096),\n }).optional(),\n\n /**\n * Trace ID generator\n */\n traceIdGenerator: z.enum(['random', 'uuid', 'custom']).optional().default('random'),\n\n /**\n * Custom trace ID generator ID\n */\n customTraceIdGeneratorId: z.string().optional().describe('Custom generator identifier'),\n\n /**\n * Performance configuration\n */\n performance: z.object({\n /**\n * Async span export\n */\n asyncExport: z.boolean().optional().default(true),\n\n /**\n * Background export interval in milliseconds\n */\n exportInterval: z.number().int().positive().optional().default(5000),\n }).optional(),\n}).describe('Tracing configuration');\n\nexport type TracingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Security Context Protocol\n *\n * Provides a central governance layer that correlates and unifies\n * the four independent security subsystems:\n * - **Audit** (audit.zod.ts): Event logging and suspicious activity detection\n * - **Encryption** (encryption.zod.ts): Field-level encryption and key management\n * - **Compliance** (compliance.zod.ts): Regulatory framework enforcement (GDPR/HIPAA/SOX/PCI-DSS)\n * - **Masking** (masking.zod.ts): PII data masking and tokenization\n *\n * This schema enforces cross-cutting security policies, ensuring compliance\n * frameworks drive encryption requirements, masking rules respect role-based\n * audit visibility, and all security operations are correlated in a single\n * governance context.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Shared data classification enum used across security subsystems.\n * Defines the canonical set of data sensitivity labels.\n */\nexport const DataClassificationSchema = z.enum([\n 'pii', 'phi', 'pci', 'financial', 'confidential', 'internal', 'public',\n]).describe('Data classification level');\n\nexport type DataClassification = z.infer;\n\n/**\n * Shared compliance framework enum used across compliance and security schemas.\n * Defines the canonical set of regulatory frameworks.\n */\nexport const ComplianceFrameworkSchema = z.enum([\n 'gdpr', 'hipaa', 'sox', 'pci_dss', 'ccpa', 'iso27001',\n]).describe('Compliance framework identifier');\n\nexport type ComplianceFramework = z.infer;\n\n/**\n * Compliance-driven audit requirement.\n * Maps specific compliance frameworks to the audit event types that MUST be captured.\n */\nexport const ComplianceAuditRequirementSchema = z.object({\n framework: ComplianceFrameworkSchema\n .describe('Compliance framework identifier'),\n requiredEvents: z.array(z.string())\n .describe('Audit event types required by this framework (e.g., \"data.delete\", \"auth.login\")'),\n retentionDays: z.number().min(1)\n .describe('Minimum audit log retention period required by this framework (in days)'),\n alertOnMissing: z.boolean().default(true)\n .describe('Raise alert if a required audit event is not being captured'),\n}).describe('Compliance framework audit event requirements');\n\nexport type ComplianceAuditRequirement = z.infer;\n\n/**\n * Compliance-driven encryption requirement.\n * Maps compliance frameworks to encryption mandates for specific data classifications.\n */\nexport const ComplianceEncryptionRequirementSchema = z.object({\n framework: ComplianceFrameworkSchema\n .describe('Compliance framework identifier'),\n dataClassifications: z.array(DataClassificationSchema)\n .describe('Data classifications that must be encrypted under this framework'),\n minimumAlgorithm: z.enum(['aes-256-gcm', 'aes-256-cbc', 'chacha20-poly1305']).default('aes-256-gcm')\n .describe('Minimum encryption algorithm strength required'),\n keyRotationMaxDays: z.number().min(1).default(90)\n .describe('Maximum key rotation interval required (in days)'),\n}).describe('Compliance framework encryption requirements');\n\nexport type ComplianceEncryptionRequirement = z.infer;\n\n/**\n * Masking visibility rule.\n * Controls which roles can view unmasked data with audit trail enforcement.\n */\nexport const MaskingVisibilityRuleSchema = z.object({\n dataClassification: DataClassificationSchema\n .describe('Data classification this rule applies to'),\n defaultMasked: z.boolean().default(true)\n .describe('Whether data is masked by default'),\n unmaskRoles: z.array(z.string()).optional()\n .describe('Roles allowed to view unmasked data'),\n auditUnmask: z.boolean().default(true)\n .describe('Log an audit event when data is unmasked'),\n requireApproval: z.boolean().default(false)\n .describe('Require explicit approval before unmasking'),\n approvalRoles: z.array(z.string()).optional()\n .describe('Roles that can approve unmasking requests'),\n}).describe('Masking visibility and audit rule per data classification');\n\nexport type MaskingVisibilityRule = z.infer;\n\n/**\n * Security Event Correlation Schema.\n * Defines how security events from different subsystems are correlated.\n */\nexport const SecurityEventCorrelationSchema = z.object({\n enabled: z.boolean().default(true)\n .describe('Enable cross-subsystem security event correlation'),\n correlationId: z.boolean().default(true)\n .describe('Inject a shared correlation ID into audit, encryption, and masking events'),\n linkAuthToAudit: z.boolean().default(true)\n .describe('Link authentication events to subsequent data operation audit trails'),\n linkEncryptionToAudit: z.boolean().default(true)\n .describe('Log encryption/decryption operations in the audit trail'),\n linkMaskingToAudit: z.boolean().default(true)\n .describe('Log masking/unmasking operations in the audit trail'),\n}).describe('Cross-subsystem security event correlation configuration');\n\nexport type SecurityEventCorrelation = z.infer;\n\n/**\n * Data Classification Policy Schema.\n * Assigns classification labels to fields/objects for unified security enforcement.\n */\nexport const DataClassificationPolicySchema = z.object({\n classification: DataClassificationSchema\n .describe('Data classification level'),\n requireEncryption: z.boolean().default(false)\n .describe('Encryption required for this classification'),\n requireMasking: z.boolean().default(false)\n .describe('Masking required for this classification'),\n requireAudit: z.boolean().default(false)\n .describe('Audit trail required for access to this classification'),\n retentionDays: z.number().optional()\n .describe('Data retention limit in days (for compliance)'),\n}).describe('Security policy for a specific data classification level');\n\nexport type DataClassificationPolicy = z.infer;\n\n/**\n * Security Context Configuration Schema\n *\n * Top-level unified security governance context that ties together\n * audit, encryption, compliance, and masking subsystems.\n */\nexport const SecurityContextConfigSchema = z.object({\n enabled: z.boolean().default(true)\n .describe('Enable unified security context governance'),\n\n complianceAuditRequirements: z.array(ComplianceAuditRequirementSchema).optional()\n .describe('Compliance-driven audit event requirements'),\n\n complianceEncryptionRequirements: z.array(ComplianceEncryptionRequirementSchema).optional()\n .describe('Compliance-driven encryption requirements by data classification'),\n\n maskingVisibility: z.array(MaskingVisibilityRuleSchema).optional()\n .describe('Masking visibility rules per data classification'),\n\n dataClassifications: z.array(DataClassificationPolicySchema).optional()\n .describe('Data classification policies for unified security enforcement'),\n\n eventCorrelation: SecurityEventCorrelationSchema.optional()\n .describe('Cross-subsystem security event correlation settings'),\n\n enforceOnWrite: z.boolean().default(true)\n .describe('Enforce encryption and masking requirements on data write operations'),\n\n enforceOnRead: z.boolean().default(true)\n .describe('Enforce masking and audit requirements on data read operations'),\n\n failOpen: z.boolean().default(false)\n .describe('When false (default), deny access if security context cannot be evaluated'),\n}).describe('Unified security context governance configuration');\n\nexport type SecurityContextConfig = z.infer;\nexport type SecurityContextConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Change Type Enum\n * \n * Classification of change requests based on risk and approval requirements.\n * Follows ITIL change management best practices.\n */\nexport const ChangeTypeSchema = z.enum([\n 'standard', // Pre-approved, low-risk changes\n 'normal', // Requires standard approval process\n 'emergency', // Fast-track approval for critical issues\n 'major', // Requires CAB (Change Advisory Board) approval\n]);\n\n/**\n * Change Priority Enum\n * \n * Priority level for change request processing.\n */\nexport const ChangePrioritySchema = z.enum([\n 'critical',\n 'high',\n 'medium',\n 'low',\n]);\n\n/**\n * Change Status Enum\n * \n * Current status of a change request in its lifecycle.\n */\nexport const ChangeStatusSchema = z.enum([\n 'draft',\n 'submitted',\n 'in-review',\n 'approved',\n 'scheduled',\n 'in-progress',\n 'completed',\n 'failed',\n 'rolled-back',\n 'cancelled',\n]);\n\n/**\n * Change Impact Schema\n * \n * Assessment of the impact and scope of a change request.\n * Used for risk evaluation and approval routing.\n * \n * @example\n * ```json\n * {\n * \"level\": \"high\",\n * \"affectedSystems\": [\"crm-api\", \"customer-portal\"],\n * \"affectedUsers\": 5000,\n * \"downtime\": {\n * \"required\": true,\n * \"durationMinutes\": 30\n * }\n * }\n * ```\n */\nexport const ChangeImpactSchema = z.object({\n /**\n * Overall impact level of the change\n */\n level: z.enum(['low', 'medium', 'high', 'critical']).describe('Impact level'),\n\n /**\n * List of systems affected by this change\n */\n affectedSystems: z.array(z.string()).describe('Affected systems'),\n\n /**\n * Estimated number of users affected\n */\n affectedUsers: z.number().optional().describe('Affected user count'),\n\n /**\n * Downtime requirements\n */\n downtime: z.object({\n /**\n * Whether downtime is required\n */\n required: z.boolean().describe('Downtime required'),\n\n /**\n * Duration of downtime in minutes\n */\n durationMinutes: z.number().optional().describe('Downtime duration'),\n }).optional().describe('Downtime information'),\n});\n\n/**\n * Rollback Plan Schema\n * \n * Detailed procedure for reverting changes if implementation fails.\n * Required for all non-standard changes.\n * \n * @example\n * ```json\n * {\n * \"description\": \"Revert database schema to previous version\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Stop application servers\",\n * \"estimatedMinutes\": 5\n * },\n * {\n * \"order\": 2,\n * \"description\": \"Restore database backup\",\n * \"estimatedMinutes\": 15\n * }\n * ],\n * \"testProcedure\": \"Verify application login and basic functionality\"\n * }\n * ```\n */\nexport const RollbackPlanSchema = z.object({\n /**\n * High-level description of the rollback approach\n */\n description: z.string().describe('Rollback description'),\n\n /**\n * Sequential steps to execute rollback\n */\n steps: z.array(z.object({\n /**\n * Step execution order\n */\n order: z.number().describe('Step order'),\n\n /**\n * Detailed description of this step\n */\n description: z.string().describe('Step description'),\n\n /**\n * Estimated time to complete this step\n */\n estimatedMinutes: z.number().describe('Estimated duration'),\n })).describe('Rollback steps'),\n\n /**\n * Testing procedure to verify successful rollback\n */\n testProcedure: z.string().optional().describe('Test procedure'),\n});\n\n/**\n * Change Request Schema\n * \n * Comprehensive change management protocol for IT governance.\n * Supports change requests, deployment tracking, and ITIL compliance.\n * \n * @example\n * ```json\n * {\n * \"id\": \"CHG-2024-001\",\n * \"title\": \"Upgrade CRM Database Schema\",\n * \"description\": \"Migrate customer database to new schema version 2.0\",\n * \"type\": \"normal\",\n * \"priority\": \"high\",\n * \"status\": \"approved\",\n * \"requestedBy\": \"user_123\",\n * \"requestedAt\": 1704067200000,\n * \"impact\": {\n * \"level\": \"high\",\n * \"affectedSystems\": [\"crm-api\", \"customer-portal\"],\n * \"affectedUsers\": 5000,\n * \"downtime\": {\n * \"required\": true,\n * \"durationMinutes\": 30\n * }\n * },\n * \"implementation\": {\n * \"description\": \"Execute database migration scripts\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Backup current database\",\n * \"estimatedMinutes\": 10\n * }\n * ],\n * \"testing\": \"Run integration test suite\"\n * },\n * \"rollbackPlan\": {\n * \"description\": \"Restore from backup\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Restore backup\",\n * \"estimatedMinutes\": 15\n * }\n * ]\n * },\n * \"schedule\": {\n * \"plannedStart\": 1704153600000,\n * \"plannedEnd\": 1704155400000\n * }\n * }\n * ```\n */\nexport const ChangeRequestSchema = z.object({\n /**\n * Unique change request identifier\n */\n id: z.string().describe('Change request ID'),\n\n /**\n * Short descriptive title of the change\n */\n title: z.string().describe('Change title'),\n\n /**\n * Detailed description of the change and its purpose\n */\n description: z.string().describe('Change description'),\n\n /**\n * Change classification type\n */\n type: ChangeTypeSchema.describe('Change type'),\n\n /**\n * Priority level for processing\n */\n priority: ChangePrioritySchema.describe('Change priority'),\n\n /**\n * Current status in the change lifecycle\n */\n status: ChangeStatusSchema.describe('Change status'),\n\n /**\n * User ID of the change requester\n */\n requestedBy: z.string().describe('Requester user ID'),\n\n /**\n * Timestamp when change was requested (Unix milliseconds)\n */\n requestedAt: z.number().describe('Request timestamp'),\n\n /**\n * Impact assessment of the change\n */\n impact: ChangeImpactSchema.describe('Impact assessment'),\n\n /**\n * Implementation plan and procedures\n */\n implementation: z.object({\n /**\n * High-level implementation description\n */\n description: z.string().describe('Implementation description'),\n\n /**\n * Sequential implementation steps\n */\n steps: z.array(z.object({\n /**\n * Step execution order\n */\n order: z.number().describe('Step order'),\n\n /**\n * Detailed description of this step\n */\n description: z.string().describe('Step description'),\n\n /**\n * Estimated time to complete this step\n */\n estimatedMinutes: z.number().describe('Estimated duration'),\n })).describe('Implementation steps'),\n\n /**\n * Testing procedures to verify successful implementation\n */\n testing: z.string().optional().describe('Testing procedure'),\n }).describe('Implementation plan'),\n\n /**\n * Rollback plan in case of failure\n */\n rollbackPlan: RollbackPlanSchema.describe('Rollback plan'),\n\n /**\n * Change schedule and timing\n */\n schedule: z.object({\n /**\n * Planned start time (Unix milliseconds)\n */\n plannedStart: z.number().describe('Planned start time'),\n\n /**\n * Planned end time (Unix milliseconds)\n */\n plannedEnd: z.number().describe('Planned end time'),\n\n /**\n * Actual start time (Unix milliseconds)\n */\n actualStart: z.number().optional().describe('Actual start time'),\n\n /**\n * Actual end time (Unix milliseconds)\n */\n actualEnd: z.number().optional().describe('Actual end time'),\n }).optional().describe('Schedule'),\n\n /**\n * Security impact assessment for the change (A.8.32)\n */\n securityImpact: z.object({\n /**\n * Whether a security impact assessment has been performed\n */\n assessed: z.boolean().describe('Whether security impact has been assessed'),\n\n /**\n * Security risk level of this change\n */\n riskLevel: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional()\n .describe('Security risk level'),\n\n /**\n * Data classifications affected by this change\n */\n affectedDataClassifications: z.array(DataClassificationSchema)\n .optional().describe('Affected data classifications'),\n\n /**\n * Whether the change requires security team approval\n */\n requiresSecurityApproval: z.boolean().default(false)\n .describe('Whether security team approval is required'),\n\n /**\n * Security reviewer user ID\n */\n reviewedBy: z.string().optional()\n .describe('Security reviewer user ID'),\n\n /**\n * Security review completion timestamp (Unix milliseconds)\n */\n reviewedAt: z.number().optional()\n .describe('Security review timestamp'),\n\n /**\n * Security review notes or conditions\n */\n reviewNotes: z.string().optional()\n .describe('Security review notes or conditions'),\n }).optional().describe('Security impact assessment per ISO 27001:2022 A.8.32'),\n\n /**\n * Approval workflow configuration\n */\n approval: z.object({\n /**\n * Whether approval is required for this change\n */\n required: z.boolean().describe('Approval required'),\n\n /**\n * List of approvers and their approval status\n */\n approvers: z.array(z.object({\n /**\n * Approver user ID\n */\n userId: z.string().describe('Approver user ID'),\n\n /**\n * Timestamp when approval was granted (Unix milliseconds)\n */\n approvedAt: z.number().optional().describe('Approval timestamp'),\n\n /**\n * Comments from the approver\n */\n comments: z.string().optional().describe('Approver comments'),\n })).describe('Approvers'),\n }).optional().describe('Approval workflow'),\n\n /**\n * Supporting documentation and files\n */\n attachments: z.array(z.object({\n /**\n * Attachment file name\n */\n name: z.string().describe('Attachment name'),\n\n /**\n * URL to download the attachment\n */\n url: z.string().url().describe('Attachment URL'),\n })).optional().describe('Attachments'),\n\n /**\n * Custom metadata key-value pairs for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n});\n\n// Type exports\nexport type ChangeRequest = z.infer;\nexport type ChangeType = z.infer;\nexport type ChangeStatus = z.infer;\nexport type ChangePriority = z.infer;\nexport type ChangeImpact = z.infer;\nexport type RollbackPlan = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # ObjectStack Validation Protocol\n * \n * This module defines the validation schema protocol for ObjectStack, providing a comprehensive\n * type-safe validation system similar to Salesforce's validation rules but with enhanced capabilities.\n * \n * ## Overview\n * \n * Validation rules are applied at the data layer to ensure data integrity and enforce business logic.\n * The system supports multiple validation types:\n * \n * 1. **Script Validation**: Formula-based validation using expressions\n * 2. **Uniqueness Validation**: Enforce unique constraints across fields\n * 3. **State Machine Validation**: Control allowed state transitions\n * 4. **Format Validation**: Validate field formats (email, URL, regex, etc.)\n * 5. **Cross-Field Validation**: Validate relationships between multiple fields\n * 6. **Async Validation**: Remote validation via API calls\n * 7. **Custom Validation**: User-defined validation functions\n * 8. **Conditional Validation**: Apply validations based on conditions\n * \n * ## Salesforce Comparison\n * \n * ObjectStack validation rules are inspired by Salesforce validation rules but enhanced:\n * - Salesforce: Formula-based validation with `Error Condition Formula`\n * - ObjectStack: Multiple validation types with composable rules\n * \n * Example Salesforce validation rule:\n * ```\n * Rule Name: Discount_Cannot_Exceed_40_Percent\n * Error Condition Formula: Discount_Percent__c > 0.40\n * Error Message: Discount cannot exceed 40%.\n * ```\n * \n * Equivalent ObjectStack rule:\n * ```typescript\n * {\n * type: 'script',\n * name: 'discount_cannot_exceed_40_percent',\n * condition: 'discount_percent > 0.40',\n * message: 'Discount cannot exceed 40%',\n * severity: 'error'\n * }\n * ```\n */\n\n/**\n * Base Validation Rule\n * \n * All validation rules extend from this base schema with common properties.\n * \n * ## Industry Standard Enhancements\n * - **Label/Description**: Essential for governance in large systems with thousands of rules.\n * - **Events**: granular control over validation timing (Context-aware validation).\n * - **Tags**: categorization for reporting and management.\n */\nconst BaseValidationSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label for the rule listing'),\n description: z.string().optional().describe('Administrative notes explaining the business reason'),\n \n // Execution Control\n active: z.boolean().default(true),\n events: z.array(z.enum(['insert', 'update', 'delete'])).default(['insert', 'update']).describe('Validation contexts'),\n priority: z.number().int().min(0).max(9999).default(100).describe('Execution priority (lower runs first, default: 100)'),\n \n // Classification\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g., \"compliance\", \"billing\")'),\n \n // Feedback\n severity: z.enum(['error', 'warning', 'info']).default('error'),\n message: z.string().describe('Error message to display to the user'),\n});\n\n/**\n * 1. Script/Expression Validation\n * Generic formula-based validation.\n */\nexport const ScriptValidationSchema = BaseValidationSchema.extend({\n type: z.literal('script'),\n condition: z.string().describe('Formula expression. If TRUE, validation fails. (e.g. amount < 0)'),\n});\n\n/**\n * 2. Uniqueness Validation\n * specialized optimized check for unique constraints.\n */\nexport const UniquenessValidationSchema = BaseValidationSchema.extend({\n type: z.literal('unique'),\n fields: z.array(z.string()).describe('Fields that must be combined unique'),\n scope: z.string().optional().describe('Formula condition for scope (e.g. active = true)'),\n caseSensitive: z.boolean().default(true),\n});\n\n/**\n * 3. State Machine Validation\n * State transition logic.\n */\nexport const StateMachineValidationSchema = BaseValidationSchema.extend({\n type: z.literal('state_machine'),\n field: z.string().describe('State field (e.g. status)'),\n transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'),\n});\n\n/**\n * 4. Value Format Validation\n * Regex or specialized formats.\n */\nexport const FormatValidationSchema = BaseValidationSchema.extend({\n type: z.literal('format'),\n field: z.string(),\n regex: z.string().optional(),\n format: z.enum(['email', 'url', 'phone', 'json']).optional(),\n});\n\n/**\n * 5. Cross-Field Validation\n * Validates relationships between multiple fields.\n * \n * ## Use Cases\n * - Date range validations (end_date > start_date)\n * - Amount comparisons (discount < total)\n * - Complex business rules involving multiple fields\n * \n * ## Salesforce Examples\n * \n * ### Example 1: Close Date Must Be In Current or Future Month\n * **Salesforce Formula:**\n * ```\n * MONTH(CloseDate) < MONTH(TODAY()) ||\n * YEAR(CloseDate) < YEAR(TODAY())\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'close_date_future',\n * condition: 'MONTH(close_date) >= MONTH(TODAY()) AND YEAR(close_date) >= YEAR(TODAY())',\n * fields: ['close_date'],\n * message: 'Close Date must be in the current or a future month'\n * }\n * ```\n * \n * ### Example 2: Discount Validation\n * **Salesforce Formula:**\n * ```\n * Discount__c > (Amount__c * 0.40)\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'discount_limit',\n * condition: 'discount > (amount * 0.40)',\n * fields: ['discount', 'amount'],\n * message: 'Discount cannot exceed 40% of the amount'\n * }\n * ```\n * \n * ### Example 3: Opportunity Must Have Products\n * **Salesforce Formula:**\n * ```\n * ISBLANK(Products__c) && ISPICKVAL(StageName, \"Closed Won\")\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'products_required_for_won',\n * condition: 'products = null AND stage = \"closed_won\"',\n * fields: ['products', 'stage'],\n * message: 'Opportunity must have products to be marked as Closed Won'\n * }\n * ```\n */\nexport const CrossFieldValidationSchema = BaseValidationSchema.extend({\n type: z.literal('cross_field'),\n condition: z.string().describe('Formula expression comparing fields (e.g. \"end_date > start_date\")'),\n fields: z.array(z.string()).describe('Fields involved in the validation'),\n});\n\n/**\n * 6. JSON Structure Validation\n * Validates JSON fields against a JSON Schema.\n * \n * ## Use Cases\n * - Validating configuration objects stored in JSON fields\n * - Enforcing API payload structures\n * - Complex nested data validation\n */\nexport const JSONValidationSchema = BaseValidationSchema.extend({\n type: z.literal('json_schema'),\n field: z.string().describe('JSON field to validate'),\n schema: z.record(z.string(), z.unknown()).describe('JSON Schema object definition'),\n});\n\n/**\n * 7. Async Validation\n * Remote validation via API call or database query.\n * \n * ## Use Cases\n * \n * ### 1. Email Uniqueness Check\n * Check if an email address is already registered in the system.\n * ```typescript\n * {\n * type: 'async',\n * name: 'unique_email',\n * field: 'email',\n * validatorUrl: '/api/users/check-email',\n * message: 'This email address is already registered',\n * debounce: 500, // Wait 500ms after user stops typing\n * timeout: 3000\n * }\n * ```\n * \n * ### 2. Username Availability\n * Verify username is available before form submission.\n * ```typescript\n * {\n * type: 'async',\n * name: 'username_available',\n * field: 'username',\n * validatorUrl: '/api/users/check-username',\n * message: 'This username is already taken',\n * debounce: 300,\n * timeout: 2000\n * }\n * ```\n * \n * ### 3. Tax ID Validation\n * Validate tax ID with government API (e.g., IRS, HMRC).\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_tax_id',\n * field: 'tax_id',\n * validatorFunction: 'validateTaxIdWithIRS',\n * message: 'Invalid Tax ID number',\n * timeout: 10000, // Government APIs may be slow\n * params: { country: 'US', format: 'EIN' }\n * }\n * ```\n * \n * ### 4. Credit Card Validation\n * Verify credit card with payment gateway without charging.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_card',\n * field: 'card_number',\n * validatorUrl: 'https://api.stripe.com/v1/tokens/validate',\n * message: 'Invalid credit card number',\n * timeout: 5000,\n * params: { \n * mode: 'validate_only',\n * checkFunds: false \n * }\n * }\n * ```\n * \n * ### 5. Address Validation\n * Validate and standardize addresses using geocoding services.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_address',\n * field: 'street_address',\n * validatorFunction: 'validateAddressWithGoogleMaps',\n * message: 'Unable to verify address',\n * timeout: 4000,\n * params: {\n * includeFields: ['city', 'state', 'zip'],\n * strictMode: true,\n * country: 'US'\n * }\n * }\n * ```\n * \n * ### 6. Domain Name Availability\n * Check if domain name is available for registration.\n * ```typescript\n * {\n * type: 'async',\n * name: 'domain_available',\n * field: 'domain_name',\n * validatorUrl: '/api/domains/check-availability',\n * message: 'This domain is already taken or reserved',\n * debounce: 500,\n * timeout: 2000\n * }\n * ```\n * \n * ### 7. Coupon Code Validation\n * Verify coupon code is valid and not expired.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_coupon',\n * field: 'coupon_code',\n * validatorUrl: '/api/coupons/validate',\n * message: 'Invalid or expired coupon code',\n * timeout: 2000,\n * params: {\n * checkExpiration: true,\n * checkUsageLimit: true,\n * userId: '{{current_user_id}}'\n * }\n * }\n * ```\n */\nexport const AsyncValidationSchema = BaseValidationSchema.extend({\n type: z.literal('async'),\n field: z.string().describe('Field to validate'),\n validatorUrl: z.string().optional().describe('External API endpoint for validation'),\n method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method for external call'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for the request'),\n validatorFunction: z.string().optional().describe('Reference to custom validator function'),\n timeout: z.number().optional().default(5000).describe('Timeout in milliseconds'),\n debounce: z.number().optional().describe('Debounce delay in milliseconds'),\n params: z.record(z.string(), z.unknown()).optional().describe('Additional parameters to pass to validator'),\n});\n\n/**\n * 8. Custom Validator Function\n * User-defined validation logic with code reference.\n */\nexport const CustomValidatorSchema = BaseValidationSchema.extend({\n type: z.literal('custom'),\n handler: z.string().describe('Name of the custom validation function registered in the system'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the custom handler'),\n});\n\n/**\n * 9. Master Validation Rule Schema\n */\n/** Base type for validation rules - used for z.lazy() recursive type annotation */\nexport interface BaseValidationRuleShape {\n type: string;\n name: string;\n message: string;\n label?: string;\n description?: string;\n active?: boolean;\n events?: ('insert' | 'update' | 'delete')[];\n priority?: number;\n tags?: string[];\n severity?: 'error' | 'warning' | 'info';\n [key: string]: unknown;\n}\n\nexport const ValidationRuleSchema: z.ZodType = z.lazy(() =>\n z.discriminatedUnion('type', [\n ScriptValidationSchema,\n UniquenessValidationSchema,\n StateMachineValidationSchema,\n FormatValidationSchema,\n CrossFieldValidationSchema,\n JSONValidationSchema,\n AsyncValidationSchema,\n CustomValidatorSchema,\n ConditionalValidationSchema,\n ])\n);\n\n/**\n * 8. Conditional Validation\n * Validation that only applies when a condition is met.\n * \n * ## Overview\n * Conditional validations follow the pattern: \"Validate X only if Y is true\"\n * This allows for context-aware validation rules that adapt to different scenarios.\n * \n * ## Use Cases\n * \n * ### 1. Validate Based on Record Type\n * Apply different validation rules based on the type of record.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_approval_required',\n * when: 'account_type = \"enterprise\"',\n * message: 'Enterprise validation',\n * then: {\n * type: 'script',\n * name: 'require_approval',\n * message: 'Enterprise accounts require manager approval',\n * condition: 'approval_status = null'\n * }\n * }\n * ```\n * \n * ### 2. Conditional Field Requirements\n * Require certain fields only when specific conditions are met.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'shipping_address_when_required',\n * when: 'requires_shipping = true',\n * message: 'Shipping validation',\n * then: {\n * type: 'script',\n * name: 'shipping_address_required',\n * message: 'Shipping address is required for physical products',\n * condition: 'shipping_address = null OR shipping_address = \"\"'\n * }\n * }\n * ```\n * \n * ### 3. Amount-Based Validation\n * Apply different rules based on transaction amount.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'high_value_approval',\n * when: 'order_total > 10000',\n * message: 'High value order validation',\n * then: {\n * type: 'script',\n * name: 'manager_approval_required',\n * message: 'Orders over $10,000 require manager approval',\n * condition: 'manager_approval_id = null'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'standard_validation',\n * message: 'Payment method is required',\n * condition: 'payment_method = null'\n * }\n * }\n * ```\n * \n * ### 4. Regional Compliance\n * Apply region-specific validation rules.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'regional_compliance',\n * when: 'region = \"EU\"',\n * message: 'EU compliance validation',\n * then: {\n * type: 'script',\n * name: 'gdpr_consent',\n * message: 'GDPR consent is required for EU customers',\n * condition: 'gdpr_consent_given = false'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'tos_acceptance',\n * message: 'Terms of Service acceptance required',\n * condition: 'tos_accepted = false'\n * }\n * }\n * ```\n * \n * ### 5. Nested Conditional Validation\n * Create complex validation logic with nested conditions.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'country_state_validation',\n * when: 'country = \"US\"',\n * message: 'US-specific validation',\n * then: {\n * type: 'conditional',\n * name: 'california_validation',\n * when: 'state = \"CA\"',\n * message: 'California-specific validation',\n * then: {\n * type: 'script',\n * name: 'ca_tax_id_required',\n * message: 'California requires a valid tax ID',\n * condition: 'tax_id = null OR NOT(REGEX(tax_id, \"^\\\\d{2}-\\\\d{7}$\"))'\n * }\n * }\n * }\n * ```\n * \n * ### 6. Tax Validation for Taxable Items\n * Only validate tax fields when the item is taxable.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'tax_field_validation',\n * when: 'is_taxable = true',\n * message: 'Tax validation',\n * then: {\n * type: 'script',\n * name: 'tax_code_required',\n * message: 'Tax code is required for taxable items',\n * condition: 'tax_code = null OR tax_code = \"\"'\n * }\n * }\n * ```\n * \n * ### 7. Role-Based Validation\n * Apply validation based on user role.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'role_based_approval_limit',\n * when: 'user_role = \"manager\"',\n * message: 'Manager approval limits',\n * then: {\n * type: 'script',\n * name: 'manager_limit',\n * message: 'Managers can approve up to $50,000',\n * condition: 'approval_amount > 50000'\n * }\n * }\n * ```\n * \n * ## Salesforce Pattern Comparison\n * \n * Salesforce doesn't have explicit \"conditional validation\" rules but achieves similar\n * behavior using formula logic. ObjectStack makes this pattern explicit and composable.\n * \n * **Salesforce Approach:**\n * ```\n * IF(\n * ISPICKVAL(Type, \"Enterprise\"),\n * AND(Amount > 100000, ISBLANK(Approval__c)),\n * FALSE\n * )\n * ```\n * \n * **ObjectStack Approach:**\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_high_value',\n * when: 'type = \"enterprise\"',\n * then: {\n * type: 'cross_field',\n * name: 'amount_approval',\n * condition: 'amount > 100000 AND approval = null',\n * fields: ['amount', 'approval']\n * }\n * }\n * ```\n */\nexport const ConditionalValidationSchema = BaseValidationSchema.extend({\n type: z.literal('conditional'),\n when: z.string().describe('Condition formula (e.g. \"type = \\'enterprise\\'\")'),\n then: ValidationRuleSchema.describe('Validation rule to apply when condition is true'),\n otherwise: ValidationRuleSchema.optional().describe('Validation rule to apply when condition is false'),\n});\n\nexport type ValidationRule = z.infer;\nexport type ScriptValidation = z.infer;\nexport type UniquenessValidation = z.infer;\nexport type StateMachineValidation = z.infer;\nexport type FormatValidation = z.infer;\nexport type CrossFieldValidation = z.infer;\nexport type JSONValidation = z.infer;\nexport type AsyncValidation = z.infer;\nexport type CustomValidation = z.infer;\nexport type ConditionalValidation = z.infer;", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * XState-inspired State Machine Protocol\n * Used to define strict business logic constraints and lifecycle management.\n * Prevent AI \"hallucinations\" by enforcing valid valid transitions.\n */\n\n// --- Primitives ---\n\n/**\n * References a named action (side effect)\n * Can be a script, a webhook, or a field update.\n */\nexport const ActionRefSchema = z.union([\n z.string().describe('Action Name'),\n z.object({\n type: z.string(), // e.g., 'xstate.assign', 'log', 'email'\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n/**\n * References a named condition (guard)\n * Must evaluate to true for the transition to occur.\n */\nexport const GuardRefSchema = z.union([\n z.string().describe('Guard Name (e.g., \"isManager\", \"amountGT1000\")'),\n z.object({\n type: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n// --- Core Structure ---\n\n/**\n * State Transition Definition\n * \"When EVENT happens, if GUARD is true, go to TARGET and run ACTIONS\"\n */\nexport const TransitionSchema = z.object({\n target: z.string().optional().describe('Target State ID'),\n cond: GuardRefSchema.optional().describe('Condition (Guard) required to take this path'),\n actions: z.array(ActionRefSchema).optional().describe('Actions to execute during transition'),\n description: z.string().optional().describe('Human readable description of this rule'),\n});\n\n/**\n * Event Definition (Signals)\n */\nexport const EventSchema = z.object({\n type: z.string().describe('Event Type (e.g. \"APPROVE\", \"REJECT\", \"Submit\")'),\n // Payload validation schema could go here if we want deep validation\n schema: z.record(z.string(), z.unknown()).optional().describe('Expected event payload structure'),\n});\n\nexport type ActionRef = z.infer;\nexport type Transition = z.infer;\n\nexport type StateNodeConfig = {\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n entry?: ActionRef[];\n exit?: ActionRef[];\n on?: Record;\n always?: Transition[];\n initial?: string;\n states?: Record;\n meta?: {\n label?: string;\n description?: string;\n color?: string;\n aiInstructions?: string;\n };\n};\n\n/**\n * State Node Definition\n */\nexport const StateNodeSchema: z.ZodType = z.lazy(() => z.object({\n /** Type of state */\n type: z.enum(['atomic', 'compound', 'parallel', 'final', 'history']).default('atomic'),\n \n /** Entry/Exit Actions */\n entry: z.array(ActionRefSchema).optional().describe('Actions to run when entering this state'),\n exit: z.array(ActionRefSchema).optional().describe('Actions to run when leaving this state'),\n \n /** Transitions (Events) */\n on: z.record(z.string(), z.union([\n z.string(), // Shorthand target\n TransitionSchema, \n z.array(TransitionSchema)\n ])).optional().describe('Map of Event Type -> Transition Definition'),\n \n /** Always Transitions (Eventless) */\n always: z.array(TransitionSchema).optional(),\n\n /** Nesting (Hierarchical States) */\n initial: z.string().optional().describe('Initial child state (if compound)'),\n states: z.record(z.string(), StateNodeSchema).optional(),\n \n /** Metadata for UI/AI */\n meta: z.object({\n label: z.string().optional(),\n description: z.string().optional(),\n color: z.string().optional(), // For UI diagrams\n // Instructions for AI Agent when in this state\n aiInstructions: z.string().optional().describe('Specific instructions for AI when in this state'),\n }).optional(),\n}));\n\n/**\n * Top-Level State Machine Definition\n */\nexport const StateMachineSchema = z.object({\n id: SnakeCaseIdentifierSchema.describe('Unique Machine ID'),\n description: z.string().optional(),\n \n /** Context (Memory) Schema */\n contextSchema: z.record(z.string(), z.unknown()).optional().describe('Zod Schema for the machine context/memory'),\n \n /** Initial State */\n initial: z.string().describe('Initial State ID'),\n \n /** State Definitions */\n states: z.record(z.string(), StateNodeSchema).describe('State Nodes'),\n \n /** Global Listeners */\n on: z.record(z.string(), z.union([z.string(), TransitionSchema, z.array(TransitionSchema)])).optional(),\n});\n\nexport type StateMachineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from './field.zod';\nimport { ValidationRuleSchema } from './validation.zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\nimport { ActionSchema } from '../ui/action.zod';\n\n/**\n * API Operations Enum\n */\nexport const ApiMethod = z.enum([\n 'get', 'list', // Read\n 'create', 'update', 'delete', // Write\n 'upsert', // Idempotent Write\n 'bulk', // Batch operations\n 'aggregate', // Analytics (count, sum)\n 'history', // Audit access\n 'search', // Search access\n 'restore', 'purge', // Trash management\n 'import', 'export', // Data portability\n]);\nexport type ApiMethod = z.infer;\n\n/**\n * Capability Flags\n * Defines what system features are enabled for this object.\n * \n * Optimized based on industry standards (Salesforce, ServiceNow):\n * - Added `activities` (Tasks/Events)\n * - Added `mru` (Recent Items)\n * - Added `feeds` (Social/Chatter)\n * - Grouped API permissions\n * \n * @example\n * {\n * trackHistory: true,\n * searchable: true,\n * apiEnabled: true,\n * files: true\n * }\n */\nexport const ObjectCapabilities = z.object({\n /** Enable history tracking (Audit Trail) */\n trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),\n \n /** Enable global search indexing */\n searchable: z.boolean().default(true).describe('Index records for global search'),\n \n /** Enable REST/GraphQL API access */\n apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),\n\n /** \n * API Supported Operations\n * Granular control over API exposure.\n */\n apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),\n \n /** Enable standard attachments/files engine */\n files: z.boolean().default(false).describe('Enable file attachments and document management'),\n \n /** Enable social collaboration (Comments, Mentions, Feeds) */\n feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),\n \n /** Enable standard Activity suite (Tasks, Calendars, Events) */\n activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),\n \n /** Enable Recycle Bin / Soft Delete */\n trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),\n\n /** Enable \"Recently Viewed\" tracking */\n mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),\n \n /** Allow cloning records */\n clone: z.boolean().default(true).describe('Allow record deep cloning'),\n});\n\n/**\n * Schema for database indexes.\n * Enhanced with additional index types and configuration options\n * \n * @example\n * {\n * name: \"idx_account_name\",\n * fields: [\"name\"],\n * type: \"btree\",\n * unique: true\n * }\n */\nexport const IndexSchema = z.object({\n name: z.string().optional().describe('Index name (auto-generated if not provided)'),\n fields: z.array(z.string()).describe('Fields included in the index'),\n type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),\n unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),\n partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),\n});\n\n/**\n * Search Configuration\n * Defines how this object behaves in search results.\n * \n * @example\n * {\n * fields: [\"name\", \"email\", \"phone\"],\n * displayFields: [\"name\", \"title\"],\n * filters: [\"status = 'active'\"]\n * }\n */\nexport const SearchConfigSchema = z.object({\n fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),\n displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),\n filters: z.array(z.string()).optional().describe('Default filters for search results'),\n});\n\n/**\n * Multi-Tenancy Configuration Schema\n * Configures tenant isolation strategy for SaaS applications\n * \n * @example Shared database with tenant_id isolation\n * {\n * enabled: true,\n * strategy: 'shared',\n * tenantField: 'tenant_id',\n * crossTenantAccess: false\n * }\n */\nexport const TenancyConfigSchema = z.object({\n enabled: z.boolean().describe('Enable multi-tenancy for this object'),\n strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),\n tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),\n crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),\n});\n\n/**\n * Soft Delete Configuration Schema\n * Implements recycle bin / trash functionality\n * \n * @example Standard soft delete with cascade\n * {\n * enabled: true,\n * field: 'deleted_at',\n * cascadeDelete: true\n * }\n */\nexport const SoftDeleteConfigSchema = z.object({\n enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),\n field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),\n cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),\n});\n\n/**\n * Versioning Configuration Schema\n * Implements record versioning and history tracking\n * \n * @example Snapshot versioning with 90-day retention\n * {\n * enabled: true,\n * strategy: 'snapshot',\n * retentionDays: 90,\n * versionField: 'version'\n * }\n */\nexport const VersioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable record versioning'),\n strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),\n retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),\n versionField: z.string().default('version').describe('Field name for version number/timestamp'),\n});\n\n/**\n * Partitioning Strategy Schema\n * Configures table partitioning for performance at scale\n * \n * @example Range partitioning by date (monthly)\n * {\n * enabled: true,\n * strategy: 'range',\n * key: 'created_at',\n * interval: '1 month'\n * }\n */\nexport const PartitioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable table partitioning'),\n strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),\n key: z.string().describe('Field name to partition by'),\n interval: z.string().optional().describe('Partition interval for range strategy (e.g., \"1 month\", \"1 year\")'),\n}).refine((data) => {\n // If strategy is 'range', interval must be provided\n if (data.strategy === 'range' && !data.interval) {\n return false;\n }\n return true;\n}, {\n message: 'interval is required when strategy is \"range\"',\n});\n\n/**\n * Change Data Capture (CDC) Configuration Schema\n * Enables real-time data streaming to external systems\n * \n * @example Stream all changes to Kafka\n * {\n * enabled: true,\n * events: ['insert', 'update', 'delete'],\n * destination: 'kafka://events.objectstack'\n * }\n */\nexport const CDCConfigSchema = z.object({\n enabled: z.boolean().describe('Enable Change Data Capture'),\n events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),\n destination: z.string().describe('Destination endpoint (e.g., \"kafka://topic\", \"webhook://url\")'),\n});\n\n/**\n * Base Object Schema Definition\n * \n * The Blueprint of a Business Object.\n * Represents a table, a collection, or a virtual entity.\n * \n * @example\n * ```yaml\n * name: project_task\n * label: Project Task\n * icon: task\n * fields:\n * project:\n * type: lookup\n * reference: project\n * status:\n * type: select\n * options: [todo, in_progress, done]\n * enable:\n * trackHistory: true\n * files: true\n * ```\n */\nconst ObjectSchemaBase = z.object({\n /** \n * Identity & Metadata \n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),\n label: z.string().optional().describe('Human readable singular label (e.g. \"Account\")'),\n pluralLabel: z.string().optional().describe('Human readable plural label (e.g. \"Accounts\")'),\n description: z.string().optional().describe('Developer documentation / description'),\n icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),\n \n /**\n * Namespace & Domain Classification\n * \n * Groups objects into logical domains for routing, permissions, and discovery.\n * System objects use `'sys'`; business packages use their own namespace.\n * \n * When set, `tableName` is auto-derived as `{namespace}_{name}` by\n * `ObjectSchema.create()` unless an explicit `tableName` is provided.\n * \n * Namespace must be a single lowercase word (no underscores or hyphens)\n * to ensure clean auto-derivation of `{namespace}_{name}` table names.\n * \n * @example namespace: 'sys' → tableName defaults to 'sys_user'\n * @example namespace: 'crm' → tableName defaults to 'crm_account'\n */\n namespace: z.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace — single lowercase word (e.g. \"sys\", \"crm\"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'),\n\n /**\n * Taxonomy & Organization\n */\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g. \"sales\", \"system\", \"reference\")'),\n active: z.boolean().optional().default(true).describe('Is the object active and usable'),\n isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),\n abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),\n\n /** \n * Storage & Virtualization \n */\n datasource: z.string().optional().default('default').describe('Target Datasource ID. \"default\" is the primary DB.'),\n tableName: z.string().optional().describe('Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set.'),\n \n /** \n * Data Model \n */\n fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {\n message: 'Field names must be lowercase snake_case (e.g., \"first_name\", \"company\", \"annual_revenue\")',\n }), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),\n indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),\n \n /**\n * Advanced Data Management\n */\n \n // Multi-tenancy configuration\n tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),\n \n // Soft delete configuration\n softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),\n \n // Versioning configuration\n versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),\n \n // Partitioning strategy\n partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),\n \n // Change Data Capture\n cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),\n \n /**\n * Logic & Validation (Co-located)\n * Best Practice: Define rules close to data.\n */\n validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),\n \n /**\n * State Machine(s)\n * Named record of state machines, where each key is a unique machine identifier.\n * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).\n * \n * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }\n */\n stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),\n\n /** \n * Display & UI Hints (Data-Layer)\n */\n displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., \"name\", \"title\"). Defaults to \"name\" if present.'),\n recordName: z.object({\n type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),\n displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., \"CASE-{0000}\", \"INV-{YYYY}-{0000}\")'),\n startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),\n }).optional().describe('Record name generation configuration (Salesforce pattern)'),\n titleFormat: z.string().optional().describe('Title expression (e.g. \"{name} - {code}\"). Overrides displayNameField.'),\n compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),\n \n /** \n * Search Engine Config \n */\n search: SearchConfigSchema.optional().describe('Search engine configuration'),\n \n /** \n * System Capabilities \n */\n enable: ObjectCapabilities.optional().describe('Enabled system features modules'),\n\n /** Record Types */\n recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),\n\n /** Sharing Model */\n sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),\n\n /** Key Prefix */\n keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., \"001\" for Account)'),\n\n /**\n * Object Actions\n * \n * Actions associated with this object. Populated automatically by `defineStack()`\n * when top-level actions specify `objectName` matching this object.\n * Can also be defined directly on the object.\n * \n * Aligns with Salesforce/ServiceNow patterns where actions are part of the\n * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)\n * include the action list without requiring downstream merge.\n */\n actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),\n});\n\n/**\n * Converts a snake_case name to a human-readable Title Case label.\n * @example snakeCaseToLabel('project_task') → 'Project Task'\n */\nfunction snakeCaseToLabel(name: string): string {\n return name\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n}\n\n/**\n * Enhanced ObjectSchema with Factory\n */\nexport const ObjectSchema = Object.assign(ObjectSchemaBase, {\n /**\n * Type-safe factory for creating business object definitions.\n * \n * Enhancements over raw schema:\n * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).\n * - **Validation**: Runs Zod `.parse()` to validate the config at creation time.\n * \n * @example\n * ```ts\n * const Task = ObjectSchema.create({\n * name: 'project_task',\n * // label auto-generated as 'Project Task'\n * fields: {\n * subject: { type: 'text', label: 'Subject', required: true },\n * },\n * });\n * ```\n */\n create: >(config: T): Omit & Pick => {\n const withDefaults = {\n ...config,\n label: config.label ?? snakeCaseToLabel(config.name),\n // Auto-derive tableName as {namespace}_{name} when namespace is set\n tableName: config.tableName ?? (config.namespace ? `${config.namespace}_${config.name}` : undefined),\n };\n return ObjectSchemaBase.parse(withDefaults) as Omit & Pick;\n },\n});\n\nexport type ServiceObject = z.infer;\nexport type ServiceObjectInput = z.input;\nexport type ObjectCapabilities = z.infer;\nexport type ObjectIndex = z.infer;\nexport type TenancyConfig = z.infer;\nexport type SoftDeleteConfig = z.infer;\nexport type VersioningConfig = z.infer;\nexport type PartitioningConfig = z.infer;\nexport type CDCConfig = z.infer;\n\n// =================================================================\n// Object Ownership Model\n// =================================================================\n\n/**\n * How a package relates to an object it references.\n * \n * - `own`: This package is the original author/owner of the object.\n * Only one package may own a given object name. The owner defines\n * the base schema (table name, primary key, core fields).\n * \n * - `extend`: This package adds fields, views, or actions to an\n * existing object owned by another package. Multiple packages\n * may extend the same object. Extensions are merged at boot time.\n * \n * Follows Salesforce/ServiceNow patterns:\n * object name = database table name, globally unique, no namespace prefix.\n */\nexport const ObjectOwnershipEnum = z.enum(['own', 'extend']);\nexport type ObjectOwnership = z.infer;\n\n/**\n * Object Extension Entry — used in `objectExtensions` array.\n * Declares fields/config to merge into an existing object owned by another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact', // target object FQN\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\nexport const ObjectExtensionSchema = z.object({\n /** The target object name (FQN) to extend */\n extend: z.string().describe('Target object name (FQN) to extend'),\n \n /** Fields to merge into the target object (additive) */\n fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),\n \n /** Override label */\n label: z.string().optional().describe('Override label for the extended object'),\n \n /** Override plural label */\n pluralLabel: z.string().optional().describe('Override plural label for the extended object'),\n \n /** Override description */\n description: z.string().optional().describe('Override description for the extended object'),\n \n /** Additional validation rules to add */\n validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),\n \n /** Additional indexes to add */\n indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),\n \n /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */\n priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),\n});\n\nexport type ObjectExtension = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from '../data/field.zod';\nimport { ObjectSchema } from '../data/object.zod';\n\n// --- Atomic Operations ---\n\nexport const AddFieldOperation = z.object({\n type: z.literal('add_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to add'),\n field: FieldSchema.describe('Full field definition to add')\n}).describe('Add a new field to an existing object');\n\nexport const ModifyFieldOperation = z.object({\n type: z.literal('modify_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to modify'),\n changes: z.record(z.string(), z.unknown()).describe('Partial field definition updates')\n}).describe('Modify properties of an existing field');\n\nexport const RemoveFieldOperation = z.object({\n type: z.literal('remove_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to remove')\n}).describe('Remove a field from an existing object');\n\nexport const CreateObjectOperation = z.object({\n type: z.literal('create_object'),\n object: ObjectSchema.describe('Full object definition to create')\n}).describe('Create a new object');\n\nexport const RenameObjectOperation = z.object({\n type: z.literal('rename_object'),\n oldName: z.string().describe('Current object name'),\n newName: z.string().describe('New object name')\n}).describe('Rename an existing object');\n\nexport const DeleteObjectOperation = z.object({\n type: z.literal('delete_object'),\n objectName: z.string().describe('Name of the object to delete')\n}).describe('Delete an existing object');\n\nexport const ExecuteSqlOperation = z.object({\n type: z.literal('execute_sql'),\n sql: z.string().describe('Raw SQL statement to execute'),\n description: z.string().optional().describe('Human-readable description of the SQL')\n}).describe('Execute a raw SQL statement');\n\n// Union of all possible operations\nexport const MigrationOperationSchema = z.discriminatedUnion('type', [\n AddFieldOperation,\n ModifyFieldOperation,\n RemoveFieldOperation,\n CreateObjectOperation,\n RenameObjectOperation,\n DeleteObjectOperation,\n ExecuteSqlOperation\n]);\n\n// --- Migration & ChangeSet ---\n\nexport const MigrationDependencySchema = z.object({\n migrationId: z.string().describe('ID of the migration this depends on'),\n package: z.string().optional().describe('Package that owns the dependency migration')\n}).describe('Dependency reference to another migration that must run first');\n\nexport const ChangeSetSchema = z.object({\n id: z.string().uuid().describe('Unique identifier for this change set'),\n name: z.string().describe('Human readable name for the migration'),\n description: z.string().optional().describe('Detailed description of what this migration does'),\n author: z.string().optional().describe('Author who created this migration'),\n createdAt: z.string().datetime().optional().describe('ISO 8601 timestamp when the migration was created'),\n \n // Dependencies ensure migrations run in order\n dependencies: z.array(MigrationDependencySchema).optional().describe('Migrations that must run before this one'),\n \n // The actual atomic operations\n operations: z.array(MigrationOperationSchema).describe('Ordered list of atomic migration operations'),\n \n // Rollback operations (AI should generate these too)\n rollback: z.array(MigrationOperationSchema).optional().describe('Operations to reverse this migration')\n}).describe('A versioned set of atomic schema migration operations');\n\nexport type ChangeSet = z.infer;\nexport type MigrationOperation = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Better-Auth Configuration Protocol\n * \n * Defines the configuration required to initialize the Better-Auth kernel.\n * Used in server-side configuration injection.\n */\n\nexport const AuthProviderConfigSchema = z.object({\n id: z.string().describe('Provider ID (github, google)'),\n clientId: z.string().describe('OAuth Client ID'),\n clientSecret: z.string().describe('OAuth Client Secret'),\n scope: z.array(z.string()).optional().describe('Requested permissions'),\n});\n\nexport const AuthPluginConfigSchema = z.object({\n organization: z.boolean().default(false).describe('Enable Organization/Teams support'),\n twoFactor: z.boolean().default(false).describe('Enable 2FA'),\n passkeys: z.boolean().default(false).describe('Enable Passkey support'),\n magicLink: z.boolean().default(false).describe('Enable Magic Link login'),\n});\n\n/**\n * Mutual TLS (mTLS) Configuration Schema\n * \n * Enables client certificate authentication for zero-trust architectures.\n */\nexport const MutualTLSConfigSchema = z.object({\n /** Enable mutual TLS authentication */\n enabled: z.boolean()\n .default(false)\n .describe('Enable mutual TLS authentication'),\n\n /** Require client certificates for all connections */\n clientCertRequired: z.boolean()\n .default(false)\n .describe('Require client certificates for all connections'),\n\n /** PEM-encoded CA certificates or file paths for trust validation */\n trustedCAs: z.array(z.string())\n .describe('PEM-encoded CA certificates or file paths'),\n\n /** Certificate Revocation List URL */\n crlUrl: z.string()\n .optional()\n .describe('Certificate Revocation List (CRL) URL'),\n\n /** Online Certificate Status Protocol URL */\n ocspUrl: z.string()\n .optional()\n .describe('Online Certificate Status Protocol (OCSP) URL'),\n\n /** Certificate validation strictness level */\n certificateValidation: z.enum(['strict', 'relaxed', 'none'])\n .describe('Certificate validation strictness level'),\n\n /** Allowed Common Names on client certificates */\n allowedCNs: z.array(z.string())\n .optional()\n .describe('Allowed Common Names (CN) on client certificates'),\n\n /** Allowed Organizational Units on client certificates */\n allowedOUs: z.array(z.string())\n .optional()\n .describe('Allowed Organizational Units (OU) on client certificates'),\n\n /** Certificate pinning configuration */\n pinning: z.object({\n /** Enable certificate pinning */\n enabled: z.boolean().describe('Enable certificate pinning'),\n /** Array of pinned certificate hashes */\n pins: z.array(z.string()).describe('Pinned certificate hashes'),\n })\n .optional()\n .describe('Certificate pinning configuration'),\n});\n\nexport type MutualTLSConfig = z.infer;\n\n/**\n * Social / OAuth Provider Configuration\n *\n * Maps provider id → { clientId, clientSecret, ... }.\n * Keys must match Better-Auth built-in provider names (google, github, etc.).\n */\nexport const SocialProviderConfigSchema = z.record(\n z.string(),\n z.object({\n clientId: z.string().describe('OAuth Client ID'),\n clientSecret: z.string().describe('OAuth Client Secret'),\n enabled: z.boolean().optional().default(true).describe('Enable this provider'),\n scope: z.array(z.string()).optional().describe('Additional OAuth scopes'),\n }).catchall(z.unknown()),\n).optional().describe(\n 'Social/OAuth provider map forwarded to better-auth socialProviders. ' +\n 'Keys are provider ids (google, github, apple, …).'\n);\n\n/**\n * Email + Password Configuration\n */\nexport const EmailAndPasswordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable email/password auth'),\n disableSignUp: z.boolean().optional().describe('Disable new user registration via email/password'),\n requireEmailVerification: z.boolean().optional().describe(\n 'Require email verification before creating a session'\n ),\n minPasswordLength: z.number().optional().describe('Minimum password length (default 8)'),\n maxPasswordLength: z.number().optional().describe('Maximum password length (default 128)'),\n resetPasswordTokenExpiresIn: z.number().optional().describe(\n 'Reset-password token TTL in seconds (default 3600)'\n ),\n autoSignIn: z.boolean().optional().describe('Auto sign-in after sign-up (default true)'),\n revokeSessionsOnPasswordReset: z.boolean().optional().describe(\n 'Revoke all other sessions on password reset'\n ),\n}).optional().describe('Email and password authentication options forwarded to better-auth');\n\n/**\n * Email Verification Configuration\n */\nexport const EmailVerificationConfigSchema = z.object({\n sendOnSignUp: z.boolean().optional().describe(\n 'Automatically send verification email after sign-up'\n ),\n sendOnSignIn: z.boolean().optional().describe(\n 'Send verification email on sign-in when not yet verified'\n ),\n autoSignInAfterVerification: z.boolean().optional().describe(\n 'Auto sign-in the user after email verification'\n ),\n expiresIn: z.number().optional().describe(\n 'Verification token TTL in seconds (default 3600)'\n ),\n}).optional().describe('Email verification options forwarded to better-auth');\n\n/**\n * Advanced / Low-level Better-Auth Options\n */\nexport const AdvancedAuthConfigSchema = z.object({\n crossSubDomainCookies: z.object({\n enabled: z.boolean().describe('Enable cross-subdomain cookies'),\n additionalCookies: z.array(z.string()).optional().describe('Extra cookies shared across subdomains'),\n domain: z.string().optional().describe(\n 'Cookie domain override — defaults to root domain derived from baseUrl'\n ),\n }).optional().describe(\n 'Share auth cookies across subdomains (critical for *.example.com multi-tenant)'\n ),\n useSecureCookies: z.boolean().optional().describe('Force Secure flag on cookies'),\n disableCSRFCheck: z.boolean().optional().describe(\n '⚠ Disable CSRF check — security risk, use with caution'\n ),\n cookiePrefix: z.string().optional().describe('Prefix for auth cookie names'),\n}).optional().describe('Advanced / low-level Better-Auth options');\n\nexport const AuthConfigSchema = z.object({\n secret: z.string().optional().describe('Encryption secret'),\n baseUrl: z.string().optional().describe('Base URL for auth routes'),\n databaseUrl: z.string().optional().describe('Database connection string'),\n providers: z.array(AuthProviderConfigSchema).optional(),\n plugins: AuthPluginConfigSchema.optional(),\n session: z.object({\n expiresIn: z.number().default(60 * 60 * 24 * 7).describe('Session duration in seconds'),\n updateAge: z.number().default(60 * 60 * 24).describe('Session update frequency'),\n }).optional(),\n trustedOrigins: z.array(z.string()).optional().describe(\n 'Trusted origins for CSRF protection. Supports wildcards (e.g. \"https://*.example.com\"). ' +\n 'The baseUrl origin is always trusted implicitly.'\n ),\n socialProviders: SocialProviderConfigSchema,\n emailAndPassword: EmailAndPasswordConfigSchema,\n emailVerification: EmailVerificationConfigSchema,\n advanced: AdvancedAuthConfigSchema,\n mutualTls: MutualTLSConfigSchema.optional().describe('Mutual TLS (mTLS) configuration'),\n}).catchall(z.unknown());\n\nexport type AuthProviderConfig = z.infer;\nexport type AuthPluginConfig = z.infer;\nexport type SocialProviderConfig = z.infer;\nexport type EmailAndPasswordConfig = z.infer;\nexport type EmailVerificationConfig = z.infer;\nexport type AdvancedAuthConfig = z.infer;\nexport type AuthConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ComplianceFrameworkSchema } from './security-context.zod';\n\n/**\n * Compliance protocol for GDPR, CCPA, HIPAA, SOX, PCI-DSS\n */\nexport const GDPRConfigSchema = z.object({\n enabled: z.boolean().describe('Enable GDPR compliance controls'),\n dataSubjectRights: z.object({\n rightToAccess: z.boolean().default(true).describe('Allow data subjects to access their data'),\n rightToRectification: z.boolean().default(true).describe('Allow data subjects to correct their data'),\n rightToErasure: z.boolean().default(true).describe('Allow data subjects to request deletion'),\n rightToRestriction: z.boolean().default(true).describe('Allow data subjects to restrict processing'),\n rightToPortability: z.boolean().default(true).describe('Allow data subjects to export their data'),\n rightToObjection: z.boolean().default(true).describe('Allow data subjects to object to processing'),\n }).describe('Data subject rights configuration per GDPR Articles 15-21'),\n legalBasis: z.enum([\n 'consent',\n 'contract',\n 'legal-obligation',\n 'vital-interests',\n 'public-task',\n 'legitimate-interests',\n ]).describe('Legal basis for data processing under GDPR Article 6'),\n consentTracking: z.boolean().default(true).describe('Track and record user consent'),\n dataRetentionDays: z.number().optional().describe('Maximum data retention period in days'),\n dataProcessingAgreement: z.string().optional().describe('URL or reference to the data processing agreement'),\n}).describe('GDPR (General Data Protection Regulation) compliance configuration');\n\nexport type GDPRConfig = z.infer;\nexport type GDPRConfigInput = z.input;\n\nexport const HIPAAConfigSchema = z.object({\n enabled: z.boolean().describe('Enable HIPAA compliance controls'),\n phi: z.object({\n encryption: z.boolean().default(true).describe('Encrypt Protected Health Information at rest'),\n accessControl: z.boolean().default(true).describe('Enforce role-based access to PHI'),\n auditTrail: z.boolean().default(true).describe('Log all PHI access events'),\n backupAndRecovery: z.boolean().default(true).describe('Enable PHI backup and disaster recovery'),\n }).describe('Protected Health Information safeguards'),\n businessAssociateAgreement: z.boolean().default(false).describe('BAA is in place with third-party processors'),\n}).describe('HIPAA (Health Insurance Portability and Accountability Act) compliance configuration');\n\nexport type HIPAAConfig = z.infer;\nexport type HIPAAConfigInput = z.input;\n\nexport const PCIDSSConfigSchema = z.object({\n enabled: z.boolean().describe('Enable PCI-DSS compliance controls'),\n level: z.enum(['1', '2', '3', '4']).describe('PCI-DSS compliance level (1 = highest)'),\n cardDataFields: z.array(z.string()).describe('Field names containing cardholder data'),\n tokenization: z.boolean().default(true).describe('Replace card data with secure tokens'),\n encryptionInTransit: z.boolean().default(true).describe('Encrypt cardholder data during transmission'),\n encryptionAtRest: z.boolean().default(true).describe('Encrypt stored cardholder data'),\n}).describe('PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration');\n\nexport type PCIDSSConfig = z.infer;\nexport type PCIDSSConfigInput = z.input;\n\nexport const AuditLogConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable audit logging'),\n retentionDays: z.number().default(365).describe('Number of days to retain audit logs'),\n immutable: z.boolean().default(true).describe('Prevent modification or deletion of audit logs'),\n signLogs: z.boolean().default(false).describe('Cryptographically sign log entries for tamper detection'),\n events: z.array(z.enum([\n 'create',\n 'read',\n 'update',\n 'delete',\n 'export',\n 'permission-change',\n 'login',\n 'logout',\n 'failed-login',\n ])).describe('Event types to capture in the audit log'),\n}).describe('Audit log configuration for compliance and security monitoring');\n\nexport type AuditLogConfig = z.infer;\nexport type AuditLogConfigInput = z.input;\n\n/**\n * Audit Finding Severity Schema\n *\n * Severity classification for audit findings.\n */\nexport const AuditFindingSeveritySchema = z.enum([\n 'critical', // Immediate remediation required\n 'major', // Significant non-conformity\n 'minor', // Minor non-conformity\n 'observation', // Improvement opportunity\n]);\n\n/**\n * Audit Finding Status Schema\n *\n * Lifecycle status of an audit finding.\n */\nexport const AuditFindingStatusSchema = z.enum([\n 'open', // Finding identified, not yet addressed\n 'in_remediation', // Remediation in progress\n 'remediated', // Remediation completed, pending verification\n 'verified', // Remediation verified and accepted\n 'accepted_risk', // Risk accepted by management\n 'closed', // Finding closed\n]);\n\n/**\n * Audit Finding Schema (A.5.35)\n *\n * Individual finding from a compliance or security audit.\n * Supports tracking from discovery through remediation and verification.\n *\n * @example\n * ```json\n * {\n * \"id\": \"FIND-2024-001\",\n * \"title\": \"Insufficient access logging\",\n * \"description\": \"PHI access events are not being logged for HIPAA compliance\",\n * \"severity\": \"major\",\n * \"status\": \"in_remediation\",\n * \"controlReference\": \"A.8.15\",\n * \"framework\": \"iso27001\",\n * \"identifiedAt\": 1704067200000,\n * \"identifiedBy\": \"external_auditor\",\n * \"remediationPlan\": \"Implement audit logging for all PHI access events\",\n * \"remediationDeadline\": 1706745600000\n * }\n * ```\n */\nexport const AuditFindingSchema = z.object({\n /**\n * Unique finding identifier\n */\n id: z.string().describe('Unique finding identifier'),\n\n /**\n * Short descriptive title\n */\n title: z.string().describe('Finding title'),\n\n /**\n * Detailed description of the finding\n */\n description: z.string().describe('Finding description'),\n\n /**\n * Finding severity\n */\n severity: AuditFindingSeveritySchema.describe('Finding severity'),\n\n /**\n * Current status\n */\n status: AuditFindingStatusSchema.describe('Finding status'),\n\n /**\n * ISO 27001 control reference (e.g., \"A.5.35\", \"A.8.15\")\n */\n controlReference: z.string().optional().describe('ISO 27001 control reference'),\n\n /**\n * Compliance framework\n */\n framework: ComplianceFrameworkSchema.optional()\n .describe('Related compliance framework'),\n\n /**\n * Timestamp when finding was identified (Unix milliseconds)\n */\n identifiedAt: z.number().describe('Identification timestamp'),\n\n /**\n * User or entity who identified the finding\n */\n identifiedBy: z.string().describe('Identifier (auditor name or system)'),\n\n /**\n * Planned remediation actions\n */\n remediationPlan: z.string().optional().describe('Remediation plan'),\n\n /**\n * Remediation deadline (Unix milliseconds)\n */\n remediationDeadline: z.number().optional().describe('Remediation deadline timestamp'),\n\n /**\n * Timestamp when remediation was verified (Unix milliseconds)\n */\n verifiedAt: z.number().optional().describe('Verification timestamp'),\n\n /**\n * Verifier name or role\n */\n verifiedBy: z.string().optional().describe('Verifier name or role'),\n\n /**\n * Notes or comments\n */\n notes: z.string().optional().describe('Additional notes'),\n}).describe('Audit finding with remediation tracking per ISO 27001:2022 A.5.35');\n\nexport type AuditFinding = z.infer;\n\n/**\n * Audit Schedule Schema (A.5.35)\n *\n * Defines audit scheduling for independent information security reviews.\n * Supports recurring audits, scope definition, and assessor assignment.\n *\n * @example\n * ```json\n * {\n * \"id\": \"AUDIT-2024-Q1\",\n * \"title\": \"Q1 ISO 27001 Internal Audit\",\n * \"scope\": [\"access_control\", \"encryption\", \"incident_response\"],\n * \"framework\": \"iso27001\",\n * \"scheduledAt\": 1711929600000,\n * \"assessor\": \"internal_audit_team\",\n * \"recurrenceMonths\": 3\n * }\n * ```\n */\nexport const AuditScheduleSchema = z.object({\n /**\n * Unique audit schedule identifier\n */\n id: z.string().describe('Unique audit schedule identifier'),\n\n /**\n * Audit title or name\n */\n title: z.string().describe('Audit title'),\n\n /**\n * Scope of areas to audit\n */\n scope: z.array(z.string()).describe('Audit scope areas'),\n\n /**\n * Target compliance framework\n */\n framework: ComplianceFrameworkSchema\n .describe('Target compliance framework'),\n\n /**\n * Scheduled audit date (Unix milliseconds)\n */\n scheduledAt: z.number().describe('Scheduled audit timestamp'),\n\n /**\n * Actual completion date (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Completion timestamp'),\n\n /**\n * Assessor name, team, or external firm\n */\n assessor: z.string().describe('Assessor or audit team'),\n\n /**\n * Whether this is an external (independent) audit\n */\n isExternal: z.boolean().default(false).describe('Whether this is an external audit'),\n\n /**\n * Recurrence interval in months (0 = one-time)\n */\n recurrenceMonths: z.number().default(0).describe('Recurrence interval in months (0 = one-time)'),\n\n /**\n * Findings from this audit\n */\n findings: z.array(AuditFindingSchema).optional().describe('Audit findings'),\n}).describe('Audit schedule for independent security reviews per ISO 27001:2022 A.5.35');\n\nexport type AuditSchedule = z.infer;\n\nexport const ComplianceConfigSchema = z.object({\n gdpr: GDPRConfigSchema.optional().describe('GDPR compliance settings'),\n hipaa: HIPAAConfigSchema.optional().describe('HIPAA compliance settings'),\n pciDss: PCIDSSConfigSchema.optional().describe('PCI-DSS compliance settings'),\n auditLog: AuditLogConfigSchema.describe('Audit log configuration'),\n auditSchedules: z.array(AuditScheduleSchema).optional()\n .describe('Scheduled compliance audits (A.5.35)'),\n}).describe('Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance');\n\nexport type ComplianceConfig = z.infer;\nexport type ComplianceConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Incident Response Protocol — ISO 27001:2022 (A.5.24–A.5.28)\n *\n * Defines schemas for information security event management including\n * incident classification, severity grading, response procedures,\n * and notification matrices.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Incident Severity Schema\n *\n * Severity grading for security incidents following ISO 27001 guidelines.\n * Determines response urgency and escalation requirements.\n */\nexport const IncidentSeveritySchema = z.enum([\n 'critical', // Immediate threat to business operations or data integrity\n 'high', // Significant impact requiring urgent response\n 'medium', // Moderate impact with controlled response timeline\n 'low', // Minor impact with standard response procedures\n]);\n\n/**\n * Incident Category Schema\n *\n * Classification of security incidents by type (A.5.25).\n * Used for routing, reporting, and trend analysis.\n */\nexport const IncidentCategorySchema = z.enum([\n 'data_breach', // Unauthorized access or disclosure of data\n 'malware', // Malicious software detection\n 'unauthorized_access', // Unauthorized system or data access\n 'denial_of_service', // Service availability attack\n 'social_engineering', // Phishing, pretexting, or manipulation\n 'insider_threat', // Threat originating from internal actors\n 'physical_security', // Physical security breach\n 'configuration_error', // Security misconfiguration\n 'vulnerability_exploit', // Exploitation of known vulnerability\n 'policy_violation', // Violation of security policies\n 'other', // Other security incidents\n]);\n\n/**\n * Incident Status Schema\n *\n * Current status of a security incident in its lifecycle.\n */\nexport const IncidentStatusSchema = z.enum([\n 'reported', // Initial report received\n 'triaged', // Severity and category assessed\n 'investigating', // Active investigation in progress\n 'containing', // Containment measures being applied\n 'eradicating', // Root cause being removed\n 'recovering', // Systems being restored to normal\n 'resolved', // Incident resolved\n 'closed', // Post-incident review complete\n]);\n\n/**\n * Incident Response Phase Schema\n *\n * Defines structured response phases per NIST SP 800-61 / ISO 27001 (A.5.26).\n */\nexport const IncidentResponsePhaseSchema = z.object({\n /**\n * Phase name identifier\n */\n phase: z.enum([\n 'identification',\n 'containment',\n 'eradication',\n 'recovery',\n 'lessons_learned',\n ]).describe('Response phase name'),\n\n /**\n * Phase description and objectives\n */\n description: z.string().describe('Phase description and objectives'),\n\n /**\n * Responsible team or role for this phase\n */\n assignedTo: z.string().describe('Responsible team or role'),\n\n /**\n * Target completion time in hours from incident start\n */\n targetHours: z.number().min(0).describe('Target completion time in hours'),\n\n /**\n * Actual completion timestamp (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Actual completion timestamp'),\n\n /**\n * Notes and findings during this phase\n */\n notes: z.string().optional().describe('Phase notes and findings'),\n}).describe('Incident response phase with timing and assignment');\n\nexport type IncidentResponsePhase = z.infer;\n\n/**\n * Notification Rule Schema\n *\n * Defines who must be notified and when, based on severity (A.5.27).\n */\nexport const IncidentNotificationRuleSchema = z.object({\n /**\n * Minimum severity level that triggers this notification\n */\n severity: IncidentSeveritySchema.describe('Minimum severity to trigger notification'),\n\n /**\n * Notification channels to use\n */\n channels: z.array(z.enum([\n 'email',\n 'sms',\n 'slack',\n 'pagerduty',\n 'webhook',\n ])).describe('Notification channels'),\n\n /**\n * Roles or teams to notify\n */\n recipients: z.array(z.string()).describe('Roles or teams to notify'),\n\n /**\n * Maximum time in minutes to send notification after incident detection\n */\n withinMinutes: z.number().min(1).describe('Notification deadline in minutes from detection'),\n\n /**\n * Whether to notify external regulators (for data breaches)\n */\n notifyRegulators: z.boolean().default(false)\n .describe('Whether to notify regulatory authorities'),\n\n /**\n * Regulatory notification deadline in hours (e.g., GDPR 72h)\n */\n regulatorDeadlineHours: z.number().optional()\n .describe('Regulatory notification deadline in hours'),\n}).describe('Incident notification rule per severity level');\n\nexport type IncidentNotificationRule = z.infer;\n\n/**\n * Notification Matrix Schema\n *\n * Complete notification matrix mapping severity levels to stakeholder groups (A.5.27).\n */\nexport const IncidentNotificationMatrixSchema = z.object({\n /**\n * Notification rules ordered by severity\n */\n rules: z.array(IncidentNotificationRuleSchema)\n .describe('Notification rules by severity level'),\n\n /**\n * Default escalation timeout in minutes before auto-escalation\n */\n escalationTimeoutMinutes: z.number().default(30)\n .describe('Auto-escalation timeout in minutes'),\n\n /**\n * Escalation chain: ordered list of roles to escalate to\n */\n escalationChain: z.array(z.string()).default([])\n .describe('Ordered escalation chain of roles'),\n}).describe('Incident notification matrix with escalation policies');\n\nexport type IncidentNotificationMatrix = z.infer;\n\n/**\n * Incident Schema\n *\n * Comprehensive security incident record following ISO 27001:2022 (A.5.24–A.5.28).\n * Tracks the full incident lifecycle from detection through post-incident review.\n *\n * @example\n * ```json\n * {\n * \"id\": \"INC-2024-001\",\n * \"title\": \"Unauthorized API Access Detected\",\n * \"description\": \"Multiple failed authentication attempts from unknown IP range\",\n * \"severity\": \"high\",\n * \"category\": \"unauthorized_access\",\n * \"status\": \"investigating\",\n * \"reportedBy\": \"monitoring_system\",\n * \"reportedAt\": 1704067200000,\n * \"affectedSystems\": [\"api-gateway\", \"auth-service\"],\n * \"affectedDataClassifications\": [\"pii\", \"confidential\"],\n * \"responsePhases\": [\n * {\n * \"phase\": \"identification\",\n * \"description\": \"Identify scope of unauthorized access\",\n * \"assignedTo\": \"security_team\",\n * \"targetHours\": 2\n * }\n * ]\n * }\n * ```\n */\nexport const IncidentSchema = z.object({\n /**\n * Unique incident identifier\n */\n id: z.string().describe('Unique incident identifier'),\n\n /**\n * Short descriptive title of the incident\n */\n title: z.string().describe('Incident title'),\n\n /**\n * Detailed description of the security event\n */\n description: z.string().describe('Detailed incident description'),\n\n /**\n * Severity classification\n */\n severity: IncidentSeveritySchema.describe('Incident severity level'),\n\n /**\n * Incident category / type\n */\n category: IncidentCategorySchema.describe('Incident category'),\n\n /**\n * Current status in the incident lifecycle\n */\n status: IncidentStatusSchema.describe('Current incident status'),\n\n /**\n * User or system that reported the incident\n */\n reportedBy: z.string().describe('Reporter user ID or system name'),\n\n /**\n * Timestamp when the incident was reported (Unix milliseconds)\n */\n reportedAt: z.number().describe('Report timestamp'),\n\n /**\n * Timestamp when the incident was detected (may differ from reported)\n */\n detectedAt: z.number().optional().describe('Detection timestamp'),\n\n /**\n * Timestamp when the incident was resolved\n */\n resolvedAt: z.number().optional().describe('Resolution timestamp'),\n\n /**\n * Systems affected by the incident\n */\n affectedSystems: z.array(z.string()).describe('Affected systems'),\n\n /**\n * Data classifications affected (for data breach assessment)\n */\n affectedDataClassifications: z.array(DataClassificationSchema)\n .optional().describe('Affected data classifications'),\n\n /**\n * Structured response phases tracking\n */\n responsePhases: z.array(IncidentResponsePhaseSchema).optional()\n .describe('Incident response phases'),\n\n /**\n * Root cause analysis (completed post-incident)\n */\n rootCause: z.string().optional().describe('Root cause analysis'),\n\n /**\n * Corrective actions taken or planned\n */\n correctiveActions: z.array(z.string()).optional()\n .describe('Corrective actions taken or planned'),\n\n /**\n * Lessons learned from the incident (A.5.28)\n */\n lessonsLearned: z.string().optional()\n .describe('Lessons learned from the incident'),\n\n /**\n * Related change request IDs (if changes resulted from incident)\n */\n relatedChangeRequestIds: z.array(z.string()).optional()\n .describe('Related change request IDs'),\n\n /**\n * Custom metadata for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Custom metadata key-value pairs'),\n}).describe('Security incident record per ISO 27001:2022 A.5.24–A.5.28');\n\n/**\n * Incident Response Policy Schema\n *\n * Organization-level incident response policy configuration (A.5.24).\n */\nexport const IncidentResponsePolicySchema = z.object({\n /**\n * Whether incident response is enabled\n */\n enabled: z.boolean().default(true)\n .describe('Enable incident response management'),\n\n /**\n * Notification matrix configuration\n */\n notificationMatrix: IncidentNotificationMatrixSchema\n .describe('Notification and escalation matrix'),\n\n /**\n * Default response team or role\n */\n defaultResponseTeam: z.string()\n .describe('Default incident response team or role'),\n\n /**\n * Maximum time in hours to begin initial triage\n */\n triageDeadlineHours: z.number().default(1)\n .describe('Maximum hours to begin triage after detection'),\n\n /**\n * Whether to require post-incident review for all incidents\n */\n requirePostIncidentReview: z.boolean().default(true)\n .describe('Require post-incident review for all incidents'),\n\n /**\n * Minimum severity level that requires regulatory notification\n */\n regulatoryNotificationThreshold: IncidentSeveritySchema.default('high')\n .describe('Minimum severity requiring regulatory notification'),\n\n /**\n * Retention period for incident records in days\n */\n retentionDays: z.number().default(2555)\n .describe('Incident record retention period in days (default ~7 years)'),\n}).describe('Organization-level incident response policy per ISO 27001:2022');\n\n// Type exports\nexport type IncidentSeverity = z.infer;\nexport type IncidentCategory = z.infer;\nexport type IncidentStatus = z.infer;\nexport type Incident = z.infer;\nexport type IncidentResponsePolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Supplier Security Protocol — ISO 27001:2022 (A.5.19–A.5.22)\n *\n * Defines schemas for supplier information security management including\n * risk assessment, security requirements, monitoring, and change control.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Supplier Risk Level Schema\n *\n * Risk classification for supplier relationships based on data access\n * and service criticality.\n */\nexport const SupplierRiskLevelSchema = z.enum([\n 'critical', // Direct access to sensitive data or core infrastructure\n 'high', // Significant data processing or service dependency\n 'medium', // Limited data access with moderate dependency\n 'low', // Minimal data access and low service dependency\n]);\n\n/**\n * Supplier Assessment Status Schema\n *\n * Current status of a supplier security assessment.\n */\nexport const SupplierAssessmentStatusSchema = z.enum([\n 'pending', // Assessment not yet started\n 'in_progress', // Assessment currently underway\n 'completed', // Assessment completed\n 'expired', // Assessment past its validity period\n 'failed', // Supplier did not meet security requirements\n]);\n\n/**\n * Supplier Security Requirement Schema\n *\n * Individual security requirement to assess against a supplier (A.5.20).\n */\nexport const SupplierSecurityRequirementSchema = z.object({\n /**\n * Requirement identifier\n */\n id: z.string().describe('Requirement identifier'),\n\n /**\n * Requirement description\n */\n description: z.string().describe('Requirement description'),\n\n /**\n * ISO 27001 control reference (e.g., \"A.5.19\")\n */\n controlReference: z.string().optional()\n .describe('ISO 27001 control reference'),\n\n /**\n * Whether this requirement is mandatory\n */\n mandatory: z.boolean().default(true)\n .describe('Whether this requirement is mandatory'),\n\n /**\n * Compliance status\n */\n compliant: z.boolean().optional()\n .describe('Whether the supplier meets this requirement'),\n\n /**\n * Evidence or notes for compliance assessment\n */\n evidence: z.string().optional()\n .describe('Compliance evidence or assessment notes'),\n}).describe('Individual supplier security requirement');\n\nexport type SupplierSecurityRequirement = z.infer;\n\n/**\n * Supplier Security Assessment Schema\n *\n * Comprehensive supplier security assessment record (A.5.19–A.5.21).\n *\n * @example\n * ```json\n * {\n * \"supplierId\": \"SUP-001\",\n * \"supplierName\": \"Cloud Provider Inc.\",\n * \"riskLevel\": \"critical\",\n * \"status\": \"completed\",\n * \"assessedBy\": \"security_team\",\n * \"assessedAt\": 1704067200000,\n * \"validUntil\": 1735689600000,\n * \"requirements\": [\n * {\n * \"id\": \"REQ-001\",\n * \"description\": \"Data encryption at rest using AES-256\",\n * \"controlReference\": \"A.8.24\",\n * \"mandatory\": true,\n * \"compliant\": true\n * }\n * ],\n * \"overallCompliant\": true,\n * \"dataClassificationsShared\": [\"pii\", \"confidential\"]\n * }\n * ```\n */\nexport const SupplierSecurityAssessmentSchema = z.object({\n /**\n * Unique supplier identifier\n */\n supplierId: z.string().describe('Unique supplier identifier'),\n\n /**\n * Supplier name\n */\n supplierName: z.string().describe('Supplier display name'),\n\n /**\n * Risk classification\n */\n riskLevel: SupplierRiskLevelSchema.describe('Supplier risk classification'),\n\n /**\n * Assessment status\n */\n status: SupplierAssessmentStatusSchema.describe('Assessment status'),\n\n /**\n * User or team who performed the assessment\n */\n assessedBy: z.string().describe('Assessor user ID or team'),\n\n /**\n * Assessment completion timestamp (Unix milliseconds)\n */\n assessedAt: z.number().describe('Assessment timestamp'),\n\n /**\n * Assessment validity expiry (Unix milliseconds)\n */\n validUntil: z.number().describe('Assessment validity expiry timestamp'),\n\n /**\n * Security requirements assessed\n */\n requirements: z.array(SupplierSecurityRequirementSchema)\n .describe('Security requirements and their compliance status'),\n\n /**\n * Overall compliance result\n */\n overallCompliant: z.boolean().describe('Whether supplier meets all mandatory requirements'),\n\n /**\n * Data classifications shared with this supplier\n */\n dataClassificationsShared: z.array(DataClassificationSchema)\n .optional().describe('Data classifications shared with supplier'),\n\n /**\n * Services provided by the supplier\n */\n servicesProvided: z.array(z.string()).optional()\n .describe('Services provided by this supplier'),\n\n /**\n * Certifications held by the supplier\n */\n certifications: z.array(z.string()).optional()\n .describe('Supplier certifications (e.g., ISO 27001, SOC 2)'),\n\n /**\n * Remediation items for non-compliant requirements\n */\n remediationItems: z.array(z.object({\n requirementId: z.string().describe('Non-compliant requirement ID'),\n action: z.string().describe('Required remediation action'),\n deadline: z.number().describe('Remediation deadline timestamp'),\n status: z.enum(['pending', 'in_progress', 'completed']).default('pending')\n .describe('Remediation status'),\n })).optional().describe('Remediation items for non-compliant requirements'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Custom metadata key-value pairs'),\n}).describe('Supplier security assessment record per ISO 27001:2022 A.5.19–A.5.21');\n\n/**\n * Supplier Security Policy Schema\n *\n * Organization-level supplier security management policy (A.5.22).\n */\nexport const SupplierSecurityPolicySchema = z.object({\n /**\n * Whether supplier security management is enabled\n */\n enabled: z.boolean().default(true)\n .describe('Enable supplier security management'),\n\n /**\n * Reassessment interval in days\n */\n reassessmentIntervalDays: z.number().default(365)\n .describe('Supplier reassessment interval in days'),\n\n /**\n * Whether to require supplier security assessment before onboarding\n */\n requirePreOnboardingAssessment: z.boolean().default(true)\n .describe('Require security assessment before supplier onboarding'),\n\n /**\n * Minimum risk level that requires formal assessment\n */\n formalAssessmentThreshold: SupplierRiskLevelSchema.default('medium')\n .describe('Minimum risk level requiring formal assessment'),\n\n /**\n * Whether to monitor supplier security changes (A.5.22)\n */\n monitorChanges: z.boolean().default(true)\n .describe('Monitor supplier security posture changes'),\n\n /**\n * Required certifications for critical suppliers\n */\n requiredCertifications: z.array(z.string()).default([])\n .describe('Required certifications for critical-risk suppliers'),\n}).describe('Organization-level supplier security management policy per ISO 27001:2022');\n\n// Type exports\nexport type SupplierRiskLevel = z.infer;\nexport type SupplierAssessmentStatus = z.infer;\nexport type SupplierSecurityAssessment = z.infer;\nexport type SupplierSecurityPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Information Security Training Protocol — ISO 27001:2022 (A.6.3)\n *\n * Defines schemas for security awareness and training management including\n * course definitions, completion tracking, and organizational training plans.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Training Category Schema\n *\n * Classification of training content by domain.\n */\nexport const TrainingCategorySchema = z.enum([\n 'security_awareness', // General security awareness\n 'data_protection', // Data handling and privacy\n 'incident_response', // Incident reporting and response\n 'access_control', // Access management best practices\n 'phishing_awareness', // Phishing and social engineering\n 'compliance', // Regulatory compliance (GDPR, HIPAA, etc.)\n 'secure_development', // Secure coding and development practices\n 'physical_security', // Physical security awareness\n 'business_continuity', // Business continuity and disaster recovery\n 'other', // Other training categories\n]);\n\n/**\n * Training Completion Status Schema\n */\nexport const TrainingCompletionStatusSchema = z.enum([\n 'not_started', // Training not yet begun\n 'in_progress', // Training currently underway\n 'completed', // Training completed successfully\n 'failed', // Training assessment not passed\n 'expired', // Training certification has expired\n]);\n\n/**\n * Training Course Schema\n *\n * Definition of a security training course or module.\n *\n * @example\n * ```json\n * {\n * \"id\": \"COURSE-SEC-001\",\n * \"title\": \"Information Security Fundamentals\",\n * \"description\": \"Annual security awareness training for all employees\",\n * \"category\": \"security_awareness\",\n * \"durationMinutes\": 60,\n * \"mandatory\": true,\n * \"targetRoles\": [\"all_employees\"],\n * \"validityDays\": 365,\n * \"passingScore\": 80\n * }\n * ```\n */\nexport const TrainingCourseSchema = z.object({\n /**\n * Unique course identifier\n */\n id: z.string().describe('Unique course identifier'),\n\n /**\n * Course title\n */\n title: z.string().describe('Course title'),\n\n /**\n * Course description and objectives\n */\n description: z.string().describe('Course description and learning objectives'),\n\n /**\n * Training category\n */\n category: TrainingCategorySchema.describe('Training category'),\n\n /**\n * Estimated duration in minutes\n */\n durationMinutes: z.number().min(1).describe('Estimated course duration in minutes'),\n\n /**\n * Whether this training is mandatory\n */\n mandatory: z.boolean().default(false).describe('Whether training is mandatory'),\n\n /**\n * Target roles or groups for this training\n */\n targetRoles: z.array(z.string()).describe('Target roles or groups'),\n\n /**\n * Validity period in days before recertification is needed\n */\n validityDays: z.number().optional().describe('Certification validity period in days'),\n\n /**\n * Minimum passing score (percentage) for assessment\n */\n passingScore: z.number().min(0).max(100).optional()\n .describe('Minimum passing score percentage'),\n\n /**\n * Course version for tracking content updates\n */\n version: z.string().optional().describe('Course content version'),\n}).describe('Security training course definition');\n\n/**\n * Training Record Schema\n *\n * Individual employee training completion record.\n */\nexport const TrainingRecordSchema = z.object({\n /**\n * Reference to the course ID\n */\n courseId: z.string().describe('Training course identifier'),\n\n /**\n * User who completed (or is assigned) the training\n */\n userId: z.string().describe('User identifier'),\n\n /**\n * Completion status\n */\n status: TrainingCompletionStatusSchema.describe('Training completion status'),\n\n /**\n * Training assignment date (Unix milliseconds)\n */\n assignedAt: z.number().describe('Assignment timestamp'),\n\n /**\n * Training completion date (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Completion timestamp'),\n\n /**\n * Assessment score (percentage)\n */\n score: z.number().min(0).max(100).optional().describe('Assessment score percentage'),\n\n /**\n * Certification expiry date (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Certification expiry timestamp'),\n\n /**\n * Notes or comments from instructor or system\n */\n notes: z.string().optional().describe('Training notes or comments'),\n}).describe('Individual training completion record');\n\n/**\n * Training Plan Schema\n *\n * Organizational training plan defining schedule and requirements (A.6.3).\n */\nexport const TrainingPlanSchema = z.object({\n /**\n * Whether training management is enabled\n */\n enabled: z.boolean().default(true).describe('Enable training management'),\n\n /**\n * Training courses in the plan\n */\n courses: z.array(TrainingCourseSchema).describe('Training courses'),\n\n /**\n * Default recertification interval in days\n */\n recertificationIntervalDays: z.number().default(365)\n .describe('Default recertification interval in days'),\n\n /**\n * Whether to track training completion for compliance reporting\n */\n trackCompletion: z.boolean().default(true)\n .describe('Track training completion for compliance'),\n\n /**\n * Grace period in days after expiry before non-compliance escalation\n */\n gracePeriodDays: z.number().default(30)\n .describe('Grace period in days after certification expiry'),\n\n /**\n * Whether to send reminders for upcoming training deadlines\n */\n sendReminders: z.boolean().default(true)\n .describe('Send reminders for upcoming training deadlines'),\n\n /**\n * Days before deadline to send first reminder\n */\n reminderDaysBefore: z.number().default(14)\n .describe('Days before deadline to send first reminder'),\n}).describe('Organizational training plan per ISO 27001:2022 A.6.3');\n\n// Type exports\nexport type TrainingCategory = z.infer;\nexport type TrainingCompletionStatus = z.infer;\nexport type TrainingCourse = z.infer;\nexport type TrainingRecord = z.infer;\nexport type TrainingPlan = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Cron Schedule Schema\n * Schedule jobs using cron expressions\n */\nexport const CronScheduleSchema = z.object({\n type: z.literal('cron'),\n expression: z.string().describe('Cron expression (e.g., \"0 0 * * *\" for daily at midnight)'),\n timezone: z.string().optional().default('UTC').describe('Timezone for cron execution (e.g., \"America/New_York\")'),\n});\n\n/**\n * Interval Schedule Schema\n * Schedule jobs at fixed intervals\n */\nexport const IntervalScheduleSchema = z.object({\n type: z.literal('interval'),\n intervalMs: z.number().int().positive().describe('Interval in milliseconds'),\n});\n\n/**\n * Once Schedule Schema\n * Schedule a job to run once at a specific time\n */\nexport const OnceScheduleSchema = z.object({\n type: z.literal('once'),\n at: z.string().datetime().describe('ISO 8601 datetime when to execute'),\n});\n\n/**\n * Schedule Schema\n * Discriminated union of all schedule types\n */\nexport const ScheduleSchema = z.discriminatedUnion('type', [\n CronScheduleSchema,\n IntervalScheduleSchema,\n OnceScheduleSchema,\n]);\n\nexport type Schedule = z.infer;\nexport type CronSchedule = z.infer;\nexport type IntervalSchedule = z.infer;\nexport type OnceSchedule = z.infer;\nexport type JobSchedule = Schedule; // Alias for backwards compatibility\n\n/**\n * Retry Policy Schema\n * Configuration for job retry behavior with exponential backoff\n */\nexport const RetryPolicySchema = z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum number of retry attempts'),\n backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay in milliseconds'),\n backoffMultiplier: z.number().positive().default(2).describe('Multiplier for exponential backoff'),\n});\n\nexport type RetryPolicy = z.infer;\n\n/**\n * Job Schema\n * Defines a scheduled job that executes background logic.\n * \n * @example Metadata Sync Job (Cron)\n * {\n * id: \"job_sync_meta\",\n * name: \"sync_metadata_nightly\",\n * schedule: {\n * type: \"cron\",\n * expression: \"0 0 * * *\", // Midnight\n * timezone: \"UTC\"\n * },\n * handler: \"services/syncStatus.ts:syncAll\", \n * retryPolicy: {\n * maxRetries: 3,\n * backoffMs: 5000\n * }\n * }\n */\nexport const JobSchema = z.object({\n id: z.string().describe('Unique job identifier'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Job name (snake_case)'),\n schedule: ScheduleSchema.describe('Job schedule configuration'),\n handler: z.string().describe('Handler path (e.g. \"path/to/file:functionName\") or script ID'),\n retryPolicy: RetryPolicySchema.optional().describe('Retry policy configuration'),\n timeout: z.number().int().positive().optional().describe('Timeout in milliseconds'),\n enabled: z.boolean().default(true).describe('Whether the job is enabled'),\n});\n\nexport type Job = z.infer;\n\n/**\n * Job Execution Status Enum\n * Status of job execution\n */\nexport const JobExecutionStatus = z.enum([\n 'running',\n 'success',\n 'failed',\n 'timeout',\n]);\n\nexport type JobExecutionStatus = z.infer;\n\n/**\n * Job Execution Schema\n * Logs for job execution\n */\nexport const JobExecutionSchema = z.object({\n jobId: z.string().describe('Job identifier'),\n startedAt: z.string().datetime().describe('ISO 8601 datetime when execution started'),\n completedAt: z.string().datetime().optional().describe('ISO 8601 datetime when execution completed'),\n status: JobExecutionStatus.describe('Execution status'),\n error: z.string().optional().describe('Error message if failed'),\n duration: z.number().int().optional().describe('Execution duration in milliseconds'),\n});\n\nexport type JobExecution = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Worker System Protocol\n * \n * Background task processing system with queues, priorities, and retry logic.\n * Provides a robust foundation for async task execution similar to:\n * - Sidekiq (Ruby)\n * - Celery (Python)\n * - Bull/BullMQ (Node.js)\n * - AWS SQS/Lambda\n * \n * Features:\n * - Task queues with priorities\n * - Task scheduling and retry logic\n * - Batch processing\n * - Dead letter queues\n * - Task monitoring and logging\n * \n * @example Basic task\n * ```typescript\n * const task: Task = {\n * id: 'task-123',\n * type: 'send_email',\n * payload: { to: 'user@example.com', subject: 'Welcome' },\n * queue: 'notifications',\n * priority: 5\n * };\n * ```\n */\n\n// ==========================================\n// Task Priority\n// ==========================================\n\n/**\n * Task Priority Enum\n * Lower numbers = higher priority\n */\nexport const TaskPriority = z.enum([\n 'critical', // 0 - Must execute immediately\n 'high', // 1 - Execute soon\n 'normal', // 2 - Default priority\n 'low', // 3 - Execute when resources available\n 'background', // 4 - Execute during low-traffic periods\n]);\n\nexport type TaskPriority = z.infer;\n\n/**\n * Task Priority Mapping\n * Maps priority names to numeric values for sorting\n */\nexport const TASK_PRIORITY_VALUES: Record = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n background: 4,\n};\n\n// ==========================================\n// Task Status\n// ==========================================\n\n/**\n * Task Status Enum\n * Lifecycle states of a task\n */\nexport const TaskStatus = z.enum([\n 'pending', // Waiting to be processed\n 'queued', // In queue, ready for worker\n 'processing', // Currently being executed\n 'completed', // Successfully completed\n 'failed', // Failed (may retry)\n 'cancelled', // Manually cancelled\n 'timeout', // Exceeded execution timeout\n 'dead', // Moved to dead letter queue\n]);\n\nexport type TaskStatus = z.infer;\n\n// ==========================================\n// Task Schema\n// ==========================================\n\n/**\n * Task Retry Policy Schema\n * Configuration for task retry behavior\n */\nexport const TaskRetryPolicySchema = z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy between retries'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay in milliseconds'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay in milliseconds'),\n backoffMultiplier: z.number().positive().default(2).describe('Multiplier for exponential backoff'),\n});\n\nexport type TaskRetryPolicy = z.infer;\nexport type TaskRetryPolicyInput = z.input;\n\n/**\n * Task Schema\n * Represents a background task to be executed\n * \n * @example\n * {\n * \"id\": \"task-abc123\",\n * \"type\": \"send_email\",\n * \"payload\": { \"to\": \"user@example.com\", \"template\": \"welcome\" },\n * \"queue\": \"notifications\",\n * \"priority\": \"high\",\n * \"retryPolicy\": {\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * }\n * }\n */\nexport const TaskSchema = z.object({\n /**\n * Unique task identifier\n */\n id: z.string().describe('Unique task identifier'),\n \n /**\n * Task type (handler identifier)\n */\n type: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Task type (snake_case)'),\n \n /**\n * Task payload data\n */\n payload: z.unknown().describe('Task payload data'),\n \n /**\n * Queue name\n */\n queue: z.string().default('default').describe('Queue name'),\n \n /**\n * Task priority\n */\n priority: TaskPriority.default('normal').describe('Task priority level'),\n \n /**\n * Retry policy\n */\n retryPolicy: TaskRetryPolicySchema.optional().describe('Retry policy configuration'),\n \n /**\n * Execution timeout in milliseconds\n */\n timeoutMs: z.number().int().positive().optional().describe('Task timeout in milliseconds'),\n \n /**\n * Scheduled execution time\n */\n scheduledAt: z.string().datetime().optional().describe('ISO 8601 datetime to execute task'),\n \n /**\n * Maximum execution attempts\n */\n attempts: z.number().int().min(0).default(0).describe('Number of execution attempts'),\n \n /**\n * Task status\n */\n status: TaskStatus.default('pending').describe('Current task status'),\n \n /**\n * Task metadata\n */\n metadata: z.object({\n createdAt: z.string().datetime().optional().describe('When task was created'),\n updatedAt: z.string().datetime().optional().describe('Last update time'),\n createdBy: z.string().optional().describe('User who created task'),\n tags: z.array(z.string()).optional().describe('Task tags for filtering'),\n }).optional().describe('Task metadata'),\n});\n\nexport type Task = z.infer;\nexport type TaskInput = z.input;\n\n// ==========================================\n// Task Execution Result\n// ==========================================\n\n/**\n * Task Execution Result Schema\n * Result of a task execution attempt\n */\nexport const TaskExecutionResultSchema = z.object({\n /**\n * Task identifier\n */\n taskId: z.string().describe('Task identifier'),\n \n /**\n * Execution status\n */\n status: TaskStatus.describe('Execution status'),\n \n /**\n * Execution result data\n */\n result: z.unknown().optional().describe('Execution result data'),\n \n /**\n * Error information\n */\n error: z.object({\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Error stack trace'),\n code: z.string().optional().describe('Error code'),\n }).optional().describe('Error details if failed'),\n \n /**\n * Execution duration\n */\n durationMs: z.number().int().optional().describe('Execution duration in milliseconds'),\n \n /**\n * Execution timestamps\n */\n startedAt: z.string().datetime().describe('When execution started'),\n completedAt: z.string().datetime().optional().describe('When execution completed'),\n \n /**\n * Retry information\n */\n attempt: z.number().int().min(1).describe('Attempt number (1-indexed)'),\n willRetry: z.boolean().describe('Whether task will be retried'),\n});\n\nexport type TaskExecutionResult = z.infer;\n\n// ==========================================\n// Queue Configuration\n// ==========================================\n\n/**\n * Queue Configuration Schema\n * Configuration for a task queue\n * \n * @example\n * {\n * \"name\": \"notifications\",\n * \"concurrency\": 10,\n * \"rateLimit\": {\n * \"max\": 100,\n * \"duration\": 60000\n * }\n * }\n */\nexport const QueueConfigSchema = z.object({\n /**\n * Queue name\n */\n name: z.string().describe('Queue name (snake_case)'),\n \n /**\n * Maximum concurrent workers\n */\n concurrency: z.number().int().min(1).default(5).describe('Max concurrent task executions'),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n max: z.number().int().positive().describe('Maximum tasks per duration'),\n duration: z.number().int().positive().describe('Duration in milliseconds'),\n }).optional().describe('Rate limit configuration'),\n \n /**\n * Default retry policy\n */\n defaultRetryPolicy: TaskRetryPolicySchema.optional().describe('Default retry policy for tasks'),\n \n /**\n * Dead letter queue\n */\n deadLetterQueue: z.string().optional().describe('Dead letter queue name'),\n \n /**\n * Queue priority\n */\n priority: z.number().int().min(0).default(0).describe('Queue priority (lower = higher priority)'),\n \n /**\n * Auto-scaling configuration\n */\n autoScale: z.object({\n enabled: z.boolean().default(false).describe('Enable auto-scaling'),\n minWorkers: z.number().int().min(1).default(1).describe('Minimum workers'),\n maxWorkers: z.number().int().min(1).default(10).describe('Maximum workers'),\n scaleUpThreshold: z.number().int().positive().default(100).describe('Queue size to scale up'),\n scaleDownThreshold: z.number().int().min(0).default(10).describe('Queue size to scale down'),\n }).optional().describe('Auto-scaling configuration'),\n});\n\nexport type QueueConfig = z.infer;\nexport type QueueConfigInput = z.input;\n\n// ==========================================\n// Batch Processing\n// ==========================================\n\n/**\n * Batch Task Schema\n * Configuration for batch processing multiple items\n * \n * @example\n * {\n * \"id\": \"batch-import-123\",\n * \"type\": \"import_records\",\n * \"items\": [{ \"name\": \"Item 1\" }, { \"name\": \"Item 2\" }],\n * \"batchSize\": 100,\n * \"queue\": \"batch_processing\"\n * }\n */\nexport const BatchTaskSchema = z.object({\n /**\n * Batch job identifier\n */\n id: z.string().describe('Unique batch job identifier'),\n \n /**\n * Task type for processing each item\n */\n type: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Task type (snake_case)'),\n \n /**\n * Items to process\n */\n items: z.array(z.unknown()).describe('Array of items to process'),\n \n /**\n * Batch size (items per task)\n */\n batchSize: z.number().int().min(1).default(100).describe('Number of items per batch'),\n \n /**\n * Queue name\n */\n queue: z.string().default('batch').describe('Queue for batch tasks'),\n \n /**\n * Priority\n */\n priority: TaskPriority.default('normal').describe('Batch task priority'),\n \n /**\n * Parallel processing\n */\n parallel: z.boolean().default(true).describe('Process batches in parallel'),\n \n /**\n * Stop on error\n */\n stopOnError: z.boolean().default(false).describe('Stop batch if any item fails'),\n \n /**\n * Progress callback\n * \n * Called after each batch completes to report progress.\n * Invoked asynchronously and should not throw errors.\n * If the callback throws, the error is logged but batch processing continues.\n * \n * @param progress - Object containing processed count, total count, and failed count\n */\n onProgress: z.function()\n .input(z.tuple([z.object({\n processed: z.number(),\n total: z.number(),\n failed: z.number(),\n })]))\n .output(z.void())\n .optional()\n .describe('Progress callback function (called after each batch)'),\n});\n\nexport type BatchTask = z.infer;\nexport type BatchTaskInput = z.input;\n\n/**\n * Batch Progress Schema\n * Tracks progress of a batch job\n */\nexport const BatchProgressSchema = z.object({\n /**\n * Batch job identifier\n */\n batchId: z.string().describe('Batch job identifier'),\n \n /**\n * Total items\n */\n total: z.number().int().min(0).describe('Total number of items'),\n \n /**\n * Processed items\n */\n processed: z.number().int().min(0).default(0).describe('Items processed'),\n \n /**\n * Successful items\n */\n succeeded: z.number().int().min(0).default(0).describe('Items succeeded'),\n \n /**\n * Failed items\n */\n failed: z.number().int().min(0).default(0).describe('Items failed'),\n \n /**\n * Progress percentage\n */\n percentage: z.number().min(0).max(100).describe('Progress percentage'),\n \n /**\n * Status\n */\n status: z.enum(['pending', 'running', 'completed', 'failed', 'cancelled']).describe('Batch status'),\n \n /**\n * Timestamps\n */\n startedAt: z.string().datetime().optional().describe('When batch started'),\n completedAt: z.string().datetime().optional().describe('When batch completed'),\n});\n\nexport type BatchProgress = z.infer;\nexport type BatchProgressInput = z.input;\n\n// ==========================================\n// Worker Configuration\n// ==========================================\n\n/**\n * Worker Configuration Schema\n * Configuration for a worker instance\n */\nexport const WorkerConfigSchema = z.object({\n /**\n * Worker name\n */\n name: z.string().describe('Worker name'),\n \n /**\n * Queues to process\n */\n queues: z.array(z.string()).min(1).describe('Queue names to process'),\n \n /**\n * Queue configurations\n */\n queueConfigs: z.array(QueueConfigSchema).optional().describe('Queue configurations'),\n \n /**\n * Polling interval\n */\n pollIntervalMs: z.number().int().positive().default(1000).describe('Queue polling interval in milliseconds'),\n \n /**\n * Visibility timeout\n */\n visibilityTimeoutMs: z.number().int().positive().default(30000)\n .describe('How long a task is invisible after being claimed'),\n \n /**\n * Task timeout\n */\n defaultTimeoutMs: z.number().int().positive().default(300000).describe('Default task timeout in milliseconds'),\n \n /**\n * Graceful shutdown timeout\n */\n shutdownTimeoutMs: z.number().int().positive().default(30000)\n .describe('Graceful shutdown timeout in milliseconds'),\n \n /**\n * Task handlers\n */\n handlers: z.record(z.string(), z.function()).optional().describe('Task type handlers'),\n});\n\nexport type WorkerConfig = z.infer;\nexport type WorkerConfigInput = z.input;\n\n// ==========================================\n// Worker Stats\n// ==========================================\n\n/**\n * Worker Stats Schema\n * Runtime statistics for a worker\n */\nexport const WorkerStatsSchema = z.object({\n /**\n * Worker name\n */\n workerName: z.string().describe('Worker name'),\n \n /**\n * Total tasks processed\n */\n totalProcessed: z.number().int().min(0).describe('Total tasks processed'),\n \n /**\n * Successful tasks\n */\n succeeded: z.number().int().min(0).describe('Successful tasks'),\n \n /**\n * Failed tasks\n */\n failed: z.number().int().min(0).describe('Failed tasks'),\n \n /**\n * Active tasks\n */\n active: z.number().int().min(0).describe('Currently active tasks'),\n \n /**\n * Average execution time\n */\n avgExecutionMs: z.number().min(0).optional().describe('Average execution time in milliseconds'),\n \n /**\n * Uptime\n */\n uptimeMs: z.number().int().min(0).describe('Worker uptime in milliseconds'),\n \n /**\n * Queue stats\n */\n queues: z.record(z.string(), z.object({\n pending: z.number().int().min(0).describe('Pending tasks'),\n active: z.number().int().min(0).describe('Active tasks'),\n completed: z.number().int().min(0).describe('Completed tasks'),\n failed: z.number().int().min(0).describe('Failed tasks'),\n })).optional().describe('Per-queue statistics'),\n});\n\nexport type WorkerStats = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create a task\n */\nexport const Task = Object.assign(TaskSchema, {\n create: >(task: T) => task,\n});\n\n/**\n * Helper to create a queue config\n */\nexport const QueueConfig = Object.assign(QueueConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create a worker config\n */\nexport const WorkerConfig = Object.assign(WorkerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create a batch task\n */\nexport const BatchTask = Object.assign(BatchTaskSchema, {\n create: >(batch: T) => batch,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Email Template Schema\n * \n * Defines the structure and content of email notifications.\n * Supports variables for personalization and file attachments.\n * \n * @example\n * ```json\n * {\n * \"id\": \"welcome-email\",\n * \"subject\": \"Welcome to {{company_name}}\",\n * \"body\": \"

Welcome {{user_name}}!

\",\n * \"bodyType\": \"html\",\n * \"variables\": [\"company_name\", \"user_name\"],\n * \"attachments\": [\n * {\n * \"name\": \"guide.pdf\",\n * \"url\": \"https://example.com/guide.pdf\"\n * }\n * ]\n * }\n * ```\n */\nexport const EmailTemplateSchema = z.object({\n /**\n * Unique identifier for the email template\n */\n id: z.string().describe('Template identifier'),\n\n /**\n * Email subject line (supports variable interpolation)\n */\n subject: z.string().describe('Email subject'),\n\n /**\n * Email body content\n */\n body: z.string().describe('Email body content'),\n\n /**\n * Content type of the email body\n * @default 'html'\n */\n bodyType: z.enum(['text', 'html', 'markdown']).optional().default('html').describe('Body content type'),\n\n /**\n * List of template variables for dynamic content\n */\n variables: z.array(z.string()).optional().describe('Template variables'),\n\n /**\n * File attachments to include with the email\n */\n attachments: z.array(z.object({\n name: z.string().describe('Attachment filename'),\n url: z.string().url().describe('Attachment URL'),\n })).optional().describe('Email attachments'),\n});\n\n/**\n * SMS Template Schema\n * \n * Defines the structure of SMS text message notifications.\n * Includes character limits and variable support.\n * \n * @example\n * ```json\n * {\n * \"id\": \"verification-sms\",\n * \"message\": \"Your code is {{code}}\",\n * \"maxLength\": 160,\n * \"variables\": [\"code\"]\n * }\n * ```\n */\nexport const SMSTemplateSchema = z.object({\n /**\n * Unique identifier for the SMS template\n */\n id: z.string().describe('Template identifier'),\n\n /**\n * SMS message content (supports variable interpolation)\n */\n message: z.string().describe('SMS message content'),\n\n /**\n * Maximum character length for the SMS\n * @default 160\n */\n maxLength: z.number().optional().default(160).describe('Maximum message length'),\n\n /**\n * List of template variables for dynamic content\n */\n variables: z.array(z.string()).optional().describe('Template variables'),\n});\n\n/**\n * Push Notification Schema\n * \n * Defines mobile and web push notification structure.\n * Supports rich notifications with actions and badges.\n * \n * @example\n * ```json\n * {\n * \"title\": \"New Message\",\n * \"body\": \"You have a new message from John\",\n * \"icon\": \"https://example.com/icon.png\",\n * \"badge\": 5,\n * \"data\": {\"messageId\": \"msg_123\"},\n * \"actions\": [\n * {\"action\": \"view\", \"title\": \"View\"},\n * {\"action\": \"dismiss\", \"title\": \"Dismiss\"}\n * ]\n * }\n * ```\n */\nexport const PushNotificationSchema = z.object({\n /**\n * Notification title\n */\n title: z.string().describe('Notification title'),\n\n /**\n * Notification body text\n */\n body: z.string().describe('Notification body'),\n\n /**\n * Icon URL to display with notification\n */\n icon: z.string().url().optional().describe('Notification icon URL'),\n\n /**\n * Badge count to display on app icon\n */\n badge: z.number().optional().describe('Badge count'),\n\n /**\n * Custom data payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Custom data'),\n\n /**\n * Action buttons for the notification\n */\n actions: z.array(z.object({\n action: z.string().describe('Action identifier'),\n title: z.string().describe('Action button title'),\n })).optional().describe('Notification actions'),\n});\n\n/**\n * In-App Notification Schema\n * \n * Defines in-application notification banners and toasts.\n * Includes severity levels and auto-dismiss settings.\n * \n * @example\n * ```json\n * {\n * \"title\": \"System Update\",\n * \"message\": \"New features are now available\",\n * \"type\": \"info\",\n * \"actionUrl\": \"/updates\",\n * \"dismissible\": true,\n * \"expiresAt\": 1704067200000\n * }\n * ```\n */\nexport const InAppNotificationSchema = z.object({\n /**\n * Notification title\n */\n title: z.string().describe('Notification title'),\n\n /**\n * Notification message content\n */\n message: z.string().describe('Notification message'),\n\n /**\n * Notification severity type\n */\n type: z.enum(['info', 'success', 'warning', 'error']).describe('Notification type'),\n\n /**\n * Optional URL to navigate to when clicked\n */\n actionUrl: z.string().optional().describe('Action URL'),\n\n /**\n * Whether the notification can be dismissed by the user\n * @default true\n */\n dismissible: z.boolean().optional().default(true).describe('User dismissible'),\n\n /**\n * Timestamp when notification expires (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Expiration timestamp'),\n});\n\n/**\n * Notification Channel Enum\n * \n * Supported notification delivery channels.\n */\nexport const NotificationChannelSchema = z.enum([\n 'email',\n 'sms',\n 'push',\n 'in-app',\n 'slack',\n 'teams',\n 'webhook',\n]);\n\n/**\n * Notification Configuration Schema\n * \n * Unified notification management protocol supporting multiple channels.\n * Includes scheduling, retry policies, and delivery tracking.\n * \n * @example\n * ```json\n * {\n * \"id\": \"welcome-notification\",\n * \"name\": \"Welcome Email\",\n * \"channel\": \"email\",\n * \"template\": {\n * \"id\": \"tpl-001\",\n * \"subject\": \"Welcome!\",\n * \"body\": \"

Welcome

\",\n * \"bodyType\": \"html\"\n * },\n * \"recipients\": {\n * \"to\": [\"user@example.com\"],\n * \"cc\": [\"admin@example.com\"]\n * },\n * \"schedule\": {\n * \"type\": \"immediate\"\n * },\n * \"retryPolicy\": {\n * \"enabled\": true,\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * },\n * \"tracking\": {\n * \"trackOpens\": true,\n * \"trackClicks\": true,\n * \"trackDelivery\": true\n * }\n * }\n * ```\n */\nexport const NotificationConfigSchema = z.object({\n /**\n * Unique identifier for this notification configuration\n */\n id: z.string().describe('Notification ID'),\n\n /**\n * Human-readable name for this notification\n */\n name: z.string().describe('Notification name'),\n\n /**\n * Delivery channel for the notification\n */\n channel: NotificationChannelSchema.describe('Notification channel'),\n\n /**\n * Notification template based on channel type\n */\n template: z.union([\n EmailTemplateSchema,\n SMSTemplateSchema,\n PushNotificationSchema,\n InAppNotificationSchema,\n ]).describe('Notification template'),\n\n /**\n * Recipient configuration\n */\n recipients: z.object({\n /**\n * Primary recipients\n */\n to: z.array(z.string()).describe('Primary recipients'),\n\n /**\n * CC recipients (email only)\n */\n cc: z.array(z.string()).optional().describe('CC recipients'),\n\n /**\n * BCC recipients (email only)\n */\n bcc: z.array(z.string()).optional().describe('BCC recipients'),\n }).describe('Recipients'),\n\n /**\n * Scheduling configuration\n */\n schedule: z.object({\n /**\n * Scheduling type\n */\n type: z.enum(['immediate', 'delayed', 'scheduled']).describe('Schedule type'),\n\n /**\n * Delay in milliseconds (for delayed type)\n */\n delay: z.number().optional().describe('Delay in milliseconds'),\n\n /**\n * Scheduled send time (Unix timestamp in milliseconds)\n */\n scheduledAt: z.number().optional().describe('Scheduled timestamp'),\n }).optional().describe('Scheduling'),\n\n /**\n * Retry policy for failed deliveries\n */\n retryPolicy: z.object({\n /**\n * Enable automatic retries\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Enable retries'),\n\n /**\n * Maximum number of retry attempts\n * @default 3\n */\n maxRetries: z.number().optional().default(3).describe('Max retry attempts'),\n\n /**\n * Backoff strategy for retries\n */\n backoffStrategy: z.enum(['exponential', 'linear', 'fixed']).describe('Backoff strategy'),\n }).optional().describe('Retry policy'),\n\n /**\n * Delivery tracking configuration\n */\n tracking: z.object({\n /**\n * Track when emails are opened\n * @default false\n */\n trackOpens: z.boolean().optional().default(false).describe('Track opens'),\n\n /**\n * Track when links are clicked\n * @default false\n */\n trackClicks: z.boolean().optional().default(false).describe('Track clicks'),\n\n /**\n * Track delivery status\n * @default true\n */\n trackDelivery: z.boolean().optional().default(true).describe('Track delivery'),\n }).optional().describe('Tracking configuration'),\n});\n\n// Type exports\nexport type NotificationConfig = z.infer;\nexport type NotificationChannel = z.infer;\nexport type EmailTemplate = z.infer;\nexport type SMSTemplate = z.infer;\nexport type PushNotification = z.infer;\nexport type InAppNotification = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const LocaleSchema = z.string().describe('BCP-47 Language Tag (e.g. en-US, zh-CN)');\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-level Translation (per-object file)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Field Translation Schema\n * Translation data for a single field.\n */\nexport const FieldTranslationSchema = z.object({\n label: z.string().optional().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n placeholder: z.string().optional().describe('Translated placeholder text for form inputs'),\n options: z.record(z.string(), z.string()).optional().describe('Option value to translated label map'),\n}).describe('Translation data for a single field');\n\nexport type FieldTranslation = z.infer;\n\n/**\n * Object Translation Data Schema\n *\n * Translation data for a **single object** in a **single locale**.\n * Use this schema to validate per-object translation files.\n *\n * File convention: `i18n/{locale}/{object_name}.json`\n *\n * @example\n * ```json\n * // i18n/en/account.json\n * {\n * \"label\": \"Account\",\n * \"pluralLabel\": \"Accounts\",\n * \"fields\": {\n * \"name\": { \"label\": \"Account Name\", \"help\": \"Legal name\" },\n * \"type\": { \"label\": \"Type\", \"options\": { \"customer\": \"Customer\" } }\n * }\n * }\n * ```\n */\nexport const ObjectTranslationDataSchema = z.object({\n /** Translated singular label for the object */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label for the object */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional().describe('Field-level translations'),\n}).describe('Translation data for a single object');\n\nexport type ObjectTranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale-level Translation Data (per-locale aggregate)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Data Schema\n * Supports i18n for labels, messages, and options within a single locale.\n * Example structure:\n * ```json\n * {\n * \"objects\": { \"account\": { \"label\": \"Account\" } },\n * \"apps\": { \"crm\": { \"label\": \"CRM\" } },\n * \"messages\": { \"common.save\": \"Save\" }\n * }\n * ```\n */\nexport const TranslationDataSchema = z.object({\n /** Object translations */\n objects: z.record(z.string(), ObjectTranslationDataSchema).optional().describe('Object translations keyed by object name'),\n \n /** App/Menu translations */\n apps: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** UI Messages */\n messages: z.record(z.string(), z.string()).optional().describe('UI message translations keyed by message ID'),\n \n /** Validation Error Messages */\n validationMessages: z.record(z.string(), z.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {\"discount_limit\": \"折扣不能超过40%\"})'),\n}).describe('Translation data for objects, apps, and UI messages');\n\nexport type TranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Bundle (all locales)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const TranslationBundleSchema = z.record(LocaleSchema, TranslationDataSchema).describe('Map of locale codes to translation data');\n\nexport type TranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// File Organization Convention\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation File Organization Strategy\n *\n * Defines how translation files are organized on disk.\n *\n * - `bundled` — All locales in a single `TranslationBundle` file.\n * Best for small projects with few objects.\n * ```\n * src/translations/\n * crm.translation.ts # { en: {...}, \"zh-CN\": {...} }\n * ```\n *\n * - `per_locale` — One file per locale containing all namespaces.\n * Recommended when a single locale file stays under ~500 lines.\n * ```\n * src/translations/\n * en.ts # TranslationData for English\n * zh-CN.ts # TranslationData for Chinese\n * ```\n *\n * - `per_namespace` — One file per namespace (object) per locale.\n * Recommended for large projects with many objects/languages.\n * Aligns with Salesforce DX and ServiceNow conventions.\n * ```\n * i18n/\n * en/\n * account.json # ObjectTranslationData\n * contact.json\n * common.json # messages + app labels\n * zh-CN/\n * account.json\n * contact.json\n * common.json\n * ```\n */\nexport const TranslationFileOrganizationSchema = z.enum([\n 'bundled',\n 'per_locale',\n 'per_namespace',\n]).describe('Translation file organization strategy');\n\nexport type TranslationFileOrganization = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Configuration\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Configuration Schema\n *\n * Defines internationalization settings for the stack.\n *\n * @example\n * ```typescript\n * export default defineStack({\n * i18n: {\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'zh-CN', 'ja-JP'],\n * fallbackLocale: 'en',\n * fileOrganization: 'per_locale',\n * },\n * translations: [...],\n * });\n * ```\n */\n/**\n * Message format standard used for interpolation, pluralization, and\n * gender-aware translations.\n *\n * - `icu` — ICU MessageFormat (recommended for complex plurals, gender, select).\n * Strings may contain `{count, plural, one {# item} other {# items}}` patterns.\n * - `simple` — Simple `{variable}` interpolation only (default).\n */\nexport const MessageFormatSchema = z.enum([\n 'icu',\n 'simple',\n]).describe('Message interpolation format: ICU MessageFormat or simple {variable} replacement');\n\nexport type MessageFormat = z.infer;\n\nexport const TranslationConfigSchema = z.object({\n /** Default locale for the application */\n defaultLocale: LocaleSchema.describe('Default locale (e.g., \"en\")'),\n /** Supported BCP-47 locale codes */\n supportedLocales: z.array(LocaleSchema).describe('Supported BCP-47 locale codes'),\n /** Fallback locale when translation is not found */\n fallbackLocale: LocaleSchema.optional().describe('Fallback locale code'),\n /** How translation files are organized on disk */\n fileOrganization: TranslationFileOrganizationSchema.default('per_locale')\n .describe('File organization strategy'),\n /**\n * Message interpolation format.\n * When set to `'icu'`, messages and validationMessages are expected to use\n * ICU MessageFormat syntax (plurals, select, number/date skeletons).\n * @default 'simple'\n */\n messageFormat: MessageFormatSchema.default('simple')\n .describe('Message interpolation format (ICU MessageFormat or simple)'),\n /** Load translations on demand instead of eagerly */\n lazyLoad: z.boolean().default(false).describe('Load translations on demand'),\n /** Cache loaded translations in memory */\n cache: z.boolean().default(true).describe('Cache loaded translations'),\n}).describe('Internationalization configuration');\n\nexport type TranslationConfig = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-First Translation Node (object-first aggregated structure)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Translatable option map: option value → translated label */\nconst OptionTranslationMapSchema = z.record(z.string(), z.string())\n .describe('Option value to translated label map');\n\n/**\n * ObjectTranslationNodeSchema\n *\n * Object-first aggregated translation node that groups **all** translatable\n * content for a single object under one key. Aligns with Salesforce / Dynamics\n * conventions where translations are organized per-object rather than per-category.\n *\n * Located at `o.{object_name}` inside an {@link AppTranslationBundle}.\n *\n * @example\n * ```typescript\n * const accountNode: ObjectTranslationNode = {\n * label: '客户',\n * pluralLabel: '客户',\n * description: '客户管理对象',\n * fields: {\n * name: { label: '客户名称', help: '公司或组织的法定名称' },\n * industry: { label: '行业', options: { tech: '科技', finance: '金融' } },\n * },\n * _options: { status: { active: '活跃', inactive: '停用' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: {\n * convert_lead: { label: '转换线索', confirmMessage: '确认转换?' },\n * },\n * };\n * ```\n */\nexport const ObjectTranslationNodeSchema = z.object({\n /** Translated singular label */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Translated object description */\n description: z.string().optional().describe('Translated object description'),\n /** Translated help text shown in tooltips or guidance panels */\n helpText: z.string().optional().describe('Translated help text for the object'),\n\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional()\n .describe('Field translations keyed by field name'),\n\n /**\n * Global picklist / select option overrides scoped to this object.\n * Keyed by field name → { optionValue: translatedLabel }.\n */\n _options: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Object-scoped picklist option translations keyed by field name'),\n\n /** View translations keyed by view name */\n _views: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated view label'),\n description: z.string().optional().describe('Translated view description'),\n })).optional().describe('View translations keyed by view name'),\n\n /** Section (form section / tab) translations keyed by section name */\n _sections: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated section label'),\n })).optional().describe('Section translations keyed by section name'),\n\n /** Action translations keyed by action name */\n _actions: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated action label'),\n confirmMessage: z.string().optional().describe('Translated confirmation message'),\n })).optional().describe('Action translations keyed by action name'),\n\n /** Notification message translations keyed by notification name */\n _notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Notification translations keyed by notification name'),\n\n /** Error message translations keyed by error code */\n _errors: z.record(z.string(), z.string()).optional()\n .describe('Error message translations keyed by error code'),\n}).describe('Object-first aggregated translation node');\n\nexport type ObjectTranslationNode = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// App Translation Bundle (object-first, full application)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * AppTranslationBundleSchema\n *\n * Complete application translation bundle for a **single locale** using\n * the **object-first** convention. All per-object translatable content\n * is aggregated under `o.{object_name}`, while global (non-object-bound)\n * translations are kept in dedicated top-level groups.\n *\n * This schema is designed for:\n * - Translation workbench UIs (object-level editing & coverage)\n * - CLI skeleton generation (`objectstack i18n extract`)\n * - Automated diff/coverage detection\n *\n * @example\n * ```typescript\n * const zh: AppTranslationBundle = {\n * o: {\n * account: {\n * label: '客户',\n * fields: { name: { label: '客户名称' } },\n * _options: { industry: { tech: '科技' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: { convert: { label: '转换' } },\n * },\n * },\n * _globalOptions: { currency: { usd: '美元', eur: '欧元' } },\n * app: { crm: { label: '客户关系管理', description: '管理销售流程' } },\n * nav: { home: '首页', settings: '设置' },\n * dashboard: { sales_overview: { label: '销售概览' } },\n * reports: { pipeline_report: { label: '管道报表' } },\n * pages: { landing: { title: '欢迎' } },\n * messages: { 'common.save': '保存' },\n * validationMessages: { 'discount_limit': '折扣不能超过40%' },\n * };\n * ```\n */\nexport const AppTranslationBundleSchema = z.object({\n /**\n * Bundle-level metadata.\n * Provides locale-aware rendering hints such as text direction (bidi)\n * and the canonical locale code this bundle represents.\n */\n _meta: z.object({\n /** BCP-47 locale code this bundle represents */\n locale: z.string().optional().describe('BCP-47 locale code for this bundle'),\n /** Text direction for the locale */\n direction: z.enum(['ltr', 'rtl']).optional().describe('Text direction: left-to-right or right-to-left'),\n }).optional().describe('Bundle-level metadata (locale, bidi direction)'),\n\n /**\n * Namespace for plugin/extension isolation.\n * When multiple plugins contribute translations, each should use a unique\n * namespace to avoid key collisions (e.g. \"crm\", \"helpdesk\", \"plugin-xyz\").\n */\n namespace: z.string().optional()\n .describe('Namespace for plugin isolation to avoid translation key collisions'),\n\n /** Object-first translations keyed by object name (snake_case) */\n o: z.record(z.string(), ObjectTranslationNodeSchema).optional()\n .describe('Object-first translations keyed by object name'),\n\n /** Global picklist options not bound to any specific object */\n _globalOptions: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Global picklist option translations keyed by option set name'),\n\n /** App-level translations */\n app: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** Navigation menu translations */\n nav: z.record(z.string(), z.string()).optional()\n .describe('Navigation item translations keyed by nav item name'),\n\n /** Dashboard translations keyed by dashboard name */\n dashboard: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated dashboard label'),\n description: z.string().optional().describe('Translated dashboard description'),\n })).optional().describe('Dashboard translations keyed by dashboard name'),\n\n /** Report translations keyed by report name */\n reports: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated report label'),\n description: z.string().optional().describe('Translated report description'),\n })).optional().describe('Report translations keyed by report name'),\n\n /** Page translations keyed by page name */\n pages: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated page title'),\n description: z.string().optional().describe('Translated page description'),\n })).optional().describe('Page translations keyed by page name'),\n\n /** UI message translations (supports ICU MessageFormat when enabled) */\n messages: z.record(z.string(), z.string()).optional()\n .describe('UI message translations keyed by message ID (supports ICU MessageFormat)'),\n\n /** Validation error message translations (supports ICU MessageFormat when enabled) */\n validationMessages: z.record(z.string(), z.string()).optional()\n .describe('Validation error message translations keyed by rule name (supports ICU MessageFormat)'),\n\n /** Global notification translations not bound to a specific object */\n notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Global notification translations keyed by notification name'),\n\n /** Global error message translations not bound to a specific object */\n errors: z.record(z.string(), z.string()).optional()\n .describe('Global error message translations keyed by error code'),\n}).describe('Object-first application translation bundle for a single locale');\n\nexport type AppTranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Diff & Coverage\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Diff Status\n *\n * Status of a single translation entry compared to the source metadata.\n */\nexport const TranslationDiffStatusSchema = z.enum([\n 'missing',\n 'redundant',\n 'stale',\n]).describe('Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)');\n\nexport type TranslationDiffStatus = z.infer;\n\n/**\n * TranslationDiffItemSchema\n *\n * Describes a single translation key that is missing, redundant, or stale\n * relative to the source metadata. Used by CLI/API diff detection.\n *\n * @example\n * ```typescript\n * const item: TranslationDiffItem = {\n * key: 'o.account.fields.website.label',\n * status: 'missing',\n * objectName: 'account',\n * locale: 'zh-CN',\n * };\n * ```\n */\nexport const TranslationDiffItemSchema = z.object({\n /** Dot-path translation key (e.g. \"o.account.fields.website.label\") */\n key: z.string().describe('Dot-path translation key'),\n /** Diff status */\n status: TranslationDiffStatusSchema.describe('Diff status of this translation key'),\n /** Object name if the key belongs to an object translation node */\n objectName: z.string().optional().describe('Associated object name (snake_case)'),\n /** Locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /**\n * Hash of the source metadata value at the time the translation was made.\n * Used by CLI/Workbench to detect stale translations without a full diff.\n */\n sourceHash: z.string().optional().describe('Hash of source metadata for precise stale detection'),\n /**\n * AI-suggested translation text for missing or stale entries.\n * Populated by AI translation hooks or TMS integrations.\n */\n aiSuggested: z.string().optional().describe('AI-suggested translation for this key'),\n /** Confidence score (0-1) for the AI suggestion */\n aiConfidence: z.number().min(0).max(1).optional().describe('AI suggestion confidence score (0–1)'),\n}).describe('A single translation diff item');\n\nexport type TranslationDiffItem = z.infer;\n\n/**\n * TranslationCoverageResultSchema\n *\n * Aggregated coverage result for a locale, optionally scoped to a single object.\n * Returned by the i18n diff detection API.\n *\n * @example\n * ```typescript\n * const result: TranslationCoverageResult = {\n * locale: 'zh-CN',\n * totalKeys: 120,\n * translatedKeys: 105,\n * missingKeys: 12,\n * redundantKeys: 3,\n * staleKeys: 0,\n * coveragePercent: 87.5,\n * items: [ ... ],\n * };\n * ```\n */\n/**\n * Per-group coverage breakdown entry.\n */\nexport const CoverageBreakdownEntrySchema = z.object({\n /** Group category (e.g. \"fields\", \"views\", \"actions\", \"messages\") */\n group: z.string().describe('Translation group category'),\n /** Total translatable keys in this group */\n totalKeys: z.number().int().nonnegative().describe('Total keys in this group'),\n /** Number of translated keys in this group */\n translatedKeys: z.number().int().nonnegative().describe('Translated keys in this group'),\n /** Coverage percentage for this group */\n coveragePercent: z.number().min(0).max(100).describe('Coverage percentage for this group'),\n}).describe('Coverage breakdown for a single translation group');\n\nexport type CoverageBreakdownEntry = z.infer;\n\nexport const TranslationCoverageResultSchema = z.object({\n /** BCP-47 locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /** Optional object name scope */\n objectName: z.string().optional().describe('Object name scope (omit for full bundle)'),\n /** Total translatable keys derived from metadata */\n totalKeys: z.number().int().nonnegative().describe('Total translatable keys from metadata'),\n /** Number of keys that have a translation */\n translatedKeys: z.number().int().nonnegative().describe('Number of translated keys'),\n /** Number of missing translations */\n missingKeys: z.number().int().nonnegative().describe('Number of missing translations'),\n /** Number of redundant (orphaned) translations */\n redundantKeys: z.number().int().nonnegative().describe('Number of redundant translations'),\n /** Number of stale translations */\n staleKeys: z.number().int().nonnegative().describe('Number of stale translations'),\n /** Coverage percentage (0-100) */\n coveragePercent: z.number().min(0).max(100).describe('Translation coverage percentage'),\n /** Individual diff items */\n items: z.array(TranslationDiffItemSchema).describe('Detailed diff items'),\n /**\n * Per-group coverage breakdown for translation project management.\n * Each entry represents a logical group (e.g. \"fields\", \"views\", \"actions\",\n * \"messages\") with its own coverage statistics.\n */\n breakdown: z.array(CoverageBreakdownEntrySchema).optional()\n .describe('Per-group coverage breakdown'),\n}).describe('Aggregated translation coverage result');\n\nexport type TranslationCoverageResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Translation Skeleton Protocol Constants\n *\n * Defines the placeholder convention used in AI-friendly translation\n * skeleton templates. Runtime implementations (skeleton generation,\n * validation) belong in implementation packages (CLI, service-i18n, etc.).\n *\n * @example\n * ```json\n * {\n * \"label\": \"__TRANSLATE__: \\\"Task\\\"\",\n * \"fields\": {\n * \"subject\": { \"label\": \"__TRANSLATE__: \\\"Subject\\\"\" }\n * }\n * }\n * ```\n */\n\n/** Placeholder prefix used in translation skeleton output */\nexport const TRANSLATE_PLACEHOLDER = '__TRANSLATE__';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Real-Time Collaboration Protocol\n * \n * Defines schemas for real-time collaborative editing in ObjectStack.\n * Supports Operational Transformation (OT), CRDT (Conflict-free Replicated Data Types),\n * cursor sharing, and awareness state for collaborative applications.\n * \n * Industry alignment: Google Docs, Figma, VSCode Live Share, Yjs\n */\n\n// ==========================================\n// Operational Transformation (OT)\n// ==========================================\n\n/**\n * OT Operation Type Enum\n * Types of operations in Operational Transformation\n */\nexport const OTOperationType = z.enum([\n 'insert', // Insert characters at position\n 'delete', // Delete characters at position\n 'retain', // Keep characters (used for composing operations)\n]);\n\nexport type OTOperationType = z.infer;\n\n/**\n * OT Operation Component\n * Single component of an OT operation\n */\nexport const OTComponentSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('insert'),\n text: z.string().describe('Text to insert'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Text formatting attributes (e.g., bold, italic)'),\n }),\n z.object({\n type: z.literal('delete'),\n count: z.number().int().positive().describe('Number of characters to delete'),\n }),\n z.object({\n type: z.literal('retain'),\n count: z.number().int().positive().describe('Number of characters to retain'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Attribute changes to apply'),\n }),\n]);\n\nexport type OTComponent = z.infer;\n\n/**\n * OT Operation Schema\n * Represents a complete OT operation\n * Based on the OT algorithm used by Google Docs and other collaborative editors\n */\nexport const OTOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n documentId: z.string().describe('Document identifier'),\n userId: z.string().describe('User who created the operation'),\n sessionId: z.string().uuid().describe('Session identifier'),\n components: z.array(OTComponentSchema).describe('Operation components'),\n baseVersion: z.number().int().nonnegative().describe('Document version this operation is based on'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional operation metadata'),\n});\n\nexport type OTOperation = z.infer;\n\n/**\n * OT Transform Result\n * Result of transforming one operation against another\n */\nexport const OTTransformResultSchema = z.object({\n operation: OTOperationSchema.describe('Transformed operation'),\n transformed: z.boolean().describe('Whether transformation was applied'),\n conflicts: z.array(z.string()).optional().describe('Conflict descriptions if any'),\n});\n\nexport type OTTransformResult = z.infer;\n\n// ==========================================\n// CRDT (Conflict-free Replicated Data Types)\n// ==========================================\n\n/**\n * CRDT Type Enum\n * Types of CRDTs supported\n */\nexport const CRDTType = z.enum([\n 'lww-register', // Last-Write-Wins Register\n 'g-counter', // Grow-only Counter\n 'pn-counter', // Positive-Negative Counter\n 'g-set', // Grow-only Set\n 'or-set', // Observed-Remove Set\n 'lww-map', // Last-Write-Wins Map\n 'text', // CRDT-based Text (e.g., Yjs, Automerge)\n 'tree', // CRDT-based Tree structure\n 'json', // CRDT-based JSON (e.g., Automerge)\n]);\n\nexport type CRDTType = z.infer;\n\n/**\n * Vector Clock Schema\n * Tracks causality in distributed systems\n */\nexport const VectorClockSchema = z.object({\n clock: z.record(z.string(), z.number().int().nonnegative()).describe('Map of replica ID to logical timestamp'),\n});\n\nexport type VectorClock = z.infer;\n\n/**\n * LWW-Register Schema\n * Last-Write-Wins Register CRDT\n */\nexport const LWWRegisterSchema = z.object({\n type: z.literal('lww-register'),\n value: z.unknown().describe('Current register value'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of last write'),\n replicaId: z.string().describe('ID of replica that performed last write'),\n vectorClock: VectorClockSchema.optional().describe('Optional vector clock for causality tracking'),\n});\n\nexport type LWWRegister = z.infer;\n\n/**\n * Counter Operation Schema\n * Operations for Counter CRDTs\n */\nexport const CounterOperationSchema = z.object({\n replicaId: z.string().describe('Replica identifier'),\n delta: z.number().int().describe('Change amount (positive for increment, negative for decrement)'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of operation'),\n});\n\nexport type CounterOperation = z.infer;\n\n/**\n * G-Counter Schema\n * Grow-only Counter CRDT\n */\nexport const GCounterSchema = z.object({\n type: z.literal('g-counter'),\n counts: z.record(z.string(), z.number().int().nonnegative()).describe('Map of replica ID to count'),\n});\n\nexport type GCounter = z.infer;\n\n/**\n * PN-Counter Schema\n * Positive-Negative Counter CRDT (supports increment and decrement)\n */\nexport const PNCounterSchema = z.object({\n type: z.literal('pn-counter'),\n positive: z.record(z.string(), z.number().int().nonnegative()).describe('Positive increments per replica'),\n negative: z.record(z.string(), z.number().int().nonnegative()).describe('Negative increments per replica'),\n});\n\nexport type PNCounter = z.infer;\n\n/**\n * OR-Set Element Schema\n * Element in an Observed-Remove Set\n */\nexport const ORSetElementSchema = z.object({\n value: z.unknown().describe('Element value'),\n timestamp: z.string().datetime().describe('Addition timestamp'),\n replicaId: z.string().describe('Replica that added the element'),\n uid: z.string().uuid().describe('Unique identifier for this addition'),\n removed: z.boolean().optional().default(false).describe('Whether element has been removed'),\n});\n\nexport type ORSetElement = z.infer;\n\n/**\n * OR-Set Schema\n * Observed-Remove Set CRDT\n */\nexport const ORSetSchema = z.object({\n type: z.literal('or-set'),\n elements: z.array(ORSetElementSchema).describe('Set elements with metadata'),\n});\n\nexport type ORSet = z.infer;\n\n/**\n * Text CRDT Operation Schema\n * Operations for text-based CRDTs (e.g., Yjs, Automerge)\n */\nexport const TextCRDTOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n replicaId: z.string().describe('Replica identifier'),\n position: z.number().int().nonnegative().describe('Position in document'),\n insert: z.string().optional().describe('Text to insert'),\n delete: z.number().int().positive().optional().describe('Number of characters to delete'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of operation'),\n lamportTimestamp: z.number().int().nonnegative().describe('Lamport timestamp for ordering'),\n});\n\nexport type TextCRDTOperation = z.infer;\n\n/**\n * Text CRDT State Schema\n * State of a text-based CRDT document\n */\nexport const TextCRDTStateSchema = z.object({\n type: z.literal('text'),\n documentId: z.string().describe('Document identifier'),\n content: z.string().describe('Current text content'),\n operations: z.array(TextCRDTOperationSchema).describe('History of operations'),\n lamportClock: z.number().int().nonnegative().describe('Current Lamport clock value'),\n vectorClock: VectorClockSchema.describe('Vector clock for causality'),\n});\n\nexport type TextCRDTState = z.infer;\n\n/**\n * CRDT State Union\n * Discriminated union of all CRDT types\n */\nexport const CRDTStateSchema = z.discriminatedUnion('type', [\n LWWRegisterSchema,\n GCounterSchema,\n PNCounterSchema,\n ORSetSchema,\n TextCRDTStateSchema,\n]);\n\nexport type CRDTState = z.infer;\n\n/**\n * CRDT Merge Schema\n * Result of merging two CRDT states\n */\nexport const CRDTMergeResultSchema = z.object({\n state: CRDTStateSchema.describe('Merged CRDT state'),\n conflicts: z.array(z.object({\n type: z.string().describe('Conflict type'),\n description: z.string().describe('Conflict description'),\n resolved: z.boolean().describe('Whether conflict was automatically resolved'),\n })).optional().describe('Conflicts encountered during merge'),\n});\n\nexport type CRDTMergeResult = z.infer;\n\n// ==========================================\n// Cursor Sharing\n// ==========================================\n\n/**\n * Cursor Color Preset Enum\n * Standard color presets for cursor visualization\n */\nexport const CursorColorPreset = z.enum([\n 'blue',\n 'green',\n 'red',\n 'yellow',\n 'purple',\n 'orange',\n 'pink',\n 'teal',\n 'indigo',\n 'cyan',\n]);\n\nexport type CursorColorPreset = z.infer;\n\n/**\n * Cursor Style Schema\n * Visual styling for collaborative cursors\n */\nexport const CursorStyleSchema = z.object({\n color: z.union([CursorColorPreset, z.string()]).describe('Cursor color (preset or custom hex)'),\n opacity: z.number().min(0).max(1).optional().default(1).describe('Cursor opacity (0-1)'),\n label: z.string().optional().describe('Label to display with cursor (usually username)'),\n showLabel: z.boolean().optional().default(true).describe('Whether to show label'),\n pulseOnUpdate: z.boolean().optional().default(true).describe('Whether to pulse when cursor moves'),\n});\n\nexport type CursorStyle = z.infer;\n\n/**\n * Cursor Selection Schema\n * Represents a text selection in collaborative editing\n */\nexport const CursorSelectionSchema = z.object({\n anchor: z.object({\n line: z.number().int().nonnegative().describe('Anchor line number'),\n column: z.number().int().nonnegative().describe('Anchor column number'),\n }).describe('Selection anchor (start point)'),\n focus: z.object({\n line: z.number().int().nonnegative().describe('Focus line number'),\n column: z.number().int().nonnegative().describe('Focus column number'),\n }).describe('Selection focus (end point)'),\n direction: z.enum(['forward', 'backward']).optional().describe('Selection direction'),\n});\n\nexport type CursorSelection = z.infer;\n\n/**\n * Collaborative Cursor Schema\n * Complete cursor state for a collaborative user\n */\nexport const CollaborativeCursorSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier'),\n userName: z.string().describe('Display name of user'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Cursor line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Cursor column number (0-indexed)'),\n }).describe('Current cursor position'),\n selection: CursorSelectionSchema.optional().describe('Current text selection'),\n style: CursorStyleSchema.describe('Visual style for this cursor'),\n isTyping: z.boolean().optional().default(false).describe('Whether user is currently typing'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional cursor metadata'),\n});\n\nexport type CollaborativeCursor = z.infer;\n\n/**\n * Cursor Update Schema\n * Update to a collaborative cursor\n */\nexport const CursorUpdateSchema = z.object({\n position: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }).optional().describe('Updated cursor position'),\n selection: CursorSelectionSchema.optional().describe('Updated selection'),\n isTyping: z.boolean().optional().describe('Updated typing state'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type CursorUpdate = z.infer;\n\n// ==========================================\n// Awareness State\n// ==========================================\n\n/**\n * User Activity Status Enum\n * User activity status for awareness\n */\nexport const UserActivityStatus = z.enum([\n 'active', // User is actively editing\n 'idle', // User is idle but connected\n 'viewing', // User is viewing but not editing\n 'disconnected', // User is disconnected\n]);\n\nexport type UserActivityStatus = z.infer;\n\n/**\n * Awareness User State Schema\n * Tracks what a user is doing in the collaborative session\n */\nexport const AwarenessUserStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n userName: z.string().describe('Display name'),\n userAvatar: z.string().optional().describe('User avatar URL'),\n status: UserActivityStatus.describe('Current activity status'),\n currentDocument: z.string().optional().describe('Document ID user is currently editing'),\n currentView: z.string().optional().describe('Current view/page user is on'),\n lastActivity: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n joinedAt: z.string().datetime().describe('ISO 8601 datetime when user joined session'),\n permissions: z.array(z.string()).optional().describe('User permissions in this session'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional user state metadata'),\n});\n\nexport type AwarenessUserState = z.infer;\n\n/**\n * Awareness Session Schema\n * Represents the complete awareness state for a collaboration session\n */\nexport const AwarenessSessionSchema = z.object({\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().optional().describe('Document ID this session is for'),\n users: z.array(AwarenessUserStateSchema).describe('Active users in session'),\n startedAt: z.string().datetime().describe('ISO 8601 datetime when session started'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last update'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Session metadata'),\n});\n\nexport type AwarenessSession = z.infer;\n\n/**\n * Awareness Update Schema\n * Update to awareness state\n */\nexport const AwarenessUpdateSchema = z.object({\n status: UserActivityStatus.optional().describe('Updated status'),\n currentDocument: z.string().optional().describe('Updated current document'),\n currentView: z.string().optional().describe('Updated current view'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type AwarenessUpdate = z.infer;\n\n/**\n * Awareness Event Schema\n * Events that occur in awareness tracking\n */\nexport const AwarenessEventSchema = z.object({\n eventId: z.string().uuid().describe('Event identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n eventType: z.enum([\n 'user.joined',\n 'user.left',\n 'user.updated',\n 'session.created',\n 'session.ended',\n ]).describe('Type of awareness event'),\n userId: z.string().optional().describe('User involved in event'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of event'),\n payload: z.unknown().describe('Event payload'),\n});\n\nexport type AwarenessEvent = z.infer;\n\n// ==========================================\n// Collaboration Session Management\n// ==========================================\n\n/**\n * Collaboration Mode Enum\n * Types of collaboration modes\n */\nexport const CollaborationMode = z.enum([\n 'ot', // Operational Transformation\n 'crdt', // CRDT-based\n 'lock', // Pessimistic locking (turn-based)\n 'hybrid', // Hybrid approach\n]);\n\nexport type CollaborationMode = z.infer;\n\n/**\n * Collaboration Session Config\n * Configuration for a collaboration session\n */\nexport const CollaborationSessionConfigSchema = z.object({\n mode: CollaborationMode.describe('Collaboration mode to use'),\n enableCursorSharing: z.boolean().optional().default(true).describe('Enable cursor sharing'),\n enablePresence: z.boolean().optional().default(true).describe('Enable presence tracking'),\n enableAwareness: z.boolean().optional().default(true).describe('Enable awareness state'),\n maxUsers: z.number().int().positive().optional().describe('Maximum concurrent users'),\n idleTimeout: z.number().int().positive().optional().default(300000).describe('Idle timeout in milliseconds'),\n conflictResolution: z.enum(['ot', 'crdt', 'manual']).optional().default('ot').describe('Conflict resolution strategy'),\n persistence: z.boolean().optional().default(true).describe('Enable operation persistence'),\n snapshot: z.object({\n enabled: z.boolean().describe('Enable periodic snapshots'),\n interval: z.number().int().positive().describe('Snapshot interval in milliseconds'),\n }).optional().describe('Snapshot configuration'),\n});\n\nexport type CollaborationSessionConfig = z.infer;\n\n/**\n * Collaboration Session Schema\n * Complete collaboration session state\n */\nexport const CollaborationSessionSchema = z.object({\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier'),\n config: CollaborationSessionConfigSchema.describe('Session configuration'),\n users: z.array(AwarenessUserStateSchema).describe('Active users'),\n cursors: z.array(CollaborativeCursorSchema).describe('Active cursors'),\n version: z.number().int().nonnegative().describe('Current document version'),\n operations: z.array(z.union([OTOperationSchema, TextCRDTOperationSchema])).optional().describe('Recent operations'),\n createdAt: z.string().datetime().describe('ISO 8601 datetime when session was created'),\n lastActivity: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n status: z.enum(['active', 'idle', 'ended']).describe('Session status'),\n});\n\nexport type CollaborationSession = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metadata Scope Enum\n * Defines the lifecycle and mutability of a metadata item.\n */\nexport const MetadataScopeSchema = z.enum([\n 'system', // Defined in Code (Files). Read-only at runtime. Upgraded via deployment.\n 'platform', // Defined in DB (Global). admin-configured. Overrides system.\n 'user', // Defined in DB (Personal). User-configured. Overrides platform/system.\n]);\n\n/**\n * Metadata Lifecycle State\n */\nexport const MetadataStateSchema = z.enum([\n 'draft', // Work in progress, not active\n 'active', // Live and running\n 'archived', // Soft deleted\n 'deprecated' // Running but flagged for removal\n]);\n\n/**\n * Unified Metadata Persistence Protocol\n * \n * Defines the standardized envelope for storing ANY metadata item (Object, View, Flow)\n * in the database (e.g. `_framework_metadata` or generic `metadata` table).\n * \n * This treats \"Metadata as Data\".\n */\nexport const MetadataRecordSchema = z.object({\n /** Primary Key (UUID) */\n id: z.string(),\n \n /** \n * Machine Name \n * The unique identifier used in code references (e.g. \"account_list_view\").\n */\n name: z.string(),\n \n /**\n * Metadata Type\n * e.g. \"object\", \"view\", \"permission_set\", \"flow\"\n */\n type: z.string(),\n \n /**\n * Namespace / Module\n * Groups metadata into packages (e.g. \"crm\", \"finance\", \"core\").\n */\n namespace: z.string().default('default'),\n\n /**\n * Package Ownership Reference\n * Links this metadata record to the package that delivered it.\n * When set, the record is \"managed\" by the package and should not be\n * directly edited — customizations go through the overlay system.\n * Null/undefined means the record was created independently (not from a package).\n */\n packageId: z.string().optional().describe('Package ID that owns/delivered this metadata'),\n\n /**\n * Managed By Indicator\n * Determines who controls this metadata record's lifecycle.\n * - \"package\": Delivered and upgraded by a plugin package (read-only base)\n * - \"platform\": Created by platform admin via UI\n * - \"user\": Created by end user\n */\n managedBy: z.enum(['package', 'platform', 'user']).optional()\n .describe('Who manages this metadata record lifecycle'),\n \n /**\n * Ownership differentiation\n */\n scope: MetadataScopeSchema.default('platform'),\n \n /**\n * The Payload\n * Stores the actual configuration JSON.\n * This field holds the value of `ViewSchema`, `ObjectSchema`, etc.\n */\n metadata: z.record(z.string(), z.unknown()),\n\n /**\n * Extension / Merge Strategy\n * If this record overrides a system record, how should it be applied?\n */\n extends: z.string().optional().describe('Name of the parent metadata to extend/override'),\n strategy: z.enum(['merge', 'replace']).default('merge'),\n\n /** Owner (for user-scope items) */\n owner: z.string().optional(),\n \n /** State */\n state: MetadataStateSchema.default('active'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant isolation'),\n\n /** Version number for optimistic concurrency */\n version: z.number().default(1).describe('Record version for optimistic concurrency control'),\n\n /** Checksum for change detection */\n checksum: z.string().optional().describe('Content checksum for change detection'),\n\n /** Source origin marker */\n source: z.enum(['filesystem', 'database', 'api', 'migration']).optional().describe('Origin of this metadata record'),\n\n /** Classification tags */\n tags: z.array(z.string()).optional().describe('Classification tags for filtering and grouping'),\n \n /** Package Publishing */\n publishedDefinition: z.unknown().optional()\n .describe('Snapshot of the last published definition'),\n publishedAt: z.string().datetime().optional()\n .describe('When this metadata was last published'),\n publishedBy: z.string().optional()\n .describe('Who published this version'),\n\n /** Audit */\n createdBy: z.string().optional(),\n createdAt: z.string().datetime().optional().describe('Creation timestamp'),\n updatedBy: z.string().optional(),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n});\n\nexport type MetadataRecord = z.infer;\nexport type MetadataScope = z.infer;\n\n/**\n * Package Publish Result\n * Returned by `publishPackage()` after a package-level metadata publish operation.\n */\nexport const PackagePublishResultSchema = z.object({\n success: z.boolean().describe('Whether the publish succeeded'),\n packageId: z.string().describe('The package ID that was published'),\n version: z.number().int().describe('New version number after publish'),\n publishedAt: z.string().datetime().describe('Publish timestamp'),\n itemsPublished: z.number().int().describe('Total metadata items published'),\n validationErrors: z.array(z.object({\n type: z.string().describe('Metadata type that failed validation'),\n name: z.string().describe('Item name that failed validation'),\n message: z.string().describe('Validation error message'),\n })).optional().describe('Validation errors if publish failed'),\n});\n\nexport type PackagePublishResult = z.infer;\n\n/**\n * Metadata Format\n * Supported file formats for metadata serialization.\n */\nexport const MetadataFormatSchema = z.enum([\n 'json', 'yaml', 'yml', 'ts', 'js',\n 'typescript', 'javascript' // Aliases\n]);\n\n/**\n * Metadata Stats\n * Statistics about a metadata item.\n */\nexport const MetadataStatsSchema = z.object({\n path: z.string().optional(),\n size: z.number().optional(),\n mtime: z.string().datetime().optional(),\n hash: z.string().optional(),\n etag: z.string().optional(), // Required by local cache\n modifiedAt: z.string().datetime().optional(), // Alias for mtime\n format: MetadataFormatSchema.optional(), // Required for serialization\n});\n\n/**\n * Metadata Loader Contract\n * Describes the capabilities and identity of a metadata loader.\n */\nexport const MetadataLoaderContractSchema = z.object({\n name: z.string(),\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Loader protocol identifier'),\n description: z.string().optional(),\n supportedFormats: z.array(z.string()).optional(),\n supportsWatch: z.boolean().optional(),\n supportsWrite: z.boolean().optional(),\n supportsCache: z.boolean().optional(),\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n scope: MetadataScopeSchema.optional(),\n namespace: z.string().optional(),\n raw: z.boolean().optional().describe('Return raw file content instead of parsed JSON'),\n cache: z.boolean().optional(),\n useCache: z.boolean().optional(), // Alias for cache\n validate: z.boolean().optional(),\n ifNoneMatch: z.string().optional(), // For caching\n recursive: z.boolean().optional(),\n limit: z.number().optional(),\n patterns: z.array(z.string()).optional(),\n loader: z.string().optional().describe('Specific loader to use (e.g. filesystem, database)'),\n});\n\n/**\n * Metadata Load Result\n */\nexport const MetadataLoadResultSchema = z.object({\n data: z.unknown(),\n stats: MetadataStatsSchema.optional(),\n format: MetadataFormatSchema.optional(),\n source: z.string().optional(), // File path or URL\n fromCache: z.boolean().optional(),\n etag: z.string().optional(),\n notModified: z.boolean().optional(),\n loadTime: z.number().optional(),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n format: MetadataFormatSchema.optional(),\n create: z.boolean().default(true),\n overwrite: z.boolean().default(true),\n path: z.string().optional(),\n prettify: z.boolean().optional(),\n indent: z.number().optional(),\n sortKeys: z.boolean().optional(),\n backup: z.boolean().optional(),\n atomic: z.boolean().optional(),\n loader: z.string().optional().describe('Specific loader to use (e.g. filesystem, database)'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n success: z.boolean(),\n path: z.string().optional(),\n stats: MetadataStatsSchema.optional(),\n etag: z.string().optional(),\n size: z.number().optional(),\n saveTime: z.number().optional(),\n backupPath: z.string().optional(),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n type: z.enum(['add', 'change', 'unlink', 'added', 'changed', 'deleted']),\n path: z.string(),\n name: z.string().optional(),\n stats: MetadataStatsSchema.optional(),\n metadataType: z.string().optional(),\n data: z.unknown().optional(),\n timestamp: z.string().datetime().optional(),\n});\n\n/**\n * Metadata Collection Info\n */\nexport const MetadataCollectionInfoSchema = z.object({\n type: z.string(),\n count: z.number(),\n namespaces: z.array(z.string()),\n});\n\n/**\n * Metadata Export/Import Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n types: z.array(z.string()).optional(),\n namespaces: z.array(z.string()).optional(),\n output: z.string().describe('Output directory or file'),\n format: MetadataFormatSchema.default('json'),\n});\n\nexport const MetadataImportOptionsSchema = z.object({\n source: z.string().describe('Input directory or file'),\n strategy: z.enum(['merge', 'replace', 'skip']).default('merge'),\n validate: z.boolean().default(true),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Source Origin\n * Indicates where a metadata record was loaded from.\n */\nexport const MetadataSourceSchema = z.enum([\n 'filesystem', // Loaded from local files\n 'database', // Loaded from database via datasource\n 'api', // Loaded from remote API\n 'migration', // Created during a migration process\n]);\n\n/**\n * Metadata Manager Config\n * \n * Unified configuration for the MetadataManager.\n * Supports datasource-backed persistence via `datasource` field,\n * which references a DatasourceSchema.name resolved at runtime.\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n * When provided, metadata is persisted to a database table.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory for filesystem-based metadata'),\n\n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).optional().describe('Enabled metadata formats'),\n\n /**\n * Enable file watching\n */\n watch: z.boolean().optional().describe('Enable file watching for filesystem loaders'),\n\n /**\n * Cache configuration\n */\n cache: z.boolean().optional().describe('Enable metadata caching'),\n\n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n }).optional().describe('File watcher options'),\n});\n\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataLoadOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\nexport type MetadataSource = z.infer;\n\n/**\n * Metadata History Record\n *\n * Represents a single version snapshot in the metadata change history.\n * Stored in the sys_metadata_history table for version tracking and rollback.\n */\nexport const MetadataHistoryRecordSchema = z.object({\n /** Primary Key (UUID) */\n id: z.string(),\n\n /** Reference to the parent metadata record ID */\n metadataId: z.string().describe('Foreign key to sys_metadata.id'),\n\n /**\n * Machine Name\n * Denormalized from parent for easier querying.\n */\n name: z.string(),\n\n /**\n * Metadata Type\n * Denormalized from parent for easier querying.\n */\n type: z.string(),\n\n /**\n * Version Number\n * Snapshot of the metadata version at this point in history.\n */\n version: z.number().describe('Version number at this snapshot'),\n\n /**\n * Operation Type\n * Indicates what kind of change triggered this history record.\n */\n operationType: z.enum(['create', 'update', 'publish', 'revert', 'delete']).describe('Type of operation that created this history entry'),\n\n /**\n * Historical Metadata Snapshot\n * Full JSON payload of the metadata definition at this version.\n * May be stored as a raw JSON string in the history table, or as a parsed object\n * in higher-level APIs. When `includeMetadata` is false, this field is null.\n */\n metadata: z\n .union([z.string(), z.record(z.string(), z.unknown())])\n .nullable()\n .optional()\n .describe('Snapshot of metadata definition at this version (raw JSON string or parsed object)'),\n\n /**\n * Content Checksum\n * SHA-256 checksum of the normalized metadata JSON for change detection.\n */\n checksum: z.string().describe('SHA-256 checksum of metadata content'),\n\n /**\n * Previous Checksum\n * Checksum of the previous version for diff optimization.\n */\n previousChecksum: z.string().optional().describe('Checksum of the previous version'),\n\n /**\n * Change Note\n * Human-readable description of what changed in this version.\n */\n changeNote: z.string().optional().describe('Description of changes made in this version'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant isolation'),\n\n /** Audit: who made this change */\n recordedBy: z.string().optional().describe('User who made this change'),\n\n /** Audit: when was this version recorded */\n recordedAt: z.string().datetime().describe('Timestamp when this version was recorded'),\n});\n\nexport type MetadataHistoryRecord = z.infer;\n\n/**\n * Metadata History Query Options\n * Options for retrieving metadata version history.\n */\nexport const MetadataHistoryQueryOptionsSchema = z.object({\n /** Limit number of history records returned */\n limit: z.number().int().positive().optional().describe('Maximum number of history records to return'),\n\n /** Offset for pagination */\n offset: z.number().int().nonnegative().optional().describe('Number of records to skip'),\n\n /** Only return versions after this timestamp */\n since: z.string().datetime().optional().describe('Only return history after this timestamp'),\n\n /** Only return versions before this timestamp */\n until: z.string().datetime().optional().describe('Only return history before this timestamp'),\n\n /** Filter by operation type */\n operationType: z.enum(['create', 'update', 'publish', 'revert', 'delete']).optional().describe('Filter by operation type'),\n\n /** Include full metadata payload in results (default: true) */\n includeMetadata: z.boolean().optional().default(true).describe('Include full metadata payload'),\n});\n\nexport type MetadataHistoryQueryOptions = z.infer;\n\n/**\n * Metadata History Query Result\n * Result of querying metadata version history.\n */\nexport const MetadataHistoryQueryResultSchema = z.object({\n /** Array of history records */\n records: z.array(MetadataHistoryRecordSchema),\n\n /** Total number of history records (for pagination) */\n total: z.number().int().nonnegative(),\n\n /** Whether there are more records available */\n hasMore: z.boolean(),\n});\n\nexport type MetadataHistoryQueryResult = z.infer;\n\n/**\n * Metadata Diff Result\n * Result of comparing two versions of metadata.\n */\nexport const MetadataDiffResultSchema = z.object({\n /** Metadata type */\n type: z.string(),\n\n /** Metadata name */\n name: z.string(),\n\n /** Version 1 (older) */\n version1: z.number(),\n\n /** Version 2 (newer) */\n version2: z.number(),\n\n /** Checksum of version 1 */\n checksum1: z.string(),\n\n /** Checksum of version 2 */\n checksum2: z.string(),\n\n /** Whether the versions are identical */\n identical: z.boolean(),\n\n /** JSON patch operations to transform v1 into v2 */\n patch: z.array(z.unknown()).optional().describe('JSON patch operations'),\n\n /** Human-readable diff summary */\n summary: z.string().optional().describe('Human-readable summary of changes'),\n});\n\nexport type MetadataDiffResult = z.infer;\n\n/**\n * Metadata History Retention Policy\n * Configuration for automatic cleanup of old history records.\n */\nexport const MetadataHistoryRetentionPolicySchema = z.object({\n /** Maximum number of versions to keep per metadata item */\n maxVersions: z.number().int().positive().optional().describe('Maximum number of versions to retain'),\n\n /** Maximum age of history records in days */\n maxAgeDays: z.number().int().positive().optional().describe('Maximum age of history records in days'),\n\n /** Whether to enable automatic cleanup */\n autoCleanup: z.boolean().default(false).describe('Enable automatic cleanup of old history'),\n\n /** Cleanup interval in hours */\n cleanupIntervalHours: z.number().int().positive().default(24).describe('How often to run cleanup (in hours)'),\n});\n\nexport type MetadataHistoryRetentionPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Service Registry Protocol\n * \n * Defines the standard built-in services that constitute the ObjectStack Kernel.\n * This registry is used by the `ObjectKernel` and `HttpDispatcher` to:\n * 1. Verify service availability.\n * 2. Route requests to the correct service handler.\n * 3. Type-check service interactions.\n */\n\n// ==========================================\n// Service Identifiers\n// ==========================================\n\nexport const CoreServiceName = z.enum([\n // Core Data & Metadata\n 'metadata', // Object/Field Definitions\n 'data', // CRUD & Query Engine\n 'auth', // Authentication & Identity\n \n // Infrastructure\n 'file-storage', // Storage Driver (Local/S3)\n 'search', // Search Engine (Elastic/Meili)\n 'cache', // Cache Driver (Redis/Memory)\n 'queue', // Job Queue (BullMQ/Redis)\n \n // Advanced Capabilities\n 'automation', // Flow & Script Engine\n 'graphql', // GraphQL API Engine\n 'analytics', // BI & Semantic Layer\n 'realtime', // WebSocket & PubSub\n 'job', // Background Job Manager\n 'notification', // Email/Push/SMS\n 'ai', // AI Engine (NLQ, Chat, Suggest, Insights)\n 'i18n', // Internationalization Service\n 'ui', // UI Metadata Service (View CRUD)\n 'workflow', // Workflow State Machine Engine\n]);\n\nexport type CoreServiceName = z.infer;\n\n/**\n * Service Criticality Level\n * Defines the startup behavior when a service is missing.\n */\nexport const ServiceCriticalitySchema = z.enum([\n 'required', // System fails to start if missing (Exit Code 1)\n 'core', // System warns if missing, functionality degraded (Warn)\n 'optional', // System ignores if missing, feature disabled (Info)\n]);\n\n/**\n * Service Requirement Definition\n */\nexport const ServiceRequirementDef = {\n // Required: The kernel cannot function without these\n data: 'required',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n metadata: 'core',\n auth: 'core',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n cache: 'core',\n queue: 'core',\n job: 'core',\n i18n: 'core',\n\n // Optional: Add-on capabilities\n 'file-storage': 'optional',\n search: 'optional',\n automation: 'optional',\n graphql: 'optional',\n analytics: 'optional',\n realtime: 'optional',\n notification: 'optional',\n ai: 'optional',\n ui: 'optional',\n workflow: 'optional',\n} as const;\n\n// ==========================================\n// Service Capabilities\n// ==========================================\n\n/**\n * Describes the availability and health of a service\n */\nexport const ServiceStatusSchema = z.object({\n name: CoreServiceName,\n enabled: z.boolean(),\n status: z.enum(['running', 'stopped', 'degraded', 'initializing']),\n version: z.string().optional(),\n provider: z.string().optional().describe('Implementation provider (e.g. \"s3\" for storage)'),\n features: z.array(z.string()).optional().describe('List of supported sub-features'),\n});\n\n/**\n * The Contract definition for what the Kernel MUST expose\n * map\n */\nexport const KernelServiceMapSchema = z.record(\n CoreServiceName, \n z.unknown().describe('Service Instance implementing the protocol interface')\n);\n\n// ==========================================\n// Service Interfaces (Stub definitions)\n// ==========================================\n// Ideally, we would define strict Typescript interfaces here \n// for what methods each service must expose to the Registry.\n// For Zod, we primarily validate configuration and status.\n\n// e.g.\nexport const ServiceConfigSchema = z.object({\n id: z.string(),\n name: CoreServiceName,\n options: z.record(z.string(), z.unknown()).optional(),\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Schema (Multi-Tenant Architecture)\n * \n * Defines the tenant/tenancy model for ObjectStack SaaS deployments.\n * Supports different levels of data isolation to meet varying security,\n * performance, and compliance requirements.\n * \n * Isolation Levels:\n * - shared_schema: All tenants share the same database and schema (row-level isolation)\n * - isolated_schema: Tenants have separate schemas within a shared database\n * - isolated_db: Each tenant has a completely separate database\n */\n\n/**\n * Tenant Isolation Level Enum\n * Defines how tenant data is separated in the system\n */\nexport const TenantIsolationLevel = z.enum([\n 'shared_schema', // Shared DB, shared schema, row-level isolation (most economical)\n 'isolated_schema', // Shared DB, separate schema per tenant (balanced)\n 'isolated_db', // Separate database per tenant (maximum isolation)\n]);\n\nexport type TenantIsolationLevel = z.infer;\n\n/**\n * Database Provider Enum\n * Defines which database backend is used for the tenant\n */\nexport const DatabaseProviderSchema = z.enum([\n 'turso', // Turso/libSQL (DB-per-Tenant, edge-native)\n 'postgres', // PostgreSQL (traditional, self-hosted or managed)\n 'memory', // In-memory (testing/development only)\n]).describe('Database provider for tenant data');\n\nexport type DatabaseProvider = z.infer;\n\n/**\n * Tenant Connection Config Schema\n * Stores the database connection details for a tenant (encrypted at rest)\n */\nexport const TenantConnectionConfigSchema = z.object({\n /** Database connection URL */\n url: z.string().min(1).describe('Database connection URL'),\n /** Authentication token (JWT for Turso, password for Postgres) */\n authToken: z.string().optional().describe('Database auth token (encrypted at rest)'),\n /** Turso database group name */\n group: z.string().optional().describe('Turso database group name'),\n}).describe('Tenant database connection configuration');\n\nexport type TenantConnectionConfig = z.infer;\n\n/**\n * Tenant Quota Schema\n * Defines resource limits and usage quotas for a tenant\n */\nexport const TenantQuotaSchema = z.object({\n /**\n * Maximum number of users allowed for this tenant\n */\n maxUsers: z.number().int().positive().optional().describe('Maximum number of users'),\n \n /**\n * Maximum storage space in bytes\n */\n maxStorage: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n \n /**\n * API rate limit (requests per minute)\n */\n apiRateLimit: z.number().int().positive().optional().describe('API requests per minute'),\n\n /**\n * Maximum number of custom objects the tenant can create\n */\n maxObjects: z.number().int().positive().optional().describe('Maximum number of custom objects'),\n\n /**\n * Maximum records per object/table\n */\n maxRecordsPerObject: z.number().int().positive().optional().describe('Maximum records per object'),\n\n /**\n * Maximum deployments allowed per day\n */\n maxDeploymentsPerDay: z.number().int().positive().optional().describe('Maximum deployments per day'),\n\n /**\n * Maximum storage in bytes\n */\n maxStorageBytes: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n});\n\nexport type TenantQuota = z.infer;\n\n/**\n * Tenant Usage Schema\n * Tracks current resource usage for quota enforcement\n */\nexport const TenantUsageSchema = z.object({\n /** Current number of custom objects */\n currentObjectCount: z.number().int().min(0).default(0).describe('Current number of custom objects'),\n /** Current total record count across all objects */\n currentRecordCount: z.number().int().min(0).default(0).describe('Total records across all objects'),\n /** Current storage usage in bytes */\n currentStorageBytes: z.number().int().min(0).default(0).describe('Current storage usage in bytes'),\n /** Deployments executed today */\n deploymentsToday: z.number().int().min(0).default(0).describe('Deployments executed today'),\n /** Current number of active users */\n currentUsers: z.number().int().min(0).default(0).describe('Current number of active users'),\n /** API requests in the current minute */\n apiRequestsThisMinute: z.number().int().min(0).default(0).describe('API requests in the current minute'),\n /** Last updated timestamp (ISO 8601) */\n lastUpdatedAt: z.string().datetime().optional().describe('Last usage update time'),\n}).describe('Current tenant resource usage');\n\nexport type TenantUsage = z.infer;\n\n/**\n * Quota Enforcement Result\n * Result of checking whether an operation would exceed tenant quotas\n */\nexport const QuotaEnforcementResultSchema = z.object({\n /** Whether the operation is allowed */\n allowed: z.boolean().describe('Whether the operation is within quota'),\n /** Quota that would be exceeded (if not allowed) */\n exceededQuota: z.string().optional().describe('Name of the exceeded quota'),\n /** Current usage value */\n currentUsage: z.number().optional().describe('Current usage value'),\n /** Quota limit value */\n limit: z.number().optional().describe('Quota limit'),\n /** Human-readable message */\n message: z.string().optional().describe('Human-readable quota message'),\n}).describe('Quota enforcement check result');\n\nexport type QuotaEnforcementResult = z.infer;\n\n/**\n * Tenant Schema\n * \n * @deprecated This schema is maintained for backward compatibility only.\n * New implementations should use HubSpaceSchema which embeds tenant concepts.\n * \n * **Migration Guide:**\n * ```typescript\n * // Old approach (deprecated):\n * const tenant: Tenant = {\n * id: 'tenant_123',\n * name: 'My Tenant',\n * isolationLevel: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * };\n * \n * // New approach (recommended):\n * const space: HubSpace = {\n * id: '...uuid...',\n * name: 'My Tenant',\n * slug: 'my-tenant',\n * ownerId: 'user_id',\n * runtime: {\n * isolation: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * },\n * bom: { ... }\n * };\n * ```\n * \n * See HubSpaceSchema in space.zod.ts for the recommended approach.\n */\nexport const TenantSchema = z.object({\n /**\n * Unique tenant identifier\n */\n id: z.string().describe('Unique tenant identifier'),\n \n /**\n * Tenant display name\n */\n name: z.string().describe('Tenant display name'),\n \n /**\n * Data isolation level\n */\n isolationLevel: TenantIsolationLevel,\n\n /**\n * Database provider for this tenant\n */\n databaseProvider: DatabaseProviderSchema.optional().describe('Database provider'),\n\n /**\n * Database connection configuration (encrypted at rest)\n */\n connectionConfig: TenantConnectionConfigSchema.optional().describe('Database connection config'),\n\n /**\n * Current provisioning status\n */\n provisioningStatus: z.enum([\n 'provisioning', 'active', 'suspended', 'failed', 'destroying',\n ]).optional().describe('Current provisioning lifecycle status'),\n\n /**\n * Tenant subscription plan\n */\n plan: z.enum(['free', 'pro', 'enterprise']).optional().describe('Subscription plan'),\n \n /**\n * Custom configuration values\n */\n customizations: z.record(z.string(), z.unknown()).optional().describe('Custom configuration values'),\n \n /**\n * Resource quotas\n */\n quotas: TenantQuotaSchema.optional(),\n});\n\nexport type Tenant = z.infer;\n\n/**\n * Tenant Isolation Strategy Documentation\n * \n * Comprehensive documentation of three isolation strategies for multi-tenant systems.\n * Each strategy has different trade-offs in terms of security, cost, complexity, and compliance.\n */\n\n/**\n * Row-Level Isolation Strategy (shared_schema)\n * \n * Recommended for: Most SaaS applications, cost-sensitive deployments\n * \n * IMPLEMENTATION:\n * - All tenants share the same database and schema\n * - Each table includes a tenant_id column\n * - PostgreSQL Row-Level Security (RLS) enforces isolation\n * - Queries automatically filter by tenant_id via RLS policies\n * \n * ADVANTAGES:\n * ✅ Simple backup and restore (single database)\n * ✅ Cost-effective (shared resources, minimal overhead)\n * ✅ Easy tenant migration (update tenant_id)\n * ✅ Efficient resource utilization (connection pooling)\n * ✅ Simple schema migrations (single schema to update)\n * ✅ Lower operational complexity\n * \n * DISADVANTAGES:\n * ❌ RLS misconfiguration can lead to data leakage\n * ❌ Performance impact from RLS policy evaluation\n * ❌ Noisy neighbor problem (one tenant can affect others)\n * ❌ Cannot easily isolate tenant to different hardware\n * ❌ Compliance challenges for regulated industries\n * \n * SECURITY CONSIDERATIONS:\n * - Requires careful RLS policy configuration\n * - Must validate tenant_id in all queries\n * - Need comprehensive testing of RLS policies\n * - Audit all database access patterns\n * - Implement application-level validation as defense-in-depth\n * \n * EXAMPLE RLS POLICY (PostgreSQL):\n * ```sql\n * -- Example: Apply RLS policy to a table (e.g., \"app_data\")\n * CREATE POLICY tenant_isolation ON app_data\n * USING (tenant_id = current_setting('app.current_tenant')::text);\n * \n * ALTER TABLE app_data ENABLE ROW LEVEL SECURITY;\n * ```\n */\nexport const RowLevelIsolationStrategySchema = z.object({\n strategy: z.literal('shared_schema').describe('Row-level isolation strategy'),\n \n /**\n * Database configuration for row-level isolation\n */\n database: z.object({\n /**\n * Whether to enable Row-Level Security (RLS)\n */\n enableRLS: z.boolean().default(true).describe('Enable PostgreSQL Row-Level Security'),\n \n /**\n * Tenant context setting method\n */\n contextMethod: z.enum([\n 'session_variable', // SET app.current_tenant = 'tenant_123'\n 'search_path', // SET search_path = tenant_123, public\n 'application_name', // SET application_name = 'tenant_123'\n ]).default('session_variable').describe('How to set tenant context'),\n \n /**\n * Session variable name for tenant context\n */\n contextVariable: z.string().default('app.current_tenant').describe('Session variable name'),\n \n /**\n * Whether to validate tenant_id at application level\n */\n applicationValidation: z.boolean().default(true).describe('Application-level tenant validation'),\n }).optional().describe('Database configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use partial indexes for tenant_id\n */\n usePartialIndexes: z.boolean().default(true).describe('Use partial indexes per tenant'),\n \n /**\n * Whether to use table partitioning\n */\n usePartitioning: z.boolean().default(false).describe('Use table partitioning by tenant_id'),\n \n /**\n * Connection pool size per tenant\n */\n poolSizePerTenant: z.number().int().positive().optional().describe('Connection pool size per tenant'),\n }).optional().describe('Performance settings'),\n});\n\nexport type RowLevelIsolationStrategy = z.infer;\nexport type RowLevelIsolationStrategyInput = z.input;\n\n/**\n * Schema-Level Isolation Strategy (isolated_schema)\n * \n * Recommended for: Enterprise SaaS, B2B platforms with compliance needs\n * \n * IMPLEMENTATION:\n * - All tenants share the same database server\n * - Each tenant has a separate database schema\n * - Schema name typically: tenant_\n * - Application switches schema using SET search_path\n * \n * ADVANTAGES:\n * ✅ Better isolation than row-level (schema boundaries)\n * ✅ Easier to debug (separate schemas)\n * ✅ Can grant different database permissions per schema\n * ✅ Reduced risk of data leakage\n * ✅ Performance isolation (indexes, statistics per schema)\n * ✅ Simplified queries (no tenant_id filtering needed)\n * \n * DISADVANTAGES:\n * ❌ More complex backups (must backup all schemas)\n * ❌ Higher migration costs (schema changes across all tenants)\n * ❌ Schema proliferation (PostgreSQL has limits)\n * ❌ Connection overhead (switching schemas)\n * ❌ More complex monitoring and maintenance\n * \n * SECURITY CONSIDERATIONS:\n * - Ensure proper schema permissions (GRANT USAGE ON SCHEMA)\n * - Validate schema name to prevent SQL injection\n * - Implement connection-level schema switching\n * - Audit schema access patterns\n * - Prevent cross-schema queries in application\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant schema\n * CREATE SCHEMA tenant_123;\n * \n * -- Grant access\n * GRANT USAGE ON SCHEMA tenant_123 TO app_user;\n * \n * -- Switch to tenant schema\n * SET search_path TO tenant_123, public;\n * ```\n */\nexport const SchemaLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_schema').describe('Schema-level isolation strategy'),\n \n /**\n * Schema configuration\n */\n schema: z.object({\n /**\n * Schema naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Schema naming pattern'),\n \n /**\n * Whether to include public schema in search_path\n */\n includePublicSchema: z.boolean().default(true).describe('Include public schema'),\n \n /**\n * Default schema for shared resources\n */\n sharedSchema: z.string().default('public').describe('Schema for shared resources'),\n \n /**\n * Whether to automatically create schema on tenant creation\n */\n autoCreateSchema: z.boolean().default(true).describe('Auto-create schema'),\n }).optional().describe('Schema configuration'),\n \n /**\n * Migration configuration\n */\n migrations: z.object({\n /**\n * Migration strategy\n */\n strategy: z.enum([\n 'parallel', // Run migrations on all schemas in parallel\n 'sequential', // Run migrations one schema at a time\n 'on_demand', // Run migrations when tenant accesses system\n ]).default('parallel').describe('Migration strategy'),\n \n /**\n * Maximum concurrent migrations\n */\n maxConcurrent: z.number().int().positive().default(10).describe('Max concurrent migrations'),\n \n /**\n * Whether to rollback on first failure\n */\n rollbackOnError: z.boolean().default(true).describe('Rollback on error'),\n }).optional().describe('Migration configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use connection pooling per schema\n */\n poolPerSchema: z.boolean().default(false).describe('Separate pool per schema'),\n \n /**\n * Schema cache TTL in seconds\n */\n schemaCacheTTL: z.number().int().positive().default(3600).describe('Schema cache TTL'),\n }).optional().describe('Performance settings'),\n});\n\nexport type SchemaLevelIsolationStrategy = z.infer;\nexport type SchemaLevelIsolationStrategyInput = z.input;\n\n/**\n * Database-Level Isolation Strategy (isolated_db)\n * \n * Recommended for: Regulated industries (healthcare, finance), strict compliance requirements\n * \n * IMPLEMENTATION:\n * - Each tenant has a completely separate database\n * - Database name typically: tenant_\n * - Requires separate connection pool per tenant\n * - Complete physical and logical isolation\n * \n * ADVANTAGES:\n * ✅ Perfect data isolation (strongest security)\n * ✅ Meets strict regulatory requirements (HIPAA, SOX, PCI-DSS)\n * ✅ Complete performance isolation (no noisy neighbors)\n * ✅ Can place databases on different hardware\n * ✅ Easy to backup/restore individual tenant\n * ✅ Simplified compliance auditing per tenant\n * ✅ Can apply different encryption keys per database\n * \n * DISADVANTAGES:\n * ❌ Most expensive option (resource overhead)\n * ❌ Complex database server management (many databases)\n * ❌ Connection pool limits (max connections per server)\n * ❌ Difficult cross-tenant analytics\n * ❌ Higher operational complexity\n * ❌ Schema migrations take longer (many databases)\n * \n * SECURITY CONSIDERATIONS:\n * - Each database can have separate credentials\n * - Enables per-tenant encryption at rest\n * - Simplifies compliance and audit trails\n * - Prevents any cross-tenant data access\n * - Supports tenant-specific backup schedules\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant database\n * CREATE DATABASE tenant_123\n * WITH OWNER = tenant_123_user\n * ENCODING = 'UTF8'\n * LC_COLLATE = 'en_US.UTF-8'\n * LC_CTYPE = 'en_US.UTF-8';\n * \n * -- Connect to tenant database\n * \\c tenant_123\n * ```\n */\nexport const DatabaseLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_db').describe('Database-level isolation strategy'),\n \n /**\n * Database configuration\n */\n database: z.object({\n /**\n * Database naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Database naming pattern'),\n \n /**\n * Database server/cluster assignment strategy\n */\n serverStrategy: z.enum([\n 'shared', // All tenant databases on same server\n 'sharded', // Tenant databases distributed across servers\n 'dedicated', // Each tenant gets dedicated server (enterprise)\n ]).default('shared').describe('Server assignment strategy'),\n \n /**\n * Whether to use separate credentials per tenant\n */\n separateCredentials: z.boolean().default(true).describe('Separate credentials per tenant'),\n \n /**\n * Whether to automatically create database on tenant creation\n */\n autoCreateDatabase: z.boolean().default(true).describe('Auto-create database'),\n }).optional().describe('Database configuration'),\n \n /**\n * Connection pooling configuration\n */\n connectionPool: z.object({\n /**\n * Pool size per tenant database\n */\n poolSize: z.number().int().positive().default(10).describe('Connection pool size'),\n \n /**\n * Maximum number of tenant pools to keep active\n */\n maxActivePools: z.number().int().positive().default(100).describe('Max active pools'),\n \n /**\n * Idle pool timeout in seconds\n */\n idleTimeout: z.number().int().positive().default(300).describe('Idle pool timeout'),\n \n /**\n * Whether to use connection pooler (PgBouncer, etc.)\n */\n usePooler: z.boolean().default(true).describe('Use connection pooler'),\n }).optional().describe('Connection pool configuration'),\n \n /**\n * Backup and restore configuration\n */\n backup: z.object({\n /**\n * Backup strategy per tenant\n */\n strategy: z.enum([\n 'individual', // Separate backup per tenant\n 'consolidated', // Combined backup with all tenants\n 'on_demand', // Backup only when requested\n ]).default('individual').describe('Backup strategy'),\n \n /**\n * Backup frequency in hours\n */\n frequencyHours: z.number().int().positive().default(24).describe('Backup frequency'),\n \n /**\n * Retention period in days\n */\n retentionDays: z.number().int().positive().default(30).describe('Backup retention days'),\n }).optional().describe('Backup configuration'),\n \n /**\n * Encryption configuration\n */\n encryption: z.object({\n /**\n * Whether to use per-tenant encryption keys\n */\n perTenantKeys: z.boolean().default(false).describe('Per-tenant encryption keys'),\n \n /**\n * Encryption algorithm\n */\n algorithm: z.string().default('AES-256-GCM').describe('Encryption algorithm'),\n \n /**\n * Key management service\n */\n keyManagement: z.enum(['aws_kms', 'azure_key_vault', 'gcp_kms', 'hashicorp_vault', 'custom']).optional().describe('Key management service'),\n }).optional().describe('Encryption configuration'),\n});\n\nexport type DatabaseLevelIsolationStrategy = z.infer;\nexport type DatabaseLevelIsolationStrategyInput = z.input;\n\n/**\n * Tenant Isolation Configuration Schema\n * \n * Complete configuration for tenant isolation strategy.\n * Supports all three isolation levels with detailed configuration options.\n */\nexport const TenantIsolationConfigSchema = z.discriminatedUnion('strategy', [\n RowLevelIsolationStrategySchema,\n SchemaLevelIsolationStrategySchema,\n DatabaseLevelIsolationStrategySchema,\n]);\n\nexport type TenantIsolationConfig = z.infer;\n\n/**\n * Tenant Security Policy Schema\n * Defines security policies and compliance requirements for tenants\n */\nexport const TenantSecurityPolicySchema = z.object({\n /**\n * Encryption requirements\n */\n encryption: z.object({\n /**\n * Require encryption at rest\n */\n atRest: z.boolean().default(true).describe('Require encryption at rest'),\n \n /**\n * Require encryption in transit\n */\n inTransit: z.boolean().default(true).describe('Require encryption in transit'),\n \n /**\n * Require field-level encryption for sensitive data\n */\n fieldLevel: z.boolean().default(false).describe('Require field-level encryption'),\n }).optional().describe('Encryption requirements'),\n \n /**\n * Access control requirements\n */\n accessControl: z.object({\n /**\n * Require multi-factor authentication\n */\n requireMFA: z.boolean().default(false).describe('Require MFA'),\n \n /**\n * Require SSO/SAML authentication\n */\n requireSSO: z.boolean().default(false).describe('Require SSO'),\n \n /**\n * IP whitelist\n */\n ipWhitelist: z.array(z.string()).optional().describe('Allowed IP addresses'),\n \n /**\n * Session timeout in seconds\n */\n sessionTimeout: z.number().int().positive().default(3600).describe('Session timeout'),\n }).optional().describe('Access control requirements'),\n \n /**\n * Audit and compliance requirements\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox',\n 'hipaa',\n 'gdpr',\n 'pci_dss',\n 'iso_27001',\n 'fedramp',\n ])).optional().describe('Compliance standards'),\n \n /**\n * Require audit logging for all operations\n */\n requireAuditLog: z.boolean().default(true).describe('Require audit logging'),\n \n /**\n * Audit log retention period in days\n */\n auditRetentionDays: z.number().int().positive().default(365).describe('Audit retention days'),\n \n /**\n * Data residency requirements\n */\n dataResidency: z.object({\n /**\n * Required geographic region\n */\n region: z.string().optional().describe('Required region (e.g., US, EU, APAC)'),\n \n /**\n * Prohibited regions\n */\n excludeRegions: z.array(z.string()).optional().describe('Prohibited regions'),\n }).optional().describe('Data residency requirements'),\n }).optional().describe('Compliance requirements'),\n});\n\nexport type TenantSecurityPolicy = z.infer;\nexport type TenantSecurityPolicyInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metric Type Classification\n */\nexport const LicenseMetricType = z.enum([\n 'boolean', // Feature Flag (Enabled/Disabled)\n 'counter', // Usage Count (e.g. API Calls, Records Created) - Accumulates\n 'gauge', // Current Level (e.g. Storage Used, Users Active) - Point in time\n]).describe('License metric type');\nexport type LicenseMetricType = z.infer;\n\n/**\n * Feature/Limit Definition Schema\n * Defines a controllable capability of the system.\n */\nexport const FeatureSchema = z.object({\n code: z.string().regex(/^[a-z_][a-z0-9_.]*$/).describe('Feature code (e.g. core.api_access)'),\n label: z.string(),\n description: z.string().optional(),\n \n type: LicenseMetricType.default('boolean'),\n \n /** For counters/gauges */\n unit: z.enum(['count', 'bytes', 'seconds', 'percent']).optional(),\n \n /** Dependencies (e.g. 'audit_log' requires 'enterprise_tier') */\n requires: z.array(z.string()).optional(),\n});\n\n/**\n * Subscription Plan Schema\n * Defines a tier of service (e.g. \"Free\", \"Pro\", \"Enterprise\").\n */\nexport const PlanSchema = z.object({\n code: z.string().describe('Plan code (e.g. pro_v1)'),\n label: z.string(),\n active: z.boolean().default(true),\n \n /** Feature Entitlements */\n features: z.array(z.string()).describe('List of enabled boolean features'),\n \n /** Limit Quotas */\n limits: z.record(z.string(), z.number()).describe('Map of metric codes to limit values (e.g. { storage_gb: 10 })'),\n \n /** Pricing (Optional Metadata) */\n currency: z.string().default('USD').optional(),\n priceMonthly: z.number().optional(),\n priceYearly: z.number().optional(),\n});\n\n/**\n * License Schema\n * The actual entitlement object assigned to a Space.\n * Often signed as a JWT.\n */\nexport const LicenseSchema = z.object({\n /** Identity */\n spaceId: z.string().describe('Target Space ID'),\n planCode: z.string(),\n \n /** Validity */\n issuedAt: z.string().datetime(),\n expiresAt: z.string().datetime().optional(), // Null = Perpetual\n \n /** Status */\n status: z.enum(['active', 'expired', 'suspended', 'trial']),\n \n /** Overrides (Specific to this space, exceeding the plan) */\n customFeatures: z.array(z.string()).optional(),\n customLimits: z.record(z.string(), z.number()).optional(),\n \n /** Authorized Add-ons */\n plugins: z.array(z.string()).optional().describe('List of enabled plugin package IDs'),\n\n /** Signature */\n signature: z.string().optional().describe('Cryptographic signature of the license'),\n});\n\nexport type Feature = z.infer;\nexport type FeatureInput = z.input;\nexport type Plan = z.infer;\nexport type PlanInput = z.input;\nexport type License = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Registry Configuration Protocol\n * \n * Defines the configuration for the ObjectStack Registry Service.\n * Includes federation, synchronization, and storage settings.\n */\n\n/**\n * Registry Sync Policy\n * Defines how registries synchronize with upstreams\n */\nexport const RegistrySyncPolicySchema = z.enum([\n 'manual', // Manual synchronization only\n 'auto', // Automatic synchronization\n 'proxy', // Proxy requests to upstream without caching\n]).describe('Registry synchronization strategy');\n\n/**\n * Registry Upstream Configuration\n * Configuration for upstream registry connection\n */\nexport const RegistryUpstreamSchema = z.object({\n /**\n * Upstream registry URL\n */\n url: z.string().url()\n .describe('Upstream registry endpoint'),\n \n /**\n * Synchronization policy\n */\n syncPolicy: RegistrySyncPolicySchema.default('auto'),\n \n /**\n * Sync interval in seconds (for auto sync)\n */\n syncInterval: z.number().int().min(60).optional()\n .describe('Auto-sync interval in seconds'),\n \n /**\n * Authentication credentials\n */\n auth: z.object({\n type: z.enum(['none', 'basic', 'bearer', 'api-key', 'oauth2']).default('none'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n }).optional(),\n \n /**\n * TLS/SSL configuration\n */\n tls: z.object({\n enabled: z.boolean().default(true),\n verifyCertificate: z.boolean().default(true),\n certificate: z.string().optional(),\n privateKey: z.string().optional(),\n }).optional(),\n \n /**\n * Timeout settings\n */\n timeout: z.number().int().min(1000).default(30000)\n .describe('Request timeout in milliseconds'),\n \n /**\n * Retry configuration\n */\n retry: z.object({\n maxAttempts: z.number().int().min(0).default(3),\n backoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),\n }).optional(),\n});\n\n/**\n * Registry Configuration\n * Complete registry configuration supporting federation\n */\nexport const RegistryConfigSchema = z.object({\n /**\n * Registry type\n */\n type: z.enum([\n 'public', // Public marketplace (e.g., plugins.objectstack.com)\n 'private', // Private enterprise registry\n 'hybrid', // Hybrid with upstream federation\n ]).describe('Registry deployment type'),\n \n /**\n * Upstream registries (for hybrid/private registries)\n */\n upstream: z.array(RegistryUpstreamSchema).optional()\n .describe('Upstream registries to sync from or proxy to'),\n \n /**\n * Scopes managed by this registry\n */\n scope: z.array(z.string()).optional()\n .describe('npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)'),\n \n /**\n * Default scope for new plugins\n */\n defaultScope: z.string().optional()\n .describe('Default scope prefix for new plugins'),\n \n /**\n * Registry storage configuration\n */\n storage: z.object({\n /**\n * Storage backend type\n */\n backend: z.enum(['local', 's3', 'gcs', 'azure-blob', 'oss']).default('local'),\n \n /**\n * Storage path or bucket name\n */\n path: z.string().optional(),\n \n /**\n * Credentials\n */\n credentials: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n \n /**\n * Registry visibility\n */\n visibility: z.enum(['public', 'private', 'internal']).default('private')\n .describe('Who can access this registry'),\n \n /**\n * Access control\n */\n accessControl: z.object({\n /**\n * Require authentication for read\n */\n requireAuthForRead: z.boolean().default(false),\n \n /**\n * Require authentication for write\n */\n requireAuthForWrite: z.boolean().default(true),\n \n /**\n * Allowed users/teams\n */\n allowedPrincipals: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Caching configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true),\n ttl: z.number().int().min(0).default(3600)\n .describe('Cache TTL in seconds'),\n maxSize: z.number().int().optional()\n .describe('Maximum cache size in bytes'),\n }).optional(),\n \n /**\n * Mirroring configuration (for high availability)\n */\n mirrors: z.array(z.object({\n url: z.string().url(),\n priority: z.number().int().min(1).default(1),\n })).optional()\n .describe('Mirror registries for redundancy'),\n});\n\nexport type RegistrySyncPolicy = z.infer;\nexport type RegistryUpstream = z.infer;\nexport type RegistryConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Provisioning Protocol\n *\n * Defines the schemas for the \"Register → Instant ObjectOS\" provisioning pipeline:\n * 1. User registers → ProvisioningRequest created\n * 2. Turso database created → Schema synced → Seed data applied\n * 3. Tenant status transitions: provisioning → active\n *\n * Provisioning is designed to be:\n * - **Idempotent**: Re-running the same request produces the same result\n * - **Observable**: Each step has explicit status tracking\n * - **Fast**: Target 2-5 seconds for complete provisioning\n */\n\n// ==========================================================================\n// 1. Enums & Constants\n// ==========================================================================\n\n/**\n * Tenant provisioning lifecycle status.\n */\nexport const TenantProvisioningStatusEnum = z.enum([\n 'provisioning', // Database creation in progress\n 'active', // Fully provisioned and operational\n 'suspended', // Temporarily disabled (billing, policy)\n 'failed', // Provisioning failed (requires retry or manual intervention)\n 'destroying', // Deletion in progress\n]).describe('Tenant provisioning lifecycle status');\n\nexport type TenantProvisioningStatus = z.infer;\n\n/**\n * Tenant subscription plan.\n */\nexport const TenantPlanSchema = z.enum([\n 'free', // Free tier with limited quotas\n 'pro', // Professional tier with higher quotas\n 'enterprise', // Enterprise tier with custom quotas and SLAs\n]).describe('Tenant subscription plan');\n\nexport type TenantPlan = z.infer;\n\n/**\n * Available deployment regions.\n */\nexport const TenantRegionSchema = z.enum([\n 'us-east', // US East (Virginia)\n 'us-west', // US West (Oregon)\n 'eu-west', // EU West (Ireland)\n 'eu-central', // EU Central (Frankfurt)\n 'ap-southeast',// Asia Pacific (Singapore)\n 'ap-northeast',// Asia Pacific (Tokyo)\n]).describe('Available deployment region');\n\nexport type TenantRegion = z.infer;\n\n// ==========================================================================\n// 2. Provisioning Step Tracking\n// ==========================================================================\n\n/**\n * Individual provisioning step status.\n * Tracks the progress of each step in the provisioning pipeline.\n */\nexport const ProvisioningStepSchema = z.object({\n /** Step identifier */\n name: z.string().min(1).describe('Step name (e.g., create_database, sync_schema)'),\n\n /** Step execution status */\n status: z.enum(['pending', 'running', 'completed', 'failed', 'skipped']).describe('Step status'),\n\n /** When the step started (ISO 8601) */\n startedAt: z.string().datetime().optional().describe('Step start time'),\n\n /** When the step completed (ISO 8601) */\n completedAt: z.string().datetime().optional().describe('Step completion time'),\n\n /** Duration in milliseconds */\n durationMs: z.number().int().min(0).optional().describe('Step duration in ms'),\n\n /** Error message if the step failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('Individual provisioning step status');\n\nexport type ProvisioningStep = z.infer;\n\n// ==========================================================================\n// 3. Provisioning Request & Result\n// ==========================================================================\n\n/**\n * Tenant Provisioning Request.\n * Input for creating a new tenant with its isolated database.\n */\nexport const TenantProvisioningRequestSchema = z.object({\n /** Organization ID that owns this tenant */\n orgId: z.string().min(1).describe('Organization ID'),\n\n /** Requested subscription plan */\n plan: TenantPlanSchema.default('free'),\n\n /** Preferred deployment region */\n region: TenantRegionSchema.default('us-east'),\n\n /** Optional tenant display name */\n displayName: z.string().optional().describe('Tenant display name'),\n\n /** Optional initial admin user email */\n adminEmail: z.string().email().optional().describe('Initial admin user email'),\n\n /** Optional metadata to attach to the tenant */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n}).describe('Tenant provisioning request');\n\nexport type TenantProvisioningRequest = z.infer;\n\n/**\n * Tenant Provisioning Result.\n * Output after provisioning completes (or fails).\n */\nexport const TenantProvisioningResultSchema = z.object({\n /** Unique tenant identifier */\n tenantId: z.string().min(1).describe('Provisioned tenant ID'),\n\n /** Database connection URL (libsql:// or https://) */\n connectionUrl: z.string().min(1).describe('Database connection URL'),\n\n /** Current provisioning status */\n status: TenantProvisioningStatusEnum,\n\n /** Deployment region */\n region: TenantRegionSchema,\n\n /** Active subscription plan */\n plan: TenantPlanSchema,\n\n /** Provisioning pipeline steps with status */\n steps: z.array(ProvisioningStepSchema).default([]).describe('Pipeline step statuses'),\n\n /** Total provisioning duration in milliseconds */\n totalDurationMs: z.number().int().min(0).optional().describe('Total provisioning duration'),\n\n /** Provisioned timestamp (ISO 8601) */\n provisionedAt: z.string().datetime().optional().describe('Provisioning completion time'),\n\n /** Error message if provisioning failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('Tenant provisioning result');\n\nexport type TenantProvisioningResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Deploy Bundle Protocol\n *\n * Defines the schemas for metadata-driven deployment:\n * Schema Push → Zod Validate → Diff → DDL Sync → Register\n *\n * This eliminates traditional CI/CD pipelines for schema changes.\n * A \"deploy\" is a bundle of metadata (objects, views, flows, permissions)\n * that is validated, diffed against the current state, and applied\n * as DDL migrations directly to the tenant database.\n *\n * Target: 2-5 second deploys vs. 2-15 minute traditional Docker/CI/CD.\n */\n\n// ==========================================================================\n// 1. Deploy Status\n// ==========================================================================\n\n/**\n * Deployment lifecycle status.\n */\nexport const DeployStatusEnum = z.enum([\n 'validating', // Zod schema validation in progress\n 'diffing', // Comparing desired state vs current state\n 'migrating', // Executing DDL statements\n 'registering', // Updating metadata registry\n 'ready', // Deployment complete and live\n 'failed', // Deployment failed at some stage\n 'rolling_back', // Rollback in progress\n]).describe('Deployment lifecycle status');\n\nexport type DeployStatus = z.infer;\n\n// ==========================================================================\n// 2. Deploy Diff\n// ==========================================================================\n\n/**\n * Schema change descriptor for a single entity (object/field).\n */\nexport const SchemaChangeSchema = z.object({\n /** Type of entity being changed */\n entityType: z.enum(['object', 'field', 'index', 'view', 'flow', 'permission']).describe('Entity type'),\n\n /** Name of the entity */\n entityName: z.string().min(1).describe('Entity name'),\n\n /** Parent entity name (e.g., object name for a field change) */\n parentEntity: z.string().optional().describe('Parent entity name'),\n\n /** Type of change */\n changeType: z.enum(['added', 'modified', 'removed']).describe('Change type'),\n\n /** Previous value (for modified/removed) */\n oldValue: z.unknown().optional().describe('Previous value'),\n\n /** New value (for added/modified) */\n newValue: z.unknown().optional().describe('New value'),\n}).describe('Individual schema change');\n\nexport type SchemaChange = z.infer;\n\n/**\n * Deploy Diff — what changed between current and desired state.\n */\nexport const DeployDiffSchema = z.object({\n /** List of all schema changes */\n changes: z.array(SchemaChangeSchema).default([]).describe('List of schema changes'),\n\n /** Summary counts */\n summary: z.object({\n added: z.number().int().min(0).default(0).describe('Number of added entities'),\n modified: z.number().int().min(0).default(0).describe('Number of modified entities'),\n removed: z.number().int().min(0).default(0).describe('Number of removed entities'),\n }).describe('Change summary counts'),\n\n /** Whether the diff contains breaking changes (e.g., column removal) */\n hasBreakingChanges: z.boolean().default(false).describe('Whether diff contains breaking changes'),\n}).describe('Schema diff between current and desired state');\n\nexport type DeployDiff = z.infer;\n\n// ==========================================================================\n// 3. Migration Plan\n// ==========================================================================\n\n/**\n * A single DDL migration statement.\n */\nexport const MigrationStatementSchema = z.object({\n /** SQL DDL statement to execute */\n sql: z.string().min(1).describe('SQL DDL statement'),\n\n /** Whether this statement is reversible */\n reversible: z.boolean().default(true).describe('Whether the statement can be reversed'),\n\n /** Reverse SQL statement (for rollback) */\n rollbackSql: z.string().optional().describe('Reverse SQL for rollback'),\n\n /** Execution order (lower = earlier) */\n order: z.number().int().min(0).describe('Execution order'),\n}).describe('Single DDL migration statement');\n\nexport type MigrationStatement = z.infer;\n\n/**\n * Migration Plan — ordered list of DDL statements to execute.\n */\nexport const MigrationPlanSchema = z.object({\n /** Ordered list of migration statements */\n statements: z.array(MigrationStatementSchema).default([]).describe('Ordered DDL statements'),\n\n /** SQL dialect the statements are written for */\n dialect: z.string().min(1).describe('Target SQL dialect'),\n\n /** Whether the entire plan is reversible */\n reversible: z.boolean().default(true).describe('Whether the plan can be fully rolled back'),\n\n /** Estimated execution time in milliseconds */\n estimatedDurationMs: z.number().int().min(0).optional().describe('Estimated execution time'),\n}).describe('Ordered migration plan');\n\nexport type MigrationPlan = z.infer;\n\n// ==========================================================================\n// 4. Deploy Validation\n// ==========================================================================\n\n/**\n * Validation issue found during bundle validation.\n */\nexport const DeployValidationIssueSchema = z.object({\n /** Severity of the issue */\n severity: z.enum(['error', 'warning', 'info']).describe('Issue severity'),\n\n /** Entity path where the issue was found */\n path: z.string().describe('Entity path (e.g., objects.project_task.fields.name)'),\n\n /** Human-readable issue description */\n message: z.string().describe('Issue description'),\n\n /** Zod error code if applicable */\n code: z.string().optional().describe('Validation error code'),\n}).describe('Validation issue');\n\nexport type DeployValidationIssue = z.infer;\n\n/**\n * Zod validation result for the entire deploy bundle.\n */\nexport const DeployValidationResultSchema = z.object({\n /** Whether the bundle passed validation */\n valid: z.boolean().describe('Whether the bundle is valid'),\n\n /** List of validation issues */\n issues: z.array(DeployValidationIssueSchema).default([]).describe('Validation issues'),\n\n /** Number of errors */\n errorCount: z.number().int().min(0).default(0).describe('Number of errors'),\n\n /** Number of warnings */\n warningCount: z.number().int().min(0).default(0).describe('Number of warnings'),\n}).describe('Bundle validation result');\n\nexport type DeployValidationResult = z.infer;\n\n// ==========================================================================\n// 5. Deploy Bundle & Manifest\n// ==========================================================================\n\n/**\n * Deploy Manifest — metadata about the deployment.\n */\nexport const DeployManifestSchema = z.object({\n /** Deployment version (semver) */\n version: z.string().min(1).describe('Deployment version'),\n\n /** SHA256 checksum of the bundle contents */\n checksum: z.string().optional().describe('SHA256 checksum'),\n\n /** Object definitions included in this deployment */\n objects: z.array(z.string()).default([]).describe('Object names included'),\n\n /** View definitions included */\n views: z.array(z.string()).default([]).describe('View names included'),\n\n /** Flow definitions included */\n flows: z.array(z.string()).default([]).describe('Flow names included'),\n\n /** Permission definitions included */\n permissions: z.array(z.string()).default([]).describe('Permission names included'),\n\n /** Timestamp of bundle creation (ISO 8601) */\n createdAt: z.string().datetime().optional().describe('Bundle creation time'),\n}).describe('Deployment manifest');\n\nexport type DeployManifest = z.infer;\n\n/**\n * Deploy Bundle — container for all metadata being deployed.\n * This is the primary input to the deploy pipeline.\n */\nexport const DeployBundleSchema = z.object({\n /** Bundle manifest with version and contents list */\n manifest: DeployManifestSchema,\n\n /** Object definitions (JSON-serialized ObjectStack objects) */\n objects: z.array(z.record(z.string(), z.unknown())).default([]).describe('Object definitions'),\n\n /** View definitions */\n views: z.array(z.record(z.string(), z.unknown())).default([]).describe('View definitions'),\n\n /** Flow definitions */\n flows: z.array(z.record(z.string(), z.unknown())).default([]).describe('Flow definitions'),\n\n /** Permission definitions */\n permissions: z.array(z.record(z.string(), z.unknown())).default([]).describe('Permission definitions'),\n\n /** Seed data records to populate after schema migration */\n seedData: z.array(z.record(z.string(), z.unknown())).default([]).describe('Seed data records'),\n}).describe('Deploy bundle containing all metadata for deployment');\n\nexport type DeployBundle = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * App Installation Protocol\n *\n * Defines the schemas for installing marketplace apps into tenant databases.\n * An \"app install\" injects metadata (objects, views, flows) + schema sync\n * into a tenant's isolated database.\n *\n * Install pipeline:\n * 1. Check compatibility (kernel version, existing objects, conflicts)\n * 2. Validate app manifest\n * 3. Apply schema changes (via deploy pipeline)\n * 4. Seed initial data\n * 5. Register app in tenant's metadata registry\n */\n\n// ==========================================================================\n// 1. App Manifest\n// ==========================================================================\n\n/**\n * App Manifest — describes an installable app package.\n */\nexport const AppManifestSchema = z.object({\n /** Unique app identifier (snake_case) */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('App identifier (snake_case)'),\n\n /** Display label for the app */\n label: z.string().min(1).describe('App display label'),\n\n /** App version (semver) */\n version: z.string().min(1).describe('App version (semver)'),\n\n /** App description */\n description: z.string().optional().describe('App description'),\n\n /** Minimum kernel version required */\n minKernelVersion: z.string().optional().describe('Minimum required kernel version'),\n\n /** Object definitions provided by this app */\n objects: z.array(z.string()).default([]).describe('Object names provided'),\n\n /** View definitions provided */\n views: z.array(z.string()).default([]).describe('View names provided'),\n\n /** Flow definitions provided */\n flows: z.array(z.string()).default([]).describe('Flow names provided'),\n\n /** Whether seed data is included */\n hasSeedData: z.boolean().default(false).describe('Whether app includes seed data'),\n\n /** Seed data records to populate on install */\n seedData: z.array(z.record(z.string(), z.unknown())).default([]).describe('Seed data records'),\n\n /** App dependencies (other apps that must be installed first) */\n dependencies: z.array(z.string()).default([]).describe('Required app dependencies'),\n}).describe('App manifest for marketplace installation');\n\nexport type AppManifest = z.infer;\n\n// ==========================================================================\n// 2. Compatibility Check\n// ==========================================================================\n\n/**\n * App Compatibility Check Result.\n */\nexport const AppCompatibilityCheckSchema = z.object({\n /** Whether the app is compatible with the current environment */\n compatible: z.boolean().describe('Whether the app is compatible'),\n\n /** Compatibility issues found */\n issues: z.array(z.object({\n /** Issue severity */\n severity: z.enum(['error', 'warning']).describe('Issue severity'),\n /** Issue description */\n message: z.string().describe('Issue description'),\n /** Issue category */\n category: z.enum([\n 'kernel_version', // Kernel version mismatch\n 'object_conflict', // Object name already exists\n 'dependency_missing', // Required dependency not installed\n 'quota_exceeded', // Tenant quota would be exceeded\n ]).describe('Issue category'),\n })).default([]).describe('Compatibility issues'),\n}).describe('App compatibility check result');\n\nexport type AppCompatibilityCheck = z.infer;\n\n// ==========================================================================\n// 3. Install Request & Result\n// ==========================================================================\n\n/**\n * App Install Request.\n */\nexport const AppInstallRequestSchema = z.object({\n /** Target tenant ID */\n tenantId: z.string().min(1).describe('Target tenant ID'),\n\n /** App identifier to install */\n appId: z.string().min(1).describe('App identifier'),\n\n /** Optional configuration overrides */\n configOverrides: z.record(z.string(), z.unknown()).optional().describe('Configuration overrides'),\n\n /** Whether to skip seed data */\n skipSeedData: z.boolean().default(false).describe('Skip seed data population'),\n}).describe('App install request');\n\nexport type AppInstallRequest = z.infer;\n\n/**\n * App Install Result.\n */\nexport const AppInstallResultSchema = z.object({\n /** Whether the installation succeeded */\n success: z.boolean().describe('Whether installation succeeded'),\n\n /** App identifier that was installed */\n appId: z.string().describe('Installed app identifier'),\n\n /** App version installed */\n version: z.string().describe('Installed app version'),\n\n /** Objects created or updated */\n installedObjects: z.array(z.string()).default([]).describe('Objects created/updated'),\n\n /** Tables created in the database */\n createdTables: z.array(z.string()).default([]).describe('Database tables created'),\n\n /** Number of seed records inserted */\n seededRecords: z.number().int().min(0).default(0).describe('Seed records inserted'),\n\n /** Installation duration in milliseconds */\n durationMs: z.number().int().min(0).optional().describe('Installation duration'),\n\n /** Error message if installation failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('App install result');\n\nexport type AppInstallResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Package conventions and directory structure constants.\n * These define the \"Law of Location\" - where things must be in ObjectStack packages.\n * \n * These paths are the source of truth used by:\n * - ObjectOS Runtime (to locate package components)\n * - ObjectStack CLI (to scaffold and validate packages)\n * - ObjectStudio IDE (to provide intelligent navigation and validation)\n */\nexport const PKG_CONVENTIONS = {\n /**\n * Standard directories within ObjectStack packages.\n * All packages MUST follow these conventions for the runtime to locate resources.\n */\n DIRS: {\n /** \n * Location for schema definitions (Zod schemas, JSON schemas).\n * Path: src/schemas\n */\n SCHEMA: 'src/schemas',\n \n /** \n * Location for server-side code and triggers.\n * Path: src/server\n */\n SERVER: 'src/server',\n \n /** \n * Location for server-side trigger functions.\n * Path: src/triggers\n */\n TRIGGERS: 'src/triggers',\n \n /** \n * Location for client-side code.\n * Path: src/client\n */\n CLIENT: 'src/client',\n \n /** \n * Location for client-side page components.\n * Path: src/client/pages\n */\n PAGES: 'src/client/pages',\n \n /** \n * Location for static assets (images, fonts, etc.).\n * Path: assets\n */\n ASSETS: 'assets',\n },\n \n /**\n * Standard file names within ObjectStack packages.\n */\n FILES: {\n /** \n * Package manifest configuration file.\n * File: objectstack.config.ts\n */\n MANIFEST: 'objectstack.config.ts',\n \n /** \n * Main entry point for the package.\n * File: src/index.ts\n */\n ENTRY: 'src/index.ts',\n },\n} as const;\n\n/**\n * Type helper to extract directory path values.\n */\nexport type PackageDirectory = typeof PKG_CONVENTIONS.DIRS[keyof typeof PKG_CONVENTIONS.DIRS];\n\n/**\n * Type helper to extract file path values.\n */\nexport type PackageFile = typeof PKG_CONVENTIONS.FILES[keyof typeof PKG_CONVENTIONS.FILES];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * System Object Names — Protocol Layer Constants\n *\n * These constants define the canonical, protocol-level names for system objects.\n * All API calls, SDK references, permissions checks, and metadata lookups MUST use\n * these names instead of hardcoded strings or physical table names.\n *\n * The actual storage table name may differ via `ObjectSchema.tableName`.\n * The mapping between protocol name and storage name is handled by the\n * ObjectQL Engine / Driver layer.\n *\n * @example\n * ```ts\n * import { SystemObjectName } from '@objectstack/spec/system';\n *\n * // Always use the constant for API / SDK / permission references\n * const users = await engine.find(SystemObjectName.USER, { ... });\n * ```\n */\nexport const SystemObjectName = {\n /** Authentication: user identity */\n USER: 'sys_user',\n /** Authentication: active session */\n SESSION: 'sys_session',\n /** Authentication: OAuth / credential account */\n ACCOUNT: 'sys_account',\n /** Authentication: email / phone verification */\n VERIFICATION: 'sys_verification',\n /** Authentication: organization (multi-org support) */\n ORGANIZATION: 'sys_organization',\n /** Authentication: organization member */\n MEMBER: 'sys_member',\n /** Authentication: organization invitation */\n INVITATION: 'sys_invitation',\n /** Authentication: team within an organization */\n TEAM: 'sys_team',\n /** Authentication: team membership */\n TEAM_MEMBER: 'sys_team_member',\n /** Authentication: API key for programmatic access */\n API_KEY: 'sys_api_key',\n /** Authentication: two-factor authentication credentials */\n TWO_FACTOR: 'sys_two_factor',\n /** Authentication: user preferences (theme, locale, etc.) */\n USER_PREFERENCE: 'sys_user_preference',\n /** Security: role definition for RBAC */\n ROLE: 'sys_role',\n /** Security: permission set grouping */\n PERMISSION_SET: 'sys_permission_set',\n /** Audit: system audit log */\n AUDIT_LOG: 'sys_audit_log',\n /** System metadata storage */\n METADATA: 'sys_metadata',\n /** Realtime: user presence state */\n PRESENCE: 'sys_presence',\n} as const;\n\n/** Union type of all system object names */\nexport type SystemObjectName = typeof SystemObjectName[keyof typeof SystemObjectName];\n\n/**\n * System Field Names — Protocol Layer Constants\n *\n * These constants define the canonical, protocol-level names for common system fields.\n * All API calls, SDK references, and permission checks MUST use these constants\n * instead of hardcoded strings or physical column names.\n *\n * The actual storage column name may differ via `FieldSchema.columnName`.\n *\n * @example\n * ```ts\n * import { SystemFieldName } from '@objectstack/spec/system';\n *\n * // Use the constant to reference the owner field in queries\n * const myRecords = await engine.find('project', {\n * filters: [SystemFieldName.OWNER_ID, '=', currentUserId],\n * });\n * ```\n */\nexport const SystemFieldName = {\n /** Primary key */\n ID: 'id',\n /** Record creation timestamp */\n CREATED_AT: 'created_at',\n /** Record last-updated timestamp */\n UPDATED_AT: 'updated_at',\n /** Record owner (lookup to user) */\n OWNER_ID: 'owner_id',\n /** Tenant isolation key */\n TENANT_ID: 'tenant_id',\n /** Foreign key to user on session / account objects */\n USER_ID: 'user_id',\n /** Soft-delete timestamp */\n DELETED_AT: 'deleted_at',\n} as const;\n\n/** Union type of all system field names */\nexport type SystemFieldName = typeof SystemFieldName[keyof typeof SystemFieldName];\n\n/**\n * Storage Name Mapping — Protocol ↔ Physical Name Resolution\n *\n * Provides pure utility functions for resolving protocol-level names to\n * physical storage names and vice-versa.\n *\n * These helpers are intended for use inside the ObjectQL Engine and Driver layers.\n * They are intentionally stateless — they receive the object definition and return\n * the resolved name.\n */\nexport const StorageNameMapping = {\n /**\n * Resolve the physical table name for an object.\n * Priority: explicit `tableName` → auto-derived `{namespace}_{name}` → `name`.\n *\n * @param object - Object definition (at minimum `{ name: string; namespace?: string; tableName?: string }`)\n * @returns The physical table / collection name to use in storage operations.\n */\n resolveTableName(object: { name: string; namespace?: string; tableName?: string }): string {\n return object.tableName ?? (object.namespace ? `${object.namespace}_${object.name}` : object.name);\n },\n\n /**\n * Resolve the physical column name for a field.\n * Falls back to `fieldKey` when `columnName` is not set on the field.\n *\n * @param fieldKey - The protocol-level field key (snake_case identifier).\n * @param field - Field definition (at minimum `{ columnName?: string }`).\n * @returns The physical column name to use in storage operations.\n */\n resolveColumnName(fieldKey: string, field: { columnName?: string }): string {\n return field.columnName ?? fieldKey;\n },\n\n /**\n * Build a complete field-key → column-name map for an entire object.\n *\n * @param fields - The fields record from an ObjectSchema.\n * @returns A record mapping every protocol field key to its physical column name.\n */\n buildColumnMap(fields: Record): Record {\n const map: Record = {};\n for (const key of Object.keys(fields)) {\n map[key] = fields[key].columnName ?? key;\n }\n return map;\n },\n\n /**\n * Build a reverse column-name → field-key map for an entire object.\n * Useful for translating storage-layer results back to protocol-level field keys.\n *\n * @param fields - The fields record from an ObjectSchema.\n * @returns A record mapping every physical column name back to its protocol field key.\n */\n buildReverseColumnMap(fields: Record): Record {\n const map: Record = {};\n for (const key of Object.keys(fields)) {\n const col = fields[key].columnName ?? key;\n map[col] = key;\n }\n return map;\n },\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from './types.js';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport type { IServiceRegistry } from '@objectstack/spec/contracts';\n\n/**\n * Kernel state machine\n */\nexport type KernelState = 'idle' | 'initializing' | 'running' | 'stopping' | 'stopped';\n\n/**\n * ObjectKernelBase - Abstract Base Class for Microkernel\n * \n * Provides common functionality for ObjectKernel and LiteKernel:\n * - Plugin management (Map storage)\n * - Dependency resolution (topological sort)\n * - Hook/Event system\n * - Context creation\n * - State validation\n * \n * This eliminates code duplication between the implementations.\n */\nexport abstract class ObjectKernelBase {\n protected plugins: Map = new Map();\n protected services: IServiceRegistry | Map = new Map();\n protected hooks: Map void | Promise>> = new Map();\n protected state: KernelState = 'idle';\n protected logger: Logger;\n protected context!: PluginContext;\n\n constructor(logger: Logger) {\n this.logger = logger;\n }\n\n /**\n * Validate kernel state\n * @param requiredState - Required state for the operation\n * @throws Error if current state doesn't match\n */\n protected validateState(requiredState: KernelState): void {\n if (this.state !== requiredState) {\n throw new Error(\n `[Kernel] Invalid state: expected '${requiredState}', got '${this.state}'`\n );\n }\n }\n\n /**\n * Validate kernel is in idle state (for plugin registration)\n */\n protected validateIdle(): void {\n if (this.state !== 'idle') {\n throw new Error('[Kernel] Cannot register plugins after bootstrap has started');\n }\n }\n\n /**\n * Create the plugin context\n * Subclasses can override to customize context creation\n */\n protected createContext(): PluginContext {\n return {\n registerService: (name, service) => {\n if (this.services instanceof Map) {\n if (this.services.has(name)) {\n throw new Error(`[Kernel] Service '${name}' already registered`);\n }\n this.services.set(name, service);\n } else {\n // IServiceRegistry implementation\n this.services.register(name, service);\n }\n this.logger.info(`Service '${name}' registered`, { service: name });\n },\n getService: (name: string): T => {\n if (this.services instanceof Map) {\n const service = this.services.get(name);\n if (!service) {\n throw new Error(`[Kernel] Service '${name}' not found`);\n }\n return service as T;\n } else {\n // IServiceRegistry implementation\n return this.services.get(name);\n }\n },\n replaceService: (name: string, implementation: T): void => {\n if (this.services instanceof Map) {\n if (!this.services.has(name)) {\n throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`);\n }\n this.services.set(name, implementation);\n } else {\n // IServiceRegistry implementation\n if (!this.services.has(name)) {\n throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`);\n }\n this.services.register(name, implementation);\n }\n this.logger.info(`Service '${name}' replaced`, { service: name });\n },\n hook: (name, handler) => {\n if (!this.hooks.has(name)) {\n this.hooks.set(name, []);\n }\n this.hooks.get(name)!.push(handler);\n },\n trigger: async (name, ...args) => {\n const handlers = this.hooks.get(name) || [];\n for (const handler of handlers) {\n await handler(...args);\n }\n },\n getServices: () => {\n if (this.services instanceof Map) {\n return new Map(this.services);\n } else {\n // For IServiceRegistry, we need to return the underlying Map\n // This is a compatibility method\n return new Map();\n }\n },\n logger: this.logger,\n getKernel: () => this as any,\n };\n }\n\n /**\n * Resolve plugin dependencies using topological sort\n * @returns Ordered list of plugins (dependencies first)\n */\n protected resolveDependencies(): Plugin[] {\n const resolved: Plugin[] = [];\n const visited = new Set();\n const visiting = new Set();\n\n const visit = (pluginName: string) => {\n if (visited.has(pluginName)) return;\n \n if (visiting.has(pluginName)) {\n throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`);\n }\n\n const plugin = this.plugins.get(pluginName);\n if (!plugin) {\n throw new Error(`[Kernel] Plugin '${pluginName}' not found`);\n }\n\n visiting.add(pluginName);\n\n // Visit dependencies first\n const deps = plugin.dependencies || [];\n for (const dep of deps) {\n if (!this.plugins.has(dep)) {\n throw new Error(\n `[Kernel] Dependency '${dep}' not found for plugin '${pluginName}'`\n );\n }\n visit(dep);\n }\n\n visiting.delete(pluginName);\n visited.add(pluginName);\n resolved.push(plugin);\n };\n\n // Visit all plugins\n for (const pluginName of this.plugins.keys()) {\n visit(pluginName);\n }\n\n return resolved;\n }\n\n /**\n * Run plugin init phase\n * @param plugin - Plugin to initialize\n */\n protected async runPluginInit(plugin: Plugin): Promise {\n const pluginName = plugin.name;\n this.logger.info(`Initializing plugin: ${pluginName}`);\n \n try {\n await plugin.init(this.context);\n this.logger.info(`Plugin initialized: ${pluginName}`);\n } catch (error) {\n this.logger.error(`Plugin init failed: ${pluginName}`, error as Error);\n throw error;\n }\n }\n\n /**\n * Run plugin start phase\n * @param plugin - Plugin to start\n */\n protected async runPluginStart(plugin: Plugin): Promise {\n if (!plugin.start) return;\n \n const pluginName = plugin.name;\n this.logger.info(`Starting plugin: ${pluginName}`);\n \n try {\n await plugin.start(this.context);\n this.logger.info(`Plugin started: ${pluginName}`);\n } catch (error) {\n this.logger.error(`Plugin start failed: ${pluginName}`, error as Error);\n throw error;\n }\n }\n\n /**\n * Run plugin destroy phase\n * @param plugin - Plugin to destroy\n */\n protected async runPluginDestroy(plugin: Plugin): Promise {\n if (!plugin.destroy) return;\n \n const pluginName = plugin.name;\n this.logger.info(`Destroying plugin: ${pluginName}`);\n \n try {\n await plugin.destroy();\n this.logger.info(`Plugin destroyed: ${pluginName}`);\n } catch (error) {\n this.logger.error(`Plugin destroy failed: ${pluginName}`, error as Error);\n throw error;\n }\n }\n\n /**\n * Trigger a hook with all registered handlers\n * @param name - Hook name\n * @param args - Arguments to pass to handlers\n */\n protected async triggerHook(name: string, ...args: any[]): Promise {\n const handlers = this.hooks.get(name) || [];\n this.logger.debug(`Triggering hook: ${name}`, { \n hook: name, \n handlerCount: handlers.length \n });\n \n for (const handler of handlers) {\n try {\n await handler(...args);\n } catch (error) {\n this.logger.error(`Hook handler failed: ${name}`, error as Error);\n // Continue with other handlers even if one fails\n }\n }\n }\n\n /**\n * Get current kernel state\n */\n getState(): KernelState {\n return this.state;\n }\n\n /**\n * Get all registered plugins\n */\n getPlugins(): Map {\n return new Map(this.plugins);\n }\n\n /**\n * Abstract methods to be implemented by subclasses\n */\n abstract use(plugin: Plugin): this | Promise;\n abstract bootstrap(): Promise;\n abstract destroy(): Promise;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Environment utilities for universal (Node/Browser) compatibility.\n */\n\n// Check if running in a Node.js environment\nexport const isNode = typeof process !== 'undefined' && \n process.versions != null && \n process.versions.node != null;\n\n/**\n * Safely access environment variables\n */\nexport function getEnv(key: string, defaultValue?: string): string | undefined {\n // Node.js\n if (typeof process !== 'undefined' && process.env) {\n return process.env[key] || defaultValue;\n }\n \n // Browser (Vite/Webpack replacement usually handles process.env, \n // but if not, we check safe global access)\n try {\n // @ts-ignore\n if (typeof globalThis !== 'undefined' && globalThis.process?.env) {\n // @ts-ignore\n return globalThis.process.env[key] || defaultValue;\n }\n } catch (e) {\n // Ignore access errors\n }\n \n return defaultValue;\n}\n\n/**\n * Safely exit the process if in Node.js\n */\nexport function safeExit(code: number = 0): void {\n if (isNode) {\n process.exit(code);\n }\n}\n\n/**\n * Safely get memory usage\n */\nexport function getMemoryUsage(): { heapUsed: number; heapTotal: number } {\n if (isNode) {\n return process.memoryUsage();\n }\n return { heapUsed: 0, heapTotal: 0 };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { LoggerConfig, LogLevel } from '@objectstack/spec/system';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport { isNode } from './utils/env.js';\n\n/**\n * Universal Logger Implementation\n * \n * A configurable logger that works in both browser and Node.js environments.\n * - Node.js: Uses Pino for high-performance structured logging\n * - Browser: Simple console-based implementation\n * \n * Features:\n * - Structured logging with multiple formats (json, text, pretty)\n * - Log level filtering\n * - Sensitive data redaction\n * - File logging with rotation (Node.js only via Pino)\n * - Browser console integration\n * - Distributed tracing support (traceId, spanId)\n */\nexport class ObjectLogger implements Logger {\n private config: Required> & { file?: string; rotation?: { maxSize: string; maxFiles: number }; name?: string };\n private isNode: boolean;\n private pinoLogger?: any; // Pino logger instance for Node.js\n private pinoInstance?: any; // Base Pino instance for creating child loggers\n private require?: any; // CommonJS require function for Node.js\n\n constructor(config: Partial = {}) {\n // Detect runtime environment\n this.isNode = isNode;\n\n // Set defaults\n this.config = {\n name: config.name,\n level: config.level ?? 'info',\n format: config.format ?? (this.isNode ? 'json' : 'pretty'),\n redact: config.redact ?? ['password', 'token', 'secret', 'key'],\n sourceLocation: config.sourceLocation ?? false,\n file: config.file,\n rotation: config.rotation ?? {\n maxSize: '10m',\n maxFiles: 5\n }\n };\n\n // Initialize Pino logger for Node.js\n if (this.isNode) {\n this.initPinoLogger();\n }\n }\n\n /**\n * Initialize Pino logger for Node.js\n */\n private async initPinoLogger() {\n if (!this.isNode) return;\n\n try {\n // Create require function dynamically for Node.js (avoids bundling issues in browser)\n // @ts-ignore - dynamic import of Node.js module\n const { createRequire } = await import('module');\n this.require = createRequire(import.meta.url);\n \n // Synchronous import for Pino using createRequire (works in ESM)\n const pino = this.require('pino');\n \n // Build Pino options\n const pinoOptions: any = {\n level: this.config.level,\n redact: {\n paths: this.config.redact,\n censor: '***REDACTED***'\n }\n };\n\n // Add name if provided\n if (this.config.name) {\n pinoOptions.name = this.config.name;\n }\n\n // Transport configuration for pretty printing or file output\n const targets: any[] = [];\n\n // Console transport\n if (this.config.format === 'pretty') {\n // Check if pino-pretty is available\n let hasPretty = false;\n try {\n this.require.resolve('pino-pretty');\n hasPretty = true;\n } catch (e) {\n // ignore\n }\n\n if (hasPretty) {\n targets.push({\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'SYS:standard',\n ignore: 'pid,hostname'\n },\n level: this.config.level\n });\n } else {\n console.warn('[Logger] pino-pretty not found. Install it for pretty logging: pnpm add -D pino-pretty');\n // Fallback to text/simple\n targets.push({\n target: 'pino/file',\n options: { destination: 1 },\n level: this.config.level\n });\n }\n } else if (this.config.format === 'json') {\n // JSON to stdout\n targets.push({\n target: 'pino/file',\n options: { destination: 1 }, // stdout\n level: this.config.level\n });\n } else {\n // text format (simple)\n targets.push({\n target: 'pino/file',\n options: { destination: 1 },\n level: this.config.level\n });\n }\n\n // File transport (if configured)\n if (this.config.file) {\n targets.push({\n target: 'pino/file',\n options: {\n destination: this.config.file,\n mkdir: true\n },\n level: this.config.level\n });\n }\n\n // Create transport\n if (targets.length > 0) {\n pinoOptions.transport = targets.length === 1 ? targets[0] : { targets };\n }\n\n // Create Pino logger\n this.pinoInstance = pino(pinoOptions);\n this.pinoLogger = this.pinoInstance;\n\n } catch (error) {\n // Fallback to console if Pino is not available\n console.warn('[Logger] Pino not available, falling back to console:', error);\n this.pinoLogger = null;\n }\n }\n\n /**\n * Redact sensitive keys from context object (for browser)\n */\n private redactSensitive(obj: any): any {\n if (!obj || typeof obj !== 'object') return obj;\n\n const redacted = Array.isArray(obj) ? [...obj] : { ...obj };\n\n for (const key in redacted) {\n const lowerKey = key.toLowerCase();\n const shouldRedact = this.config.redact.some((pattern: string) => \n lowerKey.includes(pattern.toLowerCase())\n );\n\n if (shouldRedact) {\n redacted[key] = '***REDACTED***';\n } else if (typeof redacted[key] === 'object' && redacted[key] !== null) {\n redacted[key] = this.redactSensitive(redacted[key]);\n }\n }\n\n return redacted;\n }\n\n /**\n * Format log entry for browser\n */\n private formatBrowserLog(level: LogLevel, message: string, context?: Record): string {\n if (this.config.format === 'json') {\n return JSON.stringify({\n timestamp: new Date().toISOString(),\n level,\n message,\n ...context\n });\n }\n\n if (this.config.format === 'text') {\n const parts = [new Date().toISOString(), level.toUpperCase(), message];\n if (context && Object.keys(context).length > 0) {\n parts.push(JSON.stringify(context));\n }\n return parts.join(' | ');\n }\n\n // Pretty format\n const levelColors: Record = {\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n fatal: '\\x1b[35m', // Magenta\n silent: ''\n };\n const reset = '\\x1b[0m';\n const color = levelColors[level] || '';\n\n let output = `${color}[${level.toUpperCase()}]${reset} ${message}`;\n \n if (context && Object.keys(context).length > 0) {\n output += ` ${JSON.stringify(context, null, 2)}`;\n }\n\n return output;\n }\n\n /**\n * Log using browser console\n */\n private logBrowser(level: LogLevel, message: string, context?: Record, error?: Error) {\n const redactedContext = context ? this.redactSensitive(context) : undefined;\n const mergedContext = error ? { ...redactedContext, error: { message: error.message, stack: error.stack } } : redactedContext;\n \n const formatted = this.formatBrowserLog(level, message, mergedContext);\n \n const consoleMethod = level === 'debug' ? 'debug' :\n level === 'info' ? 'log' :\n level === 'warn' ? 'warn' :\n level === 'error' || level === 'fatal' ? 'error' :\n 'log';\n \n console[consoleMethod](formatted);\n }\n\n /**\n * Public logging methods\n */\n debug(message: string, meta?: Record): void {\n if (this.isNode && this.pinoLogger) {\n this.pinoLogger.debug(meta || {}, message);\n } else {\n this.logBrowser('debug', message, meta);\n }\n }\n\n info(message: string, meta?: Record): void {\n if (this.isNode && this.pinoLogger) {\n this.pinoLogger.info(meta || {}, message);\n } else {\n this.logBrowser('info', message, meta);\n }\n }\n\n warn(message: string, meta?: Record): void {\n if (this.isNode && this.pinoLogger) {\n this.pinoLogger.warn(meta || {}, message);\n } else {\n this.logBrowser('warn', message, meta);\n }\n }\n\n error(message: string, errorOrMeta?: Error | Record, meta?: Record): void {\n let error: Error | undefined;\n let context: Record = {};\n\n if (errorOrMeta instanceof Error) {\n error = errorOrMeta;\n context = meta || {};\n } else {\n context = errorOrMeta || {};\n }\n\n if (this.isNode && this.pinoLogger) {\n const errorContext = error ? { err: error, ...context } : context;\n this.pinoLogger.error(errorContext, message);\n } else {\n this.logBrowser('error', message, context, error);\n }\n }\n\n fatal(message: string, errorOrMeta?: Error | Record, meta?: Record): void {\n let error: Error | undefined;\n let context: Record = {};\n\n if (errorOrMeta instanceof Error) {\n error = errorOrMeta;\n context = meta || {};\n } else {\n context = errorOrMeta || {};\n }\n\n if (this.isNode && this.pinoLogger) {\n const errorContext = error ? { err: error, ...context } : context;\n this.pinoLogger.fatal(errorContext, message);\n } else {\n this.logBrowser('fatal', message, context, error);\n }\n }\n\n /**\n * Create a child logger with additional context\n * Note: Child loggers share the parent's Pino instance\n */\n child(context: Record): ObjectLogger {\n const childLogger = new ObjectLogger(this.config);\n \n // For Node.js with Pino, create a Pino child logger\n if (this.isNode && this.pinoInstance) {\n childLogger.pinoLogger = this.pinoInstance.child(context);\n childLogger.pinoInstance = this.pinoInstance;\n }\n\n return childLogger;\n }\n\n /**\n * Set trace context for distributed tracing\n */\n withTrace(traceId: string, spanId?: string): ObjectLogger {\n return this.child({ traceId, spanId });\n }\n\n /**\n * Cleanup resources\n */\n async destroy(): Promise {\n if (this.pinoLogger && this.pinoLogger.flush) {\n await new Promise((resolve) => {\n this.pinoLogger.flush(() => resolve());\n });\n }\n }\n\n /**\n * Compatibility method for console.log usage\n */\n log(message: string, ...args: any[]): void {\n this.info(message, args.length > 0 ? { args } : undefined);\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(config?: Partial): ObjectLogger {\n return new ObjectLogger(config);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from './types.js';\nimport { createLogger, ObjectLogger } from './logger.js';\nimport type { LoggerConfig } from '@objectstack/spec/system';\nimport { ServiceRequirementDef } from '@objectstack/spec/system';\nimport { PluginLoader, PluginMetadata, ServiceLifecycle, ServiceFactory, PluginStartupResult } from './plugin-loader.js';\nimport { isNode, safeExit } from './utils/env.js';\nimport { CORE_FALLBACK_FACTORIES } from './fallbacks/index.js';\n\n/**\n * Enhanced Kernel Configuration\n */\nexport interface ObjectKernelConfig {\n logger?: Partial;\n \n /** Default plugin startup timeout in milliseconds */\n defaultStartupTimeout?: number;\n \n /** Whether to enable graceful shutdown */\n gracefulShutdown?: boolean;\n \n /** Graceful shutdown timeout in milliseconds */\n shutdownTimeout?: number;\n \n /** Whether to rollback on startup failure */\n rollbackOnFailure?: boolean;\n \n /** Whether to skip strict system requirement validation (Critical for testing) */\n skipSystemValidation?: boolean;\n}\n\n/**\n * Enhanced ObjectKernel with Advanced Plugin Management\n * \n * Extends the basic ObjectKernel with:\n * - Async plugin loading with validation\n * - Version compatibility checking\n * - Plugin signature verification\n * - Configuration validation (Zod)\n * - Factory-based dependency injection\n * - Service lifecycle management (singleton/transient/scoped)\n * - Circular dependency detection\n * - Lazy loading services\n * - Graceful shutdown\n * - Plugin startup timeout control\n * - Startup failure rollback\n * - Plugin health checks\n */\nexport class ObjectKernel {\n private plugins: Map = new Map();\n private services: Map = new Map();\n private hooks: Map void | Promise>> = new Map();\n private state: 'idle' | 'initializing' | 'running' | 'stopping' | 'stopped' = 'idle';\n private logger: ObjectLogger;\n private context: PluginContext;\n private pluginLoader: PluginLoader;\n private config: ObjectKernelConfig;\n private startedPlugins: Set = new Set();\n private pluginStartTimes: Map = new Map();\n private shutdownHandlers: Array<() => Promise> = [];\n\n constructor(config: ObjectKernelConfig = {}) {\n this.config = {\n defaultStartupTimeout: 30000, // 30 seconds\n gracefulShutdown: true,\n shutdownTimeout: 60000, // 60 seconds\n rollbackOnFailure: true,\n ...config,\n };\n\n this.logger = createLogger(config.logger);\n this.pluginLoader = new PluginLoader(this.logger);\n \n // Initialize context\n this.context = {\n registerService: (name, service) => {\n this.registerService(name, service);\n },\n getService: (name: string) => {\n // 1. Try direct service map first (synchronous cache)\n const service = this.services.get(name);\n if (service) {\n return service as T;\n }\n\n // 2. Try to get from plugin loader cache (Sync access to factories)\n const loaderService = this.pluginLoader.getServiceInstance(name);\n if (loaderService) {\n // Cache it locally for faster next access\n this.services.set(name, loaderService);\n return loaderService;\n }\n\n // 3. Try to get from plugin loader (support async factories)\n try {\n const service = this.pluginLoader.getService(name);\n if (service instanceof Promise) {\n // If we found it in the loader but not in the sync map, it's likely a factory-based service or still loading\n // We must silence any potential rejection from this promise since we are about to throw our own error\n // and abandon the promise. Without this, Node.js will crash with \"Unhandled Promise Rejection\".\n service.catch(() => {});\n throw new Error(`Service '${name}' is async - use await`);\n }\n return service as T;\n } catch (error: any) {\n if (error.message?.includes('is async')) {\n throw error;\n }\n \n // Re-throw critical factory errors instead of masking them as \"not found\"\n // If the error came from the factory execution (e.g. database connection failed), we must see it.\n // \"Service '${name}' not found\" comes from PluginLoader.getService fallback.\n const isNotFoundError = error.message === `Service '${name}' not found`;\n \n if (!isNotFoundError) {\n throw error;\n }\n\n throw new Error(`[Kernel] Service '${name}' not found`);\n }\n },\n replaceService: (name: string, implementation: T): void => {\n const hasService = this.services.has(name) || this.pluginLoader.hasService(name);\n if (!hasService) {\n throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`);\n }\n this.services.set(name, implementation);\n this.pluginLoader.replaceService(name, implementation);\n this.logger.info(`Service '${name}' replaced`, { service: name });\n },\n hook: (name, handler) => {\n if (!this.hooks.has(name)) {\n this.hooks.set(name, []);\n }\n this.hooks.get(name)!.push(handler);\n },\n trigger: async (name, ...args) => {\n const handlers = this.hooks.get(name) || [];\n for (const handler of handlers) {\n await handler(...args);\n }\n },\n getServices: () => {\n return new Map(this.services);\n },\n logger: this.logger,\n getKernel: () => this as any, // Type compatibility\n };\n\n this.pluginLoader.setContext(this.context);\n\n // Register shutdown handler\n if (this.config.gracefulShutdown) {\n this.registerShutdownSignals();\n }\n }\n\n /**\n * Register a plugin with enhanced validation\n */\n async use(plugin: Plugin): Promise {\n if (this.state !== 'idle') {\n throw new Error('[Kernel] Cannot register plugins after bootstrap has started');\n }\n\n // Load plugin through enhanced loader\n const result = await this.pluginLoader.loadPlugin(plugin);\n \n if (!result.success || !result.plugin) {\n throw new Error(`Failed to load plugin: ${plugin.name} - ${result.error?.message}`);\n }\n\n const pluginMeta = result.plugin;\n this.plugins.set(pluginMeta.name, pluginMeta);\n \n this.logger.info(`Plugin registered: ${pluginMeta.name}@${pluginMeta.version}`, {\n plugin: pluginMeta.name,\n version: pluginMeta.version,\n });\n\n return this;\n }\n\n /**\n * Register a service instance directly\n */\n registerService(name: string, service: T): this {\n if (this.services.has(name)) {\n throw new Error(`[Kernel] Service '${name}' already registered`);\n }\n this.services.set(name, service);\n this.pluginLoader.registerService(name, service);\n this.logger.info(`Service '${name}' registered`, { service: name });\n return this;\n }\n\n /**\n * Register a service factory with lifecycle management\n */\n registerServiceFactory(\n name: string,\n factory: ServiceFactory,\n lifecycle: ServiceLifecycle = ServiceLifecycle.SINGLETON,\n dependencies?: string[]\n ): this {\n this.pluginLoader.registerServiceFactory({\n name,\n factory,\n lifecycle,\n dependencies,\n });\n return this;\n }\n\n /**\n * Pre-inject in-memory fallbacks for 'core' services that were not registered\n * by plugins during Phase 1. Called before Phase 2 so that all core services\n * (e.g. 'metadata', 'cache', 'queue') are resolvable via ctx.getService()\n * when plugin start() methods execute.\n */\n private preInjectCoreFallbacks() {\n if (this.config.skipSystemValidation) return;\n for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) {\n if (criticality !== 'core') continue;\n const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName);\n if (!hasService) {\n const factory = CORE_FALLBACK_FACTORIES[serviceName];\n if (factory) {\n const fallback = factory();\n this.registerService(serviceName, fallback);\n this.logger.debug(`[Kernel] Pre-injected in-memory fallback for '${serviceName}' before Phase 2`);\n }\n }\n }\n }\n\n /**\n * Validate Critical System Requirements\n */\n private validateSystemRequirements() {\n if (this.config.skipSystemValidation) {\n this.logger.debug('System requirement validation skipped');\n return;\n }\n\n this.logger.debug('Validating system service requirements...');\n const missingServices: string[] = [];\n const missingCoreServices: string[] = [];\n \n // Iterate through all defined requirements\n for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) {\n const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName);\n \n if (!hasService) {\n if (criticality === 'required') {\n this.logger.error(`CRITICAL: Required service missing: ${serviceName}`);\n missingServices.push(serviceName);\n } else if (criticality === 'core') {\n // Auto-inject in-memory fallback if available\n const factory = CORE_FALLBACK_FACTORIES[serviceName];\n if (factory) {\n const fallback = factory();\n this.registerService(serviceName, fallback);\n this.logger.warn(`Service '${serviceName}' not provided — using in-memory fallback`);\n } else {\n this.logger.warn(`CORE: Core service missing, functionality may be degraded: ${serviceName}`);\n missingCoreServices.push(serviceName);\n }\n } else {\n this.logger.info(`Info: Optional service not present: ${serviceName}`);\n }\n }\n }\n\n if (missingServices.length > 0) {\n const errorMsg = `System failed to start. Missing critical services: ${missingServices.join(', ')}`;\n this.logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n if (missingCoreServices.length > 0) {\n this.logger.warn(`System started with degraded capabilities. Missing core services: ${missingCoreServices.join(', ')}`);\n }\n \n this.logger.info('System requirement check passed');\n }\n\n /**\n * Bootstrap the kernel with enhanced features\n */\n async bootstrap(): Promise {\n if (this.state !== 'idle') {\n throw new Error('[Kernel] Kernel already bootstrapped');\n }\n\n this.state = 'initializing';\n this.logger.info('Bootstrap started');\n\n try {\n // Check for circular dependencies\n const cycles = this.pluginLoader.detectCircularDependencies();\n if (cycles.length > 0) {\n this.logger.warn('Circular service dependencies detected:', { cycles });\n }\n\n // Resolve plugin dependencies\n const orderedPlugins = this.resolveDependencies();\n\n // Phase 1: Init - Plugins register services\n this.logger.info('Phase 1: Init plugins');\n for (const plugin of orderedPlugins) {\n await this.initPluginWithTimeout(plugin);\n }\n\n // Pre-inject in-memory fallbacks for 'core' services that were not\n // registered by any plugin during Phase 1. This ensures services like\n // 'metadata', 'cache', 'queue', etc. are always available when plugins\n // call ctx.getService() during their start() methods.\n this.preInjectCoreFallbacks();\n\n // Phase 2: Start - Plugins execute business logic\n this.logger.info('Phase 2: Start plugins');\n this.state = 'running';\n \n for (const plugin of orderedPlugins) {\n const result = await this.startPluginWithTimeout(plugin);\n \n if (!result.success) {\n this.logger.error(`Plugin startup failed: ${plugin.name}`, result.error);\n \n if (this.config.rollbackOnFailure) {\n this.logger.warn('Rolling back started plugins...');\n await this.rollbackStartedPlugins();\n throw new Error(`Plugin ${plugin.name} failed to start - rollback complete`);\n }\n }\n }\n\n // Phase 3: Trigger kernel:ready hook\n this.validateSystemRequirements(); // Final check before ready\n this.logger.debug('Triggering kernel:ready hook');\n await this.context.trigger('kernel:ready');\n\n this.logger.info('✅ Bootstrap complete');\n } catch (error) {\n this.state = 'stopped';\n throw error;\n }\n }\n\n /**\n * Graceful shutdown with timeout\n */\n async shutdown(): Promise {\n if (this.state === 'stopped' || this.state === 'stopping') {\n this.logger.warn('Kernel already stopped or stopping');\n return;\n }\n\n if (this.state !== 'running') {\n throw new Error('[Kernel] Kernel not running');\n }\n\n this.state = 'stopping';\n this.logger.info('Graceful shutdown started');\n\n try {\n // Create shutdown promise with timeout\n const shutdownPromise = this.performShutdown();\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error('Shutdown timeout exceeded'));\n }, this.config.shutdownTimeout);\n });\n\n // Race between shutdown and timeout\n await Promise.race([shutdownPromise, timeoutPromise]);\n\n this.state = 'stopped';\n this.logger.info('✅ Graceful shutdown complete');\n } catch (error) {\n this.logger.error('Shutdown error - forcing stop', error as Error);\n this.state = 'stopped';\n throw error;\n } finally {\n // Cleanup logger resources\n await this.logger.destroy();\n }\n }\n\n /**\n * Check health of a specific plugin\n */\n async checkPluginHealth(pluginName: string): Promise {\n return await this.pluginLoader.checkPluginHealth(pluginName);\n }\n\n /**\n * Check health of all plugins\n */\n async checkAllPluginsHealth(): Promise> {\n const results = new Map();\n \n for (const pluginName of this.plugins.keys()) {\n const health = await this.checkPluginHealth(pluginName);\n results.set(pluginName, health);\n }\n \n return results;\n }\n\n /**\n * Get plugin startup metrics\n */\n getPluginMetrics(): Map {\n return new Map(this.pluginStartTimes);\n }\n\n /**\n * Get a service (sync helper)\n */\n getService(name: string): T {\n return this.context.getService(name);\n }\n\n /**\n * Get a service asynchronously (supports factories)\n */\n async getServiceAsync(name: string, scopeId?: string): Promise {\n return await this.pluginLoader.getService(name, scopeId);\n }\n\n /**\n * Check if kernel is running\n */\n isRunning(): boolean {\n return this.state === 'running';\n }\n\n /**\n * Get kernel state\n */\n getState(): string {\n return this.state;\n }\n\n // Private methods\n\n private async initPluginWithTimeout(plugin: PluginMetadata): Promise {\n const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout!;\n \n this.logger.debug(`Init: ${plugin.name}`, { plugin: plugin.name });\n \n const initPromise = plugin.init(this.context);\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(`Plugin ${plugin.name} init timeout after ${timeout}ms`));\n }, timeout);\n });\n\n await Promise.race([initPromise, timeoutPromise]);\n }\n\n private async startPluginWithTimeout(plugin: PluginMetadata): Promise {\n if (!plugin.start) {\n return { success: true, pluginName: plugin.name };\n }\n\n const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout!;\n const startTime = Date.now();\n \n this.logger.debug(`Start: ${plugin.name}`, { plugin: plugin.name });\n \n try {\n const startPromise = plugin.start(this.context);\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(`Plugin ${plugin.name} start timeout after ${timeout}ms`));\n }, timeout);\n });\n\n await Promise.race([startPromise, timeoutPromise]);\n \n const duration = Date.now() - startTime;\n this.startedPlugins.add(plugin.name);\n this.pluginStartTimes.set(plugin.name, duration);\n \n this.logger.debug(`Plugin started: ${plugin.name} (${duration}ms)`);\n \n return {\n success: true,\n pluginName: plugin.name,\n startTime: duration,\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n const isTimeout = (error as Error).message.includes('timeout');\n \n return {\n success: false,\n pluginName: plugin.name,\n error: error as Error,\n startTime: duration,\n timedOut: isTimeout,\n };\n }\n }\n\n private async rollbackStartedPlugins(): Promise {\n const pluginsToRollback = Array.from(this.startedPlugins).reverse();\n \n for (const pluginName of pluginsToRollback) {\n const plugin = this.plugins.get(pluginName);\n if (plugin?.destroy) {\n try {\n this.logger.debug(`Rollback: ${pluginName}`);\n await plugin.destroy();\n } catch (error) {\n this.logger.error(`Rollback failed for ${pluginName}`, error as Error);\n }\n }\n }\n \n this.startedPlugins.clear();\n }\n\n private async performShutdown(): Promise {\n // Trigger shutdown hook\n await this.context.trigger('kernel:shutdown');\n\n // Destroy plugins in reverse order\n const orderedPlugins = Array.from(this.plugins.values()).reverse();\n for (const plugin of orderedPlugins) {\n if (plugin.destroy) {\n this.logger.debug(`Destroy: ${plugin.name}`, { plugin: plugin.name });\n try {\n await plugin.destroy();\n } catch (error) {\n this.logger.error(`Error destroying plugin ${plugin.name}`, error as Error);\n }\n }\n }\n\n // Execute custom shutdown handlers\n for (const handler of this.shutdownHandlers) {\n try {\n await handler();\n } catch (error) {\n this.logger.error('Shutdown handler error', error as Error);\n }\n }\n }\n\n private resolveDependencies(): PluginMetadata[] {\n const resolved: PluginMetadata[] = [];\n const visited = new Set();\n const visiting = new Set();\n\n const visit = (pluginName: string) => {\n if (visited.has(pluginName)) return;\n \n if (visiting.has(pluginName)) {\n throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`);\n }\n\n const plugin = this.plugins.get(pluginName);\n if (!plugin) {\n throw new Error(`[Kernel] Plugin '${pluginName}' not found`);\n }\n\n visiting.add(pluginName);\n\n // Visit dependencies first\n const deps = plugin.dependencies || [];\n for (const dep of deps) {\n if (!this.plugins.has(dep)) {\n throw new Error(`[Kernel] Dependency '${dep}' not found for plugin '${pluginName}'`);\n }\n visit(dep);\n }\n\n visiting.delete(pluginName);\n visited.add(pluginName);\n resolved.push(plugin);\n };\n\n // Visit all plugins\n for (const pluginName of this.plugins.keys()) {\n visit(pluginName);\n }\n\n return resolved;\n }\n\n private registerShutdownSignals(): void {\n const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGQUIT'];\n let shutdownInProgress = false;\n \n const handleShutdown = async (signal: string) => {\n if (shutdownInProgress) {\n this.logger.warn(`Shutdown already in progress, ignoring ${signal}`);\n return;\n }\n \n shutdownInProgress = true;\n this.logger.info(`Received ${signal} - initiating graceful shutdown`);\n \n try {\n await this.shutdown();\n safeExit(0);\n } catch (error) {\n this.logger.error('Shutdown failed', error as Error);\n safeExit(1);\n }\n };\n \n if (isNode) {\n for (const signal of signals) {\n process.on(signal, () => handleShutdown(signal));\n }\n }\n }\n\n /**\n * Register a custom shutdown handler\n */\n onShutdown(handler: () => Promise): void {\n this.shutdownHandlers.push(handler);\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport type { PluginMetadata } from '../plugin-loader.js';\n\n/**\n * Plugin Configuration Validator\n * \n * Validates plugin configurations against Zod schemas to ensure:\n * 1. Type safety - all config values have correct types\n * 2. Business rules - values meet constraints (min/max, regex, etc.)\n * 3. Required fields - all mandatory configuration is provided\n * 4. Default values - missing optional fields get defaults\n * \n * Architecture:\n * - Uses Zod for runtime validation\n * - Provides detailed error messages with field paths\n * - Supports nested configuration objects\n * - Allows partial validation for incremental updates\n * \n * Usage:\n * ```typescript\n * const validator = new PluginConfigValidator(logger);\n * const validConfig = validator.validatePluginConfig(plugin, userConfig);\n * ```\n */\nexport class PluginConfigValidator {\n private logger: Logger;\n \n constructor(logger: Logger) {\n this.logger = logger;\n }\n \n /**\n * Validate plugin configuration against its Zod schema\n * \n * @param plugin - Plugin metadata with configSchema\n * @param config - User-provided configuration\n * @returns Validated and typed configuration\n * @throws Error with detailed validation errors\n */\n validatePluginConfig(plugin: PluginMetadata, config: any): T {\n if (!plugin.configSchema) {\n this.logger.debug(`Plugin ${plugin.name} has no config schema - skipping validation`);\n return config as T;\n }\n \n try {\n // Use Zod to parse and validate\n const validatedConfig = plugin.configSchema.parse(config);\n \n this.logger.debug(`✅ Plugin config validated: ${plugin.name}`, {\n plugin: plugin.name,\n configKeys: Object.keys(config || {}).length,\n });\n \n return validatedConfig as T;\n } catch (error) {\n if (error instanceof z.ZodError) {\n const formattedErrors = this.formatZodErrors(error);\n const errorMessage = [\n `Plugin ${plugin.name} configuration validation failed:`,\n ...formattedErrors.map(e => ` - ${e.path}: ${e.message}`),\n ].join('\\n');\n \n this.logger.error(errorMessage, undefined, {\n plugin: plugin.name,\n errors: formattedErrors,\n });\n \n throw new Error(errorMessage);\n }\n \n // Re-throw other errors\n throw error;\n }\n }\n \n /**\n * Validate partial configuration (for incremental updates)\n * \n * @param plugin - Plugin metadata\n * @param partialConfig - Partial configuration to validate\n * @returns Validated partial configuration\n */\n validatePartialConfig(plugin: PluginMetadata, partialConfig: any): Partial {\n if (!plugin.configSchema) {\n return partialConfig as Partial;\n }\n \n try {\n // Use Zod's partial() method for partial validation\n // Cast to ZodObject to access partial() method\n const partialSchema = (plugin.configSchema as any).partial();\n const validatedConfig = partialSchema.parse(partialConfig);\n \n this.logger.debug(`✅ Partial config validated: ${plugin.name}`);\n return validatedConfig as Partial;\n } catch (error) {\n if (error instanceof z.ZodError) {\n const formattedErrors = this.formatZodErrors(error);\n const errorMessage = [\n `Plugin ${plugin.name} partial configuration validation failed:`,\n ...formattedErrors.map(e => ` - ${e.path}: ${e.message}`),\n ].join('\\n');\n \n throw new Error(errorMessage);\n }\n \n throw error;\n }\n }\n \n /**\n * Get default configuration from schema\n * \n * @param plugin - Plugin metadata\n * @returns Default configuration object\n */\n getDefaultConfig(plugin: PluginMetadata): T | undefined {\n if (!plugin.configSchema) {\n return undefined;\n }\n \n try {\n // Parse empty object to get defaults\n const defaults = plugin.configSchema.parse({});\n this.logger.debug(`Default config extracted: ${plugin.name}`);\n return defaults as T;\n } catch (error) {\n // Schema may require some fields - return undefined\n this.logger.debug(`No default config available: ${plugin.name}`);\n return undefined;\n }\n }\n \n /**\n * Check if configuration is valid without throwing\n * \n * @param plugin - Plugin metadata\n * @param config - Configuration to check\n * @returns True if valid, false otherwise\n */\n isConfigValid(plugin: PluginMetadata, config: any): boolean {\n if (!plugin.configSchema) {\n return true;\n }\n \n const result = plugin.configSchema.safeParse(config);\n return result.success;\n }\n \n /**\n * Get configuration errors without throwing\n * \n * @param plugin - Plugin metadata\n * @param config - Configuration to check\n * @returns Array of validation errors, or empty array if valid\n */\n getConfigErrors(plugin: PluginMetadata, config: any): Array<{path: string; message: string}> {\n if (!plugin.configSchema) {\n return [];\n }\n \n const result = plugin.configSchema.safeParse(config);\n \n if (result.success) {\n return [];\n }\n \n return this.formatZodErrors(result.error);\n }\n \n // Private methods\n \n private formatZodErrors(error: z.ZodError): Array<{path: string; message: string}> {\n return error.issues.map((e: z.ZodIssue) => ({\n path: e.path.join('.') || 'root',\n message: e.message,\n }));\n }\n}\n\n/**\n * Create a plugin config validator\n * \n * @param logger - Logger instance\n * @returns Plugin config validator\n */\nexport function createPluginConfigValidator(logger: Logger): PluginConfigValidator {\n return new PluginConfigValidator(logger);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from './types.js';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport { z } from 'zod';\nimport { PluginConfigValidator } from './security/plugin-config-validator.js';\n\n/**\n * Service Lifecycle Types\n * Defines how services are instantiated and managed\n */\nexport enum ServiceLifecycle {\n /** Single instance shared across all requests */\n SINGLETON = 'singleton',\n /** New instance created for each request */\n TRANSIENT = 'transient',\n /** New instance per scope (e.g., per HTTP request) */\n SCOPED = 'scoped',\n}\n\n/**\n * Service Factory\n * Function that creates a service instance\n */\nexport type ServiceFactory = (ctx: PluginContext) => T | Promise;\n\n/**\n * Service Registration Options\n */\nexport interface ServiceRegistration {\n name: string;\n factory: ServiceFactory;\n lifecycle: ServiceLifecycle;\n dependencies?: string[];\n}\n\n/**\n * Plugin Metadata with Enhanced Features\n */\nexport interface PluginMetadata extends Plugin {\n /** Semantic version (e.g., \"1.0.0\") */\n version: string;\n \n /** Configuration schema for validation */\n configSchema?: z.ZodSchema;\n \n /** Plugin signature for security verification */\n signature?: string;\n \n /** Plugin health check function */\n healthCheck?(): Promise;\n \n /** Startup timeout in milliseconds (default: 30000) */\n startupTimeout?: number;\n \n /** Whether plugin supports hot reload */\n hotReloadable?: boolean;\n}\n\n/**\n * Plugin Health Status\n */\nexport interface PluginHealthStatus {\n healthy: boolean;\n message?: string;\n details?: Record;\n lastCheck?: Date;\n}\n\n/**\n * Plugin Load Result\n */\nexport interface PluginLoadResult {\n success: boolean;\n plugin?: PluginMetadata;\n error?: Error;\n loadTime?: number;\n}\n\n/**\n * Plugin Startup Result\n */\nexport interface PluginStartupResult {\n success: boolean;\n pluginName: string;\n startTime?: number;\n error?: Error;\n timedOut?: boolean;\n}\n\n/**\n * Version Compatibility Result\n */\nexport interface VersionCompatibility {\n compatible: boolean;\n pluginVersion: string;\n requiredVersion?: string;\n message?: string;\n}\n\n/**\n * Enhanced Plugin Loader\n * Provides advanced plugin loading capabilities with validation, security, and lifecycle management\n */\nexport class PluginLoader {\n private logger: Logger;\n private context?: PluginContext;\n private configValidator: PluginConfigValidator;\n private loadedPlugins: Map = new Map();\n private serviceFactories: Map = new Map();\n private serviceInstances: Map = new Map();\n private scopedServices: Map> = new Map();\n private creating: Set = new Set();\n\n constructor(logger: Logger) {\n this.logger = logger;\n this.configValidator = new PluginConfigValidator(logger);\n }\n\n /**\n * Set the plugin context for service factories\n */\n setContext(context: PluginContext): void {\n this.context = context;\n }\n\n /**\n * Get a synchronous service instance if it exists (Sync Helper)\n */\n getServiceInstance(name: string): T | undefined {\n return this.serviceInstances.get(name) as T;\n }\n\n /**\n * Load a plugin asynchronously with validation\n */\n async loadPlugin(plugin: Plugin): Promise {\n const startTime = Date.now();\n \n try {\n this.logger.info(`Loading plugin: ${plugin.name}`);\n \n // Convert to PluginMetadata\n const metadata = this.toPluginMetadata(plugin);\n \n // Validate plugin structure\n this.validatePluginStructure(metadata);\n \n // Check version compatibility\n const versionCheck = this.checkVersionCompatibility(metadata);\n if (!versionCheck.compatible) {\n throw new Error(`Version incompatible: ${versionCheck.message}`);\n }\n \n // Validate configuration if schema is provided\n if (metadata.configSchema) {\n this.validatePluginConfig(metadata);\n }\n \n // Verify signature if provided\n if (metadata.signature) {\n await this.verifyPluginSignature(metadata);\n }\n \n // Store loaded plugin\n this.loadedPlugins.set(metadata.name, metadata);\n \n const loadTime = Date.now() - startTime;\n this.logger.info(`Plugin loaded: ${plugin.name} (${loadTime}ms)`);\n \n return {\n success: true,\n plugin: metadata,\n loadTime,\n };\n } catch (error) {\n this.logger.error(`Failed to load plugin: ${plugin.name}`, error as Error);\n return {\n success: false,\n error: error as Error,\n loadTime: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Register a service with factory function\n */\n registerServiceFactory(registration: ServiceRegistration): void {\n if (this.serviceFactories.has(registration.name)) {\n throw new Error(`Service factory '${registration.name}' already registered`);\n }\n \n this.serviceFactories.set(registration.name, registration);\n this.logger.debug(`Service factory registered: ${registration.name} (${registration.lifecycle})`);\n }\n\n /**\n * Get or create a service instance based on lifecycle type\n */\n async getService(name: string, scopeId?: string): Promise {\n const registration = this.serviceFactories.get(name);\n \n if (!registration) {\n // Fall back to static service instances\n const instance = this.serviceInstances.get(name);\n if (!instance) {\n throw new Error(`Service '${name}' not found`);\n }\n return instance as T;\n }\n \n switch (registration.lifecycle) {\n case ServiceLifecycle.SINGLETON:\n return await this.getSingletonService(registration);\n \n case ServiceLifecycle.TRANSIENT:\n return await this.createTransientService(registration);\n \n case ServiceLifecycle.SCOPED:\n if (!scopeId) {\n throw new Error(`Scope ID required for scoped service '${name}'`);\n }\n return await this.getScopedService(registration, scopeId);\n \n default:\n throw new Error(`Unknown service lifecycle: ${registration.lifecycle}`);\n }\n }\n\n /**\n * Register a static service instance (legacy support)\n */\n registerService(name: string, service: any): void {\n if (this.serviceInstances.has(name)) {\n throw new Error(`Service '${name}' already registered`);\n }\n this.serviceInstances.set(name, service);\n }\n\n /**\n * Replace an existing service instance.\n * Used by optimization plugins to swap kernel internals.\n * @throws Error if service does not exist\n */\n replaceService(name: string, service: any): void {\n if (!this.hasService(name)) {\n throw new Error(`Service '${name}' not found`);\n }\n this.serviceInstances.set(name, service);\n }\n\n /**\n * Check if a service is registered (either as instance or factory)\n */\n hasService(name: string): boolean {\n return this.serviceInstances.has(name) || this.serviceFactories.has(name);\n }\n\n /**\n * Detect circular dependencies in service factories\n * Note: This only detects cycles in service dependencies, not plugin dependencies.\n * Plugin dependency cycles are detected in the kernel's resolveDependencies method.\n */\n detectCircularDependencies(): string[] {\n const cycles: string[] = [];\n const visited = new Set();\n const visiting = new Set();\n \n const visit = (serviceName: string, path: string[] = []) => {\n if (visiting.has(serviceName)) {\n const cycle = [...path, serviceName].join(' -> ');\n cycles.push(cycle);\n return;\n }\n \n if (visited.has(serviceName)) {\n return;\n }\n \n visiting.add(serviceName);\n \n const registration = this.serviceFactories.get(serviceName);\n if (registration?.dependencies) {\n for (const dep of registration.dependencies) {\n visit(dep, [...path, serviceName]);\n }\n }\n \n visiting.delete(serviceName);\n visited.add(serviceName);\n };\n \n for (const serviceName of this.serviceFactories.keys()) {\n visit(serviceName);\n }\n \n return cycles;\n }\n\n /**\n * Check plugin health\n */\n async checkPluginHealth(pluginName: string): Promise {\n const plugin = this.loadedPlugins.get(pluginName);\n \n if (!plugin) {\n return {\n healthy: false,\n message: 'Plugin not found',\n lastCheck: new Date(),\n };\n }\n \n if (!plugin.healthCheck) {\n return {\n healthy: true,\n message: 'No health check defined',\n lastCheck: new Date(),\n };\n }\n \n try {\n const status = await plugin.healthCheck();\n return {\n ...status,\n lastCheck: new Date(),\n };\n } catch (error) {\n return {\n healthy: false,\n message: `Health check failed: ${(error as Error).message}`,\n lastCheck: new Date(),\n };\n }\n }\n\n /**\n * Clear scoped services for a scope\n */\n clearScope(scopeId: string): void {\n this.scopedServices.delete(scopeId);\n this.logger.debug(`Cleared scope: ${scopeId}`);\n }\n\n /**\n * Get all loaded plugins\n */\n getLoadedPlugins(): Map {\n return new Map(this.loadedPlugins);\n }\n\n // Private helper methods\n\n private toPluginMetadata(plugin: Plugin): PluginMetadata {\n // Fix: Do not use object spread {...plugin} as it destroys the prototype chain for Class-based plugins.\n // Instead, cast the original object and inject default values if missing.\n const metadata = plugin as PluginMetadata;\n \n if (!metadata.version) {\n metadata.version = '0.0.0';\n }\n \n return metadata;\n }\n\n private validatePluginStructure(plugin: PluginMetadata): void {\n if (!plugin.name) {\n throw new Error('Plugin name is required');\n }\n \n if (!plugin.init) {\n throw new Error('Plugin init function is required');\n }\n \n if (!this.isValidSemanticVersion(plugin.version)) {\n throw new Error(`Invalid semantic version: ${plugin.version}`);\n }\n }\n\n private checkVersionCompatibility(plugin: PluginMetadata): VersionCompatibility {\n // Basic semantic version compatibility check\n // In a real implementation, this would check against kernel version\n const version = plugin.version;\n \n if (!this.isValidSemanticVersion(version)) {\n return {\n compatible: false,\n pluginVersion: version,\n message: 'Invalid semantic version format',\n };\n }\n \n return {\n compatible: true,\n pluginVersion: version,\n };\n }\n\n private isValidSemanticVersion(version: string): boolean {\n const semverRegex = /^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?(\\+[a-zA-Z0-9.-]+)?$/;\n return semverRegex.test(version);\n }\n\n private validatePluginConfig(plugin: PluginMetadata, config?: any): void {\n if (!plugin.configSchema) {\n return;\n }\n\n if (config === undefined) {\n // In loadPlugin, we often don't have the config yet.\n // We skip validation here or valid against empty object if schema allows?\n // For now, let's keep the logging behavior but note it's delegating\n this.logger.debug(`Plugin ${plugin.name} has configuration schema (config validation postponed)`);\n return;\n }\n\n this.configValidator.validatePluginConfig(plugin, config);\n }\n\n private async verifyPluginSignature(plugin: PluginMetadata): Promise {\n if (!plugin.signature) {\n return;\n }\n \n // Plugin signature verification is now implemented in PluginSignatureVerifier\n // This is a placeholder that logs the verification would happen\n // The actual verification should be done by the caller with proper security config\n this.logger.debug(`Plugin ${plugin.name} has signature (use PluginSignatureVerifier for verification)`);\n }\n\n private async getSingletonService(registration: ServiceRegistration): Promise {\n let instance = this.serviceInstances.get(registration.name);\n \n if (!instance) {\n // Create instance (would need context)\n instance = await this.createServiceInstance(registration);\n this.serviceInstances.set(registration.name, instance);\n this.logger.debug(`Singleton service created: ${registration.name}`);\n }\n \n return instance as T;\n }\n\n private async createTransientService(registration: ServiceRegistration): Promise {\n const instance = await this.createServiceInstance(registration);\n this.logger.debug(`Transient service created: ${registration.name}`);\n return instance as T;\n }\n\n private async getScopedService(registration: ServiceRegistration, scopeId: string): Promise {\n if (!this.scopedServices.has(scopeId)) {\n this.scopedServices.set(scopeId, new Map());\n }\n \n const scope = this.scopedServices.get(scopeId)!;\n let instance = scope.get(registration.name);\n \n if (!instance) {\n instance = await this.createServiceInstance(registration);\n scope.set(registration.name, instance);\n this.logger.debug(`Scoped service created: ${registration.name} (scope: ${scopeId})`);\n }\n \n return instance as T;\n }\n\n private async createServiceInstance(registration: ServiceRegistration): Promise {\n if (!this.context) {\n throw new Error(`[PluginLoader] Context not set - cannot create service '${registration.name}'`);\n }\n\n if (this.creating.has(registration.name)) {\n throw new Error(`Circular dependency detected: ${Array.from(this.creating).join(' -> ')} -> ${registration.name}`);\n }\n\n this.creating.add(registration.name);\n try {\n return await registration.factory(this.context);\n } finally {\n this.creating.delete(registration.name);\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * In-memory Map-backed cache fallback.\n *\n * Implements the ICacheService contract with basic get/set/delete/has/clear\n * and TTL expiry. Used by ObjectKernel as an automatic fallback when no\n * real cache plugin (e.g. Redis) is registered.\n */\nexport function createMemoryCache() {\n const store = new Map();\n let hits = 0;\n let misses = 0;\n return {\n _fallback: true, _serviceName: 'cache',\n async get(key: string): Promise {\n const entry = store.get(key);\n if (!entry || (entry.expires && Date.now() > entry.expires)) {\n store.delete(key);\n misses++;\n return undefined;\n }\n hits++;\n return entry.value as T;\n },\n async set(key: string, value: T, ttl?: number): Promise {\n store.set(key, { value, expires: ttl ? Date.now() + ttl * 1000 : undefined });\n },\n async delete(key: string): Promise { return store.delete(key); },\n async has(key: string): Promise { return store.has(key); },\n async clear(): Promise { store.clear(); },\n async stats() { return { hits, misses, keyCount: store.size }; },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * In-memory publish/subscribe queue fallback.\n *\n * Implements the IQueueService contract with synchronous in-process delivery.\n * Used by ObjectKernel as an automatic fallback when no real queue plugin\n * (e.g. BullMQ / RabbitMQ) is registered.\n */\nexport function createMemoryQueue() {\n const handlers = new Map();\n let msgId = 0;\n return {\n _fallback: true, _serviceName: 'queue',\n async publish(queue: string, data: T): Promise {\n const id = `fallback-msg-${++msgId}`;\n const fns = handlers.get(queue) ?? [];\n for (const fn of fns) fn({ id, data, attempts: 1, timestamp: Date.now() });\n return id;\n },\n async subscribe(queue: string, handler: (msg: any) => Promise): Promise {\n handlers.set(queue, [...(handlers.get(queue) ?? []), handler]);\n },\n async unsubscribe(queue: string): Promise { handlers.delete(queue); },\n async getQueueSize(): Promise { return 0; },\n async purge(queue: string): Promise { handlers.delete(queue); },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * In-memory job scheduler fallback.\n *\n * Implements the IJobService contract with basic schedule/cancel/trigger\n * operations. Used by ObjectKernel as an automatic fallback when no real\n * job plugin (e.g. Agenda / BullMQ) is registered.\n */\nexport function createMemoryJob() {\n const jobs = new Map();\n return {\n _fallback: true, _serviceName: 'job',\n async schedule(name: string, schedule: any, handler: any): Promise { jobs.set(name, { schedule, handler }); },\n async cancel(name: string): Promise { jobs.delete(name); },\n async trigger(name: string, data?: unknown): Promise {\n const job = jobs.get(name);\n if (job?.handler) await job.handler({ jobId: name, data });\n },\n async getExecutions(): Promise { return []; },\n async listJobs(): Promise { return [...jobs.keys()]; },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Resolve a locale code against available locales with fallback.\n *\n * Fallback chain:\n * 1. Exact match (e.g. `zh-CN` → `zh-CN`)\n * 2. Case-insensitive match (e.g. `zh-cn` → `zh-CN`)\n * 3. Base language match (e.g. `zh-CN` → `zh`)\n * 4. Variant expansion (e.g. `zh` → `zh-CN`)\n *\n * Returns the matched locale code, or `undefined` when no match is found.\n */\nexport function resolveLocale(requestedLocale: string, availableLocales: string[]): string | undefined {\n if (availableLocales.length === 0) return undefined;\n\n // 1. Exact match\n if (availableLocales.includes(requestedLocale)) return requestedLocale;\n\n // 2. Case-insensitive match\n const lower = requestedLocale.toLowerCase();\n const caseMatch = availableLocales.find(l => l.toLowerCase() === lower);\n if (caseMatch) return caseMatch;\n\n // 3. Base language match (zh-CN → zh)\n const baseLang = requestedLocale.split('-')[0].toLowerCase();\n const baseMatch = availableLocales.find(l => l.toLowerCase() === baseLang);\n if (baseMatch) return baseMatch;\n\n // 4. Variant expansion (zh → zh-CN, zh-TW, etc. — first match wins)\n const variantMatch = availableLocales.find(l => l.split('-')[0].toLowerCase() === baseLang);\n if (variantMatch) return variantMatch;\n\n return undefined;\n}\n\n/**\n * In-memory i18n service fallback.\n *\n * Implements the II18nService contract with basic translate/load/getLocales\n * operations. Used by ObjectKernel as an automatic fallback when no real\n * i18n plugin (e.g. I18nServicePlugin) is registered.\n *\n * Supports runtime translation loading, locale management, and\n * locale code fallback (e.g. `zh` → `zh-CN`).\n * Does not load files from disk — operates purely in-memory.\n */\nexport function createMemoryI18n() {\n const translations = new Map>();\n let defaultLocale = 'en';\n\n /**\n * Resolve a dot-notation key from a nested object.\n */\n function resolveKey(data: Record, key: string): string | undefined {\n const parts = key.split('.');\n let current: unknown = data;\n for (const part of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n current = (current as Record)[part];\n }\n return typeof current === 'string' ? current : undefined;\n }\n\n /**\n * Find translation data for a locale, with fallback resolution.\n */\n function resolveTranslations(locale: string): Record | undefined {\n // Exact match\n if (translations.has(locale)) return translations.get(locale);\n\n // Locale fallback (zh → zh-CN, en-us → en-US, etc.)\n const resolved = resolveLocale(locale, [...translations.keys()]);\n if (resolved) return translations.get(resolved);\n\n return undefined;\n }\n\n return {\n _fallback: true, _serviceName: 'i18n',\n\n t(key: string, locale: string, params?: Record): string {\n const data = resolveTranslations(locale) ?? translations.get(defaultLocale);\n const value = data ? resolveKey(data, key) : undefined;\n if (value == null) return key;\n if (!params) return value;\n // Interpolation format: {{paramName}} — matches FileI18nAdapter convention\n return value.replace(/\\{\\{(\\w+)\\}\\}/g, (_, name) => String(params[name] ?? `{{${name}}}`));\n },\n\n getTranslations(locale: string): Record {\n return resolveTranslations(locale) ?? {};\n },\n\n loadTranslations(locale: string, data: Record): void {\n const existing = translations.get(locale) ?? {};\n translations.set(locale, { ...existing, ...data });\n },\n\n getLocales(): string[] {\n return [...translations.keys()];\n },\n\n getDefaultLocale(): string {\n return defaultLocale;\n },\n\n setDefaultLocale(locale: string): void {\n defaultLocale = locale;\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * In-memory metadata service fallback.\n *\n * Implements the IMetadataService contract with a simple Map-of-Maps store.\n * Used by ObjectKernel as an automatic fallback when no real metadata plugin\n * (e.g. MetadataPlugin with file-system persistence) is registered.\n */\nexport function createMemoryMetadata() {\n // type -> name -> data\n const store = new Map>();\n\n function getTypeMap(type: string): Map {\n let map = store.get(type);\n if (!map) {\n map = new Map();\n store.set(type, map);\n }\n return map;\n }\n\n return {\n _fallback: true, _serviceName: 'metadata',\n async register(type: string, name: string, data: any): Promise {\n getTypeMap(type).set(name, data);\n },\n async get(type: string, name: string): Promise {\n return getTypeMap(type).get(name);\n },\n async list(type: string): Promise {\n return Array.from(getTypeMap(type).values());\n },\n async unregister(type: string, name: string): Promise {\n getTypeMap(type).delete(name);\n },\n async exists(type: string, name: string): Promise {\n return getTypeMap(type).has(name);\n },\n async listNames(type: string): Promise {\n return Array.from(getTypeMap(type).keys());\n },\n async getObject(name: string): Promise {\n return getTypeMap('object').get(name);\n },\n async listObjects(): Promise {\n return Array.from(getTypeMap('object').values());\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { createMemoryCache } from './memory-cache.js';\nimport { createMemoryQueue } from './memory-queue.js';\nimport { createMemoryJob } from './memory-job.js';\nimport { createMemoryI18n } from './memory-i18n.js';\nimport { createMemoryMetadata } from './memory-metadata.js';\n\nexport { createMemoryCache } from './memory-cache.js';\nexport { createMemoryQueue } from './memory-queue.js';\nexport { createMemoryJob } from './memory-job.js';\nexport { createMemoryI18n, resolveLocale } from './memory-i18n.js';\nexport { createMemoryMetadata } from './memory-metadata.js';\n\n/**\n * Map of core-criticality service names to their in-memory fallback factories.\n * Used by ObjectKernel.validateSystemRequirements() to auto-inject fallbacks\n * when no real plugin provides the service.\n */\nexport const CORE_FALLBACK_FACTORIES: Record Record> = {\n metadata: createMemoryMetadata,\n cache: createMemoryCache,\n queue: createMemoryQueue,\n job: createMemoryJob,\n i18n: createMemoryI18n,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin } from './types.js';\nimport { createLogger, ObjectLogger } from './logger.js';\nimport type { LoggerConfig } from '@objectstack/spec/system';\nimport { ObjectKernelBase } from './kernel-base.js';\n\n/**\n * ObjectKernel - MiniKernel Architecture\n * \n * A highly modular, plugin-based microkernel that:\n * - Manages plugin lifecycle (init, start, destroy)\n * - Provides dependency injection via service registry\n * - Implements event/hook system for inter-plugin communication\n * - Handles dependency resolution (topological sort)\n * - Provides configurable logging for server and browser\n * \n * Core philosophy:\n * - Business logic is completely separated into plugins\n * - Kernel only manages lifecycle, DI, and hooks\n * - Plugins are loaded as equal building blocks\n */\nexport class LiteKernel extends ObjectKernelBase {\n constructor(config?: { logger?: Partial }) {\n const logger = createLogger(config?.logger);\n super(logger);\n \n // Initialize context after logger is created\n this.context = this.createContext();\n }\n\n /**\n * Register a plugin\n * @param plugin - Plugin instance\n */\n use(plugin: Plugin): this {\n this.validateIdle();\n\n const pluginName = plugin.name;\n if (this.plugins.has(pluginName)) {\n throw new Error(`[Kernel] Plugin '${pluginName}' already registered`);\n }\n\n this.plugins.set(pluginName, plugin);\n return this;\n }\n\n /**\n * Bootstrap the kernel\n * 1. Resolve dependencies (topological sort)\n * 2. Init phase - plugins register services\n * 3. Start phase - plugins execute business logic\n * 4. Trigger 'kernel:ready' hook\n */\n async bootstrap(): Promise {\n this.validateState('idle');\n\n this.state = 'initializing';\n this.logger.info('Bootstrap started');\n\n // Resolve dependencies\n const orderedPlugins = this.resolveDependencies();\n\n // Phase 1: Init - Plugins register services\n this.logger.info('Phase 1: Init plugins');\n for (const plugin of orderedPlugins) {\n await this.runPluginInit(plugin);\n }\n\n // Phase 2: Start - Plugins execute business logic\n this.logger.info('Phase 2: Start plugins');\n this.state = 'running';\n \n for (const plugin of orderedPlugins) {\n await this.runPluginStart(plugin);\n }\n\n // Trigger ready hook\n await this.triggerHook('kernel:ready');\n this.logger.info('✅ Bootstrap complete', { \n pluginCount: this.plugins.size \n });\n }\n\n /**\n * Shutdown the kernel\n * Calls destroy on all plugins in reverse order\n */\n async shutdown(): Promise {\n await this.destroy();\n }\n\n /**\n * Graceful shutdown - destroy all plugins in reverse order\n */\n async destroy(): Promise {\n if (this.state === 'stopped') {\n this.logger.warn('Kernel already stopped');\n return;\n }\n\n this.state = 'stopping';\n this.logger.info('Shutdown started');\n\n // Trigger shutdown hook\n await this.triggerHook('kernel:shutdown');\n\n // Destroy plugins in reverse order\n const orderedPlugins = this.resolveDependencies();\n for (const plugin of orderedPlugins.reverse()) {\n await this.runPluginDestroy(plugin);\n }\n\n this.state = 'stopped';\n this.logger.info('✅ Shutdown complete');\n \n // Cleanup logger resources\n if (this.logger && typeof (this.logger as ObjectLogger).destroy === 'function') {\n await (this.logger as ObjectLogger).destroy();\n }\n }\n\n /**\n * Get a service from the registry\n * Convenience method for external access\n */\n getService(name: string): T {\n return this.context.getService(name);\n }\n\n /**\n * Check if kernel is running\n */\n isRunning(): boolean {\n return this.state === 'running';\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n ApiRegistry as ApiRegistryType,\n ApiRegistryEntry,\n ApiRegistryEntryInput,\n ApiEndpointRegistration,\n ConflictResolutionStrategy,\n ApiDiscoveryQuery,\n ApiDiscoveryResponse,\n} from '@objectstack/spec/api';\nimport { ApiRegistryEntrySchema } from '@objectstack/spec/api';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport { getEnv } from './utils/env.js';\n\n/**\n * API Registry Service\n * \n * Central registry for managing API endpoints across different protocols.\n * Provides endpoint registration, discovery, and conflict resolution.\n * \n * **Features:**\n * - Multi-protocol support (REST, GraphQL, OData, WebSocket, etc.)\n * - Route conflict detection with configurable resolution strategies\n * - RBAC permission integration\n * - Dynamic schema linking with ObjectQL references\n * - Plugin API registration\n * \n * **Architecture Alignment:**\n * - Kubernetes: Service Discovery & API Server\n * - AWS API Gateway: Unified API Management\n * - Kong Gateway: Plugin-based API Management\n * \n * @example\n * ```typescript\n * const registry = new ApiRegistry(logger, 'priority');\n * \n * // Register an API\n * registry.registerApi({\n * id: 'customer_api',\n * name: 'Customer API',\n * type: 'rest',\n * version: 'v1',\n * basePath: '/api/v1/customers',\n * endpoints: [...]\n * });\n * \n * // Discover APIs\n * const apis = registry.findApis({ type: 'rest', status: 'active' });\n * \n * // Get registry snapshot\n * const snapshot = registry.getRegistry();\n * ```\n */\nexport class ApiRegistry {\n private apis: Map = new Map();\n private endpoints: Map = new Map();\n private routes: Map = new Map();\n \n // Performance optimization: Auxiliary indices for O(1) lookups\n private apisByType: Map> = new Map();\n private apisByTag: Map> = new Map();\n private apisByStatus: Map> = new Map();\n \n private conflictResolution: ConflictResolutionStrategy;\n private logger: Logger;\n private version: string;\n private updatedAt: string;\n\n constructor(\n logger: Logger,\n conflictResolution: ConflictResolutionStrategy = 'error',\n version: string = '1.0.0'\n ) {\n this.logger = logger;\n this.conflictResolution = conflictResolution;\n this.version = version;\n this.updatedAt = new Date().toISOString();\n }\n\n /**\n * Register an API with its endpoints\n * \n * @param api - API registry entry\n * @throws Error if API already registered or route conflicts detected\n */\n registerApi(api: ApiRegistryEntryInput): void {\n // Check if API already exists\n if (this.apis.has(api.id)) {\n throw new Error(`[ApiRegistry] API '${api.id}' already registered`);\n }\n\n // Parse and validate the input using Zod schema\n const fullApi = ApiRegistryEntrySchema.parse(api);\n\n // Validate and register endpoints\n for (const endpoint of fullApi.endpoints) {\n this.validateEndpoint(endpoint, fullApi.id);\n }\n\n // Register the API\n this.apis.set(fullApi.id, fullApi);\n \n // Register endpoints\n for (const endpoint of fullApi.endpoints) {\n this.registerEndpoint(fullApi.id, endpoint);\n }\n\n // Update auxiliary indices for performance optimization\n this.updateIndices(fullApi);\n\n this.updatedAt = new Date().toISOString();\n this.logger.info(`API registered: ${fullApi.id}`, {\n api: fullApi.id,\n type: fullApi.type,\n endpointCount: fullApi.endpoints.length,\n });\n }\n\n /**\n * Unregister an API and all its endpoints\n * \n * @param apiId - API identifier\n */\n unregisterApi(apiId: string): void {\n const api = this.apis.get(apiId);\n if (!api) {\n throw new Error(`[ApiRegistry] API '${apiId}' not found`);\n }\n\n // Remove all endpoints\n for (const endpoint of api.endpoints) {\n this.unregisterEndpoint(apiId, endpoint.id);\n }\n\n // Remove from auxiliary indices\n this.removeFromIndices(api);\n\n // Remove the API\n this.apis.delete(apiId);\n this.updatedAt = new Date().toISOString();\n \n this.logger.info(`API unregistered: ${apiId}`);\n }\n\n /**\n * Register a single endpoint\n * \n * @param apiId - API identifier\n * @param endpoint - Endpoint registration\n * @throws Error if route conflict detected\n */\n private registerEndpoint(apiId: string, endpoint: ApiEndpointRegistration): void {\n const endpointKey = `${apiId}:${endpoint.id}`;\n \n // Check if endpoint already registered\n if (this.endpoints.has(endpointKey)) {\n throw new Error(`[ApiRegistry] Endpoint '${endpoint.id}' already registered for API '${apiId}'`);\n }\n\n // Register endpoint\n this.endpoints.set(endpointKey, { api: apiId, endpoint });\n\n // Register route if path is defined\n if (endpoint.path) {\n this.registerRoute(apiId, endpoint);\n }\n }\n\n /**\n * Unregister a single endpoint\n * \n * @param apiId - API identifier\n * @param endpointId - Endpoint identifier\n */\n private unregisterEndpoint(apiId: string, endpointId: string): void {\n const endpointKey = `${apiId}:${endpointId}`;\n const entry = this.endpoints.get(endpointKey);\n \n if (!entry) {\n return; // Already unregistered\n }\n\n // Unregister route\n if (entry.endpoint.path) {\n const routeKey = this.getRouteKey(entry.endpoint);\n this.routes.delete(routeKey);\n }\n\n // Unregister endpoint\n this.endpoints.delete(endpointKey);\n }\n\n /**\n * Register a route with conflict detection\n * \n * @param apiId - API identifier\n * @param endpoint - Endpoint registration\n * @throws Error if route conflict detected (based on strategy)\n */\n private registerRoute(apiId: string, endpoint: ApiEndpointRegistration): void {\n const routeKey = this.getRouteKey(endpoint);\n const priority = endpoint.priority ?? 100;\n const existingRoute = this.routes.get(routeKey);\n\n if (existingRoute) {\n // Route conflict detected\n this.handleRouteConflict(routeKey, apiId, endpoint, existingRoute, priority);\n return;\n }\n\n // Register route\n this.routes.set(routeKey, {\n api: apiId,\n endpointId: endpoint.id,\n priority,\n });\n }\n\n /**\n * Handle route conflict based on resolution strategy\n * \n * @param routeKey - Route key\n * @param apiId - New API identifier\n * @param endpoint - New endpoint\n * @param existingRoute - Existing route registration\n * @param newPriority - New endpoint priority\n * @throws Error if strategy is 'error'\n */\n private handleRouteConflict(\n routeKey: string,\n apiId: string,\n endpoint: ApiEndpointRegistration,\n existingRoute: { api: string; endpointId: string; priority: number },\n newPriority: number\n ): void {\n const strategy = this.conflictResolution;\n\n switch (strategy) {\n case 'error':\n throw new Error(\n `[ApiRegistry] Route conflict detected: '${routeKey}' is already registered by API '${existingRoute.api}' endpoint '${existingRoute.endpointId}'`\n );\n\n case 'priority':\n if (newPriority > existingRoute.priority) {\n // New endpoint has higher priority, replace\n this.logger.warn(\n `Route conflict: replacing '${routeKey}' (priority ${existingRoute.priority} -> ${newPriority})`,\n {\n oldApi: existingRoute.api,\n oldEndpoint: existingRoute.endpointId,\n newApi: apiId,\n newEndpoint: endpoint.id,\n }\n );\n this.routes.set(routeKey, {\n api: apiId,\n endpointId: endpoint.id,\n priority: newPriority,\n });\n } else {\n // Existing endpoint has higher priority, keep it\n this.logger.warn(\n `Route conflict: keeping existing '${routeKey}' (priority ${existingRoute.priority} >= ${newPriority})`,\n {\n existingApi: existingRoute.api,\n existingEndpoint: existingRoute.endpointId,\n newApi: apiId,\n newEndpoint: endpoint.id,\n }\n );\n }\n break;\n\n case 'first-wins':\n // Keep existing route\n this.logger.warn(\n `Route conflict: keeping first registered '${routeKey}'`,\n {\n existingApi: existingRoute.api,\n newApi: apiId,\n }\n );\n break;\n\n case 'last-wins':\n // Replace with new route\n this.logger.warn(\n `Route conflict: replacing with last registered '${routeKey}'`,\n {\n oldApi: existingRoute.api,\n newApi: apiId,\n }\n );\n this.routes.set(routeKey, {\n api: apiId,\n endpointId: endpoint.id,\n priority: newPriority,\n });\n break;\n\n default:\n throw new Error(`[ApiRegistry] Unknown conflict resolution strategy: ${strategy}`);\n }\n }\n\n /**\n * Generate a unique route key for conflict detection\n * \n * NOTE: This implementation uses exact string matching for route conflict detection.\n * It works well for static paths but has limitations with parameterized routes.\n * For example, `/api/users/:id` and `/api/users/:userId` will NOT be detected as conflicts\n * even though they are semantically identical parameterized patterns. Similarly,\n * `/api/:resource/list` and `/api/:entity/list` would also not be detected as conflicting.\n * \n * For more advanced conflict detection (e.g., path-to-regexp pattern matching),\n * consider integrating with your routing library's conflict detection mechanism.\n * \n * @param endpoint - Endpoint registration\n * @returns Route key (e.g., \"GET:/api/v1/customers/:id\")\n */\n private getRouteKey(endpoint: ApiEndpointRegistration): string {\n const method = endpoint.method || 'ANY';\n return `${method}:${endpoint.path}`;\n }\n\n /**\n * Validate endpoint registration\n * \n * @param endpoint - Endpoint to validate\n * @param apiId - API identifier (for error messages)\n * @throws Error if endpoint is invalid\n */\n private validateEndpoint(endpoint: ApiEndpointRegistration, apiId: string): void {\n if (!endpoint.id) {\n throw new Error(`[ApiRegistry] Endpoint in API '${apiId}' missing 'id' field`);\n }\n\n if (!endpoint.path) {\n throw new Error(`[ApiRegistry] Endpoint '${endpoint.id}' in API '${apiId}' missing 'path' field`);\n }\n }\n\n /**\n * Get an API by ID\n * \n * @param apiId - API identifier\n * @returns API registry entry or undefined\n */\n getApi(apiId: string): ApiRegistryEntry | undefined {\n return this.apis.get(apiId);\n }\n\n /**\n * Get all registered APIs\n * \n * @returns Array of all APIs\n */\n getAllApis(): ApiRegistryEntry[] {\n return Array.from(this.apis.values());\n }\n\n /**\n * Find APIs matching query criteria\n * \n * Performance optimized with auxiliary indices for O(1) lookups on type, tags, and status.\n * \n * @param query - Discovery query parameters\n * @returns Matching APIs\n */\n findApis(query: ApiDiscoveryQuery): ApiDiscoveryResponse {\n let resultIds: Set | undefined;\n\n // Use indices for performance-optimized filtering\n // Start with the most restrictive filter to minimize subsequent filtering\n \n // Filter by type (using index for O(1) lookup)\n if (query.type) {\n const typeIds = this.apisByType.get(query.type);\n if (!typeIds || typeIds.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n resultIds = new Set(typeIds);\n }\n\n // Filter by status (using index for O(1) lookup)\n if (query.status) {\n const statusIds = this.apisByStatus.get(query.status);\n if (!statusIds || statusIds.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n \n if (resultIds) {\n // Intersect with previous results\n resultIds = new Set([...resultIds].filter(id => statusIds.has(id)));\n } else {\n resultIds = new Set(statusIds);\n }\n \n if (resultIds.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n }\n\n // Filter by tags (using index for O(M) lookup where M is number of tags)\n if (query.tags && query.tags.length > 0) {\n const tagMatches = new Set();\n \n for (const tag of query.tags) {\n const tagIds = this.apisByTag.get(tag);\n if (tagIds) {\n tagIds.forEach(id => tagMatches.add(id));\n }\n }\n \n if (tagMatches.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n \n if (resultIds) {\n // Intersect with previous results\n resultIds = new Set([...resultIds].filter(id => tagMatches.has(id)));\n } else {\n resultIds = tagMatches;\n }\n \n if (resultIds.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n }\n\n // Get the actual API objects\n let results: ApiRegistryEntry[];\n if (resultIds) {\n results = Array.from(resultIds)\n .map(id => this.apis.get(id))\n .filter((api): api is ApiRegistryEntry => api !== undefined);\n } else {\n results = Array.from(this.apis.values());\n }\n\n // Apply remaining filters that don't have indices (less common filters)\n \n // Filter by plugin source\n if (query.pluginSource) {\n results = results.filter(\n (api) => api.metadata?.pluginSource === query.pluginSource\n );\n }\n\n // Filter by version\n if (query.version) {\n results = results.filter((api) => api.version === query.version);\n }\n\n // Search in name/description\n if (query.search) {\n const searchLower = query.search.toLowerCase();\n results = results.filter(\n (api) =>\n api.name.toLowerCase().includes(searchLower) ||\n (api.description && api.description.toLowerCase().includes(searchLower))\n );\n }\n\n return {\n apis: results,\n total: results.length,\n filters: query,\n };\n }\n\n /**\n * Get endpoint by API ID and endpoint ID\n * \n * @param apiId - API identifier\n * @param endpointId - Endpoint identifier\n * @returns Endpoint registration or undefined\n */\n getEndpoint(apiId: string, endpointId: string): ApiEndpointRegistration | undefined {\n const key = `${apiId}:${endpointId}`;\n return this.endpoints.get(key)?.endpoint;\n }\n\n /**\n * Find endpoint by route (method + path)\n * \n * @param method - HTTP method\n * @param path - URL path\n * @returns Endpoint registration or undefined\n */\n findEndpointByRoute(method: string, path: string): {\n api: ApiRegistryEntry;\n endpoint: ApiEndpointRegistration;\n } | undefined {\n const routeKey = `${method}:${path}`;\n const route = this.routes.get(routeKey);\n \n if (!route) {\n return undefined;\n }\n\n const api = this.apis.get(route.api);\n const endpoint = this.getEndpoint(route.api, route.endpointId);\n\n if (!api || !endpoint) {\n return undefined;\n }\n\n return { api, endpoint };\n }\n\n /**\n * Get complete registry snapshot\n * \n * @returns Current registry state\n */\n getRegistry(): ApiRegistryType {\n const apis = Array.from(this.apis.values());\n \n // Group by type\n const byType: Record = {};\n for (const api of apis) {\n if (!byType[api.type]) {\n byType[api.type] = [];\n }\n byType[api.type].push(api);\n }\n\n // Group by status\n const byStatus: Record = {};\n for (const api of apis) {\n const status = api.metadata?.status || 'active';\n if (!byStatus[status]) {\n byStatus[status] = [];\n }\n byStatus[status].push(api);\n }\n\n // Count total endpoints\n const totalEndpoints = apis.reduce(\n (sum, api) => sum + api.endpoints.length,\n 0\n );\n\n return {\n version: this.version,\n conflictResolution: this.conflictResolution,\n apis,\n totalApis: apis.length,\n totalEndpoints,\n byType,\n byStatus,\n updatedAt: this.updatedAt,\n };\n }\n\n /**\n * Clear all registered APIs\n * \n * **⚠️ SAFETY WARNING:**\n * This method clears all registered APIs and should be used with caution.\n * \n * **Usage Restrictions:**\n * - In production environments (NODE_ENV=production), a `force: true` parameter is required\n * - Primarily intended for testing and development hot-reload scenarios\n * \n * @param options - Clear options\n * @param options.force - Force clear in production environment (default: false)\n * @throws Error if called in production without force flag\n * \n * @example Safe usage in tests\n * ```typescript\n * beforeEach(() => {\n * registry.clear(); // OK in test environment\n * });\n * ```\n * \n * @example Usage in production (requires explicit force)\n * ```typescript\n * // In production, explicit force is required\n * registry.clear({ force: true });\n * ```\n */\n clear(options: { force?: boolean } = {}): void {\n const isProduction = this.isProductionEnvironment();\n \n if (isProduction && !options.force) {\n throw new Error(\n '[ApiRegistry] Cannot clear registry in production environment without force flag. ' +\n 'Use clear({ force: true }) if you really want to clear the registry.'\n );\n }\n\n this.apis.clear();\n this.endpoints.clear();\n this.routes.clear();\n \n // Clear auxiliary indices\n this.apisByType.clear();\n this.apisByTag.clear();\n this.apisByStatus.clear();\n \n this.updatedAt = new Date().toISOString();\n \n if (isProduction) {\n this.logger.warn('API registry forcefully cleared in production', { force: options.force });\n } else {\n this.logger.info('API registry cleared');\n }\n }\n\n /**\n * Get registry statistics\n * \n * @returns Registry statistics\n */\n getStats(): {\n totalApis: number;\n totalEndpoints: number;\n totalRoutes: number;\n apisByType: Record;\n endpointsByApi: Record;\n } {\n const apis = Array.from(this.apis.values());\n \n const apisByType: Record = {};\n for (const api of apis) {\n apisByType[api.type] = (apisByType[api.type] || 0) + 1;\n }\n\n const endpointsByApi: Record = {};\n for (const api of apis) {\n endpointsByApi[api.id] = api.endpoints.length;\n }\n\n return {\n totalApis: this.apis.size,\n totalEndpoints: this.endpoints.size,\n totalRoutes: this.routes.size,\n apisByType,\n endpointsByApi,\n };\n }\n\n /**\n * Update auxiliary indices when an API is registered\n * \n * @param api - API entry to index\n * @private\n * @internal\n */\n private updateIndices(api: ApiRegistryEntry): void {\n // Index by type\n this.ensureIndexSet(this.apisByType, api.type).add(api.id);\n\n // Index by status\n const status = api.metadata?.status || 'active';\n this.ensureIndexSet(this.apisByStatus, status).add(api.id);\n\n // Index by tags\n const tags = api.metadata?.tags || [];\n for (const tag of tags) {\n this.ensureIndexSet(this.apisByTag, tag).add(api.id);\n }\n }\n\n /**\n * Remove API from auxiliary indices when unregistered\n * \n * @param api - API entry to remove from indices\n * @private\n * @internal\n */\n private removeFromIndices(api: ApiRegistryEntry): void {\n // Remove from type index\n this.removeFromIndexSet(this.apisByType, api.type, api.id);\n\n // Remove from status index\n const status = api.metadata?.status || 'active';\n this.removeFromIndexSet(this.apisByStatus, status, api.id);\n\n // Remove from tag indices\n const tags = api.metadata?.tags || [];\n for (const tag of tags) {\n this.removeFromIndexSet(this.apisByTag, tag, api.id);\n }\n }\n\n /**\n * Helper to ensure an index set exists and return it\n * \n * @param map - Index map\n * @param key - Index key\n * @returns The Set for this key (created if needed)\n * @private\n * @internal\n */\n private ensureIndexSet(map: Map>, key: string): Set {\n let set = map.get(key);\n if (!set) {\n set = new Set();\n map.set(key, set);\n }\n return set;\n }\n\n /**\n * Helper to remove an ID from an index set and clean up empty sets\n * \n * @param map - Index map\n * @param key - Index key\n * @param id - API ID to remove\n * @private\n * @internal\n */\n private removeFromIndexSet(map: Map>, key: string, id: string): void {\n const set = map.get(key);\n if (set) {\n set.delete(id);\n // Clean up empty sets to avoid memory leaks\n if (set.size === 0) {\n map.delete(key);\n }\n }\n }\n\n /**\n * Check if running in production environment\n * \n * @returns true if NODE_ENV is 'production'\n * @private\n * @internal\n */\n private isProductionEnvironment(): boolean {\n return getEnv('NODE_ENV') === 'production';\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from './types.js';\nimport { ApiRegistry } from './api-registry.js';\nimport type { ConflictResolutionStrategy } from '@objectstack/spec/api';\n\n/**\n * API Registry Plugin Configuration\n */\nexport interface ApiRegistryPluginConfig {\n /**\n * Conflict resolution strategy for route conflicts\n * @default 'error'\n */\n conflictResolution?: ConflictResolutionStrategy;\n \n /**\n * Registry version\n * @default '1.0.0'\n */\n version?: string;\n}\n\n/**\n * API Registry Plugin\n * \n * Registers the API Registry service in the kernel, making it available\n * to all plugins for endpoint registration and discovery.\n * \n * **Usage:**\n * ```typescript\n * const kernel = new ObjectKernel();\n * \n * // Register API Registry Plugin\n * kernel.use(createApiRegistryPlugin({ conflictResolution: 'priority' }));\n * \n * // In other plugins, access the API Registry\n * const plugin: Plugin = {\n * name: 'my-plugin',\n * init: async (ctx) => {\n * const registry = ctx.getService('api-registry');\n * \n * // Register plugin APIs\n * registry.registerApi({\n * id: 'my_plugin_api',\n * name: 'My Plugin API',\n * type: 'rest',\n * version: 'v1',\n * basePath: '/api/v1/my-plugin',\n * endpoints: [...]\n * });\n * }\n * };\n * ```\n * \n * @param config - Plugin configuration\n * @returns Plugin instance\n */\nexport function createApiRegistryPlugin(\n config: ApiRegistryPluginConfig = {}\n): Plugin {\n const {\n conflictResolution = 'error',\n version = '1.0.0',\n } = config;\n\n return {\n name: 'com.objectstack.core.api-registry',\n type: 'standard',\n version: '1.0.0',\n\n init: async (ctx: PluginContext) => {\n // Create API Registry instance\n const registry = new ApiRegistry(\n ctx.logger,\n conflictResolution,\n version\n );\n\n // Register as a service\n ctx.registerService('api-registry', registry);\n\n ctx.logger.info('API Registry plugin initialized', {\n conflictResolution,\n version,\n });\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './adapter.js';\nexport * from './runner.js';\nexport * from './http-adapter.js';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { QA } from '@objectstack/spec';\nimport { TestExecutionAdapter } from './adapter.js';\n\nexport interface TestResult {\n scenarioId: string;\n passed: boolean;\n steps: StepResult[];\n error?: unknown;\n duration: number;\n}\n\nexport interface StepResult {\n stepName: string;\n passed: boolean;\n error?: unknown;\n output?: unknown;\n duration: number;\n}\n\nexport class TestRunner {\n constructor(private adapter: TestExecutionAdapter) {}\n\n async runSuite(suite: QA.TestSuite): Promise {\n const results: TestResult[] = [];\n for (const scenario of suite.scenarios) {\n results.push(await this.runScenario(scenario));\n }\n return results;\n }\n\n async runScenario(scenario: QA.TestScenario): Promise {\n const startTime = Date.now();\n const context: Record = {}; // Variable context\n \n // Initialize context from initial payload if needed? Currently schema doesn't have initial context prop on Scenario\n // But we defined TestContextSchema separately.\n \n // Setup\n if (scenario.setup) {\n for (const step of scenario.setup) {\n try {\n await this.runStep(step, context);\n } catch (e) {\n return {\n scenarioId: scenario.id,\n passed: false,\n steps: [],\n error: `Setup failed: ${e instanceof Error ? e.message : String(e)}`,\n duration: Date.now() - startTime\n };\n }\n }\n }\n\n const stepResults: StepResult[] = [];\n let scenarioPassed = true;\n let scenarioError: unknown = undefined;\n\n // Main Steps\n for (const step of scenario.steps) {\n const stepStartTime = Date.now();\n try {\n const output = await this.runStep(step, context);\n stepResults.push({\n stepName: step.name,\n passed: true,\n output,\n duration: Date.now() - stepStartTime\n });\n } catch (e) {\n scenarioPassed = false;\n scenarioError = e;\n stepResults.push({\n stepName: step.name,\n passed: false,\n error: e,\n duration: Date.now() - stepStartTime\n });\n break; // Stop on first failure\n }\n }\n\n // Teardown (run even if failed)\n if (scenario.teardown) {\n for (const step of scenario.teardown) {\n try {\n await this.runStep(step, context);\n } catch (e) {\n // Log teardown failure but don't override main failure if it exists\n if (scenarioPassed) {\n scenarioPassed = false;\n scenarioError = `Teardown failed: ${e instanceof Error ? e.message : String(e)}`;\n }\n }\n }\n }\n\n return {\n scenarioId: scenario.id,\n passed: scenarioPassed,\n steps: stepResults,\n error: scenarioError,\n duration: Date.now() - startTime\n };\n }\n\n private async runStep(step: QA.TestStep, context: Record): Promise {\n // 1. Resolve Variables with Context (Simple interpolation or just pass context?)\n // For now, assume adpater handles context resolution or we do basic replacement\n const resolvedAction = this.resolveVariables(step.action, context);\n\n // 2. Execute Action\n const result = await this.adapter.execute(resolvedAction, context);\n\n // 3. Capture Outputs\n if (step.capture) {\n for (const [varName, path] of Object.entries(step.capture)) {\n context[varName] = this.getValueByPath(result, path);\n }\n }\n\n // 4. Run Assertions\n if (step.assertions) {\n for (const assertion of step.assertions) {\n this.assert(result, assertion, context);\n }\n }\n\n return result;\n }\n\n private resolveVariables(action: QA.TestAction, context: Record): QA.TestAction {\n const actionStr = JSON.stringify(action);\n const resolved = actionStr.replace(/\\{\\{([^}]+)\\}\\}/g, (_match, varPath: string) => {\n const value = this.getValueByPath(context, varPath.trim());\n if (value === undefined) return _match; // Keep unresolved\n return typeof value === 'string' ? value : JSON.stringify(value);\n });\n try {\n return JSON.parse(resolved) as QA.TestAction;\n } catch {\n return action; // Fallback to original if parse fails\n }\n }\n\n private getValueByPath(obj: unknown, path: string): unknown {\n if (!path) return obj;\n const parts = path.split('.');\n let current: any = obj;\n for (const part of parts) {\n if (current === null || current === undefined) return undefined;\n current = current[part];\n }\n return current;\n }\n\n private assert(result: unknown, assertion: QA.TestAssertion, _context: Record) {\n const actual = this.getValueByPath(result, assertion.field);\n // Resolve expected value if it's a variable ref? \n const expected = assertion.expectedValue; // Simplify for now\n\n switch (assertion.operator) {\n case 'equals':\n if (actual !== expected) throw new Error(`Assertion failed: ${assertion.field} expected ${expected}, got ${actual}`);\n break;\n case 'not_equals':\n if (actual === expected) throw new Error(`Assertion failed: ${assertion.field} expected not ${expected}, got ${actual}`);\n break;\n case 'contains':\n if (Array.isArray(actual)) {\n if (!actual.includes(expected)) throw new Error(`Assertion failed: ${assertion.field} array does not contain ${expected}`);\n } else if (typeof actual === 'string') {\n if (!actual.includes(String(expected))) throw new Error(`Assertion failed: ${assertion.field} string does not contain ${expected}`);\n }\n break;\n case 'not_null':\n if (actual === null || actual === undefined) throw new Error(`Assertion failed: ${assertion.field} is null`);\n break;\n case 'is_null':\n if (actual !== null && actual !== undefined) throw new Error(`Assertion failed: ${assertion.field} is not null`);\n break;\n // ... Add other operators\n default:\n throw new Error(`Unknown assertion operator: ${assertion.operator}`);\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { QA } from '@objectstack/spec';\nimport { TestExecutionAdapter } from './adapter.js';\n\nexport class HttpTestAdapter implements TestExecutionAdapter {\n constructor(private baseUrl: string, private authToken?: string) {}\n\n async execute(action: QA.TestAction, _context: Record): Promise {\n const headers: Record = {\n 'Content-Type': 'application/json',\n };\n if (this.authToken) {\n headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n // If action.user is specified, maybe add a specific header for impersonation if supported?\n if (action.user) {\n headers['X-Run-As'] = action.user;\n }\n\n switch (action.type) {\n case 'create_record':\n return this.createRecord(action.target, action.payload || {}, headers);\n case 'update_record':\n return this.updateRecord(action.target, action.payload || {}, headers);\n case 'delete_record':\n return this.deleteRecord(action.target, action.payload || {}, headers);\n case 'read_record':\n return this.readRecord(action.target, action.payload || {}, headers);\n case 'query_records':\n return this.queryRecords(action.target, action.payload || {}, headers);\n case 'api_call':\n return this.rawApiCall(action.target, action.payload || {}, headers);\n case 'wait':\n const ms = Number(action.payload?.duration || 1000);\n return new Promise(resolve => setTimeout(() => resolve({ waited: ms }), ms));\n default:\n throw new Error(`Unsupported action type in HttpAdapter: ${action.type}`);\n }\n }\n\n private async createRecord(objectName: string, data: Record, headers: Record) {\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}`, {\n method: 'POST',\n headers,\n body: JSON.stringify(data)\n });\n return this.handleResponse(response);\n }\n\n private async updateRecord(objectName: string, data: Record, headers: Record) {\n const id = data.id;\n if (!id) throw new Error('Update record requires id in payload');\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, {\n method: 'PUT',\n headers,\n body: JSON.stringify(data)\n });\n return this.handleResponse(response);\n }\n\n private async deleteRecord(objectName: string, data: Record, headers: Record) {\n const id = data.id;\n if (!id) throw new Error('Delete record requires id in payload');\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, {\n method: 'DELETE',\n headers\n });\n return this.handleResponse(response);\n }\n\n private async readRecord(objectName: string, data: Record, headers: Record) {\n const id = data.id;\n if (!id) throw new Error('Read record requires id in payload');\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, {\n method: 'GET',\n headers\n });\n return this.handleResponse(response);\n }\n\n private async queryRecords(objectName: string, data: Record, headers: Record) {\n // Assuming query via POST or GraphQL-like endpoint\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}/query`, {\n method: 'POST',\n headers,\n body: JSON.stringify(data)\n });\n return this.handleResponse(response);\n }\n\n private async rawApiCall(endpoint: string, data: Record, headers: Record) {\n const method = (data.method as string) || 'GET';\n const body = data.body ? JSON.stringify(data.body) : undefined;\n const url = endpoint.startsWith('http') ? endpoint : `${this.baseUrl}${endpoint}`;\n \n const response = await fetch(url, {\n method,\n headers,\n body\n });\n return this.handleResponse(response);\n }\n\n private async handleResponse(response: Response) {\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`HTTP Error ${response.status}: ${text}`);\n }\n const contentType = response.headers.get('content-type');\n if (contentType && contentType.includes('application/json')) {\n return response.json();\n }\n return response.text();\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Logger } from '@objectstack/spec/contracts';\nimport type { PluginMetadata } from '../plugin-loader.js';\n\n// Conditionally import crypto for Node.js environments\nlet cryptoModule: typeof import('crypto') | null = null;\n\n\n/**\n * Plugin Signature Configuration\n * Controls how plugin signatures are verified\n */\nexport interface PluginSignatureConfig {\n /**\n * Map of publisher IDs to their trusted public keys\n * Format: { 'com.objectstack': '-----BEGIN PUBLIC KEY-----...' }\n */\n trustedPublicKeys: Map;\n \n /**\n * Signature algorithm to use\n * - RS256: RSA with SHA-256\n * - ES256: ECDSA with SHA-256\n */\n algorithm: 'RS256' | 'ES256';\n \n /**\n * Strict mode: reject plugins without signatures\n * - true: All plugins must be signed\n * - false: Unsigned plugins are allowed with warning\n */\n strictMode: boolean;\n \n /**\n * Allow self-signed plugins in development\n */\n allowSelfSigned?: boolean;\n}\n\n/**\n * Plugin Signature Verification Result\n */\nexport interface SignatureVerificationResult {\n verified: boolean;\n error?: string;\n publisherId?: string;\n algorithm?: string;\n signedAt?: Date;\n}\n\n/**\n * Plugin Signature Verifier\n * \n * Implements cryptographic verification of plugin signatures to ensure:\n * 1. Plugin integrity - code hasn't been tampered with\n * 2. Publisher authenticity - plugin comes from trusted source\n * 3. Non-repudiation - publisher cannot deny signing\n * \n * Architecture:\n * - Uses Node.js crypto module for signature verification\n * - Supports RSA (RS256) and ECDSA (ES256) algorithms\n * - Verifies against trusted public key registry\n * - Computes hash of plugin code for integrity check\n * \n * Security Model:\n * - Public keys are pre-registered and trusted\n * - Plugin signature is verified before loading\n * - Strict mode rejects unsigned plugins\n * - Development mode allows self-signed plugins\n */\nexport class PluginSignatureVerifier {\n private config: PluginSignatureConfig;\n private logger: Logger;\n \n constructor(config: PluginSignatureConfig, logger: Logger) {\n this.config = config;\n this.logger = logger;\n \n this.validateConfig();\n }\n \n /**\n * Verify plugin signature\n * \n * @param plugin - Plugin metadata with signature\n * @returns Verification result\n * @throws Error if verification fails in strict mode\n */\n async verifyPluginSignature(plugin: PluginMetadata): Promise {\n // Handle unsigned plugins\n if (!plugin.signature) {\n return this.handleUnsignedPlugin(plugin);\n }\n \n try {\n // 1. Extract publisher ID from plugin name (reverse domain notation)\n const publisherId = this.extractPublisherId(plugin.name);\n \n // 2. Get trusted public key for publisher\n const publicKey = this.config.trustedPublicKeys.get(publisherId);\n if (!publicKey) {\n const error = `No trusted public key for publisher: ${publisherId}`;\n this.logger.warn(error, { plugin: plugin.name, publisherId });\n \n if (this.config.strictMode && !this.config.allowSelfSigned) {\n throw new Error(error);\n }\n \n return {\n verified: false,\n error,\n publisherId,\n };\n }\n \n // 3. Compute plugin code hash\n const pluginHash = this.computePluginHash(plugin);\n \n // 4. Verify signature using crypto module\n const isValid = await this.verifyCryptoSignature(\n pluginHash,\n plugin.signature,\n publicKey\n );\n \n if (!isValid) {\n const error = `Signature verification failed for plugin: ${plugin.name}`;\n this.logger.error(error, undefined, { plugin: plugin.name, publisherId });\n throw new Error(error);\n }\n \n this.logger.info(`✅ Plugin signature verified: ${plugin.name}`, {\n plugin: plugin.name,\n publisherId,\n algorithm: this.config.algorithm,\n });\n \n return {\n verified: true,\n publisherId,\n algorithm: this.config.algorithm,\n };\n \n } catch (error) {\n this.logger.error(`Signature verification error: ${plugin.name}`, error as Error);\n \n if (this.config.strictMode) {\n throw error;\n }\n \n return {\n verified: false,\n error: (error as Error).message,\n };\n }\n }\n \n /**\n * Register a trusted public key for a publisher\n */\n registerPublicKey(publisherId: string, publicKey: string): void {\n this.config.trustedPublicKeys.set(publisherId, publicKey);\n this.logger.info(`Trusted public key registered for: ${publisherId}`);\n }\n \n /**\n * Remove a trusted public key\n */\n revokePublicKey(publisherId: string): void {\n this.config.trustedPublicKeys.delete(publisherId);\n this.logger.warn(`Public key revoked for: ${publisherId}`);\n }\n \n /**\n * Get list of trusted publishers\n */\n getTrustedPublishers(): string[] {\n return Array.from(this.config.trustedPublicKeys.keys());\n }\n \n // Private methods\n \n private handleUnsignedPlugin(plugin: PluginMetadata): SignatureVerificationResult {\n if (this.config.strictMode) {\n const error = `Plugin missing signature (strict mode): ${plugin.name}`;\n this.logger.error(error, undefined, { plugin: plugin.name });\n throw new Error(error);\n }\n \n this.logger.warn(`⚠️ Plugin not signed: ${plugin.name}`, {\n plugin: plugin.name,\n recommendation: 'Consider signing plugins for production environments',\n });\n \n return {\n verified: false,\n error: 'Plugin not signed',\n };\n }\n \n private extractPublisherId(pluginName: string): string {\n // Extract publisher from reverse domain notation\n // Example: \"com.objectstack.engine.objectql\" -> \"com.objectstack\"\n const parts = pluginName.split('.');\n \n if (parts.length < 2) {\n throw new Error(`Invalid plugin name format: ${pluginName} (expected reverse domain notation)`);\n }\n \n // Return first two parts (domain reversed)\n return `${parts[0]}.${parts[1]}`;\n }\n \n private computePluginHash(plugin: PluginMetadata): string {\n // In browser environment, use SubtleCrypto\n if (typeof (globalThis as any).window !== 'undefined') {\n return this.computePluginHashBrowser(plugin);\n }\n \n // In Node.js environment, use crypto module\n return this.computePluginHashNode(plugin);\n }\n \n private computePluginHashNode(plugin: PluginMetadata): string {\n // Use pre-loaded crypto module\n if (!cryptoModule) {\n this.logger.warn('crypto module not available, using fallback hash');\n return this.computePluginHashFallback(plugin);\n }\n \n // Compute hash of plugin code\n const pluginCode = this.serializePluginCode(plugin);\n return cryptoModule.createHash('sha256').update(pluginCode).digest('hex');\n }\n \n private computePluginHashBrowser(plugin: PluginMetadata): string {\n // Browser environment - use simple hash for now\n // In production, should use SubtleCrypto for proper cryptographic hash\n this.logger.debug('Using browser hash (SubtleCrypto integration pending)');\n return this.computePluginHashFallback(plugin);\n }\n \n private computePluginHashFallback(plugin: PluginMetadata): string {\n // Simple hash fallback (not cryptographically secure)\n const pluginCode = this.serializePluginCode(plugin);\n let hash = 0;\n \n for (let i = 0; i < pluginCode.length; i++) {\n const char = pluginCode.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n \n return hash.toString(16);\n }\n \n private serializePluginCode(plugin: PluginMetadata): string {\n // Serialize plugin code for hashing\n // Include init, start, destroy functions\n const parts: string[] = [\n plugin.name,\n plugin.version,\n plugin.init.toString(),\n ];\n \n if (plugin.start) {\n parts.push(plugin.start.toString());\n }\n \n if (plugin.destroy) {\n parts.push(plugin.destroy.toString());\n }\n \n return parts.join('|');\n }\n \n private async verifyCryptoSignature(\n data: string,\n signature: string,\n publicKey: string\n ): Promise {\n // In browser environment, use SubtleCrypto\n if (typeof (globalThis as any).window !== 'undefined') {\n return this.verifyCryptoSignatureBrowser(data, signature, publicKey);\n }\n \n // In Node.js environment, use crypto module\n return this.verifyCryptoSignatureNode(data, signature, publicKey);\n }\n \n private async verifyCryptoSignatureNode(\n data: string,\n signature: string,\n publicKey: string\n ): Promise {\n if (!cryptoModule) {\n try {\n // @ts-ignore\n cryptoModule = await import('crypto');\n } catch (e) {\n // ignore\n }\n }\n\n if (!cryptoModule) {\n this.logger.error('Crypto module not available for signature verification');\n return false;\n }\n \n try {\n // Create verify object based on algorithm\n if (this.config.algorithm === 'ES256') {\n // ECDSA verification - requires lowercase 'sha256'\n const verify = cryptoModule.createVerify('sha256');\n verify.update(data);\n return verify.verify(\n {\n key: publicKey,\n format: 'pem',\n type: 'spki',\n },\n signature,\n 'base64'\n );\n } else {\n // RSA verification (RS256)\n const verify = cryptoModule.createVerify('RSA-SHA256');\n verify.update(data);\n return verify.verify(publicKey, signature, 'base64');\n }\n } catch (error) {\n this.logger.error('Signature verification failed', error as Error);\n return false;\n }\n }\n \n private async verifyCryptoSignatureBrowser(\n data: string,\n signature: string,\n publicKey: string\n ): Promise {\n try {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n this.logger.error('SubtleCrypto not available in this environment');\n return false;\n }\n\n // Decode PEM public key to raw DER bytes\n const pemBody = publicKey\n .replace(/-----BEGIN PUBLIC KEY-----/, '')\n .replace(/-----END PUBLIC KEY-----/, '')\n .replace(/\\s/g, '');\n const keyBytes = Uint8Array.from(atob(pemBody), c => c.charCodeAt(0));\n\n // Configure algorithms based on RS256 or ES256\n let importAlgorithm: { name: string; hash?: string; namedCurve?: string };\n let verifyAlgorithm: { name: string; hash?: string };\n\n if (this.config.algorithm === 'ES256') {\n importAlgorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n verifyAlgorithm = { name: 'ECDSA', hash: 'SHA-256' };\n } else {\n importAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };\n verifyAlgorithm = { name: 'RSASSA-PKCS1-v1_5' };\n }\n\n const cryptoKey = await subtle.importKey(\n 'spki',\n keyBytes,\n importAlgorithm,\n false,\n ['verify']\n );\n\n // Decode base64 signature to ArrayBuffer\n const signatureBytes = Uint8Array.from(atob(signature), c => c.charCodeAt(0));\n\n // Encode data to ArrayBuffer\n const dataBytes = new TextEncoder().encode(data);\n\n return await subtle.verify(verifyAlgorithm, cryptoKey, signatureBytes, dataBytes);\n } catch (error) {\n this.logger.error('Browser signature verification failed', error as Error);\n return false;\n }\n }\n \n private validateConfig(): void {\n if (!this.config.trustedPublicKeys || this.config.trustedPublicKeys.size === 0) {\n this.logger.warn('No trusted public keys configured - all signatures will fail');\n }\n \n if (!this.config.algorithm) {\n throw new Error('Signature algorithm must be specified');\n }\n \n if (!['RS256', 'ES256'].includes(this.config.algorithm)) {\n throw new Error(`Unsupported algorithm: ${this.config.algorithm}`);\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Logger } from '@objectstack/spec/contracts';\nimport type { PluginCapability } from '@objectstack/spec/kernel';\nimport type { PluginContext } from '../types.js';\n\n/**\n * Plugin Permissions\n * Defines what actions a plugin is allowed to perform\n */\nexport interface PluginPermissions {\n canAccessService(serviceName: string): boolean;\n canTriggerHook(hookName: string): boolean;\n canReadFile(path: string): boolean;\n canWriteFile(path: string): boolean;\n canNetworkRequest(url: string): boolean;\n}\n\n/**\n * Permission Check Result\n */\nexport interface PermissionCheckResult {\n allowed: boolean;\n reason?: string;\n capability?: string;\n}\n\n/**\n * Plugin Permission Enforcer\n * \n * Implements capability-based security model to enforce:\n * 1. Service access control - which services a plugin can use\n * 2. Hook restrictions - which hooks a plugin can trigger\n * 3. File system permissions - what files a plugin can read/write\n * 4. Network permissions - what URLs a plugin can access\n * \n * Architecture:\n * - Uses capability declarations from plugin manifest\n * - Checks permissions before allowing operations\n * - Logs all permission denials for security audit\n * - Supports allowlist and denylist patterns\n * \n * Security Model:\n * - Principle of least privilege - plugins get minimal permissions\n * - Explicit declaration - all capabilities must be declared\n * - Runtime enforcement - checks happen at operation time\n * - Audit trail - all denials are logged\n * \n * Usage:\n * ```typescript\n * const enforcer = new PluginPermissionEnforcer(logger);\n * enforcer.registerPluginPermissions(pluginName, capabilities);\n * enforcer.enforceServiceAccess(pluginName, 'database');\n * ```\n */\nexport class PluginPermissionEnforcer {\n private logger: Logger;\n private permissionRegistry: Map = new Map();\n private capabilityRegistry: Map = new Map();\n \n constructor(logger: Logger) {\n this.logger = logger;\n }\n \n /**\n * Register plugin capabilities and build permission set\n * \n * @param pluginName - Plugin identifier\n * @param capabilities - Array of capability declarations\n */\n registerPluginPermissions(pluginName: string, capabilities: PluginCapability[]): void {\n this.capabilityRegistry.set(pluginName, capabilities);\n \n const permissions: PluginPermissions = {\n canAccessService: (service) => this.checkServiceAccess(capabilities, service),\n canTriggerHook: (hook) => this.checkHookAccess(capabilities, hook),\n canReadFile: (path) => this.checkFileRead(capabilities, path),\n canWriteFile: (path) => this.checkFileWrite(capabilities, path),\n canNetworkRequest: (url) => this.checkNetworkAccess(capabilities, url),\n };\n \n this.permissionRegistry.set(pluginName, permissions);\n \n this.logger.info(`Permissions registered for plugin: ${pluginName}`, {\n plugin: pluginName,\n capabilityCount: capabilities.length,\n });\n }\n \n /**\n * Enforce service access permission\n * \n * @param pluginName - Plugin requesting access\n * @param serviceName - Service to access\n * @throws Error if permission denied\n */\n enforceServiceAccess(pluginName: string, serviceName: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canAccessService(serviceName));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot access service ${serviceName}`;\n this.logger.warn(error, {\n plugin: pluginName,\n service: serviceName,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`Service access granted: ${pluginName} -> ${serviceName}`);\n }\n \n /**\n * Enforce hook trigger permission\n * \n * @param pluginName - Plugin requesting access\n * @param hookName - Hook to trigger\n * @throws Error if permission denied\n */\n enforceHookTrigger(pluginName: string, hookName: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canTriggerHook(hookName));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot trigger hook ${hookName}`;\n this.logger.warn(error, {\n plugin: pluginName,\n hook: hookName,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`Hook trigger granted: ${pluginName} -> ${hookName}`);\n }\n \n /**\n * Enforce file read permission\n * \n * @param pluginName - Plugin requesting access\n * @param path - File path to read\n * @throws Error if permission denied\n */\n enforceFileRead(pluginName: string, path: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canReadFile(path));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot read file ${path}`;\n this.logger.warn(error, {\n plugin: pluginName,\n path,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`File read granted: ${pluginName} -> ${path}`);\n }\n \n /**\n * Enforce file write permission\n * \n * @param pluginName - Plugin requesting access\n * @param path - File path to write\n * @throws Error if permission denied\n */\n enforceFileWrite(pluginName: string, path: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canWriteFile(path));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot write file ${path}`;\n this.logger.warn(error, {\n plugin: pluginName,\n path,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`File write granted: ${pluginName} -> ${path}`);\n }\n \n /**\n * Enforce network request permission\n * \n * @param pluginName - Plugin requesting access\n * @param url - URL to access\n * @throws Error if permission denied\n */\n enforceNetworkRequest(pluginName: string, url: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canNetworkRequest(url));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot access URL ${url}`;\n this.logger.warn(error, {\n plugin: pluginName,\n url,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`Network request granted: ${pluginName} -> ${url}`);\n }\n \n /**\n * Get plugin capabilities\n * \n * @param pluginName - Plugin identifier\n * @returns Array of capabilities or undefined\n */\n getPluginCapabilities(pluginName: string): PluginCapability[] | undefined {\n return this.capabilityRegistry.get(pluginName);\n }\n \n /**\n * Get plugin permissions\n * \n * @param pluginName - Plugin identifier\n * @returns Permissions object or undefined\n */\n getPluginPermissions(pluginName: string): PluginPermissions | undefined {\n return this.permissionRegistry.get(pluginName);\n }\n \n /**\n * Revoke all permissions for a plugin\n * \n * @param pluginName - Plugin identifier\n */\n revokePermissions(pluginName: string): void {\n this.permissionRegistry.delete(pluginName);\n this.capabilityRegistry.delete(pluginName);\n this.logger.warn(`Permissions revoked for plugin: ${pluginName}`);\n }\n \n // Private methods\n \n private checkPermission(\n pluginName: string,\n check: (perms: PluginPermissions) => boolean\n ): PermissionCheckResult {\n const permissions = this.permissionRegistry.get(pluginName);\n \n if (!permissions) {\n return {\n allowed: false,\n reason: 'Plugin permissions not registered',\n };\n }\n \n const allowed = check(permissions);\n \n return {\n allowed,\n reason: allowed ? undefined : 'No matching capability found',\n };\n }\n \n private checkServiceAccess(capabilities: PluginCapability[], serviceName: string): boolean {\n // Check if plugin has capability to access this service\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for wildcard service access\n if (protocolId.includes('protocol.service.all')) {\n return true;\n }\n \n // Check for specific service protocol\n if (protocolId.includes(`protocol.service.${serviceName}`)) {\n return true;\n }\n \n // Check for service category match\n const serviceCategory = serviceName.split('.')[0];\n if (protocolId.includes(`protocol.service.${serviceCategory}`)) {\n return true;\n }\n \n return false;\n });\n }\n \n private checkHookAccess(capabilities: PluginCapability[], hookName: string): boolean {\n // Check if plugin has capability to trigger this hook\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for wildcard hook access\n if (protocolId.includes('protocol.hook.all')) {\n return true;\n }\n \n // Check for specific hook protocol\n if (protocolId.includes(`protocol.hook.${hookName}`)) {\n return true;\n }\n \n // Check for hook category match\n const hookCategory = hookName.split(':')[0];\n if (protocolId.includes(`protocol.hook.${hookCategory}`)) {\n return true;\n }\n \n return false;\n });\n }\n \n private matchGlob(pattern: string, str: string): boolean {\n const regexStr = pattern\n .split('**')\n .map(segment => {\n const escaped = segment.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return escaped.replace(/\\*/g, '[^/]*');\n })\n .join('.*');\n return new RegExp(`^${regexStr}$`).test(str);\n }\n \n private checkFileRead(capabilities: PluginCapability[], path: string): boolean {\n // Check if plugin has capability to read this file\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for file read capability\n if (protocolId.includes('protocol.filesystem.read')) {\n const paths = cap.metadata?.paths;\n if (!Array.isArray(paths) || paths.length === 0) {\n return true;\n }\n return paths.some(p => typeof p === 'string' && this.matchGlob(p, path));\n }\n \n return false;\n });\n }\n \n private checkFileWrite(capabilities: PluginCapability[], path: string): boolean {\n // Check if plugin has capability to write this file\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for file write capability\n if (protocolId.includes('protocol.filesystem.write')) {\n const paths = cap.metadata?.paths;\n if (!Array.isArray(paths) || paths.length === 0) {\n return true;\n }\n return paths.some(p => typeof p === 'string' && this.matchGlob(p, path));\n }\n \n return false;\n });\n }\n \n private checkNetworkAccess(capabilities: PluginCapability[], url: string): boolean {\n // Check if plugin has capability to access this URL\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for network capability\n if (protocolId.includes('protocol.network')) {\n const hosts = cap.metadata?.hosts;\n if (!Array.isArray(hosts) || hosts.length === 0) {\n return true;\n }\n return hosts.some(h => typeof h === 'string' && this.matchGlob(h, url));\n }\n \n return false;\n });\n }\n}\n\n/**\n * Secure Plugin Context\n * Wraps PluginContext with permission checks\n */\nexport class SecurePluginContext implements PluginContext {\n constructor(\n private pluginName: string,\n private permissionEnforcer: PluginPermissionEnforcer,\n private baseContext: PluginContext\n ) {}\n \n registerService(name: string, service: any): void {\n // No permission check for service registration (handled during init)\n this.baseContext.registerService(name, service);\n }\n \n getService(name: string): T {\n // Check permission before accessing service\n this.permissionEnforcer.enforceServiceAccess(this.pluginName, name);\n return this.baseContext.getService(name);\n }\n \n replaceService(name: string, implementation: T): void {\n // Check permission before replacing service\n this.permissionEnforcer.enforceServiceAccess(this.pluginName, name);\n this.baseContext.replaceService(name, implementation);\n }\n \n getServices(): Map {\n // Return all services (no permission check for listing)\n return this.baseContext.getServices();\n }\n \n hook(name: string, handler: (...args: any[]) => void | Promise): void {\n // No permission check for registering hooks (handled during init)\n this.baseContext.hook(name, handler);\n }\n \n async trigger(name: string, ...args: any[]): Promise {\n // Check permission before triggering hook\n this.permissionEnforcer.enforceHookTrigger(this.pluginName, name);\n await this.baseContext.trigger(name, ...args);\n }\n \n get logger() {\n return this.baseContext.logger;\n }\n \n getKernel() {\n return this.baseContext.getKernel();\n }\n}\n\n/**\n * Create a plugin permission enforcer\n * \n * @param logger - Logger instance\n * @returns Plugin permission enforcer\n */\nexport function createPluginPermissionEnforcer(logger: Logger): PluginPermissionEnforcer {\n return new PluginPermissionEnforcer(logger);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { \n Permission,\n PermissionSet,\n PermissionAction,\n ResourceType\n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from '../logger.js';\n\n/**\n * Permission Grant\n * Represents a granted permission at runtime\n */\nexport interface PermissionGrant {\n permissionId: string;\n pluginId: string;\n grantedAt: Date;\n grantedBy?: string;\n expiresAt?: Date;\n conditions?: Record;\n}\n\n/**\n * Permission Check Result\n */\nexport interface PermissionCheckResult {\n allowed: boolean;\n reason?: string;\n requiredPermission?: string;\n grantedPermissions?: string[];\n}\n\n/**\n * Plugin Permission Manager\n * \n * Manages fine-grained permissions for plugin security and access control\n */\nexport class PluginPermissionManager {\n private logger: ObjectLogger;\n \n // Plugin permission definitions\n private permissionSets = new Map();\n \n // Granted permissions (pluginId -> Set of permission IDs)\n private grants = new Map>();\n \n // Permission grant details\n private grantDetails = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'PermissionManager' });\n }\n\n /**\n * Register permission requirements for a plugin\n */\n registerPermissions(pluginId: string, permissionSet: PermissionSet): void {\n this.permissionSets.set(pluginId, permissionSet);\n \n this.logger.info('Permissions registered for plugin', { \n pluginId,\n permissionCount: permissionSet.permissions.length\n });\n }\n\n /**\n * Grant a permission to a plugin\n */\n grantPermission(\n pluginId: string,\n permissionId: string,\n grantedBy?: string,\n expiresAt?: Date\n ): void {\n // Verify permission exists in plugin's declared permissions\n const permissionSet = this.permissionSets.get(pluginId);\n if (!permissionSet) {\n throw new Error(`No permissions registered for plugin: ${pluginId}`);\n }\n\n const permission = permissionSet.permissions.find(p => p.id === permissionId);\n if (!permission) {\n throw new Error(`Permission ${permissionId} not declared by plugin ${pluginId}`);\n }\n\n // Create grant\n if (!this.grants.has(pluginId)) {\n this.grants.set(pluginId, new Set());\n }\n this.grants.get(pluginId)!.add(permissionId);\n\n // Store grant details\n const grantKey = `${pluginId}:${permissionId}`;\n this.grantDetails.set(grantKey, {\n permissionId,\n pluginId,\n grantedAt: new Date(),\n grantedBy,\n expiresAt,\n });\n\n this.logger.info('Permission granted', { \n pluginId, \n permissionId,\n grantedBy \n });\n }\n\n /**\n * Revoke a permission from a plugin\n */\n revokePermission(pluginId: string, permissionId: string): void {\n const grants = this.grants.get(pluginId);\n if (grants) {\n grants.delete(permissionId);\n \n const grantKey = `${pluginId}:${permissionId}`;\n this.grantDetails.delete(grantKey);\n\n this.logger.info('Permission revoked', { pluginId, permissionId });\n }\n }\n\n /**\n * Grant all permissions for a plugin\n */\n grantAllPermissions(pluginId: string, grantedBy?: string): void {\n const permissionSet = this.permissionSets.get(pluginId);\n if (!permissionSet) {\n throw new Error(`No permissions registered for plugin: ${pluginId}`);\n }\n\n for (const permission of permissionSet.permissions) {\n this.grantPermission(pluginId, permission.id, grantedBy);\n }\n\n this.logger.info('All permissions granted', { pluginId, grantedBy });\n }\n\n /**\n * Check if a plugin has a specific permission\n */\n hasPermission(pluginId: string, permissionId: string): boolean {\n const grants = this.grants.get(pluginId);\n if (!grants) {\n return false;\n }\n\n // Check if granted\n if (!grants.has(permissionId)) {\n return false;\n }\n\n // Check expiration\n const grantKey = `${pluginId}:${permissionId}`;\n const grantDetails = this.grantDetails.get(grantKey);\n if (grantDetails?.expiresAt && grantDetails.expiresAt < new Date()) {\n this.revokePermission(pluginId, permissionId);\n return false;\n }\n\n return true;\n }\n\n /**\n * Check if plugin can perform an action on a resource\n */\n checkAccess(\n pluginId: string,\n resource: ResourceType,\n action: PermissionAction,\n resourceId?: string\n ): PermissionCheckResult {\n const permissionSet = this.permissionSets.get(pluginId);\n if (!permissionSet) {\n return {\n allowed: false,\n reason: 'No permissions registered for plugin',\n };\n }\n\n // Find matching permissions\n const matchingPermissions = permissionSet.permissions.filter(p => {\n // Check resource type\n if (p.resource !== resource) {\n return false;\n }\n\n // Check action\n if (!p.actions.includes(action)) {\n return false;\n }\n\n // Check resource filter if specified\n if (resourceId && p.filter?.resourceIds) {\n if (!p.filter.resourceIds.includes(resourceId)) {\n return false;\n }\n }\n\n return true;\n });\n\n if (matchingPermissions.length === 0) {\n return {\n allowed: false,\n reason: `No permission found for ${action} on ${resource}`,\n };\n }\n\n // Check if any matching permission is granted\n const grantedPermissions = matchingPermissions.filter(p => \n this.hasPermission(pluginId, p.id)\n );\n\n if (grantedPermissions.length === 0) {\n return {\n allowed: false,\n reason: 'Required permissions not granted',\n requiredPermission: matchingPermissions[0].id,\n };\n }\n\n return {\n allowed: true,\n grantedPermissions: grantedPermissions.map(p => p.id),\n };\n }\n\n /**\n * Get all permissions for a plugin\n */\n getPluginPermissions(pluginId: string): Permission[] {\n const permissionSet = this.permissionSets.get(pluginId);\n return permissionSet?.permissions || [];\n }\n\n /**\n * Get granted permissions for a plugin\n */\n getGrantedPermissions(pluginId: string): string[] {\n const grants = this.grants.get(pluginId);\n return grants ? Array.from(grants) : [];\n }\n\n /**\n * Get required but not granted permissions\n */\n getMissingPermissions(pluginId: string): Permission[] {\n const permissionSet = this.permissionSets.get(pluginId);\n if (!permissionSet) {\n return [];\n }\n\n const granted = this.grants.get(pluginId) || new Set();\n \n return permissionSet.permissions.filter(p => \n p.required && !granted.has(p.id)\n );\n }\n\n /**\n * Check if all required permissions are granted\n */\n hasAllRequiredPermissions(pluginId: string): boolean {\n return this.getMissingPermissions(pluginId).length === 0;\n }\n\n /**\n * Get permission grant details\n */\n getGrantDetails(pluginId: string, permissionId: string): PermissionGrant | undefined {\n const grantKey = `${pluginId}:${permissionId}`;\n return this.grantDetails.get(grantKey);\n }\n\n /**\n * Validate permission against scope constraints\n */\n validatePermissionScope(\n permission: Permission,\n context: {\n tenantId?: string;\n userId?: string;\n resourceId?: string;\n }\n ): boolean {\n switch (permission.scope) {\n case 'global':\n return true;\n\n case 'tenant':\n return !!context.tenantId;\n\n case 'user':\n return !!context.userId;\n\n case 'resource':\n return !!context.resourceId;\n\n case 'plugin':\n return true;\n\n default:\n return false;\n }\n }\n\n /**\n * Clear all permissions for a plugin\n */\n clearPluginPermissions(pluginId: string): void {\n this.permissionSets.delete(pluginId);\n \n const grants = this.grants.get(pluginId);\n if (grants) {\n for (const permissionId of grants) {\n const grantKey = `${pluginId}:${permissionId}`;\n this.grantDetails.delete(grantKey);\n }\n this.grants.delete(pluginId);\n }\n\n this.logger.info('All permissions cleared', { pluginId });\n }\n\n /**\n * Shutdown permission manager\n */\n shutdown(): void {\n this.permissionSets.clear();\n this.grants.clear();\n this.grantDetails.clear();\n \n this.logger.info('Permission manager shutdown complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport nodePath from 'node:path';\n\nimport type { \n SandboxConfig\n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from '../logger.js';\nimport { getMemoryUsage } from '../utils/env.js';\n\n/**\n * Resource Usage Statistics\n */\nexport interface ResourceUsage {\n memory: {\n current: number;\n peak: number;\n limit?: number;\n };\n cpu: {\n current: number;\n average: number;\n limit?: number;\n };\n connections: {\n current: number;\n limit?: number;\n };\n}\n\n/**\n * Sandbox Execution Context\n * Represents an isolated execution environment for a plugin\n */\nexport interface SandboxContext {\n pluginId: string;\n config: SandboxConfig;\n startTime: Date;\n resourceUsage: ResourceUsage;\n}\n\n/**\n * Plugin Sandbox Runtime\n * \n * Provides isolated execution environments for plugins with resource limits\n * and access controls\n */\nexport class PluginSandboxRuntime {\n private static readonly MONITORING_INTERVAL_MS = 5000;\n\n private logger: ObjectLogger;\n \n // Active sandboxes (pluginId -> context)\n private sandboxes = new Map();\n \n // Resource monitoring intervals\n private monitoringIntervals = new Map();\n\n // Per-plugin resource baselines for delta tracking\n private memoryBaselines = new Map();\n private cpuBaselines = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'SandboxRuntime' });\n }\n\n /**\n * Create a sandbox for a plugin\n */\n createSandbox(pluginId: string, config: SandboxConfig): SandboxContext {\n if (this.sandboxes.has(pluginId)) {\n throw new Error(`Sandbox already exists for plugin: ${pluginId}`);\n }\n\n const context: SandboxContext = {\n pluginId,\n config,\n startTime: new Date(),\n resourceUsage: {\n memory: { current: 0, peak: 0, limit: config.memory?.maxHeap },\n cpu: { current: 0, average: 0, limit: config.cpu?.maxCpuPercent },\n connections: { current: 0, limit: config.network?.maxConnections },\n },\n };\n\n this.sandboxes.set(pluginId, context);\n\n // Capture resource baselines for per-plugin delta tracking\n const baselineMemory = getMemoryUsage();\n this.memoryBaselines.set(pluginId, baselineMemory.heapUsed);\n this.cpuBaselines.set(pluginId, process.cpuUsage());\n\n // Start resource monitoring\n this.startResourceMonitoring(pluginId);\n\n this.logger.info('Sandbox created', { \n pluginId,\n level: config.level,\n memoryLimit: config.memory?.maxHeap,\n cpuLimit: config.cpu?.maxCpuPercent\n });\n\n return context;\n }\n\n /**\n * Destroy a sandbox\n */\n destroySandbox(pluginId: string): void {\n const context = this.sandboxes.get(pluginId);\n if (!context) {\n return;\n }\n\n // Stop monitoring\n this.stopResourceMonitoring(pluginId);\n\n this.memoryBaselines.delete(pluginId);\n this.cpuBaselines.delete(pluginId);\n this.sandboxes.delete(pluginId);\n\n this.logger.info('Sandbox destroyed', { pluginId });\n }\n\n /**\n * Check if resource access is allowed\n */\n checkResourceAccess(\n pluginId: string,\n resourceType: 'file' | 'network' | 'process' | 'env',\n resourcePath?: string\n ): { allowed: boolean; reason?: string } {\n const context = this.sandboxes.get(pluginId);\n if (!context) {\n return { allowed: false, reason: 'Sandbox not found' };\n }\n\n const { config } = context;\n\n switch (resourceType) {\n case 'file':\n return this.checkFileAccess(config, resourcePath);\n \n case 'network':\n return this.checkNetworkAccess(config, resourcePath);\n \n case 'process':\n return this.checkProcessAccess(config);\n \n case 'env':\n return this.checkEnvAccess(config, resourcePath);\n \n default:\n return { allowed: false, reason: 'Unknown resource type' };\n }\n }\n\n /**\n * Check file system access\n * Uses path.resolve() and path.normalize() to prevent directory traversal.\n */\n private checkFileAccess(\n config: SandboxConfig,\n filePath?: string\n ): { allowed: boolean; reason?: string } {\n if (config.level === 'none') {\n return { allowed: true };\n }\n\n if (!config.filesystem) {\n return { allowed: false, reason: 'File system access not configured' };\n }\n\n // If no path specified, check general access\n if (!filePath) {\n return { allowed: config.filesystem.mode !== 'none' };\n }\n\n // Check allowed paths using proper path resolution to prevent directory traversal\n const allowedPaths = config.filesystem.allowedPaths || [];\n const resolvedPath = nodePath.normalize(nodePath.resolve(filePath));\n const isAllowed = allowedPaths.some(allowed => {\n const resolvedAllowed = nodePath.normalize(nodePath.resolve(allowed));\n return resolvedPath.startsWith(resolvedAllowed);\n });\n\n if (allowedPaths.length > 0 && !isAllowed) {\n return { \n allowed: false, \n reason: `Path not in allowed list: ${filePath}` \n };\n }\n\n // Check denied paths using proper path resolution\n const deniedPaths = config.filesystem.deniedPaths || [];\n const isDenied = deniedPaths.some(denied => {\n const resolvedDenied = nodePath.normalize(nodePath.resolve(denied));\n return resolvedPath.startsWith(resolvedDenied);\n });\n\n if (isDenied) {\n return { \n allowed: false, \n reason: `Path is explicitly denied: ${filePath}` \n };\n }\n\n return { allowed: true };\n }\n\n /**\n * Check network access\n * Uses URL parsing to properly validate hostnames.\n */\n private checkNetworkAccess(\n config: SandboxConfig,\n url?: string\n ): { allowed: boolean; reason?: string } {\n if (config.level === 'none') {\n return { allowed: true };\n }\n\n if (!config.network) {\n return { allowed: false, reason: 'Network access not configured' };\n }\n\n // Check if network access is enabled\n if (config.network.mode === 'none') {\n return { allowed: false, reason: 'Network access disabled' };\n }\n\n // If no URL specified, check general access\n if (!url) {\n return { allowed: (config.network.mode as string) !== 'none' };\n }\n\n // Parse URL and check hostname against allowed/denied hosts\n let parsedHostname: string;\n try {\n parsedHostname = new URL(url).hostname;\n } catch {\n return { allowed: false, reason: `Invalid URL: ${url}` };\n }\n\n // Check allowed hosts\n const allowedHosts = config.network.allowedHosts || [];\n if (allowedHosts.length > 0) {\n const isAllowed = allowedHosts.some(host => {\n return parsedHostname === host;\n });\n\n if (!isAllowed) {\n return { \n allowed: false, \n reason: `Host not in allowed list: ${url}` \n };\n }\n }\n\n // Check denied hosts\n const deniedHosts = config.network.deniedHosts || [];\n const isDenied = deniedHosts.some(host => {\n return parsedHostname === host;\n });\n\n if (isDenied) {\n return { \n allowed: false, \n reason: `Host is blocked: ${url}` \n };\n }\n\n return { allowed: true };\n }\n\n /**\n * Check process spawning access\n */\n private checkProcessAccess(\n config: SandboxConfig\n ): { allowed: boolean; reason?: string } {\n if (config.level === 'none') {\n return { allowed: true };\n }\n\n if (!config.process) {\n return { allowed: false, reason: 'Process access not configured' };\n }\n\n if (!config.process.allowSpawn) {\n return { allowed: false, reason: 'Process spawning not allowed' };\n }\n\n return { allowed: true };\n }\n\n /**\n * Check environment variable access\n */\n private checkEnvAccess(\n config: SandboxConfig,\n varName?: string\n ): { allowed: boolean; reason?: string } {\n if (config.level === 'none') {\n return { allowed: true };\n }\n\n if (!config.process) {\n return { allowed: false, reason: 'Environment access not configured' };\n }\n\n // If no variable specified, check general access\n if (!varName) {\n return { allowed: true };\n }\n\n // For now, allow all env access if process is configured\n // In a real implementation, would check specific allowed vars\n return { allowed: true };\n }\n\n /**\n * Check resource limits\n */\n checkResourceLimits(pluginId: string): { \n withinLimits: boolean; \n violations: string[] \n } {\n const context = this.sandboxes.get(pluginId);\n if (!context) {\n return { withinLimits: true, violations: [] };\n }\n\n const violations: string[] = [];\n const { resourceUsage, config } = context;\n\n // Check memory limit\n if (config.memory?.maxHeap && \n resourceUsage.memory.current > config.memory.maxHeap) {\n violations.push(`Memory limit exceeded: ${resourceUsage.memory.current} > ${config.memory.maxHeap}`);\n }\n\n // Check CPU limit (would need runtime config)\n if (config.runtime?.resourceLimits?.maxCpu && \n resourceUsage.cpu.current > config.runtime.resourceLimits.maxCpu) {\n violations.push(`CPU limit exceeded: ${resourceUsage.cpu.current}% > ${config.runtime.resourceLimits.maxCpu}%`);\n }\n\n // Check connection limit\n if (config.network?.maxConnections && \n resourceUsage.connections.current > config.network.maxConnections) {\n violations.push(`Connection limit exceeded: ${resourceUsage.connections.current} > ${config.network.maxConnections}`);\n }\n\n return {\n withinLimits: violations.length === 0,\n violations,\n };\n }\n\n /**\n * Get resource usage for a plugin\n */\n getResourceUsage(pluginId: string): ResourceUsage | undefined {\n const context = this.sandboxes.get(pluginId);\n return context?.resourceUsage;\n }\n\n /**\n * Start monitoring resource usage\n */\n private startResourceMonitoring(pluginId: string): void {\n // Monitor at the configured interval\n const interval = setInterval(() => {\n this.updateResourceUsage(pluginId);\n }, PluginSandboxRuntime.MONITORING_INTERVAL_MS);\n\n this.monitoringIntervals.set(pluginId, interval);\n }\n\n /**\n * Stop monitoring resource usage\n */\n private stopResourceMonitoring(pluginId: string): void {\n const interval = this.monitoringIntervals.get(pluginId);\n if (interval) {\n clearInterval(interval);\n this.monitoringIntervals.delete(pluginId);\n }\n }\n\n /**\n * Update resource usage statistics\n * \n * Tracks per-plugin memory and CPU usage using delta from baseline\n * captured at sandbox creation time. This is an approximation since\n * true per-plugin isolation isn't possible in a single Node.js process.\n */\n private updateResourceUsage(pluginId: string): void {\n const context = this.sandboxes.get(pluginId);\n if (!context) {\n return;\n }\n\n // In a real implementation, this would collect actual metrics\n // For now, this is a placeholder structure\n \n // Update memory usage using delta from baseline for per-plugin approximation\n const memoryUsage = getMemoryUsage();\n const memoryBaseline = this.memoryBaselines.get(pluginId) ?? 0;\n const memoryDelta = Math.max(0, memoryUsage.heapUsed - memoryBaseline);\n context.resourceUsage.memory.current = memoryDelta;\n context.resourceUsage.memory.peak = Math.max(\n context.resourceUsage.memory.peak,\n memoryDelta\n );\n\n // Update CPU usage using delta from baseline for per-plugin approximation\n const cpuBaseline = this.cpuBaselines.get(pluginId) ?? { user: 0, system: 0 };\n const cpuCurrent = process.cpuUsage();\n const cpuDeltaUser = cpuCurrent.user - cpuBaseline.user;\n const cpuDeltaSystem = cpuCurrent.system - cpuBaseline.system;\n // Convert microseconds to a percentage approximation over the monitoring interval\n const totalCpuMicros = cpuDeltaUser + cpuDeltaSystem;\n const intervalMicros = PluginSandboxRuntime.MONITORING_INTERVAL_MS * 1000;\n context.resourceUsage.cpu.current = (totalCpuMicros / intervalMicros) * 100;\n // Update baseline for next interval\n this.cpuBaselines.set(pluginId, cpuCurrent);\n\n // Check for violations\n const { withinLimits, violations } = this.checkResourceLimits(pluginId);\n if (!withinLimits) {\n this.logger.warn('Resource limit violations detected', { \n pluginId, \n violations \n });\n }\n }\n\n /**\n * Get all active sandboxes\n */\n getAllSandboxes(): Map {\n return new Map(this.sandboxes);\n }\n\n /**\n * Shutdown sandbox runtime\n */\n shutdown(): void {\n // Stop all monitoring\n for (const pluginId of this.monitoringIntervals.keys()) {\n this.stopResourceMonitoring(pluginId);\n }\n\n this.sandboxes.clear();\n this.memoryBaselines.clear();\n this.cpuBaselines.clear();\n \n this.logger.info('Sandbox runtime shutdown complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { \n KernelSecurityVulnerability,\n KernelSecurityScanResult\n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from '../logger.js';\n\n/**\n * Scan Target\n */\nexport interface ScanTarget {\n pluginId: string;\n version: string;\n files?: string[];\n dependencies?: Record;\n}\n\n/**\n * Security Issue\n */\nexport interface SecurityIssue {\n id: string;\n severity: 'critical' | 'high' | 'medium' | 'low' | 'info';\n category: 'vulnerability' | 'malware' | 'license' | 'code-quality' | 'configuration';\n title: string;\n description: string;\n location?: {\n file?: string;\n line?: number;\n column?: number;\n };\n remediation?: string;\n cve?: string;\n cvss?: number;\n}\n\n/**\n * Plugin Security Scanner\n * \n * Scans plugins for security vulnerabilities, malware, and license issues\n */\nexport class PluginSecurityScanner {\n private logger: ObjectLogger;\n \n // Known vulnerabilities database (CVE cache)\n private vulnerabilityDb = new Map();\n \n // Scan results cache\n private scanResults = new Map();\n\n private passThreshold: number = 70;\n\n constructor(logger: ObjectLogger, config?: { passThreshold?: number }) {\n this.logger = logger.child({ component: 'SecurityScanner' });\n if (config?.passThreshold !== undefined) {\n this.passThreshold = config.passThreshold;\n }\n }\n\n /**\n * Perform a comprehensive security scan on a plugin\n */\n async scan(target: ScanTarget): Promise {\n this.logger.info('Starting security scan', { \n pluginId: target.pluginId,\n version: target.version \n });\n\n const issues: SecurityIssue[] = [];\n\n try {\n // 1. Scan for code vulnerabilities\n const codeIssues = await this.scanCode(target);\n issues.push(...codeIssues);\n\n // 2. Scan dependencies for known vulnerabilities\n const depIssues = await this.scanDependencies(target);\n issues.push(...depIssues);\n\n // 3. Scan for malware patterns\n const malwareIssues = await this.scanMalware(target);\n issues.push(...malwareIssues);\n\n // 4. Check license compliance\n const licenseIssues = await this.scanLicenses(target);\n issues.push(...licenseIssues);\n\n // 5. Check configuration security\n const configIssues = await this.scanConfiguration(target);\n issues.push(...configIssues);\n\n // Calculate security score (0-100, higher is better)\n const score = this.calculateSecurityScore(issues);\n\n const result: KernelSecurityScanResult = {\n timestamp: new Date().toISOString(),\n scanner: { name: 'ObjectStack Security Scanner', version: '1.0.0' },\n status: score >= this.passThreshold ? 'passed' : 'failed',\n vulnerabilities: issues.map(issue => ({\n id: issue.id,\n severity: issue.severity,\n category: issue.category,\n title: issue.title,\n description: issue.description,\n location: issue.location ? `${issue.location.file}:${issue.location.line}` : undefined,\n remediation: issue.remediation,\n affectedVersions: [],\n exploitAvailable: false,\n patchAvailable: false,\n })),\n summary: {\n totalVulnerabilities: issues.length,\n criticalCount: issues.filter(i => i.severity === 'critical').length,\n highCount: issues.filter(i => i.severity === 'high').length,\n mediumCount: issues.filter(i => i.severity === 'medium').length,\n lowCount: issues.filter(i => i.severity === 'low').length,\n infoCount: issues.filter(i => i.severity === 'info').length,\n },\n };\n\n this.scanResults.set(`${target.pluginId}:${target.version}`, result);\n\n this.logger.info('Security scan complete', { \n pluginId: target.pluginId,\n score,\n status: result.status,\n summary: result.summary\n });\n\n return result;\n } catch (error) {\n this.logger.error('Security scan failed', { \n pluginId: target.pluginId, \n error \n });\n\n throw error;\n }\n }\n\n /**\n * Scan code for vulnerabilities\n */\n private async scanCode(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n // In a real implementation, this would:\n // - Parse code with AST (e.g., using @typescript-eslint/parser)\n // - Check for dangerous patterns (eval, Function constructor, etc.)\n // - Check for XSS vulnerabilities\n // - Check for SQL injection patterns\n // - Check for insecure crypto usage\n // - Check for path traversal vulnerabilities\n\n this.logger.debug('Code scan complete', { \n pluginId: target.pluginId,\n issuesFound: issues.length \n });\n\n return issues;\n }\n\n /**\n * Scan dependencies for known vulnerabilities\n */\n private async scanDependencies(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n if (!target.dependencies) {\n return issues;\n }\n\n // In a real implementation, this would:\n // - Query npm audit API\n // - Check GitHub Advisory Database\n // - Check Snyk vulnerability database\n // - Check OSV (Open Source Vulnerabilities)\n\n for (const [depName, version] of Object.entries(target.dependencies)) {\n const vulnKey = `${depName}@${version}`;\n const vulnerability = this.vulnerabilityDb.get(vulnKey);\n\n if (vulnerability) {\n issues.push({\n id: `vuln-${vulnerability.cve || depName}`,\n severity: vulnerability.severity,\n category: 'vulnerability',\n title: `Vulnerable dependency: ${depName}`,\n description: `${depName}@${version} has known security vulnerabilities`,\n remediation: vulnerability.fixedIn \n ? `Upgrade to ${vulnerability.fixedIn.join(' or ')}`\n : 'No fix available',\n cve: vulnerability.cve,\n });\n }\n }\n\n this.logger.debug('Dependency scan complete', { \n pluginId: target.pluginId,\n dependencies: Object.keys(target.dependencies).length,\n vulnerabilities: issues.length \n });\n\n return issues;\n }\n\n /**\n * Scan for malware patterns\n */\n private async scanMalware(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n // In a real implementation, this would:\n // - Check for obfuscated code\n // - Check for suspicious network activity patterns\n // - Check for crypto mining patterns\n // - Check for data exfiltration patterns\n // - Use ML-based malware detection\n // - Check file hashes against known malware databases\n\n this.logger.debug('Malware scan complete', { \n pluginId: target.pluginId,\n issuesFound: issues.length \n });\n\n return issues;\n }\n\n /**\n * Check license compliance\n */\n private async scanLicenses(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n if (!target.dependencies) {\n return issues;\n }\n\n // In a real implementation, this would:\n // - Check license compatibility\n // - Detect GPL contamination\n // - Flag proprietary dependencies\n // - Check for missing licenses\n // - Verify SPDX identifiers\n\n this.logger.debug('License scan complete', { \n pluginId: target.pluginId,\n issuesFound: issues.length \n });\n\n return issues;\n }\n\n /**\n * Check configuration security\n */\n private async scanConfiguration(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n // In a real implementation, this would:\n // - Check for hardcoded secrets\n // - Check for weak permissions\n // - Check for insecure defaults\n // - Check for missing security headers\n // - Check CSP policies\n\n this.logger.debug('Configuration scan complete', { \n pluginId: target.pluginId,\n issuesFound: issues.length \n });\n\n return issues;\n }\n\n /**\n * Calculate security score based on issues\n */\n private calculateSecurityScore(issues: SecurityIssue[]): number {\n // Start with perfect score\n let score = 100;\n\n // Deduct points based on severity\n for (const issue of issues) {\n switch (issue.severity) {\n case 'critical':\n score -= 20;\n break;\n case 'high':\n score -= 10;\n break;\n case 'medium':\n score -= 5;\n break;\n case 'low':\n score -= 2;\n break;\n case 'info':\n score -= 0;\n break;\n }\n }\n\n // Ensure score doesn't go below 0\n return Math.max(0, score);\n }\n\n /**\n * Add a vulnerability to the database\n */\n addVulnerability(\n packageName: string,\n version: string,\n vulnerability: KernelSecurityVulnerability\n ): void {\n const key = `${packageName}@${version}`;\n this.vulnerabilityDb.set(key, vulnerability);\n \n this.logger.debug('Vulnerability added to database', { \n package: packageName, \n version,\n cve: vulnerability.cve \n });\n }\n\n /**\n * Get scan result from cache\n */\n getScanResult(pluginId: string, version: string): KernelSecurityScanResult | undefined {\n return this.scanResults.get(`${pluginId}:${version}`);\n }\n\n /**\n * Clear scan results cache\n */\n clearCache(): void {\n this.scanResults.clear();\n this.logger.debug('Scan results cache cleared');\n }\n\n /**\n * Update vulnerability database from external source\n */\n async updateVulnerabilityDatabase(): Promise {\n this.logger.info('Updating vulnerability database');\n\n // In a real implementation, this would:\n // - Fetch from GitHub Advisory Database\n // - Fetch from npm audit\n // - Fetch from NVD (National Vulnerability Database)\n // - Parse and cache vulnerability data\n\n this.logger.info('Vulnerability database updated', { \n entries: this.vulnerabilityDb.size \n });\n }\n\n /**\n * Shutdown security scanner\n */\n shutdown(): void {\n this.vulnerabilityDb.clear();\n this.scanResults.clear();\n \n this.logger.info('Security scanner shutdown complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { \n PluginHealthStatus, \n PluginHealthCheck, \n PluginHealthReport \n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from './logger.js';\nimport type { Plugin } from './types.js';\n\n/**\n * Plugin Health Monitor\n * \n * Monitors plugin health status and performs automatic recovery actions.\n * Implements the advanced lifecycle health monitoring protocol.\n */\nexport class PluginHealthMonitor {\n private logger: ObjectLogger;\n private healthChecks = new Map();\n private healthStatus = new Map();\n private healthReports = new Map();\n private checkIntervals = new Map();\n private failureCounters = new Map();\n private successCounters = new Map();\n private restartAttempts = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'HealthMonitor' });\n }\n\n /**\n * Register a plugin for health monitoring\n */\n registerPlugin(pluginName: string, config: PluginHealthCheck): void {\n this.healthChecks.set(pluginName, config);\n this.healthStatus.set(pluginName, 'unknown');\n this.failureCounters.set(pluginName, 0);\n this.successCounters.set(pluginName, 0);\n this.restartAttempts.set(pluginName, 0);\n\n this.logger.info('Plugin registered for health monitoring', { \n plugin: pluginName,\n interval: config.interval \n });\n }\n\n /**\n * Start monitoring a plugin\n */\n startMonitoring(pluginName: string, plugin: Plugin): void {\n const config = this.healthChecks.get(pluginName);\n if (!config) {\n this.logger.warn('Cannot start monitoring - plugin not registered', { plugin: pluginName });\n return;\n }\n\n // Clear any existing interval\n this.stopMonitoring(pluginName);\n\n // Set up periodic health checks\n const interval = setInterval(() => {\n this.performHealthCheck(pluginName, plugin, config).catch(error => {\n this.logger.error('Health check failed with error', { \n plugin: pluginName, \n error \n });\n });\n }, config.interval);\n\n this.checkIntervals.set(pluginName, interval);\n this.logger.info('Health monitoring started', { plugin: pluginName });\n\n // Perform initial health check\n this.performHealthCheck(pluginName, plugin, config).catch(error => {\n this.logger.error('Initial health check failed', { \n plugin: pluginName, \n error \n });\n });\n }\n\n /**\n * Stop monitoring a plugin\n */\n stopMonitoring(pluginName: string): void {\n const interval = this.checkIntervals.get(pluginName);\n if (interval) {\n clearInterval(interval);\n this.checkIntervals.delete(pluginName);\n this.logger.info('Health monitoring stopped', { plugin: pluginName });\n }\n }\n\n /**\n * Perform a health check on a plugin\n */\n private async performHealthCheck(\n pluginName: string,\n plugin: Plugin,\n config: PluginHealthCheck\n ): Promise {\n const startTime = Date.now();\n let status: PluginHealthStatus = 'healthy';\n let message: string | undefined;\n const checks: Array<{ name: string; status: 'passed' | 'failed' | 'warning'; message?: string }> = [];\n\n try {\n // Check if plugin has a custom health check method\n if (config.checkMethod && typeof (plugin as any)[config.checkMethod] === 'function') {\n const checkResult = await Promise.race([\n (plugin as any)[config.checkMethod](),\n this.timeout(config.timeout, `Health check timeout after ${config.timeout}ms`)\n ]);\n\n if (checkResult === false || (checkResult && checkResult.status === 'unhealthy')) {\n status = 'unhealthy';\n message = checkResult?.message || 'Custom health check failed';\n checks.push({ name: config.checkMethod, status: 'failed', message });\n } else {\n checks.push({ name: config.checkMethod, status: 'passed' });\n }\n } else {\n // Default health check - just verify plugin is loaded\n checks.push({ name: 'plugin-loaded', status: 'passed' });\n }\n\n // Update counters based on result\n if (status === 'healthy') {\n this.successCounters.set(pluginName, (this.successCounters.get(pluginName) || 0) + 1);\n this.failureCounters.set(pluginName, 0);\n\n // Recover from unhealthy state if we have enough successes\n const currentStatus = this.healthStatus.get(pluginName);\n if (currentStatus === 'unhealthy' || currentStatus === 'degraded') {\n const successCount = this.successCounters.get(pluginName) || 0;\n if (successCount >= config.successThreshold) {\n this.healthStatus.set(pluginName, 'healthy');\n this.logger.info('Plugin recovered to healthy state', { plugin: pluginName });\n } else {\n this.healthStatus.set(pluginName, 'recovering');\n }\n } else {\n this.healthStatus.set(pluginName, 'healthy');\n }\n } else {\n this.failureCounters.set(pluginName, (this.failureCounters.get(pluginName) || 0) + 1);\n this.successCounters.set(pluginName, 0);\n\n const failureCount = this.failureCounters.get(pluginName) || 0;\n if (failureCount >= config.failureThreshold) {\n this.healthStatus.set(pluginName, 'unhealthy');\n this.logger.warn('Plugin marked as unhealthy', { \n plugin: pluginName, \n failures: failureCount \n });\n\n // Attempt auto-restart if configured\n if (config.autoRestart) {\n await this.attemptRestart(pluginName, plugin, config);\n }\n } else {\n this.healthStatus.set(pluginName, 'degraded');\n }\n }\n } catch (error) {\n status = 'failed';\n message = error instanceof Error ? error.message : 'Unknown error';\n this.failureCounters.set(pluginName, (this.failureCounters.get(pluginName) || 0) + 1);\n this.healthStatus.set(pluginName, 'failed');\n \n checks.push({ \n name: 'health-check', \n status: 'failed', \n message: message \n });\n\n this.logger.error('Health check exception', { \n plugin: pluginName, \n error \n });\n }\n\n // Create health report\n const report: PluginHealthReport = {\n status: this.healthStatus.get(pluginName) || 'unknown',\n timestamp: new Date().toISOString(),\n message,\n metrics: {\n uptime: Date.now() - startTime,\n },\n checks: checks.length > 0 ? checks : undefined,\n };\n\n this.healthReports.set(pluginName, report);\n }\n\n /**\n * Attempt to restart a plugin\n */\n private async attemptRestart(\n pluginName: string,\n plugin: Plugin,\n config: PluginHealthCheck\n ): Promise {\n const attempts = this.restartAttempts.get(pluginName) || 0;\n \n if (attempts >= config.maxRestartAttempts) {\n this.logger.error('Max restart attempts reached, giving up', { \n plugin: pluginName, \n attempts \n });\n this.healthStatus.set(pluginName, 'failed');\n return;\n }\n\n this.restartAttempts.set(pluginName, attempts + 1);\n \n // Calculate backoff delay\n const delay = this.calculateBackoff(attempts, config.restartBackoff);\n \n this.logger.info('Scheduling plugin restart', { \n plugin: pluginName, \n attempt: attempts + 1, \n delay \n });\n\n await new Promise(resolve => setTimeout(resolve, delay));\n\n try {\n // Call destroy and init to restart\n if (plugin.destroy) {\n await plugin.destroy();\n }\n \n // Note: Full restart would require kernel context\n // This is a simplified version - actual implementation would need kernel integration\n this.logger.info('Plugin restarted', { plugin: pluginName });\n \n // Reset counters on successful restart\n this.failureCounters.set(pluginName, 0);\n this.successCounters.set(pluginName, 0);\n this.healthStatus.set(pluginName, 'recovering');\n } catch (error) {\n this.logger.error('Plugin restart failed', { \n plugin: pluginName, \n error \n });\n this.healthStatus.set(pluginName, 'failed');\n }\n }\n\n /**\n * Calculate backoff delay for restarts\n */\n private calculateBackoff(attempt: number, strategy: 'fixed' | 'linear' | 'exponential'): number {\n const baseDelay = 1000; // 1 second base\n\n switch (strategy) {\n case 'fixed':\n return baseDelay;\n case 'linear':\n return baseDelay * (attempt + 1);\n case 'exponential':\n return baseDelay * Math.pow(2, attempt);\n default:\n return baseDelay;\n }\n }\n\n /**\n * Get current health status of a plugin\n */\n getHealthStatus(pluginName: string): PluginHealthStatus | undefined {\n return this.healthStatus.get(pluginName);\n }\n\n /**\n * Get latest health report for a plugin\n */\n getHealthReport(pluginName: string): PluginHealthReport | undefined {\n return this.healthReports.get(pluginName);\n }\n\n /**\n * Get all health statuses\n */\n getAllHealthStatuses(): Map {\n return new Map(this.healthStatus);\n }\n\n /**\n * Shutdown health monitor\n */\n shutdown(): void {\n // Stop all monitoring intervals\n for (const pluginName of this.checkIntervals.keys()) {\n this.stopMonitoring(pluginName);\n }\n \n this.healthChecks.clear();\n this.healthStatus.clear();\n this.healthReports.clear();\n this.failureCounters.clear();\n this.successCounters.clear();\n this.restartAttempts.clear();\n \n this.logger.info('Health monitor shutdown complete');\n }\n\n /**\n * Timeout helper\n */\n private timeout(ms: number, message: string): Promise {\n return new Promise((_, reject) => {\n setTimeout(() => reject(new Error(message)), ms);\n });\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { createHash } from 'node:crypto';\n\nimport type { \n HotReloadConfig, \n PluginStateSnapshot \n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from './logger.js';\nimport type { Plugin } from './types.js';\n\n// Polyfill for UUID generation to support both Node.js and Browser\nconst generateUUID = () => {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n // Basic UUID v4 fallback\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n};\n\n/**\n * Plugin State Manager\n * \n * Handles state persistence and restoration during hot reloads\n */\nclass PluginStateManager {\n private logger: ObjectLogger;\n private stateSnapshots = new Map();\n private memoryStore = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'StateManager' });\n }\n\n /**\n * Save plugin state before reload\n */\n async saveState(\n pluginId: string,\n version: string,\n state: Record,\n config: HotReloadConfig\n ): Promise {\n const snapshot: PluginStateSnapshot = {\n pluginId,\n version,\n timestamp: new Date().toISOString(),\n state,\n metadata: {\n checksum: this.calculateChecksum(state),\n compressed: false,\n },\n };\n\n const snapshotId = generateUUID();\n\n switch (config.stateStrategy) {\n case 'memory':\n this.memoryStore.set(snapshotId, snapshot);\n this.logger.debug('State saved to memory', { pluginId, snapshotId });\n break;\n\n case 'disk':\n // For disk storage, we would write to file system\n // For now, store in memory as fallback\n this.memoryStore.set(snapshotId, snapshot);\n this.logger.debug('State saved to disk (memory fallback)', { pluginId, snapshotId });\n break;\n\n case 'distributed':\n // For distributed storage, would use Redis/etcd\n // For now, store in memory as fallback\n this.memoryStore.set(snapshotId, snapshot);\n this.logger.debug('State saved to distributed store (memory fallback)', { \n pluginId, \n snapshotId \n });\n break;\n\n case 'none':\n this.logger.debug('State persistence disabled', { pluginId });\n break;\n }\n\n this.stateSnapshots.set(pluginId, snapshot);\n return snapshotId;\n }\n\n /**\n * Restore plugin state after reload\n */\n async restoreState(\n pluginId: string,\n snapshotId?: string\n ): Promise | undefined> {\n // Try to get from snapshot ID first, otherwise use latest for plugin\n let snapshot: PluginStateSnapshot | undefined;\n\n if (snapshotId) {\n snapshot = this.memoryStore.get(snapshotId);\n } else {\n snapshot = this.stateSnapshots.get(pluginId);\n }\n\n if (!snapshot) {\n this.logger.warn('No state snapshot found', { pluginId, snapshotId });\n return undefined;\n }\n\n // Verify checksum if available\n if (snapshot.metadata?.checksum) {\n const currentChecksum = this.calculateChecksum(snapshot.state);\n if (currentChecksum !== snapshot.metadata.checksum) {\n this.logger.error('State checksum mismatch - data may be corrupted', { \n pluginId,\n expected: snapshot.metadata.checksum,\n actual: currentChecksum\n });\n return undefined;\n }\n }\n\n this.logger.debug('State restored', { pluginId, version: snapshot.version });\n return snapshot.state;\n }\n\n /**\n * Clear state for a plugin\n */\n clearState(pluginId: string): void {\n this.stateSnapshots.delete(pluginId);\n // Note: We don't clear memory store as it might have multiple snapshots\n this.logger.debug('State cleared', { pluginId });\n }\n\n /**\n * Calculate checksum for state verification using SHA-256.\n */\n private calculateChecksum(state: Record): string {\n const stateStr = JSON.stringify(state);\n return createHash('sha256').update(stateStr).digest('hex');\n }\n\n /**\n * Shutdown state manager\n */\n shutdown(): void {\n this.stateSnapshots.clear();\n this.memoryStore.clear();\n this.logger.info('State manager shutdown complete');\n }\n}\n\n/**\n * Hot Reload Manager\n * \n * Manages hot reloading of plugins with state preservation\n */\nexport class HotReloadManager {\n private logger: ObjectLogger;\n private stateManager: PluginStateManager;\n private reloadConfigs = new Map();\n private watchHandles = new Map();\n private reloadTimers = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'HotReload' });\n this.stateManager = new PluginStateManager(logger);\n }\n\n /**\n * Register a plugin for hot reload\n */\n registerPlugin(pluginName: string, config: HotReloadConfig): void {\n if (!config.enabled) {\n this.logger.debug('Hot reload disabled for plugin', { plugin: pluginName });\n return;\n }\n\n this.reloadConfigs.set(pluginName, config);\n this.logger.info('Plugin registered for hot reload', { \n plugin: pluginName,\n watchPatterns: config.watchPatterns,\n stateStrategy: config.stateStrategy\n });\n }\n\n /**\n * Start watching for changes (requires file system integration)\n */\n startWatching(pluginName: string): void {\n const config = this.reloadConfigs.get(pluginName);\n if (!config || !config.enabled) {\n return;\n }\n\n // Note: Actual file watching would require chokidar or similar\n // This is a placeholder for the integration point\n this.logger.info('File watching started', { \n plugin: pluginName,\n patterns: config.watchPatterns \n });\n }\n\n /**\n * Stop watching for changes\n */\n stopWatching(pluginName: string): void {\n const handle = this.watchHandles.get(pluginName);\n if (handle) {\n // Stop watching (would call chokidar close())\n this.watchHandles.delete(pluginName);\n this.logger.info('File watching stopped', { plugin: pluginName });\n }\n\n // Clear any pending reload timers\n const timer = this.reloadTimers.get(pluginName);\n if (timer) {\n clearTimeout(timer);\n this.reloadTimers.delete(pluginName);\n }\n }\n\n /**\n * Trigger hot reload for a plugin\n */\n async reloadPlugin(\n pluginName: string,\n plugin: Plugin,\n version: string,\n getPluginState: () => Record,\n restorePluginState: (state: Record) => void\n ): Promise {\n const config = this.reloadConfigs.get(pluginName);\n if (!config) {\n this.logger.warn('Cannot reload - plugin not registered', { plugin: pluginName });\n return false;\n }\n\n this.logger.info('Starting hot reload', { plugin: pluginName });\n\n try {\n // Call before reload hooks\n if (config.beforeReload) {\n this.logger.debug('Executing before reload hooks', { \n plugin: pluginName,\n hooks: config.beforeReload \n });\n // Hook execution would be done through kernel's hook system\n }\n\n // Save state if configured\n let snapshotId: string | undefined;\n if (config.preserveState && config.stateStrategy !== 'none') {\n const state = getPluginState();\n snapshotId = await this.stateManager.saveState(\n pluginName,\n version,\n state,\n config\n );\n this.logger.debug('Plugin state saved', { plugin: pluginName, snapshotId });\n }\n\n // Gracefully shutdown the plugin\n if (plugin.destroy) {\n this.logger.debug('Destroying plugin', { plugin: pluginName });\n \n const shutdownPromise = plugin.destroy();\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => reject(new Error('Shutdown timeout')), config.shutdownTimeout);\n });\n\n await Promise.race([shutdownPromise, timeoutPromise]);\n this.logger.debug('Plugin destroyed successfully', { plugin: pluginName });\n }\n\n // At this point, the kernel would reload the plugin module\n // This would be handled by the plugin loader\n this.logger.debug('Plugin module would be reloaded here', { plugin: pluginName });\n\n // Restore state if we saved it\n if (snapshotId && config.preserveState) {\n const restoredState = await this.stateManager.restoreState(pluginName, snapshotId);\n if (restoredState) {\n restorePluginState(restoredState);\n this.logger.debug('Plugin state restored', { plugin: pluginName });\n }\n }\n\n // Call after reload hooks\n if (config.afterReload) {\n this.logger.debug('Executing after reload hooks', { \n plugin: pluginName,\n hooks: config.afterReload \n });\n // Hook execution would be done through kernel's hook system\n }\n\n this.logger.info('Hot reload completed successfully', { plugin: pluginName });\n return true;\n } catch (error) {\n this.logger.error('Hot reload failed', { \n plugin: pluginName, \n error \n });\n return false;\n }\n }\n\n /**\n * Schedule a reload with debouncing\n */\n scheduleReload(\n pluginName: string,\n reloadFn: () => Promise\n ): void {\n const config = this.reloadConfigs.get(pluginName);\n if (!config) {\n return;\n }\n\n // Clear existing timer\n const existingTimer = this.reloadTimers.get(pluginName);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Schedule new reload with debounce\n const timer = setTimeout(() => {\n this.logger.debug('Debounce period elapsed, executing reload', { \n plugin: pluginName \n });\n reloadFn().catch(error => {\n this.logger.error('Scheduled reload failed', { \n plugin: pluginName, \n error \n });\n });\n this.reloadTimers.delete(pluginName);\n }, config.debounceDelay);\n\n this.reloadTimers.set(pluginName, timer);\n this.logger.debug('Reload scheduled with debounce', { \n plugin: pluginName,\n delay: config.debounceDelay \n });\n }\n\n /**\n * Get state manager for direct access\n */\n getStateManager(): PluginStateManager {\n return this.stateManager;\n }\n\n /**\n * Shutdown hot reload manager\n */\n shutdown(): void {\n // Stop all watching\n for (const pluginName of this.watchHandles.keys()) {\n this.stopWatching(pluginName);\n }\n\n // Clear all timers\n for (const timer of this.reloadTimers.values()) {\n clearTimeout(timer);\n }\n\n this.reloadConfigs.clear();\n this.watchHandles.clear();\n this.reloadTimers.clear();\n this.stateManager.shutdown();\n \n this.logger.info('Hot reload manager shutdown complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { \n SemanticVersion,\n VersionConstraint,\n CompatibilityLevel,\n DependencyConflict\n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from './logger.js';\n\n/**\n * Semantic Version Parser and Comparator\n * \n * Implements semantic versioning comparison and constraint matching\n */\nexport class SemanticVersionManager {\n /**\n * Parse a version string into semantic version components\n */\n static parse(versionStr: string): SemanticVersion {\n // Remove 'v' prefix if present\n const cleanVersion = versionStr.replace(/^v/, '');\n \n // Match semver pattern: major.minor.patch[-prerelease][+build]\n const match = cleanVersion.match(\n /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([a-zA-Z0-9.-]+))?(?:\\+([a-zA-Z0-9.-]+))?$/\n );\n\n if (!match) {\n throw new Error(`Invalid semantic version: ${versionStr}`);\n }\n\n return {\n major: parseInt(match[1], 10),\n minor: parseInt(match[2], 10),\n patch: parseInt(match[3], 10),\n preRelease: match[4],\n build: match[5],\n };\n }\n\n /**\n * Convert semantic version back to string\n */\n static toString(version: SemanticVersion): string {\n let str = `${version.major}.${version.minor}.${version.patch}`;\n if (version.preRelease) {\n str += `-${version.preRelease}`;\n }\n if (version.build) {\n str += `+${version.build}`;\n }\n return str;\n }\n\n /**\n * Compare two semantic versions\n * Returns: -1 if a < b, 0 if a === b, 1 if a > b\n */\n static compare(a: SemanticVersion, b: SemanticVersion): number {\n // Compare major, minor, patch\n if (a.major !== b.major) return a.major - b.major;\n if (a.minor !== b.minor) return a.minor - b.minor;\n if (a.patch !== b.patch) return a.patch - b.patch;\n\n // Pre-release versions have lower precedence\n if (a.preRelease && !b.preRelease) return -1;\n if (!a.preRelease && b.preRelease) return 1;\n \n // Compare pre-release versions\n if (a.preRelease && b.preRelease) {\n return a.preRelease.localeCompare(b.preRelease);\n }\n\n return 0;\n }\n\n /**\n * Check if version satisfies constraint\n */\n static satisfies(version: SemanticVersion, constraint: VersionConstraint): boolean {\n const constraintStr = constraint as string;\n\n // Any version\n if (constraintStr === '*' || constraintStr === 'latest') {\n return true;\n }\n\n // Exact version\n if (/^[\\d.]+$/.test(constraintStr)) {\n const exact = this.parse(constraintStr);\n return this.compare(version, exact) === 0;\n }\n\n // Caret range (^): Compatible with version\n if (constraintStr.startsWith('^')) {\n const base = this.parse(constraintStr.slice(1));\n return (\n version.major === base.major &&\n this.compare(version, base) >= 0\n );\n }\n\n // Tilde range (~): Approximately equivalent\n if (constraintStr.startsWith('~')) {\n const base = this.parse(constraintStr.slice(1));\n return (\n version.major === base.major &&\n version.minor === base.minor &&\n this.compare(version, base) >= 0\n );\n }\n\n // Greater than or equal\n if (constraintStr.startsWith('>=')) {\n const base = this.parse(constraintStr.slice(2));\n return this.compare(version, base) >= 0;\n }\n\n // Greater than\n if (constraintStr.startsWith('>')) {\n const base = this.parse(constraintStr.slice(1));\n return this.compare(version, base) > 0;\n }\n\n // Less than or equal\n if (constraintStr.startsWith('<=')) {\n const base = this.parse(constraintStr.slice(2));\n return this.compare(version, base) <= 0;\n }\n\n // Less than\n if (constraintStr.startsWith('<')) {\n const base = this.parse(constraintStr.slice(1));\n return this.compare(version, base) < 0;\n }\n\n // Range (1.2.3 - 2.3.4)\n const rangeMatch = constraintStr.match(/^([\\d.]+)\\s*-\\s*([\\d.]+)$/);\n if (rangeMatch) {\n const min = this.parse(rangeMatch[1]);\n const max = this.parse(rangeMatch[2]);\n return this.compare(version, min) >= 0 && this.compare(version, max) <= 0;\n }\n\n return false;\n }\n\n /**\n * Determine compatibility level between two versions\n */\n static getCompatibilityLevel(from: SemanticVersion, to: SemanticVersion): CompatibilityLevel {\n const cmp = this.compare(from, to);\n\n // Same version\n if (cmp === 0) {\n return 'fully-compatible';\n }\n\n // Major version changed - breaking changes\n if (from.major !== to.major) {\n return 'breaking-changes';\n }\n\n // Minor version increased - backward compatible\n if (from.minor < to.minor) {\n return 'backward-compatible';\n }\n\n // Patch version increased - fully compatible\n if (from.patch < to.patch) {\n return 'fully-compatible';\n }\n\n // Downgrade - incompatible\n return 'incompatible';\n }\n}\n\n/**\n * Plugin Dependency Resolver\n * \n * Resolves plugin dependencies using topological sorting and conflict detection\n */\nexport class DependencyResolver {\n private logger: ObjectLogger;\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'DependencyResolver' });\n }\n\n /**\n * Resolve dependencies using topological sort\n */\n resolve(\n plugins: Map\n ): string[] {\n const graph = new Map();\n const inDegree = new Map();\n\n // Build dependency graph\n for (const [pluginName, pluginInfo] of plugins) {\n if (!graph.has(pluginName)) {\n graph.set(pluginName, []);\n inDegree.set(pluginName, 0);\n }\n\n const deps = pluginInfo.dependencies || [];\n for (const dep of deps) {\n // Check if dependency exists\n if (!plugins.has(dep)) {\n throw new Error(`Missing dependency: ${pluginName} requires ${dep}`);\n }\n\n // Add edge\n if (!graph.has(dep)) {\n graph.set(dep, []);\n inDegree.set(dep, 0);\n }\n graph.get(dep)!.push(pluginName);\n inDegree.set(pluginName, (inDegree.get(pluginName) || 0) + 1);\n }\n }\n\n // Topological sort using Kahn's algorithm\n const queue: string[] = [];\n const result: string[] = [];\n\n // Add all nodes with no incoming edges\n for (const [node, degree] of inDegree) {\n if (degree === 0) {\n queue.push(node);\n }\n }\n\n while (queue.length > 0) {\n const node = queue.shift()!;\n result.push(node);\n\n // Reduce in-degree for dependent nodes\n const dependents = graph.get(node) || [];\n for (const dependent of dependents) {\n const newDegree = (inDegree.get(dependent) || 0) - 1;\n inDegree.set(dependent, newDegree);\n \n if (newDegree === 0) {\n queue.push(dependent);\n }\n }\n }\n\n // Check for circular dependencies\n if (result.length !== plugins.size) {\n const remaining = Array.from(plugins.keys()).filter(p => !result.includes(p));\n this.logger.error('Circular dependency detected', { remaining });\n throw new Error(`Circular dependency detected among: ${remaining.join(', ')}`);\n }\n\n this.logger.debug('Dependencies resolved', { order: result });\n return result;\n }\n\n /**\n * Detect dependency conflicts\n */\n detectConflicts(\n plugins: Map }>\n ): DependencyConflict[] {\n const conflicts: DependencyConflict[] = [];\n const versionRequirements = new Map>();\n\n // Collect all version requirements\n for (const [pluginName, pluginInfo] of plugins) {\n if (!pluginInfo.dependencies) continue;\n\n for (const [depName, constraint] of Object.entries(pluginInfo.dependencies)) {\n if (!versionRequirements.has(depName)) {\n versionRequirements.set(depName, new Map());\n }\n versionRequirements.get(depName)!.set(pluginName, constraint);\n }\n }\n\n // Check for version mismatches\n for (const [depName, requirements] of versionRequirements) {\n const depInfo = plugins.get(depName);\n if (!depInfo) continue;\n\n const depVersion = SemanticVersionManager.parse(depInfo.version);\n const unsatisfied: Array<{ pluginId: string; version: string }> = [];\n\n for (const [requiringPlugin, constraint] of requirements) {\n if (!SemanticVersionManager.satisfies(depVersion, constraint)) {\n unsatisfied.push({\n pluginId: requiringPlugin,\n version: constraint as string,\n });\n }\n }\n\n if (unsatisfied.length > 0) {\n conflicts.push({\n type: 'version-mismatch',\n severity: 'error',\n description: `Version mismatch for ${depName}: detected ${unsatisfied.length} unsatisfied requirements`,\n plugins: [\n { pluginId: depName, version: depInfo.version },\n ...unsatisfied,\n ],\n resolutions: [{\n strategy: 'upgrade',\n description: `Upgrade ${depName} to satisfy all constraints`,\n targetPlugins: [depName],\n automatic: false,\n } as any],\n });\n }\n }\n\n // Check for circular dependencies (will be caught by resolve())\n try {\n this.resolve(new Map(\n Array.from(plugins.entries()).map(([name, info]) => [\n name,\n { version: info.version, dependencies: info.dependencies ? Object.keys(info.dependencies) : [] }\n ])\n ));\n } catch (error) {\n if (error instanceof Error && error.message.includes('Circular dependency')) {\n conflicts.push({\n type: 'circular-dependency',\n severity: 'critical',\n description: error.message,\n plugins: [], // Would need to extract from error\n resolutions: [{\n strategy: 'manual',\n description: 'Remove circular dependency by restructuring plugins',\n automatic: false,\n } as any],\n });\n }\n }\n\n return conflicts;\n }\n\n /**\n * Find best version that satisfies all constraints\n */\n findBestVersion(\n availableVersions: string[],\n constraints: VersionConstraint[]\n ): string | undefined {\n // Parse and sort versions (highest first)\n const versions = availableVersions\n .map(v => ({ str: v, parsed: SemanticVersionManager.parse(v) }))\n .sort((a, b) => -SemanticVersionManager.compare(a.parsed, b.parsed));\n\n // Find highest version that satisfies all constraints\n for (const version of versions) {\n const satisfiesAll = constraints.every(constraint =>\n SemanticVersionManager.satisfies(version.parsed, constraint)\n );\n\n if (satisfiesAll) {\n return version.str;\n }\n }\n\n return undefined;\n }\n\n /**\n * Check if dependencies form a valid DAG (no cycles)\n */\n isAcyclic(dependencies: Map): boolean {\n try {\n const plugins = new Map(\n Array.from(dependencies.entries()).map(([name, deps]) => [\n name,\n { dependencies: deps }\n ])\n );\n this.resolve(plugins);\n return true;\n } catch {\n return false;\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ObjectLogger } from './logger.js';\n\n/**\n * Namespace entry representing an object/view/flow etc. registered by a package.\n */\nexport interface NamespaceEntry {\n /** The namespace path (e.g. \"objects.project_task\", \"views.task_list\") */\n namespace: string;\n /** The package that owns this namespace */\n packageId: string;\n /** When this entry was registered */\n registeredAt: string;\n}\n\n/**\n * Result of a namespace conflict check.\n */\nexport interface NamespaceConflict {\n /** The conflicting namespace path */\n namespace: string;\n /** The package that currently owns this namespace */\n existingPackageId: string;\n /** The package attempting to register the same namespace */\n incomingPackageId: string;\n /** A suggested alternative name to avoid the conflict */\n suggestion?: string;\n}\n\n/**\n * Result of namespace availability check.\n */\nexport interface NamespaceCheckResult {\n /** Whether all requested namespaces are available */\n available: boolean;\n /** List of conflicts detected */\n conflicts: NamespaceConflict[];\n /** Suggested alternatives for each conflict */\n suggestions: Record;\n}\n\n/**\n * Namespace Resolver\n *\n * Manages namespace registration for installed packages and detects collisions\n * during install-time. Each metadata item (object, view, flow, page, etc.)\n * produces a namespace like `objects.` or `views.`.\n *\n * When a new package declares objects, views, or other metadata that would\n * collide with an existing package's metadata, this resolver reports the\n * conflicts and suggests prefixed alternatives.\n */\nexport class NamespaceResolver {\n private logger: ObjectLogger;\n private registry: Map = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'NamespaceResolver' });\n }\n\n /**\n * Register namespaces owned by a package.\n */\n register(packageId: string, namespaces: string[]): void {\n const now = new Date().toISOString();\n for (const ns of namespaces) {\n if (this.registry.has(ns)) {\n const existing = this.registry.get(ns)!;\n if (existing.packageId !== packageId) {\n this.logger.warn('Overwriting namespace entry', { namespace: ns, existing: existing.packageId, incoming: packageId });\n }\n }\n this.registry.set(ns, { namespace: ns, packageId, registeredAt: now });\n this.logger.debug('Namespace registered', { namespace: ns, packageId });\n }\n }\n\n /**\n * Unregister all namespaces belonging to a package.\n */\n unregister(packageId: string): string[] {\n const removed: string[] = [];\n for (const [ns, entry] of this.registry) {\n if (entry.packageId === packageId) {\n this.registry.delete(ns);\n removed.push(ns);\n }\n }\n this.logger.debug('Namespaces unregistered', { packageId, count: removed.length });\n return removed;\n }\n\n /**\n * Check whether a set of namespaces is available for a given package.\n */\n checkAvailability(packageId: string, namespaces: string[]): NamespaceCheckResult {\n const conflicts: NamespaceConflict[] = [];\n const suggestions: Record = {};\n\n for (const ns of namespaces) {\n const existing = this.registry.get(ns);\n if (existing && existing.packageId !== packageId) {\n const suggestion = this.suggestAlternative(ns, packageId);\n conflicts.push({\n namespace: ns,\n existingPackageId: existing.packageId,\n incomingPackageId: packageId,\n suggestion,\n });\n suggestions[ns] = suggestion;\n }\n }\n\n return {\n available: conflicts.length === 0,\n conflicts,\n suggestions,\n };\n }\n\n /**\n * Extract namespace strings from a package's metadata definition.\n */\n extractNamespaces(config: Record): string[] {\n const namespaces: string[] = [];\n const categories = [\n 'objects', 'views', 'pages', 'flows', 'workflows',\n 'apps', 'dashboards', 'reports', 'actions', 'agents',\n ];\n\n for (const category of categories) {\n const items = config[category];\n if (Array.isArray(items)) {\n for (const item of items) {\n const name = (item as Record)?.name;\n if (typeof name === 'string') {\n namespaces.push(`${category}.${name}`);\n }\n }\n } else if (items && typeof items === 'object') {\n for (const key of Object.keys(items as object)) {\n namespaces.push(`${category}.${key}`);\n }\n }\n }\n\n return namespaces;\n }\n\n /**\n * Get all registered entries.\n */\n getRegistry(): ReadonlyMap {\n return this.registry;\n }\n\n /**\n * Get all namespaces belonging to a specific package.\n */\n getPackageNamespaces(packageId: string): string[] {\n const namespaces: string[] = [];\n for (const [ns, entry] of this.registry) {\n if (entry.packageId === packageId) {\n namespaces.push(ns);\n }\n }\n return namespaces;\n }\n\n /**\n * Generate a prefixed alternative namespace to avoid conflicts.\n */\n private suggestAlternative(ns: string, packageId: string): string {\n // Extract the short package name for prefixing\n const shortName = packageId\n .replace(/^@[^/]+\\//, '')\n .replace(/^plugin-/, '')\n .replace(/-/g, '_');\n\n const parts = ns.split('.');\n if (parts.length >= 2) {\n // e.g. \"objects.task\" → \"objects.crm_task\"\n return `${parts[0]}.${shortName}_${parts.slice(1).join('.')}`;\n }\n return `${shortName}_${ns}`;\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ObjectLogger } from './logger.js';\nimport { DependencyResolver, SemanticVersionManager } from './dependency-resolver.js';\nimport { NamespaceResolver } from './namespace-resolver.js';\n\n/**\n * Installed package record in the runtime registry.\n */\nexport interface InstalledPackageRecord {\n /** Package identifier */\n packageId: string;\n /** Package version */\n version: string;\n /** Package manifest */\n manifest: Record;\n /** Installation timestamp */\n installedAt: string;\n /** Current status */\n status: 'installed' | 'disabled' | 'installing' | 'upgrading' | 'uninstalling' | 'error';\n /** Namespaces registered by this package */\n namespaces: string[];\n /** Dependencies of this package */\n dependencies: string[];\n}\n\n/**\n * Snapshot of a package's state before upgrade (for rollback).\n */\nexport interface PackageSnapshot {\n /** Package identifier */\n packageId: string;\n /** Version before upgrade */\n previousVersion: string;\n /** Full manifest before upgrade */\n previousManifest: Record;\n /** Namespaces before upgrade */\n previousNamespaces: string[];\n /** Original installation timestamp */\n installedAt: string;\n /** Snapshot timestamp */\n createdAt: string;\n}\n\n/**\n * Result of a package installation attempt.\n */\nexport interface InstallResult {\n success: boolean;\n packageId: string;\n version: string;\n installedDependencies: string[];\n namespaceConflicts: Array<{ namespace: string; existingPackageId: string }>;\n errorMessage?: string;\n}\n\n/**\n * Result of an upgrade attempt.\n */\nexport interface UpgradeResult {\n success: boolean;\n packageId: string;\n fromVersion: string;\n toVersion: string;\n snapshot: PackageSnapshot;\n errorMessage?: string;\n}\n\n/**\n * Result of a rollback attempt.\n */\nexport interface RollbackResult {\n success: boolean;\n packageId: string;\n restoredVersion: string;\n errorMessage?: string;\n}\n\n/**\n * Package Manager\n *\n * Runtime implementation for the full package lifecycle:\n * install → upgrade → rollback → uninstall.\n *\n * Consumes the protocol schemas defined in @objectstack/spec:\n * - DependencyResolutionResultSchema\n * - NamespaceConflictErrorSchema\n * - UpgradePlanSchema / UpgradeSnapshotSchema\n * - PackageArtifactSchema\n *\n * Coordinates with:\n * - DependencyResolver for topological ordering and conflict detection\n * - NamespaceResolver for metadata collision prevention\n */\nexport class PackageManager {\n private logger: ObjectLogger;\n private packages: Map = new Map();\n private snapshots: Map = new Map();\n private dependencyResolver: DependencyResolver;\n private namespaceResolver: NamespaceResolver;\n private platformVersion: string;\n\n constructor(\n logger: ObjectLogger,\n options: { platformVersion?: string } = {},\n ) {\n this.logger = logger.child({ component: 'PackageManager' });\n this.dependencyResolver = new DependencyResolver(logger);\n this.namespaceResolver = new NamespaceResolver(logger);\n this.platformVersion = options.platformVersion || '3.0.0';\n }\n\n /**\n * Install a package with full dependency resolution and namespace checking.\n */\n async install(\n packageId: string,\n version: string,\n manifest: Record,\n ): Promise {\n this.logger.info('Installing package', { packageId, version });\n\n // 1. Check if already installed\n if (this.packages.has(packageId)) {\n const existing = this.packages.get(packageId)!;\n if (existing.status === 'installed') {\n return {\n success: false,\n packageId,\n version,\n installedDependencies: [],\n namespaceConflicts: [],\n errorMessage: `Package ${packageId}@${existing.version} is already installed. Use upgrade instead.`,\n };\n }\n }\n\n // 2. Check platform compatibility\n const engine = (manifest as any).engine?.objectstack as string | undefined;\n if (engine) {\n const platformSemver = SemanticVersionManager.parse(this.platformVersion);\n if (!SemanticVersionManager.satisfies(platformSemver, engine)) {\n return {\n success: false,\n packageId,\n version,\n installedDependencies: [],\n namespaceConflicts: [],\n errorMessage: `Package requires platform ${engine}, but current platform is v${this.platformVersion}`,\n };\n }\n }\n\n // 3. Check namespace conflicts\n const namespaces = this.namespaceResolver.extractNamespaces(manifest);\n const nsCheck = this.namespaceResolver.checkAvailability(packageId, namespaces);\n if (!nsCheck.available) {\n return {\n success: false,\n packageId,\n version,\n installedDependencies: [],\n namespaceConflicts: nsCheck.conflicts.map(c => ({\n namespace: c.namespace,\n existingPackageId: c.existingPackageId,\n })),\n errorMessage: `Namespace conflicts detected: ${nsCheck.conflicts.map(c => c.namespace).join(', ')}`,\n };\n }\n\n // 4. Resolve dependencies\n const deps = (manifest as any).dependencies as Record | undefined;\n const depNames = deps ? Object.keys(deps) : [];\n const missingDeps = depNames.filter(d => !this.packages.has(d));\n if (missingDeps.length > 0) {\n return {\n success: false,\n packageId,\n version,\n installedDependencies: [],\n namespaceConflicts: [],\n errorMessage: `Missing dependencies: ${missingDeps.join(', ')}`,\n };\n }\n\n // 5. Register package\n this.packages.set(packageId, {\n packageId,\n version,\n manifest,\n installedAt: new Date().toISOString(),\n status: 'installed',\n namespaces,\n dependencies: depNames,\n });\n\n // 6. Register namespaces\n this.namespaceResolver.register(packageId, namespaces);\n\n this.logger.info('Package installed', { packageId, version, namespaces: namespaces.length });\n\n return {\n success: true,\n packageId,\n version,\n installedDependencies: depNames,\n namespaceConflicts: [],\n };\n }\n\n /**\n * Uninstall a package, checking for dependents first.\n */\n async uninstall(packageId: string): Promise<{ success: boolean; errorMessage?: string }> {\n const pkg = this.packages.get(packageId);\n if (!pkg) {\n return { success: false, errorMessage: `Package ${packageId} is not installed` };\n }\n\n // Check if other packages depend on this one\n const dependents: string[] = [];\n for (const [id, record] of this.packages) {\n if (id !== packageId && record.dependencies.includes(packageId)) {\n dependents.push(id);\n }\n }\n\n if (dependents.length > 0) {\n return {\n success: false,\n errorMessage: `Cannot uninstall ${packageId}: depended upon by ${dependents.join(', ')}`,\n };\n }\n\n // Remove namespaces and package\n this.namespaceResolver.unregister(packageId);\n this.packages.delete(packageId);\n this.snapshots.delete(packageId);\n\n this.logger.info('Package uninstalled', { packageId });\n return { success: true };\n }\n\n /**\n * Upgrade a package: snapshot → update → register.\n */\n async upgrade(\n packageId: string,\n newVersion: string,\n newManifest: Record,\n ): Promise {\n const existing = this.packages.get(packageId);\n if (!existing) {\n return {\n success: false,\n packageId,\n fromVersion: '',\n toVersion: newVersion,\n snapshot: { packageId, previousVersion: '', previousManifest: {}, previousNamespaces: [], installedAt: '', createdAt: new Date().toISOString() },\n errorMessage: `Package ${packageId} is not installed`,\n };\n }\n\n // 1. Create snapshot for rollback\n const snapshot: PackageSnapshot = {\n packageId,\n previousVersion: existing.version,\n previousManifest: existing.manifest,\n previousNamespaces: [...existing.namespaces],\n installedAt: existing.installedAt,\n createdAt: new Date().toISOString(),\n };\n this.snapshots.set(packageId, snapshot);\n\n // 2. Check platform compatibility\n const engine = (newManifest as any).engine?.objectstack as string | undefined;\n if (engine) {\n const platformSemver = SemanticVersionManager.parse(this.platformVersion);\n if (!SemanticVersionManager.satisfies(platformSemver, engine)) {\n return {\n success: false,\n packageId,\n fromVersion: existing.version,\n toVersion: newVersion,\n snapshot,\n errorMessage: `New version requires platform ${engine}, current is v${this.platformVersion}`,\n };\n }\n }\n\n // 3. Check namespace changes\n const newNamespaces = this.namespaceResolver.extractNamespaces(newManifest);\n // Temporarily remove old namespaces to check new ones\n this.namespaceResolver.unregister(packageId);\n const nsCheck = this.namespaceResolver.checkAvailability(packageId, newNamespaces);\n if (!nsCheck.available) {\n // Restore old namespaces on failure\n this.namespaceResolver.register(packageId, existing.namespaces);\n return {\n success: false,\n packageId,\n fromVersion: existing.version,\n toVersion: newVersion,\n snapshot,\n errorMessage: `Namespace conflicts in new version: ${nsCheck.conflicts.map(c => c.namespace).join(', ')}`,\n };\n }\n\n // 4. Register new namespaces and update record\n this.namespaceResolver.register(packageId, newNamespaces);\n const deps = (newManifest as any).dependencies as Record | undefined;\n\n this.packages.set(packageId, {\n packageId,\n version: newVersion,\n manifest: newManifest,\n installedAt: existing.installedAt,\n status: 'installed',\n namespaces: newNamespaces,\n dependencies: deps ? Object.keys(deps) : [],\n });\n\n this.logger.info('Package upgraded', { packageId, from: existing.version, to: newVersion });\n\n return {\n success: true,\n packageId,\n fromVersion: existing.version,\n toVersion: newVersion,\n snapshot,\n };\n }\n\n /**\n * Rollback a package to its pre-upgrade snapshot.\n */\n async rollback(packageId: string): Promise {\n const snapshot = this.snapshots.get(packageId);\n if (!snapshot) {\n return {\n success: false,\n packageId,\n restoredVersion: '',\n errorMessage: `No upgrade snapshot found for ${packageId}`,\n };\n }\n\n // Restore previous state\n this.namespaceResolver.unregister(packageId);\n this.namespaceResolver.register(packageId, snapshot.previousNamespaces);\n\n const deps = (snapshot.previousManifest as any).dependencies as Record | undefined;\n this.packages.set(packageId, {\n packageId,\n version: snapshot.previousVersion,\n manifest: snapshot.previousManifest,\n installedAt: snapshot.installedAt,\n status: 'installed',\n namespaces: snapshot.previousNamespaces,\n dependencies: deps ? Object.keys(deps) : [],\n });\n\n this.snapshots.delete(packageId);\n\n this.logger.info('Package rolled back', { packageId, to: snapshot.previousVersion });\n\n return {\n success: true,\n packageId,\n restoredVersion: snapshot.previousVersion,\n };\n }\n\n /**\n * Get an installed package record.\n */\n getPackage(packageId: string): InstalledPackageRecord | undefined {\n return this.packages.get(packageId);\n }\n\n /**\n * List all installed packages.\n */\n listPackages(): InstalledPackageRecord[] {\n return Array.from(this.packages.values());\n }\n\n /**\n * Resolve dependencies for a set of packages.\n */\n resolveDependencies(\n packages: Map,\n ): string[] {\n return this.dependencyResolver.resolve(packages);\n }\n\n /**\n * Check namespace availability for a package's metadata.\n */\n checkNamespaces(packageId: string, config: Record): {\n available: boolean;\n conflicts: Array<{ namespace: string; existingPackageId: string }>;\n } {\n const namespaces = this.namespaceResolver.extractNamespaces(config);\n const result = this.namespaceResolver.checkAvailability(packageId, namespaces);\n return {\n available: result.available,\n conflicts: result.conflicts.map(c => ({\n namespace: c.namespace,\n existingPackageId: c.existingPackageId,\n })),\n };\n }\n\n /**\n * Get the namespace resolver instance.\n */\n getNamespaceResolver(): NamespaceResolver {\n return this.namespaceResolver;\n }\n\n /**\n * Get a snapshot for a given package (if available).\n */\n getSnapshot(packageId: string): PackageSnapshot | undefined {\n return this.snapshots.get(packageId);\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Query DSL Specification\n * \n * Based on industry best practices from:\n * - Prisma ORM\n * - Strapi CMS\n * - TypeORM\n * - LoopBack Framework\n * \n * Version: 1.0.0\n * Status: Draft\n * \n * Objective: Define a JSON-based, database-agnostic query syntax standard\n * for data filtering interactions between frontend and backend APIs.\n * \n * Design Principles:\n * 1. Declarative: Frontend describes \"what data to get\", not \"how to query\"\n * 2. Database Agnostic: Syntax contains no database-specific directives\n * 3. Type Safe: Structure can be statically inferred by TypeScript\n * 4. Convention over Configuration: Implicit syntax for common queries\n */\n\n/**\n * Field Reference\n * Represents a reference to another field/column instead of a literal value.\n * Used for joins (ON clause) and cross-field comparisons.\n * \n * @example\n * // user.id = order.owner_id\n * { \"$eq\": { \"$field\": \"order.owner_id\" } }\n */\nexport const FieldReferenceSchema = z.object({\n $field: z.string().describe('Field Reference/Column Name')\n});\n\nexport type FieldReference = z.infer;\n\n// ============================================================================\n// 3.1 Comparison Operators\n// ============================================================================\n\n/**\n * Comparison operators for equality and inequality checks.\n * Supported data types: Any\n */\nexport const EqualityOperatorSchema = z.object({\n /** Equal to (default) - SQL: = | MongoDB: $eq */\n $eq: z.any().optional(),\n \n /** Not equal to - SQL: <> or != | MongoDB: $ne */\n $ne: z.any().optional(),\n});\n\n/**\n * Comparison operators for numeric and date comparisons.\n * Supported data types: Number, Date\n */\nexport const ComparisonOperatorSchema = z.object({\n /** Greater than - SQL: > | MongoDB: $gt */\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Greater than or equal to - SQL: >= | MongoDB: $gte */\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than - SQL: < | MongoDB: $lt */\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than or equal to - SQL: <= | MongoDB: $lte */\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n});\n\n// ============================================================================\n// 3.2 Set & Range Operators\n// ============================================================================\n\n/**\n * Set operators for membership checks.\n */\nexport const SetOperatorSchema = z.object({\n /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */\n $in: z.array(z.any()).optional(),\n \n /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */\n $nin: z.array(z.any()).optional(),\n});\n\n/**\n * Range operator for interval checks (closed interval).\n * SQL: BETWEEN ? AND ? | MongoDB: $gte AND $lte\n */\nexport const RangeOperatorSchema = z.object({\n /** Between (inclusive) - takes [min, max] array */\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n});\n\n// ============================================================================\n// 3.3 String-Specific Operators\n// ============================================================================\n\n/**\n * String pattern matching operators.\n * Note: Case sensitivity should be handled at backend level.\n */\nexport const StringOperatorSchema = z.object({\n /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */\n $contains: z.string().optional(),\n \n /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */\n $notContains: z.string().optional(),\n \n /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */\n $startsWith: z.string().optional(),\n \n /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */\n $endsWith: z.string().optional(),\n});\n\n// ============================================================================\n// 3.5 Special Operators\n// ============================================================================\n\n/**\n * Special check operators for null and existence.\n */\nexport const SpecialOperatorSchema = z.object({\n /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */\n $null: z.boolean().optional(),\n \n /** Field exists check (primarily for NoSQL) - MongoDB: $exists */\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// Combined Field Operators\n// ============================================================================\n\n/**\n * All field-level operators combined.\n * These can be applied to individual fields in a filter.\n */\nexport const FieldOperatorsSchema = z.object({\n // Equality\n $eq: z.any().optional(),\n $ne: z.any().optional(),\n \n // Comparison (numeric/date)\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n // Set & Range\n $in: z.array(z.any()).optional(),\n $nin: z.array(z.any()).optional(),\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n \n // String-specific\n $contains: z.string().optional(),\n $notContains: z.string().optional(),\n $startsWith: z.string().optional(),\n $endsWith: z.string().optional(),\n \n // Special\n $null: z.boolean().optional(),\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// 3.4 Logical Operators & Recursive Filter Structure\n// ============================================================================\n\n/**\n * Recursive filter type that supports:\n * 1. Implicit equality: { field: value }\n * 2. Explicit operators: { field: { $op: value } }\n * 3. Logical combinations: { $and: [...], $or: [...], $not: {...} }\n * 4. Nested relations: { relation: { field: value } }\n */\nexport type FilterCondition = {\n [key: string]: \n | any // Implicit equality: key: value\n | z.infer // Explicit operators: key: { $op: value }\n | FilterCondition; // Nested relation: key: { nested: ... }\n} & {\n /** Logical AND - combines all conditions that must be true */\n $and?: FilterCondition[];\n \n /** Logical OR - at least one condition must be true */\n $or?: FilterCondition[];\n \n /** Logical NOT - negates the condition */\n $not?: FilterCondition;\n};\n\n/**\n * Zod schema for recursive filter validation.\n * Uses z.lazy() to handle recursive structure.\n */\nexport const FilterConditionSchema: z.ZodType = z.lazy(() =>\n z.record(z.string(), z.unknown()).and(\n z.object({\n $and: z.array(FilterConditionSchema).optional(),\n $or: z.array(FilterConditionSchema).optional(),\n $not: FilterConditionSchema.optional(),\n })\n )\n);\n\n// ============================================================================\n// Query Filter Wrapper\n// ============================================================================\n\n/**\n * Top-level query filter wrapper.\n * This is typically used as the \"where\" clause in a query.\n * \n * @example\n * ```typescript\n * const filter: QueryFilter = {\n * where: {\n * status: \"active\", // Implicit equality\n * age: { $gte: 18 }, // Explicit operator\n * $or: [ // Logical combination\n * { role: \"admin\" },\n * { email: { $contains: \"@company.com\" } }\n * ],\n * profile: { // Nested relation\n * verified: true\n * }\n * }\n * }\n * ```\n */\nexport const QueryFilterSchema = z.object({\n where: FilterConditionSchema.optional(),\n});\n\n// ============================================================================\n// TypeScript Type Exports\n// ============================================================================\n\n/**\n * Type-safe filter operators for use in TypeScript.\n * \n * @example\n * ```typescript\n * type UserFilter = Filter;\n * \n * const filter: UserFilter = {\n * age: { $gte: 18 },\n * email: { $contains: \"@example.com\" }\n * };\n * ```\n */\nexport type Filter = {\n [K in keyof T]?: \n | T[K] // Implicit equality\n | {\n $eq?: T[K];\n $ne?: T[K];\n $gt?: T[K] extends number | Date ? T[K] : never;\n $gte?: T[K] extends number | Date ? T[K] : never;\n $lt?: T[K] extends number | Date ? T[K] : never;\n $lte?: T[K] extends number | Date ? T[K] : never;\n $in?: T[K][];\n $nin?: T[K][];\n $between?: T[K] extends number | Date ? [T[K], T[K]] : never;\n $contains?: T[K] extends string ? string : never;\n $notContains?: T[K] extends string ? string : never;\n $startsWith?: T[K] extends string ? string : never;\n $endsWith?: T[K] extends string ? string : never;\n $null?: boolean;\n $exists?: boolean;\n }\n | (T[K] extends object ? Filter : never); // Nested relation\n} & {\n $and?: Filter[];\n $or?: Filter[];\n $not?: Filter;\n};\n\n/**\n * Scalar types supported by the filter system.\n */\nexport type Scalar = string | number | boolean | Date | null;\n\n// Export inferred types\nexport type FieldOperators = z.infer;\nexport type QueryFilter = z.infer;\n\n// ============================================================================\n// Normalization Utilities (Internal Representation)\n// ============================================================================\n\n/**\n * Normalized filter AST structure.\n * This is the internal representation after converting all syntactic sugar\n * to explicit operators.\n * \n * Stage 1: Normalization Pass\n * Input: { age: 18, role: \"admin\" }\n * Output: { $and: [{ age: { $eq: 18 } }, { role: { $eq: \"admin\" } }] }\n * \n * This simplifies adapter implementation by providing a consistent structure.\n */\nexport const NormalizedFilterSchema: z.ZodType = z.lazy(() => \n z.object({\n $and: z.array(\n z.union([\n // Field condition: { field: { $op: value } }\n z.record(z.string(), FieldOperatorsSchema),\n // Nested logical group\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $or: z.array(\n z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $not: z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ]).optional(),\n })\n);\n\nexport type NormalizedFilter = z.infer;\n\n// ============================================================================\n// AST Array Format Detection & Validation\n// ============================================================================\n\n/**\n * Set of valid AST comparison operators (case-insensitive).\n * Used by `isFilterAST()` to validate AST structure beyond `Array.isArray`.\n */\nexport const VALID_AST_OPERATORS = new Set([\n '=', '==', '!=', '<>', '>', '>=', '<', '<=',\n 'in', 'nin', 'not_in',\n 'contains', 'notcontains', 'not_contains', 'like',\n 'startswith', 'starts_with',\n 'endswith', 'ends_with',\n 'between',\n 'is_null', 'is_not_null',\n]);\n\n/**\n * Detect whether a value is a valid Filter AST array structure.\n *\n * A valid AST is one of:\n * - Comparison node: `[field: string, operator: string, value: unknown]` where operator is a known operator\n * - Logical node: `[\"and\" | \"or\", ...children]` where children are valid AST nodes\n * - Legacy flat array: `[[cond], [cond], ...]` where all elements are sub-arrays (each a valid AST node)\n *\n * This replaces the naïve `Array.isArray(filter)` check, preventing accidental\n * misidentification of arbitrary arrays as filter ASTs.\n *\n * @example\n * isFilterAST([\"status\", \"=\", \"active\"]) // true\n * isFilterAST([\"and\", [\"a\", \"=\", 1], [\"b\", \">\", 2]]) // true\n * isFilterAST([[\"a\", \"=\", 1], [\"b\", \"=\", 2]]) // true (legacy)\n * isFilterAST([1, 2, 3]) // false\n * isFilterAST(\"not an array\") // false\n * isFilterAST({ status: \"active\" }) // false\n */\nexport function isFilterAST(filter: unknown): boolean {\n if (!Array.isArray(filter) || filter.length === 0) return false;\n\n const first = filter[0];\n\n // Logical node: [\"and\", ...] or [\"or\", ...]\n if (typeof first === 'string') {\n const lower = first.toLowerCase();\n if (lower === 'and' || lower === 'or') {\n return filter.length >= 2 && filter.slice(1).every((child: unknown) => isFilterAST(child));\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof filter[1] === 'string') {\n return VALID_AST_OPERATORS.has(filter[1].toLowerCase());\n }\n }\n\n // Legacy flat array: [[cond], [cond], ...]\n if (filter.every((item: unknown) => isFilterAST(item))) {\n return filter.length > 0;\n }\n\n return false;\n}\n\n// ============================================================================\n// AST Array → FilterCondition Conversion\n// ============================================================================\n\n/**\n * Operator mapping from AST infix operators to FilterCondition `$`-prefixed operators.\n */\nconst AST_OPERATOR_MAP: Record = {\n '=': '$eq',\n '==': '$eq',\n '!=': '$ne',\n '<>': '$ne',\n '>': '$gt',\n '>=': '$gte',\n '<': '$lt',\n '<=': '$lte',\n 'in': '$in',\n 'nin': '$nin',\n 'not_in': '$nin',\n 'contains': '$contains',\n 'notcontains': '$notContains',\n 'not_contains': '$notContains',\n 'like': '$contains',\n 'startswith': '$startsWith',\n 'starts_with': '$startsWith',\n 'endswith': '$endsWith',\n 'ends_with': '$endsWith',\n 'between': '$between',\n 'is_null': '$null',\n 'is_not_null': '$null',\n};\n\n/**\n * Convert a single AST comparison node `[field, operator, value]` to a FilterCondition object.\n */\nfunction convertComparison(node: [string, string, unknown]): FilterCondition {\n const [field, operator, value] = node;\n const op = operator.toLowerCase();\n\n // Special case: equality shorthand\n if (op === '=' || op === '==') {\n return { [field]: value } as FilterCondition;\n }\n\n // Null check operators\n if (op === 'is_null') {\n return { [field]: { $null: true } } as FilterCondition;\n }\n if (op === 'is_not_null') {\n return { [field]: { $null: false } } as FilterCondition;\n }\n\n const mapped = AST_OPERATOR_MAP[op];\n if (mapped) {\n return { [field]: { [mapped]: value } } as FilterCondition;\n }\n\n // Fallback: use the operator as-is with $ prefix\n return { [field]: { [`$${op}`]: value } } as FilterCondition;\n}\n\n/**\n * Parse a filter from AST array format to FilterCondition object format.\n *\n * The AST array format is used by the ObjectUI client and the `FilterBuilder`:\n * - Comparison: `[field, operator, value]` → `{ field: value }` or `{ field: { $op: value } }`\n * - Logical AND: `[\"and\", cond1, cond2, ...]` → `{ $and: [...] }`\n * - Logical OR: `[\"or\", cond1, cond2, ...]` → `{ $or: [...] }`\n *\n * If the input is already a FilterCondition object (not an array), it is returned as-is.\n * If the input is `null` or `undefined`, it is returned as-is.\n *\n * @example\n * // Simple condition\n * parseFilterAST([\"status\", \"=\", \"active\"])\n * // → { status: \"active\" }\n *\n * @example\n * // Compound AND\n * parseFilterAST([\"and\", [\"priority\", \"=\", \"high\"], [\"status\", \"=\", \"active\"]])\n * // → { $and: [{ priority: \"high\" }, { status: \"active\" }] }\n *\n * @example\n * // Object passthrough\n * parseFilterAST({ status: \"active\" })\n * // → { status: \"active\" }\n */\nexport function parseFilterAST(filter: unknown): FilterCondition | undefined {\n if (filter == null) return undefined;\n if (!Array.isArray(filter)) return filter as FilterCondition;\n if (filter.length === 0) return undefined;\n\n const first = filter[0];\n\n // Logical node: [\"and\", cond1, cond2, ...] or [\"or\", cond1, cond2, ...]\n if (typeof first === 'string' && (first.toLowerCase() === 'and' || first.toLowerCase() === 'or')) {\n const logicOp = `$${first.toLowerCase()}` as '$and' | '$or';\n const children = filter.slice(1).map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { [logicOp]: children } as FilterCondition;\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof first === 'string') {\n return convertComparison(filter as [string, string, unknown]);\n }\n\n // Legacy flat array: [[field, op, val], [field, op, val], ...]\n // All elements are sub-arrays → treat as implicit AND\n if (filter.every((item: unknown) => Array.isArray(item))) {\n const children = filter.map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { $and: children } as FilterCondition;\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Constants & Metadata\n// ============================================================================\n\n/**\n * All supported operator keys.\n * Useful for validation and parsing.\n */\nexport const FILTER_OPERATORS = [\n // Equality\n '$eq', '$ne',\n // Comparison\n '$gt', '$gte', '$lt', '$lte',\n // Set & Range\n '$in', '$nin', '$between',\n // String\n '$contains', '$notContains', '$startsWith', '$endsWith',\n // Special\n '$null', '$exists',\n] as const;\n\n/**\n * Logical operator keys.\n */\nexport const LOGICAL_OPERATORS = ['$and', '$or', '$not'] as const;\n\n/**\n * All operator keys (field + logical).\n */\nexport const ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS] as const;\n\nexport type FilterOperatorKey = typeof FILTER_OPERATORS[number];\nexport type LogicalOperatorKey = typeof LOGICAL_OPERATORS[number];\nexport type OperatorKey = typeof ALL_OPERATORS[number];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\n\n/**\n * Sort Node\n * Represents \"Order By\".\n */\nexport const SortNodeSchema = z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc']).default('asc')\n});\n\n/**\n * Aggregation Function Enum\n * Standard aggregation functions for data analysis.\n * \n * Supported Functions:\n * - **count**: Count rows (SQL: COUNT(*) or COUNT(field))\n * - **sum**: Sum numeric values (SQL: SUM(field))\n * - **avg**: Average numeric values (SQL: AVG(field))\n * - **min**: Minimum value (SQL: MIN(field))\n * - **max**: Maximum value (SQL: MAX(field))\n * - **count_distinct**: Count unique values (SQL: COUNT(DISTINCT field))\n * - **array_agg**: Aggregate values into array (SQL: ARRAY_AGG(field))\n * - **string_agg**: Concatenate values (SQL: STRING_AGG(field, delimiter))\n * \n * Performance Considerations:\n * - COUNT(*) is typically faster than COUNT(field) as it doesn't check for nulls\n * - COUNT DISTINCT may require additional memory for tracking unique values\n * - Window aggregates (with OVER clause) can be more efficient than subqueries\n * - Large GROUP BY operations benefit from proper indexing on grouped fields\n * \n * @example\n * // SQL: SELECT region, SUM(amount) FROM sales GROUP BY region\n * {\n * object: 'sales',\n * fields: ['region'],\n * aggregations: [\n * { function: 'sum', field: 'amount', alias: 'total_sales' }\n * ],\n * groupBy: ['region']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT COUNT(Id) FROM Account\n * {\n * object: 'account',\n * aggregations: [\n * { function: 'count', alias: 'total_accounts' }\n * ]\n * }\n */\nexport const AggregationFunction = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'array_agg', 'string_agg'\n]);\n\n/**\n * Aggregation Node\n * Represents an aggregated field with function.\n * \n * Aggregations summarize data across groups of rows (GROUP BY).\n * Used with `groupBy` to create analytical queries.\n * \n * @example\n * // SQL: SELECT customer_id, COUNT(*), SUM(amount) FROM orders GROUP BY customer_id\n * {\n * object: 'order',\n * fields: ['customer_id'],\n * aggregations: [\n * { function: 'count', alias: 'order_count' },\n * { function: 'sum', field: 'amount', alias: 'total_amount' }\n * ],\n * groupBy: ['customer_id']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT LeadSource, COUNT(Id) FROM Lead GROUP BY LeadSource\n * {\n * object: 'lead',\n * fields: ['lead_source'],\n * aggregations: [\n * { function: 'count', alias: 'lead_count' }\n * ],\n * groupBy: ['lead_source']\n * }\n */\nexport const AggregationNodeSchema = z.object({\n function: AggregationFunction.describe('Aggregation function'),\n field: z.string().optional().describe('Field to aggregate (optional for COUNT(*))'),\n alias: z.string().describe('Result column alias'),\n distinct: z.boolean().optional().describe('Apply DISTINCT before aggregation'),\n filter: FilterConditionSchema.optional().describe('Filter/Condition to apply to the aggregation (FILTER WHERE clause)'),\n});\n\n/**\n * Join Type Enum\n * Standard SQL join types for combining tables.\n * \n * Join Types:\n * - **inner**: Returns only matching rows from both tables (SQL: INNER JOIN)\n * - **left**: Returns all rows from left table, matching rows from right (SQL: LEFT JOIN)\n * - **right**: Returns all rows from right table, matching rows from left (SQL: RIGHT JOIN)\n * - **full**: Returns all rows from both tables (SQL: FULL OUTER JOIN)\n * \n * @example\n * // SQL: SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * on: ['order.customer_id', '=', 'customer.id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL-style: Find all customers and their orders (if any)\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * on: ['customer.id', '=', 'order.customer_id']\n * }\n * ]\n * }\n */\nexport const JoinType = z.enum(['inner', 'left', 'right', 'full']);\n\n/**\n * Join Execution Strategy\n * Hints to the query engine on how to execute the join.\n * \n * Strategies:\n * - **auto**: Engine decides best strategy (Default).\n * - **database**: Push down join to the database (Requires same datasource).\n * - **hash**: Load both sets into memory and hash join (Cross-datasource, memory intensive).\n * - **loop**: Nested loop lookup (N+1 safe version). (Good for small right-side lookups).\n */\nexport const JoinStrategy = z.enum(['auto', 'database', 'hash', 'loop']);\n\n/**\n * Join Node\n * Represents table joins for combining data from multiple objects.\n * \n * Joins connect related data across multiple tables using ON conditions.\n * Supports both direct object joins and subquery joins.\n * \n * @example\n * // SQL: SELECT o.*, c.name FROM orders o INNER JOIN customers c ON o.customer_id = c.id\n * {\n * object: 'order',\n * fields: ['id', 'amount'],\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Multi-table join\n * // SELECT * FROM orders o\n * // INNER JOIN customers c ON o.customer_id = c.id\n * // LEFT JOIN shipments s ON o.id = s.order_id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * },\n * {\n * type: 'left',\n * object: 'shipment',\n * alias: 's',\n * on: ['order.id', '=', 's.order_id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT Name, (SELECT LastName FROM Contacts) FROM Account\n * {\n * object: 'account',\n * fields: ['name'],\n * joins: [\n * {\n * type: 'left',\n * object: 'contact',\n * on: ['account.id', '=', 'contact.account_id']\n * }\n * ]\n * }\n * \n * @example\n * // Subquery Join: Join with a filtered/aggregated dataset\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * alias: 'high_value_orders',\n * on: ['customer.id', '=', 'high_value_orders.customer_id'],\n * subquery: {\n * object: 'order',\n * fields: ['customer_id', 'total'],\n * filters: ['total', '>', 1000]\n * }\n * }\n * ]\n * }\n */\nexport const JoinNodeSchema: z.ZodType = z.lazy(() => \n z.object({\n type: JoinType.describe('Join type'),\n strategy: JoinStrategy.optional().describe('Execution strategy hint'),\n object: z.string().describe('Object/table to join'),\n alias: z.string().optional().describe('Table alias'),\n on: FilterConditionSchema.describe('Join condition'),\n subquery: z.lazy(() => QuerySchema).optional().describe('Subquery instead of object'),\n })\n);\n\n/**\n * Window Function Enum\n * Advanced analytical functions for row-based calculations.\n * \n * Window Functions:\n * - **row_number**: Sequential number within partition (SQL: ROW_NUMBER() OVER (...))\n * - **rank**: Rank with gaps for ties (SQL: RANK() OVER (...))\n * - **dense_rank**: Rank without gaps (SQL: DENSE_RANK() OVER (...))\n * - **percent_rank**: Relative rank as percentage (SQL: PERCENT_RANK() OVER (...))\n * - **lag**: Access previous row value (SQL: LAG(field) OVER (...))\n * - **lead**: Access next row value (SQL: LEAD(field) OVER (...))\n * - **first_value**: First value in window (SQL: FIRST_VALUE(field) OVER (...))\n * - **last_value**: Last value in window (SQL: LAST_VALUE(field) OVER (...))\n * - **sum/avg/count/min/max**: Aggregates over window (SQL: SUM(field) OVER (...))\n * \n * @example\n * // SQL: SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) as rank\n * // FROM orders\n * {\n * object: 'order',\n * fields: ['id', 'customer_id', 'amount'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'rank',\n * over: {\n * partitionBy: ['customer_id'],\n * orderBy: [{ field: 'amount', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Running total with SUM() OVER (...)\n * {\n * object: 'transaction',\n * fields: ['date', 'amount'],\n * windowFunctions: [\n * {\n * function: 'sum',\n * field: 'amount',\n * alias: 'running_total',\n * over: {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: 'UNBOUNDED PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunction = z.enum([\n 'row_number', 'rank', 'dense_rank', 'percent_rank',\n 'lag', 'lead', 'first_value', 'last_value',\n 'sum', 'avg', 'count', 'min', 'max'\n]);\n\n/**\n * Window Specification\n * Defines PARTITION BY and ORDER BY for window functions.\n * \n * Window specifications control how window functions compute values:\n * - **partitionBy**: Divide rows into groups (like GROUP BY but without collapsing rows)\n * - **orderBy**: Define order for ranking and offset functions\n * - **frame**: Specify which rows to include in aggregate calculations\n * \n * @example\n * // Partition by department, order by salary\n * {\n * partitionBy: ['department'],\n * orderBy: [{ field: 'salary', order: 'desc' }]\n * }\n * \n * @example\n * // Moving average with frame specification\n * {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: '6 PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n */\nexport const WindowSpecSchema = z.object({\n partitionBy: z.array(z.string()).optional().describe('PARTITION BY fields'),\n orderBy: z.array(SortNodeSchema).optional().describe('ORDER BY specification'),\n frame: z.object({\n type: z.enum(['rows', 'range']).optional(),\n start: z.string().optional().describe('Frame start (e.g., \"UNBOUNDED PRECEDING\", \"1 PRECEDING\")'),\n end: z.string().optional().describe('Frame end (e.g., \"CURRENT ROW\", \"1 FOLLOWING\")'),\n }).optional().describe('Window frame specification'),\n});\n\n/**\n * Window Function Node\n * Represents window function with OVER clause.\n * \n * Window functions perform calculations across a set of rows related to the current row,\n * without collapsing the result set (unlike GROUP BY aggregations).\n * \n * @example\n * // SQL: Top 3 products per category\n * // SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as rank\n * // FROM products\n * {\n * object: 'product',\n * fields: ['name', 'category', 'sales'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'category_rank',\n * over: {\n * partitionBy: ['category'],\n * orderBy: [{ field: 'sales', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Year-over-year comparison with LAG\n * {\n * object: 'monthly_sales',\n * fields: ['month', 'revenue'],\n * windowFunctions: [\n * {\n * function: 'lag',\n * field: 'revenue',\n * alias: 'prev_year_revenue',\n * over: {\n * orderBy: [{ field: 'month', order: 'asc' }]\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunctionNodeSchema = z.object({\n function: WindowFunction.describe('Window function name'),\n field: z.string().optional().describe('Field to operate on (for aggregate window functions)'),\n alias: z.string().describe('Result column alias'),\n over: WindowSpecSchema.describe('Window specification (OVER clause)'),\n});\n\n/**\n * Field Selection Node\n * Represents \"Select\" attributes, including joins.\n */\nexport const FieldNodeSchema: z.ZodType = z.lazy(() => \n z.union([\n z.string(), // Primitive field: \"name\"\n z.object({\n field: z.string(), // Relationship field: \"owner\"\n fields: z.array(FieldNodeSchema).optional(), // Nested select: [\"name\", \"email\"]\n alias: z.string().optional()\n })\n ])\n);\n\n/**\n * Full-Text Search Configuration\n * Defines full-text search parameters for text queries.\n * \n * Supports:\n * - Multi-field search\n * - Relevance scoring\n * - Fuzzy matching\n * - Language-specific analyzers\n * \n * @example\n * {\n * query: \"John Smith\",\n * fields: [\"name\", \"email\", \"description\"],\n * fuzzy: true,\n * boost: { \"name\": 2.0, \"email\": 1.5 }\n * }\n */\nexport const FullTextSearchSchema = z.object({\n query: z.string().describe('Search query text'),\n fields: z.array(z.string()).optional().describe('Fields to search in (if not specified, searches all text fields)'),\n fuzzy: z.boolean().optional().default(false).describe('Enable fuzzy matching (tolerates typos)'),\n operator: z.enum(['and', 'or']).optional().default('or').describe('Logical operator between terms'),\n boost: z.record(z.string(), z.number()).optional().describe('Field-specific relevance boosting (field name -> boost factor)'),\n minScore: z.number().optional().describe('Minimum relevance score threshold'),\n language: z.string().optional().describe('Language for text analysis (e.g., \"en\", \"zh\", \"es\")'),\n highlight: z.boolean().optional().default(false).describe('Enable search result highlighting'),\n});\n\nexport type FullTextSearch = z.infer;\n\n/**\n * Query AST Schema\n * The universal data retrieval contract defined in `ast-structure.mdx`.\n * \n * This schema represents ObjectQL - a universal query language that abstracts\n * SQL, NoSQL, and SaaS APIs into a single unified interface.\n * \n * Updates (v2):\n * - Aligned with modern ORM standards (Prisma/TypeORM)\n * - Added `cursor` based pagination support\n * - Renamed `top`/`skip` to `limit`/`offset`\n * - Unified filtering syntax with `FilterConditionSchema`\n * \n * Updates (v3):\n * - Added `search` parameter for full-text search (P2 requirement)\n * \n * @example\n * // Simple query: SELECT name, email FROM account WHERE status = 'active'\n * {\n * object: 'account',\n * fields: ['name', 'email'],\n * where: { status: 'active' }\n * }\n * \n * @example\n * // Pagination with Limit/Offset\n * {\n * object: 'post',\n * where: { published: true },\n * orderBy: [{ field: 'created_at', order: 'desc' }],\n * limit: 20,\n * offset: 40\n * }\n * \n * @example\n * // Full-text search\n * {\n * object: 'article',\n * search: {\n * query: \"machine learning\",\n * fields: [\"title\", \"content\"],\n * fuzzy: true,\n * boost: { \"title\": 2.0 }\n * },\n * limit: 10\n * }\n */\nconst BaseQuerySchema = z.object({\n /** Target Entity */\n object: z.string().describe('Object name (e.g. account)'),\n \n /** Select Clause */\n fields: z.array(FieldNodeSchema).optional().describe('Fields to retrieve'),\n \n /** Where Clause (Filtering) */\n where: FilterConditionSchema.optional().describe('Filtering criteria (WHERE)'),\n \n /** Full-Text Search */\n search: FullTextSearchSchema.optional().describe('Full-text search configuration ($search parameter)'),\n \n /** Order By Clause (Sorting) */\n orderBy: z.array(SortNodeSchema).optional().describe('Sorting instructions (ORDER BY)'),\n \n /** Pagination */\n limit: z.number().optional().describe('Max records to return (LIMIT)'),\n offset: z.number().optional().describe('Records to skip (OFFSET)'),\n top: z.number().optional().describe('Alias for limit (OData compatibility)'),\n cursor: z.record(z.string(), z.unknown()).optional().describe('Cursor for keyset pagination'),\n \n /** Joins */\n joins: z.array(JoinNodeSchema).optional().describe('Explicit Table Joins'),\n \n /** Aggregations */\n aggregations: z.array(AggregationNodeSchema).optional().describe('Aggregation functions'),\n \n /** Group By Clause */\n groupBy: z.array(z.string()).optional().describe('GROUP BY fields'),\n \n /** Having Clause */\n having: FilterConditionSchema.optional().describe('HAVING clause for aggregation filtering'),\n \n /** Window Functions */\n windowFunctions: z.array(WindowFunctionNodeSchema).optional().describe('Window functions with OVER clause'),\n \n /** Subquery flag */\n distinct: z.boolean().optional().describe('SELECT DISTINCT flag'),\n});\n\n/**\n * QueryAST — Abstract Syntax Tree for data queries.\n *\n * The `expand` property enables recursive loading of related records through\n * lookup and master_detail fields. Each key is a relationship field name; the\n * value is a nested QueryAST that can further filter, select, sort, and expand\n * the related records (up to a default max depth of 3).\n *\n * @example\n * ```ts\n * const ast: QueryAST = {\n * object: 'task',\n * fields: ['title', 'assignee'],\n * expand: {\n * assignee: { object: 'user', fields: ['name', 'email'] },\n * project: {\n * object: 'project',\n * expand: { org: { object: 'org' } } // nested expand\n * }\n * }\n * };\n * ```\n */\nexport type QueryAST = z.infer & {\n expand?: Record;\n};\n\nexport type QueryInput = z.input & {\n expand?: Record;\n};\n\nexport const QuerySchema: z.ZodType = BaseQuerySchema.extend({\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional().describe(\n 'Recursive relation loading map. Keys are lookup/master_detail field names; '\n + 'values are nested QueryAST objects that control select, filter, sort, and '\n + 'further expansion on the related object. The engine resolves expand via '\n + 'batch $in queries (driver-agnostic) with a default max depth of 3.'\n ),\n});\n\nexport type SortNode = z.infer;\nexport type AggregationNode = z.infer;\nexport type JoinNode = z.infer;\nexport type WindowFunctionNode = z.infer;\nexport type WindowSpec = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { QuerySchema } from '../data/query.zod';\n\n// ==========================================\n// 1. Base Envelopes\n// ==========================================\n\nexport const ApiErrorSchema = z.object({\n code: z.string().describe('Error code (e.g. validation_error)'),\n message: z.string().describe('Readable error message'),\n category: z.string().optional().describe('Error category (e.g. validation, authorization)'),\n details: z.unknown().optional().describe('Additional error context (e.g. field validation errors)'),\n requestId: z.string().optional().describe('Request ID for tracking'),\n});\n\nexport const BaseResponseSchema = z.object({\n success: z.boolean().describe('Operation success status'),\n error: ApiErrorSchema.optional().describe('Error details if success is false'),\n meta: z.object({\n timestamp: z.string(),\n duration: z.number().optional(),\n requestId: z.string().optional(),\n traceId: z.string().optional(),\n }).optional().describe('Response metadata'),\n});\n\n// ==========================================\n// 2. Request Payloads (Inputs)\n// ==========================================\n\nexport const RecordDataSchema = z.record(z.string(), z.unknown()).describe('Key-value map of record data');\n\n/**\n * Standard Create Request\n */\nexport const CreateRequestSchema = z.object({\n data: RecordDataSchema.describe('Record data to insert'),\n});\n\n/**\n * Standard Update Request\n */\nexport const UpdateRequestSchema = z.object({\n data: RecordDataSchema.describe('Partial record data to update'),\n});\n\n/**\n * Standard Bulk Request\n */\nexport const BulkRequestSchema = z.object({\n records: z.array(RecordDataSchema).describe('Array of records to process'),\n allOrNone: z.boolean().default(true).describe('If true, rollback entire transaction on any failure'),\n});\n\n/**\n * Export Request\n */\nexport const ExportRequestSchema = z.intersection(\n QuerySchema,\n z.object({\n format: z.enum(['csv', 'json', 'xlsx']).default('csv'),\n })\n);\n\n// ==========================================\n// 3. Response Payloads (Outputs)\n// ==========================================\n\n/**\n * Single Record Response (Get/Create/Update)\n */\nexport const SingleRecordResponseSchema = BaseResponseSchema.extend({\n data: RecordDataSchema.describe('The requested or modified record'),\n});\n\n/**\n * List/Query Response\n */\nexport const ListRecordResponseSchema = BaseResponseSchema.extend({\n data: z.array(RecordDataSchema).describe('Array of matching records'),\n pagination: z.object({\n total: z.number().optional().describe('Total matching records count'),\n limit: z.number().optional().describe('Page size'),\n offset: z.number().optional().describe('Page offset'),\n cursor: z.string().optional().describe('Cursor for next page'),\n nextCursor: z.string().optional().describe('Next cursor for pagination'),\n hasMore: z.boolean().describe('Are there more pages?'),\n }).describe('Pagination info'),\n});\n\n/**\n * ID Request (Get/Delete)\n */\nexport const IdRequestSchema = z.object({\n id: z.string().describe('Record ID'),\n});\n\n/**\n * Modification Result (for Batch/Bulk operations)\n */\nexport const ModificationResultSchema = z.object({\n id: z.string().optional().describe('Record ID if processed'),\n success: z.boolean(),\n errors: z.array(ApiErrorSchema).optional(),\n index: z.number().optional().describe('Index in original request'),\n data: z.unknown().optional().describe('Result data (e.g. created record)'),\n});\n\n/**\n * Bulk Operation Response\n */\nexport const BulkResponseSchema = BaseResponseSchema.extend({\n data: z.array(ModificationResultSchema).describe('Results for each item in the batch'),\n});\n\n/**\n * Delete Response\n */\nexport const DeleteResponseSchema = BaseResponseSchema.extend({\n id: z.string().describe('ID of the deleted record'),\n});\n\n// ==========================================\n// 4. API Contract Registry\n// ==========================================\n\n/**\n * Standard API Contracts map\n * Used for generating SDKs and Documentation\n */\nexport const StandardApiContracts = {\n create: {\n input: CreateRequestSchema,\n output: SingleRecordResponseSchema\n },\n delete: {\n input: IdRequestSchema,\n output: DeleteResponseSchema\n },\n get: {\n input: IdRequestSchema,\n output: SingleRecordResponseSchema\n },\n update: {\n input: UpdateRequestSchema,\n output: SingleRecordResponseSchema\n },\n list: {\n input: QuerySchema,\n output: ListRecordResponseSchema\n },\n bulkCreate: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkUpdate: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkUpsert: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkDelete: {\n input: z.object({ ids: z.array(z.string()) }),\n output: BulkResponseSchema\n }\n};\n\n// ==========================================\n// 5. DataLoader / N+1 Query Prevention\n// ==========================================\n\n/**\n * DataLoader Configuration Schema\n * Batch loading configuration to prevent N+1 query problems\n */\nexport const DataLoaderConfigSchema = z.object({\n maxBatchSize: z.number().int().default(100).describe('Maximum number of keys per batch load'),\n batchScheduleFn: z.enum(['microtask', 'timeout', 'manual']).default('microtask')\n .describe('Scheduling strategy for collecting batch keys'),\n cacheEnabled: z.boolean().default(true).describe('Enable per-request result caching'),\n cacheKeyFn: z.string().optional().describe('Name or identifier of the cache key function'),\n cacheTtl: z.number().min(0).optional().describe('Cache time-to-live in seconds (0 = no expiration)'),\n coalesceRequests: z.boolean().default(true).describe('Deduplicate identical requests within a batch window'),\n maxConcurrency: z.number().int().optional().describe('Maximum parallel batch requests'),\n});\n\n/**\n * Batch Loading Strategy Schema\n * Defines how batched data loading is orchestrated\n */\nexport const BatchLoadingStrategySchema = z.object({\n strategy: z.enum(['dataloader', 'windowed', 'prefetch']).describe('Batch loading strategy type'),\n windowMs: z.number().optional().describe('Collection window duration in milliseconds (for windowed strategy)'),\n prefetchDepth: z.number().int().optional().describe('Depth of relation prefetching (for prefetch strategy)'),\n associationLoading: z.enum(['lazy', 'eager', 'batch']).default('batch')\n .describe('How to load related associations'),\n});\n\n/**\n * Query Optimization Configuration Schema\n * Top-level configuration for N+1 prevention and query optimization\n */\nexport const QueryOptimizationConfigSchema = z.object({\n preventNPlusOne: z.boolean().describe('Enable N+1 query detection and prevention'),\n dataLoader: DataLoaderConfigSchema.optional().describe('DataLoader batch loading configuration'),\n batchStrategy: BatchLoadingStrategySchema.optional().describe('Batch loading strategy configuration'),\n maxQueryDepth: z.number().int().describe('Maximum depth for nested relation queries'),\n queryComplexityLimit: z.number().optional().describe('Maximum allowed query complexity score'),\n enableQueryPlan: z.boolean().default(false).describe('Log query execution plans for debugging'),\n});\n\nexport type ApiError = z.infer;\nexport type BaseResponse = z.infer;\nexport type RecordData = z.infer;\nexport type CreateRequest = z.infer;\nexport type UpdateRequest = z.infer;\nexport type BulkRequest = z.infer;\nexport type ExportRequest = z.infer;\nexport type SingleRecordResponse = z.infer;\nexport type ListRecordResponse = z.infer;\nexport type IdRequest = z.infer;\nexport type ModificationResult = z.infer;\nexport type BulkResponse = z.infer;\nexport type DeleteResponse = z.infer;\nexport type DataLoaderConfig = z.infer;\nexport type BatchLoadingStrategy = z.infer;\nexport type QueryOptimizationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, RateLimitConfigSchema } from '../shared/http.zod';\n\n/**\n * API Mapping Schema\n * Transform input/output data.\n */\nexport const ApiMappingSchema = z.object({\n source: z.string().describe('Source field/path'),\n target: z.string().describe('Target field/path'),\n transform: z.string().optional().describe('Transformation function name'),\n});\n\n/**\n * API Endpoint Schema\n * Defines an external facing API contract.\n */\nexport const ApiEndpointSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique endpoint ID'),\n path: z.string().regex(/^\\//).describe('URL Path (e.g. /api/v1/customers)'),\n method: HttpMethod.describe('HTTP Method'),\n \n /** Documentation */\n summary: z.string().optional(),\n description: z.string().optional(),\n \n /** Execution Logic */\n type: z.enum(['flow', 'script', 'object_operation', 'proxy']).describe('Implementation type'),\n target: z.string().describe('Target Flow ID, Script Name, or Proxy URL'),\n \n /** Logic Config */\n objectParams: z.object({\n object: z.string().optional(),\n operation: z.enum(['find', 'get', 'create', 'update', 'delete']).optional(),\n }).optional().describe('For object_operation type'),\n \n /** Data Transformation */\n inputMapping: z.array(ApiMappingSchema).optional().describe('Map Request Body to Internal Params'),\n outputMapping: z.array(ApiMappingSchema).optional().describe('Map Internal Result to Response Body'),\n \n /** Policies */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n rateLimit: RateLimitConfigSchema.optional().describe('Rate limiting policy'),\n cacheTtl: z.number().optional().describe('Response cache TTL in seconds'),\n});\n\nexport const ApiEndpoint = Object.assign(ApiEndpointSchema, {\n create: >(config: T) => config,\n});\n\nexport type ApiEndpoint = z.infer;\nexport type ApiEndpointInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\n\n/**\n * Service Status Enum\n * Describes the operational state of a service in the discovery response.\n *\n * - `available` – Fully operational: service is registered AND HTTP handler is verified.\n * - `registered` – Route is declared in the dispatcher table but the HTTP handler has\n * not been verified (may 501 at runtime).\n * - `unavailable` – Service is not installed / not registered in the kernel.\n * - `degraded` – Partially working (e.g., in-memory fallback, missing persistence).\n * - `stub` – Placeholder handler that always returns 501 Not Implemented.\n */\nexport const ServiceStatus = z.enum([\n 'available',\n 'registered',\n 'unavailable',\n 'degraded',\n 'stub',\n]).describe(\n 'available = fully operational, registered = route declared but handler unverified, '\n + 'unavailable = not installed, degraded = partial, stub = placeholder that returns 501'\n);\n\nexport type ServiceStatus = z.infer;\n\n/**\n * Service Status in Discovery Response\n * Reports per-service availability so clients can adapt their UI accordingly.\n */\nexport const ServiceInfoSchema = z.object({\n /** Whether the service is enabled and available */\n enabled: z.boolean(),\n /** Current operational status */\n status: ServiceStatus,\n /**\n * Whether the HTTP handler for this service is confirmed to be mounted.\n *\n * Semantics:\n * - `undefined` (omitted) = handler readiness is unknown / not yet verified.\n * - `true` = handler is registered in the adapter / dispatcher (safe to call).\n * - `false` = route is declared but no handler exists or only a stub is present\n * — requests are expected to receive 501 Not Implemented.\n *\n * Clients SHOULD check this flag before displaying or invoking a service endpoint and may\n * distinguish between \"unknown\" (omitted) and \"known missing\" (`false`).\n */\n handlerReady: z.boolean().optional().describe(\n 'Whether the HTTP handler is confirmed to be mounted. '\n + 'Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501).'\n ),\n /** Route path (only present if enabled) */\n route: z.string().optional().describe('e.g. /api/v1/analytics'),\n /** Implementation provider name */\n provider: z.string().optional().describe('e.g. \"objectql\", \"plugin-redis\", \"driver-memory\"'),\n /** Service version */\n version: z.string().optional().describe('Semantic version of the service implementation (e.g. \"3.0.6\")'),\n /** Human-readable reason if unavailable */\n message: z.string().optional().describe('e.g. \"Install plugin-workflow to enable\"'),\n /** Rate limit configuration for this service */\n rateLimit: z.object({\n requestsPerMinute: z.number().int().optional().describe('Maximum requests per minute'),\n requestsPerHour: z.number().int().optional().describe('Maximum requests per hour'),\n burstLimit: z.number().int().optional().describe('Maximum burst request count'),\n retryAfterMs: z.number().int().optional().describe('Suggested retry-after delay in milliseconds when rate-limited'),\n }).optional().describe('Rate limit and quota info for this service'),\n});\n\n/**\n * API Routes Schema\n * The \"Map\" for the frontend to know where to send requests.\n * This decouples the frontend from hardcoded URL paths.\n */\nexport const ApiRoutesSchema = z.object({\n /** Base URL for Object CRUD (Data Protocol) */\n data: z.string().describe('e.g. /api/v1/data'),\n \n /** Base URL for Schema Definitions (Metadata Protocol) */\n metadata: z.string().describe('e.g. /api/v1/meta'),\n\n /** Base URL for API Discovery endpoint */\n discovery: z.string().optional().describe('e.g. /api/v1/discovery'),\n\n /** Base URL for UI Configurations (Views, Menus) */\n ui: z.string().optional().describe('e.g. /api/v1/ui'),\n \n /** Base URL for Authentication (plugin-provided) */\n auth: z.string().optional().describe('e.g. /api/v1/auth'),\n \n /** Base URL for Automation (Flows/Scripts) */\n automation: z.string().optional().describe('e.g. /api/v1/automation'),\n \n /** Base URL for File/Storage operations */\n storage: z.string().optional().describe('e.g. /api/v1/storage'),\n \n /** Base URL for Analytics/BI operations */\n analytics: z.string().optional().describe('e.g. /api/v1/analytics'),\n \n /** GraphQL Endpoint (if enabled) */\n graphql: z.string().optional().describe('e.g. /graphql'),\n\n /** Base URL for Package Management */\n packages: z.string().optional().describe('e.g. /api/v1/packages'),\n\n /** Base URL for Workflow Engine */\n workflow: z.string().optional().describe('e.g. /api/v1/workflow'),\n\n /** Base URL for Realtime (WebSocket/SSE) */\n realtime: z.string().optional().describe('e.g. /api/v1/realtime'),\n\n /** Base URL for Notification Service */\n notifications: z.string().optional().describe('e.g. /api/v1/notifications'),\n\n /** Base URL for AI Engine (NLQ, Chat, Suggest) */\n ai: z.string().optional().describe('e.g. /api/v1/ai'),\n\n /** Base URL for Internationalization */\n i18n: z.string().optional().describe('e.g. /api/v1/i18n'),\n\n /** Base URL for Feed / Chatter API */\n feed: z.string().optional().describe('e.g. /api/v1/feed'),\n});\n\n/**\n * Discovery Response Schema\n * The root object returned by the Metadata Discovery Endpoint.\n * \n * Design rationale:\n * - `services` is the single source of truth for service availability.\n * Each service entry includes `enabled`, `status`, `route`, and `provider`.\n * - `routes` is a convenience shortcut: a flat map of service-name → route-path\n * so that clients can resolve endpoints without iterating the services map.\n * - `capabilities`/`features` was removed because it was fully derivable\n * from `services[x].enabled`. Use `services` to determine feature availability.\n */\nexport const DiscoverySchema = z.object({\n /** System Identity */\n name: z.string(),\n version: z.string(),\n environment: z.enum(['production', 'sandbox', 'development']),\n \n /** Dynamic Routing — convenience shortcut for client routing */\n routes: ApiRoutesSchema,\n \n /** Localization Info (helping frontend init i18n) */\n locale: z.object({\n default: z.string(),\n supported: z.array(z.string()),\n timezone: z.string(),\n }),\n \n /**\n * Per-service status map.\n * This is the **single source of truth** for service availability.\n * Clients use this to determine which features are available,\n * show/hide UI elements, and display appropriate messages.\n */\n services: z.record(z.string(), ServiceInfoSchema).describe(\n 'Per-service availability map keyed by CoreServiceName'\n ),\n\n /**\n * Hierarchical capability descriptors.\n * Declares platform features so clients can adapt UI without probing individual services.\n * Each key is a capability domain (e.g., \"comments\", \"automation\", \"search\"),\n * and its value describes what sub-features are available.\n */\n capabilities: z.record(z.string(), z.object({\n enabled: z.boolean().describe('Whether this capability is available'),\n features: z.record(z.string(), z.boolean()).optional()\n .describe('Sub-feature flags within this capability'),\n description: z.string().optional()\n .describe('Human-readable capability description'),\n })).optional().describe('Hierarchical capability descriptors for frontend intelligent adaptation'),\n\n /**\n * Schema discovery URLs for cross-ecosystem interoperability.\n */\n schemaDiscovery: z.object({\n openapi: z.string().optional().describe('URL to OpenAPI (Swagger) specification (e.g., \"/api/v1/openapi.json\")'),\n graphql: z.string().optional().describe('URL to GraphQL schema endpoint (e.g., \"/graphql\")'),\n jsonSchema: z.string().optional().describe('URL to JSON Schema definitions'),\n }).optional().describe('Schema discovery endpoints for API toolchain integration'),\n\n /**\n * Custom metadata key-value pairs for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n});\n\n/**\n * Well-Known Capabilities Schema\n * Flat boolean flags for quick feature detection by clients (ObjectUI).\n * Each flag indicates whether the backend supports a specific capability.\n * Clients can use these to show/hide UI elements without probing individual endpoints.\n */\nexport const WellKnownCapabilitiesSchema = z.object({\n /** Whether the backend supports Feed / Chatter API */\n feed: z.boolean().describe('Whether the backend supports Feed / Chatter API'),\n /** Whether the backend supports comments (a subset of Feed) */\n comments: z.boolean().describe('Whether the backend supports comments (a subset of Feed)'),\n /** Whether the backend supports Automation CRUD (flows, triggers) */\n automation: z.boolean().describe('Whether the backend supports Automation CRUD (flows, triggers)'),\n /** Whether the backend supports cron scheduling */\n cron: z.boolean().describe('Whether the backend supports cron scheduling'),\n /** Whether the backend supports full-text search */\n search: z.boolean().describe('Whether the backend supports full-text search'),\n /** Whether the backend supports async export */\n export: z.boolean().describe('Whether the backend supports async export'),\n /** Whether the backend supports chunked (multipart) uploads */\n chunkedUpload: z.boolean().describe('Whether the backend supports chunked (multipart) uploads'),\n}).describe('Well-known capability flags for frontend intelligent adaptation');\n\nexport type WellKnownCapabilities = z.infer;\nexport type DiscoveryResponse = z.infer;\nexport type ApiRoutes = z.infer;\nexport type ServiceInfo = z.infer;\n\n// ============================================================================\n// Route Health Report\n// ============================================================================\n\n/**\n * Single route health entry for the coverage report.\n */\nexport const RouteHealthEntrySchema = z.object({\n /** Route path (e.g. /api/v1/analytics) */\n route: z.string().describe('Route path pattern'),\n /** HTTP method */\n method: HttpMethod.describe('HTTP method (GET, POST, etc.)'),\n /** Target service name */\n service: z.string().describe('Target service name'),\n /** Whether the route is declared in discovery */\n declared: z.boolean().describe('Whether the route is declared in discovery/metadata'),\n /** Whether the handler is actually registered in the adapter/dispatcher */\n handlerRegistered: z.boolean().describe('Whether the HTTP handler is registered'),\n /**\n * Health check result:\n * - `pass` – Handler exists and responds (2xx/4xx — i.e., not 404/501/503)\n * - `fail` – Handler returned 501 or 503\n * - `missing` – No handler registered (404)\n * - `skip` – Health check was not performed\n */\n healthStatus: z.enum(['pass', 'fail', 'missing', 'skip']).describe(\n 'pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked'\n ),\n /** Optional diagnostic message */\n message: z.string().optional().describe('Diagnostic message'),\n});\n\nexport type RouteHealthEntry = z.infer;\n\n/**\n * Route Health Report Schema\n * Aggregated route coverage report produced at startup or on demand.\n *\n * This report enables automated detection of routes that are declared\n * in discovery metadata but have no corresponding HTTP handler.\n */\nexport const RouteHealthReportSchema = z.object({\n /** ISO 8601 timestamp of when the report was generated */\n timestamp: z.string().describe('ISO 8601 timestamp of report generation'),\n /** Adapter name that generated the report (e.g. \"hono\", \"express\", \"nextjs\") */\n adapter: z.string().describe('Adapter or runtime that produced this report'),\n /** Total routes declared in discovery / dispatcher table */\n totalDeclared: z.number().int().describe('Total routes declared in discovery'),\n /** Routes with a confirmed handler registration */\n totalRegistered: z.number().int().describe('Routes with confirmed handler'),\n /** Routes missing a handler */\n totalMissing: z.number().int().describe('Routes missing a handler'),\n /** Per-route health entries */\n routes: z.array(RouteHealthEntrySchema).describe('Per-route health entries'),\n});\n\nexport type RouteHealthReport = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metadata Event Types\n *\n * Triggered when metadata items are created, updated, or deleted.\n * Follows the pattern: `metadata.{type}.{action}`\n *\n * Examples:\n * - `metadata.object.created` - A new object was created\n * - `metadata.view.updated` - A view was updated\n * - `metadata.agent.deleted` - An agent was deleted\n */\nexport const MetadataEventType = z.enum([\n 'metadata.object.created',\n 'metadata.object.updated',\n 'metadata.object.deleted',\n 'metadata.field.created',\n 'metadata.field.updated',\n 'metadata.field.deleted',\n 'metadata.view.created',\n 'metadata.view.updated',\n 'metadata.view.deleted',\n 'metadata.app.created',\n 'metadata.app.updated',\n 'metadata.app.deleted',\n 'metadata.agent.created',\n 'metadata.agent.updated',\n 'metadata.agent.deleted',\n 'metadata.tool.created',\n 'metadata.tool.updated',\n 'metadata.tool.deleted',\n 'metadata.flow.created',\n 'metadata.flow.updated',\n 'metadata.flow.deleted',\n 'metadata.action.created',\n 'metadata.action.updated',\n 'metadata.action.deleted',\n 'metadata.workflow.created',\n 'metadata.workflow.updated',\n 'metadata.workflow.deleted',\n 'metadata.dashboard.created',\n 'metadata.dashboard.updated',\n 'metadata.dashboard.deleted',\n 'metadata.report.created',\n 'metadata.report.updated',\n 'metadata.report.deleted',\n 'metadata.role.created',\n 'metadata.role.updated',\n 'metadata.role.deleted',\n 'metadata.permission.created',\n 'metadata.permission.updated',\n 'metadata.permission.deleted',\n]);\n\nexport type MetadataEventType = z.infer;\n\n/**\n * Data Event Types\n *\n * Triggered when data records are created, updated, or deleted.\n * Follows the pattern: `data.record.{action}`\n */\nexport const DataEventType = z.enum([\n 'data.record.created',\n 'data.record.updated',\n 'data.record.deleted',\n 'data.field.changed',\n]);\n\nexport type DataEventType = z.infer;\n\n/**\n * Metadata Event Payload\n *\n * Represents a metadata change event (create, update, delete).\n * Used for real-time synchronization of metadata across clients.\n */\nexport const MetadataEventSchema = z.object({\n /** Unique event identifier */\n id: z.string().uuid().describe('Unique event identifier'),\n\n /** Event type (metadata.{type}.{action}) */\n type: MetadataEventType.describe('Event type'),\n\n /** Metadata type (object, view, agent, tool, etc.) */\n metadataType: z.string().describe('Metadata type (object, view, agent, etc.)'),\n\n /** Metadata item name */\n name: z.string().describe('Metadata item name'),\n\n /** Package ID (if applicable) */\n packageId: z.string().optional().describe('Package ID'),\n\n /** Full definition (only for create/update events) */\n definition: z.unknown().optional().describe('Full definition (create/update only)'),\n\n /** User who triggered the event */\n userId: z.string().optional().describe('User who triggered the event'),\n\n /** Event timestamp (ISO 8601) */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\nexport type MetadataEvent = z.infer;\n\n/**\n * Data Event Payload\n *\n * Represents a data record change event (create, update, delete).\n * Used for real-time synchronization of data records across clients.\n */\nexport const DataEventSchema = z.object({\n /** Unique event identifier */\n id: z.string().uuid().describe('Unique event identifier'),\n\n /** Event type (data.record.{action}) */\n type: DataEventType.describe('Event type'),\n\n /** Object name */\n object: z.string().describe('Object name'),\n\n /** Record ID */\n recordId: z.string().describe('Record ID'),\n\n /** Changed fields (update events only) */\n changes: z.record(z.string(), z.unknown()).optional().describe('Changed fields'),\n\n /** Record before update (update events only) */\n before: z.record(z.string(), z.unknown()).optional().describe('Before state'),\n\n /** Record after update (create/update events) */\n after: z.record(z.string(), z.unknown()).optional().describe('After state'),\n\n /** User who triggered the event */\n userId: z.string().optional().describe('User who triggered the event'),\n\n /** Event timestamp (ISO 8601) */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\nexport type DataEvent = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Realtime Shared Protocol\n * \n * Shared schemas and types for real-time communication protocols.\n * This module consolidates overlapping definitions between the transport-level\n * realtime protocol (SSE/Polling/WebSocket) and the WebSocket collaboration protocol.\n * \n * **Architecture:**\n * - `realtime-shared.zod.ts` — Shared base schemas (Presence, Event types)\n * - `realtime.zod.ts` — Transport-layer protocol (Channel, Subscription, Transport selection)\n * - `websocket.zod.ts` — Collaboration protocol (Cursor, OT editing, Advanced presence)\n * \n * @see realtime.zod.ts for transport-layer configuration\n * @see websocket.zod.ts for collaborative editing protocol\n */\n\n// ==========================================\n// Shared Presence Status\n// ==========================================\n\n/**\n * Presence Status Enum (Unified)\n * \n * Canonical user presence status shared across all realtime protocols.\n * Used by both transport-level presence tracking (realtime.zod.ts)\n * and WebSocket collaboration presence (websocket.zod.ts).\n * \n * @example\n * ```typescript\n * import { PresenceStatus } from './realtime-shared.zod';\n * const status = PresenceStatus.parse('online'); // ✅\n * ```\n */\nexport const PresenceStatus = z.enum([\n 'online', // User is actively connected\n 'away', // User is idle/inactive\n 'busy', // User is busy (do not disturb)\n 'offline', // User is disconnected\n]);\n\nexport type PresenceStatus = z.infer;\n\n// ==========================================\n// Shared Realtime Actions\n// ==========================================\n\n/**\n * Realtime Record Action Enum (Unified)\n * \n * Canonical action types for real-time record change events.\n * Shared between transport-level events and WebSocket event messages.\n */\nexport const RealtimeRecordAction = z.enum([\n 'created',\n 'updated',\n 'deleted',\n]);\n\nexport type RealtimeRecordAction = z.infer;\n\n// ==========================================\n// Shared Base Presence Schema\n// ==========================================\n\n/**\n * Base Presence Schema (Unified)\n * \n * Core presence fields shared across all realtime protocols.\n * Transport-level (realtime.zod.ts) and collaboration-level (websocket.zod.ts)\n * presence schemas extend this base with protocol-specific fields.\n * \n * @example\n * ```typescript\n * const presence = BasePresenceSchema.parse({\n * userId: 'user-123',\n * status: 'online',\n * lastSeen: '2024-01-15T10:30:00Z',\n * });\n * ```\n */\nexport const BasePresenceSchema = z.object({\n /** User identifier */\n userId: z.string().describe('User identifier'),\n\n /** Current presence status */\n status: PresenceStatus.describe('Current presence status'),\n\n /** Last activity timestamp */\n lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n\n /** Custom metadata */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom presence data (e.g., current page, custom status)'),\n});\n\nexport type BasePresence = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { RealtimeRecordAction, BasePresenceSchema } from './realtime-shared.zod';\n\n// Re-export shared types for backward compatibility\nexport { PresenceStatus, RealtimeRecordAction, BasePresenceSchema } from './realtime-shared.zod';\nexport type { BasePresence } from './realtime-shared.zod';\n\n/**\n * Transport Protocol Enum\n * Defines the communication protocol for realtime data synchronization\n */\nexport const TransportProtocol = z.enum([\n 'websocket', // Full-duplex, low latency communication\n 'sse', // Server-Sent Events, unidirectional push\n 'polling', // Short polling, best compatibility\n]);\n\nexport type TransportProtocol = z.infer;\n\n/**\n * Event Type Enum\n * Types of realtime events that can be subscribed to\n */\nexport const RealtimeEventType = z.enum([\n 'record.created',\n 'record.updated',\n 'record.deleted',\n 'field.changed',\n]);\n\nexport type RealtimeEventType = z.infer;\n\n/**\n * Subscription Event Configuration\n * Defines what events to subscribe to with optional filtering\n */\nexport const SubscriptionEventSchema = z.object({\n type: RealtimeEventType.describe('Type of event to subscribe to'),\n object: z.string().optional().describe('Object name to subscribe to'),\n filters: z.unknown().optional().describe('Filter conditions'),\n});\n\n/**\n * Subscription Schema\n * Configuration for subscribing to realtime events\n */\nexport const SubscriptionSchema = z.object({\n id: z.string().uuid().describe('Unique subscription identifier'),\n events: z.array(SubscriptionEventSchema).describe('Array of events to subscribe to'),\n transport: TransportProtocol.describe('Transport protocol to use'),\n channel: z.string().optional().describe('Optional channel name for grouping subscriptions'),\n});\n\nexport type Subscription = z.infer;\n\n/**\n * Presence Schema\n * Tracks user online status and metadata.\n * Extends the shared BasePresenceSchema for transport-level presence tracking.\n */\nexport const RealtimePresenceSchema = BasePresenceSchema;\n\nexport type RealtimePresence = z.infer;\n\n/**\n * Realtime Event Schema\n * Represents a realtime synchronization event\n */\nexport const RealtimeEventSchema = z.object({\n id: z.string().uuid().describe('Unique event identifier'),\n type: z.string().describe('Event type (e.g., record.created, record.updated)'),\n object: z.string().optional().describe('Object name the event relates to'),\n action: RealtimeRecordAction.optional().describe('Action performed'),\n payload: z.record(z.string(), z.unknown()).describe('Event payload data'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when event occurred'),\n userId: z.string().optional().describe('User who triggered the event'),\n sessionId: z.string().optional().describe('Session identifier'),\n});\n\nexport type RealtimeEvent = z.infer;\n\n/**\n * Realtime Configuration Schema\n * \n * Configuration for enabling realtime data synchronization.\n */\nexport const RealtimeConfigSchema = z.object({\n /** Enable realtime sync */\n enabled: z.boolean().default(true).describe('Enable realtime synchronization'),\n \n /** Transport protocol */\n transport: TransportProtocol.default('websocket').describe('Transport protocol'),\n \n /** Default subscriptions */\n subscriptions: z.array(SubscriptionSchema).optional().describe('Default subscriptions'),\n}).passthrough(); // Allow additional properties\n\nexport type RealtimeConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventNameSchema } from '../shared/identifiers.zod';\nimport { PresenceStatus } from './realtime-shared.zod';\n\n// Re-export shared PresenceStatus for backward compatibility\nexport { PresenceStatus } from './realtime-shared.zod';\n\n/**\n * WebSocket Event Protocol\n * \n * Defines the schema for WebSocket-based real-time communication in ObjectStack.\n * Supports event subscriptions, filtering, presence tracking, and collaborative editing.\n * \n * Industry alignment: Firebase Realtime Database, Socket.IO, Pusher\n */\n\n// ==========================================\n// Message Types\n// ==========================================\n\n/**\n * WebSocket Message Type Enum\n * Defines the types of messages that can be sent over WebSocket\n */\nexport const WebSocketMessageType = z.enum([\n 'subscribe', // Client subscribes to events\n 'unsubscribe', // Client unsubscribes from events\n 'event', // Server sends event to client\n 'ping', // Keepalive ping\n 'pong', // Keepalive pong response\n 'ack', // Acknowledgment of message receipt\n 'error', // Error message\n 'presence', // Presence update (user status)\n 'cursor', // Cursor position update (collaborative editing)\n 'edit', // Document edit operation (collaborative editing)\n]);\n\nexport type WebSocketMessageType = z.infer;\n\n// ==========================================\n// Event Subscription\n// ==========================================\n\n/**\n * Event Filter Operator Enum\n * SQL-like filter operators for event filtering\n */\nexport const FilterOperator = z.enum([\n 'eq', // Equal\n 'ne', // Not equal\n 'gt', // Greater than\n 'gte', // Greater than or equal\n 'lt', // Less than\n 'lte', // Less than or equal\n 'in', // In array\n 'nin', // Not in array\n 'contains', // String contains\n 'startsWith', // String starts with\n 'endsWith', // String ends with\n 'exists', // Field exists\n 'regex', // Regex match\n]);\n\nexport type FilterOperator = z.infer;\n\n/**\n * Event Filter Condition\n * Defines a single filter condition for event filtering\n */\nexport const EventFilterCondition = z.object({\n field: z.string().describe('Field path to filter on (supports dot notation, e.g., \"user.email\")'),\n operator: FilterOperator.describe('Comparison operator'),\n value: z.unknown().optional().describe('Value to compare against (not needed for \"exists\" operator)'),\n});\n\nexport type EventFilterCondition = z.infer;\n\n/**\n * Event Filter Schema\n * Logical combination of filter conditions\n */\nexport const EventFilterSchema: z.ZodType<{\n conditions?: EventFilterCondition[];\n and?: EventFilter[];\n or?: EventFilter[];\n not?: EventFilter;\n}> = z.object({\n conditions: z.array(EventFilterCondition).optional().describe('Array of filter conditions'),\n and: z.lazy(() => z.array(EventFilterSchema)).optional().describe('AND logical combination of filters'),\n or: z.lazy(() => z.array(EventFilterSchema)).optional().describe('OR logical combination of filters'),\n not: z.lazy(() => EventFilterSchema).optional().describe('NOT logical negation of filter'),\n});\n\nexport type EventFilter = z.infer;\n\n/**\n * Event Pattern Schema\n * Event name pattern that supports wildcards for subscriptions\n */\nexport const EventPatternSchema = z\n .string()\n .min(1)\n .regex(/^[a-z*][a-z0-9_.*]*$/, {\n message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., \"record.*\", \"*.created\", \"user.login\")',\n })\n .describe('Event pattern (supports wildcards like \"record.*\" or \"*.created\")');\n\nexport type EventPattern = z.infer;\n\n/**\n * Event Subscription Config\n * Configuration for subscribing to specific events\n */\nexport const EventSubscriptionSchema = z.object({\n subscriptionId: z.string().uuid().describe('Unique subscription identifier'),\n events: z.array(EventPatternSchema).describe('Event patterns to subscribe to (supports wildcards, e.g., \"record.*\", \"user.created\")'),\n objects: z.array(z.string()).optional().describe('Object names to filter events by (e.g., [\"account\", \"contact\"])'),\n filters: EventFilterSchema.optional().describe('Advanced filter conditions for event payloads'),\n channels: z.array(z.string()).optional().describe('Channel names for scoped subscriptions'),\n});\n\nexport type EventSubscription = z.infer;\n\n/**\n * Unsubscribe Request\n * Request to unsubscribe from events\n */\nexport const UnsubscribeRequestSchema = z.object({\n subscriptionId: z.string().uuid().describe('Subscription ID to unsubscribe from'),\n});\n\nexport type UnsubscribeRequest = z.infer;\n\n// ==========================================\n// Presence Tracking\n// ==========================================\n\n/**\n * Presence Status Enum\n * Re-exported from realtime-shared.zod.ts for backward compatibility\n */\nexport const WebSocketPresenceStatus = PresenceStatus;\n\nexport type WebSocketPresenceStatus = z.infer;\n\n/**\n * Presence State Schema\n * Tracks real-time user presence and activity\n */\nexport const PresenceStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Unique session identifier'),\n status: WebSocketPresenceStatus.describe('Current presence status'),\n lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n currentLocation: z.string().optional().describe('Current page/route user is viewing'),\n device: z.enum(['desktop', 'mobile', 'tablet', 'other']).optional().describe('Device type'),\n customStatus: z.string().optional().describe('Custom user status message'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional custom presence data'),\n});\n\nexport type PresenceState = z.infer;\n\n/**\n * Presence Update Request\n * Client request to update presence status\n */\nexport const PresenceUpdateSchema = z.object({\n status: WebSocketPresenceStatus.optional().describe('Updated presence status'),\n currentLocation: z.string().optional().describe('Updated current location'),\n customStatus: z.string().optional().describe('Updated custom status message'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type PresenceUpdate = z.infer;\n\n// ==========================================\n// Collaborative Editing Protocol\n// ==========================================\n\n/**\n * Cursor Position Schema\n * Represents a cursor position in a document\n */\nexport const CursorPositionSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier being edited'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Column number (0-indexed)'),\n }).optional().describe('Cursor position in document'),\n selection: z.object({\n start: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }),\n end: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }),\n }).optional().describe('Selection range (if text is selected)'),\n color: z.string().optional().describe('Cursor color for visual representation'),\n userName: z.string().optional().describe('Display name of user'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),\n});\n\nexport type CursorPosition = z.infer;\n\n/**\n * Edit Operation Type Enum\n * Types of edit operations for collaborative editing\n */\nexport const EditOperationType = z.enum([\n 'insert', // Insert text at position\n 'delete', // Delete text from range\n 'replace', // Replace text in range\n]);\n\nexport type EditOperationType = z.infer;\n\n/**\n * Edit Operation Schema\n * Represents a single edit operation on a document\n * Supports Operational Transformation (OT) for conflict resolution\n */\nexport const EditOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n documentId: z.string().describe('Document identifier'),\n userId: z.string().describe('User who performed the edit'),\n sessionId: z.string().uuid().describe('Session identifier'),\n type: EditOperationType.describe('Type of edit operation'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Column number (0-indexed)'),\n }).describe('Starting position of the operation'),\n endPosition: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }).optional().describe('Ending position (for delete/replace operations)'),\n content: z.string().optional().describe('Content to insert/replace'),\n version: z.number().int().nonnegative().describe('Document version before this operation'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),\n baseOperationId: z.string().uuid().optional().describe('Previous operation ID this builds upon (for OT)'),\n});\n\nexport type EditOperation = z.infer;\n\n/**\n * Document State Schema\n * Represents the current state of a collaborative document\n */\nexport const DocumentStateSchema = z.object({\n documentId: z.string().describe('Document identifier'),\n version: z.number().int().nonnegative().describe('Current document version'),\n content: z.string().describe('Current document content'),\n lastModified: z.string().datetime().describe('ISO 8601 datetime of last modification'),\n activeSessions: z.array(z.string().uuid()).describe('Active editing session IDs'),\n checksum: z.string().optional().describe('Content checksum for integrity verification'),\n});\n\nexport type DocumentState = z.infer;\n\n// ==========================================\n// WebSocket Messages\n// ==========================================\n\n/**\n * Base WebSocket Message\n * All WebSocket messages extend this base structure\n */\nconst BaseWebSocketMessage = z.object({\n messageId: z.string().uuid().describe('Unique message identifier'),\n type: WebSocketMessageType.describe('Message type'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when message was sent'),\n});\n\n/**\n * Subscribe Message\n * Client sends this to subscribe to events\n */\nexport const SubscribeMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('subscribe'),\n subscription: EventSubscriptionSchema.describe('Subscription configuration'),\n});\n\nexport type SubscribeMessage = z.infer;\n\n/**\n * Unsubscribe Message\n * Client sends this to unsubscribe from events\n */\nexport const UnsubscribeMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('unsubscribe'),\n request: UnsubscribeRequestSchema.describe('Unsubscribe request'),\n});\n\nexport type UnsubscribeMessage = z.infer;\n\n/**\n * Event Message\n * Server sends this when a subscribed event occurs\n */\nexport const EventMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('event'),\n subscriptionId: z.string().uuid().describe('Subscription ID this event belongs to'),\n eventName: EventNameSchema.describe('Event name'),\n object: z.string().optional().describe('Object name the event relates to'),\n payload: z.unknown().describe('Event payload data'),\n userId: z.string().optional().describe('User who triggered the event'),\n});\n\nexport type EventMessage = z.infer;\n\n/**\n * Presence Message\n * Presence update message\n */\nexport const PresenceMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('presence'),\n presence: PresenceStateSchema.describe('Presence state'),\n});\n\nexport type PresenceMessage = z.infer;\n\n/**\n * Cursor Message\n * Cursor position update for collaborative editing\n */\nexport const CursorMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('cursor'),\n cursor: CursorPositionSchema.describe('Cursor position'),\n});\n\nexport type CursorMessage = z.infer;\n\n/**\n * Edit Message\n * Document edit operation for collaborative editing\n */\nexport const EditMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('edit'),\n operation: EditOperationSchema.describe('Edit operation'),\n});\n\nexport type EditMessage = z.infer;\n\n/**\n * Acknowledgment Message\n * Server acknowledges receipt of a message\n */\nexport const AckMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('ack'),\n ackMessageId: z.string().uuid().describe('ID of the message being acknowledged'),\n success: z.boolean().describe('Whether the operation was successful'),\n error: z.string().optional().describe('Error message if operation failed'),\n});\n\nexport type AckMessage = z.infer;\n\n/**\n * Error Message\n * Server sends error information\n */\nexport const ErrorMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('error'),\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n details: z.unknown().optional().describe('Additional error details'),\n});\n\nexport type ErrorMessage = z.infer;\n\n/**\n * Ping Message\n * Keepalive ping from client or server\n */\nexport const PingMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('ping'),\n});\n\nexport type PingMessage = z.infer;\n\n/**\n * Pong Message\n * Keepalive pong response\n */\nexport const PongMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('pong'),\n pingMessageId: z.string().uuid().optional().describe('ID of ping message being responded to'),\n});\n\nexport type PongMessage = z.infer;\n\n/**\n * WebSocket Message Union\n * Discriminated union of all WebSocket message types\n */\nexport const WebSocketMessageSchema = z.discriminatedUnion('type', [\n SubscribeMessageSchema,\n UnsubscribeMessageSchema,\n EventMessageSchema,\n PresenceMessageSchema,\n CursorMessageSchema,\n EditMessageSchema,\n AckMessageSchema,\n ErrorMessageSchema,\n PingMessageSchema,\n PongMessageSchema,\n]);\n\nexport type WebSocketMessage = z.infer;\n\n// ==========================================\n// Connection Configuration\n// ==========================================\n\n/**\n * WebSocket Connection Config\n * Configuration for WebSocket connections\n */\nexport const WebSocketConfigSchema = z.object({\n url: z.string().url().describe('WebSocket server URL'),\n protocols: z.array(z.string()).optional().describe('WebSocket sub-protocols'),\n reconnect: z.boolean().optional().default(true).describe('Enable automatic reconnection'),\n reconnectInterval: z.number().int().positive().optional().default(1000).describe('Reconnection interval in milliseconds'),\n maxReconnectAttempts: z.number().int().positive().optional().default(5).describe('Maximum reconnection attempts'),\n pingInterval: z.number().int().positive().optional().default(30000).describe('Ping interval in milliseconds'),\n timeout: z.number().int().positive().optional().default(5000).describe('Message timeout in milliseconds'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for WebSocket handshake'),\n});\n\nexport type WebSocketConfig = z.infer;\n\n// ==========================================\n// Simplified Collaboration API\n// ==========================================\n\n/**\n * Simplified WebSocket Event Schema\n * \n * A simplified event schema for basic WebSocket communication.\n * Complements the comprehensive WebSocketMessageSchema above for simpler use cases.\n * \n * @example Subscribe to channel\n * ```typescript\n * {\n * type: 'subscribe',\n * channel: 'record.account.123',\n * payload: { events: ['created', 'updated'] },\n * timestamp: Date.now()\n * }\n * ```\n * \n * @example Data change notification\n * ```typescript\n * {\n * type: 'data-change',\n * channel: 'record.account.123',\n * payload: { id: '123', action: 'updated', data: {...} },\n * timestamp: Date.now()\n * }\n * ```\n */\nexport const WebSocketEventSchema = z.object({\n type: z.enum([\n 'subscribe', // Client subscribes to channel\n 'unsubscribe', // Client unsubscribes from channel\n 'data-change', // Data modification event\n 'presence-update', // User presence change\n 'cursor-update', // Cursor position change (collaborative editing)\n 'error', // Error message\n ]).describe('Event type'),\n channel: z.string().describe('Channel identifier (e.g., \"record.account.123\", \"user.456\")'),\n payload: z.unknown().describe('Event payload data'),\n timestamp: z.number().describe('Unix timestamp in milliseconds'),\n});\n\nexport type WebSocketEvent = z.infer;\n\n/**\n * Simplified Presence State Schema\n * \n * A simplified presence schema for basic user presence tracking.\n * Complements the comprehensive PresenceStateSchema for simpler integrations.\n * \n * Use this for basic presence features. For advanced features like device tracking,\n * custom status, and session management, use the comprehensive PresenceStateSchema above.\n * \n * @example User online\n * ```typescript\n * {\n * userId: 'user123',\n * userName: 'John Doe',\n * status: 'online',\n * lastSeen: Date.now(),\n * metadata: { currentPage: '/dashboard' }\n * }\n * ```\n */\nexport const SimplePresenceStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n userName: z.string().describe('User display name'),\n status: z.enum(['online', 'away', 'offline']).describe('User presence status'),\n lastSeen: z.number().describe('Unix timestamp of last activity in milliseconds'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional presence metadata (e.g., current page, custom status)'),\n});\n\nexport type SimplePresenceState = z.infer;\n\n/**\n * Simplified Cursor Position Schema\n * \n * A simplified cursor position schema for basic collaborative editing.\n * Complements the comprehensive CursorPositionSchema for simpler use cases.\n * \n * Use this for basic cursor sharing. For advanced features like selections,\n * color coding, and document versioning, use the comprehensive CursorPositionSchema above.\n * \n * @example Cursor in text field\n * ```typescript\n * {\n * userId: 'user123',\n * recordId: 'account_456',\n * fieldName: 'description',\n * position: 42,\n * selection: { start: 42, end: 57 }\n * }\n * ```\n */\nexport const SimpleCursorPositionSchema = z.object({\n userId: z.string().describe('User identifier'),\n recordId: z.string().describe('Record identifier being edited'),\n fieldName: z.string().describe('Field name being edited'),\n position: z.number().describe('Cursor position (character offset from start)'),\n selection: z.object({\n start: z.number().describe('Selection start position'),\n end: z.number().describe('Selection end position'),\n }).optional().describe('Text selection range (if text is selected)'),\n});\n\nexport type SimpleCursorPosition = z.infer;\n\n/**\n * WebSocket Server Configuration Schema\n * \n * Server-side configuration for WebSocket services.\n * Controls features like presence tracking, cursor sharing, and connection management.\n * \n * @example Production configuration\n * ```typescript\n * {\n * enabled: true,\n * path: '/ws',\n * heartbeatInterval: 30000,\n * reconnectAttempts: 5,\n * presence: true,\n * cursorSharing: true\n * }\n * ```\n */\nexport const WebSocketServerConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable WebSocket server'),\n path: z.string().default('/ws').describe('WebSocket endpoint path'),\n heartbeatInterval: z.number().default(30000).describe('Heartbeat interval in milliseconds'),\n reconnectAttempts: z.number().default(5).describe('Maximum reconnection attempts for clients'),\n presence: z.boolean().default(false).describe('Enable presence tracking'),\n cursorSharing: z.boolean().default(false).describe('Enable collaborative cursor sharing'),\n});\n\nexport type WebSocketServerConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { CorsConfigSchema, StaticMountSchema, HttpMethod } from '../shared/http.zod';\n\n// Re-export HttpMethod for convenience\nexport { HttpMethod };\n\n/**\n * Route Category Enum\n * Classifies routes for middleware application and security policies.\n */\nexport const RouteCategory = z.enum([\n 'system', // Health, Metrics, Info (No Auth usually)\n 'api', // Business Logic API (Auth required)\n 'auth', // Login/Callback endpoints\n 'static', // Asset serving\n 'webhook', // External callbacks\n 'plugin' // Plugin extensions\n]);\n\nexport type RouteCategory = z.infer;\n\n/**\n * Route Definition Schema\n * Describes a single routable endpoint in the Kernel.\n */\nexport const RouteDefinitionSchema = z.object({\n /**\n * HTTP Method\n */\n method: HttpMethod,\n \n /**\n * URL Path Pattern (supports parameters like /user/:id)\n */\n path: z.string().describe('URL Path pattern'),\n \n /**\n * Route Type/Category\n */\n category: RouteCategory.default('api'),\n \n /**\n * Handler Identifier\n * References an internal function or plugin action ID.\n */\n handler: z.string().describe('Unique handler identifier'),\n \n /**\n * Route specific metadata\n */\n summary: z.string().optional().describe('OpenAPI summary'),\n description: z.string().optional().describe('OpenAPI description'),\n \n /**\n * Security constraints\n */\n public: z.boolean().default(false).describe('Is publicly accessible'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /**\n * Performance hints\n */\n timeout: z.number().int().optional().describe('Execution timeout in ms'),\n rateLimit: z.string().optional().describe('Rate limit policy name'),\n});\n\nexport type RouteDefinition = z.infer;\n\n/**\n * Router Configuration Schema\n * Global routing table configuration.\n */\nexport const RouterConfigSchema = z.object({\n /**\n * URL Prefix for all kernel routes\n */\n basePath: z.string().default('/api').describe('Global API prefix'),\n \n /**\n * Standard Protocol Mounts (Relative to basePath)\n */\n mounts: z.object({\n data: z.string().default('/data').describe('Data Protocol (CRUD)'),\n metadata: z.string().default('/meta').describe('Metadata Protocol (Schemas)'),\n auth: z.string().default('/auth').describe('Auth Protocol'),\n automation: z.string().default('/automation').describe('Automation Protocol'),\n storage: z.string().default('/storage').describe('Storage Protocol'),\n analytics: z.string().default('/analytics').describe('Analytics Protocol'),\n graphql: z.string().default('/graphql').describe('GraphQL Endpoint'),\n ui: z.string().default('/ui').describe('UI Metadata Protocol (Views, Layouts)'),\n workflow: z.string().default('/workflow').describe('Workflow Engine Protocol'),\n realtime: z.string().default('/realtime').describe('Realtime/WebSocket Protocol'),\n notifications: z.string().default('/notifications').describe('Notification Protocol'),\n ai: z.string().default('/ai').describe('AI Engine Protocol (NLQ, Chat, Suggest)'),\n i18n: z.string().default('/i18n').describe('Internationalization Protocol'),\n packages: z.string().default('/packages').describe('Package Management Protocol'),\n }).default({\n data: '/data',\n metadata: '/meta',\n auth: '/auth',\n automation: '/automation',\n storage: '/storage',\n analytics: '/analytics',\n graphql: '/graphql',\n ui: '/ui',\n workflow: '/workflow',\n realtime: '/realtime',\n notifications: '/notifications',\n ai: '/ai',\n i18n: '/i18n',\n packages: '/packages',\n }), // Defaults match standardized spec\n\n /**\n * Cross-Origin Resource Sharing\n */\n cors: CorsConfigSchema.optional(),\n \n /**\n * Static asset mounts\n */\n staticMounts: z.array(StaticMountSchema).optional(),\n});\n\nexport type RouterConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * OData v4 Protocol Support\n * \n * Open Data Protocol (OData) v4 is an industry-standard protocol for building\n * and consuming RESTful APIs. It provides a uniform way to expose, structure,\n * query, and manipulate data.\n * \n * ## Overview\n * \n * OData v4 provides standardized URL conventions for querying data including:\n * - $select: Choose which fields to return\n * - $filter: Filter results with complex expressions\n * - $orderby: Sort results\n * - $top/$skip: Pagination\n * - $expand: Include related entities\n * - $count: Get total count\n * \n * ## Use Cases\n * \n * 1. **Enterprise Integration**\n * - Integrate with Microsoft Dynamics 365\n * - Connect to SharePoint Online\n * - SAP OData services\n * \n * 2. **API Standardization**\n * - Provide consistent query interface\n * - Standard pagination and filtering\n * - Industry-recognized protocol\n * \n * 3. **External Data Sources**\n * - Connect to OData-compliant systems\n * - Federated queries\n * - Data virtualization\n * \n * @see https://www.odata.org/documentation/\n * @see https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html\n * \n * @example OData Query\n * ```\n * GET /api/odata/customers?\n * $select=name,email&\n * $filter=country eq 'US' and revenue gt 100000&\n * $orderby=revenue desc&\n * $top=10&\n * $skip=20&\n * $expand=orders&\n * $count=true\n * ```\n * \n * @example Programmatic Use\n * ```typescript\n * const query: ODataQuery = {\n * select: ['name', 'email'],\n * filter: \"country eq 'US' and revenue gt 100000\",\n * orderby: 'revenue desc',\n * top: 10,\n * skip: 20,\n * expand: ['orders'],\n * count: true\n * }\n * ```\n */\n\n/**\n * OData Query Options Schema\n * \n * System query options defined by OData v4 specification.\n * These are URL query parameters that control the query execution.\n * \n * @see https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html#sec_SystemQueryOptions\n */\nexport const ODataQuerySchema = z.object({\n /**\n * $select - Select specific fields to return\n * \n * Comma-separated list of field names to include in the response.\n * Reduces payload size and improves performance.\n * \n * @example \"name,email,phone\"\n * @example \"id,customer/name\" - With navigation path\n */\n $select: z.union([\n z.string(), // \"name,email\"\n z.array(z.string()), // [\"name\", \"email\"]\n ]).optional().describe('Fields to select'),\n\n /**\n * $filter - Filter results with conditions\n * \n * OData filter expression using comparison operators, logical operators,\n * and functions.\n * \n * Comparison: eq, ne, lt, le, gt, ge\n * Logical: and, or, not\n * Functions: contains, startswith, endswith, length, indexof, substring, etc.\n * \n * @example \"age gt 18\"\n * @example \"country eq 'US' and revenue gt 100000\"\n * @example \"contains(name, 'Smith')\"\n * @example \"startswith(email, 'admin') and isActive eq true\"\n */\n $filter: z.string().optional().describe('Filter expression (OData filter syntax)'),\n\n /**\n * $orderby - Sort results\n * \n * Comma-separated list of fields with optional asc/desc.\n * Default is ascending.\n * \n * @example \"name\"\n * @example \"revenue desc\"\n * @example \"country asc, revenue desc\"\n */\n $orderby: z.union([\n z.string(), // \"name desc\"\n z.array(z.string()), // [\"name desc\", \"email asc\"]\n ]).optional().describe('Sort order'),\n\n /**\n * $top - Limit number of results\n * \n * Maximum number of results to return.\n * Equivalent to SQL LIMIT or FETCH FIRST.\n * \n * @example 10\n * @example 100\n */\n $top: z.number().int().min(0).optional().describe('Max results to return'),\n\n /**\n * $skip - Skip results for pagination\n * \n * Number of results to skip before returning results.\n * Equivalent to SQL OFFSET.\n * \n * @example 20\n * @example 100\n */\n $skip: z.number().int().min(0).optional().describe('Results to skip'),\n\n /**\n * $expand - Include related entities (lookup/master_detail fields)\n * \n * Comma-separated list of navigation properties (relationship field names) to expand.\n * Loads related data in the same request by resolving lookup and master_detail fields.\n * The engine replaces foreign key IDs with full related objects via batch $in queries.\n * Supports nested expand via OData parenthetical syntax.\n * \n * Behavior:\n * - Only fields with `type: 'lookup'` or `type: 'master_detail'` and a valid `reference` are expanded.\n * - Fields without a schema or reference definition are silently skipped (ID returned as-is).\n * - Maximum expand depth defaults to 3 (configurable via QueryAdapterConfig).\n * \n * @example \"orders\"\n * @example \"customer,products\"\n * @example \"orders($select=id,total)\" - With nested query options\n */\n $expand: z.union([\n z.string(), // \"orders\"\n z.array(z.string()), // [\"orders\", \"customer\"]\n ]).optional().describe('Navigation properties to expand (lookup/master_detail fields)'),\n\n /**\n * $count - Include total count\n * \n * When true, includes totalResults count in response.\n * Useful for pagination UI.\n * \n * @example true\n */\n $count: z.boolean().optional().describe('Include total count'),\n\n /**\n * $search - Full-text search\n * \n * Free-text search expression.\n * Search implementation is service-specific.\n * \n * @example \"John Smith\"\n * @example \"urgent AND support\"\n */\n $search: z.string().optional().describe('Search expression'),\n\n /**\n * $format - Response format\n * \n * Preferred response format.\n * \n * @example \"json\"\n * @example \"xml\"\n */\n $format: z.enum(['json', 'xml', 'atom']).optional().describe('Response format'),\n\n /**\n * $apply - Data aggregation\n * \n * Aggregation transformations (groupby, aggregate, etc.)\n * Part of OData aggregation extension.\n * \n * @example \"groupby((country),aggregate(revenue with sum as totalRevenue))\"\n */\n $apply: z.string().optional().describe('Aggregation expression'),\n});\n\nexport type ODataQuery = z.infer;\n\n/**\n * OData Filter Operator\n * \n * Standard comparison and logical operators in OData filter expressions.\n */\nexport const ODataFilterOperatorSchema = z.enum([\n // Comparison Operators\n 'eq', // Equal to\n 'ne', // Not equal to\n 'lt', // Less than\n 'le', // Less than or equal to\n 'gt', // Greater than\n 'ge', // Greater than or equal to\n\n // Logical Operators\n 'and', // Logical AND\n 'or', // Logical OR\n 'not', // Logical NOT\n\n // Grouping\n '(', // Left parenthesis\n ')', // Right parenthesis\n\n // Other\n 'in', // Value in list\n 'has', // Has flag (for enum flags)\n]);\n\nexport type ODataFilterOperator = z.infer;\n\n/**\n * OData Filter Function\n * \n * Standard functions available in OData filter expressions.\n */\nexport const ODataFilterFunctionSchema = z.enum([\n // String Functions\n 'contains', // contains(field, 'value')\n 'startswith', // startswith(field, 'value')\n 'endswith', // endswith(field, 'value')\n 'length', // length(field)\n 'indexof', // indexof(field, 'substring')\n 'substring', // substring(field, start, length)\n 'tolower', // tolower(field)\n 'toupper', // toupper(field)\n 'trim', // trim(field)\n 'concat', // concat(field1, field2)\n\n // Date/Time Functions\n 'year', // year(dateField)\n 'month', // month(dateField)\n 'day', // day(dateField)\n 'hour', // hour(datetimeField)\n 'minute', // minute(datetimeField)\n 'second', // second(datetimeField)\n 'date', // date(datetimeField)\n 'time', // time(datetimeField)\n 'now', // now()\n 'maxdatetime', // maxdatetime()\n 'mindatetime', // mindatetime()\n\n // Math Functions\n 'round', // round(numField)\n 'floor', // floor(numField)\n 'ceiling', // ceiling(numField)\n\n // Type Functions\n 'cast', // cast(field, 'Edm.String')\n 'isof', // isof(field, 'Type')\n\n // Collection Functions\n 'any', // collection/any(d:d/prop eq value)\n 'all', // collection/all(d:d/prop eq value)\n]);\n\nexport type ODataFilterFunction = z.infer;\n\n/**\n * OData Response Schema\n * \n * Standard OData JSON response format.\n */\nexport const ODataResponseSchema = z.object({\n /**\n * OData context URL\n * Describes the payload structure\n */\n '@odata.context': z.string().url().optional().describe('Metadata context URL'),\n\n /**\n * Total count (when $count=true)\n */\n '@odata.count': z.number().int().optional().describe('Total results count'),\n\n /**\n * Next link for pagination\n */\n '@odata.nextLink': z.string().url().optional().describe('Next page URL'),\n\n /**\n * Result array\n */\n value: z.array(z.record(z.string(), z.unknown())).describe('Results array'),\n});\n\nexport type ODataResponse = z.infer;\n\n/**\n * OData Error Response Schema\n * \n * Standard OData error format.\n */\nexport const ODataErrorSchema = z.object({\n error: z.object({\n /**\n * Error code\n */\n code: z.string().describe('Error code'),\n\n /**\n * Error message\n */\n message: z.string().describe('Error message'),\n\n /**\n * Target of the error (field name, etc.)\n */\n target: z.string().optional().describe('Error target'),\n\n /**\n * Additional error details\n */\n details: z.array(z.object({\n code: z.string(),\n message: z.string(),\n target: z.string().optional(),\n })).optional().describe('Error details'),\n\n /**\n * Inner error for debugging\n */\n innererror: z.record(z.string(), z.unknown()).optional().describe('Inner error details'),\n }),\n});\n\nexport type ODataError = z.infer;\n\n/**\n * OData Metadata Configuration\n * \n * Configuration for OData metadata endpoint ($metadata).\n */\nexport const ODataMetadataSchema = z.object({\n /**\n * Service namespace\n */\n namespace: z.string().describe('Service namespace'),\n\n /**\n * Entity types to expose\n */\n entityTypes: z.array(z.object({\n name: z.string().describe('Entity type name'),\n key: z.array(z.string()).describe('Key fields'),\n properties: z.array(z.object({\n name: z.string(),\n type: z.string().describe('OData type (Edm.String, Edm.Int32, etc.)'),\n nullable: z.boolean().default(true),\n })),\n navigationProperties: z.array(z.object({\n name: z.string(),\n type: z.string(),\n partner: z.string().optional(),\n })).optional(),\n })).describe('Entity types'),\n\n /**\n * Entity sets\n */\n entitySets: z.array(z.object({\n name: z.string().describe('Entity set name'),\n entityType: z.string().describe('Entity type'),\n })).describe('Entity sets'),\n});\n\nexport type ODataMetadata = z.infer;\n\n/**\n * Helper functions for OData operations\n */\nexport const OData = {\n /**\n * Build OData query URL\n */\n buildUrl: (baseUrl: string, query: ODataQuery): string => {\n const params = new URLSearchParams();\n\n if (query.$select) {\n params.append('$select', Array.isArray(query.$select) ? query.$select.join(',') : query.$select);\n }\n if (query.$filter) {\n params.append('$filter', query.$filter);\n }\n if (query.$orderby) {\n params.append('$orderby', Array.isArray(query.$orderby) ? query.$orderby.join(',') : query.$orderby);\n }\n if (query.$top !== undefined) {\n params.append('$top', query.$top.toString());\n }\n if (query.$skip !== undefined) {\n params.append('$skip', query.$skip.toString());\n }\n if (query.$expand) {\n params.append('$expand', Array.isArray(query.$expand) ? query.$expand.join(',') : query.$expand);\n }\n if (query.$count !== undefined) {\n params.append('$count', query.$count.toString());\n }\n if (query.$search) {\n params.append('$search', query.$search);\n }\n if (query.$format) {\n params.append('$format', query.$format);\n }\n if (query.$apply) {\n params.append('$apply', query.$apply);\n }\n\n const queryString = params.toString();\n return queryString ? `${baseUrl}?${queryString}` : baseUrl;\n },\n\n /**\n * Create a simple filter expression\n */\n filter: {\n eq: (field: string, value: string | number | boolean) => \n `${field} eq ${typeof value === 'string' ? `'${value}'` : value}`,\n ne: (field: string, value: string | number | boolean) => \n `${field} ne ${typeof value === 'string' ? `'${value}'` : value}`,\n gt: (field: string, value: number) => `${field} gt ${value}`,\n lt: (field: string, value: number) => `${field} lt ${value}`,\n contains: (field: string, value: string) => `contains(${field}, '${value}')`,\n and: (...expressions: string[]) => expressions.join(' and '),\n or: (...expressions: string[]) => expressions.join(' or '),\n },\n} as const;\n\n/**\n * OData Configuration Schema\n * \n * Configuration for enabling OData v4 API endpoint.\n */\nexport const ODataConfigSchema = z.object({\n /** Enable OData endpoint */\n enabled: z.boolean().default(true).describe('Enable OData API'),\n \n /** OData endpoint path */\n path: z.string().default('/odata').describe('OData endpoint path'),\n \n /** Metadata configuration */\n metadata: ODataMetadataSchema.optional().describe('OData metadata configuration'),\n}).passthrough(); // Allow additional properties for flexibility\n\nexport type ODataConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\n\n/**\n * GraphQL Protocol Support\n * \n * GraphQL is a query language for APIs and a runtime for executing those queries.\n * It provides a complete and understandable description of the data in your API,\n * gives clients the power to ask for exactly what they need, and enables powerful\n * developer tools.\n * \n * ## Overview\n * \n * GraphQL provides:\n * - Type-safe schema definition\n * - Precise data fetching (no over/under-fetching)\n * - Introspection and documentation\n * - Real-time subscriptions\n * - Batched queries with DataLoader\n * \n * ## Use Cases\n * \n * 1. **Modern API Development**\n * - Mobile and web applications\n * - Microservices federation\n * - Real-time dashboards\n * \n * 2. **Data Aggregation**\n * - Multi-source data integration\n * - Complex nested queries\n * - Efficient data loading\n * \n * 3. **Developer Experience**\n * - Self-documenting API\n * - Type safety and validation\n * - GraphQL playground\n * \n * @see https://graphql.org/\n * @see https://spec.graphql.org/\n * \n * @example GraphQL Query\n * ```graphql\n * query GetCustomer($id: ID!) {\n * customer(id: $id) {\n * id\n * name\n * email\n * orders(limit: 10, status: \"active\") {\n * id\n * total\n * items {\n * product {\n * name\n * price\n * }\n * }\n * }\n * }\n * }\n * ```\n * \n * @example GraphQL Mutation\n * ```graphql\n * mutation CreateOrder($input: CreateOrderInput!) {\n * createOrder(input: $input) {\n * id\n * orderNumber\n * status\n * }\n * }\n * ```\n */\n\n// ==========================================\n// 1. GraphQL Type System\n// ==========================================\n\n/**\n * GraphQL Scalar Types\n * \n * Built-in scalar types in GraphQL plus custom scalars.\n */\nexport const GraphQLScalarType = z.enum([\n // Built-in GraphQL Scalars\n 'ID',\n 'String',\n 'Int',\n 'Float',\n 'Boolean',\n \n // Extended Scalars (common custom types)\n 'DateTime',\n 'Date',\n 'Time',\n 'JSON',\n 'JSONObject',\n 'Upload',\n 'URL',\n 'Email',\n 'PhoneNumber',\n 'Currency',\n 'Decimal',\n 'BigInt',\n 'Long',\n 'UUID',\n 'Base64',\n 'Void',\n]);\n\nexport type GraphQLScalarType = z.infer;\n\n/**\n * GraphQL Type Configuration\n * \n * Configuration for generating GraphQL types from Object definitions.\n */\nexport const GraphQLTypeConfigSchema = z.object({\n /** Type name in GraphQL schema */\n name: z.string().describe('GraphQL type name (PascalCase recommended)'),\n \n /** Source Object name */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Description for GraphQL schema documentation */\n description: z.string().optional().describe('Type description'),\n \n /** Fields to include/exclude */\n fields: z.object({\n /** Include only these fields (allow list) */\n include: z.array(z.string()).optional().describe('Fields to include'),\n \n /** Exclude these fields (deny list) */\n exclude: z.array(z.string()).optional().describe('Fields to exclude (e.g., sensitive fields)'),\n \n /** Custom field mappings */\n mappings: z.record(z.string(), z.object({\n graphqlName: z.string().optional().describe('Custom GraphQL field name'),\n graphqlType: z.string().optional().describe('Override GraphQL type'),\n description: z.string().optional().describe('Field description'),\n deprecationReason: z.string().optional().describe('Why field is deprecated'),\n nullable: z.boolean().optional().describe('Override nullable'),\n })).optional().describe('Field-level customizations'),\n }).optional().describe('Field configuration'),\n \n /** Interfaces this type implements */\n interfaces: z.array(z.string()).optional().describe('GraphQL interface names'),\n \n /** Whether this is an interface definition */\n isInterface: z.boolean().optional().default(false).describe('Define as GraphQL interface'),\n \n /** Custom directives */\n directives: z.array(z.object({\n name: z.string().describe('Directive name'),\n args: z.record(z.string(), z.unknown()).optional().describe('Directive arguments'),\n })).optional().describe('GraphQL directives'),\n});\n\nexport type GraphQLTypeConfig = z.infer;\nexport type GraphQLTypeConfigInput = z.input;\n\n// ==========================================\n// 2. Query Generation Configuration\n// ==========================================\n\n/**\n * GraphQL Query Configuration\n * \n * Configuration for auto-generating query fields from Objects.\n */\nexport const GraphQLQueryConfigSchema = z.object({\n /** Query name */\n name: z.string().describe('Query field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Query type: single record or list */\n type: z.enum(['get', 'list', 'search']).describe('Query type'),\n \n /** Description */\n description: z.string().optional().describe('Query description'),\n \n /** Input arguments */\n args: z.record(z.string(), z.object({\n type: z.string().describe('GraphQL type (e.g., \"ID!\", \"String\", \"Int\")'),\n description: z.string().optional().describe('Argument description'),\n defaultValue: z.unknown().optional().describe('Default value'),\n })).optional().describe('Query arguments'),\n \n /** Filtering configuration */\n filtering: z.object({\n enabled: z.boolean().default(true).describe('Allow filtering'),\n fields: z.array(z.string()).optional().describe('Filterable fields'),\n operators: z.array(z.enum([\n 'eq', 'ne', 'gt', 'gte', 'lt', 'lte',\n 'in', 'notIn', 'contains', 'startsWith', 'endsWith',\n 'isNull', 'isNotNull',\n ])).optional().describe('Allowed filter operators'),\n }).optional().describe('Filtering capabilities'),\n \n /** Sorting configuration */\n sorting: z.object({\n enabled: z.boolean().default(true).describe('Allow sorting'),\n fields: z.array(z.string()).optional().describe('Sortable fields'),\n defaultSort: z.object({\n field: z.string(),\n direction: z.enum(['ASC', 'DESC']),\n }).optional().describe('Default sort order'),\n }).optional().describe('Sorting capabilities'),\n \n /** Pagination configuration */\n pagination: z.object({\n enabled: z.boolean().default(true).describe('Enable pagination'),\n type: z.enum(['offset', 'cursor', 'relay']).default('offset').describe('Pagination style'),\n defaultLimit: z.number().int().min(1).default(20).describe('Default page size'),\n maxLimit: z.number().int().min(1).default(100).describe('Maximum page size'),\n cursors: z.object({\n field: z.string().default('id').describe('Field to use for cursor pagination'),\n }).optional(),\n }).optional().describe('Pagination configuration'),\n \n /** Field selection */\n fields: z.object({\n /** Always include these fields */\n required: z.array(z.string()).optional().describe('Required fields (always returned)'),\n \n /** Allow selecting these fields */\n selectable: z.array(z.string()).optional().describe('Selectable fields'),\n }).optional().describe('Field selection configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(false).describe('Enable caching'),\n ttl: z.number().int().min(0).optional().describe('Cache TTL in seconds'),\n key: z.string().optional().describe('Cache key template'),\n }).optional().describe('Query caching'),\n});\n\nexport type GraphQLQueryConfig = z.infer;\nexport type GraphQLQueryConfigInput = z.input;\n\n// ==========================================\n// 3. Mutation Generation Configuration\n// ==========================================\n\n/**\n * GraphQL Mutation Configuration\n * \n * Configuration for auto-generating mutation fields from Objects.\n */\nexport const GraphQLMutationConfigSchema = z.object({\n /** Mutation name */\n name: z.string().describe('Mutation field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Mutation type */\n type: z.enum(['create', 'update', 'delete', 'upsert', 'custom']).describe('Mutation type'),\n \n /** Description */\n description: z.string().optional().describe('Mutation description'),\n \n /** Input type configuration */\n input: z.object({\n /** Input type name */\n typeName: z.string().optional().describe('Custom input type name'),\n \n /** Fields to include in input */\n fields: z.object({\n include: z.array(z.string()).optional().describe('Fields to include'),\n exclude: z.array(z.string()).optional().describe('Fields to exclude'),\n required: z.array(z.string()).optional().describe('Required input fields'),\n }).optional().describe('Input field configuration'),\n \n /** Validation */\n validation: z.object({\n enabled: z.boolean().default(true).describe('Enable input validation'),\n rules: z.array(z.string()).optional().describe('Custom validation rules'),\n }).optional().describe('Input validation'),\n }).optional().describe('Input configuration'),\n \n /** Return type configuration */\n output: z.object({\n /** Type of output */\n type: z.enum(['object', 'payload', 'boolean', 'custom']).default('object').describe('Output type'),\n \n /** Include success/error envelope */\n includeEnvelope: z.boolean().optional().default(false).describe('Wrap in success/error payload'),\n \n /** Custom output type */\n customType: z.string().optional().describe('Custom output type name'),\n }).optional().describe('Output configuration'),\n \n /** Transaction handling */\n transaction: z.object({\n enabled: z.boolean().default(true).describe('Use database transaction'),\n isolationLevel: z.enum(['read_uncommitted', 'read_committed', 'repeatable_read', 'serializable']).optional().describe('Transaction isolation level'),\n }).optional().describe('Transaction configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Hooks */\n hooks: z.object({\n before: z.array(z.string()).optional().describe('Pre-mutation hooks'),\n after: z.array(z.string()).optional().describe('Post-mutation hooks'),\n }).optional().describe('Lifecycle hooks'),\n});\n\nexport type GraphQLMutationConfig = z.infer;\nexport type GraphQLMutationConfigInput = z.input;\n\n// ==========================================\n// 4. Subscription Configuration\n// ==========================================\n\n/**\n * GraphQL Subscription Configuration\n * \n * Configuration for real-time GraphQL subscriptions.\n */\nexport const GraphQLSubscriptionConfigSchema = z.object({\n /** Subscription name */\n name: z.string().describe('Subscription field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Subscription trigger events */\n events: z.array(z.enum(['created', 'updated', 'deleted', 'custom'])).describe('Events to subscribe to'),\n \n /** Description */\n description: z.string().optional().describe('Subscription description'),\n \n /** Filtering */\n filter: z.object({\n enabled: z.boolean().default(true).describe('Allow filtering subscriptions'),\n fields: z.array(z.string()).optional().describe('Filterable fields'),\n }).optional().describe('Subscription filtering'),\n \n /** Payload configuration */\n payload: z.object({\n /** Include the modified entity */\n includeEntity: z.boolean().default(true).describe('Include entity in payload'),\n \n /** Include previous values (for updates) */\n includePreviousValues: z.boolean().optional().default(false).describe('Include previous field values'),\n \n /** Include mutation metadata */\n includeMeta: z.boolean().optional().default(true).describe('Include metadata (timestamp, user, etc.)'),\n }).optional().describe('Payload configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Rate limiting for subscriptions */\n rateLimit: z.object({\n enabled: z.boolean().default(true).describe('Enable rate limiting'),\n maxSubscriptionsPerUser: z.number().int().min(1).default(10).describe('Max concurrent subscriptions per user'),\n throttleMs: z.number().int().min(0).optional().describe('Throttle interval in milliseconds'),\n }).optional().describe('Subscription rate limiting'),\n});\n\nexport type GraphQLSubscriptionConfig = z.infer;\nexport type GraphQLSubscriptionConfigInput = z.input;\n\n// ==========================================\n// 5. Resolver Configuration\n// ==========================================\n\n/**\n * GraphQL Resolver Configuration\n * \n * Configuration for custom resolver logic.\n */\nexport const GraphQLResolverConfigSchema = z.object({\n /** Field path (e.g., \"Query.users\", \"Mutation.createUser\") */\n path: z.string().describe('Resolver path (Type.field)'),\n \n /** Resolver implementation type */\n type: z.enum(['datasource', 'computed', 'script', 'proxy']).describe('Resolver implementation type'),\n \n /** Implementation details */\n implementation: z.object({\n /** For datasource type */\n datasource: z.string().optional().describe('Datasource ID'),\n query: z.string().optional().describe('Query/SQL to execute'),\n \n /** For computed type */\n expression: z.string().optional().describe('Computation expression'),\n dependencies: z.array(z.string()).optional().describe('Dependent fields'),\n \n /** For script type */\n script: z.string().optional().describe('Script ID or inline code'),\n \n /** For proxy type */\n url: z.string().optional().describe('Proxy URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).optional().describe('HTTP method'),\n }).optional().describe('Implementation configuration'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(false).describe('Enable resolver caching'),\n ttl: z.number().int().min(0).optional().describe('Cache TTL in seconds'),\n keyArgs: z.array(z.string()).optional().describe('Arguments to include in cache key'),\n }).optional().describe('Resolver caching'),\n});\n\nexport type GraphQLResolverConfig = z.infer;\nexport type GraphQLResolverConfigInput = z.input;\n\n// ==========================================\n// 6. DataLoader Configuration\n// ==========================================\n\n/**\n * GraphQL DataLoader Configuration\n * \n * Configuration for batching and caching with DataLoader pattern.\n * Prevents N+1 query problems in GraphQL.\n */\nexport const GraphQLDataLoaderConfigSchema = z.object({\n /** Loader name */\n name: z.string().describe('DataLoader name'),\n \n /** Source Object or datasource */\n source: z.string().describe('Source object or datasource'),\n \n /** Batch function configuration */\n batchFunction: z.object({\n /** Type of batch operation */\n type: z.enum(['findByIds', 'query', 'script', 'custom']).describe('Batch function type'),\n \n /** For findByIds */\n keyField: z.string().optional().describe('Field to batch on (e.g., \"id\")'),\n \n /** For query */\n query: z.string().optional().describe('Query template'),\n \n /** For script */\n script: z.string().optional().describe('Script ID'),\n \n /** Maximum batch size */\n maxBatchSize: z.number().int().min(1).optional().default(100).describe('Maximum batch size'),\n }).describe('Batch function configuration'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable per-request caching'),\n \n /** Cache key function */\n keyFn: z.string().optional().describe('Custom cache key function'),\n }).optional().describe('DataLoader caching'),\n \n /** Options */\n options: z.object({\n /** Batch multiple requests in single tick */\n batch: z.boolean().default(true).describe('Enable batching'),\n \n /** Cache loaded values */\n cache: z.boolean().default(true).describe('Enable caching'),\n \n /** Maximum cache size */\n maxCacheSize: z.number().int().min(0).optional().describe('Max cache entries'),\n }).optional().describe('DataLoader options'),\n});\n\nexport type GraphQLDataLoaderConfig = z.infer;\nexport type GraphQLDataLoaderConfigInput = z.input;\n\n// ==========================================\n// 7. GraphQL Directive Schema\n// ==========================================\n\n/**\n * GraphQL Directive Location\n * \n * Where a directive can be used in the schema.\n */\nexport const GraphQLDirectiveLocation = z.enum([\n // Executable Directive Locations\n 'QUERY',\n 'MUTATION',\n 'SUBSCRIPTION',\n 'FIELD',\n 'FRAGMENT_DEFINITION',\n 'FRAGMENT_SPREAD',\n 'INLINE_FRAGMENT',\n 'VARIABLE_DEFINITION',\n \n // Type System Directive Locations\n 'SCHEMA',\n 'SCALAR',\n 'OBJECT',\n 'FIELD_DEFINITION',\n 'ARGUMENT_DEFINITION',\n 'INTERFACE',\n 'UNION',\n 'ENUM',\n 'ENUM_VALUE',\n 'INPUT_OBJECT',\n 'INPUT_FIELD_DEFINITION',\n]);\n\nexport type GraphQLDirectiveLocation = z.infer;\n\n/**\n * GraphQL Directive Configuration\n * \n * Custom directives for schema metadata and behavior.\n */\nexport const GraphQLDirectiveConfigSchema = z.object({\n /** Directive name */\n name: z.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe('Directive name (camelCase)'),\n \n /** Description */\n description: z.string().optional().describe('Directive description'),\n \n /** Where directive can be used */\n locations: z.array(GraphQLDirectiveLocation).describe('Directive locations'),\n \n /** Arguments */\n args: z.record(z.string(), z.object({\n type: z.string().describe('Argument type'),\n description: z.string().optional().describe('Argument description'),\n defaultValue: z.unknown().optional().describe('Default value'),\n })).optional().describe('Directive arguments'),\n \n /** Is repeatable */\n repeatable: z.boolean().optional().default(false).describe('Can be applied multiple times'),\n \n /** Implementation */\n implementation: z.object({\n /** Directive behavior type */\n type: z.enum(['auth', 'validation', 'transform', 'cache', 'deprecation', 'custom']).describe('Directive type'),\n \n /** Handler function */\n handler: z.string().optional().describe('Handler function name or script'),\n }).optional().describe('Directive implementation'),\n});\n\nexport type GraphQLDirectiveConfig = z.infer;\nexport type GraphQLDirectiveConfigInput = z.input;\n\n// ==========================================\n// 8. GraphQL Security - Query Depth Limiting\n// ==========================================\n\n/**\n * Query Depth Limiting Configuration\n * \n * Prevents deeply nested queries that could cause performance issues.\n */\nexport const GraphQLQueryDepthLimitSchema = z.object({\n /** Enable depth limiting */\n enabled: z.boolean().default(true).describe('Enable query depth limiting'),\n \n /** Maximum allowed depth */\n maxDepth: z.number().int().min(1).default(10).describe('Maximum query depth'),\n \n /** Fields to ignore in depth calculation */\n ignoreFields: z.array(z.string()).optional().describe('Fields excluded from depth calculation'),\n \n /** Callback on depth exceeded */\n onDepthExceeded: z.enum(['reject', 'log', 'warn']).default('reject').describe('Action when depth exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for depth violations'),\n});\n\nexport type GraphQLQueryDepthLimit = z.infer;\nexport type GraphQLQueryDepthLimitInput = z.input;\n\n// ==========================================\n// 9. GraphQL Security - Query Complexity\n// ==========================================\n\n/**\n * Query Complexity Calculation Configuration\n * \n * Assigns complexity scores to fields and limits total query complexity.\n * Prevents expensive queries from overloading the server.\n */\nexport const GraphQLQueryComplexitySchema = z.object({\n /** Enable complexity limiting */\n enabled: z.boolean().default(true).describe('Enable query complexity limiting'),\n \n /** Maximum allowed complexity score */\n maxComplexity: z.number().int().min(1).default(1000).describe('Maximum query complexity'),\n \n /** Default field complexity */\n defaultFieldComplexity: z.number().int().min(0).default(1).describe('Default complexity per field'),\n \n /** Field-specific complexity scores */\n fieldComplexity: z.record(z.string(), z.union([\n z.number().int().min(0),\n z.object({\n /** Base complexity */\n base: z.number().int().min(0).describe('Base complexity'),\n \n /** Multiplier based on arguments */\n multiplier: z.string().optional().describe('Argument multiplier (e.g., \"limit\")'),\n \n /** Custom complexity calculation */\n calculator: z.string().optional().describe('Custom calculator function'),\n }),\n ])).optional().describe('Per-field complexity configuration'),\n \n /** List multiplier */\n listMultiplier: z.number().min(0).default(10).describe('Multiplier for list fields'),\n \n /** Callback on complexity exceeded */\n onComplexityExceeded: z.enum(['reject', 'log', 'warn']).default('reject').describe('Action when complexity exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for complexity violations'),\n});\n\nexport type GraphQLQueryComplexity = z.infer;\nexport type GraphQLQueryComplexityInput = z.input;\n\n// ==========================================\n// 10. GraphQL Security - Rate Limiting\n// ==========================================\n\n/**\n * GraphQL Rate Limiting Configuration\n * \n * Rate limiting for GraphQL operations.\n */\nexport const GraphQLRateLimitSchema = z.object({\n /** Enable rate limiting */\n enabled: z.boolean().default(true).describe('Enable rate limiting'),\n \n /** Rate limit strategy */\n strategy: z.enum(['token_bucket', 'fixed_window', 'sliding_window', 'cost_based']).default('token_bucket').describe('Rate limiting strategy'),\n \n /** Global rate limits */\n global: z.object({\n /** Requests per time window */\n maxRequests: z.number().int().min(1).default(1000).describe('Maximum requests per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n }).optional().describe('Global rate limits'),\n \n /** Per-user rate limits */\n perUser: z.object({\n /** Requests per time window */\n maxRequests: z.number().int().min(1).default(100).describe('Maximum requests per user per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n }).optional().describe('Per-user rate limits'),\n \n /** Cost-based rate limiting */\n costBased: z.object({\n /** Enable cost-based limiting */\n enabled: z.boolean().default(false).describe('Enable cost-based rate limiting'),\n \n /** Maximum cost per time window */\n maxCost: z.number().int().min(1).default(10000).describe('Maximum cost per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n \n /** Use complexity as cost */\n useComplexityAsCost: z.boolean().default(true).describe('Use query complexity as cost'),\n }).optional().describe('Cost-based rate limiting'),\n \n /** Operation-specific limits */\n operations: z.record(z.string(), z.object({\n maxRequests: z.number().int().min(1).describe('Max requests for this operation'),\n windowMs: z.number().int().min(1000).describe('Time window'),\n })).optional().describe('Per-operation rate limits'),\n \n /** Callback on limit exceeded */\n onLimitExceeded: z.enum(['reject', 'queue', 'log']).default('reject').describe('Action when rate limit exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for rate limit violations'),\n \n /** Headers to include in response */\n includeHeaders: z.boolean().default(true).describe('Include rate limit headers in response'),\n});\n\nexport type GraphQLRateLimit = z.infer;\nexport type GraphQLRateLimitInput = z.input;\n\n// ==========================================\n// 11. GraphQL Security - Persisted Queries\n// ==========================================\n\n/**\n * Persisted Queries Configuration\n * \n * Only allow pre-registered queries to execute (allow list approach).\n * Improves security and performance.\n */\nexport const GraphQLPersistedQuerySchema = z.object({\n /** Enable persisted queries */\n enabled: z.boolean().default(false).describe('Enable persisted queries'),\n \n /** Enforcement mode */\n mode: z.enum(['optional', 'required']).default('optional').describe('Persisted query mode (optional: allow both, required: only persisted)'),\n \n /** Query store configuration */\n store: z.object({\n /** Store type */\n type: z.enum(['memory', 'redis', 'database', 'file']).default('memory').describe('Query store type'),\n \n /** Store connection string */\n connection: z.string().optional().describe('Store connection string or path'),\n \n /** TTL for cached queries */\n ttl: z.number().int().min(0).optional().describe('TTL in seconds for stored queries'),\n }).optional().describe('Query store configuration'),\n \n /** Automatic Persisted Queries (APQ) */\n apq: z.object({\n /** Enable APQ */\n enabled: z.boolean().default(true).describe('Enable Automatic Persisted Queries'),\n \n /** Hash algorithm */\n hashAlgorithm: z.enum(['sha256', 'sha1', 'md5']).default('sha256').describe('Hash algorithm for query IDs'),\n \n /** Cache control */\n cache: z.object({\n /** Cache TTL */\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n \n /** Max cache size */\n maxSize: z.number().int().min(1).optional().describe('Maximum number of cached queries'),\n }).optional().describe('APQ cache configuration'),\n }).optional().describe('Automatic Persisted Queries configuration'),\n \n /** Query allow list */\n allowlist: z.object({\n /** Enable allow list mode */\n enabled: z.boolean().default(false).describe('Enable query allow list (reject queries not in list)'),\n \n /** Allowed query IDs */\n queries: z.array(z.object({\n id: z.string().describe('Query ID or hash'),\n operation: z.string().optional().describe('Operation name'),\n query: z.string().optional().describe('Query string'),\n })).optional().describe('Allowed queries'),\n \n /** External allow list source */\n source: z.string().optional().describe('External allow list source (file path or URL)'),\n }).optional().describe('Query allow list configuration'),\n \n /** Security */\n security: z.object({\n /** Maximum query size */\n maxQuerySize: z.number().int().min(1).optional().describe('Maximum query string size in bytes'),\n \n /** Reject introspection in production */\n rejectIntrospection: z.boolean().default(false).describe('Reject introspection queries'),\n }).optional().describe('Security configuration'),\n});\n\nexport type GraphQLPersistedQuery = z.infer;\nexport type GraphQLPersistedQueryInput = z.input;\n\n// ==========================================\n// 12. GraphQL Federation\n// ==========================================\n\n/**\n * Federation Entity Key Definition\n * \n * Defines how entities are uniquely identified across subgraphs.\n * Corresponds to the `@key` directive in Apollo Federation.\n * \n * @see https://www.apollographql.com/docs/federation/entities\n */\nexport const FederationEntityKeySchema = z.object({\n /** Fields composing the key (e.g., \"id\" or \"sku packageId\") */\n fields: z.string().describe('Selection set of fields composing the entity key'),\n\n /** Whether this key can be used for resolution across subgraphs */\n resolvable: z.boolean().optional().default(true).describe('Whether entities can be resolved from this subgraph'),\n});\n\nexport type FederationEntityKey = z.infer;\n\n/**\n * Federation External Field\n * \n * Marks a field as owned by another subgraph (`@external`).\n */\nexport const FederationExternalFieldSchema = z.object({\n /** Field name */\n field: z.string().describe('Field name marked as external'),\n\n /** The subgraph that owns this field */\n ownerSubgraph: z.string().optional().describe('Subgraph that owns this field'),\n});\n\nexport type FederationExternalField = z.infer;\n\n/**\n * Federation Requires Directive\n * \n * Specifies fields that must be fetched from other subgraphs\n * before resolving a computed field.\n * Corresponds to the `@requires` directive in Apollo Federation.\n */\nexport const FederationRequiresSchema = z.object({\n /** The field that has this requirement */\n field: z.string().describe('Field with the requirement'),\n\n /** Selection set of external fields required for resolution */\n fields: z.string().describe('Selection set of required fields (e.g., \"price weight\")'),\n});\n\nexport type FederationRequires = z.infer;\n\n/**\n * Federation Provides Directive\n * \n * Indicates that a field resolution provides additional fields\n * of a returned entity type.\n * Corresponds to the `@provides` directive in Apollo Federation.\n */\nexport const FederationProvidesSchema = z.object({\n /** The field that provides additional data */\n field: z.string().describe('Field that provides additional entity fields'),\n\n /** Selection set of fields provided during resolution */\n fields: z.string().describe('Selection set of provided fields (e.g., \"name price\")'),\n});\n\nexport type FederationProvides = z.infer;\n\n/**\n * Federation Entity Configuration\n * \n * Configures a type as a federated entity that can be referenced\n * and extended across multiple subgraphs.\n */\nexport const FederationEntitySchema = z.object({\n /** Type/Object name */\n typeName: z.string().describe('GraphQL type name for this entity'),\n\n /** Entity keys (`@key` directive) */\n keys: z.array(FederationEntityKeySchema).min(1).describe('Entity key definitions'),\n\n /** External fields (`@external`) */\n externalFields: z.array(FederationExternalFieldSchema).optional().describe('Fields owned by other subgraphs'),\n\n /** Requires directives (`@requires`) */\n requires: z.array(FederationRequiresSchema).optional().describe('Required external fields for computed fields'),\n\n /** Provides directives (`@provides`) */\n provides: z.array(FederationProvidesSchema).optional().describe('Fields provided during resolution'),\n\n /** Whether this subgraph owns this entity */\n owner: z.boolean().optional().default(false).describe('Whether this subgraph is the owner of this entity'),\n});\n\nexport type FederationEntity = z.infer;\n\n/**\n * Subgraph Configuration\n * \n * Configuration for an individual subgraph in a federated architecture.\n */\nexport const SubgraphConfigSchema = z.object({\n /** Subgraph name */\n name: z.string().describe('Unique subgraph identifier'),\n\n /** Subgraph URL */\n url: z.string().describe('Subgraph endpoint URL'),\n\n /** Schema source */\n schemaSource: z.enum(['introspection', 'file', 'registry']).default('introspection').describe('How to obtain the subgraph schema'),\n\n /** Schema file path (when schemaSource is \"file\") */\n schemaPath: z.string().optional().describe('Path to schema file (SDL format)'),\n\n /** Federated entities defined by this subgraph */\n entities: z.array(FederationEntitySchema).optional().describe('Entity definitions for this subgraph'),\n\n /** Health check endpoint */\n healthCheck: z.object({\n enabled: z.boolean().default(true).describe('Enable health checking'),\n path: z.string().default('/health').describe('Health check endpoint path'),\n intervalMs: z.number().int().min(1000).default(30000).describe('Health check interval in milliseconds'),\n }).optional().describe('Subgraph health check configuration'),\n\n /** Request headers to forward */\n forwardHeaders: z.array(z.string()).optional().describe('HTTP headers to forward to this subgraph'),\n});\n\nexport type SubgraphConfig = z.infer;\nexport type SubgraphConfigInput = z.input;\n\n/**\n * Federation Gateway Configuration\n * \n * Root-level gateway configuration for Apollo Federation or similar.\n * Manages query planning, routing, and composition across subgraphs.\n */\nexport const FederationGatewaySchema = z.object({\n /** Enable federation mode */\n enabled: z.boolean().default(false).describe('Enable GraphQL Federation gateway mode'),\n\n /** Federation specification version */\n version: z.enum(['v1', 'v2']).default('v2').describe('Federation specification version'),\n\n /** Registered subgraphs */\n subgraphs: z.array(SubgraphConfigSchema).describe('Subgraph configurations'),\n\n /** Service discovery */\n serviceDiscovery: z.object({\n /** Discovery mode */\n type: z.enum(['static', 'dns', 'consul', 'kubernetes']).default('static').describe('Service discovery method'),\n\n /** Poll interval for dynamic discovery */\n pollIntervalMs: z.number().int().min(1000).optional().describe('Discovery poll interval in milliseconds'),\n\n /** Kubernetes namespace (when type is \"kubernetes\") */\n namespace: z.string().optional().describe('Kubernetes namespace for subgraph discovery'),\n }).optional().describe('Service discovery configuration'),\n\n /** Query planning */\n queryPlanning: z.object({\n /** Execution strategy */\n strategy: z.enum(['parallel', 'sequential', 'adaptive']).default('parallel').describe('Query execution strategy across subgraphs'),\n\n /** Maximum query depth across subgraphs */\n maxDepth: z.number().int().min(1).optional().describe('Max query depth in federated execution'),\n\n /** Dry-run mode for debugging query plans */\n dryRun: z.boolean().optional().default(false).describe('Log query plans without executing'),\n }).optional().describe('Query planning configuration'),\n\n /** Schema composition settings */\n composition: z.object({\n /** How schema conflicts are resolved */\n conflictResolution: z.enum(['error', 'first_wins', 'last_wins']).default('error').describe('Strategy for resolving schema conflicts'),\n\n /** Whether to validate composed schema */\n validate: z.boolean().default(true).describe('Validate composed supergraph schema'),\n }).optional().describe('Schema composition configuration'),\n\n /** Gateway-level error handling */\n errorHandling: z.object({\n /** Whether to include subgraph names in errors */\n includeSubgraphName: z.boolean().default(false).describe('Include subgraph name in error responses'),\n\n /** Partial error behavior */\n partialErrors: z.enum(['propagate', 'nullify', 'reject']).default('propagate').describe('Behavior when a subgraph returns partial errors'),\n }).optional().describe('Error handling configuration'),\n});\n\nexport type FederationGateway = z.infer;\nexport type FederationGatewayInput = z.input;\n\n// ==========================================\n// 13. Complete GraphQL Configuration\n// ==========================================\n\n/**\n * Complete GraphQL Configuration\n * \n * Root configuration for GraphQL API generation and security.\n */\nexport const GraphQLConfigSchema = z.object({\n /** Enable GraphQL API */\n enabled: z.boolean().default(true).describe('Enable GraphQL API'),\n \n /** GraphQL endpoint path */\n path: z.string().default('/graphql').describe('GraphQL endpoint path'),\n \n /** GraphQL Playground */\n playground: z.object({\n enabled: z.boolean().default(true).describe('Enable GraphQL Playground'),\n path: z.string().default('/playground').describe('Playground path'),\n }).optional().describe('GraphQL Playground configuration'),\n \n /** Schema generation */\n schema: z.object({\n /** Auto-generate types from Objects */\n autoGenerateTypes: z.boolean().default(true).describe('Auto-generate types from Objects'),\n \n /** Type configurations */\n types: z.array(GraphQLTypeConfigSchema).optional().describe('Type configurations'),\n \n /** Query configurations */\n queries: z.array(GraphQLQueryConfigSchema).optional().describe('Query configurations'),\n \n /** Mutation configurations */\n mutations: z.array(GraphQLMutationConfigSchema).optional().describe('Mutation configurations'),\n \n /** Subscription configurations */\n subscriptions: z.array(GraphQLSubscriptionConfigSchema).optional().describe('Subscription configurations'),\n \n /** Custom resolvers */\n resolvers: z.array(GraphQLResolverConfigSchema).optional().describe('Custom resolver configurations'),\n \n /** Custom directives */\n directives: z.array(GraphQLDirectiveConfigSchema).optional().describe('Custom directive configurations'),\n }).optional().describe('Schema generation configuration'),\n \n /** DataLoader configurations */\n dataLoaders: z.array(GraphQLDataLoaderConfigSchema).optional().describe('DataLoader configurations'),\n \n /** Security configuration */\n security: z.object({\n /** Query depth limiting */\n depthLimit: GraphQLQueryDepthLimitSchema.optional().describe('Query depth limiting'),\n \n /** Query complexity */\n complexity: GraphQLQueryComplexitySchema.optional().describe('Query complexity calculation'),\n \n /** Rate limiting */\n rateLimit: GraphQLRateLimitSchema.optional().describe('Rate limiting'),\n \n /** Persisted queries */\n persistedQueries: GraphQLPersistedQuerySchema.optional().describe('Persisted queries'),\n }).optional().describe('Security configuration'),\n\n /** Federation configuration */\n federation: FederationGatewaySchema.optional().describe('GraphQL Federation gateway configuration'),\n});\n\nexport const GraphQLConfig = Object.assign(GraphQLConfigSchema, {\n create: >(config: T) => config,\n});\n\nexport type GraphQLConfig = z.infer;\nexport type GraphQLConfigInput = z.input;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to map ObjectQL field type to GraphQL scalar type\n */\nexport const mapFieldTypeToGraphQL = (fieldType: z.infer): string => {\n const mapping: Record = {\n // Core Text\n 'text': 'String',\n 'textarea': 'String',\n 'email': 'Email',\n 'url': 'URL',\n 'phone': 'PhoneNumber',\n 'password': 'String',\n \n // Rich Content\n 'markdown': 'String',\n 'html': 'String',\n 'richtext': 'String',\n \n // Numbers\n 'number': 'Float',\n 'currency': 'Currency',\n 'percent': 'Float',\n \n // Date & Time\n 'date': 'Date',\n 'datetime': 'DateTime',\n 'time': 'Time',\n \n // Logic\n 'boolean': 'Boolean',\n 'toggle': 'Boolean',\n \n // Selection\n 'select': 'String',\n 'multiselect': '[String]',\n 'radio': 'String',\n 'checkboxes': '[String]',\n \n // Relational\n 'lookup': 'ID',\n 'master_detail': 'ID',\n 'tree': 'ID',\n \n // Media\n 'image': 'URL',\n 'file': 'URL',\n 'avatar': 'URL',\n 'video': 'URL',\n 'audio': 'URL',\n \n // Calculated\n 'formula': 'String',\n 'summary': 'Float',\n 'autonumber': 'String',\n \n // Enhanced Types\n 'location': 'JSONObject',\n 'address': 'JSONObject',\n 'code': 'String',\n 'json': 'JSON',\n 'color': 'String',\n 'rating': 'Float',\n 'slider': 'Float',\n 'signature': 'String',\n 'qrcode': 'String',\n 'progress': 'Float',\n 'tags': '[String]',\n \n // AI/ML\n 'vector': '[Float]',\n };\n \n return mapping[fieldType] || 'String';\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ApiErrorSchema, BaseResponseSchema, RecordDataSchema } from './contract.zod';\n\n/**\n * Batch Operations API\n * \n * Provides efficient bulk data operations with transaction support.\n * Implements P0/P1 requirements for ObjectStack kernel.\n * \n * Features:\n * - Batch create/update/delete operations\n * - Atomic transaction support (all-or-none)\n * - Partial success handling\n * - Detailed error reporting per record\n * \n * Industry alignment: Salesforce Bulk API, Microsoft Dynamics Bulk Operations\n */\n\n// ==========================================\n// Batch Operation Types\n// ==========================================\n\n/**\n * Batch Operation Type Enum\n * Defines the type of batch operation to perform\n */\nexport const BatchOperationType = z.enum([\n 'create', // Batch insert\n 'update', // Batch update\n 'upsert', // Batch upsert (insert or update based on external ID)\n 'delete', // Batch delete\n]);\n\nexport type BatchOperationType = z.infer;\n\n// ==========================================\n// Batch Request Schemas\n// ==========================================\n\n/**\n * Batch Record Schema\n * Individual record in a batch operation\n */\nexport const BatchRecordSchema = z.object({\n id: z.string().optional().describe('Record ID (required for update/delete)'),\n data: RecordDataSchema.optional().describe('Record data (required for create/update/upsert)'),\n externalId: z.string().optional().describe('External ID for upsert matching'),\n});\n\nexport type BatchRecord = z.infer;\n\n/**\n * Batch Operation Options Schema\n * Configuration options for batch operations\n */\nexport const BatchOptionsSchema = z.object({\n atomic: z.boolean().optional().default(true).describe('If true, rollback entire batch on any failure (transaction mode)'),\n returnRecords: z.boolean().optional().default(false).describe('If true, return full record data in response'),\n continueOnError: z.boolean().optional().default(false).describe('If true (and atomic=false), continue processing remaining records after errors'),\n validateOnly: z.boolean().optional().default(false).describe('If true, validate records without persisting changes (dry-run mode)'),\n});\n\nexport type BatchOptions = z.infer;\n\n/**\n * Batch Update Request Schema\n * Request payload for batch update operations\n * \n * @example\n * // POST /api/v1/data/{object}/batch\n * {\n * \"operation\": \"update\",\n * \"records\": [\n * { \"id\": \"1\", \"data\": { \"name\": \"Updated Name 1\", \"status\": \"active\" } },\n * { \"id\": \"2\", \"data\": { \"name\": \"Updated Name 2\", \"status\": \"active\" } }\n * ],\n * \"options\": {\n * \"atomic\": true,\n * \"returnRecords\": true\n * }\n * }\n */\nexport const BatchUpdateRequestSchema = z.object({\n operation: BatchOperationType.describe('Type of batch operation'),\n records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to process (max 200 per batch)'),\n options: BatchOptionsSchema.optional().describe('Batch operation options'),\n});\n\nexport type BatchUpdateRequest = z.input;\n\n/**\n * Simplified Batch Update Request (for updateMany API)\n * Simplified request for batch updates without operation field\n * \n * @example\n * // POST /api/v1/data/{object}/updateMany\n * {\n * \"records\": [\n * { \"id\": \"1\", \"data\": { \"name\": \"Updated Name 1\" } },\n * { \"id\": \"2\", \"data\": { \"name\": \"Updated Name 2\" } }\n * ],\n * \"options\": { \"atomic\": true }\n * }\n */\nexport const UpdateManyRequestSchema = z.object({\n records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to update (max 200 per batch)'),\n options: BatchOptionsSchema.optional().describe('Update options'),\n});\n\nexport type UpdateManyRequest = z.input;\n\n// ==========================================\n// Batch Response Schemas\n// ==========================================\n\n/**\n * Batch Operation Result Schema\n * Result for a single record in a batch operation\n */\nexport const BatchOperationResultSchema = z.object({\n id: z.string().optional().describe('Record ID if operation succeeded'),\n success: z.boolean().describe('Whether this record was processed successfully'),\n errors: z.array(ApiErrorSchema).optional().describe('Array of errors if operation failed'),\n data: RecordDataSchema.optional().describe('Full record data (if returnRecords=true)'),\n index: z.number().optional().describe('Index of the record in the request array'),\n});\n\nexport type BatchOperationResult = z.infer;\n\n/**\n * Batch Update Response Schema\n * Response payload for batch operations\n * \n * @example Success Response\n * {\n * \"success\": true,\n * \"operation\": \"update\",\n * \"total\": 2,\n * \"succeeded\": 2,\n * \"failed\": 0,\n * \"results\": [\n * { \"id\": \"1\", \"success\": true, \"index\": 0 },\n * { \"id\": \"2\", \"success\": true, \"index\": 1 }\n * ],\n * \"meta\": {\n * \"timestamp\": \"2026-01-29T12:00:00Z\",\n * \"duration\": 150\n * }\n * }\n * \n * @example Partial Success Response (atomic=false)\n * {\n * \"success\": false,\n * \"operation\": \"update\",\n * \"total\": 2,\n * \"succeeded\": 1,\n * \"failed\": 1,\n * \"results\": [\n * { \"id\": \"1\", \"success\": true, \"index\": 0 },\n * { \n * \"success\": false, \n * \"index\": 1,\n * \"errors\": [{ \"code\": \"validation_error\", \"message\": \"Invalid email format\" }]\n * }\n * ],\n * \"meta\": {\n * \"timestamp\": \"2026-01-29T12:00:00Z\"\n * }\n * }\n */\nexport const BatchUpdateResponseSchema = BaseResponseSchema.extend({\n operation: BatchOperationType.optional().describe('Operation type that was performed'),\n total: z.number().describe('Total number of records in the batch'),\n succeeded: z.number().describe('Number of records that succeeded'),\n failed: z.number().describe('Number of records that failed'),\n results: z.array(BatchOperationResultSchema).describe('Detailed results for each record'),\n});\n\nexport type BatchUpdateResponse = z.infer;\n\n// ==========================================\n// Batch Delete Schemas\n// ==========================================\n\n/**\n * Batch Delete Request Schema\n * Simplified request for batch delete operations\n * \n * @example\n * // POST /api/v1/data/{object}/deleteMany\n * {\n * \"ids\": [\"1\", \"2\", \"3\"],\n * \"options\": { \"atomic\": true }\n * }\n */\nexport const DeleteManyRequestSchema = z.object({\n ids: z.array(z.string()).min(1).max(200).describe('Array of record IDs to delete (max 200)'),\n options: BatchOptionsSchema.optional().describe('Delete options'),\n});\n\nexport type DeleteManyRequest = z.infer;\n\n// ==========================================\n// API Contract Exports\n// ==========================================\n\n/**\n * Batch API Contracts\n * Standardized contracts for batch operations\n */\nexport const BatchApiContracts = {\n batchOperation: {\n input: BatchUpdateRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n updateMany: {\n input: UpdateManyRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n deleteMany: {\n input: DeleteManyRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n};\n\n/**\n * Batch Configuration Schema\n * \n * Configuration for enabling batch operations API.\n */\nexport const BatchConfigSchema = z.object({\n /** Enable batch operations */\n enabled: z.boolean().default(true).describe('Enable batch operations'),\n \n /** Maximum records per batch */\n maxRecordsPerBatch: z.number().int().min(1).max(1000).default(200).describe('Maximum records per batch'),\n \n /** Default options */\n defaultOptions: BatchOptionsSchema.optional().describe('Default batch options'),\n}).passthrough(); // Allow additional properties\n\nexport type BatchConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * HTTP Metadata Cache Protocol\n * \n * Implements efficient HTTP-level metadata caching with ETag support.\n * Implements P0 requirement for ObjectStack kernel.\n * \n * ## Caching in ObjectStack\n * \n * **HTTP Cache (`api/http-cache.zod.ts`) - This File**\n * - **Purpose**: Cache API responses at HTTP protocol level\n * - **Technologies**: HTTP headers (ETag, Last-Modified, Cache-Control), CDN\n * - **Configuration**: Cache-Control headers, validation tokens\n * - **Use case**: Reduce API response time for repeated metadata requests\n * - **Scope**: HTTP layer, client-server communication\n * \n * **Application Cache (`system/cache.zod.ts`)**\n * - **Purpose**: Cache computed data, query results, aggregations\n * - **Technologies**: Redis, Memcached, in-memory LRU\n * - **Configuration**: TTL, eviction policies, cache warming\n * - **Use case**: Cache expensive database queries, computed values\n * - **Scope**: Application layer, server-side data storage\n * \n * ## Features\n * - ETag-based conditional requests (HTTP 304 Not Modified)\n * - Cache-Control directives\n * - Metadata versioning\n * - Selective cache invalidation\n * \n * Industry alignment: HTTP Caching (RFC 7234), Salesforce Metadata API\n * \n * @see ../../system/cache.zod.ts for application-level caching\n */\n\n// ==========================================\n// Cache Control Headers\n// ==========================================\n\n/**\n * Cache Control Directive Enum\n * Standard HTTP cache control directives\n */\nexport const CacheDirective = z.enum([\n 'public', // Cacheable by any cache\n 'private', // Cacheable only by user-agent\n 'no-cache', // Must revalidate with server\n 'no-store', // Never cache\n 'must-revalidate', // Must revalidate stale responses\n 'max-age', // Maximum cache age in seconds\n]);\n\nexport type CacheDirective = z.infer;\n\n/**\n * Cache Control Schema\n * HTTP cache control configuration\n * \n * @example\n * {\n * \"directives\": [\"public\", \"max-age\"],\n * \"maxAge\": 3600,\n * \"staleWhileRevalidate\": 86400\n * }\n */\nexport const CacheControlSchema = z.object({\n directives: z.array(CacheDirective).describe('Cache control directives'),\n maxAge: z.number().optional().describe('Maximum cache age in seconds'),\n staleWhileRevalidate: z.number().optional().describe('Allow serving stale content while revalidating (seconds)'),\n staleIfError: z.number().optional().describe('Allow serving stale content on error (seconds)'),\n});\n\nexport type CacheControl = z.infer;\n\n// ==========================================\n// ETag Support\n// ==========================================\n\n/**\n * ETag Schema\n * Entity tag for cache validation\n * \n * ETags can be:\n * - Strong: Exact match required (e.g., \"686897696a7c876b7e\")\n * - Weak: Semantic equivalence (e.g., W/\"686897696a7c876b7e\")\n */\nexport const ETagSchema = z.object({\n value: z.string().describe('ETag value (hash or version identifier)'),\n weak: z.boolean().optional().default(false).describe('Whether this is a weak ETag'),\n});\n\nexport type ETag = z.infer;\n\n// ==========================================\n// Metadata Cache Request\n// ==========================================\n\n/**\n * Metadata Cache Request Schema\n * Request with cache validation headers\n * \n * @example\n * // GET /api/v1/metadata/objects/account\n * // Headers:\n * // If-None-Match: \"686897696a7c876b7e\"\n * // If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT\n */\nexport const MetadataCacheRequestSchema = z.object({\n ifNoneMatch: z.string().optional().describe('ETag value for conditional request (If-None-Match header)'),\n ifModifiedSince: z.string().datetime().optional().describe('Timestamp for conditional request (If-Modified-Since header)'),\n cacheControl: CacheControlSchema.optional().describe('Client cache control preferences'),\n});\n\nexport type MetadataCacheRequest = z.infer;\n\n// ==========================================\n// Metadata Cache Response\n// ==========================================\n\n/**\n * Metadata Cache Response Schema\n * Response with cache control headers\n * \n * @example Success Response (200 OK)\n * {\n * \"data\": { \"object\": \"account\" },\n * \"etag\": {\n * \"value\": \"686897696a7c876b7e\",\n * \"weak\": false\n * },\n * \"lastModified\": \"2026-01-29T12:00:00Z\",\n * \"cacheControl\": {\n * \"directives\": [\"public\", \"max-age\"],\n * \"maxAge\": 3600\n * }\n * }\n * \n * @example Not Modified Response (304 Not Modified)\n * {\n * \"notModified\": true,\n * \"etag\": {\n * \"value\": \"686897696a7c876b7e\"\n * }\n * }\n */\nexport const MetadataCacheResponseSchema = z.object({\n data: z.unknown().optional().describe('Metadata payload (omitted for 304 Not Modified)'),\n etag: ETagSchema.optional().describe('ETag for this resource version'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n cacheControl: CacheControlSchema.optional().describe('Cache control directives'),\n notModified: z.boolean().optional().default(false).describe('True if resource has not been modified (304 response)'),\n version: z.string().optional().describe('Metadata version identifier'),\n});\n\nexport type MetadataCacheResponse = z.infer;\n\n// ==========================================\n// Metadata Cache Invalidation\n// ==========================================\n\n/**\n * Cache Invalidation Target Enum\n * Specifies what to invalidate\n */\nexport const CacheInvalidationTarget = z.enum([\n 'all', // Invalidate all cached metadata\n 'object', // Invalidate specific object metadata\n 'field', // Invalidate specific field metadata\n 'permission', // Invalidate permission metadata\n 'layout', // Invalidate layout metadata\n 'custom', // Custom invalidation pattern\n]);\n\nexport type CacheInvalidationTarget = z.infer;\n\n/**\n * Cache Invalidation Request Schema\n * Request to invalidate cached metadata\n * \n * @example\n * // POST /api/v1/metadata/cache/invalidate\n * {\n * \"target\": \"object\",\n * \"identifiers\": [\"account\", \"contact\"],\n * \"cascade\": true\n * }\n */\nexport const CacheInvalidationRequestSchema = z.object({\n target: CacheInvalidationTarget.describe('What to invalidate'),\n identifiers: z.array(z.string()).optional().describe('Specific resources to invalidate (e.g., object names)'),\n cascade: z.boolean().optional().default(false).describe('If true, invalidate dependent resources'),\n pattern: z.string().optional().describe('Pattern for custom invalidation (supports wildcards)'),\n});\n\nexport type CacheInvalidationRequest = z.infer;\n\n/**\n * Cache Invalidation Response Schema\n * Response for cache invalidation\n * \n * @example\n * {\n * \"success\": true,\n * \"invalidated\": 5,\n * \"targets\": [\"account\", \"contact\", \"opportunity\"]\n * }\n */\nexport const CacheInvalidationResponseSchema = z.object({\n success: z.boolean().describe('Whether invalidation succeeded'),\n invalidated: z.number().describe('Number of cache entries invalidated'),\n targets: z.array(z.string()).optional().describe('List of invalidated resources'),\n});\n\nexport type CacheInvalidationResponse = z.infer;\n\n// ==========================================\n// Metadata Cache API Methods\n// ==========================================\n\n/**\n * Metadata Cache API Client Interface\n * \n * @example Usage\n * // Get metadata with cache support\n * const response = await client.meta.getCached('account', {\n * ifNoneMatch: '\"686897696a7c876b7e\"'\n * });\n * \n * if (response.notModified) {\n * // Use cached version\n * } else {\n * // Update cache with response.data\n * cache.set('account', response.data, {\n * etag: response.etag?.value,\n * maxAge: response.cacheControl?.maxAge\n * });\n * }\n */\nexport const MetadataCacheApi = {\n getCached: {\n input: MetadataCacheRequestSchema,\n output: MetadataCacheResponseSchema,\n },\n invalidate: {\n input: CacheInvalidationRequestSchema,\n output: CacheInvalidationResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Standardized Error Codes Protocol\n * \n * Implements P0 requirement for ObjectStack kernel.\n * Provides consistent, machine-readable error codes across the platform.\n * \n * Features:\n * - Categorized error codes (validation, authentication, authorization, etc.)\n * - HTTP status code mapping\n * - Localization support\n * - Retry guidance\n * \n * Industry alignment: Google Cloud Errors, AWS Error Codes, Stripe API Errors\n */\n\n// ==========================================\n// Error Code Categories\n// ==========================================\n\n/**\n * Error Category Enum\n * High-level categorization of errors\n */\nexport const ErrorCategory = z.enum([\n 'validation', // Input validation errors (400)\n 'authentication', // Authentication failures (401)\n 'authorization', // Permission denied errors (403)\n 'not_found', // Resource not found (404)\n 'conflict', // Resource conflict (409)\n 'rate_limit', // Rate limiting (429)\n 'server', // Internal server errors (500)\n 'external', // External service errors (502/503)\n 'maintenance', // Planned maintenance (503)\n]);\n\nexport type ErrorCategory = z.infer;\n\n// ==========================================\n// Standard Error Codes\n// ==========================================\n\n/**\n * Standard Error Code Enum\n * Machine-readable error codes for common error scenarios\n */\nexport const StandardErrorCode = z.enum([\n // Validation Errors (400)\n 'validation_error', // Generic validation failure\n 'invalid_field', // Invalid field value\n 'missing_required_field', // Required field missing\n 'invalid_format', // Field format invalid (e.g., email, date)\n 'value_too_long', // Field value exceeds max length\n 'value_too_short', // Field value below min length\n 'value_out_of_range', // Numeric value out of range\n 'invalid_reference', // Invalid foreign key reference\n 'duplicate_value', // Unique constraint violation\n 'invalid_query', // Malformed query syntax\n 'invalid_filter', // Invalid filter expression\n 'invalid_sort', // Invalid sort specification\n 'max_records_exceeded', // Query would return too many records\n \n // Authentication Errors (401)\n 'unauthenticated', // No valid authentication provided\n 'invalid_credentials', // Wrong username/password\n 'expired_token', // Authentication token expired\n 'invalid_token', // Authentication token invalid\n 'session_expired', // User session expired\n 'mfa_required', // Multi-factor authentication required\n 'email_not_verified', // Email verification required\n \n // Authorization Errors (403)\n 'permission_denied', // User lacks required permission\n 'insufficient_privileges', // Operation requires higher privileges\n 'field_not_accessible', // Field-level security restriction\n 'record_not_accessible', // Sharing rule restriction\n 'license_required', // Feature requires license\n 'ip_restricted', // IP address not allowed\n 'time_restricted', // Access outside allowed time window\n \n // Not Found Errors (404)\n 'resource_not_found', // Generic resource not found\n 'object_not_found', // Object/table not found\n 'record_not_found', // Record with given ID not found\n 'field_not_found', // Field not found in object\n 'endpoint_not_found', // API endpoint not found\n \n // Conflict Errors (409)\n 'resource_conflict', // Generic resource conflict\n 'concurrent_modification', // Record modified by another user\n 'delete_restricted', // Cannot delete due to dependencies\n 'duplicate_record', // Record already exists\n 'lock_conflict', // Record is locked by another process\n \n // Rate Limiting (429)\n 'rate_limit_exceeded', // Too many requests\n 'quota_exceeded', // API quota exceeded\n 'concurrent_limit_exceeded', // Too many concurrent requests\n \n // Server Errors (500)\n 'internal_error', // Generic internal server error\n 'database_error', // Database operation failed\n 'timeout', // Operation timed out\n 'service_unavailable', // Service temporarily unavailable\n 'not_implemented', // Feature not yet implemented\n \n // External Service Errors (502/503)\n 'external_service_error', // External API call failed\n 'integration_error', // Integration service error\n 'webhook_delivery_failed', // Webhook delivery failed\n \n // Batch Operation Errors\n 'batch_partial_failure', // Batch operation partially succeeded\n 'batch_complete_failure', // Batch operation completely failed\n 'transaction_failed', // Transaction rolled back\n]);\n\nexport type StandardErrorCode = z.infer;\n\n// ==========================================\n// Enhanced Error Schema\n// ==========================================\n\n/**\n * HTTP Status Code mapping for error categories\n */\nexport const ErrorHttpStatusMap: Record = {\n validation: 400,\n authentication: 401,\n authorization: 403,\n not_found: 404,\n conflict: 409,\n rate_limit: 429,\n server: 500,\n external: 502,\n maintenance: 503,\n};\n\n/**\n * Retry Strategy Enum\n * Guidance on whether to retry failed requests\n */\nexport const RetryStrategy = z.enum([\n 'no_retry', // Do not retry (permanent failure)\n 'retry_immediate', // Retry immediately\n 'retry_backoff', // Retry with exponential backoff\n 'retry_after', // Retry after specified delay\n]);\n\nexport type RetryStrategy = z.infer;\n\n/**\n * Field Error Schema\n * Detailed error for a specific field\n */\nexport const FieldErrorSchema = z.object({\n field: z.string().describe('Field path (supports dot notation)'),\n code: StandardErrorCode.describe('Error code for this field'),\n message: z.string().describe('Human-readable error message'),\n value: z.unknown().optional().describe('The invalid value that was provided'),\n constraint: z.unknown().optional().describe('The constraint that was violated (e.g., max length)'),\n});\n\nexport type FieldError = z.infer;\n\n/**\n * Enhanced API Error Schema\n * Standardized error response with detailed metadata\n * \n * @example Validation Error\n * {\n * \"code\": \"validation_error\",\n * \"message\": \"Validation failed for 2 fields\",\n * \"category\": \"validation\",\n * \"httpStatus\": 400,\n * \"retryable\": false,\n * \"retryStrategy\": \"no_retry\",\n * \"details\": {\n * \"fieldErrors\": [\n * {\n * \"field\": \"email\",\n * \"code\": \"invalid_format\",\n * \"message\": \"Email format is invalid\",\n * \"value\": \"not-an-email\"\n * },\n * {\n * \"field\": \"age\",\n * \"code\": \"value_out_of_range\",\n * \"message\": \"Age must be between 0 and 120\",\n * \"value\": 150,\n * \"constraint\": { \"min\": 0, \"max\": 120 }\n * }\n * ]\n * },\n * \"timestamp\": \"2026-01-29T12:00:00Z\",\n * \"requestId\": \"req_123456\",\n * \"documentation\": \"https://docs.objectstack.dev/errors/validation_error\"\n * }\n * \n * @example Rate Limit Error\n * {\n * \"code\": \"rate_limit_exceeded\",\n * \"message\": \"Rate limit exceeded. Try again in 60 seconds.\",\n * \"category\": \"rate_limit\",\n * \"httpStatus\": 429,\n * \"retryable\": true,\n * \"retryStrategy\": \"retry_after\",\n * \"retryAfter\": 60,\n * \"details\": {\n * \"limit\": 1000,\n * \"remaining\": 0,\n * \"resetAt\": \"2026-01-29T13:00:00Z\"\n * }\n * }\n */\nexport const EnhancedApiErrorSchema = z.object({\n code: StandardErrorCode.describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n category: ErrorCategory.optional().describe('Error category'),\n httpStatus: z.number().optional().describe('HTTP status code'),\n retryable: z.boolean().default(false).describe('Whether the request can be retried'),\n retryStrategy: RetryStrategy.optional().describe('Recommended retry strategy'),\n retryAfter: z.number().optional().describe('Seconds to wait before retrying'),\n details: z.unknown().optional().describe('Additional error context'),\n fieldErrors: z.array(FieldErrorSchema).optional().describe('Field-specific validation errors'),\n timestamp: z.string().datetime().optional().describe('When the error occurred'),\n requestId: z.string().optional().describe('Request ID for tracking'),\n traceId: z.string().optional().describe('Distributed trace ID'),\n documentation: z.string().url().optional().describe('URL to error documentation'),\n helpText: z.string().optional().describe('Suggested actions to resolve the error'),\n});\n\nexport type EnhancedApiError = z.infer;\n\n// ==========================================\n// Error Response Schema\n// ==========================================\n\n/**\n * Standardized Error Response Schema\n * Complete error response envelope\n * \n * @example\n * {\n * \"success\": false,\n * \"error\": {\n * \"code\": \"permission_denied\",\n * \"message\": \"You do not have permission to update this record\",\n * \"category\": \"authorization\",\n * \"httpStatus\": 403,\n * \"retryable\": false\n * }\n * }\n */\nexport const ErrorResponseSchema = z.object({\n success: z.literal(false).describe('Always false for error responses'),\n error: EnhancedApiErrorSchema.describe('Error details'),\n meta: z.object({\n timestamp: z.string().datetime().optional(),\n requestId: z.string().optional(),\n traceId: z.string().optional(),\n }).optional().describe('Response metadata'),\n});\n\nexport type ErrorResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module ui/sharing\n *\n * Sharing & Embedding Protocol\n *\n * Defines schemas for public link sharing, embed configuration,\n * domain restrictions, and password protection for apps, pages, and forms.\n */\n\nimport { z } from 'zod';\n\n/**\n * Sharing Config Schema\n * Configuration for public sharing of an app, page, or form.\n * Supports public links, password protection, domain restrictions, and expiration.\n */\nexport const SharingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable public sharing'),\n publicLink: z.string().optional().describe('Generated public share URL'),\n password: z.string().optional().describe('Password required to access shared link'),\n allowedDomains: z.array(z.string()).optional()\n .describe('Restrict access to specific email domains (e.g. [\"example.com\"])'),\n expiresAt: z.string().optional()\n .describe('Expiration date/time in ISO 8601 format'),\n allowAnonymous: z.boolean().optional().default(false)\n .describe('Allow access without authentication'),\n});\n\n/**\n * Embed Config Schema\n * Configuration for iframe embedding of an app, page, or form.\n * Supports origin restrictions, display options, and responsive sizing.\n */\nexport const EmbedConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable iframe embedding'),\n allowedOrigins: z.array(z.string()).optional()\n .describe('Allowed iframe parent origins (e.g. [\"https://example.com\"])'),\n width: z.string().optional().default('100%').describe('Embed width (CSS value)'),\n height: z.string().optional().default('600px').describe('Embed height (CSS value)'),\n showHeader: z.boolean().optional().default(true).describe('Show interface header in embed'),\n showNavigation: z.boolean().optional().default(false).describe('Show navigation in embed'),\n responsive: z.boolean().optional().default(true).describe('Enable responsive resizing'),\n});\n\n// Type Exports\nexport type SharingConfig = z.infer;\nexport type EmbedConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Breakpoint Name Enum\n * Matches the breakpoint names defined in theme.zod.ts BreakpointsSchema.\n */\nexport const BreakpointName = z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl']);\n\nexport type BreakpointName = z.infer;\n\n/**\n * Responsive Configuration Schema\n *\n * Provides responsive layout configuration for UI components.\n * Maps breakpoint names to layout behavior (columns, visibility, order).\n *\n * Aligned with theme.zod.ts BreakpointsSchema for a unified responsive system.\n *\n * @example\n * ```typescript\n * const config: ResponsiveConfig = {\n * columns: { xs: 12, sm: 6, lg: 4 },\n * hiddenOn: ['xs'],\n * order: { xs: 2, lg: 1 },\n * };\n * ```\n */\n/**\n * Breakpoint Column Map Schema\n * Maps breakpoint names to grid column counts (1-12).\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointColumnMapSchema = z.object({\n xs: z.number().min(1).max(12).optional(),\n sm: z.number().min(1).max(12).optional(),\n md: z.number().min(1).max(12).optional(),\n lg: z.number().min(1).max(12).optional(),\n xl: z.number().min(1).max(12).optional(),\n '2xl': z.number().min(1).max(12).optional(),\n}).describe('Grid columns per breakpoint (1-12)');\n\n/**\n * Breakpoint Order Map Schema\n * Maps breakpoint names to display order numbers.\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointOrderMapSchema = z.object({\n xs: z.number().optional(),\n sm: z.number().optional(),\n md: z.number().optional(),\n lg: z.number().optional(),\n xl: z.number().optional(),\n '2xl': z.number().optional(),\n}).describe('Display order per breakpoint');\n\nexport const ResponsiveConfigSchema = z.object({\n /** Minimum breakpoint for visibility */\n breakpoint: BreakpointName.optional()\n .describe('Minimum breakpoint for visibility'),\n\n /** Hide on specific breakpoints */\n hiddenOn: z.array(BreakpointName).optional()\n .describe('Hide on these breakpoints'),\n\n /** Grid columns per breakpoint (1-12 column grid) */\n columns: BreakpointColumnMapSchema.optional().describe('Grid columns per breakpoint'),\n\n /** Display order per breakpoint */\n order: BreakpointOrderMapSchema.optional().describe('Display order per breakpoint'),\n}).describe('Responsive layout configuration');\n\nexport type ResponsiveConfig = z.infer;\n\n/**\n * Performance Configuration Schema\n *\n * Defines performance optimization settings for UI components\n * such as lazy loading, virtual scrolling, and caching.\n *\n * @example\n * ```typescript\n * const perf: PerformanceConfig = {\n * lazyLoad: true,\n * virtualScroll: { enabled: true, itemHeight: 40, overscan: 5 },\n * cacheStrategy: 'stale-while-revalidate',\n * prefetch: true,\n * };\n * ```\n */\nexport const PerformanceConfigSchema = z.object({\n /** Enable lazy loading for this component */\n lazyLoad: z.boolean().optional()\n .describe('Enable lazy loading (defer rendering until visible)'),\n\n /** Virtual scrolling configuration for large datasets */\n virtualScroll: z.object({\n enabled: z.boolean().default(false).describe('Enable virtual scrolling'),\n itemHeight: z.number().optional().describe('Fixed item height in pixels (for estimation)'),\n overscan: z.number().optional().describe('Number of extra items to render outside viewport'),\n }).optional().describe('Virtual scrolling configuration'),\n\n /** Client-side caching strategy */\n cacheStrategy: z.enum([\n 'none',\n 'cache-first',\n 'network-first',\n 'stale-while-revalidate',\n ]).optional().describe('Client-side data caching strategy'),\n\n /** Enable data prefetching */\n prefetch: z.boolean().optional()\n .describe('Prefetch data before component is visible'),\n\n /** Maximum number of items to render before pagination */\n pageSize: z.number().optional()\n .describe('Number of items per page for pagination'),\n\n /** Debounce interval for user interactions (ms) */\n debounceMs: z.number().optional()\n .describe('Debounce interval for user interactions in milliseconds'),\n}).describe('Performance optimization configuration');\n\nexport type PerformanceConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema } from './sharing.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * HTTP Method Enum & HTTP Request Schema\n * Migrated to shared/http.zod.ts. Re-exported here for backward compatibility.\n */\nimport { HttpMethodSchema, HttpRequestSchema } from '../shared/http.zod';\nexport { HttpMethodSchema, HttpRequestSchema };\n\n/**\n * View Data Source Configuration\n * Supports three modes:\n * 1. 'object': Standard Protocol - Auto-connects to ObjectStack Metadata and Data APIs\n * 2. 'api': Custom API - Explicitly provided API URLs\n * 3. 'value': Static Data - Hardcoded data array\n */\nexport const ViewDataSchema = z.discriminatedUnion('provider', [\n z.object({\n provider: z.literal('object'),\n object: z.string().describe('Target object name'),\n }),\n z.object({\n provider: z.literal('api'),\n read: HttpRequestSchema.optional().describe('Configuration for fetching data'),\n write: HttpRequestSchema.optional().describe('Configuration for submitting data (for forms/editable tables)'),\n }),\n z.object({\n provider: z.literal('value'),\n items: z.array(z.unknown()).describe('Static data array'),\n }),\n]);\n\n/**\n * View Filter Rule Schema\n * Standardized filter condition used in list views, tabs, and page-level filters.\n * Uses a declarative array-of-objects format: [{ field, operator, value }].\n *\n * @example\n * ```ts\n * filter: [\n * { field: 'status', operator: 'equals', value: 'active' },\n * { field: 'close_date', operator: 'this_quarter' },\n * ]\n * ```\n */\nexport const ViewFilterRuleSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n /** Filter operator */\n operator: z.string().describe('Filter operator (e.g. equals, not_equals, contains, this_quarter)'),\n /** Filter value (optional for unary operators like is_null, this_quarter) */\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Filter value'),\n}).describe('View filter rule');\n\nexport type ViewFilterRule = z.infer;\n\n/**\n * Column Summary Function Schema\n * Aggregation function for column footer (Airtable-style column summaries)\n */\nexport const ColumnSummarySchema = z.enum([\n 'none',\n 'count',\n 'count_empty',\n 'count_filled',\n 'count_unique',\n 'percent_empty',\n 'percent_filled',\n 'sum',\n 'avg',\n 'min',\n 'max',\n]).describe('Aggregation function for column footer summary');\n\n/**\n * List Column Configuration Schema\n * Detailed configuration for individual list view columns\n */\nexport const ListColumnSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n width: z.number().positive().optional().describe('Column width in pixels'),\n align: z.enum(['left', 'center', 'right']).optional().describe('Text alignment'),\n hidden: z.boolean().optional().describe('Hide column by default'),\n sortable: z.boolean().optional().describe('Allow sorting by this column'),\n resizable: z.boolean().optional().describe('Allow resizing this column'),\n wrap: z.boolean().optional().describe('Allow text wrapping'),\n type: z.string().optional().describe('Renderer type override (e.g., \"currency\", \"date\")'),\n\n /** Pinning (Airtable-style frozen columns) */\n pinned: z.enum(['left', 'right']).optional().describe('Pin/freeze column to left or right side'),\n\n /** Column Footer Summary (Airtable-style aggregation) */\n summary: ColumnSummarySchema.optional().describe('Footer aggregation function for this column'),\n\n /** Interaction */\n link: z.boolean().optional().describe('Functions as the primary navigation link (triggers View navigation)'),\n action: z.string().optional().describe('Registered Action ID to execute when clicked'),\n});\n\n/**\n * List View Selection Configuration\n */\nexport const SelectionConfigSchema = z.object({\n type: z.enum(['none', 'single', 'multiple']).default('none').describe('Selection mode'),\n});\n\n/**\n * List View Pagination Configuration\n */\nexport const PaginationConfigSchema = z.object({\n pageSize: z.number().int().positive().default(25).describe('Number of records per page'),\n pageSizeOptions: z.array(z.number().int().positive()).optional().describe('Available page size options'),\n});\n\n/**\n * Row Height / Density Schema (Airtable-style)\n * Controls the visual density of rows in a list view.\n */\nexport const RowHeightSchema = z.enum([\n 'compact', // Minimal padding, single line\n 'short', // Reduced padding\n 'medium', // Default padding\n 'tall', // Extra padding, multi-line preview\n 'extra_tall', // Maximum padding, rich content preview\n]).describe('Row height / density setting for list view');\n\n/**\n * Grouping Field Configuration\n * Defines a single grouping level for record grouping.\n */\nexport const GroupingFieldSchema = z.object({\n field: z.string().describe('Field name to group by'),\n order: z.enum(['asc', 'desc']).default('asc').describe('Group sort order'),\n collapsed: z.boolean().default(false).describe('Collapse groups by default'),\n});\n\n/**\n * Grouping Configuration Schema (Airtable-style)\n * Supports multi-level grouping for grid/gallery views.\n */\nexport const GroupingConfigSchema = z.object({\n fields: z.array(GroupingFieldSchema).min(1).describe('Fields to group by (supports up to 3 levels)'),\n}).describe('Record grouping configuration');\n\n/**\n * Gallery View Configuration (Airtable-style)\n * Configures card layout for gallery/card views.\n */\nexport const GalleryConfigSchema = z.object({\n coverField: z.string().optional().describe('Attachment/image field to display as card cover'),\n coverFit: z.enum(['cover', 'contain']).default('cover').describe('Image fit mode for card cover'),\n cardSize: z.enum(['small', 'medium', 'large']).default('medium').describe('Card size in gallery view'),\n titleField: z.string().optional().describe('Field to display as card title'),\n visibleFields: z.array(z.string()).optional().describe('Fields to display on card body'),\n}).describe('Gallery/card view configuration');\n\n/**\n * Timeline View Configuration (Airtable-style)\n * Configures timeline/chronological views.\n */\nexport const TimelineConfigSchema = z.object({\n startDateField: z.string().describe('Field for timeline item start date'),\n endDateField: z.string().optional().describe('Field for timeline item end date'),\n titleField: z.string().describe('Field to display as timeline item title'),\n groupByField: z.string().optional().describe('Field to group timeline rows'),\n colorField: z.string().optional().describe('Field to determine item color'),\n scale: z.enum(['hour', 'day', 'week', 'month', 'quarter', 'year']).default('week').describe('Default timeline scale'),\n}).describe('Timeline view configuration');\n\n/**\n * View Sharing Configuration (Airtable-style)\n * Defines who can see and modify a view.\n */\nexport const ViewSharingSchema = z.object({\n type: z.enum(['personal', 'collaborative']).default('collaborative').describe('View ownership type'),\n lockedBy: z.string().optional().describe('User who locked the view configuration'),\n}).describe('View sharing and access configuration');\n\n/**\n * Row Color Configuration (Airtable-style)\n * Defines how rows are colored based on field values.\n */\nexport const RowColorConfigSchema = z.object({\n field: z.string().describe('Field to derive color from (typically a select/status field)'),\n colors: z.record(z.string(), z.string()).optional().describe('Map of field value to color (hex/token)'),\n}).describe('Row color configuration based on field values');\n\n/**\n * Visualization Type Schema\n * Whitelist of visualization types the user can switch between.\n * Maps to Airtable's \"Visualizations\" setting in Appearance panel.\n */\nexport const VisualizationTypeSchema = z.enum([\n 'grid',\n 'kanban',\n 'gallery',\n 'calendar',\n 'timeline',\n 'gantt',\n 'map',\n]).describe('Visualization type that users can switch to');\n\n/**\n * User Actions Configuration Schema (Airtable Interface parity)\n * Controls which interactive actions are available to users in the view toolbar.\n * Each boolean toggles the corresponding toolbar element on/off.\n *\n * @see Airtable Interface → \"User actions\" panel\n */\nexport const UserActionsConfigSchema = z.object({\n sort: z.boolean().default(true).describe('Allow users to sort records'),\n search: z.boolean().default(true).describe('Allow users to search records'),\n filter: z.boolean().default(true).describe('Allow users to filter records'),\n rowHeight: z.boolean().default(true).describe('Allow users to toggle row height/density'),\n addRecordForm: z.boolean().default(false).describe('Add records through a form instead of inline'),\n buttons: z.array(z.string()).optional().describe('Custom action button IDs to show in the toolbar'),\n}).describe('User action toggles for the view toolbar');\n\n/**\n * Appearance Configuration Schema (Airtable Interface parity)\n * Controls visual presentation options for the view.\n *\n * @see Airtable Interface → \"Appearance\" panel\n */\nexport const AppearanceConfigSchema = z.object({\n showDescription: z.boolean().default(true).describe('Show the view description text'),\n allowedVisualizations: z.array(VisualizationTypeSchema).optional()\n .describe('Whitelist of visualization types users can switch between (e.g. [\"grid\", \"gallery\", \"kanban\"])'),\n}).describe('Appearance and visualization configuration');\n\n/**\n * View Tab Schema (Airtable Interface parity)\n * Defines a tab in a multi-tab view interface.\n * Each tab references a named list view and can be ordered, pinned, or set as default.\n *\n * @see Airtable Interface → \"Tabs\" panel\n */\nexport const ViewTabSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Tab identifier (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label'),\n icon: z.string().optional().describe('Tab icon name'),\n view: z.string().optional().describe('Referenced list view name from listViews'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Tab-specific filter criteria'),\n order: z.number().int().min(0).optional().describe('Tab display order'),\n pinned: z.boolean().default(false).describe('Pin tab (cannot be removed by users)'),\n isDefault: z.boolean().default(false).describe('Set as the default active tab'),\n visible: z.boolean().default(true).describe('Tab visibility'),\n}).describe('Tab configuration for multi-tab view interface');\n\n/**\n * Add Record Configuration Schema (Airtable Interface parity)\n * Configures the \"Add Record\" entry point for a list view.\n *\n * @see Airtable Interface → \"+ Add record\" button\n */\nexport const AddRecordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Show the add record entry point'),\n position: z.enum(['top', 'bottom', 'both']).default('bottom').describe('Position of the add record button'),\n mode: z.enum(['inline', 'form', 'modal']).default('inline').describe('How to add a new record'),\n formView: z.string().optional().describe('Named form view to use when mode is \"form\" or \"modal\"'),\n}).describe('Add record entry point configuration');\n\n/**\n * Kanban Settings\n */\nexport const KanbanConfigSchema = z.object({\n groupByField: z.string().describe('Field to group columns by (usually status/select)'),\n summarizeField: z.string().optional().describe('Field to sum at top of column (e.g. amount)'),\n columns: z.array(z.string()).describe('Fields to show on cards'),\n});\n\n/**\n * Calendar Settings\n */\nexport const CalendarConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string().optional(),\n titleField: z.string(),\n colorField: z.string().optional(),\n});\n\n/**\n * Gantt Settings\n */\nexport const GanttConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string(),\n titleField: z.string(),\n progressField: z.string().optional(),\n dependenciesField: z.string().optional(),\n});\n\n/**\n * Navigation Mode Enum\n * Defines how to navigate to the detail view from a list item.\n */\nexport const NavigationModeSchema = z.enum([\n 'page', // Navigate to a new route (default)\n 'drawer', // Open details in a side drawer/panel\n 'modal', // Open details in a modal dialog\n 'split', // Show details side-by-side with the list (master-detail)\n 'popover', // Show details in a popover (lightweight)\n 'new_window', // Open in new browser tab/window\n 'none' // No navigation (read-only list)\n]);\n\n/**\n * Navigation Configuration Schema\n */\nexport const NavigationConfigSchema = z.object({\n mode: NavigationModeSchema.default('page'),\n \n /** Target View Config */\n view: z.string().optional().describe('Name of the form view to use for details (e.g. \"summary_view\", \"edit_form\")'),\n \n /** Interaction Triggers */\n preventNavigation: z.boolean().default(false).describe('Disable standard navigation entirely'),\n openNewTab: z.boolean().default(false).describe('Force open in new tab (applies to page mode)'),\n \n /** Dimensions (for modal/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Width of the drawer/modal (e.g. \"600px\", \"50%\")'),\n});\n\n/**\n * List View Schema (Expanded)\n * Defines how a collection of records is displayed to the user.\n * \n * **NAMING CONVENTION:**\n * View names (when provided) are machine identifiers and must be lowercase snake_case.\n * \n * @example Standard Grid\n * {\n * name: \"all_active\",\n * label: \"All Active\",\n * type: \"grid\",\n * columns: [\"name\", \"status\", \"created_at\"],\n * filter: [[\"status\", \"=\", \"active\"]]\n * }\n * \n * @example Kanban Board\n * {\n * type: \"kanban\",\n * columns: [\"name\", \"amount\"],\n * kanban: {\n * groupByField: \"stage\",\n * summarizeField: \"amount\",\n * columns: [\"name\", \"close_date\"]\n * }\n * }\n */\nexport const ListViewSchema = z.object({\n name: SnakeCaseIdentifierSchema.optional().describe('Internal view name (lowercase snake_case)'),\n label: I18nLabelSchema.optional(), // Display label override (supports i18n)\n type: z.enum([\n 'grid', // Standard Data Table\n 'kanban', // Board / Columns\n 'gallery', // Card Deck / Masonry\n 'calendar', // Monthly/Weekly/Daily\n 'timeline', // Chronological Stream (Feed)\n 'gantt', // Project Timeline\n 'map' // Geospatial\n ]).default('grid'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n /** Shared Query Config */\n columns: z.union([\n z.array(z.string()), // Legacy: simple field names\n z.array(ListColumnSchema), // Enhanced: detailed column config\n ]).describe('Fields to display as columns'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Filter criteria (JSON Rules)'),\n sort: z.union([\n z.string(), //Legacy \"field desc\"\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional(),\n \n /** Search & Filter */\n searchableFields: z.array(z.string()).optional().describe('Fields enabled for search'),\n filterableFields: z.array(z.string()).optional().describe('Fields enabled for end-user filtering in the top bar'),\n\n /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */\n quickFilters: z.array(z.object({\n field: z.string().describe('Field name to filter by'),\n label: z.string().optional().describe('Display label for the chip'),\n operator: z.enum(['equals', 'not_equals', 'contains', 'in', 'is_null', 'is_not_null']).default('equals').describe('Filter operator'),\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Preset filter value'),\n })).optional().describe('One-click filter chips for quick record filtering'),\n\n /** Grid Features */\n resizable: z.boolean().optional().describe('Enable column resizing'),\n striped: z.boolean().optional().describe('Striped row styling'),\n bordered: z.boolean().optional().describe('Show borders'),\n\n /** Selection */\n selection: SelectionConfigSchema.optional().describe('Row selection configuration'),\n\n /** Navigation / Interaction */\n navigation: NavigationConfigSchema.optional().describe('Configuration for item click navigation (page, drawer, modal, etc.)'),\n\n /** Pagination */\n pagination: PaginationConfigSchema.optional().describe('Pagination configuration'),\n\n /** Type Specific Config */\n kanban: KanbanConfigSchema.optional(),\n calendar: CalendarConfigSchema.optional(),\n gantt: GanttConfigSchema.optional(),\n gallery: GalleryConfigSchema.optional(),\n timeline: TimelineConfigSchema.optional(),\n\n /** View Metadata (Airtable-style view management) */\n description: I18nLabelSchema.optional().describe('View description for documentation/tooltips'),\n sharing: ViewSharingSchema.optional().describe('View sharing and access configuration'),\n\n /** Row Height / Density (Airtable-style) */\n rowHeight: RowHeightSchema.optional().describe('Row height / density setting'),\n\n /** Record Grouping (Airtable-style) */\n grouping: GroupingConfigSchema.optional().describe('Group records by one or more fields'),\n\n /** Row Color (Airtable-style) */\n rowColor: RowColorConfigSchema.optional().describe('Color rows based on field value'),\n\n /** Field Visibility & Ordering per View (Airtable-style) */\n hiddenFields: z.array(z.string()).optional().describe('Fields to hide in this specific view'),\n fieldOrder: z.array(z.string()).optional().describe('Explicit field display order for this view'),\n\n /** Row & Bulk Actions */\n rowActions: z.array(z.string()).optional().describe('Actions available for individual row items'),\n bulkActions: z.array(z.string()).optional().describe('Actions available when multiple rows are selected'),\n\n /** Performance */\n virtualScroll: z.boolean().optional().describe('Enable virtual scrolling for large datasets'),\n\n /** Conditional Formatting */\n conditionalFormatting: z.array(z.object({\n condition: z.string().describe('Condition expression to evaluate'),\n style: z.record(z.string(), z.string()).describe('CSS styles to apply when condition is true'),\n })).optional().describe('Conditional formatting rules for list rows'),\n\n /** Inline Edit */\n inlineEdit: z.boolean().optional().describe('Allow inline editing of records directly in the list view'),\n\n /** Export */\n exportOptions: z.array(z.enum(['csv', 'xlsx', 'pdf', 'json'])).optional().describe('Available export format options'),\n\n /** User Actions (Airtable Interface parity) */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles for the view toolbar'),\n\n /** Appearance (Airtable Interface parity) */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** Tabs (Airtable Interface parity) */\n tabs: z.array(ViewTabSchema).optional().describe('Tab definitions for multi-tab view interface'),\n\n /** Add Record (Airtable Interface parity) */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record Count Display (Airtable Interface parity) */\n showRecordCount: z.boolean().optional().describe('Show record count at the bottom of the list'),\n\n /** Advanced: Allow Printing (Airtable Interface parity) */\n allowPrinting: z.boolean().optional().describe('Allow users to print the view'),\n\n /** Empty State */\n emptyState: z.object({\n title: I18nLabelSchema.optional(),\n message: I18nLabelSchema.optional(),\n icon: z.string().optional(),\n }).optional().describe('Empty state configuration when no records found'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the list view'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Form Field Configuration Schema\n * Detailed configuration for individual form fields\n */\nexport const FormFieldSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n helpText: I18nLabelSchema.optional().describe('Help/hint text'),\n readonly: z.boolean().optional().describe('Read-only override'),\n required: z.boolean().optional().describe('Required override'),\n hidden: z.boolean().optional().describe('Hidden override'),\n colSpan: z.number().int().min(1).max(4).optional().describe('Column span in grid layout (1-4)'),\n widget: z.string().optional().describe('Custom widget/component name'),\n dependsOn: z.string().optional().describe('Parent field name for cascading'),\n visibleOn: z.string().optional().describe('Visibility condition expression'),\n});\n\n/**\n * Form Layout Section\n */\nexport const FormSectionSchema = z.object({\n label: I18nLabelSchema.optional(),\n collapsible: z.boolean().default(false),\n collapsed: z.boolean().default(false),\n columns: z.enum(['1', '2', '3', '4']).default('2').transform(val => parseInt(val) as 1 | 2 | 3 | 4),\n fields: z.array(z.union([\n z.string(), // Legacy: simple field name\n FormFieldSchema, // Enhanced: detailed field config\n ])),\n});\n\n/**\n * Form View Schema\n * Defines the layout for creating or editing a single record.\n * \n * @example Simple Sectioned Form\n * {\n * type: \"simple\",\n * sections: [\n * {\n * label: \"General Info\",\n * columns: 2,\n * fields: [\"name\", \"status\"]\n * },\n * {\n * label: \"Details\",\n * fields: [\"description\", { field: \"priority\", widget: \"rating\" }]\n * }\n * ]\n * }\n */\nexport const FormViewSchema = z.object({\n type: z.enum([\n 'simple', // Single column or sections\n 'tabbed', // Tabs\n 'wizard', // Step by step\n 'split', // Master-Detail split\n 'drawer', // Side panel\n 'modal' // Dialog\n ]).default('simple'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n sections: z.array(FormSectionSchema).optional(), // For simple layout\n groups: z.array(FormSectionSchema).optional(), // Legacy support -> alias to sections\n\n /** Default Sort for Related Lists (e.g., sort child records by date) */\n defaultSort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n order: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n })).optional().describe('Default sort order for related list views within this form'),\n\n /** Public form sharing configuration */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration for this form'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the form view'),\n});\n\n/**\n * Master View Schema\n * Can define multiple named views.\n */\n/**\n * View Container Schema\n * Aggregates all view definitions for a specific object or context.\n * \n * @example\n * {\n * list: { type: \"grid\", columns: [\"name\"] },\n * form: { type: \"simple\", fields: [\"name\"] },\n * listViews: {\n * \"all\": { label: \"All\", filter: [] },\n * \"my\": { label: \"Mine\", filter: [[\"owner\", \"=\", \"{user_id}\"]] }\n * }\n * }\n */\nexport const ViewSchema = z.object({\n list: ListViewSchema.optional(), // Default list view\n form: FormViewSchema.optional(), // Default form view\n listViews: z.record(z.string(), ListViewSchema).optional().describe('Additional named list views'),\n formViews: z.record(z.string(), FormViewSchema).optional().describe('Additional named form views'),\n});\n\n/**\n * Type-safe factory for creating view definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const taskViews = defineView({\n * list: {\n * type: 'grid',\n * data: { provider: 'object', object: 'task' },\n * columns: ['subject', 'status', 'priority', 'due_date'],\n * },\n * form: {\n * type: 'simple',\n * sections: [{ label: 'Details', fields: [{ field: 'subject' }] }],\n * },\n * });\n * ```\n */\nexport function defineView(config: z.input): View {\n return ViewSchema.parse(config);\n}\n\nexport type View = z.infer;\nexport type ListView = z.infer;\nexport type FormView = z.infer;\nexport type FormSection = z.infer;\nexport type ListColumn = z.infer;\nexport type FormField = z.infer;\nexport type SelectionConfig = z.infer;\nexport type NavigationConfig = z.infer;\nexport type PaginationConfig = z.infer;\nexport type ViewData = z.infer;\nexport type HttpRequest = z.infer;\nexport type HttpMethod = z.infer;\nexport type ColumnSummary = z.infer;\nexport type RowHeight = z.infer;\nexport type GroupingConfig = z.infer;\nexport type GalleryConfig = z.infer;\nexport type TimelineConfig = z.infer;\nexport type ViewSharing = z.infer;\nexport type RowColorConfig = z.infer;\nexport type VisualizationType = z.infer;\nexport type UserActionsConfig = z.infer;\nexport type AppearanceConfig = z.infer;\nexport type ViewTab = z.infer;\nexport type AddRecordConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Row-Level Security (RLS) Protocol\n * \n * Implements fine-grained record-level access control inspired by PostgreSQL RLS\n * and Salesforce Criteria-Based Sharing Rules.\n * \n * ## Overview\n * \n * Row-Level Security (RLS) allows you to control which rows users can access\n * in database tables based on their identity and role. Unlike object-level\n * permissions (CRUD), RLS provides record-level filtering.\n * \n * ## Use Cases\n * \n * 1. **Multi-Tenant Data Isolation**\n * - Users only see records from their organization\n * - `using: \"tenant_id = current_user.tenant_id\"`\n * \n * 2. **Ownership-Based Access**\n * - Users only see records they own\n * - `using: \"owner_id = current_user.id\"`\n * \n * 3. **Department-Based Access**\n * - Users only see records from their department\n * - `using: \"department = current_user.department\"`\n * \n * 4. **Regional Access Control**\n * - Sales reps only see accounts in their territory\n * - `using: \"region IN (current_user.assigned_regions)\"`\n * \n * 5. **Time-Based Access**\n * - Users can only access active records\n * - `using: \"status = 'active' AND expiry_date > NOW()\"`\n * \n * ## PostgreSQL RLS Comparison\n * \n * PostgreSQL RLS Example:\n * ```sql\n * CREATE POLICY tenant_isolation ON accounts\n * FOR SELECT\n * USING (tenant_id = current_setting('app.current_tenant_id')::uuid);\n * \n * CREATE POLICY account_insert ON accounts\n * FOR INSERT\n * WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);\n * ```\n * \n * ObjectStack RLS Equivalent:\n * ```typescript\n * {\n * name: 'tenant_isolation',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id'\n * }\n * ```\n * \n * ## Salesforce Sharing Rules Comparison\n * \n * Salesforce uses \"Sharing Rules\" and \"Role Hierarchy\" for record-level access.\n * ObjectStack RLS provides similar functionality with more flexibility.\n * \n * Salesforce:\n * - Criteria-Based Sharing: Share records matching criteria with users/roles\n * - Owner-Based Sharing: Share records based on owner's role\n * - Manual Sharing: Individual record sharing\n * \n * ObjectStack RLS:\n * - More flexible formula-based conditions\n * - Direct SQL-like syntax\n * - Supports complex logic with AND/OR/NOT\n * \n * ## Best Practices\n * \n * 1. **Always Define SELECT Policy**: Control what users can view\n * 2. **Define INSERT/UPDATE CHECK Policies**: Prevent data leakage\n * 3. **Use Role-Based Policies**: Apply different rules to different roles\n * 4. **Test Thoroughly**: RLS can have complex interactions\n * 5. **Monitor Performance**: Complex RLS policies can impact query performance\n * \n * ## Security Considerations\n * \n * 1. **Defense in Depth**: RLS is one layer; use with object permissions\n * 2. **Default Deny**: If no policy matches, access is denied\n * 3. **Policy Precedence**: More permissive policy wins (OR logic)\n * 4. **Context Variables**: Ensure current_user context is always set\n * \n * @see https://www.postgresql.org/docs/current/ddl-rowsecurity.html\n * @see https://help.salesforce.com/s/articleView?id=sf.security_sharing_rules.htm\n */\n\n/**\n * RLS Operation Enum\n * Specifies which database operation this policy applies to.\n * \n * - **select**: Controls which rows can be read (SELECT queries)\n * - **insert**: Controls which rows can be inserted (INSERT statements)\n * - **update**: Controls which rows can be updated (UPDATE statements)\n * - **delete**: Controls which rows can be deleted (DELETE statements)\n * - **all**: Shorthand for all operations (equivalent to defining 4 separate policies)\n */\nexport const RLSOperation = z.enum(['select', 'insert', 'update', 'delete', 'all']);\n\nexport type RLSOperation = z.infer;\n\n/**\n * Row-Level Security Policy Schema\n * \n * Defines a single RLS policy that filters records based on conditions.\n * Multiple policies can be defined for the same object, and they are\n * combined with OR logic (union of results).\n * \n * @example Multi-Tenant Isolation\n * ```typescript\n * {\n * name: 'tenant_isolation',\n * label: 'Multi-Tenant Data Isolation',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id',\n * enabled: true\n * }\n * ```\n * \n * @example Owner-Based Access\n * ```typescript\n * {\n * name: 'owner_access',\n * label: 'Users Can View Their Own Records',\n * object: 'opportunity',\n * operation: 'select',\n * using: 'owner_id = current_user.id',\n * enabled: true\n * }\n * ```\n * \n * @example Manager Can View Team Records\n * ```typescript\n * {\n * name: 'manager_team_access',\n * label: 'Managers Can View Team Records',\n * object: 'task',\n * operation: 'select',\n * using: 'assigned_to_id IN (SELECT id FROM users WHERE manager_id = current_user.id)',\n * roles: ['manager', 'director'],\n * enabled: true\n * }\n * ```\n * \n * @example Prevent Cross-Tenant Data Insertion\n * ```typescript\n * {\n * name: 'tenant_insert_check',\n * label: 'Prevent Cross-Tenant Data Creation',\n * object: 'account',\n * operation: 'insert',\n * check: 'tenant_id = current_user.tenant_id',\n * enabled: true\n * }\n * ```\n * \n * @example Regional Sales Access\n * ```typescript\n * {\n * name: 'regional_sales_access',\n * label: 'Sales Reps Access Regional Accounts',\n * object: 'account',\n * operation: 'select',\n * using: 'region = current_user.region OR region IS NULL',\n * roles: ['sales_rep'],\n * enabled: true\n * }\n * ```\n * \n * @example Time-Based Access Control\n * ```typescript\n * {\n * name: 'active_records_only',\n * label: 'Users Only Access Active Records',\n * object: 'contract',\n * operation: 'select',\n * using: 'status = \"active\" AND start_date <= NOW() AND end_date >= NOW()',\n * enabled: true\n * }\n * ```\n * \n * @example Hierarchical Access (Role-Based)\n * ```typescript\n * {\n * name: 'executive_full_access',\n * label: 'Executives See All Records',\n * object: 'account',\n * operation: 'all',\n * using: '1 = 1', // Always true - see everything\n * roles: ['ceo', 'cfo', 'cto'],\n * enabled: true\n * }\n * ```\n */\nexport const RowLevelSecurityPolicySchema = z.object({\n /**\n * Unique identifier for this policy.\n * Must be unique within the object.\n * Use snake_case following ObjectStack naming conventions.\n * \n * @example \"tenant_isolation\", \"owner_access\", \"manager_team_view\"\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Policy unique identifier (snake_case)'),\n\n /**\n * Human-readable label for the policy.\n * Used in admin UI and logs.\n * \n * @example \"Multi-Tenant Data Isolation\", \"Owner-Based Access\"\n */\n label: z.string()\n .optional()\n .describe('Human-readable policy label'),\n\n /**\n * Description explaining what this policy does and why.\n * Helps with governance and compliance.\n * \n * @example \"Ensures users can only access records from their own tenant organization\"\n */\n description: z.string()\n .optional()\n .describe('Policy description and business justification'),\n\n /**\n * Target object (table) this policy applies to.\n * Must reference a valid ObjectStack object name.\n * \n * @example \"account\", \"opportunity\", \"contact\", \"custom_object\"\n */\n object: z.string()\n .describe('Target object name'),\n\n /**\n * Database operation(s) this policy applies to.\n * \n * - **select**: Controls read access (SELECT queries)\n * - **insert**: Controls insert access (INSERT statements)\n * - **update**: Controls update access (UPDATE statements)\n * - **delete**: Controls delete access (DELETE statements)\n * - **all**: Applies to all operations\n * \n * @example \"select\" - Most common, controls what users can view\n * @example \"all\" - Apply same rule to all operations\n */\n operation: RLSOperation\n .describe('Database operation this policy applies to'),\n\n /**\n * USING clause - Filter condition for SELECT/UPDATE/DELETE.\n * \n * This is a SQL-like expression evaluated for each row.\n * Only rows where this expression returns TRUE are accessible.\n * \n * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed).\n * For SELECT/UPDATE/DELETE operations, USING is required.\n * \n * **Security Note**: RLS conditions are executed at the database level with\n * parameterized queries. The implementation must use prepared statements\n * to prevent SQL injection. Never concatenate user input directly into\n * RLS conditions.\n * \n * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations\n * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain\n * semantic equivalence.\n * \n * Available context variables:\n * - `current_user.id` - Current user's ID\n * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext)\n * - `current_user.role` - Current user's role\n * - `current_user.department` - Current user's department\n * - `current_user.*` - Any custom user field\n * - `NOW()` - Current timestamp\n * - `CURRENT_DATE` - Current date\n * - `CURRENT_TIME` - Current time\n * \n * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`),\n * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`).\n * Implementations must handle this mapping.\n * \n * Supported operators:\n * - Comparison: =, !=, <, >, <=, >=, <> (not equal)\n * - Logical: AND, OR, NOT\n * - NULL checks: IS NULL, IS NOT NULL\n * - Set operations: IN, NOT IN\n * - String: LIKE, NOT LIKE, ILIKE (case-insensitive)\n * - Pattern matching: ~ (regex), !~ (not regex)\n * - Subqueries: (SELECT ...)\n * - Array operations: ANY, ALL\n * \n * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE)\n * \n * @example \"tenant_id = current_user.tenant_id\"\n * @example \"owner_id = current_user.id OR created_by = current_user.id\"\n * @example \"department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)\"\n * @example \"status = 'active' AND expiry_date > NOW()\"\n */\n using: z.string()\n .optional()\n .describe('Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies.'),\n\n /**\n * CHECK clause - Validation for INSERT/UPDATE operations.\n * \n * Similar to USING but applies to new/modified rows.\n * Prevents users from creating/updating rows they wouldn't be able to see.\n * \n * **Default Behavior**: If not specified, implementations should use the\n * USING clause as the CHECK clause. This ensures data integrity by preventing\n * users from creating records they cannot view.\n * \n * Use cases:\n * - Prevent cross-tenant data creation\n * - Enforce mandatory field values\n * - Validate data integrity rules\n * - Restrict certain operations (e.g., only allow creating \"draft\" status)\n * \n * @example \"tenant_id = current_user.tenant_id\"\n * @example \"status IN ('draft', 'pending')\" - Only allow certain statuses\n * @example \"created_by = current_user.id\" - Must be the creator\n */\n check: z.string()\n .optional()\n .describe('Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)'),\n\n /**\n * Restrict this policy to specific roles.\n * If specified, only users with these roles will have this policy applied.\n * If omitted, policy applies to all users (except those with bypassRLS permission).\n * \n * Role names must match defined roles in the system.\n * \n * @example [\"sales_rep\", \"account_manager\"]\n * @example [\"employee\"] - Apply to all employees\n * @example [\"guest\"] - Special restrictions for guests\n */\n roles: z.array(z.string())\n .optional()\n .describe('Roles this policy applies to (omit for all roles)'),\n\n /**\n * Whether this policy is currently active.\n * Disabled policies are not evaluated.\n * Useful for temporary policy changes without deletion.\n * \n * @default true\n */\n enabled: z.boolean()\n .default(true)\n .describe('Whether this policy is active'),\n\n /**\n * Policy priority for conflict resolution.\n * Higher numbers = higher priority.\n * When multiple policies apply, the most permissive wins (OR logic).\n * Priority is only used for ordering evaluation (performance).\n * \n * @default 0\n */\n priority: z.number()\n .int()\n .default(0)\n .describe('Policy evaluation priority (higher = evaluated first)'),\n\n /**\n * Tags for policy categorization and reporting.\n * Useful for governance, compliance, and auditing.\n * \n * @example [\"compliance\", \"gdpr\", \"pci\"]\n * @example [\"multi-tenant\", \"security\"]\n */\n tags: z.array(z.string())\n .optional()\n .describe('Policy categorization tags'),\n}).superRefine((data, ctx) => {\n // Ensure at least one of USING or CHECK is provided\n if (!data.using && !data.check) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'At least one of \"using\" or \"check\" must be specified. For SELECT/UPDATE/DELETE operations, provide \"using\". For INSERT operations, provide \"check\".',\n });\n }\n \n // For non-insert operations, USING should typically be present\n // This is a soft warning through documentation, not enforced here\n // since 'all' and mixed operation types are valid\n});\n\n/**\n * RLS Audit Event Schema\n * \n * Records a single RLS policy evaluation event for compliance and debugging.\n */\nexport const RLSAuditEventSchema = z.object({\n /** ISO 8601 timestamp of the evaluation */\n timestamp: z.string()\n .describe('ISO 8601 timestamp of the evaluation'),\n\n /** ID of the user whose access was evaluated */\n userId: z.string()\n .describe('User ID whose access was evaluated'),\n\n /** Database operation being performed */\n operation: z.enum(['select', 'insert', 'update', 'delete'])\n .describe('Database operation being performed'),\n\n /** Target object (table) name */\n object: z.string()\n .describe('Target object name'),\n\n /** Name of the RLS policy evaluated */\n policyName: z.string()\n .describe('Name of the RLS policy evaluated'),\n\n /** Whether access was granted */\n granted: z.boolean()\n .describe('Whether access was granted'),\n\n /** Time taken to evaluate the policy in milliseconds */\n evaluationDurationMs: z.number()\n .describe('Policy evaluation duration in milliseconds'),\n\n /** Which USING/CHECK clause matched */\n matchedCondition: z.string()\n .optional()\n .describe('Which USING/CHECK clause matched'),\n\n /** Number of rows affected by the operation */\n rowCount: z.number()\n .optional()\n .describe('Number of rows affected'),\n\n /** Additional metadata for the audit event */\n metadata: z.record(z.string(), z.unknown())\n .optional()\n .describe('Additional audit event metadata'),\n});\n\nexport type RLSAuditEvent = z.infer;\n\n/**\n * RLS Audit Configuration Schema\n * \n * Controls how RLS policy evaluations are logged and monitored.\n */\nexport const RLSAuditConfigSchema = z.object({\n /** Enable RLS audit logging */\n enabled: z.boolean()\n .describe('Enable RLS audit logging'),\n\n /** Which evaluations to log */\n logLevel: z.enum(['all', 'denied_only', 'granted_only', 'none'])\n .describe('Which evaluations to log'),\n\n /** Where to send audit logs */\n destination: z.enum(['system_log', 'audit_trail', 'external'])\n .describe('Audit log destination'),\n\n /** Sampling rate for high-traffic environments (0-1) */\n sampleRate: z.number()\n .min(0)\n .max(1)\n .describe('Sampling rate (0-1) for high-traffic environments'),\n\n /** Number of days to retain audit logs */\n retentionDays: z.number()\n .int()\n .default(90)\n .describe('Audit log retention period in days'),\n\n /** Whether to include row data in audit logs (security-sensitive) */\n includeRowData: z.boolean()\n .default(false)\n .describe('Include row data in audit logs (security-sensitive)'),\n\n /** Alert when access is denied */\n alertOnDenied: z.boolean()\n .default(true)\n .describe('Send alerts when access is denied'),\n});\n\nexport type RLSAuditConfig = z.infer;\n\n/**\n * RLS Configuration Schema\n * \n * Global configuration for the Row-Level Security system.\n * Defines how RLS is enforced across the entire platform.\n */\nexport const RLSConfigSchema = z.object({\n /**\n * Global RLS enable/disable flag.\n * When false, all RLS policies are ignored (use with caution!).\n * \n * @default true\n */\n enabled: z.boolean()\n .default(true)\n .describe('Enable RLS enforcement globally'),\n\n /**\n * Default behavior when no policies match.\n * \n * - **deny**: Deny access (secure default)\n * - **allow**: Allow access (permissive mode, not recommended)\n * \n * @default \"deny\"\n */\n defaultPolicy: z.enum(['deny', 'allow'])\n .default('deny')\n .describe('Default action when no policies match'),\n\n /**\n * Whether to allow superusers to bypass RLS.\n * Superusers include system administrators and service accounts.\n * \n * @default true\n */\n allowSuperuserBypass: z.boolean()\n .default(true)\n .describe('Allow superusers to bypass RLS'),\n\n /**\n * List of roles that can bypass RLS.\n * Users with these roles see all records regardless of policies.\n * \n * @example [\"system_admin\", \"data_auditor\"]\n */\n bypassRoles: z.array(z.string())\n .optional()\n .describe('Roles that bypass RLS (see all data)'),\n\n /**\n * Whether to log RLS policy evaluations.\n * Useful for debugging and auditing.\n * Can impact performance if enabled globally.\n * \n * @default false\n */\n logEvaluations: z.boolean()\n .default(false)\n .describe('Log RLS policy evaluations for debugging'),\n\n /**\n * Cache RLS policy evaluation results.\n * Can improve performance for frequently accessed records.\n * Cache is invalidated when policies change or user context changes.\n * \n * @default true\n */\n cacheResults: z.boolean()\n .default(true)\n .describe('Cache RLS evaluation results'),\n\n /**\n * Cache TTL in seconds.\n * How long to cache RLS evaluation results.\n * \n * @default 300 (5 minutes)\n */\n cacheTtlSeconds: z.number()\n .int()\n .positive()\n .default(300)\n .describe('Cache TTL in seconds'),\n\n /**\n * Performance optimization: Pre-fetch user context.\n * Load user context once per request instead of per-query.\n * \n * @default true\n */\n prefetchUserContext: z.boolean()\n .default(true)\n .describe('Pre-fetch user context for performance'),\n\n /**\n * Audit logging configuration for RLS evaluations.\n */\n audit: RLSAuditConfigSchema\n .optional()\n .describe('RLS audit logging configuration'),\n});\n\n/**\n * User Context Schema\n * \n * Represents the current user's context for RLS evaluation.\n * This data is used to evaluate USING and CHECK clauses.\n */\nexport const RLSUserContextSchema = z.object({\n /**\n * User ID\n */\n id: z.string()\n .describe('User ID'),\n\n /**\n * User email\n */\n email: z.string()\n .email()\n .optional()\n .describe('User email'),\n\n /**\n * Tenant/Organization ID\n */\n tenantId: z.string()\n .optional()\n .describe('Tenant/Organization ID'),\n\n /**\n * User role(s)\n */\n role: z.union([\n z.string(),\n z.array(z.string()),\n ])\n .optional()\n .describe('User role(s)'),\n\n /**\n * User department\n */\n department: z.string()\n .optional()\n .describe('User department'),\n\n /**\n * Additional custom attributes\n * Can include any custom user fields for RLS evaluation\n */\n attributes: z.record(z.string(), z.unknown())\n .optional()\n .describe('Additional custom user attributes'),\n});\n\n/**\n * RLS Policy Evaluation Result\n * \n * Result of evaluating an RLS policy for a specific record.\n * Used for debugging and audit logging.\n */\nexport const RLSEvaluationResultSchema = z.object({\n /**\n * Policy name that was evaluated\n */\n policyName: z.string()\n .describe('Policy name'),\n\n /**\n * Whether access was granted\n */\n granted: z.boolean()\n .describe('Whether access was granted'),\n\n /**\n * Evaluation duration in milliseconds\n */\n durationMs: z.number()\n .optional()\n .describe('Evaluation duration in milliseconds'),\n\n /**\n * Error message if evaluation failed\n */\n error: z.string()\n .optional()\n .describe('Error message if evaluation failed'),\n\n /**\n * Evaluated USING clause result\n */\n usingResult: z.boolean()\n .optional()\n .describe('USING clause evaluation result'),\n\n /**\n * Evaluated CHECK clause result (for INSERT/UPDATE)\n */\n checkResult: z.boolean()\n .optional()\n .describe('CHECK clause evaluation result'),\n});\n\n/**\n * Type exports\n */\nexport type RowLevelSecurityPolicy = z.infer;\nexport type RLSConfig = z.infer;\nexport type RLSUserContext = z.infer;\nexport type RLSEvaluationResult = z.infer;\n\n/**\n * Helper factory for creating RLS policies\n */\nexport const RLS = {\n /**\n * Create a simple owner-based policy\n */\n ownerPolicy: (object: string, ownerField: string = 'owner_id'): RowLevelSecurityPolicy => ({\n name: `${object}_owner_access`,\n label: `Owner Access for ${object}`,\n object,\n operation: 'all',\n using: `${ownerField} = current_user.id`,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a tenant isolation policy\n */\n tenantPolicy: (object: string, tenantField: string = 'tenant_id'): RowLevelSecurityPolicy => ({\n name: `${object}_tenant_isolation`,\n label: `Tenant Isolation for ${object}`,\n object,\n operation: 'all',\n using: `${tenantField} = current_user.tenant_id`,\n check: `${tenantField} = current_user.tenant_id`,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a role-based policy\n */\n rolePolicy: (object: string, roles: string[], condition: string): RowLevelSecurityPolicy => ({\n name: `${object}_${roles.join('_')}_access`,\n label: `${roles.join(', ')} Access for ${object}`,\n object,\n operation: 'select',\n using: condition,\n roles,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a permissive policy (allow all for specific roles)\n */\n allowAllPolicy: (object: string, roles: string[]): RowLevelSecurityPolicy => ({\n name: `${object}_${roles.join('_')}_full_access`,\n label: `Full Access for ${roles.join(', ')}`,\n object,\n operation: 'all',\n using: '1 = 1', // Always true\n roles,\n enabled: true,\n priority: 0,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { RowLevelSecurityPolicySchema } from './rls.zod';\n\n/**\n * Entity (Object) Level Permissions\n * Defines CRUD + VAMA (View All / Modify All) + Lifecycle access.\n * \n * Refined with enterprise data lifecycle controls:\n * - Transfer (Ownership change)\n * - Restore (Soft delete recovery)\n * - Purge (Hard delete / Compliance)\n */\nexport const ObjectPermissionSchema = z.object({\n /** C: Create */\n allowCreate: z.boolean().default(false).describe('Create permission'),\n /** R: Read (Owned records or Shared records) */\n allowRead: z.boolean().default(false).describe('Read permission'),\n /** U: Edit (Owned records or Shared records) */\n allowEdit: z.boolean().default(false).describe('Edit permission'),\n /** D: Delete (Owned records or Shared records) */\n allowDelete: z.boolean().default(false).describe('Delete permission'),\n \n /** Lifecycle Operations */\n allowTransfer: z.boolean().default(false).describe('Change record ownership'),\n allowRestore: z.boolean().default(false).describe('Restore from trash (Undelete)'),\n allowPurge: z.boolean().default(false).describe('Permanently delete (Hard Delete/GDPR)'),\n\n /** \n * View All Records: Super-user read access. \n * Bypasses Sharing Rules and Ownership checks.\n * Equivalent to Microsoft Dataverse \"Organization\" level read access.\n */\n viewAllRecords: z.boolean().default(false).describe('View All Data (Bypass Sharing)'),\n \n /** \n * Modify All Records: Super-user write access. \n * Bypasses Sharing Rules and Ownership checks.\n * Equivalent to Microsoft Dataverse \"Organization\" level write access.\n */\n modifyAllRecords: z.boolean().default(false).describe('Modify All Data (Bypass Sharing)'),\n});\n\n/**\n * Field Level Security (FLS)\n */\nexport const FieldPermissionSchema = z.object({\n /** Can see this field */\n readable: z.boolean().default(true).describe('Field read access'),\n /** Can edit this field */\n editable: z.boolean().default(false).describe('Field edit access'),\n});\n\n/**\n * Permission Set Schema\n * Defines a collection of permissions that can be assigned to users.\n * \n * DIFFERENTIATION:\n * - Profile: The ONE primary functional definition of a user (e.g. Standard User).\n * - Permission Set: Add-on capabilities assigned to users (e.g. Export Reports).\n * - Role: (Defined in src/system/role.zod.ts) Defines data visibility hierarchy.\n * \n * **NAMING CONVENTION:**\n * Permission set names MUST be lowercase snake_case to prevent security issues.\n * \n * @example Good permission set names\n * - 'read_only'\n * - 'system_admin'\n * - 'standard_user'\n * - 'api_access'\n * \n * @example Bad permission set names (will be rejected)\n * - 'ReadOnly' (camelCase)\n * - 'SystemAdmin' (mixed case)\n * - 'Read Only' (spaces)\n */\nexport const PermissionSetSchema = z.object({\n /** Unique permission set name */\n name: SnakeCaseIdentifierSchema.describe('Permission set unique name (lowercase snake_case)'),\n \n /** Display label */\n label: z.string().optional().describe('Display label'),\n \n /** Is this a Profile? (Base set for a user) */\n isProfile: z.boolean().default(false).describe('Whether this is a user profile'),\n \n /** Object Permissions Map: -> permissions */\n objects: z.record(z.string(), ObjectPermissionSchema).describe('Entity permissions'),\n \n /** Field Permissions Map: . -> permissions */\n fields: z.record(z.string(), FieldPermissionSchema).optional().describe('Field level security'),\n \n /** System permissions (e.g., \"manage_users\") */\n systemPermissions: z.array(z.string()).optional().describe('System level capabilities'),\n \n /**\n * Tab/App Visibility Permissions (Salesforce Pattern)\n * Controls which app tabs are visible, hidden, or set as default for this permission set.\n * \n * @example\n * ```typescript\n * tabPermissions: {\n * 'app_crm': 'visible',\n * 'app_admin': 'hidden',\n * 'app_sales': 'default_on'\n * }\n * ```\n */\n tabPermissions: z.record(z.string(), z.enum(['visible', 'hidden', 'default_on', 'default_off'])).optional()\n .describe('App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)'),\n \n /** \n * Row-Level Security Rules\n * \n * Row-level security policies that filter records based on user context.\n * These rules are applied in addition to object-level permissions.\n * \n * Uses the canonical RLS protocol from rls.zod.ts for comprehensive\n * row-level security features including PostgreSQL-style USING and CHECK clauses.\n * \n * @see {@link RowLevelSecurityPolicySchema} for full RLS specification\n * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation\n * \n * @example Multi-tenant isolation\n * ```typescript\n * rls: [{\n * name: 'tenant_filter',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id'\n * }]\n * ```\n */\n rowLevelSecurity: z.array(RowLevelSecurityPolicySchema).optional()\n .describe('Row-level security policies (see rls.zod.ts for full spec)'),\n \n /**\n * Context-Based Access Control Variables\n * \n * Custom context variables that can be referenced in RLS rules.\n * These variables are evaluated at runtime based on the user's session.\n * \n * Common context variables:\n * - `current_user.id` - Current user ID\n * - `current_user.tenant_id` - User's tenant/organization ID\n * - `current_user.department` - User's department\n * - `current_user.role` - User's role\n * - `current_user.region` - User's geographic region\n * \n * @example Custom context\n * ```typescript\n * contextVariables: {\n * allowed_regions: ['US', 'EU'],\n * access_level: 2,\n * custom_attribute: 'value'\n * }\n * ```\n */\n contextVariables: z.record(z.string(), z.unknown()).optional().describe('Context variables for RLS evaluation'),\n});\n\nexport type PermissionSet = z.infer;\nexport type ObjectPermission = z.infer;\nexport type FieldPermission = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Trigger events for workflow automation\n */\nexport const WorkflowTriggerType = z.enum([\n 'on_create', // When record is created\n 'on_update', // When record is updated\n 'on_create_or_update', // Both\n 'on_delete', // When record is deleted\n 'schedule' // Time-based (cron)\n]);\n\n/**\n * Schema for Workflow Field Update Action\n * @example\n * {\n * name: \"update_status\",\n * type: \"field_update\",\n * field: \"status\",\n * value: \"approved\"\n * }\n */\nexport const FieldUpdateActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('field_update'),\n field: z.string().describe('Field to update'),\n value: z.unknown().describe('Value or Formula to set'),\n});\n\n/**\n * Schema for Workflow Email Alert Action\n * @example\n * {\n * name: \"send_approval_email\",\n * type: \"email_alert\",\n * template: \"approval_request_email\",\n * recipients: [\"user_id_123\", \"manager_field\"]\n * }\n */\nexport const EmailAlertActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('email_alert'),\n template: z.string().describe('Email template ID/DevName'),\n recipients: z.array(z.string()).describe('List of recipient emails or user IDs'),\n});\n\n/**\n * Schema for Connector Action Reference\n * Executes a capability defined in an integration connector.\n * Replaces hardcoded vendor actions (Slack, Twilio, etc).\n * \n * @example Send Slack Message\n * {\n * name: \"notify_slack\",\n * type: \"connector_action\",\n * connectorId: \"slack\",\n * actionId: \"post_message\",\n * input: {\n * channel: \"#general\",\n * text: \"New deal closed: {name}\"\n * }\n * }\n */\nexport const ConnectorActionRefSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('connector_action'),\n connectorId: z.string().describe('Target Connector ID (e.g. slack, twilio)'),\n actionId: z.string().describe('Target Action ID (e.g. send_message)'),\n input: z.record(z.string(), z.unknown()).describe('Input parameters matching the action schema'),\n});\n\n/**\n * Schema for HTTP Callout Action\n * Makes a REST API call to an external service.\n * @example\n * {\n * name: \"sync_to_erp\",\n * type: \"http_call\",\n * url: \"https://erp.api/orders\",\n * method: \"POST\",\n * headers: { \"Authorization\": \"Bearer {token}\" },\n * body: \"{ ... }\"\n * }\n */\nexport const HttpCallActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('http_call'),\n url: z.string().describe('Target URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).default('POST').describe('HTTP Method'),\n headers: z.record(z.string(), z.string()).optional().describe('HTTP Headers'),\n body: z.string().optional().describe('Request body (JSON or text)'),\n});\n\n/**\n * Schema for Workflow Task Creation Action\n * @example\n * {\n * name: \"create_followup_task\",\n * type: \"task_creation\",\n * taskObject: \"tasks\",\n * subject: \"Follow up with client\",\n * dueDate: \"TODAY() + 3\"\n * }\n */\nexport const TaskCreationActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('task_creation'),\n taskObject: z.string().describe('Task object name (e.g., \"task\", \"project_task\")'),\n subject: z.string().describe('Task subject/title'),\n description: z.string().optional().describe('Task description'),\n assignedTo: z.string().optional().describe('User ID or field reference for assignee'),\n dueDate: z.string().optional().describe('Due date (ISO string or formula)'),\n priority: z.string().optional().describe('Task priority'),\n relatedTo: z.string().optional().describe('Related record ID or field reference'),\n additionalFields: z.record(z.string(), z.unknown()).optional().describe('Additional custom fields'),\n});\n\n/**\n * Schema for Workflow Push Notification Action\n */\nexport const PushNotificationActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('push_notification'),\n title: z.string().describe('Notification title'),\n body: z.string().describe('Notification body text'),\n recipients: z.array(z.string()).describe('User IDs or device tokens'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data payload'),\n badge: z.number().optional().describe('Badge count (iOS)'),\n sound: z.string().optional().describe('Notification sound'),\n clickAction: z.string().optional().describe('Action/URL when notification is clicked'),\n});\n\n/**\n * Schema for Workflow Custom Script Action\n */\nexport const CustomScriptActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('custom_script'),\n language: z.enum(['javascript', 'typescript', 'python']).default('javascript').describe('Script language'),\n code: z.string().describe('Script code to execute'),\n timeout: z.number().default(30000).describe('Execution timeout in milliseconds'),\n context: z.record(z.string(), z.unknown()).optional().describe('Additional context variables'),\n});\n\n/**\n * Universal Workflow Action Schema\n * Union of all supported action types.\n */\nexport const WorkflowActionSchema = z.discriminatedUnion('type', [\n FieldUpdateActionSchema,\n EmailAlertActionSchema,\n HttpCallActionSchema,\n ConnectorActionRefSchema,\n TaskCreationActionSchema,\n PushNotificationActionSchema,\n CustomScriptActionSchema,\n]);\n\nexport type WorkflowAction = z.infer;\n\n/**\n * Time Trigger Definition\n * Schedules actions to run relative to a specific time or date field.\n */\nexport const TimeTriggerSchema = z.object({\n id: z.string().optional().describe('Unique identifier'),\n \n /** Timing Logic */\n timeLength: z.number().int().describe('Duration amount (e.g. 1, 30)'),\n timeUnit: z.enum(['minutes', 'hours', 'days']).describe('Unit of time'),\n \n /** Reference Point */\n offsetDirection: z.enum(['before', 'after']).describe('Before or After the reference date'),\n offsetFrom: z.enum(['trigger_date', 'date_field']).describe('Basis for calculation'),\n dateField: z.string().optional().describe('Date field to calculate from (required if offsetFrom is date_field)'),\n \n /** Actions */\n actions: z.array(WorkflowActionSchema).describe('Actions to execute at the scheduled time'),\n});\n\n/**\n * Schema for Workflow Rules (Automation)\n * \n * **NAMING CONVENTION:**\n * Workflow names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good workflow names\n * - 'send_welcome_email'\n * - 'update_lead_status'\n * - 'notify_manager_on_close'\n * - 'calculate_discount'\n * \n * @example Bad workflow names (will be rejected)\n * - 'SendWelcomeEmail' (PascalCase)\n * - 'updateLeadStatus' (camelCase)\n * - 'Send Welcome Email' (spaces)\n * \n * @example Complete Workflow\n * {\n * name: \"new_lead_process\",\n * objectName: \"lead\",\n * triggerType: \"on_create\",\n * criteria: \"amount > 1000\",\n * active: true,\n * actions: [\n * {\n * name: \"set_status\",\n * type: \"field_update\",\n * field: \"status\",\n * value: \"new\"\n * },\n * {\n * name: \"notify_team\",\n * type: \"connector_action\",\n * connectorId: \"slack\",\n * actionId: \"post_message\",\n * input: { channel: \"#sales\", text: \"New high value lead!\" }\n * }\n * ],\n * timeTriggers: [\n * {\n * timeLength: 2,\n * timeUnit: \"days\",\n * offsetDirection: \"after\",\n * offsetFrom: \"trigger_date\",\n * actions: [\n * {\n * name: \"followup_check\",\n * type: \"task_creation\",\n * taskObject: \"task\",\n * subject: \"Follow up lead\",\n * dueDate: \"TODAY()\"\n * }\n * ]\n * }\n * ]\n * }\n */\nexport const WorkflowRuleSchema = z.object({\n /** Machine name */\n name: SnakeCaseIdentifierSchema.describe('Unique workflow name (lowercase snake_case)'),\n \n /** Target Object */\n objectName: z.string().describe('Target Object'),\n \n /** When to evaluate the rule */\n triggerType: WorkflowTriggerType.describe('When to evaluate'),\n \n /** \n * Condition to start the workflow.\n * If empty, runs on every trigger event.\n */\n criteria: z.string().optional().describe('Formula condition. If TRUE, actions execute.'),\n \n /** Actions to execute immediately */\n actions: z.array(WorkflowActionSchema).optional().describe('Immediate actions'),\n \n /** \n * Time-Dependent Actions \n * Actions scheduled to run in the future.\n */\n timeTriggers: z.array(TimeTriggerSchema).optional().describe('Scheduled actions relative to trigger or date field'),\n \n /** Active status */\n active: z.boolean().default(true).describe('Whether this workflow is active'),\n\n /** Execution Order */\n executionOrder: z.number().int().min(0).default(100).describe('Deterministic execution order when multiple workflows match (lower runs first)'),\n \n /** Recursion Control */\n reevaluateOnChange: z.boolean().default(false).describe('Re-evaluate rule if field updates change the record validity'),\n});\n\nexport type WorkflowRule = z.infer;\nexport type TimeTrigger = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const LocaleSchema = z.string().describe('BCP-47 Language Tag (e.g. en-US, zh-CN)');\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-level Translation (per-object file)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Field Translation Schema\n * Translation data for a single field.\n */\nexport const FieldTranslationSchema = z.object({\n label: z.string().optional().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n placeholder: z.string().optional().describe('Translated placeholder text for form inputs'),\n options: z.record(z.string(), z.string()).optional().describe('Option value to translated label map'),\n}).describe('Translation data for a single field');\n\nexport type FieldTranslation = z.infer;\n\n/**\n * Object Translation Data Schema\n *\n * Translation data for a **single object** in a **single locale**.\n * Use this schema to validate per-object translation files.\n *\n * File convention: `i18n/{locale}/{object_name}.json`\n *\n * @example\n * ```json\n * // i18n/en/account.json\n * {\n * \"label\": \"Account\",\n * \"pluralLabel\": \"Accounts\",\n * \"fields\": {\n * \"name\": { \"label\": \"Account Name\", \"help\": \"Legal name\" },\n * \"type\": { \"label\": \"Type\", \"options\": { \"customer\": \"Customer\" } }\n * }\n * }\n * ```\n */\nexport const ObjectTranslationDataSchema = z.object({\n /** Translated singular label for the object */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label for the object */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional().describe('Field-level translations'),\n}).describe('Translation data for a single object');\n\nexport type ObjectTranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale-level Translation Data (per-locale aggregate)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Data Schema\n * Supports i18n for labels, messages, and options within a single locale.\n * Example structure:\n * ```json\n * {\n * \"objects\": { \"account\": { \"label\": \"Account\" } },\n * \"apps\": { \"crm\": { \"label\": \"CRM\" } },\n * \"messages\": { \"common.save\": \"Save\" }\n * }\n * ```\n */\nexport const TranslationDataSchema = z.object({\n /** Object translations */\n objects: z.record(z.string(), ObjectTranslationDataSchema).optional().describe('Object translations keyed by object name'),\n \n /** App/Menu translations */\n apps: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** UI Messages */\n messages: z.record(z.string(), z.string()).optional().describe('UI message translations keyed by message ID'),\n \n /** Validation Error Messages */\n validationMessages: z.record(z.string(), z.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {\"discount_limit\": \"折扣不能超过40%\"})'),\n}).describe('Translation data for objects, apps, and UI messages');\n\nexport type TranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Bundle (all locales)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const TranslationBundleSchema = z.record(LocaleSchema, TranslationDataSchema).describe('Map of locale codes to translation data');\n\nexport type TranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// File Organization Convention\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation File Organization Strategy\n *\n * Defines how translation files are organized on disk.\n *\n * - `bundled` — All locales in a single `TranslationBundle` file.\n * Best for small projects with few objects.\n * ```\n * src/translations/\n * crm.translation.ts # { en: {...}, \"zh-CN\": {...} }\n * ```\n *\n * - `per_locale` — One file per locale containing all namespaces.\n * Recommended when a single locale file stays under ~500 lines.\n * ```\n * src/translations/\n * en.ts # TranslationData for English\n * zh-CN.ts # TranslationData for Chinese\n * ```\n *\n * - `per_namespace` — One file per namespace (object) per locale.\n * Recommended for large projects with many objects/languages.\n * Aligns with Salesforce DX and ServiceNow conventions.\n * ```\n * i18n/\n * en/\n * account.json # ObjectTranslationData\n * contact.json\n * common.json # messages + app labels\n * zh-CN/\n * account.json\n * contact.json\n * common.json\n * ```\n */\nexport const TranslationFileOrganizationSchema = z.enum([\n 'bundled',\n 'per_locale',\n 'per_namespace',\n]).describe('Translation file organization strategy');\n\nexport type TranslationFileOrganization = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Configuration\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Configuration Schema\n *\n * Defines internationalization settings for the stack.\n *\n * @example\n * ```typescript\n * export default defineStack({\n * i18n: {\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'zh-CN', 'ja-JP'],\n * fallbackLocale: 'en',\n * fileOrganization: 'per_locale',\n * },\n * translations: [...],\n * });\n * ```\n */\n/**\n * Message format standard used for interpolation, pluralization, and\n * gender-aware translations.\n *\n * - `icu` — ICU MessageFormat (recommended for complex plurals, gender, select).\n * Strings may contain `{count, plural, one {# item} other {# items}}` patterns.\n * - `simple` — Simple `{variable}` interpolation only (default).\n */\nexport const MessageFormatSchema = z.enum([\n 'icu',\n 'simple',\n]).describe('Message interpolation format: ICU MessageFormat or simple {variable} replacement');\n\nexport type MessageFormat = z.infer;\n\nexport const TranslationConfigSchema = z.object({\n /** Default locale for the application */\n defaultLocale: LocaleSchema.describe('Default locale (e.g., \"en\")'),\n /** Supported BCP-47 locale codes */\n supportedLocales: z.array(LocaleSchema).describe('Supported BCP-47 locale codes'),\n /** Fallback locale when translation is not found */\n fallbackLocale: LocaleSchema.optional().describe('Fallback locale code'),\n /** How translation files are organized on disk */\n fileOrganization: TranslationFileOrganizationSchema.default('per_locale')\n .describe('File organization strategy'),\n /**\n * Message interpolation format.\n * When set to `'icu'`, messages and validationMessages are expected to use\n * ICU MessageFormat syntax (plurals, select, number/date skeletons).\n * @default 'simple'\n */\n messageFormat: MessageFormatSchema.default('simple')\n .describe('Message interpolation format (ICU MessageFormat or simple)'),\n /** Load translations on demand instead of eagerly */\n lazyLoad: z.boolean().default(false).describe('Load translations on demand'),\n /** Cache loaded translations in memory */\n cache: z.boolean().default(true).describe('Cache loaded translations'),\n}).describe('Internationalization configuration');\n\nexport type TranslationConfig = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-First Translation Node (object-first aggregated structure)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Translatable option map: option value → translated label */\nconst OptionTranslationMapSchema = z.record(z.string(), z.string())\n .describe('Option value to translated label map');\n\n/**\n * ObjectTranslationNodeSchema\n *\n * Object-first aggregated translation node that groups **all** translatable\n * content for a single object under one key. Aligns with Salesforce / Dynamics\n * conventions where translations are organized per-object rather than per-category.\n *\n * Located at `o.{object_name}` inside an {@link AppTranslationBundle}.\n *\n * @example\n * ```typescript\n * const accountNode: ObjectTranslationNode = {\n * label: '客户',\n * pluralLabel: '客户',\n * description: '客户管理对象',\n * fields: {\n * name: { label: '客户名称', help: '公司或组织的法定名称' },\n * industry: { label: '行业', options: { tech: '科技', finance: '金融' } },\n * },\n * _options: { status: { active: '活跃', inactive: '停用' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: {\n * convert_lead: { label: '转换线索', confirmMessage: '确认转换?' },\n * },\n * };\n * ```\n */\nexport const ObjectTranslationNodeSchema = z.object({\n /** Translated singular label */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Translated object description */\n description: z.string().optional().describe('Translated object description'),\n /** Translated help text shown in tooltips or guidance panels */\n helpText: z.string().optional().describe('Translated help text for the object'),\n\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional()\n .describe('Field translations keyed by field name'),\n\n /**\n * Global picklist / select option overrides scoped to this object.\n * Keyed by field name → { optionValue: translatedLabel }.\n */\n _options: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Object-scoped picklist option translations keyed by field name'),\n\n /** View translations keyed by view name */\n _views: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated view label'),\n description: z.string().optional().describe('Translated view description'),\n })).optional().describe('View translations keyed by view name'),\n\n /** Section (form section / tab) translations keyed by section name */\n _sections: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated section label'),\n })).optional().describe('Section translations keyed by section name'),\n\n /** Action translations keyed by action name */\n _actions: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated action label'),\n confirmMessage: z.string().optional().describe('Translated confirmation message'),\n })).optional().describe('Action translations keyed by action name'),\n\n /** Notification message translations keyed by notification name */\n _notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Notification translations keyed by notification name'),\n\n /** Error message translations keyed by error code */\n _errors: z.record(z.string(), z.string()).optional()\n .describe('Error message translations keyed by error code'),\n}).describe('Object-first aggregated translation node');\n\nexport type ObjectTranslationNode = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// App Translation Bundle (object-first, full application)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * AppTranslationBundleSchema\n *\n * Complete application translation bundle for a **single locale** using\n * the **object-first** convention. All per-object translatable content\n * is aggregated under `o.{object_name}`, while global (non-object-bound)\n * translations are kept in dedicated top-level groups.\n *\n * This schema is designed for:\n * - Translation workbench UIs (object-level editing & coverage)\n * - CLI skeleton generation (`objectstack i18n extract`)\n * - Automated diff/coverage detection\n *\n * @example\n * ```typescript\n * const zh: AppTranslationBundle = {\n * o: {\n * account: {\n * label: '客户',\n * fields: { name: { label: '客户名称' } },\n * _options: { industry: { tech: '科技' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: { convert: { label: '转换' } },\n * },\n * },\n * _globalOptions: { currency: { usd: '美元', eur: '欧元' } },\n * app: { crm: { label: '客户关系管理', description: '管理销售流程' } },\n * nav: { home: '首页', settings: '设置' },\n * dashboard: { sales_overview: { label: '销售概览' } },\n * reports: { pipeline_report: { label: '管道报表' } },\n * pages: { landing: { title: '欢迎' } },\n * messages: { 'common.save': '保存' },\n * validationMessages: { 'discount_limit': '折扣不能超过40%' },\n * };\n * ```\n */\nexport const AppTranslationBundleSchema = z.object({\n /**\n * Bundle-level metadata.\n * Provides locale-aware rendering hints such as text direction (bidi)\n * and the canonical locale code this bundle represents.\n */\n _meta: z.object({\n /** BCP-47 locale code this bundle represents */\n locale: z.string().optional().describe('BCP-47 locale code for this bundle'),\n /** Text direction for the locale */\n direction: z.enum(['ltr', 'rtl']).optional().describe('Text direction: left-to-right or right-to-left'),\n }).optional().describe('Bundle-level metadata (locale, bidi direction)'),\n\n /**\n * Namespace for plugin/extension isolation.\n * When multiple plugins contribute translations, each should use a unique\n * namespace to avoid key collisions (e.g. \"crm\", \"helpdesk\", \"plugin-xyz\").\n */\n namespace: z.string().optional()\n .describe('Namespace for plugin isolation to avoid translation key collisions'),\n\n /** Object-first translations keyed by object name (snake_case) */\n o: z.record(z.string(), ObjectTranslationNodeSchema).optional()\n .describe('Object-first translations keyed by object name'),\n\n /** Global picklist options not bound to any specific object */\n _globalOptions: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Global picklist option translations keyed by option set name'),\n\n /** App-level translations */\n app: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** Navigation menu translations */\n nav: z.record(z.string(), z.string()).optional()\n .describe('Navigation item translations keyed by nav item name'),\n\n /** Dashboard translations keyed by dashboard name */\n dashboard: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated dashboard label'),\n description: z.string().optional().describe('Translated dashboard description'),\n })).optional().describe('Dashboard translations keyed by dashboard name'),\n\n /** Report translations keyed by report name */\n reports: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated report label'),\n description: z.string().optional().describe('Translated report description'),\n })).optional().describe('Report translations keyed by report name'),\n\n /** Page translations keyed by page name */\n pages: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated page title'),\n description: z.string().optional().describe('Translated page description'),\n })).optional().describe('Page translations keyed by page name'),\n\n /** UI message translations (supports ICU MessageFormat when enabled) */\n messages: z.record(z.string(), z.string()).optional()\n .describe('UI message translations keyed by message ID (supports ICU MessageFormat)'),\n\n /** Validation error message translations (supports ICU MessageFormat when enabled) */\n validationMessages: z.record(z.string(), z.string()).optional()\n .describe('Validation error message translations keyed by rule name (supports ICU MessageFormat)'),\n\n /** Global notification translations not bound to a specific object */\n notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Global notification translations keyed by notification name'),\n\n /** Global error message translations not bound to a specific object */\n errors: z.record(z.string(), z.string()).optional()\n .describe('Global error message translations keyed by error code'),\n}).describe('Object-first application translation bundle for a single locale');\n\nexport type AppTranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Diff & Coverage\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Diff Status\n *\n * Status of a single translation entry compared to the source metadata.\n */\nexport const TranslationDiffStatusSchema = z.enum([\n 'missing',\n 'redundant',\n 'stale',\n]).describe('Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)');\n\nexport type TranslationDiffStatus = z.infer;\n\n/**\n * TranslationDiffItemSchema\n *\n * Describes a single translation key that is missing, redundant, or stale\n * relative to the source metadata. Used by CLI/API diff detection.\n *\n * @example\n * ```typescript\n * const item: TranslationDiffItem = {\n * key: 'o.account.fields.website.label',\n * status: 'missing',\n * objectName: 'account',\n * locale: 'zh-CN',\n * };\n * ```\n */\nexport const TranslationDiffItemSchema = z.object({\n /** Dot-path translation key (e.g. \"o.account.fields.website.label\") */\n key: z.string().describe('Dot-path translation key'),\n /** Diff status */\n status: TranslationDiffStatusSchema.describe('Diff status of this translation key'),\n /** Object name if the key belongs to an object translation node */\n objectName: z.string().optional().describe('Associated object name (snake_case)'),\n /** Locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /**\n * Hash of the source metadata value at the time the translation was made.\n * Used by CLI/Workbench to detect stale translations without a full diff.\n */\n sourceHash: z.string().optional().describe('Hash of source metadata for precise stale detection'),\n /**\n * AI-suggested translation text for missing or stale entries.\n * Populated by AI translation hooks or TMS integrations.\n */\n aiSuggested: z.string().optional().describe('AI-suggested translation for this key'),\n /** Confidence score (0-1) for the AI suggestion */\n aiConfidence: z.number().min(0).max(1).optional().describe('AI suggestion confidence score (0–1)'),\n}).describe('A single translation diff item');\n\nexport type TranslationDiffItem = z.infer;\n\n/**\n * TranslationCoverageResultSchema\n *\n * Aggregated coverage result for a locale, optionally scoped to a single object.\n * Returned by the i18n diff detection API.\n *\n * @example\n * ```typescript\n * const result: TranslationCoverageResult = {\n * locale: 'zh-CN',\n * totalKeys: 120,\n * translatedKeys: 105,\n * missingKeys: 12,\n * redundantKeys: 3,\n * staleKeys: 0,\n * coveragePercent: 87.5,\n * items: [ ... ],\n * };\n * ```\n */\n/**\n * Per-group coverage breakdown entry.\n */\nexport const CoverageBreakdownEntrySchema = z.object({\n /** Group category (e.g. \"fields\", \"views\", \"actions\", \"messages\") */\n group: z.string().describe('Translation group category'),\n /** Total translatable keys in this group */\n totalKeys: z.number().int().nonnegative().describe('Total keys in this group'),\n /** Number of translated keys in this group */\n translatedKeys: z.number().int().nonnegative().describe('Translated keys in this group'),\n /** Coverage percentage for this group */\n coveragePercent: z.number().min(0).max(100).describe('Coverage percentage for this group'),\n}).describe('Coverage breakdown for a single translation group');\n\nexport type CoverageBreakdownEntry = z.infer;\n\nexport const TranslationCoverageResultSchema = z.object({\n /** BCP-47 locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /** Optional object name scope */\n objectName: z.string().optional().describe('Object name scope (omit for full bundle)'),\n /** Total translatable keys derived from metadata */\n totalKeys: z.number().int().nonnegative().describe('Total translatable keys from metadata'),\n /** Number of keys that have a translation */\n translatedKeys: z.number().int().nonnegative().describe('Number of translated keys'),\n /** Number of missing translations */\n missingKeys: z.number().int().nonnegative().describe('Number of missing translations'),\n /** Number of redundant (orphaned) translations */\n redundantKeys: z.number().int().nonnegative().describe('Number of redundant translations'),\n /** Number of stale translations */\n staleKeys: z.number().int().nonnegative().describe('Number of stale translations'),\n /** Coverage percentage (0-100) */\n coveragePercent: z.number().min(0).max(100).describe('Translation coverage percentage'),\n /** Individual diff items */\n items: z.array(TranslationDiffItemSchema).describe('Detailed diff items'),\n /**\n * Per-group coverage breakdown for translation project management.\n * Each entry represents a logical group (e.g. \"fields\", \"views\", \"actions\",\n * \"messages\") with its own coverage statistics.\n */\n breakdown: z.array(CoverageBreakdownEntrySchema).optional()\n .describe('Per-group coverage breakdown'),\n}).describe('Aggregated translation coverage result');\n\nexport type TranslationCoverageResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Capability Protocol\n * \n * Defines the standard way plugins declare their capabilities, implementations,\n * and conformance levels to ensure interoperability across vendors.\n * \n * Based on the Protocol-Oriented Architecture pattern similar to:\n * - Kubernetes CRDs (Custom Resource Definitions)\n * - OSGi Service Registry\n * - Eclipse Extension Points\n */\n\n/**\n * Capability Conformance Level\n * Indicates how completely a plugin implements a given protocol.\n */\nexport const CapabilityConformanceLevelSchema = z.enum([\n 'full', // Complete implementation of all protocol features\n 'partial', // Subset implementation with specific features listed\n 'experimental', // Unstable/preview implementation\n 'deprecated', // Still supported but scheduled for removal\n]).describe('Level of protocol conformance');\n\n/**\n * Protocol Version Schema\n * Uses semantic versioning to track protocol evolution.\n */\nexport const ProtocolVersionSchema = z.object({\n major: z.number().int().min(0),\n minor: z.number().int().min(0),\n patch: z.number().int().min(0),\n}).describe('Semantic version of the protocol');\n\n/**\n * Protocol Reference\n * Uniquely identifies a protocol/interface that a plugin can implement.\n * \n * Examples:\n * - com.objectstack.protocol.storage.v1\n * - com.objectstack.protocol.auth.oauth2.v2\n * - com.acme.protocol.payment.stripe.v1\n */\nexport const ProtocolReferenceSchema = z.object({\n /**\n * Protocol identifier using reverse domain notation.\n * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+protocol\\.[a-z][a-z0-9._]*\\.v\\d+$/)\n .describe('Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)'),\n \n /**\n * Human-readable protocol name\n */\n label: z.string(),\n \n /**\n * Protocol version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Detailed protocol specification URL or file reference\n */\n specification: z.string().optional().describe('URL or path to protocol specification'),\n \n /**\n * Brief description of what this protocol defines\n */\n description: z.string().optional(),\n});\n\n/**\n * Protocol Feature\n * Represents a specific capability within a protocol.\n */\nexport const ProtocolFeatureSchema = z.object({\n name: z.string().describe('Feature identifier within the protocol'),\n enabled: z.boolean().default(true),\n description: z.string().optional(),\n sinceVersion: z.string().optional().describe('Version when this feature was added'),\n deprecatedSince: z.string().optional().describe('Version when deprecated'),\n});\n\n/**\n * Plugin Capability Declaration\n * Documents what protocols a plugin implements and to what extent.\n */\nexport const PluginCapabilitySchema = z.object({\n /**\n * The protocol being implemented\n */\n protocol: ProtocolReferenceSchema,\n \n /**\n * Conformance level\n */\n conformance: CapabilityConformanceLevelSchema.default('full'),\n \n /**\n * Specific features implemented (required if conformance is 'partial')\n */\n implementedFeatures: z.array(z.string()).optional().describe('List of implemented feature names'),\n \n /**\n * Optional feature flags indicating advanced capabilities\n */\n features: z.array(ProtocolFeatureSchema).optional(),\n \n /**\n * Custom metadata for vendor-specific information\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Testing/Certification status\n */\n certified: z.boolean().default(false).describe('Has passed official conformance tests'),\n certificationDate: z.string().datetime().optional(),\n});\n\n/**\n * Plugin Interface Declaration\n * Defines the contract for services this plugin provides to other plugins.\n */\nexport const PluginInterfaceSchema = z.object({\n /**\n * Unique interface identifier\n * Format: {plugin-id}.interface.{name}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+interface\\.[a-z][a-z0-9._]+$/)\n .describe('Unique interface identifier'),\n \n /**\n * Interface name\n */\n name: z.string(),\n \n /**\n * Description of what this interface provides\n */\n description: z.string().optional(),\n \n /**\n * Interface version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Methods exposed by this interface\n */\n methods: z.array(z.object({\n name: z.string().describe('Method name'),\n description: z.string().optional(),\n parameters: z.array(z.object({\n name: z.string(),\n type: z.string().describe('Type notation (e.g., string, number, User)'),\n required: z.boolean().default(true),\n description: z.string().optional(),\n })).optional(),\n returnType: z.string().optional().describe('Return value type'),\n async: z.boolean().default(false).describe('Whether method returns a Promise'),\n })),\n \n /**\n * Events emitted by this interface\n */\n events: z.array(z.object({\n name: z.string().describe('Event name'),\n description: z.string().optional(),\n payload: z.string().optional().describe('Event payload type'),\n })).optional(),\n \n /**\n * Stability level\n */\n stability: z.enum(['stable', 'beta', 'alpha', 'experimental']).default('stable'),\n});\n\n/**\n * Plugin Dependency Declaration\n * Specifies what other plugins or capabilities this plugin requires.\n */\nexport const PluginDependencySchema = z.object({\n /**\n * Plugin ID using reverse domain notation\n */\n pluginId: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Required plugin identifier'),\n \n /**\n * Version constraint (supports semver ranges)\n * Examples: \"1.0.0\", \"^1.2.3\", \">=2.0.0 <3.0.0\"\n */\n version: z.string().describe('Semantic version constraint'),\n \n /**\n * Whether this dependency is optional\n */\n optional: z.boolean().default(false),\n \n /**\n * Reason for the dependency\n */\n reason: z.string().optional(),\n \n /**\n * Minimum required capabilities from the dependency\n */\n requiredCapabilities: z.array(z.string()).optional().describe('Protocol IDs the dependency must support'),\n});\n\n/**\n * Extension Point Declaration\n * Defines hooks where other plugins can extend this plugin's functionality.\n */\nexport const ExtensionPointSchema = z.object({\n /**\n * Extension point identifier\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+extension\\.[a-z][a-z0-9._]+$/)\n .describe('Unique extension point identifier'),\n \n /**\n * Extension point name\n */\n name: z.string(),\n \n /**\n * Description\n */\n description: z.string().optional(),\n \n /**\n * Type of extension point\n */\n type: z.enum([\n 'action', // Plugins can register executable actions\n 'hook', // Plugins can listen to lifecycle events\n 'widget', // Plugins can contribute UI widgets\n 'provider', // Plugins can provide data/services\n 'transformer', // Plugins can transform data\n 'validator', // Plugins can validate data\n 'decorator', // Plugins can enhance/wrap functionality\n ]),\n \n /**\n * Expected interface contract for extensions\n */\n contract: z.object({\n input: z.string().optional().describe('Input type/schema'),\n output: z.string().optional().describe('Output type/schema'),\n signature: z.string().optional().describe('Function signature if applicable'),\n }).optional(),\n \n /**\n * Cardinality\n */\n cardinality: z.enum(['single', 'multiple']).default('multiple')\n .describe('Whether multiple extensions can register to this point'),\n});\n\n/**\n * Complete Plugin Capability Manifest\n * This is included in the main plugin manifest to declare all capabilities.\n */\nexport const PluginCapabilityManifestSchema = z.object({\n /**\n * Protocols this plugin implements\n */\n implements: z.array(PluginCapabilitySchema).optional()\n .describe('List of protocols this plugin conforms to'),\n \n /**\n * Interfaces this plugin exposes to other plugins\n */\n provides: z.array(PluginInterfaceSchema).optional()\n .describe('Services/APIs this plugin offers to others'),\n \n /**\n * Dependencies on other plugins\n */\n requires: z.array(PluginDependencySchema).optional()\n .describe('Required plugins and their capabilities'),\n \n /**\n * Extension points this plugin defines\n */\n extensionPoints: z.array(ExtensionPointSchema).optional()\n .describe('Points where other plugins can extend this plugin'),\n \n /**\n * Extensions this plugin contributes to other plugins\n */\n extensions: z.array(z.object({\n targetPluginId: z.string().describe('Plugin ID being extended'),\n extensionPointId: z.string().describe('Extension point identifier'),\n implementation: z.string().describe('Path to implementation module'),\n priority: z.number().int().default(100).describe('Registration priority (lower = higher priority)'),\n })).optional().describe('Extensions contributed to other plugins'),\n});\n\n// Export types\nexport type CapabilityConformanceLevel = z.infer;\nexport type ProtocolVersion = z.infer;\nexport type ProtocolReference = z.infer;\nexport type ProtocolFeature = z.infer;\nexport type PluginCapability = z.infer;\nexport type PluginInterface = z.infer;\nexport type PluginDependency = z.infer;\nexport type ExtensionPoint = z.infer;\nexport type PluginCapabilityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Loading Protocol\n * \n * Defines the enhanced plugin loading mechanism for the microkernel architecture.\n * Inspired by industry best practices from:\n * - Kubernetes CRDs and Operators\n * - OSGi Dynamic Module System\n * - Eclipse Plugin Framework\n * - Webpack Module Federation\n * \n * This protocol enables:\n * - Lazy loading and code splitting\n * - Dynamic imports and parallel initialization\n * - Capability-based discovery\n * - Hot reload in development\n * - Advanced caching strategies\n */\n\n/**\n * Plugin Loading Strategy\n * Determines how and when a plugin is loaded into memory\n */\nexport const PluginLoadingStrategySchema = z.enum([\n 'eager', // Load immediately during bootstrap (critical plugins)\n 'lazy', // Load on first use (feature plugins)\n 'parallel', // Load in parallel with other plugins\n 'deferred', // Load after initial bootstrap complete\n 'on-demand', // Load only when explicitly requested\n]).describe('Plugin loading strategy');\n\n/**\n * Plugin Preloading Configuration\n * Configures preloading behavior for faster activation\n */\nexport const PluginPreloadConfigSchema = z.object({\n /**\n * Enable preloading for this plugin\n */\n enabled: z.boolean().default(false),\n \n /**\n * Preload priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Resources to preload\n */\n resources: z.array(z.enum([\n 'metadata', // Plugin manifest and metadata\n 'dependencies', // Plugin dependencies\n 'assets', // Static assets (icons, translations)\n 'code', // JavaScript code chunks\n 'services', // Service definitions\n ])).optional(),\n \n /**\n * Conditions for preloading\n */\n conditions: z.object({\n /**\n * Preload only on specific routes\n */\n routes: z.array(z.string()).optional(),\n \n /**\n * Preload only for specific user roles\n */\n roles: z.array(z.string()).optional(),\n \n /**\n * Preload based on device type\n */\n deviceType: z.array(z.enum(['desktop', 'mobile', 'tablet'])).optional(),\n \n /**\n * Network connection quality threshold\n */\n minNetworkSpeed: z.enum(['slow-2g', '2g', '3g', '4g']).optional(),\n }).optional(),\n}).describe('Plugin preloading configuration');\n\n/**\n * Plugin Code Splitting Configuration\n * Configures how plugin code is split for optimal loading\n */\nexport const PluginCodeSplittingSchema = z.object({\n /**\n * Enable code splitting for this plugin\n */\n enabled: z.boolean().default(true),\n \n /**\n * Split strategy\n */\n strategy: z.enum([\n 'route', // Split by UI routes\n 'feature', // Split by feature modules\n 'size', // Split by bundle size threshold\n 'custom', // Custom split points defined by plugin\n ]).default('feature'),\n \n /**\n * Chunk naming strategy\n */\n chunkNaming: z.enum(['hashed', 'named', 'sequential']).default('hashed'),\n \n /**\n * Maximum chunk size in KB\n */\n maxChunkSize: z.number().int().min(10).optional().describe('Max chunk size in KB'),\n \n /**\n * Shared dependencies optimization\n */\n sharedDependencies: z.object({\n enabled: z.boolean().default(true),\n /**\n * Minimum times a module must be shared before extraction\n */\n minChunks: z.number().int().min(1).default(2),\n }).optional(),\n}).describe('Plugin code splitting configuration');\n\n/**\n * Plugin Dynamic Import Configuration\n * Configures dynamic import behavior for runtime module loading\n */\nexport const PluginDynamicImportSchema = z.object({\n /**\n * Enable dynamic imports\n */\n enabled: z.boolean().default(true),\n \n /**\n * Import mode\n */\n mode: z.enum([\n 'async', // Asynchronous import (recommended)\n 'sync', // Synchronous import (blocking)\n 'eager', // Eager evaluation\n 'lazy', // Lazy evaluation\n ]).default('async'),\n \n /**\n * Prefetch strategy\n */\n prefetch: z.boolean().default(false).describe('Prefetch module in idle time'),\n \n /**\n * Preload strategy\n */\n preload: z.boolean().default(false).describe('Preload module in parallel with parent'),\n \n /**\n * Webpack magic comments support\n */\n webpackChunkName: z.string().optional().describe('Custom chunk name for webpack'),\n \n /**\n * Import timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000).describe('Dynamic import timeout (ms)'),\n \n /**\n * Retry configuration on import failure\n */\n retry: z.object({\n enabled: z.boolean().default(true),\n maxAttempts: z.number().int().min(1).max(10).default(3),\n backoffMs: z.number().int().min(0).default(1000).describe('Exponential backoff base delay'),\n }).optional(),\n}).describe('Plugin dynamic import configuration');\n\n/**\n * Plugin Initialization Configuration\n * Configures how plugin initialization is executed\n */\nexport const PluginInitializationSchema = z.object({\n /**\n * Initialization mode\n */\n mode: z.enum([\n 'sync', // Synchronous initialization\n 'async', // Asynchronous initialization\n 'parallel', // Parallel with other plugins\n 'sequential', // Must complete before next plugin\n ]).default('async'),\n \n /**\n * Initialization timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000),\n \n /**\n * Startup priority (lower = higher priority, earlier initialization)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Whether to continue bootstrap if this plugin fails\n */\n critical: z.boolean().default(false).describe('If true, kernel bootstrap fails if plugin fails'),\n \n /**\n * Retry configuration on initialization failure\n */\n retry: z.object({\n enabled: z.boolean().default(false),\n maxAttempts: z.number().int().min(1).max(5).default(3),\n backoffMs: z.number().int().min(0).default(1000),\n }).optional(),\n \n /**\n * Health check interval for monitoring\n */\n healthCheckInterval: z.number().int().min(0).optional().describe('Health check interval in ms (0 = disabled)'),\n}).describe('Plugin initialization configuration');\n\n/**\n * Plugin Dependency Resolution Configuration\n * Advanced dependency resolution using semantic versioning\n */\nexport const PluginDependencyResolutionSchema = z.object({\n /**\n * Dependency resolution strategy\n */\n strategy: z.enum([\n 'strict', // Exact version match required\n 'compatible', // Semver compatible versions (^)\n 'latest', // Always use latest compatible\n 'pinned', // Lock to specific version\n ]).default('compatible'),\n \n /**\n * Peer dependency handling\n */\n peerDependencies: z.object({\n /**\n * Whether to resolve peer dependencies\n */\n resolve: z.boolean().default(true),\n \n /**\n * Action on missing peer dependency\n */\n onMissing: z.enum(['error', 'warn', 'ignore']).default('warn'),\n \n /**\n * Action on peer version mismatch\n */\n onMismatch: z.enum(['error', 'warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Optional dependency handling\n */\n optionalDependencies: z.object({\n /**\n * Whether to attempt loading optional dependencies\n */\n load: z.boolean().default(true),\n \n /**\n * Action on optional dependency load failure\n */\n onFailure: z.enum(['warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Conflict resolution\n */\n conflictResolution: z.enum([\n 'fail', // Fail on any version conflict\n 'latest', // Use latest version\n 'oldest', // Use oldest version\n 'manual', // Require manual resolution\n ]).default('latest'),\n \n /**\n * Circular dependency handling\n */\n circularDependencies: z.enum([\n 'error', // Throw error on circular dependency\n 'warn', // Warn but continue\n 'allow', // Allow circular dependencies\n ]).default('warn'),\n}).describe('Plugin dependency resolution configuration');\n\n/**\n * Plugin Hot Reload Configuration\n * Enables hot module replacement for development and production environments.\n * \n * Production mode adds safety features: health validation, rollback on failure,\n * connection draining, and concurrency control for zero-downtime reloads.\n */\nexport const PluginHotReloadSchema = z.object({\n /**\n * Enable hot reload\n */\n enabled: z.boolean().default(false),\n \n /**\n * Target environment for hot reload behavior\n */\n environment: z.enum([\n 'development', // Fast reload with relaxed safety (file watchers, no health validation)\n 'staging', // Production-like reload with validation but relaxed rollback\n 'production', // Full safety: health validation, rollback, connection draining\n ]).default('development').describe('Target environment controlling safety level'),\n \n /**\n * Hot reload strategy\n */\n strategy: z.enum([\n 'full', // Full plugin reload (destroy and reinitialize)\n 'partial', // Partial reload (update changed modules only)\n 'state-preserve', // Preserve plugin state during reload\n ]).default('full'),\n \n /**\n * Files to watch for changes\n */\n watchPatterns: z.array(z.string()).optional().describe('Glob patterns for files to watch'),\n \n /**\n * Files to ignore\n */\n ignorePatterns: z.array(z.string()).optional().describe('Glob patterns for files to ignore'),\n \n /**\n * Debounce delay in milliseconds\n */\n debounceMs: z.number().int().min(0).default(300),\n \n /**\n * Whether to preserve state during reload\n */\n preserveState: z.boolean().default(false),\n \n /**\n * State serialization\n */\n stateSerialization: z.object({\n enabled: z.boolean().default(false),\n /**\n * Path to state serialization handler\n */\n handler: z.string().optional(),\n }).optional(),\n \n /**\n * Hooks for hot reload lifecycle\n */\n hooks: z.object({\n beforeReload: z.string().optional().describe('Function to call before reload'),\n afterReload: z.string().optional().describe('Function to call after reload'),\n onError: z.string().optional().describe('Function to call on reload error'),\n }).optional(),\n \n /**\n * Production safety configuration\n * Applied when environment is 'staging' or 'production'\n */\n productionSafety: z.object({\n /**\n * Validate plugin health before completing reload\n */\n healthValidation: z.boolean().default(true)\n .describe('Run health checks after reload before accepting traffic'),\n \n /**\n * Automatically rollback to previous version on reload failure\n */\n rollbackOnFailure: z.boolean().default(true)\n .describe('Auto-rollback if reloaded plugin fails health check'),\n \n /**\n * Maximum time to wait for health validation after reload (ms)\n */\n healthTimeout: z.number().int().min(1000).default(30000)\n .describe('Health check timeout after reload in ms'),\n \n /**\n * Drain active connections before reload\n */\n drainConnections: z.boolean().default(true)\n .describe('Gracefully drain active requests before reloading'),\n \n /**\n * Maximum time to wait for connection draining (ms)\n */\n drainTimeout: z.number().int().min(0).default(15000)\n .describe('Max wait time for connection draining in ms'),\n \n /**\n * Maximum number of concurrent plugin reloads\n */\n maxConcurrentReloads: z.number().int().min(1).default(1)\n .describe('Limit concurrent reloads to prevent system instability'),\n \n /**\n * Minimum interval between reloads of the same plugin (ms)\n */\n minReloadInterval: z.number().int().min(1000).default(5000)\n .describe('Cooldown period between reloads of the same plugin'),\n }).optional(),\n}).describe('Plugin hot reload configuration');\n\n/**\n * Plugin Caching Configuration\n * Configures caching strategy for faster subsequent loads\n */\nexport const PluginCachingSchema = z.object({\n /**\n * Enable caching\n */\n enabled: z.boolean().default(true),\n \n /**\n * Cache storage type\n */\n storage: z.enum([\n 'memory', // In-memory cache (fastest, not persistent)\n 'disk', // Disk cache (persistent)\n 'indexeddb', // Browser IndexedDB (persistent, browser only)\n 'hybrid', // Memory + Disk hybrid\n ]).default('memory'),\n \n /**\n * Cache key strategy\n */\n keyStrategy: z.enum([\n 'version', // Cache by plugin version\n 'hash', // Cache by content hash\n 'timestamp', // Cache by last modified timestamp\n ]).default('version'),\n \n /**\n * Cache TTL in seconds\n */\n ttl: z.number().int().min(0).optional().describe('Time to live in seconds (0 = infinite)'),\n \n /**\n * Maximum cache size in MB\n */\n maxSize: z.number().int().min(1).optional().describe('Max cache size in MB'),\n \n /**\n * Cache invalidation triggers\n */\n invalidateOn: z.array(z.enum([\n 'version-change',\n 'dependency-change',\n 'manual',\n 'error',\n ])).optional(),\n \n /**\n * Compression\n */\n compression: z.object({\n enabled: z.boolean().default(false),\n algorithm: z.enum(['gzip', 'brotli', 'deflate']).default('gzip'),\n }).optional(),\n}).describe('Plugin caching configuration');\n\n/**\n * Plugin Sandboxing Configuration\n * Security isolation for plugins with configurable scope.\n * \n * Supports isolation beyond automation scripts: any plugin can be sandboxed\n * with process-level isolation and inter-plugin communication (IPC).\n */\nexport const PluginSandboxingSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(false),\n \n /**\n * Isolation scope - which plugins are subject to sandboxing\n */\n scope: z.enum([\n 'automation-only', // Sandbox automation/scripting plugins only (current behavior)\n 'untrusted-only', // Sandbox plugins below a trust threshold\n 'all-plugins', // Sandbox all plugins (maximum isolation)\n ]).default('automation-only').describe('Which plugins are subject to isolation'),\n \n /**\n * Sandbox isolation level\n */\n isolationLevel: z.enum([\n 'none', // No isolation\n 'process', // Separate process (Node.js worker threads)\n 'vm', // VM context isolation\n 'iframe', // iframe isolation (browser)\n 'web-worker', // Web Worker (browser)\n ]).default('none'),\n \n /**\n * Allowed capabilities\n */\n allowedCapabilities: z.array(z.string()).optional().describe('List of allowed capability IDs'),\n \n /**\n * Resource quotas\n */\n resourceQuotas: z.object({\n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(1).optional(),\n \n /**\n * Maximum CPU time in milliseconds\n */\n maxCpuTimeMs: z.number().int().min(100).optional(),\n \n /**\n * Maximum number of file descriptors\n */\n maxFileDescriptors: z.number().int().min(1).optional(),\n \n /**\n * Maximum network bandwidth in KB/s\n */\n maxNetworkKBps: z.number().int().min(1).optional(),\n }).optional(),\n \n /**\n * Permissions\n */\n permissions: z.object({\n /**\n * Allowed API access\n */\n allowedAPIs: z.array(z.string()).optional(),\n \n /**\n * Allowed file system paths\n */\n allowedPaths: z.array(z.string()).optional(),\n \n /**\n * Allowed network endpoints\n */\n allowedEndpoints: z.array(z.string()).optional(),\n \n /**\n * Allowed environment variables\n */\n allowedEnvVars: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Inter-Plugin Communication (IPC) configuration\n * Enables isolated plugins to communicate with the kernel and other plugins\n */\n ipc: z.object({\n /**\n * Enable IPC for sandboxed plugins\n */\n enabled: z.boolean().default(true)\n .describe('Allow sandboxed plugins to communicate via IPC'),\n \n /**\n * IPC transport mechanism\n */\n transport: z.enum([\n 'message-port', // MessagePort (worker threads / Web Workers)\n 'unix-socket', // Unix domain sockets (process isolation)\n 'tcp', // TCP sockets (container isolation)\n 'memory', // Shared memory channel (in-process VM)\n ]).default('message-port')\n .describe('IPC transport for cross-boundary communication'),\n \n /**\n * Maximum message size in bytes\n */\n maxMessageSize: z.number().int().min(1024).default(1048576)\n .describe('Maximum IPC message size in bytes (default 1MB)'),\n \n /**\n * Message timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000)\n .describe('IPC message response timeout in ms'),\n \n /**\n * Allowed service calls through IPC\n */\n allowedServices: z.array(z.string()).optional()\n .describe('Service names the sandboxed plugin may invoke via IPC'),\n }).optional(),\n}).describe('Plugin sandboxing configuration');\n\n/**\n * Plugin Performance Monitoring Configuration\n * Telemetry and performance tracking\n */\nexport const PluginPerformanceMonitoringSchema = z.object({\n /**\n * Enable performance monitoring\n */\n enabled: z.boolean().default(false),\n \n /**\n * Metrics to collect\n */\n metrics: z.array(z.enum([\n 'load-time',\n 'init-time',\n 'memory-usage',\n 'cpu-usage',\n 'api-calls',\n 'error-rate',\n 'cache-hit-rate',\n ])).optional(),\n \n /**\n * Sampling rate (0-1, where 1 = 100%)\n */\n samplingRate: z.number().min(0).max(1).default(1),\n \n /**\n * Reporting interval in seconds\n */\n reportingInterval: z.number().int().min(1).default(60),\n \n /**\n * Performance budget thresholds\n */\n budgets: z.object({\n /**\n * Maximum load time in milliseconds\n */\n maxLoadTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum init time in milliseconds\n */\n maxInitTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(0).optional(),\n }).optional(),\n \n /**\n * Action on budget violation\n */\n onBudgetViolation: z.enum(['warn', 'error', 'ignore']).default('warn'),\n}).describe('Plugin performance monitoring configuration');\n\n/**\n * Complete Plugin Loading Configuration\n * Combines all loading-related configurations\n */\nexport const PluginLoadingConfigSchema = z.object({\n /**\n * Loading strategy\n */\n strategy: PluginLoadingStrategySchema.default('lazy'),\n \n /**\n * Preloading configuration\n */\n preload: PluginPreloadConfigSchema.optional(),\n \n /**\n * Code splitting configuration\n */\n codeSplitting: PluginCodeSplittingSchema.optional(),\n \n /**\n * Dynamic import configuration\n */\n dynamicImport: PluginDynamicImportSchema.optional(),\n \n /**\n * Initialization configuration\n */\n initialization: PluginInitializationSchema.optional(),\n \n /**\n * Dependency resolution configuration\n */\n dependencyResolution: PluginDependencyResolutionSchema.optional(),\n \n /**\n * Hot reload configuration (development and production)\n */\n hotReload: PluginHotReloadSchema.optional(),\n \n /**\n * Caching configuration\n */\n caching: PluginCachingSchema.optional(),\n \n /**\n * Sandboxing configuration\n */\n sandboxing: PluginSandboxingSchema.optional(),\n \n /**\n * Performance monitoring\n */\n monitoring: PluginPerformanceMonitoringSchema.optional(),\n}).describe('Complete plugin loading configuration');\n\n/**\n * Plugin Loading Event\n * Emitted during plugin loading lifecycle\n */\nexport const PluginLoadingEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'load-started',\n 'load-completed',\n 'load-failed',\n 'init-started',\n 'init-completed',\n 'init-failed',\n 'preload-started',\n 'preload-completed',\n 'cache-hit',\n 'cache-miss',\n 'hot-reload',\n 'dynamic-load', // Plugin loaded at runtime\n 'dynamic-unload', // Plugin unloaded at runtime\n 'dynamic-discover', // Plugin discovered via registry\n ]),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Timestamp\n */\n timestamp: z.number().int().min(0),\n \n /**\n * Duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Error if event represents a failure\n */\n error: z.object({\n message: z.string(),\n code: z.string().optional(),\n stack: z.string().optional(),\n }).optional(),\n}).describe('Plugin loading lifecycle event');\n\n/**\n * Plugin Loading State\n * Tracks the current loading state of a plugin\n */\nexport const PluginLoadingStateSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current state\n */\n state: z.enum([\n 'pending', // Not yet loaded\n 'loading', // Currently loading\n 'loaded', // Code loaded, not initialized\n 'initializing', // Currently initializing\n 'ready', // Fully initialized and ready\n 'failed', // Failed to load or initialize\n 'reloading', // Hot reloading in progress\n 'unloading', // Being unloaded at runtime\n 'unloaded', // Successfully unloaded (dynamic loading)\n ]),\n \n /**\n * Load progress (0-100)\n */\n progress: z.number().min(0).max(100).default(0),\n \n /**\n * Loading start time\n */\n startedAt: z.number().int().min(0).optional(),\n \n /**\n * Loading completion time\n */\n completedAt: z.number().int().min(0).optional(),\n \n /**\n * Last error\n */\n lastError: z.string().optional(),\n \n /**\n * Retry count\n */\n retryCount: z.number().int().min(0).default(0),\n}).describe('Plugin loading state');\n\n// Export types\nexport type PluginLoadingStrategy = z.infer;\nexport type PluginPreloadConfig = z.infer;\nexport type PluginCodeSplitting = z.infer;\nexport type PluginDynamicImport = z.infer;\nexport type PluginInitialization = z.infer;\nexport type PluginDependencyResolution = z.infer;\nexport type PluginHotReload = z.infer;\nexport type PluginCaching = z.infer;\nexport type PluginSandboxing = z.infer;\nexport type PluginPerformanceMonitoring = z.infer;\nexport type PluginLoadingConfig = z.infer;\nexport type PluginLoadingEvent = z.infer;\nexport type PluginLoadingState = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// Service method interfaces use z.function() instead of z.any() for type safety.\n// Generic data fields use z.unknown() for type safety.\nexport const PluginContextSchema = z.object({\n ql: z.object({\n object: z.function().describe('Get object handle for method chaining'),\n query: z.function().describe('Execute a query'),\n }).passthrough().describe('ObjectQL Engine Interface'),\n\n os: z.object({\n getCurrentUser: z.function().describe('Get the current authenticated user'),\n getConfig: z.function().describe('Get platform configuration'),\n }).passthrough().describe('ObjectStack Kernel Interface'),\n\n logger: z.object({\n debug: z.function().describe('Log debug message'),\n info: z.function().describe('Log info message'),\n warn: z.function().describe('Log warning message'),\n error: z.function().describe('Log error message'),\n }).passthrough().describe('Logger Interface'),\n\n storage: z.object({\n get: z.function().describe('Get a value from storage'),\n set: z.function().describe('Set a value in storage'),\n delete: z.function().describe('Delete a value from storage'),\n }).passthrough().describe('Storage Interface'),\n\n i18n: z.object({\n t: z.function().describe('Translate a key'),\n getLocale: z.function().describe('Get current locale'),\n }).passthrough().describe('Internationalization Interface'),\n\n metadata: z.record(z.string(), z.unknown()),\n events: z.record(z.string(), z.unknown()),\n \n app: z.object({\n router: z.object({\n get: z.function().describe('Register GET route handler'),\n post: z.function().describe('Register POST route handler'),\n use: z.function().describe('Register middleware'),\n }).passthrough()\n }).passthrough().describe('App Framework Interface'),\n\n drivers: z.object({\n register: z.function().describe('Register a driver'),\n }).passthrough().describe('Driver Registry'),\n});\n\nexport type PluginContextData = z.infer;\nexport type PluginContext = PluginContextData;\n\n/**\n * Upgrade Context Schema\n *\n * Provides version migration context to the `onUpgrade` lifecycle hook.\n * Enables developers to write conditional migration logic based on\n * the previous and new versions.\n */\nexport const UpgradeContextSchema = z.object({\n /** Version before upgrade */\n previousVersion: z.string().describe('Version before upgrade'),\n\n /** Version after upgrade */\n newVersion: z.string().describe('Version after upgrade'),\n\n /** Whether this is a major version bump */\n isMajorUpgrade: z.boolean().describe('Whether this is a major version bump'),\n\n /** Metadata snapshot before upgrade (for migration logic) */\n previousMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Metadata snapshot before upgrade'),\n}).describe('Version migration context for onUpgrade hook');\n\nexport type UpgradeContext = z.infer;\n\nexport const PluginLifecycleSchema = z.object({\n onInstall: z.function().optional().describe('Called when plugin is installed'),\n \n onEnable: z.function().optional().describe('Called when plugin is enabled'),\n \n onDisable: z.function().optional().describe('Called when plugin is disabled'),\n \n onUninstall: z.function().optional().describe('Called when plugin is uninstalled'),\n \n onUpgrade: z.function().optional().describe('Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade'),\n});\n\nexport type PluginLifecycleHooks = z.infer;\n\n/**\n * Shared Plugin Types\n * These are the specialized plugin types common between Manifest (Package) and Plugin (Runtime).\n */\nexport const CORE_PLUGIN_TYPES = [\n 'ui', // Frontend: Serves static assets/SPA (e.g. Console, Studio)\n 'driver', // Connectivity: Database or Storage adapters (e.g. SQL, S3)\n 'server', // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL)\n 'app', // Business: Vertical Solution Bundle (Metadata + Logic)\n 'theme', // Appearance: UI Overrides & CSS Variables\n 'agent', // AI: Autonomous Agent & Tool Definitions\n 'objectql' // Core: ObjectQL Engine Data Provider\n] as const;\n\nexport const PluginSchema = PluginLifecycleSchema.extend({\n id: z.string().min(1).optional().describe('Unique Plugin ID (e.g. com.example.crm)'),\n type: z.enum([\n 'standard', // Default: General purpose backend logic (Service, Hook, etc.)\n ...CORE_PLUGIN_TYPES\n ]).default('standard').optional().describe('Plugin Type categorization for runtime behavior'),\n \n staticPath: z.string().optional().describe('Absolute path to static assets (Required for type=\"ui-plugin\")'),\n slug: z.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type=\"ui-plugin\")'),\n default: z.boolean().optional().describe('Serve at root path (Only one \"ui-plugin\" can be default)'),\n \n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic Version'),\n description: z.string().optional(),\n author: z.string().optional(),\n homepage: z.string().url().optional(),\n});\n\nexport type PluginDefinition = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data Import Strategy\n * Defines how the engine handles existing records.\n */\nexport const DatasetMode = z.enum([\n 'insert', // Try to insert, fail on duplicate\n 'update', // Only update found records, ignore new\n 'upsert', // Create new or Update existing (Standard)\n 'replace', // Delete ALL records in object then insert (Dangerous - use for cache tables)\n 'ignore' // Try to insert, silently skip duplicates\n]);\n\n/**\n * Dataset Schema (Seed Data / Fixtures)\n * \n * Standardized format for transporting data.\n * Used for:\n * 1. System Bootstrapping (Admin accounts, Standard Roles)\n * 2. Reference Data (Countries, Currencies)\n * 3. Demo/Test Data\n */\nexport const DatasetSchema = z.object({\n /** \n * Target Object \n * The machine name of the object to populate.\n */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target Object Name'),\n\n /** \n * Idempotency Key (The \"Upsert\" Key)\n * The field used to check if a record already exists.\n * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'.\n * Standard: 'id' is rarely used for portable seed data — prefer natural keys.\n */\n externalId: z.string().default('name').describe('Field match for uniqueness check'),\n\n /** \n * Import Strategy\n */\n mode: DatasetMode.default('upsert').describe('Conflict resolution strategy'),\n\n /**\n * Environment Scope\n * - 'all': Always load\n * - 'dev': Only for development/demo\n * - 'test': Only for CI/CD tests\n */\n env: z.array(z.enum(['prod', 'dev', 'test'])).default(['prod', 'dev', 'test']).describe('Applicable environments'),\n\n /** \n * The Payload\n * Array of raw JSON objects matching the Object Schema.\n */\n records: z.array(z.record(z.string(), z.unknown())).describe('Data records'),\n});\n\n/** Parsed/output type — all defaults are applied (env, mode, externalId always present) */\nexport type Dataset = z.infer;\n\n/** Input type — fields with defaults (env, mode, externalId) are optional */\nexport type DatasetInput = z.input;\n\nexport type DatasetImportMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\nimport { PluginLoadingConfigSchema } from './plugin-loading.zod';\nimport { CORE_PLUGIN_TYPES } from './plugin.zod';\nimport { DatasetSchema } from '../data/dataset.zod';\n\n/**\n * Schema for the ObjectStack Manifest.\n * This defines the structure of a package configuration in the ObjectStack ecosystem.\n * All packages (apps, plugins, drivers, modules) must conform to this schema.\n * \n * @example App Package\n * ```yaml\n * id: com.acme.crm\n * version: 1.0.0\n * type: app\n * name: Acme CRM\n * description: Customer Relationship Management system\n * permissions:\n * - system.user.read\n * - system.object.create\n * objects:\n * - \"./src/objects/*.object.yml\"\n * ```\n */\nexport const ManifestSchema = z.object({\n /** \n * Unique package identifier using reverse domain notation.\n * Must be unique across the entire ecosystem.\n * \n * @example \"com.steedos.crm\"\n * @example \"org.apache.superset\"\n */\n id: z.string().describe('Unique package identifier (reverse domain style)'),\n \n /**\n * Short namespace identifier for metadata scoping.\n * Used as a prefix for objects and other metadata to prevent naming collisions\n * across packages from different vendors.\n * \n * Rules:\n * - 2-20 characters, lowercase letters, digits, and underscores only.\n * - Must be unique within a running instance.\n * - Platform-reserved namespaces (no prefix applied): \"base\", \"system\".\n * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator).\n * \n * @example \"crm\" → objects become crm__account, crm__deal\n * @example \"todo\" → objects become todo__task\n * @example \"base\" → objects keep short name (platform reserved)\n */\n namespace: z.string()\n .regex(/^[a-z][a-z0-9_]{1,19}$/, 'Namespace must be 2-20 chars, lowercase alphanumeric + underscore')\n .optional()\n .describe('Short namespace identifier for metadata scoping (e.g. \"crm\", \"todo\")'),\n \n /** \n * Package version following semantic versioning (major.minor.patch).\n * \n * @example \"1.0.0\"\n * @example \"2.1.0-beta.1\"\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Package version (semantic versioning)'),\n \n /** \n * Type of the package in the ObjectStack ecosystem.\n * - plugin: General-purpose functionality extension (Runtime: standard)\n * - app: Business application package\n * - driver: Connectivity adapter\n * - server: Protocol gateway (Hono, GraphQL)\n * - ui: Frontend package (Static/SPA)\n * - theme: UI Theme\n * - agent: AI Agent\n * - module: Reusable code library/shared module\n * - objectql: Core engine\n * - adapter: Host adapter (Express, Fastify)\n */\n type: z.enum([\n 'plugin', \n ...CORE_PLUGIN_TYPES,\n 'module', \n 'gateway', // Deprecated: use 'server'\n 'adapter'\n ]).describe('Type of package'),\n \n /** \n * Human-readable name of the package.\n * Displayed in the UI for users.\n * \n * @example \"Project Management\"\n */\n name: z.string().describe('Human-readable package name'),\n \n /** \n * Brief description of the package functionality.\n * Displayed in the marketplace and plugin manager.\n */\n description: z.string().optional().describe('Package description'),\n \n /** \n * Array of permission strings that the package requires.\n * These form the \"Scope\" requested by the package at installation.\n * \n * @example [\"system.user.read\", \"system.data.write\"]\n */\n permissions: z.array(z.string()).optional().describe('Array of required permission strings'),\n \n /** \n * Glob patterns specifying ObjectQL schemas files.\n * Matches `*.object.yml` or `*.object.ts` files to load business objects.\n * \n * @example [\"./src/objects/*.object.yml\"]\n */\n objects: z.array(z.string()).optional().describe('Glob patterns for ObjectQL schemas files'),\n\n /**\n * Defines system level DataSources.\n * Matches `*.datasource.yml` files.\n * \n * @example [\"./src/datasources/*.datasource.mongo.yml\"]\n */\n datasources: z.array(z.string()).optional().describe('Glob patterns for Datasource definitions'),\n\n /**\n * Package Dependencies.\n * Map of package IDs to version requirements.\n * \n * @example { \"@steedos/plugin-auth\": \"^2.0.0\" }\n */\n dependencies: z.record(z.string(), z.string()).optional().describe('Package dependencies'),\n\n /**\n * Plugin Configuration Schema.\n * Defines the settings this plugin exposes to the user via UI/ENV.\n * Uses a simplified JSON Schema format.\n * \n * @example\n * {\n * \"title\": \"Stripe Config\",\n * \"properties\": {\n * \"apiKey\": { \"type\": \"string\", \"secret\": true },\n * \"currency\": { \"type\": \"string\", \"default\": \"USD\" }\n * }\n * }\n */\n configuration: z.object({\n title: z.string().optional(),\n properties: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']).describe('Data type of the setting'),\n default: z.unknown().optional().describe('Default value'),\n description: z.string().optional().describe('Tooltip description'),\n required: z.boolean().optional().describe('Is this setting required?'),\n secret: z.boolean().optional().describe('If true, value is encrypted/masked (e.g. API Keys)'),\n enum: z.array(z.string()).optional().describe('Allowed values for select inputs'),\n })).describe('Map of configuration keys to their definitions')\n }).optional().describe('Plugin configuration settings'),\n\n /**\n * Contribution Points (VS Code Style).\n * formalized way to extend the platform capabilities.\n */\n contributes: z.object({\n /**\n * Register new Metadata Kinds (CRDs).\n * Enables the system to parse and validate new file types.\n * Example: Registering a BI plugin to handle *.report.ts\n */\n kinds: z.array(z.object({\n id: z.string().describe('The generic identifier of the kind (e.g., \"sys.bi.report\")'),\n globs: z.array(z.string()).describe('File patterns to watch (e.g., [\"**/*.report.ts\"])'),\n description: z.string().optional().describe('Description of what this kind represents'),\n })).optional().describe('New Metadata Types to recognize'),\n\n /**\n * Register System Hooks.\n * Declares that this plugin listens to specific system events.\n */\n events: z.array(z.string()).optional().describe('Events this plugin listens to'),\n\n /**\n * Register UI Menus.\n */\n menus: z.record(z.string(), z.array(z.object({\n id: z.string(),\n label: z.string(),\n command: z.string().optional(),\n }))).optional().describe('UI Menu contributions'),\n\n /**\n * Register Custom Themes.\n */\n themes: z.array(z.object({\n id: z.string(),\n label: z.string(),\n path: z.string(),\n })).optional().describe('Theme contributions'),\n\n /**\n * Register Translations.\n * Path to translation files (e.g. \"locales/en.json\").\n */\n translations: z.array(z.object({\n locale: z.string(),\n path: z.string(),\n })).optional().describe('Translation resources'),\n\n /**\n * Register Server Actions.\n * Invocable functions exposed to Flows or API.\n */\n actions: z.array(z.object({\n name: z.string().describe('Unique action name'),\n label: z.string().optional(),\n description: z.string().optional(),\n input: z.unknown().optional().describe('Input validation schema'),\n output: z.unknown().optional().describe('Output schema'),\n })).optional().describe('Exposed server actions'),\n\n /**\n * Register Storage Drivers.\n * Enables connecting to new types of datasources.\n */\n drivers: z.array(z.object({\n id: z.string().describe('Driver unique identifier (e.g. \"postgres\", \"mongo\")'),\n label: z.string().describe('Human readable name'),\n description: z.string().optional(),\n })).optional().describe('Driver contributions'),\n\n /**\n * Register Custom Field Types.\n * Extends the data model with new widget types.\n */\n fieldTypes: z.array(z.object({\n name: z.string().describe('Unique field type name (e.g. \"vector\")'),\n label: z.string().describe('Display label'),\n description: z.string().optional(),\n })).optional().describe('Field Type contributions'),\n \n /**\n * Register Custom Query Operators/Functions.\n * Extends ObjectQL with new functions (e.g. distance()).\n */\n functions: z.array(z.object({\n name: z.string().describe('Function name (e.g. \"distance\")'),\n description: z.string().optional(),\n args: z.array(z.string()).optional().describe('Argument types'),\n returnType: z.string().optional(),\n })).optional().describe('Query Function contributions'),\n\n /**\n * Register API Route Namespaces.\n * Declares the API endpoints this plugin provides to the HttpDispatcher.\n * The kernel routes matching prefixes to this plugin's handler.\n * \n * @example\n * routes: [\n * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] }\n * ]\n */\n routes: z.array(z.object({\n /** URL path prefix (e.g. \"/api/v1/ai\") */\n prefix: z.string().regex(/^\\//).describe('API path prefix'),\n /** Service name this plugin provides */\n service: z.string().describe('Service name this plugin provides'),\n /** Protocol method names implemented */\n methods: z.array(z.string()).optional()\n .describe('Protocol method names implemented (e.g. [\"aiNlq\", \"aiChat\"])'),\n })).optional().describe('API route contributions to HttpDispatcher'),\n\n /**\n * Register CLI Commands.\n * Allows plugins to extend the ObjectStack CLI with custom commands.\n * Each command entry declares metadata; the actual Commander.js command\n * is resolved at runtime by importing the plugin's module.\n * \n * The plugin package must export a `commands` array of Commander.js `Command` instances\n * from its main entry point or from the path specified in `module`.\n * \n * @example\n * ```yaml\n * commands:\n * - name: marketplace\n * description: \"Manage marketplace apps\"\n * module: \"./cli\" # optional, defaults to package main\n * - name: deploy\n * description: \"Deploy to cloud\"\n * ```\n */\n commands: z.array(z.object({\n /** CLI command name (e.g., \"marketplace\", \"deploy\"). Must be a valid CLI identifier. */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n /** Brief description shown in `os --help` */\n description: z.string().optional().describe('Command description for help text'),\n /** \n * Optional module path (relative to package root) that exports the Commander.js commands.\n * If omitted, the CLI will import from the package's main entry point.\n * The module must export a `commands` array of Commander.js `Command` instances,\n * or a single `Command` instance as default export.\n */\n module: z.string().optional().describe('Module path exporting Commander.js commands'),\n })).optional().describe('CLI command contributions'),\n }).optional().describe('Platform contributions'),\n\n /** \n * Initial data seeding configuration.\n * Defines default records to be inserted when the package is installed.\n * \n * Uses the standard DatasetSchema which supports idempotent upsert via\n * `externalId`, environment scoping via `env`, and multiple conflict\n * resolution modes.\n * \n * @deprecated Prefer using the top-level `data` field on the Stack Definition\n * (defineStack({ data: [...] })) for better visibility and metadata registration.\n * This field is retained for backward compatibility with manifest-only packages.\n */\n data: z.array(DatasetSchema).optional().describe('Initial seed data (prefer top-level data field)'),\n\n /**\n * Plugin Capability Manifest.\n * Declares protocols implemented, interfaces provided, dependencies, and extension points.\n * This enables plugin interoperability and automatic discovery.\n */\n capabilities: PluginCapabilityManifestSchema.optional()\n .describe('Plugin capability declarations for interoperability'),\n\n /** \n * Extension points contributed by this package.\n * Allows packages to extend UI components, add functionality, etc.\n */\n extensions: z.record(z.string(), z.unknown()).optional().describe('Extension points and contributions'),\n\n /**\n * Plugin Loading Configuration.\n * Configures how the plugin is loaded, initialized, and managed at runtime.\n * Includes strategies for lazy loading, code splitting, caching, and hot reload.\n */\n loading: PluginLoadingConfigSchema.optional()\n .describe('Plugin loading and runtime behavior configuration'),\n\n /**\n * Platform Compatibility Requirements.\n * Specifies the minimum ObjectStack platform version required to run this package.\n * Used at install time to prevent incompatible packages from being installed.\n *\n * @example\n * ```yaml\n * engine:\n * objectstack: \">=3.0.0\"\n * ```\n */\n engine: z.object({\n /** ObjectStack platform version requirement (SemVer range) */\n objectstack: z.string()\n .regex(/^[><=~^]*\\d+\\.\\d+\\.\\d+/)\n .describe('ObjectStack platform version requirement (SemVer range, e.g. \">=3.0.0\")'),\n }).optional().describe('Platform compatibility requirements'),\n});\n\n/**\n * TypeScript type inferred from the ManifestSchema.\n * Use this type for type-safe manifest handling in TypeScript code.\n */\nexport type ObjectStackManifest = z.infer;\nexport type ObjectStackManifestInput = z.input;\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dependency Resolution Protocol\n *\n * Defines schemas for runtime dependency resolution when installing,\n * upgrading, or managing packages. Provides a standardized way to\n * express dependency conflicts, resolution results, and installation order.\n *\n * ## Architecture Alignment\n * - **npm**: Dependency tree resolution with conflict detection\n * - **Helm**: Dependency management with version constraints\n * - **Salesforce**: Package dependency validation at install time\n *\n * ## Resolution Flow\n * ```\n * 1. Parse manifest.dependencies (SemVer ranges)\n * 2. Check installed packages registry\n * 3. Resolve each dependency → satisfied | needs_install | needs_upgrade | conflict\n * 4. Detect circular dependencies\n * 5. Compute topological install order\n * 6. Return resolution result with required actions\n * ```\n */\n\n// ==========================================\n// Dependency Resolution Status\n// ==========================================\n\n/**\n * Resolution status for a single dependency.\n */\nexport const DependencyStatusEnum = z.enum([\n 'satisfied', // Already installed and version compatible\n 'needs_install', // Not installed, needs to be installed\n 'needs_upgrade', // Installed but version incompatible, needs upgrade\n 'conflict', // Conflicts with another package's dependency\n]).describe('Resolution status for a dependency');\n\nexport type DependencyStatus = z.infer;\n\n// ==========================================\n// Resolved Dependency\n// ==========================================\n\n/**\n * Single dependency resolution result.\n * Describes the state of one dependency after resolution.\n */\nexport const ResolvedDependencySchema = z.object({\n /** Package identifier of the dependency */\n packageId: z.string().describe('Dependency package identifier'),\n\n /** SemVer range required by the parent package */\n requiredRange: z.string().describe('SemVer range required (e.g. \"^2.0.0\")'),\n\n /** Actual version resolved (if available) */\n resolvedVersion: z.string().optional()\n .describe('Actual version resolved from registry'),\n\n /** Currently installed version (if any) */\n installedVersion: z.string().optional()\n .describe('Currently installed version'),\n\n /** Resolution status */\n status: DependencyStatusEnum.describe('Resolution status'),\n\n /** Conflict details (when status is \"conflict\") */\n conflictReason: z.string().optional()\n .describe('Explanation of the conflict'),\n}).describe('Resolution result for a single dependency');\n\nexport type ResolvedDependency = z.infer;\n\n// ==========================================\n// Required Action\n// ==========================================\n\n/**\n * An action required before installation can proceed.\n */\nexport const RequiredActionSchema = z.object({\n /** Type of action required */\n type: z.enum(['install', 'upgrade', 'confirm_conflict'])\n .describe('Type of action required'),\n\n /** Target package identifier */\n packageId: z.string().describe('Target package identifier'),\n\n /** Human-readable description of the action */\n description: z.string().describe('Human-readable action description'),\n}).describe('Action required before installation can proceed');\n\nexport type RequiredAction = z.infer;\n\n// ==========================================\n// Dependency Resolution Result\n// ==========================================\n\n/**\n * Complete dependency resolution result.\n * Aggregates all dependency statuses and computes installation feasibility.\n */\nexport const DependencyResolutionResultSchema = z.object({\n /** All dependencies and their resolution results */\n dependencies: z.array(ResolvedDependencySchema)\n .describe('Resolution result for each dependency'),\n\n /** Whether installation can proceed without conflicts */\n canProceed: z.boolean()\n .describe('Whether installation can proceed'),\n\n /** Actions that require user confirmation or system execution */\n requiredActions: z.array(RequiredActionSchema)\n .describe('Actions required before proceeding'),\n\n /** Topologically sorted package IDs for installation order */\n installOrder: z.array(z.string())\n .describe('Topologically sorted package IDs for installation'),\n\n /** Detected circular dependency chains */\n circularDependencies: z.array(z.array(z.string())).optional()\n .describe('Circular dependency chains detected (e.g. [[\"A\", \"B\", \"A\"]])'),\n}).describe('Complete dependency resolution result');\n\nexport type DependencyResolutionResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\nimport { DependencyResolutionResultSchema } from './dependency-resolution.zod';\n\n/**\n * # Package Registry Protocol\n * \n * Defines the runtime state and lifecycle operations for installed packages.\n * \n * ## Key Distinction: Package vs App\n * - **Package (Manifest)**: The unit of installation — a deployable artifact containing\n * metadata (objects, actions, flows, etc.) and optionally one or more Apps.\n * - **App (AppSchema)**: A UI navigation shell defined inside a package.\n * \n * A package may contain:\n * - Zero apps (pure functionality plugin, e.g. a storage driver)\n * - One app (typical business application)\n * - Multiple apps (suite of applications)\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Packages with install/uninstall lifecycle\n * - **VS Code**: Extension marketplace with enable/disable per-workspace\n * - **Kubernetes**: Helm charts with release state tracking\n * - **npm**: Package registry with install/uninstall/version management\n */\n\n// ==========================================\n// Package Status & Lifecycle\n// ==========================================\n\n/**\n * Package installation status.\n */\nexport const PackageStatusEnum = z.enum([\n 'installed', // Successfully installed and enabled\n 'disabled', // Installed but disabled (metadata not active)\n 'installing', // Installation in progress\n 'upgrading', // Upgrade in progress\n 'uninstalling', // Removal in progress\n 'error', // Installation or runtime error\n]).describe('Package installation status');\nexport type PackageStatus = z.infer;\n\n/**\n * Installed Package Schema\n * \n * Wraps a ManifestSchema with runtime lifecycle state.\n * This is the \"row\" in the installed packages table.\n */\nexport const InstalledPackageSchema = z.object({\n /** \n * The full package manifest (source of truth for package definition).\n */\n manifest: ManifestSchema.describe('Full package manifest'),\n\n /**\n * Current lifecycle status.\n */\n status: PackageStatusEnum.default('installed')\n .describe('Package state: installed, disabled, installing, upgrading, uninstalling, or error'),\n\n /**\n * Whether the package is currently enabled (active).\n * When disabled, the package's metadata is not loaded into the registry.\n */\n enabled: z.boolean().default(true)\n .describe('Whether the package is currently enabled'),\n\n /**\n * ISO 8601 timestamp of when the package was installed.\n */\n installedAt: z.string().datetime().optional()\n .describe('Installation timestamp'),\n\n /**\n * ISO 8601 timestamp of last update.\n */\n updatedAt: z.string().datetime().optional()\n .describe('Last update timestamp'),\n\n /**\n * The currently installed version string.\n * Mirrors manifest.version for quick access without parsing the full manifest.\n */\n installedVersion: z.string().optional()\n .describe('Currently installed version for quick access'),\n\n /**\n * The previously installed version (before last upgrade).\n * Useful for rollback and upgrade tracking.\n */\n previousVersion: z.string().optional()\n .describe('Version before the last upgrade'),\n\n /**\n * ISO 8601 timestamp of when the package was last enabled/disabled.\n */\n statusChangedAt: z.string().datetime().optional()\n .describe('Status change timestamp'),\n\n /**\n * Error message if status is 'error'.\n */\n errorMessage: z.string().optional()\n .describe('Error message when status is error'),\n\n /**\n * Configuration values set by the user for this package.\n * Keys correspond to the package's `configuration.properties`.\n */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided configuration settings'),\n\n /**\n * Upgrade history for this package.\n * Records each version migration with status and optional log.\n */\n upgradeHistory: z.array(z.object({\n /** Previous version before upgrade */\n fromVersion: z.string().describe('Version before upgrade'),\n /** New version after upgrade */\n toVersion: z.string().describe('Version after upgrade'),\n /** Timestamp of the upgrade */\n upgradedAt: z.string().datetime().describe('Upgrade timestamp'),\n /** Outcome of the upgrade */\n status: z.enum(['success', 'failed', 'rolled_back']).describe('Upgrade outcome'),\n /** Migration log entries */\n migrationLog: z.array(z.string()).optional().describe('Migration step logs'),\n })).optional().describe('Version upgrade history'),\n\n /**\n * Namespaces registered by this package.\n * Tracks which namespace prefixes are occupied by this package.\n */\n registeredNamespaces: z.array(z.string()).optional()\n .describe('Namespace prefixes registered by this package'),\n}).describe('Installed package with runtime lifecycle state');\nexport type InstalledPackage = z.infer;\n\n// ==========================================\n// Namespace Registry\n// ==========================================\n\n/**\n * Namespace Registry Entry\n * Tracks namespace ownership within the platform instance.\n */\nexport const NamespaceRegistryEntrySchema = z.object({\n /** Namespace prefix */\n namespace: z.string().describe('Namespace prefix'),\n\n /** Package that owns this namespace */\n packageId: z.string().describe('Owning package ID'),\n\n /** Registration timestamp */\n registeredAt: z.string().datetime().describe('Registration timestamp'),\n\n /** Namespace status */\n status: z.enum(['active', 'disabled', 'reserved'])\n .describe('Namespace status'),\n}).describe('Namespace ownership entry in the registry');\n\nexport type NamespaceRegistryEntry = z.infer;\n\n/**\n * Namespace Conflict Error\n * Describes a namespace collision detected during package installation.\n */\nexport const NamespaceConflictErrorSchema = z.object({\n /** Error type discriminator */\n type: z.literal('namespace_conflict').describe('Error type'),\n\n /** Namespace that was requested */\n requestedNamespace: z.string().describe('Requested namespace'),\n\n /** ID of the package that already owns the namespace */\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n\n /** Name of the conflicting package */\n conflictingPackageName: z.string().describe('Conflicting package display name'),\n\n /** Suggested alternative namespace */\n suggestion: z.string().optional()\n .describe('Suggested alternative namespace'),\n}).describe('Namespace collision error during installation');\n\nexport type NamespaceConflictError = z.infer;\n\n// ==========================================\n// Package Registry Request/Response Schemas\n// ==========================================\n\n/**\n * List Packages Request\n */\nexport const ListPackagesRequestSchema = z.object({\n /** Filter by status */\n status: PackageStatusEnum.optional().describe('Filter by package status'),\n /** Filter by package type */\n type: ManifestSchema.shape.type.optional().describe('Filter by package type'),\n /** Filter by enabled state */\n enabled: z.boolean().optional().describe('Filter by enabled state'),\n}).describe('List packages request');\nexport type ListPackagesRequest = z.infer;\n\n/**\n * List Packages Response\n */\nexport const ListPackagesResponseSchema = z.object({\n packages: z.array(InstalledPackageSchema).describe('List of installed packages'),\n total: z.number().describe('Total package count'),\n}).describe('List packages response');\nexport type ListPackagesResponse = z.infer;\n\n/**\n * Get Package Request\n */\nexport const GetPackageRequestSchema = z.object({\n /** Package ID (reverse domain identifier from manifest) */\n id: z.string().describe('Package identifier'),\n}).describe('Get package request');\nexport type GetPackageRequest = z.infer;\n\n/**\n * Get Package Response\n */\nexport const GetPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Package details'),\n}).describe('Get package response');\nexport type GetPackageResponse = z.infer;\n\n/**\n * Install Package Request\n * \n * Accepts a full manifest to install. In a production system,\n * this might also accept a package ID to fetch from a marketplace.\n */\nexport const InstallPackageRequestSchema = z.object({\n /** The package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n /** Optional: user-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n /** Whether to enable immediately after install (default: true) */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n /**\n * Current platform version for compatibility checking.\n * When provided, the system compares this against the package's\n * `engine.objectstack` requirement to verify compatibility.\n */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n}).describe('Install package request');\nexport type InstallPackageRequest = z.infer;\n\n/**\n * Install Package Response\n */\nexport const InstallPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n message: z.string().optional().describe('Installation status message'),\n /** Dependency resolution result (when dependencies were analyzed) */\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result from install analysis'),\n}).describe('Install package response');\nexport type InstallPackageResponse = z.infer;\n\n/**\n * Uninstall Package Request\n */\nexport const UninstallPackageRequestSchema = z.object({\n /** Package ID to uninstall */\n id: z.string().describe('Package ID to uninstall'),\n}).describe('Uninstall package request');\nexport type UninstallPackageRequest = z.infer;\n\n/**\n * Uninstall Package Response\n */\nexport const UninstallPackageResponseSchema = z.object({\n id: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n}).describe('Uninstall package response');\nexport type UninstallPackageResponse = z.infer;\n\n/**\n * Enable Package Request\n */\nexport const EnablePackageRequestSchema = z.object({\n /** Package ID to enable */\n id: z.string().describe('Package ID to enable'),\n}).describe('Enable package request');\nexport type EnablePackageRequest = z.infer;\n\n/**\n * Enable Package Response\n */\nexport const EnablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Enabled package details'),\n message: z.string().optional().describe('Enable status message'),\n}).describe('Enable package response');\nexport type EnablePackageResponse = z.infer;\n\n/**\n * Disable Package Request\n */\nexport const DisablePackageRequestSchema = z.object({\n /** Package ID to disable */\n id: z.string().describe('Package ID to disable'),\n}).describe('Disable package request');\nexport type DisablePackageRequest = z.infer;\n\n/**\n * Disable Package Response\n */\nexport const DisablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Disabled package details'),\n message: z.string().optional().describe('Disable status message'),\n}).describe('Disable package response');\nexport type DisablePackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ViewSchema } from '../ui/view.zod';\nimport { DiscoverySchema } from './discovery.zod';\nimport { BatchUpdateRequestSchema, BatchUpdateResponseSchema, BatchOptionsSchema } from './batch.zod';\nimport { MetadataCacheRequestSchema, MetadataCacheResponseSchema } from './http-cache.zod';\nimport { QuerySchema } from '../data/query.zod';\nimport { \n AnalyticsQueryRequestSchema, \n AnalyticsResultResponseSchema, \n GetAnalyticsMetaRequestSchema, \n AnalyticsMetadataResponseSchema \n} from './analytics.zod';\nimport { RealtimePresenceSchema, TransportProtocol } from './realtime.zod';\nimport { ObjectPermissionSchema, FieldPermissionSchema } from '../security/permission.zod';\nimport { WorkflowRuleSchema } from '../automation/workflow.zod';\nimport { TranslationDataSchema } from '../system/translation.zod';\nimport type {\n GetFeedRequest,\n GetFeedResponse,\n CreateFeedItemRequest,\n CreateFeedItemResponse,\n UpdateFeedItemRequest,\n UpdateFeedItemResponse,\n DeleteFeedItemRequest,\n DeleteFeedItemResponse,\n AddReactionRequest,\n AddReactionResponse,\n RemoveReactionRequest,\n RemoveReactionResponse,\n PinFeedItemRequest,\n PinFeedItemResponse,\n UnpinFeedItemRequest,\n UnpinFeedItemResponse,\n StarFeedItemRequest,\n StarFeedItemResponse,\n UnstarFeedItemRequest,\n UnstarFeedItemResponse,\n SearchFeedRequest,\n SearchFeedResponse,\n GetChangelogRequest,\n GetChangelogResponse,\n SubscribeRequest,\n SubscribeResponse,\n FeedUnsubscribeRequest,\n UnsubscribeResponse,\n} from './feed-api.zod';\nimport {\n ListPackagesRequestSchema,\n ListPackagesResponseSchema,\n GetPackageRequestSchema,\n GetPackageResponseSchema,\n InstallPackageRequestSchema,\n InstallPackageResponseSchema,\n UninstallPackageRequestSchema,\n UninstallPackageResponseSchema,\n EnablePackageRequestSchema,\n EnablePackageResponseSchema,\n DisablePackageRequestSchema,\n DisablePackageResponseSchema,\n} from '../kernel/package-registry.zod';\nimport type {\n ListPackagesRequest,\n ListPackagesResponse,\n GetPackageRequest,\n GetPackageResponse,\n InstallPackageRequest,\n InstallPackageResponse,\n UninstallPackageRequest,\n UninstallPackageResponse,\n EnablePackageRequest,\n EnablePackageResponse,\n DisablePackageRequest,\n DisablePackageResponse,\n InstalledPackage,\n PackageStatus,\n} from '../kernel/package-registry.zod';\n\nexport const AutomationTriggerRequestSchema = z.object({\n trigger: z.string(),\n payload: z.record(z.string(), z.unknown())\n});\n\nexport const AutomationTriggerResponseSchema = z.object({\n success: z.boolean(),\n jobId: z.string().optional(),\n result: z.unknown().optional()\n});\n\n/**\n * ObjectStack Protocol - Zod Schema Definitions\n * \n * Defines the runtime-validated contract for interacting with ObjectStack metadata and data.\n * Used by API adapters (HTTP, WebSocket, gRPC) to fetch data/metadata without knowing engine internals.\n * \n * This protocol enables:\n * - Runtime request/response validation at API gateway level\n * - Automatic API documentation generation\n * - Type-safe RPC communication between microservices\n * - Client SDK generation from schemas\n * \n * Architecture Alignment:\n * - Salesforce: REST API Request/Response schemas\n * - Kubernetes: API Resource schemas with runtime validation\n * - GraphQL: Schema-first API design\n */\n\n// ==========================================\n// Discovery & Metadata Operations\n// ==========================================\n\n/**\n * Get API Discovery Request\n * No parameters needed\n */\nexport const GetDiscoveryRequestSchema = z.object({});\n\n/**\n * Get API Discovery Response\n * Derived from DiscoverySchema (single source of truth) for protocol-level use.\n * \n * All fields from DiscoverySchema are available but made optional (except `version`)\n * to support progressive disclosure and backward compatibility with existing clients.\n * \n * - `routes` provides a flat endpoint map for client routing.\n * - `services` is the single source of truth for service availability.\n * - `apiName` is kept as an optional alias for `name` for backward compatibility.\n * \n * @see DiscoverySchema in ./discovery.zod.ts — the canonical definition.\n */\nexport const GetDiscoveryResponseSchema = DiscoverySchema\n .partial()\n .required({ version: true })\n .extend({\n /** @deprecated Use `name` instead. Kept for backward compatibility. */\n apiName: z.string().optional().describe('API name (deprecated — use name)'),\n });\n\n/**\n * Get Metadata Types Request\n */\nexport const GetMetaTypesRequestSchema = z.object({});\n\n/**\n * Get Metadata Types Response\n */\nexport const GetMetaTypesResponseSchema = z.object({\n types: z.array(z.string()).describe('Available metadata type names (e.g., \"object\", \"plugin\", \"view\")'),\n});\n\n/**\n * Get Metadata Items Request\n * Get all items of a specific metadata type\n */\nexport const GetMetaItemsRequestSchema = z.object({\n type: z.string().describe('Metadata type name (e.g., \"object\", \"plugin\")'),\n packageId: z.string().optional().describe('Optional package ID to filter items by'),\n});\n\n/**\n * Get Metadata Items Response\n */\nexport const GetMetaItemsResponseSchema = z.object({\n type: z.string().describe('Metadata type name'),\n items: z.array(z.unknown()).describe('Array of metadata items'),\n});\n\n/**\n * Get Metadata Item Request\n * Get a specific metadata item by type and name\n */\nexport const GetMetaItemRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name (snake_case identifier)'),\n packageId: z.string().optional().describe('Optional package ID to filter items by'),\n});\n\n/**\n * Get Metadata Item Response\n */\nexport const GetMetaItemResponseSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n item: z.unknown().describe('Metadata item definition'),\n});\n\n/**\n * Save Metadata Item Request\n * Create or update a metadata item\n */\nexport const SaveMetaItemRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n item: z.unknown().describe('Metadata item definition'),\n});\n\n/**\n * Save Metadata Item Response\n */\nexport const SaveMetaItemResponseSchema = z.object({\n success: z.boolean(),\n message: z.string().optional(),\n});\n\n/**\n * Get Metadata Item with Cache Request\n * Get a specific metadata item with HTTP cache validation support\n */\nexport const GetMetaItemCachedRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n cacheRequest: MetadataCacheRequestSchema.optional().describe('Cache validation parameters'),\n});\n\n/**\n * Get Metadata Item with Cache Response\n * Uses MetadataCacheResponse from http-cache.zod.ts\n */\nexport const GetMetaItemCachedResponseSchema = MetadataCacheResponseSchema;\n\n/**\n * Get UI View Request\n * Resolves the appropriate UI view for an object based on context.\n * Unlike getMetaItem, this does not require a specific View ID.\n */\nexport const GetUiViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n type: z.enum(['list', 'form']).describe('View type'),\n});\n\n/**\n * Get UI View Response\n */\nexport const GetUiViewResponseSchema = ViewSchema;\n\n// ==========================================\n// Data Operations\n// ==========================================\n\n/**\n * Find Data Request\n * Defines a query to retrieve records from a specific object.\n * Supports filtering, sorting, pagination, and field selection.\n * \n * @example\n * {\n * \"object\": \"customers\",\n * \"query\": {\n * \"where\": { \"status\": \"active\", \"revenue\": { \"$gt\": 10000 } },\n * \"orderBy\": [{ \"field\": \"name\", \"order\": \"desc\" }],\n * \"limit\": 10\n * }\n * }\n */\nexport const FindDataRequestSchema = z.object({\n object: z.string().describe('The unique machine name of the object to query (e.g. \"account\").'),\n query: QuerySchema.optional().describe('Structured query definition (filter, sort, select, pagination).'),\n});\n\n/**\n * Find Data Response\n * Returns a list of records matching the query criteria.\n */\nexport const FindDataResponseSchema = z.object({\n object: z.string().describe('The object name for the returned records.'),\n records: z.array(z.record(z.string(), z.unknown())).describe('The list of matching records.'),\n total: z.number().optional().describe('Total number of records matching the filter (if requested).'),\n nextCursor: z.string().optional().describe('Cursor for the next page of results (cursor-based pagination).'),\n hasMore: z.boolean().optional().describe('True if there are more records available (pagination).'),\n});\n\n/**\n * HTTP Find Query Parameters\n * \n * Canonical HTTP query parameter names for GET /data/:object list endpoints.\n * The canonical filter parameter is `filter` (singular). The plural `filters` is\n * accepted for backward compatibility but `filter` is the standard going forward.\n * \n * This schema defines the allowlisted query parameters for HTTP GET list requests.\n * Server-side parsers (protocol.ts) should accept both `filter` and `filters` and\n * normalize to `filter` (singular) internally.\n * \n * @example\n * GET /api/v1/data/contacts?filter={\"status\":\"active\"}&select=name,email&top=10&sort=name\n */\nexport const HttpFindQueryParamsSchema = z.object({\n /** @canonical Singular form — the standard going forward. JSON string of filter expression or AST. */\n filter: z.string().optional().describe('JSON-encoded filter expression (canonical, singular).'),\n /** @deprecated Use `filter` (singular). Accepted for backward compatibility. */\n filters: z.string().optional().describe('JSON-encoded filter expression (deprecated plural alias).'),\n select: z.string().optional().describe('Comma-separated list of fields to retrieve.'),\n sort: z.string().optional().describe('Sort expression (e.g. \"name asc,created_at desc\" or \"-created_at\").'),\n orderBy: z.string().optional().describe('Alias for sort (OData compatibility).'),\n top: z.coerce.number().optional().describe('Max records to return (limit).'),\n skip: z.coerce.number().optional().describe('Records to skip (offset).'),\n expand: z.string().optional().describe(\n 'Comma-separated list of lookup/master_detail field names to expand. '\n + 'Resolved to populate array and passed to the engine for batch $in expansion.'\n ),\n search: z.string().optional().describe('Full-text search query.'),\n distinct: z.coerce.boolean().optional().describe('SELECT DISTINCT flag.'),\n count: z.coerce.boolean().optional().describe('Include total count in response.'),\n});\n\n/**\n * Get Data Request\n * Retrieval of a single record by its unique identifier.\n * Only `select` and `expand` are permitted as additional query parameters.\n * All other query parameters should be discarded to prevent parameter pollution.\n * \n * @example\n * {\n * \"object\": \"contracts\",\n * \"id\": \"cnt_123456\",\n * \"select\": [\"name\", \"status\", \"amount\"],\n * \"expand\": [\"owner\", \"account\"]\n * }\n */\nexport const GetDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The unique record identifier (primary key).'),\n select: z.array(z.string()).optional().describe('Fields to include in the response (allowlisted query param).'),\n expand: z.array(z.string()).optional().describe(\n 'Lookup/master_detail field names to expand. '\n + 'The engine resolves these via batch $in queries, replacing foreign key IDs with full objects.'\n ),\n});\n\n/**\n * Get Data Response\n */\nexport const GetDataResponseSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The record ID.'),\n record: z.record(z.string(), z.unknown()).describe('The complete record data.'),\n});\n\n/**\n * Create Data Request\n * Creation of a new record.\n * \n * @example\n * {\n * \"object\": \"leads\",\n * \"data\": {\n * \"first_name\": \"John\",\n * \"last_name\": \"Doe\",\n * \"company\": \"Acme Inc\"\n * }\n * }\n */\nexport const CreateDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n data: z.record(z.string(), z.unknown()).describe('The dictionary of field values to insert.'),\n});\n\n/**\n * Create Data Response\n */\nexport const CreateDataResponseSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The ID of the newly created record.'),\n record: z.record(z.string(), z.unknown()).describe('The created record, including server-generated fields (created_at, owner).'),\n});\n\n/**\n * Update Data Request\n * Modification of an existing record.\n * \n * @example\n * {\n * \"object\": \"tasks\",\n * \"id\": \"tsk_001\",\n * \"data\": {\n * \"status\": \"completed\",\n * \"percent_complete\": 100\n * }\n * }\n */\nexport const UpdateDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The ID of the record to update.'),\n data: z.record(z.string(), z.unknown()).describe('The fields to update (partial update).'),\n});\n\n/**\n * Update Data Response\n */\nexport const UpdateDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Updated record ID'),\n record: z.record(z.string(), z.unknown()).describe('Updated record'),\n});\n\n/**\n * Delete Data Request\n */\nexport const DeleteDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Record ID to delete'),\n});\n\n/**\n * Delete Data Response\n */\nexport const DeleteDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Deleted record ID'),\n success: z.boolean().describe('Whether deletion succeeded'),\n});\n\n// ==========================================\n// Batch Operations\n// ==========================================\n\n/**\n * Batch Data Request\n */\nexport const BatchDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n request: BatchUpdateRequestSchema.describe('Batch operation request'),\n});\n\n/**\n * Batch Data Response\n * Uses BatchUpdateResponse from batch.zod.ts\n */\nexport const BatchDataResponseSchema = BatchUpdateResponseSchema;\n\n/**\n * Create Many Data Request\n */\nexport const CreateManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.record(z.string(), z.unknown())).describe('Array of records to create'),\n});\n\n/**\n * Create Many Data Response\n */\nexport const CreateManyDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.record(z.string(), z.unknown())).describe('Created records'),\n count: z.number().describe('Number of records created'),\n});\n\n/**\n * Update Many Data Request\n */\nexport const UpdateManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.object({\n id: z.string().describe('Record ID'),\n data: z.record(z.string(), z.unknown()).describe('Fields to update'),\n })).describe('Array of updates'),\n options: BatchOptionsSchema.optional().describe('Update options'),\n});\n\n/**\n * Update Many Data Response\n * Uses BatchUpdateResponse for consistency\n */\nexport const UpdateManyDataResponseSchema = BatchUpdateResponseSchema;\n\n/**\n * Delete Many Data Request\n */\nexport const DeleteManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n ids: z.array(z.string()).describe('Array of record IDs to delete'),\n options: BatchOptionsSchema.optional().describe('Delete options'),\n});\n\n/**\n * Delete Many Data Response\n */\nexport const DeleteManyDataResponseSchema = BatchUpdateResponseSchema;\n\n// ==========================================\n// Package Management Operations\n// ==========================================\n\n/**\n * Re-export Package Management Request/Response schemas from kernel.\n * These define the contract for package lifecycle management:\n * - List installed packages (with filters)\n * - Get a specific package by ID\n * - Install a new package (from manifest)\n * - Uninstall a package\n * - Enable/Disable a package\n * \n * Key distinction: Package (ManifestSchema) is the unit of installation.\n * An App (AppSchema) is a UI navigation entity within a package.\n * A package may contain 0, 1, or many apps.\n */\nexport {\n ListPackagesRequestSchema,\n ListPackagesResponseSchema,\n GetPackageRequestSchema,\n GetPackageResponseSchema,\n InstallPackageRequestSchema,\n InstallPackageResponseSchema,\n UninstallPackageRequestSchema,\n UninstallPackageResponseSchema,\n EnablePackageRequestSchema,\n EnablePackageResponseSchema,\n DisablePackageRequestSchema,\n DisablePackageResponseSchema,\n};\n\n// ==========================================\n// View Management Operations\n// ==========================================\n\nexport const ListViewsRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n type: z.enum(['list', 'form']).optional().describe('Filter by view type'),\n});\n\nexport const ListViewsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n views: z.array(ViewSchema).describe('Array of view definitions'),\n});\n\nexport const GetViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier'),\n});\n\nexport const GetViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n view: ViewSchema.describe('View definition'),\n});\n\nexport const CreateViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n data: ViewSchema.describe('View definition to create'),\n});\n\nexport const CreateViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Created view identifier'),\n view: ViewSchema.describe('Created view definition'),\n});\n\nexport const UpdateViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier'),\n data: ViewSchema.partial().describe('Partial view data to update'),\n});\n\nexport const UpdateViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Updated view identifier'),\n view: ViewSchema.describe('Updated view definition'),\n});\n\nexport const DeleteViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier to delete'),\n});\n\nexport const DeleteViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Deleted view identifier'),\n success: z.boolean().describe('Whether deletion succeeded'),\n});\n\n// ==========================================\n// Permission Operations\n// ==========================================\n\nexport const CheckPermissionRequestSchema = z.object({\n object: z.string().describe('Object name to check permissions for'),\n action: z.enum(['create', 'read', 'edit', 'delete', 'transfer', 'restore', 'purge']).describe('Action to check'),\n recordId: z.string().optional().describe('Specific record ID (for record-level checks)'),\n field: z.string().optional().describe('Specific field name (for field-level checks)'),\n});\n\nexport const CheckPermissionResponseSchema = z.object({\n allowed: z.boolean().describe('Whether the action is permitted'),\n reason: z.string().optional().describe('Reason if denied'),\n});\n\nexport const GetObjectPermissionsRequestSchema = z.object({\n object: z.string().describe('Object name to get permissions for'),\n});\n\nexport const GetObjectPermissionsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n permissions: ObjectPermissionSchema.describe('Object-level permissions'),\n fieldPermissions: z.record(z.string(), FieldPermissionSchema).optional().describe('Field-level permissions keyed by field name'),\n});\n\nexport const GetEffectivePermissionsRequestSchema = z.object({});\n\nexport const GetEffectivePermissionsResponseSchema = z.object({\n objects: z.record(z.string(), ObjectPermissionSchema).describe('Effective object permissions keyed by object name'),\n systemPermissions: z.array(z.string()).describe('Effective system-level permissions'),\n});\n\n// ==========================================\n// Workflow Operations\n// ==========================================\n\nexport const GetWorkflowConfigRequestSchema = z.object({\n object: z.string().describe('Object name to get workflow config for'),\n});\n\nexport const GetWorkflowConfigResponseSchema = z.object({\n object: z.string().describe('Object name'),\n workflows: z.array(WorkflowRuleSchema).describe('Active workflow rules for this object'),\n});\n\nexport const WorkflowStateSchema = z.object({\n currentState: z.string().describe('Current workflow state name'),\n availableTransitions: z.array(z.object({\n name: z.string().describe('Transition name'),\n targetState: z.string().describe('Target state after transition'),\n label: z.string().optional().describe('Display label'),\n requiresApproval: z.boolean().default(false).describe('Whether transition requires approval'),\n })).describe('Available transitions from current state'),\n history: z.array(z.object({\n fromState: z.string().describe('Previous state'),\n toState: z.string().describe('New state'),\n action: z.string().describe('Action that triggered the transition'),\n userId: z.string().describe('User who performed the action'),\n timestamp: z.string().datetime().describe('When the transition occurred'),\n comment: z.string().optional().describe('Optional comment'),\n })).optional().describe('State transition history'),\n});\n\nexport const GetWorkflowStateRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID to get workflow state for'),\n});\n\nexport const GetWorkflowStateResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n state: WorkflowStateSchema.describe('Current workflow state and available transitions'),\n});\n\nexport const WorkflowTransitionRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n transition: z.string().describe('Transition name to execute'),\n comment: z.string().optional().describe('Optional comment for the transition'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data for the transition'),\n});\n\nexport const WorkflowTransitionResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the transition succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after transition'),\n});\n\nexport const WorkflowApproveRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n comment: z.string().optional().describe('Approval comment'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data'),\n});\n\nexport const WorkflowApproveResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the approval succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after approval'),\n});\n\nexport const WorkflowRejectRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n reason: z.string().describe('Rejection reason'),\n comment: z.string().optional().describe('Additional comment'),\n});\n\nexport const WorkflowRejectResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the rejection succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after rejection'),\n});\n\n// ==========================================\n// Realtime Operations\n// ==========================================\n\nexport const RealtimeConnectRequestSchema = z.object({\n transport: TransportProtocol.optional().describe('Preferred transport protocol'),\n channels: z.array(z.string()).optional().describe('Channels to subscribe to on connect'),\n token: z.string().optional().describe('Authentication token'),\n});\n\nexport const RealtimeConnectResponseSchema = z.object({\n connectionId: z.string().describe('Unique connection identifier'),\n transport: TransportProtocol.describe('Negotiated transport protocol'),\n url: z.string().optional().describe('WebSocket/SSE endpoint URL'),\n});\n\nexport const RealtimeDisconnectRequestSchema = z.object({\n connectionId: z.string().optional().describe('Connection ID to disconnect'),\n});\n\nexport const RealtimeDisconnectResponseSchema = z.object({\n success: z.boolean().describe('Whether disconnection succeeded'),\n});\n\nexport const RealtimeSubscribeRequestSchema = z.object({\n channel: z.string().describe('Channel name to subscribe to'),\n events: z.array(z.string()).optional().describe('Specific event types to listen for'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Event filter criteria'),\n});\n\nexport const RealtimeSubscribeResponseSchema = z.object({\n subscriptionId: z.string().describe('Unique subscription identifier'),\n channel: z.string().describe('Subscribed channel name'),\n});\n\nexport const RealtimeUnsubscribeRequestSchema = z.object({\n subscriptionId: z.string().describe('Subscription ID to cancel'),\n});\n\nexport const RealtimeUnsubscribeResponseSchema = z.object({\n success: z.boolean().describe('Whether unsubscription succeeded'),\n});\n\nexport const SetPresenceRequestSchema = z.object({\n channel: z.string().describe('Channel to set presence in'),\n state: RealtimePresenceSchema.describe('Presence state to set'),\n});\n\nexport const SetPresenceResponseSchema = z.object({\n success: z.boolean().describe('Whether presence was set'),\n});\n\nexport const GetPresenceRequestSchema = z.object({\n channel: z.string().describe('Channel to get presence for'),\n});\n\nexport const GetPresenceResponseSchema = z.object({\n channel: z.string().describe('Channel name'),\n members: z.array(RealtimePresenceSchema).describe('Active members and their presence state'),\n});\n\n// ==========================================\n// Notification Operations\n// ==========================================\n\nexport const RegisterDeviceRequestSchema = z.object({\n token: z.string().describe('Device push notification token'),\n platform: z.enum(['ios', 'android', 'web']).describe('Device platform'),\n deviceId: z.string().optional().describe('Unique device identifier'),\n name: z.string().optional().describe('Device friendly name'),\n});\n\nexport const RegisterDeviceResponseSchema = z.object({\n deviceId: z.string().describe('Registered device ID'),\n success: z.boolean().describe('Whether registration succeeded'),\n});\n\nexport const UnregisterDeviceRequestSchema = z.object({\n deviceId: z.string().describe('Device ID to unregister'),\n});\n\nexport const UnregisterDeviceResponseSchema = z.object({\n success: z.boolean().describe('Whether unregistration succeeded'),\n});\n\nexport const NotificationPreferencesSchema = z.object({\n email: z.boolean().default(true).describe('Receive email notifications'),\n push: z.boolean().default(true).describe('Receive push notifications'),\n inApp: z.boolean().default(true).describe('Receive in-app notifications'),\n digest: z.enum(['none', 'daily', 'weekly']).default('none').describe('Email digest frequency'),\n channels: z.record(z.string(), z.object({\n enabled: z.boolean().default(true).describe('Whether this channel is enabled'),\n email: z.boolean().optional().describe('Override email setting'),\n push: z.boolean().optional().describe('Override push setting'),\n })).optional().describe('Per-channel notification preferences'),\n});\n\nexport const GetNotificationPreferencesRequestSchema = z.object({});\n\nexport const GetNotificationPreferencesResponseSchema = z.object({\n preferences: NotificationPreferencesSchema.describe('Current notification preferences'),\n});\n\nexport const UpdateNotificationPreferencesRequestSchema = z.object({\n preferences: NotificationPreferencesSchema.partial().describe('Preferences to update'),\n});\n\nexport const UpdateNotificationPreferencesResponseSchema = z.object({\n preferences: NotificationPreferencesSchema.describe('Updated notification preferences'),\n});\n\nexport const NotificationSchema = z.object({\n id: z.string().describe('Notification ID'),\n type: z.string().describe('Notification type'),\n title: z.string().describe('Notification title'),\n body: z.string().describe('Notification body text'),\n read: z.boolean().default(false).describe('Whether notification has been read'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional notification data'),\n actionUrl: z.string().optional().describe('URL to navigate to when clicked'),\n createdAt: z.string().datetime().describe('When notification was created'),\n});\n\nexport const ListNotificationsRequestSchema = z.object({\n read: z.boolean().optional().describe('Filter by read status'),\n type: z.string().optional().describe('Filter by notification type'),\n limit: z.number().default(20).describe('Maximum number of notifications to return'),\n cursor: z.string().optional().describe('Pagination cursor'),\n});\n\nexport const ListNotificationsResponseSchema = z.object({\n notifications: z.array(NotificationSchema).describe('List of notifications'),\n unreadCount: z.number().describe('Total number of unread notifications'),\n cursor: z.string().optional().describe('Next page cursor'),\n});\n\nexport const MarkNotificationsReadRequestSchema = z.object({\n ids: z.array(z.string()).describe('Notification IDs to mark as read'),\n});\n\nexport const MarkNotificationsReadResponseSchema = z.object({\n success: z.boolean().describe('Whether the operation succeeded'),\n readCount: z.number().describe('Number of notifications marked as read'),\n});\n\nexport const MarkAllNotificationsReadRequestSchema = z.object({});\n\nexport const MarkAllNotificationsReadResponseSchema = z.object({\n success: z.boolean().describe('Whether the operation succeeded'),\n readCount: z.number().describe('Number of notifications marked as read'),\n});\n\n// ==========================================\n// AI Operations\n// ==========================================\n\nexport const AiNlqRequestSchema = z.object({\n query: z.string().describe('Natural language query string'),\n object: z.string().optional().describe('Target object context'),\n conversationId: z.string().optional().describe('Conversation ID for multi-turn queries'),\n});\n\nexport const AiNlqResponseSchema = z.object({\n query: z.unknown().describe('Generated structured query (AST)'),\n explanation: z.string().optional().describe('Human-readable explanation of the query'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n suggestions: z.array(z.string()).optional().describe('Suggested follow-up queries'),\n});\n\n// AiChatRequestSchema and AiChatResponseSchema have been removed.\n// The AI chat wire protocol is now fully aligned with the Vercel AI SDK (`ai`).\n// Frontend consumers should use `@ai-sdk/react/useChat` directly.\n// See: https://ai-sdk.dev/docs\n\nexport const AiSuggestRequestSchema = z.object({\n object: z.string().describe('Object name for context'),\n field: z.string().optional().describe('Field to suggest values for'),\n recordId: z.string().optional().describe('Record ID for context'),\n partial: z.string().optional().describe('Partial input for completion'),\n});\n\nexport const AiSuggestResponseSchema = z.object({\n suggestions: z.array(z.object({\n value: z.unknown().describe('Suggested value'),\n label: z.string().describe('Display label'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n reason: z.string().optional().describe('Reason for this suggestion'),\n })).describe('Suggested values'),\n});\n\nexport const AiInsightsRequestSchema = z.object({\n object: z.string().describe('Object name to analyze'),\n recordId: z.string().optional().describe('Specific record to analyze'),\n type: z.enum(['summary', 'trends', 'anomalies', 'recommendations']).optional().describe('Type of insight'),\n});\n\nexport const AiInsightsResponseSchema = z.object({\n insights: z.array(z.object({\n type: z.string().describe('Insight type'),\n title: z.string().describe('Insight title'),\n description: z.string().describe('Detailed description'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n data: z.record(z.string(), z.unknown()).optional().describe('Supporting data'),\n })).describe('Generated insights'),\n});\n\n// ==========================================\n// i18n Operations\n// ==========================================\n\nexport const GetLocalesRequestSchema = z.object({});\n\nexport const GetLocalesResponseSchema = z.object({\n locales: z.array(z.object({\n code: z.string().describe('BCP-47 locale code (e.g., en-US, zh-CN)'),\n label: z.string().describe('Display name of the locale'),\n isDefault: z.boolean().default(false).describe('Whether this is the default locale'),\n })).describe('Available locales'),\n});\n\nexport const GetTranslationsRequestSchema = z.object({\n locale: z.string().describe('BCP-47 locale code'),\n namespace: z.string().optional().describe('Translation namespace (e.g., objects, apps, messages)'),\n keys: z.array(z.string()).optional().describe('Specific translation keys to fetch'),\n});\n\nexport const GetTranslationsResponseSchema = z.object({\n locale: z.string().describe('Locale code'),\n translations: TranslationDataSchema.describe('Translation data'),\n});\n\nexport const GetFieldLabelsRequestSchema = z.object({\n object: z.string().describe('Object name'),\n locale: z.string().describe('BCP-47 locale code'),\n});\n\nexport const GetFieldLabelsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n locale: z.string().describe('Locale code'),\n labels: z.record(z.string(), z.object({\n label: z.string().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n options: z.record(z.string(), z.string()).optional().describe('Translated option labels'),\n })).describe('Field labels keyed by field name'),\n});\n\n// ==========================================\n// Protocol Interface Schema\n// ==========================================\n\n/**\n * ObjectStack Protocol Contract\n * \n * This schema defines the complete API contract as a Zod schema.\n * Unlike the old TypeScript interface, this provides runtime validation\n * and can be used for:\n * - API Gateway validation\n * - RPC call validation\n * - Client SDK generation\n * - API documentation generation\n * \n * Each method is defined with its request and response schemas.\n */\nexport const ObjectStackProtocolSchema = z.object({\n // Discovery & Metadata\n getDiscovery: z.function()\n .describe('Get API discovery information'),\n\n getMetaTypes: z.function()\n .describe('Get available metadata types'),\n\n getMetaItems: z.function()\n .describe('Get all items of a metadata type'),\n\n getMetaItem: z.function()\n .describe('Get a specific metadata item'),\n saveMetaItem: z.function()\n .describe('Save metadata item'),\n getMetaItemCached: z.function()\n .describe('Get a metadata item with cache validation'),\n\n getUiView: z.function()\n .describe('Get UI view definition'),\n\n // Analytics Operations\n analyticsQuery: z.function()\n .describe('Execute analytics query'),\n\n getAnalyticsMeta: z.function()\n .describe('Get analytics metadata (cubes)'),\n\n // Automation Operations\n triggerAutomation: z.function()\n .describe('Trigger an automation flow or script'),\n\n // Package Management Operations\n listPackages: z.function()\n .describe('List installed packages with optional filters'),\n\n getPackage: z.function()\n .describe('Get a specific installed package by ID'),\n\n installPackage: z.function()\n .describe('Install a new package from manifest'),\n\n uninstallPackage: z.function()\n .describe('Uninstall a package by ID'),\n\n enablePackage: z.function()\n .describe('Enable a disabled package'),\n\n disablePackage: z.function()\n .describe('Disable an installed package'),\n\n // Data Operations\n findData: z.function()\n .describe('Find data records'),\n\n getData: z.function()\n .describe('Get single data record'),\n\n createData: z.function()\n .describe('Create a data record'),\n\n updateData: z.function()\n .describe('Update a data record'),\n\n deleteData: z.function()\n .describe('Delete a data record'),\n\n // Batch Operations\n batchData: z.function()\n .describe('Perform batch operations'),\n\n createManyData: z.function()\n .describe('Create multiple records'),\n\n updateManyData: z.function()\n .describe('Update multiple records'),\n\n deleteManyData: z.function()\n .describe('Delete multiple records'),\n\n // View Management Operations\n listViews: z.function()\n .describe('List views for an object'),\n getView: z.function()\n .describe('Get a specific view'),\n createView: z.function()\n .describe('Create a new view'),\n updateView: z.function()\n .describe('Update an existing view'),\n deleteView: z.function()\n .describe('Delete a view'),\n\n // Permission Operations\n checkPermission: z.function()\n .describe('Check if an action is permitted'),\n getObjectPermissions: z.function()\n .describe('Get permissions for an object'),\n getEffectivePermissions: z.function()\n .describe('Get effective permissions for current user'),\n\n // Workflow Operations\n getWorkflowConfig: z.function()\n .describe('Get workflow configuration for an object'),\n getWorkflowState: z.function()\n .describe('Get workflow state for a record'),\n workflowTransition: z.function()\n .describe('Execute a workflow state transition'),\n workflowApprove: z.function()\n .describe('Approve a workflow step'),\n workflowReject: z.function()\n .describe('Reject a workflow step'),\n\n // Realtime Operations\n realtimeConnect: z.function()\n .describe('Establish realtime connection'),\n realtimeDisconnect: z.function()\n .describe('Close realtime connection'),\n realtimeSubscribe: z.function()\n .describe('Subscribe to a realtime channel'),\n realtimeUnsubscribe: z.function()\n .describe('Unsubscribe from a realtime channel'),\n setPresence: z.function()\n .describe('Set user presence state'),\n getPresence: z.function()\n .describe('Get channel presence information'),\n\n // Notification Operations\n registerDevice: z.function()\n .describe('Register a device for push notifications'),\n unregisterDevice: z.function()\n .describe('Unregister a device'),\n getNotificationPreferences: z.function()\n .describe('Get notification preferences'),\n updateNotificationPreferences: z.function()\n .describe('Update notification preferences'),\n listNotifications: z.function()\n .describe('List notifications'),\n markNotificationsRead: z.function()\n .describe('Mark specific notifications as read'),\n markAllNotificationsRead: z.function()\n .describe('Mark all notifications as read'),\n\n // AI Operations\n aiNlq: z.function()\n .describe('Natural language query'),\n aiChat: z.function()\n .describe('AI chat interaction'),\n aiSuggest: z.function()\n .describe('Get AI-powered suggestions'),\n aiInsights: z.function()\n .describe('Get AI-generated insights'),\n\n // i18n Operations\n getLocales: z.function()\n .describe('Get available locales'),\n getTranslations: z.function()\n .describe('Get translations for a locale'),\n getFieldLabels: z.function()\n .describe('Get translated field labels for an object'),\n\n // Feed Operations\n listFeed: z.function()\n .describe('List feed items for a record'),\n createFeedItem: z.function()\n .describe('Create a new feed item'),\n updateFeedItem: z.function()\n .describe('Update an existing feed item'),\n deleteFeedItem: z.function()\n .describe('Delete a feed item'),\n addReaction: z.function()\n .describe('Add an emoji reaction to a feed item'),\n removeReaction: z.function()\n .describe('Remove an emoji reaction from a feed item'),\n pinFeedItem: z.function()\n .describe('Pin a feed item'),\n unpinFeedItem: z.function()\n .describe('Unpin a feed item'),\n starFeedItem: z.function()\n .describe('Star a feed item'),\n unstarFeedItem: z.function()\n .describe('Unstar a feed item'),\n searchFeed: z.function()\n .describe('Search feed items'),\n getChangelog: z.function()\n .describe('Get field-level changelog for a record'),\n feedSubscribe: z.function()\n .describe('Subscribe to record notifications'),\n feedUnsubscribe: z.function()\n .describe('Unsubscribe from record notifications'),\n});\n\n/**\n * TypeScript Types\n * Derived from Zod schemas using z.infer\n */\nexport type GetDiscoveryRequest = z.infer;\nexport type GetDiscoveryResponse = z.infer;\nexport type GetMetaTypesRequest = z.infer;\nexport type GetMetaTypesResponse = z.infer;\nexport type GetMetaItemsRequest = z.infer;\nexport type GetMetaItemsResponse = z.infer;\nexport type GetMetaItemRequest = z.infer;\nexport type GetMetaItemResponse = z.infer;\nexport type SaveMetaItemRequest = z.infer;\nexport type SaveMetaItemResponse = z.infer;\nexport type GetMetaItemCachedRequest = z.infer;\nexport type GetMetaItemCachedResponse = z.infer;\nexport type GetUiViewRequest = z.infer;\nexport type GetUiViewResponse = z.infer;\n\ntype AnalyticsQueryRequest = z.infer;\ntype AnalyticsResultResponse = z.infer;\ntype GetAnalyticsMetaRequest = z.infer;\ntype GetAnalyticsMetaResponse = z.infer;\n\nexport type AutomationTriggerRequest = z.infer;\nexport type AutomationTriggerResponse = z.infer;\n\nexport type FindDataRequest = z.input;\nexport type FindDataResponse = z.infer;\nexport type GetDataRequest = z.input;\nexport type GetDataResponse = z.infer;\nexport type CreateDataRequest = z.input;\nexport type CreateDataResponse = z.infer;\nexport type UpdateDataRequest = z.input;\nexport type UpdateDataResponse = z.infer;\nexport type DeleteDataRequest = z.input;\nexport type DeleteDataResponse = z.infer;\n\nexport type BatchDataRequest = z.input;\nexport type BatchDataResponse = z.infer;\nexport type CreateManyDataRequest = z.input;\nexport type CreateManyDataResponse = z.infer;\nexport type UpdateManyDataRequest = z.input;\nexport type UpdateManyDataResponse = z.infer;\nexport type DeleteManyDataRequest = z.input;\nexport type DeleteManyDataResponse = z.infer;\n\n// View Management Types\nexport type ListViewsRequest = z.input;\nexport type ListViewsResponse = z.infer;\nexport type GetViewRequest = z.input;\nexport type GetViewResponse = z.infer;\nexport type CreateViewRequest = z.input;\nexport type CreateViewResponse = z.infer;\nexport type UpdateViewRequest = z.input;\nexport type UpdateViewResponse = z.infer;\nexport type DeleteViewRequest = z.input;\nexport type DeleteViewResponse = z.infer;\n\n// Permission Types\nexport type CheckPermissionRequest = z.input;\nexport type CheckPermissionResponse = z.infer;\nexport type GetObjectPermissionsRequest = z.input;\nexport type GetObjectPermissionsResponse = z.infer;\nexport type GetEffectivePermissionsRequest = z.input;\nexport type GetEffectivePermissionsResponse = z.infer;\n\n// Workflow Types\nexport type GetWorkflowConfigRequest = z.input;\nexport type GetWorkflowConfigResponse = z.infer;\nexport type WorkflowState = z.infer;\nexport type GetWorkflowStateRequest = z.input;\nexport type GetWorkflowStateResponse = z.infer;\nexport type WorkflowTransitionRequest = z.input;\nexport type WorkflowTransitionResponse = z.infer;\nexport type WorkflowApproveRequest = z.input;\nexport type WorkflowApproveResponse = z.infer;\nexport type WorkflowRejectRequest = z.input;\nexport type WorkflowRejectResponse = z.infer;\n\n// Realtime Types\nexport type RealtimeConnectRequest = z.input;\nexport type RealtimeConnectResponse = z.infer;\nexport type RealtimeDisconnectRequest = z.input;\nexport type RealtimeDisconnectResponse = z.infer;\nexport type RealtimeSubscribeRequest = z.input;\nexport type RealtimeSubscribeResponse = z.infer;\nexport type RealtimeUnsubscribeRequest = z.input;\nexport type RealtimeUnsubscribeResponse = z.infer;\nexport type SetPresenceRequest = z.input;\nexport type SetPresenceResponse = z.infer;\nexport type GetPresenceRequest = z.input;\nexport type GetPresenceResponse = z.infer;\n\n// Notification Types\nexport type RegisterDeviceRequest = z.input;\nexport type RegisterDeviceResponse = z.infer;\nexport type UnregisterDeviceRequest = z.input;\nexport type UnregisterDeviceResponse = z.infer;\nexport type NotificationPreferences = z.infer;\nexport type NotificationPreferencesInput = z.input;\nexport type GetNotificationPreferencesRequest = z.input;\nexport type GetNotificationPreferencesResponse = z.infer;\nexport type UpdateNotificationPreferencesRequest = z.input;\nexport type UpdateNotificationPreferencesResponse = z.infer;\nexport type Notification = z.infer;\nexport type NotificationInput = z.input;\nexport type ListNotificationsRequest = z.input;\nexport type ListNotificationsResponse = z.infer;\nexport type MarkNotificationsReadRequest = z.input;\nexport type MarkNotificationsReadResponse = z.infer;\nexport type MarkAllNotificationsReadRequest = z.input;\nexport type MarkAllNotificationsReadResponse = z.infer;\n\n// AI Types\nexport type AiNlqRequest = z.input;\nexport type AiNlqResponse = z.infer;\nexport type AiSuggestRequest = z.input;\nexport type AiSuggestResponse = z.infer;\nexport type AiInsightsRequest = z.input;\nexport type AiInsightsResponse = z.infer;\n\n// i18n Types\nexport type GetLocalesRequest = z.input;\nexport type GetLocalesResponse = z.infer;\nexport type GetTranslationsRequest = z.input;\nexport type GetTranslationsResponse = z.infer;\nexport type GetFieldLabelsRequest = z.input;\nexport type GetFieldLabelsResponse = z.infer;\n\n// Feed Types (re-exported from feed-api.zod.ts for convenience)\nexport type {\n GetFeedRequest,\n GetFeedResponse,\n CreateFeedItemRequest,\n CreateFeedItemResponse,\n UpdateFeedItemRequest,\n UpdateFeedItemResponse,\n DeleteFeedItemRequest,\n DeleteFeedItemResponse,\n AddReactionRequest,\n AddReactionResponse,\n RemoveReactionRequest,\n RemoveReactionResponse,\n PinFeedItemRequest,\n PinFeedItemResponse,\n UnpinFeedItemRequest,\n UnpinFeedItemResponse,\n StarFeedItemRequest,\n StarFeedItemResponse,\n UnstarFeedItemRequest,\n UnstarFeedItemResponse,\n SearchFeedRequest,\n SearchFeedResponse,\n GetChangelogRequest,\n GetChangelogResponse,\n SubscribeRequest,\n SubscribeResponse,\n FeedUnsubscribeRequest,\n UnsubscribeResponse,\n} from './feed-api.zod';\n\n// Package Management Types (re-exported from kernel for convenience)\nexport type { \n ListPackagesRequest,\n ListPackagesResponse,\n GetPackageRequest,\n GetPackageResponse,\n InstallPackageRequest,\n InstallPackageResponse,\n UninstallPackageRequest,\n UninstallPackageResponse,\n EnablePackageRequest,\n EnablePackageResponse,\n DisablePackageRequest,\n DisablePackageResponse,\n InstalledPackage,\n PackageStatus,\n};\n\n/**\n * Zod-inferred protocol type (for runtime validation only).\n * Use ObjectStackProtocol interface for implementation contracts.\n */\nexport type ObjectStackProtocolZod = z.infer;\n\n/**\n * ObjectStack Protocol Interface\n * \n * Properly typed interface for implementing the ObjectStack API protocol.\n * The Zod schema (ObjectStackProtocolSchema) is used for runtime validation,\n * while this interface provides compile-time type safety for implementations.\n */\nexport interface ObjectStackProtocol {\n // Discovery & Metadata (core)\n getDiscovery(request?: GetDiscoveryRequest): Promise;\n getMetaTypes(request?: GetMetaTypesRequest): Promise;\n getMetaItems(request: GetMetaItemsRequest): Promise;\n getMetaItem(request: GetMetaItemRequest): Promise;\n saveMetaItem(request: SaveMetaItemRequest): Promise;\n getMetaItemCached?(request: GetMetaItemCachedRequest): Promise;\n getUiView?(request: GetUiViewRequest): Promise;\n \n // Analytics (optional)\n analyticsQuery?(request: AnalyticsQueryRequest): Promise;\n getAnalyticsMeta?(request: GetAnalyticsMetaRequest): Promise;\n\n // Automation (optional)\n triggerAutomation?(request: AutomationTriggerRequest): Promise;\n\n // Package Management (optional)\n listPackages?(request: ListPackagesRequest): Promise;\n getPackage?(request: GetPackageRequest): Promise;\n installPackage?(request: InstallPackageRequest): Promise;\n uninstallPackage?(request: UninstallPackageRequest): Promise;\n enablePackage?(request: EnablePackageRequest): Promise;\n disablePackage?(request: DisablePackageRequest): Promise;\n\n // Data Operations (core)\n findData(request: FindDataRequest): Promise;\n getData(request: GetDataRequest): Promise;\n createData(request: CreateDataRequest): Promise;\n updateData(request: UpdateDataRequest): Promise;\n deleteData(request: DeleteDataRequest): Promise;\n \n // Batch Operations (optional)\n batchData?(request: BatchDataRequest): Promise;\n createManyData?(request: CreateManyDataRequest): Promise;\n updateManyData?(request: UpdateManyDataRequest): Promise;\n deleteManyData?(request: DeleteManyDataRequest): Promise;\n\n // View Management (optional)\n listViews?(request: ListViewsRequest): Promise;\n getView?(request: GetViewRequest): Promise;\n createView?(request: CreateViewRequest): Promise;\n updateView?(request: UpdateViewRequest): Promise;\n deleteView?(request: DeleteViewRequest): Promise;\n\n // Permissions (optional)\n checkPermission?(request: CheckPermissionRequest): Promise;\n getObjectPermissions?(request: GetObjectPermissionsRequest): Promise;\n getEffectivePermissions?(request: GetEffectivePermissionsRequest): Promise;\n\n // Workflows (optional)\n getWorkflowConfig?(request: GetWorkflowConfigRequest): Promise;\n getWorkflowState?(request: GetWorkflowStateRequest): Promise;\n workflowTransition?(request: WorkflowTransitionRequest): Promise;\n workflowApprove?(request: WorkflowApproveRequest): Promise;\n workflowReject?(request: WorkflowRejectRequest): Promise;\n\n // Realtime (optional)\n realtimeConnect?(request: RealtimeConnectRequest): Promise;\n realtimeDisconnect?(request: RealtimeDisconnectRequest): Promise;\n realtimeSubscribe?(request: RealtimeSubscribeRequest): Promise;\n realtimeUnsubscribe?(request: RealtimeUnsubscribeRequest): Promise;\n setPresence?(request: SetPresenceRequest): Promise;\n getPresence?(request: GetPresenceRequest): Promise;\n\n // Notifications (optional)\n registerDevice?(request: RegisterDeviceRequest): Promise;\n unregisterDevice?(request: UnregisterDeviceRequest): Promise;\n getNotificationPreferences?(request: GetNotificationPreferencesRequest): Promise;\n updateNotificationPreferences?(request: UpdateNotificationPreferencesRequest): Promise;\n listNotifications?(request: ListNotificationsRequest): Promise;\n markNotificationsRead?(request: MarkNotificationsReadRequest): Promise;\n markAllNotificationsRead?(request: MarkAllNotificationsReadRequest): Promise;\n\n // AI (optional — chat is now handled by Vercel AI SDK wire protocol)\n aiNlq?(request: AiNlqRequest): Promise;\n aiSuggest?(request: AiSuggestRequest): Promise;\n aiInsights?(request: AiInsightsRequest): Promise;\n\n // i18n (optional)\n getLocales?(request: GetLocalesRequest): Promise;\n getTranslations?(request: GetTranslationsRequest): Promise;\n getFieldLabels?(request: GetFieldLabelsRequest): Promise;\n\n // Feed (optional)\n listFeed?(request: GetFeedRequest): Promise;\n createFeedItem?(request: CreateFeedItemRequest): Promise;\n updateFeedItem?(request: UpdateFeedItemRequest): Promise;\n deleteFeedItem?(request: DeleteFeedItemRequest): Promise;\n addReaction?(request: AddReactionRequest): Promise;\n removeReaction?(request: RemoveReactionRequest): Promise;\n pinFeedItem?(request: PinFeedItemRequest): Promise;\n unpinFeedItem?(request: UnpinFeedItemRequest): Promise;\n starFeedItem?(request: StarFeedItemRequest): Promise;\n unstarFeedItem?(request: UnstarFeedItemRequest): Promise;\n searchFeed?(request: SearchFeedRequest): Promise;\n getChangelog?(request: GetChangelogRequest): Promise;\n feedSubscribe?(request: SubscribeRequest): Promise;\n feedUnsubscribe?(request: FeedUnsubscribeRequest): Promise;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\n\n/**\n * REST API Server Protocol\n * \n * Defines the REST API server configuration for automatically generating\n * RESTful CRUD endpoints, metadata endpoints, and batch operations.\n * \n * Features:\n * - Automatic CRUD endpoint generation from Object definitions\n * - Standard REST conventions (GET, POST, PUT, PATCH, DELETE)\n * - Metadata API endpoints\n * - Batch operation endpoints\n * - OpenAPI/Swagger documentation generation\n * \n * Architecture alignment:\n * - Salesforce: REST API with Object CRUD\n * - Microsoft Dynamics: Web API with entity operations\n * - Strapi: Auto-generated REST endpoints\n */\n\n// ==========================================\n// REST API Configuration\n// ==========================================\n\n/**\n * REST API Configuration Schema\n * Core configuration for REST API server\n * \n * @example\n * {\n * \"version\": \"v1\",\n * \"basePath\": \"/api\",\n * \"enableCrud\": true,\n * \"enableMetadata\": true,\n * \"enableBatch\": true,\n * \"documentation\": {\n * \"enabled\": true,\n * \"title\": \"ObjectStack API\"\n * }\n * }\n */\nexport const RestApiConfigSchema = z.object({\n /**\n * API version identifier\n */\n version: z.string().regex(/^[a-zA-Z0-9_\\-\\.]+$/).default('v1').describe('API version (e.g., v1, v2, 2024-01)'),\n \n /**\n * Base path for all API routes\n */\n basePath: z.string().default('/api').describe('Base URL path for API'),\n \n /**\n * Full API path (combines basePath and version)\n */\n apiPath: z.string().optional().describe('Full API path (defaults to {basePath}/{version})'),\n \n /**\n * Enable automatic CRUD endpoints\n */\n enableCrud: z.boolean().default(true).describe('Enable automatic CRUD endpoint generation'),\n \n /**\n * Enable metadata endpoints\n */\n enableMetadata: z.boolean().default(true).describe('Enable metadata API endpoints'),\n \n /**\n * Enable UI API endpoints\n */\n enableUi: z.boolean().default(true).describe('Enable UI API endpoints (Views, Menus, Layouts)'),\n \n /**\n * Enable batch operation endpoints\n */\n enableBatch: z.boolean().default(true).describe('Enable batch operation endpoints'),\n \n /**\n * Enable discovery endpoint\n */\n enableDiscovery: z.boolean().default(true).describe('Enable API discovery endpoint'),\n\n /**\n * API documentation configuration\n */\n documentation: z.object({\n enabled: z.boolean().default(true).describe('Enable API documentation'),\n title: z.string().default('ObjectStack API').describe('API documentation title'),\n description: z.string().optional().describe('API description'),\n version: z.string().optional().describe('Documentation version'),\n termsOfService: z.string().optional().describe('Terms of service URL'),\n contact: z.object({\n name: z.string().optional(),\n url: z.string().optional(),\n email: z.string().optional(),\n }).optional(),\n license: z.object({\n name: z.string(),\n url: z.string().optional(),\n }).optional(),\n }).optional().describe('OpenAPI/Swagger documentation config'),\n \n /**\n * Response format configuration\n */\n responseFormat: z.object({\n envelope: z.boolean().default(true).describe('Wrap responses in standard envelope'),\n includeMetadata: z.boolean().default(true).describe('Include response metadata (timestamp, requestId)'),\n includePagination: z.boolean().default(true).describe('Include pagination info in list responses'),\n }).optional().describe('Response format options'),\n});\n\nexport type RestApiConfig = z.infer;\nexport type RestApiConfigInput = z.input;\n\n// ==========================================\n// CRUD Endpoint Configuration\n// ==========================================\n\n/**\n * CRUD Operation Type Enum\n */\nexport const CrudOperation = z.enum([\n 'create', // POST /api/v1/data/{object}\n 'read', // GET /api/v1/data/{object}/:id\n 'update', // PATCH /api/v1/data/{object}/:id\n 'delete', // DELETE /api/v1/data/{object}/:id\n 'list', // GET /api/v1/data/{object}\n]);\n\nexport type CrudOperation = z.infer;\n\n/**\n * CRUD Endpoint Pattern Schema\n * Defines the URL pattern for CRUD operations\n * \n * @example\n * {\n * \"create\": { \"method\": \"POST\", \"path\": \"/data/{object}\" },\n * \"read\": { \"method\": \"GET\", \"path\": \"/data/{object}/:id\" },\n * \"update\": { \"method\": \"PATCH\", \"path\": \"/data/{object}/:id\" },\n * \"delete\": { \"method\": \"DELETE\", \"path\": \"/data/{object}/:id\" },\n * \"list\": { \"method\": \"GET\", \"path\": \"/data/{object}\" }\n * }\n */\nexport const CrudEndpointPatternSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (relative to API base)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Operation summary for documentation\n */\n summary: z.string().optional().describe('Operation summary'),\n \n /**\n * Operation description\n */\n description: z.string().optional().describe('Operation description'),\n});\n\nexport type CrudEndpointPattern = z.infer;\n\n/**\n * CRUD Endpoints Configuration Schema\n * Configuration for automatic CRUD endpoint generation\n */\nexport const CrudEndpointsConfigSchema = z.object({\n /**\n * Enable/disable specific CRUD operations\n */\n operations: z.object({\n create: z.boolean().default(true).describe('Enable create operation'),\n read: z.boolean().default(true).describe('Enable read operation'),\n update: z.boolean().default(true).describe('Enable update operation'),\n delete: z.boolean().default(true).describe('Enable delete operation'),\n list: z.boolean().default(true).describe('Enable list operation'),\n }).optional().describe('Enable/disable operations'),\n \n /**\n * Custom endpoint patterns (override defaults)\n */\n patterns: z.record(CrudOperation, CrudEndpointPatternSchema.optional()).optional()\n .describe('Custom URL patterns for operations'),\n \n /**\n * Path prefix for data operations\n */\n dataPrefix: z.string().default('/data').describe('URL prefix for data endpoints'),\n \n /**\n * Object name parameter style\n */\n objectParamStyle: z.enum(['path', 'query']).default('path')\n .describe('How object name is passed (path param or query param)'),\n});\n\nexport type CrudEndpointsConfig = z.infer;\nexport type CrudEndpointsConfigInput = z.input;\n\n// ==========================================\n// Metadata Endpoint Configuration\n// ==========================================\n\n/**\n * Metadata Endpoint Configuration Schema\n * Configuration for metadata API endpoints\n * \n * @example\n * {\n * \"prefix\": \"/meta\",\n * \"enableCache\": true,\n * \"endpoints\": {\n * \"types\": true,\n * \"objects\": true,\n * \"fields\": true\n * }\n * }\n */\nexport const MetadataEndpointsConfigSchema = z.object({\n /**\n * Path prefix for metadata operations\n */\n prefix: z.string().default('/meta').describe('URL prefix for metadata endpoints'),\n \n /**\n * Enable HTTP caching for metadata\n */\n enableCache: z.boolean().default(true).describe('Enable HTTP cache headers (ETag, Last-Modified)'),\n \n /**\n * Cache TTL in seconds\n */\n cacheTtl: z.number().int().default(3600).describe('Cache TTL in seconds'),\n \n /**\n * Enable specific metadata endpoints\n */\n endpoints: z.object({\n types: z.boolean().default(true).describe('GET /meta - List all metadata types'),\n items: z.boolean().default(true).describe('GET /meta/:type - List items of type'),\n item: z.boolean().default(true).describe('GET /meta/:type/:name - Get specific item'),\n schema: z.boolean().default(true).describe('GET /meta/:type/:name/schema - Get JSON schema'),\n }).optional().describe('Enable/disable specific endpoints'),\n});\n\nexport type MetadataEndpointsConfig = z.infer;\nexport type MetadataEndpointsConfigInput = z.input;\n\n// ==========================================\n// Batch Operation Endpoint Configuration\n// ==========================================\n\n/**\n * Batch Operation Endpoint Configuration Schema\n * Configuration for batch/bulk operation endpoints\n * \n * @example\n * {\n * \"maxBatchSize\": 200,\n * \"enableBatchEndpoint\": true,\n * \"enableCreateMany\": true,\n * \"enableUpdateMany\": true,\n * \"enableDeleteMany\": true\n * }\n */\nexport const BatchEndpointsConfigSchema = z.object({\n /**\n * Maximum batch size\n */\n maxBatchSize: z.number().int().min(1).max(1000).default(200)\n .describe('Maximum records per batch operation'),\n \n /**\n * Enable generic batch endpoint\n */\n enableBatchEndpoint: z.boolean().default(true)\n .describe('Enable POST /data/:object/batch endpoint'),\n \n /**\n * Enable specific batch operations\n */\n operations: z.object({\n createMany: z.boolean().default(true).describe('Enable POST /data/:object/createMany'),\n updateMany: z.boolean().default(true).describe('Enable POST /data/:object/updateMany'),\n deleteMany: z.boolean().default(true).describe('Enable POST /data/:object/deleteMany'),\n upsertMany: z.boolean().default(true).describe('Enable POST /data/:object/upsertMany'),\n }).optional().describe('Enable/disable specific batch operations'),\n \n /**\n * Transaction mode default\n */\n defaultAtomic: z.boolean().default(true)\n .describe('Default atomic/transaction mode for batch operations'),\n});\n\nexport type BatchEndpointsConfig = z.infer;\nexport type BatchEndpointsConfigInput = z.input;\n\n// ==========================================\n// Route Generation Configuration\n// ==========================================\n\n/**\n * Route Generation Configuration Schema\n * Controls automatic route generation for objects\n */\nexport const RouteGenerationConfigSchema = z.object({\n /**\n * Objects to include (if empty, include all)\n */\n includeObjects: z.array(z.string()).optional()\n .describe('Specific objects to generate routes for (empty = all)'),\n \n /**\n * Objects to exclude\n */\n excludeObjects: z.array(z.string()).optional()\n .describe('Objects to exclude from route generation'),\n \n /**\n * Object name transformations\n */\n nameTransform: z.enum(['none', 'plural', 'kebab-case', 'camelCase']).default('none')\n .describe('Transform object names in URLs'),\n \n /**\n * Custom route overrides per object\n */\n overrides: z.record(z.string(), z.object({\n enabled: z.boolean().optional().describe('Enable/disable routes for this object'),\n basePath: z.string().optional().describe('Custom base path'),\n operations: z.record(CrudOperation, z.boolean()).optional()\n .describe('Enable/disable specific operations'),\n })).optional().describe('Per-object route customization'),\n});\n\nexport type RouteGenerationConfig = z.infer;\nexport type RouteGenerationConfigInput = z.input;\n\n// ==========================================\n// OpenAPI 3.1 Webhooks & Callbacks\n// ==========================================\n\n/**\n * Webhook Event Schema\n * Defines an event that can trigger a webhook delivery\n */\nexport const WebhookEventSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Webhook event identifier (snake_case)'),\n description: z.string().describe('Human-readable event description'),\n method: HttpMethod.default('POST').describe('HTTP method for webhook delivery'),\n payloadSchema: z.string().describe('JSON Schema $ref for the webhook payload'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers to include in webhook delivery'),\n security: z.array(\n z.enum(['hmac_sha256', 'basic', 'bearer', 'api_key'])\n ).describe('Supported authentication methods for webhook verification'),\n});\n\nexport type WebhookEvent = z.infer;\n\n/**\n * Webhook Configuration Schema\n * Top-level webhook configuration for the REST API\n */\nexport const WebhookConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable webhook support'),\n events: z.array(WebhookEventSchema).describe('Registered webhook events'),\n deliveryConfig: z.object({\n maxRetries: z.number().int().default(3).describe('Maximum delivery retry attempts'),\n retryIntervalMs: z.number().int().default(5000).describe('Milliseconds between retry attempts'),\n timeoutMs: z.number().int().default(30000).describe('Delivery request timeout in milliseconds'),\n signatureHeader: z.string().default('X-Signature-256').describe('Header name for webhook signature'),\n }).describe('Webhook delivery configuration'),\n registrationEndpoint: z.string().default('/webhooks').describe('URL path for webhook registration'),\n});\n\nexport type WebhookConfig = z.infer;\n\n/**\n * Callback Schema\n * OpenAPI 3.1 callback definition for asynchronous API responses\n */\nexport const CallbackSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Callback identifier (snake_case)'),\n expression: z.string().describe('Runtime expression (e.g., {$request.body#/callbackUrl})'),\n method: HttpMethod.describe('HTTP method for callback request'),\n url: z.string().describe('Callback URL template with runtime expressions'),\n});\n\nexport type Callback = z.infer;\n\n/**\n * OpenAPI 3.1 Extensions Schema\n * Extensions specific to OpenAPI 3.1 specification\n */\nexport const OpenApi31ExtensionsSchema = z.object({\n webhooks: z.record(z.string(), WebhookEventSchema).optional()\n .describe('OpenAPI 3.1 webhooks (top-level webhook definitions)'),\n callbacks: z.record(z.string(), z.array(CallbackSchema)).optional()\n .describe('OpenAPI 3.1 callbacks (async response definitions)'),\n jsonSchemaDialect: z.string().default('https://json-schema.org/draft/2020-12/schema')\n .describe('JSON Schema dialect for schema definitions'),\n pathItemReferences: z.boolean().default(false)\n .describe('Allow $ref in path items (OpenAPI 3.1 feature)'),\n});\n\nexport type OpenApi31Extensions = z.infer;\n\n// ==========================================\n// Complete REST Server Configuration\n// ==========================================\n\n/**\n * REST Server Configuration Schema\n * Complete configuration for REST API server with auto-generated endpoints\n * \n * @example\n * {\n * \"api\": {\n * \"version\": \"v1\",\n * \"basePath\": \"/api\",\n * \"enableCrud\": true,\n * \"enableMetadata\": true,\n * \"enableBatch\": true\n * },\n * \"crud\": {\n * \"dataPrefix\": \"/data\"\n * },\n * \"metadata\": {\n * \"prefix\": \"/meta\",\n * \"enableCache\": true\n * },\n * \"batch\": {\n * \"maxBatchSize\": 200\n * },\n * \"routes\": {\n * \"excludeObjects\": [\"system_log\"]\n * }\n * }\n */\nexport const RestServerConfigSchema = z.object({\n /**\n * API configuration\n */\n api: RestApiConfigSchema.optional().describe('REST API configuration'),\n \n /**\n * CRUD endpoints configuration\n */\n crud: CrudEndpointsConfigSchema.optional().describe('CRUD endpoints configuration'),\n \n /**\n * Metadata endpoints configuration\n */\n metadata: MetadataEndpointsConfigSchema.optional().describe('Metadata endpoints configuration'),\n \n /**\n * Batch endpoints configuration\n */\n batch: BatchEndpointsConfigSchema.optional().describe('Batch endpoints configuration'),\n \n /**\n * Route generation configuration\n */\n routes: RouteGenerationConfigSchema.optional().describe('Route generation configuration'),\n \n /**\n * OpenAPI 3.1 extensions (webhooks, callbacks)\n */\n openApi31: OpenApi31ExtensionsSchema.optional().describe('OpenAPI 3.1 extensions configuration'),\n});\n\nexport type RestServerConfig = z.infer;\nexport type RestServerConfigInput = z.input;\n\n// ==========================================\n// Endpoint Registry\n// ==========================================\n\n/**\n * Generated Endpoint Schema\n * Represents a generated REST endpoint\n */\nexport const GeneratedEndpointSchema = z.object({\n /**\n * Endpoint identifier\n */\n id: z.string().describe('Unique endpoint identifier'),\n \n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * Full URL path\n */\n path: z.string().describe('Full URL path'),\n \n /**\n * Object this endpoint operates on\n */\n object: z.string().describe('Object name (snake_case)'),\n \n /**\n * Operation type\n */\n operation: z.union([CrudOperation, z.string()]).describe('Operation type'),\n \n /**\n * Handler reference\n */\n handler: z.string().describe('Handler function identifier'),\n \n /**\n * Endpoint metadata\n */\n metadata: z.object({\n summary: z.string().optional(),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n deprecated: z.boolean().optional(),\n }).optional(),\n});\n\nexport type GeneratedEndpoint = z.infer;\n\n/**\n * Endpoint Registry Schema\n * Registry of all generated endpoints\n */\nexport const EndpointRegistrySchema = z.object({\n /**\n * Generated endpoints\n */\n endpoints: z.array(GeneratedEndpointSchema).describe('All generated endpoints'),\n \n /**\n * Total endpoint count\n */\n total: z.number().int().describe('Total number of endpoints'),\n \n /**\n * Endpoints by object\n */\n byObject: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()\n .describe('Endpoints grouped by object'),\n \n /**\n * Endpoints by operation\n */\n byOperation: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()\n .describe('Endpoints grouped by operation'),\n});\n\nexport type EndpointRegistry = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create REST API configuration\n */\nexport const RestApiConfig = Object.assign(RestApiConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create REST server configuration\n */\nexport const RestServerConfig = Object.assign(RestServerConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, RateLimitConfigSchema } from '../shared/http.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Unified API Registry Protocol\n * \n * Provides a centralized registry for managing all API endpoints across different\n * API types (REST, GraphQL, OData, WebSocket, Auth, File, Plugin-registered).\n * \n * This enables:\n * - Unified API discovery and documentation (similar to Swagger/OpenAPI)\n * - API testing interfaces\n * - API governance and monitoring\n * - Plugin API registration\n * - Multi-protocol support\n * \n * Architecture Alignment:\n * - Kubernetes: Service Discovery & API Server\n * - AWS API Gateway: Unified API Management\n * - Kong Gateway: Plugin-based API Management\n * \n * @example API Registry Entry\n * ```typescript\n * const apiEntry: ApiRegistryEntry = {\n * id: 'customer_crud',\n * name: 'Customer CRUD API',\n * type: 'rest',\n * version: 'v1',\n * basePath: '/api/v1/data/customer',\n * endpoints: [...],\n * metadata: {\n * owner: 'sales_team',\n * tags: ['customer', 'crm']\n * }\n * }\n * ```\n */\n\n// ==========================================\n// API Type Enumeration\n// ==========================================\n\n/**\n * API Protocol Type\n * \n * Defines the different types of APIs supported by ObjectStack.\n */\nexport const ApiProtocolType = z.enum([\n 'rest', // RESTful API (CRUD operations)\n 'graphql', // GraphQL API (flexible queries)\n 'odata', // OData v4 API (enterprise integration)\n 'websocket', // WebSocket API (real-time)\n 'file', // File/Storage API (uploads/downloads)\n 'auth', // Authentication/Authorization API\n 'metadata', // Metadata/Schema API\n 'plugin', // Plugin-registered custom API\n 'webhook', // Webhook endpoints\n 'rpc', // JSON-RPC or similar\n]);\n\nexport type ApiProtocolType = z.infer;\n\n// ==========================================\n// API Endpoint Registration\n// ==========================================\n\n/**\n * HTTP Status Code\n */\nexport const HttpStatusCode = z.union([\n z.number().int().min(100).max(599),\n z.enum(['2xx', '3xx', '4xx', '5xx']), // Pattern matching\n]);\n\nexport type HttpStatusCode = z.infer;\n\n// ==========================================\n// Schema Reference Types\n// ==========================================\n\n/**\n * ObjectQL Reference Schema\n * \n * Allows referencing ObjectStack data objects instead of static JSON schemas.\n * When an API parameter or response references an ObjectQL object, the schema\n * is dynamically derived from the object definition, enabling automatic updates\n * when the object schema changes.\n * \n * **IMPORTANT - Schema Resolution Responsibility:**\n * The API Registry STORES these references as metadata but does NOT resolve them.\n * Schema resolution (expanding references into actual JSON Schema) is performed by:\n * - **API Gateway**: For runtime request/response validation\n * - **OpenAPI Generator**: For Swagger/OpenAPI documentation\n * - **GraphQL Schema Builder**: For GraphQL type generation\n * - **Documentation Tools**: For developer documentation\n * \n * This separation allows the Registry to remain lightweight and focused on\n * registration/discovery, while specialized tools handle schema transformation.\n * \n * **Benefits:**\n * - Auto-updating API documentation when object schemas change\n * - Consistent type definitions across API and database\n * - Reduced duplication and maintenance\n * - Registry remains protocol-agnostic and lightweight\n * \n * @example Reference Customer object\n * ```json\n * {\n * \"objectId\": \"customer\",\n * \"includeFields\": [\"id\", \"name\", \"email\"],\n * \"excludeFields\": [\"internal_notes\"]\n * }\n * ```\n */\nexport const ObjectQLReferenceSchema = z.object({\n /** Referenced object name (snake_case) */\n objectId: SnakeCaseIdentifierSchema.describe('Object name to reference'),\n \n /** Include only specific fields (optional) */\n includeFields: z.array(z.string()).optional()\n .describe('Include only these fields in the schema'),\n \n /** Exclude specific fields (optional) */\n excludeFields: z.array(z.string()).optional()\n .describe('Exclude these fields from the schema'),\n \n /** Include related objects via lookup fields */\n includeRelated: z.array(z.string()).optional()\n .describe('Include related objects via lookup fields'),\n});\n\nexport type ObjectQLReference = z.infer;\n\n/**\n * Schema Definition\n * \n * Unified schema definition that supports both:\n * 1. Static JSON Schema (traditional approach)\n * 2. Dynamic ObjectQL reference (linked to object definitions)\n * \n * When using ObjectQL references, the API documentation and validation\n * automatically update when object schemas change, eliminating the need\n * to manually sync API schemas with data models.\n */\nexport const SchemaDefinition = z.union([\n z.unknown().describe('Static JSON Schema definition'),\n z.object({\n $ref: ObjectQLReferenceSchema.describe('Dynamic reference to ObjectQL object'),\n }).describe('Dynamic ObjectQL reference'),\n]);\n\nexport type SchemaDefinition = z.infer;\n\n// ==========================================\n// API Parameter & Response Schemas\n// ==========================================\n\n/**\n * API Parameter Schema\n * \n * Defines a single API parameter (path, query, header, or body).\n * \n * **Enhancement: Dynamic Schema Linking**\n * - Supports both static JSON Schema and dynamic ObjectQL references\n * - When using ObjectQL references, parameter validation automatically updates\n * when the referenced object schema changes\n * \n * @example Static schema\n * ```json\n * {\n * \"name\": \"customer_id\",\n * \"in\": \"path\",\n * \"schema\": {\n * \"type\": \"string\",\n * \"format\": \"uuid\"\n * }\n * }\n * ```\n * \n * @example Dynamic ObjectQL reference\n * ```json\n * {\n * \"name\": \"customer\",\n * \"in\": \"body\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\",\n * \"excludeFields\": [\"internal_notes\"]\n * }\n * }\n * }\n * ```\n */\nexport const ApiParameterSchema = z.object({\n /** Parameter name */\n name: z.string().describe('Parameter name'),\n \n /** Parameter location */\n in: z.enum(['path', 'query', 'header', 'body', 'cookie']).describe('Parameter location'),\n \n /** Parameter description */\n description: z.string().optional().describe('Parameter description'),\n \n /** Required flag */\n required: z.boolean().default(false).describe('Whether parameter is required'),\n \n /** Parameter type/schema - supports static or dynamic (ObjectQL) schemas */\n schema: z.union([\n z.object({\n type: z.enum(['string', 'number', 'integer', 'boolean', 'array', 'object']).describe('Parameter type'),\n format: z.string().optional().describe('Format (e.g., date-time, email, uuid)'),\n enum: z.array(z.unknown()).optional().describe('Allowed values'),\n default: z.unknown().optional().describe('Default value'),\n items: z.unknown().optional().describe('Array item schema'),\n properties: z.record(z.string(), z.unknown()).optional().describe('Object properties'),\n }).describe('Static JSON Schema'),\n z.object({\n $ref: ObjectQLReferenceSchema,\n }).describe('Dynamic ObjectQL reference'),\n ]).describe('Parameter schema definition'),\n \n /** Example value */\n example: z.unknown().optional().describe('Example value'),\n});\n\nexport type ApiParameter = z.infer;\n\n/**\n * API Response Schema\n * \n * Defines an API response for a specific status code.\n * \n * **Enhancement: Dynamic Schema Linking**\n * - Response schema can reference ObjectQL objects\n * - When object definitions change, response documentation auto-updates\n * \n * @example Response with ObjectQL reference\n * ```json\n * {\n * \"statusCode\": 200,\n * \"description\": \"Customer retrieved successfully\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\",\n * \"excludeFields\": [\"password_hash\"]\n * }\n * }\n * }\n * ```\n */\nexport const ApiResponseSchema = z.object({\n /** HTTP status code */\n statusCode: HttpStatusCode.describe('HTTP status code'),\n \n /** Response description */\n description: z.string().describe('Response description'),\n \n /** Response content type */\n contentType: z.string().default('application/json').describe('Response content type'),\n \n /** Response schema - supports static or dynamic (ObjectQL) schemas */\n schema: z.union([\n z.unknown().describe('Static JSON Schema'),\n z.object({\n $ref: ObjectQLReferenceSchema,\n }).describe('Dynamic ObjectQL reference'),\n ]).optional().describe('Response body schema'),\n \n /** Response headers */\n headers: z.record(z.string(), z.object({\n description: z.string().optional(),\n schema: z.unknown(),\n })).optional().describe('Response headers'),\n \n /** Example response */\n example: z.unknown().optional().describe('Example response'),\n});\n\nexport type ApiResponse = z.infer;\nexport type ApiResponseInput = z.input;\n\n/**\n * API Endpoint Registration Schema\n * \n * Represents a single API endpoint registration with complete metadata.\n * \n * **Enhancements:**\n * 1. **RBAC Integration**: `requiredPermissions` field for automatic permission checking\n * 2. **Dynamic Schema Linking**: Parameters and responses can reference ObjectQL objects\n * 3. **Route Priority**: `priority` field for conflict resolution\n * 4. **Protocol Config**: `protocolConfig` for protocol-specific extensions\n * \n * @example REST Endpoint with RBAC\n * ```json\n * {\n * \"id\": \"get_customer_by_id\",\n * \"method\": \"GET\",\n * \"path\": \"/api/v1/data/customer/:id\",\n * \"summary\": \"Get customer by ID\",\n * \"requiredPermissions\": [\"customer.read\"],\n * \"parameters\": [\n * {\n * \"name\": \"id\",\n * \"in\": \"path\",\n * \"required\": true,\n * \"schema\": { \"type\": \"string\" }\n * }\n * ],\n * \"responses\": [\n * {\n * \"statusCode\": 200,\n * \"description\": \"Customer found\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\"\n * }\n * }\n * }\n * ],\n * \"priority\": 100\n * }\n * ```\n * \n * @example Plugin Endpoint with Protocol Config\n * ```json\n * {\n * \"id\": \"grpc_service_method\",\n * \"path\": \"/grpc/ServiceName/MethodName\",\n * \"summary\": \"gRPC service method\",\n * \"protocolConfig\": {\n * \"subProtocol\": \"grpc\",\n * \"serviceName\": \"CustomerService\",\n * \"methodName\": \"GetCustomer\"\n * },\n * \"priority\": 50\n * }\n * ```\n */\nexport const ApiEndpointRegistrationSchema = z.object({\n /** Unique endpoint identifier */\n id: z.string().describe('Unique endpoint identifier'),\n \n /** HTTP method (for HTTP-based APIs) */\n method: HttpMethod.optional().describe('HTTP method'),\n \n /** URL path pattern */\n path: z.string().describe('URL path pattern'),\n \n /** Short summary */\n summary: z.string().optional().describe('Short endpoint summary'),\n \n /** Detailed description */\n description: z.string().optional().describe('Detailed endpoint description'),\n \n /** Operation ID (OpenAPI) */\n operationId: z.string().optional().describe('Unique operation identifier'),\n \n /** Tags for grouping */\n tags: z.array(z.string()).optional().default([]).describe('Tags for categorization'),\n \n /** Parameters */\n parameters: z.array(ApiParameterSchema).optional().default([]).describe('Endpoint parameters'),\n \n /** Request body schema */\n requestBody: z.object({\n description: z.string().optional(),\n required: z.boolean().default(false),\n contentType: z.string().default('application/json'),\n schema: z.unknown().optional(),\n example: z.unknown().optional(),\n }).optional().describe('Request body specification'),\n \n /** Response definitions */\n responses: z.array(ApiResponseSchema).optional().default([]).describe('Possible responses'),\n \n /** Rate Limiting */\n rateLimit: RateLimitConfigSchema.optional().describe('Endpoint specific rate limiting'),\n\n /** Security Requirements */\n security: z.array(z.record(z.string(), z.array(z.string()))).optional().describe('Security requirements (e.g. [{\"bearerAuth\": []}])'),\n \n /**\n * Required Permissions (RBAC Integration)\n * \n * Array of permission names required to access this endpoint.\n * The gateway layer automatically validates these permissions before\n * allowing the request to proceed, eliminating the need for permission\n * checks in individual API handlers.\n * \n * **Format:** `.` or system permission name\n * \n * **Object Permissions:**\n * - `customer.read` - Read customer records\n * - `customer.create` - Create customer records\n * - `customer.edit` - Update customer records\n * - `customer.delete` - Delete customer records\n * - `customer.viewAll` - View all customer records (bypass sharing)\n * - `customer.modifyAll` - Modify all customer records (bypass sharing)\n * \n * **System Permissions:**\n * - `manage_users` - User management\n * - `view_setup` - Access to system setup\n * - `customize_application` - Modify metadata\n * - `api_enabled` - API access\n * \n * @example Object-level permissions\n * ```json\n * {\n * \"requiredPermissions\": [\"customer.read\"]\n * }\n * ```\n * \n * @example Multiple permissions (ALL required)\n * ```json\n * {\n * \"requiredPermissions\": [\"customer.read\", \"account.read\"]\n * }\n * ```\n * \n * @example System permission\n * ```json\n * {\n * \"requiredPermissions\": [\"manage_users\"]\n * }\n * ```\n * \n * @see {@link file://../../permission/permission.zod.ts} for permission definitions\n */\n requiredPermissions: z.array(z.string()).optional().default([])\n .describe('Required RBAC permissions (e.g., \"customer.read\", \"manage_users\")'),\n \n /**\n * Route Priority\n * \n * Priority level for route conflict resolution. Higher priority routes\n * are registered first and take precedence when multiple routes match\n * the same path pattern.\n * \n * **Default:** 100 (medium priority)\n * **Range:** 0-1000 (higher = more important)\n * \n * **Use Cases:**\n * - Core system APIs: 900-1000\n * - Plugin APIs: 100-500\n * - Custom/override APIs: 500-900\n * - Fallback routes: 0-100\n * \n * @example High priority core endpoint\n * ```json\n * {\n * \"path\": \"/api/v1/data/:object/:id\",\n * \"priority\": 950\n * }\n * ```\n * \n * @example Medium priority plugin endpoint\n * ```json\n * {\n * \"path\": \"/api/v1/custom/action\",\n * \"priority\": 300\n * }\n * ```\n */\n priority: z.number().int().min(0).max(1000).optional().default(100)\n .describe('Route priority for conflict resolution (0-1000, higher = more important)'),\n \n /**\n * Protocol-Specific Configuration\n * \n * Allows plugins and custom APIs to define protocol-specific metadata\n * that can be used for specialized handling or documentation generation.\n * \n * **Examples:**\n * - gRPC: Service and method names\n * - tRPC: Procedure type (query/mutation)\n * - WebSocket: Event names and handlers\n * - Custom protocols: Any metadata needed\n * \n * @example gRPC configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"grpc\",\n * \"serviceName\": \"CustomerService\",\n * \"methodName\": \"GetCustomer\",\n * \"streaming\": false\n * }\n * }\n * ```\n * \n * @example tRPC configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"trpc\",\n * \"procedureType\": \"query\",\n * \"router\": \"customer\"\n * }\n * }\n * ```\n * \n * @example WebSocket configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"websocket\",\n * \"eventName\": \"customer.updated\",\n * \"direction\": \"server-to-client\"\n * }\n * }\n * ```\n */\n protocolConfig: z.record(z.string(), z.unknown()).optional()\n .describe('Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)'),\n \n /** Deprecation flag */\n deprecated: z.boolean().default(false).describe('Whether endpoint is deprecated'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation link'),\n});\n\nexport type ApiEndpointRegistration = z.infer;\nexport type ApiEndpointRegistrationInput = z.input;\n\n// ==========================================\n// API Registry Entry\n// ==========================================\n\n/**\n * API Metadata Schema\n * \n * Additional metadata for an API registration.\n */\nexport const ApiMetadataSchema = z.object({\n /** API owner/team */\n owner: z.string().optional().describe('Owner team or person'),\n \n /** API status */\n status: z.enum(['active', 'deprecated', 'experimental', 'beta']).default('active')\n .describe('API lifecycle status'),\n \n /** Categorization tags */\n tags: z.array(z.string()).optional().default([]).describe('Classification tags'),\n \n /** Plugin source (if plugin-registered) */\n pluginSource: z.string().optional().describe('Source plugin name'),\n \n /** Custom metadata */\n custom: z.record(z.string(), z.unknown()).optional().describe('Custom metadata fields'),\n});\n\nexport type ApiMetadata = z.infer;\nexport type ApiMetadataInput = z.input;\n\n/**\n * API Registry Entry Schema\n * \n * Complete registration entry for an API in the unified registry.\n * \n * @example REST API Entry\n * ```json\n * {\n * \"id\": \"customer_api\",\n * \"name\": \"Customer Management API\",\n * \"type\": \"rest\",\n * \"version\": \"v1\",\n * \"basePath\": \"/api/v1/data/customer\",\n * \"description\": \"CRUD operations for customer records\",\n * \"endpoints\": [...],\n * \"metadata\": {\n * \"owner\": \"sales_team\",\n * \"status\": \"active\",\n * \"tags\": [\"customer\", \"crm\"]\n * }\n * }\n * ```\n * \n * @example Plugin API Entry\n * ```json\n * {\n * \"id\": \"payment_webhook\",\n * \"name\": \"Payment Webhook API\",\n * \"type\": \"plugin\",\n * \"version\": \"1.0.0\",\n * \"basePath\": \"/plugins/payment/webhook\",\n * \"endpoints\": [...],\n * \"metadata\": {\n * \"pluginSource\": \"payment_gateway_plugin\",\n * \"status\": \"active\"\n * }\n * }\n * ```\n */\nexport const ApiRegistryEntrySchema = z.object({\n /** Unique API identifier */\n id: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique API identifier (snake_case)'),\n \n /** Human-readable name */\n name: z.string().describe('API display name'),\n \n /** API protocol type */\n type: ApiProtocolType.describe('API protocol type'),\n \n /** API version */\n version: z.string().describe('API version (e.g., v1, 2024-01)'),\n \n /** Base URL path */\n basePath: z.string().describe('Base URL path for this API'),\n \n /** API description */\n description: z.string().optional().describe('API description'),\n \n /** Endpoints in this API */\n endpoints: z.array(ApiEndpointRegistrationSchema).describe('Registered endpoints'),\n \n /** OpenAPI/GraphQL/OData specific configuration */\n config: z.record(z.string(), z.unknown()).optional().describe('Protocol-specific configuration'),\n \n /** API metadata */\n metadata: ApiMetadataSchema.optional().describe('Additional metadata'),\n \n /** Terms of service URL */\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n \n /** Contact information */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('Contact information'),\n \n /** License information */\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional().describe('License information'),\n});\n\nexport type ApiRegistryEntry = z.infer;\nexport type ApiRegistryEntryInput = z.input;\n\n// ==========================================\n// API Registry\n// ==========================================\n\n/**\n * Route Conflict Resolution Strategy\n * \n * Defines how to handle conflicts when multiple endpoints register\n * the same or overlapping URL patterns.\n */\nexport const ConflictResolutionStrategy = z.enum([\n 'error', // Throw error on conflict (safest, default)\n 'priority', // Use priority field to resolve (highest priority wins)\n 'first-wins', // First registered endpoint wins\n 'last-wins', // Last registered endpoint wins (override mode)\n]);\n\nexport type ConflictResolutionStrategy = z.infer;\n\n/**\n * API Registry Schema\n * \n * Central registry containing all registered APIs.\n * \n * **Enhancement: Route Conflict Detection**\n * - `conflictResolution`: Strategy for handling route conflicts\n * - Prevents silent overwrites and unexpected routing behavior\n * \n * @example\n * ```json\n * {\n * \"version\": \"1.0.0\",\n * \"conflictResolution\": \"priority\",\n * \"apis\": [\n * { \"id\": \"customer_api\", \"type\": \"rest\", ... },\n * { \"id\": \"graphql_api\", \"type\": \"graphql\", ... },\n * { \"id\": \"file_upload_api\", \"type\": \"file\", ... }\n * ],\n * \"totalApis\": 3,\n * \"totalEndpoints\": 47\n * }\n * ```\n * \n * @example Priority-based conflict resolution\n * ```json\n * {\n * \"conflictResolution\": \"priority\",\n * \"apis\": [\n * {\n * \"id\": \"core_api\",\n * \"endpoints\": [\n * {\n * \"path\": \"/api/v1/data/:object\",\n * \"priority\": 950\n * }\n * ]\n * },\n * {\n * \"id\": \"plugin_api\",\n * \"endpoints\": [\n * {\n * \"path\": \"/api/v1/data/custom\",\n * \"priority\": 300\n * }\n * ]\n * }\n * ]\n * }\n * ```\n */\nexport const ApiRegistrySchema = z.object({\n /** Registry version */\n version: z.string().describe('Registry version'),\n \n /**\n * Conflict Resolution Strategy\n * \n * Defines how to handle route conflicts when multiple endpoints\n * register the same or overlapping URL patterns.\n * \n * **Strategies:**\n * - `error`: Throw error on conflict (safest, prevents silent overwrites)\n * - `priority`: Use endpoint priority field (highest priority wins)\n * - `first-wins`: First registered endpoint wins (stable, predictable)\n * - `last-wins`: Last registered endpoint wins (allows overrides)\n * \n * **Default:** `error`\n * \n * **Best Practices:**\n * - Use `error` in production to catch configuration issues\n * - Use `priority` when mixing core and plugin APIs\n * - Use `last-wins` for development/testing overrides\n * \n * @example Prevent accidental conflicts\n * ```json\n * {\n * \"conflictResolution\": \"error\"\n * }\n * ```\n * \n * @example Allow plugin overrides with priority\n * ```json\n * {\n * \"conflictResolution\": \"priority\"\n * }\n * ```\n */\n conflictResolution: ConflictResolutionStrategy.optional().default('error')\n .describe('Strategy for handling route conflicts'),\n \n /** Registered APIs */\n apis: z.array(ApiRegistryEntrySchema).describe('All registered APIs'),\n \n /** Total API count */\n totalApis: z.number().int().describe('Total number of registered APIs'),\n \n /** Total endpoint count across all APIs */\n totalEndpoints: z.number().int().describe('Total number of endpoints'),\n \n /** APIs grouped by type */\n byType: z.record(ApiProtocolType, z.array(ApiRegistryEntrySchema)).optional()\n .describe('APIs grouped by protocol type'),\n \n /** APIs grouped by status */\n byStatus: z.record(z.string(), z.array(ApiRegistryEntrySchema)).optional()\n .describe('APIs grouped by status'),\n \n /** Last updated timestamp */\n updatedAt: z.string().datetime().optional().describe('Last registry update time'),\n});\n\nexport type ApiRegistry = z.infer;\n\n// ==========================================\n// API Discovery & Query\n// ==========================================\n\n/**\n * API Discovery Query Schema\n * \n * Query parameters for discovering/filtering APIs in the registry.\n * \n * @example\n * ```json\n * {\n * \"type\": \"rest\",\n * \"tags\": [\"customer\"],\n * \"status\": \"active\"\n * }\n * ```\n */\nexport const ApiDiscoveryQuerySchema = z.object({\n /** Filter by API type */\n type: ApiProtocolType.optional().describe('Filter by API protocol type'),\n \n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags (ANY match)'),\n \n /** Filter by status */\n status: z.enum(['active', 'deprecated', 'experimental', 'beta']).optional()\n .describe('Filter by lifecycle status'),\n \n /** Filter by plugin source */\n pluginSource: z.string().optional().describe('Filter by plugin name'),\n \n /** Search in name/description */\n search: z.string().optional().describe('Full-text search in name/description'),\n \n /** Filter by version */\n version: z.string().optional().describe('Filter by specific version'),\n});\n\nexport type ApiDiscoveryQuery = z.infer;\n\n/**\n * API Discovery Response Schema\n * \n * Response for API discovery queries.\n */\nexport const ApiDiscoveryResponseSchema = z.object({\n /** Matching APIs */\n apis: z.array(ApiRegistryEntrySchema).describe('Matching API entries'),\n \n /** Total matches */\n total: z.number().int().describe('Total matching APIs'),\n \n /** Applied filters */\n filters: ApiDiscoveryQuerySchema.optional().describe('Applied query filters'),\n});\n\nexport type ApiDiscoveryResponse = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create API endpoint registration\n */\nexport const ApiEndpointRegistration = Object.assign(ApiEndpointRegistrationSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API registry entry\n */\nexport const ApiRegistryEntry = Object.assign(ApiRegistryEntrySchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API registry\n */\nexport const ApiRegistry = Object.assign(ApiRegistrySchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * API Documentation & Testing Interface Protocol\n * \n * Provides schemas for generating interactive API documentation and testing\n * interfaces similar to Swagger UI, GraphQL Playground, Postman, etc.\n * \n * Features:\n * - OpenAPI/Swagger specification generation\n * - Interactive API testing playground\n * - API versioning and changelog\n * - Code generation templates\n * - Mock server configuration\n * \n * Architecture Alignment:\n * - Swagger UI: Interactive API documentation\n * - Postman: API testing collections\n * - GraphQL Playground: GraphQL-specific testing\n * - Redoc: Documentation rendering\n * \n * @example Documentation Config\n * ```typescript\n * const docConfig: ApiDocumentationConfig = {\n * enabled: true,\n * title: 'ObjectStack API',\n * version: '1.0.0',\n * servers: [{ url: 'https://api.example.com', description: 'Production' }],\n * ui: {\n * type: 'swagger-ui',\n * theme: 'light',\n * enableTryItOut: true\n * }\n * }\n * ```\n */\n\n// ==========================================\n// OpenAPI Specification\n// ==========================================\n\n/**\n * OpenAPI Server Schema\n * \n * Server configuration for OpenAPI specification.\n */\nexport const OpenApiServerSchema = z.object({\n /** Server URL */\n url: z.string().url().describe('Server base URL'),\n \n /** Server description */\n description: z.string().optional().describe('Server description'),\n \n /** Server variables */\n variables: z.record(z.string(), z.object({\n default: z.string(),\n description: z.string().optional(),\n enum: z.array(z.string()).optional(),\n })).optional().describe('URL template variables'),\n});\n\nexport type OpenApiServer = z.infer;\n\n/**\n * OpenAPI Security Scheme Schema\n * \n * Security scheme definition for OpenAPI.\n */\nexport const OpenApiSecuritySchemeSchema = z.object({\n /** Security scheme type */\n type: z.enum(['apiKey', 'http', 'oauth2', 'openIdConnect']).describe('Security type'),\n \n /** Scheme name */\n scheme: z.string().optional().describe('HTTP auth scheme (bearer, basic, etc.)'),\n \n /** Bearer format */\n bearerFormat: z.string().optional().describe('Bearer token format (e.g., JWT)'),\n \n /** API key name */\n name: z.string().optional().describe('API key parameter name'),\n \n /** API key location */\n in: z.enum(['header', 'query', 'cookie']).optional().describe('API key location'),\n \n /** OAuth flows */\n flows: z.object({\n implicit: z.unknown().optional(),\n password: z.unknown().optional(),\n clientCredentials: z.unknown().optional(),\n authorizationCode: z.unknown().optional(),\n }).optional().describe('OAuth2 flows'),\n \n /** OpenID Connect URL */\n openIdConnectUrl: z.string().url().optional().describe('OpenID Connect discovery URL'),\n \n /** Description */\n description: z.string().optional().describe('Security scheme description'),\n});\n\nexport type OpenApiSecurityScheme = z.infer;\n\n/**\n * OpenAPI Specification Schema\n * \n * Complete OpenAPI 3.0 specification structure.\n * \n * @see https://swagger.io/specification/\n * \n * @example\n * ```json\n * {\n * \"openapi\": \"3.0.0\",\n * \"info\": {\n * \"title\": \"ObjectStack API\",\n * \"version\": \"1.0.0\",\n * \"description\": \"ObjectStack unified API\"\n * },\n * \"servers\": [\n * { \"url\": \"https://api.example.com\" }\n * ],\n * \"paths\": { ... },\n * \"components\": { ... }\n * }\n * ```\n */\nexport const OpenApiSpecSchema = z.object({\n /** OpenAPI version */\n openapi: z.string().default('3.0.0').describe('OpenAPI specification version'),\n \n /** API information */\n info: z.object({\n title: z.string().describe('API title'),\n version: z.string().describe('API version'),\n description: z.string().optional().describe('API description'),\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional(),\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional(),\n }).describe('API metadata'),\n \n /** Servers */\n servers: z.array(OpenApiServerSchema).optional().default([]).describe('API servers'),\n \n /** API paths */\n paths: z.record(z.string(), z.unknown()).describe('API paths and operations'),\n \n /** Reusable components */\n components: z.object({\n schemas: z.record(z.string(), z.unknown()).optional(),\n responses: z.record(z.string(), z.unknown()).optional(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n examples: z.record(z.string(), z.unknown()).optional(),\n requestBodies: z.record(z.string(), z.unknown()).optional(),\n headers: z.record(z.string(), z.unknown()).optional(),\n securitySchemes: z.record(z.string(), OpenApiSecuritySchemeSchema).optional(),\n links: z.record(z.string(), z.unknown()).optional(),\n callbacks: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Reusable components'),\n \n /** Security requirements */\n security: z.array(z.record(z.string(), z.array(z.string()))).optional()\n .describe('Global security requirements'),\n \n /** Tags */\n tags: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional(),\n })).optional().describe('Tag definitions'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation'),\n});\n\nexport type OpenApiSpec = z.infer;\n\n// ==========================================\n// API Testing Playground\n// ==========================================\n\n/**\n * API Testing UI Type\n */\nexport const ApiTestingUiType = z.enum([\n 'swagger-ui', // Swagger UI\n 'redoc', // Redoc\n 'rapidoc', // RapiDoc\n 'stoplight', // Stoplight Elements\n 'scalar', // Scalar API Reference\n 'graphql-playground', // GraphQL Playground\n 'graphiql', // GraphiQL\n 'postman', // Postman-like interface\n 'custom', // Custom implementation\n]);\n\nexport type ApiTestingUiType = z.infer;\n\n/**\n * API Testing UI Configuration Schema\n * \n * Configuration for interactive API testing interface.\n * \n * @example Swagger UI Config\n * ```json\n * {\n * \"type\": \"swagger-ui\",\n * \"path\": \"/api-docs\",\n * \"theme\": \"light\",\n * \"enableTryItOut\": true,\n * \"enableFilter\": true,\n * \"enableCors\": true,\n * \"defaultModelsExpandDepth\": 1\n * }\n * ```\n */\nexport const ApiTestingUiConfigSchema = z.object({\n /** UI type */\n type: ApiTestingUiType.describe('Testing UI implementation'),\n \n /** UI path */\n path: z.string().default('/api-docs').describe('URL path for documentation UI'),\n \n /** UI theme */\n theme: z.enum(['light', 'dark', 'auto']).default('light').describe('UI color theme'),\n \n /** Enable try-it-out feature */\n enableTryItOut: z.boolean().default(true).describe('Enable interactive API testing'),\n \n /** Enable filtering */\n enableFilter: z.boolean().default(true).describe('Enable endpoint filtering'),\n \n /** Enable CORS for testing */\n enableCors: z.boolean().default(true).describe('Enable CORS for browser testing'),\n \n /** Default expand depth for models */\n defaultModelsExpandDepth: z.number().int().min(-1).default(1)\n .describe('Default expand depth for schemas (-1 = fully expand)'),\n \n /** Display request duration */\n displayRequestDuration: z.boolean().default(true).describe('Show request duration'),\n \n /** Syntax highlighting */\n syntaxHighlighting: z.boolean().default(true).describe('Enable syntax highlighting'),\n \n /** Custom CSS URL */\n customCssUrl: z.string().url().optional().describe('Custom CSS stylesheet URL'),\n \n /** Custom JavaScript URL */\n customJsUrl: z.string().url().optional().describe('Custom JavaScript URL'),\n \n /** Layout options */\n layout: z.object({\n showExtensions: z.boolean().default(false).describe('Show vendor extensions'),\n showCommonExtensions: z.boolean().default(false).describe('Show common extensions'),\n deepLinking: z.boolean().default(true).describe('Enable deep linking'),\n displayOperationId: z.boolean().default(false).describe('Display operation IDs'),\n defaultModelRendering: z.enum(['example', 'model']).default('example')\n .describe('Default model rendering mode'),\n defaultModelsExpandDepth: z.number().int().default(1).describe('Models expand depth'),\n defaultModelExpandDepth: z.number().int().default(1).describe('Single model expand depth'),\n docExpansion: z.enum(['list', 'full', 'none']).default('list')\n .describe('Documentation expansion mode'),\n }).optional().describe('Layout configuration'),\n});\n\nexport type ApiTestingUiConfig = z.infer;\n\n/**\n * API Test Request Schema\n * \n * Represents a saved/example API test request.\n * \n * @example\n * ```json\n * {\n * \"name\": \"Get Customer by ID\",\n * \"description\": \"Retrieves a customer record\",\n * \"method\": \"GET\",\n * \"url\": \"/api/v1/data/customer/123\",\n * \"headers\": {\n * \"Authorization\": \"Bearer {{token}}\"\n * },\n * \"variables\": {\n * \"token\": \"sample_token\"\n * }\n * }\n * ```\n */\nexport const ApiTestRequestSchema = z.object({\n /** Request name */\n name: z.string().describe('Test request name'),\n \n /** Request description */\n description: z.string().optional().describe('Request description'),\n \n /** HTTP method */\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])\n .describe('HTTP method'),\n \n /** Request URL */\n url: z.string().describe('Request URL (can include variables)'),\n \n /** Request headers */\n headers: z.record(z.string(), z.string()).optional().default({})\n .describe('Request headers'),\n \n /** Query parameters */\n queryParams: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional().default({}).describe('Query parameters'),\n \n /** Request body */\n body: z.unknown().optional().describe('Request body'),\n \n /** Environment variables */\n variables: z.record(z.string(), z.unknown()).optional().default({})\n .describe('Template variables'),\n \n /** Expected response */\n expectedResponse: z.object({\n statusCode: z.number().int(),\n body: z.unknown().optional(),\n }).optional().describe('Expected response for validation'),\n});\n\nexport type ApiTestRequest = z.infer;\n\n/**\n * API Test Collection Schema\n * \n * Collection of test requests (similar to Postman collections).\n * \n * @example\n * ```json\n * {\n * \"name\": \"Customer API Tests\",\n * \"description\": \"Test collection for customer endpoints\",\n * \"variables\": {\n * \"baseUrl\": \"https://api.example.com\",\n * \"apiKey\": \"test_key\"\n * },\n * \"requests\": [...]\n * }\n * ```\n */\nexport const ApiTestCollectionSchema = z.object({\n /** Collection name */\n name: z.string().describe('Collection name'),\n \n /** Collection description */\n description: z.string().optional().describe('Collection description'),\n \n /** Collection variables */\n variables: z.record(z.string(), z.unknown()).optional().default({})\n .describe('Shared variables'),\n \n /** Test requests */\n requests: z.array(ApiTestRequestSchema).describe('Test requests in this collection'),\n \n /** Folders/grouping */\n folders: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n requests: z.array(ApiTestRequestSchema),\n })).optional().describe('Request folders for organization'),\n});\n\nexport type ApiTestCollection = z.infer;\n\n// ==========================================\n// API Documentation Configuration\n// ==========================================\n\n/**\n * API Changelog Entry Schema\n * \n * Documents changes in API versions.\n */\nexport const ApiChangelogEntrySchema = z.object({\n /** Version */\n version: z.string().describe('API version'),\n \n /** Release date */\n date: z.string().date().describe('Release date'),\n \n /** Changes */\n changes: z.object({\n added: z.array(z.string()).optional().default([]).describe('New features'),\n changed: z.array(z.string()).optional().default([]).describe('Changes'),\n deprecated: z.array(z.string()).optional().default([]).describe('Deprecations'),\n removed: z.array(z.string()).optional().default([]).describe('Removed features'),\n fixed: z.array(z.string()).optional().default([]).describe('Bug fixes'),\n security: z.array(z.string()).optional().default([]).describe('Security fixes'),\n }).describe('Version changes'),\n \n /** Migration guide */\n migrationGuide: z.string().optional().describe('Migration guide URL or text'),\n});\n\nexport type ApiChangelogEntry = z.infer;\n\n/**\n * Code Generation Template Schema\n * \n * Templates for generating client code.\n */\nexport const CodeGenerationTemplateSchema = z.object({\n /** Language/framework */\n language: z.string().describe('Target language/framework (e.g., typescript, python, curl)'),\n \n /** Template name */\n name: z.string().describe('Template name'),\n \n /** Template content */\n template: z.string().describe('Code template with placeholders'),\n \n /** Template variables */\n variables: z.array(z.string()).optional().describe('Required template variables'),\n});\n\nexport type CodeGenerationTemplate = z.infer;\n\n/**\n * API Documentation Configuration Schema\n * \n * Complete configuration for API documentation and testing interface.\n * \n * @example\n * ```json\n * {\n * \"enabled\": true,\n * \"title\": \"ObjectStack API Documentation\",\n * \"version\": \"1.0.0\",\n * \"description\": \"Unified API for ObjectStack platform\",\n * \"servers\": [\n * { \"url\": \"https://api.example.com\", \"description\": \"Production\" }\n * ],\n * \"ui\": {\n * \"type\": \"swagger-ui\",\n * \"theme\": \"light\",\n * \"enableTryItOut\": true\n * },\n * \"generateOpenApi\": true,\n * \"generateTestCollections\": true\n * }\n * ```\n */\nexport const ApiDocumentationConfigSchema = z.object({\n /** Enable documentation */\n enabled: z.boolean().default(true).describe('Enable API documentation'),\n \n /** Documentation title */\n title: z.string().default('API Documentation').describe('Documentation title'),\n \n /** API version */\n version: z.string().describe('API version'),\n \n /** API description */\n description: z.string().optional().describe('API description'),\n \n /** Server configurations */\n servers: z.array(OpenApiServerSchema).optional().default([])\n .describe('API server URLs'),\n \n /** UI configuration */\n ui: ApiTestingUiConfigSchema.optional().describe('Testing UI configuration'),\n \n /** Generate OpenAPI spec */\n generateOpenApi: z.boolean().default(true).describe('Generate OpenAPI 3.0 specification'),\n \n /** Generate test collections */\n generateTestCollections: z.boolean().default(true)\n .describe('Generate API test collections'),\n \n /** Test collections */\n testCollections: z.array(ApiTestCollectionSchema).optional().default([])\n .describe('Predefined test collections'),\n \n /** API changelog */\n changelog: z.array(ApiChangelogEntrySchema).optional().default([])\n .describe('API version changelog'),\n \n /** Code generation templates */\n codeTemplates: z.array(CodeGenerationTemplateSchema).optional().default([])\n .describe('Code generation templates'),\n \n /** Terms of service */\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n \n /** Contact information */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('Contact information'),\n \n /** License */\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional().describe('API license'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation link'),\n \n /** Security schemes */\n securitySchemes: z.record(z.string(), OpenApiSecuritySchemeSchema).optional()\n .describe('Security scheme definitions'),\n \n /** Global tags */\n tags: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional(),\n })).optional().describe('Global tag definitions'),\n});\n\nexport type ApiDocumentationConfig = z.infer;\n\n// ==========================================\n// API Documentation Generation\n// ==========================================\n\n/**\n * Generated API Documentation Schema\n * \n * Output of documentation generation process.\n */\nexport const GeneratedApiDocumentationSchema = z.object({\n /** OpenAPI specification */\n openApiSpec: OpenApiSpecSchema.optional().describe('Generated OpenAPI specification'),\n \n /** Test collections */\n testCollections: z.array(ApiTestCollectionSchema).optional()\n .describe('Generated test collections'),\n \n /** Markdown documentation */\n markdown: z.string().optional().describe('Generated markdown documentation'),\n \n /** HTML documentation */\n html: z.string().optional().describe('Generated HTML documentation'),\n \n /** Generation timestamp */\n generatedAt: z.string().datetime().describe('Generation timestamp'),\n \n /** Source APIs */\n sourceApis: z.array(z.string()).describe('Source API IDs used for generation'),\n});\n\nexport type GeneratedApiDocumentation = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create API documentation config\n */\nexport const ApiDocumentationConfig = Object.assign(ApiDocumentationConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API test collection\n */\nexport const ApiTestCollection = Object.assign(ApiTestCollectionSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create OpenAPI specification\n */\nexport const OpenApiSpec = Object.assign(OpenApiSpecSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Analytics/Semantic Layer Protocol\n * \n * Defines the \"Business Logic\" for data analysis.\n * Inspired by Cube.dev, LookML, and dbt MetricFlow.\n * \n * This layer decouples the \"Physical Data\" (Tables/Columns) from the \n * \"Business Data\" (Metrics/Dimensions).\n */\n\n/**\n * Aggregation Metric Type\n * The mathematical operation to perform on a metric.\n */\nexport const AggregationMetricType = z.enum([\n 'count', \n 'sum', \n 'avg', \n 'min', \n 'max', \n 'count_distinct', \n 'number', // Custom SQL expression returning a number\n 'string', // Custom SQL expression returning a string\n 'boolean' // Custom SQL expression returning a boolean\n]);\n\n/**\n * Dimension Type\n * The nature of the grouping field.\n */\nexport const DimensionType = z.enum([\n 'string', \n 'number', \n 'boolean', \n 'time', \n 'geo'\n]);\n\n/**\n * Time Interval for Time Dimensions\n */\nexport const TimeUpdateInterval = z.enum([\n 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'\n]);\n\n/**\n * Metric Schema\n * A quantitative measurement (e.g., \"Total Revenue\", \"Average Order Value\").\n */\nexport const MetricSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique metric ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: AggregationMetricType,\n \n /** Source Calculation */\n sql: z.string().describe('SQL expression or field reference'),\n \n /** Filtering for this specific metric (e.g. \"Revenue from Premium Users\") */\n filters: z.array(z.object({\n sql: z.string()\n })).optional(),\n \n /** Format for display (e.g. \"currency\", \"percent\") */\n format: z.string().optional(),\n});\n\n/**\n * Dimension Schema\n * A categorical attribute to group by (e.g., \"Product Category\", \"Order Date\").\n */\nexport const DimensionSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique dimension ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: DimensionType,\n \n /** Source Column */\n sql: z.string().describe('SQL expression or column reference'),\n \n /** For Time Dimensions: Supported Granularities */\n granularities: z.array(TimeUpdateInterval).optional(),\n});\n\n/**\n * Join Schema\n * Defines how this cube relates to others.\n */\nexport const CubeJoinSchema = z.object({\n name: z.string().describe('Target cube name'),\n relationship: z.enum(['one_to_one', 'one_to_many', 'many_to_one']).default('many_to_one'),\n sql: z.string().describe('Join condition (ON clause)'),\n});\n\n/**\n * Cube Schema\n * A logical data model representing a business entity or process for analysis.\n * Maps physical tables to business metrics and dimensions.\n */\nexport const CubeSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Cube name (snake_case)'),\n title: z.string().optional(),\n description: z.string().optional(),\n \n /** Physical Data Source */\n sql: z.string().describe('Base SQL statement or Table Name'),\n \n /** Semantic Definitions */\n measures: z.record(z.string(), MetricSchema).describe('Quantitative metrics'),\n dimensions: z.record(z.string(), DimensionSchema).describe('Qualitative attributes'),\n \n /** Relationships */\n joins: z.record(z.string(), CubeJoinSchema).optional(),\n \n /** Pre-aggregations / Caching */\n refreshKey: z.object({\n every: z.string().optional(), // e.g. \"1 hour\"\n sql: z.string().optional(), // SQL to check for data changes\n }).optional(),\n \n /** Access Control */\n public: z.boolean().default(false),\n});\n\n/**\n * Analytics Query Schema\n * The request format for the Analytics API.\n */\nexport const AnalyticsQuerySchema = z.object({\n cube: z.string().optional().describe('Target cube name (optional when provided externally, e.g. in API request wrapper)'),\n measures: z.array(z.string()).describe('List of metrics to calculate'),\n dimensions: z.array(z.string()).optional().describe('List of dimensions to group by'),\n \n filters: z.array(z.object({\n member: z.string().describe('Dimension or Measure'),\n operator: z.enum(['equals', 'notEquals', 'contains', 'notContains', 'gt', 'gte', 'lt', 'lte', 'set', 'notSet', 'inDateRange']),\n values: z.array(z.string()).optional(),\n })).optional(),\n \n timeDimensions: z.array(z.object({\n dimension: z.string(),\n granularity: TimeUpdateInterval.optional(),\n dateRange: z.union([\n z.string(), // \"Last 7 days\"\n z.array(z.string()) // [\"2023-01-01\", \"2023-01-31\"]\n ]).optional(),\n })).optional(),\n \n order: z.record(z.string(), z.enum(['asc', 'desc'])).optional(),\n \n limit: z.number().optional(),\n offset: z.number().optional(),\n \n timezone: z.string().optional().default('UTC'),\n});\n\nexport type Metric = z.infer;\nexport type Dimension = z.infer;\nexport type CubeJoin = z.infer;\nexport type Cube = z.infer;\nexport type AnalyticsQuery = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { AnalyticsQuerySchema, CubeSchema } from '../data/analytics.zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Analytics API Protocol\n * \n * Defines the HTTP interface for the Semantic Layer.\n * Provides endpoints for executing analytical queries and discovering metadata.\n */\n\n// ==========================================\n// 1. API Endpoints\n// ==========================================\n\nexport const AnalyticsEndpoint = z.enum([\n '/api/v1/analytics/query', // Execute analysis\n '/api/v1/analytics/meta', // Discover cubes/metrics\n '/api/v1/analytics/sql', // Dry-run SQL generation\n]);\n\n// ==========================================\n// 2. Query Execution\n// ==========================================\n\n/**\n * Query Request Body\n */\nexport const AnalyticsQueryRequestSchema = z.object({\n query: AnalyticsQuerySchema.describe('The analytic query definition'),\n cube: z.string().describe('Target cube name'),\n format: z.enum(['json', 'csv', 'xlsx']).default('json').describe('Response format'),\n});\n\n/**\n * Query Response (JSON)\n */\nexport const AnalyticsResultResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n rows: z.array(z.record(z.string(), z.unknown())).describe('Result rows'),\n fields: z.array(z.object({\n name: z.string(),\n type: z.string(),\n })).describe('Column metadata'),\n sql: z.string().optional().describe('Executed SQL (if debug enabled)'),\n }),\n});\n\n// ==========================================\n// 3. Metadata Discovery\n// ==========================================\n\n/**\n * Meta Request\n */\nexport const GetAnalyticsMetaRequestSchema = z.object({\n cube: z.string().optional().describe('Optional cube name to filter'),\n});\n\n/**\n * Meta Response\n * Returns available cubes, metrics, and dimensions.\n */\nexport const AnalyticsMetadataResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n cubes: z.array(CubeSchema).describe('Available cubes'),\n }),\n});\n\n// ==========================================\n// 4. SQL Dry-Run\n// ==========================================\n\nexport const AnalyticsSqlResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n sql: z.string(),\n params: z.array(z.unknown()),\n }),\n});\n\nexport type AnalyticsEndpoint = z.infer;\nexport type AnalyticsQueryRequest = z.infer;\nexport type AnalyticsMetadataResponse = z.infer;\nexport type AnalyticsSqlResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # API Versioning Protocol\n * \n * Defines how API versions are negotiated between client and server.\n * Supports multiple versioning strategies and deprecation lifecycle management.\n * \n * Architecture Alignment:\n * - Salesforce: URL path versioning (v57.0, v58.0)\n * - Stripe: Date-based versioning (2024-01-01)\n * - Kubernetes: API group versioning (v1, v1beta1)\n * - GitHub: Accept header versioning (application/vnd.github.v3+json)\n * - Microsoft Graph: URL path versioning (v1.0, beta)\n */\n\n// ==========================================\n// Versioning Strategy\n// ==========================================\n\n/**\n * API Versioning Strategy\n * Determines how the API version is specified by clients.\n * \n * - `urlPath`: Version in URL path (e.g., /api/v1/data) — Most common, easy to understand\n * - `header`: Version in Accept header (e.g., Accept: application/vnd.objectstack.v1+json)\n * - `queryParam`: Version in query parameter (e.g., /api/data?version=v1)\n * - `dateBased`: Date-based version in header (e.g., ObjectStack-Version: 2025-01-01) — Stripe-style\n */\nexport const VersioningStrategy = z.enum([\n 'urlPath',\n 'header',\n 'queryParam',\n 'dateBased',\n]);\n\nexport type VersioningStrategy = z.infer;\n\n// ==========================================\n// Version Lifecycle\n// ==========================================\n\n/**\n * API Version Status\n * Lifecycle state of an API version.\n * \n * - `preview`: Available for testing, may change without notice (e.g., v2beta1)\n * - `current`: The recommended stable version\n * - `supported`: Older but still maintained (receives security fixes)\n * - `deprecated`: Scheduled for removal, clients should migrate\n * - `retired`: No longer available, requests return 410 Gone\n */\nexport const VersionStatus = z.enum([\n 'preview',\n 'current',\n 'supported',\n 'deprecated',\n 'retired',\n]);\n\nexport type VersionStatus = z.infer;\n\n// ==========================================\n// Version Definition\n// ==========================================\n\n/**\n * API Version Definition Schema\n * Describes a single API version and its lifecycle metadata.\n * \n * @example\n * {\n * \"version\": \"v1\",\n * \"status\": \"current\",\n * \"releasedAt\": \"2025-01-15\",\n * \"description\": \"Initial stable release\"\n * }\n * \n * @example Deprecated version\n * {\n * \"version\": \"v0\",\n * \"status\": \"deprecated\",\n * \"releasedAt\": \"2024-06-01\",\n * \"deprecatedAt\": \"2025-01-15\",\n * \"sunsetAt\": \"2025-07-15\",\n * \"migrationGuide\": \"https://docs.objectstack.dev/migrate/v0-to-v1\",\n * \"description\": \"Legacy API version\"\n * }\n */\nexport const VersionDefinitionSchema = z.object({\n /** Version identifier (e.g., \"v1\", \"v2beta1\", \"2025-01-01\") */\n version: z.string().describe('Version identifier (e.g., \"v1\", \"v2beta1\", \"2025-01-01\")'),\n\n /** Current lifecycle status */\n status: VersionStatus.describe('Lifecycle status of this version'),\n\n /** Date this version was released (ISO 8601 date) */\n releasedAt: z.string().describe('Release date (ISO 8601, e.g., \"2025-01-15\")'),\n\n /** Date this version was deprecated (ISO 8601 date) */\n deprecatedAt: z.string().optional()\n .describe('Deprecation date (ISO 8601). Only set for deprecated/retired versions'),\n\n /** Date this version will be retired (ISO 8601 date) */\n sunsetAt: z.string().optional()\n .describe('Sunset date (ISO 8601). After this date, the version returns 410 Gone'),\n\n /** URL to migration guide for moving to a newer version */\n migrationGuide: z.string().url().optional()\n .describe('URL to migration guide for upgrading from this version'),\n\n /** Human-readable description of this version */\n description: z.string().optional()\n .describe('Human-readable description or release notes summary'),\n\n /** Breaking changes introduced in or since this version */\n breakingChanges: z.array(z.string()).optional()\n .describe('List of breaking changes (for preview/new versions)'),\n});\n\nexport type VersionDefinition = z.infer;\n\n// ==========================================\n// Versioning Configuration\n// ==========================================\n\n/**\n * API Versioning Configuration Schema\n * Complete configuration for API version management.\n * \n * @example\n * {\n * \"strategy\": \"urlPath\",\n * \"current\": \"v1\",\n * \"default\": \"v1\",\n * \"versions\": [\n * { \"version\": \"v1\", \"status\": \"current\", \"releasedAt\": \"2025-01-15\" },\n * { \"version\": \"v2beta1\", \"status\": \"preview\", \"releasedAt\": \"2025-06-01\" }\n * ],\n * \"deprecation\": {\n * \"warnHeader\": true,\n * \"sunsetHeader\": true\n * }\n * }\n */\nexport const VersioningConfigSchema = z.object({\n /** Versioning strategy */\n strategy: VersioningStrategy.default('urlPath')\n .describe('How the API version is specified by clients'),\n\n /** Current (recommended) API version */\n current: z.string().describe('The current/recommended API version identifier'),\n\n /** Default version when none specified by client */\n default: z.string().describe('Fallback version when client does not specify one'),\n\n /** All available API versions */\n versions: z.array(VersionDefinitionSchema)\n .min(1)\n .describe('All available API versions with lifecycle metadata'),\n\n /** Header name for header-based versioning */\n headerName: z.string().default('ObjectStack-Version')\n .describe('HTTP header name for version negotiation (header/dateBased strategies)'),\n\n /** Query parameter name for queryParam strategy */\n queryParamName: z.string().default('version')\n .describe('Query parameter name for version specification (queryParam strategy)'),\n\n /** URL prefix pattern for urlPath strategy */\n urlPrefix: z.string().default('/api')\n .describe('URL prefix before version segment (urlPath strategy)'),\n\n /** Deprecation behavior */\n deprecation: z.object({\n /** Include Deprecation header in responses for deprecated versions */\n warnHeader: z.boolean().default(true)\n .describe('Include Deprecation header (RFC 8594) in responses'),\n\n /** Include Sunset header with retirement date */\n sunsetHeader: z.boolean().default(true)\n .describe('Include Sunset header (RFC 8594) with retirement date'),\n\n /** Include Link header pointing to migration guide */\n linkHeader: z.boolean().default(true)\n .describe('Include Link header pointing to migration guide URL'),\n\n /** Whether to reject requests to retired versions */\n rejectRetired: z.boolean().default(true)\n .describe('Return 410 Gone for retired API versions'),\n\n /** Custom deprecation warning message */\n warningMessage: z.string().optional()\n .describe('Custom warning message for deprecated version responses'),\n }).optional().describe('Deprecation lifecycle behavior'),\n\n /** Whether to include version info in discovery response */\n includeInDiscovery: z.boolean().default(true)\n .describe('Include version information in the API discovery endpoint'),\n});\n\nexport type VersioningConfig = z.infer;\nexport type VersioningConfigInput = z.input;\n\n// ==========================================\n// Version Negotiation Response\n// ==========================================\n\n/**\n * Version Negotiation Response Schema\n * Returned when a client requests version information or\n * included in the discovery endpoint response.\n * \n * @example\n * {\n * \"current\": \"v1\",\n * \"requested\": \"v1\",\n * \"resolved\": \"v1\",\n * \"supported\": [\"v1\", \"v2beta1\"],\n * \"deprecated\": [\"v0\"],\n * \"versions\": [...]\n * }\n */\nexport const VersionNegotiationResponseSchema = z.object({\n /** The current/recommended version */\n current: z.string().describe('Current recommended API version'),\n\n /** The version the client requested (if any) */\n requested: z.string().optional().describe('Version requested by the client'),\n\n /** The version actually being used for this request */\n resolved: z.string().describe('Resolved API version for this request'),\n\n /** All supported (non-retired) version identifiers */\n supported: z.array(z.string()).describe('All supported version identifiers'),\n\n /** Deprecated version identifiers (still functional but will be removed) */\n deprecated: z.array(z.string()).optional()\n .describe('Deprecated version identifiers'),\n\n /** Full version definitions (optional, for detailed clients) */\n versions: z.array(VersionDefinitionSchema).optional()\n .describe('Full version definitions with lifecycle metadata'),\n});\n\nexport type VersionNegotiationResponse = z.infer;\n\n// ==========================================\n// Default Versioning Configuration\n// ==========================================\n\n/**\n * Default versioning configuration for ObjectStack.\n * Uses URL path strategy with v1 as the current/default version.\n */\nexport const DEFAULT_VERSIONING_CONFIG: VersioningConfigInput = {\n strategy: 'urlPath',\n current: 'v1',\n default: 'v1',\n versions: [\n {\n version: 'v1',\n status: 'current',\n releasedAt: '2025-01-15',\n description: 'ObjectStack API v1 — Initial stable release',\n },\n ],\n deprecation: {\n warnHeader: true,\n sunsetHeader: true,\n linkHeader: true,\n rejectRetired: true,\n },\n includeInDiscovery: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Authentication Service Protocol\n * \n * Defines the standard API contracts for Identity, Session Management,\n * and Access Control.\n */\n\n// ==========================================\n// Authentication Types\n// ==========================================\n\nexport const AuthProvider = z.enum([\n 'local',\n 'google',\n 'github',\n 'microsoft',\n 'ldap',\n 'saml'\n]);\n\nexport const SessionUserSchema = z.object({\n id: z.string().describe('User ID'),\n email: z.string().email().describe('Email address'),\n emailVerified: z.boolean().default(false).describe('Is email verified?'),\n name: z.string().describe('Display name'),\n image: z.string().optional().describe('Avatar URL'),\n username: z.string().optional().describe('Username (optional)'),\n roles: z.array(z.string()).optional().default([]).describe('Assigned role IDs'),\n tenantId: z.string().optional().describe('Current tenant ID'),\n language: z.string().default('en').describe('Preferred language'),\n timezone: z.string().optional().describe('Preferred timezone'),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n});\n\nexport const SessionSchema = z.object({\n id: z.string(),\n expiresAt: z.string().datetime(),\n token: z.string().optional(),\n ipAddress: z.string().optional(),\n userAgent: z.string().optional(),\n userId: z.string(),\n});\n\n// ==========================================\n// Requests\n// ==========================================\n\nexport const LoginType = z.enum(['email', 'username', 'phone', 'magic-link', 'social']);\n\nexport const LoginRequestSchema = z.object({\n type: LoginType.default('email').describe('Login method'),\n email: z.string().email().optional().describe('Required for email/magic-link'),\n username: z.string().optional().describe('Required for username login'),\n password: z.string().optional().describe('Required for password login'),\n provider: z.string().optional().describe('Required for social (google, github)'),\n redirectTo: z.string().optional().describe('Redirect URL after successful login'),\n});\n\nexport const RegisterRequestSchema = z.object({\n email: z.string().email(),\n password: z.string(),\n name: z.string(),\n image: z.string().optional(),\n});\n\nexport const RefreshTokenRequestSchema = z.object({\n refreshToken: z.string().describe('Refresh token'),\n});\n\n// ==========================================\n// Responses\n// ==========================================\n\nexport const SessionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n session: SessionSchema.describe('Active Session Info'),\n user: SessionUserSchema.describe('Current User Details'),\n token: z.string().optional().describe('Bearer token if not using cookies'),\n }),\n});\n\nexport const UserProfileResponseSchema = BaseResponseSchema.extend({\n data: SessionUserSchema,\n});\n\nexport type AuthProvider = z.infer;\nexport type SessionUser = z.infer;\nexport type SessionUserInput = z.input;\nexport type Session = z.infer;\nexport type LoginType = z.infer;\nexport type LoginRequest = z.infer;\nexport type LoginRequestInput = z.input;\nexport type RegisterRequest = z.infer;\nexport type RefreshTokenRequest = z.infer;\nexport type SessionResponse = z.infer;\nexport type UserProfileResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Authentication Endpoint Specification\n * \n * Defines the canonical HTTP endpoints for the authentication service.\n * Based on better-auth v1.4.18 endpoint conventions.\n * \n * NOTE: ObjectStack's auth implementation uses better-auth library which has\n * established endpoint conventions. This spec documents those conventions as\n * the canonical API contract.\n */\n\n// ==========================================\n// Endpoint Path Definitions\n// ==========================================\n\n/**\n * Authentication Endpoint Paths\n * \n * These are the paths relative to the auth base route (e.g., /api/v1/auth).\n * Based on better-auth's endpoint structure.\n */\nexport const AuthEndpointPaths = {\n // Email/Password Authentication\n signInEmail: '/sign-in/email',\n signUpEmail: '/sign-up/email',\n signOut: '/sign-out',\n \n // Session Management\n getSession: '/get-session',\n \n // Password Management\n forgetPassword: '/forget-password',\n resetPassword: '/reset-password',\n \n // Email Verification\n sendVerificationEmail: '/send-verification-email',\n verifyEmail: '/verify-email',\n \n // OAuth (dynamic based on provider)\n // authorize: '/authorize/:provider'\n // callback: '/callback/:provider'\n \n // 2FA (when enabled)\n twoFactorEnable: '/two-factor/enable',\n twoFactorVerify: '/two-factor/verify',\n \n // Passkeys (when enabled)\n passkeyRegister: '/passkey/register',\n passkeyAuthenticate: '/passkey/authenticate',\n \n // Magic Links (when enabled)\n magicLinkSend: '/magic-link/send',\n magicLinkVerify: '/magic-link/verify',\n} as const;\n\n/**\n * HTTP Method + Path Specification\n * \n * Defines the complete HTTP contract for each endpoint.\n */\nexport const AuthEndpointSchema = z.object({\n /** Sign in with email and password */\n signInEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signInEmail),\n description: z.literal('Sign in with email and password'),\n }),\n \n /** Register new user with email and password */\n signUpEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signUpEmail),\n description: z.literal('Register new user with email and password'),\n }),\n \n /** Sign out current user */\n signOut: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signOut),\n description: z.literal('Sign out current user'),\n }),\n \n /** Get current user session */\n getSession: z.object({\n method: z.literal('GET'),\n path: z.literal(AuthEndpointPaths.getSession),\n description: z.literal('Get current user session'),\n }),\n \n /** Request password reset email */\n forgetPassword: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.forgetPassword),\n description: z.literal('Request password reset email'),\n }),\n \n /** Reset password with token */\n resetPassword: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.resetPassword),\n description: z.literal('Reset password with token'),\n }),\n \n /** Send email verification */\n sendVerificationEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.sendVerificationEmail),\n description: z.literal('Send email verification link'),\n }),\n \n /** Verify email with token */\n verifyEmail: z.object({\n method: z.literal('GET'),\n path: z.literal(AuthEndpointPaths.verifyEmail),\n description: z.literal('Verify email with token'),\n }),\n});\n\n/**\n * Endpoint Aliases\n * \n * Common aliases for better developer experience.\n * These map to the canonical better-auth endpoints.\n */\nexport const AuthEndpointAliases = {\n login: AuthEndpointPaths.signInEmail,\n register: AuthEndpointPaths.signUpEmail,\n logout: AuthEndpointPaths.signOut,\n me: AuthEndpointPaths.getSession,\n} as const;\n\n/**\n * Full Endpoint URLs\n * \n * Helper to construct full endpoint URLs given a base path.\n */\nexport function getAuthEndpointUrl(basePath: string, endpoint: keyof typeof AuthEndpointPaths): string {\n const cleanBase = basePath.replace(/\\/$/, '');\n return `${cleanBase}${AuthEndpointPaths[endpoint]}`;\n}\n\n/**\n * Endpoint Mapping\n * \n * Maps common/legacy endpoint names to canonical better-auth paths.\n * This allows clients to use simpler names while maintaining compatibility.\n */\nexport const EndpointMapping = {\n '/login': AuthEndpointPaths.signInEmail,\n '/register': AuthEndpointPaths.signUpEmail,\n '/logout': AuthEndpointPaths.signOut,\n '/me': AuthEndpointPaths.getSession,\n '/refresh': AuthEndpointPaths.getSession, // Session refresh handled by better-auth automatically\n} as const;\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type AuthEndpoint = z.infer;\nexport type AuthEndpointPath = typeof AuthEndpointPaths[keyof typeof AuthEndpointPaths];\nexport type AuthEndpointAlias = keyof typeof AuthEndpointAliases;\nexport type EndpointMappingKey = keyof typeof EndpointMapping;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Object Storage Protocol\n * \n * Unified storage protocol that combines:\n * - Object storage systems (S3, Azure Blob, GCS, MinIO)\n * - Scoped storage configuration (temp, cache, data, logs, config, public)\n * - Multi-cloud storage providers\n * - Bucket/container configuration\n * - Access control and permissions\n * - Lifecycle policies for data retention\n * - Presigned URLs for secure direct access\n * - Multipart uploads for large files\n */\n\n// ============================================================================\n// Storage Scope Protocol (formerly from scoped-storage.zod.ts)\n// ============================================================================\n\n/**\n * Storage Scope Enum\n * Defines the lifecycle and persistence guarantee of the storage area.\n */\nexport const StorageScopeSchema = z.enum([\n 'global', // Global application-wide storage\n 'tenant', // Tenant-scoped storage (multi-tenant apps)\n 'user', // User-scoped storage\n 'session', // Session-scoped storage (ephemeral)\n 'temp', // Ephemeral, cleared on restart\n 'cache', // Ephemeral, survives restarts, cleared on LRU/Expiration\n 'data', // Persistent, backed up\n 'logs', // Append-only, rotated\n 'config', // Read-heavy, versioned\n 'public' // Publicly accessible static assets\n]).describe('Storage scope classification');\n\nexport type StorageScope = z.infer;\n\n/**\n * File Metadata Schema\n * Standardized file attribute structure\n */\nexport const FileMetadataSchema = z.object({\n path: z.string().describe('File path'),\n name: z.string().describe('File name'),\n size: z.number().int().describe('File size in bytes'),\n mimeType: z.string().describe('MIME type'),\n lastModified: z.string().datetime().describe('Last modified timestamp'),\n created: z.string().datetime().describe('Creation timestamp'),\n etag: z.string().optional().describe('Entity tag'),\n});\n\nexport type FileMetadata = z.infer;\n\n// ============================================================================\n// Enums\n// ============================================================================\n\n/**\n * Storage Provider Types\n * \n * Supported cloud and self-hosted object storage providers.\n */\nexport const StorageProviderSchema = z.enum([\n 's3', // Amazon S3\n 'azure_blob', // Azure Blob Storage\n 'gcs', // Google Cloud Storage\n 'minio', // MinIO (self-hosted S3-compatible)\n 'r2', // Cloudflare R2\n 'spaces', // DigitalOcean Spaces\n 'wasabi', // Wasabi Hot Cloud Storage\n 'backblaze', // Backblaze B2\n 'local', // Local filesystem (development only)\n]).describe('Storage provider type');\n\nexport type StorageProvider = z.infer;\n\n/**\n * Storage Access Control List (ACL)\n * \n * Predefined access control configurations for objects and buckets.\n */\nexport const StorageAclSchema = z.enum([\n 'private', // Owner has full control, no one else has access\n 'public_read', // Owner has full control, everyone can read\n 'public_read_write', // Owner has full control, everyone can read/write (not recommended)\n 'authenticated_read', // Owner has full control, authenticated users can read\n 'bucket_owner_read', // Object owner has full control, bucket owner can read\n 'bucket_owner_full_control', // Both object and bucket owner have full control\n]).describe('Storage access control level');\n\nexport type StorageAcl = z.infer;\n\n/**\n * Storage Class / Tier\n * \n * Different storage tiers for cost optimization.\n * Maps to provider-specific storage classes.\n */\nexport const StorageClassSchema = z.enum([\n 'standard', // Standard/hot storage for frequently accessed data\n 'intelligent', // Intelligent tiering (auto-moves between hot/cool)\n 'infrequent_access', // Infrequent access/cool storage\n 'glacier', // Archive/cold storage (slower retrieval)\n 'deep_archive', // Deep archive (cheapest, slowest retrieval)\n]).describe('Storage class/tier for cost optimization');\n\nexport type StorageClass = z.infer;\n\n/**\n * Lifecycle Transition Action\n */\nexport const LifecycleActionSchema = z.enum([\n 'transition', // Move to different storage class\n 'delete', // Delete the object\n 'abort', // Abort incomplete multipart uploads\n]).describe('Lifecycle policy action type');\n\nexport type LifecycleAction = z.infer;\n\n// ============================================================================\n// Configuration Schemas\n// ============================================================================\n\n/**\n * Object Metadata Schema\n * \n * Standard and custom metadata attached to stored objects.\n * \n * @example\n * {\n * contentType: 'image/jpeg',\n * contentLength: 1024000,\n * etag: '\"abc123\"',\n * lastModified: new Date('2024-01-01'),\n * custom: {\n * uploadedBy: 'user123',\n * department: 'marketing'\n * }\n * }\n */\nexport const ObjectMetadataSchema = z.object({\n contentType: z.string().describe('MIME type (e.g., image/jpeg, application/pdf)'),\n contentLength: z.number().min(0).describe('File size in bytes'),\n contentEncoding: z.string().optional().describe('Content encoding (e.g., gzip)'),\n contentDisposition: z.string().optional().describe('Content disposition header'),\n contentLanguage: z.string().optional().describe('Content language'),\n cacheControl: z.string().optional().describe('Cache control directives'),\n etag: z.string().optional().describe('Entity tag for versioning/caching'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n versionId: z.string().optional().describe('Object version identifier'),\n storageClass: StorageClassSchema.optional().describe('Storage class/tier'),\n encryption: z.object({\n algorithm: z.string().describe('Encryption algorithm (e.g., AES256, aws:kms)'),\n keyId: z.string().optional().describe('KMS key ID if using managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n custom: z.record(z.string(), z.string()).optional().describe('Custom user-defined metadata'),\n});\n\nexport type ObjectMetadata = z.infer;\n\n/**\n * Presigned URL Configuration\n * \n * Configuration for generating temporary URLs for direct access to objects.\n * Useful for secure file uploads/downloads without exposing credentials.\n * \n * @example\n * // Generate download URL valid for 1 hour\n * {\n * operation: 'get',\n * expiresIn: 3600,\n * contentType: 'image/jpeg'\n * }\n * \n * @example\n * // Generate upload URL valid for 15 minutes with size limit\n * {\n * operation: 'put',\n * expiresIn: 900,\n * contentType: 'application/pdf',\n * maxSize: 10485760\n * }\n */\nexport const PresignedUrlConfigSchema = z.object({\n operation: z.enum(['get', 'put', 'delete', 'head']).describe('Allowed operation'),\n expiresIn: z.number().min(1).max(604800).describe('Expiration time in seconds (max 7 days)'),\n contentType: z.string().optional().describe('Required content type for PUT operations'),\n maxSize: z.number().min(0).optional().describe('Maximum file size in bytes for PUT operations'),\n responseContentType: z.string().optional().describe('Override content-type for GET operations'),\n responseContentDisposition: z.string().optional().describe('Override content-disposition for GET operations'),\n});\n\nexport type PresignedUrlConfig = z.infer;\n\n/**\n * Multipart Upload Configuration\n * \n * Configuration for chunked uploads of large files.\n * Enables resumable uploads and parallel transfer.\n * \n * @example\n * // Enable multipart for files > 100MB with 10MB chunks\n * {\n * enabled: true,\n * partSize: 10485760,\n * maxParts: 10000,\n * threshold: 104857600,\n * maxConcurrent: 4\n * }\n */\nexport const MultipartUploadConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable multipart uploads'),\n partSize: z.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe('Part size in bytes (min 5MB, max 5GB)'),\n maxParts: z.number().min(1).max(10000).default(10000).describe('Maximum number of parts (max 10,000)'),\n threshold: z.number().min(0).default(100 * 1024 * 1024).describe('File size threshold to trigger multipart upload (bytes)'),\n maxConcurrent: z.number().min(1).max(100).default(4).describe('Maximum concurrent part uploads'),\n abortIncompleteAfterDays: z.number().min(1).optional().describe('Auto-abort incomplete uploads after N days'),\n});\n\nexport type MultipartUploadConfig = z.infer;\n\n/**\n * Access Control Configuration\n * \n * Fine-grained access control for buckets and objects.\n * \n * @example\n * {\n * acl: 'private',\n * allowedOrigins: ['https://app.example.com'],\n * allowedMethods: ['GET', 'PUT'],\n * corsEnabled: true,\n * publicAccess: {\n * allowPublicRead: false,\n * allowPublicWrite: false\n * }\n * }\n */\nexport const AccessControlConfigSchema = z.object({\n acl: StorageAclSchema.default('private').describe('Default access control level'),\n allowedOrigins: z.array(z.string()).optional().describe('CORS allowed origins'),\n allowedMethods: z.array(z.enum(['GET', 'PUT', 'POST', 'DELETE', 'HEAD'])).optional().describe('CORS allowed HTTP methods'),\n allowedHeaders: z.array(z.string()).optional().describe('CORS allowed headers'),\n exposeHeaders: z.array(z.string()).optional().describe('CORS exposed headers'),\n maxAge: z.number().min(0).optional().describe('CORS preflight cache duration in seconds'),\n corsEnabled: z.boolean().default(false).describe('Enable CORS configuration'),\n publicAccess: z.object({\n allowPublicRead: z.boolean().default(false).describe('Allow public read access'),\n allowPublicWrite: z.boolean().default(false).describe('Allow public write access'),\n allowPublicList: z.boolean().default(false).describe('Allow public bucket listing'),\n }).optional().describe('Public access control'),\n allowedIps: z.array(z.string()).optional().describe('Allowed IP addresses/CIDR blocks'),\n blockedIps: z.array(z.string()).optional().describe('Blocked IP addresses/CIDR blocks'),\n});\n\nexport type AccessControlConfig = z.infer;\n\n/**\n * Lifecycle Policy Rule\n * \n * Individual rule for automatic object lifecycle management.\n * \n * @example\n * // Transition to infrequent access after 30 days\n * {\n * id: 'move_to_ia',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 30,\n * targetStorageClass: 'infrequent_access'\n * }\n * \n * @example\n * // Delete objects after 365 days\n * {\n * id: 'delete_old',\n * enabled: true,\n * action: 'delete',\n * daysAfterCreation: 365\n * }\n */\nexport const LifecyclePolicyRuleSchema = z.object({\n id: SystemIdentifierSchema.describe('Rule identifier'),\n enabled: z.boolean().default(true).describe('Enable this rule'),\n action: LifecycleActionSchema.describe('Action to perform'),\n prefix: z.string().optional().describe('Object key prefix filter (e.g., \"uploads/\")'),\n tags: z.record(z.string(), z.string()).optional().describe('Object tag filters'),\n daysAfterCreation: z.number().min(0).optional().describe('Days after object creation'),\n daysAfterModification: z.number().min(0).optional().describe('Days after last modification'),\n targetStorageClass: StorageClassSchema.optional().describe('Target storage class for transition action'),\n}).refine((data) => {\n // Validate that transition action has targetStorageClass\n if (data.action === 'transition' && !data.targetStorageClass) {\n return false;\n }\n return true;\n}, {\n message: 'targetStorageClass is required when action is \"transition\"',\n});\n\nexport type LifecyclePolicyRule = z.infer;\n\n/**\n * Lifecycle Policy Configuration\n * \n * Collection of lifecycle rules for automatic data management.\n * \n * @example\n * {\n * enabled: true,\n * rules: [\n * {\n * id: 'archive_old_files',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 90,\n * targetStorageClass: 'glacier'\n * },\n * {\n * id: 'delete_temp_files',\n * enabled: true,\n * action: 'delete',\n * prefix: 'temp/',\n * daysAfterCreation: 7\n * }\n * ]\n * }\n */\nexport const LifecyclePolicyConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable lifecycle policies'),\n rules: z.array(LifecyclePolicyRuleSchema).default([]).describe('Lifecycle rules'),\n});\n\nexport type LifecyclePolicyConfig = z.infer;\n\n/**\n * Bucket Configuration Schema\n * \n * Comprehensive configuration for a storage bucket/container.\n * \n * @example\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'my-app-uploads',\n * region: 'us-east-1',\n * provider: 's3',\n * versioning: true,\n * accessControl: {\n * acl: 'private',\n * corsEnabled: true,\n * allowedOrigins: ['https://app.example.com']\n * },\n * multipartConfig: {\n * enabled: true,\n * threshold: 104857600\n * }\n * }\n */\nexport const BucketConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Bucket identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n bucketName: z.string().describe('Actual bucket/container name in storage provider'),\n region: z.string().optional().describe('Storage region (e.g., us-east-1, westus)'),\n provider: StorageProviderSchema.describe('Storage provider'),\n endpoint: z.string().optional().describe('Custom endpoint URL (for S3-compatible providers)'),\n pathStyle: z.boolean().default(false).describe('Use path-style URLs (for S3-compatible providers)'),\n \n versioning: z.boolean().default(false).describe('Enable object versioning'),\n encryption: z.object({\n enabled: z.boolean().default(false).describe('Enable server-side encryption'),\n algorithm: z.enum(['AES256', 'aws:kms', 'azure:kms', 'gcp:kms']).default('AES256').describe('Encryption algorithm'),\n kmsKeyId: z.string().optional().describe('KMS key ID for managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n \n accessControl: AccessControlConfigSchema.optional().describe('Access control configuration'),\n lifecyclePolicy: LifecyclePolicyConfigSchema.optional().describe('Lifecycle policy configuration'),\n multipartConfig: MultipartUploadConfigSchema.optional().describe('Multipart upload configuration'),\n \n tags: z.record(z.string(), z.string()).optional().describe('Bucket tags for organization'),\n description: z.string().optional().describe('Bucket description'),\n enabled: z.boolean().default(true).describe('Enable this bucket'),\n});\n\nexport type BucketConfig = z.infer;\n\n/**\n * Storage Connection Configuration\n * \n * Provider-specific connection credentials and settings.\n * \n * @example S3\n * {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * sessionToken: '${AWS_SESSION_TOKEN}',\n * region: 'us-east-1'\n * }\n * \n * @example Azure\n * {\n * accountName: 'mystorageaccount',\n * accountKey: '${AZURE_STORAGE_KEY}',\n * endpoint: 'https://mystorageaccount.blob.core.windows.net'\n * }\n */\nexport const StorageConnectionSchema = z.object({\n // AWS S3 / MinIO\n accessKeyId: z.string().optional().describe('AWS access key ID or MinIO access key'),\n secretAccessKey: z.string().optional().describe('AWS secret access key or MinIO secret key'),\n sessionToken: z.string().optional().describe('AWS session token for temporary credentials'),\n \n // Azure Blob Storage\n accountName: z.string().optional().describe('Azure storage account name'),\n accountKey: z.string().optional().describe('Azure storage account key'),\n sasToken: z.string().optional().describe('Azure SAS token'),\n \n // Google Cloud Storage\n projectId: z.string().optional().describe('GCP project ID'),\n credentials: z.string().optional().describe('GCP service account credentials JSON'),\n \n // Common\n endpoint: z.string().optional().describe('Custom endpoint URL'),\n region: z.string().optional().describe('Default region'),\n useSSL: z.boolean().default(true).describe('Use SSL/TLS for connections'),\n timeout: z.number().min(0).optional().describe('Connection timeout in milliseconds'),\n});\n\nexport type StorageConnection = z.infer;\n\n/**\n * Object Storage Configuration\n * \n * Complete object storage system configuration.\n * \n * @example\n * {\n * name: 'production_storage',\n * label: 'Production File Storage',\n * provider: 's3',\n * scope: 'global',\n * connection: {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * region: 'us-east-1'\n * },\n * buckets: [\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'prod-uploads',\n * provider: 's3',\n * region: 'us-east-1'\n * }\n * ],\n * defaultBucket: 'user_uploads'\n * }\n */\nexport const ObjectStorageConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Storage configuration identifier'),\n label: z.string().describe('Display label'),\n provider: StorageProviderSchema.describe('Primary storage provider'),\n \n /**\n * Storage scope\n * Defines the lifecycle and access pattern for this storage\n */\n scope: StorageScopeSchema.optional().default('global').describe('Storage scope'),\n \n connection: StorageConnectionSchema.describe('Connection credentials'),\n buckets: z.array(BucketConfigSchema).default([]).describe('Configured buckets'),\n defaultBucket: z.string().optional().describe('Default bucket name for operations'),\n \n /**\n * Base path or location\n * For local/scoped storage configurations\n */\n location: z.string().optional().describe('Root path (local) or base location'),\n \n /**\n * Storage quota in bytes\n */\n quota: z.number().int().positive().optional().describe('Max size in bytes'),\n \n /**\n * Provider-specific options\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Provider-specific configuration options'),\n \n enabled: z.boolean().default(true).describe('Enable this storage configuration'),\n description: z.string().optional().describe('Configuration description'),\n});\n\nexport type ObjectStorageConfig = z.infer;\n\n// ============================================================================\n// Helper Examples\n// ============================================================================\n\n/**\n * Example: AWS S3 Configuration\n */\nexport const s3StorageExample = ObjectStorageConfigSchema.parse({\n name: 'aws_s3_storage',\n label: 'AWS S3 Production Storage',\n provider: 's3',\n connection: {\n accessKeyId: '${AWS_ACCESS_KEY_ID}',\n secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n region: 'us-east-1',\n },\n buckets: [\n {\n name: 'user_uploads',\n label: 'User Uploads',\n bucketName: 'my-app-user-uploads',\n region: 'us-east-1',\n provider: 's3',\n versioning: true,\n encryption: {\n enabled: true,\n algorithm: 'aws:kms',\n kmsKeyId: '${AWS_KMS_KEY_ID}',\n },\n accessControl: {\n acl: 'private',\n corsEnabled: true,\n allowedOrigins: ['https://app.example.com'],\n allowedMethods: ['GET', 'PUT', 'POST'],\n },\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'archive_old_uploads',\n enabled: true,\n action: 'transition',\n daysAfterCreation: 90,\n targetStorageClass: 'glacier',\n },\n ],\n },\n multipartConfig: {\n enabled: true,\n partSize: 10 * 1024 * 1024,\n threshold: 100 * 1024 * 1024,\n maxConcurrent: 4,\n },\n },\n ],\n defaultBucket: 'user_uploads',\n enabled: true,\n});\n\n/**\n * Example: MinIO Configuration\n */\nexport const minioStorageExample = ObjectStorageConfigSchema.parse({\n name: 'minio_local',\n label: 'MinIO Local Storage',\n provider: 'minio',\n connection: {\n accessKeyId: 'minioadmin',\n secretAccessKey: 'minioadmin',\n endpoint: 'http://localhost:9000',\n useSSL: false,\n },\n buckets: [\n {\n name: 'development_files',\n label: 'Development Files',\n bucketName: 'dev-files',\n provider: 'minio',\n endpoint: 'http://localhost:9000',\n pathStyle: true,\n accessControl: {\n acl: 'private',\n },\n },\n ],\n defaultBucket: 'development_files',\n enabled: true,\n});\n\n/**\n * Example: Azure Blob Storage Configuration\n */\nexport const azureBlobStorageExample = ObjectStorageConfigSchema.parse({\n name: 'azure_blob_storage',\n label: 'Azure Blob Storage',\n provider: 'azure_blob',\n connection: {\n accountName: 'mystorageaccount',\n accountKey: '${AZURE_STORAGE_KEY}',\n endpoint: 'https://mystorageaccount.blob.core.windows.net',\n },\n buckets: [\n {\n name: 'media_files',\n label: 'Media Files',\n bucketName: 'media',\n provider: 'azure_blob',\n region: 'eastus',\n accessControl: {\n acl: 'public_read',\n publicAccess: {\n allowPublicRead: true,\n allowPublicWrite: false,\n allowPublicList: false,\n },\n },\n },\n ],\n defaultBucket: 'media_files',\n enabled: true,\n});\n\n/**\n * Example: Google Cloud Storage Configuration\n */\nexport const gcsStorageExample = ObjectStorageConfigSchema.parse({\n name: 'gcs_storage',\n label: 'Google Cloud Storage',\n provider: 'gcs',\n connection: {\n projectId: 'my-gcp-project',\n credentials: '${GCP_SERVICE_ACCOUNT_JSON}',\n },\n buckets: [\n {\n name: 'backup_storage',\n label: 'Backup Storage',\n bucketName: 'my-app-backups',\n region: 'us-central1',\n provider: 'gcs',\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'delete_old_backups',\n enabled: true,\n action: 'delete',\n daysAfterCreation: 30,\n },\n ],\n },\n },\n ],\n defaultBucket: 'backup_storage',\n enabled: true,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { FileMetadataSchema } from '../system/object-storage.zod';\n\n/**\n * Storage Service Protocol\n * \n * Defines the API contract for client-side file operations.\n * Focuses on secure, direct-to-cloud uploads (Presigned URLs)\n * rather than proxying bytes through the API server.\n */\n\n// ==========================================\n// Requests\n// ==========================================\n\nexport const GetPresignedUrlRequestSchema = z.object({\n filename: z.string().describe('Original filename'),\n mimeType: z.string().describe('File MIME type'),\n size: z.number().describe('File size in bytes'),\n scope: z.string().default('user').describe('Target storage scope (e.g. user, private, public)'),\n bucket: z.string().optional().describe('Specific bucket override (admin only)'),\n});\n\nexport const CompleteUploadRequestSchema = z.object({\n fileId: z.string().describe('File ID returned from presigned request'),\n eTag: z.string().optional().describe('S3 ETag verification'),\n});\n\n// ==========================================\n// Responses\n// ==========================================\n\nexport const PresignedUrlResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadUrl: z.string().describe('PUT/POST URL for direct upload'),\n downloadUrl: z.string().optional().describe('Public/Private preview URL'),\n fileId: z.string().describe('Temporary File ID'),\n method: z.enum(['PUT', 'POST']).describe('HTTP Method to use'),\n headers: z.record(z.string(), z.string()).optional().describe('Required headers for upload'),\n expiresIn: z.number().describe('URL expiry in seconds'),\n }),\n});\n\nexport const FileUploadResponseSchema = BaseResponseSchema.extend({\n data: FileMetadataSchema.describe('Uploaded file metadata'),\n});\n\nexport type GetPresignedUrlRequest = z.infer;\nexport type CompleteUploadRequest = z.infer;\nexport type PresignedUrlResponse = z.infer;\nexport type FileUploadResponse = z.infer;\n\n// ==========================================\n// Chunked / Resumable Upload Protocol\n// ==========================================\n\n/**\n * File Type Validation Schema\n * Configures allowed and blocked file types for upload endpoints.\n *\n * @example Allow images only\n * { mode: 'whitelist', mimeTypes: ['image/jpeg', 'image/png', 'image/webp'], maxFileSize: 10485760 }\n */\nexport const FileTypeValidationSchema = z.object({\n mode: z.enum(['whitelist', 'blacklist'])\n .describe('whitelist = only allow listed types, blacklist = block listed types'),\n mimeTypes: z.array(z.string()).min(1)\n .describe('List of MIME types to allow or block (e.g., \"image/jpeg\", \"application/pdf\")'),\n extensions: z.array(z.string()).optional()\n .describe('List of file extensions to allow or block (e.g., \".jpg\", \".pdf\")'),\n maxFileSize: z.number().int().min(1).optional()\n .describe('Maximum file size in bytes'),\n minFileSize: z.number().int().min(0).optional()\n .describe('Minimum file size in bytes (e.g., reject empty files)'),\n});\nexport type FileTypeValidation = z.infer;\n\n/**\n * Initiate Chunked Upload Request\n * Starts a resumable multipart upload session.\n *\n * @example POST /api/v1/storage/upload/chunked\n * { filename: 'large-video.mp4', mimeType: 'video/mp4', totalSize: 1073741824, chunkSize: 5242880 }\n */\nexport const InitiateChunkedUploadRequestSchema = z.object({\n filename: z.string().describe('Original filename'),\n mimeType: z.string().describe('File MIME type'),\n totalSize: z.number().int().min(1).describe('Total file size in bytes'),\n chunkSize: z.number().int().min(5242880).default(5242880)\n .describe('Size of each chunk in bytes (minimum 5MB per S3 spec)'),\n scope: z.string().default('user').describe('Target storage scope'),\n bucket: z.string().optional().describe('Specific bucket override (admin only)'),\n metadata: z.record(z.string(), z.string()).optional().describe('Custom metadata key-value pairs'),\n});\nexport type InitiateChunkedUploadRequest = z.infer;\n\n/**\n * Initiate Chunked Upload Response\n * Returns a resume token and upload session details.\n */\nexport const InitiateChunkedUploadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n resumeToken: z.string().describe('Opaque token for resuming interrupted uploads'),\n fileId: z.string().describe('Assigned file ID'),\n totalChunks: z.number().int().min(1).describe('Expected number of chunks'),\n chunkSize: z.number().int().describe('Chunk size in bytes'),\n expiresAt: z.string().datetime().describe('Upload session expiration timestamp'),\n }),\n});\nexport type InitiateChunkedUploadResponse = z.infer;\n\n/**\n * Upload Chunk Request\n * Uploads a single chunk of a multipart upload.\n *\n * @example PUT /api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex\n */\nexport const UploadChunkRequestSchema = z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n chunkIndex: z.number().int().min(0).describe('Zero-based chunk index'),\n resumeToken: z.string().describe('Resume token from initiate response'),\n});\nexport type UploadChunkRequest = z.infer;\n\n/**\n * Upload Chunk Response\n * Confirms a single chunk upload with ETag for assembly.\n */\nexport const UploadChunkResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n chunkIndex: z.number().int().describe('Chunk index that was uploaded'),\n eTag: z.string().describe('Chunk ETag for multipart completion'),\n bytesReceived: z.number().int().describe('Bytes received for this chunk'),\n }),\n});\nexport type UploadChunkResponse = z.infer;\n\n/**\n * Complete Chunked Upload Request\n * Assembles all uploaded chunks into a final file.\n *\n * @example POST /api/v1/storage/upload/chunked/:uploadId/complete\n */\nexport const CompleteChunkedUploadRequestSchema = z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n parts: z.array(z.object({\n chunkIndex: z.number().int().describe('Chunk index'),\n eTag: z.string().describe('ETag returned from chunk upload'),\n })).min(1).describe('Ordered list of uploaded parts for assembly'),\n});\nexport type CompleteChunkedUploadRequest = z.infer;\n\n/**\n * Complete Chunked Upload Response\n * Confirms that all chunks have been assembled into the final file.\n */\nexport const CompleteChunkedUploadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n fileId: z.string().describe('Final file ID'),\n key: z.string().describe('Storage key/path of the assembled file'),\n size: z.number().int().describe('Total file size in bytes'),\n mimeType: z.string().describe('File MIME type'),\n eTag: z.string().optional().describe('Final ETag of the assembled file'),\n url: z.string().optional().describe('Download URL for the assembled file'),\n }),\n});\nexport type CompleteChunkedUploadResponse = z.infer;\n\n/**\n * Upload Progress Schema\n * Represents the current progress of an active upload session.\n *\n * @example GET /api/v1/storage/upload/chunked/:uploadId/progress\n */\nexport const UploadProgressSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n fileId: z.string().describe('Assigned file ID'),\n filename: z.string().describe('Original filename'),\n totalSize: z.number().int().describe('Total file size in bytes'),\n uploadedSize: z.number().int().describe('Bytes uploaded so far'),\n totalChunks: z.number().int().describe('Total expected chunks'),\n uploadedChunks: z.number().int().describe('Number of chunks uploaded'),\n percentComplete: z.number().min(0).max(100).describe('Upload progress percentage'),\n status: z.enum(['in_progress', 'completing', 'completed', 'failed', 'expired'])\n .describe('Current upload session status'),\n startedAt: z.string().datetime().describe('Upload session start timestamp'),\n expiresAt: z.string().datetime().describe('Session expiration timestamp'),\n }),\n});\nexport type UploadProgress = z.infer;\n\n// ==========================================\n// Storage API Contract Registry\n// ==========================================\n\n/**\n * Standard Storage API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const StorageApiContracts = {\n getPresignedUrl: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/presigned',\n input: GetPresignedUrlRequestSchema,\n output: PresignedUrlResponseSchema,\n },\n completeUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/complete',\n input: CompleteUploadRequestSchema,\n output: FileUploadResponseSchema,\n },\n initiateChunkedUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/chunked',\n input: InitiateChunkedUploadRequestSchema,\n output: InitiateChunkedUploadResponseSchema,\n },\n uploadChunk: {\n method: 'PUT' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex',\n input: UploadChunkRequestSchema,\n output: UploadChunkResponseSchema,\n },\n completeChunkedUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/complete',\n input: CompleteChunkedUploadRequestSchema,\n output: CompleteChunkedUploadResponseSchema,\n },\n getUploadProgress: {\n method: 'GET' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/progress',\n output: UploadProgressSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # ObjectStack Validation Protocol\n * \n * This module defines the validation schema protocol for ObjectStack, providing a comprehensive\n * type-safe validation system similar to Salesforce's validation rules but with enhanced capabilities.\n * \n * ## Overview\n * \n * Validation rules are applied at the data layer to ensure data integrity and enforce business logic.\n * The system supports multiple validation types:\n * \n * 1. **Script Validation**: Formula-based validation using expressions\n * 2. **Uniqueness Validation**: Enforce unique constraints across fields\n * 3. **State Machine Validation**: Control allowed state transitions\n * 4. **Format Validation**: Validate field formats (email, URL, regex, etc.)\n * 5. **Cross-Field Validation**: Validate relationships between multiple fields\n * 6. **Async Validation**: Remote validation via API calls\n * 7. **Custom Validation**: User-defined validation functions\n * 8. **Conditional Validation**: Apply validations based on conditions\n * \n * ## Salesforce Comparison\n * \n * ObjectStack validation rules are inspired by Salesforce validation rules but enhanced:\n * - Salesforce: Formula-based validation with `Error Condition Formula`\n * - ObjectStack: Multiple validation types with composable rules\n * \n * Example Salesforce validation rule:\n * ```\n * Rule Name: Discount_Cannot_Exceed_40_Percent\n * Error Condition Formula: Discount_Percent__c > 0.40\n * Error Message: Discount cannot exceed 40%.\n * ```\n * \n * Equivalent ObjectStack rule:\n * ```typescript\n * {\n * type: 'script',\n * name: 'discount_cannot_exceed_40_percent',\n * condition: 'discount_percent > 0.40',\n * message: 'Discount cannot exceed 40%',\n * severity: 'error'\n * }\n * ```\n */\n\n/**\n * Base Validation Rule\n * \n * All validation rules extend from this base schema with common properties.\n * \n * ## Industry Standard Enhancements\n * - **Label/Description**: Essential for governance in large systems with thousands of rules.\n * - **Events**: granular control over validation timing (Context-aware validation).\n * - **Tags**: categorization for reporting and management.\n */\nconst BaseValidationSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label for the rule listing'),\n description: z.string().optional().describe('Administrative notes explaining the business reason'),\n \n // Execution Control\n active: z.boolean().default(true),\n events: z.array(z.enum(['insert', 'update', 'delete'])).default(['insert', 'update']).describe('Validation contexts'),\n priority: z.number().int().min(0).max(9999).default(100).describe('Execution priority (lower runs first, default: 100)'),\n \n // Classification\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g., \"compliance\", \"billing\")'),\n \n // Feedback\n severity: z.enum(['error', 'warning', 'info']).default('error'),\n message: z.string().describe('Error message to display to the user'),\n});\n\n/**\n * 1. Script/Expression Validation\n * Generic formula-based validation.\n */\nexport const ScriptValidationSchema = BaseValidationSchema.extend({\n type: z.literal('script'),\n condition: z.string().describe('Formula expression. If TRUE, validation fails. (e.g. amount < 0)'),\n});\n\n/**\n * 2. Uniqueness Validation\n * specialized optimized check for unique constraints.\n */\nexport const UniquenessValidationSchema = BaseValidationSchema.extend({\n type: z.literal('unique'),\n fields: z.array(z.string()).describe('Fields that must be combined unique'),\n scope: z.string().optional().describe('Formula condition for scope (e.g. active = true)'),\n caseSensitive: z.boolean().default(true),\n});\n\n/**\n * 3. State Machine Validation\n * State transition logic.\n */\nexport const StateMachineValidationSchema = BaseValidationSchema.extend({\n type: z.literal('state_machine'),\n field: z.string().describe('State field (e.g. status)'),\n transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'),\n});\n\n/**\n * 4. Value Format Validation\n * Regex or specialized formats.\n */\nexport const FormatValidationSchema = BaseValidationSchema.extend({\n type: z.literal('format'),\n field: z.string(),\n regex: z.string().optional(),\n format: z.enum(['email', 'url', 'phone', 'json']).optional(),\n});\n\n/**\n * 5. Cross-Field Validation\n * Validates relationships between multiple fields.\n * \n * ## Use Cases\n * - Date range validations (end_date > start_date)\n * - Amount comparisons (discount < total)\n * - Complex business rules involving multiple fields\n * \n * ## Salesforce Examples\n * \n * ### Example 1: Close Date Must Be In Current or Future Month\n * **Salesforce Formula:**\n * ```\n * MONTH(CloseDate) < MONTH(TODAY()) ||\n * YEAR(CloseDate) < YEAR(TODAY())\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'close_date_future',\n * condition: 'MONTH(close_date) >= MONTH(TODAY()) AND YEAR(close_date) >= YEAR(TODAY())',\n * fields: ['close_date'],\n * message: 'Close Date must be in the current or a future month'\n * }\n * ```\n * \n * ### Example 2: Discount Validation\n * **Salesforce Formula:**\n * ```\n * Discount__c > (Amount__c * 0.40)\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'discount_limit',\n * condition: 'discount > (amount * 0.40)',\n * fields: ['discount', 'amount'],\n * message: 'Discount cannot exceed 40% of the amount'\n * }\n * ```\n * \n * ### Example 3: Opportunity Must Have Products\n * **Salesforce Formula:**\n * ```\n * ISBLANK(Products__c) && ISPICKVAL(StageName, \"Closed Won\")\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'products_required_for_won',\n * condition: 'products = null AND stage = \"closed_won\"',\n * fields: ['products', 'stage'],\n * message: 'Opportunity must have products to be marked as Closed Won'\n * }\n * ```\n */\nexport const CrossFieldValidationSchema = BaseValidationSchema.extend({\n type: z.literal('cross_field'),\n condition: z.string().describe('Formula expression comparing fields (e.g. \"end_date > start_date\")'),\n fields: z.array(z.string()).describe('Fields involved in the validation'),\n});\n\n/**\n * 6. JSON Structure Validation\n * Validates JSON fields against a JSON Schema.\n * \n * ## Use Cases\n * - Validating configuration objects stored in JSON fields\n * - Enforcing API payload structures\n * - Complex nested data validation\n */\nexport const JSONValidationSchema = BaseValidationSchema.extend({\n type: z.literal('json_schema'),\n field: z.string().describe('JSON field to validate'),\n schema: z.record(z.string(), z.unknown()).describe('JSON Schema object definition'),\n});\n\n/**\n * 7. Async Validation\n * Remote validation via API call or database query.\n * \n * ## Use Cases\n * \n * ### 1. Email Uniqueness Check\n * Check if an email address is already registered in the system.\n * ```typescript\n * {\n * type: 'async',\n * name: 'unique_email',\n * field: 'email',\n * validatorUrl: '/api/users/check-email',\n * message: 'This email address is already registered',\n * debounce: 500, // Wait 500ms after user stops typing\n * timeout: 3000\n * }\n * ```\n * \n * ### 2. Username Availability\n * Verify username is available before form submission.\n * ```typescript\n * {\n * type: 'async',\n * name: 'username_available',\n * field: 'username',\n * validatorUrl: '/api/users/check-username',\n * message: 'This username is already taken',\n * debounce: 300,\n * timeout: 2000\n * }\n * ```\n * \n * ### 3. Tax ID Validation\n * Validate tax ID with government API (e.g., IRS, HMRC).\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_tax_id',\n * field: 'tax_id',\n * validatorFunction: 'validateTaxIdWithIRS',\n * message: 'Invalid Tax ID number',\n * timeout: 10000, // Government APIs may be slow\n * params: { country: 'US', format: 'EIN' }\n * }\n * ```\n * \n * ### 4. Credit Card Validation\n * Verify credit card with payment gateway without charging.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_card',\n * field: 'card_number',\n * validatorUrl: 'https://api.stripe.com/v1/tokens/validate',\n * message: 'Invalid credit card number',\n * timeout: 5000,\n * params: { \n * mode: 'validate_only',\n * checkFunds: false \n * }\n * }\n * ```\n * \n * ### 5. Address Validation\n * Validate and standardize addresses using geocoding services.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_address',\n * field: 'street_address',\n * validatorFunction: 'validateAddressWithGoogleMaps',\n * message: 'Unable to verify address',\n * timeout: 4000,\n * params: {\n * includeFields: ['city', 'state', 'zip'],\n * strictMode: true,\n * country: 'US'\n * }\n * }\n * ```\n * \n * ### 6. Domain Name Availability\n * Check if domain name is available for registration.\n * ```typescript\n * {\n * type: 'async',\n * name: 'domain_available',\n * field: 'domain_name',\n * validatorUrl: '/api/domains/check-availability',\n * message: 'This domain is already taken or reserved',\n * debounce: 500,\n * timeout: 2000\n * }\n * ```\n * \n * ### 7. Coupon Code Validation\n * Verify coupon code is valid and not expired.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_coupon',\n * field: 'coupon_code',\n * validatorUrl: '/api/coupons/validate',\n * message: 'Invalid or expired coupon code',\n * timeout: 2000,\n * params: {\n * checkExpiration: true,\n * checkUsageLimit: true,\n * userId: '{{current_user_id}}'\n * }\n * }\n * ```\n */\nexport const AsyncValidationSchema = BaseValidationSchema.extend({\n type: z.literal('async'),\n field: z.string().describe('Field to validate'),\n validatorUrl: z.string().optional().describe('External API endpoint for validation'),\n method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method for external call'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for the request'),\n validatorFunction: z.string().optional().describe('Reference to custom validator function'),\n timeout: z.number().optional().default(5000).describe('Timeout in milliseconds'),\n debounce: z.number().optional().describe('Debounce delay in milliseconds'),\n params: z.record(z.string(), z.unknown()).optional().describe('Additional parameters to pass to validator'),\n});\n\n/**\n * 8. Custom Validator Function\n * User-defined validation logic with code reference.\n */\nexport const CustomValidatorSchema = BaseValidationSchema.extend({\n type: z.literal('custom'),\n handler: z.string().describe('Name of the custom validation function registered in the system'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the custom handler'),\n});\n\n/**\n * 9. Master Validation Rule Schema\n */\n/** Base type for validation rules - used for z.lazy() recursive type annotation */\nexport interface BaseValidationRuleShape {\n type: string;\n name: string;\n message: string;\n label?: string;\n description?: string;\n active?: boolean;\n events?: ('insert' | 'update' | 'delete')[];\n priority?: number;\n tags?: string[];\n severity?: 'error' | 'warning' | 'info';\n [key: string]: unknown;\n}\n\nexport const ValidationRuleSchema: z.ZodType = z.lazy(() =>\n z.discriminatedUnion('type', [\n ScriptValidationSchema,\n UniquenessValidationSchema,\n StateMachineValidationSchema,\n FormatValidationSchema,\n CrossFieldValidationSchema,\n JSONValidationSchema,\n AsyncValidationSchema,\n CustomValidatorSchema,\n ConditionalValidationSchema,\n ])\n);\n\n/**\n * 8. Conditional Validation\n * Validation that only applies when a condition is met.\n * \n * ## Overview\n * Conditional validations follow the pattern: \"Validate X only if Y is true\"\n * This allows for context-aware validation rules that adapt to different scenarios.\n * \n * ## Use Cases\n * \n * ### 1. Validate Based on Record Type\n * Apply different validation rules based on the type of record.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_approval_required',\n * when: 'account_type = \"enterprise\"',\n * message: 'Enterprise validation',\n * then: {\n * type: 'script',\n * name: 'require_approval',\n * message: 'Enterprise accounts require manager approval',\n * condition: 'approval_status = null'\n * }\n * }\n * ```\n * \n * ### 2. Conditional Field Requirements\n * Require certain fields only when specific conditions are met.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'shipping_address_when_required',\n * when: 'requires_shipping = true',\n * message: 'Shipping validation',\n * then: {\n * type: 'script',\n * name: 'shipping_address_required',\n * message: 'Shipping address is required for physical products',\n * condition: 'shipping_address = null OR shipping_address = \"\"'\n * }\n * }\n * ```\n * \n * ### 3. Amount-Based Validation\n * Apply different rules based on transaction amount.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'high_value_approval',\n * when: 'order_total > 10000',\n * message: 'High value order validation',\n * then: {\n * type: 'script',\n * name: 'manager_approval_required',\n * message: 'Orders over $10,000 require manager approval',\n * condition: 'manager_approval_id = null'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'standard_validation',\n * message: 'Payment method is required',\n * condition: 'payment_method = null'\n * }\n * }\n * ```\n * \n * ### 4. Regional Compliance\n * Apply region-specific validation rules.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'regional_compliance',\n * when: 'region = \"EU\"',\n * message: 'EU compliance validation',\n * then: {\n * type: 'script',\n * name: 'gdpr_consent',\n * message: 'GDPR consent is required for EU customers',\n * condition: 'gdpr_consent_given = false'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'tos_acceptance',\n * message: 'Terms of Service acceptance required',\n * condition: 'tos_accepted = false'\n * }\n * }\n * ```\n * \n * ### 5. Nested Conditional Validation\n * Create complex validation logic with nested conditions.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'country_state_validation',\n * when: 'country = \"US\"',\n * message: 'US-specific validation',\n * then: {\n * type: 'conditional',\n * name: 'california_validation',\n * when: 'state = \"CA\"',\n * message: 'California-specific validation',\n * then: {\n * type: 'script',\n * name: 'ca_tax_id_required',\n * message: 'California requires a valid tax ID',\n * condition: 'tax_id = null OR NOT(REGEX(tax_id, \"^\\\\d{2}-\\\\d{7}$\"))'\n * }\n * }\n * }\n * ```\n * \n * ### 6. Tax Validation for Taxable Items\n * Only validate tax fields when the item is taxable.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'tax_field_validation',\n * when: 'is_taxable = true',\n * message: 'Tax validation',\n * then: {\n * type: 'script',\n * name: 'tax_code_required',\n * message: 'Tax code is required for taxable items',\n * condition: 'tax_code = null OR tax_code = \"\"'\n * }\n * }\n * ```\n * \n * ### 7. Role-Based Validation\n * Apply validation based on user role.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'role_based_approval_limit',\n * when: 'user_role = \"manager\"',\n * message: 'Manager approval limits',\n * then: {\n * type: 'script',\n * name: 'manager_limit',\n * message: 'Managers can approve up to $50,000',\n * condition: 'approval_amount > 50000'\n * }\n * }\n * ```\n * \n * ## Salesforce Pattern Comparison\n * \n * Salesforce doesn't have explicit \"conditional validation\" rules but achieves similar\n * behavior using formula logic. ObjectStack makes this pattern explicit and composable.\n * \n * **Salesforce Approach:**\n * ```\n * IF(\n * ISPICKVAL(Type, \"Enterprise\"),\n * AND(Amount > 100000, ISBLANK(Approval__c)),\n * FALSE\n * )\n * ```\n * \n * **ObjectStack Approach:**\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_high_value',\n * when: 'type = \"enterprise\"',\n * then: {\n * type: 'cross_field',\n * name: 'amount_approval',\n * condition: 'amount > 100000 AND approval = null',\n * fields: ['amount', 'approval']\n * }\n * }\n * ```\n */\nexport const ConditionalValidationSchema = BaseValidationSchema.extend({\n type: z.literal('conditional'),\n when: z.string().describe('Condition formula (e.g. \"type = \\'enterprise\\'\")'),\n then: ValidationRuleSchema.describe('Validation rule to apply when condition is true'),\n otherwise: ValidationRuleSchema.optional().describe('Validation rule to apply when condition is false'),\n});\n\nexport type ValidationRule = z.infer;\nexport type ScriptValidation = z.infer;\nexport type UniquenessValidation = z.infer;\nexport type StateMachineValidation = z.infer;\nexport type FormatValidation = z.infer;\nexport type CrossFieldValidation = z.infer;\nexport type JSONValidation = z.infer;\nexport type AsyncValidation = z.infer;\nexport type CustomValidation = z.infer;\nexport type ConditionalValidation = z.infer;", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * XState-inspired State Machine Protocol\n * Used to define strict business logic constraints and lifecycle management.\n * Prevent AI \"hallucinations\" by enforcing valid valid transitions.\n */\n\n// --- Primitives ---\n\n/**\n * References a named action (side effect)\n * Can be a script, a webhook, or a field update.\n */\nexport const ActionRefSchema = z.union([\n z.string().describe('Action Name'),\n z.object({\n type: z.string(), // e.g., 'xstate.assign', 'log', 'email'\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n/**\n * References a named condition (guard)\n * Must evaluate to true for the transition to occur.\n */\nexport const GuardRefSchema = z.union([\n z.string().describe('Guard Name (e.g., \"isManager\", \"amountGT1000\")'),\n z.object({\n type: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n// --- Core Structure ---\n\n/**\n * State Transition Definition\n * \"When EVENT happens, if GUARD is true, go to TARGET and run ACTIONS\"\n */\nexport const TransitionSchema = z.object({\n target: z.string().optional().describe('Target State ID'),\n cond: GuardRefSchema.optional().describe('Condition (Guard) required to take this path'),\n actions: z.array(ActionRefSchema).optional().describe('Actions to execute during transition'),\n description: z.string().optional().describe('Human readable description of this rule'),\n});\n\n/**\n * Event Definition (Signals)\n */\nexport const EventSchema = z.object({\n type: z.string().describe('Event Type (e.g. \"APPROVE\", \"REJECT\", \"Submit\")'),\n // Payload validation schema could go here if we want deep validation\n schema: z.record(z.string(), z.unknown()).optional().describe('Expected event payload structure'),\n});\n\nexport type ActionRef = z.infer;\nexport type Transition = z.infer;\n\nexport type StateNodeConfig = {\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n entry?: ActionRef[];\n exit?: ActionRef[];\n on?: Record;\n always?: Transition[];\n initial?: string;\n states?: Record;\n meta?: {\n label?: string;\n description?: string;\n color?: string;\n aiInstructions?: string;\n };\n};\n\n/**\n * State Node Definition\n */\nexport const StateNodeSchema: z.ZodType = z.lazy(() => z.object({\n /** Type of state */\n type: z.enum(['atomic', 'compound', 'parallel', 'final', 'history']).default('atomic'),\n \n /** Entry/Exit Actions */\n entry: z.array(ActionRefSchema).optional().describe('Actions to run when entering this state'),\n exit: z.array(ActionRefSchema).optional().describe('Actions to run when leaving this state'),\n \n /** Transitions (Events) */\n on: z.record(z.string(), z.union([\n z.string(), // Shorthand target\n TransitionSchema, \n z.array(TransitionSchema)\n ])).optional().describe('Map of Event Type -> Transition Definition'),\n \n /** Always Transitions (Eventless) */\n always: z.array(TransitionSchema).optional(),\n\n /** Nesting (Hierarchical States) */\n initial: z.string().optional().describe('Initial child state (if compound)'),\n states: z.record(z.string(), StateNodeSchema).optional(),\n \n /** Metadata for UI/AI */\n meta: z.object({\n label: z.string().optional(),\n description: z.string().optional(),\n color: z.string().optional(), // For UI diagrams\n // Instructions for AI Agent when in this state\n aiInstructions: z.string().optional().describe('Specific instructions for AI when in this state'),\n }).optional(),\n}));\n\n/**\n * Top-Level State Machine Definition\n */\nexport const StateMachineSchema = z.object({\n id: SnakeCaseIdentifierSchema.describe('Unique Machine ID'),\n description: z.string().optional(),\n \n /** Context (Memory) Schema */\n contextSchema: z.record(z.string(), z.unknown()).optional().describe('Zod Schema for the machine context/memory'),\n \n /** Initial State */\n initial: z.string().describe('Initial State ID'),\n \n /** State Definitions */\n states: z.record(z.string(), StateNodeSchema).describe('State Nodes'),\n \n /** Global Listeners */\n on: z.record(z.string(), z.union([z.string(), TransitionSchema, z.array(TransitionSchema)])).optional(),\n});\n\nexport type StateMachineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from './field.zod';\nimport { ValidationRuleSchema } from './validation.zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\nimport { ActionSchema } from '../ui/action.zod';\n\n/**\n * API Operations Enum\n */\nexport const ApiMethod = z.enum([\n 'get', 'list', // Read\n 'create', 'update', 'delete', // Write\n 'upsert', // Idempotent Write\n 'bulk', // Batch operations\n 'aggregate', // Analytics (count, sum)\n 'history', // Audit access\n 'search', // Search access\n 'restore', 'purge', // Trash management\n 'import', 'export', // Data portability\n]);\nexport type ApiMethod = z.infer;\n\n/**\n * Capability Flags\n * Defines what system features are enabled for this object.\n * \n * Optimized based on industry standards (Salesforce, ServiceNow):\n * - Added `activities` (Tasks/Events)\n * - Added `mru` (Recent Items)\n * - Added `feeds` (Social/Chatter)\n * - Grouped API permissions\n * \n * @example\n * {\n * trackHistory: true,\n * searchable: true,\n * apiEnabled: true,\n * files: true\n * }\n */\nexport const ObjectCapabilities = z.object({\n /** Enable history tracking (Audit Trail) */\n trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),\n \n /** Enable global search indexing */\n searchable: z.boolean().default(true).describe('Index records for global search'),\n \n /** Enable REST/GraphQL API access */\n apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),\n\n /** \n * API Supported Operations\n * Granular control over API exposure.\n */\n apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),\n \n /** Enable standard attachments/files engine */\n files: z.boolean().default(false).describe('Enable file attachments and document management'),\n \n /** Enable social collaboration (Comments, Mentions, Feeds) */\n feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),\n \n /** Enable standard Activity suite (Tasks, Calendars, Events) */\n activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),\n \n /** Enable Recycle Bin / Soft Delete */\n trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),\n\n /** Enable \"Recently Viewed\" tracking */\n mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),\n \n /** Allow cloning records */\n clone: z.boolean().default(true).describe('Allow record deep cloning'),\n});\n\n/**\n * Schema for database indexes.\n * Enhanced with additional index types and configuration options\n * \n * @example\n * {\n * name: \"idx_account_name\",\n * fields: [\"name\"],\n * type: \"btree\",\n * unique: true\n * }\n */\nexport const IndexSchema = z.object({\n name: z.string().optional().describe('Index name (auto-generated if not provided)'),\n fields: z.array(z.string()).describe('Fields included in the index'),\n type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),\n unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),\n partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),\n});\n\n/**\n * Search Configuration\n * Defines how this object behaves in search results.\n * \n * @example\n * {\n * fields: [\"name\", \"email\", \"phone\"],\n * displayFields: [\"name\", \"title\"],\n * filters: [\"status = 'active'\"]\n * }\n */\nexport const SearchConfigSchema = z.object({\n fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),\n displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),\n filters: z.array(z.string()).optional().describe('Default filters for search results'),\n});\n\n/**\n * Multi-Tenancy Configuration Schema\n * Configures tenant isolation strategy for SaaS applications\n * \n * @example Shared database with tenant_id isolation\n * {\n * enabled: true,\n * strategy: 'shared',\n * tenantField: 'tenant_id',\n * crossTenantAccess: false\n * }\n */\nexport const TenancyConfigSchema = z.object({\n enabled: z.boolean().describe('Enable multi-tenancy for this object'),\n strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),\n tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),\n crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),\n});\n\n/**\n * Soft Delete Configuration Schema\n * Implements recycle bin / trash functionality\n * \n * @example Standard soft delete with cascade\n * {\n * enabled: true,\n * field: 'deleted_at',\n * cascadeDelete: true\n * }\n */\nexport const SoftDeleteConfigSchema = z.object({\n enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),\n field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),\n cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),\n});\n\n/**\n * Versioning Configuration Schema\n * Implements record versioning and history tracking\n * \n * @example Snapshot versioning with 90-day retention\n * {\n * enabled: true,\n * strategy: 'snapshot',\n * retentionDays: 90,\n * versionField: 'version'\n * }\n */\nexport const VersioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable record versioning'),\n strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),\n retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),\n versionField: z.string().default('version').describe('Field name for version number/timestamp'),\n});\n\n/**\n * Partitioning Strategy Schema\n * Configures table partitioning for performance at scale\n * \n * @example Range partitioning by date (monthly)\n * {\n * enabled: true,\n * strategy: 'range',\n * key: 'created_at',\n * interval: '1 month'\n * }\n */\nexport const PartitioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable table partitioning'),\n strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),\n key: z.string().describe('Field name to partition by'),\n interval: z.string().optional().describe('Partition interval for range strategy (e.g., \"1 month\", \"1 year\")'),\n}).refine((data) => {\n // If strategy is 'range', interval must be provided\n if (data.strategy === 'range' && !data.interval) {\n return false;\n }\n return true;\n}, {\n message: 'interval is required when strategy is \"range\"',\n});\n\n/**\n * Change Data Capture (CDC) Configuration Schema\n * Enables real-time data streaming to external systems\n * \n * @example Stream all changes to Kafka\n * {\n * enabled: true,\n * events: ['insert', 'update', 'delete'],\n * destination: 'kafka://events.objectstack'\n * }\n */\nexport const CDCConfigSchema = z.object({\n enabled: z.boolean().describe('Enable Change Data Capture'),\n events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),\n destination: z.string().describe('Destination endpoint (e.g., \"kafka://topic\", \"webhook://url\")'),\n});\n\n/**\n * Base Object Schema Definition\n * \n * The Blueprint of a Business Object.\n * Represents a table, a collection, or a virtual entity.\n * \n * @example\n * ```yaml\n * name: project_task\n * label: Project Task\n * icon: task\n * fields:\n * project:\n * type: lookup\n * reference: project\n * status:\n * type: select\n * options: [todo, in_progress, done]\n * enable:\n * trackHistory: true\n * files: true\n * ```\n */\nconst ObjectSchemaBase = z.object({\n /** \n * Identity & Metadata \n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),\n label: z.string().optional().describe('Human readable singular label (e.g. \"Account\")'),\n pluralLabel: z.string().optional().describe('Human readable plural label (e.g. \"Accounts\")'),\n description: z.string().optional().describe('Developer documentation / description'),\n icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),\n \n /**\n * Namespace & Domain Classification\n * \n * Groups objects into logical domains for routing, permissions, and discovery.\n * System objects use `'sys'`; business packages use their own namespace.\n * \n * When set, `tableName` is auto-derived as `{namespace}_{name}` by\n * `ObjectSchema.create()` unless an explicit `tableName` is provided.\n * \n * Namespace must be a single lowercase word (no underscores or hyphens)\n * to ensure clean auto-derivation of `{namespace}_{name}` table names.\n * \n * @example namespace: 'sys' → tableName defaults to 'sys_user'\n * @example namespace: 'crm' → tableName defaults to 'crm_account'\n */\n namespace: z.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace — single lowercase word (e.g. \"sys\", \"crm\"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'),\n\n /**\n * Taxonomy & Organization\n */\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g. \"sales\", \"system\", \"reference\")'),\n active: z.boolean().optional().default(true).describe('Is the object active and usable'),\n isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),\n abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),\n\n /** \n * Storage & Virtualization \n */\n datasource: z.string().optional().default('default').describe('Target Datasource ID. \"default\" is the primary DB.'),\n tableName: z.string().optional().describe('Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set.'),\n \n /** \n * Data Model \n */\n fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {\n message: 'Field names must be lowercase snake_case (e.g., \"first_name\", \"company\", \"annual_revenue\")',\n }), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),\n indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),\n \n /**\n * Advanced Data Management\n */\n \n // Multi-tenancy configuration\n tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),\n \n // Soft delete configuration\n softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),\n \n // Versioning configuration\n versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),\n \n // Partitioning strategy\n partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),\n \n // Change Data Capture\n cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),\n \n /**\n * Logic & Validation (Co-located)\n * Best Practice: Define rules close to data.\n */\n validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),\n \n /**\n * State Machine(s)\n * Named record of state machines, where each key is a unique machine identifier.\n * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).\n * \n * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }\n */\n stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),\n\n /** \n * Display & UI Hints (Data-Layer)\n */\n displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., \"name\", \"title\"). Defaults to \"name\" if present.'),\n recordName: z.object({\n type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),\n displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., \"CASE-{0000}\", \"INV-{YYYY}-{0000}\")'),\n startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),\n }).optional().describe('Record name generation configuration (Salesforce pattern)'),\n titleFormat: z.string().optional().describe('Title expression (e.g. \"{name} - {code}\"). Overrides displayNameField.'),\n compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),\n \n /** \n * Search Engine Config \n */\n search: SearchConfigSchema.optional().describe('Search engine configuration'),\n \n /** \n * System Capabilities \n */\n enable: ObjectCapabilities.optional().describe('Enabled system features modules'),\n\n /** Record Types */\n recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),\n\n /** Sharing Model */\n sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),\n\n /** Key Prefix */\n keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., \"001\" for Account)'),\n\n /**\n * Object Actions\n * \n * Actions associated with this object. Populated automatically by `defineStack()`\n * when top-level actions specify `objectName` matching this object.\n * Can also be defined directly on the object.\n * \n * Aligns with Salesforce/ServiceNow patterns where actions are part of the\n * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)\n * include the action list without requiring downstream merge.\n */\n actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),\n});\n\n/**\n * Converts a snake_case name to a human-readable Title Case label.\n * @example snakeCaseToLabel('project_task') → 'Project Task'\n */\nfunction snakeCaseToLabel(name: string): string {\n return name\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n}\n\n/**\n * Enhanced ObjectSchema with Factory\n */\nexport const ObjectSchema = Object.assign(ObjectSchemaBase, {\n /**\n * Type-safe factory for creating business object definitions.\n * \n * Enhancements over raw schema:\n * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).\n * - **Validation**: Runs Zod `.parse()` to validate the config at creation time.\n * \n * @example\n * ```ts\n * const Task = ObjectSchema.create({\n * name: 'project_task',\n * // label auto-generated as 'Project Task'\n * fields: {\n * subject: { type: 'text', label: 'Subject', required: true },\n * },\n * });\n * ```\n */\n create: >(config: T): Omit & Pick => {\n const withDefaults = {\n ...config,\n label: config.label ?? snakeCaseToLabel(config.name),\n // Auto-derive tableName as {namespace}_{name} when namespace is set\n tableName: config.tableName ?? (config.namespace ? `${config.namespace}_${config.name}` : undefined),\n };\n return ObjectSchemaBase.parse(withDefaults) as Omit & Pick;\n },\n});\n\nexport type ServiceObject = z.infer;\nexport type ServiceObjectInput = z.input;\nexport type ObjectCapabilities = z.infer;\nexport type ObjectIndex = z.infer;\nexport type TenancyConfig = z.infer;\nexport type SoftDeleteConfig = z.infer;\nexport type VersioningConfig = z.infer;\nexport type PartitioningConfig = z.infer;\nexport type CDCConfig = z.infer;\n\n// =================================================================\n// Object Ownership Model\n// =================================================================\n\n/**\n * How a package relates to an object it references.\n * \n * - `own`: This package is the original author/owner of the object.\n * Only one package may own a given object name. The owner defines\n * the base schema (table name, primary key, core fields).\n * \n * - `extend`: This package adds fields, views, or actions to an\n * existing object owned by another package. Multiple packages\n * may extend the same object. Extensions are merged at boot time.\n * \n * Follows Salesforce/ServiceNow patterns:\n * object name = database table name, globally unique, no namespace prefix.\n */\nexport const ObjectOwnershipEnum = z.enum(['own', 'extend']);\nexport type ObjectOwnership = z.infer;\n\n/**\n * Object Extension Entry — used in `objectExtensions` array.\n * Declares fields/config to merge into an existing object owned by another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact', // target object FQN\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\nexport const ObjectExtensionSchema = z.object({\n /** The target object name (FQN) to extend */\n extend: z.string().describe('Target object name (FQN) to extend'),\n \n /** Fields to merge into the target object (additive) */\n fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),\n \n /** Override label */\n label: z.string().optional().describe('Override label for the extended object'),\n \n /** Override plural label */\n pluralLabel: z.string().optional().describe('Override plural label for the extended object'),\n \n /** Override description */\n description: z.string().optional().describe('Override description for the extended object'),\n \n /** Additional validation rules to add */\n validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),\n \n /** Additional indexes to add */\n indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),\n \n /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */\n priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),\n});\n\nexport type ObjectExtension = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema, EmbedConfigSchema } from './sharing.zod';\n\n/**\n * Base Navigation Item Schema\n * Shared properties for all navigation types.\n * \n * **NAMING CONVENTION:**\n * Navigation item IDs are used in URLs and configuration and must be lowercase snake_case.\n * \n * @example Good IDs\n * - 'menu_accounts'\n * - 'page_dashboard'\n * - 'nav_settings'\n * \n * @example Bad IDs (will be rejected)\n * - 'MenuAccounts' (PascalCase)\n * - 'Page Dashboard' (spaces)\n */\nconst BaseNavItemSchema = z.object({\n /** Unique identifier for the item */\n id: SnakeCaseIdentifierSchema.describe('Unique identifier for this navigation item (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display proper label'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Sort order within the same level (lower numbers appear first) */\n order: z.number().optional().describe('Sort order within the same level (lower = first)'),\n\n /** Badge text or count displayed on the navigation item (e.g. \"3\", \"New\") */\n badge: z.union([z.string(), z.number()]).optional().describe('Badge text or count displayed on the item'),\n\n /** \n * Visibility condition. \n * Formula expression returning boolean. \n * e.g. \"user.is_admin || user.department == 'sales'\"\n */\n visible: z.string().optional().describe('Visibility formula condition'),\n\n /** Permissions required to see/access this navigation item */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this item'),\n});\n\n/**\n * 1. Object Navigation Item\n * Navigates to an object's list view.\n */\nexport const ObjectNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('object'),\n objectName: z.string().describe('Target object name'),\n viewName: z.string().optional().describe('Default list view to open. Defaults to \"all\"'),\n});\n\n/**\n * 2. Dashboard Navigation Item\n * Navigates to a specific dashboard.\n */\nexport const DashboardNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('dashboard'),\n dashboardName: z.string().describe('Target dashboard name'),\n});\n\n/**\n * 3. Page Navigation Item\n * Navigates to a custom UI page/component.\n */\nexport const PageNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('page'),\n pageName: z.string().describe('Target custom page component name'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the page context'),\n});\n\n/**\n * 4. URL Navigation Item\n * Navigates to an external or absolute URL.\n */\nexport const UrlNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('url'),\n url: z.string().describe('Target external URL'),\n target: z.enum(['_self', '_blank']).default('_self').describe('Link target window'),\n});\n\n/**\n * 5. Report Navigation Item\n * Navigates to a specific report.\n */\nexport const ReportNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('report'),\n reportName: z.string().describe('Target report name'),\n});\n\n/**\n * 6. Action Navigation Item\n * Triggers an action (e.g. opening a flow, running a script, or launching a screen action).\n */\nexport const ActionNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('action'),\n actionDef: z.object({\n actionName: z.string().describe('Action machine name to execute'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the action'),\n }).describe('Action definition to execute when clicked'),\n});\n\n/**\n * 7. Group Navigation Item\n * A container for child navigation items (Sub-menu).\n * Does not perform navigation itself.\n */\nexport const GroupNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('group'),\n expanded: z.boolean().default(false).describe('Default expansion state in sidebar'),\n // children property is added in the recursive definition below\n});\n\n/**\n * Recursive Union of all navigation item types.\n * Allows constructing an unlimited-depth navigation tree.\n */\nexport const NavigationItemSchema: z.ZodType = z.lazy(() => \n z.union([\n ObjectNavItemSchema.extend({\n children: z.array(NavigationItemSchema).optional().describe('Child navigation items (e.g. specific views)'),\n }),\n DashboardNavItemSchema,\n PageNavItemSchema,\n UrlNavItemSchema,\n ReportNavItemSchema,\n ActionNavItemSchema,\n GroupNavItemSchema.extend({\n children: z.array(NavigationItemSchema).describe('Child navigation items'),\n })\n ])\n);\n\n/**\n * App Branding Configuration\n * Allows configuring the look and feel of the specific app.\n */\nexport const AppBrandingSchema = z.object({\n primaryColor: z.string().optional().describe('Primary theme color hex code'),\n logo: z.string().optional().describe('Custom logo URL for this app'),\n favicon: z.string().optional().describe('Custom favicon URL for this app'),\n});\n\n/**\n * Navigation Area Schema\n * \n * A logical grouping (zone/section) of navigation items, similar to Salesforce \"App Areas\"\n * or Dynamics 365 \"Site Map Areas\". Each area represents a business domain (e.g. Sales, Service, Settings)\n * and contains its own independent navigation tree.\n * \n * Areas allow large applications to partition navigation by business function while\n * keeping a single AppSchema definition. The runtime may render areas as top-level tabs,\n * sidebar sections, or a switchable navigation context.\n * \n * @example\n * ```ts\n * const salesArea: NavigationArea = {\n * id: 'area_sales',\n * label: 'Sales',\n * icon: 'briefcase',\n * order: 1,\n * navigation: [\n * { id: 'nav_leads', type: 'object', label: 'Leads', objectName: 'lead' },\n * { id: 'nav_opportunities', type: 'object', label: 'Opportunities', objectName: 'opportunity' },\n * ],\n * };\n * ```\n */\nexport const NavigationAreaSchema = z.object({\n /** Unique area identifier */\n id: SnakeCaseIdentifierSchema.describe('Unique area identifier (lowercase snake_case)'),\n\n /** Display label */\n label: I18nLabelSchema.describe('Area display label'),\n\n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Area icon name'),\n\n /** Sort order among areas (lower = first) */\n order: z.number().optional().describe('Sort order among areas (lower = first)'),\n\n /** Area description */\n description: I18nLabelSchema.optional().describe('Area description'),\n\n /** \n * Visibility condition.\n * Formula expression returning boolean.\n */\n visible: z.string().optional().describe('Visibility formula condition for this area'),\n\n /** Permissions required to access this area */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this area'),\n\n /** Navigation items within this area */\n navigation: z.array(NavigationItemSchema).describe('Navigation items within this area'),\n});\n\n/**\n * Schema for Applications (Apps).\n * A logical container for business functionality (e.g., \"Sales CRM\", \"HR Portal\").\n * \n * **NAMING CONVENTION:**\n * App names are used in URLs and routing and must be lowercase snake_case.\n * Prefix with 'app_' is recommended for clarity.\n * \n * @example Good app names\n * - 'app_crm'\n * - 'app_finance'\n * - 'app_portal'\n * - 'sales_app'\n * \n * @example Bad app names (will be rejected)\n * - 'CRM' (uppercase)\n * - 'FinanceApp' (mixed case)\n * - 'Sales App' (spaces)\n */\n/**\n * App Configuration Schema\n * Defines a business application container, including its navigation, branding, and permissions.\n * \n * The App is the top-level navigation shell. The `navigation[]` field holds the complete\n * sidebar tree with unlimited nesting depth via `type: 'group'` items. Pages are referenced\n * by name via `type: 'page'` items and defined independently.\n * \n * @example CRM App with nested navigation tree\n * {\n * name: \"crm\",\n * label: \"Sales CRM\",\n * icon: \"briefcase\",\n * navigation: [\n * { type: \"group\", id: \"grp_sales\", label: \"Sales Cloud\", expanded: true, children: [\n * { type: \"page\", id: \"nav_pipeline\", label: \"Pipeline\", pageName: \"page_pipeline\" },\n * { type: \"page\", id: \"nav_accounts\", label: \"Accounts\", pageName: \"page_accounts\" },\n * ]},\n * { type: \"page\", id: \"nav_settings\", label: \"Settings\", pageName: \"admin_settings\" },\n * ]\n * }\n */\nexport const AppSchema = z.object({\n /** Machine name (id) */\n name: SnakeCaseIdentifierSchema.describe('App unique machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('App display label'),\n\n /** App version */\n version: z.string().optional().describe('App version'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('App description'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('App icon used in the App Launcher'),\n \n /** Branding/Theming Configuration */\n branding: AppBrandingSchema.optional().describe('App-specific branding'),\n \n /** Application status */\n active: z.boolean().optional().default(true).describe('Whether the app is enabled'),\n\n /** Is this the default app for new users? */\n isDefault: z.boolean().optional().default(false).describe('Is default app'),\n \n /** \n * Full Navigation Tree — supports unlimited nesting depth.\n * Pages are referenced by name via `type: 'page'` items.\n * Groups can contain other groups for arbitrary sidebar depth.\n * \n * For simple apps, use `navigation` directly.\n * For enterprise apps with multiple business domains, use `areas` instead.\n */\n navigation: z.array(NavigationItemSchema).optional()\n .describe('Full navigation tree for the app sidebar'),\n\n /**\n * Navigation Areas — partitions navigation by business domain.\n * Each area defines an independent navigation tree (e.g. Sales, Service, Settings).\n * When areas are defined, they take precedence over the top-level `navigation` array.\n * \n * @example\n * ```ts\n * areas: [\n * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] },\n * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] },\n * ]\n * ```\n */\n areas: z.array(NavigationAreaSchema).optional()\n .describe('Navigation areas for partitioning navigation by business domain'),\n \n /** \n * App-level Home Page Override\n * ID of the navigation item to act as the landing page.\n * If not set, usually defaults to the first navigation item.\n */\n homePageId: z.string().optional().describe('ID of the navigation item to serve as landing page'),\n\n /** \n * Access Control\n * List of permissions required to access this app.\n * Modern replacement for role/profile based assignment.\n * Example: [\"app.access.crm\"]\n */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this app'),\n \n /** \n * Package Components (For config file convenience)\n * In a real monorepo these might be auto-discovered, but here we allow explicit registration.\n */\n objects: z.array(z.unknown()).optional().describe('Objects belonging to this app'),\n apis: z.array(z.unknown()).optional().describe('Custom APIs belonging to this app'),\n\n /** Sharing configuration for public access */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration'),\n\n /** Embed configuration for iframe embedding */\n embed: EmbedConfigSchema.optional().describe('Iframe embedding configuration'),\n\n /** Mobile navigation mode */\n mobileNavigation: z.object({\n mode: z.enum(['drawer', 'bottom_nav', 'hamburger']).default('drawer')\n .describe('Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu'),\n bottomNavItems: z.array(z.string()).optional()\n .describe('Navigation item IDs to show in bottom nav (max 5)'),\n }).optional().describe('Mobile-specific navigation configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the application'),\n});\n\n/**\n * App Factory Helper\n */\nexport const App = {\n create: (config: z.input): App => AppSchema.parse(config),\n} as const;\n\n/**\n * Type-safe factory for creating application definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example CRM App with nested navigation tree\n * ```ts\n * const crmApp = defineApp({\n * name: 'crm',\n * label: 'Sales CRM',\n * navigation: [\n * { id: 'grp_sales', type: 'group', label: 'Sales Cloud', expanded: true, children: [\n * { id: 'nav_pipeline', type: 'page', label: 'Pipeline', pageName: 'page_pipeline' },\n * { id: 'nav_accounts', type: 'page', label: 'Accounts', pageName: 'page_accounts' },\n * ]},\n * { id: 'nav_settings', type: 'page', label: 'Settings', pageName: 'admin_settings' },\n * ],\n * });\n * ```\n */\nexport function defineApp(config: z.input): App {\n return AppSchema.parse(config);\n}\n\n// Main Types\nexport type App = z.infer;\nexport type AppInput = z.input;\nexport type AppBranding = z.infer;\nexport type NavigationItem = z.infer;\nexport type NavigationArea = z.infer;\n\n// Discriminated Item Types (Helper exports)\nexport type ObjectNavItem = z.infer;\nexport type DashboardNavItem = z.infer;\nexport type PageNavItem = z.infer;\nexport type UrlNavItem = z.infer;\nexport type ReportNavItem = z.infer;\nexport type ActionNavItem = z.infer;\nexport type GroupNavItem = z.infer & { children: NavigationItem[] };\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Loader Protocol\n * \n * Defines the standard interface for loading and saving metadata in ObjectStack.\n * This protocol enables consistent metadata operations across different storage backends\n * (filesystem, HTTP, S3, databases) and serialization formats (JSON, YAML, TypeScript).\n */\n\n/**\n * Metadata Format Enum\n * Supported serialization formats for metadata\n */\nexport const MetadataFormatSchema = z.enum(['json', 'yaml', 'typescript', 'javascript']);\n\n/**\n * Metadata Statistics\n * Information about a metadata item without loading its full content\n */\nexport const MetadataStatsSchema = z.object({\n /**\n * Size of the metadata file in bytes\n */\n size: z.number().int().min(0).describe('File size in bytes'),\n \n /**\n * Last modification timestamp\n */\n modifiedAt: z.string().datetime().describe('Last modified date'),\n \n /**\n * ETag for cache validation\n * Used for conditional requests (If-None-Match header)\n */\n etag: z.string().describe('Entity tag for cache validation'),\n \n /**\n * Serialization format\n */\n format: MetadataFormatSchema.describe('Serialization format'),\n \n /**\n * Full file path (if applicable)\n */\n path: z.string().optional().describe('File system path'),\n \n /**\n * Additional metadata provider-specific properties\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Provider-specific metadata'),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n /**\n * Glob patterns to match files\n * Example: [\"**\\/*.object.ts\", \"**\\/*.object.json\"]\n */\n patterns: z.array(z.string()).optional().describe('File glob patterns'),\n \n /**\n * If-None-Match header for conditional loading\n * Only load if ETag doesn't match\n */\n ifNoneMatch: z.string().optional().describe('ETag for conditional request'),\n \n /**\n * If-Modified-Since header for conditional loading\n */\n ifModifiedSince: z.string().datetime().optional().describe('Only load if modified after this date'),\n \n /**\n * Whether to validate against Zod schema\n */\n validate: z.boolean().default(true).describe('Validate against schema'),\n \n /**\n * Whether to use cache if available\n */\n useCache: z.boolean().default(true).describe('Enable caching'),\n \n /**\n * Filter function (serialized as string)\n * Example: \"(item) => item.name.startsWith('sys_')\"\n */\n filter: z.string().optional().describe('Filter predicate as string'),\n \n /**\n * Maximum number of items to load\n */\n limit: z.number().int().min(1).optional().describe('Maximum items to load'),\n \n /**\n * Recursively search subdirectories\n */\n recursive: z.boolean().default(true).describe('Search subdirectories'),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n /**\n * Serialization format\n */\n format: MetadataFormatSchema.default('typescript').describe('Output format'),\n \n /**\n * Prettify output (formatted with indentation)\n */\n prettify: z.boolean().default(true).describe('Format with indentation'),\n \n /**\n * Indentation size (spaces)\n */\n indent: z.number().int().min(0).max(8).default(2).describe('Indentation spaces'),\n \n /**\n * Sort object keys alphabetically\n */\n sortKeys: z.boolean().default(false).describe('Sort object keys'),\n \n /**\n * Include default values in output\n */\n includeDefaults: z.boolean().default(false).describe('Include default values'),\n \n /**\n * Create backup before overwriting\n */\n backup: z.boolean().default(false).describe('Create backup file'),\n \n /**\n * Overwrite if exists\n */\n overwrite: z.boolean().default(true).describe('Overwrite existing file'),\n \n /**\n * Atomic write (write to temp file, then rename)\n */\n atomic: z.boolean().default(true).describe('Use atomic write operation'),\n \n /**\n * Custom file path (overrides default location)\n */\n path: z.string().optional().describe('Custom output path'),\n});\n\n/**\n * Metadata Export Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n /**\n * Output file path\n */\n output: z.string().describe('Output file path'),\n \n /**\n * Export format\n */\n format: MetadataFormatSchema.default('json').describe('Export format'),\n \n /**\n * Filter predicate as string\n */\n filter: z.string().optional().describe('Filter items to export'),\n \n /**\n * Include statistics in export\n */\n includeStats: z.boolean().default(false).describe('Include metadata statistics'),\n \n /**\n * Compress output\n */\n compress: z.boolean().default(false).describe('Compress output (gzip)'),\n \n /**\n * Pretty print output\n */\n prettify: z.boolean().default(true).describe('Pretty print output'),\n});\n\n/**\n * Metadata Import Options\n */\nexport const MetadataImportOptionsSchema = z.object({\n /**\n * Conflict resolution strategy\n */\n conflictResolution: z.enum(['skip', 'overwrite', 'merge', 'fail'])\n .default('merge')\n .describe('How to handle existing items'),\n \n /**\n * Validate items against schema\n */\n validate: z.boolean().default(true).describe('Validate before import'),\n \n /**\n * Dry run (don't actually save)\n */\n dryRun: z.boolean().default(false).describe('Simulate import without saving'),\n \n /**\n * Continue on errors\n */\n continueOnError: z.boolean().default(false).describe('Continue if validation fails'),\n \n /**\n * Transform function (as string)\n * Example: \"(item) => ({ ...item, imported: true })\"\n */\n transform: z.string().optional().describe('Transform items before import'),\n});\n\n/**\n * Metadata Loader Result\n * Result of a metadata load operation\n */\nexport const MetadataLoadResultSchema = z.object({\n /**\n * Loaded data\n */\n data: z.unknown().nullable().describe('Loaded metadata'),\n \n /**\n * Whether data came from cache (304 Not Modified)\n */\n fromCache: z.boolean().default(false).describe('Loaded from cache'),\n \n /**\n * Not modified (conditional request matched)\n */\n notModified: z.boolean().default(false).describe('Not modified since last request'),\n \n /**\n * ETag of loaded data\n */\n etag: z.string().optional().describe('Entity tag'),\n \n /**\n * Statistics about loaded data\n */\n stats: MetadataStatsSchema.optional().describe('Metadata statistics'),\n \n /**\n * Load time in milliseconds\n */\n loadTime: z.number().min(0).optional().describe('Load duration in ms'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n /**\n * Whether save was successful\n */\n success: z.boolean().describe('Save successful'),\n \n /**\n * Path where file was saved\n */\n path: z.string().describe('Output path'),\n \n /**\n * Generated ETag\n */\n etag: z.string().optional().describe('Generated entity tag'),\n \n /**\n * File size in bytes\n */\n size: z.number().int().min(0).optional().describe('File size'),\n \n /**\n * Save time in milliseconds\n */\n saveTime: z.number().min(0).optional().describe('Save duration in ms'),\n \n /**\n * Backup path (if created)\n */\n backupPath: z.string().optional().describe('Backup file path'),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum(['added', 'changed', 'deleted']).describe('Event type'),\n \n /**\n * Metadata type (e.g., 'object', 'view', 'app')\n */\n metadataType: z.string().describe('Type of metadata'),\n \n /**\n * Item name/identifier\n */\n name: z.string().describe('Item identifier'),\n \n /**\n * Full file path\n */\n path: z.string().describe('File path'),\n \n /**\n * Loaded item data (for added/changed events)\n */\n data: z.unknown().optional().describe('Item data'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\n/**\n * Metadata Collection Info\n * Summary of a metadata collection\n */\nexport const MetadataCollectionInfoSchema = z.object({\n /**\n * Collection type (e.g., 'object', 'view', 'app')\n */\n type: z.string().describe('Collection type'),\n \n /**\n * Total items in collection\n */\n count: z.number().int().min(0).describe('Number of items'),\n \n /**\n * Formats found in collection\n */\n formats: z.array(MetadataFormatSchema).describe('Formats in collection'),\n \n /**\n * Total size in bytes\n */\n totalSize: z.number().int().min(0).optional().describe('Total size in bytes'),\n \n /**\n * Last modified timestamp\n */\n lastModified: z.string().datetime().optional().describe('Last modification date'),\n \n /**\n * Collection location (path or URL)\n */\n location: z.string().optional().describe('Collection location'),\n});\n\n/**\n * Metadata Loader Interface Contract\n * Defines the standard methods all metadata loaders must implement\n */\nexport const MetadataLoaderContractSchema = z.object({\n /**\n * Loader name/identifier\n */\n name: z.string().describe('Loader identifier'),\n\n /**\n * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:')\n */\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Protocol identifier'),\n\n /**\n * Detailed capabilities\n */\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }).describe('Loader capabilities'),\n \n /**\n * Supported formats\n */\n supportedFormats: z.array(MetadataFormatSchema).describe('Supported formats'),\n \n /**\n * Whether loader supports watching for changes\n */\n supportsWatch: z.boolean().default(false).describe('Supports file watching'),\n \n /**\n * Whether loader supports saving\n */\n supportsWrite: z.boolean().default(true).describe('Supports write operations'),\n \n /**\n * Whether loader supports caching\n */\n supportsCache: z.boolean().default(true).describe('Supports caching'),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Manager Configuration\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory path'),\n \n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).default(['typescript', 'json', 'yaml']).describe('Enabled formats'),\n \n /**\n * Cache configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable caching'),\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n maxSize: z.number().int().min(0).optional().describe('Max cache size in bytes'),\n }).optional().describe('Cache settings'),\n \n /**\n * Watch for file changes\n */\n watch: z.boolean().default(false).describe('Enable file watching'),\n \n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n ignoreInitial: z.boolean().default(true).describe('Ignore initial add events'),\n }).optional().describe('File watcher options'),\n \n /**\n * Validation settings\n */\n validation: z.object({\n strict: z.boolean().default(true).describe('Strict validation'),\n throwOnError: z.boolean().default(true).describe('Throw on validation error'),\n }).optional().describe('Validation settings'),\n \n /**\n * Loader-specific options\n */\n loaderOptions: z.record(z.string(), z.unknown()).optional().describe('Loader-specific configuration'),\n});\n\n// Export types\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoadOptions = z.input;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Customization Layer Protocol\n * \n * Defines the overlay system for managing user customizations on top of\n * package-delivered metadata. This protocol solves the critical challenge\n * of separating \"vendor-managed\" metadata from \"customer-customized\" metadata,\n * enabling safe package upgrades without losing user changes.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed vs Unmanaged metadata components\n * - **ServiceNow**: Update Sets with collision detection\n * - **WordPress**: Parent/child theme overlay model\n * - **Kubernetes**: Strategic merge patch for resource customization\n * \n * ## Three-Layer Model\n * ```\n * ┌─────────────────────────────────┐\n * │ User Layer (scope: user) │ ← Personal overrides (per-user)\n * ├─────────────────────────────────┤\n * │ Platform Layer (scope: platform)│ ← Admin customizations (per-tenant)\n * ├─────────────────────────────────┤\n * │ System Layer (scope: system) │ ← Package-delivered metadata (read-only)\n * └─────────────────────────────────┘\n * ```\n * \n * ## Merge Resolution Order\n * Effective metadata = System ← merge(Platform) ← merge(User)\n * Each layer only stores the delta (changed fields), not the full definition.\n */\n\n// ==========================================\n// Customization Tracking\n// ==========================================\n\n/**\n * Customization Origin\n * Identifies who created the customization.\n */\nexport const CustomizationOriginSchema = z.enum([\n 'package', // Delivered by a plugin package (system layer, read-only)\n 'admin', // Created/modified by platform admin via UI\n 'user', // Created/modified by end user via UI\n 'migration', // Created during data migration\n 'api', // Created via API\n]);\n\n/**\n * Field-Level Change Tracking\n * Records exactly which fields were modified by the customer.\n */\nexport const FieldChangeSchema = z.object({\n /** JSON path to the changed field (e.g. \"fields.status.label\") */\n path: z.string().describe('JSON path to the changed field'),\n\n /** Original value from the package (for diff/rollback) */\n originalValue: z.unknown().optional().describe('Original value from the package'),\n\n /** Current customized value */\n currentValue: z.unknown().describe('Current customized value'),\n\n /** Who made this change */\n changedBy: z.string().optional().describe('User or admin who made this change'),\n\n /** When this change was made */\n changedAt: z.string().datetime().optional().describe('Timestamp of the change'),\n});\n\n/**\n * Metadata Overlay Schema\n * \n * Represents a customization layer on top of package-delivered metadata.\n * Each overlay stores only the delta (changed fields) relative to the base definition.\n * \n * During package upgrades, the system performs a 3-way merge:\n * 1. Old package version (base)\n * 2. New package version (theirs)\n * 3. Customer customizations (ours)\n * \n * @example\n * ```yaml\n * # Package delivers: object \"crm__account\" with field \"status\" label \"Status\"\n * # Admin changes label to \"Account Status\"\n * # Overlay record:\n * baseType: object\n * baseName: crm__account\n * packageId: com.acme.crm\n * packageVersion: \"1.0.0\"\n * changes:\n * - path: \"fields.status.label\"\n * originalValue: \"Status\"\n * currentValue: \"Account Status\"\n * ```\n */\nexport const MetadataOverlaySchema = z.object({\n /** Primary key */\n id: z.string().describe('Overlay record ID (UUID)'),\n\n /** The metadata type being customized (e.g. \"object\", \"view\", \"flow\") */\n baseType: z.string().describe('Metadata type being customized'),\n\n /** The metadata name being customized (e.g. \"crm__account\") */\n baseName: z.string().describe('Metadata name being customized'),\n\n /** Package that owns the base metadata (null for platform-created metadata) */\n packageId: z.string().optional().describe('Package ID that delivered the base metadata'),\n\n /** Package version when the customization was made (for upgrade diffing) */\n packageVersion: z.string().optional().describe('Package version when overlay was created'),\n\n /** Customization scope */\n scope: z.enum(['platform', 'user']).default('platform')\n .describe('Customization scope (platform=admin, user=personal)'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Owner user ID (for user-scope overlays) */\n owner: z.string().optional().describe('Owner user ID for user-scope overlays'),\n\n /**\n * The overlay payload.\n * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396).\n * - To modify a field: include the field with its new value\n * - To delete a field: set its value to null\n * - Omitted fields remain unchanged from base\n */\n patch: z.record(z.string(), z.unknown()).describe('JSON Merge Patch payload (changed fields only)'),\n\n /**\n * Detailed change tracking for each modified field.\n * Enables field-level conflict detection during upgrades.\n */\n changes: z.array(FieldChangeSchema).optional()\n .describe('Field-level change tracking for conflict detection'),\n\n /** Whether this overlay is currently active */\n active: z.boolean().default(true).describe('Whether this overlay is active'),\n\n /** Audit timestamps */\n createdAt: z.string().datetime().optional(),\n createdBy: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n updatedBy: z.string().optional(),\n});\n\n// ==========================================\n// Merge & Conflict Resolution\n// ==========================================\n\n/**\n * Merge Conflict\n * Represents a conflict between package update and customer customization.\n */\nexport const MergeConflictSchema = z.object({\n /** JSON path to the conflicting field */\n path: z.string().describe('JSON path to the conflicting field'),\n\n /** Value in the old package version */\n baseValue: z.unknown().describe('Value in the old package version'),\n\n /** Value in the new package version */\n incomingValue: z.unknown().describe('Value in the new package version'),\n\n /** Customer's customized value */\n customValue: z.unknown().describe('Customer customized value'),\n\n /** Suggested resolution strategy */\n suggestedResolution: z.enum([\n 'keep-custom', // Keep customer's customization\n 'accept-incoming', // Accept package update\n 'manual', // Requires manual resolution\n ]).describe('Suggested resolution strategy'),\n\n /** Reason for the suggested resolution */\n reason: z.string().optional().describe('Explanation for the suggested resolution'),\n});\n\n/**\n * Merge Strategy Configuration\n * Controls how metadata merging behaves during package upgrades.\n */\nexport const MergeStrategyConfigSchema = z.object({\n /** Default strategy when no field-level rule matches */\n defaultStrategy: z.enum([\n 'keep-custom', // Preserve all customer customizations (safe)\n 'accept-incoming', // Accept all package updates (overwrite)\n 'three-way-merge', // Intelligent 3-way merge with conflict detection\n ]).default('three-way-merge').describe('Default merge strategy'),\n\n /** \n * Field paths that should always accept incoming package updates.\n * Use for fields that the package vendor considers \"owned\" and should not be customized.\n * @example [\"fields.*.type\", \"triggers.*\"]\n */\n alwaysAcceptIncoming: z.array(z.string()).optional()\n .describe('Field paths that always accept package updates'),\n\n /**\n * Field paths where customer customizations always win.\n * Use for UI-facing fields like labels, descriptions, help text.\n * @example [\"fields.*.label\", \"fields.*.helpText\", \"description\"]\n */\n alwaysKeepCustom: z.array(z.string()).optional()\n .describe('Field paths where customer customizations always win'),\n\n /** Whether to automatically resolve non-conflicting changes */\n autoResolveNonConflicting: z.boolean().default(true)\n .describe('Auto-resolve changes that do not conflict'),\n});\n\n/**\n * Merge Result\n * Result of a 3-way merge operation during package upgrade.\n */\nexport const MergeResultSchema = z.object({\n /** Whether the merge completed successfully (no unresolved conflicts) */\n success: z.boolean().describe('Whether merge completed without unresolved conflicts'),\n\n /** The merged metadata payload */\n mergedMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Merged metadata result'),\n\n /** Updated overlay with remaining customizations */\n updatedOverlay: z.record(z.string(), z.unknown()).optional()\n .describe('Updated overlay after merge'),\n\n /** List of conflicts that require manual resolution */\n conflicts: z.array(MergeConflictSchema).optional()\n .describe('Unresolved merge conflicts'),\n\n /** Summary of automatically resolved changes */\n autoResolved: z.array(z.object({\n path: z.string(),\n resolution: z.string(),\n description: z.string().optional(),\n })).optional().describe('Summary of auto-resolved changes'),\n\n /** Statistics */\n stats: z.object({\n totalFields: z.number().int().min(0).describe('Total fields evaluated'),\n unchanged: z.number().int().min(0).describe('Fields with no changes'),\n autoResolved: z.number().int().min(0).describe('Fields auto-resolved'),\n conflicts: z.number().int().min(0).describe('Fields with conflicts'),\n }).optional(),\n});\n\n// ==========================================\n// Customization Management\n// ==========================================\n\n/**\n * Customizable Metadata Policy\n * Defines what parts of a metadata item can be customized by admins/users.\n * Package vendors use this to control customization boundaries.\n */\nexport const CustomizationPolicySchema = z.object({\n /** Metadata type this policy applies to */\n metadataType: z.string().describe('Metadata type (e.g. \"object\", \"view\")'),\n\n /** Whether customization is allowed at all for this type */\n allowCustomization: z.boolean().default(true),\n\n /**\n * Field paths that are locked (cannot be customized).\n * @example [\"name\", \"type\", \"fields.*.type\"]\n */\n lockedFields: z.array(z.string()).optional()\n .describe('Field paths that cannot be customized'),\n\n /**\n * Field paths that are customizable.\n * If specified, only these fields can be customized (whitelist mode).\n * @example [\"label\", \"description\", \"fields.*.label\", \"fields.*.helpText\"]\n */\n customizableFields: z.array(z.string()).optional()\n .describe('Field paths that can be customized (whitelist)'),\n\n /**\n * Whether users can add new fields to package objects.\n * When true, admins can extend package objects with custom fields.\n */\n allowAddFields: z.boolean().default(true)\n .describe('Whether admins can add new fields to package objects'),\n\n /**\n * Whether users can delete package-delivered fields.\n * Typically false — fields can only be hidden, not deleted.\n */\n allowDeleteFields: z.boolean().default(false)\n .describe('Whether admins can delete package-delivered fields'),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type CustomizationOrigin = z.infer;\nexport type FieldChange = z.infer;\nexport type MetadataOverlay = z.infer;\nexport type MergeConflict = z.infer;\nexport type MergeStrategyConfig = z.infer;\nexport type MergeResult = z.infer;\nexport type CustomizationPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { MetadataManagerConfigSchema } from './metadata-loader.zod';\nimport { MergeStrategyConfigSchema, CustomizationPolicySchema } from './metadata-customization.zod';\n\n/**\n * # Metadata Plugin Protocol\n *\n * Defines the specification for the **Metadata Plugin** — the central authority\n * responsible for managing ALL metadata across the ObjectStack platform.\n *\n * ## Architecture\n * The Metadata Plugin consolidates all scattered metadata operations into a single,\n * cohesive plugin that \"takes over\" the entire platform's metadata management:\n *\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ Metadata Plugin │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Type Registry │ │ Loader │ │ Customization Layer │ │\n * │ │ (all types) │ │ (file/db/s3)│ │ (overlay / merge) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Persistence │ │ Query │ │ Lifecycle │ │\n * │ │ (db records) │ │ (search) │ │ (validate/deploy) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n *\n * ## References\n * - kernel/metadata-loader.zod.ts — Storage backend protocol\n * - kernel/metadata-customization.zod.ts — Overlay/merge protocol\n * - system/metadata-persistence.zod.ts — Database record format\n * - contracts/metadata-service.ts — Service interface\n */\n\n// ==========================================\n// Metadata Type Registry\n// ==========================================\n\n/**\n * Platform Metadata Type Enum\n *\n * The canonical list of all metadata types managed by the platform.\n * Each type maps to a specific Zod schema (e.g., ObjectSchema, ViewSchema).\n * Plugins can extend this registry via `contributes.kinds` in the manifest.\n *\n * ## Naming Convention\n * **IMPORTANT:** All metadata type names are in **SINGULAR** form:\n * - ✅ Use: `'agent'`, `'tool'`, `'skill'`, `'view'`, `'flow'`, `'action'`\n * - ❌ NOT: `'agents'`, `'tools'`, `'skills'`, `'views'`, `'flows'`, `'actions'`\n *\n * This convention applies to:\n * - Protocol definitions (this enum)\n * - UI plugin registrations (`metadataTypes`, `metadataIcons`)\n * - Metadata service operations\n * - File patterns (`*.agent.ts`, `*.tool.ts`)\n *\n * REST API endpoints continue to use plural forms per REST conventions:\n * - `/api/v1/ai/agents`, `/api/v1/ai/conversations`\n */\nexport const MetadataTypeSchema = z.enum([\n // Data Protocol\n 'object', // Business entity definition (ObjectSchema)\n 'field', // Standalone field definition (FieldSchema)\n 'trigger', // Data-layer event triggers (TriggerSchema)\n 'validation', // Validation rules (ValidationSchema)\n 'hook', // Data hooks (HookSchema)\n\n // UI Protocol\n 'view', // List/form views (ViewSchema)\n 'page', // Standalone pages (PageSchema)\n 'dashboard', // Dashboard layouts (DashboardSchema)\n 'app', // Application shell (AppSchema)\n 'action', // UI/Server actions (ActionSchema)\n 'report', // Report definitions (ReportSchema)\n\n // Automation Protocol\n 'flow', // Visual logic flows (FlowSchema)\n 'workflow', // State machines (WorkflowSchema)\n 'approval', // Approval processes (ApprovalSchema)\n\n // System Protocol\n 'datasource', // Data connections (DatasourceSchema)\n 'translation', // i18n resources (TranslationSchema)\n 'router', // API routes\n 'function', // Serverless functions\n 'service', // Service definitions\n\n // Security Protocol\n 'permission', // Permission sets (PermissionSetSchema)\n 'profile', // User profiles (ProfileSchema)\n 'role', // Security roles\n\n // AI Protocol\n 'agent', // AI agent definitions (AgentSchema)\n 'tool', // AI tool definitions (ToolSchema)\n 'skill', // AI skill definitions (SkillSchema)\n]);\n\nexport type MetadataType = z.infer;\n\n// ==========================================\n// Type Registry Entry\n// ==========================================\n\n/**\n * Metadata Type Registry Entry\n *\n * Describes a registered metadata type, including its validation schema,\n * file patterns, and capabilities. Used by the metadata plugin to:\n * 1. Discover metadata files on disk\n * 2. Validate metadata payloads\n * 3. Determine storage behavior\n */\nexport const MetadataTypeRegistryEntrySchema = z.object({\n /** Metadata type identifier (e.g., 'object', 'view') */\n type: MetadataTypeSchema.describe('Metadata type identifier'),\n\n /** Human-readable label */\n label: z.string().describe('Display label for the metadata type'),\n\n /** Brief description */\n description: z.string().optional().describe('Description of the metadata type'),\n\n /**\n * File glob patterns for this type.\n * Used to discover metadata files on disk.\n * @example [\"**\\/*.object.ts\", \"**\\/*.object.yml\"]\n */\n filePatterns: z.array(z.string()).describe('Glob patterns to discover files of this type'),\n\n /**\n * Whether this type supports the customization overlay system.\n * When true, platform/user overlays can be applied on top of package-delivered metadata.\n */\n supportsOverlay: z.boolean().default(true).describe('Whether overlay customization is supported'),\n\n /**\n * Whether metadata of this type can be created at runtime via API.\n * Some types (e.g., 'object') may be restricted to deployment-only.\n */\n allowRuntimeCreate: z.boolean().default(true).describe('Allow runtime creation via API'),\n\n /**\n * Whether this type supports versioning.\n * When true, changes are tracked with version history.\n */\n supportsVersioning: z.boolean().default(false).describe('Whether version history is tracked'),\n\n /**\n * Priority order for loading (lower = earlier).\n * Objects load before views, views before dashboards.\n */\n loadOrder: z.number().int().min(0).default(100).describe('Loading priority (lower = earlier)'),\n\n /** The domain this type belongs to */\n domain: z.enum(['data', 'ui', 'automation', 'system', 'security', 'ai'])\n .describe('Protocol domain'),\n});\n\nexport type MetadataTypeRegistryEntry = z.infer;\n\n// ==========================================\n// Metadata Query Protocol\n// ==========================================\n\n/**\n * Metadata Query Schema\n *\n * Standard protocol for searching and filtering metadata items.\n * Used by the metadata service to support advanced metadata discovery.\n */\nexport const MetadataQuerySchema = z.object({\n /** Filter by metadata type(s) */\n types: z.array(MetadataTypeSchema).optional().describe('Filter by metadata types'),\n\n /** Filter by namespace(s) */\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n\n /** Filter by package ID */\n packageId: z.string().optional().describe('Filter by owning package'),\n\n /** Full-text search across name, label, description */\n search: z.string().optional().describe('Full-text search query'),\n\n /** Filter by scope */\n scope: z.enum(['system', 'platform', 'user']).optional().describe('Filter by scope'),\n\n /** Filter by state */\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional().describe('Filter by lifecycle state'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Sort field */\n sortBy: z.enum(['name', 'type', 'updatedAt', 'createdAt']).default('name').describe('Sort field'),\n\n /** Sort direction */\n sortOrder: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n\n /** Pagination: page number (1-based) */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(500).default(50).describe('Items per page'),\n});\n\nexport type MetadataQuery = z.input;\n\n/**\n * Metadata Query Result\n */\nexport const MetadataQueryResultSchema = z.object({\n /** Matched items */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n namespace: z.string().optional().describe('Namespace'),\n label: z.string().optional().describe('Display label'),\n scope: z.enum(['system', 'platform', 'user']).optional(),\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional(),\n packageId: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n })).describe('Matched metadata items'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching items'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page'),\n\n /** Page size */\n pageSize: z.number().int().min(1).describe('Page size'),\n});\n\nexport type MetadataQueryResult = z.infer;\n\n// ==========================================\n// Metadata Lifecycle Events\n// ==========================================\n\n/**\n * Metadata Event Schema\n *\n * Events emitted by the metadata plugin when metadata changes.\n * Enables reactive patterns across the platform (cache invalidation,\n * UI refresh, dependency tracking, etc.).\n */\nexport const MetadataEventSchema = z.object({\n /** Event type */\n event: z.enum([\n 'metadata.registered',\n 'metadata.updated',\n 'metadata.unregistered',\n 'metadata.validated',\n 'metadata.deployed',\n 'metadata.overlay.applied',\n 'metadata.overlay.removed',\n 'metadata.imported',\n 'metadata.exported',\n ]).describe('Event type'),\n\n /** Metadata type */\n metadataType: MetadataTypeSchema.describe('Metadata type'),\n\n /** Item name */\n name: z.string().describe('Metadata item name'),\n\n /** Namespace */\n namespace: z.string().optional().describe('Namespace'),\n\n /** Package ID (if package-managed) */\n packageId: z.string().optional().describe('Owning package ID'),\n\n /** Timestamp */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /** Actor who caused the event */\n actor: z.string().optional().describe('User or system that triggered the event'),\n\n /** Additional event-specific payload */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event-specific payload'),\n});\n\nexport type MetadataEvent = z.infer;\n\n// ==========================================\n// Metadata Validation\n// ==========================================\n\n/**\n * Metadata Validation Result\n */\nexport const MetadataValidationResultSchema = z.object({\n /** Whether validation passed */\n valid: z.boolean().describe('Whether the metadata is valid'),\n\n /** Validation errors */\n errors: z.array(z.object({\n path: z.string().describe('JSON path to the invalid field'),\n message: z.string().describe('Error description'),\n code: z.string().optional().describe('Error code'),\n })).optional().describe('Validation errors'),\n\n /** Validation warnings (non-blocking) */\n warnings: z.array(z.object({\n path: z.string().describe('JSON path to the field'),\n message: z.string().describe('Warning description'),\n })).optional().describe('Validation warnings'),\n});\n\nexport type MetadataValidationResult = z.infer;\n\n// ==========================================\n// Metadata Plugin Configuration\n// ==========================================\n\n/**\n * Metadata Plugin Configuration\n *\n * The unified configuration for the metadata plugin, combining\n * storage, caching, customization, and type registry settings.\n */\nexport const MetadataPluginConfigSchema = z.object({\n /**\n * Storage configuration.\n * References MetadataManagerConfigSchema for the underlying storage backend.\n */\n storage: MetadataManagerConfigSchema.describe('Storage backend configuration'),\n\n /**\n * Default customization policies per metadata type.\n * Controls what parts of metadata can be customized by admins/users.\n */\n customizationPolicies: z.array(CustomizationPolicySchema).optional()\n .describe('Default customization policies per type'),\n\n /**\n * Merge strategy for package upgrades.\n */\n mergeStrategy: MergeStrategyConfigSchema.optional()\n .describe('Merge strategy for package upgrades'),\n\n /**\n * Additional metadata type registrations.\n * Used by plugins to register custom metadata types beyond the built-in set.\n */\n additionalTypes: z.array(MetadataTypeRegistryEntrySchema.omit({ type: true }).extend({\n type: z.string().describe('Custom metadata type identifier'),\n })).optional().describe('Additional custom metadata types'),\n\n /**\n * Enable metadata change events.\n * When true, the plugin emits events on every metadata change.\n */\n enableEvents: z.boolean().default(true).describe('Emit metadata change events'),\n\n /**\n * Enable metadata validation on write operations.\n * When true, all metadata is validated against its type schema before saving.\n */\n validateOnWrite: z.boolean().default(true).describe('Validate metadata on write'),\n\n /**\n * Enable metadata versioning.\n * When true, changes to metadata are tracked with version history.\n */\n enableVersioning: z.boolean().default(false).describe('Track metadata version history'),\n\n /**\n * Maximum number of metadata items to keep in memory cache.\n */\n cacheMaxItems: z.number().int().min(0).default(10000).describe('Max items in memory cache'),\n});\n\nexport type MetadataPluginConfig = z.input;\n\n// ==========================================\n// Metadata Plugin Manifest\n// ==========================================\n\n/**\n * Metadata Plugin Manifest\n *\n * The complete manifest for the Metadata Plugin, declaring its identity,\n * capabilities, and configuration. This is the \"contract\" between the\n * metadata plugin and the kernel.\n */\nexport const MetadataPluginManifestSchema = z.object({\n /** Plugin identifier */\n id: z.literal('com.objectstack.metadata').describe('Metadata plugin ID'),\n\n /** Plugin name */\n name: z.literal('ObjectStack Metadata Service').describe('Plugin name'),\n\n /** Plugin version */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Plugin version'),\n\n /** Plugin type */\n type: z.literal('standard').describe('Plugin type'),\n\n /** Plugin description */\n description: z.string().default('Core metadata management service for ObjectStack platform')\n .describe('Plugin description'),\n\n /**\n * Capabilities this plugin provides.\n * The kernel uses this to route metadata requests to this plugin.\n */\n capabilities: z.object({\n /** Supports CRUD operations on metadata */\n crud: z.boolean().default(true).describe('Supports metadata CRUD'),\n\n /** Supports metadata query/search */\n query: z.boolean().default(true).describe('Supports metadata query'),\n\n /** Supports the overlay/customization system */\n overlay: z.boolean().default(true).describe('Supports customization overlays'),\n\n /** Supports file watching for hot reload */\n watch: z.boolean().default(false).describe('Supports file watching'),\n\n /** Supports bulk import/export */\n importExport: z.boolean().default(true).describe('Supports import/export'),\n\n /** Supports metadata validation */\n validation: z.boolean().default(true).describe('Supports schema validation'),\n\n /** Supports metadata versioning */\n versioning: z.boolean().default(false).describe('Supports version history'),\n\n /** Supports metadata events */\n events: z.boolean().default(true).describe('Emits metadata events'),\n }).describe('Plugin capabilities'),\n\n /** Plugin configuration */\n config: MetadataPluginConfigSchema.optional().describe('Plugin configuration'),\n});\n\nexport type MetadataPluginManifest = z.input;\n\n// ==========================================\n// Built-in Type Registry Defaults\n// ==========================================\n\n/**\n * Default Type Registry\n *\n * The built-in metadata type registry with default configurations.\n * Plugins extend this via `contributes.kinds` in the manifest.\n */\nexport const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntry[] = [\n // Data Protocol (load first)\n { type: 'object', label: 'Object', filePatterns: ['**/*.object.ts', '**/*.object.yml', '**/*.object.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 10, domain: 'data' },\n { type: 'field', label: 'Field', filePatterns: ['**/*.field.ts', '**/*.field.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 20, domain: 'data' },\n { type: 'trigger', label: 'Trigger', filePatterns: ['**/*.trigger.ts', '**/*.trigger.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'validation', label: 'Validation Rule', filePatterns: ['**/*.validation.ts', '**/*.validation.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'hook', label: 'Hook', filePatterns: ['**/*.hook.ts', '**/*.hook.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n\n // UI Protocol\n { type: 'view', label: 'View', filePatterns: ['**/*.view.ts', '**/*.view.yml', '**/*.view.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'page', label: 'Page', filePatterns: ['**/*.page.ts', '**/*.page.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'dashboard', label: 'Dashboard', filePatterns: ['**/*.dashboard.ts', '**/*.dashboard.yml', '**/*.dashboard.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n { type: 'app', label: 'Application', filePatterns: ['**/*.app.ts', '**/*.app.yml', '**/*.app.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 70, domain: 'ui' },\n { type: 'action', label: 'Action', filePatterns: ['**/*.action.ts', '**/*.action.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'report', label: 'Report', filePatterns: ['**/*.report.ts', '**/*.report.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n\n // Automation Protocol\n { type: 'flow', label: 'Flow', filePatterns: ['**/*.flow.ts', '**/*.flow.yml', '**/*.flow.json'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'workflow', label: 'Workflow', filePatterns: ['**/*.workflow.ts', '**/*.workflow.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'approval', label: 'Approval Process', filePatterns: ['**/*.approval.ts', '**/*.approval.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 80, domain: 'automation' },\n\n // System Protocol\n { type: 'datasource', label: 'Datasource', filePatterns: ['**/*.datasource.ts', '**/*.datasource.yml'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 5, domain: 'system' },\n { type: 'translation', label: 'Translation', filePatterns: ['**/*.translation.ts', '**/*.translation.yml', '**/*.translation.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 90, domain: 'system' },\n { type: 'router', label: 'Router', filePatterns: ['**/*.router.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'function', label: 'Function', filePatterns: ['**/*.function.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'service', label: 'Service', filePatterns: ['**/*.service.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n\n // Security Protocol\n { type: 'permission', label: 'Permission Set', filePatterns: ['**/*.permission.ts', '**/*.permission.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 15, domain: 'security' },\n { type: 'profile', label: 'Profile', filePatterns: ['**/*.profile.ts', '**/*.profile.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n { type: 'role', label: 'Role', filePatterns: ['**/*.role.ts', '**/*.role.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n\n // AI Protocol\n { type: 'agent', label: 'AI Agent', filePatterns: ['**/*.agent.ts', '**/*.agent.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 90, domain: 'ai' },\n { type: 'tool', label: 'AI Tool', filePatterns: ['**/*.tool.ts', '**/*.tool.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 85, domain: 'ai' },\n { type: 'skill', label: 'AI Skill', filePatterns: ['**/*.skill.ts', '**/*.skill.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 88, domain: 'ai' },\n];\n\n// ==========================================\n// Bulk Operation Types\n// ==========================================\n\n/**\n * Bulk Register Request\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n /** Items to register */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Namespace'),\n })).min(1).describe('Items to register'),\n\n /** Continue on individual item failure */\n continueOnError: z.boolean().default(false).describe('Continue if individual item fails'),\n\n /** Validate items before registering */\n validate: z.boolean().default(true).describe('Validate before register'),\n});\n\nexport type MetadataBulkRegisterRequest = z.input;\n\n/**\n * Bulk Operation Result\n */\nexport const MetadataBulkResultSchema = z.object({\n /** Total items processed */\n total: z.number().int().min(0).describe('Total items processed'),\n\n /** Successfully processed items */\n succeeded: z.number().int().min(0).describe('Successfully processed'),\n\n /** Failed items */\n failed: z.number().int().min(0).describe('Failed items'),\n\n /** Per-item error details */\n errors: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n error: z.string().describe('Error message'),\n })).optional().describe('Per-item errors'),\n});\n\nexport type MetadataBulkResult = z.infer;\n\n// ==========================================\n// Metadata Dependency\n// ==========================================\n\n/**\n * Metadata Dependency Schema\n *\n * Tracks dependencies between metadata items.\n * Used for impact analysis and safe deletion checks.\n */\nexport const MetadataDependencySchema = z.object({\n /** Source metadata type */\n sourceType: z.string().describe('Dependent metadata type'),\n\n /** Source metadata name */\n sourceName: z.string().describe('Dependent metadata name'),\n\n /** Target metadata type */\n targetType: z.string().describe('Referenced metadata type'),\n\n /** Target metadata name */\n targetName: z.string().describe('Referenced metadata name'),\n\n /** Dependency kind */\n kind: z.enum(['reference', 'extends', 'includes', 'triggers'])\n .describe('How the dependency is formed'),\n});\n\nexport type MetadataDependency = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { ObjectSchema } from '../data/object.zod';\nimport { AppSchema } from '../ui/app.zod';\nimport { MetadataTypeSchema, MetadataQuerySchema, MetadataQueryResultSchema, MetadataValidationResultSchema, MetadataBulkResultSchema, MetadataDependencySchema } from '../kernel/metadata-plugin.zod';\nimport { MetadataOverlaySchema } from '../kernel/metadata-customization.zod';\n\n/**\n * Metadata Service Protocol\n *\n * Defines the standard API contracts for the **@objectstack/metadata** package.\n * This is the single authority for ALL metadata-related services and APIs across\n * the entire platform, including Hono, Next.js, and NestJS adapters.\n *\n * ## Architecture\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ @objectstack/metadata — API Contracts │\n * │ │\n * │ CRUD │ Query/Search │ Bulk Ops │ Overlay │ Watch │\n * │ Import/Export│ Validation │ Type Reg │ Deps │ │\n * ├──────────────────────────────────────────────────────────────────┤\n * │ Hono Adapter │ Next.js Adapter │ NestJS Adapter │ CLI │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n */\n\n// ==========================================\n// 1. Legacy Responses (existing)\n// ==========================================\n\n/**\n * Single Object Definition Response\n * Returns the full JSON schema for an Entity (Fields, Actions, Config).\n */\nexport const ObjectDefinitionResponseSchema = BaseResponseSchema.extend({\n data: ObjectSchema.describe('Full Object Schema'),\n});\n\n/**\n * App Definition Response\n * Returns the navigation, branding, and layout for an App.\n */\nexport const AppDefinitionResponseSchema = BaseResponseSchema.extend({\n data: AppSchema.describe('Full App Configuration'),\n});\n\n/**\n * All Concepts Response\n * Bulk load lightweight definitions for autocomplete/pickers.\n */\nexport const ConceptListResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.object({\n name: z.string(),\n label: z.string(),\n icon: z.string().optional(),\n description: z.string().optional(),\n })).describe('List of available concepts (Objects, Apps, Flows)'),\n});\n\n// ==========================================\n// 2. CRUD Request / Response Schemas\n// ==========================================\n\n/**\n * Register (Create/Update) Metadata Request\n * POST /api/meta/:type\n * PUT /api/meta/:type/:name\n */\nexport const MetadataRegisterRequestSchema = z.object({\n type: MetadataTypeSchema.describe('Metadata type'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Item name (snake_case)'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Optional namespace'),\n});\n\n/**\n * Single Metadata Item Response\n * GET /api/meta/:type/:name\n */\nexport const MetadataItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n definition: z.record(z.string(), z.unknown()).describe('Metadata definition payload'),\n }).describe('Metadata item'),\n});\n\n/**\n * Metadata List Response\n * GET /api/meta/:type\n */\nexport const MetadataListResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.record(z.string(), z.unknown())).describe('Array of metadata definitions'),\n});\n\n/**\n * Metadata Names Response\n * GET /api/meta/:type/names\n */\nexport const MetadataNamesResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.string()).describe('Array of metadata item names'),\n});\n\n/**\n * Metadata Exists Response\n * GET /api/meta/:type/:name/exists\n */\nexport const MetadataExistsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n exists: z.boolean().describe('Whether the item exists'),\n }),\n});\n\n/**\n * Metadata Delete Response\n * DELETE /api/meta/:type/:name\n */\nexport const MetadataDeleteResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Deleted item name'),\n }),\n});\n\n// ==========================================\n// 3. Query / Search\n// ==========================================\n\n/**\n * Metadata Query Request\n * POST /api/meta/query\n */\nexport const MetadataQueryRequestSchema = MetadataQuerySchema.describe(\n 'Metadata query with filtering, sorting, and pagination',\n);\n\n/**\n * Metadata Query Response\n * POST /api/meta/query\n */\nexport const MetadataQueryResponseSchema = BaseResponseSchema.extend({\n data: MetadataQueryResultSchema.describe('Paginated query result'),\n});\n\n// ==========================================\n// 4. Bulk Operations\n// ==========================================\n\n/**\n * Bulk Register Request\n * POST /api/meta/bulk/register\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n })).min(1).describe('Items to register'),\n continueOnError: z.boolean().default(false).describe('Continue on individual failure'),\n validate: z.boolean().default(true).describe('Validate before registering'),\n});\n\n/**\n * Bulk Unregister Request\n * POST /api/meta/bulk/unregister\n */\nexport const MetadataBulkUnregisterRequestSchema = z.object({\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n })).min(1).describe('Items to unregister'),\n});\n\n/**\n * Bulk Operation Response\n * POST /api/meta/bulk/*\n */\nexport const MetadataBulkResponseSchema = BaseResponseSchema.extend({\n data: MetadataBulkResultSchema.describe('Bulk operation result'),\n});\n\n// ==========================================\n// 5. Overlay / Customization\n// ==========================================\n\n/**\n * Get Overlay Response\n * GET /api/meta/:type/:name/overlay\n */\nexport const MetadataOverlayResponseSchema = BaseResponseSchema.extend({\n data: MetadataOverlaySchema.optional().describe('Overlay definition, undefined if none'),\n});\n\n/**\n * Save Overlay Request\n * PUT /api/meta/:type/:name/overlay\n */\nexport const MetadataOverlaySaveRequestSchema = MetadataOverlaySchema.describe(\n 'Overlay to save',\n);\n\n/**\n * Get Effective (merged) Response\n * GET /api/meta/:type/:name/effective\n */\nexport const MetadataEffectiveResponseSchema = BaseResponseSchema.extend({\n data: z.record(z.string(), z.unknown()).optional()\n .describe('Effective metadata with all overlays applied'),\n});\n\n// ==========================================\n// 6. Import / Export\n// ==========================================\n\n/**\n * Export Metadata Request\n * POST /api/meta/export\n */\nexport const MetadataExportRequestSchema = z.object({\n types: z.array(z.string()).optional().describe('Filter by metadata types'),\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n format: z.enum(['json', 'yaml']).default('json').describe('Export format'),\n});\n\n/**\n * Export Metadata Response\n * POST /api/meta/export\n */\nexport const MetadataExportResponseSchema = BaseResponseSchema.extend({\n data: z.unknown().describe('Exported metadata bundle'),\n});\n\n/**\n * Import Metadata Request\n * POST /api/meta/import\n */\nexport const MetadataImportRequestSchema = z.object({\n data: z.unknown().describe('Metadata bundle to import'),\n conflictResolution: z.enum(['skip', 'overwrite', 'merge']).default('skip')\n .describe('Conflict resolution strategy'),\n validate: z.boolean().default(true).describe('Validate before import'),\n dryRun: z.boolean().default(false).describe('Dry run (no save)'),\n});\n\n/**\n * Import Metadata Response\n * POST /api/meta/import\n */\nexport const MetadataImportResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n total: z.number().int().min(0),\n imported: z.number().int().min(0),\n skipped: z.number().int().min(0),\n failed: z.number().int().min(0),\n errors: z.array(z.object({\n type: z.string(),\n name: z.string(),\n error: z.string(),\n })).optional(),\n }).describe('Import result'),\n});\n\n// ==========================================\n// 7. Validation\n// ==========================================\n\n/**\n * Validate Metadata Request\n * POST /api/meta/validate\n */\nexport const MetadataValidateRequestSchema = z.object({\n type: z.string().describe('Metadata type to validate against'),\n data: z.unknown().describe('Metadata payload to validate'),\n});\n\n/**\n * Validate Metadata Response\n * POST /api/meta/validate\n */\nexport const MetadataValidateResponseSchema = BaseResponseSchema.extend({\n data: MetadataValidationResultSchema.describe('Validation result'),\n});\n\n// ==========================================\n// 8. Type Registry\n// ==========================================\n\n/**\n * List Registered Types Response\n * GET /api/meta/types\n */\nexport const MetadataTypesResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.string()).describe('Registered metadata type identifiers'),\n});\n\n/**\n * Type Info Response\n * GET /api/meta/types/:type\n */\nexport const MetadataTypeInfoResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type identifier'),\n label: z.string().describe('Display label'),\n description: z.string().optional().describe('Description'),\n filePatterns: z.array(z.string()).describe('File glob patterns'),\n supportsOverlay: z.boolean().describe('Overlay support'),\n domain: z.string().describe('Protocol domain'),\n }).optional().describe('Type info'),\n});\n\n// ==========================================\n// 9. Dependency Tracking\n// ==========================================\n\n/**\n * Dependencies Response\n * GET /api/meta/:type/:name/dependencies\n */\nexport const MetadataDependenciesResponseSchema = BaseResponseSchema.extend({\n data: z.array(MetadataDependencySchema).describe('Items this item depends on'),\n});\n\n/**\n * Dependents Response\n * GET /api/meta/:type/:name/dependents\n */\nexport const MetadataDependentsResponseSchema = BaseResponseSchema.extend({\n data: z.array(MetadataDependencySchema).describe('Items that depend on this item'),\n});\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type ObjectDefinitionResponse = z.infer;\nexport type AppDefinitionResponse = z.infer;\nexport type ConceptListResponse = z.infer;\nexport type MetadataRegisterRequest = z.infer;\nexport type MetadataItemResponse = z.infer;\nexport type MetadataListResponse = z.infer;\nexport type MetadataNamesResponse = z.infer;\nexport type MetadataExistsResponse = z.infer;\nexport type MetadataDeleteResponse = z.infer;\nexport type MetadataQueryResponse = z.infer;\nexport type MetadataBulkResponse = z.infer;\nexport type MetadataOverlayResponse = z.infer;\nexport type MetadataEffectiveResponse = z.infer;\nexport type MetadataExportResponse = z.infer;\nexport type MetadataImportResponse = z.infer;\nexport type MetadataValidateResponse = z.infer;\nexport type MetadataTypesResponse = z.infer;\nexport type MetadataTypeInfoResponse = z.infer;\nexport type MetadataDependenciesResponse = z.infer;\nexport type MetadataDependentsResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Service Registry Protocol\n * \n * Defines the standard built-in services that constitute the ObjectStack Kernel.\n * This registry is used by the `ObjectKernel` and `HttpDispatcher` to:\n * 1. Verify service availability.\n * 2. Route requests to the correct service handler.\n * 3. Type-check service interactions.\n */\n\n// ==========================================\n// Service Identifiers\n// ==========================================\n\nexport const CoreServiceName = z.enum([\n // Core Data & Metadata\n 'metadata', // Object/Field Definitions\n 'data', // CRUD & Query Engine\n 'auth', // Authentication & Identity\n \n // Infrastructure\n 'file-storage', // Storage Driver (Local/S3)\n 'search', // Search Engine (Elastic/Meili)\n 'cache', // Cache Driver (Redis/Memory)\n 'queue', // Job Queue (BullMQ/Redis)\n \n // Advanced Capabilities\n 'automation', // Flow & Script Engine\n 'graphql', // GraphQL API Engine\n 'analytics', // BI & Semantic Layer\n 'realtime', // WebSocket & PubSub\n 'job', // Background Job Manager\n 'notification', // Email/Push/SMS\n 'ai', // AI Engine (NLQ, Chat, Suggest, Insights)\n 'i18n', // Internationalization Service\n 'ui', // UI Metadata Service (View CRUD)\n 'workflow', // Workflow State Machine Engine\n]);\n\nexport type CoreServiceName = z.infer;\n\n/**\n * Service Criticality Level\n * Defines the startup behavior when a service is missing.\n */\nexport const ServiceCriticalitySchema = z.enum([\n 'required', // System fails to start if missing (Exit Code 1)\n 'core', // System warns if missing, functionality degraded (Warn)\n 'optional', // System ignores if missing, feature disabled (Info)\n]);\n\n/**\n * Service Requirement Definition\n */\nexport const ServiceRequirementDef = {\n // Required: The kernel cannot function without these\n data: 'required',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n metadata: 'core',\n auth: 'core',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n cache: 'core',\n queue: 'core',\n job: 'core',\n i18n: 'core',\n\n // Optional: Add-on capabilities\n 'file-storage': 'optional',\n search: 'optional',\n automation: 'optional',\n graphql: 'optional',\n analytics: 'optional',\n realtime: 'optional',\n notification: 'optional',\n ai: 'optional',\n ui: 'optional',\n workflow: 'optional',\n} as const;\n\n// ==========================================\n// Service Capabilities\n// ==========================================\n\n/**\n * Describes the availability and health of a service\n */\nexport const ServiceStatusSchema = z.object({\n name: CoreServiceName,\n enabled: z.boolean(),\n status: z.enum(['running', 'stopped', 'degraded', 'initializing']),\n version: z.string().optional(),\n provider: z.string().optional().describe('Implementation provider (e.g. \"s3\" for storage)'),\n features: z.array(z.string()).optional().describe('List of supported sub-features'),\n});\n\n/**\n * The Contract definition for what the Kernel MUST expose\n * map\n */\nexport const KernelServiceMapSchema = z.record(\n CoreServiceName, \n z.unknown().describe('Service Instance implementing the protocol interface')\n);\n\n// ==========================================\n// Service Interfaces (Stub definitions)\n// ==========================================\n// Ideally, we would define strict Typescript interfaces here \n// for what methods each service must expose to the Registry.\n// For Zod, we primarily validate configuration and status.\n\n// e.g.\nexport const ServiceConfigSchema = z.object({\n id: z.string(),\n name: CoreServiceName,\n options: z.record(z.string(), z.unknown()).optional(),\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { CoreServiceName, ServiceCriticalitySchema } from '../system/core-services.zod';\n\n/**\n * # HttpDispatcher Protocol\n * \n * Defines how the ObjectStack HttpDispatcher routes incoming API requests\n * to the correct kernel service based on URL prefix matching.\n * \n * The dispatcher is the central routing component that:\n * 1. Matches incoming request URLs against registered route prefixes\n * 2. Delegates to the corresponding CoreService implementation\n * 3. Returns 503 Service Unavailable when a service is not registered\n * 4. Supports dynamic route registration from plugins via contributes.routes\n * \n * Architecture alignment:\n * - Kubernetes: API server aggregation layer\n * - Eclipse: Extension registry routing\n * - VS Code: Command palette routing\n */\n\n// ============================================================================\n// Route Definition\n// ============================================================================\n\n/**\n * Dispatcher Route Schema\n * Maps a URL prefix to a kernel service.\n * \n * @example\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"authRequired\": true,\n * \"criticality\": \"required\"\n * }\n */\nexport const DispatcherRouteSchema = z.object({\n /**\n * URL path prefix for routing.\n * Incoming requests matching this prefix are routed to the target service.\n * Must start with '/'.\n */\n prefix: z.string().regex(/^\\//).describe('URL path prefix for routing (e.g. /api/v1/data)'),\n \n /**\n * Target core service name.\n * The service that handles requests matching this prefix.\n */\n service: CoreServiceName.describe('Target core service name'),\n \n /**\n * Whether requests to this route require authentication.\n * Discovery endpoint is typically public; most others require auth.\n * @default true\n */\n authRequired: z.boolean().default(true).describe('Whether authentication is required'),\n \n /**\n * Service criticality level.\n * Determines behavior when the service is unavailable:\n * - required: return 500 Internal Server Error\n * - core: return 503 with degraded notice\n * - optional: return 503 Service Unavailable\n * @default 'optional'\n */\n criticality: ServiceCriticalitySchema.default('optional')\n .describe('Service criticality level for unavailability handling'),\n \n /**\n * Required permissions for accessing this route namespace.\n * Applied as a baseline before individual endpoint permission checks.\n */\n permissions: z.array(z.string()).optional()\n .describe('Required permissions for this route namespace'),\n});\n\nexport type DispatcherRoute = z.infer;\nexport type DispatcherRouteInput = z.input;\n\n// ============================================================================\n// Dispatcher Configuration\n// ============================================================================\n\n/**\n * Dispatcher Configuration Schema\n * Complete configuration for the HttpDispatcher routing table.\n * \n * @example\n * {\n * \"routes\": [\n * { \"prefix\": \"/api/v1/discovery\", \"service\": \"metadata\", \"authRequired\": false },\n * { \"prefix\": \"/api/v1/meta\", \"service\": \"metadata\" },\n * { \"prefix\": \"/api/v1/data\", \"service\": \"data\", \"criticality\": \"required\" },\n * { \"prefix\": \"/api/v1/auth\", \"service\": \"auth\", \"criticality\": \"required\" },\n * { \"prefix\": \"/api/v1/ai\", \"service\": \"ai\" }\n * ],\n * \"fallback\": \"404\"\n * }\n */\nexport const DispatcherConfigSchema = z.object({\n /**\n * Registered route mappings.\n * Routes are matched by longest-prefix-first strategy.\n */\n routes: z.array(DispatcherRouteSchema).describe('Route-to-service mappings'),\n \n /**\n * Behavior when no route matches the request.\n * - 404: Return 404 Not Found (default)\n * - proxy: Forward to a configured proxy target\n * - custom: Delegate to a custom handler\n * @default '404'\n */\n fallback: z.enum(['404', 'proxy', 'custom']).default('404')\n .describe('Behavior when no route matches'),\n \n /**\n * Proxy target URL for fallback: 'proxy' mode.\n */\n proxyTarget: z.string().url().optional()\n .describe('Proxy target URL when fallback is \"proxy\"'),\n});\n\nexport type DispatcherConfig = z.infer;\nexport type DispatcherConfigInput = z.input;\n\n// ============================================================================\n// Default Route Table\n// ============================================================================\n\n/**\n * Default route table for the ObjectStack HttpDispatcher.\n * Maps all Protocol namespaces to their corresponding services.\n * \n * This is the recommended baseline configuration. Plugins can extend\n * this table by declaring routes in their manifest's contributes.routes.\n */\nexport const DEFAULT_DISPATCHER_ROUTES: DispatcherRouteInput[] = [\n // Discovery (public)\n { prefix: '/api/v1/discovery', service: 'metadata', authRequired: false, criticality: 'required' },\n \n // Health (public)\n { prefix: '/api/v1/health', service: 'metadata', authRequired: false, criticality: 'required' },\n \n // Required Services\n { prefix: '/api/v1/meta', service: 'metadata', criticality: 'required' },\n { prefix: '/api/v1/data', service: 'data', criticality: 'required' },\n { prefix: '/api/v1/auth', service: 'auth', criticality: 'required' },\n \n // Optional Services (plugin-provided)\n { prefix: '/api/v1/packages', service: 'metadata' },\n { prefix: '/api/v1/ui', service: 'ui' }, // @deprecated — use /api/v1/meta/view and /api/v1/meta/dashboard instead\n { prefix: '/api/v1/workflow', service: 'workflow' },\n { prefix: '/api/v1/analytics', service: 'analytics' },\n { prefix: '/api/v1/automation', service: 'automation' },\n { prefix: '/api/v1/storage', service: 'file-storage' },\n { prefix: '/api/v1/feed', service: 'data' },\n { prefix: '/api/v1/i18n', service: 'i18n' },\n { prefix: '/api/v1/notifications', service: 'notification' },\n { prefix: '/api/v1/realtime', service: 'realtime' },\n { prefix: '/api/v1/ai', service: 'ai' },\n];\n\n// ============================================================================\n// Dispatcher Error Codes\n// ============================================================================\n\n/**\n * Semantic HTTP error codes used by the Dispatcher.\n *\n * The dispatcher MUST distinguish between these four failure modes so that\n * clients (and developers) can understand *why* an API call failed:\n *\n * - `404` – Route Not Found: no route is registered for this path.\n * - `405` – Method Not Allowed: route exists but the HTTP method is not supported.\n * - `501` – Not Implemented: route is declared but the handler is a stub / not yet coded.\n * - `503` – Service Unavailable: service exists but is temporarily down or not loaded.\n *\n * Note: These are string representations of HTTP status codes for use in enum\n * matching. The `DispatcherErrorResponseSchema.error.code` field carries the\n * numeric HTTP status code for direct use in HTTP responses.\n */\nexport const DispatcherErrorCode = z.enum(['404', '405', '501', '503']).describe(\n '404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable'\n);\n\nexport type DispatcherErrorCode = z.infer;\n\n/**\n * Dispatcher Error Response Schema\n *\n * Standardised error envelope returned by the dispatcher when a request cannot\n * be fulfilled. Adapters MUST use this shape (or a superset) for all non-2xx\n * responses so that clients can programmatically distinguish failure modes.\n */\nexport const DispatcherErrorResponseSchema = z.object({\n /** Always `false` for error responses */\n success: z.literal(false),\n error: z.object({\n /** HTTP status code */\n code: z.number().int().describe('HTTP status code (404, 405, 501, 503, …)'),\n /** Human-readable error message */\n message: z.string().describe('Human-readable error message'),\n /**\n * Machine-readable error type for programmatic branching.\n */\n type: z.enum([\n 'ROUTE_NOT_FOUND',\n 'METHOD_NOT_ALLOWED',\n 'NOT_IMPLEMENTED',\n 'SERVICE_UNAVAILABLE',\n ]).optional().describe('Machine-readable error type'),\n /** Route that was requested */\n route: z.string().optional().describe('Requested route path'),\n /** Service that the route maps to (if known) */\n service: z.string().optional().describe('Target service name, if resolvable'),\n /** Guidance for the developer */\n hint: z.string().optional().describe('Actionable hint for the developer (e.g., \"Install plugin-workflow\")'),\n }),\n});\n\nexport type DispatcherErrorResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, CorsConfigSchema, RateLimitConfigSchema, StaticMountSchema } from '../shared/http.zod';\n\n/**\n * HTTP Server Protocol\n * \n * Defines the runtime HTTP server configuration and capabilities.\n * Provides abstractions for HTTP server implementations (Express, Fastify, Hono, etc.)\n * \n * Architecture alignment:\n * - Kubernetes: Service and Ingress resources\n * - AWS: API Gateway configuration\n * - Spring Boot: Application properties\n */\n\n// ==========================================\n// Server Configuration\n// ==========================================\n\n/**\n * HTTP Server Configuration Schema\n * Core configuration for HTTP server instances\n * \n * @example\n * {\n * \"port\": 3000,\n * \"host\": \"0.0.0.0\",\n * \"cors\": {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\"]\n * },\n * \"compression\": true,\n * \"requestTimeout\": 30000\n * }\n */\nexport const HttpServerConfigSchema = z.object({\n /**\n * Server port number\n */\n port: z.number().int().min(1).max(65535).default(3000).describe('Port number to listen on'),\n \n /**\n * Server host address\n */\n host: z.string().default('0.0.0.0').describe('Host address to bind to'),\n \n /**\n * CORS configuration\n */\n cors: CorsConfigSchema.optional().describe('CORS configuration'),\n \n /**\n * Request handling options\n */\n requestTimeout: z.number().int().default(30000).describe('Request timeout in milliseconds'),\n bodyLimit: z.string().default('10mb').describe('Maximum request body size'),\n \n /**\n * Compression settings\n */\n compression: z.boolean().default(true).describe('Enable response compression'),\n \n /**\n * Security headers\n */\n security: z.object({\n helmet: z.boolean().default(true).describe('Enable security headers via helmet'),\n rateLimit: RateLimitConfigSchema.optional().describe('Global rate limiting configuration'),\n }).optional().describe('Security configuration'),\n \n /**\n * Static file serving\n */\n static: z.array(StaticMountSchema).optional().describe('Static file serving configuration'),\n \n /**\n * Trust proxy settings\n */\n trustProxy: z.boolean().default(false).describe('Trust X-Forwarded-* headers'),\n});\n\nexport type HttpServerConfig = z.infer;\nexport type HttpServerConfigInput = z.input;\n\n// ==========================================\n// Route Registration\n// ==========================================\n\n/**\n * Route Handler Metadata Schema\n * Metadata for route handlers used in registration\n */\nexport const RouteHandlerMetadataSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (supports parameters like /api/users/:id)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Handler function name or identifier\n */\n handler: z.string().describe('Handler identifier or name'),\n \n /**\n * Route metadata\n */\n metadata: z.object({\n summary: z.string().optional().describe('Route summary for documentation'),\n description: z.string().optional().describe('Route description'),\n tags: z.array(z.string()).optional().describe('Tags for grouping'),\n operationId: z.string().optional().describe('Unique operation identifier'),\n }).optional(),\n \n /**\n * Security requirements\n */\n security: z.object({\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n rateLimit: z.string().optional().describe('Rate limit policy override'),\n }).optional(),\n});\n\nexport type RouteHandlerMetadata = z.infer;\nexport type RouteHandlerMetadataInput = z.input;\n\n// ==========================================\n// Middleware Configuration\n// ==========================================\n\n/**\n * Middleware Type Enum\n */\nexport const MiddlewareType = z.enum([\n 'authentication', // Authentication middleware\n 'authorization', // Authorization/permission checks\n 'logging', // Request/response logging\n 'validation', // Input validation\n 'transformation', // Request/response transformation\n 'error', // Error handling\n 'custom', // Custom middleware\n]);\n\nexport type MiddlewareType = z.infer;\n\n/**\n * Middleware Configuration Schema\n * Defines middleware execution order and configuration\n * \n * @example\n * {\n * \"name\": \"auth_middleware\",\n * \"type\": \"authentication\",\n * \"enabled\": true,\n * \"order\": 10,\n * \"config\": {\n * \"jwtSecret\": \"secret\",\n * \"excludePaths\": [\"/health\", \"/metrics\"]\n * }\n * }\n */\nexport const MiddlewareConfigSchema = z.object({\n /**\n * Middleware identifier\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Middleware name (snake_case)'),\n \n /**\n * Middleware type\n */\n type: MiddlewareType.describe('Middleware type'),\n \n /**\n * Enable/disable middleware\n */\n enabled: z.boolean().default(true).describe('Whether middleware is enabled'),\n \n /**\n * Execution order (lower numbers execute first)\n */\n order: z.number().int().default(100).describe('Execution order priority'),\n \n /**\n * Middleware-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Middleware configuration object'),\n \n /**\n * Path patterns to apply middleware to\n */\n paths: z.object({\n include: z.array(z.string()).optional().describe('Include path patterns (glob)'),\n exclude: z.array(z.string()).optional().describe('Exclude path patterns (glob)'),\n }).optional().describe('Path filtering'),\n});\n\nexport type MiddlewareConfig = z.infer;\nexport type MiddlewareConfigInput = z.input;\n\n// ==========================================\n// Server Lifecycle Events\n// ==========================================\n\n/**\n * Server Event Type Enum\n */\nexport const ServerEventType = z.enum([\n 'starting', // Server is starting\n 'started', // Server has started and is listening\n 'stopping', // Server is stopping\n 'stopped', // Server has stopped\n 'request', // Request received\n 'response', // Response sent\n 'error', // Error occurred\n]);\n\nexport type ServerEventType = z.infer;\n\n/**\n * Server Event Schema\n * Events emitted by the HTTP server during lifecycle\n */\nexport const ServerEventSchema = z.object({\n /**\n * Event type\n */\n type: ServerEventType.describe('Event type'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp (ISO 8601)'),\n \n /**\n * Event payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Event-specific data'),\n});\n\nexport type ServerEvent = z.infer;\n\n// ==========================================\n// Server Capability Declaration\n// ==========================================\n\n/**\n * Server Capabilities Schema\n * Declares what features a server implementation supports\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Supported HTTP versions\n */\n httpVersions: z.array(z.enum(['1.0', '1.1', '2.0', '3.0'])).default(['1.1']).describe('Supported HTTP versions'),\n \n /**\n * WebSocket support\n */\n websocket: z.boolean().default(false).describe('WebSocket support'),\n \n /**\n * Server-Sent Events support\n */\n sse: z.boolean().default(false).describe('Server-Sent Events support'),\n \n /**\n * HTTP/2 Server Push\n */\n serverPush: z.boolean().default(false).describe('HTTP/2 Server Push support'),\n \n /**\n * Streaming support\n */\n streaming: z.boolean().default(true).describe('Response streaming support'),\n \n /**\n * Middleware support\n */\n middleware: z.boolean().default(true).describe('Middleware chain support'),\n \n /**\n * Route parameterization\n */\n routeParams: z.boolean().default(true).describe('URL parameter support (/users/:id)'),\n \n /**\n * Built-in compression\n */\n compression: z.boolean().default(true).describe('Built-in compression support'),\n});\n\nexport type ServerCapabilities = z.infer;\nexport type ServerCapabilitiesInput = z.input;\n\n// ==========================================\n// Server Status & Metrics\n// ==========================================\n\n/**\n * Server Status Schema\n * Current operational status of the server\n */\nexport const ServerStatusSchema = z.object({\n /**\n * Server state\n */\n state: z.enum(['stopped', 'starting', 'running', 'stopping', 'error']).describe('Current server state'),\n \n /**\n * Uptime in milliseconds\n */\n uptime: z.number().int().optional().describe('Server uptime in milliseconds'),\n \n /**\n * Server information\n */\n server: z.object({\n port: z.number().int().describe('Listening port'),\n host: z.string().describe('Bound host'),\n url: z.string().optional().describe('Full server URL'),\n }).optional(),\n \n /**\n * Connection metrics\n */\n connections: z.object({\n active: z.number().int().describe('Active connections'),\n total: z.number().int().describe('Total connections handled'),\n }).optional(),\n \n /**\n * Request metrics\n */\n requests: z.object({\n total: z.number().int().describe('Total requests processed'),\n success: z.number().int().describe('Successful requests'),\n errors: z.number().int().describe('Failed requests'),\n }).optional(),\n});\n\nexport type ServerStatus = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create HTTP server configuration\n */\nexport const HttpServerConfig = Object.assign(HttpServerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create middleware configuration\n */\nexport const MiddlewareConfig = Object.assign(MiddlewareConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\nimport { MiddlewareConfigSchema } from '../system/http-server.zod';\n\n/**\n * REST API Plugin Protocol\n * \n * Defines the schema for REST API plugins that register Discovery, Metadata,\n * Data CRUD, Batch, and Permission routes with the HTTP Dispatcher.\n * \n * This plugin type implements Phase 2 of the API Protocol implementation plan,\n * providing standardized REST endpoints with:\n * - Request validation middleware using Zod schemas\n * - Response envelope wrapping with BaseResponseSchema\n * - Error handling using ApiErrorSchema\n * - OpenAPI documentation auto-generation\n * \n * Features:\n * - Route registration for core API endpoints\n * - Automatic schema-based validation\n * - Standardized request/response envelopes\n * - OpenAPI/Swagger documentation generation\n * \n * Architecture Alignment:\n * - Salesforce: REST API with metadata and data CRUD\n * - Microsoft Dynamics: Web API with entity operations\n * - Strapi: Auto-generated REST endpoints from schemas\n * \n * @example Plugin Manifest\n * ```typescript\n * {\n * \"name\": \"rest_api\",\n * \"version\": \"1.0.0\",\n * \"type\": \"server\",\n * \"contributes\": {\n * \"routes\": [\n * {\n * \"prefix\": \"/api/v1/discovery\",\n * \"service\": \"metadata\",\n * \"methods\": [\"getDiscovery\"],\n * \"middleware\": [\n * { \"name\": \"response_envelope\", \"type\": \"transformation\", \"enabled\": true }\n * ]\n * },\n * {\n * \"prefix\": \"/api/v1/meta\",\n * \"service\": \"metadata\",\n * \"methods\": [\"getMetaTypes\", \"getMetaItems\", \"getMetaItem\", \"saveMetaItem\"],\n * \"middleware\": [\n * { \"name\": \"auth\", \"type\": \"authentication\", \"enabled\": true },\n * { \"name\": \"request_validation\", \"type\": \"validation\", \"enabled\": true }\n * ]\n * },\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"methods\": [\"findData\", \"getData\", \"createData\", \"updateData\", \"deleteData\"]\n * }\n * ]\n * }\n * }\n * ```\n */\n\n// ==========================================\n// REST API Route Categories\n// ==========================================\n\n/**\n * REST API Route Category Enum\n * Categorizes REST API routes by their primary function\n */\nexport const RestApiRouteCategory = z.enum([\n 'discovery', // API discovery and capabilities\n 'metadata', // Metadata operations (objects, fields, views)\n 'data', // Data CRUD operations\n 'batch', // Batch/bulk operations\n 'permission', // Permission/authorization checks\n 'analytics', // Analytics and reporting\n 'automation', // Automation triggers and flows\n 'workflow', // Workflow state management\n 'ui', // UI metadata (views, layouts)\n 'realtime', // Realtime/WebSocket\n 'notification', // Notification management\n 'ai', // AI operations (NLQ, chat)\n 'i18n', // Internationalization\n]);\n\nexport type RestApiRouteCategory = z.infer;\n\n// ==========================================\n// Route Registration Schema\n// ==========================================\n\n/**\n * Handler Implementation Status\n * Shared enum for tracking whether an endpoint has a real handler.\n * Used by both `RestApiEndpointSchema` and `RouteCoverageEntrySchema`.\n *\n * - `implemented` – A real handler is coded and registered.\n * - `stub` – A placeholder handler exists that returns 501 Not Implemented.\n * - `planned` – Declared in the protocol spec but not yet implemented.\n */\nexport const HandlerStatusSchema = z.enum(['implemented', 'stub', 'planned']);\nexport type HandlerStatus = z.infer;\n\n/**\n * REST API Endpoint Schema\n * Defines a single REST API endpoint with its metadata\n * \n * @example Discovery Endpoint\n * {\n * \"method\": \"GET\",\n * \"path\": \"/api/v1/discovery\",\n * \"handler\": \"getDiscovery\",\n * \"category\": \"discovery\",\n * \"public\": true,\n * \"description\": \"Get API discovery information\"\n * }\n */\nexport const RestApiEndpointSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method for this endpoint'),\n \n /**\n * URL path pattern (supports parameters like :id)\n */\n path: z.string().describe('URL path pattern (e.g., /api/v1/data/:object/:id)'),\n \n /**\n * Handler reference (protocol method name)\n */\n handler: z.string().describe('Protocol method name or handler identifier'),\n \n /**\n * Route category\n */\n category: RestApiRouteCategory.describe('Route category'),\n \n /**\n * Whether endpoint is publicly accessible (no auth required)\n */\n public: z.boolean().default(false).describe('Is publicly accessible without authentication'),\n \n /**\n * Required permissions\n */\n permissions: z.array(z.string()).optional().describe('Required permissions (e.g., [\"data.read\", \"object.account.read\"])'),\n \n /**\n * OpenAPI documentation metadata\n */\n summary: z.string().optional().describe('Short description for OpenAPI'),\n description: z.string().optional().describe('Detailed description for OpenAPI'),\n tags: z.array(z.string()).optional().describe('OpenAPI tags for grouping'),\n \n /**\n * Request/Response schema references\n */\n requestSchema: z.string().optional().describe('Request schema name (for validation)'),\n responseSchema: z.string().optional().describe('Response schema name (for documentation)'),\n \n /**\n * Performance and reliability settings\n */\n timeout: z.number().int().optional().describe('Request timeout in milliseconds'),\n rateLimit: z.string().optional().describe('Rate limit policy name'),\n cacheable: z.boolean().default(false).describe('Whether response can be cached'),\n cacheTtl: z.number().int().optional().describe('Cache TTL in seconds'),\n\n /**\n * Handler implementation status.\n * Tracks whether this endpoint has a real handler or is only declared.\n *\n * - `implemented` – A real handler is coded and registered.\n * - `stub` – A placeholder handler exists that returns 501 Not Implemented.\n * - `planned` – Declared in the protocol spec but not yet implemented.\n * @default 'implemented'\n */\n handlerStatus: HandlerStatusSchema.optional()\n .describe('Handler implementation status: implemented (default if omitted), stub, or planned'),\n});\n\nexport type RestApiEndpoint = z.infer;\n\n/**\n * REST API Route Registration Schema\n * Registers a group of related endpoints under a common prefix\n * \n * @example Data CRUD Routes\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"category\": \"data\",\n * \"endpoints\": [\n * { \"method\": \"GET\", \"path\": \"/:object\", \"handler\": \"findData\" },\n * { \"method\": \"GET\", \"path\": \"/:object/:id\", \"handler\": \"getData\" },\n * { \"method\": \"POST\", \"path\": \"/:object\", \"handler\": \"createData\" },\n * { \"method\": \"PATCH\", \"path\": \"/:object/:id\", \"handler\": \"updateData\" },\n * { \"method\": \"DELETE\", \"path\": \"/:object/:id\", \"handler\": \"deleteData\" }\n * ],\n * \"middleware\": [\n * { \"name\": \"auth\", \"type\": \"authentication\", \"enabled\": true },\n * { \"name\": \"validation\", \"type\": \"validation\", \"enabled\": true },\n * { \"name\": \"response_envelope\", \"type\": \"transformation\", \"enabled\": true }\n * ]\n * }\n */\nexport const RestApiRouteRegistrationSchema = z.object({\n /**\n * URL prefix for this route group (e.g., /api/v1/data)\n */\n prefix: z.string().regex(/^\\//).describe('URL path prefix for this route group'),\n \n /**\n * Service name that handles these routes\n */\n service: z.string().describe('Core service name (metadata, data, auth, etc.)'),\n \n /**\n * Route category\n */\n category: RestApiRouteCategory.describe('Primary category for this route group'),\n \n /**\n * Protocol methods implemented\n */\n methods: z.array(z.string()).optional().describe('Protocol method names implemented'),\n \n /**\n * Detailed endpoint definitions\n */\n endpoints: z.array(RestApiEndpointSchema).optional().describe('Endpoint definitions'),\n \n /**\n * Middleware applied to all routes in this group\n */\n middleware: z.array(MiddlewareConfigSchema).optional().describe('Middleware stack for this route group'),\n \n /**\n * Whether authentication is required for all routes\n */\n authRequired: z.boolean().default(true).describe('Whether authentication is required by default'),\n \n /**\n * OpenAPI documentation\n */\n documentation: z.object({\n title: z.string().optional().describe('Route group title'),\n description: z.string().optional().describe('Route group description'),\n tags: z.array(z.string()).optional().describe('OpenAPI tags'),\n }).optional().describe('Documentation metadata for this route group'),\n});\n\nexport type RestApiRouteRegistration = z.infer;\n\n// ==========================================\n// Request Validation Configuration\n// ==========================================\n\n/**\n * Request Validation Mode Enum\n * Defines how validation errors are handled\n */\nexport const ValidationMode = z.enum([\n 'strict', // Reject requests with validation errors (400 Bad Request)\n 'permissive', // Log validation errors but allow request to proceed\n 'strip', // Remove invalid fields and continue with valid data\n]);\n\nexport type ValidationMode = z.infer;\n\n/**\n * Request Validation Configuration Schema\n * Configures Zod-based request validation middleware\n * \n * @example\n * {\n * \"enabled\": true,\n * \"mode\": \"strict\",\n * \"validateBody\": true,\n * \"validateQuery\": true,\n * \"validateParams\": true,\n * \"includeFieldErrors\": true\n * }\n */\nexport const RequestValidationConfigSchema = z.object({\n /**\n * Enable request validation\n */\n enabled: z.boolean().default(true).describe('Enable automatic request validation'),\n \n /**\n * Validation mode\n */\n mode: ValidationMode.default('strict').describe('How to handle validation errors'),\n \n /**\n * Validate request body\n */\n validateBody: z.boolean().default(true).describe('Validate request body against schema'),\n \n /**\n * Validate query parameters\n */\n validateQuery: z.boolean().default(true).describe('Validate query string parameters'),\n \n /**\n * Validate URL parameters\n */\n validateParams: z.boolean().default(true).describe('Validate URL path parameters'),\n \n /**\n * Validate request headers\n */\n validateHeaders: z.boolean().default(false).describe('Validate request headers'),\n \n /**\n * Include detailed field errors in response\n */\n includeFieldErrors: z.boolean().default(true).describe('Include field-level error details in response'),\n \n /**\n * Custom error message prefix\n */\n errorPrefix: z.string().optional().describe('Custom prefix for validation error messages'),\n \n /**\n * Schema registry reference\n */\n schemaRegistry: z.string().optional().describe('Schema registry name to use for validation'),\n});\n\nexport type RequestValidationConfig = z.infer;\nexport type RequestValidationConfigInput = z.input;\n\n// ==========================================\n// Response Envelope Configuration\n// ==========================================\n\n/**\n * Response Envelope Configuration Schema\n * Configures automatic response wrapping with BaseResponseSchema\n * \n * @example\n * {\n * \"enabled\": true,\n * \"includeMetadata\": true,\n * \"includeTimestamp\": true,\n * \"includeRequestId\": true,\n * \"includeDuration\": true\n * }\n */\nexport const ResponseEnvelopeConfigSchema = z.object({\n /**\n * Enable response envelope wrapping\n */\n enabled: z.boolean().default(true).describe('Enable automatic response envelope wrapping'),\n \n /**\n * Include metadata object\n */\n includeMetadata: z.boolean().default(true).describe('Include meta object in responses'),\n \n /**\n * Include timestamp in metadata\n */\n includeTimestamp: z.boolean().default(true).describe('Include timestamp in response metadata'),\n \n /**\n * Include request ID in metadata\n */\n includeRequestId: z.boolean().default(true).describe('Include requestId in response metadata'),\n \n /**\n * Include request duration in metadata\n */\n includeDuration: z.boolean().default(false).describe('Include request duration in ms'),\n \n /**\n * Include trace ID for distributed tracing\n */\n includeTraceId: z.boolean().default(false).describe('Include distributed traceId'),\n \n /**\n * Custom metadata fields\n */\n customMetadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata fields to include'),\n \n /**\n * Whether to wrap already-wrapped responses\n */\n skipIfWrapped: z.boolean().default(true).describe('Skip wrapping if response already has success field'),\n});\n\nexport type ResponseEnvelopeConfig = z.infer;\nexport type ResponseEnvelopeConfigInput = z.input;\n\n// ==========================================\n// Error Handling Configuration\n// ==========================================\n\n/**\n * Error Handling Configuration Schema\n * Configures error handling and ApiErrorSchema formatting\n * \n * @example\n * {\n * \"enabled\": true,\n * \"includeStackTrace\": false,\n * \"logErrors\": true,\n * \"exposeInternalErrors\": false,\n * \"customErrorMessages\": {\n * \"validation_error\": \"The request data is invalid. Please check your input.\"\n * }\n * }\n */\nexport const ErrorHandlingConfigSchema = z.object({\n /**\n * Enable standardized error handling\n */\n enabled: z.boolean().default(true).describe('Enable standardized error handling'),\n \n /**\n * Include stack traces in error responses (dev only)\n */\n includeStackTrace: z.boolean().default(false).describe('Include stack traces in error responses'),\n \n /**\n * Log errors to logger\n */\n logErrors: z.boolean().default(true).describe('Log errors to system logger'),\n \n /**\n * Expose internal error details\n */\n exposeInternalErrors: z.boolean().default(false).describe('Expose internal error details in responses'),\n \n /**\n * Include request ID in errors\n */\n includeRequestId: z.boolean().default(true).describe('Include requestId in error responses'),\n \n /**\n * Include timestamp in errors\n */\n includeTimestamp: z.boolean().default(true).describe('Include timestamp in error responses'),\n \n /**\n * Include error documentation URLs\n */\n includeDocumentation: z.boolean().default(true).describe('Include documentation URLs for errors'),\n \n /**\n * Documentation base URL\n */\n documentationBaseUrl: z.string().url().optional().describe('Base URL for error documentation'),\n \n /**\n * Custom error messages by code\n */\n customErrorMessages: z.record(z.string(), z.string()).optional()\n .describe('Custom error messages by error code'),\n \n /**\n * Sensitive fields to redact from error details\n */\n redactFields: z.array(z.string()).optional().describe('Field names to redact from error details'),\n});\n\nexport type ErrorHandlingConfig = z.infer;\nexport type ErrorHandlingConfigInput = z.input;\n\n// ==========================================\n// OpenAPI Documentation Configuration\n// ==========================================\n\n/**\n * OpenAPI Generation Configuration Schema\n * Configures automatic OpenAPI documentation generation\n * \n * @example\n * {\n * \"enabled\": true,\n * \"version\": \"3.0.0\",\n * \"title\": \"ObjectStack API\",\n * \"description\": \"ObjectStack REST API\",\n * \"outputPath\": \"/api/docs/openapi.json\",\n * \"uiPath\": \"/api/docs\",\n * \"includeInternal\": false,\n * \"generateSchemas\": true\n * }\n */\nexport const OpenApiGenerationConfigSchema = z.object({\n /**\n * Enable OpenAPI generation\n */\n enabled: z.boolean().default(true).describe('Enable automatic OpenAPI documentation generation'),\n \n /**\n * OpenAPI specification version\n */\n version: z.enum(['3.0.0', '3.0.1', '3.0.2', '3.0.3', '3.1.0']).default('3.0.3')\n .describe('OpenAPI specification version'),\n \n /**\n * API title\n */\n title: z.string().default('ObjectStack API').describe('API title'),\n \n /**\n * API description\n */\n description: z.string().optional().describe('API description'),\n \n /**\n * API version\n */\n apiVersion: z.string().default('1.0.0').describe('API version'),\n \n /**\n * Output path for OpenAPI spec\n */\n outputPath: z.string().default('/api/docs/openapi.json').describe('URL path to serve OpenAPI JSON'),\n \n /**\n * UI path for Swagger/Redoc\n */\n uiPath: z.string().default('/api/docs').describe('URL path to serve documentation UI'),\n \n /**\n * UI framework to use\n */\n uiFramework: z.enum(['swagger-ui', 'redoc', 'rapidoc', 'elements']).default('swagger-ui')\n .describe('Documentation UI framework'),\n \n /**\n * Include internal/admin endpoints\n */\n includeInternal: z.boolean().default(false).describe('Include internal endpoints in documentation'),\n \n /**\n * Generate JSON schemas from Zod\n */\n generateSchemas: z.boolean().default(true).describe('Auto-generate schemas from Zod definitions'),\n \n /**\n * Include examples in documentation\n */\n includeExamples: z.boolean().default(true).describe('Include request/response examples'),\n \n /**\n * Server URLs\n */\n servers: z.array(z.object({\n url: z.string().describe('Server URL'),\n description: z.string().optional().describe('Server description'),\n })).optional().describe('Server URLs for API'),\n \n /**\n * Contact information\n */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('API contact information'),\n \n /**\n * License information\n */\n license: z.object({\n name: z.string().describe('License name'),\n url: z.string().url().optional().describe('License URL'),\n }).optional().describe('API license information'),\n \n /**\n * Security schemes\n */\n securitySchemes: z.record(z.string(), z.object({\n type: z.enum(['apiKey', 'http', 'oauth2', 'openIdConnect']),\n scheme: z.string().optional(),\n bearerFormat: z.string().optional(),\n })).optional().describe('Security scheme definitions'),\n});\n\nexport type OpenApiGenerationConfig = z.infer;\nexport type OpenApiGenerationConfigInput = z.input;\n\n// ==========================================\n// REST API Plugin Configuration\n// ==========================================\n\n/**\n * REST API Plugin Configuration Schema\n * Complete configuration for REST API plugin\n * \n * @example\n * {\n * \"enabled\": true,\n * \"basePath\": \"/api\",\n * \"version\": \"v1\",\n * \"routes\": [...],\n * \"validation\": { \"enabled\": true, \"mode\": \"strict\" },\n * \"responseEnvelope\": { \"enabled\": true, \"includeMetadata\": true },\n * \"errorHandling\": { \"enabled\": true, \"includeStackTrace\": false },\n * \"openApi\": { \"enabled\": true, \"title\": \"ObjectStack API\" }\n * }\n */\nexport const RestApiPluginConfigSchema = z.object({\n /**\n * Enable REST API plugin\n */\n enabled: z.boolean().default(true).describe('Enable REST API plugin'),\n \n /**\n * API base path\n */\n basePath: z.string().default('/api').describe('Base path for all API routes'),\n \n /**\n * API version\n */\n version: z.string().default('v1').describe('API version identifier'),\n \n /**\n * Route registrations\n */\n routes: z.array(RestApiRouteRegistrationSchema).describe('Route registrations'),\n \n /**\n * Request validation configuration\n */\n validation: RequestValidationConfigSchema.optional().describe('Request validation configuration'),\n \n /**\n * Response envelope configuration\n */\n responseEnvelope: ResponseEnvelopeConfigSchema.optional().describe('Response envelope configuration'),\n \n /**\n * Error handling configuration\n */\n errorHandling: ErrorHandlingConfigSchema.optional().describe('Error handling configuration'),\n \n /**\n * OpenAPI documentation configuration\n */\n openApi: OpenApiGenerationConfigSchema.optional().describe('OpenAPI documentation configuration'),\n \n /**\n * Global middleware applied to all routes\n */\n globalMiddleware: z.array(MiddlewareConfigSchema).optional().describe('Global middleware stack'),\n \n /**\n * CORS configuration\n */\n cors: z.object({\n enabled: z.boolean().default(true),\n origins: z.array(z.string()).optional(),\n methods: z.array(HttpMethod).optional(),\n credentials: z.boolean().default(true),\n }).optional().describe('CORS configuration'),\n \n /**\n * Performance settings\n */\n performance: z.object({\n enableCompression: z.boolean().default(true).describe('Enable response compression'),\n enableETag: z.boolean().default(true).describe('Enable ETag generation'),\n enableCaching: z.boolean().default(true).describe('Enable HTTP caching'),\n defaultCacheTtl: z.number().int().default(300).describe('Default cache TTL in seconds'),\n }).optional().describe('Performance optimization settings'),\n});\n\nexport type RestApiPluginConfig = z.infer;\nexport type RestApiPluginConfigInput = z.input;\n\n// ==========================================\n// Default Route Registrations\n// ==========================================\n\n/**\n * Default Discovery Routes\n * Standard routes for API discovery endpoint\n */\nexport const DEFAULT_DISCOVERY_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/discovery',\n service: 'metadata',\n category: 'discovery',\n methods: ['getDiscovery'],\n authRequired: false,\n endpoints: [{\n method: 'GET',\n path: '',\n handler: 'getDiscovery',\n category: 'discovery',\n public: true,\n summary: 'Get API discovery information',\n description: 'Returns API version, capabilities, and available routes',\n tags: ['Discovery'],\n responseSchema: 'GetDiscoveryResponseSchema',\n cacheable: true,\n cacheTtl: 3600, // Cache for 1 hour as discovery info rarely changes\n }],\n middleware: [\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n/**\n * Default Metadata Routes\n * Standard routes for metadata operations\n * \n * Note: getMetaItemCached is not a separate endpoint - it's handled by the getMetaItem\n * endpoint with HTTP cache headers (ETag, If-None-Match, etc.) for conditional requests.\n */\nexport const DEFAULT_METADATA_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/meta',\n service: 'metadata',\n category: 'metadata',\n methods: ['getMetaTypes', 'getMetaItems', 'getMetaItem', 'saveMetaItem'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '',\n handler: 'getMetaTypes',\n category: 'metadata',\n public: false,\n summary: 'List all metadata types',\n description: 'Returns available metadata types (object, field, view, etc.)',\n tags: ['Metadata'],\n responseSchema: 'GetMetaTypesResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:type',\n handler: 'getMetaItems',\n category: 'metadata',\n public: false,\n summary: 'List metadata items of a type',\n description: 'Returns all items of the specified metadata type',\n tags: ['Metadata'],\n responseSchema: 'GetMetaItemsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:type/:name',\n handler: 'getMetaItem',\n category: 'metadata',\n public: false,\n summary: 'Get specific metadata item',\n description: 'Returns a specific metadata item by type and name',\n tags: ['Metadata'],\n requestSchema: 'GetMetaItemRequestSchema',\n responseSchema: 'GetMetaItemResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'PUT',\n path: '/:type/:name',\n handler: 'saveMetaItem',\n category: 'metadata',\n public: false,\n summary: 'Create or update metadata item',\n description: 'Creates or updates a metadata item',\n tags: ['Metadata'],\n requestSchema: 'SaveMetaItemRequestSchema',\n responseSchema: 'SaveMetaItemResponseSchema',\n permissions: ['metadata.write'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n/**\n * Default Data CRUD Routes\n * Standard routes for data operations\n */\nexport const DEFAULT_DATA_CRUD_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/data',\n service: 'data',\n category: 'data',\n methods: ['findData', 'getData', 'createData', 'updateData', 'deleteData'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/:object',\n handler: 'findData',\n category: 'data',\n public: false,\n summary: 'Query records',\n description: 'Query records with filtering, sorting, and pagination',\n tags: ['Data'],\n requestSchema: 'FindDataRequestSchema',\n responseSchema: 'ListRecordResponseSchema',\n permissions: ['data.read'],\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/:object/:id',\n handler: 'getData',\n category: 'data',\n public: false,\n summary: 'Get record by ID',\n description: 'Retrieve a single record by its ID',\n tags: ['Data'],\n requestSchema: 'IdRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.read'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object',\n handler: 'createData',\n category: 'data',\n public: false,\n summary: 'Create record',\n description: 'Create a new record',\n tags: ['Data'],\n requestSchema: 'CreateRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.create'],\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/:object/:id',\n handler: 'updateData',\n category: 'data',\n public: false,\n summary: 'Update record',\n description: 'Update an existing record',\n tags: ['Data'],\n requestSchema: 'UpdateRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.update'],\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/:object/:id',\n handler: 'deleteData',\n category: 'data',\n public: false,\n summary: 'Delete record',\n description: 'Delete a record by ID',\n tags: ['Data'],\n requestSchema: 'IdRequestSchema',\n responseSchema: 'DeleteResponseSchema',\n permissions: ['data.delete'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n/**\n * Default Batch Routes\n * Standard routes for batch operations\n */\nexport const DEFAULT_BATCH_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/data/:object',\n service: 'data',\n category: 'batch',\n methods: ['batchData', 'createManyData', 'updateManyData', 'deleteManyData'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/batch',\n handler: 'batchData',\n category: 'batch',\n public: false,\n summary: 'Batch operation',\n description: 'Execute a batch operation (create, update, upsert, delete)',\n tags: ['Batch'],\n requestSchema: 'BatchUpdateRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.batch'],\n timeout: 60000, // 60 seconds for batch operations\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/createMany',\n handler: 'createManyData',\n category: 'batch',\n public: false,\n summary: 'Batch create',\n description: 'Create multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'CreateManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.create', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/updateMany',\n handler: 'updateManyData',\n category: 'batch',\n public: false,\n summary: 'Batch update',\n description: 'Update multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'UpdateManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.update', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/deleteMany',\n handler: 'deleteManyData',\n category: 'batch',\n public: false,\n summary: 'Batch delete',\n description: 'Delete multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'DeleteManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.delete', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n/**\n * Default Permission Routes\n * Standard routes for permission checking\n */\nexport const DEFAULT_PERMISSION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/auth',\n service: 'auth',\n category: 'permission',\n methods: ['checkPermission', 'getObjectPermissions', 'getEffectivePermissions'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/check',\n handler: 'checkPermission',\n category: 'permission',\n public: false,\n summary: 'Check permission',\n description: 'Check if current user has a specific permission',\n tags: ['Permission'],\n requestSchema: 'CheckPermissionRequestSchema',\n responseSchema: 'CheckPermissionResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/permissions/:object',\n handler: 'getObjectPermissions',\n category: 'permission',\n public: false,\n summary: 'Get object permissions',\n description: 'Get all permissions for a specific object',\n tags: ['Permission'],\n responseSchema: 'ObjectPermissionsResponseSchema',\n cacheable: true,\n cacheTtl: 300,\n },\n {\n method: 'GET',\n path: '/permissions/effective',\n handler: 'getEffectivePermissions',\n category: 'permission',\n public: false,\n summary: 'Get effective permissions',\n description: 'Get all effective permissions for current user',\n tags: ['Permission'],\n responseSchema: 'EffectivePermissionsResponseSchema',\n cacheable: true,\n cacheTtl: 300,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// View Management Routes\n// ==========================================\n\n/**\n * Default View Management Routes\n * Standard routes for UI view CRUD operations\n */\nexport const DEFAULT_VIEW_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/ui',\n service: 'ui',\n category: 'ui',\n methods: ['listViews', 'getView', 'createView', 'updateView', 'deleteView'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/views/:object',\n handler: 'listViews',\n category: 'ui',\n public: false,\n summary: 'List views for an object',\n description: 'Returns all views (list, form) for the specified object',\n tags: ['Views', 'UI'],\n responseSchema: 'ListViewsResponseSchema',\n cacheable: true,\n cacheTtl: 1800,\n },\n {\n method: 'GET',\n path: '/views/:object/:viewId',\n handler: 'getView',\n category: 'ui',\n public: false,\n summary: 'Get a specific view',\n description: 'Returns a specific view definition by object and view ID',\n tags: ['Views', 'UI'],\n responseSchema: 'GetViewResponseSchema',\n cacheable: true,\n cacheTtl: 1800,\n },\n {\n method: 'POST',\n path: '/views/:object',\n handler: 'createView',\n category: 'ui',\n public: false,\n summary: 'Create a new view',\n description: 'Creates a new view definition for the specified object',\n tags: ['Views', 'UI'],\n requestSchema: 'CreateViewRequestSchema',\n responseSchema: 'CreateViewResponseSchema',\n permissions: ['ui.view.create'],\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/views/:object/:viewId',\n handler: 'updateView',\n category: 'ui',\n public: false,\n summary: 'Update a view',\n description: 'Updates an existing view definition',\n tags: ['Views', 'UI'],\n requestSchema: 'UpdateViewRequestSchema',\n responseSchema: 'UpdateViewResponseSchema',\n permissions: ['ui.view.update'],\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/views/:object/:viewId',\n handler: 'deleteView',\n category: 'ui',\n public: false,\n summary: 'Delete a view',\n description: 'Deletes a view definition',\n tags: ['Views', 'UI'],\n responseSchema: 'DeleteViewResponseSchema',\n permissions: ['ui.view.delete'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Workflow Routes\n// ==========================================\n\n/**\n * Default Workflow Routes\n * Standard routes for workflow state management and transitions\n */\nexport const DEFAULT_WORKFLOW_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/workflow',\n service: 'workflow',\n category: 'workflow',\n methods: ['getWorkflowConfig', 'getWorkflowState', 'workflowTransition', 'workflowApprove', 'workflowReject'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/:object/config',\n handler: 'getWorkflowConfig',\n category: 'workflow',\n public: false,\n summary: 'Get workflow configuration',\n description: 'Returns workflow rules and state machine configuration for an object',\n tags: ['Workflow'],\n responseSchema: 'GetWorkflowConfigResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:object/:recordId/state',\n handler: 'getWorkflowState',\n category: 'workflow',\n public: false,\n summary: 'Get workflow state',\n description: 'Returns current workflow state and available transitions for a record',\n tags: ['Workflow'],\n responseSchema: 'GetWorkflowStateResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/transition',\n handler: 'workflowTransition',\n category: 'workflow',\n public: false,\n summary: 'Execute workflow transition',\n description: 'Transitions a record to a new workflow state',\n tags: ['Workflow'],\n requestSchema: 'WorkflowTransitionRequestSchema',\n responseSchema: 'WorkflowTransitionResponseSchema',\n permissions: ['workflow.transition'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/approve',\n handler: 'workflowApprove',\n category: 'workflow',\n public: false,\n summary: 'Approve workflow step',\n description: 'Approves a pending workflow approval step',\n tags: ['Workflow'],\n requestSchema: 'WorkflowApproveRequestSchema',\n responseSchema: 'WorkflowApproveResponseSchema',\n permissions: ['workflow.approve'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/reject',\n handler: 'workflowReject',\n category: 'workflow',\n public: false,\n summary: 'Reject workflow step',\n description: 'Rejects a pending workflow approval step',\n tags: ['Workflow'],\n requestSchema: 'WorkflowRejectRequestSchema',\n responseSchema: 'WorkflowRejectResponseSchema',\n permissions: ['workflow.reject'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Realtime Routes\n// ==========================================\n\n/**\n * Default Realtime Routes\n * Standard routes for realtime connection management and subscriptions\n */\nexport const DEFAULT_REALTIME_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/realtime',\n service: 'realtime',\n category: 'realtime',\n methods: ['realtimeConnect', 'realtimeDisconnect', 'realtimeSubscribe', 'realtimeUnsubscribe', 'setPresence', 'getPresence'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/connect',\n handler: 'realtimeConnect',\n category: 'realtime',\n public: false,\n summary: 'Establish realtime connection',\n description: 'Negotiates a realtime connection (WebSocket/SSE) and returns connection details',\n tags: ['Realtime'],\n requestSchema: 'RealtimeConnectRequestSchema',\n responseSchema: 'RealtimeConnectResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/disconnect',\n handler: 'realtimeDisconnect',\n category: 'realtime',\n public: false,\n summary: 'Close realtime connection',\n description: 'Closes an active realtime connection',\n tags: ['Realtime'],\n requestSchema: 'RealtimeDisconnectRequestSchema',\n responseSchema: 'RealtimeDisconnectResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/subscribe',\n handler: 'realtimeSubscribe',\n category: 'realtime',\n public: false,\n summary: 'Subscribe to channel',\n description: 'Subscribes to a realtime channel for receiving events',\n tags: ['Realtime'],\n requestSchema: 'RealtimeSubscribeRequestSchema',\n responseSchema: 'RealtimeSubscribeResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/unsubscribe',\n handler: 'realtimeUnsubscribe',\n category: 'realtime',\n public: false,\n summary: 'Unsubscribe from channel',\n description: 'Unsubscribes from a realtime channel',\n tags: ['Realtime'],\n requestSchema: 'RealtimeUnsubscribeRequestSchema',\n responseSchema: 'RealtimeUnsubscribeResponseSchema',\n cacheable: false,\n },\n {\n method: 'PUT',\n path: '/presence/:channel',\n handler: 'setPresence',\n category: 'realtime',\n public: false,\n summary: 'Set presence state',\n description: 'Sets the current user\\'s presence state in a channel',\n tags: ['Realtime'],\n requestSchema: 'SetPresenceRequestSchema',\n responseSchema: 'SetPresenceResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/presence/:channel',\n handler: 'getPresence',\n category: 'realtime',\n public: false,\n summary: 'Get channel presence',\n description: 'Returns all active members and their presence state in a channel',\n tags: ['Realtime'],\n responseSchema: 'GetPresenceResponseSchema',\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Notification Routes\n// ==========================================\n\n/**\n * Default Notification Routes\n * Standard routes for notification management (device registration, preferences, listing)\n */\nexport const DEFAULT_NOTIFICATION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/notifications',\n service: 'notification',\n category: 'notification',\n methods: [\n 'registerDevice', 'unregisterDevice',\n 'getNotificationPreferences', 'updateNotificationPreferences',\n 'listNotifications', 'markNotificationsRead', 'markAllNotificationsRead',\n ],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/devices',\n handler: 'registerDevice',\n category: 'notification',\n public: false,\n summary: 'Register device for push notifications',\n description: 'Registers a device token for receiving push notifications',\n tags: ['Notifications'],\n requestSchema: 'RegisterDeviceRequestSchema',\n responseSchema: 'RegisterDeviceResponseSchema',\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/devices/:deviceId',\n handler: 'unregisterDevice',\n category: 'notification',\n public: false,\n summary: 'Unregister device',\n description: 'Removes a device from push notification registration',\n tags: ['Notifications'],\n responseSchema: 'UnregisterDeviceResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/preferences',\n handler: 'getNotificationPreferences',\n category: 'notification',\n public: false,\n summary: 'Get notification preferences',\n description: 'Returns current user notification preferences',\n tags: ['Notifications'],\n responseSchema: 'GetNotificationPreferencesResponseSchema',\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/preferences',\n handler: 'updateNotificationPreferences',\n category: 'notification',\n public: false,\n summary: 'Update notification preferences',\n description: 'Updates user notification preferences',\n tags: ['Notifications'],\n requestSchema: 'UpdateNotificationPreferencesRequestSchema',\n responseSchema: 'UpdateNotificationPreferencesResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '',\n handler: 'listNotifications',\n category: 'notification',\n public: false,\n summary: 'List notifications',\n description: 'Returns paginated list of notifications for the current user',\n tags: ['Notifications'],\n responseSchema: 'ListNotificationsResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/read',\n handler: 'markNotificationsRead',\n category: 'notification',\n public: false,\n summary: 'Mark notifications as read',\n description: 'Marks specific notifications as read by their IDs',\n tags: ['Notifications'],\n requestSchema: 'MarkNotificationsReadRequestSchema',\n responseSchema: 'MarkNotificationsReadResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/read/all',\n handler: 'markAllNotificationsRead',\n category: 'notification',\n public: false,\n summary: 'Mark all notifications as read',\n description: 'Marks all notifications as read for the current user',\n tags: ['Notifications'],\n responseSchema: 'MarkAllNotificationsReadResponseSchema',\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// AI Routes\n// ==========================================\n\n/**\n * Default AI Routes\n * Standard routes for AI operations (NLQ, Chat, Suggest, Insights)\n */\nexport const DEFAULT_AI_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/ai',\n service: 'ai',\n category: 'ai',\n methods: ['aiNlq', 'aiSuggest', 'aiInsights'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/nlq',\n handler: 'aiNlq',\n category: 'ai',\n public: false,\n summary: 'Natural language query',\n description: 'Converts a natural language query to a structured query AST',\n tags: ['AI'],\n requestSchema: 'AiNlqRequestSchema',\n responseSchema: 'AiNlqResponseSchema',\n timeout: 30000,\n cacheable: false,\n },\n // AI chat route removed — wire protocol aligned with Vercel AI SDK.\n // The chat endpoint should use Vercel's `toDataStreamResponse()` directly.\n {\n method: 'POST',\n path: '/suggest',\n handler: 'aiSuggest',\n category: 'ai',\n public: false,\n summary: 'Get AI-powered suggestions',\n description: 'Returns AI-generated field value suggestions based on context',\n tags: ['AI'],\n requestSchema: 'AiSuggestRequestSchema',\n responseSchema: 'AiSuggestResponseSchema',\n timeout: 15000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/insights',\n handler: 'aiInsights',\n category: 'ai',\n public: false,\n summary: 'Get AI-generated insights',\n description: 'Returns AI-generated insights (summaries, trends, anomalies, recommendations)',\n tags: ['AI'],\n requestSchema: 'AiInsightsRequestSchema',\n responseSchema: 'AiInsightsResponseSchema',\n timeout: 60000,\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// i18n Routes\n// ==========================================\n\n/**\n * Default i18n Routes\n * Standard routes for internationalization operations\n */\nexport const DEFAULT_I18N_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/i18n',\n service: 'i18n',\n category: 'i18n',\n methods: ['getLocales', 'getTranslations', 'getFieldLabels'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/locales',\n handler: 'getLocales',\n category: 'i18n',\n public: false,\n summary: 'Get available locales',\n description: 'Returns all available locales with their metadata',\n tags: ['i18n'],\n responseSchema: 'GetLocalesResponseSchema',\n cacheable: true,\n cacheTtl: 86400, // 24 hours — locales change very rarely\n },\n {\n method: 'GET',\n path: '/translations/:locale',\n handler: 'getTranslations',\n category: 'i18n',\n public: false,\n summary: 'Get translations for a locale',\n description: 'Returns translation strings for the specified locale and optional namespace',\n tags: ['i18n'],\n responseSchema: 'GetTranslationsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/labels/:object/:locale',\n handler: 'getFieldLabels',\n category: 'i18n',\n public: false,\n summary: 'Get translated field labels',\n description: 'Returns translated field labels, help text, and option labels for an object',\n tags: ['i18n'],\n responseSchema: 'GetFieldLabelsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Analytics Routes\n// ==========================================\n\n/**\n * Default Analytics Routes\n * Standard routes for analytics and BI operations\n */\nexport const DEFAULT_ANALYTICS_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/analytics',\n service: 'analytics',\n category: 'analytics',\n methods: ['analyticsQuery', 'getAnalyticsMeta'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/query',\n handler: 'analyticsQuery',\n category: 'analytics',\n public: false,\n summary: 'Execute analytics query',\n description: 'Executes a structured analytics query against the semantic layer',\n tags: ['Analytics'],\n requestSchema: 'AnalyticsQueryRequestSchema',\n responseSchema: 'AnalyticsResultResponseSchema',\n permissions: ['analytics.query'],\n timeout: 120000, // 2 minutes for analytics queries\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/meta',\n handler: 'getAnalyticsMeta',\n category: 'analytics',\n public: false,\n summary: 'Get analytics metadata',\n description: 'Returns available cubes, dimensions, measures, and segments',\n tags: ['Analytics'],\n responseSchema: 'AnalyticsMetadataResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Automation Routes\n// ==========================================\n\n/**\n * Default Automation Routes\n * Standard routes for automation triggers\n */\nexport const DEFAULT_AUTOMATION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/automation',\n service: 'automation',\n category: 'automation',\n methods: ['triggerAutomation'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/trigger',\n handler: 'triggerAutomation',\n category: 'automation',\n public: false,\n summary: 'Trigger automation',\n description: 'Triggers an automation flow or script by name',\n tags: ['Automation'],\n requestSchema: 'AutomationTriggerRequestSchema',\n responseSchema: 'AutomationTriggerResponseSchema',\n permissions: ['automation.trigger'],\n timeout: 120000, // 2 minutes for long-running automations\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create REST API plugin configuration\n */\nexport const RestApiPluginConfig = Object.assign(RestApiPluginConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create route registration\n */\nexport const RestApiRouteRegistration = Object.assign(RestApiRouteRegistrationSchema, {\n create: >(registration: T) => registration,\n});\n\n/**\n * Get all default route registrations.\n * Returns the complete set of standard REST API routes covering all protocol namespaces.\n * \n * Route groups (13 total):\n * 1. Discovery - API capabilities and routing info\n * 2. Metadata - Object/field schema CRUD\n * 3. Data CRUD - Record operations\n * 4. Batch - Bulk operations\n * 5. Permission - Authorization checks\n * 6. Views - UI view CRUD\n * 7. Workflow - State machine transitions\n * 8. Realtime - WebSocket/SSE connections\n * 9. Notification - Push notifications and preferences\n * 10. AI - NLQ, chat, suggestions, insights\n * 11. i18n - Locales and translations\n * 12. Analytics - BI queries and metadata\n * 13. Automation - Trigger flows and scripts\n */\nexport function getDefaultRouteRegistrations(): RestApiRouteRegistration[] {\n return [\n DEFAULT_DISCOVERY_ROUTES,\n DEFAULT_METADATA_ROUTES,\n DEFAULT_DATA_CRUD_ROUTES,\n DEFAULT_BATCH_ROUTES,\n DEFAULT_PERMISSION_ROUTES,\n DEFAULT_VIEW_ROUTES,\n DEFAULT_WORKFLOW_ROUTES,\n DEFAULT_REALTIME_ROUTES,\n DEFAULT_NOTIFICATION_ROUTES,\n DEFAULT_AI_ROUTES,\n DEFAULT_I18N_ROUTES,\n DEFAULT_ANALYTICS_ROUTES,\n DEFAULT_AUTOMATION_ROUTES,\n ];\n}\n\n// ==========================================\n// Route Coverage Report\n// ==========================================\n\n/**\n * Route Coverage Entry Schema\n * Reports the coverage status of a single declared endpoint.\n */\nexport const RouteCoverageEntrySchema = z.object({\n /** Full URL path of the endpoint */\n path: z.string().describe('Full URL path (e.g. /api/v1/analytics/query)'),\n /** HTTP method */\n method: HttpMethod.describe('HTTP method (GET, POST, etc.)'),\n /** Route category */\n category: RestApiRouteCategory.describe('Route category'),\n /** Handler implementation status */\n handlerStatus: HandlerStatusSchema.describe('Handler status'),\n /** Target service */\n service: z.string().describe('Target service name'),\n /** Whether the handler was successfully called during health check */\n healthCheckPassed: z.boolean().optional().describe('Whether the health check probe succeeded'),\n});\n\nexport type RouteCoverageEntry = z.infer;\n\n/**\n * Route Coverage Report Schema\n *\n * Aggregated report generated by the adapter/dispatcher at startup.\n * Lists every declared endpoint and whether a handler is confirmed.\n *\n * Adapters SHOULD log a warning for every endpoint where\n * `handlerStatus !== 'implemented'` and emit this report as part\n * of the startup health diagnostics.\n */\nexport const RouteCoverageReportSchema = z.object({\n /** ISO 8601 timestamp of report generation */\n timestamp: z.string().describe('ISO 8601 timestamp'),\n /** Adapter that generated the report */\n adapter: z.string().describe('Adapter name (e.g. \"hono\", \"express\", \"nextjs\")'),\n /** Summary counters */\n summary: z.object({\n total: z.number().int().describe('Total declared endpoints'),\n implemented: z.number().int().describe('Endpoints with real handlers'),\n stub: z.number().int().describe('Endpoints with stub handlers (501)'),\n planned: z.number().int().describe('Endpoints not yet implemented'),\n }),\n /** Per-endpoint entries */\n entries: z.array(RouteCoverageEntrySchema).describe('Per-endpoint coverage entries'),\n});\n\nexport type RouteCoverageReport = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * API Query DSL Adapter Protocol\n * \n * Defines mapping rules between the internal unified query DSL\n * (defined in `data/query.zod.ts`) and external API protocol formats:\n * REST, GraphQL, and OData.\n * \n * This enables ObjectStack to expose a single internal query representation\n * while supporting multiple API standards for external consumers.\n * \n * @see data/query.zod.ts - Unified internal query DSL\n * @see api/rest-server.zod.ts - REST API configuration\n * @see api/graphql.zod.ts - GraphQL API configuration\n * @see api/odata.zod.ts - OData API configuration\n */\n\n// ==========================================\n// 1. Shared Adapter Types\n// ==========================================\n\n/**\n * Query Adapter Target Protocol\n */\nexport const QueryAdapterTargetSchema = z.enum([\n 'rest', // REST API (?filter[field][op]=value)\n 'graphql', // GraphQL (where: \\{ field: \\{ op: value \\}\\})\n 'odata', // OData ($filter=field op value)\n]);\n\nexport type QueryAdapterTarget = z.infer;\n\n/**\n * Operator Mapping Entry\n * \n * Maps a unified DSL operator to its protocol-specific syntax.\n */\nexport const OperatorMappingSchema = z.object({\n /** Unified DSL operator (e.g., 'eq', 'gt', 'contains') */\n operator: z.string().describe('Unified DSL operator'),\n\n /** REST query parameter format (e.g., 'filter[{field}][{op}]') */\n rest: z.string().optional().describe('REST query parameter template'),\n\n /** GraphQL where clause format (e.g., '{field}: { {op}: $value }') */\n graphql: z.string().optional().describe('GraphQL where clause template'),\n\n /** OData $filter expression format (e.g., '{field} {op} {value}') */\n odata: z.string().optional().describe('OData $filter expression template'),\n});\n\nexport type OperatorMapping = z.infer;\n\n// ==========================================\n// 2. REST Adapter Configuration\n// ==========================================\n\n/**\n * REST Query Adapter Configuration\n * \n * Defines how unified query DSL maps to REST query parameters.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10 }\n * REST: ?filter[status][eq]=active&limit=10\n */\nexport const RestQueryAdapterSchema = z.object({\n /** Filter parameter style */\n filterStyle: z.enum([\n 'bracket', // ?filter[field][op]=value (JSON API style)\n 'dot', // ?filter.field.op=value\n 'flat', // ?field=value (simple equality)\n 'rsql', // ?filter=field==value;field=gt=10 (RSQL / FIQL)\n ]).default('bracket').describe('REST filter parameter encoding style'),\n\n /** Pagination parameter names */\n pagination: z.object({\n /** Page size parameter name */\n limitParam: z.string().default('limit').describe('Page size parameter name'),\n\n /** Offset parameter name */\n offsetParam: z.string().default('offset').describe('Offset parameter name'),\n\n /** Cursor parameter name (for cursor-based pagination) */\n cursorParam: z.string().default('cursor').describe('Cursor parameter name'),\n\n /** Page number parameter name (for page-based pagination) */\n pageParam: z.string().default('page').describe('Page number parameter name'),\n }).optional().describe('Pagination parameter name mappings'),\n\n /** Sort parameter name and format */\n sorting: z.object({\n /** Sort parameter name */\n param: z.string().default('sort').describe('Sort parameter name'),\n\n /** Sort format */\n format: z.enum([\n 'comma', // ?sort=field1,-field2\n 'array', // ?sort[]=field1&sort[]=-field2\n 'pipe', // ?sort=field1|asc,field2|desc\n ]).default('comma').describe('Sort parameter encoding format'),\n }).optional().describe('Sort parameter mapping'),\n\n /** Field selection parameter name */\n fieldsParam: z.string().default('fields').describe('Field selection parameter name'),\n});\n\nexport type RestQueryAdapter = z.infer;\nexport type RestQueryAdapterInput = z.input;\n\n// ==========================================\n// 3. GraphQL Adapter Configuration\n// ==========================================\n\n/**\n * GraphQL Query Adapter Configuration\n * \n * Defines how unified query DSL maps to GraphQL arguments.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10, sort: [{ field: 'name', order: 'asc' }] }\n * GraphQL: query { items(where: { status: { eq: \"active\" } }, limit: 10, orderBy: { name: ASC }) { ... } }\n */\nexport const GraphQLQueryAdapterSchema = z.object({\n /** Filter argument name in GraphQL queries */\n filterArgName: z.string().default('where').describe('GraphQL filter argument name'),\n\n /** Filter nesting style */\n filterStyle: z.enum([\n 'nested', // where: { field: { op: value } } (Prisma style)\n 'flat', // where: { field_op: value } (Hasura style)\n 'array', // where: [{ field, op, value }] (Array of conditions)\n ]).default('nested').describe('GraphQL filter nesting style'),\n\n /** Pagination argument names */\n pagination: z.object({\n limitArg: z.string().default('limit').describe('Page size argument name'),\n offsetArg: z.string().default('offset').describe('Offset argument name'),\n firstArg: z.string().default('first').describe('Relay \"first\" argument name'),\n afterArg: z.string().default('after').describe('Relay \"after\" cursor argument name'),\n }).optional().describe('Pagination argument name mappings'),\n\n /** Sort argument configuration */\n sorting: z.object({\n argName: z.string().default('orderBy').describe('Sort argument name'),\n format: z.enum([\n 'enum', // orderBy: { field: ASC }\n 'array', // orderBy: [{ field: \"name\", direction: \"ASC\" }]\n ]).default('enum').describe('Sort argument format'),\n }).optional().describe('Sort argument mapping'),\n});\n\nexport type GraphQLQueryAdapter = z.infer;\nexport type GraphQLQueryAdapterInput = z.input;\n\n// ==========================================\n// 4. OData Adapter Configuration\n// ==========================================\n\n/**\n * OData Query Adapter Configuration\n * \n * Defines how unified query DSL maps to OData system query options.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10, sort: [{ field: 'name', order: 'asc' }] }\n * OData: ?$filter=status eq 'active'&$top=10&$orderby=name asc\n */\nexport const ODataQueryAdapterSchema = z.object({\n /** OData version */\n version: z.enum(['v2', 'v4']).default('v4').describe('OData version'),\n\n /** System query option prefixes */\n usePrefix: z.boolean().default(true).describe('Use $ prefix for system query options ($filter vs filter)'),\n\n /** String function support */\n stringFunctions: z.array(z.enum([\n 'contains',\n 'startswith',\n 'endswith',\n 'tolower',\n 'toupper',\n 'trim',\n 'concat',\n 'substring',\n 'length',\n ])).optional().describe('Supported OData string functions'),\n\n /** Expand (nested resource) configuration */\n expand: z.object({\n enabled: z.boolean().default(true).describe('Enable $expand support'),\n maxDepth: z.number().int().min(1).default(3).describe('Maximum expand depth'),\n }).optional().describe('$expand configuration'),\n});\n\nexport type ODataQueryAdapter = z.infer;\nexport type ODataQueryAdapterInput = z.input;\n\n// ==========================================\n// 5. Complete Query Adapter Configuration\n// ==========================================\n\n/**\n * Query Adapter Configuration\n * \n * Root configuration for query DSL adapters across all supported protocols.\n * Controls how the internal unified DSL is translated to external API formats.\n */\nexport const QueryAdapterConfigSchema = z.object({\n /** Default operator mappings */\n operatorMappings: z.array(OperatorMappingSchema).optional().describe('Custom operator mappings'),\n\n /** REST adapter configuration */\n rest: RestQueryAdapterSchema.optional().describe('REST query adapter configuration'),\n\n /** GraphQL adapter configuration */\n graphql: GraphQLQueryAdapterSchema.optional().describe('GraphQL query adapter configuration'),\n\n /** OData adapter configuration */\n odata: ODataQueryAdapterSchema.optional().describe('OData query adapter configuration'),\n});\n\nexport type QueryAdapterConfig = z.infer;\nexport type QueryAdapterConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Feed Item Type\n * Unified activity types for the record timeline.\n * Covers comments, field changes, tasks, events, and system activities.\n */\nexport const FeedItemType = z.enum([\n 'comment',\n 'field_change',\n 'task',\n 'event',\n 'email',\n 'call',\n 'note',\n 'file',\n 'record_create',\n 'record_delete',\n 'approval',\n 'sharing',\n 'system',\n]);\nexport type FeedItemType = z.infer;\n\n/**\n * Mention Schema\n * Represents an @mention within comment body text.\n */\nexport const MentionSchema = z.object({\n type: z.enum(['user', 'team', 'record']).describe('Mention target type'),\n id: z.string().describe('Target ID'),\n name: z.string().describe('Display name for rendering'),\n offset: z.number().int().min(0).describe('Character offset in body text'),\n length: z.number().int().min(1).describe('Length of mention token in body text'),\n});\nexport type Mention = z.infer;\n\n/**\n * Field Change Entry Schema\n * Represents a single field-level change within a field_change feed item.\n */\nexport const FieldChangeEntrySchema = z.object({\n field: z.string().describe('Field machine name'),\n fieldLabel: z.string().optional().describe('Field display label'),\n oldValue: z.unknown().optional().describe('Previous value'),\n newValue: z.unknown().optional().describe('New value'),\n oldDisplayValue: z.string().optional().describe('Human-readable old value'),\n newDisplayValue: z.string().optional().describe('Human-readable new value'),\n});\nexport type FieldChangeEntry = z.infer;\n\n/**\n * Reaction Schema\n * Represents an emoji reaction on a feed item.\n */\nexport const ReactionSchema = z.object({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n userIds: z.array(z.string()).describe('Users who reacted'),\n count: z.number().int().min(1).describe('Total reaction count'),\n});\nexport type Reaction = z.infer;\n\n/**\n * Feed Actor Schema\n * Represents the actor who performed the action.\n */\nexport const FeedActorSchema = z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n avatarUrl: z.string().url().optional().describe('Actor avatar URL'),\n source: z.string().optional().describe('Source application (e.g., \"Omni\", \"API\", \"Studio\")'),\n});\nexport type FeedActor = z.infer;\n\n/**\n * Feed Item Visibility\n */\nexport const FeedVisibility = z.enum(['public', 'internal', 'private']);\nexport type FeedVisibility = z.infer;\n\n/**\n * Feed Item Schema\n * A single entry in the unified activity timeline.\n *\n * @example Comment\n * {\n * id: 'feed_001',\n * type: 'comment',\n * object: 'account',\n * recordId: 'rec_123',\n * body: 'Great progress! @jane.doe can you follow up?',\n * mentions: [{ type: 'user', id: 'user_123', name: 'Jane Doe', offset: 17, length: 9 }],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:30:00Z',\n * }\n *\n * @example Field Change\n * {\n * id: 'feed_002',\n * type: 'field_change',\n * object: 'account',\n * recordId: 'rec_123',\n * changes: [\n * { field: 'status', oldDisplayValue: 'New', newDisplayValue: 'Active' },\n * { field: 'region', oldDisplayValue: '', newDisplayValue: 'Asia-Pacific' },\n * ],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:25:00Z',\n * }\n */\nexport const FeedItemSchema = z.object({\n /** Unique identifier */\n id: z.string().describe('Feed item ID'),\n\n /** Feed item type */\n type: FeedItemType.describe('Activity type'),\n\n /** Target record reference */\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID this feed item belongs to'),\n\n /** Actor (who performed the action) */\n actor: FeedActorSchema.describe('Who performed this action'),\n\n /** Content (for comments/notes) */\n body: z.string().optional().describe('Rich text body (Markdown supported)'),\n\n /** @Mentions */\n mentions: z.array(MentionSchema).optional().describe('Mentioned users/teams/records'),\n\n /** Field changes (for field_change type) */\n changes: z.array(FieldChangeEntrySchema).optional().describe('Field-level changes'),\n\n /** Reactions */\n reactions: z.array(ReactionSchema).optional().describe('Emoji reactions on this item'),\n\n /** Reply threading */\n parentId: z.string().optional().describe('Parent feed item ID for threaded replies'),\n replyCount: z.number().int().min(0).default(0).describe('Number of replies'),\n\n /** Pin / Star */\n pinned: z.boolean().default(false).describe('Whether the feed item is pinned to the top of the timeline'),\n pinnedAt: z.string().datetime().optional().describe('Timestamp when the item was pinned'),\n pinnedBy: z.string().optional().describe('User ID who pinned the item'),\n starred: z.boolean().default(false).describe('Whether the feed item is starred/bookmarked by the current user'),\n starredAt: z.string().datetime().optional().describe('Timestamp when the item was starred'),\n\n /** Visibility */\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public (all users), internal (team only), private (author + mentioned)'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n editedAt: z.string().datetime().optional().describe('When comment was last edited'),\n isEdited: z.boolean().default(false).describe('Whether comment has been edited'),\n});\nexport type FeedItem = z.infer;\n\n/**\n * Feed Filter Mode\n * Controls which feed item types to display in the timeline.\n */\nexport const FeedFilterMode = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\nexport type FeedFilterMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Subscription Event Type\n * Event types that can be subscribed to for record-level notifications.\n */\nexport const SubscriptionEventType = z.enum([\n 'comment',\n 'mention',\n 'field_change',\n 'task',\n 'approval',\n 'all',\n]);\nexport type SubscriptionEventType = z.infer;\n\n/**\n * Notification Channel\n * Delivery channels for record subscription notifications.\n */\nexport const NotificationChannel = z.enum([\n 'in_app',\n 'email',\n 'push',\n 'slack',\n]);\nexport type NotificationChannel = z.infer;\n\n/**\n * Record Subscription Schema\n * Defines a user's subscription to record-level notifications.\n * Enables Airtable-style bell icon for record change notifications.\n */\nexport const RecordSubscriptionSchema = z.object({\n /** Target */\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n\n /** Subscriber */\n userId: z.string().describe('Subscribing user ID'),\n\n /** Events to subscribe to */\n events: z.array(SubscriptionEventType)\n .default(['all'])\n .describe('Event types to receive notifications for'),\n\n /** Notification channels */\n channels: z.array(NotificationChannel)\n .default(['in_app'])\n .describe('Notification delivery channels'),\n\n /** Active */\n active: z.boolean().default(true).describe('Whether the subscription is active'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Subscription creation timestamp'),\n});\nexport type RecordSubscription = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport {\n FeedItemType,\n FeedItemSchema,\n FeedVisibility,\n MentionSchema,\n ReactionSchema,\n FieldChangeEntrySchema,\n} from '../data/feed.zod';\nimport {\n SubscriptionEventType,\n NotificationChannel,\n RecordSubscriptionSchema,\n} from '../data/subscription.zod';\n\n/**\n * Feed / Chatter API Protocol\n *\n * Defines the HTTP interface for the unified activity timeline (Feed).\n * Covers Feed CRUD, Emoji Reactions, Pin/Star, Search, Changelog,\n * and Record Subscription endpoints.\n *\n * Base path: /api/data/{object}/{recordId}/feed\n *\n * @example Endpoints\n * GET /api/data/{object}/{recordId}/feed — List feed items\n * POST /api/data/{object}/{recordId}/feed — Create feed item\n * PUT /api/data/{object}/{recordId}/feed/{feedId} — Update feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId} — Delete feed item\n * POST /api/data/{object}/{recordId}/feed/{feedId}/reactions — Add reaction\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/reactions/{emoji} — Remove reaction\n * POST /api/data/{object}/{recordId}/feed/{feedId}/pin — Pin feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/pin — Unpin feed item\n * POST /api/data/{object}/{recordId}/feed/{feedId}/star — Star feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/star — Unstar feed item\n * GET /api/data/{object}/{recordId}/feed/search — Search feed items\n * GET /api/data/{object}/{recordId}/changelog — Get field-level changelog\n * POST /api/data/{object}/{recordId}/subscribe — Subscribe\n * DELETE /api/data/{object}/{recordId}/subscribe — Unsubscribe\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Common path parameters shared across all feed endpoints.\n */\nexport const FeedPathParamsSchema = z.object({\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID'),\n});\nexport type FeedPathParams = z.infer;\n\n/**\n * Path parameters for single-feed-item operations (update, delete).\n */\nexport const FeedItemPathParamsSchema = FeedPathParamsSchema.extend({\n feedId: z.string().describe('Feed item ID'),\n});\nexport type FeedItemPathParams = z.infer;\n\n// ==========================================\n// 2. Feed List (GET)\n// ==========================================\n\n/**\n * Feed filter type for the list query.\n * Maps to FeedFilterMode: all | comments_only | changes_only | tasks_only\n */\nexport const FeedListFilterType = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\n\n/**\n * Query parameters for listing feed items.\n *\n * @example GET /api/data/account/rec_123/feed?type=all&limit=20&cursor=xxx\n */\nexport const GetFeedRequestSchema = FeedPathParamsSchema.extend({\n type: FeedListFilterType.default('all')\n .describe('Filter by feed item category'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of items to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination (opaque string from previous response)'),\n});\nexport type GetFeedRequest = z.infer;\n\n/**\n * Response for the feed list endpoint.\n */\nexport const GetFeedResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n items: z.array(FeedItemSchema).describe('Feed items in reverse chronological order'),\n total: z.number().int().optional().describe('Total feed items matching filter'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more items are available'),\n }),\n});\nexport type GetFeedResponse = z.infer;\n\n// ==========================================\n// 3. Feed Create (POST)\n// ==========================================\n\n/**\n * Request body for creating a new feed item (comment, note, task, etc.).\n *\n * @example POST /api/data/account/rec_123/feed\n * { type: 'comment', body: 'Great progress! @jane can you follow up?', mentions: [...] }\n */\nexport const CreateFeedItemRequestSchema = FeedPathParamsSchema.extend({\n type: FeedItemType.describe('Type of feed item to create'),\n body: z.string().optional()\n .describe('Rich text body (Markdown supported)'),\n mentions: z.array(MentionSchema).optional()\n .describe('Mentioned users, teams, or records'),\n parentId: z.string().optional()\n .describe('Parent feed item ID for threaded replies'),\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public, internal, or private'),\n});\nexport type CreateFeedItemRequest = z.infer;\n\n/**\n * Response after creating a feed item.\n */\nexport const CreateFeedItemResponseSchema = BaseResponseSchema.extend({\n data: FeedItemSchema.describe('The created feed item'),\n});\nexport type CreateFeedItemResponse = z.infer;\n\n// ==========================================\n// 4. Feed Update (PUT)\n// ==========================================\n\n/**\n * Request body for updating an existing feed item (e.g., editing a comment).\n *\n * @example PUT /api/data/account/rec_123/feed/feed_001\n * { body: 'Updated comment text', mentions: [...] }\n */\nexport const UpdateFeedItemRequestSchema = FeedItemPathParamsSchema.extend({\n body: z.string().optional()\n .describe('Updated rich text body'),\n mentions: z.array(MentionSchema).optional()\n .describe('Updated mentions'),\n visibility: FeedVisibility.optional()\n .describe('Updated visibility'),\n});\nexport type UpdateFeedItemRequest = z.infer;\n\n/**\n * Response after updating a feed item.\n */\nexport const UpdateFeedItemResponseSchema = BaseResponseSchema.extend({\n data: FeedItemSchema.describe('The updated feed item'),\n});\nexport type UpdateFeedItemResponse = z.infer;\n\n// ==========================================\n// 5. Feed Delete (DELETE)\n// ==========================================\n\n/**\n * Request parameters for deleting a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001\n */\nexport const DeleteFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type DeleteFeedItemRequest = z.infer;\n\n/**\n * Response after deleting a feed item.\n */\nexport const DeleteFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the deleted feed item'),\n }),\n});\nexport type DeleteFeedItemResponse = z.infer;\n\n// ==========================================\n// 6. Reactions (POST / DELETE)\n// ==========================================\n\n/**\n * Request for adding an emoji reaction to a feed item.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/reactions\n * { emoji: '👍' }\n */\nexport const AddReactionRequestSchema = FeedItemPathParamsSchema.extend({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n});\nexport type AddReactionRequest = z.infer;\n\n/**\n * Response after adding a reaction.\n */\nexport const AddReactionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n reactions: z.array(ReactionSchema).describe('Updated reaction list for the feed item'),\n }),\n});\nexport type AddReactionResponse = z.infer;\n\n/**\n * Request for removing an emoji reaction from a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/reactions/👍\n */\nexport const RemoveReactionRequestSchema = FeedItemPathParamsSchema.extend({\n emoji: z.string().describe('Emoji character or shortcode to remove'),\n});\nexport type RemoveReactionRequest = z.infer;\n\n/**\n * Response after removing a reaction.\n */\nexport const RemoveReactionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n reactions: z.array(ReactionSchema).describe('Updated reaction list for the feed item'),\n }),\n});\nexport type RemoveReactionResponse = z.infer;\n\n// ==========================================\n// 7. Pin / Star\n// ==========================================\n\n/**\n * Request for pinning a feed item to the top of the timeline.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/pin\n */\nexport const PinFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type PinFeedItemRequest = z.infer;\n\n/**\n * Response after pinning a feed item.\n */\nexport const PinFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the pinned feed item'),\n pinned: z.boolean().describe('Whether the item is now pinned'),\n pinnedAt: z.string().datetime().describe('Timestamp when pinned'),\n }),\n});\nexport type PinFeedItemResponse = z.infer;\n\n/**\n * Request for unpinning a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/pin\n */\nexport const UnpinFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type UnpinFeedItemRequest = z.infer;\n\n/**\n * Response after unpinning a feed item.\n */\nexport const UnpinFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the unpinned feed item'),\n pinned: z.boolean().describe('Whether the item is now pinned (should be false)'),\n }),\n});\nexport type UnpinFeedItemResponse = z.infer;\n\n/**\n * Request for starring (bookmarking) a feed item.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/star\n */\nexport const StarFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type StarFeedItemRequest = z.infer;\n\n/**\n * Response after starring a feed item.\n */\nexport const StarFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the starred feed item'),\n starred: z.boolean().describe('Whether the item is now starred'),\n starredAt: z.string().datetime().describe('Timestamp when starred'),\n }),\n});\nexport type StarFeedItemResponse = z.infer;\n\n/**\n * Request for unstarring a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/star\n */\nexport const UnstarFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type UnstarFeedItemRequest = z.infer;\n\n/**\n * Response after unstarring a feed item.\n */\nexport const UnstarFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the unstarred feed item'),\n starred: z.boolean().describe('Whether the item is now starred (should be false)'),\n }),\n});\nexport type UnstarFeedItemResponse = z.infer;\n\n// ==========================================\n// 8. Activity Feed Search & Filter\n// ==========================================\n\n/**\n * Request for searching feed items with full-text query and advanced filters.\n *\n * @example GET /api/data/account/rec_123/feed/search?query=follow+up&actorId=user_456&dateFrom=2026-01-01T00:00:00Z\n */\nexport const SearchFeedRequestSchema = FeedPathParamsSchema.extend({\n query: z.string().min(1).describe('Full-text search query against feed body content'),\n type: FeedListFilterType.optional()\n .describe('Filter by feed item category'),\n actorId: z.string().optional()\n .describe('Filter by actor user ID'),\n dateFrom: z.string().datetime().optional()\n .describe('Filter feed items created after this timestamp'),\n dateTo: z.string().datetime().optional()\n .describe('Filter feed items created before this timestamp'),\n hasAttachments: z.boolean().optional()\n .describe('Filter for items with file attachments'),\n pinnedOnly: z.boolean().optional()\n .describe('Return only pinned items'),\n starredOnly: z.boolean().optional()\n .describe('Return only starred items'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of items to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type SearchFeedRequest = z.infer;\n\n/**\n * Response for the feed search endpoint.\n */\nexport const SearchFeedResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n items: z.array(FeedItemSchema).describe('Matching feed items sorted by relevance'),\n total: z.number().int().optional().describe('Total matching items'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more items are available'),\n }),\n});\nexport type SearchFeedResponse = z.infer;\n\n// ==========================================\n// 9. Changelog (Field-Level Audit Trail)\n// ==========================================\n\n/**\n * Request for retrieving the field-level changelog of a record.\n *\n * @example GET /api/data/account/rec_123/changelog?field=status&limit=50\n */\nexport const GetChangelogRequestSchema = FeedPathParamsSchema.extend({\n field: z.string().optional()\n .describe('Filter changelog to a specific field name'),\n actorId: z.string().optional()\n .describe('Filter changelog by actor user ID'),\n dateFrom: z.string().datetime().optional()\n .describe('Filter changes after this timestamp'),\n dateTo: z.string().datetime().optional()\n .describe('Filter changes before this timestamp'),\n limit: z.number().int().min(1).max(200).default(50)\n .describe('Maximum number of changelog entries to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type GetChangelogRequest = z.infer;\n\n/**\n * A single changelog entry representing one or more field changes at a point in time.\n */\nexport const ChangelogEntrySchema = z.object({\n id: z.string().describe('Changelog entry ID'),\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n actor: z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n }).describe('Who made the change'),\n changes: z.array(FieldChangeEntrySchema).min(1).describe('Field-level changes'),\n timestamp: z.string().datetime().describe('When the change occurred'),\n source: z.string().optional().describe('Change source (e.g., \"API\", \"UI\", \"automation\")'),\n});\nexport type ChangelogEntry = z.infer;\n\n/**\n * Response for the changelog endpoint.\n */\nexport const GetChangelogResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n entries: z.array(ChangelogEntrySchema).describe('Changelog entries in reverse chronological order'),\n total: z.number().int().optional().describe('Total changelog entries matching filter'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more entries are available'),\n }),\n});\nexport type GetChangelogResponse = z.infer;\n\n// ==========================================\n// 10. Record Subscription (POST / DELETE)\n// ==========================================\n\n/**\n * Request for subscribing to record notifications.\n *\n * @example POST /api/data/account/rec_123/subscribe\n * { events: ['comment', 'field_change'], channels: ['in_app', 'email'] }\n */\nexport const SubscribeRequestSchema = FeedPathParamsSchema.extend({\n events: z.array(SubscriptionEventType).default(['all'])\n .describe('Event types to subscribe to'),\n channels: z.array(NotificationChannel).default(['in_app'])\n .describe('Notification delivery channels'),\n});\nexport type SubscribeRequest = z.infer;\n\n/**\n * Response after subscribing.\n */\nexport const SubscribeResponseSchema = BaseResponseSchema.extend({\n data: RecordSubscriptionSchema.describe('The created or updated subscription'),\n});\nexport type SubscribeResponse = z.infer;\n\n/**\n * Request for unsubscribing from record notifications.\n *\n * @example DELETE /api/data/account/rec_123/subscribe\n */\nexport const FeedUnsubscribeRequestSchema = FeedPathParamsSchema;\nexport type FeedUnsubscribeRequest = z.infer;\n\n/**\n * Response after unsubscribing.\n */\nexport const UnsubscribeResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n unsubscribed: z.boolean().describe('Whether the user was unsubscribed'),\n }),\n});\nexport type UnsubscribeResponse = z.infer;\n\n// ==========================================\n// 11. Feed API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Feed/Chatter operations.\n */\nexport const FeedApiErrorCode = z.enum([\n 'feed_item_not_found',\n 'feed_permission_denied',\n 'feed_item_not_editable',\n 'feed_invalid_parent',\n 'reaction_already_exists',\n 'reaction_not_found',\n 'subscription_already_exists',\n 'subscription_not_found',\n 'invalid_feed_type',\n 'feed_already_pinned',\n 'feed_not_pinned',\n 'feed_already_starred',\n 'feed_not_starred',\n 'feed_search_query_too_short',\n]);\nexport type FeedApiErrorCode = z.infer;\n\n// ==========================================\n// 12. Feed API Contract Registry\n// ==========================================\n\n/**\n * Standard Feed API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const FeedApiContracts = {\n listFeed: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/feed',\n input: GetFeedRequestSchema,\n output: GetFeedResponseSchema,\n },\n createFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed',\n input: CreateFeedItemRequestSchema,\n output: CreateFeedItemResponseSchema,\n },\n updateFeedItem: {\n method: 'PUT' as const,\n path: '/api/data/:object/:recordId/feed/:feedId',\n input: UpdateFeedItemRequestSchema,\n output: UpdateFeedItemResponseSchema,\n },\n deleteFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId',\n input: DeleteFeedItemRequestSchema,\n output: DeleteFeedItemResponseSchema,\n },\n addReaction: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/reactions',\n input: AddReactionRequestSchema,\n output: AddReactionResponseSchema,\n },\n removeReaction: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/reactions/:emoji',\n input: RemoveReactionRequestSchema,\n output: RemoveReactionResponseSchema,\n },\n pinFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/pin',\n input: PinFeedItemRequestSchema,\n output: PinFeedItemResponseSchema,\n },\n unpinFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/pin',\n input: UnpinFeedItemRequestSchema,\n output: UnpinFeedItemResponseSchema,\n },\n starFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/star',\n input: StarFeedItemRequestSchema,\n output: StarFeedItemResponseSchema,\n },\n unstarFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/star',\n input: UnstarFeedItemRequestSchema,\n output: UnstarFeedItemResponseSchema,\n },\n searchFeed: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/feed/search',\n input: SearchFeedRequestSchema,\n output: SearchFeedResponseSchema,\n },\n getChangelog: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/changelog',\n input: GetChangelogRequestSchema,\n output: GetChangelogResponseSchema,\n },\n subscribe: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/subscribe',\n input: SubscribeRequestSchema,\n output: SubscribeResponseSchema,\n },\n unsubscribe: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/subscribe',\n input: FeedUnsubscribeRequestSchema,\n output: UnsubscribeResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Data Export & Import Protocol\n *\n * Defines schemas for streaming data export, import validation,\n * template-based field mapping, and scheduled export jobs.\n *\n * Industry alignment: Salesforce Data Export, Airtable CSV Export,\n * Dynamics 365 Data Management.\n *\n * Base path: /api/v1/data/{object}/export\n */\n\n// ==========================================\n// 1. Export Format & Configuration\n// ==========================================\n\n/**\n * Export Format Enum\n * Supported file formats for data export.\n */\nexport const ExportFormat = z.enum([\n 'csv',\n 'json',\n 'jsonl',\n 'xlsx',\n 'parquet',\n]);\nexport type ExportFormat = z.infer;\n\n/**\n * Export Job Status\n */\nexport const ExportJobStatus = z.enum([\n 'pending',\n 'processing',\n 'completed',\n 'failed',\n 'cancelled',\n 'expired',\n]);\nexport type ExportJobStatus = z.infer;\n\n// ==========================================\n// 2. Export Job Request / Response\n// ==========================================\n\n/**\n * Create Export Job Request\n * Initiates an asynchronous streaming export.\n *\n * @example POST /api/v1/data/account/export\n * { format: 'csv', fields: ['name', 'email', 'status'], filter: { status: 'active' }, limit: 10000 }\n */\nexport const CreateExportJobRequestSchema = z.object({\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional()\n .describe('Specific fields to include (omit for all fields)'),\n filter: z.record(z.string(), z.unknown()).optional()\n .describe('Filter criteria for records to export'),\n sort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n direction: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n })).optional().describe('Sort order for exported records'),\n limit: z.number().int().min(1).optional()\n .describe('Maximum number of records to export'),\n includeHeaders: z.boolean().default(true)\n .describe('Include header row (CSV/XLSX)'),\n encoding: z.string().default('utf-8')\n .describe('Character encoding for the export file'),\n templateId: z.string().optional()\n .describe('Export template ID for predefined field mappings'),\n});\nexport type CreateExportJobRequest = z.infer;\n\n/**\n * Export Job Response\n * Returns the created export job with tracking info.\n */\nexport const CreateExportJobResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n status: ExportJobStatus.describe('Initial job status'),\n estimatedRecords: z.number().int().optional().describe('Estimated total records'),\n createdAt: z.string().datetime().describe('Job creation timestamp'),\n }),\n});\nexport type CreateExportJobResponse = z.infer;\n\n/**\n * Export Job Progress\n * Tracks the progress of an active export job.\n *\n * @example GET /api/v1/data/export/:jobId\n */\nexport const ExportJobProgressSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n status: ExportJobStatus.describe('Current job status'),\n format: ExportFormat.describe('Export format'),\n totalRecords: z.number().int().optional().describe('Total records to export'),\n processedRecords: z.number().int().describe('Records processed so far'),\n percentComplete: z.number().min(0).max(100).describe('Export progress percentage'),\n fileSize: z.number().int().optional().describe('Current file size in bytes'),\n downloadUrl: z.string().optional()\n .describe('Presigned download URL (available when status is \"completed\")'),\n downloadExpiresAt: z.string().datetime().optional()\n .describe('Download URL expiration timestamp'),\n error: z.object({\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n }).optional().describe('Error details if job failed'),\n startedAt: z.string().datetime().optional().describe('Processing start timestamp'),\n completedAt: z.string().datetime().optional().describe('Completion timestamp'),\n }),\n});\nexport type ExportJobProgress = z.infer;\n\n// ==========================================\n// 3. Import Validation & Deduplication\n// ==========================================\n\n/**\n * Import Validation Mode\n */\nexport const ImportValidationMode = z.enum([\n 'strict', // Reject entire import on any validation error\n 'lenient', // Skip invalid records, import valid ones\n 'dry_run', // Validate all records without persisting\n]);\nexport type ImportValidationMode = z.infer;\n\n/**\n * Deduplication Strategy\n * How to handle duplicate records during import.\n */\nexport const DeduplicationStrategy = z.enum([\n 'skip', // Skip duplicates (keep existing)\n 'update', // Update existing with import data\n 'create_new', // Create new record even if duplicate\n 'fail', // Fail the import if duplicates found\n]);\nexport type DeduplicationStrategy = z.infer;\n\n/**\n * Import Validation Config Schema\n * Configuration for validating and deduplicating imported data.\n *\n * @example\n * {\n * mode: 'lenient',\n * deduplication: { strategy: 'update', matchFields: ['email', 'external_id'] },\n * maxErrors: 50,\n * trimWhitespace: true,\n * }\n */\nexport const ImportValidationConfigSchema = z.object({\n mode: ImportValidationMode.default('strict')\n .describe('Validation mode for the import'),\n deduplication: z.object({\n strategy: DeduplicationStrategy.default('skip')\n .describe('How to handle duplicate records'),\n matchFields: z.array(z.string()).min(1)\n .describe('Fields used to identify duplicates (e.g., \"email\", \"external_id\")'),\n }).optional().describe('Deduplication configuration'),\n maxErrors: z.number().int().min(1).default(100)\n .describe('Maximum validation errors before aborting'),\n trimWhitespace: z.boolean().default(true)\n .describe('Trim leading/trailing whitespace from string fields'),\n dateFormat: z.string().optional()\n .describe('Expected date format in import data (e.g., \"YYYY-MM-DD\")'),\n nullValues: z.array(z.string()).optional()\n .describe('Strings to treat as null (e.g., [\"\", \"N/A\", \"null\"])'),\n});\nexport type ImportValidationConfig = z.infer;\n\n/**\n * Import Validation Result Schema\n * Summary of the import validation pass.\n */\nexport const ImportValidationResultSchema = BaseResponseSchema.extend({\n data: z.object({\n totalRecords: z.number().int().describe('Total records in import file'),\n validRecords: z.number().int().describe('Records that passed validation'),\n invalidRecords: z.number().int().describe('Records that failed validation'),\n duplicateRecords: z.number().int().describe('Duplicate records detected'),\n errors: z.array(z.object({\n row: z.number().int().describe('Row number in the import file'),\n field: z.string().optional().describe('Field that failed validation'),\n code: z.string().describe('Validation error code'),\n message: z.string().describe('Validation error message'),\n })).describe('List of validation errors'),\n preview: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Preview of first N valid records (for dry_run mode)'),\n }),\n});\nexport type ImportValidationResult = z.infer;\n\n// ==========================================\n// 4. Export/Import Template\n// ==========================================\n\n/**\n * Field Mapping Entry Schema\n * Maps a source field to a target field with optional transformation.\n */\nexport const FieldMappingEntrySchema = z.object({\n sourceField: z.string().describe('Field name in the source data (import) or object (export)'),\n targetField: z.string().describe('Field name in the target object (import) or file column (export)'),\n targetLabel: z.string().optional().describe('Display label for the target column (export)'),\n transform: z.enum(['none', 'uppercase', 'lowercase', 'trim', 'date_format', 'lookup'])\n .default('none')\n .describe('Transformation to apply during mapping'),\n defaultValue: z.unknown().optional()\n .describe('Default value if source field is null/empty'),\n required: z.boolean().default(false)\n .describe('Whether this field is required (import validation)'),\n});\nexport type FieldMappingEntry = z.infer;\n\n/**\n * Export/Import Template Schema\n * Reusable template for predefined field mappings.\n *\n * @example\n * {\n * name: 'account_export_v1',\n * label: 'Account Export (Standard)',\n * object: 'account',\n * direction: 'export',\n * mappings: [\n * { sourceField: 'name', targetField: 'Company Name' },\n * { sourceField: 'email', targetField: 'Email', transform: 'lowercase' },\n * ],\n * }\n */\nexport const ExportImportTemplateSchema = z.object({\n id: z.string().optional().describe('Template ID (generated on save)'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Template machine name (snake_case)'),\n label: z.string().describe('Human-readable template label'),\n description: z.string().optional().describe('Template description'),\n object: z.string().describe('Target object name'),\n direction: z.enum(['import', 'export', 'bidirectional'])\n .describe('Template direction'),\n format: ExportFormat.optional().describe('Default file format for this template'),\n mappings: z.array(FieldMappingEntrySchema).min(1)\n .describe('Field mapping entries'),\n createdAt: z.string().datetime().optional().describe('Template creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n createdBy: z.string().optional().describe('User who created the template'),\n});\nexport type ExportImportTemplate = z.infer;\n\n// ==========================================\n// 5. Scheduled Export Jobs\n// ==========================================\n\n/**\n * Scheduled Export Schema\n * Defines a recurring data export job.\n *\n * @example\n * {\n * name: 'weekly_account_export',\n * object: 'account',\n * format: 'csv',\n * schedule: { cronExpression: '0 6 * * MON', timezone: 'America/New_York' },\n * delivery: { method: 'email', recipients: ['admin@example.com'] },\n * }\n */\nexport const ScheduledExportSchema = z.object({\n id: z.string().optional().describe('Scheduled export ID'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Schedule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional().describe('Fields to include'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Record filter criteria'),\n templateId: z.string().optional().describe('Export template ID for field mappings'),\n schedule: z.object({\n cronExpression: z.string().describe('Cron expression for schedule'),\n timezone: z.string().default('UTC').describe('IANA timezone'),\n }).describe('Schedule timing configuration'),\n delivery: z.object({\n method: z.enum(['email', 'storage', 'webhook'])\n .describe('How to deliver the export file'),\n recipients: z.array(z.string()).optional()\n .describe('Email recipients (for email delivery)'),\n storagePath: z.string().optional()\n .describe('Storage path (for storage delivery)'),\n webhookUrl: z.string().optional()\n .describe('Webhook URL (for webhook delivery)'),\n }).describe('Export delivery configuration'),\n enabled: z.boolean().default(true).describe('Whether the scheduled export is active'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution'),\n createdAt: z.string().datetime().optional().describe('Creation timestamp'),\n createdBy: z.string().optional().describe('User who created the schedule'),\n});\nexport type ScheduledExport = z.infer;\n\n// ==========================================\n// 6. Get Export Job Download\n// ==========================================\n\n/**\n * Get Export Job Download Request\n * Retrieves a presigned download link for a completed export job.\n *\n * @example GET /api/v1/data/export/:jobId/download\n */\nexport const GetExportJobDownloadRequestSchema = z.object({\n jobId: z.string().describe('Export job ID'),\n});\nexport type GetExportJobDownloadRequest = z.infer;\n\n/**\n * Get Export Job Download Response\n * Returns the presigned download URL and metadata.\n */\nexport const GetExportJobDownloadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n downloadUrl: z.string().describe('Presigned download URL'),\n fileName: z.string().describe('Suggested file name'),\n fileSize: z.number().int().describe('File size in bytes'),\n format: ExportFormat.describe('Export file format'),\n expiresAt: z.string().datetime().describe('Download URL expiration timestamp'),\n checksum: z.string().optional().describe('File checksum (SHA-256)'),\n }),\n});\nexport type GetExportJobDownloadResponse = z.infer;\n\n// ==========================================\n// 7. List Export Jobs\n// ==========================================\n\n/**\n * List Export Jobs Request\n * Retrieves a paginated list of historical export jobs.\n *\n * @example GET /api/v1/data/export?object=account&status=completed&limit=20\n */\nexport const ListExportJobsRequestSchema = z.object({\n object: z.string().optional().describe('Filter by object name'),\n status: ExportJobStatus.optional().describe('Filter by job status'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of jobs to return'),\n cursor: z.string().optional()\n .describe('Pagination cursor from a previous response'),\n});\nexport type ListExportJobsRequest = z.infer;\n\n/**\n * Export Job Summary\n * Compact representation of an export job for list views.\n */\nexport const ExportJobSummarySchema = z.object({\n jobId: z.string().describe('Export job ID'),\n object: z.string().describe('Object name that was exported'),\n status: ExportJobStatus.describe('Current job status'),\n format: ExportFormat.describe('Export file format'),\n totalRecords: z.number().int().optional().describe('Total records exported'),\n fileSize: z.number().int().optional().describe('File size in bytes'),\n createdAt: z.string().datetime().describe('Job creation timestamp'),\n completedAt: z.string().datetime().optional().describe('Completion timestamp'),\n createdBy: z.string().optional().describe('User who initiated the export'),\n});\nexport type ExportJobSummary = z.infer;\n\n/**\n * List Export Jobs Response\n * Paginated list of export jobs with cursor-based pagination.\n */\nexport const ListExportJobsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobs: z.array(ExportJobSummarySchema).describe('List of export jobs'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more jobs are available'),\n }),\n});\nexport type ListExportJobsResponse = z.infer;\n\n// ==========================================\n// 8. Schedule Export Request/Response\n// ==========================================\n\n/**\n * Schedule Export Request\n * Creates a new scheduled (recurring) export job.\n *\n * @example POST /api/v1/data/export/schedules\n */\nexport const ScheduleExportRequestSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Schedule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional().describe('Fields to include'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Record filter criteria'),\n templateId: z.string().optional().describe('Export template ID for field mappings'),\n schedule: z.object({\n cronExpression: z.string().describe('Cron expression for schedule'),\n timezone: z.string().default('UTC').describe('IANA timezone'),\n }).describe('Schedule timing configuration'),\n delivery: z.object({\n method: z.enum(['email', 'storage', 'webhook'])\n .describe('How to deliver the export file'),\n recipients: z.array(z.string()).optional()\n .describe('Email recipients (for email delivery)'),\n storagePath: z.string().optional()\n .describe('Storage path (for storage delivery)'),\n webhookUrl: z.string().optional()\n .describe('Webhook URL (for webhook delivery)'),\n }).describe('Export delivery configuration'),\n});\nexport type ScheduleExportRequest = z.infer;\n\n/**\n * Schedule Export Response\n * Returns the created scheduled export with generated ID and next run info.\n */\nexport const ScheduleExportResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n id: z.string().describe('Scheduled export ID'),\n name: z.string().describe('Schedule name'),\n enabled: z.boolean().describe('Whether the schedule is active'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution'),\n createdAt: z.string().datetime().describe('Creation timestamp'),\n }),\n});\nexport type ScheduleExportResponse = z.infer;\n\n// ==========================================\n// 9. Export API Contracts\n// ==========================================\n\n/**\n * Export API Contract Registry\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const ExportApiContracts = {\n createExportJob: {\n method: 'POST' as const,\n path: '/api/v1/data/:object/export',\n input: CreateExportJobRequestSchema,\n output: CreateExportJobResponseSchema,\n },\n getExportJobProgress: {\n method: 'GET' as const,\n path: '/api/v1/data/export/:jobId',\n input: z.object({ jobId: z.string() }),\n output: ExportJobProgressSchema,\n },\n getExportJobDownload: {\n method: 'GET' as const,\n path: '/api/v1/data/export/:jobId/download',\n input: GetExportJobDownloadRequestSchema,\n output: GetExportJobDownloadResponseSchema,\n },\n listExportJobs: {\n method: 'GET' as const,\n path: '/api/v1/data/export',\n input: ListExportJobsRequestSchema,\n output: ListExportJobsResponseSchema,\n },\n scheduleExport: {\n method: 'POST' as const,\n path: '/api/v1/data/export/schedules',\n input: ScheduleExportRequestSchema,\n output: ScheduleExportResponseSchema,\n },\n cancelExportJob: {\n method: 'POST' as const,\n path: '/api/v1/data/export/:jobId/cancel',\n input: z.object({ jobId: z.string() }),\n output: BaseResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Flow Node Types\n */\nexport const FlowNodeAction = z.enum([\n 'start', // Trigger\n 'end', // Return/Stop\n 'decision', // If/Else logic\n 'assignment', // Set Variable\n 'loop', // For Each\n 'create_record', // CRUD: Create\n 'update_record', // CRUD: Update\n 'delete_record', // CRUD: Delete\n 'get_record', // CRUD: Get/Query\n 'http_request', // Webhook/API Call\n 'script', // Custom Script (JS/TS)\n 'screen', // Screen / User-Input Element\n 'wait', // Delay/Sleep\n 'subflow', // Call another flow\n 'connector_action', // Zapier-style integration action\n 'parallel_gateway', // BPMN Parallel Gateway — AND-split (all outgoing branches execute concurrently)\n 'join_gateway', // BPMN Join Gateway — AND-join (waits for all incoming branches to complete)\n 'boundary_event', // BPMN Boundary Event — attached to a host node for timer/error/signal interrupts\n]);\n\n/**\n * Flow Variable Schema\n * Variables available within the flow execution context.\n */\nexport const FlowVariableSchema = z.object({\n name: z.string().describe('Variable name'),\n type: z.string().describe('Data type (text, number, boolean, object, list)'),\n isInput: z.boolean().default(false).describe('Is input parameter'),\n isOutput: z.boolean().default(false).describe('Is output parameter'),\n});\n\n/**\n * Flow Node Schema\n * A single step in the visual logic graph.\n * \n * @example Decision Node\n * {\n * id: \"dec_1\",\n * type: \"decision\",\n * label: \"Is High Value?\",\n * config: {\n * conditions: [\n * { label: \"Yes\", expression: \"{amount} > 10000\" },\n * { label: \"No\", expression: \"true\" } // default\n * ]\n * },\n * position: { x: 300, y: 200 }\n * }\n */\nexport const FlowNodeSchema = z.object({\n id: z.string().describe('Node unique ID'),\n type: FlowNodeAction.describe('Action type'),\n label: z.string().describe('Node label'),\n \n /** Node Configuration Options (Specific to type) */\n config: z.record(z.string(), z.unknown()).optional().describe('Node configuration'),\n \n /** \n * Connector Action Configuration\n * Used when type is 'connector_action'\n */\n connectorConfig: z.object({\n connectorId: z.string(),\n actionId: z.string(),\n input: z.record(z.string(), z.unknown()).describe('Mapped inputs for the action'),\n }).optional(),\n\n /** UI Position (for the canvas) */\n position: z.object({ x: z.number(), y: z.number() }).optional(),\n\n /** Node-level execution timeout */\n timeoutMs: z.number().int().min(0).optional().describe('Maximum execution time for this node in milliseconds'),\n\n /** Node input schema declaration for Studio form generation and runtime validation */\n inputSchema: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).describe('Parameter type'),\n required: z.boolean().default(false).describe('Whether the parameter is required'),\n description: z.string().optional().describe('Parameter description'),\n })).optional().describe('Input parameter schema for this node'),\n\n /** Node output schema declaration */\n outputSchema: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).describe('Output type'),\n description: z.string().optional().describe('Output description'),\n })).optional().describe('Output schema declaration for this node'),\n\n /**\n * Wait Event Configuration (for 'wait' nodes)\n * Defines what external event or condition should resume the paused execution.\n * Industry alignment: BPMN Intermediate Catch Events, Temporal Signals.\n */\n waitEventConfig: z.object({\n /** Type of event to wait for */\n eventType: z.enum(['timer', 'signal', 'webhook', 'manual', 'condition'])\n .describe('What kind of event resumes the execution'),\n /** Duration to wait (ISO 8601 duration or milliseconds) — for timer events */\n timerDuration: z.string().optional().describe('ISO 8601 duration (e.g., \"PT1H\") or wait time for timer events'),\n /** Signal name to listen for — for signal/webhook events */\n signalName: z.string().optional().describe('Named signal or webhook event to wait for'),\n /** Timeout before auto-failing or continuing — optional guard */\n timeoutMs: z.number().int().min(0).optional().describe('Maximum wait time before timeout (ms)'),\n /** Action to take on timeout */\n onTimeout: z.enum(['fail', 'continue']).default('fail').describe('Behavior when the wait times out'),\n }).optional().describe('Configuration for wait node event resumption'),\n\n /**\n * Boundary Event Configuration (for 'boundary_event' nodes)\n * Attaches an event handler to a host activity node (BPMN Boundary Event pattern).\n * Industry alignment: BPMN Boundary Error/Timer/Signal Events.\n */\n boundaryConfig: z.object({\n /** ID of the host node this boundary event is attached to */\n attachedToNodeId: z.string().describe('Host node ID this boundary event monitors'),\n /** Type of boundary event */\n eventType: z.enum(['error', 'timer', 'signal', 'cancel'])\n .describe('Boundary event trigger type'),\n /** Whether the boundary event interrupts the host activity */\n interrupting: z.boolean().default(true)\n .describe('If true, the host activity is cancelled when this event fires'),\n /** Error code filter — only for error boundary events */\n errorCode: z.string().optional().describe('Specific error code to catch (empty = catch all errors)'),\n /** Timer duration — only for timer boundary events */\n timerDuration: z.string().optional().describe('ISO 8601 duration for timer boundary events'),\n /** Signal name — only for signal boundary events */\n signalName: z.string().optional().describe('Named signal to catch'),\n }).optional().describe('Configuration for boundary events attached to host nodes'),\n});\n\n/**\n * Flow Edge Schema\n * Connections between nodes.\n */\nexport const FlowEdgeSchema = z.object({\n id: z.string().describe('Edge unique ID'),\n source: z.string().describe('Source Node ID'),\n target: z.string().describe('Target Node ID'),\n \n /** Condition for this path (only for decision/branch nodes) */\n condition: z.string().optional().describe('Expression returning boolean used for branching'),\n \n type: z.enum(['default', 'fault', 'conditional']).default('default')\n .describe('Connection type: default (normal flow), fault (error path), or conditional (expression-guarded)'),\n label: z.string().optional().describe('Label on the connector'),\n\n /**\n * Default Sequence Flow marker (BPMN Default Flow semantics).\n * When true, this edge is taken when no sibling conditional edges match.\n * Only meaningful on outgoing edges of decision/gateway nodes.\n */\n isDefault: z.boolean().default(false)\n .describe('Marks this edge as the default path when no other conditions match'),\n});\n\n/**\n * Flow Schema\n * Visual Business Logic Orchestration.\n * \n * @example Simple Approval Logic\n * {\n * name: \"approve_order_flow\",\n * label: \"Approve Large Orders\",\n * type: \"record_change\",\n * status: \"active\",\n * nodes: [\n * { id: \"start\", type: \"start\", label: \"Start\", position: {x: 0, y: 0} },\n * { id: \"check_amount\", type: \"decision\", label: \"Check Amount\", position: {x: 0, y: 100} },\n * { id: \"auto_approve\", type: \"update_record\", label: \"Auto Approve\", position: {x: -100, y: 200} },\n * { id: \"submit_for_approval\", type: \"connector_action\", label: \"Submit\", position: {x: 100, y: 200} }\n * ],\n * edges: [\n * { id: \"e1\", source: \"start\", target: \"check_amount\" },\n * { id: \"e2\", source: \"check_amount\", target: \"auto_approve\", condition: \"{amount} < 500\" },\n * { id: \"e3\", source: \"check_amount\", target: \"submit_for_approval\", condition: \"{amount} >= 500\" }\n * ]\n * }\n */\nexport const FlowSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name'),\n label: z.string().describe('Flow label'),\n description: z.string().optional(),\n \n /** Metadata & Versioning */\n version: z.number().int().default(1).describe('Version number'),\n status: z.enum(['draft', 'active', 'obsolete', 'invalid']).default('draft').describe('Deployment status'),\n template: z.boolean().default(false).describe('Is logic template (Subflow)'),\n\n /** Trigger Type */\n type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).describe('Flow type'),\n \n /** Configuration Variables */\n variables: z.array(FlowVariableSchema).optional().describe('Flow variables'),\n \n /** Graph Definition */\n nodes: z.array(FlowNodeSchema).describe('Flow nodes'),\n edges: z.array(FlowEdgeSchema).describe('Flow connections'),\n \n /** Execution Config */\n active: z.boolean().default(false).describe('Is active (Deprecated: use status)'),\n runAs: z.enum(['system', 'user']).default('user').describe('Execution context'),\n\n /** Error Handling Strategy */\n errorHandling: z.object({\n strategy: z.enum(['fail', 'retry', 'continue']).default('fail').describe('How to handle node execution errors'),\n maxRetries: z.number().int().min(0).max(10).default(0).describe('Number of retry attempts (only for retry strategy)'),\n retryDelayMs: z.number().int().min(0).default(1000).describe('Delay between retries in milliseconds'),\n backoffMultiplier: z.number().min(1).default(1).describe('Multiplier for exponential backoff between retries'),\n maxRetryDelayMs: z.number().int().min(0).default(30000).describe('Maximum delay between retries in milliseconds'),\n jitter: z.boolean().default(false).describe('Add random jitter to retry delay to avoid thundering herd'),\n fallbackNodeId: z.string().optional().describe('Node ID to jump to on unrecoverable error'),\n }).optional().describe('Flow-level error handling configuration'),\n});\n\n/**\n * Type-safe factory for creating flow definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const onCreateFlow = defineFlow({\n * name: 'on_task_create',\n * label: 'On Task Create',\n * type: 'record_change',\n * nodes: [\n * { id: 'start', type: 'start', label: 'Start' },\n * { id: 'end', type: 'end', label: 'End' },\n * ],\n * edges: [{ id: 'e1', source: 'start', target: 'end' }],\n * });\n * ```\n */\nexport function defineFlow(config: z.input): FlowParsed {\n return FlowSchema.parse(config);\n}\n\nexport type Flow = z.input;\nexport type FlowParsed = z.infer;\nexport type FlowNode = z.input;\nexport type FlowNodeParsed = z.infer;\nexport type FlowEdge = z.input;\nexport type FlowEdgeParsed = z.infer;\n\n/**\n * Flow Version History Schema\n * Tracks historical versions of flow definitions for rollback support.\n *\n * Industry alignment: Salesforce Flow Versions, n8n Workflow History.\n */\nexport const FlowVersionHistorySchema = z.object({\n flowName: z.string().describe('Flow machine name'),\n version: z.number().int().min(1).describe('Version number'),\n definition: FlowSchema.describe('Complete flow definition snapshot'),\n createdAt: z.string().datetime().describe('When this version was created'),\n createdBy: z.string().optional().describe('User who created this version'),\n changeNote: z.string().optional().describe('Description of what changed in this version'),\n});\n\nexport type FlowVersionHistory = z.input;\nexport type FlowVersionHistoryParsed = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Automation Execution Protocol\n *\n * Defines schemas for execution logging, error tracking, checkpointing,\n * concurrency control, and scheduled execution persistence.\n *\n * Industry alignment: Salesforce Flow Interviews, Temporal Workflow History,\n * AWS Step Functions execution logs.\n */\n\n// ==========================================\n// 1. Execution Status\n// ==========================================\n\n/**\n * Execution Status Enum\n * Tracks the lifecycle of a flow execution instance.\n */\nexport const ExecutionStatus = z.enum([\n 'pending', // Queued, not yet started\n 'running', // Currently executing\n 'paused', // Paused at a wait/checkpoint node\n 'completed', // Successfully finished\n 'failed', // Terminated with error\n 'cancelled', // Manually cancelled\n 'timed_out', // Exceeded max execution time\n 'retrying', // Failed and retrying\n]);\nexport type ExecutionStatus = z.infer;\n\n// ==========================================\n// 2. Execution Log\n// ==========================================\n\n/**\n * Execution Step Log Entry\n * Records the result of executing a single node in the flow graph.\n */\nexport const ExecutionStepLogSchema = z.object({\n nodeId: z.string().describe('Node ID that was executed'),\n nodeType: z.string().describe('Node action type (e.g., \"decision\", \"http_request\")'),\n nodeLabel: z.string().optional().describe('Human-readable node label'),\n status: z.enum(['success', 'failure', 'skipped']).describe('Step execution result'),\n startedAt: z.string().datetime().describe('When the step started'),\n completedAt: z.string().datetime().optional().describe('When the step completed'),\n durationMs: z.number().int().min(0).optional().describe('Step execution duration in milliseconds'),\n input: z.record(z.string(), z.unknown()).optional().describe('Input data passed to the node'),\n output: z.record(z.string(), z.unknown()).optional().describe('Output data produced by the node'),\n error: z.object({\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n }).optional().describe('Error details if step failed'),\n retryAttempt: z.number().int().min(0).optional().describe('Retry attempt number (0 = first try)'),\n});\nexport type ExecutionStepLog = z.infer;\n\n/**\n * Execution Log Schema\n * Full execution history for a single flow run.\n *\n * @example\n * {\n * id: 'exec_001',\n * flowName: 'approve_order_flow',\n * flowVersion: 1,\n * status: 'completed',\n * trigger: { type: 'record_change', recordId: 'rec_123', object: 'order' },\n * steps: [\n * { nodeId: 'start', nodeType: 'start', status: 'success', startedAt: '...', durationMs: 1 },\n * { nodeId: 'check_amount', nodeType: 'decision', status: 'success', startedAt: '...', durationMs: 5 },\n * ],\n * startedAt: '2026-02-01T10:00:00Z',\n * completedAt: '2026-02-01T10:00:01Z',\n * durationMs: 1050,\n * }\n */\nexport const ExecutionLogSchema = z.object({\n /** Unique execution ID */\n id: z.string().describe('Execution instance ID'),\n\n /** Flow reference */\n flowName: z.string().describe('Machine name of the executed flow'),\n flowVersion: z.number().int().optional().describe('Version of the flow that was executed'),\n\n /** Execution status */\n status: ExecutionStatus.describe('Current execution status'),\n\n /** Trigger context */\n trigger: z.object({\n type: z.string().describe('Trigger type (e.g., \"record_change\", \"schedule\", \"api\", \"manual\")'),\n recordId: z.string().optional().describe('Triggering record ID'),\n object: z.string().optional().describe('Triggering object name'),\n userId: z.string().optional().describe('User who triggered the execution'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional trigger context'),\n }).describe('What triggered this execution'),\n\n /** Step-by-step execution history */\n steps: z.array(ExecutionStepLogSchema).describe('Ordered list of executed steps'),\n\n /** Execution variables snapshot */\n variables: z.record(z.string(), z.unknown()).optional().describe('Final state of flow variables'),\n\n /** Timing */\n startedAt: z.string().datetime().describe('Execution start timestamp'),\n completedAt: z.string().datetime().optional().describe('Execution completion timestamp'),\n durationMs: z.number().int().min(0).optional().describe('Total execution duration in milliseconds'),\n\n /** Context */\n runAs: z.enum(['system', 'user']).optional().describe('Execution context identity'),\n tenantId: z.string().optional().describe('Tenant ID for multi-tenant isolation'),\n});\nexport type ExecutionLog = z.infer;\n\n// ==========================================\n// 3. Execution Error Tracking & Diagnostics\n// ==========================================\n\n/**\n * Execution Error Severity\n */\nexport const ExecutionErrorSeverity = z.enum([\n 'warning', // Non-fatal issue (e.g., deprecated node type)\n 'error', // Node-level failure (may be retried)\n 'critical', // Flow-level failure (execution terminated)\n]);\nexport type ExecutionErrorSeverity = z.infer;\n\n/**\n * Execution Error Schema\n * Detailed error record for diagnostics and troubleshooting.\n */\nexport const ExecutionErrorSchema = z.object({\n id: z.string().describe('Error record ID'),\n executionId: z.string().describe('Parent execution ID'),\n nodeId: z.string().optional().describe('Node where the error occurred'),\n severity: ExecutionErrorSeverity.describe('Error severity level'),\n code: z.string().describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n stack: z.string().optional().describe('Stack trace for debugging'),\n context: z.record(z.string(), z.unknown()).optional()\n .describe('Additional diagnostic context (input data, config snapshot)'),\n timestamp: z.string().datetime().describe('When the error occurred'),\n retryable: z.boolean().default(false).describe('Whether this error can be retried'),\n resolvedAt: z.string().datetime().optional().describe('When the error was resolved (e.g., after successful retry)'),\n});\nexport type ExecutionError = z.infer;\n\n// ==========================================\n// 4. Checkpointing / Resume\n// ==========================================\n\n/**\n * Checkpoint Schema\n * Captures the execution state at a specific node for pause/resume.\n *\n * Used by wait nodes, user-input screens, and crash recovery.\n */\nexport const CheckpointSchema = z.object({\n /** Unique checkpoint ID */\n id: z.string().describe('Checkpoint ID'),\n\n /** Execution reference */\n executionId: z.string().describe('Parent execution ID'),\n flowName: z.string().describe('Flow machine name'),\n\n /** State snapshot */\n currentNodeId: z.string().describe('Node ID where execution is paused'),\n variables: z.record(z.string(), z.unknown()).describe('Flow variable state at checkpoint'),\n completedNodeIds: z.array(z.string()).describe('List of node IDs already executed'),\n\n /** Timing */\n createdAt: z.string().datetime().describe('Checkpoint creation timestamp'),\n expiresAt: z.string().datetime().optional().describe('Checkpoint expiration (auto-cleanup)'),\n\n /** Reason */\n reason: z.enum(['wait', 'screen_input', 'approval', 'error', 'manual_pause', 'parallel_join', 'boundary_event'])\n .describe('Why the execution was checkpointed'),\n});\nexport type Checkpoint = z.infer;\n\n// ==========================================\n// 5. Concurrency Control\n// ==========================================\n\n/**\n * Concurrency Policy Schema\n * Controls how concurrent executions of the same flow are handled.\n *\n * Industry alignment: Salesforce \"Allow multiple instances\", Temporal \"Workflow ID reuse policy\"\n */\nexport const ConcurrencyPolicySchema = z.object({\n /** Maximum concurrent executions of this flow */\n maxConcurrent: z.number().int().min(1).default(1)\n .describe('Maximum number of concurrent executions allowed'),\n\n /** What to do when max concurrency is reached */\n onConflict: z.enum(['queue', 'reject', 'cancel_existing'])\n .default('queue')\n .describe('queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance'),\n\n /** Lock scope for concurrency */\n lockScope: z.enum(['global', 'per_record', 'per_user'])\n .default('global')\n .describe('Scope of the concurrency lock'),\n\n /** Queue timeout (only when onConflict is \"queue\") */\n queueTimeoutMs: z.number().int().min(0).optional()\n .describe('Maximum time to wait in queue before timing out (ms)'),\n});\nexport type ConcurrencyPolicy = z.infer;\n\n// ==========================================\n// 6. Scheduled Execution Persistence\n// ==========================================\n\n/**\n * Schedule State Schema\n * Tracks the runtime state of scheduled flow executions.\n *\n * Persists next-run times, pause/resume state, and execution history references.\n */\nexport const ScheduleStateSchema = z.object({\n /** Unique schedule ID */\n id: z.string().describe('Schedule instance ID'),\n\n /** Flow reference */\n flowName: z.string().describe('Flow machine name'),\n\n /** Schedule configuration */\n cronExpression: z.string().describe('Cron expression (e.g., \"0 9 * * MON-FRI\")'),\n timezone: z.string().default('UTC').describe('IANA timezone for cron evaluation'),\n\n /** Runtime state */\n status: z.enum(['active', 'paused', 'disabled', 'expired'])\n .default('active')\n .describe('Current schedule status'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution timestamp'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n lastExecutionId: z.string().optional().describe('Execution ID of the last run'),\n lastRunStatus: ExecutionStatus.optional().describe('Status of the last run'),\n\n /** Execution tracking */\n totalRuns: z.number().int().min(0).default(0).describe('Total number of executions'),\n consecutiveFailures: z.number().int().min(0).default(0).describe('Consecutive failed executions'),\n\n /** Bounds */\n startDate: z.string().datetime().optional().describe('Schedule effective start date'),\n endDate: z.string().datetime().optional().describe('Schedule expiration date'),\n maxRuns: z.number().int().min(1).optional().describe('Maximum total executions before auto-disable'),\n\n /** Metadata */\n createdAt: z.string().datetime().describe('Schedule creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n createdBy: z.string().optional().describe('User who created the schedule'),\n});\nexport type ScheduleState = z.infer;\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type ExecutionStepLogParsed = z.infer;\nexport type ExecutionLogParsed = z.infer;\nexport type ExecutionErrorParsed = z.infer;\nexport type CheckpointParsed = z.infer;\nexport type ConcurrencyPolicyParsed = z.infer;\nexport type ScheduleStateParsed = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { FlowSchema } from '../automation/flow.zod';\nimport { ExecutionLogSchema } from '../automation/execution.zod';\n\n/**\n * Automation API Protocol\n *\n * Defines REST CRUD endpoint schemas for managing automation flows,\n * triggering executions, and querying execution history.\n *\n * Base path: /api/automation\n *\n * @example Endpoints\n * GET /api/automation — List flows\n * GET /api/automation/:name — Get flow\n * POST /api/automation — Create flow\n * PUT /api/automation/:name — Update flow\n * DELETE /api/automation/:name — Delete flow\n * POST /api/automation/:name/trigger — Trigger flow execution\n * POST /api/automation/:name/toggle — Enable/disable flow\n * GET /api/automation/:name/runs — List execution runs\n * GET /api/automation/:name/runs/:runId — Get single execution run\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Path parameters for flow-level operations.\n */\nexport const AutomationFlowPathParamsSchema = z.object({\n name: z.string().describe('Flow machine name (snake_case)'),\n});\nexport type AutomationFlowPathParams = z.infer;\n\n/**\n * Path parameters for run-level operations.\n */\nexport const AutomationRunPathParamsSchema = AutomationFlowPathParamsSchema.extend({\n runId: z.string().describe('Execution run ID'),\n});\nexport type AutomationRunPathParams = z.infer;\n\n// ==========================================\n// 2. List Flows (GET /api/automation)\n// ==========================================\n\n/**\n * Query parameters for listing automation flows.\n *\n * @example GET /api/automation?status=active&limit=20\n */\nexport const ListFlowsRequestSchema = z.object({\n status: z.enum(['draft', 'active', 'obsolete', 'invalid']).optional()\n .describe('Filter by flow status'),\n type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).optional()\n .describe('Filter by flow type'),\n limit: z.number().int().min(1).max(100).default(50)\n .describe('Maximum number of flows to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type ListFlowsRequest = z.infer;\n\n/**\n * Summary information for a flow in list results.\n */\nexport const FlowSummarySchema = z.object({\n name: z.string().describe('Flow machine name'),\n label: z.string().describe('Flow display label'),\n type: z.string().describe('Flow type'),\n status: z.string().describe('Flow deployment status'),\n version: z.number().int().describe('Flow version number'),\n enabled: z.boolean().describe('Whether the flow is enabled for execution'),\n nodeCount: z.number().int().optional().describe('Number of nodes in the flow'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n});\nexport type FlowSummary = z.infer;\n\n/**\n * Response for the list flows endpoint.\n */\nexport const ListFlowsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n flows: z.array(FlowSummarySchema).describe('Flow summaries'),\n total: z.number().int().optional().describe('Total matching flows'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more flows are available'),\n }),\n});\nexport type ListFlowsResponse = z.infer;\n\n// ==========================================\n// 3. Get Flow (GET /api/automation/:name)\n// ==========================================\n\n/**\n * Request parameters for getting a single flow.\n */\nexport const GetFlowRequestSchema = AutomationFlowPathParamsSchema;\nexport type GetFlowRequest = z.infer;\n\n/**\n * Response for the get flow endpoint.\n */\nexport const GetFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('Full flow definition'),\n});\nexport type GetFlowResponse = z.infer;\n\n// ==========================================\n// 4. Create Flow (POST /api/automation)\n// ==========================================\n\n/**\n * Request body for creating a new flow.\n *\n * @example POST /api/automation\n * { name: 'approval_flow', label: 'Approval Flow', type: 'autolaunched', ... }\n */\nexport const CreateFlowRequestSchema = FlowSchema;\nexport type CreateFlowRequest = z.input;\n\n/**\n * Response after creating a flow.\n */\nexport const CreateFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('The created flow definition'),\n});\nexport type CreateFlowResponse = z.infer;\n\n// ==========================================\n// 5. Update Flow (PUT /api/automation/:name)\n// ==========================================\n\n/**\n * Request body for updating an existing flow.\n *\n * @example PUT /api/automation/approval_flow\n * { label: 'Updated Label', nodes: [...], edges: [...] }\n */\nexport const UpdateFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n definition: FlowSchema.partial().describe('Partial flow definition to update'),\n});\nexport type UpdateFlowRequest = z.infer;\n\n/**\n * Response after updating a flow.\n */\nexport const UpdateFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('The updated flow definition'),\n});\nexport type UpdateFlowResponse = z.infer;\n\n// ==========================================\n// 6. Delete Flow (DELETE /api/automation/:name)\n// ==========================================\n\n/**\n * Request parameters for deleting a flow.\n */\nexport const DeleteFlowRequestSchema = AutomationFlowPathParamsSchema;\nexport type DeleteFlowRequest = z.infer;\n\n/**\n * Response after deleting a flow.\n */\nexport const DeleteFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n name: z.string().describe('Name of the deleted flow'),\n deleted: z.boolean().describe('Whether the flow was deleted'),\n }),\n});\nexport type DeleteFlowResponse = z.infer;\n\n// ==========================================\n// 7. Trigger Flow (POST /api/automation/:name/trigger)\n// ==========================================\n\n/**\n * Request body for triggering a flow execution.\n *\n * @example POST /api/automation/approval_flow/trigger\n * { record: { id: 'rec-1' }, object: 'account', event: 'on_create' }\n */\nexport const TriggerFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n record: z.record(z.string(), z.unknown()).optional()\n .describe('Record that triggered the automation'),\n object: z.string().optional()\n .describe('Object name the record belongs to'),\n event: z.string().optional()\n .describe('Trigger event type'),\n userId: z.string().optional()\n .describe('User who triggered the automation'),\n params: z.record(z.string(), z.unknown()).optional()\n .describe('Additional contextual data'),\n});\nexport type TriggerFlowRequest = z.infer;\n\n/**\n * Response after triggering a flow execution.\n */\nexport const TriggerFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the automation completed successfully'),\n output: z.unknown().optional().describe('Output data from the automation'),\n error: z.string().optional().describe('Error message if execution failed'),\n durationMs: z.number().optional().describe('Execution duration in milliseconds'),\n }),\n});\nexport type TriggerFlowResponse = z.infer;\n\n// ==========================================\n// 8. Toggle Flow (POST /api/automation/:name/toggle)\n// ==========================================\n\n/**\n * Request body for enabling/disabling a flow.\n *\n * @example POST /api/automation/approval_flow/toggle\n * { enabled: true }\n */\nexport const ToggleFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n enabled: z.boolean().describe('Whether to enable (true) or disable (false) the flow'),\n});\nexport type ToggleFlowRequest = z.infer;\n\n/**\n * Response after toggling a flow.\n */\nexport const ToggleFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n name: z.string().describe('Flow name'),\n enabled: z.boolean().describe('New enabled state'),\n }),\n});\nexport type ToggleFlowResponse = z.infer;\n\n// ==========================================\n// 9. List Runs (GET /api/automation/:name/runs)\n// ==========================================\n\n/**\n * Query parameters for listing execution runs.\n *\n * @example GET /api/automation/approval_flow/runs?status=completed&limit=10\n */\nexport const ListRunsRequestSchema = AutomationFlowPathParamsSchema.extend({\n status: z.enum(['pending', 'running', 'paused', 'completed', 'failed', 'cancelled', 'timed_out', 'retrying']).optional()\n .describe('Filter by execution status'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of runs to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type ListRunsRequest = z.infer;\n\n/**\n * Response for the list runs endpoint.\n */\nexport const ListRunsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n runs: z.array(ExecutionLogSchema).describe('Execution run logs'),\n total: z.number().int().optional().describe('Total matching runs'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more runs are available'),\n }),\n});\nexport type ListRunsResponse = z.infer;\n\n// ==========================================\n// 10. Get Run (GET /api/automation/:name/runs/:runId)\n// ==========================================\n\n/**\n * Request parameters for getting a single execution run.\n */\nexport const GetRunRequestSchema = AutomationRunPathParamsSchema;\nexport type GetRunRequest = z.infer;\n\n/**\n * Response for the get run endpoint.\n */\nexport const GetRunResponseSchema = BaseResponseSchema.extend({\n data: ExecutionLogSchema.describe('Full execution log with step details'),\n});\nexport type GetRunResponse = z.infer;\n\n// ==========================================\n// 11. Automation API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Automation operations.\n */\nexport const AutomationApiErrorCode = z.enum([\n 'flow_not_found',\n 'flow_already_exists',\n 'flow_validation_failed',\n 'flow_disabled',\n 'execution_not_found',\n 'execution_failed',\n 'execution_timeout',\n 'node_executor_not_found',\n 'concurrent_execution_limit',\n]);\nexport type AutomationApiErrorCode = z.infer;\n\n// ==========================================\n// 12. Automation API Contract Registry\n// ==========================================\n\n/**\n * Standard Automation API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const AutomationApiContracts = {\n listFlows: {\n method: 'GET' as const,\n path: '/api/automation',\n input: ListFlowsRequestSchema,\n output: ListFlowsResponseSchema,\n },\n getFlow: {\n method: 'GET' as const,\n path: '/api/automation/:name',\n input: GetFlowRequestSchema,\n output: GetFlowResponseSchema,\n },\n createFlow: {\n method: 'POST' as const,\n path: '/api/automation',\n input: CreateFlowRequestSchema,\n output: CreateFlowResponseSchema,\n },\n updateFlow: {\n method: 'PUT' as const,\n path: '/api/automation/:name',\n input: UpdateFlowRequestSchema,\n output: UpdateFlowResponseSchema,\n },\n deleteFlow: {\n method: 'DELETE' as const,\n path: '/api/automation/:name',\n input: DeleteFlowRequestSchema,\n output: DeleteFlowResponseSchema,\n },\n triggerFlow: {\n method: 'POST' as const,\n path: '/api/automation/:name/trigger',\n input: TriggerFlowRequestSchema,\n output: TriggerFlowResponseSchema,\n },\n toggleFlow: {\n method: 'POST' as const,\n path: '/api/automation/:name/toggle',\n input: ToggleFlowRequestSchema,\n output: ToggleFlowResponseSchema,\n },\n listRuns: {\n method: 'GET' as const,\n path: '/api/automation/:name/runs',\n input: ListRunsRequestSchema,\n output: ListRunsResponseSchema,\n },\n getRun: {\n method: 'GET' as const,\n path: '/api/automation/:name/runs/:runId',\n input: GetRunRequestSchema,\n output: GetRunResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\n\n/**\n * # Package Upgrade Protocol\n * \n * Defines the complete lifecycle for upgrading installed packages,\n * including pre-upgrade analysis, snapshot/backup, execution, validation,\n * and rollback capabilities.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Package upgrade with push upgrades and subscriber control\n * - **ServiceNow**: Update Sets with preview, commit, and back-out support\n * - **Helm**: Helm upgrade with rollback to previous release\n * - **Kubernetes**: Rolling update with readiness probes and automatic rollback\n * \n * ## Upgrade Flow\n * ```\n * 1. PreCheck → Validate compatibility, check dependencies\n * 2. Plan → Generate upgrade plan with metadata diff\n * 3. Snapshot → Backup current state (metadata + customizations)\n * 4. Execute → Apply new package metadata with 3-way merge\n * 5. Validate → Run post-upgrade health checks\n * 6. Commit → Finalize upgrade (or Rollback on failure)\n * ```\n */\n\n// ==========================================\n// Upgrade Plan & Analysis\n// ==========================================\n\n/**\n * Metadata Change Type\n * Type of change detected between package versions.\n */\nexport const MetadataChangeTypeSchema = z.enum([\n 'added', // New metadata item added in new version\n 'modified', // Existing metadata item modified\n 'removed', // Metadata item removed in new version\n 'renamed', // Metadata item renamed\n]).describe('Type of metadata change between package versions');\n\n/**\n * Metadata Diff Item\n * Describes a single metadata change between two package versions.\n */\nexport const MetadataDiffItemSchema = z.object({\n /** Metadata type (e.g. \"object\", \"view\", \"flow\") */\n type: z.string().describe('Metadata type'),\n\n /** Metadata name */\n name: z.string().describe('Metadata name'),\n\n /** Type of change */\n changeType: MetadataChangeTypeSchema.describe('Category of metadata modification (added, modified, removed, or renamed)'),\n\n /** Whether this change has potential conflicts with customizations */\n hasConflict: z.boolean().default(false)\n .describe('Whether this change may conflict with customizations'),\n\n /** Human-readable summary of the change */\n summary: z.string().optional().describe('Human-readable change summary'),\n\n /** Previous name (for renames) */\n previousName: z.string().optional().describe('Previous name if renamed'),\n}).describe('Single metadata change between package versions');\n\n/**\n * Upgrade Impact Level\n * Indicates the severity of impact the upgrade will have.\n */\nexport const UpgradeImpactLevelSchema = z.enum([\n 'none', // No impact, seamless upgrade\n 'low', // Minor changes, no user action needed\n 'medium', // Some changes that may affect workflows\n 'high', // Significant changes, user review recommended\n 'critical', // Breaking changes, manual intervention required\n]).describe('Severity of upgrade impact');\n\n/**\n * Upgrade Plan Schema\n * The analysis result before executing an upgrade.\n * Generated by comparing old version metadata with new version metadata.\n */\nexport const UpgradePlanSchema = z.object({\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Current installed version */\n fromVersion: z.string().describe('Currently installed version'),\n\n /** Target version to upgrade to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Overall impact level */\n impactLevel: UpgradeImpactLevelSchema.describe('Severity assessment from none (seamless) to critical (breaking changes)'),\n\n /** List of all metadata changes between versions */\n changes: z.array(MetadataDiffItemSchema).describe('All metadata changes'),\n\n /** Number of customer customizations that may be affected */\n affectedCustomizations: z.number().int().min(0).default(0)\n .describe('Count of customizations that may be affected'),\n\n /** Whether any migration scripts need to run */\n requiresMigration: z.boolean().default(false)\n .describe('Whether data migration scripts are needed'),\n\n /** Migration script paths (relative to package root) */\n migrationScripts: z.array(z.string()).optional()\n .describe('Paths to migration scripts'),\n\n /** Dependencies that also need upgrading */\n dependencyUpgrades: z.array(z.object({\n packageId: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n })).optional().describe('Dependent packages that also need upgrading'),\n\n /** Estimated upgrade duration in seconds */\n estimatedDuration: z.number().int().min(0).optional()\n .describe('Estimated upgrade duration in seconds'),\n\n /** Human-readable summary */\n summary: z.string().optional().describe('Human-readable upgrade summary'),\n}).describe('Upgrade analysis plan generated before execution');\n\n// ==========================================\n// Upgrade Snapshot (Pre-Upgrade Backup)\n// ==========================================\n\n/**\n * Upgrade Snapshot Schema\n * Captures the complete state before an upgrade for rollback capability.\n */\nexport const UpgradeSnapshotSchema = z.object({\n /** Snapshot ID (UUID) */\n id: z.string().describe('Snapshot identifier'),\n\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being upgraded from */\n fromVersion: z.string().describe('Version before upgrade'),\n\n /** Version being upgraded to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Complete manifest of the old package version */\n previousManifest: ManifestSchema.describe('Complete manifest of the previous package version'),\n\n /**\n * Snapshot of all metadata records owned by this package.\n * Stored as array of { type, name, metadata } tuples.\n */\n metadataSnapshot: z.array(z.object({\n type: z.string(),\n name: z.string(),\n metadata: z.record(z.string(), z.unknown()),\n })).describe('Snapshot of all package metadata'),\n\n /**\n * Snapshot of all customer customizations (overlays) for this package's metadata.\n */\n customizationSnapshot: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Snapshot of customer customizations'),\n\n /** When the snapshot was created */\n createdAt: z.string().datetime().describe('Snapshot creation timestamp'),\n\n /** Expiry time for snapshot cleanup */\n expiresAt: z.string().datetime().optional().describe('Snapshot expiry timestamp'),\n}).describe('Pre-upgrade state snapshot for rollback capability');\n\n// ==========================================\n// Upgrade Request/Response\n// ==========================================\n\n/**\n * Upgrade Package Request\n */\nexport const UpgradePackageRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (if omitted, upgrades to latest) */\n targetVersion: z.string().optional().describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional().describe('New manifest (if installing from local)'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum([\n 'keep-custom',\n 'accept-incoming',\n 'three-way-merge',\n ]).default('three-way-merge').describe('How to handle customer customizations'),\n\n /** Whether to run in dry-run mode (preview only, no changes) */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Whether to skip pre-upgrade validation */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\n\n/**\n * Upgrade Phase\n * Current phase of the upgrade process.\n */\nexport const UpgradePhaseSchema = z.enum([\n 'pending', // Upgrade requested but not started\n 'analyzing', // Generating upgrade plan\n 'snapshot', // Creating pre-upgrade snapshot\n 'executing', // Applying metadata changes\n 'migrating', // Running migration scripts\n 'validating', // Post-upgrade validation\n 'completed', // Upgrade completed successfully\n 'failed', // Upgrade failed\n 'rolling-back', // Rollback in progress\n 'rolled-back', // Rollback completed\n]).describe('Current phase of the upgrade process');\n\n/**\n * Upgrade Package Response\n */\nexport const UpgradePackageResponseSchema = z.object({\n /** Whether the upgrade was successful */\n success: z.boolean().describe('Whether the upgrade succeeded'),\n\n /** Current upgrade phase */\n phase: UpgradePhaseSchema.describe('Current upgrade phase'),\n\n /** The upgrade plan that was executed */\n plan: UpgradePlanSchema.optional().describe('Upgrade plan'),\n\n /** Snapshot ID for rollback */\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n\n /** Merge conflicts that need manual resolution (if any) */\n conflicts: z.array(z.object({\n path: z.string(),\n baseValue: z.unknown(),\n incomingValue: z.unknown(),\n customValue: z.unknown(),\n })).optional().describe('Unresolved merge conflicts'),\n\n /** Error message (if failed) */\n errorMessage: z.string().optional().describe('Error message if upgrade failed'),\n\n /** Human-readable summary */\n message: z.string().optional().describe('Human-readable status message'),\n}).describe('Upgrade package response');\n\n// ==========================================\n// Rollback\n// ==========================================\n\n/**\n * Rollback Package Request\n */\nexport const RollbackPackageRequestSchema = z.object({\n /** Package ID to rollback */\n packageId: z.string().describe('Package ID to rollback'),\n\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\n\n/**\n * Rollback Package Response\n */\nexport const RollbackPackageResponseSchema = z.object({\n /** Whether the rollback was successful */\n success: z.boolean().describe('Whether the rollback succeeded'),\n\n /** Restored version */\n restoredVersion: z.string().optional().describe('Version restored to'),\n\n /** Message */\n message: z.string().optional().describe('Rollback status message'),\n}).describe('Rollback package response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type MetadataChangeType = z.infer;\nexport type MetadataDiffItem = z.infer;\nexport type UpgradeImpactLevel = z.infer;\nexport type UpgradePlan = z.infer;\nexport type UpgradeSnapshot = z.infer;\nexport type UpgradePackageRequest = z.infer;\nexport type UpgradePhase = z.infer;\nexport type UpgradePackageResponse = z.infer;\nexport type RollbackPackageRequest = z.infer;\nexport type RollbackPackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Package Artifact Format Protocol\n *\n * Defines the standard structure of a package artifact (.tgz) produced by\n * `os plugin build`. The marketplace uses these schemas to validate, store,\n * and distribute package artifacts.\n *\n * ## Artifact Internal Structure\n * ```\n * ├── manifest.json ← ManifestSchema serialized\n * ├── metadata/ ← 30+ metadata types (JSON)\n * │ ├── objects/ ← *.object.json\n * │ ├── views/ ← *.view.json\n * │ ├── pages/ ← *.page.json\n * │ ├── flows/ ← *.flow.json\n * │ ├── dashboards/ ← *.dashboard.json\n * │ ├── permissions/ ← *.permission.json\n * │ ├── agents/ ← *.agent.json\n * │ └── ... ← Other metadata types\n * ├── assets/ ← Static resources\n * │ ├── icon.svg\n * │ └── screenshots/\n * ├── data/ ← Seed data (DatasetSchema serialized)\n * ├── locales/ ← i18n translation files\n * ├── checksums.json ← SHA256 checksum per file\n * └── signature.sig ← RSA-SHA256 package signature\n * ```\n *\n * ## Architecture Alignment\n * - **Salesforce**: Managed Package .zip with metadata components\n * - **npm**: .tgz with package.json + contents\n * - **Helm**: Chart .tgz with Chart.yaml + templates\n * - **VS Code**: .vsix (zip) with extension manifest + assets\n */\n\n// ==========================================\n// Metadata Category Definitions\n// ==========================================\n\n/**\n * Supported metadata categories within an artifact.\n * Each category maps to a subdirectory under `metadata/`.\n */\nexport const MetadataCategoryEnum = z.enum([\n 'objects',\n 'views',\n 'pages',\n 'flows',\n 'dashboards',\n 'permissions',\n 'agents',\n 'reports',\n 'actions',\n 'translations',\n 'themes',\n 'datasets',\n 'apis',\n 'triggers',\n 'workflows',\n]).describe('Metadata category within the artifact');\n\nexport type MetadataCategory = z.infer;\n\n// ==========================================\n// Artifact File Entry\n// ==========================================\n\n/**\n * A single file entry within the artifact.\n */\nexport const ArtifactFileEntrySchema = z.object({\n /** Relative path within the artifact (e.g. \"metadata/objects/account.object.json\") */\n path: z.string().describe('Relative file path within the artifact'),\n\n /** File size in bytes */\n size: z.number().int().nonnegative().describe('File size in bytes'),\n\n /** Metadata category (if under metadata/) */\n category: MetadataCategoryEnum.optional()\n .describe('Metadata category this file belongs to'),\n}).describe('A single file entry within the artifact');\n\nexport type ArtifactFileEntry = z.infer;\n\n// ==========================================\n// Artifact Checksum\n// ==========================================\n\n/**\n * Checksum map for artifact integrity verification.\n * Maps relative file paths to their SHA256 hash values.\n *\n * @example\n * {\n * \"manifest.json\": \"a1b2c3...\",\n * \"metadata/objects/account.object.json\": \"d4e5f6...\"\n * }\n */\nexport const ArtifactChecksumSchema = z.object({\n /** Hash algorithm used (default: SHA256) */\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm used for checksums'),\n\n /** Map of relative file paths to their hash values */\n files: z.record(z.string(), z.string().regex(/^[a-f0-9]+$/))\n .describe('File path to hash value mapping'),\n}).describe('Checksum manifest for artifact integrity verification');\n\nexport type ArtifactChecksum = z.infer;\n\n// ==========================================\n// Artifact Signature\n// ==========================================\n\n/**\n * Digital signature for artifact authenticity verification.\n * Ensures the artifact was produced by a trusted publisher and has not been tampered with.\n */\nexport const ArtifactSignatureSchema = z.object({\n /** Signature algorithm */\n algorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).default('RSA-SHA256')\n .describe('Signing algorithm used'),\n\n /** Public key reference (URL or fingerprint) for verification */\n publicKeyRef: z.string()\n .describe('Public key reference (URL or fingerprint) for signature verification'),\n\n /** Base64-encoded signature value */\n signature: z.string()\n .describe('Base64-encoded digital signature'),\n\n /** Timestamp of when the artifact was signed */\n signedAt: z.string().datetime().optional()\n .describe('ISO 8601 timestamp of when the artifact was signed'),\n\n /** Signer identity (publisher ID or email) */\n signedBy: z.string().optional()\n .describe('Identity of the signer (publisher ID or email)'),\n}).describe('Digital signature for artifact authenticity verification');\n\nexport type ArtifactSignature = z.infer;\n\n// ==========================================\n// Package Artifact Schema\n// ==========================================\n\n/**\n * Package Artifact Schema\n *\n * Describes the complete structure and metadata of a built package artifact.\n * This schema is used to validate artifacts before upload to the marketplace.\n */\nexport const PackageArtifactSchema = z.object({\n /** Artifact format version (for forward compatibility) */\n formatVersion: z.string().regex(/^\\d+\\.\\d+$/).default('1.0')\n .describe('Artifact format version (e.g. \"1.0\")'),\n\n /** Package ID from the manifest */\n packageId: z.string().describe('Package identifier from manifest'),\n\n /** Package version from the manifest */\n version: z.string().describe('Package version from manifest'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format of the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().positive().optional()\n .describe('Total artifact file size in bytes'),\n\n /** Build timestamp */\n builtAt: z.string().datetime()\n .describe('ISO 8601 timestamp of when the artifact was built'),\n\n /** Build tool and version that produced this artifact */\n builtWith: z.string().optional()\n .describe('Build tool identifier (e.g. \"os-cli@3.2.0\")'),\n\n /** File listing within the artifact */\n files: z.array(ArtifactFileEntrySchema).optional()\n .describe('List of files contained in the artifact'),\n\n /** Metadata categories present in the artifact */\n metadataCategories: z.array(MetadataCategoryEnum).optional()\n .describe('Metadata categories included in this artifact'),\n\n /** Integrity checksums for all files */\n checksums: ArtifactChecksumSchema.optional()\n .describe('SHA256 checksums for artifact integrity verification'),\n\n /** Digital signature for authenticity */\n signature: ArtifactSignatureSchema.optional()\n .describe('Digital signature for artifact authenticity verification'),\n}).describe('Package artifact structure and metadata');\n\nexport type PackageArtifact = z.infer;\nexport type PackageArtifactInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Marketplace Protocol\n * \n * Defines the core schemas for the plugin marketplace ecosystem, covering:\n * - **Developer Side**: Package publishing, submission, and version releases\n * - **Platform Side**: Marketplace listing, review, approval, and discovery\n * \n * This protocol defines the contract between plugin developers, the marketplace\n * platform, and customers who install plugins.\n * \n * ## Architecture Alignment\n * - **Salesforce AppExchange**: Security review, managed packages, listing profiles\n * - **VS Code Marketplace**: Extension publishing, ratings, verified publishers\n * - **npm Registry**: Package publishing, versioning, scoped packages\n * - **Shopify App Store**: App review process, billing integration, merchant installs\n * \n * ## Developer Publishing Flow\n * ```\n * 1. Develop → Build plugin locally using ObjectStack CLI\n * 2. Validate → Run `os plugin validate` (schema + security checks)\n * 3. Build → Run `os plugin build` (bundle + sign)\n * 4. Submit → Run `os plugin publish` (submit to marketplace)\n * 5. Review → Platform conducts automated + manual review\n * 6. Publish → Approved listing goes live on marketplace\n * ```\n * \n * ## Platform Management Flow\n * ```\n * 1. Receive → Accept submissions from verified publishers\n * 2. Scan → Automated security scan and compatibility check\n * 3. Review → Human review for quality and policy compliance\n * 4. Catalog → Index in marketplace search catalog\n * 5. Monitor → Track installs, ratings, issues, and enforce SLAs\n * ```\n */\n\n// ==========================================\n// Publisher Identity\n// ==========================================\n\n/**\n * Publisher Verification Status\n */\nexport const PublisherVerificationSchema = z.enum([\n 'unverified', // Not yet verified\n 'pending', // Verification in progress\n 'verified', // Identity verified by platform\n 'trusted', // Trusted publisher (track record of quality)\n 'partner', // Official platform partner\n]).describe('Publisher verification status');\n\n/**\n * Publisher Schema\n * Represents a developer or organization that publishes packages.\n */\nexport const PublisherSchema = z.object({\n /** Publisher unique identifier */\n id: z.string().describe('Publisher ID'),\n\n /** Display name */\n name: z.string().describe('Publisher display name'),\n\n /** Publisher type */\n type: z.enum(['individual', 'organization']).describe('Publisher type'),\n\n /** Verification status */\n verification: PublisherVerificationSchema.default('unverified')\n .describe('Publisher verification status'),\n\n /** Contact email */\n email: z.string().email().optional().describe('Contact email'),\n\n /** Website URL */\n website: z.string().url().optional().describe('Publisher website'),\n\n /** Organization logo URL */\n logoUrl: z.string().url().optional().describe('Publisher logo URL'),\n\n /** Short description/bio */\n description: z.string().optional().describe('Publisher description'),\n\n /** Registration date */\n registeredAt: z.string().datetime().optional()\n .describe('Publisher registration timestamp'),\n}).describe('Developer or organization that publishes packages');\n\n// ==========================================\n// Artifact Reference & Distribution\n// ==========================================\n\n/**\n * Artifact Reference Schema\n *\n * Points to a downloadable package artifact with integrity verification.\n * Used in marketplace listings and install workflows.\n */\nexport const ArtifactReferenceSchema = z.object({\n /** Artifact download URL */\n url: z.string().url().describe('Artifact download URL'),\n\n /** SHA256 integrity checksum */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA256 checksum'),\n\n /** File size in bytes */\n size: z.number().int().positive().describe('Artifact size in bytes'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz').describe('Artifact format'),\n\n /** Upload timestamp */\n uploadedAt: z.string().datetime().describe('Upload timestamp'),\n}).describe('Reference to a downloadable package artifact');\n\nexport type ArtifactReference = z.infer;\n\n/**\n * Artifact Download Response Schema\n *\n * Response from the artifact download API endpoint.\n * Provides a time-limited download URL with integrity metadata.\n */\nexport const ArtifactDownloadResponseSchema = z.object({\n /** Pre-signed or direct download URL */\n downloadUrl: z.string().url().describe('Artifact download URL (may be pre-signed)'),\n\n /** SHA256 checksum for download verification */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA256 checksum for verification'),\n\n /** File size in bytes */\n size: z.number().int().positive().describe('Artifact size in bytes'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).describe('Artifact format'),\n\n /** URL expiration time (for pre-signed URLs) */\n expiresAt: z.string().datetime().optional()\n .describe('URL expiration timestamp for pre-signed URLs'),\n}).describe('Artifact download response with integrity metadata');\n\nexport type ArtifactDownloadResponse = z.infer;\n\n// ==========================================\n// Marketplace Listing\n// ==========================================\n\n/**\n * Marketplace Category\n */\nexport const MarketplaceCategorySchema = z.enum([\n 'crm', // Customer Relationship Management\n 'erp', // Enterprise Resource Planning\n 'hr', // Human Resources\n 'finance', // Finance & Accounting\n 'project', // Project Management\n 'collaboration', // Collaboration & Communication\n 'analytics', // Analytics & Reporting\n 'integration', // Integrations & Connectors\n 'automation', // Automation & Workflows\n 'ai', // AI & Machine Learning\n 'security', // Security & Compliance\n 'developer-tools', // Developer Tools\n 'ui-theme', // UI Themes & Appearance\n 'storage', // Storage & Drivers\n 'other', // Other / Uncategorized\n]).describe('Marketplace package category');\n\n/**\n * Listing Status\n */\nexport const ListingStatusSchema = z.enum([\n 'draft', // Not yet submitted\n 'submitted', // Submitted for review\n 'in-review', // Under review\n 'approved', // Approved, ready to publish\n 'published', // Live on marketplace\n 'rejected', // Review rejected\n 'suspended', // Suspended by platform (policy violation)\n 'deprecated', // Deprecated by publisher\n 'unlisted', // Available by direct link only\n]).describe('Marketplace listing status');\n\n/**\n * Pricing Model\n */\nexport const PricingModelSchema = z.enum([\n 'free', // Free to install\n 'freemium', // Free with paid premium features\n 'paid', // Requires purchase\n 'subscription', // Recurring subscription\n 'usage-based', // Pay per usage\n 'contact-sales', // Enterprise pricing, contact for quote\n]).describe('Package pricing model');\n\n/**\n * Marketplace Listing Schema\n * \n * The public-facing profile of a package on the marketplace.\n * Contains marketing information, pricing, and installation metadata.\n */\nexport const MarketplaceListingSchema = z.object({\n /** Listing ID (matches package ID) */\n id: z.string().describe('Listing ID (matches package manifest ID)'),\n\n /** Package ID (reverse domain notation) */\n packageId: z.string().describe('Package identifier'),\n\n /** Publisher information */\n publisherId: z.string().describe('Publisher ID'),\n\n /** Current listing status */\n status: ListingStatusSchema.default('draft')\n .describe('Publication state: draft, published, under-review, suspended, deprecated, or unlisted'),\n\n /** Display name */\n name: z.string().describe('Display name'),\n\n /** Tagline (short description for cards/search results) */\n tagline: z.string().max(120).optional().describe('Short tagline (max 120 chars)'),\n\n /** Full description (supports Markdown) */\n description: z.string().optional().describe('Full description (Markdown)'),\n\n /** Category */\n category: MarketplaceCategorySchema.describe('Package category'),\n\n /** Additional tags for search discovery */\n tags: z.array(z.string()).optional().describe('Search tags'),\n\n /** Icon/logo URL */\n iconUrl: z.string().url().optional().describe('Package icon URL'),\n\n /** Screenshot URLs */\n screenshots: z.array(z.object({\n url: z.string().url(),\n caption: z.string().optional(),\n })).optional().describe('Screenshots'),\n\n /** Documentation URL */\n documentationUrl: z.string().url().optional()\n .describe('Documentation URL'),\n\n /** Support URL */\n supportUrl: z.string().url().optional()\n .describe('Support URL'),\n\n /** Source repository URL (if open source) */\n repositoryUrl: z.string().url().optional()\n .describe('Source repository URL'),\n\n /** Pricing model */\n pricing: PricingModelSchema.default('free')\n .describe('Pricing model'),\n\n /** Price in cents (if paid) */\n priceInCents: z.number().int().min(0).optional()\n .describe('Price in cents (e.g. 999 = $9.99)'),\n\n /** Latest published version */\n latestVersion: z.string().describe('Latest published version'),\n\n /** Minimum platform version required */\n minPlatformVersion: z.string().optional()\n .describe('Minimum ObjectStack platform version'),\n\n /** Available versions for installation */\n versions: z.array(z.object({\n version: z.string().describe('Version string'),\n releaseDate: z.string().datetime().describe('Release date'),\n releaseNotes: z.string().optional().describe('Release notes'),\n minPlatformVersion: z.string().optional().describe('Minimum platform version'),\n deprecated: z.boolean().default(false).describe('Whether this version is deprecated'),\n /** Artifact reference for this version */\n artifact: ArtifactReferenceSchema.optional()\n .describe('Downloadable artifact for this version'),\n })).optional().describe('Published versions'),\n\n /** Aggregate statistics */\n stats: z.object({\n totalInstalls: z.number().int().min(0).default(0).describe('Total installs'),\n activeInstalls: z.number().int().min(0).default(0).describe('Active installs'),\n averageRating: z.number().min(0).max(5).optional().describe('Average user rating (0-5)'),\n totalRatings: z.number().int().min(0).default(0).describe('Total ratings count'),\n totalReviews: z.number().int().min(0).default(0).describe('Total reviews count'),\n }).optional().describe('Aggregate marketplace statistics'),\n\n /** First published date */\n publishedAt: z.string().datetime().optional()\n .describe('First published timestamp'),\n\n /** Last updated date */\n updatedAt: z.string().datetime().optional()\n .describe('Last updated timestamp'),\n}).describe('Public-facing package listing on the marketplace');\n\n// ==========================================\n// Package Submission & Review\n// ==========================================\n\n/**\n * Package Submission Schema\n * A developer's submission of a package version for marketplace review.\n */\nexport const PackageSubmissionSchema = z.object({\n /** Submission ID */\n id: z.string().describe('Submission ID'),\n\n /** Package ID */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being submitted */\n version: z.string().describe('Version being submitted'),\n\n /** Publisher ID */\n publisherId: z.string().describe('Publisher submitting'),\n\n /** Submission status */\n status: z.enum([\n 'pending', // Awaiting review\n 'scanning', // Automated scan in progress\n 'in-review', // Under manual review\n 'changes-requested', // Reviewer requests changes\n 'approved', // Approved for publishing\n 'rejected', // Rejected\n ]).default('pending').describe('Review status'),\n\n /**\n * Package artifact URL or reference.\n * Points to the built package bundle for review.\n */\n artifactUrl: z.string().describe('Package artifact URL for review'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional().describe('Release notes for this version'),\n\n /** Whether this is the first submission (new listing) vs version update */\n isNewListing: z.boolean().default(false).describe('Whether this is a new listing submission'),\n\n /** Automated scan results */\n scanResults: z.object({\n /** Whether automated scan passed */\n passed: z.boolean(),\n /** Security scan score (0-100) */\n securityScore: z.number().min(0).max(100).optional(),\n /** Compatibility check passed */\n compatibilityCheck: z.boolean().optional(),\n /** Issues found during scan */\n issues: z.array(z.object({\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),\n message: z.string(),\n file: z.string().optional(),\n line: z.number().optional(),\n })).optional(),\n }).optional().describe('Automated scan results'),\n\n /** Reviewer notes (from platform reviewer) */\n reviewerNotes: z.string().optional().describe('Notes from the platform reviewer'),\n\n /** Submitted timestamp */\n submittedAt: z.string().datetime().optional().describe('Submission timestamp'),\n\n /** Review completed timestamp */\n reviewedAt: z.string().datetime().optional().describe('Review completion timestamp'),\n}).describe('Developer submission of a package version for review');\n\n// ==========================================\n// Marketplace Search & Discovery\n// ==========================================\n\n/**\n * Marketplace Search Request\n */\nexport const MarketplaceSearchRequestSchema = z.object({\n /** Search query string */\n query: z.string().optional().describe('Full-text search query'),\n\n /** Filter by category */\n category: MarketplaceCategorySchema.optional().describe('Filter by category'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Filter by pricing model */\n pricing: PricingModelSchema.optional().describe('Filter by pricing model'),\n\n /** Filter by publisher verification level */\n publisherVerification: PublisherVerificationSchema.optional()\n .describe('Filter by publisher verification level'),\n\n /** Sort by */\n sortBy: z.enum([\n 'relevance', // Best match (default for search)\n 'popularity', // Most installs\n 'rating', // Highest rated\n 'newest', // Most recently published\n 'updated', // Most recently updated\n 'name', // Alphabetical\n ]).default('relevance').describe('Sort field'),\n\n /** Sort direction */\n sortDirection: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n\n /** Pagination: page number */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(100).default(20).describe('Items per page'),\n\n /** Filter by minimum platform version compatibility */\n platformVersion: z.string().optional()\n .describe('Filter by platform version compatibility'),\n}).describe('Marketplace search request');\n\n/**\n * Marketplace Search Response\n */\nexport const MarketplaceSearchResponseSchema = z.object({\n /** Search results */\n items: z.array(MarketplaceListingSchema).describe('Search result listings'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching results'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page number'),\n\n /** Items per page */\n pageSize: z.number().int().min(1).describe('Items per page'),\n\n /** Facets for filtering */\n facets: z.object({\n categories: z.array(z.object({\n category: MarketplaceCategorySchema,\n count: z.number().int().min(0),\n })).optional(),\n pricing: z.array(z.object({\n model: PricingModelSchema,\n count: z.number().int().min(0),\n })).optional(),\n }).optional().describe('Aggregation facets for refining search'),\n}).describe('Marketplace search response');\n\n// ==========================================\n// Marketplace Install from Marketplace\n// ==========================================\n\n/**\n * Install from Marketplace Request\n * Extends the basic package install with marketplace-specific fields.\n */\nexport const MarketplaceInstallRequestSchema = z.object({\n /** Listing ID to install */\n listingId: z.string().describe('Marketplace listing ID'),\n\n /** Specific version to install (defaults to latest) */\n version: z.string().optional().describe('Version to install'),\n\n /** License key (for paid packages) */\n licenseKey: z.string().optional().describe('License key for paid packages'),\n\n /** User-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n\n /** Whether to enable immediately after install */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n\n /** Artifact reference (resolved from listing version, or provided directly) */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference for direct installation'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n}).describe('Install from marketplace request');\n\n/**\n * Install from Marketplace Response\n */\nexport const MarketplaceInstallResponseSchema = z.object({\n /** Whether installation was successful */\n success: z.boolean().describe('Whether installation succeeded'),\n\n /** Installed package ID */\n packageId: z.string().optional().describe('Installed package identifier'),\n\n /** Installed version */\n version: z.string().optional().describe('Installed version'),\n\n /** Human-readable message */\n message: z.string().optional().describe('Installation status message'),\n}).describe('Install from marketplace response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type PublisherVerification = z.infer;\nexport type Publisher = z.infer;\nexport type MarketplaceCategory = z.infer;\nexport type ListingStatus = z.infer;\nexport type PricingModel = z.infer;\nexport type MarketplaceListing = z.infer;\nexport type PackageSubmission = z.infer;\nexport type MarketplaceSearchRequest = z.infer;\nexport type MarketplaceSearchResponse = z.infer;\nexport type MarketplaceInstallRequest = z.infer;\nexport type MarketplaceInstallResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { InstalledPackageSchema } from '../kernel/package-registry.zod';\nimport { DependencyResolutionResultSchema } from '../kernel/dependency-resolution.zod';\nimport { UpgradePlanSchema } from '../kernel/package-upgrade.zod';\nimport { PackageArtifactSchema } from '../kernel/package-artifact.zod';\nimport { ManifestSchema } from '../kernel/manifest.zod';\nimport { ArtifactReferenceSchema } from '../cloud/marketplace.zod';\n\n/**\n * # Package API Protocol\n *\n * REST API endpoint schemas for package lifecycle management.\n *\n * Base path: /api/v1/packages\n *\n * @example Endpoints\n * POST /api/v1/packages/install — Install a package\n * POST /api/v1/packages/upgrade — Upgrade a package\n * POST /api/v1/packages/resolve-dependencies — Resolve dependencies\n * POST /api/v1/packages/upload — Upload an artifact\n * GET /api/v1/packages — List installed packages\n * GET /api/v1/packages/:packageId — Get package details\n * POST /api/v1/packages/:packageId/rollback — Rollback a package\n * DELETE /api/v1/packages/:packageId — Uninstall a package\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Path parameters for package-level operations.\n */\nexport const PackagePathParamsSchema = z.object({\n packageId: z.string().describe('Package identifier'),\n});\nexport type PackagePathParams = z.infer;\n\n// ==========================================\n// 2. List Packages (GET /api/v1/packages)\n// ==========================================\n\n/**\n * Query parameters for listing installed packages.\n */\nexport const ListInstalledPackagesRequestSchema = z.object({\n /** Filter by package status */\n status: z.enum(['installed', 'disabled', 'installing', 'upgrading', 'uninstalling', 'error']).optional()\n .describe('Filter by package status'),\n /** Filter by enabled state */\n enabled: z.boolean().optional()\n .describe('Filter by enabled state'),\n /** Maximum number of packages to return */\n limit: z.number().int().min(1).max(100).default(50)\n .describe('Maximum number of packages to return'),\n /** Cursor for pagination */\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n}).describe('List installed packages request');\nexport type ListInstalledPackagesRequest = z.infer;\n\n/**\n * Response for listing installed packages.\n */\nexport const ListInstalledPackagesResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n packages: z.array(InstalledPackageSchema).describe('Installed packages'),\n total: z.number().int().optional().describe('Total matching packages'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more packages are available'),\n }),\n}).describe('List installed packages response');\nexport type ListInstalledPackagesResponse = z.infer;\n\n// ==========================================\n// 3. Get Package (GET /api/v1/packages/:packageId)\n// ==========================================\n\n/**\n * Request for getting a single installed package.\n */\nexport const GetInstalledPackageRequestSchema = PackagePathParamsSchema;\nexport type GetInstalledPackageRequest = z.infer;\n\n/**\n * Response for getting a single installed package.\n */\nexport const GetInstalledPackageResponseSchema = BaseResponseSchema.extend({\n data: InstalledPackageSchema.describe('Installed package details'),\n}).describe('Get installed package response');\nexport type GetInstalledPackageResponse = z.infer;\n\n// ==========================================\n// 4. Install Package (POST /api/v1/packages/install)\n// ==========================================\n\n/**\n * Request body for installing a package.\n *\n * @example POST /api/v1/packages/install\n * { manifest: {...}, platformVersion: '3.2.0', enableOnInstall: true }\n */\nexport const PackageInstallRequestSchema = z.object({\n /** Package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n\n /** User-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n\n /** Whether to enable immediately after install */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n\n /** Current platform version for compatibility verification */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n\n /** Artifact reference for the package (if installing from marketplace) */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference for marketplace installation'),\n}).describe('Install package request');\nexport type PackageInstallRequest = z.infer;\n\n/**\n * Response after installing a package.\n */\nexport const PackageInstallResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result'),\n namespaceConflicts: z.array(z.object({\n type: z.literal('namespace_conflict').describe('Error type'),\n requestedNamespace: z.string().describe('Requested namespace'),\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n conflictingPackageName: z.string().describe('Conflicting package name'),\n suggestion: z.string().optional().describe('Suggested alternative'),\n })).optional().describe('Namespace conflicts detected'),\n message: z.string().optional().describe('Installation status message'),\n }),\n}).describe('Install package response');\nexport type PackageInstallResponse = z.infer;\n\n// ==========================================\n// 5. Upgrade Package (POST /api/v1/packages/upgrade)\n// ==========================================\n\n/**\n * Request body for upgrading a package.\n *\n * @example POST /api/v1/packages/upgrade\n * { packageId: 'com.acme.crm', targetVersion: '2.0.0', createSnapshot: true }\n */\nexport const PackageUpgradeRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (defaults to latest) */\n targetVersion: z.string().optional()\n .describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional()\n .describe('New manifest for the target version'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum(['keep-custom', 'accept-incoming', 'three-way-merge'])\n .default('three-way-merge')\n .describe('How to handle customer customizations'),\n\n /** Preview upgrade without making changes */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Skip pre-upgrade compatibility checks */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\nexport type PackageUpgradeRequest = z.infer;\n\n/**\n * Response after upgrading a package.\n */\nexport const PackageUpgradeResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the upgrade succeeded'),\n phase: z.string().describe('Current upgrade phase'),\n plan: UpgradePlanSchema.optional().describe('Upgrade plan that was executed'),\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n conflicts: z.array(z.object({\n path: z.string().describe('Conflict path'),\n baseValue: z.unknown().describe('Base value'),\n incomingValue: z.unknown().describe('Incoming value'),\n customValue: z.unknown().describe('Custom value'),\n })).optional().describe('Unresolved merge conflicts'),\n errorMessage: z.string().optional().describe('Error message if failed'),\n message: z.string().optional().describe('Human-readable status message'),\n }),\n}).describe('Upgrade package response');\nexport type PackageUpgradeResponse = z.infer;\n\n// ==========================================\n// 6. Resolve Dependencies (POST /api/v1/packages/resolve-dependencies)\n// ==========================================\n\n/**\n * Request body for resolving package dependencies.\n *\n * @example POST /api/v1/packages/resolve-dependencies\n * { manifest: {...}, platformVersion: '3.2.0' }\n */\nexport const ResolveDependenciesRequestSchema = z.object({\n /** Package manifest whose dependencies to resolve */\n manifest: ManifestSchema.describe('Package manifest to resolve dependencies for'),\n\n /** Current platform version for compatibility checking */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility filtering'),\n}).describe('Resolve dependencies request');\nexport type ResolveDependenciesRequest = z.infer;\n\n/**\n * Response with dependency resolution results.\n */\nexport const ResolveDependenciesResponseSchema = BaseResponseSchema.extend({\n data: DependencyResolutionResultSchema.describe('Dependency resolution result with topological sort'),\n}).describe('Resolve dependencies response');\nexport type ResolveDependenciesResponse = z.infer;\n\n// ==========================================\n// 7. Upload Artifact (POST /api/v1/packages/upload)\n// ==========================================\n\n/**\n * Request body for uploading a package artifact.\n *\n * @example POST /api/v1/packages/upload\n * Content-Type: multipart/form-data\n * { artifact: , file: }\n */\nexport const UploadArtifactRequestSchema = z.object({\n /** Artifact metadata */\n artifact: PackageArtifactSchema.describe('Package artifact metadata'),\n\n /** SHA256 checksum of the uploaded file (for verification) */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).optional()\n .describe('SHA256 checksum of the uploaded file'),\n\n /** Publisher authentication token */\n token: z.string().optional()\n .describe('Publisher authentication token'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional()\n .describe('Release notes for this version'),\n}).describe('Upload artifact request');\nexport type UploadArtifactRequest = z.infer;\n\n/**\n * Response after uploading a package artifact.\n */\nexport const UploadArtifactResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n /** Whether the upload succeeded */\n success: z.boolean().describe('Whether the upload succeeded'),\n /** Artifact reference for the uploaded package */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference in the registry'),\n /** Submission ID for review tracking */\n submissionId: z.string().optional()\n .describe('Marketplace submission ID for review tracking'),\n /** Message */\n message: z.string().optional().describe('Upload status message'),\n }),\n}).describe('Upload artifact response');\nexport type UploadArtifactResponse = z.infer;\n\n// ==========================================\n// 8. Rollback Package (POST /api/v1/packages/:packageId/rollback)\n// ==========================================\n\n/**\n * Request body for rolling back a package upgrade.\n */\nexport const PackageRollbackRequestSchema = PackagePathParamsSchema.extend({\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\nexport type PackageRollbackRequest = z.infer;\n\n/**\n * Response after rolling back a package.\n */\nexport const PackageRollbackResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the rollback succeeded'),\n restoredVersion: z.string().optional().describe('Restored version'),\n message: z.string().optional().describe('Rollback status message'),\n }),\n}).describe('Rollback package response');\nexport type PackageRollbackResponse = z.infer;\n\n// ==========================================\n// 9. Uninstall Package (DELETE /api/v1/packages/:packageId)\n// ==========================================\n\n/**\n * Request for uninstalling a package.\n */\nexport const UninstallPackageApiRequestSchema = PackagePathParamsSchema;\nexport type UninstallPackageApiRequest = z.infer;\n\n/**\n * Response after uninstalling a package.\n */\nexport const UninstallPackageApiResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n packageId: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n }),\n}).describe('Uninstall package response');\nexport type UninstallPackageApiResponse = z.infer;\n\n// ==========================================\n// 10. Package API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Package operations.\n */\nexport const PackageApiErrorCode = z.enum([\n 'package_not_found',\n 'package_already_installed',\n 'version_not_found',\n 'dependency_conflict',\n 'namespace_conflict',\n 'platform_incompatible',\n 'artifact_invalid',\n 'checksum_mismatch',\n 'signature_invalid',\n 'upgrade_failed',\n 'rollback_failed',\n 'snapshot_not_found',\n 'upload_failed',\n]);\nexport type PackageApiErrorCode = z.infer;\n\n// ==========================================\n// 11. Package API Contract Registry\n// ==========================================\n\n/**\n * Standard Package API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const PackageApiContracts = {\n listPackages: {\n method: 'GET' as const,\n path: '/api/v1/packages',\n input: ListInstalledPackagesRequestSchema,\n output: ListInstalledPackagesResponseSchema,\n },\n getPackage: {\n method: 'GET' as const,\n path: '/api/v1/packages/:packageId',\n input: GetInstalledPackageRequestSchema,\n output: GetInstalledPackageResponseSchema,\n },\n installPackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/install',\n input: PackageInstallRequestSchema,\n output: PackageInstallResponseSchema,\n },\n upgradePackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/upgrade',\n input: PackageUpgradeRequestSchema,\n output: PackageUpgradeResponseSchema,\n },\n resolveDependencies: {\n method: 'POST' as const,\n path: '/api/v1/packages/resolve-dependencies',\n input: ResolveDependenciesRequestSchema,\n output: ResolveDependenciesResponseSchema,\n },\n uploadArtifact: {\n method: 'POST' as const,\n path: '/api/v1/packages/upload',\n input: UploadArtifactRequestSchema,\n output: UploadArtifactResponseSchema,\n },\n rollbackPackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/:packageId/rollback',\n input: PackageRollbackRequestSchema,\n output: PackageRollbackResponseSchema,\n },\n uninstallPackage: {\n method: 'DELETE' as const,\n path: '/api/v1/packages/:packageId',\n input: UninstallPackageApiRequestSchema,\n output: UninstallPackageApiResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n// Export Kernels\nexport { ObjectKernel } from '@objectstack/core';\n\n// Export Runtime\nexport { Runtime } from './runtime.js';\nexport type { RuntimeConfig } from './runtime.js';\n\n// Export Plugins\nexport { DriverPlugin } from './driver-plugin.js';\nexport { AppPlugin } from './app-plugin.js';\nexport { SeedLoaderService } from './seed-loader.js';\nexport { createDispatcherPlugin } from './dispatcher-plugin.js';\nexport type { DispatcherPluginConfig } from './dispatcher-plugin.js';\n\n// Export HTTP Server Components\nexport { HttpServer } from './http-server.js';\nexport { HttpDispatcher } from './http-dispatcher.js';\nexport type { HttpProtocolContext, HttpDispatcherResult } from './http-dispatcher.js';\nexport { MiddlewareManager } from './middleware.js';\n\n// Re-export from @objectstack/rest\nexport {\n RestServer,\n RouteManager,\n RouteGroupBuilder,\n createRestApiPlugin,\n} from '@objectstack/rest';\nexport type {\n RouteEntry,\n RestApiPluginConfig,\n} from '@objectstack/rest';\n\n// Export Types\nexport * from '@objectstack/core';\n\n\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectKernel, Plugin, IHttpServer, ObjectKernelConfig } from '@objectstack/core';\n\nexport interface RuntimeConfig {\n /**\n * Optional existing server instance (e.g. Hono, Express app)\n * If provided, Runtime will use it as the 'http.server' service.\n * If not provided, Runtime expects a server plugin (like HonoServerPlugin) to be registered manually.\n */\n server?: IHttpServer;\n\n /**\n * Kernel Configuration\n */\n kernel?: ObjectKernelConfig;\n}\n\n/**\n * ObjectStack Runtime\n * \n * High-level entry point for bootstrapping an ObjectStack application.\n * Wraps ObjectKernel and provides standard orchestration for:\n * - HTTP Server binding\n * - Plugin Management\n * \n * REST API is opt-in — register it explicitly:\n * ```ts\n * import { createRestApiPlugin } from '@objectstack/rest';\n * runtime.use(createRestApiPlugin());\n * ```\n */\nexport class Runtime {\n readonly kernel: ObjectKernel;\n \n constructor(config: RuntimeConfig = {}) {\n this.kernel = new ObjectKernel(config.kernel);\n \n // If external server provided, register it immediately\n if (config.server) {\n this.kernel.registerService('http.server', config.server);\n }\n }\n \n /**\n * Register a plugin\n */\n use(plugin: Plugin) {\n this.kernel.use(plugin);\n return this;\n }\n \n /**\n * Start the runtime\n * 1. Initializes all plugins (init phase)\n * 2. Starts all plugins (start phase)\n */\n async start() {\n await this.kernel.bootstrap();\n return this;\n }\n \n /**\n * Get the kernel instance\n */\n getKernel() {\n return this.kernel;\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from '@objectstack/core';\n\n/**\n * Driver Plugin\n * \n * Generic plugin wrapper for ObjectQL drivers.\n * Registers a driver with the ObjectQL engine.\n * \n * Dependencies: None (Registers service for ObjectQL to discover)\n * Services: driver.{name}\n * \n * @example\n * const memoryDriver = new InMemoryDriver();\n * const driverPlugin = new DriverPlugin(memoryDriver, 'memory');\n * kernel.use(driverPlugin);\n */\nexport class DriverPlugin implements Plugin {\n name: string;\n type = 'driver';\n version = '1.0.0';\n // dependencies = ['com.objectstack.engine.objectql']; // Removed: Driver is a producer, not strictly a consumer during init\n\n private driver: any;\n\n constructor(driver: any, driverName?: string) {\n this.driver = driver;\n this.name = `com.objectstack.driver.${driverName || driver.name || 'unknown'}`;\n }\n\n init = async (ctx: PluginContext) => {\n // Register driver as a service instead of directly to objectql\n const serviceName = `driver.${this.driver.name || 'unknown'}`;\n ctx.registerService(serviceName, this.driver);\n ctx.logger.info('Driver service registered', { \n serviceName, \n driverName: this.driver.name,\n driverVersion: this.driver.version \n });\n }\n\n start = async (ctx: PluginContext) => {\n // Drivers don't need start phase, initialization happens in init\n // Auto-configure alias for shorter access if it follows reverse domain standard\n if (this.name.startsWith('com.objectstack.driver.')) {\n // const shortName = this.name.split('.').pop();\n // Optional: ctx.registerService(`driver.${shortName}`, this.driver);\n }\n\n // Auto-configure 'default' datasource if none exists\n // We do this in 'start' phase to ensure metadata service is likely available\n try {\n const metadata = ctx.getService('metadata');\n if (metadata && metadata.addDatasource) {\n // Check if default datasource exists\n const datasources = metadata.getDatasources ? metadata.getDatasources() : [];\n const hasDefault = datasources.some((ds: any) => ds.name === 'default');\n\n if (!hasDefault) {\n ctx.logger.info(`[DriverPlugin] No 'default' datasource found. Auto-configuring '${this.driver.name}' as default.`);\n await metadata.addDatasource({\n name: 'default',\n driver: this.driver.name, // The driver's internal name (e.g. com.objectstack.driver.memory)\n });\n }\n }\n } catch (e) {\n // Metadata service might not be ready or available, which is fine\n // We just skip auto-configuration\n ctx.logger.debug('[DriverPlugin] Failed to auto-configure default datasource (Metadata service missing?)', { error: e });\n }\n\n ctx.logger.debug('Driver plugin started', { driverName: this.driver.name || 'unknown' });\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IDataEngine, IMetadataService, ISeedLoaderService } from '@objectstack/spec/contracts';\nimport type {\n SeedLoaderRequest,\n SeedLoaderResult,\n SeedLoaderConfig,\n SeedLoaderConfigInput,\n ObjectDependencyGraph,\n ObjectDependencyNode,\n ReferenceResolution,\n ReferenceResolutionError,\n DatasetLoadResult,\n Dataset,\n} from '@objectstack/spec/data';\nimport { SeedLoaderConfigSchema } from '@objectstack/spec/data';\n\ninterface Logger {\n info(message: string, meta?: Record): void;\n warn(message: string, meta?: Record): void;\n error(message: string, error?: Error, meta?: Record): void;\n debug(message: string, meta?: Record): void;\n}\n\n/** Default field used for externalId matching on target objects */\nconst DEFAULT_EXTERNAL_ID_FIELD = 'name';\n\n/**\n * SeedLoaderService — Runtime implementation of ISeedLoaderService\n *\n * Provides metadata-driven seed data loading with:\n * - Automatic lookup/master_detail reference resolution via externalId\n * - Topological dependency ordering (parents before children)\n * - Multi-pass loading for circular references\n * - Dry-run validation mode\n * - Upsert support honoring DatasetSchema mode\n * - Actionable error reporting\n */\nexport class SeedLoaderService implements ISeedLoaderService {\n private engine: IDataEngine;\n private metadata: IMetadataService;\n private logger: Logger;\n\n constructor(engine: IDataEngine, metadata: IMetadataService, logger: Logger) {\n this.engine = engine;\n this.metadata = metadata;\n this.logger = logger;\n }\n\n // ==========================================================================\n // Public API\n // ==========================================================================\n\n async load(request: SeedLoaderRequest): Promise {\n const startTime = Date.now();\n const config = request.config;\n const allErrors: ReferenceResolutionError[] = [];\n const allResults: DatasetLoadResult[] = [];\n\n // 1. Filter datasets by environment\n const datasets = this.filterByEnv(request.datasets, config.env);\n\n if (datasets.length === 0) {\n return this.buildEmptyResult(config, Date.now() - startTime);\n }\n\n // 2. Build dependency graph\n const objectNames = datasets.map(d => d.object);\n const graph = await this.buildDependencyGraph(objectNames);\n\n this.logger.info('[SeedLoader] Dependency graph built', {\n objects: objectNames.length,\n insertOrder: graph.insertOrder,\n circularDeps: graph.circularDependencies.length,\n });\n\n // 3. Order datasets by topological insert order\n const orderedDatasets = this.orderDatasets(datasets, graph.insertOrder);\n\n // 4. Build reference lookup map from metadata (field → target object)\n const refMap = this.buildReferenceMap(graph);\n\n // 5. Pass 1: Insert/upsert records, resolving references\n const insertedRecords = new Map>(); // object → externalIdValue → internalId\n const deferredUpdates: DeferredUpdate[] = [];\n\n for (const dataset of orderedDatasets) {\n const result = await this.loadDataset(\n dataset, config, refMap, insertedRecords, deferredUpdates, allErrors\n );\n allResults.push(result);\n\n if (config.haltOnError && result.errored > 0) {\n this.logger.warn('[SeedLoader] Halting on first error', { object: dataset.object });\n break;\n }\n }\n\n // 6. Pass 2: Resolve deferred references (circular dependencies)\n if (config.multiPass && deferredUpdates.length > 0 && !config.dryRun) {\n this.logger.info('[SeedLoader] Pass 2: resolving deferred references', {\n count: deferredUpdates.length,\n });\n await this.resolveDeferredUpdates(deferredUpdates, insertedRecords, allResults, allErrors);\n }\n\n // 7. Build final result\n const durationMs = Date.now() - startTime;\n return this.buildResult(config, graph, allResults, allErrors, durationMs);\n }\n\n async buildDependencyGraph(objectNames: string[]): Promise {\n const nodes: ObjectDependencyNode[] = [];\n const objectSet = new Set(objectNames);\n\n for (const objectName of objectNames) {\n const objDef = await this.metadata.getObject(objectName) as any;\n const dependsOn: string[] = [];\n const references: ReferenceResolution[] = [];\n\n if (objDef && objDef.fields) {\n const fields = objDef.fields as Record;\n for (const [fieldName, fieldDef] of Object.entries(fields)) {\n if (\n (fieldDef.type === 'lookup' || fieldDef.type === 'master_detail') &&\n fieldDef.reference\n ) {\n const targetObject = fieldDef.reference as string;\n\n // Track dependency ordering only for objects within the graph\n if (objectSet.has(targetObject) && !dependsOn.includes(targetObject)) {\n dependsOn.push(targetObject);\n }\n\n // Track ALL references for resolution (target may exist in database)\n references.push({\n field: fieldName,\n targetObject,\n targetField: DEFAULT_EXTERNAL_ID_FIELD,\n fieldType: fieldDef.type as 'lookup' | 'master_detail',\n });\n }\n }\n }\n\n nodes.push({ object: objectName, dependsOn, references });\n }\n\n // Topological sort\n const { insertOrder, circularDependencies } = this.topologicalSort(nodes);\n\n return { nodes, insertOrder, circularDependencies };\n }\n\n async validate(datasets: Dataset[], config?: SeedLoaderConfigInput): Promise {\n const parsedConfig = SeedLoaderConfigSchema.parse({ ...config, dryRun: true });\n return this.load({ datasets, config: parsedConfig });\n }\n\n // ==========================================================================\n // Internal: Dataset Loading\n // ==========================================================================\n\n private async loadDataset(\n dataset: Dataset,\n config: SeedLoaderConfig,\n refMap: Map,\n insertedRecords: Map>,\n deferredUpdates: DeferredUpdate[],\n allErrors: ReferenceResolutionError[],\n ): Promise {\n const objectName = dataset.object;\n const mode = dataset.mode || config.defaultMode;\n const externalId = dataset.externalId || 'name';\n\n let inserted = 0;\n let updated = 0;\n let skipped = 0;\n let errored = 0;\n let referencesResolved = 0;\n let referencesDeferred = 0;\n const errors: ReferenceResolutionError[] = [];\n\n // Ensure the object's record map exists\n if (!insertedRecords.has(objectName)) {\n insertedRecords.set(objectName, new Map());\n }\n\n // Pre-load existing records for upsert matching\n let existingRecords: Map | undefined;\n if ((mode === 'upsert' || mode === 'update' || mode === 'ignore') && !config.dryRun) {\n existingRecords = await this.loadExistingRecords(objectName, externalId);\n }\n\n // Get reference resolutions for this object\n const objectRefs = refMap.get(objectName) || [];\n\n for (let i = 0; i < dataset.records.length; i++) {\n const record = { ...dataset.records[i] }; // Clone to avoid mutation\n\n // Resolve references\n for (const ref of objectRefs) {\n const fieldValue = record[ref.field];\n if (fieldValue === undefined || fieldValue === null) continue;\n\n // Skip if value looks like an internal ID (not a natural key)\n if (typeof fieldValue !== 'string' || this.looksLikeInternalId(fieldValue)) continue;\n\n // Try to resolve via already-inserted records\n const targetMap = insertedRecords.get(ref.targetObject);\n const resolvedId = targetMap?.get(String(fieldValue));\n\n if (resolvedId) {\n record[ref.field] = resolvedId;\n referencesResolved++;\n } else if (!config.dryRun) {\n // Try to resolve from existing data in the database\n const dbId = await this.resolveFromDatabase(ref.targetObject, ref.targetField, fieldValue);\n if (dbId) {\n record[ref.field] = dbId;\n referencesResolved++;\n } else if (config.multiPass) {\n // Defer to pass 2\n record[ref.field] = null;\n deferredUpdates.push({\n objectName,\n recordExternalId: String(record[externalId] ?? ''),\n field: ref.field,\n targetObject: ref.targetObject,\n targetField: ref.targetField,\n attemptedValue: fieldValue,\n recordIndex: i,\n });\n referencesDeferred++;\n } else {\n // Cannot resolve - record error\n const error: ReferenceResolutionError = {\n sourceObject: objectName,\n field: ref.field,\n targetObject: ref.targetObject,\n targetField: ref.targetField,\n attemptedValue: fieldValue,\n recordIndex: i,\n message: `Cannot resolve reference: ${objectName}.${ref.field} = '${fieldValue}' → ${ref.targetObject}.${ref.targetField} not found`,\n };\n errors.push(error);\n allErrors.push(error);\n }\n } else {\n // Dry-run: attempt resolution, report error if not found\n const targetMap2 = insertedRecords.get(ref.targetObject);\n if (!targetMap2?.has(String(fieldValue))) {\n const error: ReferenceResolutionError = {\n sourceObject: objectName,\n field: ref.field,\n targetObject: ref.targetObject,\n targetField: ref.targetField,\n attemptedValue: fieldValue,\n recordIndex: i,\n message: `[dry-run] Reference may not resolve: ${objectName}.${ref.field} = '${fieldValue}' → ${ref.targetObject}.${ref.targetField}`,\n };\n errors.push(error);\n allErrors.push(error);\n }\n }\n }\n\n // Insert/upsert the record\n if (!config.dryRun) {\n try {\n const result = await this.writeRecord(\n objectName, record, mode, externalId, existingRecords\n );\n\n if (result.action === 'inserted') inserted++;\n else if (result.action === 'updated') updated++;\n else if (result.action === 'skipped') skipped++;\n\n // Track the inserted/updated record's ID for reference resolution\n const externalIdValue = String(record[externalId] ?? '');\n const internalId = result.id;\n if (externalIdValue && internalId) {\n insertedRecords.get(objectName)!.set(externalIdValue, String(internalId));\n }\n } catch (err: any) {\n errored++;\n this.logger.warn(`[SeedLoader] Failed to write ${objectName} record`, {\n error: err.message,\n recordIndex: i,\n });\n }\n } else {\n // Dry-run: simulate insert tracking\n const externalIdValue = String(record[externalId] ?? '');\n if (externalIdValue) {\n insertedRecords.get(objectName)!.set(externalIdValue, `dry-run-id-${i}`);\n }\n inserted++; // Count as \"would be inserted\"\n }\n }\n\n return {\n object: objectName,\n mode,\n inserted,\n updated,\n skipped,\n errored,\n total: dataset.records.length,\n referencesResolved,\n referencesDeferred,\n errors,\n };\n }\n\n // ==========================================================================\n // Internal: Reference Resolution\n // ==========================================================================\n\n private async resolveFromDatabase(\n targetObject: string,\n targetField: string,\n value: unknown,\n ): Promise {\n try {\n const records = await this.engine.find(targetObject, {\n where: { [targetField]: value },\n fields: ['id'],\n limit: 1,\n });\n if (records && records.length > 0) {\n return String(records[0].id || records[0]._id);\n }\n } catch {\n // Target object may not exist yet\n }\n return null;\n }\n\n private async resolveDeferredUpdates(\n deferredUpdates: DeferredUpdate[],\n insertedRecords: Map>,\n allResults: DatasetLoadResult[],\n allErrors: ReferenceResolutionError[],\n ): Promise {\n for (const deferred of deferredUpdates) {\n // Try to resolve from inserted records\n const targetMap = insertedRecords.get(deferred.targetObject);\n let resolvedId = targetMap?.get(String(deferred.attemptedValue));\n\n // Try database fallback\n if (!resolvedId) {\n resolvedId = (await this.resolveFromDatabase(\n deferred.targetObject, deferred.targetField, deferred.attemptedValue\n )) ?? undefined;\n }\n\n if (resolvedId) {\n // Find the record and update the reference\n const objectRecordMap = insertedRecords.get(deferred.objectName);\n const recordId = objectRecordMap?.get(deferred.recordExternalId);\n\n if (recordId) {\n try {\n await this.engine.update(deferred.objectName, {\n id: recordId,\n [deferred.field]: resolvedId,\n });\n\n // Update result stats\n const resultEntry = allResults.find(r => r.object === deferred.objectName);\n if (resultEntry) {\n resultEntry.referencesResolved++;\n resultEntry.referencesDeferred--;\n }\n } catch (err: any) {\n this.logger.warn('[SeedLoader] Failed to resolve deferred reference', {\n object: deferred.objectName,\n field: deferred.field,\n error: err.message,\n });\n }\n }\n } else {\n // Still unresolved after pass 2\n const error: ReferenceResolutionError = {\n sourceObject: deferred.objectName,\n field: deferred.field,\n targetObject: deferred.targetObject,\n targetField: deferred.targetField,\n attemptedValue: deferred.attemptedValue,\n recordIndex: deferred.recordIndex,\n message: `Deferred reference unresolved after pass 2: ${deferred.objectName}.${deferred.field} = '${deferred.attemptedValue}' → ${deferred.targetObject}.${deferred.targetField} not found`,\n };\n\n const resultEntry = allResults.find(r => r.object === deferred.objectName);\n if (resultEntry) {\n resultEntry.errors.push(error);\n }\n allErrors.push(error);\n }\n }\n }\n\n // ==========================================================================\n // Internal: Write Operations\n // ==========================================================================\n\n private async writeRecord(\n objectName: string,\n record: Record,\n mode: string,\n externalId: string,\n existingRecords?: Map,\n ): Promise<{ action: 'inserted' | 'updated' | 'skipped'; id?: string }> {\n const externalIdValue = record[externalId];\n const existing = existingRecords?.get(String(externalIdValue ?? ''));\n\n switch (mode) {\n case 'insert': {\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n\n case 'update': {\n if (!existing) {\n return { action: 'skipped' };\n }\n const id = this.extractId(existing);\n await this.engine.update(objectName, { ...record, id });\n return { action: 'updated', id };\n }\n\n case 'upsert': {\n if (existing) {\n const id = this.extractId(existing);\n await this.engine.update(objectName, { ...record, id });\n return { action: 'updated', id };\n } else {\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n }\n\n case 'ignore': {\n if (existing) {\n return { action: 'skipped', id: this.extractId(existing) };\n }\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n\n case 'replace': {\n // Replace mode: just insert (caller should have cleared the table)\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n\n default: {\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n }\n }\n\n // ==========================================================================\n // Internal: Dependency Graph\n // ==========================================================================\n\n /**\n * Kahn's algorithm for topological sort with cycle detection.\n */\n private topologicalSort(\n nodes: ObjectDependencyNode[],\n ): { insertOrder: string[]; circularDependencies: string[][] } {\n const inDegree = new Map();\n const adjacency = new Map();\n const objectSet = new Set(nodes.map(n => n.object));\n\n // Initialize\n for (const node of nodes) {\n inDegree.set(node.object, 0);\n adjacency.set(node.object, []);\n }\n\n // Build adjacency list and in-degree counts\n for (const node of nodes) {\n for (const dep of node.dependsOn) {\n // Exclude self-references from ordering (e.g., employee.manager_id → employee).\n // Self-referencing fields are still tracked in node.references for resolution.\n if (objectSet.has(dep) && dep !== node.object) {\n adjacency.get(dep)!.push(node.object);\n inDegree.set(node.object, (inDegree.get(node.object) || 0) + 1);\n }\n }\n }\n\n // Kahn's algorithm\n const queue: string[] = [];\n for (const [obj, degree] of inDegree) {\n if (degree === 0) queue.push(obj);\n }\n\n const insertOrder: string[] = [];\n while (queue.length > 0) {\n const current = queue.shift()!;\n insertOrder.push(current);\n\n for (const neighbor of (adjacency.get(current) || [])) {\n const newDegree = (inDegree.get(neighbor) || 0) - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) {\n queue.push(neighbor);\n }\n }\n }\n\n // Detect circular dependencies\n const circularDependencies: string[][] = [];\n const remaining = nodes.filter(n => !insertOrder.includes(n.object));\n\n if (remaining.length > 0) {\n // Find cycles using DFS\n const cycles = this.findCycles(remaining);\n circularDependencies.push(...cycles);\n\n // Add remaining objects to insertOrder (they'll need multi-pass)\n for (const node of remaining) {\n if (!insertOrder.includes(node.object)) {\n insertOrder.push(node.object);\n }\n }\n }\n\n return { insertOrder, circularDependencies };\n }\n\n private findCycles(nodes: ObjectDependencyNode[]): string[][] {\n const cycles: string[][] = [];\n const nodeMap = new Map(nodes.map(n => [n.object, n]));\n const visited = new Set();\n const inStack = new Set();\n\n const dfs = (current: string, path: string[]) => {\n if (inStack.has(current)) {\n // Found a cycle\n const cycleStart = path.indexOf(current);\n if (cycleStart !== -1) {\n cycles.push([...path.slice(cycleStart), current]);\n }\n return;\n }\n if (visited.has(current)) return;\n\n visited.add(current);\n inStack.add(current);\n path.push(current);\n\n const node = nodeMap.get(current);\n if (node) {\n for (const dep of node.dependsOn) {\n if (nodeMap.has(dep)) {\n dfs(dep, [...path]);\n }\n }\n }\n\n inStack.delete(current);\n };\n\n for (const node of nodes) {\n if (!visited.has(node.object)) {\n dfs(node.object, []);\n }\n }\n\n return cycles;\n }\n\n // ==========================================================================\n // Internal: Helpers\n // ==========================================================================\n\n private filterByEnv(datasets: Dataset[], env?: string): Dataset[] {\n if (!env) return datasets;\n return datasets.filter(d => (d.env as string[]).includes(env));\n }\n\n private orderDatasets(datasets: Dataset[], insertOrder: string[]): Dataset[] {\n const orderMap = new Map(insertOrder.map((name, i) => [name, i]));\n return [...datasets].sort((a, b) => {\n const orderA = orderMap.get(a.object) ?? Number.MAX_SAFE_INTEGER;\n const orderB = orderMap.get(b.object) ?? Number.MAX_SAFE_INTEGER;\n return orderA - orderB;\n });\n }\n\n private buildReferenceMap(graph: ObjectDependencyGraph): Map {\n const map = new Map();\n for (const node of graph.nodes) {\n if (node.references.length > 0) {\n map.set(node.object, node.references);\n }\n }\n return map;\n }\n\n private async loadExistingRecords(\n objectName: string,\n externalId: string,\n ): Promise> {\n const map = new Map();\n try {\n const records = await this.engine.find(objectName, {\n fields: ['id', externalId],\n });\n for (const record of records || []) {\n const key = String(record[externalId] ?? '');\n if (key) {\n map.set(key, record);\n }\n }\n } catch {\n // Object may not have records yet\n }\n return map;\n }\n\n private looksLikeInternalId(value: string): boolean {\n // UUID v4 pattern\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {\n return true;\n }\n // MongoDB ObjectId pattern (24 hex chars)\n if (/^[0-9a-f]{24}$/i.test(value)) {\n return true;\n }\n return false;\n }\n\n private extractId(record: any): string | undefined {\n if (!record) return undefined;\n return String(record.id || record._id || '');\n }\n\n private buildEmptyResult(config: SeedLoaderConfig, durationMs: number): SeedLoaderResult {\n return {\n success: true,\n dryRun: config.dryRun,\n dependencyGraph: { nodes: [], insertOrder: [], circularDependencies: [] },\n results: [],\n errors: [],\n summary: {\n objectsProcessed: 0,\n totalRecords: 0,\n totalInserted: 0,\n totalUpdated: 0,\n totalSkipped: 0,\n totalErrored: 0,\n totalReferencesResolved: 0,\n totalReferencesDeferred: 0,\n circularDependencyCount: 0,\n durationMs,\n },\n };\n }\n\n private buildResult(\n config: SeedLoaderConfig,\n graph: ObjectDependencyGraph,\n results: DatasetLoadResult[],\n errors: ReferenceResolutionError[],\n durationMs: number,\n ): SeedLoaderResult {\n const summary = {\n objectsProcessed: results.length,\n totalRecords: results.reduce((sum, r) => sum + r.total, 0),\n totalInserted: results.reduce((sum, r) => sum + r.inserted, 0),\n totalUpdated: results.reduce((sum, r) => sum + r.updated, 0),\n totalSkipped: results.reduce((sum, r) => sum + r.skipped, 0),\n totalErrored: results.reduce((sum, r) => sum + r.errored, 0),\n totalReferencesResolved: results.reduce((sum, r) => sum + r.referencesResolved, 0),\n totalReferencesDeferred: results.reduce((sum, r) => sum + r.referencesDeferred, 0),\n circularDependencyCount: graph.circularDependencies.length,\n durationMs,\n };\n\n const hasErrors = errors.length > 0 || summary.totalErrored > 0;\n\n return {\n success: !hasErrors,\n dryRun: config.dryRun,\n dependencyGraph: graph,\n results,\n errors,\n summary,\n };\n }\n}\n\n// ==========================================================================\n// Internal Types\n// ==========================================================================\n\ninterface DeferredUpdate {\n objectName: string;\n recordExternalId: string;\n field: string;\n targetObject: string;\n targetField: string;\n attemptedValue: unknown;\n recordIndex: number;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from '@objectstack/core';\nimport { SeedLoaderService } from './seed-loader.js';\nimport type { IMetadataService, II18nService } from '@objectstack/spec/contracts';\n\n/**\n * AppPlugin\n * \n * Adapts a generic App Bundle (Manifest + Runtime Code) into a Kernel Plugin.\n * \n * Responsibilities:\n * 1. Register App Manifest as a service (for ObjectQL discovery)\n * 2. Execute Runtime `onEnable` hook (for code logic)\n * 3. Auto-load i18n translation bundles into the kernel's i18n service\n */\nexport class AppPlugin implements Plugin {\n name: string;\n type = 'app';\n version?: string;\n \n private bundle: any;\n\n constructor(bundle: any) {\n this.bundle = bundle;\n // Support both direct manifest (legacy) and Stack Definition (nested manifest)\n const sys = bundle.manifest || bundle;\n const appId = sys.id || sys.name || 'unnamed-app';\n \n this.name = `plugin.app.${appId}`;\n this.version = sys.version;\n }\n\n init = async (ctx: PluginContext) => {\n const sys = this.bundle.manifest || this.bundle;\n const appId = sys.id || sys.name;\n\n ctx.logger.info('Registering App Service', { \n appId, \n pluginName: this.name,\n version: this.version \n });\n \n // Register the app manifest directly via the manifest service.\n // This immediately decomposes the manifest into SchemaRegistry entries.\n const servicePayload = this.bundle.manifest\n ? { ...this.bundle.manifest, ...this.bundle }\n : this.bundle;\n\n ctx.getService<{ register(m: any): void }>('manifest').register(servicePayload);\n }\n\n start = async (ctx: PluginContext) => {\n const sys = this.bundle.manifest || this.bundle;\n const appId = sys.id || sys.name;\n \n // Execute Runtime Step\n // Retrieve ObjectQL engine from services\n // ctx.getService throws when a service is not registered, so we\n // must use try/catch instead of a null-check.\n let ql: any;\n try {\n ql = ctx.getService('objectql');\n } catch {\n // Service not registered — handled below\n }\n\n if (!ql) {\n ctx.logger.warn('ObjectQL engine service not found', { \n appName: this.name,\n appId \n });\n return;\n }\n\n ctx.logger.debug('Retrieved ObjectQL engine service', { appId });\n\n const runtime = this.bundle.default || this.bundle;\n \n if (runtime && typeof runtime.onEnable === 'function') {\n ctx.logger.info('Executing runtime.onEnable', { \n appName: this.name,\n appId \n });\n \n // Construct the Host Context (mirroring old ObjectQL.use logic)\n const hostContext = {\n ...ctx,\n ql,\n logger: ctx.logger,\n drivers: {\n register: (driver: any) => {\n ctx.logger.debug('Registering driver via app runtime', { \n driverName: driver.name,\n appId \n });\n ql.registerDriver(driver);\n }\n },\n };\n \n await runtime.onEnable(hostContext);\n ctx.logger.debug('Runtime.onEnable completed', { appId });\n } else {\n ctx.logger.debug('No runtime.onEnable function found', { appId });\n }\n\n // ── i18n Translation Loading ─────────────────────────────────────\n // Auto-load translation bundles from the app config into the\n // kernel's i18n service, so discovery and handlers stay consistent.\n this.loadTranslations(ctx, appId);\n\n // Data Seeding\n // Collect seed data from multiple locations (top-level `data` preferred, `manifest.data` for backward compat)\n const seedDatasets: any[] = [];\n \n // 1. Top-level `data` field (new standard location on ObjectStackDefinition)\n if (Array.isArray(this.bundle.data)) {\n seedDatasets.push(...this.bundle.data);\n }\n \n // 2. Legacy: `manifest.data` (backward compatibility)\n const manifest = this.bundle.manifest || this.bundle;\n if (manifest && Array.isArray(manifest.data)) {\n seedDatasets.push(...manifest.data);\n }\n\n // Resolve short object names to FQN using the package's namespace.\n // e.g., seed `object: 'task'` in namespace 'todo' → 'todo__task'\n // Reserved namespaces ('base', 'system') are not prefixed.\n const namespace = (this.bundle.manifest || this.bundle)?.namespace as string | undefined;\n const RESERVED_NS = new Set(['base', 'system']);\n const toFQN = (name: string) => {\n if (name.includes('__') || !namespace || RESERVED_NS.has(namespace)) return name;\n return `${namespace}__${name}`;\n };\n \n if (seedDatasets.length > 0) {\n ctx.logger.info(`[AppPlugin] Found ${seedDatasets.length} seed datasets for ${appId}`);\n\n // Normalize dataset object names to FQN\n const normalizedDatasets = seedDatasets\n .filter((d: any) => d.object && Array.isArray(d.records))\n .map((d: any) => ({\n ...d,\n object: toFQN(d.object),\n }));\n\n // Use SeedLoaderService for metadata-driven loading with reference resolution\n try {\n const metadata = ctx.getService('metadata') as IMetadataService | undefined;\n if (metadata) {\n const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger);\n const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data');\n const request = SeedLoaderRequestSchema.parse({\n datasets: normalizedDatasets,\n config: { defaultMode: 'upsert', multiPass: true },\n });\n const result = await seedLoader.load(request);\n ctx.logger.info('[Seeder] Seed loading complete', {\n inserted: result.summary.totalInserted,\n updated: result.summary.totalUpdated,\n errors: result.errors.length,\n });\n } else {\n // Fallback: basic insert when metadata service is not available\n ctx.logger.debug('[Seeder] No metadata service; using basic insert fallback');\n for (const dataset of normalizedDatasets) {\n ctx.logger.info(`[Seeder] Seeding ${dataset.records.length} records for ${dataset.object}`);\n for (const record of dataset.records) {\n try {\n await ql.insert(dataset.object, record);\n } catch (err: any) {\n ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: err.message });\n }\n }\n }\n ctx.logger.info('[Seeder] Data seeding complete.');\n }\n } catch (err: any) {\n // If SeedLoaderService fails (e.g., metadata not available), fall back to basic insert\n ctx.logger.warn('[Seeder] SeedLoaderService failed, falling back to basic insert', { error: err.message });\n for (const dataset of normalizedDatasets) {\n for (const record of dataset.records) {\n try {\n await ql.insert(dataset.object, record);\n } catch (insertErr: any) {\n ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: insertErr.message });\n }\n }\n }\n ctx.logger.info('[Seeder] Data seeding complete (fallback).');\n }\n }\n }\n\n /**\n * Auto-load i18n translation bundles from the app config into the\n * kernel's i18n service. Handles both `translations` (array of\n * TranslationBundle) and `i18n` config (default locale, etc.).\n *\n * Gracefully skips when the i18n service is not registered —\n * this keeps AppPlugin resilient across server/dev/mock environments.\n */\n private loadTranslations(ctx: PluginContext, appId: string): void {\n // ctx.getService throws when a service is not registered, so we\n // must use try/catch to gracefully skip when no i18n plugin is loaded.\n let i18nService: II18nService | undefined;\n try {\n i18nService = ctx.getService('i18n') as II18nService;\n } catch {\n // Service not registered — handled below\n }\n\n // Collect translation bundles early to determine if we have data\n const bundles: Array> = [];\n if (Array.isArray(this.bundle.translations)) {\n bundles.push(...this.bundle.translations);\n }\n const manifest = this.bundle.manifest || this.bundle;\n if (manifest && Array.isArray(manifest.translations) && manifest.translations !== this.bundle.translations) {\n bundles.push(...manifest.translations);\n }\n\n if (!i18nService) {\n if (bundles.length > 0) {\n ctx.logger.warn(\n `[i18n] App \"${appId}\" has ${bundles.length} translation bundle(s) but no i18n service is registered. ` +\n 'Translations will not be served via REST API. ' +\n 'Register I18nServicePlugin from @objectstack/service-i18n, or use DevPlugin ' +\n 'which auto-detects translations and registers the i18n service automatically.'\n );\n } else {\n ctx.logger.debug('[i18n] No i18n service registered; skipping translation loading', { appId });\n }\n return;\n }\n\n // Apply i18n config (default locale, etc.)\n const i18nConfig = this.bundle.i18n || (this.bundle.manifest || this.bundle)?.i18n;\n if (i18nConfig?.defaultLocale && typeof i18nService.setDefaultLocale === 'function') {\n i18nService.setDefaultLocale(i18nConfig.defaultLocale);\n ctx.logger.debug('[i18n] Set default locale', { appId, locale: i18nConfig.defaultLocale });\n }\n\n if (bundles.length === 0) {\n return;\n }\n\n let loadedLocales = 0;\n for (const bundle of bundles) {\n // Each bundle is a TranslationBundle: Record\n for (const [locale, data] of Object.entries(bundle)) {\n if (data && typeof data === 'object') {\n try {\n i18nService.loadTranslations(locale, data as Record);\n loadedLocales++;\n } catch (err: any) {\n ctx.logger.warn('[i18n] Failed to load translations', { appId, locale, error: err.message });\n }\n }\n }\n }\n\n // Emit diagnostic when the active i18n service is a fallback/stub\n const svcAny = i18nService as unknown as Record;\n if (svcAny._fallback || svcAny._dev) {\n ctx.logger.info(\n `[i18n] Loaded ${loadedLocales} locale(s) into in-memory i18n fallback for \"${appId}\". ` +\n 'For production, consider registering I18nServicePlugin from @objectstack/service-i18n.'\n );\n } else {\n ctx.logger.info('[i18n] Loaded translation bundles', { appId, bundles: bundles.length, locales: loadedLocales });\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectKernel, getEnv, resolveLocale } from '@objectstack/core';\nimport { CoreServiceName } from '@objectstack/spec/system';\nimport { pluralToSingular } from '@objectstack/spec/shared';\n\n/** Browser-safe UUID generator — prefers Web Crypto, falls back to RFC 4122 v4 */\nfunction randomUUID(): string {\n if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\nexport interface HttpProtocolContext {\n request: any;\n response?: any;\n}\n\nexport interface HttpDispatcherResult {\n handled: boolean;\n response?: {\n status: number;\n body?: any;\n headers?: Record;\n };\n result?: any; // For flexible return types or direct response objects (Response/NextResponse)\n}\n\n/**\n * @deprecated Use `createDispatcherPlugin()` from `@objectstack/runtime` instead.\n * This class will be removed in v2. Prefer the plugin-based approach:\n * ```ts\n * import { createDispatcherPlugin } from '@objectstack/runtime';\n * kernel.use(createDispatcherPlugin({ prefix: '/api/v1' }));\n * ```\n */\nexport class HttpDispatcher {\n private kernel: any; // Casting to any to access dynamic props like broker, services, graphql\n\n constructor(kernel: ObjectKernel) {\n this.kernel = kernel;\n }\n\n private success(data: any, meta?: any) {\n return {\n status: 200,\n body: { success: true, data, meta }\n };\n }\n\n private error(message: string, code: number = 500, details?: any) {\n return {\n status: code,\n body: { success: false, error: { message, code, details } }\n };\n }\n\n /**\n * 404 Route Not Found — no route is registered for this path.\n */\n private routeNotFound(route: string) {\n return {\n status: 404,\n body: {\n success: false,\n error: {\n code: 404,\n message: `Route Not Found: ${route}`,\n type: 'ROUTE_NOT_FOUND' as const,\n route,\n hint: 'No route is registered for this path. Check the API discovery endpoint for available routes.',\n },\n },\n };\n }\n\n private ensureBroker() {\n if (!this.kernel.broker) {\n throw { statusCode: 500, message: 'Kernel Broker not available' };\n }\n return this.kernel.broker;\n }\n\n /**\n * Generates the discovery JSON response for the API root.\n *\n * Uses the same async `resolveService()` fallback chain that request\n * handlers use, so the reported service status is always consistent\n * with the actual runtime availability.\n */\n async getDiscoveryInfo(prefix: string) {\n // Resolve all services through the same async fallback chain\n // that request handlers (handleI18n, handleAuth, …) use.\n const [\n authSvc, graphqlSvc, searchSvc, realtimeSvc, filesSvc,\n analyticsSvc, workflowSvc, aiSvc, notificationSvc, i18nSvc,\n uiSvc, automationSvc, cacheSvc, queueSvc, jobSvc,\n ] = await Promise.all([\n this.resolveService(CoreServiceName.enum.auth),\n this.resolveService(CoreServiceName.enum.graphql),\n this.resolveService(CoreServiceName.enum.search),\n this.resolveService(CoreServiceName.enum.realtime),\n this.resolveService(CoreServiceName.enum['file-storage']),\n this.resolveService(CoreServiceName.enum.analytics),\n this.resolveService(CoreServiceName.enum.workflow),\n this.resolveService(CoreServiceName.enum.ai),\n this.resolveService(CoreServiceName.enum.notification),\n this.resolveService(CoreServiceName.enum.i18n),\n this.resolveService(CoreServiceName.enum.ui),\n this.resolveService(CoreServiceName.enum.automation),\n this.resolveService(CoreServiceName.enum.cache),\n this.resolveService(CoreServiceName.enum.queue),\n this.resolveService(CoreServiceName.enum.job),\n ]);\n\n const hasAuth = !!authSvc;\n const hasGraphQL = !!(graphqlSvc || this.kernel.graphql);\n const hasSearch = !!searchSvc;\n const hasWebSockets = !!realtimeSvc;\n const hasFiles = !!filesSvc;\n const hasAnalytics = !!analyticsSvc;\n const hasWorkflow = !!workflowSvc;\n const hasAi = !!aiSvc;\n const hasNotification = !!notificationSvc;\n const hasI18n = !!i18nSvc;\n const hasUi = !!uiSvc;\n const hasAutomation = !!automationSvc;\n const hasCache = !!cacheSvc;\n const hasQueue = !!queueSvc;\n const hasJob = !!jobSvc;\n\n // Routes are only exposed when a plugin provides the service\n const routes = {\n data: `${prefix}/data`,\n metadata: `${prefix}/meta`,\n packages: `${prefix}/packages`,\n auth: hasAuth ? `${prefix}/auth` : undefined,\n ui: hasUi ? `${prefix}/ui` : undefined,\n graphql: hasGraphQL ? `${prefix}/graphql` : undefined,\n storage: hasFiles ? `${prefix}/storage` : undefined,\n analytics: hasAnalytics ? `${prefix}/analytics` : undefined,\n automation: hasAutomation ? `${prefix}/automation` : undefined,\n workflow: hasWorkflow ? `${prefix}/workflow` : undefined,\n realtime: hasWebSockets ? `${prefix}/realtime` : undefined,\n notifications: hasNotification ? `${prefix}/notifications` : undefined,\n ai: hasAi ? `${prefix}/ai` : undefined,\n i18n: hasI18n ? `${prefix}/i18n` : undefined,\n };\n\n // Build per-service status map\n // handlerReady: true means the dispatcher has a real, bound handler for this route.\n // handlerReady: false means the route is present in the discovery table but may not\n // yet have a concrete implementation or may be served by a stub.\n const svcAvailable = (route?: string, provider?: string) => ({\n enabled: true, status: 'available' as const, handlerReady: true, route, provider,\n });\n const svcUnavailable = (name: string) => ({\n enabled: false, status: 'unavailable' as const, handlerReady: false,\n message: `Install a ${name} plugin to enable`,\n });\n\n // Derive locale info from actual i18n service when available\n let locale = { default: 'en', supported: ['en'], timezone: 'UTC' };\n if (hasI18n && i18nSvc) {\n const defaultLocale = typeof i18nSvc.getDefaultLocale === 'function'\n ? i18nSvc.getDefaultLocale() : 'en';\n const locales = typeof i18nSvc.getLocales === 'function'\n ? i18nSvc.getLocales() : [];\n locale = {\n default: defaultLocale,\n supported: locales.length > 0 ? locales : [defaultLocale],\n timezone: 'UTC',\n };\n }\n\n return {\n name: 'ObjectOS',\n version: '1.0.0',\n environment: getEnv('NODE_ENV', 'development'),\n routes,\n endpoints: routes, // Alias for backward compatibility with some clients\n features: {\n graphql: hasGraphQL,\n search: hasSearch,\n websockets: hasWebSockets,\n files: hasFiles,\n analytics: hasAnalytics,\n ai: hasAi,\n workflow: hasWorkflow,\n notifications: hasNotification,\n i18n: hasI18n,\n },\n services: {\n // Kernel-provided (always available via protocol implementation)\n metadata: { enabled: true, status: 'degraded' as const, handlerReady: true, route: routes.metadata, provider: 'kernel', message: 'In-memory registry; DB persistence pending' },\n data: svcAvailable(routes.data, 'kernel'),\n // Plugin-provided — only available when a plugin registers the service\n auth: hasAuth ? svcAvailable(routes.auth) : svcUnavailable('auth'),\n automation: hasAutomation ? svcAvailable(routes.automation) : svcUnavailable('automation'),\n analytics: hasAnalytics ? svcAvailable(routes.analytics) : svcUnavailable('analytics'),\n cache: hasCache ? svcAvailable() : svcUnavailable('cache'),\n queue: hasQueue ? svcAvailable() : svcUnavailable('queue'),\n job: hasJob ? svcAvailable() : svcUnavailable('job'),\n ui: hasUi ? svcAvailable(routes.ui) : svcUnavailable('ui'),\n workflow: hasWorkflow ? svcAvailable(routes.workflow) : svcUnavailable('workflow'),\n realtime: hasWebSockets ? svcAvailable(routes.realtime) : svcUnavailable('realtime'),\n notification: hasNotification ? svcAvailable(routes.notifications) : svcUnavailable('notification'),\n ai: hasAi ? svcAvailable(routes.ai) : svcUnavailable('ai'),\n i18n: hasI18n ? svcAvailable(routes.i18n) : svcUnavailable('i18n'),\n graphql: hasGraphQL ? svcAvailable(routes.graphql) : svcUnavailable('graphql'),\n 'file-storage': hasFiles ? svcAvailable(routes.storage) : svcUnavailable('file-storage'),\n search: hasSearch ? svcAvailable() : svcUnavailable('search'),\n },\n locale,\n };\n }\n\n /**\n * Handles GraphQL requests\n */\n async handleGraphQL(body: { query: string; variables?: any }, context: HttpProtocolContext) {\n if (!body || !body.query) {\n throw { statusCode: 400, message: 'Missing query in request body' };\n }\n \n if (typeof this.kernel.graphql !== 'function') {\n throw { statusCode: 501, message: 'GraphQL service not available' };\n }\n\n return this.kernel.graphql(body.query, body.variables, { \n request: context.request \n });\n }\n\n /**\n * Handles Auth requests\n * path: sub-path after /auth/\n */\n async handleAuth(path: string, method: string, body: any, context: HttpProtocolContext): Promise {\n // 1. Try generic Auth Service\n const authService = await this.getService(CoreServiceName.enum.auth);\n if (authService && typeof authService.handler === 'function') {\n const response = await authService.handler(context.request, context.response);\n return { handled: true, result: response };\n }\n\n // 2. Legacy Login via broker\n const normalizedPath = path.replace(/^\\/+/, '');\n if (normalizedPath === 'login' && method.toUpperCase() === 'POST') {\n try {\n const broker = this.ensureBroker();\n const data = await broker.call('auth.login', body, { request: context.request });\n return { handled: true, response: { status: 200, body: data } };\n } catch (error: any) {\n // Only fall through to mock when the broker is truly unavailable\n // (ensureBroker throws statusCode 500 when kernel.broker is null)\n const statusCode = error?.statusCode ?? error?.status;\n if (statusCode !== 500 || !error?.message?.includes('Broker not available')) {\n throw error;\n }\n }\n }\n\n // 3. Mock fallback for MSW/test environments when no auth service is registered\n return this.mockAuthFallback(normalizedPath, method, body);\n }\n\n /**\n * Provides mock auth responses for core better-auth endpoints when\n * AuthPlugin is not loaded (e.g. MSW/browser-only environments).\n * This ensures registration/sign-in flows do not 404 in mock mode.\n */\n private mockAuthFallback(path: string, method: string, body: any): HttpDispatcherResult {\n const m = method.toUpperCase();\n const MOCK_SESSION_EXPIRY_MS = 86_400_000; // 24 hours\n\n // POST sign-up/email\n if ((path === 'sign-up/email' || path === 'register') && m === 'POST') {\n const id = `mock_${randomUUID()}`;\n return {\n handled: true,\n response: {\n status: 200,\n body: {\n user: { id, name: body?.name || 'Mock User', email: body?.email || 'mock@test.local', emailVerified: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },\n session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() },\n },\n },\n };\n }\n\n // POST sign-in/email or login\n if ((path === 'sign-in/email' || path === 'login') && m === 'POST') {\n const id = `mock_${randomUUID()}`;\n return {\n handled: true,\n response: {\n status: 200,\n body: {\n user: { id, name: 'Mock User', email: body?.email || 'mock@test.local', emailVerified: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },\n session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() },\n },\n },\n };\n }\n\n // GET get-session\n if (path === 'get-session' && m === 'GET') {\n return {\n handled: true,\n response: { status: 200, body: { session: null, user: null } },\n };\n }\n\n // POST sign-out\n if (path === 'sign-out' && m === 'POST') {\n return {\n handled: true,\n response: { status: 200, body: { success: true } },\n };\n }\n\n return { handled: false };\n }\n\n /**\n * Handles Metadata requests\n * Standard: /metadata/:type/:name\n * Fallback for backward compat: /metadata (all objects), /metadata/:objectName (get object)\n */\n async handleMetadata(path: string, context: HttpProtocolContext, method?: string, body?: any, query?: any): Promise {\n // Broker is used as a fallback — not required upfront.\n // This allows metadata to be served when only the protocol service\n // or ObjectQL service is available (e.g. lightweight / serverless setups).\n const broker = this.kernel.broker ?? null;\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n \n // GET /metadata/types\n if (parts[0] === 'types') {\n // PRIORITY 1: Try MetadataService directly (includes both typeRegistry with agent/tool AND runtime-registered types)\n console.log('[HttpDispatcher] Attempting to resolve MetadataService...');\n console.log('[HttpDispatcher] Available kernel methods:', {\n hasGetServiceAsync: typeof this.kernel.getServiceAsync === 'function',\n hasGetService: typeof this.kernel.getService === 'function',\n hasContext: !!this.kernel.context,\n hasContextGetService: typeof this.kernel.context?.getService === 'function',\n });\n\n // Try all service resolution paths with detailed logging\n let metadataService: any = null;\n\n // Path 1: kernel.getServiceAsync\n if (typeof this.kernel.getServiceAsync === 'function') {\n try {\n metadataService = await this.kernel.getServiceAsync('metadata');\n console.log('[HttpDispatcher] kernel.getServiceAsync(\"metadata\") returned:', !!metadataService);\n } catch (e: any) {\n console.log('[HttpDispatcher] kernel.getServiceAsync(\"metadata\") failed:', e.message);\n }\n }\n\n // Path 2: kernel.getService (if not found via async)\n if (!metadataService && typeof this.kernel.getService === 'function') {\n try {\n metadataService = await this.kernel.getService('metadata');\n console.log('[HttpDispatcher] kernel.getService(\"metadata\") returned:', !!metadataService);\n } catch (e: any) {\n console.log('[HttpDispatcher] kernel.getService(\"metadata\") failed:', e.message);\n }\n }\n\n // Path 3: kernel.context.getService (if not found)\n if (!metadataService && this.kernel.context?.getService) {\n try {\n metadataService = await this.kernel.context.getService('metadata');\n console.log('[HttpDispatcher] kernel.context.getService(\"metadata\") returned:', !!metadataService);\n } catch (e: any) {\n console.log('[HttpDispatcher] kernel.context.getService(\"metadata\") failed:', e.message);\n }\n }\n\n console.log('[HttpDispatcher] Final metadataService:', !!metadataService, 'has getRegisteredTypes:', typeof (metadataService as any)?.getRegisteredTypes);\n\n if (metadataService && typeof (metadataService as any).getRegisteredTypes === 'function') {\n try {\n const types = await (metadataService as any).getRegisteredTypes();\n console.log('[HttpDispatcher] MetadataService.getRegisteredTypes() returned:', types);\n return { handled: true, response: this.success({ types }) };\n } catch (e: any) {\n // Log error but continue to fallbacks\n console.warn('[HttpDispatcher] MetadataService.getRegisteredTypes() failed:', e.message, e.stack);\n }\n } else {\n console.log('[HttpDispatcher] MetadataService not available or missing getRegisteredTypes, falling back to protocol service');\n }\n // PRIORITY 2: Try protocol service (returns SchemaRegistry types only - missing agent/tool)\n const protocol = await this.resolveService('protocol');\n if (protocol && typeof protocol.getMetaTypes === 'function') {\n const result = await protocol.getMetaTypes({});\n console.log('[HttpDispatcher] Protocol service returned types:', result);\n return { handled: true, response: this.success(result) };\n }\n // PRIORITY 3: ask broker for registered types\n if (broker) {\n try {\n const data = await broker.call('metadata.types', {}, { request: context.request });\n console.log('[HttpDispatcher] Broker returned types:', data);\n return { handled: true, response: this.success(data) };\n } catch (e) {\n console.log('[HttpDispatcher] Broker call failed:', e);\n // fall through to hardcoded defaults\n }\n }\n // Last resort: hardcoded defaults\n console.warn('[HttpDispatcher] Falling back to hardcoded defaults for metadata types');\n return { handled: true, response: this.success({ types: ['object', 'app', 'plugin'] }) };\n }\n\n // GET /metadata/:type/:name/published → get published version\n if (parts.length === 3 && parts[2] === 'published' && (!method || method === 'GET')) {\n const [type, name] = parts;\n const metadataService = await this.getService(CoreServiceName.enum.metadata);\n if (metadataService && typeof (metadataService as any).getPublished === 'function') {\n const data = await (metadataService as any).getPublished(type, name);\n if (data === undefined) return { handled: true, response: this.error('Not found', 404) };\n return { handled: true, response: this.success(data) };\n }\n // Broker fallback\n if (broker) {\n try {\n const data = await broker.call('metadata.getPublished', { type, name }, { request: context.request });\n return { handled: true, response: this.success(data) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, 404) };\n }\n }\n return { handled: true, response: this.error('Not found', 404) };\n }\n\n // /metadata/:type/:name\n if (parts.length === 2) {\n const [type, name] = parts;\n // Extract optional package filter from query string\n const packageId = query?.package || undefined;\n\n // PUT /metadata/:type/:name (Save)\n if (method === 'PUT' && body) {\n // Try to get the protocol service directly\n const protocol = await this.resolveService('protocol');\n\n if (protocol && typeof protocol.saveMetaItem === 'function') {\n try {\n const result = await protocol.saveMetaItem({ type, name, item: body });\n return { handled: true, response: this.success(result) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, 400) };\n }\n }\n\n // Fallback to broker if protocol not available (legacy)\n if (broker) {\n try {\n const data = await broker.call('metadata.saveItem', { type, name, item: body }, { request: context.request });\n return { handled: true, response: this.success(data) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message || 'Save not supported', 501) };\n }\n }\n return { handled: true, response: this.error('Save not supported', 501) };\n }\n\n try {\n // Try specific calls based on type\n if (type === 'objects' || type === 'object') {\n if (broker) {\n const data = await broker.call('metadata.getObject', { objectName: name }, { request: context.request });\n return { handled: true, response: this.success(data) };\n }\n // Try ObjectQL service directly when broker is unavailable\n const qlService = await this.getObjectQLService();\n if (qlService?.registry) {\n const data = qlService.registry.getObject(name);\n if (data) return { handled: true, response: this.success(data) };\n }\n return { handled: true, response: this.error('Not found', 404) };\n }\n\n // Normalize plural URL paths to singular registry type names\n const singularType = pluralToSingular(type);\n\n // Try Protocol Service First (Preferred)\n const protocol = await this.resolveService('protocol');\n if (protocol && typeof protocol.getMetaItem === 'function') {\n try {\n const data = await protocol.getMetaItem({ type: singularType, name, packageId });\n return { handled: true, response: this.success(data) };\n } catch (e: any) {\n // Protocol might throw if not found or not supported\n // Fallback to broker?\n }\n }\n\n // Generic call for other types if supported via Broker (Legacy)\n if (broker) {\n const method = `metadata.get${this.capitalize(singularType)}`;\n const data = await broker.call(method, { name }, { request: context.request });\n return { handled: true, response: this.success(data) };\n }\n return { handled: true, response: this.error('Not found', 404) };\n } catch (e: any) {\n // Fallback: treat first part as object name if only 1 part (handled below)\n // But here we are deep in 2 parts. Must be an error.\n return { handled: true, response: this.error(e.message, 404) };\n }\n }\n \n // GET /metadata/:type (List items of type) OR /metadata/:objectName (Legacy)\n if (parts.length === 1) {\n const typeOrName = parts[0];\n // Extract optional package filter from query string\n const packageId = query?.package || undefined;\n\n // Try protocol service first for any type\n const protocol = await this.resolveService('protocol');\n if (protocol && typeof protocol.getMetaItems === 'function') {\n try {\n const data = await protocol.getMetaItems({ type: typeOrName, packageId });\n // Return any valid response from protocol (including empty items arrays)\n if (data && (data.items !== undefined || Array.isArray(data))) {\n return { handled: true, response: this.success(data) };\n }\n } catch {\n // Protocol doesn't know this type, fall through\n }\n }\n\n // Try MetadataService directly for runtime-registered metadata (agents, tools, etc.)\n const metadataService = await this.getService(CoreServiceName.enum.metadata);\n if (metadataService && typeof (metadataService as any).list === 'function') {\n try {\n const items = await (metadataService as any).list(typeOrName);\n if (items && items.length > 0) {\n return { handled: true, response: this.success({ type: typeOrName, items }) };\n }\n } catch (e: any) {\n // MetadataService doesn't know this type or failed, continue to other fallbacks\n // Sanitize typeOrName to prevent log injection (CodeQL warning)\n const sanitizedType = String(typeOrName).replace(/[\\r\\n\\t]/g, '');\n console.debug(`[HttpDispatcher] MetadataService.list() failed for type:`, sanitizedType, 'error:', e.message);\n }\n }\n\n // Try broker for the type\n if (broker) {\n try {\n if (typeOrName === 'objects') {\n const data = await broker.call('metadata.objects', { packageId }, { request: context.request });\n return { handled: true, response: this.success(data) };\n }\n const data = await broker.call(`metadata.${typeOrName}`, { packageId }, { request: context.request });\n if (data !== null && data !== undefined) {\n return { handled: true, response: this.success(data) };\n }\n } catch {\n // Broker doesn't support this action, fall through\n }\n\n // Legacy: /metadata/:objectName (treat as single object lookup)\n try {\n const data = await broker.call('metadata.getObject', { objectName: typeOrName }, { request: context.request });\n return { handled: true, response: this.success(data) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, 404) };\n }\n }\n\n // No broker — try ObjectQL registry directly for object lookups\n const qlService = await this.getObjectQLService();\n if (qlService?.registry) {\n if (typeOrName === 'objects') {\n const objs = qlService.registry.getAllObjects(packageId);\n return { handled: true, response: this.success({ type: 'object', items: objs }) };\n }\n // Try listing items of the given type\n const items = qlService.registry.listItems?.(typeOrName, packageId);\n if (items && items.length > 0) {\n return { handled: true, response: this.success({ type: typeOrName, items }) };\n }\n // Legacy: treat as object name\n const obj = qlService.registry.getObject(typeOrName);\n if (obj) return { handled: true, response: this.success(obj) };\n }\n return { handled: true, response: this.error('Not found', 404) };\n }\n\n // GET /metadata — return available metadata types\n if (parts.length === 0) {\n // Try protocol service for dynamic types\n const protocol = await this.resolveService('protocol');\n if (protocol && typeof protocol.getMetaTypes === 'function') {\n const result = await protocol.getMetaTypes({});\n return { handled: true, response: this.success(result) };\n }\n // Fallback: ask broker for registered types\n if (broker) {\n try {\n const data = await broker.call('metadata.types', {}, { request: context.request });\n return { handled: true, response: this.success(data) };\n } catch {\n // fall through to hardcoded defaults\n }\n }\n return { handled: true, response: this.success({ types: ['object', 'app', 'plugin'] }) };\n }\n \n return { handled: false };\n }\n\n /**\n * Handles Data requests\n * path: sub-path after /data/ (e.g. \"contacts\", \"contacts/123\", \"contacts/query\")\n */\n async handleData(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise {\n const broker = this.ensureBroker();\n const parts = path.replace(/^\\/+/, '').split('/');\n const objectName = parts[0];\n \n if (!objectName) {\n return { handled: true, response: this.error('Object name required', 400) };\n }\n\n const m = method.toUpperCase();\n\n // 1. Custom Actions (query, batch)\n if (parts.length > 1) {\n const action = parts[1];\n \n // POST /data/:object/query\n if (action === 'query' && m === 'POST') {\n // Spec: broker returns FindDataResponse = { object, records, total?, hasMore? }\n const result = await broker.call('data.query', { object: objectName, ...body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // POST /data/:object/batch\n if (action === 'batch' && m === 'POST') {\n const result = await broker.call('data.batch', { object: objectName, ...body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // GET /data/:object/:id\n if (parts.length === 2 && m === 'GET') {\n const id = parts[1];\n // Spec: Only select/expand are allowlisted query params for GET by ID.\n // All other query parameters are discarded to prevent parameter pollution.\n const { select, expand } = query || {};\n const allowedParams: Record = {};\n if (select != null) allowedParams.select = select;\n if (expand != null) allowedParams.expand = expand;\n // Spec: broker returns GetDataResponse = { object, id, record }\n const result = await broker.call('data.get', { object: objectName, id, ...allowedParams }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // PATCH /data/:object/:id\n if (parts.length === 2 && m === 'PATCH') {\n const id = parts[1];\n // Spec: broker returns UpdateDataResponse = { object, id, record }\n const result = await broker.call('data.update', { object: objectName, id, data: body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // DELETE /data/:object/:id\n if (parts.length === 2 && m === 'DELETE') {\n const id = parts[1];\n // Spec: broker returns DeleteDataResponse = { object, id, deleted }\n const result = await broker.call('data.delete', { object: objectName, id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n } else {\n // GET /data/:object (List)\n if (m === 'GET') {\n // ── Normalize HTTP transport params → Spec canonical (QueryAST) ──\n // HTTP GET query params use transport-level names (filter, sort, top,\n // skip, select, expand) which are normalized here to canonical\n // QueryAST field names (where, orderBy, limit, offset, fields,\n // expand) before forwarding to the broker layer.\n // The protocol.ts findData() method performs a deeper normalization\n // pass, but pre-normalizing here ensures the broker always receives\n // Spec-canonical keys.\n const normalized: Record = { ...query };\n\n // filter/filters → where\n // Note: `filter` is the canonical HTTP *transport* parameter name\n // (see HttpFindQueryParamsSchema). It is normalized here to the\n // canonical *QueryAST* field name `where` before broker dispatch.\n // `filters` (plural) is a deprecated alias for `filter`.\n if (normalized.filter != null || normalized.filters != null) {\n normalized.where = normalized.where ?? normalized.filter ?? normalized.filters;\n delete normalized.filter;\n delete normalized.filters;\n }\n // select → fields\n if (normalized.select != null && normalized.fields == null) {\n normalized.fields = normalized.select;\n delete normalized.select;\n }\n // sort → orderBy\n if (normalized.sort != null && normalized.orderBy == null) {\n normalized.orderBy = normalized.sort;\n delete normalized.sort;\n }\n // top → limit\n if (normalized.top != null && normalized.limit == null) {\n normalized.limit = normalized.top;\n delete normalized.top;\n }\n // skip → offset\n if (normalized.skip != null && normalized.offset == null) {\n normalized.offset = normalized.skip;\n delete normalized.skip;\n }\n\n // Spec: broker returns FindDataResponse = { object, records, total?, hasMore? }\n const result = await broker.call('data.query', { object: objectName, query: normalized }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // POST /data/:object (Create)\n if (m === 'POST') {\n // Spec: broker returns CreateDataResponse = { object, id, record }\n const result = await broker.call('data.create', { object: objectName, data: body }, { request: context.request });\n const res = this.success(result);\n res.status = 201;\n return { handled: true, response: res };\n }\n }\n \n return { handled: false };\n }\n\n /**\n * Handles Analytics requests\n * path: sub-path after /analytics/\n */\n async handleAnalytics(path: string, method: string, body: any, _context: HttpProtocolContext): Promise {\n const analyticsService = await this.getService(CoreServiceName.enum.analytics);\n if (!analyticsService) return { handled: false }; // 404 handled by caller if unhandled\n\n const m = method.toUpperCase();\n const subPath = path.replace(/^\\/+/, '');\n\n // POST /analytics/query\n if (subPath === 'query' && m === 'POST') {\n const result = await analyticsService.query(body);\n return { handled: true, response: this.success(result) };\n }\n\n // GET /analytics/meta\n if (subPath === 'meta' && m === 'GET') {\n const result = await analyticsService.getMeta();\n return { handled: true, response: this.success(result) };\n }\n\n // POST /analytics/sql (Dry-run or debug)\n if (subPath === 'sql' && m === 'POST') {\n // Assuming service has generateSql method\n const result = await analyticsService.generateSql(body);\n return { handled: true, response: this.success(result) };\n }\n\n return { handled: false };\n }\n\n /**\n * Handles i18n requests\n * path: sub-path after /i18n/\n *\n * Routes:\n * GET /locales → getLocales\n * GET /translations/:locale → getTranslations (locale from path)\n * GET /translations?locale=xx → getTranslations (locale from query)\n * GET /labels/:object/:locale → getFieldLabels (both from path)\n * GET /labels/:object?locale=xx → getFieldLabels (locale from query)\n */\n async handleI18n(path: string, method: string, query: any, _context: HttpProtocolContext): Promise {\n const i18nService = await this.getService(CoreServiceName.enum.i18n);\n if (!i18nService) return { handled: true, response: this.error('i18n service not available', 501) };\n\n const m = method.toUpperCase();\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n\n if (m !== 'GET') return { handled: false };\n\n // GET /i18n/locales\n if (parts[0] === 'locales' && parts.length === 1) {\n const locales = i18nService.getLocales();\n return { handled: true, response: this.success({ locales }) };\n }\n\n // GET /i18n/translations/:locale OR /i18n/translations?locale=xx\n if (parts[0] === 'translations') {\n const locale = parts[1] ? decodeURIComponent(parts[1]) : query?.locale;\n if (!locale) return { handled: true, response: this.error('Missing locale parameter', 400) };\n\n let translations = i18nService.getTranslations(locale);\n\n // Locale fallback: try resolving to an available locale when\n // the exact code yields empty translations (e.g. zh → zh-CN).\n if (Object.keys(translations).length === 0) {\n const availableLocales = typeof i18nService.getLocales === 'function'\n ? i18nService.getLocales() : [];\n const resolved = resolveLocale(locale, availableLocales);\n if (resolved && resolved !== locale) {\n translations = i18nService.getTranslations(resolved);\n return { handled: true, response: this.success({ locale: resolved, requestedLocale: locale, translations }) };\n }\n }\n\n return { handled: true, response: this.success({ locale, translations }) };\n }\n\n // GET /i18n/labels/:object/:locale OR /i18n/labels/:object?locale=xx\n if (parts[0] === 'labels' && parts.length >= 2) {\n const objectName = decodeURIComponent(parts[1]);\n let locale = parts[2] ? decodeURIComponent(parts[2]) : query?.locale;\n if (!locale) return { handled: true, response: this.error('Missing locale parameter', 400) };\n\n // Locale fallback for labels endpoint\n const availableLocales = typeof i18nService.getLocales === 'function'\n ? i18nService.getLocales() : [];\n const resolved = resolveLocale(locale, availableLocales);\n if (resolved) locale = resolved;\n\n if (typeof i18nService.getFieldLabels === 'function') {\n const labels = i18nService.getFieldLabels(objectName, locale);\n return { handled: true, response: this.success({ object: objectName, locale, labels }) };\n }\n // Fallback: derive field labels from full translation bundle\n const translations = i18nService.getTranslations(locale);\n const prefix = `o.${objectName}.fields.`;\n const labels: Record = {};\n for (const [key, value] of Object.entries(translations)) {\n if (key.startsWith(prefix)) {\n labels[key.substring(prefix.length)] = value as string;\n }\n }\n return { handled: true, response: this.success({ object: objectName, locale, labels }) };\n }\n\n return { handled: false };\n }\n\n /**\n * Handles Package Management requests\n * \n * REST Endpoints:\n * - GET /packages → list all installed packages\n * - GET /packages/:id → get a specific package\n * - POST /packages → install a new package\n * - DELETE /packages/:id → uninstall a package\n * - PATCH /packages/:id/enable → enable a package\n * - PATCH /packages/:id/disable → disable a package\n * - POST /packages/:id/publish → publish a package (metadata snapshot)\n * - POST /packages/:id/revert → revert a package to last published state\n * \n * Uses ObjectQL SchemaRegistry directly (via the 'objectql' service)\n * with broker fallback for backward compatibility.\n */\n async handlePackages(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise {\n const m = method.toUpperCase();\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n\n // Try to get SchemaRegistry from the ObjectQL service\n const qlService = await this.getObjectQLService();\n const registry = qlService?.registry;\n\n // If no registry available, try broker as fallback\n if (!registry) {\n if (this.kernel.broker) {\n return this.handlePackagesViaBroker(parts, m, body, query, context);\n }\n return { handled: true, response: this.error('Package service not available', 503) };\n }\n\n try {\n // GET /packages → list packages\n if (parts.length === 0 && m === 'GET') {\n let packages = registry.getAllPackages();\n // Apply optional filters\n if (query?.status) {\n packages = packages.filter((p: any) => p.status === query.status);\n }\n if (query?.type) {\n packages = packages.filter((p: any) => p.manifest?.type === query.type);\n }\n return { handled: true, response: this.success({ packages, total: packages.length }) };\n }\n\n // POST /packages → install package\n if (parts.length === 0 && m === 'POST') {\n const pkg = registry.installPackage(body.manifest || body, body.settings);\n const res = this.success(pkg);\n res.status = 201;\n return { handled: true, response: res };\n }\n\n // PATCH /packages/:id/enable\n if (parts.length === 2 && parts[1] === 'enable' && m === 'PATCH') {\n const id = decodeURIComponent(parts[0]);\n const pkg = registry.enablePackage(id);\n if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };\n return { handled: true, response: this.success(pkg) };\n }\n\n // PATCH /packages/:id/disable\n if (parts.length === 2 && parts[1] === 'disable' && m === 'PATCH') {\n const id = decodeURIComponent(parts[0]);\n const pkg = registry.disablePackage(id);\n if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };\n return { handled: true, response: this.success(pkg) };\n }\n\n // POST /packages/:id/publish → publish package metadata\n if (parts.length === 2 && parts[1] === 'publish' && m === 'POST') {\n const id = decodeURIComponent(parts[0]);\n const metadataService = await this.getService(CoreServiceName.enum.metadata);\n if (metadataService && typeof (metadataService as any).publishPackage === 'function') {\n const result = await (metadataService as any).publishPackage(id, body || {});\n return { handled: true, response: this.success(result) };\n }\n // Broker fallback\n if (this.kernel.broker) {\n const result = await this.kernel.broker.call('metadata.publishPackage', { packageId: id, ...body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n return { handled: true, response: this.error('Metadata service not available', 503) };\n }\n\n // POST /packages/:id/revert → revert package to last published state\n if (parts.length === 2 && parts[1] === 'revert' && m === 'POST') {\n const id = decodeURIComponent(parts[0]);\n const metadataService = await this.getService(CoreServiceName.enum.metadata);\n if (metadataService && typeof (metadataService as any).revertPackage === 'function') {\n await (metadataService as any).revertPackage(id);\n return { handled: true, response: this.success({ success: true }) };\n }\n // Broker fallback\n if (this.kernel.broker) {\n await this.kernel.broker.call('metadata.revertPackage', { packageId: id }, { request: context.request });\n return { handled: true, response: this.success({ success: true }) };\n }\n return { handled: true, response: this.error('Metadata service not available', 503) };\n }\n\n // GET /packages/:id → get package\n if (parts.length === 1 && m === 'GET') {\n const id = decodeURIComponent(parts[0]);\n const pkg = registry.getPackage(id);\n if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };\n return { handled: true, response: this.success(pkg) };\n }\n\n // DELETE /packages/:id → uninstall package\n if (parts.length === 1 && m === 'DELETE') {\n const id = decodeURIComponent(parts[0]);\n const success = registry.uninstallPackage(id);\n if (!success) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };\n return { handled: true, response: this.success({ success: true }) };\n }\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, e.statusCode || 500) };\n }\n\n return { handled: false };\n }\n\n /**\n * Fallback: handle packages via broker (for backward compatibility)\n */\n private async handlePackagesViaBroker(parts: string[], m: string, body: any, query: any, context: HttpProtocolContext): Promise {\n const broker = this.kernel.broker;\n try {\n if (parts.length === 0 && m === 'GET') {\n const result = await broker.call('package.list', query || {}, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (parts.length === 0 && m === 'POST') {\n const result = await broker.call('package.install', body, { request: context.request });\n const res = this.success(result);\n res.status = 201;\n return { handled: true, response: res };\n }\n if (parts.length === 2 && parts[1] === 'enable' && m === 'PATCH') {\n const id = decodeURIComponent(parts[0]);\n const result = await broker.call('package.enable', { id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (parts.length === 2 && parts[1] === 'disable' && m === 'PATCH') {\n const id = decodeURIComponent(parts[0]);\n const result = await broker.call('package.disable', { id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (parts.length === 1 && m === 'GET') {\n const id = decodeURIComponent(parts[0]);\n const result = await broker.call('package.get', { id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (parts.length === 1 && m === 'DELETE') {\n const id = decodeURIComponent(parts[0]);\n const result = await broker.call('package.uninstall', { id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, e.statusCode || 500) };\n }\n return { handled: false };\n }\n\n /**\n * Handles Storage requests\n * path: sub-path after /storage/\n */\n async handleStorage(path: string, method: string, file: any, context: HttpProtocolContext): Promise {\n const storageService = await this.getService(CoreServiceName.enum['file-storage']) || this.kernel.services?.['file-storage'];\n if (!storageService) {\n return { handled: true, response: this.error('File storage not configured', 501) };\n }\n \n const m = method.toUpperCase();\n const parts = path.replace(/^\\/+/, '').split('/');\n \n // POST /storage/upload\n if (parts[0] === 'upload' && m === 'POST') {\n if (!file) {\n return { handled: true, response: this.error('No file provided', 400) };\n }\n const result = await storageService.upload(file, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n \n // GET /storage/file/:id\n if (parts[0] === 'file' && parts[1] && m === 'GET') {\n const id = parts[1];\n const result = await storageService.download(id, { request: context.request });\n \n // Result can be URL (redirect), Stream/Blob, or metadata\n if (result.url && result.redirect) {\n // Must be handled by adapter to do actual redirect\n return { handled: true, result: { type: 'redirect', url: result.url } };\n }\n \n if (result.stream) {\n // Must be handled by adapter to pipe stream\n return { \n handled: true, \n result: { \n type: 'stream', \n stream: result.stream, \n headers: {\n 'Content-Type': result.mimeType || 'application/octet-stream',\n 'Content-Length': result.size\n }\n } \n };\n }\n \n return { handled: true, response: this.success(result) };\n }\n \n return { handled: false };\n }\n\n /**\n * Handles UI requests\n * path: sub-path after /ui/\n */\n async handleUi(path: string, query: any, _context: HttpProtocolContext): Promise {\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n \n // GET /ui/view/:object (with optional type param)\n if (parts[0] === 'view' && parts[1]) {\n const objectName = parts[1];\n // Support both path param /view/obj/list AND query param /view/obj?type=list\n const type = parts[2] || query?.type || 'list';\n\n const protocol = await this.resolveService('protocol');\n \n if (protocol && typeof protocol.getUiView === 'function') {\n try {\n const result = await protocol.getUiView({ object: objectName, type });\n return { handled: true, response: this.success(result) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, 500) };\n }\n } else {\n return { handled: true, response: this.error('Protocol service not available', 503) };\n }\n }\n\n return { handled: false };\n }\n\n /**\n * Handles Automation requests\n * path: sub-path after /automation/\n *\n * Routes:\n * GET / → listFlows\n * GET /:name → getFlow\n * POST / → createFlow (registerFlow)\n * PUT /:name → updateFlow\n * DELETE /:name → deleteFlow (unregisterFlow)\n * POST /:name/trigger → execute (legacy: trigger/:name also supported)\n * POST /:name/toggle → toggleFlow\n * GET /:name/runs → listRuns\n * GET /:name/runs/:runId → getRun\n */\n async handleAutomation(path: string, method: string, body: any, context: HttpProtocolContext, query?: any): Promise {\n const automationService = await this.getService(CoreServiceName.enum.automation);\n if (!automationService) return { handled: false };\n\n const m = method.toUpperCase();\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n\n // Legacy: POST /automation/trigger/:name\n if (parts[0] === 'trigger' && parts[1] && m === 'POST') {\n const triggerName = parts[1];\n if (typeof automationService.trigger === 'function') {\n const result = await automationService.trigger(triggerName, body, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n // Fallback to execute\n if (typeof automationService.execute === 'function') {\n const result = await automationService.execute(triggerName, body);\n return { handled: true, response: this.success(result) };\n }\n }\n\n // GET / → listFlows\n if (parts.length === 0 && m === 'GET') {\n if (typeof automationService.listFlows === 'function') {\n const names = await automationService.listFlows();\n return { handled: true, response: this.success({ flows: names, total: names.length, hasMore: false }) };\n }\n }\n\n // POST / → createFlow\n if (parts.length === 0 && m === 'POST') {\n if (typeof automationService.registerFlow === 'function') {\n automationService.registerFlow(body?.name, body);\n return { handled: true, response: this.success(body) };\n }\n }\n\n // Routes with :name\n if (parts.length >= 1) {\n const name = parts[0];\n\n // POST /:name/trigger → execute\n if (parts[1] === 'trigger' && m === 'POST') {\n if (typeof automationService.execute === 'function') {\n const result = await automationService.execute(name, body);\n return { handled: true, response: this.success(result) };\n }\n }\n\n // POST /:name/toggle → toggleFlow\n if (parts[1] === 'toggle' && m === 'POST') {\n if (typeof automationService.toggleFlow === 'function') {\n await automationService.toggleFlow(name, body?.enabled ?? true);\n return { handled: true, response: this.success({ name, enabled: body?.enabled ?? true }) };\n }\n }\n\n // GET /:name/runs/:runId → getRun\n if (parts[1] === 'runs' && parts[2] && m === 'GET') {\n if (typeof automationService.getRun === 'function') {\n const run = await automationService.getRun(parts[2]);\n if (!run) return { handled: true, response: this.error('Execution not found', 404) };\n return { handled: true, response: this.success(run) };\n }\n }\n\n // GET /:name/runs → listRuns\n if (parts[1] === 'runs' && !parts[2] && m === 'GET') {\n if (typeof automationService.listRuns === 'function') {\n const options = query ? { limit: query.limit ? Number(query.limit) : undefined, cursor: query.cursor } : undefined;\n const runs = await automationService.listRuns(name, options);\n return { handled: true, response: this.success({ runs, hasMore: false }) };\n }\n }\n\n // GET /:name → getFlow (no sub-path)\n if (parts.length === 1 && m === 'GET') {\n if (typeof automationService.getFlow === 'function') {\n const flow = await automationService.getFlow(name);\n if (!flow) return { handled: true, response: this.error('Flow not found', 404) };\n return { handled: true, response: this.success(flow) };\n }\n }\n\n // PUT /:name → updateFlow\n if (parts.length === 1 && m === 'PUT') {\n if (typeof automationService.registerFlow === 'function') {\n automationService.registerFlow(name, body?.definition ?? body);\n return { handled: true, response: this.success(body?.definition ?? body) };\n }\n }\n\n // DELETE /:name → deleteFlow\n if (parts.length === 1 && m === 'DELETE') {\n if (typeof automationService.unregisterFlow === 'function') {\n automationService.unregisterFlow(name);\n return { handled: true, response: this.success({ name, deleted: true }) };\n }\n }\n }\n \n return { handled: false };\n }\n\n private getServicesMap(): Record {\n if (this.kernel.services instanceof Map) {\n return Object.fromEntries(this.kernel.services);\n }\n return this.kernel.services || {};\n }\n\n private async getService(name: CoreServiceName) {\n return this.resolveService(name);\n }\n\n /**\n * Resolve any service by name, supporting async factories.\n * Fallback chain: getServiceAsync → getService (sync) → context.getService → services map.\n * Only returns when a non-null service is found; otherwise falls through to the next step.\n */\n private async resolveService(name: string) {\n // Prefer async resolution to support factory-based services (e.g. auth, analytics, protocol)\n if (typeof this.kernel.getServiceAsync === 'function') {\n try {\n const svc = await this.kernel.getServiceAsync(name);\n if (svc != null) return svc;\n } catch {\n // Service not registered or async resolution failed — fall through\n }\n }\n if (typeof this.kernel.getService === 'function') {\n try {\n const svc = await this.kernel.getService(name);\n if (svc != null) return svc;\n } catch {\n // Service not registered or sync resolution threw \"is async\" — fall through\n }\n }\n if (this.kernel?.context?.getService) {\n try {\n const svc = await this.kernel.context.getService(name);\n if (svc != null) return svc;\n } catch {\n // Service not registered — fall through\n }\n }\n const services = this.getServicesMap();\n return services[name];\n }\n\n /**\n * Get the ObjectQL service which provides access to SchemaRegistry.\n * Tries multiple access patterns since kernel structure varies.\n */\n private async getObjectQLService(): Promise {\n // 1. Try via resolveService (handles async factories, sync, context, and map)\n try {\n const svc = await this.resolveService('objectql');\n if (svc?.registry) return svc;\n } catch { /* service not available */ }\n return null;\n }\n\n private capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n }\n\n /**\n * Handle AI service routes (/ai/chat, /ai/models, /ai/conversations, etc.)\n * Resolves the AI service and its built-in route handlers, then dispatches.\n */\n async handleAI(subPath: string, method: string, body: any, query: any, _context: HttpProtocolContext): Promise {\n let aiService: any;\n try {\n aiService = await this.resolveService('ai');\n } catch {\n // AI service not registered\n }\n\n if (!aiService) {\n return {\n handled: true,\n response: {\n status: 404,\n body: { success: false, error: { message: 'AI service is not configured', code: 404 } },\n },\n };\n }\n\n // The AI service exposes route definitions via buildAIRoutes.\n // We match the request path against known AI route patterns.\n const fullPath = `/api/v1${subPath}`;\n\n // Build a simple param-extracting matcher for route patterns like /api/v1/ai/conversations/:id\n const matchRoute = (pattern: string, path: string): Record | null => {\n const patternParts = pattern.split('/');\n const pathParts = path.split('/');\n if (patternParts.length !== pathParts.length) return null;\n const params: Record = {};\n for (let i = 0; i < patternParts.length; i++) {\n if (patternParts[i].startsWith(':')) {\n params[patternParts[i].substring(1)] = pathParts[i];\n } else if (patternParts[i] !== pathParts[i]) {\n return null;\n }\n }\n return params;\n };\n\n // Try to get route definitions from the AI service's cached routes\n const routes = (this.kernel as any).__aiRoutes as Array<{\n method: string; path: string; handler: (req: any) => Promise;\n }> | undefined;\n\n if (!routes) {\n return {\n handled: true,\n response: {\n status: 503,\n body: { success: false, error: { message: 'AI service routes not yet initialized', code: 503 } },\n },\n };\n }\n\n for (const route of routes) {\n if (route.method !== method) continue;\n const params = matchRoute(route.path, fullPath);\n if (params === null) continue;\n\n const result = await route.handler({ body, params, query });\n\n if (result.stream && result.events) {\n // Return a streaming result for the adapter to handle\n return {\n handled: true,\n result: {\n type: 'stream',\n contentType: result.vercelDataStream\n ? 'text/plain; charset=utf-8'\n : 'text/event-stream',\n events: result.events,\n vercelDataStream: result.vercelDataStream,\n headers: {\n 'Content-Type': result.vercelDataStream\n ? 'text/plain; charset=utf-8'\n : 'text/event-stream',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n },\n },\n };\n }\n\n return {\n handled: true,\n response: {\n status: result.status,\n body: result.body,\n },\n };\n }\n\n return {\n handled: true,\n response: this.routeNotFound(subPath),\n };\n }\n\n /**\n * Main Dispatcher Entry Point\n * Routes the request to the appropriate handler based on path and precedence\n */\n async dispatch(method: string, path: string, body: any, query: any, context: HttpProtocolContext, prefix?: string): Promise {\n const cleanPath = path.replace(/\\/$/, ''); // Remove trailing slash if present, but strict on clean paths\n\n // 0. Discovery Endpoint (GET /discovery or GET /)\n // Standard route: /discovery (protocol-compliant)\n // Legacy route: / (empty path, for backward compatibility — MSW strips base URL)\n if ((cleanPath === '/discovery' || cleanPath === '') && method === 'GET') {\n const info = await this.getDiscoveryInfo(prefix ?? '');\n return { \n handled: true, \n response: this.success(info) \n };\n }\n\n // 0b. Health Endpoint (GET /health)\n if (cleanPath === '/health' && method === 'GET') {\n return {\n handled: true,\n response: this.success({\n status: 'ok',\n timestamp: new Date().toISOString(),\n version: '1.0.0',\n uptime: typeof process !== 'undefined' ? process.uptime() : undefined,\n }),\n };\n }\n\n // 1. System Protocols (Prefix-based)\n if (cleanPath.startsWith('/auth')) {\n return this.handleAuth(cleanPath.substring(5), method, body, context);\n }\n \n if (cleanPath.startsWith('/meta')) {\n return this.handleMetadata(cleanPath.substring(5), context, method, body, query);\n }\n\n if (cleanPath.startsWith('/data')) {\n return this.handleData(cleanPath.substring(5), method, body, query, context);\n }\n \n if (cleanPath.startsWith('/graphql')) {\n if (method === 'POST') return this.handleGraphQL(body, context);\n // GraphQL usually GET for Playground is handled by middleware but we can return 405 or handle it\n }\n\n if (cleanPath.startsWith('/storage')) {\n return this.handleStorage(cleanPath.substring(8), method, body, context); // body here is file/stream for upload\n }\n \n if (cleanPath.startsWith('/ui')) {\n return this.handleUi(cleanPath.substring(3), query, context);\n }\n\n if (cleanPath.startsWith('/automation')) {\n return this.handleAutomation(cleanPath.substring(11), method, body, context, query);\n }\n \n if (cleanPath.startsWith('/analytics')) {\n return this.handleAnalytics(cleanPath.substring(10), method, body, context);\n }\n\n if (cleanPath.startsWith('/packages')) {\n return this.handlePackages(cleanPath.substring(9), method, body, query, context);\n }\n\n if (cleanPath.startsWith('/i18n')) {\n return this.handleI18n(cleanPath.substring(5), method, query, context);\n }\n\n // AI Service — delegate to the registered AI route handlers\n if (cleanPath.startsWith('/ai')) {\n return this.handleAI(cleanPath, method, body, query, context);\n }\n\n // OpenAPI Specification\n if (cleanPath === '/openapi.json' && method === 'GET') {\n const broker = this.ensureBroker();\n try {\n const result = await broker.call('metadata.generateOpenApi', {}, { request: context.request });\n return { handled: true, response: this.success(result) };\n } catch (e) {\n // If not implemented, fall through or return 404\n }\n }\n\n // 2. Custom API Endpoints (Registry lookup)\n // Check if there is a custom endpoint defined for this path\n const result = await this.handleApiEndpoint(cleanPath, method, body, query, context);\n if (result.handled) return result;\n\n // 3. Fallback — return semantic 404 with diagnostic info\n return {\n handled: true,\n response: this.routeNotFound(cleanPath),\n };\n }\n\n /**\n * Handles Custom API Endpoints defined in metadata\n */\n async handleApiEndpoint(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise {\n const broker = this.ensureBroker();\n try {\n // Attempt to find a matching endpoint in the registry\n // This assumes a 'metadata.matchEndpoint' action exists in the kernel/registry\n // path should include initial slash e.g. /api/v1/customers\n const endpoint = await broker.call('metadata.matchEndpoint', { path, method });\n \n if (endpoint) {\n // Execute the endpoint target logic\n if (endpoint.type === 'flow') {\n const result = await broker.call('automation.runFlow', { \n flowId: endpoint.target, \n inputs: { ...query, ...body, _request: context.request } \n });\n return { handled: true, response: this.success(result) };\n }\n \n if (endpoint.type === 'script') {\n const result = await broker.call('automation.runScript', { \n scriptName: endpoint.target, \n context: { ...query, ...body, request: context.request } \n }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n if (endpoint.type === 'object_operation') {\n // e.g. Proxy to an object action\n if (endpoint.objectParams) {\n const { object, operation } = endpoint.objectParams;\n // Map standard CRUD operations\n if (operation === 'find') {\n const result = await broker.call('data.query', { object, query }, { request: context.request });\n // Spec: FindDataResponse = { object, records, total?, hasMore? }\n return { handled: true, response: this.success(result.records, { total: result.total }) };\n }\n if (operation === 'get' && query.id) {\n const result = await broker.call('data.get', { object, id: query.id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (operation === 'create') {\n const result = await broker.call('data.create', { object, data: body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n }\n }\n\n if (endpoint.type === 'proxy') {\n // Simple proxy implementation (requires a network call, which usually is done by a service but here we can stub return)\n // In real implementation this might fetch(endpoint.target)\n // For now, return target info\n return { \n handled: true, \n response: { \n status: 200, \n body: { proxy: true, target: endpoint.target, note: 'Proxy execution requires http-client service' } \n } \n };\n }\n }\n } catch (e) {\n // If matchEndpoint fails (e.g. not found), we just return not handled\n // so we can fallback to 404 or other handlers\n }\n\n return { handled: false };\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext, IHttpServer } from '@objectstack/core';\nimport { HttpDispatcher, HttpDispatcherResult } from './http-dispatcher.js';\n\nexport interface DispatcherPluginConfig {\n /**\n * API path prefix for all endpoints.\n * @default '/api/v1'\n */\n prefix?: string;\n}\n\n/**\n * Route definition emitted by service plugins (e.g. AIServicePlugin) via hooks.\n * Minimal interface — matches the shape produced by `buildAIRoutes()`.\n */\ninterface RouteDefinition {\n method: 'GET' | 'POST' | 'DELETE';\n path: string;\n description: string;\n handler: (req: any) => Promise;\n}\n\n/**\n * Register a single RouteDefinition on the HTTP server.\n * Returns true if the route was successfully registered.\n */\nfunction mountRouteOnServer(route: RouteDefinition, server: IHttpServer, routePath: string): boolean {\n const handler = async (req: any, res: any) => {\n try {\n const result = await route.handler({\n body: req.body,\n params: req.params,\n query: req.query,\n });\n\n if (result.stream && result.events) {\n // SSE streaming response\n res.status(result.status);\n\n // Apply headers from the route result if available\n if (result.headers) {\n for (const [k, v] of Object.entries(result.headers)) {\n res.header(k, String(v));\n }\n } else {\n res.header('Content-Type', 'text/event-stream');\n res.header('Cache-Control', 'no-cache');\n res.header('Connection', 'keep-alive');\n }\n\n // Write the stream — events are pre-encoded SSE strings\n if (typeof res.write === 'function' && typeof res.end === 'function') {\n for await (const event of result.events) {\n res.write(typeof event === 'string' ? event : `data: ${JSON.stringify(event)}\\n\\n`);\n }\n res.end();\n } else {\n // Fallback: collect events into array\n const events = [];\n for await (const event of result.events) {\n events.push(event);\n }\n res.json({ events });\n }\n } else {\n res.status(result.status);\n if (result.body !== undefined) {\n res.json(result.body);\n } else {\n res.end();\n }\n }\n } catch (err: any) {\n errorResponse(err, res);\n }\n };\n\n const m = route.method.toLowerCase();\n if (m === 'get' && typeof server.get === 'function') {\n server.get(routePath, handler);\n return true;\n } else if (m === 'post' && typeof server.post === 'function') {\n server.post(routePath, handler);\n return true;\n } else if (m === 'delete' && typeof server.delete === 'function') {\n server.delete(routePath, handler);\n return true;\n }\n return false;\n}\n\n/**\n * Send an HttpDispatcherResult through IHttpResponse.\n * Differentiates between handled, unhandled (404), and special results.\n */\nfunction sendResult(result: HttpDispatcherResult, res: any): void {\n if (result.handled) {\n if (result.response) {\n res.status(result.response.status);\n if (result.response.headers) {\n for (const [k, v] of Object.entries(result.response.headers)) {\n res.header(k, v);\n }\n }\n res.json(result.response.body);\n return;\n }\n if (result.result) {\n // Special results (redirect, stream) — pass through as JSON for now\n res.status(200).json(result.result);\n return;\n }\n }\n // Semantic 404: no route matched — include diagnostic info\n res.status(404).json({\n success: false,\n error: {\n message: 'Not Found',\n code: 404,\n type: 'ROUTE_NOT_FOUND',\n hint: 'No handler matched this request. Check the API discovery endpoint for available routes.',\n },\n });\n}\n\nfunction errorResponse(err: any, res: any): void {\n const code = err.statusCode || 500;\n res.status(code).json({\n success: false,\n error: { message: err.message || 'Internal Server Error', code },\n });\n}\n\n/**\n * Dispatcher Plugin\n *\n * Bridges legacy HttpDispatcher handlers to the IHttpServer route-registration model.\n * Registers routes for domains NOT covered by @objectstack/rest:\n * - /.well-known/objectstack (discovery)\n * - /auth (authentication)\n * - /graphql (GraphQL)\n * - /analytics (BI queries)\n * - /packages (package management)\n * - /i18n (internationalization — locales, translations, field labels)\n * - /storage (file storage)\n * - /automation (CRUD + triggers + runs)\n *\n * Usage:\n * ```ts\n * import { createDispatcherPlugin } from '@objectstack/runtime';\n * runtime.use(createDispatcherPlugin({ prefix: '/api/v1' }));\n * ```\n */\nexport function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plugin {\n return {\n name: 'com.objectstack.runtime.dispatcher',\n version: '1.0.0',\n\n init: async (_ctx: PluginContext) => {\n // Consumer-only plugin — no services registered\n },\n\n start: async (ctx: PluginContext) => {\n let server: IHttpServer | undefined;\n try {\n server = ctx.getService('http.server');\n } catch {\n // No HTTP server available — skip silently\n return;\n }\n if (!server) return;\n\n const kernel = ctx.getKernel();\n const dispatcher = new HttpDispatcher(kernel);\n const prefix = config.prefix || '/api/v1';\n\n // ── Discovery (.well-known) ─────────────────────────────────\n server.get('/.well-known/objectstack', async (_req: any, res: any) => {\n res.json({ data: await dispatcher.getDiscoveryInfo(prefix) });\n });\n\n // ── Discovery (versioned API path) ──────────────────────────\n server.get(`${prefix}/discovery`, async (_req: any, res: any) => {\n res.json({ data: await dispatcher.getDiscoveryInfo(prefix) });\n });\n\n // ── Health ──────────────────────────────────────────────────\n server.get(`${prefix}/health`, async (_req: any, res: any) => {\n try {\n const result = await dispatcher.dispatch('GET', '/health', undefined, {}, { request: _req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Auth ────────────────────────────────────────────────────\n server.post(`${prefix}/auth/login`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAuth('login', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── GraphQL ─────────────────────────────────────────────────\n server.post(`${prefix}/graphql`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleGraphQL(req.body, { request: req });\n res.json(result);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Analytics ───────────────────────────────────────────────\n server.post(`${prefix}/analytics/query`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAnalytics('query', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/analytics/meta`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAnalytics('meta', 'GET', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/analytics/sql`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAnalytics('sql', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Packages ────────────────────────────────────────────────\n server.get(`${prefix}/packages`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages('', 'GET', {}, req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/packages`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages('', 'POST', req.body, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/packages/:id`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}`, 'GET', {}, req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.delete(`${prefix}/packages/:id`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}`, 'DELETE', {}, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.patch(`${prefix}/packages/:id/enable`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}/enable`, 'PATCH', {}, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.patch(`${prefix}/packages/:id/disable`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}/disable`, 'PATCH', {}, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/packages/:id/publish`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}/publish`, 'POST', req.body, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/packages/:id/revert`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}/revert`, 'POST', req.body, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Storage ─────────────────────────────────────────────────\n server.post(`${prefix}/storage/upload`, async (req: any, res: any) => {\n try {\n // For file uploads the body *is* the file (parsed by adapter)\n const result = await dispatcher.handleStorage('upload', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/storage/file/:id`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleStorage(`file/${req.params.id}`, 'GET', undefined, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── i18n ────────────────────────────────────────────────────\n // Bridges to HttpDispatcher.handleI18n() which resolves the i18n\n // service from the kernel (either I18nServicePlugin or memory fallback).\n server.get(`${prefix}/i18n/locales`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleI18n('/locales', 'GET', req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/i18n/translations/:locale`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleI18n(`/translations/${req.params.locale}`, 'GET', req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/i18n/labels/:object/:locale`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleI18n(`/labels/${req.params.object}/${req.params.locale}`, 'GET', req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Automation ──────────────────────────────────────────────\n server.get(`${prefix}/automation`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation('', 'GET', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/automation`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation('', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/automation/:name`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}`, 'GET', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.put(`${prefix}/automation/:name`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}`, 'PUT', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.delete(`${prefix}/automation/:name`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}`, 'DELETE', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/automation/trigger/:name`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`trigger/${req.params.name}`, 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/automation/:name/trigger`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}/trigger`, 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/automation/:name/toggle`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}/toggle`, 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/automation/:name/runs`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}/runs`, 'GET', {}, { request: req }, req.query);\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/automation/:name/runs/:runId`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}/runs/${req.params.runId}`, 'GET', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n ctx.logger.info('Dispatcher bridge routes registered', { prefix });\n\n // ── Dynamic service routes (AI, etc.) ───────────────────\n // Listen for route definitions emitted by service plugins.\n // The AIServicePlugin emits 'ai:routes' with RouteDefinition[].\n ctx.hook('ai:routes', async (routes: RouteDefinition[]) => {\n if (!server) return;\n for (const route of routes) {\n // Strip the /api/v1 prefix if present (it's already in the path)\n // and register on the HTTP server with the configured prefix.\n const routePath = route.path.startsWith('/api/v1')\n ? route.path\n : `${prefix}${route.path}`;\n mountRouteOnServer(route, server, routePath);\n }\n ctx.logger.info(`[Dispatcher] Registered ${routes.length} AI routes`);\n });\n\n // ── Fallback: recover routes cached before hook was registered ──\n // If AIServicePlugin.start() ran before DispatcherPlugin.start()\n // (possible when plugin start order differs from registration order),\n // the 'ai:routes' trigger fires with no listener. The AIServicePlugin\n // caches the routes on the kernel as __aiRoutes (see AIServicePlugin.start())\n // as an internal cross-plugin protocol so we can recover them here.\n // TODO: replace with a formal kernel.getCachedRoutes('ai') API in a future release.\n const cachedRoutes = (kernel as any).__aiRoutes as RouteDefinition[] | undefined;\n if (cachedRoutes && Array.isArray(cachedRoutes) && cachedRoutes.length > 0) {\n let registered = 0;\n for (const route of cachedRoutes) {\n const routePath = route.path.startsWith('/api/v1')\n ? route.path\n : `${prefix}${route.path}`;\n if (mountRouteOnServer(route, server, routePath)) {\n registered++;\n }\n }\n if (registered > 0) {\n ctx.logger.info(`[Dispatcher] Recovered ${registered} cached AI routes (hook timing fallback)`);\n }\n }\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { IHttpServer, RouteHandler, Middleware } from '@objectstack/core';\n\n/**\n * HttpServer - Unified HTTP Server Abstraction\n * \n * Provides a framework-agnostic HTTP server interface that wraps\n * underlying server implementations (Hono, Express, Fastify, etc.)\n * \n * This class serves as an adapter between the IHttpServer interface\n * and concrete server implementations, allowing plugins to register\n * routes and middleware without depending on specific frameworks.\n * \n * Features:\n * - Unified route registration API\n * - Middleware management with ordering\n * - Request/response lifecycle hooks\n * - Framework-agnostic abstractions\n */\nexport class HttpServer implements IHttpServer {\n protected server: IHttpServer;\n protected routes: Map;\n protected middlewares: Middleware[];\n \n /**\n * Create an HTTP server wrapper\n * @param server - The underlying server implementation (Hono, Express, etc.)\n */\n constructor(server: IHttpServer) {\n this.server = server;\n this.routes = new Map();\n this.middlewares = [];\n }\n \n /**\n * Register a GET route handler\n * @param path - Route path (e.g., '/api/users/:id')\n * @param handler - Route handler function\n */\n get(path: string, handler: RouteHandler): void {\n const key = `GET:${path}`;\n this.routes.set(key, handler);\n this.server.get(path, handler);\n }\n \n /**\n * Register a POST route handler\n * @param path - Route path\n * @param handler - Route handler function\n */\n post(path: string, handler: RouteHandler): void {\n const key = `POST:${path}`;\n this.routes.set(key, handler);\n this.server.post(path, handler);\n }\n \n /**\n * Register a PUT route handler\n * @param path - Route path\n * @param handler - Route handler function\n */\n put(path: string, handler: RouteHandler): void {\n const key = `PUT:${path}`;\n this.routes.set(key, handler);\n this.server.put(path, handler);\n }\n \n /**\n * Register a DELETE route handler\n * @param path - Route path\n * @param handler - Route handler function\n */\n delete(path: string, handler: RouteHandler): void {\n const key = `DELETE:${path}`;\n this.routes.set(key, handler);\n this.server.delete(path, handler);\n }\n \n /**\n * Register a PATCH route handler\n * @param path - Route path\n * @param handler - Route handler function\n */\n patch(path: string, handler: RouteHandler): void {\n const key = `PATCH:${path}`;\n this.routes.set(key, handler);\n this.server.patch(path, handler);\n }\n \n /**\n * Register middleware\n * @param path - Optional path to apply middleware to (if omitted, applies globally)\n * @param handler - Middleware function\n */\n use(path: string | Middleware, handler?: Middleware): void {\n if (typeof path === 'function') {\n // Global middleware\n this.middlewares.push(path);\n this.server.use(path);\n } else if (handler) {\n // Path-specific middleware\n this.middlewares.push(handler);\n this.server.use(path, handler);\n }\n }\n \n /**\n * Start the HTTP server\n * @param port - Port number to listen on\n * @returns Promise that resolves when server is ready\n */\n async listen(port: number): Promise {\n await this.server.listen(port);\n }\n \n /**\n * Stop the HTTP server\n * @returns Promise that resolves when server is stopped\n */\n async close(): Promise {\n if (this.server.close) {\n await this.server.close();\n }\n }\n \n /**\n * Get registered routes\n * @returns Map of route keys to handlers\n */\n getRoutes(): Map {\n return new Map(this.routes);\n }\n \n /**\n * Get registered middlewares\n * @returns Array of middleware functions\n */\n getMiddlewares(): Middleware[] {\n return [...this.middlewares];\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Middleware, IHttpRequest, IHttpResponse } from '@objectstack/core';\nimport { MiddlewareConfig, MiddlewareType } from '@objectstack/spec/system';\n\n/**\n * Middleware Entry\n * Internal representation of registered middleware\n */\ninterface MiddlewareEntry {\n name: string;\n type: MiddlewareType;\n middleware: Middleware;\n order: number;\n enabled: boolean;\n paths?: {\n include?: string[];\n exclude?: string[];\n };\n}\n\n/**\n * MiddlewareManager\n * \n * Manages middleware registration, ordering, and execution.\n * Provides fine-grained control over middleware chains with:\n * - Execution order management\n * - Path-based filtering\n * - Enable/disable individual middleware\n * - Middleware categorization by type\n * \n * @example\n * const manager = new MiddlewareManager();\n * \n * // Register middleware with configuration\n * manager.register({\n * name: 'auth',\n * type: 'authentication',\n * order: 10,\n * paths: { exclude: ['/health', '/metrics'] }\n * }, authMiddleware);\n * \n * // Get sorted middleware chain\n * const chain = manager.getMiddlewareChain();\n * chain.forEach(mw => server.use(mw));\n */\nexport class MiddlewareManager {\n private middlewares: Map;\n \n constructor() {\n this.middlewares = new Map();\n }\n \n /**\n * Register middleware with configuration\n * @param config - Middleware configuration\n * @param middleware - Middleware function\n */\n register(config: MiddlewareConfig, middleware: Middleware): void {\n const entry: MiddlewareEntry = {\n name: config.name,\n type: config.type,\n middleware,\n order: config.order ?? 100,\n enabled: config.enabled ?? true,\n paths: config.paths,\n };\n \n this.middlewares.set(config.name, entry);\n }\n \n /**\n * Unregister middleware by name\n * @param name - Middleware name\n */\n unregister(name: string): void {\n this.middlewares.delete(name);\n }\n \n /**\n * Enable middleware by name\n * @param name - Middleware name\n */\n enable(name: string): void {\n const entry = this.middlewares.get(name);\n if (entry) {\n entry.enabled = true;\n }\n }\n \n /**\n * Disable middleware by name\n * @param name - Middleware name\n */\n disable(name: string): void {\n const entry = this.middlewares.get(name);\n if (entry) {\n entry.enabled = false;\n }\n }\n \n /**\n * Get middleware entry by name\n * @param name - Middleware name\n */\n get(name: string): MiddlewareEntry | undefined {\n return this.middlewares.get(name);\n }\n \n /**\n * Get all middleware entries\n */\n getAll(): MiddlewareEntry[] {\n return Array.from(this.middlewares.values());\n }\n \n /**\n * Get middleware by type\n * @param type - Middleware type\n */\n getByType(type: MiddlewareType): MiddlewareEntry[] {\n return this.getAll().filter(entry => entry.type === type);\n }\n \n /**\n * Get middleware chain sorted by order\n * Returns only enabled middleware\n */\n getMiddlewareChain(): Middleware[] {\n return this.getAll()\n .filter(entry => entry.enabled)\n .sort((a, b) => a.order - b.order)\n .map(entry => entry.middleware);\n }\n \n /**\n * Get middleware chain with path filtering\n * @param path - Request path to match against\n */\n getMiddlewareChainForPath(path: string): Middleware[] {\n return this.getAll()\n .filter(entry => {\n if (!entry.enabled) return false;\n \n // Check path filters\n if (entry.paths) {\n // Check exclude patterns\n if (entry.paths.exclude) {\n const excluded = entry.paths.exclude.some(pattern => \n this.matchPath(path, pattern)\n );\n if (excluded) return false;\n }\n \n // Check include patterns (if specified)\n if (entry.paths.include) {\n const included = entry.paths.include.some(pattern => \n this.matchPath(path, pattern)\n );\n if (!included) return false;\n }\n }\n \n return true;\n })\n .sort((a, b) => a.order - b.order)\n .map(entry => entry.middleware);\n }\n \n /**\n * Match path against pattern (simple glob matching)\n * @param path - Request path\n * @param pattern - Pattern to match (supports * wildcard)\n */\n private matchPath(path: string, pattern: string): boolean {\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n \n const regex = new RegExp(`^${regexPattern}$`);\n return regex.test(path);\n }\n \n /**\n * Clear all middleware\n */\n clear(): void {\n this.middlewares.clear();\n }\n \n /**\n * Get middleware count\n */\n count(): number {\n return this.middlewares.size;\n }\n \n /**\n * Create a composite middleware from the chain\n * This can be used to apply all middleware at once\n */\n createCompositeMiddleware(): Middleware {\n const chain = this.getMiddlewareChain();\n \n return async (req: IHttpRequest, res: IHttpResponse, next: () => void | Promise) => {\n let index = 0;\n \n const executeNext = async (): Promise => {\n if (index >= chain.length) {\n await next();\n return;\n }\n \n const middleware = chain[index++];\n await middleware(req, res, executeNext);\n };\n \n await executeNext();\n };\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Base Field Mapping Protocol\n * \n * Shared by: ETL, Sync, Connector, External Lookup\n * \n * This module provides the canonical field mapping schema used across\n * ObjectStack for data transformation and synchronization.\n * \n * **Use Cases:**\n * - ETL pipelines (data/mapping.zod.ts)\n * - Data synchronization (automation/sync.zod.ts)\n * - Integration connectors (integration/connector.zod.ts)\n * - External lookups (data/external-lookup.zod.ts)\n * \n * @example Basic field mapping\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'external_user_id',\n * target: 'user_id',\n * };\n * ```\n * \n * @example With transformation\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'user_name',\n * target: 'name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: 'Unknown'\n * };\n * ```\n */\n\n/**\n * Transform Type Schema\n * \n * Defines the type of transformation to apply to a field value.\n * Implementations can extend this for domain-specific transforms.\n */\nexport const TransformTypeSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('constant'),\n value: z.unknown().describe('Constant value to use'),\n }).describe('Set a constant value'),\n \n z.object({\n type: z.literal('cast'),\n targetType: z.enum(['string', 'number', 'boolean', 'date']).describe('Target data type'),\n }).describe('Cast to a specific data type'),\n \n z.object({\n type: z.literal('lookup'),\n table: z.string().describe('Lookup table name'),\n keyField: z.string().describe('Field to match on'),\n valueField: z.string().describe('Field to retrieve'),\n }).describe('Lookup value from another table'),\n \n z.object({\n type: z.literal('javascript'),\n expression: z.string().describe('JavaScript expression (e.g., \"value.toUpperCase()\")'),\n }).describe('Custom JavaScript transformation'),\n \n z.object({\n type: z.literal('map'),\n mappings: z.record(z.string(), z.unknown()).describe('Value mappings (e.g., {\"Active\": \"active\"})'),\n }).describe('Map values using a dictionary'),\n]);\n\nexport type TransformType = z.infer;\n\n/**\n * Field Mapping Schema\n * \n * Base schema for mapping fields between source and target systems.\n * \n * **NAMING CONVENTION:**\n * - source: Field name in the source system\n * - target: Field name in the target system (should be snake_case for ObjectStack)\n * \n * @example\n * ```typescript\n * {\n * source: 'FirstName',\n * target: 'first_name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: ''\n * }\n * ```\n */\nexport const FieldMappingSchema = z.object({\n /**\n * Source field name\n */\n source: z.string().describe('Source field name'),\n \n /**\n * Target field name (should be snake_case for ObjectStack)\n */\n target: z.string().describe('Target field name'),\n \n /**\n * Transformation to apply\n */\n transform: TransformTypeSchema.optional().describe('Transformation to apply'),\n \n /**\n * Default value if source is null/undefined\n */\n defaultValue: z.unknown().optional().describe('Default if source is null/undefined'),\n});\n\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Shared Enumerations\n// ============================================================================\n\n/** Aggregation functions used across query, data-engine, analytics, field */\nexport const AggregationFunctionEnum = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'percentile', 'median', 'stddev', 'variance',\n]).describe('Standard aggregation functions');\nexport type AggregationFunction = z.infer;\n\n/** Sort direction used across query, data-engine, analytics */\nexport const SortDirectionEnum = z.enum(['asc', 'desc'])\n .describe('Sort order direction');\nexport type SortDirection = z.infer;\n\n/** Reusable sort item — field + direction pair used across views, data sources, filters */\nexport const SortItemSchema = z.object({\n field: z.string().describe('Field name to sort by'),\n order: SortDirectionEnum.describe('Sort direction'),\n}).describe('Sort field and direction pair');\nexport type SortItem = z.infer;\n\n/** CRUD mutation events used across hook, validation, object CDC */\nexport const MutationEventEnum = z.enum([\n 'insert', 'update', 'delete', 'upsert',\n]).describe('Data mutation event types');\nexport type MutationEvent = z.infer;\n\n/** Database isolation levels — unified format */\nexport const IsolationLevelEnum = z.enum([\n 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable', 'snapshot',\n]).describe('Transaction isolation levels (snake_case standard)');\nexport type IsolationLevel = z.infer;\n\n/** Cache eviction strategies */\nexport const CacheStrategyEnum = z.enum(['lru', 'lfu', 'ttl', 'fifo'])\n .describe('Cache eviction strategy');\nexport type CacheStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from './identifiers.zod';\n\n// ============================================================================\n// Shared Metadata Types\n// ============================================================================\n\n/** Supported metadata file formats */\nexport const MetadataFormatSchema = z.enum(['yaml', 'json', 'typescript', 'javascript'])\n .describe('Metadata file format');\nexport type MetadataFormat = z.infer;\n\n/** Base metadata record fields shared across kernel and system layers */\nexport const BaseMetadataRecordSchema = z.object({\n id: z.string().describe('Unique metadata record identifier'),\n type: z.string().describe('Metadata type (e.g. \"object\", \"view\", \"flow\")'),\n name: SnakeCaseIdentifierSchema.describe('Machine name (snake_case)'),\n format: MetadataFormatSchema.optional().describe('Source file format'),\n}).describe('Base metadata record fields shared across kernel and system');\nexport type BaseMetadataRecord = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema, SystemIdentifierSchema } from './identifiers.zod';\n\n/**\n * Branded Types for ObjectStack Identifiers\n *\n * Branded types provide compile-time safety by preventing accidental mixing\n * of different identifier kinds. For example, you cannot pass an ObjectName\n * where a FieldName is expected, even though both are strings at runtime.\n *\n * @example\n * ```ts\n * import { ObjectNameSchema, FieldNameSchema } from '@objectstack/spec';\n *\n * const objName = ObjectNameSchema.parse('project_task'); // ObjectName\n * const fieldName = FieldNameSchema.parse('task_name'); // FieldName\n *\n * // TypeScript will catch this at compile time:\n * // const fn: FieldName = objName; // Error!\n * ```\n */\n\n/**\n * ObjectName — Branded type for business object names.\n *\n * Must be snake_case (no dots). Used for table/collection names.\n *\n * @example 'project_task', 'crm_account', 'user_profile'\n */\nexport const ObjectNameSchema = SnakeCaseIdentifierSchema\n .brand<'ObjectName'>()\n .describe('Branded object name (snake_case, no dots)');\n\nexport type ObjectName = z.infer;\n\n/**\n * FieldName — Branded type for field (column) names.\n *\n * Must be snake_case (no dots). Used for column/property names within objects.\n *\n * @example 'first_name', 'created_at', 'total_amount'\n */\nexport const FieldNameSchema = SnakeCaseIdentifierSchema\n .brand<'FieldName'>()\n .describe('Branded field name (snake_case, no dots)');\n\nexport type FieldName = z.infer;\n\n/**\n * ViewName — Branded type for view identifiers.\n *\n * Must be a valid system identifier (lowercase, may contain dots for namespacing).\n *\n * @example 'all_tasks', 'my_open_deals', 'contact.recent'\n */\nexport const ViewNameSchema = SystemIdentifierSchema\n .brand<'ViewName'>()\n .describe('Branded view name (system identifier)');\n\nexport type ViewName = z.infer;\n\n/**\n * AppName — Branded type for application identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'crm', 'helpdesk', 'project_management'\n */\nexport const AppNameSchema = SystemIdentifierSchema\n .brand<'AppName'>()\n .describe('Branded app name (system identifier)');\n\nexport type AppName = z.infer;\n\n/**\n * FlowName — Branded type for flow identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'approval_flow', 'onboarding_wizard', 'lead_qualification'\n */\nexport const FlowNameSchema = SystemIdentifierSchema\n .brand<'FlowName'>()\n .describe('Branded flow name (system identifier)');\n\nexport type FlowName = z.infer;\n\n/**\n * RoleName — Branded type for role identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'admin', 'sales_manager', 'read_only'\n */\nexport const RoleNameSchema = SystemIdentifierSchema\n .brand<'RoleName'>()\n .describe('Branded role name (system identifier)');\n\nexport type RoleName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { FieldType } from '../data/field.zod';\n\n/**\n * \"Did you mean?\" Suggestion Utilities\n *\n * Provides fuzzy matching for common ObjectStack identifiers.\n * Used by the custom error map to suggest corrections for typos.\n *\n * @example\n * ```ts\n * suggestFieldType('text_area'); // ['textarea']\n * suggestFieldType('String'); // ['text']\n * suggestFieldType('int'); // ['number']\n * ```\n */\n\n/**\n * Compute Levenshtein edit distance between two strings.\n * Uses space-optimized two-row approach (O(min(m,n)) space).\n */\nexport function levenshteinDistance(a: string, b: string): number {\n const la = a.length;\n const lb = b.length;\n\n if (la === 0) return lb;\n if (lb === 0) return la;\n\n // Use only two rows for space efficiency\n let prev = new Array(lb + 1);\n let curr = new Array(lb + 1);\n\n for (let j = 0; j <= lb; j++) {\n prev[j] = j;\n }\n\n for (let i = 1; i <= la; i++) {\n curr[0] = i;\n for (let j = 1; j <= lb; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n prev[j] + 1, // deletion\n curr[j - 1] + 1, // insertion\n prev[j - 1] + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n\n return prev[lb];\n}\n\n/**\n * Find the closest matches from a list of candidates.\n *\n * @param input - The user-provided (possibly invalid) value\n * @param candidates - Array of valid values to compare against\n * @param maxDistance - Maximum edit distance to consider (default: 3)\n * @param maxResults - Maximum number of suggestions to return (default: 3)\n * @returns Array of suggested values, sorted by similarity\n */\nexport function findClosestMatches(\n input: string,\n candidates: readonly string[],\n maxDistance = 3,\n maxResults = 3,\n): string[] {\n const normalized = input.toLowerCase().replace(/[-\\s]/g, '_');\n\n const scored = candidates\n .map((candidate) => ({\n value: candidate,\n distance: levenshteinDistance(normalized, candidate),\n }))\n .filter((s) => s.distance <= maxDistance && s.distance > 0)\n .sort((a, b) => a.distance - b.distance);\n\n return scored.slice(0, maxResults).map((s) => s.value);\n}\n\n/**\n * Well-known aliases that map common typos / alternative names to valid FieldTypes.\n */\nconst FIELD_TYPE_ALIASES: Record = {\n // Common alternative names\n string: 'text',\n str: 'text',\n varchar: 'text',\n char: 'text',\n int: 'number',\n integer: 'number',\n float: 'number',\n double: 'number',\n decimal: 'number',\n numeric: 'number',\n bool: 'boolean',\n checkbox: 'boolean',\n check: 'boolean',\n date_time: 'datetime',\n timestamp: 'datetime',\n // Common typos\n text_area: 'textarea',\n textarea_: 'textarea',\n textfield: 'text',\n dropdown: 'select',\n picklist: 'select',\n enum: 'select',\n multi_select: 'multiselect',\n multiselect_: 'multiselect',\n reference: 'lookup',\n ref: 'lookup',\n foreign_key: 'lookup',\n fk: 'lookup',\n relation: 'lookup',\n master: 'master_detail',\n richtext_: 'richtext',\n rich_text: 'richtext',\n upload: 'file',\n attachment: 'file',\n photo: 'image',\n picture: 'image',\n img: 'image',\n percent_: 'percent',\n percentage: 'percent',\n money: 'currency',\n price: 'currency',\n auto_number: 'autonumber',\n auto_increment: 'autonumber',\n sequence: 'autonumber',\n markdown_: 'markdown',\n md: 'markdown',\n barcode: 'qrcode',\n tag: 'tags',\n star: 'rating',\n stars: 'rating',\n geo: 'location',\n gps: 'location',\n coordinates: 'location',\n embed: 'vector',\n embedding: 'vector',\n embeddings: 'vector',\n};\n\n/**\n * Suggest valid FieldType values for an invalid input.\n *\n * First checks known aliases, then falls back to fuzzy matching.\n *\n * @param input - Invalid field type string\n * @returns Array of suggested valid FieldType values\n *\n * @example\n * ```ts\n * suggestFieldType('text_area'); // ['textarea']\n * suggestFieldType('String'); // ['text']\n * suggestFieldType('int'); // ['number']\n * suggestFieldType('dropdown'); // ['select']\n * ```\n */\nexport function suggestFieldType(input: string): string[] {\n const normalized = input.toLowerCase().replace(/[-\\s]/g, '_');\n\n // Check alias map first\n const alias = FIELD_TYPE_ALIASES[normalized];\n if (alias) {\n return [alias];\n }\n\n // Fall back to fuzzy matching\n return findClosestMatches(normalized, FieldType.options);\n}\n\n/**\n * Format a \"Did you mean?\" message for display.\n *\n * @param suggestions - Array of suggested values\n * @returns Formatted string or empty string if no suggestions\n */\nexport function formatSuggestion(suggestions: string[]): string {\n if (suggestions.length === 0) return '';\n if (suggestions.length === 1) return `Did you mean '${suggestions[0]}'?`;\n return `Did you mean one of: ${suggestions.map((s) => `'${s}'`).join(', ')}?`;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { suggestFieldType, formatSuggestion, findClosestMatches } from './suggestions.zod';\nimport { FieldType } from '../data/field.zod';\n\n/**\n * Zod v4 raw issue type used by the error map.\n */\nexport type ObjectStackRawIssue = z.core.$ZodRawIssue;\n\n/**\n * ObjectStack Custom Zod Error Map\n *\n * Provides contextual, actionable error messages for ObjectStack schema validation.\n * Instead of generic Zod messages like \"Invalid option\", this error map returns\n * messages that explain the ObjectStack context and suggest fixes.\n *\n * In Zod v4, the error map is a function `(issue) => { message: string } | string | null`.\n * Pass it via the `error` option on `.safeParse()` / `.parse()`.\n *\n * @example\n * ```ts\n * import { objectStackErrorMap } from '@objectstack/spec';\n *\n * // Per-parse usage\n * SomeSchema.safeParse(data, { error: objectStackErrorMap });\n * ```\n */\nexport const objectStackErrorMap = (issue: ObjectStackRawIssue): { message: string } | null => {\n // --- Invalid value (enum) with suggestions ---\n if (issue.code === 'invalid_value') {\n const values = issue.values as unknown[];\n const input = issue.input;\n const received = String(input ?? '');\n const options = values.map(String);\n\n // Check if this looks like a FieldType enum\n const fieldTypeOptions = FieldType.options as readonly string[];\n const isFieldTypeEnum = options.length > 10 &&\n fieldTypeOptions.every((ft) => options.includes(ft));\n\n if (isFieldTypeEnum) {\n const suggestions = suggestFieldType(received);\n const suggestion = formatSuggestion(suggestions);\n const base = `Invalid field type '${received}'.`;\n return {\n message: suggestion ? `${base} ${suggestion}` : `${base} Valid types: ${options.slice(0, 10).join(', ')}...`,\n };\n }\n\n // Generic enum suggestion\n const suggestions = findClosestMatches(received, options);\n const suggestion = formatSuggestion(suggestions);\n const base = `Invalid value '${received}'.`;\n return {\n message: suggestion\n ? `${base} ${suggestion}`\n : `${base} Expected one of: ${options.join(', ')}.`,\n };\n }\n\n // --- String/array/number size validation ---\n if (issue.code === 'too_small') {\n const origin = issue.origin as string;\n const minimum = issue.minimum as number;\n if (origin === 'string') {\n return {\n message: `Must be at least ${minimum} character${minimum === 1 ? '' : 's'} long.`,\n };\n }\n }\n\n if (issue.code === 'too_big') {\n const origin = issue.origin as string;\n const maximum = issue.maximum as number;\n if (origin === 'string') {\n return {\n message: `Must be at most ${maximum} character${maximum === 1 ? '' : 's'} long.`,\n };\n }\n }\n\n // --- String format validation (regex) ---\n if (issue.code === 'invalid_format') {\n const format = issue.format as string;\n const input = issue.input as string | undefined;\n if (format === 'regex' && input) {\n const pathArr = issue.path as (string | number)[] | undefined;\n const pathStr = pathArr?.join('.') ?? '';\n if (pathStr.endsWith('name') || pathStr === 'name') {\n return {\n message: `Invalid identifier '${input}'. Must be lowercase snake_case (e.g., 'my_object', 'task_name'). No uppercase, spaces, or hyphens allowed.`,\n };\n }\n }\n }\n\n // --- Missing required / type mismatch ---\n if (issue.code === 'invalid_type') {\n const expected = issue.expected as string;\n const input = issue.input;\n if (input === undefined) {\n const pathArr = issue.path as (string | number)[] | undefined;\n const field = pathArr?.[pathArr.length - 1] ?? '';\n return {\n message: `Required property '${field}' is missing.`,\n };\n }\n const receivedType = input === null ? 'null' : typeof input;\n return {\n message: `Expected ${expected} but received ${receivedType}.`,\n };\n }\n\n // --- Unrecognized keys ---\n if (issue.code === 'unrecognized_keys') {\n const keys = issue.keys as string[];\n const keyStr = keys.join(', ');\n return {\n message: `Unrecognized key${keys.length > 1 ? 's' : ''}: ${keyStr}. Check for typos in property names.`,\n };\n }\n\n // Fallback to Zod default\n return null;\n};\n\n/**\n * Zod Issue interface (subset needed for formatting).\n */\ninterface ZodIssueMinimal {\n path: PropertyKey[];\n message: string;\n code?: string;\n}\n\n/**\n * Format a single Zod issue into a human-readable line.\n *\n * @param issue - A single Zod issue\n * @returns Formatted string with path and message\n */\nexport function formatZodIssue(issue: ZodIssueMinimal): string {\n const path = issue.path.length > 0\n ? issue.path.join('.')\n : '(root)';\n return ` ✗ ${path}: ${issue.message}`;\n}\n\n/**\n * Pretty-print Zod validation errors for CLI output.\n *\n * Formats a ZodError into a readable block suitable for terminal display.\n * Groups errors by path depth and includes a summary count.\n *\n * @param error - A ZodError to format\n * @param label - Optional label for the error block (e.g., 'Stack validation failed')\n * @returns Formatted multi-line string\n *\n * @example\n * ```ts\n * import { formatZodError, ObjectStackDefinitionSchema } from '@objectstack/spec';\n *\n * const result = ObjectStackDefinitionSchema.safeParse(data);\n * if (!result.success) {\n * console.error(formatZodError(result.error, 'Stack validation failed'));\n * }\n * ```\n *\n * Output:\n * ```\n * Stack validation failed (3 issues):\n *\n * ✗ manifest.name: Required property 'name' is missing.\n * ✗ objects[0].fields.status.type: Invalid field type 'dropdown'. Did you mean 'select'?\n * ✗ views[0].object: Invalid identifier 'MyTasks'. Must be lowercase snake_case.\n * ```\n */\nexport function formatZodError(error: z.ZodError, label?: string): string {\n const count = error.issues.length;\n const header = label\n ? `${label} (${count} issue${count === 1 ? '' : 's'}):`\n : `Validation failed (${count} issue${count === 1 ? '' : 's'}):`;\n\n const lines = error.issues.map(formatZodIssue);\n\n return `${header}\\n\\n${lines.join('\\n')}`;\n}\n\n/**\n * Parse with the ObjectStack error map and return formatted errors.\n *\n * A convenience function that combines parsing with the custom error map\n * and pretty-print formatting. Returns a discriminated union result.\n *\n * @param schema - Any Zod schema to parse with\n * @param data - Data to validate\n * @param label - Optional label for error formatting\n * @returns Object with `success`, `data`, and optional `formatted` error string\n *\n * @example\n * ```ts\n * const result = safeParsePretty(ObjectStackDefinitionSchema, config, 'objectstack.config.ts');\n * if (!result.success) {\n * console.error(result.formatted);\n * process.exit(1);\n * }\n * ```\n */\nexport function safeParsePretty(\n schema: T,\n data: unknown,\n label?: string,\n): { success: true; data: z.infer } | { success: false; error: z.ZodError; formatted: string } {\n const result = schema.safeParse(data, { error: objectStackErrorMap });\n if (result.success) {\n return { success: true, data: result.data };\n }\n return {\n success: false,\n error: result.error,\n formatted: formatZodError(result.error, label),\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Metadata Collection Utilities\n * \n * Provides support for defining metadata collections in either array or map (Record) format.\n * Map format automatically injects the key as the `name` field, following the same pattern\n * used by `fields` in ObjectSchema (which already uses `z.record(key, FieldSchema)`).\n * \n * ## Usage\n * \n * Both formats are accepted and normalized to arrays:\n * \n * ```ts\n * // Array format (traditional)\n * defineStack({\n * objects: [\n * { name: 'account', fields: { ... } },\n * { name: 'contact', fields: { ... } },\n * ]\n * });\n * \n * // Map format (key becomes `name`)\n * defineStack({\n * objects: {\n * account: { fields: { ... } },\n * contact: { fields: { ... } },\n * }\n * });\n * ```\n * \n * @module\n */\n\n/**\n * Input type for metadata collections: accepts either an array or a named map.\n * When using map format, the key is injected as the `name` field of each item.\n * \n * @typeParam T - The metadata item type (e.g., `ObjectSchema`, `AppSchema`)\n * \n * @example\n * ```ts\n * // Array format — name is required in each item\n * const apps: MetadataCollectionInput = [\n * { name: 'sales', label: 'Sales' },\n * { name: 'service', label: 'Service' },\n * ];\n * \n * // Map format — key serves as name, so name is optional in value\n * const apps: MetadataCollectionInput = {\n * sales: { label: 'Sales' },\n * service: { label: 'Service' },\n * };\n * ```\n */\nexport type MetadataCollectionInput =\n | T[]\n | Record & { name?: string }>;\n\n/**\n * List of metadata fields in ObjectStackDefinitionSchema that support map format.\n * These are fields where each item has a `name` field that can be inferred from the map key.\n * \n * Excluded fields:\n * - `views` — ViewSchema has no `name` field (it's a container with `list`/`form`)\n * - `objectExtensions` — uses `extend` as its identifier, not `name`\n * - `data` — DatasetSchema uses `object` as its identifier\n * - `translations` — TranslationBundleSchema is a record, not a named object\n * - `plugins` / `devPlugins` — not named metadata schemas\n */\nexport const MAP_SUPPORTED_FIELDS = [\n 'objects',\n 'apps',\n 'pages',\n 'dashboards',\n 'reports',\n 'actions',\n 'themes',\n 'workflows',\n 'approvals',\n 'flows',\n 'roles',\n 'permissions',\n 'sharingRules',\n 'policies',\n 'apis',\n 'webhooks',\n 'agents',\n 'ragPipelines',\n 'hooks',\n 'mappings',\n 'analyticsCubes',\n 'connectors',\n 'datasources',\n] as const;\n\nexport type MapSupportedField = (typeof MAP_SUPPORTED_FIELDS)[number];\n\n/**\n * Mapping from plural manifest field names to singular metadata type names.\n *\n * Manifest / `defineStack()` uses plural property names because they are\n * collection fields (e.g. `objects: [...]`, `apps: [...]`). The metadata\n * registry and `MetadataTypeSchema` use singular names as the canonical form.\n *\n * Use this mapping at the boundary where manifest fields are fed into the\n * metadata registry to ensure a consistent singular naming convention.\n */\nexport const PLURAL_TO_SINGULAR: Record = {\n objects: 'object',\n apps: 'app',\n pages: 'page',\n dashboards: 'dashboard',\n reports: 'report',\n actions: 'action',\n themes: 'theme',\n workflows: 'workflow',\n approvals: 'approval',\n flows: 'flow',\n roles: 'role',\n permissions: 'permission',\n profiles: 'profile',\n sharingRules: 'sharingRule',\n policies: 'policy',\n apis: 'api',\n webhooks: 'webhook',\n agents: 'agent',\n ragPipelines: 'ragPipeline',\n hooks: 'hook',\n mappings: 'mapping',\n analyticsCubes: 'analyticsCube',\n connectors: 'connector',\n datasources: 'datasource',\n views: 'view',\n};\n\n/** Reverse mapping: singular metadata type → plural manifest field name. */\nexport const SINGULAR_TO_PLURAL: Record = Object.fromEntries(\n Object.entries(PLURAL_TO_SINGULAR).map(([plural, singular]) => [singular, plural]),\n);\n\n/** Convert a plural manifest field name to its singular metadata type name. Returns the input unchanged if no mapping exists. */\nexport function pluralToSingular(key: string): string {\n return PLURAL_TO_SINGULAR[key] ?? key;\n}\n\n/** Convert a singular metadata type name to its plural manifest field name. Returns the input unchanged if no mapping exists. */\nexport function singularToPlural(key: string): string {\n return SINGULAR_TO_PLURAL[key] ?? key;\n}\n\n\n/**\n * Normalize a single metadata collection value from map format to array format.\n * If the input is already an array (or nullish), it is returned unchanged.\n * If the input is a plain object (map), it is converted to an array where\n * each key is injected as the `name` field of the corresponding item.\n * \n * **Precedence:** If an item already has a `name` property, it is preserved\n * (the map key is only used as a fallback).\n * \n * @param value - The raw input value (array, map, or nullish)\n * @param keyField - The field name to inject the key into (default: `'name'`)\n * @returns The normalized array, or the original value if already an array/nullish\n * \n * @example\n * ```ts\n * // Map input\n * normalizeMetadataCollection({\n * account: { fields: { name: { type: 'text' } } },\n * contact: { fields: { email: { type: 'email' } } },\n * });\n * // → [\n * // { name: 'account', fields: { name: { type: 'text' } } },\n * // { name: 'contact', fields: { email: { type: 'email' } } },\n * // ]\n * \n * // Array input (pass-through)\n * normalizeMetadataCollection([{ name: 'account', fields: {} }]);\n * // → [{ name: 'account', fields: {} }]\n * ```\n */\nexport function normalizeMetadataCollection(value: unknown, keyField = 'name'): unknown {\n // Nullish or already an array — pass through\n if (value == null || Array.isArray(value)) return value;\n\n // Plain object — treat as map and convert to array\n if (typeof value === 'object') {\n return Object.entries(value as Record).map(([key, item]) => {\n if (item && typeof item === 'object' && !Array.isArray(item)) {\n const obj = item as Record;\n // Only inject key if the item doesn't already have the field set\n if (!(keyField in obj) || obj[keyField] === undefined) {\n return { ...obj, [keyField]: key };\n }\n return obj;\n }\n // Non-object values (shouldn't happen, but let Zod handle the error)\n return item;\n });\n }\n\n // Other types — return as-is and let Zod validation handle the error\n return value;\n}\n\n/**\n * Normalize all metadata collections in a stack definition input.\n * Converts any map-formatted collections to arrays with key→name injection.\n * \n * This function is applied to the raw input before Zod validation,\n * ensuring the canonical internal format is always arrays.\n * \n * @param input - The raw stack definition input\n * @returns A new object with all map collections normalized to arrays\n */\nexport function normalizeStackInput>(input: T): T {\n const result = { ...input };\n for (const field of MAP_SUPPORTED_FIELDS) {\n if (field in result) {\n (result as Record)[field] = normalizeMetadataCollection(result[field]);\n }\n }\n return result;\n}\n\n/**\n * Mapping of legacy / alternative field names to their canonical names\n * in `ObjectStackDefinitionSchema`.\n *\n * Plugins may use legacy names (e.g., `triggers` instead of `hooks`).\n * This map lets `normalizePluginMetadata()` rewrite them automatically.\n */\nexport const METADATA_ALIASES: Record = {\n triggers: 'hooks',\n};\n\n/**\n * Normalize plugin metadata so it matches the canonical format expected by the runtime.\n *\n * This handles two issues that commonly arise when loading third-party plugin metadata:\n *\n * 1. **Map → Array conversion** — plugins often define metadata as maps\n * (e.g., `actions: { convert_lead: { ... } }`), but the runtime expects arrays.\n * Every key listed in {@link MAP_SUPPORTED_FIELDS} is normalized via\n * {@link normalizeMetadataCollection}.\n *\n * 2. **Field aliasing** — plugins may use legacy or alternative field names\n * (e.g., `triggers` instead of `hooks`). {@link METADATA_ALIASES} maps them\n * to their canonical counterparts.\n *\n * 3. **Recursive normalization** — if the plugin itself contains nested `plugins`,\n * each nested plugin is normalized recursively.\n *\n * @param metadata - Raw plugin metadata object\n * @returns A new object with all collections normalized to arrays, aliases resolved,\n * and nested plugins recursively normalized\n *\n * @example\n * ```ts\n * const raw = {\n * actions: { lead_convert: { type: 'custom', label: 'Convert' } },\n * triggers: { lead_scoring: { object: 'lead', event: 'afterInsert' } },\n * };\n * const normalized = normalizePluginMetadata(raw);\n * // normalized.actions → [{ name: 'lead_convert', type: 'custom', label: 'Convert' }]\n * // normalized.hooks → [{ name: 'lead_scoring', object: 'lead', event: 'afterInsert' }]\n * // normalized.triggers → removed (merged into hooks)\n * ```\n */\nexport function normalizePluginMetadata>(metadata: T): T {\n const result = { ...metadata };\n\n // 1. Resolve aliases (e.g. triggers → hooks), merging with any existing canonical values\n for (const [alias, canonical] of Object.entries(METADATA_ALIASES)) {\n if (alias in result) {\n const aliasValue = normalizeMetadataCollection(result[alias]);\n const canonicalValue = normalizeMetadataCollection(result[canonical]);\n\n // Merge: canonical array wins; alias values are appended\n if (Array.isArray(aliasValue)) {\n (result as Record)[canonical] = Array.isArray(canonicalValue)\n ? [...canonicalValue, ...aliasValue]\n : aliasValue;\n }\n\n delete (result as Record)[alias];\n }\n }\n\n // 2. Normalize map-formatted collections → arrays\n for (const field of MAP_SUPPORTED_FIELDS) {\n if (field in result) {\n (result as Record)[field] = normalizeMetadataCollection(result[field]);\n }\n }\n\n // 3. Recursively normalize nested plugins\n if (Array.isArray(result.plugins)) {\n (result as Record).plugins = result.plugins.map((p: unknown) => {\n if (p && typeof p === 'object' && !Array.isArray(p)) {\n return normalizePluginMetadata(p as Record);\n }\n return p;\n });\n }\n\n return result;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ServiceObject, ObjectSchema, ObjectOwnership } from '@objectstack/spec/data';\nimport { ObjectStackManifest, ManifestSchema, InstalledPackage, InstalledPackageSchema } from '@objectstack/spec/kernel';\nimport { AppSchema } from '@objectstack/spec/ui';\n\n/**\n * Reserved namespaces that do not get FQN prefix applied.\n * Objects in these namespaces keep their short names (e.g., \"user\" not \"base__user\").\n */\nexport const RESERVED_NAMESPACES = new Set(['base', 'system']);\n\n/**\n * Default priorities for ownership types.\n */\nexport const DEFAULT_OWNER_PRIORITY = 100;\nexport const DEFAULT_EXTENDER_PRIORITY = 200;\n\n/**\n * Contributor Record\n * Tracks how a package contributes to an object (own or extend).\n */\nexport interface ObjectContributor {\n packageId: string;\n namespace: string;\n ownership: ObjectOwnership;\n priority: number;\n definition: ServiceObject;\n}\n\n/**\n * Compute Fully Qualified Name (FQN) for an object.\n * \n * @param namespace - The package namespace (e.g., \"crm\", \"todo\")\n * @param shortName - The object's short name (e.g., \"task\", \"account\")\n * @returns FQN string (e.g., \"crm__task\") or just shortName for reserved namespaces\n * \n * @example\n * computeFQN('crm', 'account') // => 'crm__account'\n * computeFQN('base', 'user') // => 'user' (reserved, no prefix)\n * computeFQN(undefined, 'task') // => 'task' (legacy, no namespace)\n */\nexport function computeFQN(namespace: string | undefined, shortName: string): string {\n if (!namespace || RESERVED_NAMESPACES.has(namespace)) {\n return shortName;\n }\n return `${namespace}__${shortName}`;\n}\n\n/**\n * Parse FQN back to namespace and short name.\n * \n * @param fqn - Fully qualified name (e.g., \"crm__account\" or \"user\")\n * @returns { namespace, shortName } - namespace is undefined for unprefixed names\n */\nexport function parseFQN(fqn: string): { namespace: string | undefined; shortName: string } {\n const idx = fqn.indexOf('__');\n if (idx === -1) {\n return { namespace: undefined, shortName: fqn };\n }\n return {\n namespace: fqn.slice(0, idx),\n shortName: fqn.slice(idx + 2),\n };\n}\n\n/**\n * Deep merge two ServiceObject definitions.\n * Fields are merged additively. Other props: later value wins.\n */\nfunction mergeObjectDefinitions(base: ServiceObject, extension: Partial): ServiceObject {\n const merged = { ...base };\n\n // Merge fields additively\n if (extension.fields) {\n merged.fields = { ...base.fields, ...extension.fields };\n }\n\n // Merge validations additively\n if (extension.validations) {\n merged.validations = [...(base.validations || []), ...extension.validations];\n }\n\n // Merge indexes additively\n if (extension.indexes) {\n merged.indexes = [...(base.indexes || []), ...extension.indexes];\n }\n\n // Override scalar props (last writer wins)\n if (extension.label !== undefined) merged.label = extension.label;\n if (extension.pluralLabel !== undefined) merged.pluralLabel = extension.pluralLabel;\n if (extension.description !== undefined) merged.description = extension.description;\n\n return merged;\n}\n\n/**\n * Global Schema Registry\n * Unified storage for all metadata types (Objects, Apps, Flows, Layouts, etc.)\n * \n * ## Namespace & Ownership Model\n * \n * Objects use a namespace-based FQN system:\n * - `namespace`: Short identifier from package manifest (e.g., \"crm\", \"todo\")\n * - `FQN`: `{namespace}__{short_name}` (e.g., \"crm__account\")\n * - Reserved namespaces (`base`, `system`) don't get prefixed\n * \n * Ownership modes:\n * - `own`: One package owns the object (creates the table, defines base schema)\n * - `extend`: Multiple packages can extend an object (add fields, merge by priority)\n * \n * ## Package vs App Distinction\n * - **Package**: The unit of installation, stored under type 'package'.\n * Each InstalledPackage wraps a ManifestSchema with lifecycle state.\n * - **App**: A UI navigation shell (AppSchema), registered under type 'apps'.\n * Apps are extracted from packages during registration.\n * - A package may contain 0, 1, or many apps.\n */\nexport type RegistryLogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\nexport class SchemaRegistry {\n // ==========================================\n // Logging control\n // ==========================================\n\n /** Controls verbosity of registry console messages. Default: 'info'. */\n private static _logLevel: RegistryLogLevel = 'info';\n\n static get logLevel(): RegistryLogLevel { return this._logLevel; }\n static set logLevel(level: RegistryLogLevel) { this._logLevel = level; }\n\n private static log(msg: string): void {\n if (this._logLevel === 'silent' || this._logLevel === 'error' || this._logLevel === 'warn') return;\n console.log(msg);\n }\n\n // ==========================================\n // Object-specific storage (Ownership Model)\n // ==========================================\n \n /** FQN → Contributor[] (all packages that own/extend this object) */\n private static objectContributors = new Map();\n \n /** FQN → Merged ServiceObject (cached, invalidated on changes) */\n private static mergedObjectCache = new Map();\n \n /** Namespace → Set (multiple packages can share a namespace) */\n private static namespaceRegistry = new Map>();\n\n // ==========================================\n // Generic metadata storage (non-object types)\n // ==========================================\n \n /** Type → Name/ID → MetadataItem */\n private static metadata = new Map>();\n\n // ==========================================\n // Namespace Management\n // ==========================================\n\n /**\n * Register a namespace for a package.\n * Multiple packages can share the same namespace (e.g. 'sys').\n */\n static registerNamespace(namespace: string, packageId: string): void {\n if (!namespace) return;\n\n let owners = this.namespaceRegistry.get(namespace);\n if (!owners) {\n owners = new Set();\n this.namespaceRegistry.set(namespace, owners);\n }\n owners.add(packageId);\n this.log(`[Registry] Registered namespace: ${namespace} → ${packageId}`);\n }\n\n /**\n * Unregister a namespace when a package is uninstalled.\n */\n static unregisterNamespace(namespace: string, packageId: string): void {\n const owners = this.namespaceRegistry.get(namespace);\n if (owners) {\n owners.delete(packageId);\n if (owners.size === 0) {\n this.namespaceRegistry.delete(namespace);\n }\n this.log(`[Registry] Unregistered namespace: ${namespace} ← ${packageId}`);\n }\n }\n\n /**\n * Get the packages that use a namespace.\n */\n static getNamespaceOwner(namespace: string): string | undefined {\n const owners = this.namespaceRegistry.get(namespace);\n if (!owners || owners.size === 0) return undefined;\n // Return the first registered package for backwards compatibility\n return owners.values().next().value;\n }\n\n /**\n * Get all packages that share a namespace.\n */\n static getNamespaceOwners(namespace: string): string[] {\n const owners = this.namespaceRegistry.get(namespace);\n return owners ? Array.from(owners) : [];\n }\n\n // ==========================================\n // Object Registration (Ownership Model)\n // ==========================================\n\n /**\n * Register an object with ownership semantics.\n * \n * @param schema - The object definition\n * @param packageId - The owning package ID\n * @param namespace - The package namespace (for FQN computation)\n * @param ownership - 'own' (single owner) or 'extend' (additive merge)\n * @param priority - Merge priority (lower applied first, higher wins on conflict)\n * \n * @throws Error if trying to 'own' an object that already has an owner\n */\n static registerObject(\n schema: ServiceObject,\n packageId: string,\n namespace?: string,\n ownership: ObjectOwnership = 'own',\n priority: number = ownership === 'own' ? DEFAULT_OWNER_PRIORITY : DEFAULT_EXTENDER_PRIORITY\n ): string {\n const shortName = schema.name;\n const fqn = computeFQN(namespace, shortName);\n\n // Ensure namespace is registered\n if (namespace) {\n this.registerNamespace(namespace, packageId);\n }\n\n // Get or create contributor list\n let contributors = this.objectContributors.get(fqn);\n if (!contributors) {\n contributors = [];\n this.objectContributors.set(fqn, contributors);\n }\n\n // Validate ownership rules\n if (ownership === 'own') {\n const existingOwner = contributors.find(c => c.ownership === 'own');\n if (existingOwner && existingOwner.packageId !== packageId) {\n throw new Error(\n `Object \"${fqn}\" is already owned by package \"${existingOwner.packageId}\". ` +\n `Package \"${packageId}\" cannot claim ownership. Use 'extend' to add fields.`\n );\n }\n // Remove existing owner contribution from same package (re-registration)\n const idx = contributors.findIndex(c => c.packageId === packageId && c.ownership === 'own');\n if (idx !== -1) {\n contributors.splice(idx, 1);\n console.warn(`[Registry] Re-registering owned object: ${fqn} from ${packageId}`);\n }\n } else {\n // extend mode: remove existing extension from same package\n const idx = contributors.findIndex(c => c.packageId === packageId && c.ownership === 'extend');\n if (idx !== -1) {\n contributors.splice(idx, 1);\n }\n }\n\n // Add new contributor\n const contributor: ObjectContributor = {\n packageId,\n namespace: namespace || '',\n ownership,\n priority,\n definition: { ...schema, name: fqn }, // Store with FQN as name\n };\n contributors.push(contributor);\n\n // Sort by priority (ascending: lower priority applied first)\n contributors.sort((a, b) => a.priority - b.priority);\n\n // Invalidate merge cache\n this.mergedObjectCache.delete(fqn);\n\n this.log(`[Registry] Registered object: ${fqn} (${ownership}, priority=${priority}) from ${packageId}`);\n return fqn;\n }\n\n /**\n * Resolve an object by FQN, merging all contributions.\n * Returns the merged object or undefined if not found.\n */\n static resolveObject(fqn: string): ServiceObject | undefined {\n // Check cache first\n const cached = this.mergedObjectCache.get(fqn);\n if (cached) return cached;\n\n const contributors = this.objectContributors.get(fqn);\n if (!contributors || contributors.length === 0) {\n return undefined;\n }\n\n // Find owner (must exist for a valid object)\n const ownerContrib = contributors.find(c => c.ownership === 'own');\n if (!ownerContrib) {\n console.warn(`[Registry] Object \"${fqn}\" has extenders but no owner. Skipping.`);\n return undefined;\n }\n\n // Start with owner's definition\n let merged = { ...ownerContrib.definition };\n\n // Apply extensions in priority order (already sorted)\n for (const contrib of contributors) {\n if (contrib.ownership === 'extend') {\n merged = mergeObjectDefinitions(merged, contrib.definition);\n }\n }\n\n // Cache the result\n this.mergedObjectCache.set(fqn, merged);\n return merged;\n }\n\n /**\n * Get object by name (FQN, short name, or physical table name).\n *\n * Resolution order:\n * 1. Exact FQN match (e.g., 'crm__account')\n * 2. Short name fallback (e.g., 'account' → 'crm__account')\n * 3. Physical table name match (e.g., 'sys_user' → 'sys__user')\n * ObjectSchema.create() auto-derives tableName as {namespace}_{name},\n * which uses a single underscore — different from the FQN double underscore.\n */\n static getObject(name: string): ServiceObject | undefined {\n // Direct FQN lookup\n const direct = this.resolveObject(name);\n if (direct) return direct;\n\n // Fallback: scan for objects ending with the short name\n // This handles legacy code that doesn't use FQN\n for (const fqn of this.objectContributors.keys()) {\n const { shortName } = parseFQN(fqn);\n if (shortName === name) {\n return this.resolveObject(fqn);\n }\n }\n\n // Fallback: match by physical table name (e.g., 'sys_user' → FQN 'sys__user')\n // This bridges the gap between protocol names (SystemObjectName) and FQN.\n for (const fqn of this.objectContributors.keys()) {\n const resolved = this.resolveObject(fqn);\n if (resolved?.tableName === name) {\n return resolved;\n }\n }\n\n return undefined;\n }\n\n /**\n * Get all registered objects (merged).\n * \n * @param packageId - Optional filter: only objects contributed by this package\n */\n static getAllObjects(packageId?: string): ServiceObject[] {\n const results: ServiceObject[] = [];\n\n for (const fqn of this.objectContributors.keys()) {\n // If filtering by package, check if this package contributes\n if (packageId) {\n const contributors = this.objectContributors.get(fqn);\n const hasContribution = contributors?.some(c => c.packageId === packageId);\n if (!hasContribution) continue;\n }\n\n const merged = this.resolveObject(fqn);\n if (merged) {\n // Tag with contributor info for UI\n (merged as any)._packageId = this.getObjectOwner(fqn)?.packageId;\n results.push(merged);\n }\n }\n\n return results;\n }\n\n /**\n * Get all contributors for an object.\n */\n static getObjectContributors(fqn: string): ObjectContributor[] {\n return this.objectContributors.get(fqn) || [];\n }\n\n /**\n * Get the owner contributor for an object.\n */\n static getObjectOwner(fqn: string): ObjectContributor | undefined {\n const contributors = this.objectContributors.get(fqn);\n return contributors?.find(c => c.ownership === 'own');\n }\n\n /**\n * Unregister all objects contributed by a package.\n * \n * @throws Error if trying to uninstall an owner that has extenders\n */\n static unregisterObjectsByPackage(packageId: string, force: boolean = false): void {\n for (const [fqn, contributors] of this.objectContributors.entries()) {\n // Find this package's contributions\n const packageContribs = contributors.filter(c => c.packageId === packageId);\n \n for (const contrib of packageContribs) {\n if (contrib.ownership === 'own' && !force) {\n // Check if there are extenders from other packages\n const otherExtenders = contributors.filter(\n c => c.packageId !== packageId && c.ownership === 'extend'\n );\n if (otherExtenders.length > 0) {\n throw new Error(\n `Cannot uninstall package \"${packageId}\": object \"${fqn}\" is extended by ` +\n `${otherExtenders.map(c => c.packageId).join(', ')}. Uninstall extenders first.`\n );\n }\n }\n\n // Remove contribution\n const idx = contributors.indexOf(contrib);\n if (idx !== -1) {\n contributors.splice(idx, 1);\n this.log(`[Registry] Removed ${contrib.ownership} contribution to ${fqn} from ${packageId}`);\n }\n }\n\n // Clean up empty contributor lists\n if (contributors.length === 0) {\n this.objectContributors.delete(fqn);\n }\n\n // Invalidate cache\n this.mergedObjectCache.delete(fqn);\n }\n }\n\n // ==========================================\n // Generic Metadata (Non-Object Types)\n // ==========================================\n\n /**\n * Universal Register Method for non-object metadata.\n */\n static registerItem(type: string, item: T, keyField: keyof T = 'name' as keyof T, packageId?: string) {\n if (!this.metadata.has(type)) {\n this.metadata.set(type, new Map());\n }\n const collection = this.metadata.get(type)!;\n const baseName = String(item[keyField]);\n \n // Tag item with owning package for scoped queries\n if (packageId) {\n (item as any)._packageId = packageId;\n }\n\n // Validation Hook\n try {\n this.validate(type, item);\n } catch (e: any) {\n console.error(`[Registry] Validation failed for ${type} ${baseName}: ${e.message}`);\n }\n\n // Use composite key (packageId:name) when packageId is provided\n const storageKey = packageId ? `${packageId}:${baseName}` : baseName;\n\n if (collection.has(storageKey)) {\n console.warn(`[Registry] Overwriting ${type}: ${storageKey}`);\n }\n collection.set(storageKey, item);\n this.log(`[Registry] Registered ${type}: ${storageKey}`);\n }\n\n /**\n * Validate Metadata against Spec Zod Schemas\n */\n static validate(type: string, item: any) {\n if (type === 'object') {\n return ObjectSchema.parse(item);\n }\n if (type === 'app') {\n return AppSchema.parse(item);\n }\n if (type === 'package') {\n return InstalledPackageSchema.parse(item);\n }\n if (type === 'plugin') {\n return ManifestSchema.parse(item);\n }\n return true;\n }\n\n /**\n * Universal Unregister Method\n */\n static unregisterItem(type: string, name: string) {\n const collection = this.metadata.get(type);\n if (!collection) {\n console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`);\n return;\n }\n if (collection.has(name)) {\n collection.delete(name);\n this.log(`[Registry] Unregistered ${type}: ${name}`);\n return;\n }\n // Scan composite keys\n for (const key of collection.keys()) {\n if (key.endsWith(`:${name}`)) {\n collection.delete(key);\n this.log(`[Registry] Unregistered ${type}: ${key}`);\n return;\n }\n }\n console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`);\n }\n\n /**\n * Universal Get Method\n */\n static getItem(type: string, name: string): T | undefined {\n // Special handling for 'object' and 'objects' types - use objectContributors\n if (type === 'object' || type === 'objects') {\n return this.getObject(name) as unknown as T | undefined;\n }\n \n const collection = this.metadata.get(type);\n if (!collection) return undefined;\n const direct = collection.get(name);\n if (direct) return direct as T;\n // Scan for composite keys\n for (const [key, item] of collection) {\n if (key.endsWith(`:${name}`)) return item as T;\n }\n return undefined;\n }\n\n /**\n * Universal List Method\n */\n static listItems(type: string, packageId?: string): T[] {\n // Special handling for 'object' and 'objects' types - use objectContributors\n if (type === 'object' || type === 'objects') {\n return this.getAllObjects(packageId) as unknown as T[];\n }\n\n const items = Array.from(this.metadata.get(type)?.values() || []) as T[];\n if (packageId) {\n return items.filter((item: any) => item._packageId === packageId);\n }\n return items;\n }\n\n /**\n * Get all registered metadata types (Kinds)\n */\n static getRegisteredTypes(): string[] {\n const types = Array.from(this.metadata.keys());\n // Always include 'object' even if stored separately\n if (!types.includes('object') && this.objectContributors.size > 0) {\n types.push('object');\n }\n return types;\n }\n\n // ==========================================\n // Package Management\n // ==========================================\n\n static installPackage(manifest: ObjectStackManifest, settings?: Record): InstalledPackage {\n const now = new Date().toISOString();\n const pkg: InstalledPackage = {\n manifest,\n status: 'installed',\n enabled: true,\n installedAt: now,\n updatedAt: now,\n settings,\n };\n \n // Register namespace if present\n if (manifest.namespace) {\n this.registerNamespace(manifest.namespace, manifest.id);\n }\n \n if (!this.metadata.has('package')) {\n this.metadata.set('package', new Map());\n }\n const collection = this.metadata.get('package')!;\n if (collection.has(manifest.id)) {\n console.warn(`[Registry] Overwriting package: ${manifest.id}`);\n }\n collection.set(manifest.id, pkg);\n this.log(`[Registry] Installed package: ${manifest.id} (${manifest.name})`);\n return pkg;\n }\n\n static uninstallPackage(id: string): boolean {\n const pkg = this.getPackage(id);\n if (!pkg) {\n console.warn(`[Registry] Package not found for uninstall: ${id}`);\n return false;\n }\n\n // Unregister namespace\n if (pkg.manifest.namespace) {\n this.unregisterNamespace(pkg.manifest.namespace, id);\n }\n\n // Unregister objects (will throw if extenders exist)\n this.unregisterObjectsByPackage(id);\n\n // Remove package record\n const collection = this.metadata.get('package');\n if (collection) {\n collection.delete(id);\n this.log(`[Registry] Uninstalled package: ${id}`);\n return true;\n }\n return false;\n }\n\n static getPackage(id: string): InstalledPackage | undefined {\n return this.metadata.get('package')?.get(id) as InstalledPackage | undefined;\n }\n\n static getAllPackages(): InstalledPackage[] {\n return this.listItems('package');\n }\n\n static enablePackage(id: string): InstalledPackage | undefined {\n const pkg = this.getPackage(id);\n if (pkg) {\n pkg.enabled = true;\n pkg.status = 'installed';\n pkg.statusChangedAt = new Date().toISOString();\n pkg.updatedAt = new Date().toISOString();\n this.log(`[Registry] Enabled package: ${id}`);\n }\n return pkg;\n }\n\n static disablePackage(id: string): InstalledPackage | undefined {\n const pkg = this.getPackage(id);\n if (pkg) {\n pkg.enabled = false;\n pkg.status = 'disabled';\n pkg.statusChangedAt = new Date().toISOString();\n pkg.updatedAt = new Date().toISOString();\n this.log(`[Registry] Disabled package: ${id}`);\n }\n return pkg;\n }\n\n // ==========================================\n // App Helpers\n // ==========================================\n\n static registerApp(app: any, packageId?: string) {\n this.registerItem('app', app, 'name', packageId);\n }\n\n static getApp(name: string): any {\n return this.getItem('app', name);\n }\n\n static getAllApps(): any[] {\n return this.listItems('app');\n }\n\n // ==========================================\n // Plugin Helpers\n // ==========================================\n\n static registerPlugin(manifest: ObjectStackManifest) {\n this.registerItem('plugin', manifest, 'id');\n }\n\n static getAllPlugins(): ObjectStackManifest[] {\n return this.listItems('plugin');\n }\n\n // ==========================================\n // Kind Helpers\n // ==========================================\n\n static registerKind(kind: { id: string, globs: string[] }) {\n this.registerItem('kind', kind, 'id');\n }\n \n static getAllKinds(): { id: string, globs: string[] }[] {\n return this.listItems('kind');\n }\n\n // ==========================================\n // Reset (for testing)\n // ==========================================\n\n /**\n * Clear all registry state. Use only for testing.\n */\n static reset(): void {\n this.objectContributors.clear();\n this.mergedObjectCache.clear();\n this.namespaceRegistry.clear();\n this.metadata.clear();\n this.log('[Registry] Reset complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectStackProtocol } from '@objectstack/spec/api';\nimport { IDataEngine } from '@objectstack/core';\nimport type {\n BatchUpdateRequest,\n BatchUpdateResponse,\n UpdateManyDataRequest,\n DeleteManyDataRequest\n} from '@objectstack/spec/api';\nimport type { MetadataCacheRequest, MetadataCacheResponse, ServiceInfo, ApiRoutes, WellKnownCapabilities } from '@objectstack/spec/api';\nimport type { IFeedService } from '@objectstack/spec/contracts';\nimport { parseFilterAST, isFilterAST } from '@objectstack/spec/data';\nimport { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared';\n\n// We import SchemaRegistry directly since this class lives in the same package\nimport { SchemaRegistry } from './registry.js';\n\n/**\n * Simple hash function for ETag generation (browser-compatible)\n * Uses a basic hash algorithm instead of crypto.createHash\n */\nfunction simpleHash(str: string): string {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return Math.abs(hash).toString(16);\n}\n\n/**\n * Service Configuration for Discovery\n * Maps service names to their routes and plugin providers\n */\nconst SERVICE_CONFIG: Record = {\n auth: { route: '/api/v1/auth', plugin: 'plugin-auth' },\n automation: { route: '/api/v1/automation', plugin: 'plugin-automation' },\n cache: { route: '/api/v1/cache', plugin: 'plugin-redis' },\n queue: { route: '/api/v1/queue', plugin: 'plugin-bullmq' },\n job: { route: '/api/v1/jobs', plugin: 'job-scheduler' },\n ui: { route: '/api/v1/ui', plugin: 'ui-plugin' },\n workflow: { route: '/api/v1/workflow', plugin: 'plugin-workflow' },\n realtime: { route: '/api/v1/realtime', plugin: 'plugin-realtime' },\n notification: { route: '/api/v1/notifications', plugin: 'plugin-notifications' },\n ai: { route: '/api/v1/ai', plugin: 'plugin-ai' },\n i18n: { route: '/api/v1/i18n', plugin: 'service-i18n' },\n graphql: { route: '/graphql', plugin: 'plugin-graphql' }, // GraphQL uses /graphql by convention (not versioned REST)\n 'file-storage': { route: '/api/v1/storage', plugin: 'plugin-storage' },\n search: { route: '/api/v1/search', plugin: 'plugin-search' },\n};\n\nexport class ObjectStackProtocolImplementation implements ObjectStackProtocol {\n private engine: IDataEngine;\n private getServicesRegistry?: () => Map;\n private getFeedService?: () => IFeedService | undefined;\n\n constructor(engine: IDataEngine, getServicesRegistry?: () => Map, getFeedService?: () => IFeedService | undefined) {\n this.engine = engine;\n this.getServicesRegistry = getServicesRegistry;\n this.getFeedService = getFeedService;\n }\n\n private requireFeedService(): IFeedService {\n const svc = this.getFeedService?.();\n if (!svc) {\n throw new Error('Feed service not available. Install and register service-feed to enable feed operations.');\n }\n return svc;\n }\n\n async getDiscovery() {\n // Get registered services from kernel if available\n const registeredServices = this.getServicesRegistry ? this.getServicesRegistry() : new Map();\n \n // Build dynamic service info with proper typing\n const services: Record = {\n // --- Kernel-provided (objectql is an example kernel implementation) ---\n metadata: { enabled: true, status: 'available' as const, route: '/api/v1/meta', provider: 'objectql' },\n data: { enabled: true, status: 'available' as const, route: '/api/v1/data', provider: 'objectql' },\n analytics: { enabled: true, status: 'available' as const, route: '/api/v1/analytics', provider: 'objectql' },\n };\n\n // Check which services are actually registered\n for (const [serviceName, config] of Object.entries(SERVICE_CONFIG)) {\n if (registeredServices.has(serviceName)) {\n // Service is registered and available\n services[serviceName] = {\n enabled: true,\n status: 'available' as const,\n route: config.route,\n provider: config.plugin,\n };\n } else {\n // Service is not registered\n services[serviceName] = {\n enabled: false,\n status: 'unavailable' as const,\n message: `Install ${config.plugin} to enable`,\n };\n }\n }\n\n // Build routes from services — a flat convenience map for client routing\n const serviceToRouteKey: Record = {\n auth: 'auth',\n automation: 'automation',\n ui: 'ui',\n workflow: 'workflow',\n realtime: 'realtime',\n notification: 'notifications',\n ai: 'ai',\n i18n: 'i18n',\n graphql: 'graphql',\n 'file-storage': 'storage',\n };\n\n const optionalRoutes: Partial = {\n analytics: '/api/v1/analytics',\n };\n\n // Add routes for available plugin services\n for (const [serviceName, config] of Object.entries(SERVICE_CONFIG)) {\n if (registeredServices.has(serviceName)) {\n const routeKey = serviceToRouteKey[serviceName];\n if (routeKey) {\n optionalRoutes[routeKey] = config.route;\n }\n }\n }\n\n // Add feed service status\n if (registeredServices.has('feed')) {\n services['feed'] = {\n enabled: true,\n status: 'available' as const,\n route: '/api/v1/data',\n provider: 'service-feed',\n };\n } else {\n services['feed'] = {\n enabled: false,\n status: 'unavailable' as const,\n message: 'Install service-feed to enable',\n };\n }\n\n const routes: ApiRoutes = {\n data: '/api/v1/data',\n metadata: '/api/v1/meta',\n ...optionalRoutes,\n };\n\n // Build well-known capabilities from registered services.\n // DiscoverySchema defines capabilities as Record\n // (hierarchical format). We also keep a flat WellKnownCapabilities for backward compat.\n const wellKnown: WellKnownCapabilities = {\n feed: registeredServices.has('feed'),\n comments: registeredServices.has('feed'),\n automation: registeredServices.has('automation'),\n cron: registeredServices.has('job'),\n search: registeredServices.has('search'),\n export: registeredServices.has('automation') || registeredServices.has('queue'),\n chunkedUpload: registeredServices.has('file-storage'),\n };\n\n // Convert flat booleans → hierarchical capability objects\n const capabilities: Record = {};\n for (const [key, enabled] of Object.entries(wellKnown)) {\n capabilities[key] = { enabled };\n }\n\n return {\n version: '1.0',\n apiName: 'ObjectStack API',\n routes,\n services,\n capabilities,\n };\n }\n\n async getMetaTypes() {\n const schemaTypes = SchemaRegistry.getRegisteredTypes();\n\n // Also include types from MetadataService (runtime-registered: agent, tool, etc.)\n let runtimeTypes: string[] = [];\n try {\n const services = this.getServicesRegistry?.();\n const metadataService = services?.get('metadata');\n if (metadataService && typeof metadataService.getRegisteredTypes === 'function') {\n runtimeTypes = await metadataService.getRegisteredTypes();\n }\n } catch {\n // MetadataService not available\n }\n\n const allTypes = Array.from(new Set([...schemaTypes, ...runtimeTypes]));\n return { types: allTypes };\n }\n\n async getMetaItems(request: { type: string; packageId?: string }) {\n const { packageId } = request;\n let items = SchemaRegistry.listItems(request.type, packageId);\n // Normalize singular/plural using explicit mapping\n if (items.length === 0) {\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) items = SchemaRegistry.listItems(alt, packageId);\n }\n\n // Fallback to database if registry is empty for this type\n if (items.length === 0) {\n try {\n const whereClause: any = { type: request.type, state: 'active' };\n if (packageId) whereClause._packageId = packageId;\n const allRecords = await this.engine.find('sys_metadata', {\n where: whereClause\n });\n if (allRecords && allRecords.length > 0) {\n items = allRecords.map((record: any) => {\n const data = typeof record.metadata === 'string'\n ? JSON.parse(record.metadata)\n : record.metadata;\n // Hydrate back into registry\n SchemaRegistry.registerItem(request.type, data, 'name' as any);\n return data;\n });\n } else {\n // Try alternate type name in DB using explicit mapping\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) {\n const altRecords = await this.engine.find('sys_metadata', {\n where: { type: alt, state: 'active' }\n });\n if (altRecords && altRecords.length > 0) {\n items = altRecords.map((record: any) => {\n const data = typeof record.metadata === 'string'\n ? JSON.parse(record.metadata)\n : record.metadata;\n SchemaRegistry.registerItem(request.type, data, 'name' as any);\n return data;\n });\n }\n }\n }\n } catch {\n // DB not available, return registry results (empty)\n }\n }\n\n // Merge with MetadataService (runtime-registered items: agents, tools, etc.)\n try {\n const services = this.getServicesRegistry?.();\n const metadataService = services?.get('metadata');\n if (metadataService && typeof metadataService.list === 'function') {\n const runtimeItems = await metadataService.list(request.type);\n if (runtimeItems && runtimeItems.length > 0) {\n // Merge, avoiding duplicates by name\n const itemMap = new Map();\n for (const item of items) {\n const entry = item as any;\n if (entry && typeof entry === 'object' && 'name' in entry) {\n itemMap.set(entry.name, entry);\n }\n }\n for (const item of runtimeItems) {\n const entry = item as any;\n if (entry && typeof entry === 'object' && 'name' in entry) {\n itemMap.set(entry.name, entry);\n }\n }\n items = Array.from(itemMap.values());\n }\n }\n } catch {\n // MetadataService not available or doesn't support this type\n }\n\n return {\n type: request.type,\n items\n };\n }\n\n async getMetaItem(request: { type: string, name: string, packageId?: string }) {\n let item = SchemaRegistry.getItem(request.type, request.name);\n // Normalize singular/plural using explicit mapping\n if (item === undefined) {\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) item = SchemaRegistry.getItem(alt, request.name);\n }\n\n // Fallback to database if not in registry\n if (item === undefined) {\n try {\n const record = await this.engine.findOne('sys_metadata', {\n where: { type: request.type, name: request.name, state: 'active' }\n });\n if (record) {\n item = typeof record.metadata === 'string'\n ? JSON.parse(record.metadata)\n : record.metadata;\n // Hydrate back into registry for next time\n SchemaRegistry.registerItem(request.type, item, 'name' as any);\n } else {\n // Try alternate type name using explicit mapping\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) {\n const altRecord = await this.engine.findOne('sys_metadata', {\n where: { type: alt, name: request.name, state: 'active' }\n });\n if (altRecord) {\n item = typeof altRecord.metadata === 'string'\n ? JSON.parse(altRecord.metadata)\n : altRecord.metadata;\n // Hydrate back into registry for next time\n SchemaRegistry.registerItem(request.type, item, 'name' as any);\n }\n }\n }\n } catch {\n // DB not available, return undefined\n }\n }\n\n // Fallback to MetadataService for runtime-registered items (agents, tools, etc.)\n if (item === undefined) {\n try {\n const services = this.getServicesRegistry?.();\n const metadataService = services?.get('metadata');\n if (metadataService && typeof metadataService.get === 'function') {\n item = await metadataService.get(request.type, request.name);\n }\n } catch {\n // MetadataService not available\n }\n }\n\n return {\n type: request.type,\n name: request.name,\n item\n };\n }\n\n async getUiView(request: { object: string, type: 'list' | 'form' }) {\n const schema = SchemaRegistry.getObject(request.object);\n if (!schema) throw new Error(`Object ${request.object} not found`);\n\n const fields = schema.fields || {};\n const fieldKeys = Object.keys(fields);\n\n if (request.type === 'list') {\n // Intelligent Column Selection\n // 1. Always include 'name' or name-like fields\n // 2. Limit to 6 columns by default\n const priorityFields = ['name', 'title', 'label', 'subject', 'email', 'status', 'type', 'category', 'created_at'];\n \n let columns = fieldKeys.filter(k => priorityFields.includes(k));\n \n // If few priority fields, add others until 5\n if (columns.length < 5) {\n const remaining = fieldKeys.filter(k => !columns.includes(k) && k !== 'id' && !fields[k].hidden);\n columns = [...columns, ...remaining.slice(0, 5 - columns.length)];\n }\n \n // Sort columns by priority then alphabet or schema order\n // For now, just keep them roughly in order they appear in schema or priority list\n \n return {\n list: {\n type: 'grid' as const,\n object: request.object,\n label: schema.label || schema.name,\n columns: columns.map(f => ({\n field: f,\n label: fields[f]?.label || f,\n sortable: true\n })),\n sort: fields['created_at'] ? ([{ field: 'created_at', order: 'desc' }] as any) : undefined,\n searchableFields: columns.slice(0, 3) // Make first few textual columns searchable\n }\n };\n } else {\n // Form View Generation\n // Simple single-section layout for now\n const formFields = fieldKeys\n .filter(k => k !== 'id' && k !== 'created_at' && k !== 'updated_at' && !fields[k].hidden)\n .map(f => ({\n field: f,\n label: fields[f]?.label,\n required: fields[f]?.required,\n readonly: fields[f]?.readonly,\n type: fields[f]?.type,\n // Default to 2 columns for most, 1 for textareas\n colSpan: (fields[f]?.type === 'textarea' || fields[f]?.type === 'html') ? 2 : 1\n }));\n\n return {\n form: {\n type: 'simple' as const,\n object: request.object,\n label: `Edit ${schema.label || schema.name}`,\n sections: [\n {\n label: 'General Information',\n columns: 2 as const,\n collapsible: false,\n collapsed: false,\n fields: formFields\n }\n ]\n }\n };\n }\n }\n\n async findData(request: { object: string, query?: any }) {\n const options: any = { ...request.query };\n\n // ====================================================================\n // Normalize legacy params → QueryAST standard (where/fields/orderBy/offset/expand)\n // ====================================================================\n\n // Numeric fields — normalize top → limit, skip → offset\n if (options.top != null) {\n options.limit = Number(options.top);\n delete options.top;\n }\n if (options.skip != null) {\n options.offset = Number(options.skip);\n delete options.skip;\n }\n if (options.limit != null) options.limit = Number(options.limit);\n if (options.offset != null) options.offset = Number(options.offset);\n\n // Select → fields: comma-separated string → array\n if (typeof options.select === 'string') {\n options.fields = options.select.split(',').map((s: string) => s.trim()).filter(Boolean);\n } else if (Array.isArray(options.select)) {\n options.fields = options.select;\n }\n if (options.select !== undefined) delete options.select;\n\n // Sort/orderBy → orderBy: string → SortNode[] array\n const sortValue = options.orderBy ?? options.sort;\n if (typeof sortValue === 'string') {\n const parsed = sortValue.split(',').map((part: string) => {\n const trimmed = part.trim();\n if (trimmed.startsWith('-')) {\n return { field: trimmed.slice(1), order: 'desc' as const };\n }\n const [field, order] = trimmed.split(/\\s+/);\n return { field, order: (order?.toLowerCase() === 'desc' ? 'desc' : 'asc') as 'asc' | 'desc' };\n }).filter((s: any) => s.field);\n options.orderBy = parsed;\n } else if (Array.isArray(sortValue)) {\n options.orderBy = sortValue;\n }\n delete options.sort;\n\n // Filter/filters/$filter → where: normalize all filter aliases\n const filterValue = options.filter ?? options.filters ?? options.$filter ?? options.where;\n delete options.filter;\n delete options.filters;\n delete options.$filter;\n\n if (filterValue !== undefined) {\n let parsedFilter = filterValue;\n // JSON string → object\n if (typeof parsedFilter === 'string') {\n try { parsedFilter = JSON.parse(parsedFilter); } catch { /* keep as-is */ }\n }\n // Filter AST array → FilterCondition object\n if (isFilterAST(parsedFilter)) {\n parsedFilter = parseFilterAST(parsedFilter);\n }\n options.where = parsedFilter;\n }\n\n // Populate/expand/$expand → expand (Record)\n const populateValue = options.populate;\n const expandValue = options.$expand ?? options.expand;\n const expandNames: string[] = [];\n if (typeof populateValue === 'string') {\n expandNames.push(...populateValue.split(',').map((s: string) => s.trim()).filter(Boolean));\n } else if (Array.isArray(populateValue)) {\n expandNames.push(...populateValue);\n }\n if (!expandNames.length && expandValue) {\n if (typeof expandValue === 'string') {\n expandNames.push(...expandValue.split(',').map((s: string) => s.trim()).filter(Boolean));\n } else if (Array.isArray(expandValue)) {\n expandNames.push(...expandValue);\n }\n }\n delete options.populate;\n delete options.$expand;\n // Clean up non-object expand (e.g. string) BEFORE the Record conversion\n // below, so that populate-derived names can create the expand Record even\n // when a legacy string expand was also present.\n if (typeof options.expand !== 'object' || options.expand === null) {\n delete options.expand;\n }\n // Only set expand if not already an object (advanced usage)\n if (expandNames.length > 0 && !options.expand) {\n options.expand = {} as Record;\n for (const rel of expandNames) {\n options.expand[rel] = { object: rel };\n }\n }\n\n // Boolean fields\n for (const key of ['distinct', 'count']) {\n if (options[key] === 'true') options[key] = true;\n else if (options[key] === 'false') options[key] = false;\n }\n \n // Flat field filters: REST-style query params like ?id=abc&status=open\n // After extracting all known query parameters, any remaining keys are\n // treated as implicit field-level equality filters merged into `where`.\n const knownParams = new Set([\n 'top', 'limit', 'offset',\n 'orderBy',\n 'fields',\n 'where',\n 'expand',\n 'distinct', 'count',\n 'aggregations', 'groupBy',\n 'search', 'context', 'cursor',\n ]);\n if (!options.where) {\n const implicitFilters: Record = {};\n for (const key of Object.keys(options)) {\n if (!knownParams.has(key)) {\n implicitFilters[key] = options[key];\n delete options[key];\n }\n }\n if (Object.keys(implicitFilters).length > 0) {\n options.where = implicitFilters;\n }\n }\n \n const records = await this.engine.find(request.object, options);\n // Spec: FindDataResponseSchema — only `records` is returned.\n // OData `value` adaptation (if needed) is handled in the HTTP dispatch layer.\n return {\n object: request.object,\n records,\n total: records.length,\n hasMore: false\n };\n }\n\n async getData(request: { object: string, id: string, expand?: string | string[], select?: string | string[] }) {\n const queryOptions: any = {\n where: { id: request.id }\n };\n\n // Support fields for single-record retrieval\n if (request.select) {\n queryOptions.fields = typeof request.select === 'string'\n ? request.select.split(',').map((s: string) => s.trim()).filter(Boolean)\n : request.select;\n }\n\n // Support expand for single-record retrieval\n if (request.expand) {\n const expandNames = typeof request.expand === 'string'\n ? request.expand.split(',').map((s: string) => s.trim()).filter(Boolean)\n : request.expand;\n queryOptions.expand = {} as Record;\n for (const rel of expandNames) {\n queryOptions.expand[rel] = { object: rel };\n }\n }\n\n const result = await this.engine.findOne(request.object, queryOptions);\n if (result) {\n return {\n object: request.object,\n id: request.id,\n record: result\n };\n }\n throw new Error(`Record ${request.id} not found in ${request.object}`);\n }\n\n async createData(request: { object: string, data: any }) {\n const result = await this.engine.insert(request.object, request.data);\n return {\n object: request.object,\n id: result.id,\n record: result\n };\n }\n\n async updateData(request: { object: string, id: string, data: any }) {\n // Adapt: update(obj, id, data) -> update(obj, data, options)\n const result = await this.engine.update(request.object, request.data, { where: { id: request.id } });\n return {\n object: request.object,\n id: request.id,\n record: result\n };\n }\n\n async deleteData(request: { object: string, id: string }) {\n // Adapt: delete(obj, id) -> delete(obj, options)\n await this.engine.delete(request.object, { where: { id: request.id } });\n return {\n object: request.object,\n id: request.id,\n success: true\n };\n }\n\n // ==========================================\n // Metadata Caching\n // ==========================================\n\n async getMetaItemCached(request: { type: string, name: string, cacheRequest?: MetadataCacheRequest }): Promise {\n try {\n let item = SchemaRegistry.getItem(request.type, request.name);\n\n // Normalize singular/plural using explicit mapping\n if (!item) {\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) item = SchemaRegistry.getItem(alt, request.name);\n }\n\n // Fallback to MetadataService (e.g. agents, tools registered in MetadataManager)\n if (!item) {\n try {\n const services = this.getServicesRegistry?.();\n const metadataService = services?.get('metadata');\n if (metadataService && typeof metadataService.get === 'function') {\n item = await metadataService.get(request.type, request.name);\n }\n } catch {\n // MetadataService not available\n }\n }\n\n if (!item) {\n throw new Error(`Metadata item ${request.type}/${request.name} not found`);\n }\n\n // Calculate ETag (simple hash of the stringified metadata)\n const content = JSON.stringify(item);\n const hash = simpleHash(content);\n const etag = { value: hash, weak: false };\n\n // Check If-None-Match header\n if (request.cacheRequest?.ifNoneMatch) {\n const clientEtag = request.cacheRequest.ifNoneMatch.replace(/^\"(.*)\"$/, '$1').replace(/^W\\/\"(.*)\"$/, '$1');\n if (clientEtag === hash) {\n // Return 304 Not Modified\n return {\n notModified: true,\n etag,\n };\n }\n }\n\n // Return full metadata with cache headers\n return {\n data: item,\n etag,\n lastModified: new Date().toISOString(),\n cacheControl: {\n directives: ['public', 'max-age'],\n maxAge: 3600, // 1 hour\n },\n notModified: false,\n };\n } catch (error: any) {\n throw error;\n }\n }\n\n // ==========================================\n // Batch Operations\n // ==========================================\n\n async batchData(request: { object: string, request: BatchUpdateRequest }): Promise {\n const { object, request: batchReq } = request;\n const { operation, records, options } = batchReq;\n const results: Array<{ id?: string; success: boolean; error?: string; record?: any }> = [];\n let succeeded = 0;\n let failed = 0;\n\n for (const record of records) {\n try {\n switch (operation) {\n case 'create': {\n const created = await this.engine.insert(object, record.data || record);\n results.push({ id: created.id, success: true, record: created });\n succeeded++;\n break;\n }\n case 'update': {\n if (!record.id) throw new Error('Record id is required for update');\n const updated = await this.engine.update(object, record.data || {}, { where: { id: record.id } });\n results.push({ id: record.id, success: true, record: updated });\n succeeded++;\n break;\n }\n case 'upsert': {\n // Try update first, then create if not found\n if (record.id) {\n try {\n const existing = await this.engine.findOne(object, { where: { id: record.id } });\n if (existing) {\n const updated = await this.engine.update(object, record.data || {}, { where: { id: record.id } });\n results.push({ id: record.id, success: true, record: updated });\n } else {\n const created = await this.engine.insert(object, { id: record.id, ...(record.data || {}) });\n results.push({ id: created.id, success: true, record: created });\n }\n } catch {\n const created = await this.engine.insert(object, { id: record.id, ...(record.data || {}) });\n results.push({ id: created.id, success: true, record: created });\n }\n } else {\n const created = await this.engine.insert(object, record.data || record);\n results.push({ id: created.id, success: true, record: created });\n }\n succeeded++;\n break;\n }\n case 'delete': {\n if (!record.id) throw new Error('Record id is required for delete');\n await this.engine.delete(object, { where: { id: record.id } });\n results.push({ id: record.id, success: true });\n succeeded++;\n break;\n }\n default:\n results.push({ id: record.id, success: false, error: `Unknown operation: ${operation}` });\n failed++;\n }\n } catch (err: any) {\n results.push({ id: record.id, success: false, error: err.message });\n failed++;\n if (options?.atomic) {\n // Abort remaining operations on first failure in atomic mode\n break;\n }\n if (!options?.continueOnError) {\n break;\n }\n }\n }\n\n return {\n success: failed === 0,\n operation,\n total: records.length,\n succeeded,\n failed,\n results: options?.returnRecords !== false ? results : results.map(r => ({ id: r.id, success: r.success, error: r.error })),\n } as BatchUpdateResponse;\n }\n \n async createManyData(request: { object: string, records: any[] }): Promise {\n const records = await this.engine.insert(request.object, request.records);\n return {\n object: request.object,\n records,\n count: records.length\n };\n }\n \n async updateManyData(request: UpdateManyDataRequest): Promise {\n const { object, records, options } = request;\n const results: Array<{ id?: string; success: boolean; error?: string; record?: any }> = [];\n let succeeded = 0;\n let failed = 0;\n\n for (const record of records) {\n try {\n const updated = await this.engine.update(object, record.data, { where: { id: record.id } });\n results.push({ id: record.id, success: true, record: updated });\n succeeded++;\n } catch (err: any) {\n results.push({ id: record.id, success: false, error: err.message });\n failed++;\n if (!options?.continueOnError) {\n break;\n }\n }\n }\n\n return {\n success: failed === 0,\n operation: 'update',\n total: records.length,\n succeeded,\n failed,\n results,\n } as BatchUpdateResponse;\n }\n\n async analyticsQuery(request: any): Promise {\n // Map AnalyticsQuery (cube-style) to engine aggregation.\n // cube name maps to object name; measures → aggregations; dimensions → groupBy.\n const { query, cube } = request;\n const object = cube;\n\n // Build groupBy from dimensions\n const groupBy = query.dimensions || [];\n\n // Build aggregations from measures\n // Measures can be simple field names like \"count\" or \"field_name.sum\"\n // Or cube-defined measure names. We support: field.function or just function(field).\n const aggregations: Array<{ field: string; method: string; alias: string }> = [];\n if (query.measures) {\n for (const measure of query.measures) {\n // Support formats: \"count\", \"amount.sum\", \"revenue.avg\"\n if (measure === 'count' || measure === 'count_all') {\n aggregations.push({ field: '*', method: 'count', alias: 'count' });\n } else if (measure.includes('.')) {\n const [field, method] = measure.split('.');\n aggregations.push({ field, method, alias: `${field}_${method}` });\n } else {\n // Treat as count of the field\n aggregations.push({ field: measure, method: 'sum', alias: measure });\n }\n }\n }\n\n // Build filter from analytics filters\n let filter: any = undefined;\n if (query.filters && query.filters.length > 0) {\n const conditions: any[] = query.filters.map((f: any) => {\n const op = this.mapAnalyticsOperator(f.operator);\n if (f.values && f.values.length === 1) {\n return { [f.member]: { [op]: f.values[0] } };\n } else if (f.values && f.values.length > 1) {\n return { [f.member]: { $in: f.values } };\n }\n return { [f.member]: { [op]: true } };\n });\n filter = conditions.length === 1 ? conditions[0] : { $and: conditions };\n }\n\n // Execute via engine.aggregate (which delegates to driver.find with groupBy/aggregations)\n const rows = await this.engine.aggregate(object, {\n where: filter,\n groupBy: groupBy.length > 0 ? groupBy : undefined,\n aggregations: aggregations.length > 0\n ? aggregations.map(a => ({ function: a.method as any, field: a.field, alias: a.alias }))\n : [{ function: 'count' as any, alias: 'count' }],\n });\n\n // Build field metadata\n const fields = [\n ...groupBy.map((d: string) => ({ name: d, type: 'string' })),\n ...aggregations.map(a => ({ name: a.alias, type: 'number' })),\n ];\n\n return {\n success: true,\n data: {\n rows,\n fields,\n },\n };\n }\n\n async getAnalyticsMeta(request: any): Promise {\n // Auto-generate cube metadata from registered objects in SchemaRegistry.\n // Each object becomes a cube; number fields → measures; other fields → dimensions.\n const objects = SchemaRegistry.listItems('object');\n const cubeFilter = request?.cube;\n\n const cubes: any[] = [];\n for (const obj of objects) {\n const schema = obj as any;\n if (cubeFilter && schema.name !== cubeFilter) continue;\n\n const measures: Record = {};\n const dimensions: Record = {};\n const fields = schema.fields || {};\n\n // Always add a count measure\n measures['count'] = {\n name: 'count',\n label: 'Count',\n type: 'count',\n sql: '*',\n };\n\n for (const [fieldName, fieldDef] of Object.entries(fields)) {\n const fd = fieldDef as any;\n const fieldType = fd.type || 'text';\n\n if (['number', 'currency', 'percent'].includes(fieldType)) {\n // Numeric fields become both measures and dimensions\n measures[`${fieldName}_sum`] = {\n name: `${fieldName}_sum`,\n label: `${fd.label || fieldName} (Sum)`,\n type: 'sum',\n sql: fieldName,\n };\n measures[`${fieldName}_avg`] = {\n name: `${fieldName}_avg`,\n label: `${fd.label || fieldName} (Avg)`,\n type: 'avg',\n sql: fieldName,\n };\n dimensions[fieldName] = {\n name: fieldName,\n label: fd.label || fieldName,\n type: 'number',\n sql: fieldName,\n };\n } else if (['date', 'datetime'].includes(fieldType)) {\n dimensions[fieldName] = {\n name: fieldName,\n label: fd.label || fieldName,\n type: 'time',\n sql: fieldName,\n granularities: ['day', 'week', 'month', 'quarter', 'year'],\n };\n } else if (['boolean'].includes(fieldType)) {\n dimensions[fieldName] = {\n name: fieldName,\n label: fd.label || fieldName,\n type: 'boolean',\n sql: fieldName,\n };\n } else {\n // text, select, lookup, etc. → dimension\n dimensions[fieldName] = {\n name: fieldName,\n label: fd.label || fieldName,\n type: 'string',\n sql: fieldName,\n };\n }\n }\n\n cubes.push({\n name: schema.name,\n title: schema.label || schema.name,\n description: schema.description,\n sql: schema.name,\n measures,\n dimensions,\n public: true,\n });\n }\n\n return {\n success: true,\n data: { cubes },\n };\n }\n\n private mapAnalyticsOperator(op: string): string {\n const map: Record = {\n equals: '$eq',\n notEquals: '$ne',\n contains: '$contains',\n notContains: '$notContains',\n gt: '$gt',\n gte: '$gte',\n lt: '$lt',\n lte: '$lte',\n set: '$ne',\n notSet: '$eq',\n };\n return map[op] || '$eq';\n }\n\n async triggerAutomation(_request: any): Promise {\n throw new Error('triggerAutomation requires plugin-automation service. Install and register a plugin that provides the \"automation\" service.');\n }\n\n async deleteManyData(request: DeleteManyDataRequest): Promise {\n // This expects deleting by IDs.\n return this.engine.delete(request.object, {\n where: { id: { $in: request.ids } },\n ...request.options\n });\n }\n\n async saveMetaItem(request: { type: string, name: string, item?: any }) {\n if (!request.item) {\n throw new Error('Item data is required');\n }\n\n // 1. Always update the in-memory registry (runtime cache)\n SchemaRegistry.registerItem(request.type, request.item, 'name');\n\n // 2. Persist to database via data engine\n try {\n const now = new Date().toISOString();\n // Check if record exists\n const existing = await this.engine.findOne('sys_metadata', {\n where: { type: request.type, name: request.name }\n });\n\n if (existing) {\n await this.engine.update('sys_metadata', {\n metadata: JSON.stringify(request.item),\n updated_at: now,\n version: (existing.version || 0) + 1,\n }, {\n where: { id: existing.id }\n });\n } else {\n // Use crypto.randomUUID() when available (modern browsers and Node ≥ 14.17);\n // fall back to a time+random ID for older or restricted environments.\n const id = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : `meta_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n await this.engine.insert('sys_metadata', {\n id,\n name: request.name,\n type: request.type,\n scope: 'platform',\n metadata: JSON.stringify(request.item),\n state: 'active',\n version: 1,\n created_at: now,\n updated_at: now,\n });\n }\n\n return {\n success: true,\n message: 'Saved to database and registry'\n };\n } catch (dbError: any) {\n // DB write failed but in-memory registry was updated — degrade gracefully\n console.warn(`[Protocol] DB persistence failed for ${request.type}/${request.name}: ${dbError.message}`);\n return {\n success: true,\n message: 'Saved to memory registry (DB persistence unavailable)',\n warning: dbError.message\n };\n }\n }\n\n /**\n * Hydrate SchemaRegistry from the database on startup.\n * Loads all active metadata records and registers them in the in-memory registry.\n * Safe to call repeatedly — idempotent (latest DB record wins).\n */\n async loadMetaFromDb(): Promise<{ loaded: number; errors: number }> {\n let loaded = 0;\n let errors = 0;\n try {\n const records = await this.engine.find('sys_metadata', {\n where: { state: 'active' }\n });\n for (const record of records) {\n try {\n const data = typeof record.metadata === 'string'\n ? JSON.parse(record.metadata)\n : record.metadata;\n // Normalize DB type to singular (DB may store legacy plural forms)\n const normalizedType = PLURAL_TO_SINGULAR[record.type] ?? record.type;\n if (normalizedType === 'object') {\n SchemaRegistry.registerObject(data as any, record.packageId || 'sys_metadata');\n } else {\n SchemaRegistry.registerItem(normalizedType, data, 'name' as any);\n }\n loaded++;\n } catch (e) {\n errors++;\n console.warn(`[Protocol] Failed to hydrate ${record.type}/${record.name}: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n } catch (e: any) {\n console.warn(`[Protocol] DB hydration skipped: ${e.message}`);\n }\n return { loaded, errors };\n }\n\n // ==========================================\n // Feed Operations\n // ==========================================\n\n async listFeed(request: any): Promise {\n const svc = this.requireFeedService();\n const result = await svc.listFeed({\n object: request.object,\n recordId: request.recordId,\n filter: request.type,\n limit: request.limit,\n cursor: request.cursor,\n });\n return { success: true, data: result };\n }\n\n async createFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.createFeedItem({\n object: request.object,\n recordId: request.recordId,\n type: request.type,\n actor: { type: 'user', id: 'current_user' },\n body: request.body,\n mentions: request.mentions,\n parentId: request.parentId,\n visibility: request.visibility,\n });\n return { success: true, data: item };\n }\n\n async updateFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.updateFeedItem(request.feedId, {\n body: request.body,\n mentions: request.mentions,\n visibility: request.visibility,\n });\n return { success: true, data: item };\n }\n\n async deleteFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n await svc.deleteFeedItem(request.feedId);\n return { success: true, data: { feedId: request.feedId } };\n }\n\n async addReaction(request: any): Promise {\n const svc = this.requireFeedService();\n const reactions = await svc.addReaction(request.feedId, request.emoji, 'current_user');\n return { success: true, data: { reactions } };\n }\n\n async removeReaction(request: any): Promise {\n const svc = this.requireFeedService();\n const reactions = await svc.removeReaction(request.feedId, request.emoji, 'current_user');\n return { success: true, data: { reactions } };\n }\n\n async pinFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.getFeedItem(request.feedId);\n if (!item) throw new Error(`Feed item ${request.feedId} not found`);\n // IFeedService doesn't have dedicated pin/unpin — use updateFeedItem to persist pin state\n await svc.updateFeedItem(request.feedId, { visibility: item.visibility });\n return { success: true, data: { feedId: request.feedId, pinned: true, pinnedAt: new Date().toISOString() } };\n }\n\n async unpinFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.getFeedItem(request.feedId);\n if (!item) throw new Error(`Feed item ${request.feedId} not found`);\n await svc.updateFeedItem(request.feedId, { visibility: item.visibility });\n return { success: true, data: { feedId: request.feedId, pinned: false } };\n }\n\n async starFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.getFeedItem(request.feedId);\n if (!item) throw new Error(`Feed item ${request.feedId} not found`);\n // IFeedService doesn't have dedicated star/unstar — verify item exists then return state\n await svc.updateFeedItem(request.feedId, { visibility: item.visibility });\n return { success: true, data: { feedId: request.feedId, starred: true, starredAt: new Date().toISOString() } };\n }\n\n async unstarFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.getFeedItem(request.feedId);\n if (!item) throw new Error(`Feed item ${request.feedId} not found`);\n await svc.updateFeedItem(request.feedId, { visibility: item.visibility });\n return { success: true, data: { feedId: request.feedId, starred: false } };\n }\n\n async searchFeed(request: any): Promise {\n const svc = this.requireFeedService();\n // Search delegates to listFeed with filter since IFeedService doesn't have a dedicated search\n const result = await svc.listFeed({\n object: request.object,\n recordId: request.recordId,\n filter: request.type,\n limit: request.limit,\n cursor: request.cursor,\n });\n // Filter by query text in body\n const queryLower = (request.query || '').toLowerCase();\n const filtered = result.items.filter((item: any) =>\n item.body?.toLowerCase().includes(queryLower)\n );\n return { success: true, data: { items: filtered, total: filtered.length, hasMore: false } };\n }\n\n async getChangelog(request: any): Promise {\n const svc = this.requireFeedService();\n // Changelog retrieves field_change type feed items\n const result = await svc.listFeed({\n object: request.object,\n recordId: request.recordId,\n filter: 'changes_only',\n limit: request.limit,\n cursor: request.cursor,\n });\n const entries = result.items.map((item: any) => ({\n id: item.id,\n object: item.object,\n recordId: item.recordId,\n actor: item.actor,\n changes: item.changes || [],\n timestamp: item.createdAt,\n source: item.source,\n }));\n return { success: true, data: { entries, total: result.total, nextCursor: result.nextCursor, hasMore: result.hasMore } };\n }\n\n async feedSubscribe(request: any): Promise {\n const svc = this.requireFeedService();\n const subscription = await svc.subscribe({\n object: request.object,\n recordId: request.recordId,\n userId: 'current_user',\n events: request.events,\n channels: request.channels,\n });\n return { success: true, data: subscription };\n }\n\n async feedUnsubscribe(request: any): Promise {\n const svc = this.requireFeedService();\n const unsubscribed = await svc.unsubscribe(request.object, request.recordId, 'current_user');\n return { success: true, data: { object: request.object, recordId: request.recordId, unsubscribed } };\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { QueryAST, HookContext, ServiceObject } from '@objectstack/spec/data';\nimport {\n EngineQueryOptions,\n DataEngineInsertOptions,\n EngineUpdateOptions,\n EngineDeleteOptions,\n EngineAggregateOptions,\n EngineCountOptions\n} from '@objectstack/spec/data';\nimport { ExecutionContext, ExecutionContextSchema } from '@objectstack/spec/kernel';\nimport { DriverInterface, IDataEngine, Logger, createLogger } from '@objectstack/core';\nimport { CoreServiceName } from '@objectstack/spec/system';\nimport { IRealtimeService, RealtimeEventPayload } from '@objectstack/spec/contracts';\nimport { pluralToSingular } from '@objectstack/spec/shared';\nimport { SchemaRegistry } from './registry.js';\n\nexport type HookHandler = (context: HookContext) => Promise | void;\n\n/**\n * Per-object hook entry with priority support\n */\nexport interface HookEntry {\n handler: HookHandler;\n object?: string | string[]; // undefined = global hook\n priority: number;\n packageId?: string;\n}\n\n/**\n * Operation Context for Middleware Chain\n */\nexport interface OperationContext {\n object: string;\n operation: 'find' | 'findOne' | 'insert' | 'update' | 'delete' | 'count' | 'aggregate';\n ast?: QueryAST;\n data?: any;\n options?: any;\n context?: ExecutionContext;\n result?: any;\n}\n\n/**\n * Engine Middleware (Onion model)\n */\nexport type EngineMiddleware = (\n ctx: OperationContext,\n next: () => Promise\n) => Promise;\n\n/**\n * Host Context provided to plugins (Internal ObjectQL Plugin System)\n */\nexport interface ObjectQLHostContext {\n ql: ObjectQL;\n logger: Logger;\n // Extensible map for host-specific globals (like HTTP Router, etc.)\n [key: string]: any;\n}\n\n/**\n * ObjectQL Engine\n * \n * Implements the IDataEngine interface for data persistence.\n * Acts as the reference implementation for:\n * - CoreServiceName.data (CRUD)\n * - CoreServiceName.metadata (Schema Registry)\n */\nexport class ObjectQL implements IDataEngine {\n private drivers = new Map();\n private defaultDriver: string | null = null;\n private logger: Logger;\n\n // Per-object hooks with priority support\n private hooks: Map = new Map([\n ['beforeFind', []], ['afterFind', []],\n ['beforeInsert', []], ['afterInsert', []],\n ['beforeUpdate', []], ['afterUpdate', []],\n ['beforeDelete', []], ['afterDelete', []],\n ]);\n\n // Middleware chain (onion model)\n private middlewares: Array<{\n fn: EngineMiddleware;\n object?: string;\n }> = [];\n\n // Action registry: key = \"objectName:actionName\"\n private actions = new Map Promise | any; package?: string }>();\n\n // Host provided context additions (e.g. Server router)\n private hostContext: Record = {};\n\n // Realtime service for event publishing\n private realtimeService?: IRealtimeService;\n\n constructor(hostContext: Record = {}) {\n this.hostContext = hostContext;\n // Use provided logger or create a new one\n this.logger = hostContext.logger || createLogger({ level: 'info', format: 'pretty' });\n this.logger.info('ObjectQL Engine Instance Created');\n }\n\n /**\n * Service Status Report\n * Used by Kernel to verify health and capabilities.\n */\n getStatus() {\n return {\n name: CoreServiceName.enum.data,\n status: 'running',\n version: '0.9.0',\n features: ['crud', 'query', 'aggregate', 'transactions', 'metadata']\n };\n }\n\n /**\n * Expose the SchemaRegistry for plugins to register metadata\n */\n get registry() {\n return SchemaRegistry;\n }\n\n /**\n * Load and Register a Plugin\n */\n async use(manifestPart: any, runtimePart?: any) {\n this.logger.debug('Loading plugin', { \n hasManifest: !!manifestPart, \n hasRuntime: !!runtimePart \n });\n\n // 1. Validate / Register Manifest\n if (manifestPart) {\n this.registerApp(manifestPart);\n }\n\n // 2. Execute Runtime\n if (runtimePart) {\n const pluginDef = (runtimePart as any).default || runtimePart;\n if (pluginDef.onEnable) {\n this.logger.debug('Executing plugin runtime onEnable');\n \n const context: ObjectQLHostContext = {\n ql: this,\n logger: this.logger,\n // Expose the driver registry helper explicitly if needed\n drivers: {\n register: (driver: DriverInterface) => this.registerDriver(driver)\n },\n ...this.hostContext\n };\n \n await pluginDef.onEnable(context);\n this.logger.debug('Plugin runtime onEnable completed');\n }\n }\n }\n\n /**\n * Register a hook\n * @param event The event name (e.g. 'beforeFind', 'afterInsert')\n * @param handler The handler function\n * @param options Optional: target object(s) and priority\n */\n registerHook(event: string, handler: HookHandler, options?: {\n object?: string | string[];\n priority?: number;\n packageId?: string;\n }) {\n if (!this.hooks.has(event)) {\n this.hooks.set(event, []);\n }\n const entries = this.hooks.get(event)!;\n entries.push({\n handler,\n object: options?.object,\n priority: options?.priority ?? 100,\n packageId: options?.packageId,\n });\n // Sort by priority (lower runs first)\n entries.sort((a, b) => a.priority - b.priority);\n this.logger.debug('Registered hook', { event, object: options?.object, priority: options?.priority ?? 100, totalHandlers: entries.length });\n }\n\n public async triggerHooks(event: string, context: HookContext) {\n const entries = this.hooks.get(event) || [];\n \n if (entries.length === 0) {\n this.logger.debug('No hooks registered for event', { event });\n return;\n }\n\n this.logger.debug('Triggering hooks', { event, count: entries.length });\n \n for (const entry of entries) {\n // Per-object matching\n if (entry.object) {\n const targets = Array.isArray(entry.object) ? entry.object : [entry.object];\n if (!targets.includes('*') && !targets.includes(context.object)) {\n continue; // Skip non-matching hooks\n }\n }\n await entry.handler(context);\n }\n }\n\n // ========================================\n // Action System\n // ========================================\n\n /**\n * Register a named action on an object.\n * Actions are custom business logic callable via `repo.execute(actionName, params)`.\n *\n * @param objectName Target object\n * @param actionName Unique action name within the object\n * @param handler Handler function\n * @param packageName Optional package owner (for cleanup)\n */\n registerAction(objectName: string, actionName: string, handler: (ctx: any) => Promise | any, packageName?: string): void {\n const key = `${objectName}:${actionName}`;\n this.actions.set(key, { handler, package: packageName });\n this.logger.debug('Registered action', { objectName, actionName, package: packageName });\n }\n\n /**\n * Execute a named action on an object.\n */\n async executeAction(objectName: string, actionName: string, ctx: any): Promise {\n const entry = this.actions.get(`${objectName}:${actionName}`);\n if (!entry) {\n throw new Error(`Action '${actionName}' on object '${objectName}' not found`);\n }\n return entry.handler(ctx);\n }\n\n /**\n * Remove all actions registered by a specific package.\n */\n removeActionsByPackage(packageName: string): void {\n for (const [key, entry] of this.actions.entries()) {\n if (entry.package === packageName) {\n this.actions.delete(key);\n }\n }\n }\n\n /**\n * Register a middleware function\n * Middlewares execute in onion model around every data operation.\n * @param fn The middleware function\n * @param options Optional: target object filter\n */\n registerMiddleware(fn: EngineMiddleware, options?: { object?: string }): void {\n this.middlewares.push({ fn, object: options?.object });\n this.logger.debug('Registered middleware', { object: options?.object, total: this.middlewares.length });\n }\n\n /**\n * Execute an operation through the middleware chain\n */\n private async executeWithMiddleware(ctx: OperationContext, executor: () => Promise): Promise {\n const applicable = this.middlewares.filter(m =>\n !m.object || m.object === '*' || m.object === ctx.object\n );\n\n let index = 0;\n const next = async (): Promise => {\n if (index < applicable.length) {\n const mw = applicable[index++];\n await mw.fn(ctx, next);\n } else {\n ctx.result = await executor();\n }\n };\n\n await next();\n return ctx.result;\n }\n\n /**\n * Build a HookContext.session from ExecutionContext\n */\n private buildSession(execCtx?: ExecutionContext): HookContext['session'] {\n if (!execCtx) return undefined;\n return {\n userId: execCtx.userId,\n tenantId: execCtx.tenantId,\n roles: execCtx.roles,\n accessToken: execCtx.accessToken,\n };\n }\n\n /**\n * Register contribution (Manifest)\n * \n * Installs the manifest as a Package (the unit of installation),\n * then decomposes it into individual metadata items (objects, apps, actions, etc.)\n * and registers each into the SchemaRegistry.\n * \n * Key: Package ≠ App. The manifest is the package. The apps[] array inside\n * the manifest contains UI navigation definitions (AppSchema).\n */\n registerApp(manifest: any) {\n const id = manifest.id || manifest.name;\n const namespace = manifest.namespace as string | undefined;\n this.logger.debug('Registering package manifest', { id, namespace });\n\n // 1. Register the Package (manifest + lifecycle state)\n SchemaRegistry.installPackage(manifest);\n this.logger.debug('Installed Package', { id: manifest.id, name: manifest.name, namespace });\n\n // 2. Register owned objects\n if (manifest.objects) {\n if (Array.isArray(manifest.objects)) {\n this.logger.debug('Registering objects from manifest (Array)', { id, objectCount: manifest.objects.length });\n for (const objDef of manifest.objects) {\n const fqn = SchemaRegistry.registerObject(objDef, id, namespace, 'own');\n this.logger.debug('Registered Object', { fqn, from: id });\n }\n } else {\n this.logger.debug('Registering objects from manifest (Map)', { id, objectCount: Object.keys(manifest.objects).length });\n for (const [name, objDef] of Object.entries(manifest.objects)) {\n // Ensure name in definition matches key\n (objDef as any).name = name;\n const fqn = SchemaRegistry.registerObject(objDef as any, id, namespace, 'own');\n this.logger.debug('Registered Object', { fqn, from: id });\n }\n }\n }\n\n // 2b. Register object extensions (fields added to objects owned by other packages)\n if (Array.isArray(manifest.objectExtensions) && manifest.objectExtensions.length > 0) {\n this.logger.debug('Registering object extensions', { id, count: manifest.objectExtensions.length });\n for (const ext of manifest.objectExtensions) {\n const targetFqn = ext.extend;\n const priority = ext.priority ?? 200;\n // Create a partial object definition for the extension\n const extDef = {\n name: targetFqn, // Use the target FQN as name\n fields: ext.fields,\n label: ext.label,\n pluralLabel: ext.pluralLabel,\n description: ext.description,\n validations: ext.validations,\n indexes: ext.indexes,\n };\n // Register as extension (namespace is undefined since we're targeting by FQN)\n SchemaRegistry.registerObject(extDef as any, id, undefined, 'extend', priority);\n this.logger.debug('Registered Object Extension', { target: targetFqn, priority, from: id });\n }\n }\n\n // 3. Register apps (UI navigation definitions) as their own metadata type\n if (Array.isArray(manifest.apps) && manifest.apps.length > 0) {\n this.logger.debug('Registering apps from manifest', { id, count: manifest.apps.length });\n for (const app of manifest.apps) {\n const appName = app.name || app.id;\n if (appName) {\n SchemaRegistry.registerApp(app, id);\n this.logger.debug('Registered App', { app: appName, from: id });\n }\n }\n }\n\n // 4. If manifest itself looks like an App (has navigation), also register as app\n // This handles the case where the manifest IS the app definition (legacy/simple packages)\n if (manifest.name && manifest.navigation && !manifest.apps?.length) {\n SchemaRegistry.registerApp(manifest, id);\n this.logger.debug('Registered manifest-as-app', { app: manifest.name, from: id });\n }\n\n // 5. Register all other metadata types generically\n const metadataArrayKeys = [\n // UI Protocol\n 'actions', 'views', 'pages', 'dashboards', 'reports', 'themes',\n // Automation Protocol\n 'flows', 'workflows', 'approvals', 'webhooks',\n // Security Protocol\n 'roles', 'permissions', 'profiles', 'sharingRules', 'policies',\n // AI Protocol\n 'agents', 'ragPipelines',\n // API Protocol\n 'apis',\n // Data Extensions\n 'hooks', 'mappings', 'analyticsCubes',\n // Integration Protocol\n 'connectors',\n ];\n for (const key of metadataArrayKeys) {\n const items = (manifest as any)[key];\n if (Array.isArray(items) && items.length > 0) {\n this.logger.debug(`Registering ${key} from manifest`, { id, count: items.length });\n for (const item of items) {\n const itemName = item.name || item.id;\n if (itemName) {\n SchemaRegistry.registerItem(pluralToSingular(key), item, 'name' as any, id);\n }\n }\n }\n }\n\n // 6. Register seed data as metadata (keyed by target object name)\n const seedData = (manifest as any).data;\n if (Array.isArray(seedData) && seedData.length > 0) {\n this.logger.debug('Registering seed data datasets', { id, count: seedData.length });\n for (const dataset of seedData) {\n if (dataset.object) {\n SchemaRegistry.registerItem('data', dataset, 'object' as any, id);\n }\n }\n }\n\n // 6. Register contributions\n if (manifest.contributes?.kinds) {\n this.logger.debug('Registering kinds from manifest', { id, kindCount: manifest.contributes.kinds.length });\n for (const kind of manifest.contributes.kinds) {\n SchemaRegistry.registerKind(kind);\n this.logger.debug('Registered Kind', { kind: kind.name || kind.type, from: id });\n }\n }\n\n // 7. Recursively register nested plugins\n if (Array.isArray(manifest.plugins) && manifest.plugins.length > 0) {\n this.logger.debug('Processing nested plugins', { id, count: manifest.plugins.length });\n for (const plugin of manifest.plugins) {\n if (plugin && typeof plugin === 'object') {\n const pluginName = plugin.name || plugin.id || 'unnamed-plugin';\n this.logger.debug('Registering nested plugin', { pluginName, parentId: id });\n this.registerPlugin(plugin, id, namespace);\n }\n }\n }\n }\n\n /**\n * Register a nested plugin's metadata (objects, actions, views, etc.)\n *\n * Unlike registerApp(), this does NOT call SchemaRegistry.installPackage()\n * because plugins are not formal manifests — they are lightweight config\n * bundles with objects, actions, triggers, and navigation.\n *\n * @param plugin - The plugin config object\n * @param parentId - The parent package ID (for ownership tracking)\n * @param parentNamespace - The parent package's namespace (for FQN resolution)\n */\n private registerPlugin(plugin: any, parentId: string, parentNamespace?: string) {\n const pluginName = plugin.name || plugin.id || 'unnamed';\n const pluginNamespace = plugin.namespace || parentNamespace;\n\n // Use parentId as the owning package for namespace consistency.\n // The parent package already claimed the namespace — nested plugins\n // contribute objects UNDER the parent's ownership.\n const ownerId = parentId;\n\n // Register objects (supports both Array and Map formats)\n if (plugin.objects) {\n try {\n if (Array.isArray(plugin.objects)) {\n this.logger.debug('Registering plugin objects (Array)', { pluginName, count: plugin.objects.length });\n for (const objDef of plugin.objects) {\n const fqn = SchemaRegistry.registerObject(objDef, ownerId, pluginNamespace, 'own');\n this.logger.debug('Registered Object', { fqn, from: pluginName });\n }\n } else {\n const entries = Object.entries(plugin.objects);\n this.logger.debug('Registering plugin objects (Map)', { pluginName, count: entries.length });\n for (const [name, objDef] of entries) {\n (objDef as any).name = name;\n const fqn = SchemaRegistry.registerObject(objDef as any, ownerId, pluginNamespace, 'own');\n this.logger.debug('Registered Object', { fqn, from: pluginName });\n }\n }\n } catch (err: any) {\n this.logger.warn('Failed to register plugin objects', { pluginName, error: err.message });\n }\n }\n\n // Register plugin as app if it has navigation (for sidebar display)\n if (plugin.name && plugin.navigation) {\n try {\n SchemaRegistry.registerApp(plugin, ownerId);\n this.logger.debug('Registered plugin-as-app', { app: plugin.name, from: pluginName });\n } catch (err: any) {\n this.logger.warn('Failed to register plugin as app', { pluginName, error: err.message });\n }\n }\n\n // Register metadata arrays (actions, views, triggers, etc.)\n const metadataArrayKeys = [\n 'actions', 'views', 'pages', 'dashboards', 'reports', 'themes',\n 'flows', 'workflows', 'approvals', 'webhooks',\n 'roles', 'permissions', 'profiles', 'sharingRules', 'policies',\n 'agents', 'ragPipelines', 'apis',\n 'hooks', 'mappings', 'analyticsCubes', 'connectors',\n ];\n for (const key of metadataArrayKeys) {\n const items = (plugin as any)[key];\n if (Array.isArray(items) && items.length > 0) {\n for (const item of items) {\n const itemName = item.name || item.id;\n if (itemName) {\n SchemaRegistry.registerItem(pluralToSingular(key), item, 'name' as any, ownerId);\n }\n }\n }\n }\n }\n\n /**\n * Register a new storage driver\n */\n registerDriver(driver: DriverInterface, isDefault: boolean = false) {\n if (this.drivers.has(driver.name)) {\n this.logger.warn('Driver already registered, skipping', { driverName: driver.name });\n return;\n }\n\n this.drivers.set(driver.name, driver);\n this.logger.info('Registered driver', {\n driverName: driver.name,\n version: driver.version\n });\n\n if (isDefault || this.drivers.size === 1) {\n this.defaultDriver = driver.name;\n this.logger.info('Set default driver', { driverName: driver.name });\n }\n }\n\n /**\n * Set the realtime service for publishing data change events.\n * Should be called after kernel resolves the realtime service.\n *\n * @param service - An IRealtimeService instance for event publishing\n */\n setRealtimeService(service: IRealtimeService): void {\n this.realtimeService = service;\n this.logger.info('RealtimeService configured for data events');\n }\n\n /**\n * Helper to get object definition\n */\n getSchema(objectName: string): ServiceObject | undefined {\n return SchemaRegistry.getObject(objectName);\n }\n\n /**\n * Resolve an object name to its Fully Qualified Name (FQN).\n * \n * Short names like 'task' are resolved to FQN like 'todo__task'\n * via SchemaRegistry lookup. If no match is found, the name is\n * returned as-is (for ad-hoc / unregistered objects).\n * \n * This ensures that all driver operations use a consistent key\n * regardless of whether the caller uses the short name or FQN.\n */\n private resolveObjectName(name: string): string {\n const schema = SchemaRegistry.getObject(name);\n if (schema) {\n // Prefer the physical table name (e.g., 'sys_user') over the FQN\n // (e.g., 'sys__user'). ObjectSchema.create() auto-derives tableName\n // as {namespace}_{name} which matches the storage convention.\n return schema.tableName || schema.name;\n }\n return name; // Ad-hoc object, keep as-is\n }\n\n /**\n * Helper to get the target driver\n */\n private getDriver(objectName: string): DriverInterface {\n const object = SchemaRegistry.getObject(objectName);\n \n // 1. If object definition exists, check for explicit datasource\n if (object) {\n const datasourceName = object.datasource || 'default';\n \n // If configured for 'default', try to find the default driver\n if (datasourceName === 'default') {\n if (this.defaultDriver && this.drivers.has(this.defaultDriver)) {\n return this.drivers.get(this.defaultDriver)!;\n }\n } else {\n // Specific datasource requested\n if (this.drivers.has(datasourceName)) {\n return this.drivers.get(datasourceName)!;\n }\n throw new Error(`[ObjectQL] Datasource '${datasourceName}' configured for object '${objectName}' is not registered.`);\n }\n }\n\n // 2. Fallback for ad-hoc objects or missing definitions\n if (this.defaultDriver) {\n return this.drivers.get(this.defaultDriver)!;\n }\n\n throw new Error(`[ObjectQL] No driver available for object '${objectName}'`);\n }\n\n /**\n * Initialize the engine and all registered drivers\n */\n async init() {\n this.logger.info('Initializing ObjectQL engine', { \n driverCount: this.drivers.size,\n drivers: Array.from(this.drivers.keys())\n });\n \n const failedDrivers: string[] = [];\n for (const [name, driver] of this.drivers) {\n try {\n await driver.connect();\n this.logger.info('Driver connected successfully', { driverName: name });\n } catch (e) {\n failedDrivers.push(name);\n this.logger.error('Failed to connect driver', e as Error, { driverName: name });\n }\n }\n\n if (failedDrivers.length > 0) {\n this.logger.warn(\n `${failedDrivers.length} of ${this.drivers.size} driver(s) failed initial connect. ` +\n `Operations may recover via lazy reconnection or fail at query time.`,\n { failedDrivers }\n );\n }\n \n this.logger.info('ObjectQL engine initialization complete');\n }\n\n async destroy() {\n this.logger.info('Destroying ObjectQL engine', { driverCount: this.drivers.size });\n \n for (const [name, driver] of this.drivers.entries()) {\n try {\n await driver.disconnect();\n } catch (e) {\n this.logger.error('Error disconnecting driver', e as Error, { driverName: name });\n }\n }\n \n this.logger.info('ObjectQL engine destroyed');\n }\n\n // ============================================\n // Helper: Expand Related Records\n // ============================================\n\n /** Maximum depth for recursive expand to prevent infinite loops */\n private static readonly MAX_EXPAND_DEPTH = 3;\n\n /**\n * Post-process expand: resolve lookup/master_detail fields by batch-loading related records.\n * \n * This is a driver-agnostic implementation that uses secondary queries ($in batches)\n * to load related records, then injects them into the result set.\n * \n * @param objectName - The source object name\n * @param records - The records returned by the driver\n * @param expand - The expand map from QueryAST (field name → nested QueryAST)\n * @param depth - Current recursion depth (0-based)\n * @returns Records with expanded lookup fields (IDs replaced by full objects)\n */\n private async expandRelatedRecords(\n objectName: string,\n records: any[],\n expand: Record,\n depth: number = 0,\n ): Promise {\n if (!records || records.length === 0) return records;\n if (depth >= ObjectQL.MAX_EXPAND_DEPTH) return records;\n\n const objectSchema = SchemaRegistry.getObject(objectName);\n // If no schema registered, skip expand — return raw data\n if (!objectSchema || !objectSchema.fields) return records;\n\n for (const [fieldName, nestedAST] of Object.entries(expand)) {\n const fieldDef = objectSchema.fields[fieldName];\n\n // Skip if field not found or not a relationship type\n if (!fieldDef || !fieldDef.reference) continue;\n if (fieldDef.type !== 'lookup' && fieldDef.type !== 'master_detail') continue;\n\n const referenceObject = fieldDef.reference;\n\n // Collect all foreign key IDs from records (handle both single and multiple values)\n const allIds: any[] = [];\n for (const record of records) {\n const val = record[fieldName];\n if (val == null) continue;\n if (Array.isArray(val)) {\n allIds.push(...val.filter((id: any) => id != null));\n } else if (typeof val === 'object') {\n // Already expanded — skip\n continue;\n } else {\n allIds.push(val);\n }\n }\n\n // De-duplicate IDs\n const uniqueIds = [...new Set(allIds)];\n if (uniqueIds.length === 0) continue;\n\n // Batch-load related records using $in query\n try {\n const relatedQuery: QueryAST = {\n object: referenceObject,\n where: { id: { $in: uniqueIds } },\n ...(nestedAST.fields ? { fields: nestedAST.fields } : {}),\n ...(nestedAST.orderBy ? { orderBy: nestedAST.orderBy } : {}),\n };\n\n const driver = this.getDriver(referenceObject);\n const relatedRecords = await driver.find(referenceObject, relatedQuery) ?? [];\n\n // Build a lookup map: id → record\n const recordMap = new Map();\n for (const rec of relatedRecords) {\n const id = rec.id;\n if (id != null) recordMap.set(String(id), rec);\n }\n\n // Recursively expand nested relations if present\n if (nestedAST.expand && Object.keys(nestedAST.expand).length > 0) {\n const expandedRelated = await this.expandRelatedRecords(\n referenceObject,\n relatedRecords,\n nestedAST.expand,\n depth + 1,\n );\n // Rebuild map with expanded records\n recordMap.clear();\n for (const rec of expandedRelated) {\n const id = rec.id;\n if (id != null) recordMap.set(String(id), rec);\n }\n }\n\n // Inject expanded records back into the original result set\n for (const record of records) {\n const val = record[fieldName];\n if (val == null) continue;\n\n if (Array.isArray(val)) {\n record[fieldName] = val.map((id: any) => recordMap.get(String(id)) ?? id);\n } else if (typeof val !== 'object') {\n record[fieldName] = recordMap.get(String(val)) ?? val;\n }\n // If val is already an object, leave it as-is\n }\n } catch (e) {\n // Graceful degradation: if expand fails, keep original IDs\n this.logger.warn('Failed to expand relationship field; retaining foreign key IDs', {\n object: objectName,\n field: fieldName,\n reference: referenceObject,\n error: (e as Error).message,\n });\n }\n }\n\n return records;\n }\n\n // ============================================\n // Data Access Methods (IDataEngine Interface)\n // ============================================\n\n async find(object: string, query?: EngineQueryOptions): Promise {\n object = this.resolveObjectName(object);\n this.logger.debug('Find operation starting', { object, query });\n const driver = this.getDriver(object);\n const ast: QueryAST = { object, ...query };\n // Remove context from the AST — it's not a driver concern\n delete (ast as any).context;\n // Normalize OData `top` alias → standard `limit`\n if ((ast as any).top != null && ast.limit == null) {\n ast.limit = (ast as any).top;\n }\n delete (ast as any).top;\n\n const opCtx: OperationContext = {\n object,\n operation: 'find',\n ast,\n options: query,\n context: query?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const hookContext: HookContext = {\n object,\n event: 'beforeFind',\n input: { ast: opCtx.ast, options: opCtx.options },\n session: this.buildSession(opCtx.context),\n transaction: opCtx.context?.transaction,\n ql: this\n };\n await this.triggerHooks('beforeFind', hookContext);\n\n try {\n let result = await driver.find(object, hookContext.input.ast as QueryAST, hookContext.input.options as any);\n\n // Post-process: expand related records if expand is requested\n if (ast.expand && Object.keys(ast.expand).length > 0 && Array.isArray(result)) {\n result = await this.expandRelatedRecords(object, result, ast.expand, 0);\n }\n \n hookContext.event = 'afterFind';\n hookContext.result = result;\n await this.triggerHooks('afterFind', hookContext);\n \n return hookContext.result;\n } catch (e) {\n this.logger.error('Find operation failed', e as Error, { object });\n throw e;\n }\n });\n\n return opCtx.result as any[];\n }\n\n async findOne(objectName: string, query?: EngineQueryOptions): Promise {\n objectName = this.resolveObjectName(objectName);\n this.logger.debug('FindOne operation', { objectName });\n const driver = this.getDriver(objectName);\n const ast: QueryAST = { object: objectName, ...query, limit: 1 };\n // Remove context and top alias from the AST\n delete (ast as any).context;\n delete (ast as any).top;\n\n const opCtx: OperationContext = {\n object: objectName,\n operation: 'findOne',\n ast,\n options: query,\n context: query?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n let result = await driver.findOne(objectName, opCtx.ast as QueryAST);\n\n // Post-process: expand related records if expand is requested\n if (ast.expand && Object.keys(ast.expand).length > 0 && result != null) {\n const expanded = await this.expandRelatedRecords(objectName, [result], ast.expand, 0);\n result = expanded[0];\n }\n\n return result;\n });\n\n return opCtx.result;\n }\n\n async insert(object: string, data: any | any[], options?: DataEngineInsertOptions): Promise {\n object = this.resolveObjectName(object);\n this.logger.debug('Insert operation starting', { object, isBatch: Array.isArray(data) });\n const driver = this.getDriver(object);\n\n const opCtx: OperationContext = {\n object,\n operation: 'insert',\n data,\n options,\n context: options?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const hookContext: HookContext = {\n object,\n event: 'beforeInsert',\n input: { data: opCtx.data, options: opCtx.options },\n session: this.buildSession(opCtx.context),\n transaction: opCtx.context?.transaction,\n ql: this\n };\n await this.triggerHooks('beforeInsert', hookContext);\n\n try {\n let result;\n if (Array.isArray(hookContext.input.data)) {\n // Bulk Create\n if (driver.bulkCreate) {\n result = await driver.bulkCreate(object, hookContext.input.data as any[], hookContext.input.options as any);\n } else {\n // Fallback loop\n result = await Promise.all((hookContext.input.data as any[]).map((item: any) => driver.create(object, item, hookContext.input.options as any)));\n }\n } else {\n result = await driver.create(object, hookContext.input.data as Record, hookContext.input.options as any);\n }\n\n hookContext.event = 'afterInsert';\n hookContext.result = result;\n await this.triggerHooks('afterInsert', hookContext);\n\n // Publish data.record.created event to realtime service\n if (this.realtimeService) {\n try {\n if (Array.isArray(result)) {\n // Bulk insert - publish event for each record\n for (const record of result) {\n const event: RealtimeEventPayload = {\n type: 'data.record.created',\n object,\n payload: {\n recordId: record.id,\n after: record,\n },\n timestamp: new Date().toISOString(),\n };\n await this.realtimeService.publish(event);\n }\n this.logger.debug(`Published ${result.length} data.record.created events`, { object });\n } else {\n const event: RealtimeEventPayload = {\n type: 'data.record.created',\n object,\n payload: {\n recordId: result.id,\n after: result,\n },\n timestamp: new Date().toISOString(),\n };\n await this.realtimeService.publish(event);\n this.logger.debug('Published data.record.created event', { object, recordId: result.id });\n }\n } catch (error) {\n this.logger.warn('Failed to publish data event', { object, error });\n }\n }\n\n return hookContext.result;\n } catch (e) {\n this.logger.error('Insert operation failed', e as Error, { object });\n throw e;\n }\n });\n\n return opCtx.result;\n }\n\n async update(object: string, data: any, options?: EngineUpdateOptions): Promise {\n object = this.resolveObjectName(object);\n this.logger.debug('Update operation starting', { object });\n const driver = this.getDriver(object);\n \n // 1. Extract ID from data or where if it's a single update by ID\n let id = data.id;\n if (!id && options?.where && typeof options.where === 'object' && 'id' in options.where) {\n id = (options.where as Record).id;\n }\n\n const opCtx: OperationContext = {\n object,\n operation: 'update',\n data,\n options,\n context: options?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const hookContext: HookContext = {\n object,\n event: 'beforeUpdate',\n input: { id, data: opCtx.data, options: opCtx.options },\n session: this.buildSession(opCtx.context),\n transaction: opCtx.context?.transaction,\n ql: this\n };\n await this.triggerHooks('beforeUpdate', hookContext);\n\n try {\n let result;\n if (hookContext.input.id) {\n result = await driver.update(object, hookContext.input.id as string, hookContext.input.data as Record, hookContext.input.options as any);\n } else if (options?.multi && driver.updateMany) {\n const ast: QueryAST = { object, where: options.where };\n result = await driver.updateMany(object, ast, hookContext.input.data as Record, hookContext.input.options as any);\n } else {\n throw new Error('Update requires an ID or options.multi=true');\n }\n\n hookContext.event = 'afterUpdate';\n hookContext.result = result;\n await this.triggerHooks('afterUpdate', hookContext);\n\n // Publish data.record.updated event to realtime service\n if (this.realtimeService) {\n try {\n const resultId = (typeof result === 'object' && result && 'id' in result) ? (result as any).id : undefined;\n const recordId = String(hookContext.input.id || resultId || '');\n const event: RealtimeEventPayload = {\n type: 'data.record.updated',\n object,\n payload: {\n recordId,\n changes: hookContext.input.data,\n after: result,\n },\n timestamp: new Date().toISOString(),\n };\n await this.realtimeService.publish(event);\n this.logger.debug('Published data.record.updated event', { object, recordId });\n } catch (error) {\n this.logger.warn('Failed to publish data event', { object, error });\n }\n }\n\n return hookContext.result;\n } catch (e) {\n this.logger.error('Update operation failed', e as Error, { object });\n throw e;\n }\n });\n\n return opCtx.result;\n }\n\n async delete(object: string, options?: EngineDeleteOptions): Promise {\n object = this.resolveObjectName(object);\n this.logger.debug('Delete operation starting', { object });\n const driver = this.getDriver(object);\n\n // Extract ID logic similar to update\n let id: any = undefined;\n if (options?.where && typeof options.where === 'object' && 'id' in options.where) {\n id = (options.where as Record).id;\n }\n\n const opCtx: OperationContext = {\n object,\n operation: 'delete',\n options,\n context: options?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const hookContext: HookContext = {\n object,\n event: 'beforeDelete',\n input: { id, options: opCtx.options },\n session: this.buildSession(opCtx.context),\n transaction: opCtx.context?.transaction,\n ql: this\n };\n await this.triggerHooks('beforeDelete', hookContext);\n\n try {\n let result;\n if (hookContext.input.id) {\n result = await driver.delete(object, hookContext.input.id as string, hookContext.input.options as any);\n } else if (options?.multi && driver.deleteMany) {\n const ast: QueryAST = { object, where: options.where };\n result = await driver.deleteMany(object, ast, hookContext.input.options as any);\n } else {\n throw new Error('Delete requires an ID or options.multi=true');\n }\n\n hookContext.event = 'afterDelete';\n hookContext.result = result;\n await this.triggerHooks('afterDelete', hookContext);\n\n // Publish data.record.deleted event to realtime service\n if (this.realtimeService) {\n try {\n const resultId = (typeof result === 'object' && result && 'id' in result) ? (result as any).id : undefined;\n const recordId = String(hookContext.input.id || resultId || '');\n const event: RealtimeEventPayload = {\n type: 'data.record.deleted',\n object,\n payload: {\n recordId,\n },\n timestamp: new Date().toISOString(),\n };\n await this.realtimeService.publish(event);\n this.logger.debug('Published data.record.deleted event', { object, recordId });\n } catch (error) {\n this.logger.warn('Failed to publish data event', { object, error });\n }\n }\n\n return hookContext.result;\n } catch (e) {\n this.logger.error('Delete operation failed', e as Error, { object });\n throw e;\n }\n });\n\n return opCtx.result;\n }\n\n async count(object: string, query?: EngineCountOptions): Promise {\n object = this.resolveObjectName(object);\n const driver = this.getDriver(object);\n\n const opCtx: OperationContext = {\n object,\n operation: 'count',\n options: query,\n context: query?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n if (driver.count) {\n const ast: QueryAST = { object, where: query?.where };\n return driver.count(object, ast);\n }\n // Fallback to find().length\n const res = await this.find(object, { where: query?.where, fields: ['id'] });\n return res.length;\n });\n\n return opCtx.result as number;\n }\n\n async aggregate(object: string, query: EngineAggregateOptions): Promise {\n object = this.resolveObjectName(object);\n const driver = this.getDriver(object);\n this.logger.debug(`Aggregate on ${object} using ${driver.name}`, query);\n\n const opCtx: OperationContext = {\n object,\n operation: 'aggregate',\n options: query,\n context: query?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const ast: QueryAST = {\n object,\n where: query.where,\n groupBy: query.groupBy,\n aggregations: query.aggregations,\n };\n\n return driver.find(object, ast);\n });\n\n return opCtx.result as any[];\n }\n \n async execute(command: any, options?: Record): Promise {\n // Direct pass-through implies we know which driver to use?\n // Usually execute is tied to a specific object context OR we need a way to select driver.\n // If command has 'object', we use that.\n if (options?.object) {\n const driver = this.getDriver(options.object);\n if (driver.execute) {\n return driver.execute(command, undefined, options);\n }\n }\n throw new Error('Execute requires options.object to select driver');\n }\n\n // ============================================\n // Compatibility / Convenience API\n // ============================================\n // These methods provide a higher-level API matching the @objectql/core\n // ObjectQL interface, enabling painless migration from the legacy layer.\n\n /**\n * Register a single object definition.\n * \n * Proxies to SchemaRegistry.registerObject() with sensible defaults.\n * Fields without a `name` property are auto-assigned from their key.\n */\n registerObject(\n schema: ServiceObject,\n packageId: string = '__runtime__',\n namespace?: string\n ): string {\n // Auto-assign field names from keys\n if (schema.fields) {\n for (const [key, field] of Object.entries(schema.fields)) {\n if (field && typeof field === 'object' && !('name' in field)) {\n (field as any).name = key;\n }\n }\n }\n return SchemaRegistry.registerObject(schema, packageId, namespace);\n }\n\n /**\n * Unregister a single object by name.\n */\n unregisterObject(name: string, packageId?: string): void {\n if (packageId) {\n SchemaRegistry.unregisterObjectsByPackage(packageId);\n } else {\n // Remove from generic metadata as fallback\n SchemaRegistry.unregisterItem('object', name);\n }\n }\n\n /**\n * Get an object definition by name.\n * Alias for getSchema() — matches @objectql/core API.\n */\n getObject(name: string): ServiceObject | undefined {\n return this.getSchema(name);\n }\n\n /**\n * Get all registered object configs as a name→config map.\n * Matches @objectql/core getConfigs() API.\n */\n getConfigs(): Record {\n const result: Record = {};\n const objects = SchemaRegistry.getAllObjects();\n for (const obj of objects) {\n if (obj.name) {\n result[obj.name] = obj;\n }\n }\n return result;\n }\n\n /**\n * Get a registered driver by datasource name.\n * \n * Unlike the private getDriver() (which resolves by object name),\n * this method directly looks up a driver by its registered name.\n */\n getDriverByName(name: string): DriverInterface | undefined {\n return this.drivers.get(name);\n }\n\n /**\n * Get the driver responsible for the given object.\n *\n * Resolves datasource binding from the object's schema definition,\n * falling back to the default driver. This is a public version of\n * the internal getDriver() used by CRUD operations.\n *\n * @param objectName - FQN or short name of the registered object.\n * @returns The resolved DriverInterface, or undefined if no driver is available.\n */\n getDriverForObject(objectName: string): DriverInterface | undefined {\n try {\n return this.getDriver(objectName);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Get a registered driver by datasource name.\n * Alias matching @objectql/core datasource() API.\n * \n * @throws Error if the datasource is not found\n */\n datasource(name: string): DriverInterface {\n const driver = this.drivers.get(name);\n if (!driver) {\n throw new Error(`[ObjectQL] Datasource '${name}' not found`);\n }\n return driver;\n }\n\n /**\n * Register a hook handler.\n * Convenience alias for registerHook() matching @objectql/core on() API.\n * \n * Usage:\n * ql.on('beforeInsert', 'user', async (ctx) => { ... });\n */\n on(\n event: string,\n objectName: string,\n handler: (ctx: HookContext) => Promise | void,\n packageId?: string\n ): void {\n this.registerHook(event, handler, { object: objectName, packageId });\n }\n\n /**\n * Remove all hooks, actions, and objects contributed by a package.\n */\n removePackage(packageId: string): void {\n // Remove hooks\n for (const [key, handlers] of this.hooks.entries()) {\n const filtered = handlers.filter(h => h.packageId !== packageId);\n if (filtered.length !== handlers.length) {\n this.hooks.set(key, filtered);\n }\n }\n // Remove actions\n this.removeActionsByPackage(packageId);\n // Remove objects\n SchemaRegistry.unregisterObjectsByPackage(packageId, true);\n }\n\n /**\n * Gracefully shut down the engine, disconnecting all drivers.\n * Alias for destroy() — matches @objectql/core close() API.\n */\n async close(): Promise {\n return this.destroy();\n }\n\n /**\n * Create a scoped execution context bound to this engine.\n * \n * Usage:\n * const ctx = engine.createContext({ userId: '...', tenantId: '...' });\n * const users = ctx.object('user');\n * await users.find({ filter: { status: 'active' } });\n */\n createContext(ctx: Partial): ScopedContext {\n return new ScopedContext(\n ExecutionContextSchema.parse(ctx),\n this\n );\n }\n\n /**\n * Static factory: create a fully configured ObjectQL instance.\n * \n * Matches @objectql/core's `new ObjectQL(config)` pattern but also\n * registers drivers and objects, then calls init().\n * \n * Usage:\n * const ql = await ObjectQL.create({\n * datasources: { default: myDriver },\n * objects: { user: { name: 'user', fields: { ... } } }\n * });\n */\n static async create(config: {\n datasources?: Record;\n objects?: Record;\n hooks?: Array<{ event: string; object: string; handler: (ctx: HookContext) => Promise | void }>;\n }): Promise {\n const ql = new ObjectQL();\n\n // Register drivers\n if (config.datasources) {\n for (const [name, driver] of Object.entries(config.datasources)) {\n // Set driver name if not already set\n if (!driver.name) {\n (driver as any).name = name;\n }\n ql.registerDriver(driver, name === 'default');\n }\n }\n\n // Register objects\n if (config.objects) {\n for (const [_key, schema] of Object.entries(config.objects)) {\n ql.registerObject(schema);\n }\n }\n\n // Register hooks\n if (config.hooks) {\n for (const hook of config.hooks) {\n ql.on(hook.event, hook.object, hook.handler);\n }\n }\n\n // Initialize (connect drivers)\n await ql.init();\n\n return ql;\n }\n}\n\n/**\n * Repository scoped to a single object, bound to an execution context.\n *\n * Provides both IDataEngine-style methods (find, insert, update, delete)\n * and convenience aliases (create, updateById, deleteById) matching\n * the @objectql/core ObjectRepository API.\n */\nexport class ObjectRepository {\n constructor(\n private objectName: string,\n private context: ExecutionContext,\n private engine: IDataEngine & { executeAction?: (o: string, a: string, c: any) => Promise }\n ) {}\n\n async find(query: any = {}): Promise {\n return this.engine.find(this.objectName, {\n ...query,\n context: this.context,\n });\n }\n\n async findOne(query: any = {}): Promise {\n return this.engine.findOne(this.objectName, {\n ...query,\n context: this.context,\n });\n }\n\n async insert(data: any): Promise {\n return this.engine.insert(this.objectName, data, {\n context: this.context,\n });\n }\n\n /** Alias for insert() — matches @objectql/core convention */\n async create(data: any): Promise {\n return this.insert(data);\n }\n\n async update(data: any, options: any = {}): Promise {\n return this.engine.update(this.objectName, data, {\n ...options,\n context: this.context,\n });\n }\n\n /** Update a single record by ID */\n async updateById(id: string | number, data: any): Promise {\n return this.engine.update(this.objectName, { ...data, id: id }, {\n where: { id: id },\n context: this.context,\n });\n }\n\n async delete(options: any = {}): Promise {\n return this.engine.delete(this.objectName, {\n ...options,\n context: this.context,\n });\n }\n\n /** Delete a single record by ID */\n async deleteById(id: string | number): Promise {\n return this.engine.delete(this.objectName, {\n where: { id: id },\n context: this.context,\n });\n }\n\n async count(query: any = {}): Promise {\n return this.engine.count(this.objectName, {\n ...query,\n context: this.context,\n });\n }\n\n /** Aggregate query */\n async aggregate(query: any = {}): Promise {\n return this.engine.aggregate(this.objectName, {\n ...query,\n context: this.context,\n });\n }\n\n /** Execute a named action registered on this object */\n async execute(actionName: string, params?: any): Promise {\n if (this.engine.executeAction) {\n return this.engine.executeAction(this.objectName, actionName, {\n ...params,\n userId: this.context.userId,\n tenantId: this.context.tenantId,\n roles: this.context.roles,\n });\n }\n throw new Error(`Actions not supported by engine`);\n }\n}\n\n/**\n * Scoped execution context with object() accessor.\n * \n * Provides identity (userId, tenantId/spaceId, roles),\n * repository access via object(), privilege escalation via sudo(),\n * and transactional execution via transaction().\n */\nexport class ScopedContext {\n constructor(\n private executionContext: ExecutionContext,\n private engine: IDataEngine\n ) {}\n\n /** Get a repository scoped to this context */\n object(name: string): ObjectRepository {\n return new ObjectRepository(name, this.executionContext, this.engine as any);\n }\n\n /** Create an elevated (system) context */\n sudo(): ScopedContext {\n return new ScopedContext(\n { ...this.executionContext, isSystem: true },\n this.engine\n );\n }\n\n /**\n * Execute a callback within a database transaction.\n *\n * The callback receives a new ScopedContext whose operations\n * share the same transaction handle. If the callback throws,\n * the transaction is rolled back; otherwise it is committed.\n *\n * Falls back to non-transactional execution if the driver\n * does not support transactions.\n */\n async transaction(callback: (trxCtx: ScopedContext) => Promise): Promise {\n const engine = this.engine as any;\n\n // Find the default driver for transaction support\n const driver = engine.defaultDriver\n ? engine.drivers?.get(engine.defaultDriver)\n : undefined;\n\n if (!driver?.beginTransaction) {\n // No transaction support — execute directly\n return callback(this);\n }\n\n const trx = await driver.beginTransaction();\n const trxCtx = new ScopedContext(\n { ...this.executionContext, transaction: trx },\n this.engine\n );\n\n try {\n const result = await callback(trxCtx);\n if (driver.commit) await driver.commit(trx);\n else if (driver.commitTransaction) await driver.commitTransaction(trx);\n return result;\n } catch (error) {\n if (driver.rollback) await driver.rollback(trx);\n else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx);\n throw error;\n }\n }\n\n get userId() { return this.executionContext.userId; }\n get tenantId() { return this.executionContext.tenantId; }\n /** Alias for tenantId — matches ObjectQLContext.spaceId convention */\n get spaceId() { return this.executionContext.tenantId; }\n get roles() { return this.executionContext.roles; }\n get isSystem() { return this.executionContext.isSystem; }\n\n /** Internal: expose the transaction handle for driver-level access */\n get transactionHandle() { return this.executionContext.transaction; }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { SchemaRegistry } from './registry.js';\n\n/**\n * MetadataFacade\n * \n * Provides a clean, injectable interface over SchemaRegistry.\n * Registered as the 'metadata' kernel service to eliminate\n * downstream packages needing to manually wrap SchemaRegistry.\n * \n * Implements the async IMetadataService interface.\n * Internally delegates to SchemaRegistry (in-memory) with Promise wrappers.\n */\nexport class MetadataFacade {\n /**\n * Register a metadata item\n */\n async register(type: string, name: string, data: any): Promise {\n const definition = typeof data === 'object' && data !== null\n ? { ...data, name: data.name ?? name }\n : data;\n if (type === 'object') {\n SchemaRegistry.registerItem(type, definition, 'name' as any);\n } else {\n SchemaRegistry.registerItem(type, definition, definition.id ? 'id' as any : 'name' as any);\n }\n }\n\n /**\n * Get a metadata item by type and name\n */\n async get(type: string, name: string): Promise {\n const item = SchemaRegistry.getItem(type, name) as any;\n return item?.content ?? item;\n }\n\n /**\n * Get the raw entry (with metadata wrapper)\n */\n getEntry(type: string, name: string): any {\n return SchemaRegistry.getItem(type, name);\n }\n\n /**\n * List all items of a type\n */\n async list(type: string): Promise {\n const items = SchemaRegistry.listItems(type);\n return items.map((item: any) => item?.content ?? item);\n }\n\n /**\n * Unregister a metadata item\n */\n async unregister(type: string, name: string): Promise {\n SchemaRegistry.unregisterItem(type, name);\n }\n\n /**\n * Check if a metadata item exists\n */\n async exists(type: string, name: string): Promise {\n const item = SchemaRegistry.getItem(type, name);\n return item !== undefined && item !== null;\n }\n\n /**\n * List all names of metadata items of a given type\n */\n async listNames(type: string): Promise {\n const items = SchemaRegistry.listItems(type);\n return items.map((item: any) => item?.name ?? item?.content?.name ?? '').filter(Boolean);\n }\n\n /**\n * Unregister all metadata from a package\n */\n async unregisterPackage(packageName: string): Promise {\n SchemaRegistry.unregisterObjectsByPackage(packageName);\n }\n\n /**\n * Convenience: get object definition\n */\n async getObject(name: string): Promise {\n return SchemaRegistry.getObject(name);\n }\n\n /**\n * Convenience: list all objects\n */\n async listObjects(): Promise {\n return SchemaRegistry.getAllObjects();\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectQL } from './engine.js';\nimport { ObjectStackProtocolImplementation } from './protocol.js';\nimport { Plugin, PluginContext } from '@objectstack/core';\n\nexport type { Plugin, PluginContext };\n\n/**\n * Protocol extension for DB-based metadata hydration.\n * `loadMetaFromDb` is implemented by ObjectStackProtocolImplementation but\n * is NOT (yet) part of the canonical ObjectStackProtocol wire-contract in\n * `@objectstack/spec`, since it is a server-side bootstrap concern only.\n */\ninterface ProtocolWithDbRestore {\n loadMetaFromDb(): Promise<{ loaded: number; errors: number }>;\n}\n\n/** Type guard — checks whether the service exposes `loadMetaFromDb`. */\nfunction hasLoadMetaFromDb(service: unknown): service is ProtocolWithDbRestore {\n return (\n typeof service === 'object' &&\n service !== null &&\n typeof (service as Record)['loadMetaFromDb'] === 'function'\n );\n}\n\nexport class ObjectQLPlugin implements Plugin {\n name = 'com.objectstack.engine.objectql';\n type = 'objectql';\n version = '1.0.0';\n \n private ql: ObjectQL | undefined;\n private hostContext?: Record;\n\n constructor(ql?: ObjectQL, hostContext?: Record) {\n if (ql) {\n this.ql = ql;\n } else {\n this.hostContext = hostContext;\n // Lazily created in init\n }\n }\n\n init = async (ctx: PluginContext) => {\n if (!this.ql) {\n // Pass kernel logger to engine to avoid creating a separate pino instance\n const hostCtx = { ...this.hostContext, logger: ctx.logger };\n this.ql = new ObjectQL(hostCtx);\n }\n \n // Register as provider for Core Kernel Services\n ctx.registerService('objectql', this.ql);\n\n ctx.registerService('data', this.ql); // ObjectQL implements IDataEngine\n\n // Register manifest service for direct app/package registration.\n // Plugins call ctx.getService('manifest').register(manifestData)\n // instead of the legacy ctx.registerService('app.', manifestData) convention.\n const ql = this.ql;\n ctx.registerService('manifest', {\n register: (manifest: any) => {\n ql.registerApp(manifest);\n ctx.logger.debug('Manifest registered via manifest service', {\n id: manifest.id || manifest.name\n });\n }\n });\n\n ctx.logger.info('ObjectQL engine registered', {\n services: ['objectql', 'data', 'manifest'],\n });\n\n // Register Protocol Implementation\n const protocolShim = new ObjectStackProtocolImplementation(\n this.ql, \n () => ctx.getServices ? ctx.getServices() : new Map()\n );\n\n ctx.registerService('protocol', protocolShim);\n ctx.logger.info('Protocol service registered');\n }\n\n start = async (ctx: PluginContext) => {\n ctx.logger.info('ObjectQL engine starting...');\n\n // Sync from external metadata service (e.g. MetadataPlugin) if available\n try {\n const metadataService = ctx.getService('metadata') as any;\n if (metadataService && typeof metadataService.loadMany === 'function' && this.ql) {\n await this.loadMetadataFromService(metadataService, ctx);\n }\n } catch (e: any) {\n ctx.logger.debug('No external metadata service to sync from');\n }\n \n // Discover features from Kernel Services\n if (ctx.getServices && this.ql) {\n const services = ctx.getServices();\n for (const [name, service] of services.entries()) {\n if (name.startsWith('driver.')) {\n // Register Driver\n this.ql.registerDriver(service);\n ctx.logger.debug('Discovered and registered driver service', { serviceName: name });\n }\n if (name.startsWith('app.')) {\n // Legacy fallback: discover app.* services (DEPRECATED)\n ctx.logger.warn(\n `[DEPRECATED] Service \"${name}\" uses legacy app.* convention. ` +\n `Migrate to ctx.getService('manifest').register(data).`\n );\n this.ql.registerApp(service); // service is Manifest\n ctx.logger.debug('Discovered and registered app service (legacy)', { serviceName: name });\n }\n }\n\n // Bridge realtime service from kernel service registry to ObjectQL.\n // RealtimeServicePlugin registers as 'realtime' service during init().\n // This enables ObjectQL to publish data change events.\n try {\n const realtimeService = ctx.getService('realtime');\n if (realtimeService && typeof realtimeService === 'object' && 'publish' in realtimeService) {\n ctx.logger.info('[ObjectQLPlugin] Bridging realtime service to ObjectQL for event publishing');\n this.ql.setRealtimeService(realtimeService as any);\n }\n } catch (e: any) {\n ctx.logger.debug('[ObjectQLPlugin] No realtime service found — data events will not be published', {\n error: e.message,\n });\n }\n }\n\n // Initialize drivers (calls driver.connect() which sets up persistence)\n await this.ql?.init();\n\n // Restore persisted metadata from sys_metadata table.\n // This hydrates SchemaRegistry with objects/views/apps that were saved\n // via protocol.saveMetaItem() in a previous session, ensuring custom\n // schemas survive cold starts and redeployments.\n await this.restoreMetadataFromDb(ctx);\n\n // Sync all registered object schemas to database\n // This ensures tables/collections are created or updated for every\n // object registered by plugins (e.g., sys_user from plugin-auth).\n await this.syncRegisteredSchemas(ctx);\n\n // Bridge all SchemaRegistry objects to metadata service\n // This ensures AI tools and other IMetadataService consumers can see all objects\n await this.bridgeObjectsToMetadataService(ctx);\n\n // Register built-in audit hooks\n this.registerAuditHooks(ctx);\n\n // Register tenant isolation middleware\n this.registerTenantMiddleware(ctx);\n\n ctx.logger.info('ObjectQL engine started', {\n driversRegistered: this.ql?.['drivers']?.size || 0,\n objectsRegistered: this.ql?.registry?.getAllObjects?.()?.length || 0\n });\n }\n\n /**\n * Register built-in audit hooks for auto-stamping created_by/updated_by\n * and fetching previousData for update/delete operations.\n */\n private registerAuditHooks(ctx: PluginContext) {\n if (!this.ql) return;\n\n // Auto-stamp created_by/updated_by on insert\n this.ql.registerHook('beforeInsert', async (hookCtx) => {\n if (hookCtx.session?.userId && hookCtx.input?.data) {\n const data = hookCtx.input.data as Record;\n if (typeof data === 'object' && data !== null) {\n data.created_by = data.created_by ?? hookCtx.session.userId;\n data.updated_by = hookCtx.session.userId;\n data.created_at = data.created_at ?? new Date().toISOString();\n data.updated_at = new Date().toISOString();\n if (hookCtx.session.tenantId) {\n data.tenant_id = data.tenant_id ?? hookCtx.session.tenantId;\n }\n }\n }\n }, { object: '*', priority: 10 });\n\n // Auto-stamp updated_by on update\n this.ql.registerHook('beforeUpdate', async (hookCtx) => {\n if (hookCtx.session?.userId && hookCtx.input?.data) {\n const data = hookCtx.input.data as Record;\n if (typeof data === 'object' && data !== null) {\n data.updated_by = hookCtx.session.userId;\n data.updated_at = new Date().toISOString();\n }\n }\n }, { object: '*', priority: 10 });\n\n // Auto-fetch previousData for update hooks\n this.ql.registerHook('beforeUpdate', async (hookCtx) => {\n if (hookCtx.input?.id && !hookCtx.previous) {\n try {\n const existing = await this.ql!.findOne(hookCtx.object, {\n where: { id: hookCtx.input.id }\n });\n if (existing) {\n hookCtx.previous = existing;\n }\n } catch (_e) {\n // Non-fatal: some objects may not support findOne\n }\n }\n }, { object: '*', priority: 5 });\n\n // Auto-fetch previousData for delete hooks\n this.ql.registerHook('beforeDelete', async (hookCtx) => {\n if (hookCtx.input?.id && !hookCtx.previous) {\n try {\n const existing = await this.ql!.findOne(hookCtx.object, {\n where: { id: hookCtx.input.id }\n });\n if (existing) {\n hookCtx.previous = existing;\n }\n } catch (_e) {\n // Non-fatal\n }\n }\n }, { object: '*', priority: 5 });\n\n ctx.logger.debug('Audit hooks registered (created_by/updated_by, previousData)');\n }\n\n /**\n * Register tenant isolation middleware that auto-injects tenant_id filter\n * for multi-tenant operations.\n */\n private registerTenantMiddleware(ctx: PluginContext) {\n if (!this.ql) return;\n\n this.ql.registerMiddleware(async (opCtx, next) => {\n // Only apply to operations with tenantId that are not system-level\n if (!opCtx.context?.tenantId || opCtx.context?.isSystem) {\n return next();\n }\n\n // Read operations: inject tenant_id filter into AST\n if (['find', 'findOne', 'count', 'aggregate'].includes(opCtx.operation)) {\n if (opCtx.ast) {\n const tenantFilter = { tenant_id: opCtx.context.tenantId };\n if (opCtx.ast.where) {\n opCtx.ast.where = { $and: [opCtx.ast.where, tenantFilter] };\n } else {\n opCtx.ast.where = tenantFilter;\n }\n }\n }\n\n await next();\n });\n\n ctx.logger.debug('Tenant isolation middleware registered');\n }\n\n /**\n * Synchronize all registered object schemas to the database.\n *\n * Groups objects by their responsible driver, then:\n * - If the driver advertises `supports.batchSchemaSync` and implements\n * `syncSchemasBatch()`, submits all schemas in a single call (reducing\n * network round-trips for remote drivers like Turso).\n * - Otherwise falls back to sequential `syncSchema()` per object.\n *\n * This is idempotent — drivers must tolerate repeated calls without\n * duplicating tables or erroring out.\n *\n * Drivers that do not implement `syncSchema` are silently skipped.\n */\n private async syncRegisteredSchemas(ctx: PluginContext) {\n if (!this.ql) return;\n\n const allObjects = this.ql.registry?.getAllObjects?.() ?? [];\n if (allObjects.length === 0) return;\n\n let synced = 0;\n let skipped = 0;\n\n // Group objects by driver for potential batch optimization\n const driverGroups = new Map>();\n\n for (const obj of allObjects) {\n const driver = this.ql.getDriverForObject(obj.name);\n if (!driver) {\n ctx.logger.debug('No driver available for object, skipping schema sync', {\n object: obj.name,\n });\n skipped++;\n continue;\n }\n\n if (typeof driver.syncSchema !== 'function') {\n ctx.logger.debug('Driver does not support syncSchema, skipping', {\n object: obj.name,\n driver: driver.name,\n });\n skipped++;\n continue;\n }\n\n const tableName = obj.tableName || obj.name;\n\n let group = driverGroups.get(driver);\n if (!group) {\n group = [];\n driverGroups.set(driver, group);\n }\n group.push({ obj, tableName });\n }\n\n // Process each driver group\n for (const [driver, entries] of driverGroups) {\n // Batch path: driver supports batch schema sync\n if (\n driver.supports?.batchSchemaSync &&\n typeof driver.syncSchemasBatch === 'function'\n ) {\n const batchPayload = entries.map((e) => ({\n object: e.tableName,\n schema: e.obj,\n }));\n try {\n await driver.syncSchemasBatch(batchPayload);\n synced += entries.length;\n ctx.logger.debug('Batch schema sync succeeded', {\n driver: driver.name,\n count: entries.length,\n });\n } catch (e: unknown) {\n ctx.logger.warn('Batch schema sync failed, falling back to sequential', {\n driver: driver.name,\n error: e instanceof Error ? e.message : String(e),\n });\n // Fallback: sequential sync for this driver's objects\n for (const { obj, tableName } of entries) {\n try {\n await driver.syncSchema(tableName, obj);\n synced++;\n } catch (seqErr: unknown) {\n ctx.logger.warn('Failed to sync schema for object', {\n object: obj.name,\n tableName,\n driver: driver.name,\n error: seqErr instanceof Error ? seqErr.message : String(seqErr),\n });\n }\n }\n }\n } else {\n // Sequential path: no batch support\n for (const { obj, tableName } of entries) {\n try {\n await driver.syncSchema(tableName, obj);\n synced++;\n } catch (e: unknown) {\n ctx.logger.warn('Failed to sync schema for object', {\n object: obj.name,\n tableName,\n driver: driver.name,\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n }\n }\n\n if (synced > 0 || skipped > 0) {\n ctx.logger.info('Schema sync complete', { synced, skipped, total: allObjects.length });\n }\n }\n\n /**\n * Restore persisted metadata from the database (sys_metadata) on startup.\n *\n * Calls `protocol.loadMetaFromDb()` to bulk-load all active metadata\n * records (objects, views, apps, etc.) into the in-memory SchemaRegistry.\n * This closes the persistence loop so that user-created schemas survive\n * kernel cold starts and redeployments.\n *\n * Gracefully degrades when:\n * - The protocol service is unavailable (e.g., in-memory-only mode).\n * - `loadMetaFromDb` is not implemented by the protocol shim.\n * - The underlying driver/table does not exist yet (first-run scenario).\n */\n private async restoreMetadataFromDb(ctx: PluginContext): Promise {\n // Phase 1: Resolve protocol service (separate from DB I/O for clearer diagnostics)\n let protocol: ProtocolWithDbRestore;\n try {\n const service = ctx.getService('protocol');\n if (!service || !hasLoadMetaFromDb(service)) {\n ctx.logger.debug('Protocol service does not support loadMetaFromDb, skipping DB restore');\n return;\n }\n protocol = service;\n } catch (e: unknown) {\n ctx.logger.debug('Protocol service unavailable, skipping DB restore', {\n error: e instanceof Error ? e.message : String(e),\n });\n return;\n }\n\n // Phase 2: DB hydration (loads into SchemaRegistry)\n try {\n const { loaded, errors } = await protocol.loadMetaFromDb();\n\n if (loaded > 0 || errors > 0) {\n ctx.logger.info('Metadata restored from database to SchemaRegistry', { loaded, errors });\n } else {\n ctx.logger.debug('No persisted metadata found in database');\n }\n } catch (e: unknown) {\n // Non-fatal: first-run or in-memory driver may not have sys_metadata yet\n ctx.logger.debug('DB metadata restore failed (non-fatal)', {\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n /**\n * Bridge all SchemaRegistry objects to the metadata service.\n *\n * This ensures objects registered by plugins and loaded from sys_metadata\n * are visible to AI tools and other consumers that query IMetadataService.\n *\n * Runs after both restoreMetadataFromDb() and syncRegisteredSchemas() to\n * catch all objects in the SchemaRegistry regardless of their source.\n */\n private async bridgeObjectsToMetadataService(ctx: PluginContext): Promise {\n try {\n const metadataService = ctx.getService('metadata');\n if (!metadataService || typeof metadataService.register !== 'function') {\n ctx.logger.debug('Metadata service unavailable for bridging, skipping');\n return;\n }\n\n if (!this.ql?.registry) {\n ctx.logger.debug('SchemaRegistry unavailable for bridging, skipping');\n return;\n }\n\n const objects = this.ql.registry.getAllObjects();\n let bridged = 0;\n\n for (const obj of objects) {\n try {\n // Check if object is already in metadata service to avoid duplicates\n const existing = await metadataService.getObject(obj.name);\n if (!existing) {\n // Register object that exists in SchemaRegistry but not in metadata service\n await metadataService.register('object', obj.name, obj);\n bridged++;\n }\n } catch (e: unknown) {\n ctx.logger.debug('Failed to bridge object to metadata service', {\n object: obj.name,\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n if (bridged > 0) {\n ctx.logger.info('Bridged objects from SchemaRegistry to metadata service', {\n count: bridged,\n total: objects.length\n });\n } else {\n ctx.logger.debug('No objects needed bridging (all already in metadata service)');\n }\n } catch (e: unknown) {\n ctx.logger.debug('Failed to bridge objects to metadata service', {\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n /**\n * Load metadata from external metadata service into ObjectQL registry\n * This enables ObjectQL to use file-based or remote metadata\n */\n private async loadMetadataFromService(metadataService: any, ctx: PluginContext) {\n ctx.logger.info('Syncing metadata from external service into ObjectQL registry...');\n \n // Metadata types to sync\n const metadataTypes = ['object', 'view', 'app', 'flow', 'workflow', 'function'];\n let totalLoaded = 0;\n \n for (const type of metadataTypes) {\n try {\n // Check if service has loadMany method\n if (typeof metadataService.loadMany === 'function') {\n const items = await metadataService.loadMany(type);\n \n if (items && items.length > 0) {\n items.forEach((item: any) => {\n // Determine key field (usually 'name' or 'id')\n const keyField = item.id ? 'id' : 'name';\n \n // For objects, use the ownership-aware registration\n if (type === 'object' && this.ql) {\n // Objects are registered differently (ownership model)\n // Skip for now - handled by app registration\n return;\n }\n \n // Register other types in the registry\n if (this.ql?.registry?.registerItem) {\n this.ql.registry.registerItem(type, item, keyField);\n }\n });\n \n totalLoaded += items.length;\n ctx.logger.info(`Synced ${items.length} ${type}(s) from metadata service`);\n }\n }\n } catch (e: any) {\n // Type might not exist in metadata service - that's ok\n ctx.logger.debug(`No ${type} metadata found or error loading`, { \n error: e.message \n });\n }\n }\n \n if (totalLoaded > 0) {\n ctx.logger.info(`Metadata sync complete: ${totalLoaded} items loaded into ObjectQL registry`);\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectKernel } from '@objectstack/core';\nimport { ObjectQLPlugin } from './plugin.js';\nimport type { Plugin } from '@objectstack/core';\n\n/**\n * Options for creating an ObjectQL Kernel.\n */\nexport interface ObjectQLKernelOptions {\n /**\n * Additional plugins to register with the kernel.\n */\n plugins?: Plugin[];\n}\n\n/**\n * Convenience factory for creating an ObjectQL-ready kernel.\n *\n * Creates an ObjectKernel pre-configured with the ObjectQLPlugin\n * (data engine, schema registry, protocol implementation) plus any\n * additional plugins provided.\n *\n * @example\n * ```typescript\n * import { createObjectQLKernel } from '@objectstack/objectql';\n *\n * const kernel = createObjectQLKernel({\n * plugins: [myDriverPlugin, myAuthPlugin],\n * });\n * await kernel.bootstrap();\n * ```\n */\nexport async function createObjectQLKernel(options: ObjectQLKernelOptions = {}): Promise {\n const kernel = new ObjectKernel();\n\n // Register the core ObjectQLPlugin first\n await kernel.use(new ObjectQLPlugin());\n\n // Register any additional plugins\n if (options.plugins) {\n for (const plugin of options.plugins) {\n await kernel.use(plugin);\n }\n }\n\n return kernel;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ServiceObject } from '@objectstack/spec/data';\n\n// ── Introspection Types ──────────────────────────────────────────────────────\n\n/**\n * Column metadata from database introspection.\n */\nexport interface IntrospectedColumn {\n /** Column name */\n name: string;\n /** Native database type (e.g., 'varchar', 'integer', 'timestamp') */\n type: string;\n /** Whether the column is nullable */\n nullable: boolean;\n /** Default value if any */\n defaultValue?: unknown;\n /** Whether this is a primary key */\n isPrimary?: boolean;\n /** Whether this column has a unique constraint */\n isUnique?: boolean;\n /** Maximum length for string types */\n maxLength?: number;\n}\n\n/**\n * Foreign key relationship metadata.\n */\nexport interface IntrospectedForeignKey {\n /** Column name in the source table */\n columnName: string;\n /** Referenced table name */\n referencedTable: string;\n /** Referenced column name */\n referencedColumn: string;\n /** Constraint name */\n constraintName?: string;\n}\n\n/**\n * Table metadata from database introspection.\n */\nexport interface IntrospectedTable {\n /** Table name */\n name: string;\n /** List of columns */\n columns: IntrospectedColumn[];\n /** List of foreign key relationships */\n foreignKeys: IntrospectedForeignKey[];\n /** Primary key columns */\n primaryKeys: string[];\n}\n\n/**\n * Complete database schema introspection result.\n */\nexport interface IntrospectedSchema {\n /** Map of table name to table metadata */\n tables: Record;\n}\n\n// ── Utility Functions ────────────────────────────────────────────────────────\n\n/**\n * Convert a snake_case or plain string to Title Case.\n *\n * @example\n * toTitleCase('first_name') // => 'First Name'\n * toTitleCase('project_task') // => 'Project Task'\n */\nexport function toTitleCase(str: string): string {\n return str\n .replace(/_/g, ' ')\n .replace(/\\b\\w/g, (char) => char.toUpperCase());\n}\n\n/**\n * Map a native database column type to an ObjectStack FieldType.\n */\nfunction mapDatabaseTypeToFieldType(\n dbType: string\n): 'text' | 'textarea' | 'number' | 'boolean' | 'datetime' | 'date' | 'time' | 'json' {\n const type = dbType.toLowerCase();\n\n // Text types\n if (type.includes('char') || type.includes('varchar') || type.includes('text')) {\n if (type.includes('text')) return 'textarea';\n return 'text';\n }\n\n // Numeric types\n if (\n type.includes('int') || type === 'integer' || type === 'bigint' || type === 'smallint'\n ) {\n return 'number';\n }\n if (\n type.includes('float') || type.includes('double') || type.includes('decimal') ||\n type.includes('numeric') || type === 'real'\n ) {\n return 'number';\n }\n\n // Boolean\n if (type.includes('bool')) {\n return 'boolean';\n }\n\n // Date / Time types\n if (type.includes('timestamp') || type === 'datetime') {\n return 'datetime';\n }\n if (type === 'date') {\n return 'date';\n }\n if (type === 'time') {\n return 'time';\n }\n\n // JSON types\n if (type === 'json' || type === 'jsonb') {\n return 'json';\n }\n\n // Default to text\n return 'text';\n}\n\n/**\n * Convert an introspected database schema to ObjectStack object definitions.\n *\n * This allows using existing database tables without manually defining metadata.\n *\n * @param introspectedSchema - The schema returned from driver.introspectSchema()\n * @param options - Optional filtering / conversion settings\n * @returns Array of ServiceObject definitions that can be registered with ObjectQL\n *\n * @example\n * ```typescript\n * const schema = await driver.introspectSchema();\n * const objects = convertIntrospectedSchemaToObjects(schema);\n * for (const obj of objects) {\n * engine.registerObject(obj);\n * }\n * ```\n */\nexport function convertIntrospectedSchemaToObjects(\n introspectedSchema: IntrospectedSchema,\n options?: {\n /** Tables to exclude from conversion */\n excludeTables?: string[];\n /** Tables to include (if specified, only these will be converted) */\n includeTables?: string[];\n /** Whether to skip system columns like id, created_at, updated_at (default: true) */\n skipSystemColumns?: boolean;\n }\n): ServiceObject[] {\n const objects: ServiceObject[] = [];\n const excludeTables = options?.excludeTables || [];\n const includeTables = options?.includeTables;\n const skipSystemColumns = options?.skipSystemColumns !== false;\n\n for (const [tableName, table] of Object.entries(introspectedSchema.tables)) {\n if (excludeTables.includes(tableName)) continue;\n if (includeTables && !includeTables.includes(tableName)) continue;\n\n const fields: Record = {};\n\n for (const column of table.columns) {\n // Skip system columns if requested\n if (skipSystemColumns && ['id', 'created_at', 'updated_at'].includes(column.name)) {\n continue;\n }\n\n // Check for foreign key → lookup field\n const foreignKey = table.foreignKeys.find((fk) => fk.columnName === column.name);\n\n if (foreignKey) {\n fields[column.name] = {\n name: column.name,\n type: 'lookup' as const,\n reference: foreignKey.referencedTable,\n label: toTitleCase(column.name),\n required: !column.nullable,\n };\n } else {\n const fieldType = mapDatabaseTypeToFieldType(column.type);\n\n const field: Record = {\n name: column.name,\n type: fieldType,\n label: toTitleCase(column.name),\n required: !column.nullable,\n };\n\n if (column.isUnique) {\n field.unique = true;\n }\n if (column.maxLength && (fieldType === 'text' || fieldType === 'textarea')) {\n field.maxLength = column.maxLength;\n }\n if (column.defaultValue != null) {\n field.defaultValue = column.defaultValue;\n }\n\n fields[column.name] = field;\n }\n }\n\n objects.push({\n name: tableName,\n label: toTitleCase(tableName),\n fields,\n } as ServiceObject);\n }\n\n return objects;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # CLI Extension Protocol\n * \n * Defines the contract for plugins that extend the ObjectStack CLI with\n * custom commands. This enables third-party packages (e.g., marketplace,\n * cloud deployment tools) to register new CLI commands via oclif's\n * built-in plugin system.\n * \n * ## How It Works (oclif Plugin Model)\n * \n * 1. **Declare** — Plugin's `package.json` includes an `oclif` config section\n * declaring its commands directory and any topics.\n * 2. **Discover** — The main CLI (`@objectstack/cli`) lists the plugin in its\n * `oclif.plugins` array, or users install it via `os plugins install `.\n * 3. **Load** — oclif automatically discovers and registers all Command classes\n * exported from the plugin's commands directory.\n * \n * ## Plugin Package Contract\n * \n * The plugin must be a valid oclif plugin:\n * \n * ```json\n * // package.json of the plugin\n * {\n * \"name\": \"@acme/plugin-marketplace\",\n * \"oclif\": {\n * \"commands\": {\n * \"strategy\": \"pattern\",\n * \"target\": \"./dist/commands\",\n * \"glob\": \"**\\/*.js\"\n * }\n * }\n * }\n * ```\n * \n * Commands are standard oclif Command classes:\n * \n * ```typescript\n * // src/commands/marketplace/search.ts\n * import { Args, Command, Flags } from '@oclif/core';\n * \n * export default class MarketplaceSearch extends Command {\n * static override description = 'Search marketplace apps';\n * static override args = {\n * query: Args.string({ description: 'Search query', required: true }),\n * };\n * async run() {\n * const { args } = await this.parse(MarketplaceSearch);\n * // ...\n * }\n * }\n * ```\n * \n * ## Migration from Commander.js\n * \n * The previous plugin model required `contributes.commands` in the manifest\n * and exported Commander.js `Command` instances. The new model uses oclif's\n * native plugin system for automatic command discovery and registration.\n * The `objectstack.config.ts` plugins array no longer determines CLI commands.\n */\n\n/**\n * Schema for a CLI Command Contribution declaration in the manifest.\n * \n * This declarative metadata describes CLI commands contributed by a plugin.\n * With the oclif migration, commands are auto-discovered from the plugin's\n * commands directory. This schema is retained for backward compatibility\n * and for describing command metadata in plugin manifests.\n */\nexport const CLICommandContributionSchema = z.object({\n /** \n * CLI command name. Must be a valid identifier: lowercase alphanumeric with hyphens.\n * This becomes a top-level subcommand of the `os` CLI.\n * \n * @example \"marketplace\"\n * @example \"deploy\"\n * @example \"cloud-sync\"\n */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n\n /** Brief description shown in `os --help` output. */\n description: z.string().optional().describe('Command description for help text'),\n\n /** \n * Module path that exports the oclif Command class(es).\n * Relative to the plugin package root. With oclif, this is typically\n * auto-discovered from the `commands` directory, but can be specified\n * for documentation or manifest purposes.\n * \n * @example \"./dist/commands/marketplace.js\"\n * @example \"./dist/commands\"\n */\n module: z.string().optional().describe('Module path exporting oclif Command classes'),\n});\n\n/**\n * Schema for oclif plugin configuration in package.json.\n * Validates the shape of the `oclif` section in a plugin's package.json.\n */\nexport const OclifPluginConfigSchema = z.object({\n /** Command discovery configuration */\n commands: z.object({\n /** Discovery strategy — typically \"pattern\" for file-based discovery */\n strategy: z.enum(['pattern', 'explicit', 'single']).optional()\n .describe('Command discovery strategy'),\n /** Directory path containing compiled command files */\n target: z.string().optional()\n .describe('Target directory for command files'),\n /** Glob pattern for matching command files */\n glob: z.string().optional()\n .describe('Glob pattern for command file matching'),\n }).optional().describe('Command discovery configuration'),\n\n /** Topic separator character (default: space) */\n topicSeparator: z.string().optional()\n .describe('Character separating topic and command names'),\n}).describe('oclif plugin configuration section');\n\n// ─── Types ───────────────────────────────────────────────────────────\n\nexport type CLICommandContribution = z.infer;\nexport type OclifPluginConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Package Artifact Format Protocol\n *\n * Defines the standard structure of a package artifact (.tgz) produced by\n * `os plugin build`. The marketplace uses these schemas to validate, store,\n * and distribute package artifacts.\n *\n * ## Artifact Internal Structure\n * ```\n * ├── manifest.json ← ManifestSchema serialized\n * ├── metadata/ ← 30+ metadata types (JSON)\n * │ ├── objects/ ← *.object.json\n * │ ├── views/ ← *.view.json\n * │ ├── pages/ ← *.page.json\n * │ ├── flows/ ← *.flow.json\n * │ ├── dashboards/ ← *.dashboard.json\n * │ ├── permissions/ ← *.permission.json\n * │ ├── agents/ ← *.agent.json\n * │ └── ... ← Other metadata types\n * ├── assets/ ← Static resources\n * │ ├── icon.svg\n * │ └── screenshots/\n * ├── data/ ← Seed data (DatasetSchema serialized)\n * ├── locales/ ← i18n translation files\n * ├── checksums.json ← SHA256 checksum per file\n * └── signature.sig ← RSA-SHA256 package signature\n * ```\n *\n * ## Architecture Alignment\n * - **Salesforce**: Managed Package .zip with metadata components\n * - **npm**: .tgz with package.json + contents\n * - **Helm**: Chart .tgz with Chart.yaml + templates\n * - **VS Code**: .vsix (zip) with extension manifest + assets\n */\n\n// ==========================================\n// Metadata Category Definitions\n// ==========================================\n\n/**\n * Supported metadata categories within an artifact.\n * Each category maps to a subdirectory under `metadata/`.\n */\nexport const MetadataCategoryEnum = z.enum([\n 'objects',\n 'views',\n 'pages',\n 'flows',\n 'dashboards',\n 'permissions',\n 'agents',\n 'reports',\n 'actions',\n 'translations',\n 'themes',\n 'datasets',\n 'apis',\n 'triggers',\n 'workflows',\n]).describe('Metadata category within the artifact');\n\nexport type MetadataCategory = z.infer;\n\n// ==========================================\n// Artifact File Entry\n// ==========================================\n\n/**\n * A single file entry within the artifact.\n */\nexport const ArtifactFileEntrySchema = z.object({\n /** Relative path within the artifact (e.g. \"metadata/objects/account.object.json\") */\n path: z.string().describe('Relative file path within the artifact'),\n\n /** File size in bytes */\n size: z.number().int().nonnegative().describe('File size in bytes'),\n\n /** Metadata category (if under metadata/) */\n category: MetadataCategoryEnum.optional()\n .describe('Metadata category this file belongs to'),\n}).describe('A single file entry within the artifact');\n\nexport type ArtifactFileEntry = z.infer;\n\n// ==========================================\n// Artifact Checksum\n// ==========================================\n\n/**\n * Checksum map for artifact integrity verification.\n * Maps relative file paths to their SHA256 hash values.\n *\n * @example\n * {\n * \"manifest.json\": \"a1b2c3...\",\n * \"metadata/objects/account.object.json\": \"d4e5f6...\"\n * }\n */\nexport const ArtifactChecksumSchema = z.object({\n /** Hash algorithm used (default: SHA256) */\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm used for checksums'),\n\n /** Map of relative file paths to their hash values */\n files: z.record(z.string(), z.string().regex(/^[a-f0-9]+$/))\n .describe('File path to hash value mapping'),\n}).describe('Checksum manifest for artifact integrity verification');\n\nexport type ArtifactChecksum = z.infer;\n\n// ==========================================\n// Artifact Signature\n// ==========================================\n\n/**\n * Digital signature for artifact authenticity verification.\n * Ensures the artifact was produced by a trusted publisher and has not been tampered with.\n */\nexport const ArtifactSignatureSchema = z.object({\n /** Signature algorithm */\n algorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).default('RSA-SHA256')\n .describe('Signing algorithm used'),\n\n /** Public key reference (URL or fingerprint) for verification */\n publicKeyRef: z.string()\n .describe('Public key reference (URL or fingerprint) for signature verification'),\n\n /** Base64-encoded signature value */\n signature: z.string()\n .describe('Base64-encoded digital signature'),\n\n /** Timestamp of when the artifact was signed */\n signedAt: z.string().datetime().optional()\n .describe('ISO 8601 timestamp of when the artifact was signed'),\n\n /** Signer identity (publisher ID or email) */\n signedBy: z.string().optional()\n .describe('Identity of the signer (publisher ID or email)'),\n}).describe('Digital signature for artifact authenticity verification');\n\nexport type ArtifactSignature = z.infer;\n\n// ==========================================\n// Package Artifact Schema\n// ==========================================\n\n/**\n * Package Artifact Schema\n *\n * Describes the complete structure and metadata of a built package artifact.\n * This schema is used to validate artifacts before upload to the marketplace.\n */\nexport const PackageArtifactSchema = z.object({\n /** Artifact format version (for forward compatibility) */\n formatVersion: z.string().regex(/^\\d+\\.\\d+$/).default('1.0')\n .describe('Artifact format version (e.g. \"1.0\")'),\n\n /** Package ID from the manifest */\n packageId: z.string().describe('Package identifier from manifest'),\n\n /** Package version from the manifest */\n version: z.string().describe('Package version from manifest'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format of the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().positive().optional()\n .describe('Total artifact file size in bytes'),\n\n /** Build timestamp */\n builtAt: z.string().datetime()\n .describe('ISO 8601 timestamp of when the artifact was built'),\n\n /** Build tool and version that produced this artifact */\n builtWith: z.string().optional()\n .describe('Build tool identifier (e.g. \"os-cli@3.2.0\")'),\n\n /** File listing within the artifact */\n files: z.array(ArtifactFileEntrySchema).optional()\n .describe('List of files contained in the artifact'),\n\n /** Metadata categories present in the artifact */\n metadataCategories: z.array(MetadataCategoryEnum).optional()\n .describe('Metadata categories included in this artifact'),\n\n /** Integrity checksums for all files */\n checksums: ArtifactChecksumSchema.optional()\n .describe('SHA256 checksums for artifact integrity verification'),\n\n /** Digital signature for authenticity */\n signature: ArtifactSignatureSchema.optional()\n .describe('Digital signature for artifact authenticity verification'),\n}).describe('Package artifact structure and metadata');\n\nexport type PackageArtifact = z.infer;\nexport type PackageArtifactInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PackageArtifactSchema, ArtifactChecksumSchema, ArtifactSignatureSchema } from './package-artifact.zod';\n\n/**\n * # CLI Plugin Commands Protocol\n *\n * Defines the input/output schemas for the `os plugin` CLI commands\n * that manage the package build → validate → publish lifecycle.\n *\n * ## Commands\n * ```\n * os plugin build — Build a .tgz artifact from the current project\n * os plugin validate — Validate an artifact's structure, checksums, and signature\n * os plugin publish — Upload an artifact to the marketplace\n * ```\n *\n * ## Architecture Alignment\n * - **npm**: `npm pack` → `npm publish`\n * - **Helm**: `helm package` → `helm push`\n * - **VS Code**: `vsce package` → `vsce publish`\n * - **Salesforce**: `sf package version create` → `sf package version promote`\n */\n\n// ==========================================\n// os plugin build\n// ==========================================\n\n/**\n * Options for the `os plugin build` command.\n * Reads the project manifest and produces a .tgz artifact.\n */\nexport const PluginBuildOptionsSchema = z.object({\n /** Project root directory (defaults to cwd) */\n directory: z.string().optional()\n .describe('Project root directory (defaults to current working directory)'),\n\n /** Output directory for the built artifact */\n outDir: z.string().optional()\n .describe('Output directory for the built artifact (defaults to ./dist)'),\n\n /** Archive format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format for the artifact'),\n\n /** Whether to sign the artifact */\n sign: z.boolean().default(false)\n .describe('Whether to digitally sign the artifact'),\n\n /** Path to the private key for signing */\n privateKeyPath: z.string().optional()\n .describe('Path to RSA/ECDSA private key file for signing'),\n\n /** Signing algorithm */\n signAlgorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).optional()\n .describe('Signing algorithm to use'),\n\n /** Checksum algorithm */\n checksumAlgorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm for file checksums'),\n\n /** Whether to include seed data */\n includeData: z.boolean().default(true)\n .describe('Whether to include seed data in the artifact'),\n\n /** Whether to include locale/translation files */\n includeLocales: z.boolean().default(true)\n .describe('Whether to include locale/translation files'),\n}).describe('Options for the os plugin build command');\n\nexport type PluginBuildOptions = z.infer;\n\n/**\n * Result of the `os plugin build` command.\n */\nexport const PluginBuildResultSchema = z.object({\n /** Whether the build succeeded */\n success: z.boolean().describe('Whether the build succeeded'),\n\n /** Path to the generated artifact file */\n artifactPath: z.string().optional()\n .describe('Absolute path to the generated artifact file'),\n\n /** Artifact metadata (validated against PackageArtifactSchema) */\n artifact: PackageArtifactSchema.optional()\n .describe('Artifact metadata'),\n\n /** Total file count in the artifact */\n fileCount: z.number().int().min(0).optional()\n .describe('Total number of files in the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().min(0).optional()\n .describe('Total artifact size in bytes'),\n\n /** Build duration in milliseconds */\n durationMs: z.number().optional()\n .describe('Build duration in milliseconds'),\n\n /** Error message if build failed */\n errorMessage: z.string().optional()\n .describe('Error message if build failed'),\n\n /** Warnings emitted during build */\n warnings: z.array(z.string()).optional()\n .describe('Warnings emitted during build'),\n}).describe('Result of the os plugin build command');\n\nexport type PluginBuildResult = z.infer;\n\n// ==========================================\n// os plugin validate\n// ==========================================\n\n/**\n * Validation severity levels.\n */\nexport const ValidationSeverityEnum = z.enum([\n 'error', // Must fix — artifact is invalid\n 'warning', // Should fix — may cause issues\n 'info', // Informational — suggestion\n]).describe('Validation issue severity');\n\n/**\n * A single validation finding.\n */\nexport const ValidationFindingSchema = z.object({\n /** Finding severity */\n severity: ValidationSeverityEnum.describe('Issue severity level'),\n\n /** Rule or check that produced this finding */\n rule: z.string().describe('Validation rule identifier'),\n\n /** Human-readable message */\n message: z.string().describe('Human-readable finding description'),\n\n /** File path within the artifact (if applicable) */\n path: z.string().optional()\n .describe('Relative file path within the artifact'),\n}).describe('A single validation finding');\n\nexport type ValidationFinding = z.infer;\n\n/**\n * Options for the `os plugin validate` command.\n */\nexport const PluginValidateOptionsSchema = z.object({\n /** Path to the .tgz artifact file to validate */\n artifactPath: z.string()\n .describe('Path to the artifact file to validate'),\n\n /** Whether to verify the digital signature */\n verifySignature: z.boolean().default(true)\n .describe('Whether to verify the digital signature'),\n\n /** Path to the public key for signature verification */\n publicKeyPath: z.string().optional()\n .describe('Path to the public key for signature verification'),\n\n /** Whether to verify SHA256 checksums of all files */\n verifyChecksums: z.boolean().default(true)\n .describe('Whether to verify checksums of all files'),\n\n /** Whether to validate metadata schema compliance */\n validateMetadata: z.boolean().default(true)\n .describe('Whether to validate metadata against schemas'),\n\n /** Target platform version for compatibility check */\n platformVersion: z.string().optional()\n .describe('Platform version for compatibility verification'),\n}).describe('Options for the os plugin validate command');\n\nexport type PluginValidateOptions = z.infer;\n\n/**\n * Result of the `os plugin validate` command.\n */\nexport const PluginValidateResultSchema = z.object({\n /** Whether the artifact is valid (no error-level findings) */\n valid: z.boolean().describe('Whether the artifact passed validation'),\n\n /** Artifact metadata extracted from the archive */\n artifact: PackageArtifactSchema.optional()\n .describe('Extracted artifact metadata'),\n\n /** Checksum verification result */\n checksumVerification: z.object({\n /** Whether all checksums match */\n passed: z.boolean().describe('Whether all checksums match'),\n /** Checksum details */\n checksums: ArtifactChecksumSchema.optional().describe('Verified checksums'),\n /** Files with mismatched checksums */\n mismatches: z.array(z.string()).optional()\n .describe('Files with checksum mismatches'),\n }).optional().describe('Checksum verification result'),\n\n /** Signature verification result */\n signatureVerification: z.object({\n /** Whether the signature is valid */\n passed: z.boolean().describe('Whether the signature is valid'),\n /** Signature details */\n signature: ArtifactSignatureSchema.optional().describe('Signature details'),\n /** Reason for failure */\n failureReason: z.string().optional().describe('Signature verification failure reason'),\n }).optional().describe('Signature verification result'),\n\n /** Platform compatibility result */\n platformCompatibility: z.object({\n /** Whether the artifact is compatible with the target platform */\n compatible: z.boolean().describe('Whether artifact is compatible'),\n /** Required platform version range */\n requiredRange: z.string().optional().describe('Required platform version range'),\n /** Target platform version checked against */\n targetVersion: z.string().optional().describe('Target platform version'),\n }).optional().describe('Platform compatibility check result'),\n\n /** All validation findings */\n findings: z.array(ValidationFindingSchema)\n .describe('All validation findings'),\n\n /** Counts by severity */\n summary: z.object({\n errors: z.number().int().min(0).describe('Error count'),\n warnings: z.number().int().min(0).describe('Warning count'),\n infos: z.number().int().min(0).describe('Info count'),\n }).optional().describe('Finding counts by severity'),\n}).describe('Result of the os plugin validate command');\n\nexport type PluginValidateResult = z.infer;\n\n// ==========================================\n// os plugin publish\n// ==========================================\n\n/**\n * Options for the `os plugin publish` command.\n */\nexport const PluginPublishOptionsSchema = z.object({\n /** Path to the .tgz artifact file to publish */\n artifactPath: z.string()\n .describe('Path to the artifact file to publish'),\n\n /** Marketplace API base URL */\n registryUrl: z.string().url().optional()\n .describe('Marketplace API base URL'),\n\n /** Authentication token for the marketplace API */\n token: z.string().optional()\n .describe('Authentication token for marketplace API'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional()\n .describe('Release notes for this version'),\n\n /** Whether this is a pre-release */\n preRelease: z.boolean().default(false)\n .describe('Whether this is a pre-release version'),\n\n /** Whether to skip validation before publishing */\n skipValidation: z.boolean().default(false)\n .describe('Whether to skip local validation before publish'),\n\n /** Access level for the published package */\n access: z.enum(['public', 'restricted']).default('public')\n .describe('Package access level on the marketplace'),\n\n /** Tags for categorization */\n tags: z.array(z.string()).optional()\n .describe('Tags for marketplace categorization'),\n}).describe('Options for the os plugin publish command');\n\nexport type PluginPublishOptions = z.infer;\n\n/**\n * Result of the `os plugin publish` command.\n */\nexport const PluginPublishResultSchema = z.object({\n /** Whether the publish succeeded */\n success: z.boolean().describe('Whether the publish succeeded'),\n\n /** Package ID that was published */\n packageId: z.string().optional()\n .describe('Published package identifier'),\n\n /** Version that was published */\n version: z.string().optional()\n .describe('Published version string'),\n\n /** Artifact reference in the marketplace */\n artifactUrl: z.string().url().optional()\n .describe('URL of the published artifact in the marketplace'),\n\n /** SHA256 checksum of the uploaded artifact */\n sha256: z.string().optional()\n .describe('SHA256 checksum of the uploaded artifact'),\n\n /** Submission ID for tracking the review process */\n submissionId: z.string().optional()\n .describe('Marketplace submission ID for review tracking'),\n\n /** Error message if publish failed */\n errorMessage: z.string().optional()\n .describe('Error message if publish failed'),\n\n /** Human-readable status message */\n message: z.string().optional()\n .describe('Human-readable status message'),\n}).describe('Result of the os plugin publish command');\n\nexport type PluginPublishResult = z.infer;\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type ValidationSeverity = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Schema (Multi-Tenant Architecture)\n * \n * Defines the tenant/tenancy model for ObjectStack SaaS deployments.\n * Supports different levels of data isolation to meet varying security,\n * performance, and compliance requirements.\n * \n * Isolation Levels:\n * - shared_schema: All tenants share the same database and schema (row-level isolation)\n * - isolated_schema: Tenants have separate schemas within a shared database\n * - isolated_db: Each tenant has a completely separate database\n */\n\n/**\n * Tenant Isolation Level Enum\n * Defines how tenant data is separated in the system\n */\nexport const TenantIsolationLevel = z.enum([\n 'shared_schema', // Shared DB, shared schema, row-level isolation (most economical)\n 'isolated_schema', // Shared DB, separate schema per tenant (balanced)\n 'isolated_db', // Separate database per tenant (maximum isolation)\n]);\n\nexport type TenantIsolationLevel = z.infer;\n\n/**\n * Database Provider Enum\n * Defines which database backend is used for the tenant\n */\nexport const DatabaseProviderSchema = z.enum([\n 'turso', // Turso/libSQL (DB-per-Tenant, edge-native)\n 'postgres', // PostgreSQL (traditional, self-hosted or managed)\n 'memory', // In-memory (testing/development only)\n]).describe('Database provider for tenant data');\n\nexport type DatabaseProvider = z.infer;\n\n/**\n * Tenant Connection Config Schema\n * Stores the database connection details for a tenant (encrypted at rest)\n */\nexport const TenantConnectionConfigSchema = z.object({\n /** Database connection URL */\n url: z.string().min(1).describe('Database connection URL'),\n /** Authentication token (JWT for Turso, password for Postgres) */\n authToken: z.string().optional().describe('Database auth token (encrypted at rest)'),\n /** Turso database group name */\n group: z.string().optional().describe('Turso database group name'),\n}).describe('Tenant database connection configuration');\n\nexport type TenantConnectionConfig = z.infer;\n\n/**\n * Tenant Quota Schema\n * Defines resource limits and usage quotas for a tenant\n */\nexport const TenantQuotaSchema = z.object({\n /**\n * Maximum number of users allowed for this tenant\n */\n maxUsers: z.number().int().positive().optional().describe('Maximum number of users'),\n \n /**\n * Maximum storage space in bytes\n */\n maxStorage: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n \n /**\n * API rate limit (requests per minute)\n */\n apiRateLimit: z.number().int().positive().optional().describe('API requests per minute'),\n\n /**\n * Maximum number of custom objects the tenant can create\n */\n maxObjects: z.number().int().positive().optional().describe('Maximum number of custom objects'),\n\n /**\n * Maximum records per object/table\n */\n maxRecordsPerObject: z.number().int().positive().optional().describe('Maximum records per object'),\n\n /**\n * Maximum deployments allowed per day\n */\n maxDeploymentsPerDay: z.number().int().positive().optional().describe('Maximum deployments per day'),\n\n /**\n * Maximum storage in bytes\n */\n maxStorageBytes: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n});\n\nexport type TenantQuota = z.infer;\n\n/**\n * Tenant Usage Schema\n * Tracks current resource usage for quota enforcement\n */\nexport const TenantUsageSchema = z.object({\n /** Current number of custom objects */\n currentObjectCount: z.number().int().min(0).default(0).describe('Current number of custom objects'),\n /** Current total record count across all objects */\n currentRecordCount: z.number().int().min(0).default(0).describe('Total records across all objects'),\n /** Current storage usage in bytes */\n currentStorageBytes: z.number().int().min(0).default(0).describe('Current storage usage in bytes'),\n /** Deployments executed today */\n deploymentsToday: z.number().int().min(0).default(0).describe('Deployments executed today'),\n /** Current number of active users */\n currentUsers: z.number().int().min(0).default(0).describe('Current number of active users'),\n /** API requests in the current minute */\n apiRequestsThisMinute: z.number().int().min(0).default(0).describe('API requests in the current minute'),\n /** Last updated timestamp (ISO 8601) */\n lastUpdatedAt: z.string().datetime().optional().describe('Last usage update time'),\n}).describe('Current tenant resource usage');\n\nexport type TenantUsage = z.infer;\n\n/**\n * Quota Enforcement Result\n * Result of checking whether an operation would exceed tenant quotas\n */\nexport const QuotaEnforcementResultSchema = z.object({\n /** Whether the operation is allowed */\n allowed: z.boolean().describe('Whether the operation is within quota'),\n /** Quota that would be exceeded (if not allowed) */\n exceededQuota: z.string().optional().describe('Name of the exceeded quota'),\n /** Current usage value */\n currentUsage: z.number().optional().describe('Current usage value'),\n /** Quota limit value */\n limit: z.number().optional().describe('Quota limit'),\n /** Human-readable message */\n message: z.string().optional().describe('Human-readable quota message'),\n}).describe('Quota enforcement check result');\n\nexport type QuotaEnforcementResult = z.infer;\n\n/**\n * Tenant Schema\n * \n * @deprecated This schema is maintained for backward compatibility only.\n * New implementations should use HubSpaceSchema which embeds tenant concepts.\n * \n * **Migration Guide:**\n * ```typescript\n * // Old approach (deprecated):\n * const tenant: Tenant = {\n * id: 'tenant_123',\n * name: 'My Tenant',\n * isolationLevel: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * };\n * \n * // New approach (recommended):\n * const space: HubSpace = {\n * id: '...uuid...',\n * name: 'My Tenant',\n * slug: 'my-tenant',\n * ownerId: 'user_id',\n * runtime: {\n * isolation: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * },\n * bom: { ... }\n * };\n * ```\n * \n * See HubSpaceSchema in space.zod.ts for the recommended approach.\n */\nexport const TenantSchema = z.object({\n /**\n * Unique tenant identifier\n */\n id: z.string().describe('Unique tenant identifier'),\n \n /**\n * Tenant display name\n */\n name: z.string().describe('Tenant display name'),\n \n /**\n * Data isolation level\n */\n isolationLevel: TenantIsolationLevel,\n\n /**\n * Database provider for this tenant\n */\n databaseProvider: DatabaseProviderSchema.optional().describe('Database provider'),\n\n /**\n * Database connection configuration (encrypted at rest)\n */\n connectionConfig: TenantConnectionConfigSchema.optional().describe('Database connection config'),\n\n /**\n * Current provisioning status\n */\n provisioningStatus: z.enum([\n 'provisioning', 'active', 'suspended', 'failed', 'destroying',\n ]).optional().describe('Current provisioning lifecycle status'),\n\n /**\n * Tenant subscription plan\n */\n plan: z.enum(['free', 'pro', 'enterprise']).optional().describe('Subscription plan'),\n \n /**\n * Custom configuration values\n */\n customizations: z.record(z.string(), z.unknown()).optional().describe('Custom configuration values'),\n \n /**\n * Resource quotas\n */\n quotas: TenantQuotaSchema.optional(),\n});\n\nexport type Tenant = z.infer;\n\n/**\n * Tenant Isolation Strategy Documentation\n * \n * Comprehensive documentation of three isolation strategies for multi-tenant systems.\n * Each strategy has different trade-offs in terms of security, cost, complexity, and compliance.\n */\n\n/**\n * Row-Level Isolation Strategy (shared_schema)\n * \n * Recommended for: Most SaaS applications, cost-sensitive deployments\n * \n * IMPLEMENTATION:\n * - All tenants share the same database and schema\n * - Each table includes a tenant_id column\n * - PostgreSQL Row-Level Security (RLS) enforces isolation\n * - Queries automatically filter by tenant_id via RLS policies\n * \n * ADVANTAGES:\n * ✅ Simple backup and restore (single database)\n * ✅ Cost-effective (shared resources, minimal overhead)\n * ✅ Easy tenant migration (update tenant_id)\n * ✅ Efficient resource utilization (connection pooling)\n * ✅ Simple schema migrations (single schema to update)\n * ✅ Lower operational complexity\n * \n * DISADVANTAGES:\n * ❌ RLS misconfiguration can lead to data leakage\n * ❌ Performance impact from RLS policy evaluation\n * ❌ Noisy neighbor problem (one tenant can affect others)\n * ❌ Cannot easily isolate tenant to different hardware\n * ❌ Compliance challenges for regulated industries\n * \n * SECURITY CONSIDERATIONS:\n * - Requires careful RLS policy configuration\n * - Must validate tenant_id in all queries\n * - Need comprehensive testing of RLS policies\n * - Audit all database access patterns\n * - Implement application-level validation as defense-in-depth\n * \n * EXAMPLE RLS POLICY (PostgreSQL):\n * ```sql\n * -- Example: Apply RLS policy to a table (e.g., \"app_data\")\n * CREATE POLICY tenant_isolation ON app_data\n * USING (tenant_id = current_setting('app.current_tenant')::text);\n * \n * ALTER TABLE app_data ENABLE ROW LEVEL SECURITY;\n * ```\n */\nexport const RowLevelIsolationStrategySchema = z.object({\n strategy: z.literal('shared_schema').describe('Row-level isolation strategy'),\n \n /**\n * Database configuration for row-level isolation\n */\n database: z.object({\n /**\n * Whether to enable Row-Level Security (RLS)\n */\n enableRLS: z.boolean().default(true).describe('Enable PostgreSQL Row-Level Security'),\n \n /**\n * Tenant context setting method\n */\n contextMethod: z.enum([\n 'session_variable', // SET app.current_tenant = 'tenant_123'\n 'search_path', // SET search_path = tenant_123, public\n 'application_name', // SET application_name = 'tenant_123'\n ]).default('session_variable').describe('How to set tenant context'),\n \n /**\n * Session variable name for tenant context\n */\n contextVariable: z.string().default('app.current_tenant').describe('Session variable name'),\n \n /**\n * Whether to validate tenant_id at application level\n */\n applicationValidation: z.boolean().default(true).describe('Application-level tenant validation'),\n }).optional().describe('Database configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use partial indexes for tenant_id\n */\n usePartialIndexes: z.boolean().default(true).describe('Use partial indexes per tenant'),\n \n /**\n * Whether to use table partitioning\n */\n usePartitioning: z.boolean().default(false).describe('Use table partitioning by tenant_id'),\n \n /**\n * Connection pool size per tenant\n */\n poolSizePerTenant: z.number().int().positive().optional().describe('Connection pool size per tenant'),\n }).optional().describe('Performance settings'),\n});\n\nexport type RowLevelIsolationStrategy = z.infer;\nexport type RowLevelIsolationStrategyInput = z.input;\n\n/**\n * Schema-Level Isolation Strategy (isolated_schema)\n * \n * Recommended for: Enterprise SaaS, B2B platforms with compliance needs\n * \n * IMPLEMENTATION:\n * - All tenants share the same database server\n * - Each tenant has a separate database schema\n * - Schema name typically: tenant_\n * - Application switches schema using SET search_path\n * \n * ADVANTAGES:\n * ✅ Better isolation than row-level (schema boundaries)\n * ✅ Easier to debug (separate schemas)\n * ✅ Can grant different database permissions per schema\n * ✅ Reduced risk of data leakage\n * ✅ Performance isolation (indexes, statistics per schema)\n * ✅ Simplified queries (no tenant_id filtering needed)\n * \n * DISADVANTAGES:\n * ❌ More complex backups (must backup all schemas)\n * ❌ Higher migration costs (schema changes across all tenants)\n * ❌ Schema proliferation (PostgreSQL has limits)\n * ❌ Connection overhead (switching schemas)\n * ❌ More complex monitoring and maintenance\n * \n * SECURITY CONSIDERATIONS:\n * - Ensure proper schema permissions (GRANT USAGE ON SCHEMA)\n * - Validate schema name to prevent SQL injection\n * - Implement connection-level schema switching\n * - Audit schema access patterns\n * - Prevent cross-schema queries in application\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant schema\n * CREATE SCHEMA tenant_123;\n * \n * -- Grant access\n * GRANT USAGE ON SCHEMA tenant_123 TO app_user;\n * \n * -- Switch to tenant schema\n * SET search_path TO tenant_123, public;\n * ```\n */\nexport const SchemaLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_schema').describe('Schema-level isolation strategy'),\n \n /**\n * Schema configuration\n */\n schema: z.object({\n /**\n * Schema naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Schema naming pattern'),\n \n /**\n * Whether to include public schema in search_path\n */\n includePublicSchema: z.boolean().default(true).describe('Include public schema'),\n \n /**\n * Default schema for shared resources\n */\n sharedSchema: z.string().default('public').describe('Schema for shared resources'),\n \n /**\n * Whether to automatically create schema on tenant creation\n */\n autoCreateSchema: z.boolean().default(true).describe('Auto-create schema'),\n }).optional().describe('Schema configuration'),\n \n /**\n * Migration configuration\n */\n migrations: z.object({\n /**\n * Migration strategy\n */\n strategy: z.enum([\n 'parallel', // Run migrations on all schemas in parallel\n 'sequential', // Run migrations one schema at a time\n 'on_demand', // Run migrations when tenant accesses system\n ]).default('parallel').describe('Migration strategy'),\n \n /**\n * Maximum concurrent migrations\n */\n maxConcurrent: z.number().int().positive().default(10).describe('Max concurrent migrations'),\n \n /**\n * Whether to rollback on first failure\n */\n rollbackOnError: z.boolean().default(true).describe('Rollback on error'),\n }).optional().describe('Migration configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use connection pooling per schema\n */\n poolPerSchema: z.boolean().default(false).describe('Separate pool per schema'),\n \n /**\n * Schema cache TTL in seconds\n */\n schemaCacheTTL: z.number().int().positive().default(3600).describe('Schema cache TTL'),\n }).optional().describe('Performance settings'),\n});\n\nexport type SchemaLevelIsolationStrategy = z.infer;\nexport type SchemaLevelIsolationStrategyInput = z.input;\n\n/**\n * Database-Level Isolation Strategy (isolated_db)\n * \n * Recommended for: Regulated industries (healthcare, finance), strict compliance requirements\n * \n * IMPLEMENTATION:\n * - Each tenant has a completely separate database\n * - Database name typically: tenant_\n * - Requires separate connection pool per tenant\n * - Complete physical and logical isolation\n * \n * ADVANTAGES:\n * ✅ Perfect data isolation (strongest security)\n * ✅ Meets strict regulatory requirements (HIPAA, SOX, PCI-DSS)\n * ✅ Complete performance isolation (no noisy neighbors)\n * ✅ Can place databases on different hardware\n * ✅ Easy to backup/restore individual tenant\n * ✅ Simplified compliance auditing per tenant\n * ✅ Can apply different encryption keys per database\n * \n * DISADVANTAGES:\n * ❌ Most expensive option (resource overhead)\n * ❌ Complex database server management (many databases)\n * ❌ Connection pool limits (max connections per server)\n * ❌ Difficult cross-tenant analytics\n * ❌ Higher operational complexity\n * ❌ Schema migrations take longer (many databases)\n * \n * SECURITY CONSIDERATIONS:\n * - Each database can have separate credentials\n * - Enables per-tenant encryption at rest\n * - Simplifies compliance and audit trails\n * - Prevents any cross-tenant data access\n * - Supports tenant-specific backup schedules\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant database\n * CREATE DATABASE tenant_123\n * WITH OWNER = tenant_123_user\n * ENCODING = 'UTF8'\n * LC_COLLATE = 'en_US.UTF-8'\n * LC_CTYPE = 'en_US.UTF-8';\n * \n * -- Connect to tenant database\n * \\c tenant_123\n * ```\n */\nexport const DatabaseLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_db').describe('Database-level isolation strategy'),\n \n /**\n * Database configuration\n */\n database: z.object({\n /**\n * Database naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Database naming pattern'),\n \n /**\n * Database server/cluster assignment strategy\n */\n serverStrategy: z.enum([\n 'shared', // All tenant databases on same server\n 'sharded', // Tenant databases distributed across servers\n 'dedicated', // Each tenant gets dedicated server (enterprise)\n ]).default('shared').describe('Server assignment strategy'),\n \n /**\n * Whether to use separate credentials per tenant\n */\n separateCredentials: z.boolean().default(true).describe('Separate credentials per tenant'),\n \n /**\n * Whether to automatically create database on tenant creation\n */\n autoCreateDatabase: z.boolean().default(true).describe('Auto-create database'),\n }).optional().describe('Database configuration'),\n \n /**\n * Connection pooling configuration\n */\n connectionPool: z.object({\n /**\n * Pool size per tenant database\n */\n poolSize: z.number().int().positive().default(10).describe('Connection pool size'),\n \n /**\n * Maximum number of tenant pools to keep active\n */\n maxActivePools: z.number().int().positive().default(100).describe('Max active pools'),\n \n /**\n * Idle pool timeout in seconds\n */\n idleTimeout: z.number().int().positive().default(300).describe('Idle pool timeout'),\n \n /**\n * Whether to use connection pooler (PgBouncer, etc.)\n */\n usePooler: z.boolean().default(true).describe('Use connection pooler'),\n }).optional().describe('Connection pool configuration'),\n \n /**\n * Backup and restore configuration\n */\n backup: z.object({\n /**\n * Backup strategy per tenant\n */\n strategy: z.enum([\n 'individual', // Separate backup per tenant\n 'consolidated', // Combined backup with all tenants\n 'on_demand', // Backup only when requested\n ]).default('individual').describe('Backup strategy'),\n \n /**\n * Backup frequency in hours\n */\n frequencyHours: z.number().int().positive().default(24).describe('Backup frequency'),\n \n /**\n * Retention period in days\n */\n retentionDays: z.number().int().positive().default(30).describe('Backup retention days'),\n }).optional().describe('Backup configuration'),\n \n /**\n * Encryption configuration\n */\n encryption: z.object({\n /**\n * Whether to use per-tenant encryption keys\n */\n perTenantKeys: z.boolean().default(false).describe('Per-tenant encryption keys'),\n \n /**\n * Encryption algorithm\n */\n algorithm: z.string().default('AES-256-GCM').describe('Encryption algorithm'),\n \n /**\n * Key management service\n */\n keyManagement: z.enum(['aws_kms', 'azure_key_vault', 'gcp_kms', 'hashicorp_vault', 'custom']).optional().describe('Key management service'),\n }).optional().describe('Encryption configuration'),\n});\n\nexport type DatabaseLevelIsolationStrategy = z.infer;\nexport type DatabaseLevelIsolationStrategyInput = z.input;\n\n/**\n * Tenant Isolation Configuration Schema\n * \n * Complete configuration for tenant isolation strategy.\n * Supports all three isolation levels with detailed configuration options.\n */\nexport const TenantIsolationConfigSchema = z.discriminatedUnion('strategy', [\n RowLevelIsolationStrategySchema,\n SchemaLevelIsolationStrategySchema,\n DatabaseLevelIsolationStrategySchema,\n]);\n\nexport type TenantIsolationConfig = z.infer;\n\n/**\n * Tenant Security Policy Schema\n * Defines security policies and compliance requirements for tenants\n */\nexport const TenantSecurityPolicySchema = z.object({\n /**\n * Encryption requirements\n */\n encryption: z.object({\n /**\n * Require encryption at rest\n */\n atRest: z.boolean().default(true).describe('Require encryption at rest'),\n \n /**\n * Require encryption in transit\n */\n inTransit: z.boolean().default(true).describe('Require encryption in transit'),\n \n /**\n * Require field-level encryption for sensitive data\n */\n fieldLevel: z.boolean().default(false).describe('Require field-level encryption'),\n }).optional().describe('Encryption requirements'),\n \n /**\n * Access control requirements\n */\n accessControl: z.object({\n /**\n * Require multi-factor authentication\n */\n requireMFA: z.boolean().default(false).describe('Require MFA'),\n \n /**\n * Require SSO/SAML authentication\n */\n requireSSO: z.boolean().default(false).describe('Require SSO'),\n \n /**\n * IP whitelist\n */\n ipWhitelist: z.array(z.string()).optional().describe('Allowed IP addresses'),\n \n /**\n * Session timeout in seconds\n */\n sessionTimeout: z.number().int().positive().default(3600).describe('Session timeout'),\n }).optional().describe('Access control requirements'),\n \n /**\n * Audit and compliance requirements\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox',\n 'hipaa',\n 'gdpr',\n 'pci_dss',\n 'iso_27001',\n 'fedramp',\n ])).optional().describe('Compliance standards'),\n \n /**\n * Require audit logging for all operations\n */\n requireAuditLog: z.boolean().default(true).describe('Require audit logging'),\n \n /**\n * Audit log retention period in days\n */\n auditRetentionDays: z.number().int().positive().default(365).describe('Audit retention days'),\n \n /**\n * Data residency requirements\n */\n dataResidency: z.object({\n /**\n * Required geographic region\n */\n region: z.string().optional().describe('Required region (e.g., US, EU, APAC)'),\n \n /**\n * Prohibited regions\n */\n excludeRegions: z.array(z.string()).optional().describe('Prohibited regions'),\n }).optional().describe('Data residency requirements'),\n }).optional().describe('Compliance requirements'),\n});\n\nexport type TenantSecurityPolicy = z.infer;\nexport type TenantSecurityPolicyInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TenantQuotaSchema } from '../system/tenant.zod.js';\n\n/**\n * Runtime Mode Enum\n * Defines the operating mode of the kernel\n */\nexport const RuntimeMode = z.enum([\n 'development', // Hot-reload, verbose logging\n 'production', // Optimized, strict security\n 'test', // Mocked interfaces\n 'provisioning', // Setup/Migration mode\n 'preview', // Demo/preview mode — bypass auth, simulate admin identity\n]).describe('Kernel operating mode');\n\nexport type RuntimeMode = z.infer;\n\n/**\n * Preview Mode Configuration Schema\n *\n * Configures the kernel's preview/demo mode behaviour.\n * When `mode` is set to `'preview'`, the platform skips authentication\n * screens and optionally simulates an admin identity so that visitors\n * (e.g. app-marketplace customers) can explore the system without\n * registering or logging in.\n *\n * **Security note:** preview mode should NEVER be used in production.\n * The runtime must enforce this constraint.\n *\n * @example\n * ```ts\n * const ctx = KernelContextSchema.parse({\n * instanceId: '550e8400-e29b-41d4-a716-446655440000',\n * mode: 'preview',\n * version: '1.0.0',\n * cwd: '/app',\n * startTime: Date.now(),\n * previewMode: {\n * autoLogin: true,\n * simulatedRole: 'admin',\n * },\n * });\n * ```\n */\nexport const PreviewModeConfigSchema = z.object({\n /**\n * Automatically log in as a simulated user on startup.\n * When enabled, the frontend skips login/registration screens entirely.\n */\n autoLogin: z.boolean().default(true)\n .describe('Auto-login as simulated user, skipping login/registration pages'),\n\n /**\n * Role of the simulated user.\n * Determines the permission level of the auto-created preview session.\n */\n simulatedRole: z.enum(['admin', 'user', 'viewer']).default('admin')\n .describe('Permission role for the simulated preview user'),\n\n /**\n * Display name for the simulated user shown in the UI.\n */\n simulatedUserName: z.string().default('Preview User')\n .describe('Display name for the simulated preview user'),\n\n /**\n * Whether the preview session is read-only.\n * When true, all write operations (create, update, delete) are blocked.\n */\n readOnly: z.boolean().default(false)\n .describe('Restrict the preview session to read-only operations'),\n\n /**\n * Session duration in seconds. After expiry the preview session ends.\n * 0 means no expiration.\n */\n expiresInSeconds: z.number().int().min(0).default(0)\n .describe('Preview session duration in seconds (0 = no expiration)'),\n\n /**\n * Optional banner message shown in the UI to indicate preview mode.\n * Useful for marketplace demos so visitors know they are in a sandbox.\n */\n bannerMessage: z.string().optional()\n .describe('Banner message displayed in the UI during preview mode'),\n});\n\nexport type PreviewModeConfig = z.infer;\n\n/**\n * Kernel Context Schema\n * Defines the static environment information available to the Kernel at boot.\n */\nexport const KernelContextSchema = z.object({\n /**\n * Instance Identity\n */\n instanceId: z.string().uuid().describe('Unique UUID for this running kernel process'),\n \n /**\n * Environment Metadata\n */\n mode: RuntimeMode.default('production'),\n version: z.string().describe('Kernel version'),\n appName: z.string().optional().describe('Host application name'),\n \n /**\n * Paths\n */\n cwd: z.string().describe('Current working directory'),\n workspaceRoot: z.string().optional().describe('Workspace root if different from cwd'),\n \n /**\n * Telemetry\n */\n startTime: z.number().int().describe('Boot timestamp (ms)'),\n \n /**\n * Feature Flags (Global)\n */\n features: z.record(z.string(), z.boolean()).default({}).describe('Global feature toggles'),\n\n /**\n * Preview Mode Configuration.\n * Only relevant when `mode` is `'preview'`. Configures auto-login,\n * simulated identity, read-only restrictions, and UI banner.\n */\n previewMode: PreviewModeConfigSchema.optional()\n .describe('Preview/demo mode configuration (used when mode is \"preview\")'),\n});\n\nexport type KernelContext = z.infer;\n\n// ==========================================================================\n// Tenant Runtime Context\n// ==========================================================================\n\n/**\n * Tenant Runtime Context Schema.\n *\n * Extends the base KernelContext with tenant-specific information.\n * Constructed per-request from: session → org → tenant lookup.\n * Provides the tenant identity, plan, region, and database URL to all\n * downstream services during request processing.\n */\nexport const TenantRuntimeContextSchema = KernelContextSchema.extend({\n /** Unique tenant identifier resolved from the current session */\n tenantId: z.string().min(1).describe('Resolved tenant identifier'),\n\n /** Tenant subscription plan */\n tenantPlan: z.enum(['free', 'pro', 'enterprise']).describe('Tenant subscription plan'),\n\n /** Tenant deployment region */\n tenantRegion: z.string().optional().describe('Tenant deployment region'),\n\n /** Tenant database connection URL */\n tenantDbUrl: z.string().min(1).describe('Tenant database connection URL'),\n\n /** Optional tenant quotas for the current plan */\n tenantQuotas: TenantQuotaSchema.optional().describe('Tenant resource quotas'),\n}).describe('Tenant-aware kernel runtime context');\n\nexport type TenantRuntimeContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dependency Resolution Protocol\n *\n * Defines schemas for runtime dependency resolution when installing,\n * upgrading, or managing packages. Provides a standardized way to\n * express dependency conflicts, resolution results, and installation order.\n *\n * ## Architecture Alignment\n * - **npm**: Dependency tree resolution with conflict detection\n * - **Helm**: Dependency management with version constraints\n * - **Salesforce**: Package dependency validation at install time\n *\n * ## Resolution Flow\n * ```\n * 1. Parse manifest.dependencies (SemVer ranges)\n * 2. Check installed packages registry\n * 3. Resolve each dependency → satisfied | needs_install | needs_upgrade | conflict\n * 4. Detect circular dependencies\n * 5. Compute topological install order\n * 6. Return resolution result with required actions\n * ```\n */\n\n// ==========================================\n// Dependency Resolution Status\n// ==========================================\n\n/**\n * Resolution status for a single dependency.\n */\nexport const DependencyStatusEnum = z.enum([\n 'satisfied', // Already installed and version compatible\n 'needs_install', // Not installed, needs to be installed\n 'needs_upgrade', // Installed but version incompatible, needs upgrade\n 'conflict', // Conflicts with another package's dependency\n]).describe('Resolution status for a dependency');\n\nexport type DependencyStatus = z.infer;\n\n// ==========================================\n// Resolved Dependency\n// ==========================================\n\n/**\n * Single dependency resolution result.\n * Describes the state of one dependency after resolution.\n */\nexport const ResolvedDependencySchema = z.object({\n /** Package identifier of the dependency */\n packageId: z.string().describe('Dependency package identifier'),\n\n /** SemVer range required by the parent package */\n requiredRange: z.string().describe('SemVer range required (e.g. \"^2.0.0\")'),\n\n /** Actual version resolved (if available) */\n resolvedVersion: z.string().optional()\n .describe('Actual version resolved from registry'),\n\n /** Currently installed version (if any) */\n installedVersion: z.string().optional()\n .describe('Currently installed version'),\n\n /** Resolution status */\n status: DependencyStatusEnum.describe('Resolution status'),\n\n /** Conflict details (when status is \"conflict\") */\n conflictReason: z.string().optional()\n .describe('Explanation of the conflict'),\n}).describe('Resolution result for a single dependency');\n\nexport type ResolvedDependency = z.infer;\n\n// ==========================================\n// Required Action\n// ==========================================\n\n/**\n * An action required before installation can proceed.\n */\nexport const RequiredActionSchema = z.object({\n /** Type of action required */\n type: z.enum(['install', 'upgrade', 'confirm_conflict'])\n .describe('Type of action required'),\n\n /** Target package identifier */\n packageId: z.string().describe('Target package identifier'),\n\n /** Human-readable description of the action */\n description: z.string().describe('Human-readable action description'),\n}).describe('Action required before installation can proceed');\n\nexport type RequiredAction = z.infer;\n\n// ==========================================\n// Dependency Resolution Result\n// ==========================================\n\n/**\n * Complete dependency resolution result.\n * Aggregates all dependency statuses and computes installation feasibility.\n */\nexport const DependencyResolutionResultSchema = z.object({\n /** All dependencies and their resolution results */\n dependencies: z.array(ResolvedDependencySchema)\n .describe('Resolution result for each dependency'),\n\n /** Whether installation can proceed without conflicts */\n canProceed: z.boolean()\n .describe('Whether installation can proceed'),\n\n /** Actions that require user confirmation or system execution */\n requiredActions: z.array(RequiredActionSchema)\n .describe('Actions required before proceeding'),\n\n /** Topologically sorted package IDs for installation order */\n installOrder: z.array(z.string())\n .describe('Topologically sorted package IDs for installation'),\n\n /** Detected circular dependency chains */\n circularDependencies: z.array(z.array(z.string())).optional()\n .describe('Circular dependency chains detected (e.g. [[\"A\", \"B\", \"A\"]])'),\n}).describe('Complete dependency resolution result');\n\nexport type DependencyResolutionResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dev Mode Plugin Protocol\n *\n * Defines the schema for a development-mode plugin that automatically enables\n * all platform services for local simulation. When loaded as a `devPlugin`,\n * the kernel bootstraps every subsystem (data, UI, API, auth, events, jobs, …)\n * using in-memory or stub implementations so that developers can exercise the\n * full stack without external dependencies.\n *\n * Design goals:\n * - Zero-config by default: `devPlugins: ['@objectstack/plugin-dev']`\n * - Every service can be overridden or disabled individually\n * - Preset profiles (minimal / standard / full) for common scenarios\n *\n * Inspired by:\n * - Spring Boot DevTools (auto-configuration)\n * - Next.js Dev Server (HMR + mock APIs)\n * - Vite Plugin Dev Mode (instant startup)\n */\n\n// ============================================================================\n// Dev Service Override\n// ============================================================================\n\n/**\n * Dev Service Override Schema\n *\n * Allows fine-grained control over a single service in development mode.\n * Each override targets a service by name and specifies whether it should\n * be enabled, which implementation strategy to use, and optional config.\n */\nexport const DevServiceOverrideSchema = z.object({\n /** Service identifier (e.g. 'auth', 'eventBus', 'fileStorage') */\n service: z.string().min(1).describe('Target service identifier'),\n\n /** Whether this service is enabled in dev mode */\n enabled: z.boolean().default(true).describe('Enable or disable this service'),\n\n /**\n * Implementation strategy for the service in dev mode.\n * - mock: Use a mock/stub that records calls (for assertions)\n * - memory: Use a real but in-memory implementation (e.g. SQLite, Map)\n * - stub: Use a static/no-op implementation\n * - passthrough: Use the real production implementation (for integration testing)\n */\n strategy: z.enum(['mock', 'memory', 'stub', 'passthrough']).default('memory')\n .describe('Implementation strategy for development'),\n\n /** Optional per-service configuration (strategy-specific) */\n config: z.record(z.string(), z.unknown()).optional()\n .describe('Strategy-specific configuration for this service override'),\n});\n\nexport type DevServiceOverride = z.infer;\n\n// ============================================================================\n// Dev Fixture Configuration\n// ============================================================================\n\n/**\n * Dev Fixture Config Schema\n *\n * Configures automatic seed/fixture data loading in development mode.\n * Fixtures provide a reproducible dataset for local development and demos.\n */\nexport const DevFixtureConfigSchema = z.object({\n /** Whether to load fixtures on startup */\n enabled: z.boolean().default(true).describe('Load fixture data on startup'),\n\n /**\n * Glob patterns pointing to fixture files\n * (e.g. `[\"./fixtures/*.json\", \"./test/data/*.yml\"]`)\n */\n paths: z.array(z.string()).optional()\n .describe('Glob patterns for fixture files'),\n\n /** Whether to reset data before loading fixtures */\n resetBeforeLoad: z.boolean().default(true)\n .describe('Clear existing data before loading fixtures'),\n\n /**\n * Environment tag filter – only load fixtures tagged for these environments.\n * When omitted, all fixtures are loaded.\n */\n envFilter: z.array(z.string()).optional()\n .describe('Only load fixtures matching these environment tags'),\n});\n\nexport type DevFixtureConfig = z.infer;\n\n// ============================================================================\n// Dev Tools Configuration\n// ============================================================================\n\n/**\n * Dev Tools Config Schema\n *\n * Optional developer tooling that can be enabled alongside the dev plugin.\n */\nexport const DevToolsConfigSchema = z.object({\n /** Enable hot-module replacement / live reload */\n hotReload: z.boolean().default(true).describe('Enable HMR / live-reload'),\n\n /** Enable request inspector UI for debugging HTTP traffic */\n requestInspector: z.boolean().default(false).describe('Enable request inspector'),\n\n /** Enable an in-browser database explorer */\n dbExplorer: z.boolean().default(false).describe('Enable database explorer UI'),\n\n /** Enable verbose logging across all services */\n verboseLogging: z.boolean().default(true).describe('Enable verbose logging'),\n\n /** Enable OpenAPI / Swagger documentation endpoint */\n apiDocs: z.boolean().default(true).describe('Serve OpenAPI docs at /_dev/docs'),\n\n /** Enable a mail catcher for outbound email (like MailHog) */\n mailCatcher: z.boolean().default(false).describe('Capture outbound emails in dev'),\n});\n\nexport type DevToolsConfig = z.infer;\n\n// ============================================================================\n// Dev Plugin Preset\n// ============================================================================\n\n/**\n * Dev Plugin Preset\n *\n * Predefined configuration profiles for common development scenarios.\n * - minimal: Only core data services (fast startup, low memory)\n * - standard: Core + API + auth + events (typical full-stack dev)\n * - full: Every service enabled, including background jobs and AI agents\n */\nexport const DevPluginPreset = z.enum([\n 'minimal',\n 'standard',\n 'full',\n]).describe('Predefined dev configuration profile');\n\nexport type DevPluginPreset = z.infer;\n\n// ============================================================================\n// Dev Plugin Configuration\n// ============================================================================\n\n/**\n * Dev Plugin Config Schema\n *\n * Top-level configuration for the development-mode plugin.\n * This is the shape of the configuration payload that\n * `@objectstack/plugin-dev` (or equivalent) understands.\n *\n * The outer wiring (e.g. how a stack declares `devPlugins`) is defined\n * by the stack/manifest schemas; this type only describes the plugin's\n * own config object.\n *\n * @example Minimal usage (zero-config)\n * ```ts\n * const devConfig: DevPluginConfig = {};\n * ```\n *\n * @example With preset\n * ```ts\n * const devConfig: DevPluginConfig = {\n * preset: 'full',\n * };\n * ```\n *\n * @example Fine-grained overrides\n * ```ts\n * const devConfig: DevPluginConfig = {\n * preset: 'standard',\n * services: {\n * auth: { enabled: true, strategy: 'mock' },\n * fileStorage: { enabled: false },\n * },\n * fixtures: { paths: ['./fixtures/*.json'] },\n * tools: { dbExplorer: true },\n * };\n * ```\n */\nexport const DevPluginConfigSchema = z.object({\n /**\n * Configuration preset.\n * When provided, services and tools are pre-configured for the selected\n * profile. Individual `services` and `tools` settings override the preset.\n * @default 'standard'\n */\n preset: DevPluginPreset.default('standard')\n .describe('Base configuration preset'),\n\n /**\n * Per-service overrides.\n * Keys are service names; values configure the dev strategy.\n * Only services explicitly listed here override the preset defaults.\n */\n services: z.record(\n z.string().min(1),\n DevServiceOverrideSchema.omit({ service: true }),\n ).optional().describe('Per-service dev overrides keyed by service name'),\n\n /** Fixture / seed data configuration */\n fixtures: DevFixtureConfigSchema.optional()\n .describe('Fixture data loading configuration'),\n\n /** Developer tooling configuration */\n tools: DevToolsConfigSchema.optional()\n .describe('Developer tooling settings'),\n\n /**\n * Port for the dev-tools UI dashboard.\n * Serves a lightweight web dashboard for inspecting services, events,\n * and request logs during development.\n * @default 4400\n */\n port: z.number().int().min(1).max(65535).default(4400)\n .describe('Port for the dev-tools dashboard'),\n\n /**\n * Auto-open the dev-tools dashboard in the default browser on startup.\n */\n open: z.boolean().default(false)\n .describe('Auto-open dev dashboard in browser'),\n\n /**\n * Seed a default admin user for development.\n * When enabled, the dev plugin creates a pre-authenticated admin user\n * so that developers can bypass login flows.\n */\n seedAdminUser: z.boolean().default(true)\n .describe('Create a default admin user for development'),\n\n /**\n * Simulated latency (ms) to add to service calls.\n * Helps developers build UIs that handle loading states correctly.\n * Set to 0 to disable.\n */\n simulatedLatency: z.number().int().min(0).default(0)\n .describe('Artificial latency (ms) added to service calls'),\n});\n\nexport type DevPluginConfig = z.infer;\nexport type DevPluginConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventNameSchema } from '../../shared/identifiers.zod';\n\n// ==========================================\n// Event Priority\n// ==========================================\n\n/**\n * Event Priority Enum\n * Priority levels for event processing\n * Lower numbers = higher priority\n */\nexport const EventPriority = z.enum([\n 'critical', // 0 - Process immediately, block if necessary\n 'high', // 1 - Process soon, minimal delay\n 'normal', // 2 - Default priority\n 'low', // 3 - Process when resources available\n 'background', // 4 - Process during idle time\n]);\n\nexport type EventPriority = z.infer;\n\n/**\n * Event Priority Values\n * Maps priority names to numeric values for sorting\n */\nexport const EVENT_PRIORITY_VALUES: Record = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n background: 4,\n};\n\n// ==========================================\n// Event Metadata\n// ==========================================\n\n/**\n * Event Metadata Schema\n * Metadata associated with every event\n */\nexport const EventMetadataSchema = z.object({\n source: z.string().describe('Event source (e.g., plugin name, system component)'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when event was created'),\n userId: z.string().optional().describe('User who triggered the event'),\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant systems'),\n correlationId: z.string().optional().describe('Correlation ID for event tracing'),\n causationId: z.string().optional().describe('ID of the event that caused this event'),\n priority: EventPriority.optional().default('normal').describe('Event priority'),\n});\n\n// ==========================================\n// Event Schema\n// ==========================================\n\n/**\n * Event Type Definition Schema\n * Defines the structure of an event type\n * \n * @example\n * {\n * \"name\": \"order.created\",\n * \"version\": \"1.0.0\",\n * \"schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"orderId\": { \"type\": \"string\" },\n * \"customerId\": { \"type\": \"string\" },\n * \"total\": { \"type\": \"number\" }\n * }\n * }\n * }\n */\nexport const EventTypeDefinitionSchema = z.object({\n name: EventNameSchema.describe('Event type name (lowercase with dots)'),\n version: z.string().default('1.0.0').describe('Event schema version'),\n schema: z.unknown().optional().describe('JSON Schema for event payload validation'),\n description: z.string().optional().describe('Event type description'),\n deprecated: z.boolean().optional().default(false).describe('Whether this event type is deprecated'),\n tags: z.array(z.string()).optional().describe('Event type tags'),\n});\n\nexport type EventTypeDefinition = z.infer;\n\n/**\n * Event Schema\n * Base schema for all events in the system\n * \n * Event names follow dot notation for namespacing (e.g., 'user.created', 'order.paid').\n * This aligns with industry standards for event-driven architectures and message queues.\n */\nexport const EventSchema = z.object({\n /**\n * Event identifier (for tracking and deduplication)\n */\n id: z.string().optional().describe('Unique event identifier'),\n \n /**\n * Event name\n */\n name: EventNameSchema.describe('Event name (lowercase with dots, e.g., user.created, order.paid)'),\n \n /**\n * Event payload\n */\n payload: z.unknown().describe('Event payload schema'),\n \n /**\n * Event metadata\n */\n metadata: EventMetadataSchema.describe('Event metadata'),\n});\n\nexport type Event = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Event Handlers\n// ==========================================\n\n/**\n * Event Handler Schema\n * Defines how to handle a specific event\n */\nexport const EventHandlerSchema = z.object({\n /**\n * Handler identifier\n */\n id: z.string().optional().describe('Unique handler identifier'),\n \n /**\n * Event name pattern\n */\n eventName: z.string().describe('Name of event to handle (supports wildcards like user.*)'),\n \n /**\n * Handler function\n */\n handler: z.unknown()\n .describe('Handler function'),\n \n /**\n * Execution priority\n */\n priority: z.number().int().default(0).describe('Execution priority (lower numbers execute first)'),\n \n /**\n * Async execution\n */\n async: z.boolean().default(true).describe('Execute in background (true) or block (false)'),\n \n /**\n * Retry configuration\n */\n retry: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),\n backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay'),\n backoffMultiplier: z.number().positive().default(2).describe('Backoff multiplier'),\n }).optional().describe('Retry policy for failed handlers'),\n \n /**\n * Timeout\n */\n timeoutMs: z.number().int().positive().optional().describe('Handler timeout in milliseconds'),\n \n /**\n * Filter function\n */\n filter: z.unknown()\n .optional()\n .describe('Optional filter to determine if handler should execute'),\n});\n\nexport type EventHandler = z.infer;\n\n/**\n * Event Route Schema\n * Routes events from one pattern to multiple targets with optional transformation\n */\nexport const EventRouteSchema = z.object({\n from: z.string().describe('Source event pattern (supports wildcards, e.g., user.* or *.created)'),\n to: z.array(z.string()).describe('Target event names to route to'),\n transform: z.unknown().optional().describe('Optional function to transform payload'),\n});\n\nexport type EventRoute = z.infer;\n\n/**\n * Event Persistence Schema\n * Configuration for persisting events to storage\n */\nexport const EventPersistenceSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable event persistence'),\n retention: z.number().int().positive().describe('Days to retain persisted events'),\n filter: z.unknown().optional().describe('Optional filter function to select which events to persist'),\n storage: z.enum(['database', 'file', 's3', 'custom']).default('database')\n .describe('Storage backend for persisted events'),\n});\n\nexport type EventPersistence = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Event Queue\n// ==========================================\n\n/**\n * Event Queue Configuration Schema\n * Configuration for async event processing queue\n * \n * @example\n * {\n * \"name\": \"event_queue\",\n * \"concurrency\": 10,\n * \"retryPolicy\": {\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * }\n * }\n */\nexport const EventQueueConfigSchema = z.object({\n /**\n * Queue name\n */\n name: z.string().default('events').describe('Event queue name'),\n \n /**\n * Concurrency\n */\n concurrency: z.number().int().min(1).default(10).describe('Max concurrent event handlers'),\n \n /**\n * Retry policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Max retries for failed events'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay'),\n }).optional().describe('Default retry policy for events'),\n \n /**\n * Dead letter queue\n */\n deadLetterQueue: z.string().optional().describe('Dead letter queue name for failed events'),\n \n /**\n * Enable priority processing\n */\n priorityEnabled: z.boolean().default(true).describe('Process events based on priority'),\n});\n\nexport type EventQueueConfig = z.infer;\n\n// ==========================================\n// Event Replay\n// ==========================================\n\n/**\n * Event Replay Configuration Schema\n * Configuration for replaying historical events\n * \n * @example\n * {\n * \"fromTimestamp\": \"2024-01-01T00:00:00Z\",\n * \"toTimestamp\": \"2024-01-31T23:59:59Z\",\n * \"eventTypes\": [\"order.created\", \"order.updated\"],\n * \"speed\": 10\n * }\n */\nexport const EventReplayConfigSchema = z.object({\n /**\n * Start timestamp\n */\n fromTimestamp: z.string().datetime().describe('Start timestamp for replay (ISO 8601)'),\n \n /**\n * End timestamp\n */\n toTimestamp: z.string().datetime().optional().describe('End timestamp for replay (ISO 8601)'),\n \n /**\n * Event types to replay\n */\n eventTypes: z.array(z.string()).optional().describe('Event types to replay (empty = all)'),\n \n /**\n * Event filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters for event selection'),\n \n /**\n * Replay speed multiplier\n */\n speed: z.number().positive().default(1).describe('Replay speed multiplier (1 = real-time)'),\n \n /**\n * Target handlers\n */\n targetHandlers: z.array(z.string()).optional().describe('Handler IDs to execute (empty = all)'),\n});\n\nexport type EventReplayConfig = z.infer;\n\n// ==========================================\n// Event Sourcing\n// ==========================================\n\n/**\n * Event Sourcing Configuration Schema\n * Configuration for event sourcing pattern\n * \n * Event sourcing stores all changes to application state as a sequence of events.\n * The current state can be reconstructed by replaying the events.\n * \n * @example\n * {\n * \"enabled\": true,\n * \"snapshotInterval\": 100,\n * \"retention\": 365\n * }\n */\nexport const EventSourcingConfigSchema = z.object({\n /**\n * Enable event sourcing\n */\n enabled: z.boolean().default(false).describe('Enable event sourcing'),\n \n /**\n * Snapshot interval\n */\n snapshotInterval: z.number().int().positive().default(100)\n .describe('Create snapshot every N events'),\n \n /**\n * Snapshot retention\n */\n snapshotRetention: z.number().int().positive().default(10)\n .describe('Number of snapshots to retain'),\n \n /**\n * Event retention\n */\n retention: z.number().int().positive().default(365)\n .describe('Days to retain events'),\n \n /**\n * Aggregate types\n */\n aggregateTypes: z.array(z.string()).optional()\n .describe('Aggregate types to enable event sourcing for'),\n \n /**\n * Storage configuration\n */\n storage: z.object({\n type: z.enum(['database', 'file', 's3', 'eventstore']).default('database')\n .describe('Storage backend'),\n options: z.record(z.string(), z.unknown()).optional().describe('Storage-specific options'),\n }).optional().describe('Event store configuration'),\n});\n\nexport type EventSourcingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventSchema } from './core.zod';\n\n// ==========================================\n// Dead Letter Queue\n// ==========================================\n\n/**\n * Dead Letter Queue Entry Schema\n * Represents a failed event in the dead letter queue\n */\nexport const DeadLetterQueueEntrySchema = z.object({\n /**\n * Entry identifier\n */\n id: z.string().describe('Unique entry identifier'),\n \n /**\n * Original event\n */\n event: EventSchema.describe('Original event'),\n \n /**\n * Failure reason\n */\n error: z.object({\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Error stack trace'),\n code: z.string().optional().describe('Error code'),\n }).describe('Failure details'),\n \n /**\n * Retry count\n */\n retries: z.number().int().min(0).describe('Number of retry attempts'),\n \n /**\n * Timestamps\n */\n firstFailedAt: z.string().datetime().describe('When event first failed'),\n lastFailedAt: z.string().datetime().describe('When event last failed'),\n \n /**\n * Handler that failed\n */\n failedHandler: z.string().optional().describe('Handler ID that failed'),\n});\n\nexport type DeadLetterQueueEntry = z.infer;\n\n// ==========================================\n// Event Log\n// ==========================================\n\n/**\n * Event Log Entry Schema\n * Represents a logged event\n */\nexport const EventLogEntrySchema = z.object({\n /**\n * Log entry ID\n */\n id: z.string().describe('Unique log entry identifier'),\n \n /**\n * Event\n */\n event: EventSchema.describe('The event'),\n \n /**\n * Status\n */\n status: z.enum(['pending', 'processing', 'completed', 'failed']).describe('Processing status'),\n \n /**\n * Handlers executed\n */\n handlersExecuted: z.array(z.object({\n handlerId: z.string().describe('Handler identifier'),\n status: z.enum(['success', 'failed', 'timeout']).describe('Handler execution status'),\n durationMs: z.number().int().optional().describe('Execution duration'),\n error: z.string().optional().describe('Error message if failed'),\n })).optional().describe('Handlers that processed this event'),\n \n /**\n * Timestamps\n */\n receivedAt: z.string().datetime().describe('When event was received'),\n processedAt: z.string().datetime().optional().describe('When event was processed'),\n \n /**\n * Total duration\n */\n totalDurationMs: z.number().int().optional().describe('Total processing time'),\n});\n\nexport type EventLogEntry = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Webhook Integration\n// ==========================================\n\n/**\n * Event Webhook Configuration Schema\n * Configuration for sending events to webhooks\n * \n * @example\n * {\n * \"eventPattern\": \"order.*\",\n * \"url\": \"https://api.example.com/webhooks/orders\",\n * \"method\": \"POST\",\n * \"headers\": { \"Authorization\": \"Bearer token\" }\n * }\n */\nexport const EventWebhookConfigSchema = z.object({\n /**\n * Webhook identifier\n */\n id: z.string().optional().describe('Unique webhook identifier'),\n \n /**\n * Event pattern to match\n */\n eventPattern: z.string().describe('Event name pattern (supports wildcards)'),\n \n /**\n * Target URL\n */\n url: z.string().url().describe('Webhook endpoint URL'),\n \n /**\n * HTTP method\n */\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH']).default('POST').describe('HTTP method'),\n \n /**\n * Headers\n */\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n \n /**\n * Authentication\n */\n authentication: z.object({\n type: z.enum(['none', 'bearer', 'basic', 'api-key']).describe('Auth type'),\n credentials: z.record(z.string(), z.string()).optional().describe('Auth credentials'),\n }).optional().describe('Authentication configuration'),\n \n /**\n * Retry policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Max retry attempts'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Max retry delay'),\n }).optional().describe('Retry policy'),\n \n /**\n * Timeout\n */\n timeoutMs: z.number().int().positive().default(30000).describe('Request timeout in milliseconds'),\n \n /**\n * Event transformation\n */\n transform: z.unknown()\n .optional()\n .describe('Transform event before sending'),\n \n /**\n * Enabled\n */\n enabled: z.boolean().default(true).describe('Whether webhook is enabled'),\n});\n\nexport type EventWebhookConfig = z.infer;\n\n// ==========================================\n// Message Queue Integration\n// ==========================================\n\n/**\n * Event Message Queue Configuration Schema\n * Configuration for publishing events to message queues\n * \n * @example\n * {\n * \"provider\": \"kafka\",\n * \"topic\": \"events\",\n * \"eventPattern\": \"*\",\n * \"partitionKey\": \"metadata.tenantId\"\n * }\n */\nexport const EventMessageQueueConfigSchema = z.object({\n /**\n * Provider\n */\n provider: z.enum(['kafka', 'rabbitmq', 'aws-sqs', 'redis-pubsub', 'google-pubsub', 'azure-service-bus'])\n .describe('Message queue provider'),\n \n /**\n * Topic/Queue name\n */\n topic: z.string().describe('Topic or queue name'),\n \n /**\n * Event pattern\n */\n eventPattern: z.string().default('*').describe('Event name pattern to publish (supports wildcards)'),\n \n /**\n * Partition key\n */\n partitionKey: z.string().optional().describe('JSON path for partition key (e.g., \"metadata.tenantId\")'),\n \n /**\n * Message format\n */\n format: z.enum(['json', 'avro', 'protobuf']).default('json').describe('Message serialization format'),\n \n /**\n * Include metadata\n */\n includeMetadata: z.boolean().default(true).describe('Include event metadata in message'),\n \n /**\n * Compression\n */\n compression: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression'),\n \n /**\n * Batch size\n */\n batchSize: z.number().int().min(1).default(1).describe('Batch size for publishing'),\n \n /**\n * Flush interval\n */\n flushIntervalMs: z.number().int().positive().default(1000).describe('Flush interval for batching'),\n});\n\nexport type EventMessageQueueConfig = z.infer;\n\n// ==========================================\n// Real-time Notifications\n// ==========================================\n\n/**\n * Real-time Notification Configuration Schema\n * Configuration for real-time event notifications via WebSocket/SSE\n * \n * @example\n * {\n * \"enabled\": true,\n * \"protocol\": \"websocket\",\n * \"eventPattern\": \"notification.*\",\n * \"userFilter\": true\n * }\n */\nexport const RealTimeNotificationConfigSchema = z.object({\n /**\n * Enable real-time notifications\n */\n enabled: z.boolean().default(true).describe('Enable real-time notifications'),\n \n /**\n * Protocol\n */\n protocol: z.enum(['websocket', 'sse', 'long-polling']).default('websocket')\n .describe('Real-time protocol'),\n \n /**\n * Event pattern\n */\n eventPattern: z.string().default('*').describe('Event pattern to broadcast'),\n \n /**\n * User-specific filtering\n */\n userFilter: z.boolean().default(true).describe('Filter events by user'),\n \n /**\n * Tenant-specific filtering\n */\n tenantFilter: z.boolean().default(true).describe('Filter events by tenant'),\n \n /**\n * Channels\n */\n channels: z.array(z.object({\n name: z.string().describe('Channel name'),\n eventPattern: z.string().describe('Event pattern for channel'),\n filter: z.unknown()\n .optional()\n .describe('Additional filter function'),\n })).optional().describe('Named channels for event broadcasting'),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n maxEventsPerSecond: z.number().int().positive().describe('Max events per second per client'),\n windowMs: z.number().int().positive().default(1000).describe('Rate limit window'),\n }).optional().describe('Rate limiting configuration'),\n});\n\nexport type RealTimeNotificationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventTypeDefinitionSchema } from './core.zod';\nimport { EventHandlerSchema, EventPersistenceSchema } from './handlers.zod';\nimport { EventQueueConfigSchema, EventSourcingConfigSchema } from './queue.zod';\nimport { EventWebhookConfigSchema, EventMessageQueueConfigSchema, RealTimeNotificationConfigSchema } from './integrations.zod';\n\n// ==========================================\n// Complete Event Bus Configuration\n// ==========================================\n\n/**\n * Event Bus Configuration Schema\n * Complete configuration for the event bus system\n * \n * @example\n * {\n * \"persistence\": { \"enabled\": true, \"retention\": 365 },\n * \"queue\": { \"concurrency\": 20 },\n * \"eventSourcing\": { \"enabled\": true },\n * \"webhooks\": [],\n * \"messageQueue\": { \"provider\": \"kafka\", \"topic\": \"events\" },\n * \"realtime\": { \"enabled\": true, \"protocol\": \"websocket\" }\n * }\n */\nexport const EventBusConfigSchema = z.object({\n /**\n * Event persistence\n */\n persistence: EventPersistenceSchema.optional().describe('Event persistence configuration'),\n \n /**\n * Event queue\n */\n queue: EventQueueConfigSchema.optional().describe('Event queue configuration'),\n \n /**\n * Event sourcing\n */\n eventSourcing: EventSourcingConfigSchema.optional().describe('Event sourcing configuration'),\n \n /**\n * Event replay\n */\n replay: z.object({\n enabled: z.boolean().default(true).describe('Enable event replay capability'),\n }).optional().describe('Event replay configuration'),\n \n /**\n * Webhooks\n */\n webhooks: z.array(EventWebhookConfigSchema).optional().describe('Webhook configurations'),\n \n /**\n * Message queue integration\n */\n messageQueue: EventMessageQueueConfigSchema.optional().describe('Message queue integration'),\n \n /**\n * Real-time notifications\n */\n realtime: RealTimeNotificationConfigSchema.optional().describe('Real-time notification configuration'),\n \n /**\n * Event type definitions\n */\n eventTypes: z.array(EventTypeDefinitionSchema).optional().describe('Event type definitions'),\n \n /**\n * Global handlers\n */\n handlers: z.array(EventHandlerSchema).optional().describe('Global event handlers'),\n});\n\nexport type EventBusConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Feature Rollout Strategy\n */\nexport const FeatureStrategy = z.enum([\n 'boolean', // Simple On/Off\n 'percentage', // Gradual rollout (0-100%)\n 'user_list', // Specific users\n 'group', // Specific groups/roles\n 'custom' // Custom constraint/script\n]);\n\n/**\n * Feature Flag Protocol\n * \n * Manages feature toggles and gradual rollouts.\n * Used for CI/CD, A/B Testing, and Trunk-Based Development.\n */\nexport const FeatureFlagSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Feature key (snake_case)'),\n label: z.string().optional().describe('Display label'),\n description: z.string().optional(),\n \n /** Default state */\n enabled: z.boolean().default(false).describe('Is globally enabled'),\n \n /** Rollout Strategy */\n strategy: FeatureStrategy.default('boolean'),\n \n /** Strategy Configuration */\n conditions: z.object({\n percentage: z.number().min(0).max(100).optional(),\n users: z.array(z.string()).optional(),\n groups: z.array(z.string()).optional(),\n expression: z.string().optional().describe('Custom formula expression')\n }).optional(),\n \n /** Integration */\n environment: z.enum(['dev', 'staging', 'prod', 'all']).default('all')\n .describe('Environment validity'),\n \n /** Expiration */\n expiresAt: z.string().datetime().optional().describe('Feature flag expiration date'),\n});\n\nexport const FeatureFlag = Object.assign(FeatureFlagSchema, {\n create: >(config: T) => config,\n});\n\nexport type FeatureFlag = z.infer;\nexport type FeatureFlagInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Capability Protocol\n * \n * Defines the standard way plugins declare their capabilities, implementations,\n * and conformance levels to ensure interoperability across vendors.\n * \n * Based on the Protocol-Oriented Architecture pattern similar to:\n * - Kubernetes CRDs (Custom Resource Definitions)\n * - OSGi Service Registry\n * - Eclipse Extension Points\n */\n\n/**\n * Capability Conformance Level\n * Indicates how completely a plugin implements a given protocol.\n */\nexport const CapabilityConformanceLevelSchema = z.enum([\n 'full', // Complete implementation of all protocol features\n 'partial', // Subset implementation with specific features listed\n 'experimental', // Unstable/preview implementation\n 'deprecated', // Still supported but scheduled for removal\n]).describe('Level of protocol conformance');\n\n/**\n * Protocol Version Schema\n * Uses semantic versioning to track protocol evolution.\n */\nexport const ProtocolVersionSchema = z.object({\n major: z.number().int().min(0),\n minor: z.number().int().min(0),\n patch: z.number().int().min(0),\n}).describe('Semantic version of the protocol');\n\n/**\n * Protocol Reference\n * Uniquely identifies a protocol/interface that a plugin can implement.\n * \n * Examples:\n * - com.objectstack.protocol.storage.v1\n * - com.objectstack.protocol.auth.oauth2.v2\n * - com.acme.protocol.payment.stripe.v1\n */\nexport const ProtocolReferenceSchema = z.object({\n /**\n * Protocol identifier using reverse domain notation.\n * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+protocol\\.[a-z][a-z0-9._]*\\.v\\d+$/)\n .describe('Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)'),\n \n /**\n * Human-readable protocol name\n */\n label: z.string(),\n \n /**\n * Protocol version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Detailed protocol specification URL or file reference\n */\n specification: z.string().optional().describe('URL or path to protocol specification'),\n \n /**\n * Brief description of what this protocol defines\n */\n description: z.string().optional(),\n});\n\n/**\n * Protocol Feature\n * Represents a specific capability within a protocol.\n */\nexport const ProtocolFeatureSchema = z.object({\n name: z.string().describe('Feature identifier within the protocol'),\n enabled: z.boolean().default(true),\n description: z.string().optional(),\n sinceVersion: z.string().optional().describe('Version when this feature was added'),\n deprecatedSince: z.string().optional().describe('Version when deprecated'),\n});\n\n/**\n * Plugin Capability Declaration\n * Documents what protocols a plugin implements and to what extent.\n */\nexport const PluginCapabilitySchema = z.object({\n /**\n * The protocol being implemented\n */\n protocol: ProtocolReferenceSchema,\n \n /**\n * Conformance level\n */\n conformance: CapabilityConformanceLevelSchema.default('full'),\n \n /**\n * Specific features implemented (required if conformance is 'partial')\n */\n implementedFeatures: z.array(z.string()).optional().describe('List of implemented feature names'),\n \n /**\n * Optional feature flags indicating advanced capabilities\n */\n features: z.array(ProtocolFeatureSchema).optional(),\n \n /**\n * Custom metadata for vendor-specific information\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Testing/Certification status\n */\n certified: z.boolean().default(false).describe('Has passed official conformance tests'),\n certificationDate: z.string().datetime().optional(),\n});\n\n/**\n * Plugin Interface Declaration\n * Defines the contract for services this plugin provides to other plugins.\n */\nexport const PluginInterfaceSchema = z.object({\n /**\n * Unique interface identifier\n * Format: {plugin-id}.interface.{name}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+interface\\.[a-z][a-z0-9._]+$/)\n .describe('Unique interface identifier'),\n \n /**\n * Interface name\n */\n name: z.string(),\n \n /**\n * Description of what this interface provides\n */\n description: z.string().optional(),\n \n /**\n * Interface version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Methods exposed by this interface\n */\n methods: z.array(z.object({\n name: z.string().describe('Method name'),\n description: z.string().optional(),\n parameters: z.array(z.object({\n name: z.string(),\n type: z.string().describe('Type notation (e.g., string, number, User)'),\n required: z.boolean().default(true),\n description: z.string().optional(),\n })).optional(),\n returnType: z.string().optional().describe('Return value type'),\n async: z.boolean().default(false).describe('Whether method returns a Promise'),\n })),\n \n /**\n * Events emitted by this interface\n */\n events: z.array(z.object({\n name: z.string().describe('Event name'),\n description: z.string().optional(),\n payload: z.string().optional().describe('Event payload type'),\n })).optional(),\n \n /**\n * Stability level\n */\n stability: z.enum(['stable', 'beta', 'alpha', 'experimental']).default('stable'),\n});\n\n/**\n * Plugin Dependency Declaration\n * Specifies what other plugins or capabilities this plugin requires.\n */\nexport const PluginDependencySchema = z.object({\n /**\n * Plugin ID using reverse domain notation\n */\n pluginId: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Required plugin identifier'),\n \n /**\n * Version constraint (supports semver ranges)\n * Examples: \"1.0.0\", \"^1.2.3\", \">=2.0.0 <3.0.0\"\n */\n version: z.string().describe('Semantic version constraint'),\n \n /**\n * Whether this dependency is optional\n */\n optional: z.boolean().default(false),\n \n /**\n * Reason for the dependency\n */\n reason: z.string().optional(),\n \n /**\n * Minimum required capabilities from the dependency\n */\n requiredCapabilities: z.array(z.string()).optional().describe('Protocol IDs the dependency must support'),\n});\n\n/**\n * Extension Point Declaration\n * Defines hooks where other plugins can extend this plugin's functionality.\n */\nexport const ExtensionPointSchema = z.object({\n /**\n * Extension point identifier\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+extension\\.[a-z][a-z0-9._]+$/)\n .describe('Unique extension point identifier'),\n \n /**\n * Extension point name\n */\n name: z.string(),\n \n /**\n * Description\n */\n description: z.string().optional(),\n \n /**\n * Type of extension point\n */\n type: z.enum([\n 'action', // Plugins can register executable actions\n 'hook', // Plugins can listen to lifecycle events\n 'widget', // Plugins can contribute UI widgets\n 'provider', // Plugins can provide data/services\n 'transformer', // Plugins can transform data\n 'validator', // Plugins can validate data\n 'decorator', // Plugins can enhance/wrap functionality\n ]),\n \n /**\n * Expected interface contract for extensions\n */\n contract: z.object({\n input: z.string().optional().describe('Input type/schema'),\n output: z.string().optional().describe('Output type/schema'),\n signature: z.string().optional().describe('Function signature if applicable'),\n }).optional(),\n \n /**\n * Cardinality\n */\n cardinality: z.enum(['single', 'multiple']).default('multiple')\n .describe('Whether multiple extensions can register to this point'),\n});\n\n/**\n * Complete Plugin Capability Manifest\n * This is included in the main plugin manifest to declare all capabilities.\n */\nexport const PluginCapabilityManifestSchema = z.object({\n /**\n * Protocols this plugin implements\n */\n implements: z.array(PluginCapabilitySchema).optional()\n .describe('List of protocols this plugin conforms to'),\n \n /**\n * Interfaces this plugin exposes to other plugins\n */\n provides: z.array(PluginInterfaceSchema).optional()\n .describe('Services/APIs this plugin offers to others'),\n \n /**\n * Dependencies on other plugins\n */\n requires: z.array(PluginDependencySchema).optional()\n .describe('Required plugins and their capabilities'),\n \n /**\n * Extension points this plugin defines\n */\n extensionPoints: z.array(ExtensionPointSchema).optional()\n .describe('Points where other plugins can extend this plugin'),\n \n /**\n * Extensions this plugin contributes to other plugins\n */\n extensions: z.array(z.object({\n targetPluginId: z.string().describe('Plugin ID being extended'),\n extensionPointId: z.string().describe('Extension point identifier'),\n implementation: z.string().describe('Path to implementation module'),\n priority: z.number().int().default(100).describe('Registration priority (lower = higher priority)'),\n })).optional().describe('Extensions contributed to other plugins'),\n});\n\n// Export types\nexport type CapabilityConformanceLevel = z.infer;\nexport type ProtocolVersion = z.infer;\nexport type ProtocolReference = z.infer;\nexport type ProtocolFeature = z.infer;\nexport type PluginCapability = z.infer;\nexport type PluginInterface = z.infer;\nexport type PluginDependency = z.infer;\nexport type ExtensionPoint = z.infer;\nexport type PluginCapabilityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Loading Protocol\n * \n * Defines the enhanced plugin loading mechanism for the microkernel architecture.\n * Inspired by industry best practices from:\n * - Kubernetes CRDs and Operators\n * - OSGi Dynamic Module System\n * - Eclipse Plugin Framework\n * - Webpack Module Federation\n * \n * This protocol enables:\n * - Lazy loading and code splitting\n * - Dynamic imports and parallel initialization\n * - Capability-based discovery\n * - Hot reload in development\n * - Advanced caching strategies\n */\n\n/**\n * Plugin Loading Strategy\n * Determines how and when a plugin is loaded into memory\n */\nexport const PluginLoadingStrategySchema = z.enum([\n 'eager', // Load immediately during bootstrap (critical plugins)\n 'lazy', // Load on first use (feature plugins)\n 'parallel', // Load in parallel with other plugins\n 'deferred', // Load after initial bootstrap complete\n 'on-demand', // Load only when explicitly requested\n]).describe('Plugin loading strategy');\n\n/**\n * Plugin Preloading Configuration\n * Configures preloading behavior for faster activation\n */\nexport const PluginPreloadConfigSchema = z.object({\n /**\n * Enable preloading for this plugin\n */\n enabled: z.boolean().default(false),\n \n /**\n * Preload priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Resources to preload\n */\n resources: z.array(z.enum([\n 'metadata', // Plugin manifest and metadata\n 'dependencies', // Plugin dependencies\n 'assets', // Static assets (icons, translations)\n 'code', // JavaScript code chunks\n 'services', // Service definitions\n ])).optional(),\n \n /**\n * Conditions for preloading\n */\n conditions: z.object({\n /**\n * Preload only on specific routes\n */\n routes: z.array(z.string()).optional(),\n \n /**\n * Preload only for specific user roles\n */\n roles: z.array(z.string()).optional(),\n \n /**\n * Preload based on device type\n */\n deviceType: z.array(z.enum(['desktop', 'mobile', 'tablet'])).optional(),\n \n /**\n * Network connection quality threshold\n */\n minNetworkSpeed: z.enum(['slow-2g', '2g', '3g', '4g']).optional(),\n }).optional(),\n}).describe('Plugin preloading configuration');\n\n/**\n * Plugin Code Splitting Configuration\n * Configures how plugin code is split for optimal loading\n */\nexport const PluginCodeSplittingSchema = z.object({\n /**\n * Enable code splitting for this plugin\n */\n enabled: z.boolean().default(true),\n \n /**\n * Split strategy\n */\n strategy: z.enum([\n 'route', // Split by UI routes\n 'feature', // Split by feature modules\n 'size', // Split by bundle size threshold\n 'custom', // Custom split points defined by plugin\n ]).default('feature'),\n \n /**\n * Chunk naming strategy\n */\n chunkNaming: z.enum(['hashed', 'named', 'sequential']).default('hashed'),\n \n /**\n * Maximum chunk size in KB\n */\n maxChunkSize: z.number().int().min(10).optional().describe('Max chunk size in KB'),\n \n /**\n * Shared dependencies optimization\n */\n sharedDependencies: z.object({\n enabled: z.boolean().default(true),\n /**\n * Minimum times a module must be shared before extraction\n */\n minChunks: z.number().int().min(1).default(2),\n }).optional(),\n}).describe('Plugin code splitting configuration');\n\n/**\n * Plugin Dynamic Import Configuration\n * Configures dynamic import behavior for runtime module loading\n */\nexport const PluginDynamicImportSchema = z.object({\n /**\n * Enable dynamic imports\n */\n enabled: z.boolean().default(true),\n \n /**\n * Import mode\n */\n mode: z.enum([\n 'async', // Asynchronous import (recommended)\n 'sync', // Synchronous import (blocking)\n 'eager', // Eager evaluation\n 'lazy', // Lazy evaluation\n ]).default('async'),\n \n /**\n * Prefetch strategy\n */\n prefetch: z.boolean().default(false).describe('Prefetch module in idle time'),\n \n /**\n * Preload strategy\n */\n preload: z.boolean().default(false).describe('Preload module in parallel with parent'),\n \n /**\n * Webpack magic comments support\n */\n webpackChunkName: z.string().optional().describe('Custom chunk name for webpack'),\n \n /**\n * Import timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000).describe('Dynamic import timeout (ms)'),\n \n /**\n * Retry configuration on import failure\n */\n retry: z.object({\n enabled: z.boolean().default(true),\n maxAttempts: z.number().int().min(1).max(10).default(3),\n backoffMs: z.number().int().min(0).default(1000).describe('Exponential backoff base delay'),\n }).optional(),\n}).describe('Plugin dynamic import configuration');\n\n/**\n * Plugin Initialization Configuration\n * Configures how plugin initialization is executed\n */\nexport const PluginInitializationSchema = z.object({\n /**\n * Initialization mode\n */\n mode: z.enum([\n 'sync', // Synchronous initialization\n 'async', // Asynchronous initialization\n 'parallel', // Parallel with other plugins\n 'sequential', // Must complete before next plugin\n ]).default('async'),\n \n /**\n * Initialization timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000),\n \n /**\n * Startup priority (lower = higher priority, earlier initialization)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Whether to continue bootstrap if this plugin fails\n */\n critical: z.boolean().default(false).describe('If true, kernel bootstrap fails if plugin fails'),\n \n /**\n * Retry configuration on initialization failure\n */\n retry: z.object({\n enabled: z.boolean().default(false),\n maxAttempts: z.number().int().min(1).max(5).default(3),\n backoffMs: z.number().int().min(0).default(1000),\n }).optional(),\n \n /**\n * Health check interval for monitoring\n */\n healthCheckInterval: z.number().int().min(0).optional().describe('Health check interval in ms (0 = disabled)'),\n}).describe('Plugin initialization configuration');\n\n/**\n * Plugin Dependency Resolution Configuration\n * Advanced dependency resolution using semantic versioning\n */\nexport const PluginDependencyResolutionSchema = z.object({\n /**\n * Dependency resolution strategy\n */\n strategy: z.enum([\n 'strict', // Exact version match required\n 'compatible', // Semver compatible versions (^)\n 'latest', // Always use latest compatible\n 'pinned', // Lock to specific version\n ]).default('compatible'),\n \n /**\n * Peer dependency handling\n */\n peerDependencies: z.object({\n /**\n * Whether to resolve peer dependencies\n */\n resolve: z.boolean().default(true),\n \n /**\n * Action on missing peer dependency\n */\n onMissing: z.enum(['error', 'warn', 'ignore']).default('warn'),\n \n /**\n * Action on peer version mismatch\n */\n onMismatch: z.enum(['error', 'warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Optional dependency handling\n */\n optionalDependencies: z.object({\n /**\n * Whether to attempt loading optional dependencies\n */\n load: z.boolean().default(true),\n \n /**\n * Action on optional dependency load failure\n */\n onFailure: z.enum(['warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Conflict resolution\n */\n conflictResolution: z.enum([\n 'fail', // Fail on any version conflict\n 'latest', // Use latest version\n 'oldest', // Use oldest version\n 'manual', // Require manual resolution\n ]).default('latest'),\n \n /**\n * Circular dependency handling\n */\n circularDependencies: z.enum([\n 'error', // Throw error on circular dependency\n 'warn', // Warn but continue\n 'allow', // Allow circular dependencies\n ]).default('warn'),\n}).describe('Plugin dependency resolution configuration');\n\n/**\n * Plugin Hot Reload Configuration\n * Enables hot module replacement for development and production environments.\n * \n * Production mode adds safety features: health validation, rollback on failure,\n * connection draining, and concurrency control for zero-downtime reloads.\n */\nexport const PluginHotReloadSchema = z.object({\n /**\n * Enable hot reload\n */\n enabled: z.boolean().default(false),\n \n /**\n * Target environment for hot reload behavior\n */\n environment: z.enum([\n 'development', // Fast reload with relaxed safety (file watchers, no health validation)\n 'staging', // Production-like reload with validation but relaxed rollback\n 'production', // Full safety: health validation, rollback, connection draining\n ]).default('development').describe('Target environment controlling safety level'),\n \n /**\n * Hot reload strategy\n */\n strategy: z.enum([\n 'full', // Full plugin reload (destroy and reinitialize)\n 'partial', // Partial reload (update changed modules only)\n 'state-preserve', // Preserve plugin state during reload\n ]).default('full'),\n \n /**\n * Files to watch for changes\n */\n watchPatterns: z.array(z.string()).optional().describe('Glob patterns for files to watch'),\n \n /**\n * Files to ignore\n */\n ignorePatterns: z.array(z.string()).optional().describe('Glob patterns for files to ignore'),\n \n /**\n * Debounce delay in milliseconds\n */\n debounceMs: z.number().int().min(0).default(300),\n \n /**\n * Whether to preserve state during reload\n */\n preserveState: z.boolean().default(false),\n \n /**\n * State serialization\n */\n stateSerialization: z.object({\n enabled: z.boolean().default(false),\n /**\n * Path to state serialization handler\n */\n handler: z.string().optional(),\n }).optional(),\n \n /**\n * Hooks for hot reload lifecycle\n */\n hooks: z.object({\n beforeReload: z.string().optional().describe('Function to call before reload'),\n afterReload: z.string().optional().describe('Function to call after reload'),\n onError: z.string().optional().describe('Function to call on reload error'),\n }).optional(),\n \n /**\n * Production safety configuration\n * Applied when environment is 'staging' or 'production'\n */\n productionSafety: z.object({\n /**\n * Validate plugin health before completing reload\n */\n healthValidation: z.boolean().default(true)\n .describe('Run health checks after reload before accepting traffic'),\n \n /**\n * Automatically rollback to previous version on reload failure\n */\n rollbackOnFailure: z.boolean().default(true)\n .describe('Auto-rollback if reloaded plugin fails health check'),\n \n /**\n * Maximum time to wait for health validation after reload (ms)\n */\n healthTimeout: z.number().int().min(1000).default(30000)\n .describe('Health check timeout after reload in ms'),\n \n /**\n * Drain active connections before reload\n */\n drainConnections: z.boolean().default(true)\n .describe('Gracefully drain active requests before reloading'),\n \n /**\n * Maximum time to wait for connection draining (ms)\n */\n drainTimeout: z.number().int().min(0).default(15000)\n .describe('Max wait time for connection draining in ms'),\n \n /**\n * Maximum number of concurrent plugin reloads\n */\n maxConcurrentReloads: z.number().int().min(1).default(1)\n .describe('Limit concurrent reloads to prevent system instability'),\n \n /**\n * Minimum interval between reloads of the same plugin (ms)\n */\n minReloadInterval: z.number().int().min(1000).default(5000)\n .describe('Cooldown period between reloads of the same plugin'),\n }).optional(),\n}).describe('Plugin hot reload configuration');\n\n/**\n * Plugin Caching Configuration\n * Configures caching strategy for faster subsequent loads\n */\nexport const PluginCachingSchema = z.object({\n /**\n * Enable caching\n */\n enabled: z.boolean().default(true),\n \n /**\n * Cache storage type\n */\n storage: z.enum([\n 'memory', // In-memory cache (fastest, not persistent)\n 'disk', // Disk cache (persistent)\n 'indexeddb', // Browser IndexedDB (persistent, browser only)\n 'hybrid', // Memory + Disk hybrid\n ]).default('memory'),\n \n /**\n * Cache key strategy\n */\n keyStrategy: z.enum([\n 'version', // Cache by plugin version\n 'hash', // Cache by content hash\n 'timestamp', // Cache by last modified timestamp\n ]).default('version'),\n \n /**\n * Cache TTL in seconds\n */\n ttl: z.number().int().min(0).optional().describe('Time to live in seconds (0 = infinite)'),\n \n /**\n * Maximum cache size in MB\n */\n maxSize: z.number().int().min(1).optional().describe('Max cache size in MB'),\n \n /**\n * Cache invalidation triggers\n */\n invalidateOn: z.array(z.enum([\n 'version-change',\n 'dependency-change',\n 'manual',\n 'error',\n ])).optional(),\n \n /**\n * Compression\n */\n compression: z.object({\n enabled: z.boolean().default(false),\n algorithm: z.enum(['gzip', 'brotli', 'deflate']).default('gzip'),\n }).optional(),\n}).describe('Plugin caching configuration');\n\n/**\n * Plugin Sandboxing Configuration\n * Security isolation for plugins with configurable scope.\n * \n * Supports isolation beyond automation scripts: any plugin can be sandboxed\n * with process-level isolation and inter-plugin communication (IPC).\n */\nexport const PluginSandboxingSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(false),\n \n /**\n * Isolation scope - which plugins are subject to sandboxing\n */\n scope: z.enum([\n 'automation-only', // Sandbox automation/scripting plugins only (current behavior)\n 'untrusted-only', // Sandbox plugins below a trust threshold\n 'all-plugins', // Sandbox all plugins (maximum isolation)\n ]).default('automation-only').describe('Which plugins are subject to isolation'),\n \n /**\n * Sandbox isolation level\n */\n isolationLevel: z.enum([\n 'none', // No isolation\n 'process', // Separate process (Node.js worker threads)\n 'vm', // VM context isolation\n 'iframe', // iframe isolation (browser)\n 'web-worker', // Web Worker (browser)\n ]).default('none'),\n \n /**\n * Allowed capabilities\n */\n allowedCapabilities: z.array(z.string()).optional().describe('List of allowed capability IDs'),\n \n /**\n * Resource quotas\n */\n resourceQuotas: z.object({\n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(1).optional(),\n \n /**\n * Maximum CPU time in milliseconds\n */\n maxCpuTimeMs: z.number().int().min(100).optional(),\n \n /**\n * Maximum number of file descriptors\n */\n maxFileDescriptors: z.number().int().min(1).optional(),\n \n /**\n * Maximum network bandwidth in KB/s\n */\n maxNetworkKBps: z.number().int().min(1).optional(),\n }).optional(),\n \n /**\n * Permissions\n */\n permissions: z.object({\n /**\n * Allowed API access\n */\n allowedAPIs: z.array(z.string()).optional(),\n \n /**\n * Allowed file system paths\n */\n allowedPaths: z.array(z.string()).optional(),\n \n /**\n * Allowed network endpoints\n */\n allowedEndpoints: z.array(z.string()).optional(),\n \n /**\n * Allowed environment variables\n */\n allowedEnvVars: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Inter-Plugin Communication (IPC) configuration\n * Enables isolated plugins to communicate with the kernel and other plugins\n */\n ipc: z.object({\n /**\n * Enable IPC for sandboxed plugins\n */\n enabled: z.boolean().default(true)\n .describe('Allow sandboxed plugins to communicate via IPC'),\n \n /**\n * IPC transport mechanism\n */\n transport: z.enum([\n 'message-port', // MessagePort (worker threads / Web Workers)\n 'unix-socket', // Unix domain sockets (process isolation)\n 'tcp', // TCP sockets (container isolation)\n 'memory', // Shared memory channel (in-process VM)\n ]).default('message-port')\n .describe('IPC transport for cross-boundary communication'),\n \n /**\n * Maximum message size in bytes\n */\n maxMessageSize: z.number().int().min(1024).default(1048576)\n .describe('Maximum IPC message size in bytes (default 1MB)'),\n \n /**\n * Message timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000)\n .describe('IPC message response timeout in ms'),\n \n /**\n * Allowed service calls through IPC\n */\n allowedServices: z.array(z.string()).optional()\n .describe('Service names the sandboxed plugin may invoke via IPC'),\n }).optional(),\n}).describe('Plugin sandboxing configuration');\n\n/**\n * Plugin Performance Monitoring Configuration\n * Telemetry and performance tracking\n */\nexport const PluginPerformanceMonitoringSchema = z.object({\n /**\n * Enable performance monitoring\n */\n enabled: z.boolean().default(false),\n \n /**\n * Metrics to collect\n */\n metrics: z.array(z.enum([\n 'load-time',\n 'init-time',\n 'memory-usage',\n 'cpu-usage',\n 'api-calls',\n 'error-rate',\n 'cache-hit-rate',\n ])).optional(),\n \n /**\n * Sampling rate (0-1, where 1 = 100%)\n */\n samplingRate: z.number().min(0).max(1).default(1),\n \n /**\n * Reporting interval in seconds\n */\n reportingInterval: z.number().int().min(1).default(60),\n \n /**\n * Performance budget thresholds\n */\n budgets: z.object({\n /**\n * Maximum load time in milliseconds\n */\n maxLoadTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum init time in milliseconds\n */\n maxInitTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(0).optional(),\n }).optional(),\n \n /**\n * Action on budget violation\n */\n onBudgetViolation: z.enum(['warn', 'error', 'ignore']).default('warn'),\n}).describe('Plugin performance monitoring configuration');\n\n/**\n * Complete Plugin Loading Configuration\n * Combines all loading-related configurations\n */\nexport const PluginLoadingConfigSchema = z.object({\n /**\n * Loading strategy\n */\n strategy: PluginLoadingStrategySchema.default('lazy'),\n \n /**\n * Preloading configuration\n */\n preload: PluginPreloadConfigSchema.optional(),\n \n /**\n * Code splitting configuration\n */\n codeSplitting: PluginCodeSplittingSchema.optional(),\n \n /**\n * Dynamic import configuration\n */\n dynamicImport: PluginDynamicImportSchema.optional(),\n \n /**\n * Initialization configuration\n */\n initialization: PluginInitializationSchema.optional(),\n \n /**\n * Dependency resolution configuration\n */\n dependencyResolution: PluginDependencyResolutionSchema.optional(),\n \n /**\n * Hot reload configuration (development and production)\n */\n hotReload: PluginHotReloadSchema.optional(),\n \n /**\n * Caching configuration\n */\n caching: PluginCachingSchema.optional(),\n \n /**\n * Sandboxing configuration\n */\n sandboxing: PluginSandboxingSchema.optional(),\n \n /**\n * Performance monitoring\n */\n monitoring: PluginPerformanceMonitoringSchema.optional(),\n}).describe('Complete plugin loading configuration');\n\n/**\n * Plugin Loading Event\n * Emitted during plugin loading lifecycle\n */\nexport const PluginLoadingEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'load-started',\n 'load-completed',\n 'load-failed',\n 'init-started',\n 'init-completed',\n 'init-failed',\n 'preload-started',\n 'preload-completed',\n 'cache-hit',\n 'cache-miss',\n 'hot-reload',\n 'dynamic-load', // Plugin loaded at runtime\n 'dynamic-unload', // Plugin unloaded at runtime\n 'dynamic-discover', // Plugin discovered via registry\n ]),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Timestamp\n */\n timestamp: z.number().int().min(0),\n \n /**\n * Duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Error if event represents a failure\n */\n error: z.object({\n message: z.string(),\n code: z.string().optional(),\n stack: z.string().optional(),\n }).optional(),\n}).describe('Plugin loading lifecycle event');\n\n/**\n * Plugin Loading State\n * Tracks the current loading state of a plugin\n */\nexport const PluginLoadingStateSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current state\n */\n state: z.enum([\n 'pending', // Not yet loaded\n 'loading', // Currently loading\n 'loaded', // Code loaded, not initialized\n 'initializing', // Currently initializing\n 'ready', // Fully initialized and ready\n 'failed', // Failed to load or initialize\n 'reloading', // Hot reloading in progress\n 'unloading', // Being unloaded at runtime\n 'unloaded', // Successfully unloaded (dynamic loading)\n ]),\n \n /**\n * Load progress (0-100)\n */\n progress: z.number().min(0).max(100).default(0),\n \n /**\n * Loading start time\n */\n startedAt: z.number().int().min(0).optional(),\n \n /**\n * Loading completion time\n */\n completedAt: z.number().int().min(0).optional(),\n \n /**\n * Last error\n */\n lastError: z.string().optional(),\n \n /**\n * Retry count\n */\n retryCount: z.number().int().min(0).default(0),\n}).describe('Plugin loading state');\n\n// Export types\nexport type PluginLoadingStrategy = z.infer;\nexport type PluginPreloadConfig = z.infer;\nexport type PluginCodeSplitting = z.infer;\nexport type PluginDynamicImport = z.infer;\nexport type PluginInitialization = z.infer;\nexport type PluginDependencyResolution = z.infer;\nexport type PluginHotReload = z.infer;\nexport type PluginCaching = z.infer;\nexport type PluginSandboxing = z.infer;\nexport type PluginPerformanceMonitoring = z.infer;\nexport type PluginLoadingConfig = z.infer;\nexport type PluginLoadingEvent = z.infer;\nexport type PluginLoadingState = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// Service method interfaces use z.function() instead of z.any() for type safety.\n// Generic data fields use z.unknown() for type safety.\nexport const PluginContextSchema = z.object({\n ql: z.object({\n object: z.function().describe('Get object handle for method chaining'),\n query: z.function().describe('Execute a query'),\n }).passthrough().describe('ObjectQL Engine Interface'),\n\n os: z.object({\n getCurrentUser: z.function().describe('Get the current authenticated user'),\n getConfig: z.function().describe('Get platform configuration'),\n }).passthrough().describe('ObjectStack Kernel Interface'),\n\n logger: z.object({\n debug: z.function().describe('Log debug message'),\n info: z.function().describe('Log info message'),\n warn: z.function().describe('Log warning message'),\n error: z.function().describe('Log error message'),\n }).passthrough().describe('Logger Interface'),\n\n storage: z.object({\n get: z.function().describe('Get a value from storage'),\n set: z.function().describe('Set a value in storage'),\n delete: z.function().describe('Delete a value from storage'),\n }).passthrough().describe('Storage Interface'),\n\n i18n: z.object({\n t: z.function().describe('Translate a key'),\n getLocale: z.function().describe('Get current locale'),\n }).passthrough().describe('Internationalization Interface'),\n\n metadata: z.record(z.string(), z.unknown()),\n events: z.record(z.string(), z.unknown()),\n \n app: z.object({\n router: z.object({\n get: z.function().describe('Register GET route handler'),\n post: z.function().describe('Register POST route handler'),\n use: z.function().describe('Register middleware'),\n }).passthrough()\n }).passthrough().describe('App Framework Interface'),\n\n drivers: z.object({\n register: z.function().describe('Register a driver'),\n }).passthrough().describe('Driver Registry'),\n});\n\nexport type PluginContextData = z.infer;\nexport type PluginContext = PluginContextData;\n\n/**\n * Upgrade Context Schema\n *\n * Provides version migration context to the `onUpgrade` lifecycle hook.\n * Enables developers to write conditional migration logic based on\n * the previous and new versions.\n */\nexport const UpgradeContextSchema = z.object({\n /** Version before upgrade */\n previousVersion: z.string().describe('Version before upgrade'),\n\n /** Version after upgrade */\n newVersion: z.string().describe('Version after upgrade'),\n\n /** Whether this is a major version bump */\n isMajorUpgrade: z.boolean().describe('Whether this is a major version bump'),\n\n /** Metadata snapshot before upgrade (for migration logic) */\n previousMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Metadata snapshot before upgrade'),\n}).describe('Version migration context for onUpgrade hook');\n\nexport type UpgradeContext = z.infer;\n\nexport const PluginLifecycleSchema = z.object({\n onInstall: z.function().optional().describe('Called when plugin is installed'),\n \n onEnable: z.function().optional().describe('Called when plugin is enabled'),\n \n onDisable: z.function().optional().describe('Called when plugin is disabled'),\n \n onUninstall: z.function().optional().describe('Called when plugin is uninstalled'),\n \n onUpgrade: z.function().optional().describe('Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade'),\n});\n\nexport type PluginLifecycleHooks = z.infer;\n\n/**\n * Shared Plugin Types\n * These are the specialized plugin types common between Manifest (Package) and Plugin (Runtime).\n */\nexport const CORE_PLUGIN_TYPES = [\n 'ui', // Frontend: Serves static assets/SPA (e.g. Console, Studio)\n 'driver', // Connectivity: Database or Storage adapters (e.g. SQL, S3)\n 'server', // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL)\n 'app', // Business: Vertical Solution Bundle (Metadata + Logic)\n 'theme', // Appearance: UI Overrides & CSS Variables\n 'agent', // AI: Autonomous Agent & Tool Definitions\n 'objectql' // Core: ObjectQL Engine Data Provider\n] as const;\n\nexport const PluginSchema = PluginLifecycleSchema.extend({\n id: z.string().min(1).optional().describe('Unique Plugin ID (e.g. com.example.crm)'),\n type: z.enum([\n 'standard', // Default: General purpose backend logic (Service, Hook, etc.)\n ...CORE_PLUGIN_TYPES\n ]).default('standard').optional().describe('Plugin Type categorization for runtime behavior'),\n \n staticPath: z.string().optional().describe('Absolute path to static assets (Required for type=\"ui-plugin\")'),\n slug: z.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type=\"ui-plugin\")'),\n default: z.boolean().optional().describe('Serve at root path (Only one \"ui-plugin\" can be default)'),\n \n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic Version'),\n description: z.string().optional(),\n author: z.string().optional(),\n homepage: z.string().url().optional(),\n});\n\nexport type PluginDefinition = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data Import Strategy\n * Defines how the engine handles existing records.\n */\nexport const DatasetMode = z.enum([\n 'insert', // Try to insert, fail on duplicate\n 'update', // Only update found records, ignore new\n 'upsert', // Create new or Update existing (Standard)\n 'replace', // Delete ALL records in object then insert (Dangerous - use for cache tables)\n 'ignore' // Try to insert, silently skip duplicates\n]);\n\n/**\n * Dataset Schema (Seed Data / Fixtures)\n * \n * Standardized format for transporting data.\n * Used for:\n * 1. System Bootstrapping (Admin accounts, Standard Roles)\n * 2. Reference Data (Countries, Currencies)\n * 3. Demo/Test Data\n */\nexport const DatasetSchema = z.object({\n /** \n * Target Object \n * The machine name of the object to populate.\n */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target Object Name'),\n\n /** \n * Idempotency Key (The \"Upsert\" Key)\n * The field used to check if a record already exists.\n * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'.\n * Standard: 'id' is rarely used for portable seed data — prefer natural keys.\n */\n externalId: z.string().default('name').describe('Field match for uniqueness check'),\n\n /** \n * Import Strategy\n */\n mode: DatasetMode.default('upsert').describe('Conflict resolution strategy'),\n\n /**\n * Environment Scope\n * - 'all': Always load\n * - 'dev': Only for development/demo\n * - 'test': Only for CI/CD tests\n */\n env: z.array(z.enum(['prod', 'dev', 'test'])).default(['prod', 'dev', 'test']).describe('Applicable environments'),\n\n /** \n * The Payload\n * Array of raw JSON objects matching the Object Schema.\n */\n records: z.array(z.record(z.string(), z.unknown())).describe('Data records'),\n});\n\n/** Parsed/output type — all defaults are applied (env, mode, externalId always present) */\nexport type Dataset = z.infer;\n\n/** Input type — fields with defaults (env, mode, externalId) are optional */\nexport type DatasetInput = z.input;\n\nexport type DatasetImportMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\nimport { PluginLoadingConfigSchema } from './plugin-loading.zod';\nimport { CORE_PLUGIN_TYPES } from './plugin.zod';\nimport { DatasetSchema } from '../data/dataset.zod';\n\n/**\n * Schema for the ObjectStack Manifest.\n * This defines the structure of a package configuration in the ObjectStack ecosystem.\n * All packages (apps, plugins, drivers, modules) must conform to this schema.\n * \n * @example App Package\n * ```yaml\n * id: com.acme.crm\n * version: 1.0.0\n * type: app\n * name: Acme CRM\n * description: Customer Relationship Management system\n * permissions:\n * - system.user.read\n * - system.object.create\n * objects:\n * - \"./src/objects/*.object.yml\"\n * ```\n */\nexport const ManifestSchema = z.object({\n /** \n * Unique package identifier using reverse domain notation.\n * Must be unique across the entire ecosystem.\n * \n * @example \"com.steedos.crm\"\n * @example \"org.apache.superset\"\n */\n id: z.string().describe('Unique package identifier (reverse domain style)'),\n \n /**\n * Short namespace identifier for metadata scoping.\n * Used as a prefix for objects and other metadata to prevent naming collisions\n * across packages from different vendors.\n * \n * Rules:\n * - 2-20 characters, lowercase letters, digits, and underscores only.\n * - Must be unique within a running instance.\n * - Platform-reserved namespaces (no prefix applied): \"base\", \"system\".\n * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator).\n * \n * @example \"crm\" → objects become crm__account, crm__deal\n * @example \"todo\" → objects become todo__task\n * @example \"base\" → objects keep short name (platform reserved)\n */\n namespace: z.string()\n .regex(/^[a-z][a-z0-9_]{1,19}$/, 'Namespace must be 2-20 chars, lowercase alphanumeric + underscore')\n .optional()\n .describe('Short namespace identifier for metadata scoping (e.g. \"crm\", \"todo\")'),\n \n /** \n * Package version following semantic versioning (major.minor.patch).\n * \n * @example \"1.0.0\"\n * @example \"2.1.0-beta.1\"\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Package version (semantic versioning)'),\n \n /** \n * Type of the package in the ObjectStack ecosystem.\n * - plugin: General-purpose functionality extension (Runtime: standard)\n * - app: Business application package\n * - driver: Connectivity adapter\n * - server: Protocol gateway (Hono, GraphQL)\n * - ui: Frontend package (Static/SPA)\n * - theme: UI Theme\n * - agent: AI Agent\n * - module: Reusable code library/shared module\n * - objectql: Core engine\n * - adapter: Host adapter (Express, Fastify)\n */\n type: z.enum([\n 'plugin', \n ...CORE_PLUGIN_TYPES,\n 'module', \n 'gateway', // Deprecated: use 'server'\n 'adapter'\n ]).describe('Type of package'),\n \n /** \n * Human-readable name of the package.\n * Displayed in the UI for users.\n * \n * @example \"Project Management\"\n */\n name: z.string().describe('Human-readable package name'),\n \n /** \n * Brief description of the package functionality.\n * Displayed in the marketplace and plugin manager.\n */\n description: z.string().optional().describe('Package description'),\n \n /** \n * Array of permission strings that the package requires.\n * These form the \"Scope\" requested by the package at installation.\n * \n * @example [\"system.user.read\", \"system.data.write\"]\n */\n permissions: z.array(z.string()).optional().describe('Array of required permission strings'),\n \n /** \n * Glob patterns specifying ObjectQL schemas files.\n * Matches `*.object.yml` or `*.object.ts` files to load business objects.\n * \n * @example [\"./src/objects/*.object.yml\"]\n */\n objects: z.array(z.string()).optional().describe('Glob patterns for ObjectQL schemas files'),\n\n /**\n * Defines system level DataSources.\n * Matches `*.datasource.yml` files.\n * \n * @example [\"./src/datasources/*.datasource.mongo.yml\"]\n */\n datasources: z.array(z.string()).optional().describe('Glob patterns for Datasource definitions'),\n\n /**\n * Package Dependencies.\n * Map of package IDs to version requirements.\n * \n * @example { \"@steedos/plugin-auth\": \"^2.0.0\" }\n */\n dependencies: z.record(z.string(), z.string()).optional().describe('Package dependencies'),\n\n /**\n * Plugin Configuration Schema.\n * Defines the settings this plugin exposes to the user via UI/ENV.\n * Uses a simplified JSON Schema format.\n * \n * @example\n * {\n * \"title\": \"Stripe Config\",\n * \"properties\": {\n * \"apiKey\": { \"type\": \"string\", \"secret\": true },\n * \"currency\": { \"type\": \"string\", \"default\": \"USD\" }\n * }\n * }\n */\n configuration: z.object({\n title: z.string().optional(),\n properties: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']).describe('Data type of the setting'),\n default: z.unknown().optional().describe('Default value'),\n description: z.string().optional().describe('Tooltip description'),\n required: z.boolean().optional().describe('Is this setting required?'),\n secret: z.boolean().optional().describe('If true, value is encrypted/masked (e.g. API Keys)'),\n enum: z.array(z.string()).optional().describe('Allowed values for select inputs'),\n })).describe('Map of configuration keys to their definitions')\n }).optional().describe('Plugin configuration settings'),\n\n /**\n * Contribution Points (VS Code Style).\n * formalized way to extend the platform capabilities.\n */\n contributes: z.object({\n /**\n * Register new Metadata Kinds (CRDs).\n * Enables the system to parse and validate new file types.\n * Example: Registering a BI plugin to handle *.report.ts\n */\n kinds: z.array(z.object({\n id: z.string().describe('The generic identifier of the kind (e.g., \"sys.bi.report\")'),\n globs: z.array(z.string()).describe('File patterns to watch (e.g., [\"**/*.report.ts\"])'),\n description: z.string().optional().describe('Description of what this kind represents'),\n })).optional().describe('New Metadata Types to recognize'),\n\n /**\n * Register System Hooks.\n * Declares that this plugin listens to specific system events.\n */\n events: z.array(z.string()).optional().describe('Events this plugin listens to'),\n\n /**\n * Register UI Menus.\n */\n menus: z.record(z.string(), z.array(z.object({\n id: z.string(),\n label: z.string(),\n command: z.string().optional(),\n }))).optional().describe('UI Menu contributions'),\n\n /**\n * Register Custom Themes.\n */\n themes: z.array(z.object({\n id: z.string(),\n label: z.string(),\n path: z.string(),\n })).optional().describe('Theme contributions'),\n\n /**\n * Register Translations.\n * Path to translation files (e.g. \"locales/en.json\").\n */\n translations: z.array(z.object({\n locale: z.string(),\n path: z.string(),\n })).optional().describe('Translation resources'),\n\n /**\n * Register Server Actions.\n * Invocable functions exposed to Flows or API.\n */\n actions: z.array(z.object({\n name: z.string().describe('Unique action name'),\n label: z.string().optional(),\n description: z.string().optional(),\n input: z.unknown().optional().describe('Input validation schema'),\n output: z.unknown().optional().describe('Output schema'),\n })).optional().describe('Exposed server actions'),\n\n /**\n * Register Storage Drivers.\n * Enables connecting to new types of datasources.\n */\n drivers: z.array(z.object({\n id: z.string().describe('Driver unique identifier (e.g. \"postgres\", \"mongo\")'),\n label: z.string().describe('Human readable name'),\n description: z.string().optional(),\n })).optional().describe('Driver contributions'),\n\n /**\n * Register Custom Field Types.\n * Extends the data model with new widget types.\n */\n fieldTypes: z.array(z.object({\n name: z.string().describe('Unique field type name (e.g. \"vector\")'),\n label: z.string().describe('Display label'),\n description: z.string().optional(),\n })).optional().describe('Field Type contributions'),\n \n /**\n * Register Custom Query Operators/Functions.\n * Extends ObjectQL with new functions (e.g. distance()).\n */\n functions: z.array(z.object({\n name: z.string().describe('Function name (e.g. \"distance\")'),\n description: z.string().optional(),\n args: z.array(z.string()).optional().describe('Argument types'),\n returnType: z.string().optional(),\n })).optional().describe('Query Function contributions'),\n\n /**\n * Register API Route Namespaces.\n * Declares the API endpoints this plugin provides to the HttpDispatcher.\n * The kernel routes matching prefixes to this plugin's handler.\n * \n * @example\n * routes: [\n * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] }\n * ]\n */\n routes: z.array(z.object({\n /** URL path prefix (e.g. \"/api/v1/ai\") */\n prefix: z.string().regex(/^\\//).describe('API path prefix'),\n /** Service name this plugin provides */\n service: z.string().describe('Service name this plugin provides'),\n /** Protocol method names implemented */\n methods: z.array(z.string()).optional()\n .describe('Protocol method names implemented (e.g. [\"aiNlq\", \"aiChat\"])'),\n })).optional().describe('API route contributions to HttpDispatcher'),\n\n /**\n * Register CLI Commands.\n * Allows plugins to extend the ObjectStack CLI with custom commands.\n * Each command entry declares metadata; the actual Commander.js command\n * is resolved at runtime by importing the plugin's module.\n * \n * The plugin package must export a `commands` array of Commander.js `Command` instances\n * from its main entry point or from the path specified in `module`.\n * \n * @example\n * ```yaml\n * commands:\n * - name: marketplace\n * description: \"Manage marketplace apps\"\n * module: \"./cli\" # optional, defaults to package main\n * - name: deploy\n * description: \"Deploy to cloud\"\n * ```\n */\n commands: z.array(z.object({\n /** CLI command name (e.g., \"marketplace\", \"deploy\"). Must be a valid CLI identifier. */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n /** Brief description shown in `os --help` */\n description: z.string().optional().describe('Command description for help text'),\n /** \n * Optional module path (relative to package root) that exports the Commander.js commands.\n * If omitted, the CLI will import from the package's main entry point.\n * The module must export a `commands` array of Commander.js `Command` instances,\n * or a single `Command` instance as default export.\n */\n module: z.string().optional().describe('Module path exporting Commander.js commands'),\n })).optional().describe('CLI command contributions'),\n }).optional().describe('Platform contributions'),\n\n /** \n * Initial data seeding configuration.\n * Defines default records to be inserted when the package is installed.\n * \n * Uses the standard DatasetSchema which supports idempotent upsert via\n * `externalId`, environment scoping via `env`, and multiple conflict\n * resolution modes.\n * \n * @deprecated Prefer using the top-level `data` field on the Stack Definition\n * (defineStack({ data: [...] })) for better visibility and metadata registration.\n * This field is retained for backward compatibility with manifest-only packages.\n */\n data: z.array(DatasetSchema).optional().describe('Initial seed data (prefer top-level data field)'),\n\n /**\n * Plugin Capability Manifest.\n * Declares protocols implemented, interfaces provided, dependencies, and extension points.\n * This enables plugin interoperability and automatic discovery.\n */\n capabilities: PluginCapabilityManifestSchema.optional()\n .describe('Plugin capability declarations for interoperability'),\n\n /** \n * Extension points contributed by this package.\n * Allows packages to extend UI components, add functionality, etc.\n */\n extensions: z.record(z.string(), z.unknown()).optional().describe('Extension points and contributions'),\n\n /**\n * Plugin Loading Configuration.\n * Configures how the plugin is loaded, initialized, and managed at runtime.\n * Includes strategies for lazy loading, code splitting, caching, and hot reload.\n */\n loading: PluginLoadingConfigSchema.optional()\n .describe('Plugin loading and runtime behavior configuration'),\n\n /**\n * Platform Compatibility Requirements.\n * Specifies the minimum ObjectStack platform version required to run this package.\n * Used at install time to prevent incompatible packages from being installed.\n *\n * @example\n * ```yaml\n * engine:\n * objectstack: \">=3.0.0\"\n * ```\n */\n engine: z.object({\n /** ObjectStack platform version requirement (SemVer range) */\n objectstack: z.string()\n .regex(/^[><=~^]*\\d+\\.\\d+\\.\\d+/)\n .describe('ObjectStack platform version requirement (SemVer range, e.g. \">=3.0.0\")'),\n }).optional().describe('Platform compatibility requirements'),\n});\n\n/**\n * TypeScript type inferred from the ManifestSchema.\n * Use this type for type-safe manifest handling in TypeScript code.\n */\nexport type ObjectStackManifest = z.infer;\nexport type ObjectStackManifestInput = z.input;\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Customization Layer Protocol\n * \n * Defines the overlay system for managing user customizations on top of\n * package-delivered metadata. This protocol solves the critical challenge\n * of separating \"vendor-managed\" metadata from \"customer-customized\" metadata,\n * enabling safe package upgrades without losing user changes.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed vs Unmanaged metadata components\n * - **ServiceNow**: Update Sets with collision detection\n * - **WordPress**: Parent/child theme overlay model\n * - **Kubernetes**: Strategic merge patch for resource customization\n * \n * ## Three-Layer Model\n * ```\n * ┌─────────────────────────────────┐\n * │ User Layer (scope: user) │ ← Personal overrides (per-user)\n * ├─────────────────────────────────┤\n * │ Platform Layer (scope: platform)│ ← Admin customizations (per-tenant)\n * ├─────────────────────────────────┤\n * │ System Layer (scope: system) │ ← Package-delivered metadata (read-only)\n * └─────────────────────────────────┘\n * ```\n * \n * ## Merge Resolution Order\n * Effective metadata = System ← merge(Platform) ← merge(User)\n * Each layer only stores the delta (changed fields), not the full definition.\n */\n\n// ==========================================\n// Customization Tracking\n// ==========================================\n\n/**\n * Customization Origin\n * Identifies who created the customization.\n */\nexport const CustomizationOriginSchema = z.enum([\n 'package', // Delivered by a plugin package (system layer, read-only)\n 'admin', // Created/modified by platform admin via UI\n 'user', // Created/modified by end user via UI\n 'migration', // Created during data migration\n 'api', // Created via API\n]);\n\n/**\n * Field-Level Change Tracking\n * Records exactly which fields were modified by the customer.\n */\nexport const FieldChangeSchema = z.object({\n /** JSON path to the changed field (e.g. \"fields.status.label\") */\n path: z.string().describe('JSON path to the changed field'),\n\n /** Original value from the package (for diff/rollback) */\n originalValue: z.unknown().optional().describe('Original value from the package'),\n\n /** Current customized value */\n currentValue: z.unknown().describe('Current customized value'),\n\n /** Who made this change */\n changedBy: z.string().optional().describe('User or admin who made this change'),\n\n /** When this change was made */\n changedAt: z.string().datetime().optional().describe('Timestamp of the change'),\n});\n\n/**\n * Metadata Overlay Schema\n * \n * Represents a customization layer on top of package-delivered metadata.\n * Each overlay stores only the delta (changed fields) relative to the base definition.\n * \n * During package upgrades, the system performs a 3-way merge:\n * 1. Old package version (base)\n * 2. New package version (theirs)\n * 3. Customer customizations (ours)\n * \n * @example\n * ```yaml\n * # Package delivers: object \"crm__account\" with field \"status\" label \"Status\"\n * # Admin changes label to \"Account Status\"\n * # Overlay record:\n * baseType: object\n * baseName: crm__account\n * packageId: com.acme.crm\n * packageVersion: \"1.0.0\"\n * changes:\n * - path: \"fields.status.label\"\n * originalValue: \"Status\"\n * currentValue: \"Account Status\"\n * ```\n */\nexport const MetadataOverlaySchema = z.object({\n /** Primary key */\n id: z.string().describe('Overlay record ID (UUID)'),\n\n /** The metadata type being customized (e.g. \"object\", \"view\", \"flow\") */\n baseType: z.string().describe('Metadata type being customized'),\n\n /** The metadata name being customized (e.g. \"crm__account\") */\n baseName: z.string().describe('Metadata name being customized'),\n\n /** Package that owns the base metadata (null for platform-created metadata) */\n packageId: z.string().optional().describe('Package ID that delivered the base metadata'),\n\n /** Package version when the customization was made (for upgrade diffing) */\n packageVersion: z.string().optional().describe('Package version when overlay was created'),\n\n /** Customization scope */\n scope: z.enum(['platform', 'user']).default('platform')\n .describe('Customization scope (platform=admin, user=personal)'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Owner user ID (for user-scope overlays) */\n owner: z.string().optional().describe('Owner user ID for user-scope overlays'),\n\n /**\n * The overlay payload.\n * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396).\n * - To modify a field: include the field with its new value\n * - To delete a field: set its value to null\n * - Omitted fields remain unchanged from base\n */\n patch: z.record(z.string(), z.unknown()).describe('JSON Merge Patch payload (changed fields only)'),\n\n /**\n * Detailed change tracking for each modified field.\n * Enables field-level conflict detection during upgrades.\n */\n changes: z.array(FieldChangeSchema).optional()\n .describe('Field-level change tracking for conflict detection'),\n\n /** Whether this overlay is currently active */\n active: z.boolean().default(true).describe('Whether this overlay is active'),\n\n /** Audit timestamps */\n createdAt: z.string().datetime().optional(),\n createdBy: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n updatedBy: z.string().optional(),\n});\n\n// ==========================================\n// Merge & Conflict Resolution\n// ==========================================\n\n/**\n * Merge Conflict\n * Represents a conflict between package update and customer customization.\n */\nexport const MergeConflictSchema = z.object({\n /** JSON path to the conflicting field */\n path: z.string().describe('JSON path to the conflicting field'),\n\n /** Value in the old package version */\n baseValue: z.unknown().describe('Value in the old package version'),\n\n /** Value in the new package version */\n incomingValue: z.unknown().describe('Value in the new package version'),\n\n /** Customer's customized value */\n customValue: z.unknown().describe('Customer customized value'),\n\n /** Suggested resolution strategy */\n suggestedResolution: z.enum([\n 'keep-custom', // Keep customer's customization\n 'accept-incoming', // Accept package update\n 'manual', // Requires manual resolution\n ]).describe('Suggested resolution strategy'),\n\n /** Reason for the suggested resolution */\n reason: z.string().optional().describe('Explanation for the suggested resolution'),\n});\n\n/**\n * Merge Strategy Configuration\n * Controls how metadata merging behaves during package upgrades.\n */\nexport const MergeStrategyConfigSchema = z.object({\n /** Default strategy when no field-level rule matches */\n defaultStrategy: z.enum([\n 'keep-custom', // Preserve all customer customizations (safe)\n 'accept-incoming', // Accept all package updates (overwrite)\n 'three-way-merge', // Intelligent 3-way merge with conflict detection\n ]).default('three-way-merge').describe('Default merge strategy'),\n\n /** \n * Field paths that should always accept incoming package updates.\n * Use for fields that the package vendor considers \"owned\" and should not be customized.\n * @example [\"fields.*.type\", \"triggers.*\"]\n */\n alwaysAcceptIncoming: z.array(z.string()).optional()\n .describe('Field paths that always accept package updates'),\n\n /**\n * Field paths where customer customizations always win.\n * Use for UI-facing fields like labels, descriptions, help text.\n * @example [\"fields.*.label\", \"fields.*.helpText\", \"description\"]\n */\n alwaysKeepCustom: z.array(z.string()).optional()\n .describe('Field paths where customer customizations always win'),\n\n /** Whether to automatically resolve non-conflicting changes */\n autoResolveNonConflicting: z.boolean().default(true)\n .describe('Auto-resolve changes that do not conflict'),\n});\n\n/**\n * Merge Result\n * Result of a 3-way merge operation during package upgrade.\n */\nexport const MergeResultSchema = z.object({\n /** Whether the merge completed successfully (no unresolved conflicts) */\n success: z.boolean().describe('Whether merge completed without unresolved conflicts'),\n\n /** The merged metadata payload */\n mergedMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Merged metadata result'),\n\n /** Updated overlay with remaining customizations */\n updatedOverlay: z.record(z.string(), z.unknown()).optional()\n .describe('Updated overlay after merge'),\n\n /** List of conflicts that require manual resolution */\n conflicts: z.array(MergeConflictSchema).optional()\n .describe('Unresolved merge conflicts'),\n\n /** Summary of automatically resolved changes */\n autoResolved: z.array(z.object({\n path: z.string(),\n resolution: z.string(),\n description: z.string().optional(),\n })).optional().describe('Summary of auto-resolved changes'),\n\n /** Statistics */\n stats: z.object({\n totalFields: z.number().int().min(0).describe('Total fields evaluated'),\n unchanged: z.number().int().min(0).describe('Fields with no changes'),\n autoResolved: z.number().int().min(0).describe('Fields auto-resolved'),\n conflicts: z.number().int().min(0).describe('Fields with conflicts'),\n }).optional(),\n});\n\n// ==========================================\n// Customization Management\n// ==========================================\n\n/**\n * Customizable Metadata Policy\n * Defines what parts of a metadata item can be customized by admins/users.\n * Package vendors use this to control customization boundaries.\n */\nexport const CustomizationPolicySchema = z.object({\n /** Metadata type this policy applies to */\n metadataType: z.string().describe('Metadata type (e.g. \"object\", \"view\")'),\n\n /** Whether customization is allowed at all for this type */\n allowCustomization: z.boolean().default(true),\n\n /**\n * Field paths that are locked (cannot be customized).\n * @example [\"name\", \"type\", \"fields.*.type\"]\n */\n lockedFields: z.array(z.string()).optional()\n .describe('Field paths that cannot be customized'),\n\n /**\n * Field paths that are customizable.\n * If specified, only these fields can be customized (whitelist mode).\n * @example [\"label\", \"description\", \"fields.*.label\", \"fields.*.helpText\"]\n */\n customizableFields: z.array(z.string()).optional()\n .describe('Field paths that can be customized (whitelist)'),\n\n /**\n * Whether users can add new fields to package objects.\n * When true, admins can extend package objects with custom fields.\n */\n allowAddFields: z.boolean().default(true)\n .describe('Whether admins can add new fields to package objects'),\n\n /**\n * Whether users can delete package-delivered fields.\n * Typically false — fields can only be hidden, not deleted.\n */\n allowDeleteFields: z.boolean().default(false)\n .describe('Whether admins can delete package-delivered fields'),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type CustomizationOrigin = z.infer;\nexport type FieldChange = z.infer;\nexport type MetadataOverlay = z.infer;\nexport type MergeConflict = z.infer;\nexport type MergeStrategyConfig = z.infer;\nexport type MergeResult = z.infer;\nexport type CustomizationPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Loader Protocol\n * \n * Defines the standard interface for loading and saving metadata in ObjectStack.\n * This protocol enables consistent metadata operations across different storage backends\n * (filesystem, HTTP, S3, databases) and serialization formats (JSON, YAML, TypeScript).\n */\n\n/**\n * Metadata Format Enum\n * Supported serialization formats for metadata\n */\nexport const MetadataFormatSchema = z.enum(['json', 'yaml', 'typescript', 'javascript']);\n\n/**\n * Metadata Statistics\n * Information about a metadata item without loading its full content\n */\nexport const MetadataStatsSchema = z.object({\n /**\n * Size of the metadata file in bytes\n */\n size: z.number().int().min(0).describe('File size in bytes'),\n \n /**\n * Last modification timestamp\n */\n modifiedAt: z.string().datetime().describe('Last modified date'),\n \n /**\n * ETag for cache validation\n * Used for conditional requests (If-None-Match header)\n */\n etag: z.string().describe('Entity tag for cache validation'),\n \n /**\n * Serialization format\n */\n format: MetadataFormatSchema.describe('Serialization format'),\n \n /**\n * Full file path (if applicable)\n */\n path: z.string().optional().describe('File system path'),\n \n /**\n * Additional metadata provider-specific properties\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Provider-specific metadata'),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n /**\n * Glob patterns to match files\n * Example: [\"**\\/*.object.ts\", \"**\\/*.object.json\"]\n */\n patterns: z.array(z.string()).optional().describe('File glob patterns'),\n \n /**\n * If-None-Match header for conditional loading\n * Only load if ETag doesn't match\n */\n ifNoneMatch: z.string().optional().describe('ETag for conditional request'),\n \n /**\n * If-Modified-Since header for conditional loading\n */\n ifModifiedSince: z.string().datetime().optional().describe('Only load if modified after this date'),\n \n /**\n * Whether to validate against Zod schema\n */\n validate: z.boolean().default(true).describe('Validate against schema'),\n \n /**\n * Whether to use cache if available\n */\n useCache: z.boolean().default(true).describe('Enable caching'),\n \n /**\n * Filter function (serialized as string)\n * Example: \"(item) => item.name.startsWith('sys_')\"\n */\n filter: z.string().optional().describe('Filter predicate as string'),\n \n /**\n * Maximum number of items to load\n */\n limit: z.number().int().min(1).optional().describe('Maximum items to load'),\n \n /**\n * Recursively search subdirectories\n */\n recursive: z.boolean().default(true).describe('Search subdirectories'),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n /**\n * Serialization format\n */\n format: MetadataFormatSchema.default('typescript').describe('Output format'),\n \n /**\n * Prettify output (formatted with indentation)\n */\n prettify: z.boolean().default(true).describe('Format with indentation'),\n \n /**\n * Indentation size (spaces)\n */\n indent: z.number().int().min(0).max(8).default(2).describe('Indentation spaces'),\n \n /**\n * Sort object keys alphabetically\n */\n sortKeys: z.boolean().default(false).describe('Sort object keys'),\n \n /**\n * Include default values in output\n */\n includeDefaults: z.boolean().default(false).describe('Include default values'),\n \n /**\n * Create backup before overwriting\n */\n backup: z.boolean().default(false).describe('Create backup file'),\n \n /**\n * Overwrite if exists\n */\n overwrite: z.boolean().default(true).describe('Overwrite existing file'),\n \n /**\n * Atomic write (write to temp file, then rename)\n */\n atomic: z.boolean().default(true).describe('Use atomic write operation'),\n \n /**\n * Custom file path (overrides default location)\n */\n path: z.string().optional().describe('Custom output path'),\n});\n\n/**\n * Metadata Export Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n /**\n * Output file path\n */\n output: z.string().describe('Output file path'),\n \n /**\n * Export format\n */\n format: MetadataFormatSchema.default('json').describe('Export format'),\n \n /**\n * Filter predicate as string\n */\n filter: z.string().optional().describe('Filter items to export'),\n \n /**\n * Include statistics in export\n */\n includeStats: z.boolean().default(false).describe('Include metadata statistics'),\n \n /**\n * Compress output\n */\n compress: z.boolean().default(false).describe('Compress output (gzip)'),\n \n /**\n * Pretty print output\n */\n prettify: z.boolean().default(true).describe('Pretty print output'),\n});\n\n/**\n * Metadata Import Options\n */\nexport const MetadataImportOptionsSchema = z.object({\n /**\n * Conflict resolution strategy\n */\n conflictResolution: z.enum(['skip', 'overwrite', 'merge', 'fail'])\n .default('merge')\n .describe('How to handle existing items'),\n \n /**\n * Validate items against schema\n */\n validate: z.boolean().default(true).describe('Validate before import'),\n \n /**\n * Dry run (don't actually save)\n */\n dryRun: z.boolean().default(false).describe('Simulate import without saving'),\n \n /**\n * Continue on errors\n */\n continueOnError: z.boolean().default(false).describe('Continue if validation fails'),\n \n /**\n * Transform function (as string)\n * Example: \"(item) => ({ ...item, imported: true })\"\n */\n transform: z.string().optional().describe('Transform items before import'),\n});\n\n/**\n * Metadata Loader Result\n * Result of a metadata load operation\n */\nexport const MetadataLoadResultSchema = z.object({\n /**\n * Loaded data\n */\n data: z.unknown().nullable().describe('Loaded metadata'),\n \n /**\n * Whether data came from cache (304 Not Modified)\n */\n fromCache: z.boolean().default(false).describe('Loaded from cache'),\n \n /**\n * Not modified (conditional request matched)\n */\n notModified: z.boolean().default(false).describe('Not modified since last request'),\n \n /**\n * ETag of loaded data\n */\n etag: z.string().optional().describe('Entity tag'),\n \n /**\n * Statistics about loaded data\n */\n stats: MetadataStatsSchema.optional().describe('Metadata statistics'),\n \n /**\n * Load time in milliseconds\n */\n loadTime: z.number().min(0).optional().describe('Load duration in ms'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n /**\n * Whether save was successful\n */\n success: z.boolean().describe('Save successful'),\n \n /**\n * Path where file was saved\n */\n path: z.string().describe('Output path'),\n \n /**\n * Generated ETag\n */\n etag: z.string().optional().describe('Generated entity tag'),\n \n /**\n * File size in bytes\n */\n size: z.number().int().min(0).optional().describe('File size'),\n \n /**\n * Save time in milliseconds\n */\n saveTime: z.number().min(0).optional().describe('Save duration in ms'),\n \n /**\n * Backup path (if created)\n */\n backupPath: z.string().optional().describe('Backup file path'),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum(['added', 'changed', 'deleted']).describe('Event type'),\n \n /**\n * Metadata type (e.g., 'object', 'view', 'app')\n */\n metadataType: z.string().describe('Type of metadata'),\n \n /**\n * Item name/identifier\n */\n name: z.string().describe('Item identifier'),\n \n /**\n * Full file path\n */\n path: z.string().describe('File path'),\n \n /**\n * Loaded item data (for added/changed events)\n */\n data: z.unknown().optional().describe('Item data'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\n/**\n * Metadata Collection Info\n * Summary of a metadata collection\n */\nexport const MetadataCollectionInfoSchema = z.object({\n /**\n * Collection type (e.g., 'object', 'view', 'app')\n */\n type: z.string().describe('Collection type'),\n \n /**\n * Total items in collection\n */\n count: z.number().int().min(0).describe('Number of items'),\n \n /**\n * Formats found in collection\n */\n formats: z.array(MetadataFormatSchema).describe('Formats in collection'),\n \n /**\n * Total size in bytes\n */\n totalSize: z.number().int().min(0).optional().describe('Total size in bytes'),\n \n /**\n * Last modified timestamp\n */\n lastModified: z.string().datetime().optional().describe('Last modification date'),\n \n /**\n * Collection location (path or URL)\n */\n location: z.string().optional().describe('Collection location'),\n});\n\n/**\n * Metadata Loader Interface Contract\n * Defines the standard methods all metadata loaders must implement\n */\nexport const MetadataLoaderContractSchema = z.object({\n /**\n * Loader name/identifier\n */\n name: z.string().describe('Loader identifier'),\n\n /**\n * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:')\n */\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Protocol identifier'),\n\n /**\n * Detailed capabilities\n */\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }).describe('Loader capabilities'),\n \n /**\n * Supported formats\n */\n supportedFormats: z.array(MetadataFormatSchema).describe('Supported formats'),\n \n /**\n * Whether loader supports watching for changes\n */\n supportsWatch: z.boolean().default(false).describe('Supports file watching'),\n \n /**\n * Whether loader supports saving\n */\n supportsWrite: z.boolean().default(true).describe('Supports write operations'),\n \n /**\n * Whether loader supports caching\n */\n supportsCache: z.boolean().default(true).describe('Supports caching'),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Manager Configuration\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory path'),\n \n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).default(['typescript', 'json', 'yaml']).describe('Enabled formats'),\n \n /**\n * Cache configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable caching'),\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n maxSize: z.number().int().min(0).optional().describe('Max cache size in bytes'),\n }).optional().describe('Cache settings'),\n \n /**\n * Watch for file changes\n */\n watch: z.boolean().default(false).describe('Enable file watching'),\n \n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n ignoreInitial: z.boolean().default(true).describe('Ignore initial add events'),\n }).optional().describe('File watcher options'),\n \n /**\n * Validation settings\n */\n validation: z.object({\n strict: z.boolean().default(true).describe('Strict validation'),\n throwOnError: z.boolean().default(true).describe('Throw on validation error'),\n }).optional().describe('Validation settings'),\n \n /**\n * Loader-specific options\n */\n loaderOptions: z.record(z.string(), z.unknown()).optional().describe('Loader-specific configuration'),\n});\n\n// Export types\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoadOptions = z.input;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { MetadataManagerConfigSchema } from './metadata-loader.zod';\nimport { MergeStrategyConfigSchema, CustomizationPolicySchema } from './metadata-customization.zod';\n\n/**\n * # Metadata Plugin Protocol\n *\n * Defines the specification for the **Metadata Plugin** — the central authority\n * responsible for managing ALL metadata across the ObjectStack platform.\n *\n * ## Architecture\n * The Metadata Plugin consolidates all scattered metadata operations into a single,\n * cohesive plugin that \"takes over\" the entire platform's metadata management:\n *\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ Metadata Plugin │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Type Registry │ │ Loader │ │ Customization Layer │ │\n * │ │ (all types) │ │ (file/db/s3)│ │ (overlay / merge) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Persistence │ │ Query │ │ Lifecycle │ │\n * │ │ (db records) │ │ (search) │ │ (validate/deploy) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n *\n * ## References\n * - kernel/metadata-loader.zod.ts — Storage backend protocol\n * - kernel/metadata-customization.zod.ts — Overlay/merge protocol\n * - system/metadata-persistence.zod.ts — Database record format\n * - contracts/metadata-service.ts — Service interface\n */\n\n// ==========================================\n// Metadata Type Registry\n// ==========================================\n\n/**\n * Platform Metadata Type Enum\n *\n * The canonical list of all metadata types managed by the platform.\n * Each type maps to a specific Zod schema (e.g., ObjectSchema, ViewSchema).\n * Plugins can extend this registry via `contributes.kinds` in the manifest.\n *\n * ## Naming Convention\n * **IMPORTANT:** All metadata type names are in **SINGULAR** form:\n * - ✅ Use: `'agent'`, `'tool'`, `'skill'`, `'view'`, `'flow'`, `'action'`\n * - ❌ NOT: `'agents'`, `'tools'`, `'skills'`, `'views'`, `'flows'`, `'actions'`\n *\n * This convention applies to:\n * - Protocol definitions (this enum)\n * - UI plugin registrations (`metadataTypes`, `metadataIcons`)\n * - Metadata service operations\n * - File patterns (`*.agent.ts`, `*.tool.ts`)\n *\n * REST API endpoints continue to use plural forms per REST conventions:\n * - `/api/v1/ai/agents`, `/api/v1/ai/conversations`\n */\nexport const MetadataTypeSchema = z.enum([\n // Data Protocol\n 'object', // Business entity definition (ObjectSchema)\n 'field', // Standalone field definition (FieldSchema)\n 'trigger', // Data-layer event triggers (TriggerSchema)\n 'validation', // Validation rules (ValidationSchema)\n 'hook', // Data hooks (HookSchema)\n\n // UI Protocol\n 'view', // List/form views (ViewSchema)\n 'page', // Standalone pages (PageSchema)\n 'dashboard', // Dashboard layouts (DashboardSchema)\n 'app', // Application shell (AppSchema)\n 'action', // UI/Server actions (ActionSchema)\n 'report', // Report definitions (ReportSchema)\n\n // Automation Protocol\n 'flow', // Visual logic flows (FlowSchema)\n 'workflow', // State machines (WorkflowSchema)\n 'approval', // Approval processes (ApprovalSchema)\n\n // System Protocol\n 'datasource', // Data connections (DatasourceSchema)\n 'translation', // i18n resources (TranslationSchema)\n 'router', // API routes\n 'function', // Serverless functions\n 'service', // Service definitions\n\n // Security Protocol\n 'permission', // Permission sets (PermissionSetSchema)\n 'profile', // User profiles (ProfileSchema)\n 'role', // Security roles\n\n // AI Protocol\n 'agent', // AI agent definitions (AgentSchema)\n 'tool', // AI tool definitions (ToolSchema)\n 'skill', // AI skill definitions (SkillSchema)\n]);\n\nexport type MetadataType = z.infer;\n\n// ==========================================\n// Type Registry Entry\n// ==========================================\n\n/**\n * Metadata Type Registry Entry\n *\n * Describes a registered metadata type, including its validation schema,\n * file patterns, and capabilities. Used by the metadata plugin to:\n * 1. Discover metadata files on disk\n * 2. Validate metadata payloads\n * 3. Determine storage behavior\n */\nexport const MetadataTypeRegistryEntrySchema = z.object({\n /** Metadata type identifier (e.g., 'object', 'view') */\n type: MetadataTypeSchema.describe('Metadata type identifier'),\n\n /** Human-readable label */\n label: z.string().describe('Display label for the metadata type'),\n\n /** Brief description */\n description: z.string().optional().describe('Description of the metadata type'),\n\n /**\n * File glob patterns for this type.\n * Used to discover metadata files on disk.\n * @example [\"**\\/*.object.ts\", \"**\\/*.object.yml\"]\n */\n filePatterns: z.array(z.string()).describe('Glob patterns to discover files of this type'),\n\n /**\n * Whether this type supports the customization overlay system.\n * When true, platform/user overlays can be applied on top of package-delivered metadata.\n */\n supportsOverlay: z.boolean().default(true).describe('Whether overlay customization is supported'),\n\n /**\n * Whether metadata of this type can be created at runtime via API.\n * Some types (e.g., 'object') may be restricted to deployment-only.\n */\n allowRuntimeCreate: z.boolean().default(true).describe('Allow runtime creation via API'),\n\n /**\n * Whether this type supports versioning.\n * When true, changes are tracked with version history.\n */\n supportsVersioning: z.boolean().default(false).describe('Whether version history is tracked'),\n\n /**\n * Priority order for loading (lower = earlier).\n * Objects load before views, views before dashboards.\n */\n loadOrder: z.number().int().min(0).default(100).describe('Loading priority (lower = earlier)'),\n\n /** The domain this type belongs to */\n domain: z.enum(['data', 'ui', 'automation', 'system', 'security', 'ai'])\n .describe('Protocol domain'),\n});\n\nexport type MetadataTypeRegistryEntry = z.infer;\n\n// ==========================================\n// Metadata Query Protocol\n// ==========================================\n\n/**\n * Metadata Query Schema\n *\n * Standard protocol for searching and filtering metadata items.\n * Used by the metadata service to support advanced metadata discovery.\n */\nexport const MetadataQuerySchema = z.object({\n /** Filter by metadata type(s) */\n types: z.array(MetadataTypeSchema).optional().describe('Filter by metadata types'),\n\n /** Filter by namespace(s) */\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n\n /** Filter by package ID */\n packageId: z.string().optional().describe('Filter by owning package'),\n\n /** Full-text search across name, label, description */\n search: z.string().optional().describe('Full-text search query'),\n\n /** Filter by scope */\n scope: z.enum(['system', 'platform', 'user']).optional().describe('Filter by scope'),\n\n /** Filter by state */\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional().describe('Filter by lifecycle state'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Sort field */\n sortBy: z.enum(['name', 'type', 'updatedAt', 'createdAt']).default('name').describe('Sort field'),\n\n /** Sort direction */\n sortOrder: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n\n /** Pagination: page number (1-based) */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(500).default(50).describe('Items per page'),\n});\n\nexport type MetadataQuery = z.input;\n\n/**\n * Metadata Query Result\n */\nexport const MetadataQueryResultSchema = z.object({\n /** Matched items */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n namespace: z.string().optional().describe('Namespace'),\n label: z.string().optional().describe('Display label'),\n scope: z.enum(['system', 'platform', 'user']).optional(),\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional(),\n packageId: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n })).describe('Matched metadata items'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching items'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page'),\n\n /** Page size */\n pageSize: z.number().int().min(1).describe('Page size'),\n});\n\nexport type MetadataQueryResult = z.infer;\n\n// ==========================================\n// Metadata Lifecycle Events\n// ==========================================\n\n/**\n * Metadata Event Schema\n *\n * Events emitted by the metadata plugin when metadata changes.\n * Enables reactive patterns across the platform (cache invalidation,\n * UI refresh, dependency tracking, etc.).\n */\nexport const MetadataEventSchema = z.object({\n /** Event type */\n event: z.enum([\n 'metadata.registered',\n 'metadata.updated',\n 'metadata.unregistered',\n 'metadata.validated',\n 'metadata.deployed',\n 'metadata.overlay.applied',\n 'metadata.overlay.removed',\n 'metadata.imported',\n 'metadata.exported',\n ]).describe('Event type'),\n\n /** Metadata type */\n metadataType: MetadataTypeSchema.describe('Metadata type'),\n\n /** Item name */\n name: z.string().describe('Metadata item name'),\n\n /** Namespace */\n namespace: z.string().optional().describe('Namespace'),\n\n /** Package ID (if package-managed) */\n packageId: z.string().optional().describe('Owning package ID'),\n\n /** Timestamp */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /** Actor who caused the event */\n actor: z.string().optional().describe('User or system that triggered the event'),\n\n /** Additional event-specific payload */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event-specific payload'),\n});\n\nexport type MetadataEvent = z.infer;\n\n// ==========================================\n// Metadata Validation\n// ==========================================\n\n/**\n * Metadata Validation Result\n */\nexport const MetadataValidationResultSchema = z.object({\n /** Whether validation passed */\n valid: z.boolean().describe('Whether the metadata is valid'),\n\n /** Validation errors */\n errors: z.array(z.object({\n path: z.string().describe('JSON path to the invalid field'),\n message: z.string().describe('Error description'),\n code: z.string().optional().describe('Error code'),\n })).optional().describe('Validation errors'),\n\n /** Validation warnings (non-blocking) */\n warnings: z.array(z.object({\n path: z.string().describe('JSON path to the field'),\n message: z.string().describe('Warning description'),\n })).optional().describe('Validation warnings'),\n});\n\nexport type MetadataValidationResult = z.infer;\n\n// ==========================================\n// Metadata Plugin Configuration\n// ==========================================\n\n/**\n * Metadata Plugin Configuration\n *\n * The unified configuration for the metadata plugin, combining\n * storage, caching, customization, and type registry settings.\n */\nexport const MetadataPluginConfigSchema = z.object({\n /**\n * Storage configuration.\n * References MetadataManagerConfigSchema for the underlying storage backend.\n */\n storage: MetadataManagerConfigSchema.describe('Storage backend configuration'),\n\n /**\n * Default customization policies per metadata type.\n * Controls what parts of metadata can be customized by admins/users.\n */\n customizationPolicies: z.array(CustomizationPolicySchema).optional()\n .describe('Default customization policies per type'),\n\n /**\n * Merge strategy for package upgrades.\n */\n mergeStrategy: MergeStrategyConfigSchema.optional()\n .describe('Merge strategy for package upgrades'),\n\n /**\n * Additional metadata type registrations.\n * Used by plugins to register custom metadata types beyond the built-in set.\n */\n additionalTypes: z.array(MetadataTypeRegistryEntrySchema.omit({ type: true }).extend({\n type: z.string().describe('Custom metadata type identifier'),\n })).optional().describe('Additional custom metadata types'),\n\n /**\n * Enable metadata change events.\n * When true, the plugin emits events on every metadata change.\n */\n enableEvents: z.boolean().default(true).describe('Emit metadata change events'),\n\n /**\n * Enable metadata validation on write operations.\n * When true, all metadata is validated against its type schema before saving.\n */\n validateOnWrite: z.boolean().default(true).describe('Validate metadata on write'),\n\n /**\n * Enable metadata versioning.\n * When true, changes to metadata are tracked with version history.\n */\n enableVersioning: z.boolean().default(false).describe('Track metadata version history'),\n\n /**\n * Maximum number of metadata items to keep in memory cache.\n */\n cacheMaxItems: z.number().int().min(0).default(10000).describe('Max items in memory cache'),\n});\n\nexport type MetadataPluginConfig = z.input;\n\n// ==========================================\n// Metadata Plugin Manifest\n// ==========================================\n\n/**\n * Metadata Plugin Manifest\n *\n * The complete manifest for the Metadata Plugin, declaring its identity,\n * capabilities, and configuration. This is the \"contract\" between the\n * metadata plugin and the kernel.\n */\nexport const MetadataPluginManifestSchema = z.object({\n /** Plugin identifier */\n id: z.literal('com.objectstack.metadata').describe('Metadata plugin ID'),\n\n /** Plugin name */\n name: z.literal('ObjectStack Metadata Service').describe('Plugin name'),\n\n /** Plugin version */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Plugin version'),\n\n /** Plugin type */\n type: z.literal('standard').describe('Plugin type'),\n\n /** Plugin description */\n description: z.string().default('Core metadata management service for ObjectStack platform')\n .describe('Plugin description'),\n\n /**\n * Capabilities this plugin provides.\n * The kernel uses this to route metadata requests to this plugin.\n */\n capabilities: z.object({\n /** Supports CRUD operations on metadata */\n crud: z.boolean().default(true).describe('Supports metadata CRUD'),\n\n /** Supports metadata query/search */\n query: z.boolean().default(true).describe('Supports metadata query'),\n\n /** Supports the overlay/customization system */\n overlay: z.boolean().default(true).describe('Supports customization overlays'),\n\n /** Supports file watching for hot reload */\n watch: z.boolean().default(false).describe('Supports file watching'),\n\n /** Supports bulk import/export */\n importExport: z.boolean().default(true).describe('Supports import/export'),\n\n /** Supports metadata validation */\n validation: z.boolean().default(true).describe('Supports schema validation'),\n\n /** Supports metadata versioning */\n versioning: z.boolean().default(false).describe('Supports version history'),\n\n /** Supports metadata events */\n events: z.boolean().default(true).describe('Emits metadata events'),\n }).describe('Plugin capabilities'),\n\n /** Plugin configuration */\n config: MetadataPluginConfigSchema.optional().describe('Plugin configuration'),\n});\n\nexport type MetadataPluginManifest = z.input;\n\n// ==========================================\n// Built-in Type Registry Defaults\n// ==========================================\n\n/**\n * Default Type Registry\n *\n * The built-in metadata type registry with default configurations.\n * Plugins extend this via `contributes.kinds` in the manifest.\n */\nexport const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntry[] = [\n // Data Protocol (load first)\n { type: 'object', label: 'Object', filePatterns: ['**/*.object.ts', '**/*.object.yml', '**/*.object.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 10, domain: 'data' },\n { type: 'field', label: 'Field', filePatterns: ['**/*.field.ts', '**/*.field.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 20, domain: 'data' },\n { type: 'trigger', label: 'Trigger', filePatterns: ['**/*.trigger.ts', '**/*.trigger.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'validation', label: 'Validation Rule', filePatterns: ['**/*.validation.ts', '**/*.validation.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'hook', label: 'Hook', filePatterns: ['**/*.hook.ts', '**/*.hook.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n\n // UI Protocol\n { type: 'view', label: 'View', filePatterns: ['**/*.view.ts', '**/*.view.yml', '**/*.view.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'page', label: 'Page', filePatterns: ['**/*.page.ts', '**/*.page.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'dashboard', label: 'Dashboard', filePatterns: ['**/*.dashboard.ts', '**/*.dashboard.yml', '**/*.dashboard.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n { type: 'app', label: 'Application', filePatterns: ['**/*.app.ts', '**/*.app.yml', '**/*.app.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 70, domain: 'ui' },\n { type: 'action', label: 'Action', filePatterns: ['**/*.action.ts', '**/*.action.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'report', label: 'Report', filePatterns: ['**/*.report.ts', '**/*.report.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n\n // Automation Protocol\n { type: 'flow', label: 'Flow', filePatterns: ['**/*.flow.ts', '**/*.flow.yml', '**/*.flow.json'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'workflow', label: 'Workflow', filePatterns: ['**/*.workflow.ts', '**/*.workflow.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'approval', label: 'Approval Process', filePatterns: ['**/*.approval.ts', '**/*.approval.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 80, domain: 'automation' },\n\n // System Protocol\n { type: 'datasource', label: 'Datasource', filePatterns: ['**/*.datasource.ts', '**/*.datasource.yml'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 5, domain: 'system' },\n { type: 'translation', label: 'Translation', filePatterns: ['**/*.translation.ts', '**/*.translation.yml', '**/*.translation.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 90, domain: 'system' },\n { type: 'router', label: 'Router', filePatterns: ['**/*.router.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'function', label: 'Function', filePatterns: ['**/*.function.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'service', label: 'Service', filePatterns: ['**/*.service.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n\n // Security Protocol\n { type: 'permission', label: 'Permission Set', filePatterns: ['**/*.permission.ts', '**/*.permission.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 15, domain: 'security' },\n { type: 'profile', label: 'Profile', filePatterns: ['**/*.profile.ts', '**/*.profile.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n { type: 'role', label: 'Role', filePatterns: ['**/*.role.ts', '**/*.role.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n\n // AI Protocol\n { type: 'agent', label: 'AI Agent', filePatterns: ['**/*.agent.ts', '**/*.agent.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 90, domain: 'ai' },\n { type: 'tool', label: 'AI Tool', filePatterns: ['**/*.tool.ts', '**/*.tool.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 85, domain: 'ai' },\n { type: 'skill', label: 'AI Skill', filePatterns: ['**/*.skill.ts', '**/*.skill.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 88, domain: 'ai' },\n];\n\n// ==========================================\n// Bulk Operation Types\n// ==========================================\n\n/**\n * Bulk Register Request\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n /** Items to register */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Namespace'),\n })).min(1).describe('Items to register'),\n\n /** Continue on individual item failure */\n continueOnError: z.boolean().default(false).describe('Continue if individual item fails'),\n\n /** Validate items before registering */\n validate: z.boolean().default(true).describe('Validate before register'),\n});\n\nexport type MetadataBulkRegisterRequest = z.input;\n\n/**\n * Bulk Operation Result\n */\nexport const MetadataBulkResultSchema = z.object({\n /** Total items processed */\n total: z.number().int().min(0).describe('Total items processed'),\n\n /** Successfully processed items */\n succeeded: z.number().int().min(0).describe('Successfully processed'),\n\n /** Failed items */\n failed: z.number().int().min(0).describe('Failed items'),\n\n /** Per-item error details */\n errors: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n error: z.string().describe('Error message'),\n })).optional().describe('Per-item errors'),\n});\n\nexport type MetadataBulkResult = z.infer;\n\n// ==========================================\n// Metadata Dependency\n// ==========================================\n\n/**\n * Metadata Dependency Schema\n *\n * Tracks dependencies between metadata items.\n * Used for impact analysis and safe deletion checks.\n */\nexport const MetadataDependencySchema = z.object({\n /** Source metadata type */\n sourceType: z.string().describe('Dependent metadata type'),\n\n /** Source metadata name */\n sourceName: z.string().describe('Dependent metadata name'),\n\n /** Target metadata type */\n targetType: z.string().describe('Referenced metadata type'),\n\n /** Target metadata name */\n targetName: z.string().describe('Referenced metadata name'),\n\n /** Dependency kind */\n kind: z.enum(['reference', 'extends', 'includes', 'triggers'])\n .describe('How the dependency is formed'),\n});\n\nexport type MetadataDependency = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\nimport { DependencyResolutionResultSchema } from './dependency-resolution.zod';\n\n/**\n * # Package Registry Protocol\n * \n * Defines the runtime state and lifecycle operations for installed packages.\n * \n * ## Key Distinction: Package vs App\n * - **Package (Manifest)**: The unit of installation — a deployable artifact containing\n * metadata (objects, actions, flows, etc.) and optionally one or more Apps.\n * - **App (AppSchema)**: A UI navigation shell defined inside a package.\n * \n * A package may contain:\n * - Zero apps (pure functionality plugin, e.g. a storage driver)\n * - One app (typical business application)\n * - Multiple apps (suite of applications)\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Packages with install/uninstall lifecycle\n * - **VS Code**: Extension marketplace with enable/disable per-workspace\n * - **Kubernetes**: Helm charts with release state tracking\n * - **npm**: Package registry with install/uninstall/version management\n */\n\n// ==========================================\n// Package Status & Lifecycle\n// ==========================================\n\n/**\n * Package installation status.\n */\nexport const PackageStatusEnum = z.enum([\n 'installed', // Successfully installed and enabled\n 'disabled', // Installed but disabled (metadata not active)\n 'installing', // Installation in progress\n 'upgrading', // Upgrade in progress\n 'uninstalling', // Removal in progress\n 'error', // Installation or runtime error\n]).describe('Package installation status');\nexport type PackageStatus = z.infer;\n\n/**\n * Installed Package Schema\n * \n * Wraps a ManifestSchema with runtime lifecycle state.\n * This is the \"row\" in the installed packages table.\n */\nexport const InstalledPackageSchema = z.object({\n /** \n * The full package manifest (source of truth for package definition).\n */\n manifest: ManifestSchema.describe('Full package manifest'),\n\n /**\n * Current lifecycle status.\n */\n status: PackageStatusEnum.default('installed')\n .describe('Package state: installed, disabled, installing, upgrading, uninstalling, or error'),\n\n /**\n * Whether the package is currently enabled (active).\n * When disabled, the package's metadata is not loaded into the registry.\n */\n enabled: z.boolean().default(true)\n .describe('Whether the package is currently enabled'),\n\n /**\n * ISO 8601 timestamp of when the package was installed.\n */\n installedAt: z.string().datetime().optional()\n .describe('Installation timestamp'),\n\n /**\n * ISO 8601 timestamp of last update.\n */\n updatedAt: z.string().datetime().optional()\n .describe('Last update timestamp'),\n\n /**\n * The currently installed version string.\n * Mirrors manifest.version for quick access without parsing the full manifest.\n */\n installedVersion: z.string().optional()\n .describe('Currently installed version for quick access'),\n\n /**\n * The previously installed version (before last upgrade).\n * Useful for rollback and upgrade tracking.\n */\n previousVersion: z.string().optional()\n .describe('Version before the last upgrade'),\n\n /**\n * ISO 8601 timestamp of when the package was last enabled/disabled.\n */\n statusChangedAt: z.string().datetime().optional()\n .describe('Status change timestamp'),\n\n /**\n * Error message if status is 'error'.\n */\n errorMessage: z.string().optional()\n .describe('Error message when status is error'),\n\n /**\n * Configuration values set by the user for this package.\n * Keys correspond to the package's `configuration.properties`.\n */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided configuration settings'),\n\n /**\n * Upgrade history for this package.\n * Records each version migration with status and optional log.\n */\n upgradeHistory: z.array(z.object({\n /** Previous version before upgrade */\n fromVersion: z.string().describe('Version before upgrade'),\n /** New version after upgrade */\n toVersion: z.string().describe('Version after upgrade'),\n /** Timestamp of the upgrade */\n upgradedAt: z.string().datetime().describe('Upgrade timestamp'),\n /** Outcome of the upgrade */\n status: z.enum(['success', 'failed', 'rolled_back']).describe('Upgrade outcome'),\n /** Migration log entries */\n migrationLog: z.array(z.string()).optional().describe('Migration step logs'),\n })).optional().describe('Version upgrade history'),\n\n /**\n * Namespaces registered by this package.\n * Tracks which namespace prefixes are occupied by this package.\n */\n registeredNamespaces: z.array(z.string()).optional()\n .describe('Namespace prefixes registered by this package'),\n}).describe('Installed package with runtime lifecycle state');\nexport type InstalledPackage = z.infer;\n\n// ==========================================\n// Namespace Registry\n// ==========================================\n\n/**\n * Namespace Registry Entry\n * Tracks namespace ownership within the platform instance.\n */\nexport const NamespaceRegistryEntrySchema = z.object({\n /** Namespace prefix */\n namespace: z.string().describe('Namespace prefix'),\n\n /** Package that owns this namespace */\n packageId: z.string().describe('Owning package ID'),\n\n /** Registration timestamp */\n registeredAt: z.string().datetime().describe('Registration timestamp'),\n\n /** Namespace status */\n status: z.enum(['active', 'disabled', 'reserved'])\n .describe('Namespace status'),\n}).describe('Namespace ownership entry in the registry');\n\nexport type NamespaceRegistryEntry = z.infer;\n\n/**\n * Namespace Conflict Error\n * Describes a namespace collision detected during package installation.\n */\nexport const NamespaceConflictErrorSchema = z.object({\n /** Error type discriminator */\n type: z.literal('namespace_conflict').describe('Error type'),\n\n /** Namespace that was requested */\n requestedNamespace: z.string().describe('Requested namespace'),\n\n /** ID of the package that already owns the namespace */\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n\n /** Name of the conflicting package */\n conflictingPackageName: z.string().describe('Conflicting package display name'),\n\n /** Suggested alternative namespace */\n suggestion: z.string().optional()\n .describe('Suggested alternative namespace'),\n}).describe('Namespace collision error during installation');\n\nexport type NamespaceConflictError = z.infer;\n\n// ==========================================\n// Package Registry Request/Response Schemas\n// ==========================================\n\n/**\n * List Packages Request\n */\nexport const ListPackagesRequestSchema = z.object({\n /** Filter by status */\n status: PackageStatusEnum.optional().describe('Filter by package status'),\n /** Filter by package type */\n type: ManifestSchema.shape.type.optional().describe('Filter by package type'),\n /** Filter by enabled state */\n enabled: z.boolean().optional().describe('Filter by enabled state'),\n}).describe('List packages request');\nexport type ListPackagesRequest = z.infer;\n\n/**\n * List Packages Response\n */\nexport const ListPackagesResponseSchema = z.object({\n packages: z.array(InstalledPackageSchema).describe('List of installed packages'),\n total: z.number().describe('Total package count'),\n}).describe('List packages response');\nexport type ListPackagesResponse = z.infer;\n\n/**\n * Get Package Request\n */\nexport const GetPackageRequestSchema = z.object({\n /** Package ID (reverse domain identifier from manifest) */\n id: z.string().describe('Package identifier'),\n}).describe('Get package request');\nexport type GetPackageRequest = z.infer;\n\n/**\n * Get Package Response\n */\nexport const GetPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Package details'),\n}).describe('Get package response');\nexport type GetPackageResponse = z.infer;\n\n/**\n * Install Package Request\n * \n * Accepts a full manifest to install. In a production system,\n * this might also accept a package ID to fetch from a marketplace.\n */\nexport const InstallPackageRequestSchema = z.object({\n /** The package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n /** Optional: user-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n /** Whether to enable immediately after install (default: true) */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n /**\n * Current platform version for compatibility checking.\n * When provided, the system compares this against the package's\n * `engine.objectstack` requirement to verify compatibility.\n */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n}).describe('Install package request');\nexport type InstallPackageRequest = z.infer;\n\n/**\n * Install Package Response\n */\nexport const InstallPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n message: z.string().optional().describe('Installation status message'),\n /** Dependency resolution result (when dependencies were analyzed) */\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result from install analysis'),\n}).describe('Install package response');\nexport type InstallPackageResponse = z.infer;\n\n/**\n * Uninstall Package Request\n */\nexport const UninstallPackageRequestSchema = z.object({\n /** Package ID to uninstall */\n id: z.string().describe('Package ID to uninstall'),\n}).describe('Uninstall package request');\nexport type UninstallPackageRequest = z.infer;\n\n/**\n * Uninstall Package Response\n */\nexport const UninstallPackageResponseSchema = z.object({\n id: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n}).describe('Uninstall package response');\nexport type UninstallPackageResponse = z.infer;\n\n/**\n * Enable Package Request\n */\nexport const EnablePackageRequestSchema = z.object({\n /** Package ID to enable */\n id: z.string().describe('Package ID to enable'),\n}).describe('Enable package request');\nexport type EnablePackageRequest = z.infer;\n\n/**\n * Enable Package Response\n */\nexport const EnablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Enabled package details'),\n message: z.string().optional().describe('Enable status message'),\n}).describe('Enable package response');\nexport type EnablePackageResponse = z.infer;\n\n/**\n * Disable Package Request\n */\nexport const DisablePackageRequestSchema = z.object({\n /** Package ID to disable */\n id: z.string().describe('Package ID to disable'),\n}).describe('Disable package request');\nexport type DisablePackageRequest = z.infer;\n\n/**\n * Disable Package Response\n */\nexport const DisablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Disabled package details'),\n message: z.string().optional().describe('Disable status message'),\n}).describe('Disable package response');\nexport type DisablePackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\n\n/**\n * # Package Upgrade Protocol\n * \n * Defines the complete lifecycle for upgrading installed packages,\n * including pre-upgrade analysis, snapshot/backup, execution, validation,\n * and rollback capabilities.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Package upgrade with push upgrades and subscriber control\n * - **ServiceNow**: Update Sets with preview, commit, and back-out support\n * - **Helm**: Helm upgrade with rollback to previous release\n * - **Kubernetes**: Rolling update with readiness probes and automatic rollback\n * \n * ## Upgrade Flow\n * ```\n * 1. PreCheck → Validate compatibility, check dependencies\n * 2. Plan → Generate upgrade plan with metadata diff\n * 3. Snapshot → Backup current state (metadata + customizations)\n * 4. Execute → Apply new package metadata with 3-way merge\n * 5. Validate → Run post-upgrade health checks\n * 6. Commit → Finalize upgrade (or Rollback on failure)\n * ```\n */\n\n// ==========================================\n// Upgrade Plan & Analysis\n// ==========================================\n\n/**\n * Metadata Change Type\n * Type of change detected between package versions.\n */\nexport const MetadataChangeTypeSchema = z.enum([\n 'added', // New metadata item added in new version\n 'modified', // Existing metadata item modified\n 'removed', // Metadata item removed in new version\n 'renamed', // Metadata item renamed\n]).describe('Type of metadata change between package versions');\n\n/**\n * Metadata Diff Item\n * Describes a single metadata change between two package versions.\n */\nexport const MetadataDiffItemSchema = z.object({\n /** Metadata type (e.g. \"object\", \"view\", \"flow\") */\n type: z.string().describe('Metadata type'),\n\n /** Metadata name */\n name: z.string().describe('Metadata name'),\n\n /** Type of change */\n changeType: MetadataChangeTypeSchema.describe('Category of metadata modification (added, modified, removed, or renamed)'),\n\n /** Whether this change has potential conflicts with customizations */\n hasConflict: z.boolean().default(false)\n .describe('Whether this change may conflict with customizations'),\n\n /** Human-readable summary of the change */\n summary: z.string().optional().describe('Human-readable change summary'),\n\n /** Previous name (for renames) */\n previousName: z.string().optional().describe('Previous name if renamed'),\n}).describe('Single metadata change between package versions');\n\n/**\n * Upgrade Impact Level\n * Indicates the severity of impact the upgrade will have.\n */\nexport const UpgradeImpactLevelSchema = z.enum([\n 'none', // No impact, seamless upgrade\n 'low', // Minor changes, no user action needed\n 'medium', // Some changes that may affect workflows\n 'high', // Significant changes, user review recommended\n 'critical', // Breaking changes, manual intervention required\n]).describe('Severity of upgrade impact');\n\n/**\n * Upgrade Plan Schema\n * The analysis result before executing an upgrade.\n * Generated by comparing old version metadata with new version metadata.\n */\nexport const UpgradePlanSchema = z.object({\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Current installed version */\n fromVersion: z.string().describe('Currently installed version'),\n\n /** Target version to upgrade to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Overall impact level */\n impactLevel: UpgradeImpactLevelSchema.describe('Severity assessment from none (seamless) to critical (breaking changes)'),\n\n /** List of all metadata changes between versions */\n changes: z.array(MetadataDiffItemSchema).describe('All metadata changes'),\n\n /** Number of customer customizations that may be affected */\n affectedCustomizations: z.number().int().min(0).default(0)\n .describe('Count of customizations that may be affected'),\n\n /** Whether any migration scripts need to run */\n requiresMigration: z.boolean().default(false)\n .describe('Whether data migration scripts are needed'),\n\n /** Migration script paths (relative to package root) */\n migrationScripts: z.array(z.string()).optional()\n .describe('Paths to migration scripts'),\n\n /** Dependencies that also need upgrading */\n dependencyUpgrades: z.array(z.object({\n packageId: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n })).optional().describe('Dependent packages that also need upgrading'),\n\n /** Estimated upgrade duration in seconds */\n estimatedDuration: z.number().int().min(0).optional()\n .describe('Estimated upgrade duration in seconds'),\n\n /** Human-readable summary */\n summary: z.string().optional().describe('Human-readable upgrade summary'),\n}).describe('Upgrade analysis plan generated before execution');\n\n// ==========================================\n// Upgrade Snapshot (Pre-Upgrade Backup)\n// ==========================================\n\n/**\n * Upgrade Snapshot Schema\n * Captures the complete state before an upgrade for rollback capability.\n */\nexport const UpgradeSnapshotSchema = z.object({\n /** Snapshot ID (UUID) */\n id: z.string().describe('Snapshot identifier'),\n\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being upgraded from */\n fromVersion: z.string().describe('Version before upgrade'),\n\n /** Version being upgraded to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Complete manifest of the old package version */\n previousManifest: ManifestSchema.describe('Complete manifest of the previous package version'),\n\n /**\n * Snapshot of all metadata records owned by this package.\n * Stored as array of { type, name, metadata } tuples.\n */\n metadataSnapshot: z.array(z.object({\n type: z.string(),\n name: z.string(),\n metadata: z.record(z.string(), z.unknown()),\n })).describe('Snapshot of all package metadata'),\n\n /**\n * Snapshot of all customer customizations (overlays) for this package's metadata.\n */\n customizationSnapshot: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Snapshot of customer customizations'),\n\n /** When the snapshot was created */\n createdAt: z.string().datetime().describe('Snapshot creation timestamp'),\n\n /** Expiry time for snapshot cleanup */\n expiresAt: z.string().datetime().optional().describe('Snapshot expiry timestamp'),\n}).describe('Pre-upgrade state snapshot for rollback capability');\n\n// ==========================================\n// Upgrade Request/Response\n// ==========================================\n\n/**\n * Upgrade Package Request\n */\nexport const UpgradePackageRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (if omitted, upgrades to latest) */\n targetVersion: z.string().optional().describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional().describe('New manifest (if installing from local)'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum([\n 'keep-custom',\n 'accept-incoming',\n 'three-way-merge',\n ]).default('three-way-merge').describe('How to handle customer customizations'),\n\n /** Whether to run in dry-run mode (preview only, no changes) */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Whether to skip pre-upgrade validation */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\n\n/**\n * Upgrade Phase\n * Current phase of the upgrade process.\n */\nexport const UpgradePhaseSchema = z.enum([\n 'pending', // Upgrade requested but not started\n 'analyzing', // Generating upgrade plan\n 'snapshot', // Creating pre-upgrade snapshot\n 'executing', // Applying metadata changes\n 'migrating', // Running migration scripts\n 'validating', // Post-upgrade validation\n 'completed', // Upgrade completed successfully\n 'failed', // Upgrade failed\n 'rolling-back', // Rollback in progress\n 'rolled-back', // Rollback completed\n]).describe('Current phase of the upgrade process');\n\n/**\n * Upgrade Package Response\n */\nexport const UpgradePackageResponseSchema = z.object({\n /** Whether the upgrade was successful */\n success: z.boolean().describe('Whether the upgrade succeeded'),\n\n /** Current upgrade phase */\n phase: UpgradePhaseSchema.describe('Current upgrade phase'),\n\n /** The upgrade plan that was executed */\n plan: UpgradePlanSchema.optional().describe('Upgrade plan'),\n\n /** Snapshot ID for rollback */\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n\n /** Merge conflicts that need manual resolution (if any) */\n conflicts: z.array(z.object({\n path: z.string(),\n baseValue: z.unknown(),\n incomingValue: z.unknown(),\n customValue: z.unknown(),\n })).optional().describe('Unresolved merge conflicts'),\n\n /** Error message (if failed) */\n errorMessage: z.string().optional().describe('Error message if upgrade failed'),\n\n /** Human-readable summary */\n message: z.string().optional().describe('Human-readable status message'),\n}).describe('Upgrade package response');\n\n// ==========================================\n// Rollback\n// ==========================================\n\n/**\n * Rollback Package Request\n */\nexport const RollbackPackageRequestSchema = z.object({\n /** Package ID to rollback */\n packageId: z.string().describe('Package ID to rollback'),\n\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\n\n/**\n * Rollback Package Response\n */\nexport const RollbackPackageResponseSchema = z.object({\n /** Whether the rollback was successful */\n success: z.boolean().describe('Whether the rollback succeeded'),\n\n /** Restored version */\n restoredVersion: z.string().optional().describe('Version restored to'),\n\n /** Message */\n message: z.string().optional().describe('Rollback status message'),\n}).describe('Rollback package response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type MetadataChangeType = z.infer;\nexport type MetadataDiffItem = z.infer;\nexport type UpgradeImpactLevel = z.infer;\nexport type UpgradePlan = z.infer;\nexport type UpgradeSnapshot = z.infer;\nexport type UpgradePackageRequest = z.infer;\nexport type UpgradePhase = z.infer;\nexport type UpgradePackageResponse = z.infer;\nexport type RollbackPackageRequest = z.infer;\nexport type RollbackPackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Advanced Plugin Lifecycle Protocol\n * \n * Defines advanced lifecycle management capabilities including:\n * - Hot reload and live updates\n * - Graceful degradation and fallback mechanisms\n * - Health monitoring and auto-recovery\n * - State preservation during updates\n * \n * This protocol extends the basic plugin lifecycle with enterprise-grade\n * features for production environments.\n */\n\n/**\n * Plugin Health Status\n * Represents the current operational state of a plugin\n */\nexport const PluginHealthStatusSchema = z.enum([\n 'healthy', // Plugin is operating normally\n 'degraded', // Plugin is operational but with reduced functionality\n 'unhealthy', // Plugin has critical issues but still running\n 'failed', // Plugin has failed and is not operational\n 'recovering', // Plugin is in recovery process\n 'unknown', // Health status cannot be determined\n]).describe('Current health status of the plugin');\n\n/**\n * Plugin Health Check Configuration\n * Defines how to check plugin health\n */\nexport const PluginHealthCheckSchema = z.object({\n /**\n * Health check interval in milliseconds\n */\n interval: z.number().int().min(1000).default(30000)\n .describe('How often to perform health checks (default: 30s)'),\n \n /**\n * Timeout for health check in milliseconds\n */\n timeout: z.number().int().min(100).default(5000)\n .describe('Maximum time to wait for health check response'),\n \n /**\n * Number of consecutive failures before marking as unhealthy\n */\n failureThreshold: z.number().int().min(1).default(3)\n .describe('Consecutive failures needed to mark unhealthy'),\n \n /**\n * Number of consecutive successes to recover from unhealthy state\n */\n successThreshold: z.number().int().min(1).default(1)\n .describe('Consecutive successes needed to mark healthy'),\n \n /**\n * Custom health check function name or endpoint\n */\n checkMethod: z.string().optional()\n .describe('Method name to call for health check'),\n \n /**\n * Enable automatic restart on failure\n */\n autoRestart: z.boolean().default(false)\n .describe('Automatically restart plugin on health check failure'),\n \n /**\n * Maximum number of restart attempts\n */\n maxRestartAttempts: z.number().int().min(0).default(3)\n .describe('Maximum restart attempts before giving up'),\n \n /**\n * Backoff strategy for restarts\n */\n restartBackoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy for restart delays'),\n});\n\n/**\n * Plugin Health Report\n * Detailed health information from a plugin\n */\nexport const PluginHealthReportSchema = z.object({\n /**\n * Overall health status\n */\n status: PluginHealthStatusSchema,\n \n /**\n * Timestamp of the health check\n */\n timestamp: z.string().datetime(),\n \n /**\n * Human-readable message about health status\n */\n message: z.string().optional(),\n \n /**\n * Detailed metrics\n */\n metrics: z.object({\n uptime: z.number().describe('Plugin uptime in milliseconds'),\n memoryUsage: z.number().optional().describe('Memory usage in bytes'),\n cpuUsage: z.number().optional().describe('CPU usage percentage'),\n activeConnections: z.number().optional().describe('Number of active connections'),\n errorRate: z.number().optional().describe('Error rate (errors per minute)'),\n responseTime: z.number().optional().describe('Average response time in ms'),\n }).partial().optional(),\n \n /**\n * List of checks performed\n */\n checks: z.array(z.object({\n name: z.string().describe('Check name'),\n status: z.enum(['passed', 'failed', 'warning']),\n message: z.string().optional(),\n data: z.record(z.string(), z.unknown()).optional(),\n })).optional(),\n \n /**\n * Dependencies health\n */\n dependencies: z.array(z.object({\n pluginId: z.string(),\n status: PluginHealthStatusSchema,\n message: z.string().optional(),\n })).optional(),\n});\n\n/**\n * Distributed State Configuration\n * Configuration for distributed state management in cluster environments\n */\nexport const DistributedStateConfigSchema = z.object({\n /**\n * Distributed cache provider\n */\n provider: z.enum(['redis', 'etcd', 'custom'])\n .describe('Distributed state backend provider'),\n \n /**\n * Connection URL or endpoints\n */\n endpoints: z.array(z.string()).optional()\n .describe('Backend connection endpoints'),\n \n /**\n * Key prefix for namespacing\n */\n keyPrefix: z.string().optional()\n .describe('Prefix for all keys (e.g., \"plugin:my-plugin:\")'),\n \n /**\n * Time to live in seconds\n */\n ttl: z.number().int().min(0).optional()\n .describe('State expiration time in seconds'),\n \n /**\n * Authentication configuration\n */\n auth: z.object({\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n certificate: z.string().optional(),\n }).optional(),\n \n /**\n * Replication settings\n */\n replication: z.object({\n enabled: z.boolean().default(true),\n minReplicas: z.number().int().min(1).default(1),\n }).optional(),\n \n /**\n * Custom provider configuration\n */\n customConfig: z.record(z.string(), z.unknown()).optional()\n .describe('Provider-specific configuration'),\n});\n\n/**\n * Hot Reload Configuration\n * Controls how plugins handle live updates\n */\nexport const HotReloadConfigSchema = z.object({\n /**\n * Enable hot reload capability\n */\n enabled: z.boolean().default(false),\n \n /**\n * Watch file patterns for auto-reload\n */\n watchPatterns: z.array(z.string()).optional()\n .describe('Glob patterns to watch for changes'),\n \n /**\n * Debounce delay before reloading (milliseconds)\n */\n debounceDelay: z.number().int().min(0).default(1000)\n .describe('Wait time after change detection before reload'),\n \n /**\n * Preserve plugin state during reload\n */\n preserveState: z.boolean().default(true)\n .describe('Keep plugin state across reloads'),\n \n /**\n * State serialization strategy\n */\n stateStrategy: z.enum(['memory', 'disk', 'distributed', 'none']).default('memory')\n .describe('How to preserve state during reload'),\n \n /**\n * Distributed state configuration (required when stateStrategy is \"distributed\")\n */\n distributedConfig: DistributedStateConfigSchema.optional()\n .describe('Configuration for distributed state management'),\n \n /**\n * Graceful shutdown timeout\n */\n shutdownTimeout: z.number().int().min(0).default(30000)\n .describe('Maximum time to wait for graceful shutdown'),\n \n /**\n * Pre-reload hooks\n */\n beforeReload: z.array(z.string()).optional()\n .describe('Hook names to call before reload'),\n \n /**\n * Post-reload hooks\n */\n afterReload: z.array(z.string()).optional()\n .describe('Hook names to call after reload'),\n});\n\n/**\n * Graceful Degradation Configuration\n * Defines how plugin degrades when dependencies fail\n */\nexport const GracefulDegradationSchema = z.object({\n /**\n * Enable graceful degradation\n */\n enabled: z.boolean().default(true),\n \n /**\n * Fallback mode when dependencies fail\n */\n fallbackMode: z.enum([\n 'minimal', // Provide minimal functionality\n 'cached', // Use cached data\n 'readonly', // Allow read-only operations\n 'offline', // Offline mode with local data\n 'disabled', // Disable plugin functionality\n ]).default('minimal'),\n \n /**\n * Critical dependencies that must be available\n */\n criticalDependencies: z.array(z.string()).optional()\n .describe('Plugin IDs that are required for operation'),\n \n /**\n * Optional dependencies that can fail\n */\n optionalDependencies: z.array(z.string()).optional()\n .describe('Plugin IDs that are nice to have but not required'),\n \n /**\n * Feature flags for degraded mode\n */\n degradedFeatures: z.array(z.object({\n feature: z.string().describe('Feature name'),\n enabled: z.boolean().describe('Whether feature is available in degraded mode'),\n reason: z.string().optional(),\n })).optional(),\n \n /**\n * Automatic recovery attempts\n */\n autoRecovery: z.object({\n enabled: z.boolean().default(true),\n retryInterval: z.number().int().min(1000).default(60000)\n .describe('Interval between recovery attempts (ms)'),\n maxAttempts: z.number().int().min(0).default(5)\n .describe('Maximum recovery attempts before giving up'),\n }).optional(),\n});\n\n/**\n * Plugin Update Strategy\n * Defines how plugin handles version updates\n */\nexport const PluginUpdateStrategySchema = z.object({\n /**\n * Update mode\n */\n mode: z.enum([\n 'manual', // Manual updates only\n 'automatic', // Automatic updates\n 'scheduled', // Scheduled update windows\n 'rolling', // Rolling updates with zero downtime\n ]).default('manual'),\n \n /**\n * Version constraints for automatic updates\n */\n autoUpdateConstraints: z.object({\n major: z.boolean().default(false).describe('Allow major version updates'),\n minor: z.boolean().default(true).describe('Allow minor version updates'),\n patch: z.boolean().default(true).describe('Allow patch version updates'),\n }).optional(),\n \n /**\n * Update schedule (for scheduled mode)\n */\n schedule: z.object({\n /**\n * Cron expression for update window\n */\n cron: z.string().optional(),\n \n /**\n * Timezone for schedule\n */\n timezone: z.string().default('UTC'),\n \n /**\n * Maintenance window duration in minutes\n */\n maintenanceWindow: z.number().int().min(1).default(60),\n }).optional(),\n \n /**\n * Rollback configuration\n */\n rollback: z.object({\n enabled: z.boolean().default(true),\n \n /**\n * Automatic rollback on failure\n */\n automatic: z.boolean().default(true),\n \n /**\n * Keep N previous versions for rollback\n */\n keepVersions: z.number().int().min(1).default(3),\n \n /**\n * Rollback timeout in milliseconds\n */\n timeout: z.number().int().min(1000).default(30000),\n }).optional(),\n \n /**\n * Pre-update validation\n */\n validation: z.object({\n /**\n * Run compatibility checks before update\n */\n checkCompatibility: z.boolean().default(true),\n \n /**\n * Run tests before applying update\n */\n runTests: z.boolean().default(false),\n \n /**\n * Test suite to run\n */\n testSuite: z.string().optional(),\n }).optional(),\n});\n\n/**\n * Plugin State Snapshot\n * Captures plugin state for preservation during updates/reloads\n */\nexport const PluginStateSnapshotSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Version at time of snapshot\n */\n version: z.string(),\n \n /**\n * Snapshot timestamp\n */\n timestamp: z.string().datetime(),\n \n /**\n * Serialized state data\n */\n state: z.record(z.string(), z.unknown()),\n \n /**\n * State metadata\n */\n metadata: z.object({\n checksum: z.string().optional().describe('State checksum for verification'),\n compressed: z.boolean().default(false),\n encryption: z.string().optional().describe('Encryption algorithm if encrypted'),\n }).optional(),\n});\n\n/**\n * Advanced Plugin Lifecycle Configuration\n * Complete configuration for advanced lifecycle management\n */\nexport const AdvancedPluginLifecycleConfigSchema = z.object({\n /**\n * Health monitoring configuration\n */\n health: PluginHealthCheckSchema.optional(),\n \n /**\n * Hot reload configuration\n */\n hotReload: HotReloadConfigSchema.optional(),\n \n /**\n * Graceful degradation configuration\n */\n degradation: GracefulDegradationSchema.optional(),\n \n /**\n * Update strategy\n */\n updates: PluginUpdateStrategySchema.optional(),\n \n /**\n * Resource limits\n */\n resources: z.object({\n maxMemory: z.number().int().optional().describe('Maximum memory in bytes'),\n maxCpu: z.number().min(0).max(100).optional().describe('Maximum CPU percentage'),\n maxConnections: z.number().int().optional().describe('Maximum concurrent connections'),\n timeout: z.number().int().optional().describe('Operation timeout in milliseconds'),\n }).optional(),\n \n /**\n * Monitoring and observability\n */\n observability: z.object({\n enableMetrics: z.boolean().default(true),\n enableTracing: z.boolean().default(true),\n enableProfiling: z.boolean().default(false),\n metricsInterval: z.number().int().min(1000).default(60000)\n .describe('Metrics collection interval in ms'),\n }).optional(),\n});\n\n// Export types\nexport type PluginHealthStatus = z.infer;\nexport type PluginHealthCheck = z.infer;\nexport type PluginHealthReport = z.infer;\nexport type DistributedStateConfig = z.infer;\nexport type HotReloadConfig = z.infer;\nexport type GracefulDegradation = z.infer;\nexport type PluginUpdateStrategy = z.infer;\nexport type PluginStateSnapshot = z.infer;\nexport type AdvancedPluginLifecycleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Plugin Lifecycle Events Protocol\n * \n * Zod schemas for plugin lifecycle event data structures.\n * These schemas align with the IPluginLifecycleEvents contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Event Payload Schemas\n// ============================================================================\n\n/**\n * Event Phase Enum\n * Lifecycle phase where an error occurred\n */\nexport const EventPhaseSchema = z.enum(['init', 'start', 'destroy'])\n .describe('Plugin lifecycle phase');\n\nexport type EventPhase = z.infer;\n\n/**\n * Plugin Event Base Schema\n * Common fields for all plugin events\n */\nexport const PluginEventBaseSchema = z.object({\n /**\n * Plugin name\n */\n pluginName: z.string().describe('Name of the plugin'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds when event occurred'),\n});\n\n/**\n * Plugin Registered Event Schema\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"version\": \"1.0.0\"\n * }\n */\nexport const PluginRegisteredEventSchema = PluginEventBaseSchema.extend({\n /**\n * Plugin version (optional)\n */\n version: z.string().optional().describe('Plugin version'),\n});\n\nexport type PluginRegisteredEvent = z.infer;\n\n/**\n * Plugin Lifecycle Phase Event Schema\n * For init, start, destroy phases\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"duration\": 1250,\n * \"phase\": \"init\"\n * }\n */\nexport const PluginLifecyclePhaseEventSchema = PluginEventBaseSchema.extend({\n /**\n * Duration of the phase (milliseconds)\n */\n duration: z.number().min(0).optional().describe('Duration of the lifecycle phase in milliseconds'),\n \n /**\n * Lifecycle phase\n */\n phase: EventPhaseSchema.optional().describe('Lifecycle phase'),\n});\n\nexport type PluginLifecyclePhaseEvent = z.infer;\n\n/**\n * Plugin Error Event Schema\n * When a plugin encounters an error\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"error\": Error(\"Connection failed\"),\n * \"phase\": \"start\",\n * \"errorMessage\": \"Connection failed\",\n * \"errorStack\": \"Error: Connection failed\\n at ...\"\n * }\n */\nexport const PluginErrorEventSchema = PluginEventBaseSchema.extend({\n /**\n * Error object\n */\n error: z.object({\n name: z.string().describe('Error class name'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n code: z.string().optional().describe('Error code'),\n }).describe('Serializable error representation'),\n \n /**\n * Lifecycle phase where error occurred\n */\n phase: EventPhaseSchema.describe('Lifecycle phase where error occurred'),\n \n /**\n * Error message (for serialization)\n */\n errorMessage: z.string().optional().describe('Error message'),\n \n /**\n * Error stack trace (for debugging)\n */\n errorStack: z.string().optional().describe('Error stack trace'),\n});\n\nexport type PluginErrorEvent = z.infer;\n\n// ============================================================================\n// Service Event Schemas\n// ============================================================================\n\n/**\n * Service Registered Event Schema\n * \n * @example\n * {\n * \"serviceName\": \"database\",\n * \"timestamp\": 1706659200000,\n * \"serviceType\": \"IDataEngine\"\n * }\n */\nexport const ServiceRegisteredEventSchema = z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Name of the registered service'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Service type (optional)\n */\n serviceType: z.string().optional().describe('Type or interface name of the service'),\n});\n\nexport type ServiceRegisteredEvent = z.infer;\n\n/**\n * Service Unregistered Event Schema\n * \n * @example\n * {\n * \"serviceName\": \"database\",\n * \"timestamp\": 1706659200000\n * }\n */\nexport const ServiceUnregisteredEventSchema = z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Name of the unregistered service'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n});\n\nexport type ServiceUnregisteredEvent = z.infer;\n\n// ============================================================================\n// Hook Event Schemas\n// ============================================================================\n\n/**\n * Hook Registered Event Schema\n * \n * @example\n * {\n * \"hookName\": \"data.beforeInsert\",\n * \"timestamp\": 1706659200000,\n * \"handlerCount\": 3\n * }\n */\nexport const HookRegisteredEventSchema = z.object({\n /**\n * Hook name\n */\n hookName: z.string().describe('Name of the hook'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Number of handlers registered for this hook\n */\n handlerCount: z.number().int().min(0).describe('Number of handlers registered for this hook'),\n});\n\nexport type HookRegisteredEvent = z.infer;\n\n/**\n * Hook Triggered Event Schema\n * \n * @example\n * {\n * \"hookName\": \"data.beforeInsert\",\n * \"timestamp\": 1706659200000,\n * \"args\": [{ \"object\": \"customer\", \"data\": {...} }],\n * \"handlerCount\": 3\n * }\n */\nexport const HookTriggeredEventSchema = z.object({\n /**\n * Hook name\n */\n hookName: z.string().describe('Name of the hook'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Arguments passed to the hook\n */\n args: z.array(z.unknown()).describe('Arguments passed to the hook handlers'),\n \n /**\n * Number of handlers that will handle this event\n */\n handlerCount: z.number().int().min(0).optional().describe('Number of handlers that will handle this event'),\n});\n\nexport type HookTriggeredEvent = z.infer;\n\n// ============================================================================\n// Kernel Event Schemas\n// ============================================================================\n\n/**\n * Kernel Event Base Schema\n * Common fields for kernel events\n */\nexport const KernelEventBaseSchema = z.object({\n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n});\n\n/**\n * Kernel Ready Event Schema\n * \n * @example\n * {\n * \"timestamp\": 1706659200000,\n * \"duration\": 5400,\n * \"pluginCount\": 12\n * }\n */\nexport const KernelReadyEventSchema = KernelEventBaseSchema.extend({\n /**\n * Total initialization duration (milliseconds)\n */\n duration: z.number().min(0).optional().describe('Total initialization duration in milliseconds'),\n \n /**\n * Number of plugins initialized\n */\n pluginCount: z.number().int().min(0).optional().describe('Number of plugins initialized'),\n});\n\nexport type KernelReadyEvent = z.infer;\n\n/**\n * Kernel Shutdown Event Schema\n * \n * @example\n * {\n * \"timestamp\": 1706659200000,\n * \"reason\": \"SIGTERM received\"\n * }\n */\nexport const KernelShutdownEventSchema = KernelEventBaseSchema.extend({\n /**\n * Shutdown reason (optional)\n */\n reason: z.string().optional().describe('Reason for kernel shutdown'),\n});\n\nexport type KernelShutdownEvent = z.infer;\n\n// ============================================================================\n// Event Type Registry\n// ============================================================================\n\n/**\n * Plugin Lifecycle Event Type Enum\n * All possible plugin lifecycle event types\n */\nexport const PluginLifecycleEventType = z.enum([\n 'kernel:ready',\n 'kernel:shutdown',\n 'kernel:before-init',\n 'kernel:after-init',\n 'plugin:registered',\n 'plugin:before-init',\n 'plugin:init',\n 'plugin:after-init',\n 'plugin:before-start',\n 'plugin:started',\n 'plugin:after-start',\n 'plugin:before-destroy',\n 'plugin:destroyed',\n 'plugin:after-destroy',\n 'plugin:error',\n 'service:registered',\n 'service:unregistered',\n 'hook:registered',\n 'hook:triggered',\n]).describe('Plugin lifecycle event type');\n\nexport type PluginLifecycleEventType = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Runtime Management Protocol\n * \n * Defines the protocol for dynamic plugin loading, unloading, and discovery\n * at runtime. Addresses the \"Dynamic Loading\" gap in the microkernel architecture\n * by enabling plugins to be loaded and unloaded without restarting the kernel.\n * \n * Inspired by:\n * - OSGi Dynamic Module System (bundle lifecycle)\n * - Kubernetes Operator pattern (reconciliation loop)\n * - VS Code Extension Host (activation events)\n * \n * This protocol enables:\n * - Runtime load/unload of plugins without kernel restart\n * - Plugin discovery from registries and local filesystem\n * - Activation events (load plugin only when needed)\n * - Safe unload with dependency awareness\n */\n\n/**\n * Dynamic Plugin Operation Type\n * Operations that can be performed on plugins at runtime\n */\nexport const DynamicPluginOperationSchema = z.enum([\n 'load', // Load and initialize a plugin at runtime\n 'unload', // Gracefully unload a running plugin\n 'reload', // Unload then load (e.g., version upgrade)\n 'enable', // Enable a loaded but disabled plugin\n 'disable', // Disable a running plugin without unloading\n]).describe('Runtime plugin operation type');\n\n/**\n * Plugin Source\n * Where to resolve a plugin for dynamic loading\n */\nexport const PluginSourceSchema = z.object({\n /**\n * Source type\n */\n type: z.enum([\n 'npm', // npm registry package\n 'local', // Local filesystem path\n 'url', // Remote URL (tarball or module)\n 'registry', // ObjectStack plugin registry\n 'git', // Git repository\n ]).describe('Plugin source type'),\n \n /**\n * Source location (package name, path, URL, or git repo)\n */\n location: z.string().describe('Package name, file path, URL, or git repository'),\n \n /**\n * Version constraint (semver range)\n */\n version: z.string().optional().describe('Semver version range (e.g., \"^1.0.0\")'),\n \n /**\n * Integrity hash for verification\n */\n integrity: z.string().optional().describe('Subresource Integrity hash (e.g., \"sha384-...\")'),\n}).describe('Plugin source location for dynamic resolution');\n\n/**\n * Activation Event\n * Defines when a dynamically available plugin should be activated.\n * Plugins remain dormant until an activation event fires.\n */\nexport const ActivationEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'onCommand', // Activate when a specific command is executed\n 'onRoute', // Activate when a URL route is matched\n 'onObject', // Activate when a specific object type is accessed\n 'onEvent', // Activate when a system event fires\n 'onService', // Activate when a service is requested\n 'onSchedule', // Activate on a cron schedule\n 'onStartup', // Activate immediately on kernel startup\n ]).describe('Trigger type for lazy activation'),\n \n /**\n * Pattern to match (command name, route glob, object name, event pattern, etc.)\n */\n pattern: z.string().describe('Match pattern for the activation trigger'),\n}).describe('Lazy activation trigger for a dynamic plugin');\n\n/**\n * Dynamic Load Request\n * Request to load a plugin at runtime\n */\nexport const DynamicLoadRequestSchema = z.object({\n /**\n * Plugin identifier to load\n */\n pluginId: z.string().describe('Unique plugin identifier'),\n \n /**\n * Plugin source\n */\n source: PluginSourceSchema,\n \n /**\n * Activation events (if omitted, plugin activates immediately)\n */\n activationEvents: z.array(ActivationEventSchema).optional()\n .describe('Lazy activation triggers; if omitted plugin starts immediately'),\n \n /**\n * Configuration overrides for the plugin\n */\n config: z.record(z.string(), z.unknown()).optional()\n .describe('Runtime configuration overrides'),\n \n /**\n * Loading priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100)\n .describe('Loading priority (lower is higher)'),\n \n /**\n * Whether to enable sandboxing for this dynamically loaded plugin\n */\n sandbox: z.boolean().default(false)\n .describe('Run in an isolated sandbox'),\n \n /**\n * Timeout for the load operation in milliseconds\n */\n timeout: z.number().int().min(1000).default(60000)\n .describe('Maximum time to complete loading in ms'),\n}).describe('Request to dynamically load a plugin at runtime');\n\n/**\n * Dynamic Unload Request\n * Request to unload a plugin at runtime\n */\nexport const DynamicUnloadRequestSchema = z.object({\n /**\n * Plugin identifier to unload\n */\n pluginId: z.string().describe('Plugin to unload'),\n \n /**\n * Unload strategy\n */\n strategy: z.enum([\n 'graceful', // Wait for in-flight requests, then unload\n 'forceful', // Unload immediately, cancel pending work\n 'drain', // Stop accepting new work, finish existing, then unload\n ]).default('graceful').describe('How to handle in-flight work during unload'),\n \n /**\n * Timeout for the unload operation in milliseconds\n */\n timeout: z.number().int().min(1000).default(30000)\n .describe('Maximum time to complete unloading in ms'),\n \n /**\n * Whether to remove cached artifacts\n */\n cleanupCache: z.boolean().default(false)\n .describe('Remove cached code and assets after unload'),\n \n /**\n * Action for dependents: plugins that depend on this one\n */\n dependentAction: z.enum([\n 'cascade', // Also unload dependent plugins\n 'warn', // Warn about dependents but proceed\n 'block', // Block unload if dependents exist\n ]).default('block').describe('How to handle plugins that depend on this one'),\n}).describe('Request to dynamically unload a plugin at runtime');\n\n/**\n * Dynamic Plugin Operation Result\n * Result of a dynamic load/unload/reload operation\n */\nexport const DynamicPluginResultSchema = z.object({\n /**\n * Whether the operation succeeded\n */\n success: z.boolean(),\n \n /**\n * The operation that was performed\n */\n operation: DynamicPluginOperationSchema,\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Operation duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Resulting plugin version (for load/reload)\n */\n version: z.string().optional(),\n \n /**\n * Error details if operation failed\n */\n error: z.object({\n code: z.string().describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n details: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n \n /**\n * Warnings (e.g., dependents affected)\n */\n warnings: z.array(z.string()).optional(),\n}).describe('Result of a dynamic plugin operation');\n\n/**\n * Plugin Discovery Source\n * Defines where to discover available plugins at runtime\n */\nexport const PluginDiscoverySourceSchema = z.object({\n /**\n * Discovery source type\n */\n type: z.enum([\n 'registry', // ObjectStack plugin registry API\n 'npm', // npm registry search\n 'directory', // Local filesystem directory scan\n 'url', // Remote manifest URL\n ]).describe('Discovery source type'),\n \n /**\n * Source endpoint or path\n */\n endpoint: z.string().describe('Registry URL, directory path, or manifest URL'),\n \n /**\n * Polling interval in milliseconds (0 = manual only)\n */\n pollInterval: z.number().int().min(0).default(0)\n .describe('How often to re-scan for new plugins (0 = manual)'),\n \n /**\n * Filter criteria for discovered plugins\n */\n filter: z.object({\n /**\n * Only discover plugins matching these tags\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Only discover plugins from these vendors\n */\n vendors: z.array(z.string()).optional(),\n \n /**\n * Minimum trust level\n */\n minTrustLevel: z.enum(['verified', 'trusted', 'community', 'untrusted']).optional(),\n }).optional(),\n}).describe('Source for runtime plugin discovery');\n\n/**\n * Plugin Discovery Configuration\n * Controls how the kernel discovers available plugins at runtime\n */\nexport const PluginDiscoveryConfigSchema = z.object({\n /**\n * Enable runtime plugin discovery\n */\n enabled: z.boolean().default(false),\n \n /**\n * Discovery sources\n */\n sources: z.array(PluginDiscoverySourceSchema).default([]),\n \n /**\n * Auto-load discovered plugins matching criteria\n */\n autoLoad: z.boolean().default(false)\n .describe('Automatically load newly discovered plugins'),\n \n /**\n * Require approval before loading discovered plugins\n */\n requireApproval: z.boolean().default(true)\n .describe('Require admin approval before loading discovered plugins'),\n}).describe('Runtime plugin discovery configuration');\n\n/**\n * Dynamic Loading Configuration\n * Top-level configuration for the dynamic plugin loading subsystem\n */\nexport const DynamicLoadingConfigSchema = z.object({\n /**\n * Enable dynamic loading/unloading at runtime\n */\n enabled: z.boolean().default(false)\n .describe('Enable runtime load/unload of plugins'),\n \n /**\n * Maximum number of dynamically loaded plugins\n */\n maxDynamicPlugins: z.number().int().min(1).default(50)\n .describe('Upper limit on runtime-loaded plugins'),\n \n /**\n * Plugin discovery configuration\n */\n discovery: PluginDiscoveryConfigSchema.optional(),\n \n /**\n * Default sandbox policy for dynamically loaded plugins\n */\n defaultSandbox: z.boolean().default(true)\n .describe('Sandbox dynamically loaded plugins by default'),\n \n /**\n * Allowed plugin sources (empty = all allowed)\n */\n allowedSources: z.array(z.enum(['npm', 'local', 'url', 'registry', 'git'])).optional()\n .describe('Restrict which source types are permitted'),\n \n /**\n * Require integrity verification for remote plugins\n */\n requireIntegrity: z.boolean().default(true)\n .describe('Require integrity hash verification for remote sources'),\n \n /**\n * Global timeout for dynamic operations in milliseconds\n */\n operationTimeout: z.number().int().min(1000).default(60000)\n .describe('Default timeout for load/unload operations in ms'),\n}).describe('Dynamic plugin loading subsystem configuration');\n\n// Export types\nexport type DynamicPluginOperation = z.infer;\nexport type PluginSource = z.infer;\nexport type ActivationEvent = z.infer;\nexport type DynamicLoadRequest = z.infer;\nexport type DynamicUnloadRequest = z.infer;\nexport type DynamicPluginResult = z.infer;\nexport type PluginDiscoverySource = z.infer;\nexport type PluginDiscoveryConfig = z.infer;\nexport type DynamicLoadingConfig = z.infer;\n\n// Export input types for schemas with defaults\nexport type DynamicLoadRequestInput = z.input;\nexport type DynamicUnloadRequestInput = z.input;\nexport type DynamicLoadingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Security and Sandboxing Protocol\n * \n * Defines comprehensive security mechanisms for plugin isolation, permission\n * management, and threat protection in the ObjectStack ecosystem.\n * \n * Features:\n * - Fine-grained permission system\n * - Resource access control\n * - Sandboxing and isolation\n * - Security scanning and verification\n * - Runtime security monitoring\n */\n\n/**\n * Permission Scope\n * Defines the scope of a permission\n */\nexport const PermissionScopeSchema = z.enum([\n 'global', // Applies to entire system\n 'tenant', // Applies to specific tenant\n 'user', // Applies to specific user\n 'resource', // Applies to specific resource\n 'plugin', // Applies within plugin boundaries\n]).describe('Scope of permission application');\n\n/**\n * Permission Action\n * Standard CRUD + extended actions\n */\nexport const PermissionActionSchema = z.enum([\n 'create', // Create new resources\n 'read', // Read existing resources\n 'update', // Update existing resources\n 'delete', // Delete resources\n 'execute', // Execute operations/functions\n 'manage', // Full management rights\n 'configure', // Configuration changes\n 'share', // Share with others\n 'export', // Export data\n 'import', // Import data\n 'admin', // Administrative access\n]).describe('Type of action being permitted');\n\n/**\n * Resource Type\n * Types of resources that can be accessed\n */\nexport const ResourceTypeSchema = z.enum([\n 'data.object', // ObjectQL objects\n 'data.record', // Individual records\n 'data.field', // Specific fields\n 'ui.view', // UI views\n 'ui.dashboard', // Dashboards\n 'ui.report', // Reports\n 'system.config', // System configuration\n 'system.plugin', // Other plugins\n 'system.api', // API endpoints\n 'system.service', // System services\n 'storage.file', // File storage\n 'storage.database', // Database access\n 'network.http', // HTTP requests\n 'network.websocket', // WebSocket connections\n 'process.spawn', // Process spawning\n 'process.env', // Environment variables\n]).describe('Type of resource being accessed');\n\n/**\n * Permission Definition\n * Defines a single permission requirement\n */\nexport const PermissionSchema = z.object({\n /**\n * Permission identifier\n */\n id: z.string().describe('Unique permission identifier'),\n \n /**\n * Resource type\n */\n resource: ResourceTypeSchema,\n \n /**\n * Allowed actions\n */\n actions: z.array(PermissionActionSchema),\n \n /**\n * Permission scope\n */\n scope: PermissionScopeSchema.default('plugin'),\n \n /**\n * Resource filter\n */\n filter: z.object({\n /**\n * Specific resource IDs\n */\n resourceIds: z.array(z.string()).optional(),\n \n /**\n * Filter condition\n */\n condition: z.string().optional().describe('Filter expression (e.g., owner = currentUser)'),\n \n /**\n * Field-level access\n */\n fields: z.array(z.string()).optional().describe('Allowed fields for data resources'),\n }).optional(),\n \n /**\n * Human-readable description\n */\n description: z.string(),\n \n /**\n * Whether this permission is required or optional\n */\n required: z.boolean().default(true),\n \n /**\n * Justification for permission\n */\n justification: z.string().optional().describe('Why this permission is needed'),\n});\n\n/**\n * Permission Set\n * Collection of permissions for a plugin\n */\nexport const PermissionSetSchema = z.object({\n /**\n * All permissions required by plugin\n */\n permissions: z.array(PermissionSchema),\n \n /**\n * Permission groups for easier management\n */\n groups: z.array(z.object({\n name: z.string().describe('Group name'),\n description: z.string(),\n permissions: z.array(z.string()).describe('Permission IDs in this group'),\n })).optional(),\n \n /**\n * Default grant strategy\n */\n defaultGrant: z.enum([\n 'prompt', // Always prompt user\n 'allow', // Allow by default\n 'deny', // Deny by default\n 'inherit', // Inherit from parent\n ]).default('prompt'),\n});\n\n/**\n * Runtime Configuration\n * Defines the execution environment for plugin isolation\n */\nexport const RuntimeConfigSchema = z.object({\n /**\n * Runtime engine type\n */\n engine: z.enum([\n 'v8-isolate', // V8 isolate-based isolation (lightweight, fast)\n 'wasm', // WebAssembly-based isolation (secure, portable)\n 'container', // Container-based isolation (Docker, podman)\n 'process', // Process-based isolation (traditional)\n ]).default('v8-isolate')\n .describe('Execution environment engine'),\n \n /**\n * Engine-specific configuration\n */\n engineConfig: z.object({\n /**\n * WASM-specific settings (when engine is \"wasm\")\n */\n wasm: z.object({\n /**\n * Maximum memory pages (64KB per page)\n */\n maxMemoryPages: z.number().int().min(1).max(65536).optional()\n .describe('Maximum WASM memory pages (64KB each)'),\n \n /**\n * Instruction execution limit\n */\n instructionLimit: z.number().int().min(1).optional()\n .describe('Maximum instructions before timeout'),\n \n /**\n * Enable SIMD instructions\n */\n enableSimd: z.boolean().default(false)\n .describe('Enable WebAssembly SIMD support'),\n \n /**\n * Enable threads\n */\n enableThreads: z.boolean().default(false)\n .describe('Enable WebAssembly threads'),\n \n /**\n * Enable bulk memory operations\n */\n enableBulkMemory: z.boolean().default(true)\n .describe('Enable bulk memory operations'),\n }).optional(),\n \n /**\n * Container-specific settings (when engine is \"container\")\n */\n container: z.object({\n /**\n * Container image\n */\n image: z.string().optional()\n .describe('Container image to use'),\n \n /**\n * Container runtime\n */\n runtime: z.enum(['docker', 'podman', 'containerd']).default('docker'),\n \n /**\n * Resource limits\n */\n resources: z.object({\n cpuLimit: z.string().optional().describe('CPU limit (e.g., \"0.5\", \"2\")'),\n memoryLimit: z.string().optional().describe('Memory limit (e.g., \"512m\", \"1g\")'),\n }).optional(),\n \n /**\n * Network mode\n */\n networkMode: z.enum(['none', 'bridge', 'host']).default('bridge'),\n }).optional(),\n \n /**\n * V8 Isolate-specific settings (when engine is \"v8-isolate\")\n */\n v8Isolate: z.object({\n /**\n * Heap size limit in MB\n */\n heapSizeMb: z.number().int().min(1).optional(),\n \n /**\n * Enable snapshot\n */\n enableSnapshot: z.boolean().default(true),\n }).optional(),\n }).optional(),\n \n /**\n * General resource limits (applies to all engines)\n */\n resourceLimits: z.object({\n /**\n * Maximum memory in bytes\n */\n maxMemory: z.number().int().optional()\n .describe('Maximum memory allocation'),\n \n /**\n * Maximum CPU percentage\n */\n maxCpu: z.number().min(0).max(100).optional()\n .describe('Maximum CPU usage percentage'),\n \n /**\n * Execution timeout in milliseconds\n */\n timeout: z.number().int().min(0).optional()\n .describe('Maximum execution time'),\n }).optional(),\n});\n\n/**\n * Sandbox Configuration\n * Defines how plugin is isolated\n */\nexport const SandboxConfigSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(true),\n \n /**\n * Sandboxing level\n */\n level: z.enum([\n 'none', // No sandboxing\n 'minimal', // Basic isolation\n 'standard', // Standard sandboxing\n 'strict', // Strict isolation\n 'paranoid', // Maximum isolation\n ]).default('standard'),\n \n /**\n * Runtime environment configuration\n */\n runtime: RuntimeConfigSchema.optional()\n .describe('Execution environment and isolation settings'),\n \n /**\n * File system access\n */\n filesystem: z.object({\n mode: z.enum(['none', 'readonly', 'restricted', 'full']).default('restricted'),\n allowedPaths: z.array(z.string()).optional().describe('Whitelisted paths'),\n deniedPaths: z.array(z.string()).optional().describe('Blacklisted paths'),\n maxFileSize: z.number().int().optional().describe('Maximum file size in bytes'),\n }).optional(),\n \n /**\n * Network access\n */\n network: z.object({\n mode: z.enum(['none', 'local', 'restricted', 'full']).default('restricted'),\n allowedHosts: z.array(z.string()).optional().describe('Whitelisted hosts'),\n deniedHosts: z.array(z.string()).optional().describe('Blacklisted hosts'),\n allowedPorts: z.array(z.number()).optional().describe('Allowed port numbers'),\n maxConnections: z.number().int().optional(),\n }).optional(),\n \n /**\n * Process execution\n */\n process: z.object({\n allowSpawn: z.boolean().default(false).describe('Allow spawning child processes'),\n allowedCommands: z.array(z.string()).optional().describe('Whitelisted commands'),\n timeout: z.number().int().optional().describe('Process timeout in ms'),\n }).optional(),\n \n /**\n * Memory limits\n */\n memory: z.object({\n maxHeap: z.number().int().optional().describe('Maximum heap size in bytes'),\n maxStack: z.number().int().optional().describe('Maximum stack size in bytes'),\n }).optional(),\n \n /**\n * CPU limits\n */\n cpu: z.object({\n maxCpuPercent: z.number().min(0).max(100).optional(),\n maxThreads: z.number().int().optional(),\n }).optional(),\n \n /**\n * Environment variables\n */\n environment: z.object({\n mode: z.enum(['none', 'readonly', 'restricted', 'full']).default('readonly'),\n allowedVars: z.array(z.string()).optional(),\n deniedVars: z.array(z.string()).optional(),\n }).optional(),\n});\n\n/**\n * Security Vulnerability\n * Represents a known security vulnerability\n */\nexport const KernelSecurityVulnerabilitySchema = z.object({\n /**\n * CVE identifier\n */\n cve: z.string().optional(),\n \n /**\n * Vulnerability identifier\n */\n id: z.string(),\n \n /**\n * Severity level\n */\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),\n \n /**\n * Category (e.g., SAST, DAST, Dependency)\n */\n category: z.string().optional(),\n\n /**\n * Title\n */\n title: z.string(),\n \n /**\n * Location of the vulnerability\n */\n location: z.string().optional(),\n\n /**\n * Remediation steps\n */\n remediation: z.string().optional(),\n\n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Affected versions\n */\n affectedVersions: z.array(z.string()),\n \n /**\n * Fixed in versions\n */\n fixedIn: z.array(z.string()).optional(),\n \n /**\n * CVSS score\n */\n cvssScore: z.number().min(0).max(10).optional(),\n \n /**\n * Exploit availability\n */\n exploitAvailable: z.boolean().default(false),\n \n /**\n * Patch available\n */\n patchAvailable: z.boolean().default(false),\n \n /**\n * Workaround\n */\n workaround: z.string().optional(),\n \n /**\n * References\n */\n references: z.array(z.string()).optional(),\n \n /**\n * Discovered date\n */\n discoveredDate: z.string().datetime().optional(),\n \n /**\n * Published date\n */\n publishedDate: z.string().datetime().optional(),\n});\n\n/**\n * Security Scan Result\n * Result of security scanning\n */\nexport const KernelSecurityScanResultSchema = z.object({\n /**\n * Scan timestamp\n */\n timestamp: z.string().datetime(),\n \n /**\n * Scanner information\n */\n scanner: z.object({\n name: z.string(),\n version: z.string(),\n }),\n \n /**\n * Overall status\n */\n status: z.enum(['passed', 'failed', 'warning']),\n \n /**\n * Vulnerabilities found\n */\n vulnerabilities: z.array(KernelSecurityVulnerabilitySchema).optional(),\n \n /**\n * Code quality issues\n */\n codeIssues: z.array(z.object({\n severity: z.enum(['error', 'warning', 'info']),\n type: z.string().describe('Issue type (e.g., sql-injection, xss)'),\n file: z.string(),\n line: z.number().int().optional(),\n message: z.string(),\n suggestion: z.string().optional(),\n })).optional(),\n \n /**\n * Dependency vulnerabilities\n */\n dependencyVulnerabilities: z.array(z.object({\n package: z.string(),\n version: z.string(),\n vulnerability: KernelSecurityVulnerabilitySchema,\n })).optional(),\n \n /**\n * License compliance\n */\n licenseCompliance: z.object({\n status: z.enum(['compliant', 'non-compliant', 'unknown']),\n issues: z.array(z.object({\n package: z.string(),\n license: z.string(),\n reason: z.string(),\n })).optional(),\n }).optional(),\n \n /**\n * Summary statistics\n */\n summary: z.object({\n totalVulnerabilities: z.number().int(),\n criticalCount: z.number().int(),\n highCount: z.number().int(),\n mediumCount: z.number().int(),\n lowCount: z.number().int(),\n infoCount: z.number().int(),\n }),\n});\n\n/**\n * Security Policy\n * Defines security policies for plugin\n */\nexport const KernelSecurityPolicySchema = z.object({\n /**\n * Content Security Policy\n */\n csp: z.object({\n directives: z.record(z.string(), z.array(z.string())).optional(),\n reportOnly: z.boolean().default(false),\n }).optional(),\n \n /**\n * CORS policy\n */\n cors: z.object({\n allowedOrigins: z.array(z.string()),\n allowedMethods: z.array(z.string()),\n allowedHeaders: z.array(z.string()),\n allowCredentials: z.boolean().default(false),\n maxAge: z.number().int().optional(),\n }).optional(),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n enabled: z.boolean().default(true),\n maxRequests: z.number().int(),\n windowMs: z.number().int().describe('Time window in milliseconds'),\n strategy: z.enum(['fixed', 'sliding', 'token-bucket']).default('sliding'),\n }).optional(),\n \n /**\n * Authentication requirements\n */\n authentication: z.object({\n required: z.boolean().default(true),\n methods: z.array(z.enum(['jwt', 'oauth2', 'api-key', 'session', 'certificate'])),\n tokenExpiration: z.number().int().optional().describe('Token expiration in seconds'),\n }).optional(),\n \n /**\n * Encryption requirements\n */\n encryption: z.object({\n dataAtRest: z.boolean().default(false).describe('Encrypt data at rest'),\n dataInTransit: z.boolean().default(true).describe('Enforce HTTPS/TLS'),\n algorithm: z.string().optional().describe('Encryption algorithm'),\n minKeyLength: z.number().int().optional().describe('Minimum key length in bits'),\n }).optional(),\n \n /**\n * Audit logging\n */\n auditLog: z.object({\n enabled: z.boolean().default(true),\n events: z.array(z.string()).optional().describe('Events to log'),\n retention: z.number().int().optional().describe('Log retention in days'),\n }).optional(),\n});\n\n/**\n * Plugin Trust Level\n * Indicates trust level of plugin\n */\nexport const PluginTrustLevelSchema = z.enum([\n 'verified', // Official/verified plugin\n 'trusted', // Trusted third-party\n 'community', // Community plugin\n 'untrusted', // Unverified plugin\n 'blocked', // Blocked/malicious\n]).describe('Trust level of the plugin');\n\n/**\n * Plugin Security Manifest\n * Complete security information for plugin\n */\nexport const PluginSecurityManifestSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Trust level\n */\n trustLevel: PluginTrustLevelSchema,\n \n /**\n * Required permissions\n */\n permissions: PermissionSetSchema,\n \n /**\n * Sandbox configuration\n */\n sandbox: SandboxConfigSchema,\n \n /**\n * Security policy\n */\n policy: KernelSecurityPolicySchema.optional(),\n \n /**\n * Security scan results\n */\n scanResults: z.array(KernelSecurityScanResultSchema).optional(),\n \n /**\n * Known vulnerabilities\n */\n vulnerabilities: z.array(KernelSecurityVulnerabilitySchema).optional(),\n \n /**\n * Code signing\n */\n codeSigning: z.object({\n signed: z.boolean(),\n signature: z.string().optional(),\n certificate: z.string().optional(),\n algorithm: z.string().optional(),\n timestamp: z.string().datetime().optional(),\n }).optional(),\n \n /**\n * Security certifications\n */\n certifications: z.array(z.object({\n name: z.string().describe('Certification name (e.g., SOC 2, ISO 27001)'),\n issuer: z.string(),\n issuedDate: z.string().datetime(),\n expiryDate: z.string().datetime().optional(),\n certificateUrl: z.string().url().optional(),\n })).optional(),\n \n /**\n * Security contact\n */\n securityContact: z.object({\n email: z.string().email().optional(),\n url: z.string().url().optional(),\n pgpKey: z.string().optional(),\n }).optional(),\n \n /**\n * Vulnerability disclosure policy\n */\n vulnerabilityDisclosure: z.object({\n policyUrl: z.string().url().optional(),\n responseTime: z.number().int().optional().describe('Expected response time in hours'),\n bugBounty: z.boolean().default(false),\n }).optional(),\n});\n\n// Export types\nexport type PermissionScope = z.infer;\nexport type PermissionAction = z.infer;\nexport type ResourceType = z.infer;\nexport type Permission = z.infer;\nexport type PermissionSet = z.infer;\nexport type RuntimeConfig = z.infer;\nexport type SandboxConfig = z.infer;\nexport type KernelSecurityVulnerability = z.infer;\nexport type KernelSecurityScanResult = z.infer;\nexport type KernelSecurityPolicy = z.infer;\nexport type PluginTrustLevel = z.infer;\nexport type PluginSecurityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * ObjectStack Plugin Structure Standards (OPS)\n * \n * Formal Zod definitions for the Plugin Directory Structure and File Naming conventions.\n * This can be used by the CLI or IDE extensions to lint project structure.\n * \n * @see PLUGIN_STANDARDS.md\n */\n\n// REGEX: snake_case identifiers\nconst SNAKE_CASE_REGEX = /^[a-z][a-z0-9_]*$/;\n\n// REGEX: Standard File Suffixes\nconst OPS_FILE_SUFFIX_REGEX = /\\.(object|field|trigger|function|view|page|dashboard|flow|app|router|service)\\.ts$/;\n\n/**\n * Validates a single file path against OPS Naming Conventions.\n * \n * @example Valid Paths\n * - \"src/crm/lead.object.ts\"\n * - \"src/finance/invoice_payment.trigger.ts\"\n * - \"src/index.ts\"\n * \n * @example Invalid Paths\n * - \"src/CRM/LeadObject.ts\" (PascalCase)\n * - \"src/utils/helper.js\" (Wrong extension)\n */\nexport const OpsFilePathSchema = z.string().describe('Validates a file path against OPS naming conventions').superRefine((path, ctx) => {\n // 1. Must be in src/\n if (!path.startsWith('src/')) {\n // Non-source files (package.json, config) are ignored by this specific validator\n // or handled separately.\n return; \n }\n\n const parts = path.split('/');\n \n // 2. Validate Domain Directory (src/[domain])\n if (parts.length > 2) {\n const domainDir = parts[1];\n if (!SNAKE_CASE_REGEX.test(domainDir)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Domain directory '${domainDir}' must be lowercase snake_case`\n });\n }\n }\n\n // 3. Validate Filename suffix\n const filename = parts[parts.length - 1];\n \n // Skip index.ts and utility files if they don't match the specific resource pattern\n // But strict OPS encourages explicit suffixes for resources.\n if (filename === 'index.ts' || filename === 'main.ts') return;\n\n if (!SNAKE_CASE_REGEX.test(filename.split('.')[0])) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Filename '${filename}' base name must be lowercase snake_case`\n });\n }\n\n if (!OPS_FILE_SUFFIX_REGEX.test(filename)) {\n // We allow other files, but we warn or mark them as non-standard resources\n // For strict mode:\n // ctx.addIssue({\n // code: z.ZodIssueCode.custom,\n // message: `Filename '${filename}' does not end with a valid semantic suffix (.object.ts, .view.ts, etc.)`\n // });\n }\n});\n\n/**\n * Schema for a \"Scanned Module\" structure.\n * Represents the contents of a domain folder.\n */\nexport const OpsDomainModuleSchema = z.object({\n name: z.string().regex(SNAKE_CASE_REGEX).describe('Module name (snake_case)'),\n files: z.array(z.string()).describe('List of files in this module'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n}).describe('Scanned domain module representing a plugin folder').superRefine((module, ctx) => {\n // Rule: Must have an index.ts\n if (!module.files.includes('index.ts')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Module '${module.name}' is missing an 'index.ts' entry point.`\n });\n }\n});\n\n/**\n * Schema for a full Plugin Project Layout\n */\nexport const OpsPluginStructureSchema = z.object({\n root: z.string().describe('Root directory path of the plugin project'),\n files: z.array(z.string()).describe('List of all file paths relative to root'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n}).describe('Full plugin project layout validated against OPS conventions').superRefine((project, ctx) => {\n // Check for configuration file\n if (!project.files.includes('objectstack.config.ts')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"Missing 'objectstack.config.ts' configuration file.\"\n });\n }\n \n // Validate each source file individually\n project.files.filter(f => f.startsWith('src/')).forEach(file => {\n const result = OpsFilePathSchema.safeParse(file);\n if (!result.success) {\n result.error.issues.forEach(issue => {\n ctx.addIssue({ ...issue, path: [file] });\n })\n }\n });\n});\n\nexport type OpsFilePath = z.infer;\nexport type OpsDomainModule = z.infer;\nexport type OpsPluginStructure = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Plugin Validator Protocol\n * \n * Zod schemas for plugin validation data structures.\n * These schemas align with the IPluginValidator contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Validation Result Schemas\n// ============================================================================\n\n/**\n * Validation Error Schema\n * Represents a single validation error\n * \n * @example\n * {\n * \"field\": \"version\",\n * \"message\": \"Invalid semver format\",\n * \"code\": \"INVALID_VERSION\"\n * }\n */\nexport const ValidationErrorSchema = z.object({\n /**\n * Field that failed validation\n */\n field: z.string().describe('Field name that failed validation'),\n \n /**\n * Human-readable error message\n */\n message: z.string().describe('Human-readable error message'),\n \n /**\n * Machine-readable error code (optional)\n */\n code: z.string().optional().describe('Machine-readable error code'),\n});\n\nexport type ValidationError = z.infer;\n\n/**\n * Validation Warning Schema\n * Represents a non-fatal validation warning\n * \n * @example\n * {\n * \"field\": \"description\",\n * \"message\": \"Description is empty\",\n * \"code\": \"MISSING_DESCRIPTION\"\n * }\n */\nexport const ValidationWarningSchema = z.object({\n /**\n * Field with warning\n */\n field: z.string().describe('Field name with warning'),\n \n /**\n * Human-readable warning message\n */\n message: z.string().describe('Human-readable warning message'),\n \n /**\n * Machine-readable warning code (optional)\n */\n code: z.string().optional().describe('Machine-readable warning code'),\n});\n\nexport type ValidationWarning = z.infer;\n\n/**\n * Validation Result Schema\n * Result of plugin validation operation\n * \n * @example\n * {\n * \"valid\": false,\n * \"errors\": [{\n * \"field\": \"name\",\n * \"message\": \"Plugin name is required\",\n * \"code\": \"REQUIRED_FIELD\"\n * }],\n * \"warnings\": [{\n * \"field\": \"description\",\n * \"message\": \"Description is recommended\",\n * \"code\": \"MISSING_DESCRIPTION\"\n * }]\n * }\n */\nexport const ValidationResultSchema = z.object({\n /**\n * Whether validation passed\n */\n valid: z.boolean().describe('Whether the plugin passed validation'),\n \n /**\n * Validation errors (if any)\n */\n errors: z.array(ValidationErrorSchema).optional().describe('Validation errors'),\n \n /**\n * Validation warnings (non-fatal issues)\n */\n warnings: z.array(ValidationWarningSchema).optional().describe('Validation warnings'),\n});\n\nexport type ValidationResult = z.infer;\n\n// ============================================================================\n// Plugin Metadata Schema\n// ============================================================================\n\n/**\n * Plugin Schema\n * Metadata structure for a plugin\n * \n * This aligns with and extends the existing PluginSchema from plugin.zod.ts\n * \n * @example\n * {\n * \"name\": \"crm-plugin\",\n * \"version\": \"1.0.0\",\n * \"dependencies\": [\"core-plugin\"]\n * }\n */\nexport const PluginMetadataSchema = z.object({\n /**\n * Unique plugin identifier (snake_case)\n */\n name: z.string().min(1).describe('Unique plugin identifier'),\n \n /**\n * Plugin version (semver)\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic version (e.g., 1.0.0)'),\n \n /**\n * Plugin dependencies (array of plugin names)\n */\n dependencies: z.array(z.string()).optional().describe('Array of plugin names this plugin depends on'),\n \n /**\n * Plugin signature for cryptographic verification (optional)\n */\n signature: z.string().optional().describe('Cryptographic signature for plugin verification'),\n \n /**\n * Additional plugin metadata\n */\n}).passthrough().describe('Plugin metadata for validation');\n\nexport type PluginMetadata = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Versioning and Compatibility Protocol\n * \n * Defines comprehensive versioning, compatibility checking, and dependency\n * resolution mechanisms for the plugin ecosystem.\n * \n * Based on semantic versioning (SemVer) with extensions for:\n * - Compatibility matrices\n * - Breaking change detection\n * - Migration paths\n * - Multi-version support\n */\n\n/**\n * Semantic Version Schema\n * Standard SemVer format with optional pre-release and build metadata\n */\nexport const SemanticVersionSchema = z.object({\n major: z.number().int().min(0).describe('Major version (breaking changes)'),\n minor: z.number().int().min(0).describe('Minor version (backward compatible features)'),\n patch: z.number().int().min(0).describe('Patch version (backward compatible fixes)'),\n preRelease: z.string().optional().describe('Pre-release identifier (alpha, beta, rc.1)'),\n build: z.string().optional().describe('Build metadata'),\n}).describe('Semantic version number');\n\n/**\n * Version Constraint Schema\n * Defines version requirements using SemVer ranges\n */\nexport const VersionConstraintSchema = z.union([\n z.string().regex(/^[\\d.]+$/).describe('Exact version: `1.2.3`'),\n z.string().regex(/^\\^[\\d.]+$/).describe('Compatible with: `^1.2.3` (`>=1.2.3 <2.0.0`)'),\n z.string().regex(/^~[\\d.]+$/).describe('Approximately: `~1.2.3` (`>=1.2.3 <1.3.0`)'),\n z.string().regex(/^>=[\\d.]+$/).describe('Greater than or equal: `>=1.2.3`'),\n z.string().regex(/^>[\\d.]+$/).describe('Greater than: `>1.2.3`'),\n z.string().regex(/^<=[\\d.]+$/).describe('Less than or equal: `<=1.2.3`'),\n z.string().regex(/^<[\\d.]+$/).describe('Less than: `<1.2.3`'),\n z.string().regex(/^[\\d.]+ - [\\d.]+$/).describe('Range: `1.2.3 - 2.3.4`'),\n z.literal('*').describe('Any version'),\n z.literal('latest').describe('Latest stable version'),\n]);\n\n/**\n * Compatibility Level\n * Describes the level of compatibility between versions\n */\nexport const CompatibilityLevelSchema = z.enum([\n 'fully-compatible', // 100% compatible, drop-in replacement\n 'backward-compatible', // Backward compatible, new features added\n 'deprecated-compatible', // Compatible but uses deprecated features\n 'breaking-changes', // Breaking changes, migration required\n 'incompatible', // Completely incompatible\n]).describe('Compatibility level between versions');\n\n/**\n * Breaking Change\n * Documents a breaking change in a version\n */\nexport const BreakingChangeSchema = z.object({\n /**\n * Version where the change was introduced\n */\n introducedIn: z.string().describe('Version that introduced this breaking change'),\n \n /**\n * Type of breaking change\n */\n type: z.enum([\n 'api-removed', // API removed\n 'api-renamed', // API renamed\n 'api-signature-changed', // Function signature changed\n 'behavior-changed', // Behavior changed\n 'dependency-changed', // Dependency requirement changed\n 'configuration-changed', // Configuration schema changed\n 'protocol-changed', // Protocol implementation changed\n ]),\n \n /**\n * What was changed\n */\n description: z.string(),\n \n /**\n * Migration guide\n */\n migrationGuide: z.string().optional().describe('How to migrate from old to new'),\n \n /**\n * Deprecated in version\n */\n deprecatedIn: z.string().optional().describe('Version where old API was deprecated'),\n \n /**\n * Will be removed in version\n */\n removedIn: z.string().optional().describe('Version where old API will be removed'),\n \n /**\n * Automated migration available\n */\n automatedMigration: z.boolean().default(false)\n .describe('Whether automated migration tool is available'),\n \n /**\n * Impact severity\n */\n severity: z.enum(['critical', 'major', 'minor']).describe('Impact severity'),\n});\n\n/**\n * Deprecation Notice\n * Information about deprecated features\n */\nexport const DeprecationNoticeSchema = z.object({\n /**\n * Feature or API being deprecated\n */\n feature: z.string().describe('Deprecated feature identifier'),\n \n /**\n * Version when deprecated\n */\n deprecatedIn: z.string(),\n \n /**\n * Planned removal version\n */\n removeIn: z.string().optional(),\n \n /**\n * Reason for deprecation\n */\n reason: z.string(),\n \n /**\n * Recommended alternative\n */\n alternative: z.string().optional().describe('What to use instead'),\n \n /**\n * Migration path\n */\n migrationPath: z.string().optional().describe('How to migrate to alternative'),\n});\n\n/**\n * Compatibility Matrix Entry\n * Maps compatibility between different plugin versions\n */\nexport const CompatibilityMatrixEntrySchema = z.object({\n /**\n * Source version\n */\n from: z.string().describe('Version being upgraded from'),\n \n /**\n * Target version\n */\n to: z.string().describe('Version being upgraded to'),\n \n /**\n * Compatibility level\n */\n compatibility: CompatibilityLevelSchema,\n \n /**\n * Breaking changes list\n */\n breakingChanges: z.array(BreakingChangeSchema).optional(),\n \n /**\n * Migration required\n */\n migrationRequired: z.boolean().default(false),\n \n /**\n * Migration complexity\n */\n migrationComplexity: z.enum(['trivial', 'simple', 'moderate', 'complex', 'major']).optional(),\n \n /**\n * Estimated migration time in hours\n */\n estimatedMigrationTime: z.number().optional(),\n \n /**\n * Migration script available\n */\n migrationScript: z.string().optional().describe('Path to migration script'),\n \n /**\n * Test coverage for migration\n */\n testCoverage: z.number().min(0).max(100).optional()\n .describe('Percentage of migration covered by tests'),\n});\n\n/**\n * Plugin Compatibility Matrix\n * Complete compatibility information for a plugin\n */\nexport const PluginCompatibilityMatrixSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current version\n */\n currentVersion: z.string(),\n \n /**\n * Compatibility entries\n */\n compatibilityMatrix: z.array(CompatibilityMatrixEntrySchema),\n \n /**\n * Supported versions\n */\n supportedVersions: z.array(z.object({\n version: z.string(),\n supported: z.boolean(),\n endOfLife: z.string().datetime().optional().describe('End of support date'),\n securitySupport: z.boolean().default(false).describe('Still receives security updates'),\n })),\n \n /**\n * Minimum compatible version\n */\n minimumCompatibleVersion: z.string().optional()\n .describe('Oldest version that can be directly upgraded'),\n});\n\n/**\n * Dependency Conflict\n * Represents a conflict in plugin dependencies at the kernel level.\n * Models plugin-to-plugin dependency conflicts with typed conflict categories.\n * \n * @see hub/plugin-security.zod.ts DependencyConflictSchema for hub-level package version conflicts\n * which focuses on marketplace registry resolution.\n */\nexport const DependencyConflictSchema = z.object({\n /**\n * Type of conflict\n */\n type: z.enum([\n 'version-mismatch', // Different versions required\n 'missing-dependency', // Required dependency not found\n 'circular-dependency', // Circular dependency detected\n 'incompatible-versions', // Incompatible versions required by different plugins\n 'conflicting-interfaces', // Plugins implement conflicting interfaces\n ]),\n \n /**\n * Plugins involved in conflict\n */\n plugins: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n requirement: z.string().optional().describe('What this plugin requires'),\n })),\n \n /**\n * Conflict description\n */\n description: z.string(),\n \n /**\n * Possible resolutions\n */\n resolutions: z.array(z.object({\n strategy: z.enum([\n 'upgrade', // Upgrade one or more plugins\n 'downgrade', // Downgrade one or more plugins\n 'replace', // Replace with alternative plugin\n 'disable', // Disable conflicting plugin\n 'manual', // Manual intervention required\n ]),\n description: z.string(),\n automaticResolution: z.boolean().default(false),\n riskLevel: z.enum(['low', 'medium', 'high']),\n })).optional(),\n \n /**\n * Severity of conflict\n */\n severity: z.enum(['critical', 'error', 'warning', 'info']),\n});\n\n/**\n * Dependency Resolution Result\n * Result of dependency resolution process\n */\nexport const PluginDependencyResolutionResultSchema = z.object({\n /**\n * Resolution successful\n */\n success: z.boolean(),\n \n /**\n * Resolved plugin versions\n */\n resolved: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n resolvedVersion: z.string(),\n })).optional(),\n \n /**\n * Conflicts found\n */\n conflicts: z.array(DependencyConflictSchema).optional(),\n \n /**\n * Warnings\n */\n warnings: z.array(z.string()).optional(),\n \n /**\n * Installation order (topologically sorted)\n */\n installationOrder: z.array(z.string()).optional()\n .describe('Plugin IDs in order they should be installed'),\n \n /**\n * Dependency graph\n */\n dependencyGraph: z.record(z.string(), z.array(z.string())).optional()\n .describe('Map of plugin ID to its dependencies'),\n});\n\n/**\n * Multi-Version Support Configuration\n * Allows running multiple versions of a plugin simultaneously\n */\nexport const MultiVersionSupportSchema = z.object({\n /**\n * Enable multi-version support\n */\n enabled: z.boolean().default(false),\n \n /**\n * Maximum concurrent versions\n */\n maxConcurrentVersions: z.number().int().min(1).default(2)\n .describe('How many versions can run at the same time'),\n \n /**\n * Version selection strategy\n */\n selectionStrategy: z.enum([\n 'latest', // Always use latest version\n 'stable', // Use latest stable version\n 'compatible', // Use version compatible with dependencies\n 'pinned', // Use pinned version\n 'canary', // Use canary/preview version\n 'custom', // Custom selection logic\n ]).default('latest'),\n \n /**\n * Version routing rules\n */\n routing: z.array(z.object({\n condition: z.string().describe('Routing condition (e.g., tenant, user, feature flag)'),\n version: z.string().describe('Version to use when condition matches'),\n priority: z.number().int().default(100).describe('Rule priority'),\n })).optional(),\n \n /**\n * Gradual rollout configuration\n */\n rollout: z.object({\n enabled: z.boolean().default(false),\n strategy: z.enum(['percentage', 'blue-green', 'canary']),\n percentage: z.number().min(0).max(100).optional()\n .describe('Percentage of traffic to new version'),\n duration: z.number().int().optional()\n .describe('Rollout duration in milliseconds'),\n }).optional(),\n});\n\n/**\n * Plugin Version Metadata\n * Complete version information for a plugin\n */\nexport const PluginVersionMetadataSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Version number\n */\n version: SemanticVersionSchema,\n \n /**\n * Version string (computed)\n */\n versionString: z.string().describe('Full version string (e.g., 1.2.3-beta.1+build.123)'),\n \n /**\n * Release date\n */\n releaseDate: z.string().datetime(),\n \n /**\n * Release notes\n */\n releaseNotes: z.string().optional(),\n \n /**\n * Breaking changes\n */\n breakingChanges: z.array(BreakingChangeSchema).optional(),\n \n /**\n * Deprecations\n */\n deprecations: z.array(DeprecationNoticeSchema).optional(),\n \n /**\n * Compatibility matrix\n */\n compatibilityMatrix: z.array(CompatibilityMatrixEntrySchema).optional(),\n \n /**\n * Security vulnerabilities fixed\n */\n securityFixes: z.array(z.object({\n cve: z.string().optional().describe('CVE identifier'),\n severity: z.enum(['critical', 'high', 'medium', 'low']),\n description: z.string(),\n fixedIn: z.string().describe('Version where vulnerability was fixed'),\n })).optional(),\n \n /**\n * Download statistics\n */\n statistics: z.object({\n downloads: z.number().int().min(0).optional(),\n installations: z.number().int().min(0).optional(),\n ratings: z.number().min(0).max(5).optional(),\n }).optional(),\n \n /**\n * Support status\n */\n support: z.object({\n status: z.enum(['active', 'maintenance', 'deprecated', 'eol']),\n endOfLife: z.string().datetime().optional(),\n securitySupport: z.boolean().default(true),\n }),\n});\n\n// Export types\nexport type SemanticVersion = z.infer;\nexport type VersionConstraint = z.infer;\nexport type CompatibilityLevel = z.infer;\nexport type BreakingChange = z.infer;\nexport type DeprecationNotice = z.infer;\nexport type CompatibilityMatrixEntry = z.infer;\nexport type PluginCompatibilityMatrix = z.infer;\nexport type DependencyConflict = z.infer;\nexport type PluginDependencyResolutionResult = z.infer;\nexport type MultiVersionSupport = z.infer;\nexport type PluginVersionMetadata = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Service Registry Protocol\n * \n * Zod schemas for service registry data structures.\n * These schemas align with the IServiceRegistry contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n * \n * Note: IServiceRegistry itself is a runtime interface (methods only),\n * so it correctly remains a TypeScript interface. This file contains\n * schemas for configuration and metadata related to service registry.\n */\n\n// ============================================================================\n// Service Metadata Schemas\n// ============================================================================\n\n/**\n * Service Scope Type Enum\n * Different service scoping strategies\n */\nexport const ServiceScopeType = z.enum([\n 'singleton', // Single instance shared across the application\n 'transient', // New instance created each time\n 'scoped', // Instance per scope (request, session, transaction, etc.)\n]).describe('Service scope type');\n\nexport type ServiceScopeType = z.infer;\n\n/**\n * Service Metadata Schema\n * Metadata about a registered service\n * \n * @example\n * {\n * \"name\": \"database\",\n * \"scope\": \"singleton\",\n * \"type\": \"IDataEngine\",\n * \"registeredAt\": 1706659200000\n * }\n */\nexport const ServiceMetadataSchema = z.object({\n /**\n * Service name (unique identifier)\n */\n name: z.string().min(1).describe('Unique service name identifier'),\n \n /**\n * Service scope type\n */\n scope: ServiceScopeType.optional().default('singleton')\n .describe('Service scope type'),\n \n /**\n * Service type or interface name (optional)\n */\n type: z.string().optional().describe('Service type or interface name'),\n \n /**\n * Registration timestamp (Unix milliseconds)\n */\n registeredAt: z.number().int().optional()\n .describe('Unix timestamp in milliseconds when service was registered'),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Additional service-specific metadata'),\n});\n\nexport type ServiceMetadata = z.infer;\n\n// ============================================================================\n// Service Registry Configuration Schemas\n// ============================================================================\n\n/**\n * Service Registry Configuration Schema\n * Configuration for service registry behavior\n * \n * @example\n * {\n * \"strictMode\": true,\n * \"allowOverwrite\": false,\n * \"enableLogging\": true,\n * \"scopeTypes\": [\"singleton\", \"transient\", \"request\", \"session\"]\n * }\n */\nexport const ServiceRegistryConfigSchema = z.object({\n /**\n * Strict mode: throw errors on invalid operations\n * @default true\n */\n strictMode: z.boolean().optional().default(true)\n .describe('Throw errors on invalid operations (duplicate registration, service not found, etc.)'),\n \n /**\n * Allow overwriting existing services\n * @default false\n */\n allowOverwrite: z.boolean().optional().default(false)\n .describe('Allow overwriting existing service registrations'),\n \n /**\n * Enable logging for service operations\n * @default false\n */\n enableLogging: z.boolean().optional().default(false)\n .describe('Enable logging for service registration and retrieval'),\n \n /**\n * Custom scope types (beyond singleton, transient, scoped)\n * @default ['singleton', 'transient', 'scoped']\n */\n scopeTypes: z.array(z.string()).optional()\n .describe('Supported scope types'),\n \n /**\n * Maximum number of services (prevent memory leaks)\n */\n maxServices: z.number().int().min(1).optional()\n .describe('Maximum number of services that can be registered'),\n});\n\nexport type ServiceRegistryConfig = z.infer;\nexport type ServiceRegistryConfigInput = z.input;\n\n// ============================================================================\n// Service Factory Schemas\n// ============================================================================\n\n/**\n * Service Factory Registration Schema\n * Configuration for registering a service factory\n * \n * @example\n * {\n * \"name\": \"logger\",\n * \"scope\": \"singleton\",\n * \"factoryType\": \"sync\"\n * }\n */\nexport const ServiceFactoryRegistrationSchema = z.object({\n /**\n * Service name (unique identifier)\n */\n name: z.string().min(1).describe('Unique service name identifier'),\n \n /**\n * Service scope type\n */\n scope: ServiceScopeType.optional().default('singleton')\n .describe('Service scope type'),\n \n /**\n * Factory type (sync or async)\n */\n factoryType: z.enum(['sync', 'async']).optional().default('sync')\n .describe('Whether factory is synchronous or asynchronous'),\n \n /**\n * Whether this is a singleton (cache factory result)\n */\n singleton: z.boolean().optional().default(true)\n .describe('Whether to cache the factory result (singleton pattern)'),\n});\n\nexport type ServiceFactoryRegistration = z.infer;\n\n// ============================================================================\n// Scoped Service Schemas\n// ============================================================================\n\n/**\n * Scope Configuration Schema\n * Configuration for creating a new scope\n * \n * @example\n * {\n * \"scopeType\": \"request\",\n * \"scopeId\": \"req-12345\",\n * \"metadata\": {\n * \"userId\": \"user-123\",\n * \"requestId\": \"req-12345\"\n * }\n * }\n */\nexport const ScopeConfigSchema = z.object({\n /**\n * Type of scope (request, session, transaction, etc.)\n */\n scopeType: z.string().describe('Type of scope'),\n \n /**\n * Scope identifier (optional, auto-generated if not provided)\n */\n scopeId: z.string().optional().describe('Unique scope identifier'),\n \n /**\n * Scope metadata (context information)\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Scope-specific context metadata'),\n});\n\nexport type ScopeConfig = z.infer;\n\n/**\n * Scope Info Schema\n * Information about an active scope\n * \n * @example\n * {\n * \"scopeId\": \"req-12345\",\n * \"scopeType\": \"request\",\n * \"createdAt\": 1706659200000,\n * \"serviceCount\": 5,\n * \"metadata\": {\n * \"userId\": \"user-123\"\n * }\n * }\n */\nexport const ScopeInfoSchema = z.object({\n /**\n * Scope identifier\n */\n scopeId: z.string().describe('Unique scope identifier'),\n \n /**\n * Type of scope\n */\n scopeType: z.string().describe('Type of scope'),\n \n /**\n * Creation timestamp (Unix milliseconds)\n */\n createdAt: z.number().int().describe('Unix timestamp in milliseconds when scope was created'),\n \n /**\n * Number of services in this scope\n */\n serviceCount: z.number().int().min(0).optional()\n .describe('Number of services registered in this scope'),\n \n /**\n * Scope metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Scope-specific context metadata'),\n});\n\nexport type ScopeInfo = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Startup Orchestrator Protocol\n * \n * Zod schemas for plugin startup orchestration data structures.\n * These schemas align with the IStartupOrchestrator contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Startup Configuration Schemas\n// ============================================================================\n\n/**\n * Startup Options Schema\n * Configuration for plugin startup orchestration\n * \n * @example\n * {\n * \"timeout\": 30000,\n * \"rollbackOnFailure\": true,\n * \"healthCheck\": false,\n * \"parallel\": false\n * }\n */\nexport const StartupOptionsSchema = z.object({\n /**\n * Maximum time (ms) to wait for each plugin to start\n * @default 30000 (30 seconds)\n */\n timeout: z.number().int().min(0).optional().default(30000)\n .describe('Maximum time in milliseconds to wait for each plugin to start'),\n \n /**\n * Whether to rollback (destroy) already-started plugins on failure\n * @default true\n */\n rollbackOnFailure: z.boolean().optional().default(true)\n .describe('Whether to rollback already-started plugins if any plugin fails'),\n \n /**\n * Whether to run health checks after startup\n * @default false\n */\n healthCheck: z.boolean().optional().default(false)\n .describe('Whether to run health checks after plugin startup'),\n \n /**\n * Whether to run plugins in parallel (if dependencies allow)\n * @default false (sequential startup)\n */\n parallel: z.boolean().optional().default(false)\n .describe('Whether to start plugins in parallel when dependencies allow'),\n \n /**\n * Custom context to pass to plugin lifecycle methods\n */\n context: z.unknown().optional().describe('Custom context object to pass to plugin lifecycle methods'),\n});\n\nexport type StartupOptions = z.infer;\nexport type StartupOptionsInput = z.input;\n\n// ============================================================================\n// Health Status Schemas\n// ============================================================================\n\n/**\n * Health Status Schema\n * Health status for a plugin\n * \n * @example\n * {\n * \"healthy\": true,\n * \"timestamp\": 1706659200000,\n * \"details\": {\n * \"databaseConnected\": true,\n * \"memoryUsage\": 45.2\n * }\n * }\n */\nexport const HealthStatusSchema = z.object({\n /**\n * Whether the plugin is healthy\n */\n healthy: z.boolean().describe('Whether the plugin is healthy'),\n \n /**\n * Health check timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds when health check was performed'),\n \n /**\n * Optional health details (plugin-specific)\n */\n details: z.record(z.string(), z.unknown()).optional().describe('Optional plugin-specific health details'),\n \n /**\n * Optional error message if unhealthy\n */\n message: z.string().optional().describe('Error message if plugin is unhealthy'),\n});\n\nexport type HealthStatus = z.infer;\n\n// ============================================================================\n// Startup Result Schemas\n// ============================================================================\n\n/**\n * Plugin Startup Result Schema\n * Result of a single plugin startup operation\n * \n * @example\n * {\n * \"plugin\": { \"name\": \"crm-plugin\", \"version\": \"1.0.0\" },\n * \"success\": true,\n * \"duration\": 1250,\n * \"health\": {\n * \"healthy\": true,\n * \"timestamp\": 1706659200000\n * }\n * }\n */\nexport const PluginStartupResultSchema = z.object({\n /**\n * Plugin that was started\n */\n plugin: z.object({\n name: z.string(),\n version: z.string().optional(),\n }).passthrough().describe('Plugin metadata'),\n \n /**\n * Whether startup was successful\n */\n success: z.boolean().describe('Whether the plugin started successfully'),\n \n /**\n * Time taken to start (milliseconds)\n */\n duration: z.number().min(0).describe('Time taken to start the plugin in milliseconds'),\n \n /**\n * Error if startup failed\n */\n error: z.object({\n name: z.string().describe('Error class name'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n code: z.string().optional().describe('Error code'),\n }).optional().describe('Serializable error representation if startup failed'),\n \n /**\n * Health status after startup (if healthCheck enabled)\n */\n health: HealthStatusSchema.optional().describe('Health status after startup if health check was enabled'),\n});\n\nexport type PluginStartupResult = z.infer;\n\n// ============================================================================\n// Startup Orchestration Result Schema\n// ============================================================================\n\n/**\n * Startup Orchestration Result Schema\n * Overall result of orchestrating startup for multiple plugins\n * \n * @example\n * {\n * \"results\": [\n * { \"plugin\": { \"name\": \"plugin1\" }, \"success\": true, \"duration\": 1200 },\n * { \"plugin\": { \"name\": \"plugin2\" }, \"success\": true, \"duration\": 850 }\n * ],\n * \"totalDuration\": 2050,\n * \"allSuccessful\": true\n * }\n */\nexport const StartupOrchestrationResultSchema = z.object({\n /**\n * Individual plugin startup results\n */\n results: z.array(PluginStartupResultSchema).describe('Startup results for each plugin'),\n \n /**\n * Total time taken for all plugins (milliseconds)\n */\n totalDuration: z.number().min(0).describe('Total time taken for all plugins in milliseconds'),\n \n /**\n * Whether all plugins started successfully\n */\n allSuccessful: z.boolean().describe('Whether all plugins started successfully'),\n \n /**\n * Plugins that were rolled back (if rollbackOnFailure was enabled)\n */\n rolledBack: z.array(z.string()).optional().describe('Names of plugins that were rolled back'),\n});\n\nexport type StartupOrchestrationResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\n\n/**\n * # Plugin Registry Protocol\n * \n * Defines the schema for the plugin discovery and registry system.\n * This enables plugins from different vendors to be discovered, validated,\n * and composed together in the ObjectStack ecosystem.\n */\n\n/**\n * Plugin Vendor Information\n */\nexport const PluginVendorSchema = z.object({\n /**\n * Vendor identifier (reverse domain notation)\n * Example: \"com.acme\", \"org.apache\", \"com.objectstack\"\n */\n id: z.string()\n .regex(/^[a-z][a-z0-9]*(\\.[a-z][a-z0-9]*)+$/)\n .describe('Vendor identifier (reverse domain)'),\n \n /**\n * Vendor display name\n */\n name: z.string(),\n \n /**\n * Vendor website\n */\n website: z.string().url().optional(),\n \n /**\n * Contact email\n */\n email: z.string().email().optional(),\n \n /**\n * Verification status\n */\n verified: z.boolean().default(false).describe('Whether vendor is verified by ObjectStack'),\n \n /**\n * Trust level\n */\n trustLevel: z.enum(['official', 'verified', 'community', 'unverified']).default('unverified'),\n});\n\n/**\n * Plugin Quality Metrics\n */\nexport const PluginQualityMetricsSchema = z.object({\n /**\n * Test coverage percentage\n */\n testCoverage: z.number().min(0).max(100).optional(),\n \n /**\n * Documentation score (0-100)\n */\n documentationScore: z.number().min(0).max(100).optional(),\n \n /**\n * Code quality score (0-100)\n */\n codeQuality: z.number().min(0).max(100).optional(),\n \n /**\n * Security scan status\n */\n securityScan: z.object({\n lastScanDate: z.string().datetime().optional(),\n vulnerabilities: z.object({\n critical: z.number().int().min(0).default(0),\n high: z.number().int().min(0).default(0),\n medium: z.number().int().min(0).default(0),\n low: z.number().int().min(0).default(0),\n }).optional(),\n passed: z.boolean().default(false),\n }).optional(),\n \n /**\n * Conformance test results\n */\n conformanceTests: z.array(z.object({\n protocolId: z.string().describe('Protocol being tested'),\n passed: z.boolean(),\n totalTests: z.number().int().min(0),\n passedTests: z.number().int().min(0),\n lastRunDate: z.string().datetime().optional(),\n })).optional(),\n});\n\n/**\n * Plugin Usage Statistics\n */\nexport const PluginStatisticsSchema = z.object({\n /**\n * Total downloads\n */\n downloads: z.number().int().min(0).default(0),\n \n /**\n * Downloads in the last 30 days\n */\n downloadsLastMonth: z.number().int().min(0).default(0),\n \n /**\n * Number of active installations\n */\n activeInstallations: z.number().int().min(0).default(0),\n \n /**\n * User ratings\n */\n ratings: z.object({\n average: z.number().min(0).max(5).default(0),\n count: z.number().int().min(0).default(0),\n distribution: z.object({\n '5': z.number().int().min(0).default(0),\n '4': z.number().int().min(0).default(0),\n '3': z.number().int().min(0).default(0),\n '2': z.number().int().min(0).default(0),\n '1': z.number().int().min(0).default(0),\n }).optional(),\n }).optional(),\n \n /**\n * GitHub stars (if open source)\n */\n stars: z.number().int().min(0).optional(),\n \n /**\n * Number of dependent plugins\n */\n dependents: z.number().int().min(0).default(0),\n});\n\n/**\n * Plugin Registry Entry\n * Complete metadata for a plugin in the registry.\n */\nexport const PluginRegistryEntrySchema = z.object({\n /**\n * Plugin identifier (must match manifest.id)\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Plugin identifier (reverse domain notation)'),\n \n /**\n * Current version\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/),\n \n /**\n * Plugin display name\n */\n name: z.string(),\n \n /**\n * Short description\n */\n description: z.string().optional(),\n \n /**\n * Detailed documentation/README\n */\n readme: z.string().optional(),\n \n /**\n * Plugin type/category\n */\n category: z.enum([\n 'data', // Data management, storage, databases\n 'integration', // External service integrations\n 'ui', // UI components and themes\n 'analytics', // Analytics and reporting\n 'security', // Security, auth, compliance\n 'automation', // Workflows and automation\n 'ai', // AI/ML capabilities\n 'utility', // General utilities\n 'driver', // Database/storage drivers\n 'gateway', // API gateways\n 'adapter', // Runtime adapters\n ]).optional(),\n \n /**\n * Tags for categorization\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Vendor information\n */\n vendor: PluginVendorSchema,\n \n /**\n * Capability manifest (what the plugin implements/provides)\n */\n capabilities: PluginCapabilityManifestSchema.optional(),\n \n /**\n * Compatibility information\n */\n compatibility: z.object({\n /**\n * Minimum ObjectStack version required\n */\n minObjectStackVersion: z.string().optional(),\n \n /**\n * Maximum ObjectStack version supported\n */\n maxObjectStackVersion: z.string().optional(),\n \n /**\n * Node.js version requirement\n */\n nodeVersion: z.string().optional(),\n \n /**\n * Supported platforms\n */\n platforms: z.array(z.enum(['linux', 'darwin', 'win32', 'browser'])).optional(),\n }).optional(),\n \n /**\n * Links and resources\n */\n links: z.object({\n homepage: z.string().url().optional(),\n repository: z.string().url().optional(),\n documentation: z.string().url().optional(),\n bugs: z.string().url().optional(),\n changelog: z.string().url().optional(),\n }).optional(),\n \n /**\n * Media assets\n */\n media: z.object({\n icon: z.string().url().optional(),\n logo: z.string().url().optional(),\n screenshots: z.array(z.string().url()).optional(),\n video: z.string().url().optional(),\n }).optional(),\n \n /**\n * Quality metrics\n */\n quality: PluginQualityMetricsSchema.optional(),\n \n /**\n * Usage statistics\n */\n statistics: PluginStatisticsSchema.optional(),\n \n /**\n * License information\n */\n license: z.string().optional().describe('SPDX license identifier'),\n \n /**\n * Pricing (if commercial)\n */\n pricing: z.object({\n model: z.enum(['free', 'freemium', 'paid', 'enterprise']),\n price: z.number().min(0).optional(),\n currency: z.string().default('USD').optional(),\n billingPeriod: z.enum(['one-time', 'monthly', 'yearly']).optional(),\n }).optional(),\n \n /**\n * Publication dates\n */\n publishedAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n \n /**\n * Deprecation status\n */\n deprecated: z.boolean().default(false),\n deprecationMessage: z.string().optional(),\n replacedBy: z.string().optional().describe('Plugin ID that replaces this one'),\n \n /**\n * Feature flags\n */\n flags: z.object({\n experimental: z.boolean().default(false),\n beta: z.boolean().default(false),\n featured: z.boolean().default(false),\n verified: z.boolean().default(false),\n }).optional(),\n});\n\n/**\n * Plugin Search Filters\n */\nexport const PluginSearchFiltersSchema = z.object({\n /**\n * Search query\n */\n query: z.string().optional(),\n \n /**\n * Filter by category\n */\n category: z.array(z.string()).optional(),\n \n /**\n * Filter by tags\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Filter by vendor trust level\n */\n trustLevel: z.array(z.enum(['official', 'verified', 'community', 'unverified'])).optional(),\n \n /**\n * Filter by protocols implemented\n */\n implementsProtocols: z.array(z.string()).optional(),\n \n /**\n * Filter by pricing model\n */\n pricingModel: z.array(z.enum(['free', 'freemium', 'paid', 'enterprise'])).optional(),\n \n /**\n * Minimum rating\n */\n minRating: z.number().min(0).max(5).optional(),\n \n /**\n * Sort options\n */\n sortBy: z.enum([\n 'relevance',\n 'downloads',\n 'rating',\n 'updated',\n 'name',\n ]).optional(),\n \n /**\n * Sort order\n */\n sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),\n \n /**\n * Pagination\n */\n page: z.number().int().min(1).default(1).optional(),\n limit: z.number().int().min(1).max(100).default(20).optional(),\n});\n\n/**\n * Plugin Installation Configuration\n */\nexport const PluginInstallConfigSchema = z.object({\n /**\n * Plugin identifier to install\n */\n pluginId: z.string(),\n \n /**\n * Version to install (supports semver ranges)\n */\n version: z.string().optional().describe('Defaults to latest'),\n \n /**\n * Plugin-specific configuration values\n */\n config: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Whether to auto-update\n */\n autoUpdate: z.boolean().default(false).optional(),\n \n /**\n * Installation options\n */\n options: z.object({\n /**\n * Skip dependency installation\n */\n skipDependencies: z.boolean().default(false).optional(),\n \n /**\n * Force reinstall\n */\n force: z.boolean().default(false).optional(),\n \n /**\n * Installation target\n */\n target: z.enum(['system', 'space', 'user']).default('space').optional(),\n }).optional(),\n});\n\n// Export types\nexport type PluginVendor = z.infer;\nexport type PluginVendorInput = z.input;\nexport type PluginQualityMetrics = z.infer;\nexport type PluginQualityMetricsInput = z.input;\nexport type PluginStatistics = z.infer;\nexport type PluginStatisticsInput = z.input;\nexport type PluginRegistryEntry = z.infer;\nexport type PluginRegistryEntryInput = z.input;\nexport type PluginSearchFilters = z.infer;\nexport type PluginSearchFiltersInput = z.input;\nexport type PluginInstallConfig = z.infer;\nexport type PluginInstallConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Security & Dependency Resolution Protocol\n * \n * Provides comprehensive security scanning, vulnerability management,\n * and dependency resolution for the ObjectStack plugin ecosystem.\n * \n * Features:\n * - CVE/vulnerability scanning\n * - Dependency graph resolution\n * - Semantic version conflict detection\n * - Supply chain security\n * - Plugin sandboxing policies\n * - Trust and verification workflows\n */\n\n// ============================================================================\n// Security Scanning\n// ============================================================================\n\n/**\n * Vulnerability Severity\n */\nexport const VulnerabilitySeverity = z.enum([\n 'critical',\n 'high',\n 'medium',\n 'low',\n 'info',\n]).describe('Severity level of a security vulnerability');\n\nexport type VulnerabilitySeverity = z.infer;\n\n/**\n * Security Vulnerability\n */\nexport const SecurityVulnerabilitySchema = z.object({\n /**\n * CVE identifier (if applicable)\n */\n cve: z.string().regex(/^CVE-\\d{4}-\\d+$/).optional().describe('CVE identifier'),\n \n /**\n * Vulnerability identifier (GHSA, SNYK, etc.)\n */\n id: z.string().describe('Vulnerability ID'),\n \n /**\n * Title\n */\n title: z.string().describe('Short title summarizing the vulnerability'),\n \n /**\n * Description\n */\n description: z.string().describe('Detailed description of the vulnerability'),\n \n /**\n * Severity\n */\n severity: VulnerabilitySeverity.describe('Severity level of this vulnerability'),\n \n /**\n * CVSS score (0-10)\n */\n cvss: z.number().min(0).max(10).optional().describe('CVSS score ranging from 0 to 10'),\n \n /**\n * Affected package\n */\n package: z.object({\n name: z.string().describe('Name of the affected package'),\n version: z.string().describe('Version of the affected package'),\n ecosystem: z.string().optional().describe('Package ecosystem (e.g., npm, pip, maven)'),\n }).describe('Affected package information'),\n \n /**\n * Vulnerable version range\n */\n vulnerableVersions: z.string().describe('Semver range of vulnerable versions'),\n \n /**\n * Patched versions\n */\n patchedVersions: z.string().optional().describe('Semver range of patched versions'),\n \n /**\n * References\n */\n references: z.array(z.object({\n type: z.enum(['advisory', 'article', 'report', 'web']).describe('Type of reference source'),\n url: z.string().url().describe('URL of the reference'),\n })).default([]).describe('External references related to the vulnerability'),\n \n /**\n * CWE (Common Weakness Enumeration)\n */\n cwe: z.array(z.string()).default([]).describe('CWE identifiers associated with this vulnerability'),\n \n /**\n * Published date\n */\n publishedAt: z.string().datetime().optional().describe('ISO 8601 date when the vulnerability was published'),\n \n /**\n * Mitigation advice\n */\n mitigation: z.string().optional().describe('Recommended steps to mitigate the vulnerability'),\n}).describe('A known security vulnerability in a package dependency');\n\nexport type SecurityVulnerability = z.infer;\n\n/**\n * Security Scan Result\n */\nexport const SecurityScanResultSchema = z.object({\n /**\n * Scan identifier\n */\n scanId: z.string().uuid().describe('Unique identifier for this security scan'),\n \n /**\n * Plugin being scanned\n */\n plugin: z.object({\n id: z.string().describe('Plugin identifier'),\n version: z.string().describe('Plugin version that was scanned'),\n }).describe('Plugin that was scanned'),\n \n /**\n * Scan timestamp\n */\n scannedAt: z.string().datetime().describe('ISO 8601 timestamp when the scan was performed'),\n \n /**\n * Scanner information\n */\n scanner: z.object({\n name: z.string().describe('Scanner name (e.g., snyk, osv, trivy)'),\n version: z.string().describe('Version of the scanner tool'),\n }).describe('Information about the scanner tool used'),\n \n /**\n * Scan status\n */\n status: z.enum(['passed', 'failed', 'warning']).describe('Overall result status of the security scan'),\n \n /**\n * Vulnerabilities found\n */\n vulnerabilities: z.array(SecurityVulnerabilitySchema).describe('List of vulnerabilities discovered during the scan'),\n \n /**\n * Vulnerability summary\n */\n summary: z.object({\n critical: z.number().int().min(0).default(0).describe('Count of critical severity vulnerabilities'),\n high: z.number().int().min(0).default(0).describe('Count of high severity vulnerabilities'),\n medium: z.number().int().min(0).default(0).describe('Count of medium severity vulnerabilities'),\n low: z.number().int().min(0).default(0).describe('Count of low severity vulnerabilities'),\n info: z.number().int().min(0).default(0).describe('Count of informational severity vulnerabilities'),\n total: z.number().int().min(0).default(0).describe('Total count of all vulnerabilities'),\n }).describe('Summary counts of vulnerabilities by severity'),\n \n /**\n * License compliance issues\n */\n licenseIssues: z.array(z.object({\n package: z.string().describe('Name of the package with a license issue'),\n license: z.string().describe('License identifier of the package'),\n reason: z.string().describe('Reason the license is flagged'),\n severity: z.enum(['error', 'warning', 'info']).describe('Severity of the license compliance issue'),\n })).default([]).describe('License compliance issues found during the scan'),\n \n /**\n * Code quality issues\n */\n codeQuality: z.object({\n score: z.number().min(0).max(100).optional().describe('Overall code quality score from 0 to 100'),\n issues: z.array(z.object({\n type: z.enum(['security', 'quality', 'style']).describe('Category of the code quality issue'),\n severity: z.enum(['error', 'warning', 'info']).describe('Severity of the code quality issue'),\n message: z.string().describe('Description of the code quality issue'),\n file: z.string().optional().describe('File path where the issue was found'),\n line: z.number().int().optional().describe('Line number where the issue was found'),\n })).default([]).describe('List of individual code quality issues'),\n }).optional().describe('Code quality analysis results'),\n \n /**\n * Next scan scheduled\n */\n nextScanAt: z.string().datetime().optional().describe('ISO 8601 timestamp for the next scheduled scan'),\n}).describe('Result of a security scan performed on a plugin');\n\nexport type SecurityScanResult = z.infer;\n\n/**\n * Security Policy\n */\nexport const SecurityPolicySchema = z.object({\n /**\n * Policy identifier\n */\n id: z.string().describe('Unique identifier for the security policy'),\n \n /**\n * Policy name\n */\n name: z.string().describe('Human-readable name of the security policy'),\n \n /**\n * Automatic scanning\n */\n autoScan: z.object({\n enabled: z.boolean().default(true).describe('Whether automatic scanning is enabled'),\n frequency: z.enum(['on-publish', 'daily', 'weekly', 'monthly']).default('daily').describe('How often automatic scans are performed'),\n }).describe('Automatic security scanning configuration'),\n \n /**\n * Vulnerability thresholds\n */\n thresholds: z.object({\n /**\n * Block plugin if critical vulnerabilities exceed this\n */\n maxCritical: z.number().int().min(0).default(0).describe('Maximum allowed critical vulnerabilities before blocking'),\n \n /**\n * Block plugin if high vulnerabilities exceed this\n */\n maxHigh: z.number().int().min(0).default(0).describe('Maximum allowed high vulnerabilities before blocking'),\n \n /**\n * Warn if medium vulnerabilities exceed this\n */\n maxMedium: z.number().int().min(0).default(5).describe('Maximum allowed medium vulnerabilities before warning'),\n }).describe('Vulnerability count thresholds for policy enforcement'),\n \n /**\n * Allowed licenses\n */\n allowedLicenses: z.array(z.string()).default([\n 'MIT',\n 'Apache-2.0',\n 'BSD-3-Clause',\n 'BSD-2-Clause',\n 'ISC',\n ]).describe('List of SPDX license identifiers that are permitted'),\n \n /**\n * Prohibited licenses\n */\n prohibitedLicenses: z.array(z.string()).default([\n 'GPL-3.0',\n 'AGPL-3.0',\n ]).describe('List of SPDX license identifiers that are prohibited'),\n \n /**\n * Code signing requirements\n */\n codeSigning: z.object({\n required: z.boolean().default(false).describe('Whether code signing is required for plugins'),\n allowedSigners: z.array(z.string()).default([]).describe('List of trusted signer identities'),\n }).optional().describe('Code signing requirements for plugin artifacts'),\n \n /**\n * Sandbox restrictions\n */\n sandbox: z.object({\n /**\n * Restrict network access\n */\n networkAccess: z.enum(['none', 'localhost', 'allowlist', 'all']).default('all').describe('Level of network access granted to the plugin'),\n \n /**\n * Allowed network destinations (if allowlist)\n */\n allowedDestinations: z.array(z.string()).default([]).describe('Permitted network destinations when using allowlist mode'),\n \n /**\n * File system access\n */\n filesystemAccess: z.enum(['none', 'read-only', 'temp-only', 'full']).default('full').describe('Level of file system access granted to the plugin'),\n \n /**\n * Maximum memory (MB)\n */\n maxMemoryMB: z.number().int().positive().optional().describe('Maximum memory allocation in megabytes'),\n \n /**\n * Maximum CPU time (seconds)\n */\n maxCPUSeconds: z.number().int().positive().optional().describe('Maximum CPU time allowed in seconds'),\n }).optional().describe('Sandbox restrictions for plugin execution'),\n}).describe('Security policy governing plugin scanning and enforcement');\n\nexport type SecurityPolicy = z.infer;\n\n// ============================================================================\n// Dependency Resolution\n// ============================================================================\n\n/**\n * Package Dependency\n */\nexport const PackageDependencySchema = z.object({\n /**\n * Package name/ID\n */\n name: z.string().describe('Package name or identifier'),\n \n /**\n * Version constraint (semver range)\n */\n versionConstraint: z.string().describe('Semver range (e.g., `^1.0.0`, `>=2.0.0 <3.0.0`)'),\n \n /**\n * Dependency type\n */\n type: z.enum(['required', 'optional', 'peer', 'dev']).default('required').describe('Category of the dependency relationship'),\n \n /**\n * Resolved version (filled during resolution)\n */\n resolvedVersion: z.string().optional().describe('Concrete version resolved during dependency resolution'),\n}).describe('A package dependency with its version constraint');\n\nexport type PackageDependency = z.infer;\n\n/**\n * Dependency Graph Node\n */\nexport const DependencyGraphNodeSchema = z.object({\n /**\n * Package identifier\n */\n id: z.string().describe('Unique identifier of the package'),\n \n /**\n * Package version\n */\n version: z.string().describe('Resolved version of the package'),\n \n /**\n * Dependencies of this package\n */\n dependencies: z.array(PackageDependencySchema).default([]).describe('Dependencies required by this package'),\n \n /**\n * Depth in dependency tree\n */\n depth: z.number().int().min(0).describe('Depth level in the dependency tree (0 = root)'),\n \n /**\n * Whether this is a direct dependency\n */\n isDirect: z.boolean().describe('Whether this is a direct (top-level) dependency'),\n \n /**\n * Package metadata\n */\n metadata: z.object({\n name: z.string().describe('Display name of the package'),\n description: z.string().optional().describe('Short description of the package'),\n license: z.string().optional().describe('SPDX license identifier of the package'),\n homepage: z.string().url().optional().describe('Homepage URL of the package'),\n }).optional().describe('Additional metadata about the package'),\n}).describe('A node in the dependency graph representing a resolved package');\n\nexport type DependencyGraphNode = z.infer;\n\n/**\n * Dependency Graph\n */\nexport const DependencyGraphSchema = z.object({\n /**\n * Root package\n */\n root: z.object({\n id: z.string().describe('Identifier of the root package'),\n version: z.string().describe('Version of the root package'),\n }).describe('Root package of the dependency graph'),\n \n /**\n * All nodes in the graph\n */\n nodes: z.array(DependencyGraphNodeSchema).describe('All resolved package nodes in the dependency graph'),\n \n /**\n * Edges (dependency relationships)\n */\n edges: z.array(z.object({\n from: z.string().describe('Package ID'),\n to: z.string().describe('Package ID'),\n constraint: z.string().describe('Version constraint'),\n })).describe('Directed edges representing dependency relationships'),\n \n /**\n * Resolution statistics\n */\n stats: z.object({\n totalDependencies: z.number().int().min(0).describe('Total number of resolved dependencies'),\n directDependencies: z.number().int().min(0).describe('Number of direct (top-level) dependencies'),\n maxDepth: z.number().int().min(0).describe('Maximum depth of the dependency tree'),\n }).describe('Summary statistics for the dependency graph'),\n}).describe('Complete dependency graph for a package and its transitive dependencies');\n\nexport type DependencyGraph = z.infer;\n\n/**\n * Dependency Conflict\n * \n * Hub-level dependency conflict detected during plugin resolution.\n * Focuses on package version conflicts across the marketplace/registry.\n * \n * @see kernel/plugin-versioning.zod.ts DependencyConflictSchema for kernel-level plugin conflicts\n * which models plugin-to-plugin conflicts with richer resolution strategies.\n */\nexport const PackageDependencyConflictSchema = z.object({\n /**\n * Package with conflict\n */\n package: z.string().describe('Name of the package with conflicting version requirements'),\n \n /**\n * Conflicting versions\n */\n conflicts: z.array(z.object({\n version: z.string().describe('Conflicting version of the package'),\n requestedBy: z.array(z.string()).describe('Packages that require this version'),\n constraint: z.string().describe('Semver constraint that produced this version requirement'),\n })).describe('List of conflicting version requirements'),\n \n /**\n * Suggested resolution\n */\n resolution: z.object({\n strategy: z.enum(['pick-highest', 'pick-lowest', 'manual']).describe('Strategy used to resolve the conflict'),\n version: z.string().optional().describe('Resolved version selected by the strategy'),\n reason: z.string().optional().describe('Explanation of why this resolution was chosen'),\n }).optional().describe('Suggested resolution for the conflict'),\n \n /**\n * Severity\n */\n severity: z.enum(['error', 'warning', 'info']).describe('Severity level of the dependency conflict'),\n}).describe('A detected conflict between dependency version requirements');\n\nexport type PackageDependencyConflict = z.infer;\n\n/**\n * Dependency Resolution Result\n */\nexport const PackageDependencyResolutionResultSchema = z.object({\n /**\n * Resolution status\n */\n status: z.enum(['success', 'conflict', 'error']).describe('Overall status of the dependency resolution'),\n \n /**\n * Resolved dependency graph\n */\n graph: DependencyGraphSchema.optional().describe('Resolved dependency graph if resolution succeeded'),\n \n /**\n * Conflicts detected\n */\n conflicts: z.array(PackageDependencyConflictSchema).default([]).describe('List of dependency conflicts detected during resolution'),\n \n /**\n * Errors encountered\n */\n errors: z.array(z.object({\n package: z.string().describe('Name of the package that caused the error'),\n error: z.string().describe('Error message describing what went wrong'),\n })).default([]).describe('Errors encountered during dependency resolution'),\n \n /**\n * Installation order (topological sort)\n */\n installOrder: z.array(z.string()).default([]).describe('Topologically sorted list of package IDs for installation'),\n \n /**\n * Resolution time (ms)\n */\n resolvedIn: z.number().int().min(0).optional().describe('Time taken to resolve dependencies in milliseconds'),\n}).describe('Result of a dependency resolution process');\n\nexport type PackageDependencyResolutionResult = z.infer;\n\n// ============================================================================\n// Supply Chain Security\n// ============================================================================\n\n/**\n * SBOM (Software Bill of Materials) Entry\n */\nexport const SBOMEntrySchema = z.object({\n /**\n * Component name\n */\n name: z.string().describe('Name of the software component'),\n \n /**\n * Component version\n */\n version: z.string().describe('Version of the software component'),\n \n /**\n * Package URL (purl)\n */\n purl: z.string().optional().describe('Package URL identifier'),\n \n /**\n * License\n */\n license: z.string().optional().describe('SPDX license identifier of the component'),\n \n /**\n * Hashes\n */\n hashes: z.object({\n sha256: z.string().optional().describe('SHA-256 hash of the component artifact'),\n sha512: z.string().optional().describe('SHA-512 hash of the component artifact'),\n }).optional().describe('Cryptographic hashes for integrity verification'),\n \n /**\n * Supplier\n */\n supplier: z.object({\n name: z.string().describe('Name of the component supplier'),\n url: z.string().url().optional().describe('URL of the component supplier'),\n }).optional().describe('Supplier information for the component'),\n \n /**\n * External references\n */\n externalRefs: z.array(z.object({\n type: z.enum(['website', 'repository', 'documentation', 'issue-tracker']).describe('Type of external reference'),\n url: z.string().url().describe('URL of the external reference'),\n })).default([]).describe('External references related to the component'),\n}).describe('A single entry in a Software Bill of Materials');\n\nexport type SBOMEntry = z.infer;\n\n/**\n * Software Bill of Materials (SBOM)\n */\nexport const SBOMSchema = z.object({\n /**\n * SBOM format\n */\n format: z.enum(['spdx', 'cyclonedx']).default('cyclonedx').describe('SBOM standard format used'),\n \n /**\n * SBOM version\n */\n version: z.string().describe('Version of the SBOM specification'),\n \n /**\n * Plugin metadata\n */\n plugin: z.object({\n id: z.string().describe('Plugin identifier'),\n version: z.string().describe('Plugin version'),\n name: z.string().describe('Human-readable plugin name'),\n }).describe('Metadata about the plugin this SBOM describes'),\n \n /**\n * Components (dependencies)\n */\n components: z.array(SBOMEntrySchema).describe('List of software components included in the plugin'),\n \n /**\n * Generation timestamp\n */\n generatedAt: z.string().datetime().describe('ISO 8601 timestamp when the SBOM was generated'),\n \n /**\n * Generator tool\n */\n generator: z.object({\n name: z.string().describe('Name of the SBOM generator tool'),\n version: z.string().describe('Version of the SBOM generator tool'),\n }).optional().describe('Tool used to generate this SBOM'),\n}).describe('Software Bill of Materials for a plugin');\n\nexport type SBOM = z.infer;\n\n/**\n * Plugin Provenance\n * Verifiable chain of custody for plugin artifacts\n */\nexport const PluginProvenanceSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string().describe('Unique identifier of the plugin'),\n \n /**\n * Plugin version\n */\n version: z.string().describe('Version of the plugin artifact'),\n \n /**\n * Build information\n */\n build: z.object({\n /**\n * Build timestamp\n */\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the build was produced'),\n \n /**\n * Build environment\n */\n environment: z.object({\n os: z.string().describe('Operating system used for the build'),\n arch: z.string().describe('CPU architecture used for the build'),\n nodeVersion: z.string().describe('Node.js version used for the build'),\n }).optional().describe('Environment details where the build was executed'),\n \n /**\n * Source repository\n */\n source: z.object({\n repository: z.string().url().describe('URL of the source repository'),\n commit: z.string().regex(/^[a-f0-9]{40}$/).describe('Full SHA-1 commit hash of the source'),\n branch: z.string().optional().describe('Branch name the build was produced from'),\n tag: z.string().optional().describe('Git tag associated with the build'),\n }).optional().describe('Source repository information for the build'),\n \n /**\n * Builder identity\n */\n builder: z.object({\n name: z.string().describe('Name of the person or system that produced the build'),\n email: z.string().email().optional().describe('Email address of the builder'),\n }).optional().describe('Identity of the builder who produced the artifact'),\n }).describe('Build provenance information'),\n \n /**\n * Artifact hashes\n */\n artifacts: z.array(z.object({\n filename: z.string().describe('Name of the artifact file'),\n sha256: z.string().describe('SHA-256 hash of the artifact'),\n size: z.number().int().positive().describe('Size of the artifact in bytes'),\n })).describe('List of build artifacts with integrity hashes'),\n \n /**\n * Signatures\n */\n signatures: z.array(z.object({\n algorithm: z.enum(['rsa', 'ecdsa', 'ed25519']).describe('Cryptographic algorithm used for signing'),\n publicKey: z.string().describe('Public key used to verify the signature'),\n signature: z.string().describe('Digital signature value'),\n signedBy: z.string().describe('Identity of the signer'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the signature was created'),\n })).default([]).describe('Cryptographic signatures for the plugin artifact'),\n \n /**\n * Attestations\n */\n attestations: z.array(z.object({\n type: z.enum(['code-review', 'security-scan', 'test-results', 'ci-build']).describe('Type of attestation'),\n status: z.enum(['passed', 'failed']).describe('Result status of the attestation'),\n url: z.string().url().optional().describe('URL with details about the attestation'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the attestation was issued'),\n })).default([]).describe('Verification attestations for the plugin'),\n}).describe('Verifiable provenance and chain of custody for a plugin artifact');\n\nexport type PluginProvenance = z.infer;\n\n// ============================================================================\n// Trust & Verification\n// ============================================================================\n\n/**\n * Plugin Trust Score\n */\nexport const PluginTrustScoreSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string().describe('Unique identifier of the plugin'),\n \n /**\n * Overall trust score (0-100)\n */\n score: z.number().min(0).max(100).describe('Overall trust score from 0 to 100'),\n \n /**\n * Score components\n */\n components: z.object({\n /**\n * Vendor reputation (0-100)\n */\n vendorReputation: z.number().min(0).max(100).describe('Vendor reputation score from 0 to 100'),\n \n /**\n * Security scan results (0-100)\n */\n securityScore: z.number().min(0).max(100).describe('Security scan results score from 0 to 100'),\n \n /**\n * Code quality (0-100)\n */\n codeQuality: z.number().min(0).max(100).describe('Code quality score from 0 to 100'),\n \n /**\n * Community engagement (0-100)\n */\n communityScore: z.number().min(0).max(100).describe('Community engagement score from 0 to 100'),\n \n /**\n * Update frequency (0-100)\n */\n maintenanceScore: z.number().min(0).max(100).describe('Maintenance and update frequency score from 0 to 100'),\n }).describe('Individual score components contributing to the overall trust score'),\n \n /**\n * Trust level\n */\n level: z.enum(['verified', 'trusted', 'neutral', 'untrusted', 'blocked']).describe('Computed trust level based on the overall score'),\n \n /**\n * Verification badges\n */\n badges: z.array(z.enum([\n 'official', // Official ObjectStack plugin\n 'verified-vendor', // Verified vendor\n 'security-scanned', // Passed security scan\n 'code-signed', // Digitally signed\n 'open-source', // Open source\n 'popular', // High downloads\n ])).default([]).describe('Verification badges earned by the plugin'),\n \n /**\n * Last updated\n */\n updatedAt: z.string().datetime().describe('ISO 8601 timestamp when the trust score was last updated'),\n}).describe('Trust score and verification status for a plugin');\n\nexport type PluginTrustScore = z.infer;\n\n// ============================================================================\n// Export All\n// ============================================================================\n\nexport const PluginSecurityProtocol = {\n VulnerabilitySeverity,\n SecurityVulnerability: SecurityVulnerabilitySchema,\n SecurityScanResult: SecurityScanResultSchema,\n SecurityPolicy: SecurityPolicySchema,\n PackageDependency: PackageDependencySchema,\n DependencyGraphNode: DependencyGraphNodeSchema,\n DependencyGraph: DependencyGraphSchema,\n DependencyConflict: PackageDependencyConflictSchema,\n DependencyResolutionResult: PackageDependencyResolutionResultSchema,\n SBOMEntry: SBOMEntrySchema,\n SBOM: SBOMSchema,\n PluginProvenance: PluginProvenanceSchema,\n PluginTrustScore: PluginTrustScoreSchema,\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Execution Context Schema\n * \n * Defines the runtime context that flows from HTTP request → data operations.\n * This is the \"identity + environment\" envelope that every data operation can carry.\n * \n * Design:\n * - All fields are optional for backward compatibility\n * - `isSystem` bypasses permission checks (for internal/migration operations)\n * - `transaction` carries the database transaction handle for atomicity\n * - `traceId` enables distributed tracing across microservices\n * \n * Usage:\n * engine.find('account', { context: { userId: '...', tenantId: '...' } })\n */\nexport const ExecutionContextSchema = z.object({\n /** Current user ID (resolved from session) */\n userId: z.string().optional(),\n \n /** Current organization/tenant ID (resolved from session.activeOrganizationId) */\n tenantId: z.string().optional(),\n \n /** User role names (resolved from Member + Role) */\n roles: z.array(z.string()).default([]),\n \n /** Aggregated permission names (resolved from PermissionSet) */\n permissions: z.array(z.string()).default([]),\n \n /** Whether this is a system-level operation (bypasses permission checks) */\n isSystem: z.boolean().default(false),\n \n /** Raw access token (for external API call pass-through) */\n accessToken: z.string().optional(),\n \n /** Database transaction handle */\n transaction: z.unknown().optional(),\n \n /** Request trace ID (for distributed tracing) */\n traceId: z.string().optional(),\n});\n\nexport type ExecutionContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Unified Chart Type Taxonomy\n * \n * Shared by Dashboard and Report widgets.\n * Provides a comprehensive set of chart types for data visualization.\n */\n\n/**\n * Chart Type Enum\n * Categorized by visualization purpose\n */\nexport const ChartTypeSchema = z.enum([\n // Comparison\n 'bar',\n 'horizontal-bar',\n 'column',\n 'grouped-bar',\n 'stacked-bar',\n 'bi-polar-bar',\n \n // Trend\n 'line',\n 'area',\n 'stacked-area',\n 'step-line',\n 'spline',\n \n // Distribution\n 'pie',\n 'donut',\n 'funnel',\n 'pyramid',\n \n // Relationship\n 'scatter',\n 'bubble',\n \n // Composition\n 'treemap',\n 'sunburst',\n 'sankey',\n 'word-cloud',\n \n // Performance\n 'gauge',\n 'solid-gauge',\n 'metric',\n 'kpi',\n 'bullet',\n \n // Geo\n 'choropleth',\n 'bubble-map',\n 'gl-map',\n \n // Advanced\n 'heatmap',\n 'radar',\n 'waterfall',\n 'box-plot',\n 'violin',\n 'candlestick',\n 'stock',\n \n // Tabular\n 'table',\n 'pivot',\n]);\n\nexport type ChartType = z.infer;\n\n/**\n * Chart Axis Schema\n * Definition for X and Y axes\n */\nexport const ChartAxisSchema = z.object({\n /** Data field to map to this axis */\n field: z.string().describe('Data field key'),\n \n /** Axis title */\n title: I18nLabelSchema.optional().describe('Axis display title'),\n\n /** Value formatting (d3-format or similar) */\n format: z.string().optional().describe('Value format string (e.g., \"$0,0.00\")'),\n \n /** Axis scale settings */\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n stepSize: z.number().optional().describe('Step size for ticks'),\n \n /** Appearance */\n showGridLines: z.boolean().default(true),\n position: z.enum(['left', 'right', 'top', 'bottom']).optional().describe('Axis position'),\n \n /** Logarithmic scale */\n logarithmic: z.boolean().default(false),\n});\n\n/**\n * Chart Series Schema\n * Defines a single data series in the chart\n */\nexport const ChartSeriesSchema = z.object({\n /** Field name for values */\n name: z.string().describe('Field name or series identifier'),\n \n /** Display label */\n label: I18nLabelSchema.optional().describe('Series display label'),\n \n /** Series type override (combo charts) */\n type: ChartTypeSchema.optional().describe('Override chart type for this series'),\n \n /** Specific color */\n color: z.string().optional().describe('Series color (hex/rgb/token)'),\n \n /** Stacking group */\n stack: z.string().optional().describe('Stack identifier to group series'),\n \n /** Axis binding */\n yAxis: z.enum(['left', 'right']).default('left').describe('Bind to specific Y-Axis'),\n});\n\n/**\n * Chart Annotation Schema\n * Static lines or regions to highlight data\n */\nexport const ChartAnnotationSchema = z.object({\n type: z.enum(['line', 'region']).default('line'),\n axis: z.enum(['x', 'y']).default('y'),\n value: z.union([z.number(), z.string()]).describe('Start value'),\n endValue: z.union([z.number(), z.string()]).optional().describe('End value for regions'),\n color: z.string().optional(),\n label: I18nLabelSchema.optional(),\n style: z.enum(['solid', 'dashed', 'dotted']).default('dashed'),\n});\n\n/**\n * Chart Interaction Schema\n */\nexport const ChartInteractionSchema = z.object({\n tooltips: z.boolean().default(true),\n zoom: z.boolean().default(false),\n brush: z.boolean().default(false),\n clickAction: z.string().optional().describe('Action ID to trigger on click'),\n});\n\n/**\n * Chart Configuration Base\n * Common configuration for all chart types\n */\nexport const ChartConfigSchema = z.object({\n /** Chart Type */\n type: ChartTypeSchema,\n \n /** Titles */\n title: I18nLabelSchema.optional().describe('Chart title'),\n subtitle: I18nLabelSchema.optional().describe('Chart subtitle'),\n description: I18nLabelSchema.optional().describe('Accessibility description'),\n \n /** Axes Mapping */\n xAxis: ChartAxisSchema.optional().describe('X-Axis configuration'),\n yAxis: z.array(ChartAxisSchema).optional().describe('Y-Axis configuration (support dual axis)'),\n \n /** Series Configuration */\n series: z.array(ChartSeriesSchema).optional().describe('Defined series configuration'),\n \n /** Appearance */\n colors: z.array(z.string()).optional().describe('Color palette'),\n height: z.number().optional().describe('Fixed height in pixels'),\n \n /** Components */\n showLegend: z.boolean().default(true).describe('Display legend'),\n showDataLabels: z.boolean().default(false).describe('Display data labels'),\n \n /** Annotations & Reference Lines */\n annotations: z.array(ChartAnnotationSchema).optional(),\n \n /** Interactions */\n interaction: ChartInteractionSchema.optional(),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport type ChartConfig = z.infer;\nexport type ChartAxis = z.infer;\nexport type ChartSeries = z.infer;\nexport type ChartAnnotation = z.infer;\nexport type ChartInteraction = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Breakpoint Name Enum\n * Matches the breakpoint names defined in theme.zod.ts BreakpointsSchema.\n */\nexport const BreakpointName = z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl']);\n\nexport type BreakpointName = z.infer;\n\n/**\n * Responsive Configuration Schema\n *\n * Provides responsive layout configuration for UI components.\n * Maps breakpoint names to layout behavior (columns, visibility, order).\n *\n * Aligned with theme.zod.ts BreakpointsSchema for a unified responsive system.\n *\n * @example\n * ```typescript\n * const config: ResponsiveConfig = {\n * columns: { xs: 12, sm: 6, lg: 4 },\n * hiddenOn: ['xs'],\n * order: { xs: 2, lg: 1 },\n * };\n * ```\n */\n/**\n * Breakpoint Column Map Schema\n * Maps breakpoint names to grid column counts (1-12).\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointColumnMapSchema = z.object({\n xs: z.number().min(1).max(12).optional(),\n sm: z.number().min(1).max(12).optional(),\n md: z.number().min(1).max(12).optional(),\n lg: z.number().min(1).max(12).optional(),\n xl: z.number().min(1).max(12).optional(),\n '2xl': z.number().min(1).max(12).optional(),\n}).describe('Grid columns per breakpoint (1-12)');\n\n/**\n * Breakpoint Order Map Schema\n * Maps breakpoint names to display order numbers.\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointOrderMapSchema = z.object({\n xs: z.number().optional(),\n sm: z.number().optional(),\n md: z.number().optional(),\n lg: z.number().optional(),\n xl: z.number().optional(),\n '2xl': z.number().optional(),\n}).describe('Display order per breakpoint');\n\nexport const ResponsiveConfigSchema = z.object({\n /** Minimum breakpoint for visibility */\n breakpoint: BreakpointName.optional()\n .describe('Minimum breakpoint for visibility'),\n\n /** Hide on specific breakpoints */\n hiddenOn: z.array(BreakpointName).optional()\n .describe('Hide on these breakpoints'),\n\n /** Grid columns per breakpoint (1-12 column grid) */\n columns: BreakpointColumnMapSchema.optional().describe('Grid columns per breakpoint'),\n\n /** Display order per breakpoint */\n order: BreakpointOrderMapSchema.optional().describe('Display order per breakpoint'),\n}).describe('Responsive layout configuration');\n\nexport type ResponsiveConfig = z.infer;\n\n/**\n * Performance Configuration Schema\n *\n * Defines performance optimization settings for UI components\n * such as lazy loading, virtual scrolling, and caching.\n *\n * @example\n * ```typescript\n * const perf: PerformanceConfig = {\n * lazyLoad: true,\n * virtualScroll: { enabled: true, itemHeight: 40, overscan: 5 },\n * cacheStrategy: 'stale-while-revalidate',\n * prefetch: true,\n * };\n * ```\n */\nexport const PerformanceConfigSchema = z.object({\n /** Enable lazy loading for this component */\n lazyLoad: z.boolean().optional()\n .describe('Enable lazy loading (defer rendering until visible)'),\n\n /** Virtual scrolling configuration for large datasets */\n virtualScroll: z.object({\n enabled: z.boolean().default(false).describe('Enable virtual scrolling'),\n itemHeight: z.number().optional().describe('Fixed item height in pixels (for estimation)'),\n overscan: z.number().optional().describe('Number of extra items to render outside viewport'),\n }).optional().describe('Virtual scrolling configuration'),\n\n /** Client-side caching strategy */\n cacheStrategy: z.enum([\n 'none',\n 'cache-first',\n 'network-first',\n 'stale-while-revalidate',\n ]).optional().describe('Client-side data caching strategy'),\n\n /** Enable data prefetching */\n prefetch: z.boolean().optional()\n .describe('Prefetch data before component is visible'),\n\n /** Maximum number of items to render before pagination */\n pageSize: z.number().optional()\n .describe('Number of items per page for pagination'),\n\n /** Debounce interval for user interactions (ms) */\n debounceMs: z.number().optional()\n .describe('Debounce interval for user interactions in milliseconds'),\n}).describe('Performance optimization configuration');\n\nexport type PerformanceConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module ui/sharing\n *\n * Sharing & Embedding Protocol\n *\n * Defines schemas for public link sharing, embed configuration,\n * domain restrictions, and password protection for apps, pages, and forms.\n */\n\nimport { z } from 'zod';\n\n/**\n * Sharing Config Schema\n * Configuration for public sharing of an app, page, or form.\n * Supports public links, password protection, domain restrictions, and expiration.\n */\nexport const SharingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable public sharing'),\n publicLink: z.string().optional().describe('Generated public share URL'),\n password: z.string().optional().describe('Password required to access shared link'),\n allowedDomains: z.array(z.string()).optional()\n .describe('Restrict access to specific email domains (e.g. [\"example.com\"])'),\n expiresAt: z.string().optional()\n .describe('Expiration date/time in ISO 8601 format'),\n allowAnonymous: z.boolean().optional().default(false)\n .describe('Allow access without authentication'),\n});\n\n/**\n * Embed Config Schema\n * Configuration for iframe embedding of an app, page, or form.\n * Supports origin restrictions, display options, and responsive sizing.\n */\nexport const EmbedConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable iframe embedding'),\n allowedOrigins: z.array(z.string()).optional()\n .describe('Allowed iframe parent origins (e.g. [\"https://example.com\"])'),\n width: z.string().optional().default('100%').describe('Embed width (CSS value)'),\n height: z.string().optional().default('600px').describe('Embed height (CSS value)'),\n showHeader: z.boolean().optional().default(true).describe('Show interface header in embed'),\n showNavigation: z.boolean().optional().default(false).describe('Show navigation in embed'),\n responsive: z.boolean().optional().default(true).describe('Enable responsive resizing'),\n});\n\n// Type Exports\nexport type SharingConfig = z.infer;\nexport type EmbedConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema, EmbedConfigSchema } from './sharing.zod';\n\n/**\n * Base Navigation Item Schema\n * Shared properties for all navigation types.\n * \n * **NAMING CONVENTION:**\n * Navigation item IDs are used in URLs and configuration and must be lowercase snake_case.\n * \n * @example Good IDs\n * - 'menu_accounts'\n * - 'page_dashboard'\n * - 'nav_settings'\n * \n * @example Bad IDs (will be rejected)\n * - 'MenuAccounts' (PascalCase)\n * - 'Page Dashboard' (spaces)\n */\nconst BaseNavItemSchema = z.object({\n /** Unique identifier for the item */\n id: SnakeCaseIdentifierSchema.describe('Unique identifier for this navigation item (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display proper label'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Sort order within the same level (lower numbers appear first) */\n order: z.number().optional().describe('Sort order within the same level (lower = first)'),\n\n /** Badge text or count displayed on the navigation item (e.g. \"3\", \"New\") */\n badge: z.union([z.string(), z.number()]).optional().describe('Badge text or count displayed on the item'),\n\n /** \n * Visibility condition. \n * Formula expression returning boolean. \n * e.g. \"user.is_admin || user.department == 'sales'\"\n */\n visible: z.string().optional().describe('Visibility formula condition'),\n\n /** Permissions required to see/access this navigation item */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this item'),\n});\n\n/**\n * 1. Object Navigation Item\n * Navigates to an object's list view.\n */\nexport const ObjectNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('object'),\n objectName: z.string().describe('Target object name'),\n viewName: z.string().optional().describe('Default list view to open. Defaults to \"all\"'),\n});\n\n/**\n * 2. Dashboard Navigation Item\n * Navigates to a specific dashboard.\n */\nexport const DashboardNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('dashboard'),\n dashboardName: z.string().describe('Target dashboard name'),\n});\n\n/**\n * 3. Page Navigation Item\n * Navigates to a custom UI page/component.\n */\nexport const PageNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('page'),\n pageName: z.string().describe('Target custom page component name'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the page context'),\n});\n\n/**\n * 4. URL Navigation Item\n * Navigates to an external or absolute URL.\n */\nexport const UrlNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('url'),\n url: z.string().describe('Target external URL'),\n target: z.enum(['_self', '_blank']).default('_self').describe('Link target window'),\n});\n\n/**\n * 5. Report Navigation Item\n * Navigates to a specific report.\n */\nexport const ReportNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('report'),\n reportName: z.string().describe('Target report name'),\n});\n\n/**\n * 6. Action Navigation Item\n * Triggers an action (e.g. opening a flow, running a script, or launching a screen action).\n */\nexport const ActionNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('action'),\n actionDef: z.object({\n actionName: z.string().describe('Action machine name to execute'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the action'),\n }).describe('Action definition to execute when clicked'),\n});\n\n/**\n * 7. Group Navigation Item\n * A container for child navigation items (Sub-menu).\n * Does not perform navigation itself.\n */\nexport const GroupNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('group'),\n expanded: z.boolean().default(false).describe('Default expansion state in sidebar'),\n // children property is added in the recursive definition below\n});\n\n/**\n * Recursive Union of all navigation item types.\n * Allows constructing an unlimited-depth navigation tree.\n */\nexport const NavigationItemSchema: z.ZodType = z.lazy(() => \n z.union([\n ObjectNavItemSchema.extend({\n children: z.array(NavigationItemSchema).optional().describe('Child navigation items (e.g. specific views)'),\n }),\n DashboardNavItemSchema,\n PageNavItemSchema,\n UrlNavItemSchema,\n ReportNavItemSchema,\n ActionNavItemSchema,\n GroupNavItemSchema.extend({\n children: z.array(NavigationItemSchema).describe('Child navigation items'),\n })\n ])\n);\n\n/**\n * App Branding Configuration\n * Allows configuring the look and feel of the specific app.\n */\nexport const AppBrandingSchema = z.object({\n primaryColor: z.string().optional().describe('Primary theme color hex code'),\n logo: z.string().optional().describe('Custom logo URL for this app'),\n favicon: z.string().optional().describe('Custom favicon URL for this app'),\n});\n\n/**\n * Navigation Area Schema\n * \n * A logical grouping (zone/section) of navigation items, similar to Salesforce \"App Areas\"\n * or Dynamics 365 \"Site Map Areas\". Each area represents a business domain (e.g. Sales, Service, Settings)\n * and contains its own independent navigation tree.\n * \n * Areas allow large applications to partition navigation by business function while\n * keeping a single AppSchema definition. The runtime may render areas as top-level tabs,\n * sidebar sections, or a switchable navigation context.\n * \n * @example\n * ```ts\n * const salesArea: NavigationArea = {\n * id: 'area_sales',\n * label: 'Sales',\n * icon: 'briefcase',\n * order: 1,\n * navigation: [\n * { id: 'nav_leads', type: 'object', label: 'Leads', objectName: 'lead' },\n * { id: 'nav_opportunities', type: 'object', label: 'Opportunities', objectName: 'opportunity' },\n * ],\n * };\n * ```\n */\nexport const NavigationAreaSchema = z.object({\n /** Unique area identifier */\n id: SnakeCaseIdentifierSchema.describe('Unique area identifier (lowercase snake_case)'),\n\n /** Display label */\n label: I18nLabelSchema.describe('Area display label'),\n\n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Area icon name'),\n\n /** Sort order among areas (lower = first) */\n order: z.number().optional().describe('Sort order among areas (lower = first)'),\n\n /** Area description */\n description: I18nLabelSchema.optional().describe('Area description'),\n\n /** \n * Visibility condition.\n * Formula expression returning boolean.\n */\n visible: z.string().optional().describe('Visibility formula condition for this area'),\n\n /** Permissions required to access this area */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this area'),\n\n /** Navigation items within this area */\n navigation: z.array(NavigationItemSchema).describe('Navigation items within this area'),\n});\n\n/**\n * Schema for Applications (Apps).\n * A logical container for business functionality (e.g., \"Sales CRM\", \"HR Portal\").\n * \n * **NAMING CONVENTION:**\n * App names are used in URLs and routing and must be lowercase snake_case.\n * Prefix with 'app_' is recommended for clarity.\n * \n * @example Good app names\n * - 'app_crm'\n * - 'app_finance'\n * - 'app_portal'\n * - 'sales_app'\n * \n * @example Bad app names (will be rejected)\n * - 'CRM' (uppercase)\n * - 'FinanceApp' (mixed case)\n * - 'Sales App' (spaces)\n */\n/**\n * App Configuration Schema\n * Defines a business application container, including its navigation, branding, and permissions.\n * \n * The App is the top-level navigation shell. The `navigation[]` field holds the complete\n * sidebar tree with unlimited nesting depth via `type: 'group'` items. Pages are referenced\n * by name via `type: 'page'` items and defined independently.\n * \n * @example CRM App with nested navigation tree\n * {\n * name: \"crm\",\n * label: \"Sales CRM\",\n * icon: \"briefcase\",\n * navigation: [\n * { type: \"group\", id: \"grp_sales\", label: \"Sales Cloud\", expanded: true, children: [\n * { type: \"page\", id: \"nav_pipeline\", label: \"Pipeline\", pageName: \"page_pipeline\" },\n * { type: \"page\", id: \"nav_accounts\", label: \"Accounts\", pageName: \"page_accounts\" },\n * ]},\n * { type: \"page\", id: \"nav_settings\", label: \"Settings\", pageName: \"admin_settings\" },\n * ]\n * }\n */\nexport const AppSchema = z.object({\n /** Machine name (id) */\n name: SnakeCaseIdentifierSchema.describe('App unique machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('App display label'),\n\n /** App version */\n version: z.string().optional().describe('App version'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('App description'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('App icon used in the App Launcher'),\n \n /** Branding/Theming Configuration */\n branding: AppBrandingSchema.optional().describe('App-specific branding'),\n \n /** Application status */\n active: z.boolean().optional().default(true).describe('Whether the app is enabled'),\n\n /** Is this the default app for new users? */\n isDefault: z.boolean().optional().default(false).describe('Is default app'),\n \n /** \n * Full Navigation Tree — supports unlimited nesting depth.\n * Pages are referenced by name via `type: 'page'` items.\n * Groups can contain other groups for arbitrary sidebar depth.\n * \n * For simple apps, use `navigation` directly.\n * For enterprise apps with multiple business domains, use `areas` instead.\n */\n navigation: z.array(NavigationItemSchema).optional()\n .describe('Full navigation tree for the app sidebar'),\n\n /**\n * Navigation Areas — partitions navigation by business domain.\n * Each area defines an independent navigation tree (e.g. Sales, Service, Settings).\n * When areas are defined, they take precedence over the top-level `navigation` array.\n * \n * @example\n * ```ts\n * areas: [\n * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] },\n * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] },\n * ]\n * ```\n */\n areas: z.array(NavigationAreaSchema).optional()\n .describe('Navigation areas for partitioning navigation by business domain'),\n \n /** \n * App-level Home Page Override\n * ID of the navigation item to act as the landing page.\n * If not set, usually defaults to the first navigation item.\n */\n homePageId: z.string().optional().describe('ID of the navigation item to serve as landing page'),\n\n /** \n * Access Control\n * List of permissions required to access this app.\n * Modern replacement for role/profile based assignment.\n * Example: [\"app.access.crm\"]\n */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this app'),\n \n /** \n * Package Components (For config file convenience)\n * In a real monorepo these might be auto-discovered, but here we allow explicit registration.\n */\n objects: z.array(z.unknown()).optional().describe('Objects belonging to this app'),\n apis: z.array(z.unknown()).optional().describe('Custom APIs belonging to this app'),\n\n /** Sharing configuration for public access */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration'),\n\n /** Embed configuration for iframe embedding */\n embed: EmbedConfigSchema.optional().describe('Iframe embedding configuration'),\n\n /** Mobile navigation mode */\n mobileNavigation: z.object({\n mode: z.enum(['drawer', 'bottom_nav', 'hamburger']).default('drawer')\n .describe('Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu'),\n bottomNavItems: z.array(z.string()).optional()\n .describe('Navigation item IDs to show in bottom nav (max 5)'),\n }).optional().describe('Mobile-specific navigation configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the application'),\n});\n\n/**\n * App Factory Helper\n */\nexport const App = {\n create: (config: z.input): App => AppSchema.parse(config),\n} as const;\n\n/**\n * Type-safe factory for creating application definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example CRM App with nested navigation tree\n * ```ts\n * const crmApp = defineApp({\n * name: 'crm',\n * label: 'Sales CRM',\n * navigation: [\n * { id: 'grp_sales', type: 'group', label: 'Sales Cloud', expanded: true, children: [\n * { id: 'nav_pipeline', type: 'page', label: 'Pipeline', pageName: 'page_pipeline' },\n * { id: 'nav_accounts', type: 'page', label: 'Accounts', pageName: 'page_accounts' },\n * ]},\n * { id: 'nav_settings', type: 'page', label: 'Settings', pageName: 'admin_settings' },\n * ],\n * });\n * ```\n */\nexport function defineApp(config: z.input): App {\n return AppSchema.parse(config);\n}\n\n// Main Types\nexport type App = z.infer;\nexport type AppInput = z.input;\nexport type AppBranding = z.infer;\nexport type NavigationItem = z.infer;\nexport type NavigationArea = z.infer;\n\n// Discriminated Item Types (Helper exports)\nexport type ObjectNavItem = z.infer;\nexport type DashboardNavItem = z.infer;\nexport type PageNavItem = z.infer;\nexport type UrlNavItem = z.infer;\nexport type ReportNavItem = z.infer;\nexport type ActionNavItem = z.infer;\nexport type GroupNavItem = z.infer & { children: NavigationItem[] };\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema } from './sharing.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * HTTP Method Enum & HTTP Request Schema\n * Migrated to shared/http.zod.ts. Re-exported here for backward compatibility.\n */\nimport { HttpMethodSchema, HttpRequestSchema } from '../shared/http.zod';\nexport { HttpMethodSchema, HttpRequestSchema };\n\n/**\n * View Data Source Configuration\n * Supports three modes:\n * 1. 'object': Standard Protocol - Auto-connects to ObjectStack Metadata and Data APIs\n * 2. 'api': Custom API - Explicitly provided API URLs\n * 3. 'value': Static Data - Hardcoded data array\n */\nexport const ViewDataSchema = z.discriminatedUnion('provider', [\n z.object({\n provider: z.literal('object'),\n object: z.string().describe('Target object name'),\n }),\n z.object({\n provider: z.literal('api'),\n read: HttpRequestSchema.optional().describe('Configuration for fetching data'),\n write: HttpRequestSchema.optional().describe('Configuration for submitting data (for forms/editable tables)'),\n }),\n z.object({\n provider: z.literal('value'),\n items: z.array(z.unknown()).describe('Static data array'),\n }),\n]);\n\n/**\n * View Filter Rule Schema\n * Standardized filter condition used in list views, tabs, and page-level filters.\n * Uses a declarative array-of-objects format: [{ field, operator, value }].\n *\n * @example\n * ```ts\n * filter: [\n * { field: 'status', operator: 'equals', value: 'active' },\n * { field: 'close_date', operator: 'this_quarter' },\n * ]\n * ```\n */\nexport const ViewFilterRuleSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n /** Filter operator */\n operator: z.string().describe('Filter operator (e.g. equals, not_equals, contains, this_quarter)'),\n /** Filter value (optional for unary operators like is_null, this_quarter) */\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Filter value'),\n}).describe('View filter rule');\n\nexport type ViewFilterRule = z.infer;\n\n/**\n * Column Summary Function Schema\n * Aggregation function for column footer (Airtable-style column summaries)\n */\nexport const ColumnSummarySchema = z.enum([\n 'none',\n 'count',\n 'count_empty',\n 'count_filled',\n 'count_unique',\n 'percent_empty',\n 'percent_filled',\n 'sum',\n 'avg',\n 'min',\n 'max',\n]).describe('Aggregation function for column footer summary');\n\n/**\n * List Column Configuration Schema\n * Detailed configuration for individual list view columns\n */\nexport const ListColumnSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n width: z.number().positive().optional().describe('Column width in pixels'),\n align: z.enum(['left', 'center', 'right']).optional().describe('Text alignment'),\n hidden: z.boolean().optional().describe('Hide column by default'),\n sortable: z.boolean().optional().describe('Allow sorting by this column'),\n resizable: z.boolean().optional().describe('Allow resizing this column'),\n wrap: z.boolean().optional().describe('Allow text wrapping'),\n type: z.string().optional().describe('Renderer type override (e.g., \"currency\", \"date\")'),\n\n /** Pinning (Airtable-style frozen columns) */\n pinned: z.enum(['left', 'right']).optional().describe('Pin/freeze column to left or right side'),\n\n /** Column Footer Summary (Airtable-style aggregation) */\n summary: ColumnSummarySchema.optional().describe('Footer aggregation function for this column'),\n\n /** Interaction */\n link: z.boolean().optional().describe('Functions as the primary navigation link (triggers View navigation)'),\n action: z.string().optional().describe('Registered Action ID to execute when clicked'),\n});\n\n/**\n * List View Selection Configuration\n */\nexport const SelectionConfigSchema = z.object({\n type: z.enum(['none', 'single', 'multiple']).default('none').describe('Selection mode'),\n});\n\n/**\n * List View Pagination Configuration\n */\nexport const PaginationConfigSchema = z.object({\n pageSize: z.number().int().positive().default(25).describe('Number of records per page'),\n pageSizeOptions: z.array(z.number().int().positive()).optional().describe('Available page size options'),\n});\n\n/**\n * Row Height / Density Schema (Airtable-style)\n * Controls the visual density of rows in a list view.\n */\nexport const RowHeightSchema = z.enum([\n 'compact', // Minimal padding, single line\n 'short', // Reduced padding\n 'medium', // Default padding\n 'tall', // Extra padding, multi-line preview\n 'extra_tall', // Maximum padding, rich content preview\n]).describe('Row height / density setting for list view');\n\n/**\n * Grouping Field Configuration\n * Defines a single grouping level for record grouping.\n */\nexport const GroupingFieldSchema = z.object({\n field: z.string().describe('Field name to group by'),\n order: z.enum(['asc', 'desc']).default('asc').describe('Group sort order'),\n collapsed: z.boolean().default(false).describe('Collapse groups by default'),\n});\n\n/**\n * Grouping Configuration Schema (Airtable-style)\n * Supports multi-level grouping for grid/gallery views.\n */\nexport const GroupingConfigSchema = z.object({\n fields: z.array(GroupingFieldSchema).min(1).describe('Fields to group by (supports up to 3 levels)'),\n}).describe('Record grouping configuration');\n\n/**\n * Gallery View Configuration (Airtable-style)\n * Configures card layout for gallery/card views.\n */\nexport const GalleryConfigSchema = z.object({\n coverField: z.string().optional().describe('Attachment/image field to display as card cover'),\n coverFit: z.enum(['cover', 'contain']).default('cover').describe('Image fit mode for card cover'),\n cardSize: z.enum(['small', 'medium', 'large']).default('medium').describe('Card size in gallery view'),\n titleField: z.string().optional().describe('Field to display as card title'),\n visibleFields: z.array(z.string()).optional().describe('Fields to display on card body'),\n}).describe('Gallery/card view configuration');\n\n/**\n * Timeline View Configuration (Airtable-style)\n * Configures timeline/chronological views.\n */\nexport const TimelineConfigSchema = z.object({\n startDateField: z.string().describe('Field for timeline item start date'),\n endDateField: z.string().optional().describe('Field for timeline item end date'),\n titleField: z.string().describe('Field to display as timeline item title'),\n groupByField: z.string().optional().describe('Field to group timeline rows'),\n colorField: z.string().optional().describe('Field to determine item color'),\n scale: z.enum(['hour', 'day', 'week', 'month', 'quarter', 'year']).default('week').describe('Default timeline scale'),\n}).describe('Timeline view configuration');\n\n/**\n * View Sharing Configuration (Airtable-style)\n * Defines who can see and modify a view.\n */\nexport const ViewSharingSchema = z.object({\n type: z.enum(['personal', 'collaborative']).default('collaborative').describe('View ownership type'),\n lockedBy: z.string().optional().describe('User who locked the view configuration'),\n}).describe('View sharing and access configuration');\n\n/**\n * Row Color Configuration (Airtable-style)\n * Defines how rows are colored based on field values.\n */\nexport const RowColorConfigSchema = z.object({\n field: z.string().describe('Field to derive color from (typically a select/status field)'),\n colors: z.record(z.string(), z.string()).optional().describe('Map of field value to color (hex/token)'),\n}).describe('Row color configuration based on field values');\n\n/**\n * Visualization Type Schema\n * Whitelist of visualization types the user can switch between.\n * Maps to Airtable's \"Visualizations\" setting in Appearance panel.\n */\nexport const VisualizationTypeSchema = z.enum([\n 'grid',\n 'kanban',\n 'gallery',\n 'calendar',\n 'timeline',\n 'gantt',\n 'map',\n]).describe('Visualization type that users can switch to');\n\n/**\n * User Actions Configuration Schema (Airtable Interface parity)\n * Controls which interactive actions are available to users in the view toolbar.\n * Each boolean toggles the corresponding toolbar element on/off.\n *\n * @see Airtable Interface → \"User actions\" panel\n */\nexport const UserActionsConfigSchema = z.object({\n sort: z.boolean().default(true).describe('Allow users to sort records'),\n search: z.boolean().default(true).describe('Allow users to search records'),\n filter: z.boolean().default(true).describe('Allow users to filter records'),\n rowHeight: z.boolean().default(true).describe('Allow users to toggle row height/density'),\n addRecordForm: z.boolean().default(false).describe('Add records through a form instead of inline'),\n buttons: z.array(z.string()).optional().describe('Custom action button IDs to show in the toolbar'),\n}).describe('User action toggles for the view toolbar');\n\n/**\n * Appearance Configuration Schema (Airtable Interface parity)\n * Controls visual presentation options for the view.\n *\n * @see Airtable Interface → \"Appearance\" panel\n */\nexport const AppearanceConfigSchema = z.object({\n showDescription: z.boolean().default(true).describe('Show the view description text'),\n allowedVisualizations: z.array(VisualizationTypeSchema).optional()\n .describe('Whitelist of visualization types users can switch between (e.g. [\"grid\", \"gallery\", \"kanban\"])'),\n}).describe('Appearance and visualization configuration');\n\n/**\n * View Tab Schema (Airtable Interface parity)\n * Defines a tab in a multi-tab view interface.\n * Each tab references a named list view and can be ordered, pinned, or set as default.\n *\n * @see Airtable Interface → \"Tabs\" panel\n */\nexport const ViewTabSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Tab identifier (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label'),\n icon: z.string().optional().describe('Tab icon name'),\n view: z.string().optional().describe('Referenced list view name from listViews'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Tab-specific filter criteria'),\n order: z.number().int().min(0).optional().describe('Tab display order'),\n pinned: z.boolean().default(false).describe('Pin tab (cannot be removed by users)'),\n isDefault: z.boolean().default(false).describe('Set as the default active tab'),\n visible: z.boolean().default(true).describe('Tab visibility'),\n}).describe('Tab configuration for multi-tab view interface');\n\n/**\n * Add Record Configuration Schema (Airtable Interface parity)\n * Configures the \"Add Record\" entry point for a list view.\n *\n * @see Airtable Interface → \"+ Add record\" button\n */\nexport const AddRecordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Show the add record entry point'),\n position: z.enum(['top', 'bottom', 'both']).default('bottom').describe('Position of the add record button'),\n mode: z.enum(['inline', 'form', 'modal']).default('inline').describe('How to add a new record'),\n formView: z.string().optional().describe('Named form view to use when mode is \"form\" or \"modal\"'),\n}).describe('Add record entry point configuration');\n\n/**\n * Kanban Settings\n */\nexport const KanbanConfigSchema = z.object({\n groupByField: z.string().describe('Field to group columns by (usually status/select)'),\n summarizeField: z.string().optional().describe('Field to sum at top of column (e.g. amount)'),\n columns: z.array(z.string()).describe('Fields to show on cards'),\n});\n\n/**\n * Calendar Settings\n */\nexport const CalendarConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string().optional(),\n titleField: z.string(),\n colorField: z.string().optional(),\n});\n\n/**\n * Gantt Settings\n */\nexport const GanttConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string(),\n titleField: z.string(),\n progressField: z.string().optional(),\n dependenciesField: z.string().optional(),\n});\n\n/**\n * Navigation Mode Enum\n * Defines how to navigate to the detail view from a list item.\n */\nexport const NavigationModeSchema = z.enum([\n 'page', // Navigate to a new route (default)\n 'drawer', // Open details in a side drawer/panel\n 'modal', // Open details in a modal dialog\n 'split', // Show details side-by-side with the list (master-detail)\n 'popover', // Show details in a popover (lightweight)\n 'new_window', // Open in new browser tab/window\n 'none' // No navigation (read-only list)\n]);\n\n/**\n * Navigation Configuration Schema\n */\nexport const NavigationConfigSchema = z.object({\n mode: NavigationModeSchema.default('page'),\n \n /** Target View Config */\n view: z.string().optional().describe('Name of the form view to use for details (e.g. \"summary_view\", \"edit_form\")'),\n \n /** Interaction Triggers */\n preventNavigation: z.boolean().default(false).describe('Disable standard navigation entirely'),\n openNewTab: z.boolean().default(false).describe('Force open in new tab (applies to page mode)'),\n \n /** Dimensions (for modal/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Width of the drawer/modal (e.g. \"600px\", \"50%\")'),\n});\n\n/**\n * List View Schema (Expanded)\n * Defines how a collection of records is displayed to the user.\n * \n * **NAMING CONVENTION:**\n * View names (when provided) are machine identifiers and must be lowercase snake_case.\n * \n * @example Standard Grid\n * {\n * name: \"all_active\",\n * label: \"All Active\",\n * type: \"grid\",\n * columns: [\"name\", \"status\", \"created_at\"],\n * filter: [[\"status\", \"=\", \"active\"]]\n * }\n * \n * @example Kanban Board\n * {\n * type: \"kanban\",\n * columns: [\"name\", \"amount\"],\n * kanban: {\n * groupByField: \"stage\",\n * summarizeField: \"amount\",\n * columns: [\"name\", \"close_date\"]\n * }\n * }\n */\nexport const ListViewSchema = z.object({\n name: SnakeCaseIdentifierSchema.optional().describe('Internal view name (lowercase snake_case)'),\n label: I18nLabelSchema.optional(), // Display label override (supports i18n)\n type: z.enum([\n 'grid', // Standard Data Table\n 'kanban', // Board / Columns\n 'gallery', // Card Deck / Masonry\n 'calendar', // Monthly/Weekly/Daily\n 'timeline', // Chronological Stream (Feed)\n 'gantt', // Project Timeline\n 'map' // Geospatial\n ]).default('grid'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n /** Shared Query Config */\n columns: z.union([\n z.array(z.string()), // Legacy: simple field names\n z.array(ListColumnSchema), // Enhanced: detailed column config\n ]).describe('Fields to display as columns'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Filter criteria (JSON Rules)'),\n sort: z.union([\n z.string(), //Legacy \"field desc\"\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional(),\n \n /** Search & Filter */\n searchableFields: z.array(z.string()).optional().describe('Fields enabled for search'),\n filterableFields: z.array(z.string()).optional().describe('Fields enabled for end-user filtering in the top bar'),\n\n /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */\n quickFilters: z.array(z.object({\n field: z.string().describe('Field name to filter by'),\n label: z.string().optional().describe('Display label for the chip'),\n operator: z.enum(['equals', 'not_equals', 'contains', 'in', 'is_null', 'is_not_null']).default('equals').describe('Filter operator'),\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Preset filter value'),\n })).optional().describe('One-click filter chips for quick record filtering'),\n\n /** Grid Features */\n resizable: z.boolean().optional().describe('Enable column resizing'),\n striped: z.boolean().optional().describe('Striped row styling'),\n bordered: z.boolean().optional().describe('Show borders'),\n\n /** Selection */\n selection: SelectionConfigSchema.optional().describe('Row selection configuration'),\n\n /** Navigation / Interaction */\n navigation: NavigationConfigSchema.optional().describe('Configuration for item click navigation (page, drawer, modal, etc.)'),\n\n /** Pagination */\n pagination: PaginationConfigSchema.optional().describe('Pagination configuration'),\n\n /** Type Specific Config */\n kanban: KanbanConfigSchema.optional(),\n calendar: CalendarConfigSchema.optional(),\n gantt: GanttConfigSchema.optional(),\n gallery: GalleryConfigSchema.optional(),\n timeline: TimelineConfigSchema.optional(),\n\n /** View Metadata (Airtable-style view management) */\n description: I18nLabelSchema.optional().describe('View description for documentation/tooltips'),\n sharing: ViewSharingSchema.optional().describe('View sharing and access configuration'),\n\n /** Row Height / Density (Airtable-style) */\n rowHeight: RowHeightSchema.optional().describe('Row height / density setting'),\n\n /** Record Grouping (Airtable-style) */\n grouping: GroupingConfigSchema.optional().describe('Group records by one or more fields'),\n\n /** Row Color (Airtable-style) */\n rowColor: RowColorConfigSchema.optional().describe('Color rows based on field value'),\n\n /** Field Visibility & Ordering per View (Airtable-style) */\n hiddenFields: z.array(z.string()).optional().describe('Fields to hide in this specific view'),\n fieldOrder: z.array(z.string()).optional().describe('Explicit field display order for this view'),\n\n /** Row & Bulk Actions */\n rowActions: z.array(z.string()).optional().describe('Actions available for individual row items'),\n bulkActions: z.array(z.string()).optional().describe('Actions available when multiple rows are selected'),\n\n /** Performance */\n virtualScroll: z.boolean().optional().describe('Enable virtual scrolling for large datasets'),\n\n /** Conditional Formatting */\n conditionalFormatting: z.array(z.object({\n condition: z.string().describe('Condition expression to evaluate'),\n style: z.record(z.string(), z.string()).describe('CSS styles to apply when condition is true'),\n })).optional().describe('Conditional formatting rules for list rows'),\n\n /** Inline Edit */\n inlineEdit: z.boolean().optional().describe('Allow inline editing of records directly in the list view'),\n\n /** Export */\n exportOptions: z.array(z.enum(['csv', 'xlsx', 'pdf', 'json'])).optional().describe('Available export format options'),\n\n /** User Actions (Airtable Interface parity) */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles for the view toolbar'),\n\n /** Appearance (Airtable Interface parity) */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** Tabs (Airtable Interface parity) */\n tabs: z.array(ViewTabSchema).optional().describe('Tab definitions for multi-tab view interface'),\n\n /** Add Record (Airtable Interface parity) */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record Count Display (Airtable Interface parity) */\n showRecordCount: z.boolean().optional().describe('Show record count at the bottom of the list'),\n\n /** Advanced: Allow Printing (Airtable Interface parity) */\n allowPrinting: z.boolean().optional().describe('Allow users to print the view'),\n\n /** Empty State */\n emptyState: z.object({\n title: I18nLabelSchema.optional(),\n message: I18nLabelSchema.optional(),\n icon: z.string().optional(),\n }).optional().describe('Empty state configuration when no records found'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the list view'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Form Field Configuration Schema\n * Detailed configuration for individual form fields\n */\nexport const FormFieldSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n helpText: I18nLabelSchema.optional().describe('Help/hint text'),\n readonly: z.boolean().optional().describe('Read-only override'),\n required: z.boolean().optional().describe('Required override'),\n hidden: z.boolean().optional().describe('Hidden override'),\n colSpan: z.number().int().min(1).max(4).optional().describe('Column span in grid layout (1-4)'),\n widget: z.string().optional().describe('Custom widget/component name'),\n dependsOn: z.string().optional().describe('Parent field name for cascading'),\n visibleOn: z.string().optional().describe('Visibility condition expression'),\n});\n\n/**\n * Form Layout Section\n */\nexport const FormSectionSchema = z.object({\n label: I18nLabelSchema.optional(),\n collapsible: z.boolean().default(false),\n collapsed: z.boolean().default(false),\n columns: z.enum(['1', '2', '3', '4']).default('2').transform(val => parseInt(val) as 1 | 2 | 3 | 4),\n fields: z.array(z.union([\n z.string(), // Legacy: simple field name\n FormFieldSchema, // Enhanced: detailed field config\n ])),\n});\n\n/**\n * Form View Schema\n * Defines the layout for creating or editing a single record.\n * \n * @example Simple Sectioned Form\n * {\n * type: \"simple\",\n * sections: [\n * {\n * label: \"General Info\",\n * columns: 2,\n * fields: [\"name\", \"status\"]\n * },\n * {\n * label: \"Details\",\n * fields: [\"description\", { field: \"priority\", widget: \"rating\" }]\n * }\n * ]\n * }\n */\nexport const FormViewSchema = z.object({\n type: z.enum([\n 'simple', // Single column or sections\n 'tabbed', // Tabs\n 'wizard', // Step by step\n 'split', // Master-Detail split\n 'drawer', // Side panel\n 'modal' // Dialog\n ]).default('simple'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n sections: z.array(FormSectionSchema).optional(), // For simple layout\n groups: z.array(FormSectionSchema).optional(), // Legacy support -> alias to sections\n\n /** Default Sort for Related Lists (e.g., sort child records by date) */\n defaultSort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n order: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n })).optional().describe('Default sort order for related list views within this form'),\n\n /** Public form sharing configuration */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration for this form'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the form view'),\n});\n\n/**\n * Master View Schema\n * Can define multiple named views.\n */\n/**\n * View Container Schema\n * Aggregates all view definitions for a specific object or context.\n * \n * @example\n * {\n * list: { type: \"grid\", columns: [\"name\"] },\n * form: { type: \"simple\", fields: [\"name\"] },\n * listViews: {\n * \"all\": { label: \"All\", filter: [] },\n * \"my\": { label: \"Mine\", filter: [[\"owner\", \"=\", \"{user_id}\"]] }\n * }\n * }\n */\nexport const ViewSchema = z.object({\n list: ListViewSchema.optional(), // Default list view\n form: FormViewSchema.optional(), // Default form view\n listViews: z.record(z.string(), ListViewSchema).optional().describe('Additional named list views'),\n formViews: z.record(z.string(), FormViewSchema).optional().describe('Additional named form views'),\n});\n\n/**\n * Type-safe factory for creating view definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const taskViews = defineView({\n * list: {\n * type: 'grid',\n * data: { provider: 'object', object: 'task' },\n * columns: ['subject', 'status', 'priority', 'due_date'],\n * },\n * form: {\n * type: 'simple',\n * sections: [{ label: 'Details', fields: [{ field: 'subject' }] }],\n * },\n * });\n * ```\n */\nexport function defineView(config: z.input): View {\n return ViewSchema.parse(config);\n}\n\nexport type View = z.infer;\nexport type ListView = z.infer;\nexport type FormView = z.infer;\nexport type FormSection = z.infer;\nexport type ListColumn = z.infer;\nexport type FormField = z.infer;\nexport type SelectionConfig = z.infer;\nexport type NavigationConfig = z.infer;\nexport type PaginationConfig = z.infer;\nexport type ViewData = z.infer;\nexport type HttpRequest = z.infer;\nexport type HttpMethod = z.infer;\nexport type ColumnSummary = z.infer;\nexport type RowHeight = z.infer;\nexport type GroupingConfig = z.infer;\nexport type GalleryConfig = z.infer;\nexport type TimelineConfig = z.infer;\nexport type ViewSharing = z.infer;\nexport type RowColorConfig = z.infer;\nexport type VisualizationType = z.infer;\nexport type UserActionsConfig = z.infer;\nexport type AppearanceConfig = z.infer;\nexport type ViewTab = z.infer;\nexport type AddRecordConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Query DSL Specification\n * \n * Based on industry best practices from:\n * - Prisma ORM\n * - Strapi CMS\n * - TypeORM\n * - LoopBack Framework\n * \n * Version: 1.0.0\n * Status: Draft\n * \n * Objective: Define a JSON-based, database-agnostic query syntax standard\n * for data filtering interactions between frontend and backend APIs.\n * \n * Design Principles:\n * 1. Declarative: Frontend describes \"what data to get\", not \"how to query\"\n * 2. Database Agnostic: Syntax contains no database-specific directives\n * 3. Type Safe: Structure can be statically inferred by TypeScript\n * 4. Convention over Configuration: Implicit syntax for common queries\n */\n\n/**\n * Field Reference\n * Represents a reference to another field/column instead of a literal value.\n * Used for joins (ON clause) and cross-field comparisons.\n * \n * @example\n * // user.id = order.owner_id\n * { \"$eq\": { \"$field\": \"order.owner_id\" } }\n */\nexport const FieldReferenceSchema = z.object({\n $field: z.string().describe('Field Reference/Column Name')\n});\n\nexport type FieldReference = z.infer;\n\n// ============================================================================\n// 3.1 Comparison Operators\n// ============================================================================\n\n/**\n * Comparison operators for equality and inequality checks.\n * Supported data types: Any\n */\nexport const EqualityOperatorSchema = z.object({\n /** Equal to (default) - SQL: = | MongoDB: $eq */\n $eq: z.any().optional(),\n \n /** Not equal to - SQL: <> or != | MongoDB: $ne */\n $ne: z.any().optional(),\n});\n\n/**\n * Comparison operators for numeric and date comparisons.\n * Supported data types: Number, Date\n */\nexport const ComparisonOperatorSchema = z.object({\n /** Greater than - SQL: > | MongoDB: $gt */\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Greater than or equal to - SQL: >= | MongoDB: $gte */\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than - SQL: < | MongoDB: $lt */\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than or equal to - SQL: <= | MongoDB: $lte */\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n});\n\n// ============================================================================\n// 3.2 Set & Range Operators\n// ============================================================================\n\n/**\n * Set operators for membership checks.\n */\nexport const SetOperatorSchema = z.object({\n /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */\n $in: z.array(z.any()).optional(),\n \n /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */\n $nin: z.array(z.any()).optional(),\n});\n\n/**\n * Range operator for interval checks (closed interval).\n * SQL: BETWEEN ? AND ? | MongoDB: $gte AND $lte\n */\nexport const RangeOperatorSchema = z.object({\n /** Between (inclusive) - takes [min, max] array */\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n});\n\n// ============================================================================\n// 3.3 String-Specific Operators\n// ============================================================================\n\n/**\n * String pattern matching operators.\n * Note: Case sensitivity should be handled at backend level.\n */\nexport const StringOperatorSchema = z.object({\n /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */\n $contains: z.string().optional(),\n \n /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */\n $notContains: z.string().optional(),\n \n /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */\n $startsWith: z.string().optional(),\n \n /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */\n $endsWith: z.string().optional(),\n});\n\n// ============================================================================\n// 3.5 Special Operators\n// ============================================================================\n\n/**\n * Special check operators for null and existence.\n */\nexport const SpecialOperatorSchema = z.object({\n /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */\n $null: z.boolean().optional(),\n \n /** Field exists check (primarily for NoSQL) - MongoDB: $exists */\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// Combined Field Operators\n// ============================================================================\n\n/**\n * All field-level operators combined.\n * These can be applied to individual fields in a filter.\n */\nexport const FieldOperatorsSchema = z.object({\n // Equality\n $eq: z.any().optional(),\n $ne: z.any().optional(),\n \n // Comparison (numeric/date)\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n // Set & Range\n $in: z.array(z.any()).optional(),\n $nin: z.array(z.any()).optional(),\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n \n // String-specific\n $contains: z.string().optional(),\n $notContains: z.string().optional(),\n $startsWith: z.string().optional(),\n $endsWith: z.string().optional(),\n \n // Special\n $null: z.boolean().optional(),\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// 3.4 Logical Operators & Recursive Filter Structure\n// ============================================================================\n\n/**\n * Recursive filter type that supports:\n * 1. Implicit equality: { field: value }\n * 2. Explicit operators: { field: { $op: value } }\n * 3. Logical combinations: { $and: [...], $or: [...], $not: {...} }\n * 4. Nested relations: { relation: { field: value } }\n */\nexport type FilterCondition = {\n [key: string]: \n | any // Implicit equality: key: value\n | z.infer // Explicit operators: key: { $op: value }\n | FilterCondition; // Nested relation: key: { nested: ... }\n} & {\n /** Logical AND - combines all conditions that must be true */\n $and?: FilterCondition[];\n \n /** Logical OR - at least one condition must be true */\n $or?: FilterCondition[];\n \n /** Logical NOT - negates the condition */\n $not?: FilterCondition;\n};\n\n/**\n * Zod schema for recursive filter validation.\n * Uses z.lazy() to handle recursive structure.\n */\nexport const FilterConditionSchema: z.ZodType = z.lazy(() =>\n z.record(z.string(), z.unknown()).and(\n z.object({\n $and: z.array(FilterConditionSchema).optional(),\n $or: z.array(FilterConditionSchema).optional(),\n $not: FilterConditionSchema.optional(),\n })\n )\n);\n\n// ============================================================================\n// Query Filter Wrapper\n// ============================================================================\n\n/**\n * Top-level query filter wrapper.\n * This is typically used as the \"where\" clause in a query.\n * \n * @example\n * ```typescript\n * const filter: QueryFilter = {\n * where: {\n * status: \"active\", // Implicit equality\n * age: { $gte: 18 }, // Explicit operator\n * $or: [ // Logical combination\n * { role: \"admin\" },\n * { email: { $contains: \"@company.com\" } }\n * ],\n * profile: { // Nested relation\n * verified: true\n * }\n * }\n * }\n * ```\n */\nexport const QueryFilterSchema = z.object({\n where: FilterConditionSchema.optional(),\n});\n\n// ============================================================================\n// TypeScript Type Exports\n// ============================================================================\n\n/**\n * Type-safe filter operators for use in TypeScript.\n * \n * @example\n * ```typescript\n * type UserFilter = Filter;\n * \n * const filter: UserFilter = {\n * age: { $gte: 18 },\n * email: { $contains: \"@example.com\" }\n * };\n * ```\n */\nexport type Filter = {\n [K in keyof T]?: \n | T[K] // Implicit equality\n | {\n $eq?: T[K];\n $ne?: T[K];\n $gt?: T[K] extends number | Date ? T[K] : never;\n $gte?: T[K] extends number | Date ? T[K] : never;\n $lt?: T[K] extends number | Date ? T[K] : never;\n $lte?: T[K] extends number | Date ? T[K] : never;\n $in?: T[K][];\n $nin?: T[K][];\n $between?: T[K] extends number | Date ? [T[K], T[K]] : never;\n $contains?: T[K] extends string ? string : never;\n $notContains?: T[K] extends string ? string : never;\n $startsWith?: T[K] extends string ? string : never;\n $endsWith?: T[K] extends string ? string : never;\n $null?: boolean;\n $exists?: boolean;\n }\n | (T[K] extends object ? Filter : never); // Nested relation\n} & {\n $and?: Filter[];\n $or?: Filter[];\n $not?: Filter;\n};\n\n/**\n * Scalar types supported by the filter system.\n */\nexport type Scalar = string | number | boolean | Date | null;\n\n// Export inferred types\nexport type FieldOperators = z.infer;\nexport type QueryFilter = z.infer;\n\n// ============================================================================\n// Normalization Utilities (Internal Representation)\n// ============================================================================\n\n/**\n * Normalized filter AST structure.\n * This is the internal representation after converting all syntactic sugar\n * to explicit operators.\n * \n * Stage 1: Normalization Pass\n * Input: { age: 18, role: \"admin\" }\n * Output: { $and: [{ age: { $eq: 18 } }, { role: { $eq: \"admin\" } }] }\n * \n * This simplifies adapter implementation by providing a consistent structure.\n */\nexport const NormalizedFilterSchema: z.ZodType = z.lazy(() => \n z.object({\n $and: z.array(\n z.union([\n // Field condition: { field: { $op: value } }\n z.record(z.string(), FieldOperatorsSchema),\n // Nested logical group\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $or: z.array(\n z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $not: z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ]).optional(),\n })\n);\n\nexport type NormalizedFilter = z.infer;\n\n// ============================================================================\n// AST Array Format Detection & Validation\n// ============================================================================\n\n/**\n * Set of valid AST comparison operators (case-insensitive).\n * Used by `isFilterAST()` to validate AST structure beyond `Array.isArray`.\n */\nexport const VALID_AST_OPERATORS = new Set([\n '=', '==', '!=', '<>', '>', '>=', '<', '<=',\n 'in', 'nin', 'not_in',\n 'contains', 'notcontains', 'not_contains', 'like',\n 'startswith', 'starts_with',\n 'endswith', 'ends_with',\n 'between',\n 'is_null', 'is_not_null',\n]);\n\n/**\n * Detect whether a value is a valid Filter AST array structure.\n *\n * A valid AST is one of:\n * - Comparison node: `[field: string, operator: string, value: unknown]` where operator is a known operator\n * - Logical node: `[\"and\" | \"or\", ...children]` where children are valid AST nodes\n * - Legacy flat array: `[[cond], [cond], ...]` where all elements are sub-arrays (each a valid AST node)\n *\n * This replaces the naïve `Array.isArray(filter)` check, preventing accidental\n * misidentification of arbitrary arrays as filter ASTs.\n *\n * @example\n * isFilterAST([\"status\", \"=\", \"active\"]) // true\n * isFilterAST([\"and\", [\"a\", \"=\", 1], [\"b\", \">\", 2]]) // true\n * isFilterAST([[\"a\", \"=\", 1], [\"b\", \"=\", 2]]) // true (legacy)\n * isFilterAST([1, 2, 3]) // false\n * isFilterAST(\"not an array\") // false\n * isFilterAST({ status: \"active\" }) // false\n */\nexport function isFilterAST(filter: unknown): boolean {\n if (!Array.isArray(filter) || filter.length === 0) return false;\n\n const first = filter[0];\n\n // Logical node: [\"and\", ...] or [\"or\", ...]\n if (typeof first === 'string') {\n const lower = first.toLowerCase();\n if (lower === 'and' || lower === 'or') {\n return filter.length >= 2 && filter.slice(1).every((child: unknown) => isFilterAST(child));\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof filter[1] === 'string') {\n return VALID_AST_OPERATORS.has(filter[1].toLowerCase());\n }\n }\n\n // Legacy flat array: [[cond], [cond], ...]\n if (filter.every((item: unknown) => isFilterAST(item))) {\n return filter.length > 0;\n }\n\n return false;\n}\n\n// ============================================================================\n// AST Array → FilterCondition Conversion\n// ============================================================================\n\n/**\n * Operator mapping from AST infix operators to FilterCondition `$`-prefixed operators.\n */\nconst AST_OPERATOR_MAP: Record = {\n '=': '$eq',\n '==': '$eq',\n '!=': '$ne',\n '<>': '$ne',\n '>': '$gt',\n '>=': '$gte',\n '<': '$lt',\n '<=': '$lte',\n 'in': '$in',\n 'nin': '$nin',\n 'not_in': '$nin',\n 'contains': '$contains',\n 'notcontains': '$notContains',\n 'not_contains': '$notContains',\n 'like': '$contains',\n 'startswith': '$startsWith',\n 'starts_with': '$startsWith',\n 'endswith': '$endsWith',\n 'ends_with': '$endsWith',\n 'between': '$between',\n 'is_null': '$null',\n 'is_not_null': '$null',\n};\n\n/**\n * Convert a single AST comparison node `[field, operator, value]` to a FilterCondition object.\n */\nfunction convertComparison(node: [string, string, unknown]): FilterCondition {\n const [field, operator, value] = node;\n const op = operator.toLowerCase();\n\n // Special case: equality shorthand\n if (op === '=' || op === '==') {\n return { [field]: value } as FilterCondition;\n }\n\n // Null check operators\n if (op === 'is_null') {\n return { [field]: { $null: true } } as FilterCondition;\n }\n if (op === 'is_not_null') {\n return { [field]: { $null: false } } as FilterCondition;\n }\n\n const mapped = AST_OPERATOR_MAP[op];\n if (mapped) {\n return { [field]: { [mapped]: value } } as FilterCondition;\n }\n\n // Fallback: use the operator as-is with $ prefix\n return { [field]: { [`$${op}`]: value } } as FilterCondition;\n}\n\n/**\n * Parse a filter from AST array format to FilterCondition object format.\n *\n * The AST array format is used by the ObjectUI client and the `FilterBuilder`:\n * - Comparison: `[field, operator, value]` → `{ field: value }` or `{ field: { $op: value } }`\n * - Logical AND: `[\"and\", cond1, cond2, ...]` → `{ $and: [...] }`\n * - Logical OR: `[\"or\", cond1, cond2, ...]` → `{ $or: [...] }`\n *\n * If the input is already a FilterCondition object (not an array), it is returned as-is.\n * If the input is `null` or `undefined`, it is returned as-is.\n *\n * @example\n * // Simple condition\n * parseFilterAST([\"status\", \"=\", \"active\"])\n * // → { status: \"active\" }\n *\n * @example\n * // Compound AND\n * parseFilterAST([\"and\", [\"priority\", \"=\", \"high\"], [\"status\", \"=\", \"active\"]])\n * // → { $and: [{ priority: \"high\" }, { status: \"active\" }] }\n *\n * @example\n * // Object passthrough\n * parseFilterAST({ status: \"active\" })\n * // → { status: \"active\" }\n */\nexport function parseFilterAST(filter: unknown): FilterCondition | undefined {\n if (filter == null) return undefined;\n if (!Array.isArray(filter)) return filter as FilterCondition;\n if (filter.length === 0) return undefined;\n\n const first = filter[0];\n\n // Logical node: [\"and\", cond1, cond2, ...] or [\"or\", cond1, cond2, ...]\n if (typeof first === 'string' && (first.toLowerCase() === 'and' || first.toLowerCase() === 'or')) {\n const logicOp = `$${first.toLowerCase()}` as '$and' | '$or';\n const children = filter.slice(1).map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { [logicOp]: children } as FilterCondition;\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof first === 'string') {\n return convertComparison(filter as [string, string, unknown]);\n }\n\n // Legacy flat array: [[field, op, val], [field, op, val], ...]\n // All elements are sub-arrays → treat as implicit AND\n if (filter.every((item: unknown) => Array.isArray(item))) {\n const children = filter.map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { $and: children } as FilterCondition;\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Constants & Metadata\n// ============================================================================\n\n/**\n * All supported operator keys.\n * Useful for validation and parsing.\n */\nexport const FILTER_OPERATORS = [\n // Equality\n '$eq', '$ne',\n // Comparison\n '$gt', '$gte', '$lt', '$lte',\n // Set & Range\n '$in', '$nin', '$between',\n // String\n '$contains', '$notContains', '$startsWith', '$endsWith',\n // Special\n '$null', '$exists',\n] as const;\n\n/**\n * Logical operator keys.\n */\nexport const LOGICAL_OPERATORS = ['$and', '$or', '$not'] as const;\n\n/**\n * All operator keys (field + logical).\n */\nexport const ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS] as const;\n\nexport type FilterOperatorKey = typeof FILTER_OPERATORS[number];\nexport type LogicalOperatorKey = typeof LOGICAL_OPERATORS[number];\nexport type OperatorKey = typeof ALL_OPERATORS[number];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ChartTypeSchema, ChartConfigSchema } from './chart.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Color variant for dashboard widgets (e.g., KPI cards).\n */\nexport const WidgetColorVariantSchema = z.enum([\n 'default',\n 'blue',\n 'teal',\n 'orange',\n 'purple',\n 'success',\n 'warning',\n 'danger',\n]).describe('Widget color variant');\n\n/**\n * Action type for widget action buttons.\n */\nexport const WidgetActionTypeSchema = z.enum([\n 'script',\n 'url',\n 'modal',\n 'flow',\n 'api',\n]).describe('Widget action type');\n\n/**\n * Dashboard Header Action Schema\n * An action button displayed in the dashboard header area.\n */\nexport const DashboardHeaderActionSchema = z.object({\n /** Action label */\n label: I18nLabelSchema.describe('Action button label'),\n\n /** Action URL or target */\n actionUrl: z.string().describe('URL or target for the action'),\n\n /** Action type */\n actionType: WidgetActionTypeSchema.optional().describe('Type of action'),\n\n /** Icon identifier */\n icon: z.string().optional().describe('Icon identifier for the action button'),\n}).describe('Dashboard header action');\n\n/**\n * Dashboard Header Schema\n * Structured header configuration for the dashboard.\n */\nexport const DashboardHeaderSchema = z.object({\n /** Whether to show the dashboard title in the header */\n showTitle: z.boolean().default(true).describe('Show dashboard title in header'),\n\n /** Whether to show the dashboard description in the header */\n showDescription: z.boolean().default(true).describe('Show dashboard description in header'),\n\n /** Action buttons displayed in the header */\n actions: z.array(DashboardHeaderActionSchema).optional().describe('Header action buttons'),\n}).describe('Dashboard header configuration');\n\n/**\n * Widget Measure Schema\n * A single measure definition for multi-measure pivot/matrix widgets.\n */\nexport const WidgetMeasureSchema = z.object({\n /** Value field to aggregate */\n valueField: z.string().describe('Field to aggregate'),\n\n /** Aggregate function */\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max']).default('count').describe('Aggregate function'),\n\n /** Display label for the measure */\n label: I18nLabelSchema.optional().describe('Measure display label'),\n\n /** Number format string (e.g., \"$0,0.00\", \"0.0%\") */\n format: z.string().optional().describe('Number format string'),\n}).describe('Widget measure definition');\n\n/**\n * Dashboard Widget Schema\n * A single component on the dashboard grid.\n */\nexport const DashboardWidgetSchema = z.object({\n /** Unique widget identifier (snake_case, used for targetWidgets references) */\n id: SnakeCaseIdentifierSchema.describe('Unique widget identifier (snake_case)'),\n\n /** Widget Title */\n title: I18nLabelSchema.optional().describe('Widget title'),\n\n /** Widget Description (displayed below the title) */\n description: I18nLabelSchema.optional().describe('Widget description text below the header'),\n \n /** Visualization Type */\n type: ChartTypeSchema.default('metric').describe('Visualization type'),\n \n /** Chart Configuration */\n chartConfig: ChartConfigSchema.optional().describe('Chart visualization configuration'),\n\n /** Color variant for the widget (e.g., KPI card accent color) */\n colorVariant: WidgetColorVariantSchema.optional().describe('Widget color variant for theming'),\n\n /** Action URL for the widget header action button */\n actionUrl: z.string().optional().describe('URL or target for the widget action button'),\n\n /** Action type for the widget header action button */\n actionType: WidgetActionTypeSchema.optional().describe('Type of action for the widget action button'),\n\n /** Icon for the widget header action button */\n actionIcon: z.string().optional().describe('Icon identifier for the widget action button'),\n \n /** Data Source Object */\n object: z.string().optional().describe('Data source object name'),\n \n /** Data Filter (MongoDB-style FilterCondition) */\n filter: FilterConditionSchema.optional().describe('Data filter criteria'),\n \n /** Category Field (X-Axis / Group By) */\n categoryField: z.string().optional().describe('Field for grouping (X-Axis)'),\n \n /** Value Field (Y-Axis) */\n valueField: z.string().optional().describe('Field for values (Y-Axis)'),\n \n /** Aggregate operation */\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max']).optional().default('count').describe('Aggregate function'),\n \n /** Multi-measure definitions for pivot/matrix widgets */\n measures: z.array(WidgetMeasureSchema).optional().describe('Multiple measures for pivot/matrix analysis'),\n \n /** \n * Layout Position (React-Grid-Layout style)\n * x: column (0-11)\n * y: row\n * w: width (1-12)\n * h: height\n */\n layout: z.object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n }).describe('Grid layout position'),\n \n /** Widget specific options (colors, legend, etc.) */\n options: z.unknown().optional().describe('Widget specific configuration'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * Dynamic options binding for global filters.\n * Allows dropdown options to be fetched from an object at runtime.\n */\nexport const GlobalFilterOptionsFromSchema = z.object({\n /** Source object name to fetch options from */\n object: z.string().describe('Source object name'),\n\n /** Field to use as option value */\n valueField: z.string().describe('Field to use as option value'),\n\n /** Field to use as option label */\n labelField: z.string().describe('Field to use as option label'),\n\n /** Optional filter to apply when fetching options */\n filter: FilterConditionSchema.optional().describe('Filter to apply to source object'),\n}).describe('Dynamic filter options from object');\n\n/**\n * Global Filter Schema\n * Defines a single global filter control for the dashboard filter bar.\n */\nexport const GlobalFilterSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n\n /** Display label for the filter */\n label: I18nLabelSchema.optional().describe('Display label for the filter'),\n\n /** Filter input type */\n type: z.enum(['text', 'select', 'date', 'number', 'lookup']).optional().describe('Filter input type'),\n\n /** Static options for select/lookup filters */\n options: z.array(z.object({\n value: z.union([z.string(), z.number(), z.boolean()]).describe('Option value'),\n label: I18nLabelSchema,\n })).optional().describe('Static filter options'),\n\n /** Dynamic data binding for filter options */\n optionsFrom: GlobalFilterOptionsFromSchema.optional().describe('Dynamic filter options from object'),\n\n /** Default filter value */\n defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional().describe('Default filter value'),\n\n /** Filter application scope */\n scope: z.enum(['dashboard', 'widget']).default('dashboard').describe('Filter application scope'),\n\n /** Widget IDs to apply this filter to (when scope is widget) */\n targetWidgets: z.array(z.string()).optional().describe('Widget IDs to apply this filter to'),\n});\n\n/**\n * Dashboard Schema\n * Represents a page containing multiple visualizations.\n * \n * @example Sales Executive Dashboard\n * {\n * name: \"sales_overview\",\n * label: \"Sales Executive Overview\",\n * widgets: [\n * {\n * title: \"Total Pipe\",\n * type: \"metric\",\n * object: \"opportunity\",\n * valueField: \"amount\",\n * aggregate: \"sum\",\n * layout: { x: 0, y: 0, w: 3, h: 2 }\n * },\n * {\n * title: \"Revenue by Region\",\n * type: \"bar\",\n * object: \"order\",\n * categoryField: \"region\",\n * valueField: \"total\",\n * aggregate: \"sum\",\n * layout: { x: 3, y: 0, w: 6, h: 4 }\n * }\n * ]\n * }\n */\nexport const DashboardSchema = z.object({\n /** Machine name */\n name: SnakeCaseIdentifierSchema.describe('Dashboard unique name'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Dashboard label'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('Dashboard description'),\n\n /** Structured header configuration */\n header: DashboardHeaderSchema.optional().describe('Dashboard header configuration'),\n \n /** Collection of widgets */\n widgets: z.array(DashboardWidgetSchema).describe('Widgets to display'),\n\n /** Auto-refresh */\n refreshInterval: z.number().optional().describe('Auto-refresh interval in seconds'),\n\n /** Dashboard Date Range (Global time filter) */\n dateRange: z.object({\n field: z.string().optional().describe('Default date field name for time-based filtering'),\n defaultRange: z.enum(['today', 'yesterday', 'this_week', 'last_week', 'this_month', 'last_month', 'this_quarter', 'last_quarter', 'this_year', 'last_year', 'last_7_days', 'last_30_days', 'last_90_days', 'custom']).default('this_month').describe('Default date range preset'),\n allowCustomRange: z.boolean().default(true).describe('Allow users to pick a custom date range'),\n }).optional().describe('Global dashboard date range filter configuration'),\n\n /** Global Filters */\n globalFilters: z.array(GlobalFilterSchema).optional().describe('Global filters that apply to all widgets in the dashboard'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\nexport type Dashboard = z.infer;\nexport type DashboardInput = z.input;\nexport type DashboardWidget = z.infer;\nexport type DashboardHeader = z.infer;\nexport type DashboardHeaderAction = z.infer;\nexport type WidgetMeasure = z.infer;\nexport type WidgetColorVariant = z.infer;\nexport type WidgetActionType = z.infer;\nexport type GlobalFilter = z.infer;\nexport type GlobalFilterOptionsFrom = z.infer;\n\n/**\n * Dashboard Factory Helper\n */\nexport const Dashboard = {\n create: (config: z.input): Dashboard => DashboardSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ChartConfigSchema } from './chart.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Report Type Enum\n */\nexport const ReportType = z.enum([\n 'tabular', // Simple list\n 'summary', // Grouped by row\n 'matrix', // Grouped by row and column\n 'joined' // Joined multiple blocks\n]);\n\n/**\n * Report Column Schema\n */\nexport const ReportColumnSchema = z.object({\n field: z.string().describe('Field name'),\n label: I18nLabelSchema.optional().describe('Override label'),\n aggregate: z.enum(['sum', 'avg', 'max', 'min', 'count', 'unique']).optional().describe('Aggregation function'),\n /** Responsive visibility/priority per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive visibility for this column'),\n});\n\n/**\n * Report Grouping Schema\n */\nexport const ReportGroupingSchema = z.object({\n field: z.string().describe('Field to group by'),\n sortOrder: z.enum(['asc', 'desc']).default('asc'),\n dateGranularity: z.enum(['day', 'week', 'month', 'quarter', 'year']).optional().describe('For date fields'),\n});\n\n/**\n * Report Chart Schema\n * Embedded visualization configuration using unified chart taxonomy.\n */\nexport const ReportChartSchema = ChartConfigSchema.extend({\n /** Report-specific chart configuration */\n xAxis: z.string().describe('Grouping field for X-Axis'),\n yAxis: z.string().describe('Summary field for Y-Axis'),\n groupBy: z.string().optional().describe('Additional grouping field'),\n});\n\n/**\n * Report Schema\n * Deep data analysis definition.\n */\nexport const ReportSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Report unique name'),\n label: I18nLabelSchema.describe('Report label'),\n description: I18nLabelSchema.optional(),\n \n /** Data Source */\n objectName: z.string().describe('Primary object'),\n \n /** Report Configuration */\n type: ReportType.default('tabular').describe('Report format type'),\n \n columns: z.array(ReportColumnSchema).describe('Columns to display'),\n \n /** Grouping (for Summary/Matrix) */\n groupingsDown: z.array(ReportGroupingSchema).optional().describe('Row groupings'),\n groupingsAcross: z.array(ReportGroupingSchema).optional().describe('Column groupings (Matrix only)'),\n \n /** Filtering (MongoDB-style FilterCondition) */\n filter: FilterConditionSchema.optional().describe('Filter criteria'),\n \n /** Visualization */\n chart: ReportChartSchema.optional().describe('Embedded chart configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Report Types\n * \n * Note: For configuration/definition contexts, use the Input types (e.g., ReportInput)\n * which allow optional fields with defaults to be omitted.\n */\nexport type Report = z.infer;\nexport type ReportColumn = z.infer;\nexport type ReportGrouping = z.infer;\nexport type ReportChart = z.infer;\n\n/**\n * Input Types for Report Configuration\n * Use these when defining reports in configuration files.\n */\nexport type ReportInput = z.input;\nexport type ReportColumnInput = z.input;\nexport type ReportGroupingInput = z.input;\nexport type ReportChartInput = z.input;\n\n/**\n * Report Factory Helper\n */\nexport const Report = {\n create: (config: ReportInput): Report => ReportSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Shared Enumerations\n// ============================================================================\n\n/** Aggregation functions used across query, data-engine, analytics, field */\nexport const AggregationFunctionEnum = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'percentile', 'median', 'stddev', 'variance',\n]).describe('Standard aggregation functions');\nexport type AggregationFunction = z.infer;\n\n/** Sort direction used across query, data-engine, analytics */\nexport const SortDirectionEnum = z.enum(['asc', 'desc'])\n .describe('Sort order direction');\nexport type SortDirection = z.infer;\n\n/** Reusable sort item — field + direction pair used across views, data sources, filters */\nexport const SortItemSchema = z.object({\n field: z.string().describe('Field name to sort by'),\n order: SortDirectionEnum.describe('Sort direction'),\n}).describe('Sort field and direction pair');\nexport type SortItem = z.infer;\n\n/** CRUD mutation events used across hook, validation, object CDC */\nexport const MutationEventEnum = z.enum([\n 'insert', 'update', 'delete', 'upsert',\n]).describe('Data mutation event types');\nexport type MutationEvent = z.infer;\n\n/** Database isolation levels — unified format */\nexport const IsolationLevelEnum = z.enum([\n 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable', 'snapshot',\n]).describe('Transaction isolation levels (snake_case standard)');\nexport type IsolationLevel = z.infer;\n\n/** Cache eviction strategies */\nexport const CacheStrategyEnum = z.enum(['lru', 'lfu', 'ttl', 'fifo'])\n .describe('Cache eviction strategy');\nexport type CacheStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { SortItemSchema } from '../shared/enums.zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema } from './responsive.zod';\nimport {\n UserActionsConfigSchema,\n AppearanceConfigSchema,\n ViewTabSchema,\n ViewFilterRuleSchema,\n AddRecordConfigSchema,\n} from './view.zod';\n\n/**\n * Page Region Schema\n * A named region in the template where components are dropped.\n */\nexport const PageRegionSchema = z.object({\n name: z.string().describe('Region name (e.g. \"sidebar\", \"main\", \"header\")'),\n width: z.enum(['small', 'medium', 'large', 'full']).optional(),\n components: z.array(z.lazy(() => PageComponentSchema)).describe('Components in this region')\n});\n\n/**\n * Standard Page Component Types\n */\nexport const PageComponentType = z.enum([\n // Structure\n 'page:header', 'page:footer', 'page:sidebar', 'page:tabs', 'page:accordion', 'page:card', 'page:section',\n // Record Context\n 'record:details', 'record:highlights', 'record:related_list', 'record:activity', 'record:chatter', 'record:path',\n // Navigation\n 'app:launcher', 'nav:menu', 'nav:breadcrumb',\n // Utility\n 'global:search', 'global:notifications', 'user:profile',\n // AI\n 'ai:chat_window', 'ai:suggestion',\n // Content Elements (Airtable Interface parity)\n 'element:text', 'element:number', 'element:image', 'element:divider',\n // Interactive Elements (Phase B — Element Library)\n 'element:button', 'element:filter', 'element:form', 'element:record_picker'\n]);\n\n/**\n * Element Data Source Schema\n * Per-element data binding for multi-object pages.\n * Overrides page-level object context so each element can query a different object.\n */\nexport const ElementDataSourceSchema = z.object({\n object: z.string().describe('Object to query'),\n view: z.string().optional().describe('Named view to apply'),\n filter: FilterConditionSchema.optional().describe('Additional filter criteria'),\n sort: z.array(SortItemSchema).optional().describe('Sort order'),\n limit: z.number().int().positive().optional().describe('Max records to display'),\n});\n\n/**\n * Page Component Schema\n * A configured instance of a UI component.\n */\nexport const PageComponentSchema = z.object({\n /** Definition */\n type: z.union([\n PageComponentType,\n z.string()\n ]).describe('Component Type (Standard enum or custom string)'),\n id: z.string().optional().describe('Unique instance ID'),\n \n /** Configuration */\n label: I18nLabelSchema.optional(),\n properties: z.record(z.string(), z.unknown()).describe('Component props passed to the widget. See component.zod.ts for schemas.'),\n \n /** \n * Event Handlers \n * Map event names to Action expressions.\n * \"onClick\": \"set_variable('userId', $event.id)\"\n * \"onRowSelect\": \"navigate_to('page_detail', { id: $event.id })\"\n */\n events: z.record(z.string(), z.string()).optional().describe('Event handlers map'),\n\n /** Appearance */\n style: z.record(z.string(), z.string()).optional().describe('Inline styles or utility classes'),\n className: z.string().optional().describe('CSS class names'),\n\n /** Visibility Rule */\n visibility: z.string().optional().describe('Visibility filter/formula'),\n\n /** Per-element data binding, overrides page-level object context */\n dataSource: ElementDataSourceSchema.optional().describe('Per-element data binding for multi-object pages'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * Page Variable Schema\n * Defines local state for the page.\n * Variables can be bound to interactive elements (e.g. element:record_picker, element:filter).\n */\nexport const PageVariableSchema = z.object({\n name: z.string().describe('Variable name'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array', 'record_id']).default('string'),\n defaultValue: z.unknown().optional(),\n /** Source element binding (e.g. element:record_picker writes to this variable) */\n source: z.string().optional().describe('Component ID that writes to this variable'),\n});\n\n/**\n * Blank Page Layout Item Schema\n * Positions a component on a free-form grid canvas.\n */\nexport const BlankPageLayoutItemSchema = z.object({\n componentId: z.string().describe('Reference to a PageComponent.id in the page'),\n x: z.number().int().min(0).describe('Grid column position (0-based)'),\n y: z.number().int().min(0).describe('Grid row position (0-based)'),\n width: z.number().int().min(1).describe('Width in grid columns'),\n height: z.number().int().min(1).describe('Height in grid rows'),\n});\n\n/**\n * Blank Page Layout Schema\n * Free-form canvas composition with grid-based positioning.\n * Used when page type is 'blank' to enable drag-and-drop element placement.\n */\nexport const BlankPageLayoutSchema = z.object({\n columns: z.number().int().min(1).default(12).describe('Number of grid columns'),\n rowHeight: z.number().int().min(1).default(40).describe('Height of each grid row in pixels'),\n gap: z.number().int().min(0).default(8).describe('Gap between grid items in pixels'),\n items: z.array(BlankPageLayoutItemSchema).describe('Positioned components on the canvas'),\n});\n\n/**\n * Page Type Schema\n * Unified page type enum covering both platform pages (Salesforce FlexiPage style)\n * and Airtable-inspired interface page types.\n *\n * **Disambiguation of similar types:**\n * - `record` vs `record_detail`: `record` is a component-based layout page (FlexiPage style with regions),\n * `record_detail` is a field-display page showing all fields of a single record (Airtable style).\n * Use `record` for custom record pages with regions/components, `record_detail` for auto-generated detail views.\n * - `home` vs `overview`: `home` is the platform-level landing page (tab landing),\n * `overview` is an interface-level navigation hub with links/instructions.\n * Use `home` for app-level landing, `overview` for in-interface navigation hubs.\n * - `app` vs `utility` vs `blank`: `app` is an app-level page with navigation context,\n * `utility` is a floating utility panel (e.g. notes, phone), `blank` is a free-form canvas\n * for custom composition. They serve distinct layout purposes.\n */\nexport const PageTypeSchema = z.enum([\n // Platform page types (Salesforce FlexiPage style)\n 'record', // Component-based record layout page with regions\n 'home', // Platform-level home/landing page\n 'app', // App-level page with navigation context\n 'utility', // Floating utility panel (e.g. notes, phone dialer)\n // Interface page types (Airtable Interface parity)\n 'dashboard', // KPI summary with charts/metrics\n 'grid', // Spreadsheet-like data table\n 'list', // Record list with quick actions\n 'gallery', // Card-based visual browsing\n 'kanban', // Status-based board\n 'calendar', // Date-based scheduling\n 'timeline', // Gantt-like project timeline\n 'form', // Data entry form\n 'record_detail', // Auto-generated single record field display\n 'record_review', // Sequential record review/approval\n 'overview', // Interface-level navigation/landing hub\n 'blank', // Free-form canvas for custom composition\n]).describe('Page type — platform or interface page types');\n\n/**\n * Record Review Config Schema\n * Configuration for a sequential record review/approval page.\n * Users navigate through records one-by-one, taking actions (approve/reject/skip).\n * Only applicable when page type is 'record_review'.\n */\nexport const RecordReviewConfigSchema = z.object({\n object: z.string().describe('Target object for review'),\n filter: FilterConditionSchema.optional().describe('Filter criteria for review queue'),\n sort: z.array(SortItemSchema).optional().describe('Sort order for review queue'),\n displayFields: z.array(z.string()).optional()\n .describe('Fields to display on the review page'),\n actions: z.array(z.object({\n label: z.string().describe('Action button label'),\n type: z.enum(['approve', 'reject', 'skip', 'custom'])\n .describe('Action type'),\n field: z.string().optional()\n .describe('Field to update on action'),\n value: z.union([z.string(), z.number(), z.boolean()]).optional()\n .describe('Value to set on action'),\n nextRecord: z.boolean().optional().default(true)\n .describe('Auto-advance to next record after action'),\n })).describe('Review actions'),\n navigation: z.enum(['sequential', 'random', 'filtered'])\n .optional().default('sequential')\n .describe('Record navigation mode'),\n showProgress: z.boolean().optional().default(true)\n .describe('Show review progress indicator'),\n});\n\n/**\n * Interface Page Configuration Schema (Airtable Interface parity)\n * Page-level declarative configuration for Airtable-style interface pages.\n * Covers title/data binding, levels, filter by, appearance, user actions,\n * tabs, record count, add record, and advanced options (printing).\n *\n * @see Airtable Interface → right panel (Page / Data / Appearance / User filters / User actions / Advanced)\n */\nexport const InterfacePageConfigSchema = z.object({\n /** Data binding */\n source: z.string().optional().describe('Source object name for the page'),\n levels: z.number().int().min(1).optional().describe('Number of hierarchy levels to display'),\n filterBy: z.array(ViewFilterRuleSchema).optional().describe('Page-level filter criteria'),\n\n /** Appearance */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** User filters */\n userFilters: z.object({\n elements: z.array(z.enum(['grid', 'gallery', 'kanban'])).optional()\n .describe('Visualization element types available in user filter bar'),\n tabs: z.array(ViewTabSchema).optional().describe('User-configurable tabs'),\n }).optional().describe('User filter configuration'),\n\n /** User actions */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles'),\n\n /** Add record */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record count */\n showRecordCount: z.boolean().optional().describe('Show record count at page bottom'),\n\n /** Advanced */\n allowPrinting: z.boolean().optional().describe('Allow users to print the page'),\n}).describe('Interface-level page configuration (Airtable parity)');\n\n/**\n * Page Schema\n * Defines a composition of components for a specific context.\n * Supports both platform pages (Salesforce FlexiPage style: record, home, app, utility)\n * and interface pages (Airtable Interface style: dashboard, grid, kanban, record_review, etc.).\n * \n * **NAMING CONVENTION:**\n * Page names are used in routing and must be lowercase snake_case.\n * Prefix with 'page_' is recommended for clarity.\n * \n * @example Good page names\n * - 'page_dashboard'\n * - 'page_settings'\n * - 'home_page'\n * - 'record_detail'\n * \n * @example Bad page names (will be rejected)\n * - 'PageDashboard' (PascalCase)\n * - 'Settings Page' (spaces)\n */\nexport const PageSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Page unique name (lowercase snake_case)'),\n label: I18nLabelSchema,\n description: I18nLabelSchema.optional(),\n\n /** Icon (used in interface navigation) */\n icon: z.string().optional().describe('Page icon name'),\n \n /** Page Type */\n type: PageTypeSchema.default('record').describe('Page type'),\n \n /** Page State Definitions */\n variables: z.array(PageVariableSchema).optional().describe('Local page state variables'),\n\n /** Context */\n object: z.string().optional().describe('Bound object (for Record pages)'),\n\n /** Record Review Configuration (only for record_review pages) */\n recordReview: RecordReviewConfigSchema.optional()\n .describe('Record review configuration (required when type is \"record_review\")'),\n\n /** Blank Page Layout (only for blank pages) */\n blankLayout: BlankPageLayoutSchema.optional()\n .describe('Free-form grid layout for blank pages (used when type is \"blank\")'),\n \n /** Layout Template */\n template: z.string().default('default').describe('Layout template name (e.g. \"header-sidebar-main\")'),\n \n /** Regions & Content */\n regions: z.array(PageRegionSchema).describe('Defined regions with components'),\n \n /** Activation */\n isDefault: z.boolean().default(false),\n assignedProfiles: z.array(z.string()).optional(),\n\n /** Interface Page Configuration (Airtable Interface parity) */\n interfaceConfig: InterfacePageConfigSchema.optional()\n .describe('Interface-level page configuration (for Airtable-style interface pages)'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).superRefine((data, ctx) => {\n if (data.type === 'record_review' && !data.recordReview) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['recordReview'],\n message: 'recordReview is required when type is \"record_review\"',\n });\n }\n if (data.type === 'blank' && !data.blankLayout) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['blankLayout'],\n message: 'blankLayout is required when type is \"blank\"',\n });\n }\n});\n\nexport type Page = z.infer;\nexport type PageType = z.infer;\nexport type PageComponent = z.infer;\nexport type PageRegion = z.infer;\nexport type PageVariable = z.infer;\nexport type ElementDataSource = z.infer;\nexport type RecordReviewConfig = z.infer;\nexport type BlankPageLayoutItem = z.infer;\nexport type BlankPageLayout = z.infer;\nexport type InterfacePageConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Widget Lifecycle Hooks Schema\n * \n * Defines lifecycle callbacks for custom widgets inspired by Web Components and React.\n * These hooks allow widgets to perform initialization, cleanup, and respond to changes.\n * \n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components\n * @see https://react.dev/reference/react/Component#component-lifecycle\n * \n * @example\n * ```typescript\n * const widget = {\n * lifecycle: {\n * onMount: \"console.log('Widget mounted')\",\n * onUpdate: \"if (prevProps.value !== props.value) { updateUI() }\",\n * onUnmount: \"cleanup()\",\n * onValidate: \"return value.length > 0 ? null : 'Required field'\"\n * }\n * }\n * ```\n */\nexport const WidgetLifecycleSchema = z.object({\n /**\n * Called when widget is mounted/rendered for the first time\n * Use for initialization, setting up event listeners, loading data, etc.\n * \n * @example \"initializeDatePicker(); loadOptions();\"\n */\n onMount: z.string().optional().describe('Initialization code when widget mounts'),\n\n /**\n * Called when widget props change\n * Receives previous props for comparison\n * \n * @example \"if (prevProps.value !== props.value) { updateDisplay() }\"\n */\n onUpdate: z.string().optional().describe('Code to run when props change'),\n\n /**\n * Called when widget is about to be removed from DOM\n * Use for cleanup, removing event listeners, canceling timers, etc.\n * \n * @example \"destroyDatePicker(); cancelPendingRequests();\"\n */\n onUnmount: z.string().optional().describe('Cleanup code when widget unmounts'),\n\n /**\n * Custom validation logic for this widget\n * Should return error message string if invalid, null/undefined if valid\n * \n * @example \"return value && value.length >= 10 ? null : 'Minimum 10 characters'\"\n */\n onValidate: z.string().optional().describe('Custom validation logic'),\n\n /**\n * Called when widget receives focus\n * \n * @example \"highlightField(); logFocusEvent();\"\n */\n onFocus: z.string().optional().describe('Code to run on focus'),\n\n /**\n * Called when widget loses focus\n * \n * @example \"validateField(); saveFieldState();\"\n */\n onBlur: z.string().optional().describe('Code to run on blur'),\n\n /**\n * Called on any error in the widget\n * \n * @example \"logError(error); showErrorNotification();\"\n */\n onError: z.string().optional().describe('Error handling code'),\n});\n\nexport type WidgetLifecycle = z.infer;\n\n/**\n * Widget Event Schema\n * \n * Defines custom events that widgets can emit, inspired by DOM Events and Lightning Web Components.\n * \n * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events\n * @see https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.events\n * \n * @example\n * ```typescript\n * const searchEvent = {\n * name: 'search',\n * bubbles: true,\n * cancelable: false,\n * payload: {\n * query: 'string',\n * filters: 'object'\n * }\n * }\n * ```\n */\nexport const WidgetEventSchema = z.object({\n /**\n * Event name\n * Should be lowercase, dash-separated for consistency\n * \n * @example \"value-change\", \"item-selected\", \"search-complete\"\n */\n name: z.string().describe('Event name'),\n\n /**\n * Event label for documentation\n */\n label: I18nLabelSchema.optional().describe('Human-readable event label'),\n\n /**\n * Event description\n */\n description: I18nLabelSchema.optional().describe('Event description and usage'),\n\n /**\n * Whether event bubbles up through the DOM hierarchy\n * \n * @default false\n */\n bubbles: z.boolean().default(false).describe('Whether event bubbles'),\n\n /**\n * Whether event can be cancelled\n * \n * @default false\n */\n cancelable: z.boolean().default(false).describe('Whether event is cancelable'),\n\n /**\n * Event payload schema\n * Defines the data structure sent with the event\n * \n * @example { userId: 'string', timestamp: 'number' }\n */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event payload schema'),\n});\n\nexport type WidgetEvent = z.infer;\n\n/**\n * Widget Property Definition Schema\n * \n * Defines the contract for widget configuration properties.\n * Inspired by React PropTypes and Web Component attributes.\n * \n * @see https://react.dev/reference/react/Component#static-proptypes\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements\n * \n * @example\n * ```typescript\n * const widgetProps = {\n * maxLength: {\n * type: 'number',\n * required: false,\n * default: 100,\n * description: 'Maximum input length'\n * }\n * }\n * ```\n */\nexport const WidgetPropertySchema = z.object({\n /**\n * Property name\n * Should be camelCase following ObjectStack conventions\n */\n name: z.string().describe('Property name (camelCase)'),\n\n /**\n * Property label for UI\n */\n label: I18nLabelSchema.optional().describe('Human-readable label'),\n\n /**\n * Property data type\n * \n * @example \"string\", \"number\", \"boolean\", \"array\", \"object\", \"function\"\n */\n type: z.enum(['string', 'number', 'boolean', 'array', 'object', 'function', 'any'])\n .describe('TypeScript type'),\n\n /**\n * Whether property is required\n * \n * @default false\n */\n required: z.boolean().default(false).describe('Whether property is required'),\n\n /**\n * Default value for the property\n */\n default: z.unknown().optional().describe('Default value'),\n\n /**\n * Property description\n */\n description: I18nLabelSchema.optional().describe('Property description'),\n\n /**\n * Property validation schema\n * Can include min/max, regex, enum values, etc.\n */\n validation: z.record(z.string(), z.unknown()).optional().describe('Validation rules'),\n\n /**\n * Property category for grouping in UI\n */\n category: z.string().optional().describe('Property category'),\n});\n\nexport type WidgetProperty = z.infer;\n\n/**\n * Widget Manifest Schema\n * \n * Complete definition for a custom widget including metadata, lifecycle, events, and props.\n * This is used for widget registration and discovery.\n * \n * @example\n * ```typescript\n * const customWidget = {\n * name: 'custom_date_picker',\n * label: 'Custom Date Picker',\n * version: '1.0.0',\n * author: 'Company Name',\n * fieldTypes: ['date', 'datetime'],\n * lifecycle: { ... },\n * events: [ ... ],\n * properties: [ ... ]\n * }\n * ```\n */\n/**\n * Widget Source Schema\n * Defines how the widget code is loaded.\n */\nexport const WidgetSourceSchema = z.discriminatedUnion('type', [\n // NPM Registry (standard)\n z.object({\n type: z.literal('npm'),\n packageName: z.string().describe('NPM package name'),\n version: z.string().default('latest'),\n exportName: z.string().optional().describe('Named export (default: default)'),\n }),\n // Module Federation (Remote)\n z.object({\n type: z.literal('remote'),\n url: z.string().url().describe('Remote entry URL (.js)'),\n moduleName: z.string().describe('Exposed module name'),\n scope: z.string().describe('Remote scope name'),\n }),\n // Inline Code (Simple scripts)\n z.object({\n type: z.literal('inline'),\n code: z.string().describe('JavaScript code body'),\n }),\n]);\n\nexport type WidgetSource = z.infer;\n\nexport const WidgetManifestSchema = z.object({\n /**\n * Widget identifier (snake_case)\n */\n name: SnakeCaseIdentifierSchema\n .describe('Widget identifier (snake_case)'),\n\n /**\n * Human-readable widget name\n */\n label: I18nLabelSchema.describe('Widget display name'),\n\n /**\n * Widget description\n */\n description: I18nLabelSchema.optional().describe('Widget description'),\n\n /**\n * Widget version (semver)\n */\n version: z.string().optional().describe('Widget version (semver)'),\n\n /**\n * Widget author/organization\n */\n author: z.string().optional().describe('Widget author'),\n\n /**\n * Icon name or URL\n */\n icon: z.string().optional().describe('Widget icon'),\n\n /**\n * Field types this widget supports\n * \n * @example [\"text\", \"email\", \"url\"]\n */\n fieldTypes: z.array(z.string()).optional().describe('Supported field types'),\n\n /**\n * Widget category for organization\n */\n category: z.enum(['input', 'display', 'picker', 'editor', 'custom'])\n .default('custom')\n .describe('Widget category'),\n\n /**\n * Widget lifecycle hooks\n */\n lifecycle: WidgetLifecycleSchema.optional().describe('Lifecycle hooks'),\n\n /**\n * Custom events this widget emits\n */\n events: z.array(WidgetEventSchema).optional().describe('Custom events'),\n\n /**\n * Widget configuration properties\n */\n properties: z.array(WidgetPropertySchema).optional().describe('Configuration properties'),\n\n /**\n * Widget implementation\n * Defines how to load the widget code\n */\n implementation: WidgetSourceSchema.optional().describe('Widget implementation source'),\n\n /**\n * Widget dependencies\n * External libraries or scripts needed\n */\n dependencies: z.array(z.object({\n name: z.string(),\n version: z.string().optional(),\n url: z.string().url().optional(),\n })).optional().describe('Widget dependencies'),\n\n /**\n * Widget screenshots for showcase\n */\n screenshots: z.array(z.string().url()).optional().describe('Screenshot URLs'),\n\n /**\n * Widget documentation URL\n */\n documentation: z.string().url().optional().describe('Documentation URL'),\n\n /**\n * License information\n */\n license: z.string().optional().describe('License (SPDX identifier)'),\n\n /**\n * Tags for discovery\n */\n tags: z.array(z.string()).optional().describe('Tags for categorization'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\nexport type WidgetManifest = z.infer;\n\n/**\n * Field Widget Props Schema\n * \n * This defines the contract for custom field components and plugin UI extensions.\n * Third-party developers use this interface to build custom field widgets that integrate\n * seamlessly with the ObjectStack UI system.\n * \n * @example\n * // Custom widget implementation\n * function CustomDatePicker(props: FieldWidgetProps) {\n * const { value, onChange, readonly, required, error, field, record, options } = props;\n * // Widget implementation...\n * }\n */\nexport const FieldWidgetPropsSchema = z.object({\n /**\n * Current field value.\n * Type depends on the field type (string, number, boolean, array, object, etc.)\n */\n value: z.unknown().describe('Current field value'),\n\n /**\n * Callback function to update the field value.\n * Should be called when user interaction changes the value.\n * \n * @param newValue - The new value to set\n */\n onChange: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.void())\n .describe('Callback to update field value'),\n\n /**\n * Whether the field is in read-only mode.\n * When true, the widget should display the value but not allow editing.\n */\n readonly: z.boolean().default(false).describe('Read-only mode flag'),\n\n /**\n * Whether the field is required.\n * Widget should indicate required state visually and validate accordingly.\n */\n required: z.boolean().default(false).describe('Required field flag'),\n\n /**\n * Validation error message to display.\n * When present, widget should display the error in its UI.\n */\n error: z.string().optional().describe('Validation error message'),\n\n /**\n * Complete field definition from the schema.\n * Contains metadata like type, constraints, options, etc.\n */\n field: FieldSchema.describe('Field schema definition'),\n\n /**\n * The complete record/document being edited.\n * Useful for conditional logic and cross-field dependencies.\n */\n record: z.record(z.string(), z.unknown()).optional().describe('Complete record data'),\n\n /**\n * Custom options passed to the widget.\n * Can contain widget-specific configuration like themes, behaviors, etc.\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Custom widget options'),\n});\n\n/**\n * TypeScript type for Field Widget Props\n */\nexport type FieldWidgetProps = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Feed Item Type\n * Unified activity types for the record timeline.\n * Covers comments, field changes, tasks, events, and system activities.\n */\nexport const FeedItemType = z.enum([\n 'comment',\n 'field_change',\n 'task',\n 'event',\n 'email',\n 'call',\n 'note',\n 'file',\n 'record_create',\n 'record_delete',\n 'approval',\n 'sharing',\n 'system',\n]);\nexport type FeedItemType = z.infer;\n\n/**\n * Mention Schema\n * Represents an @mention within comment body text.\n */\nexport const MentionSchema = z.object({\n type: z.enum(['user', 'team', 'record']).describe('Mention target type'),\n id: z.string().describe('Target ID'),\n name: z.string().describe('Display name for rendering'),\n offset: z.number().int().min(0).describe('Character offset in body text'),\n length: z.number().int().min(1).describe('Length of mention token in body text'),\n});\nexport type Mention = z.infer;\n\n/**\n * Field Change Entry Schema\n * Represents a single field-level change within a field_change feed item.\n */\nexport const FieldChangeEntrySchema = z.object({\n field: z.string().describe('Field machine name'),\n fieldLabel: z.string().optional().describe('Field display label'),\n oldValue: z.unknown().optional().describe('Previous value'),\n newValue: z.unknown().optional().describe('New value'),\n oldDisplayValue: z.string().optional().describe('Human-readable old value'),\n newDisplayValue: z.string().optional().describe('Human-readable new value'),\n});\nexport type FieldChangeEntry = z.infer;\n\n/**\n * Reaction Schema\n * Represents an emoji reaction on a feed item.\n */\nexport const ReactionSchema = z.object({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n userIds: z.array(z.string()).describe('Users who reacted'),\n count: z.number().int().min(1).describe('Total reaction count'),\n});\nexport type Reaction = z.infer;\n\n/**\n * Feed Actor Schema\n * Represents the actor who performed the action.\n */\nexport const FeedActorSchema = z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n avatarUrl: z.string().url().optional().describe('Actor avatar URL'),\n source: z.string().optional().describe('Source application (e.g., \"Omni\", \"API\", \"Studio\")'),\n});\nexport type FeedActor = z.infer;\n\n/**\n * Feed Item Visibility\n */\nexport const FeedVisibility = z.enum(['public', 'internal', 'private']);\nexport type FeedVisibility = z.infer;\n\n/**\n * Feed Item Schema\n * A single entry in the unified activity timeline.\n *\n * @example Comment\n * {\n * id: 'feed_001',\n * type: 'comment',\n * object: 'account',\n * recordId: 'rec_123',\n * body: 'Great progress! @jane.doe can you follow up?',\n * mentions: [{ type: 'user', id: 'user_123', name: 'Jane Doe', offset: 17, length: 9 }],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:30:00Z',\n * }\n *\n * @example Field Change\n * {\n * id: 'feed_002',\n * type: 'field_change',\n * object: 'account',\n * recordId: 'rec_123',\n * changes: [\n * { field: 'status', oldDisplayValue: 'New', newDisplayValue: 'Active' },\n * { field: 'region', oldDisplayValue: '', newDisplayValue: 'Asia-Pacific' },\n * ],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:25:00Z',\n * }\n */\nexport const FeedItemSchema = z.object({\n /** Unique identifier */\n id: z.string().describe('Feed item ID'),\n\n /** Feed item type */\n type: FeedItemType.describe('Activity type'),\n\n /** Target record reference */\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID this feed item belongs to'),\n\n /** Actor (who performed the action) */\n actor: FeedActorSchema.describe('Who performed this action'),\n\n /** Content (for comments/notes) */\n body: z.string().optional().describe('Rich text body (Markdown supported)'),\n\n /** @Mentions */\n mentions: z.array(MentionSchema).optional().describe('Mentioned users/teams/records'),\n\n /** Field changes (for field_change type) */\n changes: z.array(FieldChangeEntrySchema).optional().describe('Field-level changes'),\n\n /** Reactions */\n reactions: z.array(ReactionSchema).optional().describe('Emoji reactions on this item'),\n\n /** Reply threading */\n parentId: z.string().optional().describe('Parent feed item ID for threaded replies'),\n replyCount: z.number().int().min(0).default(0).describe('Number of replies'),\n\n /** Pin / Star */\n pinned: z.boolean().default(false).describe('Whether the feed item is pinned to the top of the timeline'),\n pinnedAt: z.string().datetime().optional().describe('Timestamp when the item was pinned'),\n pinnedBy: z.string().optional().describe('User ID who pinned the item'),\n starred: z.boolean().default(false).describe('Whether the feed item is starred/bookmarked by the current user'),\n starredAt: z.string().datetime().optional().describe('Timestamp when the item was starred'),\n\n /** Visibility */\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public (all users), internal (team only), private (author + mentioned)'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n editedAt: z.string().datetime().optional().describe('When comment was last edited'),\n isEdited: z.boolean().default(false).describe('Whether comment has been edited'),\n});\nexport type FeedItem = z.infer;\n\n/**\n * Feed Filter Mode\n * Controls which feed item types to display in the timeline.\n */\nexport const FeedFilterMode = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\nexport type FeedFilterMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ViewFilterRuleSchema } from './view.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { FeedItemType, FeedFilterMode } from '../data/feed.zod';\n\n/**\n * Empty Properties Schema\n */\nconst EmptyProps = z.object({});\n\n/**\n * ----------------------------------------------------------------------\n * 1. Structure Components\n * ----------------------------------------------------------------------\n */\n\nexport const PageHeaderProps = z.object({\n title: I18nLabelSchema.describe('Page title'),\n subtitle: I18nLabelSchema.optional().describe('Page subtitle'),\n icon: z.string().optional().describe('Icon name'),\n breadcrumb: z.boolean().default(true).describe('Show breadcrumb'),\n actions: z.array(z.string()).optional().describe('Action IDs to show in header'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageTabsProps = z.object({\n type: z.enum(['line', 'card', 'pill']).default('line'),\n position: z.enum(['top', 'left']).default('top'),\n items: z.array(z.object({\n label: I18nLabelSchema,\n icon: z.string().optional(),\n children: z.array(z.unknown()).describe('Child components')\n })),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageCardProps = z.object({\n title: I18nLabelSchema.optional(),\n bordered: z.boolean().default(true),\n actions: z.array(z.string()).optional(),\n /** Slot for nested content in the Card body */\n body: z.array(z.unknown()).optional().describe('Card content components (slot)'),\n /** Slot for footer content */\n footer: z.array(z.unknown()).optional().describe('Card footer components (slot)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 2. Record Context Components\n * ----------------------------------------------------------------------\n */\n\nexport const RecordDetailsProps = z.object({\n columns: z.enum(['1', '2', '3', '4']).default('2').describe('Number of columns for field layout (1-4)'),\n layout: z.enum(['auto', 'custom']).default('auto').describe('Layout mode: auto uses object compactLayout, custom uses explicit sections'),\n sections: z.array(z.string()).optional().describe('Section IDs to show (required when layout is \"custom\")'),\n fields: z.array(z.string()).optional().describe('Explicit field list to display (optional, overrides compactLayout)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordRelatedListProps = z.object({\n objectName: z.string().describe('Related object name (e.g., \"task\", \"opportunity\")'),\n relationshipField: z.string().describe('Field on related object that points to this record (e.g., \"account_id\")'),\n columns: z.array(z.string()).describe('Fields to display in the related list'),\n sort: z.union([\n z.string(),\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional().describe('Sort order for related records'),\n limit: z.number().int().positive().default(5).describe('Number of records to display initially'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Additional filter criteria for related records'),\n title: I18nLabelSchema.optional().describe('Custom title for the related list'),\n showViewAll: z.boolean().default(true).describe('Show \"View All\" link to see all related records'),\n actions: z.array(z.string()).optional().describe('Action IDs available for related records'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordHighlightsProps = z.object({\n fields: z.array(z.string()).min(1).max(7).describe('Key fields to highlight (1-7 fields max, typically displayed as prominent cards)'),\n layout: z.enum(['horizontal', 'vertical']).default('horizontal').describe('Layout orientation for highlight fields'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordActivityProps = z.object({\n /** Activity types to display (unified enum including comment, field_change, etc.) */\n types: z.array(FeedItemType).optional().describe('Feed item types to show (default: all)'),\n /** Default filter mode (Airtable-style dropdown) */\n filterMode: FeedFilterMode.default('all').describe('Default activity filter'),\n /** Allow user to switch filter modes */\n showFilterToggle: z.boolean().default(true).describe('Show filter dropdown in panel header'),\n /** Pagination */\n limit: z.number().int().positive().default(20).describe('Number of items to load per page'),\n /** Show completed activities */\n showCompleted: z.boolean().default(false).describe('Include completed activities'),\n /** Merge field_change + comment in a unified timeline */\n unifiedTimeline: z.boolean().default(true).describe('Mix field changes and comments in one timeline (Airtable style)'),\n /** Show the comment input box at the bottom */\n showCommentInput: z.boolean().default(true).describe('Show \"Leave a comment\" input at the bottom'),\n /** Enable @mentions in comments */\n enableMentions: z.boolean().default(true).describe('Enable @mentions in comments'),\n /** Enable emoji reactions */\n enableReactions: z.boolean().default(false).describe('Enable emoji reactions on feed items'),\n /** Enable threaded replies */\n enableThreading: z.boolean().default(false).describe('Enable threaded replies on comments'),\n /** Show notification subscription toggle (bell icon) */\n showSubscriptionToggle: z.boolean().default(true).describe('Show bell icon for record-level notification subscription'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordChatterProps = z.object({\n /** Panel position */\n position: z.enum(['sidebar', 'inline', 'drawer']).default('sidebar').describe('Where to render the chatter panel'),\n /** Panel width (for sidebar/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Panel width (e.g., \"350px\", \"30%\")'),\n /** Collapsible */\n collapsible: z.boolean().default(true).describe('Whether the panel can be collapsed'),\n /** Default collapsed state */\n defaultCollapsed: z.boolean().default(false).describe('Whether the panel starts collapsed'),\n /** Feed configuration (delegates to RecordActivityProps) */\n feed: RecordActivityProps.optional().describe('Embedded activity feed configuration'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordPathProps = z.object({\n statusField: z.string().describe('Field name representing the current status/stage'),\n stages: z.array(z.object({\n value: z.string(),\n label: I18nLabelSchema,\n })).optional().describe('Explicit stage definitions (if not using field metadata)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageAccordionProps = z.object({\n items: z.array(z.object({\n label: I18nLabelSchema,\n icon: z.string().optional(),\n collapsed: z.boolean().default(false),\n children: z.array(z.unknown()).describe('Child components'),\n })),\n allowMultiple: z.boolean().default(false).describe('Allow multiple panels to be expanded simultaneously'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const AIChatWindowProps = z.object({\n mode: z.enum(['float', 'sidebar', 'inline']).default('float').describe('Display mode for the chat window'),\n agentId: z.string().optional().describe('Specific AI agent to use'),\n context: z.record(z.string(), z.unknown()).optional().describe('Contextual data to pass to the AI'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 3. Content Element Components (Airtable Interface Parity)\n * ----------------------------------------------------------------------\n */\n\nexport const ElementTextPropsSchema = z.object({\n content: z.string().describe('Text or Markdown content'),\n variant: z.enum(['heading', 'subheading', 'body', 'caption'])\n .optional().default('body').describe('Text style variant'),\n align: z.enum(['left', 'center', 'right'])\n .optional().default('left').describe('Text alignment'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementNumberPropsSchema = z.object({\n object: z.string().describe('Source object'),\n field: z.string().optional().describe('Field to aggregate'),\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max'])\n .describe('Aggregation function'),\n filter: FilterConditionSchema.optional().describe('Filter criteria'),\n format: z.enum(['number', 'currency', 'percent']).optional().describe('Number display format'),\n prefix: z.string().optional().describe('Prefix text (e.g. \"$\")'),\n suffix: z.string().optional().describe('Suffix text (e.g. \"%\")'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementImagePropsSchema = z.object({\n src: z.string().describe('Image URL or attachment field'),\n alt: z.string().optional().describe('Alt text for accessibility'),\n fit: z.enum(['cover', 'contain', 'fill'])\n .optional().default('cover').describe('Image object-fit mode'),\n height: z.number().optional().describe('Fixed height in pixels'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 4. Interactive Element Components (Phase B — Element Library)\n * ----------------------------------------------------------------------\n */\n\nexport const ElementButtonPropsSchema = z.object({\n label: I18nLabelSchema.describe('Button display label'),\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link'])\n .optional().default('primary').describe('Button visual variant'),\n size: z.enum(['small', 'medium', 'large'])\n .optional().default('medium').describe('Button size'),\n icon: z.string().optional().describe('Icon name (Lucide icon)'),\n iconPosition: z.enum(['left', 'right'])\n .optional().default('left').describe('Icon position relative to label'),\n disabled: z.boolean().optional().default(false).describe('Disable the button'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementFilterPropsSchema = z.object({\n object: z.string().describe('Object to filter'),\n fields: z.array(z.string()).describe('Filterable field names'),\n targetVariable: z.string().optional().describe('Page variable to store filter state'),\n layout: z.enum(['inline', 'dropdown', 'sidebar'])\n .optional().default('inline').describe('Filter display layout'),\n showSearch: z.boolean().optional().default(true).describe('Show search input'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementFormPropsSchema = z.object({\n object: z.string().describe('Object for the form'),\n fields: z.array(z.string()).optional().describe('Fields to display (defaults to all editable fields)'),\n mode: z.enum(['create', 'edit']).optional().default('create').describe('Form mode'),\n submitLabel: I18nLabelSchema.optional().describe('Submit button label'),\n onSubmit: z.string().optional().describe('Action expression on form submit'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementRecordPickerPropsSchema = z.object({\n object: z.string().describe('Object to pick records from'),\n displayField: z.string().describe('Field to display as the record label'),\n searchFields: z.array(z.string()).optional().describe('Fields to search against'),\n filter: FilterConditionSchema.optional().describe('Filter criteria for available records'),\n multiple: z.boolean().optional().default(false).describe('Allow multiple record selection'),\n targetVariable: z.string().optional().describe('Page variable to bind selected record ID(s)'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * Component Props Map\n * Maps Component Type to its Property Schema\n * ----------------------------------------------------------------------\n */\nexport const ComponentPropsMap = {\n // Structure\n 'page:header': PageHeaderProps,\n 'page:tabs': PageTabsProps,\n 'page:card': PageCardProps,\n 'page:footer': EmptyProps,\n 'page:sidebar': EmptyProps,\n 'page:accordion': PageAccordionProps,\n 'page:section': EmptyProps,\n\n // Record\n 'record:details': RecordDetailsProps,\n 'record:related_list': RecordRelatedListProps,\n 'record:highlights': RecordHighlightsProps,\n 'record:activity': RecordActivityProps,\n 'record:chatter': RecordChatterProps,\n 'record:path': RecordPathProps,\n\n // Navigation\n 'app:launcher': EmptyProps,\n 'nav:menu': EmptyProps,\n 'nav:breadcrumb': EmptyProps,\n\n // Utility\n 'global:search': EmptyProps,\n 'global:notifications': EmptyProps,\n 'user:profile': EmptyProps,\n \n // AI\n 'ai:chat_window': AIChatWindowProps,\n 'ai:suggestion': z.object({ context: z.string().optional() }),\n\n // Content Elements\n 'element:text': ElementTextPropsSchema,\n 'element:number': ElementNumberPropsSchema,\n 'element:image': ElementImagePropsSchema,\n 'element:divider': EmptyProps,\n\n // Interactive Elements\n 'element:button': ElementButtonPropsSchema,\n 'element:filter': ElementFilterPropsSchema,\n 'element:form': ElementFormPropsSchema,\n 'element:record_picker': ElementRecordPickerPropsSchema,\n} as const;\n\n/**\n * Type Helper to extract props from map\n */\nexport type ComponentProps = z.infer;\nexport type ComponentPropsInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Touch Target Configuration Schema\n * Ensures touch targets meet WCAG 2.5.5 minimum size requirements (44x44px).\n */\nexport const TouchTargetConfigSchema = z.object({\n minWidth: z.number().default(44).describe('Minimum touch target width in pixels (WCAG 2.5.5: 44px)'),\n minHeight: z.number().default(44).describe('Minimum touch target height in pixels (WCAG 2.5.5: 44px)'),\n padding: z.number().optional().describe('Additional padding around touch target in pixels'),\n hitSlop: z.object({\n top: z.number().optional().describe('Extra hit area above the element'),\n right: z.number().optional().describe('Extra hit area to the right of the element'),\n bottom: z.number().optional().describe('Extra hit area below the element'),\n left: z.number().optional().describe('Extra hit area to the left of the element'),\n }).optional().describe('Invisible hit area extension beyond the visible bounds'),\n}).describe('Touch target sizing configuration (WCAG accessible)');\n\nexport type TouchTargetConfig = z.infer;\n\n/**\n * Gesture Type Enum\n * Supported touch gesture types.\n */\nexport const GestureTypeSchema = z.enum([\n 'swipe',\n 'pinch',\n 'long_press',\n 'double_tap',\n 'drag',\n 'rotate',\n 'pan',\n]).describe('Touch gesture type');\n\nexport type GestureType = z.infer;\n\n/**\n * Swipe Direction Enum\n */\nexport const SwipeDirectionSchema = z.enum(['up', 'down', 'left', 'right']);\n\nexport type SwipeDirection = z.infer;\n\n/**\n * Swipe Gesture Configuration Schema\n */\nexport const SwipeGestureConfigSchema = z.object({\n direction: z.array(SwipeDirectionSchema).describe('Allowed swipe directions'),\n threshold: z.number().optional().describe('Minimum distance in pixels to recognize swipe'),\n velocity: z.number().optional().describe('Minimum velocity (px/ms) to trigger swipe'),\n}).describe('Swipe gesture recognition settings');\n\nexport type SwipeGestureConfig = z.infer;\n\n/**\n * Pinch Gesture Configuration Schema\n */\nexport const PinchGestureConfigSchema = z.object({\n minScale: z.number().optional().describe('Minimum scale factor (e.g., 0.5 for 50%)'),\n maxScale: z.number().optional().describe('Maximum scale factor (e.g., 3.0 for 300%)'),\n}).describe('Pinch/zoom gesture recognition settings');\n\nexport type PinchGestureConfig = z.infer;\n\n/**\n * Long Press Gesture Configuration Schema\n */\nexport const LongPressGestureConfigSchema = z.object({\n duration: z.number().default(500).describe('Hold duration in milliseconds to trigger long press'),\n moveTolerance: z.number().optional().describe('Max movement in pixels allowed during press'),\n}).describe('Long press gesture recognition settings');\n\nexport type LongPressGestureConfig = z.infer;\n\n/**\n * Gesture Configuration Schema\n * Unified configuration for all supported gesture types.\n */\nexport const GestureConfigSchema = z.object({\n type: GestureTypeSchema.describe('Gesture type to configure'),\n label: I18nLabelSchema.optional().describe('Descriptive label for the gesture action'),\n enabled: z.boolean().default(true).describe('Whether this gesture is active'),\n swipe: SwipeGestureConfigSchema.optional().describe('Swipe gesture settings (when type is swipe)'),\n pinch: PinchGestureConfigSchema.optional().describe('Pinch gesture settings (when type is pinch)'),\n longPress: LongPressGestureConfigSchema.optional().describe('Long press settings (when type is long_press)'),\n}).describe('Per-gesture configuration');\n\nexport type GestureConfig = z.infer;\n\n/**\n * Touch Interaction Schema\n * Top-level touch and gesture interaction configuration for a component.\n */\nexport const TouchInteractionSchema = z.object({\n gestures: z.array(GestureConfigSchema).optional().describe('Configured gesture recognizers'),\n touchTarget: TouchTargetConfigSchema.optional().describe('Touch target sizing and hit area'),\n hapticFeedback: z.boolean().optional().describe('Enable haptic feedback on touch interactions'),\n}).merge(AriaPropsSchema.partial()).describe('Touch and gesture interaction configuration');\n\nexport type TouchInteraction = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Focus Trap Configuration Schema\n * Constrains keyboard focus within a specific container (e.g., modals, dialogs).\n */\nexport const FocusTrapConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable focus trapping within this container'),\n initialFocus: z.string().optional().describe('CSS selector for the element to focus on activation'),\n returnFocus: z.boolean().default(true).describe('Return focus to trigger element on deactivation'),\n escapeDeactivates: z.boolean().default(true).describe('Allow Escape key to deactivate the focus trap'),\n}).describe('Focus trap configuration for modal-like containers');\n\nexport type FocusTrapConfig = z.infer;\n\n/**\n * Keyboard Shortcut Schema\n * Defines a single keyboard shortcut binding.\n */\nexport const KeyboardShortcutSchema = z.object({\n key: z.string().describe('Key combination (e.g., \"Ctrl+S\", \"Alt+N\", \"Escape\")'),\n action: z.string().describe('Action identifier to invoke when shortcut is triggered'),\n description: I18nLabelSchema.optional().describe('Human-readable description of what the shortcut does'),\n scope: z.enum(['global', 'view', 'form', 'modal', 'list']).default('global')\n .describe('Scope in which this shortcut is active'),\n}).describe('Keyboard shortcut binding');\n\nexport type KeyboardShortcut = z.infer;\n\n/**\n * Focus Management Schema\n * Controls tab order, focus visibility, and navigation behavior.\n */\nexport const FocusManagementSchema = z.object({\n tabOrder: z.enum(['auto', 'manual']).default('auto')\n .describe('Tab order strategy: auto (DOM order) or manual (explicit tabIndex)'),\n skipLinks: z.boolean().default(false).describe('Provide skip-to-content navigation links'),\n focusVisible: z.boolean().default(true).describe('Show visible focus indicators for keyboard users'),\n focusTrap: FocusTrapConfigSchema.optional().describe('Focus trap settings'),\n arrowNavigation: z.boolean().default(false)\n .describe('Enable arrow key navigation between focusable items'),\n}).describe('Focus and tab navigation management');\n\nexport type FocusManagement = z.infer;\n\n/**\n * Keyboard Navigation Configuration Schema\n * Top-level keyboard navigation and shortcut configuration.\n */\nexport const KeyboardNavigationConfigSchema = z.object({\n shortcuts: z.array(KeyboardShortcutSchema).optional().describe('Registered keyboard shortcuts'),\n focusManagement: FocusManagementSchema.optional().describe('Focus and tab order management'),\n rovingTabindex: z.boolean().default(false)\n .describe('Enable roving tabindex pattern for composite widgets'),\n}).merge(AriaPropsSchema.partial()).describe('Keyboard navigation and shortcut configuration');\n\nexport type KeyboardNavigationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { TouchTargetConfigSchema } from './touch.zod';\nimport { FocusManagementSchema } from './keyboard.zod';\n\n/**\n * Color Palette Schema\n * Defines brand colors and their variants.\n */\nexport const ColorPaletteSchema = z.object({\n primary: z.string().describe('Primary brand color (hex, rgb, or hsl)'),\n secondary: z.string().optional().describe('Secondary brand color'),\n accent: z.string().optional().describe('Accent color for highlights'),\n success: z.string().optional().describe('Success state color (default: green)'),\n warning: z.string().optional().describe('Warning state color (default: yellow)'),\n error: z.string().optional().describe('Error state color (default: red)'),\n info: z.string().optional().describe('Info state color (default: blue)'),\n \n // Neutral colors\n background: z.string().optional().describe('Background color'),\n surface: z.string().optional().describe('Surface/card background color'),\n text: z.string().optional().describe('Primary text color'),\n textSecondary: z.string().optional().describe('Secondary text color'),\n border: z.string().optional().describe('Border color'),\n disabled: z.string().optional().describe('Disabled state color'),\n \n // Color variants (shades)\n primaryLight: z.string().optional().describe('Lighter shade of primary'),\n primaryDark: z.string().optional().describe('Darker shade of primary'),\n secondaryLight: z.string().optional().describe('Lighter shade of secondary'),\n secondaryDark: z.string().optional().describe('Darker shade of secondary'),\n});\n\n/**\n * Typography Settings Schema\n * Font families, sizes, weights, and line heights.\n */\nexport const TypographySchema = z.object({\n fontFamily: z.object({\n base: z.string().optional().describe('Base font family (default: system fonts)'),\n heading: z.string().optional().describe('Heading font family'),\n mono: z.string().optional().describe('Monospace font family for code'),\n }).optional(),\n \n fontSize: z.object({\n xs: z.string().optional().describe('Extra small font size (e.g., 0.75rem)'),\n sm: z.string().optional().describe('Small font size (e.g., 0.875rem)'),\n base: z.string().optional().describe('Base font size (e.g., 1rem)'),\n lg: z.string().optional().describe('Large font size (e.g., 1.125rem)'),\n xl: z.string().optional().describe('Extra large font size (e.g., 1.25rem)'),\n '2xl': z.string().optional().describe('2X large font size (e.g., 1.5rem)'),\n '3xl': z.string().optional().describe('3X large font size (e.g., 1.875rem)'),\n '4xl': z.string().optional().describe('4X large font size (e.g., 2.25rem)'),\n }).optional(),\n \n fontWeight: z.object({\n light: z.number().optional().describe('Light weight (default: 300)'),\n normal: z.number().optional().describe('Normal weight (default: 400)'),\n medium: z.number().optional().describe('Medium weight (default: 500)'),\n semibold: z.number().optional().describe('Semibold weight (default: 600)'),\n bold: z.number().optional().describe('Bold weight (default: 700)'),\n }).optional(),\n \n lineHeight: z.object({\n tight: z.string().optional().describe('Tight line height (e.g., 1.25)'),\n normal: z.string().optional().describe('Normal line height (e.g., 1.5)'),\n relaxed: z.string().optional().describe('Relaxed line height (e.g., 1.75)'),\n loose: z.string().optional().describe('Loose line height (e.g., 2)'),\n }).optional(),\n \n letterSpacing: z.object({\n tighter: z.string().optional().describe('Tighter letter spacing (e.g., -0.05em)'),\n tight: z.string().optional().describe('Tight letter spacing (e.g., -0.025em)'),\n normal: z.string().optional().describe('Normal letter spacing (e.g., 0)'),\n wide: z.string().optional().describe('Wide letter spacing (e.g., 0.025em)'),\n wider: z.string().optional().describe('Wider letter spacing (e.g., 0.05em)'),\n }).optional(),\n});\n\n/**\n * Spacing Units Schema\n * Defines spacing scale for margins, padding, gaps.\n */\nexport const SpacingSchema = z.object({\n '0': z.string().optional().describe('0 spacing (0)'),\n '1': z.string().optional().describe('Spacing unit 1 (e.g., 0.25rem)'),\n '2': z.string().optional().describe('Spacing unit 2 (e.g., 0.5rem)'),\n '3': z.string().optional().describe('Spacing unit 3 (e.g., 0.75rem)'),\n '4': z.string().optional().describe('Spacing unit 4 (e.g., 1rem)'),\n '5': z.string().optional().describe('Spacing unit 5 (e.g., 1.25rem)'),\n '6': z.string().optional().describe('Spacing unit 6 (e.g., 1.5rem)'),\n '8': z.string().optional().describe('Spacing unit 8 (e.g., 2rem)'),\n '10': z.string().optional().describe('Spacing unit 10 (e.g., 2.5rem)'),\n '12': z.string().optional().describe('Spacing unit 12 (e.g., 3rem)'),\n '16': z.string().optional().describe('Spacing unit 16 (e.g., 4rem)'),\n '20': z.string().optional().describe('Spacing unit 20 (e.g., 5rem)'),\n '24': z.string().optional().describe('Spacing unit 24 (e.g., 6rem)'),\n});\n\n/**\n * Border Radius Schema\n * Rounded corners configuration.\n */\nexport const BorderRadiusSchema = z.object({\n none: z.string().optional().describe('No border radius (0)'),\n sm: z.string().optional().describe('Small border radius (e.g., 0.125rem)'),\n base: z.string().optional().describe('Base border radius (e.g., 0.25rem)'),\n md: z.string().optional().describe('Medium border radius (e.g., 0.375rem)'),\n lg: z.string().optional().describe('Large border radius (e.g., 0.5rem)'),\n xl: z.string().optional().describe('Extra large border radius (e.g., 0.75rem)'),\n '2xl': z.string().optional().describe('2X large border radius (e.g., 1rem)'),\n full: z.string().optional().describe('Full border radius (50%)'),\n});\n\n/**\n * Shadow Schema\n * Box shadow effects.\n */\nexport const ShadowSchema = z.object({\n none: z.string().optional().describe('No shadow'),\n sm: z.string().optional().describe('Small shadow'),\n base: z.string().optional().describe('Base shadow'),\n md: z.string().optional().describe('Medium shadow'),\n lg: z.string().optional().describe('Large shadow'),\n xl: z.string().optional().describe('Extra large shadow'),\n '2xl': z.string().optional().describe('2X large shadow'),\n inner: z.string().optional().describe('Inner shadow (inset)'),\n});\n\n/**\n * Breakpoints Schema\n * Responsive design breakpoints.\n */\nexport const BreakpointsSchema = z.object({\n xs: z.string().optional().describe('Extra small breakpoint (e.g., 480px)'),\n sm: z.string().optional().describe('Small breakpoint (e.g., 640px)'),\n md: z.string().optional().describe('Medium breakpoint (e.g., 768px)'),\n lg: z.string().optional().describe('Large breakpoint (e.g., 1024px)'),\n xl: z.string().optional().describe('Extra large breakpoint (e.g., 1280px)'),\n '2xl': z.string().optional().describe('2X large breakpoint (e.g., 1536px)'),\n});\n\n/**\n * Animation Schema\n * Animation timing and duration settings.\n */\nexport const AnimationSchema = z.object({\n duration: z.object({\n fast: z.string().optional().describe('Fast animation (e.g., 150ms)'),\n base: z.string().optional().describe('Base animation (e.g., 300ms)'),\n slow: z.string().optional().describe('Slow animation (e.g., 500ms)'),\n }).optional(),\n \n timing: z.object({\n linear: z.string().optional().describe('Linear timing function'),\n ease: z.string().optional().describe('Ease timing function'),\n ease_in: z.string().optional().describe('Ease-in timing function'),\n ease_out: z.string().optional().describe('Ease-out timing function'),\n ease_in_out: z.string().optional().describe('Ease-in-out timing function'),\n }).optional(),\n});\n\n/**\n * Z-Index Scale Schema\n * Layering and stacking order.\n */\nexport const ZIndexSchema = z.object({\n base: z.number().optional().describe('Base z-index (e.g., 0)'),\n dropdown: z.number().optional().describe('Dropdown z-index (e.g., 1000)'),\n sticky: z.number().optional().describe('Sticky z-index (e.g., 1020)'),\n fixed: z.number().optional().describe('Fixed z-index (e.g., 1030)'),\n modalBackdrop: z.number().optional().describe('Modal backdrop z-index (e.g., 1040)'),\n modal: z.number().optional().describe('Modal z-index (e.g., 1050)'),\n popover: z.number().optional().describe('Popover z-index (e.g., 1060)'),\n tooltip: z.number().optional().describe('Tooltip z-index (e.g., 1070)'),\n});\n\n/**\n * Theme Mode Schema\n */\nexport const ThemeModeSchema = z.enum(['light', 'dark', 'auto']);\n\n/** @deprecated Use ThemeModeSchema instead */\nexport const ThemeMode = ThemeModeSchema;\n\n/**\n * Density Mode Schema\n * Controls spacing and sizing for different use cases.\n */\nexport const DensityModeSchema = z.enum(['compact', 'regular', 'spacious']);\n\n/** @deprecated Use DensityModeSchema instead */\nexport const DensityMode = DensityModeSchema;\n\n/**\n * WCAG Contrast Level Schema\n * Web Content Accessibility Guidelines color contrast requirements.\n */\nexport const WcagContrastLevelSchema = z.enum(['AA', 'AAA']);\n\n/** @deprecated Use WcagContrastLevelSchema instead */\nexport const WcagContrastLevel = WcagContrastLevelSchema;\n\n/**\n * Theme Configuration Schema\n * Complete theme definition for brand customization.\n */\nexport const ThemeSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Unique theme identifier (snake_case)'),\n label: z.string().describe('Human-readable theme name'),\n description: z.string().optional().describe('Theme description'),\n \n /** Theme mode */\n mode: ThemeModeSchema.default('light').describe('Theme mode (light, dark, or auto)'),\n \n /** Color system */\n colors: ColorPaletteSchema.describe('Color palette configuration'),\n \n /** Typography */\n typography: TypographySchema.optional().describe('Typography settings'),\n \n /** Spacing */\n spacing: SpacingSchema.optional().describe('Spacing scale'),\n \n /** Border radius */\n borderRadius: BorderRadiusSchema.optional().describe('Border radius scale'),\n \n /** Shadows */\n shadows: ShadowSchema.optional().describe('Box shadow effects'),\n \n /** Breakpoints */\n breakpoints: BreakpointsSchema.optional().describe('Responsive breakpoints'),\n \n /** Animation */\n animation: AnimationSchema.optional().describe('Animation settings'),\n \n /** Z-Index */\n zIndex: ZIndexSchema.optional().describe('Z-index scale for layering'),\n \n /** Custom CSS variables */\n customVars: z.record(z.string(), z.string()).optional().describe('Custom CSS variables (key-value pairs)'),\n \n /** Logo */\n logo: z.object({\n light: z.string().optional().describe('Logo URL for light mode'),\n dark: z.string().optional().describe('Logo URL for dark mode'),\n favicon: z.string().optional().describe('Favicon URL'),\n }).optional().describe('Logo assets'),\n \n /** Extends another theme */\n extends: z.string().optional().describe('Base theme to extend from'),\n\n /** Display density mode */\n density: DensityModeSchema.optional().describe('Display density: compact, regular, or spacious'),\n\n /** WCAG contrast level requirement */\n wcagContrast: WcagContrastLevelSchema.optional().describe('WCAG color contrast level (AA or AAA)'),\n\n /** Right-to-left language support */\n rtl: z.boolean().optional().describe('Enable right-to-left layout direction'),\n\n /** Touch target accessibility configuration */\n touchTarget: TouchTargetConfigSchema.optional().describe('Touch target sizing defaults'),\n\n /** Keyboard navigation and focus management */\n keyboardNavigation: FocusManagementSchema.optional().describe('Keyboard focus management settings'),\n});\n\nexport type Theme = z.infer;\nexport type ColorPalette = z.infer;\nexport type Typography = z.infer;\nexport type Spacing = z.infer;\nexport type BorderRadius = z.infer;\nexport type Shadow = z.infer;\nexport type Breakpoints = z.infer;\nexport type Animation = z.infer;\nexport type ZIndex = z.infer;\nexport type ThemeMode = z.infer;\nexport type DensityMode = z.infer;\nexport type WcagContrastLevel = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema } from './i18n.zod';\n\n/**\n * Offline Strategy Schema\n * Determines how data is fetched when connectivity is limited.\n */\nexport const OfflineStrategySchema = z.enum([\n 'cache_first',\n 'network_first',\n 'stale_while_revalidate',\n 'network_only',\n 'cache_only',\n]).describe('Data fetching strategy for offline/online transitions');\n\nexport type OfflineStrategy = z.infer;\n\n/**\n * Conflict Resolution Strategy Enum\n */\nexport const ConflictResolutionSchema = z.enum([\n 'client_wins',\n 'server_wins',\n 'manual',\n 'last_write_wins',\n]).describe('How to resolve conflicts when syncing offline changes');\n\nexport type ConflictResolution = z.infer;\n\n/**\n * Sync Configuration Schema\n * Controls how offline mutations are synchronized with the server.\n */\nexport const SyncConfigSchema = z.object({\n strategy: OfflineStrategySchema.default('network_first').describe('Sync fetch strategy'),\n conflictResolution: ConflictResolutionSchema.default('last_write_wins').describe('Conflict resolution policy'),\n retryInterval: z.number().optional().describe('Retry interval in milliseconds between sync attempts'),\n maxRetries: z.number().optional().describe('Maximum number of sync retry attempts'),\n batchSize: z.number().optional().describe('Number of mutations to sync per batch'),\n}).describe('Offline-to-online synchronization configuration');\n\nexport type SyncConfig = z.infer;\n\n/**\n * Persist Storage Backend Enum\n */\nexport const PersistStorageSchema = z.enum([\n 'indexeddb',\n 'localstorage',\n 'sqlite',\n]).describe('Client-side storage backend for offline cache');\n\nexport type PersistStorage = z.infer;\n\n/**\n * Eviction Policy Enum\n */\nexport const EvictionPolicySchema = z.enum([\n 'lru',\n 'lfu',\n 'fifo',\n]).describe('Cache eviction policy');\n\nexport type EvictionPolicy = z.infer;\n\n/**\n * Offline Cache Configuration Schema\n * Controls how data is persisted on the client for offline access.\n */\nexport const OfflineCacheConfigSchema = z.object({\n maxSize: z.number().optional().describe('Maximum cache size in bytes'),\n ttl: z.number().optional().describe('Time-to-live for cached entries in milliseconds'),\n persistStorage: PersistStorageSchema.default('indexeddb').describe('Storage backend'),\n evictionPolicy: EvictionPolicySchema.default('lru').describe('Cache eviction policy when full'),\n}).describe('Client-side offline cache configuration');\n\nexport type OfflineCacheConfig = z.infer;\n\n/**\n * Offline Configuration Schema\n * Top-level offline support configuration for an application or component.\n */\nexport const OfflineConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable offline support'),\n strategy: OfflineStrategySchema.default('network_first').describe('Default offline fetch strategy'),\n cache: OfflineCacheConfigSchema.optional().describe('Cache settings for offline data'),\n sync: SyncConfigSchema.optional().describe('Sync settings for offline mutations'),\n offlineIndicator: z.boolean().default(true).describe('Show a visual indicator when offline'),\n offlineMessage: I18nLabelSchema.optional().describe('Customizable offline status message shown to users'),\n queueMaxSize: z.number().optional().describe('Maximum number of queued offline mutations'),\n}).describe('Offline support configuration');\n\nexport type OfflineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Transition Preset Schema\n * Common animation transition presets.\n */\nexport const TransitionPresetSchema = z.enum([\n 'fade',\n 'slide_up',\n 'slide_down',\n 'slide_left',\n 'slide_right',\n 'scale',\n 'rotate',\n 'flip',\n 'none',\n]).describe('Transition preset type');\n\nexport type TransitionPreset = z.infer;\n\n/**\n * Easing Function Schema\n * Supported animation easing/timing functions.\n */\nexport const EasingFunctionSchema = z.enum([\n 'linear',\n 'ease',\n 'ease_in',\n 'ease_out',\n 'ease_in_out',\n 'spring',\n]).describe('Animation easing function');\n\nexport type EasingFunction = z.infer;\n\n/**\n * Transition Configuration Schema\n * Defines a single animation transition with timing and easing options.\n */\nexport const TransitionConfigSchema = z.object({\n preset: TransitionPresetSchema.optional().describe('Transition preset to apply'),\n duration: z.number().optional().describe('Transition duration in milliseconds'),\n easing: EasingFunctionSchema.optional().describe('Easing function for the transition'),\n delay: z.number().optional().describe('Delay before transition starts in milliseconds'),\n customKeyframes: z.string().optional().describe('CSS @keyframes name for custom animations'),\n themeToken: z.string().optional().describe('Reference to a theme animation token (e.g. \"animation.duration.fast\")'),\n}).describe('Animation transition configuration');\n\nexport type TransitionConfig = z.infer;\n\n/**\n * Animation Trigger Schema\n * Events that can trigger an animation.\n */\nexport const AnimationTriggerSchema = z.enum([\n 'on_mount',\n 'on_unmount',\n 'on_hover',\n 'on_focus',\n 'on_click',\n 'on_scroll',\n 'on_visible',\n]).describe('Event that triggers the animation');\n\nexport type AnimationTrigger = z.infer;\n\n/**\n * Component Animation Schema\n * Animation configuration for an individual UI component.\n */\nexport const ComponentAnimationSchema = z.object({\n label: I18nLabelSchema.optional().describe('Descriptive label for this animation configuration'),\n enter: TransitionConfigSchema.optional().describe('Enter/mount animation'),\n exit: TransitionConfigSchema.optional().describe('Exit/unmount animation'),\n hover: TransitionConfigSchema.optional().describe('Hover state animation'),\n trigger: AnimationTriggerSchema.optional().describe('When to trigger the animation'),\n reducedMotion: z.enum(['respect', 'disable', 'alternative']).default('respect')\n .describe('Accessibility: how to handle prefers-reduced-motion'),\n}).merge(AriaPropsSchema.partial()).describe('Component-level animation configuration');\n\nexport type ComponentAnimation = z.infer;\n\n/**\n * Page Transition Schema\n * Defines the animation used when navigating between pages.\n */\nexport const PageTransitionSchema = z.object({\n type: TransitionPresetSchema.default('fade').describe('Page transition type'),\n duration: z.number().default(300).describe('Transition duration in milliseconds'),\n easing: EasingFunctionSchema.default('ease_in_out').describe('Easing function for the transition'),\n crossFade: z.boolean().default(false).describe('Whether to cross-fade between pages'),\n}).describe('Page-level transition configuration');\n\nexport type PageTransition = z.infer;\n\n/**\n * Motion Configuration Schema\n * Top-level animation and motion design configuration.\n */\nexport const MotionConfigSchema = z.object({\n label: I18nLabelSchema.optional().describe('Descriptive label for the motion configuration'),\n defaultTransition: TransitionConfigSchema.optional().describe('Default transition applied to all animations'),\n pageTransitions: PageTransitionSchema.optional().describe('Page navigation transition settings'),\n componentAnimations: z.record(z.string(), ComponentAnimationSchema).optional()\n .describe('Component name to animation configuration mapping'),\n reducedMotion: z.boolean().default(false).describe('When true, respect prefers-reduced-motion and suppress animations globally'),\n enabled: z.boolean().default(true).describe('Enable or disable all animations globally'),\n}).describe('Top-level motion and animation design configuration');\n\nexport type MotionConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Notification Type Schema\n * Defines the visual presentation style of the notification.\n */\nexport const NotificationTypeSchema = z.enum([\n 'toast',\n 'snackbar',\n 'banner',\n 'alert',\n 'inline',\n]).describe('Notification presentation style');\n\nexport type NotificationType = z.infer;\n\n/**\n * Notification Severity Schema\n * Indicates the urgency and visual treatment of the notification.\n */\nexport const NotificationSeveritySchema = z.enum([\n 'info',\n 'success',\n 'warning',\n 'error',\n]).describe('Notification severity level');\n\nexport type NotificationSeverity = z.infer;\n\n/**\n * Notification Position Schema\n * Screen position for rendering notifications.\n */\nexport const NotificationPositionSchema = z.enum([\n 'top_left',\n 'top_center',\n 'top_right',\n 'bottom_left',\n 'bottom_center',\n 'bottom_right',\n]).describe('Screen position for notification placement');\n\nexport type NotificationPosition = z.infer;\n\n/**\n * Notification Action Schema\n * Defines an interactive action button within a notification.\n */\nexport const NotificationActionSchema = z.object({\n label: I18nLabelSchema.describe('Action button label'),\n action: z.string().describe('Action identifier to execute'),\n variant: z.enum(['primary', 'secondary', 'link']).default('primary')\n .describe('Button variant style'),\n}).describe('Notification action button');\n\nexport type NotificationAction = z.infer;\n\n/**\n * Notification Schema\n * Defines a single notification instance with content, behavior, and positioning.\n */\nexport const NotificationSchema = z.object({\n type: NotificationTypeSchema.default('toast').describe('Notification presentation style'),\n severity: NotificationSeveritySchema.default('info').describe('Notification severity level'),\n title: I18nLabelSchema.optional().describe('Notification title'),\n message: I18nLabelSchema.describe('Notification message body'),\n icon: z.string().optional().describe('Icon name override'),\n duration: z.number().optional().describe('Auto-dismiss duration in ms, omit for persistent'),\n dismissible: z.boolean().default(true).describe('Allow user to dismiss the notification'),\n actions: z.array(NotificationActionSchema).optional().describe('Action buttons'),\n position: NotificationPositionSchema.optional().describe('Override default position'),\n}).merge(AriaPropsSchema.partial()).describe('Notification instance definition');\n\nexport type Notification = z.infer;\n\n/**\n * Notification Config Schema\n * Top-level notification system configuration.\n */\nexport const NotificationConfigSchema = z.object({\n defaultPosition: NotificationPositionSchema.default('top_right')\n .describe('Default screen position for notifications'),\n defaultDuration: z.number().default(5000)\n .describe('Default auto-dismiss duration in ms'),\n maxVisible: z.number().default(5)\n .describe('Maximum number of notifications visible at once'),\n stackDirection: z.enum(['up', 'down']).default('down')\n .describe('Stack direction for multiple notifications'),\n pauseOnHover: z.boolean().default(true)\n .describe('Pause auto-dismiss timer on hover'),\n}).describe('Global notification system configuration');\n\nexport type NotificationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Drag Handle Schema\n * Defines how a drag interaction is initiated on an element.\n */\nexport const DragHandleSchema = z.enum([\n 'element',\n 'handle',\n 'grip_icon',\n]).describe('Drag initiation method');\n\nexport type DragHandle = z.infer;\n\n/**\n * Drop Effect Schema\n * Visual feedback indicating the result of a drop operation.\n */\nexport const DropEffectSchema = z.enum([\n 'move',\n 'copy',\n 'link',\n 'none',\n]).describe('Drop operation effect');\n\nexport type DropEffect = z.infer;\n\n/**\n * Drag Constraint Schema\n * Constrains drag movement along axes, within bounds, or to a grid.\n */\nexport const DragConstraintSchema = z.object({\n axis: z.enum(['x', 'y', 'both']).default('both').describe('Constrain drag axis'),\n bounds: z.enum(['parent', 'viewport', 'none']).default('none').describe('Constrain within bounds'),\n grid: z.tuple([z.number(), z.number()]).optional().describe('Snap to grid [x, y] in pixels'),\n}).describe('Drag movement constraints');\n\nexport type DragConstraint = z.infer;\n\n/**\n * Drop Zone Schema\n * Configures a container that accepts dragged items.\n */\nexport const DropZoneSchema = z.object({\n label: I18nLabelSchema.optional().describe('Accessible label for the drop zone'),\n accept: z.array(z.string()).describe('Accepted drag item types'),\n maxItems: z.number().optional().describe('Maximum items allowed in drop zone'),\n highlightOnDragOver: z.boolean().default(true).describe('Highlight drop zone when dragging over'),\n dropEffect: DropEffectSchema.default('move').describe('Visual effect on drop'),\n}).merge(AriaPropsSchema.partial()).describe('Drop zone configuration');\n\nexport type DropZone = z.infer;\n\n/**\n * Drag Item Schema\n * Configures a draggable element including handle, constraints, and preview.\n */\nexport const DragItemSchema = z.object({\n type: z.string().describe('Drag item type identifier for matching with drop zones'),\n label: I18nLabelSchema.optional().describe('Accessible label describing the draggable item'),\n handle: DragHandleSchema.default('element').describe('How to initiate drag'),\n constraint: DragConstraintSchema.optional().describe('Drag movement constraints'),\n preview: z.enum(['element', 'custom', 'none']).default('element').describe('Drag preview type'),\n disabled: z.boolean().default(false).describe('Disable dragging'),\n}).merge(AriaPropsSchema.partial()).describe('Draggable item configuration');\n\nexport type DragItem = z.infer;\n\n/**\n * Drag and Drop Configuration Schema\n * Top-level drag-and-drop interaction configuration for a component.\n */\nexport const DndConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable drag and drop'),\n dragItem: DragItemSchema.optional().describe('Configuration for draggable item'),\n dropZone: DropZoneSchema.optional().describe('Configuration for drop target'),\n sortable: z.boolean().default(false).describe('Enable sortable list behavior'),\n autoScroll: z.boolean().default(true).describe('Auto-scroll during drag near edges'),\n touchDelay: z.number().default(200).describe('Delay in ms before drag starts on touch devices'),\n}).describe('Drag and drop interaction configuration');\n\nexport type DndConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * LocalStoragePersistenceAdapter\n *\n * Persists the in-memory database to browser localStorage.\n * Synchronous storage with a ~5MB size limit warning.\n *\n * Browser only — will throw if used in non-browser environments.\n */\nexport class LocalStoragePersistenceAdapter {\n private readonly storageKey: string;\n private static readonly SIZE_WARNING_BYTES = 4.5 * 1024 * 1024; // 4.5MB warning threshold\n\n constructor(options?: { key?: string }) {\n this.storageKey = options?.key || 'objectstack:memory-db';\n }\n\n /**\n * Load persisted data from localStorage.\n * Returns null if no data exists.\n */\n async load(): Promise | null> {\n try {\n const raw = localStorage.getItem(this.storageKey);\n if (!raw) return null;\n return JSON.parse(raw) as Record;\n } catch {\n return null;\n }\n }\n\n /**\n * Save data to localStorage.\n * Warns if data size approaches the ~5MB localStorage limit.\n */\n async save(db: Record): Promise {\n const json = JSON.stringify(db);\n\n if (json.length > LocalStoragePersistenceAdapter.SIZE_WARNING_BYTES) {\n console.warn(\n `[ObjectStack] localStorage persistence data size (${(json.length / 1024 / 1024).toFixed(2)}MB) ` +\n `is approaching the ~5MB limit. Consider using a different persistence strategy.`\n );\n }\n\n try {\n localStorage.setItem(this.storageKey, json);\n } catch (e: any) {\n console.error('[ObjectStack] Failed to persist data to localStorage:', e?.message || e);\n }\n }\n\n /**\n * Flush is a no-op for localStorage (writes are synchronous).\n */\n async flush(): Promise {\n // localStorage writes are synchronous, no flushing needed\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * FileSystemPersistenceAdapter\n *\n * Persists the in-memory database to a JSON file on disk.\n * Supports atomic writes (write to temp file then rename) and auto-save with dirty tracking.\n *\n * Node.js only — will throw if used in non-Node.js environments.\n */\nexport class FileSystemPersistenceAdapter {\n private readonly filePath: string;\n private readonly autoSaveInterval: number;\n private dirty = false;\n private timer: ReturnType | null = null;\n private currentDb: Record | null = null;\n\n constructor(options?: { path?: string; autoSaveInterval?: number }) {\n this.filePath = options?.path || path.join('.objectstack', 'data', 'memory-driver.json');\n this.autoSaveInterval = options?.autoSaveInterval ?? 2000;\n }\n\n /**\n * Load persisted data from disk.\n * Returns null if no file exists.\n */\n async load(): Promise | null> {\n try {\n if (!fs.existsSync(this.filePath)) {\n return null;\n }\n const raw = fs.readFileSync(this.filePath, 'utf-8');\n const data = JSON.parse(raw);\n return data as Record;\n } catch {\n return null;\n }\n }\n\n /**\n * Save data to disk using atomic write (temp file + rename).\n */\n async save(db: Record): Promise {\n this.currentDb = db;\n this.dirty = true;\n }\n\n /**\n * Flush pending writes to disk immediately.\n */\n async flush(): Promise {\n if (!this.dirty || !this.currentDb) return;\n await this.writeToDisk(this.currentDb);\n this.dirty = false;\n }\n\n /**\n * Start the auto-save timer.\n */\n startAutoSave(): void {\n if (this.timer) return;\n this.timer = setInterval(async () => {\n if (this.dirty && this.currentDb) {\n await this.writeToDisk(this.currentDb);\n this.dirty = false;\n }\n }, this.autoSaveInterval);\n\n // Allow process to exit even if timer is running\n if (this.timer) {\n this.timer.unref();\n }\n }\n\n /**\n * Stop the auto-save timer and flush pending writes.\n */\n async stopAutoSave(): Promise {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n await this.flush();\n }\n\n /**\n * Atomic write: write to temp file, then rename.\n */\n private async writeToDisk(db: Record): Promise {\n const dir = path.dirname(this.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n const tmpPath = this.filePath + '.tmp';\n const json = JSON.stringify(db, null, 2);\n fs.writeFileSync(tmpPath, json, 'utf-8');\n fs.renameSync(tmpPath, this.filePath);\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { QueryAST, QueryInput, DriverOptions } from '@objectstack/spec/data';\nimport type { IDataDriver } from '@objectstack/spec/contracts';\nimport { Logger, createLogger } from '@objectstack/core';\nimport { Query, Aggregator } from 'mingo';\nimport { getValueByPath } from './memory-matcher.js';\n\n/**\n * Persistence adapter interface.\n * Matches the PersistenceAdapterSchema contract from @objectstack/spec.\n */\nexport interface PersistenceAdapterInterface {\n load(): Promise | null>;\n save(db: Record): Promise;\n flush(): Promise;\n /** Optional: Start periodic auto-save (used by FileSystemPersistenceAdapter). */\n startAutoSave?(): void;\n /** Optional: Stop auto-save timer and flush pending writes. */\n stopAutoSave?(): Promise;\n}\n\n/**\n * Configuration options for the InMemory driver.\n * Aligned with @objectstack/spec MemoryConfigSchema.\n */\nexport interface InMemoryDriverConfig {\n /** Optional: Initial data to populate the store */\n initialData?: Record[]>;\n /** Optional: Enable strict mode (throw on missing records) */\n strictMode?: boolean;\n /** Optional: Logger instance */\n logger?: Logger;\n /**\n * Persistence configuration. Defaults to `'auto'`.\n * - `'auto'` (default) — Auto-detect environment (browser → localStorage, Node.js → file, serverless → disabled)\n * - `'file'` — File-system persistence with defaults (Node.js only)\n * - `'local'` — localStorage persistence with defaults (Browser only)\n * - `{ type: 'file', path?: string, autoSaveInterval?: number }` — File-system with options\n * - `{ type: 'local', key?: string }` — localStorage with options\n * - `{ type: 'auto', path?: string, key?: string, autoSaveInterval?: number }` — Auto-detect with options\n * - `{ adapter: PersistenceAdapterInterface }` — Custom adapter\n * - `false` — Disable persistence (pure in-memory)\n *\n * ⚠️ In serverless environments (Vercel, AWS Lambda, Netlify, etc.),\n * auto mode disables file persistence to prevent silent data loss.\n * Use `persistence: false` or supply a custom adapter for serverless deployments.\n */\n persistence?: string | false | {\n type?: 'file' | 'local' | 'auto';\n path?: string;\n key?: string;\n autoSaveInterval?: number;\n adapter?: PersistenceAdapterInterface;\n };\n}\n\n/**\n * Snapshot for in-memory transactions.\n */\ninterface MemoryTransaction {\n id: string;\n snapshot: Record;\n}\n\n/**\n * In-Memory Driver for ObjectStack\n * \n * A production-ready implementation of the ObjectStack Driver Protocol\n * powered by Mingo — a MongoDB-compatible query and aggregation engine.\n * \n * Features:\n * - MongoDB-compatible query engine (Mingo) for filtering, projection, aggregation\n * - Full CRUD and bulk operations\n * - Aggregation pipeline support ($match, $group, $sort, $project, $unwind, etc.)\n * - Snapshot-based transactions (begin/commit/rollback)\n * - Field projection and distinct values\n * - Strict mode and initial data loading\n * \n * Reference: objectql/packages/drivers/memory\n */\nexport class InMemoryDriver implements IDataDriver {\n readonly name = 'com.objectstack.driver.memory';\n type = 'driver';\n readonly version = '1.0.0';\n private config: InMemoryDriverConfig;\n private logger: Logger;\n private idCounters: Map = new Map();\n private transactions: Map = new Map();\n private persistenceAdapter: PersistenceAdapterInterface | null = null;\n\n constructor(config?: InMemoryDriverConfig) {\n this.config = config || {};\n this.logger = config?.logger || createLogger({ level: 'info', format: 'pretty' });\n this.logger.debug('InMemory driver instance created');\n }\n\n // Duck-typed RuntimePlugin hook\n install(ctx: any) {\n this.logger.debug('Installing InMemory driver via plugin hook');\n if (ctx.engine && ctx.engine.ql && typeof ctx.engine.ql.registerDriver === 'function') {\n ctx.engine.ql.registerDriver(this);\n this.logger.info('InMemory driver registered with ObjectQL engine');\n } else {\n this.logger.warn('Could not register driver - ObjectQL engine not found in context');\n }\n }\n \n readonly supports = {\n // Basic CRUD Operations\n create: true,\n read: true,\n update: true,\n delete: true,\n\n // Bulk Operations\n bulkCreate: true,\n bulkUpdate: true,\n bulkDelete: true,\n\n // Transaction & Connection Management\n transactions: true, // Snapshot-based transactions\n savepoints: false,\n \n // Query Operations\n queryFilters: true, // Implemented via memory-matcher\n queryAggregations: true, // Implemented\n querySorting: true, // Implemented via JS sort\n queryPagination: true, // Implemented\n queryWindowFunctions: false, // @planned: Window functions (ROW_NUMBER, RANK, etc.)\n querySubqueries: false, // @planned: Subquery execution\n queryCTE: false,\n joins: false, // @planned: In-memory join operations\n \n // Advanced Features\n fullTextSearch: false, // @planned: Text tokenization + matching\n jsonQuery: false,\n geospatialQuery: false,\n streaming: true, // Implemented via findStream()\n jsonFields: true, // Native JS object support\n arrayFields: true, // Native JS array support\n vectorSearch: false, // @planned: Cosine similarity search\n\n // Schema Management\n schemaSync: true, // Implemented via syncSchema()\n batchSchemaSync: false,\n migrations: false,\n indexes: false,\n\n // Performance & Optimization\n connectionPooling: false,\n preparedStatements: false,\n queryCache: false,\n };\n\n /**\n * The \"Database\": A map of TableName -> Array of Records\n */\n private db: Record = {};\n\n // ===================================\n // Lifecycle\n // ===================================\n\n async connect() {\n // Initialize persistence adapter if configured\n await this.initPersistence();\n\n // Load persisted data if available\n if (this.persistenceAdapter) {\n const persisted = await this.persistenceAdapter.load();\n if (persisted) {\n for (const [objectName, records] of Object.entries(persisted)) {\n this.db[objectName] = records;\n // Update ID counters based on persisted data\n for (const record of records) {\n if (record.id && typeof record.id === 'string') {\n // ID format: {objectName}-{timestamp}-{counter}\n const parts = record.id.split('-');\n const lastPart = parts[parts.length - 1];\n const counter = parseInt(lastPart, 10);\n if (!isNaN(counter)) {\n const current = this.idCounters.get(objectName) || 0;\n if (counter > current) {\n this.idCounters.set(objectName, counter);\n }\n }\n }\n }\n }\n this.logger.info('InMemory Database restored from persistence', {\n tables: Object.keys(persisted).length,\n });\n }\n }\n\n // Load initial data if provided\n if (this.config.initialData) {\n for (const [objectName, records] of Object.entries(this.config.initialData)) {\n const table = this.getTable(objectName);\n for (const record of records) {\n const id = (record as any).id || this.generateId(objectName);\n table.push({ ...record, id });\n }\n }\n this.logger.info('InMemory Database Connected with initial data', {\n tables: Object.keys(this.config.initialData).length,\n });\n } else {\n this.logger.info('InMemory Database Connected (Virtual)');\n }\n\n // Start auto-save if using file adapter\n if (this.persistenceAdapter?.startAutoSave) {\n this.persistenceAdapter.startAutoSave();\n }\n }\n\n async disconnect() {\n // Stop auto-save and flush pending writes\n if (this.persistenceAdapter) {\n if (this.persistenceAdapter.stopAutoSave) {\n await this.persistenceAdapter.stopAutoSave();\n }\n await this.persistenceAdapter.flush();\n }\n\n const tableCount = Object.keys(this.db).length;\n const recordCount = Object.values(this.db).reduce((sum, table) => sum + table.length, 0);\n \n this.db = {};\n this.logger.info('InMemory Database Disconnected & Cleared', { \n tableCount, \n recordCount \n });\n }\n\n async checkHealth() {\n this.logger.debug('Health check performed', { \n tableCount: Object.keys(this.db).length,\n status: 'healthy' \n });\n return true; \n }\n\n // ===================================\n // Execution\n // ===================================\n\n async execute(command: any, params?: any[]) {\n this.logger.warn('Raw execution not supported in InMemory driver', { command });\n return null;\n }\n\n // ===================================\n // CRUD\n // ===================================\n\n async find(object: string, query: QueryAST, options?: DriverOptions) {\n this.logger.debug('Find operation', { object, query });\n \n const table = this.getTable(object);\n let results = [...table]; // Work on copy\n\n // 1. Filter using Mingo\n if (query.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n results = mingoQuery.find(results).all();\n }\n }\n\n // 1.5 Aggregation & Grouping\n if (query.groupBy || (query.aggregations && query.aggregations.length > 0)) {\n results = this.performAggregation(results, query);\n }\n\n // 2. Sort\n if (query.orderBy) {\n const sortFields = Array.isArray(query.orderBy) ? query.orderBy : [query.orderBy];\n results = this.applySort(results, sortFields);\n }\n\n // 3. Pagination (Offset)\n if (query.offset) {\n results = results.slice(query.offset);\n }\n\n // 4. Pagination (Limit)\n if (query.limit) {\n results = results.slice(0, query.limit);\n }\n\n // 5. Field Projection\n if (query.fields && Array.isArray(query.fields) && query.fields.length > 0) {\n results = results.map(record => this.projectFields(record, query.fields as string[]));\n }\n\n this.logger.debug('Find completed', { object, resultCount: results.length });\n return results;\n }\n\n async *findStream(object: string, query: QueryAST, options?: DriverOptions) {\n this.logger.debug('FindStream operation', { object });\n \n const results = await this.find(object, query, options);\n for (const record of results) {\n yield record;\n }\n }\n\n async findOne(object: string, query: QueryAST, options?: DriverOptions) {\n this.logger.debug('FindOne operation', { object, query });\n \n const results = await this.find(object, { ...query, limit: 1 }, options);\n const result = results[0] || null;\n \n this.logger.debug('FindOne completed', { object, found: !!result });\n return result;\n }\n\n async create(object: string, data: Record, options?: DriverOptions) {\n this.logger.debug('Create operation', { object, hasData: !!data });\n \n const table = this.getTable(object);\n \n const newRecord = {\n id: data.id || this.generateId(object),\n ...data,\n created_at: data.created_at || new Date().toISOString(),\n updated_at: data.updated_at || new Date().toISOString(),\n };\n\n table.push(newRecord);\n this.markDirty();\n this.logger.debug('Record created', { object, id: newRecord.id, tableSize: table.length });\n return { ...newRecord };\n }\n\n async update(object: string, id: string | number, data: Record, options?: DriverOptions) {\n this.logger.debug('Update operation', { object, id });\n \n const table = this.getTable(object);\n const index = table.findIndex(r => r.id == id);\n \n if (index === -1) {\n if (this.config.strictMode) {\n this.logger.warn('Record not found for update', { object, id });\n throw new Error(`Record with ID ${id} not found in ${object}`);\n }\n return null;\n }\n\n const updatedRecord = {\n ...table[index],\n ...data,\n id: table[index].id, // Preserve original ID\n created_at: table[index].created_at, // Preserve created_at\n updated_at: new Date().toISOString(),\n };\n \n table[index] = updatedRecord;\n this.markDirty();\n this.logger.debug('Record updated', { object, id });\n return { ...updatedRecord };\n }\n\n async upsert(object: string, data: Record, conflictKeys?: string[], options?: DriverOptions) {\n this.logger.debug('Upsert operation', { object, conflictKeys });\n \n const table = this.getTable(object);\n let existingRecord: any = null;\n\n if (data.id) {\n existingRecord = table.find(r => r.id === data.id);\n } else if (conflictKeys && conflictKeys.length > 0) {\n existingRecord = table.find(r => conflictKeys.every(key => r[key] === data[key]));\n }\n\n if (existingRecord) {\n this.logger.debug('Record exists, updating', { object, id: existingRecord.id });\n return this.update(object, existingRecord.id, data, options);\n } else {\n this.logger.debug('Record does not exist, creating', { object });\n return this.create(object, data, options);\n }\n }\n\n async delete(object: string, id: string | number, options?: DriverOptions) {\n this.logger.debug('Delete operation', { object, id });\n \n const table = this.getTable(object);\n const index = table.findIndex(r => r.id == id);\n \n if (index === -1) {\n if (this.config.strictMode) {\n throw new Error(`Record with ID ${id} not found in ${object}`);\n }\n this.logger.warn('Record not found for deletion', { object, id });\n return false;\n }\n\n table.splice(index, 1);\n this.markDirty();\n this.logger.debug('Record deleted', { object, id, tableSize: table.length });\n return true;\n }\n\n async count(object: string, query?: QueryAST, options?: DriverOptions) {\n let records = this.getTable(object);\n if (query?.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n records = mingoQuery.find(records).all();\n }\n }\n const count = records.length;\n this.logger.debug('Count operation', { object, count });\n return count;\n }\n\n // ===================================\n // Bulk Operations\n // ===================================\n\n async bulkCreate(object: string, dataArray: Record[], options?: DriverOptions) {\n this.logger.debug('BulkCreate operation', { object, count: dataArray.length });\n const results = await Promise.all(dataArray.map(data => this.create(object, data, options)));\n this.logger.debug('BulkCreate completed', { object, count: results.length });\n return results;\n }\n \n async updateMany(object: string, query: QueryAST, data: Record, options?: DriverOptions): Promise {\n this.logger.debug('UpdateMany operation', { object, query });\n \n const table = this.getTable(object);\n let targetRecords = table;\n \n if (query && query.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n targetRecords = mingoQuery.find(targetRecords).all();\n }\n }\n \n const count = targetRecords.length;\n \n for (const record of targetRecords) {\n const index = table.findIndex(r => r.id === record.id);\n if (index !== -1) {\n const updated = {\n ...table[index],\n ...data,\n updated_at: new Date().toISOString()\n };\n table[index] = updated;\n }\n }\n \n if (count > 0) this.markDirty();\n this.logger.debug('UpdateMany completed', { object, count });\n return count;\n }\n\n async deleteMany(object: string, query: QueryAST, options?: DriverOptions): Promise {\n this.logger.debug('DeleteMany operation', { object, query });\n \n const table = this.getTable(object);\n const initialLength = table.length;\n \n if (query && query.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n const matched = mingoQuery.find(table).all();\n const matchedIds = new Set(matched.map((r: any) => r.id));\n this.db[object] = table.filter(r => !matchedIds.has(r.id));\n } else {\n // Empty query = delete all\n this.db[object] = [];\n }\n } else {\n // No where clause = delete all\n this.db[object] = [];\n }\n \n const count = initialLength - this.db[object].length;\n if (count > 0) this.markDirty();\n this.logger.debug('DeleteMany completed', { object, count });\n return count;\n }\n\n // Compatibility aliases\n async bulkUpdate(object: string, updates: { id: string | number, data: Record }[], options?: DriverOptions) {\n this.logger.debug('BulkUpdate operation', { object, count: updates.length });\n const results = await Promise.all(updates.map(u => this.update(object, u.id, u.data, options)));\n this.logger.debug('BulkUpdate completed', { object, count: results.length });\n return results;\n }\n\n async bulkDelete(object: string, ids: (string | number)[], options?: DriverOptions) {\n this.logger.debug('BulkDelete operation', { object, count: ids.length });\n await Promise.all(ids.map(id => this.delete(object, id, options)));\n this.logger.debug('BulkDelete completed', { object, count: ids.length });\n }\n\n // ===================================\n // Transaction Management\n // ===================================\n\n async beginTransaction() {\n const txId = `tx_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\n // Deep-clone current database state as a snapshot\n const snapshot: Record = {};\n for (const [table, records] of Object.entries(this.db)) {\n snapshot[table] = records.map(r => ({ ...r }));\n }\n\n const transaction: MemoryTransaction = { id: txId, snapshot };\n this.transactions.set(txId, transaction);\n this.logger.debug('Transaction started', { txId });\n return { id: txId };\n }\n\n async commit(txHandle?: unknown) {\n const txId = (txHandle as any)?.id;\n if (!txId || !this.transactions.has(txId)) {\n this.logger.warn('Commit called with unknown transaction');\n return;\n }\n // Data is already in the store; just remove the snapshot\n this.transactions.delete(txId);\n this.logger.debug('Transaction committed', { txId });\n }\n\n async rollback(txHandle?: unknown) {\n const txId = (txHandle as any)?.id;\n if (!txId || !this.transactions.has(txId)) {\n this.logger.warn('Rollback called with unknown transaction');\n return;\n }\n const tx = this.transactions.get(txId)!;\n // Restore the snapshot\n this.db = tx.snapshot;\n this.transactions.delete(txId);\n this.markDirty();\n this.logger.debug('Transaction rolled back', { txId });\n }\n\n // ===================================\n // Utility Methods\n // ===================================\n\n /**\n * Remove all data from the store.\n */\n async clear() {\n this.db = {};\n this.idCounters.clear();\n this.markDirty();\n this.logger.debug('All data cleared');\n }\n\n /**\n * Get total number of records across all tables.\n */\n getSize(): number {\n return Object.values(this.db).reduce((sum, table) => sum + table.length, 0);\n }\n\n /**\n * Get distinct values for a field, optionally filtered.\n */\n async distinct(object: string, field: string, query?: QueryInput): Promise {\n let records = this.getTable(object);\n if (query?.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n records = mingoQuery.find(records).all();\n }\n }\n const values = new Set();\n for (const record of records) {\n const value = getValueByPath(record, field);\n if (value !== undefined && value !== null) {\n values.add(value);\n }\n }\n return Array.from(values);\n }\n\n /**\n * Execute a MongoDB-style aggregation pipeline using Mingo.\n * \n * Supports all standard MongoDB pipeline stages:\n * - $match, $group, $sort, $project, $unwind, $limit, $skip\n * - $addFields, $replaceRoot, $lookup (limited), $count\n * - Accumulator operators: $sum, $avg, $min, $max, $first, $last, $push, $addToSet\n * \n * @example\n * // Group by status and count\n * const results = await driver.aggregate('orders', [\n * { $match: { status: 'completed' } },\n * { $group: { _id: '$customer', totalAmount: { $sum: '$amount' } } }\n * ]);\n * \n * @example\n * // Calculate average with filter\n * const results = await driver.aggregate('products', [\n * { $match: { category: 'electronics' } },\n * { $group: { _id: null, avgPrice: { $avg: '$price' } } }\n * ]);\n */\n async aggregate(object: string, pipeline: Record[], options?: DriverOptions): Promise {\n this.logger.debug('Aggregate operation', { object, stageCount: pipeline.length });\n \n const records = this.getTable(object).map(r => ({ ...r }));\n const aggregator = new Aggregator(pipeline);\n const results = aggregator.run(records);\n \n this.logger.debug('Aggregate completed', { object, resultCount: results.length });\n return results;\n }\n\n // ===================================\n // Query Conversion (ObjectQL → MongoDB)\n // ===================================\n\n /**\n * Convert ObjectQL filter format to MongoDB query format for Mingo.\n * \n * Supports:\n * 1. AST Comparison Node: { type: 'comparison', field, operator, value }\n * 2. AST Logical Node: { type: 'logical', operator: 'and'|'or', conditions: [...] }\n * 3. Legacy Array Format: [['field', 'op', value], 'and', ['field2', 'op', value2]]\n * 4. MongoDB Format: { field: value } or { field: { $eq: value } } (passthrough)\n */\n private convertToMongoQuery(filters?: any): Record {\n if (!filters) return {};\n\n // AST node format (ObjectQL QueryAST)\n if (!Array.isArray(filters) && typeof filters === 'object') {\n if (filters.type === 'comparison') {\n return this.convertConditionToMongo(filters.field, filters.operator, filters.value) || {};\n }\n if (filters.type === 'logical') {\n const conditions = filters.conditions?.map((c: any) => this.convertToMongoQuery(c)) || [];\n if (conditions.length === 0) return {};\n if (conditions.length === 1) return conditions[0];\n const op = filters.operator === 'or' ? '$or' : '$and';\n return { [op]: conditions };\n }\n // MongoDB/FilterCondition format: { field: value } or { field: { $op: value } }\n // Translate non-standard operators ($contains, $notContains, etc.) to Mingo-compatible format\n return this.normalizeFilterCondition(filters);\n }\n\n // Legacy array format\n if (!Array.isArray(filters) || filters.length === 0) return {};\n\n const logicGroups: { logic: 'and' | 'or'; conditions: Record[] }[] = [\n { logic: 'and', conditions: [] },\n ];\n let currentLogic: 'and' | 'or' = 'and';\n\n for (const item of filters) {\n if (typeof item === 'string') {\n const newLogic = item.toLowerCase() as 'and' | 'or';\n if (newLogic !== currentLogic) {\n currentLogic = newLogic;\n logicGroups.push({ logic: currentLogic, conditions: [] });\n }\n } else if (Array.isArray(item)) {\n const [field, operator, value] = item;\n const cond = this.convertConditionToMongo(field, operator, value);\n if (cond) logicGroups[logicGroups.length - 1].conditions.push(cond);\n }\n }\n\n const allConditions: Record[] = [];\n for (const group of logicGroups) {\n if (group.conditions.length === 0) continue;\n if (group.conditions.length === 1) {\n allConditions.push(group.conditions[0]);\n } else {\n const op = group.logic === 'or' ? '$or' : '$and';\n allConditions.push({ [op]: group.conditions });\n }\n }\n\n if (allConditions.length === 0) return {};\n if (allConditions.length === 1) return allConditions[0];\n return { $and: allConditions };\n }\n\n /**\n * Convert a single ObjectQL condition to MongoDB operator format.\n */\n private convertConditionToMongo(field: string, operator: string, value: any): Record | null {\n switch (operator) {\n case '=': case '==':\n return { [field]: value };\n case '!=': case '<>':\n return { [field]: { $ne: value } };\n case '>':\n return { [field]: { $gt: value } };\n case '>=':\n return { [field]: { $gte: value } };\n case '<':\n return { [field]: { $lt: value } };\n case '<=':\n return { [field]: { $lte: value } };\n case 'in':\n return { [field]: { $in: value } };\n case 'nin': case 'not in':\n return { [field]: { $nin: value } };\n case 'contains': case 'like':\n return { [field]: { $regex: new RegExp(this.escapeRegex(value), 'i') } };\n case 'notcontains': case 'not_contains':\n return { [field]: { $not: { $regex: new RegExp(this.escapeRegex(value), 'i') } } };\n case 'startswith': case 'starts_with':\n return { [field]: { $regex: new RegExp(`^${this.escapeRegex(value)}`, 'i') } };\n case 'endswith': case 'ends_with':\n return { [field]: { $regex: new RegExp(`${this.escapeRegex(value)}$`, 'i') } };\n case 'between':\n if (Array.isArray(value) && value.length === 2) {\n return { [field]: { $gte: value[0], $lte: value[1] } };\n }\n return null;\n default:\n return null;\n }\n }\n\n /**\n * Normalize a FilterCondition object by converting non-standard $-prefixed\n * operators ($contains, $notContains, $startsWith, $endsWith, $between, $null)\n * to Mingo-compatible equivalents ($regex, $gte/$lte, null checks).\n */\n private normalizeFilterCondition(filter: Record): Record {\n const result: Record = {};\n const extraAndConditions: Record[] = [];\n\n for (const key of Object.keys(filter)) {\n const value = filter[key];\n // Recurse into logical operators\n if (key === '$and' || key === '$or') {\n result[key] = Array.isArray(value)\n ? value.map((child: any) => this.normalizeFilterCondition(child))\n : value;\n continue;\n }\n if (key === '$not') {\n result[key] = value && typeof value === 'object'\n ? this.normalizeFilterCondition(value)\n : value;\n continue;\n }\n // Skip $-prefixed keys that aren't field names (already handled or unknown)\n if (key.startsWith('$')) {\n result[key] = value;\n continue;\n }\n // Field-level: value may be primitive (implicit eq) or operator object\n if (value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp)) {\n const normalized = this.normalizeFieldOperators(value);\n // Handle multiple regex conditions on the same field (e.g. $startsWith + $endsWith)\n if (normalized._multiRegex) {\n const regexConditions: Record[] = normalized._multiRegex;\n delete normalized._multiRegex;\n // Each regex becomes its own { field: { $regex: ... } } inside $and\n for (const rc of regexConditions) {\n extraAndConditions.push({ [key]: { ...normalized, ...rc } });\n }\n } else {\n result[key] = normalized;\n }\n } else {\n result[key] = value;\n }\n }\n\n // Merge extra $and conditions from multi-regex fields\n if (extraAndConditions.length > 0) {\n const existing = result.$and;\n const andArray = Array.isArray(existing) ? existing : [];\n // Include the rest of result as a condition too\n if (Object.keys(result).filter(k => k !== '$and').length > 0) {\n const rest = { ...result };\n delete rest.$and;\n andArray.push(rest);\n }\n andArray.push(...extraAndConditions);\n return { $and: andArray };\n }\n\n return result;\n }\n\n /**\n * Convert non-standard field operators to Mingo-compatible format.\n * When multiple regex-producing operators appear on the same field\n * (e.g. $startsWith + $endsWith), they are combined via $and.\n */\n private normalizeFieldOperators(ops: Record): Record {\n const result: Record = {};\n const regexConditions: Record[] = [];\n\n for (const op of Object.keys(ops)) {\n const val = ops[op];\n switch (op) {\n case '$contains':\n regexConditions.push({ $regex: new RegExp(this.escapeRegex(val), 'i') });\n break;\n case '$notContains':\n result.$not = { $regex: new RegExp(this.escapeRegex(val), 'i') };\n break;\n case '$startsWith':\n regexConditions.push({ $regex: new RegExp(`^${this.escapeRegex(val)}`, 'i') });\n break;\n case '$endsWith':\n regexConditions.push({ $regex: new RegExp(`${this.escapeRegex(val)}$`, 'i') });\n break;\n case '$between':\n if (Array.isArray(val) && val.length === 2) {\n result.$gte = val[0];\n result.$lte = val[1];\n }\n break;\n case '$null':\n // $null: true → field is null, $null: false → field is not null\n // Use $eq/$ne null for Mingo compatibility\n if (val === true) {\n result.$eq = null;\n } else {\n result.$ne = null;\n }\n break;\n default:\n result[op] = val;\n break;\n }\n }\n\n // Merge regex conditions: single → inline, multiple → wrap with $and\n if (regexConditions.length === 1) {\n Object.assign(result, regexConditions[0]);\n } else if (regexConditions.length > 1) {\n // Cannot have multiple $regex on one object; promote to top-level $and.\n // _multiRegex is an internal sentinel consumed by normalizeFilterCondition().\n result._multiRegex = regexConditions;\n }\n\n return result;\n }\n\n /**\n * Escape special regex characters for safe literal matching.\n */\n private escapeRegex(str: string): string {\n return String(str).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n\n // ===================================\n // Aggregation Logic\n // ===================================\n\n private performAggregation(records: any[], query: QueryInput): any[] {\n const { groupBy, aggregations } = query;\n const groups: Map = new Map();\n\n // 1. Group records\n if (groupBy && groupBy.length > 0) {\n for (const record of records) {\n // Create a composite key from group values\n const keyParts = groupBy.map(field => {\n const val = getValueByPath(record, field);\n return val === undefined || val === null ? 'null' : String(val);\n });\n const key = JSON.stringify(keyParts);\n \n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key)!.push(record);\n }\n } else {\n groups.set('all', records);\n }\n\n // 2. Compute aggregates for each group\n const resultRows: any[] = [];\n \n for (const [_key, groupRecords] of groups.entries()) {\n const row: any = {};\n \n // A. Add Group fields to row (if groupBy exists)\n if (groupBy && groupBy.length > 0) {\n if (groupRecords.length > 0) {\n const firstRecord = groupRecords[0];\n for (const field of groupBy) {\n this.setValueByPath(row, field, getValueByPath(firstRecord, field));\n }\n }\n }\n \n // B. Compute Aggregations\n if (aggregations) {\n for (const agg of aggregations) {\n const value = this.computeAggregate(groupRecords, agg);\n row[agg.alias] = value;\n }\n }\n \n resultRows.push(row);\n }\n \n return resultRows;\n }\n \n private computeAggregate(records: any[], agg: any): any {\n const { function: func, field } = agg;\n \n const values = field ? records.map(r => getValueByPath(r, field)) : [];\n \n switch (func) {\n case 'count':\n if (!field || field === '*') return records.length;\n return values.filter(v => v !== null && v !== undefined).length;\n \n case 'sum':\n case 'avg': {\n const nums = values.filter(v => typeof v === 'number');\n const sum = nums.reduce((a, b) => a + b, 0);\n if (func === 'sum') return sum;\n return nums.length > 0 ? sum / nums.length : null;\n }\n \n case 'min': {\n // Handle comparable values\n const valid = values.filter(v => v !== null && v !== undefined);\n if (valid.length === 0) return null;\n // Works for numbers and strings\n return valid.reduce((min, v) => (v < min ? v : min), valid[0]);\n }\n\n case 'max': {\n const valid = values.filter(v => v !== null && v !== undefined);\n if (valid.length === 0) return null;\n return valid.reduce((max, v) => (v > max ? v : max), valid[0]);\n }\n\n default:\n return null;\n }\n }\n\n private setValueByPath(obj: any, path: string, value: any) {\n const parts = path.split('.');\n let current = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!current[part]) current[part] = {};\n current = current[part];\n }\n current[parts[parts.length - 1]] = value;\n }\n\n // ===================================\n // Schema Management\n // ===================================\n\n async syncSchema(object: string, schema: any, options?: DriverOptions) {\n if (!this.db[object]) {\n this.db[object] = [];\n this.logger.info('Created in-memory table', { object });\n }\n }\n\n async dropTable(object: string, options?: DriverOptions) {\n if (this.db[object]) {\n const recordCount = this.db[object].length;\n delete this.db[object];\n this.logger.info('Dropped in-memory table', { object, recordCount });\n }\n }\n\n // ===================================\n // Helpers\n // ===================================\n\n /**\n * Apply manual sorting (Mingo sort has CJS build issues).\n */\n private applySort(records: any[], sortFields: any[]): any[] {\n const sorted = [...records];\n for (let i = sortFields.length - 1; i >= 0; i--) {\n const sortItem = sortFields[i];\n let field: string;\n let direction: string;\n if (typeof sortItem === 'object' && !Array.isArray(sortItem)) {\n field = sortItem.field;\n direction = sortItem.order || sortItem.direction || 'asc';\n } else if (Array.isArray(sortItem)) {\n [field, direction] = sortItem;\n } else {\n continue;\n }\n sorted.sort((a, b) => {\n const aVal = getValueByPath(a, field);\n const bVal = getValueByPath(b, field);\n if (aVal == null && bVal == null) return 0;\n if (aVal == null) return 1;\n if (bVal == null) return -1;\n if (aVal < bVal) return direction === 'desc' ? 1 : -1;\n if (aVal > bVal) return direction === 'desc' ? -1 : 1;\n return 0;\n });\n }\n return sorted;\n }\n\n /**\n * Project specific fields from a record.\n */\n private projectFields(record: any, fields: string[]): any {\n const result: any = {};\n for (const field of fields) {\n const value = getValueByPath(record, field);\n if (value !== undefined) {\n result[field] = value;\n }\n }\n // Always include id if not explicitly listed\n if (!fields.includes('id') && record.id !== undefined) {\n result.id = record.id;\n }\n return result;\n }\n\n private getTable(name: string) {\n if (!this.db[name]) {\n this.db[name] = [];\n }\n return this.db[name];\n }\n\n private generateId(objectName?: string) {\n const key = objectName || '_global';\n const counter = (this.idCounters.get(key) || 0) + 1;\n this.idCounters.set(key, counter);\n const timestamp = Date.now();\n return `${key}-${timestamp}-${counter}`;\n }\n\n // ===================================\n // Persistence\n // ===================================\n\n /**\n * Mark the database as dirty, triggering persistence save.\n */\n private markDirty(): void {\n if (this.persistenceAdapter) {\n this.persistenceAdapter.save(this.db);\n }\n }\n\n /**\n * Flush pending persistence writes to ensure data is safely stored.\n */\n async flush(): Promise {\n if (this.persistenceAdapter) {\n await this.persistenceAdapter.flush();\n }\n }\n\n /**\n * Detect whether the current runtime is a browser environment.\n */\n private isBrowserEnvironment(): boolean {\n return typeof globalThis.localStorage !== 'undefined';\n }\n\n /**\n * Detect whether the current runtime is a serverless/edge environment.\n *\n * Checks well-known environment variables set by serverless platforms:\n * - `VERCEL` / `VERCEL_ENV` — Vercel Functions / Edge\n * - `AWS_LAMBDA_FUNCTION_NAME` — AWS Lambda\n * - `NETLIFY` — Netlify Functions\n * - `FUNCTIONS_WORKER_RUNTIME` — Azure Functions\n * - `K_SERVICE` — Google Cloud Run / Cloud Functions\n * - `FUNCTION_TARGET` — Google Cloud Functions (Node.js)\n * - `DENO_DEPLOYMENT_ID` — Deno Deploy\n *\n * Returns `false` when `process` or `process.env` is unavailable\n * (e.g. browser or edge runtimes without a Node.js process object).\n */\n private isServerlessEnvironment(): boolean {\n if (typeof globalThis.process === 'undefined' || !globalThis.process.env) {\n return false;\n }\n const env = globalThis.process.env;\n return !!(\n env.VERCEL ||\n env.VERCEL_ENV ||\n env.AWS_LAMBDA_FUNCTION_NAME ||\n env.NETLIFY ||\n env.FUNCTIONS_WORKER_RUNTIME ||\n env.K_SERVICE ||\n env.FUNCTION_TARGET ||\n env.DENO_DEPLOYMENT_ID\n );\n }\n\n private static readonly SERVERLESS_PERSISTENCE_WARNING =\n 'Serverless environment detected — file-system persistence is disabled in auto mode. ' +\n 'Data will NOT be persisted across function invocations. ' +\n 'Set persistence: false to silence this warning, or provide a custom adapter ' +\n '(e.g. Upstash Redis, Vercel KV) via persistence: { adapter: yourAdapter }.';\n\n /**\n * Initialize the persistence adapter based on configuration.\n * Defaults to 'auto' when persistence is not specified.\n * Use `persistence: false` to explicitly disable persistence.\n *\n * In serverless environments (Vercel, AWS Lambda, etc.), auto mode disables\n * file-system persistence and emits a warning. Use `persistence: false` or\n * supply a custom adapter for serverless-safe operation.\n */\n private async initPersistence(): Promise {\n const persistence = this.config.persistence === undefined ? 'auto' : this.config.persistence;\n if (persistence === false) return;\n\n if (typeof persistence === 'string') {\n if (persistence === 'auto') {\n if (this.isBrowserEnvironment()) {\n const { LocalStoragePersistenceAdapter } = await import('./persistence/local-storage-adapter.js');\n this.persistenceAdapter = new LocalStoragePersistenceAdapter();\n this.logger.debug('Auto-detected browser environment, using localStorage persistence');\n } else if (this.isServerlessEnvironment()) {\n this.logger.warn(InMemoryDriver.SERVERLESS_PERSISTENCE_WARNING);\n } else {\n const { FileSystemPersistenceAdapter } = await import('./persistence/file-adapter.js');\n this.persistenceAdapter = new FileSystemPersistenceAdapter();\n this.logger.debug('Auto-detected Node.js environment, using file persistence');\n }\n } else if (persistence === 'file') {\n const { FileSystemPersistenceAdapter } = await import('./persistence/file-adapter.js');\n this.persistenceAdapter = new FileSystemPersistenceAdapter();\n } else if (persistence === 'local') {\n const { LocalStoragePersistenceAdapter } = await import('./persistence/local-storage-adapter.js');\n this.persistenceAdapter = new LocalStoragePersistenceAdapter();\n } else {\n throw new Error(`Unknown persistence type: \"${persistence}\". Use 'file', 'local', or 'auto'.`);\n }\n } else if ('adapter' in persistence && persistence.adapter) {\n this.persistenceAdapter = persistence.adapter;\n } else if ('type' in persistence) {\n if (persistence.type === 'auto') {\n if (this.isBrowserEnvironment()) {\n const { LocalStoragePersistenceAdapter } = await import('./persistence/local-storage-adapter.js');\n this.persistenceAdapter = new LocalStoragePersistenceAdapter({\n key: persistence.key,\n });\n this.logger.debug('Auto-detected browser environment, using localStorage persistence');\n } else if (this.isServerlessEnvironment()) {\n this.logger.warn(InMemoryDriver.SERVERLESS_PERSISTENCE_WARNING);\n } else {\n const { FileSystemPersistenceAdapter } = await import('./persistence/file-adapter.js');\n this.persistenceAdapter = new FileSystemPersistenceAdapter({\n path: persistence.path,\n autoSaveInterval: persistence.autoSaveInterval,\n });\n this.logger.debug('Auto-detected Node.js environment, using file persistence');\n }\n } else if (persistence.type === 'file') {\n const { FileSystemPersistenceAdapter } = await import('./persistence/file-adapter.js');\n this.persistenceAdapter = new FileSystemPersistenceAdapter({\n path: persistence.path,\n autoSaveInterval: persistence.autoSaveInterval,\n });\n } else if (persistence.type === 'local') {\n const { LocalStoragePersistenceAdapter } = await import('./persistence/local-storage-adapter.js');\n this.persistenceAdapter = new LocalStoragePersistenceAdapter({\n key: persistence.key,\n });\n }\n }\n\n if (this.persistenceAdapter) {\n this.logger.debug('Persistence adapter initialized');\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n\n/**\n * Simple In-Memory Query Matcher\n * \n * Implements a subset of the ObjectStack Filter Protocol (MongoDB-compatible)\n * for evaluating conditions against in-memory JavaScript objects.\n */\n\ntype RecordType = Record;\n\n/**\n * matches - Check if a record matches a filter criteria\n * @param record The data record to check\n * @param filter The filter condition (where clause)\n */\nexport function match(record: RecordType, filter: any): boolean {\n if (!filter || Object.keys(filter).length === 0) return true;\n \n // 1. Handle Top-Level Logical Operators ($and, $or, $not)\n // These usually appear at the root or nested.\n \n // $and: [ { ... }, { ... } ]\n if (Array.isArray(filter.$and)) {\n if (!filter.$and.every((f: any) => match(record, f))) {\n return false;\n }\n }\n \n // $or: [ { ... }, { ... } ]\n if (Array.isArray(filter.$or)) {\n if (!filter.$or.some((f: any) => match(record, f))) {\n return false;\n }\n }\n \n // $not: { ... }\n if (filter.$not) {\n if (match(record, filter.$not)) {\n return false;\n }\n }\n \n // 2. Iterate over field constraints\n for (const key of Object.keys(filter)) {\n // Skip logical operators we already handled (or future ones)\n if (key.startsWith('$')) continue;\n \n const condition = filter[key];\n const value = getValueByPath(record, key);\n \n if (!checkCondition(value, condition)) {\n return false;\n }\n }\n \n return true;\n}\n\n/**\n * Access nested properties via dot-notation (e.g. \"user.name\")\n */\nexport function getValueByPath(obj: any, path: string): any {\n if (!path.includes('.')) return obj[path];\n return path.split('.').reduce((o, i) => (o ? o[i] : undefined), obj);\n}\n\n/**\n * Evaluate a specific condition against a value\n */\nfunction checkCondition(value: any, condition: any): boolean {\n // Case A: Implicit Equality (e.g. status: 'active')\n // If condition is a primitive or Date/Array (exact match), treat as equality.\n if (\n typeof condition !== 'object' || \n condition === null || \n condition instanceof Date ||\n Array.isArray(condition)\n ) {\n // Loose equality to handle undefined/null mismatch or string/number coercion if desired.\n // But stick to == for JS loose equality which is often convenient in weakly typed queries.\n return value == condition;\n }\n \n // Case B: Operator Object (e.g. { $gt: 10, $lt: 20 })\n const keys = Object.keys(condition);\n const isOperatorObject = keys.some(k => k.startsWith('$'));\n \n if (!isOperatorObject) {\n // It's just a nested object comparison or implicit equality against an object\n // Simplistic check:\n return JSON.stringify(value) === JSON.stringify(condition);\n }\n\n // Iterate operators\n for (const op of keys) {\n const target = condition[op];\n \n // Handle undefined values\n if (value === undefined && op !== '$exists' && op !== '$ne' && op !== '$null') {\n return false; \n }\n\n switch (op) {\n case '$eq': \n if (value != target) return false; \n break;\n case '$ne': \n if (value == target) return false; \n break;\n \n // Numeric / Date\n case '$gt': \n if (!(value > target)) return false; \n break;\n case '$gte': \n if (!(value >= target)) return false; \n break;\n case '$lt': \n if (!(value < target)) return false; \n break;\n case '$lte': \n if (!(value <= target)) return false; \n break;\n case '$between':\n // target should be [min, max]\n if (Array.isArray(target) && (value < target[0] || value > target[1])) return false;\n break;\n\n // Sets\n case '$in': \n if (!Array.isArray(target) || !target.includes(value)) return false; \n break;\n case '$nin': \n if (Array.isArray(target) && target.includes(value)) return false; \n break;\n \n // Existence\n case '$exists':\n const exists = value !== undefined && value !== null;\n if (exists !== !!target) return false;\n break;\n\n // Strings\n case '$contains': \n if (typeof value !== 'string' || !value.includes(target)) return false; \n break;\n case '$notContains':\n if (typeof value !== 'string' || value.includes(target)) return false;\n break;\n case '$startsWith': \n if (typeof value !== 'string' || !value.startsWith(target)) return false; \n break;\n case '$endsWith': \n if (typeof value !== 'string' || !value.endsWith(target)) return false; \n break;\n case '$null':\n // $null: true → value must be null/undefined; $null: false → value must not be null/undefined\n if (target === true && value != null) return false;\n if (target === false && value == null) return false;\n break;\n case '$regex':\n try {\n const re = new RegExp(target, condition.$options || '');\n if (!re.test(String(value))) return false;\n } catch (e) { return false; }\n break;\n\n default: \n // Unknown operator, ignore or fail. Ignoring safe for optional features.\n break;\n }\n }\n \n return true;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { InMemoryDriver } from './memory-driver.js';\n\nexport { InMemoryDriver }; // Export class for direct usage\nexport type { InMemoryDriverConfig, PersistenceAdapterInterface } from './memory-driver.js';\n\nexport { FileSystemPersistenceAdapter } from './persistence/file-adapter.js';\nexport { LocalStoragePersistenceAdapter } from './persistence/local-storage-adapter.js';\n\nexport { MemoryAnalyticsService } from './memory-analytics.js';\nexport type { MemoryAnalyticsConfig } from './memory-analytics.js';\n\nexport { InMemoryStrategy } from './in-memory-strategy.js';\n\nexport default {\n id: 'com.objectstack.driver.memory',\n version: '1.0.0',\n\n onEnable: async (context: any) => {\n const { logger, config, drivers } = context;\n logger.info('[Memory Driver] Initializing...');\n\n if (drivers) {\n const driver = new InMemoryDriver(config);\n drivers.register(driver);\n logger.info(`[Memory Driver] Registered driver: ${driver.name}`);\n } else {\n logger.warn('[Memory Driver] No driver registry found in context.');\n }\n }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IAnalyticsService, AnalyticsResult, CubeMeta } from '@objectstack/spec/contracts';\nimport type { Cube, AnalyticsQuery } from '@objectstack/spec/data';\nimport type { InMemoryDriver } from './memory-driver.js';\nimport { Logger, createLogger } from '@objectstack/core';\n\n/**\n * Configuration for MemoryAnalyticsService\n */\nexport interface MemoryAnalyticsConfig {\n /** The data driver instance to use for queries */\n driver: InMemoryDriver;\n /** Cube definitions for the semantic layer */\n cubes: Cube[];\n /** Optional logger */\n logger?: Logger;\n}\n\n/**\n * Memory-Based Analytics Service\n * \n * Implements IAnalyticsService using InMemoryDriver's aggregation capabilities.\n * Provides a semantic layer (Cubes, Metrics, Dimensions) on top of in-memory data.\n * \n * Features:\n * - Cube-based semantic modeling\n * - Measure calculations (count, sum, avg, min, max, count_distinct)\n * - Dimension grouping\n * - Filter support\n * - Time dimension handling\n * - SQL generation (for debugging/transparency)\n * \n * This implementation is suitable for:\n * - Development and testing\n * - Local-first analytics\n * - Small to medium datasets\n * - Prototyping BI applications\n */\nexport class MemoryAnalyticsService implements IAnalyticsService {\n private driver: InMemoryDriver;\n private cubes: Map;\n private logger: Logger;\n\n constructor(config: MemoryAnalyticsConfig) {\n this.driver = config.driver;\n this.cubes = new Map(config.cubes.map(c => [c.name, c]));\n this.logger = config.logger || createLogger({ level: 'info', format: 'pretty' });\n this.logger.debug('MemoryAnalyticsService initialized', { cubeCount: this.cubes.size });\n }\n\n /**\n * Execute an analytical query using the memory driver's aggregation pipeline\n */\n async query(query: AnalyticsQuery): Promise {\n this.logger.debug('Executing analytics query', { cube: query.cube, measures: query.measures });\n\n // Get cube definition\n if (!query.cube) {\n throw new Error('Cube name is required');\n }\n const cube = this.cubes.get(query.cube);\n if (!cube) {\n throw new Error(`Cube not found: ${query.cube}`);\n }\n\n // Build MongoDB aggregation pipeline\n const pipeline: Record[] = [];\n\n // Stage 1: $match for filters\n if (query.filters && query.filters.length > 0) {\n const matchStage: Record = {};\n for (const filter of query.filters) {\n const mongoOp = this.convertOperatorToMongo(filter.operator);\n const fieldPath = this.resolveFieldPath(cube, filter.member);\n \n if (filter.values && filter.values.length > 0) {\n if (mongoOp === '$in') {\n matchStage[fieldPath] = { $in: filter.values };\n } else if (mongoOp === '$nin') {\n matchStage[fieldPath] = { $nin: filter.values };\n } else {\n matchStage[fieldPath] = { [mongoOp]: filter.values[0] };\n }\n } else if (mongoOp === '$exists') {\n matchStage[fieldPath] = { $exists: filter.operator === 'set' };\n }\n }\n if (Object.keys(matchStage).length > 0) {\n pipeline.push({ $match: matchStage });\n }\n }\n\n // Stage 2: Time dimension filters\n if (query.timeDimensions && query.timeDimensions.length > 0) {\n for (const timeDim of query.timeDimensions) {\n const fieldPath = this.resolveFieldPath(cube, timeDim.dimension);\n if (timeDim.dateRange) {\n const range = Array.isArray(timeDim.dateRange) \n ? timeDim.dateRange \n : this.parseDateRangeString(timeDim.dateRange);\n \n if (range.length === 2) {\n pipeline.push({\n $match: {\n [fieldPath]: {\n $gte: new Date(range[0]),\n $lte: new Date(range[1])\n }\n }\n });\n }\n }\n }\n }\n\n // Stage 3: $group for measures and dimensions\n const groupStage: Record = { _id: {} };\n \n // Add dimensions to _id\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n const fieldPath = this.resolveFieldPath(cube, dim);\n const dimName = this.getShortName(dim);\n groupStage._id[dimName] = `$${fieldPath}`;\n }\n } else {\n groupStage._id = null; // No grouping, aggregate all\n }\n\n // Add measures as computed fields\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const measureDef = this.resolveMeasure(cube, measure);\n const measureName = this.getShortName(measure);\n \n if (measureDef) {\n const aggregator = this.buildAggregator(measureDef);\n groupStage[measureName] = aggregator;\n }\n }\n }\n\n pipeline.push({ $group: groupStage });\n\n // Stage 4: $project to reshape results (use short names, we'll fix them later)\n const projectStage: Record = { _id: 0 };\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n const dimName = this.getShortName(dim);\n projectStage[dimName] = `$_id.${dimName}`;\n }\n }\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const measureName = this.getShortName(measure);\n projectStage[measureName] = `$${measureName}`;\n }\n }\n pipeline.push({ $project: projectStage });\n\n // Stage 5: $sort (use short names)\n if (query.order && Object.keys(query.order).length > 0) {\n const sortStage: Record = {};\n for (const [field, direction] of Object.entries(query.order)) {\n const shortName = this.getShortName(field);\n sortStage[shortName] = direction === 'asc' ? 1 : -1;\n }\n pipeline.push({ $sort: sortStage });\n }\n\n // Stage 6: $limit and $skip\n if (query.offset) {\n pipeline.push({ $skip: query.offset });\n }\n if (query.limit) {\n pipeline.push({ $limit: query.limit });\n }\n\n // Execute the aggregation pipeline\n const tableName = this.extractTableName(cube.sql);\n const rawRows = await this.driver.aggregate(tableName, pipeline);\n\n // Rename fields from short names to full cube.field names\n const rows = rawRows.map(row => {\n const renamedRow: Record = {};\n \n // Rename dimensions\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const shortName = this.getShortName(dim);\n if (shortName in row) {\n renamedRow[dim] = row[shortName];\n }\n }\n }\n \n // Rename measures\n if (query.measures) {\n for (const measure of query.measures) {\n const shortName = this.getShortName(measure);\n if (shortName in row) {\n renamedRow[measure] = row[shortName];\n }\n }\n }\n \n return renamedRow;\n });\n\n // Build field metadata\n const fields: Array<{ name: string; type: string }> = [];\n \n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const dimension = this.resolveDimension(cube, dim);\n fields.push({\n name: dim,\n type: dimension?.type || 'string'\n });\n }\n }\n \n if (query.measures) {\n for (const measure of query.measures) {\n const measureDef = this.resolveMeasure(cube, measure);\n fields.push({\n name: measure,\n type: this.measureTypeToFieldType(measureDef?.type || 'count')\n });\n }\n }\n\n this.logger.debug('Analytics query completed', { rowCount: rows.length });\n\n return {\n rows,\n fields,\n sql: this.generateSqlFromPipeline(tableName, pipeline) // For debugging\n };\n }\n\n /**\n * Get available cube metadata for discovery\n */\n async getMeta(cubeName?: string): Promise {\n const cubes = cubeName \n ? [this.cubes.get(cubeName)].filter(Boolean) as Cube[]\n : Array.from(this.cubes.values());\n\n return cubes.map(cube => ({\n name: cube.name,\n title: cube.title,\n measures: Object.entries(cube.measures).map(([key, measure]) => ({\n name: `${cube.name}.${key}`,\n type: measure.type,\n title: measure.label\n })),\n dimensions: Object.entries(cube.dimensions).map(([key, dimension]) => ({\n name: `${cube.name}.${key}`,\n type: dimension.type,\n title: dimension.label\n }))\n }));\n }\n\n /**\n * Generate SQL representation for debugging/transparency\n */\n async generateSql(query: AnalyticsQuery): Promise<{ sql: string; params: unknown[] }> {\n if (!query.cube) {\n throw new Error('Cube name is required');\n }\n const cube = this.cubes.get(query.cube);\n if (!cube) {\n throw new Error(`Cube not found: ${query.cube}`);\n }\n\n const tableName = this.extractTableName(cube.sql);\n const selectClauses: string[] = [];\n const groupByClauses: string[] = [];\n\n // Build SELECT for dimensions\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n const fieldPath = this.resolveFieldPath(cube, dim);\n selectClauses.push(`${fieldPath} AS \"${dim}\"`);\n groupByClauses.push(fieldPath);\n }\n }\n\n // Build SELECT for measures\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const measureDef = this.resolveMeasure(cube, measure);\n if (measureDef) {\n const aggSql = this.measureToSql(measureDef);\n selectClauses.push(`${aggSql} AS \"${measure}\"`);\n }\n }\n }\n\n // Build WHERE clause\n const whereClauses: string[] = [];\n if (query.filters && query.filters.length > 0) {\n for (const filter of query.filters) {\n const fieldPath = this.resolveFieldPath(cube, filter.member);\n const sqlOp = this.operatorToSql(filter.operator);\n if (filter.values && filter.values.length > 0) {\n whereClauses.push(`${fieldPath} ${sqlOp} '${filter.values[0]}'`);\n }\n }\n }\n\n let sql = `SELECT ${selectClauses.join(', ')} FROM ${tableName}`;\n if (whereClauses.length > 0) {\n sql += ` WHERE ${whereClauses.join(' AND ')}`;\n }\n if (groupByClauses.length > 0) {\n sql += ` GROUP BY ${groupByClauses.join(', ')}`;\n }\n if (query.order) {\n const orderClauses = Object.entries(query.order).map(([field, dir]) => \n `\"${field}\" ${dir.toUpperCase()}`\n );\n sql += ` ORDER BY ${orderClauses.join(', ')}`;\n }\n if (query.limit) {\n sql += ` LIMIT ${query.limit}`;\n }\n if (query.offset) {\n sql += ` OFFSET ${query.offset}`;\n }\n\n return { sql, params: [] };\n }\n\n // ===================================\n // Helper Methods\n // ===================================\n\n private resolveFieldPath(cube: Cube, member: string): string {\n // Handle both \"cube.field\" and \"field\" formats\n const parts = member.split('.');\n const fieldName = parts.length > 1 ? parts[1] : parts[0];\n\n // Check if it's a dimension\n const dimension = cube.dimensions[fieldName];\n if (dimension) {\n // Extract field path from SQL expression\n return dimension.sql.replace(/^\\$/, ''); // Remove $ prefix if present\n }\n\n // Check if it's a measure (for filters)\n const measure = cube.measures[fieldName];\n if (measure) {\n return measure.sql.replace(/^\\$/, '');\n }\n\n return fieldName;\n }\n\n private resolveMeasure(cube: Cube, measureName: string) {\n const parts = measureName.split('.');\n const fieldName = parts.length > 1 ? parts[1] : parts[0];\n return cube.measures[fieldName];\n }\n\n private resolveDimension(cube: Cube, dimensionName: string) {\n const parts = dimensionName.split('.');\n const fieldName = parts.length > 1 ? parts[1] : parts[0];\n return cube.dimensions[fieldName];\n }\n\n private getShortName(fullName: string): string {\n const parts = fullName.split('.');\n return parts.length > 1 ? parts[1] : parts[0];\n }\n\n private buildAggregator(measure: { type: string; sql: string; filters?: any[] }): any {\n const fieldPath = measure.sql.replace(/^\\$/, '');\n\n switch (measure.type) {\n case 'count':\n return { $sum: 1 };\n case 'sum':\n return { $sum: `$${fieldPath}` };\n case 'avg':\n return { $avg: `$${fieldPath}` };\n case 'min':\n return { $min: `$${fieldPath}` };\n case 'max':\n return { $max: `$${fieldPath}` };\n case 'count_distinct':\n return { $addToSet: `$${fieldPath}` }; // Will need post-processing for count\n default:\n return { $sum: 1 }; // Default to count\n }\n }\n\n private measureTypeToFieldType(measureType: string): string {\n switch (measureType) {\n case 'count':\n case 'sum':\n case 'count_distinct':\n return 'number';\n case 'avg':\n case 'min':\n case 'max':\n return 'number';\n case 'string':\n return 'string';\n case 'boolean':\n return 'boolean';\n default:\n return 'number';\n }\n }\n\n private convertOperatorToMongo(operator: string): string {\n const opMap: Record = {\n 'equals': '$eq',\n 'notEquals': '$ne',\n 'contains': '$regex',\n 'notContains': '$not',\n 'gt': '$gt',\n 'gte': '$gte',\n 'lt': '$lt',\n 'lte': '$lte',\n 'set': '$exists',\n 'notSet': '$exists',\n 'inDateRange': '$gte', // Will need special handling\n };\n return opMap[operator] || '$eq';\n }\n\n private operatorToSql(operator: string): string {\n const opMap: Record = {\n 'equals': '=',\n 'notEquals': '!=',\n 'contains': 'LIKE',\n 'notContains': 'NOT LIKE',\n 'gt': '>',\n 'gte': '>=',\n 'lt': '<',\n 'lte': '<=',\n };\n return opMap[operator] || '=';\n }\n\n private measureToSql(measure: { type: string; sql: string }): string {\n const fieldPath = measure.sql.replace(/^\\$/, '');\n \n switch (measure.type) {\n case 'count':\n return 'COUNT(*)';\n case 'sum':\n return `SUM(${fieldPath})`;\n case 'avg':\n return `AVG(${fieldPath})`;\n case 'min':\n return `MIN(${fieldPath})`;\n case 'max':\n return `MAX(${fieldPath})`;\n case 'count_distinct':\n return `COUNT(DISTINCT ${fieldPath})`;\n default:\n return 'COUNT(*)';\n }\n }\n\n private extractTableName(sql: string): string {\n // For simple table names, return as-is\n // For complex SQL, this would need more sophisticated parsing\n return sql.trim();\n }\n\n private parseDateRangeString(range: string): string[] {\n // Simple parser for common date range strings\n // In production, this would use a proper date range parser\n const now = new Date();\n const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n \n if (range === 'today') {\n return [today.toISOString(), new Date(today.getTime() + 86400000).toISOString()];\n } else if (range.startsWith('last ')) {\n const parts = range.split(' ');\n const num = parseInt(parts[1]);\n const unit = parts[2];\n const start = new Date(today);\n \n if (unit.startsWith('day')) {\n start.setDate(start.getDate() - num);\n } else if (unit.startsWith('week')) {\n start.setDate(start.getDate() - num * 7);\n } else if (unit.startsWith('month')) {\n start.setMonth(start.getMonth() - num);\n } else if (unit.startsWith('year')) {\n start.setFullYear(start.getFullYear() - num);\n }\n \n return [start.toISOString(), now.toISOString()];\n }\n \n return [range, range]; // Fallback\n }\n\n private generateSqlFromPipeline(table: string, pipeline: Record[]): string {\n // Simplified SQL generation for debugging\n // This is a basic representation of the aggregation pipeline\n const stages = pipeline.map((stage, idx) => {\n const op = Object.keys(stage)[0];\n return `/* Stage ${idx + 1}: ${op} */ ${JSON.stringify(stage[op])}`;\n }).join('\\n');\n \n return `-- MongoDB Aggregation Pipeline on table: ${table}\\n${stages}`;\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AnalyticsQuery, AnalyticsResult, AnalyticsStrategy, StrategyContext } from '@objectstack/spec/contracts';\n\n/**\n * InMemoryStrategy — Priority 3\n *\n * Delegates to an existing `IAnalyticsService` instance that was registered\n * as a fallback (typically `MemoryAnalyticsService` from this package).\n *\n * This is the lowest-priority strategy, used in:\n * - `dev` / `test` environments\n * - Any runtime where the backing driver is in-memory\n */\nexport class InMemoryStrategy implements AnalyticsStrategy {\n readonly name = 'InMemoryStrategy';\n readonly priority = 30;\n\n canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {\n if (!query.cube) return false;\n // Can handle when a fallback service exists\n if (ctx.fallbackService) return true;\n // Or when the driver is flagged as in-memory\n const caps = ctx.queryCapabilities(query.cube);\n return caps.inMemory;\n }\n\n async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise {\n if (!ctx.fallbackService) {\n throw new Error(\n `[InMemoryStrategy] No fallback analytics service available for cube \"${query.cube}\". ` +\n 'Register a MemoryAnalyticsService or configure a driver with analytics support.'\n );\n }\n return ctx.fallbackService.query(query);\n }\n\n async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {\n if (ctx.fallbackService?.generateSql) {\n return ctx.fallbackService.generateSql(query);\n }\n return {\n sql: `-- InMemoryStrategy: SQL generation not supported for cube \"${query.cube}\"`,\n params: [],\n };\n }\n}\n", "// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n", "// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n", "// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n", "// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return value.indexOf(\"%\") !== -1 ? tryDecode(value, decodeURIComponent_) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI\n};\n", "// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from \"./utils/url.js\";\nvar tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.#getParamValue(paramKey);\n return param && /\\%/.test(param) ? tryDecodeURIComponent(param) : param;\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = /\\%/.test(value) ? tryDecodeURIComponent(value) : value;\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n const requestInit = {\n body: await req[cacheKey](),\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers: req.header(),\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n", "// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n", "// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * \n * \n *

{content}

\n * \n * \n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();\n if (typeof arg === \"object\" && \"headers\" in arg) {\n const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);\n for (const [key, value] of argHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, { status, headers: responseHeaders });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n", "// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n", "// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n", "// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = url.pathname.slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = { basePath: this._basePath, path, method, handler };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} Env - env Object\n * @param {ExecutionContext} - context of execution\n * @returns {Response | Promise} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n", "// src/router/reg-exp-router/matcher.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nvar emptyParam = [];\nfunction match(method, path) {\n const matchers = this.buildAllMatchers();\n const match2 = ((method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match3 = path2.match(matcher[0]);\n if (!match3) {\n return [[], emptyParam];\n }\n const index = match3.indexOf(\"\", 1);\n return [matcher[1][index], match3];\n });\n this.match = match2;\n return match2(method, path);\n}\nexport {\n emptyParam,\n match\n};\n", "// src/router/reg-exp-router/node.ts\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = /* @__PURE__ */ Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class _Node {\n #index;\n #varIndex;\n #children = /* @__PURE__ */ Object.create(null);\n insert(tokens, index, paramMap, context, pathErrorCheckOnly) {\n if (tokens.length === 0) {\n if (this.#index !== void 0) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n this.#index = index;\n return;\n }\n const [token, ...restTokens] = tokens;\n const pattern = token === \"*\" ? restTokens.length === 0 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let node;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n if (regexpStr === \".*\") {\n throw PATH_ERROR;\n }\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n node = this.#children[regexpStr];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[regexpStr] = new _Node();\n if (name !== \"\") {\n node.#varIndex = context.varIndex++;\n }\n }\n if (!pathErrorCheckOnly && name !== \"\") {\n paramMap.push([name, node.#varIndex]);\n }\n } else {\n node = this.#children[token];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[token] = new _Node();\n }\n }\n node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.#children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.#children[k];\n return (typeof c.#varIndex === \"number\" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + c.buildRegExpStr();\n });\n if (typeof this.#index === \"number\") {\n strList.unshift(`#${this.#index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n Node,\n PATH_ERROR\n};\n", "// src/router/reg-exp-router/trie.ts\nimport { Node } from \"./node.js\";\nvar Trie = class {\n #context = { varIndex: 0 };\n #root = new Node();\n insert(path, index, pathErrorCheckOnly) {\n const paramAssoc = [];\n const groups = [];\n for (let i = 0; ; ) {\n let replaced = false;\n path = path.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = path.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);\n return paramAssoc;\n }\n buildRegExp() {\n let regexp = this.#root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (handlerIndex !== void 0) {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (paramIndex !== void 0) {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n", "// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport { PATH_ERROR } from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];\nvar wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n path === \"*\" ? \"\" : `^${path.replace(\n /\\/\\*$|([.\\\\+*[^\\]$()])/g,\n (_, metaChar) => metaChar ? `\\\\${metaChar}` : \"(?:|/.*)\"\n )}$`\n );\n}\nfunction clearWildcardRegExpCache() {\n wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\n}\nfunction buildMatcherFromPreprocessedRoutes(routes) {\n const trie = new Trie();\n const handlerData = [];\n if (routes.length === 0) {\n return nullMatcher;\n }\n const routesWithStaticPathFlag = routes.map(\n (route) => [!/\\*|\\/:/.test(route[0]), ...route]\n ).sort(\n ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length\n );\n const staticMap = /* @__PURE__ */ Object.create(null);\n for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {\n const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];\n if (pathErrorCheckOnly) {\n staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];\n } else {\n j++;\n }\n let paramAssoc;\n try {\n paramAssoc = trie.insert(path, j, pathErrorCheckOnly);\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n if (pathErrorCheckOnly) {\n continue;\n }\n handlerData[j] = handlers.map(([h, paramCount]) => {\n const paramIndexMap = /* @__PURE__ */ Object.create(null);\n paramCount -= 1;\n for (; paramCount >= 0; paramCount--) {\n const [key, value] = paramAssoc[paramCount];\n paramIndexMap[key] = value;\n }\n return [h, paramIndexMap];\n });\n }\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (let i = 0, len = handlerData.length; i < len; i++) {\n for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {\n const map = handlerData[i][j]?.[1];\n if (!map) {\n continue;\n }\n const keys = Object.keys(map);\n for (let k = 0, len3 = keys.length; k < len3; k++) {\n map[keys[k]] = paramReplacementMap[map[keys[k]]];\n }\n }\n }\n const handlerMap = [];\n for (const i in indexReplacementMap) {\n handlerMap[i] = handlerData[indexReplacementMap[i]];\n }\n return [regexp, handlerMap, staticMap];\n}\nfunction findMiddleware(middleware, path) {\n if (!middleware) {\n return void 0;\n }\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n #middleware;\n #routes;\n constructor() {\n this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n }\n add(method, path, handler) {\n const middleware = this.#middleware;\n const routes = this.#routes;\n if (!middleware || !routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n ;\n [middleware, routes].forEach((handlerMap) => {\n handlerMap[method] = /* @__PURE__ */ Object.create(null);\n Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n });\n });\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const paramCount = (path.match(/\\/:/g) || []).length;\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n if (method === METHOD_NAME_ALL) {\n Object.keys(middleware).forEach((m) => {\n middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n });\n } else {\n middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n Object.keys(middleware).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(middleware[m]).forEach((p) => {\n re.test(p) && middleware[m][p].push([handler, paramCount]);\n });\n }\n });\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(routes[m]).forEach(\n (p) => re.test(p) && routes[m][p].push([handler, paramCount])\n );\n }\n });\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (let i = 0, len = paths.length; i < len; i++) {\n const path2 = paths[i];\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n routes[m][path2] ||= [\n ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []\n ];\n routes[m][path2].push([handler, paramCount - len + i + 1]);\n }\n });\n }\n }\n match = match;\n buildAllMatchers() {\n const matchers = /* @__PURE__ */ Object.create(null);\n Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {\n matchers[method] ||= this.#buildMatcher(method);\n });\n this.#middleware = this.#routes = void 0;\n clearWildcardRegExpCache();\n return matchers;\n }\n #buildMatcher(method) {\n const routes = [];\n let hasOwnRoute = method === METHOD_NAME_ALL;\n [this.#middleware, this.#routes].forEach((r) => {\n const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];\n if (ownRoute.length !== 0) {\n hasOwnRoute ||= true;\n routes.push(...ownRoute);\n } else if (method !== METHOD_NAME_ALL) {\n routes.push(\n ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])\n );\n }\n });\n if (!hasOwnRoute) {\n return null;\n } else {\n return buildMatcherFromPreprocessedRoutes(routes);\n }\n }\n};\nexport {\n RegExpRouter\n};\n", "// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n #routers = [];\n #routes = [];\n constructor(init) {\n this.#routers = init.routers;\n }\n add(method, path, handler) {\n if (!this.#routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.#routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.#routes) {\n throw new Error(\"Fatal error\");\n }\n const routers = this.#routers;\n const routes = this.#routes;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {\n router.add(...routes[i2]);\n }\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.#routers = [router];\n this.#routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.#routes || this.#routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.#routers[0];\n }\n};\nexport {\n SmartRouter\n};\n", "// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nvar emptyParams = /* @__PURE__ */ Object.create(null);\nvar hasChildren = (children) => {\n for (const _ in children) {\n return true;\n }\n return false;\n};\nvar Node = class _Node {\n #methods;\n #children;\n #patterns;\n #order = 0;\n #params = emptyParams;\n constructor(method, handler, children) {\n this.#children = children || /* @__PURE__ */ Object.create(null);\n this.#methods = [];\n if (method && handler) {\n const m = /* @__PURE__ */ Object.create(null);\n m[method] = { handler, possibleKeys: [], score: 0 };\n this.#methods = [m];\n }\n this.#patterns = [];\n }\n insert(method, path, handler) {\n this.#order = ++this.#order;\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = [];\n for (let i = 0, len = parts.length; i < len; i++) {\n const p = parts[i];\n const nextP = parts[i + 1];\n const pattern = getPattern(p, nextP);\n const key = Array.isArray(pattern) ? pattern[0] : p;\n if (key in curNode.#children) {\n curNode = curNode.#children[key];\n if (pattern) {\n possibleKeys.push(pattern[1]);\n }\n continue;\n }\n curNode.#children[key] = new _Node();\n if (pattern) {\n curNode.#patterns.push(pattern);\n possibleKeys.push(pattern[1]);\n }\n curNode = curNode.#children[key];\n }\n curNode.#methods.push({\n [method]: {\n handler,\n possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),\n score: this.#order\n }\n });\n return curNode;\n }\n #pushHandlerSets(handlerSets, node, method, nodeParams, params) {\n for (let i = 0, len = node.#methods.length; i < len; i++) {\n const m = node.#methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n const processedSet = {};\n if (handlerSet !== void 0) {\n handlerSet.params = /* @__PURE__ */ Object.create(null);\n handlerSets.push(handlerSet);\n if (nodeParams !== emptyParams || params && params !== emptyParams) {\n for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {\n const key = handlerSet.possibleKeys[i2];\n const processed = processedSet[handlerSet.score];\n handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];\n processedSet[handlerSet.score] = true;\n }\n }\n }\n }\n }\n search(method, path) {\n const handlerSets = [];\n this.#params = emptyParams;\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n const curNodesQueue = [];\n const len = parts.length;\n let partOffsets = null;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.#children[part];\n if (nextNode) {\n nextNode.#params = node.#params;\n if (isLast) {\n if (nextNode.#children[\"*\"]) {\n this.#pushHandlerSets(handlerSets, nextNode.#children[\"*\"], method, node.#params);\n }\n this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {\n const pattern = node.#patterns[k];\n const params = node.#params === emptyParams ? {} : { ...node.#params };\n if (pattern === \"*\") {\n const astNode = node.#children[\"*\"];\n if (astNode) {\n this.#pushHandlerSets(handlerSets, astNode, method, node.#params);\n astNode.#params = params;\n tempNodes.push(astNode);\n }\n continue;\n }\n const [key, name, matcher] = pattern;\n if (!part && !(matcher instanceof RegExp)) {\n continue;\n }\n const child = node.#children[key];\n if (matcher instanceof RegExp) {\n if (partOffsets === null) {\n partOffsets = new Array(len);\n let offset = path[0] === \"/\" ? 1 : 0;\n for (let p = 0; p < len; p++) {\n partOffsets[p] = offset;\n offset += parts[p].length + 1;\n }\n }\n const restPathString = path.substring(partOffsets[i]);\n const m = matcher.exec(restPathString);\n if (m) {\n params[name] = m[0];\n this.#pushHandlerSets(handlerSets, child, method, node.#params, params);\n if (hasChildren(child.#children)) {\n child.#params = params;\n const componentCount = m[0].match(/\\//)?.length ?? 0;\n const targetCurNodes = curNodesQueue[componentCount] ||= [];\n targetCurNodes.push(child);\n }\n continue;\n }\n }\n if (matcher === true || matcher.test(part)) {\n params[name] = part;\n if (isLast) {\n this.#pushHandlerSets(handlerSets, child, method, params, node.#params);\n if (child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n params,\n node.#params\n );\n }\n } else {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n const shifted = curNodesQueue.shift();\n curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;\n }\n if (handlerSets.length > 1) {\n handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n }\n return [handlerSets.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n", "// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n #node;\n constructor() {\n this.#node = new Node();\n }\n add(method, path, handler) {\n const results = checkOptionalParameter(path);\n if (results) {\n for (let i = 0, len = results.length; i < len; i++) {\n this.#node.insert(method, results[i], handler);\n }\n return;\n }\n this.#node.insert(method, path, handler);\n }\n match(method, path) {\n return this.#node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n", "// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n /**\n * Creates an instance of the Hono class.\n *\n * @param options - Optional configuration options for the Hono instance.\n */\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Hono } from 'hono';\nimport { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime';\n\nexport interface ObjectStackHonoOptions {\n kernel: ObjectKernel;\n prefix?: string;\n}\n\n/**\n * Auth service interface with handleRequest method\n */\ninterface AuthService {\n handleRequest(request: Request): Promise;\n}\n\n/**\n * Middleware mode for existing Hono apps\n */\nexport function objectStackMiddleware(kernel: ObjectKernel) {\n return async (c: any, next: any) => {\n c.set('objectStack', kernel);\n await next();\n };\n}\n\n/**\n * Creates a full-featured Hono app with all ObjectStack route dispatchers.\n *\n * Only routes that need framework-specific handling (auth service, storage\n * formData, GraphQL raw result, discovery wrapper) are registered explicitly.\n * All other routes (meta, data, packages, analytics, automation, i18n, ui,\n * openapi, custom endpoints, and any future routes) are handled by a\n * catch-all that delegates to `HttpDispatcher.dispatch()`.\n *\n * This means new routes added to `HttpDispatcher` automatically work in\n * every adapter without any adapter-side code changes.\n *\n * @example\n * ```ts\n * import { createHonoApp } from '@objectstack/hono';\n * const app = createHonoApp({ kernel });\n * export default app;\n * ```\n */\nexport function createHonoApp(options: ObjectStackHonoOptions): Hono {\n const app = new Hono();\n const prefix = options.prefix || '/api';\n const dispatcher = new HttpDispatcher(options.kernel);\n\n const errorJson = (c: any, message: string, code: number = 500) => {\n return c.json({ success: false, error: { message, code } }, code);\n };\n\n const toResponse = (c: any, result: HttpDispatcherResult) => {\n if (result.handled) {\n if (result.response) {\n if (result.response.headers) {\n Object.entries(result.response.headers).forEach(([k, v]) => c.header(k, v as string));\n }\n return c.json(result.response.body, result.response.status);\n }\n if (result.result) {\n const res = result.result;\n if (res.type === 'redirect' && res.url) {\n return c.redirect(res.url);\n }\n if (res.type === 'stream' && res.events) {\n // SSE / Vercel Data Stream streaming response\n const headers: Record = {\n 'Content-Type': res.contentType || 'text/event-stream',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n ...(res.headers || {}),\n };\n const stream = new ReadableStream({\n async start(controller) {\n try {\n const encoder = new TextEncoder();\n for await (const event of res.events) {\n const chunk = res.vercelDataStream\n ? (typeof event === 'string' ? event : JSON.stringify(event) + '\\n')\n : `data: ${JSON.stringify(event)}\\n\\n`;\n controller.enqueue(encoder.encode(chunk));\n }\n } catch (err) {\n // Stream error — close gracefully\n } finally {\n controller.close();\n }\n },\n });\n return new Response(stream, { status: 200, headers });\n }\n if (res.type === 'stream' && res.stream) {\n if (res.headers) {\n Object.entries(res.headers).forEach(([k, v]) => c.header(k, v as string));\n }\n return new Response(res.stream, { status: 200 });\n }\n return c.json(res, 200);\n }\n }\n return errorJson(c, 'Not Found', 404);\n };\n\n // ─── Explicit routes (framework-specific handling required) ────────────────\n\n // --- Discovery ---\n app.get(prefix, async (c) => {\n return c.json({ data: await dispatcher.getDiscoveryInfo(prefix) });\n });\n\n app.get(`${prefix}/discovery`, async (c) => {\n return c.json({ data: await dispatcher.getDiscoveryInfo(prefix) });\n });\n\n // --- .well-known ---\n app.get('/.well-known/objectstack', (c) => {\n return c.redirect(prefix);\n });\n\n // --- Auth (needs auth service integration) ---\n app.all(`${prefix}/auth/*`, async (c) => {\n try {\n const path = c.req.path.substring(`${prefix}/auth/`.length);\n const method = c.req.method;\n\n // Try AuthPlugin service first (prefer async to support factory-based services)\n let authService: AuthService | null = null;\n try {\n if (typeof options.kernel.getServiceAsync === 'function') {\n authService = await options.kernel.getServiceAsync('auth');\n } else if (typeof options.kernel.getService === 'function') {\n authService = options.kernel.getService('auth');\n }\n } catch {\n // Service not registered — fall through to dispatcher\n authService = null;\n }\n\n if (authService && typeof authService.handleRequest === 'function') {\n const response = await authService.handleRequest(c.req.raw);\n return new Response(response.body, {\n status: response.status,\n headers: response.headers,\n });\n }\n\n // Fallback to legacy dispatcher\n const body = method === 'GET' || method === 'HEAD'\n ? {}\n : await c.req.json().catch(() => ({}));\n const result = await dispatcher.handleAuth(path, method, body, { request: c.req.raw });\n return toResponse(c, result);\n } catch (err: any) {\n return errorJson(c, err.message || 'Internal Server Error', err.statusCode || 500);\n }\n });\n\n // --- GraphQL (returns raw result, not HttpDispatcherResult) ---\n app.post(`${prefix}/graphql`, async (c) => {\n try {\n const body = await c.req.json();\n const result = await dispatcher.handleGraphQL(body, { request: c.req.raw });\n return c.json(result);\n } catch (err: any) {\n return errorJson(c, err.message || 'Internal Server Error', err.statusCode || 500);\n }\n });\n\n // --- Storage (needs formData parsing) ---\n app.all(`${prefix}/storage/*`, async (c) => {\n try {\n const subPath = c.req.path.substring(`${prefix}/storage`.length);\n const method = c.req.method;\n\n let file: any = undefined;\n if (method === 'POST' && subPath === '/upload') {\n const formData = await c.req.formData();\n file = formData.get('file');\n }\n\n const result = await dispatcher.handleStorage(subPath, method, file, { request: c.req.raw });\n return toResponse(c, result);\n } catch (err: any) {\n return errorJson(c, err.message || 'Internal Server Error', err.statusCode || 500);\n }\n });\n\n // ─── Catch-all: delegate to dispatcher.dispatch() ─────────────────────────\n // Handles meta, data, packages, analytics, automation, i18n, ui, openapi,\n // custom API endpoints, and any future routes added to HttpDispatcher.\n app.all(`${prefix}/*`, async (c) => {\n try {\n const subPath = c.req.path.substring(prefix.length);\n const method = c.req.method;\n\n let body: any = undefined;\n if (method === 'POST' || method === 'PUT' || method === 'PATCH') {\n body = await c.req.json().catch(() => ({}));\n }\n\n const queryParams: Record = {};\n const url = new URL(c.req.url);\n url.searchParams.forEach((val, key) => { queryParams[key] = val; });\n\n const result = await dispatcher.dispatch(method, subPath, body, queryParams, { request: c.req.raw }, prefix);\n return toResponse(c, result);\n } catch (err: any) {\n return errorJson(c, err.message || 'Internal Server Error', err.statusCode || 500);\n }\n });\n\n return app;\n}\n", "//#region src/utils/wildcard.ts\n/**\n* Escapes a character if it has a special meaning in regular expressions\n* and returns the character as is if it doesn't\n*/\nfunction escapeRegExpChar(char) {\n\tif (char === \"-\" || char === \"^\" || char === \"$\" || char === \"+\" || char === \".\" || char === \"(\" || char === \")\" || char === \"|\" || char === \"[\" || char === \"]\" || char === \"{\" || char === \"}\" || char === \"*\" || char === \"?\" || char === \"\\\\\") return `\\\\${char}`;\n\telse return char;\n}\n/**\n* Escapes all characters in a given string that have a special meaning in regular expressions\n*/\nfunction escapeRegExpString(str) {\n\tlet result = \"\";\n\tfor (let i = 0; i < str.length; i++) result += escapeRegExpChar(str[i]);\n\treturn result;\n}\n/**\n* Transforms one or more glob patterns into a RegExp pattern\n*/\nfunction transform(pattern, separator = true) {\n\tif (Array.isArray(pattern)) return `(?:${pattern.map((p) => `^${transform(p, separator)}$`).join(\"|\")})`;\n\tlet separatorSplitter = \"\";\n\tlet separatorMatcher = \"\";\n\tlet wildcard = \".\";\n\tif (separator === true) {\n\t\tseparatorSplitter = \"/\";\n\t\tseparatorMatcher = \"[/\\\\\\\\]\";\n\t\twildcard = \"[^/\\\\\\\\]\";\n\t} else if (separator) {\n\t\tseparatorSplitter = separator;\n\t\tseparatorMatcher = escapeRegExpString(separatorSplitter);\n\t\tif (separatorMatcher.length > 1) {\n\t\t\tseparatorMatcher = `(?:${separatorMatcher})`;\n\t\t\twildcard = `((?!${separatorMatcher}).)`;\n\t\t} else wildcard = `[^${separatorMatcher}]`;\n\t}\n\tconst requiredSeparator = separator ? `${separatorMatcher}+?` : \"\";\n\tconst optionalSeparator = separator ? `${separatorMatcher}*?` : \"\";\n\tconst segments = separator ? pattern.split(separatorSplitter) : [pattern];\n\tlet result = \"\";\n\tfor (let s = 0; s < segments.length; s++) {\n\t\tconst segment = segments[s];\n\t\tconst nextSegment = segments[s + 1];\n\t\tlet currentSeparator = \"\";\n\t\tif (!segment && s > 0) continue;\n\t\tif (separator) if (s === segments.length - 1) currentSeparator = optionalSeparator;\n\t\telse if (nextSegment !== \"**\") currentSeparator = requiredSeparator;\n\t\telse currentSeparator = \"\";\n\t\tif (separator && segment === \"**\") {\n\t\t\tif (currentSeparator) {\n\t\t\t\tresult += s === 0 ? \"\" : currentSeparator;\n\t\t\t\tresult += `(?:${wildcard}*?${currentSeparator})*?`;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (let c = 0; c < segment.length; c++) {\n\t\t\tconst char = segment[c];\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tif (c < segment.length - 1) {\n\t\t\t\t\tresult += escapeRegExpChar(segment[c + 1]);\n\t\t\t\t\tc++;\n\t\t\t\t}\n\t\t\t} else if (char === \"?\") result += wildcard;\n\t\t\telse if (char === \"*\") result += `${wildcard}*?`;\n\t\t\telse result += escapeRegExpChar(char);\n\t\t}\n\t\tresult += currentSeparator;\n\t}\n\treturn result;\n}\nfunction isMatch(regexp, sample) {\n\tif (typeof sample !== \"string\") throw new TypeError(`Sample must be a string, but ${typeof sample} given`);\n\treturn regexp.test(sample);\n}\n/**\n* Compiles one or more glob patterns into a RegExp and returns an isMatch function.\n* The isMatch function takes a sample string as its only argument and returns `true`\n* if the string matches the pattern(s).\n*\n* ```js\n* wildcardMatch('src/*.js')('src/index.js') //=> true\n* ```\n*\n* ```js\n* const isMatch = wildcardMatch('*.example.com', '.')\n* isMatch('foo.example.com') //=> true\n* isMatch('foo.bar.com') //=> false\n* ```\n*/\nfunction wildcardMatch(pattern, options) {\n\tif (typeof pattern !== \"string\" && !Array.isArray(pattern)) throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`);\n\tif (typeof options === \"string\" || typeof options === \"boolean\") options = { separator: options };\n\tif (arguments.length === 2 && !(typeof options === \"undefined\" || typeof options === \"object\" && options !== null && !Array.isArray(options))) throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof options} given`);\n\toptions = options || {};\n\tif (options.separator === \"\\\\\") throw new Error(\"\\\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead\");\n\tconst regexpPattern = transform(pattern, options.separator);\n\tconst regexp = new RegExp(`^${regexpPattern}$`, options.flags);\n\tconst fn = isMatch.bind(null, regexp);\n\tfn.options = options;\n\tfn.pattern = pattern;\n\tfn.regexp = regexp;\n\treturn fn;\n}\n//#endregion\nexport { wildcardMatch };\n", "import { wildcardMatch } from \"./wildcard.mjs\";\nimport { env } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/utils/url.ts\nfunction checkHasPath(url) {\n\ttry {\n\t\treturn (new URL(url).pathname.replace(/\\/+$/, \"\") || \"/\") !== \"/\";\n\t} catch {\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`);\n\t}\n}\nfunction assertHasProtocol(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\tif (parsedUrl.protocol !== \"http:\" && parsedUrl.protocol !== \"https:\") throw new BetterAuthError(`Invalid base URL: ${url}. URL must include 'http://' or 'https://'`);\n\t} catch (error) {\n\t\tif (error instanceof BetterAuthError) throw error;\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`, { cause: error });\n\t}\n}\nfunction withPath(url, path = \"/api/auth\") {\n\tassertHasProtocol(url);\n\tif (checkHasPath(url)) return url;\n\tconst trimmedUrl = url.replace(/\\/+$/, \"\");\n\tif (!path || path === \"/\") return trimmedUrl;\n\tpath = path.startsWith(\"/\") ? path : `/${path}`;\n\treturn `${trimmedUrl}${path}`;\n}\nfunction validateProxyHeader(header, type) {\n\tif (!header || header.trim() === \"\") return false;\n\tif (type === \"proto\") return header === \"http\" || header === \"https\";\n\tif (type === \"host\") {\n\t\tif ([\n\t\t\t/\\.\\./,\n\t\t\t/\\0/,\n\t\t\t/[\\s]/,\n\t\t\t/^[.]/,\n\t\t\t/[<>'\"]/,\n\t\t\t/javascript:/i,\n\t\t\t/file:/i,\n\t\t\t/data:/i\n\t\t].some((pattern) => pattern.test(header))) return false;\n\t\treturn /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(header) || /^(\\d{1,3}\\.){3}\\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\\[[0-9a-fA-F:]+\\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header);\n\t}\n\treturn false;\n}\nfunction getBaseURL(url, path, request, loadEnv, trustedProxyHeaders) {\n\tif (url) return withPath(url, path);\n\tif (loadEnv !== false) {\n\t\tconst fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== \"/\" ? env.BASE_URL : void 0);\n\t\tif (fromEnv) return withPath(fromEnv, path);\n\t}\n\tconst fromRequest = request?.headers.get(\"x-forwarded-host\");\n\tconst fromRequestProto = request?.headers.get(\"x-forwarded-proto\");\n\tif (fromRequest && fromRequestProto && trustedProxyHeaders) {\n\t\tif (validateProxyHeader(fromRequestProto, \"proto\") && validateProxyHeader(fromRequest, \"host\")) try {\n\t\t\treturn withPath(`${fromRequestProto}://${fromRequest}`, path);\n\t\t} catch (_error) {}\n\t}\n\tif (request) {\n\t\tconst url = getOrigin(request.url);\n\t\tif (!url) throw new BetterAuthError(\"Could not get origin from request. Please provide a valid base URL.\");\n\t\treturn withPath(url, path);\n\t}\n\tif (typeof window !== \"undefined\" && window.location) return withPath(window.location.origin, path);\n}\nfunction getOrigin(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\treturn parsedUrl.origin === \"null\" ? null : parsedUrl.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getProtocol(url) {\n\ttry {\n\t\treturn new URL(url).protocol;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getHost(url) {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Checks if the baseURL config is a dynamic config object\n*/\nfunction isDynamicBaseURLConfig(config) {\n\treturn typeof config === \"object\" && config !== null && \"allowedHosts\" in config && Array.isArray(config.allowedHosts);\n}\n/**\n* Extracts the host from the request headers.\n* Tries x-forwarded-host first (for proxy setups), then falls back to host header.\n*\n* @param request The incoming request\n* @returns The host string or null if not found\n*/\nfunction getHostFromRequest(request) {\n\tconst forwardedHost = request.headers.get(\"x-forwarded-host\");\n\tif (forwardedHost && validateProxyHeader(forwardedHost, \"host\")) return forwardedHost;\n\tconst host = request.headers.get(\"host\");\n\tif (host && validateProxyHeader(host, \"host\")) return host;\n\ttry {\n\t\treturn new URL(request.url).host;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Extracts the protocol from the request headers.\n* Tries x-forwarded-proto first (for proxy setups), then infers from request URL.\n*\n* @param request The incoming request\n* @param configProtocol Protocol override from config\n* @returns The protocol (\"http\" or \"https\")\n*/\nfunction getProtocolFromRequest(request, configProtocol) {\n\tif (configProtocol === \"http\" || configProtocol === \"https\") return configProtocol;\n\tconst forwardedProto = request.headers.get(\"x-forwarded-proto\");\n\tif (forwardedProto && validateProxyHeader(forwardedProto, \"proto\")) return forwardedProto;\n\ttry {\n\t\tconst url = new URL(request.url);\n\t\tif (url.protocol === \"http:\" || url.protocol === \"https:\") return url.protocol.slice(0, -1);\n\t} catch {}\n\treturn \"https\";\n}\n/**\n* Matches a hostname against a host pattern.\n* Supports wildcard patterns like `*.vercel.app` or `preview-*.myapp.com`.\n*\n* @param host The hostname to test (e.g., \"myapp.com\", \"preview-123.vercel.app\")\n* @param pattern The host pattern (e.g., \"myapp.com\", \"*.vercel.app\")\n* @returns {boolean} true if the host matches the pattern, false otherwise.\n*\n* @example\n* ```ts\n* matchesHostPattern(\"myapp.com\", \"myapp.com\") // true\n* matchesHostPattern(\"preview-123.vercel.app\", \"*.vercel.app\") // true\n* matchesHostPattern(\"preview-123.myapp.com\", \"preview-*.myapp.com\") // true\n* matchesHostPattern(\"evil.com\", \"myapp.com\") // false\n* ```\n*/\nconst matchesHostPattern = (host, pattern) => {\n\tif (!host || !pattern) return false;\n\tconst normalizedHost = host.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tconst normalizedPattern = pattern.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tif (normalizedPattern.includes(\"*\") || normalizedPattern.includes(\"?\")) return wildcardMatch(normalizedPattern)(normalizedHost);\n\treturn normalizedHost.toLowerCase() === normalizedPattern.toLowerCase();\n};\n/**\n* Resolves the base URL from a dynamic config based on the incoming request.\n* Validates the derived host against the allowedHosts allowlist.\n*\n* @param config The dynamic base URL config\n* @param request The incoming request\n* @param basePath The base path to append\n* @returns The resolved base URL with path\n* @throws BetterAuthError if host is not in allowedHosts and no fallback is set\n*/\nfunction resolveDynamicBaseURL(config, request, basePath) {\n\tconst host = getHostFromRequest(request);\n\tif (!host) {\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\tthrow new BetterAuthError(\"Could not determine host from request headers. Please provide a fallback URL in your baseURL config.\");\n\t}\n\tif (config.allowedHosts.some((pattern) => matchesHostPattern(host, pattern))) return withPath(`${getProtocolFromRequest(request, config.protocol)}://${host}`, basePath);\n\tif (config.fallback) return withPath(config.fallback, basePath);\n\tthrow new BetterAuthError(`Host \"${host}\" is not in the allowed hosts list. Allowed hosts: ${config.allowedHosts.join(\", \")}. Add this host to your allowedHosts config or provide a fallback URL.`);\n}\n/**\n* Resolves the base URL from any config type (static string or dynamic object).\n* This is the main entry point for base URL resolution.\n*\n* @param config The base URL config (string or object)\n* @param basePath The base path to append\n* @param request Optional request for dynamic resolution\n* @param loadEnv Whether to load from environment variables\n* @param trustedProxyHeaders Whether to trust proxy headers (for legacy behavior)\n* @returns The resolved base URL with path\n*/\nfunction resolveBaseURL(config, basePath, request, loadEnv, trustedProxyHeaders) {\n\tif (isDynamicBaseURLConfig(config)) {\n\t\tif (request) return resolveDynamicBaseURL(config, request, basePath);\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\treturn getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders);\n\t}\n\tif (typeof config === \"string\") return getBaseURL(config, basePath, request, loadEnv, trustedProxyHeaders);\n\treturn getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders);\n}\n//#endregion\nexport { getBaseURL, getHost, getHostFromRequest, getOrigin, getProtocol, getProtocolFromRequest, isDynamicBaseURLConfig, matchesHostPattern, resolveBaseURL, resolveDynamicBaseURL };\n", "import { createRandomStringGenerator } from \"@better-auth/utils/random\";\n//#region src/crypto/random.ts\nconst generateRandomString = createRandomStringGenerator(\"a-z\", \"0-9\", \"A-Z\", \"-_\");\n//#endregion\nexport { generateRandomString };\n", "//#region src/crypto/buffer.ts\n/**\n* Compare two buffers in constant time.\n*/\nfunction constantTimeEqual(a, b) {\n\tif (typeof a === \"string\") a = new TextEncoder().encode(a);\n\tif (typeof b === \"string\") b = new TextEncoder().encode(b);\n\tconst aBuffer = new Uint8Array(a);\n\tconst bBuffer = new Uint8Array(b);\n\tlet c = aBuffer.length ^ bBuffer.length;\n\tconst length = Math.max(aBuffer.length, bBuffer.length);\n\tfor (let i = 0; i < length; i++) c |= (i < aBuffer.length ? aBuffer[i] : 0) ^ (i < bBuffer.length ? bBuffer[i] : 0);\n\treturn c === 0;\n}\n//#endregion\nexport { constantTimeEqual };\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n value: TArg,\n length?: number,\n title: string = ''\n): TRet {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg): TRet {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg): TRet {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg): TRet {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg): TRet {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg) => TRet = isLE\n ? (u: TArg) => u as TRet\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg, errorTitle = ''): TRet {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg): TRet {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg): TRet;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet;\n};\n/** Callable hash function type. */\nexport type CHash = Hash, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg): TRet;\n create(): T;\n }\n : {\n (msg: TArg, opts?: TArg): TRet;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: TArg = {}\n): TRet> {\n const hashC: any = (msg: TArg, opts?: TArg) =>\n hashCons(opts as Opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet> => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport {\n abytes,\n aexists,\n ahash,\n aoutput,\n clean,\n type CHash,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC> implements Hash<_HMAC> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n canXOF = false;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: TArg, key: TArg) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: TArg): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: TArg): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest(): TRet {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out as TRet;\n }\n _cloneInto(to?: _HMAC): _HMAC {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - authentication key bytes\n * @param message - message bytes to authenticate\n * @returns Authentication tag bytes.\n * @example\n * Compute an RFC 2104 HMAC.\n * ```ts\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\ntype HmacFn = {\n (hash: TArg, key: TArg, message: TArg): TRet;\n create(hash: TArg, key: TArg): TRet<_HMAC>;\n};\nexport const hmac: TRet = /* @__PURE__ */ (() => {\n const hmac_ = ((\n hash: TArg,\n key: TArg,\n message: TArg\n ): TRet => new _HMAC(hash, key).update(message).digest()) as TRet;\n hmac_.create = (hash: TArg, key: TArg): TRet<_HMAC> =>\n new _HMAC(hash, key) as TRet<_HMAC>;\n return hmac_;\n})();\n", "/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.\n * @module\n */\nimport { hmac } from './hmac.ts';\nimport { abytes, ahash, anumber, type CHash, clean, type TArg, type TRet } from './utils.ts';\n\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @returns Pseudorandom key derived from input keying material.\n * @example\n * Run the HKDF extract step.\n * ```ts\n * import { extract } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\nexport function extract(\n hash: TArg,\n ikm: TArg,\n salt?: TArg\n): TRet {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined) salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\n\n// Shared mutable scratch byte for the RFC 5869 block counter `N`.\n// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);\n// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets\n * (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material with the requested length.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * Run the HKDF expand step.\n * ```ts\n * import { expand } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);\n * ```\n */\nexport function expand(\n hash: TArg,\n prk: TArg,\n info?: TArg,\n length: number = 32\n): TRet {\n ahash(hash);\n anumber(length, 'length');\n abytes(prk, undefined, 'prk');\n const olen = hash.outputLen;\n // RFC 5869 \u00A72.3: PRK is \"a pseudorandom key of at least HashLen octets\".\n if (prk.length < olen) throw new Error('\"prk\" must be at least HashLen octets');\n // RFC 5869 \u00A72.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.\n if (length > 255 * olen) throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined) info = EMPTY_BUFFER;\n else abytes(info, undefined, 'info');\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * olen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, olen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n clean(T, HKDF_COUNTER);\n return okm.slice(0, length) as TRet;\n}\n\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information bytes\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material derived from the input key.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * HKDF (RFC 5869): derive keys from an initial input.\n * ```ts\n * import { hkdf } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = utf8ToBytes('application-key');\n * const okm = hkdf(sha256, inputKey, salt, info, 32);\n * ```\n */\nexport const hkdf = (\n hash: TArg,\n ikm: TArg,\n salt: TArg,\n info: TArg,\n length: number\n): TRet => expand(hash, extract(hash, ikm, salt), info, length);\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD> implements Hash {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly canXOF = false;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: TArg): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: TArg): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): TRet {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n", "import { encoder, decoder } from '../lib/buffer_utils.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nexport function decode(input) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {\n alphabet: 'base64url',\n });\n }\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');\n try {\n return decodeBase64(encoded);\n }\n catch {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n}\nexport function encode(input) {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n if (Uint8Array.prototype.toBase64) {\n return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });\n }\n return encodeBase64(unencoded).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n", "export const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers) {\n buf.set(buffer, i);\n i += buffer.length;\n }\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function encode(string) {\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127) {\n throw new TypeError('non-ASCII string encountered in encode()');\n }\n bytes[i] = code;\n }\n return bytes;\n}\n", "export function encodeBase64(input) {\n if (Uint8Array.prototype.toBase64) {\n return input.toBase64();\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n}\nexport function decodeBase64(encoded) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(encoded);\n }\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n", "const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nconst isAlgorithm = (algorithm, name) => algorithm.name === name;\nfunction getHashLength(hash) {\n return parseInt(hash.name.slice(4), 10);\n}\nfunction checkHashLength(algorithm, expected) {\n const actual = getHashLength(algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n}\nfunction getNamedCurve(alg) {\n switch (alg) {\n case 'ES256':\n return 'P-256';\n case 'ES384':\n return 'P-384';\n case 'ES512':\n return 'P-521';\n default:\n throw new Error('unreachable');\n }\n}\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage)) {\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n }\n}\nexport function checkSigCryptoKey(key, alg, usage) {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512': {\n if (!isAlgorithm(key.algorithm, 'HMAC'))\n throw unusable('HMAC');\n checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n break;\n }\n case 'RS256':\n case 'RS384':\n case 'RS512': {\n if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n throw unusable('RSASSA-PKCS1-v1_5');\n checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n break;\n }\n case 'PS256':\n case 'PS384':\n case 'PS512': {\n if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n throw unusable('RSA-PSS');\n checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n break;\n }\n case 'Ed25519':\n case 'EdDSA': {\n if (!isAlgorithm(key.algorithm, 'Ed25519'))\n throw unusable('Ed25519');\n break;\n }\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87': {\n if (!isAlgorithm(key.algorithm, alg))\n throw unusable(alg);\n break;\n }\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n if (!isAlgorithm(key.algorithm, 'ECDSA'))\n throw unusable('ECDSA');\n const expected = getNamedCurve(alg);\n const actual = key.algorithm.namedCurve;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.namedCurve');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usage);\n}\nexport function checkEncCryptoKey(key, alg, usage) {\n switch (alg) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM': {\n if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n throw unusable('AES-GCM');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (!isAlgorithm(key.algorithm, 'AES-KW'))\n throw unusable('AES-KW');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'ECDH': {\n switch (key.algorithm.name) {\n case 'ECDH':\n case 'X25519':\n break;\n default:\n throw unusable('ECDH or X25519');\n }\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW':\n if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n throw unusable('PBKDF2');\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n throw unusable('RSA-OAEP');\n checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1);\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usage);\n}\n", "function message(msg, actual, ...types) {\n types = types.filter(Boolean);\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(', ')}, or ${last}.`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}.`;\n }\n else {\n msg += `of type ${types[0]}.`;\n }\n if (actual == null) {\n msg += ` Received ${actual}`;\n }\n else if (typeof actual === 'function' && actual.name) {\n msg += ` Received function ${actual.name}`;\n }\n else if (typeof actual === 'object' && actual != null) {\n if (actual.constructor?.name) {\n msg += ` Received an instance of ${actual.constructor.name}`;\n }\n }\n return msg;\n}\nexport const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types);\nexport const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);\n", "export class JOSEError extends Error {\n static code = 'ERR_JOSE_GENERIC';\n code = 'ERR_JOSE_GENERIC';\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JWTExpired extends JOSEError {\n static code = 'ERR_JWT_EXPIRED';\n code = 'ERR_JWT_EXPIRED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n static code = 'ERR_JOSE_NOT_SUPPORTED';\n code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n static code = 'ERR_JWE_DECRYPTION_FAILED';\n code = 'ERR_JWE_DECRYPTION_FAILED';\n constructor(message = 'decryption operation failed', options) {\n super(message, options);\n }\n}\nexport class JWEInvalid extends JOSEError {\n static code = 'ERR_JWE_INVALID';\n code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n static code = 'ERR_JWS_INVALID';\n code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n static code = 'ERR_JWT_INVALID';\n code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n static code = 'ERR_JWK_INVALID';\n code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n static code = 'ERR_JWKS_INVALID';\n code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n static code = 'ERR_JWKS_NO_MATCHING_KEY';\n code = 'ERR_JWKS_NO_MATCHING_KEY';\n constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator];\n static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSTimeout extends JOSEError {\n static code = 'ERR_JWKS_TIMEOUT';\n code = 'ERR_JWKS_TIMEOUT';\n constructor(message = 'request timed out', options) {\n super(message, options);\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n constructor(message = 'signature verification failed', options) {\n super(message, options);\n }\n}\n", "export function assertCryptoKey(key) {\n if (!isCryptoKey(key)) {\n throw new Error('CryptoKey instance expected');\n }\n}\nexport const isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === 'CryptoKey')\n return true;\n try {\n return key instanceof CryptoKey;\n }\n catch {\n return false;\n }\n};\nexport const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject';\nexport const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\n", "import { concat, uint64be } from './buffer_utils.js';\nimport { checkEncCryptoKey } from './crypto_key.js';\nimport { invalidKeyInput } from './invalid_key_input.js';\nimport { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js';\nimport { isCryptoKey } from './is_key_like.js';\nexport function cekLength(alg) {\n switch (alg) {\n case 'A128GCM':\n return 128;\n case 'A192GCM':\n return 192;\n case 'A256GCM':\n case 'A128CBC-HS256':\n return 256;\n case 'A192CBC-HS384':\n return 384;\n case 'A256CBC-HS512':\n return 512;\n default:\n throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);\n }\n}\nexport const generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3));\nfunction checkCekLength(cek, expected) {\n const actual = cek.byteLength << 3;\n if (actual !== expected) {\n throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);\n }\n}\nfunction ivBitLength(alg) {\n switch (alg) {\n case 'A128GCM':\n case 'A128GCMKW':\n case 'A192GCM':\n case 'A192GCMKW':\n case 'A256GCM':\n case 'A256GCMKW':\n return 96;\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n return 128;\n default:\n throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);\n }\n}\nexport const generateIv = (alg) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg) >> 3));\nexport function checkIvLength(enc, iv) {\n if (iv.length << 3 !== ivBitLength(enc)) {\n throw new JWEInvalid('Invalid Initialization Vector length');\n }\n}\nasync function cbcKeySetup(enc, cek, usage) {\n if (!(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));\n }\n const keySize = parseInt(enc.slice(1, 4), 10);\n const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, [usage]);\n const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {\n hash: `SHA-${keySize << 1}`,\n name: 'HMAC',\n }, false, ['sign']);\n return { encKey, macKey, keySize };\n}\nasync function cbcHmacTag(macKey, macData, keySize) {\n return new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));\n}\nasync function cbcEncrypt(enc, plaintext, cek, iv, aad) {\n const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, 'encrypt');\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({\n iv: iv,\n name: 'AES-CBC',\n }, encKey, plaintext));\n const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));\n const tag = await cbcHmacTag(macKey, macData, keySize);\n return { ciphertext, tag, iv };\n}\nasync function timingSafeEqual(a, b) {\n if (!(a instanceof Uint8Array)) {\n throw new TypeError('First argument must be a buffer');\n }\n if (!(b instanceof Uint8Array)) {\n throw new TypeError('Second argument must be a buffer');\n }\n const algorithm = { name: 'HMAC', hash: 'SHA-256' };\n const key = (await crypto.subtle.generateKey(algorithm, false, ['sign']));\n const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));\n const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));\n let out = 0;\n let i = -1;\n while (++i < 32) {\n out |= aHmac[i] ^ bHmac[i];\n }\n return out === 0;\n}\nasync function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {\n const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, 'decrypt');\n const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));\n const expectedTag = await cbcHmacTag(macKey, macData, keySize);\n let macCheckPassed;\n try {\n macCheckPassed = await timingSafeEqual(tag, expectedTag);\n }\n catch {\n }\n if (!macCheckPassed) {\n throw new JWEDecryptionFailed();\n }\n let plaintext;\n try {\n plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, encKey, ciphertext));\n }\n catch {\n }\n if (!plaintext) {\n throw new JWEDecryptionFailed();\n }\n return plaintext;\n}\nasync function gcmEncrypt(enc, plaintext, cek, iv, aad) {\n let encKey;\n if (cek instanceof Uint8Array) {\n encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);\n }\n else {\n checkEncCryptoKey(cek, enc, 'encrypt');\n encKey = cek;\n }\n const encrypted = new Uint8Array(await crypto.subtle.encrypt({\n additionalData: aad,\n iv: iv,\n name: 'AES-GCM',\n tagLength: 128,\n }, encKey, plaintext));\n const tag = encrypted.slice(-16);\n const ciphertext = encrypted.slice(0, -16);\n return { ciphertext, tag, iv };\n}\nasync function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {\n let encKey;\n if (cek instanceof Uint8Array) {\n encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']);\n }\n else {\n checkEncCryptoKey(cek, enc, 'decrypt');\n encKey = cek;\n }\n try {\n return new Uint8Array(await crypto.subtle.decrypt({\n additionalData: aad,\n iv: iv,\n name: 'AES-GCM',\n tagLength: 128,\n }, encKey, concat(ciphertext, tag)));\n }\n catch {\n throw new JWEDecryptionFailed();\n }\n}\nconst unsupportedEnc = 'Unsupported JWE Content Encryption Algorithm';\nexport async function encrypt(enc, plaintext, cek, iv, aad) {\n if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'));\n }\n if (iv) {\n checkIvLength(enc, iv);\n }\n else {\n iv = generateIv(enc);\n }\n switch (enc) {\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n if (cek instanceof Uint8Array) {\n checkCekLength(cek, parseInt(enc.slice(-3), 10));\n }\n return cbcEncrypt(enc, plaintext, cek, iv, aad);\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM':\n if (cek instanceof Uint8Array) {\n checkCekLength(cek, parseInt(enc.slice(1, 4), 10));\n }\n return gcmEncrypt(enc, plaintext, cek, iv, aad);\n default:\n throw new JOSENotSupported(unsupportedEnc);\n }\n}\nexport async function decrypt(enc, cek, ciphertext, iv, tag, aad) {\n if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'));\n }\n if (!iv) {\n throw new JWEInvalid('JWE Initialization Vector missing');\n }\n if (!tag) {\n throw new JWEInvalid('JWE Authentication Tag missing');\n }\n checkIvLength(enc, iv);\n switch (enc) {\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n if (cek instanceof Uint8Array)\n checkCekLength(cek, parseInt(enc.slice(-3), 10));\n return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM':\n if (cek instanceof Uint8Array)\n checkCekLength(cek, parseInt(enc.slice(1, 4), 10));\n return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);\n default:\n throw new JOSENotSupported(unsupportedEnc);\n }\n}\n", "import { decode } from '../util/base64url.js';\nexport const unprotected = Symbol();\nexport function assertNotSet(value, name) {\n if (value) {\n throw new TypeError(`${name} can only be called once`);\n }\n}\nexport function decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n }\n catch {\n throw new ErrorClass(`Failed to base64url decode the ${label}`);\n }\n}\nexport async function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\n", "const isObjectLike = (value) => typeof value === 'object' && value !== null;\nexport function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\nexport function isDisjoint(...headers) {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n}\nexport const isJWK = (key) => isObject(key) && typeof key.kty === 'string';\nexport const isPrivateJWK = (key) => key.kty !== 'oct' &&\n ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');\nexport const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;\nexport const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';\n", "import { checkEncCryptoKey } from './crypto_key.js';\nfunction checkKeySize(key, alg) {\n if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {\n throw new TypeError(`Invalid key size for alg: ${alg}`);\n }\n}\nfunction getCryptoKey(key, alg, usage) {\n if (key instanceof Uint8Array) {\n return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]);\n }\n checkEncCryptoKey(key, alg, usage);\n return key;\n}\nexport async function wrap(alg, key, cek) {\n const cryptoKey = await getCryptoKey(key, alg, 'wrapKey');\n checkKeySize(cryptoKey, alg);\n const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']);\n return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'));\n}\nexport async function unwrap(alg, key, encryptedKey) {\n const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey');\n checkKeySize(cryptoKey, alg);\n const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']);\n return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));\n}\n", "import { encode, concat, uint32be } from './buffer_utils.js';\nimport { checkEncCryptoKey } from './crypto_key.js';\nimport { digest } from './helpers.js';\nfunction lengthAndInput(input) {\n return concat(uint32be(input.length), input);\n}\nasync function concatKdf(Z, L, OtherInfo) {\n const dkLen = L >> 3;\n const hashLen = 32;\n const reps = Math.ceil(dkLen / hashLen);\n const dk = new Uint8Array(reps * hashLen);\n for (let i = 1; i <= reps; i++) {\n const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);\n hashInput.set(uint32be(i), 0);\n hashInput.set(Z, 4);\n hashInput.set(OtherInfo, 4 + Z.length);\n const hashResult = await digest('sha256', hashInput);\n dk.set(hashResult, (i - 1) * hashLen);\n }\n return dk.slice(0, dkLen);\n}\nexport async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {\n checkEncCryptoKey(publicKey, 'ECDH');\n checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');\n const algorithmID = lengthAndInput(encode(algorithm));\n const partyUInfo = lengthAndInput(apu);\n const partyVInfo = lengthAndInput(apv);\n const suppPubInfo = uint32be(keyLength);\n const suppPrivInfo = new Uint8Array();\n const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);\n const Z = new Uint8Array(await crypto.subtle.deriveBits({\n name: publicKey.algorithm.name,\n public: publicKey,\n }, privateKey, getEcdhBitLength(publicKey)));\n return concatKdf(Z, keyLength, otherInfo);\n}\nfunction getEcdhBitLength(publicKey) {\n if (publicKey.algorithm.name === 'X25519') {\n return 256;\n }\n return (Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3);\n}\nexport function allowed(key) {\n switch (key.algorithm.namedCurve) {\n case 'P-256':\n case 'P-384':\n case 'P-521':\n return true;\n default:\n return key.algorithm.name === 'X25519';\n }\n}\n", "import { encode as b64u } from '../util/base64url.js';\nimport * as aeskw from './aeskw.js';\nimport { checkEncCryptoKey } from './crypto_key.js';\nimport { concat, encode } from './buffer_utils.js';\nimport { JWEInvalid } from '../util/errors.js';\nfunction getCryptoKey(key, alg) {\n if (key instanceof Uint8Array) {\n return crypto.subtle.importKey('raw', key, 'PBKDF2', false, [\n 'deriveBits',\n ]);\n }\n checkEncCryptoKey(key, alg, 'deriveBits');\n return key;\n}\nconst concatSalt = (alg, p2sInput) => concat(encode(alg), Uint8Array.of(0x00), p2sInput);\nasync function deriveKey(p2s, alg, p2c, key) {\n if (!(p2s instanceof Uint8Array) || p2s.length < 8) {\n throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets');\n }\n const salt = concatSalt(alg, p2s);\n const keylen = parseInt(alg.slice(13, 16), 10);\n const subtleAlg = {\n hash: `SHA-${alg.slice(8, 11)}`,\n iterations: p2c,\n name: 'PBKDF2',\n salt,\n };\n const cryptoKey = await getCryptoKey(key, alg);\n return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));\n}\nexport async function wrap(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {\n const derived = await deriveKey(p2s, alg, p2c, key);\n const encryptedKey = await aeskw.wrap(alg.slice(-6), derived, cek);\n return { encryptedKey, p2c, p2s: b64u(p2s) };\n}\nexport async function unwrap(alg, key, encryptedKey, p2c, p2s) {\n const derived = await deriveKey(p2s, alg, p2c, key);\n return aeskw.unwrap(alg.slice(-6), derived, encryptedKey);\n}\n", "import { JOSENotSupported } from '../util/errors.js';\nimport { checkSigCryptoKey } from './crypto_key.js';\nimport { invalidKeyInput } from './invalid_key_input.js';\nexport function checkKeyLength(alg, key) {\n if (alg.startsWith('RS') || alg.startsWith('PS')) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n }\n }\n}\nfunction subtleAlgorithm(alg, algorithm) {\n const hash = `SHA-${alg.slice(-3)}`;\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { hash, name: 'HMAC' };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { hash, name: 'RSASSA-PKCS1-v1_5' };\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n case 'Ed25519':\n case 'EdDSA':\n return { name: 'Ed25519' };\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return { name: alg };\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\nasync function getSigKey(alg, key, usage) {\n if (key instanceof Uint8Array) {\n if (!alg.startsWith('HS')) {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n }\n checkSigCryptoKey(key, alg, usage);\n return key;\n}\nexport async function sign(alg, key, data) {\n const cryptoKey = await getSigKey(alg, key, 'sign');\n checkKeyLength(alg, cryptoKey);\n const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);\n return new Uint8Array(signature);\n}\nexport async function verify(alg, key, signature, data) {\n const cryptoKey = await getSigKey(alg, key, 'verify');\n checkKeyLength(alg, cryptoKey);\n const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n try {\n return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n }\n catch {\n return false;\n }\n}\n", "import { checkEncCryptoKey } from './crypto_key.js';\nimport { checkKeyLength } from './signing.js';\nimport { JOSENotSupported } from '../util/errors.js';\nconst subtleAlgorithm = (alg) => {\n switch (alg) {\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n return 'RSA-OAEP';\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n};\nexport async function encrypt(alg, key, cek) {\n checkEncCryptoKey(key, alg, 'encrypt');\n checkKeyLength(alg, key);\n return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));\n}\nexport async function decrypt(alg, key, encryptedKey) {\n checkEncCryptoKey(key, alg, 'decrypt');\n checkKeyLength(alg, key);\n return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));\n}\n", "import { JOSENotSupported } from '../util/errors.js';\nconst unsupportedAlg = 'Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value';\nfunction subtleMapping(jwk) {\n let algorithm;\n let keyUsages;\n switch (jwk.kty) {\n case 'AKP': {\n switch (jwk.alg) {\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: jwk.alg };\n keyUsages = jwk.priv ? ['sign'] : ['verify'];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'RSA': {\n switch (jwk.alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n };\n keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'EC': {\n switch (jwk.alg) {\n case 'ES256':\n case 'ES384':\n case 'ES512':\n algorithm = {\n name: 'ECDSA',\n namedCurve: { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[jwk.alg],\n };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'OKP': {\n switch (jwk.alg) {\n case 'Ed25519':\n case 'EdDSA':\n algorithm = { name: 'Ed25519' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n }\n return { algorithm, keyUsages };\n}\nexport async function jwkToKey(jwk) {\n if (!jwk.alg) {\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n }\n const { algorithm, keyUsages } = subtleMapping(jwk);\n const keyData = { ...jwk };\n if (keyData.kty !== 'AKP') {\n delete keyData.alg;\n }\n delete keyData.use;\n return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);\n}\n", "import { isJWK } from './type_checks.js';\nimport { decode } from '../util/base64url.js';\nimport { jwkToKey } from './jwk_to_key.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nconst unusableForAlg = 'given KeyObject instance cannot be used for this algorithm';\nlet cache;\nconst handleJWK = async (key, jwk, alg, freeze = false) => {\n cache ||= new WeakMap();\n let cached = cache.get(key);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const cryptoKey = await jwkToKey({ ...jwk, alg });\n if (freeze)\n Object.freeze(key);\n if (!cached) {\n cache.set(key, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nconst handleKeyObject = (keyObject, alg) => {\n cache ||= new WeakMap();\n let cached = cache.get(keyObject);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const isPublic = keyObject.type === 'public';\n const extractable = isPublic ? true : false;\n let cryptoKey;\n if (keyObject.asymmetricKeyType === 'x25519') {\n switch (alg) {\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n break;\n default:\n throw new TypeError(unusableForAlg);\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']);\n }\n if (keyObject.asymmetricKeyType === 'ed25519') {\n if (alg !== 'EdDSA' && alg !== 'Ed25519') {\n throw new TypeError(unusableForAlg);\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n isPublic ? 'verify' : 'sign',\n ]);\n }\n switch (keyObject.asymmetricKeyType) {\n case 'ml-dsa-44':\n case 'ml-dsa-65':\n case 'ml-dsa-87': {\n if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {\n throw new TypeError(unusableForAlg);\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n isPublic ? 'verify' : 'sign',\n ]);\n }\n }\n if (keyObject.asymmetricKeyType === 'rsa') {\n let hash;\n switch (alg) {\n case 'RSA-OAEP':\n hash = 'SHA-1';\n break;\n case 'RS256':\n case 'PS256':\n case 'RSA-OAEP-256':\n hash = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'RSA-OAEP-384':\n hash = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'RSA-OAEP-512':\n hash = 'SHA-512';\n break;\n default:\n throw new TypeError(unusableForAlg);\n }\n if (alg.startsWith('RSA-OAEP')) {\n return keyObject.toCryptoKey({\n name: 'RSA-OAEP',\n hash,\n }, extractable, isPublic ? ['encrypt'] : ['decrypt']);\n }\n cryptoKey = keyObject.toCryptoKey({\n name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',\n hash,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (keyObject.asymmetricKeyType === 'ec') {\n const nist = new Map([\n ['prime256v1', 'P-256'],\n ['secp384r1', 'P-384'],\n ['secp521r1', 'P-521'],\n ]);\n const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);\n if (!namedCurve) {\n throw new TypeError(unusableForAlg);\n }\n const expectedCurve = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };\n if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDSA',\n namedCurve,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (alg.startsWith('ECDH-ES')) {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDH',\n namedCurve,\n }, extractable, isPublic ? [] : ['deriveBits']);\n }\n }\n if (!cryptoKey) {\n throw new TypeError(unusableForAlg);\n }\n if (!cached) {\n cache.set(keyObject, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nexport async function normalizeKey(key, alg) {\n if (key instanceof Uint8Array) {\n return key;\n }\n if (isCryptoKey(key)) {\n return key;\n }\n if (isKeyObject(key)) {\n if (key.type === 'secret') {\n return key.export();\n }\n if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') {\n try {\n return handleKeyObject(key, alg);\n }\n catch (err) {\n if (err instanceof TypeError) {\n throw err;\n }\n }\n }\n let jwk = key.export({ format: 'jwk' });\n return handleJWK(key, jwk, alg);\n }\n if (isJWK(key)) {\n if (key.k) {\n return decode(key.k);\n }\n return handleJWK(key, key, alg, true);\n }\n throw new Error('unreachable');\n}\n", "import { decode as decodeBase64URL } from '../util/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';\nimport { jwkToKey } from '../lib/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, options) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n let ext;\n alg ??= jwk.alg;\n ext ??= options?.extractable ?? jwk.ext;\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if ('oth' in jwk && jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n return jwkToKey({ ...jwk, alg, ext });\n case 'AKP': {\n if (typeof jwk.alg !== 'string' || !jwk.alg) {\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n }\n if (alg !== undefined && alg !== jwk.alg) {\n throw new TypeError('JWK alg and alg option value mismatch');\n }\n return jwkToKey({ ...jwk, ext });\n }\n case 'EC':\n case 'OKP':\n return jwkToKey({ ...jwk, alg, ext });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n", "import { invalidKeyInput } from './invalid_key_input.js';\nimport { encode as b64u } from '../util/base64url.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nexport async function keyToJWK(key) {\n if (isKeyObject(key)) {\n if (key.type === 'secret') {\n key = key.export();\n }\n else {\n return key.export({ format: 'jwk' });\n }\n }\n if (key instanceof Uint8Array) {\n return {\n kty: 'oct',\n k: b64u(key),\n };\n }\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'Uint8Array'));\n }\n if (!key.extractable) {\n throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');\n }\n const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key);\n if (jwk.kty === 'AKP') {\n ;\n jwk.alg = alg;\n }\n return jwk;\n}\n", "import { toSPKI as exportPublic, toPKCS8 as exportPrivate } from '../lib/asn1.js';\nimport { keyToJWK } from '../lib/key_to_jwk.js';\nexport async function exportSPKI(key) {\n return exportPublic(key);\n}\nexport async function exportPKCS8(key) {\n return exportPrivate(key);\n}\nexport async function exportJWK(key) {\n return keyToJWK(key);\n}\n", "import { encrypt, decrypt } from './content_encryption.js';\nimport { encode as b64u } from '../util/base64url.js';\nexport async function wrap(alg, key, cek, iv) {\n const jweAlgorithm = alg.slice(0, 7);\n const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array());\n return {\n encryptedKey: wrapped.ciphertext,\n iv: b64u(wrapped.iv),\n tag: b64u(wrapped.tag),\n };\n}\nexport async function unwrap(alg, key, encryptedKey, iv, tag) {\n const jweAlgorithm = alg.slice(0, 7);\n return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array());\n}\n", "import * as aeskw from './aeskw.js';\nimport * as ecdhes from './ecdhes.js';\nimport * as pbes2kw from './pbes2kw.js';\nimport * as rsaes from './rsaes.js';\nimport { encode as b64u } from '../util/base64url.js';\nimport { normalizeKey } from './normalize_key.js';\nimport { JOSENotSupported, JWEInvalid } from '../util/errors.js';\nimport { decodeBase64url } from './helpers.js';\nimport { generateCek, cekLength } from './content_encryption.js';\nimport { importJWK } from '../key/import.js';\nimport { exportJWK } from '../key/export.js';\nimport { isObject } from './type_checks.js';\nimport { wrap as aesGcmKwWrap, unwrap as aesGcmKwUnwrap } from './aesgcmkw.js';\nimport { assertCryptoKey } from './is_key_like.js';\nconst unsupportedAlgHeader = 'Invalid or unsupported \"alg\" (JWE Algorithm) header value';\nfunction assertEncryptedKey(encryptedKey) {\n if (encryptedKey === undefined)\n throw new JWEInvalid('JWE Encrypted Key missing');\n}\nexport async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {\n switch (alg) {\n case 'dir': {\n if (encryptedKey !== undefined)\n throw new JWEInvalid('Encountered unexpected JWE Encrypted Key');\n return key;\n }\n case 'ECDH-ES':\n if (encryptedKey !== undefined)\n throw new JWEInvalid('Encountered unexpected JWE Encrypted Key');\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n if (!isObject(joseHeader.epk))\n throw new JWEInvalid(`JOSE Header \"epk\" (Ephemeral Public Key) missing or invalid`);\n assertCryptoKey(key);\n if (!ecdhes.allowed(key))\n throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');\n const epk = await importJWK(joseHeader.epk, alg);\n assertCryptoKey(epk);\n let partyUInfo;\n let partyVInfo;\n if (joseHeader.apu !== undefined) {\n if (typeof joseHeader.apu !== 'string')\n throw new JWEInvalid(`JOSE Header \"apu\" (Agreement PartyUInfo) invalid`);\n partyUInfo = decodeBase64url(joseHeader.apu, 'apu', JWEInvalid);\n }\n if (joseHeader.apv !== undefined) {\n if (typeof joseHeader.apv !== 'string')\n throw new JWEInvalid(`JOSE Header \"apv\" (Agreement PartyVInfo) invalid`);\n partyVInfo = decodeBase64url(joseHeader.apv, 'apv', JWEInvalid);\n }\n const sharedSecret = await ecdhes.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);\n if (alg === 'ECDH-ES')\n return sharedSecret;\n assertEncryptedKey(encryptedKey);\n return aeskw.unwrap(alg.slice(-6), sharedSecret, encryptedKey);\n }\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n assertEncryptedKey(encryptedKey);\n assertCryptoKey(key);\n return rsaes.decrypt(alg, key, encryptedKey);\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n assertEncryptedKey(encryptedKey);\n if (typeof joseHeader.p2c !== 'number')\n throw new JWEInvalid(`JOSE Header \"p2c\" (PBES2 Count) missing or invalid`);\n const p2cLimit = options?.maxPBES2Count || 10_000;\n if (joseHeader.p2c > p2cLimit)\n throw new JWEInvalid(`JOSE Header \"p2c\" (PBES2 Count) out is of acceptable bounds`);\n if (typeof joseHeader.p2s !== 'string')\n throw new JWEInvalid(`JOSE Header \"p2s\" (PBES2 Salt) missing or invalid`);\n let p2s;\n p2s = decodeBase64url(joseHeader.p2s, 'p2s', JWEInvalid);\n return pbes2kw.unwrap(alg, key, encryptedKey, joseHeader.p2c, p2s);\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n assertEncryptedKey(encryptedKey);\n return aeskw.unwrap(alg, key, encryptedKey);\n }\n case 'A128GCMKW':\n case 'A192GCMKW':\n case 'A256GCMKW': {\n assertEncryptedKey(encryptedKey);\n if (typeof joseHeader.iv !== 'string')\n throw new JWEInvalid(`JOSE Header \"iv\" (Initialization Vector) missing or invalid`);\n if (typeof joseHeader.tag !== 'string')\n throw new JWEInvalid(`JOSE Header \"tag\" (Authentication Tag) missing or invalid`);\n let iv;\n iv = decodeBase64url(joseHeader.iv, 'iv', JWEInvalid);\n let tag;\n tag = decodeBase64url(joseHeader.tag, 'tag', JWEInvalid);\n return aesGcmKwUnwrap(alg, key, encryptedKey, iv, tag);\n }\n default: {\n throw new JOSENotSupported(unsupportedAlgHeader);\n }\n }\n}\nexport async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {\n let encryptedKey;\n let parameters;\n let cek;\n switch (alg) {\n case 'dir': {\n cek = key;\n break;\n }\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n assertCryptoKey(key);\n if (!ecdhes.allowed(key)) {\n throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');\n }\n const { apu, apv } = providedParameters;\n let ephemeralKey;\n if (providedParameters.epk) {\n ephemeralKey = (await normalizeKey(providedParameters.epk, alg));\n }\n else {\n ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ['deriveBits'])).privateKey;\n }\n const { x, y, crv, kty } = await exportJWK(ephemeralKey);\n const sharedSecret = await ecdhes.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);\n parameters = { epk: { x, crv, kty } };\n if (kty === 'EC')\n parameters.epk.y = y;\n if (apu)\n parameters.apu = b64u(apu);\n if (apv)\n parameters.apv = b64u(apv);\n if (alg === 'ECDH-ES') {\n cek = sharedSecret;\n break;\n }\n cek = providedCek || generateCek(enc);\n const kwAlg = alg.slice(-6);\n encryptedKey = await aeskw.wrap(kwAlg, sharedSecret, cek);\n break;\n }\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n cek = providedCek || generateCek(enc);\n assertCryptoKey(key);\n encryptedKey = await rsaes.encrypt(alg, key, cek);\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n cek = providedCek || generateCek(enc);\n const { p2c, p2s } = providedParameters;\n ({ encryptedKey, ...parameters } = await pbes2kw.wrap(alg, key, cek, p2c, p2s));\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n cek = providedCek || generateCek(enc);\n encryptedKey = await aeskw.wrap(alg, key, cek);\n break;\n }\n case 'A128GCMKW':\n case 'A192GCMKW':\n case 'A256GCMKW': {\n cek = providedCek || generateCek(enc);\n const { iv } = providedParameters;\n ({ encryptedKey, ...parameters } = await aesGcmKwWrap(alg, key, cek, iv));\n break;\n }\n default: {\n throw new JOSENotSupported(unsupportedAlgHeader);\n }\n }\n return { cek, encryptedKey, parameters };\n}\n", "import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js';\nexport function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n }\n if (!protectedHeader || protectedHeader.crit === undefined) {\n return new Set();\n }\n if (!Array.isArray(protectedHeader.crit) ||\n protectedHeader.crit.length === 0 ||\n protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n }\n let recognized;\n if (recognizedOption !== undefined) {\n recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n }\n else {\n recognized = recognizedDefault;\n }\n for (const parameter of protectedHeader.crit) {\n if (!recognized.has(parameter)) {\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n }\n if (joseHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n }\n if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n }\n return new Set(protectedHeader.crit);\n}\n", "export function validateAlgorithms(option, algorithms) {\n if (algorithms !== undefined &&\n (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n }\n if (!algorithms) {\n return undefined;\n }\n return new Set(algorithms);\n}\n", "import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport { isKeyLike } from './is_key_like.js';\nimport * as jwk from './type_checks.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n if (key.use !== undefined) {\n let expected;\n switch (usage) {\n case 'sign':\n case 'verify':\n expected = 'sig';\n break;\n case 'encrypt':\n case 'decrypt':\n expected = 'enc';\n break;\n }\n if (key.use !== expected) {\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n }\n if (key.alg !== undefined && key.alg !== alg) {\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n }\n if (Array.isArray(key.key_ops)) {\n let expectedKeyOp;\n switch (true) {\n case usage === 'sign' || usage === 'verify':\n case alg === 'dir':\n case alg.includes('CBC-HS'):\n expectedKeyOp = usage;\n break;\n case alg.startsWith('PBES2'):\n expectedKeyOp = 'deriveBits';\n break;\n case /^A\\d{3}(?:GCM)?(?:KW)?$/.test(alg):\n if (!alg.includes('GCM') && alg.endsWith('KW')) {\n expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey';\n }\n else {\n expectedKeyOp = usage;\n }\n break;\n case usage === 'encrypt' && alg.startsWith('RSA'):\n expectedKeyOp = 'wrapKey';\n break;\n case usage === 'decrypt':\n expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits';\n break;\n }\n if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n }\n return true;\n};\nconst symmetricTypeCheck = (alg, key, usage) => {\n if (key instanceof Uint8Array)\n return;\n if (jwk.isJWK(key)) {\n if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'));\n }\n if (key.type !== 'secret') {\n throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n }\n};\nconst asymmetricTypeCheck = (alg, key, usage) => {\n if (jwk.isJWK(key)) {\n switch (usage) {\n case 'decrypt':\n case 'sign':\n if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation must be a private JWK`);\n case 'encrypt':\n case 'verify':\n if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation must be a public JWK`);\n }\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n if (key.type === 'secret') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n }\n if (key.type === 'public') {\n switch (usage) {\n case 'sign':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n case 'decrypt':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n }\n }\n if (key.type === 'private') {\n switch (usage) {\n case 'verify':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n case 'encrypt':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n }\n }\n};\nexport function checkKeyType(alg, key, usage) {\n switch (alg.substring(0, 2)) {\n case 'A1':\n case 'A2':\n case 'di':\n case 'HS':\n case 'PB':\n symmetricTypeCheck(alg, key, usage);\n break;\n default:\n asymmetricTypeCheck(alg, key, usage);\n }\n}\n", "import { JOSENotSupported, JWEInvalid } from '../util/errors.js';\nimport { concat } from './buffer_utils.js';\nfunction supported(name) {\n if (typeof globalThis[name] === 'undefined') {\n throw new JOSENotSupported(`JWE \"zip\" (Compression Algorithm) Header Parameter requires the ${name} API.`);\n }\n}\nexport async function compress(input) {\n supported('CompressionStream');\n const cs = new CompressionStream('deflate-raw');\n const writer = cs.writable.getWriter();\n writer.write(input).catch(() => { });\n writer.close().catch(() => { });\n const chunks = [];\n const reader = cs.readable.getReader();\n for (;;) {\n const { value, done } = await reader.read();\n if (done)\n break;\n chunks.push(value);\n }\n return concat(...chunks);\n}\nexport async function decompress(input, maxLength) {\n supported('DecompressionStream');\n const ds = new DecompressionStream('deflate-raw');\n const writer = ds.writable.getWriter();\n writer.write(input).catch(() => { });\n writer.close().catch(() => { });\n const chunks = [];\n let length = 0;\n const reader = ds.readable.getReader();\n for (;;) {\n const { value, done } = await reader.read();\n if (done)\n break;\n chunks.push(value);\n length += value.byteLength;\n if (maxLength !== Infinity && length > maxLength) {\n throw new JWEInvalid('Decompressed plaintext exceeded the configured limit');\n }\n }\n return concat(...chunks);\n}\n", "import { decode as b64u } from '../../util/base64url.js';\nimport { decrypt } from '../../lib/content_encryption.js';\nimport { decodeBase64url } from '../../lib/helpers.js';\nimport { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { isObject } from '../../lib/type_checks.js';\nimport { decryptKeyManagement } from '../../lib/key_management.js';\nimport { decoder, concat, encode } from '../../lib/buffer_utils.js';\nimport { generateCek } from '../../lib/content_encryption.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { validateAlgorithms } from '../../lib/validate_algorithms.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { decompress } from '../../lib/deflate.js';\nexport async function flattenedDecrypt(jwe, key, options) {\n if (!isObject(jwe)) {\n throw new JWEInvalid('Flattened JWE must be an object');\n }\n if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {\n throw new JWEInvalid('JOSE Header missing');\n }\n if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {\n throw new JWEInvalid('JWE Initialization Vector incorrect type');\n }\n if (typeof jwe.ciphertext !== 'string') {\n throw new JWEInvalid('JWE Ciphertext missing or incorrect type');\n }\n if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {\n throw new JWEInvalid('JWE Authentication Tag incorrect type');\n }\n if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {\n throw new JWEInvalid('JWE Protected Header incorrect type');\n }\n if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {\n throw new JWEInvalid('JWE Encrypted Key incorrect type');\n }\n if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {\n throw new JWEInvalid('JWE AAD incorrect type');\n }\n if (jwe.header !== undefined && !isObject(jwe.header)) {\n throw new JWEInvalid('JWE Shared Unprotected Header incorrect type');\n }\n if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {\n throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');\n }\n let parsedProt;\n if (jwe.protected) {\n try {\n const protectedHeader = b64u(jwe.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWEInvalid('JWE Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {\n throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jwe.header,\n ...jwe.unprotected,\n };\n validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);\n if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {\n throw new JOSENotSupported('Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.');\n }\n if (joseHeader.zip !== undefined && !parsedProt?.zip) {\n throw new JWEInvalid('JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.');\n }\n const { alg, enc } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header');\n }\n if (typeof enc !== 'string' || !enc) {\n throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');\n }\n const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms);\n const contentEncryptionAlgorithms = options &&\n validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);\n if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||\n (!keyManagementAlgorithms && alg.startsWith('PBES2'))) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {\n throw new JOSEAlgNotAllowed('\"enc\" (Encryption Algorithm) Header Parameter value not allowed');\n }\n let encryptedKey;\n if (jwe.encrypted_key !== undefined) {\n encryptedKey = decodeBase64url(jwe.encrypted_key, 'encrypted_key', JWEInvalid);\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jwe);\n resolvedKey = true;\n }\n checkKeyType(alg === 'dir' ? enc : alg, key, 'decrypt');\n const k = await normalizeKey(key, alg);\n let cek;\n try {\n cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);\n }\n catch (err) {\n if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {\n throw err;\n }\n cek = generateCek(enc);\n }\n let iv;\n let tag;\n if (jwe.iv !== undefined) {\n iv = decodeBase64url(jwe.iv, 'iv', JWEInvalid);\n }\n if (jwe.tag !== undefined) {\n tag = decodeBase64url(jwe.tag, 'tag', JWEInvalid);\n }\n const protectedHeader = jwe.protected !== undefined ? encode(jwe.protected) : new Uint8Array();\n let additionalData;\n if (jwe.aad !== undefined) {\n additionalData = concat(protectedHeader, encode('.'), encode(jwe.aad));\n }\n else {\n additionalData = protectedHeader;\n }\n const ciphertext = decodeBase64url(jwe.ciphertext, 'ciphertext', JWEInvalid);\n const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);\n const result = { plaintext };\n if (joseHeader.zip === 'DEF') {\n const maxDecompressedLength = options?.maxDecompressedLength ?? 250_000;\n if (maxDecompressedLength === 0) {\n throw new JOSENotSupported('JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.');\n }\n if (maxDecompressedLength !== Infinity &&\n (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) {\n throw new TypeError('maxDecompressedLength must be 0, a positive safe integer, or Infinity');\n }\n result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => {\n if (cause instanceof JWEInvalid)\n throw cause;\n throw new JWEInvalid('Failed to decompress plaintext', { cause });\n });\n }\n if (jwe.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jwe.aad !== undefined) {\n result.additionalAuthenticatedData = decodeBase64url(jwe.aad, 'aad', JWEInvalid);\n }\n if (jwe.unprotected !== undefined) {\n result.sharedUnprotectedHeader = jwe.unprotected;\n }\n if (jwe.header !== undefined) {\n result.unprotectedHeader = jwe.header;\n }\n if (resolvedKey) {\n return { ...result, key: k };\n }\n return result;\n}\n", "import { flattenedDecrypt } from '../flattened/decrypt.js';\nimport { JWEInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactDecrypt(jwe, key, options) {\n if (jwe instanceof Uint8Array) {\n jwe = decoder.decode(jwe);\n }\n if (typeof jwe !== 'string') {\n throw new JWEInvalid('Compact JWE must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.');\n if (length !== 5) {\n throw new JWEInvalid('Invalid Compact JWE');\n }\n const decrypted = await flattenedDecrypt({\n ciphertext,\n iv: iv || undefined,\n protected: protectedHeader,\n tag: tag || undefined,\n encrypted_key: encryptedKey || undefined,\n }, key, options);\n const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: decrypted.key };\n }\n return result;\n}\n", "import { encode as b64u } from '../../util/base64url.js';\nimport { unprotected, assertNotSet } from '../../lib/helpers.js';\nimport { encrypt } from '../../lib/content_encryption.js';\nimport { encryptKeyManagement } from '../../lib/key_management.js';\nimport { JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { concat, encode } from '../../lib/buffer_utils.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { compress } from '../../lib/deflate.js';\nexport class FlattenedEncrypt {\n #plaintext;\n #protectedHeader;\n #sharedUnprotectedHeader;\n #unprotectedHeader;\n #aad;\n #cek;\n #iv;\n #keyManagementParameters;\n constructor(plaintext) {\n if (!(plaintext instanceof Uint8Array)) {\n throw new TypeError('plaintext must be an instance of Uint8Array');\n }\n this.#plaintext = plaintext;\n }\n setKeyManagementParameters(parameters) {\n assertNotSet(this.#keyManagementParameters, 'setKeyManagementParameters');\n this.#keyManagementParameters = parameters;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n assertNotSet(this.#protectedHeader, 'setProtectedHeader');\n this.#protectedHeader = protectedHeader;\n return this;\n }\n setSharedUnprotectedHeader(sharedUnprotectedHeader) {\n assertNotSet(this.#sharedUnprotectedHeader, 'setSharedUnprotectedHeader');\n this.#sharedUnprotectedHeader = sharedUnprotectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n assertNotSet(this.#unprotectedHeader, 'setUnprotectedHeader');\n this.#unprotectedHeader = unprotectedHeader;\n return this;\n }\n setAdditionalAuthenticatedData(aad) {\n this.#aad = aad;\n return this;\n }\n setContentEncryptionKey(cek) {\n assertNotSet(this.#cek, 'setContentEncryptionKey');\n this.#cek = cek;\n return this;\n }\n setInitializationVector(iv) {\n assertNotSet(this.#iv, 'setInitializationVector');\n this.#iv = iv;\n return this;\n }\n async encrypt(key, options) {\n if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) {\n throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');\n }\n if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {\n throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this.#protectedHeader,\n ...this.#unprotectedHeader,\n ...this.#sharedUnprotectedHeader,\n };\n validateCrit(JWEInvalid, new Map(), options?.crit, this.#protectedHeader, joseHeader);\n if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {\n throw new JOSENotSupported('Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.');\n }\n if (joseHeader.zip !== undefined && !this.#protectedHeader?.zip) {\n throw new JWEInvalid('JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.');\n }\n const { alg, enc } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('JWE \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n if (typeof enc !== 'string' || !enc) {\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid');\n }\n let encryptedKey;\n if (this.#cek && (alg === 'dir' || alg === 'ECDH-ES')) {\n throw new TypeError(`setContentEncryptionKey cannot be called with JWE \"alg\" (Algorithm) Header ${alg}`);\n }\n checkKeyType(alg === 'dir' ? enc : alg, key, 'encrypt');\n let cek;\n {\n let parameters;\n const k = await normalizeKey(key, alg);\n ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters));\n if (parameters) {\n if (options && unprotected in options) {\n if (!this.#unprotectedHeader) {\n this.setUnprotectedHeader(parameters);\n }\n else {\n this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters };\n }\n }\n else if (!this.#protectedHeader) {\n this.setProtectedHeader(parameters);\n }\n else {\n this.#protectedHeader = { ...this.#protectedHeader, ...parameters };\n }\n }\n }\n let additionalData;\n let protectedHeaderS;\n let protectedHeaderB;\n let aadMember;\n if (this.#protectedHeader) {\n protectedHeaderS = b64u(JSON.stringify(this.#protectedHeader));\n protectedHeaderB = encode(protectedHeaderS);\n }\n else {\n protectedHeaderS = '';\n protectedHeaderB = new Uint8Array();\n }\n if (this.#aad) {\n aadMember = b64u(this.#aad);\n const aadMemberBytes = encode(aadMember);\n additionalData = concat(protectedHeaderB, encode('.'), aadMemberBytes);\n }\n else {\n additionalData = protectedHeaderB;\n }\n let plaintext = this.#plaintext;\n if (joseHeader.zip === 'DEF') {\n plaintext = await compress(plaintext).catch((cause) => {\n throw new JWEInvalid('Failed to compress plaintext', { cause });\n });\n }\n const { ciphertext, tag, iv } = await encrypt(enc, plaintext, cek, this.#iv, additionalData);\n const jwe = {\n ciphertext: b64u(ciphertext),\n };\n if (iv) {\n jwe.iv = b64u(iv);\n }\n if (tag) {\n jwe.tag = b64u(tag);\n }\n if (encryptedKey) {\n jwe.encrypted_key = b64u(encryptedKey);\n }\n if (aadMember) {\n jwe.aad = aadMember;\n }\n if (this.#protectedHeader) {\n jwe.protected = protectedHeaderS;\n }\n if (this.#sharedUnprotectedHeader) {\n jwe.unprotected = this.#sharedUnprotectedHeader;\n }\n if (this.#unprotectedHeader) {\n jwe.header = this.#unprotectedHeader;\n }\n return jwe;\n }\n}\n", "import { decode as b64u } from '../../util/base64url.js';\nimport { verify } from '../../lib/signing.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder, encode } from '../../lib/buffer_utils.js';\nimport { decodeBase64url } from '../../lib/helpers.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { isObject } from '../../lib/type_checks.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { validateAlgorithms } from '../../lib/validate_algorithms.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nexport async function flattenedVerify(jws, key, options) {\n if (!isObject(jws)) {\n throw new JWSInvalid('Flattened JWS must be an object');\n }\n if (jws.protected === undefined && jws.header === undefined) {\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n }\n if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n throw new JWSInvalid('JWS Protected Header incorrect type');\n }\n if (jws.payload === undefined) {\n throw new JWSInvalid('JWS Payload missing');\n }\n if (typeof jws.signature !== 'string') {\n throw new JWSInvalid('JWS Signature missing or incorrect type');\n }\n if (jws.header !== undefined && !isObject(jws.header)) {\n throw new JWSInvalid('JWS Unprotected Header incorrect type');\n }\n let parsedProt = {};\n if (jws.protected) {\n try {\n const protectedHeader = b64u(jws.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWSInvalid('JWS Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jws.header)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jws.header,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = parsedProt.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n if (algorithms && !algorithms.has(alg)) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (b64) {\n if (typeof jws.payload !== 'string') {\n throw new JWSInvalid('JWS Payload must be a string');\n }\n }\n else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jws);\n resolvedKey = true;\n }\n checkKeyType(alg, key, 'verify');\n const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array(), encode('.'), typeof jws.payload === 'string'\n ? b64\n ? encode(jws.payload)\n : encoder.encode(jws.payload)\n : jws.payload);\n const signature = decodeBase64url(jws.signature, 'signature', JWSInvalid);\n const k = await normalizeKey(key, alg);\n const verified = await verify(alg, k, signature, data);\n if (!verified) {\n throw new JWSSignatureVerificationFailed();\n }\n let payload;\n if (b64) {\n payload = decodeBase64url(jws.payload, 'payload', JWSInvalid);\n }\n else if (typeof jws.payload === 'string') {\n payload = encoder.encode(jws.payload);\n }\n else {\n payload = jws.payload;\n }\n const result = { payload };\n if (jws.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jws.header !== undefined) {\n result.unprotectedHeader = jws.header;\n }\n if (resolvedKey) {\n return { ...result, key: k };\n }\n return result;\n}\n", "import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n if (jws instanceof Uint8Array) {\n jws = decoder.decode(jws);\n }\n if (typeof jws !== 'string') {\n throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n if (length !== 3) {\n throw new JWSInvalid('Invalid Compact JWS');\n }\n const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n", "import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { encoder, decoder } from './buffer_utils.js';\nimport { isObject } from './type_checks.js';\nconst epoch = (date) => Math.floor(date.getTime() / 1000);\nconst minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport function secs(str) {\n const matched = REGEX.exec(str);\n if (!matched || (matched[4] && matched[1])) {\n throw new TypeError('Invalid time period format');\n }\n const value = parseFloat(matched[2]);\n const unit = matched[3].toLowerCase();\n let numericDate;\n switch (unit) {\n case 'sec':\n case 'secs':\n case 'second':\n case 'seconds':\n case 's':\n numericDate = Math.round(value);\n break;\n case 'minute':\n case 'minutes':\n case 'min':\n case 'mins':\n case 'm':\n numericDate = Math.round(value * minute);\n break;\n case 'hour':\n case 'hours':\n case 'hr':\n case 'hrs':\n case 'h':\n numericDate = Math.round(value * hour);\n break;\n case 'day':\n case 'days':\n case 'd':\n numericDate = Math.round(value * day);\n break;\n case 'week':\n case 'weeks':\n case 'w':\n numericDate = Math.round(value * week);\n break;\n default:\n numericDate = Math.round(value * year);\n break;\n }\n if (matched[1] === '-' || matched[4] === 'ago') {\n return -numericDate;\n }\n return numericDate;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input)) {\n throw new TypeError(`Invalid ${label} input`);\n }\n return input;\n}\nconst normalizeTyp = (value) => {\n if (value.includes('/')) {\n return value.toLowerCase();\n }\n return `application/${value.toLowerCase()}`;\n};\nconst checkAudiencePresence = (audPayload, audOption) => {\n if (typeof audPayload === 'string') {\n return audOption.includes(audPayload);\n }\n if (Array.isArray(audPayload)) {\n return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n }\n return false;\n};\nexport function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(decoder.decode(encodedPayload));\n }\n catch {\n }\n if (!isObject(payload)) {\n throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n }\n const { typ } = options;\n if (typ &&\n (typeof protectedHeader.typ !== 'string' ||\n normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, 'typ', 'check_failed');\n }\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n const presenceCheck = [...requiredClaims];\n if (maxTokenAge !== undefined)\n presenceCheck.push('iat');\n if (audience !== undefined)\n presenceCheck.push('aud');\n if (subject !== undefined)\n presenceCheck.push('sub');\n if (issuer !== undefined)\n presenceCheck.push('iss');\n for (const claim of new Set(presenceCheck.reverse())) {\n if (!(claim in payload)) {\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, 'missing');\n }\n }\n if (issuer &&\n !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', payload, 'iss', 'check_failed');\n }\n if (subject && payload.sub !== subject) {\n throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', payload, 'sub', 'check_failed');\n }\n if (audience &&\n !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', payload, 'aud', 'check_failed');\n }\n let tolerance;\n switch (typeof options.clockTolerance) {\n case 'string':\n tolerance = secs(options.clockTolerance);\n break;\n case 'number':\n tolerance = options.clockTolerance;\n break;\n case 'undefined':\n tolerance = 0;\n break;\n default:\n throw new TypeError('Invalid clockTolerance option type');\n }\n const { currentDate } = options;\n const now = epoch(currentDate || new Date());\n if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n throw new JWTClaimValidationFailed('\"iat\" claim must be a number', payload, 'iat', 'invalid');\n }\n if (payload.nbf !== undefined) {\n if (typeof payload.nbf !== 'number') {\n throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', payload, 'nbf', 'invalid');\n }\n if (payload.nbf > now + tolerance) {\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, 'nbf', 'check_failed');\n }\n }\n if (payload.exp !== undefined) {\n if (typeof payload.exp !== 'number') {\n throw new JWTClaimValidationFailed('\"exp\" claim must be a number', payload, 'exp', 'invalid');\n }\n if (payload.exp <= now - tolerance) {\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, 'exp', 'check_failed');\n }\n }\n if (maxTokenAge) {\n const age = now - payload.iat;\n const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n if (age - tolerance > max) {\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');\n }\n if (age < 0 - tolerance) {\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');\n }\n }\n return payload;\n}\nexport class JWTClaimsBuilder {\n #payload;\n constructor(payload) {\n if (!isObject(payload)) {\n throw new TypeError('JWT Claims Set MUST be an object');\n }\n this.#payload = structuredClone(payload);\n }\n data() {\n return encoder.encode(JSON.stringify(this.#payload));\n }\n get iss() {\n return this.#payload.iss;\n }\n set iss(value) {\n this.#payload.iss = value;\n }\n get sub() {\n return this.#payload.sub;\n }\n set sub(value) {\n this.#payload.sub = value;\n }\n get aud() {\n return this.#payload.aud;\n }\n set aud(value) {\n this.#payload.aud = value;\n }\n set jti(value) {\n this.#payload.jti = value;\n }\n set nbf(value) {\n if (typeof value === 'number') {\n this.#payload.nbf = validateInput('setNotBefore', value);\n }\n else if (value instanceof Date) {\n this.#payload.nbf = validateInput('setNotBefore', epoch(value));\n }\n else {\n this.#payload.nbf = epoch(new Date()) + secs(value);\n }\n }\n set exp(value) {\n if (typeof value === 'number') {\n this.#payload.exp = validateInput('setExpirationTime', value);\n }\n else if (value instanceof Date) {\n this.#payload.exp = validateInput('setExpirationTime', epoch(value));\n }\n else {\n this.#payload.exp = epoch(new Date()) + secs(value);\n }\n }\n set iat(value) {\n if (value === undefined) {\n this.#payload.iat = epoch(new Date());\n }\n else if (value instanceof Date) {\n this.#payload.iat = validateInput('setIssuedAt', epoch(value));\n }\n else if (typeof value === 'string') {\n this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));\n }\n else {\n this.#payload.iat = validateInput('setIssuedAt', value);\n }\n }\n}\n", "import { compactVerify } from '../jws/compact/verify.js';\nimport { validateClaimsSet } from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n const verified = await compactVerify(jwt, key, options);\n if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n const result = { payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n", "import { compactDecrypt } from '../jwe/compact/decrypt.js';\nimport { validateClaimsSet } from '../lib/jwt_claims_set.js';\nimport { JWTClaimValidationFailed } from '../util/errors.js';\nexport async function jwtDecrypt(jwt, key, options) {\n const decrypted = await compactDecrypt(jwt, key, options);\n const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options);\n const { protectedHeader } = decrypted;\n if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {\n throw new JWTClaimValidationFailed('replicated \"iss\" claim header parameter mismatch', payload, 'iss', 'mismatch');\n }\n if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {\n throw new JWTClaimValidationFailed('replicated \"sub\" claim header parameter mismatch', payload, 'sub', 'mismatch');\n }\n if (protectedHeader.aud !== undefined &&\n JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {\n throw new JWTClaimValidationFailed('replicated \"aud\" claim header parameter mismatch', payload, 'aud', 'mismatch');\n }\n const result = { payload, protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: decrypted.key };\n }\n return result;\n}\n", "import { FlattenedEncrypt } from '../flattened/encrypt.js';\nexport class CompactEncrypt {\n #flattened;\n constructor(plaintext) {\n this.#flattened = new FlattenedEncrypt(plaintext);\n }\n setContentEncryptionKey(cek) {\n this.#flattened.setContentEncryptionKey(cek);\n return this;\n }\n setInitializationVector(iv) {\n this.#flattened.setInitializationVector(iv);\n return this;\n }\n setProtectedHeader(protectedHeader) {\n this.#flattened.setProtectedHeader(protectedHeader);\n return this;\n }\n setKeyManagementParameters(parameters) {\n this.#flattened.setKeyManagementParameters(parameters);\n return this;\n }\n async encrypt(key, options) {\n const jwe = await this.#flattened.encrypt(key, options);\n return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');\n }\n}\n", "import { encode as b64u } from '../../util/base64url.js';\nimport { sign } from '../../lib/signing.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { concat, encode } from '../../lib/buffer_utils.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nimport { assertNotSet } from '../../lib/helpers.js';\nexport class FlattenedSign {\n #payload;\n #protectedHeader;\n #unprotectedHeader;\n constructor(payload) {\n if (!(payload instanceof Uint8Array)) {\n throw new TypeError('payload must be an instance of Uint8Array');\n }\n this.#payload = payload;\n }\n setProtectedHeader(protectedHeader) {\n assertNotSet(this.#protectedHeader, 'setProtectedHeader');\n this.#protectedHeader = protectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n assertNotSet(this.#unprotectedHeader, 'setUnprotectedHeader');\n this.#unprotectedHeader = unprotectedHeader;\n return this;\n }\n async sign(key, options) {\n if (!this.#protectedHeader && !this.#unprotectedHeader) {\n throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');\n }\n if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this.#protectedHeader,\n ...this.#unprotectedHeader,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this.#protectedHeader, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = this.#protectedHeader.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n checkKeyType(alg, key, 'sign');\n let payloadS;\n let payloadB;\n if (b64) {\n payloadS = b64u(this.#payload);\n payloadB = encode(payloadS);\n }\n else {\n payloadB = this.#payload;\n payloadS = '';\n }\n let protectedHeaderString;\n let protectedHeaderBytes;\n if (this.#protectedHeader) {\n protectedHeaderString = b64u(JSON.stringify(this.#protectedHeader));\n protectedHeaderBytes = encode(protectedHeaderString);\n }\n else {\n protectedHeaderString = '';\n protectedHeaderBytes = new Uint8Array();\n }\n const data = concat(protectedHeaderBytes, encode('.'), payloadB);\n const k = await normalizeKey(key, alg);\n const signature = await sign(alg, k, data);\n const jws = {\n signature: b64u(signature),\n payload: payloadS,\n };\n if (this.#unprotectedHeader) {\n jws.header = this.#unprotectedHeader;\n }\n if (this.#protectedHeader) {\n jws.protected = protectedHeaderString;\n }\n return jws;\n }\n}\n", "import { FlattenedSign } from '../flattened/sign.js';\nexport class CompactSign {\n #flattened;\n constructor(payload) {\n this.#flattened = new FlattenedSign(payload);\n }\n setProtectedHeader(protectedHeader) {\n this.#flattened.setProtectedHeader(protectedHeader);\n return this;\n }\n async sign(key, options) {\n const jws = await this.#flattened.sign(key, options);\n if (jws.payload === undefined) {\n throw new TypeError('use the flattened module for creating JWS with b64: false');\n }\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n }\n}\n", "import { CompactSign } from '../jws/compact/sign.js';\nimport { JWTInvalid } from '../util/errors.js';\nimport { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';\nexport class SignJWT {\n #protectedHeader;\n #jwt;\n constructor(payload = {}) {\n this.#jwt = new JWTClaimsBuilder(payload);\n }\n setIssuer(issuer) {\n this.#jwt.iss = issuer;\n return this;\n }\n setSubject(subject) {\n this.#jwt.sub = subject;\n return this;\n }\n setAudience(audience) {\n this.#jwt.aud = audience;\n return this;\n }\n setJti(jwtId) {\n this.#jwt.jti = jwtId;\n return this;\n }\n setNotBefore(input) {\n this.#jwt.nbf = input;\n return this;\n }\n setExpirationTime(input) {\n this.#jwt.exp = input;\n return this;\n }\n setIssuedAt(input) {\n this.#jwt.iat = input;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n this.#protectedHeader = protectedHeader;\n return this;\n }\n async sign(key, options) {\n const sig = new CompactSign(this.#jwt.data());\n sig.setProtectedHeader(this.#protectedHeader);\n if (Array.isArray(this.#protectedHeader?.crit) &&\n this.#protectedHeader.crit.includes('b64') &&\n this.#protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n return sig.sign(key, options);\n }\n}\n", "import { CompactEncrypt } from '../jwe/compact/encrypt.js';\nimport { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';\nimport { assertNotSet } from '../lib/helpers.js';\nexport class EncryptJWT {\n #cek;\n #iv;\n #keyManagementParameters;\n #protectedHeader;\n #replicateIssuerAsHeader;\n #replicateSubjectAsHeader;\n #replicateAudienceAsHeader;\n #jwt;\n constructor(payload = {}) {\n this.#jwt = new JWTClaimsBuilder(payload);\n }\n setIssuer(issuer) {\n this.#jwt.iss = issuer;\n return this;\n }\n setSubject(subject) {\n this.#jwt.sub = subject;\n return this;\n }\n setAudience(audience) {\n this.#jwt.aud = audience;\n return this;\n }\n setJti(jwtId) {\n this.#jwt.jti = jwtId;\n return this;\n }\n setNotBefore(input) {\n this.#jwt.nbf = input;\n return this;\n }\n setExpirationTime(input) {\n this.#jwt.exp = input;\n return this;\n }\n setIssuedAt(input) {\n this.#jwt.iat = input;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n assertNotSet(this.#protectedHeader, 'setProtectedHeader');\n this.#protectedHeader = protectedHeader;\n return this;\n }\n setKeyManagementParameters(parameters) {\n assertNotSet(this.#keyManagementParameters, 'setKeyManagementParameters');\n this.#keyManagementParameters = parameters;\n return this;\n }\n setContentEncryptionKey(cek) {\n assertNotSet(this.#cek, 'setContentEncryptionKey');\n this.#cek = cek;\n return this;\n }\n setInitializationVector(iv) {\n assertNotSet(this.#iv, 'setInitializationVector');\n this.#iv = iv;\n return this;\n }\n replicateIssuerAsHeader() {\n this.#replicateIssuerAsHeader = true;\n return this;\n }\n replicateSubjectAsHeader() {\n this.#replicateSubjectAsHeader = true;\n return this;\n }\n replicateAudienceAsHeader() {\n this.#replicateAudienceAsHeader = true;\n return this;\n }\n async encrypt(key, options) {\n const enc = new CompactEncrypt(this.#jwt.data());\n if (this.#protectedHeader &&\n (this.#replicateIssuerAsHeader ||\n this.#replicateSubjectAsHeader ||\n this.#replicateAudienceAsHeader)) {\n this.#protectedHeader = {\n ...this.#protectedHeader,\n iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : undefined,\n sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : undefined,\n aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : undefined,\n };\n }\n enc.setProtectedHeader(this.#protectedHeader);\n if (this.#iv) {\n enc.setInitializationVector(this.#iv);\n }\n if (this.#cek) {\n enc.setContentEncryptionKey(this.#cek);\n }\n if (this.#keyManagementParameters) {\n enc.setKeyManagementParameters(this.#keyManagementParameters);\n }\n return enc.encrypt(key, options);\n }\n}\n", "import { digest } from '../lib/helpers.js';\nimport { encode as b64u } from '../util/base64url.js';\nimport { JOSENotSupported, JWKInvalid } from '../util/errors.js';\nimport { encode } from '../lib/buffer_utils.js';\nimport { isKeyLike } from '../lib/is_key_like.js';\nimport { isJWK } from '../lib/type_checks.js';\nimport { exportJWK } from '../key/export.js';\nimport { invalidKeyInput } from '../lib/invalid_key_input.js';\nconst check = (value, description) => {\n if (typeof value !== 'string' || !value) {\n throw new JWKInvalid(`${description} missing or invalid`);\n }\n};\nexport async function calculateJwkThumbprint(key, digestAlgorithm) {\n let jwk;\n if (isJWK(key)) {\n jwk = key;\n }\n else if (isKeyLike(key)) {\n jwk = await exportJWK(key);\n }\n else {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n digestAlgorithm ??= 'sha256';\n if (digestAlgorithm !== 'sha256' &&\n digestAlgorithm !== 'sha384' &&\n digestAlgorithm !== 'sha512') {\n throw new TypeError('digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"');\n }\n let components;\n switch (jwk.kty) {\n case 'AKP':\n check(jwk.alg, '\"alg\" (Algorithm) Parameter');\n check(jwk.pub, '\"pub\" (Public key) Parameter');\n components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };\n break;\n case 'EC':\n check(jwk.crv, '\"crv\" (Curve) Parameter');\n check(jwk.x, '\"x\" (X Coordinate) Parameter');\n check(jwk.y, '\"y\" (Y Coordinate) Parameter');\n components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n break;\n case 'OKP':\n check(jwk.crv, '\"crv\" (Subtype of Key Pair) Parameter');\n check(jwk.x, '\"x\" (Public Key) Parameter');\n components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n break;\n case 'RSA':\n check(jwk.e, '\"e\" (Exponent) Parameter');\n check(jwk.n, '\"n\" (Modulus) Parameter');\n components = { e: jwk.e, kty: jwk.kty, n: jwk.n };\n break;\n case 'oct':\n check(jwk.k, '\"k\" (Key Value) Parameter');\n components = { k: jwk.k, kty: jwk.kty };\n break;\n default:\n throw new JOSENotSupported('\"kty\" (Key Type) Parameter missing or unsupported');\n }\n const data = encode(JSON.stringify(components));\n return b64u(await digest(digestAlgorithm, data));\n}\nexport async function calculateJwkThumbprintUri(key, digestAlgorithm) {\n digestAlgorithm ??= 'sha256';\n const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);\n return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;\n}\n", "import { importJWK } from '../key/import.js';\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nfunction getKtyFromAlg(alg) {\n switch (typeof alg === 'string' && alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n return 'RSA';\n case 'ES':\n return 'EC';\n case 'Ed':\n return 'OKP';\n case 'ML':\n return 'AKP';\n default:\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n }\n}\nfunction isJWKSLike(jwks) {\n return (jwks &&\n typeof jwks === 'object' &&\n Array.isArray(jwks.keys) &&\n jwks.keys.every(isJWKLike));\n}\nfunction isJWKLike(key) {\n return isObject(key);\n}\nclass LocalJWKSet {\n #jwks;\n #cached = new WeakMap();\n constructor(jwks) {\n if (!isJWKSLike(jwks)) {\n throw new JWKSInvalid('JSON Web Key Set malformed');\n }\n this.#jwks = structuredClone(jwks);\n }\n jwks() {\n return this.#jwks;\n }\n async getKey(protectedHeader, token) {\n const { alg, kid } = { ...protectedHeader, ...token?.header };\n const kty = getKtyFromAlg(alg);\n const candidates = this.#jwks.keys.filter((jwk) => {\n let candidate = kty === jwk.kty;\n if (candidate && typeof kid === 'string') {\n candidate = kid === jwk.kid;\n }\n if (candidate && (typeof jwk.alg === 'string' || kty === 'AKP')) {\n candidate = alg === jwk.alg;\n }\n if (candidate && typeof jwk.use === 'string') {\n candidate = jwk.use === 'sig';\n }\n if (candidate && Array.isArray(jwk.key_ops)) {\n candidate = jwk.key_ops.includes('verify');\n }\n if (candidate) {\n switch (alg) {\n case 'ES256':\n candidate = jwk.crv === 'P-256';\n break;\n case 'ES384':\n candidate = jwk.crv === 'P-384';\n break;\n case 'ES512':\n candidate = jwk.crv === 'P-521';\n break;\n case 'Ed25519':\n case 'EdDSA':\n candidate = jwk.crv === 'Ed25519';\n break;\n }\n }\n return candidate;\n });\n const { 0: jwk, length } = candidates;\n if (length === 0) {\n throw new JWKSNoMatchingKey();\n }\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n const _cached = this.#cached;\n error[Symbol.asyncIterator] = async function* () {\n for (const jwk of candidates) {\n try {\n yield await importWithAlgCache(_cached, jwk, alg);\n }\n catch { }\n }\n };\n throw error;\n }\n return importWithAlgCache(this.#cached, jwk, alg);\n }\n}\nasync function importWithAlgCache(cache, jwk, alg) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);\n if (cached[alg] === undefined) {\n const key = await importJWK({ ...jwk, ext: true }, alg);\n if (key instanceof Uint8Array || key.type !== 'public') {\n throw new JWKSInvalid('JSON Web Key Set members must be public keys');\n }\n cached[alg] = key;\n }\n return cached[alg];\n}\nexport function createLocalJWKSet(jwks) {\n const set = new LocalJWKSet(jwks);\n const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(localJWKSet, {\n jwks: {\n value: () => structuredClone(set.jwks()),\n enumerable: false,\n configurable: false,\n writable: false,\n },\n });\n return localJWKSet;\n}\n", "import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js';\nimport { createLocalJWKSet } from './local.js';\nimport { isObject } from '../lib/type_checks.js';\nfunction isCloudflareWorkers() {\n return (typeof WebSocketPair !== 'undefined' ||\n (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||\n (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));\n}\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'jose';\n const VERSION = 'v6.2.2';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nexport const customFetch = Symbol();\nasync function fetchJwks(url, headers, signal, fetchImpl = fetch) {\n const response = await fetchImpl(url, {\n method: 'GET',\n signal,\n redirect: 'manual',\n headers,\n }).catch((err) => {\n if (err.name === 'TimeoutError') {\n throw new JWKSTimeout();\n }\n throw err;\n });\n if (response.status !== 200) {\n throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');\n }\n try {\n return await response.json();\n }\n catch {\n throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');\n }\n}\nexport const jwksCache = Symbol();\nfunction isFreshJwksCache(input, cacheMaxAge) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {\n return false;\n }\n if (!('jwks' in input) ||\n !isObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isObject)) {\n return false;\n }\n return true;\n}\nclass RemoteJWKSet {\n #url;\n #timeoutDuration;\n #cooldownDuration;\n #cacheMaxAge;\n #jwksTimestamp;\n #pendingFetch;\n #headers;\n #customFetch;\n #local;\n #cache;\n constructor(url, options) {\n if (!(url instanceof URL)) {\n throw new TypeError('url must be an instance of URL');\n }\n this.#url = new URL(url.href);\n this.#timeoutDuration =\n typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;\n this.#cooldownDuration =\n typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;\n this.#cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;\n this.#headers = new Headers(options?.headers);\n if (USER_AGENT && !this.#headers.has('User-Agent')) {\n this.#headers.set('User-Agent', USER_AGENT);\n }\n if (!this.#headers.has('accept')) {\n this.#headers.set('accept', 'application/json');\n this.#headers.append('accept', 'application/jwk-set+json');\n }\n this.#customFetch = options?.[customFetch];\n if (options?.[jwksCache] !== undefined) {\n this.#cache = options?.[jwksCache];\n if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {\n this.#jwksTimestamp = this.#cache.uat;\n this.#local = createLocalJWKSet(this.#cache.jwks);\n }\n }\n }\n pendingFetch() {\n return !!this.#pendingFetch;\n }\n coolingDown() {\n return typeof this.#jwksTimestamp === 'number'\n ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration\n : false;\n }\n fresh() {\n return typeof this.#jwksTimestamp === 'number'\n ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge\n : false;\n }\n jwks() {\n return this.#local?.jwks();\n }\n async getKey(protectedHeader, token) {\n if (!this.#local || !this.fresh()) {\n await this.reload();\n }\n try {\n return await this.#local(protectedHeader, token);\n }\n catch (err) {\n if (err instanceof JWKSNoMatchingKey) {\n if (this.coolingDown() === false) {\n await this.reload();\n return this.#local(protectedHeader, token);\n }\n }\n throw err;\n }\n }\n async reload() {\n if (this.#pendingFetch && isCloudflareWorkers()) {\n this.#pendingFetch = undefined;\n }\n this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch)\n .then((json) => {\n this.#local = createLocalJWKSet(json);\n if (this.#cache) {\n this.#cache.uat = Date.now();\n this.#cache.jwks = json;\n }\n this.#jwksTimestamp = Date.now();\n this.#pendingFetch = undefined;\n })\n .catch((err) => {\n this.#pendingFetch = undefined;\n throw err;\n });\n await this.#pendingFetch;\n }\n}\nexport function createRemoteJWKSet(url, options) {\n const set = new RemoteJWKSet(url, options);\n const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(remoteJWKSet, {\n coolingDown: {\n get: () => set.coolingDown(),\n enumerable: true,\n configurable: false,\n },\n fresh: {\n get: () => set.fresh(),\n enumerable: true,\n configurable: false,\n },\n reload: {\n value: () => set.reload(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n reloading: {\n get: () => set.pendingFetch(),\n enumerable: true,\n configurable: false,\n },\n jwks: {\n value: () => set.jwks(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n });\n return remoteJWKSet;\n}\n", "import { decode as b64u } from './base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport { isObject } from '../lib/type_checks.js';\nexport function decodeProtectedHeader(token) {\n let protectedB64u;\n if (typeof token === 'string') {\n const parts = token.split('.');\n if (parts.length === 3 || parts.length === 5) {\n ;\n [protectedB64u] = parts;\n }\n }\n else if (typeof token === 'object' && token) {\n if ('protected' in token) {\n protectedB64u = token.protected;\n }\n else {\n throw new TypeError('Token does not contain a Protected Header');\n }\n }\n try {\n if (typeof protectedB64u !== 'string' || !protectedB64u) {\n throw new Error();\n }\n const result = JSON.parse(decoder.decode(b64u(protectedB64u)));\n if (!isObject(result)) {\n throw new Error();\n }\n return result;\n }\n catch {\n throw new TypeError('Invalid Token or Protected Header formatting');\n }\n}\n", "import { decode as b64u } from './base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport { isObject } from '../lib/type_checks.js';\nimport { JWTInvalid } from './errors.js';\nexport function decodeJwt(jwt) {\n if (typeof jwt !== 'string')\n throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');\n const { 1: payload, length } = jwt.split('.');\n if (length === 5)\n throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');\n if (length !== 3)\n throw new JWTInvalid('Invalid JWT');\n if (!payload)\n throw new JWTInvalid('JWTs must contain a payload');\n let decoded;\n try {\n decoded = b64u(payload);\n }\n catch {\n throw new JWTInvalid('Failed to base64url decode the payload');\n }\n let result;\n try {\n result = JSON.parse(decoder.decode(decoded));\n }\n catch {\n throw new JWTInvalid('Failed to parse the decoded payload as JSON');\n }\n if (!isObject(result))\n throw new JWTInvalid('Invalid JWT Claims Set');\n return result;\n}\n", "import { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { EncryptJWT, SignJWT, base64url, calculateJwkThumbprint, decodeProtectedHeader, jwtDecrypt, jwtVerify } from \"jose\";\n//#region src/crypto/jwt.ts\nasync function signJWT(payload, secret, expiresIn = 3600) {\n\treturn await new SignJWT(payload).setProtectedHeader({ alg: \"HS256\" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret));\n}\nasync function verifyJWT(token, secret) {\n\ttry {\n\t\treturn (await jwtVerify(token, new TextEncoder().encode(secret))).payload;\n\t} catch {\n\t\treturn null;\n\t}\n}\nconst info = new Uint8Array([\n\t66,\n\t101,\n\t116,\n\t116,\n\t101,\n\t114,\n\t65,\n\t117,\n\t116,\n\t104,\n\t46,\n\t106,\n\t115,\n\t32,\n\t71,\n\t101,\n\t110,\n\t101,\n\t114,\n\t97,\n\t116,\n\t101,\n\t100,\n\t32,\n\t69,\n\t110,\n\t99,\n\t114,\n\t121,\n\t112,\n\t116,\n\t105,\n\t111,\n\t110,\n\t32,\n\t75,\n\t101,\n\t121\n]);\nconst now = () => Date.now() / 1e3 | 0;\nconst alg = \"dir\";\nconst enc = \"A256CBC-HS512\";\nfunction deriveEncryptionSecret(secret, salt) {\n\treturn hkdf(sha256, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64);\n}\nfunction getCurrentSecret(secret) {\n\tif (typeof secret === \"string\") return secret;\n\tconst value = secret.keys.get(secret.currentVersion);\n\tif (!value) throw new Error(`Secret version ${secret.currentVersion} not found in keys`);\n\treturn value;\n}\nfunction getAllSecrets(secret) {\n\tif (typeof secret === \"string\") return [{\n\t\tversion: 0,\n\t\tvalue: secret\n\t}];\n\tconst result = [];\n\tfor (const [version, value] of secret.keys) result.push({\n\t\tversion,\n\t\tvalue\n\t});\n\tif (secret.legacySecret && !result.some((s) => s.value === secret.legacySecret)) result.push({\n\t\tversion: -1,\n\t\tvalue: secret.legacySecret\n\t});\n\treturn result;\n}\nasync function symmetricEncodeJWT(payload, secret, salt, expiresIn = 3600) {\n\tconst encryptionSecret = deriveEncryptionSecret(getCurrentSecret(secret), salt);\n\tconst thumbprint = await calculateJwkThumbprint({\n\t\tkty: \"oct\",\n\t\tk: base64url.encode(encryptionSecret)\n\t}, \"sha256\");\n\treturn await new EncryptJWT(payload).setProtectedHeader({\n\t\talg,\n\t\tenc,\n\t\tkid: thumbprint\n\t}).setIssuedAt().setExpirationTime(now() + expiresIn).setJti(crypto.randomUUID()).encrypt(encryptionSecret);\n}\nconst jwtDecryptOpts = {\n\tclockTolerance: 15,\n\tkeyManagementAlgorithms: [alg],\n\tcontentEncryptionAlgorithms: [enc, \"A256GCM\"]\n};\nasync function symmetricDecodeJWT(token, secret, salt) {\n\tif (!token) return null;\n\tlet hasKid = false;\n\ttry {\n\t\thasKid = decodeProtectedHeader(token).kid !== void 0;\n\t} catch {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst secrets = getAllSecrets(secret);\n\t\tconst { payload } = await jwtDecrypt(token, async (protectedHeader) => {\n\t\t\tconst kid = protectedHeader.kid;\n\t\t\tif (kid !== void 0) {\n\t\t\t\tfor (const s of secrets) {\n\t\t\t\t\tconst encryptionSecret = deriveEncryptionSecret(s.value, salt);\n\t\t\t\t\tif (kid === await calculateJwkThumbprint({\n\t\t\t\t\t\tkty: \"oct\",\n\t\t\t\t\t\tk: base64url.encode(encryptionSecret)\n\t\t\t\t\t}, \"sha256\")) return encryptionSecret;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"no matching decryption secret\");\n\t\t\t}\n\t\t\tif (secrets.length === 1) return deriveEncryptionSecret(secrets[0].value, salt);\n\t\t\treturn deriveEncryptionSecret(secrets[0].value, salt);\n\t\t}, jwtDecryptOpts);\n\t\treturn payload;\n\t} catch {\n\t\tif (hasKid) return null;\n\t\tconst secrets = getAllSecrets(secret);\n\t\tif (secrets.length <= 1) return null;\n\t\tfor (let i = 1; i < secrets.length; i++) try {\n\t\t\tconst s = secrets[i];\n\t\t\tconst { payload } = await jwtDecrypt(token, deriveEncryptionSecret(s.value, salt), jwtDecryptOpts);\n\t\t\treturn payload;\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\treturn null;\n\t}\n}\n//#endregion\nexport { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT };\n", "import { randomBytes, scrypt } from 'node:crypto';\n\nconst config = {\n N: 16384,\n r: 16,\n p: 1,\n dkLen: 64\n};\nfunction generateKey(password, salt) {\n return new Promise((resolve, reject) => {\n scrypt(\n password.normalize(\"NFKC\"),\n salt,\n config.dkLen,\n {\n N: config.N,\n r: config.r,\n p: config.p,\n maxmem: 128 * config.N * config.r * 2\n },\n (err, key) => {\n if (err)\n reject(err);\n else\n resolve(key);\n }\n );\n });\n}\nasync function hashPassword(password) {\n const salt = randomBytes(16).toString(\"hex\");\n const key = await generateKey(password, salt);\n return `${salt}:${key.toString(\"hex\")}`;\n}\nasync function verifyPassword(hash, password) {\n const [salt, key] = hash.split(\":\");\n if (!salt || !key) {\n throw new Error(\"Invalid password hash\");\n }\n const targetKey = await generateKey(password, salt);\n return targetKey.toString(\"hex\") === key;\n}\n\nexport { hashPassword, verifyPassword };\n", "import { hashPassword, verifyPassword } from \"@better-auth/utils/password\";\n//#region src/crypto/password.ts\n/**\n* `@better-auth/utils/password` uses the \"node\" export condition in package.json\n* to automatically pick the right implementation:\n* - Node.js / Bun / Deno \u2192 `node:crypto scrypt` (libuv thread pool, non-blocking)\n* - Unsupported runtimes \u2192 `@noble/hashes scrypt` (pure JS fallback)\n*/\nconst hashPassword$1 = hashPassword;\nconst verifyPassword$1 = async ({ hash, password }) => {\n\treturn verifyPassword(hash, password);\n};\n//#endregion\nexport { hashPassword$1 as hashPassword, verifyPassword$1 as verifyPassword };\n", "function getAlphabet(urlSafe) {\n return urlSafe ? \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n}\nfunction base64Encode(data, alphabet, padding) {\n let result = \"\";\n let buffer = 0;\n let shift = 0;\n for (const byte of data) {\n buffer = buffer << 8 | byte;\n shift += 8;\n while (shift >= 6) {\n shift -= 6;\n result += alphabet[buffer >> shift & 63];\n }\n }\n if (shift > 0) {\n result += alphabet[buffer << 6 - shift & 63];\n }\n if (padding) {\n const padCount = (4 - result.length % 4) % 4;\n result += \"=\".repeat(padCount);\n }\n return result;\n}\nfunction base64Decode(data, alphabet) {\n const decodeMap = /* @__PURE__ */ new Map();\n for (let i = 0; i < alphabet.length; i++) {\n decodeMap.set(alphabet[i], i);\n }\n const result = [];\n let buffer = 0;\n let bitsCollected = 0;\n for (const char of data) {\n if (char === \"=\")\n break;\n const value = decodeMap.get(char);\n if (value === void 0) {\n throw new Error(`Invalid Base64 character: ${char}`);\n }\n buffer = buffer << 6 | value;\n bitsCollected += 6;\n if (bitsCollected >= 8) {\n bitsCollected -= 8;\n result.push(buffer >> bitsCollected & 255);\n }\n }\n return Uint8Array.from(result);\n}\nconst base64 = {\n encode(data, options = {}) {\n const alphabet = getAlphabet(false);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base64Encode(buffer, alphabet, options.padding ?? true);\n },\n decode(data) {\n if (typeof data !== \"string\") {\n data = new TextDecoder().decode(data);\n }\n const urlSafe = data.includes(\"-\") || data.includes(\"_\");\n const alphabet = getAlphabet(urlSafe);\n return base64Decode(data, alphabet);\n }\n};\nconst base64Url = {\n encode(data, options = {}) {\n const alphabet = getAlphabet(true);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base64Encode(buffer, alphabet, options.padding ?? true);\n },\n decode(data) {\n const urlSafe = data.includes(\"-\") || data.includes(\"_\");\n const alphabet = getAlphabet(urlSafe);\n return base64Decode(data, alphabet);\n }\n};\n\nexport { base64, base64Url };\n", "function getWebcryptoSubtle() {\n const cr = typeof globalThis !== \"undefined\" && globalThis.crypto;\n if (cr && typeof cr.subtle === \"object\" && cr.subtle != null)\n return cr.subtle;\n throw new Error(\"crypto.subtle must be defined\");\n}\n\nexport { getWebcryptoSubtle };\n", "import { base64Url, base64 } from './base64.mjs';\nimport { getWebcryptoSubtle } from './index.mjs';\n\nfunction createHash(algorithm, encoding) {\n return {\n digest: async (input) => {\n const encoder = new TextEncoder();\n const data = typeof input === \"string\" ? encoder.encode(input) : input;\n const hashBuffer = await getWebcryptoSubtle().digest(algorithm, data);\n if (encoding === \"hex\") {\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return hashHex;\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n if (encoding.includes(\"url\")) {\n return base64Url.encode(hashBuffer, {\n padding: encoding !== \"base64urlnopad\"\n });\n }\n const hashBase64 = base64.encode(hashBuffer);\n return hashBase64;\n }\n return hashBuffer;\n }\n };\n}\n\nexport { createHash };\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - Value to inspect.\n * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.\n * @example\n * Guards a value before treating it as raw key material.\n *\n * ```ts\n * isBytes(new Uint8Array());\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /\n // cross-realm cases. The fallback still requires a real ArrayBuffer view\n // so plain JSON-deserialized `{ constructor: ... }`\n // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is boolean.\n * @param b - Value to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validates a boolean option before branching on it.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(b: boolean): void {\n if (typeof b !== 'boolean') throw new TypeError(`boolean expected, not ${b}`);\n}\n\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validates a non-negative length or counter.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport function anumber(n: number): void {\n if (typeof n !== 'number') throw new TypeError('number expected, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError('positive integer expected, got ' + n);\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - Value to validate.\n * @param length - Expected byte length.\n * @param title - Optional label used in error messages.\n * @returns The validated byte array.\n * On Node, `Buffer` is accepted too because it is a Uint8Array view.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument lengths. {@link RangeError}\n * @example\n * Validates a fixed-length nonce or key buffer.\n *\n * ```ts\n * abytes(new Uint8Array([1, 2]), 2);\n * ```\n */\nexport function abytes(\n value: TArg,\n length?: number,\n title: string = ''\n): TRet {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet;\n}\n\n/**\n * Asserts a hash- or MAC-like instance has not been destroyed or finished.\n * @param instance - Stateful instance to validate.\n * @param checkFinished - Whether to reject finished instances.\n * When `false`, only `destroyed` is checked.\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Guards against calling `update()` or `digest()` on a finished hash.\n *\n * ```ts\n * aexists({ destroyed: false, finished: false });\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a properly-sized byte array.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,\n * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.\n * @throws On wrong argument types. {@link TypeError}\n * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @throws On wrong output buffer alignment. {@link Error}\n * @example\n * Verifies that a caller-provided output buffer is large enough.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out: any, instance: any, onlyAligned = false): void {\n abytes(out, undefined, 'output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('digestInto() expects output buffer of length at least ' + min);\n }\n if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n}\n\n/** One-shot hash helper with `.create()`. */\nexport type IHash = {\n (data: string | TArg): TRet;\n /** Input block size in bytes. */\n blockLen: number;\n /** Digest size in bytes. */\n outputLen: number;\n /** Creates a fresh incremental hash instance of the same algorithm. */\n create: any;\n};\n\n/** One-shot MAC helper with `.create()`. */\nexport type CMac = {\n (msg: TArg, key: TArg): TRet;\n /** Input block size in bytes. */\n blockLen: number;\n /** Digest size in bytes. */\n outputLen: number;\n /**\n * Creates a fresh incremental MAC instance of the same algorithm.\n * @param key - MAC key bytes.\n * @param args - Additional constructor arguments, when the MAC wrapper needs them.\n * @returns Fresh incremental MAC instance.\n */\n create(key: TArg, ...args: A): H;\n};\n\n/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed-array view to Uint8Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint8Array view over the same bytes.\n * @example\n * Views 32-bit words as raw bytes without copying.\n *\n * ```ts\n * u8(new Uint32Array([1]));\n * ```\n */\nexport function u8(arr: TArg): TRet {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet;\n}\n\n/**\n * Casts a typed-array view to Uint32Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint32Array view over the same bytes. Callers are expected to provide a\n * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.\n * @example\n * Views a byte buffer as 32-bit words for block processing.\n *\n * ```ts\n * u32(new Uint8Array(4));\n * ```\n */\nexport function u32(arr: TArg): TRet {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet;\n}\n\n/**\n * Zeroizes typed arrays in place.\n * Warning: JS provides no guarantees.\n * @param arrays - Arrays to wipe.\n * @example\n * Wipes a temporary key buffer after use.\n *\n * ```ts\n * const bytes = new Uint8Array([1]);\n * clean(bytes);\n * ```\n */\nexport function clean(...arrays: TArg): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - Typed-array view to wrap.\n * @returns DataView over the same bytes.\n * @example\n * Creates an endian-aware view for length encoding.\n *\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Whether the current platform is little-endian.\n * Most are; some IBM systems are not.\n */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Reverses byte order of one 32-bit word.\n * @param word - Unsigned 32-bit word to swap.\n * @returns The same word with bytes reversed.\n * @example\n * Swaps a big-endian word into little-endian byte order.\n *\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport const byteSwap = (word: number): number =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n\n/**\n * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.\n * @param n - Unsigned 32-bit word to normalize.\n * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.\n * @example\n * Normalizes a host-endian word before passing it into an ARX/AES core.\n *\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - Uint32Array whose words should be swapped.\n * @returns The same array after in-place byte swapping.\n * @example\n * Swaps every 32-bit word in a word-view buffer.\n *\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport const byteSwap32 = (arr: TArg): TRet => {\n for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]);\n return arr as TRet;\n};\n\n/**\n * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.\n * @param u - Word view to normalize in place.\n * @returns Little-endian normalized word view.\n * @example\n * Normalizes a word-view buffer before block processing.\n *\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg) => TRet = isLE\n ? (u: TArg) => u as TRet\n : byteSwap32;\n\n// Built-in hex conversion:\n// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Formats ciphertext bytes for logs or test vectors.\n *\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - Hexadecimal string to decode.\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On malformed hexadecimal input. {@link RangeError}\n * @example\n * Parses a hex test vector into bytes.\n *\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array as TRet;\n}\n\n// Used in micro\n/**\n * Converts a big-endian hex string into bigint.\n * @param hex - Hexadecimal string without `0x`.\n * @returns Parsed bigint value. The empty string is treated as `0n`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parses a big-endian field element or counter from hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian\n}\n\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\n/**\n * Converts big-endian bytes into bigint.\n * @param bytes - Big-endian bytes.\n * @returns Parsed bigint value. Empty input is treated as `0n`.\n * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}\n * @example\n * Reads a big-endian integer from serialized bytes.\n *\n * ```ts\n * bytesToNumberBE(new Uint8Array([1, 0]));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\n// Used in micro, ff1\n/**\n * Converts a number into big-endian bytes of fixed length.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Big-endian bytes padded to `len`.\n * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,\n * and values that do not fit surface through the downstream hex parser instead of a\n * dedicated range guard here.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the requested output length cannot represent the encoded value. {@link RangeError}\n * @example\n * Encodes a counter as fixed-width big-endian bytes.\n *\n * ```ts\n * numberToBytesBE(1, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet {\n // Reject coercible non-numeric inputs before string/hex conversion changes behavior.\n if (typeof n === 'number') anumber(n);\n else if (typeof n !== 'bigint') throw new TypeError(`number or bigint expected, got ${typeof n}`);\n anumber(len);\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// Global symbols, but ts doesn't see them:\n// {@link https://github.com/microsoft/TypeScript/issues/31535 | TypeScript issue 31535}\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @param str - String to encode.\n * @returns UTF-8 bytes in a detached fresh Uint8Array copy.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encodes application text before encryption or MACing.\n *\n * ```ts\n * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)) as TRet; // {@link https://bugzil.la/1681809 | Firefox bug 1681809}\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @param bytes - UTF-8 bytes.\n * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed\n * UTF-8 is replacement-decoded instead of rejected.\n * @example\n * Decodes UTF-8 plaintext back into a string.\n *\n * ```ts\n * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'\n * ```\n */\nexport function bytesToUtf8(bytes: TArg): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n * @param a - First byte view.\n * @param b - Second byte view.\n * @returns `true` when the views overlap in memory.\n * @example\n * Detects whether two slices alias the same backing buffer.\n *\n * ```ts\n * overlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function overlapBytes(a: TArg, b: TArg): boolean {\n // Zero-length views cannot overwrite anything, even if their offset sits inside another range.\n if (!a.byteLength || !b.byteLength) return false;\n return (\n a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported for most ciphers\n * (except chacha/salsa, which were designed for this)\n * @param input - Input bytes.\n * @param output - Output bytes.\n * @throws If the output view would overwrite unread input bytes. {@link Error}\n * @example\n * Rejects an in-place layout that would overwrite unread input bytes.\n *\n * ```ts\n * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function complexOverlapBytes(input: TArg, output: TArg): void {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - Byte arrays to concatenate.\n * @returns Combined byte array.\n * @throws On wrong argument types inside the byte-array list. {@link TypeError}\n * @example\n * Builds a `nonce || ciphertext` style buffer.\n *\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg): TRet {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res as TRet;\n}\n\n// Used in ARX only\ntype EmptyObj = {};\n/**\n * Merges user options into defaults.\n * @param defaults - Default option values.\n * @param opts - User-provided overrides.\n * @returns Combined options object.\n * The merge mutates `defaults` in place and returns the same object.\n * @throws If options are missing or not an object. {@link Error}\n * @example\n * Applies user overrides to the default cipher options.\n *\n * ```ts\n * checkOpts({ rounds: 20 }, { rounds: 8 });\n * ```\n */\nexport function checkOpts(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/**\n * Compares two byte arrays in kinda constant time once lengths already match.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` when the arrays contain the same bytes. Different lengths still return early.\n * @example\n * Compares an expected authentication tag with the received one.\n *\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg, b: TArg): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// TODO: remove\n/** Incremental hash interface used internally. */\nexport interface IHash2 {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by the final digest. */\n outputLen: number;\n /**\n * Absorbs one more chunk into the hash state.\n * @param buf - Data chunk to hash.\n * @returns The same hash instance for chaining.\n */\n update(buf: string | TArg): this;\n /**\n * Writes the final digest into a caller-provided buffer.\n * @param buf - Destination buffer for the digest bytes.\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg): void;\n /**\n * Finalizes the hash and returns a fresh digest buffer.\n * @returns Digest bytes.\n */\n digest(): TRet;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n destroy(): void;\n}\n\n/**\n * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.\n * @param keyLen - Valid probe-key length used to read static metadata once.\n * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes\n * can pass any representative size as long as those values stay fixed.\n * @param macCons - Keyed MAC constructor or factory.\n * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.\n * @returns Callable MAC helper with `.create()`.\n */\nexport function wrapMacConstructor(\n keyLen: number,\n macCons: TArg<(key: Uint8Array, ...args: A) => H>,\n fromMsg?: TArg<(msg: Uint8Array) => A>\n): TRet> {\n const mac = macCons as (key: TArg, ...args: A) => H;\n const getArgs = (fromMsg || (() => [] as unknown as A)) as (msg: TArg) => A;\n const macC: any = (msg: TArg, key: TArg): TRet =>\n mac(key, ...getArgs(msg))\n .update(msg)\n .digest();\n const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));\n macC.outputLen = tmp.outputLen;\n macC.blockLen = tmp.blockLen;\n macC.create = (key: TArg, ...args: A) => mac(key, ...args);\n return macC as TRet>;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\n\n/** Sync cipher: takes byte array and returns byte array. */\nexport type Cipher = {\n /**\n * Encrypts plaintext bytes.\n * @param plaintext - Data to encrypt.\n * @returns Ciphertext bytes.\n */\n encrypt(plaintext: TArg): TRet;\n /**\n * Decrypts ciphertext bytes.\n * @param ciphertext - Data to decrypt.\n * @returns Plaintext bytes.\n */\n decrypt(ciphertext: TArg): TRet;\n};\n\n/** Async cipher e.g. from built-in WebCrypto. */\nexport type AsyncCipher = {\n /**\n * Encrypts plaintext bytes.\n * @param plaintext - Data to encrypt.\n * @returns Promise resolving to ciphertext bytes.\n */\n encrypt(plaintext: TArg): Promise>;\n /**\n * Decrypts ciphertext bytes.\n * @param ciphertext - Data to decrypt.\n * @returns Promise resolving to plaintext bytes.\n */\n decrypt(ciphertext: TArg): Promise>;\n};\n\n/** Cipher with `output` argument which can optimize by doing 1 less allocation. */\nexport type CipherWithOutput = Cipher & {\n /**\n * Encrypts plaintext bytes into an optional caller-provided buffer.\n * @param plaintext - Data to encrypt.\n * @param output - Optional destination buffer.\n * @returns Ciphertext bytes.\n */\n encrypt(plaintext: TArg, output?: TArg): TRet;\n /**\n * Decrypts ciphertext bytes into an optional caller-provided buffer.\n * @param ciphertext - Data to decrypt.\n * @param output - Optional destination buffer.\n * @returns Plaintext bytes.\n */\n decrypt(ciphertext: TArg, output?: TArg): TRet;\n};\n\n/**\n * Params are outside of return type, so it is accessible before calling constructor.\n * If function support multiple nonceLength's, we return the best one.\n */\nexport type CipherParams = {\n /** Cipher block size in bytes. */\n blockSize: number;\n /** Nonce length in bytes when the cipher uses a fixed nonce size. */\n nonceLength?: number;\n /** Authentication-tag length in bytes for AEAD modes. */\n tagLength?: number;\n /** Whether nonce length is variable at runtime. */\n varSizeNonce?: boolean;\n};\n/**\n * ARX AEAD cipher, like salsa or chacha.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param AAD - Optional associated data.\n * @returns Cipher instance with caller-managed output buffers.\n */\nexport type ARXCipher = ((\n key: TArg,\n nonce: TArg,\n AAD?: TArg\n) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n};\n/**\n * Cipher constructor signature.\n * @param key - Secret key bytes.\n * @param args - Additional constructor arguments, such as nonce or IV.\n * @returns Cipher instance.\n */\nexport type CipherCons = (key: TArg, ...args: T) => Cipher;\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * Used internally by the exported cipher constructors.\n * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`\n * arity (`fn.length === 2`), and tag-bearing constructors are expected to use\n * `args[1]` for optional AAD.\n * @__NO_SIDE_EFFECTS__\n * @param params - Static cipher metadata. See {@link CipherParams}.\n * @param constructor - Cipher constructor.\n * @returns Wrapped constructor with validation.\n */\nexport const wrapCipher = , P extends CipherParams>(\n params: P,\n constructor: C\n): C & P => {\n function wrappedCipher(key: TArg, ...args: any[]): TRet {\n // Validate key\n abytes(key, undefined, 'key');\n\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n }\n\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined) abytes(args[1], undefined, 'AAD');\n\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength: number, output?: TArg) => {\n if (output !== undefined) {\n if (fnLength !== 2) throw new Error('cipher output not supported');\n abytes(output, undefined, 'output');\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data: TArg, output?: TArg) {\n if (called) throw new Error('cannot encrypt() twice with same key + nonce');\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return (cipher as CipherWithOutput).encrypt(data, output);\n },\n decrypt(data: TArg, output?: TArg) {\n abytes(data);\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return (cipher as CipherWithOutput).decrypt(data, output);\n },\n };\n\n return wrCipher as TRet;\n }\n\n Object.assign(wrappedCipher, params);\n return wrappedCipher as C & P;\n};\n\n/**\n * Represents a Salsa or ChaCha xor stream.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Optional starting block counter.\n * @returns Output bytes.\n */\nexport type XorStream = (\n key: TArg,\n nonce: TArg,\n data: TArg,\n output?: TArg,\n counter?: number\n) => TRet;\n\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n * @param expectedLength - Required output length.\n * @param out - Optional destination buffer.\n * @param onlyAligned - Whether `out` must be 4-byte aligned.\n * @returns Output buffer ready for writing.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the provided output buffer has the wrong size or alignment. {@link Error}\n * @example\n * Reuses a caller-provided output buffer when lengths match.\n *\n * ```ts\n * getOutput(16, new Uint8Array(16));\n * ```\n */\nexport function getOutput(\n expectedLength: number,\n out?: TArg,\n onlyAligned = true\n): TRet {\n if (out === undefined) return new Uint8Array(expectedLength) as TRet;\n // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.\n abytes(out, undefined, 'output');\n if (out.length !== expectedLength)\n throw new Error(\n '\"output\" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length\n );\n if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n return out as TRet;\n}\n\n/**\n * Encodes data and AAD bit lengths into a 16-byte buffer.\n * @param dataLength - Data length in bits.\n * @param aadLength - AAD length in bits.\n * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305\n * conventions even though the helper parameter order is `(dataLength, aadLength)`.\n * @param isLE - Whether to encode lengths as little-endian.\n * @returns 16-byte length block.\n * @throws On wrong argument types passed to the endian validator. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Builds the length block appended by GCM and Poly1305.\n *\n * ```ts\n * u64Lengths(16, 8, true);\n * ```\n */\nexport function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet {\n // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.\n anumber(dataLength);\n anumber(aadLength);\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, BigInt(aadLength), isLE);\n view.setBigUint64(8, BigInt(dataLength), isLE);\n return num as TRet;\n}\n\n/**\n * Checks whether a byte array is aligned to a 4-byte offset.\n * @param bytes - Byte array to inspect.\n * @returns `true` when the view is 4-byte aligned.\n * @example\n * Checks whether a buffer can be safely viewed as Uint32Array.\n *\n * ```ts\n * isAligned32(new Uint8Array(4));\n * ```\n */\nexport function isAligned32(bytes: TArg): boolean {\n return bytes.byteOffset % 4 === 0;\n}\n\n/**\n * Copies bytes into a new Uint8Array.\n * @param bytes - Bytes to copy.\n * @returns Copied byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Copies input into an aligned Uint8Array before block processing.\n *\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg): TRet {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet;\n}\n\n/**\n * Cryptographically secure PRNG.\n * Uses internal OS-level `crypto.getRandomValues`.\n * @param bytesLength - Number of bytes to produce.\n * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so\n * non-integers, negative lengths, and oversize requests surface backend/runtime errors.\n * @returns Random byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}\n * @example\n * Generates a fresh nonce or key.\n *\n * ```ts\n * randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet {\n // Validate upfront so fractional / coercible lengths do not silently\n // truncate through Uint8Array().\n anumber(bytesLength);\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength)) as TRet;\n}\n\n/**\n * The pseudorandom number generator doesn't wipe current state:\n * instead, it generates new one based on previous state + entropy.\n * Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes,\n * which is in fact `reseed`, since it changes counter too.\n */\nexport interface PRG {\n /**\n * Mixes fresh entropy into the current generator state.\n * @param seed - Entropy bytes to absorb.\n */\n addEntropy(seed: TArg): void;\n /**\n * Produces a requested number of pseudorandom bytes.\n * @param bytesLength - Number of bytes to generate.\n * @returns Random byte array.\n */\n randomBytes(bytesLength: number): TRet;\n /** Destroys the generator state. */\n clean(): void;\n}\n\n/** Removes the nonce argument from a cipher constructor type. */\nexport type RemoveNonce any> = T extends (\n arg0: any,\n arg1: any,\n ...rest: infer R\n) => infer Ret\n ? (key: TArg, ...args: R) => Ret\n : never;\n/**\n * Cipher constructor that requires a nonce argument.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param args - Additional cipher-specific arguments.\n * @returns Cipher instance.\n */\nexport type CipherWithNonce = ((\n key: TArg,\n nonce: TArg,\n ...args: any[]\n) => Cipher | AsyncCipher) & {\n nonceLength: number;\n};\n\n/**\n * Uses CSPRNG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`\n * buffer on encrypt and intentionally does not support caller-provided destination buffers.\n * Too-short decrypt inputs are split into short/empty nonce views and then delegated\n * to the wrapped cipher instead of being rejected here first.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of\n * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to\n * `2**-33`, still negligible but creeping up.\n * @param fn - Cipher constructor that expects a nonce.\n * @param randomBytes_ - Random-byte source used for nonce generation.\n * @returns Cipher constructor that prepends the nonce to ciphertext.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}\n * @example\n * Prepends a fresh random nonce to every ciphertext.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';\n * const wrapped = managedNonce(gcm);\n * const key = randomBytes(16);\n * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));\n * wrapped(key).decrypt(ciphertext);\n * ```\n */\nexport function managedNonce(\n fn: T,\n randomBytes_: typeof randomBytes = randomBytes\n): TRet> {\n const { nonceLength } = fn;\n anumber(nonceLength);\n const addNonce = (\n nonce: TArg,\n ciphertext: TArg,\n plaintext: TArg\n ) => {\n const out = concatBytes(nonce, ciphertext);\n // Wrapped ciphers may alias caller plaintext on encrypt(); never zero\n // caller-owned buffers here.\n if (!overlapBytes(plaintext, ciphertext)) ciphertext.fill(0);\n return out;\n };\n // NOTE: we cannot support DST here, it would be mistake:\n // - we don't know how much dst length cipher requires\n // - nonce may unalign dst and break everything\n // - we create new u8a anyway (concatBytes)\n // - previously we passed all args to cipher, but that was mistake!\n const res = ((key: TArg, ...args: any[]): any => ({\n encrypt(plaintext: TArg) {\n abytes(plaintext);\n const nonce = randomBytes_(nonceLength);\n const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n // @ts-ignore\n if (encrypted instanceof Promise)\n return encrypted.then((ct) => addNonce(nonce, ct, plaintext));\n return addNonce(nonce, encrypted, plaintext);\n },\n decrypt(ciphertext: TArg) {\n abytes(ciphertext);\n const nonce = ciphertext.subarray(0, nonceLength);\n const decrypted = ciphertext.subarray(nonceLength);\n return fn(key, nonce, ...args).decrypt(decrypted);\n },\n })) as RemoveNonce & { blockSize?: number; tagLength?: number };\n // Auto-nonce wrappers still preserve the wrapped payload geometry.\n if ('blockSize' in fn) res.blockSize = (fn as any).blockSize;\n if ('tagLength' in fn) res.tagLength = (fn as any).tagLength;\n return res as TRet>;\n}\n\n/** `Uint8Array.of()` return type helper for TS 5.9. */\nexport type Uint8ArrayBuffer = TRet;\n", "/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).\nCounter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.\nCurrent noble policy is strict non-wrap for the shared 32-bit counter path:\nexported ARX ciphers reject initial `0xffffffff` and stop before any implicit\nwrap back to zero.\nSee {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.\n\n * @module\n */\nimport {\n type PRG,\n type TArg,\n type TRet,\n type XorStream,\n abool,\n abytes,\n anumber,\n checkOpts,\n clean,\n copyBytes,\n getOutput,\n isAligned32,\n isLE,\n randomBytes,\n swap32IfBE,\n u32,\n} from './utils.ts';\n\n// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.\n// Non-ASCII input would not match UTF-8 `TextEncoder` output.\nconst encodeStr = (str: string) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));\n// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.\n// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.\n// RFC 8439 \u00A72.3 / RFC 7539 \u00A72.3 only define the 256-bit-key constants; this 16-byte sigma is\n// kept for legacy allowShortKeys Salsa/ChaCha variants.\nconst sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();\n// RFC 8439 \u00A72.3 / RFC 7539 \u00A72.3 define words 0-3 as\n// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.\nconst sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();\n\n/**\n * Rotates a 32-bit word left.\n * @param a - Input word.\n * @param b - Rotation count in bits.\n * @returns Rotated 32-bit word.\n * @example\n * Moves the top byte of `0x12345678` into the low byte position.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(a: number, b: number): number {\n return (a << b) | (a >>> (32 - b));\n}\n\n/**\n * ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.\n * @param sigma - Sigma constants for the selected cipher layout.\n * @param key - Expanded key words.\n * @param nonce - Nonce and counter words prepared for the round function.\n * @param output - Output block written in place.\n * @param counter - Block counter value.\n * @param rounds - Optional round count override.\n */\nexport type CipherCoreFn = (\n sigma: TArg,\n key: TArg,\n nonce: TArg,\n output: TArg,\n counter: number,\n rounds?: number\n) => void;\n\n/**\n * Nonce-extension function used by XChaCha and XSalsa.\n * @param sigma - Sigma constants for the selected cipher layout.\n * @param key - Expanded key words.\n * @param input - Input nonce words used for subkey derivation.\n * @param output - Output buffer written with the derived nonce words.\n */\nexport type ExtendNonceFn = (\n sigma: TArg,\n key: TArg,\n input: TArg,\n output: TArg\n) => void;\n\n/** ARX cipher options.\n * * `allowShortKeys` for 16-byte keys\n * * `counterLength` in bytes\n * * `counterRight`: right: `nonce|counter`; left: `counter|nonce`\n * */\nexport type CipherOpts = {\n /** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */\n allowShortKeys?: boolean;\n /** Optional nonce-expansion hook used by extended-nonce variants. */\n extendNonceFn?: ExtendNonceFn;\n /** Counter length in bytes inside the nonce/counter layout. */\n counterLength?: number;\n /** Whether the layout is `nonce|counter` instead of `counter|nonce`. */\n counterRight?: boolean;\n /** Number of core rounds to execute. */\n rounds?: number;\n};\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\n// RFC 8439 \u00A72.2 / RFC 7539 \u00A72.2: the ChaCha state has 16 32-bit words.\nconst BLOCK_LEN32 = 16;\n\n// Counter policy for the shared public `counter` argument:\n// - RFC/IETF ChaCha20 uses a 32-bit counter.\n// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit\n// counter state and carry into the next word.\n// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium\n// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max\n// boundary instead of carrying.\n// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from\n// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.\n// Noble intentionally throws instead of silently picking one wrap model for users. In the default\n// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically\n// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement\n// whatever wider carry / wrap policy they need on top.\nconst MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();\nconst U32_EMPTY = /* @__PURE__ */ Uint32Array.of();\nfunction runCipher(\n core: TArg,\n sigma: TArg,\n key: TArg,\n nonce: TArg,\n data: TArg,\n output: TArg,\n counter: number,\n rounds: number\n): void {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isLE && isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n // RFC 8439 \u00A72.4.1 / RFC 7539 \u00A72.4.1 allow XORing one keystream block at a time and\n // truncating the final partial block instead of materializing the whole keystream.\n if (!isLE) {\n for (let pos = 0; pos < len; counter++) {\n core(\n sigma as TRet,\n key as TRet,\n nonce as TRet,\n b32,\n counter,\n rounds\n );\n // RFC 8439 \u00A72.4 / RFC 7539 \u00A72.4 serialize keystream words in little-endian order.\n swap32IfBE(b32);\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n return;\n }\n for (let pos = 0; pos < len; counter++) {\n core(\n sigma as TRet,\n key as TRet,\n nonce as TRet,\n b32,\n counter,\n rounds\n );\n // See MAX_COUNTER policy note above: never silently wrap the shared public counter.\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n\n/**\n * Creates an ARX stream cipher from a 32-bit core permutation.\n * Used internally to build the exported Salsa and ChaCha stream ciphers.\n * @param core - Core function that fills one keystream block.\n * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.\n * @returns Stream cipher function over byte arrays.\n * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}\n */\nexport function createCipher(core: TArg, opts: TArg): TRet {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n opts\n );\n if (typeof core !== 'function') throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (\n key: TArg,\n nonce: TArg,\n data: TArg,\n output?: TArg,\n counter = 0\n ): TRet => {\n abytes(key, undefined, 'key');\n abytes(nonce, undefined, 'nonce');\n abytes(data, undefined, 'data');\n const len = data.length;\n // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs\n // must match the logical result length exactly instead of returning an oversized workspace.\n output = getOutput(len, output, false);\n anumber(counter);\n // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.\n if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const toClean = [];\n\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length;\n let k: Uint8Array;\n let sigma: Uint32Array;\n if (l === 32) {\n // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and\n // final clean(...) all mutate or wipe the temporary buffer in place.\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n } else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n } else {\n abytes(key, 32, 'arx key');\n throw new Error('invalid key size');\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n }\n\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later\n // swap32IfBE(...) never mutates caller nonce bytes in place.\n if (!isLE || !isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));\n\n let k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n const n16 = nonce.subarray(0, 16);\n if (isLE) extendNonceFn(sigma as TRet, k32, u32(n16), k32);\n else {\n const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));\n extendNonceFn(sigmaRaw, k32, u32(n16), k32);\n clean(sigmaRaw);\n swap32IfBE(k32);\n }\n nonce = nonce.subarray(16);\n } else if (!isLE) swap32IfBE(k32);\n\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero\n // counter bytes, while Salsa/XSalsa append them after the nonce words.\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = swap32IfBE(u32(nonce));\n // Ensure temporary key/nonce copies are wiped even if the remaining\n // runtime guard in runCipher(...) throws on counter overflow.\n try {\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n return output as TRet;\n } finally {\n clean(...toClean);\n }\n };\n}\n\n/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */\nexport class _XorStreamPRG implements PRG {\n readonly blockLen: number;\n readonly keyLen: number;\n readonly nonceLen: number;\n private state: TRet;\n private buf: TRet;\n private key: TRet;\n private nonce: TRet;\n private pos: number;\n private ctr: number;\n private cipher: TArg;\n constructor(\n cipher: TArg,\n blockLen: number,\n keyLen: number,\n nonceLen: number,\n seed: TArg\n ) {\n this.cipher = cipher;\n this.blockLen = blockLen;\n this.keyLen = keyLen;\n this.nonceLen = nonceLen;\n this.state = new Uint8Array(this.keyLen + this.nonceLen) as TRet;\n this.reseed(seed);\n this.ctr = 0;\n this.pos = this.blockLen;\n this.buf = new Uint8Array(this.blockLen) as TRet;\n // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher\n // inputs in place through these subarray views.\n this.key = this.state.subarray(0, this.keyLen) as TRet;\n this.nonce = this.state.subarray(this.keyLen) as TRet;\n }\n private reseed(seed: TArg) {\n abytes(seed);\n if (!seed || seed.length === 0) throw new Error('entropy required');\n // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the\n // keystream so buffered leftovers from the previous state are never reused.\n for (let i = 0; i < seed.length; i++) this.state[i % this.state.length] ^= seed[i];\n this.ctr = 0;\n this.pos = this.blockLen;\n }\n addEntropy(seed: TArg): void {\n // Reject empty entropy before re-keying, otherwise a throwing call would still advance state.\n abytes(seed);\n if (seed.length === 0) throw new Error('entropy required');\n // Re-key from the current stream first, then mix external entropy into the fresh key||nonce\n // state through reseed() so stale buffered bytes are discarded.\n this.state.set(this.randomBytes(this.state.length));\n this.reseed(seed);\n }\n randomBytes(len: number): TRet {\n anumber(len);\n if (len === 0) return new Uint8Array(0) as TRet;\n const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;\n const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);\n // Preflight overflow so failed reads don't partially consume keystream\n // and leave the PRG repeating blocks.\n if (blocks > 0 && this.ctr > MAX_COUNTER - blocks) throw new Error('arx: counter overflow');\n const out = new Uint8Array(len);\n let outPos = 0;\n // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream\n // ciphers then emit raw keystream bytes directly into those buffers.\n // Serve buffered leftovers first so split reads stay identical to one larger read.\n if (this.pos < this.blockLen) {\n const take = Math.min(len, this.blockLen - this.pos);\n out.set(this.buf.subarray(this.pos, this.pos + take), 0);\n this.pos += take;\n outPos += take;\n if (outPos === len) return out as TRet; // fast path\n }\n // Full blocks directly to out\n const full = Math.floor((len - outPos) / this.blockLen);\n if (full > 0) {\n const blockBytes = full * this.blockLen;\n const b = out.subarray(outPos, outPos + blockBytes);\n this.cipher(this.key, this.nonce, b as TRet, b as TRet, this.ctr);\n this.ctr += full;\n outPos += blockBytes;\n }\n // Save leftovers\n const left = len - outPos;\n if (left > 0) {\n this.buf.fill(0);\n // NOTE: cipher will handle overflow\n this.cipher(\n this.key,\n this.nonce,\n this.buf as TRet,\n this.buf as TRet,\n this.ctr++\n );\n out.set(this.buf.subarray(0, left), outPos);\n this.pos = left;\n }\n return out as TRet;\n }\n // Clone seeds the new instance from this stream, so the source PRG advances too.\n clone(): _XorStreamPRG {\n return new _XorStreamPRG(\n this.cipher,\n this.blockLen,\n this.keyLen,\n this.nonceLen,\n this.randomBytes(this.state.length)\n );\n }\n // Zeroes the current state and leftover buffer, but does not make the instance unusable:\n // Later reads first drain zeros from the cleared buffer and then continue\n // from zero key||nonce state.\n clean(): void {\n this.pos = 0;\n this.ctr = 0;\n this.buf.fill(0);\n this.state.fill(0);\n }\n}\n\n/**\n * PRG constructor backed by an ARX stream cipher.\n * @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32\n * random bytes are mixed in by default: larger states keep a zero tail, while smaller states\n * wrap those bytes through `reseed()`'s XOR schedule.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n */\nexport type XorPRG = (seed?: TArg) => TRet<_XorStreamPRG>;\n\n/**\n * Creates a PRG constructor from a stream cipher.\n * @param cipher - Stream cipher used to fill output blocks.\n * @param blockLen - Keystream block length in bytes.\n * @param keyLen - Internal key length in bytes.\n * @param nonceLen - Internal nonce length in bytes.\n * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.\n * @example\n * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { createPRG } from '@noble/ciphers/_arx.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const init = createPRG(xchacha20, 64, 32, 24);\n * const prg = init(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const createPRG = (\n cipher: TArg,\n blockLen: number,\n keyLen: number,\n nonceLen: number\n): TRet => {\n return ((seed: TArg = randomBytes(32)): TRet<_XorStreamPRG> =>\n new _XorStreamPRG(\n cipher,\n blockLen,\n keyLen,\n nonceLen,\n seed\n ) as TRet<_XorStreamPRG>) as TRet;\n};\n", "/**\n * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out the {@link https://cr.yp.to/mac.html | original website}.\n * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.\n * @module\n */\n// prettier-ignore\nimport {\n abytes, aexists, aoutput, bytesToHex,\n clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE,\n wrapMacConstructor, type CMac, type IHash2, type TArg, type TRet\n} from './utils.ts';\n\n// Little-endian 2-byte load used by the Poly1305 limb decomposition.\nfunction u8to16(a: TArg, i: number) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n\nfunction bytesToNumberLE(bytes: TArg): bigint {\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\n/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */\nfunction poly1305_small(msg: TArg, key: TArg): TRet {\n abytes(msg);\n abytes(key, 32, 'key');\n const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5\n const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1\n const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');\n const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;\n const s = bytesToNumberLE(key.subarray(16));\n // Process by 16 byte chunks\n let acc = BigInt(0);\n for (let i = 0; i < msg.length; i += 16) {\n const m = msg.subarray(i, i + 16);\n // RFC 8439 \u00A72.5.1 / RFC 7539 \u00A72.5.1 append [0x01] to each chunk before multiplying by r.\n const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));\n acc = ((acc + n) * r) % POW_2_130_5;\n }\n const res = (acc + s) & POW_2_128_1;\n // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5 serialize the low 128 bits in little-endian order.\n return numberToBytesBE(res, 16).reverse() as TRet; // LE\n}\n\n// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.\n// @ts-expect-error\nfunction poly1305_computeTag_small(\n authKey: TArg,\n // AEAD trailer must already be the 16-byte length block:\n // 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.\n lengths: TArg,\n ciphertext: TArg,\n AAD?: TArg\n): TRet {\n // RFC 8439 \u00A72.8.1 / RFC 7539 \u00A72.8.1 MAC input is\n // AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.\n const res = [];\n const updatePadded2 = (msg: TArg) => {\n res.push(msg);\n const leftover = msg.length % 16;\n // RFC 8439 \u00A72.8.1 / RFC 7539 \u00A72.8.1: pad16(x) is empty for aligned\n // inputs, else 16-(len%16) zero bytes.\n if (leftover) res.push(new Uint8Array(16).slice(leftover));\n };\n if (AAD) updatePadded2(AAD);\n updatePadded2(ciphertext);\n res.push(lengths);\n return poly1305_small(concatBytes(...res), authKey);\n}\n\n/**\n * Incremental Poly1305 MAC state.\n * Prefer `poly1305()` for one-shot use.\n * @param key - 32-byte Poly1305 one-time key.\n * @example\n * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.\n *\n * ```ts\n * import { Poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const mac = new Poly1305(key);\n * mac.update(new Uint8Array([1, 2, 3]));\n * mac.digest();\n * ```\n */\nexport class Poly1305 implements IHash2 {\n readonly blockLen = 16;\n readonly outputLen = 16;\n private buffer = new Uint8Array(16);\n private r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3\n private h = new Uint16Array(10);\n private pad = new Uint16Array(8);\n private pos = 0;\n protected finished = false;\n protected destroyed = false;\n\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key: TArg) {\n key = copyBytes(abytes(key, 32, 'key'));\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n\n // RFC 8439 \u00A72.5.1 / RFC 7539 \u00A72.5.1 clamp r before multiplication.\n // These masks unpack that clamped value into 13-bit limbs, while pad\n // keeps the raw s half for finalize().\n // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n\n private process(data: TArg, offset: number, isLast = false) {\n // RFC 8439 \u00A72.5 / \u00A72.5.1 and RFC 7539 \u00A72.5 / \u00A72.5.1 add an extra high\n // bit to every full 16-byte block. The final partial block gets its\n // explicit `1` byte during digestInto(), so `hibit` stays zero there.\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n let c = 0;\n\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n\n private finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n\n // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5 reduce modulo 2^130-5 before repacking\n // to 16-bit words and adding the raw s half.\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data: TArg): this {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { buffer, blockLen } = this;\n const len = data.length;\n\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy(): void {\n // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.\n this.destroyed = true;\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out: TArg): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5: the final short block appends a\n // single `0x01` byte and zero-fills the remaining bytes before the\n // last multiplication step.\n buffer[pos++] = 1;\n for (; pos < 16; pos++) buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n }\n digest(): TRet {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy out before destroy() zeroes the internal buffer.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet;\n }\n}\n\n/** One-shot keyed hash helper with `.create()`. */\nexport type CHash = CMac;\n\n/**\n * Poly1305 MAC from RFC 8439.\n * @param msg - Message bytes to authenticate.\n * @param key - 32-byte Poly1305 one-time key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates one message with a one-shot Poly1305 call and a fresh key.\n *\n * ```ts\n * import { poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * poly1305(new Uint8Array(), key);\n * ```\n */\nexport const poly1305: TRet = /* @__PURE__ */ wrapMacConstructor(\n 32,\n (key: TArg) => new Poly1305(key)\n);\n", "/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and\n * is now used in TLS 1.3.\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out\n * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and\n * {@link https://cr.yp.to/chacha.html | website}.\n *\n * @module\n */\nimport { type XorPRG, createCipher, createPRG, rotl } from './_arx.ts';\nimport { poly1305 } from './_poly1305.ts';\nimport {\n type ARXCipher,\n type CipherWithOutput,\n type TArg,\n type TRet,\n type XorStream,\n abytes,\n clean,\n equalBytes,\n getOutput,\n swap8IfBE,\n swap32IfBE,\n u64Lengths,\n wrapCipher,\n} from './utils.ts';\n\n/**\n * ChaCha core function. It is implemented twice:\n * 1. Simple loop (chachaCore_small, hchacha_small)\n * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read\n * The specific implementation is selected in `createCipher` below.\n */\n\n/** RFC 8439 \u00A72.1 quarter round on words a, b, c, d. */\n// prettier-ignore\nfunction chachaQR(x: TArg, a: number, b: number, c: number, d: number) {\n x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 16);\n x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 12);\n x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 8);\n x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 7);\n}\n\n/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */\nfunction chachaRound(x: TArg, rounds = 20) {\n for (let r = 0; r < rounds; r += 2) {\n // RFC 8439 \u00A72.3 / \u00A72.3.1 inner_block: four column rounds, then four diagonal rounds.\n chachaQR(x, 0, 4, 8, 12);\n chachaQR(x, 1, 5, 9, 13);\n chachaQR(x, 2, 6, 10, 14);\n chachaQR(x, 3, 7, 11, 15);\n chachaQR(x, 0, 5, 10, 15);\n chachaQR(x, 1, 6, 11, 12);\n chachaQR(x, 2, 7, 8, 13);\n chachaQR(x, 3, 4, 9, 14);\n }\n}\n\n// Shared scratch for the auditability-only helper below; only the test-only\n// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.\nconst ctmp = /* @__PURE__ */ new Uint32Array(16);\n\n/** Small version of chacha without loop unrolling. Unused, provided for auditability. */\n// prettier-ignore\nfunction chacha(\n s: TArg, k: TArg, i: TArg, out: TArg,\n isHChacha: boolean = true, rounds: number = 20\n): void {\n // `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block\n // function or the full 128-bit nonce prefix for the HChaCha subkey path.\n // Create initial array using common pattern\n const y = Uint32Array.from([\n s[0], s[1], s[2], s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n k[0], k[1], k[2], k[3], // Key Key Key Key\n k[4], k[5], k[6], k[7], // Key Key Key Key\n i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce\n ]);\n const x = ctmp;\n x.set(y);\n chachaRound(x, rounds);\n\n // HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha\n // block path adds the original state word-by-word.\n if (isHChacha) {\n const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];\n for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];\n } else {\n for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;\n }\n}\n\n/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */\n// @ts-ignore\nconst chachaCore_small: typeof chachaCore = (s, k, n, out, cnt, rounds) =>\n // Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().\n chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);\n/** Identical to `hchacha`. Unused. */\n// @ts-ignore\nconst hchacha_small: typeof hchacha = chacha;\n\n/** RFC 8439 \u00A72.3 block core for `state = constants | key | counter | nonce`. */\n// prettier-ignore\nfunction chachaCore(\n s: TArg, k: TArg, n: TArg, out: TArg, cnt: number, rounds = 20\n): void {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // RFC 8439 \u00A72.3 / \u00A72.3.1: add the original state words back in state order.\n let oi = 0;\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha hashes key and nonce into key' and nonce' for xchacha20.\n * Algorithmically identical to `hchacha_small`, but this exported path\n * normalizes word order on big-endian hosts.\n * Need to find a way to merge it with `chachaCore` without 25% performance hit.\n * @param s - Sigma constants as 32-bit words.\n * @param k - Key words.\n * @param i - Nonce-prefix words.\n * @param out - Output buffer for the derived subkey.\n * @example\n * Derives the XChaCha subkey from sigma, key, and nonce-prefix words.\n *\n * ```ts\n * const sigma = new Uint32Array(4);\n * const key = new Uint32Array(8);\n * const nonce = new Uint32Array(4);\n * const out = new Uint32Array(8);\n * hchacha(sigma, key, nonce, out);\n * ```\n */\n// prettier-ignore\nexport function hchacha(\n s: TArg, k: TArg, i: TArg, out: TArg\n): void {\n let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]),\n x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]),\n x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]),\n x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.\n let oi = 0;\n out[oi++] = x00; out[oi++] = x01;\n out[oi++] = x02; out[oi++] = x03;\n out[oi++] = x12; out[oi++] = x13;\n out[oi++] = x14; out[oi++] = x15;\n swap32IfBE(out);\n}\n\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 16-byte or 32-byte key.\n * @param nonce - 8-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20orig } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(8);\n * chacha20orig(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20orig: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 32-byte key.\n * @param nonce - 24-byte extended nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * xchacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const xchacha20: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha8(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha8: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha12 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha12(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha12: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n\n// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.\nexport const __TESTS: {\n chachaCore_small: typeof chachaCore_small;\n chachaCore: typeof chachaCore;\n} = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });\n\n// RFC 8439 \u00A72.8.1 pad16(x): shared zero block for AAD/ciphertext padding.\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// RFC 8439 \u00A72.8 / \u00A72.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.\nconst updatePadded = (h: ReturnType, msg: TArg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover) h.update(ZEROS16.subarray(leftover));\n};\n\n// RFC 8439 \u00A72.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key\n// generation only needs 32 zero bytes.\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n fn: TArg,\n key: TArg,\n nonce: TArg,\n ciphertext: TArg,\n AAD?: TArg\n): TRet {\n if (AAD !== undefined) abytes(AAD, undefined, 'AAD');\n // RFC 8439 \u00A72.6 / \u00A72.8: derive the Poly1305 one-time key from counter 0,\n // then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).\n const authKey = fn(\n key as TRet,\n nonce as TRet,\n ZEROS32 as TRet\n );\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n\n // Methods below can be replaced with\n // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)\n const h = poly1305.create(authKey);\n if (AAD) updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n (xorStream: TArg) =>\n (key: TArg, nonce: TArg, AAD?: TArg): CipherWithOutput => {\n // This borrows caller key/nonce/AAD buffers by reference; mutating them after construction\n // changes future encrypt/decrypt results.\n const tagLength = 16;\n return {\n encrypt(plaintext: TArg, output?: TArg): TRet {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // RFC 8439 \u00A72.8: payload encryption starts at counter 1 because counter 0 produced the OTK.\n xorStream(\n key as TRet,\n nonce as TRet,\n oPlain as TRet,\n oPlain as TRet,\n 1\n );\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output as TRet;\n },\n decrypt(ciphertext: TArg, output?: TArg): TRet {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n // RFC 8439 \u00A72.8 / \u00A74: authenticate ciphertext before decrypting it, and compare tags with\n // the constant-time equalBytes() helper rather than decrypting speculative plaintext first.\n if (!equalBytes(passedTag, tag)) {\n clean(tag);\n throw new Error('invalid tag');\n }\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(\n key as TRet,\n nonce as TRet,\n output as TRet,\n output as TRet,\n 1\n ); // start stream with i=1\n clean(tag);\n return output as TRet;\n },\n };\n };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce.\n *\n * ```ts\n * import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * const cipher = chacha20poly1305(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const chacha20poly1305: TRet = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 12, tagLength: 16 },\n /* @__PURE__ */ _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n *\n * Can be safely used with random nonces (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * @param key - 32-byte key.\n * @param nonce - 24-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * const cipher = xchacha20poly1305(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const xchacha20poly1305: TRet = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 24, tagLength: 16 },\n /* @__PURE__ */ _poly1305_aead(xchacha20)\n);\n\n/**\n * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 40-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the test-only ChaCha20 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha20(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha20: TRet = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);\n/**\n * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Faster than `rngChacha20`.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 44-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the faster test-only ChaCha8 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha8(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha8: TRet = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);\n", "import { constantTimeEqual } from \"./buffer.mjs\";\nimport { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT } from \"./jwt.mjs\";\nimport { hashPassword, verifyPassword } from \"./password.mjs\";\nimport { generateRandomString } from \"./random.mjs\";\nimport { createHash } from \"@better-auth/utils/hash\";\nimport { getWebcryptoSubtle } from \"@better-auth/utils\";\nimport { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { bytesToHex, hexToBytes, managedNonce, utf8ToBytes } from \"@noble/ciphers/utils.js\";\n//#region src/crypto/index.ts\nconst algorithm = {\n\tname: \"HMAC\",\n\thash: \"SHA-256\"\n};\nconst ENVELOPE_PREFIX = \"$ba$\";\nfunction parseEnvelope(data) {\n\tif (!data.startsWith(ENVELOPE_PREFIX)) return null;\n\tconst firstSep = 4;\n\tconst secondSep = data.indexOf(\"$\", firstSep);\n\tif (secondSep === -1) return null;\n\tconst version = parseInt(data.slice(firstSep, secondSep), 10);\n\tif (!Number.isInteger(version) || version < 0) return null;\n\treturn {\n\t\tversion,\n\t\tciphertext: data.slice(secondSep + 1)\n\t};\n}\nfunction formatEnvelope(version, ciphertext) {\n\treturn `${ENVELOPE_PREFIX}${version}$${ciphertext}`;\n}\nasync function rawEncrypt(secret, data) {\n\tconst keyAsBytes = await createHash(\"SHA-256\").digest(secret);\n\tconst dataAsBytes = utf8ToBytes(data);\n\treturn bytesToHex(managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)).encrypt(dataAsBytes));\n}\nasync function rawDecrypt(secret, hex) {\n\tconst keyAsBytes = await createHash(\"SHA-256\").digest(secret);\n\tconst dataAsBytes = hexToBytes(hex);\n\tconst chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes));\n\treturn new TextDecoder().decode(chacha.decrypt(dataAsBytes));\n}\nconst symmetricEncrypt = async ({ key, data }) => {\n\tif (typeof key === \"string\") return rawEncrypt(key, data);\n\tconst secret = key.keys.get(key.currentVersion);\n\tif (!secret) throw new Error(`Secret version ${key.currentVersion} not found in keys`);\n\tconst ciphertext = await rawEncrypt(secret, data);\n\treturn formatEnvelope(key.currentVersion, ciphertext);\n};\nconst symmetricDecrypt = async ({ key, data }) => {\n\tif (typeof key === \"string\") return rawDecrypt(key, data);\n\tconst envelope = parseEnvelope(data);\n\tif (envelope) {\n\t\tconst secret = key.keys.get(envelope.version);\n\t\tif (!secret) throw new Error(`Secret version ${envelope.version} not found in keys (key may have been retired)`);\n\t\treturn rawDecrypt(secret, envelope.ciphertext);\n\t}\n\tif (key.legacySecret) return rawDecrypt(key.legacySecret, data);\n\tthrow new Error(\"Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.\");\n};\nconst getCryptoKey = async (secret) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await getWebcryptoSubtle().importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\nconst makeSignature = async (value, secret) => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value));\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n//#endregion\nexport { constantTimeEqual, formatEnvelope, generateRandomString, getCryptoKey, hashPassword, makeSignature, parseEnvelope, signJWT, symmetricDecodeJWT, symmetricDecrypt, symmetricEncodeJWT, symmetricEncrypt, verifyJWT, verifyPassword };\n", "//#region src/utils/date.ts\nconst getDate = (span, unit = \"ms\") => {\n\treturn new Date(Date.now() + (unit === \"sec\" ? span * 1e3 : span));\n};\n//#endregion\nexport { getDate };\n", "import { getAuthTables } from \"./get-tables.mjs\";\nimport { coreSchema } from \"./schema/shared.mjs\";\nimport { accountSchema } from \"./schema/account.mjs\";\nimport { rateLimitSchema } from \"./schema/rate-limit.mjs\";\nimport { sessionSchema } from \"./schema/session.mjs\";\nimport { userSchema } from \"./schema/user.mjs\";\nimport { verificationSchema } from \"./schema/verification.mjs\";\nexport { accountSchema, coreSchema, getAuthTables, rateLimitSchema, sessionSchema, userSchema, verificationSchema };\n", "import { getAuthTables } from \"@better-auth/core/db\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { filterOutputFields } from \"@better-auth/core/utils/db\";\n//#region src/db/schema.ts\nconst cache = /* @__PURE__ */ new WeakMap();\nfunction getFields(options, modelName, mode) {\n\tconst cacheKey = `${modelName}:${mode}`;\n\tif (!cache.has(options)) cache.set(options, /* @__PURE__ */ new Map());\n\tconst tableCache = cache.get(options);\n\tif (tableCache.has(cacheKey)) return tableCache.get(cacheKey);\n\tconst coreSchema = mode === \"output\" ? getAuthTables(options)[modelName]?.fields ?? {} : {};\n\tconst additionalFields = modelName === \"user\" || modelName === \"session\" || modelName === \"account\" ? options[modelName]?.additionalFields : void 0;\n\tlet schema = {\n\t\t...coreSchema,\n\t\t...additionalFields ?? {}\n\t};\n\tfor (const plugin of options.plugins || []) if (plugin.schema && plugin.schema[modelName]) schema = {\n\t\t...schema,\n\t\t...plugin.schema[modelName].fields\n\t};\n\ttableCache.set(cacheKey, schema);\n\treturn schema;\n}\nfunction parseUserOutput(options, user) {\n\treturn filterOutputFields(user, getFields(options, \"user\", \"output\"));\n}\nfunction parseSessionOutput(options, session) {\n\treturn filterOutputFields(session, getFields(options, \"session\", \"output\"));\n}\nfunction parseAccountOutput(options, account) {\n\tconst { accessToken: _accessToken, refreshToken: _refreshToken, idToken: _idToken, accessTokenExpiresAt: _accessTokenExpiresAt, refreshTokenExpiresAt: _refreshTokenExpiresAt, password: _password, ...rest } = filterOutputFields(account, getFields(options, \"account\", \"output\"));\n\treturn rest;\n}\nfunction parseInputData(data, schema) {\n\tconst action = schema.action || \"create\";\n\tconst fields = schema.fields;\n\tconst parsedData = Object.create(null);\n\tfor (const key in fields) {\n\t\tif (key in data) {\n\t\t\tif (fields[key].input === false) {\n\t\t\t\tif (fields[key].defaultValue !== void 0) {\n\t\t\t\t\tif (action !== \"update\") {\n\t\t\t\t\t\tparsedData[key] = fields[key].defaultValue;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (data[key]) throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t...BASE_ERROR_CODES.FIELD_NOT_ALLOWED,\n\t\t\t\t\tmessage: `${key} is not allowed to be set`\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (fields[key].validator?.input && data[key] !== void 0) {\n\t\t\t\tconst result = fields[key].validator.input[\"~standard\"].validate(data[key]);\n\t\t\t\tif (result instanceof Promise) throw APIError.from(\"INTERNAL_SERVER_ERROR\", BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED);\n\t\t\t\tif (\"issues\" in result && result.issues) throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t...BASE_ERROR_CODES.VALIDATION_ERROR,\n\t\t\t\t\tmessage: result.issues[0]?.message || \"Validation Error\"\n\t\t\t\t});\n\t\t\t\tparsedData[key] = result.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (fields[key].transform?.input && data[key] !== void 0) {\n\t\t\t\tparsedData[key] = fields[key].transform?.input(data[key]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparsedData[key] = data[key];\n\t\t\tcontinue;\n\t\t}\n\t\tif (fields[key].defaultValue !== void 0 && action === \"create\") {\n\t\t\tif (typeof fields[key].defaultValue === \"function\") {\n\t\t\t\tparsedData[key] = fields[key].defaultValue();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparsedData[key] = fields[key].defaultValue;\n\t\t\tcontinue;\n\t\t}\n\t\tif (fields[key].required && action === \"create\") throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t...BASE_ERROR_CODES.MISSING_FIELD,\n\t\t\tmessage: `${key} is required`\n\t\t});\n\t}\n\treturn parsedData;\n}\nfunction parseUserInput(options, user = {}, action) {\n\treturn parseInputData(user, {\n\t\tfields: getFields(options, \"user\", \"input\"),\n\t\taction\n\t});\n}\nfunction parseAdditionalUserInput(options, user) {\n\tconst schema = getFields(options, \"user\", \"input\");\n\treturn parseInputData(user || {}, { fields: schema });\n}\nfunction parseAccountInput(options, account) {\n\treturn parseInputData(account, { fields: getFields(options, \"account\", \"input\") });\n}\nfunction parseSessionInput(options, session, action) {\n\treturn parseInputData(session, {\n\t\tfields: getFields(options, \"session\", \"input\"),\n\t\taction\n\t});\n}\nfunction getSessionDefaultFields(options) {\n\tconst fields = getFields(options, \"session\", \"input\");\n\tconst defaults = {};\n\tfor (const key in fields) if (fields[key].defaultValue !== void 0) defaults[key] = typeof fields[key].defaultValue === \"function\" ? fields[key].defaultValue() : fields[key].defaultValue;\n\treturn defaults;\n}\nfunction mergeSchema(schema, newSchema) {\n\tif (!newSchema) return schema;\n\tfor (const table in newSchema) {\n\t\tconst newModelName = newSchema[table]?.modelName;\n\t\tif (newModelName) schema[table].modelName = newModelName;\n\t\tfor (const field in schema[table].fields) {\n\t\t\tconst newField = newSchema[table]?.fields?.[field];\n\t\t\tif (!newField) continue;\n\t\t\tschema[table].fields[field].fieldName = newField;\n\t\t}\n\t}\n\treturn schema;\n}\n//#endregion\nexport { getSessionDefaultFields, mergeSchema, parseAccountInput, parseAccountOutput, parseAdditionalUserInput, parseInputData, parseSessionInput, parseSessionOutput, parseUserInput, parseUserOutput };\n", "//#region src/utils/db.ts\n/**\n* Filters output data by removing fields with the `returned: false` attribute.\n* This ensures sensitive fields are not exposed in API responses.\n*/\nfunction filterOutputFields(data, additionalFields) {\n\tif (!data || !additionalFields) return data;\n\tconst returnFiltered = Object.entries(additionalFields).filter(([, { returned }]) => returned === false).map(([key]) => key);\n\treturn Object.entries(structuredClone(data)).filter(([key]) => !returnFiltered.includes(key)).reduce((acc, [key, value]) => ({\n\t\t...acc,\n\t\t[key]: value\n\t}), {});\n}\n//#endregion\nexport { filterOutputFields };\n", "//#region src/utils/is-promise.ts\nfunction isPromise(obj) {\n\treturn !!obj && (typeof obj === \"object\" || typeof obj === \"function\") && typeof obj.then === \"function\";\n}\n//#endregion\nexport { isPromise };\n", "import { symmetricDecodeJWT, symmetricEncodeJWT } from \"../crypto/jwt.mjs\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport * as z from \"zod\";\n//#region src/cookies/session-store.ts\nconst ALLOWED_COOKIE_SIZE = 4096;\nconst ESTIMATED_EMPTY_COOKIE_SIZE = 200;\nconst CHUNK_SIZE = ALLOWED_COOKIE_SIZE - ESTIMATED_EMPTY_COOKIE_SIZE;\n/**\n* Parse cookies from the request headers\n*/\nfunction parseCookiesFromContext(ctx) {\n\tconst cookieHeader = ctx.headers?.get(\"cookie\");\n\tif (!cookieHeader) return {};\n\tconst cookies = {};\n\tconst pairs = cookieHeader.split(\"; \");\n\tfor (const pair of pairs) {\n\t\tconst [name, ...valueParts] = pair.split(\"=\");\n\t\tif (name && valueParts.length > 0) cookies[name] = valueParts.join(\"=\");\n\t}\n\treturn cookies;\n}\n/**\n* Extract the chunk index from a cookie name\n*/\nfunction getChunkIndex(cookieName) {\n\tconst parts = cookieName.split(\".\");\n\tconst lastPart = parts[parts.length - 1];\n\tconst index = parseInt(lastPart || \"0\", 10);\n\treturn isNaN(index) ? 0 : index;\n}\n/**\n* Read all existing chunks from cookies\n*/\nfunction readExistingChunks(cookieName, ctx) {\n\tconst chunks = {};\n\tconst cookies = parseCookiesFromContext(ctx);\n\tfor (const [name, value] of Object.entries(cookies)) if (name.startsWith(cookieName)) chunks[name] = value;\n\treturn chunks;\n}\n/**\n* Get the full session data by joining all chunks\n*/\nfunction joinChunks(chunks) {\n\treturn Object.keys(chunks).sort((a, b) => {\n\t\treturn getChunkIndex(a) - getChunkIndex(b);\n\t}).map((key) => chunks[key]).join(\"\");\n}\n/**\n* Split a cookie value into chunks if needed\n*/\nfunction chunkCookie(storeName, cookie, chunks, logger) {\n\tconst chunkCount = Math.ceil(cookie.value.length / CHUNK_SIZE);\n\tif (chunkCount === 1) {\n\t\tchunks[cookie.name] = cookie.value;\n\t\treturn [cookie];\n\t}\n\tconst cookies = [];\n\tfor (let i = 0; i < chunkCount; i++) {\n\t\tconst name = `${cookie.name}.${i}`;\n\t\tconst start = i * CHUNK_SIZE;\n\t\tconst value = cookie.value.substring(start, start + CHUNK_SIZE);\n\t\tcookies.push({\n\t\t\t...cookie,\n\t\t\tname,\n\t\t\tvalue\n\t\t});\n\t\tchunks[name] = value;\n\t}\n\tlogger.debug(`CHUNKING_${storeName.toUpperCase()}_COOKIE`, {\n\t\tmessage: `${storeName} cookie exceeds allowed ${ALLOWED_COOKIE_SIZE} bytes.`,\n\t\temptyCookieSize: ESTIMATED_EMPTY_COOKIE_SIZE,\n\t\tvalueSize: cookie.value.length,\n\t\tchunkCount,\n\t\tchunks: cookies.map((c) => c.value.length + ESTIMATED_EMPTY_COOKIE_SIZE)\n\t});\n\treturn cookies;\n}\n/**\n* Get all cookies that should be cleaned (removed)\n*/\nfunction getCleanCookies(chunks, cookieOptions) {\n\tconst cleanedChunks = {};\n\tfor (const name in chunks) cleanedChunks[name] = {\n\t\tname,\n\t\tvalue: \"\",\n\t\tattributes: {\n\t\t\t...cookieOptions,\n\t\t\tmaxAge: 0\n\t\t}\n\t};\n\treturn cleanedChunks;\n}\n/**\n* Create a session store for handling cookie chunking.\n* When session data exceeds 4KB, it automatically splits it into multiple cookies.\n*\n* Based on next-auth's SessionStore implementation.\n* @see https://github.com/nextauthjs/next-auth/blob/27b2519b84b8eb9cf053775dea29d577d2aa0098/packages/next-auth/src/core/lib/cookie.ts\n*/\nconst storeFactory = (storeName) => (cookieName, cookieOptions, ctx) => {\n\tconst chunks = readExistingChunks(cookieName, ctx);\n\tconst logger = ctx.context.logger;\n\treturn {\n\t\tgetValue() {\n\t\t\treturn joinChunks(chunks);\n\t\t},\n\t\thasChunks() {\n\t\t\treturn Object.keys(chunks).length > 0;\n\t\t},\n\t\tchunk(value, options) {\n\t\t\tconst cleanedChunks = getCleanCookies(chunks, cookieOptions);\n\t\t\tfor (const name in chunks) delete chunks[name];\n\t\t\tconst cookies = cleanedChunks;\n\t\t\tconst chunked = chunkCookie(storeName, {\n\t\t\t\tname: cookieName,\n\t\t\t\tvalue,\n\t\t\t\tattributes: {\n\t\t\t\t\t...cookieOptions,\n\t\t\t\t\t...options\n\t\t\t\t}\n\t\t\t}, chunks, logger);\n\t\t\tfor (const chunk of chunked) cookies[chunk.name] = chunk;\n\t\t\treturn Object.values(cookies);\n\t\t},\n\t\tclean() {\n\t\t\tconst cleanedChunks = getCleanCookies(chunks, cookieOptions);\n\t\t\tfor (const name in chunks) delete chunks[name];\n\t\t\treturn Object.values(cleanedChunks);\n\t\t},\n\t\tsetCookies(cookies) {\n\t\t\tfor (const cookie of cookies) ctx.setCookie(cookie.name, cookie.value, cookie.attributes);\n\t\t}\n\t};\n};\nconst createSessionStore = storeFactory(\"Session\");\nconst createAccountStore = storeFactory(\"Account\");\nfunction getChunkedCookie(ctx, cookieName) {\n\tconst value = ctx.getCookie(cookieName);\n\tif (value) return value;\n\tconst chunks = [];\n\tconst cookieHeader = ctx.headers?.get(\"cookie\");\n\tif (!cookieHeader) return null;\n\tconst cookies = {};\n\tconst pairs = cookieHeader.split(\"; \");\n\tfor (const pair of pairs) {\n\t\tconst [name, ...valueParts] = pair.split(\"=\");\n\t\tif (name && valueParts.length > 0) cookies[name] = valueParts.join(\"=\");\n\t}\n\tfor (const [name, val] of Object.entries(cookies)) if (name.startsWith(cookieName + \".\")) {\n\t\tconst indexStr = name.split(\".\").at(-1);\n\t\tconst index = parseInt(indexStr || \"0\", 10);\n\t\tif (!isNaN(index)) chunks.push({\n\t\t\tindex,\n\t\t\tvalue: val\n\t\t});\n\t}\n\tif (chunks.length > 0) {\n\t\tchunks.sort((a, b) => a.index - b.index);\n\t\treturn chunks.map((c) => c.value).join(\"\");\n\t}\n\treturn null;\n}\nasync function setAccountCookie(c, accountData) {\n\tconst accountDataCookie = c.context.authCookies.accountData;\n\tconst options = {\n\t\tmaxAge: 300,\n\t\t...accountDataCookie.attributes\n\t};\n\tconst data = await symmetricEncodeJWT(accountData, c.context.secretConfig, \"better-auth-account\", options.maxAge);\n\tif (data.length > ALLOWED_COOKIE_SIZE) {\n\t\tconst accountStore = createAccountStore(accountDataCookie.name, options, c);\n\t\tconst cookies = accountStore.chunk(data, options);\n\t\taccountStore.setCookies(cookies);\n\t} else {\n\t\tconst accountStore = createAccountStore(accountDataCookie.name, options, c);\n\t\tif (accountStore.hasChunks()) {\n\t\t\tconst cleanCookies = accountStore.clean();\n\t\t\taccountStore.setCookies(cleanCookies);\n\t\t}\n\t\tc.setCookie(accountDataCookie.name, data, options);\n\t}\n}\nasync function getAccountCookie(c) {\n\tconst accountCookie = getChunkedCookie(c, c.context.authCookies.accountData.name);\n\tif (accountCookie) {\n\t\tconst accountData = safeJSONParse(await symmetricDecodeJWT(accountCookie, c.context.secretConfig, \"better-auth-account\"));\n\t\tif (accountData) return accountData;\n\t}\n\treturn null;\n}\nconst getSessionQuerySchema = z.optional(z.object({\n\tdisableCookieCache: z.coerce.boolean().meta({ description: \"Disable cookie cache and fetch session from database\" }).optional(),\n\tdisableRefresh: z.coerce.boolean().meta({ description: \"Disable session refresh. Useful for checking session status, without updating the session\" }).optional()\n}));\n//#endregion\nexport { createAccountStore, createSessionStore, getAccountCookie, getChunkedCookie, getSessionQuerySchema, setAccountCookie };\n", "//#region src/utils/time.ts\nconst SEC = 1e3;\nconst MIN = SEC * 60;\nconst HOUR = MIN * 60;\nconst DAY = HOUR * 24;\nconst WEEK = DAY * 7;\nconst MONTH = DAY * 30;\nconst YEAR = DAY * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;\nfunction parse(value) {\n\tconst match = REGEX.exec(value);\n\tif (!match || match[4] && match[1]) throw new TypeError(`Invalid time string format: \"${value}\". Use formats like \"7d\", \"30m\", \"1 hour\", etc.`);\n\tconst n = parseFloat(match[2]);\n\tconst unit = match[3].toLowerCase();\n\tlet result;\n\tswitch (unit) {\n\t\tcase \"years\":\n\t\tcase \"year\":\n\t\tcase \"yrs\":\n\t\tcase \"yr\":\n\t\tcase \"y\":\n\t\t\tresult = n * YEAR;\n\t\t\tbreak;\n\t\tcase \"months\":\n\t\tcase \"month\":\n\t\tcase \"mo\":\n\t\t\tresult = n * MONTH;\n\t\t\tbreak;\n\t\tcase \"weeks\":\n\t\tcase \"week\":\n\t\tcase \"w\":\n\t\t\tresult = n * WEEK;\n\t\t\tbreak;\n\t\tcase \"days\":\n\t\tcase \"day\":\n\t\tcase \"d\":\n\t\t\tresult = n * DAY;\n\t\t\tbreak;\n\t\tcase \"hours\":\n\t\tcase \"hour\":\n\t\tcase \"hrs\":\n\t\tcase \"hr\":\n\t\tcase \"h\":\n\t\t\tresult = n * HOUR;\n\t\t\tbreak;\n\t\tcase \"minutes\":\n\t\tcase \"minute\":\n\t\tcase \"mins\":\n\t\tcase \"min\":\n\t\tcase \"m\":\n\t\t\tresult = n * MIN;\n\t\t\tbreak;\n\t\tcase \"seconds\":\n\t\tcase \"second\":\n\t\tcase \"secs\":\n\t\tcase \"sec\":\n\t\tcase \"s\":\n\t\t\tresult = n * SEC;\n\t\t\tbreak;\n\t\tdefault: throw new TypeError(`Unknown time unit: \"${unit}\"`);\n\t}\n\tif (match[1] === \"-\" || match[4] === \"ago\") return -result;\n\treturn result;\n}\n/**\n* Parse a time string and return the value in milliseconds.\n*\n* @param value - A time string like \"7d\", \"30m\", \"1 hour\", \"2 hours ago\"\n* @returns The parsed value in milliseconds\n* @throws TypeError if the string format is invalid\n*\n* @example\n* ms(\"1d\") // 86400000\n* ms(\"2 hours\") // 7200000\n* ms(\"30s\") // 30000\n* ms(\"2 hours ago\") // -7200000\n*/\nfunction ms(value) {\n\treturn parse(value);\n}\n/**\n* Parse a time string and return the value in seconds.\n*\n* @param value - A time string like \"7d\", \"30m\", \"1 hour\", \"2 hours ago\"\n* @returns The parsed value in seconds (rounded)\n* @throws TypeError if the string format is invalid\n*\n* @example\n* sec(\"1d\") // 86400\n* sec(\"2 hours\") // 7200\n* sec(\"-30s\") // -30\n* sec(\"2 hours ago\") // -7200\n*/\nfunction sec(value) {\n\treturn Math.round(parse(value) / 1e3);\n}\n//#endregion\nexport { ms, sec };\n", "//#region src/cookies/cookie-utils.ts\nfunction tryDecode(str) {\n\ttry {\n\t\treturn decodeURIComponent(str);\n\t} catch {\n\t\treturn str;\n\t}\n}\nconst SECURE_COOKIE_PREFIX = \"__Secure-\";\nconst HOST_COOKIE_PREFIX = \"__Host-\";\n/**\n* Remove __Secure- or __Host- prefix from cookie name.\n*/\nfunction stripSecureCookiePrefix(cookieName) {\n\tif (cookieName.startsWith(\"__Secure-\")) return cookieName.slice(9);\n\tif (cookieName.startsWith(\"__Host-\")) return cookieName.slice(7);\n\treturn cookieName;\n}\n/**\n* Split a comma-joined `Set-Cookie` header string into individual cookies.\n*/\nfunction splitSetCookieHeader(setCookie) {\n\tif (!setCookie) return [];\n\tconst result = [];\n\tlet start = 0;\n\tlet i = 0;\n\twhile (i < setCookie.length) {\n\t\tif (setCookie[i] === \",\") {\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < setCookie.length && setCookie[j] === \" \") j++;\n\t\t\twhile (j < setCookie.length && setCookie[j] !== \"=\" && setCookie[j] !== \";\" && setCookie[j] !== \",\") j++;\n\t\t\tif (j < setCookie.length && setCookie[j] === \"=\") {\n\t\t\t\tconst part = setCookie.slice(start, i).trim();\n\t\t\t\tif (part) result.push(part);\n\t\t\t\tstart = i + 1;\n\t\t\t\twhile (start < setCookie.length && setCookie[start] === \" \") start++;\n\t\t\t\ti = start;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\tconst last = setCookie.slice(start).trim();\n\tif (last) result.push(last);\n\treturn result;\n}\nfunction parseSetCookieHeader(setCookie) {\n\tconst cookies = /* @__PURE__ */ new Map();\n\tsplitSetCookieHeader(setCookie).forEach((cookieString) => {\n\t\tconst [nameValue, ...attributes] = cookieString.split(\";\").map((part) => part.trim());\n\t\tconst [name, ...valueParts] = (nameValue || \"\").split(\"=\");\n\t\tconst value = valueParts.join(\"=\");\n\t\tif (!name || value === void 0) return;\n\t\tconst attrObj = { value: value.includes(\"%\") ? tryDecode(value) : value };\n\t\tattributes.forEach((attribute) => {\n\t\t\tconst [attrName, ...attrValueParts] = attribute.split(\"=\");\n\t\t\tconst attrValue = attrValueParts.join(\"=\");\n\t\t\tconst normalizedAttrName = attrName.trim().toLowerCase();\n\t\t\tswitch (normalizedAttrName) {\n\t\t\t\tcase \"max-age\":\n\t\t\t\t\tattrObj[\"max-age\"] = attrValue ? parseInt(attrValue.trim(), 10) : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"expires\":\n\t\t\t\t\tattrObj.expires = attrValue ? new Date(attrValue.trim()) : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"domain\":\n\t\t\t\t\tattrObj.domain = attrValue ? attrValue.trim() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"path\":\n\t\t\t\t\tattrObj.path = attrValue ? attrValue.trim() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"secure\":\n\t\t\t\t\tattrObj.secure = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"httponly\":\n\t\t\t\t\tattrObj.httponly = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"samesite\":\n\t\t\t\t\tattrObj.samesite = attrValue ? attrValue.trim().toLowerCase() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tattrObj[normalizedAttrName] = attrValue ? attrValue.trim() : true;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tcookies.set(name, attrObj);\n\t});\n\treturn cookies;\n}\nfunction setCookieToHeader(headers) {\n\treturn (context) => {\n\t\tconst setCookieHeader = context.response.headers.get(\"set-cookie\");\n\t\tif (!setCookieHeader) return;\n\t\tconst cookieMap = /* @__PURE__ */ new Map();\n\t\t(headers.get(\"cookie\") || \"\").split(\";\").forEach((cookie) => {\n\t\t\tconst [name, ...rest] = cookie.trim().split(\"=\");\n\t\t\tif (name && rest.length > 0) cookieMap.set(name, rest.join(\"=\"));\n\t\t});\n\t\tparseSetCookieHeader(setCookieHeader).forEach((value, name) => {\n\t\t\tcookieMap.set(name, value.value);\n\t\t});\n\t\tconst updatedCookies = Array.from(cookieMap.entries()).map(([name, value]) => `${name}=${value}`).join(\"; \");\n\t\theaders.set(\"cookie\", updatedCookies);\n\t};\n}\n//#endregion\nexport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, parseSetCookieHeader, setCookieToHeader, splitSetCookieHeader, stripSecureCookiePrefix };\n", "import { isDynamicBaseURLConfig } from \"../utils/url.mjs\";\nimport { getDate } from \"../utils/date.mjs\";\nimport { parseUserOutput } from \"../db/schema.mjs\";\nimport { isPromise } from \"../utils/is-promise.mjs\";\nimport { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT } from \"../crypto/jwt.mjs\";\nimport { createAccountStore, createSessionStore, getAccountCookie, getChunkedCookie, setAccountCookie } from \"./session-store.mjs\";\nimport { sec } from \"../utils/time.mjs\";\nimport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, parseSetCookieHeader, setCookieToHeader, splitSetCookieHeader, stripSecureCookiePrefix } from \"./cookie-utils.mjs\";\nimport { env, isProduction } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { filterOutputFields } from \"@better-auth/core/utils/db\";\nimport { base64Url } from \"@better-auth/utils/base64\";\nimport { binary } from \"@better-auth/utils/binary\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\n//#region src/cookies/index.ts\nfunction createCookieGetter(options) {\n\tconst baseURLString = typeof options.baseURL === \"string\" ? options.baseURL : void 0;\n\tconst dynamicProtocol = typeof options.baseURL === \"object\" && options.baseURL !== null ? options.baseURL.protocol : void 0;\n\tconst secureCookiePrefix = (options.advanced?.useSecureCookies !== void 0 ? options.advanced?.useSecureCookies : dynamicProtocol === \"https\" ? true : dynamicProtocol === \"http\" ? false : baseURLString ? baseURLString.startsWith(\"https://\") : isProduction) ? SECURE_COOKIE_PREFIX : \"\";\n\tconst crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled;\n\tconst domain = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (baseURLString ? new URL(baseURLString).hostname : void 0) : void 0;\n\tif (crossSubdomainEnabled && !domain && !isDynamicBaseURLConfig(options.baseURL)) throw new BetterAuthError(\"baseURL is required when crossSubdomainCookies are enabled.\");\n\tfunction createCookie(cookieName, overrideAttributes = {}) {\n\t\tconst prefix = options.advanced?.cookiePrefix || \"better-auth\";\n\t\tconst name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`;\n\t\tconst attributes = options.advanced?.cookies?.[cookieName]?.attributes ?? {};\n\t\treturn {\n\t\t\tname: `${secureCookiePrefix}${name}`,\n\t\t\tattributes: {\n\t\t\t\tsecure: !!secureCookiePrefix,\n\t\t\t\tsameSite: \"lax\",\n\t\t\t\tpath: \"/\",\n\t\t\t\thttpOnly: true,\n\t\t\t\t...crossSubdomainEnabled ? { domain } : {},\n\t\t\t\t...options.advanced?.defaultCookieAttributes,\n\t\t\t\t...overrideAttributes,\n\t\t\t\t...attributes\n\t\t\t}\n\t\t};\n\t}\n\treturn createCookie;\n}\nfunction getCookies(options) {\n\tconst createCookie = createCookieGetter(options);\n\tconst sessionToken = createCookie(\"session_token\", { maxAge: options.session?.expiresIn || sec(\"7d\") });\n\tconst sessionData = createCookie(\"session_data\", { maxAge: options.session?.cookieCache?.maxAge || 300 });\n\tconst accountData = createCookie(\"account_data\", { maxAge: options.session?.cookieCache?.maxAge || 300 });\n\tconst dontRememberToken = createCookie(\"dont_remember\");\n\treturn {\n\t\tsessionToken: {\n\t\t\tname: sessionToken.name,\n\t\t\tattributes: sessionToken.attributes\n\t\t},\n\t\tsessionData: {\n\t\t\tname: sessionData.name,\n\t\t\tattributes: sessionData.attributes\n\t\t},\n\t\tdontRememberToken: {\n\t\t\tname: dontRememberToken.name,\n\t\t\tattributes: dontRememberToken.attributes\n\t\t},\n\t\taccountData: {\n\t\t\tname: accountData.name,\n\t\t\tattributes: accountData.attributes\n\t\t}\n\t};\n}\nasync function setCookieCache(ctx, session, dontRememberMe) {\n\tif (!ctx.context.options.session?.cookieCache?.enabled) return;\n\tconst filteredSession = filterOutputFields(session.session, ctx.context.options.session?.additionalFields);\n\tconst filteredUser = parseUserOutput(ctx.context.options, session.user);\n\tconst versionConfig = ctx.context.options.session?.cookieCache?.version;\n\tlet version = \"1\";\n\tif (versionConfig) {\n\t\tif (typeof versionConfig === \"string\") version = versionConfig;\n\t\telse if (typeof versionConfig === \"function\") {\n\t\t\tconst result = versionConfig(session.session, session.user);\n\t\t\tversion = isPromise(result) ? await result : result;\n\t\t}\n\t}\n\tconst sessionData = {\n\t\tsession: filteredSession,\n\t\tuser: filteredUser,\n\t\tupdatedAt: Date.now(),\n\t\tversion\n\t};\n\tconst options = {\n\t\t...ctx.context.authCookies.sessionData.attributes,\n\t\tmaxAge: dontRememberMe ? void 0 : ctx.context.authCookies.sessionData.attributes.maxAge\n\t};\n\tconst expiresAtDate = getDate(options.maxAge || 60, \"sec\").getTime();\n\tconst strategy = ctx.context.options.session?.cookieCache?.strategy || \"compact\";\n\tlet data;\n\tif (strategy === \"jwe\") data = await symmetricEncodeJWT(sessionData, ctx.context.secretConfig, \"better-auth-session\", options.maxAge || 300);\n\telse if (strategy === \"jwt\") data = await signJWT(sessionData, ctx.context.secret, options.maxAge || 300);\n\telse data = base64Url.encode(JSON.stringify({\n\t\tsession: sessionData,\n\t\texpiresAt: expiresAtDate,\n\t\tsignature: await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, JSON.stringify({\n\t\t\t...sessionData,\n\t\t\texpiresAt: expiresAtDate\n\t\t}))\n\t}), { padding: false });\n\tif (data.length > 4093) {\n\t\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx);\n\t\tconst cookies = sessionStore.chunk(data, options);\n\t\tsessionStore.setCookies(cookies);\n\t} else {\n\t\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx);\n\t\tif (sessionStore.hasChunks()) {\n\t\t\tconst cleanCookies = sessionStore.clean();\n\t\t\tsessionStore.setCookies(cleanCookies);\n\t\t}\n\t\tctx.setCookie(ctx.context.authCookies.sessionData.name, data, options);\n\t}\n\tif (ctx.context.options.account?.storeAccountCookie) {\n\t\tconst accountData = await getAccountCookie(ctx);\n\t\tif (accountData) await setAccountCookie(ctx, accountData);\n\t}\n}\nasync function setSessionCookie(ctx, session, dontRememberMe, overrides) {\n\tconst dontRememberMeCookie = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);\n\tdontRememberMe = dontRememberMe !== void 0 ? dontRememberMe : !!dontRememberMeCookie;\n\tconst options = ctx.context.authCookies.sessionToken.attributes;\n\tconst maxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn;\n\tawait ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, {\n\t\t...options,\n\t\tmaxAge,\n\t\t...overrides\n\t});\n\tif (dontRememberMe) await ctx.setSignedCookie(ctx.context.authCookies.dontRememberToken.name, \"true\", ctx.context.secret, ctx.context.authCookies.dontRememberToken.attributes);\n\tawait setCookieCache(ctx, session, dontRememberMe);\n\tctx.context.setNewSession(session);\n}\n/**\n* Expires a cookie by setting `maxAge: 0` while preserving its attributes\n*/\nfunction expireCookie(ctx, cookie) {\n\tctx.setCookie(cookie.name, \"\", {\n\t\t...cookie.attributes,\n\t\tmaxAge: 0\n\t});\n}\nfunction deleteSessionCookie(ctx, skipDontRememberMe) {\n\texpireCookie(ctx, ctx.context.authCookies.sessionToken);\n\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\tif (ctx.context.options.account?.storeAccountCookie) {\n\t\texpireCookie(ctx, ctx.context.authCookies.accountData);\n\t\tconst accountStore = createAccountStore(ctx.context.authCookies.accountData.name, ctx.context.authCookies.accountData.attributes, ctx);\n\t\tconst cleanCookies = accountStore.clean();\n\t\taccountStore.setCookies(cleanCookies);\n\t}\n\tif (ctx.context.oauthConfig.storeStateStrategy === \"cookie\") expireCookie(ctx, ctx.context.createAuthCookie(\"oauth_state\"));\n\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, ctx.context.authCookies.sessionData.attributes, ctx);\n\tconst cleanCookies = sessionStore.clean();\n\tsessionStore.setCookies(cleanCookies);\n\tif (!skipDontRememberMe) expireCookie(ctx, ctx.context.authCookies.dontRememberToken);\n}\nfunction parseCookies(cookieHeader) {\n\tconst cookies = cookieHeader.split(\"; \");\n\tconst cookieMap = /* @__PURE__ */ new Map();\n\tcookies.forEach((cookie) => {\n\t\tconst [name, value] = cookie.split(/=(.*)/s);\n\t\tcookieMap.set(name, value);\n\t});\n\treturn cookieMap;\n}\nconst getSessionCookie = (request, config) => {\n\tconst cookies = (request instanceof Headers || !(\"headers\" in request) ? request : request.headers).get(\"cookie\");\n\tif (!cookies) return null;\n\tconst { cookieName = \"session_token\", cookiePrefix = \"better-auth\" } = config || {};\n\tconst parsedCookie = parseCookies(cookies);\n\tconst getCookie = (name) => parsedCookie.get(name) || parsedCookie.get(`__Secure-${name}`);\n\tconst sessionToken = getCookie(`${cookiePrefix}.${cookieName}`) || getCookie(`${cookiePrefix}-${cookieName}`);\n\tif (sessionToken) return sessionToken;\n\treturn null;\n};\nconst getCookieCache = async (request, config) => {\n\tconst cookies = (request instanceof Headers || !(\"headers\" in request) ? request : request.headers).get(\"cookie\");\n\tif (!cookies) return null;\n\tconst { cookieName = \"session_data\", cookiePrefix = \"better-auth\" } = config || {};\n\tconst name = config?.isSecure !== void 0 ? config.isSecure ? `${SECURE_COOKIE_PREFIX}${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}` : isProduction ? `${SECURE_COOKIE_PREFIX}${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}`;\n\tconst parsedCookie = parseCookies(cookies);\n\tlet sessionData = parsedCookie.get(name);\n\tif (!sessionData) {\n\t\tconst chunks = [];\n\t\tfor (const [cookieName, value] of parsedCookie.entries()) if (cookieName.startsWith(name + \".\")) {\n\t\t\tconst parts = cookieName.split(\".\");\n\t\t\tconst indexStr = parts[parts.length - 1];\n\t\t\tconst index = parseInt(indexStr || \"0\", 10);\n\t\t\tif (!isNaN(index)) chunks.push({\n\t\t\t\tindex,\n\t\t\t\tvalue\n\t\t\t});\n\t\t}\n\t\tif (chunks.length > 0) {\n\t\t\tchunks.sort((a, b) => a.index - b.index);\n\t\t\tsessionData = chunks.map((c) => c.value).join(\"\");\n\t\t}\n\t}\n\tif (sessionData) {\n\t\tconst secret = config?.secret || env.BETTER_AUTH_SECRET;\n\t\tif (!secret) throw new BetterAuthError(\"getCookieCache requires a secret to be provided. Either pass it as an option or set the BETTER_AUTH_SECRET environment variable\");\n\t\tconst strategy = config?.strategy || \"compact\";\n\t\tif (strategy === \"jwe\") {\n\t\t\tconst payload = await symmetricDecodeJWT(sessionData, secret, \"better-auth-session\");\n\t\t\tif (payload && payload.session && payload.user) {\n\t\t\t\tif (config?.version) {\n\t\t\t\t\tconst cookieVersion = payload.version || \"1\";\n\t\t\t\t\tlet expectedVersion = \"1\";\n\t\t\t\t\tif (typeof config.version === \"string\") expectedVersion = config.version;\n\t\t\t\t\telse if (typeof config.version === \"function\") {\n\t\t\t\t\t\tconst result = config.version(payload.session, payload.user);\n\t\t\t\t\t\texpectedVersion = isPromise(result) ? await result : result;\n\t\t\t\t\t}\n\t\t\t\t\tif (cookieVersion !== expectedVersion) return null;\n\t\t\t\t}\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn null;\n\t\t} else if (strategy === \"jwt\") {\n\t\t\tconst payload = await verifyJWT(sessionData, secret);\n\t\t\tif (payload && payload.session && payload.user) {\n\t\t\t\tif (config?.version) {\n\t\t\t\t\tconst cookieVersion = payload.version || \"1\";\n\t\t\t\t\tlet expectedVersion = \"1\";\n\t\t\t\t\tif (typeof config.version === \"string\") expectedVersion = config.version;\n\t\t\t\t\telse if (typeof config.version === \"function\") {\n\t\t\t\t\t\tconst result = config.version(payload.session, payload.user);\n\t\t\t\t\t\texpectedVersion = isPromise(result) ? await result : result;\n\t\t\t\t\t}\n\t\t\t\t\tif (cookieVersion !== expectedVersion) return null;\n\t\t\t\t}\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn null;\n\t\t} else {\n\t\t\tconst sessionDataPayload = safeJSONParse(binary.decode(base64Url.decode(sessionData)));\n\t\t\tif (!sessionDataPayload) return null;\n\t\t\tif (!await createHMAC(\"SHA-256\", \"base64urlnopad\").verify(secret, JSON.stringify({\n\t\t\t\t...sessionDataPayload.session,\n\t\t\t\texpiresAt: sessionDataPayload.expiresAt\n\t\t\t}), sessionDataPayload.signature)) return null;\n\t\t\tif (config?.version && sessionDataPayload.session) {\n\t\t\t\tconst cookieVersion = sessionDataPayload.session.version || \"1\";\n\t\t\t\tlet expectedVersion = \"1\";\n\t\t\t\tif (typeof config.version === \"string\") expectedVersion = config.version;\n\t\t\t\telse if (typeof config.version === \"function\") {\n\t\t\t\t\tconst result = config.version(sessionDataPayload.session.session, sessionDataPayload.session.user);\n\t\t\t\t\texpectedVersion = isPromise(result) ? await result : result;\n\t\t\t\t}\n\t\t\t\tif (cookieVersion !== expectedVersion) return null;\n\t\t\t}\n\t\t\treturn sessionDataPayload.session;\n\t\t}\n\t}\n\treturn null;\n};\n//#endregion\nexport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, createCookieGetter, createSessionStore, deleteSessionCookie, expireCookie, getAccountCookie, getChunkedCookie, getCookieCache, getCookies, getSessionCookie, parseCookies, parseSetCookieHeader, setCookieCache, setCookieToHeader, setSessionCookie, splitSetCookieHeader, stripSecureCookiePrefix };\n", "const decoders = /* @__PURE__ */ new Map();\nconst encoder = new TextEncoder();\nconst binary = {\n decode: (data, encoding = \"utf-8\") => {\n if (!decoders.has(encoding)) {\n decoders.set(encoding, new TextDecoder(encoding));\n }\n const decoder = decoders.get(encoding);\n return decoder.decode(data);\n },\n encode: encoder.encode\n};\n\nexport { binary };\n", "const hexadecimal = \"0123456789abcdef\";\nconst hex = {\n encode: (data) => {\n if (typeof data === \"string\") {\n data = new TextEncoder().encode(data);\n }\n if (data.byteLength === 0) {\n return \"\";\n }\n const buffer = new Uint8Array(data);\n let result = \"\";\n for (const byte of buffer) {\n result += byte.toString(16).padStart(2, \"0\");\n }\n return result;\n },\n decode: (data) => {\n if (!data) {\n return \"\";\n }\n if (typeof data === \"string\") {\n if (data.length % 2 !== 0) {\n throw new Error(\"Invalid hexadecimal string\");\n }\n if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) {\n throw new Error(\"Invalid hexadecimal string\");\n }\n const result = new Uint8Array(data.length / 2);\n for (let i = 0; i < data.length; i += 2) {\n result[i / 2] = parseInt(data.slice(i, i + 2), 16);\n }\n return new TextDecoder().decode(result);\n }\n return new TextDecoder().decode(data);\n }\n};\n\nexport { hex };\n", "import { hex } from './hex.mjs';\nimport { base64Url, base64 } from './base64.mjs';\nimport { getWebcryptoSubtle } from './index.mjs';\n\nconst createHMAC = (algorithm = \"SHA-256\", encoding = \"none\") => {\n const hmac = {\n importKey: async (key, keyUsage) => {\n return getWebcryptoSubtle().importKey(\n \"raw\",\n typeof key === \"string\" ? new TextEncoder().encode(key) : key,\n { name: \"HMAC\", hash: { name: algorithm } },\n false,\n [keyUsage]\n );\n },\n sign: async (hmacKey, data) => {\n if (typeof hmacKey === \"string\") {\n hmacKey = await hmac.importKey(hmacKey, \"sign\");\n }\n const signature = await getWebcryptoSubtle().sign(\n \"HMAC\",\n hmacKey,\n typeof data === \"string\" ? new TextEncoder().encode(data) : data\n );\n if (encoding === \"hex\") {\n return hex.encode(signature);\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n return base64Url.encode(signature, {\n padding: encoding !== \"base64urlnopad\"\n });\n }\n return signature;\n },\n verify: async (hmacKey, data, signature) => {\n if (typeof hmacKey === \"string\") {\n hmacKey = await hmac.importKey(hmacKey, \"verify\");\n }\n if (encoding === \"hex\") {\n signature = hex.decode(signature);\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n signature = await base64.decode(signature);\n }\n return getWebcryptoSubtle().verify(\n \"HMAC\",\n hmacKey,\n typeof signature === \"string\" ? new TextEncoder().encode(signature) : signature,\n typeof data === \"string\" ? new TextEncoder().encode(data) : data\n );\n }\n };\n return hmac;\n};\n\nexport { createHMAC };\n", "import { generateRandomString } from \"./crypto/random.mjs\";\nimport { symmetricDecrypt, symmetricEncrypt } from \"./crypto/index.mjs\";\nimport { expireCookie } from \"./cookies/index.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport * as z from \"zod\";\n//#region src/state.ts\nconst stateDataSchema = z.looseObject({\n\tcallbackURL: z.string(),\n\tcodeVerifier: z.string(),\n\terrorURL: z.string().optional(),\n\tnewUserURL: z.string().optional(),\n\texpiresAt: z.number(),\n\toauthState: z.string().optional(),\n\tlink: z.object({\n\t\temail: z.string(),\n\t\tuserId: z.coerce.string()\n\t}).optional(),\n\trequestSignUp: z.boolean().optional()\n});\nvar StateError = class extends BetterAuthError {\n\tcode;\n\tdetails;\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.code = options.code;\n\t\tthis.details = options.details;\n\t}\n};\nasync function generateGenericState(c, stateData, settings) {\n\tconst state = generateRandomString(32);\n\tif (c.context.oauthConfig.storeStateStrategy === \"cookie\") {\n\t\tconst payload = {\n\t\t\t...stateData,\n\t\t\toauthState: state\n\t\t};\n\t\tconst encryptedData = await symmetricEncrypt({\n\t\t\tkey: c.context.secretConfig,\n\t\t\tdata: JSON.stringify(payload)\n\t\t});\n\t\tconst stateCookie = c.context.createAuthCookie(settings?.cookieName ?? \"oauth_state\", { maxAge: 600 });\n\t\tc.setCookie(stateCookie.name, encryptedData, stateCookie.attributes);\n\t\treturn {\n\t\t\tstate,\n\t\t\tcodeVerifier: stateData.codeVerifier\n\t\t};\n\t}\n\tconst stateCookie = c.context.createAuthCookie(settings?.cookieName ?? \"state\", { maxAge: 300 });\n\tawait c.setSignedCookie(stateCookie.name, state, c.context.secret, stateCookie.attributes);\n\tconst expiresAt = /* @__PURE__ */ new Date();\n\texpiresAt.setMinutes(expiresAt.getMinutes() + 10);\n\tif (!await c.context.internalAdapter.createVerificationValue({\n\t\tvalue: JSON.stringify({\n\t\t\t...stateData,\n\t\t\toauthState: state\n\t\t}),\n\t\tidentifier: state,\n\t\texpiresAt\n\t})) throw new StateError(\"Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database\", { code: \"state_generation_error\" });\n\treturn {\n\t\tstate,\n\t\tcodeVerifier: stateData.codeVerifier\n\t};\n}\nasync function parseGenericState(c, state, settings) {\n\tconst storeStateStrategy = c.context.oauthConfig.storeStateStrategy;\n\tlet parsedData;\n\tif (storeStateStrategy === \"cookie\") {\n\t\tconst stateCookie = c.context.createAuthCookie(settings?.cookieName ?? \"oauth_state\");\n\t\tconst encryptedData = c.getCookie(stateCookie.name);\n\t\tif (!encryptedData) throw new StateError(\"State mismatch: auth state cookie not found\", {\n\t\t\tcode: \"state_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\ttry {\n\t\t\tconst decryptedData = await symmetricDecrypt({\n\t\t\t\tkey: c.context.secretConfig,\n\t\t\t\tdata: encryptedData\n\t\t\t});\n\t\t\tparsedData = stateDataSchema.parse(JSON.parse(decryptedData));\n\t\t} catch (error) {\n\t\t\tthrow new StateError(\"State invalid: Failed to decrypt or parse auth state\", {\n\t\t\t\tcode: \"state_invalid\",\n\t\t\t\tdetails: { state },\n\t\t\t\tcause: error\n\t\t\t});\n\t\t}\n\t\tif (!parsedData.oauthState || parsedData.oauthState !== state) throw new StateError(\"State mismatch: OAuth state parameter does not match stored state\", {\n\t\t\tcode: \"state_security_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\texpireCookie(c, stateCookie);\n\t} else {\n\t\tconst data = await c.context.internalAdapter.findVerificationValue(state);\n\t\tif (!data) throw new StateError(\"State mismatch: verification not found\", {\n\t\t\tcode: \"state_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\tparsedData = stateDataSchema.parse(JSON.parse(data.value));\n\t\tif (parsedData.oauthState !== void 0 && parsedData.oauthState !== state) throw new StateError(\"State mismatch: OAuth state parameter does not match stored state\", {\n\t\t\tcode: \"state_security_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\tconst stateCookie = c.context.createAuthCookie(settings?.cookieName ?? \"state\");\n\t\tconst stateCookieValue = await c.getSignedCookie(stateCookie.name, c.context.secret);\n\t\tif (!(settings?.skipStateCookieCheck ?? c.context.oauthConfig.skipStateCookieCheck) && (!stateCookieValue || stateCookieValue !== state)) throw new StateError(\"State mismatch: State not persisted correctly\", {\n\t\t\tcode: \"state_security_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\texpireCookie(c, stateCookie);\n\t\tawait c.context.internalAdapter.deleteVerificationByIdentifier(state);\n\t}\n\tif (parsedData.expiresAt < Date.now()) throw new StateError(\"Invalid state: request expired\", {\n\t\tcode: \"state_mismatch\",\n\t\tdetails: { expiresAt: parsedData.expiresAt }\n\t});\n\treturn parsedData;\n}\n//#endregion\nexport { StateError, generateGenericState, parseGenericState };\n", "//#region src/context/global.ts\nconst symbol = Symbol.for(\"better-auth:global\");\nlet bind = null;\nconst __context = {};\nconst __betterAuthVersion = \"1.6.2\";\n/**\n* We store context instance in the globalThis.\n*\n* The reason we do this is that some bundlers, web framework, or package managers might\n* create multiple copies of BetterAuth in the same process intentionally or unintentionally.\n*\n* For example, yarn v1, Next.js, SSR, Vite...\n*\n* @internal\n*/\nfunction __getBetterAuthGlobal() {\n\tif (!globalThis[symbol]) {\n\t\tglobalThis[symbol] = {\n\t\t\tversion: __betterAuthVersion,\n\t\t\tepoch: 1,\n\t\t\tcontext: __context\n\t\t};\n\t\tbind = globalThis[symbol];\n\t}\n\tbind = globalThis[symbol];\n\tif (bind.version !== __betterAuthVersion) {\n\t\tbind.version = __betterAuthVersion;\n\t\tbind.epoch++;\n\t}\n\treturn globalThis[symbol];\n}\nfunction getBetterAuthVersion() {\n\treturn __getBetterAuthGlobal().version;\n}\n//#endregion\nexport { __getBetterAuthGlobal, getBetterAuthVersion };\n", "//#region src/async_hooks/index.ts\nconst AsyncLocalStoragePromise = import(\n\t/* @vite-ignore */\n\t/* webpackIgnore: true */\n\t\"node:async_hooks\"\n).then((mod) => mod.AsyncLocalStorage).catch((err) => {\n\tif (\"AsyncLocalStorage\" in globalThis) return globalThis.AsyncLocalStorage;\n\tif (typeof window !== \"undefined\") return null;\n\tconsole.warn(\"[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.\");\n\tconsole.warn(\"[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler\");\n\tconsole.warn(\"[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag\");\n\tthrow err;\n});\nasync function getAsyncLocalStorage() {\n\tconst mod = await AsyncLocalStoragePromise;\n\tif (mod === null) throw new Error(\"getAsyncLocalStorage is only available in server code\");\n\telse return mod;\n}\n//#endregion\nexport { getAsyncLocalStorage };\n", "import { __getBetterAuthGlobal } from \"./global.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/endpoint-context.ts\nconst ensureAsyncStorage = async () => {\n\tconst betterAuthGlobal = __getBetterAuthGlobal();\n\tif (!betterAuthGlobal.context.endpointContextAsyncStorage) {\n\t\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\t\tbetterAuthGlobal.context.endpointContextAsyncStorage = new AsyncLocalStorage();\n\t}\n\treturn betterAuthGlobal.context.endpointContextAsyncStorage;\n};\n/**\n* This is for internal use only. Most users should use `getCurrentAuthContext` instead.\n*\n* It is exposed for advanced use cases where you need direct access to the AsyncLocalStorage instance.\n*/\nasync function getCurrentAuthContextAsyncLocalStorage() {\n\treturn ensureAsyncStorage();\n}\nasync function getCurrentAuthContext() {\n\tconst context = (await ensureAsyncStorage()).getStore();\n\tif (!context) throw new Error(\"No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.\");\n\treturn context;\n}\nasync function runWithEndpointContext(context, fn) {\n\treturn (await ensureAsyncStorage()).run(context, fn);\n}\n//#endregion\nexport { getCurrentAuthContext, getCurrentAuthContextAsyncLocalStorage, runWithEndpointContext };\n", "import { __getBetterAuthGlobal } from \"./global.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/request-state.ts\nconst ensureAsyncStorage = async () => {\n\tconst betterAuthGlobal = __getBetterAuthGlobal();\n\tif (!betterAuthGlobal.context.requestStateAsyncStorage) {\n\t\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\t\tbetterAuthGlobal.context.requestStateAsyncStorage = new AsyncLocalStorage();\n\t}\n\treturn betterAuthGlobal.context.requestStateAsyncStorage;\n};\nasync function getRequestStateAsyncLocalStorage() {\n\treturn ensureAsyncStorage();\n}\nasync function hasRequestState() {\n\treturn (await ensureAsyncStorage()).getStore() !== void 0;\n}\nasync function getCurrentRequestState() {\n\tconst store = (await ensureAsyncStorage()).getStore();\n\tif (!store) throw new Error(\"No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.\");\n\treturn store;\n}\nasync function runWithRequestState(store, fn) {\n\treturn (await ensureAsyncStorage()).run(store, fn);\n}\nfunction defineRequestState(initFn) {\n\tconst ref = Object.freeze({});\n\treturn {\n\t\tget ref() {\n\t\t\treturn ref;\n\t\t},\n\t\tasync get() {\n\t\t\tconst store = await getCurrentRequestState();\n\t\t\tif (!store.has(ref)) {\n\t\t\t\tconst initialValue = await initFn();\n\t\t\t\tstore.set(ref, initialValue);\n\t\t\t\treturn initialValue;\n\t\t\t}\n\t\t\treturn store.get(ref);\n\t\t},\n\t\tasync set(value) {\n\t\t\t(await getCurrentRequestState()).set(ref, value);\n\t\t}\n\t};\n}\n//#endregion\nexport { defineRequestState, getCurrentRequestState, getRequestStateAsyncLocalStorage, hasRequestState, runWithRequestState };\n", "import { __getBetterAuthGlobal } from \"./global.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/transaction.ts\nconst ensureAsyncStorage = async () => {\n\tconst betterAuthGlobal = __getBetterAuthGlobal();\n\tif (!betterAuthGlobal.context.adapterAsyncStorage) {\n\t\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\t\tbetterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage();\n\t}\n\treturn betterAuthGlobal.context.adapterAsyncStorage;\n};\n/**\n* This is for internal use only. Most users should use `getCurrentAdapter` instead.\n*\n* It is exposed for advanced use cases where you need direct access to the AsyncLocalStorage instance.\n*/\nconst getCurrentDBAdapterAsyncLocalStorage = async () => {\n\treturn ensureAsyncStorage();\n};\nconst getCurrentAdapter = async (fallback) => {\n\treturn ensureAsyncStorage().then((als) => {\n\t\treturn als.getStore()?.adapter || fallback;\n\t}).catch(() => {\n\t\treturn fallback;\n\t});\n};\nconst runWithAdapter = async (adapter, fn) => {\n\tlet called = false;\n\treturn ensureAsyncStorage().then(async (als) => {\n\t\tcalled = true;\n\t\tconst pendingHooks = [];\n\t\tlet result;\n\t\tlet error;\n\t\tlet hasError = false;\n\t\ttry {\n\t\t\tresult = await als.run({\n\t\t\t\tadapter,\n\t\t\t\tpendingHooks\n\t\t\t}, fn);\n\t\t} catch (err) {\n\t\t\terror = err;\n\t\t\thasError = true;\n\t\t}\n\t\tfor (const hook of pendingHooks) await hook();\n\t\tif (hasError) throw error;\n\t\treturn result;\n\t}).catch((err) => {\n\t\tif (!called) return fn();\n\t\tthrow err;\n\t});\n};\nconst runWithTransaction = async (adapter, fn) => {\n\tlet called = true;\n\treturn ensureAsyncStorage().then(async (als) => {\n\t\tcalled = true;\n\t\tconst pendingHooks = [];\n\t\tlet result;\n\t\tlet error;\n\t\tlet hasError = false;\n\t\ttry {\n\t\t\tresult = await adapter.transaction(async (trx) => {\n\t\t\t\treturn als.run({\n\t\t\t\t\tadapter: trx,\n\t\t\t\t\tpendingHooks\n\t\t\t\t}, fn);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\thasError = true;\n\t\t\terror = e;\n\t\t}\n\t\tfor (const hook of pendingHooks) await hook();\n\t\tif (hasError) throw error;\n\t\treturn result;\n\t}).catch((err) => {\n\t\tif (!called) return fn();\n\t\tthrow err;\n\t});\n};\n/**\n* Queue a hook to be executed after the current transaction commits.\n* If not in a transaction, the hook will execute immediately.\n*/\nconst queueAfterTransactionHook = async (hook) => {\n\treturn ensureAsyncStorage().then((als) => {\n\t\tconst store = als.getStore();\n\t\tif (store) store.pendingHooks.push(hook);\n\t\telse return hook();\n\t}).catch(() => {\n\t\treturn hook();\n\t});\n};\n//#endregion\nexport { getCurrentAdapter, getCurrentDBAdapterAsyncLocalStorage, queueAfterTransactionHook, runWithAdapter, runWithTransaction };\n", "import { defineRequestState } from \"@better-auth/core/context\";\n//#region src/api/state/oauth.ts\nconst { get: getOAuthState, set: setOAuthState } = defineRequestState(() => null);\n//#endregion\nexport { getOAuthState, setOAuthState };\n", "import { generateRandomString } from \"../crypto/random.mjs\";\nimport { setOAuthState } from \"../api/state/oauth.mjs\";\nimport { StateError, generateGenericState, parseGenericState } from \"../state.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\n//#region src/oauth2/state.ts\nasync function generateState(c, link, additionalData) {\n\tconst callbackURL = c.body?.callbackURL || c.context.options.baseURL;\n\tif (!callbackURL) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.CALLBACK_URL_REQUIRED);\n\tconst codeVerifier = generateRandomString(128);\n\tconst stateData = {\n\t\t...additionalData ? additionalData : {},\n\t\tcallbackURL,\n\t\tcodeVerifier,\n\t\terrorURL: c.body?.errorCallbackURL,\n\t\tnewUserURL: c.body?.newUserCallbackURL,\n\t\tlink,\n\t\texpiresAt: Date.now() + 600 * 1e3,\n\t\trequestSignUp: c.body?.requestSignUp\n\t};\n\tawait setOAuthState(stateData);\n\ttry {\n\t\treturn generateGenericState(c, stateData);\n\t} catch (error) {\n\t\tc.context.logger.error(\"Failed to create verification\", error);\n\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\t\tmessage: \"Unable to create verification\",\n\t\t\tcause: error\n\t\t});\n\t}\n}\nasync function parseState(c) {\n\tconst state = c.query.state || c.body.state;\n\tconst errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;\n\tlet parsedData;\n\ttry {\n\t\tparsedData = await parseGenericState(c, state);\n\t} catch (error) {\n\t\tc.context.logger.error(\"Failed to parse state\", error);\n\t\tif (error instanceof StateError && error.code === \"state_security_mismatch\") throw c.redirect(`${errorURL}?error=state_mismatch`);\n\t\tthrow c.redirect(`${errorURL}?error=please_restart_the_process`);\n\t}\n\tif (!parsedData.errorURL) parsedData.errorURL = errorURL;\n\tif (parsedData) await setOAuthState(parsedData);\n\treturn parsedData;\n}\n//#endregion\nexport { generateState, parseState };\n", "//#region src/utils/hide-metadata.ts\nconst HIDE_METADATA = { scope: \"server\" };\n//#endregion\nexport { HIDE_METADATA };\n", "import { APIError } from \"@better-auth/core/error\";\nimport { APIError as APIError$1 } from \"better-call\";\n//#region src/utils/is-api-error.ts\nfunction isAPIError(error) {\n\treturn error instanceof APIError$1 || error instanceof APIError || error?.name === \"APIError\";\n}\n//#endregion\nexport { isAPIError };\n", "import { APIError, BetterCallError, ValidationError, hideInternalStackFrames, kAPIErrorHeaderSymbol, makeErrorForHideStackFrame, statusCodes } from \"./error.mjs\";\nimport { toResponse } from \"./to-response.mjs\";\nimport { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from \"./cookies.mjs\";\nimport { createInternalContext } from \"./context.mjs\";\nimport { createEndpoint } from \"./endpoint.mjs\";\nimport { createMiddleware } from \"./middleware.mjs\";\nimport { generator, getHTML } from \"./openapi.mjs\";\nimport { createRouter } from \"./router.mjs\";\n\nexport { APIError, BetterCallError, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, kAPIErrorHeaderSymbol, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };", "import { APIError } from \"./error\";\n\nconst jsonContentTypeRegex = /^application\\/([a-z0-9.+-]*\\+)?json/i;\n\nexport async function getBody(request: Request, allowedMediaTypes?: string[]) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\tconst normalizedContentType = contentType.toLowerCase();\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\t// Validate content-type if allowedMediaTypes is provided\n\tif (allowedMediaTypes && allowedMediaTypes.length > 0) {\n\t\tconst isAllowed = allowedMediaTypes.some((allowed) => {\n\t\t\t// Normalize both content types for comparison\n\t\t\tconst normalizedContentTypeBase = normalizedContentType\n\t\t\t\t.split(\";\")[0]!\n\t\t\t\t.trim();\n\t\t\tconst normalizedAllowed = allowed.toLowerCase().trim();\n\t\t\treturn (\n\t\t\t\tnormalizedContentTypeBase === normalizedAllowed ||\n\t\t\t\tnormalizedContentTypeBase.includes(normalizedAllowed)\n\t\t\t);\n\t\t});\n\n\t\tif (!isAllowed) {\n\t\t\tif (!normalizedContentType) {\n\t\t\t\tthrow new APIError(415, {\n\t\t\t\t\tmessage: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(\", \")}`,\n\t\t\t\t\tcode: \"UNSUPPORTED_MEDIA_TYPE\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow new APIError(415, {\n\t\t\t\tmessage: `Content-Type \"${contentType}\" is not allowed. Allowed types: ${allowedMediaTypes.join(\", \")}`,\n\t\t\t\tcode: \"UNSUPPORTED_MEDIA_TYPE\",\n\t\t\t});\n\t\t}\n\t}\n\n\tif (jsonContentTypeRegex.test(normalizedContentType)) {\n\t\treturn await request.json();\n\t}\n\n\tif (normalizedContentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (normalizedContentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (normalizedContentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (normalizedContentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tnormalizedContentType.includes(\"application/pdf\") ||\n\t\tnormalizedContentType.includes(\"image/\") ||\n\t\tnormalizedContentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (\n\t\tnormalizedContentType.includes(\"application/stream\") ||\n\t\trequest.body instanceof ReadableStream\n\t) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n\nexport function isAPIError(error: any): error is APIError {\n\treturn error instanceof APIError || error?.name === \"APIError\";\n}\n\nexport function tryDecode(str: string) {\n\ttry {\n\t\treturn str.includes(\"%\") ? decodeURIComponent(str) : str;\n\t} catch {\n\t\treturn str;\n\t}\n}\n\ntype Success = {\n\tdata: T;\n\terror: null;\n};\n\ntype Failure = {\n\tdata: null;\n\terror: E;\n};\n\ntype Result = Success | Failure;\n\nexport async function tryCatch(\n\tpromise: Promise,\n): Promise> {\n\ttry {\n\t\tconst data = await promise;\n\t\treturn { data, error: null };\n\t} catch (error) {\n\t\treturn { data: null, error: error as E };\n\t}\n}\n\n/**\n * Check if an object is a `Request`\n * - `instanceof`: works for native Request instances\n * - `toString`: handles where instanceof check fails but the object is still a valid Request\n */\nexport function isRequest(obj: unknown): obj is Request {\n\treturn (\n\t\tobj instanceof Request ||\n\t\tObject.prototype.toString.call(obj) === \"[object Request]\"\n\t);\n}\n", "import { getWebcryptoSubtle } from \"@better-auth/utils\";\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nexport const getCryptoKey = async (secret: string | BufferSource) => {\n\tconst secretBuf =\n\t\ttypeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await getWebcryptoSubtle().importKey(\n\t\t\"raw\",\n\t\tsecretBuf,\n\t\talgorithm,\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n};\n\nexport const verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await getWebcryptoSubtle().verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\nconst makeSignature = async (\n\tvalue: string,\n\tsecret: string | BufferSource,\n): Promise => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await getWebcryptoSubtle().sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nexport const signCookieValue = async (\n\tvalue: string,\n\tsecret: string | BufferSource,\n) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\n};\n", "import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (\n\tkey: string,\n\tvalue: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n", "import type { EndpointOptions } from \"./endpoint\";\nimport type { InputContext } from \"./context\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\n\ntype ValidationResponse =\n\t| {\n\t\t\tdata: {\n\t\t\t\tbody: any;\n\t\t\t\tquery: any;\n\t\t\t};\n\t\t\terror: null;\n\t }\n\t| {\n\t\t\tdata: null;\n\t\t\terror: {\n\t\t\t\tmessage: string;\n\t\t\t\tissues: readonly StandardSchemaV1.Issue[];\n\t\t\t};\n\t };\n\n/**\n * Runs validation on body and query\n * @returns error and data object\n */\nexport async function runValidation(\n\toptions: EndpointOptions,\n\tcontext: InputContext = {},\n): Promise {\n\tlet request = {\n\t\tbody: context.body,\n\t\tquery: context.query,\n\t} as {\n\t\tbody: any;\n\t\tquery: any;\n\t};\n\tif (options.body) {\n\t\tconst result = await options.body[\"~standard\"].validate(context.body);\n\t\tif (result.issues) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: fromError(result.issues, \"body\"),\n\t\t\t};\n\t\t}\n\t\trequest.body = result.value;\n\t}\n\n\tif (options.query) {\n\t\tconst result = await options.query[\"~standard\"].validate(context.query);\n\t\tif (result.issues) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: fromError(result.issues, \"query\"),\n\t\t\t};\n\t\t}\n\t\trequest.query = result.value;\n\t}\n\tif (options.requireHeaders && !context.headers) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: { message: \"Headers is required\", issues: [] },\n\t\t};\n\t}\n\tif (options.requireRequest && !context.request) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: { message: \"Request is required\", issues: [] },\n\t\t};\n\t}\n\treturn {\n\t\tdata: request,\n\t\terror: null,\n\t};\n}\n\nfunction fromError(\n\terror: readonly StandardSchemaV1.Issue[],\n\tvalidating: string,\n) {\n\tconst message = error\n\t\t.map((e) => {\n\t\t\treturn `[${e.path?.length ? `${validating}.` + e.path.map((x) => (typeof x === \"object\" ? x.key : x)).join(\".\") : validating}] ${e.message}`;\n\t\t})\n\t\t.join(\"; \");\n\n\treturn {\n\t\tmessage,\n\t\tissues: error,\n\t};\n}\n", "import { ZodObject, ZodOptional, ZodType } from \"zod\";\nimport type { Endpoint, EndpointOptions } from \"./endpoint\";\n\nexport type OpenAPISchemaType =\n\t| \"string\"\n\t| \"number\"\n\t| \"integer\"\n\t| \"boolean\"\n\t| \"array\"\n\t| \"object\";\n\nexport interface OpenAPIParameter {\n\tin: \"query\" | \"path\" | \"header\" | \"cookie\";\n\tname?: string;\n\tdescription?: string;\n\trequired?: boolean;\n\tschema?: {\n\t\ttype: OpenAPISchemaType;\n\t\tformat?: string | undefined;\n\t\titems?: {\n\t\t\ttype: OpenAPISchemaType;\n\t\t};\n\t\tenum?: string[];\n\t\tminLength?: number;\n\t\tdescription?: string | undefined;\n\t\tdefault?: string | undefined;\n\t\texample?: string | undefined;\n\t};\n}\n\nexport interface Path {\n\tget?: {\n\t\ttags?: string[];\n\t\toperationId?: string;\n\t\tdescription?: string;\n\t\tsecurity?: [{ bearerAuth: string[] }];\n\t\tparameters?: OpenAPIParameter[];\n\t\tresponses?: {\n\t\t\t[key in string]: {\n\t\t\t\tdescription?: string;\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n\tpost?: {\n\t\ttags?: string[];\n\t\toperationId?: string;\n\t\tdescription?: string;\n\t\tsecurity?: [{ bearerAuth: string[] }];\n\t\tparameters?: OpenAPIParameter[];\n\t\trequestBody?: {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\tproperties?: Record;\n\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\tresponses?: {\n\t\t\t[key in string]: {\n\t\t\t\tdescription?: string;\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n}\nconst paths: Record = {};\n\nfunction getTypeFromZodType(zodType: ZodType) {\n\tswitch (zodType.constructor.name) {\n\t\tcase \"ZodString\":\n\t\t\treturn \"string\";\n\t\tcase \"ZodNumber\":\n\t\t\treturn \"number\";\n\t\tcase \"ZodBoolean\":\n\t\t\treturn \"boolean\";\n\t\tcase \"ZodObject\":\n\t\t\treturn \"object\";\n\t\tcase \"ZodArray\":\n\t\t\treturn \"array\";\n\t\tdefault:\n\t\t\treturn \"string\";\n\t}\n}\n\nfunction getParameters(options: EndpointOptions) {\n\tconst parameters: OpenAPIParameter[] = [];\n\tif (options.metadata?.openapi?.parameters) {\n\t\tparameters.push(...options.metadata.openapi.parameters);\n\t\treturn parameters;\n\t}\n\tif (options.query instanceof ZodObject) {\n\t\tObject.entries(options.query.shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodObject) {\n\t\t\t\tparameters.push({\n\t\t\t\t\tname: key,\n\t\t\t\t\tin: \"query\",\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\t\t...(\"minLength\" in value && value.minLength\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tminLength: value.minLength as number,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tdescription: value.description,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\treturn parameters;\n}\n\nfunction getRequestBody(options: EndpointOptions): any {\n\tif (options.metadata?.openapi?.requestBody) {\n\t\treturn options.metadata.openapi.requestBody;\n\t}\n\tif (!options.body) return undefined;\n\tif (\n\t\toptions.body instanceof ZodObject ||\n\t\toptions.body instanceof ZodOptional\n\t) {\n\t\t// @ts-ignore\n\t\tconst shape = options.body.shape;\n\t\tif (!shape) return undefined;\n\t\tconst properties: Record = {};\n\t\tconst required: string[] = [];\n\t\tObject.entries(shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodObject) {\n\t\t\t\tproperties[key] = {\n\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\tdescription: value.description,\n\t\t\t\t};\n\t\t\t\tif (!(value instanceof ZodOptional)) {\n\t\t\t\t\trequired.push(key);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\trequired:\n\t\t\t\toptions.body instanceof ZodOptional\n\t\t\t\t\t? false\n\t\t\t\t\t: options.body\n\t\t\t\t\t\t? true\n\t\t\t\t\t\t: false,\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties,\n\t\t\t\t\t\trequired,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction getResponse(responses?: Record) {\n\treturn {\n\t\t\"400\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"message\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Bad Request. Usually due to missing parameters, or invalid parameters.\",\n\t\t},\n\t\t\"401\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"message\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Unauthorized. Due to missing or invalid authentication.\",\n\t\t},\n\t\t\"403\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Forbidden. You do not have permission to access this resource or to perform this action.\",\n\t\t},\n\t\t\"404\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Not Found. The requested resource was not found.\",\n\t\t},\n\t\t\"429\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Too Many Requests. You have exceeded the rate limit. Try again later.\",\n\t\t},\n\t\t\"500\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Internal Server Error. This is a problem with the server that you cannot fix.\",\n\t\t},\n\t\t...responses,\n\t} as any;\n}\n\nexport async function generator(\n\tendpoints: Record,\n\tconfig?: {\n\t\turl: string;\n\t},\n) {\n\tconst components = {\n\t\tschemas: {},\n\t};\n\n\tObject.entries(endpoints).forEach(([_, value]) => {\n\t\tconst options = value.options as EndpointOptions;\n\t\tif (!value.path || options.metadata?.SERVER_ONLY) return;\n\t\tif (options.method === \"GET\") {\n\t\t\tpaths[value.path] = {\n\t\t\t\tget: {\n\t\t\t\t\ttags: [\"Default\", ...(options.metadata?.openapi?.tags || [])],\n\t\t\t\t\tdescription: options.metadata?.openapi?.description,\n\t\t\t\t\toperationId: options.metadata?.openapi?.operationId,\n\t\t\t\t\tsecurity: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbearerAuth: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tparameters: getParameters(options),\n\t\t\t\t\tresponses: getResponse(options.metadata?.openapi?.responses),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (options.method === \"POST\") {\n\t\t\tconst body = getRequestBody(options);\n\t\t\tpaths[value.path] = {\n\t\t\t\tpost: {\n\t\t\t\t\ttags: [\"Default\", ...(options.metadata?.openapi?.tags || [])],\n\t\t\t\t\tdescription: options.metadata?.openapi?.description,\n\t\t\t\t\toperationId: options.metadata?.openapi?.operationId,\n\t\t\t\t\tsecurity: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbearerAuth: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tparameters: getParameters(options),\n\t\t\t\t\t...(body\n\t\t\t\t\t\t? { requestBody: body }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\t\t\t//set body none\n\t\t\t\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\tresponses: getResponse(options.metadata?.openapi?.responses),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t});\n\n\tconst res = {\n\t\topenapi: \"3.1.1\",\n\t\tinfo: {\n\t\t\ttitle: \"Better Auth\",\n\t\t\tdescription: \"API Reference for your Better Auth Instance\",\n\t\t\tversion: \"1.1.0\",\n\t\t},\n\t\tcomponents,\n\t\tsecurity: [\n\t\t\t{\n\t\t\t\tapiKeyCookie: [],\n\t\t\t},\n\t\t],\n\t\tservers: [\n\t\t\t{\n\t\t\t\turl: config?.url,\n\t\t\t},\n\t\t],\n\t\ttags: [\n\t\t\t{\n\t\t\t\tname: \"Default\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.\",\n\t\t\t},\n\t\t],\n\t\tpaths,\n\t};\n\treturn res;\n}\n\nexport const getHTML = (\n\tapiReference: Record,\n\tconfig?: {\n\t\tlogo?: string;\n\t\ttheme?: string;\n\t\ttitle?: string;\n\t\tdescription?: string;\n\t},\n) => `\n\n \n Scalar API Reference\n \n \n \n \n \n ${JSON.stringify(apiReference)}\n \n\t \n\t \n \n`;\n", "const NullProtoObj = /* @__PURE__ */ (() => {\n\tconst e = function() {};\n\treturn e.prototype = Object.create(null), Object.freeze(e.prototype), e;\n})();\n\n/**\n* Create a new router context.\n*/\nfunction createRouter() {\n\treturn {\n\t\troot: { key: \"\" },\n\t\tstatic: new NullProtoObj()\n\t};\n}\n\nfunction splitPath(path) {\n\tconst [_, ...s] = path.split(\"/\");\n\treturn s[s.length - 1] === \"\" ? s.slice(0, -1) : s;\n}\nfunction getMatchParams(segments, paramsMap) {\n\tconst params = new NullProtoObj();\n\tfor (const [index, name] of paramsMap) {\n\t\tconst segment = index < 0 ? segments.slice(-(index + 1)).join(\"/\") : segments[index];\n\t\tif (typeof name === \"string\") params[name] = segment;\n\t\telse {\n\t\t\tconst match = segment.match(name);\n\t\t\tif (match) for (const key in match.groups) params[key] = match.groups[key];\n\t\t}\n\t}\n\treturn params;\n}\n\n/**\n* Add a route to the router context.\n*/\nfunction addRoute(ctx, method = \"\", path, data) {\n\tmethod = method.toUpperCase();\n\tif (path.charCodeAt(0) !== 47) path = `/${path}`;\n\tpath = path.replace(/\\\\:/g, \"%3A\");\n\tconst segments = splitPath(path);\n\tlet node = ctx.root;\n\tlet _unnamedParamIndex = 0;\n\tconst paramsMap = [];\n\tconst paramsRegexp = [];\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tlet segment = segments[i];\n\t\tif (segment.startsWith(\"**\")) {\n\t\t\tif (!node.wildcard) node.wildcard = { key: \"**\" };\n\t\t\tnode = node.wildcard;\n\t\t\tparamsMap.push([\n\t\t\t\t-(i + 1),\n\t\t\t\tsegment.split(\":\")[1] || \"_\",\n\t\t\t\tsegment.length === 2\n\t\t\t]);\n\t\t\tbreak;\n\t\t}\n\t\tif (segment === \"*\" || segment.includes(\":\")) {\n\t\t\tif (!node.param) node.param = { key: \"*\" };\n\t\t\tnode = node.param;\n\t\t\tif (segment === \"*\") paramsMap.push([\n\t\t\t\ti,\n\t\t\t\t`_${_unnamedParamIndex++}`,\n\t\t\t\ttrue\n\t\t\t]);\n\t\t\telse if (segment.includes(\":\", 1)) {\n\t\t\t\tconst regexp = getParamRegexp(segment);\n\t\t\t\tparamsRegexp[i] = regexp;\n\t\t\t\tnode.hasRegexParam = true;\n\t\t\t\tparamsMap.push([\n\t\t\t\t\ti,\n\t\t\t\t\tregexp,\n\t\t\t\t\tfalse\n\t\t\t\t]);\n\t\t\t} else paramsMap.push([\n\t\t\t\ti,\n\t\t\t\tsegment.slice(1),\n\t\t\t\tfalse\n\t\t\t]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"\\\\*\") segment = segments[i] = \"*\";\n\t\telse if (segment === \"\\\\*\\\\*\") segment = segments[i] = \"**\";\n\t\tconst child = node.static?.[segment];\n\t\tif (child) node = child;\n\t\telse {\n\t\t\tconst staticNode = { key: segment };\n\t\t\tif (!node.static) node.static = new NullProtoObj();\n\t\t\tnode.static[segment] = staticNode;\n\t\t\tnode = staticNode;\n\t\t}\n\t}\n\tconst hasParams = paramsMap.length > 0;\n\tif (!node.methods) node.methods = new NullProtoObj();\n\tnode.methods[method] ??= [];\n\tnode.methods[method].push({\n\t\tdata: data || null,\n\t\tparamsRegexp,\n\t\tparamsMap: hasParams ? paramsMap : void 0\n\t});\n\tif (!hasParams) ctx.static[\"/\" + segments.join(\"/\")] = node;\n}\nfunction getParamRegexp(segment) {\n\tconst regex = segment.replace(/:(\\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\\./g, \"\\\\.\");\n\treturn /* @__PURE__ */ new RegExp(`^${regex}$`);\n}\n\n/**\n* Find a route by path.\n*/\nfunction findRoute(ctx, method = \"\", path, opts) {\n\tif (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);\n\tconst staticNode = ctx.static[path];\n\tif (staticNode && staticNode.methods) {\n\t\tconst staticMatch = staticNode.methods[method] || staticNode.methods[\"\"];\n\t\tif (staticMatch !== void 0) return staticMatch[0];\n\t}\n\tconst segments = splitPath(path);\n\tconst match = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0];\n\tif (match === void 0) return;\n\tif (opts?.params === false) return match;\n\treturn {\n\t\tdata: match.data,\n\t\tparams: match.paramsMap ? getMatchParams(segments, match.paramsMap) : void 0\n\t};\n}\nfunction _lookupTree(ctx, node, method, segments, index) {\n\tif (index === segments.length) {\n\t\tif (node.methods) {\n\t\t\tconst match = node.methods[method] || node.methods[\"\"];\n\t\t\tif (match) return match;\n\t\t}\n\t\tif (node.param && node.param.methods) {\n\t\t\tconst match = node.param.methods[method] || node.param.methods[\"\"];\n\t\t\tif (match) {\n\t\t\t\tconst pMap = match[0].paramsMap;\n\t\t\t\tif (pMap?.[pMap?.length - 1]?.[2]) return match;\n\t\t\t}\n\t\t}\n\t\tif (node.wildcard && node.wildcard.methods) {\n\t\t\tconst match = node.wildcard.methods[method] || node.wildcard.methods[\"\"];\n\t\t\tif (match) {\n\t\t\t\tconst pMap = match[0].paramsMap;\n\t\t\t\tif (pMap?.[pMap?.length - 1]?.[2]) return match;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\tconst segment = segments[index];\n\tif (node.static) {\n\t\tconst staticChild = node.static[segment];\n\t\tif (staticChild) {\n\t\t\tconst match = _lookupTree(ctx, staticChild, method, segments, index + 1);\n\t\t\tif (match) return match;\n\t\t}\n\t}\n\tif (node.param) {\n\t\tconst match = _lookupTree(ctx, node.param, method, segments, index + 1);\n\t\tif (match) {\n\t\t\tif (node.param.hasRegexParam) {\n\t\t\t\tconst exactMatch = match.find((m) => m.paramsRegexp[index]?.test(segment)) || match.find((m) => !m.paramsRegexp[index]);\n\t\t\t\treturn exactMatch ? [exactMatch] : void 0;\n\t\t\t}\n\t\t\treturn match;\n\t\t}\n\t}\n\tif (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[\"\"];\n}\n\n/**\n* Remove a route from the router context.\n*/\nfunction removeRoute(ctx, method, path) {\n\tconst segments = splitPath(path);\n\treturn _remove(ctx.root, method || \"\", segments, 0);\n}\nfunction _remove(node, method, segments, index) {\n\tif (index === segments.length) {\n\t\tif (node.methods && method in node.methods) {\n\t\t\tdelete node.methods[method];\n\t\t\tif (Object.keys(node.methods).length === 0) node.methods = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tconst segment = segments[index];\n\tif (segment === \"*\") {\n\t\tif (node.param) {\n\t\t\t_remove(node.param, method, segments, index + 1);\n\t\t\tif (_isEmptyNode(node.param)) node.param = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tif (segment.startsWith(\"**\")) {\n\t\tif (node.wildcard) {\n\t\t\t_remove(node.wildcard, method, segments, index + 1);\n\t\t\tif (_isEmptyNode(node.wildcard)) node.wildcard = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tconst childNode = node.static?.[segment];\n\tif (childNode) {\n\t\t_remove(childNode, method, segments, index + 1);\n\t\tif (_isEmptyNode(childNode)) {\n\t\t\tdelete node.static[segment];\n\t\t\tif (Object.keys(node.static).length === 0) node.static = void 0;\n\t\t}\n\t}\n}\nfunction _isEmptyNode(node) {\n\treturn node.methods === void 0 && node.static === void 0 && node.param === void 0 && node.wildcard === void 0;\n}\n\n/**\n* Find all route patterns that match the given path.\n*/\nfunction findAllRoutes(ctx, method = \"\", path, opts) {\n\tif (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);\n\tconst segments = splitPath(path);\n\tconst matches = _findAll(ctx, ctx.root, method, segments, 0);\n\tif (opts?.params === false) return matches;\n\treturn matches.map((m) => {\n\t\treturn {\n\t\t\tdata: m.data,\n\t\t\tparams: m.paramsMap ? getMatchParams(segments, m.paramsMap) : void 0\n\t\t};\n\t});\n}\nfunction _findAll(ctx, node, method, segments, index, matches = []) {\n\tconst segment = segments[index];\n\tif (node.wildcard && node.wildcard.methods) {\n\t\tconst match = node.wildcard.methods[method] || node.wildcard.methods[\"\"];\n\t\tif (match) matches.push(...match);\n\t}\n\tif (node.param) {\n\t\t_findAll(ctx, node.param, method, segments, index + 1, matches);\n\t\tif (index === segments.length && node.param.methods) {\n\t\t\tconst match = node.param.methods[method] || node.param.methods[\"\"];\n\t\t\tif (match) {\n\t\t\t\tconst pMap = match[0].paramsMap;\n\t\t\t\tif (pMap?.[pMap?.length - 1]?.[2]) matches.push(...match);\n\t\t\t}\n\t\t}\n\t}\n\tconst staticChild = node.static?.[segment];\n\tif (staticChild) _findAll(ctx, staticChild, method, segments, index + 1, matches);\n\tif (index === segments.length && node.methods) {\n\t\tconst match = node.methods[method] || node.methods[\"\"];\n\t\tif (match) matches.push(...match);\n\t}\n\treturn matches;\n}\n\nfunction routeToRegExp(route = \"/\") {\n\tconst reSegments = [];\n\tlet idCtr = 0;\n\tfor (const segment of route.split(\"/\")) {\n\t\tif (!segment) continue;\n\t\tif (segment === \"*\") reSegments.push(`(?<_${idCtr++}>[^/]*)`);\n\t\telse if (segment.startsWith(\"**\")) reSegments.push(segment === \"**\" ? \"?(?<_>.*)\" : `?(?<${segment.slice(3)}>.+)`);\n\t\telse if (segment.includes(\":\")) reSegments.push(segment.replace(/:(\\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\\./g, \"\\\\.\"));\n\t\telse reSegments.push(segment);\n\t}\n\treturn /* @__PURE__ */ new RegExp(`^/${reSegments.join(\"/\")}/?$`);\n}\n\nexport { NullProtoObj, addRoute, createRouter, findAllRoutes, findRoute, removeRoute, routeToRegExp };", "import {\n\taddRoute,\n\tcreateRouter as createRou3Router,\n\tfindAllRoutes,\n\tfindRoute,\n} from \"rou3\";\nimport { type Endpoint, createEndpoint } from \"./endpoint\";\nimport type { Middleware } from \"./middleware\";\nimport { generator, getHTML } from \"./openapi\";\nimport { toResponse } from \"./to-response\";\nimport { getBody, isAPIError, isRequest } from \"./utils\";\n\nexport interface RouterConfig {\n\tthrowError?: boolean;\n\tbasePath?: string;\n\trouterMiddleware?: Array<{\n\t\tpath: string;\n\t\tmiddleware: Middleware;\n\t}>;\n\t/**\n\t * additional Context that needs to passed to endpoints\n\t *\n\t * this will be available on `ctx.context` on endpoints\n\t */\n\trouterContext?: Record;\n\t/**\n\t * A callback to run before any response\n\t */\n\tonResponse?: (response: Response, request: Request) => any | Promise;\n\t/**\n\t * A callback to run before any request\n\t */\n\tonRequest?: (request: Request) => any | Promise;\n\t/**\n\t * A callback to run when an error is thrown in the router or middleware.\n\t *\n\t * @param error - the error that was thrown in the router or middleware.\n\t * @returns a Response object that will be returned to the client.\n\t */\n\tonError?: (\n\t\terror: unknown,\n\t\trequest: Request,\n\t) => void | Promise | Response | Promise;\n\t/**\n\t * List of allowed media types (MIME types) for the router\n\t *\n\t * if provided, only the media types in the list will be allowed to be passed in the body.\n\t *\n\t * If an endpoint has allowed media types, it will override the router's allowed media types.\n\t *\n\t * @example\n\t * ```ts\n\t * const router = createRouter({\n\t * \t\tallowedMediaTypes: [\"application/json\", \"application/x-www-form-urlencoded\"],\n\t * \t})\n\t */\n\tallowedMediaTypes?: string[];\n\t/**\n\t * Skip trailing slashes\n\t *\n\t * @default false\n\t */\n\tskipTrailingSlashes?: boolean;\n\t/**\n\t * Open API route configuration\n\t */\n\topenapi?: {\n\t\t/**\n\t\t * Disable openapi route\n\t\t *\n\t\t * @default false\n\t\t */\n\t\tdisabled?: boolean;\n\t\t/**\n\t\t * A path to display open api using scalar\n\t\t *\n\t\t * @default \"/api/reference\"\n\t\t */\n\t\tpath?: string;\n\t\t/**\n\t\t * Scalar Configuration\n\t\t */\n\t\tscalar?: {\n\t\t\t/**\n\t\t\t * Title\n\t\t\t * @default \"Open API Reference\"\n\t\t\t */\n\t\t\ttitle?: string;\n\t\t\t/**\n\t\t\t * Description\n\t\t\t *\n\t\t\t * @default \"Better Call Open API Reference\"\n\t\t\t */\n\t\t\tdescription?: string;\n\t\t\t/**\n\t\t\t * Logo URL\n\t\t\t */\n\t\t\tlogo?: string;\n\t\t\t/**\n\t\t\t * Scalar theme\n\t\t\t * @default \"saturn\"\n\t\t\t */\n\t\t\ttheme?: string;\n\t\t};\n\t};\n}\n\nexport const createRouter = <\n\tE extends Record,\n\tConfig extends RouterConfig,\n>(\n\tendpoints: E,\n\tconfig?: Config,\n) => {\n\tif (!config?.openapi?.disabled) {\n\t\tconst openapi = {\n\t\t\tpath: \"/api/reference\",\n\t\t\t...config?.openapi,\n\t\t};\n\t\t//@ts-expect-error\n\t\tendpoints[\"openapi\"] = createEndpoint(\n\t\t\topenapi.path,\n\t\t\t{\n\t\t\t\tmethod: \"GET\",\n\t\t\t},\n\t\t\tasync (c) => {\n\t\t\t\tconst schema = await generator(endpoints);\n\t\t\t\treturn new Response(getHTML(schema, openapi.scalar), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t}\n\tconst router = createRou3Router();\n\tconst middlewareRouter = createRou3Router();\n\n\tfor (const endpoint of Object.values(endpoints)) {\n\t\tif (!endpoint.options || !endpoint.path) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (endpoint.options?.metadata?.SERVER_ONLY) continue;\n\n\t\tconst methods = Array.isArray(endpoint.options?.method)\n\t\t\t? endpoint.options.method\n\t\t\t: [endpoint.options?.method];\n\n\t\tfor (const method of methods) {\n\t\t\taddRoute(router, method, endpoint.path, endpoint);\n\t\t}\n\t}\n\n\tif (config?.routerMiddleware?.length) {\n\t\tfor (const { path, middleware } of config.routerMiddleware) {\n\t\t\taddRoute(middlewareRouter, \"*\", path, middleware);\n\t\t}\n\t}\n\n\tconst processRequest = async (request: Request) => {\n\t\tconst url = new URL(request.url);\n\t\tconst pathname = url.pathname;\n\t\tconst path =\n\t\t\tconfig?.basePath && config.basePath !== \"/\"\n\t\t\t\t? pathname\n\t\t\t\t\t\t.split(config.basePath)\n\t\t\t\t\t\t.reduce((acc, curr, index) => {\n\t\t\t\t\t\t\tif (index !== 0) {\n\t\t\t\t\t\t\t\tif (index > 1) {\n\t\t\t\t\t\t\t\t\tacc.push(`${config.basePath}${curr}`);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tacc.push(curr);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t}, [] as string[])\n\t\t\t\t\t\t.join(\"\")\n\t\t\t\t: url.pathname;\n\t\tif (!path?.length) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\n\t\t// Reject paths with consecutive slashes\n\t\tif (/\\/{2,}/.test(path)) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\n\t\tconst route = findRoute(router, request.method, path) as {\n\t\t\tdata: Endpoint & { path: string };\n\t\t\tparams: Record;\n\t\t};\n\t\tconst hasTrailingSlash = path.endsWith(\"/\");\n\t\tconst routeHasTrailingSlash = route?.data?.path?.endsWith(\"/\");\n\n\t\t// If the path has a trailing slash and the route doesn't have a trailing slash and skipTrailingSlashes is not set, return 404\n\t\tif (\n\t\t\thasTrailingSlash !== routeHasTrailingSlash &&\n\t\t\t!config?.skipTrailingSlashes\n\t\t) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\t\tif (!route?.data)\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\n\t\tconst query: Record = {};\n\t\turl.searchParams.forEach((value, key) => {\n\t\t\tif (key in query) {\n\t\t\t\tif (Array.isArray(query[key])) {\n\t\t\t\t\t(query[key] as string[]).push(value);\n\t\t\t\t} else {\n\t\t\t\t\tquery[key] = [query[key] as string, value];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tquery[key] = value;\n\t\t\t}\n\t\t});\n\n\t\tconst handler = route.data as Endpoint;\n\n\t\ttry {\n\t\t\t// Determine which allowedMediaTypes to use: endpoint-level overrides router-level\n\t\t\tconst allowedMediaTypes =\n\t\t\t\thandler.options.metadata?.allowedMediaTypes ||\n\t\t\t\tconfig?.allowedMediaTypes;\n\t\t\tconst context = {\n\t\t\t\tpath,\n\t\t\t\tmethod: request.method as \"GET\",\n\t\t\t\theaders: request.headers,\n\t\t\t\tparams: route.params\n\t\t\t\t\t? (JSON.parse(JSON.stringify(route.params)) as any)\n\t\t\t\t\t: {},\n\t\t\t\trequest: request,\n\t\t\t\tbody: handler.options.disableBody\n\t\t\t\t\t? undefined\n\t\t\t\t\t: await getBody(\n\t\t\t\t\t\t\thandler.options.cloneRequest ? request.clone() : request,\n\t\t\t\t\t\t\tallowedMediaTypes,\n\t\t\t\t\t\t),\n\t\t\t\tquery,\n\t\t\t\t_flag: \"router\" as const,\n\t\t\t\tasResponse: true,\n\t\t\t\tcontext: config?.routerContext,\n\t\t\t};\n\t\t\tconst middlewareRoutes = findAllRoutes(middlewareRouter, \"*\", path);\n\t\t\tif (middlewareRoutes?.length) {\n\t\t\t\tfor (const { data: middleware, params } of middlewareRoutes) {\n\t\t\t\t\tconst res = await (middleware as Endpoint)({\n\t\t\t\t\t\t...context,\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tasResponse: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (res instanceof Response) return res;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst response = (await handler(context)) as Response;\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tif (config?.onError) {\n\t\t\t\ttry {\n\t\t\t\t\tconst errorResponse = await config.onError(error, request);\n\n\t\t\t\t\tif (errorResponse instanceof Response) {\n\t\t\t\t\t\treturn toResponse(errorResponse);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isAPIError(error)) {\n\t\t\t\t\t\treturn toResponse(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (config?.throwError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isAPIError(error)) {\n\t\t\t\treturn toResponse(error);\n\t\t\t}\n\n\t\t\tconsole.error(`# SERVER_ERROR: `, error);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: \"Internal Server Error\",\n\t\t\t});\n\t\t}\n\t};\n\n\treturn {\n\t\thandler: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = isRequest(onReq) ? onReq : request;\n\t\t\tconst res = await processRequest(req);\n\t\t\tconst onRes = await config?.onResponse?.(res, req);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType;\n", "import { runWithEndpointContext } from \"../context/endpoint-context.mjs\";\nimport { createEndpoint, createMiddleware } from \"better-call\";\n//#region src/api/index.ts\nconst optionsMiddleware = createMiddleware(async () => {\n\t/**\n\t* This will be passed on the instance of\n\t* the context. Used to infer the type\n\t* here.\n\t*/\n\treturn {};\n});\nconst createAuthMiddleware = createMiddleware.create({ use: [optionsMiddleware, createMiddleware(async () => {\n\treturn {};\n})] });\nconst use = [optionsMiddleware];\nfunction createAuthEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) {\n\tconst path = typeof pathOrOptions === \"string\" ? pathOrOptions : void 0;\n\tconst options = typeof handlerOrOptions === \"object\" ? handlerOrOptions : pathOrOptions;\n\tconst handler = typeof handlerOrOptions === \"function\" ? handlerOrOptions : handlerOrNever;\n\tif (path) return createEndpoint(path, {\n\t\t...options,\n\t\tuse: [...options?.use || [], ...use]\n\t}, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));\n\treturn createEndpoint({\n\t\t...options,\n\t\tuse: [...options?.use || [], ...use]\n\t}, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));\n}\n//#endregion\nexport { createAuthEndpoint, createAuthMiddleware, optionsMiddleware };\n", "import { wildcardMatch } from \"../utils/wildcard.mjs\";\nimport { getHost, getOrigin, getProtocol } from \"../utils/url.mjs\";\n//#region src/auth/trusted-origins.ts\n/**\n* Matches the given url against an origin or origin pattern\n* See \"options.trustedOrigins\" for details of supported patterns\n*\n* @param url The url to test\n* @param pattern The origin pattern\n* @param [settings] Specify supported pattern matching settings\n* @returns {boolean} true if the URL matches the origin pattern, false otherwise.\n*/\nconst matchesOriginPattern = (url, pattern, settings) => {\n\tif (url.startsWith(\"/\")) {\n\t\tif (settings?.allowRelativePaths) return url.startsWith(\"/\") && /^\\/(?!\\/|\\\\|%2f|%5c)[\\w\\-.\\+/@]*(?:\\?[\\w\\-.\\+/=&%@]*)?$/.test(url);\n\t\treturn false;\n\t}\n\tif (pattern.includes(\"*\") || pattern.includes(\"?\")) {\n\t\tif (pattern.includes(\"://\")) return wildcardMatch(pattern)(getOrigin(url) || url);\n\t\tconst host = getHost(url);\n\t\tif (!host) return false;\n\t\treturn wildcardMatch(pattern)(host);\n\t}\n\tconst protocol = getProtocol(url);\n\treturn protocol === \"http:\" || protocol === \"https:\" || !protocol ? pattern === getOrigin(url) : url.startsWith(pattern);\n};\n//#endregion\nexport { matchesOriginPattern };\n", "import { matchesOriginPattern } from \"../../auth/trusted-origins.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { normalizePathname } from \"@better-auth/core/utils/url\";\nimport { createAuthMiddleware } from \"@better-auth/core/api\";\nimport { deprecate } from \"@better-auth/core/utils/deprecate\";\n//#region src/api/middlewares/origin-check.ts\n/**\n* Checks if CSRF should be skipped for backward compatibility.\n* Previously, disableOriginCheck also disabled CSRF checks.\n* This maintains that behavior when disableCSRFCheck isn't explicitly set.\n* Only triggers for skipOriginCheck === true, not for path arrays.\n*/\nfunction shouldSkipCSRFForBackwardCompat(ctx) {\n\treturn ctx.context.skipOriginCheck === true && ctx.context.options.advanced?.disableCSRFCheck === void 0;\n}\n/**\n* Checks if the origin check should be skipped for the current request.\n* Handles both boolean (skip all) and array (skip specific paths) configurations.\n*/\nfunction shouldSkipOriginCheck(ctx) {\n\tconst skipOriginCheck = ctx.context.skipOriginCheck;\n\tif (skipOriginCheck === true) return true;\n\tif (Array.isArray(skipOriginCheck) && ctx.request) try {\n\t\tconst basePath = new URL(ctx.context.baseURL).pathname;\n\t\tconst currentPath = normalizePathname(ctx.request.url, basePath);\n\t\treturn skipOriginCheck.some((skipPath) => currentPath.startsWith(skipPath));\n\t} catch {}\n\treturn false;\n}\n/**\n* Logs deprecation warning for users relying on coupled behavior.\n* Only logs if user explicitly set disableOriginCheck (not test environment default).\n*/\nconst logBackwardCompatWarning = deprecate(function logBackwardCompatWarning() {}, \"disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config.\");\n/**\n* A middleware to validate callbackURL and origin against trustedOrigins.\n* Also handles CSRF protection using Fetch Metadata for first-login scenarios.\n*/\nconst originCheckMiddleware = createAuthMiddleware(async (ctx) => {\n\tif (ctx.request?.method === \"GET\" || ctx.request?.method === \"OPTIONS\" || ctx.request?.method === \"HEAD\" || !ctx.request) return;\n\tawait validateOrigin(ctx);\n\tif (shouldSkipOriginCheck(ctx)) return;\n\tconst { body, query } = ctx;\n\tconst callbackURL = body?.callbackURL || query?.callbackURL;\n\tconst redirectURL = body?.redirectTo;\n\tconst errorCallbackURL = body?.errorCallbackURL;\n\tconst newUserCallbackURL = body?.newUserCallbackURL;\n\tconst validateURL = (url, label) => {\n\t\tif (!url) return;\n\t\tif (!ctx.context.isTrustedOrigin(url, { allowRelativePaths: label !== \"origin\" })) {\n\t\t\tctx.context.logger.error(`Invalid ${label}: ${url}`);\n\t\t\tctx.context.logger.info(`If it's a valid URL, please add ${url} to trustedOrigins in your auth config\\n`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`);\n\t\t\tif (label === \"origin\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ORIGIN);\n\t\t\tif (label === \"callbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_CALLBACK_URL);\n\t\t\tif (label === \"redirectURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_REDIRECT_URL);\n\t\t\tif (label === \"errorCallbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);\n\t\t\tif (label === \"newUserCallbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);\n\t\t\tthrow APIError.fromStatus(\"FORBIDDEN\", { message: `Invalid ${label}` });\n\t\t}\n\t};\n\tcallbackURL && validateURL(callbackURL, \"callbackURL\");\n\tredirectURL && validateURL(redirectURL, \"redirectURL\");\n\terrorCallbackURL && validateURL(errorCallbackURL, \"errorCallbackURL\");\n\tnewUserCallbackURL && validateURL(newUserCallbackURL, \"newUserCallbackURL\");\n});\nconst originCheck = (getValue) => createAuthMiddleware(async (ctx) => {\n\tif (!ctx.request) return;\n\tif (shouldSkipOriginCheck(ctx)) return;\n\tconst callbackURL = getValue(ctx);\n\tconst validateURL = (url, label) => {\n\t\tif (!url) return;\n\t\tif (!ctx.context.isTrustedOrigin(url, { allowRelativePaths: label !== \"origin\" })) {\n\t\t\tctx.context.logger.error(`Invalid ${label}: ${url}`);\n\t\t\tctx.context.logger.info(`If it's a valid URL, please add ${url} to trustedOrigins in your auth config\\n`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`);\n\t\t\tif (label === \"origin\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ORIGIN);\n\t\t\tif (label === \"callbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_CALLBACK_URL);\n\t\t\tif (label === \"redirectURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_REDIRECT_URL);\n\t\t\tif (label === \"errorCallbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);\n\t\t\tif (label === \"newUserCallbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);\n\t\t\tthrow APIError.fromStatus(\"FORBIDDEN\", { message: `Invalid ${label}` });\n\t\t}\n\t};\n\tconst callbacks = Array.isArray(callbackURL) ? callbackURL : [callbackURL];\n\tfor (const url of callbacks) validateURL(url, \"callbackURL\");\n});\n/**\n* Validates origin header against trusted origins.\n* @param ctx - The endpoint context\n* @param forceValidate - If true, always validate origin regardless of cookies/skip flags\n*/\nasync function validateOrigin(ctx, forceValidate = false) {\n\tconst headers = ctx.request?.headers;\n\tif (!headers || !ctx.request) return;\n\tconst originHeader = headers.get(\"origin\") || headers.get(\"referer\") || \"\";\n\tconst useCookies = headers.has(\"cookie\");\n\tif (ctx.context.skipCSRFCheck) return;\n\tif (shouldSkipCSRFForBackwardCompat(ctx)) {\n\t\tctx.context.options.advanced?.disableOriginCheck === true && logBackwardCompatWarning();\n\t\treturn;\n\t}\n\tif (shouldSkipOriginCheck(ctx)) return;\n\tif (!(forceValidate || useCookies)) return;\n\tif (!originHeader || originHeader === \"null\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN);\n\tconst trustedOrigins = Array.isArray(ctx.context.options.trustedOrigins) ? ctx.context.trustedOrigins : [...ctx.context.trustedOrigins, ...(await ctx.context.options.trustedOrigins?.(ctx.request))?.filter((v) => Boolean(v)) || []];\n\tif (!trustedOrigins.some((origin) => matchesOriginPattern(originHeader, origin))) {\n\t\tctx.context.logger.error(`Invalid origin: ${originHeader}`);\n\t\tctx.context.logger.info(`If it's a valid URL, please add ${originHeader} to trustedOrigins in your auth config\\n`, `Current list of trustedOrigins: ${trustedOrigins}`);\n\t\tthrow APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ORIGIN);\n\t}\n}\n/**\n* Middleware for CSRF protection using Fetch Metadata headers.\n* This prevents cross-site navigation login attacks while supporting progressive enhancement.\n*/\nconst formCsrfMiddleware = createAuthMiddleware(async (ctx) => {\n\tif (!ctx.request) return;\n\tawait validateFormCsrf(ctx);\n});\n/**\n* Validates CSRF protection for first-login scenarios using Fetch Metadata headers.\n* This prevents cross-site form submission attacks while supporting progressive enhancement.\n*/\nasync function validateFormCsrf(ctx) {\n\tconst req = ctx.request;\n\tif (!req) return;\n\tif (ctx.context.skipCSRFCheck) return;\n\tif (shouldSkipCSRFForBackwardCompat(ctx)) return;\n\tconst headers = req.headers;\n\tif (headers.has(\"cookie\")) return await validateOrigin(ctx);\n\tconst site = headers.get(\"Sec-Fetch-Site\");\n\tconst mode = headers.get(\"Sec-Fetch-Mode\");\n\tconst dest = headers.get(\"Sec-Fetch-Dest\");\n\tif (Boolean(site && site.trim() || mode && mode.trim() || dest && dest.trim())) {\n\t\tif (site === \"cross-site\" && mode === \"navigate\") {\n\t\t\tctx.context.logger.error(\"Blocked cross-site navigation login attempt (CSRF protection)\", {\n\t\t\t\tsecFetchSite: site,\n\t\t\t\tsecFetchMode: mode,\n\t\t\t\tsecFetchDest: dest\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);\n\t\t}\n\t\treturn await validateOrigin(ctx, true);\n\t}\n}\n//#endregion\nexport { formCsrfMiddleware, originCheck, originCheckMiddleware };\n", "//#region src/utils/url.ts\n/**\n* Normalizes a request pathname by removing the basePath prefix and trailing slashes.\n* This is useful for matching paths against configured path lists.\n*\n* @param requestUrl - The full request URL\n* @param basePath - The base path of the auth API (e.g., \"/api/auth\")\n* @returns The normalized path without basePath prefix or trailing slashes,\n* or \"/\" if URL parsing fails\n*\n* @example\n* normalizePathname(\"http://localhost:3000/api/auth/sso/saml2/callback/provider1\", \"/api/auth\")\n* // Returns: \"/sso/saml2/callback/provider1\"\n*\n* normalizePathname(\"http://localhost:3000/sso/saml2/callback/provider1/\", \"/\")\n* // Returns: \"/sso/saml2/callback/provider1\"\n*/\nfunction normalizePathname(requestUrl, basePath) {\n\tlet pathname;\n\ttry {\n\t\tpathname = new URL(requestUrl).pathname.replace(/\\/+$/, \"\") || \"/\";\n\t} catch {\n\t\treturn \"/\";\n\t}\n\tif (basePath === \"/\" || basePath === \"\") return pathname;\n\tif (pathname === basePath) return \"/\";\n\tif (pathname.startsWith(basePath + \"/\")) return pathname.slice(basePath.length).replace(/\\/+$/, \"\") || \"/\";\n\treturn pathname;\n}\n//#endregion\nexport { normalizePathname };\n", "//#region src/utils/deprecate.ts\n/**\n* Wraps a function to log a deprecation warning at once.\n*/\nfunction deprecate(fn, message, logger) {\n\tlet warned = false;\n\treturn function(...args) {\n\t\tif (!warned) {\n\t\t\t(logger?.warn ?? console.warn)(`[Deprecation] ${message}`);\n\t\t\twarned = true;\n\t\t}\n\t\treturn fn.apply(this, args);\n\t};\n}\n//#endregion\nexport { deprecate };\n", "import { isDevelopment, isTest } from \"@better-auth/core/env\";\nimport { isValidIP, normalizeIP } from \"@better-auth/core/utils/ip\";\n//#region src/utils/get-request-ip.ts\nconst LOCALHOST_IP = \"127.0.0.1\";\nfunction getIp(req, options) {\n\tif (options.advanced?.ipAddress?.disableIpTracking) return null;\n\tconst headers = \"headers\" in req ? req.headers : req;\n\tconst ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || [\"x-forwarded-for\"];\n\tfor (const key of ipHeaders) {\n\t\tconst value = \"get\" in headers ? headers.get(key) : headers[key];\n\t\tif (typeof value === \"string\") {\n\t\t\tconst ip = value.split(\",\")[0].trim();\n\t\t\tif (isValidIP(ip)) return normalizeIP(ip, { ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet });\n\t\t}\n\t}\n\tif (isTest() || isDevelopment()) return LOCALHOST_IP;\n\treturn null;\n}\n//#endregion\nexport { getIp };\n", "import * as z from \"zod\";\n//#region src/utils/ip.ts\n/**\n* Checks if an IP is valid IPv4 or IPv6\n*/\nfunction isValidIP(ip) {\n\treturn z.ipv4().safeParse(ip).success || z.ipv6().safeParse(ip).success;\n}\n/**\n* Checks if an IP is IPv6\n*/\nfunction isIPv6(ip) {\n\treturn z.ipv6().safeParse(ip).success;\n}\n/**\n* Converts IPv4-mapped IPv6 address to IPv4\n* e.g., \"::ffff:192.0.2.1\" -> \"192.0.2.1\"\n*/\nfunction extractIPv4FromMapped(ipv6) {\n\tconst lower = ipv6.toLowerCase();\n\tif (lower.startsWith(\"::ffff:\")) {\n\t\tconst ipv4Part = lower.substring(7);\n\t\tif (z.ipv4().safeParse(ipv4Part).success) return ipv4Part;\n\t}\n\tconst parts = ipv6.split(\":\");\n\tif (parts.length === 7 && parts[5]?.toLowerCase() === \"ffff\") {\n\t\tconst ipv4Part = parts[6];\n\t\tif (ipv4Part && z.ipv4().safeParse(ipv4Part).success) return ipv4Part;\n\t}\n\tif (lower.includes(\"::ffff:\") || lower.includes(\":ffff:\")) {\n\t\tconst groups = expandIPv6(ipv6);\n\t\tif (groups.length === 8 && groups[0] === \"0000\" && groups[1] === \"0000\" && groups[2] === \"0000\" && groups[3] === \"0000\" && groups[4] === \"0000\" && groups[5] === \"ffff\" && groups[6] && groups[7]) return `${Number.parseInt(groups[6].substring(0, 2), 16)}.${Number.parseInt(groups[6].substring(2, 4), 16)}.${Number.parseInt(groups[7].substring(0, 2), 16)}.${Number.parseInt(groups[7].substring(2, 4), 16)}`;\n\t}\n\treturn null;\n}\n/**\n* Expands a compressed IPv6 address to full form\n* e.g., \"2001:db8::1\" -> [\"2001\", \"0db8\", \"0000\", \"0000\", \"0000\", \"0000\", \"0000\", \"0001\"]\n*/\nfunction expandIPv6(ipv6) {\n\tif (ipv6.includes(\"::\")) {\n\t\tconst sides = ipv6.split(\"::\");\n\t\tconst left = sides[0] ? sides[0].split(\":\") : [];\n\t\tconst right = sides[1] ? sides[1].split(\":\") : [];\n\t\tconst missingGroups = 8 - left.length - right.length;\n\t\tconst zeros = Array(missingGroups).fill(\"0000\");\n\t\tconst paddedLeft = left.map((g) => g.padStart(4, \"0\"));\n\t\tconst paddedRight = right.map((g) => g.padStart(4, \"0\"));\n\t\treturn [\n\t\t\t...paddedLeft,\n\t\t\t...zeros,\n\t\t\t...paddedRight\n\t\t];\n\t}\n\treturn ipv6.split(\":\").map((g) => g.padStart(4, \"0\"));\n}\n/**\n* Normalizes an IPv6 address to canonical form\n* e.g., \"2001:DB8::1\" -> \"2001:0db8:0000:0000:0000:0000:0000:0001\"\n*/\nfunction normalizeIPv6(ipv6, subnetPrefix) {\n\tconst groups = expandIPv6(ipv6);\n\tif (subnetPrefix && subnetPrefix < 128) {\n\t\tlet bitsRemaining = subnetPrefix;\n\t\treturn groups.map((group) => {\n\t\t\tif (bitsRemaining <= 0) return \"0000\";\n\t\t\tif (bitsRemaining >= 16) {\n\t\t\t\tbitsRemaining -= 16;\n\t\t\t\treturn group;\n\t\t\t}\n\t\t\tconst masked = Number.parseInt(group, 16) & (65535 << 16 - bitsRemaining & 65535);\n\t\t\tbitsRemaining = 0;\n\t\t\treturn masked.toString(16).padStart(4, \"0\");\n\t\t}).join(\":\").toLowerCase();\n\t}\n\treturn groups.join(\":\").toLowerCase();\n}\n/**\n* Normalizes an IP address (IPv4 or IPv6) for consistent rate limiting.\n*\n* @param ip - The IP address to normalize\n* @param options - Normalization options\n* @returns Normalized IP address\n*\n* @example\n* normalizeIP(\"2001:DB8::1\")\n* // -> \"2001:0db8:0000:0000:0000:0000:0000:0000\"\n*\n* @example\n* normalizeIP(\"::ffff:192.0.2.1\")\n* // -> \"192.0.2.1\" (converted to IPv4)\n*\n* @example\n* normalizeIP(\"2001:db8::1\", { ipv6Subnet: 64 })\n* // -> \"2001:0db8:0000:0000:0000:0000:0000:0000\" (subnet /64)\n*/\nfunction normalizeIP(ip, options = {}) {\n\tif (z.ipv4().safeParse(ip).success) return ip.toLowerCase();\n\tif (!isIPv6(ip)) return ip.toLowerCase();\n\tconst ipv4 = extractIPv4FromMapped(ip);\n\tif (ipv4) return ipv4.toLowerCase();\n\treturn normalizeIPv6(ip, options.ipv6Subnet || 64);\n}\n/**\n* Creates a rate limit key from IP and path\n* Uses a separator to prevent collision attacks\n*\n* @param ip - The IP address (should be normalized)\n* @param path - The request path\n* @returns Rate limit key\n*/\nfunction createRateLimitKey(ip, path) {\n\treturn `${ip}|${path}`;\n}\n//#endregion\nexport { createRateLimitKey, isValidIP, normalizeIP };\n", "import { wildcardMatch } from \"../../utils/wildcard.mjs\";\nimport { getIp } from \"../../utils/get-request-ip.mjs\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { normalizePathname } from \"@better-auth/core/utils/url\";\nimport { createRateLimitKey } from \"@better-auth/core/utils/ip\";\n//#region src/api/rate-limiter/index.ts\nconst memory = /* @__PURE__ */ new Map();\nfunction shouldRateLimit(max, window, rateLimitData) {\n\tconst now = Date.now();\n\tconst windowInMs = window * 1e3;\n\treturn now - rateLimitData.lastRequest < windowInMs && rateLimitData.count >= max;\n}\nfunction rateLimitResponse(retryAfter) {\n\treturn new Response(JSON.stringify({ message: \"Too many requests. Please try again later.\" }), {\n\t\tstatus: 429,\n\t\tstatusText: \"Too Many Requests\",\n\t\theaders: { \"X-Retry-After\": retryAfter.toString() }\n\t});\n}\nfunction getRetryAfter(lastRequest, window) {\n\tconst now = Date.now();\n\tconst windowInMs = window * 1e3;\n\treturn Math.ceil((lastRequest + windowInMs - now) / 1e3);\n}\nfunction createDatabaseStorageWrapper(ctx) {\n\tconst model = \"rateLimit\";\n\tconst db = ctx.adapter;\n\treturn {\n\t\tget: async (key) => {\n\t\t\tconst data = (await db.findMany({\n\t\t\t\tmodel,\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"key\",\n\t\t\t\t\tvalue: key\n\t\t\t\t}]\n\t\t\t}))[0];\n\t\t\tif (typeof data?.lastRequest === \"bigint\") data.lastRequest = Number(data.lastRequest);\n\t\t\treturn data;\n\t\t},\n\t\tset: async (key, value, _update) => {\n\t\t\ttry {\n\t\t\t\tif (_update) await db.updateMany({\n\t\t\t\t\tmodel,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"key\",\n\t\t\t\t\t\tvalue: key\n\t\t\t\t\t}],\n\t\t\t\t\tupdate: {\n\t\t\t\t\t\tcount: value.count,\n\t\t\t\t\t\tlastRequest: value.lastRequest\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\telse await db.create({\n\t\t\t\t\tmodel,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tcount: value.count,\n\t\t\t\t\t\tlastRequest: value.lastRequest\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tctx.logger.error(\"Error setting rate limit\", e);\n\t\t\t}\n\t\t}\n\t};\n}\nfunction getRateLimitStorage(ctx, rateLimitSettings) {\n\tif (ctx.options.rateLimit?.customStorage) return ctx.options.rateLimit.customStorage;\n\tconst storage = ctx.rateLimit.storage;\n\tif (storage === \"secondary-storage\") return {\n\t\tget: async (key) => {\n\t\t\tconst data = await ctx.options.secondaryStorage?.get(key);\n\t\t\treturn data ? safeJSONParse(data) : null;\n\t\t},\n\t\tset: async (key, value, _update) => {\n\t\t\tconst ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10;\n\t\t\tawait ctx.options.secondaryStorage?.set?.(key, JSON.stringify(value), ttl);\n\t\t}\n\t};\n\telse if (storage === \"memory\") return {\n\t\tasync get(key) {\n\t\t\tconst entry = memory.get(key);\n\t\t\tif (!entry) return null;\n\t\t\tif (Date.now() >= entry.expiresAt) {\n\t\t\t\tmemory.delete(key);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn entry.data;\n\t\t},\n\t\tasync set(key, value, _update) {\n\t\t\tconst ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10;\n\t\t\tconst expiresAt = Date.now() + ttl * 1e3;\n\t\t\tmemory.set(key, {\n\t\t\t\tdata: value,\n\t\t\t\texpiresAt\n\t\t\t});\n\t\t}\n\t};\n\treturn createDatabaseStorageWrapper(ctx);\n}\nlet ipWarningLogged = false;\nasync function resolveRateLimitConfig(req, ctx) {\n\tconst basePath = new URL(ctx.baseURL).pathname;\n\tconst path = normalizePathname(req.url, basePath);\n\tlet currentWindow = ctx.rateLimit.window;\n\tlet currentMax = ctx.rateLimit.max;\n\tconst ip = getIp(req, ctx.options);\n\tif (!ip) {\n\t\tif (!ipWarningLogged) {\n\t\t\tctx.logger.warn(\"Rate limiting skipped: could not determine client IP address. Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed.\");\n\t\t\tipWarningLogged = true;\n\t\t}\n\t\treturn null;\n\t}\n\tconst key = createRateLimitKey(ip, path);\n\tconst specialRule = getDefaultSpecialRules().find((rule) => rule.pathMatcher(path));\n\tif (specialRule) {\n\t\tcurrentWindow = specialRule.window;\n\t\tcurrentMax = specialRule.max;\n\t}\n\tfor (const plugin of ctx.options.plugins || []) if (plugin.rateLimit) {\n\t\tconst matchedRule = plugin.rateLimit.find((rule) => rule.pathMatcher(path));\n\t\tif (matchedRule) {\n\t\t\tcurrentWindow = matchedRule.window;\n\t\t\tcurrentMax = matchedRule.max;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (ctx.rateLimit.customRules) {\n\t\tconst _path = Object.keys(ctx.rateLimit.customRules).find((p) => {\n\t\t\tif (p.includes(\"*\")) return wildcardMatch(p)(path);\n\t\t\treturn p === path;\n\t\t});\n\t\tif (_path) {\n\t\t\tconst customRule = ctx.rateLimit.customRules[_path];\n\t\t\tconst resolved = typeof customRule === \"function\" ? await customRule(req, {\n\t\t\t\twindow: currentWindow,\n\t\t\t\tmax: currentMax\n\t\t\t}) : customRule;\n\t\t\tif (resolved) {\n\t\t\t\tcurrentWindow = resolved.window;\n\t\t\t\tcurrentMax = resolved.max;\n\t\t\t}\n\t\t\tif (resolved === false) return null;\n\t\t}\n\t}\n\treturn {\n\t\tkey,\n\t\tcurrentWindow,\n\t\tcurrentMax\n\t};\n}\nasync function onRequestRateLimit(req, ctx) {\n\tif (!ctx.rateLimit.enabled) return;\n\tconst config = await resolveRateLimitConfig(req, ctx);\n\tif (!config) return;\n\tconst { key, currentWindow, currentMax } = config;\n\tconst data = await getRateLimitStorage(ctx, { window: currentWindow }).get(key);\n\tif (data && shouldRateLimit(currentMax, currentWindow, data)) return rateLimitResponse(getRetryAfter(data.lastRequest, currentWindow));\n}\nasync function onResponseRateLimit(req, ctx) {\n\tif (!ctx.rateLimit.enabled) return;\n\tconst config = await resolveRateLimitConfig(req, ctx);\n\tif (!config) return;\n\tconst { key, currentWindow } = config;\n\tconst storage = getRateLimitStorage(ctx, { window: currentWindow });\n\tconst data = await storage.get(key);\n\tconst now = Date.now();\n\tif (!data) await storage.set(key, {\n\t\tkey,\n\t\tcount: 1,\n\t\tlastRequest: now\n\t});\n\telse if (now - data.lastRequest > currentWindow * 1e3) await storage.set(key, {\n\t\t...data,\n\t\tcount: 1,\n\t\tlastRequest: now\n\t}, true);\n\telse await storage.set(key, {\n\t\t...data,\n\t\tcount: data.count + 1,\n\t\tlastRequest: now\n\t}, true);\n}\nfunction getDefaultSpecialRules() {\n\treturn [{\n\t\tpathMatcher(path) {\n\t\t\treturn path.startsWith(\"/sign-in\") || path.startsWith(\"/sign-up\") || path.startsWith(\"/change-password\") || path.startsWith(\"/change-email\");\n\t\t},\n\t\twindow: 10,\n\t\tmax: 3\n\t}, {\n\t\tpathMatcher(path) {\n\t\t\treturn path === \"/request-password-reset\" || path === \"/send-verification-email\" || path.startsWith(\"/forget-password\") || path === \"/email-otp/send-verification-otp\" || path === \"/email-otp/request-password-reset\";\n\t\t},\n\t\twindow: 60,\n\t\tmax: 3\n\t}];\n}\n//#endregion\nexport { onRequestRateLimit, onResponseRateLimit };\n", "import { defineRequestState } from \"@better-auth/core/context\";\n//#region src/api/state/should-session-refresh.ts\n/**\n* State for skipping session refresh\n*\n* In some cases, such as when using server-side rendering (SSR) or when dealing with\n* certain types of requests, it may be necessary to skip session refresh to prevent\n* potential inconsistencies between the session data in the database and the session\n* data stored in cookies.\n*/\nconst { get: getShouldSkipSessionRefresh, set: setShouldSkipSessionRefresh } = defineRequestState(() => false);\n//#endregion\nexport { getShouldSkipSessionRefresh, setShouldSkipSessionRefresh };\n", "import { isAPIError } from \"../../utils/is-api-error.mjs\";\nimport { getDate } from \"../../utils/date.mjs\";\nimport { parseSessionOutput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { symmetricDecodeJWT, verifyJWT } from \"../../crypto/jwt.mjs\";\nimport { getChunkedCookie, getSessionQuerySchema } from \"../../cookies/session-store.mjs\";\nimport { deleteSessionCookie, expireCookie, setCookieCache, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { getShouldSkipSessionRefresh } from \"../state/should-session-refresh.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { createAuthEndpoint, createAuthMiddleware } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\nimport { base64Url } from \"@better-auth/utils/base64\";\nimport { binary } from \"@better-auth/utils/binary\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\n//#region src/api/routes/session.ts\nconst getSession = () => createAuthEndpoint(\"/get-session\", {\n\tmethod: [\"GET\", \"POST\"],\n\toperationId: \"getSession\",\n\tquery: getSessionQuerySchema,\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\toperationId: \"getSession\",\n\t\tdescription: \"Get the current session\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tnullable: true,\n\t\t\t\tproperties: {\n\t\t\t\t\tsession: { $ref: \"#/components/schemas/Session\" },\n\t\t\t\t\tuser: { $ref: \"#/components/schemas/User\" }\n\t\t\t\t},\n\t\t\t\trequired: [\"session\", \"user\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst deferSessionRefresh = ctx.context.options.session?.deferSessionRefresh;\n\tconst isPostRequest = ctx.method === \"POST\";\n\tif (isPostRequest && !deferSessionRefresh) throw APIError.from(\"METHOD_NOT_ALLOWED\", BASE_ERROR_CODES.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);\n\ttry {\n\t\tconst sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);\n\t\tif (!sessionCookieToken) return null;\n\t\tconst sessionDataCookie = getChunkedCookie(ctx, ctx.context.authCookies.sessionData.name);\n\t\tlet sessionDataPayload = null;\n\t\tif (sessionDataCookie) {\n\t\t\tconst strategy = ctx.context.options.session?.cookieCache?.strategy || \"compact\";\n\t\t\tif (strategy === \"jwe\") {\n\t\t\t\tconst payload = await symmetricDecodeJWT(sessionDataCookie, ctx.context.secretConfig, \"better-auth-session\");\n\t\t\t\tif (payload && payload.session && payload.user) sessionDataPayload = {\n\t\t\t\t\tsession: {\n\t\t\t\t\t\tsession: payload.session,\n\t\t\t\t\t\tuser: payload.user,\n\t\t\t\t\t\tupdatedAt: payload.updatedAt,\n\t\t\t\t\t\tversion: payload.version\n\t\t\t\t\t},\n\t\t\t\t\texpiresAt: payload.exp ? payload.exp * 1e3 : Date.now()\n\t\t\t\t};\n\t\t\t\telse {\n\t\t\t\t\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\t\t\treturn ctx.json(null);\n\t\t\t\t}\n\t\t\t} else if (strategy === \"jwt\") {\n\t\t\t\tconst payload = await verifyJWT(sessionDataCookie, ctx.context.secret);\n\t\t\t\tif (payload && payload.session && payload.user) sessionDataPayload = {\n\t\t\t\t\tsession: {\n\t\t\t\t\t\tsession: payload.session,\n\t\t\t\t\t\tuser: payload.user,\n\t\t\t\t\t\tupdatedAt: payload.updatedAt,\n\t\t\t\t\t\tversion: payload.version\n\t\t\t\t\t},\n\t\t\t\t\texpiresAt: payload.exp ? payload.exp * 1e3 : Date.now()\n\t\t\t\t};\n\t\t\t\telse {\n\t\t\t\t\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\t\t\treturn ctx.json(null);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst parsed = safeJSONParse(binary.decode(base64Url.decode(sessionDataCookie)));\n\t\t\t\tif (parsed) if (await createHMAC(\"SHA-256\", \"base64urlnopad\").verify(ctx.context.secret, JSON.stringify({\n\t\t\t\t\t...parsed.session,\n\t\t\t\t\texpiresAt: parsed.expiresAt\n\t\t\t\t}), parsed.signature)) sessionDataPayload = parsed;\n\t\t\t\telse {\n\t\t\t\t\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\t\t\treturn ctx.json(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);\n\t\t/**\n\t\t* If session data is present in the cookie, check if it should be used or refreshed\n\t\t*/\n\t\tif (sessionDataPayload?.session && ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache) {\n\t\t\tconst session = sessionDataPayload.session;\n\t\t\tconst versionConfig = ctx.context.options.session?.cookieCache?.version;\n\t\t\tlet expectedVersion = \"1\";\n\t\t\tif (versionConfig) {\n\t\t\t\tif (typeof versionConfig === \"string\") expectedVersion = versionConfig;\n\t\t\t\telse if (typeof versionConfig === \"function\") {\n\t\t\t\t\tconst result = versionConfig(session.session, session.user);\n\t\t\t\t\texpectedVersion = result instanceof Promise ? await result : result;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((session.version || \"1\") !== expectedVersion) expireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\telse {\n\t\t\t\tconst cachedSessionExpiresAt = new Date(session.session.expiresAt);\n\t\t\t\tif (sessionDataPayload.expiresAt < Date.now() || cachedSessionExpiresAt < /* @__PURE__ */ new Date()) expireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\t\telse {\n\t\t\t\t\tconst cookieRefreshCache = ctx.context.sessionConfig.cookieRefreshCache;\n\t\t\t\t\tif (cookieRefreshCache === false) {\n\t\t\t\t\t\tctx.context.session = session;\n\t\t\t\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t\t\t...session.session,\n\t\t\t\t\t\t\texpiresAt: new Date(session.session.expiresAt),\n\t\t\t\t\t\t\tcreatedAt: new Date(session.session.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(session.session.updatedAt)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t\t\t...session.user,\n\t\t\t\t\t\t\tcreatedAt: new Date(session.user.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(session.user.updatedAt)\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\t\t\tuser: parsedUser\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst timeUntilExpiry = sessionDataPayload.expiresAt - Date.now();\n\t\t\t\t\tconst updateAge = cookieRefreshCache.updateAge * 1e3;\n\t\t\t\t\tconst shouldSkipSessionRefresh = await getShouldSkipSessionRefresh();\n\t\t\t\t\tif (timeUntilExpiry < updateAge && !shouldSkipSessionRefresh) {\n\t\t\t\t\t\tconst newExpiresAt = getDate(ctx.context.options.session?.cookieCache?.maxAge || 300, \"sec\");\n\t\t\t\t\t\tconst refreshedSession = {\n\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t...session.session,\n\t\t\t\t\t\t\t\texpiresAt: newExpiresAt\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tuser: session.user,\n\t\t\t\t\t\t\tupdatedAt: Date.now()\n\t\t\t\t\t\t};\n\t\t\t\t\t\tawait setCookieCache(ctx, refreshedSession, false);\n\t\t\t\t\t\tconst sessionTokenOptions = ctx.context.authCookies.sessionToken.attributes;\n\t\t\t\t\t\tconst sessionTokenMaxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn;\n\t\t\t\t\t\tawait ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, {\n\t\t\t\t\t\t\t...sessionTokenOptions,\n\t\t\t\t\t\t\tmaxAge: sessionTokenMaxAge\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst parsedRefreshedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t\t\t...refreshedSession.session,\n\t\t\t\t\t\t\texpiresAt: new Date(refreshedSession.session.expiresAt),\n\t\t\t\t\t\t\tcreatedAt: new Date(refreshedSession.session.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(refreshedSession.session.updatedAt)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst parsedRefreshedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t\t\t...refreshedSession.user,\n\t\t\t\t\t\t\tcreatedAt: new Date(refreshedSession.user.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(refreshedSession.user.updatedAt)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tctx.context.session = {\n\t\t\t\t\t\t\tsession: parsedRefreshedSession,\n\t\t\t\t\t\t\tuser: parsedRefreshedUser\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\t\tsession: parsedRefreshedSession,\n\t\t\t\t\t\t\tuser: parsedRefreshedUser\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t\t...session.session,\n\t\t\t\t\t\texpiresAt: new Date(session.session.expiresAt),\n\t\t\t\t\t\tcreatedAt: new Date(session.session.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(session.session.updatedAt)\n\t\t\t\t\t});\n\t\t\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t\t...session.user,\n\t\t\t\t\t\tcreatedAt: new Date(session.user.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(session.user.updatedAt)\n\t\t\t\t\t});\n\t\t\t\t\tctx.context.session = {\n\t\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\t\tuser: parsedUser\n\t\t\t\t\t};\n\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\t\tuser: parsedUser\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst session = await ctx.context.internalAdapter.findSession(sessionCookieToken);\n\t\tctx.context.session = session;\n\t\tif (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) {\n\t\t\tdeleteSessionCookie(ctx);\n\t\t\tif (session) {\n\t\t\t\t/**\n\t\t\t\t* if session expired clean up the session\n\t\t\t\t* Only delete on POST when deferSessionRefresh is enabled\n\t\t\t\t*/\n\t\t\t\tif (!deferSessionRefresh || isPostRequest) await ctx.context.internalAdapter.deleteSession(session.session.token);\n\t\t\t}\n\t\t\treturn ctx.json(null);\n\t\t}\n\t\t/**\n\t\t* We don't need to update the session if the user doesn't want to be remembered\n\t\t* or if the session refresh is disabled\n\t\t*/\n\t\tif (dontRememberMe || ctx.query?.disableRefresh) {\n\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedSession,\n\t\t\t\tuser: parsedUser\n\t\t\t});\n\t\t}\n\t\tconst expiresIn = ctx.context.sessionConfig.expiresIn;\n\t\tconst updateAge = ctx.context.sessionConfig.updateAge;\n\t\tconst shouldBeUpdated = session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3 <= Date.now();\n\t\tconst disableRefresh = ctx.query?.disableRefresh || ctx.context.options.session?.disableSessionRefresh;\n\t\tconst shouldSkipSessionRefresh = await getShouldSkipSessionRefresh();\n\t\tconst needsRefresh = shouldBeUpdated && !disableRefresh && !shouldSkipSessionRefresh;\n\t\t/**\n\t\t* When deferSessionRefresh is enabled and this is a GET request,\n\t\t* return the session without performing writes, but include needsRefresh flag\n\t\t*/\n\t\tif (deferSessionRefresh && !isPostRequest) {\n\t\t\tawait setCookieCache(ctx, session, !!dontRememberMe);\n\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedSession,\n\t\t\t\tuser: parsedUser,\n\t\t\t\tneedsRefresh\n\t\t\t});\n\t\t}\n\t\tif (needsRefresh) {\n\t\t\tconst updatedSession = await ctx.context.internalAdapter.updateSession(session.session.token, {\n\t\t\t\texpiresAt: getDate(ctx.context.sessionConfig.expiresIn, \"sec\"),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t\t});\n\t\t\tif (!updatedSession) {\n\t\t\t\t/**\n\t\t\t\t* Handle case where session update fails (e.g., concurrent deletion)\n\t\t\t\t*/\n\t\t\t\tdeleteSessionCookie(ctx);\n\t\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_GET_SESSION);\n\t\t\t}\n\t\t\tconst maxAge = (updatedSession.expiresAt.valueOf() - Date.now()) / 1e3;\n\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\tsession: updatedSession,\n\t\t\t\tuser: session.user\n\t\t\t}, false, { maxAge });\n\t\t\tconst parsedUpdatedSession = parseSessionOutput(ctx.context.options, updatedSession);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedUpdatedSession,\n\t\t\t\tuser: parsedUser\n\t\t\t});\n\t\t}\n\t\tawait setCookieCache(ctx, session, !!dontRememberMe);\n\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\treturn ctx.json({\n\t\t\tsession: parsedSession,\n\t\t\tuser: parsedUser\n\t\t});\n\t} catch (error) {\n\t\tif (isAPIError(error)) throw error;\n\t\tctx.context.logger.error(\"INTERNAL_SERVER_ERROR\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", BASE_ERROR_CODES.FAILED_TO_GET_SESSION);\n\t}\n});\nconst getSessionFromCtx = async (ctx, config) => {\n\tif (ctx.context.session) return ctx.context.session;\n\tconst session = await getSession()({\n\t\t...ctx,\n\t\tmethod: \"GET\",\n\t\tasResponse: false,\n\t\theaders: ctx.headers,\n\t\treturnHeaders: false,\n\t\treturnStatus: false,\n\t\tquery: {\n\t\t\t...config,\n\t\t\t...ctx.query\n\t\t}\n\t}).catch((e) => {\n\t\treturn null;\n\t});\n\tctx.context.session = session;\n\treturn session;\n};\n/**\n* The middleware forces the endpoint to require a valid session.\n*/\nconst sessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware forces the endpoint to require a valid session and ignores cookie cache.\n* This should be used for sensitive operations like password changes, account deletion, etc.\n* to ensure that revoked sessions cannot be used even if they're still cached in cookies.\n*/\nconst sensitiveSessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx, { disableCookieCache: true });\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware allows you to call the endpoint on the client if session is valid.\n* However, if called on the server, no session is required.\n*/\nconst requestOnlySessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session && (ctx.request || ctx.headers)) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware forces the endpoint to require a valid session,\n* as well as making sure the session is fresh before proceeding.\n*\n* Session freshness check will be skipped if the session config's freshAge\n* is set to 0\n*/\nconst freshSessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\tif (ctx.context.sessionConfig.freshAge !== 0) {\n\t\tconst createdAt = new Date(session.session.createdAt).getTime();\n\t\tconst freshAge = ctx.context.sessionConfig.freshAge * 1e3;\n\t\tif (Date.now() - createdAt >= freshAge) throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.SESSION_NOT_FRESH);\n\t}\n\treturn { session };\n});\n/**\n* user active sessions list\n*/\nconst listSessions = () => createAuthEndpoint(\"/list-sessions\", {\n\tmethod: \"GET\",\n\toperationId: \"listUserSessions\",\n\tuse: [sessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\toperationId: \"listUserSessions\",\n\t\tdescription: \"List all active sessions for the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: { $ref: \"#/components/schemas/Session\" }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\ttry {\n\t\tconst activeSessions = (await ctx.context.internalAdapter.listSessions(ctx.context.session.user.id, { onlyActiveSessions: true })).filter((session) => {\n\t\t\treturn session.expiresAt > /* @__PURE__ */ new Date();\n\t\t});\n\t\treturn ctx.json(activeSessions.map((session) => parseSessionOutput(ctx.context.options, session)));\n\t} catch (e) {\n\t\tctx.context.logger.error(e);\n\t\tthrow ctx.error(\"INTERNAL_SERVER_ERROR\");\n\t}\n});\n/**\n* revoke a single session\n*/\nconst revokeSession = createAuthEndpoint(\"/revoke-session\", {\n\tmethod: \"POST\",\n\tbody: z.object({ token: z.string().meta({ description: \"The token to revoke\" }) }),\n\tuse: [sensitiveSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke a single session\",\n\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\ttype: \"object\",\n\t\t\tproperties: { token: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tdescription: \"The token to revoke\"\n\t\t\t} },\n\t\t\trequired: [\"token\"]\n\t\t} } } },\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if the session was revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst token = ctx.body.token;\n\tif ((await ctx.context.internalAdapter.findSession(token))?.session.userId === ctx.context.session.user.id) try {\n\t\tawait ctx.context.internalAdapter.deleteSession(token);\n\t} catch (error) {\n\t\tctx.context.logger.error(error && typeof error === \"object\" && \"name\" in error ? error.name : \"\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\t\tmessage: \"Internal Server Error\",\n\t\t\tcode: \"INTERNAL_SERVER_ERROR\"\n\t\t});\n\t}\n\treturn ctx.json({ status: true });\n});\n/**\n* revoke all user sessions\n*/\nconst revokeSessions = createAuthEndpoint(\"/revoke-sessions\", {\n\tmethod: \"POST\",\n\tuse: [sensitiveSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke all sessions for the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if all sessions were revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\ttry {\n\t\tawait ctx.context.internalAdapter.deleteSessions(ctx.context.session.user.id);\n\t} catch (error) {\n\t\tctx.context.logger.error(error && typeof error === \"object\" && \"name\" in error ? error.name : \"\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\t\tmessage: \"Internal Server Error\",\n\t\t\tcode: \"INTERNAL_SERVER_ERROR\"\n\t\t});\n\t}\n\treturn ctx.json({ status: true });\n});\nconst revokeOtherSessions = createAuthEndpoint(\"/revoke-other-sessions\", {\n\tmethod: \"POST\",\n\trequireHeaders: true,\n\tuse: [sensitiveSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke all other sessions for the user except the current one\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if all other sessions were revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tif (!session.user) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\tconst otherSessions = (await ctx.context.internalAdapter.listSessions(session.user.id)).filter((session) => {\n\t\treturn session.expiresAt > /* @__PURE__ */ new Date();\n\t}).filter((session) => session.token !== ctx.context.session.session.token);\n\tawait Promise.all(otherSessions.map((session) => ctx.context.internalAdapter.deleteSession(session.token)));\n\treturn ctx.json({ status: true });\n});\n//#endregion\nexport { freshSessionMiddleware, getSession, getSessionFromCtx, listSessions, requestOnlySessionMiddleware, revokeOtherSessions, revokeSession, revokeSessions, sensitiveSessionMiddleware, sessionMiddleware };\n", "import { base64Url } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\n//#region src/db/verification-token-storage.ts\nconst defaultKeyHasher = async (identifier) => {\n\tconst hash = await createHash(\"SHA-256\").digest(new TextEncoder().encode(identifier));\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n};\nasync function processIdentifier(identifier, option) {\n\tif (!option || option === \"plain\") return identifier;\n\tif (option === \"hashed\") return defaultKeyHasher(identifier);\n\tif (typeof option === \"object\" && \"hash\" in option) return option.hash(identifier);\n\treturn identifier;\n}\nfunction getStorageOption(identifier, config) {\n\tif (!config) return;\n\tif (typeof config === \"object\" && \"default\" in config) {\n\t\tif (config.overrides) {\n\t\t\tfor (const [prefix, option] of Object.entries(config.overrides)) if (identifier.startsWith(prefix)) return option;\n\t\t}\n\t\treturn config.default;\n\t}\n\treturn config;\n}\n//#endregion\nexport { getStorageOption, processIdentifier };\n", "import { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID } from \"./attributes.mjs\";\nimport { withSpan } from \"./tracer.mjs\";\nexport { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID, withSpan };\n", "import { getCurrentAdapter, getCurrentAuthContext, queueAfterTransactionHook } from \"@better-auth/core/context\";\nimport { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_HOOK_TYPE, withSpan } from \"@better-auth/core/instrumentation\";\n//#region src/db/with-hooks.ts\nfunction getWithHooks(adapter, ctx) {\n\tconst hooksEntries = ctx.hooks;\n\tasync function createWithHooks(data, model, customCreateFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet actualData = data;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.create?.before;\n\t\t\tif (toRun) {\n\t\t\t\tconst result = await withSpan(`db create.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"create.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(actualData, context));\n\t\t\t\tif (result === false) return null;\n\t\t\t\tif (typeof result === \"object\" && \"data\" in result) actualData = {\n\t\t\t\t\t...actualData,\n\t\t\t\t\t...result.data\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tlet created = null;\n\t\tif (!customCreateFn || customCreateFn.executeMainFn) created = await (await getCurrentAdapter(adapter)).create({\n\t\t\tmodel,\n\t\t\tdata: actualData,\n\t\t\tforceAllowId: true\n\t\t});\n\t\tif (customCreateFn?.fn) created = await customCreateFn.fn(created ?? actualData);\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.create?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db create.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"create.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(created, context));\n\t\t\t});\n\t\t}\n\t\treturn created;\n\t}\n\tasync function updateWithHooks(data, where, model, customUpdateFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet actualData = data;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.update?.before;\n\t\t\tif (toRun) {\n\t\t\t\tconst result = await withSpan(`db update.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"update.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(data, context));\n\t\t\t\tif (result === false) return null;\n\t\t\t\tif (typeof result === \"object\" && \"data\" in result) actualData = {\n\t\t\t\t\t...actualData,\n\t\t\t\t\t...result.data\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null;\n\t\tconst updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).update({\n\t\t\tmodel,\n\t\t\tupdate: actualData,\n\t\t\twhere\n\t\t}) : customUpdated;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.update?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db update.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"update.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(updated, context));\n\t\t\t});\n\t\t}\n\t\treturn updated;\n\t}\n\tasync function updateManyWithHooks(data, where, model, customUpdateFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet actualData = data;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.update?.before;\n\t\t\tif (toRun) {\n\t\t\t\tconst result = await withSpan(`db updateMany.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"updateMany.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(data, context));\n\t\t\t\tif (result === false) return null;\n\t\t\t\tif (typeof result === \"object\" && \"data\" in result) actualData = {\n\t\t\t\t\t...actualData,\n\t\t\t\t\t...result.data\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null;\n\t\tconst updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).updateMany({\n\t\t\tmodel,\n\t\t\tupdate: actualData,\n\t\t\twhere\n\t\t}) : customUpdated;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.update?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db updateMany.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"updateMany.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(updated, context));\n\t\t\t});\n\t\t}\n\t\treturn updated;\n\t}\n\tasync function deleteWithHooks(where, model, customDeleteFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet entityToDelete = null;\n\t\ttry {\n\t\t\tentityToDelete = (await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tlimit: 1\n\t\t\t}))[0] || null;\n\t\t} catch {}\n\t\tif (entityToDelete) for (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.delete?.before;\n\t\t\tif (toRun) {\n\t\t\t\tif (await withSpan(`db delete.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"delete.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(entityToDelete, context)) === false) return null;\n\t\t\t}\n\t\t}\n\t\tconst customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null;\n\t\tconst deleted = (!customDeleteFn || customDeleteFn.executeMainFn) && entityToDelete ? await (await getCurrentAdapter(adapter)).delete({\n\t\t\tmodel,\n\t\t\twhere\n\t\t}) : customDeleted;\n\t\tif (entityToDelete) for (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.delete?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db delete.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"delete.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(entityToDelete, context));\n\t\t\t});\n\t\t}\n\t\treturn deleted;\n\t}\n\tasync function deleteManyWithHooks(where, model, customDeleteFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet entitiesToDelete = [];\n\t\ttry {\n\t\t\tentitiesToDelete = await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t});\n\t\t} catch {}\n\t\tfor (const entity of entitiesToDelete) for (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.delete?.before;\n\t\t\tif (toRun) {\n\t\t\t\tif (await withSpan(`db delete.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"delete.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(entity, context)) === false) return null;\n\t\t\t}\n\t\t}\n\t\tconst customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null;\n\t\tconst deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await (await getCurrentAdapter(adapter)).deleteMany({\n\t\t\tmodel,\n\t\t\twhere\n\t\t}) : customDeleted;\n\t\tfor (const entity of entitiesToDelete) for (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.delete?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db delete.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"delete.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(entity, context));\n\t\t\t});\n\t\t}\n\t\treturn deleted;\n\t}\n\treturn {\n\t\tcreateWithHooks,\n\t\tupdateWithHooks,\n\t\tupdateManyWithHooks,\n\t\tdeleteWithHooks,\n\t\tdeleteManyWithHooks\n\t};\n}\n//#endregion\nexport { getWithHooks };\n", "import { getIp } from \"../utils/get-request-ip.mjs\";\nimport { getDate } from \"../utils/date.mjs\";\nimport { getSessionDefaultFields, parseSessionOutput, parseUserOutput } from \"./schema.mjs\";\nimport { getStorageOption, processIdentifier } from \"./verification-token-storage.mjs\";\nimport { getWithHooks } from \"./with-hooks.mjs\";\nimport { getCurrentAdapter, getCurrentAuthContext, runWithTransaction } from \"@better-auth/core/context\";\nimport { generateId } from \"@better-auth/core/utils/id\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\n//#region src/db/internal-adapter.ts\nfunction getTTLSeconds(expiresAt, now = Date.now()) {\n\tconst expiresMs = typeof expiresAt === \"number\" ? expiresAt : expiresAt.getTime();\n\treturn Math.max(Math.floor((expiresMs - now) / 1e3), 0);\n}\nconst createInternalAdapter = (adapter, ctx) => {\n\tconst logger = ctx.logger;\n\tconst options = ctx.options;\n\tconst secondaryStorage = options.secondaryStorage;\n\tconst sessionExpiration = options.session?.expiresIn || 3600 * 24 * 7;\n\tconst { createWithHooks, updateWithHooks, updateManyWithHooks, deleteWithHooks, deleteManyWithHooks } = getWithHooks(adapter, ctx);\n\tasync function refreshUserSessions(user) {\n\t\tif (!secondaryStorage) return;\n\t\tconst listRaw = await secondaryStorage.get(`active-sessions-${user.id}`);\n\t\tif (!listRaw) return;\n\t\tconst now = Date.now();\n\t\tconst validSessions = (safeJSONParse(listRaw) || []).filter((s) => s.expiresAt > now);\n\t\tawait Promise.all(validSessions.map(async ({ token }) => {\n\t\t\tconst cached = await secondaryStorage.get(token);\n\t\t\tif (!cached) return;\n\t\t\tconst parsed = safeJSONParse(cached);\n\t\t\tif (!parsed) return;\n\t\t\tconst sessionTTL = getTTLSeconds(parsed.session.expiresAt, now);\n\t\t\tawait secondaryStorage.set(token, JSON.stringify({\n\t\t\t\tsession: parsed.session,\n\t\t\t\tuser\n\t\t\t}), Math.floor(sessionTTL));\n\t\t}));\n\t}\n\treturn {\n\t\tcreateOAuthUser: async (user, account) => {\n\t\t\treturn runWithTransaction(adapter, async () => {\n\t\t\t\tconst createdUser = await createWithHooks({\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\t...user\n\t\t\t\t}, \"user\", void 0);\n\t\t\t\treturn {\n\t\t\t\t\tuser: createdUser,\n\t\t\t\t\taccount: await createWithHooks({\n\t\t\t\t\t\t...account,\n\t\t\t\t\t\tuserId: createdUser.id,\n\t\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t\t\t\t}, \"account\", void 0)\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tcreateUser: async (user) => {\n\t\t\treturn await createWithHooks({\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...user,\n\t\t\t\temail: user.email?.toLowerCase()\n\t\t\t}, \"user\", void 0);\n\t\t},\n\t\tcreateAccount: async (account) => {\n\t\t\treturn await createWithHooks({\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...account\n\t\t\t}, \"account\", void 0);\n\t\t},\n\t\tlistSessions: async (userId, options) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst currentList = await secondaryStorage.get(`active-sessions-${userId}`);\n\t\t\t\tif (!currentList) return [];\n\t\t\t\tconst list = safeJSONParse(currentList) || [];\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst seenTokens = /* @__PURE__ */ new Set();\n\t\t\t\tconst sessions = [];\n\t\t\t\tfor (const { token, expiresAt } of list) {\n\t\t\t\t\tif (expiresAt <= now || seenTokens.has(token)) continue;\n\t\t\t\t\tseenTokens.add(token);\n\t\t\t\t\tconst data = await secondaryStorage.get(token);\n\t\t\t\t\tif (!data) continue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed = typeof data === \"string\" ? JSON.parse(data) : data;\n\t\t\t\t\t\tif (!parsed?.session) continue;\n\t\t\t\t\t\tsessions.push(parseSessionOutput(ctx.options, {\n\t\t\t\t\t\t\t...parsed.session,\n\t\t\t\t\t\t\texpiresAt: new Date(parsed.session.expiresAt)\n\t\t\t\t\t\t}));\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn sessions;\n\t\t\t}\n\t\t\treturn await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"session\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}, ...options?.onlyActiveSessions ? [{\n\t\t\t\t\tfield: \"expiresAt\",\n\t\t\t\t\tvalue: /* @__PURE__ */ new Date(),\n\t\t\t\t\toperator: \"gt\"\n\t\t\t\t}] : []]\n\t\t\t});\n\t\t},\n\t\tlistUsers: async (limit, offset, sortBy, where) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"user\",\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\tsortBy,\n\t\t\t\twhere\n\t\t\t});\n\t\t},\n\t\tcountTotalUsers: async (where) => {\n\t\t\tconst total = await (await getCurrentAdapter(adapter)).count({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere\n\t\t\t});\n\t\t\tif (typeof total === \"string\") return parseInt(total);\n\t\t\treturn total;\n\t\t},\n\t\tdeleteUser: async (userId) => {\n\t\t\tif (!secondaryStorage || options.session?.storeSessionInDatabase) await deleteManyWithHooks([{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"session\", void 0);\n\t\t\tawait deleteManyWithHooks([{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"account\", void 0);\n\t\t\tawait deleteWithHooks([{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"user\", void 0);\n\t\t},\n\t\tcreateSession: async (userId, dontRememberMe, override, overrideAll) => {\n\t\t\tconst headers = await (async () => {\n\t\t\t\tconst ctx = await getCurrentAuthContext().catch(() => null);\n\t\t\t\treturn ctx?.headers || ctx?.request?.headers;\n\t\t\t})();\n\t\t\tconst storeInDb = options.session?.storeSessionInDatabase;\n\t\t\tconst { id: _, ...rest } = override || {};\n\t\t\tlet sessionId;\n\t\t\tif (secondaryStorage && !storeInDb) {\n\t\t\t\tconst generatedId = ctx.generateId({ model: \"session\" });\n\t\t\t\tsessionId = generatedId !== false ? generatedId : generateId();\n\t\t\t}\n\t\t\tconst defaultAdditionalFields = getSessionDefaultFields(options);\n\t\t\tconst data = {\n\t\t\t\t...sessionId ? { id: sessionId } : {},\n\t\t\t\tipAddress: headers ? getIp(headers, options) || \"\" : \"\",\n\t\t\t\tuserAgent: headers?.get(\"user-agent\") || \"\",\n\t\t\t\t...rest,\n\t\t\t\texpiresAt: dontRememberMe ? getDate(3600 * 24, \"sec\") : getDate(sessionExpiration, \"sec\"),\n\t\t\t\tuserId,\n\t\t\t\ttoken: generateId(32),\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...defaultAdditionalFields,\n\t\t\t\t...overrideAll ? rest : {}\n\t\t\t};\n\t\t\treturn await createWithHooks(data, \"session\", secondaryStorage ? {\n\t\t\t\tfn: async (sessionData) => {\n\t\t\t\t\t/**\n\t\t\t\t\t* store the session token for the user\n\t\t\t\t\t* so we can retrieve it later for listing sessions\n\t\t\t\t\t*/\n\t\t\t\t\tconst currentList = await secondaryStorage.get(`active-sessions-${userId}`);\n\t\t\t\t\tlet list = [];\n\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\tif (currentList) {\n\t\t\t\t\t\tlist = safeJSONParse(currentList) || [];\n\t\t\t\t\t\tlist = list.filter((session) => session.expiresAt > now && session.token !== data.token);\n\t\t\t\t\t}\n\t\t\t\t\tconst sorted = [...list, {\n\t\t\t\t\t\ttoken: data.token,\n\t\t\t\t\t\texpiresAt: data.expiresAt.getTime()\n\t\t\t\t\t}].sort((a, b) => a.expiresAt - b.expiresAt);\n\t\t\t\t\tconst furthestSessionTTL = getTTLSeconds(sorted.at(-1)?.expiresAt ?? data.expiresAt.getTime(), now);\n\t\t\t\t\tif (furthestSessionTTL > 0) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(sorted), furthestSessionTTL);\n\t\t\t\t\tconst user = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\twhere: [{\n\t\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\t\tvalue: userId\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tconst sessionTTL = getTTLSeconds(data.expiresAt, now);\n\t\t\t\t\tif (sessionTTL > 0) await secondaryStorage.set(data.token, JSON.stringify({\n\t\t\t\t\t\tsession: sessionData,\n\t\t\t\t\t\tuser\n\t\t\t\t\t}), sessionTTL);\n\t\t\t\t\treturn sessionData;\n\t\t\t\t},\n\t\t\t\texecuteMainFn: storeInDb\n\t\t\t} : void 0);\n\t\t},\n\t\tfindSession: async (token) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst sessionStringified = await secondaryStorage.get(token);\n\t\t\t\tif (!sessionStringified && (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase)) return null;\n\t\t\t\tif (sessionStringified) {\n\t\t\t\t\tconst s = safeJSONParse(sessionStringified);\n\t\t\t\t\tif (!s) return null;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsession: parseSessionOutput(ctx.options, {\n\t\t\t\t\t\t\t...s.session,\n\t\t\t\t\t\t\texpiresAt: new Date(s.session.expiresAt),\n\t\t\t\t\t\t\tcreatedAt: new Date(s.session.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(s.session.updatedAt)\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tuser: parseUserOutput(ctx.options, {\n\t\t\t\t\t\t\t...s.user,\n\t\t\t\t\t\t\tcreatedAt: new Date(s.user.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(s.user.updatedAt)\n\t\t\t\t\t\t})\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst result = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"session\",\n\t\t\t\twhere: [{\n\t\t\t\t\tvalue: token,\n\t\t\t\t\tfield: \"token\"\n\t\t\t\t}],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { user, ...session } = result;\n\t\t\tif (!user) return null;\n\t\t\treturn {\n\t\t\t\tsession: parseSessionOutput(ctx.options, session),\n\t\t\t\tuser: parseUserOutput(ctx.options, user)\n\t\t\t};\n\t\t},\n\t\tfindSessions: async (sessionTokens, options) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst sessions = [];\n\t\t\t\tfor (const sessionToken of sessionTokens) {\n\t\t\t\t\tconst sessionStringified = await secondaryStorage.get(sessionToken);\n\t\t\t\t\tif (sessionStringified) try {\n\t\t\t\t\t\tconst s = typeof sessionStringified === \"string\" ? JSON.parse(sessionStringified) : sessionStringified;\n\t\t\t\t\t\tif (!s) return [];\n\t\t\t\t\t\tconst expiresAt = new Date(s.session.expiresAt);\n\t\t\t\t\t\tif (options?.onlyActiveSessions && expiresAt <= /* @__PURE__ */ new Date()) continue;\n\t\t\t\t\t\tconst session = {\n\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t...s.session,\n\t\t\t\t\t\t\t\texpiresAt: new Date(s.session.expiresAt)\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\t\t...s.user,\n\t\t\t\t\t\t\t\tcreatedAt: new Date(s.user.createdAt),\n\t\t\t\t\t\t\t\tupdatedAt: new Date(s.user.updatedAt)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsessions.push(session);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn sessions;\n\t\t\t}\n\t\t\tconst sessions = await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"session\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"token\",\n\t\t\t\t\tvalue: sessionTokens,\n\t\t\t\t\toperator: \"in\"\n\t\t\t\t}, ...options?.onlyActiveSessions ? [{\n\t\t\t\t\tfield: \"expiresAt\",\n\t\t\t\t\tvalue: /* @__PURE__ */ new Date(),\n\t\t\t\t\toperator: \"gt\"\n\t\t\t\t}] : []],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (!sessions.length) return [];\n\t\t\tif (sessions.some((session) => !session.user)) return [];\n\t\t\treturn sessions.map((_session) => {\n\t\t\t\tconst { user, ...session } = _session;\n\t\t\t\treturn {\n\t\t\t\t\tsession,\n\t\t\t\t\tuser\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tupdateSession: async (sessionToken, session) => {\n\t\t\treturn await updateWithHooks(session, [{\n\t\t\t\tfield: \"token\",\n\t\t\t\tvalue: sessionToken\n\t\t\t}], \"session\", secondaryStorage ? {\n\t\t\t\tasync fn(data) {\n\t\t\t\t\tconst currentSession = await secondaryStorage.get(sessionToken);\n\t\t\t\t\tif (!currentSession) return null;\n\t\t\t\t\tconst parsedSession = safeJSONParse(currentSession);\n\t\t\t\t\tif (!parsedSession) return null;\n\t\t\t\t\tconst mergedSession = {\n\t\t\t\t\t\t...parsedSession.session,\n\t\t\t\t\t\t...data,\n\t\t\t\t\t\texpiresAt: new Date(data.expiresAt ?? parsedSession.session.expiresAt),\n\t\t\t\t\t\tcreatedAt: new Date(parsedSession.session.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(data.updatedAt ?? parsedSession.session.updatedAt)\n\t\t\t\t\t};\n\t\t\t\t\tconst updatedSession = parseSessionOutput(ctx.options, mergedSession);\n\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\tconst expiresMs = new Date(updatedSession.expiresAt).getTime();\n\t\t\t\t\tconst sessionTTL = getTTLSeconds(expiresMs, now);\n\t\t\t\t\tif (sessionTTL > 0) {\n\t\t\t\t\t\tawait secondaryStorage.set(sessionToken, JSON.stringify({\n\t\t\t\t\t\t\tsession: updatedSession,\n\t\t\t\t\t\t\tuser: parsedSession.user\n\t\t\t\t\t\t}), sessionTTL);\n\t\t\t\t\t\tconst listKey = `active-sessions-${updatedSession.userId}`;\n\t\t\t\t\t\tconst listRaw = await secondaryStorage.get(listKey);\n\t\t\t\t\t\tconst sorted = (listRaw ? safeJSONParse(listRaw) || [] : []).filter((s) => s.token !== sessionToken && s.expiresAt > now).concat([{\n\t\t\t\t\t\t\ttoken: sessionToken,\n\t\t\t\t\t\t\texpiresAt: expiresMs\n\t\t\t\t\t\t}]).sort((a, b) => a.expiresAt - b.expiresAt);\n\t\t\t\t\t\tconst furthestSessionExp = sorted.at(-1)?.expiresAt;\n\t\t\t\t\t\tif (furthestSessionExp && furthestSessionExp > now) await secondaryStorage.set(listKey, JSON.stringify(sorted), getTTLSeconds(furthestSessionExp, now));\n\t\t\t\t\t\telse await secondaryStorage.delete(listKey);\n\t\t\t\t\t}\n\t\t\t\t\treturn updatedSession;\n\t\t\t\t},\n\t\t\t\texecuteMainFn: options.session?.storeSessionInDatabase\n\t\t\t} : void 0);\n\t\t},\n\t\tdeleteSession: async (token) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst data = await secondaryStorage.get(token);\n\t\t\t\tif (data) {\n\t\t\t\t\tconst { session } = safeJSONParse(data) ?? {};\n\t\t\t\t\tif (!session) {\n\t\t\t\t\t\tlogger.error(\"Session not found in secondary storage\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst userId = session.userId;\n\t\t\t\t\tconst currentList = await secondaryStorage.get(`active-sessions-${userId}`);\n\t\t\t\t\tif (currentList) {\n\t\t\t\t\t\tconst list = safeJSONParse(currentList) || [];\n\t\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\t\tconst filtered = list.filter((session) => session.expiresAt > now && session.token !== token);\n\t\t\t\t\t\tconst furthestSessionExp = filtered.sort((a, b) => a.expiresAt - b.expiresAt).at(-1)?.expiresAt;\n\t\t\t\t\t\tif (filtered.length > 0 && furthestSessionExp && furthestSessionExp > Date.now()) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(filtered), getTTLSeconds(furthestSessionExp, now));\n\t\t\t\t\t\telse await secondaryStorage.delete(`active-sessions-${userId}`);\n\t\t\t\t\t} else logger.error(\"Active sessions list not found in secondary storage\");\n\t\t\t\t}\n\t\t\t\tawait secondaryStorage.delete(token);\n\t\t\t\tif (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return;\n\t\t\t}\n\t\t\tawait deleteWithHooks([{\n\t\t\t\tfield: \"token\",\n\t\t\t\tvalue: token\n\t\t\t}], \"session\", void 0);\n\t\t},\n\t\tdeleteAccounts: async (userId) => {\n\t\t\tawait deleteManyWithHooks([{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"account\", void 0);\n\t\t},\n\t\tdeleteAccount: async (accountId) => {\n\t\t\tawait deleteWithHooks([{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: accountId\n\t\t\t}], \"account\", void 0);\n\t\t},\n\t\tdeleteSessions: async (userIdOrSessionTokens) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tif (typeof userIdOrSessionTokens === \"string\") {\n\t\t\t\t\tconst activeSession = await secondaryStorage.get(`active-sessions-${userIdOrSessionTokens}`);\n\t\t\t\t\tconst sessions = activeSession ? safeJSONParse(activeSession) : [];\n\t\t\t\t\tif (!sessions) return;\n\t\t\t\t\tfor (const session of sessions) await secondaryStorage.delete(session.token);\n\t\t\t\t\tawait secondaryStorage.delete(`active-sessions-${userIdOrSessionTokens}`);\n\t\t\t\t} else for (const sessionToken of userIdOrSessionTokens) if (await secondaryStorage.get(sessionToken)) await secondaryStorage.delete(sessionToken);\n\t\t\t\tif (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return;\n\t\t\t}\n\t\t\tawait deleteManyWithHooks([{\n\t\t\t\tfield: Array.isArray(userIdOrSessionTokens) ? \"token\" : \"userId\",\n\t\t\t\tvalue: userIdOrSessionTokens,\n\t\t\t\toperator: Array.isArray(userIdOrSessionTokens) ? \"in\" : void 0\n\t\t\t}], \"session\", void 0);\n\t\t},\n\t\tfindOAuthUser: async (email, accountId, providerId) => {\n\t\t\tconst account = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tvalue: accountId,\n\t\t\t\t\tfield: \"accountId\"\n\t\t\t\t}, {\n\t\t\t\t\tvalue: providerId,\n\t\t\t\t\tfield: \"providerId\"\n\t\t\t\t}],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (account) if (account.user) return {\n\t\t\t\tuser: account.user,\n\t\t\t\tlinkedAccount: account,\n\t\t\t\taccounts: [account]\n\t\t\t};\n\t\t\telse {\n\t\t\t\tconst user = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tvalue: email.toLowerCase(),\n\t\t\t\t\t\tfield: \"email\"\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (user) return {\n\t\t\t\t\tuser,\n\t\t\t\t\tlinkedAccount: account,\n\t\t\t\t\taccounts: [account]\n\t\t\t\t};\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst user = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tvalue: email.toLowerCase(),\n\t\t\t\t\t\tfield: \"email\"\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (user) return {\n\t\t\t\t\tuser,\n\t\t\t\t\tlinkedAccount: null,\n\t\t\t\t\taccounts: await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\t\t\tmodel: \"account\",\n\t\t\t\t\t\twhere: [{\n\t\t\t\t\t\t\tvalue: user.id,\n\t\t\t\t\t\t\tfield: \"userId\"\n\t\t\t\t\t\t}]\n\t\t\t\t\t}) || []\n\t\t\t\t};\n\t\t\t\telse return null;\n\t\t\t}\n\t\t},\n\t\tfindUserByEmail: async (email, options) => {\n\t\t\tconst result = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tvalue: email.toLowerCase(),\n\t\t\t\t\tfield: \"email\"\n\t\t\t\t}],\n\t\t\t\tjoin: { ...options?.includeAccounts ? { account: true } : {} }\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { account: accounts, ...user } = result;\n\t\t\treturn {\n\t\t\t\tuser,\n\t\t\t\taccounts: accounts ?? []\n\t\t\t};\n\t\t},\n\t\tfindUserById: async (userId) => {\n\t\t\tif (!userId) return null;\n\t\t\treturn await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tlinkAccount: async (account) => {\n\t\t\treturn await createWithHooks({\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...account\n\t\t\t}, \"account\", void 0);\n\t\t},\n\t\tupdateUser: async (userId, data) => {\n\t\t\tconst user = await updateWithHooks(data, [{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"user\", void 0);\n\t\t\tawait refreshUserSessions(user);\n\t\t\treturn user;\n\t\t},\n\t\tupdateUserByEmail: async (email, data) => {\n\t\t\tconst user = await updateWithHooks(data, [{\n\t\t\t\tfield: \"email\",\n\t\t\t\tvalue: email.toLowerCase()\n\t\t\t}], \"user\", void 0);\n\t\t\tawait refreshUserSessions(user);\n\t\t\treturn user;\n\t\t},\n\t\tupdatePassword: async (userId, password) => {\n\t\t\tawait updateManyWithHooks({ password }, [{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: userId\n\t\t\t}, {\n\t\t\t\tfield: \"providerId\",\n\t\t\t\tvalue: \"credential\"\n\t\t\t}], \"account\", void 0);\n\t\t},\n\t\tfindAccounts: async (userId) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindAccount: async (accountId) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"accountId\",\n\t\t\t\t\tvalue: accountId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindAccountByProviderId: async (accountId, providerId) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"accountId\",\n\t\t\t\t\tvalue: accountId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"providerId\",\n\t\t\t\t\tvalue: providerId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindAccountByUserId: async (userId) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tupdateAccount: async (id, data) => {\n\t\t\treturn await updateWithHooks(data, [{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: id\n\t\t\t}], \"account\", void 0);\n\t\t},\n\t\tcreateVerificationValue: async (data) => {\n\t\t\tconst storageOption = getStorageOption(data.identifier, options.verification?.storeIdentifier);\n\t\t\tconst storedIdentifier = await processIdentifier(data.identifier, storageOption);\n\t\t\treturn await createWithHooks({\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...data,\n\t\t\t\tidentifier: storedIdentifier\n\t\t\t}, \"verification\", secondaryStorage ? {\n\t\t\t\tasync fn(verificationData) {\n\t\t\t\t\tconst ttl = getTTLSeconds(verificationData.expiresAt);\n\t\t\t\t\tif (ttl > 0) await secondaryStorage.set(`verification:${storedIdentifier}`, JSON.stringify(verificationData), ttl);\n\t\t\t\t\treturn verificationData;\n\t\t\t\t},\n\t\t\t\texecuteMainFn: options.verification?.storeInDatabase\n\t\t\t} : void 0);\n\t\t},\n\t\tfindVerificationValue: async (identifier) => {\n\t\t\tconst storageOption = getStorageOption(identifier, options.verification?.storeIdentifier);\n\t\t\tconst storedIdentifier = await processIdentifier(identifier, storageOption);\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst cached = await secondaryStorage.get(`verification:${storedIdentifier}`);\n\t\t\t\tif (cached) {\n\t\t\t\t\tconst parsed = safeJSONParse(cached);\n\t\t\t\t\tif (parsed) return parsed;\n\t\t\t\t}\n\t\t\t\tif (storageOption && storageOption !== \"plain\") {\n\t\t\t\t\tconst plainCached = await secondaryStorage.get(`verification:${identifier}`);\n\t\t\t\t\tif (plainCached) {\n\t\t\t\t\t\tconst parsed = safeJSONParse(plainCached);\n\t\t\t\t\t\tif (parsed) return parsed;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!options.verification?.storeInDatabase) return null;\n\t\t\t}\n\t\t\tconst currentAdapter = await getCurrentAdapter(adapter);\n\t\t\tasync function findByIdentifier(id) {\n\t\t\t\treturn currentAdapter.findMany({\n\t\t\t\t\tmodel: \"verification\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"identifier\",\n\t\t\t\t\t\tvalue: id\n\t\t\t\t\t}],\n\t\t\t\t\tsortBy: {\n\t\t\t\t\t\tfield: \"createdAt\",\n\t\t\t\t\t\tdirection: \"desc\"\n\t\t\t\t\t},\n\t\t\t\t\tlimit: 1\n\t\t\t\t});\n\t\t\t}\n\t\t\tlet verification = await findByIdentifier(storedIdentifier);\n\t\t\tif (!verification.length && storageOption && storageOption !== \"plain\") verification = await findByIdentifier(identifier);\n\t\t\tif (!options.verification?.disableCleanup) await deleteManyWithHooks([{\n\t\t\t\tfield: \"expiresAt\",\n\t\t\t\tvalue: /* @__PURE__ */ new Date(),\n\t\t\t\toperator: \"lt\"\n\t\t\t}], \"verification\", void 0);\n\t\t\treturn verification[0] || null;\n\t\t},\n\t\tdeleteVerificationByIdentifier: async (identifier) => {\n\t\t\tconst storedIdentifier = await processIdentifier(identifier, getStorageOption(identifier, options.verification?.storeIdentifier));\n\t\t\tif (secondaryStorage) await secondaryStorage.delete(`verification:${storedIdentifier}`);\n\t\t\tif (!secondaryStorage || options.verification?.storeInDatabase) await deleteWithHooks([{\n\t\t\t\tfield: \"identifier\",\n\t\t\t\tvalue: storedIdentifier\n\t\t\t}], \"verification\", void 0);\n\t\t},\n\t\tupdateVerificationByIdentifier: async (identifier, data) => {\n\t\t\tconst storedIdentifier = await processIdentifier(identifier, getStorageOption(identifier, options.verification?.storeIdentifier));\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst cached = await secondaryStorage.get(`verification:${storedIdentifier}`);\n\t\t\t\tif (cached) {\n\t\t\t\t\tconst parsed = safeJSONParse(cached);\n\t\t\t\t\tif (parsed) {\n\t\t\t\t\t\tconst updated = {\n\t\t\t\t\t\t\t...parsed,\n\t\t\t\t\t\t\t...data\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst expiresAt = updated.expiresAt ?? parsed.expiresAt;\n\t\t\t\t\t\tconst ttl = getTTLSeconds(expiresAt instanceof Date ? expiresAt : new Date(expiresAt));\n\t\t\t\t\t\tif (ttl > 0) await secondaryStorage.set(`verification:${storedIdentifier}`, JSON.stringify(updated), ttl);\n\t\t\t\t\t\tif (!options.verification?.storeInDatabase) return updated;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!secondaryStorage || options.verification?.storeInDatabase) return await updateWithHooks(data, [{\n\t\t\t\tfield: \"identifier\",\n\t\t\t\tvalue: storedIdentifier\n\t\t\t}], \"verification\", void 0);\n\t\t\treturn data;\n\t\t}\n\t};\n};\n//#endregion\nexport { createInternalAdapter };\n", "import { getBaseURL, isDynamicBaseURLConfig } from \"../utils/url.mjs\";\nimport { createInternalAdapter } from \"../db/internal-adapter.mjs\";\nimport { isPromise } from \"../utils/is-promise.mjs\";\nimport { env } from \"@better-auth/core/env\";\nimport { defu } from \"defu\";\n//#region src/context/helpers.ts\nasync function runPluginInit(context) {\n\tlet options = context.options;\n\tconst plugins = options.plugins || [];\n\tconst pluginTrustedOrigins = [];\n\tconst dbHooks = [];\n\tfor (const plugin of plugins) if (plugin.init) {\n\t\tconst initPromise = plugin.init(context);\n\t\tlet result;\n\t\tif (isPromise(initPromise)) result = await initPromise;\n\t\telse result = initPromise;\n\t\tif (typeof result === \"object\") {\n\t\t\tif (result.options) {\n\t\t\t\tconst { databaseHooks, trustedOrigins, ...restOpts } = result.options;\n\t\t\t\tif (databaseHooks) dbHooks.push({\n\t\t\t\t\tsource: `plugin:${plugin.id}`,\n\t\t\t\t\thooks: databaseHooks\n\t\t\t\t});\n\t\t\t\tif (trustedOrigins) pluginTrustedOrigins.push(trustedOrigins);\n\t\t\t\toptions = defu(options, restOpts);\n\t\t\t}\n\t\t\tif (result.context) Object.assign(context, result.context);\n\t\t}\n\t}\n\tif (pluginTrustedOrigins.length > 0) {\n\t\tconst allSources = [...options.trustedOrigins ? [options.trustedOrigins] : [], ...pluginTrustedOrigins];\n\t\tconst staticOrigins = allSources.filter(Array.isArray).flat();\n\t\tconst dynamicOrigins = allSources.filter((s) => typeof s === \"function\");\n\t\tif (dynamicOrigins.length > 0) options.trustedOrigins = async (request) => {\n\t\t\tconst resolved = await Promise.all(dynamicOrigins.map((fn) => fn(request)));\n\t\t\treturn [...staticOrigins, ...resolved.flat()].filter((v) => typeof v === \"string\" && v !== \"\");\n\t\t};\n\t\telse options.trustedOrigins = staticOrigins;\n\t}\n\tif (options.databaseHooks) dbHooks.push({\n\t\tsource: \"user\",\n\t\thooks: options.databaseHooks\n\t});\n\tcontext.internalAdapter = createInternalAdapter(context.adapter, {\n\t\toptions,\n\t\tlogger: context.logger,\n\t\thooks: dbHooks,\n\t\tgenerateId: context.generateId\n\t});\n\tcontext.options = options;\n}\nfunction getInternalPlugins(options) {\n\tconst plugins = [];\n\tif (options.advanced?.crossSubDomainCookies?.enabled) {}\n\treturn plugins;\n}\nasync function getTrustedOrigins(options, request) {\n\tconst trustedOrigins = [];\n\tif (isDynamicBaseURLConfig(options.baseURL)) {\n\t\tconst allowedHosts = options.baseURL.allowedHosts;\n\t\tfor (const host of allowedHosts) if (!host.includes(\"://\")) {\n\t\t\ttrustedOrigins.push(`https://${host}`);\n\t\t\tif (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) trustedOrigins.push(`http://${host}`);\n\t\t} else trustedOrigins.push(host);\n\t\tif (options.baseURL.fallback) try {\n\t\t\ttrustedOrigins.push(new URL(options.baseURL.fallback).origin);\n\t\t} catch {}\n\t} else {\n\t\tconst baseURL = getBaseURL(typeof options.baseURL === \"string\" ? options.baseURL : void 0, options.basePath, request);\n\t\tif (baseURL) trustedOrigins.push(new URL(baseURL).origin);\n\t}\n\tif (options.trustedOrigins) {\n\t\tif (Array.isArray(options.trustedOrigins)) trustedOrigins.push(...options.trustedOrigins);\n\t\tif (typeof options.trustedOrigins === \"function\") {\n\t\t\tconst validOrigins = await options.trustedOrigins(request);\n\t\t\ttrustedOrigins.push(...validOrigins);\n\t\t}\n\t}\n\tconst envTrustedOrigins = env.BETTER_AUTH_TRUSTED_ORIGINS;\n\tif (envTrustedOrigins) trustedOrigins.push(...envTrustedOrigins.split(\",\"));\n\treturn trustedOrigins.filter((v) => Boolean(v));\n}\nasync function getAwaitableValue(arr, item) {\n\tif (!arr) return void 0;\n\tfor (const val of arr) {\n\t\tconst value = typeof val === \"function\" ? await val() : val;\n\t\tif (value[item.field ?? \"id\"] === item.value) return value;\n\t}\n}\nasync function getTrustedProviders(options, request) {\n\tconst trustedProviders = options.account?.accountLinking?.trustedProviders;\n\tif (!trustedProviders) return [];\n\tif (Array.isArray(trustedProviders)) return trustedProviders.filter((v) => Boolean(v));\n\treturn (await trustedProviders(request) ?? []).filter((v) => Boolean(v));\n}\n//#endregion\nexport { getAwaitableValue, getInternalPlugins, getTrustedOrigins, getTrustedProviders, runPluginInit };\n", "function isPlainObject(value) {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {\n return false;\n }\n if (Symbol.iterator in value) {\n return false;\n }\n if (Symbol.toStringTag in value) {\n return Object.prototype.toString.call(value) === \"[object Module]\";\n }\n return true;\n}\n\nfunction _defu(baseObject, defaults, namespace = \".\", merger) {\n if (!isPlainObject(defaults)) {\n return _defu(baseObject, {}, namespace, merger);\n }\n const object = { ...defaults };\n for (const key of Object.keys(baseObject)) {\n if (key === \"__proto__\" || key === \"constructor\") {\n continue;\n }\n const value = baseObject[key];\n if (value === null || value === void 0) {\n continue;\n }\n if (merger && merger(object, key, value, namespace)) {\n continue;\n }\n if (Array.isArray(value) && Array.isArray(object[key])) {\n object[key] = [...value, ...object[key]];\n } else if (isPlainObject(value) && isPlainObject(object[key])) {\n object[key] = _defu(\n value,\n object[key],\n (namespace ? `${namespace}.` : \"\") + key.toString(),\n merger\n );\n } else {\n object[key] = value;\n }\n }\n return object;\n}\nfunction createDefu(merger) {\n return (...arguments_) => (\n // eslint-disable-next-line unicorn/no-array-reduce\n arguments_.reduce((p, c) => _defu(p, c, \"\", merger), {})\n );\n}\nconst defu = createDefu();\nconst defuFn = createDefu((object, key, currentValue) => {\n if (object[key] !== void 0 && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\nconst defuArrayFn = createDefu((object, key, currentValue) => {\n if (Array.isArray(object[key]) && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\n\nexport { createDefu, defu as default, defu, defuArrayFn, defuFn };\n", "import { symmetricDecrypt, symmetricEncrypt } from \"../crypto/index.mjs\";\n//#region src/oauth2/utils.ts\n/**\n* Check if a string looks like encrypted data\n*/\nfunction isLikelyEncrypted(token) {\n\tif (token.startsWith(\"$ba$\")) return true;\n\treturn token.length % 2 === 0 && /^[0-9a-f]+$/i.test(token);\n}\nfunction decryptOAuthToken(token, ctx) {\n\tif (!token) return token;\n\tif (ctx.options.account?.encryptOAuthTokens) {\n\t\tif (!isLikelyEncrypted(token)) return token;\n\t\treturn symmetricDecrypt({\n\t\t\tkey: ctx.secretConfig,\n\t\t\tdata: token\n\t\t});\n\t}\n\treturn token;\n}\nfunction setTokenUtil(token, ctx) {\n\tif (ctx.options.account?.encryptOAuthTokens && token) return symmetricEncrypt({\n\t\tkey: ctx.secretConfig,\n\t\tdata: token\n\t});\n\treturn token;\n}\n//#endregion\nexport { decryptOAuthToken, setTokenUtil };\n", "import { parseAccountOutput } from \"../../db/schema.mjs\";\nimport { getAwaitableValue } from \"../../context/helpers.mjs\";\nimport { getAccountCookie, setAccountCookie } from \"../../cookies/session-store.mjs\";\nimport { generateState } from \"../../oauth2/state.mjs\";\nimport { decryptOAuthToken, setTokenUtil } from \"../../oauth2/utils.mjs\";\nimport { freshSessionMiddleware, getSessionFromCtx, sessionMiddleware } from \"./session.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { SocialProviderListEnum } from \"@better-auth/core/social-providers\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/account.ts\nconst listUserAccounts = createAuthEndpoint(\"/list-accounts\", {\n\tmethod: \"GET\",\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: {\n\t\toperationId: \"listUserAccounts\",\n\t\tdescription: \"List all accounts linked to the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\tproviderId: { type: \"string\" },\n\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\taccountId: { type: \"string\" },\n\t\t\t\t\t\tuserId: { type: \"string\" },\n\t\t\t\t\t\tscopes: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" }\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"providerId\",\n\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\"updatedAt\",\n\t\t\t\t\t\t\"accountId\",\n\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\"scopes\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (c) => {\n\tconst session = c.context.session;\n\tconst accounts = await c.context.internalAdapter.findAccounts(session.user.id);\n\treturn c.json(accounts.map((a) => {\n\t\tconst { scope, ...parsed } = parseAccountOutput(c.context.options, a);\n\t\treturn {\n\t\t\t...parsed,\n\t\t\tscopes: scope?.split(\",\") || []\n\t\t};\n\t}));\n});\nconst linkSocialAccount = createAuthEndpoint(\"/link-social\", {\n\tmethod: \"POST\",\n\trequireHeaders: true,\n\tbody: z.object({\n\t\tcallbackURL: z.string().meta({ description: \"The URL to redirect to after the user has signed in\" }).optional(),\n\t\tprovider: SocialProviderListEnum,\n\t\tidToken: z.object({\n\t\t\ttoken: z.string(),\n\t\t\tnonce: z.string().optional(),\n\t\t\taccessToken: z.string().optional(),\n\t\t\trefreshToken: z.string().optional(),\n\t\t\tscopes: z.array(z.string()).optional()\n\t\t}).optional(),\n\t\trequestSignUp: z.boolean().optional(),\n\t\tscopes: z.array(z.string()).meta({ description: \"Additional scopes to request from the provider\" }).optional(),\n\t\terrorCallbackURL: z.string().meta({ description: \"The URL to redirect to if there is an error during the link process\" }).optional(),\n\t\tdisableRedirect: z.boolean().meta({ description: \"Disable automatic redirection to the provider. Useful for handling the redirection yourself\" }).optional(),\n\t\tadditionalData: z.record(z.string(), z.any()).optional()\n\t}),\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Link a social account to the user\",\n\t\toperationId: \"linkSocialAccount\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\turl: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The authorization URL to redirect the user to\"\n\t\t\t\t\t},\n\t\t\t\t\tredirect: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the user should be redirected to the authorization URL\"\n\t\t\t\t\t},\n\t\t\t\t\tstatus: { type: \"boolean\" }\n\t\t\t\t},\n\t\t\t\trequired: [\"redirect\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (c) => {\n\tconst session = c.context.session;\n\tconst provider = await getAwaitableValue(c.context.socialProviders, { value: c.body.provider });\n\tif (!provider) {\n\t\tc.context.logger.error(\"Provider not found. Make sure to add the provider in your auth config\", { provider: c.body.provider });\n\t\tthrow APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.PROVIDER_NOT_FOUND);\n\t}\n\tif (c.body.idToken) {\n\t\tif (!provider.verifyIdToken) {\n\t\t\tc.context.logger.error(\"Provider does not support id token verification\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);\n\t\t}\n\t\tconst { token, nonce } = c.body.idToken;\n\t\tif (!await provider.verifyIdToken(token, nonce)) {\n\t\t\tc.context.logger.error(\"Invalid id token\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_TOKEN);\n\t\t}\n\t\tconst linkingUserInfo = await provider.getUserInfo({\n\t\t\tidToken: token,\n\t\t\taccessToken: c.body.idToken.accessToken,\n\t\t\trefreshToken: c.body.idToken.refreshToken\n\t\t});\n\t\tif (!linkingUserInfo || !linkingUserInfo?.user) {\n\t\t\tc.context.logger.error(\"Failed to get user info\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);\n\t\t}\n\t\tconst linkingUserId = String(linkingUserInfo.user.id);\n\t\tif (!linkingUserInfo.user.email) {\n\t\t\tc.context.logger.error(\"User email not found\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);\n\t\t}\n\t\tif ((await c.context.internalAdapter.findAccounts(session.user.id)).find((a) => a.providerId === provider.id && a.accountId === linkingUserId)) return c.json({\n\t\t\turl: \"\",\n\t\t\tstatus: true,\n\t\t\tredirect: false\n\t\t});\n\t\tif (!c.context.trustedProviders.includes(provider.id) && !linkingUserInfo.user.emailVerified || c.context.options.account?.accountLinking?.enabled === false) throw APIError.from(\"UNAUTHORIZED\", {\n\t\t\tmessage: \"Account not linked - linking not allowed\",\n\t\t\tcode: \"LINKING_NOT_ALLOWED\"\n\t\t});\n\t\tif (linkingUserInfo.user.email?.toLowerCase() !== session.user.email.toLowerCase() && c.context.options.account?.accountLinking?.allowDifferentEmails !== true) throw APIError.from(\"UNAUTHORIZED\", {\n\t\t\tmessage: \"Account not linked - different emails not allowed\",\n\t\t\tcode: \"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED\"\n\t\t});\n\t\ttry {\n\t\t\tawait c.context.internalAdapter.createAccount({\n\t\t\t\tuserId: session.user.id,\n\t\t\t\tproviderId: provider.id,\n\t\t\t\taccountId: linkingUserId,\n\t\t\t\taccessToken: c.body.idToken.accessToken,\n\t\t\t\tidToken: token,\n\t\t\t\trefreshToken: c.body.idToken.refreshToken,\n\t\t\t\tscope: c.body.idToken.scopes?.join(\",\")\n\t\t\t});\n\t\t} catch (_e) {\n\t\t\tthrow APIError.from(\"EXPECTATION_FAILED\", {\n\t\t\t\tmessage: \"Account not linked - unable to create account\",\n\t\t\t\tcode: \"LINKING_FAILED\"\n\t\t\t});\n\t\t}\n\t\tif (c.context.options.account?.accountLinking?.updateUserInfoOnLink === true) try {\n\t\t\tawait c.context.internalAdapter.updateUser(session.user.id, {\n\t\t\t\tname: linkingUserInfo.user?.name,\n\t\t\t\timage: linkingUserInfo.user?.image\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.warn(\"Could not update user - \" + e.toString());\n\t\t}\n\t\treturn c.json({\n\t\t\turl: \"\",\n\t\t\tstatus: true,\n\t\t\tredirect: false\n\t\t});\n\t}\n\tconst state = await generateState(c, {\n\t\tuserId: session.user.id,\n\t\temail: session.user.email\n\t}, c.body.additionalData);\n\tconst url = await provider.createAuthorizationURL({\n\t\tstate: state.state,\n\t\tcodeVerifier: state.codeVerifier,\n\t\tredirectURI: `${c.context.baseURL}/callback/${provider.id}`,\n\t\tscopes: c.body.scopes\n\t});\n\tif (!c.body.disableRedirect) c.setHeader(\"Location\", url.toString());\n\treturn c.json({\n\t\turl: url.toString(),\n\t\tredirect: !c.body.disableRedirect\n\t});\n});\nconst unlinkAccount = createAuthEndpoint(\"/unlink-account\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tproviderId: z.string(),\n\t\taccountId: z.string().optional()\n\t}),\n\tuse: [freshSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Unlink an account\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst { providerId, accountId } = ctx.body;\n\tconst accounts = await ctx.context.internalAdapter.findAccounts(ctx.context.session.user.id);\n\tif (accounts.length === 1 && !ctx.context.options.account?.accountLinking?.allowUnlinkingAll) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT);\n\tconst accountExist = accounts.find((account) => accountId ? account.accountId === accountId && account.providerId === providerId : account.providerId === providerId);\n\tif (!accountExist) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);\n\tawait ctx.context.internalAdapter.deleteAccount(accountExist.id);\n\treturn ctx.json({ status: true });\n});\nconst getAccessToken = createAuthEndpoint(\"/get-access-token\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tproviderId: z.string().meta({ description: \"The provider ID for the OAuth provider\" }),\n\t\taccountId: z.string().meta({ description: \"The account ID associated with the refresh token\" }).optional(),\n\t\tuserId: z.string().meta({ description: \"The user ID associated with the account\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\tdescription: \"Get a valid access token, doing a refresh if needed\",\n\t\tresponses: {\n\t\t\t200: {\n\t\t\t\tdescription: \"A Valid access token\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttokenType: { type: \"string\" },\n\t\t\t\t\t\tidToken: { type: \"string\" },\n\t\t\t\t\t\taccessToken: { type: \"string\" },\n\t\t\t\t\t\taccessTokenExpiresAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} } }\n\t\t\t},\n\t\t\t400: { description: \"Invalid refresh token or provider configuration\" }\n\t\t}\n\t} }\n}, async (ctx) => {\n\tconst { providerId, accountId, userId } = ctx.body || {};\n\tconst req = ctx.request;\n\tconst session = await getSessionFromCtx(ctx);\n\tif (req && !session) throw ctx.error(\"UNAUTHORIZED\");\n\tconst resolvedUserId = session?.user?.id || userId;\n\tif (!resolvedUserId) throw ctx.error(\"UNAUTHORIZED\");\n\tconst provider = await getAwaitableValue(ctx.context.socialProviders, { value: providerId });\n\tif (!provider) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: `Provider ${providerId} is not supported.`,\n\t\tcode: \"PROVIDER_NOT_SUPPORTED\"\n\t});\n\tconst accountData = await getAccountCookie(ctx);\n\tlet account = void 0;\n\tif (accountData && accountData.userId === resolvedUserId && providerId === accountData.providerId && (!accountId || accountData.accountId === accountId)) account = accountData;\n\telse account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.accountId === accountId && acc.providerId === providerId : acc.providerId === providerId);\n\tif (!account) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);\n\ttry {\n\t\tlet newTokens = null;\n\t\tconst accessTokenExpired = account.accessTokenExpiresAt && new Date(account.accessTokenExpiresAt).getTime() - Date.now() < 5e3;\n\t\tif (account.refreshToken && accessTokenExpired && provider.refreshAccessToken) {\n\t\t\tconst refreshToken = await decryptOAuthToken(account.refreshToken, ctx.context);\n\t\t\tnewTokens = await provider.refreshAccessToken(refreshToken);\n\t\t\tconst updatedData = {\n\t\t\t\taccessToken: await setTokenUtil(newTokens?.accessToken, ctx.context),\n\t\t\t\taccessTokenExpiresAt: newTokens?.accessTokenExpiresAt,\n\t\t\t\trefreshToken: newTokens?.refreshToken ? await setTokenUtil(newTokens.refreshToken, ctx.context) : account.refreshToken,\n\t\t\t\trefreshTokenExpiresAt: newTokens?.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt,\n\t\t\t\tidToken: newTokens?.idToken || account.idToken\n\t\t\t};\n\t\t\tlet updatedAccount = null;\n\t\t\tif (account.id) updatedAccount = await ctx.context.internalAdapter.updateAccount(account.id, updatedData);\n\t\t\tif (ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, {\n\t\t\t\t...account,\n\t\t\t\t...updatedAccount ?? updatedData\n\t\t\t});\n\t\t}\n\t\tconst accessTokenExpiresAt = (() => {\n\t\t\tif (newTokens?.accessTokenExpiresAt) {\n\t\t\t\tif (typeof newTokens.accessTokenExpiresAt === \"string\") return new Date(newTokens.accessTokenExpiresAt);\n\t\t\t\treturn newTokens.accessTokenExpiresAt;\n\t\t\t}\n\t\t\tif (account.accessTokenExpiresAt) {\n\t\t\t\tif (typeof account.accessTokenExpiresAt === \"string\") return new Date(account.accessTokenExpiresAt);\n\t\t\t\treturn account.accessTokenExpiresAt;\n\t\t\t}\n\t\t})();\n\t\tconst tokens = {\n\t\t\taccessToken: newTokens?.accessToken ?? await decryptOAuthToken(account.accessToken ?? \"\", ctx.context),\n\t\t\taccessTokenExpiresAt,\n\t\t\tscopes: account.scope?.split(\",\") ?? [],\n\t\t\tidToken: newTokens?.idToken ?? account.idToken ?? void 0\n\t\t};\n\t\treturn ctx.json(tokens);\n\t} catch (_error) {\n\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Failed to get a valid access token\",\n\t\t\tcode: \"FAILED_TO_GET_ACCESS_TOKEN\"\n\t\t});\n\t}\n});\nconst refreshToken = createAuthEndpoint(\"/refresh-token\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tproviderId: z.string().meta({ description: \"The provider ID for the OAuth provider\" }),\n\t\taccountId: z.string().meta({ description: \"The account ID associated with the refresh token\" }).optional(),\n\t\tuserId: z.string().meta({ description: \"The user ID associated with the account\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\tdescription: \"Refresh the access token using a refresh token\",\n\t\tresponses: {\n\t\t\t200: {\n\t\t\t\tdescription: \"Access token refreshed successfully\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttokenType: { type: \"string\" },\n\t\t\t\t\t\tidToken: { type: \"string\" },\n\t\t\t\t\t\taccessToken: { type: \"string\" },\n\t\t\t\t\t\trefreshToken: { type: \"string\" },\n\t\t\t\t\t\taccessTokenExpiresAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\trefreshTokenExpiresAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} } }\n\t\t\t},\n\t\t\t400: { description: \"Invalid refresh token or provider configuration\" }\n\t\t}\n\t} }\n}, async (ctx) => {\n\tconst { providerId, accountId, userId } = ctx.body;\n\tconst req = ctx.request;\n\tconst session = await getSessionFromCtx(ctx);\n\tif (req && !session) throw ctx.error(\"UNAUTHORIZED\");\n\tconst resolvedUserId = session?.user?.id || userId;\n\tif (!resolvedUserId) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: `Either userId or session is required`,\n\t\tcode: \"USER_ID_OR_SESSION_REQUIRED\"\n\t});\n\tconst provider = await getAwaitableValue(ctx.context.socialProviders, { value: providerId });\n\tif (!provider) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: `Provider ${providerId} is not supported.`,\n\t\tcode: \"PROVIDER_NOT_SUPPORTED\"\n\t});\n\tif (!provider.refreshAccessToken) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: `Provider ${providerId} does not support token refreshing.`,\n\t\tcode: \"TOKEN_REFRESH_NOT_SUPPORTED\"\n\t});\n\tlet account = void 0;\n\tconst accountData = await getAccountCookie(ctx);\n\tif (accountData && accountData.userId === resolvedUserId && (!providerId || providerId === accountData?.providerId)) account = accountData;\n\telse account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.accountId === accountId && acc.providerId === providerId : acc.providerId === providerId);\n\tif (!account) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);\n\tlet refreshToken = void 0;\n\tif (accountData && providerId === accountData.providerId) refreshToken = accountData.refreshToken ?? void 0;\n\telse refreshToken = account.refreshToken ?? void 0;\n\tif (!refreshToken) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: \"Refresh token not found\",\n\t\tcode: \"REFRESH_TOKEN_NOT_FOUND\"\n\t});\n\ttry {\n\t\tconst decryptedRefreshToken = await decryptOAuthToken(refreshToken, ctx.context);\n\t\tconst tokens = await provider.refreshAccessToken(decryptedRefreshToken);\n\t\tconst resolvedRefreshToken = tokens.refreshToken ? await setTokenUtil(tokens.refreshToken, ctx.context) : refreshToken;\n\t\tconst resolvedRefreshTokenExpiresAt = tokens.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt;\n\t\tif (account.id) {\n\t\t\tconst updateData = {\n\t\t\t\t...account || {},\n\t\t\t\taccessToken: await setTokenUtil(tokens.accessToken, ctx.context),\n\t\t\t\trefreshToken: resolvedRefreshToken,\n\t\t\t\taccessTokenExpiresAt: tokens.accessTokenExpiresAt,\n\t\t\t\trefreshTokenExpiresAt: resolvedRefreshTokenExpiresAt,\n\t\t\t\tscope: tokens.scopes?.join(\",\") || account.scope,\n\t\t\t\tidToken: tokens.idToken || account.idToken\n\t\t\t};\n\t\t\tawait ctx.context.internalAdapter.updateAccount(account.id, updateData);\n\t\t}\n\t\tif (accountData && providerId === accountData.providerId && ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, {\n\t\t\t...accountData,\n\t\t\taccessToken: await setTokenUtil(tokens.accessToken, ctx.context),\n\t\t\trefreshToken: resolvedRefreshToken,\n\t\t\taccessTokenExpiresAt: tokens.accessTokenExpiresAt,\n\t\t\trefreshTokenExpiresAt: resolvedRefreshTokenExpiresAt,\n\t\t\tscope: tokens.scopes?.join(\",\") || accountData.scope,\n\t\t\tidToken: tokens.idToken || accountData.idToken\n\t\t});\n\t\treturn ctx.json({\n\t\t\taccessToken: tokens.accessToken,\n\t\t\trefreshToken: tokens.refreshToken ?? decryptedRefreshToken,\n\t\t\taccessTokenExpiresAt: tokens.accessTokenExpiresAt,\n\t\t\trefreshTokenExpiresAt: resolvedRefreshTokenExpiresAt,\n\t\t\tscope: tokens.scopes?.join(\",\") || account.scope,\n\t\t\tidToken: tokens.idToken || account.idToken,\n\t\t\tproviderId: account.providerId,\n\t\t\taccountId: account.accountId\n\t\t});\n\t} catch (_error) {\n\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Failed to refresh access token\",\n\t\t\tcode: \"FAILED_TO_REFRESH_ACCESS_TOKEN\"\n\t\t});\n\t}\n});\nconst accountInfoQuerySchema = z.optional(z.object({ accountId: z.string().meta({ description: \"The provider given account id for which to get the account info\" }).optional() }));\nconst accountInfo = createAuthEndpoint(\"/account-info\", {\n\tmethod: \"GET\",\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Get the account info provided by the provider\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tuser: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\t\t\temail: { type: \"string\" },\n\t\t\t\t\t\t\timage: { type: \"string\" },\n\t\t\t\t\t\t\temailVerified: { type: \"boolean\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"id\", \"emailVerified\"]\n\t\t\t\t\t},\n\t\t\t\t\tdata: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\tadditionalProperties: true\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"user\", \"data\"],\n\t\t\t\tadditionalProperties: false\n\t\t\t} } }\n\t\t} }\n\t} },\n\tquery: accountInfoQuerySchema\n}, async (ctx) => {\n\tconst providedAccountId = ctx.query?.accountId;\n\tlet account = void 0;\n\tif (!providedAccountId) {\n\t\tif (ctx.context.options.account?.storeAccountCookie) {\n\t\t\tconst accountData = await getAccountCookie(ctx);\n\t\t\tif (accountData) account = accountData;\n\t\t}\n\t} else {\n\t\tconst accountData = await ctx.context.internalAdapter.findAccount(providedAccountId);\n\t\tif (accountData) account = accountData;\n\t}\n\tif (!account || account.userId !== ctx.context.session.user.id) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);\n\tconst provider = await getAwaitableValue(ctx.context.socialProviders, { value: account.providerId });\n\tif (!provider) throw APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\tmessage: `Provider account provider is ${account.providerId} but it is not configured`,\n\t\tcode: \"PROVIDER_NOT_CONFIGURED\"\n\t});\n\tconst tokens = await getAccessToken({\n\t\t...ctx,\n\t\tmethod: \"POST\",\n\t\tbody: {\n\t\t\taccountId: account.accountId,\n\t\t\tproviderId: account.providerId\n\t\t},\n\t\treturnHeaders: false,\n\t\treturnStatus: false\n\t});\n\tif (!tokens.accessToken) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: \"Access token not found\",\n\t\tcode: \"ACCESS_TOKEN_NOT_FOUND\"\n\t});\n\tconst info = await provider.getUserInfo({\n\t\t...tokens,\n\t\taccessToken: tokens.accessToken\n\t});\n\treturn ctx.json(info);\n});\n//#endregion\nexport { accountInfo, getAccessToken, linkSocialAccount, listUserAccounts, refreshToken, unlinkAccount };\n", "import { APIError } from \"../error/index.mjs\";\nimport { createAuthorizationURL } from \"../oauth2/create-authorization-url.mjs\";\nimport { refreshAccessToken } from \"../oauth2/refresh-access-token.mjs\";\nimport { validateAuthorizationCode } from \"../oauth2/validate-authorization-code.mjs\";\nimport { betterFetch } from \"@better-fetch/fetch\";\nimport { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from \"jose\";\n//#region src/social-providers/apple.ts\nconst apple = (options) => {\n\tconst tokenEndpoint = \"https://appleid.apple.com/auth/token\";\n\treturn {\n\t\tid: \"apple\",\n\t\tname: \"Apple\",\n\t\tasync createAuthorizationURL({ state, scopes, redirectURI }) {\n\t\t\tconst _scope = options.disableDefaultScope ? [] : [\"email\", \"name\"];\n\t\t\tif (options.scope) _scope.push(...options.scope);\n\t\t\tif (scopes) _scope.push(...scopes);\n\t\t\treturn await createAuthorizationURL({\n\t\t\t\tid: \"apple\",\n\t\t\t\toptions,\n\t\t\t\tauthorizationEndpoint: \"https://appleid.apple.com/auth/authorize\",\n\t\t\t\tscopes: _scope,\n\t\t\t\tstate,\n\t\t\t\tredirectURI,\n\t\t\t\tresponseMode: \"form_post\",\n\t\t\t\tresponseType: \"code id_token\"\n\t\t\t});\n\t\t},\n\t\tvalidateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n\t\t\treturn validateAuthorizationCode({\n\t\t\t\tcode,\n\t\t\t\tcodeVerifier,\n\t\t\t\tredirectURI,\n\t\t\t\toptions,\n\t\t\t\ttokenEndpoint\n\t\t\t});\n\t\t},\n\t\tasync verifyIdToken(token, nonce) {\n\t\t\tif (options.disableIdTokenSignIn) return false;\n\t\t\tif (options.verifyIdToken) return options.verifyIdToken(token, nonce);\n\t\t\ttry {\n\t\t\t\tconst { kid, alg: jwtAlg } = decodeProtectedHeader(token);\n\t\t\t\tif (!kid || !jwtAlg) return false;\n\t\t\t\tconst { payload: jwtClaims } = await jwtVerify(token, await getApplePublicKey(kid), {\n\t\t\t\t\talgorithms: [jwtAlg],\n\t\t\t\t\tissuer: \"https://appleid.apple.com\",\n\t\t\t\t\taudience: options.audience && options.audience.length ? options.audience : options.appBundleIdentifier ? options.appBundleIdentifier : options.clientId,\n\t\t\t\t\tmaxTokenAge: \"1h\"\n\t\t\t\t});\n\t\t\t\t[\"email_verified\", \"is_private_email\"].forEach((field) => {\n\t\t\t\t\tif (jwtClaims[field] !== void 0) jwtClaims[field] = Boolean(jwtClaims[field]);\n\t\t\t\t});\n\t\t\t\tif (nonce && jwtClaims.nonce !== nonce) return false;\n\t\t\t\treturn !!jwtClaims;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t\trefreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n\t\t\treturn refreshAccessToken({\n\t\t\t\trefreshToken,\n\t\t\t\toptions,\n\t\t\t\ttokenEndpoint\n\t\t\t});\n\t\t},\n\t\tasync getUserInfo(token) {\n\t\t\tif (options.getUserInfo) return options.getUserInfo(token);\n\t\t\tif (!token.idToken) return null;\n\t\t\tconst profile = decodeJwt(token.idToken);\n\t\t\tif (!profile) return null;\n\t\t\tlet name;\n\t\t\tif (token.user?.name) name = `${token.user.name.firstName || \"\"} ${token.user.name.lastName || \"\"}`.trim();\n\t\t\telse name = profile.name || \"\";\n\t\t\tconst emailVerified = typeof profile.email_verified === \"boolean\" ? profile.email_verified : profile.email_verified === \"true\";\n\t\t\tconst enrichedProfile = {\n\t\t\t\t...profile,\n\t\t\t\tname\n\t\t\t};\n\t\t\tconst userMap = await options.mapProfileToUser?.(enrichedProfile);\n\t\t\treturn {\n\t\t\t\tuser: {\n\t\t\t\t\tid: profile.sub,\n\t\t\t\t\tname: enrichedProfile.name,\n\t\t\t\t\temailVerified,\n\t\t\t\t\temail: profile.email,\n\t\t\t\t\t...userMap\n\t\t\t\t},\n\t\t\t\tdata: enrichedProfile\n\t\t\t};\n\t\t},\n\t\toptions\n\t};\n};\nconst getApplePublicKey = async (kid) => {\n\tconst { data } = await betterFetch(`https://appleid.apple.com/auth/keys`);\n\tif (!data?.keys) throw new APIError(\"BAD_REQUEST\", { message: \"Keys not found\" });\n\tconst jwk = data.keys.find((key) => key.kid === kid);\n\tif (!jwk) throw new Error(`JWK with kid ${kid} not found`);\n\treturn await importJWK(jwk, jwk.alg);\n};\n//#endregion\nexport { apple, getApplePublicKey };\n", "import { base64Url } from \"@better-auth/utils/base64\";\n//#region src/oauth2/utils.ts\nfunction getOAuth2Tokens(data) {\n\tconst getDate = (seconds) => {\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\treturn new Date(now.getTime() + seconds * 1e3);\n\t};\n\treturn {\n\t\ttokenType: data.token_type,\n\t\taccessToken: data.access_token,\n\t\trefreshToken: data.refresh_token,\n\t\taccessTokenExpiresAt: data.expires_in ? getDate(data.expires_in) : void 0,\n\t\trefreshTokenExpiresAt: data.refresh_token_expires_in ? getDate(data.refresh_token_expires_in) : void 0,\n\t\tscopes: data?.scope ? typeof data.scope === \"string\" ? data.scope.split(\" \") : data.scope : [],\n\t\tidToken: data.id_token,\n\t\traw: data\n\t};\n}\nasync function generateCodeChallenge(codeVerifier) {\n\tconst data = new TextEncoder().encode(codeVerifier);\n\tconst hash = await crypto.subtle.digest(\"SHA-256\", data);\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n}\n//#endregion\nexport { generateCodeChallenge, getOAuth2Tokens };\n", "import { generateCodeChallenge } from \"./utils.mjs\";\n//#region src/oauth2/create-authorization-url.ts\nasync function createAuthorizationURL({ id, options, authorizationEndpoint, state, codeVerifier, scopes, claims, redirectURI, duration, prompt, accessType, responseType, display, loginHint, hd, responseMode, additionalParams, scopeJoiner }) {\n\toptions = typeof options === \"function\" ? await options() : options;\n\tconst url = new URL(options.authorizationEndpoint || authorizationEndpoint);\n\turl.searchParams.set(\"response_type\", responseType || \"code\");\n\tconst primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;\n\turl.searchParams.set(\"client_id\", primaryClientId);\n\turl.searchParams.set(\"state\", state);\n\tif (scopes) url.searchParams.set(\"scope\", scopes.join(scopeJoiner || \" \"));\n\turl.searchParams.set(\"redirect_uri\", options.redirectURI || redirectURI);\n\tduration && url.searchParams.set(\"duration\", duration);\n\tdisplay && url.searchParams.set(\"display\", display);\n\tloginHint && url.searchParams.set(\"login_hint\", loginHint);\n\tprompt && url.searchParams.set(\"prompt\", prompt);\n\thd && url.searchParams.set(\"hd\", hd);\n\taccessType && url.searchParams.set(\"access_type\", accessType);\n\tresponseMode && url.searchParams.set(\"response_mode\", responseMode);\n\tif (codeVerifier) {\n\t\tconst codeChallenge = await generateCodeChallenge(codeVerifier);\n\t\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\t\turl.searchParams.set(\"code_challenge\", codeChallenge);\n\t}\n\tif (claims) {\n\t\tconst claimsObj = claims.reduce((acc, claim) => {\n\t\t\tacc[claim] = null;\n\t\t\treturn acc;\n\t\t}, {});\n\t\turl.searchParams.set(\"claims\", JSON.stringify({ id_token: {\n\t\t\temail: null,\n\t\t\temail_verified: null,\n\t\t\t...claimsObj\n\t\t} }));\n\t}\n\tif (additionalParams) Object.entries(additionalParams).forEach(([key, value]) => {\n\t\turl.searchParams.set(key, value);\n\t});\n\treturn url;\n}\n//#endregion\nexport { createAuthorizationURL };\n", "export class BetterFetchError extends Error {\n\tconstructor(\n\t\tpublic status: number,\n\t\tpublic statusText: string,\n\t\tpublic error: any,\n\t) {\n\t\tsuper(statusText || status.toString(), {\n\t\t\tcause: error,\n\t\t});\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n", "import type { StandardSchemaV1 } from \"./standard-schema\";\nimport type { Schema } from \"./create-fetch\";\nimport type { BetterFetchError } from \"./error\";\nimport type { BetterFetchOption } from \"./types\";\n\nexport type RequestContext = any> = {\n\turl: URL | string;\n\theaders: Headers;\n\tbody: any;\n\tmethod: string;\n\tsignal: AbortSignal;\n} & BetterFetchOption;\nexport type ResponseContext = {\n\tresponse: Response;\n\trequest: RequestContext;\n};\nexport type SuccessContext = {\n\tdata: Res;\n\tresponse: Response;\n\trequest: RequestContext;\n};\nexport type ErrorContext = {\n\tresponse: Response;\n\trequest: RequestContext;\n\terror: BetterFetchError & Record;\n};\nexport interface FetchHooks {\n\t/**\n\t * a callback function that will be called when a\n\t * request is made.\n\t *\n\t * The returned context object will be reassigned to\n\t * the original request context.\n\t */\n\tonRequest?: >(\n\t\tcontext: RequestContext,\n\t) => Promise | RequestContext | void;\n\t/**\n\t * a callback function that will be called when\n\t * response is received. This will be called before\n\t * the response is parsed and returned.\n\t *\n\t * The returned response will be reassigned to the\n\t * original response if it's changed.\n\t */\n\tonResponse?: (\n\t\tcontext: ResponseContext,\n\t) =>\n\t\t| Promise\n\t\t| Response\n\t\t| ResponseContext\n\t\t| void;\n\t/**\n\t * a callback function that will be called when a\n\t * response is successful.\n\t */\n\tonSuccess?: (context: SuccessContext) => Promise | void;\n\t/**\n\t * a callback function that will be called when an\n\t * error occurs.\n\t */\n\tonError?: (context: ErrorContext) => Promise | void;\n\t/**\n\t * a callback function that will be called when a\n\t * request is retried.\n\t */\n\tonRetry?: (response: ResponseContext) => Promise | void;\n\t/**\n\t * Options for the hooks\n\t */\n\thookOptions?: {\n\t\t/**\n\t\t * Clone the response\n\t\t * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone\n\t\t */\n\t\tcloneResponse?: boolean;\n\t};\n}\n\n/**\n * A plugin that returns an id and hooks\n */\nexport type BetterFetchPlugin<\n\tExtraOptions extends Record = Record,\n> = {\n\t/**\n\t * A unique id for the plugin\n\t */\n\tid: string;\n\t/**\n\t * A name for the plugin\n\t */\n\tname: string;\n\t/**\n\t * A description for the plugin\n\t */\n\tdescription?: string;\n\t/**\n\t * A version for the plugin\n\t */\n\tversion?: string;\n\t/**\n\t * Hooks for the plugin\n\t */\n\thooks?: FetchHooks;\n\t/**\n\t * A function that will be called when the plugin is\n\t * initialized. This will be called before the any\n\t * of the other internal functions.\n\t *\n\t * The returned options will be merged with the\n\t * original options.\n\t */\n\tinit?: (\n\t\turl: string,\n\t\toptions?: BetterFetchOption & ExtraOptions,\n\t) =>\n\t\t| Promise<{\n\t\t\t\turl: string;\n\t\t\t\toptions?: BetterFetchOption;\n\t\t }>\n\t\t| {\n\t\t\t\turl: string;\n\t\t\t\toptions?: BetterFetchOption;\n\t\t };\n\t/**\n\t * A schema for the plugin\n\t */\n\tschema?: Schema;\n\t/**\n\t * Additional options that can be passed to the plugin\n\t *\n\t * @deprecated Use type inference through direct typescript instead\n\t * ```ts\n\t * const plugin = {\n\t *\n\t * } satisfies BetterFetchPlugin<{\n\t * myCustomOptions: string;\n\t * }>\n\t * ```\n\t */\n\tgetOptions?: () => StandardSchemaV1;\n};\n\nexport const initializePlugins = async (\n\turl: string,\n\toptions?: BetterFetchOption,\n) => {\n\tlet opts = options || {};\n\tconst hooks: {\n\t\tonRequest: Array;\n\t\tonResponse: Array;\n\t\tonSuccess: Array;\n\t\tonError: Array;\n\t\tonRetry: Array;\n\t} = {\n\t\tonRequest: [options?.onRequest],\n\t\tonResponse: [options?.onResponse],\n\t\tonSuccess: [options?.onSuccess],\n\t\tonError: [options?.onError],\n\t\tonRetry: [options?.onRetry],\n\t};\n\tif (!options || !options?.plugins) {\n\t\treturn {\n\t\t\turl,\n\t\t\toptions: opts,\n\t\t\thooks,\n\t\t};\n\t}\n\tfor (const plugin of options?.plugins || []) {\n\t\tif (plugin.init) {\n\t\t\tconst pluginRes = await plugin.init?.(url.toString(), options);\n\t\t\topts = pluginRes.options || opts;\n\t\t\turl = pluginRes.url;\n\t\t}\n\t\thooks.onRequest.push(plugin.hooks?.onRequest);\n\t\thooks.onResponse.push(plugin.hooks?.onResponse);\n\t\thooks.onSuccess.push(plugin.hooks?.onSuccess);\n\t\thooks.onError.push(plugin.hooks?.onError);\n\t\thooks.onRetry.push(plugin.hooks?.onRetry);\n\t}\n\n\treturn {\n\t\turl,\n\t\toptions: opts,\n\t\thooks,\n\t};\n};\n", "export type RetryCondition = (\n\tresponse: Response | null,\n) => boolean | Promise;\n\nexport type LinearRetry = {\n\ttype: \"linear\";\n\tattempts: number;\n\tdelay: number;\n\tshouldRetry?: RetryCondition;\n};\n\nexport type ExponentialRetry = {\n\ttype: \"exponential\";\n\tattempts: number;\n\tbaseDelay: number;\n\tmaxDelay: number;\n\tshouldRetry?: RetryCondition;\n};\n\nexport type RetryOptions = LinearRetry | ExponentialRetry | number;\n\nexport interface RetryStrategy {\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise;\n\tgetDelay(attempt: number): number;\n}\n\nclass LinearRetryStrategy implements RetryStrategy {\n\tconstructor(private options: LinearRetry) {}\n\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise {\n\t\tif (this.options.shouldRetry) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tattempt < this.options.attempts && this.options.shouldRetry(response),\n\t\t\t);\n\t\t}\n\t\treturn Promise.resolve(attempt < this.options.attempts);\n\t}\n\n\tgetDelay(): number {\n\t\treturn this.options.delay;\n\t}\n}\n\nclass ExponentialRetryStrategy implements RetryStrategy {\n\tconstructor(private options: ExponentialRetry) {}\n\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise {\n\t\tif (this.options.shouldRetry) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tattempt < this.options.attempts && this.options.shouldRetry(response),\n\t\t\t);\n\t\t}\n\t\treturn Promise.resolve(attempt < this.options.attempts);\n\t}\n\n\tgetDelay(attempt: number): number {\n\t\tconst delay = Math.min(\n\t\t\tthis.options.maxDelay,\n\t\t\tthis.options.baseDelay * 2 ** attempt,\n\t\t);\n\t\treturn delay;\n\t}\n}\n\nexport function createRetryStrategy(options: RetryOptions): RetryStrategy {\n\tif (typeof options === \"number\") {\n\t\treturn new LinearRetryStrategy({\n\t\t\ttype: \"linear\",\n\t\t\tattempts: options,\n\t\t\tdelay: 1000,\n\t\t});\n\t}\n\n\tswitch (options.type) {\n\t\tcase \"linear\":\n\t\t\treturn new LinearRetryStrategy(options);\n\t\tcase \"exponential\":\n\t\t\treturn new ExponentialRetryStrategy(options);\n\t\tdefault:\n\t\t\tthrow new Error(\"Invalid retry strategy\");\n\t}\n}\n", "import type { BetterFetchOption } from \"./types\";\n\nexport type typeOrTypeReturning = T | (() => T);\n/**\n * Bearer token authentication\n *\n * the value of `token` will be added to a header as\n * `auth: Bearer token`,\n */\nexport type Bearer = {\n\ttype: \"Bearer\";\n\ttoken: typeOrTypeReturning>;\n};\n\n/**\n * Basic auth\n */\nexport type Basic = {\n\ttype: \"Basic\";\n\tusername: typeOrTypeReturning;\n\tpassword: typeOrTypeReturning;\n};\n\n/**\n * Custom auth\n *\n * @param prefix - prefix of the header\n * @param value - value of the header\n *\n * @example\n * ```ts\n * {\n * type: \"Custom\",\n * prefix: \"Token\",\n * value: \"token\"\n * }\n * ```\n */\nexport type Custom = {\n\ttype: \"Custom\";\n\tprefix: typeOrTypeReturning;\n\tvalue: typeOrTypeReturning;\n};\n\nexport type Auth = Bearer | Basic | Custom;\n\nexport const getAuthHeader = async (options?: BetterFetchOption) => {\n\tconst headers: Record = {};\n\tconst getValue = async (\n\t\tvalue: typeOrTypeReturning<\n\t\t\tstring | undefined | Promise\n\t\t>,\n\t) => (typeof value === \"function\" ? await value() : value);\n\tif (options?.auth) {\n\t\tif (options.auth.type === \"Bearer\") {\n\t\t\tconst token = await getValue(options.auth.token);\n\t\t\tif (!token) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `Bearer ${token}`;\n\t\t} else if (options.auth.type === \"Basic\") {\n\t\t\tconst [username, password] = await Promise.all([\n\t\t\t\tgetValue(options.auth.username),\n\t\t\t\tgetValue(options.auth.password),\n\t\t\t]);\n\t\t\tif (!username || !password) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `Basic ${btoa(`${username}:${password}`)}`;\n\t\t} else if (options.auth.type === \"Custom\") {\n\t\t\tconst [prefix, value] = await Promise.all([\n\t\t\t\tgetValue(options.auth.prefix),\n\t\t\t\tgetValue(options.auth.value),\n\t\t\t]);\n\t\t\tif (!value) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `${prefix ?? \"\"} ${value}`;\n\t\t}\n\t}\n\treturn headers;\n};\n", "import type { StandardSchemaV1 } from \"./standard-schema\";\nimport { getAuthHeader } from \"./auth\";\nimport { methods } from \"./create-fetch\";\nimport type { BetterFetchOption, FetchEsque } from \"./types\";\n\nconst JSON_RE = /^application\\/(?:[\\w!#$%&*.^`~-]*\\+)?json(;.+)?$/i;\n\nexport type ResponseType = \"json\" | \"text\" | \"blob\";\nexport function detectResponseType(request: Response): ResponseType {\n\tconst _contentType = request.headers.get(\"content-type\");\n\tconst textTypes = new Set([\n\t\t\"image/svg\",\n\t\t\"application/xml\",\n\t\t\"application/xhtml\",\n\t\t\"application/html\",\n\t]);\n\tif (!_contentType) {\n\t\treturn \"json\";\n\t}\n\tconst contentType = _contentType.split(\";\").shift() || \"\";\n\tif (JSON_RE.test(contentType)) {\n\t\treturn \"json\";\n\t}\n\tif (textTypes.has(contentType) || contentType.startsWith(\"text/\")) {\n\t\treturn \"text\";\n\t}\n\treturn \"blob\";\n}\n\nexport function isJSONParsable(value: any) {\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn false;\n\t}\n}\n\n//https://github.com/unjs/ofetch/blob/main/src/utils.ts\nexport function isJSONSerializable(value: any) {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst t = typeof value;\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n\t\treturn true;\n\t}\n\tif (t !== \"object\") {\n\t\treturn false;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn true;\n\t}\n\tif (value.buffer) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t(value.constructor && value.constructor.name === \"Object\") ||\n\t\ttypeof value.toJSON === \"function\"\n\t);\n}\n\nexport function jsonParse(text: string) {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch (error) {\n\t\treturn text;\n\t}\n}\n\nexport function isFunction(value: any): value is () => any {\n\treturn typeof value === \"function\";\n}\n\nexport function getFetch(options?: BetterFetchOption): FetchEsque {\n\tif (options?.customFetchImpl) {\n\t\treturn options.customFetchImpl;\n\t}\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) {\n\t\treturn globalThis.fetch;\n\t}\n\tif (typeof window !== \"undefined\" && isFunction(window.fetch)) {\n\t\treturn window.fetch;\n\t}\n\tthrow new Error(\"No fetch implementation found\");\n}\n\nexport function isPayloadMethod(method?: string) {\n\tif (!method) {\n\t\treturn false;\n\t}\n\tconst payloadMethod = [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\treturn payloadMethod.includes(method.toUpperCase());\n}\n\nexport function isRouteMethod(method?: string) {\n\tconst routeMethod = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\tif (!method) {\n\t\treturn false;\n\t}\n\treturn routeMethod.includes(method.toUpperCase());\n}\n\nexport async function getHeaders(opts?: BetterFetchOption) {\n\tconst headers = new Headers(opts?.headers);\n\tconst authHeader = await getAuthHeader(opts);\n\tfor (const [key, value] of Object.entries(authHeader || {})) {\n\t\theaders.set(key, value);\n\t}\n\tif (!headers.has(\"content-type\")) {\n\t\tconst t = detectContentType(opts?.body);\n\t\tif (t) {\n\t\t\theaders.set(\"content-type\", t);\n\t\t}\n\t}\n\n\treturn headers;\n}\n\nexport function getURL(url: string, options?: BetterFetchOption) {\n\tif (url.startsWith(\"@\")) {\n\t\tconst m = url.toString().split(\"@\")[1].split(\"/\")[0];\n\t\tif (methods.includes(m)) {\n\t\t\turl = url.replace(`@${m}/`, \"/\");\n\t\t}\n\t}\n\tlet _url: string | URL;\n\ttry {\n\t\tif (url.startsWith(\"http\")) {\n\t\t\t_url = url;\n\t\t} else {\n\t\t\tlet baseURL = options?.baseURL;\n\t\t\tif (baseURL && !baseURL?.endsWith(\"/\")) {\n\t\t\t\tbaseURL = baseURL + \"/\";\n\t\t\t}\n\t\t\tif (url.startsWith(\"/\")) {\n\t\t\t\t_url = new URL(url.substring(1), baseURL);\n\t\t\t} else {\n\t\t\t\t_url = new URL(url, options?.baseURL);\n\t\t\t}\n\t\t}\n\t} catch (e) {\n\t\tif (e instanceof TypeError) {\n\t\t\tif (!options?.baseURL) {\n\t\t\t\tthrow TypeError(\n\t\t\t\t\t`Invalid URL ${url}. Are you passing in a relative url but not setting the baseURL?`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow TypeError(\n\t\t\t\t`Invalid URL ${url}. Please validate that you are passing the correct input.`,\n\t\t\t);\n\t\t}\n\t\tthrow e;\n\t}\n\n\t/**\n\t * Dynamic Parameters.\n\t */\n\tif (options?.params) {\n\t\tif (Array.isArray(options?.params)) {\n\t\t\tconst params = options?.params\n\t\t\t\t? Array.isArray(options.params)\n\t\t\t\t\t? `/${options.params.join(\"/\")}`\n\t\t\t\t\t: `/${Object.values(options.params).join(\"/\")}`\n\t\t\t\t: \"\";\n\t\t\t_url = _url.toString().split(\"/:\")[0];\n\t\t\t_url = `${_url.toString()}${params}`;\n\t\t} else {\n\t\t\tfor (const [key, value] of Object.entries(options?.params)) {\n\t\t\t\t_url = _url.toString().replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t}\n\tconst __url = new URL(_url);\n\t/**\n\t * Query Parameters\n\t */\n\tconst queryParams = options?.query;\n\tif (queryParams) {\n\t\tfor (const [key, value] of Object.entries(queryParams)) {\n\t\t\t__url.searchParams.append(key, String(value));\n\t\t}\n\t}\n\treturn __url;\n}\n\nexport function detectContentType(body: any) {\n\tif (isJSONSerializable(body)) {\n\t\treturn \"application/json\";\n\t}\n\n\treturn null;\n}\n\nexport function getBody(options?: BetterFetchOption) {\n\tif (!options?.body) {\n\t\treturn null;\n\t}\n\tconst headers = new Headers(options?.headers);\n\tif (isJSONSerializable(options.body) && !headers.has(\"content-type\")) {\n\t\tfor (const [key, value] of Object.entries(options?.body)) {\n\t\t\tif (value instanceof Date) {\n\t\t\t\toptions.body[key] = value.toISOString();\n\t\t\t}\n\t\t}\n\t\treturn JSON.stringify(options.body);\n\t}\n\n\tif (\n\t\theaders.has(\"content-type\") &&\n\t\theaders.get(\"content-type\") === \"application/x-www-form-urlencoded\"\n\t) {\n\t\tif (isJSONSerializable(options.body)) {\n\t\t\treturn new URLSearchParams(options.body).toString();\n\t\t}\n\t\treturn options.body;\n\t}\n\n\treturn options.body;\n}\n\nexport function getMethod(url: string, options?: BetterFetchOption) {\n\tif (options?.method) {\n\t\treturn options.method.toUpperCase();\n\t}\n\tif (url.startsWith(\"@\")) {\n\t\tconst pMethod = url.split(\"@\")[1]?.split(\"/\")[0];\n\t\tif (!methods.includes(pMethod)) {\n\t\t\treturn options?.body ? \"POST\" : \"GET\";\n\t\t}\n\t\treturn pMethod.toUpperCase();\n\t}\n\treturn options?.body ? \"POST\" : \"GET\";\n}\n\nexport function getTimeout(\n\toptions?: BetterFetchOption,\n\tcontroller?: AbortController,\n) {\n\tlet abortTimeout: ReturnType | undefined;\n\tif (!options?.signal && options?.timeout) {\n\t\tabortTimeout = setTimeout(() => controller?.abort(), options?.timeout);\n\t}\n\treturn {\n\t\tabortTimeout,\n\t\tclearTimeout: () => {\n\t\t\tif (abortTimeout) {\n\t\t\t\tclearTimeout(abortTimeout);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function bodyParser(data: any, responseType: ResponseType) {\n\tif (responseType === \"json\") {\n\t\treturn JSON.parse(data);\n\t}\n\treturn data;\n}\n\nexport class ValidationError extends Error {\n\tpublic readonly issues: ReadonlyArray;\n\n\tconstructor(issues: ReadonlyArray, message?: string) {\n\t\t// Default message fallback in case one isn't supplied.\n\t\tsuper(message || JSON.stringify(issues, null, 2));\n\t\tthis.issues = issues;\n\n\t\t// Set the prototype explicitly to ensure that instanceof works correctly.\n\t\tObject.setPrototypeOf(this, ValidationError.prototype);\n\t}\n}\n\nexport async function parseStandardSchema(\n\tschema: TSchema,\n\tinput: StandardSchemaV1.InferInput,\n): Promise> {\n\tconst result = await schema[\"~standard\"].validate(input);\n\n\tif (result.issues) {\n\t\tthrow new ValidationError(result.issues);\n\t}\n\treturn result.value;\n}\n", "import type { StandardSchemaV1 } from \"../standard-schema\";\nimport type { StringLiteralUnion } from \"../type-utils\";\n\nexport type FetchSchema = {\n\tinput?: StandardSchemaV1;\n\toutput?: StandardSchemaV1;\n\tquery?: StandardSchemaV1;\n\tparams?: StandardSchemaV1> | undefined;\n\tmethod?: Methods;\n};\n\nexport type Methods = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\n\nexport const methods = [\"get\", \"post\", \"put\", \"patch\", \"delete\"];\n\ntype RouteKey = StringLiteralUnion<`@${Methods}/`>;\n\nexport type FetchSchemaRoutes = {\n\t[key in RouteKey]?: FetchSchema;\n};\n\nexport const createSchema = <\n\tF extends FetchSchemaRoutes,\n\tS extends SchemaConfig,\n>(\n\tschema: F,\n\tconfig?: S,\n) => {\n\treturn {\n\t\tschema: schema as F,\n\t\tconfig: config as S,\n\t};\n};\n\nexport type SchemaConfig = {\n\tstrict?: boolean;\n\t/**\n\t * A prefix that will be prepended when it's\n\t * calling the schema.\n\t *\n\t * NOTE: Make sure to handle converting\n\t * the prefix to the baseURL in the init\n\t * function if you you are defining for a\n\t * plugin.\n\t */\n\tprefix?: \"\" | (string & Record);\n\t/**\n\t * The base url of the schema. By default it's the baseURL of the fetch instance.\n\t */\n\tbaseURL?: \"\" | (string & Record);\n};\n\nexport type Schema = {\n\tschema: FetchSchemaRoutes;\n\tconfig: SchemaConfig;\n};\n", "import { betterFetch } from \"../fetch\";\nimport { BetterFetchPlugin } from \"../plugins\";\nimport type { BetterFetchOption } from \"../types\";\nimport { parseStandardSchema } from \"../utils\";\nimport type { BetterFetch, CreateFetchOption } from \"./types\";\n\nexport const applySchemaPlugin = (config: CreateFetchOption) =>\n\t({\n\t\tid: \"apply-schema\",\n\t\tname: \"Apply Schema\",\n\t\tversion: \"1.0.0\",\n\t\tasync init(url, options) {\n\t\t\tconst schema =\n\t\t\t\tconfig.plugins?.find((plugin) =>\n\t\t\t\t\tplugin.schema?.config\n\t\t\t\t\t\t? url.startsWith(plugin.schema.config.baseURL || \"\") ||\n\t\t\t\t\t\t\turl.startsWith(plugin.schema.config.prefix || \"\")\n\t\t\t\t\t\t: false,\n\t\t\t\t)?.schema || config.schema;\n\t\t\tif (schema) {\n\t\t\t\tlet urlKey = url;\n\t\t\t\tif (schema.config?.prefix) {\n\t\t\t\t\tif (urlKey.startsWith(schema.config.prefix)) {\n\t\t\t\t\t\turlKey = urlKey.replace(schema.config.prefix, \"\");\n\t\t\t\t\t\tif (schema.config.baseURL) {\n\t\t\t\t\t\t\turl = url.replace(schema.config.prefix, schema.config.baseURL);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (schema.config?.baseURL) {\n\t\t\t\t\tif (urlKey.startsWith(schema.config.baseURL)) {\n\t\t\t\t\t\turlKey = urlKey.replace(schema.config.baseURL, \"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst keySchema = schema.schema[urlKey];\n\t\t\t\tif (keySchema) {\n\t\t\t\t\tlet opts = {\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\tmethod: keySchema.method,\n\t\t\t\t\t\toutput: keySchema.output,\n\t\t\t\t\t};\n\t\t\t\t\tif (!options?.disableValidation) {\n\t\t\t\t\t\topts = {\n\t\t\t\t\t\t\t...opts,\n\t\t\t\t\t\t\tbody: keySchema.input\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.input, options?.body)\n\t\t\t\t\t\t\t\t: options?.body,\n\t\t\t\t\t\t\tparams: keySchema.params\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.params, options?.params)\n\t\t\t\t\t\t\t\t: options?.params,\n\t\t\t\t\t\t\tquery: keySchema.query\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.query, options?.query)\n\t\t\t\t\t\t\t\t: options?.query,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\toptions: opts,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\turl,\n\t\t\t\toptions,\n\t\t\t};\n\t\t},\n\t}) satisfies BetterFetchPlugin;\n\nexport const createFetch = here.` : description}\n

\n \n\n \n \n \n Go Home\n \n \n \n \n Ask AI\n \n \n \n \n \n \n`;\n};\nconst error = createAuthEndpoint(\"/error\", {\n\tmethod: \"GET\",\n\tmetadata: {\n\t\t...HIDE_METADATA,\n\t\topenapi: {\n\t\t\tdescription: \"Displays an error page\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"text/html\": { schema: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The HTML content of the error page\"\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (c) => {\n\tconst url = new URL(c.request?.url || \"\");\n\tconst unsanitizedCode = url.searchParams.get(\"error\") || \"UNKNOWN\";\n\tconst unsanitizedDescription = url.searchParams.get(\"error_description\") || null;\n\tconst safeCode = /^[\\'A-Za-z0-9_-]+$/.test(unsanitizedCode || \"\") ? unsanitizedCode : \"UNKNOWN\";\n\tconst safeDescription = unsanitizedDescription ? sanitize(unsanitizedDescription) : null;\n\tconst queryParams = new URLSearchParams();\n\tqueryParams.set(\"error\", safeCode);\n\tif (unsanitizedDescription) queryParams.set(\"error_description\", unsanitizedDescription);\n\tconst options = c.context.options;\n\tconst errorURL = options.onAPIError?.errorURL;\n\tif (errorURL) return new Response(null, {\n\t\tstatus: 302,\n\t\theaders: { Location: `${errorURL}${errorURL.includes(\"?\") ? \"&\" : \"?\"}${queryParams.toString()}` }\n\t});\n\tif (isProduction && !options.onAPIError?.customizeDefaultErrorPage) return new Response(null, {\n\t\tstatus: 302,\n\t\theaders: { Location: `/?${queryParams.toString()}` }\n\t});\n\treturn new Response(html(c.context.options, safeCode, safeDescription), { headers: { \"Content-Type\": \"text/html\" } });\n});\n//#endregion\nexport { error };\n", "import { HIDE_METADATA } from \"../../utils/hide-metadata.mjs\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\n//#region src/api/routes/ok.ts\nconst ok = createAuthEndpoint(\"/ok\", {\n\tmethod: \"GET\",\n\tmetadata: {\n\t\t...HIDE_METADATA,\n\t\topenapi: {\n\t\t\tdescription: \"Check if the API is working\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"API is working\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { ok: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the API is working\"\n\t\t\t\t\t} },\n\t\t\t\t\trequired: [\"ok\"]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\treturn ctx.json({ ok: true });\n});\n//#endregion\nexport { ok };\n", "import { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\n//#region src/utils/password.ts\nasync function validatePassword(ctx, data) {\n\tconst credentialAccount = (await ctx.context.internalAdapter.findAccounts(data.userId))?.find((account) => account.providerId === \"credential\");\n\tconst currentPassword = credentialAccount?.password;\n\tif (!credentialAccount || !currentPassword) return false;\n\treturn await ctx.context.password.verify({\n\t\thash: currentPassword,\n\t\tpassword: data.password\n\t});\n}\nasync function checkPassword(userId, c) {\n\tconst credentialAccount = (await c.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === \"credential\");\n\tconst currentPassword = credentialAccount?.password;\n\tconst password = c.body.password;\n\tif (!credentialAccount || !currentPassword || !password) {\n\t\tif (password) await c.context.password.hash(password);\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t}\n\tif (!await c.context.password.verify({\n\t\thash: currentPassword,\n\t\tpassword\n\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\treturn true;\n}\nasync function shouldRequirePassword(ctx, userId, allowPasswordless) {\n\tif (!allowPasswordless) return true;\n\tconst credentialAccount = (await ctx.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === \"credential\" && account.password);\n\treturn Boolean(credentialAccount);\n}\n//#endregion\nexport { checkPassword, shouldRequirePassword, validatePassword };\n", "import { originCheck } from \"../middlewares/origin-check.mjs\";\nimport { getDate } from \"../../utils/date.mjs\";\nimport { sensitiveSessionMiddleware } from \"./session.mjs\";\nimport { validatePassword } from \"../../utils/password.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { generateId } from \"@better-auth/core/utils/id\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/password.ts\nfunction redirectError(ctx, callbackURL, query) {\n\tconst url = callbackURL ? new URL(callbackURL, ctx.baseURL) : new URL(`${ctx.baseURL}/error`);\n\tif (query) Object.entries(query).forEach(([k, v]) => url.searchParams.set(k, v));\n\treturn url.href;\n}\nfunction redirectCallback(ctx, callbackURL, query) {\n\tconst url = new URL(callbackURL, ctx.baseURL);\n\tif (query) Object.entries(query).forEach(([k, v]) => url.searchParams.set(k, v));\n\treturn url.href;\n}\nconst requestPasswordReset = createAuthEndpoint(\"/request-password-reset\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\temail: z.email().meta({ description: \"The email address of the user to send a password reset email to\" }),\n\t\tredirectTo: z.string().meta({ description: \"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\toperationId: \"requestPasswordReset\",\n\t\tdescription: \"Send a password reset email to the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tstatus: { type: \"boolean\" },\n\t\t\t\t\tmessage: { type: \"string\" }\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} },\n\tuse: [originCheck((ctx) => ctx.body.redirectTo)]\n}, async (ctx) => {\n\tif (!ctx.context.options.emailAndPassword?.sendResetPassword) {\n\t\tctx.context.logger.error(\"Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Reset password isn't enabled\",\n\t\t\tcode: \"RESET_PASSWORD_DISABLED\"\n\t\t});\n\t}\n\tconst { email, redirectTo } = ctx.body;\n\tconst user = await ctx.context.internalAdapter.findUserByEmail(email, { includeAccounts: true });\n\tif (!user) {\n\t\t/**\n\t\t* We simulate the verification token generation and the database lookup\n\t\t* to mitigate timing attacks.\n\t\t*/\n\t\tgenerateId(24);\n\t\tawait ctx.context.internalAdapter.findVerificationValue(\"dummy-verification-token\");\n\t\tctx.context.logger.error(\"Reset Password: User not found\", { email });\n\t\treturn ctx.json({\n\t\t\tstatus: true,\n\t\t\tmessage: \"If this email exists in our system, check your email for the reset link\"\n\t\t});\n\t}\n\tconst expiresAt = getDate(ctx.context.options.emailAndPassword.resetPasswordTokenExpiresIn || 3600 * 1, \"sec\");\n\tconst verificationToken = generateId(24);\n\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\tvalue: user.user.id,\n\t\tidentifier: `reset-password:${verificationToken}`,\n\t\texpiresAt\n\t});\n\tconst callbackURL = redirectTo ? encodeURIComponent(redirectTo) : \"\";\n\tconst url = `${ctx.context.baseURL}/reset-password/${verificationToken}?callbackURL=${callbackURL}`;\n\tawait ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.sendResetPassword({\n\t\tuser: user.user,\n\t\turl,\n\t\ttoken: verificationToken\n\t}, ctx.request));\n\treturn ctx.json({\n\t\tstatus: true,\n\t\tmessage: \"If this email exists in our system, check your email for the reset link\"\n\t});\n});\nconst requestPasswordResetCallback = createAuthEndpoint(\"/reset-password/:token\", {\n\tmethod: \"GET\",\n\toperationId: \"forgetPasswordCallback\",\n\tquery: z.object({ callbackURL: z.string().meta({ description: \"The URL to redirect the user to reset their password\" }) }),\n\tuse: [originCheck((ctx) => ctx.query.callbackURL)],\n\tmetadata: { openapi: {\n\t\toperationId: \"resetPasswordCallback\",\n\t\tdescription: \"Redirects the user to the callback URL with the token\",\n\t\tparameters: [{\n\t\t\tname: \"token\",\n\t\t\tin: \"path\",\n\t\t\trequired: true,\n\t\t\tdescription: \"The token to reset the password\",\n\t\t\tschema: { type: \"string\" }\n\t\t}, {\n\t\t\tname: \"callbackURL\",\n\t\t\tin: \"query\",\n\t\t\trequired: true,\n\t\t\tdescription: \"The URL to redirect the user to reset their password\",\n\t\t\tschema: { type: \"string\" }\n\t\t}],\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { token: { type: \"string\" } }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst { token } = ctx.params;\n\tconst { callbackURL } = ctx.query;\n\tif (!token || !callbackURL) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: \"INVALID_TOKEN\" }));\n\tconst verification = await ctx.context.internalAdapter.findVerificationValue(`reset-password:${token}`);\n\tif (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: \"INVALID_TOKEN\" }));\n\tthrow ctx.redirect(redirectCallback(ctx.context, callbackURL, { token }));\n});\nconst resetPassword = createAuthEndpoint(\"/reset-password\", {\n\tmethod: \"POST\",\n\toperationId: \"resetPassword\",\n\tquery: z.object({ token: z.string().optional() }).optional(),\n\tbody: z.object({\n\t\tnewPassword: z.string().meta({ description: \"The new password to set\" }),\n\t\ttoken: z.string().meta({ description: \"The token to reset the password\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\toperationId: \"resetPassword\",\n\t\tdescription: \"Reset the password for a user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst token = ctx.body.token || ctx.query?.token;\n\tif (!token) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_TOKEN);\n\tconst { newPassword } = ctx.body;\n\tconst minLength = ctx.context.password?.config.minPasswordLength;\n\tconst maxLength = ctx.context.password?.config.maxPasswordLength;\n\tif (newPassword.length < minLength) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_SHORT);\n\tif (newPassword.length > maxLength) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_LONG);\n\tconst id = `reset-password:${token}`;\n\tconst verification = await ctx.context.internalAdapter.findVerificationValue(id);\n\tif (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_TOKEN);\n\tconst userId = verification.value;\n\tconst hashedPassword = await ctx.context.password.hash(newPassword);\n\tif (!(await ctx.context.internalAdapter.findAccounts(userId)).find((ac) => ac.providerId === \"credential\")) await ctx.context.internalAdapter.createAccount({\n\t\tuserId,\n\t\tproviderId: \"credential\",\n\t\tpassword: hashedPassword,\n\t\taccountId: userId\n\t});\n\telse await ctx.context.internalAdapter.updatePassword(userId, hashedPassword);\n\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(id);\n\tif (ctx.context.options.emailAndPassword?.onPasswordReset) {\n\t\tconst user = await ctx.context.internalAdapter.findUserById(userId);\n\t\tif (user) await ctx.context.options.emailAndPassword.onPasswordReset({ user }, ctx.request);\n\t}\n\tif (ctx.context.options.emailAndPassword?.revokeSessionsOnPasswordReset) await ctx.context.internalAdapter.deleteSessions(userId);\n\treturn ctx.json({ status: true });\n});\nconst verifyPassword = createAuthEndpoint(\"/verify-password\", {\n\tmethod: \"POST\",\n\tbody: z.object({ password: z.string().meta({ description: \"The password to verify\" }) }),\n\tmetadata: {\n\t\tscope: \"server\",\n\t\topenapi: {\n\t\t\toperationId: \"verifyPassword\",\n\t\t\tdescription: \"Verify the current user's password\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t},\n\tuse: [sensitiveSessionMiddleware]\n}, async (ctx) => {\n\tconst { password } = ctx.body;\n\tconst session = ctx.context.session;\n\tif (!await validatePassword(ctx, {\n\t\tpassword,\n\t\tuserId: session.user.id\n\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\treturn ctx.json({ status: true });\n});\n//#endregion\nexport { requestPasswordReset, requestPasswordResetCallback, resetPassword, verifyPassword };\n", "import { formCsrfMiddleware } from \"../middlewares/origin-check.mjs\";\nimport { parseUserOutput } from \"../../db/schema.mjs\";\nimport { getAwaitableValue } from \"../../context/helpers.mjs\";\nimport { setSessionCookie } from \"../../cookies/index.mjs\";\nimport { generateState } from \"../../oauth2/state.mjs\";\nimport { handleOAuthUserInfo } from \"../../oauth2/link-account.mjs\";\nimport { createEmailVerificationToken } from \"./email-verification.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { SocialProviderListEnum } from \"@better-auth/core/social-providers\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/sign-in.ts\nconst socialSignInBodySchema = z.object({\n\tcallbackURL: z.string().meta({ description: \"Callback URL to redirect to after the user has signed in\" }).optional(),\n\tnewUserCallbackURL: z.string().optional(),\n\terrorCallbackURL: z.string().meta({ description: \"Callback URL to redirect to if an error happens\" }).optional(),\n\tprovider: SocialProviderListEnum,\n\tdisableRedirect: z.boolean().meta({ description: \"Disable automatic redirection to the provider. Useful for handling the redirection yourself\" }).optional(),\n\tidToken: z.optional(z.object({\n\t\ttoken: z.string().meta({ description: \"ID token from the provider\" }),\n\t\tnonce: z.string().meta({ description: \"Nonce used to generate the token\" }).optional(),\n\t\taccessToken: z.string().meta({ description: \"Access token from the provider\" }).optional(),\n\t\trefreshToken: z.string().meta({ description: \"Refresh token from the provider\" }).optional(),\n\t\texpiresAt: z.number().meta({ description: \"Expiry date of the token\" }).optional(),\n\t\tuser: z.object({\n\t\t\tname: z.object({\n\t\t\t\tfirstName: z.string().optional(),\n\t\t\t\tlastName: z.string().optional()\n\t\t\t}).optional(),\n\t\t\temail: z.string().optional()\n\t\t}).meta({ description: \"The user object from the provider. Only available for some providers like Apple.\" }).optional()\n\t})),\n\tscopes: z.array(z.string()).meta({ description: \"Array of scopes to request from the provider. This will override the default scopes passed.\" }).optional(),\n\trequestSignUp: z.boolean().meta({ description: \"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider\" }).optional(),\n\tloginHint: z.string().meta({ description: \"The login hint to use for the authorization code request\" }).optional(),\n\tadditionalData: z.record(z.string(), z.any()).optional().meta({ description: \"Additional data to be passed through the OAuth flow\" })\n});\nconst signInSocial = () => createAuthEndpoint(\"/sign-in/social\", {\n\tmethod: \"POST\",\n\toperationId: \"socialSignIn\",\n\tbody: socialSignInBodySchema,\n\tmetadata: {\n\t\t$Infer: {\n\t\t\tbody: {},\n\t\t\treturned: {}\n\t\t},\n\t\topenapi: {\n\t\t\tdescription: \"Sign in with a social provider\",\n\t\t\toperationId: \"socialSignIn\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success - Returns either session details or redirect URL\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"Session response when idToken is provided\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttoken: { type: \"string\" },\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t$ref: \"#/components/schemas/User\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\turl: { type: \"string\" },\n\t\t\t\t\t\tredirect: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tenum: [false]\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"redirect\",\n\t\t\t\t\t\t\"token\",\n\t\t\t\t\t\t\"user\"\n\t\t\t\t\t]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (c) => {\n\tconst provider = await getAwaitableValue(c.context.socialProviders, { value: c.body.provider });\n\tif (!provider) {\n\t\tc.context.logger.error(\"Provider not found. Make sure to add the provider in your auth config\", { provider: c.body.provider });\n\t\tthrow APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.PROVIDER_NOT_FOUND);\n\t}\n\tif (c.body.idToken) {\n\t\tif (!provider.verifyIdToken) {\n\t\t\tc.context.logger.error(\"Provider does not support id token verification\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);\n\t\t}\n\t\tconst { token, nonce } = c.body.idToken;\n\t\tif (!await provider.verifyIdToken(token, nonce)) {\n\t\t\tc.context.logger.error(\"Invalid id token\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_TOKEN);\n\t\t}\n\t\tconst userInfo = await provider.getUserInfo({\n\t\t\tidToken: token,\n\t\t\taccessToken: c.body.idToken.accessToken,\n\t\t\trefreshToken: c.body.idToken.refreshToken,\n\t\t\tuser: c.body.idToken.user\n\t\t});\n\t\tif (!userInfo || !userInfo?.user) {\n\t\t\tc.context.logger.error(\"Failed to get user info\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);\n\t\t}\n\t\tif (!userInfo.user.email) {\n\t\t\tc.context.logger.error(\"User email not found\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);\n\t\t}\n\t\tconst data = await handleOAuthUserInfo(c, {\n\t\t\tuserInfo: {\n\t\t\t\t...userInfo.user,\n\t\t\t\temail: userInfo.user.email,\n\t\t\t\tid: String(userInfo.user.id),\n\t\t\t\tname: userInfo.user.name || \"\",\n\t\t\t\timage: userInfo.user.image,\n\t\t\t\temailVerified: userInfo.user.emailVerified || false\n\t\t\t},\n\t\t\taccount: {\n\t\t\t\tproviderId: provider.id,\n\t\t\t\taccountId: String(userInfo.user.id),\n\t\t\t\taccessToken: c.body.idToken.accessToken\n\t\t\t},\n\t\t\tcallbackURL: c.body.callbackURL,\n\t\t\tdisableSignUp: provider.disableImplicitSignUp && !c.body.requestSignUp || provider.disableSignUp\n\t\t});\n\t\tif (data.error) throw APIError.from(\"UNAUTHORIZED\", {\n\t\t\tmessage: data.error,\n\t\t\tcode: \"OAUTH_LINK_ERROR\"\n\t\t});\n\t\tawait setSessionCookie(c, data.data);\n\t\treturn c.json({\n\t\t\tredirect: false,\n\t\t\ttoken: data.data.session.token,\n\t\t\turl: void 0,\n\t\t\tuser: parseUserOutput(c.context.options, data.data.user)\n\t\t});\n\t}\n\tconst { codeVerifier, state } = await generateState(c, void 0, c.body.additionalData);\n\tconst url = await provider.createAuthorizationURL({\n\t\tstate,\n\t\tcodeVerifier,\n\t\tredirectURI: `${c.context.baseURL}/callback/${provider.id}`,\n\t\tscopes: c.body.scopes,\n\t\tloginHint: c.body.loginHint\n\t});\n\tif (!c.body.disableRedirect) c.setHeader(\"Location\", url.toString());\n\treturn c.json({\n\t\turl: url.toString(),\n\t\tredirect: !c.body.disableRedirect\n\t});\n});\nconst signInEmail = () => createAuthEndpoint(\"/sign-in/email\", {\n\tmethod: \"POST\",\n\toperationId: \"signInEmail\",\n\tuse: [formCsrfMiddleware],\n\tbody: z.object({\n\t\temail: z.string().meta({ description: \"Email of the user\" }),\n\t\tpassword: z.string().meta({ description: \"Password of the user\" }),\n\t\tcallbackURL: z.string().meta({ description: \"Callback URL to use as a redirect for email verification\" }).optional(),\n\t\trememberMe: z.boolean().meta({ description: \"If this is false, the session will not be remembered. Default is `true`.\" }).default(true).optional()\n\t}),\n\tmetadata: {\n\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\", \"application/json\"],\n\t\t$Infer: {\n\t\t\tbody: {},\n\t\t\treturned: {}\n\t\t},\n\t\topenapi: {\n\t\t\toperationId: \"signInEmail\",\n\t\t\tdescription: \"Sign in with email and password\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success - Returns either session details or redirect URL\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"Session response when idToken is provided\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tredirect: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tenum: [false]\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Session token\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\turl: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tnullable: true\n\t\t\t\t\t\t},\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t$ref: \"#/components/schemas/User\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"redirect\",\n\t\t\t\t\t\t\"token\",\n\t\t\t\t\t\t\"user\"\n\t\t\t\t\t]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\tif (!ctx.context.options?.emailAndPassword?.enabled) {\n\t\tctx.context.logger.error(\"Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\tcode: \"EMAIL_PASSWORD_DISABLED\",\n\t\t\tmessage: \"Email and password is not enabled\"\n\t\t});\n\t}\n\tconst { email, password } = ctx.body;\n\tif (!z.email().safeParse(email).success) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_EMAIL);\n\tconst user = await ctx.context.internalAdapter.findUserByEmail(email, { includeAccounts: true });\n\tif (!user) {\n\t\tawait ctx.context.password.hash(password);\n\t\tctx.context.logger.error(\"User not found\", { email });\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);\n\t}\n\tconst credentialAccount = user.accounts.find((a) => a.providerId === \"credential\");\n\tif (!credentialAccount) {\n\t\tawait ctx.context.password.hash(password);\n\t\tctx.context.logger.error(\"Credential account not found\", { email });\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);\n\t}\n\tconst currentPassword = credentialAccount?.password;\n\tif (!currentPassword) {\n\t\tawait ctx.context.password.hash(password);\n\t\tctx.context.logger.error(\"Password not found\", { email });\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);\n\t}\n\tif (!await ctx.context.password.verify({\n\t\thash: currentPassword,\n\t\tpassword\n\t})) {\n\t\tctx.context.logger.error(\"Invalid password\");\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);\n\t}\n\tif (ctx.context.options?.emailAndPassword?.requireEmailVerification && !user.user.emailVerified) {\n\t\tif (!ctx.context.options?.emailVerification?.sendVerificationEmail) throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.EMAIL_NOT_VERIFIED);\n\t\tif (ctx.context.options?.emailVerification?.sendOnSignIn) {\n\t\t\tconst token = await createEmailVerificationToken(ctx.context.secret, user.user.email, void 0, ctx.context.options.emailVerification?.expiresIn);\n\t\t\tconst callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent(\"/\");\n\t\t\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`;\n\t\t\tawait ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({\n\t\t\t\tuser: user.user,\n\t\t\t\turl,\n\t\t\t\ttoken\n\t\t\t}, ctx.request));\n\t\t}\n\t\tthrow APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.EMAIL_NOT_VERIFIED);\n\t}\n\tconst session = await ctx.context.internalAdapter.createSession(user.user.id, ctx.body.rememberMe === false);\n\tif (!session) {\n\t\tctx.context.logger.error(\"Failed to create session\");\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);\n\t}\n\tawait setSessionCookie(ctx, {\n\t\tsession,\n\t\tuser: user.user\n\t}, ctx.body.rememberMe === false);\n\tif (ctx.body.callbackURL) ctx.setHeader(\"Location\", ctx.body.callbackURL);\n\treturn ctx.json({\n\t\tredirect: !!ctx.body.callbackURL,\n\t\ttoken: session.token,\n\t\turl: ctx.body.callbackURL,\n\t\tuser: parseUserOutput(ctx.context.options, user.user)\n\t});\n});\n//#endregion\nexport { signInEmail, signInSocial };\n", "import { deleteSessionCookie } from \"../../cookies/index.mjs\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\n//#region src/api/routes/sign-out.ts\nconst signOut = createAuthEndpoint(\"/sign-out\", {\n\tmethod: \"POST\",\n\toperationId: \"signOut\",\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\toperationId: \"signOut\",\n\t\tdescription: \"Sign out the current user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { success: { type: \"boolean\" } }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);\n\tif (sessionCookieToken) try {\n\t\tawait ctx.context.internalAdapter.deleteSession(sessionCookieToken);\n\t} catch (e) {\n\t\tctx.context.logger.error(\"Failed to delete session from database\", e);\n\t}\n\tdeleteSessionCookie(ctx);\n\treturn ctx.json({ success: true });\n});\n//#endregion\nexport { signOut };\n", "import { isAPIError } from \"../../utils/is-api-error.mjs\";\nimport { formCsrfMiddleware } from \"../middlewares/origin-check.mjs\";\nimport { parseUserInput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { setSessionCookie } from \"../../cookies/index.mjs\";\nimport { createEmailVerificationToken } from \"./email-verification.mjs\";\nimport { runWithTransaction } from \"@better-auth/core/context\";\nimport { isDevelopment } from \"@better-auth/core/env\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { generateId } from \"@better-auth/core/utils/id\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/sign-up.ts\nconst signUpEmailBodySchema = z.object({\n\tname: z.string(),\n\temail: z.email(),\n\tpassword: z.string().nonempty(),\n\timage: z.string().optional(),\n\tcallbackURL: z.string().optional(),\n\trememberMe: z.boolean().optional()\n}).and(z.record(z.string(), z.any()));\nconst signUpEmail = () => createAuthEndpoint(\"/sign-up/email\", {\n\tmethod: \"POST\",\n\toperationId: \"signUpWithEmailAndPassword\",\n\tuse: [formCsrfMiddleware],\n\tbody: signUpEmailBodySchema,\n\tmetadata: {\n\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\", \"application/json\"],\n\t\t$Infer: {\n\t\t\tbody: {},\n\t\t\treturned: {}\n\t\t},\n\t\topenapi: {\n\t\t\toperationId: \"signUpWithEmailAndPassword\",\n\t\t\tdescription: \"Sign up a user using email and password\",\n\t\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tname: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The name of the user\"\n\t\t\t\t\t},\n\t\t\t\t\temail: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The email of the user\"\n\t\t\t\t\t},\n\t\t\t\t\tpassword: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The password of the user\"\n\t\t\t\t\t},\n\t\t\t\t\timage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The profile image URL of the user\"\n\t\t\t\t\t},\n\t\t\t\t\tcallbackURL: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The URL to use for email verification callback\"\n\t\t\t\t\t},\n\t\t\t\t\trememberMe: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"If this is false, the session will not be remembered. Default is `true`.\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\n\t\t\t\t\t\"name\",\n\t\t\t\t\t\"email\",\n\t\t\t\t\t\"password\"\n\t\t\t\t]\n\t\t\t} } } },\n\t\t\tresponses: {\n\t\t\t\t\"200\": {\n\t\t\t\t\tdescription: \"Successfully created user\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\tdescription: \"Authentication token for the session\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"The unique identifier of the user\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"The email address of the user\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"The name of the user\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\timage: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\tdescription: \"The profile image URL of the user\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\temailVerified: {\n\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the email has been verified\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"When the user was created\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"When the user was last updated\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\t\t\"email\",\n\t\t\t\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\t\t\t\"emailVerified\",\n\t\t\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"user\"]\n\t\t\t\t\t} } }\n\t\t\t\t},\n\t\t\t\t\"422\": {\n\t\t\t\t\tdescription: \"Unprocessable Entity. User already exists or failed to create user.\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: { message: { type: \"string\" } }\n\t\t\t\t\t} } }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}, async (ctx) => {\n\treturn runWithTransaction(ctx.context.adapter, async () => {\n\t\tif (!ctx.context.options.emailAndPassword?.enabled || ctx.context.options.emailAndPassword?.disableSignUp) throw APIError.from(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Email and password sign up is not enabled\",\n\t\t\tcode: \"EMAIL_PASSWORD_SIGN_UP_DISABLED\"\n\t\t});\n\t\tconst body = ctx.body;\n\t\tconst { name, email, password, image, callbackURL: _callbackURL, rememberMe, ...rest } = body;\n\t\tif (!z.email().safeParse(email).success) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_EMAIL);\n\t\tif (!password || typeof password !== \"string\") throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\tconst minPasswordLength = ctx.context.password.config.minPasswordLength;\n\t\tif (password.length < minPasswordLength) {\n\t\t\tctx.context.logger.error(\"Password is too short\");\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_SHORT);\n\t\t}\n\t\tconst maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n\t\tif (password.length > maxPasswordLength) {\n\t\t\tctx.context.logger.error(\"Password is too long\");\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_LONG);\n\t\t}\n\t\tconst shouldReturnGenericDuplicateResponse = ctx.context.options.emailAndPassword.requireEmailVerification;\n\t\tconst shouldSkipAutoSignIn = ctx.context.options.emailAndPassword.autoSignIn === false || shouldReturnGenericDuplicateResponse;\n\t\tconst additionalUserFields = parseUserInput(ctx.context.options, rest, \"create\");\n\t\tconst normalizedEmail = email.toLowerCase();\n\t\tconst dbUser = await ctx.context.internalAdapter.findUserByEmail(normalizedEmail);\n\t\tif (dbUser?.user) {\n\t\t\tctx.context.logger.info(`Sign-up attempt for existing email: ${email}`);\n\t\t\tif (shouldReturnGenericDuplicateResponse) {\n\t\t\t\t/**\n\t\t\t\t* Hash the password to reduce timing differences\n\t\t\t\t* between existing and non-existing emails.\n\t\t\t\t*/\n\t\t\t\tawait ctx.context.password.hash(password);\n\t\t\t\tif (ctx.context.options.emailAndPassword?.onExistingUserSignUp) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.onExistingUserSignUp({ user: dbUser.user }, ctx.request));\n\t\t\t\tconst now = /* @__PURE__ */ new Date();\n\t\t\t\tconst generatedId = ctx.context.generateId({ model: \"user\" }) || generateId();\n\t\t\t\tconst coreFields = {\n\t\t\t\t\tname,\n\t\t\t\t\temail: normalizedEmail,\n\t\t\t\t\temailVerified: false,\n\t\t\t\t\timage: image || null,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now\n\t\t\t\t};\n\t\t\t\tconst customSyntheticUser = ctx.context.options.emailAndPassword?.customSyntheticUser;\n\t\t\t\tlet syntheticUser;\n\t\t\t\tif (customSyntheticUser) {\n\t\t\t\t\tconst additionalFieldKeys = Object.keys(ctx.context.options.user?.additionalFields ?? {});\n\t\t\t\t\tconst additionalFields = {};\n\t\t\t\t\tfor (const key of additionalFieldKeys) if (key in additionalUserFields) additionalFields[key] = additionalUserFields[key];\n\t\t\t\t\tsyntheticUser = customSyntheticUser({\n\t\t\t\t\t\tcoreFields,\n\t\t\t\t\t\tadditionalFields,\n\t\t\t\t\t\tid: generatedId\n\t\t\t\t\t});\n\t\t\t\t} else syntheticUser = {\n\t\t\t\t\t...coreFields,\n\t\t\t\t\t...additionalUserFields,\n\t\t\t\t\tid: generatedId\n\t\t\t\t};\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttoken: null,\n\t\t\t\t\tuser: parseUserOutput(ctx.context.options, syntheticUser)\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow APIError.from(\"UNPROCESSABLE_ENTITY\", BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);\n\t\t}\n\t\t/**\n\t\t* Hash the password\n\t\t*\n\t\t* This is done prior to creating the user\n\t\t* to ensure that any plugin that\n\t\t* may break the hashing should break\n\t\t* before the user is created.\n\t\t*/\n\t\tconst hash = await ctx.context.password.hash(password);\n\t\tlet createdUser;\n\t\ttry {\n\t\t\tcreatedUser = await ctx.context.internalAdapter.createUser({\n\t\t\t\temail: normalizedEmail,\n\t\t\t\tname,\n\t\t\t\timage,\n\t\t\t\t...additionalUserFields,\n\t\t\t\temailVerified: false\n\t\t\t});\n\t\t\tif (!createdUser) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.FAILED_TO_CREATE_USER);\n\t\t} catch (e) {\n\t\t\tif (isDevelopment()) ctx.context.logger.error(\"Failed to create user\", e);\n\t\t\tif (isAPIError(e)) throw e;\n\t\t\tctx.context.logger?.error(\"Failed to create user\", e);\n\t\t\tthrow APIError.from(\"UNPROCESSABLE_ENTITY\", BASE_ERROR_CODES.FAILED_TO_CREATE_USER);\n\t\t}\n\t\tif (!createdUser) throw APIError.from(\"UNPROCESSABLE_ENTITY\", BASE_ERROR_CODES.FAILED_TO_CREATE_USER);\n\t\tawait ctx.context.internalAdapter.linkAccount({\n\t\t\tuserId: createdUser.id,\n\t\t\tproviderId: \"credential\",\n\t\t\taccountId: createdUser.id,\n\t\t\tpassword: hash\n\t\t});\n\t\tif (ctx.context.options.emailVerification?.sendOnSignUp ?? ctx.context.options.emailAndPassword.requireEmailVerification) {\n\t\t\tconst token = await createEmailVerificationToken(ctx.context.secret, createdUser.email, void 0, ctx.context.options.emailVerification?.expiresIn);\n\t\t\tconst callbackURL = body.callbackURL ? encodeURIComponent(body.callbackURL) : encodeURIComponent(\"/\");\n\t\t\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`;\n\t\t\tif (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({\n\t\t\t\tuser: createdUser,\n\t\t\t\turl,\n\t\t\t\ttoken\n\t\t\t}, ctx.request));\n\t\t}\n\t\tif (shouldSkipAutoSignIn) return ctx.json({\n\t\t\ttoken: null,\n\t\t\tuser: parseUserOutput(ctx.context.options, createdUser)\n\t\t});\n\t\tconst session = await ctx.context.internalAdapter.createSession(createdUser.id, rememberMe === false);\n\t\tif (!session) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession,\n\t\t\tuser: createdUser\n\t\t}, rememberMe === false);\n\t\treturn ctx.json({\n\t\t\ttoken: session.token,\n\t\t\tuser: parseUserOutput(ctx.context.options, createdUser)\n\t\t});\n\t});\n});\n//#endregion\nexport { signUpEmail };\n", "import { parseSessionInput, parseSessionOutput } from \"../../db/schema.mjs\";\nimport { setSessionCookie } from \"../../cookies/index.mjs\";\nimport { sessionMiddleware } from \"./session.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/update-session.ts\nconst updateSessionBodySchema = z.record(z.string().meta({ description: \"Field name must be a string\" }), z.any());\nconst updateSession = () => createAuthEndpoint(\"/update-session\", {\n\tmethod: \"POST\",\n\toperationId: \"updateSession\",\n\tbody: updateSessionBodySchema,\n\tuse: [sessionMiddleware],\n\tmetadata: {\n\t\t$Infer: { body: {} },\n\t\topenapi: {\n\t\t\toperationId: \"updateSession\",\n\t\t\tdescription: \"Update the current session\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { session: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/Session\"\n\t\t\t\t\t} }\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\tconst body = ctx.body;\n\tif (typeof body !== \"object\" || Array.isArray(body)) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);\n\tconst session = ctx.context.session;\n\tconst additionalFields = parseSessionInput(ctx.context.options, body, \"update\");\n\tif (Object.keys(additionalFields).length === 0) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"No fields to update\" });\n\tconst newSession = await ctx.context.internalAdapter.updateSession(session.session.token, {\n\t\t...additionalFields,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}) ?? {\n\t\t...session.session,\n\t\t...additionalFields,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tawait setSessionCookie(ctx, {\n\t\tsession: newSession,\n\t\tuser: session.user\n\t});\n\treturn ctx.json({ session: parseSessionOutput(ctx.context.options, newSession) });\n});\n//#endregion\nexport { updateSession };\n", "import { originCheck } from \"../middlewares/origin-check.mjs\";\nimport { parseUserInput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { generateRandomString } from \"../../crypto/random.mjs\";\nimport { deleteSessionCookie, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { getSessionFromCtx, sensitiveSessionMiddleware, sessionMiddleware } from \"./session.mjs\";\nimport { createEmailVerificationToken } from \"./email-verification.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/update-user.ts\nconst updateUserBodySchema = z.record(z.string().meta({ description: \"Field name must be a string\" }), z.any());\nconst updateUser = () => createAuthEndpoint(\"/update-user\", {\n\tmethod: \"POST\",\n\toperationId: \"updateUser\",\n\tbody: updateUserBodySchema,\n\tuse: [sessionMiddleware],\n\tmetadata: {\n\t\t$Infer: { body: {} },\n\t\topenapi: {\n\t\t\toperationId: \"updateUser\",\n\t\t\tdescription: \"Update the current user\",\n\t\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tname: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The name of the user\"\n\t\t\t\t\t},\n\t\t\t\t\timage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The image of the user\",\n\t\t\t\t\t\tnullable: true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} } } },\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { user: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/User\"\n\t\t\t\t\t} }\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\tconst body = ctx.body;\n\tif (typeof body !== \"object\" || Array.isArray(body)) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);\n\tif (body.email) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED);\n\tconst { name, image, ...rest } = body;\n\tconst session = ctx.context.session;\n\tconst additionalFields = parseUserInput(ctx.context.options, rest, \"update\");\n\tif (image === void 0 && name === void 0 && Object.keys(additionalFields).length === 0) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"No fields to update\" });\n\tconst updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, {\n\t\tname,\n\t\timage,\n\t\t...additionalFields\n\t}) ?? {\n\t\t...session.user,\n\t\t...name !== void 0 && { name },\n\t\t...image !== void 0 && { image },\n\t\t...additionalFields\n\t};\n\t/**\n\t* Update the session cookie with the new user data\n\t*/\n\tawait setSessionCookie(ctx, {\n\t\tsession: session.session,\n\t\tuser: updatedUser\n\t});\n\treturn ctx.json({ status: true });\n});\nconst changePassword = createAuthEndpoint(\"/change-password\", {\n\tmethod: \"POST\",\n\toperationId: \"changePassword\",\n\tbody: z.object({\n\t\tnewPassword: z.string().meta({ description: \"The new password to set\" }),\n\t\tcurrentPassword: z.string().meta({ description: \"The current password is required\" }),\n\t\trevokeOtherSessions: z.boolean().meta({ description: \"Must be a boolean value\" }).optional()\n\t}),\n\tuse: [sensitiveSessionMiddleware],\n\tmetadata: { openapi: {\n\t\toperationId: \"changePassword\",\n\t\tdescription: \"Change the password of the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Password successfully changed\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\ttoken: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\tdescription: \"New session token if other sessions were revoked\"\n\t\t\t\t\t},\n\t\t\t\t\tuser: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"The unique identifier of the user\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\tdescription: \"The email address of the user\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"The name of the user\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\timage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\tdescription: \"The profile image URL of the user\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\temailVerified: {\n\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\tdescription: \"Whether the email has been verified\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"When the user was created\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"When the user was last updated\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"email\",\n\t\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\t\"emailVerified\",\n\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t]\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"user\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst { newPassword, currentPassword, revokeOtherSessions } = ctx.body;\n\tconst session = ctx.context.session;\n\tconst minPasswordLength = ctx.context.password.config.minPasswordLength;\n\tif (newPassword.length < minPasswordLength) {\n\t\tctx.context.logger.error(\"Password is too short\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_SHORT);\n\t}\n\tconst maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n\tif (newPassword.length > maxPasswordLength) {\n\t\tctx.context.logger.error(\"Password is too long\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_LONG);\n\t}\n\tconst account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account) => account.providerId === \"credential\" && account.password);\n\tif (!account || !account.password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);\n\tconst passwordHash = await ctx.context.password.hash(newPassword);\n\tif (!await ctx.context.password.verify({\n\t\thash: account.password,\n\t\tpassword: currentPassword\n\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\tawait ctx.context.internalAdapter.updateAccount(account.id, { password: passwordHash });\n\tlet token = null;\n\tif (revokeOtherSessions) {\n\t\tawait ctx.context.internalAdapter.deleteSessions(session.user.id);\n\t\tconst newSession = await ctx.context.internalAdapter.createSession(session.user.id);\n\t\tif (!newSession) throw APIError.from(\"INTERNAL_SERVER_ERROR\", BASE_ERROR_CODES.FAILED_TO_GET_SESSION);\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession: newSession,\n\t\t\tuser: session.user\n\t\t});\n\t\ttoken = newSession.token;\n\t}\n\treturn ctx.json({\n\t\ttoken,\n\t\tuser: parseUserOutput(ctx.context.options, session.user)\n\t});\n});\nconst setPassword = createAuthEndpoint({\n\tmethod: \"POST\",\n\tbody: z.object({ newPassword: z.string().meta({ description: \"The new password to set is required\" }) }),\n\tuse: [sensitiveSessionMiddleware]\n}, async (ctx) => {\n\tconst { newPassword } = ctx.body;\n\tconst session = ctx.context.session;\n\tconst minPasswordLength = ctx.context.password.config.minPasswordLength;\n\tif (newPassword.length < minPasswordLength) {\n\t\tctx.context.logger.error(\"Password is too short\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_SHORT);\n\t}\n\tconst maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n\tif (newPassword.length > maxPasswordLength) {\n\t\tctx.context.logger.error(\"Password is too long\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_LONG);\n\t}\n\tconst account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account) => account.providerId === \"credential\" && account.password);\n\tconst passwordHash = await ctx.context.password.hash(newPassword);\n\tif (!account) {\n\t\tawait ctx.context.internalAdapter.linkAccount({\n\t\t\tuserId: session.user.id,\n\t\t\tproviderId: \"credential\",\n\t\t\taccountId: session.user.id,\n\t\t\tpassword: passwordHash\n\t\t});\n\t\treturn ctx.json({ status: true });\n\t}\n\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_ALREADY_SET);\n});\nconst deleteUser = createAuthEndpoint(\"/delete-user\", {\n\tmethod: \"POST\",\n\tuse: [sensitiveSessionMiddleware],\n\tbody: z.object({\n\t\tcallbackURL: z.string().meta({ description: \"The callback URL to redirect to after the user is deleted\" }).optional(),\n\t\tpassword: z.string().meta({ description: \"The password of the user is required to delete the user\" }).optional(),\n\t\ttoken: z.string().meta({ description: \"The token to delete the user is required\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\toperationId: \"deleteUser\",\n\t\tdescription: \"Delete the user\",\n\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\ttype: \"object\",\n\t\t\tproperties: {\n\t\t\t\tcallbackURL: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The callback URL to redirect to after the user is deleted\"\n\t\t\t\t},\n\t\t\t\tpassword: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The user's password. Required if session is not fresh\"\n\t\t\t\t},\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The deletion verification token\"\n\t\t\t\t}\n\t\t\t}\n\t\t} } } },\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"User deletion processed successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tsuccess: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the operation was successful\"\n\t\t\t\t\t},\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tenum: [\"User deleted\", \"Verification email sent\"],\n\t\t\t\t\t\tdescription: \"Status message of the deletion process\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"success\", \"message\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tif (!ctx.context.options.user?.deleteUser?.enabled) {\n\t\tctx.context.logger.error(\"Delete user is disabled. Enable it in the options\");\n\t\tthrow APIError.fromStatus(\"NOT_FOUND\");\n\t}\n\tconst session = ctx.context.session;\n\tif (ctx.body.password) {\n\t\tconst account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account) => account.providerId === \"credential\" && account.password);\n\t\tif (!account || !account.password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);\n\t\tif (!await ctx.context.password.verify({\n\t\t\thash: account.password,\n\t\t\tpassword: ctx.body.password\n\t\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t}\n\tif (ctx.body.token) {\n\t\tawait deleteUserCallback({\n\t\t\t...ctx,\n\t\t\tquery: { token: ctx.body.token }\n\t\t});\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t\tmessage: \"User deleted\"\n\t\t});\n\t}\n\tif (ctx.context.options.user.deleteUser?.sendDeleteAccountVerification) {\n\t\tconst token = generateRandomString(32, \"0-9\", \"a-z\");\n\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\tvalue: session.user.id,\n\t\t\tidentifier: `delete-account-${token}`,\n\t\t\texpiresAt: new Date(Date.now() + (ctx.context.options.user.deleteUser?.deleteTokenExpiresIn || 3600 * 24) * 1e3)\n\t\t});\n\t\tconst url = `${ctx.context.baseURL}/delete-user/callback?token=${token}&callbackURL=${encodeURIComponent(ctx.body.callbackURL || \"/\")}`;\n\t\tawait ctx.context.runInBackgroundOrAwait(ctx.context.options.user.deleteUser.sendDeleteAccountVerification({\n\t\t\tuser: session.user,\n\t\t\turl,\n\t\t\ttoken\n\t\t}, ctx.request));\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t\tmessage: \"Verification email sent\"\n\t\t});\n\t}\n\tif (!ctx.body.password && ctx.context.sessionConfig.freshAge !== 0) {\n\t\tconst createdAt = new Date(session.session.createdAt).getTime();\n\t\tconst freshAge = ctx.context.sessionConfig.freshAge * 1e3;\n\t\tif (Date.now() - createdAt >= freshAge) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.SESSION_EXPIRED);\n\t}\n\tconst beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete;\n\tif (beforeDelete) await beforeDelete(session.user, ctx.request);\n\tawait ctx.context.internalAdapter.deleteUser(session.user.id);\n\tawait ctx.context.internalAdapter.deleteSessions(session.user.id);\n\tdeleteSessionCookie(ctx);\n\tconst afterDelete = ctx.context.options.user.deleteUser?.afterDelete;\n\tif (afterDelete) await afterDelete(session.user, ctx.request);\n\treturn ctx.json({\n\t\tsuccess: true,\n\t\tmessage: \"User deleted\"\n\t});\n});\nconst deleteUserCallback = createAuthEndpoint(\"/delete-user/callback\", {\n\tmethod: \"GET\",\n\tquery: z.object({\n\t\ttoken: z.string().meta({ description: \"The token to verify the deletion request\" }),\n\t\tcallbackURL: z.string().meta({ description: \"The URL to redirect to after deletion\" }).optional()\n\t}),\n\tuse: [originCheck((ctx) => ctx.query.callbackURL)],\n\tmetadata: { openapi: {\n\t\tdescription: \"Callback to complete user deletion with verification token\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"User successfully deleted\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tsuccess: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the deletion was successful\"\n\t\t\t\t\t},\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tenum: [\"User deleted\"],\n\t\t\t\t\t\tdescription: \"Confirmation message\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"success\", \"message\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tif (!ctx.context.options.user?.deleteUser?.enabled) {\n\t\tctx.context.logger.error(\"Delete user is disabled. Enable it in the options\");\n\t\tthrow APIError.from(\"NOT_FOUND\", {\n\t\t\tmessage: \"Not found\",\n\t\t\tcode: \"NOT_FOUND\"\n\t\t});\n\t}\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);\n\tconst token = await ctx.context.internalAdapter.findVerificationValue(`delete-account-${ctx.query.token}`);\n\tif (!token || token.expiresAt < /* @__PURE__ */ new Date()) throw APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.INVALID_TOKEN);\n\tif (token.value !== session.user.id) throw APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.INVALID_TOKEN);\n\tconst beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete;\n\tif (beforeDelete) await beforeDelete(session.user, ctx.request);\n\tawait ctx.context.internalAdapter.deleteUser(session.user.id);\n\tawait ctx.context.internalAdapter.deleteSessions(session.user.id);\n\tawait ctx.context.internalAdapter.deleteAccounts(session.user.id);\n\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(`delete-account-${ctx.query.token}`);\n\tdeleteSessionCookie(ctx);\n\tconst afterDelete = ctx.context.options.user.deleteUser?.afterDelete;\n\tif (afterDelete) await afterDelete(session.user, ctx.request);\n\tif (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL || \"/\");\n\treturn ctx.json({\n\t\tsuccess: true,\n\t\tmessage: \"User deleted\"\n\t});\n});\nconst changeEmail = createAuthEndpoint(\"/change-email\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tnewEmail: z.email().meta({ description: \"The new email address to set must be a valid email address\" }),\n\t\tcallbackURL: z.string().meta({ description: \"The URL to redirect to after email verification\" }).optional()\n\t}),\n\tuse: [sensitiveSessionMiddleware],\n\tmetadata: { openapi: {\n\t\toperationId: \"changeEmail\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Email change request processed successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tuser: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/User\"\n\t\t\t\t\t},\n\t\t\t\t\tstatus: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the request was successful\"\n\t\t\t\t\t},\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tenum: [\"Email updated\", \"Verification email sent\"],\n\t\t\t\t\t\tdescription: \"Status message of the email change process\",\n\t\t\t\t\t\tnullable: true\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tif (!ctx.context.options.user?.changeEmail?.enabled) {\n\t\tctx.context.logger.error(\"Change email is disabled.\");\n\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Change email is disabled\" });\n\t}\n\tconst newEmail = ctx.body.newEmail.toLowerCase();\n\tif (newEmail === ctx.context.session.user.email) {\n\t\tctx.context.logger.error(\"Email is the same\");\n\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Email is the same\" });\n\t}\n\t/**\n\t* Early config check: ensure at least one email-change flow is\n\t* available for the current session state. Without this, an\n\t* existing-email lookup would return 200 while a non-existing\n\t* email would later throw 400, leaking email existence.\n\t*/\n\tconst canUpdateWithoutVerification = ctx.context.session.user.emailVerified !== true && ctx.context.options.user.changeEmail.updateEmailWithoutVerification;\n\tconst canSendConfirmation = ctx.context.session.user.emailVerified && ctx.context.options.user.changeEmail.sendChangeEmailConfirmation;\n\tconst canSendVerification = ctx.context.options.emailVerification?.sendVerificationEmail;\n\tif (!canUpdateWithoutVerification && !canSendConfirmation && !canSendVerification) {\n\t\tctx.context.logger.error(\"Verification email isn't enabled.\");\n\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Verification email isn't enabled\" });\n\t}\n\tif (await ctx.context.internalAdapter.findUserByEmail(newEmail)) {\n\t\tawait createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn);\n\t\tctx.context.logger.info(\"Change email attempt for existing email\");\n\t\treturn ctx.json({ status: true });\n\t}\n\t/**\n\t* If the email is not verified, we can update the email if the option is enabled\n\t*/\n\tif (canUpdateWithoutVerification) {\n\t\tawait ctx.context.internalAdapter.updateUserByEmail(ctx.context.session.user.email, { email: newEmail });\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession: ctx.context.session.session,\n\t\t\tuser: {\n\t\t\t\t...ctx.context.session.user,\n\t\t\t\temail: newEmail\n\t\t\t}\n\t\t});\n\t\tif (canSendVerification) {\n\t\t\tconst token = await createEmailVerificationToken(ctx.context.secret, newEmail, void 0, ctx.context.options.emailVerification?.expiresIn);\n\t\t\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n\t\t\tawait ctx.context.runInBackgroundOrAwait(canSendVerification({\n\t\t\t\tuser: {\n\t\t\t\t\t...ctx.context.session.user,\n\t\t\t\t\temail: newEmail\n\t\t\t\t},\n\t\t\t\turl,\n\t\t\t\ttoken\n\t\t\t}, ctx.request));\n\t\t}\n\t\treturn ctx.json({ status: true });\n\t}\n\t/**\n\t* If the email is verified, we need to send a verification email\n\t*/\n\tif (canSendConfirmation) {\n\t\tconst token = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: \"change-email-confirmation\" });\n\t\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n\t\tawait ctx.context.runInBackgroundOrAwait(canSendConfirmation({\n\t\t\tuser: ctx.context.session.user,\n\t\t\tnewEmail,\n\t\t\turl,\n\t\t\ttoken\n\t\t}, ctx.request));\n\t\treturn ctx.json({ status: true });\n\t}\n\tif (!canSendVerification) {\n\t\tctx.context.logger.error(\"Verification email isn't enabled.\");\n\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Verification email isn't enabled\" });\n\t}\n\tconst token = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: \"change-email-verification\" });\n\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n\tawait ctx.context.runInBackgroundOrAwait(canSendVerification({\n\t\tuser: {\n\t\t\t...ctx.context.session.user,\n\t\t\temail: newEmail\n\t\t},\n\t\turl,\n\t\ttoken\n\t}, ctx.request));\n\treturn ctx.json({ status: true });\n});\n//#endregion\nexport { changeEmail, changePassword, deleteUser, deleteUserCallback, setPassword, updateUser };\n", "import { isAPIError } from \"../utils/is-api-error.mjs\";\nimport { hasRequestState, runWithEndpointContext, runWithRequestState } from \"@better-auth/core/context\";\nimport { shouldPublishLog } from \"@better-auth/core/env\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createDefu } from \"defu\";\nimport { ATTR_CONTEXT, ATTR_HOOK_TYPE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID, withSpan } from \"@better-auth/core/instrumentation\";\nimport { kAPIErrorHeaderSymbol, toResponse } from \"better-call\";\n//#region src/api/to-auth-endpoints.ts\nconst defuReplaceArrays = createDefu((obj, key, value) => {\n\tif (Array.isArray(obj[key]) && Array.isArray(value)) {\n\t\tobj[key] = value;\n\t\treturn true;\n\t}\n});\nconst hooksSourceWeakMap = /* @__PURE__ */ new WeakMap();\nfunction getOperationId(endpoint, key) {\n\tif (!endpoint?.options) return key;\n\tconst opts = endpoint.options;\n\treturn opts.operationId ?? opts.metadata?.openapi?.operationId ?? key;\n}\nfunction toAuthEndpoints(endpoints, ctx) {\n\tconst api = {};\n\tfor (const [key, endpoint] of Object.entries(endpoints)) {\n\t\tapi[key] = async (context) => {\n\t\t\tconst operationId = getOperationId(endpoint, key);\n\t\t\tconst endpointMethod = endpoint?.options?.method;\n\t\t\tconst defaultMethod = Array.isArray(endpointMethod) ? endpointMethod[0] : endpointMethod;\n\t\t\tconst run = async () => {\n\t\t\t\tconst authContext = await ctx;\n\t\t\t\tconst methodName = context?.method ?? context?.request?.method ?? defaultMethod ?? \"?\";\n\t\t\t\tconst route = endpoint.path ?? \"/:virtual\";\n\t\t\t\tlet internalContext = {\n\t\t\t\t\t...context,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...authContext,\n\t\t\t\t\t\treturned: void 0,\n\t\t\t\t\t\tresponseHeaders: void 0,\n\t\t\t\t\t\tsession: null\n\t\t\t\t\t},\n\t\t\t\t\tpath: endpoint.path,\n\t\t\t\t\theaders: context?.headers ? new Headers(context?.headers) : void 0\n\t\t\t\t};\n\t\t\t\tconst hasRequest = context?.request instanceof Request;\n\t\t\t\tconst shouldReturnResponse = context?.asResponse ?? hasRequest;\n\t\t\t\treturn withSpan(`${methodName} ${route}`, {\n\t\t\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t\t\t}, async () => runWithEndpointContext(internalContext, async () => {\n\t\t\t\t\tconst { beforeHooks, afterHooks } = getHooks(authContext);\n\t\t\t\t\tconst before = await runBeforeHooks(internalContext, beforeHooks, endpoint, operationId);\n\t\t\t\t\t/**\n\t\t\t\t\t* If `before.context` is returned, it should\n\t\t\t\t\t* get merged with the original context\n\t\t\t\t\t*/\n\t\t\t\t\tif (\"context\" in before && before.context && typeof before.context === \"object\") {\n\t\t\t\t\t\tconst { headers, ...rest } = before.context;\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t* Headers should be merged differently\n\t\t\t\t\t\t* so the hook doesn't override the whole\n\t\t\t\t\t\t* header\n\t\t\t\t\t\t*/\n\t\t\t\t\t\tif (headers) headers.forEach((value, key) => {\n\t\t\t\t\t\t\tinternalContext.headers.set(key, value);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tinternalContext = defuReplaceArrays(rest, internalContext);\n\t\t\t\t\t} else if (before) return shouldReturnResponse ? toResponse(before, { headers: context?.headers }) : context?.returnHeaders ? {\n\t\t\t\t\t\theaders: context?.headers,\n\t\t\t\t\t\tresponse: before\n\t\t\t\t\t} : before;\n\t\t\t\t\tinternalContext.asResponse = false;\n\t\t\t\t\tinternalContext.returnHeaders = true;\n\t\t\t\t\tinternalContext.returnStatus = true;\n\t\t\t\t\tconst result = await runWithEndpointContext(internalContext, () => withSpan(`handler ${route}`, {\n\t\t\t\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t\t\t\t}, () => endpoint(internalContext))).catch((e) => {\n\t\t\t\t\t\tif (isAPIError(e))\n /**\n\t\t\t\t\t\t* API Errors from response are caught\n\t\t\t\t\t\t* and returned to hooks\n\t\t\t\t\t\t*/\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tresponse: e,\n\t\t\t\t\t\t\tstatus: e.statusCode,\n\t\t\t\t\t\t\theaders: e.headers ? new Headers(e.headers) : null\n\t\t\t\t\t\t};\n\t\t\t\t\t\tthrow e;\n\t\t\t\t\t});\n\t\t\t\t\tif (result && result instanceof Response) return result;\n\t\t\t\t\tinternalContext.context.returned = result.response;\n\t\t\t\t\tinternalContext.context.responseHeaders = result.headers;\n\t\t\t\t\tconst after = await runAfterHooks(internalContext, afterHooks, endpoint, operationId);\n\t\t\t\t\tif (after.response) result.response = after.response;\n\t\t\t\t\tif (isAPIError(result.response) && shouldPublishLog(authContext.logger.level, \"debug\")) result.response.stack = result.response.errorStack;\n\t\t\t\t\tif (isAPIError(result.response) && !shouldReturnResponse) throw result.response;\n\t\t\t\t\treturn shouldReturnResponse ? toResponse(result.response, {\n\t\t\t\t\t\theaders: result.headers,\n\t\t\t\t\t\tstatus: result.status\n\t\t\t\t\t}) : context?.returnHeaders ? context?.returnStatus ? {\n\t\t\t\t\t\theaders: result.headers,\n\t\t\t\t\t\tresponse: result.response,\n\t\t\t\t\t\tstatus: result.status\n\t\t\t\t\t} : {\n\t\t\t\t\t\theaders: result.headers,\n\t\t\t\t\t\tresponse: result.response\n\t\t\t\t\t} : context?.returnStatus ? {\n\t\t\t\t\t\tresponse: result.response,\n\t\t\t\t\t\tstatus: result.status\n\t\t\t\t\t} : result.response;\n\t\t\t\t}));\n\t\t\t};\n\t\t\tif (await hasRequestState()) return run();\n\t\t\telse return runWithRequestState(/* @__PURE__ */ new WeakMap(), run);\n\t\t};\n\t\tapi[key].path = endpoint.path;\n\t\tapi[key].options = endpoint.options;\n\t}\n\treturn api;\n}\nasync function runBeforeHooks(context, hooks, endpoint, operationId) {\n\tlet modifiedContext = {};\n\tfor (const hook of hooks) {\n\t\tlet matched = false;\n\t\ttry {\n\t\t\tmatched = hook.matcher(context);\n\t\t} catch (error) {\n\t\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\t\tcontext.context.logger.error(`An error occurred during ${hookSource} hook matcher execution:`, error);\n\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", { message: `An error occurred during hook matcher execution. Check the logs for more details.` });\n\t\t}\n\t\tif (matched) {\n\t\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\t\tconst route = endpoint.path ?? \"/:virtual\";\n\t\t\tconst result = await withSpan(`hook before ${route} ${hookSource}`, {\n\t\t\t\t[ATTR_HOOK_TYPE]: \"before\",\n\t\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t\t[ATTR_CONTEXT]: hookSource,\n\t\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t\t}, () => hook.handler({\n\t\t\t\t...context,\n\t\t\t\treturnHeaders: false\n\t\t\t})).catch((e) => {\n\t\t\t\tif (isAPIError(e) && shouldPublishLog(context.context.logger.level, \"debug\")) e.stack = e.errorStack;\n\t\t\t\tthrow e;\n\t\t\t});\n\t\t\tif (result && typeof result === \"object\") {\n\t\t\t\tif (\"context\" in result && typeof result.context === \"object\") {\n\t\t\t\t\tconst { headers, ...rest } = result.context;\n\t\t\t\t\tif (headers instanceof Headers) if (modifiedContext.headers) headers.forEach((value, key) => {\n\t\t\t\t\t\tmodifiedContext.headers?.set(key, value);\n\t\t\t\t\t});\n\t\t\t\t\telse modifiedContext.headers = headers;\n\t\t\t\t\tmodifiedContext = defuReplaceArrays(rest, modifiedContext);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t}\n\treturn { context: modifiedContext };\n}\nasync function runAfterHooks(context, hooks, endpoint, operationId) {\n\tfor (const hook of hooks) if (hook.matcher(context)) {\n\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\tconst route = endpoint.path ?? \"/:virtual\";\n\t\tconst result = await withSpan(`hook after ${route} ${hookSource}`, {\n\t\t\t[ATTR_HOOK_TYPE]: \"after\",\n\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t[ATTR_CONTEXT]: hookSource,\n\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t}, () => hook.handler(context)).catch((e) => {\n\t\t\tif (isAPIError(e)) {\n\t\t\t\tconst headers = e[kAPIErrorHeaderSymbol];\n\t\t\t\tif (shouldPublishLog(context.context.logger.level, \"debug\")) e.stack = e.errorStack;\n\t\t\t\treturn {\n\t\t\t\t\tresponse: e,\n\t\t\t\t\theaders: headers ? headers : e.headers ? new Headers(e.headers) : null\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow e;\n\t\t});\n\t\tif (result.headers) result.headers.forEach((value, key) => {\n\t\t\tif (!context.context.responseHeaders) context.context.responseHeaders = new Headers({ [key]: value });\n\t\t\telse if (key.toLowerCase() === \"set-cookie\") context.context.responseHeaders.append(key, value);\n\t\t\telse context.context.responseHeaders.set(key, value);\n\t\t});\n\t\tif (result.response) context.context.returned = result.response;\n\t}\n\treturn {\n\t\tresponse: context.context.returned,\n\t\theaders: context.context.responseHeaders\n\t};\n}\nfunction getHooks(authContext) {\n\tconst plugins = authContext.options.plugins || [];\n\tconst beforeHooks = [];\n\tconst afterHooks = [];\n\tconst beforeHookHandler = authContext.options.hooks?.before;\n\tif (beforeHookHandler) {\n\t\thooksSourceWeakMap.set(beforeHookHandler, \"user\");\n\t\tbeforeHooks.push({\n\t\t\tmatcher: () => true,\n\t\t\thandler: beforeHookHandler\n\t\t});\n\t}\n\tconst afterHookHandler = authContext.options.hooks?.after;\n\tif (afterHookHandler) {\n\t\thooksSourceWeakMap.set(afterHookHandler, \"user\");\n\t\tafterHooks.push({\n\t\t\tmatcher: () => true,\n\t\t\thandler: afterHookHandler\n\t\t});\n\t}\n\tconst pluginBeforeHooks = plugins.flatMap((plugin) => (plugin.hooks?.before ?? []).map((h) => {\n\t\thooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`);\n\t\treturn h;\n\t}));\n\tconst pluginAfterHooks = plugins.flatMap((plugin) => (plugin.hooks?.after ?? []).map((h) => {\n\t\thooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`);\n\t\treturn h;\n\t}));\n\t/**\n\t* Add plugin added hooks at last\n\t*/\n\tif (pluginBeforeHooks.length) beforeHooks.push(...pluginBeforeHooks);\n\tif (pluginAfterHooks.length) afterHooks.push(...pluginAfterHooks);\n\treturn {\n\t\tbeforeHooks,\n\t\tafterHooks\n\t};\n}\n//#endregion\nexport { toAuthEndpoints };\n", "import { isAPIError } from \"../utils/is-api-error.mjs\";\nimport { requireOrgRole, requireResourceOwnership } from \"./middlewares/authorization.mjs\";\nimport { formCsrfMiddleware, originCheck, originCheckMiddleware } from \"./middlewares/origin-check.mjs\";\nimport { getIp } from \"../utils/get-request-ip.mjs\";\nimport { onRequestRateLimit, onResponseRateLimit } from \"./rate-limiter/index.mjs\";\nimport { getOAuthState } from \"./state/oauth.mjs\";\nimport { getShouldSkipSessionRefresh, setShouldSkipSessionRefresh } from \"./state/should-session-refresh.mjs\";\nimport { freshSessionMiddleware, getSession, getSessionFromCtx, listSessions, requestOnlySessionMiddleware, revokeOtherSessions, revokeSession, revokeSessions, sensitiveSessionMiddleware, sessionMiddleware } from \"./routes/session.mjs\";\nimport { accountInfo, getAccessToken, linkSocialAccount, listUserAccounts, refreshToken, unlinkAccount } from \"./routes/account.mjs\";\nimport { callbackOAuth } from \"./routes/callback.mjs\";\nimport { createEmailVerificationToken, sendVerificationEmail, sendVerificationEmailFn, verifyEmail } from \"./routes/email-verification.mjs\";\nimport { error } from \"./routes/error.mjs\";\nimport { ok } from \"./routes/ok.mjs\";\nimport { requestPasswordReset, requestPasswordResetCallback, resetPassword, verifyPassword } from \"./routes/password.mjs\";\nimport { signInEmail, signInSocial } from \"./routes/sign-in.mjs\";\nimport { signOut } from \"./routes/sign-out.mjs\";\nimport { signUpEmail } from \"./routes/sign-up.mjs\";\nimport { updateSession } from \"./routes/update-session.mjs\";\nimport { changeEmail, changePassword, deleteUser, deleteUserCallback, setPassword, updateUser } from \"./routes/update-user.mjs\";\nimport { toAuthEndpoints } from \"./to-auth-endpoints.mjs\";\nimport { logger } from \"@better-auth/core/env\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { ATTR_CONTEXT, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, withSpan } from \"@better-auth/core/instrumentation\";\nimport { normalizePathname } from \"@better-auth/core/utils/url\";\nimport { createRouter } from \"better-call\";\nimport { createAuthEndpoint, createAuthMiddleware, optionsMiddleware } from \"@better-auth/core/api\";\n//#region src/api/index.ts\nfunction checkEndpointConflicts(options, logger) {\n\tconst endpointRegistry = /* @__PURE__ */ new Map();\n\toptions.plugins?.forEach((plugin) => {\n\t\tif (plugin.endpoints) {\n\t\t\tfor (const [key, endpoint] of Object.entries(plugin.endpoints)) if (endpoint && \"path\" in endpoint && typeof endpoint.path === \"string\") {\n\t\t\t\tconst path = endpoint.path;\n\t\t\t\tlet methods = [];\n\t\t\t\tif (endpoint.options && \"method\" in endpoint.options) {\n\t\t\t\t\tif (Array.isArray(endpoint.options.method)) methods = endpoint.options.method;\n\t\t\t\t\telse if (typeof endpoint.options.method === \"string\") methods = [endpoint.options.method];\n\t\t\t\t}\n\t\t\t\tif (methods.length === 0) methods = [\"*\"];\n\t\t\t\tif (!endpointRegistry.has(path)) endpointRegistry.set(path, []);\n\t\t\t\tendpointRegistry.get(path).push({\n\t\t\t\t\tpluginId: plugin.id,\n\t\t\t\t\tendpointKey: key,\n\t\t\t\t\tmethods\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n\tconst conflicts = [];\n\tfor (const [path, entries] of endpointRegistry.entries()) if (entries.length > 1) {\n\t\tconst methodMap = /* @__PURE__ */ new Map();\n\t\tlet hasConflict = false;\n\t\tfor (const entry of entries) for (const method of entry.methods) {\n\t\t\tif (!methodMap.has(method)) methodMap.set(method, []);\n\t\t\tmethodMap.get(method).push(entry.pluginId);\n\t\t\tif (methodMap.get(method).length > 1) hasConflict = true;\n\t\t\tif (method === \"*\" && entries.length > 1) hasConflict = true;\n\t\t\telse if (method !== \"*\" && methodMap.has(\"*\")) hasConflict = true;\n\t\t}\n\t\tif (hasConflict) {\n\t\t\tconst uniquePlugins = [...new Set(entries.map((e) => e.pluginId))];\n\t\t\tconst conflictingMethods = [];\n\t\t\tfor (const [method, plugins] of methodMap.entries()) if (plugins.length > 1 || method === \"*\" && entries.length > 1 || method !== \"*\" && methodMap.has(\"*\")) conflictingMethods.push(method);\n\t\t\tconflicts.push({\n\t\t\t\tpath,\n\t\t\t\tplugins: uniquePlugins,\n\t\t\t\tconflictingMethods\n\t\t\t});\n\t\t}\n\t}\n\tif (conflicts.length > 0) {\n\t\tconst conflictMessages = conflicts.map((conflict) => ` - \"${conflict.path}\" [${conflict.conflictingMethods.join(\", \")}] used by plugins: ${conflict.plugins.join(\", \")}`).join(\"\\n\");\n\t\tlogger.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:\n${conflictMessages}\n\nTo resolve this, you can:\n\t1. Use only one of the conflicting plugins\n\t2. Configure the plugins to use different paths (if supported)\n\t3. Ensure plugins use different HTTP methods for the same path\n`);\n\t}\n}\nfunction getEndpoints(ctx, options) {\n\tconst pluginEndpoints = options.plugins?.reduce((acc, plugin) => {\n\t\treturn {\n\t\t\t...acc,\n\t\t\t...plugin.endpoints\n\t\t};\n\t}, {}) ?? {};\n\tconst middlewares = options.plugins?.map((plugin) => plugin.middlewares?.map((m) => {\n\t\tconst middleware = (async (context) => {\n\t\t\tconst authContext = await ctx;\n\t\t\treturn withSpan(`middleware ${m.path} ${plugin.id}`, {\n\t\t\t\t[ATTR_HOOK_TYPE]: \"middleware\",\n\t\t\t\t[ATTR_HTTP_ROUTE]: m.path,\n\t\t\t\t[ATTR_CONTEXT]: `plugin:${plugin.id}`\n\t\t\t}, () => m.middleware({\n\t\t\t\t...context,\n\t\t\t\tcontext: {\n\t\t\t\t\t...authContext,\n\t\t\t\t\t...context.context\n\t\t\t\t}\n\t\t\t}));\n\t\t});\n\t\tmiddleware.options = m.middleware.options;\n\t\treturn {\n\t\t\tpath: m.path,\n\t\t\tmiddleware\n\t\t};\n\t})).filter((plugin) => plugin !== void 0).flat() || [];\n\treturn {\n\t\tapi: toAuthEndpoints({\n\t\t\tsignInSocial: signInSocial(),\n\t\t\tcallbackOAuth,\n\t\t\tgetSession: getSession(),\n\t\t\tsignOut,\n\t\t\tsignUpEmail: signUpEmail(),\n\t\t\tsignInEmail: signInEmail(),\n\t\t\tresetPassword,\n\t\t\tverifyPassword,\n\t\t\tverifyEmail,\n\t\t\tsendVerificationEmail,\n\t\t\tchangeEmail,\n\t\t\tchangePassword,\n\t\t\tsetPassword,\n\t\t\tupdateSession: updateSession(),\n\t\t\tupdateUser: updateUser(),\n\t\t\tdeleteUser,\n\t\t\trequestPasswordReset,\n\t\t\trequestPasswordResetCallback,\n\t\t\tlistSessions: listSessions(),\n\t\t\trevokeSession,\n\t\t\trevokeSessions,\n\t\t\trevokeOtherSessions,\n\t\t\tlinkSocialAccount,\n\t\t\tlistUserAccounts,\n\t\t\tdeleteUserCallback,\n\t\t\tunlinkAccount,\n\t\t\trefreshToken,\n\t\t\tgetAccessToken,\n\t\t\taccountInfo,\n\t\t\t...pluginEndpoints,\n\t\t\tok,\n\t\t\terror\n\t\t}, ctx),\n\t\tmiddlewares\n\t};\n}\nconst router = (ctx, options) => {\n\tconst { api, middlewares } = getEndpoints(ctx, options);\n\tconst basePath = new URL(ctx.baseURL).pathname;\n\treturn createRouter(api, {\n\t\trouterContext: ctx,\n\t\topenapi: { disabled: true },\n\t\tbasePath,\n\t\trouterMiddleware: [{\n\t\t\tpath: \"/**\",\n\t\t\tmiddleware: originCheckMiddleware\n\t\t}, ...middlewares],\n\t\tallowedMediaTypes: [\"application/json\"],\n\t\tskipTrailingSlashes: options.advanced?.skipTrailingSlashes ?? false,\n\t\tasync onRequest(req) {\n\t\t\tconst disabledPaths = ctx.options.disabledPaths || [];\n\t\t\tconst normalizedPath = normalizePathname(req.url, basePath);\n\t\t\tif (disabledPaths.includes(normalizedPath)) return new Response(\"Not Found\", { status: 404 });\n\t\t\tlet currentRequest = req;\n\t\t\tfor (const plugin of ctx.options.plugins || []) if (plugin.onRequest) {\n\t\t\t\tconst response = await withSpan(`onRequest ${plugin.id}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"onRequest\",\n\t\t\t\t\t[ATTR_CONTEXT]: `plugin:${plugin.id}`\n\t\t\t\t}, () => plugin.onRequest(currentRequest, ctx));\n\t\t\t\tif (response && \"response\" in response) return response.response;\n\t\t\t\tif (response && \"request\" in response) currentRequest = response.request;\n\t\t\t}\n\t\t\tconst rateLimitResponse = await onRequestRateLimit(currentRequest, ctx);\n\t\t\tif (rateLimitResponse) return rateLimitResponse;\n\t\t\treturn currentRequest;\n\t\t},\n\t\tasync onResponse(res, req) {\n\t\t\tawait onResponseRateLimit(req, ctx);\n\t\t\tfor (const plugin of ctx.options.plugins || []) if (plugin.onResponse) {\n\t\t\t\tconst response = await withSpan(`onResponse ${plugin.id}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"onResponse\",\n\t\t\t\t\t[ATTR_CONTEXT]: `plugin:${plugin.id}`,\n\t\t\t\t\t[ATTR_HTTP_RESPONSE_STATUS_CODE]: res.status\n\t\t\t\t}, () => plugin.onResponse(res, ctx));\n\t\t\t\tif (response) return response.response;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tonError(e) {\n\t\t\tif (isAPIError(e) && e.status === \"FOUND\") return;\n\t\t\tif (options.onAPIError?.throw) throw e;\n\t\t\tif (options.onAPIError?.onError) {\n\t\t\t\toptions.onAPIError.onError(e, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst optLogLevel = options.logger?.level;\n\t\t\tconst log = optLogLevel === \"error\" || optLogLevel === \"warn\" || optLogLevel === \"debug\" ? logger : void 0;\n\t\t\tif (options.logger?.disabled !== true) {\n\t\t\t\tif (e && typeof e === \"object\" && \"message\" in e && typeof e.message === \"string\") {\n\t\t\t\t\tif (e.message.includes(\"no column\") || e.message.includes(\"column\") || e.message.includes(\"relation\") || e.message.includes(\"table\") || e.message.includes(\"does not exist\")) {\n\t\t\t\t\t\tctx.logger?.error(e.message);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (isAPIError(e)) {\n\t\t\t\t\tif (e.status === \"INTERNAL_SERVER_ERROR\") ctx.logger.error(e.status, e);\n\t\t\t\t\tlog?.error(e.message);\n\t\t\t\t} else ctx.logger?.error(e && typeof e === \"object\" && \"name\" in e ? e.name : \"\", e);\n\t\t\t}\n\t\t}\n\t});\n};\n//#endregion\nexport { APIError, accountInfo, callbackOAuth, changeEmail, changePassword, checkEndpointConflicts, createAuthEndpoint, createAuthMiddleware, createEmailVerificationToken, deleteUser, deleteUserCallback, error, formCsrfMiddleware, freshSessionMiddleware, getAccessToken, getEndpoints, getIp, getOAuthState, getSession, getSessionFromCtx, getShouldSkipSessionRefresh, isAPIError, linkSocialAccount, listSessions, listUserAccounts, ok, optionsMiddleware, originCheck, originCheckMiddleware, refreshToken, requestOnlySessionMiddleware, requestPasswordReset, requestPasswordResetCallback, requireOrgRole, requireResourceOwnership, resetPassword, revokeOtherSessions, revokeSession, revokeSessions, router, sendVerificationEmail, sendVerificationEmailFn, sensitiveSessionMiddleware, sessionMiddleware, setPassword, setShouldSkipSessionRefresh, signInEmail, signInSocial, signOut, signUpEmail, unlinkAccount, updateSession, updateUser, verifyEmail, verifyPassword };\n", "import { getAuthTables } from \"@better-auth/core/db\";\nimport { logger } from \"@better-auth/core/env\";\n//#region src/db/adapter-base.ts\nasync function getBaseAdapter(options, handleDirectDatabase) {\n\tlet adapter;\n\tif (!options.database) {\n\t\tconst tables = getAuthTables(options);\n\t\tconst memoryDB = Object.keys(tables).reduce((acc, key) => {\n\t\t\tacc[key] = [];\n\t\t\treturn acc;\n\t\t}, {});\n\t\tconst { memoryAdapter } = await import(\"@better-auth/memory-adapter\");\n\t\tadapter = memoryAdapter(memoryDB)(options);\n\t} else if (typeof options.database === \"function\") adapter = options.database(options);\n\telse adapter = await handleDirectDatabase(options);\n\tif (!adapter.transaction) {\n\t\tlogger.warn(\"Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.\");\n\t\tadapter.transaction = async (cb) => {\n\t\t\treturn cb(adapter);\n\t\t};\n\t}\n\treturn adapter;\n}\n//#endregion\nexport { getBaseAdapter };\n", "import { getBaseAdapter } from \"./adapter-base.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/db/adapter-kysely.ts\nasync function getAdapter(options) {\n\treturn getBaseAdapter(options, async (opts) => {\n\t\tconst { createKyselyAdapter } = await import(\"../adapters/kysely-adapter/index.mjs\");\n\t\tconst { kysely, databaseType, transaction } = await createKyselyAdapter(opts);\n\t\tif (!kysely) throw new BetterAuthError(\"Failed to initialize database adapter\");\n\t\tconst { kyselyAdapter } = await import(\"../adapters/kysely-adapter/index.mjs\");\n\t\treturn kyselyAdapter(kysely, {\n\t\t\ttype: databaseType || \"sqlite\",\n\t\t\tdebugLogs: opts.database && \"debugLogs\" in opts.database ? opts.database.debugLogs : false,\n\t\t\ttransaction\n\t\t})(opts);\n\t});\n}\n//#endregion\nexport { getAdapter };\n", "import { getAuthTables } from \"@better-auth/core/db\";\n//#region src/db/get-schema.ts\nfunction getSchema(config) {\n\tconst tables = getAuthTables(config);\n\tconst schema = {};\n\tfor (const key in tables) {\n\t\tconst table = tables[key];\n\t\tconst fields = table.fields;\n\t\tconst actualFields = {};\n\t\tObject.entries(fields).forEach(([key, field]) => {\n\t\t\tactualFields[field.fieldName || key] = field;\n\t\t\tif (field.references) {\n\t\t\t\tconst refTable = tables[field.references.model];\n\t\t\t\tif (refTable) actualFields[field.fieldName || key].references = {\n\t\t\t\t\t...field.references,\n\t\t\t\t\tmodel: refTable.modelName,\n\t\t\t\t\tfield: field.references.field\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t\tif (schema[table.modelName]) {\n\t\t\tschema[table.modelName].fields = {\n\t\t\t\t...schema[table.modelName].fields,\n\t\t\t\t...actualFields\n\t\t\t};\n\t\t\tcontinue;\n\t\t}\n\t\tschema[table.modelName] = {\n\t\t\tfields: actualFields,\n\t\t\torder: table.order || Infinity\n\t\t};\n\t}\n\treturn schema;\n}\n//#endregion\nexport { getSchema };\n", "import { getSchema } from \"./get-schema.mjs\";\nimport { getAuthTables } from \"@better-auth/core/db\";\nimport { createLogger } from \"@better-auth/core/env\";\nimport { createKyselyAdapter } from \"@better-auth/kysely-adapter\";\nimport { initGetFieldName, initGetModelName } from \"@better-auth/core/db/adapter\";\nimport { sql } from \"kysely\";\n//#region src/db/get-migration.ts\nconst map = {\n\tpostgres: {\n\t\tstring: [\n\t\t\t\"character varying\",\n\t\t\t\"varchar\",\n\t\t\t\"text\",\n\t\t\t\"uuid\"\n\t\t],\n\t\tnumber: [\n\t\t\t\"int4\",\n\t\t\t\"integer\",\n\t\t\t\"bigint\",\n\t\t\t\"smallint\",\n\t\t\t\"numeric\",\n\t\t\t\"real\",\n\t\t\t\"double precision\"\n\t\t],\n\t\tboolean: [\"bool\", \"boolean\"],\n\t\tdate: [\n\t\t\t\"timestamptz\",\n\t\t\t\"timestamp\",\n\t\t\t\"date\"\n\t\t],\n\t\tjson: [\"json\", \"jsonb\"]\n\t},\n\tmysql: {\n\t\tstring: [\n\t\t\t\"varchar\",\n\t\t\t\"text\",\n\t\t\t\"uuid\"\n\t\t],\n\t\tnumber: [\n\t\t\t\"integer\",\n\t\t\t\"int\",\n\t\t\t\"bigint\",\n\t\t\t\"smallint\",\n\t\t\t\"decimal\",\n\t\t\t\"float\",\n\t\t\t\"double\"\n\t\t],\n\t\tboolean: [\"boolean\", \"tinyint\"],\n\t\tdate: [\n\t\t\t\"timestamp\",\n\t\t\t\"datetime\",\n\t\t\t\"date\"\n\t\t],\n\t\tjson: [\"json\"]\n\t},\n\tsqlite: {\n\t\tstring: [\"TEXT\"],\n\t\tnumber: [\"INTEGER\", \"REAL\"],\n\t\tboolean: [\"INTEGER\", \"BOOLEAN\"],\n\t\tdate: [\"DATE\", \"INTEGER\"],\n\t\tjson: [\"TEXT\"]\n\t},\n\tmssql: {\n\t\tstring: [\n\t\t\t\"varchar\",\n\t\t\t\"nvarchar\",\n\t\t\t\"uniqueidentifier\"\n\t\t],\n\t\tnumber: [\n\t\t\t\"int\",\n\t\t\t\"bigint\",\n\t\t\t\"smallint\",\n\t\t\t\"decimal\",\n\t\t\t\"float\",\n\t\t\t\"double\"\n\t\t],\n\t\tboolean: [\"bit\", \"smallint\"],\n\t\tdate: [\n\t\t\t\"datetime2\",\n\t\t\t\"date\",\n\t\t\t\"datetime\"\n\t\t],\n\t\tjson: [\"varchar\", \"nvarchar\"]\n\t}\n};\nfunction matchType(columnDataType, fieldType, dbType) {\n\tfunction normalize(type) {\n\t\treturn type.toLowerCase().split(\"(\")[0].trim();\n\t}\n\tif (fieldType === \"string[]\" || fieldType === \"number[]\") return columnDataType.toLowerCase().includes(\"json\");\n\tconst types = map[dbType];\n\treturn (Array.isArray(fieldType) ? types[\"string\"].map((t) => t.toLowerCase()) : types[fieldType].map((t) => t.toLowerCase())).includes(normalize(columnDataType));\n}\n/**\n* Get the current PostgreSQL schema (search_path) for the database connection\n* Returns the first schema in the search_path, defaulting to 'public' if not found\n*/\nasync function getPostgresSchema(db) {\n\ttry {\n\t\tconst result = await sql`SHOW search_path`.execute(db);\n\t\tconst searchPath = result.rows[0]?.search_path ?? result.rows[0]?.searchPath;\n\t\tif (searchPath) return searchPath.split(\",\").map((s) => s.trim()).map((s) => s.replace(/^[\"']|[\"']$/g, \"\")).filter((s) => !s.startsWith(\"$\") && !s.startsWith(\"\\\\$\"))[0] || \"public\";\n\t} catch {}\n\treturn \"public\";\n}\nasync function getMigrations(config) {\n\tconst betterAuthSchema = getSchema(config);\n\tconst logger = createLogger(config.logger);\n\tlet { kysely: db, databaseType: dbType } = await createKyselyAdapter(config);\n\tif (!dbType) {\n\t\tlogger.warn(\"Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.\");\n\t\tdbType = \"sqlite\";\n\t}\n\tif (!db) {\n\t\tlogger.error(\"Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter.\");\n\t\tprocess.exit(1);\n\t}\n\tlet currentSchema = \"public\";\n\tif (dbType === \"postgres\") {\n\t\tcurrentSchema = await getPostgresSchema(db);\n\t\tlogger.debug(`PostgreSQL migration: Using schema '${currentSchema}' (from search_path)`);\n\t\ttry {\n\t\t\tconst schemaCheck = await sql`\n\t\t\t\tSELECT schema_name\n\t\t\t\tFROM information_schema.schemata\n\t\t\t\tWHERE schema_name = ${currentSchema}\n\t\t\t`.execute(db);\n\t\t\tif (!(schemaCheck.rows[0]?.schema_name ?? schemaCheck.rows[0]?.schemaName)) logger.warn(`Schema '${currentSchema}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`);\n\t\t} catch (error) {\n\t\t\tlogger.debug(`Could not verify schema existence: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\tconst allTableMetadata = await db.introspection.getTables();\n\tlet tableMetadata = allTableMetadata;\n\tif (dbType === \"postgres\") try {\n\t\tconst tablesInSchema = await sql`\n\t\t\t\tSELECT table_name\n\t\t\t\tFROM information_schema.tables\n\t\t\t\tWHERE table_schema = ${currentSchema}\n\t\t\t\tAND table_type = 'BASE TABLE'\n\t\t\t`.execute(db);\n\t\tconst tableNamesInSchema = new Set(tablesInSchema.rows.map((row) => row.table_name ?? row.tableName));\n\t\ttableMetadata = allTableMetadata.filter((table) => table.schema === currentSchema && tableNamesInSchema.has(table.name));\n\t\tlogger.debug(`Found ${tableMetadata.length} table(s) in schema '${currentSchema}': ${tableMetadata.map((t) => t.name).join(\", \") || \"(none)\"}`);\n\t} catch (error) {\n\t\tlogger.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tconst toBeCreated = [];\n\tconst toBeAdded = [];\n\tfor (const [key, value] of Object.entries(betterAuthSchema)) {\n\t\tconst table = tableMetadata.find((t) => t.name === key);\n\t\tif (!table) {\n\t\t\tconst tIndex = toBeCreated.findIndex((t) => t.table === key);\n\t\t\tconst tableData = {\n\t\t\t\ttable: key,\n\t\t\t\tfields: value.fields,\n\t\t\t\torder: value.order || Infinity\n\t\t\t};\n\t\t\tconst insertIndex = toBeCreated.findIndex((t) => (t.order || Infinity) > tableData.order);\n\t\t\tif (insertIndex === -1) if (tIndex === -1) toBeCreated.push(tableData);\n\t\t\telse toBeCreated[tIndex].fields = {\n\t\t\t\t...toBeCreated[tIndex].fields,\n\t\t\t\t...value.fields\n\t\t\t};\n\t\t\telse toBeCreated.splice(insertIndex, 0, tableData);\n\t\t\tcontinue;\n\t\t}\n\t\tconst toBeAddedFields = {};\n\t\tfor (const [fieldName, field] of Object.entries(value.fields)) {\n\t\t\tconst column = table.columns.find((c) => c.name === fieldName);\n\t\t\tif (!column) {\n\t\t\t\ttoBeAddedFields[fieldName] = field;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (matchType(column.dataType, field.type, dbType)) continue;\n\t\t\telse logger.warn(`Field ${fieldName} in table ${key} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`);\n\t\t}\n\t\tif (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({\n\t\t\ttable: key,\n\t\t\tfields: toBeAddedFields,\n\t\t\torder: value.order || Infinity\n\t\t});\n\t}\n\tconst migrations = [];\n\tconst useUUIDs = config.advanced?.database?.generateId === \"uuid\";\n\tconst useNumberId = config.advanced?.database?.generateId === \"serial\";\n\tfunction getType(field, fieldName) {\n\t\tconst type = field.type;\n\t\tconst provider = dbType || \"sqlite\";\n\t\tconst typeMap = {\n\t\t\tstring: {\n\t\t\t\tsqlite: \"text\",\n\t\t\t\tpostgres: \"text\",\n\t\t\t\tmysql: field.unique ? \"varchar(255)\" : field.references ? \"varchar(36)\" : field.sortable ? \"varchar(255)\" : field.index ? \"varchar(255)\" : \"text\",\n\t\t\t\tmssql: field.unique || field.sortable ? \"varchar(255)\" : field.references ? \"varchar(36)\" : \"varchar(8000)\"\n\t\t\t},\n\t\t\tboolean: {\n\t\t\t\tsqlite: \"integer\",\n\t\t\t\tpostgres: \"boolean\",\n\t\t\t\tmysql: \"boolean\",\n\t\t\t\tmssql: \"smallint\"\n\t\t\t},\n\t\t\tnumber: {\n\t\t\t\tsqlite: field.bigint ? \"bigint\" : \"integer\",\n\t\t\t\tpostgres: field.bigint ? \"bigint\" : \"integer\",\n\t\t\t\tmysql: field.bigint ? \"bigint\" : \"integer\",\n\t\t\t\tmssql: field.bigint ? \"bigint\" : \"integer\"\n\t\t\t},\n\t\t\tdate: {\n\t\t\t\tsqlite: \"date\",\n\t\t\t\tpostgres: \"timestamptz\",\n\t\t\t\tmysql: \"timestamp(3)\",\n\t\t\t\tmssql: sql`datetime2(3)`\n\t\t\t},\n\t\t\tjson: {\n\t\t\t\tsqlite: \"text\",\n\t\t\t\tpostgres: \"jsonb\",\n\t\t\t\tmysql: \"json\",\n\t\t\t\tmssql: \"varchar(8000)\"\n\t\t\t},\n\t\t\tid: {\n\t\t\t\tpostgres: useNumberId ? sql`integer GENERATED BY DEFAULT AS IDENTITY` : useUUIDs ? \"uuid\" : \"text\",\n\t\t\t\tmysql: useNumberId ? \"integer\" : useUUIDs ? \"varchar(36)\" : \"varchar(36)\",\n\t\t\t\tmssql: useNumberId ? \"integer\" : useUUIDs ? \"varchar(36)\" : \"varchar(36)\",\n\t\t\t\tsqlite: useNumberId ? \"integer\" : \"text\"\n\t\t\t},\n\t\t\tforeignKeyId: {\n\t\t\t\tpostgres: useNumberId ? \"integer\" : useUUIDs ? \"uuid\" : \"text\",\n\t\t\t\tmysql: useNumberId ? \"integer\" : useUUIDs ? \"varchar(36)\" : \"varchar(36)\",\n\t\t\t\tmssql: useNumberId ? \"integer\" : useUUIDs ? \"varchar(36)\" : \"varchar(36)\",\n\t\t\t\tsqlite: useNumberId ? \"integer\" : \"text\"\n\t\t\t},\n\t\t\t\"string[]\": {\n\t\t\t\tsqlite: \"text\",\n\t\t\t\tpostgres: \"jsonb\",\n\t\t\t\tmysql: \"json\",\n\t\t\t\tmssql: \"varchar(8000)\"\n\t\t\t},\n\t\t\t\"number[]\": {\n\t\t\t\tsqlite: \"text\",\n\t\t\t\tpostgres: \"jsonb\",\n\t\t\t\tmysql: \"json\",\n\t\t\t\tmssql: \"varchar(8000)\"\n\t\t\t}\n\t\t};\n\t\tif (fieldName === \"id\" || field.references?.field === \"id\") {\n\t\t\tif (fieldName === \"id\") return typeMap.id[provider];\n\t\t\treturn typeMap.foreignKeyId[provider];\n\t\t}\n\t\tif (Array.isArray(type)) return \"text\";\n\t\tif (!(type in typeMap)) throw new Error(`Unsupported field type '${String(type)}' for field '${fieldName}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: \"string\") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);\n\t\treturn typeMap[type][provider];\n\t}\n\tconst getModelName = initGetModelName({\n\t\tschema: getAuthTables(config),\n\t\tusePlural: false\n\t});\n\tconst getFieldName = initGetFieldName({\n\t\tschema: getAuthTables(config),\n\t\tusePlural: false\n\t});\n\tfunction getReferencePath(model, field) {\n\t\ttry {\n\t\t\treturn `${getModelName(model)}.${getFieldName({\n\t\t\t\tmodel,\n\t\t\t\tfield\n\t\t\t})}`;\n\t\t} catch {\n\t\t\treturn `${model}.${field}`;\n\t\t}\n\t}\n\tif (toBeAdded.length) for (const table of toBeAdded) for (const [fieldName, field] of Object.entries(table.fields)) {\n\t\tconst type = getType(field, fieldName);\n\t\tconst builder = db.schema.alterTable(table.table);\n\t\tif (field.index) {\n\t\t\tconst indexName = `${table.table}_${fieldName}_${field.unique ? \"uidx\" : \"idx\"}`;\n\t\t\tconst indexBuilder = db.schema.createIndex(indexName).on(table.table).columns([fieldName]);\n\t\t\tmigrations.push(field.unique ? indexBuilder.unique() : indexBuilder);\n\t\t}\n\t\tconst built = builder.addColumn(fieldName, type, (col) => {\n\t\t\tcol = field.required !== false ? col.notNull() : col;\n\t\t\tif (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || \"cascade\");\n\t\t\tif (field.unique) col = col.unique();\n\t\t\tif (field.type === \"date\" && typeof field.defaultValue === \"function\" && (dbType === \"postgres\" || dbType === \"mysql\" || dbType === \"mssql\")) if (dbType === \"mysql\") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`);\n\t\t\telse col = col.defaultTo(sql`CURRENT_TIMESTAMP`);\n\t\t\treturn col;\n\t\t});\n\t\tmigrations.push(built);\n\t}\n\tconst toBeIndexed = [];\n\tif (toBeCreated.length) for (const table of toBeCreated) {\n\t\tconst idType = getType({ type: useNumberId ? \"number\" : \"string\" }, \"id\");\n\t\tlet dbT = db.schema.createTable(table.table).addColumn(\"id\", idType, (col) => {\n\t\t\tif (useNumberId) {\n\t\t\t\tif (dbType === \"postgres\") return col.primaryKey().notNull();\n\t\t\t\telse if (dbType === \"sqlite\") return col.primaryKey().notNull();\n\t\t\t\telse if (dbType === \"mssql\") return col.identity().primaryKey().notNull();\n\t\t\t\treturn col.autoIncrement().primaryKey().notNull();\n\t\t\t}\n\t\t\tif (useUUIDs) {\n\t\t\t\tif (dbType === \"postgres\") return col.primaryKey().defaultTo(sql`pg_catalog.gen_random_uuid()`).notNull();\n\t\t\t\treturn col.primaryKey().notNull();\n\t\t\t}\n\t\t\treturn col.primaryKey().notNull();\n\t\t});\n\t\tfor (const [fieldName, field] of Object.entries(table.fields)) {\n\t\t\tconst type = getType(field, fieldName);\n\t\t\tdbT = dbT.addColumn(fieldName, type, (col) => {\n\t\t\t\tcol = field.required !== false ? col.notNull() : col;\n\t\t\t\tif (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || \"cascade\");\n\t\t\t\tif (field.unique) col = col.unique();\n\t\t\t\tif (field.type === \"date\" && typeof field.defaultValue === \"function\" && (dbType === \"postgres\" || dbType === \"mysql\" || dbType === \"mssql\")) if (dbType === \"mysql\") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`);\n\t\t\t\telse col = col.defaultTo(sql`CURRENT_TIMESTAMP`);\n\t\t\t\treturn col;\n\t\t\t});\n\t\t\tif (field.index) {\n\t\t\t\tconst builder = db.schema.createIndex(`${table.table}_${fieldName}_${field.unique ? \"uidx\" : \"idx\"}`).on(table.table).columns([fieldName]);\n\t\t\t\ttoBeIndexed.push(field.unique ? builder.unique() : builder);\n\t\t\t}\n\t\t}\n\t\tmigrations.push(dbT);\n\t}\n\tif (toBeIndexed.length) for (const index of toBeIndexed) migrations.push(index);\n\tasync function runMigrations() {\n\t\tfor (const migration of migrations) await migration.execute();\n\t}\n\tasync function compileMigrations() {\n\t\treturn migrations.map((m) => m.compile().sql).join(\";\\n\\n\") + \";\";\n\t}\n\treturn {\n\t\ttoBeCreated,\n\t\ttoBeAdded,\n\t\trunMigrations,\n\t\tcompileMigrations\n\t};\n}\n//#endregion\nexport { getMigrations, matchType };\n", "//#region src/utils/constants.ts\nconst DEFAULT_SECRET = \"better-auth-secret-12345678901234567890\";\n//#endregion\nexport { DEFAULT_SECRET };\n", "import \"../utils/constants.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/context/secret-utils.ts\n/**\n* Estimates the entropy of a string in bits.\n* This is a simple approximation that helps detect low-entropy secrets.\n*/\nfunction estimateEntropy(str) {\n\tconst unique = new Set(str).size;\n\tif (unique === 0) return 0;\n\treturn Math.log2(Math.pow(unique, str.length));\n}\nfunction parseSecretsEnv(envValue) {\n\tif (!envValue) return null;\n\treturn envValue.split(\",\").map((entry) => {\n\t\tentry = entry.trim();\n\t\tconst colonIdx = entry.indexOf(\":\");\n\t\tif (colonIdx === -1) throw new BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry: \"${entry}\". Expected format: \":\"`);\n\t\tconst version = parseInt(entry.slice(0, colonIdx), 10);\n\t\tif (!Number.isInteger(version) || version < 0) throw new BetterAuthError(`Invalid version in BETTER_AUTH_SECRETS: \"${entry.slice(0, colonIdx)}\". Version must be a non-negative integer.`);\n\t\tconst value = entry.slice(colonIdx + 1).trim();\n\t\tif (!value) throw new BetterAuthError(`Empty secret value for version ${version} in BETTER_AUTH_SECRETS.`);\n\t\treturn {\n\t\t\tversion,\n\t\t\tvalue\n\t\t};\n\t});\n}\nfunction validateSecretsArray(secrets, logger) {\n\tif (secrets.length === 0) throw new BetterAuthError(\"`secrets` array must contain at least one entry.\");\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const s of secrets) {\n\t\tconst version = parseInt(String(s.version), 10);\n\t\tif (!Number.isInteger(version) || version < 0 || String(version) !== String(s.version).trim()) throw new BetterAuthError(`Invalid version ${s.version} in \\`secrets\\`. Version must be a non-negative integer.`);\n\t\tif (!s.value) throw new BetterAuthError(`Empty secret value for version ${version} in \\`secrets\\`.`);\n\t\tif (seen.has(version)) throw new BetterAuthError(`Duplicate version ${version} in \\`secrets\\`. Each version must be unique.`);\n\t\tseen.add(version);\n\t}\n\tconst current = secrets[0];\n\tif (current.value.length < 32) logger.warn(`[better-auth] Warning: the current secret (version ${current.version}) should be at least 32 characters long for adequate security.`);\n\tif (estimateEntropy(current.value) < 120) logger.warn(\"[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.\");\n}\nfunction buildSecretConfig(secrets, legacySecret) {\n\tconst keys = /* @__PURE__ */ new Map();\n\tfor (const s of secrets) keys.set(parseInt(String(s.version), 10), s.value);\n\treturn {\n\t\tkeys,\n\t\tcurrentVersion: parseInt(String(secrets[0].version), 10),\n\t\tlegacySecret: legacySecret && legacySecret !== \"better-auth-secret-12345678901234567890\" ? legacySecret : void 0\n\t};\n}\n//#endregion\nexport { buildSecretConfig, parseSecretsEnv, validateSecretsArray };\n", "import { getBaseURL, isDynamicBaseURLConfig } from \"../utils/url.mjs\";\nimport { matchesOriginPattern } from \"../auth/trusted-origins.mjs\";\nimport { createInternalAdapter } from \"../db/internal-adapter.mjs\";\nimport { isPromise } from \"../utils/is-promise.mjs\";\nimport { getInternalPlugins, getTrustedOrigins, getTrustedProviders, runPluginInit } from \"./helpers.mjs\";\nimport { hashPassword, verifyPassword } from \"../crypto/password.mjs\";\nimport { createCookieGetter, getCookies } from \"../cookies/index.mjs\";\nimport { checkPassword } from \"../utils/password.mjs\";\nimport { checkEndpointConflicts } from \"../api/index.mjs\";\nimport { DEFAULT_SECRET } from \"../utils/constants.mjs\";\nimport { buildSecretConfig, parseSecretsEnv, validateSecretsArray } from \"./secret-utils.mjs\";\nimport { getBetterAuthVersion } from \"@better-auth/core/context\";\nimport { getAuthTables } from \"@better-auth/core/db\";\nimport { createLogger, env, isProduction, isTest } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { generateId } from \"@better-auth/core/utils/id\";\nimport { socialProviders } from \"@better-auth/core/social-providers\";\nimport { createTelemetry } from \"@better-auth/telemetry\";\nimport defu$1 from \"defu\";\n//#region src/context/create-context.ts\n/**\n* Estimates the entropy of a string in bits.\n* This is a simple approximation that helps detect low-entropy secrets.\n*/\nfunction estimateEntropy(str) {\n\tconst unique = new Set(str).size;\n\tif (unique === 0) return 0;\n\treturn Math.log2(Math.pow(unique, str.length));\n}\n/**\n* Validates that the secret meets minimum security requirements.\n* Throws BetterAuthError if the secret is invalid.\n* Skips validation for DEFAULT_SECRET in test environments only.\n* Only throws for DEFAULT_SECRET in production environment.\n*/\nfunction validateSecret(secret, logger) {\n\tconst isDefaultSecret = secret === DEFAULT_SECRET;\n\tif (isTest()) return;\n\tif (isDefaultSecret && isProduction) throw new BetterAuthError(\"You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.\");\n\tif (!secret) throw new BetterAuthError(\"BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).\");\n\tif (secret.length < 32) logger.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with \\`npx auth secret\\` or \\`openssl rand -base64 32\\`.`);\n\tif (estimateEntropy(secret) < 120) logger.warn(\"[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.\");\n}\nasync function createAuthContext(adapter, options, getDatabaseType) {\n\tif (!options.database) options = defu$1(options, {\n\t\tsession: { cookieCache: {\n\t\t\tenabled: true,\n\t\t\tstrategy: \"jwe\",\n\t\t\trefreshCache: true,\n\t\t\tmaxAge: options.session?.expiresIn || 3600 * 24 * 7\n\t\t} },\n\t\taccount: {\n\t\t\tstoreStateStrategy: \"cookie\",\n\t\t\tstoreAccountCookie: true\n\t\t}\n\t});\n\tconst plugins = options.plugins || [];\n\tconst internalPlugins = getInternalPlugins(options);\n\tconst logger = createLogger(options.logger);\n\tconst isDynamicConfig = isDynamicBaseURLConfig(options.baseURL);\n\tif (isDynamicBaseURLConfig(options.baseURL)) {\n\t\tconst { allowedHosts } = options.baseURL;\n\t\tif (!allowedHosts || allowedHosts.length === 0) throw new BetterAuthError(\"baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., [\\\"myapp.com\\\", \\\"*.vercel.app\\\"]).\");\n\t}\n\tconst baseURL = isDynamicConfig ? void 0 : getBaseURL(typeof options.baseURL === \"string\" ? options.baseURL : void 0, options.basePath);\n\tif (!baseURL && !isDynamicConfig) logger.warn(`[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_URL environment variable. Without this, callbacks and redirects may not work correctly.`);\n\tif (adapter.id === \"memory\" && options.advanced?.database?.generateId === false) logger.error(`[better-auth] Misconfiguration detected.\nYou are using the memory DB with generateId: false.\nThis will cause no id to be generated for any model.\nMost of the features of Better Auth will not work correctly.`);\n\tconst secretsArray = options.secrets ?? parseSecretsEnv(env.BETTER_AUTH_SECRETS);\n\tconst legacySecret = options.secret || env.BETTER_AUTH_SECRET || env.AUTH_SECRET || \"\";\n\tlet secret;\n\tlet secretConfig;\n\tif (secretsArray) {\n\t\tvalidateSecretsArray(secretsArray, logger);\n\t\tsecret = secretsArray[0].value;\n\t\tsecretConfig = buildSecretConfig(secretsArray, legacySecret);\n\t} else {\n\t\tsecret = legacySecret || \"better-auth-secret-12345678901234567890\";\n\t\tvalidateSecret(secret, logger);\n\t\tsecretConfig = secret;\n\t}\n\toptions = {\n\t\t...options,\n\t\tsecret,\n\t\tbaseURL: isDynamicConfig ? options.baseURL : baseURL ? new URL(baseURL).origin : \"\",\n\t\tbasePath: options.basePath || \"/api/auth\",\n\t\tplugins: plugins.concat(internalPlugins)\n\t};\n\tcheckEndpointConflicts(options, logger);\n\tconst cookies = getCookies(options);\n\tconst tables = getAuthTables(options);\n\tconst providers = (await Promise.all(Object.entries(options.socialProviders || {}).map(async ([key, originalConfig]) => {\n\t\tconst config = typeof originalConfig === \"function\" ? await originalConfig() : originalConfig;\n\t\tif (config == null) return null;\n\t\tif (config.enabled === false) return null;\n\t\tif (!config.clientId) logger.warn(`Social provider ${key} is missing clientId or clientSecret`);\n\t\tconst provider = socialProviders[key](config);\n\t\tprovider.disableImplicitSignUp = config.disableImplicitSignUp;\n\t\treturn provider;\n\t}))).filter((x) => x !== null);\n\tconst generateIdFunc = ({ model, size }) => {\n\t\tif (typeof options.advanced?.generateId === \"function\") return options.advanced.generateId({\n\t\t\tmodel,\n\t\t\tsize\n\t\t});\n\t\tconst dbGenerateId = options?.advanced?.database?.generateId;\n\t\tif (typeof dbGenerateId === \"function\") return dbGenerateId({\n\t\t\tmodel,\n\t\t\tsize\n\t\t});\n\t\tif (dbGenerateId === \"uuid\") return crypto.randomUUID();\n\t\tif (dbGenerateId === \"serial\" || dbGenerateId === false) return false;\n\t\treturn generateId(size);\n\t};\n\tconst { publish } = await createTelemetry(options, {\n\t\tadapter: adapter.id,\n\t\tdatabase: typeof options.database === \"function\" ? \"adapter\" : getDatabaseType(options.database)\n\t});\n\tconst pluginIds = new Set(options.plugins.map((p) => p.id));\n\tconst getPluginFn = (id) => options.plugins.find((p) => p.id === id) ?? null;\n\tconst hasPluginFn = (id) => pluginIds.has(id);\n\tconst trustedOrigins = await getTrustedOrigins(options);\n\tconst trustedProviders = await getTrustedProviders(options);\n\tconst ctx = {\n\t\tappName: options.appName || \"Better Auth\",\n\t\tbaseURL: baseURL || \"\",\n\t\tversion: getBetterAuthVersion(),\n\t\tsocialProviders: providers,\n\t\toptions,\n\t\toauthConfig: {\n\t\t\tstoreStateStrategy: options.account?.storeStateStrategy || (options.database ? \"database\" : \"cookie\"),\n\t\t\tskipStateCookieCheck: !!options.account?.skipStateCookieCheck\n\t\t},\n\t\ttables,\n\t\ttrustedOrigins,\n\t\ttrustedProviders,\n\t\tisTrustedOrigin(url, settings) {\n\t\t\treturn this.trustedOrigins.some((origin) => matchesOriginPattern(url, origin, settings));\n\t\t},\n\t\tsessionConfig: {\n\t\t\tupdateAge: options.session?.updateAge !== void 0 ? options.session.updateAge : 1440 * 60,\n\t\t\texpiresIn: options.session?.expiresIn || 3600 * 24 * 7,\n\t\t\tfreshAge: options.session?.freshAge === void 0 ? 3600 * 24 : options.session.freshAge,\n\t\t\tcookieRefreshCache: (() => {\n\t\t\t\tconst refreshCache = options.session?.cookieCache?.refreshCache;\n\t\t\t\tconst maxAge = options.session?.cookieCache?.maxAge || 300;\n\t\t\t\tif ((!!options.database || !!options.secondaryStorage) && refreshCache) {\n\t\t\t\t\tlogger.warn(\"[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` \u2014 remove it from your config to silence this warning.\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (refreshCache === false || refreshCache === void 0) return false;\n\t\t\t\tif (refreshCache === true) return {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tupdateAge: Math.floor(maxAge * .2)\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tupdateAge: refreshCache.updateAge !== void 0 ? refreshCache.updateAge : Math.floor(maxAge * .2)\n\t\t\t\t};\n\t\t\t})()\n\t\t},\n\t\tsecret,\n\t\tsecretConfig,\n\t\trateLimit: {\n\t\t\t...options.rateLimit,\n\t\t\tenabled: options.rateLimit?.enabled ?? isProduction,\n\t\t\twindow: options.rateLimit?.window || 10,\n\t\t\tmax: options.rateLimit?.max || 100,\n\t\t\tstorage: options.rateLimit?.storage || (options.secondaryStorage ? \"secondary-storage\" : \"memory\")\n\t\t},\n\t\tauthCookies: cookies,\n\t\tlogger,\n\t\tgenerateId: generateIdFunc,\n\t\tsession: null,\n\t\tsecondaryStorage: options.secondaryStorage,\n\t\tpassword: {\n\t\t\thash: options.emailAndPassword?.password?.hash || hashPassword,\n\t\t\tverify: options.emailAndPassword?.password?.verify || verifyPassword,\n\t\t\tconfig: {\n\t\t\t\tminPasswordLength: options.emailAndPassword?.minPasswordLength || 8,\n\t\t\t\tmaxPasswordLength: options.emailAndPassword?.maxPasswordLength || 128\n\t\t\t},\n\t\t\tcheckPassword\n\t\t},\n\t\tsetNewSession(session) {\n\t\t\tthis.newSession = session;\n\t\t},\n\t\tnewSession: null,\n\t\tadapter,\n\t\tinternalAdapter: createInternalAdapter(adapter, {\n\t\t\toptions,\n\t\t\tlogger,\n\t\t\thooks: options.databaseHooks ? [{\n\t\t\t\tsource: \"user\",\n\t\t\t\thooks: options.databaseHooks\n\t\t\t}] : [],\n\t\t\tgenerateId: generateIdFunc\n\t\t}),\n\t\tcreateAuthCookie: createCookieGetter(options),\n\t\tasync runMigrations() {\n\t\t\tthrow new BetterAuthError(\"runMigrations will be set by the specific init implementation\");\n\t\t},\n\t\tpublishTelemetry: publish,\n\t\tskipCSRFCheck: !!options.advanced?.disableCSRFCheck,\n\t\tskipOriginCheck: options.advanced?.disableOriginCheck !== void 0 ? options.advanced.disableOriginCheck : isTest() ? true : false,\n\t\trunInBackground: options.advanced?.backgroundTasks?.handler ?? ((p) => {\n\t\t\tp.catch(() => {});\n\t\t}),\n\t\tasync runInBackgroundOrAwait(promise) {\n\t\t\ttry {\n\t\t\t\tif (options.advanced?.backgroundTasks?.handler) {\n\t\t\t\t\tif (promise instanceof Promise) options.advanced.backgroundTasks.handler(promise.catch((e) => {\n\t\t\t\t\t\tlogger.error(\"Failed to run background task:\", e);\n\t\t\t\t\t}));\n\t\t\t\t} else await promise;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error(\"Failed to run background task:\", e);\n\t\t\t}\n\t\t},\n\t\tgetPlugin: getPluginFn,\n\t\thasPlugin: hasPluginFn\n\t};\n\tconst initOrPromise = runPluginInit(ctx);\n\tif (isPromise(initOrPromise)) await initOrPromise;\n\treturn ctx;\n}\n//#endregion\nexport { createAuthContext };\n", "import fs from \"node:fs\";\nimport fsPromises from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { ENV, env, getBooleanEnvVar, getEnvVar, isTest, logger } from \"@better-auth/core/env\";\nimport { betterFetch } from \"@better-fetch/fetch\";\nimport { base64 } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\nimport { createRandomStringGenerator } from \"@better-auth/utils/random\";\n//#region src/detectors/detect-auth-config.ts\nasync function getTelemetryAuthConfig(options, context) {\n\treturn {\n\t\tdatabase: context?.database,\n\t\tadapter: context?.adapter,\n\t\temailVerification: {\n\t\t\tsendVerificationEmail: !!options.emailVerification?.sendVerificationEmail,\n\t\t\tsendOnSignUp: !!options.emailVerification?.sendOnSignUp,\n\t\t\tsendOnSignIn: !!options.emailVerification?.sendOnSignIn,\n\t\t\tautoSignInAfterVerification: !!options.emailVerification?.autoSignInAfterVerification,\n\t\t\texpiresIn: options.emailVerification?.expiresIn,\n\t\t\tbeforeEmailVerification: !!options.emailVerification?.beforeEmailVerification,\n\t\t\tafterEmailVerification: !!options.emailVerification?.afterEmailVerification\n\t\t},\n\t\temailAndPassword: {\n\t\t\tenabled: !!options.emailAndPassword?.enabled,\n\t\t\tdisableSignUp: !!options.emailAndPassword?.disableSignUp,\n\t\t\trequireEmailVerification: !!options.emailAndPassword?.requireEmailVerification,\n\t\t\tmaxPasswordLength: options.emailAndPassword?.maxPasswordLength,\n\t\t\tminPasswordLength: options.emailAndPassword?.minPasswordLength,\n\t\t\tsendResetPassword: !!options.emailAndPassword?.sendResetPassword,\n\t\t\tresetPasswordTokenExpiresIn: options.emailAndPassword?.resetPasswordTokenExpiresIn,\n\t\t\tonPasswordReset: !!options.emailAndPassword?.onPasswordReset,\n\t\t\tpassword: {\n\t\t\t\thash: !!options.emailAndPassword?.password?.hash,\n\t\t\t\tverify: !!options.emailAndPassword?.password?.verify\n\t\t\t},\n\t\t\tautoSignIn: !!options.emailAndPassword?.autoSignIn,\n\t\t\trevokeSessionsOnPasswordReset: !!options.emailAndPassword?.revokeSessionsOnPasswordReset\n\t\t},\n\t\tsocialProviders: await Promise.all(Object.keys(options.socialProviders || {}).map(async (key) => {\n\t\t\tconst p = options.socialProviders?.[key];\n\t\t\tif (!p) return {};\n\t\t\tconst provider = typeof p === \"function\" ? await p() : p;\n\t\t\treturn {\n\t\t\t\tid: key,\n\t\t\t\tmapProfileToUser: !!provider.mapProfileToUser,\n\t\t\t\tdisableDefaultScope: !!provider.disableDefaultScope,\n\t\t\t\tdisableIdTokenSignIn: !!provider.disableIdTokenSignIn,\n\t\t\t\tdisableImplicitSignUp: provider.disableImplicitSignUp,\n\t\t\t\tdisableSignUp: provider.disableSignUp,\n\t\t\t\tgetUserInfo: !!provider.getUserInfo,\n\t\t\t\toverrideUserInfoOnSignIn: !!provider.overrideUserInfoOnSignIn,\n\t\t\t\tprompt: provider.prompt,\n\t\t\t\tverifyIdToken: !!provider.verifyIdToken,\n\t\t\t\tscope: provider.scope,\n\t\t\t\trefreshAccessToken: !!provider.refreshAccessToken\n\t\t\t};\n\t\t})),\n\t\tplugins: options.plugins?.map((p) => p.id.toString()),\n\t\tuser: {\n\t\t\tmodelName: options.user?.modelName,\n\t\t\tfields: options.user?.fields,\n\t\t\tadditionalFields: options.user?.additionalFields,\n\t\t\tchangeEmail: {\n\t\t\t\tenabled: options.user?.changeEmail?.enabled,\n\t\t\t\tsendChangeEmailConfirmation: !!options.user?.changeEmail?.sendChangeEmailConfirmation\n\t\t\t}\n\t\t},\n\t\tverification: {\n\t\t\tmodelName: options.verification?.modelName,\n\t\t\tdisableCleanup: options.verification?.disableCleanup,\n\t\t\tfields: options.verification?.fields\n\t\t},\n\t\tsession: {\n\t\t\tmodelName: options.session?.modelName,\n\t\t\tadditionalFields: options.session?.additionalFields,\n\t\t\tcookieCache: {\n\t\t\t\tenabled: options.session?.cookieCache?.enabled,\n\t\t\t\tmaxAge: options.session?.cookieCache?.maxAge,\n\t\t\t\tstrategy: options.session?.cookieCache?.strategy\n\t\t\t},\n\t\t\tdisableSessionRefresh: options.session?.disableSessionRefresh,\n\t\t\texpiresIn: options.session?.expiresIn,\n\t\t\tfields: options.session?.fields,\n\t\t\tfreshAge: options.session?.freshAge,\n\t\t\tpreserveSessionInDatabase: options.session?.preserveSessionInDatabase,\n\t\t\tstoreSessionInDatabase: options.session?.storeSessionInDatabase,\n\t\t\tupdateAge: options.session?.updateAge\n\t\t},\n\t\taccount: {\n\t\t\tmodelName: options.account?.modelName,\n\t\t\tfields: options.account?.fields,\n\t\t\tencryptOAuthTokens: options.account?.encryptOAuthTokens,\n\t\t\tupdateAccountOnSignIn: options.account?.updateAccountOnSignIn,\n\t\t\taccountLinking: {\n\t\t\t\tenabled: options.account?.accountLinking?.enabled,\n\t\t\t\ttrustedProviders: options.account?.accountLinking?.trustedProviders,\n\t\t\t\tupdateUserInfoOnLink: options.account?.accountLinking?.updateUserInfoOnLink,\n\t\t\t\tallowUnlinkingAll: options.account?.accountLinking?.allowUnlinkingAll\n\t\t\t}\n\t\t},\n\t\thooks: {\n\t\t\tafter: !!options.hooks?.after,\n\t\t\tbefore: !!options.hooks?.before\n\t\t},\n\t\tsecondaryStorage: !!options.secondaryStorage,\n\t\tadvanced: {\n\t\t\tcookiePrefix: !!options.advanced?.cookiePrefix,\n\t\t\tcookies: !!options.advanced?.cookies,\n\t\t\tcrossSubDomainCookies: {\n\t\t\t\tdomain: !!options.advanced?.crossSubDomainCookies?.domain,\n\t\t\t\tenabled: options.advanced?.crossSubDomainCookies?.enabled,\n\t\t\t\tadditionalCookies: options.advanced?.crossSubDomainCookies?.additionalCookies\n\t\t\t},\n\t\t\tdatabase: {\n\t\t\t\tgenerateId: options.advanced?.database?.generateId,\n\t\t\t\tdefaultFindManyLimit: options.advanced?.database?.defaultFindManyLimit\n\t\t\t},\n\t\t\tuseSecureCookies: options.advanced?.useSecureCookies,\n\t\t\tipAddress: {\n\t\t\t\tdisableIpTracking: options.advanced?.ipAddress?.disableIpTracking,\n\t\t\t\tipAddressHeaders: options.advanced?.ipAddress?.ipAddressHeaders\n\t\t\t},\n\t\t\tdisableCSRFCheck: options.advanced?.disableCSRFCheck,\n\t\t\tcookieAttributes: {\n\t\t\t\texpires: options.advanced?.defaultCookieAttributes?.expires,\n\t\t\t\tsecure: options.advanced?.defaultCookieAttributes?.secure,\n\t\t\t\tsameSite: options.advanced?.defaultCookieAttributes?.sameSite,\n\t\t\t\tdomain: !!options.advanced?.defaultCookieAttributes?.domain,\n\t\t\t\tpath: options.advanced?.defaultCookieAttributes?.path,\n\t\t\t\thttpOnly: options.advanced?.defaultCookieAttributes?.httpOnly\n\t\t\t}\n\t\t},\n\t\ttrustedOrigins: options.trustedOrigins?.length,\n\t\trateLimit: {\n\t\t\tstorage: options.rateLimit?.storage,\n\t\t\tmodelName: options.rateLimit?.modelName,\n\t\t\twindow: options.rateLimit?.window,\n\t\t\tcustomStorage: !!options.rateLimit?.customStorage,\n\t\t\tenabled: options.rateLimit?.enabled,\n\t\t\tmax: options.rateLimit?.max\n\t\t},\n\t\tonAPIError: {\n\t\t\terrorURL: options.onAPIError?.errorURL,\n\t\t\tonError: !!options.onAPIError?.onError,\n\t\t\tthrow: options.onAPIError?.throw\n\t\t},\n\t\tlogger: {\n\t\t\tdisabled: options.logger?.disabled,\n\t\t\tlevel: options.logger?.level,\n\t\t\tlog: !!options.logger?.log\n\t\t},\n\t\tdatabaseHooks: {\n\t\t\tuser: {\n\t\t\t\tcreate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.user?.create?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.user?.create?.before\n\t\t\t\t},\n\t\t\t\tupdate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.user?.update?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.user?.update?.before\n\t\t\t\t}\n\t\t\t},\n\t\t\tsession: {\n\t\t\t\tcreate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.session?.create?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.session?.create?.before\n\t\t\t\t},\n\t\t\t\tupdate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.session?.update?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.session?.update?.before\n\t\t\t\t}\n\t\t\t},\n\t\t\taccount: {\n\t\t\t\tcreate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.account?.create?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.account?.create?.before\n\t\t\t\t},\n\t\t\t\tupdate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.account?.update?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.account?.update?.before\n\t\t\t\t}\n\t\t\t},\n\t\t\tverification: {\n\t\t\t\tcreate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.verification?.create?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.verification?.create?.before\n\t\t\t\t},\n\t\t\t\tupdate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.verification?.update?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.verification?.update?.before\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/detectors/detect-project-info.ts\nfunction detectPackageManager() {\n\tconst userAgent = env.npm_config_user_agent;\n\tif (!userAgent) return;\n\tconst pmSpec = userAgent.split(\" \")[0];\n\tconst separatorPos = pmSpec.lastIndexOf(\"/\");\n\tconst name = pmSpec.substring(0, separatorPos);\n\treturn {\n\t\tname: name === \"npminstall\" ? \"cnpm\" : name,\n\t\tversion: pmSpec.substring(separatorPos + 1)\n\t};\n}\n//#endregion\n//#region src/detectors/detect-system-info.ts\nfunction isCI() {\n\treturn env.CI !== \"false\" && (\"BUILD_ID\" in env || \"BUILD_NUMBER\" in env || \"CI\" in env || \"CI_APP_ID\" in env || \"CI_BUILD_ID\" in env || \"CI_BUILD_NUMBER\" in env || \"CI_NAME\" in env || \"CONTINUOUS_INTEGRATION\" in env || \"RUN_ID\" in env);\n}\n//#endregion\n//#region src/detectors/detect-runtime.ts\nfunction detectRuntime() {\n\tif (typeof Deno !== \"undefined\") return {\n\t\tname: \"deno\",\n\t\tversion: Deno?.version?.deno ?? null\n\t};\n\tif (typeof Bun !== \"undefined\") return {\n\t\tname: \"bun\",\n\t\tversion: Bun?.version ?? null\n\t};\n\tif (typeof process !== \"undefined\" && process?.versions?.node) return {\n\t\tname: \"node\",\n\t\tversion: process.versions.node ?? null\n\t};\n\treturn {\n\t\tname: \"edge\",\n\t\tversion: null\n\t};\n}\nfunction detectEnvironment() {\n\treturn getEnvVar(\"NODE_ENV\") === \"production\" ? \"production\" : isCI() ? \"ci\" : isTest() ? \"test\" : \"development\";\n}\n//#endregion\n//#region src/utils/hash.ts\nasync function hashToBase64(data) {\n\tconst buffer = await createHash(\"SHA-256\").digest(data);\n\treturn base64.encode(buffer);\n}\n//#endregion\n//#region src/utils/id.ts\nconst generateId = (size) => {\n\treturn createRandomStringGenerator(\"a-z\", \"A-Z\", \"0-9\")(size || 32);\n};\n//#endregion\n//#region src/node.ts\nlet packageJSONCache;\nasync function readRootPackageJson() {\n\tif (packageJSONCache) return packageJSONCache;\n\ttry {\n\t\tconst cwd = process.cwd();\n\t\tif (!cwd) return void 0;\n\t\tconst raw = await fsPromises.readFile(path.join(cwd, \"package.json\"), \"utf-8\");\n\t\tpackageJSONCache = JSON.parse(raw);\n\t\treturn packageJSONCache;\n\t} catch {}\n}\nasync function getPackageVersion(pkg) {\n\tif (packageJSONCache) return packageJSONCache.dependencies?.[pkg] || packageJSONCache.devDependencies?.[pkg] || packageJSONCache.peerDependencies?.[pkg];\n\ttry {\n\t\tconst cwd = process.cwd();\n\t\tif (!cwd) throw new Error(\"no-cwd\");\n\t\tconst pkgJsonPath = path.join(cwd, \"node_modules\", pkg, \"package.json\");\n\t\tconst raw = await fsPromises.readFile(pkgJsonPath, \"utf-8\");\n\t\treturn JSON.parse(raw).version || await getVersionFromLocalPackageJson(pkg) || void 0;\n\t} catch {}\n\treturn getVersionFromLocalPackageJson(pkg);\n}\nasync function getVersionFromLocalPackageJson(pkg) {\n\tconst json = await readRootPackageJson();\n\tif (!json) return void 0;\n\treturn {\n\t\t...json.dependencies,\n\t\t...json.devDependencies,\n\t\t...json.peerDependencies\n\t}[pkg];\n}\nasync function getNameFromLocalPackageJson() {\n\treturn (await readRootPackageJson())?.name;\n}\nasync function detectSystemInfo() {\n\ttry {\n\t\tconst cpus = os.cpus();\n\t\treturn {\n\t\t\tdeploymentVendor: getVendor(),\n\t\t\tsystemPlatform: os.platform(),\n\t\t\tsystemRelease: os.release(),\n\t\t\tsystemArchitecture: os.arch(),\n\t\t\tcpuCount: cpus.length,\n\t\t\tcpuModel: cpus.length ? cpus[0].model : null,\n\t\t\tcpuSpeed: cpus.length ? cpus[0].speed : null,\n\t\t\tmemory: os.totalmem(),\n\t\t\tisWSL: await isWsl(),\n\t\t\tisDocker: await isDocker(),\n\t\t\tisTTY: process.stdout ? process.stdout.isTTY : null\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsystemPlatform: null,\n\t\t\tsystemRelease: null,\n\t\t\tsystemArchitecture: null,\n\t\t\tcpuCount: null,\n\t\t\tcpuModel: null,\n\t\t\tcpuSpeed: null,\n\t\t\tmemory: null,\n\t\t\tisWSL: null,\n\t\t\tisDocker: null,\n\t\t\tisTTY: null\n\t\t};\n\t}\n}\nfunction getVendor() {\n\tconst env = process.env;\n\tconst hasAny = (...keys) => keys.some((k) => Boolean(env[k]));\n\tif (hasAny(\"CF_PAGES\", \"CF_PAGES_URL\", \"CF_ACCOUNT_ID\") || typeof navigator !== \"undefined\" && navigator.userAgent === \"Cloudflare-Workers\") return \"cloudflare\";\n\tif (hasAny(\"VERCEL\", \"VERCEL_URL\", \"VERCEL_ENV\")) return \"vercel\";\n\tif (hasAny(\"NETLIFY\", \"NETLIFY_URL\")) return \"netlify\";\n\tif (hasAny(\"RENDER\", \"RENDER_URL\", \"RENDER_INTERNAL_HOSTNAME\", \"RENDER_SERVICE_ID\")) return \"render\";\n\tif (hasAny(\"AWS_LAMBDA_FUNCTION_NAME\", \"AWS_EXECUTION_ENV\", \"LAMBDA_TASK_ROOT\")) return \"aws\";\n\tif (hasAny(\"GOOGLE_CLOUD_FUNCTION_NAME\", \"GOOGLE_CLOUD_PROJECT\", \"GCP_PROJECT\", \"K_SERVICE\")) return \"gcp\";\n\tif (hasAny(\"AZURE_FUNCTION_NAME\", \"FUNCTIONS_WORKER_RUNTIME\", \"WEBSITE_INSTANCE_ID\", \"WEBSITE_SITE_NAME\")) return \"azure\";\n\tif (hasAny(\"DENO_DEPLOYMENT_ID\", \"DENO_REGION\")) return \"deno-deploy\";\n\tif (hasAny(\"FLY_APP_NAME\", \"FLY_REGION\", \"FLY_ALLOC_ID\")) return \"fly-io\";\n\tif (hasAny(\"RAILWAY_STATIC_URL\", \"RAILWAY_ENVIRONMENT_NAME\")) return \"railway\";\n\tif (hasAny(\"DYNO\", \"HEROKU_APP_NAME\")) return \"heroku\";\n\tif (hasAny(\"DO_DEPLOYMENT_ID\", \"DO_APP_NAME\", \"DIGITALOCEAN\")) return \"digitalocean\";\n\tif (hasAny(\"KOYEB\", \"KOYEB_DEPLOYMENT_ID\", \"KOYEB_APP_NAME\")) return \"koyeb\";\n\treturn null;\n}\nlet isDockerCached;\nasync function hasDockerEnv() {\n\ttry {\n\t\tfs.statSync(\"/.dockerenv\");\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function hasDockerCGroup() {\n\ttry {\n\t\treturn fs.readFileSync(\"/proc/self/cgroup\", \"utf8\").includes(\"docker\");\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function isDocker() {\n\tif (isDockerCached === void 0) isDockerCached = await hasDockerEnv() || await hasDockerCGroup();\n\treturn isDockerCached;\n}\nlet isInsideContainerCached;\nconst hasContainerEnv = async () => {\n\ttry {\n\t\tfs.statSync(\"/run/.containerenv\");\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\nasync function isInsideContainer() {\n\tif (isInsideContainerCached === void 0) isInsideContainerCached = await hasContainerEnv() || await isDocker();\n\treturn isInsideContainerCached;\n}\nasync function isWsl() {\n\ttry {\n\t\tif (process.platform !== \"linux\") return false;\n\t\tif (os.release().toLowerCase().includes(\"microsoft\")) {\n\t\t\tif (await isInsideContainer()) return false;\n\t\t\treturn true;\n\t\t}\n\t\treturn fs.readFileSync(\"/proc/version\", \"utf8\").toLowerCase().includes(\"microsoft\") ? !await isInsideContainer() : false;\n\t} catch {\n\t\treturn false;\n\t}\n}\nlet projectIdCached = null;\nasync function getProjectId(baseUrl) {\n\tif (projectIdCached) return projectIdCached;\n\tconst projectName = await getNameFromLocalPackageJson();\n\tif (projectName) {\n\t\tprojectIdCached = await hashToBase64(baseUrl ? baseUrl + projectName : projectName);\n\t\treturn projectIdCached;\n\t}\n\tif (baseUrl) {\n\t\tprojectIdCached = await hashToBase64(baseUrl);\n\t\treturn projectIdCached;\n\t}\n\tprojectIdCached = generateId(32);\n\treturn projectIdCached;\n}\nasync function detectDatabaseNode() {\n\tfor (const [pkg, name] of Object.entries({\n\t\tpg: \"postgresql\",\n\t\tmysql: \"mysql\",\n\t\tmariadb: \"mariadb\",\n\t\tsqlite3: \"sqlite\",\n\t\t\"better-sqlite3\": \"sqlite\",\n\t\t\"@prisma/client\": \"prisma\",\n\t\tmongoose: \"mongodb\",\n\t\tmongodb: \"mongodb\",\n\t\t\"drizzle-orm\": \"drizzle\"\n\t})) {\n\t\tconst version = await getPackageVersion(pkg);\n\t\tif (version) return {\n\t\t\tname,\n\t\t\tversion\n\t\t};\n\t}\n}\nasync function detectFrameworkNode() {\n\tfor (const [pkg, name] of Object.entries({\n\t\tnext: \"next\",\n\t\tnuxt: \"nuxt\",\n\t\t\"react-router\": \"react-router\",\n\t\tastro: \"astro\",\n\t\t\"@sveltejs/kit\": \"sveltekit\",\n\t\t\"solid-start\": \"solid-start\",\n\t\t\"tanstack-start\": \"tanstack-start\",\n\t\thono: \"hono\",\n\t\texpress: \"express\",\n\t\telysia: \"elysia\",\n\t\texpo: \"expo\"\n\t})) {\n\t\tconst version = await getPackageVersion(pkg);\n\t\tif (version) return {\n\t\t\tname,\n\t\t\tversion\n\t\t};\n\t}\n}\nconst noop = async function noop() {};\nasync function createTelemetry(options, context) {\n\tconst debugEnabled = options.telemetry?.debug || getBooleanEnvVar(\"BETTER_AUTH_TELEMETRY_DEBUG\", false);\n\tconst telemetryEndpoint = ENV.BETTER_AUTH_TELEMETRY_ENDPOINT;\n\tif (!telemetryEndpoint && !context?.customTrack) return { publish: noop };\n\tconst track = async (event) => {\n\t\tif (context?.customTrack) await context.customTrack(event).catch(logger.error);\n\t\telse if (telemetryEndpoint) if (debugEnabled) logger.info(\"telemetry event\", JSON.stringify(event, null, 2));\n\t\telse await betterFetch(telemetryEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: event\n\t\t}).catch(logger.error);\n\t};\n\tconst isEnabled = async () => {\n\t\tconst telemetryEnabled = options.telemetry?.enabled !== void 0 ? options.telemetry.enabled : false;\n\t\treturn (getBooleanEnvVar(\"BETTER_AUTH_TELEMETRY\", false) || telemetryEnabled) && (context?.skipTestCheck || !isTest());\n\t};\n\tconst enabled = await isEnabled();\n\tlet anonymousId;\n\tif (enabled) {\n\t\tanonymousId = await getProjectId(typeof options.baseURL === \"string\" ? options.baseURL : void 0);\n\t\ttrack({\n\t\t\ttype: \"init\",\n\t\t\tpayload: {\n\t\t\t\tconfig: await getTelemetryAuthConfig(options, context),\n\t\t\t\truntime: detectRuntime(),\n\t\t\t\tdatabase: await detectDatabaseNode(),\n\t\t\t\tframework: await detectFrameworkNode(),\n\t\t\t\tenvironment: detectEnvironment(),\n\t\t\t\tsystemInfo: await detectSystemInfo(),\n\t\t\t\tpackageManager: detectPackageManager()\n\t\t\t},\n\t\t\tanonymousId\n\t\t});\n\t}\n\treturn { publish: async (event) => {\n\t\tif (!enabled) return;\n\t\tif (!anonymousId) anonymousId = await getProjectId(typeof options.baseURL === \"string\" ? options.baseURL : void 0);\n\t\tawait track({\n\t\t\ttype: event.type,\n\t\t\tpayload: event.payload,\n\t\t\tanonymousId\n\t\t});\n\t} };\n}\n//#endregion\nexport { createTelemetry, getTelemetryAuthConfig };\n", "import { getAdapter } from \"../db/adapter-kysely.mjs\";\nimport { getMigrations } from \"../db/get-migration.mjs\";\nimport { createAuthContext } from \"./create-context.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { getKyselyDatabaseType } from \"@better-auth/kysely-adapter\";\n//#region src/context/init.ts\nconst init = async (options) => {\n\tconst adapter = await getAdapter(options);\n\tconst getDatabaseType = (database) => getKyselyDatabaseType(database) || \"unknown\";\n\tconst ctx = await createAuthContext(adapter, options, getDatabaseType);\n\tctx.runMigrations = async function() {\n\t\tif (!options.database || \"updateMany\" in options.database) throw new BetterAuthError(\"Database is not provided or it's an adapter. Migrations are only supported with a database instance.\");\n\t\tconst { runMigrations } = await getMigrations(options);\n\t\tawait runMigrations();\n\t};\n\treturn ctx;\n};\n//#endregion\nexport { init };\n", "import { getBaseURL, getOrigin, isDynamicBaseURLConfig, resolveBaseURL } from \"../utils/url.mjs\";\nimport { getTrustedOrigins, getTrustedProviders } from \"../context/helpers.mjs\";\nimport { createCookieGetter, getCookies } from \"../cookies/index.mjs\";\nimport { getEndpoints, router } from \"../api/index.mjs\";\nimport { runWithAdapter } from \"@better-auth/core/context\";\nimport { BASE_ERROR_CODES, BetterAuthError } from \"@better-auth/core/error\";\n//#region src/auth/base.ts\nconst createBetterAuth = (options, initFn) => {\n\tconst authContext = initFn(options);\n\tconst { api } = getEndpoints(authContext, options);\n\treturn {\n\t\thandler: async (request) => {\n\t\t\tconst ctx = await authContext;\n\t\t\tconst basePath = ctx.options.basePath || \"/api/auth\";\n\t\t\tlet handlerCtx;\n\t\t\tif (isDynamicBaseURLConfig(options.baseURL)) {\n\t\t\t\thandlerCtx = Object.create(Object.getPrototypeOf(ctx), Object.getOwnPropertyDescriptors(ctx));\n\t\t\t\tconst baseURL = resolveBaseURL(options.baseURL, basePath, request);\n\t\t\t\tif (baseURL) {\n\t\t\t\t\thandlerCtx.baseURL = baseURL;\n\t\t\t\t\thandlerCtx.options = {\n\t\t\t\t\t\t...ctx.options,\n\t\t\t\t\t\tbaseURL: getOrigin(baseURL) || void 0\n\t\t\t\t\t};\n\t\t\t\t} else throw new BetterAuthError(\"Could not resolve base URL from request. Check your allowedHosts config.\");\n\t\t\t\tconst trustedOriginOptions = {\n\t\t\t\t\t...handlerCtx.options,\n\t\t\t\t\tbaseURL: options.baseURL\n\t\t\t\t};\n\t\t\t\thandlerCtx.trustedOrigins = await getTrustedOrigins(trustedOriginOptions, request);\n\t\t\t\tif (options.advanced?.crossSubDomainCookies?.enabled) {\n\t\t\t\t\thandlerCtx.authCookies = getCookies(handlerCtx.options);\n\t\t\t\t\thandlerCtx.createAuthCookie = createCookieGetter(handlerCtx.options);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thandlerCtx = ctx;\n\t\t\t\tif (!ctx.options.baseURL) {\n\t\t\t\t\tconst baseURL = getBaseURL(void 0, basePath, request, void 0, ctx.options.advanced?.trustedProxyHeaders);\n\t\t\t\t\tif (baseURL) {\n\t\t\t\t\t\tctx.baseURL = baseURL;\n\t\t\t\t\t\tctx.options.baseURL = getOrigin(ctx.baseURL) || void 0;\n\t\t\t\t\t} else throw new BetterAuthError(\"Could not get base URL from request. Please provide a valid base URL.\");\n\t\t\t\t}\n\t\t\t\thandlerCtx.trustedOrigins = await getTrustedOrigins(ctx.options, request);\n\t\t\t}\n\t\t\thandlerCtx.trustedProviders = await getTrustedProviders(handlerCtx.options, request);\n\t\t\tconst { handler } = router(handlerCtx, options);\n\t\t\treturn runWithAdapter(handlerCtx.adapter, () => handler(request));\n\t\t},\n\t\tapi,\n\t\toptions,\n\t\t$context: authContext,\n\t\t$ERROR_CODES: {\n\t\t\t...options.plugins?.reduce((acc, plugin) => {\n\t\t\t\tif (plugin.$ERROR_CODES) return {\n\t\t\t\t\t...acc,\n\t\t\t\t\t...plugin.$ERROR_CODES\n\t\t\t\t};\n\t\t\t\treturn acc;\n\t\t\t}, {}),\n\t\t\t...BASE_ERROR_CODES\n\t\t}\n\t};\n};\n//#endregion\nexport { createBetterAuth };\n", "import { init } from \"../context/init.mjs\";\nimport { createBetterAuth } from \"./base.mjs\";\n//#region src/auth/full.ts\n/**\n* Better Auth initializer for full mode (with Kysely)\n*\n* @example\n* ```ts\n* import { betterAuth } from \"better-auth\";\n*\n* const auth = betterAuth({\n* \tdatabase: new PostgresDialect({ connection: process.env.DATABASE_URL }),\n* });\n* ```\n*\n* For minimal mode (without Kysely), import from `better-auth/minimal` instead\n* @example\n* ```ts\n* import { betterAuth } from \"better-auth/minimal\";\n*\n* const auth = betterAuth({\n*\t database: drizzleAdapter(db, { provider: \"pg\" }),\n* });\n*/\nconst betterAuth = (options) => {\n\treturn createBetterAuth(options, init);\n};\n//#endregion\nexport { betterAuth };\n", "import { getBaseURL, getHost, getHostFromRequest, getOrigin, getProtocol, getProtocolFromRequest, isDynamicBaseURLConfig, matchesHostPattern, resolveBaseURL, resolveDynamicBaseURL } from \"./utils/url.mjs\";\nimport { generateGenericState, parseGenericState } from \"./state.mjs\";\nimport { generateState, parseState } from \"./oauth2/state.mjs\";\nimport { HIDE_METADATA } from \"./utils/hide-metadata.mjs\";\nimport { APIError } from \"./api/index.mjs\";\nimport { betterAuth } from \"./auth/full.mjs\";\nimport { getCurrentAdapter } from \"@better-auth/core/context\";\nimport { createTelemetry, getTelemetryAuthConfig } from \"@better-auth/telemetry\";\nexport * from \"@better-auth/core\";\nexport * from \"@better-auth/core/db\";\nexport * from \"@better-auth/core/env\";\nexport * from \"@better-auth/core/error\";\nexport * from \"@better-auth/core/oauth2\";\nexport * from \"@better-auth/core/utils/error-codes\";\nexport * from \"@better-auth/core/utils/id\";\nexport * from \"@better-auth/core/utils/json\";\nexport { APIError, HIDE_METADATA, betterAuth, createTelemetry, generateGenericState, generateState, getBaseURL, getCurrentAdapter, getHost, getHostFromRequest, getOrigin, getProtocol, getProtocolFromRequest, getTelemetryAuthConfig, isDynamicBaseURLConfig, matchesHostPattern, parseGenericState, parseState, resolveBaseURL, resolveDynamicBaseURL };\n", "//#region src/client/parser.ts\nconst PROTO_POLLUTION_PATTERNS = {\n\tproto: /\"(?:_|\\\\u0{2}5[Ff]){2}(?:p|\\\\u0{2}70)(?:r|\\\\u0{2}72)(?:o|\\\\u0{2}6[Ff])(?:t|\\\\u0{2}74)(?:o|\\\\u0{2}6[Ff])(?:_|\\\\u0{2}5[Ff]){2}\"\\s*:/,\n\tconstructor: /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/,\n\tprotoShort: /\"__proto__\"\\s*:/,\n\tconstructorShort: /\"constructor\"\\s*:/\n};\nconst JSON_SIGNATURE = /^\\s*[\"[{]|^\\s*-?\\d{1,16}(\\.\\d{1,17})?([Ee][+-]?\\d+)?\\s*$/;\nconst SPECIAL_VALUES = {\n\ttrue: true,\n\tfalse: false,\n\tnull: null,\n\tundefined: void 0,\n\tnan: NaN,\n\tinfinity: Number.POSITIVE_INFINITY,\n\t\"-infinity\": Number.NEGATIVE_INFINITY\n};\nconst ISO_DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,7}))?(?:Z|([+-])(\\d{2}):(\\d{2}))$/;\nfunction isValidDate(date) {\n\treturn date instanceof Date && !isNaN(date.getTime());\n}\nfunction parseISODate(value) {\n\tconst match = ISO_DATE_REGEX.exec(value);\n\tif (!match) return null;\n\tconst [, year, month, day, hour, minute, second, ms, offsetSign, offsetHour, offsetMinute] = match;\n\tconst date = new Date(Date.UTC(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10), parseInt(hour, 10), parseInt(minute, 10), parseInt(second, 10), ms ? parseInt(ms.padEnd(3, \"0\"), 10) : 0));\n\tif (offsetSign) {\n\t\tconst offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === \"+\" ? -1 : 1);\n\t\tdate.setUTCMinutes(date.getUTCMinutes() + offset);\n\t}\n\treturn isValidDate(date) ? date : null;\n}\nfunction betterJSONParse(value, options = {}) {\n\tconst { strict = false, warnings = false, reviver, parseDates = true } = options;\n\tif (typeof value !== \"string\") return value;\n\tconst trimmed = value.trim();\n\tif (trimmed.length > 0 && trimmed[0] === \"\\\"\" && trimmed.endsWith(\"\\\"\") && !trimmed.slice(1, -1).includes(\"\\\"\")) return trimmed.slice(1, -1);\n\tconst lowerValue = trimmed.toLowerCase();\n\tif (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) return SPECIAL_VALUES[lowerValue];\n\tif (!JSON_SIGNATURE.test(trimmed)) {\n\t\tif (strict) throw new SyntaxError(\"[better-json] Invalid JSON\");\n\t\treturn value;\n\t}\n\tif (Object.entries(PROTO_POLLUTION_PATTERNS).some(([key, pattern]) => {\n\t\tconst matches = pattern.test(trimmed);\n\t\tif (matches && warnings) console.warn(`[better-json] Detected potential prototype pollution attempt using ${key} pattern`);\n\t\treturn matches;\n\t}) && strict) throw new Error(\"[better-json] Potential prototype pollution attempt detected\");\n\ttry {\n\t\tconst secureReviver = (key, value) => {\n\t\t\tif (key === \"__proto__\" || key === \"constructor\" && value && typeof value === \"object\" && \"prototype\" in value) {\n\t\t\t\tif (warnings) console.warn(`[better-json] Dropping \"${key}\" key to prevent prototype pollution`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parseDates && typeof value === \"string\") {\n\t\t\t\tconst date = parseISODate(value);\n\t\t\t\tif (date) return date;\n\t\t\t}\n\t\t\treturn reviver ? reviver(key, value) : value;\n\t\t};\n\t\treturn JSON.parse(trimmed, secureReviver);\n\t} catch (error) {\n\t\tif (strict) throw error;\n\t\treturn value;\n\t}\n}\nfunction parseJSON(value, options = { strict: true }) {\n\treturn betterJSONParse(value, options);\n}\n//#endregion\nexport { parseJSON };\n", "import { getDate } from \"../../utils/date.mjs\";\nimport { parseJSON } from \"../../client/parser.mjs\";\nimport { getCurrentAdapter } from \"@better-auth/core/context\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { filterOutputFields } from \"@better-auth/core/utils/db\";\n//#region src/plugins/organization/adapter.ts\nconst getOrgAdapter = (context, options) => {\n\tconst baseAdapter = context.adapter;\n\tconst orgAdditionalFields = options?.schema?.organization?.additionalFields;\n\tconst memberAdditionalFields = options?.schema?.member?.additionalFields;\n\tconst invitationAdditionalFields = options?.schema?.invitation?.additionalFields;\n\tconst teamAdditionalFields = options?.schema?.team?.additionalFields;\n\treturn {\n\t\tfindOrganizationBySlug: async (slug) => {\n\t\t\treturn filterOutputFields(await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"slug\",\n\t\t\t\t\tvalue: slug\n\t\t\t\t}]\n\t\t\t}), orgAdditionalFields);\n\t\t},\n\t\tcreateOrganization: async (data) => {\n\t\t\tconst organization = await (await getCurrentAdapter(baseAdapter)).create({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\tdata: {\n\t\t\t\t\t...data.organization,\n\t\t\t\t\tmetadata: data.organization.metadata ? JSON.stringify(data.organization.metadata) : void 0\n\t\t\t\t},\n\t\t\t\tforceAllowId: true\n\t\t\t});\n\t\t\treturn filterOutputFields({\n\t\t\t\t...organization,\n\t\t\t\tmetadata: organization.metadata && typeof organization.metadata === \"string\" ? JSON.parse(organization.metadata) : void 0\n\t\t\t}, orgAdditionalFields);\n\t\t},\n\t\tfindMemberByEmail: async (data) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst user = await adapter.findOne({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"email\",\n\t\t\t\t\tvalue: data.email.toLowerCase()\n\t\t\t\t}]\n\t\t\t});\n\t\t\tif (!user) return null;\n\t\t\tconst member = await adapter.findOne({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: user.id\n\t\t\t\t}]\n\t\t\t});\n\t\t\tif (!member) return null;\n\t\t\treturn {\n\t\t\t\t...member,\n\t\t\t\tuser: {\n\t\t\t\t\tid: user.id,\n\t\t\t\t\tname: user.name,\n\t\t\t\t\temail: user.email,\n\t\t\t\t\timage: user.image\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tlistMembers: async (data) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst members = await Promise.all([adapter.findMany({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}, ...data.filter?.field ? [{\n\t\t\t\t\tfield: data.filter?.field,\n\t\t\t\t\tvalue: data.filter?.value,\n\t\t\t\t\t...data.filter.operator ? { operator: data.filter.operator } : {}\n\t\t\t\t}] : []],\n\t\t\t\tlimit: data.limit || (typeof options?.membershipLimit === \"number\" ? options.membershipLimit : 100) || 100,\n\t\t\t\toffset: data.offset || 0,\n\t\t\t\tsortBy: data.sortBy ? {\n\t\t\t\t\tfield: data.sortBy,\n\t\t\t\t\tdirection: data.sortOrder || \"asc\"\n\t\t\t\t} : void 0\n\t\t\t}), adapter.count({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}, ...data.filter?.field ? [{\n\t\t\t\t\tfield: data.filter?.field,\n\t\t\t\t\tvalue: data.filter?.value,\n\t\t\t\t\t...data.filter.operator ? { operator: data.filter.operator } : {}\n\t\t\t\t}] : []]\n\t\t\t})]);\n\t\t\tconst users = await adapter.findMany({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: members[0].map((member) => member.userId),\n\t\t\t\t\toperator: \"in\"\n\t\t\t\t}]\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tmembers: members[0].map((member) => {\n\t\t\t\t\tconst user = users.find((user) => user.id === member.userId);\n\t\t\t\t\tif (!user) throw new BetterAuthError(\"Unexpected error: User not found for member\");\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...member,\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tid: user.id,\n\t\t\t\t\t\t\tname: user.name,\n\t\t\t\t\t\t\temail: user.email,\n\t\t\t\t\t\t\timage: user.image\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t\ttotal: members[1]\n\t\t\t};\n\t\t},\n\t\tfindMemberByOrgId: async (data) => {\n\t\t\tconst result = await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (!result || !result.user) return null;\n\t\t\tconst { user, ...member } = result;\n\t\t\treturn {\n\t\t\t\t...member,\n\t\t\t\tuser: {\n\t\t\t\t\tid: user.id,\n\t\t\t\t\tname: user.name,\n\t\t\t\t\temail: user.email,\n\t\t\t\t\timage: user.image\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tfindMemberById: async (memberId) => {\n\t\t\tconst result = await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: memberId\n\t\t\t\t}],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { user, ...member } = result;\n\t\t\treturn {\n\t\t\t\t...member,\n\t\t\t\tuser: {\n\t\t\t\t\tid: user.id,\n\t\t\t\t\tname: user.name,\n\t\t\t\t\temail: user.email,\n\t\t\t\t\timage: user.image\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tcreateMember: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).create({\n\t\t\t\tmodel: \"member\",\n\t\t\t\tdata: {\n\t\t\t\t\t...data,\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tupdateMember: async (memberId, role) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).update({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: memberId\n\t\t\t\t}],\n\t\t\t\tupdate: { role }\n\t\t\t});\n\t\t},\n\t\tdeleteMember: async ({ memberId, organizationId, userId: _userId }) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tlet userId;\n\t\t\tif (!_userId) {\n\t\t\t\tconst member = await adapter.findOne({\n\t\t\t\t\tmodel: \"member\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\tvalue: memberId\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!member) throw new BetterAuthError(\"Member not found\");\n\t\t\t\tuserId = member.userId;\n\t\t\t} else userId = _userId;\n\t\t\tconst member = await adapter.delete({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: memberId\n\t\t\t\t}]\n\t\t\t});\n\t\t\tif (options?.teams?.enabled) {\n\t\t\t\tconst teams = await adapter.findMany({\n\t\t\t\t\tmodel: \"team\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\t\tvalue: organizationId\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tawait Promise.all(teams.map((team) => adapter.deleteMany({\n\t\t\t\t\tmodel: \"teamMember\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\t\tvalue: team.id\n\t\t\t\t\t}, {\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: userId\n\t\t\t\t\t}]\n\t\t\t\t})));\n\t\t\t}\n\t\t\treturn member;\n\t\t},\n\t\tupdateOrganization: async (organizationId, data) => {\n\t\t\tconst organization = await (await getCurrentAdapter(baseAdapter)).update({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}],\n\t\t\t\tupdate: {\n\t\t\t\t\t...data,\n\t\t\t\t\tmetadata: typeof data.metadata === \"object\" ? JSON.stringify(data.metadata) : data.metadata\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (!organization) return null;\n\t\t\treturn filterOutputFields({\n\t\t\t\t...organization,\n\t\t\t\tmetadata: organization.metadata ? parseJSON(organization.metadata) : void 0\n\t\t\t}, orgAdditionalFields);\n\t\t},\n\t\tdeleteOrganization: async (organizationId) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tawait adapter.deleteMany({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t\tawait adapter.deleteMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t\tawait adapter.delete({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t\treturn organizationId;\n\t\t},\n\t\tsetActiveOrganization: async (sessionToken, organizationId, ctx) => {\n\t\t\treturn await context.internalAdapter.updateSession(sessionToken, { activeOrganizationId: organizationId });\n\t\t},\n\t\tfindOrganizationById: async (organizationId) => {\n\t\t\treturn filterOutputFields(await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t}), orgAdditionalFields);\n\t\t},\n\t\tcheckMembership: async ({ userId, organizationId }) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindFullOrganization: async ({ organizationId, isSlug, includeTeams, membersLimit }) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst result = await adapter.findOne({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: isSlug ? \"slug\" : \"id\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}],\n\t\t\t\tjoin: {\n\t\t\t\t\tinvitation: true,\n\t\t\t\t\tmember: membersLimit ? { limit: membersLimit } : true,\n\t\t\t\t\t...includeTeams ? { team: true } : {}\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { invitation: invitations, member: members, team: teams, ...org } = result;\n\t\t\tconst userIds = members.map((member) => member.userId);\n\t\t\tconst users = userIds.length > 0 ? await adapter.findMany({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: userIds,\n\t\t\t\t\toperator: \"in\"\n\t\t\t\t}],\n\t\t\t\tlimit: (typeof options?.membershipLimit === \"number\" ? options.membershipLimit : 100) || 100\n\t\t\t}) : [];\n\t\t\tconst userMap = new Map(users.map((user) => [user.id, user]));\n\t\t\tconst membersWithUsers = members.map((member) => {\n\t\t\t\tconst user = userMap.get(member.userId);\n\t\t\t\tif (!user) throw new BetterAuthError(\"Unexpected error: User not found for member\");\n\t\t\t\treturn {\n\t\t\t\t\t...filterOutputFields(member, memberAdditionalFields),\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid: user.id,\n\t\t\t\t\t\tname: user.name,\n\t\t\t\t\t\temail: user.email,\n\t\t\t\t\t\timage: user.image\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t});\n\t\t\tconst filteredOrg = filterOutputFields(org, orgAdditionalFields);\n\t\t\tconst filteredInvitations = invitations.map((inv) => filterOutputFields(inv, invitationAdditionalFields));\n\t\t\tconst filteredTeams = teams?.map((team) => filterOutputFields(team, teamAdditionalFields));\n\t\t\treturn {\n\t\t\t\t...filteredOrg,\n\t\t\t\tinvitations: filteredInvitations,\n\t\t\t\tmembers: membersWithUsers,\n\t\t\t\tteams: filteredTeams\n\t\t\t};\n\t\t},\n\t\tlistOrganizations: async (userId) => {\n\t\t\tconst result = await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}],\n\t\t\t\tjoin: { organization: true }\n\t\t\t});\n\t\t\tif (!result || result.length === 0) return [];\n\t\t\treturn result.map((member) => filterOutputFields(member.organization, orgAdditionalFields));\n\t\t},\n\t\tcreateTeam: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).create({\n\t\t\t\tmodel: \"team\",\n\t\t\t\tdata\n\t\t\t});\n\t\t},\n\t\tfindTeamById: async ({ teamId, organizationId, includeTeamMembers }) => {\n\t\t\tconst result = await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"team\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}, ...organizationId ? [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}] : []],\n\t\t\t\tjoin: { ...includeTeamMembers ? { teamMember: true } : {} }\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { teamMember, ...team } = result;\n\t\t\treturn {\n\t\t\t\t...team,\n\t\t\t\t...includeTeamMembers ? { members: teamMember } : {}\n\t\t\t};\n\t\t},\n\t\tupdateTeam: async (teamId, data) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tif (\"id\" in data) data.id = void 0;\n\t\t\treturn await adapter.update({\n\t\t\t\tmodel: \"team\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}],\n\t\t\t\tupdate: { ...data }\n\t\t\t});\n\t\t},\n\t\tdeleteTeam: async (teamId) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tawait adapter.deleteMany({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t\treturn await adapter.delete({\n\t\t\t\tmodel: \"team\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tlistTeams: async (organizationId) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"team\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tcreateTeamInvitation: async ({ email, role, teamId, organizationId, inviterId, expiresIn = 1e3 * 60 * 60 * 48 }) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst expiresAt = getDate(expiresIn);\n\t\t\treturn await adapter.create({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\tdata: {\n\t\t\t\t\temail,\n\t\t\t\t\trole,\n\t\t\t\t\torganizationId,\n\t\t\t\t\tteamId,\n\t\t\t\t\tinviterId,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\texpiresAt\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tsetActiveTeam: async (sessionToken, teamId, ctx) => {\n\t\t\treturn await context.internalAdapter.updateSession(sessionToken, { activeTeamId: teamId });\n\t\t},\n\t\tlistTeamMembers: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tcountTeamMembers: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).count({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tcountMembers: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).count({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tlistTeamsByUser: async (data) => {\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}],\n\t\t\t\tjoin: { team: true }\n\t\t\t})).map((result) => result.team);\n\t\t},\n\t\tfindTeamMember: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindOrCreateTeamMember: async (data) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst member = await adapter.findOne({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}]\n\t\t\t});\n\t\t\tif (member) return member;\n\t\t\treturn await adapter.create({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\tdata: {\n\t\t\t\t\tteamId: data.teamId,\n\t\t\t\t\tuserId: data.userId,\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tremoveTeamMember: async (data) => {\n\t\t\tawait (await getCurrentAdapter(baseAdapter)).deleteMany({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindInvitationsByTeamId: async (teamId) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tlistUserInvitations: async (email) => {\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"email\",\n\t\t\t\t\tvalue: email.toLowerCase()\n\t\t\t\t}],\n\t\t\t\tjoin: { organization: true }\n\t\t\t})).filter(Boolean).map(({ organization, ...inv }) => ({\n\t\t\t\t...inv,\n\t\t\t\torganizationName: organization?.name\n\t\t\t}));\n\t\t},\n\t\tcreateInvitation: async ({ invitation, user }) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst expiresAt = getDate(options?.invitationExpiresIn || 3600 * 48, \"sec\");\n\t\t\treturn await adapter.create({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\tdata: {\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\tinviterId: user.id,\n\t\t\t\t\t...invitation,\n\t\t\t\t\tteamId: invitation.teamIds.length > 0 ? invitation.teamIds.join(\",\") : null\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tfindInvitationById: async (id) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: id\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindPendingInvitation: async (data) => {\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [\n\t\t\t\t\t{\n\t\t\t\t\t\tfield: \"email\",\n\t\t\t\t\t\tvalue: data.email.toLowerCase()\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tfield: \"status\",\n\t\t\t\t\t\tvalue: \"pending\"\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})).filter((invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date());\n\t\t},\n\t\tfindPendingInvitations: async (data) => {\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"status\",\n\t\t\t\t\tvalue: \"pending\"\n\t\t\t\t}]\n\t\t\t})).filter((invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date());\n\t\t},\n\t\tlistInvitations: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tupdateInvitation: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).update({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: data.invitationId\n\t\t\t\t}],\n\t\t\t\tupdate: { status: data.status }\n\t\t\t});\n\t\t}\n\t};\n};\n//#endregion\nexport { getOrgAdapter };\n", "import { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/plugins/access/access.ts\nfunction role(statements) {\n\treturn {\n\t\tauthorize(request, connector = \"AND\") {\n\t\t\tlet success = false;\n\t\t\tfor (const [requestedResource, requestedActions] of Object.entries(request)) {\n\t\t\t\tconst allowedActions = statements[requestedResource];\n\t\t\t\tif (!allowedActions) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: `You are not allowed to access resource: ${requestedResource}`\n\t\t\t\t};\n\t\t\t\tif (Array.isArray(requestedActions)) success = requestedActions.every((requestedAction) => allowedActions.includes(requestedAction));\n\t\t\t\telse if (typeof requestedActions === \"object\") {\n\t\t\t\t\tconst actions = requestedActions;\n\t\t\t\t\tif (actions.connector === \"OR\") success = actions.actions.some((requestedAction) => allowedActions.includes(requestedAction));\n\t\t\t\t\telse success = actions.actions.every((requestedAction) => allowedActions.includes(requestedAction));\n\t\t\t\t} else throw new BetterAuthError(\"Invalid access control request\");\n\t\t\t\tif (success && connector === \"OR\") return { success };\n\t\t\t\tif (!success && connector === \"AND\") return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: `unauthorized to access resource \"${requestedResource}\"`\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (success) return { success };\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: \"Not authorized\"\n\t\t\t};\n\t\t},\n\t\tstatements\n\t};\n}\nfunction createAccessControl(s) {\n\treturn {\n\t\tnewRole(statements) {\n\t\t\treturn role(statements);\n\t\t},\n\t\tstatements: s\n\t};\n}\n//#endregion\nexport { createAccessControl, role };\n", "import { createAccessControl } from \"../../access/access.mjs\";\n//#region src/plugins/organization/access/statement.ts\nconst defaultStatements = {\n\torganization: [\"update\", \"delete\"],\n\tmember: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tinvitation: [\"create\", \"cancel\"],\n\tteam: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tac: [\n\t\t\"create\",\n\t\t\"read\",\n\t\t\"update\",\n\t\t\"delete\"\n\t]\n};\nconst defaultAc = createAccessControl(defaultStatements);\nconst adminAc = defaultAc.newRole({\n\torganization: [\"update\"],\n\tinvitation: [\"create\", \"cancel\"],\n\tmember: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tteam: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tac: [\n\t\t\"create\",\n\t\t\"read\",\n\t\t\"update\",\n\t\t\"delete\"\n\t]\n});\nconst ownerAc = defaultAc.newRole({\n\torganization: [\"update\", \"delete\"],\n\tmember: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tinvitation: [\"create\", \"cancel\"],\n\tteam: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tac: [\n\t\t\"create\",\n\t\t\"read\",\n\t\t\"update\",\n\t\t\"delete\"\n\t]\n});\nconst memberAc = defaultAc.newRole({\n\torganization: [],\n\tmember: [],\n\tinvitation: [],\n\tteam: [],\n\tac: [\"read\"]\n});\nconst defaultRoles = {\n\tadmin: adminAc,\n\towner: ownerAc,\n\tmember: memberAc\n};\n//#endregion\nexport { adminAc, defaultAc, defaultRoles, defaultStatements, memberAc, ownerAc };\n", "//#region src/plugins/organization/permission.ts\nconst hasPermissionFn = (input, acRoles) => {\n\tif (!input.permissions) return false;\n\tconst roles = input.role.split(\",\");\n\tconst creatorRole = input.options.creatorRole || \"owner\";\n\tconst isCreator = roles.includes(creatorRole);\n\tconst allowCreatorsAllPermissions = input.allowCreatorAllPermissions || false;\n\tif (isCreator && allowCreatorsAllPermissions) return true;\n\tfor (const role of roles) if ((acRoles[role]?.authorize(input.permissions))?.success) return true;\n\treturn false;\n};\nconst cacheAllRoles = /* @__PURE__ */ new Map();\n//#endregion\nexport { cacheAllRoles, hasPermissionFn };\n", "import { APIError } from \"../../api/index.mjs\";\nimport { defaultRoles } from \"./access/statement.mjs\";\nimport { cacheAllRoles, hasPermissionFn } from \"./permission.mjs\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/has-permission.ts\nconst hasPermission = async (input, ctx) => {\n\tlet acRoles = { ...input.options.roles || defaultRoles };\n\tif (ctx && input.organizationId && input.options.dynamicAccessControl?.enabled && input.options.ac && !input.useMemoryCache) {\n\t\tconst roles = await ctx.context.adapter.findMany({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: input.organizationId\n\t\t\t}]\n\t\t});\n\t\tfor (const { role, permission: permissionsString } of roles) {\n\t\t\tconst result = z.record(z.string(), z.array(z.string())).safeParse(JSON.parse(permissionsString));\n\t\t\tif (!result.success) {\n\t\t\t\tctx.context.logger.error(\"[hasPermission] Invalid permissions for role \" + role, { permissions: JSON.parse(permissionsString) });\n\t\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", { message: \"Invalid permissions for role \" + role });\n\t\t\t}\n\t\t\tconst merged = { ...acRoles[role]?.statements };\n\t\t\tfor (const [key, actions] of Object.entries(result.data)) merged[key] = [...new Set([...merged[key] ?? [], ...actions])];\n\t\t\tacRoles[role] = input.options.ac.newRole(merged);\n\t\t}\n\t}\n\tif (input.useMemoryCache) acRoles = cacheAllRoles.get(input.organizationId) || acRoles;\n\tcacheAllRoles.set(input.organizationId, acRoles);\n\treturn hasPermissionFn(input, acRoles);\n};\n//#endregion\nexport { hasPermission };\n", "//#region package.json\nvar version = \"1.6.2\";\n//#endregion\nexport { version };\n", "import { version } from \"./package.mjs\";\n//#region src/version.ts\nconst PACKAGE_VERSION = version;\n//#endregion\nexport { PACKAGE_VERSION };\n", "import { defineErrorCodes } from \"@better-auth/core/utils/error-codes\";\n//#region src/plugins/organization/error-codes.ts\nconst ORGANIZATION_ERROR_CODES = defineErrorCodes({\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION: \"You are not allowed to create a new organization\",\n\tYOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS: \"You have reached the maximum number of organizations\",\n\tORGANIZATION_ALREADY_EXISTS: \"Organization already exists\",\n\tORGANIZATION_SLUG_ALREADY_TAKEN: \"Organization slug already taken\",\n\tORGANIZATION_NOT_FOUND: \"Organization not found\",\n\tUSER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION: \"User is not a member of the organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION: \"You are not allowed to update this organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION: \"You are not allowed to delete this organization\",\n\tNO_ACTIVE_ORGANIZATION: \"No active organization\",\n\tUSER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION: \"User is already a member of this organization\",\n\tMEMBER_NOT_FOUND: \"Member not found\",\n\tROLE_NOT_FOUND: \"Role not found\",\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM: \"You are not allowed to create a new team\",\n\tTEAM_ALREADY_EXISTS: \"Team already exists\",\n\tTEAM_NOT_FOUND: \"Team not found\",\n\tYOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER: \"You cannot leave the organization as the only owner\",\n\tYOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER: \"You cannot leave the organization without an owner\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER: \"You are not allowed to delete this member\",\n\tYOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION: \"You are not allowed to invite users to this organization\",\n\tUSER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION: \"User is already invited to this organization\",\n\tINVITATION_NOT_FOUND: \"Invitation not found\",\n\tYOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION: \"You are not the recipient of the invitation\",\n\tEMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION: \"Email verification required before accepting or rejecting invitation\",\n\tYOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION: \"You are not allowed to cancel this invitation\",\n\tINVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION: \"Inviter is no longer a member of the organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE: \"You are not allowed to invite a user with this role\",\n\tFAILED_TO_RETRIEVE_INVITATION: \"Failed to retrieve invitation\",\n\tYOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS: \"You have reached the maximum number of teams\",\n\tUNABLE_TO_REMOVE_LAST_TEAM: \"Unable to remove last team\",\n\tYOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER: \"You are not allowed to update this member\",\n\tORGANIZATION_MEMBERSHIP_LIMIT_REACHED: \"Organization membership limit reached\",\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION: \"You are not allowed to create teams in this organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION: \"You are not allowed to delete teams in this organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM: \"You are not allowed to update this team\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM: \"You are not allowed to delete this team\",\n\tINVITATION_LIMIT_REACHED: \"Invitation limit reached\",\n\tTEAM_MEMBER_LIMIT_REACHED: \"Team member limit reached\",\n\tUSER_IS_NOT_A_MEMBER_OF_THE_TEAM: \"User is not a member of the team\",\n\tYOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM: \"You are not allowed to list the members of this team\",\n\tYOU_DO_NOT_HAVE_AN_ACTIVE_TEAM: \"You do not have an active team\",\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER: \"You are not allowed to create a new member\",\n\tYOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER: \"You are not allowed to remove a team member\",\n\tYOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION: \"You are not allowed to access this organization as an owner\",\n\tYOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION: \"You are not a member of this organization\",\n\tMISSING_AC_INSTANCE: \"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information\",\n\tYOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE: \"You must be in an organization to create a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE: \"You are not allowed to create a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE: \"You are not allowed to update a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE: \"You are not allowed to delete a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE: \"You are not allowed to read a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE: \"You are not allowed to list a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE: \"You are not allowed to get a role\",\n\tTOO_MANY_ROLES: \"This organization has too many roles\",\n\tINVALID_RESOURCE: \"The provided permission includes an invalid resource\",\n\tROLE_NAME_IS_ALREADY_TAKEN: \"That role name is already taken\",\n\tCANNOT_DELETE_A_PRE_DEFINED_ROLE: \"Cannot delete a pre-defined role\",\n\tROLE_IS_ASSIGNED_TO_MEMBERS: \"Cannot delete a role that is assigned to members. Please reassign the members to a different role first\"\n});\n//#endregion\nexport { ORGANIZATION_ERROR_CODES };\n", "//#region src/utils/shim.ts\nconst shimContext = (originalObject, newContext) => {\n\tconst shimmedObj = {};\n\tfor (const [key, value] of Object.entries(originalObject)) {\n\t\tshimmedObj[key] = (ctx) => {\n\t\t\treturn value({\n\t\t\t\t...ctx,\n\t\t\t\tcontext: {\n\t\t\t\t\t...newContext,\n\t\t\t\t\t...ctx.context\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t\tshimmedObj[key].path = value.path;\n\t\tshimmedObj[key].method = value.method;\n\t\tshimmedObj[key].options = value.options;\n\t\tshimmedObj[key].headers = value.headers;\n\t}\n\treturn shimmedObj;\n};\n//#endregion\nexport { shimContext };\n", "import { sessionMiddleware } from \"../../api/routes/session.mjs\";\nimport { createAuthMiddleware } from \"@better-auth/core/api\";\n//#region src/plugins/organization/call.ts\nconst orgMiddleware = createAuthMiddleware(async () => {\n\treturn {};\n});\n/**\n* The middleware forces the endpoint to require a valid session by utilizing the `sessionMiddleware`.\n* It also appends additional types to the session type regarding organizations.\n*/\nconst orgSessionMiddleware = createAuthMiddleware({ use: [sessionMiddleware] }, async (ctx) => {\n\treturn { session: ctx.context.session };\n});\n//#endregion\nexport { orgMiddleware, orgSessionMiddleware };\n", "import * as z from \"zod\";\n//#region src/db/to-zod.ts\nfunction toZodSchema({ fields, isClientSide }) {\n\tconst zodFields = Object.keys(fields).reduce((acc, key) => {\n\t\tconst field = fields[key];\n\t\tif (!field) return acc;\n\t\tif (isClientSide && field.input === false) return acc;\n\t\tlet schema;\n\t\tif (field.type === \"json\") schema = z.json ? z.json() : z.any();\n\t\telse if (field.type === \"string[]\" || field.type === \"number[]\") schema = z.array(field.type === \"string[]\" ? z.string() : z.number());\n\t\telse if (Array.isArray(field.type)) schema = z.any();\n\t\telse schema = z[field.type]();\n\t\tif (field?.required === false) schema = schema.optional();\n\t\tif (!isClientSide && field?.returned === false) return acc;\n\t\treturn {\n\t\t\t...acc,\n\t\t\t[key]: schema\n\t\t};\n\t}, {});\n\treturn z.object(zodFields);\n}\n//#endregion\nexport { toZodSchema };\n", "import { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-access-control.ts\nconst normalizeRoleName = (role) => role.toLowerCase();\nconst DEFAULT_MAXIMUM_ROLES_PER_ORGANIZATION = Number.POSITIVE_INFINITY;\nconst getAdditionalFields = (options, shouldBePartial = false) => {\n\tconst additionalFields = options?.schema?.organizationRole?.additionalFields || {};\n\tif (shouldBePartial) for (const key in additionalFields) additionalFields[key].required = false;\n\treturn {\n\t\tadditionalFieldsSchema: toZodSchema({\n\t\t\tfields: additionalFields,\n\t\t\tisClientSide: true\n\t\t}),\n\t\t$AdditionalFields: {},\n\t\t$ReturnAdditionalFields: {}\n\t};\n};\nconst baseCreateOrgRoleSchema = z.object({\n\torganizationId: z.string().optional().meta({ description: \"The id of the organization to create the role in. If not provided, the user's active organization will be used.\" }),\n\trole: z.string().meta({ description: \"The name of the role to create\" }),\n\tpermission: z.record(z.string(), z.array(z.string())).meta({ description: \"The permission to assign to the role\" })\n});\nconst createOrgRole = (options) => {\n\tconst { additionalFieldsSchema, $AdditionalFields, $ReturnAdditionalFields } = getAdditionalFields(options, false);\n\treturn createAuthEndpoint(\"/organization/create-role\", {\n\t\tmethod: \"POST\",\n\t\tbody: baseCreateOrgRoleSchema.safeExtend({ additionalFields: z.object({ ...additionalFieldsSchema.shape }).optional() }),\n\t\tmetadata: { $Infer: { body: {} } },\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware]\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tlet roleName = ctx.body.role;\n\t\tconst permission = ctx.body.permission;\n\t\tconst additionalFields = ctx.body.additionalFields;\n\t\tconst ac = options.ac;\n\t\tif (!ac) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.`, `\\nPlease refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`);\n\t\t\tthrow APIError.from(\"NOT_IMPLEMENTED\", ORGANIZATION_ERROR_CODES.MISSING_AC_INSTANCE);\n\t\t}\n\t\tconst organizationId = ctx.body.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to create a role. Either set an active org id, or pass an organizationId in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE);\n\t\t}\n\t\troleName = normalizeRoleName(roleName);\n\t\tawait checkIfRoleNameIsTakenByPreDefinedRole({\n\t\t\trole: roleName,\n\t\t\torganizationId,\n\t\t\toptions,\n\t\t\tctx\n\t\t});\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to create a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { ac: [\"create\"] },\n\t\t\trole: member.role\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to create a role. If this is unexpected, please make sure the role associated to that member has the \"ac\" resource with the \"create\" permission.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId,\n\t\t\t\trole: member.role\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE);\n\t\t}\n\t\tconst maximumRolesPerOrganization = typeof options.dynamicAccessControl?.maximumRolesPerOrganization === \"function\" ? await options.dynamicAccessControl.maximumRolesPerOrganization(organizationId) : options.dynamicAccessControl?.maximumRolesPerOrganization ?? DEFAULT_MAXIMUM_ROLES_PER_ORGANIZATION;\n\t\tconst rolesInDB = await ctx.context.adapter.count({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (rolesInDB >= maximumRolesPerOrganization) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] Failed to create a new role, the organization has too many roles. Maximum allowed roles is ${maximumRolesPerOrganization}.`, {\n\t\t\t\torganizationId,\n\t\t\t\tmaximumRolesPerOrganization,\n\t\t\t\trolesInDB\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TOO_MANY_ROLES);\n\t\t}\n\t\tawait checkForInvalidResources({\n\t\t\tac,\n\t\t\tctx,\n\t\t\tpermission\n\t\t});\n\t\tawait checkIfMemberHasPermission({\n\t\t\tctx,\n\t\t\tmember,\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissionRequired: permission,\n\t\t\tuser,\n\t\t\taction: \"create\"\n\t\t});\n\t\tawait checkIfRoleNameIsTakenByRoleInDB({\n\t\t\tctx,\n\t\t\torganizationId,\n\t\t\trole: roleName\n\t\t});\n\t\tconst newRole = ac.newRole(permission);\n\t\tconst data = {\n\t\t\t...await ctx.context.adapter.create({\n\t\t\t\tmodel: \"organizationRole\",\n\t\t\t\tdata: {\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\torganizationId,\n\t\t\t\t\tpermission: JSON.stringify(permission),\n\t\t\t\t\trole: roleName,\n\t\t\t\t\t...additionalFields\n\t\t\t\t}\n\t\t\t}),\n\t\t\tpermission\n\t\t};\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t\troleData: data,\n\t\t\tstatements: newRole.statements\n\t\t});\n\t});\n};\nconst deleteOrgRoleBodySchema = z.object({ organizationId: z.string().optional().meta({ description: \"The id of the organization to create the role in. If not provided, the user's active organization will be used.\" }) }).and(z.union([z.object({ roleName: z.string().nonempty().meta({ description: \"The name of the role to delete\" }) }), z.object({ roleId: z.string().nonempty().meta({ description: \"The id of the role to delete\" }) })]));\nconst deleteOrgRole = (options) => {\n\treturn createAuthEndpoint(\"/organization/delete-role\", {\n\t\tmethod: \"POST\",\n\t\tbody: deleteOrgRoleBodySchema,\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware],\n\t\tmetadata: { $Infer: { body: {} } }\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tconst organizationId = ctx.body.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to delete a role. Either set an active org id, or pass an organizationId in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\t}\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to delete a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { ac: [\"delete\"] },\n\t\t\trole: member.role\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to delete a role. If this is unexpected, please make sure the role associated to that member has the \"ac\" resource with the \"delete\" permission.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId,\n\t\t\t\trole: member.role\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE);\n\t\t}\n\t\tif (ctx.body.roleName) {\n\t\t\tconst roleName = ctx.body.roleName;\n\t\t\tconst defaultRoles = options.roles ? Object.keys(options.roles) : [\n\t\t\t\t\"owner\",\n\t\t\t\t\"admin\",\n\t\t\t\t\"member\"\n\t\t\t];\n\t\t\tif (defaultRoles.includes(roleName)) {\n\t\t\t\tctx.context.logger.error(`[Dynamic Access Control] Cannot delete a pre-defined role.`, {\n\t\t\t\t\troleName,\n\t\t\t\t\torganizationId,\n\t\t\t\t\tdefaultRoles\n\t\t\t\t});\n\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.CANNOT_DELETE_A_PRE_DEFINED_ROLE);\n\t\t\t}\n\t\t}\n\t\tlet condition;\n\t\tif (ctx.body.roleName) condition = {\n\t\t\tfield: \"role\",\n\t\t\tvalue: ctx.body.roleName,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse if (ctx.body.roleId) condition = {\n\t\t\tfield: \"id\",\n\t\t\tvalue: ctx.body.roleId,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\tconst existingRoleInDB = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition]\n\t\t});\n\t\tif (!existingRoleInDB) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, {\n\t\t\t\t...\"roleName\" in ctx.body ? { roleName: ctx.body.roleName } : { roleId: ctx.body.roleId },\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\texistingRoleInDB.permission = JSON.parse(existingRoleInDB.permission);\n\t\tconst roleToDelete = existingRoleInDB.role;\n\t\tif ((await ctx.context.adapter.findMany({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"role\",\n\t\t\t\tvalue: roleToDelete,\n\t\t\t\toperator: \"contains\"\n\t\t\t}]\n\t\t})).find((member) => {\n\t\t\treturn member.role.split(\",\").map((r) => r.trim()).includes(roleToDelete);\n\t\t})) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] Cannot delete a role that is assigned to members.`, {\n\t\t\t\trole: existingRoleInDB.role,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_IS_ASSIGNED_TO_MEMBERS);\n\t\t}\n\t\tawait ctx.context.adapter.delete({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition]\n\t\t});\n\t\treturn ctx.json({ success: true });\n\t});\n};\nconst listOrgRolesQuerySchema = z.object({ organizationId: z.string().optional().meta({ description: \"The id of the organization to list roles for. If not provided, the user's active organization will be used.\" }) }).optional();\nconst listOrgRoles = (options) => {\n\tconst { $ReturnAdditionalFields } = getAdditionalFields(options, false);\n\treturn createAuthEndpoint(\"/organization/list-roles\", {\n\t\tmethod: \"GET\",\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware],\n\t\tquery: listOrgRolesQuerySchema\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tconst organizationId = ctx.query?.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to list roles. Either set an active org id, or pass an organizationId in the request query.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\t}\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to list roles.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { ac: [\"read\"] },\n\t\t\trole: member.role\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to list roles.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId,\n\t\t\t\trole: member.role\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE);\n\t\t}\n\t\tlet roles = await ctx.context.adapter.findMany({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\troles = roles.map((x) => ({\n\t\t\t...x,\n\t\t\tpermission: JSON.parse(x.permission)\n\t\t}));\n\t\treturn ctx.json(roles);\n\t});\n};\nconst getOrgRoleQuerySchema = z.object({ organizationId: z.string().optional().meta({ description: \"The id of the organization to read a role for. If not provided, the user's active organization will be used.\" }) }).and(z.union([z.object({ roleName: z.string().nonempty().meta({ description: \"The name of the role to read\" }) }), z.object({ roleId: z.string().nonempty().meta({ description: \"The id of the role to read\" }) })])).optional();\nconst getOrgRole = (options) => {\n\tconst { $ReturnAdditionalFields } = getAdditionalFields(options, false);\n\treturn createAuthEndpoint(\"/organization/get-role\", {\n\t\tmethod: \"GET\",\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware],\n\t\tquery: getOrgRoleQuerySchema,\n\t\tmetadata: { $Infer: { query: {} } }\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tconst organizationId = ctx.query?.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to read a role. Either set an active org id, or pass an organizationId in the request query.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\t}\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to read a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { ac: [\"read\"] },\n\t\t\trole: member.role\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to read a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId,\n\t\t\t\trole: member.role\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE);\n\t\t}\n\t\tlet condition;\n\t\tif (ctx.query.roleName) condition = {\n\t\t\tfield: \"role\",\n\t\t\tvalue: ctx.query.roleName,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse if (ctx.query.roleId) condition = {\n\t\t\tfield: \"id\",\n\t\t\tvalue: ctx.query.roleId,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request query.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\tconst role = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition]\n\t\t});\n\t\tif (!role) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, {\n\t\t\t\t...\"roleName\" in ctx.query ? { roleName: ctx.query.roleName } : { roleId: ctx.query.roleId },\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\trole.permission = JSON.parse(role.permission);\n\t\treturn ctx.json(role);\n\t});\n};\nconst roleNameOrIdSchema = z.union([z.object({ roleName: z.string().nonempty().meta({ description: \"The name of the role to update\" }) }), z.object({ roleId: z.string().nonempty().meta({ description: \"The id of the role to update\" }) })]);\nconst updateOrgRole = (options) => {\n\tconst { additionalFieldsSchema, $AdditionalFields, $ReturnAdditionalFields } = getAdditionalFields(options, true);\n\treturn createAuthEndpoint(\"/organization/update-role\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\torganizationId: z.string().optional().meta({ description: \"The id of the organization to update the role in. If not provided, the user's active organization will be used.\" }),\n\t\t\tdata: z.object({\n\t\t\t\tpermission: z.record(z.string(), z.array(z.string())).optional().meta({ description: \"The permission to update the role with\" }),\n\t\t\t\troleName: z.string().optional().meta({ description: \"The name of the role to update\" }),\n\t\t\t\t...additionalFieldsSchema.shape\n\t\t\t})\n\t\t}).and(roleNameOrIdSchema),\n\t\tmetadata: { $Infer: { body: {} } },\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware]\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tconst ac = options.ac;\n\t\tif (!ac) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.`, `\\nPlease refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`);\n\t\t\tthrow APIError.from(\"NOT_IMPLEMENTED\", ORGANIZATION_ERROR_CODES.MISSING_AC_INSTANCE);\n\t\t}\n\t\tconst organizationId = ctx.body.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to update a role. Either set an active org id, or pass an organizationId in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\t}\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to update a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\trole: member.role,\n\t\t\tpermissions: { ac: [\"update\"] }\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to update a role.`);\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE);\n\t\t}\n\t\tlet condition;\n\t\tif (ctx.body.roleName) condition = {\n\t\t\tfield: \"role\",\n\t\t\tvalue: ctx.body.roleName,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse if (ctx.body.roleId) condition = {\n\t\t\tfield: \"id\",\n\t\t\tvalue: ctx.body.roleId,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\tconst role = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition]\n\t\t});\n\t\tif (!role) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, {\n\t\t\t\t...\"roleName\" in ctx.body ? { roleName: ctx.body.roleName } : { roleId: ctx.body.roleId },\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\trole.permission = role.permission ? JSON.parse(role.permission) : void 0;\n\t\tconst { permission: _, roleName: __, ...additionalFields } = ctx.body.data;\n\t\tconst updateData = { ...additionalFields };\n\t\tif (ctx.body.data.permission) {\n\t\t\tconst newPermission = ctx.body.data.permission;\n\t\t\tawait checkForInvalidResources({\n\t\t\t\tac,\n\t\t\t\tctx,\n\t\t\t\tpermission: newPermission\n\t\t\t});\n\t\t\tawait checkIfMemberHasPermission({\n\t\t\t\tctx,\n\t\t\t\tmember,\n\t\t\t\toptions,\n\t\t\t\torganizationId,\n\t\t\t\tpermissionRequired: newPermission,\n\t\t\t\tuser,\n\t\t\t\taction: \"update\"\n\t\t\t});\n\t\t\tupdateData.permission = newPermission;\n\t\t}\n\t\tif (ctx.body.data.roleName) {\n\t\t\tlet newRoleName = ctx.body.data.roleName;\n\t\t\tnewRoleName = normalizeRoleName(newRoleName);\n\t\t\tawait checkIfRoleNameIsTakenByPreDefinedRole({\n\t\t\t\trole: newRoleName,\n\t\t\t\torganizationId,\n\t\t\t\toptions,\n\t\t\t\tctx\n\t\t\t});\n\t\t\tawait checkIfRoleNameIsTakenByRoleInDB({\n\t\t\t\trole: newRoleName,\n\t\t\t\torganizationId,\n\t\t\t\tctx\n\t\t\t});\n\t\t\tupdateData.role = newRoleName;\n\t\t}\n\t\tconst update = {\n\t\t\t...updateData,\n\t\t\t...updateData.permission ? { permission: JSON.stringify(updateData.permission) } : {}\n\t\t};\n\t\tawait ctx.context.adapter.update({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition],\n\t\t\tupdate\n\t\t});\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t\troleData: {\n\t\t\t\t...role,\n\t\t\t\t...update,\n\t\t\t\tpermission: updateData.permission || role.permission || null\n\t\t\t}\n\t\t});\n\t});\n};\nasync function checkForInvalidResources({ ac, ctx, permission }) {\n\tconst validResources = Object.keys(ac.statements);\n\tconst providedResources = Object.keys(permission);\n\tif (providedResources.some((r) => !validResources.includes(r))) {\n\t\tctx.context.logger.error(`[Dynamic Access Control] The provided permission includes an invalid resource.`, {\n\t\t\tprovidedResources,\n\t\t\tvalidResources\n\t\t});\n\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.INVALID_RESOURCE);\n\t}\n}\nasync function checkIfMemberHasPermission({ ctx, permissionRequired: permission, options, organizationId, member, user, action }) {\n\tconst hasNecessaryPermissions = [];\n\tconst permissionEntries = Object.entries(permission);\n\tfor await (const [resource, permissions] of permissionEntries) for await (const perm of permissions) hasNecessaryPermissions.push({\n\t\tresource: { [resource]: [perm] },\n\t\thasPermission: await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { [resource]: [perm] },\n\t\t\tuseMemoryCache: true,\n\t\t\trole: member.role\n\t\t}, ctx)\n\t});\n\tconst missingPermissions = hasNecessaryPermissions.filter((x) => x.hasPermission === false).map((x) => {\n\t\tconst key = Object.keys(x.resource)[0];\n\t\treturn `${key}:${x.resource[key][0]}`;\n\t});\n\tif (missingPermissions.length > 0) {\n\t\tctx.context.logger.error(`[Dynamic Access Control] The user is missing permissions necessary to ${action} a role with those set of permissions.\\n`, {\n\t\t\tuserId: user.id,\n\t\t\torganizationId,\n\t\t\trole: member.role,\n\t\t\tmissingPermissions\n\t\t});\n\t\tlet error;\n\t\tif (action === \"create\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE;\n\t\telse if (action === \"update\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE;\n\t\telse if (action === \"delete\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE;\n\t\telse if (action === \"read\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE;\n\t\telse if (action === \"list\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE;\n\t\telse error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE;\n\t\tthrow APIError.fromStatus(\"FORBIDDEN\", {\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code,\n\t\t\tmissingPermissions\n\t\t});\n\t}\n}\nasync function checkIfRoleNameIsTakenByPreDefinedRole({ options, organizationId, role, ctx }) {\n\tconst defaultRoles = options.roles ? Object.keys(options.roles) : [\n\t\t\"owner\",\n\t\t\"admin\",\n\t\t\"member\"\n\t];\n\tif (defaultRoles.includes(role)) {\n\t\tctx.context.logger.error(`[Dynamic Access Control] The role name \"${role}\" is already taken by a pre-defined role.`, {\n\t\t\trole,\n\t\t\torganizationId,\n\t\t\tdefaultRoles\n\t\t});\n\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NAME_IS_ALREADY_TAKEN);\n\t}\n}\nasync function checkIfRoleNameIsTakenByRoleInDB({ organizationId, role, ctx }) {\n\tif (await ctx.context.adapter.findOne({\n\t\tmodel: \"organizationRole\",\n\t\twhere: [{\n\t\t\tfield: \"organizationId\",\n\t\t\tvalue: organizationId,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t}, {\n\t\t\tfield: \"role\",\n\t\t\tvalue: role,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t}]\n\t})) {\n\t\tctx.context.logger.error(`[Dynamic Access Control] The role name \"${role}\" is already taken by a role in the database.`, {\n\t\t\trole,\n\t\t\torganizationId\n\t\t});\n\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NAME_IS_ALREADY_TAKEN);\n\t}\n}\n//#endregion\nexport { createOrgRole, deleteOrgRole, getOrgRole, listOrgRoles, updateOrgRole };\n", "import { getDate } from \"../../../utils/date.mjs\";\nimport { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { getSessionFromCtx } from \"../../../api/routes/session.mjs\";\nimport { defaultRoles } from \"../access/statement.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { getOrgAdapter } from \"../adapter.mjs\";\nimport { orgMiddleware, orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { parseRoles } from \"../organization.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-invites.ts\nconst baseInvitationSchema = z.object({\n\temail: z.string().meta({ description: \"The email address of the user to invite\" }),\n\trole: z.union([z.string().meta({ description: \"The role to assign to the user\" }), z.array(z.string().meta({ description: \"The roles to assign to the user\" }))]).meta({ description: \"The role(s) to assign to the user. It can be `admin`, `member`, owner. Eg: \\\"member\\\"\" }),\n\torganizationId: z.string().meta({ description: \"The organization ID to invite the user to\" }).optional(),\n\tresend: z.boolean().meta({ description: \"Resend the invitation email, if the user is already invited. Eg: true\" }).optional(),\n\tteamId: z.union([z.string().meta({ description: \"The team ID to invite the user to\" }).optional(), z.array(z.string()).meta({ description: \"The team IDs to invite the user to\" }).optional()])\n});\nconst createInvitation = (option) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: option?.schema?.invitation?.additionalFields || {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/invite-member\", {\n\t\tmethod: \"POST\",\n\t\trequireHeaders: true,\n\t\tuse: [orgMiddleware, orgSessionMiddleware],\n\t\tbody: z.object({\n\t\t\t...baseInvitationSchema.shape,\n\t\t\t...additionalFieldsSchema.shape\n\t\t}),\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\toperationId: \"createOrganizationInvitation\",\n\t\t\t\tdescription: \"Create an invitation to an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\t\temail: { type: \"string\" },\n\t\t\t\t\t\t\trole: { type: \"string\" },\n\t\t\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\t\t\tinviterId: { type: \"string\" },\n\t\t\t\t\t\t\tstatus: { type: \"string\" },\n\t\t\t\t\t\t\texpiresAt: { type: \"string\" },\n\t\t\t\t\t\t\tcreatedAt: { type: \"string\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"email\",\n\t\t\t\t\t\t\t\"role\",\n\t\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\t\"inviterId\",\n\t\t\t\t\t\t\t\"status\",\n\t\t\t\t\t\t\t\"expiresAt\",\n\t\t\t\t\t\t\t\"createdAt\"\n\t\t\t\t\t\t]\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = ctx.context.session;\n\t\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tconst email = ctx.body.email.toLowerCase();\n\t\tif (!z.email().safeParse(email).success) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_EMAIL);\n\t\tconst adapter = getOrgAdapter(ctx.context, option);\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\t\tif (!await hasPermission({\n\t\t\trole: member.role,\n\t\t\toptions: ctx.context.orgOptions,\n\t\t\tpermissions: { invitation: [\"create\"] },\n\t\t\torganizationId\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION);\n\t\tconst creatorRole = ctx.context.orgOptions.creatorRole || \"owner\";\n\t\tconst roles = parseRoles(ctx.body.role);\n\t\tconst rolesArray = roles.split(\",\").map((r) => r.trim()).filter(Boolean);\n\t\tconst defaults = Object.keys(defaultRoles);\n\t\tconst customRoles = Object.keys(ctx.context.orgOptions.roles || {});\n\t\tconst validStaticRoles = new Set([...defaults, ...customRoles]);\n\t\tconst unknownRoles = rolesArray.filter((role) => !validStaticRoles.has(role));\n\t\tif (unknownRoles.length > 0) if (ctx.context.orgOptions.dynamicAccessControl?.enabled) {\n\t\t\tconst foundRoleNames = (await ctx.context.adapter.findMany({\n\t\t\t\tmodel: \"organizationRole\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"role\",\n\t\t\t\t\tvalue: unknownRoles,\n\t\t\t\t\toperator: \"in\"\n\t\t\t\t}]\n\t\t\t})).map((r) => r.role);\n\t\t\tconst stillInvalid = unknownRoles.filter((r) => !foundRoleNames.includes(r));\n\t\t\tif (stillInvalid.length > 0) throw new APIError(\"BAD_REQUEST\", { message: `${ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND}: ${stillInvalid.join(\", \")}` });\n\t\t} else throw new APIError(\"BAD_REQUEST\", { message: `${ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND}: ${unknownRoles.join(\", \")}` });\n\t\tif (!member.role.split(\",\").map((r) => r.trim()).includes(creatorRole) && roles.split(\",\").includes(creatorRole)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE);\n\t\tif (await adapter.findMemberByEmail({\n\t\t\temail,\n\t\t\torganizationId\n\t\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\tconst alreadyInvited = await adapter.findPendingInvitation({\n\t\t\temail,\n\t\t\torganizationId\n\t\t});\n\t\tif (alreadyInvited.length && !ctx.body.resend) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION);\n\t\tconst organization = await adapter.findOrganizationById(organizationId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tif (alreadyInvited.length && ctx.body.resend) {\n\t\t\tconst existingInvitation = alreadyInvited[0];\n\t\t\tconst newExpiresAt = getDate(ctx.context.orgOptions.invitationExpiresIn || 3600 * 48, \"sec\");\n\t\t\tawait ctx.context.adapter.update({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: existingInvitation.id\n\t\t\t\t}],\n\t\t\t\tupdate: { expiresAt: newExpiresAt }\n\t\t\t});\n\t\t\tconst updatedInvitation = {\n\t\t\t\t...existingInvitation,\n\t\t\t\texpiresAt: newExpiresAt\n\t\t\t};\n\t\t\tif (ctx.context.orgOptions.sendInvitationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.orgOptions.sendInvitationEmail({\n\t\t\t\tid: updatedInvitation.id,\n\t\t\t\trole: updatedInvitation.role,\n\t\t\t\temail: updatedInvitation.email.toLowerCase(),\n\t\t\t\torganization,\n\t\t\t\tinviter: {\n\t\t\t\t\t...member,\n\t\t\t\t\tuser: session.user\n\t\t\t\t},\n\t\t\t\tinvitation: updatedInvitation\n\t\t\t}, ctx.request));\n\t\t\treturn ctx.json(updatedInvitation);\n\t\t}\n\t\tif (alreadyInvited.length && ctx.context.orgOptions.cancelPendingInvitationsOnReInvite) await adapter.updateInvitation({\n\t\t\tinvitationId: alreadyInvited[0].id,\n\t\t\tstatus: \"canceled\"\n\t\t});\n\t\tconst invitationLimit = typeof ctx.context.orgOptions.invitationLimit === \"function\" ? await ctx.context.orgOptions.invitationLimit({\n\t\t\tuser: session.user,\n\t\t\torganization,\n\t\t\tmember\n\t\t}, ctx.context) : ctx.context.orgOptions.invitationLimit ?? 100;\n\t\tif ((await adapter.findPendingInvitations({ organizationId })).length >= invitationLimit) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.INVITATION_LIMIT_REACHED);\n\t\tif (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== \"undefined\" && \"teamId\" in ctx.body && ctx.body.teamId) {\n\t\t\tconst teamIds = typeof ctx.body.teamId === \"string\" ? [ctx.body.teamId] : ctx.body.teamId;\n\t\t\tfor (const teamId of teamIds) {\n\t\t\t\tconst team = await adapter.findTeamById({\n\t\t\t\t\tteamId,\n\t\t\t\t\torganizationId,\n\t\t\t\t\tincludeTeamMembers: true\n\t\t\t\t});\n\t\t\t\tif (!team) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\t\t\t\tconst maximumMembersPerTeam = typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === \"function\" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({\n\t\t\t\t\tteamId,\n\t\t\t\t\tsession,\n\t\t\t\t\torganizationId\n\t\t\t\t}) : ctx.context.orgOptions.teams.maximumMembersPerTeam;\n\t\t\t\tif (team.members.length >= maximumMembersPerTeam) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED);\n\t\t\t}\n\t\t}\n\t\tconst teamIds = \"teamId\" in ctx.body ? typeof ctx.body.teamId === \"string\" ? [ctx.body.teamId] : ctx.body.teamId ?? [] : [];\n\t\tconst { email: _, role: __, organizationId: ___, resend: ____, ...additionalFields } = ctx.body;\n\t\tlet invitationData = {\n\t\t\trole: roles,\n\t\t\temail,\n\t\t\torganizationId,\n\t\t\tteamIds,\n\t\t\t...additionalFields ? additionalFields : {}\n\t\t};\n\t\tif (option?.organizationHooks?.beforeCreateInvitation) {\n\t\t\tconst response = await option?.organizationHooks.beforeCreateInvitation({\n\t\t\t\tinvitation: {\n\t\t\t\t\t...invitationData,\n\t\t\t\t\tinviterId: session.user.id,\n\t\t\t\t\tteamId: teamIds.length > 0 ? teamIds[0] : void 0\n\t\t\t\t},\n\t\t\t\tinviter: session.user,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) invitationData = {\n\t\t\t\t...invitationData,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst invitation = await adapter.createInvitation({\n\t\t\tinvitation: invitationData,\n\t\t\tuser: session.user\n\t\t});\n\t\tif (ctx.context.orgOptions.sendInvitationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.orgOptions.sendInvitationEmail({\n\t\t\tid: invitation.id,\n\t\t\trole: invitation.role,\n\t\t\temail: invitation.email.toLowerCase(),\n\t\t\torganization,\n\t\t\tinviter: {\n\t\t\t\t...member,\n\t\t\t\tuser: session.user\n\t\t\t},\n\t\t\tinvitation\n\t\t}, ctx.request));\n\t\tif (option?.organizationHooks?.afterCreateInvitation) await option?.organizationHooks.afterCreateInvitation({\n\t\t\tinvitation,\n\t\t\tinviter: session.user,\n\t\t\torganization\n\t\t});\n\t\treturn ctx.json(invitation);\n\t});\n};\nconst acceptInvitationBodySchema = z.object({ invitationId: z.string().meta({ description: \"The ID of the invitation to accept\" }) });\nconst acceptInvitation = (options) => createAuthEndpoint(\"/organization/accept-invitation\", {\n\tmethod: \"POST\",\n\tbody: acceptInvitationBodySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Accept an invitation to an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tinvitation: { type: \"object\" },\n\t\t\t\t\tmember: { type: \"object\" }\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst invitation = await adapter.findInvitationById(ctx.body.invitationId);\n\tif (!invitation || invitation.expiresAt < /* @__PURE__ */ new Date() || invitation.status !== \"pending\") throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND);\n\tif (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);\n\tif (ctx.context.orgOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION);\n\tconst membershipLimit = ctx.context.orgOptions?.membershipLimit || 100;\n\tconst membersCount = await adapter.countMembers({ organizationId: invitation.organizationId });\n\tconst organization = await adapter.findOrganizationById(invitation.organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (membersCount >= (typeof membershipLimit === \"number\" ? membershipLimit : await membershipLimit(session.user, organization))) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED);\n\tif (options?.organizationHooks?.beforeAcceptInvitation) await options?.organizationHooks.beforeAcceptInvitation({\n\t\tinvitation,\n\t\tuser: session.user,\n\t\torganization\n\t});\n\tconst acceptedI = await adapter.updateInvitation({\n\t\tinvitationId: ctx.body.invitationId,\n\t\tstatus: \"accepted\"\n\t});\n\tif (!acceptedI) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.FAILED_TO_RETRIEVE_INVITATION);\n\tif (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && \"teamId\" in acceptedI && acceptedI.teamId) {\n\t\tconst teamIds = acceptedI.teamId.split(\",\");\n\t\tconst onlyOne = teamIds.length === 1;\n\t\tfor (const teamId of teamIds) {\n\t\t\tawait adapter.findOrCreateTeamMember({\n\t\t\t\tteamId,\n\t\t\t\tuserId: session.user.id\n\t\t\t});\n\t\t\tif (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== \"undefined\") {\n\t\t\t\tif (await adapter.countTeamMembers({ teamId }) >= (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === \"function\" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({\n\t\t\t\t\tteamId,\n\t\t\t\t\tsession,\n\t\t\t\t\torganizationId: invitation.organizationId\n\t\t\t\t}) : ctx.context.orgOptions.teams.maximumMembersPerTeam)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED);\n\t\t\t}\n\t\t}\n\t\tif (onlyOne) {\n\t\t\tconst teamId = teamIds[0];\n\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\tsession: await adapter.setActiveTeam(session.session.token, teamId, ctx),\n\t\t\t\tuser: session.user\n\t\t\t});\n\t\t}\n\t}\n\tconst member = await adapter.createMember({\n\t\torganizationId: invitation.organizationId,\n\t\tuserId: session.user.id,\n\t\trole: invitation.role,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n\tawait adapter.setActiveOrganization(session.session.token, invitation.organizationId, ctx);\n\tif (options?.organizationHooks?.afterAcceptInvitation) await options?.organizationHooks.afterAcceptInvitation({\n\t\tinvitation: acceptedI,\n\t\tmember,\n\t\tuser: session.user,\n\t\torganization\n\t});\n\treturn ctx.json({\n\t\tinvitation: acceptedI,\n\t\tmember\n\t});\n});\nconst rejectInvitationBodySchema = z.object({ invitationId: z.string().meta({ description: \"The ID of the invitation to reject\" }) });\nconst rejectInvitation = (options) => createAuthEndpoint(\"/organization/reject-invitation\", {\n\tmethod: \"POST\",\n\tbody: rejectInvitationBodySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Reject an invitation to an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tinvitation: { type: \"object\" },\n\t\t\t\t\tmember: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tnullable: true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst invitation = await adapter.findInvitationById(ctx.body.invitationId);\n\tif (!invitation || invitation.status !== \"pending\") throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: \"Invitation not found!\",\n\t\tcode: \"INVITATION_NOT_FOUND\"\n\t});\n\tif (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);\n\tif (ctx.context.orgOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION);\n\tconst organization = await adapter.findOrganizationById(invitation.organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (options?.organizationHooks?.beforeRejectInvitation) await options?.organizationHooks.beforeRejectInvitation({\n\t\tinvitation,\n\t\tuser: session.user,\n\t\torganization\n\t});\n\tconst rejectedI = await adapter.updateInvitation({\n\t\tinvitationId: ctx.body.invitationId,\n\t\tstatus: \"rejected\"\n\t});\n\tif (options?.organizationHooks?.afterRejectInvitation) await options?.organizationHooks.afterRejectInvitation({\n\t\tinvitation: rejectedI || invitation,\n\t\tuser: session.user,\n\t\torganization\n\t});\n\treturn ctx.json({\n\t\tinvitation: rejectedI,\n\t\tmember: null\n\t});\n});\nconst cancelInvitationBodySchema = z.object({ invitationId: z.string().meta({ description: \"The ID of the invitation to cancel\" }) });\nconst cancelInvitation = (options) => createAuthEndpoint(\"/organization/cancel-invitation\", {\n\tmethod: \"POST\",\n\tbody: cancelInvitationBodySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\topenapi: {\n\t\toperationId: \"cancelOrganizationInvitation\",\n\t\tdescription: \"Cancel an invitation to an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { invitation: { type: \"object\" } }\n\t\t\t} } }\n\t\t} }\n\t}\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst invitation = await adapter.findInvitationById(ctx.body.invitationId);\n\tif (!invitation) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND);\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId: invitation.organizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tif (!await hasPermission({\n\t\trole: member.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { invitation: [\"cancel\"] },\n\t\torganizationId: invitation.organizationId\n\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION);\n\tconst organization = await adapter.findOrganizationById(invitation.organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (options?.organizationHooks?.beforeCancelInvitation) await options?.organizationHooks.beforeCancelInvitation({\n\t\tinvitation,\n\t\tcancelledBy: session.user,\n\t\torganization\n\t});\n\tconst canceledI = await adapter.updateInvitation({\n\t\tinvitationId: ctx.body.invitationId,\n\t\tstatus: \"canceled\"\n\t});\n\tif (options?.organizationHooks?.afterCancelInvitation) await options?.organizationHooks.afterCancelInvitation({\n\t\tinvitation: canceledI || invitation,\n\t\tcancelledBy: session.user,\n\t\torganization\n\t});\n\treturn ctx.json(canceledI);\n});\nconst getInvitationQuerySchema = z.object({ id: z.string().meta({ description: \"The ID of the invitation to get\" }) });\nconst getInvitation = (options) => createAuthEndpoint(\"/organization/get-invitation\", {\n\tmethod: \"GET\",\n\tuse: [orgMiddleware],\n\trequireHeaders: true,\n\tquery: getInvitationQuerySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"Get an invitation by ID\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\temail: { type: \"string\" },\n\t\t\t\t\trole: { type: \"string\" },\n\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\tinviterId: { type: \"string\" },\n\t\t\t\t\tstatus: { type: \"string\" },\n\t\t\t\t\texpiresAt: { type: \"string\" },\n\t\t\t\t\torganizationName: { type: \"string\" },\n\t\t\t\t\torganizationSlug: { type: \"string\" },\n\t\t\t\t\tinviterEmail: { type: \"string\" }\n\t\t\t\t},\n\t\t\t\trequired: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"email\",\n\t\t\t\t\t\"role\",\n\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\"inviterId\",\n\t\t\t\t\t\"status\",\n\t\t\t\t\t\"expiresAt\",\n\t\t\t\t\t\"organizationName\",\n\t\t\t\t\t\"organizationSlug\",\n\t\t\t\t\t\"inviterEmail\"\n\t\t\t\t]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw APIError.fromStatus(\"UNAUTHORIZED\", { message: \"Not authenticated\" });\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst invitation = await adapter.findInvitationById(ctx.query.id);\n\tif (!invitation || invitation.status !== \"pending\" || invitation.expiresAt < /* @__PURE__ */ new Date()) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"Invitation not found!\" });\n\tif (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);\n\tconst organization = await adapter.findOrganizationById(invitation.organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: invitation.inviterId,\n\t\torganizationId: invitation.organizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION);\n\treturn ctx.json({\n\t\t...invitation,\n\t\torganizationName: organization.name,\n\t\torganizationSlug: organization.slug,\n\t\tinviterEmail: member.user.email\n\t});\n});\nconst listInvitationQuerySchema = z.object({ organizationId: z.string().meta({ description: \"The ID of the organization to list invitations for\" }).optional() }).optional();\nconst listInvitations = (options) => createAuthEndpoint(\"/organization/list-invitations\", {\n\tmethod: \"GET\",\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tquery: listInvitationQuerySchema\n}, async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw APIError.fromStatus(\"UNAUTHORIZED\", { message: \"Not authenticated\" });\n\tconst orgId = ctx.query?.organizationId || session.session.activeOrganizationId;\n\tif (!orgId) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"Organization ID is required\" });\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId: orgId\n\t})) throw APIError.fromStatus(\"FORBIDDEN\", { message: \"You are not a member of this organization\" });\n\tconst invitations = await adapter.listInvitations({ organizationId: orgId });\n\treturn ctx.json(invitations);\n});\n/**\n* List all invitations a user has received\n*/\nconst listUserInvitations = (options) => createAuthEndpoint(\"/organization/list-user-invitations\", {\n\tmethod: \"GET\",\n\tuse: [orgMiddleware],\n\tquery: z.object({ email: z.string().meta({ description: \"The email of the user to list invitations for. This only works for server side API calls.\" }).optional() }).optional(),\n\tmetadata: { openapi: {\n\t\tdescription: \"List all invitations a user has received\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\temail: { type: \"string\" },\n\t\t\t\t\t\trole: { type: \"string\" },\n\t\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\t\torganizationName: { type: \"string\" },\n\t\t\t\t\t\tinviterId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The ID of the user who created the invitation\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tteamId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The ID of the team associated with the invitation\",\n\t\t\t\t\t\t\tnullable: true\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: { type: \"string\" },\n\t\t\t\t\t\texpiresAt: { type: \"string\" },\n\t\t\t\t\t\tcreatedAt: { type: \"string\" }\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"email\",\n\t\t\t\t\t\t\"role\",\n\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\"organizationName\",\n\t\t\t\t\t\t\"inviterId\",\n\t\t\t\t\t\t\"status\",\n\t\t\t\t\t\t\"expiresAt\",\n\t\t\t\t\t\t\"createdAt\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (ctx.request && ctx.query?.email) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User email cannot be passed for client side API calls.\" });\n\tconst userEmail = session?.user.email || ctx.query?.email;\n\tif (!userEmail) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"Missing session headers, or email query parameter.\" });\n\tconst pendingInvitations = (await getOrgAdapter(ctx.context, options).listUserInvitations(userEmail)).filter((inv) => inv.status === \"pending\");\n\treturn ctx.json(pendingInvitations);\n});\n//#endregion\nexport { acceptInvitation, cancelInvitation, createInvitation, getInvitation, listInvitations, listUserInvitations, rejectInvitation };\n", "import { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { getSessionFromCtx, sessionMiddleware } from \"../../../api/routes/session.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { getOrgAdapter } from \"../adapter.mjs\";\nimport { orgMiddleware, orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { parseRoles } from \"../organization.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { whereOperators } from \"@better-auth/core/db/adapter\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-members.ts\nconst baseMemberSchema = z.object({\n\tuserId: z.coerce.string().meta({ description: \"The user Id which represents the user to be added as a member. If `null` is provided, then it's expected to provide session headers. Eg: \\\"user-id\\\"\" }),\n\trole: z.union([z.string(), z.array(z.string())]).meta({ description: \"The role(s) to assign to the new member. Eg: [\\\"admin\\\", \\\"sale\\\"]\" }),\n\torganizationId: z.string().meta({ description: \"An optional organization ID to pass. If not provided, will default to the user's active organization. Eg: \\\"org-id\\\"\" }).optional(),\n\tteamId: z.string().meta({ description: \"An optional team ID to add the member to. Eg: \\\"team-id\\\"\" }).optional()\n});\nconst addMember = (option) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: option?.schema?.member?.additionalFields || {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint({\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\t...baseMemberSchema.shape,\n\t\t\t...additionalFieldsSchema.shape\n\t\t}),\n\t\tuse: [orgMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\toperationId: \"addOrganizationMember\",\n\t\t\t\tdescription: \"Add a member to an organization\"\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = ctx.body.userId ? await getSessionFromCtx(ctx).catch((e) => null) : null;\n\t\tconst orgId = ctx.body.organizationId || session?.session.activeOrganizationId;\n\t\tif (!orgId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\tconst teamId = \"teamId\" in ctx.body ? ctx.body.teamId : void 0;\n\t\tif (teamId && !ctx.context.orgOptions.teams?.enabled) {\n\t\t\tctx.context.logger.error(\"Teams are not enabled\");\n\t\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Teams are not enabled\" });\n\t\t}\n\t\tconst adapter = getOrgAdapter(ctx.context, option);\n\t\tconst user = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n\t\tif (!user) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.USER_NOT_FOUND);\n\t\tif (await adapter.findMemberByEmail({\n\t\t\temail: user.email,\n\t\t\torganizationId: orgId\n\t\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\tif (teamId) {\n\t\t\tconst team = await adapter.findTeamById({\n\t\t\t\tteamId,\n\t\t\t\torganizationId: orgId\n\t\t\t});\n\t\t\tif (!team || team.organizationId !== orgId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\t\t}\n\t\tconst membershipLimit = ctx.context.orgOptions?.membershipLimit || 100;\n\t\tconst count = await adapter.countMembers({ organizationId: orgId });\n\t\tconst organization = await adapter.findOrganizationById(orgId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tif (count >= (typeof membershipLimit === \"number\" ? membershipLimit : await membershipLimit(user, organization))) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED);\n\t\tconst { role: _, userId: __, organizationId: ___, ...additionalFields } = ctx.body;\n\t\tlet memberData = {\n\t\t\torganizationId: orgId,\n\t\t\tuserId: user.id,\n\t\t\trole: parseRoles(ctx.body.role),\n\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t...additionalFields ? additionalFields : {}\n\t\t};\n\t\tif (option?.organizationHooks?.beforeAddMember) {\n\t\t\tconst response = await option?.organizationHooks.beforeAddMember({\n\t\t\t\tmember: {\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\torganizationId: orgId,\n\t\t\t\t\trole: parseRoles(ctx.body.role),\n\t\t\t\t\t...additionalFields\n\t\t\t\t},\n\t\t\t\tuser,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) memberData = {\n\t\t\t\t...memberData,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst createdMember = await adapter.createMember(memberData);\n\t\tif (teamId) await adapter.findOrCreateTeamMember({\n\t\t\tuserId: user.id,\n\t\t\tteamId\n\t\t});\n\t\tif (option?.organizationHooks?.afterAddMember) await option?.organizationHooks.afterAddMember({\n\t\t\tmember: createdMember,\n\t\t\tuser,\n\t\t\torganization\n\t\t});\n\t\treturn ctx.json(createdMember);\n\t});\n};\nconst removeMemberBodySchema = z.object({\n\tmemberIdOrEmail: z.string().meta({ description: \"The ID or email of the member to remove\" }),\n\torganizationId: z.string().meta({ description: \"The ID of the organization to remove the member from. If not provided, the active organization will be used. Eg: \\\"org-id\\\"\" }).optional()\n});\nconst removeMember = (options) => createAuthEndpoint(\"/organization/remove-member\", {\n\tmethod: \"POST\",\n\tbody: removeMemberBodySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Remove a member from an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { member: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\tuserId: { type: \"string\" },\n\t\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\t\trole: { type: \"string\" }\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\"role\"\n\t\t\t\t\t]\n\t\t\t\t} },\n\t\t\t\trequired: [\"member\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tlet toBeRemovedMember = null;\n\tif (ctx.body.memberIdOrEmail.includes(\"@\")) toBeRemovedMember = await adapter.findMemberByEmail({\n\t\temail: ctx.body.memberIdOrEmail,\n\t\torganizationId\n\t});\n\telse {\n\t\tconst result = await adapter.findMemberById(ctx.body.memberIdOrEmail);\n\t\tif (!result) toBeRemovedMember = null;\n\t\telse {\n\t\t\tconst { user: _user, ...member } = result;\n\t\t\ttoBeRemovedMember = member;\n\t\t}\n\t}\n\tif (!toBeRemovedMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tconst roles = toBeRemovedMember.role.split(\",\");\n\tconst creatorRole = ctx.context.orgOptions?.creatorRole || \"owner\";\n\tif (roles.includes(creatorRole)) {\n\t\tif (!member.role.split(\",\").map((r) => r.trim()).includes(creatorRole)) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);\n\t\tconst { members } = await adapter.listMembers({ organizationId });\n\t\tif (members.filter((member) => {\n\t\t\treturn member.role.split(\",\").includes(creatorRole);\n\t\t}).length <= 1) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);\n\t}\n\tif (!await hasPermission({\n\t\trole: member.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { member: [\"delete\"] },\n\t\torganizationId\n\t}, ctx)) throw APIError.from(\"UNAUTHORIZED\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER);\n\tif (toBeRemovedMember?.organizationId !== organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst userBeingRemoved = await ctx.context.internalAdapter.findUserById(toBeRemovedMember.userId);\n\tif (!userBeingRemoved) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User not found\" });\n\tif (options?.organizationHooks?.beforeRemoveMember) await options?.organizationHooks.beforeRemoveMember({\n\t\tmember: toBeRemovedMember,\n\t\tuser: userBeingRemoved,\n\t\torganization\n\t});\n\tawait adapter.deleteMember({\n\t\tmemberId: toBeRemovedMember.id,\n\t\torganizationId,\n\t\tuserId: toBeRemovedMember.userId\n\t});\n\tif (session.user.id === toBeRemovedMember.userId && session.session.activeOrganizationId === toBeRemovedMember.organizationId) await adapter.setActiveOrganization(session.session.token, null, ctx);\n\tif (options?.organizationHooks?.afterRemoveMember) await options?.organizationHooks.afterRemoveMember({\n\t\tmember: toBeRemovedMember,\n\t\tuser: userBeingRemoved,\n\t\torganization\n\t});\n\treturn ctx.json({ member: toBeRemovedMember });\n});\nconst updateMemberRoleBodySchema = z.object({\n\trole: z.union([z.string(), z.array(z.string())]).meta({ description: \"The new role to be applied. This can be a string or array of strings representing the roles. Eg: [\\\"admin\\\", \\\"sale\\\"]\" }),\n\tmemberId: z.string().meta({ description: \"The member id to apply the role update to. Eg: \\\"member-id\\\"\" }),\n\torganizationId: z.string().meta({ description: \"An optional organization ID which the member is a part of to apply the role update. If not provided, you must provide session headers to get the active organization. Eg: \\\"organization-id\\\"\" }).optional()\n});\nconst updateMemberRole = (option) => createAuthEndpoint(\"/organization/update-member-role\", {\n\tmethod: \"POST\",\n\tbody: updateMemberRoleBodySchema,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: {\n\t\t$Infer: { body: {} },\n\t\topenapi: {\n\t\t\toperationId: \"updateOrganizationMemberRole\",\n\t\t\tdescription: \"Update the role of a member in an organization\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { member: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\t\tuserId: { type: \"string\" },\n\t\t\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\t\t\trole: { type: \"string\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\t\"role\"\n\t\t\t\t\t\t]\n\t\t\t\t\t} },\n\t\t\t\t\trequired: [\"member\"]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tif (!ctx.body.role) throw APIError.fromStatus(\"BAD_REQUEST\");\n\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst roleToSet = Array.isArray(ctx.body.role) ? ctx.body.role : ctx.body.role ? [ctx.body.role] : [];\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tconst toBeUpdatedMember = member.id !== ctx.body.memberId ? await adapter.findMemberById(ctx.body.memberId) : member;\n\tif (!toBeUpdatedMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tif (!(toBeUpdatedMember.organizationId === organizationId)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);\n\tconst creatorRole = ctx.context.orgOptions?.creatorRole || \"owner\";\n\tconst updatingMemberRoles = member.role.split(\",\");\n\tconst isUpdatingCreator = toBeUpdatedMember.role.split(\",\").includes(creatorRole);\n\tconst updaterIsCreator = updatingMemberRoles.includes(creatorRole);\n\tconst isSettingCreatorRole = roleToSet.includes(creatorRole);\n\tconst memberIsUpdatingThemselves = member.id === toBeUpdatedMember.id;\n\tif (isUpdatingCreator && !updaterIsCreator || isSettingCreatorRole && !updaterIsCreator) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);\n\tif (updaterIsCreator && memberIsUpdatingThemselves) {\n\t\tif ((await ctx.context.adapter.findMany({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId\n\t\t\t}]\n\t\t})).filter((member) => {\n\t\t\treturn member.role.split(\",\").includes(creatorRole);\n\t\t}).length <= 1 && !isSettingCreatorRole) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER);\n\t}\n\tif (!await hasPermission({\n\t\trole: member.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { member: [\"update\"] },\n\t\tallowCreatorAllPermissions: true,\n\t\torganizationId\n\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst userBeingUpdated = await ctx.context.internalAdapter.findUserById(toBeUpdatedMember.userId);\n\tif (!userBeingUpdated) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User not found\" });\n\tconst previousRole = toBeUpdatedMember.role;\n\tconst newRole = parseRoles(ctx.body.role);\n\tif (option?.organizationHooks?.beforeUpdateMemberRole) {\n\t\tconst response = await option?.organizationHooks.beforeUpdateMemberRole({\n\t\t\tmember: toBeUpdatedMember,\n\t\t\tnewRole,\n\t\t\tuser: userBeingUpdated,\n\t\t\torganization\n\t\t});\n\t\tif (response && typeof response === \"object\" && \"data\" in response) {\n\t\t\tconst updatedMember = await adapter.updateMember(ctx.body.memberId, response.data.role || newRole);\n\t\t\tif (!updatedMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\t\t\tif (option?.organizationHooks?.afterUpdateMemberRole) await option?.organizationHooks.afterUpdateMemberRole({\n\t\t\t\tmember: updatedMember,\n\t\t\t\tpreviousRole,\n\t\t\t\tuser: userBeingUpdated,\n\t\t\t\torganization\n\t\t\t});\n\t\t\treturn ctx.json(updatedMember);\n\t\t}\n\t}\n\tconst updatedMember = await adapter.updateMember(ctx.body.memberId, newRole);\n\tif (!updatedMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tif (option?.organizationHooks?.afterUpdateMemberRole) await option?.organizationHooks.afterUpdateMemberRole({\n\t\tmember: updatedMember,\n\t\tpreviousRole,\n\t\tuser: userBeingUpdated,\n\t\torganization\n\t});\n\treturn ctx.json(updatedMember);\n});\nconst getActiveMember = (options) => createAuthEndpoint(\"/organization/get-active-member\", {\n\tmethod: \"GET\",\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"Get the member details of the active organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\tuserId: { type: \"string\" },\n\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\trole: { type: \"string\" }\n\t\t\t\t},\n\t\t\t\trequired: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"userId\",\n\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\"role\"\n\t\t\t\t]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst organizationId = session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst member = await getOrgAdapter(ctx.context, options).findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\treturn ctx.json(member);\n});\nconst leaveOrganizationBodySchema = z.object({ organizationId: z.string().meta({ description: \"The organization Id for the member to leave. Eg: \\\"organization-id\\\"\" }) });\nconst leaveOrganization = (options) => createAuthEndpoint(\"/organization/leave\", {\n\tmethod: \"POST\",\n\tbody: leaveOrganizationBodySchema,\n\trequireHeaders: true,\n\tuse: [sessionMiddleware, orgMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId: ctx.body.organizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tconst creatorRole = ctx.context.orgOptions?.creatorRole || \"owner\";\n\tif (member.role.split(\",\").includes(creatorRole)) {\n\t\tif ((await ctx.context.adapter.findMany({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: ctx.body.organizationId\n\t\t\t}]\n\t\t})).filter((member) => member.role.split(\",\").includes(creatorRole)).length <= 1) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);\n\t}\n\tawait adapter.deleteMember({\n\t\tmemberId: member.id,\n\t\torganizationId: ctx.body.organizationId,\n\t\tuserId: session.user.id\n\t});\n\tif (session.session.activeOrganizationId === ctx.body.organizationId) await adapter.setActiveOrganization(session.session.token, null, ctx);\n\treturn ctx.json(member);\n});\nconst listMembers = (options) => createAuthEndpoint(\"/organization/list-members\", {\n\tmethod: \"GET\",\n\tquery: z.object({\n\t\tlimit: z.string().meta({ description: \"The number of users to return\" }).or(z.number()).optional(),\n\t\toffset: z.string().meta({ description: \"The offset to start from\" }).or(z.number()).optional(),\n\t\tsortBy: z.string().meta({ description: \"The field to sort by\" }).optional(),\n\t\tsortDirection: z.enum([\"asc\", \"desc\"]).meta({ description: \"The direction to sort by\" }).optional(),\n\t\tfilterField: z.string().meta({ description: \"The field to filter by\" }).optional(),\n\t\tfilterValue: z.string().meta({ description: \"The value to filter by\" }).or(z.number()).or(z.boolean()).or(z.array(z.string())).or(z.array(z.number())).optional(),\n\t\tfilterOperator: z.enum(whereOperators).meta({ description: \"The operator to use for the filter\" }).optional(),\n\t\torganizationId: z.string().meta({ description: \"The organization ID to list members for. If not provided, will default to the user's active organization. Eg: \\\"organization-id\\\"\" }).optional(),\n\t\torganizationSlug: z.string().meta({ description: \"The organization slug to list members for. If not provided, will default to the user's active organization. Eg: \\\"organization-slug\\\"\" }).optional()\n\t}).optional(),\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tlet organizationId = ctx.query?.organizationId || session.session.activeOrganizationId;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (ctx.query?.organizationSlug) {\n\t\tconst organization = await adapter.findOrganizationBySlug(ctx.query?.organizationSlug);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\torganizationId = organization.id;\n\t}\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t})) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\tconst { members, total } = await adapter.listMembers({\n\t\torganizationId,\n\t\tlimit: ctx.query?.limit ? Number(ctx.query.limit) : void 0,\n\t\toffset: ctx.query?.offset ? Number(ctx.query.offset) : void 0,\n\t\tsortBy: ctx.query?.sortBy,\n\t\tsortOrder: ctx.query?.sortDirection,\n\t\tfilter: ctx.query?.filterField ? {\n\t\t\tfield: ctx.query?.filterField,\n\t\t\toperator: ctx.query.filterOperator,\n\t\t\tvalue: ctx.query.filterValue\n\t\t} : void 0\n\t});\n\treturn ctx.json({\n\t\tmembers,\n\t\ttotal\n\t});\n});\nconst getActiveMemberRoleQuerySchema = z.object({\n\tuserId: z.string().meta({ description: \"The user ID to get the role for. If not provided, will default to the current user's\" }).optional(),\n\torganizationId: z.string().meta({ description: \"The organization ID to list members for. If not provided, will default to the user's active organization. Eg: \\\"organization-id\\\"\" }).optional(),\n\torganizationSlug: z.string().meta({ description: \"The organization slug to list members for. If not provided, will default to the user's active organization. Eg: \\\"organization-slug\\\"\" }).optional()\n}).optional();\nconst getActiveMemberRole = (options) => createAuthEndpoint(\"/organization/get-active-member-role\", {\n\tmethod: \"GET\",\n\tquery: getActiveMemberRoleQuerySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tlet organizationId = ctx.query?.organizationId || session.session.activeOrganizationId;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (ctx.query?.organizationSlug) {\n\t\tconst organization = await adapter.findOrganizationBySlug(ctx.query?.organizationSlug);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\torganizationId = organization.id;\n\t}\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst isMember = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!isMember) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\tif (!ctx.query?.userId) return ctx.json({ role: isMember.role });\n\tconst userIdToGetRole = ctx.query?.userId;\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: userIdToGetRole,\n\t\torganizationId\n\t});\n\tif (!member) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\treturn ctx.json({ role: member?.role });\n});\n//#endregion\nexport { addMember, getActiveMember, getActiveMemberRole, leaveOrganization, listMembers, removeMember, updateMemberRole };\n", "import { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { getSessionFromCtx, requestOnlySessionMiddleware } from \"../../../api/routes/session.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { getOrgAdapter } from \"../adapter.mjs\";\nimport { orgMiddleware, orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-org.ts\nconst baseOrganizationSchema = z.object({\n\tname: z.string().min(1).meta({ description: \"The name of the organization\" }),\n\tslug: z.string().min(1).meta({ description: \"The slug of the organization\" }),\n\tuserId: z.coerce.string().meta({ description: \"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server. server-only. Eg: \\\"user-id\\\"\" }).optional(),\n\tlogo: z.string().meta({ description: \"The logo of the organization\" }).optional(),\n\tmetadata: z.record(z.string(), z.any()).meta({ description: \"The metadata of the organization\" }).optional(),\n\tkeepCurrentActiveOrganization: z.boolean().meta({ description: \"Whether to keep the current active organization active after creating a new one. Eg: true\" }).optional()\n});\nconst createOrganization = (options) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: options?.schema?.organization?.additionalFields || {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/create\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\t...baseOrganizationSchema.shape,\n\t\t\t...additionalFieldsSchema.shape\n\t\t}),\n\t\tuse: [orgMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Create an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tdescription: \"The organization that was created\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/Organization\"\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = await getSessionFromCtx(ctx);\n\t\tif (!session && (ctx.request || ctx.headers)) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\tlet user = session?.user || null;\n\t\tif (!user) {\n\t\t\tif (!ctx.body.userId) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\t\tuser = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n\t\t}\n\t\tif (!user) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\tconst options = ctx.context.orgOptions;\n\t\tconst canCreateOrg = typeof options?.allowUserToCreateOrganization === \"function\" ? await options.allowUserToCreateOrganization(user) : options?.allowUserToCreateOrganization === void 0 ? true : options.allowUserToCreateOrganization;\n\t\tconst isSystemAction = !session && ctx.body.userId;\n\t\tif (!canCreateOrg && !isSystemAction) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst userOrganizations = await adapter.listOrganizations(user.id);\n\t\tif (typeof options.organizationLimit === \"number\" ? userOrganizations.length >= options.organizationLimit : typeof options.organizationLimit === \"function\" ? await options.organizationLimit(user) : false) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS);\n\t\tif (await adapter.findOrganizationBySlug(ctx.body.slug)) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_ALREADY_EXISTS);\n\t\tlet { keepCurrentActiveOrganization: _, userId: __, ...orgData } = ctx.body;\n\t\tif (options?.organizationHooks?.beforeCreateOrganization) {\n\t\t\tconst response = await options?.organizationHooks.beforeCreateOrganization({\n\t\t\t\torganization: orgData,\n\t\t\t\tuser\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) orgData = {\n\t\t\t\t...ctx.body,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst organization = await adapter.createOrganization({ organization: {\n\t\t\t...orgData,\n\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t} });\n\t\tlet member;\n\t\tlet teamMember = null;\n\t\tlet data = {\n\t\t\tuserId: user.id,\n\t\t\torganizationId: organization.id,\n\t\t\trole: ctx.context.orgOptions.creatorRole || \"owner\"\n\t\t};\n\t\tif (options?.organizationHooks?.beforeAddMember) {\n\t\t\tconst response = await options?.organizationHooks.beforeAddMember({\n\t\t\t\tmember: {\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\torganizationId: organization.id,\n\t\t\t\t\trole: ctx.context.orgOptions.creatorRole || \"owner\"\n\t\t\t\t},\n\t\t\t\tuser,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) data = {\n\t\t\t\t...data,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tmember = await adapter.createMember(data);\n\t\tif (options?.organizationHooks?.afterAddMember) await options?.organizationHooks.afterAddMember({\n\t\t\tmember,\n\t\t\tuser,\n\t\t\torganization\n\t\t});\n\t\tif (options?.teams?.enabled && options.teams.defaultTeam?.enabled !== false) {\n\t\t\tlet teamData = {\n\t\t\t\torganizationId: organization.id,\n\t\t\t\tname: `${organization.name}`,\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t};\n\t\t\tif (options?.organizationHooks?.beforeCreateTeam) {\n\t\t\t\tconst response = await options?.organizationHooks.beforeCreateTeam({\n\t\t\t\t\tteam: {\n\t\t\t\t\t\torganizationId: organization.id,\n\t\t\t\t\t\tname: `${organization.name}`\n\t\t\t\t\t},\n\t\t\t\t\tuser,\n\t\t\t\t\torganization\n\t\t\t\t});\n\t\t\t\tif (response && typeof response === \"object\" && \"data\" in response) teamData = {\n\t\t\t\t\t...teamData,\n\t\t\t\t\t...response.data\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst defaultTeam = await options.teams.defaultTeam?.customCreateDefaultTeam?.(organization, ctx) || await adapter.createTeam(teamData);\n\t\t\tteamMember = await adapter.findOrCreateTeamMember({\n\t\t\t\tteamId: defaultTeam.id,\n\t\t\t\tuserId: user.id\n\t\t\t});\n\t\t\tif (options?.organizationHooks?.afterCreateTeam) await options?.organizationHooks.afterCreateTeam({\n\t\t\t\tteam: defaultTeam,\n\t\t\t\tuser,\n\t\t\t\torganization\n\t\t\t});\n\t\t}\n\t\tif (options?.organizationHooks?.afterCreateOrganization) await options?.organizationHooks.afterCreateOrganization({\n\t\t\torganization,\n\t\t\tuser,\n\t\t\tmember\n\t\t});\n\t\tif (ctx.context.session && !ctx.body.keepCurrentActiveOrganization) await adapter.setActiveOrganization(ctx.context.session.session.token, organization.id, ctx);\n\t\tif (teamMember && ctx.context.session && !ctx.body.keepCurrentActiveOrganization) await adapter.setActiveTeam(ctx.context.session.session.token, teamMember.teamId, ctx);\n\t\treturn ctx.json({\n\t\t\t...organization,\n\t\t\tmetadata: organization.metadata && typeof organization.metadata === \"string\" ? JSON.parse(organization.metadata) : organization.metadata,\n\t\t\tmembers: [member]\n\t\t});\n\t});\n};\nconst checkOrganizationSlugBodySchema = z.object({ slug: z.string().meta({ description: \"The organization slug to check. Eg: \\\"my-org\\\"\" }) });\nconst checkOrganizationSlug = (options) => createAuthEndpoint(\"/organization/check-slug\", {\n\tmethod: \"POST\",\n\tbody: checkOrganizationSlugBodySchema,\n\tuse: [requestOnlySessionMiddleware, orgMiddleware]\n}, async (ctx) => {\n\tif (!await getOrgAdapter(ctx.context, options).findOrganizationBySlug(ctx.body.slug)) return ctx.json({ status: true });\n\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_SLUG_ALREADY_TAKEN);\n});\nconst baseUpdateOrganizationSchema = z.object({\n\tname: z.string().min(1).meta({ description: \"The name of the organization\" }).optional(),\n\tslug: z.string().min(1).meta({ description: \"The slug of the organization\" }).optional(),\n\tlogo: z.string().meta({ description: \"The logo of the organization\" }).optional(),\n\tmetadata: z.record(z.string(), z.any()).meta({ description: \"The metadata of the organization\" }).optional()\n});\nconst updateOrganization = (options) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: options?.schema?.organization?.additionalFields || {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/update\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\tdata: z.object({\n\t\t\t\t...additionalFieldsSchema.shape,\n\t\t\t\t...baseUpdateOrganizationSchema.shape\n\t\t\t}).partial(),\n\t\t\torganizationId: z.string().meta({ description: \"The organization ID. Eg: \\\"org-id\\\"\" }).optional()\n\t\t}),\n\t\trequireHeaders: true,\n\t\tuse: [orgMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Update an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tdescription: \"The updated organization\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/Organization\"\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = await ctx.context.getSession(ctx);\n\t\tif (!session) throw APIError.fromStatus(\"UNAUTHORIZED\", { message: \"User not found\" });\n\t\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t\tif (!await hasPermission({\n\t\t\tpermissions: { organization: [\"update\"] },\n\t\t\trole: member.role,\n\t\t\toptions: ctx.context.orgOptions,\n\t\t\torganizationId\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION);\n\t\tif (typeof ctx.body.data.slug === \"string\") {\n\t\t\tconst existingOrganization = await adapter.findOrganizationBySlug(ctx.body.data.slug);\n\t\t\tif (existingOrganization && existingOrganization.id !== organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_SLUG_ALREADY_TAKEN);\n\t\t}\n\t\tif (options?.organizationHooks?.beforeUpdateOrganization) {\n\t\t\tconst response = await options.organizationHooks.beforeUpdateOrganization({\n\t\t\t\torganization: ctx.body.data,\n\t\t\t\tuser: session.user,\n\t\t\t\tmember\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) ctx.body.data = {\n\t\t\t\t...ctx.body.data,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst updatedOrg = await adapter.updateOrganization(organizationId, ctx.body.data);\n\t\tif (options?.organizationHooks?.afterUpdateOrganization) await options.organizationHooks.afterUpdateOrganization({\n\t\t\torganization: updatedOrg,\n\t\t\tuser: session.user,\n\t\t\tmember\n\t\t});\n\t\treturn ctx.json(updatedOrg);\n\t});\n};\nconst deleteOrganizationBodySchema = z.object({ organizationId: z.string().meta({ description: \"The organization id to delete\" }) });\nconst deleteOrganization = (options) => {\n\treturn createAuthEndpoint(\"/organization/delete\", {\n\t\tmethod: \"POST\",\n\t\tbody: deleteOrganizationBodySchema,\n\t\trequireHeaders: true,\n\t\tuse: [orgMiddleware],\n\t\tmetadata: { openapi: {\n\t\t\tdescription: \"Delete an organization\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The organization id that was deleted\"\n\t\t\t\t} } }\n\t\t\t} }\n\t\t} }\n\t}, async (ctx) => {\n\t\tif (ctx.context.orgOptions.disableOrganizationDeletion) throw APIError.from(\"NOT_FOUND\", {\n\t\t\tmessage: \"Organization deletion is disabled\",\n\t\t\tcode: \"ORGANIZATION_DELETION_DISABLED\"\n\t\t});\n\t\tconst session = await ctx.context.getSession(ctx);\n\t\tif (!session) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\tconst organizationId = ctx.body.organizationId;\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t\tif (!await hasPermission({\n\t\t\trole: member.role,\n\t\t\tpermissions: { organization: [\"delete\"] },\n\t\t\torganizationId,\n\t\t\toptions: ctx.context.orgOptions\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION);\n\t\tif (organizationId === session.session.activeOrganizationId)\n /**\n\t\t* If the organization is deleted, we set the active organization to null\n\t\t*/\n\t\tawait adapter.setActiveOrganization(session.session.token, null, ctx);\n\t\tconst org = await adapter.findOrganizationById(organizationId);\n\t\tif (!org) throw APIError.fromStatus(\"BAD_REQUEST\");\n\t\tif (options?.organizationHooks?.beforeDeleteOrganization) await options.organizationHooks.beforeDeleteOrganization({\n\t\t\torganization: org,\n\t\t\tuser: session.user\n\t\t});\n\t\tawait adapter.deleteOrganization(organizationId);\n\t\tif (options?.organizationHooks?.afterDeleteOrganization) await options.organizationHooks.afterDeleteOrganization({\n\t\t\torganization: org,\n\t\t\tuser: session.user\n\t\t});\n\t\treturn ctx.json(org);\n\t});\n};\nconst getFullOrganizationQuerySchema = z.optional(z.object({\n\torganizationId: z.string().meta({ description: \"The organization id to get\" }).optional(),\n\torganizationSlug: z.string().meta({ description: \"The organization slug to get\" }).optional(),\n\tmembersLimit: z.number().or(z.string().transform((val) => parseInt(val))).meta({ description: \"The limit of members to get. By default, it uses the membershipLimit option.\" }).optional()\n}));\nconst getFullOrganization = (options) => createAuthEndpoint(\"/organization/get-full-organization\", {\n\tmethod: \"GET\",\n\tquery: getFullOrganizationQuerySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tmetadata: { openapi: {\n\t\toperationId: \"getOrganization\",\n\t\tdescription: \"Get the full organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tdescription: \"The organization\",\n\t\t\t\t$ref: \"#/components/schemas/Organization\"\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst organizationId = ctx.query?.organizationSlug || ctx.query?.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) return ctx.json(null, { status: 200 });\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst organization = await adapter.findFullOrganization({\n\t\torganizationId,\n\t\tisSlug: !!ctx.query?.organizationSlug,\n\t\tincludeTeams: ctx.context.orgOptions.teams?.enabled,\n\t\tmembersLimit: ctx.query?.membersLimit\n\t});\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (!await adapter.checkMembership({\n\t\tuserId: session.user.id,\n\t\torganizationId: organization.id\n\t})) {\n\t\tawait adapter.setActiveOrganization(session.session.token, null, ctx);\n\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t}\n\treturn ctx.json(organization);\n});\nconst setActiveOrganizationBodySchema = z.object({\n\torganizationId: z.string().meta({ description: \"The organization id to set as active. It can be null to unset the active organization. Eg: \\\"org-id\\\"\" }).nullable().optional(),\n\torganizationSlug: z.string().meta({ description: \"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided. Eg: \\\"org-slug\\\"\" }).optional()\n});\nconst setActiveOrganization = (options) => {\n\treturn createAuthEndpoint(\"/organization/set-active\", {\n\t\tmethod: \"POST\",\n\t\tbody: setActiveOrganizationBodySchema,\n\t\tuse: [orgSessionMiddleware, orgMiddleware],\n\t\trequireHeaders: true,\n\t\tmetadata: { openapi: {\n\t\t\toperationId: \"setActiveOrganization\",\n\t\t\tdescription: \"Set the active organization\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"The organization\",\n\t\t\t\t\t$ref: \"#/components/schemas/Organization\"\n\t\t\t\t} } }\n\t\t\t} }\n\t\t} }\n\t}, async (ctx) => {\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst session = ctx.context.session;\n\t\tlet organizationId = ctx.body.organizationId;\n\t\tconst organizationSlug = ctx.body.organizationSlug;\n\t\tif (organizationId === null) {\n\t\t\tif (!session.session.activeOrganizationId) return ctx.json(null);\n\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\tsession: await adapter.setActiveOrganization(session.session.token, null, ctx),\n\t\t\t\tuser: session.user\n\t\t\t});\n\t\t\treturn ctx.json(null);\n\t\t}\n\t\tif (!organizationId && !organizationSlug) {\n\t\t\tconst sessionOrgId = session.session.activeOrganizationId;\n\t\t\tif (!sessionOrgId) return ctx.json(null);\n\t\t\torganizationId = sessionOrgId;\n\t\t}\n\t\tif (organizationSlug && !organizationId) {\n\t\t\tconst organization = await adapter.findOrganizationBySlug(organizationSlug);\n\t\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\t\torganizationId = organization.id;\n\t\t}\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tif (!await adapter.checkMembership({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t})) {\n\t\t\tawait adapter.setActiveOrganization(session.session.token, null, ctx);\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t\t}\n\t\tconst organization = await adapter.findOrganizationById(organizationId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession: await adapter.setActiveOrganization(session.session.token, organization.id, ctx),\n\t\t\tuser: session.user\n\t\t});\n\t\treturn ctx.json(organization);\n\t});\n};\nconst listOrganizations = (options) => createAuthEndpoint(\"/organization/list\", {\n\tmethod: \"GET\",\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"List all organizations\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: { $ref: \"#/components/schemas/Organization\" }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst organizations = await getOrgAdapter(ctx.context, options).listOrganizations(ctx.context.session.user.id);\n\treturn ctx.json(organizations);\n});\n//#endregion\nexport { checkOrganizationSlug, createOrganization, deleteOrganization, getFullOrganization, listOrganizations, setActiveOrganization, updateOrganization };\n", "import { generateId } from \"@better-auth/core/utils/id\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/schema.ts\nconst roleSchema = z.string();\nconst invitationStatus = z.enum([\n\t\"pending\",\n\t\"accepted\",\n\t\"rejected\",\n\t\"canceled\"\n]).default(\"pending\");\nz.object({\n\tid: z.string().default(generateId),\n\tname: z.string(),\n\tslug: z.string(),\n\tlogo: z.string().nullish().optional(),\n\tmetadata: z.record(z.string(), z.unknown()).or(z.string().transform((v) => JSON.parse(v))).optional(),\n\tcreatedAt: z.date()\n});\nz.object({\n\tid: z.string().default(generateId),\n\torganizationId: z.string(),\n\tuserId: z.coerce.string(),\n\trole: roleSchema,\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nz.object({\n\tid: z.string().default(generateId),\n\torganizationId: z.string(),\n\temail: z.string(),\n\trole: roleSchema,\n\tstatus: invitationStatus,\n\tteamId: z.string().nullish(),\n\tinviterId: z.string(),\n\texpiresAt: z.date(),\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nconst teamSchema = z.object({\n\tid: z.string().default(generateId),\n\tname: z.string().min(1),\n\torganizationId: z.string(),\n\tcreatedAt: z.date(),\n\tupdatedAt: z.date().optional()\n});\nz.object({\n\tid: z.string().default(generateId),\n\tteamId: z.string(),\n\tuserId: z.string(),\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nz.object({\n\tid: z.string().default(generateId),\n\torganizationId: z.string(),\n\trole: z.string(),\n\tpermission: z.record(z.string(), z.array(z.string())),\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date()),\n\tupdatedAt: z.date().optional()\n});\nconst defaultRoles = [\n\t\"admin\",\n\t\"member\",\n\t\"owner\"\n];\nz.union([z.enum(defaultRoles), z.array(z.enum(defaultRoles))]);\n//#endregion\nexport { teamSchema };\n", "import { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { getSessionFromCtx } from \"../../../api/routes/session.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { getOrgAdapter } from \"../adapter.mjs\";\nimport { orgMiddleware, orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { teamSchema } from \"../schema.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-team.ts\nconst teamBaseSchema = z.object({\n\tname: z.string().meta({ description: \"The name of the team. Eg: \\\"my-team\\\"\" }),\n\torganizationId: z.string().meta({ description: \"The organization ID which the team will be created in. Defaults to the active organization. Eg: \\\"organization-id\\\"\" }).optional()\n});\nconst createTeam = (options) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: options?.schema?.team?.additionalFields ?? {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/create-team\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\t...teamBaseSchema.shape,\n\t\t\t...additionalFieldsSchema.shape\n\t\t}),\n\t\tuse: [orgMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Create a new team within an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Team created successfully\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"Unique identifier of the created team\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"Name of the team\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\torganizationId: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"ID of the organization the team belongs to\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"Timestamp when the team was created\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"Timestamp when the team was last updated\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t]\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = await getSessionFromCtx(ctx);\n\t\tconst organizationId = ctx.body.organizationId || session?.session.activeOrganizationId;\n\t\tif (!session && (ctx.request || ctx.headers)) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tif (session) {\n\t\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\t\tuserId: session.user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tif (!member) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION);\n\t\t\tif (!await hasPermission({\n\t\t\t\trole: member.role,\n\t\t\t\toptions: ctx.context.orgOptions,\n\t\t\t\tpermissions: { team: [\"create\"] },\n\t\t\t\torganizationId\n\t\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION);\n\t\t}\n\t\tconst existingTeams = await adapter.listTeams(organizationId);\n\t\tconst maximum = typeof ctx.context.orgOptions.teams?.maximumTeams === \"function\" ? await ctx.context.orgOptions.teams?.maximumTeams({\n\t\t\torganizationId,\n\t\t\tsession\n\t\t}, ctx) : ctx.context.orgOptions.teams?.maximumTeams;\n\t\tif (maximum ? existingTeams.length >= maximum : false) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS);\n\t\tconst { name, organizationId: _, ...additionalFields } = ctx.body;\n\t\tconst organization = await adapter.findOrganizationById(organizationId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tlet teamData = {\n\t\t\tname,\n\t\t\torganizationId,\n\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t...additionalFields\n\t\t};\n\t\tif (options?.organizationHooks?.beforeCreateTeam) {\n\t\t\tconst response = await options?.organizationHooks.beforeCreateTeam({\n\t\t\t\tteam: {\n\t\t\t\t\tname,\n\t\t\t\t\torganizationId,\n\t\t\t\t\t...additionalFields\n\t\t\t\t},\n\t\t\t\tuser: session?.user,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) teamData = {\n\t\t\t\t...teamData,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst createdTeam = await adapter.createTeam(teamData);\n\t\tif (options?.organizationHooks?.afterCreateTeam) await options?.organizationHooks.afterCreateTeam({\n\t\t\tteam: createdTeam,\n\t\t\tuser: session?.user,\n\t\t\torganization\n\t\t});\n\t\treturn ctx.json(createdTeam);\n\t});\n};\nconst removeTeamBodySchema = z.object({\n\tteamId: z.string().meta({ description: `The team ID of the team to remove. Eg: \"team-id\"` }),\n\torganizationId: z.string().meta({ description: `The organization ID which the team falls under. If not provided, it will default to the user's active organization. Eg: \"organization-id\"` }).optional()\n});\nconst removeTeam = (options) => createAuthEndpoint(\"/organization/remove-team\", {\n\tmethod: \"POST\",\n\tbody: removeTeamBodySchema,\n\tuse: [orgMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Remove a team from an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Team removed successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"Confirmation message indicating successful removal\",\n\t\t\t\t\tenum: [\"Team removed successfully.\"]\n\t\t\t\t} },\n\t\t\t\trequired: [\"message\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tconst organizationId = ctx.body.organizationId || session?.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tif (!session && (ctx.request || ctx.headers)) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (session) {\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member || session.session?.activeTeamId === ctx.body.teamId) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM);\n\t\tif (!await hasPermission({\n\t\t\trole: member.role,\n\t\t\toptions: ctx.context.orgOptions,\n\t\t\tpermissions: { team: [\"delete\"] },\n\t\t\torganizationId\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION);\n\t}\n\tconst team = await adapter.findTeamById({\n\t\tteamId: ctx.body.teamId,\n\t\torganizationId\n\t});\n\tif (!team || team.organizationId !== organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\tif (!ctx.context.orgOptions.teams?.allowRemovingAllTeams) {\n\t\tif ((await adapter.listTeams(organizationId)).length <= 1) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.UNABLE_TO_REMOVE_LAST_TEAM);\n\t}\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (options?.organizationHooks?.beforeDeleteTeam) await options?.organizationHooks.beforeDeleteTeam({\n\t\tteam,\n\t\tuser: session?.user,\n\t\torganization\n\t});\n\tawait adapter.deleteTeam(team.id);\n\tif (options?.organizationHooks?.afterDeleteTeam) await options?.organizationHooks.afterDeleteTeam({\n\t\tteam,\n\t\tuser: session?.user,\n\t\torganization\n\t});\n\treturn ctx.json({ message: \"Team removed successfully.\" });\n});\nconst updateTeam = (options) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: options?.schema?.team?.additionalFields ?? {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/update-team\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\tteamId: z.string().meta({ description: `The ID of the team to be updated. Eg: \"team-id\"` }),\n\t\t\tdata: z.object({\n\t\t\t\t...teamSchema.shape,\n\t\t\t\t...additionalFieldsSchema.shape\n\t\t\t}).partial()\n\t\t}),\n\t\trequireHeaders: true,\n\t\tuse: [orgMiddleware, orgSessionMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Update an existing team in an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Team updated successfully\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"Unique identifier of the updated team\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"Updated name of the team\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\torganizationId: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"ID of the organization the team belongs to\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"Timestamp when the team was created\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"Timestamp when the team was last updated\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t]\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = ctx.context.session;\n\t\tconst organizationId = ctx.body.data.organizationId || session.session.activeOrganizationId;\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM);\n\t\tif (!await hasPermission({\n\t\t\trole: member.role,\n\t\t\toptions: ctx.context.orgOptions,\n\t\t\tpermissions: { team: [\"update\"] },\n\t\t\torganizationId\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM);\n\t\tconst team = await adapter.findTeamById({\n\t\t\tteamId: ctx.body.teamId,\n\t\t\torganizationId\n\t\t});\n\t\tif (!team || team.organizationId !== organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\t\tconst { name, organizationId: __, ...additionalFields } = ctx.body.data;\n\t\tconst organization = await adapter.findOrganizationById(organizationId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tconst updates = {\n\t\t\tname,\n\t\t\t...additionalFields\n\t\t};\n\t\tif (options?.organizationHooks?.beforeUpdateTeam) {\n\t\t\tconst response = await options?.organizationHooks.beforeUpdateTeam({\n\t\t\t\tteam,\n\t\t\t\tupdates,\n\t\t\t\tuser: session.user,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) {\n\t\t\t\tconst modifiedUpdates = response.data;\n\t\t\t\tconst updatedTeam = await adapter.updateTeam(team.id, modifiedUpdates);\n\t\t\t\tif (options?.organizationHooks?.afterUpdateTeam) await options?.organizationHooks.afterUpdateTeam({\n\t\t\t\t\tteam: updatedTeam,\n\t\t\t\t\tuser: session.user,\n\t\t\t\t\torganization\n\t\t\t\t});\n\t\t\t\treturn ctx.json(updatedTeam);\n\t\t\t}\n\t\t}\n\t\tconst updatedTeam = await adapter.updateTeam(team.id, updates);\n\t\tif (options?.organizationHooks?.afterUpdateTeam) await options?.organizationHooks.afterUpdateTeam({\n\t\t\tteam: updatedTeam,\n\t\t\tuser: session.user,\n\t\t\torganization\n\t\t});\n\t\treturn ctx.json(updatedTeam);\n\t});\n};\nconst listOrganizationTeamsQuerySchema = z.optional(z.object({ organizationId: z.string().meta({ description: `The organization ID which the teams are under to list. Defaults to the users active organization. Eg: \"organization-id\"` }).optional() }));\nconst listOrganizationTeams = (options) => createAuthEndpoint(\"/organization/list-teams\", {\n\tmethod: \"GET\",\n\tquery: listOrganizationTeamsQuerySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"List all teams in an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Teams retrieved successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Unique identifier of the team\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Name of the team\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\torganizationId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"ID of the organization the team belongs to\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\tdescription: \"Timestamp when the team was created\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\tdescription: \"Timestamp when the team was last updated\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\tdescription: \"Array of team objects within the organization\"\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst organizationId = ctx.query?.organizationId || session?.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId: organizationId || \"\"\n\t})) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION);\n\tconst teams = await adapter.listTeams(organizationId);\n\treturn ctx.json(teams);\n});\nconst setActiveTeamBodySchema = z.object({ teamId: z.string().meta({ description: \"The team id to set as active. It can be null to unset the active team\" }).nullable().optional() });\nconst setActiveTeam = (options) => createAuthEndpoint(\"/organization/set-active-team\", {\n\tmethod: \"POST\",\n\tbody: setActiveTeamBodySchema,\n\trequireHeaders: true,\n\tuse: [orgSessionMiddleware, orgMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Set the active team\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tdescription: \"The team\",\n\t\t\t\t$ref: \"#/components/schemas/Team\"\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst session = ctx.context.session;\n\tif (ctx.body.teamId === null) {\n\t\tif (!session.session.activeTeamId) return ctx.json(null);\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession: await adapter.setActiveTeam(session.session.token, null, ctx),\n\t\t\tuser: session.user\n\t\t});\n\t\treturn ctx.json(null);\n\t}\n\tlet teamId;\n\tif (!ctx.body.teamId) {\n\t\tconst sessionTeamId = session.session.activeTeamId;\n\t\tif (!sessionTeamId) return ctx.json(null);\n\t\telse teamId = sessionTeamId;\n\t} else teamId = ctx.body.teamId;\n\tconst team = await adapter.findTeamById({ teamId });\n\tif (!team) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\tif (!await adapter.findTeamMember({\n\t\tteamId,\n\t\tuserId: session.user.id\n\t})) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);\n\tawait setSessionCookie(ctx, {\n\t\tsession: await adapter.setActiveTeam(session.session.token, team.id, ctx),\n\t\tuser: session.user\n\t});\n\treturn ctx.json(team);\n});\nconst listUserTeams = (options) => createAuthEndpoint(\"/organization/list-user-teams\", {\n\tmethod: \"GET\",\n\tmetadata: { openapi: {\n\t\tdescription: \"List all teams that the current user is a part of.\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Teams retrieved successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"The team\",\n\t\t\t\t\t$ref: \"#/components/schemas/Team\"\n\t\t\t\t},\n\t\t\t\tdescription: \"Array of team objects within the organization\"\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst teams = await getOrgAdapter(ctx.context, ctx.context.orgOptions).listTeamsByUser({ userId: session.user.id });\n\treturn ctx.json(teams);\n});\nconst listTeamMembersQuerySchema = z.optional(z.object({ teamId: z.string().optional().meta({ description: \"The team whose members we should return. If this is not provided the members of the current active team get returned.\" }) }));\nconst listTeamMembers = (options) => createAuthEndpoint(\"/organization/list-team-members\", {\n\tmethod: \"GET\",\n\tquery: listTeamMembersQuerySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"List the members of the given team.\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Teams retrieved successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"The team member\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Unique identifier of the team member\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tuserId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The user ID of the team member\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tteamId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The team ID of the team the team member is in\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\tdescription: \"Timestamp when the team member was created\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\"teamId\",\n\t\t\t\t\t\t\"createdAt\"\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\tdescription: \"Array of team member objects within the team\"\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst teamId = ctx.query?.teamId || session?.session.activeTeamId;\n\tif (!teamId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM);\n\tif (!await adapter.findTeamMember({\n\t\tuserId: session.user.id,\n\t\tteamId\n\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);\n\tconst members = await adapter.listTeamMembers({ teamId });\n\treturn ctx.json(members);\n});\nconst addTeamMemberBodySchema = z.object({\n\tteamId: z.string().meta({ description: \"The team the user should be a member of.\" }),\n\tuserId: z.coerce.string().meta({ description: \"The user Id which represents the user to be added as a member.\" }),\n\torganizationId: z.string().meta({ description: \"The organization ID which the team falls under. If not provided, it will default to the user's active organization.\" }).optional()\n});\nconst addTeamMember = (options) => createAuthEndpoint(\"/organization/add-team-member\", {\n\tmethod: \"POST\",\n\tbody: addTeamMemberBodySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"The newly created member\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Team member created successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tdescription: \"The team member\",\n\t\t\t\tproperties: {\n\t\t\t\t\tid: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"Unique identifier of the team member\"\n\t\t\t\t\t},\n\t\t\t\t\tuserId: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The user ID of the team member\"\n\t\t\t\t\t},\n\t\t\t\t\tteamId: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The team ID of the team the team member is in\"\n\t\t\t\t\t},\n\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\tdescription: \"Timestamp when the team member was created\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"userId\",\n\t\t\t\t\t\"teamId\",\n\t\t\t\t\t\"createdAt\"\n\t\t\t\t]\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst currentMember = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!currentMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\tif (!await hasPermission({\n\t\trole: currentMember.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { member: [\"update\"] },\n\t\torganizationId\n\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: ctx.body.userId,\n\t\torganizationId\n\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\tconst team = await adapter.findTeamById({\n\t\tteamId: ctx.body.teamId,\n\t\torganizationId\n\t});\n\tif (!team) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst userBeingAdded = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n\tif (!userBeingAdded) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User not found\" });\n\tif (options?.organizationHooks?.beforeAddTeamMember) {\n\t\tconst response = await options?.organizationHooks.beforeAddTeamMember({\n\t\t\tteamMember: {\n\t\t\t\tteamId: ctx.body.teamId,\n\t\t\t\tuserId: ctx.body.userId\n\t\t\t},\n\t\t\tteam,\n\t\t\tuser: userBeingAdded,\n\t\t\torganization\n\t\t});\n\t\tif (response && typeof response === \"object\" && \"data\" in response) {}\n\t}\n\tconst teamMember = await adapter.findOrCreateTeamMember({\n\t\tteamId: ctx.body.teamId,\n\t\tuserId: ctx.body.userId\n\t});\n\tif (options?.organizationHooks?.afterAddTeamMember) await options?.organizationHooks.afterAddTeamMember({\n\t\tteamMember,\n\t\tteam,\n\t\tuser: userBeingAdded,\n\t\torganization\n\t});\n\treturn ctx.json(teamMember);\n});\nconst removeTeamMemberBodySchema = z.object({\n\tteamId: z.string().meta({ description: \"The team the user should be removed from.\" }),\n\tuserId: z.coerce.string().meta({ description: \"The user which should be removed from the team.\" }),\n\torganizationId: z.string().meta({ description: \"The organization ID which the team falls under. If not provided, it will default to the user's active organization.\" }).optional()\n});\nconst removeTeamMember = (options) => createAuthEndpoint(\"/organization/remove-team-member\", {\n\tmethod: \"POST\",\n\tbody: removeTeamMemberBodySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"Remove a member from a team\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Team member removed successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"Confirmation message indicating successful removal\",\n\t\t\t\t\tenum: [\"Team member removed successfully.\"]\n\t\t\t\t} },\n\t\t\t\trequired: [\"message\"]\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst currentMember = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!currentMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\tif (!await hasPermission({\n\t\trole: currentMember.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { member: [\"delete\"] },\n\t\torganizationId\n\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: ctx.body.userId,\n\t\torganizationId\n\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\tconst team = await adapter.findTeamById({\n\t\tteamId: ctx.body.teamId,\n\t\torganizationId\n\t});\n\tif (!team) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst userBeingRemoved = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n\tif (!userBeingRemoved) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User not found\" });\n\tconst teamMember = await adapter.findTeamMember({\n\t\tteamId: ctx.body.teamId,\n\t\tuserId: ctx.body.userId\n\t});\n\tif (!teamMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);\n\tif (options?.organizationHooks?.beforeRemoveTeamMember) await options?.organizationHooks.beforeRemoveTeamMember({\n\t\tteamMember,\n\t\tteam,\n\t\tuser: userBeingRemoved,\n\t\torganization\n\t});\n\tawait adapter.removeTeamMember({\n\t\tteamId: ctx.body.teamId,\n\t\tuserId: ctx.body.userId\n\t});\n\tif (options?.organizationHooks?.afterRemoveTeamMember) await options?.organizationHooks.afterRemoveTeamMember({\n\t\tteamMember,\n\t\tteam,\n\t\tuser: userBeingRemoved,\n\t\torganization\n\t});\n\treturn ctx.json({ message: \"Team member removed successfully.\" });\n});\n//#endregion\nexport { addTeamMember, createTeam, listOrganizationTeams, listTeamMembers, listUserTeams, removeTeam, removeTeamMember, setActiveTeam, updateTeam };\n", "import { getSessionFromCtx } from \"../../api/routes/session.mjs\";\nimport { PACKAGE_VERSION } from \"../../version.mjs\";\nimport { defaultRoles } from \"./access/statement.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"./error-codes.mjs\";\nimport { getOrgAdapter } from \"./adapter.mjs\";\nimport { shimContext } from \"../../utils/shim.mjs\";\nimport { orgSessionMiddleware } from \"./call.mjs\";\nimport { hasPermission } from \"./has-permission.mjs\";\nimport { createOrgRole, deleteOrgRole, getOrgRole, listOrgRoles, updateOrgRole } from \"./routes/crud-access-control.mjs\";\nimport { acceptInvitation, cancelInvitation, createInvitation, getInvitation, listInvitations, listUserInvitations, rejectInvitation } from \"./routes/crud-invites.mjs\";\nimport { addMember, getActiveMember, getActiveMemberRole, leaveOrganization, listMembers, removeMember, updateMemberRole } from \"./routes/crud-members.mjs\";\nimport { checkOrganizationSlug, createOrganization, deleteOrganization, getFullOrganization, listOrganizations, setActiveOrganization, updateOrganization } from \"./routes/crud-org.mjs\";\nimport { addTeamMember, createTeam, listOrganizationTeams, listTeamMembers, listUserTeams, removeTeam, removeTeamMember, setActiveTeam, updateTeam } from \"./routes/crud-team.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/organization.ts\nfunction parseRoles(roles) {\n\treturn Array.isArray(roles) ? roles.join(\",\") : roles;\n}\nconst createHasPermissionBodySchema = z.object({ organizationId: z.string().optional() }).and(z.union([z.object({\n\tpermission: z.record(z.string(), z.array(z.string())),\n\tpermissions: z.undefined()\n}), z.object({\n\tpermission: z.undefined(),\n\tpermissions: z.record(z.string(), z.array(z.string()))\n})]));\nconst createHasPermission = (options) => {\n\treturn createAuthEndpoint(\"/organization/has-permission\", {\n\t\tmethod: \"POST\",\n\t\trequireHeaders: true,\n\t\tbody: createHasPermissionBodySchema,\n\t\tuse: [orgSessionMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Check if the user has permission\",\n\t\t\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tpermission: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tdescription: \"The permission to check\",\n\t\t\t\t\t\t\tdeprecated: true\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpermissions: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tdescription: \"The permission to check\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"permissions\"]\n\t\t\t\t} } } },\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\terror: { type: \"string\" },\n\t\t\t\t\t\t\tsuccess: { type: \"boolean\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"success\"]\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst activeOrganizationId = ctx.body.organizationId || ctx.context.session.session.activeOrganizationId;\n\t\tif (!activeOrganizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\tconst member = await getOrgAdapter(ctx.context, options).findMemberByOrgId({\n\t\t\tuserId: ctx.context.session.user.id,\n\t\t\torganizationId: activeOrganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"UNAUTHORIZED\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t\tconst result = await hasPermission({\n\t\t\trole: member.role,\n\t\t\toptions,\n\t\t\tpermissions: ctx.body.permissions,\n\t\t\torganizationId: activeOrganizationId\n\t\t}, ctx);\n\t\treturn ctx.json({\n\t\t\terror: null,\n\t\t\tsuccess: result\n\t\t});\n\t});\n};\nfunction organization(options) {\n\tconst opts = options || {};\n\tlet endpoints = {\n\t\tcreateOrganization: createOrganization(opts),\n\t\tupdateOrganization: updateOrganization(opts),\n\t\tdeleteOrganization: deleteOrganization(opts),\n\t\tsetActiveOrganization: setActiveOrganization(opts),\n\t\tgetFullOrganization: getFullOrganization(opts),\n\t\tlistOrganizations: listOrganizations(opts),\n\t\tcreateInvitation: createInvitation(opts),\n\t\tcancelInvitation: cancelInvitation(opts),\n\t\tacceptInvitation: acceptInvitation(opts),\n\t\tgetInvitation: getInvitation(opts),\n\t\trejectInvitation: rejectInvitation(opts),\n\t\tlistInvitations: listInvitations(opts),\n\t\tgetActiveMember: getActiveMember(opts),\n\t\tcheckOrganizationSlug: checkOrganizationSlug(opts),\n\t\taddMember: addMember(opts),\n\t\tremoveMember: removeMember(opts),\n\t\tupdateMemberRole: updateMemberRole(opts),\n\t\tleaveOrganization: leaveOrganization(opts),\n\t\tlistUserInvitations: listUserInvitations(opts),\n\t\tlistMembers: listMembers(opts),\n\t\tgetActiveMemberRole: getActiveMemberRole(opts)\n\t};\n\tconst teamSupport = opts.teams?.enabled;\n\tconst teamEndpoints = {\n\t\tcreateTeam: createTeam(opts),\n\t\tlistOrganizationTeams: listOrganizationTeams(opts),\n\t\tremoveTeam: removeTeam(opts),\n\t\tupdateTeam: updateTeam(opts),\n\t\tsetActiveTeam: setActiveTeam(opts),\n\t\tlistUserTeams: listUserTeams(opts),\n\t\tlistTeamMembers: listTeamMembers(opts),\n\t\taddTeamMember: addTeamMember(opts),\n\t\tremoveTeamMember: removeTeamMember(opts)\n\t};\n\tif (teamSupport) endpoints = {\n\t\t...endpoints,\n\t\t...teamEndpoints\n\t};\n\tconst dynamicAccessControlEndpoints = {\n\t\tcreateOrgRole: createOrgRole(opts),\n\t\tdeleteOrgRole: deleteOrgRole(opts),\n\t\tlistOrgRoles: listOrgRoles(opts),\n\t\tgetOrgRole: getOrgRole(opts),\n\t\tupdateOrgRole: updateOrgRole(opts)\n\t};\n\tif (opts.dynamicAccessControl?.enabled) endpoints = {\n\t\t...endpoints,\n\t\t...dynamicAccessControlEndpoints\n\t};\n\tconst roles = {\n\t\t...defaultRoles,\n\t\t...opts.roles\n\t};\n\tconst teamSchema = teamSupport ? {\n\t\tteam: {\n\t\t\tmodelName: opts.schema?.team?.modelName,\n\t\t\tfields: {\n\t\t\t\tname: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.team?.fields?.name\n\t\t\t\t},\n\t\t\t\torganizationId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.team?.fields?.organizationId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.team?.fields?.createdAt\n\t\t\t\t},\n\t\t\t\tupdatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.team?.fields?.updatedAt,\n\t\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date()\n\t\t\t\t},\n\t\t\t\t...opts.schema?.team?.additionalFields || {}\n\t\t\t}\n\t\t},\n\t\tteamMember: {\n\t\t\tmodelName: opts.schema?.teamMember?.modelName,\n\t\t\tfields: {\n\t\t\t\tteamId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"team\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.teamMember?.fields?.teamId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tuserId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.teamMember?.fields?.userId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.teamMember?.fields?.createdAt\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} : {};\n\tconst organizationRoleSchema = opts.dynamicAccessControl?.enabled ? { organizationRole: {\n\t\tfields: {\n\t\t\torganizationId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\tfield: \"id\"\n\t\t\t\t},\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.organizationId,\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\trole: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.role,\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tpermission: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.permission\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.createdAt\n\t\t\t},\n\t\t\tupdatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: false,\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.updatedAt,\n\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date()\n\t\t\t},\n\t\t\t...opts.schema?.organizationRole?.additionalFields || {}\n\t\t},\n\t\tmodelName: opts.schema?.organizationRole?.modelName\n\t} } : {};\n\tconst schema = {\n\t\torganization: {\n\t\t\tmodelName: opts.schema?.organization?.modelName,\n\t\t\tfields: {\n\t\t\t\tname: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.name\n\t\t\t\t},\n\t\t\t\tslug: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tunique: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.slug,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tlogo: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.logo\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.createdAt\n\t\t\t\t},\n\t\t\t\tmetadata: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.metadata\n\t\t\t\t},\n\t\t\t\t...opts.schema?.organization?.additionalFields || {}\n\t\t\t}\n\t\t},\n\t\t...organizationRoleSchema,\n\t\t...teamSchema,\n\t\tmember: {\n\t\t\tmodelName: opts.schema?.member?.modelName,\n\t\t\tfields: {\n\t\t\t\torganizationId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.member?.fields?.organizationId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tuserId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.member?.fields?.userId,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\trole: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tdefaultValue: \"member\",\n\t\t\t\t\tfieldName: opts.schema?.member?.fields?.role\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.member?.fields?.createdAt\n\t\t\t\t},\n\t\t\t\t...opts.schema?.member?.additionalFields || {}\n\t\t\t}\n\t\t},\n\t\tinvitation: {\n\t\t\tmodelName: opts.schema?.invitation?.modelName,\n\t\t\tfields: {\n\t\t\t\torganizationId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.organizationId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\temail: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.email,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\trole: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.role\n\t\t\t\t},\n\t\t\t\t...teamSupport ? { teamId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.teamId\n\t\t\t\t} } : {},\n\t\t\t\tstatus: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tdefaultValue: \"pending\",\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.status\n\t\t\t\t},\n\t\t\t\texpiresAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.expiresAt\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.createdAt,\n\t\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date()\n\t\t\t\t},\n\t\t\t\tinviterId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.inviterId,\n\t\t\t\t\trequired: true\n\t\t\t\t},\n\t\t\t\t...opts.schema?.invitation?.additionalFields || {}\n\t\t\t}\n\t\t}\n\t};\n\treturn {\n\t\tid: \"organization\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\t...shimContext(endpoints, {\n\t\t\t\torgOptions: opts,\n\t\t\t\troles,\n\t\t\t\tgetSession: async (context) => {\n\t\t\t\t\treturn await getSessionFromCtx(context);\n\t\t\t\t}\n\t\t\t}),\n\t\t\thasPermission: createHasPermission(opts)\n\t\t},\n\t\tschema: {\n\t\t\t...schema,\n\t\t\tsession: { fields: {\n\t\t\t\tactiveOrganizationId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.session?.fields?.activeOrganizationId\n\t\t\t\t},\n\t\t\t\t...teamSupport ? { activeTeamId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.session?.fields?.activeTeamId\n\t\t\t\t} } : {}\n\t\t\t} }\n\t\t},\n\t\t$Infer: {\n\t\t\tOrganization: {},\n\t\t\tInvitation: {},\n\t\t\tMember: {},\n\t\t\tTeam: teamSupport ? {} : {},\n\t\t\tTeamMember: teamSupport ? {} : {},\n\t\t\tActiveOrganization: {}\n\t\t},\n\t\t$ERROR_CODES: ORGANIZATION_ERROR_CODES,\n\t\toptions: opts\n\t};\n}\n//#endregion\nexport { organization, parseRoles };\n", "import { defineErrorCodes } from \"@better-auth/core/utils/error-codes\";\n//#region src/plugins/two-factor/error-code.ts\nconst TWO_FACTOR_ERROR_CODES = defineErrorCodes({\n\tOTP_NOT_ENABLED: \"OTP not enabled\",\n\tOTP_HAS_EXPIRED: \"OTP has expired\",\n\tTOTP_NOT_ENABLED: \"TOTP not enabled\",\n\tTWO_FACTOR_NOT_ENABLED: \"Two factor isn't enabled\",\n\tBACKUP_CODES_NOT_ENABLED: \"Backup codes aren't enabled\",\n\tINVALID_BACKUP_CODE: \"Invalid backup code\",\n\tINVALID_CODE: \"Invalid code\",\n\tTOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: \"Too many attempts. Please request a new code.\",\n\tINVALID_TWO_FACTOR_COOKIE: \"Invalid two factor cookie\"\n});\n//#endregion\nexport { TWO_FACTOR_ERROR_CODES };\n", "//#region src/plugins/two-factor/constant.ts\nconst TWO_FACTOR_COOKIE_NAME = \"two_factor\";\nconst TRUST_DEVICE_COOKIE_NAME = \"trust_device\";\nconst TRUST_DEVICE_COOKIE_MAX_AGE = 720 * 60 * 60;\n//#endregion\nexport { TRUST_DEVICE_COOKIE_MAX_AGE, TRUST_DEVICE_COOKIE_NAME, TWO_FACTOR_COOKIE_NAME };\n", "import { parseUserOutput } from \"../../db/schema.mjs\";\nimport { generateRandomString } from \"../../crypto/random.mjs\";\nimport { expireCookie, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { getSessionFromCtx } from \"../../api/routes/session.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"./error-code.mjs\";\nimport { TRUST_DEVICE_COOKIE_NAME, TWO_FACTOR_COOKIE_NAME } from \"./constant.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\n//#region src/plugins/two-factor/verify-two-factor.ts\nasync function verifyTwoFactor(ctx) {\n\tconst invalid = (errorKey) => {\n\t\tthrow APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES[errorKey]);\n\t};\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) {\n\t\tconst twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME);\n\t\tconst signedTwoFactorCookie = await ctx.getSignedCookie(twoFactorCookie.name, ctx.context.secret);\n\t\tif (!signedTwoFactorCookie) throw APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE);\n\t\tconst verificationToken = await ctx.context.internalAdapter.findVerificationValue(signedTwoFactorCookie);\n\t\tif (!verificationToken) throw APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE);\n\t\tconst user = await ctx.context.internalAdapter.findUserById(verificationToken.value);\n\t\tif (!user) throw APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE);\n\t\tconst dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);\n\t\treturn {\n\t\t\tvalid: async (ctx) => {\n\t\t\t\tconst session = await ctx.context.internalAdapter.createSession(verificationToken.value, !!dontRememberMe);\n\t\t\t\tif (!session) throw APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\t\t\t\tmessage: \"failed to create session\",\n\t\t\t\t\tcode: \"FAILED_TO_CREATE_SESSION\"\n\t\t\t\t});\n\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(signedTwoFactorCookie);\n\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\tsession,\n\t\t\t\t\tuser\n\t\t\t\t});\n\t\t\t\texpireCookie(ctx, twoFactorCookie);\n\t\t\t\tif (ctx.body.trustDevice) {\n\t\t\t\t\tconst maxAge = ctx.context.getPlugin(\"two-factor\").options?.trustDeviceMaxAge ?? 2592e3;\n\t\t\t\t\tconst trustDeviceCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge });\n\t\t\t\t\t/**\n\t\t\t\t\t* Create a random identifier for the trust device record.\n\t\t\t\t\t* Store it in the verification table with an expiration\n\t\t\t\t\t* so the server can validate and revoke it.\n\t\t\t\t\t*/\n\t\t\t\t\tconst trustIdentifier = `trust-device-${generateRandomString(32)}`;\n\t\t\t\t\tconst token = await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, `${user.id}!${trustIdentifier}`);\n\t\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\t\tvalue: user.id,\n\t\t\t\t\t\tidentifier: trustIdentifier,\n\t\t\t\t\t\texpiresAt: new Date(Date.now() + maxAge * 1e3)\n\t\t\t\t\t});\n\t\t\t\t\tawait ctx.setSignedCookie(trustDeviceCookie.name, `${token}!${trustIdentifier}`, ctx.context.secret, trustDeviceCookie.attributes);\n\t\t\t\t\texpireCookie(ctx, ctx.context.authCookies.dontRememberToken);\n\t\t\t\t}\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttoken: session.token,\n\t\t\t\t\tuser: parseUserOutput(ctx.context.options, user)\n\t\t\t\t});\n\t\t\t},\n\t\t\tinvalid,\n\t\t\tsession: {\n\t\t\t\tsession: null,\n\t\t\t\tuser\n\t\t\t},\n\t\t\tkey: signedTwoFactorCookie\n\t\t};\n\t}\n\treturn {\n\t\tvalid: async (ctx) => {\n\t\t\treturn ctx.json({\n\t\t\t\ttoken: session.session.token,\n\t\t\t\tuser: parseUserOutput(ctx.context.options, session.user)\n\t\t\t});\n\t\t},\n\t\tinvalid,\n\t\tsession,\n\t\tkey: `${session.user.id}!${session.session.id}`\n\t};\n}\n//#endregion\nexport { verifyTwoFactor };\n", "import { parseUserOutput } from \"../../../db/schema.mjs\";\nimport { generateRandomString } from \"../../../crypto/random.mjs\";\nimport { symmetricDecrypt, symmetricEncrypt } from \"../../../crypto/index.mjs\";\nimport { sessionMiddleware } from \"../../../api/routes/session.mjs\";\nimport { shouldRequirePassword } from \"../../../utils/password.mjs\";\nimport { PACKAGE_VERSION } from \"../../../version.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"../error-code.mjs\";\nimport { verifyTwoFactor } from \"../verify-two-factor.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/two-factor/backup-codes/index.ts\nfunction generateBackupCodesFn(options) {\n\treturn Array.from({ length: options?.amount ?? 10 }).fill(null).map(() => generateRandomString(options?.length ?? 10, \"a-z\", \"0-9\", \"A-Z\")).map((code) => `${code.slice(0, 5)}-${code.slice(5)}`);\n}\nasync function generateBackupCodes(secret, options) {\n\tconst backupCodes = options?.customBackupCodesGenerate ? options.customBackupCodesGenerate() : generateBackupCodesFn(options);\n\tif (options?.storeBackupCodes === \"encrypted\") return {\n\t\tbackupCodes,\n\t\tencryptedBackupCodes: await symmetricEncrypt({\n\t\t\tdata: JSON.stringify(backupCodes),\n\t\t\tkey: secret\n\t\t})\n\t};\n\tif (typeof options?.storeBackupCodes === \"object\" && \"encrypt\" in options?.storeBackupCodes) return {\n\t\tbackupCodes,\n\t\tencryptedBackupCodes: await options?.storeBackupCodes.encrypt(JSON.stringify(backupCodes))\n\t};\n\treturn {\n\t\tbackupCodes,\n\t\tencryptedBackupCodes: JSON.stringify(backupCodes)\n\t};\n}\nasync function verifyBackupCode(data, key, options) {\n\tconst codes = await getBackupCodes(data.backupCodes, key, options);\n\tif (!codes) return {\n\t\tstatus: false,\n\t\tupdated: null\n\t};\n\treturn {\n\t\tstatus: codes.includes(data.code),\n\t\tupdated: codes.filter((code) => code !== data.code)\n\t};\n}\nasync function getBackupCodes(backupCodes, key, options) {\n\tif (options?.storeBackupCodes === \"encrypted\") return safeJSONParse(await symmetricDecrypt({\n\t\tkey,\n\t\tdata: backupCodes\n\t}));\n\tif (typeof options?.storeBackupCodes === \"object\" && \"decrypt\" in options?.storeBackupCodes) return safeJSONParse(await options?.storeBackupCodes.decrypt(backupCodes));\n\treturn safeJSONParse(backupCodes);\n}\nconst verifyBackupCodeBodySchema = z.object({\n\tcode: z.string().meta({ description: `A backup code to verify. Eg: \"123456\"` }),\n\tdisableSession: z.boolean().meta({ description: \"If true, the session cookie will not be set.\" }).optional(),\n\ttrustDevice: z.boolean().meta({ description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\" }).optional()\n});\nconst viewBackupCodesBodySchema = z.object({ userId: z.coerce.string().meta({ description: `The user ID to view all backup codes. Eg: \"user-id\"` }) });\nconst backupCode2fa = (opts) => {\n\tconst twoFactorTable = \"twoFactor\";\n\tconst passwordSchema = z.string().meta({ description: \"The users password.\" });\n\tconst generateBackupCodesBodySchema = opts.allowPasswordless ? z.object({ password: passwordSchema.optional() }) : z.object({ password: passwordSchema });\n\treturn {\n\t\tid: \"backup_code\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\tverifyBackupCode: createAuthEndpoint(\"/two-factor/verify-backup-code\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: verifyBackupCodeBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tdescription: \"Verify a backup code for two-factor authentication\",\n\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\tdescription: \"Backup code verified successfully\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Unique identifier of the user\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's email address\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temailVerified: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the email is verified\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's name\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\timage: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's profile image URL\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\ttwoFactorEnabled: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Whether two-factor authentication is enabled for the user\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the user was created\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the user was last updated\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\t\t\t\"twoFactorEnabled\",\n\t\t\t\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdescription: \"The authenticated user object with two-factor details\"\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Session token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tuserId: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"ID of the user associated with the session\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the session was created\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\texpiresAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the session expires\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\t\"token\",\n\t\t\t\t\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\t\t\t\"expiresAt\"\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdescription: \"The current session object, included unless disableSession is true\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\trequired: [\"user\", \"session\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst { session, valid } = await verifyTwoFactor(ctx);\n\t\t\t\tconst user = session.user;\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED);\n\t\t\t\tconst validate = await verifyBackupCode({\n\t\t\t\t\tbackupCodes: twoFactor.backupCodes,\n\t\t\t\t\tcode: ctx.body.code\n\t\t\t\t}, ctx.context.secretConfig, opts);\n\t\t\t\tif (!validate.status) throw APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE);\n\t\t\t\tconst updatedBackupCodes = await symmetricEncrypt({\n\t\t\t\t\tkey: ctx.context.secretConfig,\n\t\t\t\t\tdata: JSON.stringify(validate.updated)\n\t\t\t\t});\n\t\t\t\tif (!await ctx.context.adapter.update({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\tupdate: { backupCodes: updatedBackupCodes },\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\tvalue: twoFactor.id\n\t\t\t\t\t}, {\n\t\t\t\t\t\tfield: \"backupCodes\",\n\t\t\t\t\t\tvalue: twoFactor.backupCodes\n\t\t\t\t\t}]\n\t\t\t\t})) throw APIError.fromStatus(\"CONFLICT\", { message: \"Failed to verify backup code. Please try again.\" });\n\t\t\t\tif (!ctx.body.disableSession) return valid(ctx);\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttoken: session.session?.token,\n\t\t\t\t\tuser: parseUserOutput(ctx.context.options, session.user)\n\t\t\t\t});\n\t\t\t}),\n\t\t\tgenerateBackupCodes: createAuthEndpoint(\"/two-factor/generate-backup-codes\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: generateBackupCodesBodySchema,\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tdescription: \"Generate new backup codes for two-factor authentication\",\n\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\tdescription: \"Backup codes generated successfully\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\tdescription: \"Indicates if the backup codes were generated successfully\",\n\t\t\t\t\t\t\t\t\tenum: [true]\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbackupCodes: {\n\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\t\t\tdescription: \"Array of generated backup codes in plain text\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\trequired: [\"status\", \"backupCodes\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst user = ctx.context.session.user;\n\t\t\t\tif (!user.twoFactorEnabled) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED);\n\t\t\t\tif (await shouldRequirePassword(ctx, user.id, opts.allowPasswordless)) {\n\t\t\t\t\tif (!ctx.body.password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t\tawait ctx.context.password.checkPassword(user.id, ctx);\n\t\t\t\t}\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED);\n\t\t\t\tconst backupCodes = await generateBackupCodes(ctx.context.secretConfig, opts);\n\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\tupdate: { backupCodes: backupCodes.encryptedBackupCodes },\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\tvalue: twoFactor.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\treturn ctx.json({\n\t\t\t\t\tstatus: true,\n\t\t\t\t\tbackupCodes: backupCodes.backupCodes\n\t\t\t\t});\n\t\t\t}),\n\t\t\tviewBackupCodes: createAuthEndpoint({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: viewBackupCodesBodySchema\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: ctx.body.userId\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED);\n\t\t\t\tconst decryptedBackupCodes = await getBackupCodes(twoFactor.backupCodes, ctx.context.secretConfig, opts);\n\t\t\t\tif (!decryptedBackupCodes) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE);\n\t\t\t\treturn ctx.json({\n\t\t\t\t\tstatus: true,\n\t\t\t\t\tbackupCodes: decryptedBackupCodes\n\t\t\t\t});\n\t\t\t})\n\t\t}\n\t};\n};\n//#endregion\nexport { backupCode2fa, generateBackupCodes };\n", "import { base64Url } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\n//#region src/plugins/two-factor/utils.ts\nconst defaultKeyHasher = async (token) => {\n\tconst hash = await createHash(\"SHA-256\").digest(new TextEncoder().encode(token));\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n};\n//#endregion\nexport { defaultKeyHasher };\n", "import { parseUserOutput } from \"../../../db/schema.mjs\";\nimport { constantTimeEqual } from \"../../../crypto/buffer.mjs\";\nimport { generateRandomString } from \"../../../crypto/random.mjs\";\nimport { symmetricDecrypt, symmetricEncrypt } from \"../../../crypto/index.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { PACKAGE_VERSION } from \"../../../version.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"../error-code.mjs\";\nimport { verifyTwoFactor } from \"../verify-two-factor.mjs\";\nimport { defaultKeyHasher } from \"../utils.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/two-factor/otp/index.ts\nconst verifyOTPBodySchema = z.object({\n\tcode: z.string().meta({ description: \"The otp code to verify. Eg: \\\"012345\\\"\" }),\n\ttrustDevice: z.boolean().optional().meta({ description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\" })\n});\nconst send2FaOTPBodySchema = z.object({ trustDevice: z.boolean().optional().meta({ description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\" }) }).optional();\n/**\n* The otp adapter is created from the totp adapter.\n*/\nconst otp2fa = (options) => {\n\tconst opts = {\n\t\tstoreOTP: \"plain\",\n\t\tdigits: 6,\n\t\t...options,\n\t\tperiod: (options?.period || 3) * 60 * 1e3\n\t};\n\tasync function storeOTP(ctx, otp) {\n\t\tif (opts.storeOTP === \"hashed\") return await defaultKeyHasher(otp);\n\t\tif (typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) return await opts.storeOTP.hash(otp);\n\t\tif (typeof opts.storeOTP === \"object\" && \"encrypt\" in opts.storeOTP) return await opts.storeOTP.encrypt(otp);\n\t\tif (opts.storeOTP === \"encrypted\") return await symmetricEncrypt({\n\t\t\tkey: ctx.context.secretConfig,\n\t\t\tdata: otp\n\t\t});\n\t\treturn otp;\n\t}\n\tasync function decryptOrHashForComparison(ctx, storedOtp, userInput) {\n\t\tif (opts.storeOTP === \"hashed\") return [storedOtp, await defaultKeyHasher(userInput)];\n\t\tif (opts.storeOTP === \"encrypted\") return [await symmetricDecrypt({\n\t\t\tkey: ctx.context.secretConfig,\n\t\t\tdata: storedOtp\n\t\t}), userInput];\n\t\tif (typeof opts.storeOTP === \"object\" && \"encrypt\" in opts.storeOTP) return [await opts.storeOTP.decrypt(storedOtp), userInput];\n\t\tif (typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) return [storedOtp, await opts.storeOTP.hash(userInput)];\n\t\treturn [storedOtp, userInput];\n\t}\n\treturn {\n\t\tid: \"otp\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\tsendTwoFactorOTP: createAuthEndpoint(\"/two-factor/send-otp\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: send2FaOTPBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Send two factor OTP\",\n\t\t\t\t\tdescription: \"Send two factor OTP to the user\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (!options || !options.sendOTP) {\n\t\t\t\t\tctx.context.logger.error(\"send otp isn't configured. Please configure the send otp function on otp options.\");\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"otp isn't configured\",\n\t\t\t\t\t\tcode: \"OTP_NOT_CONFIGURED\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst { session, key } = await verifyTwoFactor(ctx);\n\t\t\t\tconst code = generateRandomString(opts.digits, \"0-9\");\n\t\t\t\tconst hashedCode = await storeOTP(ctx, code);\n\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\tvalue: `${hashedCode}:0`,\n\t\t\t\t\tidentifier: `2fa-otp-${key}`,\n\t\t\t\t\texpiresAt: new Date(Date.now() + opts.period)\n\t\t\t\t});\n\t\t\t\tconst sendOTPResult = options.sendOTP({\n\t\t\t\t\tuser: session.user,\n\t\t\t\t\totp: code\n\t\t\t\t}, ctx);\n\t\t\t\tif (sendOTPResult instanceof Promise) await ctx.context.runInBackgroundOrAwait(sendOTPResult.catch((e) => {\n\t\t\t\t\tctx.context.logger.error(\"Failed to send two-factor OTP\", e);\n\t\t\t\t}));\n\t\t\t\treturn ctx.json({ status: true });\n\t\t\t}),\n\t\t\tverifyTwoFactorOTP: createAuthEndpoint(\"/two-factor/verify-otp\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: verifyOTPBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Verify two factor OTP\",\n\t\t\t\t\tdescription: \"Verify two factor OTP\",\n\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\tdescription: \"Two-factor OTP verified successfully\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\tdescription: \"Session token for the authenticated session\"\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Unique identifier of the user\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's email address\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temailVerified: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the email is verified\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's name\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\timage: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's profile image URL\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the user was created\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the user was last updated\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdescription: \"The authenticated user object\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\trequired: [\"token\", \"user\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst { session, key, valid, invalid } = await verifyTwoFactor(ctx);\n\t\t\t\tconst toCheckOtp = await ctx.context.internalAdapter.findVerificationValue(`2fa-otp-${key}`);\n\t\t\t\tconst [otp, counter] = toCheckOtp?.value?.split(\":\") ?? [];\n\t\t\t\tif (!toCheckOtp || toCheckOtp.expiresAt < /* @__PURE__ */ new Date()) {\n\t\t\t\t\tif (toCheckOtp) await ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`);\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.OTP_HAS_EXPIRED);\n\t\t\t\t}\n\t\t\t\tconst allowedAttempts = options?.allowedAttempts || 5;\n\t\t\t\tif (parseInt(counter) >= allowedAttempts) {\n\t\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`);\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE);\n\t\t\t\t}\n\t\t\t\tconst [storedValue, inputValue] = await decryptOrHashForComparison(ctx, otp, ctx.body.code);\n\t\t\t\tif (constantTimeEqual(new TextEncoder().encode(storedValue), new TextEncoder().encode(inputValue))) {\n\t\t\t\t\tif (!session.user.twoFactorEnabled) {\n\t\t\t\t\t\tif (!session.session) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);\n\t\t\t\t\t\tconst updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { twoFactorEnabled: true });\n\t\t\t\t\t\tconst newSession = await ctx.context.internalAdapter.createSession(session.user.id, false, session.session);\n\t\t\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\t\t\tsession: newSession,\n\t\t\t\t\t\t\tuser: updatedUser\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait ctx.context.internalAdapter.deleteSession(session.session.token);\n\t\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\t\ttoken: newSession.token,\n\t\t\t\t\t\t\tuser: parseUserOutput(ctx.context.options, updatedUser)\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\treturn valid(ctx);\n\t\t\t\t} else {\n\t\t\t\t\tawait ctx.context.internalAdapter.updateVerificationByIdentifier(`2fa-otp-${key}`, { value: `${otp}:${(parseInt(counter, 10) || 0) + 1}` });\n\t\t\t\t\treturn invalid(\"INVALID_CODE\");\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t};\n};\n//#endregion\nexport { otp2fa };\n", "//#region src/plugins/two-factor/schema.ts\nconst schema = {\n\tuser: { fields: { twoFactorEnabled: {\n\t\ttype: \"boolean\",\n\t\trequired: false,\n\t\tdefaultValue: false,\n\t\tinput: false\n\t} } },\n\ttwoFactor: { fields: {\n\t\tsecret: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\treturned: false,\n\t\t\tindex: true\n\t\t},\n\t\tbackupCodes: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\treturned: false\n\t\t},\n\t\tuserId: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\treturned: false,\n\t\t\treferences: {\n\t\t\t\tmodel: \"user\",\n\t\t\t\tfield: \"id\"\n\t\t\t},\n\t\t\tindex: true\n\t\t},\n\t\tverified: {\n\t\t\ttype: \"boolean\",\n\t\t\trequired: false,\n\t\t\tdefaultValue: true,\n\t\t\tinput: false\n\t\t}\n\t} }\n};\n//#endregion\nexport { schema };\n", "import { symmetricDecrypt } from \"../../../crypto/index.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { sessionMiddleware } from \"../../../api/routes/session.mjs\";\nimport { shouldRequirePassword } from \"../../../utils/password.mjs\";\nimport { PACKAGE_VERSION } from \"../../../version.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"../error-code.mjs\";\nimport { verifyTwoFactor } from \"../verify-two-factor.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\nimport { createOTP } from \"@better-auth/utils/otp\";\n//#region src/plugins/two-factor/totp/index.ts\nconst generateTOTPBodySchema = z.object({ secret: z.string().meta({ description: \"The secret to generate the TOTP code\" }) });\nconst verifyTOTPBodySchema = z.object({\n\tcode: z.string().meta({ description: \"The otp code to verify. Eg: \\\"012345\\\"\" }),\n\ttrustDevice: z.boolean().meta({ description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\" }).optional()\n});\nconst totp2fa = (options) => {\n\tconst opts = {\n\t\t...options,\n\t\tdigits: options?.digits || 6,\n\t\tperiod: options?.period || 30\n\t};\n\tconst passwordSchema = z.string().meta({ description: \"User password\" });\n\tconst getTOTPURIBodySchema = options?.allowPasswordless ? z.object({ password: passwordSchema.optional() }) : z.object({ password: passwordSchema });\n\tconst twoFactorTable = \"twoFactor\";\n\treturn {\n\t\tid: \"totp\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\tgenerateTOTP: createAuthEndpoint({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: generateTOTPBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Generate TOTP code\",\n\t\t\t\t\tdescription: \"Use this endpoint to generate a TOTP code\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { code: { type: \"string\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (options?.disable) {\n\t\t\t\t\tctx.context.logger.error(\"totp isn't configured. please pass totp option on two factor plugin to enable totp\");\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"totp isn't configured\",\n\t\t\t\t\t\tcode: \"TOTP_NOT_CONFIGURED\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { code: await createOTP(ctx.body.secret, {\n\t\t\t\t\tperiod: opts.period,\n\t\t\t\t\tdigits: opts.digits\n\t\t\t\t}).totp() };\n\t\t\t}),\n\t\t\tgetTOTPURI: createAuthEndpoint(\"/two-factor/get-totp-uri\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tbody: getTOTPURIBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Get TOTP URI\",\n\t\t\t\t\tdescription: \"Use this endpoint to get the TOTP URI\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { totpURI: { type: \"string\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (options?.disable) {\n\t\t\t\t\tctx.context.logger.error(\"totp isn't configured. please pass totp option on two factor plugin to enable totp\");\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"totp isn't configured\",\n\t\t\t\t\t\tcode: \"TOTP_NOT_CONFIGURED\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst user = ctx.context.session.user;\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED);\n\t\t\t\tconst secret = await symmetricDecrypt({\n\t\t\t\t\tkey: ctx.context.secretConfig,\n\t\t\t\t\tdata: twoFactor.secret\n\t\t\t\t});\n\t\t\t\tif (await shouldRequirePassword(ctx, user.id, options?.allowPasswordless)) {\n\t\t\t\t\tif (!ctx.body.password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t\tawait ctx.context.password.checkPassword(user.id, ctx);\n\t\t\t\t}\n\t\t\t\treturn { totpURI: createOTP(secret, {\n\t\t\t\t\tdigits: opts.digits,\n\t\t\t\t\tperiod: opts.period\n\t\t\t\t}).url(options?.issuer || ctx.context.appName, user.email) };\n\t\t\t}),\n\t\t\tverifyTOTP: createAuthEndpoint(\"/two-factor/verify-totp\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: verifyTOTPBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Verify two factor TOTP\",\n\t\t\t\t\tdescription: \"Verify two factor TOTP\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (options?.disable) {\n\t\t\t\t\tctx.context.logger.error(\"totp isn't configured. please pass totp option on two factor plugin to enable totp\");\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"totp isn't configured\",\n\t\t\t\t\t\tcode: \"TOTP_NOT_CONFIGURED\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst { session, valid, invalid } = await verifyTwoFactor(ctx);\n\t\t\t\tconst user = session.user;\n\t\t\t\tconst isSignIn = !session.session;\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED);\n\t\t\t\tif (isSignIn && twoFactor.verified === false) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED);\n\t\t\t\tif (!await createOTP(await symmetricDecrypt({\n\t\t\t\t\tkey: ctx.context.secretConfig,\n\t\t\t\t\tdata: twoFactor.secret\n\t\t\t\t}), {\n\t\t\t\t\tperiod: opts.period,\n\t\t\t\t\tdigits: opts.digits\n\t\t\t\t}).verify(ctx.body.code)) return invalid(\"INVALID_CODE\");\n\t\t\t\tif (twoFactor.verified !== true) {\n\t\t\t\t\tif (!user.twoFactorEnabled) {\n\t\t\t\t\t\tconst activeSession = session.session;\n\t\t\t\t\t\tconst updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: true });\n\t\t\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\t\t\tsession: await ctx.context.internalAdapter.createSession(user.id, false, activeSession),\n\t\t\t\t\t\t\tuser: updatedUser\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait ctx.context.internalAdapter.deleteSession(activeSession.token);\n\t\t\t\t\t}\n\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\t\tupdate: { verified: true },\n\t\t\t\t\t\twhere: [{\n\t\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\t\tvalue: twoFactor.id\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn valid(ctx);\n\t\t\t})\n\t\t}\n\t};\n};\n//#endregion\nexport { totp2fa };\n", "function getAlphabet(hex) {\n return hex ? \"0123456789ABCDEFGHIJKLMNOPQRSTUV\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n}\nfunction createDecodeMap(alphabet) {\n const decodeMap = /* @__PURE__ */ new Map();\n for (let i = 0; i < alphabet.length; i++) {\n decodeMap.set(alphabet[i], i);\n }\n return decodeMap;\n}\nfunction base32Encode(data, alphabet, padding) {\n let result = \"\";\n let buffer = 0;\n let shift = 0;\n for (const byte of data) {\n buffer = buffer << 8 | byte;\n shift += 8;\n while (shift >= 5) {\n shift -= 5;\n result += alphabet[buffer >> shift & 31];\n }\n }\n if (shift > 0) {\n result += alphabet[buffer << 5 - shift & 31];\n }\n if (padding) {\n const padCount = (8 - result.length % 8) % 8;\n result += \"=\".repeat(padCount);\n }\n return result;\n}\nfunction base32Decode(data, alphabet) {\n const decodeMap = createDecodeMap(alphabet);\n const result = [];\n let buffer = 0;\n let bitsCollected = 0;\n for (const char of data) {\n if (char === \"=\")\n break;\n const value = decodeMap.get(char);\n if (value === void 0) {\n throw new Error(`Invalid Base32 character: ${char}`);\n }\n buffer = buffer << 5 | value;\n bitsCollected += 5;\n while (bitsCollected >= 8) {\n bitsCollected -= 8;\n result.push(buffer >> bitsCollected & 255);\n }\n }\n return Uint8Array.from(result);\n}\nconst base32 = {\n /**\n * Encodes data into a Base32 string.\n * @param data - The data to encode (ArrayBuffer, TypedArray, or string).\n * @param options - Encoding options.\n * @returns The Base32 encoded string.\n */\n encode(data, options = {}) {\n const alphabet = getAlphabet(false);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base32Encode(buffer, alphabet, options.padding ?? true);\n },\n /**\n * Decodes a Base32 string into a Uint8Array.\n * @param data - The Base32 encoded string or ArrayBuffer/TypedArray.\n * @returns The decoded Uint8Array.\n */\n decode(data) {\n if (typeof data !== \"string\") {\n data = new TextDecoder().decode(data);\n }\n const alphabet = getAlphabet(false);\n return base32Decode(data, alphabet);\n }\n};\nconst base32hex = {\n /**\n * Encodes data into a Base32hex string.\n * @param data - The data to encode (ArrayBuffer, TypedArray, or string).\n * @param options - Encoding options.\n * @returns The Base32hex encoded string.\n */\n encode(data, options = {}) {\n const alphabet = getAlphabet(true);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base32Encode(buffer, alphabet, options.padding ?? true);\n },\n /**\n * Decodes a Base32hex string into a Uint8Array.\n * @param data - The Base32hex encoded string.\n * @returns The decoded Uint8Array.\n */\n decode(data) {\n const alphabet = getAlphabet(true);\n return base32Decode(data, alphabet);\n }\n};\n\nexport { base32, base32hex };\n", "import { base32 } from './base32.mjs';\nimport { createHMAC } from './hmac.mjs';\nimport './hex.mjs';\nimport './base64.mjs';\nimport './index.mjs';\n\nconst defaultPeriod = 30;\nconst defaultDigits = 6;\nasync function generateHOTP(secret, {\n counter,\n digits,\n hash = \"SHA-1\"\n}) {\n const _digits = digits ?? defaultDigits;\n if (_digits < 1 || _digits > 8) {\n throw new TypeError(\"Digits must be between 1 and 8\");\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigUint64(0, BigInt(counter), false);\n const bytes = new Uint8Array(buffer);\n const hmacResult = new Uint8Array(await createHMAC(hash).sign(secret, bytes));\n const offset = hmacResult[hmacResult.length - 1] & 15;\n const truncated = (hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255;\n const otp = truncated % 10 ** _digits;\n return otp.toString().padStart(_digits, \"0\");\n}\nasync function generateTOTP(secret, options) {\n const digits = options?.digits ?? defaultDigits;\n const period = options?.period ?? defaultPeriod;\n const milliseconds = period * 1e3;\n const counter = Math.floor(Date.now() / milliseconds);\n return await generateHOTP(secret, { counter, digits, hash: options?.hash });\n}\nasync function verifyTOTP(otp, {\n window = 1,\n digits = defaultDigits,\n secret,\n period = defaultPeriod\n}) {\n const milliseconds = period * 1e3;\n const counter = Math.floor(Date.now() / milliseconds);\n for (let i = -window; i <= window; i++) {\n const generatedOTP = await generateHOTP(secret, {\n counter: counter + i,\n digits\n });\n if (otp === generatedOTP) {\n return true;\n }\n }\n return false;\n}\nfunction generateQRCode({\n issuer,\n account,\n secret,\n digits = defaultDigits,\n period = defaultPeriod\n}) {\n const encodedIssuer = encodeURIComponent(issuer);\n const encodedAccountName = encodeURIComponent(account);\n const baseURI = `otpauth://totp/${encodedIssuer}:${encodedAccountName}`;\n const params = new URLSearchParams({\n secret: base32.encode(secret, {\n padding: false\n }),\n issuer\n });\n if (digits !== void 0) {\n params.set(\"digits\", digits.toString());\n }\n if (period !== void 0) {\n params.set(\"period\", period.toString());\n }\n return `${baseURI}?${params.toString()}`;\n}\nconst createOTP = (secret, opts) => {\n const digits = opts?.digits ?? defaultDigits;\n const period = opts?.period ?? defaultPeriod;\n return {\n hotp: (counter) => generateHOTP(secret, { counter, digits }),\n totp: () => generateTOTP(secret, { digits, period }),\n verify: (otp, options) => verifyTOTP(otp, { secret, digits, period, ...options }),\n url: (issuer, account) => generateQRCode({ issuer, account, secret, digits, period })\n };\n};\n\nexport { createOTP };\n", "import { mergeSchema } from \"../../db/schema.mjs\";\nimport { generateRandomString } from \"../../crypto/random.mjs\";\nimport { symmetricEncrypt } from \"../../crypto/index.mjs\";\nimport { deleteSessionCookie, expireCookie, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { sessionMiddleware } from \"../../api/routes/session.mjs\";\nimport { shouldRequirePassword, validatePassword } from \"../../utils/password.mjs\";\nimport { PACKAGE_VERSION } from \"../../version.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"./error-code.mjs\";\nimport { twoFactorClient } from \"./client.mjs\";\nimport { TRUST_DEVICE_COOKIE_NAME, TWO_FACTOR_COOKIE_NAME } from \"./constant.mjs\";\nimport { backupCode2fa, generateBackupCodes } from \"./backup-codes/index.mjs\";\nimport { otp2fa } from \"./otp/index.mjs\";\nimport { schema } from \"./schema.mjs\";\nimport { totp2fa } from \"./totp/index.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint, createAuthMiddleware } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\nimport { createOTP } from \"@better-auth/utils/otp\";\n//#region src/plugins/two-factor/index.ts\nconst twoFactor = (options) => {\n\tconst opts = { twoFactorTable: \"twoFactor\" };\n\tconst trustDeviceMaxAge = options?.trustDeviceMaxAge ?? 2592e3;\n\tconst allowPasswordless = options?.allowPasswordless;\n\tconst backupCodeOptions = {\n\t\tstoreBackupCodes: \"encrypted\",\n\t\t...options?.backupCodeOptions\n\t};\n\tconst totp = totp2fa({\n\t\t...options?.totpOptions,\n\t\tallowPasswordless: options?.totpOptions?.allowPasswordless ?? allowPasswordless\n\t});\n\tconst backupCode = backupCode2fa({\n\t\t...backupCodeOptions,\n\t\tallowPasswordless: options?.backupCodeOptions?.allowPasswordless ?? allowPasswordless\n\t});\n\tconst otp = otp2fa(options?.otpOptions);\n\tconst passwordSchema = z.string().meta({ description: \"User password\" });\n\tconst enableTwoFactorBodySchema = allowPasswordless ? z.object({\n\t\tpassword: passwordSchema.optional(),\n\t\tissuer: z.string().meta({ description: \"Custom issuer for the TOTP URI\" }).optional()\n\t}) : z.object({\n\t\tpassword: passwordSchema,\n\t\tissuer: z.string().meta({ description: \"Custom issuer for the TOTP URI\" }).optional()\n\t});\n\tconst disableTwoFactorBodySchema = allowPasswordless ? z.object({ password: passwordSchema.optional() }) : z.object({ password: passwordSchema });\n\treturn {\n\t\tid: \"two-factor\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\t...totp.endpoints,\n\t\t\t...otp.endpoints,\n\t\t\t...backupCode.endpoints,\n\t\t\tenableTwoFactor: createAuthEndpoint(\"/two-factor/enable\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: enableTwoFactorBodySchema,\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Enable two factor authentication\",\n\t\t\t\t\tdescription: \"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\ttotpURI: {\n\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\tdescription: \"TOTP URI\"\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbackupCodes: {\n\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\t\t\tdescription: \"Backup codes\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst user = ctx.context.session.user;\n\t\t\t\tconst { password, issuer } = ctx.body;\n\t\t\t\tif (await shouldRequirePassword(ctx, user.id, allowPasswordless)) {\n\t\t\t\t\tif (!password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t\tif (!await validatePassword(ctx, {\n\t\t\t\t\t\tpassword,\n\t\t\t\t\t\tuserId: user.id\n\t\t\t\t\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t}\n\t\t\t\tconst secret = generateRandomString(32);\n\t\t\t\tconst encryptedSecret = await symmetricEncrypt({\n\t\t\t\t\tkey: ctx.context.secretConfig,\n\t\t\t\t\tdata: secret\n\t\t\t\t});\n\t\t\t\tconst backupCodes = await generateBackupCodes(ctx.context.secretConfig, backupCodeOptions);\n\t\t\t\tif (options?.skipVerificationOnEnable) {\n\t\t\t\t\tconst updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: true });\n\t\t\t\t\t/**\n\t\t\t\t\t* Update the session cookie with the new user data\n\t\t\t\t\t*/\n\t\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\t\tsession: await ctx.context.internalAdapter.createSession(updatedUser.id, false, ctx.context.session.session),\n\t\t\t\t\t\tuser: updatedUser\n\t\t\t\t\t});\n\t\t\t\t\tawait ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token);\n\t\t\t\t}\n\t\t\t\tconst existingTwoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tawait ctx.context.adapter.deleteMany({\n\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tawait ctx.context.adapter.create({\n\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tsecret: encryptedSecret,\n\t\t\t\t\t\tbackupCodes: backupCodes.encryptedBackupCodes,\n\t\t\t\t\t\tuserId: user.id,\n\t\t\t\t\t\tverified: existingTwoFactor != null && existingTwoFactor.verified !== false || !!options?.skipVerificationOnEnable\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tconst totpURI = createOTP(secret, {\n\t\t\t\t\tdigits: options?.totpOptions?.digits || 6,\n\t\t\t\t\tperiod: options?.totpOptions?.period\n\t\t\t\t}).url(issuer || options?.issuer || ctx.context.appName, user.email);\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttotpURI,\n\t\t\t\t\tbackupCodes: backupCodes.backupCodes\n\t\t\t\t});\n\t\t\t}),\n\t\t\tdisableTwoFactor: createAuthEndpoint(\"/two-factor/disable\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: disableTwoFactorBodySchema,\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Disable two factor authentication\",\n\t\t\t\t\tdescription: \"Use this endpoint to disable two factor authentication.\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst user = ctx.context.session.user;\n\t\t\t\tconst { password } = ctx.body;\n\t\t\t\tif (await shouldRequirePassword(ctx, user.id, allowPasswordless)) {\n\t\t\t\t\tif (!password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t\tif (!await validatePassword(ctx, {\n\t\t\t\t\t\tpassword,\n\t\t\t\t\t\tuserId: user.id\n\t\t\t\t\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t}\n\t\t\t\tconst updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: false });\n\t\t\t\tawait ctx.context.adapter.delete({\n\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: updatedUser.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\t/**\n\t\t\t\t* Update the session cookie with the new user data\n\t\t\t\t*/\n\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\tsession: await ctx.context.internalAdapter.createSession(updatedUser.id, false, ctx.context.session.session),\n\t\t\t\t\tuser: updatedUser\n\t\t\t\t});\n\t\t\t\tawait ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token);\n\t\t\t\tconst disableTrustCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });\n\t\t\t\tconst disableTrustValue = await ctx.getSignedCookie(disableTrustCookie.name, ctx.context.secret);\n\t\t\t\tif (disableTrustValue) {\n\t\t\t\t\tconst [, trustId] = disableTrustValue.split(\"!\");\n\t\t\t\t\tif (trustId) await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustId);\n\t\t\t\t\texpireCookie(ctx, disableTrustCookie);\n\t\t\t\t}\n\t\t\t\treturn ctx.json({ status: true });\n\t\t\t})\n\t\t},\n\t\toptions,\n\t\thooks: { after: [{\n\t\t\tmatcher(context) {\n\t\t\t\treturn context.path === \"/sign-in/email\" || context.path === \"/sign-in/username\" || context.path === \"/sign-in/phone-number\";\n\t\t\t},\n\t\t\thandler: createAuthMiddleware(async (ctx) => {\n\t\t\t\tconst data = ctx.context.newSession;\n\t\t\t\tif (!data) return;\n\t\t\t\tif (!data?.user.twoFactorEnabled) return;\n\t\t\t\tconst trustDeviceCookieAttrs = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });\n\t\t\t\tconst trustDeviceCookie = await ctx.getSignedCookie(trustDeviceCookieAttrs.name, ctx.context.secret);\n\t\t\t\tif (trustDeviceCookie) {\n\t\t\t\t\tconst [token, trustIdentifier] = trustDeviceCookie.split(\"!\");\n\t\t\t\t\tif (token && trustIdentifier) {\n\t\t\t\t\t\tif (token === await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, `${data.user.id}!${trustIdentifier}`)) {\n\t\t\t\t\t\t\tconst verificationRecord = await ctx.context.internalAdapter.findVerificationValue(trustIdentifier);\n\t\t\t\t\t\t\tif (verificationRecord && verificationRecord.value === data.user.id && verificationRecord.expiresAt > /* @__PURE__ */ new Date()) {\n\t\t\t\t\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(trustIdentifier);\n\t\t\t\t\t\t\t\tconst newTrustIdentifier = `trust-device-${generateRandomString(32)}`;\n\t\t\t\t\t\t\t\tconst newToken = await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, `${data.user.id}!${newTrustIdentifier}`);\n\t\t\t\t\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\t\t\t\t\tvalue: data.user.id,\n\t\t\t\t\t\t\t\t\tidentifier: newTrustIdentifier,\n\t\t\t\t\t\t\t\t\texpiresAt: new Date(Date.now() + trustDeviceMaxAge * 1e3)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst newTrustDeviceCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });\n\t\t\t\t\t\t\t\tawait ctx.setSignedCookie(newTrustDeviceCookie.name, `${newToken}!${newTrustIdentifier}`, ctx.context.secret, trustDeviceCookieAttrs.attributes);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\texpireCookie(ctx, trustDeviceCookieAttrs);\n\t\t\t\t}\n\t\t\t\t/**\n\t\t\t\t* remove the session cookie. It's set by the sign in credential\n\t\t\t\t*/\n\t\t\t\tdeleteSessionCookie(ctx, true);\n\t\t\t\tawait ctx.context.internalAdapter.deleteSession(data.session.token);\n\t\t\t\tconst maxAge = options?.twoFactorCookieMaxAge ?? 600;\n\t\t\t\tconst twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME, { maxAge });\n\t\t\t\tconst identifier = `2fa-${generateRandomString(20)}`;\n\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\tvalue: data.user.id,\n\t\t\t\t\tidentifier,\n\t\t\t\t\texpiresAt: new Date(Date.now() + maxAge * 1e3)\n\t\t\t\t});\n\t\t\t\tawait ctx.setSignedCookie(twoFactorCookie.name, identifier, ctx.context.secret, twoFactorCookie.attributes);\n\t\t\t\tconst twoFactorMethods = [];\n\t\t\t\t/**\n\t\t\t\t* totp requires per-user setup, so we check\n\t\t\t\t* that the user actually has a secret stored.\n\t\t\t\t*/\n\t\t\t\tif (!options?.totpOptions?.disable) {\n\t\t\t\t\tconst userTotpSecret = await ctx.context.adapter.findOne({\n\t\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\t\twhere: [{\n\t\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\t\tvalue: data.user.id\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tif (userTotpSecret && userTotpSecret.verified !== false) twoFactorMethods.push(\"totp\");\n\t\t\t\t}\n\t\t\t\t/**\n\t\t\t\t* otp is server-level \u2014 if sendOTP is configured,\n\t\t\t\t* any user with 2fa enabled can receive a code.\n\t\t\t\t*/\n\t\t\t\tif (options?.otpOptions?.sendOTP) twoFactorMethods.push(\"otp\");\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttwoFactorRedirect: true,\n\t\t\t\t\ttwoFactorMethods\n\t\t\t\t});\n\t\t\t})\n\t\t}] },\n\t\tschema: mergeSchema(schema, {\n\t\t\t...options?.schema,\n\t\t\ttwoFactor: {\n\t\t\t\t...options?.schema?.twoFactor,\n\t\t\t\t...options?.twoFactorTable ? { modelName: options.twoFactorTable } : {}\n\t\t\t}\n\t\t}),\n\t\trateLimit: [{\n\t\t\tpathMatcher(path) {\n\t\t\t\treturn path.startsWith(\"/two-factor/\");\n\t\t\t},\n\t\t\twindow: 10,\n\t\t\tmax: 3\n\t\t}],\n\t\t$ERROR_CODES: TWO_FACTOR_ERROR_CODES\n\t};\n};\n//#endregion\nexport { TWO_FACTOR_ERROR_CODES, twoFactor, twoFactorClient };\n", "import { base64Url } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\n//#region src/plugins/magic-link/utils.ts\nconst defaultKeyHasher = async (otp) => {\n\tconst hash = await createHash(\"SHA-256\").digest(new TextEncoder().encode(otp));\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n};\n//#endregion\nexport { defaultKeyHasher };\n", "import { originCheck } from \"../../api/middlewares/origin-check.mjs\";\nimport { parseSessionOutput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { generateRandomString } from \"../../crypto/random.mjs\";\nimport { setSessionCookie } from \"../../cookies/index.mjs\";\nimport { PACKAGE_VERSION } from \"../../version.mjs\";\nimport { defaultKeyHasher } from \"./utils.mjs\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/magic-link/index.ts\nconst signInMagicLinkBodySchema = z.object({\n\temail: z.email().meta({ description: \"Email address to send the magic link\" }),\n\tname: z.string().meta({ description: \"User display name. Only used if the user is registering for the first time. Eg: \\\"my-name\\\"\" }).optional(),\n\tcallbackURL: z.string().meta({ description: \"URL to redirect after magic link verification\" }).optional(),\n\tnewUserCallbackURL: z.string().meta({ description: \"URL to redirect after new user signup. Only used if the user is registering for the first time.\" }).optional(),\n\terrorCallbackURL: z.string().meta({ description: \"URL to redirect after error.\" }).optional(),\n\tmetadata: z.record(z.string(), z.any()).meta({ description: \"Additional metadata to pass to sendMagicLink.\" }).optional()\n});\nconst magicLinkVerifyQuerySchema = z.object({\n\ttoken: z.string().meta({ description: \"Verification token\" }),\n\tcallbackURL: z.string().meta({ description: \"URL to redirect after magic link verification, if not provided the user will be redirected to the root URL. Eg: \\\"/dashboard\\\"\" }).optional(),\n\terrorCallbackURL: z.string().meta({ description: \"URL to redirect after error.\" }).optional(),\n\tnewUserCallbackURL: z.string().meta({ description: \"URL to redirect after new user signup. Only used if the user is registering for the first time.\" }).optional()\n});\nconst magicLink = (options) => {\n\tconst opts = {\n\t\tstoreToken: \"plain\",\n\t\tallowedAttempts: 1,\n\t\t...options\n\t};\n\tasync function storeToken(ctx, token) {\n\t\tif (opts.storeToken === \"hashed\") return await defaultKeyHasher(token);\n\t\tif (typeof opts.storeToken === \"object\" && \"type\" in opts.storeToken && opts.storeToken.type === \"custom-hasher\") return await opts.storeToken.hash(token);\n\t\treturn token;\n\t}\n\treturn {\n\t\tid: \"magic-link\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\tsignInMagicLink: createAuthEndpoint(\"/sign-in/magic-link\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\trequireHeaders: true,\n\t\t\t\tbody: signInMagicLinkBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\toperationId: \"signInWithMagicLink\",\n\t\t\t\t\tdescription: \"Sign in with magic link\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst { email, metadata } = ctx.body;\n\t\t\t\tconst verificationToken = opts?.generateToken ? await opts.generateToken(email) : generateRandomString(32, \"a-z\", \"A-Z\");\n\t\t\t\tconst storedToken = await storeToken(ctx, verificationToken);\n\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\tidentifier: storedToken,\n\t\t\t\t\tvalue: JSON.stringify({\n\t\t\t\t\t\temail,\n\t\t\t\t\t\tname: ctx.body.name,\n\t\t\t\t\t\tattempt: 0\n\t\t\t\t\t}),\n\t\t\t\t\texpiresAt: new Date(Date.now() + (opts.expiresIn || 300) * 1e3)\n\t\t\t\t});\n\t\t\t\tconst realBaseURL = new URL(ctx.context.baseURL);\n\t\t\t\tconst pathname = realBaseURL.pathname === \"/\" ? \"\" : realBaseURL.pathname;\n\t\t\t\tconst basePath = pathname ? \"\" : ctx.context.options.basePath || \"\";\n\t\t\t\tconst url = new URL(`${pathname}${basePath}/magic-link/verify`, realBaseURL.origin);\n\t\t\t\turl.searchParams.set(\"token\", verificationToken);\n\t\t\t\turl.searchParams.set(\"callbackURL\", ctx.body.callbackURL || \"/\");\n\t\t\t\tif (ctx.body.newUserCallbackURL) url.searchParams.set(\"newUserCallbackURL\", ctx.body.newUserCallbackURL);\n\t\t\t\tif (ctx.body.errorCallbackURL) url.searchParams.set(\"errorCallbackURL\", ctx.body.errorCallbackURL);\n\t\t\t\tawait options.sendMagicLink({\n\t\t\t\t\temail,\n\t\t\t\t\turl: url.toString(),\n\t\t\t\t\ttoken: verificationToken,\n\t\t\t\t\tmetadata\n\t\t\t\t}, ctx);\n\t\t\t\treturn ctx.json({ status: true });\n\t\t\t}),\n\t\t\tmagicLinkVerify: createAuthEndpoint(\"/magic-link/verify\", {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tquery: magicLinkVerifyQuerySchema,\n\t\t\t\tuse: [\n\t\t\t\t\toriginCheck((ctx) => {\n\t\t\t\t\t\treturn ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : \"/\";\n\t\t\t\t\t}),\n\t\t\t\t\toriginCheck((ctx) => {\n\t\t\t\t\t\treturn ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : \"/\";\n\t\t\t\t\t}),\n\t\t\t\t\toriginCheck((ctx) => {\n\t\t\t\t\t\treturn ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : \"/\";\n\t\t\t\t\t})\n\t\t\t\t],\n\t\t\t\trequireHeaders: true,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\toperationId: \"verifyMagicLink\",\n\t\t\t\t\tdescription: \"Verify magic link\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tsession: { $ref: \"#/components/schemas/Session\" },\n\t\t\t\t\t\t\t\tuser: { $ref: \"#/components/schemas/User\" }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst token = ctx.query.token;\n\t\t\t\tconst callbackURL = new URL(ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : \"/\", ctx.context.baseURL).toString();\n\t\t\t\tconst errorCallbackURL = new URL(ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : callbackURL, ctx.context.baseURL);\n\t\t\t\tfunction redirectWithError(error) {\n\t\t\t\t\terrorCallbackURL.searchParams.set(\"error\", error);\n\t\t\t\t\tthrow ctx.redirect(errorCallbackURL.toString());\n\t\t\t\t}\n\t\t\t\tconst newUserCallbackURL = new URL(ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : callbackURL, ctx.context.baseURL).toString();\n\t\t\t\tconst storedToken = await storeToken(ctx, token);\n\t\t\t\tconst tokenValue = await ctx.context.internalAdapter.findVerificationValue(storedToken);\n\t\t\t\tif (!tokenValue) redirectWithError(\"INVALID_TOKEN\");\n\t\t\t\tif (tokenValue.expiresAt < /* @__PURE__ */ new Date()) {\n\t\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(storedToken);\n\t\t\t\t\tredirectWithError(\"EXPIRED_TOKEN\");\n\t\t\t\t}\n\t\t\t\tconst { email, name, attempt = 0 } = JSON.parse(tokenValue.value);\n\t\t\t\tif (attempt >= opts.allowedAttempts) {\n\t\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(storedToken);\n\t\t\t\t\tredirectWithError(\"ATTEMPTS_EXCEEDED\");\n\t\t\t\t}\n\t\t\t\tawait ctx.context.internalAdapter.updateVerificationByIdentifier(storedToken, { value: JSON.stringify({\n\t\t\t\t\temail,\n\t\t\t\t\tname,\n\t\t\t\t\tattempt: attempt + 1\n\t\t\t\t}) });\n\t\t\t\tlet isNewUser = false;\n\t\t\t\tlet user = await ctx.context.internalAdapter.findUserByEmail(email).then((res) => res?.user);\n\t\t\t\tif (!user) if (!opts.disableSignUp) {\n\t\t\t\t\tconst newUser = await ctx.context.internalAdapter.createUser({\n\t\t\t\t\t\temail,\n\t\t\t\t\t\temailVerified: true,\n\t\t\t\t\t\tname: name || \"\"\n\t\t\t\t\t});\n\t\t\t\t\tisNewUser = true;\n\t\t\t\t\tuser = newUser;\n\t\t\t\t\tif (!user) redirectWithError(\"failed_to_create_user\");\n\t\t\t\t} else redirectWithError(\"new_user_signup_disabled\");\n\t\t\t\tif (!user.emailVerified) user = await ctx.context.internalAdapter.updateUser(user.id, { emailVerified: true });\n\t\t\t\tconst session = await ctx.context.internalAdapter.createSession(user.id);\n\t\t\t\tif (!session) redirectWithError(\"failed_to_create_session\");\n\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\tsession,\n\t\t\t\t\tuser\n\t\t\t\t});\n\t\t\t\tif (!ctx.query.callbackURL) return ctx.json({\n\t\t\t\t\ttoken: session.token,\n\t\t\t\t\tuser: parseUserOutput(ctx.context.options, user),\n\t\t\t\t\tsession: parseSessionOutput(ctx.context.options, session)\n\t\t\t\t});\n\t\t\t\tif (isNewUser) throw ctx.redirect(newUserCallbackURL);\n\t\t\t\tthrow ctx.redirect(callbackURL);\n\t\t\t})\n\t\t},\n\t\trateLimit: [{\n\t\t\tpathMatcher(path) {\n\t\t\t\treturn path.startsWith(\"/sign-in/magic-link\") || path.startsWith(\"/magic-link/verify\");\n\t\t\t},\n\t\t\twindow: opts.rateLimit?.window || 60,\n\t\t\tmax: opts.rateLimit?.max || 5\n\t\t}],\n\t\toptions\n\t};\n};\n//#endregion\nexport { magicLink };\n", "import { createAdapterFactory, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName } from \"@better-auth/core/db/adapter\";\nexport * from \"@better-auth/core/db/adapter\";\n//#region src/adapters/index.ts\n/**\n* @deprecated Use `createAdapterFactory` instead.\n*/\nconst createAdapter = createAdapterFactory;\n//#endregion\nexport { createAdapter, createAdapterFactory, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName };\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { betterAuth } from 'better-auth';\nimport type { Auth, BetterAuthOptions } from 'better-auth';\nimport { organization } from 'better-auth/plugins/organization';\nimport { twoFactor } from 'better-auth/plugins/two-factor';\nimport { magicLink } from 'better-auth/plugins/magic-link';\nimport type { AuthConfig } from '@objectstack/spec/system';\nimport type { IDataEngine } from '@objectstack/core';\nimport { createObjectQLAdapterFactory } from './objectql-adapter.js';\nimport {\n AUTH_USER_CONFIG,\n AUTH_SESSION_CONFIG,\n AUTH_ACCOUNT_CONFIG,\n AUTH_VERIFICATION_CONFIG,\n buildOrganizationPluginSchema,\n buildTwoFactorPluginSchema,\n} from './auth-schema-config.js';\n\n/**\n * Extended options for AuthManager\n */\nexport interface AuthManagerOptions extends Partial {\n /**\n * Better-Auth instance (for advanced use cases)\n * If not provided, one will be created from config\n */\n authInstance?: Auth;\n\n /**\n * ObjectQL Data Engine instance\n * Required for database operations using ObjectQL instead of third-party ORMs\n */\n dataEngine?: IDataEngine;\n\n /**\n * Base path for auth routes\n * Forwarded to better-auth's basePath option so it can match incoming\n * request URLs without manual path rewriting.\n * @default '/api/v1/auth'\n */\n basePath?: string;\n}\n\n/**\n * Authentication Manager\n *\n * Wraps better-auth and provides authentication services for ObjectStack.\n * Supports multiple authentication methods:\n * - Email/password\n * - OAuth providers (Google, GitHub, etc.)\n * - Magic links\n * - Two-factor authentication\n * - Passkeys\n * - Organization/teams\n */\nexport class AuthManager {\n private auth: Auth | null = null;\n private config: AuthManagerOptions;\n\n constructor(config: AuthManagerOptions) {\n this.config = config;\n\n // Use provided auth instance\n if (config.authInstance) {\n this.auth = config.authInstance;\n }\n // Don't create auth instance automatically to avoid database initialization errors\n // It will be created lazily when needed\n }\n\n /**\n * Get or create the better-auth instance (lazy initialization)\n */\n private getOrCreateAuth(): Auth {\n if (!this.auth) {\n this.auth = this.createAuthInstance();\n }\n return this.auth;\n }\n\n /**\n * Create a better-auth instance from configuration\n */\n private createAuthInstance(): Auth {\n const betterAuthConfig: BetterAuthOptions = {\n // Base configuration\n secret: this.config.secret || this.generateSecret(),\n baseURL: this.config.baseUrl || 'http://localhost:3000',\n basePath: this.config.basePath || '/api/v1/auth',\n\n // Database adapter configuration\n database: this.createDatabaseConfig(),\n\n // Model/field mapping: camelCase (better-auth) → snake_case (ObjectStack)\n // These declarations tell better-auth the actual table/column names used\n // by ObjectStack's protocol layer, enabling automatic transformation via\n // createAdapterFactory.\n user: {\n ...AUTH_USER_CONFIG,\n },\n account: {\n ...AUTH_ACCOUNT_CONFIG,\n },\n verification: {\n ...AUTH_VERIFICATION_CONFIG,\n },\n\n // Social / OAuth providers\n ...(this.config.socialProviders ? { socialProviders: this.config.socialProviders as any } : {}),\n\n // Email and password configuration\n emailAndPassword: {\n enabled: this.config.emailAndPassword?.enabled ?? true,\n ...(this.config.emailAndPassword?.disableSignUp != null\n ? { disableSignUp: this.config.emailAndPassword.disableSignUp } : {}),\n ...(this.config.emailAndPassword?.requireEmailVerification != null\n ? { requireEmailVerification: this.config.emailAndPassword.requireEmailVerification } : {}),\n ...(this.config.emailAndPassword?.minPasswordLength != null\n ? { minPasswordLength: this.config.emailAndPassword.minPasswordLength } : {}),\n ...(this.config.emailAndPassword?.maxPasswordLength != null\n ? { maxPasswordLength: this.config.emailAndPassword.maxPasswordLength } : {}),\n ...(this.config.emailAndPassword?.resetPasswordTokenExpiresIn != null\n ? { resetPasswordTokenExpiresIn: this.config.emailAndPassword.resetPasswordTokenExpiresIn } : {}),\n ...(this.config.emailAndPassword?.autoSignIn != null\n ? { autoSignIn: this.config.emailAndPassword.autoSignIn } : {}),\n ...(this.config.emailAndPassword?.revokeSessionsOnPasswordReset != null\n ? { revokeSessionsOnPasswordReset: this.config.emailAndPassword.revokeSessionsOnPasswordReset } : {}),\n },\n\n // Email verification\n ...(this.config.emailVerification ? {\n emailVerification: {\n ...(this.config.emailVerification.sendOnSignUp != null\n ? { sendOnSignUp: this.config.emailVerification.sendOnSignUp } : {}),\n ...(this.config.emailVerification.sendOnSignIn != null\n ? { sendOnSignIn: this.config.emailVerification.sendOnSignIn } : {}),\n ...(this.config.emailVerification.autoSignInAfterVerification != null\n ? { autoSignInAfterVerification: this.config.emailVerification.autoSignInAfterVerification } : {}),\n ...(this.config.emailVerification.expiresIn != null\n ? { expiresIn: this.config.emailVerification.expiresIn } : {}),\n },\n } : {}),\n\n // Session configuration\n session: {\n ...AUTH_SESSION_CONFIG,\n expiresIn: this.config.session?.expiresIn || 60 * 60 * 24 * 7, // 7 days default\n updateAge: this.config.session?.updateAge || 60 * 60 * 24, // 1 day default\n },\n\n // better-auth plugins — registered based on AuthPluginConfig flags\n plugins: this.buildPluginList(),\n\n // Trusted origins for CSRF protection (supports wildcards like \"https://*.example.com\")\n ...(this.config.trustedOrigins?.length ? { trustedOrigins: this.config.trustedOrigins } : {}),\n\n // Advanced options (cross-subdomain cookies, secure cookies, CSRF, etc.)\n ...(this.config.advanced ? {\n advanced: {\n ...(this.config.advanced.crossSubDomainCookies\n ? { crossSubDomainCookies: this.config.advanced.crossSubDomainCookies } : {}),\n ...(this.config.advanced.useSecureCookies != null\n ? { useSecureCookies: this.config.advanced.useSecureCookies } : {}),\n ...(this.config.advanced.disableCSRFCheck != null\n ? { disableCSRFCheck: this.config.advanced.disableCSRFCheck } : {}),\n ...(this.config.advanced.cookiePrefix != null\n ? { cookiePrefix: this.config.advanced.cookiePrefix } : {}),\n },\n } : {}),\n };\n\n return betterAuth(betterAuthConfig);\n }\n\n /**\n * Build the list of better-auth plugins based on AuthPluginConfig flags.\n *\n * Each plugin that introduces its own database tables is configured with\n * a `schema` option containing the appropriate snake_case field mappings,\n * so that `createAdapterFactory` transforms them automatically.\n */\n private buildPluginList(): any[] {\n const pluginConfig = this.config.plugins;\n const plugins: any[] = [];\n\n if (pluginConfig?.organization) {\n plugins.push(organization({\n schema: buildOrganizationPluginSchema(),\n }));\n }\n\n if (pluginConfig?.twoFactor) {\n plugins.push(twoFactor({\n schema: buildTwoFactorPluginSchema(),\n }));\n }\n\n if (pluginConfig?.magicLink) {\n // magic-link reuses the `verification` table — no extra schema mapping needed.\n // The sendMagicLink callback must be provided by the application at a higher level.\n // Here we provide a no-op default that logs a warning; real applications should\n // override this via AuthManagerOptions or a config extension point.\n plugins.push(magicLink({\n sendMagicLink: async ({ email, url }) => {\n console.warn(\n `[AuthManager] Magic-link requested for ${email} but no sendMagicLink handler configured. URL: ${url}`,\n );\n },\n }));\n }\n\n return plugins;\n }\n\n /**\n * Create database configuration using ObjectQL adapter\n *\n * better-auth resolves the `database` option as follows:\n * - `undefined` → in-memory adapter\n * - `typeof fn === \"function\"` → treated as `DBAdapterInstance`, called with `(options)`\n * - otherwise → forwarded to Kysely adapter factory (pool/dialect)\n *\n * A raw `CustomAdapter` object would fall into the third branch and fail\n * silently. We therefore wrap the ObjectQL adapter in a factory function\n * so it is correctly recognised as a `DBAdapterInstance`.\n */\n private createDatabaseConfig(): any {\n // Use ObjectQL adapter factory if dataEngine is provided\n if (this.config.dataEngine) {\n // createObjectQLAdapterFactory returns an AdapterFactory\n // (options => DBAdapter) which better-auth invokes via getBaseAdapter().\n // The factory is created by better-auth's createAdapterFactory and\n // automatically applies modelName/fields transformations declared in\n // the betterAuth config above.\n return createObjectQLAdapterFactory(this.config.dataEngine);\n }\n\n // Fallback warning if no dataEngine is provided\n console.warn(\n '⚠️ WARNING: No dataEngine provided to AuthManager! ' +\n 'Using in-memory storage. This is NOT suitable for production. ' +\n 'Please provide a dataEngine instance (e.g., ObjectQL) in AuthManagerOptions.'\n );\n\n // Return a minimal in-memory configuration as fallback\n // This allows the system to work in development/testing without a real database\n return undefined; // better-auth will use its default in-memory adapter\n }\n\n /**\n * Generate a secure secret if not provided\n */\n private generateSecret(): string {\n const envSecret = process.env.AUTH_SECRET;\n\n if (!envSecret) {\n // In production, a secret MUST be provided\n // For development/testing, we'll use a fallback but warn about it\n const fallbackSecret = 'dev-secret-' + Date.now();\n\n console.warn(\n '⚠️ WARNING: No AUTH_SECRET environment variable set! ' +\n 'Using a temporary development secret. ' +\n 'This is NOT secure for production use. ' +\n 'Please set AUTH_SECRET in your environment variables.'\n );\n\n return fallbackSecret;\n }\n\n return envSecret;\n }\n\n /**\n * Update the base URL at runtime.\n *\n * This **must** be called before the first request triggers lazy\n * initialisation of the better-auth instance — typically from a\n * `kernel:ready` hook where the actual server port is known.\n *\n * If the auth instance has already been created this is a no-op and\n * a warning is emitted.\n */\n setRuntimeBaseUrl(url: string): void {\n if (this.auth) {\n console.warn(\n '[AuthManager] setRuntimeBaseUrl() called after the auth instance was already created — ignoring. ' +\n 'Ensure this method is called before the first request.',\n );\n return;\n }\n this.config = { ...this.config, baseUrl: url };\n }\n\n /**\n * Get the underlying better-auth instance\n * Useful for advanced use cases\n */\n getAuthInstance(): Auth {\n return this.getOrCreateAuth();\n }\n\n /**\n * Handle an authentication request\n * Forwards the request directly to better-auth's universal handler\n *\n * better-auth catches internal errors (database / adapter / ORM) and\n * returns a 500 Response instead of throwing. We therefore inspect the\n * response status and log server errors so they are not silently swallowed.\n *\n * @param request - Web standard Request object\n * @returns Web standard Response object\n */\n async handleRequest(request: Request): Promise {\n const auth = this.getOrCreateAuth();\n const response = await auth.handler(request);\n\n if (response.status >= 500) {\n try {\n const body = await response.clone().text();\n console.error('[AuthManager] better-auth returned error:', response.status, body);\n } catch {\n console.error('[AuthManager] better-auth returned error:', response.status, '(unable to read body)');\n }\n }\n\n return response;\n }\n\n /**\n * Get the better-auth API for programmatic access\n * Use this for server-side operations (e.g., creating users, checking sessions)\n */\n get api() {\n return this.getOrCreateAuth().api;\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IDataEngine } from '@objectstack/core';\nimport { createAdapterFactory } from 'better-auth/adapters';\nimport type { CleanedWhere } from 'better-auth/adapters';\nimport { SystemObjectName } from '@objectstack/spec/system';\n\n/**\n * Mapping from better-auth model names to ObjectStack protocol object names.\n *\n * better-auth uses hardcoded model names ('user', 'session', 'account', 'verification')\n * while ObjectStack's protocol layer uses `sys_` prefixed names. This map bridges the two.\n */\nexport const AUTH_MODEL_TO_PROTOCOL: Record = {\n user: SystemObjectName.USER,\n session: SystemObjectName.SESSION,\n account: SystemObjectName.ACCOUNT,\n verification: SystemObjectName.VERIFICATION,\n};\n\n/**\n * Resolve a better-auth model name to the ObjectStack protocol object name.\n * Falls back to the original model name for custom / non-core models.\n */\nexport function resolveProtocolName(model: string): string {\n return AUTH_MODEL_TO_PROTOCOL[model] ?? model;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert better-auth where clause to ObjectQL query format.\n *\n * Field names in the incoming {@link CleanedWhere} are expected to already be\n * in snake_case (transformed by `createAdapterFactory`).\n */\nfunction convertWhere(where: CleanedWhere[]): Record {\n const filter: Record = {};\n\n for (const condition of where) {\n const fieldName = condition.field;\n\n if (condition.operator === 'eq') {\n filter[fieldName] = condition.value;\n } else if (condition.operator === 'ne') {\n filter[fieldName] = { $ne: condition.value };\n } else if (condition.operator === 'in') {\n filter[fieldName] = { $in: condition.value };\n } else if (condition.operator === 'gt') {\n filter[fieldName] = { $gt: condition.value };\n } else if (condition.operator === 'gte') {\n filter[fieldName] = { $gte: condition.value };\n } else if (condition.operator === 'lt') {\n filter[fieldName] = { $lt: condition.value };\n } else if (condition.operator === 'lte') {\n filter[fieldName] = { $lte: condition.value };\n } else if (condition.operator === 'contains') {\n filter[fieldName] = { $regex: condition.value };\n }\n }\n\n return filter;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create an ObjectQL adapter **factory** for better-auth.\n *\n * Uses better-auth's official `createAdapterFactory` so that model-name and\n * field-name transformations (declared via `modelName` / `fields` in the\n * betterAuth config) are applied **automatically** before any data reaches\n * ObjectQL. This eliminates the need for manual camelCase ↔ snake_case\n * conversion inside the adapter.\n *\n * The returned value is an `AdapterFactory` – a function of type\n * `(options: BetterAuthOptions) => DBAdapter` – which is the shape expected\n * by `betterAuth({ database: … })`.\n *\n * @param dataEngine - ObjectQL data engine instance\n * @returns better-auth AdapterFactory\n */\nexport function createObjectQLAdapterFactory(dataEngine: IDataEngine) {\n return createAdapterFactory({\n config: {\n adapterId: 'objectql',\n // ObjectQL natively supports these types — no extra conversion needed\n supportsBooleans: true,\n supportsDates: true,\n supportsJSON: true,\n },\n adapter: () => ({\n create: async >(\n { model, data, select: _select }: { model: string; data: T; select?: string[] },\n ): Promise => {\n const result = await dataEngine.insert(model, data);\n return result as T;\n },\n\n findOne: async (\n { model, where, select, join: _join }: { model: string; where: CleanedWhere[]; select?: string[]; join?: any },\n ): Promise => {\n const filter = convertWhere(where);\n\n const result = await dataEngine.findOne(model, { where: filter, fields: select });\n\n return result ? (result as T) : null;\n },\n\n findMany: async (\n { model, where, limit, offset, sortBy, join: _join }: {\n model: string; where?: CleanedWhere[]; limit: number;\n offset?: number; sortBy?: { field: string; direction: 'asc' | 'desc' }; join?: any;\n },\n ): Promise => {\n const filter = where ? convertWhere(where) : {};\n\n const orderBy = sortBy\n ? [{ field: sortBy.field, order: sortBy.direction as 'asc' | 'desc' }]\n : undefined;\n\n const results = await dataEngine.find(model, {\n where: filter,\n limit: limit || 100,\n offset,\n orderBy,\n });\n\n return results as T[];\n },\n\n count: async (\n { model, where }: { model: string; where?: CleanedWhere[] },\n ): Promise => {\n const filter = where ? convertWhere(where) : {};\n return await dataEngine.count(model, { where: filter });\n },\n\n update: async (\n { model, where, update }: { model: string; where: CleanedWhere[]; update: T },\n ): Promise => {\n const filter = convertWhere(where);\n\n // ObjectQL requires an ID for updates – find the record first\n const record = await dataEngine.findOne(model, { where: filter });\n if (!record) return null;\n\n const result = await dataEngine.update(model, { ...(update as any), id: record.id });\n return result ? (result as T) : null;\n },\n\n updateMany: async (\n { model, where, update }: { model: string; where: CleanedWhere[]; update: Record },\n ): Promise => {\n const filter = convertWhere(where);\n\n // Sequential updates: ObjectQL requires an ID per update\n const records = await dataEngine.find(model, { where: filter });\n for (const record of records) {\n await dataEngine.update(model, { ...update, id: record.id });\n }\n return records.length;\n },\n\n delete: async (\n { model, where }: { model: string; where: CleanedWhere[] },\n ): Promise => {\n const filter = convertWhere(where);\n\n const record = await dataEngine.findOne(model, { where: filter });\n if (!record) return;\n\n await dataEngine.delete(model, { where: { id: record.id } });\n },\n\n deleteMany: async (\n { model, where }: { model: string; where: CleanedWhere[] },\n ): Promise => {\n const filter = convertWhere(where);\n\n const records = await dataEngine.find(model, { where: filter });\n for (const record of records) {\n await dataEngine.delete(model, { where: { id: record.id } });\n }\n return records.length;\n },\n }),\n });\n}\n\n// ---------------------------------------------------------------------------\n// Legacy adapter (kept for backward compatibility)\n// ---------------------------------------------------------------------------\n\n/**\n * Create a raw ObjectQL adapter for better-auth (without factory wrapping).\n *\n * > **Prefer {@link createObjectQLAdapterFactory}** for production use.\n * > The factory version leverages `createAdapterFactory` and automatically\n * > handles model-name + field-name transformations declared in the\n * > better-auth config.\n *\n * This function is retained for direct / low-level usage where callers\n * manage field-name conversion themselves.\n *\n * @param dataEngine - ObjectQL data engine instance\n * @returns better-auth CustomAdapter (raw, without factory wrapping)\n */\nexport function createObjectQLAdapter(dataEngine: IDataEngine) {\n return {\n create: async >({ model, data, select: _select }: { model: string; data: T; select?: string[] }): Promise => {\n const objectName = resolveProtocolName(model);\n const result = await dataEngine.insert(objectName, data);\n return result as T;\n },\n\n findOne: async ({ model, where, select, join: _join }: { model: string; where: CleanedWhere[]; select?: string[]; join?: any }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const result = await dataEngine.findOne(objectName, { where: filter, fields: select });\n return result ? result as T : null;\n },\n\n findMany: async ({ model, where, limit, offset, sortBy, join: _join }: { model: string; where?: CleanedWhere[]; limit: number; offset?: number; sortBy?: { field: string; direction: 'asc' | 'desc' }; join?: any }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = where ? convertWhere(where) : {};\n const orderBy = sortBy ? [{ field: sortBy.field, order: sortBy.direction as 'asc' | 'desc' }] : undefined;\n const results = await dataEngine.find(objectName, { where: filter, limit: limit || 100, offset, orderBy });\n return results as T[];\n },\n\n count: async ({ model, where }: { model: string; where?: CleanedWhere[] }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = where ? convertWhere(where) : {};\n return await dataEngine.count(objectName, { where: filter });\n },\n\n update: async ({ model, where, update }: { model: string; where: CleanedWhere[]; update: Record }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const record = await dataEngine.findOne(objectName, { where: filter });\n if (!record) return null;\n const result = await dataEngine.update(objectName, { ...update, id: record.id });\n return result ? result as T : null;\n },\n\n updateMany: async ({ model, where, update }: { model: string; where: CleanedWhere[]; update: Record }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const records = await dataEngine.find(objectName, { where: filter });\n for (const record of records) {\n await dataEngine.update(objectName, { ...update, id: record.id });\n }\n return records.length;\n },\n\n delete: async ({ model, where }: { model: string; where: CleanedWhere[] }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const record = await dataEngine.findOne(objectName, { where: filter });\n if (!record) return;\n await dataEngine.delete(objectName, { where: { id: record.id } });\n },\n\n deleteMany: async ({ model, where }: { model: string; where: CleanedWhere[] }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const records = await dataEngine.find(objectName, { where: filter });\n for (const record of records) {\n await dataEngine.delete(objectName, { where: { id: record.id } });\n }\n return records.length;\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { SystemObjectName } from '@objectstack/spec/system';\n\n/**\n * better-auth ↔ ObjectStack Schema Mapping\n *\n * better-auth uses camelCase field names internally (e.g. `emailVerified`, `userId`)\n * while ObjectStack's protocol layer uses snake_case (e.g. `email_verified`, `user_id`).\n *\n * These constants declare the `modelName` and `fields` mappings for each core auth\n * model, following better-auth's official schema customisation API\n * ({@link https://www.better-auth.com/docs/concepts/database}).\n *\n * The mappings serve two purposes:\n * 1. `modelName` — maps the default model name to the ObjectStack protocol name\n * (e.g. `user` → `sys_user`).\n * 2. `fields` — maps camelCase field names to their snake_case database column\n * equivalents. Only fields whose names differ need to be listed; fields that\n * are already identical (e.g. `email`, `name`, `token`) are omitted.\n *\n * These mappings are consumed by:\n * - The `betterAuth()` configuration in {@link AuthManager} so that\n * `getAuthTables()` builds the correct schema.\n * - The ObjectQL adapter factory (via `createAdapterFactory`) which uses the\n * schema to transform data and where-clauses automatically.\n */\n\n// ---------------------------------------------------------------------------\n// User model\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth `user` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | emailVerified | email_verified |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_USER_CONFIG = {\n modelName: SystemObjectName.USER, // 'sys_user'\n fields: {\n emailVerified: 'email_verified',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Session model\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth `session` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | userId | user_id |\n * | expiresAt | expires_at |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n * | ipAddress | ip_address |\n * | userAgent | user_agent |\n */\nexport const AUTH_SESSION_CONFIG = {\n modelName: SystemObjectName.SESSION, // 'sys_session'\n fields: {\n userId: 'user_id',\n expiresAt: 'expires_at',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n ipAddress: 'ip_address',\n userAgent: 'user_agent',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Account model\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth `account` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:--------------------------|:-------------------------------|\n * | userId | user_id |\n * | providerId | provider_id |\n * | accountId | account_id |\n * | accessToken | access_token |\n * | refreshToken | refresh_token |\n * | idToken | id_token |\n * | accessTokenExpiresAt | access_token_expires_at |\n * | refreshTokenExpiresAt | refresh_token_expires_at |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_ACCOUNT_CONFIG = {\n modelName: SystemObjectName.ACCOUNT, // 'sys_account'\n fields: {\n userId: 'user_id',\n providerId: 'provider_id',\n accountId: 'account_id',\n accessToken: 'access_token',\n refreshToken: 'refresh_token',\n idToken: 'id_token',\n accessTokenExpiresAt: 'access_token_expires_at',\n refreshTokenExpiresAt: 'refresh_token_expires_at',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Verification model\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth `verification` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | expiresAt | expires_at |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_VERIFICATION_CONFIG = {\n modelName: SystemObjectName.VERIFICATION, // 'sys_verification'\n fields: {\n expiresAt: 'expires_at',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ===========================================================================\n// Plugin Table Mappings\n// ===========================================================================\n//\n// better-auth plugins (organization, two-factor, etc.) introduce additional\n// tables with their own camelCase field names. The mappings below are passed\n// to the plugin's `schema` option so that `createAdapterFactory` transforms\n// them to snake_case automatically, just like the core models above.\n// ===========================================================================\n\n// ---------------------------------------------------------------------------\n// Organization plugin – organization table\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `organization` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_ORGANIZATION_SCHEMA = {\n modelName: SystemObjectName.ORGANIZATION, // 'sys_organization'\n fields: {\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – member table\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `member` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | organizationId | organization_id |\n * | userId | user_id |\n * | createdAt | created_at |\n */\nexport const AUTH_MEMBER_SCHEMA = {\n modelName: SystemObjectName.MEMBER, // 'sys_member'\n fields: {\n organizationId: 'organization_id',\n userId: 'user_id',\n createdAt: 'created_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – invitation table\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `invitation` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | organizationId | organization_id |\n * | inviterId | inviter_id |\n * | expiresAt | expires_at |\n * | createdAt | created_at |\n * | teamId | team_id |\n */\nexport const AUTH_INVITATION_SCHEMA = {\n modelName: SystemObjectName.INVITATION, // 'sys_invitation'\n fields: {\n organizationId: 'organization_id',\n inviterId: 'inviter_id',\n expiresAt: 'expires_at',\n createdAt: 'created_at',\n teamId: 'team_id',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – session additional fields\n// ---------------------------------------------------------------------------\n\n/**\n * Organization plugin adds `activeOrganizationId` (and optionally\n * `activeTeamId`) to the session model. These field mappings are\n * injected via the organization plugin's `schema.session.fields`.\n */\nexport const AUTH_ORG_SESSION_FIELDS = {\n activeOrganizationId: 'active_organization_id',\n activeTeamId: 'active_team_id',\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – team table (optional, when teams enabled)\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `team` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | organizationId | organization_id |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_TEAM_SCHEMA = {\n modelName: SystemObjectName.TEAM, // 'sys_team'\n fields: {\n organizationId: 'organization_id',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – teamMember table (optional, when teams enabled)\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `teamMember` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | teamId | team_id |\n * | userId | user_id |\n * | createdAt | created_at |\n */\nexport const AUTH_TEAM_MEMBER_SCHEMA = {\n modelName: SystemObjectName.TEAM_MEMBER, // 'sys_team_member'\n fields: {\n teamId: 'team_id',\n userId: 'user_id',\n createdAt: 'created_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Two-Factor plugin – twoFactor table\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Two-Factor plugin `twoFactor` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | backupCodes | backup_codes |\n * | userId | user_id |\n */\nexport const AUTH_TWO_FACTOR_SCHEMA = {\n modelName: SystemObjectName.TWO_FACTOR, // 'sys_two_factor'\n fields: {\n backupCodes: 'backup_codes',\n userId: 'user_id',\n },\n} as const;\n\n/**\n * Two-Factor plugin adds a `twoFactorEnabled` field to the user model.\n */\nexport const AUTH_TWO_FACTOR_USER_FIELDS = {\n twoFactorEnabled: 'two_factor_enabled',\n} as const;\n\n/**\n * Builds the `schema` option for better-auth's `twoFactor()` plugin.\n *\n * @returns An object suitable for `twoFactor({ schema: … })`\n */\nexport function buildTwoFactorPluginSchema() {\n return {\n twoFactor: AUTH_TWO_FACTOR_SCHEMA,\n user: {\n fields: AUTH_TWO_FACTOR_USER_FIELDS,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helper: build organization plugin schema option\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the `schema` option for better-auth's `organization()` plugin.\n *\n * The organization plugin accepts a `schema` sub-option that allows\n * customising model names and field names for each table it manages.\n * This helper assembles the correct snake_case mappings from the\n * individual `AUTH_*_SCHEMA` constants above.\n *\n * @returns An object suitable for `organization({ schema: … })`\n */\nexport function buildOrganizationPluginSchema() {\n return {\n organization: AUTH_ORGANIZATION_SCHEMA,\n member: AUTH_MEMBER_SCHEMA,\n invitation: AUTH_INVITATION_SCHEMA,\n team: AUTH_TEAM_SCHEMA,\n teamMember: AUTH_TEAM_MEMBER_SCHEMA,\n session: {\n fields: AUTH_ORG_SESSION_FIELDS,\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_user — System User Object\n *\n * Canonical user identity record for the ObjectStack platform.\n * Backed by better-auth's `user` model with ObjectStack field conventions.\n *\n * @namespace sys\n */\nexport const SysUser = ObjectSchema.create({\n namespace: 'sys',\n name: 'user',\n label: 'User',\n pluralLabel: 'Users',\n icon: 'user',\n isSystem: true,\n description: 'User accounts for authentication',\n titleFormat: '{name} ({email})',\n compactLayout: ['name', 'email', 'email_verified'],\n \n fields: {\n id: Field.text({\n label: 'User ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n email: Field.email({\n label: 'Email',\n required: true,\n searchable: true,\n }),\n \n email_verified: Field.boolean({\n label: 'Email Verified',\n defaultValue: false,\n }),\n \n name: Field.text({\n label: 'Name',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n image: Field.url({\n label: 'Profile Image',\n required: false,\n }),\n },\n \n indexes: [\n { fields: ['email'], unique: true },\n { fields: ['created_at'], unique: false },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: true,\n mru: true,\n },\n \n validations: [\n {\n name: 'email_unique',\n type: 'unique',\n severity: 'error',\n message: 'Email must be unique',\n fields: ['email'],\n caseSensitive: false,\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_session — System Session Object\n *\n * Active user session record for the ObjectStack platform.\n * Backed by better-auth's `session` model with ObjectStack field conventions.\n *\n * @namespace sys\n */\nexport const SysSession = ObjectSchema.create({\n namespace: 'sys',\n name: 'session',\n label: 'Session',\n pluralLabel: 'Sessions',\n icon: 'key',\n isSystem: true,\n description: 'Active user sessions',\n titleFormat: 'Session {token}',\n compactLayout: ['user_id', 'expires_at', 'ip_address'],\n \n fields: {\n id: Field.text({\n label: 'Session ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n }),\n \n expires_at: Field.datetime({\n label: 'Expires At',\n required: true,\n }),\n \n token: Field.text({\n label: 'Session Token',\n required: true,\n }),\n \n ip_address: Field.text({\n label: 'IP Address',\n required: false,\n maxLength: 45, // Support IPv6\n }),\n \n user_agent: Field.textarea({\n label: 'User Agent',\n required: false,\n }),\n },\n \n indexes: [\n { fields: ['token'], unique: true },\n { fields: ['user_id'], unique: false },\n { fields: ['expires_at'], unique: false },\n ],\n \n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_account — System Account Object\n *\n * OAuth / credential provider account record.\n * Backed by better-auth's `account` model with ObjectStack field conventions.\n *\n * @namespace sys\n */\nexport const SysAccount = ObjectSchema.create({\n namespace: 'sys',\n name: 'account',\n label: 'Account',\n pluralLabel: 'Accounts',\n icon: 'link',\n isSystem: true,\n description: 'OAuth and authentication provider accounts',\n titleFormat: '{provider_id} - {account_id}',\n compactLayout: ['provider_id', 'user_id', 'account_id'],\n \n fields: {\n id: Field.text({\n label: 'Account ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n provider_id: Field.text({\n label: 'Provider ID',\n required: true,\n description: 'OAuth provider identifier (google, github, etc.)',\n }),\n \n account_id: Field.text({\n label: 'Provider Account ID',\n required: true,\n description: \"User's ID in the provider's system\",\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n description: 'Link to user table',\n }),\n \n access_token: Field.textarea({\n label: 'Access Token',\n required: false,\n }),\n \n refresh_token: Field.textarea({\n label: 'Refresh Token',\n required: false,\n }),\n \n id_token: Field.textarea({\n label: 'ID Token',\n required: false,\n }),\n \n access_token_expires_at: Field.datetime({\n label: 'Access Token Expires At',\n required: false,\n }),\n \n refresh_token_expires_at: Field.datetime({\n label: 'Refresh Token Expires At',\n required: false,\n }),\n \n scope: Field.text({\n label: 'OAuth Scope',\n required: false,\n }),\n \n password: Field.text({\n label: 'Password Hash',\n required: false,\n description: 'Hashed password for email/password provider',\n }),\n },\n \n indexes: [\n { fields: ['user_id'], unique: false },\n { fields: ['provider_id', 'account_id'], unique: true },\n ],\n \n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: true,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_verification — System Verification Object\n *\n * Email and phone verification token record.\n * Backed by better-auth's `verification` model with ObjectStack field conventions.\n *\n * @namespace sys\n */\nexport const SysVerification = ObjectSchema.create({\n namespace: 'sys',\n name: 'verification',\n label: 'Verification',\n pluralLabel: 'Verifications',\n icon: 'shield-check',\n isSystem: true,\n description: 'Email and phone verification tokens',\n titleFormat: 'Verification for {identifier}',\n compactLayout: ['identifier', 'expires_at', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Verification ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n value: Field.text({\n label: 'Verification Token',\n required: true,\n description: 'Token or code for verification',\n }),\n \n expires_at: Field.datetime({\n label: 'Expires At',\n required: true,\n }),\n \n identifier: Field.text({\n label: 'Identifier',\n required: true,\n description: 'Email address or phone number',\n }),\n },\n \n indexes: [\n { fields: ['value'], unique: true },\n { fields: ['identifier'], unique: false },\n { fields: ['expires_at'], unique: false },\n ],\n \n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'create', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_organization — System Organization Object\n *\n * Multi-organization support for the ObjectStack platform.\n * Backed by better-auth's organization plugin.\n *\n * @namespace sys\n */\nexport const SysOrganization = ObjectSchema.create({\n namespace: 'sys',\n name: 'organization',\n label: 'Organization',\n pluralLabel: 'Organizations',\n icon: 'building-2',\n isSystem: true,\n description: 'Organizations for multi-tenant grouping',\n titleFormat: '{name}',\n compactLayout: ['name', 'slug', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Organization ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n name: Field.text({\n label: 'Name',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n slug: Field.text({\n label: 'Slug',\n required: false,\n maxLength: 255,\n description: 'URL-friendly identifier',\n }),\n \n logo: Field.url({\n label: 'Logo',\n required: false,\n }),\n \n metadata: Field.textarea({\n label: 'Metadata',\n required: false,\n description: 'JSON-serialized organization metadata',\n }),\n },\n \n indexes: [\n { fields: ['slug'], unique: true },\n { fields: ['name'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: true,\n mru: true,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_member — System Member Object\n *\n * Organization membership linking users to organizations with roles.\n * Backed by better-auth's organization plugin.\n *\n * @namespace sys\n */\nexport const SysMember = ObjectSchema.create({\n namespace: 'sys',\n name: 'member',\n label: 'Member',\n pluralLabel: 'Members',\n icon: 'user-check',\n isSystem: true,\n description: 'Organization membership records',\n titleFormat: '{user_id} in {organization_id}',\n compactLayout: ['user_id', 'organization_id', 'role'],\n \n fields: {\n id: Field.text({\n label: 'Member ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n organization_id: Field.text({\n label: 'Organization ID',\n required: true,\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n }),\n \n role: Field.text({\n label: 'Role',\n required: false,\n description: 'Member role within the organization (e.g. admin, member)',\n maxLength: 100,\n }),\n },\n \n indexes: [\n { fields: ['organization_id', 'user_id'], unique: true },\n { fields: ['user_id'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_invitation — System Invitation Object\n *\n * Organization invitation tokens for inviting users.\n * Backed by better-auth's organization plugin.\n *\n * @namespace sys\n */\nexport const SysInvitation = ObjectSchema.create({\n namespace: 'sys',\n name: 'invitation',\n label: 'Invitation',\n pluralLabel: 'Invitations',\n icon: 'mail',\n isSystem: true,\n description: 'Organization invitations for user onboarding',\n titleFormat: 'Invitation to {organization_id}',\n compactLayout: ['email', 'organization_id', 'status'],\n \n fields: {\n id: Field.text({\n label: 'Invitation ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n organization_id: Field.text({\n label: 'Organization ID',\n required: true,\n }),\n \n email: Field.email({\n label: 'Email',\n required: true,\n description: 'Email address of the invited user',\n }),\n \n role: Field.text({\n label: 'Role',\n required: false,\n maxLength: 100,\n description: 'Role to assign upon acceptance',\n }),\n \n status: Field.select(['pending', 'accepted', 'rejected', 'expired', 'canceled'], {\n label: 'Status',\n required: true,\n defaultValue: 'pending',\n }),\n \n inviter_id: Field.text({\n label: 'Inviter ID',\n required: true,\n description: 'User ID of the person who sent the invitation',\n }),\n \n expires_at: Field.datetime({\n label: 'Expires At',\n required: true,\n }),\n \n team_id: Field.text({\n label: 'Team ID',\n required: false,\n description: 'Optional team to assign upon acceptance',\n }),\n },\n \n indexes: [\n { fields: ['organization_id'] },\n { fields: ['email'] },\n { fields: ['expires_at'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_team — System Team Object\n *\n * Teams within an organization for fine-grained grouping.\n * Backed by better-auth's organization plugin (teams feature).\n *\n * @namespace sys\n */\nexport const SysTeam = ObjectSchema.create({\n namespace: 'sys',\n name: 'team',\n label: 'Team',\n pluralLabel: 'Teams',\n icon: 'users',\n isSystem: true,\n description: 'Teams within organizations for fine-grained grouping',\n titleFormat: '{name}',\n compactLayout: ['name', 'organization_id', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Team ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n name: Field.text({\n label: 'Name',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n organization_id: Field.text({\n label: 'Organization ID',\n required: true,\n }),\n },\n \n indexes: [\n { fields: ['organization_id'] },\n { fields: ['name', 'organization_id'], unique: true },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: true,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_team_member — System Team Member Object\n *\n * Links users to teams within organizations.\n * Backed by better-auth's organization plugin (teams feature).\n *\n * @namespace sys\n */\nexport const SysTeamMember = ObjectSchema.create({\n namespace: 'sys',\n name: 'team_member',\n label: 'Team Member',\n pluralLabel: 'Team Members',\n icon: 'user-plus',\n isSystem: true,\n description: 'Team membership records linking users to teams',\n titleFormat: '{user_id} in {team_id}',\n compactLayout: ['user_id', 'team_id', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Team Member ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n team_id: Field.text({\n label: 'Team ID',\n required: true,\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n }),\n },\n \n indexes: [\n { fields: ['team_id', 'user_id'], unique: true },\n { fields: ['user_id'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_api_key — System API Key Object\n *\n * API keys for programmatic/machine access to the platform.\n *\n * @namespace sys\n */\nexport const SysApiKey = ObjectSchema.create({\n namespace: 'sys',\n name: 'api_key',\n label: 'API Key',\n pluralLabel: 'API Keys',\n icon: 'key-round',\n isSystem: true,\n description: 'API keys for programmatic access',\n titleFormat: '{name}',\n compactLayout: ['name', 'user_id', 'expires_at'],\n \n fields: {\n id: Field.text({\n label: 'API Key ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n name: Field.text({\n label: 'Name',\n required: true,\n maxLength: 255,\n description: 'Human-readable label for the API key',\n }),\n \n key: Field.text({\n label: 'Key',\n required: true,\n description: 'Hashed API key value',\n }),\n \n prefix: Field.text({\n label: 'Prefix',\n required: false,\n maxLength: 16,\n description: 'Visible prefix for identifying the key (e.g., \"osk_\")',\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n description: 'Owner user of this API key',\n }),\n \n scopes: Field.textarea({\n label: 'Scopes',\n required: false,\n description: 'JSON array of permission scopes',\n }),\n \n expires_at: Field.datetime({\n label: 'Expires At',\n required: false,\n }),\n \n last_used_at: Field.datetime({\n label: 'Last Used At',\n required: false,\n }),\n \n revoked: Field.boolean({\n label: 'Revoked',\n defaultValue: false,\n }),\n },\n \n indexes: [\n { fields: ['key'], unique: true },\n { fields: ['user_id'] },\n { fields: ['prefix'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_two_factor — System Two-Factor Object\n *\n * Two-factor authentication credentials (TOTP, backup codes).\n * Backed by better-auth's two-factor plugin.\n *\n * @namespace sys\n */\nexport const SysTwoFactor = ObjectSchema.create({\n namespace: 'sys',\n name: 'two_factor',\n label: 'Two Factor',\n pluralLabel: 'Two Factor Credentials',\n icon: 'smartphone',\n isSystem: true,\n description: 'Two-factor authentication credentials',\n titleFormat: 'Two-factor for {user_id}',\n compactLayout: ['user_id', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Two Factor ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n }),\n \n secret: Field.text({\n label: 'Secret',\n required: true,\n description: 'TOTP secret key',\n }),\n \n backup_codes: Field.textarea({\n label: 'Backup Codes',\n required: false,\n description: 'JSON-serialized backup recovery codes',\n }),\n },\n \n indexes: [\n { fields: ['user_id'], unique: true },\n ],\n \n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_user_preference — System User Preference Object\n *\n * Per-user key-value preferences for storing UI state, settings, and personalization.\n * Supports the User Preferences layer in the Config Resolution hierarchy\n * (Runtime > User Preferences > Tenant > Env).\n *\n * Common use cases:\n * - UI preferences: theme, locale, timezone, sidebar state\n * - Feature flags: plugin.ai.auto_save, plugin.dev.debug_mode\n * - User-specific settings: default_view, notifications_enabled\n *\n * @namespace sys\n */\nexport const SysUserPreference = ObjectSchema.create({\n namespace: 'sys',\n name: 'user_preference',\n label: 'User Preference',\n pluralLabel: 'User Preferences',\n icon: 'settings',\n isSystem: true,\n description: 'Per-user key-value preferences (theme, locale, etc.)',\n titleFormat: '{key}',\n compactLayout: ['user_id', 'key'],\n\n fields: {\n id: Field.text({\n label: 'Preference ID',\n required: true,\n readonly: true,\n }),\n\n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n\n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n\n user_id: Field.text({\n label: 'User ID',\n required: true,\n maxLength: 255,\n description: 'Owner user of this preference',\n }),\n\n key: Field.text({\n label: 'Key',\n required: true,\n maxLength: 255,\n description: 'Preference key (e.g., theme, locale, plugin.ai.auto_save)',\n }),\n\n value: Field.json({\n label: 'Value',\n description: 'Preference value (any JSON-serializable type)',\n }),\n },\n\n indexes: [\n { fields: ['user_id', 'key'], unique: true },\n { fields: ['user_id'], unique: false },\n ],\n\n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext, IHttpServer } from '@objectstack/core';\nimport { AuthConfig } from '@objectstack/spec/system';\nimport { AuthManager } from './auth-manager.js';\nimport {\n SysUser, SysSession, SysAccount, SysVerification,\n SysOrganization, SysMember, SysInvitation,\n SysTeam, SysTeamMember,\n SysApiKey, SysTwoFactor, SysUserPreference,\n} from './objects/index.js';\n\n/**\n * Auth Plugin Options\n * Extends AuthConfig from spec with additional runtime options\n */\nexport interface AuthPluginOptions extends Partial {\n /**\n * Whether to automatically register auth routes\n * @default true\n */\n registerRoutes?: boolean;\n \n /**\n * Base path for auth routes\n * @default '/api/v1/auth'\n */\n basePath?: string;\n}\n\n/**\n * Authentication Plugin\n * \n * Provides authentication and identity services for ObjectStack applications.\n * \n * **Dual-Mode Operation:**\n * - **Server mode** (HonoServerPlugin active): Registers HTTP routes at basePath,\n * forwarding all auth requests to better-auth's universal handler.\n * - **MSW/Mock mode** (no HTTP server): Gracefully skips route registration but\n * still registers the `auth` service, allowing HttpDispatcher.handleAuth() to\n * simulate auth flows (sign-up, sign-in, etc.) for development and testing.\n * \n * Features:\n * - Session management\n * - User registration/login\n * - OAuth providers (Google, GitHub, etc.)\n * - Organization/team support\n * - 2FA, passkeys, magic links\n * \n * This plugin registers:\n * - `auth` service (auth manager instance) — always\n * - `app.com.objectstack.system` service (system object definitions) — always\n * - HTTP routes for authentication endpoints — only when HTTP server is available\n * \n * Integrates with better-auth library to provide comprehensive\n * authentication capabilities including email/password, OAuth, 2FA,\n * magic links, passkeys, and organization support.\n */\nexport class AuthPlugin implements Plugin {\n name = 'com.objectstack.auth';\n type = 'standard';\n version = '1.0.0';\n dependencies: string[] = ['com.objectstack.engine.objectql']; // manifest service required\n \n private options: AuthPluginOptions;\n private authManager: AuthManager | null = null;\n\n constructor(options: AuthPluginOptions = {}) {\n this.options = {\n registerRoutes: true,\n basePath: '/api/v1/auth',\n ...options\n };\n }\n\n async init(ctx: PluginContext): Promise {\n ctx.logger.info('Initializing Auth Plugin...');\n\n // Validate required configuration\n if (!this.options.secret) {\n throw new Error('AuthPlugin: secret is required');\n }\n\n // Get data engine service for database operations\n const dataEngine = ctx.getService('data');\n if (!dataEngine) {\n ctx.logger.warn('No data engine service found - auth will use in-memory storage');\n }\n\n // Initialize auth manager with data engine\n this.authManager = new AuthManager({\n ...this.options,\n dataEngine,\n });\n\n // Register auth service\n ctx.registerService('auth', this.authManager);\n\n // Register system objects via the manifest service.\n ctx.getService<{ register(m: any): void }>('manifest').register({\n id: 'com.objectstack.system',\n name: 'System',\n version: '1.0.0',\n type: 'plugin',\n namespace: 'sys',\n objects: [\n SysUser, SysSession, SysAccount, SysVerification,\n SysOrganization, SysMember, SysInvitation,\n SysTeam, SysTeamMember,\n SysApiKey, SysTwoFactor, SysUserPreference,\n ],\n });\n\n // Contribute navigation items to the Setup App (if SetupPlugin is loaded).\n // Uses try/catch so AuthPlugin works independently of SetupPlugin.\n try {\n const setupNav = ctx.getService<{ contribute(c: any): void }>('setupNav');\n if (setupNav) {\n setupNav.contribute({\n areaId: 'area_administration',\n items: [\n { id: 'nav_users', type: 'object', label: 'Users', objectName: 'user', icon: 'users', order: 10 },\n { id: 'nav_organizations', type: 'object', label: 'Organizations', objectName: 'organization', icon: 'building-2', order: 20 },\n { id: 'nav_teams', type: 'object', label: 'Teams', objectName: 'team', icon: 'users-round', order: 30 },\n { id: 'nav_api_keys', type: 'object', label: 'API Keys', objectName: 'api_key', icon: 'key', order: 40 },\n { id: 'nav_sessions', type: 'object', label: 'Sessions', objectName: 'session', icon: 'monitor', order: 50 },\n ],\n });\n ctx.logger.info('Auth navigation items contributed to Setup App');\n }\n } catch {\n // SetupPlugin not loaded — skip silently\n }\n\n ctx.logger.info('Auth Plugin initialized successfully');\n }\n\n async start(ctx: PluginContext): Promise {\n ctx.logger.info('Starting Auth Plugin...');\n\n if (!this.authManager) {\n throw new Error('Auth manager not initialized');\n }\n\n // Defer HTTP route registration to kernel:ready hook.\n // This ensures all plugins (including HonoServerPlugin) have completed\n // their init and start phases before we attempt to look up the\n // http-server service — making AuthPlugin resilient to plugin\n // loading order.\n if (this.options.registerRoutes) {\n ctx.hook('kernel:ready', async () => {\n let httpServer: IHttpServer | null = null;\n try {\n httpServer = ctx.getService('http-server');\n } catch {\n // Service not found — expected in MSW/mock mode\n }\n\n if (httpServer) {\n // Auto-detect the actual server URL when no explicit baseUrl was\n // configured, or when the configured baseUrl uses a different port\n // than the running server (e.g. port 3000 configured but 3002 bound).\n // getPort() is optional on IHttpServer; duck-type check for it.\n const serverWithPort = httpServer as IHttpServer & { getPort?: () => number };\n if (this.authManager && typeof serverWithPort.getPort === 'function') {\n const actualPort = serverWithPort.getPort();\n if (actualPort) {\n const configuredUrl = this.options.baseUrl || 'http://localhost:3000';\n const configuredOrigin = new URL(configuredUrl).origin;\n const actualUrl = `http://localhost:${actualPort}`;\n\n if (configuredOrigin !== actualUrl) {\n this.authManager.setRuntimeBaseUrl(actualUrl);\n ctx.logger.info(\n `Auth baseUrl auto-updated to ${actualUrl} (configured: ${configuredUrl})`,\n );\n }\n }\n }\n\n // Route registration errors should propagate (server misconfiguration)\n this.registerAuthRoutes(httpServer, ctx);\n ctx.logger.info(`Auth routes registered at ${this.options.basePath}`);\n } else {\n ctx.logger.warn(\n 'No HTTP server available — auth routes not registered. ' +\n 'Auth service is still available for MSW/mock environments via HttpDispatcher.'\n );\n }\n });\n }\n\n // Register auth middleware on ObjectQL engine (if available)\n try {\n const ql = ctx.getService('objectql');\n if (ql && typeof ql.registerMiddleware === 'function') {\n ql.registerMiddleware(async (opCtx: any, next: () => Promise) => {\n // If context already has userId or isSystem, skip auth resolution\n if (opCtx.context?.userId || opCtx.context?.isSystem) {\n return next();\n }\n // Future: resolve session from AsyncLocalStorage or request context\n await next();\n });\n ctx.logger.info('Auth middleware registered on ObjectQL engine');\n }\n } catch (_e) {\n ctx.logger.debug('ObjectQL engine not available, skipping auth middleware registration');\n }\n\n ctx.logger.info('Auth Plugin started successfully');\n }\n\n async destroy(): Promise {\n // Cleanup if needed\n this.authManager = null;\n }\n\n /**\n * Register authentication routes with HTTP server\n * \n * Uses better-auth's universal handler for all authentication requests.\n * This forwards all requests under basePath to better-auth, which handles:\n * - Email/password authentication\n * - OAuth providers (Google, GitHub, etc.)\n * - Session management\n * - Password reset\n * - Email verification\n * - 2FA, passkeys, magic links (if enabled)\n */\n private registerAuthRoutes(httpServer: IHttpServer, ctx: PluginContext): void {\n if (!this.authManager) return;\n\n const basePath = this.options.basePath || '/api/v1/auth';\n\n // Get raw Hono app to use native wildcard routing\n // Type assertion is safe here because we explicitly require Hono server as a dependency\n if (!('getRawApp' in httpServer) || typeof (httpServer as any).getRawApp !== 'function') {\n ctx.logger.error('HTTP server does not support getRawApp() - wildcard routing requires Hono server');\n throw new Error(\n 'AuthPlugin requires HonoServerPlugin for wildcard routing support. ' +\n 'Please ensure HonoServerPlugin is loaded before AuthPlugin.'\n );\n }\n\n const rawApp = (httpServer as any).getRawApp();\n\n // Register wildcard route to forward all auth requests to better-auth.\n // better-auth is configured with basePath matching our route prefix, so we\n // forward the original request directly — no path rewriting needed.\n rawApp.all(`${basePath}/*`, async (c: any) => {\n try {\n // Forward the original request to better-auth handler\n const response = await this.authManager!.handleRequest(c.req.raw);\n\n // better-auth catches internal errors and returns error Responses\n // without throwing, so the catch block below would never trigger.\n // We proactively log server errors here for observability.\n if (response.status >= 500) {\n try {\n const body = await response.clone().text();\n ctx.logger.error('[AuthPlugin] better-auth returned server error', new Error(`HTTP ${response.status}: ${body}`));\n } catch {\n ctx.logger.error('[AuthPlugin] better-auth returned server error', new Error(`HTTP ${response.status}: (unable to read body)`));\n }\n }\n \n return response;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n ctx.logger.error('Auth request error:', err);\n \n // Return error response\n return new Response(\n JSON.stringify({\n success: false,\n error: err.message,\n }),\n {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n });\n\n ctx.logger.info(`Auth routes registered: All requests under ${basePath}/* forwarded to better-auth`);\n }\n}\n\n\n\n", "// src/server.ts\nimport { createServer as createServerHTTP } from \"http\";\n\n// src/listener.ts\nimport { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from \"http2\";\n\n// src/request.ts\nimport { Http2ServerRequest } from \"http2\";\nimport { Readable } from \"stream\";\nvar RequestError = class extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = \"RequestError\";\n }\n};\nvar toRequestError = (e) => {\n if (e instanceof RequestError) {\n return e;\n }\n return new RequestError(e.message, { cause: e });\n};\nvar GlobalRequest = global.Request;\nvar Request = class extends GlobalRequest {\n constructor(input, options) {\n if (typeof input === \"object\" && getRequestCache in input) {\n input = input[getRequestCache]();\n }\n if (typeof options?.body?.getReader !== \"undefined\") {\n ;\n options.duplex ??= \"half\";\n }\n super(input, options);\n }\n};\nvar newHeadersFromIncoming = (incoming) => {\n const headerRecord = [];\n const rawHeaders = incoming.rawHeaders;\n for (let i = 0; i < rawHeaders.length; i += 2) {\n const { [i]: key, [i + 1]: value } = rawHeaders;\n if (key.charCodeAt(0) !== /*:*/\n 58) {\n headerRecord.push([key, value]);\n }\n }\n return new Headers(headerRecord);\n};\nvar wrapBodyStream = Symbol(\"wrapBodyStream\");\nvar newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n const init = {\n method,\n headers,\n signal: abortController.signal\n };\n if (method === \"TRACE\") {\n init.method = \"GET\";\n const req = new Request(url, init);\n Object.defineProperty(req, \"method\", {\n get() {\n return \"TRACE\";\n }\n });\n return req;\n }\n if (!(method === \"GET\" || method === \"HEAD\")) {\n if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) {\n init.body = new ReadableStream({\n start(controller) {\n controller.enqueue(incoming.rawBody);\n controller.close();\n }\n });\n } else if (incoming[wrapBodyStream]) {\n let reader;\n init.body = new ReadableStream({\n async pull(controller) {\n try {\n reader ||= Readable.toWeb(incoming).getReader();\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n });\n } else {\n init.body = Readable.toWeb(incoming);\n }\n }\n return new Request(url, init);\n};\nvar getRequestCache = Symbol(\"getRequestCache\");\nvar requestCache = Symbol(\"requestCache\");\nvar incomingKey = Symbol(\"incomingKey\");\nvar urlKey = Symbol(\"urlKey\");\nvar headersKey = Symbol(\"headersKey\");\nvar abortControllerKey = Symbol(\"abortControllerKey\");\nvar getAbortController = Symbol(\"getAbortController\");\nvar requestPrototype = {\n get method() {\n return this[incomingKey].method || \"GET\";\n },\n get url() {\n return this[urlKey];\n },\n get headers() {\n return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n },\n [getAbortController]() {\n this[getRequestCache]();\n return this[abortControllerKey];\n },\n [getRequestCache]() {\n this[abortControllerKey] ||= new AbortController();\n return this[requestCache] ||= newRequestFromIncoming(\n this.method,\n this[urlKey],\n this.headers,\n this[incomingKey],\n this[abortControllerKey]\n );\n }\n};\n[\n \"body\",\n \"bodyUsed\",\n \"cache\",\n \"credentials\",\n \"destination\",\n \"integrity\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"keepalive\"\n].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n get() {\n return this[getRequestCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n value: function() {\n return this[getRequestCache]()[k]();\n }\n });\n});\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: function(depth, options, inspectFn) {\n const props = {\n method: this.method,\n url: this.url,\n headers: this.headers,\n nativeRequest: this[requestCache]\n };\n return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;\n }\n});\nObject.setPrototypeOf(requestPrototype, Request.prototype);\nvar newRequest = (incoming, defaultHostname) => {\n const req = Object.create(requestPrototype);\n req[incomingKey] = incoming;\n const incomingUrl = incoming.url || \"\";\n if (incomingUrl[0] !== \"/\" && // short-circuit for performance. most requests are relative URL.\n (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n if (incoming instanceof Http2ServerRequest) {\n throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n }\n try {\n const url2 = new URL(incomingUrl);\n req[urlKey] = url2.href;\n } catch (e) {\n throw new RequestError(\"Invalid absolute URL\", { cause: e });\n }\n return req;\n }\n const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n if (!host) {\n throw new RequestError(\"Missing host header\");\n }\n let scheme;\n if (incoming instanceof Http2ServerRequest) {\n scheme = incoming.scheme;\n if (!(scheme === \"http\" || scheme === \"https\")) {\n throw new RequestError(\"Unsupported scheme\");\n }\n } else {\n scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n }\n const url = new URL(`${scheme}://${host}${incomingUrl}`);\n if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\\d+$/, \"\")) {\n throw new RequestError(\"Invalid host header\");\n }\n req[urlKey] = url.href;\n return req;\n};\n\n// src/response.ts\nvar responseCache = Symbol(\"responseCache\");\nvar getResponseCache = Symbol(\"getResponseCache\");\nvar cacheKey = Symbol(\"cache\");\nvar GlobalResponse = global.Response;\nvar Response2 = class _Response {\n #body;\n #init;\n [getResponseCache]() {\n delete this[cacheKey];\n return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);\n }\n constructor(body, init) {\n let headers;\n this.#body = body;\n if (init instanceof _Response) {\n const cachedGlobalResponse = init[responseCache];\n if (cachedGlobalResponse) {\n this.#init = cachedGlobalResponse;\n this[getResponseCache]();\n return;\n } else {\n this.#init = init.#init;\n headers = new Headers(init.#init.headers);\n }\n } else {\n this.#init = init;\n }\n if (typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) {\n ;\n this[cacheKey] = [init?.status || 200, body, headers || init?.headers];\n }\n }\n get headers() {\n const cache = this[cacheKey];\n if (cache) {\n if (!(cache[2] instanceof Headers)) {\n cache[2] = new Headers(\n cache[2] || { \"content-type\": \"text/plain; charset=UTF-8\" }\n );\n }\n return cache[2];\n }\n return this[getResponseCache]().headers;\n }\n get status() {\n return this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n }\n get ok() {\n const status = this.status;\n return status >= 200 && status < 300;\n }\n};\n[\"body\", \"bodyUsed\", \"redirected\", \"statusText\", \"trailers\", \"type\", \"url\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n get() {\n return this[getResponseCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n value: function() {\n return this[getResponseCache]()[k]();\n }\n });\n});\nObject.defineProperty(Response2.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: function(depth, options, inspectFn) {\n const props = {\n status: this.status,\n headers: this.headers,\n ok: this.ok,\n nativeResponse: this[responseCache]\n };\n return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;\n }\n});\nObject.setPrototypeOf(Response2, GlobalResponse);\nObject.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);\n\n// src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n const cancel = (error) => {\n reader.cancel(error).catch(() => {\n });\n };\n writable.on(\"close\", cancel);\n writable.on(\"error\", cancel);\n (currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n return reader.closed.finally(() => {\n writable.off(\"close\", cancel);\n writable.off(\"error\", cancel);\n });\n function handleStreamError(error) {\n if (error) {\n writable.destroy(error);\n }\n }\n function onDrain() {\n reader.read().then(flow, handleStreamError);\n }\n function flow({ done, value }) {\n try {\n if (done) {\n writable.end();\n } else if (!writable.write(value)) {\n writable.once(\"drain\", onDrain);\n } else {\n return reader.read().then(flow, handleStreamError);\n }\n } catch (e) {\n handleStreamError(e);\n }\n }\n}\nfunction writeFromReadableStream(stream, writable) {\n if (stream.locked) {\n throw new TypeError(\"ReadableStream is locked.\");\n } else if (writable.destroyed) {\n return;\n }\n return writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nvar buildOutgoingHttpHeaders = (headers) => {\n const res = {};\n if (!(headers instanceof Headers)) {\n headers = new Headers(headers ?? void 0);\n }\n const cookies = [];\n for (const [k, v] of headers) {\n if (k === \"set-cookie\") {\n cookies.push(v);\n } else {\n res[k] = v;\n }\n }\n if (cookies.length > 0) {\n res[\"set-cookie\"] = cookies;\n }\n res[\"content-type\"] ??= \"text/plain; charset=UTF-8\";\n return res;\n};\n\n// src/utils/response/constants.ts\nvar X_ALREADY_SENT = \"x-hono-already-sent\";\n\n// src/globals.ts\nimport crypto from \"crypto\";\nif (typeof global.crypto === \"undefined\") {\n global.crypto = crypto;\n}\n\n// src/listener.ts\nvar outgoingEnded = Symbol(\"outgoingEnded\");\nvar incomingDraining = Symbol(\"incomingDraining\");\nvar DRAIN_TIMEOUT_MS = 500;\nvar MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nvar drainIncoming = (incoming) => {\n const incomingWithDrainState = incoming;\n if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {\n return;\n }\n incomingWithDrainState[incomingDraining] = true;\n if (incoming instanceof Http2ServerRequest2) {\n try {\n ;\n incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);\n } catch {\n }\n return;\n }\n let bytesRead = 0;\n const cleanup = () => {\n clearTimeout(timer);\n incoming.off(\"data\", onData);\n incoming.off(\"end\", cleanup);\n incoming.off(\"error\", cleanup);\n };\n const forceClose = () => {\n cleanup();\n const socket = incoming.socket;\n if (socket && !socket.destroyed) {\n socket.destroySoon();\n }\n };\n const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n timer.unref?.();\n const onData = (chunk) => {\n bytesRead += chunk.length;\n if (bytesRead > MAX_DRAIN_BYTES) {\n forceClose();\n }\n };\n incoming.on(\"data\", onData);\n incoming.on(\"end\", cleanup);\n incoming.on(\"error\", cleanup);\n incoming.resume();\n};\nvar handleRequestError = () => new Response(null, {\n status: 400\n});\nvar handleFetchError = (e) => new Response(null, {\n status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500\n});\nvar handleResponseError = (e, outgoing) => {\n const err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n if (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") {\n console.info(\"The user aborted a request.\");\n } else {\n console.error(e);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n }\n outgoing.end(`Error: ${err.message}`);\n outgoing.destroy(err);\n }\n};\nvar flushHeaders = (outgoing) => {\n if (\"flushHeaders\" in outgoing && outgoing.writable) {\n outgoing.flushHeaders();\n }\n};\nvar responseViaCache = async (res, outgoing) => {\n let [status, body, header] = res[cacheKey];\n let hasContentLength = false;\n if (!header) {\n header = { \"content-type\": \"text/plain; charset=UTF-8\" };\n } else if (header instanceof Headers) {\n hasContentLength = header.has(\"content-length\");\n header = buildOutgoingHttpHeaders(header);\n } else if (Array.isArray(header)) {\n const headerObj = new Headers(header);\n hasContentLength = headerObj.has(\"content-length\");\n header = buildOutgoingHttpHeaders(headerObj);\n } else {\n for (const key in header) {\n if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n hasContentLength = true;\n break;\n }\n }\n }\n if (!hasContentLength) {\n if (typeof body === \"string\") {\n header[\"Content-Length\"] = Buffer.byteLength(body);\n } else if (body instanceof Uint8Array) {\n header[\"Content-Length\"] = body.byteLength;\n } else if (body instanceof Blob) {\n header[\"Content-Length\"] = body.size;\n }\n }\n outgoing.writeHead(status, header);\n if (typeof body === \"string\" || body instanceof Uint8Array) {\n outgoing.end(body);\n } else if (body instanceof Blob) {\n outgoing.end(new Uint8Array(await body.arrayBuffer()));\n } else {\n flushHeaders(outgoing);\n await writeFromReadableStream(body, outgoing)?.catch(\n (e) => handleResponseError(e, outgoing)\n );\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar isPromise = (res) => typeof res.then === \"function\";\nvar responseViaResponseObject = async (res, outgoing, options = {}) => {\n if (isPromise(res)) {\n if (options.errorHandler) {\n try {\n res = await res;\n } catch (err) {\n const errRes = await options.errorHandler(err);\n if (!errRes) {\n return;\n }\n res = errRes;\n }\n } else {\n res = await res.catch(handleFetchError);\n }\n }\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);\n if (res.body) {\n const reader = res.body.getReader();\n const values = [];\n let done = false;\n let currentReadPromise = void 0;\n if (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n let maxReadCount = 2;\n for (let i = 0; i < maxReadCount; i++) {\n currentReadPromise ||= reader.read();\n const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n console.error(e);\n done = true;\n });\n if (!chunk) {\n if (i === 1) {\n await new Promise((resolve) => setTimeout(resolve));\n maxReadCount = 3;\n continue;\n }\n break;\n }\n currentReadPromise = void 0;\n if (chunk.value) {\n values.push(chunk.value);\n }\n if (chunk.done) {\n done = true;\n break;\n }\n }\n if (done && !(\"content-length\" in resHeaderRecord)) {\n resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n }\n }\n outgoing.writeHead(res.status, resHeaderRecord);\n values.forEach((value) => {\n ;\n outgoing.write(value);\n });\n if (done) {\n outgoing.end();\n } else {\n if (values.length === 0) {\n flushHeaders(outgoing);\n }\n await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n }\n } else if (resHeaderRecord[X_ALREADY_SENT]) {\n } else {\n outgoing.writeHead(res.status, resHeaderRecord);\n outgoing.end();\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar getRequestListener = (fetchCallback, options = {}) => {\n const autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n if (options.overrideGlobalObjects !== false && global.Request !== Request) {\n Object.defineProperty(global, \"Request\", {\n value: Request\n });\n Object.defineProperty(global, \"Response\", {\n value: Response2\n });\n }\n return async (incoming, outgoing) => {\n let res, req;\n try {\n req = newRequest(incoming, options.hostname);\n let incomingEnded = !autoCleanupIncoming || incoming.method === \"GET\" || incoming.method === \"HEAD\";\n if (!incomingEnded) {\n ;\n incoming[wrapBodyStream] = true;\n incoming.on(\"end\", () => {\n incomingEnded = true;\n });\n if (incoming instanceof Http2ServerRequest2) {\n ;\n outgoing[outgoingEnded] = () => {\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n };\n }\n outgoing.on(\"finish\", () => {\n if (!incomingEnded) {\n drainIncoming(incoming);\n }\n });\n }\n outgoing.on(\"close\", () => {\n const abortController = req[abortControllerKey];\n if (abortController) {\n if (incoming.errored) {\n req[abortControllerKey].abort(incoming.errored.toString());\n } else if (!outgoing.writableFinished) {\n req[abortControllerKey].abort(\"Client connection prematurely closed.\");\n }\n }\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n });\n res = fetchCallback(req, { incoming, outgoing });\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n } catch (e) {\n if (!res) {\n if (options.errorHandler) {\n res = await options.errorHandler(req ? e : toRequestError(e));\n if (!res) {\n return;\n }\n } else if (!req) {\n res = handleRequestError();\n } else {\n res = handleFetchError(e);\n }\n } else {\n return handleResponseError(e, outgoing);\n }\n }\n try {\n return await responseViaResponseObject(res, outgoing, options);\n } catch (e) {\n return handleResponseError(e, outgoing);\n }\n };\n};\n\n// src/server.ts\nvar createAdaptorServer = (options) => {\n const fetchCallback = options.fetch;\n const requestListener = getRequestListener(fetchCallback, {\n hostname: options.hostname,\n overrideGlobalObjects: options.overrideGlobalObjects,\n autoCleanupIncoming: options.autoCleanupIncoming\n });\n const createServer = options.createServer || createServerHTTP;\n const server = createServer(options.serverOptions || {}, requestListener);\n return server;\n};\nvar serve = (options, listeningListener) => {\n const server = createAdaptorServer(options);\n server.listen(options?.port ?? 3e3, options.hostname, () => {\n const serverInfo = server.address();\n listeningListener && listeningListener(serverInfo);\n });\n return server;\n};\nexport {\n RequestError,\n createAdaptorServer,\n getRequestListener,\n serve\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Shared Schemas and Utilities\n * Common schemas used across multiple modules\n */\n\nexport * from './identifiers.zod';\nexport * from './mapping.zod';\nexport * from './http.zod';\nexport * from './enums.zod';\nexport * from './metadata-types.zod';\nexport * from './branded-types.zod';\nexport * from './suggestions.zod';\nexport * from './error-map.zod';\nexport * from './metadata-collection.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Base Field Mapping Protocol\n * \n * Shared by: ETL, Sync, Connector, External Lookup\n * \n * This module provides the canonical field mapping schema used across\n * ObjectStack for data transformation and synchronization.\n * \n * **Use Cases:**\n * - ETL pipelines (data/mapping.zod.ts)\n * - Data synchronization (automation/sync.zod.ts)\n * - Integration connectors (integration/connector.zod.ts)\n * - External lookups (data/external-lookup.zod.ts)\n * \n * @example Basic field mapping\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'external_user_id',\n * target: 'user_id',\n * };\n * ```\n * \n * @example With transformation\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'user_name',\n * target: 'name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: 'Unknown'\n * };\n * ```\n */\n\n/**\n * Transform Type Schema\n * \n * Defines the type of transformation to apply to a field value.\n * Implementations can extend this for domain-specific transforms.\n */\nexport const TransformTypeSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('constant'),\n value: z.unknown().describe('Constant value to use'),\n }).describe('Set a constant value'),\n \n z.object({\n type: z.literal('cast'),\n targetType: z.enum(['string', 'number', 'boolean', 'date']).describe('Target data type'),\n }).describe('Cast to a specific data type'),\n \n z.object({\n type: z.literal('lookup'),\n table: z.string().describe('Lookup table name'),\n keyField: z.string().describe('Field to match on'),\n valueField: z.string().describe('Field to retrieve'),\n }).describe('Lookup value from another table'),\n \n z.object({\n type: z.literal('javascript'),\n expression: z.string().describe('JavaScript expression (e.g., \"value.toUpperCase()\")'),\n }).describe('Custom JavaScript transformation'),\n \n z.object({\n type: z.literal('map'),\n mappings: z.record(z.string(), z.unknown()).describe('Value mappings (e.g., {\"Active\": \"active\"})'),\n }).describe('Map values using a dictionary'),\n]);\n\nexport type TransformType = z.infer;\n\n/**\n * Field Mapping Schema\n * \n * Base schema for mapping fields between source and target systems.\n * \n * **NAMING CONVENTION:**\n * - source: Field name in the source system\n * - target: Field name in the target system (should be snake_case for ObjectStack)\n * \n * @example\n * ```typescript\n * {\n * source: 'FirstName',\n * target: 'first_name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: ''\n * }\n * ```\n */\nexport const FieldMappingSchema = z.object({\n /**\n * Source field name\n */\n source: z.string().describe('Source field name'),\n \n /**\n * Target field name (should be snake_case for ObjectStack)\n */\n target: z.string().describe('Target field name'),\n \n /**\n * Transformation to apply\n */\n transform: TransformTypeSchema.optional().describe('Transformation to apply'),\n \n /**\n * Default value if source is null/undefined\n */\n defaultValue: z.unknown().optional().describe('Default if source is null/undefined'),\n});\n\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Shared Enumerations\n// ============================================================================\n\n/** Aggregation functions used across query, data-engine, analytics, field */\nexport const AggregationFunctionEnum = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'percentile', 'median', 'stddev', 'variance',\n]).describe('Standard aggregation functions');\nexport type AggregationFunction = z.infer;\n\n/** Sort direction used across query, data-engine, analytics */\nexport const SortDirectionEnum = z.enum(['asc', 'desc'])\n .describe('Sort order direction');\nexport type SortDirection = z.infer;\n\n/** Reusable sort item — field + direction pair used across views, data sources, filters */\nexport const SortItemSchema = z.object({\n field: z.string().describe('Field name to sort by'),\n order: SortDirectionEnum.describe('Sort direction'),\n}).describe('Sort field and direction pair');\nexport type SortItem = z.infer;\n\n/** CRUD mutation events used across hook, validation, object CDC */\nexport const MutationEventEnum = z.enum([\n 'insert', 'update', 'delete', 'upsert',\n]).describe('Data mutation event types');\nexport type MutationEvent = z.infer;\n\n/** Database isolation levels — unified format */\nexport const IsolationLevelEnum = z.enum([\n 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable', 'snapshot',\n]).describe('Transaction isolation levels (snake_case standard)');\nexport type IsolationLevel = z.infer;\n\n/** Cache eviction strategies */\nexport const CacheStrategyEnum = z.enum(['lru', 'lfu', 'ttl', 'fifo'])\n .describe('Cache eviction strategy');\nexport type CacheStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from './identifiers.zod';\n\n// ============================================================================\n// Shared Metadata Types\n// ============================================================================\n\n/** Supported metadata file formats */\nexport const MetadataFormatSchema = z.enum(['yaml', 'json', 'typescript', 'javascript'])\n .describe('Metadata file format');\nexport type MetadataFormat = z.infer;\n\n/** Base metadata record fields shared across kernel and system layers */\nexport const BaseMetadataRecordSchema = z.object({\n id: z.string().describe('Unique metadata record identifier'),\n type: z.string().describe('Metadata type (e.g. \"object\", \"view\", \"flow\")'),\n name: SnakeCaseIdentifierSchema.describe('Machine name (snake_case)'),\n format: MetadataFormatSchema.optional().describe('Source file format'),\n}).describe('Base metadata record fields shared across kernel and system');\nexport type BaseMetadataRecord = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema, SystemIdentifierSchema } from './identifiers.zod';\n\n/**\n * Branded Types for ObjectStack Identifiers\n *\n * Branded types provide compile-time safety by preventing accidental mixing\n * of different identifier kinds. For example, you cannot pass an ObjectName\n * where a FieldName is expected, even though both are strings at runtime.\n *\n * @example\n * ```ts\n * import { ObjectNameSchema, FieldNameSchema } from '@objectstack/spec';\n *\n * const objName = ObjectNameSchema.parse('project_task'); // ObjectName\n * const fieldName = FieldNameSchema.parse('task_name'); // FieldName\n *\n * // TypeScript will catch this at compile time:\n * // const fn: FieldName = objName; // Error!\n * ```\n */\n\n/**\n * ObjectName — Branded type for business object names.\n *\n * Must be snake_case (no dots). Used for table/collection names.\n *\n * @example 'project_task', 'crm_account', 'user_profile'\n */\nexport const ObjectNameSchema = SnakeCaseIdentifierSchema\n .brand<'ObjectName'>()\n .describe('Branded object name (snake_case, no dots)');\n\nexport type ObjectName = z.infer;\n\n/**\n * FieldName — Branded type for field (column) names.\n *\n * Must be snake_case (no dots). Used for column/property names within objects.\n *\n * @example 'first_name', 'created_at', 'total_amount'\n */\nexport const FieldNameSchema = SnakeCaseIdentifierSchema\n .brand<'FieldName'>()\n .describe('Branded field name (snake_case, no dots)');\n\nexport type FieldName = z.infer;\n\n/**\n * ViewName — Branded type for view identifiers.\n *\n * Must be a valid system identifier (lowercase, may contain dots for namespacing).\n *\n * @example 'all_tasks', 'my_open_deals', 'contact.recent'\n */\nexport const ViewNameSchema = SystemIdentifierSchema\n .brand<'ViewName'>()\n .describe('Branded view name (system identifier)');\n\nexport type ViewName = z.infer;\n\n/**\n * AppName — Branded type for application identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'crm', 'helpdesk', 'project_management'\n */\nexport const AppNameSchema = SystemIdentifierSchema\n .brand<'AppName'>()\n .describe('Branded app name (system identifier)');\n\nexport type AppName = z.infer;\n\n/**\n * FlowName — Branded type for flow identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'approval_flow', 'onboarding_wizard', 'lead_qualification'\n */\nexport const FlowNameSchema = SystemIdentifierSchema\n .brand<'FlowName'>()\n .describe('Branded flow name (system identifier)');\n\nexport type FlowName = z.infer;\n\n/**\n * RoleName — Branded type for role identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'admin', 'sales_manager', 'read_only'\n */\nexport const RoleNameSchema = SystemIdentifierSchema\n .brand<'RoleName'>()\n .describe('Branded role name (system identifier)');\n\nexport type RoleName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { FieldType } from '../data/field.zod';\n\n/**\n * \"Did you mean?\" Suggestion Utilities\n *\n * Provides fuzzy matching for common ObjectStack identifiers.\n * Used by the custom error map to suggest corrections for typos.\n *\n * @example\n * ```ts\n * suggestFieldType('text_area'); // ['textarea']\n * suggestFieldType('String'); // ['text']\n * suggestFieldType('int'); // ['number']\n * ```\n */\n\n/**\n * Compute Levenshtein edit distance between two strings.\n * Uses space-optimized two-row approach (O(min(m,n)) space).\n */\nexport function levenshteinDistance(a: string, b: string): number {\n const la = a.length;\n const lb = b.length;\n\n if (la === 0) return lb;\n if (lb === 0) return la;\n\n // Use only two rows for space efficiency\n let prev = new Array(lb + 1);\n let curr = new Array(lb + 1);\n\n for (let j = 0; j <= lb; j++) {\n prev[j] = j;\n }\n\n for (let i = 1; i <= la; i++) {\n curr[0] = i;\n for (let j = 1; j <= lb; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n prev[j] + 1, // deletion\n curr[j - 1] + 1, // insertion\n prev[j - 1] + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n\n return prev[lb];\n}\n\n/**\n * Find the closest matches from a list of candidates.\n *\n * @param input - The user-provided (possibly invalid) value\n * @param candidates - Array of valid values to compare against\n * @param maxDistance - Maximum edit distance to consider (default: 3)\n * @param maxResults - Maximum number of suggestions to return (default: 3)\n * @returns Array of suggested values, sorted by similarity\n */\nexport function findClosestMatches(\n input: string,\n candidates: readonly string[],\n maxDistance = 3,\n maxResults = 3,\n): string[] {\n const normalized = input.toLowerCase().replace(/[-\\s]/g, '_');\n\n const scored = candidates\n .map((candidate) => ({\n value: candidate,\n distance: levenshteinDistance(normalized, candidate),\n }))\n .filter((s) => s.distance <= maxDistance && s.distance > 0)\n .sort((a, b) => a.distance - b.distance);\n\n return scored.slice(0, maxResults).map((s) => s.value);\n}\n\n/**\n * Well-known aliases that map common typos / alternative names to valid FieldTypes.\n */\nconst FIELD_TYPE_ALIASES: Record = {\n // Common alternative names\n string: 'text',\n str: 'text',\n varchar: 'text',\n char: 'text',\n int: 'number',\n integer: 'number',\n float: 'number',\n double: 'number',\n decimal: 'number',\n numeric: 'number',\n bool: 'boolean',\n checkbox: 'boolean',\n check: 'boolean',\n date_time: 'datetime',\n timestamp: 'datetime',\n // Common typos\n text_area: 'textarea',\n textarea_: 'textarea',\n textfield: 'text',\n dropdown: 'select',\n picklist: 'select',\n enum: 'select',\n multi_select: 'multiselect',\n multiselect_: 'multiselect',\n reference: 'lookup',\n ref: 'lookup',\n foreign_key: 'lookup',\n fk: 'lookup',\n relation: 'lookup',\n master: 'master_detail',\n richtext_: 'richtext',\n rich_text: 'richtext',\n upload: 'file',\n attachment: 'file',\n photo: 'image',\n picture: 'image',\n img: 'image',\n percent_: 'percent',\n percentage: 'percent',\n money: 'currency',\n price: 'currency',\n auto_number: 'autonumber',\n auto_increment: 'autonumber',\n sequence: 'autonumber',\n markdown_: 'markdown',\n md: 'markdown',\n barcode: 'qrcode',\n tag: 'tags',\n star: 'rating',\n stars: 'rating',\n geo: 'location',\n gps: 'location',\n coordinates: 'location',\n embed: 'vector',\n embedding: 'vector',\n embeddings: 'vector',\n};\n\n/**\n * Suggest valid FieldType values for an invalid input.\n *\n * First checks known aliases, then falls back to fuzzy matching.\n *\n * @param input - Invalid field type string\n * @returns Array of suggested valid FieldType values\n *\n * @example\n * ```ts\n * suggestFieldType('text_area'); // ['textarea']\n * suggestFieldType('String'); // ['text']\n * suggestFieldType('int'); // ['number']\n * suggestFieldType('dropdown'); // ['select']\n * ```\n */\nexport function suggestFieldType(input: string): string[] {\n const normalized = input.toLowerCase().replace(/[-\\s]/g, '_');\n\n // Check alias map first\n const alias = FIELD_TYPE_ALIASES[normalized];\n if (alias) {\n return [alias];\n }\n\n // Fall back to fuzzy matching\n return findClosestMatches(normalized, FieldType.options);\n}\n\n/**\n * Format a \"Did you mean?\" message for display.\n *\n * @param suggestions - Array of suggested values\n * @returns Formatted string or empty string if no suggestions\n */\nexport function formatSuggestion(suggestions: string[]): string {\n if (suggestions.length === 0) return '';\n if (suggestions.length === 1) return `Did you mean '${suggestions[0]}'?`;\n return `Did you mean one of: ${suggestions.map((s) => `'${s}'`).join(', ')}?`;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { suggestFieldType, formatSuggestion, findClosestMatches } from './suggestions.zod';\nimport { FieldType } from '../data/field.zod';\n\n/**\n * Zod v4 raw issue type used by the error map.\n */\nexport type ObjectStackRawIssue = z.core.$ZodRawIssue;\n\n/**\n * ObjectStack Custom Zod Error Map\n *\n * Provides contextual, actionable error messages for ObjectStack schema validation.\n * Instead of generic Zod messages like \"Invalid option\", this error map returns\n * messages that explain the ObjectStack context and suggest fixes.\n *\n * In Zod v4, the error map is a function `(issue) => { message: string } | string | null`.\n * Pass it via the `error` option on `.safeParse()` / `.parse()`.\n *\n * @example\n * ```ts\n * import { objectStackErrorMap } from '@objectstack/spec';\n *\n * // Per-parse usage\n * SomeSchema.safeParse(data, { error: objectStackErrorMap });\n * ```\n */\nexport const objectStackErrorMap = (issue: ObjectStackRawIssue): { message: string } | null => {\n // --- Invalid value (enum) with suggestions ---\n if (issue.code === 'invalid_value') {\n const values = issue.values as unknown[];\n const input = issue.input;\n const received = String(input ?? '');\n const options = values.map(String);\n\n // Check if this looks like a FieldType enum\n const fieldTypeOptions = FieldType.options as readonly string[];\n const isFieldTypeEnum = options.length > 10 &&\n fieldTypeOptions.every((ft) => options.includes(ft));\n\n if (isFieldTypeEnum) {\n const suggestions = suggestFieldType(received);\n const suggestion = formatSuggestion(suggestions);\n const base = `Invalid field type '${received}'.`;\n return {\n message: suggestion ? `${base} ${suggestion}` : `${base} Valid types: ${options.slice(0, 10).join(', ')}...`,\n };\n }\n\n // Generic enum suggestion\n const suggestions = findClosestMatches(received, options);\n const suggestion = formatSuggestion(suggestions);\n const base = `Invalid value '${received}'.`;\n return {\n message: suggestion\n ? `${base} ${suggestion}`\n : `${base} Expected one of: ${options.join(', ')}.`,\n };\n }\n\n // --- String/array/number size validation ---\n if (issue.code === 'too_small') {\n const origin = issue.origin as string;\n const minimum = issue.minimum as number;\n if (origin === 'string') {\n return {\n message: `Must be at least ${minimum} character${minimum === 1 ? '' : 's'} long.`,\n };\n }\n }\n\n if (issue.code === 'too_big') {\n const origin = issue.origin as string;\n const maximum = issue.maximum as number;\n if (origin === 'string') {\n return {\n message: `Must be at most ${maximum} character${maximum === 1 ? '' : 's'} long.`,\n };\n }\n }\n\n // --- String format validation (regex) ---\n if (issue.code === 'invalid_format') {\n const format = issue.format as string;\n const input = issue.input as string | undefined;\n if (format === 'regex' && input) {\n const pathArr = issue.path as (string | number)[] | undefined;\n const pathStr = pathArr?.join('.') ?? '';\n if (pathStr.endsWith('name') || pathStr === 'name') {\n return {\n message: `Invalid identifier '${input}'. Must be lowercase snake_case (e.g., 'my_object', 'task_name'). No uppercase, spaces, or hyphens allowed.`,\n };\n }\n }\n }\n\n // --- Missing required / type mismatch ---\n if (issue.code === 'invalid_type') {\n const expected = issue.expected as string;\n const input = issue.input;\n if (input === undefined) {\n const pathArr = issue.path as (string | number)[] | undefined;\n const field = pathArr?.[pathArr.length - 1] ?? '';\n return {\n message: `Required property '${field}' is missing.`,\n };\n }\n const receivedType = input === null ? 'null' : typeof input;\n return {\n message: `Expected ${expected} but received ${receivedType}.`,\n };\n }\n\n // --- Unrecognized keys ---\n if (issue.code === 'unrecognized_keys') {\n const keys = issue.keys as string[];\n const keyStr = keys.join(', ');\n return {\n message: `Unrecognized key${keys.length > 1 ? 's' : ''}: ${keyStr}. Check for typos in property names.`,\n };\n }\n\n // Fallback to Zod default\n return null;\n};\n\n/**\n * Zod Issue interface (subset needed for formatting).\n */\ninterface ZodIssueMinimal {\n path: PropertyKey[];\n message: string;\n code?: string;\n}\n\n/**\n * Format a single Zod issue into a human-readable line.\n *\n * @param issue - A single Zod issue\n * @returns Formatted string with path and message\n */\nexport function formatZodIssue(issue: ZodIssueMinimal): string {\n const path = issue.path.length > 0\n ? issue.path.join('.')\n : '(root)';\n return ` ✗ ${path}: ${issue.message}`;\n}\n\n/**\n * Pretty-print Zod validation errors for CLI output.\n *\n * Formats a ZodError into a readable block suitable for terminal display.\n * Groups errors by path depth and includes a summary count.\n *\n * @param error - A ZodError to format\n * @param label - Optional label for the error block (e.g., 'Stack validation failed')\n * @returns Formatted multi-line string\n *\n * @example\n * ```ts\n * import { formatZodError, ObjectStackDefinitionSchema } from '@objectstack/spec';\n *\n * const result = ObjectStackDefinitionSchema.safeParse(data);\n * if (!result.success) {\n * console.error(formatZodError(result.error, 'Stack validation failed'));\n * }\n * ```\n *\n * Output:\n * ```\n * Stack validation failed (3 issues):\n *\n * ✗ manifest.name: Required property 'name' is missing.\n * ✗ objects[0].fields.status.type: Invalid field type 'dropdown'. Did you mean 'select'?\n * ✗ views[0].object: Invalid identifier 'MyTasks'. Must be lowercase snake_case.\n * ```\n */\nexport function formatZodError(error: z.ZodError, label?: string): string {\n const count = error.issues.length;\n const header = label\n ? `${label} (${count} issue${count === 1 ? '' : 's'}):`\n : `Validation failed (${count} issue${count === 1 ? '' : 's'}):`;\n\n const lines = error.issues.map(formatZodIssue);\n\n return `${header}\\n\\n${lines.join('\\n')}`;\n}\n\n/**\n * Parse with the ObjectStack error map and return formatted errors.\n *\n * A convenience function that combines parsing with the custom error map\n * and pretty-print formatting. Returns a discriminated union result.\n *\n * @param schema - Any Zod schema to parse with\n * @param data - Data to validate\n * @param label - Optional label for error formatting\n * @returns Object with `success`, `data`, and optional `formatted` error string\n *\n * @example\n * ```ts\n * const result = safeParsePretty(ObjectStackDefinitionSchema, config, 'objectstack.config.ts');\n * if (!result.success) {\n * console.error(result.formatted);\n * process.exit(1);\n * }\n * ```\n */\nexport function safeParsePretty(\n schema: T,\n data: unknown,\n label?: string,\n): { success: true; data: z.infer } | { success: false; error: z.ZodError; formatted: string } {\n const result = schema.safeParse(data, { error: objectStackErrorMap });\n if (result.success) {\n return { success: true, data: result.data };\n }\n return {\n success: false,\n error: result.error,\n formatted: formatZodError(result.error, label),\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Metadata Collection Utilities\n * \n * Provides support for defining metadata collections in either array or map (Record) format.\n * Map format automatically injects the key as the `name` field, following the same pattern\n * used by `fields` in ObjectSchema (which already uses `z.record(key, FieldSchema)`).\n * \n * ## Usage\n * \n * Both formats are accepted and normalized to arrays:\n * \n * ```ts\n * // Array format (traditional)\n * defineStack({\n * objects: [\n * { name: 'account', fields: { ... } },\n * { name: 'contact', fields: { ... } },\n * ]\n * });\n * \n * // Map format (key becomes `name`)\n * defineStack({\n * objects: {\n * account: { fields: { ... } },\n * contact: { fields: { ... } },\n * }\n * });\n * ```\n * \n * @module\n */\n\n/**\n * Input type for metadata collections: accepts either an array or a named map.\n * When using map format, the key is injected as the `name` field of each item.\n * \n * @typeParam T - The metadata item type (e.g., `ObjectSchema`, `AppSchema`)\n * \n * @example\n * ```ts\n * // Array format — name is required in each item\n * const apps: MetadataCollectionInput = [\n * { name: 'sales', label: 'Sales' },\n * { name: 'service', label: 'Service' },\n * ];\n * \n * // Map format — key serves as name, so name is optional in value\n * const apps: MetadataCollectionInput = {\n * sales: { label: 'Sales' },\n * service: { label: 'Service' },\n * };\n * ```\n */\nexport type MetadataCollectionInput =\n | T[]\n | Record & { name?: string }>;\n\n/**\n * List of metadata fields in ObjectStackDefinitionSchema that support map format.\n * These are fields where each item has a `name` field that can be inferred from the map key.\n * \n * Excluded fields:\n * - `views` — ViewSchema has no `name` field (it's a container with `list`/`form`)\n * - `objectExtensions` — uses `extend` as its identifier, not `name`\n * - `data` — DatasetSchema uses `object` as its identifier\n * - `translations` — TranslationBundleSchema is a record, not a named object\n * - `plugins` / `devPlugins` — not named metadata schemas\n */\nexport const MAP_SUPPORTED_FIELDS = [\n 'objects',\n 'apps',\n 'pages',\n 'dashboards',\n 'reports',\n 'actions',\n 'themes',\n 'workflows',\n 'approvals',\n 'flows',\n 'roles',\n 'permissions',\n 'sharingRules',\n 'policies',\n 'apis',\n 'webhooks',\n 'agents',\n 'ragPipelines',\n 'hooks',\n 'mappings',\n 'analyticsCubes',\n 'connectors',\n 'datasources',\n] as const;\n\nexport type MapSupportedField = (typeof MAP_SUPPORTED_FIELDS)[number];\n\n/**\n * Mapping from plural manifest field names to singular metadata type names.\n *\n * Manifest / `defineStack()` uses plural property names because they are\n * collection fields (e.g. `objects: [...]`, `apps: [...]`). The metadata\n * registry and `MetadataTypeSchema` use singular names as the canonical form.\n *\n * Use this mapping at the boundary where manifest fields are fed into the\n * metadata registry to ensure a consistent singular naming convention.\n */\nexport const PLURAL_TO_SINGULAR: Record = {\n objects: 'object',\n apps: 'app',\n pages: 'page',\n dashboards: 'dashboard',\n reports: 'report',\n actions: 'action',\n themes: 'theme',\n workflows: 'workflow',\n approvals: 'approval',\n flows: 'flow',\n roles: 'role',\n permissions: 'permission',\n profiles: 'profile',\n sharingRules: 'sharingRule',\n policies: 'policy',\n apis: 'api',\n webhooks: 'webhook',\n agents: 'agent',\n ragPipelines: 'ragPipeline',\n hooks: 'hook',\n mappings: 'mapping',\n analyticsCubes: 'analyticsCube',\n connectors: 'connector',\n datasources: 'datasource',\n views: 'view',\n};\n\n/** Reverse mapping: singular metadata type → plural manifest field name. */\nexport const SINGULAR_TO_PLURAL: Record = Object.fromEntries(\n Object.entries(PLURAL_TO_SINGULAR).map(([plural, singular]) => [singular, plural]),\n);\n\n/** Convert a plural manifest field name to its singular metadata type name. Returns the input unchanged if no mapping exists. */\nexport function pluralToSingular(key: string): string {\n return PLURAL_TO_SINGULAR[key] ?? key;\n}\n\n/** Convert a singular metadata type name to its plural manifest field name. Returns the input unchanged if no mapping exists. */\nexport function singularToPlural(key: string): string {\n return SINGULAR_TO_PLURAL[key] ?? key;\n}\n\n\n/**\n * Normalize a single metadata collection value from map format to array format.\n * If the input is already an array (or nullish), it is returned unchanged.\n * If the input is a plain object (map), it is converted to an array where\n * each key is injected as the `name` field of the corresponding item.\n * \n * **Precedence:** If an item already has a `name` property, it is preserved\n * (the map key is only used as a fallback).\n * \n * @param value - The raw input value (array, map, or nullish)\n * @param keyField - The field name to inject the key into (default: `'name'`)\n * @returns The normalized array, or the original value if already an array/nullish\n * \n * @example\n * ```ts\n * // Map input\n * normalizeMetadataCollection({\n * account: { fields: { name: { type: 'text' } } },\n * contact: { fields: { email: { type: 'email' } } },\n * });\n * // → [\n * // { name: 'account', fields: { name: { type: 'text' } } },\n * // { name: 'contact', fields: { email: { type: 'email' } } },\n * // ]\n * \n * // Array input (pass-through)\n * normalizeMetadataCollection([{ name: 'account', fields: {} }]);\n * // → [{ name: 'account', fields: {} }]\n * ```\n */\nexport function normalizeMetadataCollection(value: unknown, keyField = 'name'): unknown {\n // Nullish or already an array — pass through\n if (value == null || Array.isArray(value)) return value;\n\n // Plain object — treat as map and convert to array\n if (typeof value === 'object') {\n return Object.entries(value as Record).map(([key, item]) => {\n if (item && typeof item === 'object' && !Array.isArray(item)) {\n const obj = item as Record;\n // Only inject key if the item doesn't already have the field set\n if (!(keyField in obj) || obj[keyField] === undefined) {\n return { ...obj, [keyField]: key };\n }\n return obj;\n }\n // Non-object values (shouldn't happen, but let Zod handle the error)\n return item;\n });\n }\n\n // Other types — return as-is and let Zod validation handle the error\n return value;\n}\n\n/**\n * Normalize all metadata collections in a stack definition input.\n * Converts any map-formatted collections to arrays with key→name injection.\n * \n * This function is applied to the raw input before Zod validation,\n * ensuring the canonical internal format is always arrays.\n * \n * @param input - The raw stack definition input\n * @returns A new object with all map collections normalized to arrays\n */\nexport function normalizeStackInput>(input: T): T {\n const result = { ...input };\n for (const field of MAP_SUPPORTED_FIELDS) {\n if (field in result) {\n (result as Record)[field] = normalizeMetadataCollection(result[field]);\n }\n }\n return result;\n}\n\n/**\n * Mapping of legacy / alternative field names to their canonical names\n * in `ObjectStackDefinitionSchema`.\n *\n * Plugins may use legacy names (e.g., `triggers` instead of `hooks`).\n * This map lets `normalizePluginMetadata()` rewrite them automatically.\n */\nexport const METADATA_ALIASES: Record = {\n triggers: 'hooks',\n};\n\n/**\n * Normalize plugin metadata so it matches the canonical format expected by the runtime.\n *\n * This handles two issues that commonly arise when loading third-party plugin metadata:\n *\n * 1. **Map → Array conversion** — plugins often define metadata as maps\n * (e.g., `actions: { convert_lead: { ... } }`), but the runtime expects arrays.\n * Every key listed in {@link MAP_SUPPORTED_FIELDS} is normalized via\n * {@link normalizeMetadataCollection}.\n *\n * 2. **Field aliasing** — plugins may use legacy or alternative field names\n * (e.g., `triggers` instead of `hooks`). {@link METADATA_ALIASES} maps them\n * to their canonical counterparts.\n *\n * 3. **Recursive normalization** — if the plugin itself contains nested `plugins`,\n * each nested plugin is normalized recursively.\n *\n * @param metadata - Raw plugin metadata object\n * @returns A new object with all collections normalized to arrays, aliases resolved,\n * and nested plugins recursively normalized\n *\n * @example\n * ```ts\n * const raw = {\n * actions: { lead_convert: { type: 'custom', label: 'Convert' } },\n * triggers: { lead_scoring: { object: 'lead', event: 'afterInsert' } },\n * };\n * const normalized = normalizePluginMetadata(raw);\n * // normalized.actions → [{ name: 'lead_convert', type: 'custom', label: 'Convert' }]\n * // normalized.hooks → [{ name: 'lead_scoring', object: 'lead', event: 'afterInsert' }]\n * // normalized.triggers → removed (merged into hooks)\n * ```\n */\nexport function normalizePluginMetadata>(metadata: T): T {\n const result = { ...metadata };\n\n // 1. Resolve aliases (e.g. triggers → hooks), merging with any existing canonical values\n for (const [alias, canonical] of Object.entries(METADATA_ALIASES)) {\n if (alias in result) {\n const aliasValue = normalizeMetadataCollection(result[alias]);\n const canonicalValue = normalizeMetadataCollection(result[canonical]);\n\n // Merge: canonical array wins; alias values are appended\n if (Array.isArray(aliasValue)) {\n (result as Record)[canonical] = Array.isArray(canonicalValue)\n ? [...canonicalValue, ...aliasValue]\n : aliasValue;\n }\n\n delete (result as Record)[alias];\n }\n }\n\n // 2. Normalize map-formatted collections → arrays\n for (const field of MAP_SUPPORTED_FIELDS) {\n if (field in result) {\n (result as Record)[field] = normalizeMetadataCollection(result[field]);\n }\n }\n\n // 3. Recursively normalize nested plugins\n if (Array.isArray(result.plugins)) {\n (result as Record).plugins = result.plugins.map((p: unknown) => {\n if (p && typeof p === 'object' && !Array.isArray(p)) {\n return normalizePluginMetadata(p as Record);\n }\n return p;\n });\n }\n\n return result;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './query.zod';\nexport * from './filter.zod';\nexport * from './object.zod';\nexport * from './field.zod';\nexport * from './validation.zod';\nexport * from './hook.zod';\nexport * from './mapping.zod';\nexport * from './data-engine.zod';\nexport * from './driver.zod';\nexport * from './driver-sql.zod';\nexport * from './driver-nosql.zod';\n\nexport * from './dataset.zod';\n\n// Seed Loader Protocol (Relationship Resolution & Dependency Ordering)\nexport * from './seed-loader.zod';\n\n// Document Management Protocol\nexport * from './document.zod';\n\n// External Lookup Protocol\nexport * from './external-lookup.zod';\nexport * from './datasource.zod';\n\n// Analytics Protocol (Semantic Layer)\nexport * from './analytics.zod';\n\n// Feed & Activity Protocol\nexport * from './feed.zod';\n\n// Subscription Protocol\nexport * from './subscription.zod';\n\n// Turso Multi-Tenant Driver\nexport * from './driver/turso-multi-tenant.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Query DSL Specification\n * \n * Based on industry best practices from:\n * - Prisma ORM\n * - Strapi CMS\n * - TypeORM\n * - LoopBack Framework\n * \n * Version: 1.0.0\n * Status: Draft\n * \n * Objective: Define a JSON-based, database-agnostic query syntax standard\n * for data filtering interactions between frontend and backend APIs.\n * \n * Design Principles:\n * 1. Declarative: Frontend describes \"what data to get\", not \"how to query\"\n * 2. Database Agnostic: Syntax contains no database-specific directives\n * 3. Type Safe: Structure can be statically inferred by TypeScript\n * 4. Convention over Configuration: Implicit syntax for common queries\n */\n\n/**\n * Field Reference\n * Represents a reference to another field/column instead of a literal value.\n * Used for joins (ON clause) and cross-field comparisons.\n * \n * @example\n * // user.id = order.owner_id\n * { \"$eq\": { \"$field\": \"order.owner_id\" } }\n */\nexport const FieldReferenceSchema = z.object({\n $field: z.string().describe('Field Reference/Column Name')\n});\n\nexport type FieldReference = z.infer;\n\n// ============================================================================\n// 3.1 Comparison Operators\n// ============================================================================\n\n/**\n * Comparison operators for equality and inequality checks.\n * Supported data types: Any\n */\nexport const EqualityOperatorSchema = z.object({\n /** Equal to (default) - SQL: = | MongoDB: $eq */\n $eq: z.any().optional(),\n \n /** Not equal to - SQL: <> or != | MongoDB: $ne */\n $ne: z.any().optional(),\n});\n\n/**\n * Comparison operators for numeric and date comparisons.\n * Supported data types: Number, Date\n */\nexport const ComparisonOperatorSchema = z.object({\n /** Greater than - SQL: > | MongoDB: $gt */\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Greater than or equal to - SQL: >= | MongoDB: $gte */\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than - SQL: < | MongoDB: $lt */\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than or equal to - SQL: <= | MongoDB: $lte */\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n});\n\n// ============================================================================\n// 3.2 Set & Range Operators\n// ============================================================================\n\n/**\n * Set operators for membership checks.\n */\nexport const SetOperatorSchema = z.object({\n /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */\n $in: z.array(z.any()).optional(),\n \n /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */\n $nin: z.array(z.any()).optional(),\n});\n\n/**\n * Range operator for interval checks (closed interval).\n * SQL: BETWEEN ? AND ? | MongoDB: $gte AND $lte\n */\nexport const RangeOperatorSchema = z.object({\n /** Between (inclusive) - takes [min, max] array */\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n});\n\n// ============================================================================\n// 3.3 String-Specific Operators\n// ============================================================================\n\n/**\n * String pattern matching operators.\n * Note: Case sensitivity should be handled at backend level.\n */\nexport const StringOperatorSchema = z.object({\n /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */\n $contains: z.string().optional(),\n \n /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */\n $notContains: z.string().optional(),\n \n /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */\n $startsWith: z.string().optional(),\n \n /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */\n $endsWith: z.string().optional(),\n});\n\n// ============================================================================\n// 3.5 Special Operators\n// ============================================================================\n\n/**\n * Special check operators for null and existence.\n */\nexport const SpecialOperatorSchema = z.object({\n /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */\n $null: z.boolean().optional(),\n \n /** Field exists check (primarily for NoSQL) - MongoDB: $exists */\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// Combined Field Operators\n// ============================================================================\n\n/**\n * All field-level operators combined.\n * These can be applied to individual fields in a filter.\n */\nexport const FieldOperatorsSchema = z.object({\n // Equality\n $eq: z.any().optional(),\n $ne: z.any().optional(),\n \n // Comparison (numeric/date)\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n // Set & Range\n $in: z.array(z.any()).optional(),\n $nin: z.array(z.any()).optional(),\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n \n // String-specific\n $contains: z.string().optional(),\n $notContains: z.string().optional(),\n $startsWith: z.string().optional(),\n $endsWith: z.string().optional(),\n \n // Special\n $null: z.boolean().optional(),\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// 3.4 Logical Operators & Recursive Filter Structure\n// ============================================================================\n\n/**\n * Recursive filter type that supports:\n * 1. Implicit equality: { field: value }\n * 2. Explicit operators: { field: { $op: value } }\n * 3. Logical combinations: { $and: [...], $or: [...], $not: {...} }\n * 4. Nested relations: { relation: { field: value } }\n */\nexport type FilterCondition = {\n [key: string]: \n | any // Implicit equality: key: value\n | z.infer // Explicit operators: key: { $op: value }\n | FilterCondition; // Nested relation: key: { nested: ... }\n} & {\n /** Logical AND - combines all conditions that must be true */\n $and?: FilterCondition[];\n \n /** Logical OR - at least one condition must be true */\n $or?: FilterCondition[];\n \n /** Logical NOT - negates the condition */\n $not?: FilterCondition;\n};\n\n/**\n * Zod schema for recursive filter validation.\n * Uses z.lazy() to handle recursive structure.\n */\nexport const FilterConditionSchema: z.ZodType = z.lazy(() =>\n z.record(z.string(), z.unknown()).and(\n z.object({\n $and: z.array(FilterConditionSchema).optional(),\n $or: z.array(FilterConditionSchema).optional(),\n $not: FilterConditionSchema.optional(),\n })\n )\n);\n\n// ============================================================================\n// Query Filter Wrapper\n// ============================================================================\n\n/**\n * Top-level query filter wrapper.\n * This is typically used as the \"where\" clause in a query.\n * \n * @example\n * ```typescript\n * const filter: QueryFilter = {\n * where: {\n * status: \"active\", // Implicit equality\n * age: { $gte: 18 }, // Explicit operator\n * $or: [ // Logical combination\n * { role: \"admin\" },\n * { email: { $contains: \"@company.com\" } }\n * ],\n * profile: { // Nested relation\n * verified: true\n * }\n * }\n * }\n * ```\n */\nexport const QueryFilterSchema = z.object({\n where: FilterConditionSchema.optional(),\n});\n\n// ============================================================================\n// TypeScript Type Exports\n// ============================================================================\n\n/**\n * Type-safe filter operators for use in TypeScript.\n * \n * @example\n * ```typescript\n * type UserFilter = Filter;\n * \n * const filter: UserFilter = {\n * age: { $gte: 18 },\n * email: { $contains: \"@example.com\" }\n * };\n * ```\n */\nexport type Filter = {\n [K in keyof T]?: \n | T[K] // Implicit equality\n | {\n $eq?: T[K];\n $ne?: T[K];\n $gt?: T[K] extends number | Date ? T[K] : never;\n $gte?: T[K] extends number | Date ? T[K] : never;\n $lt?: T[K] extends number | Date ? T[K] : never;\n $lte?: T[K] extends number | Date ? T[K] : never;\n $in?: T[K][];\n $nin?: T[K][];\n $between?: T[K] extends number | Date ? [T[K], T[K]] : never;\n $contains?: T[K] extends string ? string : never;\n $notContains?: T[K] extends string ? string : never;\n $startsWith?: T[K] extends string ? string : never;\n $endsWith?: T[K] extends string ? string : never;\n $null?: boolean;\n $exists?: boolean;\n }\n | (T[K] extends object ? Filter : never); // Nested relation\n} & {\n $and?: Filter[];\n $or?: Filter[];\n $not?: Filter;\n};\n\n/**\n * Scalar types supported by the filter system.\n */\nexport type Scalar = string | number | boolean | Date | null;\n\n// Export inferred types\nexport type FieldOperators = z.infer;\nexport type QueryFilter = z.infer;\n\n// ============================================================================\n// Normalization Utilities (Internal Representation)\n// ============================================================================\n\n/**\n * Normalized filter AST structure.\n * This is the internal representation after converting all syntactic sugar\n * to explicit operators.\n * \n * Stage 1: Normalization Pass\n * Input: { age: 18, role: \"admin\" }\n * Output: { $and: [{ age: { $eq: 18 } }, { role: { $eq: \"admin\" } }] }\n * \n * This simplifies adapter implementation by providing a consistent structure.\n */\nexport const NormalizedFilterSchema: z.ZodType = z.lazy(() => \n z.object({\n $and: z.array(\n z.union([\n // Field condition: { field: { $op: value } }\n z.record(z.string(), FieldOperatorsSchema),\n // Nested logical group\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $or: z.array(\n z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $not: z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ]).optional(),\n })\n);\n\nexport type NormalizedFilter = z.infer;\n\n// ============================================================================\n// AST Array Format Detection & Validation\n// ============================================================================\n\n/**\n * Set of valid AST comparison operators (case-insensitive).\n * Used by `isFilterAST()` to validate AST structure beyond `Array.isArray`.\n */\nexport const VALID_AST_OPERATORS = new Set([\n '=', '==', '!=', '<>', '>', '>=', '<', '<=',\n 'in', 'nin', 'not_in',\n 'contains', 'notcontains', 'not_contains', 'like',\n 'startswith', 'starts_with',\n 'endswith', 'ends_with',\n 'between',\n 'is_null', 'is_not_null',\n]);\n\n/**\n * Detect whether a value is a valid Filter AST array structure.\n *\n * A valid AST is one of:\n * - Comparison node: `[field: string, operator: string, value: unknown]` where operator is a known operator\n * - Logical node: `[\"and\" | \"or\", ...children]` where children are valid AST nodes\n * - Legacy flat array: `[[cond], [cond], ...]` where all elements are sub-arrays (each a valid AST node)\n *\n * This replaces the naïve `Array.isArray(filter)` check, preventing accidental\n * misidentification of arbitrary arrays as filter ASTs.\n *\n * @example\n * isFilterAST([\"status\", \"=\", \"active\"]) // true\n * isFilterAST([\"and\", [\"a\", \"=\", 1], [\"b\", \">\", 2]]) // true\n * isFilterAST([[\"a\", \"=\", 1], [\"b\", \"=\", 2]]) // true (legacy)\n * isFilterAST([1, 2, 3]) // false\n * isFilterAST(\"not an array\") // false\n * isFilterAST({ status: \"active\" }) // false\n */\nexport function isFilterAST(filter: unknown): boolean {\n if (!Array.isArray(filter) || filter.length === 0) return false;\n\n const first = filter[0];\n\n // Logical node: [\"and\", ...] or [\"or\", ...]\n if (typeof first === 'string') {\n const lower = first.toLowerCase();\n if (lower === 'and' || lower === 'or') {\n return filter.length >= 2 && filter.slice(1).every((child: unknown) => isFilterAST(child));\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof filter[1] === 'string') {\n return VALID_AST_OPERATORS.has(filter[1].toLowerCase());\n }\n }\n\n // Legacy flat array: [[cond], [cond], ...]\n if (filter.every((item: unknown) => isFilterAST(item))) {\n return filter.length > 0;\n }\n\n return false;\n}\n\n// ============================================================================\n// AST Array → FilterCondition Conversion\n// ============================================================================\n\n/**\n * Operator mapping from AST infix operators to FilterCondition `$`-prefixed operators.\n */\nconst AST_OPERATOR_MAP: Record = {\n '=': '$eq',\n '==': '$eq',\n '!=': '$ne',\n '<>': '$ne',\n '>': '$gt',\n '>=': '$gte',\n '<': '$lt',\n '<=': '$lte',\n 'in': '$in',\n 'nin': '$nin',\n 'not_in': '$nin',\n 'contains': '$contains',\n 'notcontains': '$notContains',\n 'not_contains': '$notContains',\n 'like': '$contains',\n 'startswith': '$startsWith',\n 'starts_with': '$startsWith',\n 'endswith': '$endsWith',\n 'ends_with': '$endsWith',\n 'between': '$between',\n 'is_null': '$null',\n 'is_not_null': '$null',\n};\n\n/**\n * Convert a single AST comparison node `[field, operator, value]` to a FilterCondition object.\n */\nfunction convertComparison(node: [string, string, unknown]): FilterCondition {\n const [field, operator, value] = node;\n const op = operator.toLowerCase();\n\n // Special case: equality shorthand\n if (op === '=' || op === '==') {\n return { [field]: value } as FilterCondition;\n }\n\n // Null check operators\n if (op === 'is_null') {\n return { [field]: { $null: true } } as FilterCondition;\n }\n if (op === 'is_not_null') {\n return { [field]: { $null: false } } as FilterCondition;\n }\n\n const mapped = AST_OPERATOR_MAP[op];\n if (mapped) {\n return { [field]: { [mapped]: value } } as FilterCondition;\n }\n\n // Fallback: use the operator as-is with $ prefix\n return { [field]: { [`$${op}`]: value } } as FilterCondition;\n}\n\n/**\n * Parse a filter from AST array format to FilterCondition object format.\n *\n * The AST array format is used by the ObjectUI client and the `FilterBuilder`:\n * - Comparison: `[field, operator, value]` → `{ field: value }` or `{ field: { $op: value } }`\n * - Logical AND: `[\"and\", cond1, cond2, ...]` → `{ $and: [...] }`\n * - Logical OR: `[\"or\", cond1, cond2, ...]` → `{ $or: [...] }`\n *\n * If the input is already a FilterCondition object (not an array), it is returned as-is.\n * If the input is `null` or `undefined`, it is returned as-is.\n *\n * @example\n * // Simple condition\n * parseFilterAST([\"status\", \"=\", \"active\"])\n * // → { status: \"active\" }\n *\n * @example\n * // Compound AND\n * parseFilterAST([\"and\", [\"priority\", \"=\", \"high\"], [\"status\", \"=\", \"active\"]])\n * // → { $and: [{ priority: \"high\" }, { status: \"active\" }] }\n *\n * @example\n * // Object passthrough\n * parseFilterAST({ status: \"active\" })\n * // → { status: \"active\" }\n */\nexport function parseFilterAST(filter: unknown): FilterCondition | undefined {\n if (filter == null) return undefined;\n if (!Array.isArray(filter)) return filter as FilterCondition;\n if (filter.length === 0) return undefined;\n\n const first = filter[0];\n\n // Logical node: [\"and\", cond1, cond2, ...] or [\"or\", cond1, cond2, ...]\n if (typeof first === 'string' && (first.toLowerCase() === 'and' || first.toLowerCase() === 'or')) {\n const logicOp = `$${first.toLowerCase()}` as '$and' | '$or';\n const children = filter.slice(1).map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { [logicOp]: children } as FilterCondition;\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof first === 'string') {\n return convertComparison(filter as [string, string, unknown]);\n }\n\n // Legacy flat array: [[field, op, val], [field, op, val], ...]\n // All elements are sub-arrays → treat as implicit AND\n if (filter.every((item: unknown) => Array.isArray(item))) {\n const children = filter.map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { $and: children } as FilterCondition;\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Constants & Metadata\n// ============================================================================\n\n/**\n * All supported operator keys.\n * Useful for validation and parsing.\n */\nexport const FILTER_OPERATORS = [\n // Equality\n '$eq', '$ne',\n // Comparison\n '$gt', '$gte', '$lt', '$lte',\n // Set & Range\n '$in', '$nin', '$between',\n // String\n '$contains', '$notContains', '$startsWith', '$endsWith',\n // Special\n '$null', '$exists',\n] as const;\n\n/**\n * Logical operator keys.\n */\nexport const LOGICAL_OPERATORS = ['$and', '$or', '$not'] as const;\n\n/**\n * All operator keys (field + logical).\n */\nexport const ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS] as const;\n\nexport type FilterOperatorKey = typeof FILTER_OPERATORS[number];\nexport type LogicalOperatorKey = typeof LOGICAL_OPERATORS[number];\nexport type OperatorKey = typeof ALL_OPERATORS[number];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\n\n/**\n * Sort Node\n * Represents \"Order By\".\n */\nexport const SortNodeSchema = z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc']).default('asc')\n});\n\n/**\n * Aggregation Function Enum\n * Standard aggregation functions for data analysis.\n * \n * Supported Functions:\n * - **count**: Count rows (SQL: COUNT(*) or COUNT(field))\n * - **sum**: Sum numeric values (SQL: SUM(field))\n * - **avg**: Average numeric values (SQL: AVG(field))\n * - **min**: Minimum value (SQL: MIN(field))\n * - **max**: Maximum value (SQL: MAX(field))\n * - **count_distinct**: Count unique values (SQL: COUNT(DISTINCT field))\n * - **array_agg**: Aggregate values into array (SQL: ARRAY_AGG(field))\n * - **string_agg**: Concatenate values (SQL: STRING_AGG(field, delimiter))\n * \n * Performance Considerations:\n * - COUNT(*) is typically faster than COUNT(field) as it doesn't check for nulls\n * - COUNT DISTINCT may require additional memory for tracking unique values\n * - Window aggregates (with OVER clause) can be more efficient than subqueries\n * - Large GROUP BY operations benefit from proper indexing on grouped fields\n * \n * @example\n * // SQL: SELECT region, SUM(amount) FROM sales GROUP BY region\n * {\n * object: 'sales',\n * fields: ['region'],\n * aggregations: [\n * { function: 'sum', field: 'amount', alias: 'total_sales' }\n * ],\n * groupBy: ['region']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT COUNT(Id) FROM Account\n * {\n * object: 'account',\n * aggregations: [\n * { function: 'count', alias: 'total_accounts' }\n * ]\n * }\n */\nexport const AggregationFunction = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'array_agg', 'string_agg'\n]);\n\n/**\n * Aggregation Node\n * Represents an aggregated field with function.\n * \n * Aggregations summarize data across groups of rows (GROUP BY).\n * Used with `groupBy` to create analytical queries.\n * \n * @example\n * // SQL: SELECT customer_id, COUNT(*), SUM(amount) FROM orders GROUP BY customer_id\n * {\n * object: 'order',\n * fields: ['customer_id'],\n * aggregations: [\n * { function: 'count', alias: 'order_count' },\n * { function: 'sum', field: 'amount', alias: 'total_amount' }\n * ],\n * groupBy: ['customer_id']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT LeadSource, COUNT(Id) FROM Lead GROUP BY LeadSource\n * {\n * object: 'lead',\n * fields: ['lead_source'],\n * aggregations: [\n * { function: 'count', alias: 'lead_count' }\n * ],\n * groupBy: ['lead_source']\n * }\n */\nexport const AggregationNodeSchema = z.object({\n function: AggregationFunction.describe('Aggregation function'),\n field: z.string().optional().describe('Field to aggregate (optional for COUNT(*))'),\n alias: z.string().describe('Result column alias'),\n distinct: z.boolean().optional().describe('Apply DISTINCT before aggregation'),\n filter: FilterConditionSchema.optional().describe('Filter/Condition to apply to the aggregation (FILTER WHERE clause)'),\n});\n\n/**\n * Join Type Enum\n * Standard SQL join types for combining tables.\n * \n * Join Types:\n * - **inner**: Returns only matching rows from both tables (SQL: INNER JOIN)\n * - **left**: Returns all rows from left table, matching rows from right (SQL: LEFT JOIN)\n * - **right**: Returns all rows from right table, matching rows from left (SQL: RIGHT JOIN)\n * - **full**: Returns all rows from both tables (SQL: FULL OUTER JOIN)\n * \n * @example\n * // SQL: SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * on: ['order.customer_id', '=', 'customer.id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL-style: Find all customers and their orders (if any)\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * on: ['customer.id', '=', 'order.customer_id']\n * }\n * ]\n * }\n */\nexport const JoinType = z.enum(['inner', 'left', 'right', 'full']);\n\n/**\n * Join Execution Strategy\n * Hints to the query engine on how to execute the join.\n * \n * Strategies:\n * - **auto**: Engine decides best strategy (Default).\n * - **database**: Push down join to the database (Requires same datasource).\n * - **hash**: Load both sets into memory and hash join (Cross-datasource, memory intensive).\n * - **loop**: Nested loop lookup (N+1 safe version). (Good for small right-side lookups).\n */\nexport const JoinStrategy = z.enum(['auto', 'database', 'hash', 'loop']);\n\n/**\n * Join Node\n * Represents table joins for combining data from multiple objects.\n * \n * Joins connect related data across multiple tables using ON conditions.\n * Supports both direct object joins and subquery joins.\n * \n * @example\n * // SQL: SELECT o.*, c.name FROM orders o INNER JOIN customers c ON o.customer_id = c.id\n * {\n * object: 'order',\n * fields: ['id', 'amount'],\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Multi-table join\n * // SELECT * FROM orders o\n * // INNER JOIN customers c ON o.customer_id = c.id\n * // LEFT JOIN shipments s ON o.id = s.order_id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * },\n * {\n * type: 'left',\n * object: 'shipment',\n * alias: 's',\n * on: ['order.id', '=', 's.order_id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT Name, (SELECT LastName FROM Contacts) FROM Account\n * {\n * object: 'account',\n * fields: ['name'],\n * joins: [\n * {\n * type: 'left',\n * object: 'contact',\n * on: ['account.id', '=', 'contact.account_id']\n * }\n * ]\n * }\n * \n * @example\n * // Subquery Join: Join with a filtered/aggregated dataset\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * alias: 'high_value_orders',\n * on: ['customer.id', '=', 'high_value_orders.customer_id'],\n * subquery: {\n * object: 'order',\n * fields: ['customer_id', 'total'],\n * filters: ['total', '>', 1000]\n * }\n * }\n * ]\n * }\n */\nexport const JoinNodeSchema: z.ZodType = z.lazy(() => \n z.object({\n type: JoinType.describe('Join type'),\n strategy: JoinStrategy.optional().describe('Execution strategy hint'),\n object: z.string().describe('Object/table to join'),\n alias: z.string().optional().describe('Table alias'),\n on: FilterConditionSchema.describe('Join condition'),\n subquery: z.lazy(() => QuerySchema).optional().describe('Subquery instead of object'),\n })\n);\n\n/**\n * Window Function Enum\n * Advanced analytical functions for row-based calculations.\n * \n * Window Functions:\n * - **row_number**: Sequential number within partition (SQL: ROW_NUMBER() OVER (...))\n * - **rank**: Rank with gaps for ties (SQL: RANK() OVER (...))\n * - **dense_rank**: Rank without gaps (SQL: DENSE_RANK() OVER (...))\n * - **percent_rank**: Relative rank as percentage (SQL: PERCENT_RANK() OVER (...))\n * - **lag**: Access previous row value (SQL: LAG(field) OVER (...))\n * - **lead**: Access next row value (SQL: LEAD(field) OVER (...))\n * - **first_value**: First value in window (SQL: FIRST_VALUE(field) OVER (...))\n * - **last_value**: Last value in window (SQL: LAST_VALUE(field) OVER (...))\n * - **sum/avg/count/min/max**: Aggregates over window (SQL: SUM(field) OVER (...))\n * \n * @example\n * // SQL: SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) as rank\n * // FROM orders\n * {\n * object: 'order',\n * fields: ['id', 'customer_id', 'amount'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'rank',\n * over: {\n * partitionBy: ['customer_id'],\n * orderBy: [{ field: 'amount', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Running total with SUM() OVER (...)\n * {\n * object: 'transaction',\n * fields: ['date', 'amount'],\n * windowFunctions: [\n * {\n * function: 'sum',\n * field: 'amount',\n * alias: 'running_total',\n * over: {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: 'UNBOUNDED PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunction = z.enum([\n 'row_number', 'rank', 'dense_rank', 'percent_rank',\n 'lag', 'lead', 'first_value', 'last_value',\n 'sum', 'avg', 'count', 'min', 'max'\n]);\n\n/**\n * Window Specification\n * Defines PARTITION BY and ORDER BY for window functions.\n * \n * Window specifications control how window functions compute values:\n * - **partitionBy**: Divide rows into groups (like GROUP BY but without collapsing rows)\n * - **orderBy**: Define order for ranking and offset functions\n * - **frame**: Specify which rows to include in aggregate calculations\n * \n * @example\n * // Partition by department, order by salary\n * {\n * partitionBy: ['department'],\n * orderBy: [{ field: 'salary', order: 'desc' }]\n * }\n * \n * @example\n * // Moving average with frame specification\n * {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: '6 PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n */\nexport const WindowSpecSchema = z.object({\n partitionBy: z.array(z.string()).optional().describe('PARTITION BY fields'),\n orderBy: z.array(SortNodeSchema).optional().describe('ORDER BY specification'),\n frame: z.object({\n type: z.enum(['rows', 'range']).optional(),\n start: z.string().optional().describe('Frame start (e.g., \"UNBOUNDED PRECEDING\", \"1 PRECEDING\")'),\n end: z.string().optional().describe('Frame end (e.g., \"CURRENT ROW\", \"1 FOLLOWING\")'),\n }).optional().describe('Window frame specification'),\n});\n\n/**\n * Window Function Node\n * Represents window function with OVER clause.\n * \n * Window functions perform calculations across a set of rows related to the current row,\n * without collapsing the result set (unlike GROUP BY aggregations).\n * \n * @example\n * // SQL: Top 3 products per category\n * // SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as rank\n * // FROM products\n * {\n * object: 'product',\n * fields: ['name', 'category', 'sales'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'category_rank',\n * over: {\n * partitionBy: ['category'],\n * orderBy: [{ field: 'sales', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Year-over-year comparison with LAG\n * {\n * object: 'monthly_sales',\n * fields: ['month', 'revenue'],\n * windowFunctions: [\n * {\n * function: 'lag',\n * field: 'revenue',\n * alias: 'prev_year_revenue',\n * over: {\n * orderBy: [{ field: 'month', order: 'asc' }]\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunctionNodeSchema = z.object({\n function: WindowFunction.describe('Window function name'),\n field: z.string().optional().describe('Field to operate on (for aggregate window functions)'),\n alias: z.string().describe('Result column alias'),\n over: WindowSpecSchema.describe('Window specification (OVER clause)'),\n});\n\n/**\n * Field Selection Node\n * Represents \"Select\" attributes, including joins.\n */\nexport const FieldNodeSchema: z.ZodType = z.lazy(() => \n z.union([\n z.string(), // Primitive field: \"name\"\n z.object({\n field: z.string(), // Relationship field: \"owner\"\n fields: z.array(FieldNodeSchema).optional(), // Nested select: [\"name\", \"email\"]\n alias: z.string().optional()\n })\n ])\n);\n\n/**\n * Full-Text Search Configuration\n * Defines full-text search parameters for text queries.\n * \n * Supports:\n * - Multi-field search\n * - Relevance scoring\n * - Fuzzy matching\n * - Language-specific analyzers\n * \n * @example\n * {\n * query: \"John Smith\",\n * fields: [\"name\", \"email\", \"description\"],\n * fuzzy: true,\n * boost: { \"name\": 2.0, \"email\": 1.5 }\n * }\n */\nexport const FullTextSearchSchema = z.object({\n query: z.string().describe('Search query text'),\n fields: z.array(z.string()).optional().describe('Fields to search in (if not specified, searches all text fields)'),\n fuzzy: z.boolean().optional().default(false).describe('Enable fuzzy matching (tolerates typos)'),\n operator: z.enum(['and', 'or']).optional().default('or').describe('Logical operator between terms'),\n boost: z.record(z.string(), z.number()).optional().describe('Field-specific relevance boosting (field name -> boost factor)'),\n minScore: z.number().optional().describe('Minimum relevance score threshold'),\n language: z.string().optional().describe('Language for text analysis (e.g., \"en\", \"zh\", \"es\")'),\n highlight: z.boolean().optional().default(false).describe('Enable search result highlighting'),\n});\n\nexport type FullTextSearch = z.infer;\n\n/**\n * Query AST Schema\n * The universal data retrieval contract defined in `ast-structure.mdx`.\n * \n * This schema represents ObjectQL - a universal query language that abstracts\n * SQL, NoSQL, and SaaS APIs into a single unified interface.\n * \n * Updates (v2):\n * - Aligned with modern ORM standards (Prisma/TypeORM)\n * - Added `cursor` based pagination support\n * - Renamed `top`/`skip` to `limit`/`offset`\n * - Unified filtering syntax with `FilterConditionSchema`\n * \n * Updates (v3):\n * - Added `search` parameter for full-text search (P2 requirement)\n * \n * @example\n * // Simple query: SELECT name, email FROM account WHERE status = 'active'\n * {\n * object: 'account',\n * fields: ['name', 'email'],\n * where: { status: 'active' }\n * }\n * \n * @example\n * // Pagination with Limit/Offset\n * {\n * object: 'post',\n * where: { published: true },\n * orderBy: [{ field: 'created_at', order: 'desc' }],\n * limit: 20,\n * offset: 40\n * }\n * \n * @example\n * // Full-text search\n * {\n * object: 'article',\n * search: {\n * query: \"machine learning\",\n * fields: [\"title\", \"content\"],\n * fuzzy: true,\n * boost: { \"title\": 2.0 }\n * },\n * limit: 10\n * }\n */\nconst BaseQuerySchema = z.object({\n /** Target Entity */\n object: z.string().describe('Object name (e.g. account)'),\n \n /** Select Clause */\n fields: z.array(FieldNodeSchema).optional().describe('Fields to retrieve'),\n \n /** Where Clause (Filtering) */\n where: FilterConditionSchema.optional().describe('Filtering criteria (WHERE)'),\n \n /** Full-Text Search */\n search: FullTextSearchSchema.optional().describe('Full-text search configuration ($search parameter)'),\n \n /** Order By Clause (Sorting) */\n orderBy: z.array(SortNodeSchema).optional().describe('Sorting instructions (ORDER BY)'),\n \n /** Pagination */\n limit: z.number().optional().describe('Max records to return (LIMIT)'),\n offset: z.number().optional().describe('Records to skip (OFFSET)'),\n top: z.number().optional().describe('Alias for limit (OData compatibility)'),\n cursor: z.record(z.string(), z.unknown()).optional().describe('Cursor for keyset pagination'),\n \n /** Joins */\n joins: z.array(JoinNodeSchema).optional().describe('Explicit Table Joins'),\n \n /** Aggregations */\n aggregations: z.array(AggregationNodeSchema).optional().describe('Aggregation functions'),\n \n /** Group By Clause */\n groupBy: z.array(z.string()).optional().describe('GROUP BY fields'),\n \n /** Having Clause */\n having: FilterConditionSchema.optional().describe('HAVING clause for aggregation filtering'),\n \n /** Window Functions */\n windowFunctions: z.array(WindowFunctionNodeSchema).optional().describe('Window functions with OVER clause'),\n \n /** Subquery flag */\n distinct: z.boolean().optional().describe('SELECT DISTINCT flag'),\n});\n\n/**\n * QueryAST — Abstract Syntax Tree for data queries.\n *\n * The `expand` property enables recursive loading of related records through\n * lookup and master_detail fields. Each key is a relationship field name; the\n * value is a nested QueryAST that can further filter, select, sort, and expand\n * the related records (up to a default max depth of 3).\n *\n * @example\n * ```ts\n * const ast: QueryAST = {\n * object: 'task',\n * fields: ['title', 'assignee'],\n * expand: {\n * assignee: { object: 'user', fields: ['name', 'email'] },\n * project: {\n * object: 'project',\n * expand: { org: { object: 'org' } } // nested expand\n * }\n * }\n * };\n * ```\n */\nexport type QueryAST = z.infer & {\n expand?: Record;\n};\n\nexport type QueryInput = z.input & {\n expand?: Record;\n};\n\nexport const QuerySchema: z.ZodType = BaseQuerySchema.extend({\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional().describe(\n 'Recursive relation loading map. Keys are lookup/master_detail field names; '\n + 'values are nested QueryAST objects that control select, filter, sort, and '\n + 'further expansion on the related object. The engine resolves expand via '\n + 'batch $in queries (driver-agnostic) with a default max depth of 3.'\n ),\n});\n\nexport type SortNode = z.infer;\nexport type AggregationNode = z.infer;\nexport type JoinNode = z.infer;\nexport type WindowFunctionNode = z.infer;\nexport type WindowSpec = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # ObjectStack Validation Protocol\n * \n * This module defines the validation schema protocol for ObjectStack, providing a comprehensive\n * type-safe validation system similar to Salesforce's validation rules but with enhanced capabilities.\n * \n * ## Overview\n * \n * Validation rules are applied at the data layer to ensure data integrity and enforce business logic.\n * The system supports multiple validation types:\n * \n * 1. **Script Validation**: Formula-based validation using expressions\n * 2. **Uniqueness Validation**: Enforce unique constraints across fields\n * 3. **State Machine Validation**: Control allowed state transitions\n * 4. **Format Validation**: Validate field formats (email, URL, regex, etc.)\n * 5. **Cross-Field Validation**: Validate relationships between multiple fields\n * 6. **Async Validation**: Remote validation via API calls\n * 7. **Custom Validation**: User-defined validation functions\n * 8. **Conditional Validation**: Apply validations based on conditions\n * \n * ## Salesforce Comparison\n * \n * ObjectStack validation rules are inspired by Salesforce validation rules but enhanced:\n * - Salesforce: Formula-based validation with `Error Condition Formula`\n * - ObjectStack: Multiple validation types with composable rules\n * \n * Example Salesforce validation rule:\n * ```\n * Rule Name: Discount_Cannot_Exceed_40_Percent\n * Error Condition Formula: Discount_Percent__c > 0.40\n * Error Message: Discount cannot exceed 40%.\n * ```\n * \n * Equivalent ObjectStack rule:\n * ```typescript\n * {\n * type: 'script',\n * name: 'discount_cannot_exceed_40_percent',\n * condition: 'discount_percent > 0.40',\n * message: 'Discount cannot exceed 40%',\n * severity: 'error'\n * }\n * ```\n */\n\n/**\n * Base Validation Rule\n * \n * All validation rules extend from this base schema with common properties.\n * \n * ## Industry Standard Enhancements\n * - **Label/Description**: Essential for governance in large systems with thousands of rules.\n * - **Events**: granular control over validation timing (Context-aware validation).\n * - **Tags**: categorization for reporting and management.\n */\nconst BaseValidationSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label for the rule listing'),\n description: z.string().optional().describe('Administrative notes explaining the business reason'),\n \n // Execution Control\n active: z.boolean().default(true),\n events: z.array(z.enum(['insert', 'update', 'delete'])).default(['insert', 'update']).describe('Validation contexts'),\n priority: z.number().int().min(0).max(9999).default(100).describe('Execution priority (lower runs first, default: 100)'),\n \n // Classification\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g., \"compliance\", \"billing\")'),\n \n // Feedback\n severity: z.enum(['error', 'warning', 'info']).default('error'),\n message: z.string().describe('Error message to display to the user'),\n});\n\n/**\n * 1. Script/Expression Validation\n * Generic formula-based validation.\n */\nexport const ScriptValidationSchema = BaseValidationSchema.extend({\n type: z.literal('script'),\n condition: z.string().describe('Formula expression. If TRUE, validation fails. (e.g. amount < 0)'),\n});\n\n/**\n * 2. Uniqueness Validation\n * specialized optimized check for unique constraints.\n */\nexport const UniquenessValidationSchema = BaseValidationSchema.extend({\n type: z.literal('unique'),\n fields: z.array(z.string()).describe('Fields that must be combined unique'),\n scope: z.string().optional().describe('Formula condition for scope (e.g. active = true)'),\n caseSensitive: z.boolean().default(true),\n});\n\n/**\n * 3. State Machine Validation\n * State transition logic.\n */\nexport const StateMachineValidationSchema = BaseValidationSchema.extend({\n type: z.literal('state_machine'),\n field: z.string().describe('State field (e.g. status)'),\n transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'),\n});\n\n/**\n * 4. Value Format Validation\n * Regex or specialized formats.\n */\nexport const FormatValidationSchema = BaseValidationSchema.extend({\n type: z.literal('format'),\n field: z.string(),\n regex: z.string().optional(),\n format: z.enum(['email', 'url', 'phone', 'json']).optional(),\n});\n\n/**\n * 5. Cross-Field Validation\n * Validates relationships between multiple fields.\n * \n * ## Use Cases\n * - Date range validations (end_date > start_date)\n * - Amount comparisons (discount < total)\n * - Complex business rules involving multiple fields\n * \n * ## Salesforce Examples\n * \n * ### Example 1: Close Date Must Be In Current or Future Month\n * **Salesforce Formula:**\n * ```\n * MONTH(CloseDate) < MONTH(TODAY()) ||\n * YEAR(CloseDate) < YEAR(TODAY())\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'close_date_future',\n * condition: 'MONTH(close_date) >= MONTH(TODAY()) AND YEAR(close_date) >= YEAR(TODAY())',\n * fields: ['close_date'],\n * message: 'Close Date must be in the current or a future month'\n * }\n * ```\n * \n * ### Example 2: Discount Validation\n * **Salesforce Formula:**\n * ```\n * Discount__c > (Amount__c * 0.40)\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'discount_limit',\n * condition: 'discount > (amount * 0.40)',\n * fields: ['discount', 'amount'],\n * message: 'Discount cannot exceed 40% of the amount'\n * }\n * ```\n * \n * ### Example 3: Opportunity Must Have Products\n * **Salesforce Formula:**\n * ```\n * ISBLANK(Products__c) && ISPICKVAL(StageName, \"Closed Won\")\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'products_required_for_won',\n * condition: 'products = null AND stage = \"closed_won\"',\n * fields: ['products', 'stage'],\n * message: 'Opportunity must have products to be marked as Closed Won'\n * }\n * ```\n */\nexport const CrossFieldValidationSchema = BaseValidationSchema.extend({\n type: z.literal('cross_field'),\n condition: z.string().describe('Formula expression comparing fields (e.g. \"end_date > start_date\")'),\n fields: z.array(z.string()).describe('Fields involved in the validation'),\n});\n\n/**\n * 6. JSON Structure Validation\n * Validates JSON fields against a JSON Schema.\n * \n * ## Use Cases\n * - Validating configuration objects stored in JSON fields\n * - Enforcing API payload structures\n * - Complex nested data validation\n */\nexport const JSONValidationSchema = BaseValidationSchema.extend({\n type: z.literal('json_schema'),\n field: z.string().describe('JSON field to validate'),\n schema: z.record(z.string(), z.unknown()).describe('JSON Schema object definition'),\n});\n\n/**\n * 7. Async Validation\n * Remote validation via API call or database query.\n * \n * ## Use Cases\n * \n * ### 1. Email Uniqueness Check\n * Check if an email address is already registered in the system.\n * ```typescript\n * {\n * type: 'async',\n * name: 'unique_email',\n * field: 'email',\n * validatorUrl: '/api/users/check-email',\n * message: 'This email address is already registered',\n * debounce: 500, // Wait 500ms after user stops typing\n * timeout: 3000\n * }\n * ```\n * \n * ### 2. Username Availability\n * Verify username is available before form submission.\n * ```typescript\n * {\n * type: 'async',\n * name: 'username_available',\n * field: 'username',\n * validatorUrl: '/api/users/check-username',\n * message: 'This username is already taken',\n * debounce: 300,\n * timeout: 2000\n * }\n * ```\n * \n * ### 3. Tax ID Validation\n * Validate tax ID with government API (e.g., IRS, HMRC).\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_tax_id',\n * field: 'tax_id',\n * validatorFunction: 'validateTaxIdWithIRS',\n * message: 'Invalid Tax ID number',\n * timeout: 10000, // Government APIs may be slow\n * params: { country: 'US', format: 'EIN' }\n * }\n * ```\n * \n * ### 4. Credit Card Validation\n * Verify credit card with payment gateway without charging.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_card',\n * field: 'card_number',\n * validatorUrl: 'https://api.stripe.com/v1/tokens/validate',\n * message: 'Invalid credit card number',\n * timeout: 5000,\n * params: { \n * mode: 'validate_only',\n * checkFunds: false \n * }\n * }\n * ```\n * \n * ### 5. Address Validation\n * Validate and standardize addresses using geocoding services.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_address',\n * field: 'street_address',\n * validatorFunction: 'validateAddressWithGoogleMaps',\n * message: 'Unable to verify address',\n * timeout: 4000,\n * params: {\n * includeFields: ['city', 'state', 'zip'],\n * strictMode: true,\n * country: 'US'\n * }\n * }\n * ```\n * \n * ### 6. Domain Name Availability\n * Check if domain name is available for registration.\n * ```typescript\n * {\n * type: 'async',\n * name: 'domain_available',\n * field: 'domain_name',\n * validatorUrl: '/api/domains/check-availability',\n * message: 'This domain is already taken or reserved',\n * debounce: 500,\n * timeout: 2000\n * }\n * ```\n * \n * ### 7. Coupon Code Validation\n * Verify coupon code is valid and not expired.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_coupon',\n * field: 'coupon_code',\n * validatorUrl: '/api/coupons/validate',\n * message: 'Invalid or expired coupon code',\n * timeout: 2000,\n * params: {\n * checkExpiration: true,\n * checkUsageLimit: true,\n * userId: '{{current_user_id}}'\n * }\n * }\n * ```\n */\nexport const AsyncValidationSchema = BaseValidationSchema.extend({\n type: z.literal('async'),\n field: z.string().describe('Field to validate'),\n validatorUrl: z.string().optional().describe('External API endpoint for validation'),\n method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method for external call'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for the request'),\n validatorFunction: z.string().optional().describe('Reference to custom validator function'),\n timeout: z.number().optional().default(5000).describe('Timeout in milliseconds'),\n debounce: z.number().optional().describe('Debounce delay in milliseconds'),\n params: z.record(z.string(), z.unknown()).optional().describe('Additional parameters to pass to validator'),\n});\n\n/**\n * 8. Custom Validator Function\n * User-defined validation logic with code reference.\n */\nexport const CustomValidatorSchema = BaseValidationSchema.extend({\n type: z.literal('custom'),\n handler: z.string().describe('Name of the custom validation function registered in the system'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the custom handler'),\n});\n\n/**\n * 9. Master Validation Rule Schema\n */\n/** Base type for validation rules - used for z.lazy() recursive type annotation */\nexport interface BaseValidationRuleShape {\n type: string;\n name: string;\n message: string;\n label?: string;\n description?: string;\n active?: boolean;\n events?: ('insert' | 'update' | 'delete')[];\n priority?: number;\n tags?: string[];\n severity?: 'error' | 'warning' | 'info';\n [key: string]: unknown;\n}\n\nexport const ValidationRuleSchema: z.ZodType = z.lazy(() =>\n z.discriminatedUnion('type', [\n ScriptValidationSchema,\n UniquenessValidationSchema,\n StateMachineValidationSchema,\n FormatValidationSchema,\n CrossFieldValidationSchema,\n JSONValidationSchema,\n AsyncValidationSchema,\n CustomValidatorSchema,\n ConditionalValidationSchema,\n ])\n);\n\n/**\n * 8. Conditional Validation\n * Validation that only applies when a condition is met.\n * \n * ## Overview\n * Conditional validations follow the pattern: \"Validate X only if Y is true\"\n * This allows for context-aware validation rules that adapt to different scenarios.\n * \n * ## Use Cases\n * \n * ### 1. Validate Based on Record Type\n * Apply different validation rules based on the type of record.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_approval_required',\n * when: 'account_type = \"enterprise\"',\n * message: 'Enterprise validation',\n * then: {\n * type: 'script',\n * name: 'require_approval',\n * message: 'Enterprise accounts require manager approval',\n * condition: 'approval_status = null'\n * }\n * }\n * ```\n * \n * ### 2. Conditional Field Requirements\n * Require certain fields only when specific conditions are met.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'shipping_address_when_required',\n * when: 'requires_shipping = true',\n * message: 'Shipping validation',\n * then: {\n * type: 'script',\n * name: 'shipping_address_required',\n * message: 'Shipping address is required for physical products',\n * condition: 'shipping_address = null OR shipping_address = \"\"'\n * }\n * }\n * ```\n * \n * ### 3. Amount-Based Validation\n * Apply different rules based on transaction amount.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'high_value_approval',\n * when: 'order_total > 10000',\n * message: 'High value order validation',\n * then: {\n * type: 'script',\n * name: 'manager_approval_required',\n * message: 'Orders over $10,000 require manager approval',\n * condition: 'manager_approval_id = null'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'standard_validation',\n * message: 'Payment method is required',\n * condition: 'payment_method = null'\n * }\n * }\n * ```\n * \n * ### 4. Regional Compliance\n * Apply region-specific validation rules.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'regional_compliance',\n * when: 'region = \"EU\"',\n * message: 'EU compliance validation',\n * then: {\n * type: 'script',\n * name: 'gdpr_consent',\n * message: 'GDPR consent is required for EU customers',\n * condition: 'gdpr_consent_given = false'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'tos_acceptance',\n * message: 'Terms of Service acceptance required',\n * condition: 'tos_accepted = false'\n * }\n * }\n * ```\n * \n * ### 5. Nested Conditional Validation\n * Create complex validation logic with nested conditions.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'country_state_validation',\n * when: 'country = \"US\"',\n * message: 'US-specific validation',\n * then: {\n * type: 'conditional',\n * name: 'california_validation',\n * when: 'state = \"CA\"',\n * message: 'California-specific validation',\n * then: {\n * type: 'script',\n * name: 'ca_tax_id_required',\n * message: 'California requires a valid tax ID',\n * condition: 'tax_id = null OR NOT(REGEX(tax_id, \"^\\\\d{2}-\\\\d{7}$\"))'\n * }\n * }\n * }\n * ```\n * \n * ### 6. Tax Validation for Taxable Items\n * Only validate tax fields when the item is taxable.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'tax_field_validation',\n * when: 'is_taxable = true',\n * message: 'Tax validation',\n * then: {\n * type: 'script',\n * name: 'tax_code_required',\n * message: 'Tax code is required for taxable items',\n * condition: 'tax_code = null OR tax_code = \"\"'\n * }\n * }\n * ```\n * \n * ### 7. Role-Based Validation\n * Apply validation based on user role.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'role_based_approval_limit',\n * when: 'user_role = \"manager\"',\n * message: 'Manager approval limits',\n * then: {\n * type: 'script',\n * name: 'manager_limit',\n * message: 'Managers can approve up to $50,000',\n * condition: 'approval_amount > 50000'\n * }\n * }\n * ```\n * \n * ## Salesforce Pattern Comparison\n * \n * Salesforce doesn't have explicit \"conditional validation\" rules but achieves similar\n * behavior using formula logic. ObjectStack makes this pattern explicit and composable.\n * \n * **Salesforce Approach:**\n * ```\n * IF(\n * ISPICKVAL(Type, \"Enterprise\"),\n * AND(Amount > 100000, ISBLANK(Approval__c)),\n * FALSE\n * )\n * ```\n * \n * **ObjectStack Approach:**\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_high_value',\n * when: 'type = \"enterprise\"',\n * then: {\n * type: 'cross_field',\n * name: 'amount_approval',\n * condition: 'amount > 100000 AND approval = null',\n * fields: ['amount', 'approval']\n * }\n * }\n * ```\n */\nexport const ConditionalValidationSchema = BaseValidationSchema.extend({\n type: z.literal('conditional'),\n when: z.string().describe('Condition formula (e.g. \"type = \\'enterprise\\'\")'),\n then: ValidationRuleSchema.describe('Validation rule to apply when condition is true'),\n otherwise: ValidationRuleSchema.optional().describe('Validation rule to apply when condition is false'),\n});\n\nexport type ValidationRule = z.infer;\nexport type ScriptValidation = z.infer;\nexport type UniquenessValidation = z.infer;\nexport type StateMachineValidation = z.infer;\nexport type FormatValidation = z.infer;\nexport type CrossFieldValidation = z.infer;\nexport type JSONValidation = z.infer;\nexport type AsyncValidation = z.infer;\nexport type CustomValidation = z.infer;\nexport type ConditionalValidation = z.infer;", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * XState-inspired State Machine Protocol\n * Used to define strict business logic constraints and lifecycle management.\n * Prevent AI \"hallucinations\" by enforcing valid valid transitions.\n */\n\n// --- Primitives ---\n\n/**\n * References a named action (side effect)\n * Can be a script, a webhook, or a field update.\n */\nexport const ActionRefSchema = z.union([\n z.string().describe('Action Name'),\n z.object({\n type: z.string(), // e.g., 'xstate.assign', 'log', 'email'\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n/**\n * References a named condition (guard)\n * Must evaluate to true for the transition to occur.\n */\nexport const GuardRefSchema = z.union([\n z.string().describe('Guard Name (e.g., \"isManager\", \"amountGT1000\")'),\n z.object({\n type: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n// --- Core Structure ---\n\n/**\n * State Transition Definition\n * \"When EVENT happens, if GUARD is true, go to TARGET and run ACTIONS\"\n */\nexport const TransitionSchema = z.object({\n target: z.string().optional().describe('Target State ID'),\n cond: GuardRefSchema.optional().describe('Condition (Guard) required to take this path'),\n actions: z.array(ActionRefSchema).optional().describe('Actions to execute during transition'),\n description: z.string().optional().describe('Human readable description of this rule'),\n});\n\n/**\n * Event Definition (Signals)\n */\nexport const EventSchema = z.object({\n type: z.string().describe('Event Type (e.g. \"APPROVE\", \"REJECT\", \"Submit\")'),\n // Payload validation schema could go here if we want deep validation\n schema: z.record(z.string(), z.unknown()).optional().describe('Expected event payload structure'),\n});\n\nexport type ActionRef = z.infer;\nexport type Transition = z.infer;\n\nexport type StateNodeConfig = {\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n entry?: ActionRef[];\n exit?: ActionRef[];\n on?: Record;\n always?: Transition[];\n initial?: string;\n states?: Record;\n meta?: {\n label?: string;\n description?: string;\n color?: string;\n aiInstructions?: string;\n };\n};\n\n/**\n * State Node Definition\n */\nexport const StateNodeSchema: z.ZodType = z.lazy(() => z.object({\n /** Type of state */\n type: z.enum(['atomic', 'compound', 'parallel', 'final', 'history']).default('atomic'),\n \n /** Entry/Exit Actions */\n entry: z.array(ActionRefSchema).optional().describe('Actions to run when entering this state'),\n exit: z.array(ActionRefSchema).optional().describe('Actions to run when leaving this state'),\n \n /** Transitions (Events) */\n on: z.record(z.string(), z.union([\n z.string(), // Shorthand target\n TransitionSchema, \n z.array(TransitionSchema)\n ])).optional().describe('Map of Event Type -> Transition Definition'),\n \n /** Always Transitions (Eventless) */\n always: z.array(TransitionSchema).optional(),\n\n /** Nesting (Hierarchical States) */\n initial: z.string().optional().describe('Initial child state (if compound)'),\n states: z.record(z.string(), StateNodeSchema).optional(),\n \n /** Metadata for UI/AI */\n meta: z.object({\n label: z.string().optional(),\n description: z.string().optional(),\n color: z.string().optional(), // For UI diagrams\n // Instructions for AI Agent when in this state\n aiInstructions: z.string().optional().describe('Specific instructions for AI when in this state'),\n }).optional(),\n}));\n\n/**\n * Top-Level State Machine Definition\n */\nexport const StateMachineSchema = z.object({\n id: SnakeCaseIdentifierSchema.describe('Unique Machine ID'),\n description: z.string().optional(),\n \n /** Context (Memory) Schema */\n contextSchema: z.record(z.string(), z.unknown()).optional().describe('Zod Schema for the machine context/memory'),\n \n /** Initial State */\n initial: z.string().describe('Initial State ID'),\n \n /** State Definitions */\n states: z.record(z.string(), StateNodeSchema).describe('State Nodes'),\n \n /** Global Listeners */\n on: z.record(z.string(), z.union([z.string(), TransitionSchema, z.array(TransitionSchema)])).optional(),\n});\n\nexport type StateMachineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from './field.zod';\nimport { ValidationRuleSchema } from './validation.zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\nimport { ActionSchema } from '../ui/action.zod';\n\n/**\n * API Operations Enum\n */\nexport const ApiMethod = z.enum([\n 'get', 'list', // Read\n 'create', 'update', 'delete', // Write\n 'upsert', // Idempotent Write\n 'bulk', // Batch operations\n 'aggregate', // Analytics (count, sum)\n 'history', // Audit access\n 'search', // Search access\n 'restore', 'purge', // Trash management\n 'import', 'export', // Data portability\n]);\nexport type ApiMethod = z.infer;\n\n/**\n * Capability Flags\n * Defines what system features are enabled for this object.\n * \n * Optimized based on industry standards (Salesforce, ServiceNow):\n * - Added `activities` (Tasks/Events)\n * - Added `mru` (Recent Items)\n * - Added `feeds` (Social/Chatter)\n * - Grouped API permissions\n * \n * @example\n * {\n * trackHistory: true,\n * searchable: true,\n * apiEnabled: true,\n * files: true\n * }\n */\nexport const ObjectCapabilities = z.object({\n /** Enable history tracking (Audit Trail) */\n trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),\n \n /** Enable global search indexing */\n searchable: z.boolean().default(true).describe('Index records for global search'),\n \n /** Enable REST/GraphQL API access */\n apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),\n\n /** \n * API Supported Operations\n * Granular control over API exposure.\n */\n apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),\n \n /** Enable standard attachments/files engine */\n files: z.boolean().default(false).describe('Enable file attachments and document management'),\n \n /** Enable social collaboration (Comments, Mentions, Feeds) */\n feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),\n \n /** Enable standard Activity suite (Tasks, Calendars, Events) */\n activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),\n \n /** Enable Recycle Bin / Soft Delete */\n trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),\n\n /** Enable \"Recently Viewed\" tracking */\n mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),\n \n /** Allow cloning records */\n clone: z.boolean().default(true).describe('Allow record deep cloning'),\n});\n\n/**\n * Schema for database indexes.\n * Enhanced with additional index types and configuration options\n * \n * @example\n * {\n * name: \"idx_account_name\",\n * fields: [\"name\"],\n * type: \"btree\",\n * unique: true\n * }\n */\nexport const IndexSchema = z.object({\n name: z.string().optional().describe('Index name (auto-generated if not provided)'),\n fields: z.array(z.string()).describe('Fields included in the index'),\n type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),\n unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),\n partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),\n});\n\n/**\n * Search Configuration\n * Defines how this object behaves in search results.\n * \n * @example\n * {\n * fields: [\"name\", \"email\", \"phone\"],\n * displayFields: [\"name\", \"title\"],\n * filters: [\"status = 'active'\"]\n * }\n */\nexport const SearchConfigSchema = z.object({\n fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),\n displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),\n filters: z.array(z.string()).optional().describe('Default filters for search results'),\n});\n\n/**\n * Multi-Tenancy Configuration Schema\n * Configures tenant isolation strategy for SaaS applications\n * \n * @example Shared database with tenant_id isolation\n * {\n * enabled: true,\n * strategy: 'shared',\n * tenantField: 'tenant_id',\n * crossTenantAccess: false\n * }\n */\nexport const TenancyConfigSchema = z.object({\n enabled: z.boolean().describe('Enable multi-tenancy for this object'),\n strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),\n tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),\n crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),\n});\n\n/**\n * Soft Delete Configuration Schema\n * Implements recycle bin / trash functionality\n * \n * @example Standard soft delete with cascade\n * {\n * enabled: true,\n * field: 'deleted_at',\n * cascadeDelete: true\n * }\n */\nexport const SoftDeleteConfigSchema = z.object({\n enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),\n field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),\n cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),\n});\n\n/**\n * Versioning Configuration Schema\n * Implements record versioning and history tracking\n * \n * @example Snapshot versioning with 90-day retention\n * {\n * enabled: true,\n * strategy: 'snapshot',\n * retentionDays: 90,\n * versionField: 'version'\n * }\n */\nexport const VersioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable record versioning'),\n strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),\n retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),\n versionField: z.string().default('version').describe('Field name for version number/timestamp'),\n});\n\n/**\n * Partitioning Strategy Schema\n * Configures table partitioning for performance at scale\n * \n * @example Range partitioning by date (monthly)\n * {\n * enabled: true,\n * strategy: 'range',\n * key: 'created_at',\n * interval: '1 month'\n * }\n */\nexport const PartitioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable table partitioning'),\n strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),\n key: z.string().describe('Field name to partition by'),\n interval: z.string().optional().describe('Partition interval for range strategy (e.g., \"1 month\", \"1 year\")'),\n}).refine((data) => {\n // If strategy is 'range', interval must be provided\n if (data.strategy === 'range' && !data.interval) {\n return false;\n }\n return true;\n}, {\n message: 'interval is required when strategy is \"range\"',\n});\n\n/**\n * Change Data Capture (CDC) Configuration Schema\n * Enables real-time data streaming to external systems\n * \n * @example Stream all changes to Kafka\n * {\n * enabled: true,\n * events: ['insert', 'update', 'delete'],\n * destination: 'kafka://events.objectstack'\n * }\n */\nexport const CDCConfigSchema = z.object({\n enabled: z.boolean().describe('Enable Change Data Capture'),\n events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),\n destination: z.string().describe('Destination endpoint (e.g., \"kafka://topic\", \"webhook://url\")'),\n});\n\n/**\n * Base Object Schema Definition\n * \n * The Blueprint of a Business Object.\n * Represents a table, a collection, or a virtual entity.\n * \n * @example\n * ```yaml\n * name: project_task\n * label: Project Task\n * icon: task\n * fields:\n * project:\n * type: lookup\n * reference: project\n * status:\n * type: select\n * options: [todo, in_progress, done]\n * enable:\n * trackHistory: true\n * files: true\n * ```\n */\nconst ObjectSchemaBase = z.object({\n /** \n * Identity & Metadata \n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),\n label: z.string().optional().describe('Human readable singular label (e.g. \"Account\")'),\n pluralLabel: z.string().optional().describe('Human readable plural label (e.g. \"Accounts\")'),\n description: z.string().optional().describe('Developer documentation / description'),\n icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),\n \n /**\n * Namespace & Domain Classification\n * \n * Groups objects into logical domains for routing, permissions, and discovery.\n * System objects use `'sys'`; business packages use their own namespace.\n * \n * When set, `tableName` is auto-derived as `{namespace}_{name}` by\n * `ObjectSchema.create()` unless an explicit `tableName` is provided.\n * \n * Namespace must be a single lowercase word (no underscores or hyphens)\n * to ensure clean auto-derivation of `{namespace}_{name}` table names.\n * \n * @example namespace: 'sys' → tableName defaults to 'sys_user'\n * @example namespace: 'crm' → tableName defaults to 'crm_account'\n */\n namespace: z.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace — single lowercase word (e.g. \"sys\", \"crm\"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'),\n\n /**\n * Taxonomy & Organization\n */\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g. \"sales\", \"system\", \"reference\")'),\n active: z.boolean().optional().default(true).describe('Is the object active and usable'),\n isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),\n abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),\n\n /** \n * Storage & Virtualization \n */\n datasource: z.string().optional().default('default').describe('Target Datasource ID. \"default\" is the primary DB.'),\n tableName: z.string().optional().describe('Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set.'),\n \n /** \n * Data Model \n */\n fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {\n message: 'Field names must be lowercase snake_case (e.g., \"first_name\", \"company\", \"annual_revenue\")',\n }), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),\n indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),\n \n /**\n * Advanced Data Management\n */\n \n // Multi-tenancy configuration\n tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),\n \n // Soft delete configuration\n softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),\n \n // Versioning configuration\n versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),\n \n // Partitioning strategy\n partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),\n \n // Change Data Capture\n cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),\n \n /**\n * Logic & Validation (Co-located)\n * Best Practice: Define rules close to data.\n */\n validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),\n \n /**\n * State Machine(s)\n * Named record of state machines, where each key is a unique machine identifier.\n * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).\n * \n * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }\n */\n stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),\n\n /** \n * Display & UI Hints (Data-Layer)\n */\n displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., \"name\", \"title\"). Defaults to \"name\" if present.'),\n recordName: z.object({\n type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),\n displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., \"CASE-{0000}\", \"INV-{YYYY}-{0000}\")'),\n startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),\n }).optional().describe('Record name generation configuration (Salesforce pattern)'),\n titleFormat: z.string().optional().describe('Title expression (e.g. \"{name} - {code}\"). Overrides displayNameField.'),\n compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),\n \n /** \n * Search Engine Config \n */\n search: SearchConfigSchema.optional().describe('Search engine configuration'),\n \n /** \n * System Capabilities \n */\n enable: ObjectCapabilities.optional().describe('Enabled system features modules'),\n\n /** Record Types */\n recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),\n\n /** Sharing Model */\n sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),\n\n /** Key Prefix */\n keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., \"001\" for Account)'),\n\n /**\n * Object Actions\n * \n * Actions associated with this object. Populated automatically by `defineStack()`\n * when top-level actions specify `objectName` matching this object.\n * Can also be defined directly on the object.\n * \n * Aligns with Salesforce/ServiceNow patterns where actions are part of the\n * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)\n * include the action list without requiring downstream merge.\n */\n actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),\n});\n\n/**\n * Converts a snake_case name to a human-readable Title Case label.\n * @example snakeCaseToLabel('project_task') → 'Project Task'\n */\nfunction snakeCaseToLabel(name: string): string {\n return name\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n}\n\n/**\n * Enhanced ObjectSchema with Factory\n */\nexport const ObjectSchema = Object.assign(ObjectSchemaBase, {\n /**\n * Type-safe factory for creating business object definitions.\n * \n * Enhancements over raw schema:\n * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).\n * - **Validation**: Runs Zod `.parse()` to validate the config at creation time.\n * \n * @example\n * ```ts\n * const Task = ObjectSchema.create({\n * name: 'project_task',\n * // label auto-generated as 'Project Task'\n * fields: {\n * subject: { type: 'text', label: 'Subject', required: true },\n * },\n * });\n * ```\n */\n create: >(config: T): Omit & Pick => {\n const withDefaults = {\n ...config,\n label: config.label ?? snakeCaseToLabel(config.name),\n // Auto-derive tableName as {namespace}_{name} when namespace is set\n tableName: config.tableName ?? (config.namespace ? `${config.namespace}_${config.name}` : undefined),\n };\n return ObjectSchemaBase.parse(withDefaults) as Omit & Pick;\n },\n});\n\nexport type ServiceObject = z.infer;\nexport type ServiceObjectInput = z.input;\nexport type ObjectCapabilities = z.infer;\nexport type ObjectIndex = z.infer;\nexport type TenancyConfig = z.infer;\nexport type SoftDeleteConfig = z.infer;\nexport type VersioningConfig = z.infer;\nexport type PartitioningConfig = z.infer;\nexport type CDCConfig = z.infer;\n\n// =================================================================\n// Object Ownership Model\n// =================================================================\n\n/**\n * How a package relates to an object it references.\n * \n * - `own`: This package is the original author/owner of the object.\n * Only one package may own a given object name. The owner defines\n * the base schema (table name, primary key, core fields).\n * \n * - `extend`: This package adds fields, views, or actions to an\n * existing object owned by another package. Multiple packages\n * may extend the same object. Extensions are merged at boot time.\n * \n * Follows Salesforce/ServiceNow patterns:\n * object name = database table name, globally unique, no namespace prefix.\n */\nexport const ObjectOwnershipEnum = z.enum(['own', 'extend']);\nexport type ObjectOwnership = z.infer;\n\n/**\n * Object Extension Entry — used in `objectExtensions` array.\n * Declares fields/config to merge into an existing object owned by another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact', // target object FQN\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\nexport const ObjectExtensionSchema = z.object({\n /** The target object name (FQN) to extend */\n extend: z.string().describe('Target object name (FQN) to extend'),\n \n /** Fields to merge into the target object (additive) */\n fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),\n \n /** Override label */\n label: z.string().optional().describe('Override label for the extended object'),\n \n /** Override plural label */\n pluralLabel: z.string().optional().describe('Override plural label for the extended object'),\n \n /** Override description */\n description: z.string().optional().describe('Override description for the extended object'),\n \n /** Additional validation rules to add */\n validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),\n \n /** Additional indexes to add */\n indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),\n \n /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */\n priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),\n});\n\nexport type ObjectExtension = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Hook Lifecycle Events\n * Defines the interception points in the ObjectQL execution pipeline.\n */\nexport const HookEvent = z.enum([\n // Read Operations\n 'beforeFind', 'afterFind',\n 'beforeFindOne', 'afterFindOne',\n 'beforeCount', 'afterCount',\n 'beforeAggregate', 'afterAggregate',\n\n // Write Operations\n 'beforeInsert', 'afterInsert',\n 'beforeUpdate', 'afterUpdate',\n 'beforeDelete', 'afterDelete',\n \n // Bulk Operations (Query-based)\n 'beforeUpdateMany', 'afterUpdateMany',\n 'beforeDeleteMany', 'afterDeleteMany',\n]);\n\n/**\n * Hook Definition Schema\n * \n * Hooks serve as the \"Logic Layer\" in ObjectStack, allowing developers to \n * inject custom code during the data access lifecycle.\n * \n * Use cases:\n * - Data Enrichment (Default values, Calculated fields)\n * - Validation (Complex business rules)\n * - Side Effects (Sending emails, Syncing to external systems)\n * - Security (Filtering data based on context)\n */\nexport const HookSchema = z.object({\n /**\n * Unique identifier for the hook\n * Required for debugging and overriding.\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Hook unique name (snake_case)'),\n\n /**\n * Human readable label\n */\n label: z.string().optional().describe('Description of what this hook does'),\n\n /**\n * Target Object(s)\n * can be:\n * - Single object: \"account\"\n * - List of objects: [\"account\", \"contact\"]\n * - Wildcard: \"*\" (All objects)\n */\n object: z.union([z.string(), z.array(z.string())]).describe('Target object(s)'),\n\n /**\n * Events to subscribe to\n * Combinations of timing (before/after) and action (find/insert/update/delete/etc)\n */\n events: z.array(HookEvent).describe('Lifecycle events'),\n\n /**\n * Handler Logic\n * Reference to a registered function in the plugin system OR a direct function (runtime only).\n */\n handler: z.union([z.string(), z.function()]).optional().describe('Handler function name (string) or inline function reference'),\n\n /**\n * Execution Order\n * Lower numbers run first.\n * - System Hooks: 0-99\n * - App Hooks: 100-999\n * - User Hooks: 1000+\n */\n priority: z.number().default(100).describe('Execution priority'),\n\n /**\n * Async / Background Execution\n * If true, the hook runs in the background and does not block the transaction.\n * Only applicable for 'after*' events.\n * Default: false (Blocking)\n */\n async: z.boolean().default(false).describe('Run specifically as fire-and-forget'),\n\n /**\n * Declarative Condition\n * Formula expression evaluated before the handler runs.\n * If provided and evaluates to FALSE, the hook is skipped entirely.\n * Useful for filtering by record data without writing handler code.\n * \n * @example \"status = 'active' AND amount > 1000\"\n */\n condition: z.string().optional().describe('Formula expression; hook runs only when TRUE (e.g., \"status = \\'closed\\' AND amount > 1000\")'),\n\n /**\n * Human-readable description\n */\n description: z.string().optional().describe('Human-readable description of what this hook does'),\n\n /**\n * Retry Policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().default(3).describe('Maximum retry attempts on failure'),\n backoffMs: z.number().default(1000).describe('Backoff delay between retries in milliseconds'),\n }).optional().describe('Retry policy for failed hook executions'),\n\n /**\n * Execution Timeout\n */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds before the hook is aborted'),\n\n /**\n * Error Policy\n * What to do if the hook throws an exception?\n * - abort: Rollback transaction (if blocking)\n * - log: Log error and continue\n */\n onError: z.enum(['abort', 'log']).default('abort').describe('Error handling strategy'),\n});\n\n/**\n * Hook Runtime Context\n * Defines what is available to the hook handler during execution.\n * \n * Best Practices:\n * - **Immutability**: `object`, `event`, `id` are immutable.\n * - **Mutability**: `input` and `result` are mutable to allow transformation.\n * - **Encapsulation**: `session` isolates auth info; `transaction` ensures atomicity.\n */\nexport const HookContextSchema = z.object({\n /** Tracing ID */\n id: z.string().optional().describe('Unique execution ID for tracing'),\n\n /** Target Object Name */\n object: z.string(),\n \n /** Current Lifecycle Event */\n event: HookEvent,\n\n /** \n * Input Parameters (Mutable)\n * Modify this to change the behavior of the operation.\n * \n * - find: { query: QueryAST, options: DriverOptions }\n * - insert: { doc: Record, options: DriverOptions }\n * - update: { id: ID, doc: Record, options: DriverOptions }\n * - delete: { id: ID, options: DriverOptions }\n * - updateMany: { query: QueryAST, doc: Record, options: DriverOptions }\n * - deleteMany: { query: QueryAST, options: DriverOptions }\n */\n input: z.record(z.string(), z.unknown()).describe('Mutable input parameters'),\n\n /** \n * Operation Result (Mutable)\n * Available in 'after*' events. Modify this to transform the output.\n */\n result: z.unknown().optional().describe('Operation result (After hooks only)'),\n\n /**\n * Data Snapshot\n * The state of the record BEFORE the operation (for update/delete).\n */\n previous: z.record(z.string(), z.unknown()).optional().describe('Record state before operation'),\n\n /**\n * Execution Session\n * Contains authentication and tenancy information.\n */\n session: z.object({\n userId: z.string().optional(),\n tenantId: z.string().optional(),\n roles: z.array(z.string()).optional(),\n accessToken: z.string().optional(),\n }).optional().describe('Current session context'),\n \n /**\n * Transaction Handle\n * If the operation is part of a transaction, use this handle for side-effects.\n */\n transaction: z.unknown().optional().describe('Database transaction handle'),\n\n /**\n * Engine Access\n * Reference to the ObjectQL engine for performing side effects.\n */\n ql: z.unknown().describe('ObjectQL Engine Reference'),\n\n /**\n * Cross-Object API\n * Provides a scoped data access interface for performing CRUD operations\n * on other objects within hooks. Bound to the current execution context\n * (userId, tenantId, transaction).\n *\n * Usage in hooks:\n * const users = ctx.api.object('user');\n * const admin = await users.findOne({ filter: { role: 'admin' } });\n */\n api: z.unknown().optional().describe('Cross-object data access (ScopedContext)'),\n\n /**\n * Current User Info\n * Convenience shortcut for session.userId + additional user metadata.\n * Populated by the engine when available.\n */\n user: z.object({\n id: z.string().optional(),\n name: z.string().optional(),\n email: z.string().optional(),\n }).optional().describe('Current user info shortcut'),\n});\n\nexport type Hook = z.input;\nexport type ResolvedHook = z.output;\nexport type HookEventType = z.infer;\nexport type HookContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { QuerySchema } from './query.zod';\n\n/**\n * Transformation Logic\n * Built-in helpers for converting data during import.\n */\nexport const TransformType = z.enum([\n 'none', // Direct copy\n 'constant', // Use a hardcoded value\n 'lookup', // Resolve FK (Name -> ID)\n 'split', // \"John Doe\" -> [\"John\", \"Doe\"]\n 'join', // [\"John\", \"Doe\"] -> \"John Doe\"\n 'javascript', // Custom script (Review security!)\n 'map' // Value mapping (e.g. \"Active\" -> \"active\")\n]);\n\n/**\n * Field Mapping Item\n */\nexport const FieldMappingSchema = z.object({\n /** Source Column */\n source: z.union([z.string(), z.array(z.string())]).describe('Source column header(s)'),\n \n /** Target Field */\n target: z.union([z.string(), z.array(z.string())]).describe('Target object field(s)'),\n \n /** Transformation */\n transform: TransformType.default('none'),\n \n /** Configuration for transform */\n params: z.object({\n // Constant\n value: z.unknown().optional(),\n \n // Lookup\n object: z.string().optional(), // Lookup Object\n fromField: z.string().optional(), // Match on (e.g. \"name\")\n toField: z.string().optional(), // Value to take (e.g. \"id\")\n autoCreate: z.boolean().optional(), // Create if missing\n \n // Map\n valueMap: z.record(z.string(), z.unknown()).optional(), // { \"Open\": \"draft\" }\n \n // Split/Join\n separator: z.string().optional()\n }).optional()\n});\n\n/**\n * Data Mapping Schema\n * Defines a reusable data mapping configuration for ETL operations.\n * \n * **NAMING CONVENTION:**\n * Mapping names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good mapping names\n * - 'salesforce_to_crm'\n * - 'csv_import_contacts'\n * - 'api_sync_orders'\n * \n * @example Bad mapping names (will be rejected)\n * - 'SalesforceToCRM' (PascalCase)\n * - 'CSV Import' (spaces)\n */\nexport const MappingSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Mapping unique name (lowercase snake_case)'),\n label: z.string().optional(),\n \n /** Scope */\n sourceFormat: z.enum(['csv', 'json', 'xml', 'sql']).default('csv'),\n targetObject: z.string().describe('Target Object Name'),\n \n /** Column Mappings */\n fieldMapping: z.array(FieldMappingSchema),\n \n /** Upsert Logic */\n mode: z.enum(['insert', 'update', 'upsert']).default('insert'),\n upsertKey: z.array(z.string()).optional().describe('Fields to match for upsert (e.g. email)'),\n \n /** Extract Logic (For Export) */\n extractQuery: QuerySchema.optional().describe('Query to run for export only'),\n \n /** Error Handling */\n errorPolicy: z.enum(['skip', 'abort', 'retry']).default('skip'),\n batchSize: z.number().default(1000)\n});\n\nexport type Mapping = z.infer;\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Execution Context Schema\n * \n * Defines the runtime context that flows from HTTP request → data operations.\n * This is the \"identity + environment\" envelope that every data operation can carry.\n * \n * Design:\n * - All fields are optional for backward compatibility\n * - `isSystem` bypasses permission checks (for internal/migration operations)\n * - `transaction` carries the database transaction handle for atomicity\n * - `traceId` enables distributed tracing across microservices\n * \n * Usage:\n * engine.find('account', { context: { userId: '...', tenantId: '...' } })\n */\nexport const ExecutionContextSchema = z.object({\n /** Current user ID (resolved from session) */\n userId: z.string().optional(),\n \n /** Current organization/tenant ID (resolved from session.activeOrganizationId) */\n tenantId: z.string().optional(),\n \n /** User role names (resolved from Member + Role) */\n roles: z.array(z.string()).default([]),\n \n /** Aggregated permission names (resolved from PermissionSet) */\n permissions: z.array(z.string()).default([]),\n \n /** Whether this is a system-level operation (bypasses permission checks) */\n isSystem: z.boolean().default(false),\n \n /** Raw access token (for external API call pass-through) */\n accessToken: z.string().optional(),\n \n /** Database transaction handle */\n transaction: z.unknown().optional(),\n \n /** Request trace ID (for distributed tracing) */\n traceId: z.string().optional(),\n});\n\nexport type ExecutionContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\nimport { SortNodeSchema, QuerySchema, FullTextSearchSchema, FieldNodeSchema, AggregationNodeSchema } from './query.zod';\nimport { ExecutionContextSchema } from '../kernel/execution-context.zod';\n\n/**\n * Data Engine Protocol\n * \n * Defines the standard interface for data persistence engines in ObjectStack.\n * This protocol abstracts the underlying storage mechanism (SQL, NoSQL, API, Memory),\n * allowing the ObjectQL engine to execute standardized CRUD and Aggregation operations\n * regardless of where the data resides.\n * \n * The Data Engine acts as the \"Driver\" layer in the Hexagonal Architecture.\n */\n\n// ==========================================================================\n// 1. Shared Definitions\n// ==========================================================================\n\n/**\n * Data Engine Query filter conditions\n * Supports simple key-value map or complex Logic/Field expressions (DSL)\n */\nexport const DataEngineFilterSchema = z.union([\n z.record(z.string(), z.unknown()),\n FilterConditionSchema\n]).describe('Data Engine query filter conditions');\n\n/**\n * Sort order definition\n * Supports:\n * - { name: 'asc' }\n * - { name: 1 }\n * - [{ field: 'name', order: 'asc' }]\n */\nexport const DataEngineSortSchema = z.union([\n z.record(z.string(), z.enum(['asc', 'desc'])), \n z.record(z.string(), z.union([z.literal(1), z.literal(-1)])),\n z.array(SortNodeSchema)\n]).describe('Sort order definition');\n\n// ==========================================================================\n// 1b. Base Engine Options (shared context)\n// ==========================================================================\n\n/**\n * Base Engine Options\n * \n * All Data Engine operation options extend this schema to carry\n * an optional ExecutionContext for identity, tenant, and transaction propagation.\n */\nexport const BaseEngineOptionsSchema = z.object({\n /** Execution context (identity, tenant, transaction) */\n context: ExecutionContextSchema.optional(),\n});\n\n// ==========================================================================\n// 2. method: FIND (QueryAST-aligned)\n// ==========================================================================\n\n/**\n * Engine Query Options — QueryAST-aligned parameters for IDataEngine.find/findOne.\n * \n * Uses standard QueryAST field names (where/fields/orderBy/limit/offset/expand)\n * so that no mechanical translation is needed between the Engine and Driver layers.\n * \n * @example\n * ```ts\n * engine.find('account', {\n * where: { status: 'active' },\n * fields: ['id', 'name', 'email'],\n * orderBy: [{ field: 'name', order: 'asc' }],\n * limit: 10,\n * offset: 20,\n * expand: { owner: { object: 'user', fields: ['name'] } },\n * });\n * ```\n */\nexport const EngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions (WHERE) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n\n /** Fields to retrieve (SELECT) — standard QueryAST `fields` */\n fields: z.array(FieldNodeSchema).optional(),\n\n /** Sorting instructions (ORDER BY) — standard QueryAST `orderBy` */\n orderBy: z.array(SortNodeSchema).optional(),\n\n /** Max records to return (LIMIT) */\n limit: z.number().optional(),\n\n /** Records to skip (OFFSET) — standard QueryAST `offset` */\n offset: z.number().optional(),\n\n /** Alias for limit (OData compatibility) */\n top: z.number().optional(),\n\n /** Cursor for keyset pagination */\n cursor: z.record(z.string(), z.unknown()).optional(),\n\n /** Full-text search configuration */\n search: FullTextSearchSchema.optional(),\n\n /**\n * Recursive relation loading map (expand).\n * \n * Keys are lookup/master_detail field names; values are nested QueryAST\n * objects that control select, filter, sort, and further expansion on\n * the related object. The engine resolves expand via batch $in queries\n * (driver-agnostic) with a default max depth of 3.\n */\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional(),\n\n /** SELECT DISTINCT flag */\n distinct: z.boolean().optional(),\n}).describe('QueryAST-aligned query options for IDataEngine.find() operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineQueryOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineQueryOptionsSchema` instead.\n * This schema uses legacy parameter names (filter/select/sort/skip/populate)\n * that require mechanical translation to QueryAST. Migrate to the\n * QueryAST-aligned `EngineQueryOptionsSchema` (where/fields/orderBy/offset/expand).\n */\nexport const DataEngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineQueryOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n /** @deprecated Use `fields` (EngineQueryOptionsSchema) */\n select: z.array(z.string()).optional(),\n /** @deprecated Use `orderBy` (EngineQueryOptionsSchema) */\n sort: DataEngineSortSchema.optional(),\n limit: z.number().int().min(1).optional(),\n /** @deprecated Use `offset` (EngineQueryOptionsSchema) */\n skip: z.number().int().min(0).optional(),\n top: z.number().int().min(1).optional(),\n /** @deprecated Use `expand` (EngineQueryOptionsSchema) */\n populate: z.array(z.string()).optional(),\n}).describe('Query options for IDataEngine.find() operations');\n\n// ==========================================================================\n// 3. method: INSERT\n// ==========================================================================\n\nexport const DataEngineInsertOptionsSchema = BaseEngineOptionsSchema.extend({\n /** \n * Return the inserted record(s)? \n * Some drivers support RETURNING clause for efficiency.\n * Default: true\n */\n returning: z.boolean().default(true).optional(),\n}).describe('Options for DataEngine.insert operations');\n\n// ==========================================================================\n// 4. method: UPDATE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions to identify records to update — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Perform an upsert? If true, insert if not found. */\n upsert: z.boolean().default(false).optional(),\n /** Update multiple records? If false, only the first match is updated. Default: false */\n multi: z.boolean().default(false).optional(),\n /** Return the updated record(s)? Default: false (returns update count/status) */\n returning: z.boolean().default(false).optional(),\n}).describe('QueryAST-aligned options for DataEngine.update operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineUpdateOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineUpdateOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineUpdateOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n upsert: z.boolean().default(false).optional(),\n multi: z.boolean().default(false).optional(),\n returning: z.boolean().default(false).optional(),\n}).describe('Options for DataEngine.update operations');\n\n// ==========================================================================\n// 5. method: DELETE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions to identify records to delete — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Delete multiple records? If false, only the first match is deleted. Default: false */\n multi: z.boolean().default(false).optional(),\n}).describe('QueryAST-aligned options for DataEngine.delete operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineDeleteOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineDeleteOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineDeleteOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n multi: z.boolean().default(false).optional(),\n}).describe('Options for DataEngine.delete operations');\n\n// ==========================================================================\n// 6. method: AGGREGATE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions (WHERE) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Group By fields */\n groupBy: z.array(z.string()).optional(),\n /** \n * Aggregation definitions — uses standard AggregationNodeSchema (`function` key).\n * e.g. [{ function: 'sum', field: 'amount', alias: 'total' }]\n */\n aggregations: z.array(AggregationNodeSchema).optional(),\n}).describe('QueryAST-aligned options for DataEngine.aggregate operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineAggregateOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineAggregateOptionsSchema` instead.\n * Migrate `filter` → `where`, aggregation `method` → `function`.\n */\nexport const DataEngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineAggregateOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n groupBy: z.array(z.string()).optional(),\n /** \n * @deprecated Use `EngineAggregateOptionsSchema` with standard AggregationNodeSchema (`function` key).\n */\n aggregations: z.array(z.object({\n field: z.string(),\n method: z.enum(['count', 'sum', 'avg', 'min', 'max', 'count_distinct']),\n alias: z.string().optional()\n })).optional(),\n}).describe('Options for DataEngine.aggregate operations');\n\n// ==========================================================================\n// 7. method: COUNT (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineCountOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n}).describe('QueryAST-aligned options for DataEngine.count operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineCountOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineCountOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineCountOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineCountOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n}).describe('Options for DataEngine.count operations');\n\n// ==========================================================================\n// 8. Definition (Contract)\n// ==========================================================================\n\nexport const DataEngineContractSchema = z.object({\n find: z.function()\n .input(z.tuple([z.string(), EngineQueryOptionsSchema.optional()]))\n .output(z.promise(z.array(z.unknown()))),\n \n findOne: z.function()\n .input(z.tuple([z.string(), EngineQueryOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n insert: z.function()\n .input(z.tuple([z.string(), z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]), DataEngineInsertOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n update: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), EngineUpdateOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n delete: z.function()\n .input(z.tuple([z.string(), EngineDeleteOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n count: z.function()\n .input(z.tuple([z.string(), EngineCountOptionsSchema.optional()]))\n .output(z.promise(z.number())),\n \n aggregate: z.function()\n .input(z.tuple([z.string(), EngineAggregateOptionsSchema]))\n .output(z.promise(z.array(z.unknown())))\n}).describe('Standard Data Engine Contract');\n\n// ==========================================================================\n// 9. Virtualization & RPC Protocol\n// ==========================================================================\n\n/**\n * Data Engine RPC Request (Virtual ObjectQL)\n * \n * This schema defines the serialized format for executing Data Engine operations\n * via HTTP, Message Queue, or Plugin boundaries.\n * \n * It enables \"Virtual Data Engines\" where the implementation resides in a \n * separate microservice or plugin.\n */\n\n/**\n * RPC backward-compatibility mixin — shared `@deprecated filter` field.\n * When both `filter` and `where` are present, the protocol/engine ignores\n * `filter` in favor of `where`; only one should be provided.\n */\nconst RpcLegacyFilterMixin = {\n /** @deprecated Use `where` */\n filter: DataEngineFilterSchema.optional(),\n};\n\n/**\n * RPC query options that accept BOTH new (where/fields/orderBy) and\n * legacy (filter/select/sort/skip/populate) parameter names.\n * \n * **Precedence:** When both legacy and new keys are present for the same\n * concern, the protocol normalizer uses the new key (`where` > `filter`,\n * `fields` > `select`, `orderBy` > `sort`, `offset` > `skip`,\n * `expand` > `populate`). Callers should not mix vocabularies.\n */\nconst RpcQueryOptionsSchema = EngineQueryOptionsSchema.extend({\n ...RpcLegacyFilterMixin,\n /** @deprecated Use `fields` */\n select: z.array(z.string()).optional(),\n /** @deprecated Use `orderBy` */\n sort: DataEngineSortSchema.optional(),\n /** @deprecated Use `offset` */\n skip: z.number().int().min(0).optional(),\n /** @deprecated Use `expand` */\n populate: z.array(z.string()).optional(),\n});\n\nexport const DataEngineFindRequestSchema = z.object({\n method: z.literal('find'),\n object: z.string(),\n query: RpcQueryOptionsSchema.optional()\n});\n\nexport const DataEngineFindOneRequestSchema = z.object({\n method: z.literal('findOne'),\n object: z.string(),\n query: RpcQueryOptionsSchema.optional()\n});\n\nexport const DataEngineInsertRequestSchema = z.object({\n method: z.literal('insert'),\n object: z.string(),\n data: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]),\n options: DataEngineInsertOptionsSchema.optional()\n});\n\nexport const DataEngineUpdateRequestSchema = z.object({\n method: z.literal('update'),\n object: z.string(),\n data: z.record(z.string(), z.unknown()),\n id: z.union([z.string(), z.number()]).optional().describe('ID for single update, or use where in options'),\n options: EngineUpdateOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineDeleteRequestSchema = z.object({\n method: z.literal('delete'),\n object: z.string(),\n id: z.union([z.string(), z.number()]).optional().describe('ID for single delete, or use where in options'),\n options: EngineDeleteOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineCountRequestSchema = z.object({\n method: z.literal('count'),\n object: z.string(),\n query: EngineCountOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineAggregateRequestSchema = z.object({\n method: z.literal('aggregate'),\n object: z.string(),\n query: EngineAggregateOptionsSchema.extend(RpcLegacyFilterMixin)\n});\n\n/**\n * Data Engine Execute Request (Raw Command)\n * Execute a raw command/query native to the driver (e.g. SQL, Shell, Remote API).\n */\nexport const DataEngineExecuteRequestSchema = z.object({\n method: z.literal('execute'),\n /** The abstract command (string SQL, or JSON object) */\n command: z.unknown(),\n /** Optional options */\n options: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Data Engine Vector Find Request (AI/RAG)\n * Perform a similarity search using vector embeddings.\n */\nexport const DataEngineVectorFindRequestSchema = z.object({\n method: z.literal('vectorFind'),\n object: z.string(),\n /** The vector embedding to search for */\n vector: z.array(z.number()),\n /** Optional pre-filter (Metadata filtering) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Fields to retrieve — standard QueryAST `fields` */\n fields: z.array(z.string()).optional(),\n /** Number of results */\n limit: z.number().int().default(5).optional(),\n /** Minimum similarity score (0-1) or distance threshold */\n threshold: z.number().optional()\n});\n\n/**\n * Data Engine Batch Request\n * Execute multiple operations in a single transaction/request efficiently.\n */\nexport const DataEngineBatchRequestSchema = z.object({\n method: z.literal('batch'),\n requests: z.array(z.discriminatedUnion('method', [\n DataEngineFindRequestSchema,\n DataEngineFindOneRequestSchema,\n DataEngineInsertRequestSchema,\n DataEngineUpdateRequestSchema,\n DataEngineDeleteRequestSchema,\n DataEngineCountRequestSchema,\n DataEngineAggregateRequestSchema,\n DataEngineExecuteRequestSchema,\n DataEngineVectorFindRequestSchema\n ])),\n /** \n * Transaction Mode\n * - true: All or nothing (Atomic)\n * - false: Best effort, continue on error\n */\n transaction: z.boolean().default(true).optional()\n});\n\n/**\n * Unified Data Engine Request Union\n * Use this to validate any incoming \"Virtual ObjectQL\" request.\n */\nexport const DataEngineRequestSchema = z.discriminatedUnion('method', [\n DataEngineFindRequestSchema,\n DataEngineFindOneRequestSchema,\n DataEngineInsertRequestSchema,\n DataEngineUpdateRequestSchema,\n DataEngineDeleteRequestSchema,\n DataEngineCountRequestSchema,\n DataEngineAggregateRequestSchema,\n DataEngineBatchRequestSchema,\n DataEngineExecuteRequestSchema,\n DataEngineVectorFindRequestSchema\n]).describe('Virtual ObjectQL Request Protocol');\n\n// ==========================================================================\n// 10. Type Exports\n// ==========================================================================\n\n// --- New: QueryAST-aligned types (preferred) ---\nexport type EngineQueryOptions = z.infer;\nexport type EngineUpdateOptions = z.infer;\nexport type EngineDeleteOptions = z.infer;\nexport type EngineAggregateOptions = z.infer;\nexport type EngineCountOptions = z.infer;\n\n// --- Legacy: deprecated types (kept for backward compatibility) ---\nexport type DataEngineFilter = z.infer;\n/** @deprecated Use standard `SortNode[]` from QueryAST instead. */\nexport type DataEngineSort = z.infer;\nexport type BaseEngineOptions = z.infer;\n/** @deprecated Use `EngineQueryOptions` instead. */\nexport type DataEngineQueryOptions = z.infer;\nexport type DataEngineInsertOptions = z.infer;\n/** @deprecated Use `EngineUpdateOptions` instead. */\nexport type DataEngineUpdateOptions = z.infer;\n/** @deprecated Use `EngineDeleteOptions` instead. */\nexport type DataEngineDeleteOptions = z.infer;\n/** @deprecated Use `EngineAggregateOptions` instead. */\nexport type DataEngineAggregateOptions = z.infer;\n/** @deprecated Use `EngineCountOptions` instead. */\nexport type DataEngineCountOptions = z.infer;\nexport type DataEngineRequest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { QuerySchema } from '../data/query.zod';\nimport { IsolationLevelEnum } from '../shared/enums.zod';\n\n/**\n * Common Driver Options\n * Passed to most driver methods to control behavior (transactions, timeouts, etc.)\n */\nexport const DriverOptionsSchema = z.object({\n /**\n * Transaction handle/identifier.\n * If provided, the operation must run within this transaction.\n */\n transaction: z.unknown().optional().describe('Transaction handle'),\n\n /**\n * Operation timeout in milliseconds.\n */\n timeout: z.number().optional().describe('Timeout in ms'),\n\n /**\n * Whether to bypass cache and force a fresh read.\n */\n skipCache: z.boolean().optional().describe('Bypass cache'),\n\n /**\n * Distributed Tracing Context.\n * Used for passing OpenTelemetry span context or request IDs for observability.\n */\n traceContext: z.record(z.string(), z.string()).optional().describe('OpenTelemetry context or request ID'),\n\n /**\n * Tenant Identifier.\n * For multi-tenant databases (row-level security or schema-per-tenant).\n */\n tenantId: z.string().optional().describe('Tenant Isolation identifier'),\n});\n\n/**\n * Driver Capabilities Schema\n * \n * Defines what features a database driver supports.\n * This allows ObjectQL to adapt its behavior based on underlying database capabilities.\n * Enhanced with granular capability flags for better feature detection.\n */\nexport const DriverCapabilitiesSchema = z.object({\n // ============================================================================\n // Basic CRUD Operations\n // ============================================================================\n \n /**\n * Whether the driver supports create operations.\n */\n create: z.boolean().default(true).describe('Supports CREATE operations'),\n \n /**\n * Whether the driver supports read operations.\n */\n read: z.boolean().default(true).describe('Supports READ operations'),\n \n /**\n * Whether the driver supports update operations.\n */\n update: z.boolean().default(true).describe('Supports UPDATE operations'),\n \n /**\n * Whether the driver supports delete operations.\n */\n delete: z.boolean().default(true).describe('Supports DELETE operations'),\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n \n /**\n * Whether the driver supports bulk create operations.\n */\n bulkCreate: z.boolean().default(false).describe('Supports bulk CREATE operations'),\n \n /**\n * Whether the driver supports bulk update operations.\n */\n bulkUpdate: z.boolean().default(false).describe('Supports bulk UPDATE operations'),\n \n /**\n * Whether the driver supports bulk delete operations.\n */\n bulkDelete: z.boolean().default(false).describe('Supports bulk DELETE operations'),\n\n // ============================================================================\n // Transaction & Connection Management\n // ============================================================================\n \n /**\n * Whether the driver supports database transactions.\n * If true, beginTransaction, commit, and rollback must be implemented.\n */\n transactions: z.boolean().default(false).describe('Supports ACID transactions'),\n \n /**\n * Whether the driver supports savepoints within transactions.\n */\n savepoints: z.boolean().default(false).describe('Supports transaction savepoints'),\n \n /**\n * Supported transaction isolation levels.\n */\n isolationLevels: z.array(IsolationLevelEnum).optional().describe('Supported isolation levels'),\n\n // ============================================================================\n // Query Operations\n // ============================================================================\n \n /**\n * Whether the driver supports WHERE clause filters.\n * If false, ObjectQL will fetch all records and filter in memory.\n * \n * Example: Memory driver might not support complex filter conditions.\n */\n queryFilters: z.boolean().default(true).describe('Supports WHERE clause filtering'),\n\n /**\n * Whether the driver supports aggregation functions (COUNT, SUM, AVG, etc.).\n * If false, ObjectQL will compute aggregations in memory.\n */\n queryAggregations: z.boolean().default(false).describe('Supports GROUP BY and aggregation functions'),\n\n /**\n * Whether the driver supports ORDER BY sorting.\n * If false, ObjectQL will sort results in memory.\n */\n querySorting: z.boolean().default(true).describe('Supports ORDER BY sorting'),\n\n /**\n * Whether the driver supports LIMIT/OFFSET pagination.\n * If false, ObjectQL will fetch all records and paginate in memory.\n */\n queryPagination: z.boolean().default(true).describe('Supports LIMIT/OFFSET pagination'),\n\n /**\n * Whether the driver supports window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.).\n * If false, ObjectQL will compute window functions in memory.\n */\n queryWindowFunctions: z.boolean().default(false).describe('Supports window functions with OVER clause'),\n\n /**\n * Whether the driver supports subqueries (nested SELECT statements).\n * If false, ObjectQL will execute queries separately and combine results.\n */\n querySubqueries: z.boolean().default(false).describe('Supports subqueries'),\n \n /**\n * Whether the driver supports Common Table Expressions (WITH clause).\n */\n queryCTE: z.boolean().default(false).describe('Supports Common Table Expressions (WITH clause)'),\n\n /**\n * Whether the driver supports SQL-style joins.\n * If false, ObjectQL will fetch related data separately and join in memory.\n */\n joins: z.boolean().default(false).describe('Supports SQL joins'),\n\n // ============================================================================\n // Advanced Features\n // ============================================================================\n \n /**\n * Whether the driver supports full-text search.\n * If true, text search queries can be pushed to the database.\n */\n fullTextSearch: z.boolean().default(false).describe('Supports full-text search'),\n \n /**\n * Whether the driver supports JSON querying capabilities.\n */\n jsonQuery: z.boolean().default(false).describe('Supports JSON field querying'),\n \n /**\n * Whether the driver supports geospatial queries.\n */\n geospatialQuery: z.boolean().default(false).describe('Supports geospatial queries'),\n \n /**\n * Whether the driver supports streaming large result sets.\n */\n streaming: z.boolean().default(false).describe('Supports result streaming (cursors/iterators)'),\n\n /**\n * Whether the driver supports JSON field types.\n * If false, JSON data will be serialized as strings.\n */\n jsonFields: z.boolean().default(false).describe('Supports JSON field types'),\n\n /**\n * Whether the driver supports array field types.\n * If false, arrays will be stored as JSON strings or in separate tables.\n */\n arrayFields: z.boolean().default(false).describe('Supports array field types'),\n\n /**\n * Whether the driver supports vector embeddings and similarity search.\n * Required for RAG (Retrieval-Augmented Generation) and AI features.\n */\n vectorSearch: z.boolean().default(false).describe('Supports vector embeddings and similarity search'),\n\n // ============================================================================\n // Schema Management\n // ============================================================================\n \n /**\n * Whether the driver supports automatic schema synchronization.\n */\n schemaSync: z.boolean().default(false).describe('Supports automatic schema synchronization'),\n\n /**\n * Whether the driver supports batching multiple schema sync operations\n * into a single (or fewer) round-trips for the DDL phase. When true,\n * the engine may call `syncSchemasBatch()` instead of calling\n * `syncSchema()` per object, reducing network round-trips for remote drivers.\n */\n batchSchemaSync: z.boolean().default(false).describe('Supports batched schema sync to reduce schema DDL round-trips'),\n \n /**\n * Whether the driver supports database migrations.\n */\n migrations: z.boolean().default(false).describe('Supports database migrations'),\n \n /**\n * Whether the driver supports index management.\n */\n indexes: z.boolean().default(false).describe('Supports index creation and management'),\n\n // ============================================================================\n // Performance & Optimization\n // ============================================================================\n \n /**\n * Whether the driver supports connection pooling.\n */\n connectionPooling: z.boolean().default(false).describe('Supports connection pooling'),\n \n /**\n * Whether the driver supports prepared statements.\n */\n preparedStatements: z.boolean().default(false).describe('Supports prepared statements (SQL injection prevention)'),\n \n /**\n * Whether the driver supports query result caching.\n */\n queryCache: z.boolean().default(false).describe('Supports query result caching'),\n});\n\n/**\n * Unified Database Driver Interface\n * \n * This is the contract that all storage adapters (Postgres, Mongo, Excel, Salesforce) must implement.\n * It abstracts the underlying engine, enabling ObjectStack to be \"Database Agnostic\".\n */\nexport const DriverInterfaceSchema = z.object({\n /**\n * Driver name (e.g., 'postgresql', 'mongodb', 'rest_api').\n */\n name: z.string().describe('Driver unique name'),\n\n /**\n * Driver version.\n */\n version: z.string().describe('Driver version'),\n\n /**\n * Capabilities descriptor.\n */\n supports: DriverCapabilitiesSchema,\n\n // ============================================================================\n // Lifecycle Management\n // ============================================================================\n\n /**\n * Initialize connection pool or authenticate.\n */\n connect: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.void()))\n .describe('Establish connection'),\n\n /**\n * Close connections and cleanup resources.\n */\n disconnect: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.void()))\n .describe('Close connection'),\n\n /**\n * Check connection health.\n * @returns true if healthy, false otherwise.\n */\n checkHealth: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.boolean()))\n .describe('Health check'),\n \n /**\n * Get Connection Pool Statistics.\n * Useful for monitoring database load.\n */\n getPoolStats: z.function()\n .input(z.tuple([]))\n .output(z.object({\n total: z.number(),\n idle: z.number(),\n active: z.number(),\n waiting: z.number(),\n }).optional())\n .optional()\n .describe('Get connection pool statistics'),\n\n // ============================================================================\n // Raw Execution (Escape Hatch)\n // ============================================================================\n\n /**\n * Execute a raw command/query native to the driver.\n * Useful for complex reports, stored procedures, or DDL not covered by standard sync.\n * \n * @param command - The raw command (e.g., SQL string, shell command, or remote API payload).\n * @param parameters - Optional array of bound parameters for safe execution (prevention of injection).\n * @param options - Driver options (transaction context, timeout).\n * @returns Promise resolving to the raw result from the driver.\n * \n * @example\n * // SQL Driver\n * await driver.execute('SELECT * FROM complex_view WHERE id = ?', [123]);\n * \n * // Mongo Driver\n * await driver.execute({ aggregate: 'orders', pipeline: [...] });\n */\n execute: z.function()\n .input(z.tuple([z.unknown(), z.array(z.unknown()).optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.unknown()))\n .describe('Execute raw command'),\n\n // ============================================================================\n // CRUD Operations\n // ============================================================================\n\n /**\n * Find multiple records matching the structured query.\n * Parsing the QueryAST is the responsibility of the driver implementation.\n * \n * @param object - The name of the object/table to query (e.g. 'account').\n * @param query - The structured QueryAST (filters, sorts, joins, pagination).\n * @param options - Driver options.\n * @returns Array of records.\n * \n * @example\n * await driver.find('account', {\n * filters: [['status', '=', 'active'], 'and', ['amount', '>', 500]],\n * sort: [{ field: 'created_at', order: 'desc' }],\n * top: 10\n * });\n * @returns Array of records.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n find: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown()))))\n .describe('Find records'),\n\n /**\n * Stream records matching the structured query.\n * Optimized for large datasets to avoid memory overflow.\n * \n * @param object - The name of the object.\n * @param query - The structured QueryAST.\n * @param options - Driver options.\n * @returns AsyncIterable/ReadableStream of records.\n */\n findStream: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.unknown())\n .describe('Stream records (AsyncIterable)'),\n\n /**\n * Find a single record by query.\n * Similar to find(), but returns only the first match or null.\n * \n * @param object - The name of the object.\n * @param query - QueryAST.\n * @param options - Driver options.\n * @returns The record or null.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n findOne: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown()).nullable()))\n .describe('Find one record'),\n\n /**\n * Create a new record.\n * \n * @param object - The object name.\n * @param data - Key-value map of field data.\n * @param options - Driver options.\n * @returns The created record, including server-generated fields (id, created_at, etc.).\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n create: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Create record'),\n\n /**\n * Update an existing record by ID.\n * \n * @param object - The object name.\n * @param id - The unique identifier of the record.\n * @param data - The fields to update.\n * @param options - Driver options.\n * @returns The updated record.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n update: z.function()\n .input(z.tuple([z.string(), z.string().or(z.number()), z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Update record'),\n\n /**\n * Upsert (Update or Insert) a record.\n * \n * @param object - The object name.\n * @param data - The data to upsert.\n * @param conflictKeys - Fields to check for conflict (uniqueness).\n * @param options - Driver options.\n * @returns The created or updated record.\n */\n upsert: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), z.array(z.string()).optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Upsert record'),\n\n /**\n * Delete a record by ID.\n * \n * @param object - The object name.\n * @param id - The unique identifier of the record.\n * @param options - Driver options.\n * @returns True if deleted, false if not found.\n */\n delete: z.function()\n .input(z.tuple([z.string(), z.string().or(z.number()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.boolean()))\n .describe('Delete record'),\n\n /**\n * Count records matching a query.\n * \n * @param object - The object name.\n * @param query - Optional filtering criteria.\n * @param options - Driver options.\n * @returns Total count.\n */\n count: z.function()\n .input(z.tuple([z.string(), QuerySchema.optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .describe('Count records'),\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n\n /**\n * Create multiple records in a single batch.\n * Optimized for performance.\n * \n * @param object - The object name.\n * @param dataArray - Array of record data.\n * @returns Array of created records.\n */\n bulkCreate: z.function()\n .input(z.tuple([z.string(), z.array(z.record(z.string(), z.unknown())), DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown())))),\n\n /**\n * Update multiple records in a single batch.\n * \n * @param object - The object name.\n * @param updates - Array of objects containing {id, data}.\n * @returns Array of updated records.\n */\n bulkUpdate: z.function()\n .input(z.tuple([z.string(), z.array(z.object({ id: z.string().or(z.number()), data: z.record(z.string(), z.unknown()) })), DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown())))),\n\n /**\n * Delete multiple records in a single batch.\n * \n * @param object - The object name.\n * @param ids - Array of record IDs.\n */\n bulkDelete: z.function()\n .input(z.tuple([z.string(), z.array(z.string().or(z.number())), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void())),\n\n /**\n * Update multiple records matching a query.\n * Direct database push-down. DOES NOT trigger per-record hooks.\n * \n * @param object - The object name.\n * @param query - The filtering criteria.\n * @param data - The data to update.\n * @returns Count of modified records.\n */\n updateMany: z.function()\n .input(z.tuple([z.string(), QuerySchema, z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .optional(),\n\n /**\n * Delete multiple records matching a query.\n * Direct database push-down. DOES NOT trigger per-record hooks.\n * \n * @param object - The object name.\n * @param query - The filtering criteria.\n * @returns Count of deleted records.\n */\n deleteMany: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .optional(),\n\n // ============================================================================\n // Transaction Management\n // ============================================================================\n\n /**\n * Begin a new database transaction.\n * @param options - Isolation level and other settings.\n * @returns A transaction handle to be passed to subsequent operations via `options.transaction`.\n */\n beginTransaction: z.function()\n .input(z.tuple([z.object({\n isolationLevel: IsolationLevelEnum.optional()\n }).optional()]))\n .output(z.promise(z.unknown()))\n .describe('Start transaction'),\n\n /**\n * Commit the transaction.\n * @param transaction - The transaction handle.\n */\n commit: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.promise(z.void()))\n .describe('Commit transaction'),\n\n /**\n * Rollback the transaction.\n * @param transaction - The transaction handle.\n */\n rollback: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.promise(z.void()))\n .describe('Rollback transaction'),\n\n // ============================================================================\n // Schema Management\n // ============================================================================\n\n /**\n * Synchronize the database schema with the Object definition.\n * This is an idempotent operation: it should create tables if missing, \n * add columns if missing, and update indexes.\n * \n * @param object - The object name.\n * @param schema - The full Object Schema (fields, indexes, etc).\n * @param options - Driver options.\n */\n syncSchema: z.function()\n .input(z.tuple([z.string(), z.unknown(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void()))\n .describe('Sync object schema to DB'),\n\n /**\n * Batch-synchronize multiple object schemas with fewer round-trips.\n *\n * Drivers that advertise `supports.batchSchemaSync = true` MUST implement\n * this method. The engine will call it once with every\n * `{ object, schema }` pair instead of calling `syncSchema()` N times.\n *\n * @param schemas - Array of `{ object: string; schema: unknown }` pairs.\n * @param options - Driver options.\n */\n syncSchemasBatch: z.function()\n .input(z.tuple([\n z.array(z.object({ object: z.string(), schema: z.unknown() })),\n DriverOptionsSchema.optional(),\n ]))\n .output(z.promise(z.void()))\n .optional()\n .describe('Batch sync multiple schemas in one round-trip'),\n \n /**\n * Drop the underlying table or collection for an object.\n * WARNING: Destructive operation.\n * \n * @param object - The object name.\n */\n dropTable: z.function()\n .input(z.tuple([z.string(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void())),\n\n /**\n * Analyze query performance.\n * Returns execution plan without executing the query (where possible).\n * \n * @param object - The object name.\n * @param query - The query to explain.\n * @returns The execution plan details.\n */\n explain: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.unknown()))\n .optional(),\n});\n\n/**\n * Connection Pool Configuration Schema\n * Manages database connection pooling for performance\n */\nexport const PoolConfigSchema = z.object({\n min: z.number().min(0).default(2).describe('Minimum number of connections in pool'),\n max: z.number().min(1).default(10).describe('Maximum number of connections in pool'),\n idleTimeoutMillis: z.number().min(0).default(30000).describe('Time in ms before idle connection is closed'),\n connectionTimeoutMillis: z.number().min(0).default(5000).describe('Time in ms to wait for available connection'),\n});\n\n/**\n * Driver Configuration Schema\n * Base configuration for database drivers\n */\nexport const DriverConfigSchema = z.object({\n name: z.string().describe('Driver instance name'),\n type: z.enum(['sql', 'nosql', 'cache', 'search', 'graph', 'timeseries']).describe('Driver type category'),\n capabilities: DriverCapabilitiesSchema.describe('Driver capability flags'),\n connectionString: z.string().optional().describe('Database connection string (driver-specific format)'),\n poolConfig: PoolConfigSchema.optional().describe('Connection pool configuration'),\n});\n\n/**\n * TypeScript types\n */\nexport type DriverOptions = z.infer;\nexport type DriverCapabilities = z.infer;\nexport type DriverInterface = z.infer;\nexport type DriverConfig = z.infer;\nexport type PoolConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DriverConfigSchema } from './driver.zod';\n\n/**\n * SQL Dialect Enumeration\n * Supported SQL database dialects\n */\nexport const SQLDialectSchema = z.enum([\n 'postgresql',\n 'mysql',\n 'sqlite',\n 'mssql',\n 'oracle',\n 'mariadb',\n]);\n\nexport type SQLDialect = z.infer;\n\n/**\n * Data Type Mapping Schema\n * Maps ObjectStack field types to SQL-specific data types\n * \n * @example PostgreSQL data type mapping\n * {\n * text: 'VARCHAR(255)',\n * number: 'NUMERIC',\n * boolean: 'BOOLEAN',\n * date: 'DATE',\n * datetime: 'TIMESTAMP',\n * json: 'JSONB',\n * uuid: 'UUID',\n * binary: 'BYTEA'\n * }\n */\nexport const DataTypeMappingSchema = z.object({\n text: z.string().describe('SQL type for text fields (e.g., VARCHAR, TEXT)'),\n number: z.string().describe('SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)'),\n boolean: z.string().describe('SQL type for boolean fields (e.g., BOOLEAN, BIT)'),\n date: z.string().describe('SQL type for date fields (e.g., DATE)'),\n datetime: z.string().describe('SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)'),\n json: z.string().optional().describe('SQL type for JSON fields (e.g., JSON, JSONB)'),\n uuid: z.string().optional().describe('SQL type for UUID fields (e.g., UUID, CHAR(36))'),\n binary: z.string().optional().describe('SQL type for binary fields (e.g., BLOB, BYTEA)'),\n});\n\nexport type DataTypeMapping = z.infer;\n\n/**\n * SSL Configuration Schema\n * SSL/TLS connection configuration for secure database connections\n * \n * @example PostgreSQL SSL configuration\n * {\n * rejectUnauthorized: true,\n * ca: '/path/to/ca-cert.pem',\n * cert: '/path/to/client-cert.pem',\n * key: '/path/to/client-key.pem'\n * }\n */\nexport const SSLConfigSchema = z.object({\n rejectUnauthorized: z.boolean().default(true).describe('Reject connections with invalid certificates'),\n ca: z.string().optional().describe('CA certificate file path or content'),\n cert: z.string().optional().describe('Client certificate file path or content'),\n key: z.string().optional().describe('Client private key file path or content'),\n}).refine((data) => {\n // If cert is provided, key must also be provided, and vice versa\n const hasCert = data.cert !== undefined;\n const hasKey = data.key !== undefined;\n return hasCert === hasKey;\n}, {\n message: 'Client certificate (cert) and private key (key) must be provided together',\n});\n\nexport type SSLConfig = z.infer;\n\n/**\n * SQL Driver Configuration Schema\n * Extended driver configuration specific to SQL databases\n * \n * @example PostgreSQL driver configuration\n * {\n * name: 'primary-db',\n * type: 'sql',\n * dialect: 'postgresql',\n * connectionString: 'postgresql://user:pass@localhost:5432/mydb',\n * dataTypeMapping: {\n * text: 'VARCHAR(255)',\n * number: 'NUMERIC',\n * boolean: 'BOOLEAN',\n * date: 'DATE',\n * datetime: 'TIMESTAMP',\n * json: 'JSONB',\n * uuid: 'UUID',\n * binary: 'BYTEA'\n * },\n * ssl: true,\n * sslConfig: {\n * rejectUnauthorized: true,\n * ca: '/etc/ssl/certs/ca.pem'\n * },\n * poolConfig: {\n * min: 2,\n * max: 10,\n * idleTimeoutMillis: 30000,\n * connectionTimeoutMillis: 5000\n * },\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: true,\n * bulkDelete: true,\n * transactions: true,\n * savepoints: true,\n * isolationLevels: ['read-committed', 'repeatable-read', 'serializable'],\n * queryFilters: true,\n * queryAggregations: true,\n * querySorting: true,\n * queryPagination: true,\n * queryWindowFunctions: true,\n * querySubqueries: true,\n * queryCTE: true,\n * joins: true,\n * fullTextSearch: true,\n * jsonQuery: true,\n * geospatialQuery: false,\n * streaming: true,\n * jsonFields: true,\n * arrayFields: true,\n * vectorSearch: true,\n * schemaSync: true,\n * migrations: true,\n * indexes: true,\n * connectionPooling: true,\n * preparedStatements: true,\n * queryCache: false\n * }\n * }\n */\nexport const SQLDriverConfigSchema = DriverConfigSchema.extend({\n type: z.literal('sql').describe('Driver type must be \"sql\"'),\n dialect: SQLDialectSchema.describe('SQL database dialect'),\n dataTypeMapping: DataTypeMappingSchema.describe('SQL data type mapping configuration'),\n ssl: z.boolean().default(false).describe('Enable SSL/TLS connection'),\n sslConfig: SSLConfigSchema.optional().describe('SSL/TLS configuration (required when ssl is true)'),\n}).refine((data) => {\n // If ssl is enabled, sslConfig must be provided\n if (data.ssl && !data.sslConfig) {\n return false;\n }\n return true;\n}, {\n message: 'sslConfig is required when ssl is true',\n});\n\nexport type SQLDriverConfig = z.infer;\n\n// ==========================================================================\n// SQLite-Specific Constants\n// ==========================================================================\n\n/**\n * Default data type mappings for SQLite/libSQL dialect.\n *\n * SQLite uses a simplified type system with type affinity:\n * - TEXT: strings, dates, UUIDs\n * - REAL: floating-point numbers\n * - INTEGER: integers, booleans\n * - BLOB: binary data\n *\n * @see https://www.sqlite.org/datatype3.html\n */\nexport const SQLiteDataTypeMappingDefaults: DataTypeMapping = {\n text: 'TEXT',\n number: 'REAL',\n boolean: 'INTEGER',\n date: 'TEXT',\n datetime: 'TEXT',\n json: 'TEXT',\n uuid: 'TEXT',\n binary: 'BLOB',\n};\n\n/**\n * SQLite ALTER TABLE Limitations.\n *\n * SQLite has limited ALTER TABLE support compared to other SQL databases.\n * This constant documents the known limitations that affect migration planning.\n * The schema diff service must use the \"table rebuild\" strategy for operations\n * that SQLite cannot perform natively.\n *\n * @see https://www.sqlite.org/lang_altertable.html\n */\nexport const SQLiteAlterTableLimitations = {\n /** SQLite supports ADD COLUMN */\n supportsAddColumn: true,\n /** SQLite supports RENAME COLUMN (3.25.0+) */\n supportsRenameColumn: true,\n /** SQLite supports DROP COLUMN (3.35.0+) */\n supportsDropColumn: true,\n /** SQLite does NOT support MODIFY/ALTER COLUMN type */\n supportsModifyColumn: false,\n /** SQLite does NOT support adding constraints to existing columns */\n supportsAddConstraint: false,\n /**\n * When an unsupported alteration is needed, the migration planner\n * must use the 12-step table rebuild strategy:\n * 1. CREATE new table with desired schema\n * 2. Copy data from old table\n * 3. DROP old table\n * 4. RENAME new table to old name\n */\n rebuildStrategy: 'create_copy_drop_rename',\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DriverConfigSchema } from './driver.zod';\n\n/**\n * NoSQL Database Type Enumeration\n * Supported NoSQL database types\n */\nexport const NoSQLDatabaseTypeSchema = z.enum([\n 'mongodb',\n 'couchdb',\n 'dynamodb',\n 'cassandra',\n 'redis',\n 'elasticsearch',\n 'neo4j',\n 'orientdb',\n]);\n\nexport type NoSQLDatabaseType = z.infer;\n\n/**\n * NoSQL Query Operation Types\n * Different types of operations supported by NoSQL databases\n */\nexport const NoSQLOperationTypeSchema = z.enum([\n 'find', // Query documents/records\n 'findOne', // Get single document\n 'insert', // Insert document\n 'update', // Update document\n 'delete', // Delete document\n 'aggregate', // Aggregation pipeline\n 'mapReduce', // MapReduce operation\n 'count', // Count documents\n 'distinct', // Get distinct values\n 'createIndex', // Create index\n 'dropIndex', // Drop index\n]);\n\nexport type NoSQLOperationType = z.infer;\n\n/**\n * NoSQL Consistency Level\n * Consistency guarantees for distributed NoSQL databases\n * \n * Consistency levels (from strongest to weakest):\n * - **all**: All replicas must respond (strongest consistency, lowest availability)\n * - **quorum**: Majority of replicas must respond (balanced)\n * - **one**: Any single replica responds (weakest consistency, highest availability)\n * - **local_quorum**: Majority of replicas in local datacenter\n * - **each_quorum**: Quorum of replicas in each datacenter\n * - **eventual**: Eventual consistency (highest availability, weakest consistency)\n */\nexport const ConsistencyLevelSchema = z.enum([\n 'all',\n 'quorum',\n 'one',\n 'local_quorum',\n 'each_quorum',\n 'eventual',\n]);\n\nexport type ConsistencyLevel = z.infer;\n\n/**\n * NoSQL Index Type\n * Types of indexes supported by NoSQL databases\n */\nexport const NoSQLIndexTypeSchema = z.enum([\n 'single', // Single field index\n 'compound', // Multiple fields index\n 'unique', // Unique constraint\n 'text', // Full-text search index\n 'geospatial', // Geospatial index (2d, 2dsphere)\n 'hashed', // Hashed index for sharding\n 'ttl', // Time-to-live index (auto-deletion)\n 'sparse', // Sparse index (only indexed documents with field)\n]);\n\nexport type NoSQLIndexType = z.infer;\n\n/**\n * NoSQL Sharding Configuration\n * Configuration for horizontal partitioning across multiple nodes\n */\nexport const ShardingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable sharding'),\n shardKey: z.string().optional().describe('Field to use as shard key'),\n shardingStrategy: z.enum(['hash', 'range', 'zone']).optional().describe('Sharding strategy'),\n numShards: z.number().int().positive().optional().describe('Number of shards'),\n});\n\nexport type ShardingConfig = z.infer;\n\n/**\n * NoSQL Replication Configuration\n * Configuration for data replication across nodes\n */\nexport const ReplicationConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable replication'),\n replicaSetName: z.string().optional().describe('Replica set name'),\n replicas: z.number().int().positive().optional().describe('Number of replicas'),\n readPreference: z.enum(['primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'])\n .optional()\n .describe('Read preference for replica set'),\n writeConcern: z.enum(['majority', 'acknowledged', 'unacknowledged'])\n .optional()\n .describe('Write concern level'),\n});\n\nexport type ReplicationConfig = z.infer;\n\n/**\n * Document Schema Validation\n * Schema validation rules for document-based NoSQL databases\n */\nexport const DocumentSchemaValidationSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable schema validation'),\n validationLevel: z.enum(['strict', 'moderate', 'off']).optional().describe('Validation strictness'),\n validationAction: z.enum(['error', 'warn']).optional().describe('Action on validation failure'),\n jsonSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for validation'),\n});\n\nexport type DocumentSchemaValidation = z.infer;\n\n/**\n * NoSQL Data Type Mapping Schema\n * Maps ObjectStack field types to NoSQL-specific data types\n * \n * @example MongoDB data type mapping\n * {\n * text: 'string',\n * number: 'double',\n * boolean: 'bool',\n * date: 'date',\n * datetime: 'date',\n * json: 'object',\n * uuid: 'string',\n * binary: 'binData',\n * array: 'array',\n * objectId: 'objectId'\n * }\n */\nexport const NoSQLDataTypeMappingSchema = z.object({\n text: z.string().describe('NoSQL type for text fields'),\n number: z.string().describe('NoSQL type for number fields'),\n boolean: z.string().describe('NoSQL type for boolean fields'),\n date: z.string().describe('NoSQL type for date fields'),\n datetime: z.string().describe('NoSQL type for datetime fields'),\n json: z.string().optional().describe('NoSQL type for JSON/object fields'),\n uuid: z.string().optional().describe('NoSQL type for UUID fields'),\n binary: z.string().optional().describe('NoSQL type for binary fields'),\n array: z.string().optional().describe('NoSQL type for array fields'),\n objectId: z.string().optional().describe('NoSQL type for ObjectID fields (MongoDB)'),\n geopoint: z.string().optional().describe('NoSQL type for geospatial point fields'),\n});\n\nexport type NoSQLDataTypeMapping = z.infer;\n\n/**\n * NoSQL Driver Configuration Schema\n * Extended driver configuration specific to NoSQL databases\n * \n * @example MongoDB driver configuration\n * {\n * name: 'primary-mongo',\n * type: 'nosql',\n * databaseType: 'mongodb',\n * connectionString: 'mongodb://user:pass@localhost:27017/mydb',\n * dataTypeMapping: {\n * text: 'string',\n * number: 'double',\n * boolean: 'bool',\n * date: 'date',\n * datetime: 'date',\n * json: 'object',\n * uuid: 'string',\n * binary: 'binData',\n * array: 'array',\n * objectId: 'objectId'\n * },\n * consistency: 'quorum',\n * replication: {\n * enabled: true,\n * replicaSetName: 'rs0',\n * replicas: 3,\n * readPreference: 'primaryPreferred',\n * writeConcern: 'majority'\n * },\n * sharding: {\n * enabled: true,\n * shardKey: '_id',\n * shardingStrategy: 'hash',\n * numShards: 4\n * },\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: true,\n * bulkDelete: true,\n * transactions: true,\n * savepoints: false,\n * queryFilters: true,\n * queryAggregations: true,\n * querySorting: true,\n * queryPagination: true,\n * queryWindowFunctions: false,\n * querySubqueries: false,\n * queryCTE: false,\n * joins: false,\n * fullTextSearch: true,\n * jsonQuery: true,\n * geospatialQuery: true,\n * streaming: true,\n * jsonFields: true,\n * arrayFields: true,\n * vectorSearch: false,\n * schemaSync: true,\n * migrations: false,\n * indexes: true,\n * connectionPooling: true,\n * preparedStatements: false,\n * queryCache: false\n * }\n * }\n * \n * @example DynamoDB driver configuration\n * {\n * name: 'dynamodb-main',\n * type: 'nosql',\n * databaseType: 'dynamodb',\n * region: 'us-east-1',\n * accessKeyId: 'AKIAIOSFODNN7EXAMPLE',\n * secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n * consistency: 'eventual',\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: false,\n * bulkDelete: false,\n * transactions: true,\n * queryFilters: true,\n * queryAggregations: false,\n * querySorting: true,\n * queryPagination: true,\n * fullTextSearch: false,\n * jsonQuery: true,\n * indexes: true\n * }\n * }\n */\nexport const NoSQLDriverConfigSchema = DriverConfigSchema.extend({\n type: z.literal('nosql').describe('Driver type must be \"nosql\"'),\n databaseType: NoSQLDatabaseTypeSchema.describe('Specific NoSQL database type'),\n dataTypeMapping: NoSQLDataTypeMappingSchema.describe('NoSQL data type mapping configuration'),\n \n /**\n * Consistency level for reads/writes\n */\n consistency: ConsistencyLevelSchema.optional().describe('Consistency level for operations'),\n \n /**\n * Replication configuration\n */\n replication: ReplicationConfigSchema.optional().describe('Replication configuration'),\n \n /**\n * Sharding configuration\n */\n sharding: ShardingConfigSchema.optional().describe('Sharding configuration'),\n \n /**\n * Schema validation rules (for document databases)\n */\n schemaValidation: DocumentSchemaValidationSchema.optional().describe('Document schema validation'),\n \n /**\n * AWS Region (for DynamoDB, DocumentDB, etc.)\n */\n region: z.string().optional().describe('AWS region (for managed NoSQL services)'),\n \n /**\n * AWS Access Key ID (for DynamoDB, DocumentDB, etc.)\n */\n accessKeyId: z.string().optional().describe('AWS access key ID'),\n \n /**\n * AWS Secret Access Key (for DynamoDB, DocumentDB, etc.)\n */\n secretAccessKey: z.string().optional().describe('AWS secret access key'),\n \n /**\n * Time-to-live (TTL) field name\n * Automatically delete documents after a specified time\n */\n ttlField: z.string().optional().describe('Field name for TTL (auto-deletion)'),\n \n /**\n * Maximum document size in bytes\n */\n maxDocumentSize: z.number().int().positive().optional().describe('Maximum document size in bytes'),\n \n /**\n * Collection/Table name prefix\n * Useful for multi-tenancy or environment isolation\n */\n collectionPrefix: z.string().optional().describe('Prefix for collection/table names'),\n});\n\nexport type NoSQLDriverConfig = z.infer;\n\n/**\n * NoSQL Query Options\n * Additional options for NoSQL queries\n */\nexport const NoSQLQueryOptionsSchema = z.object({\n /**\n * Consistency level for this query\n */\n consistency: ConsistencyLevelSchema.optional().describe('Consistency level override'),\n \n /**\n * Read from secondary replicas\n */\n readFromSecondary: z.boolean().optional().describe('Allow reading from secondary replicas'),\n \n /**\n * Projection (fields to include/exclude)\n */\n projection: z.record(z.string(), z.union([z.literal(0), z.literal(1)])).optional().describe('Field projection'),\n \n /**\n * Query timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().describe('Query timeout (ms)'),\n \n /**\n * Use cursor for large result sets\n */\n useCursor: z.boolean().optional().describe('Use cursor instead of loading all results'),\n \n /**\n * Batch size for cursor iteration\n */\n batchSize: z.number().int().positive().optional().describe('Cursor batch size'),\n \n /**\n * Enable query profiling\n */\n profile: z.boolean().optional().describe('Enable query profiling'),\n \n /**\n * Use hinted index\n */\n hint: z.string().optional().describe('Index hint for query optimization'),\n});\n\nexport type NoSQLQueryOptions = z.infer;\n\n/**\n * NoSQL Aggregation Pipeline Stage\n * Represents a single stage in an aggregation pipeline (MongoDB-style)\n */\nexport const AggregationStageSchema = z.object({\n /**\n * Stage operator (e.g., $match, $group, $sort, $project)\n */\n operator: z.string().describe('Aggregation operator (e.g., $match, $group, $sort)'),\n \n /**\n * Stage parameters/options\n */\n options: z.record(z.string(), z.unknown()).describe('Stage-specific options'),\n});\n\nexport type AggregationStage = z.infer;\n\n/**\n * NoSQL Aggregation Pipeline\n * Sequence of aggregation stages for complex data transformations\n */\nexport const AggregationPipelineSchema = z.object({\n /**\n * Collection/Table to aggregate\n */\n collection: z.string().describe('Collection/table name'),\n \n /**\n * Pipeline stages\n */\n stages: z.array(AggregationStageSchema).describe('Aggregation pipeline stages'),\n \n /**\n * Additional options\n */\n options: NoSQLQueryOptionsSchema.optional().describe('Query options'),\n});\n\nexport type AggregationPipeline = z.infer;\n\n/**\n * NoSQL Index Definition\n * Definition for creating indexes in NoSQL databases\n */\nexport const NoSQLIndexSchema = z.object({\n /**\n * Index name\n */\n name: z.string().describe('Index name'),\n \n /**\n * Index type\n */\n type: NoSQLIndexTypeSchema.describe('Index type'),\n \n /**\n * Fields to index\n * For compound indexes, order matters\n */\n fields: z.array(z.object({\n field: z.string().describe('Field name'),\n order: z.enum(['asc', 'desc', 'text', '2dsphere']).optional().describe('Index order or type'),\n })).describe('Fields to index'),\n \n /**\n * Unique constraint\n */\n unique: z.boolean().default(false).describe('Enforce uniqueness'),\n \n /**\n * Sparse index (only index documents with the field)\n */\n sparse: z.boolean().default(false).describe('Sparse index'),\n \n /**\n * TTL in seconds (for TTL indexes)\n */\n expireAfterSeconds: z.number().int().positive().optional().describe('TTL in seconds'),\n \n /**\n * Partial index filter\n */\n partialFilterExpression: z.record(z.string(), z.unknown()).optional().describe('Partial index filter'),\n \n /**\n * Background index creation\n */\n background: z.boolean().default(false).describe('Create index in background'),\n});\n\nexport type NoSQLIndex = z.infer;\n\n/**\n * NoSQL Transaction Options\n * Options for NoSQL transactions (where supported)\n */\nexport const NoSQLTransactionOptionsSchema = z.object({\n /**\n * Read concern level\n */\n readConcern: z.enum(['local', 'majority', 'linearizable', 'snapshot']).optional().describe('Read concern level'),\n \n /**\n * Write concern level\n */\n writeConcern: z.enum(['majority', 'acknowledged', 'unacknowledged']).optional().describe('Write concern level'),\n \n /**\n * Read preference\n */\n readPreference: z.enum(['primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'])\n .optional()\n .describe('Read preference'),\n \n /**\n * Transaction timeout in milliseconds\n */\n maxCommitTimeMS: z.number().int().positive().optional().describe('Transaction commit timeout (ms)'),\n});\n\nexport type NoSQLTransactionOptions = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data Import Strategy\n * Defines how the engine handles existing records.\n */\nexport const DatasetMode = z.enum([\n 'insert', // Try to insert, fail on duplicate\n 'update', // Only update found records, ignore new\n 'upsert', // Create new or Update existing (Standard)\n 'replace', // Delete ALL records in object then insert (Dangerous - use for cache tables)\n 'ignore' // Try to insert, silently skip duplicates\n]);\n\n/**\n * Dataset Schema (Seed Data / Fixtures)\n * \n * Standardized format for transporting data.\n * Used for:\n * 1. System Bootstrapping (Admin accounts, Standard Roles)\n * 2. Reference Data (Countries, Currencies)\n * 3. Demo/Test Data\n */\nexport const DatasetSchema = z.object({\n /** \n * Target Object \n * The machine name of the object to populate.\n */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target Object Name'),\n\n /** \n * Idempotency Key (The \"Upsert\" Key)\n * The field used to check if a record already exists.\n * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'.\n * Standard: 'id' is rarely used for portable seed data — prefer natural keys.\n */\n externalId: z.string().default('name').describe('Field match for uniqueness check'),\n\n /** \n * Import Strategy\n */\n mode: DatasetMode.default('upsert').describe('Conflict resolution strategy'),\n\n /**\n * Environment Scope\n * - 'all': Always load\n * - 'dev': Only for development/demo\n * - 'test': Only for CI/CD tests\n */\n env: z.array(z.enum(['prod', 'dev', 'test'])).default(['prod', 'dev', 'test']).describe('Applicable environments'),\n\n /** \n * The Payload\n * Array of raw JSON objects matching the Object Schema.\n */\n records: z.array(z.record(z.string(), z.unknown())).describe('Data records'),\n});\n\n/** Parsed/output type — all defaults are applied (env, mode, externalId always present) */\nexport type Dataset = z.infer;\n\n/** Input type — fields with defaults (env, mode, externalId) are optional */\nexport type DatasetInput = z.input;\n\nexport type DatasetImportMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DatasetSchema, DatasetMode } from './dataset.zod';\n\n/**\n * # Seed Loader Protocol\n *\n * Defines the schemas for metadata-driven seed data loading with automatic\n * relationship resolution, dependency ordering, and multi-pass insertion.\n *\n * ## Architecture Alignment\n * - **Salesforce Data Loader**: External ID-based upsert with relationship resolution\n * - **ServiceNow**: Sys ID and display value mapping during import\n * - **Airtable**: Linked record resolution via display names\n *\n * ## Loading Flow\n * ```\n * 1. Build object dependency graph from field metadata (lookup/master_detail)\n * 2. Topological sort → determine insert order (parents before children)\n * 3. Pass 1: Insert/upsert records, resolve references via externalId\n * 4. Pass 2: Fill deferred references (circular/delayed dependencies)\n * 5. Validate & report unresolved references\n * 6. Return structured result with per-object stats\n * ```\n */\n\n// ==========================================================================\n// 1. Reference Resolution\n// ==========================================================================\n\n/**\n * Describes how a single field reference should be resolved during seed loading.\n *\n * When a lookup/master_detail field value is not an internal ID, the loader\n * attempts to match it against the target object's externalId field.\n */\nexport const ReferenceResolutionSchema = z.object({\n /** The field name on the source object (e.g., 'account_id') */\n field: z.string().describe('Source field name containing the reference value'),\n\n /** The target object being referenced (e.g., 'account') */\n targetObject: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target object name (snake_case)'),\n\n /**\n * The field on the target object used to match the reference value.\n * Defaults to the target object's externalId (usually 'name').\n */\n targetField: z.string().default('name').describe('Field on target object used for matching'),\n\n /** The field type that triggered this resolution (lookup or master_detail) */\n fieldType: z.enum(['lookup', 'master_detail']).describe('Relationship field type'),\n}).describe('Describes how a field reference is resolved during seed loading');\n\nexport type ReferenceResolution = z.infer;\n\n// ==========================================================================\n// 2. Object Dependency Node\n// ==========================================================================\n\n/**\n * Represents a single object in the dependency graph.\n * Built from object metadata by inspecting lookup/master_detail fields.\n */\nexport const ObjectDependencyNodeSchema = z.object({\n /** Object machine name */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Object name (snake_case)'),\n\n /**\n * Objects that this object depends on (via lookup/master_detail fields).\n * These must be loaded before this object.\n */\n dependsOn: z.array(z.string()).describe('Objects this object depends on'),\n\n /**\n * Field-level reference details for each dependency.\n * Maps field name → reference resolution info.\n */\n references: z.array(ReferenceResolutionSchema).describe('Field-level reference details'),\n}).describe('Object node in the seed data dependency graph');\n\nexport type ObjectDependencyNode = z.infer;\n\n// ==========================================================================\n// 3. Object Dependency Graph\n// ==========================================================================\n\n/**\n * The complete object dependency graph for seed data loading.\n * Used to determine topological insert order and detect circular dependencies.\n */\nexport const ObjectDependencyGraphSchema = z.object({\n /** All object nodes in the graph */\n nodes: z.array(ObjectDependencyNodeSchema).describe('All objects in the dependency graph'),\n\n /**\n * Topologically sorted object names for insertion order.\n * Parent objects appear before child objects.\n */\n insertOrder: z.array(z.string()).describe('Topologically sorted insert order'),\n\n /**\n * Circular dependency chains detected in the graph.\n * Each chain is an array of object names forming a cycle.\n * When present, the loader must use a multi-pass strategy.\n *\n * @example [['project', 'task', 'project']]\n */\n circularDependencies: z.array(z.array(z.string())).default([])\n .describe('Circular dependency chains (e.g., [[\"a\", \"b\", \"a\"]])'),\n}).describe('Complete object dependency graph for seed data loading');\n\nexport type ObjectDependencyGraph = z.infer;\n\n// ==========================================================================\n// 4. Reference Resolution Error\n// ==========================================================================\n\n/**\n * Actionable error for a failed reference resolution.\n * Provides all context needed to diagnose and fix the broken reference.\n *\n * Aligns with Salesforce Data Loader error reporting patterns:\n * field name, target object, attempted value, and reason.\n */\nexport const ReferenceResolutionErrorSchema = z.object({\n /** The source object containing the broken reference */\n sourceObject: z.string().describe('Object with the broken reference'),\n\n /** The field containing the unresolved value */\n field: z.string().describe('Field name with unresolved reference'),\n\n /** The target object that was searched */\n targetObject: z.string().describe('Target object searched for the reference'),\n\n /** The externalId field used for matching on the target object */\n targetField: z.string().describe('ExternalId field used for matching'),\n\n /** The value that could not be resolved */\n attemptedValue: z.unknown().describe('Value that failed to resolve'),\n\n /** The index of the record in the dataset's records array */\n recordIndex: z.number().int().min(0).describe('Index of the record in the dataset'),\n\n /** Human-readable error message */\n message: z.string().describe('Human-readable error description'),\n}).describe('Actionable error for a failed reference resolution');\n\nexport type ReferenceResolutionError = z.infer;\n\n// ==========================================================================\n// 5. Seed Loader Configuration\n// ==========================================================================\n\n/**\n * Configuration for the seed data loader.\n * Controls behavior for reference resolution, error handling, and validation.\n */\nexport const SeedLoaderConfigSchema = z.object({\n /**\n * Dry-run mode: validate all references without writing data.\n * Surfaces broken references before any mutations occur.\n * @default false\n */\n dryRun: z.boolean().default(false)\n .describe('Validate references without writing data'),\n\n /**\n * Whether to halt on the first reference resolution error.\n * When false, collects all errors and continues loading.\n * @default false\n */\n haltOnError: z.boolean().default(false)\n .describe('Stop on first reference resolution error'),\n\n /**\n * Enable multi-pass loading for circular dependencies.\n * Pass 1: Insert records with null for circular references.\n * Pass 2: Update records to fill deferred references.\n * @default true\n */\n multiPass: z.boolean().default(true)\n .describe('Enable multi-pass loading for circular dependencies'),\n\n /**\n * Default dataset mode when not specified per-dataset.\n * @default 'upsert'\n */\n defaultMode: DatasetMode.default('upsert')\n .describe('Default conflict resolution strategy'),\n\n /**\n * Maximum number of records to process in a single batch.\n * Controls memory usage for large datasets.\n * @default 1000\n */\n batchSize: z.number().int().min(1).default(1000)\n .describe('Maximum records per batch insert/upsert'),\n\n /**\n * Whether to wrap the entire load operation in a transaction.\n * When true, all-or-nothing semantics apply.\n * @default false\n */\n transaction: z.boolean().default(false)\n .describe('Wrap entire load in a transaction (all-or-nothing)'),\n\n /**\n * Environment filter. Only datasets matching this environment are loaded.\n * When not specified, all datasets are loaded regardless of env scope.\n */\n env: z.enum(['prod', 'dev', 'test']).optional()\n .describe('Only load datasets matching this environment'),\n}).describe('Seed data loader configuration');\n\nexport type SeedLoaderConfig = z.infer;\n\n/** Input type — all fields with defaults are optional */\nexport type SeedLoaderConfigInput = z.input;\n\n// ==========================================================================\n// 6. Per-Object Load Result\n// ==========================================================================\n\n/**\n * Result of loading a single object's dataset.\n */\nexport const DatasetLoadResultSchema = z.object({\n /** Target object name */\n object: z.string().describe('Object that was loaded'),\n\n /** Import mode used */\n mode: DatasetMode.describe('Import mode used'),\n\n /** Number of records successfully inserted */\n inserted: z.number().int().min(0).describe('Records inserted'),\n\n /** Number of records successfully updated (upsert matched existing) */\n updated: z.number().int().min(0).describe('Records updated'),\n\n /** Number of records skipped (mode: ignore, or already exists) */\n skipped: z.number().int().min(0).describe('Records skipped'),\n\n /** Number of records with errors */\n errored: z.number().int().min(0).describe('Records with errors'),\n\n /** Total records in the dataset */\n total: z.number().int().min(0).describe('Total records in dataset'),\n\n /** Number of references resolved via externalId */\n referencesResolved: z.number().int().min(0).describe('References resolved via externalId'),\n\n /** Number of references deferred to pass 2 (circular dependencies) */\n referencesDeferred: z.number().int().min(0).describe('References deferred to second pass'),\n\n /** Reference resolution errors for this object */\n errors: z.array(ReferenceResolutionErrorSchema).default([])\n .describe('Reference resolution errors'),\n}).describe('Result of loading a single dataset');\n\nexport type DatasetLoadResult = z.infer;\n\n// ==========================================================================\n// 7. Seed Loader Result\n// ==========================================================================\n\n/**\n * Complete result of a seed loading operation.\n * Aggregates all per-object results and provides summary statistics.\n */\nexport const SeedLoaderResultSchema = z.object({\n /** Whether the overall load operation succeeded */\n success: z.boolean().describe('Overall success status'),\n\n /** Was this a dry-run (validation only, no writes)? */\n dryRun: z.boolean().describe('Whether this was a dry-run'),\n\n /** The dependency graph used for ordering */\n dependencyGraph: ObjectDependencyGraphSchema.describe('Object dependency graph'),\n\n /** Per-object load results, in the order they were processed */\n results: z.array(DatasetLoadResultSchema).describe('Per-object load results'),\n\n /** All reference resolution errors across all objects */\n errors: z.array(ReferenceResolutionErrorSchema).describe('All reference resolution errors'),\n\n /** Summary statistics */\n summary: z.object({\n /** Total objects processed */\n objectsProcessed: z.number().int().min(0).describe('Total objects processed'),\n\n /** Total records across all objects */\n totalRecords: z.number().int().min(0).describe('Total records across all objects'),\n\n /** Total records inserted */\n totalInserted: z.number().int().min(0).describe('Total records inserted'),\n\n /** Total records updated */\n totalUpdated: z.number().int().min(0).describe('Total records updated'),\n\n /** Total records skipped */\n totalSkipped: z.number().int().min(0).describe('Total records skipped'),\n\n /** Total records with errors */\n totalErrored: z.number().int().min(0).describe('Total records with errors'),\n\n /** Total references resolved via externalId */\n totalReferencesResolved: z.number().int().min(0).describe('Total references resolved'),\n\n /** Total references deferred to second pass */\n totalReferencesDeferred: z.number().int().min(0).describe('Total references deferred'),\n\n /** Number of circular dependency chains detected */\n circularDependencyCount: z.number().int().min(0).describe('Circular dependency chains detected'),\n\n /** Duration of the load operation in milliseconds */\n durationMs: z.number().min(0).describe('Load duration in milliseconds'),\n }).describe('Summary statistics'),\n}).describe('Complete seed loader result');\n\nexport type SeedLoaderResult = z.infer;\n\n// ==========================================================================\n// 8. Seed Loader Request\n// ==========================================================================\n\n/**\n * Input request for the seed loader.\n * Combines datasets with loader configuration.\n */\nexport const SeedLoaderRequestSchema = z.object({\n /** Datasets to load */\n datasets: z.array(DatasetSchema).min(1).describe('Datasets to load'),\n\n /** Loader configuration */\n config: z.preprocess((val) => val ?? {}, SeedLoaderConfigSchema).describe('Loader configuration'),\n}).describe('Seed loader request with datasets and configuration');\n\nexport type SeedLoaderRequest = z.infer;\n\n/** Input type — config defaults are optional */\nexport type SeedLoaderRequestInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Document Version Schema\n * \n * Represents a single version of a document in a version-controlled system.\n * Each version is immutable and maintains its own metadata and download URL.\n * \n * @example\n * ```json\n * {\n * \"versionNumber\": 2,\n * \"createdAt\": 1704067200000,\n * \"createdBy\": \"user_123\",\n * \"size\": 2048576,\n * \"checksum\": \"a1b2c3d4e5f6\",\n * \"downloadUrl\": \"https://storage.example.com/docs/v2/file.pdf\",\n * \"isLatest\": true\n * }\n * ```\n */\nexport const DocumentVersionSchema = z.object({\n /**\n * Sequential version number (increments with each new version)\n */\n versionNumber: z.number().describe('Version number'),\n\n /**\n * Timestamp when this version was created (Unix milliseconds)\n */\n createdAt: z.number().describe('Creation timestamp'),\n\n /**\n * User ID who created this version\n */\n createdBy: z.string().describe('Creator user ID'),\n\n /**\n * File size in bytes\n */\n size: z.number().describe('File size in bytes'),\n\n /**\n * Checksum/hash of the file content (for integrity verification)\n */\n checksum: z.string().describe('File checksum'),\n\n /**\n * URL to download this specific version\n */\n downloadUrl: z.string().url().describe('Download URL'),\n\n /**\n * Whether this is the latest version\n * @default false\n */\n isLatest: z.boolean().optional().default(false).describe('Is latest version'),\n});\n\n/**\n * Document Template Schema\n * \n * Defines a reusable document template with dynamic placeholders.\n * Templates can be used to generate documents with variable content.\n * \n * @example\n * ```json\n * {\n * \"id\": \"contract-template\",\n * \"name\": \"Service Agreement\",\n * \"description\": \"Standard service agreement template\",\n * \"fileUrl\": \"https://example.com/templates/contract.docx\",\n * \"fileType\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n * \"placeholders\": [\n * {\n * \"key\": \"client_name\",\n * \"label\": \"Client Name\",\n * \"type\": \"text\",\n * \"required\": true\n * },\n * {\n * \"key\": \"contract_date\",\n * \"label\": \"Contract Date\",\n * \"type\": \"date\",\n * \"required\": true\n * }\n * ]\n * }\n * ```\n */\nexport const DocumentTemplateSchema = z.object({\n /**\n * Unique identifier for the template\n */\n id: z.string().describe('Template ID'),\n\n /**\n * Human-readable name of the template\n */\n name: z.string().describe('Template name'),\n\n /**\n * Optional description of the template's purpose\n */\n description: z.string().optional().describe('Template description'),\n\n /**\n * URL to the template file\n */\n fileUrl: z.string().url().describe('Template file URL'),\n\n /**\n * MIME type of the template file\n */\n fileType: z.string().describe('File MIME type'),\n\n /**\n * List of dynamic placeholders in the template\n */\n placeholders: z.array(z.object({\n /**\n * Placeholder identifier (used in template)\n */\n key: z.string().describe('Placeholder key'),\n\n /**\n * Human-readable label for the placeholder\n */\n label: z.string().describe('Placeholder label'),\n\n /**\n * Data type of the placeholder value\n */\n type: z.enum(['text', 'number', 'date', 'image']).describe('Placeholder type'),\n\n /**\n * Whether this placeholder must be filled\n * @default false\n */\n required: z.boolean().optional().default(false).describe('Is required'),\n })).describe('Template placeholders'),\n});\n\n/**\n * E-Signature Configuration Schema\n * \n * Configuration for electronic signature workflows.\n * Supports integration with popular e-signature providers.\n * \n * @example\n * ```json\n * {\n * \"provider\": \"docusign\",\n * \"enabled\": true,\n * \"signers\": [\n * {\n * \"email\": \"client@example.com\",\n * \"name\": \"John Doe\",\n * \"role\": \"Client\",\n * \"order\": 1\n * },\n * {\n * \"email\": \"manager@example.com\",\n * \"name\": \"Jane Smith\",\n * \"role\": \"Manager\",\n * \"order\": 2\n * }\n * ],\n * \"expirationDays\": 30,\n * \"reminderDays\": 7\n * }\n * ```\n */\nexport const ESignatureConfigSchema = z.object({\n /**\n * E-signature service provider\n */\n provider: z.enum(['docusign', 'adobe-sign', 'hellosign', 'custom']).describe('E-signature provider'),\n\n /**\n * Whether e-signature is enabled for this document\n * @default false\n */\n enabled: z.boolean().optional().default(false).describe('E-signature enabled'),\n\n /**\n * List of signers in signing order\n */\n signers: z.array(z.object({\n /**\n * Signer's email address\n */\n email: z.string().email().describe('Signer email'),\n\n /**\n * Signer's full name\n */\n name: z.string().describe('Signer name'),\n\n /**\n * Signer's role in the document\n */\n role: z.string().describe('Signer role'),\n\n /**\n * Signing order (lower numbers sign first)\n */\n order: z.number().describe('Signing order'),\n })).describe('Document signers'),\n\n /**\n * Days until signature request expires\n * @default 30\n */\n expirationDays: z.number().optional().default(30).describe('Expiration days'),\n\n /**\n * Days between reminder emails\n * @default 7\n */\n reminderDays: z.number().optional().default(7).describe('Reminder interval days'),\n});\n\n/**\n * Document Schema\n * \n * Comprehensive document management protocol supporting versioning,\n * templates, e-signatures, and access control.\n * \n * @example\n * ```json\n * {\n * \"id\": \"doc_123\",\n * \"name\": \"Service Agreement 2024\",\n * \"description\": \"Annual service agreement\",\n * \"fileType\": \"application/pdf\",\n * \"fileSize\": 1048576,\n * \"category\": \"contracts\",\n * \"tags\": [\"legal\", \"2024\", \"services\"],\n * \"versioning\": {\n * \"enabled\": true,\n * \"versions\": [\n * {\n * \"versionNumber\": 1,\n * \"createdAt\": 1704067200000,\n * \"createdBy\": \"user_123\",\n * \"size\": 1048576,\n * \"checksum\": \"abc123\",\n * \"downloadUrl\": \"https://example.com/docs/v1.pdf\",\n * \"isLatest\": true\n * }\n * ],\n * \"majorVersion\": 1,\n * \"minorVersion\": 0\n * },\n * \"access\": {\n * \"isPublic\": false,\n * \"sharedWith\": [\"user_456\", \"team_789\"],\n * \"expiresAt\": 1735689600000\n * },\n * \"metadata\": {\n * \"author\": \"John Doe\",\n * \"department\": \"Legal\"\n * }\n * }\n * ```\n */\nexport const DocumentSchema = z.object({\n /**\n * Unique document identifier\n */\n id: z.string().describe('Document ID'),\n\n /**\n * Document name\n */\n name: z.string().describe('Document name'),\n\n /**\n * Optional document description\n */\n description: z.string().optional().describe('Document description'),\n\n /**\n * MIME type of the document\n */\n fileType: z.string().describe('File MIME type'),\n\n /**\n * File size in bytes\n */\n fileSize: z.number().describe('File size in bytes'),\n\n /**\n * Document category for organization\n */\n category: z.string().optional().describe('Document category'),\n\n /**\n * Tags for searchability and organization\n */\n tags: z.array(z.string()).optional().describe('Document tags'),\n\n /**\n * Version control configuration\n */\n versioning: z.object({\n /**\n * Whether versioning is enabled\n */\n enabled: z.boolean().describe('Versioning enabled'),\n\n /**\n * List of all document versions\n */\n versions: z.array(DocumentVersionSchema).describe('Version history'),\n\n /**\n * Current major version number\n */\n majorVersion: z.number().describe('Major version'),\n\n /**\n * Current minor version number\n */\n minorVersion: z.number().describe('Minor version'),\n }).optional().describe('Version control'),\n\n /**\n * Template configuration (if document is generated from template)\n */\n template: DocumentTemplateSchema.optional().describe('Document template'),\n\n /**\n * E-signature configuration\n */\n eSignature: ESignatureConfigSchema.optional().describe('E-signature config'),\n\n /**\n * Access control settings\n */\n access: z.object({\n /**\n * Whether document is publicly accessible\n * @default false\n */\n isPublic: z.boolean().optional().default(false).describe('Public access'),\n\n /**\n * List of user/team IDs with access\n */\n sharedWith: z.array(z.string()).optional().describe('Shared with'),\n\n /**\n * Timestamp when access expires (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Access expiration'),\n }).optional().describe('Access control'),\n\n /**\n * Custom metadata fields\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\n// Type exports\nexport type Document = z.infer;\nexport type DocumentVersion = z.infer;\nexport type DocumentTemplate = z.infer;\nexport type ESignatureConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldMappingSchema as BaseFieldMappingSchema } from '../shared/mapping.zod';\n\n/**\n * External Data Source Schema\n * \n * Configuration for connecting to external data systems.\n * Similar to Salesforce External Objects for real-time data integration.\n * \n * @example\n * ```json\n * {\n * \"id\": \"salesforce-accounts\",\n * \"name\": \"Salesforce Account Data\",\n * \"type\": \"rest-api\",\n * \"endpoint\": \"https://api.salesforce.com/services/data/v58.0\",\n * \"authentication\": {\n * \"type\": \"oauth2\",\n * \"config\": {\n * \"clientId\": \"...\",\n * \"clientSecret\": \"...\",\n * \"tokenUrl\": \"https://login.salesforce.com/services/oauth2/token\"\n * }\n * }\n * }\n * ```\n */\nexport const ExternalDataSourceSchema = z.object({\n /**\n * Unique identifier for the external data source\n */\n id: z.string().describe('Data source ID'),\n\n /**\n * Human-readable name of the data source\n */\n name: z.string().describe('Data source name'),\n\n /**\n * Protocol type for connecting to the data source\n */\n type: z.enum(['odata', 'rest-api', 'graphql', 'custom']).describe('Protocol type'),\n\n /**\n * Base URL endpoint for the external system\n */\n endpoint: z.string().url().describe('API endpoint URL'),\n\n /**\n * Authentication configuration\n */\n authentication: z.object({\n /**\n * Authentication method\n */\n type: z.enum(['oauth2', 'api-key', 'basic', 'none']).describe('Auth type'),\n\n /**\n * Authentication-specific configuration\n * Structure varies based on auth type\n */\n config: z.record(z.string(), z.unknown()).describe('Auth configuration'),\n }).describe('Authentication'),\n});\n\n/**\n * Field Mapping Schema for External Lookups\n * \n * Extends the base field mapping with external lookup specific features.\n * Uses the canonical field mapping protocol from shared/mapping.zod.ts.\n * \n * @see {@link BaseFieldMappingSchema} for the base field mapping schema\n * \n * @example\n * ```json\n * {\n * \"source\": \"AccountName\",\n * \"target\": \"name\",\n * \"readonly\": true\n * }\n * ```\n */\nexport const ExternalFieldMappingSchema = BaseFieldMappingSchema.extend({\n /**\n * Field data type\n */\n type: z.string().optional().describe('Field type'),\n\n /**\n * Whether the field is read-only\n * @default true\n */\n readonly: z.boolean().optional().default(true).describe('Read-only field'),\n});\n\n/**\n * External Lookup Schema\n * \n * Real-time data lookup protocol for external systems.\n * Enables querying external data sources without replication.\n * Inspired by Salesforce External Objects and OData protocols.\n * \n * @example\n * ```json\n * {\n * \"fieldName\": \"external_account\",\n * \"dataSource\": {\n * \"id\": \"salesforce-api\",\n * \"name\": \"Salesforce\",\n * \"type\": \"rest-api\",\n * \"endpoint\": \"https://api.salesforce.com/services/data/v58.0\",\n * \"authentication\": {\n * \"type\": \"oauth2\",\n * \"config\": {\"clientId\": \"...\"}\n * }\n * },\n * \"query\": {\n * \"endpoint\": \"/sobjects/Account\",\n * \"method\": \"GET\",\n * \"parameters\": {\"limit\": 100}\n * },\n * \"fieldMappings\": [\n * {\n * \"externalField\": \"Name\",\n * \"localField\": \"account_name\",\n * \"type\": \"text\",\n * \"readonly\": true\n * }\n * ],\n * \"caching\": {\n * \"enabled\": true,\n * \"ttl\": 300,\n * \"strategy\": \"ttl\"\n * },\n * \"fallback\": {\n * \"enabled\": true,\n * \"showError\": true\n * },\n * \"rateLimit\": {\n * \"requestsPerSecond\": 10,\n * \"burstSize\": 20\n * }\n * }\n * ```\n */\nexport const ExternalLookupSchema = z.object({\n /**\n * Name of the field that uses external lookup\n */\n fieldName: z.string().describe('Field name'),\n\n /**\n * External data source configuration\n */\n dataSource: ExternalDataSourceSchema.describe('External data source'),\n\n /**\n * Query configuration for fetching external data\n */\n query: z.object({\n /**\n * API endpoint path (relative to base endpoint)\n */\n endpoint: z.string().describe('Query endpoint path'),\n\n /**\n * HTTP method for the query\n * @default 'GET'\n */\n method: z.enum(['GET', 'POST']).optional().default('GET').describe('HTTP method'),\n\n /**\n * Query parameters or request body\n */\n parameters: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n }).describe('Query configuration'),\n\n /**\n * Mapping between external and local fields\n */\n fieldMappings: z.array(ExternalFieldMappingSchema).describe('Field mappings'),\n\n /**\n * Cache configuration for external data\n */\n caching: z.object({\n /**\n * Whether caching is enabled\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Cache enabled'),\n\n /**\n * Time-to-live in seconds\n * @default 300\n */\n ttl: z.number().optional().default(300).describe('Cache TTL (seconds)'),\n\n /**\n * Cache eviction strategy\n * @default 'ttl'\n */\n strategy: z.enum(['lru', 'lfu', 'ttl']).optional().default('ttl').describe('Cache strategy'),\n }).optional().describe('Caching configuration'),\n\n /**\n * Fallback behavior when external system is unavailable\n */\n fallback: z.object({\n /**\n * Whether fallback is enabled\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Fallback enabled'),\n\n /**\n * Default value to use when external system fails\n */\n defaultValue: z.unknown().optional().describe('Default fallback value'),\n\n /**\n * Whether to show error message to user\n * @default true\n */\n showError: z.boolean().optional().default(true).describe('Show error to user'),\n }).optional().describe('Fallback configuration'),\n\n /**\n * Rate limiting to prevent overwhelming external system\n */\n rateLimit: z.object({\n /**\n * Maximum requests per second\n */\n requestsPerSecond: z.number().describe('Requests per second limit'),\n\n /**\n * Burst size for handling spikes\n */\n burstSize: z.number().optional().describe('Burst size'),\n }).optional().describe('Rate limiting'),\n\n /**\n * Retry configuration with exponential backoff\n *\n * @example\n * ```json\n * {\n * \"maxRetries\": 3,\n * \"initialDelayMs\": 1000,\n * \"maxDelayMs\": 30000,\n * \"backoffMultiplier\": 2,\n * \"retryableStatusCodes\": [429, 500, 502, 503, 504]\n * }\n * ```\n */\n retry: z.object({\n /** Maximum number of retry attempts */\n maxRetries: z.number().min(0).default(3).describe('Maximum retry attempts'),\n /** Initial delay before first retry (ms) */\n initialDelayMs: z.number().default(1000).describe('Initial retry delay in milliseconds'),\n /** Maximum delay between retries (ms) */\n maxDelayMs: z.number().default(30000).describe('Maximum retry delay in milliseconds'),\n /** Backoff multiplier for exponential backoff */\n backoffMultiplier: z.number().default(2).describe('Exponential backoff multiplier'),\n /** HTTP status codes that trigger a retry */\n retryableStatusCodes: z.array(z.number()).default([429, 500, 502, 503, 504])\n .describe('HTTP status codes that are retryable'),\n }).optional().describe('Retry configuration with exponential backoff'),\n\n /**\n * Request/response transformation pipeline\n *\n * Allows transforming request parameters and response data\n * before they are processed by the external lookup system.\n */\n transform: z.object({\n /** Transform request parameters before sending */\n request: z.object({\n /** Header transformations (key-value additions) */\n headers: z.record(z.string(), z.string()).optional().describe('Additional request headers'),\n /** Query parameter transformations */\n queryParams: z.record(z.string(), z.string()).optional().describe('Additional query parameters'),\n }).optional().describe('Request transformation'),\n /** Transform response data after receiving */\n response: z.object({\n /** JSONPath expression to extract data from response */\n dataPath: z.string().optional().describe('JSONPath to extract data (e.g., \"$.data.results\")'),\n /** JSONPath expression to extract total count for pagination */\n totalPath: z.string().optional().describe('JSONPath to extract total count (e.g., \"$.meta.total\")'),\n }).optional().describe('Response transformation'),\n }).optional().describe('Request/response transformation pipeline'),\n\n /** Pagination support for external data sources */\n pagination: z.object({\n /** Pagination type */\n type: z.enum(['offset', 'cursor', 'page']).default('offset').describe('Pagination type'),\n /** Page size */\n pageSize: z.number().default(100).describe('Items per page'),\n /** Maximum pages to fetch */\n maxPages: z.number().optional().describe('Maximum number of pages to fetch'),\n }).optional().describe('Pagination configuration for external data'),\n});\n\n// Type exports\nexport type ExternalLookup = z.infer;\nexport type ExternalDataSource = z.infer;\nexport type ExternalFieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n\n/**\n * Driver Identifier\n * Can be a built-in driver or a plugin-contributed driver (e.g., \"com.vendor.snowflake\").\n */\nexport const DriverType = z.string().describe('Underlying driver identifier');\n\n/**\n * Driver Definition Schema\n * Metadata describing a Database Driver.\n * Plugins use this to register new connectivity options.\n */\nexport const DriverDefinitionSchema = z.object({\n id: z.string().describe('Unique driver identifier (e.g. \"postgres\")'),\n label: z.string().describe('Display label (e.g. \"PostgreSQL\")'),\n description: z.string().optional(),\n icon: z.string().optional(),\n \n /**\n * Configuration Schema (JSON Schema)\n * Describes the structure of the `config` object needed for this driver.\n * Used by the UI to generate the connection form.\n */\n configSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for connection configuration'),\n \n /**\n * Default Capabilities\n * What this driver supports out-of-the-box.\n */\n capabilities: z.lazy(() => DatasourceCapabilities).optional(),\n});\n\n/**\n * Datasource Capabilities Schema\n * Declares what this datasource naturally supports.\n * The ObjectQL engine uses this to determine what logic to push down\n * and what to compute in memory.\n */\nexport const DatasourceCapabilities = z.object({\n // ============================================================================\n // Transaction & Connection Management\n // ============================================================================\n \n /** Can handle ACID transactions? */\n transactions: z.boolean().default(false),\n \n // ============================================================================\n // Query Operations\n // ============================================================================\n \n /** Can execute WHERE clause filters natively? */\n queryFilters: z.boolean().default(false),\n \n /** Can perform aggregation (group by, sum, avg)? */\n queryAggregations: z.boolean().default(false),\n \n /** Can perform ORDER BY sorting? */\n querySorting: z.boolean().default(false),\n \n /** Can perform LIMIT/OFFSET pagination? */\n queryPagination: z.boolean().default(false),\n \n /** Can perform window functions? */\n queryWindowFunctions: z.boolean().default(false),\n \n /** Can perform subqueries? */\n querySubqueries: z.boolean().default(false),\n \n /** Can execute SQL-like joins natively? */\n joins: z.boolean().default(false),\n \n // ============================================================================\n // Advanced Features\n // ============================================================================\n \n /** Can perform full-text search? */\n fullTextSearch: z.boolean().default(false),\n \n /** Is read-only? */\n readOnly: z.boolean().default(false),\n \n /** Is scheme-less (needs schema inference)? */\n dynamicSchema: z.boolean().default(false),\n});\n\n/**\n * Datasource Schema\n * Represents a connection to an external data store.\n */\nexport const DatasourceSchema = z.object({\n /** Machine Name */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique datasource identifier'),\n \n /** Human Label */\n label: z.string().optional().describe('Display label'),\n \n /** Driver */\n driver: DriverType.describe('Underlying driver type'),\n \n /** \n * Connection Configuration \n * Specific to the driver (e.g., host, port, user, password, bucket, etc.)\n * Stored securely (passwords usually interpolated from ENV).\n */\n config: z.record(z.string(), z.unknown()).describe('Driver specific configuration'),\n \n /**\n * Connection Pool Configuration\n * Standard connection pooling settings.\n */\n pool: z.object({\n min: z.number().default(0).describe('Minimum connections'),\n max: z.number().default(10).describe('Maximum connections'),\n idleTimeoutMillis: z.number().default(30000).describe('Idle timeout'),\n connectionTimeoutMillis: z.number().default(3000).describe('Connection establishment timeout'),\n }).optional().describe('Connection pool settings'),\n\n /**\n * Read Replicas\n * Optional list of duplicate configurations for read-only operations.\n * Useful for scaling read throughput.\n */\n readReplicas: z.array(z.record(z.string(), z.unknown())).optional().describe('Read-only replica configurations'),\n\n /**\n * Capability Overrides\n * Manually override what the driver claims to support.\n */\n capabilities: DatasourceCapabilities.optional().describe('Capability overrides'),\n \n /** Health Check */\n healthCheck: z.object({\n enabled: z.boolean().default(true).describe('Enable health check endpoint'),\n intervalMs: z.number().default(30000).describe('Health check interval in milliseconds'),\n timeoutMs: z.number().default(5000).describe('Health check timeout in milliseconds'),\n }).optional().describe('Datasource health check configuration'),\n\n /** SSL/TLS Configuration */\n ssl: z.object({\n enabled: z.boolean().default(false).describe('Enable SSL/TLS for database connection'),\n rejectUnauthorized: z.boolean().default(true).describe('Reject connections with invalid/self-signed certificates'),\n ca: z.string().optional().describe('CA certificate (PEM format or path to file)'),\n cert: z.string().optional().describe('Client certificate (PEM format or path to file)'),\n key: z.string().optional().describe('Client private key (PEM format or path to file)'),\n }).optional().describe('SSL/TLS configuration for secure database connections'),\n\n /** Retry Policy */\n retryPolicy: z.object({\n maxRetries: z.number().default(3).describe('Maximum number of retry attempts'),\n baseDelayMs: z.number().default(1000).describe('Base delay between retries in milliseconds'),\n maxDelayMs: z.number().default(30000).describe('Maximum delay between retries in milliseconds'),\n backoffMultiplier: z.number().default(2).describe('Exponential backoff multiplier'),\n }).optional().describe('Connection retry policy for transient failures'),\n\n /** Description */\n description: z.string().optional().describe('Internal description'),\n \n /** Is enabled? */\n active: z.boolean().default(true).describe('Is datasource enabled'),\n});\n\nexport type Datasource = z.infer;\nexport type DatasourceCapabilitiesType = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Analytics/Semantic Layer Protocol\n * \n * Defines the \"Business Logic\" for data analysis.\n * Inspired by Cube.dev, LookML, and dbt MetricFlow.\n * \n * This layer decouples the \"Physical Data\" (Tables/Columns) from the \n * \"Business Data\" (Metrics/Dimensions).\n */\n\n/**\n * Aggregation Metric Type\n * The mathematical operation to perform on a metric.\n */\nexport const AggregationMetricType = z.enum([\n 'count', \n 'sum', \n 'avg', \n 'min', \n 'max', \n 'count_distinct', \n 'number', // Custom SQL expression returning a number\n 'string', // Custom SQL expression returning a string\n 'boolean' // Custom SQL expression returning a boolean\n]);\n\n/**\n * Dimension Type\n * The nature of the grouping field.\n */\nexport const DimensionType = z.enum([\n 'string', \n 'number', \n 'boolean', \n 'time', \n 'geo'\n]);\n\n/**\n * Time Interval for Time Dimensions\n */\nexport const TimeUpdateInterval = z.enum([\n 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'\n]);\n\n/**\n * Metric Schema\n * A quantitative measurement (e.g., \"Total Revenue\", \"Average Order Value\").\n */\nexport const MetricSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique metric ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: AggregationMetricType,\n \n /** Source Calculation */\n sql: z.string().describe('SQL expression or field reference'),\n \n /** Filtering for this specific metric (e.g. \"Revenue from Premium Users\") */\n filters: z.array(z.object({\n sql: z.string()\n })).optional(),\n \n /** Format for display (e.g. \"currency\", \"percent\") */\n format: z.string().optional(),\n});\n\n/**\n * Dimension Schema\n * A categorical attribute to group by (e.g., \"Product Category\", \"Order Date\").\n */\nexport const DimensionSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique dimension ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: DimensionType,\n \n /** Source Column */\n sql: z.string().describe('SQL expression or column reference'),\n \n /** For Time Dimensions: Supported Granularities */\n granularities: z.array(TimeUpdateInterval).optional(),\n});\n\n/**\n * Join Schema\n * Defines how this cube relates to others.\n */\nexport const CubeJoinSchema = z.object({\n name: z.string().describe('Target cube name'),\n relationship: z.enum(['one_to_one', 'one_to_many', 'many_to_one']).default('many_to_one'),\n sql: z.string().describe('Join condition (ON clause)'),\n});\n\n/**\n * Cube Schema\n * A logical data model representing a business entity or process for analysis.\n * Maps physical tables to business metrics and dimensions.\n */\nexport const CubeSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Cube name (snake_case)'),\n title: z.string().optional(),\n description: z.string().optional(),\n \n /** Physical Data Source */\n sql: z.string().describe('Base SQL statement or Table Name'),\n \n /** Semantic Definitions */\n measures: z.record(z.string(), MetricSchema).describe('Quantitative metrics'),\n dimensions: z.record(z.string(), DimensionSchema).describe('Qualitative attributes'),\n \n /** Relationships */\n joins: z.record(z.string(), CubeJoinSchema).optional(),\n \n /** Pre-aggregations / Caching */\n refreshKey: z.object({\n every: z.string().optional(), // e.g. \"1 hour\"\n sql: z.string().optional(), // SQL to check for data changes\n }).optional(),\n \n /** Access Control */\n public: z.boolean().default(false),\n});\n\n/**\n * Analytics Query Schema\n * The request format for the Analytics API.\n */\nexport const AnalyticsQuerySchema = z.object({\n cube: z.string().optional().describe('Target cube name (optional when provided externally, e.g. in API request wrapper)'),\n measures: z.array(z.string()).describe('List of metrics to calculate'),\n dimensions: z.array(z.string()).optional().describe('List of dimensions to group by'),\n \n filters: z.array(z.object({\n member: z.string().describe('Dimension or Measure'),\n operator: z.enum(['equals', 'notEquals', 'contains', 'notContains', 'gt', 'gte', 'lt', 'lte', 'set', 'notSet', 'inDateRange']),\n values: z.array(z.string()).optional(),\n })).optional(),\n \n timeDimensions: z.array(z.object({\n dimension: z.string(),\n granularity: TimeUpdateInterval.optional(),\n dateRange: z.union([\n z.string(), // \"Last 7 days\"\n z.array(z.string()) // [\"2023-01-01\", \"2023-01-31\"]\n ]).optional(),\n })).optional(),\n \n order: z.record(z.string(), z.enum(['asc', 'desc'])).optional(),\n \n limit: z.number().optional(),\n offset: z.number().optional(),\n \n timezone: z.string().optional().default('UTC'),\n});\n\nexport type Metric = z.infer;\nexport type Dimension = z.infer;\nexport type CubeJoin = z.infer;\nexport type Cube = z.infer;\nexport type AnalyticsQuery = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Feed Item Type\n * Unified activity types for the record timeline.\n * Covers comments, field changes, tasks, events, and system activities.\n */\nexport const FeedItemType = z.enum([\n 'comment',\n 'field_change',\n 'task',\n 'event',\n 'email',\n 'call',\n 'note',\n 'file',\n 'record_create',\n 'record_delete',\n 'approval',\n 'sharing',\n 'system',\n]);\nexport type FeedItemType = z.infer;\n\n/**\n * Mention Schema\n * Represents an @mention within comment body text.\n */\nexport const MentionSchema = z.object({\n type: z.enum(['user', 'team', 'record']).describe('Mention target type'),\n id: z.string().describe('Target ID'),\n name: z.string().describe('Display name for rendering'),\n offset: z.number().int().min(0).describe('Character offset in body text'),\n length: z.number().int().min(1).describe('Length of mention token in body text'),\n});\nexport type Mention = z.infer;\n\n/**\n * Field Change Entry Schema\n * Represents a single field-level change within a field_change feed item.\n */\nexport const FieldChangeEntrySchema = z.object({\n field: z.string().describe('Field machine name'),\n fieldLabel: z.string().optional().describe('Field display label'),\n oldValue: z.unknown().optional().describe('Previous value'),\n newValue: z.unknown().optional().describe('New value'),\n oldDisplayValue: z.string().optional().describe('Human-readable old value'),\n newDisplayValue: z.string().optional().describe('Human-readable new value'),\n});\nexport type FieldChangeEntry = z.infer;\n\n/**\n * Reaction Schema\n * Represents an emoji reaction on a feed item.\n */\nexport const ReactionSchema = z.object({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n userIds: z.array(z.string()).describe('Users who reacted'),\n count: z.number().int().min(1).describe('Total reaction count'),\n});\nexport type Reaction = z.infer;\n\n/**\n * Feed Actor Schema\n * Represents the actor who performed the action.\n */\nexport const FeedActorSchema = z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n avatarUrl: z.string().url().optional().describe('Actor avatar URL'),\n source: z.string().optional().describe('Source application (e.g., \"Omni\", \"API\", \"Studio\")'),\n});\nexport type FeedActor = z.infer;\n\n/**\n * Feed Item Visibility\n */\nexport const FeedVisibility = z.enum(['public', 'internal', 'private']);\nexport type FeedVisibility = z.infer;\n\n/**\n * Feed Item Schema\n * A single entry in the unified activity timeline.\n *\n * @example Comment\n * {\n * id: 'feed_001',\n * type: 'comment',\n * object: 'account',\n * recordId: 'rec_123',\n * body: 'Great progress! @jane.doe can you follow up?',\n * mentions: [{ type: 'user', id: 'user_123', name: 'Jane Doe', offset: 17, length: 9 }],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:30:00Z',\n * }\n *\n * @example Field Change\n * {\n * id: 'feed_002',\n * type: 'field_change',\n * object: 'account',\n * recordId: 'rec_123',\n * changes: [\n * { field: 'status', oldDisplayValue: 'New', newDisplayValue: 'Active' },\n * { field: 'region', oldDisplayValue: '', newDisplayValue: 'Asia-Pacific' },\n * ],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:25:00Z',\n * }\n */\nexport const FeedItemSchema = z.object({\n /** Unique identifier */\n id: z.string().describe('Feed item ID'),\n\n /** Feed item type */\n type: FeedItemType.describe('Activity type'),\n\n /** Target record reference */\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID this feed item belongs to'),\n\n /** Actor (who performed the action) */\n actor: FeedActorSchema.describe('Who performed this action'),\n\n /** Content (for comments/notes) */\n body: z.string().optional().describe('Rich text body (Markdown supported)'),\n\n /** @Mentions */\n mentions: z.array(MentionSchema).optional().describe('Mentioned users/teams/records'),\n\n /** Field changes (for field_change type) */\n changes: z.array(FieldChangeEntrySchema).optional().describe('Field-level changes'),\n\n /** Reactions */\n reactions: z.array(ReactionSchema).optional().describe('Emoji reactions on this item'),\n\n /** Reply threading */\n parentId: z.string().optional().describe('Parent feed item ID for threaded replies'),\n replyCount: z.number().int().min(0).default(0).describe('Number of replies'),\n\n /** Pin / Star */\n pinned: z.boolean().default(false).describe('Whether the feed item is pinned to the top of the timeline'),\n pinnedAt: z.string().datetime().optional().describe('Timestamp when the item was pinned'),\n pinnedBy: z.string().optional().describe('User ID who pinned the item'),\n starred: z.boolean().default(false).describe('Whether the feed item is starred/bookmarked by the current user'),\n starredAt: z.string().datetime().optional().describe('Timestamp when the item was starred'),\n\n /** Visibility */\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public (all users), internal (team only), private (author + mentioned)'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n editedAt: z.string().datetime().optional().describe('When comment was last edited'),\n isEdited: z.boolean().default(false).describe('Whether comment has been edited'),\n});\nexport type FeedItem = z.infer;\n\n/**\n * Feed Filter Mode\n * Controls which feed item types to display in the timeline.\n */\nexport const FeedFilterMode = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\nexport type FeedFilterMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Subscription Event Type\n * Event types that can be subscribed to for record-level notifications.\n */\nexport const SubscriptionEventType = z.enum([\n 'comment',\n 'mention',\n 'field_change',\n 'task',\n 'approval',\n 'all',\n]);\nexport type SubscriptionEventType = z.infer;\n\n/**\n * Notification Channel\n * Delivery channels for record subscription notifications.\n */\nexport const NotificationChannel = z.enum([\n 'in_app',\n 'email',\n 'push',\n 'slack',\n]);\nexport type NotificationChannel = z.infer;\n\n/**\n * Record Subscription Schema\n * Defines a user's subscription to record-level notifications.\n * Enables Airtable-style bell icon for record change notifications.\n */\nexport const RecordSubscriptionSchema = z.object({\n /** Target */\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n\n /** Subscriber */\n userId: z.string().describe('Subscribing user ID'),\n\n /** Events to subscribe to */\n events: z.array(SubscriptionEventType)\n .default(['all'])\n .describe('Event types to receive notifications for'),\n\n /** Notification channels */\n channels: z.array(NotificationChannel)\n .default(['in_app'])\n .describe('Notification delivery channels'),\n\n /** Active */\n active: z.boolean().default(true).describe('Whether the subscription is active'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Subscription creation timestamp'),\n});\nexport type RecordSubscription = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Turso Multi-Tenant Router Schema\n *\n * Defines the configuration for Turso DB-per-Tenant architectures where each\n * tenant receives an independent Turso/libSQL database. The router resolves\n * the correct database URL and auth token per request based on the current\n * tenant context.\n *\n * Architecture: Shared Compute + Isolated Data\n * - Serverless functions are shared across tenants\n * - Each tenant has a physically isolated Turso database\n * - Turso Platform API manages database lifecycle (create/delete/suspend)\n *\n * @see https://docs.turso.tech/features/multi-db-schemas\n */\n\n// ==========================================================================\n// 1. Tenant Resolver Strategy\n// ==========================================================================\n\n/**\n * Strategy for resolving which tenant database to connect to.\n */\nexport const TenantResolverStrategySchema = z.enum([\n 'header', // Resolve from X-Tenant-ID request header\n 'subdomain', // Resolve from subdomain (e.g., acme.app.com → acme)\n 'path', // Resolve from URL path segment (e.g., /api/acme/...)\n 'token', // Resolve from JWT claim (e.g., tenant_id in access token)\n 'lookup', // Resolve from control-plane database lookup\n]).describe('Strategy for resolving tenant identity from request context');\n\nexport type TenantResolverStrategy = z.infer;\n\n// ==========================================================================\n// 2. Turso Group Configuration\n// ==========================================================================\n\n/**\n * Turso Database Group Configuration.\n * Groups allow databases to share schema and be managed as a unit.\n * All databases in a group are deployed to the same set of locations.\n *\n * @see https://docs.turso.tech/features/multi-db-schemas\n */\nexport const TursoGroupSchema = z.object({\n /**\n * Group name identifier.\n * Used to reference the group when creating new tenant databases.\n */\n name: z.string().min(1).describe('Turso database group name'),\n\n /**\n * Primary location for the group (Turso region code).\n * Example: 'iad' (US East), 'lhr' (London), 'nrt' (Tokyo)\n */\n primaryLocation: z.string().min(2).describe('Primary Turso region code (e.g., iad, lhr, nrt)'),\n\n /**\n * Additional replica locations for read performance.\n * Databases in this group will have read replicas in these regions.\n */\n replicaLocations: z.array(z.string().min(2)).default([]).describe('Additional replica region codes'),\n\n /**\n * Schema database name within the group.\n * When using multi-db schemas, this is the \"parent\" database\n * whose schema is shared by all child (tenant) databases.\n */\n schemaDatabase: z.string().optional().describe('Schema database name for multi-db schemas'),\n}).describe('Turso database group configuration');\n\nexport type TursoGroup = z.infer;\n\n// ==========================================================================\n// 3. Tenant Database Lifecycle Hooks\n// ==========================================================================\n\n/**\n * Database Lifecycle Hook Schema.\n * Defines what happens at each tenant lifecycle event.\n */\nexport const TenantDatabaseLifecycleSchema = z.object({\n /**\n * Hook executed when a new tenant is created.\n * Defines how the tenant database is provisioned.\n */\n onTenantCreate: z.object({\n /** Whether to automatically create a Turso database */\n autoCreate: z.boolean().default(true).describe('Auto-create database on tenant registration'),\n\n /** Database group to create the database in */\n group: z.string().optional().describe('Turso group for the new database'),\n\n /** Whether to apply schema from the group schema database */\n applyGroupSchema: z.boolean().default(true).describe('Apply shared schema from group'),\n\n /** Seed data to populate on creation */\n seedData: z.boolean().default(false).describe('Populate seed data on creation'),\n }).describe('Tenant creation hook'),\n\n /**\n * Hook executed when a tenant is deleted/destroyed.\n */\n onTenantDelete: z.object({\n /** Whether to destroy the database immediately or schedule for deletion */\n immediate: z.boolean().default(false).describe('Destroy database immediately'),\n\n /** Grace period in hours before permanent deletion (soft-delete) */\n gracePeriodHours: z.number().int().min(0).default(72).describe('Grace period before permanent deletion'),\n\n /** Whether to create a final backup before deletion */\n createBackup: z.boolean().default(true).describe('Create backup before deletion'),\n }).describe('Tenant deletion hook'),\n\n /**\n * Hook executed when a tenant is suspended (e.g., unpaid, policy violation).\n */\n onTenantSuspend: z.object({\n /** Whether to revoke auth tokens on suspension */\n revokeTokens: z.boolean().default(true).describe('Revoke auth tokens on suspension'),\n\n /** Whether to set database to read-only mode */\n readOnly: z.boolean().default(true).describe('Set database to read-only on suspension'),\n }).describe('Tenant suspension hook'),\n}).describe('Tenant database lifecycle hooks');\n\nexport type TenantDatabaseLifecycle = z.infer;\n\n// ==========================================================================\n// 4. Multi-Tenant Router Configuration\n// ==========================================================================\n\n/**\n * Turso Multi-Tenant Configuration Schema.\n *\n * Configures the DB-per-Tenant router that resolves the correct Turso\n * database for each request. Works with the Turso Platform API to manage\n * database lifecycle.\n *\n * @example\n * ```ts\n * const config = TursoMultiTenantConfigSchema.parse({\n * organizationSlug: 'myorg',\n * urlTemplate: 'libsql://{tenant_id}-myorg.turso.io',\n * groupAuthToken: process.env.TURSO_GROUP_AUTH_TOKEN,\n * tenantResolverStrategy: 'token',\n * group: {\n * name: 'production',\n * primaryLocation: 'iad',\n * replicaLocations: ['lhr', 'nrt'],\n * schemaDatabase: 'schema-db',\n * },\n * lifecycle: {\n * onTenantCreate: { autoCreate: true, applyGroupSchema: true },\n * onTenantDelete: { gracePeriodHours: 168 },\n * onTenantSuspend: { revokeTokens: true },\n * },\n * });\n * ```\n */\nexport const TursoMultiTenantConfigSchema = z.object({\n /**\n * Turso organization slug.\n * Used for Platform API calls and URL construction.\n */\n organizationSlug: z.string().min(1).describe('Turso organization slug'),\n\n /**\n * URL template for constructing tenant database URLs.\n * Use `{tenant_id}` as placeholder for the tenant identifier.\n *\n * Example: 'libsql://{tenant_id}-myorg.turso.io'\n */\n urlTemplate: z.string().min(1).describe('URL template with {tenant_id} placeholder'),\n\n /**\n * Group-level auth token for Turso Platform API operations.\n * Used for database creation, deletion, and management.\n * This token has full access to all databases in the group.\n */\n groupAuthToken: z.string().min(1).describe('Group-level auth token for platform operations'),\n\n /**\n * Strategy for resolving tenant identity from the request context.\n */\n tenantResolverStrategy: TenantResolverStrategySchema.default('token'),\n\n /**\n * Turso database group configuration.\n */\n group: TursoGroupSchema.optional().describe('Database group configuration'),\n\n /**\n * Lifecycle hooks for tenant database management.\n */\n lifecycle: TenantDatabaseLifecycleSchema.optional().describe('Lifecycle hooks'),\n\n /**\n * Maximum number of cached tenant database connections.\n * Connections are evicted using LRU strategy when the limit is reached.\n */\n maxCachedConnections: z.number().int().min(1).default(100).describe('Max cached tenant connections (LRU)'),\n\n /**\n * Connection cache TTL in seconds.\n * Cached connections are refreshed after this period.\n */\n connectionCacheTTL: z.number().int().min(0).default(300).describe('Connection cache TTL in seconds'),\n}).describe('Turso multi-tenant router configuration');\n\nexport type TursoMultiTenantConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Permission Protocol Exports\n * \n * Fine-grained Access Control\n * - Permission Sets (CRUD + Field-Level Security)\n * - Sharing Rules (Record Ownership)\n * - Territory Management (Geographic/Hierarchical)\n * - Row-Level Security (RLS - PostgreSQL-style)\n */\n\nexport * from './permission.zod';\nexport * from './sharing.zod';\nexport * from './territory.zod';\nexport * from './rls.zod';\nexport * from './policy.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Row-Level Security (RLS) Protocol\n * \n * Implements fine-grained record-level access control inspired by PostgreSQL RLS\n * and Salesforce Criteria-Based Sharing Rules.\n * \n * ## Overview\n * \n * Row-Level Security (RLS) allows you to control which rows users can access\n * in database tables based on their identity and role. Unlike object-level\n * permissions (CRUD), RLS provides record-level filtering.\n * \n * ## Use Cases\n * \n * 1. **Multi-Tenant Data Isolation**\n * - Users only see records from their organization\n * - `using: \"tenant_id = current_user.tenant_id\"`\n * \n * 2. **Ownership-Based Access**\n * - Users only see records they own\n * - `using: \"owner_id = current_user.id\"`\n * \n * 3. **Department-Based Access**\n * - Users only see records from their department\n * - `using: \"department = current_user.department\"`\n * \n * 4. **Regional Access Control**\n * - Sales reps only see accounts in their territory\n * - `using: \"region IN (current_user.assigned_regions)\"`\n * \n * 5. **Time-Based Access**\n * - Users can only access active records\n * - `using: \"status = 'active' AND expiry_date > NOW()\"`\n * \n * ## PostgreSQL RLS Comparison\n * \n * PostgreSQL RLS Example:\n * ```sql\n * CREATE POLICY tenant_isolation ON accounts\n * FOR SELECT\n * USING (tenant_id = current_setting('app.current_tenant_id')::uuid);\n * \n * CREATE POLICY account_insert ON accounts\n * FOR INSERT\n * WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);\n * ```\n * \n * ObjectStack RLS Equivalent:\n * ```typescript\n * {\n * name: 'tenant_isolation',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id'\n * }\n * ```\n * \n * ## Salesforce Sharing Rules Comparison\n * \n * Salesforce uses \"Sharing Rules\" and \"Role Hierarchy\" for record-level access.\n * ObjectStack RLS provides similar functionality with more flexibility.\n * \n * Salesforce:\n * - Criteria-Based Sharing: Share records matching criteria with users/roles\n * - Owner-Based Sharing: Share records based on owner's role\n * - Manual Sharing: Individual record sharing\n * \n * ObjectStack RLS:\n * - More flexible formula-based conditions\n * - Direct SQL-like syntax\n * - Supports complex logic with AND/OR/NOT\n * \n * ## Best Practices\n * \n * 1. **Always Define SELECT Policy**: Control what users can view\n * 2. **Define INSERT/UPDATE CHECK Policies**: Prevent data leakage\n * 3. **Use Role-Based Policies**: Apply different rules to different roles\n * 4. **Test Thoroughly**: RLS can have complex interactions\n * 5. **Monitor Performance**: Complex RLS policies can impact query performance\n * \n * ## Security Considerations\n * \n * 1. **Defense in Depth**: RLS is one layer; use with object permissions\n * 2. **Default Deny**: If no policy matches, access is denied\n * 3. **Policy Precedence**: More permissive policy wins (OR logic)\n * 4. **Context Variables**: Ensure current_user context is always set\n * \n * @see https://www.postgresql.org/docs/current/ddl-rowsecurity.html\n * @see https://help.salesforce.com/s/articleView?id=sf.security_sharing_rules.htm\n */\n\n/**\n * RLS Operation Enum\n * Specifies which database operation this policy applies to.\n * \n * - **select**: Controls which rows can be read (SELECT queries)\n * - **insert**: Controls which rows can be inserted (INSERT statements)\n * - **update**: Controls which rows can be updated (UPDATE statements)\n * - **delete**: Controls which rows can be deleted (DELETE statements)\n * - **all**: Shorthand for all operations (equivalent to defining 4 separate policies)\n */\nexport const RLSOperation = z.enum(['select', 'insert', 'update', 'delete', 'all']);\n\nexport type RLSOperation = z.infer;\n\n/**\n * Row-Level Security Policy Schema\n * \n * Defines a single RLS policy that filters records based on conditions.\n * Multiple policies can be defined for the same object, and they are\n * combined with OR logic (union of results).\n * \n * @example Multi-Tenant Isolation\n * ```typescript\n * {\n * name: 'tenant_isolation',\n * label: 'Multi-Tenant Data Isolation',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id',\n * enabled: true\n * }\n * ```\n * \n * @example Owner-Based Access\n * ```typescript\n * {\n * name: 'owner_access',\n * label: 'Users Can View Their Own Records',\n * object: 'opportunity',\n * operation: 'select',\n * using: 'owner_id = current_user.id',\n * enabled: true\n * }\n * ```\n * \n * @example Manager Can View Team Records\n * ```typescript\n * {\n * name: 'manager_team_access',\n * label: 'Managers Can View Team Records',\n * object: 'task',\n * operation: 'select',\n * using: 'assigned_to_id IN (SELECT id FROM users WHERE manager_id = current_user.id)',\n * roles: ['manager', 'director'],\n * enabled: true\n * }\n * ```\n * \n * @example Prevent Cross-Tenant Data Insertion\n * ```typescript\n * {\n * name: 'tenant_insert_check',\n * label: 'Prevent Cross-Tenant Data Creation',\n * object: 'account',\n * operation: 'insert',\n * check: 'tenant_id = current_user.tenant_id',\n * enabled: true\n * }\n * ```\n * \n * @example Regional Sales Access\n * ```typescript\n * {\n * name: 'regional_sales_access',\n * label: 'Sales Reps Access Regional Accounts',\n * object: 'account',\n * operation: 'select',\n * using: 'region = current_user.region OR region IS NULL',\n * roles: ['sales_rep'],\n * enabled: true\n * }\n * ```\n * \n * @example Time-Based Access Control\n * ```typescript\n * {\n * name: 'active_records_only',\n * label: 'Users Only Access Active Records',\n * object: 'contract',\n * operation: 'select',\n * using: 'status = \"active\" AND start_date <= NOW() AND end_date >= NOW()',\n * enabled: true\n * }\n * ```\n * \n * @example Hierarchical Access (Role-Based)\n * ```typescript\n * {\n * name: 'executive_full_access',\n * label: 'Executives See All Records',\n * object: 'account',\n * operation: 'all',\n * using: '1 = 1', // Always true - see everything\n * roles: ['ceo', 'cfo', 'cto'],\n * enabled: true\n * }\n * ```\n */\nexport const RowLevelSecurityPolicySchema = z.object({\n /**\n * Unique identifier for this policy.\n * Must be unique within the object.\n * Use snake_case following ObjectStack naming conventions.\n * \n * @example \"tenant_isolation\", \"owner_access\", \"manager_team_view\"\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Policy unique identifier (snake_case)'),\n\n /**\n * Human-readable label for the policy.\n * Used in admin UI and logs.\n * \n * @example \"Multi-Tenant Data Isolation\", \"Owner-Based Access\"\n */\n label: z.string()\n .optional()\n .describe('Human-readable policy label'),\n\n /**\n * Description explaining what this policy does and why.\n * Helps with governance and compliance.\n * \n * @example \"Ensures users can only access records from their own tenant organization\"\n */\n description: z.string()\n .optional()\n .describe('Policy description and business justification'),\n\n /**\n * Target object (table) this policy applies to.\n * Must reference a valid ObjectStack object name.\n * \n * @example \"account\", \"opportunity\", \"contact\", \"custom_object\"\n */\n object: z.string()\n .describe('Target object name'),\n\n /**\n * Database operation(s) this policy applies to.\n * \n * - **select**: Controls read access (SELECT queries)\n * - **insert**: Controls insert access (INSERT statements)\n * - **update**: Controls update access (UPDATE statements)\n * - **delete**: Controls delete access (DELETE statements)\n * - **all**: Applies to all operations\n * \n * @example \"select\" - Most common, controls what users can view\n * @example \"all\" - Apply same rule to all operations\n */\n operation: RLSOperation\n .describe('Database operation this policy applies to'),\n\n /**\n * USING clause - Filter condition for SELECT/UPDATE/DELETE.\n * \n * This is a SQL-like expression evaluated for each row.\n * Only rows where this expression returns TRUE are accessible.\n * \n * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed).\n * For SELECT/UPDATE/DELETE operations, USING is required.\n * \n * **Security Note**: RLS conditions are executed at the database level with\n * parameterized queries. The implementation must use prepared statements\n * to prevent SQL injection. Never concatenate user input directly into\n * RLS conditions.\n * \n * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations\n * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain\n * semantic equivalence.\n * \n * Available context variables:\n * - `current_user.id` - Current user's ID\n * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext)\n * - `current_user.role` - Current user's role\n * - `current_user.department` - Current user's department\n * - `current_user.*` - Any custom user field\n * - `NOW()` - Current timestamp\n * - `CURRENT_DATE` - Current date\n * - `CURRENT_TIME` - Current time\n * \n * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`),\n * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`).\n * Implementations must handle this mapping.\n * \n * Supported operators:\n * - Comparison: =, !=, <, >, <=, >=, <> (not equal)\n * - Logical: AND, OR, NOT\n * - NULL checks: IS NULL, IS NOT NULL\n * - Set operations: IN, NOT IN\n * - String: LIKE, NOT LIKE, ILIKE (case-insensitive)\n * - Pattern matching: ~ (regex), !~ (not regex)\n * - Subqueries: (SELECT ...)\n * - Array operations: ANY, ALL\n * \n * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE)\n * \n * @example \"tenant_id = current_user.tenant_id\"\n * @example \"owner_id = current_user.id OR created_by = current_user.id\"\n * @example \"department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)\"\n * @example \"status = 'active' AND expiry_date > NOW()\"\n */\n using: z.string()\n .optional()\n .describe('Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies.'),\n\n /**\n * CHECK clause - Validation for INSERT/UPDATE operations.\n * \n * Similar to USING but applies to new/modified rows.\n * Prevents users from creating/updating rows they wouldn't be able to see.\n * \n * **Default Behavior**: If not specified, implementations should use the\n * USING clause as the CHECK clause. This ensures data integrity by preventing\n * users from creating records they cannot view.\n * \n * Use cases:\n * - Prevent cross-tenant data creation\n * - Enforce mandatory field values\n * - Validate data integrity rules\n * - Restrict certain operations (e.g., only allow creating \"draft\" status)\n * \n * @example \"tenant_id = current_user.tenant_id\"\n * @example \"status IN ('draft', 'pending')\" - Only allow certain statuses\n * @example \"created_by = current_user.id\" - Must be the creator\n */\n check: z.string()\n .optional()\n .describe('Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)'),\n\n /**\n * Restrict this policy to specific roles.\n * If specified, only users with these roles will have this policy applied.\n * If omitted, policy applies to all users (except those with bypassRLS permission).\n * \n * Role names must match defined roles in the system.\n * \n * @example [\"sales_rep\", \"account_manager\"]\n * @example [\"employee\"] - Apply to all employees\n * @example [\"guest\"] - Special restrictions for guests\n */\n roles: z.array(z.string())\n .optional()\n .describe('Roles this policy applies to (omit for all roles)'),\n\n /**\n * Whether this policy is currently active.\n * Disabled policies are not evaluated.\n * Useful for temporary policy changes without deletion.\n * \n * @default true\n */\n enabled: z.boolean()\n .default(true)\n .describe('Whether this policy is active'),\n\n /**\n * Policy priority for conflict resolution.\n * Higher numbers = higher priority.\n * When multiple policies apply, the most permissive wins (OR logic).\n * Priority is only used for ordering evaluation (performance).\n * \n * @default 0\n */\n priority: z.number()\n .int()\n .default(0)\n .describe('Policy evaluation priority (higher = evaluated first)'),\n\n /**\n * Tags for policy categorization and reporting.\n * Useful for governance, compliance, and auditing.\n * \n * @example [\"compliance\", \"gdpr\", \"pci\"]\n * @example [\"multi-tenant\", \"security\"]\n */\n tags: z.array(z.string())\n .optional()\n .describe('Policy categorization tags'),\n}).superRefine((data, ctx) => {\n // Ensure at least one of USING or CHECK is provided\n if (!data.using && !data.check) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'At least one of \"using\" or \"check\" must be specified. For SELECT/UPDATE/DELETE operations, provide \"using\". For INSERT operations, provide \"check\".',\n });\n }\n \n // For non-insert operations, USING should typically be present\n // This is a soft warning through documentation, not enforced here\n // since 'all' and mixed operation types are valid\n});\n\n/**\n * RLS Audit Event Schema\n * \n * Records a single RLS policy evaluation event for compliance and debugging.\n */\nexport const RLSAuditEventSchema = z.object({\n /** ISO 8601 timestamp of the evaluation */\n timestamp: z.string()\n .describe('ISO 8601 timestamp of the evaluation'),\n\n /** ID of the user whose access was evaluated */\n userId: z.string()\n .describe('User ID whose access was evaluated'),\n\n /** Database operation being performed */\n operation: z.enum(['select', 'insert', 'update', 'delete'])\n .describe('Database operation being performed'),\n\n /** Target object (table) name */\n object: z.string()\n .describe('Target object name'),\n\n /** Name of the RLS policy evaluated */\n policyName: z.string()\n .describe('Name of the RLS policy evaluated'),\n\n /** Whether access was granted */\n granted: z.boolean()\n .describe('Whether access was granted'),\n\n /** Time taken to evaluate the policy in milliseconds */\n evaluationDurationMs: z.number()\n .describe('Policy evaluation duration in milliseconds'),\n\n /** Which USING/CHECK clause matched */\n matchedCondition: z.string()\n .optional()\n .describe('Which USING/CHECK clause matched'),\n\n /** Number of rows affected by the operation */\n rowCount: z.number()\n .optional()\n .describe('Number of rows affected'),\n\n /** Additional metadata for the audit event */\n metadata: z.record(z.string(), z.unknown())\n .optional()\n .describe('Additional audit event metadata'),\n});\n\nexport type RLSAuditEvent = z.infer;\n\n/**\n * RLS Audit Configuration Schema\n * \n * Controls how RLS policy evaluations are logged and monitored.\n */\nexport const RLSAuditConfigSchema = z.object({\n /** Enable RLS audit logging */\n enabled: z.boolean()\n .describe('Enable RLS audit logging'),\n\n /** Which evaluations to log */\n logLevel: z.enum(['all', 'denied_only', 'granted_only', 'none'])\n .describe('Which evaluations to log'),\n\n /** Where to send audit logs */\n destination: z.enum(['system_log', 'audit_trail', 'external'])\n .describe('Audit log destination'),\n\n /** Sampling rate for high-traffic environments (0-1) */\n sampleRate: z.number()\n .min(0)\n .max(1)\n .describe('Sampling rate (0-1) for high-traffic environments'),\n\n /** Number of days to retain audit logs */\n retentionDays: z.number()\n .int()\n .default(90)\n .describe('Audit log retention period in days'),\n\n /** Whether to include row data in audit logs (security-sensitive) */\n includeRowData: z.boolean()\n .default(false)\n .describe('Include row data in audit logs (security-sensitive)'),\n\n /** Alert when access is denied */\n alertOnDenied: z.boolean()\n .default(true)\n .describe('Send alerts when access is denied'),\n});\n\nexport type RLSAuditConfig = z.infer;\n\n/**\n * RLS Configuration Schema\n * \n * Global configuration for the Row-Level Security system.\n * Defines how RLS is enforced across the entire platform.\n */\nexport const RLSConfigSchema = z.object({\n /**\n * Global RLS enable/disable flag.\n * When false, all RLS policies are ignored (use with caution!).\n * \n * @default true\n */\n enabled: z.boolean()\n .default(true)\n .describe('Enable RLS enforcement globally'),\n\n /**\n * Default behavior when no policies match.\n * \n * - **deny**: Deny access (secure default)\n * - **allow**: Allow access (permissive mode, not recommended)\n * \n * @default \"deny\"\n */\n defaultPolicy: z.enum(['deny', 'allow'])\n .default('deny')\n .describe('Default action when no policies match'),\n\n /**\n * Whether to allow superusers to bypass RLS.\n * Superusers include system administrators and service accounts.\n * \n * @default true\n */\n allowSuperuserBypass: z.boolean()\n .default(true)\n .describe('Allow superusers to bypass RLS'),\n\n /**\n * List of roles that can bypass RLS.\n * Users with these roles see all records regardless of policies.\n * \n * @example [\"system_admin\", \"data_auditor\"]\n */\n bypassRoles: z.array(z.string())\n .optional()\n .describe('Roles that bypass RLS (see all data)'),\n\n /**\n * Whether to log RLS policy evaluations.\n * Useful for debugging and auditing.\n * Can impact performance if enabled globally.\n * \n * @default false\n */\n logEvaluations: z.boolean()\n .default(false)\n .describe('Log RLS policy evaluations for debugging'),\n\n /**\n * Cache RLS policy evaluation results.\n * Can improve performance for frequently accessed records.\n * Cache is invalidated when policies change or user context changes.\n * \n * @default true\n */\n cacheResults: z.boolean()\n .default(true)\n .describe('Cache RLS evaluation results'),\n\n /**\n * Cache TTL in seconds.\n * How long to cache RLS evaluation results.\n * \n * @default 300 (5 minutes)\n */\n cacheTtlSeconds: z.number()\n .int()\n .positive()\n .default(300)\n .describe('Cache TTL in seconds'),\n\n /**\n * Performance optimization: Pre-fetch user context.\n * Load user context once per request instead of per-query.\n * \n * @default true\n */\n prefetchUserContext: z.boolean()\n .default(true)\n .describe('Pre-fetch user context for performance'),\n\n /**\n * Audit logging configuration for RLS evaluations.\n */\n audit: RLSAuditConfigSchema\n .optional()\n .describe('RLS audit logging configuration'),\n});\n\n/**\n * User Context Schema\n * \n * Represents the current user's context for RLS evaluation.\n * This data is used to evaluate USING and CHECK clauses.\n */\nexport const RLSUserContextSchema = z.object({\n /**\n * User ID\n */\n id: z.string()\n .describe('User ID'),\n\n /**\n * User email\n */\n email: z.string()\n .email()\n .optional()\n .describe('User email'),\n\n /**\n * Tenant/Organization ID\n */\n tenantId: z.string()\n .optional()\n .describe('Tenant/Organization ID'),\n\n /**\n * User role(s)\n */\n role: z.union([\n z.string(),\n z.array(z.string()),\n ])\n .optional()\n .describe('User role(s)'),\n\n /**\n * User department\n */\n department: z.string()\n .optional()\n .describe('User department'),\n\n /**\n * Additional custom attributes\n * Can include any custom user fields for RLS evaluation\n */\n attributes: z.record(z.string(), z.unknown())\n .optional()\n .describe('Additional custom user attributes'),\n});\n\n/**\n * RLS Policy Evaluation Result\n * \n * Result of evaluating an RLS policy for a specific record.\n * Used for debugging and audit logging.\n */\nexport const RLSEvaluationResultSchema = z.object({\n /**\n * Policy name that was evaluated\n */\n policyName: z.string()\n .describe('Policy name'),\n\n /**\n * Whether access was granted\n */\n granted: z.boolean()\n .describe('Whether access was granted'),\n\n /**\n * Evaluation duration in milliseconds\n */\n durationMs: z.number()\n .optional()\n .describe('Evaluation duration in milliseconds'),\n\n /**\n * Error message if evaluation failed\n */\n error: z.string()\n .optional()\n .describe('Error message if evaluation failed'),\n\n /**\n * Evaluated USING clause result\n */\n usingResult: z.boolean()\n .optional()\n .describe('USING clause evaluation result'),\n\n /**\n * Evaluated CHECK clause result (for INSERT/UPDATE)\n */\n checkResult: z.boolean()\n .optional()\n .describe('CHECK clause evaluation result'),\n});\n\n/**\n * Type exports\n */\nexport type RowLevelSecurityPolicy = z.infer;\nexport type RLSConfig = z.infer;\nexport type RLSUserContext = z.infer;\nexport type RLSEvaluationResult = z.infer;\n\n/**\n * Helper factory for creating RLS policies\n */\nexport const RLS = {\n /**\n * Create a simple owner-based policy\n */\n ownerPolicy: (object: string, ownerField: string = 'owner_id'): RowLevelSecurityPolicy => ({\n name: `${object}_owner_access`,\n label: `Owner Access for ${object}`,\n object,\n operation: 'all',\n using: `${ownerField} = current_user.id`,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a tenant isolation policy\n */\n tenantPolicy: (object: string, tenantField: string = 'tenant_id'): RowLevelSecurityPolicy => ({\n name: `${object}_tenant_isolation`,\n label: `Tenant Isolation for ${object}`,\n object,\n operation: 'all',\n using: `${tenantField} = current_user.tenant_id`,\n check: `${tenantField} = current_user.tenant_id`,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a role-based policy\n */\n rolePolicy: (object: string, roles: string[], condition: string): RowLevelSecurityPolicy => ({\n name: `${object}_${roles.join('_')}_access`,\n label: `${roles.join(', ')} Access for ${object}`,\n object,\n operation: 'select',\n using: condition,\n roles,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a permissive policy (allow all for specific roles)\n */\n allowAllPolicy: (object: string, roles: string[]): RowLevelSecurityPolicy => ({\n name: `${object}_${roles.join('_')}_full_access`,\n label: `Full Access for ${roles.join(', ')}`,\n object,\n operation: 'all',\n using: '1 = 1', // Always true\n roles,\n enabled: true,\n priority: 0,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { RowLevelSecurityPolicySchema } from './rls.zod';\n\n/**\n * Entity (Object) Level Permissions\n * Defines CRUD + VAMA (View All / Modify All) + Lifecycle access.\n * \n * Refined with enterprise data lifecycle controls:\n * - Transfer (Ownership change)\n * - Restore (Soft delete recovery)\n * - Purge (Hard delete / Compliance)\n */\nexport const ObjectPermissionSchema = z.object({\n /** C: Create */\n allowCreate: z.boolean().default(false).describe('Create permission'),\n /** R: Read (Owned records or Shared records) */\n allowRead: z.boolean().default(false).describe('Read permission'),\n /** U: Edit (Owned records or Shared records) */\n allowEdit: z.boolean().default(false).describe('Edit permission'),\n /** D: Delete (Owned records or Shared records) */\n allowDelete: z.boolean().default(false).describe('Delete permission'),\n \n /** Lifecycle Operations */\n allowTransfer: z.boolean().default(false).describe('Change record ownership'),\n allowRestore: z.boolean().default(false).describe('Restore from trash (Undelete)'),\n allowPurge: z.boolean().default(false).describe('Permanently delete (Hard Delete/GDPR)'),\n\n /** \n * View All Records: Super-user read access. \n * Bypasses Sharing Rules and Ownership checks.\n * Equivalent to Microsoft Dataverse \"Organization\" level read access.\n */\n viewAllRecords: z.boolean().default(false).describe('View All Data (Bypass Sharing)'),\n \n /** \n * Modify All Records: Super-user write access. \n * Bypasses Sharing Rules and Ownership checks.\n * Equivalent to Microsoft Dataverse \"Organization\" level write access.\n */\n modifyAllRecords: z.boolean().default(false).describe('Modify All Data (Bypass Sharing)'),\n});\n\n/**\n * Field Level Security (FLS)\n */\nexport const FieldPermissionSchema = z.object({\n /** Can see this field */\n readable: z.boolean().default(true).describe('Field read access'),\n /** Can edit this field */\n editable: z.boolean().default(false).describe('Field edit access'),\n});\n\n/**\n * Permission Set Schema\n * Defines a collection of permissions that can be assigned to users.\n * \n * DIFFERENTIATION:\n * - Profile: The ONE primary functional definition of a user (e.g. Standard User).\n * - Permission Set: Add-on capabilities assigned to users (e.g. Export Reports).\n * - Role: (Defined in src/system/role.zod.ts) Defines data visibility hierarchy.\n * \n * **NAMING CONVENTION:**\n * Permission set names MUST be lowercase snake_case to prevent security issues.\n * \n * @example Good permission set names\n * - 'read_only'\n * - 'system_admin'\n * - 'standard_user'\n * - 'api_access'\n * \n * @example Bad permission set names (will be rejected)\n * - 'ReadOnly' (camelCase)\n * - 'SystemAdmin' (mixed case)\n * - 'Read Only' (spaces)\n */\nexport const PermissionSetSchema = z.object({\n /** Unique permission set name */\n name: SnakeCaseIdentifierSchema.describe('Permission set unique name (lowercase snake_case)'),\n \n /** Display label */\n label: z.string().optional().describe('Display label'),\n \n /** Is this a Profile? (Base set for a user) */\n isProfile: z.boolean().default(false).describe('Whether this is a user profile'),\n \n /** Object Permissions Map: -> permissions */\n objects: z.record(z.string(), ObjectPermissionSchema).describe('Entity permissions'),\n \n /** Field Permissions Map: . -> permissions */\n fields: z.record(z.string(), FieldPermissionSchema).optional().describe('Field level security'),\n \n /** System permissions (e.g., \"manage_users\") */\n systemPermissions: z.array(z.string()).optional().describe('System level capabilities'),\n \n /**\n * Tab/App Visibility Permissions (Salesforce Pattern)\n * Controls which app tabs are visible, hidden, or set as default for this permission set.\n * \n * @example\n * ```typescript\n * tabPermissions: {\n * 'app_crm': 'visible',\n * 'app_admin': 'hidden',\n * 'app_sales': 'default_on'\n * }\n * ```\n */\n tabPermissions: z.record(z.string(), z.enum(['visible', 'hidden', 'default_on', 'default_off'])).optional()\n .describe('App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)'),\n \n /** \n * Row-Level Security Rules\n * \n * Row-level security policies that filter records based on user context.\n * These rules are applied in addition to object-level permissions.\n * \n * Uses the canonical RLS protocol from rls.zod.ts for comprehensive\n * row-level security features including PostgreSQL-style USING and CHECK clauses.\n * \n * @see {@link RowLevelSecurityPolicySchema} for full RLS specification\n * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation\n * \n * @example Multi-tenant isolation\n * ```typescript\n * rls: [{\n * name: 'tenant_filter',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id'\n * }]\n * ```\n */\n rowLevelSecurity: z.array(RowLevelSecurityPolicySchema).optional()\n .describe('Row-level security policies (see rls.zod.ts for full spec)'),\n \n /**\n * Context-Based Access Control Variables\n * \n * Custom context variables that can be referenced in RLS rules.\n * These variables are evaluated at runtime based on the user's session.\n * \n * Common context variables:\n * - `current_user.id` - Current user ID\n * - `current_user.tenant_id` - User's tenant/organization ID\n * - `current_user.department` - User's department\n * - `current_user.role` - User's role\n * - `current_user.region` - User's geographic region\n * \n * @example Custom context\n * ```typescript\n * contextVariables: {\n * allowed_regions: ['US', 'EU'],\n * access_level: 2,\n * custom_attribute: 'value'\n * }\n * ```\n */\n contextVariables: z.record(z.string(), z.unknown()).optional().describe('Context variables for RLS evaluation'),\n});\n\nexport type PermissionSet = z.infer;\nexport type ObjectPermission = z.infer;\nexport type FieldPermission = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Organization-Wide Defaults (OWD)\n * The baseline security posture for an object.\n */\nexport const OWDModel = z.enum([\n 'private', // Only owner can see\n 'public_read', // Everyone can see, owner can edit\n 'public_read_write', // Everyone can see and edit\n 'controlled_by_parent' // Access derived from parent record (Master-Detail)\n]);\n\n/**\n * Sharing Rule Type\n * How is the data shared?\n */\nexport const SharingRuleType = z.enum([\n 'owner', // Based on record ownership (Role Hierarchy)\n 'criteria', // Based on field values (e.g. Status = 'Open')\n]);\n\n/**\n * Sharing Level\n * What access is granted?\n */\nexport const SharingLevel = z.enum([\n 'read', // Read Only\n 'edit', // Read / Write\n 'full' // Full Access (Transfer, Share, Delete)\n]);\n\n/**\n * Recipient Type \n * Who receives the access?\n */\nexport const ShareRecipientType = z.enum([\n 'user',\n 'group',\n 'role',\n 'role_and_subordinates',\n 'guest' // for public sharing\n]);\n\n/**\n * Base Sharing Rule\n * Common metadata for all sharing strategies.\n */\nconst BaseSharingRuleSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n description: z.string().optional().describe('Administrative notes'),\n \n // Scope\n object: z.string().describe('Target Object Name'),\n active: z.boolean().default(true),\n \n // Access\n accessLevel: SharingLevel.default('read'),\n \n // Recipient (Whom to share with)\n sharedWith: z.object({\n type: ShareRecipientType,\n value: z.string().describe('ID or Code of the User/Group/Role'),\n }).describe('The recipient of the shared access'),\n});\n\n/**\n * 1. Criteria-Based Sharing Rule\n * Share records that meet specific field criteria.\n */\nexport const CriteriaSharingRuleSchema = BaseSharingRuleSchema.extend({\n type: z.literal('criteria'),\n condition: z.string().describe('Formula condition (e.g. \"department = \\'Sales\\'\")'),\n});\n\n/**\n * 2. Owner-Based Sharing Rule\n * Share records owned by a specific group of users.\n */\nexport const OwnerSharingRuleSchema = BaseSharingRuleSchema.extend({\n type: z.literal('owner'),\n ownedBy: z.object({\n type: ShareRecipientType,\n value: z.string(),\n }).describe('Source group/role whose records are being shared'),\n});\n\n/**\n * Master Sharing Rule Schema\n */\nexport const SharingRuleSchema = z.discriminatedUnion('type', [\n CriteriaSharingRuleSchema,\n OwnerSharingRuleSchema\n]);\n\nexport type SharingRule = z.infer;\nexport type CriteriaSharingRule = z.infer;\nexport type OwnerSharingRule = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Territory Management Protocol\n * Defines a matrix reporting structure that exists parallel to the Role Hierarchy.\n * \n * USE CASE:\n * - Enterprise Sales Teams (Geo-based: \"EMEA\", \"APAC\")\n * - Industry Verticals (Industry-based: \"Healthcare\", \"Financial\")\n * - Strategic Accounts (Account-based: \"Strategic Accounts\")\n * \n * DIFFERENCE FROM ROLE:\n * - Role: Hierarchy of PEOPLE (Who reports to whom). Stable. HR-driven.\n * - Territory: Hierarchy of ACCOUNTS/REVENUE (Who owns which market). Flexible. Sales-driven.\n * - One User can be assigned to MANY Territories (Matrix).\n * - One User has only ONE Role (Tree).\n */\n\nexport const TerritoryType = z.enum([\n 'geography', // Region/Country/City\n 'industry', // Vertical\n 'named_account', // Key Accounts\n 'product_line' // Product Specialty\n]);\n\n/**\n * Territory Model Schema\n * A container for a version of territory planning.\n * (e.g. \"Fiscal Year 2024 Planning\" vs \"Fiscal Year 2025 Planning\")\n */\nexport const TerritoryModelSchema = z.object({\n name: z.string().describe('Model Name (e.g. FY24 Planning)'),\n state: z.enum(['planning', 'active', 'archived']).default('planning'),\n startDate: z.string().optional(),\n endDate: z.string().optional(),\n});\n\n/**\n * Territory Node Schema\n * A single node in the territory tree.\n * \n * **NAMING CONVENTION:**\n * Territory names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good territory names\n * - 'west_coast'\n * - 'emea_region'\n * - 'healthcare_vertical'\n * - 'strategic_accounts'\n * \n * @example Bad territory names (will be rejected)\n * - 'WestCoast' (PascalCase)\n * - 'West Coast' (spaces)\n */\nexport const TerritorySchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Territory unique name (lowercase snake_case)'),\n label: z.string().describe('Territory Label (e.g. \"West Coast\")'),\n \n /** Structure */\n modelId: z.string().describe('Belongs to which Territory Model'),\n parent: z.string().optional().describe('Parent Territory'),\n type: TerritoryType.default('geography'),\n \n /** \n * Assignment Rules (The \"Magic\")\n * How do accounts automatically fall into this territory?\n * e.g. \"BillingCountry = 'US' AND BillingState = 'CA'\"\n */\n assignmentRule: z.string().optional().describe('Criteria based assignment rule'),\n \n /**\n * User Assignment\n * Users assigned to work this territory.\n */\n assignedUsers: z.array(z.string()).optional(),\n \n /** Access Level */\n accountAccess: z.enum(['read', 'edit']).default('read'),\n opportunityAccess: z.enum(['read', 'edit']).default('read'),\n caseAccess: z.enum(['read', 'edit']).default('read'),\n});\n\nexport type Territory = z.infer;\nexport type TerritoryModel = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Password Complexity Policy\n */\nexport const PasswordPolicySchema = z.object({\n minLength: z.number().default(8),\n requireUppercase: z.boolean().default(true),\n requireLowercase: z.boolean().default(true),\n requireNumbers: z.boolean().default(true),\n requireSymbols: z.boolean().default(false),\n expirationDays: z.number().optional().describe('Force password change every X days'),\n historyCount: z.number().default(3).describe('Prevent reusing last X passwords'),\n});\n\n/**\n * Network Access Policy (IP Whitelisting)\n */\nexport const NetworkPolicySchema = z.object({\n trustedRanges: z.array(z.string()).describe('CIDR ranges allowed to access (e.g. 10.0.0.0/8)'),\n blockUnknown: z.boolean().default(false).describe('Block all IPs not in trusted ranges'),\n vpnRequired: z.boolean().default(false),\n});\n\n/**\n * Session Policy\n */\nexport const SessionPolicySchema = z.object({\n idleTimeout: z.number().default(30).describe('Minutes before idle session logout'),\n absoluteTimeout: z.number().default(480).describe('Max session duration (minutes)'),\n forceMfa: z.boolean().default(false).describe('Require 2FA for all users'),\n});\n\n/**\n * Audit Retention Policy\n */\nexport const AuditPolicySchema = z.object({\n logRetentionDays: z.number().default(180),\n sensitiveFields: z.array(z.string()).describe('Fields to redact in logs (e.g. password, ssn)'),\n captureRead: z.boolean().default(false).describe('Log read access (High volume!)'),\n});\n\n/**\n * Security Policy Schema\n * \"The Cloud Compliance Contract\"\n */\nexport const PolicySchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Policy Name'),\n \n password: PasswordPolicySchema.optional(),\n network: NetworkPolicySchema.optional(),\n session: SessionPolicySchema.optional(),\n audit: AuditPolicySchema.optional(),\n\n /** Assignment */\n isDefault: z.boolean().default(false).describe('Apply to all users by default'),\n assignedProfiles: z.array(z.string()).optional().describe('Apply to specific profiles'),\n});\n\nexport type Policy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * UI Protocol Exports\n * \n * Presentation & Interaction\n * - App, Page, View (Grid/Kanban)\n * - Dashboard (Widgets), Report\n * - Action (Triggers)\n * - Chart (Unified Visualization Types)\n */\n\nexport * from './chart.zod';\nexport * from './i18n.zod';\nexport * from './responsive.zod';\nexport * from './app.zod';\nexport * from './view.zod';\nexport * from './dashboard.zod';\nexport * from './report.zod';\nexport * from './action.zod';\nexport * from './page.zod';\nexport * from './widget.zod';\nexport * from './component.zod';\nexport * from './theme.zod';\nexport * from './touch.zod';\nexport * from './offline.zod';\nexport * from './keyboard.zod';\nexport * from './animation.zod';\nexport * from './notification.zod';\nexport * from './dnd.zod';\nexport * from './sharing.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Unified Chart Type Taxonomy\n * \n * Shared by Dashboard and Report widgets.\n * Provides a comprehensive set of chart types for data visualization.\n */\n\n/**\n * Chart Type Enum\n * Categorized by visualization purpose\n */\nexport const ChartTypeSchema = z.enum([\n // Comparison\n 'bar',\n 'horizontal-bar',\n 'column',\n 'grouped-bar',\n 'stacked-bar',\n 'bi-polar-bar',\n \n // Trend\n 'line',\n 'area',\n 'stacked-area',\n 'step-line',\n 'spline',\n \n // Distribution\n 'pie',\n 'donut',\n 'funnel',\n 'pyramid',\n \n // Relationship\n 'scatter',\n 'bubble',\n \n // Composition\n 'treemap',\n 'sunburst',\n 'sankey',\n 'word-cloud',\n \n // Performance\n 'gauge',\n 'solid-gauge',\n 'metric',\n 'kpi',\n 'bullet',\n \n // Geo\n 'choropleth',\n 'bubble-map',\n 'gl-map',\n \n // Advanced\n 'heatmap',\n 'radar',\n 'waterfall',\n 'box-plot',\n 'violin',\n 'candlestick',\n 'stock',\n \n // Tabular\n 'table',\n 'pivot',\n]);\n\nexport type ChartType = z.infer;\n\n/**\n * Chart Axis Schema\n * Definition for X and Y axes\n */\nexport const ChartAxisSchema = z.object({\n /** Data field to map to this axis */\n field: z.string().describe('Data field key'),\n \n /** Axis title */\n title: I18nLabelSchema.optional().describe('Axis display title'),\n\n /** Value formatting (d3-format or similar) */\n format: z.string().optional().describe('Value format string (e.g., \"$0,0.00\")'),\n \n /** Axis scale settings */\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n stepSize: z.number().optional().describe('Step size for ticks'),\n \n /** Appearance */\n showGridLines: z.boolean().default(true),\n position: z.enum(['left', 'right', 'top', 'bottom']).optional().describe('Axis position'),\n \n /** Logarithmic scale */\n logarithmic: z.boolean().default(false),\n});\n\n/**\n * Chart Series Schema\n * Defines a single data series in the chart\n */\nexport const ChartSeriesSchema = z.object({\n /** Field name for values */\n name: z.string().describe('Field name or series identifier'),\n \n /** Display label */\n label: I18nLabelSchema.optional().describe('Series display label'),\n \n /** Series type override (combo charts) */\n type: ChartTypeSchema.optional().describe('Override chart type for this series'),\n \n /** Specific color */\n color: z.string().optional().describe('Series color (hex/rgb/token)'),\n \n /** Stacking group */\n stack: z.string().optional().describe('Stack identifier to group series'),\n \n /** Axis binding */\n yAxis: z.enum(['left', 'right']).default('left').describe('Bind to specific Y-Axis'),\n});\n\n/**\n * Chart Annotation Schema\n * Static lines or regions to highlight data\n */\nexport const ChartAnnotationSchema = z.object({\n type: z.enum(['line', 'region']).default('line'),\n axis: z.enum(['x', 'y']).default('y'),\n value: z.union([z.number(), z.string()]).describe('Start value'),\n endValue: z.union([z.number(), z.string()]).optional().describe('End value for regions'),\n color: z.string().optional(),\n label: I18nLabelSchema.optional(),\n style: z.enum(['solid', 'dashed', 'dotted']).default('dashed'),\n});\n\n/**\n * Chart Interaction Schema\n */\nexport const ChartInteractionSchema = z.object({\n tooltips: z.boolean().default(true),\n zoom: z.boolean().default(false),\n brush: z.boolean().default(false),\n clickAction: z.string().optional().describe('Action ID to trigger on click'),\n});\n\n/**\n * Chart Configuration Base\n * Common configuration for all chart types\n */\nexport const ChartConfigSchema = z.object({\n /** Chart Type */\n type: ChartTypeSchema,\n \n /** Titles */\n title: I18nLabelSchema.optional().describe('Chart title'),\n subtitle: I18nLabelSchema.optional().describe('Chart subtitle'),\n description: I18nLabelSchema.optional().describe('Accessibility description'),\n \n /** Axes Mapping */\n xAxis: ChartAxisSchema.optional().describe('X-Axis configuration'),\n yAxis: z.array(ChartAxisSchema).optional().describe('Y-Axis configuration (support dual axis)'),\n \n /** Series Configuration */\n series: z.array(ChartSeriesSchema).optional().describe('Defined series configuration'),\n \n /** Appearance */\n colors: z.array(z.string()).optional().describe('Color palette'),\n height: z.number().optional().describe('Fixed height in pixels'),\n \n /** Components */\n showLegend: z.boolean().default(true).describe('Display legend'),\n showDataLabels: z.boolean().default(false).describe('Display data labels'),\n \n /** Annotations & Reference Lines */\n annotations: z.array(ChartAnnotationSchema).optional(),\n \n /** Interactions */\n interaction: ChartInteractionSchema.optional(),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport type ChartConfig = z.infer;\nexport type ChartAxis = z.infer;\nexport type ChartSeries = z.infer;\nexport type ChartAnnotation = z.infer;\nexport type ChartInteraction = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Breakpoint Name Enum\n * Matches the breakpoint names defined in theme.zod.ts BreakpointsSchema.\n */\nexport const BreakpointName = z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl']);\n\nexport type BreakpointName = z.infer;\n\n/**\n * Responsive Configuration Schema\n *\n * Provides responsive layout configuration for UI components.\n * Maps breakpoint names to layout behavior (columns, visibility, order).\n *\n * Aligned with theme.zod.ts BreakpointsSchema for a unified responsive system.\n *\n * @example\n * ```typescript\n * const config: ResponsiveConfig = {\n * columns: { xs: 12, sm: 6, lg: 4 },\n * hiddenOn: ['xs'],\n * order: { xs: 2, lg: 1 },\n * };\n * ```\n */\n/**\n * Breakpoint Column Map Schema\n * Maps breakpoint names to grid column counts (1-12).\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointColumnMapSchema = z.object({\n xs: z.number().min(1).max(12).optional(),\n sm: z.number().min(1).max(12).optional(),\n md: z.number().min(1).max(12).optional(),\n lg: z.number().min(1).max(12).optional(),\n xl: z.number().min(1).max(12).optional(),\n '2xl': z.number().min(1).max(12).optional(),\n}).describe('Grid columns per breakpoint (1-12)');\n\n/**\n * Breakpoint Order Map Schema\n * Maps breakpoint names to display order numbers.\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointOrderMapSchema = z.object({\n xs: z.number().optional(),\n sm: z.number().optional(),\n md: z.number().optional(),\n lg: z.number().optional(),\n xl: z.number().optional(),\n '2xl': z.number().optional(),\n}).describe('Display order per breakpoint');\n\nexport const ResponsiveConfigSchema = z.object({\n /** Minimum breakpoint for visibility */\n breakpoint: BreakpointName.optional()\n .describe('Minimum breakpoint for visibility'),\n\n /** Hide on specific breakpoints */\n hiddenOn: z.array(BreakpointName).optional()\n .describe('Hide on these breakpoints'),\n\n /** Grid columns per breakpoint (1-12 column grid) */\n columns: BreakpointColumnMapSchema.optional().describe('Grid columns per breakpoint'),\n\n /** Display order per breakpoint */\n order: BreakpointOrderMapSchema.optional().describe('Display order per breakpoint'),\n}).describe('Responsive layout configuration');\n\nexport type ResponsiveConfig = z.infer;\n\n/**\n * Performance Configuration Schema\n *\n * Defines performance optimization settings for UI components\n * such as lazy loading, virtual scrolling, and caching.\n *\n * @example\n * ```typescript\n * const perf: PerformanceConfig = {\n * lazyLoad: true,\n * virtualScroll: { enabled: true, itemHeight: 40, overscan: 5 },\n * cacheStrategy: 'stale-while-revalidate',\n * prefetch: true,\n * };\n * ```\n */\nexport const PerformanceConfigSchema = z.object({\n /** Enable lazy loading for this component */\n lazyLoad: z.boolean().optional()\n .describe('Enable lazy loading (defer rendering until visible)'),\n\n /** Virtual scrolling configuration for large datasets */\n virtualScroll: z.object({\n enabled: z.boolean().default(false).describe('Enable virtual scrolling'),\n itemHeight: z.number().optional().describe('Fixed item height in pixels (for estimation)'),\n overscan: z.number().optional().describe('Number of extra items to render outside viewport'),\n }).optional().describe('Virtual scrolling configuration'),\n\n /** Client-side caching strategy */\n cacheStrategy: z.enum([\n 'none',\n 'cache-first',\n 'network-first',\n 'stale-while-revalidate',\n ]).optional().describe('Client-side data caching strategy'),\n\n /** Enable data prefetching */\n prefetch: z.boolean().optional()\n .describe('Prefetch data before component is visible'),\n\n /** Maximum number of items to render before pagination */\n pageSize: z.number().optional()\n .describe('Number of items per page for pagination'),\n\n /** Debounce interval for user interactions (ms) */\n debounceMs: z.number().optional()\n .describe('Debounce interval for user interactions in milliseconds'),\n}).describe('Performance optimization configuration');\n\nexport type PerformanceConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module ui/sharing\n *\n * Sharing & Embedding Protocol\n *\n * Defines schemas for public link sharing, embed configuration,\n * domain restrictions, and password protection for apps, pages, and forms.\n */\n\nimport { z } from 'zod';\n\n/**\n * Sharing Config Schema\n * Configuration for public sharing of an app, page, or form.\n * Supports public links, password protection, domain restrictions, and expiration.\n */\nexport const SharingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable public sharing'),\n publicLink: z.string().optional().describe('Generated public share URL'),\n password: z.string().optional().describe('Password required to access shared link'),\n allowedDomains: z.array(z.string()).optional()\n .describe('Restrict access to specific email domains (e.g. [\"example.com\"])'),\n expiresAt: z.string().optional()\n .describe('Expiration date/time in ISO 8601 format'),\n allowAnonymous: z.boolean().optional().default(false)\n .describe('Allow access without authentication'),\n});\n\n/**\n * Embed Config Schema\n * Configuration for iframe embedding of an app, page, or form.\n * Supports origin restrictions, display options, and responsive sizing.\n */\nexport const EmbedConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable iframe embedding'),\n allowedOrigins: z.array(z.string()).optional()\n .describe('Allowed iframe parent origins (e.g. [\"https://example.com\"])'),\n width: z.string().optional().default('100%').describe('Embed width (CSS value)'),\n height: z.string().optional().default('600px').describe('Embed height (CSS value)'),\n showHeader: z.boolean().optional().default(true).describe('Show interface header in embed'),\n showNavigation: z.boolean().optional().default(false).describe('Show navigation in embed'),\n responsive: z.boolean().optional().default(true).describe('Enable responsive resizing'),\n});\n\n// Type Exports\nexport type SharingConfig = z.infer;\nexport type EmbedConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema, EmbedConfigSchema } from './sharing.zod';\n\n/**\n * Base Navigation Item Schema\n * Shared properties for all navigation types.\n * \n * **NAMING CONVENTION:**\n * Navigation item IDs are used in URLs and configuration and must be lowercase snake_case.\n * \n * @example Good IDs\n * - 'menu_accounts'\n * - 'page_dashboard'\n * - 'nav_settings'\n * \n * @example Bad IDs (will be rejected)\n * - 'MenuAccounts' (PascalCase)\n * - 'Page Dashboard' (spaces)\n */\nconst BaseNavItemSchema = z.object({\n /** Unique identifier for the item */\n id: SnakeCaseIdentifierSchema.describe('Unique identifier for this navigation item (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display proper label'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Sort order within the same level (lower numbers appear first) */\n order: z.number().optional().describe('Sort order within the same level (lower = first)'),\n\n /** Badge text or count displayed on the navigation item (e.g. \"3\", \"New\") */\n badge: z.union([z.string(), z.number()]).optional().describe('Badge text or count displayed on the item'),\n\n /** \n * Visibility condition. \n * Formula expression returning boolean. \n * e.g. \"user.is_admin || user.department == 'sales'\"\n */\n visible: z.string().optional().describe('Visibility formula condition'),\n\n /** Permissions required to see/access this navigation item */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this item'),\n});\n\n/**\n * 1. Object Navigation Item\n * Navigates to an object's list view.\n */\nexport const ObjectNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('object'),\n objectName: z.string().describe('Target object name'),\n viewName: z.string().optional().describe('Default list view to open. Defaults to \"all\"'),\n});\n\n/**\n * 2. Dashboard Navigation Item\n * Navigates to a specific dashboard.\n */\nexport const DashboardNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('dashboard'),\n dashboardName: z.string().describe('Target dashboard name'),\n});\n\n/**\n * 3. Page Navigation Item\n * Navigates to a custom UI page/component.\n */\nexport const PageNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('page'),\n pageName: z.string().describe('Target custom page component name'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the page context'),\n});\n\n/**\n * 4. URL Navigation Item\n * Navigates to an external or absolute URL.\n */\nexport const UrlNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('url'),\n url: z.string().describe('Target external URL'),\n target: z.enum(['_self', '_blank']).default('_self').describe('Link target window'),\n});\n\n/**\n * 5. Report Navigation Item\n * Navigates to a specific report.\n */\nexport const ReportNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('report'),\n reportName: z.string().describe('Target report name'),\n});\n\n/**\n * 6. Action Navigation Item\n * Triggers an action (e.g. opening a flow, running a script, or launching a screen action).\n */\nexport const ActionNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('action'),\n actionDef: z.object({\n actionName: z.string().describe('Action machine name to execute'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the action'),\n }).describe('Action definition to execute when clicked'),\n});\n\n/**\n * 7. Group Navigation Item\n * A container for child navigation items (Sub-menu).\n * Does not perform navigation itself.\n */\nexport const GroupNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('group'),\n expanded: z.boolean().default(false).describe('Default expansion state in sidebar'),\n // children property is added in the recursive definition below\n});\n\n/**\n * Recursive Union of all navigation item types.\n * Allows constructing an unlimited-depth navigation tree.\n */\nexport const NavigationItemSchema: z.ZodType = z.lazy(() => \n z.union([\n ObjectNavItemSchema.extend({\n children: z.array(NavigationItemSchema).optional().describe('Child navigation items (e.g. specific views)'),\n }),\n DashboardNavItemSchema,\n PageNavItemSchema,\n UrlNavItemSchema,\n ReportNavItemSchema,\n ActionNavItemSchema,\n GroupNavItemSchema.extend({\n children: z.array(NavigationItemSchema).describe('Child navigation items'),\n })\n ])\n);\n\n/**\n * App Branding Configuration\n * Allows configuring the look and feel of the specific app.\n */\nexport const AppBrandingSchema = z.object({\n primaryColor: z.string().optional().describe('Primary theme color hex code'),\n logo: z.string().optional().describe('Custom logo URL for this app'),\n favicon: z.string().optional().describe('Custom favicon URL for this app'),\n});\n\n/**\n * Navigation Area Schema\n * \n * A logical grouping (zone/section) of navigation items, similar to Salesforce \"App Areas\"\n * or Dynamics 365 \"Site Map Areas\". Each area represents a business domain (e.g. Sales, Service, Settings)\n * and contains its own independent navigation tree.\n * \n * Areas allow large applications to partition navigation by business function while\n * keeping a single AppSchema definition. The runtime may render areas as top-level tabs,\n * sidebar sections, or a switchable navigation context.\n * \n * @example\n * ```ts\n * const salesArea: NavigationArea = {\n * id: 'area_sales',\n * label: 'Sales',\n * icon: 'briefcase',\n * order: 1,\n * navigation: [\n * { id: 'nav_leads', type: 'object', label: 'Leads', objectName: 'lead' },\n * { id: 'nav_opportunities', type: 'object', label: 'Opportunities', objectName: 'opportunity' },\n * ],\n * };\n * ```\n */\nexport const NavigationAreaSchema = z.object({\n /** Unique area identifier */\n id: SnakeCaseIdentifierSchema.describe('Unique area identifier (lowercase snake_case)'),\n\n /** Display label */\n label: I18nLabelSchema.describe('Area display label'),\n\n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Area icon name'),\n\n /** Sort order among areas (lower = first) */\n order: z.number().optional().describe('Sort order among areas (lower = first)'),\n\n /** Area description */\n description: I18nLabelSchema.optional().describe('Area description'),\n\n /** \n * Visibility condition.\n * Formula expression returning boolean.\n */\n visible: z.string().optional().describe('Visibility formula condition for this area'),\n\n /** Permissions required to access this area */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this area'),\n\n /** Navigation items within this area */\n navigation: z.array(NavigationItemSchema).describe('Navigation items within this area'),\n});\n\n/**\n * Schema for Applications (Apps).\n * A logical container for business functionality (e.g., \"Sales CRM\", \"HR Portal\").\n * \n * **NAMING CONVENTION:**\n * App names are used in URLs and routing and must be lowercase snake_case.\n * Prefix with 'app_' is recommended for clarity.\n * \n * @example Good app names\n * - 'app_crm'\n * - 'app_finance'\n * - 'app_portal'\n * - 'sales_app'\n * \n * @example Bad app names (will be rejected)\n * - 'CRM' (uppercase)\n * - 'FinanceApp' (mixed case)\n * - 'Sales App' (spaces)\n */\n/**\n * App Configuration Schema\n * Defines a business application container, including its navigation, branding, and permissions.\n * \n * The App is the top-level navigation shell. The `navigation[]` field holds the complete\n * sidebar tree with unlimited nesting depth via `type: 'group'` items. Pages are referenced\n * by name via `type: 'page'` items and defined independently.\n * \n * @example CRM App with nested navigation tree\n * {\n * name: \"crm\",\n * label: \"Sales CRM\",\n * icon: \"briefcase\",\n * navigation: [\n * { type: \"group\", id: \"grp_sales\", label: \"Sales Cloud\", expanded: true, children: [\n * { type: \"page\", id: \"nav_pipeline\", label: \"Pipeline\", pageName: \"page_pipeline\" },\n * { type: \"page\", id: \"nav_accounts\", label: \"Accounts\", pageName: \"page_accounts\" },\n * ]},\n * { type: \"page\", id: \"nav_settings\", label: \"Settings\", pageName: \"admin_settings\" },\n * ]\n * }\n */\nexport const AppSchema = z.object({\n /** Machine name (id) */\n name: SnakeCaseIdentifierSchema.describe('App unique machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('App display label'),\n\n /** App version */\n version: z.string().optional().describe('App version'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('App description'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('App icon used in the App Launcher'),\n \n /** Branding/Theming Configuration */\n branding: AppBrandingSchema.optional().describe('App-specific branding'),\n \n /** Application status */\n active: z.boolean().optional().default(true).describe('Whether the app is enabled'),\n\n /** Is this the default app for new users? */\n isDefault: z.boolean().optional().default(false).describe('Is default app'),\n \n /** \n * Full Navigation Tree — supports unlimited nesting depth.\n * Pages are referenced by name via `type: 'page'` items.\n * Groups can contain other groups for arbitrary sidebar depth.\n * \n * For simple apps, use `navigation` directly.\n * For enterprise apps with multiple business domains, use `areas` instead.\n */\n navigation: z.array(NavigationItemSchema).optional()\n .describe('Full navigation tree for the app sidebar'),\n\n /**\n * Navigation Areas — partitions navigation by business domain.\n * Each area defines an independent navigation tree (e.g. Sales, Service, Settings).\n * When areas are defined, they take precedence over the top-level `navigation` array.\n * \n * @example\n * ```ts\n * areas: [\n * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] },\n * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] },\n * ]\n * ```\n */\n areas: z.array(NavigationAreaSchema).optional()\n .describe('Navigation areas for partitioning navigation by business domain'),\n \n /** \n * App-level Home Page Override\n * ID of the navigation item to act as the landing page.\n * If not set, usually defaults to the first navigation item.\n */\n homePageId: z.string().optional().describe('ID of the navigation item to serve as landing page'),\n\n /** \n * Access Control\n * List of permissions required to access this app.\n * Modern replacement for role/profile based assignment.\n * Example: [\"app.access.crm\"]\n */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this app'),\n \n /** \n * Package Components (For config file convenience)\n * In a real monorepo these might be auto-discovered, but here we allow explicit registration.\n */\n objects: z.array(z.unknown()).optional().describe('Objects belonging to this app'),\n apis: z.array(z.unknown()).optional().describe('Custom APIs belonging to this app'),\n\n /** Sharing configuration for public access */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration'),\n\n /** Embed configuration for iframe embedding */\n embed: EmbedConfigSchema.optional().describe('Iframe embedding configuration'),\n\n /** Mobile navigation mode */\n mobileNavigation: z.object({\n mode: z.enum(['drawer', 'bottom_nav', 'hamburger']).default('drawer')\n .describe('Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu'),\n bottomNavItems: z.array(z.string()).optional()\n .describe('Navigation item IDs to show in bottom nav (max 5)'),\n }).optional().describe('Mobile-specific navigation configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the application'),\n});\n\n/**\n * App Factory Helper\n */\nexport const App = {\n create: (config: z.input): App => AppSchema.parse(config),\n} as const;\n\n/**\n * Type-safe factory for creating application definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example CRM App with nested navigation tree\n * ```ts\n * const crmApp = defineApp({\n * name: 'crm',\n * label: 'Sales CRM',\n * navigation: [\n * { id: 'grp_sales', type: 'group', label: 'Sales Cloud', expanded: true, children: [\n * { id: 'nav_pipeline', type: 'page', label: 'Pipeline', pageName: 'page_pipeline' },\n * { id: 'nav_accounts', type: 'page', label: 'Accounts', pageName: 'page_accounts' },\n * ]},\n * { id: 'nav_settings', type: 'page', label: 'Settings', pageName: 'admin_settings' },\n * ],\n * });\n * ```\n */\nexport function defineApp(config: z.input): App {\n return AppSchema.parse(config);\n}\n\n// Main Types\nexport type App = z.infer;\nexport type AppInput = z.input;\nexport type AppBranding = z.infer;\nexport type NavigationItem = z.infer;\nexport type NavigationArea = z.infer;\n\n// Discriminated Item Types (Helper exports)\nexport type ObjectNavItem = z.infer;\nexport type DashboardNavItem = z.infer;\nexport type PageNavItem = z.infer;\nexport type UrlNavItem = z.infer;\nexport type ReportNavItem = z.infer;\nexport type ActionNavItem = z.infer;\nexport type GroupNavItem = z.infer & { children: NavigationItem[] };\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema } from './sharing.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * HTTP Method Enum & HTTP Request Schema\n * Migrated to shared/http.zod.ts. Re-exported here for backward compatibility.\n */\nimport { HttpMethodSchema, HttpRequestSchema } from '../shared/http.zod';\nexport { HttpMethodSchema, HttpRequestSchema };\n\n/**\n * View Data Source Configuration\n * Supports three modes:\n * 1. 'object': Standard Protocol - Auto-connects to ObjectStack Metadata and Data APIs\n * 2. 'api': Custom API - Explicitly provided API URLs\n * 3. 'value': Static Data - Hardcoded data array\n */\nexport const ViewDataSchema = z.discriminatedUnion('provider', [\n z.object({\n provider: z.literal('object'),\n object: z.string().describe('Target object name'),\n }),\n z.object({\n provider: z.literal('api'),\n read: HttpRequestSchema.optional().describe('Configuration for fetching data'),\n write: HttpRequestSchema.optional().describe('Configuration for submitting data (for forms/editable tables)'),\n }),\n z.object({\n provider: z.literal('value'),\n items: z.array(z.unknown()).describe('Static data array'),\n }),\n]);\n\n/**\n * View Filter Rule Schema\n * Standardized filter condition used in list views, tabs, and page-level filters.\n * Uses a declarative array-of-objects format: [{ field, operator, value }].\n *\n * @example\n * ```ts\n * filter: [\n * { field: 'status', operator: 'equals', value: 'active' },\n * { field: 'close_date', operator: 'this_quarter' },\n * ]\n * ```\n */\nexport const ViewFilterRuleSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n /** Filter operator */\n operator: z.string().describe('Filter operator (e.g. equals, not_equals, contains, this_quarter)'),\n /** Filter value (optional for unary operators like is_null, this_quarter) */\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Filter value'),\n}).describe('View filter rule');\n\nexport type ViewFilterRule = z.infer;\n\n/**\n * Column Summary Function Schema\n * Aggregation function for column footer (Airtable-style column summaries)\n */\nexport const ColumnSummarySchema = z.enum([\n 'none',\n 'count',\n 'count_empty',\n 'count_filled',\n 'count_unique',\n 'percent_empty',\n 'percent_filled',\n 'sum',\n 'avg',\n 'min',\n 'max',\n]).describe('Aggregation function for column footer summary');\n\n/**\n * List Column Configuration Schema\n * Detailed configuration for individual list view columns\n */\nexport const ListColumnSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n width: z.number().positive().optional().describe('Column width in pixels'),\n align: z.enum(['left', 'center', 'right']).optional().describe('Text alignment'),\n hidden: z.boolean().optional().describe('Hide column by default'),\n sortable: z.boolean().optional().describe('Allow sorting by this column'),\n resizable: z.boolean().optional().describe('Allow resizing this column'),\n wrap: z.boolean().optional().describe('Allow text wrapping'),\n type: z.string().optional().describe('Renderer type override (e.g., \"currency\", \"date\")'),\n\n /** Pinning (Airtable-style frozen columns) */\n pinned: z.enum(['left', 'right']).optional().describe('Pin/freeze column to left or right side'),\n\n /** Column Footer Summary (Airtable-style aggregation) */\n summary: ColumnSummarySchema.optional().describe('Footer aggregation function for this column'),\n\n /** Interaction */\n link: z.boolean().optional().describe('Functions as the primary navigation link (triggers View navigation)'),\n action: z.string().optional().describe('Registered Action ID to execute when clicked'),\n});\n\n/**\n * List View Selection Configuration\n */\nexport const SelectionConfigSchema = z.object({\n type: z.enum(['none', 'single', 'multiple']).default('none').describe('Selection mode'),\n});\n\n/**\n * List View Pagination Configuration\n */\nexport const PaginationConfigSchema = z.object({\n pageSize: z.number().int().positive().default(25).describe('Number of records per page'),\n pageSizeOptions: z.array(z.number().int().positive()).optional().describe('Available page size options'),\n});\n\n/**\n * Row Height / Density Schema (Airtable-style)\n * Controls the visual density of rows in a list view.\n */\nexport const RowHeightSchema = z.enum([\n 'compact', // Minimal padding, single line\n 'short', // Reduced padding\n 'medium', // Default padding\n 'tall', // Extra padding, multi-line preview\n 'extra_tall', // Maximum padding, rich content preview\n]).describe('Row height / density setting for list view');\n\n/**\n * Grouping Field Configuration\n * Defines a single grouping level for record grouping.\n */\nexport const GroupingFieldSchema = z.object({\n field: z.string().describe('Field name to group by'),\n order: z.enum(['asc', 'desc']).default('asc').describe('Group sort order'),\n collapsed: z.boolean().default(false).describe('Collapse groups by default'),\n});\n\n/**\n * Grouping Configuration Schema (Airtable-style)\n * Supports multi-level grouping for grid/gallery views.\n */\nexport const GroupingConfigSchema = z.object({\n fields: z.array(GroupingFieldSchema).min(1).describe('Fields to group by (supports up to 3 levels)'),\n}).describe('Record grouping configuration');\n\n/**\n * Gallery View Configuration (Airtable-style)\n * Configures card layout for gallery/card views.\n */\nexport const GalleryConfigSchema = z.object({\n coverField: z.string().optional().describe('Attachment/image field to display as card cover'),\n coverFit: z.enum(['cover', 'contain']).default('cover').describe('Image fit mode for card cover'),\n cardSize: z.enum(['small', 'medium', 'large']).default('medium').describe('Card size in gallery view'),\n titleField: z.string().optional().describe('Field to display as card title'),\n visibleFields: z.array(z.string()).optional().describe('Fields to display on card body'),\n}).describe('Gallery/card view configuration');\n\n/**\n * Timeline View Configuration (Airtable-style)\n * Configures timeline/chronological views.\n */\nexport const TimelineConfigSchema = z.object({\n startDateField: z.string().describe('Field for timeline item start date'),\n endDateField: z.string().optional().describe('Field for timeline item end date'),\n titleField: z.string().describe('Field to display as timeline item title'),\n groupByField: z.string().optional().describe('Field to group timeline rows'),\n colorField: z.string().optional().describe('Field to determine item color'),\n scale: z.enum(['hour', 'day', 'week', 'month', 'quarter', 'year']).default('week').describe('Default timeline scale'),\n}).describe('Timeline view configuration');\n\n/**\n * View Sharing Configuration (Airtable-style)\n * Defines who can see and modify a view.\n */\nexport const ViewSharingSchema = z.object({\n type: z.enum(['personal', 'collaborative']).default('collaborative').describe('View ownership type'),\n lockedBy: z.string().optional().describe('User who locked the view configuration'),\n}).describe('View sharing and access configuration');\n\n/**\n * Row Color Configuration (Airtable-style)\n * Defines how rows are colored based on field values.\n */\nexport const RowColorConfigSchema = z.object({\n field: z.string().describe('Field to derive color from (typically a select/status field)'),\n colors: z.record(z.string(), z.string()).optional().describe('Map of field value to color (hex/token)'),\n}).describe('Row color configuration based on field values');\n\n/**\n * Visualization Type Schema\n * Whitelist of visualization types the user can switch between.\n * Maps to Airtable's \"Visualizations\" setting in Appearance panel.\n */\nexport const VisualizationTypeSchema = z.enum([\n 'grid',\n 'kanban',\n 'gallery',\n 'calendar',\n 'timeline',\n 'gantt',\n 'map',\n]).describe('Visualization type that users can switch to');\n\n/**\n * User Actions Configuration Schema (Airtable Interface parity)\n * Controls which interactive actions are available to users in the view toolbar.\n * Each boolean toggles the corresponding toolbar element on/off.\n *\n * @see Airtable Interface → \"User actions\" panel\n */\nexport const UserActionsConfigSchema = z.object({\n sort: z.boolean().default(true).describe('Allow users to sort records'),\n search: z.boolean().default(true).describe('Allow users to search records'),\n filter: z.boolean().default(true).describe('Allow users to filter records'),\n rowHeight: z.boolean().default(true).describe('Allow users to toggle row height/density'),\n addRecordForm: z.boolean().default(false).describe('Add records through a form instead of inline'),\n buttons: z.array(z.string()).optional().describe('Custom action button IDs to show in the toolbar'),\n}).describe('User action toggles for the view toolbar');\n\n/**\n * Appearance Configuration Schema (Airtable Interface parity)\n * Controls visual presentation options for the view.\n *\n * @see Airtable Interface → \"Appearance\" panel\n */\nexport const AppearanceConfigSchema = z.object({\n showDescription: z.boolean().default(true).describe('Show the view description text'),\n allowedVisualizations: z.array(VisualizationTypeSchema).optional()\n .describe('Whitelist of visualization types users can switch between (e.g. [\"grid\", \"gallery\", \"kanban\"])'),\n}).describe('Appearance and visualization configuration');\n\n/**\n * View Tab Schema (Airtable Interface parity)\n * Defines a tab in a multi-tab view interface.\n * Each tab references a named list view and can be ordered, pinned, or set as default.\n *\n * @see Airtable Interface → \"Tabs\" panel\n */\nexport const ViewTabSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Tab identifier (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label'),\n icon: z.string().optional().describe('Tab icon name'),\n view: z.string().optional().describe('Referenced list view name from listViews'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Tab-specific filter criteria'),\n order: z.number().int().min(0).optional().describe('Tab display order'),\n pinned: z.boolean().default(false).describe('Pin tab (cannot be removed by users)'),\n isDefault: z.boolean().default(false).describe('Set as the default active tab'),\n visible: z.boolean().default(true).describe('Tab visibility'),\n}).describe('Tab configuration for multi-tab view interface');\n\n/**\n * Add Record Configuration Schema (Airtable Interface parity)\n * Configures the \"Add Record\" entry point for a list view.\n *\n * @see Airtable Interface → \"+ Add record\" button\n */\nexport const AddRecordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Show the add record entry point'),\n position: z.enum(['top', 'bottom', 'both']).default('bottom').describe('Position of the add record button'),\n mode: z.enum(['inline', 'form', 'modal']).default('inline').describe('How to add a new record'),\n formView: z.string().optional().describe('Named form view to use when mode is \"form\" or \"modal\"'),\n}).describe('Add record entry point configuration');\n\n/**\n * Kanban Settings\n */\nexport const KanbanConfigSchema = z.object({\n groupByField: z.string().describe('Field to group columns by (usually status/select)'),\n summarizeField: z.string().optional().describe('Field to sum at top of column (e.g. amount)'),\n columns: z.array(z.string()).describe('Fields to show on cards'),\n});\n\n/**\n * Calendar Settings\n */\nexport const CalendarConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string().optional(),\n titleField: z.string(),\n colorField: z.string().optional(),\n});\n\n/**\n * Gantt Settings\n */\nexport const GanttConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string(),\n titleField: z.string(),\n progressField: z.string().optional(),\n dependenciesField: z.string().optional(),\n});\n\n/**\n * Navigation Mode Enum\n * Defines how to navigate to the detail view from a list item.\n */\nexport const NavigationModeSchema = z.enum([\n 'page', // Navigate to a new route (default)\n 'drawer', // Open details in a side drawer/panel\n 'modal', // Open details in a modal dialog\n 'split', // Show details side-by-side with the list (master-detail)\n 'popover', // Show details in a popover (lightweight)\n 'new_window', // Open in new browser tab/window\n 'none' // No navigation (read-only list)\n]);\n\n/**\n * Navigation Configuration Schema\n */\nexport const NavigationConfigSchema = z.object({\n mode: NavigationModeSchema.default('page'),\n \n /** Target View Config */\n view: z.string().optional().describe('Name of the form view to use for details (e.g. \"summary_view\", \"edit_form\")'),\n \n /** Interaction Triggers */\n preventNavigation: z.boolean().default(false).describe('Disable standard navigation entirely'),\n openNewTab: z.boolean().default(false).describe('Force open in new tab (applies to page mode)'),\n \n /** Dimensions (for modal/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Width of the drawer/modal (e.g. \"600px\", \"50%\")'),\n});\n\n/**\n * List View Schema (Expanded)\n * Defines how a collection of records is displayed to the user.\n * \n * **NAMING CONVENTION:**\n * View names (when provided) are machine identifiers and must be lowercase snake_case.\n * \n * @example Standard Grid\n * {\n * name: \"all_active\",\n * label: \"All Active\",\n * type: \"grid\",\n * columns: [\"name\", \"status\", \"created_at\"],\n * filter: [[\"status\", \"=\", \"active\"]]\n * }\n * \n * @example Kanban Board\n * {\n * type: \"kanban\",\n * columns: [\"name\", \"amount\"],\n * kanban: {\n * groupByField: \"stage\",\n * summarizeField: \"amount\",\n * columns: [\"name\", \"close_date\"]\n * }\n * }\n */\nexport const ListViewSchema = z.object({\n name: SnakeCaseIdentifierSchema.optional().describe('Internal view name (lowercase snake_case)'),\n label: I18nLabelSchema.optional(), // Display label override (supports i18n)\n type: z.enum([\n 'grid', // Standard Data Table\n 'kanban', // Board / Columns\n 'gallery', // Card Deck / Masonry\n 'calendar', // Monthly/Weekly/Daily\n 'timeline', // Chronological Stream (Feed)\n 'gantt', // Project Timeline\n 'map' // Geospatial\n ]).default('grid'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n /** Shared Query Config */\n columns: z.union([\n z.array(z.string()), // Legacy: simple field names\n z.array(ListColumnSchema), // Enhanced: detailed column config\n ]).describe('Fields to display as columns'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Filter criteria (JSON Rules)'),\n sort: z.union([\n z.string(), //Legacy \"field desc\"\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional(),\n \n /** Search & Filter */\n searchableFields: z.array(z.string()).optional().describe('Fields enabled for search'),\n filterableFields: z.array(z.string()).optional().describe('Fields enabled for end-user filtering in the top bar'),\n\n /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */\n quickFilters: z.array(z.object({\n field: z.string().describe('Field name to filter by'),\n label: z.string().optional().describe('Display label for the chip'),\n operator: z.enum(['equals', 'not_equals', 'contains', 'in', 'is_null', 'is_not_null']).default('equals').describe('Filter operator'),\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Preset filter value'),\n })).optional().describe('One-click filter chips for quick record filtering'),\n\n /** Grid Features */\n resizable: z.boolean().optional().describe('Enable column resizing'),\n striped: z.boolean().optional().describe('Striped row styling'),\n bordered: z.boolean().optional().describe('Show borders'),\n\n /** Selection */\n selection: SelectionConfigSchema.optional().describe('Row selection configuration'),\n\n /** Navigation / Interaction */\n navigation: NavigationConfigSchema.optional().describe('Configuration for item click navigation (page, drawer, modal, etc.)'),\n\n /** Pagination */\n pagination: PaginationConfigSchema.optional().describe('Pagination configuration'),\n\n /** Type Specific Config */\n kanban: KanbanConfigSchema.optional(),\n calendar: CalendarConfigSchema.optional(),\n gantt: GanttConfigSchema.optional(),\n gallery: GalleryConfigSchema.optional(),\n timeline: TimelineConfigSchema.optional(),\n\n /** View Metadata (Airtable-style view management) */\n description: I18nLabelSchema.optional().describe('View description for documentation/tooltips'),\n sharing: ViewSharingSchema.optional().describe('View sharing and access configuration'),\n\n /** Row Height / Density (Airtable-style) */\n rowHeight: RowHeightSchema.optional().describe('Row height / density setting'),\n\n /** Record Grouping (Airtable-style) */\n grouping: GroupingConfigSchema.optional().describe('Group records by one or more fields'),\n\n /** Row Color (Airtable-style) */\n rowColor: RowColorConfigSchema.optional().describe('Color rows based on field value'),\n\n /** Field Visibility & Ordering per View (Airtable-style) */\n hiddenFields: z.array(z.string()).optional().describe('Fields to hide in this specific view'),\n fieldOrder: z.array(z.string()).optional().describe('Explicit field display order for this view'),\n\n /** Row & Bulk Actions */\n rowActions: z.array(z.string()).optional().describe('Actions available for individual row items'),\n bulkActions: z.array(z.string()).optional().describe('Actions available when multiple rows are selected'),\n\n /** Performance */\n virtualScroll: z.boolean().optional().describe('Enable virtual scrolling for large datasets'),\n\n /** Conditional Formatting */\n conditionalFormatting: z.array(z.object({\n condition: z.string().describe('Condition expression to evaluate'),\n style: z.record(z.string(), z.string()).describe('CSS styles to apply when condition is true'),\n })).optional().describe('Conditional formatting rules for list rows'),\n\n /** Inline Edit */\n inlineEdit: z.boolean().optional().describe('Allow inline editing of records directly in the list view'),\n\n /** Export */\n exportOptions: z.array(z.enum(['csv', 'xlsx', 'pdf', 'json'])).optional().describe('Available export format options'),\n\n /** User Actions (Airtable Interface parity) */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles for the view toolbar'),\n\n /** Appearance (Airtable Interface parity) */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** Tabs (Airtable Interface parity) */\n tabs: z.array(ViewTabSchema).optional().describe('Tab definitions for multi-tab view interface'),\n\n /** Add Record (Airtable Interface parity) */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record Count Display (Airtable Interface parity) */\n showRecordCount: z.boolean().optional().describe('Show record count at the bottom of the list'),\n\n /** Advanced: Allow Printing (Airtable Interface parity) */\n allowPrinting: z.boolean().optional().describe('Allow users to print the view'),\n\n /** Empty State */\n emptyState: z.object({\n title: I18nLabelSchema.optional(),\n message: I18nLabelSchema.optional(),\n icon: z.string().optional(),\n }).optional().describe('Empty state configuration when no records found'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the list view'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Form Field Configuration Schema\n * Detailed configuration for individual form fields\n */\nexport const FormFieldSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n helpText: I18nLabelSchema.optional().describe('Help/hint text'),\n readonly: z.boolean().optional().describe('Read-only override'),\n required: z.boolean().optional().describe('Required override'),\n hidden: z.boolean().optional().describe('Hidden override'),\n colSpan: z.number().int().min(1).max(4).optional().describe('Column span in grid layout (1-4)'),\n widget: z.string().optional().describe('Custom widget/component name'),\n dependsOn: z.string().optional().describe('Parent field name for cascading'),\n visibleOn: z.string().optional().describe('Visibility condition expression'),\n});\n\n/**\n * Form Layout Section\n */\nexport const FormSectionSchema = z.object({\n label: I18nLabelSchema.optional(),\n collapsible: z.boolean().default(false),\n collapsed: z.boolean().default(false),\n columns: z.enum(['1', '2', '3', '4']).default('2').transform(val => parseInt(val) as 1 | 2 | 3 | 4),\n fields: z.array(z.union([\n z.string(), // Legacy: simple field name\n FormFieldSchema, // Enhanced: detailed field config\n ])),\n});\n\n/**\n * Form View Schema\n * Defines the layout for creating or editing a single record.\n * \n * @example Simple Sectioned Form\n * {\n * type: \"simple\",\n * sections: [\n * {\n * label: \"General Info\",\n * columns: 2,\n * fields: [\"name\", \"status\"]\n * },\n * {\n * label: \"Details\",\n * fields: [\"description\", { field: \"priority\", widget: \"rating\" }]\n * }\n * ]\n * }\n */\nexport const FormViewSchema = z.object({\n type: z.enum([\n 'simple', // Single column or sections\n 'tabbed', // Tabs\n 'wizard', // Step by step\n 'split', // Master-Detail split\n 'drawer', // Side panel\n 'modal' // Dialog\n ]).default('simple'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n sections: z.array(FormSectionSchema).optional(), // For simple layout\n groups: z.array(FormSectionSchema).optional(), // Legacy support -> alias to sections\n\n /** Default Sort for Related Lists (e.g., sort child records by date) */\n defaultSort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n order: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n })).optional().describe('Default sort order for related list views within this form'),\n\n /** Public form sharing configuration */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration for this form'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the form view'),\n});\n\n/**\n * Master View Schema\n * Can define multiple named views.\n */\n/**\n * View Container Schema\n * Aggregates all view definitions for a specific object or context.\n * \n * @example\n * {\n * list: { type: \"grid\", columns: [\"name\"] },\n * form: { type: \"simple\", fields: [\"name\"] },\n * listViews: {\n * \"all\": { label: \"All\", filter: [] },\n * \"my\": { label: \"Mine\", filter: [[\"owner\", \"=\", \"{user_id}\"]] }\n * }\n * }\n */\nexport const ViewSchema = z.object({\n list: ListViewSchema.optional(), // Default list view\n form: FormViewSchema.optional(), // Default form view\n listViews: z.record(z.string(), ListViewSchema).optional().describe('Additional named list views'),\n formViews: z.record(z.string(), FormViewSchema).optional().describe('Additional named form views'),\n});\n\n/**\n * Type-safe factory for creating view definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const taskViews = defineView({\n * list: {\n * type: 'grid',\n * data: { provider: 'object', object: 'task' },\n * columns: ['subject', 'status', 'priority', 'due_date'],\n * },\n * form: {\n * type: 'simple',\n * sections: [{ label: 'Details', fields: [{ field: 'subject' }] }],\n * },\n * });\n * ```\n */\nexport function defineView(config: z.input): View {\n return ViewSchema.parse(config);\n}\n\nexport type View = z.infer;\nexport type ListView = z.infer;\nexport type FormView = z.infer;\nexport type FormSection = z.infer;\nexport type ListColumn = z.infer;\nexport type FormField = z.infer;\nexport type SelectionConfig = z.infer;\nexport type NavigationConfig = z.infer;\nexport type PaginationConfig = z.infer;\nexport type ViewData = z.infer;\nexport type HttpRequest = z.infer;\nexport type HttpMethod = z.infer;\nexport type ColumnSummary = z.infer;\nexport type RowHeight = z.infer;\nexport type GroupingConfig = z.infer;\nexport type GalleryConfig = z.infer;\nexport type TimelineConfig = z.infer;\nexport type ViewSharing = z.infer;\nexport type RowColorConfig = z.infer;\nexport type VisualizationType = z.infer;\nexport type UserActionsConfig = z.infer;\nexport type AppearanceConfig = z.infer;\nexport type ViewTab = z.infer;\nexport type AddRecordConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ChartTypeSchema, ChartConfigSchema } from './chart.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Color variant for dashboard widgets (e.g., KPI cards).\n */\nexport const WidgetColorVariantSchema = z.enum([\n 'default',\n 'blue',\n 'teal',\n 'orange',\n 'purple',\n 'success',\n 'warning',\n 'danger',\n]).describe('Widget color variant');\n\n/**\n * Action type for widget action buttons.\n */\nexport const WidgetActionTypeSchema = z.enum([\n 'script',\n 'url',\n 'modal',\n 'flow',\n 'api',\n]).describe('Widget action type');\n\n/**\n * Dashboard Header Action Schema\n * An action button displayed in the dashboard header area.\n */\nexport const DashboardHeaderActionSchema = z.object({\n /** Action label */\n label: I18nLabelSchema.describe('Action button label'),\n\n /** Action URL or target */\n actionUrl: z.string().describe('URL or target for the action'),\n\n /** Action type */\n actionType: WidgetActionTypeSchema.optional().describe('Type of action'),\n\n /** Icon identifier */\n icon: z.string().optional().describe('Icon identifier for the action button'),\n}).describe('Dashboard header action');\n\n/**\n * Dashboard Header Schema\n * Structured header configuration for the dashboard.\n */\nexport const DashboardHeaderSchema = z.object({\n /** Whether to show the dashboard title in the header */\n showTitle: z.boolean().default(true).describe('Show dashboard title in header'),\n\n /** Whether to show the dashboard description in the header */\n showDescription: z.boolean().default(true).describe('Show dashboard description in header'),\n\n /** Action buttons displayed in the header */\n actions: z.array(DashboardHeaderActionSchema).optional().describe('Header action buttons'),\n}).describe('Dashboard header configuration');\n\n/**\n * Widget Measure Schema\n * A single measure definition for multi-measure pivot/matrix widgets.\n */\nexport const WidgetMeasureSchema = z.object({\n /** Value field to aggregate */\n valueField: z.string().describe('Field to aggregate'),\n\n /** Aggregate function */\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max']).default('count').describe('Aggregate function'),\n\n /** Display label for the measure */\n label: I18nLabelSchema.optional().describe('Measure display label'),\n\n /** Number format string (e.g., \"$0,0.00\", \"0.0%\") */\n format: z.string().optional().describe('Number format string'),\n}).describe('Widget measure definition');\n\n/**\n * Dashboard Widget Schema\n * A single component on the dashboard grid.\n */\nexport const DashboardWidgetSchema = z.object({\n /** Unique widget identifier (snake_case, used for targetWidgets references) */\n id: SnakeCaseIdentifierSchema.describe('Unique widget identifier (snake_case)'),\n\n /** Widget Title */\n title: I18nLabelSchema.optional().describe('Widget title'),\n\n /** Widget Description (displayed below the title) */\n description: I18nLabelSchema.optional().describe('Widget description text below the header'),\n \n /** Visualization Type */\n type: ChartTypeSchema.default('metric').describe('Visualization type'),\n \n /** Chart Configuration */\n chartConfig: ChartConfigSchema.optional().describe('Chart visualization configuration'),\n\n /** Color variant for the widget (e.g., KPI card accent color) */\n colorVariant: WidgetColorVariantSchema.optional().describe('Widget color variant for theming'),\n\n /** Action URL for the widget header action button */\n actionUrl: z.string().optional().describe('URL or target for the widget action button'),\n\n /** Action type for the widget header action button */\n actionType: WidgetActionTypeSchema.optional().describe('Type of action for the widget action button'),\n\n /** Icon for the widget header action button */\n actionIcon: z.string().optional().describe('Icon identifier for the widget action button'),\n \n /** Data Source Object */\n object: z.string().optional().describe('Data source object name'),\n \n /** Data Filter (MongoDB-style FilterCondition) */\n filter: FilterConditionSchema.optional().describe('Data filter criteria'),\n \n /** Category Field (X-Axis / Group By) */\n categoryField: z.string().optional().describe('Field for grouping (X-Axis)'),\n \n /** Value Field (Y-Axis) */\n valueField: z.string().optional().describe('Field for values (Y-Axis)'),\n \n /** Aggregate operation */\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max']).optional().default('count').describe('Aggregate function'),\n \n /** Multi-measure definitions for pivot/matrix widgets */\n measures: z.array(WidgetMeasureSchema).optional().describe('Multiple measures for pivot/matrix analysis'),\n \n /** \n * Layout Position (React-Grid-Layout style)\n * x: column (0-11)\n * y: row\n * w: width (1-12)\n * h: height\n */\n layout: z.object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n }).describe('Grid layout position'),\n \n /** Widget specific options (colors, legend, etc.) */\n options: z.unknown().optional().describe('Widget specific configuration'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * Dynamic options binding for global filters.\n * Allows dropdown options to be fetched from an object at runtime.\n */\nexport const GlobalFilterOptionsFromSchema = z.object({\n /** Source object name to fetch options from */\n object: z.string().describe('Source object name'),\n\n /** Field to use as option value */\n valueField: z.string().describe('Field to use as option value'),\n\n /** Field to use as option label */\n labelField: z.string().describe('Field to use as option label'),\n\n /** Optional filter to apply when fetching options */\n filter: FilterConditionSchema.optional().describe('Filter to apply to source object'),\n}).describe('Dynamic filter options from object');\n\n/**\n * Global Filter Schema\n * Defines a single global filter control for the dashboard filter bar.\n */\nexport const GlobalFilterSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n\n /** Display label for the filter */\n label: I18nLabelSchema.optional().describe('Display label for the filter'),\n\n /** Filter input type */\n type: z.enum(['text', 'select', 'date', 'number', 'lookup']).optional().describe('Filter input type'),\n\n /** Static options for select/lookup filters */\n options: z.array(z.object({\n value: z.union([z.string(), z.number(), z.boolean()]).describe('Option value'),\n label: I18nLabelSchema,\n })).optional().describe('Static filter options'),\n\n /** Dynamic data binding for filter options */\n optionsFrom: GlobalFilterOptionsFromSchema.optional().describe('Dynamic filter options from object'),\n\n /** Default filter value */\n defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional().describe('Default filter value'),\n\n /** Filter application scope */\n scope: z.enum(['dashboard', 'widget']).default('dashboard').describe('Filter application scope'),\n\n /** Widget IDs to apply this filter to (when scope is widget) */\n targetWidgets: z.array(z.string()).optional().describe('Widget IDs to apply this filter to'),\n});\n\n/**\n * Dashboard Schema\n * Represents a page containing multiple visualizations.\n * \n * @example Sales Executive Dashboard\n * {\n * name: \"sales_overview\",\n * label: \"Sales Executive Overview\",\n * widgets: [\n * {\n * title: \"Total Pipe\",\n * type: \"metric\",\n * object: \"opportunity\",\n * valueField: \"amount\",\n * aggregate: \"sum\",\n * layout: { x: 0, y: 0, w: 3, h: 2 }\n * },\n * {\n * title: \"Revenue by Region\",\n * type: \"bar\",\n * object: \"order\",\n * categoryField: \"region\",\n * valueField: \"total\",\n * aggregate: \"sum\",\n * layout: { x: 3, y: 0, w: 6, h: 4 }\n * }\n * ]\n * }\n */\nexport const DashboardSchema = z.object({\n /** Machine name */\n name: SnakeCaseIdentifierSchema.describe('Dashboard unique name'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Dashboard label'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('Dashboard description'),\n\n /** Structured header configuration */\n header: DashboardHeaderSchema.optional().describe('Dashboard header configuration'),\n \n /** Collection of widgets */\n widgets: z.array(DashboardWidgetSchema).describe('Widgets to display'),\n\n /** Auto-refresh */\n refreshInterval: z.number().optional().describe('Auto-refresh interval in seconds'),\n\n /** Dashboard Date Range (Global time filter) */\n dateRange: z.object({\n field: z.string().optional().describe('Default date field name for time-based filtering'),\n defaultRange: z.enum(['today', 'yesterday', 'this_week', 'last_week', 'this_month', 'last_month', 'this_quarter', 'last_quarter', 'this_year', 'last_year', 'last_7_days', 'last_30_days', 'last_90_days', 'custom']).default('this_month').describe('Default date range preset'),\n allowCustomRange: z.boolean().default(true).describe('Allow users to pick a custom date range'),\n }).optional().describe('Global dashboard date range filter configuration'),\n\n /** Global Filters */\n globalFilters: z.array(GlobalFilterSchema).optional().describe('Global filters that apply to all widgets in the dashboard'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\nexport type Dashboard = z.infer;\nexport type DashboardInput = z.input;\nexport type DashboardWidget = z.infer;\nexport type DashboardHeader = z.infer;\nexport type DashboardHeaderAction = z.infer;\nexport type WidgetMeasure = z.infer;\nexport type WidgetColorVariant = z.infer;\nexport type WidgetActionType = z.infer;\nexport type GlobalFilter = z.infer;\nexport type GlobalFilterOptionsFrom = z.infer;\n\n/**\n * Dashboard Factory Helper\n */\nexport const Dashboard = {\n create: (config: z.input): Dashboard => DashboardSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ChartConfigSchema } from './chart.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Report Type Enum\n */\nexport const ReportType = z.enum([\n 'tabular', // Simple list\n 'summary', // Grouped by row\n 'matrix', // Grouped by row and column\n 'joined' // Joined multiple blocks\n]);\n\n/**\n * Report Column Schema\n */\nexport const ReportColumnSchema = z.object({\n field: z.string().describe('Field name'),\n label: I18nLabelSchema.optional().describe('Override label'),\n aggregate: z.enum(['sum', 'avg', 'max', 'min', 'count', 'unique']).optional().describe('Aggregation function'),\n /** Responsive visibility/priority per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive visibility for this column'),\n});\n\n/**\n * Report Grouping Schema\n */\nexport const ReportGroupingSchema = z.object({\n field: z.string().describe('Field to group by'),\n sortOrder: z.enum(['asc', 'desc']).default('asc'),\n dateGranularity: z.enum(['day', 'week', 'month', 'quarter', 'year']).optional().describe('For date fields'),\n});\n\n/**\n * Report Chart Schema\n * Embedded visualization configuration using unified chart taxonomy.\n */\nexport const ReportChartSchema = ChartConfigSchema.extend({\n /** Report-specific chart configuration */\n xAxis: z.string().describe('Grouping field for X-Axis'),\n yAxis: z.string().describe('Summary field for Y-Axis'),\n groupBy: z.string().optional().describe('Additional grouping field'),\n});\n\n/**\n * Report Schema\n * Deep data analysis definition.\n */\nexport const ReportSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Report unique name'),\n label: I18nLabelSchema.describe('Report label'),\n description: I18nLabelSchema.optional(),\n \n /** Data Source */\n objectName: z.string().describe('Primary object'),\n \n /** Report Configuration */\n type: ReportType.default('tabular').describe('Report format type'),\n \n columns: z.array(ReportColumnSchema).describe('Columns to display'),\n \n /** Grouping (for Summary/Matrix) */\n groupingsDown: z.array(ReportGroupingSchema).optional().describe('Row groupings'),\n groupingsAcross: z.array(ReportGroupingSchema).optional().describe('Column groupings (Matrix only)'),\n \n /** Filtering (MongoDB-style FilterCondition) */\n filter: FilterConditionSchema.optional().describe('Filter criteria'),\n \n /** Visualization */\n chart: ReportChartSchema.optional().describe('Embedded chart configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Report Types\n * \n * Note: For configuration/definition contexts, use the Input types (e.g., ReportInput)\n * which allow optional fields with defaults to be omitted.\n */\nexport type Report = z.infer;\nexport type ReportColumn = z.infer;\nexport type ReportGrouping = z.infer;\nexport type ReportChart = z.infer;\n\n/**\n * Input Types for Report Configuration\n * Use these when defining reports in configuration files.\n */\nexport type ReportInput = z.input;\nexport type ReportColumnInput = z.input;\nexport type ReportGroupingInput = z.input;\nexport type ReportChartInput = z.input;\n\n/**\n * Report Factory Helper\n */\nexport const Report = {\n create: (config: ReportInput): Report => ReportSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { SortItemSchema } from '../shared/enums.zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema } from './responsive.zod';\nimport {\n UserActionsConfigSchema,\n AppearanceConfigSchema,\n ViewTabSchema,\n ViewFilterRuleSchema,\n AddRecordConfigSchema,\n} from './view.zod';\n\n/**\n * Page Region Schema\n * A named region in the template where components are dropped.\n */\nexport const PageRegionSchema = z.object({\n name: z.string().describe('Region name (e.g. \"sidebar\", \"main\", \"header\")'),\n width: z.enum(['small', 'medium', 'large', 'full']).optional(),\n components: z.array(z.lazy(() => PageComponentSchema)).describe('Components in this region')\n});\n\n/**\n * Standard Page Component Types\n */\nexport const PageComponentType = z.enum([\n // Structure\n 'page:header', 'page:footer', 'page:sidebar', 'page:tabs', 'page:accordion', 'page:card', 'page:section',\n // Record Context\n 'record:details', 'record:highlights', 'record:related_list', 'record:activity', 'record:chatter', 'record:path',\n // Navigation\n 'app:launcher', 'nav:menu', 'nav:breadcrumb',\n // Utility\n 'global:search', 'global:notifications', 'user:profile',\n // AI\n 'ai:chat_window', 'ai:suggestion',\n // Content Elements (Airtable Interface parity)\n 'element:text', 'element:number', 'element:image', 'element:divider',\n // Interactive Elements (Phase B — Element Library)\n 'element:button', 'element:filter', 'element:form', 'element:record_picker'\n]);\n\n/**\n * Element Data Source Schema\n * Per-element data binding for multi-object pages.\n * Overrides page-level object context so each element can query a different object.\n */\nexport const ElementDataSourceSchema = z.object({\n object: z.string().describe('Object to query'),\n view: z.string().optional().describe('Named view to apply'),\n filter: FilterConditionSchema.optional().describe('Additional filter criteria'),\n sort: z.array(SortItemSchema).optional().describe('Sort order'),\n limit: z.number().int().positive().optional().describe('Max records to display'),\n});\n\n/**\n * Page Component Schema\n * A configured instance of a UI component.\n */\nexport const PageComponentSchema = z.object({\n /** Definition */\n type: z.union([\n PageComponentType,\n z.string()\n ]).describe('Component Type (Standard enum or custom string)'),\n id: z.string().optional().describe('Unique instance ID'),\n \n /** Configuration */\n label: I18nLabelSchema.optional(),\n properties: z.record(z.string(), z.unknown()).describe('Component props passed to the widget. See component.zod.ts for schemas.'),\n \n /** \n * Event Handlers \n * Map event names to Action expressions.\n * \"onClick\": \"set_variable('userId', $event.id)\"\n * \"onRowSelect\": \"navigate_to('page_detail', { id: $event.id })\"\n */\n events: z.record(z.string(), z.string()).optional().describe('Event handlers map'),\n\n /** Appearance */\n style: z.record(z.string(), z.string()).optional().describe('Inline styles or utility classes'),\n className: z.string().optional().describe('CSS class names'),\n\n /** Visibility Rule */\n visibility: z.string().optional().describe('Visibility filter/formula'),\n\n /** Per-element data binding, overrides page-level object context */\n dataSource: ElementDataSourceSchema.optional().describe('Per-element data binding for multi-object pages'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * Page Variable Schema\n * Defines local state for the page.\n * Variables can be bound to interactive elements (e.g. element:record_picker, element:filter).\n */\nexport const PageVariableSchema = z.object({\n name: z.string().describe('Variable name'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array', 'record_id']).default('string'),\n defaultValue: z.unknown().optional(),\n /** Source element binding (e.g. element:record_picker writes to this variable) */\n source: z.string().optional().describe('Component ID that writes to this variable'),\n});\n\n/**\n * Blank Page Layout Item Schema\n * Positions a component on a free-form grid canvas.\n */\nexport const BlankPageLayoutItemSchema = z.object({\n componentId: z.string().describe('Reference to a PageComponent.id in the page'),\n x: z.number().int().min(0).describe('Grid column position (0-based)'),\n y: z.number().int().min(0).describe('Grid row position (0-based)'),\n width: z.number().int().min(1).describe('Width in grid columns'),\n height: z.number().int().min(1).describe('Height in grid rows'),\n});\n\n/**\n * Blank Page Layout Schema\n * Free-form canvas composition with grid-based positioning.\n * Used when page type is 'blank' to enable drag-and-drop element placement.\n */\nexport const BlankPageLayoutSchema = z.object({\n columns: z.number().int().min(1).default(12).describe('Number of grid columns'),\n rowHeight: z.number().int().min(1).default(40).describe('Height of each grid row in pixels'),\n gap: z.number().int().min(0).default(8).describe('Gap between grid items in pixels'),\n items: z.array(BlankPageLayoutItemSchema).describe('Positioned components on the canvas'),\n});\n\n/**\n * Page Type Schema\n * Unified page type enum covering both platform pages (Salesforce FlexiPage style)\n * and Airtable-inspired interface page types.\n *\n * **Disambiguation of similar types:**\n * - `record` vs `record_detail`: `record` is a component-based layout page (FlexiPage style with regions),\n * `record_detail` is a field-display page showing all fields of a single record (Airtable style).\n * Use `record` for custom record pages with regions/components, `record_detail` for auto-generated detail views.\n * - `home` vs `overview`: `home` is the platform-level landing page (tab landing),\n * `overview` is an interface-level navigation hub with links/instructions.\n * Use `home` for app-level landing, `overview` for in-interface navigation hubs.\n * - `app` vs `utility` vs `blank`: `app` is an app-level page with navigation context,\n * `utility` is a floating utility panel (e.g. notes, phone), `blank` is a free-form canvas\n * for custom composition. They serve distinct layout purposes.\n */\nexport const PageTypeSchema = z.enum([\n // Platform page types (Salesforce FlexiPage style)\n 'record', // Component-based record layout page with regions\n 'home', // Platform-level home/landing page\n 'app', // App-level page with navigation context\n 'utility', // Floating utility panel (e.g. notes, phone dialer)\n // Interface page types (Airtable Interface parity)\n 'dashboard', // KPI summary with charts/metrics\n 'grid', // Spreadsheet-like data table\n 'list', // Record list with quick actions\n 'gallery', // Card-based visual browsing\n 'kanban', // Status-based board\n 'calendar', // Date-based scheduling\n 'timeline', // Gantt-like project timeline\n 'form', // Data entry form\n 'record_detail', // Auto-generated single record field display\n 'record_review', // Sequential record review/approval\n 'overview', // Interface-level navigation/landing hub\n 'blank', // Free-form canvas for custom composition\n]).describe('Page type — platform or interface page types');\n\n/**\n * Record Review Config Schema\n * Configuration for a sequential record review/approval page.\n * Users navigate through records one-by-one, taking actions (approve/reject/skip).\n * Only applicable when page type is 'record_review'.\n */\nexport const RecordReviewConfigSchema = z.object({\n object: z.string().describe('Target object for review'),\n filter: FilterConditionSchema.optional().describe('Filter criteria for review queue'),\n sort: z.array(SortItemSchema).optional().describe('Sort order for review queue'),\n displayFields: z.array(z.string()).optional()\n .describe('Fields to display on the review page'),\n actions: z.array(z.object({\n label: z.string().describe('Action button label'),\n type: z.enum(['approve', 'reject', 'skip', 'custom'])\n .describe('Action type'),\n field: z.string().optional()\n .describe('Field to update on action'),\n value: z.union([z.string(), z.number(), z.boolean()]).optional()\n .describe('Value to set on action'),\n nextRecord: z.boolean().optional().default(true)\n .describe('Auto-advance to next record after action'),\n })).describe('Review actions'),\n navigation: z.enum(['sequential', 'random', 'filtered'])\n .optional().default('sequential')\n .describe('Record navigation mode'),\n showProgress: z.boolean().optional().default(true)\n .describe('Show review progress indicator'),\n});\n\n/**\n * Interface Page Configuration Schema (Airtable Interface parity)\n * Page-level declarative configuration for Airtable-style interface pages.\n * Covers title/data binding, levels, filter by, appearance, user actions,\n * tabs, record count, add record, and advanced options (printing).\n *\n * @see Airtable Interface → right panel (Page / Data / Appearance / User filters / User actions / Advanced)\n */\nexport const InterfacePageConfigSchema = z.object({\n /** Data binding */\n source: z.string().optional().describe('Source object name for the page'),\n levels: z.number().int().min(1).optional().describe('Number of hierarchy levels to display'),\n filterBy: z.array(ViewFilterRuleSchema).optional().describe('Page-level filter criteria'),\n\n /** Appearance */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** User filters */\n userFilters: z.object({\n elements: z.array(z.enum(['grid', 'gallery', 'kanban'])).optional()\n .describe('Visualization element types available in user filter bar'),\n tabs: z.array(ViewTabSchema).optional().describe('User-configurable tabs'),\n }).optional().describe('User filter configuration'),\n\n /** User actions */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles'),\n\n /** Add record */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record count */\n showRecordCount: z.boolean().optional().describe('Show record count at page bottom'),\n\n /** Advanced */\n allowPrinting: z.boolean().optional().describe('Allow users to print the page'),\n}).describe('Interface-level page configuration (Airtable parity)');\n\n/**\n * Page Schema\n * Defines a composition of components for a specific context.\n * Supports both platform pages (Salesforce FlexiPage style: record, home, app, utility)\n * and interface pages (Airtable Interface style: dashboard, grid, kanban, record_review, etc.).\n * \n * **NAMING CONVENTION:**\n * Page names are used in routing and must be lowercase snake_case.\n * Prefix with 'page_' is recommended for clarity.\n * \n * @example Good page names\n * - 'page_dashboard'\n * - 'page_settings'\n * - 'home_page'\n * - 'record_detail'\n * \n * @example Bad page names (will be rejected)\n * - 'PageDashboard' (PascalCase)\n * - 'Settings Page' (spaces)\n */\nexport const PageSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Page unique name (lowercase snake_case)'),\n label: I18nLabelSchema,\n description: I18nLabelSchema.optional(),\n\n /** Icon (used in interface navigation) */\n icon: z.string().optional().describe('Page icon name'),\n \n /** Page Type */\n type: PageTypeSchema.default('record').describe('Page type'),\n \n /** Page State Definitions */\n variables: z.array(PageVariableSchema).optional().describe('Local page state variables'),\n\n /** Context */\n object: z.string().optional().describe('Bound object (for Record pages)'),\n\n /** Record Review Configuration (only for record_review pages) */\n recordReview: RecordReviewConfigSchema.optional()\n .describe('Record review configuration (required when type is \"record_review\")'),\n\n /** Blank Page Layout (only for blank pages) */\n blankLayout: BlankPageLayoutSchema.optional()\n .describe('Free-form grid layout for blank pages (used when type is \"blank\")'),\n \n /** Layout Template */\n template: z.string().default('default').describe('Layout template name (e.g. \"header-sidebar-main\")'),\n \n /** Regions & Content */\n regions: z.array(PageRegionSchema).describe('Defined regions with components'),\n \n /** Activation */\n isDefault: z.boolean().default(false),\n assignedProfiles: z.array(z.string()).optional(),\n\n /** Interface Page Configuration (Airtable Interface parity) */\n interfaceConfig: InterfacePageConfigSchema.optional()\n .describe('Interface-level page configuration (for Airtable-style interface pages)'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).superRefine((data, ctx) => {\n if (data.type === 'record_review' && !data.recordReview) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['recordReview'],\n message: 'recordReview is required when type is \"record_review\"',\n });\n }\n if (data.type === 'blank' && !data.blankLayout) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['blankLayout'],\n message: 'blankLayout is required when type is \"blank\"',\n });\n }\n});\n\nexport type Page = z.infer;\nexport type PageType = z.infer;\nexport type PageComponent = z.infer;\nexport type PageRegion = z.infer;\nexport type PageVariable = z.infer;\nexport type ElementDataSource = z.infer;\nexport type RecordReviewConfig = z.infer;\nexport type BlankPageLayoutItem = z.infer;\nexport type BlankPageLayout = z.infer;\nexport type InterfacePageConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Widget Lifecycle Hooks Schema\n * \n * Defines lifecycle callbacks for custom widgets inspired by Web Components and React.\n * These hooks allow widgets to perform initialization, cleanup, and respond to changes.\n * \n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components\n * @see https://react.dev/reference/react/Component#component-lifecycle\n * \n * @example\n * ```typescript\n * const widget = {\n * lifecycle: {\n * onMount: \"console.log('Widget mounted')\",\n * onUpdate: \"if (prevProps.value !== props.value) { updateUI() }\",\n * onUnmount: \"cleanup()\",\n * onValidate: \"return value.length > 0 ? null : 'Required field'\"\n * }\n * }\n * ```\n */\nexport const WidgetLifecycleSchema = z.object({\n /**\n * Called when widget is mounted/rendered for the first time\n * Use for initialization, setting up event listeners, loading data, etc.\n * \n * @example \"initializeDatePicker(); loadOptions();\"\n */\n onMount: z.string().optional().describe('Initialization code when widget mounts'),\n\n /**\n * Called when widget props change\n * Receives previous props for comparison\n * \n * @example \"if (prevProps.value !== props.value) { updateDisplay() }\"\n */\n onUpdate: z.string().optional().describe('Code to run when props change'),\n\n /**\n * Called when widget is about to be removed from DOM\n * Use for cleanup, removing event listeners, canceling timers, etc.\n * \n * @example \"destroyDatePicker(); cancelPendingRequests();\"\n */\n onUnmount: z.string().optional().describe('Cleanup code when widget unmounts'),\n\n /**\n * Custom validation logic for this widget\n * Should return error message string if invalid, null/undefined if valid\n * \n * @example \"return value && value.length >= 10 ? null : 'Minimum 10 characters'\"\n */\n onValidate: z.string().optional().describe('Custom validation logic'),\n\n /**\n * Called when widget receives focus\n * \n * @example \"highlightField(); logFocusEvent();\"\n */\n onFocus: z.string().optional().describe('Code to run on focus'),\n\n /**\n * Called when widget loses focus\n * \n * @example \"validateField(); saveFieldState();\"\n */\n onBlur: z.string().optional().describe('Code to run on blur'),\n\n /**\n * Called on any error in the widget\n * \n * @example \"logError(error); showErrorNotification();\"\n */\n onError: z.string().optional().describe('Error handling code'),\n});\n\nexport type WidgetLifecycle = z.infer;\n\n/**\n * Widget Event Schema\n * \n * Defines custom events that widgets can emit, inspired by DOM Events and Lightning Web Components.\n * \n * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events\n * @see https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.events\n * \n * @example\n * ```typescript\n * const searchEvent = {\n * name: 'search',\n * bubbles: true,\n * cancelable: false,\n * payload: {\n * query: 'string',\n * filters: 'object'\n * }\n * }\n * ```\n */\nexport const WidgetEventSchema = z.object({\n /**\n * Event name\n * Should be lowercase, dash-separated for consistency\n * \n * @example \"value-change\", \"item-selected\", \"search-complete\"\n */\n name: z.string().describe('Event name'),\n\n /**\n * Event label for documentation\n */\n label: I18nLabelSchema.optional().describe('Human-readable event label'),\n\n /**\n * Event description\n */\n description: I18nLabelSchema.optional().describe('Event description and usage'),\n\n /**\n * Whether event bubbles up through the DOM hierarchy\n * \n * @default false\n */\n bubbles: z.boolean().default(false).describe('Whether event bubbles'),\n\n /**\n * Whether event can be cancelled\n * \n * @default false\n */\n cancelable: z.boolean().default(false).describe('Whether event is cancelable'),\n\n /**\n * Event payload schema\n * Defines the data structure sent with the event\n * \n * @example { userId: 'string', timestamp: 'number' }\n */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event payload schema'),\n});\n\nexport type WidgetEvent = z.infer;\n\n/**\n * Widget Property Definition Schema\n * \n * Defines the contract for widget configuration properties.\n * Inspired by React PropTypes and Web Component attributes.\n * \n * @see https://react.dev/reference/react/Component#static-proptypes\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements\n * \n * @example\n * ```typescript\n * const widgetProps = {\n * maxLength: {\n * type: 'number',\n * required: false,\n * default: 100,\n * description: 'Maximum input length'\n * }\n * }\n * ```\n */\nexport const WidgetPropertySchema = z.object({\n /**\n * Property name\n * Should be camelCase following ObjectStack conventions\n */\n name: z.string().describe('Property name (camelCase)'),\n\n /**\n * Property label for UI\n */\n label: I18nLabelSchema.optional().describe('Human-readable label'),\n\n /**\n * Property data type\n * \n * @example \"string\", \"number\", \"boolean\", \"array\", \"object\", \"function\"\n */\n type: z.enum(['string', 'number', 'boolean', 'array', 'object', 'function', 'any'])\n .describe('TypeScript type'),\n\n /**\n * Whether property is required\n * \n * @default false\n */\n required: z.boolean().default(false).describe('Whether property is required'),\n\n /**\n * Default value for the property\n */\n default: z.unknown().optional().describe('Default value'),\n\n /**\n * Property description\n */\n description: I18nLabelSchema.optional().describe('Property description'),\n\n /**\n * Property validation schema\n * Can include min/max, regex, enum values, etc.\n */\n validation: z.record(z.string(), z.unknown()).optional().describe('Validation rules'),\n\n /**\n * Property category for grouping in UI\n */\n category: z.string().optional().describe('Property category'),\n});\n\nexport type WidgetProperty = z.infer;\n\n/**\n * Widget Manifest Schema\n * \n * Complete definition for a custom widget including metadata, lifecycle, events, and props.\n * This is used for widget registration and discovery.\n * \n * @example\n * ```typescript\n * const customWidget = {\n * name: 'custom_date_picker',\n * label: 'Custom Date Picker',\n * version: '1.0.0',\n * author: 'Company Name',\n * fieldTypes: ['date', 'datetime'],\n * lifecycle: { ... },\n * events: [ ... ],\n * properties: [ ... ]\n * }\n * ```\n */\n/**\n * Widget Source Schema\n * Defines how the widget code is loaded.\n */\nexport const WidgetSourceSchema = z.discriminatedUnion('type', [\n // NPM Registry (standard)\n z.object({\n type: z.literal('npm'),\n packageName: z.string().describe('NPM package name'),\n version: z.string().default('latest'),\n exportName: z.string().optional().describe('Named export (default: default)'),\n }),\n // Module Federation (Remote)\n z.object({\n type: z.literal('remote'),\n url: z.string().url().describe('Remote entry URL (.js)'),\n moduleName: z.string().describe('Exposed module name'),\n scope: z.string().describe('Remote scope name'),\n }),\n // Inline Code (Simple scripts)\n z.object({\n type: z.literal('inline'),\n code: z.string().describe('JavaScript code body'),\n }),\n]);\n\nexport type WidgetSource = z.infer;\n\nexport const WidgetManifestSchema = z.object({\n /**\n * Widget identifier (snake_case)\n */\n name: SnakeCaseIdentifierSchema\n .describe('Widget identifier (snake_case)'),\n\n /**\n * Human-readable widget name\n */\n label: I18nLabelSchema.describe('Widget display name'),\n\n /**\n * Widget description\n */\n description: I18nLabelSchema.optional().describe('Widget description'),\n\n /**\n * Widget version (semver)\n */\n version: z.string().optional().describe('Widget version (semver)'),\n\n /**\n * Widget author/organization\n */\n author: z.string().optional().describe('Widget author'),\n\n /**\n * Icon name or URL\n */\n icon: z.string().optional().describe('Widget icon'),\n\n /**\n * Field types this widget supports\n * \n * @example [\"text\", \"email\", \"url\"]\n */\n fieldTypes: z.array(z.string()).optional().describe('Supported field types'),\n\n /**\n * Widget category for organization\n */\n category: z.enum(['input', 'display', 'picker', 'editor', 'custom'])\n .default('custom')\n .describe('Widget category'),\n\n /**\n * Widget lifecycle hooks\n */\n lifecycle: WidgetLifecycleSchema.optional().describe('Lifecycle hooks'),\n\n /**\n * Custom events this widget emits\n */\n events: z.array(WidgetEventSchema).optional().describe('Custom events'),\n\n /**\n * Widget configuration properties\n */\n properties: z.array(WidgetPropertySchema).optional().describe('Configuration properties'),\n\n /**\n * Widget implementation\n * Defines how to load the widget code\n */\n implementation: WidgetSourceSchema.optional().describe('Widget implementation source'),\n\n /**\n * Widget dependencies\n * External libraries or scripts needed\n */\n dependencies: z.array(z.object({\n name: z.string(),\n version: z.string().optional(),\n url: z.string().url().optional(),\n })).optional().describe('Widget dependencies'),\n\n /**\n * Widget screenshots for showcase\n */\n screenshots: z.array(z.string().url()).optional().describe('Screenshot URLs'),\n\n /**\n * Widget documentation URL\n */\n documentation: z.string().url().optional().describe('Documentation URL'),\n\n /**\n * License information\n */\n license: z.string().optional().describe('License (SPDX identifier)'),\n\n /**\n * Tags for discovery\n */\n tags: z.array(z.string()).optional().describe('Tags for categorization'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\nexport type WidgetManifest = z.infer;\n\n/**\n * Field Widget Props Schema\n * \n * This defines the contract for custom field components and plugin UI extensions.\n * Third-party developers use this interface to build custom field widgets that integrate\n * seamlessly with the ObjectStack UI system.\n * \n * @example\n * // Custom widget implementation\n * function CustomDatePicker(props: FieldWidgetProps) {\n * const { value, onChange, readonly, required, error, field, record, options } = props;\n * // Widget implementation...\n * }\n */\nexport const FieldWidgetPropsSchema = z.object({\n /**\n * Current field value.\n * Type depends on the field type (string, number, boolean, array, object, etc.)\n */\n value: z.unknown().describe('Current field value'),\n\n /**\n * Callback function to update the field value.\n * Should be called when user interaction changes the value.\n * \n * @param newValue - The new value to set\n */\n onChange: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.void())\n .describe('Callback to update field value'),\n\n /**\n * Whether the field is in read-only mode.\n * When true, the widget should display the value but not allow editing.\n */\n readonly: z.boolean().default(false).describe('Read-only mode flag'),\n\n /**\n * Whether the field is required.\n * Widget should indicate required state visually and validate accordingly.\n */\n required: z.boolean().default(false).describe('Required field flag'),\n\n /**\n * Validation error message to display.\n * When present, widget should display the error in its UI.\n */\n error: z.string().optional().describe('Validation error message'),\n\n /**\n * Complete field definition from the schema.\n * Contains metadata like type, constraints, options, etc.\n */\n field: FieldSchema.describe('Field schema definition'),\n\n /**\n * The complete record/document being edited.\n * Useful for conditional logic and cross-field dependencies.\n */\n record: z.record(z.string(), z.unknown()).optional().describe('Complete record data'),\n\n /**\n * Custom options passed to the widget.\n * Can contain widget-specific configuration like themes, behaviors, etc.\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Custom widget options'),\n});\n\n/**\n * TypeScript type for Field Widget Props\n */\nexport type FieldWidgetProps = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ViewFilterRuleSchema } from './view.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { FeedItemType, FeedFilterMode } from '../data/feed.zod';\n\n/**\n * Empty Properties Schema\n */\nconst EmptyProps = z.object({});\n\n/**\n * ----------------------------------------------------------------------\n * 1. Structure Components\n * ----------------------------------------------------------------------\n */\n\nexport const PageHeaderProps = z.object({\n title: I18nLabelSchema.describe('Page title'),\n subtitle: I18nLabelSchema.optional().describe('Page subtitle'),\n icon: z.string().optional().describe('Icon name'),\n breadcrumb: z.boolean().default(true).describe('Show breadcrumb'),\n actions: z.array(z.string()).optional().describe('Action IDs to show in header'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageTabsProps = z.object({\n type: z.enum(['line', 'card', 'pill']).default('line'),\n position: z.enum(['top', 'left']).default('top'),\n items: z.array(z.object({\n label: I18nLabelSchema,\n icon: z.string().optional(),\n children: z.array(z.unknown()).describe('Child components')\n })),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageCardProps = z.object({\n title: I18nLabelSchema.optional(),\n bordered: z.boolean().default(true),\n actions: z.array(z.string()).optional(),\n /** Slot for nested content in the Card body */\n body: z.array(z.unknown()).optional().describe('Card content components (slot)'),\n /** Slot for footer content */\n footer: z.array(z.unknown()).optional().describe('Card footer components (slot)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 2. Record Context Components\n * ----------------------------------------------------------------------\n */\n\nexport const RecordDetailsProps = z.object({\n columns: z.enum(['1', '2', '3', '4']).default('2').describe('Number of columns for field layout (1-4)'),\n layout: z.enum(['auto', 'custom']).default('auto').describe('Layout mode: auto uses object compactLayout, custom uses explicit sections'),\n sections: z.array(z.string()).optional().describe('Section IDs to show (required when layout is \"custom\")'),\n fields: z.array(z.string()).optional().describe('Explicit field list to display (optional, overrides compactLayout)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordRelatedListProps = z.object({\n objectName: z.string().describe('Related object name (e.g., \"task\", \"opportunity\")'),\n relationshipField: z.string().describe('Field on related object that points to this record (e.g., \"account_id\")'),\n columns: z.array(z.string()).describe('Fields to display in the related list'),\n sort: z.union([\n z.string(),\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional().describe('Sort order for related records'),\n limit: z.number().int().positive().default(5).describe('Number of records to display initially'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Additional filter criteria for related records'),\n title: I18nLabelSchema.optional().describe('Custom title for the related list'),\n showViewAll: z.boolean().default(true).describe('Show \"View All\" link to see all related records'),\n actions: z.array(z.string()).optional().describe('Action IDs available for related records'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordHighlightsProps = z.object({\n fields: z.array(z.string()).min(1).max(7).describe('Key fields to highlight (1-7 fields max, typically displayed as prominent cards)'),\n layout: z.enum(['horizontal', 'vertical']).default('horizontal').describe('Layout orientation for highlight fields'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordActivityProps = z.object({\n /** Activity types to display (unified enum including comment, field_change, etc.) */\n types: z.array(FeedItemType).optional().describe('Feed item types to show (default: all)'),\n /** Default filter mode (Airtable-style dropdown) */\n filterMode: FeedFilterMode.default('all').describe('Default activity filter'),\n /** Allow user to switch filter modes */\n showFilterToggle: z.boolean().default(true).describe('Show filter dropdown in panel header'),\n /** Pagination */\n limit: z.number().int().positive().default(20).describe('Number of items to load per page'),\n /** Show completed activities */\n showCompleted: z.boolean().default(false).describe('Include completed activities'),\n /** Merge field_change + comment in a unified timeline */\n unifiedTimeline: z.boolean().default(true).describe('Mix field changes and comments in one timeline (Airtable style)'),\n /** Show the comment input box at the bottom */\n showCommentInput: z.boolean().default(true).describe('Show \"Leave a comment\" input at the bottom'),\n /** Enable @mentions in comments */\n enableMentions: z.boolean().default(true).describe('Enable @mentions in comments'),\n /** Enable emoji reactions */\n enableReactions: z.boolean().default(false).describe('Enable emoji reactions on feed items'),\n /** Enable threaded replies */\n enableThreading: z.boolean().default(false).describe('Enable threaded replies on comments'),\n /** Show notification subscription toggle (bell icon) */\n showSubscriptionToggle: z.boolean().default(true).describe('Show bell icon for record-level notification subscription'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordChatterProps = z.object({\n /** Panel position */\n position: z.enum(['sidebar', 'inline', 'drawer']).default('sidebar').describe('Where to render the chatter panel'),\n /** Panel width (for sidebar/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Panel width (e.g., \"350px\", \"30%\")'),\n /** Collapsible */\n collapsible: z.boolean().default(true).describe('Whether the panel can be collapsed'),\n /** Default collapsed state */\n defaultCollapsed: z.boolean().default(false).describe('Whether the panel starts collapsed'),\n /** Feed configuration (delegates to RecordActivityProps) */\n feed: RecordActivityProps.optional().describe('Embedded activity feed configuration'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordPathProps = z.object({\n statusField: z.string().describe('Field name representing the current status/stage'),\n stages: z.array(z.object({\n value: z.string(),\n label: I18nLabelSchema,\n })).optional().describe('Explicit stage definitions (if not using field metadata)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageAccordionProps = z.object({\n items: z.array(z.object({\n label: I18nLabelSchema,\n icon: z.string().optional(),\n collapsed: z.boolean().default(false),\n children: z.array(z.unknown()).describe('Child components'),\n })),\n allowMultiple: z.boolean().default(false).describe('Allow multiple panels to be expanded simultaneously'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const AIChatWindowProps = z.object({\n mode: z.enum(['float', 'sidebar', 'inline']).default('float').describe('Display mode for the chat window'),\n agentId: z.string().optional().describe('Specific AI agent to use'),\n context: z.record(z.string(), z.unknown()).optional().describe('Contextual data to pass to the AI'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 3. Content Element Components (Airtable Interface Parity)\n * ----------------------------------------------------------------------\n */\n\nexport const ElementTextPropsSchema = z.object({\n content: z.string().describe('Text or Markdown content'),\n variant: z.enum(['heading', 'subheading', 'body', 'caption'])\n .optional().default('body').describe('Text style variant'),\n align: z.enum(['left', 'center', 'right'])\n .optional().default('left').describe('Text alignment'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementNumberPropsSchema = z.object({\n object: z.string().describe('Source object'),\n field: z.string().optional().describe('Field to aggregate'),\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max'])\n .describe('Aggregation function'),\n filter: FilterConditionSchema.optional().describe('Filter criteria'),\n format: z.enum(['number', 'currency', 'percent']).optional().describe('Number display format'),\n prefix: z.string().optional().describe('Prefix text (e.g. \"$\")'),\n suffix: z.string().optional().describe('Suffix text (e.g. \"%\")'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementImagePropsSchema = z.object({\n src: z.string().describe('Image URL or attachment field'),\n alt: z.string().optional().describe('Alt text for accessibility'),\n fit: z.enum(['cover', 'contain', 'fill'])\n .optional().default('cover').describe('Image object-fit mode'),\n height: z.number().optional().describe('Fixed height in pixels'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 4. Interactive Element Components (Phase B — Element Library)\n * ----------------------------------------------------------------------\n */\n\nexport const ElementButtonPropsSchema = z.object({\n label: I18nLabelSchema.describe('Button display label'),\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link'])\n .optional().default('primary').describe('Button visual variant'),\n size: z.enum(['small', 'medium', 'large'])\n .optional().default('medium').describe('Button size'),\n icon: z.string().optional().describe('Icon name (Lucide icon)'),\n iconPosition: z.enum(['left', 'right'])\n .optional().default('left').describe('Icon position relative to label'),\n disabled: z.boolean().optional().default(false).describe('Disable the button'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementFilterPropsSchema = z.object({\n object: z.string().describe('Object to filter'),\n fields: z.array(z.string()).describe('Filterable field names'),\n targetVariable: z.string().optional().describe('Page variable to store filter state'),\n layout: z.enum(['inline', 'dropdown', 'sidebar'])\n .optional().default('inline').describe('Filter display layout'),\n showSearch: z.boolean().optional().default(true).describe('Show search input'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementFormPropsSchema = z.object({\n object: z.string().describe('Object for the form'),\n fields: z.array(z.string()).optional().describe('Fields to display (defaults to all editable fields)'),\n mode: z.enum(['create', 'edit']).optional().default('create').describe('Form mode'),\n submitLabel: I18nLabelSchema.optional().describe('Submit button label'),\n onSubmit: z.string().optional().describe('Action expression on form submit'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementRecordPickerPropsSchema = z.object({\n object: z.string().describe('Object to pick records from'),\n displayField: z.string().describe('Field to display as the record label'),\n searchFields: z.array(z.string()).optional().describe('Fields to search against'),\n filter: FilterConditionSchema.optional().describe('Filter criteria for available records'),\n multiple: z.boolean().optional().default(false).describe('Allow multiple record selection'),\n targetVariable: z.string().optional().describe('Page variable to bind selected record ID(s)'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * Component Props Map\n * Maps Component Type to its Property Schema\n * ----------------------------------------------------------------------\n */\nexport const ComponentPropsMap = {\n // Structure\n 'page:header': PageHeaderProps,\n 'page:tabs': PageTabsProps,\n 'page:card': PageCardProps,\n 'page:footer': EmptyProps,\n 'page:sidebar': EmptyProps,\n 'page:accordion': PageAccordionProps,\n 'page:section': EmptyProps,\n\n // Record\n 'record:details': RecordDetailsProps,\n 'record:related_list': RecordRelatedListProps,\n 'record:highlights': RecordHighlightsProps,\n 'record:activity': RecordActivityProps,\n 'record:chatter': RecordChatterProps,\n 'record:path': RecordPathProps,\n\n // Navigation\n 'app:launcher': EmptyProps,\n 'nav:menu': EmptyProps,\n 'nav:breadcrumb': EmptyProps,\n\n // Utility\n 'global:search': EmptyProps,\n 'global:notifications': EmptyProps,\n 'user:profile': EmptyProps,\n \n // AI\n 'ai:chat_window': AIChatWindowProps,\n 'ai:suggestion': z.object({ context: z.string().optional() }),\n\n // Content Elements\n 'element:text': ElementTextPropsSchema,\n 'element:number': ElementNumberPropsSchema,\n 'element:image': ElementImagePropsSchema,\n 'element:divider': EmptyProps,\n\n // Interactive Elements\n 'element:button': ElementButtonPropsSchema,\n 'element:filter': ElementFilterPropsSchema,\n 'element:form': ElementFormPropsSchema,\n 'element:record_picker': ElementRecordPickerPropsSchema,\n} as const;\n\n/**\n * Type Helper to extract props from map\n */\nexport type ComponentProps = z.infer;\nexport type ComponentPropsInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Touch Target Configuration Schema\n * Ensures touch targets meet WCAG 2.5.5 minimum size requirements (44x44px).\n */\nexport const TouchTargetConfigSchema = z.object({\n minWidth: z.number().default(44).describe('Minimum touch target width in pixels (WCAG 2.5.5: 44px)'),\n minHeight: z.number().default(44).describe('Minimum touch target height in pixels (WCAG 2.5.5: 44px)'),\n padding: z.number().optional().describe('Additional padding around touch target in pixels'),\n hitSlop: z.object({\n top: z.number().optional().describe('Extra hit area above the element'),\n right: z.number().optional().describe('Extra hit area to the right of the element'),\n bottom: z.number().optional().describe('Extra hit area below the element'),\n left: z.number().optional().describe('Extra hit area to the left of the element'),\n }).optional().describe('Invisible hit area extension beyond the visible bounds'),\n}).describe('Touch target sizing configuration (WCAG accessible)');\n\nexport type TouchTargetConfig = z.infer;\n\n/**\n * Gesture Type Enum\n * Supported touch gesture types.\n */\nexport const GestureTypeSchema = z.enum([\n 'swipe',\n 'pinch',\n 'long_press',\n 'double_tap',\n 'drag',\n 'rotate',\n 'pan',\n]).describe('Touch gesture type');\n\nexport type GestureType = z.infer;\n\n/**\n * Swipe Direction Enum\n */\nexport const SwipeDirectionSchema = z.enum(['up', 'down', 'left', 'right']);\n\nexport type SwipeDirection = z.infer;\n\n/**\n * Swipe Gesture Configuration Schema\n */\nexport const SwipeGestureConfigSchema = z.object({\n direction: z.array(SwipeDirectionSchema).describe('Allowed swipe directions'),\n threshold: z.number().optional().describe('Minimum distance in pixels to recognize swipe'),\n velocity: z.number().optional().describe('Minimum velocity (px/ms) to trigger swipe'),\n}).describe('Swipe gesture recognition settings');\n\nexport type SwipeGestureConfig = z.infer;\n\n/**\n * Pinch Gesture Configuration Schema\n */\nexport const PinchGestureConfigSchema = z.object({\n minScale: z.number().optional().describe('Minimum scale factor (e.g., 0.5 for 50%)'),\n maxScale: z.number().optional().describe('Maximum scale factor (e.g., 3.0 for 300%)'),\n}).describe('Pinch/zoom gesture recognition settings');\n\nexport type PinchGestureConfig = z.infer;\n\n/**\n * Long Press Gesture Configuration Schema\n */\nexport const LongPressGestureConfigSchema = z.object({\n duration: z.number().default(500).describe('Hold duration in milliseconds to trigger long press'),\n moveTolerance: z.number().optional().describe('Max movement in pixels allowed during press'),\n}).describe('Long press gesture recognition settings');\n\nexport type LongPressGestureConfig = z.infer;\n\n/**\n * Gesture Configuration Schema\n * Unified configuration for all supported gesture types.\n */\nexport const GestureConfigSchema = z.object({\n type: GestureTypeSchema.describe('Gesture type to configure'),\n label: I18nLabelSchema.optional().describe('Descriptive label for the gesture action'),\n enabled: z.boolean().default(true).describe('Whether this gesture is active'),\n swipe: SwipeGestureConfigSchema.optional().describe('Swipe gesture settings (when type is swipe)'),\n pinch: PinchGestureConfigSchema.optional().describe('Pinch gesture settings (when type is pinch)'),\n longPress: LongPressGestureConfigSchema.optional().describe('Long press settings (when type is long_press)'),\n}).describe('Per-gesture configuration');\n\nexport type GestureConfig = z.infer;\n\n/**\n * Touch Interaction Schema\n * Top-level touch and gesture interaction configuration for a component.\n */\nexport const TouchInteractionSchema = z.object({\n gestures: z.array(GestureConfigSchema).optional().describe('Configured gesture recognizers'),\n touchTarget: TouchTargetConfigSchema.optional().describe('Touch target sizing and hit area'),\n hapticFeedback: z.boolean().optional().describe('Enable haptic feedback on touch interactions'),\n}).merge(AriaPropsSchema.partial()).describe('Touch and gesture interaction configuration');\n\nexport type TouchInteraction = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Focus Trap Configuration Schema\n * Constrains keyboard focus within a specific container (e.g., modals, dialogs).\n */\nexport const FocusTrapConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable focus trapping within this container'),\n initialFocus: z.string().optional().describe('CSS selector for the element to focus on activation'),\n returnFocus: z.boolean().default(true).describe('Return focus to trigger element on deactivation'),\n escapeDeactivates: z.boolean().default(true).describe('Allow Escape key to deactivate the focus trap'),\n}).describe('Focus trap configuration for modal-like containers');\n\nexport type FocusTrapConfig = z.infer;\n\n/**\n * Keyboard Shortcut Schema\n * Defines a single keyboard shortcut binding.\n */\nexport const KeyboardShortcutSchema = z.object({\n key: z.string().describe('Key combination (e.g., \"Ctrl+S\", \"Alt+N\", \"Escape\")'),\n action: z.string().describe('Action identifier to invoke when shortcut is triggered'),\n description: I18nLabelSchema.optional().describe('Human-readable description of what the shortcut does'),\n scope: z.enum(['global', 'view', 'form', 'modal', 'list']).default('global')\n .describe('Scope in which this shortcut is active'),\n}).describe('Keyboard shortcut binding');\n\nexport type KeyboardShortcut = z.infer;\n\n/**\n * Focus Management Schema\n * Controls tab order, focus visibility, and navigation behavior.\n */\nexport const FocusManagementSchema = z.object({\n tabOrder: z.enum(['auto', 'manual']).default('auto')\n .describe('Tab order strategy: auto (DOM order) or manual (explicit tabIndex)'),\n skipLinks: z.boolean().default(false).describe('Provide skip-to-content navigation links'),\n focusVisible: z.boolean().default(true).describe('Show visible focus indicators for keyboard users'),\n focusTrap: FocusTrapConfigSchema.optional().describe('Focus trap settings'),\n arrowNavigation: z.boolean().default(false)\n .describe('Enable arrow key navigation between focusable items'),\n}).describe('Focus and tab navigation management');\n\nexport type FocusManagement = z.infer;\n\n/**\n * Keyboard Navigation Configuration Schema\n * Top-level keyboard navigation and shortcut configuration.\n */\nexport const KeyboardNavigationConfigSchema = z.object({\n shortcuts: z.array(KeyboardShortcutSchema).optional().describe('Registered keyboard shortcuts'),\n focusManagement: FocusManagementSchema.optional().describe('Focus and tab order management'),\n rovingTabindex: z.boolean().default(false)\n .describe('Enable roving tabindex pattern for composite widgets'),\n}).merge(AriaPropsSchema.partial()).describe('Keyboard navigation and shortcut configuration');\n\nexport type KeyboardNavigationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { TouchTargetConfigSchema } from './touch.zod';\nimport { FocusManagementSchema } from './keyboard.zod';\n\n/**\n * Color Palette Schema\n * Defines brand colors and their variants.\n */\nexport const ColorPaletteSchema = z.object({\n primary: z.string().describe('Primary brand color (hex, rgb, or hsl)'),\n secondary: z.string().optional().describe('Secondary brand color'),\n accent: z.string().optional().describe('Accent color for highlights'),\n success: z.string().optional().describe('Success state color (default: green)'),\n warning: z.string().optional().describe('Warning state color (default: yellow)'),\n error: z.string().optional().describe('Error state color (default: red)'),\n info: z.string().optional().describe('Info state color (default: blue)'),\n \n // Neutral colors\n background: z.string().optional().describe('Background color'),\n surface: z.string().optional().describe('Surface/card background color'),\n text: z.string().optional().describe('Primary text color'),\n textSecondary: z.string().optional().describe('Secondary text color'),\n border: z.string().optional().describe('Border color'),\n disabled: z.string().optional().describe('Disabled state color'),\n \n // Color variants (shades)\n primaryLight: z.string().optional().describe('Lighter shade of primary'),\n primaryDark: z.string().optional().describe('Darker shade of primary'),\n secondaryLight: z.string().optional().describe('Lighter shade of secondary'),\n secondaryDark: z.string().optional().describe('Darker shade of secondary'),\n});\n\n/**\n * Typography Settings Schema\n * Font families, sizes, weights, and line heights.\n */\nexport const TypographySchema = z.object({\n fontFamily: z.object({\n base: z.string().optional().describe('Base font family (default: system fonts)'),\n heading: z.string().optional().describe('Heading font family'),\n mono: z.string().optional().describe('Monospace font family for code'),\n }).optional(),\n \n fontSize: z.object({\n xs: z.string().optional().describe('Extra small font size (e.g., 0.75rem)'),\n sm: z.string().optional().describe('Small font size (e.g., 0.875rem)'),\n base: z.string().optional().describe('Base font size (e.g., 1rem)'),\n lg: z.string().optional().describe('Large font size (e.g., 1.125rem)'),\n xl: z.string().optional().describe('Extra large font size (e.g., 1.25rem)'),\n '2xl': z.string().optional().describe('2X large font size (e.g., 1.5rem)'),\n '3xl': z.string().optional().describe('3X large font size (e.g., 1.875rem)'),\n '4xl': z.string().optional().describe('4X large font size (e.g., 2.25rem)'),\n }).optional(),\n \n fontWeight: z.object({\n light: z.number().optional().describe('Light weight (default: 300)'),\n normal: z.number().optional().describe('Normal weight (default: 400)'),\n medium: z.number().optional().describe('Medium weight (default: 500)'),\n semibold: z.number().optional().describe('Semibold weight (default: 600)'),\n bold: z.number().optional().describe('Bold weight (default: 700)'),\n }).optional(),\n \n lineHeight: z.object({\n tight: z.string().optional().describe('Tight line height (e.g., 1.25)'),\n normal: z.string().optional().describe('Normal line height (e.g., 1.5)'),\n relaxed: z.string().optional().describe('Relaxed line height (e.g., 1.75)'),\n loose: z.string().optional().describe('Loose line height (e.g., 2)'),\n }).optional(),\n \n letterSpacing: z.object({\n tighter: z.string().optional().describe('Tighter letter spacing (e.g., -0.05em)'),\n tight: z.string().optional().describe('Tight letter spacing (e.g., -0.025em)'),\n normal: z.string().optional().describe('Normal letter spacing (e.g., 0)'),\n wide: z.string().optional().describe('Wide letter spacing (e.g., 0.025em)'),\n wider: z.string().optional().describe('Wider letter spacing (e.g., 0.05em)'),\n }).optional(),\n});\n\n/**\n * Spacing Units Schema\n * Defines spacing scale for margins, padding, gaps.\n */\nexport const SpacingSchema = z.object({\n '0': z.string().optional().describe('0 spacing (0)'),\n '1': z.string().optional().describe('Spacing unit 1 (e.g., 0.25rem)'),\n '2': z.string().optional().describe('Spacing unit 2 (e.g., 0.5rem)'),\n '3': z.string().optional().describe('Spacing unit 3 (e.g., 0.75rem)'),\n '4': z.string().optional().describe('Spacing unit 4 (e.g., 1rem)'),\n '5': z.string().optional().describe('Spacing unit 5 (e.g., 1.25rem)'),\n '6': z.string().optional().describe('Spacing unit 6 (e.g., 1.5rem)'),\n '8': z.string().optional().describe('Spacing unit 8 (e.g., 2rem)'),\n '10': z.string().optional().describe('Spacing unit 10 (e.g., 2.5rem)'),\n '12': z.string().optional().describe('Spacing unit 12 (e.g., 3rem)'),\n '16': z.string().optional().describe('Spacing unit 16 (e.g., 4rem)'),\n '20': z.string().optional().describe('Spacing unit 20 (e.g., 5rem)'),\n '24': z.string().optional().describe('Spacing unit 24 (e.g., 6rem)'),\n});\n\n/**\n * Border Radius Schema\n * Rounded corners configuration.\n */\nexport const BorderRadiusSchema = z.object({\n none: z.string().optional().describe('No border radius (0)'),\n sm: z.string().optional().describe('Small border radius (e.g., 0.125rem)'),\n base: z.string().optional().describe('Base border radius (e.g., 0.25rem)'),\n md: z.string().optional().describe('Medium border radius (e.g., 0.375rem)'),\n lg: z.string().optional().describe('Large border radius (e.g., 0.5rem)'),\n xl: z.string().optional().describe('Extra large border radius (e.g., 0.75rem)'),\n '2xl': z.string().optional().describe('2X large border radius (e.g., 1rem)'),\n full: z.string().optional().describe('Full border radius (50%)'),\n});\n\n/**\n * Shadow Schema\n * Box shadow effects.\n */\nexport const ShadowSchema = z.object({\n none: z.string().optional().describe('No shadow'),\n sm: z.string().optional().describe('Small shadow'),\n base: z.string().optional().describe('Base shadow'),\n md: z.string().optional().describe('Medium shadow'),\n lg: z.string().optional().describe('Large shadow'),\n xl: z.string().optional().describe('Extra large shadow'),\n '2xl': z.string().optional().describe('2X large shadow'),\n inner: z.string().optional().describe('Inner shadow (inset)'),\n});\n\n/**\n * Breakpoints Schema\n * Responsive design breakpoints.\n */\nexport const BreakpointsSchema = z.object({\n xs: z.string().optional().describe('Extra small breakpoint (e.g., 480px)'),\n sm: z.string().optional().describe('Small breakpoint (e.g., 640px)'),\n md: z.string().optional().describe('Medium breakpoint (e.g., 768px)'),\n lg: z.string().optional().describe('Large breakpoint (e.g., 1024px)'),\n xl: z.string().optional().describe('Extra large breakpoint (e.g., 1280px)'),\n '2xl': z.string().optional().describe('2X large breakpoint (e.g., 1536px)'),\n});\n\n/**\n * Animation Schema\n * Animation timing and duration settings.\n */\nexport const AnimationSchema = z.object({\n duration: z.object({\n fast: z.string().optional().describe('Fast animation (e.g., 150ms)'),\n base: z.string().optional().describe('Base animation (e.g., 300ms)'),\n slow: z.string().optional().describe('Slow animation (e.g., 500ms)'),\n }).optional(),\n \n timing: z.object({\n linear: z.string().optional().describe('Linear timing function'),\n ease: z.string().optional().describe('Ease timing function'),\n ease_in: z.string().optional().describe('Ease-in timing function'),\n ease_out: z.string().optional().describe('Ease-out timing function'),\n ease_in_out: z.string().optional().describe('Ease-in-out timing function'),\n }).optional(),\n});\n\n/**\n * Z-Index Scale Schema\n * Layering and stacking order.\n */\nexport const ZIndexSchema = z.object({\n base: z.number().optional().describe('Base z-index (e.g., 0)'),\n dropdown: z.number().optional().describe('Dropdown z-index (e.g., 1000)'),\n sticky: z.number().optional().describe('Sticky z-index (e.g., 1020)'),\n fixed: z.number().optional().describe('Fixed z-index (e.g., 1030)'),\n modalBackdrop: z.number().optional().describe('Modal backdrop z-index (e.g., 1040)'),\n modal: z.number().optional().describe('Modal z-index (e.g., 1050)'),\n popover: z.number().optional().describe('Popover z-index (e.g., 1060)'),\n tooltip: z.number().optional().describe('Tooltip z-index (e.g., 1070)'),\n});\n\n/**\n * Theme Mode Schema\n */\nexport const ThemeModeSchema = z.enum(['light', 'dark', 'auto']);\n\n/** @deprecated Use ThemeModeSchema instead */\nexport const ThemeMode = ThemeModeSchema;\n\n/**\n * Density Mode Schema\n * Controls spacing and sizing for different use cases.\n */\nexport const DensityModeSchema = z.enum(['compact', 'regular', 'spacious']);\n\n/** @deprecated Use DensityModeSchema instead */\nexport const DensityMode = DensityModeSchema;\n\n/**\n * WCAG Contrast Level Schema\n * Web Content Accessibility Guidelines color contrast requirements.\n */\nexport const WcagContrastLevelSchema = z.enum(['AA', 'AAA']);\n\n/** @deprecated Use WcagContrastLevelSchema instead */\nexport const WcagContrastLevel = WcagContrastLevelSchema;\n\n/**\n * Theme Configuration Schema\n * Complete theme definition for brand customization.\n */\nexport const ThemeSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Unique theme identifier (snake_case)'),\n label: z.string().describe('Human-readable theme name'),\n description: z.string().optional().describe('Theme description'),\n \n /** Theme mode */\n mode: ThemeModeSchema.default('light').describe('Theme mode (light, dark, or auto)'),\n \n /** Color system */\n colors: ColorPaletteSchema.describe('Color palette configuration'),\n \n /** Typography */\n typography: TypographySchema.optional().describe('Typography settings'),\n \n /** Spacing */\n spacing: SpacingSchema.optional().describe('Spacing scale'),\n \n /** Border radius */\n borderRadius: BorderRadiusSchema.optional().describe('Border radius scale'),\n \n /** Shadows */\n shadows: ShadowSchema.optional().describe('Box shadow effects'),\n \n /** Breakpoints */\n breakpoints: BreakpointsSchema.optional().describe('Responsive breakpoints'),\n \n /** Animation */\n animation: AnimationSchema.optional().describe('Animation settings'),\n \n /** Z-Index */\n zIndex: ZIndexSchema.optional().describe('Z-index scale for layering'),\n \n /** Custom CSS variables */\n customVars: z.record(z.string(), z.string()).optional().describe('Custom CSS variables (key-value pairs)'),\n \n /** Logo */\n logo: z.object({\n light: z.string().optional().describe('Logo URL for light mode'),\n dark: z.string().optional().describe('Logo URL for dark mode'),\n favicon: z.string().optional().describe('Favicon URL'),\n }).optional().describe('Logo assets'),\n \n /** Extends another theme */\n extends: z.string().optional().describe('Base theme to extend from'),\n\n /** Display density mode */\n density: DensityModeSchema.optional().describe('Display density: compact, regular, or spacious'),\n\n /** WCAG contrast level requirement */\n wcagContrast: WcagContrastLevelSchema.optional().describe('WCAG color contrast level (AA or AAA)'),\n\n /** Right-to-left language support */\n rtl: z.boolean().optional().describe('Enable right-to-left layout direction'),\n\n /** Touch target accessibility configuration */\n touchTarget: TouchTargetConfigSchema.optional().describe('Touch target sizing defaults'),\n\n /** Keyboard navigation and focus management */\n keyboardNavigation: FocusManagementSchema.optional().describe('Keyboard focus management settings'),\n});\n\nexport type Theme = z.infer;\nexport type ColorPalette = z.infer;\nexport type Typography = z.infer;\nexport type Spacing = z.infer;\nexport type BorderRadius = z.infer;\nexport type Shadow = z.infer;\nexport type Breakpoints = z.infer;\nexport type Animation = z.infer;\nexport type ZIndex = z.infer;\nexport type ThemeMode = z.infer;\nexport type DensityMode = z.infer;\nexport type WcagContrastLevel = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema } from './i18n.zod';\n\n/**\n * Offline Strategy Schema\n * Determines how data is fetched when connectivity is limited.\n */\nexport const OfflineStrategySchema = z.enum([\n 'cache_first',\n 'network_first',\n 'stale_while_revalidate',\n 'network_only',\n 'cache_only',\n]).describe('Data fetching strategy for offline/online transitions');\n\nexport type OfflineStrategy = z.infer;\n\n/**\n * Conflict Resolution Strategy Enum\n */\nexport const ConflictResolutionSchema = z.enum([\n 'client_wins',\n 'server_wins',\n 'manual',\n 'last_write_wins',\n]).describe('How to resolve conflicts when syncing offline changes');\n\nexport type ConflictResolution = z.infer;\n\n/**\n * Sync Configuration Schema\n * Controls how offline mutations are synchronized with the server.\n */\nexport const SyncConfigSchema = z.object({\n strategy: OfflineStrategySchema.default('network_first').describe('Sync fetch strategy'),\n conflictResolution: ConflictResolutionSchema.default('last_write_wins').describe('Conflict resolution policy'),\n retryInterval: z.number().optional().describe('Retry interval in milliseconds between sync attempts'),\n maxRetries: z.number().optional().describe('Maximum number of sync retry attempts'),\n batchSize: z.number().optional().describe('Number of mutations to sync per batch'),\n}).describe('Offline-to-online synchronization configuration');\n\nexport type SyncConfig = z.infer;\n\n/**\n * Persist Storage Backend Enum\n */\nexport const PersistStorageSchema = z.enum([\n 'indexeddb',\n 'localstorage',\n 'sqlite',\n]).describe('Client-side storage backend for offline cache');\n\nexport type PersistStorage = z.infer;\n\n/**\n * Eviction Policy Enum\n */\nexport const EvictionPolicySchema = z.enum([\n 'lru',\n 'lfu',\n 'fifo',\n]).describe('Cache eviction policy');\n\nexport type EvictionPolicy = z.infer;\n\n/**\n * Offline Cache Configuration Schema\n * Controls how data is persisted on the client for offline access.\n */\nexport const OfflineCacheConfigSchema = z.object({\n maxSize: z.number().optional().describe('Maximum cache size in bytes'),\n ttl: z.number().optional().describe('Time-to-live for cached entries in milliseconds'),\n persistStorage: PersistStorageSchema.default('indexeddb').describe('Storage backend'),\n evictionPolicy: EvictionPolicySchema.default('lru').describe('Cache eviction policy when full'),\n}).describe('Client-side offline cache configuration');\n\nexport type OfflineCacheConfig = z.infer;\n\n/**\n * Offline Configuration Schema\n * Top-level offline support configuration for an application or component.\n */\nexport const OfflineConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable offline support'),\n strategy: OfflineStrategySchema.default('network_first').describe('Default offline fetch strategy'),\n cache: OfflineCacheConfigSchema.optional().describe('Cache settings for offline data'),\n sync: SyncConfigSchema.optional().describe('Sync settings for offline mutations'),\n offlineIndicator: z.boolean().default(true).describe('Show a visual indicator when offline'),\n offlineMessage: I18nLabelSchema.optional().describe('Customizable offline status message shown to users'),\n queueMaxSize: z.number().optional().describe('Maximum number of queued offline mutations'),\n}).describe('Offline support configuration');\n\nexport type OfflineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Transition Preset Schema\n * Common animation transition presets.\n */\nexport const TransitionPresetSchema = z.enum([\n 'fade',\n 'slide_up',\n 'slide_down',\n 'slide_left',\n 'slide_right',\n 'scale',\n 'rotate',\n 'flip',\n 'none',\n]).describe('Transition preset type');\n\nexport type TransitionPreset = z.infer;\n\n/**\n * Easing Function Schema\n * Supported animation easing/timing functions.\n */\nexport const EasingFunctionSchema = z.enum([\n 'linear',\n 'ease',\n 'ease_in',\n 'ease_out',\n 'ease_in_out',\n 'spring',\n]).describe('Animation easing function');\n\nexport type EasingFunction = z.infer;\n\n/**\n * Transition Configuration Schema\n * Defines a single animation transition with timing and easing options.\n */\nexport const TransitionConfigSchema = z.object({\n preset: TransitionPresetSchema.optional().describe('Transition preset to apply'),\n duration: z.number().optional().describe('Transition duration in milliseconds'),\n easing: EasingFunctionSchema.optional().describe('Easing function for the transition'),\n delay: z.number().optional().describe('Delay before transition starts in milliseconds'),\n customKeyframes: z.string().optional().describe('CSS @keyframes name for custom animations'),\n themeToken: z.string().optional().describe('Reference to a theme animation token (e.g. \"animation.duration.fast\")'),\n}).describe('Animation transition configuration');\n\nexport type TransitionConfig = z.infer;\n\n/**\n * Animation Trigger Schema\n * Events that can trigger an animation.\n */\nexport const AnimationTriggerSchema = z.enum([\n 'on_mount',\n 'on_unmount',\n 'on_hover',\n 'on_focus',\n 'on_click',\n 'on_scroll',\n 'on_visible',\n]).describe('Event that triggers the animation');\n\nexport type AnimationTrigger = z.infer;\n\n/**\n * Component Animation Schema\n * Animation configuration for an individual UI component.\n */\nexport const ComponentAnimationSchema = z.object({\n label: I18nLabelSchema.optional().describe('Descriptive label for this animation configuration'),\n enter: TransitionConfigSchema.optional().describe('Enter/mount animation'),\n exit: TransitionConfigSchema.optional().describe('Exit/unmount animation'),\n hover: TransitionConfigSchema.optional().describe('Hover state animation'),\n trigger: AnimationTriggerSchema.optional().describe('When to trigger the animation'),\n reducedMotion: z.enum(['respect', 'disable', 'alternative']).default('respect')\n .describe('Accessibility: how to handle prefers-reduced-motion'),\n}).merge(AriaPropsSchema.partial()).describe('Component-level animation configuration');\n\nexport type ComponentAnimation = z.infer;\n\n/**\n * Page Transition Schema\n * Defines the animation used when navigating between pages.\n */\nexport const PageTransitionSchema = z.object({\n type: TransitionPresetSchema.default('fade').describe('Page transition type'),\n duration: z.number().default(300).describe('Transition duration in milliseconds'),\n easing: EasingFunctionSchema.default('ease_in_out').describe('Easing function for the transition'),\n crossFade: z.boolean().default(false).describe('Whether to cross-fade between pages'),\n}).describe('Page-level transition configuration');\n\nexport type PageTransition = z.infer;\n\n/**\n * Motion Configuration Schema\n * Top-level animation and motion design configuration.\n */\nexport const MotionConfigSchema = z.object({\n label: I18nLabelSchema.optional().describe('Descriptive label for the motion configuration'),\n defaultTransition: TransitionConfigSchema.optional().describe('Default transition applied to all animations'),\n pageTransitions: PageTransitionSchema.optional().describe('Page navigation transition settings'),\n componentAnimations: z.record(z.string(), ComponentAnimationSchema).optional()\n .describe('Component name to animation configuration mapping'),\n reducedMotion: z.boolean().default(false).describe('When true, respect prefers-reduced-motion and suppress animations globally'),\n enabled: z.boolean().default(true).describe('Enable or disable all animations globally'),\n}).describe('Top-level motion and animation design configuration');\n\nexport type MotionConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Notification Type Schema\n * Defines the visual presentation style of the notification.\n */\nexport const NotificationTypeSchema = z.enum([\n 'toast',\n 'snackbar',\n 'banner',\n 'alert',\n 'inline',\n]).describe('Notification presentation style');\n\nexport type NotificationType = z.infer;\n\n/**\n * Notification Severity Schema\n * Indicates the urgency and visual treatment of the notification.\n */\nexport const NotificationSeveritySchema = z.enum([\n 'info',\n 'success',\n 'warning',\n 'error',\n]).describe('Notification severity level');\n\nexport type NotificationSeverity = z.infer;\n\n/**\n * Notification Position Schema\n * Screen position for rendering notifications.\n */\nexport const NotificationPositionSchema = z.enum([\n 'top_left',\n 'top_center',\n 'top_right',\n 'bottom_left',\n 'bottom_center',\n 'bottom_right',\n]).describe('Screen position for notification placement');\n\nexport type NotificationPosition = z.infer;\n\n/**\n * Notification Action Schema\n * Defines an interactive action button within a notification.\n */\nexport const NotificationActionSchema = z.object({\n label: I18nLabelSchema.describe('Action button label'),\n action: z.string().describe('Action identifier to execute'),\n variant: z.enum(['primary', 'secondary', 'link']).default('primary')\n .describe('Button variant style'),\n}).describe('Notification action button');\n\nexport type NotificationAction = z.infer;\n\n/**\n * Notification Schema\n * Defines a single notification instance with content, behavior, and positioning.\n */\nexport const NotificationSchema = z.object({\n type: NotificationTypeSchema.default('toast').describe('Notification presentation style'),\n severity: NotificationSeveritySchema.default('info').describe('Notification severity level'),\n title: I18nLabelSchema.optional().describe('Notification title'),\n message: I18nLabelSchema.describe('Notification message body'),\n icon: z.string().optional().describe('Icon name override'),\n duration: z.number().optional().describe('Auto-dismiss duration in ms, omit for persistent'),\n dismissible: z.boolean().default(true).describe('Allow user to dismiss the notification'),\n actions: z.array(NotificationActionSchema).optional().describe('Action buttons'),\n position: NotificationPositionSchema.optional().describe('Override default position'),\n}).merge(AriaPropsSchema.partial()).describe('Notification instance definition');\n\nexport type Notification = z.infer;\n\n/**\n * Notification Config Schema\n * Top-level notification system configuration.\n */\nexport const NotificationConfigSchema = z.object({\n defaultPosition: NotificationPositionSchema.default('top_right')\n .describe('Default screen position for notifications'),\n defaultDuration: z.number().default(5000)\n .describe('Default auto-dismiss duration in ms'),\n maxVisible: z.number().default(5)\n .describe('Maximum number of notifications visible at once'),\n stackDirection: z.enum(['up', 'down']).default('down')\n .describe('Stack direction for multiple notifications'),\n pauseOnHover: z.boolean().default(true)\n .describe('Pause auto-dismiss timer on hover'),\n}).describe('Global notification system configuration');\n\nexport type NotificationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Drag Handle Schema\n * Defines how a drag interaction is initiated on an element.\n */\nexport const DragHandleSchema = z.enum([\n 'element',\n 'handle',\n 'grip_icon',\n]).describe('Drag initiation method');\n\nexport type DragHandle = z.infer;\n\n/**\n * Drop Effect Schema\n * Visual feedback indicating the result of a drop operation.\n */\nexport const DropEffectSchema = z.enum([\n 'move',\n 'copy',\n 'link',\n 'none',\n]).describe('Drop operation effect');\n\nexport type DropEffect = z.infer;\n\n/**\n * Drag Constraint Schema\n * Constrains drag movement along axes, within bounds, or to a grid.\n */\nexport const DragConstraintSchema = z.object({\n axis: z.enum(['x', 'y', 'both']).default('both').describe('Constrain drag axis'),\n bounds: z.enum(['parent', 'viewport', 'none']).default('none').describe('Constrain within bounds'),\n grid: z.tuple([z.number(), z.number()]).optional().describe('Snap to grid [x, y] in pixels'),\n}).describe('Drag movement constraints');\n\nexport type DragConstraint = z.infer;\n\n/**\n * Drop Zone Schema\n * Configures a container that accepts dragged items.\n */\nexport const DropZoneSchema = z.object({\n label: I18nLabelSchema.optional().describe('Accessible label for the drop zone'),\n accept: z.array(z.string()).describe('Accepted drag item types'),\n maxItems: z.number().optional().describe('Maximum items allowed in drop zone'),\n highlightOnDragOver: z.boolean().default(true).describe('Highlight drop zone when dragging over'),\n dropEffect: DropEffectSchema.default('move').describe('Visual effect on drop'),\n}).merge(AriaPropsSchema.partial()).describe('Drop zone configuration');\n\nexport type DropZone = z.infer;\n\n/**\n * Drag Item Schema\n * Configures a draggable element including handle, constraints, and preview.\n */\nexport const DragItemSchema = z.object({\n type: z.string().describe('Drag item type identifier for matching with drop zones'),\n label: I18nLabelSchema.optional().describe('Accessible label describing the draggable item'),\n handle: DragHandleSchema.default('element').describe('How to initiate drag'),\n constraint: DragConstraintSchema.optional().describe('Drag movement constraints'),\n preview: z.enum(['element', 'custom', 'none']).default('element').describe('Drag preview type'),\n disabled: z.boolean().default(false).describe('Disable dragging'),\n}).merge(AriaPropsSchema.partial()).describe('Draggable item configuration');\n\nexport type DragItem = z.infer;\n\n/**\n * Drag and Drop Configuration Schema\n * Top-level drag-and-drop interaction configuration for a component.\n */\nexport const DndConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable drag and drop'),\n dragItem: DragItemSchema.optional().describe('Configuration for draggable item'),\n dropZone: DropZoneSchema.optional().describe('Configuration for drop target'),\n sortable: z.boolean().default(false).describe('Enable sortable list behavior'),\n autoScroll: z.boolean().default(true).describe('Auto-scroll during drag near edges'),\n touchDelay: z.number().default(200).describe('Delay in ms before drag starts on touch devices'),\n}).describe('Drag and drop interaction configuration');\n\nexport type DndConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * System Protocol Exports\n * \n * Runtime Services & Infrastructure Configuration\n * - Infrastructure: Cache, Queue, Storage, Search, HTTP\n * - Observability: Audit, Logging, Metrics, Tracing, Change Management\n * - Security: Compliance, Encryption, Masking, Auth Config\n * - Services: Job, Worker, Notification, Translation\n */\n\n// Infrastructure Services\nexport * from './cache.zod';\nexport * from './disaster-recovery.zod';\nexport * from './message-queue.zod';\nexport * from './object-storage.zod';\nexport * from './search-engine.zod';\nexport * from './http-server.zod';\n\n// Observability & Operations\nexport * from './audit.zod';\nexport * from './logging.zod';\nexport * from './metrics.zod';\nexport * from './tracing.zod';\nexport * from './change-management.zod';\nexport * from './migration.zod';\n\n// Security & Compliance\nexport * from './auth-config.zod';\nexport * from './compliance.zod';\nexport * from './encryption.zod';\nexport * from './masking.zod';\nexport * from './security-context.zod';\nexport * from './incident-response.zod';\nexport * from './supplier-security.zod';\nexport * from './training.zod';\n\n// Runtime Services\nexport * from './job.zod';\nexport * from './worker.zod';\nexport * from './notification.zod';\nexport * from './translation.zod';\nexport * from './translation-typegen';\nexport * from './translation-skeleton';\nexport * from './collaboration.zod';\nexport * from './metadata-persistence.zod';\nexport * from './core-services.zod';\n\n// Multi-Tenant & Licensing\nexport * from './tenant.zod';\nexport * from './license.zod';\nexport * from './registry-config.zod';\n\n// Provisioning & Deployment\nexport * from './provisioning.zod';\nexport * from './deploy-bundle.zod';\nexport * from './app-install.zod';\n\n// Constants\nexport * from './constants';\n\n// Types\nexport * from './types';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Application-Level Cache Protocol\n * \n * Multi-tier caching strategy for application data.\n * Supports Memory, Redis, Memcached, and CDN.\n * \n * ## Caching in ObjectStack\n * \n * **Application Cache (`system/cache.zod.ts`) - This File**\n * - **Purpose**: Cache computed data, query results, aggregations\n * - **Technologies**: Redis, Memcached, in-memory LRU\n * - **Configuration**: TTL, eviction policies, cache warming\n * - **Use case**: Cache expensive database queries, computed values\n * - **Scope**: Application layer, server-side data storage\n * \n * **HTTP Cache (`api/http-cache.zod.ts`)**\n * - **Purpose**: Cache API responses at HTTP protocol level\n * - **Technologies**: HTTP headers (ETag, Last-Modified, Cache-Control), CDN\n * - **Configuration**: Cache-Control headers, validation tokens\n * - **Use case**: Reduce API response time for repeated metadata requests\n * - **Scope**: HTTP layer, client-server communication\n * \n * @see ../../api/http-cache.zod.ts for HTTP-level caching\n */\nexport const CacheStrategySchema = z.enum([\n 'lru', // Least Recently Used\n 'lfu', // Least Frequently Used\n 'fifo', // First In First Out\n 'ttl', // Time To Live only\n 'adaptive', // Dynamic strategy selection\n]).describe('Cache eviction strategy');\n\nexport type CacheStrategy = z.infer;\n\nexport const CacheTierSchema = z.object({\n name: z.string().describe('Unique cache tier name'),\n type: z.enum(['memory', 'redis', 'memcached', 'cdn']).describe('Cache backend type'),\n maxSize: z.number().optional().describe('Max size in MB'),\n ttl: z.number().default(300).describe('Default TTL in seconds'),\n strategy: CacheStrategySchema.default('lru').describe('Eviction strategy'),\n warmup: z.boolean().default(false).describe('Pre-populate cache on startup'),\n}).describe('Configuration for a single cache tier in the hierarchy');\n\nexport type CacheTier = z.infer;\nexport type CacheTierInput = z.input;\n\nexport const CacheInvalidationSchema = z.object({\n trigger: z.enum(['create', 'update', 'delete', 'manual']).describe('Event that triggers invalidation'),\n scope: z.enum(['key', 'pattern', 'tag', 'all']).describe('Invalidation scope'),\n pattern: z.string().optional().describe('Key pattern for pattern-based invalidation'),\n tags: z.array(z.string()).optional().describe('Cache tags to invalidate'),\n}).describe('Rule defining when and how cached entries are invalidated');\n\nexport type CacheInvalidation = z.infer;\n\nexport const CacheConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable application-level caching'),\n tiers: z.array(CacheTierSchema).describe('Ordered cache tier hierarchy'),\n invalidation: z.array(CacheInvalidationSchema).describe('Cache invalidation rules'),\n prefetch: z.boolean().default(false).describe('Enable cache prefetching'),\n compression: z.boolean().default(false).describe('Enable data compression in cache'),\n encryption: z.boolean().default(false).describe('Enable encryption for cached data'),\n}).describe('Top-level application cache configuration');\n\nexport type CacheConfig = z.infer;\nexport type CacheConfigInput = z.input;\n\n/**\n * Distributed Cache Consistency Schema\n *\n * Defines write strategies for distributed cache consistency.\n *\n * - **write_through**: Write to cache and backend simultaneously\n * - **write_behind**: Write to cache first, async persist to backend\n * - **write_around**: Write to backend only, cache on next read\n * - **refresh_ahead**: Proactively refresh expiring entries before TTL\n */\nexport const CacheConsistencySchema = z.enum([\n 'write_through',\n 'write_behind',\n 'write_around',\n 'refresh_ahead',\n]).describe('Distributed cache write consistency strategy');\n\nexport type CacheConsistency = z.infer;\n\n/**\n * Cache Avalanche Prevention Schema\n *\n * Strategies to prevent cache stampede/avalanche when many keys expire simultaneously.\n *\n * @example\n * ```typescript\n * const prevention: CacheAvalanchePrevention = {\n * jitterTtl: { enabled: true, maxJitterSeconds: 60 },\n * circuitBreaker: { enabled: true, failureThreshold: 5, resetTimeout: 30 },\n * lockout: { enabled: true, lockTimeoutMs: 5000 },\n * };\n * ```\n */\nexport const CacheAvalanchePreventionSchema = z.object({\n /** TTL jitter to stagger cache expiration */\n jitterTtl: z.object({\n enabled: z.boolean().default(false).describe('Add random jitter to TTL values'),\n maxJitterSeconds: z.number().default(60).describe('Maximum jitter added to TTL in seconds'),\n }).optional().describe('TTL jitter to prevent simultaneous expiration'),\n\n /** Circuit breaker to protect backend under cache pressure */\n circuitBreaker: z.object({\n enabled: z.boolean().default(false).describe('Enable circuit breaker for backend protection'),\n failureThreshold: z.number().default(5).describe('Failures before circuit opens'),\n resetTimeout: z.number().default(30).describe('Seconds before half-open state'),\n }).optional().describe('Circuit breaker for backend protection'),\n\n /** Cache lock to prevent thundering herd on key miss */\n lockout: z.object({\n enabled: z.boolean().default(false).describe('Enable cache locking for key regeneration'),\n lockTimeoutMs: z.number().default(5000).describe('Maximum lock wait time in milliseconds'),\n }).optional().describe('Lock-based stampede prevention'),\n}).describe('Cache avalanche/stampede prevention configuration');\n\nexport type CacheAvalanchePrevention = z.infer;\n\n/**\n * Cache Warmup Strategy Schema\n *\n * Defines how cache is pre-populated on startup or after cache flush.\n */\nexport const CacheWarmupSchema = z.object({\n /** Enable cache warming */\n enabled: z.boolean().default(false).describe('Enable cache warmup'),\n /** Warmup strategy */\n strategy: z.enum(['eager', 'lazy', 'scheduled']).default('lazy')\n .describe('Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)'),\n /** Cron schedule for scheduled warmup */\n schedule: z.string().optional().describe('Cron expression for scheduled warmup'),\n /** Keys/patterns to warm up */\n patterns: z.array(z.string()).optional().describe('Key patterns to warm up (e.g., \"user:*\", \"config:*\")'),\n /** Maximum concurrent warmup operations */\n concurrency: z.number().default(10).describe('Maximum concurrent warmup operations'),\n}).describe('Cache warmup strategy');\n\nexport type CacheWarmup = z.infer;\n\n/**\n * Distributed Cache Configuration Schema\n *\n * Extended cache configuration for distributed multi-node deployments.\n * Adds consistency strategies, avalanche prevention, and warmup policies.\n *\n * @example\n * ```typescript\n * const distributedCache: DistributedCacheConfig = {\n * enabled: true,\n * tiers: [\n * { name: 'l1', type: 'memory', maxSize: 100, ttl: 60, strategy: 'lru' },\n * { name: 'l2', type: 'redis', maxSize: 1000, ttl: 300, strategy: 'lru' },\n * ],\n * invalidation: [\n * { trigger: 'update', scope: 'key' },\n * ],\n * consistency: 'write_through',\n * avalanchePrevention: {\n * jitterTtl: { enabled: true, maxJitterSeconds: 30 },\n * circuitBreaker: { enabled: true, failureThreshold: 5 },\n * },\n * warmup: { enabled: true, strategy: 'eager', patterns: ['config:*'] },\n * };\n * ```\n */\nexport const DistributedCacheConfigSchema = CacheConfigSchema.extend({\n /** Distributed write consistency strategy */\n consistency: CacheConsistencySchema.optional().describe('Distributed cache consistency strategy'),\n /** Avalanche/stampede prevention settings */\n avalanchePrevention: CacheAvalanchePreventionSchema.optional()\n .describe('Cache avalanche and stampede prevention'),\n /** Cache warmup configuration */\n warmup: CacheWarmupSchema.optional().describe('Cache warmup strategy'),\n}).describe('Distributed cache configuration with consistency and avalanche prevention');\n\nexport type DistributedCacheConfig = z.infer;\nexport type DistributedCacheConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Backup Strategy Schema\n *\n * Defines backup methods for disaster recovery.\n *\n * - **full**: Complete snapshot of all data\n * - **incremental**: Only changes since last backup\n * - **differential**: All changes since last full backup\n *\n * @example\n * ```typescript\n * const backup: BackupConfig = {\n * strategy: 'incremental',\n * schedule: '0 2 * * *',\n * retention: { days: 30, minCopies: 3 },\n * encryption: { enabled: true, algorithm: 'AES-256-GCM' },\n * };\n * ```\n */\nexport const BackupStrategySchema = z.enum([\n 'full',\n 'incremental',\n 'differential',\n]).describe('Backup strategy type');\n\nexport type BackupStrategy = z.infer;\n\n/**\n * Backup Retention Policy Schema\n */\nexport const BackupRetentionSchema = z.object({\n /** Number of days to retain backups */\n days: z.number().min(1).describe('Retention period in days'),\n /** Minimum number of backup copies to keep regardless of age */\n minCopies: z.number().min(1).default(3).describe('Minimum backup copies to retain'),\n /** Maximum number of backup copies */\n maxCopies: z.number().optional().describe('Maximum backup copies to store'),\n}).describe('Backup retention policy');\n\nexport type BackupRetention = z.infer;\n\n/**\n * Backup Configuration Schema\n */\nexport const BackupConfigSchema = z.object({\n /** Backup strategy */\n strategy: BackupStrategySchema.default('incremental').describe('Backup strategy'),\n /** Cron schedule for automated backups */\n schedule: z.string().optional().describe('Cron expression for backup schedule (e.g., \"0 2 * * *\")'),\n /** Retention policy */\n retention: BackupRetentionSchema.describe('Backup retention policy'),\n /** Storage destination */\n destination: z.object({\n type: z.enum(['s3', 'gcs', 'azure_blob', 'local']).describe('Storage backend type'),\n bucket: z.string().optional().describe('Cloud storage bucket/container name'),\n path: z.string().optional().describe('Storage path prefix'),\n region: z.string().optional().describe('Cloud storage region'),\n }).describe('Backup storage destination'),\n /** Encryption settings */\n encryption: z.object({\n enabled: z.boolean().default(true).describe('Enable backup encryption'),\n algorithm: z.enum(['AES-256-GCM', 'AES-256-CBC', 'ChaCha20-Poly1305']).default('AES-256-GCM')\n .describe('Encryption algorithm'),\n keyId: z.string().optional().describe('KMS key ID for encryption'),\n }).optional().describe('Backup encryption settings'),\n /** Compression settings */\n compression: z.object({\n enabled: z.boolean().default(true).describe('Enable backup compression'),\n algorithm: z.enum(['gzip', 'zstd', 'lz4', 'snappy']).default('zstd').describe('Compression algorithm'),\n }).optional().describe('Backup compression settings'),\n /** Verify backup integrity after creation */\n verifyAfterBackup: z.boolean().default(true).describe('Verify backup integrity after creation'),\n}).describe('Backup configuration');\n\nexport type BackupConfig = z.infer;\nexport type BackupConfigInput = z.input;\n\n/**\n * Failover Mode Schema\n *\n * Defines how traffic is routed between primary and secondary systems.\n *\n * - **active_passive**: Secondary is standby, activated on primary failure\n * - **active_active**: Both primary and secondary handle traffic\n * - **pilot_light**: Minimal secondary with quick scale-up capability\n * - **warm_standby**: Reduced-capacity secondary, faster failover than pilot light\n */\nexport const FailoverModeSchema = z.enum([\n 'active_passive',\n 'active_active',\n 'pilot_light',\n 'warm_standby',\n]).describe('Failover mode');\n\nexport type FailoverMode = z.infer;\n\n/**\n * Failover Configuration Schema\n */\nexport const FailoverConfigSchema = z.object({\n /** Failover mode */\n mode: FailoverModeSchema.default('active_passive').describe('Failover mode'),\n /** Automatic failover enabled */\n autoFailover: z.boolean().default(true).describe('Enable automatic failover'),\n /** Health check interval in seconds */\n healthCheckInterval: z.number().default(30).describe('Health check interval in seconds'),\n /** Number of consecutive failures before triggering failover */\n failureThreshold: z.number().default(3).describe('Consecutive failures before failover'),\n /** Regions/zones for disaster recovery */\n regions: z.array(z.object({\n name: z.string().describe('Region identifier (e.g., \"us-east-1\", \"eu-west-1\")'),\n role: z.enum(['primary', 'secondary', 'witness']).describe('Region role'),\n endpoint: z.string().optional().describe('Region endpoint URL'),\n priority: z.number().optional().describe('Failover priority (lower = higher priority)'),\n })).min(2).describe('Multi-region configuration (minimum 2 regions)'),\n /** DNS failover configuration */\n dns: z.object({\n ttl: z.number().default(60).describe('DNS TTL in seconds for failover'),\n provider: z.enum(['route53', 'cloudflare', 'azure_dns', 'custom']).optional()\n .describe('DNS provider for automatic failover'),\n }).optional().describe('DNS failover settings'),\n}).describe('Failover configuration');\n\nexport type FailoverConfig = z.infer;\nexport type FailoverConfigInput = z.input;\n\n/**\n * Recovery Point Objective (RPO) Schema\n *\n * Maximum acceptable amount of data loss measured in time.\n */\nexport const RPOSchema = z.object({\n /** RPO value */\n value: z.number().min(0).describe('RPO value'),\n /** RPO time unit */\n unit: z.enum(['seconds', 'minutes', 'hours']).default('minutes').describe('RPO time unit'),\n}).describe('Recovery Point Objective (maximum acceptable data loss)');\n\nexport type RPO = z.infer;\n\n/**\n * Recovery Time Objective (RTO) Schema\n *\n * Maximum acceptable time to restore service after a disaster.\n */\nexport const RTOSchema = z.object({\n /** RTO value */\n value: z.number().min(0).describe('RTO value'),\n /** RTO time unit */\n unit: z.enum(['seconds', 'minutes', 'hours']).default('minutes').describe('RTO time unit'),\n}).describe('Recovery Time Objective (maximum acceptable downtime)');\n\nexport type RTO = z.infer;\n\n/**\n * Disaster Recovery Plan Schema\n *\n * Complete disaster recovery configuration for an ObjectStack deployment.\n * Covers backup, failover, replication, and recovery objectives.\n *\n * Aligned with industry standards:\n * - ISO 22301 (Business Continuity Management)\n * - AWS Well-Architected Framework (Reliability Pillar)\n *\n * @example\n * ```typescript\n * const drPlan: DisasterRecoveryPlan = {\n * enabled: true,\n * rpo: { value: 15, unit: 'minutes' },\n * rto: { value: 1, unit: 'hours' },\n * backup: {\n * strategy: 'incremental',\n * schedule: '0 0/6 * * *',\n * retention: { days: 90, minCopies: 5 },\n * destination: { type: 's3', bucket: 'backup-bucket', region: 'us-east-1' },\n * },\n * failover: {\n * mode: 'active_passive',\n * autoFailover: true,\n * healthCheckInterval: 30,\n * failureThreshold: 3,\n * regions: [\n * { name: 'us-east-1', role: 'primary' },\n * { name: 'us-west-2', role: 'secondary' },\n * ],\n * },\n * };\n * ```\n */\nexport const DisasterRecoveryPlanSchema = z.object({\n /** Enable disaster recovery */\n enabled: z.boolean().default(false).describe('Enable disaster recovery plan'),\n\n /** Recovery Point Objective */\n rpo: RPOSchema.describe('Recovery Point Objective'),\n\n /** Recovery Time Objective */\n rto: RTOSchema.describe('Recovery Time Objective'),\n\n /** Backup configuration */\n backup: BackupConfigSchema.describe('Backup configuration'),\n\n /** Failover configuration */\n failover: FailoverConfigSchema.optional().describe('Multi-region failover configuration'),\n\n /** Data replication settings */\n replication: z.object({\n /** Replication mode */\n mode: z.enum(['synchronous', 'asynchronous', 'semi_synchronous']).default('asynchronous')\n .describe('Data replication mode'),\n /** Maximum replication lag allowed (seconds) */\n maxLagSeconds: z.number().optional().describe('Maximum acceptable replication lag in seconds'),\n /** Objects/tables to replicate (empty = all) */\n includeObjects: z.array(z.string()).optional().describe('Objects to replicate (empty = all)'),\n /** Objects/tables to exclude from replication */\n excludeObjects: z.array(z.string()).optional().describe('Objects to exclude from replication'),\n }).optional().describe('Data replication settings'),\n\n /** Automated recovery testing */\n testing: z.object({\n /** Enable periodic DR testing */\n enabled: z.boolean().default(false).describe('Enable automated DR testing'),\n /** Cron schedule for DR tests */\n schedule: z.string().optional().describe('Cron expression for DR test schedule'),\n /** Notification channel for test results */\n notificationChannel: z.string().optional().describe('Notification channel for DR test results'),\n }).optional().describe('Automated disaster recovery testing'),\n\n /** Runbook URL for manual procedures */\n runbookUrl: z.string().optional().describe('URL to disaster recovery runbook/playbook'),\n\n /** Contact list for DR incidents */\n contacts: z.array(z.object({\n name: z.string().describe('Contact name'),\n role: z.string().describe('Contact role (e.g., \"DBA\", \"SRE Lead\")'),\n email: z.string().optional().describe('Contact email'),\n phone: z.string().optional().describe('Contact phone'),\n })).optional().describe('Emergency contact list for DR incidents'),\n}).describe('Complete disaster recovery plan configuration');\n\nexport type DisasterRecoveryPlan = z.infer;\nexport type DisasterRecoveryPlanInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Message queue protocol for async communication\n * Supports Kafka, RabbitMQ, AWS SQS, Redis Pub/Sub\n */\nexport const MessageQueueProviderSchema = z.enum([\n 'kafka',\n 'rabbitmq',\n 'aws-sqs',\n 'redis-pubsub',\n 'google-pubsub',\n 'azure-service-bus',\n]).describe('Supported message queue backend provider');\n\nexport type MessageQueueProvider = z.infer;\n\nexport const TopicConfigSchema = z.object({\n name: z.string().describe('Topic name identifier'),\n partitions: z.number().default(1).describe('Number of partitions for parallel consumption'),\n replicationFactor: z.number().default(1).describe('Number of replicas for fault tolerance'),\n retentionMs: z.number().optional().describe('Message retention period in milliseconds'),\n compressionType: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression algorithm'),\n}).describe('Configuration for a message queue topic');\n\nexport type TopicConfig = z.infer;\n\nexport const ConsumerConfigSchema = z.object({\n groupId: z.string().describe('Consumer group identifier'),\n autoOffsetReset: z.enum(['earliest', 'latest']).default('latest').describe('Where to start reading when no offset exists'),\n enableAutoCommit: z.boolean().default(true).describe('Automatically commit consumed offsets'),\n maxPollRecords: z.number().default(500).describe('Maximum records returned per poll'),\n}).describe('Consumer group configuration for topic consumption');\n\nexport type ConsumerConfig = z.infer;\n\nexport const DeadLetterQueueSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable dead letter queue for failed messages'),\n maxRetries: z.number().default(3).describe('Maximum delivery attempts before sending to DLQ'),\n queueName: z.string().describe('Name of the dead letter queue'),\n}).describe('Dead letter queue configuration for unprocessable messages');\n\nexport type DeadLetterQueue = z.infer;\n\nexport const MessageQueueConfigSchema = z.object({\n provider: MessageQueueProviderSchema.describe('Message queue backend provider'),\n topics: z.array(TopicConfigSchema).describe('List of topic configurations'),\n consumers: z.array(ConsumerConfigSchema).optional().describe('Consumer group configurations'),\n deadLetterQueue: DeadLetterQueueSchema.optional().describe('Dead letter queue for failed messages'),\n ssl: z.boolean().default(false).describe('Enable SSL/TLS for broker connections'),\n sasl: z.object({\n mechanism: z.enum(['plain', 'scram-sha-256', 'scram-sha-512']).describe('SASL authentication mechanism'),\n username: z.string().describe('SASL username'),\n password: z.string().describe('SASL password'),\n }).optional().describe('SASL authentication configuration'),\n}).describe('Top-level message queue configuration');\n\nexport type MessageQueueConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Object Storage Protocol\n * \n * Unified storage protocol that combines:\n * - Object storage systems (S3, Azure Blob, GCS, MinIO)\n * - Scoped storage configuration (temp, cache, data, logs, config, public)\n * - Multi-cloud storage providers\n * - Bucket/container configuration\n * - Access control and permissions\n * - Lifecycle policies for data retention\n * - Presigned URLs for secure direct access\n * - Multipart uploads for large files\n */\n\n// ============================================================================\n// Storage Scope Protocol (formerly from scoped-storage.zod.ts)\n// ============================================================================\n\n/**\n * Storage Scope Enum\n * Defines the lifecycle and persistence guarantee of the storage area.\n */\nexport const StorageScopeSchema = z.enum([\n 'global', // Global application-wide storage\n 'tenant', // Tenant-scoped storage (multi-tenant apps)\n 'user', // User-scoped storage\n 'session', // Session-scoped storage (ephemeral)\n 'temp', // Ephemeral, cleared on restart\n 'cache', // Ephemeral, survives restarts, cleared on LRU/Expiration\n 'data', // Persistent, backed up\n 'logs', // Append-only, rotated\n 'config', // Read-heavy, versioned\n 'public' // Publicly accessible static assets\n]).describe('Storage scope classification');\n\nexport type StorageScope = z.infer;\n\n/**\n * File Metadata Schema\n * Standardized file attribute structure\n */\nexport const FileMetadataSchema = z.object({\n path: z.string().describe('File path'),\n name: z.string().describe('File name'),\n size: z.number().int().describe('File size in bytes'),\n mimeType: z.string().describe('MIME type'),\n lastModified: z.string().datetime().describe('Last modified timestamp'),\n created: z.string().datetime().describe('Creation timestamp'),\n etag: z.string().optional().describe('Entity tag'),\n});\n\nexport type FileMetadata = z.infer;\n\n// ============================================================================\n// Enums\n// ============================================================================\n\n/**\n * Storage Provider Types\n * \n * Supported cloud and self-hosted object storage providers.\n */\nexport const StorageProviderSchema = z.enum([\n 's3', // Amazon S3\n 'azure_blob', // Azure Blob Storage\n 'gcs', // Google Cloud Storage\n 'minio', // MinIO (self-hosted S3-compatible)\n 'r2', // Cloudflare R2\n 'spaces', // DigitalOcean Spaces\n 'wasabi', // Wasabi Hot Cloud Storage\n 'backblaze', // Backblaze B2\n 'local', // Local filesystem (development only)\n]).describe('Storage provider type');\n\nexport type StorageProvider = z.infer;\n\n/**\n * Storage Access Control List (ACL)\n * \n * Predefined access control configurations for objects and buckets.\n */\nexport const StorageAclSchema = z.enum([\n 'private', // Owner has full control, no one else has access\n 'public_read', // Owner has full control, everyone can read\n 'public_read_write', // Owner has full control, everyone can read/write (not recommended)\n 'authenticated_read', // Owner has full control, authenticated users can read\n 'bucket_owner_read', // Object owner has full control, bucket owner can read\n 'bucket_owner_full_control', // Both object and bucket owner have full control\n]).describe('Storage access control level');\n\nexport type StorageAcl = z.infer;\n\n/**\n * Storage Class / Tier\n * \n * Different storage tiers for cost optimization.\n * Maps to provider-specific storage classes.\n */\nexport const StorageClassSchema = z.enum([\n 'standard', // Standard/hot storage for frequently accessed data\n 'intelligent', // Intelligent tiering (auto-moves between hot/cool)\n 'infrequent_access', // Infrequent access/cool storage\n 'glacier', // Archive/cold storage (slower retrieval)\n 'deep_archive', // Deep archive (cheapest, slowest retrieval)\n]).describe('Storage class/tier for cost optimization');\n\nexport type StorageClass = z.infer;\n\n/**\n * Lifecycle Transition Action\n */\nexport const LifecycleActionSchema = z.enum([\n 'transition', // Move to different storage class\n 'delete', // Delete the object\n 'abort', // Abort incomplete multipart uploads\n]).describe('Lifecycle policy action type');\n\nexport type LifecycleAction = z.infer;\n\n// ============================================================================\n// Configuration Schemas\n// ============================================================================\n\n/**\n * Object Metadata Schema\n * \n * Standard and custom metadata attached to stored objects.\n * \n * @example\n * {\n * contentType: 'image/jpeg',\n * contentLength: 1024000,\n * etag: '\"abc123\"',\n * lastModified: new Date('2024-01-01'),\n * custom: {\n * uploadedBy: 'user123',\n * department: 'marketing'\n * }\n * }\n */\nexport const ObjectMetadataSchema = z.object({\n contentType: z.string().describe('MIME type (e.g., image/jpeg, application/pdf)'),\n contentLength: z.number().min(0).describe('File size in bytes'),\n contentEncoding: z.string().optional().describe('Content encoding (e.g., gzip)'),\n contentDisposition: z.string().optional().describe('Content disposition header'),\n contentLanguage: z.string().optional().describe('Content language'),\n cacheControl: z.string().optional().describe('Cache control directives'),\n etag: z.string().optional().describe('Entity tag for versioning/caching'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n versionId: z.string().optional().describe('Object version identifier'),\n storageClass: StorageClassSchema.optional().describe('Storage class/tier'),\n encryption: z.object({\n algorithm: z.string().describe('Encryption algorithm (e.g., AES256, aws:kms)'),\n keyId: z.string().optional().describe('KMS key ID if using managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n custom: z.record(z.string(), z.string()).optional().describe('Custom user-defined metadata'),\n});\n\nexport type ObjectMetadata = z.infer;\n\n/**\n * Presigned URL Configuration\n * \n * Configuration for generating temporary URLs for direct access to objects.\n * Useful for secure file uploads/downloads without exposing credentials.\n * \n * @example\n * // Generate download URL valid for 1 hour\n * {\n * operation: 'get',\n * expiresIn: 3600,\n * contentType: 'image/jpeg'\n * }\n * \n * @example\n * // Generate upload URL valid for 15 minutes with size limit\n * {\n * operation: 'put',\n * expiresIn: 900,\n * contentType: 'application/pdf',\n * maxSize: 10485760\n * }\n */\nexport const PresignedUrlConfigSchema = z.object({\n operation: z.enum(['get', 'put', 'delete', 'head']).describe('Allowed operation'),\n expiresIn: z.number().min(1).max(604800).describe('Expiration time in seconds (max 7 days)'),\n contentType: z.string().optional().describe('Required content type for PUT operations'),\n maxSize: z.number().min(0).optional().describe('Maximum file size in bytes for PUT operations'),\n responseContentType: z.string().optional().describe('Override content-type for GET operations'),\n responseContentDisposition: z.string().optional().describe('Override content-disposition for GET operations'),\n});\n\nexport type PresignedUrlConfig = z.infer;\n\n/**\n * Multipart Upload Configuration\n * \n * Configuration for chunked uploads of large files.\n * Enables resumable uploads and parallel transfer.\n * \n * @example\n * // Enable multipart for files > 100MB with 10MB chunks\n * {\n * enabled: true,\n * partSize: 10485760,\n * maxParts: 10000,\n * threshold: 104857600,\n * maxConcurrent: 4\n * }\n */\nexport const MultipartUploadConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable multipart uploads'),\n partSize: z.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe('Part size in bytes (min 5MB, max 5GB)'),\n maxParts: z.number().min(1).max(10000).default(10000).describe('Maximum number of parts (max 10,000)'),\n threshold: z.number().min(0).default(100 * 1024 * 1024).describe('File size threshold to trigger multipart upload (bytes)'),\n maxConcurrent: z.number().min(1).max(100).default(4).describe('Maximum concurrent part uploads'),\n abortIncompleteAfterDays: z.number().min(1).optional().describe('Auto-abort incomplete uploads after N days'),\n});\n\nexport type MultipartUploadConfig = z.infer;\n\n/**\n * Access Control Configuration\n * \n * Fine-grained access control for buckets and objects.\n * \n * @example\n * {\n * acl: 'private',\n * allowedOrigins: ['https://app.example.com'],\n * allowedMethods: ['GET', 'PUT'],\n * corsEnabled: true,\n * publicAccess: {\n * allowPublicRead: false,\n * allowPublicWrite: false\n * }\n * }\n */\nexport const AccessControlConfigSchema = z.object({\n acl: StorageAclSchema.default('private').describe('Default access control level'),\n allowedOrigins: z.array(z.string()).optional().describe('CORS allowed origins'),\n allowedMethods: z.array(z.enum(['GET', 'PUT', 'POST', 'DELETE', 'HEAD'])).optional().describe('CORS allowed HTTP methods'),\n allowedHeaders: z.array(z.string()).optional().describe('CORS allowed headers'),\n exposeHeaders: z.array(z.string()).optional().describe('CORS exposed headers'),\n maxAge: z.number().min(0).optional().describe('CORS preflight cache duration in seconds'),\n corsEnabled: z.boolean().default(false).describe('Enable CORS configuration'),\n publicAccess: z.object({\n allowPublicRead: z.boolean().default(false).describe('Allow public read access'),\n allowPublicWrite: z.boolean().default(false).describe('Allow public write access'),\n allowPublicList: z.boolean().default(false).describe('Allow public bucket listing'),\n }).optional().describe('Public access control'),\n allowedIps: z.array(z.string()).optional().describe('Allowed IP addresses/CIDR blocks'),\n blockedIps: z.array(z.string()).optional().describe('Blocked IP addresses/CIDR blocks'),\n});\n\nexport type AccessControlConfig = z.infer;\n\n/**\n * Lifecycle Policy Rule\n * \n * Individual rule for automatic object lifecycle management.\n * \n * @example\n * // Transition to infrequent access after 30 days\n * {\n * id: 'move_to_ia',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 30,\n * targetStorageClass: 'infrequent_access'\n * }\n * \n * @example\n * // Delete objects after 365 days\n * {\n * id: 'delete_old',\n * enabled: true,\n * action: 'delete',\n * daysAfterCreation: 365\n * }\n */\nexport const LifecyclePolicyRuleSchema = z.object({\n id: SystemIdentifierSchema.describe('Rule identifier'),\n enabled: z.boolean().default(true).describe('Enable this rule'),\n action: LifecycleActionSchema.describe('Action to perform'),\n prefix: z.string().optional().describe('Object key prefix filter (e.g., \"uploads/\")'),\n tags: z.record(z.string(), z.string()).optional().describe('Object tag filters'),\n daysAfterCreation: z.number().min(0).optional().describe('Days after object creation'),\n daysAfterModification: z.number().min(0).optional().describe('Days after last modification'),\n targetStorageClass: StorageClassSchema.optional().describe('Target storage class for transition action'),\n}).refine((data) => {\n // Validate that transition action has targetStorageClass\n if (data.action === 'transition' && !data.targetStorageClass) {\n return false;\n }\n return true;\n}, {\n message: 'targetStorageClass is required when action is \"transition\"',\n});\n\nexport type LifecyclePolicyRule = z.infer;\n\n/**\n * Lifecycle Policy Configuration\n * \n * Collection of lifecycle rules for automatic data management.\n * \n * @example\n * {\n * enabled: true,\n * rules: [\n * {\n * id: 'archive_old_files',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 90,\n * targetStorageClass: 'glacier'\n * },\n * {\n * id: 'delete_temp_files',\n * enabled: true,\n * action: 'delete',\n * prefix: 'temp/',\n * daysAfterCreation: 7\n * }\n * ]\n * }\n */\nexport const LifecyclePolicyConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable lifecycle policies'),\n rules: z.array(LifecyclePolicyRuleSchema).default([]).describe('Lifecycle rules'),\n});\n\nexport type LifecyclePolicyConfig = z.infer;\n\n/**\n * Bucket Configuration Schema\n * \n * Comprehensive configuration for a storage bucket/container.\n * \n * @example\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'my-app-uploads',\n * region: 'us-east-1',\n * provider: 's3',\n * versioning: true,\n * accessControl: {\n * acl: 'private',\n * corsEnabled: true,\n * allowedOrigins: ['https://app.example.com']\n * },\n * multipartConfig: {\n * enabled: true,\n * threshold: 104857600\n * }\n * }\n */\nexport const BucketConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Bucket identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n bucketName: z.string().describe('Actual bucket/container name in storage provider'),\n region: z.string().optional().describe('Storage region (e.g., us-east-1, westus)'),\n provider: StorageProviderSchema.describe('Storage provider'),\n endpoint: z.string().optional().describe('Custom endpoint URL (for S3-compatible providers)'),\n pathStyle: z.boolean().default(false).describe('Use path-style URLs (for S3-compatible providers)'),\n \n versioning: z.boolean().default(false).describe('Enable object versioning'),\n encryption: z.object({\n enabled: z.boolean().default(false).describe('Enable server-side encryption'),\n algorithm: z.enum(['AES256', 'aws:kms', 'azure:kms', 'gcp:kms']).default('AES256').describe('Encryption algorithm'),\n kmsKeyId: z.string().optional().describe('KMS key ID for managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n \n accessControl: AccessControlConfigSchema.optional().describe('Access control configuration'),\n lifecyclePolicy: LifecyclePolicyConfigSchema.optional().describe('Lifecycle policy configuration'),\n multipartConfig: MultipartUploadConfigSchema.optional().describe('Multipart upload configuration'),\n \n tags: z.record(z.string(), z.string()).optional().describe('Bucket tags for organization'),\n description: z.string().optional().describe('Bucket description'),\n enabled: z.boolean().default(true).describe('Enable this bucket'),\n});\n\nexport type BucketConfig = z.infer;\n\n/**\n * Storage Connection Configuration\n * \n * Provider-specific connection credentials and settings.\n * \n * @example S3\n * {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * sessionToken: '${AWS_SESSION_TOKEN}',\n * region: 'us-east-1'\n * }\n * \n * @example Azure\n * {\n * accountName: 'mystorageaccount',\n * accountKey: '${AZURE_STORAGE_KEY}',\n * endpoint: 'https://mystorageaccount.blob.core.windows.net'\n * }\n */\nexport const StorageConnectionSchema = z.object({\n // AWS S3 / MinIO\n accessKeyId: z.string().optional().describe('AWS access key ID or MinIO access key'),\n secretAccessKey: z.string().optional().describe('AWS secret access key or MinIO secret key'),\n sessionToken: z.string().optional().describe('AWS session token for temporary credentials'),\n \n // Azure Blob Storage\n accountName: z.string().optional().describe('Azure storage account name'),\n accountKey: z.string().optional().describe('Azure storage account key'),\n sasToken: z.string().optional().describe('Azure SAS token'),\n \n // Google Cloud Storage\n projectId: z.string().optional().describe('GCP project ID'),\n credentials: z.string().optional().describe('GCP service account credentials JSON'),\n \n // Common\n endpoint: z.string().optional().describe('Custom endpoint URL'),\n region: z.string().optional().describe('Default region'),\n useSSL: z.boolean().default(true).describe('Use SSL/TLS for connections'),\n timeout: z.number().min(0).optional().describe('Connection timeout in milliseconds'),\n});\n\nexport type StorageConnection = z.infer;\n\n/**\n * Object Storage Configuration\n * \n * Complete object storage system configuration.\n * \n * @example\n * {\n * name: 'production_storage',\n * label: 'Production File Storage',\n * provider: 's3',\n * scope: 'global',\n * connection: {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * region: 'us-east-1'\n * },\n * buckets: [\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'prod-uploads',\n * provider: 's3',\n * region: 'us-east-1'\n * }\n * ],\n * defaultBucket: 'user_uploads'\n * }\n */\nexport const ObjectStorageConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Storage configuration identifier'),\n label: z.string().describe('Display label'),\n provider: StorageProviderSchema.describe('Primary storage provider'),\n \n /**\n * Storage scope\n * Defines the lifecycle and access pattern for this storage\n */\n scope: StorageScopeSchema.optional().default('global').describe('Storage scope'),\n \n connection: StorageConnectionSchema.describe('Connection credentials'),\n buckets: z.array(BucketConfigSchema).default([]).describe('Configured buckets'),\n defaultBucket: z.string().optional().describe('Default bucket name for operations'),\n \n /**\n * Base path or location\n * For local/scoped storage configurations\n */\n location: z.string().optional().describe('Root path (local) or base location'),\n \n /**\n * Storage quota in bytes\n */\n quota: z.number().int().positive().optional().describe('Max size in bytes'),\n \n /**\n * Provider-specific options\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Provider-specific configuration options'),\n \n enabled: z.boolean().default(true).describe('Enable this storage configuration'),\n description: z.string().optional().describe('Configuration description'),\n});\n\nexport type ObjectStorageConfig = z.infer;\n\n// ============================================================================\n// Helper Examples\n// ============================================================================\n\n/**\n * Example: AWS S3 Configuration\n */\nexport const s3StorageExample = ObjectStorageConfigSchema.parse({\n name: 'aws_s3_storage',\n label: 'AWS S3 Production Storage',\n provider: 's3',\n connection: {\n accessKeyId: '${AWS_ACCESS_KEY_ID}',\n secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n region: 'us-east-1',\n },\n buckets: [\n {\n name: 'user_uploads',\n label: 'User Uploads',\n bucketName: 'my-app-user-uploads',\n region: 'us-east-1',\n provider: 's3',\n versioning: true,\n encryption: {\n enabled: true,\n algorithm: 'aws:kms',\n kmsKeyId: '${AWS_KMS_KEY_ID}',\n },\n accessControl: {\n acl: 'private',\n corsEnabled: true,\n allowedOrigins: ['https://app.example.com'],\n allowedMethods: ['GET', 'PUT', 'POST'],\n },\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'archive_old_uploads',\n enabled: true,\n action: 'transition',\n daysAfterCreation: 90,\n targetStorageClass: 'glacier',\n },\n ],\n },\n multipartConfig: {\n enabled: true,\n partSize: 10 * 1024 * 1024,\n threshold: 100 * 1024 * 1024,\n maxConcurrent: 4,\n },\n },\n ],\n defaultBucket: 'user_uploads',\n enabled: true,\n});\n\n/**\n * Example: MinIO Configuration\n */\nexport const minioStorageExample = ObjectStorageConfigSchema.parse({\n name: 'minio_local',\n label: 'MinIO Local Storage',\n provider: 'minio',\n connection: {\n accessKeyId: 'minioadmin',\n secretAccessKey: 'minioadmin',\n endpoint: 'http://localhost:9000',\n useSSL: false,\n },\n buckets: [\n {\n name: 'development_files',\n label: 'Development Files',\n bucketName: 'dev-files',\n provider: 'minio',\n endpoint: 'http://localhost:9000',\n pathStyle: true,\n accessControl: {\n acl: 'private',\n },\n },\n ],\n defaultBucket: 'development_files',\n enabled: true,\n});\n\n/**\n * Example: Azure Blob Storage Configuration\n */\nexport const azureBlobStorageExample = ObjectStorageConfigSchema.parse({\n name: 'azure_blob_storage',\n label: 'Azure Blob Storage',\n provider: 'azure_blob',\n connection: {\n accountName: 'mystorageaccount',\n accountKey: '${AZURE_STORAGE_KEY}',\n endpoint: 'https://mystorageaccount.blob.core.windows.net',\n },\n buckets: [\n {\n name: 'media_files',\n label: 'Media Files',\n bucketName: 'media',\n provider: 'azure_blob',\n region: 'eastus',\n accessControl: {\n acl: 'public_read',\n publicAccess: {\n allowPublicRead: true,\n allowPublicWrite: false,\n allowPublicList: false,\n },\n },\n },\n ],\n defaultBucket: 'media_files',\n enabled: true,\n});\n\n/**\n * Example: Google Cloud Storage Configuration\n */\nexport const gcsStorageExample = ObjectStorageConfigSchema.parse({\n name: 'gcs_storage',\n label: 'Google Cloud Storage',\n provider: 'gcs',\n connection: {\n projectId: 'my-gcp-project',\n credentials: '${GCP_SERVICE_ACCOUNT_JSON}',\n },\n buckets: [\n {\n name: 'backup_storage',\n label: 'Backup Storage',\n bucketName: 'my-app-backups',\n region: 'us-central1',\n provider: 'gcs',\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'delete_old_backups',\n enabled: true,\n action: 'delete',\n daysAfterCreation: 30,\n },\n ],\n },\n },\n ],\n defaultBucket: 'backup_storage',\n enabled: true,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Full-text search protocol\n * Supports Elasticsearch, Algolia, Meilisearch, Typesense\n */\nexport const SearchProviderSchema = z.enum([\n 'elasticsearch',\n 'algolia',\n 'meilisearch',\n 'typesense',\n 'opensearch',\n]).describe('Supported full-text search engine provider');\n\nexport type SearchProvider = z.infer;\n\nexport const AnalyzerConfigSchema = z.object({\n type: z.enum(['standard', 'simple', 'whitespace', 'keyword', 'pattern', 'language']).describe('Text analyzer type'),\n language: z.string().optional().describe('Language for language-specific analysis'),\n stopwords: z.array(z.string()).optional().describe('Custom stopwords to filter during analysis'),\n customFilters: z.array(z.string()).optional().describe('Additional token filter names to apply'),\n}).describe('Text analyzer configuration for index tokenization and normalization');\n\nexport type AnalyzerConfig = z.infer;\n\nexport const SearchIndexConfigSchema = z.object({\n indexName: z.string().describe('Name of the search index'),\n objectName: z.string().describe('Source ObjectQL object'),\n fields: z.array(z.object({\n name: z.string().describe('Field name to index'),\n type: z.enum(['text', 'keyword', 'number', 'date', 'boolean', 'geo']).describe('Index field data type'),\n analyzer: z.string().optional().describe('Named analyzer to use for this field'),\n searchable: z.boolean().default(true).describe('Include field in full-text search'),\n filterable: z.boolean().default(false).describe('Allow filtering on this field'),\n sortable: z.boolean().default(false).describe('Allow sorting by this field'),\n boost: z.number().default(1).describe('Relevance boost factor for this field'),\n })).describe('Fields to include in the search index'),\n replicas: z.number().default(1).describe('Number of index replicas for availability'),\n shards: z.number().default(1).describe('Number of index shards for distribution'),\n}).describe('Search index definition mapping an ObjectQL object to a search engine index');\n\nexport type SearchIndexConfig = z.infer;\n\nexport const FacetConfigSchema = z.object({\n field: z.string().describe('Field name to generate facets from'),\n maxValues: z.number().default(10).describe('Maximum number of facet values to return'),\n sort: z.enum(['count', 'alpha']).default('count').describe('Facet value sort order'),\n}).describe('Faceted search configuration for a single field');\n\nexport type FacetConfig = z.infer;\n\nexport const SearchConfigSchema = z.object({\n provider: SearchProviderSchema.describe('Search engine backend provider'),\n indexes: z.array(SearchIndexConfigSchema).describe('Search index definitions'),\n analyzers: z.record(z.string(), AnalyzerConfigSchema).optional().describe('Named text analyzer configurations'),\n facets: z.array(FacetConfigSchema).optional().describe('Faceted search configurations'),\n typoTolerance: z.boolean().default(true).describe('Enable typo-tolerant search'),\n synonyms: z.record(z.string(), z.array(z.string())).optional().describe('Synonym mappings for search expansion'),\n ranking: z.array(z.enum(['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom'])).optional().describe('Custom ranking rule order'),\n}).describe('Top-level full-text search engine configuration');\n\nexport type SearchConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, CorsConfigSchema, RateLimitConfigSchema, StaticMountSchema } from '../shared/http.zod';\n\n/**\n * HTTP Server Protocol\n * \n * Defines the runtime HTTP server configuration and capabilities.\n * Provides abstractions for HTTP server implementations (Express, Fastify, Hono, etc.)\n * \n * Architecture alignment:\n * - Kubernetes: Service and Ingress resources\n * - AWS: API Gateway configuration\n * - Spring Boot: Application properties\n */\n\n// ==========================================\n// Server Configuration\n// ==========================================\n\n/**\n * HTTP Server Configuration Schema\n * Core configuration for HTTP server instances\n * \n * @example\n * {\n * \"port\": 3000,\n * \"host\": \"0.0.0.0\",\n * \"cors\": {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\"]\n * },\n * \"compression\": true,\n * \"requestTimeout\": 30000\n * }\n */\nexport const HttpServerConfigSchema = z.object({\n /**\n * Server port number\n */\n port: z.number().int().min(1).max(65535).default(3000).describe('Port number to listen on'),\n \n /**\n * Server host address\n */\n host: z.string().default('0.0.0.0').describe('Host address to bind to'),\n \n /**\n * CORS configuration\n */\n cors: CorsConfigSchema.optional().describe('CORS configuration'),\n \n /**\n * Request handling options\n */\n requestTimeout: z.number().int().default(30000).describe('Request timeout in milliseconds'),\n bodyLimit: z.string().default('10mb').describe('Maximum request body size'),\n \n /**\n * Compression settings\n */\n compression: z.boolean().default(true).describe('Enable response compression'),\n \n /**\n * Security headers\n */\n security: z.object({\n helmet: z.boolean().default(true).describe('Enable security headers via helmet'),\n rateLimit: RateLimitConfigSchema.optional().describe('Global rate limiting configuration'),\n }).optional().describe('Security configuration'),\n \n /**\n * Static file serving\n */\n static: z.array(StaticMountSchema).optional().describe('Static file serving configuration'),\n \n /**\n * Trust proxy settings\n */\n trustProxy: z.boolean().default(false).describe('Trust X-Forwarded-* headers'),\n});\n\nexport type HttpServerConfig = z.infer;\nexport type HttpServerConfigInput = z.input;\n\n// ==========================================\n// Route Registration\n// ==========================================\n\n/**\n * Route Handler Metadata Schema\n * Metadata for route handlers used in registration\n */\nexport const RouteHandlerMetadataSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (supports parameters like /api/users/:id)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Handler function name or identifier\n */\n handler: z.string().describe('Handler identifier or name'),\n \n /**\n * Route metadata\n */\n metadata: z.object({\n summary: z.string().optional().describe('Route summary for documentation'),\n description: z.string().optional().describe('Route description'),\n tags: z.array(z.string()).optional().describe('Tags for grouping'),\n operationId: z.string().optional().describe('Unique operation identifier'),\n }).optional(),\n \n /**\n * Security requirements\n */\n security: z.object({\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n rateLimit: z.string().optional().describe('Rate limit policy override'),\n }).optional(),\n});\n\nexport type RouteHandlerMetadata = z.infer;\nexport type RouteHandlerMetadataInput = z.input;\n\n// ==========================================\n// Middleware Configuration\n// ==========================================\n\n/**\n * Middleware Type Enum\n */\nexport const MiddlewareType = z.enum([\n 'authentication', // Authentication middleware\n 'authorization', // Authorization/permission checks\n 'logging', // Request/response logging\n 'validation', // Input validation\n 'transformation', // Request/response transformation\n 'error', // Error handling\n 'custom', // Custom middleware\n]);\n\nexport type MiddlewareType = z.infer;\n\n/**\n * Middleware Configuration Schema\n * Defines middleware execution order and configuration\n * \n * @example\n * {\n * \"name\": \"auth_middleware\",\n * \"type\": \"authentication\",\n * \"enabled\": true,\n * \"order\": 10,\n * \"config\": {\n * \"jwtSecret\": \"secret\",\n * \"excludePaths\": [\"/health\", \"/metrics\"]\n * }\n * }\n */\nexport const MiddlewareConfigSchema = z.object({\n /**\n * Middleware identifier\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Middleware name (snake_case)'),\n \n /**\n * Middleware type\n */\n type: MiddlewareType.describe('Middleware type'),\n \n /**\n * Enable/disable middleware\n */\n enabled: z.boolean().default(true).describe('Whether middleware is enabled'),\n \n /**\n * Execution order (lower numbers execute first)\n */\n order: z.number().int().default(100).describe('Execution order priority'),\n \n /**\n * Middleware-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Middleware configuration object'),\n \n /**\n * Path patterns to apply middleware to\n */\n paths: z.object({\n include: z.array(z.string()).optional().describe('Include path patterns (glob)'),\n exclude: z.array(z.string()).optional().describe('Exclude path patterns (glob)'),\n }).optional().describe('Path filtering'),\n});\n\nexport type MiddlewareConfig = z.infer;\nexport type MiddlewareConfigInput = z.input;\n\n// ==========================================\n// Server Lifecycle Events\n// ==========================================\n\n/**\n * Server Event Type Enum\n */\nexport const ServerEventType = z.enum([\n 'starting', // Server is starting\n 'started', // Server has started and is listening\n 'stopping', // Server is stopping\n 'stopped', // Server has stopped\n 'request', // Request received\n 'response', // Response sent\n 'error', // Error occurred\n]);\n\nexport type ServerEventType = z.infer;\n\n/**\n * Server Event Schema\n * Events emitted by the HTTP server during lifecycle\n */\nexport const ServerEventSchema = z.object({\n /**\n * Event type\n */\n type: ServerEventType.describe('Event type'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp (ISO 8601)'),\n \n /**\n * Event payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Event-specific data'),\n});\n\nexport type ServerEvent = z.infer;\n\n// ==========================================\n// Server Capability Declaration\n// ==========================================\n\n/**\n * Server Capabilities Schema\n * Declares what features a server implementation supports\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Supported HTTP versions\n */\n httpVersions: z.array(z.enum(['1.0', '1.1', '2.0', '3.0'])).default(['1.1']).describe('Supported HTTP versions'),\n \n /**\n * WebSocket support\n */\n websocket: z.boolean().default(false).describe('WebSocket support'),\n \n /**\n * Server-Sent Events support\n */\n sse: z.boolean().default(false).describe('Server-Sent Events support'),\n \n /**\n * HTTP/2 Server Push\n */\n serverPush: z.boolean().default(false).describe('HTTP/2 Server Push support'),\n \n /**\n * Streaming support\n */\n streaming: z.boolean().default(true).describe('Response streaming support'),\n \n /**\n * Middleware support\n */\n middleware: z.boolean().default(true).describe('Middleware chain support'),\n \n /**\n * Route parameterization\n */\n routeParams: z.boolean().default(true).describe('URL parameter support (/users/:id)'),\n \n /**\n * Built-in compression\n */\n compression: z.boolean().default(true).describe('Built-in compression support'),\n});\n\nexport type ServerCapabilities = z.infer;\nexport type ServerCapabilitiesInput = z.input;\n\n// ==========================================\n// Server Status & Metrics\n// ==========================================\n\n/**\n * Server Status Schema\n * Current operational status of the server\n */\nexport const ServerStatusSchema = z.object({\n /**\n * Server state\n */\n state: z.enum(['stopped', 'starting', 'running', 'stopping', 'error']).describe('Current server state'),\n \n /**\n * Uptime in milliseconds\n */\n uptime: z.number().int().optional().describe('Server uptime in milliseconds'),\n \n /**\n * Server information\n */\n server: z.object({\n port: z.number().int().describe('Listening port'),\n host: z.string().describe('Bound host'),\n url: z.string().optional().describe('Full server URL'),\n }).optional(),\n \n /**\n * Connection metrics\n */\n connections: z.object({\n active: z.number().int().describe('Active connections'),\n total: z.number().int().describe('Total connections handled'),\n }).optional(),\n \n /**\n * Request metrics\n */\n requests: z.object({\n total: z.number().int().describe('Total requests processed'),\n success: z.number().int().describe('Successful requests'),\n errors: z.number().int().describe('Failed requests'),\n }).optional(),\n});\n\nexport type ServerStatus = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create HTTP server configuration\n */\nexport const HttpServerConfig = Object.assign(HttpServerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create middleware configuration\n */\nexport const MiddlewareConfig = Object.assign(MiddlewareConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Audit Log Architecture\n * \n * Comprehensive audit logging system for compliance and security.\n * Supports SOX, HIPAA, GDPR, and other regulatory requirements.\n * \n * Features:\n * - Records all CRUD operations on data\n * - Tracks authentication events (login, logout, password reset)\n * - Monitors authorization changes (permissions, roles)\n * - Configurable retention policies (180-day GDPR requirement)\n * - Suspicious activity detection and alerting\n */\n\n/**\n * Audit Event Type Enum\n * Categorizes different types of auditable events in the system\n */\nexport const AuditEventType = z.enum([\n // Data Operations (CRUD)\n 'data.create', // Record creation\n 'data.read', // Record retrieval/viewing\n 'data.update', // Record modification\n 'data.delete', // Record deletion\n 'data.export', // Data export operations\n 'data.import', // Data import operations\n 'data.bulk_update', // Bulk update operations\n 'data.bulk_delete', // Bulk delete operations\n \n // Authentication Events\n 'auth.login', // Successful login\n 'auth.login_failed', // Failed login attempt\n 'auth.logout', // User logout\n 'auth.session_created', // New session created\n 'auth.session_expired', // Session expiration\n 'auth.password_reset', // Password reset initiated\n 'auth.password_changed', // Password successfully changed\n 'auth.email_verified', // Email verification completed\n 'auth.mfa_enabled', // Multi-factor auth enabled\n 'auth.mfa_disabled', // Multi-factor auth disabled\n 'auth.account_locked', // Account locked (too many failures)\n 'auth.account_unlocked', // Account unlocked\n \n // Authorization Events\n 'authz.permission_granted', // Permission granted to user\n 'authz.permission_revoked', // Permission revoked from user\n 'authz.role_assigned', // Role assigned to user\n 'authz.role_removed', // Role removed from user\n 'authz.role_created', // New role created\n 'authz.role_updated', // Role permissions modified\n 'authz.role_deleted', // Role deleted\n 'authz.policy_created', // Security policy created\n 'authz.policy_updated', // Security policy updated\n 'authz.policy_deleted', // Security policy deleted\n \n // System Events\n 'system.config_changed', // System configuration modified\n 'system.plugin_installed', // Plugin installed\n 'system.plugin_uninstalled', // Plugin uninstalled\n 'system.backup_created', // Backup created\n 'system.backup_restored', // Backup restored\n 'system.integration_added', // External integration added\n 'system.integration_removed',// External integration removed\n \n // Security Events\n 'security.access_denied', // Access denied (authorization failure)\n 'security.suspicious_activity', // Suspicious activity detected\n 'security.data_breach', // Potential data breach detected\n 'security.api_key_created', // API key created\n 'security.api_key_revoked', // API key revoked\n]);\n\nexport type AuditEventType = z.infer;\n\n/**\n * Audit Event Severity Level\n * Indicates the importance/criticality of an audit event\n */\nexport const AuditEventSeverity = z.enum([\n 'debug', // Diagnostic information\n 'info', // Informational events (normal operations)\n 'notice', // Normal but significant events\n 'warning', // Warning conditions\n 'error', // Error conditions\n 'critical', // Critical conditions requiring immediate attention\n 'alert', // Action must be taken immediately\n 'emergency', // System is unusable\n]);\n\nexport type AuditEventSeverity = z.infer;\n\n/**\n * Audit Event Actor Schema\n * Identifies who/what performed the action\n */\nexport const AuditEventActorSchema = z.object({\n /**\n * Actor type (user, system, service, api_client, etc.)\n */\n type: z.enum(['user', 'system', 'service', 'api_client', 'integration']).describe('Actor type'),\n \n /**\n * Unique identifier for the actor\n */\n id: z.string().describe('Actor identifier'),\n \n /**\n * Display name of the actor\n */\n name: z.string().optional().describe('Actor display name'),\n \n /**\n * Email address (for user actors)\n */\n email: z.string().email().optional().describe('Actor email address'),\n \n /**\n * IP address of the actor\n */\n ipAddress: z.string().optional().describe('Actor IP address'),\n \n /**\n * User agent string (for web/API requests)\n */\n userAgent: z.string().optional().describe('User agent string'),\n});\n\nexport type AuditEventActor = z.infer;\n\n/**\n * Audit Event Target Schema\n * Identifies what was acted upon\n */\nexport const AuditEventTargetSchema = z.object({\n /**\n * Target type (e.g., 'object', 'record', 'user', 'role', 'config')\n */\n type: z.string().describe('Target type'),\n \n /**\n * Unique identifier for the target\n */\n id: z.string().describe('Target identifier'),\n \n /**\n * Display name of the target\n */\n name: z.string().optional().describe('Target display name'),\n \n /**\n * Additional metadata about the target\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Target metadata'),\n});\n\nexport type AuditEventTarget = z.infer;\n\n/**\n * Audit Event Change Schema\n * Describes what changed (for update operations)\n */\nexport const AuditEventChangeSchema = z.object({\n /**\n * Field/property that changed\n */\n field: z.string().describe('Changed field name'),\n \n /**\n * Value before the change\n */\n oldValue: z.unknown().optional().describe('Previous value'),\n \n /**\n * Value after the change\n */\n newValue: z.unknown().optional().describe('New value'),\n});\n\nexport type AuditEventChange = z.infer;\n\n/**\n * Audit Event Schema\n * Complete audit event record\n */\nexport const AuditEventSchema = z.object({\n /**\n * Unique identifier for this audit event\n */\n id: z.string().describe('Audit event ID'),\n \n /**\n * Type of event being audited\n */\n eventType: AuditEventType.describe('Event type'),\n \n /**\n * Severity level of the event\n */\n severity: AuditEventSeverity.default('info').describe('Event severity'),\n \n /**\n * Timestamp when the event occurred (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n \n /**\n * Who/what performed the action\n */\n actor: AuditEventActorSchema.describe('Event actor'),\n \n /**\n * What was acted upon\n */\n target: AuditEventTargetSchema.optional().describe('Event target'),\n \n /**\n * Human-readable description of the action\n */\n description: z.string().describe('Event description'),\n \n /**\n * Detailed changes (for update operations)\n */\n changes: z.array(AuditEventChangeSchema).optional().describe('List of changes'),\n \n /**\n * Result of the action (success, failure, partial)\n */\n result: z.enum(['success', 'failure', 'partial']).default('success').describe('Action result'),\n \n /**\n * Error message (if result is failure)\n */\n errorMessage: z.string().optional().describe('Error message'),\n \n /**\n * Tenant identifier (for multi-tenant systems)\n */\n tenantId: z.string().optional().describe('Tenant identifier'),\n \n /**\n * Request/trace ID for correlation\n */\n requestId: z.string().optional().describe('Request ID for tracing'),\n \n /**\n * Additional context and metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n \n /**\n * Geographic location (if available)\n */\n location: z.object({\n country: z.string().optional(),\n region: z.string().optional(),\n city: z.string().optional(),\n }).optional().describe('Geographic location'),\n});\n\nexport type AuditEvent = z.infer;\n\n/**\n * Audit Retention Policy Schema\n * Defines how long audit logs are retained\n */\nexport const AuditRetentionPolicySchema = z.object({\n /**\n * Retention period in days\n * Default: 180 days (GDPR 6-month requirement)\n */\n retentionDays: z.number().int().min(1).default(180).describe('Retention period in days'),\n \n /**\n * Whether to archive logs after retention period\n * If true, logs are moved to cold storage; if false, they are deleted\n */\n archiveAfterRetention: z.boolean().default(true).describe('Archive logs after retention period'),\n \n /**\n * Archive storage configuration\n */\n archiveStorage: z.object({\n type: z.enum(['s3', 'gcs', 'azure_blob', 'filesystem']).describe('Archive storage type'),\n endpoint: z.string().optional().describe('Storage endpoint URL'),\n bucket: z.string().optional().describe('Storage bucket/container name'),\n path: z.string().optional().describe('Storage path prefix'),\n credentials: z.record(z.string(), z.unknown()).optional().describe('Storage credentials'),\n }).optional().describe('Archive storage configuration'),\n \n /**\n * Event types that have different retention periods\n * Overrides the default retentionDays for specific event types\n */\n customRetention: z.record(z.string(), z.number().int().positive()).optional().describe('Custom retention by event type'),\n \n /**\n * Minimum retention period for compliance\n * Prevents accidental deletion below compliance requirements\n */\n minimumRetentionDays: z.number().int().positive().optional().describe('Minimum retention for compliance'),\n});\n\nexport type AuditRetentionPolicy = z.infer;\n\n/**\n * Suspicious Activity Rule Schema\n * Defines rules for detecting suspicious activities\n */\nexport const SuspiciousActivityRuleSchema = z.object({\n /**\n * Unique identifier for the rule\n */\n id: z.string().describe('Rule identifier'),\n \n /**\n * Rule name\n */\n name: z.string().describe('Rule name'),\n \n /**\n * Rule description\n */\n description: z.string().optional().describe('Rule description'),\n \n /**\n * Whether the rule is enabled\n */\n enabled: z.boolean().default(true).describe('Rule enabled status'),\n \n /**\n * Event types to monitor\n */\n eventTypes: z.array(AuditEventType).describe('Event types to monitor'),\n \n /**\n * Detection condition\n */\n condition: z.object({\n /**\n * Number of events that trigger the rule\n */\n threshold: z.number().int().positive().describe('Event threshold'),\n \n /**\n * Time window in seconds\n */\n windowSeconds: z.number().int().positive().describe('Time window in seconds'),\n \n /**\n * Grouping criteria (e.g., by actor.id, by ipAddress)\n */\n groupBy: z.array(z.string()).optional().describe('Grouping criteria'),\n \n /**\n * Additional filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters'),\n }).describe('Detection condition'),\n \n /**\n * Actions to take when rule is triggered\n */\n actions: z.array(z.enum([\n 'alert', // Send alert notification\n 'lock_account', // Lock the user account\n 'block_ip', // Block the IP address\n 'require_mfa', // Require multi-factor authentication\n 'log_critical', // Log as critical event\n 'webhook', // Call webhook\n ])).describe('Actions to take'),\n \n /**\n * Severity level for triggered alerts\n */\n alertSeverity: AuditEventSeverity.default('warning').describe('Alert severity'),\n \n /**\n * Notification configuration\n */\n notifications: z.object({\n /**\n * Email addresses to notify\n */\n email: z.array(z.string().email()).optional().describe('Email recipients'),\n \n /**\n * Slack webhook URL\n */\n slack: z.string().url().optional().describe('Slack webhook URL'),\n \n /**\n * Custom webhook URL\n */\n webhook: z.string().url().optional().describe('Custom webhook URL'),\n }).optional().describe('Notification configuration'),\n});\n\nexport type SuspiciousActivityRule = z.infer;\n\n/**\n * Audit Log Storage Configuration\n * Defines where and how audit logs are stored\n */\nexport const AuditStorageConfigSchema = z.object({\n /**\n * Storage backend type\n */\n type: z.enum([\n 'database', // Store in database (PostgreSQL, MySQL, etc.)\n 'elasticsearch', // Store in Elasticsearch\n 'mongodb', // Store in MongoDB\n 'clickhouse', // Store in ClickHouse (for analytics)\n 's3', // Store in S3-compatible storage\n 'gcs', // Store in Google Cloud Storage\n 'azure_blob', // Store in Azure Blob Storage\n 'custom', // Custom storage implementation\n ]).describe('Storage backend type'),\n \n /**\n * Connection string or configuration\n */\n connectionString: z.string().optional().describe('Connection string'),\n \n /**\n * Storage configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Storage-specific configuration'),\n \n /**\n * Whether to enable buffering/batching\n */\n bufferEnabled: z.boolean().default(true).describe('Enable buffering'),\n \n /**\n * Buffer size (number of events before flush)\n */\n bufferSize: z.number().int().positive().default(100).describe('Buffer size'),\n \n /**\n * Buffer flush interval in seconds\n */\n flushIntervalSeconds: z.number().int().positive().default(5).describe('Flush interval in seconds'),\n \n /**\n * Whether to compress stored data\n */\n compression: z.boolean().default(true).describe('Enable compression'),\n});\n\nexport type AuditStorageConfig = z.infer;\n\n/**\n * Audit Event Filter Schema\n * Defines filters for querying audit events\n */\nexport const AuditEventFilterSchema = z.object({\n /**\n * Filter by event types\n */\n eventTypes: z.array(AuditEventType).optional().describe('Event types to include'),\n \n /**\n * Filter by severity levels\n */\n severities: z.array(AuditEventSeverity).optional().describe('Severity levels to include'),\n \n /**\n * Filter by actor ID\n */\n actorId: z.string().optional().describe('Actor identifier'),\n \n /**\n * Filter by tenant ID\n */\n tenantId: z.string().optional().describe('Tenant identifier'),\n \n /**\n * Filter by time range\n */\n timeRange: z.object({\n from: z.string().datetime().describe('Start time'),\n to: z.string().datetime().describe('End time'),\n }).optional().describe('Time range filter'),\n \n /**\n * Filter by result status\n */\n result: z.enum(['success', 'failure', 'partial']).optional().describe('Result status'),\n \n /**\n * Search query (full-text search)\n */\n searchQuery: z.string().optional().describe('Search query'),\n \n /**\n * Custom filters\n */\n customFilters: z.record(z.string(), z.unknown()).optional().describe('Custom filters'),\n});\n\nexport type AuditEventFilter = z.infer;\n\n/**\n * Complete Audit Configuration Schema\n * Main configuration for the audit system\n */\nexport const AuditConfigSchema = z.object({\n /**\n * Unique identifier for this audit configuration\n * Must be in snake_case following ObjectStack conventions\n * Maximum length: 64 characters\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n \n /**\n * Human-readable label\n */\n label: z.string().describe('Display label'),\n \n /**\n * Whether audit logging is enabled\n */\n enabled: z.boolean().default(true).describe('Enable audit logging'),\n \n /**\n * Event types to audit\n * If not specified, all event types are audited\n */\n eventTypes: z.array(AuditEventType).optional().describe('Event types to audit'),\n \n /**\n * Event types to exclude from auditing\n */\n excludeEventTypes: z.array(AuditEventType).optional().describe('Event types to exclude'),\n \n /**\n * Minimum severity level to log\n * Events below this level are not logged\n */\n minimumSeverity: AuditEventSeverity.default('info').describe('Minimum severity level'),\n \n /**\n * Storage configuration\n */\n storage: AuditStorageConfigSchema.describe('Storage configuration'),\n \n /**\n * Retention policy\n */\n retentionPolicy: AuditRetentionPolicySchema.optional().describe('Retention policy'),\n \n /**\n * Suspicious activity detection rules\n */\n suspiciousActivityRules: z.array(SuspiciousActivityRuleSchema).default([]).describe('Suspicious activity rules'),\n \n /**\n * Whether to include sensitive data in audit logs\n * If false, sensitive fields are redacted/masked\n */\n includeSensitiveData: z.boolean().default(false).describe('Include sensitive data'),\n \n /**\n * Fields to redact from audit logs\n */\n redactFields: z.array(z.string()).default([\n 'password',\n 'passwordHash',\n 'token',\n 'apiKey',\n 'secret',\n 'creditCard',\n 'ssn',\n ]).describe('Fields to redact'),\n \n /**\n * Whether to log successful read operations\n * Can be disabled to reduce log volume\n */\n logReads: z.boolean().default(false).describe('Log read operations'),\n \n /**\n * Sampling rate for read operations (0.0 to 1.0)\n * Only applies if logReads is true\n */\n readSamplingRate: z.number().min(0).max(1).default(0.1).describe('Read sampling rate'),\n \n /**\n * Whether to log system/internal operations\n */\n logSystemEvents: z.boolean().default(true).describe('Log system events'),\n \n /**\n * Custom audit event handlers\n * Note: Function handlers are for runtime configuration only and will not be serialized to JSON Schema\n */\n customHandlers: z.array(z.object({\n eventType: AuditEventType.describe('Event type to handle'),\n handlerId: z.string().describe('Unique identifier for the handler'),\n })).optional().describe('Custom event handler references'),\n \n /**\n * Compliance mode configuration\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox', // Sarbanes-Oxley Act\n 'hipaa', // Health Insurance Portability and Accountability Act\n 'gdpr', // General Data Protection Regulation\n 'pci_dss', // Payment Card Industry Data Security Standard\n 'iso_27001',// ISO/IEC 27001\n 'fedramp', // Federal Risk and Authorization Management Program\n ])).optional().describe('Compliance standards'),\n \n /**\n * Whether to enforce immutable audit logs\n */\n immutableLogs: z.boolean().default(true).describe('Enforce immutable logs'),\n \n /**\n * Whether to require cryptographic signing\n */\n requireSigning: z.boolean().default(false).describe('Require log signing'),\n \n /**\n * Signing key configuration\n */\n signingKey: z.string().optional().describe('Signing key'),\n }).optional().describe('Compliance configuration'),\n});\n\nexport type AuditConfig = z.infer;\n\n/**\n * Default suspicious activity rules\n * Common security patterns to detect\n */\nexport const DEFAULT_SUSPICIOUS_ACTIVITY_RULES: SuspiciousActivityRule[] = [\n {\n id: 'multiple_failed_logins',\n name: 'Multiple Failed Login Attempts',\n description: 'Detects multiple failed login attempts from the same user or IP',\n enabled: true,\n eventTypes: ['auth.login_failed'],\n condition: {\n threshold: 5,\n windowSeconds: 600, // 10 minutes\n groupBy: ['actor.id', 'actor.ipAddress'],\n },\n actions: ['alert', 'lock_account'],\n alertSeverity: 'warning',\n },\n {\n id: 'bulk_data_export',\n name: 'Bulk Data Export',\n description: 'Detects large data export operations',\n enabled: true,\n eventTypes: ['data.export'],\n condition: {\n threshold: 3,\n windowSeconds: 3600, // 1 hour\n groupBy: ['actor.id'],\n },\n actions: ['alert', 'log_critical'],\n alertSeverity: 'warning',\n },\n {\n id: 'suspicious_permission_changes',\n name: 'Rapid Permission Changes',\n description: 'Detects rapid permission or role changes',\n enabled: true,\n eventTypes: ['authz.permission_granted', 'authz.role_assigned'],\n condition: {\n threshold: 10,\n windowSeconds: 300, // 5 minutes\n groupBy: ['actor.id'],\n },\n actions: ['alert', 'log_critical'],\n alertSeverity: 'critical',\n },\n {\n id: 'after_hours_access',\n name: 'After Hours Access',\n description: 'Detects access during non-business hours',\n enabled: false, // Disabled by default, requires time zone configuration\n eventTypes: ['auth.login'],\n condition: {\n threshold: 1,\n windowSeconds: 86400, // 24 hours\n },\n actions: ['alert'],\n alertSeverity: 'notice',\n },\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Logging Protocol - Comprehensive Observability Logging\n * \n * Unified logging protocol that combines:\n * - Basic kernel logging (LoggerConfig)\n * - Enterprise-grade features (LoggingConfig)\n * - Multiple log destinations (file, console, external services)\n * - Structured logging with enrichment\n * - Log aggregation and forwarding\n * - Integration with external log management systems\n */\n\n// ============================================================================\n// Basic Logger Protocol (formerly from logger.zod.ts)\n// ============================================================================\n\n/**\n * Log Level Enum\n * Standard RFC 5424 severity levels (simplified)\n */\nexport const LogLevel = z.enum([\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'fatal',\n 'silent'\n]).describe('Log severity level');\n\nexport type LogLevel = z.infer;\n\n/**\n * Log Format Enum\n */\nexport const LogFormat = z.enum([\n 'json', // Structured JSON for machine parsing\n 'text', // Simple text format\n 'pretty' // Colored human-readable output for CLI/console\n]).describe('Log output format');\n\nexport type LogFormat = z.infer;\n\n/**\n * Logger Configuration Schema\n * Configuration for the Kernel's internal logger\n */\nexport const LoggerConfigSchema = z.object({\n /**\n * Logger name\n */\n name: z.string().optional().describe('Logger name identifier'),\n\n /**\n * Minimum level to log\n */\n level: LogLevel.optional().default('info'),\n\n /**\n * Output format\n */\n format: LogFormat.optional().default('json'),\n\n /**\n * Redact sensitive keys\n */\n redact: z.array(z.string()).optional().default(['password', 'token', 'secret', 'key'])\n .describe('Keys to redact from log context'),\n\n /**\n * Enable source location (file/line)\n */\n sourceLocation: z.boolean().optional().default(false)\n .describe('Include file and line number'),\n\n /**\n * Log to file (optional)\n */\n file: z.string().optional().describe('Path to log file'),\n\n /**\n * Log rotation config (if file is set)\n */\n rotation: z.object({\n maxSize: z.string().optional().default('10m'),\n maxFiles: z.number().optional().default(5)\n }).optional()\n});\n\nexport type LoggerConfig = z.infer;\n\n/**\n * Log Entry Schema\n * The shape of a structured log record\n */\nexport const LogEntrySchema = z.object({\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n level: LogLevel,\n message: z.string().describe('Log message'),\n context: z.record(z.string(), z.unknown()).optional().describe('Structured context data'),\n error: z.record(z.string(), z.unknown()).optional().describe('Error object if present'),\n \n /** Tracing */\n traceId: z.string().optional().describe('Distributed trace ID'),\n spanId: z.string().optional().describe('Span ID'),\n \n /** Source */\n service: z.string().optional().describe('Service name'),\n component: z.string().optional().describe('Component name (e.g. plugin id)'),\n});\n\nexport type LogEntry = z.infer;\n\n// ============================================================================\n// Extended Logging Protocol (enterprise features)\n// ============================================================================\n\n/**\n * Extended Log Level Enum\n * Standard RFC 5424 severity levels with trace\n */\nexport const ExtendedLogLevel = z.enum([\n 'trace', // Very detailed debugging information\n 'debug', // Debugging information\n 'info', // Informational messages\n 'warn', // Warning messages\n 'error', // Error messages\n 'fatal', // Fatal errors causing shutdown\n]).describe('Extended log severity level');\n\nexport type ExtendedLogLevel = z.infer;\n\n/**\n * Log Destination Type Enum\n * Where logs can be sent\n */\nexport const LogDestinationType = z.enum([\n 'console', // Standard output/error\n 'file', // File system\n 'syslog', // System logger\n 'elasticsearch', // Elasticsearch\n 'cloudwatch', // AWS CloudWatch\n 'stackdriver', // Google Cloud Logging\n 'azure_monitor', // Azure Monitor\n 'datadog', // Datadog\n 'splunk', // Splunk\n 'loki', // Grafana Loki\n 'http', // HTTP endpoint\n 'kafka', // Apache Kafka\n 'redis', // Redis streams\n 'custom', // Custom implementation\n]).describe('Log destination type');\n\nexport type LogDestinationType = z.infer;\n\n/**\n * Console Destination Configuration\n */\nexport const ConsoleDestinationConfigSchema = z.object({\n /**\n * Output stream\n */\n stream: z.enum(['stdout', 'stderr']).optional().default('stdout'),\n\n /**\n * Enable colored output\n */\n colors: z.boolean().optional().default(true),\n\n /**\n * Pretty print JSON\n */\n prettyPrint: z.boolean().optional().default(false),\n}).describe('Console destination configuration');\n\nexport type ConsoleDestinationConfig = z.infer;\n\n/**\n * File Destination Configuration\n */\nexport const FileDestinationConfigSchema = z.object({\n /**\n * File path\n */\n path: z.string().describe('Log file path'),\n\n /**\n * Enable log rotation\n */\n rotation: z.object({\n /**\n * Maximum file size before rotation (e.g., '10m', '100k', '1g')\n */\n maxSize: z.string().optional().default('10m'),\n\n /**\n * Maximum number of files to keep\n */\n maxFiles: z.number().int().positive().optional().default(5),\n\n /**\n * Compress rotated files\n */\n compress: z.boolean().optional().default(true),\n\n /**\n * Rotation interval (e.g., 'daily', 'weekly')\n */\n interval: z.enum(['hourly', 'daily', 'weekly', 'monthly']).optional(),\n }).optional(),\n\n /**\n * File encoding\n */\n encoding: z.string().optional().default('utf8'),\n\n /**\n * Append to existing file\n */\n append: z.boolean().optional().default(true),\n}).describe('File destination configuration');\n\nexport type FileDestinationConfig = z.infer;\n\n/**\n * HTTP Destination Configuration\n */\nexport const HttpDestinationConfigSchema = z.object({\n /**\n * HTTP endpoint URL\n */\n url: z.string().url().describe('HTTP endpoint URL'),\n\n /**\n * HTTP method\n */\n method: z.enum(['POST', 'PUT']).optional().default('POST'),\n\n /**\n * Headers to include\n */\n headers: z.record(z.string(), z.string()).optional(),\n\n /**\n * Authentication\n */\n auth: z.object({\n type: z.enum(['basic', 'bearer', 'api_key']).describe('Auth type'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n apiKeyHeader: z.string().optional().default('X-API-Key'),\n }).optional(),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n /**\n * Maximum batch size\n */\n maxSize: z.number().int().positive().optional().default(100),\n\n /**\n * Flush interval in milliseconds\n */\n flushInterval: z.number().int().positive().optional().default(5000),\n }).optional(),\n\n /**\n * Retry configuration\n */\n retry: z.object({\n /**\n * Maximum retry attempts\n */\n maxAttempts: z.number().int().positive().optional().default(3),\n\n /**\n * Initial retry delay in milliseconds\n */\n initialDelay: z.number().int().positive().optional().default(1000),\n\n /**\n * Backoff multiplier\n */\n backoffMultiplier: z.number().positive().optional().default(2),\n }).optional(),\n\n /**\n * Timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().default(30000),\n}).describe('HTTP destination configuration');\n\nexport type HttpDestinationConfig = z.infer;\n\n/**\n * External Service Destination Configuration\n * Generic configuration for cloud logging services\n */\nexport const ExternalServiceDestinationConfigSchema = z.object({\n /**\n * Service-specific endpoint\n */\n endpoint: z.string().url().optional(),\n\n /**\n * Region (for cloud services)\n */\n region: z.string().optional(),\n\n /**\n * Credentials\n */\n credentials: z.object({\n accessKeyId: z.string().optional(),\n secretAccessKey: z.string().optional(),\n apiKey: z.string().optional(),\n projectId: z.string().optional(),\n }).optional(),\n\n /**\n * Log group/stream/index name\n */\n logGroup: z.string().optional(),\n logStream: z.string().optional(),\n index: z.string().optional(),\n\n /**\n * Service-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional(),\n}).describe('External service destination configuration');\n\nexport type ExternalServiceDestinationConfig = z.infer;\n\n/**\n * Log Destination Schema\n * Configuration for a single log destination\n */\nexport const LogDestinationSchema = z.object({\n /**\n * Destination name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Destination name (snake_case)'),\n\n /**\n * Destination type\n */\n type: LogDestinationType.describe('Destination type'),\n\n /**\n * Minimum log level for this destination\n */\n level: ExtendedLogLevel.optional().default('info'),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Console configuration\n */\n console: ConsoleDestinationConfigSchema.optional(),\n\n /**\n * File configuration\n */\n file: FileDestinationConfigSchema.optional(),\n\n /**\n * HTTP configuration\n */\n http: HttpDestinationConfigSchema.optional(),\n\n /**\n * External service configuration\n */\n externalService: ExternalServiceDestinationConfigSchema.optional(),\n\n /**\n * Format for this destination\n */\n format: z.enum(['json', 'text', 'pretty']).optional().default('json'),\n\n /**\n * Filter function reference (runtime only)\n */\n filterId: z.string().optional().describe('Filter function identifier'),\n}).describe('Log destination configuration');\n\nexport type LogDestination = z.infer;\n\n/**\n * Log Enrichment Configuration\n * Add contextual data to all log entries\n */\nexport const LogEnrichmentConfigSchema = z.object({\n /**\n * Static fields to add to all logs\n */\n staticFields: z.record(z.string(), z.unknown()).optional().describe('Static fields added to every log'),\n\n /**\n * Dynamic field enrichers (runtime only)\n * References to functions that add dynamic context\n */\n dynamicEnrichers: z.array(z.string()).optional().describe('Dynamic enricher function IDs'),\n\n /**\n * Add hostname\n */\n addHostname: z.boolean().optional().default(true),\n\n /**\n * Add process ID\n */\n addProcessId: z.boolean().optional().default(true),\n\n /**\n * Add environment info\n */\n addEnvironment: z.boolean().optional().default(true),\n\n /**\n * Add timestamp in additional formats\n */\n addTimestampFormats: z.object({\n unix: z.boolean().optional().default(false),\n iso: z.boolean().optional().default(true),\n }).optional(),\n\n /**\n * Add caller information (file, line, function)\n */\n addCaller: z.boolean().optional().default(false),\n\n /**\n * Add correlation IDs\n */\n addCorrelationIds: z.boolean().optional().default(true),\n}).describe('Log enrichment configuration');\n\nexport type LogEnrichmentConfig = z.infer;\n\n/**\n * Structured Log Entry Schema\n * Enhanced structured log record with enrichment\n */\nexport const StructuredLogEntrySchema = z.object({\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n\n /**\n * Log level\n */\n level: ExtendedLogLevel.describe('Log severity level'),\n\n /**\n * Log message\n */\n message: z.string().describe('Log message'),\n\n /**\n * Structured context data\n */\n context: z.record(z.string(), z.unknown()).optional().describe('Structured context'),\n\n /**\n * Error information\n */\n error: z.object({\n name: z.string().optional(),\n message: z.string().optional(),\n stack: z.string().optional(),\n code: z.string().optional(),\n details: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Error details'),\n\n /**\n * Trace context\n */\n trace: z.object({\n traceId: z.string().describe('Trace ID'),\n spanId: z.string().describe('Span ID'),\n parentSpanId: z.string().optional().describe('Parent span ID'),\n traceFlags: z.number().int().optional().describe('Trace flags'),\n }).optional().describe('Distributed tracing context'),\n\n /**\n * Source information\n */\n source: z.object({\n service: z.string().optional().describe('Service name'),\n component: z.string().optional().describe('Component name'),\n file: z.string().optional().describe('Source file'),\n line: z.number().int().optional().describe('Line number'),\n function: z.string().optional().describe('Function name'),\n }).optional().describe('Source information'),\n\n /**\n * Host information\n */\n host: z.object({\n hostname: z.string().optional(),\n pid: z.number().int().optional(),\n ip: z.string().optional(),\n }).optional().describe('Host information'),\n\n /**\n * Environment\n */\n environment: z.string().optional().describe('Environment (e.g., production, staging)'),\n\n /**\n * User information\n */\n user: z.object({\n id: z.string().optional(),\n username: z.string().optional(),\n email: z.string().optional(),\n }).optional().describe('User context'),\n\n /**\n * Request information\n */\n request: z.object({\n id: z.string().optional(),\n method: z.string().optional(),\n path: z.string().optional(),\n userAgent: z.string().optional(),\n ip: z.string().optional(),\n }).optional().describe('Request context'),\n\n /**\n * Custom labels/tags\n */\n labels: z.record(z.string(), z.string()).optional().describe('Custom labels'),\n\n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n}).describe('Structured log entry');\n\nexport type StructuredLogEntry = z.infer;\n\n/**\n * Logging Configuration Schema\n * Main configuration for the logging system\n */\nexport const LoggingConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable logging\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Global minimum log level\n */\n level: ExtendedLogLevel.optional().default('info'),\n\n /**\n * Default logger configuration\n * Basic logger config for the kernel\n */\n default: LoggerConfigSchema.optional().describe('Default logger configuration'),\n\n /**\n * Named logger configurations\n * Map of logger name to logger config for different components/modules\n */\n loggers: z.record(z.string(), LoggerConfigSchema).optional().describe('Named logger configurations'),\n\n /**\n * Log destinations\n */\n destinations: z.array(LogDestinationSchema).describe('Log destinations'),\n\n /**\n * Log enrichment configuration\n */\n enrichment: LogEnrichmentConfigSchema.optional(),\n\n /**\n * Fields to redact from logs\n */\n redact: z.array(z.string()).optional().default([\n 'password',\n 'passwordHash',\n 'token',\n 'apiKey',\n 'secret',\n 'creditCard',\n 'ssn',\n 'authorization',\n ]).describe('Fields to redact'),\n\n /**\n * Sampling configuration\n */\n sampling: z.object({\n /**\n * Enable sampling\n */\n enabled: z.boolean().optional().default(false),\n\n /**\n * Sample rate (0.0 to 1.0)\n */\n rate: z.number().min(0).max(1).optional().default(1.0),\n\n /**\n * Sample rate by level\n */\n rateByLevel: z.record(z.string(), z.number().min(0).max(1)).optional(),\n }).optional(),\n\n /**\n * Buffer configuration\n */\n buffer: z.object({\n /**\n * Enable buffering\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Buffer size\n */\n size: z.number().int().positive().optional().default(1000),\n\n /**\n * Flush interval in milliseconds\n */\n flushInterval: z.number().int().positive().optional().default(1000),\n\n /**\n * Flush on shutdown\n */\n flushOnShutdown: z.boolean().optional().default(true),\n }).optional(),\n\n /**\n * Performance configuration\n */\n performance: z.object({\n /**\n * Async logging\n */\n async: z.boolean().optional().default(true),\n\n /**\n * Worker threads for async logging\n */\n workers: z.number().int().positive().optional().default(1),\n }).optional(),\n}).describe('Logging configuration');\n\nexport type LoggingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metrics Protocol - Performance and Operational Metrics\n * \n * Comprehensive metrics collection and monitoring:\n * - Counter, Gauge, Histogram, Summary metric types\n * - Time-series data collection\n * - SLI/SLO definitions\n * - Metric aggregation and export\n * - Integration with monitoring systems (Prometheus, etc.)\n */\n\n/**\n * Metric Type Enum\n * Standard Prometheus metric types\n */\nexport const MetricType = z.enum([\n 'counter', // Monotonically increasing value\n 'gauge', // Value that can go up and down\n 'histogram', // Observations bucketed by configurable ranges\n 'summary', // Observations with quantiles\n]).describe('Metric type');\n\nexport type MetricType = z.infer;\n\n/**\n * Metric Unit Enum\n * Standard units for metrics\n */\nexport const MetricUnit = z.enum([\n // Time units\n 'nanoseconds',\n 'microseconds',\n 'milliseconds',\n 'seconds',\n 'minutes',\n 'hours',\n 'days',\n\n // Size units\n 'bytes',\n 'kilobytes',\n 'megabytes',\n 'gigabytes',\n 'terabytes',\n\n // Rate units\n 'requests_per_second',\n 'events_per_second',\n 'bytes_per_second',\n\n // Percentage\n 'percent',\n 'ratio',\n\n // Count\n 'count',\n 'operations',\n\n // Custom\n 'custom',\n]).describe('Metric unit');\n\nexport type MetricUnit = z.infer;\n\n/**\n * Metric Aggregation Type\n */\nexport const MetricAggregationType = z.enum([\n 'sum', // Sum of all values\n 'avg', // Average of all values\n 'min', // Minimum value\n 'max', // Maximum value\n 'count', // Count of observations\n 'p50', // 50th percentile (median)\n 'p75', // 75th percentile\n 'p90', // 90th percentile\n 'p95', // 95th percentile\n 'p99', // 99th percentile\n 'p999', // 99.9th percentile\n 'rate', // Rate of change\n 'stddev', // Standard deviation\n]).describe('Metric aggregation type');\n\nexport type MetricAggregationType = z.infer;\n\n/**\n * Histogram Bucket Configuration\n */\nexport const HistogramBucketConfigSchema = z.object({\n /**\n * Bucket type\n */\n type: z.enum(['linear', 'exponential', 'explicit']).describe('Bucket type'),\n\n /**\n * Linear bucket configuration\n */\n linear: z.object({\n start: z.number().describe('Start value'),\n width: z.number().positive().describe('Bucket width'),\n count: z.number().int().positive().describe('Number of buckets'),\n }).optional(),\n\n /**\n * Exponential bucket configuration\n */\n exponential: z.object({\n start: z.number().positive().describe('Start value'),\n factor: z.number().positive().describe('Growth factor'),\n count: z.number().int().positive().describe('Number of buckets'),\n }).optional(),\n\n /**\n * Explicit bucket boundaries\n */\n explicit: z.object({\n boundaries: z.array(z.number()).describe('Bucket boundaries'),\n }).optional(),\n}).describe('Histogram bucket configuration');\n\nexport type HistogramBucketConfig = z.infer;\n\n/**\n * Metric Labels Schema\n * Key-value pairs for metric dimensions\n */\nexport const MetricLabelsSchema = z.record(z.string(), z.string()).describe('Metric labels');\n\nexport type MetricLabels = z.infer;\n\n/**\n * Metric Definition Schema\n */\nexport const MetricDefinitionSchema = z.object({\n /**\n * Metric name (snake_case)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Metric name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().optional().describe('Display label'),\n\n /**\n * Metric type\n */\n type: MetricType.describe('Metric type'),\n\n /**\n * Metric unit\n */\n unit: MetricUnit.optional().describe('Metric unit'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('Metric description'),\n\n /**\n * Label names for this metric\n */\n labelNames: z.array(z.string()).optional().default([]).describe('Label names'),\n\n /**\n * Histogram configuration (for histogram type)\n */\n histogram: HistogramBucketConfigSchema.optional(),\n\n /**\n * Summary configuration (for summary type)\n */\n summary: z.object({\n /**\n * Quantiles to track\n */\n quantiles: z.array(z.number().min(0).max(1)).optional().default([0.5, 0.9, 0.99]),\n\n /**\n * Max age of observations in seconds\n */\n maxAge: z.number().int().positive().optional().default(600),\n\n /**\n * Number of age buckets\n */\n ageBuckets: z.number().int().positive().optional().default(5),\n }).optional(),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Metric definition');\n\nexport type MetricDefinition = z.infer;\n\n/**\n * Metric Data Point Schema\n * A single metric observation\n */\nexport const MetricDataPointSchema = z.object({\n /**\n * Metric name\n */\n name: z.string().describe('Metric name'),\n\n /**\n * Metric type\n */\n type: MetricType.describe('Metric type'),\n\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Observation timestamp'),\n\n /**\n * Value (for counter and gauge)\n */\n value: z.number().optional().describe('Metric value'),\n\n /**\n * Labels\n */\n labels: MetricLabelsSchema.optional().describe('Metric labels'),\n\n /**\n * Histogram data\n */\n histogram: z.object({\n count: z.number().int().nonnegative().describe('Total count'),\n sum: z.number().describe('Sum of all values'),\n buckets: z.array(z.object({\n upperBound: z.number().describe('Upper bound of bucket'),\n count: z.number().int().nonnegative().describe('Count in bucket'),\n })).describe('Histogram buckets'),\n }).optional(),\n\n /**\n * Summary data\n */\n summary: z.object({\n count: z.number().int().nonnegative().describe('Total count'),\n sum: z.number().describe('Sum of all values'),\n quantiles: z.array(z.object({\n quantile: z.number().min(0).max(1).describe('Quantile (0-1)'),\n value: z.number().describe('Quantile value'),\n })).describe('Summary quantiles'),\n }).optional(),\n}).describe('Metric data point');\n\nexport type MetricDataPoint = z.infer;\n\n/**\n * Time Series Data Point Schema\n */\nexport const TimeSeriesDataPointSchema = z.object({\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Timestamp'),\n\n /**\n * Value\n */\n value: z.number().describe('Value'),\n\n /**\n * Labels/tags\n */\n labels: z.record(z.string(), z.string()).optional().describe('Labels'),\n}).describe('Time series data point');\n\nexport type TimeSeriesDataPoint = z.infer;\n\n/**\n * Time Series Schema\n */\nexport const TimeSeriesSchema = z.object({\n /**\n * Series name\n */\n name: z.string().describe('Series name'),\n\n /**\n * Series labels\n */\n labels: z.record(z.string(), z.string()).optional().describe('Series labels'),\n\n /**\n * Data points\n */\n dataPoints: z.array(TimeSeriesDataPointSchema).describe('Data points'),\n\n /**\n * Start time\n */\n startTime: z.string().datetime().optional().describe('Start time'),\n\n /**\n * End time\n */\n endTime: z.string().datetime().optional().describe('End time'),\n}).describe('Time series');\n\nexport type TimeSeries = z.infer;\n\n/**\n * Metric Aggregation Configuration\n */\nexport const MetricAggregationConfigSchema = z.object({\n /**\n * Aggregation type\n */\n type: MetricAggregationType.describe('Aggregation type'),\n\n /**\n * Time window for aggregation\n */\n window: z.object({\n /**\n * Window size in seconds\n */\n size: z.number().int().positive().describe('Window size in seconds'),\n\n /**\n * Sliding window (true) or tumbling window (false)\n */\n sliding: z.boolean().optional().default(false),\n\n /**\n * Slide interval for sliding windows\n */\n slideInterval: z.number().int().positive().optional(),\n }).optional(),\n\n /**\n * Group by labels\n */\n groupBy: z.array(z.string()).optional().describe('Group by label names'),\n\n /**\n * Filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter criteria'),\n}).describe('Metric aggregation configuration');\n\nexport type MetricAggregationConfig = z.infer;\n\n/**\n * Service Level Indicator (SLI) Schema\n */\nexport const ServiceLevelIndicatorSchema = z.object({\n /**\n * SLI name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('SLI name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('SLI description'),\n\n /**\n * Metric name this SLI is based on\n */\n metric: z.string().describe('Base metric name'),\n\n /**\n * SLI type\n */\n type: z.enum([\n 'availability', // Percentage of successful requests\n 'latency', // Response time percentile\n 'throughput', // Requests per second\n 'error_rate', // Error percentage\n 'saturation', // Resource utilization\n 'custom', // Custom calculation\n ]).describe('SLI type'),\n\n /**\n * Success criteria\n */\n successCriteria: z.object({\n /**\n * Threshold value\n */\n threshold: z.number().describe('Threshold value'),\n\n /**\n * Comparison operator\n */\n operator: z.enum(['lt', 'lte', 'gt', 'gte', 'eq']).describe('Comparison operator'),\n\n /**\n * Percentile (for latency SLIs)\n */\n percentile: z.number().min(0).max(1).optional().describe('Percentile (0-1)'),\n }).describe('Success criteria'),\n\n /**\n * Measurement window\n */\n window: z.object({\n /**\n * Window size in seconds\n */\n size: z.number().int().positive().describe('Window size in seconds'),\n\n /**\n * Rolling window (true) or calendar-aligned (false)\n */\n rolling: z.boolean().optional().default(true),\n }).describe('Measurement window'),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Service Level Indicator');\n\nexport type ServiceLevelIndicator = z.infer;\n\n/**\n * Service Level Objective (SLO) Schema\n */\nexport const ServiceLevelObjectiveSchema = z.object({\n /**\n * SLO name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('SLO name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('SLO description'),\n\n /**\n * SLI this SLO is based on\n */\n sli: z.string().describe('SLI name'),\n\n /**\n * Target percentage (0-100)\n */\n target: z.number().min(0).max(100).describe('Target percentage'),\n\n /**\n * Time period for SLO\n */\n period: z.object({\n /**\n * Period type\n */\n type: z.enum(['rolling', 'calendar']).describe('Period type'),\n\n /**\n * Duration in seconds (for rolling)\n */\n duration: z.number().int().positive().optional().describe('Duration in seconds'),\n\n /**\n * Calendar period (for calendar)\n */\n calendar: z.enum(['daily', 'weekly', 'monthly', 'quarterly', 'yearly']).optional(),\n }).describe('Time period'),\n\n /**\n * Error budget configuration\n */\n errorBudget: z.object({\n /**\n * Auto-calculated budget (1 - target)\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Alert when budget consumed percentage exceeds threshold\n */\n alertThreshold: z.number().min(0).max(100).optional().default(80),\n\n /**\n * Burn rate alert windows\n */\n burnRateWindows: z.array(z.object({\n /**\n * Window size in seconds\n */\n window: z.number().int().positive().describe('Window size'),\n\n /**\n * Burn rate multiplier threshold\n */\n threshold: z.number().positive().describe('Burn rate threshold'),\n })).optional(),\n }).optional(),\n\n /**\n * Alert configuration\n */\n alerts: z.array(z.object({\n /**\n * Alert name\n */\n name: z.string().describe('Alert name'),\n\n /**\n * Severity\n */\n severity: z.enum(['info', 'warning', 'critical']).describe('Alert severity'),\n\n /**\n * Condition\n */\n condition: z.object({\n type: z.enum(['slo_breach', 'error_budget', 'burn_rate']).describe('Condition type'),\n threshold: z.number().optional().describe('Threshold value'),\n }).describe('Alert condition'),\n })).optional().default([]),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Service Level Objective');\n\nexport type ServiceLevelObjective = z.infer;\n\n/**\n * Metric Export Configuration\n */\nexport const MetricExportConfigSchema = z.object({\n /**\n * Export type\n */\n type: z.enum([\n 'prometheus', // Prometheus exposition format\n 'openmetrics', // OpenMetrics format\n 'graphite', // Graphite plaintext protocol\n 'statsd', // StatsD protocol\n 'influxdb', // InfluxDB line protocol\n 'datadog', // Datadog agent\n 'cloudwatch', // AWS CloudWatch\n 'stackdriver', // Google Cloud Monitoring\n 'azure_monitor', // Azure Monitor\n 'http', // HTTP push\n 'custom', // Custom exporter\n ]).describe('Export type'),\n\n /**\n * Endpoint configuration\n */\n endpoint: z.string().optional().describe('Export endpoint'),\n\n /**\n * Export interval in seconds\n */\n interval: z.number().int().positive().optional().default(60),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n enabled: z.boolean().optional().default(true),\n size: z.number().int().positive().optional().default(1000),\n }).optional(),\n\n /**\n * Authentication\n */\n auth: z.object({\n type: z.enum(['none', 'basic', 'bearer', 'api_key']).describe('Auth type'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n }).optional(),\n\n /**\n * Additional configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Additional configuration'),\n}).describe('Metric export configuration');\n\nexport type MetricExportConfig = z.infer;\n\n/**\n * Metrics Configuration Schema\n */\nexport const MetricsConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable metrics collection\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Metric definitions\n */\n metrics: z.array(MetricDefinitionSchema).optional().default([]),\n\n /**\n * Default labels applied to all metrics\n */\n defaultLabels: MetricLabelsSchema.optional().default({}),\n\n /**\n * Aggregation configurations\n */\n aggregations: z.array(MetricAggregationConfigSchema).optional().default([]),\n\n /**\n * Service Level Indicators\n */\n slis: z.array(ServiceLevelIndicatorSchema).optional().default([]),\n\n /**\n * Service Level Objectives\n */\n slos: z.array(ServiceLevelObjectiveSchema).optional().default([]),\n\n /**\n * Export configurations\n */\n exports: z.array(MetricExportConfigSchema).optional().default([]),\n\n /**\n * Collection interval in seconds\n */\n collectionInterval: z.number().int().positive().optional().default(15),\n\n /**\n * Retention configuration\n */\n retention: z.object({\n /**\n * Retention period in seconds\n */\n period: z.number().int().positive().optional().default(604800), // 7 days\n\n /**\n * Downsampling configuration\n */\n downsampling: z.array(z.object({\n /**\n * After this duration, downsample to this resolution\n */\n afterSeconds: z.number().int().positive().describe('Downsample after seconds'),\n\n /**\n * Resolution in seconds\n */\n resolution: z.number().int().positive().describe('Downsampled resolution'),\n })).optional(),\n }).optional(),\n\n /**\n * Cardinality limits\n */\n cardinalityLimits: z.object({\n /**\n * Maximum unique label combinations per metric\n */\n maxLabelCombinations: z.number().int().positive().optional().default(10000),\n\n /**\n * Action when limit exceeded\n */\n onLimitExceeded: z.enum(['drop', 'sample', 'alert']).optional().default('alert'),\n }).optional(),\n}).describe('Metrics configuration');\n\nexport type MetricsConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tracing Protocol - Distributed Tracing & Observability\n * \n * Comprehensive distributed tracing based on OpenTelemetry standards:\n * - Trace context propagation\n * - Span creation and management\n * - Sampling strategies\n * - Integration with tracing backends (Jaeger, Zipkin, etc.)\n * - W3C Trace Context standard compliance\n */\n\n/**\n * Trace State Schema\n * W3C Trace Context tracestate header\n */\nexport const TraceStateSchema = z.object({\n /**\n * Vendor-specific key-value pairs\n */\n entries: z.record(z.string(), z.string()).describe('Trace state entries'),\n}).describe('Trace state');\n\nexport type TraceState = z.infer;\n\n/**\n * Trace Flags Enum\n * W3C Trace Context trace flags\n */\nexport const TraceFlagsSchema = z.number().int().min(0).max(255).describe('Trace flags bitmap');\n\nexport type TraceFlags = z.infer;\n\n/**\n * Trace Context Schema\n * W3C Trace Context standard\n */\nexport const TraceContextSchema = z.object({\n /**\n * Trace ID (128-bit identifier, 32 hex chars)\n */\n traceId: z.string()\n .regex(/^[0-9a-f]{32}$/)\n .describe('Trace ID (32 hex chars)'),\n\n /**\n * Span ID (64-bit identifier, 16 hex chars)\n */\n spanId: z.string()\n .regex(/^[0-9a-f]{16}$/)\n .describe('Span ID (16 hex chars)'),\n\n /**\n * Trace flags (8-bit)\n */\n traceFlags: TraceFlagsSchema.optional().default(1),\n\n /**\n * Trace state (vendor-specific)\n */\n traceState: TraceStateSchema.optional(),\n\n /**\n * Parent span ID\n */\n parentSpanId: z.string()\n .regex(/^[0-9a-f]{16}$/)\n .optional()\n .describe('Parent span ID (16 hex chars)'),\n\n /**\n * Is sampled\n */\n sampled: z.boolean().optional().default(true),\n\n /**\n * Remote context (from incoming request)\n */\n remote: z.boolean().optional().default(false),\n}).describe('Trace context (W3C Trace Context)');\n\nexport type TraceContext = z.infer;\n\n/**\n * Span Kind Enum\n * OpenTelemetry span kinds\n */\nexport const SpanKind = z.enum([\n 'internal', // Internal operation\n 'server', // Server-side request handling\n 'client', // Client-side request\n 'producer', // Message producer\n 'consumer', // Message consumer\n]).describe('Span kind');\n\nexport type SpanKind = z.infer;\n\n/**\n * Span Status Enum\n * OpenTelemetry span status\n */\nexport const SpanStatus = z.enum([\n 'unset', // Default status\n 'ok', // Successful operation\n 'error', // Error occurred\n]).describe('Span status');\n\nexport type SpanStatus = z.infer;\n\n/**\n * Span Attribute Value Schema\n */\nexport const SpanAttributeValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.array(z.string()),\n z.array(z.number()),\n z.array(z.boolean()),\n]).describe('Span attribute value');\n\nexport type SpanAttributeValue = z.infer;\n\n/**\n * Span Attributes Schema\n * OpenTelemetry semantic conventions\n */\nexport const SpanAttributesSchema = z.record(z.string(), SpanAttributeValueSchema).describe('Span attributes');\n\nexport type SpanAttributes = z.infer;\n\n/**\n * Span Event Schema\n */\nexport const SpanEventSchema = z.object({\n /**\n * Event name\n */\n name: z.string().describe('Event name'),\n\n /**\n * Event timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /**\n * Event attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Event attributes'),\n}).describe('Span event');\n\nexport type SpanEvent = z.infer;\n\n/**\n * Span Link Schema\n * Links to other spans\n */\nexport const SpanLinkSchema = z.object({\n /**\n * Linked trace context\n */\n context: TraceContextSchema.describe('Linked trace context'),\n\n /**\n * Link attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Link attributes'),\n}).describe('Span link');\n\nexport type SpanLink = z.infer;\n\n/**\n * Span Schema\n * OpenTelemetry span representation\n */\nexport const SpanSchema = z.object({\n /**\n * Trace context\n */\n context: TraceContextSchema.describe('Trace context'),\n\n /**\n * Span name\n */\n name: z.string().describe('Span name'),\n\n /**\n * Span kind\n */\n kind: SpanKind.optional().default('internal'),\n\n /**\n * Start time (ISO 8601)\n */\n startTime: z.string().datetime().describe('Span start time'),\n\n /**\n * End time (ISO 8601)\n */\n endTime: z.string().datetime().optional().describe('Span end time'),\n\n /**\n * Duration in milliseconds\n */\n duration: z.number().nonnegative().optional().describe('Duration in milliseconds'),\n\n /**\n * Span status\n */\n status: z.object({\n code: SpanStatus.describe('Status code'),\n message: z.string().optional().describe('Status message'),\n }).optional(),\n\n /**\n * Span attributes\n */\n attributes: SpanAttributesSchema.optional().default({}),\n\n /**\n * Span events\n */\n events: z.array(SpanEventSchema).optional().default([]),\n\n /**\n * Span links\n */\n links: z.array(SpanLinkSchema).optional().default([]),\n\n /**\n * Resource attributes\n */\n resource: SpanAttributesSchema.optional().describe('Resource attributes'),\n\n /**\n * Instrumentation library\n */\n instrumentationLibrary: z.object({\n name: z.string().describe('Library name'),\n version: z.string().optional().describe('Library version'),\n }).optional(),\n}).describe('OpenTelemetry span');\n\nexport type Span = z.infer;\n\n/**\n * Sampling Decision Enum\n */\nexport const SamplingDecision = z.enum([\n 'drop', // Do not record or export\n 'record_only', // Record but do not export\n 'record_and_sample', // Record and export\n]).describe('Sampling decision');\n\nexport type SamplingDecision = z.infer;\n\n/**\n * Sampling Strategy Type Enum\n */\nexport const SamplingStrategyType = z.enum([\n 'always_on', // Always sample\n 'always_off', // Never sample\n 'trace_id_ratio', // Sample based on trace ID ratio\n 'rate_limiting', // Rate-limited sampling\n 'parent_based', // Respect parent span sampling decision\n 'probability', // Probability-based sampling\n 'composite', // Combine multiple strategies\n 'custom', // Custom sampling logic\n]).describe('Sampling strategy type');\n\nexport type SamplingStrategyType = z.infer;\n\n/**\n * Trace Sampling Configuration Schema\n */\nexport const TraceSamplingConfigSchema = z.object({\n /**\n * Sampling strategy type\n */\n type: SamplingStrategyType.describe('Sampling strategy'),\n\n /**\n * Sample ratio (0.0 to 1.0) for trace_id_ratio and probability strategies\n */\n ratio: z.number().min(0).max(1).optional().describe('Sample ratio (0-1)'),\n\n /**\n * Rate limit (traces per second) for rate_limiting strategy\n */\n rateLimit: z.number().positive().optional().describe('Traces per second'),\n\n /**\n * Parent-based configuration\n */\n parentBased: z.object({\n /**\n * Sampler to use when parent is sampled\n */\n whenParentSampled: SamplingStrategyType.optional().default('always_on'),\n\n /**\n * Sampler to use when parent is not sampled\n */\n whenParentNotSampled: SamplingStrategyType.optional().default('always_off'),\n\n /**\n * Sampler to use when there is no parent (root span)\n */\n root: SamplingStrategyType.optional().default('trace_id_ratio'),\n\n /**\n * Root sampler ratio\n */\n rootRatio: z.number().min(0).max(1).optional().default(0.1),\n }).optional(),\n\n /**\n * Composite sampling (multiple strategies)\n */\n composite: z.array(z.object({\n strategy: SamplingStrategyType.describe('Strategy type'),\n ratio: z.number().min(0).max(1).optional(),\n condition: z.record(z.string(), z.unknown()).optional().describe('Condition for this strategy'),\n })).optional(),\n\n /**\n * Sampling rules\n */\n rules: z.array(z.object({\n /**\n * Rule name\n */\n name: z.string().describe('Rule name'),\n\n /**\n * Match condition\n */\n match: z.object({\n /**\n * Service name pattern\n */\n service: z.string().optional(),\n\n /**\n * Span name pattern (regex)\n */\n spanName: z.string().optional(),\n\n /**\n * Attribute filters\n */\n attributes: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n\n /**\n * Sampling decision for matching spans\n */\n decision: SamplingDecision.describe('Sampling decision'),\n\n /**\n * Sample rate for this rule\n */\n rate: z.number().min(0).max(1).optional(),\n })).optional().default([]),\n\n /**\n * Custom sampler ID (for custom strategy)\n */\n customSamplerId: z.string().optional().describe('Custom sampler identifier'),\n}).describe('Trace sampling configuration');\n\nexport type TraceSamplingConfig = z.infer;\n\n/**\n * Trace Context Propagation Format Enum\n */\nexport const TracePropagationFormat = z.enum([\n 'w3c', // W3C Trace Context\n 'b3', // Zipkin B3 (single header)\n 'b3_multi', // Zipkin B3 (multi header)\n 'jaeger', // Jaeger propagation\n 'xray', // AWS X-Ray\n 'ottrace', // OpenTracing\n 'custom', // Custom format\n]).describe('Trace propagation format');\n\nexport type TracePropagationFormat = z.infer;\n\n/**\n * Trace Context Propagation Schema\n */\nexport const TraceContextPropagationSchema = z.object({\n /**\n * Propagation formats (in priority order)\n */\n formats: z.array(TracePropagationFormat).optional().default(['w3c']),\n\n /**\n * Extract context from incoming requests\n */\n extract: z.boolean().optional().default(true),\n\n /**\n * Inject context into outgoing requests\n */\n inject: z.boolean().optional().default(true),\n\n /**\n * Custom header mappings\n */\n headers: z.object({\n /**\n * Trace ID header name\n */\n traceId: z.string().optional(),\n\n /**\n * Span ID header name\n */\n spanId: z.string().optional(),\n\n /**\n * Trace flags header name\n */\n traceFlags: z.string().optional(),\n\n /**\n * Trace state header name\n */\n traceState: z.string().optional(),\n }).optional(),\n\n /**\n * Baggage propagation\n */\n baggage: z.object({\n /**\n * Enable baggage propagation\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Maximum baggage size in bytes\n */\n maxSize: z.number().int().positive().optional().default(8192),\n\n /**\n * Allowed baggage keys (whitelist)\n */\n allowedKeys: z.array(z.string()).optional(),\n }).optional(),\n}).describe('Trace context propagation');\n\nexport type TraceContextPropagation = z.infer;\n\n/**\n * OpenTelemetry Exporter Type Enum\n */\nexport const OtelExporterType = z.enum([\n 'otlp_http', // OTLP over HTTP\n 'otlp_grpc', // OTLP over gRPC\n 'jaeger', // Jaeger\n 'zipkin', // Zipkin\n 'console', // Console (for debugging)\n 'datadog', // Datadog\n 'honeycomb', // Honeycomb\n 'lightstep', // Lightstep\n 'newrelic', // New Relic\n 'custom', // Custom exporter\n]).describe('OpenTelemetry exporter type');\n\nexport type OtelExporterType = z.infer;\n\n/**\n * OpenTelemetry Compatibility Schema\n */\nexport const OpenTelemetryCompatibilitySchema = z.object({\n /**\n * OpenTelemetry SDK version\n */\n sdkVersion: z.string().optional().describe('OTel SDK version'),\n\n /**\n * Exporter configuration\n */\n exporter: z.object({\n /**\n * Exporter type\n */\n type: OtelExporterType.describe('Exporter type'),\n\n /**\n * Endpoint URL\n */\n endpoint: z.string().url().optional().describe('Exporter endpoint'),\n\n /**\n * Protocol version\n */\n protocol: z.string().optional().describe('Protocol version'),\n\n /**\n * Headers\n */\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n\n /**\n * Timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().default(10000),\n\n /**\n * Compression\n */\n compression: z.enum(['none', 'gzip']).optional().default('none'),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n /**\n * Maximum batch size\n */\n maxBatchSize: z.number().int().positive().optional().default(512),\n\n /**\n * Maximum queue size\n */\n maxQueueSize: z.number().int().positive().optional().default(2048),\n\n /**\n * Export timeout in milliseconds\n */\n exportTimeout: z.number().int().positive().optional().default(30000),\n\n /**\n * Scheduled delay in milliseconds\n */\n scheduledDelay: z.number().int().positive().optional().default(5000),\n }).optional(),\n }).describe('Exporter configuration'),\n\n /**\n * Resource attributes (service identification)\n */\n resource: z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Service name'),\n\n /**\n * Service version\n */\n serviceVersion: z.string().optional().describe('Service version'),\n\n /**\n * Service instance ID\n */\n serviceInstanceId: z.string().optional().describe('Service instance ID'),\n\n /**\n * Service namespace\n */\n serviceNamespace: z.string().optional().describe('Service namespace'),\n\n /**\n * Deployment environment\n */\n deploymentEnvironment: z.string().optional().describe('Deployment environment'),\n\n /**\n * Additional resource attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Additional resource attributes'),\n }).describe('Resource attributes'),\n\n /**\n * Instrumentation configuration\n */\n instrumentation: z.object({\n /**\n * Auto-instrumentation enabled\n */\n autoInstrumentation: z.boolean().optional().default(true),\n\n /**\n * Instrumentation libraries to enable\n */\n libraries: z.array(z.string()).optional().describe('Enabled libraries'),\n\n /**\n * Instrumentation libraries to disable\n */\n disabledLibraries: z.array(z.string()).optional().describe('Disabled libraries'),\n }).optional(),\n\n /**\n * Semantic conventions version\n */\n semanticConventionsVersion: z.string().optional().describe('Semantic conventions version'),\n}).describe('OpenTelemetry compatibility configuration');\n\nexport type OpenTelemetryCompatibility = z.infer;\n\n/**\n * Tracing Configuration Schema\n */\nexport const TracingConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable tracing\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Sampling configuration\n */\n sampling: TraceSamplingConfigSchema.optional().default({ type: 'always_on', rules: [] }),\n\n /**\n * Context propagation\n */\n propagation: TraceContextPropagationSchema.optional().default({ formats: ['w3c'], extract: true, inject: true }),\n\n /**\n * OpenTelemetry configuration\n */\n openTelemetry: OpenTelemetryCompatibilitySchema.optional(),\n\n /**\n * Span limits\n */\n spanLimits: z.object({\n /**\n * Maximum number of attributes per span\n */\n maxAttributes: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum number of events per span\n */\n maxEvents: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum number of links per span\n */\n maxLinks: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum attribute value length\n */\n maxAttributeValueLength: z.number().int().positive().optional().default(4096),\n }).optional(),\n\n /**\n * Trace ID generator\n */\n traceIdGenerator: z.enum(['random', 'uuid', 'custom']).optional().default('random'),\n\n /**\n * Custom trace ID generator ID\n */\n customTraceIdGeneratorId: z.string().optional().describe('Custom generator identifier'),\n\n /**\n * Performance configuration\n */\n performance: z.object({\n /**\n * Async span export\n */\n asyncExport: z.boolean().optional().default(true),\n\n /**\n * Background export interval in milliseconds\n */\n exportInterval: z.number().int().positive().optional().default(5000),\n }).optional(),\n}).describe('Tracing configuration');\n\nexport type TracingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Security Context Protocol\n *\n * Provides a central governance layer that correlates and unifies\n * the four independent security subsystems:\n * - **Audit** (audit.zod.ts): Event logging and suspicious activity detection\n * - **Encryption** (encryption.zod.ts): Field-level encryption and key management\n * - **Compliance** (compliance.zod.ts): Regulatory framework enforcement (GDPR/HIPAA/SOX/PCI-DSS)\n * - **Masking** (masking.zod.ts): PII data masking and tokenization\n *\n * This schema enforces cross-cutting security policies, ensuring compliance\n * frameworks drive encryption requirements, masking rules respect role-based\n * audit visibility, and all security operations are correlated in a single\n * governance context.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Shared data classification enum used across security subsystems.\n * Defines the canonical set of data sensitivity labels.\n */\nexport const DataClassificationSchema = z.enum([\n 'pii', 'phi', 'pci', 'financial', 'confidential', 'internal', 'public',\n]).describe('Data classification level');\n\nexport type DataClassification = z.infer;\n\n/**\n * Shared compliance framework enum used across compliance and security schemas.\n * Defines the canonical set of regulatory frameworks.\n */\nexport const ComplianceFrameworkSchema = z.enum([\n 'gdpr', 'hipaa', 'sox', 'pci_dss', 'ccpa', 'iso27001',\n]).describe('Compliance framework identifier');\n\nexport type ComplianceFramework = z.infer;\n\n/**\n * Compliance-driven audit requirement.\n * Maps specific compliance frameworks to the audit event types that MUST be captured.\n */\nexport const ComplianceAuditRequirementSchema = z.object({\n framework: ComplianceFrameworkSchema\n .describe('Compliance framework identifier'),\n requiredEvents: z.array(z.string())\n .describe('Audit event types required by this framework (e.g., \"data.delete\", \"auth.login\")'),\n retentionDays: z.number().min(1)\n .describe('Minimum audit log retention period required by this framework (in days)'),\n alertOnMissing: z.boolean().default(true)\n .describe('Raise alert if a required audit event is not being captured'),\n}).describe('Compliance framework audit event requirements');\n\nexport type ComplianceAuditRequirement = z.infer;\n\n/**\n * Compliance-driven encryption requirement.\n * Maps compliance frameworks to encryption mandates for specific data classifications.\n */\nexport const ComplianceEncryptionRequirementSchema = z.object({\n framework: ComplianceFrameworkSchema\n .describe('Compliance framework identifier'),\n dataClassifications: z.array(DataClassificationSchema)\n .describe('Data classifications that must be encrypted under this framework'),\n minimumAlgorithm: z.enum(['aes-256-gcm', 'aes-256-cbc', 'chacha20-poly1305']).default('aes-256-gcm')\n .describe('Minimum encryption algorithm strength required'),\n keyRotationMaxDays: z.number().min(1).default(90)\n .describe('Maximum key rotation interval required (in days)'),\n}).describe('Compliance framework encryption requirements');\n\nexport type ComplianceEncryptionRequirement = z.infer;\n\n/**\n * Masking visibility rule.\n * Controls which roles can view unmasked data with audit trail enforcement.\n */\nexport const MaskingVisibilityRuleSchema = z.object({\n dataClassification: DataClassificationSchema\n .describe('Data classification this rule applies to'),\n defaultMasked: z.boolean().default(true)\n .describe('Whether data is masked by default'),\n unmaskRoles: z.array(z.string()).optional()\n .describe('Roles allowed to view unmasked data'),\n auditUnmask: z.boolean().default(true)\n .describe('Log an audit event when data is unmasked'),\n requireApproval: z.boolean().default(false)\n .describe('Require explicit approval before unmasking'),\n approvalRoles: z.array(z.string()).optional()\n .describe('Roles that can approve unmasking requests'),\n}).describe('Masking visibility and audit rule per data classification');\n\nexport type MaskingVisibilityRule = z.infer;\n\n/**\n * Security Event Correlation Schema.\n * Defines how security events from different subsystems are correlated.\n */\nexport const SecurityEventCorrelationSchema = z.object({\n enabled: z.boolean().default(true)\n .describe('Enable cross-subsystem security event correlation'),\n correlationId: z.boolean().default(true)\n .describe('Inject a shared correlation ID into audit, encryption, and masking events'),\n linkAuthToAudit: z.boolean().default(true)\n .describe('Link authentication events to subsequent data operation audit trails'),\n linkEncryptionToAudit: z.boolean().default(true)\n .describe('Log encryption/decryption operations in the audit trail'),\n linkMaskingToAudit: z.boolean().default(true)\n .describe('Log masking/unmasking operations in the audit trail'),\n}).describe('Cross-subsystem security event correlation configuration');\n\nexport type SecurityEventCorrelation = z.infer;\n\n/**\n * Data Classification Policy Schema.\n * Assigns classification labels to fields/objects for unified security enforcement.\n */\nexport const DataClassificationPolicySchema = z.object({\n classification: DataClassificationSchema\n .describe('Data classification level'),\n requireEncryption: z.boolean().default(false)\n .describe('Encryption required for this classification'),\n requireMasking: z.boolean().default(false)\n .describe('Masking required for this classification'),\n requireAudit: z.boolean().default(false)\n .describe('Audit trail required for access to this classification'),\n retentionDays: z.number().optional()\n .describe('Data retention limit in days (for compliance)'),\n}).describe('Security policy for a specific data classification level');\n\nexport type DataClassificationPolicy = z.infer;\n\n/**\n * Security Context Configuration Schema\n *\n * Top-level unified security governance context that ties together\n * audit, encryption, compliance, and masking subsystems.\n */\nexport const SecurityContextConfigSchema = z.object({\n enabled: z.boolean().default(true)\n .describe('Enable unified security context governance'),\n\n complianceAuditRequirements: z.array(ComplianceAuditRequirementSchema).optional()\n .describe('Compliance-driven audit event requirements'),\n\n complianceEncryptionRequirements: z.array(ComplianceEncryptionRequirementSchema).optional()\n .describe('Compliance-driven encryption requirements by data classification'),\n\n maskingVisibility: z.array(MaskingVisibilityRuleSchema).optional()\n .describe('Masking visibility rules per data classification'),\n\n dataClassifications: z.array(DataClassificationPolicySchema).optional()\n .describe('Data classification policies for unified security enforcement'),\n\n eventCorrelation: SecurityEventCorrelationSchema.optional()\n .describe('Cross-subsystem security event correlation settings'),\n\n enforceOnWrite: z.boolean().default(true)\n .describe('Enforce encryption and masking requirements on data write operations'),\n\n enforceOnRead: z.boolean().default(true)\n .describe('Enforce masking and audit requirements on data read operations'),\n\n failOpen: z.boolean().default(false)\n .describe('When false (default), deny access if security context cannot be evaluated'),\n}).describe('Unified security context governance configuration');\n\nexport type SecurityContextConfig = z.infer;\nexport type SecurityContextConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Change Type Enum\n * \n * Classification of change requests based on risk and approval requirements.\n * Follows ITIL change management best practices.\n */\nexport const ChangeTypeSchema = z.enum([\n 'standard', // Pre-approved, low-risk changes\n 'normal', // Requires standard approval process\n 'emergency', // Fast-track approval for critical issues\n 'major', // Requires CAB (Change Advisory Board) approval\n]);\n\n/**\n * Change Priority Enum\n * \n * Priority level for change request processing.\n */\nexport const ChangePrioritySchema = z.enum([\n 'critical',\n 'high',\n 'medium',\n 'low',\n]);\n\n/**\n * Change Status Enum\n * \n * Current status of a change request in its lifecycle.\n */\nexport const ChangeStatusSchema = z.enum([\n 'draft',\n 'submitted',\n 'in-review',\n 'approved',\n 'scheduled',\n 'in-progress',\n 'completed',\n 'failed',\n 'rolled-back',\n 'cancelled',\n]);\n\n/**\n * Change Impact Schema\n * \n * Assessment of the impact and scope of a change request.\n * Used for risk evaluation and approval routing.\n * \n * @example\n * ```json\n * {\n * \"level\": \"high\",\n * \"affectedSystems\": [\"crm-api\", \"customer-portal\"],\n * \"affectedUsers\": 5000,\n * \"downtime\": {\n * \"required\": true,\n * \"durationMinutes\": 30\n * }\n * }\n * ```\n */\nexport const ChangeImpactSchema = z.object({\n /**\n * Overall impact level of the change\n */\n level: z.enum(['low', 'medium', 'high', 'critical']).describe('Impact level'),\n\n /**\n * List of systems affected by this change\n */\n affectedSystems: z.array(z.string()).describe('Affected systems'),\n\n /**\n * Estimated number of users affected\n */\n affectedUsers: z.number().optional().describe('Affected user count'),\n\n /**\n * Downtime requirements\n */\n downtime: z.object({\n /**\n * Whether downtime is required\n */\n required: z.boolean().describe('Downtime required'),\n\n /**\n * Duration of downtime in minutes\n */\n durationMinutes: z.number().optional().describe('Downtime duration'),\n }).optional().describe('Downtime information'),\n});\n\n/**\n * Rollback Plan Schema\n * \n * Detailed procedure for reverting changes if implementation fails.\n * Required for all non-standard changes.\n * \n * @example\n * ```json\n * {\n * \"description\": \"Revert database schema to previous version\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Stop application servers\",\n * \"estimatedMinutes\": 5\n * },\n * {\n * \"order\": 2,\n * \"description\": \"Restore database backup\",\n * \"estimatedMinutes\": 15\n * }\n * ],\n * \"testProcedure\": \"Verify application login and basic functionality\"\n * }\n * ```\n */\nexport const RollbackPlanSchema = z.object({\n /**\n * High-level description of the rollback approach\n */\n description: z.string().describe('Rollback description'),\n\n /**\n * Sequential steps to execute rollback\n */\n steps: z.array(z.object({\n /**\n * Step execution order\n */\n order: z.number().describe('Step order'),\n\n /**\n * Detailed description of this step\n */\n description: z.string().describe('Step description'),\n\n /**\n * Estimated time to complete this step\n */\n estimatedMinutes: z.number().describe('Estimated duration'),\n })).describe('Rollback steps'),\n\n /**\n * Testing procedure to verify successful rollback\n */\n testProcedure: z.string().optional().describe('Test procedure'),\n});\n\n/**\n * Change Request Schema\n * \n * Comprehensive change management protocol for IT governance.\n * Supports change requests, deployment tracking, and ITIL compliance.\n * \n * @example\n * ```json\n * {\n * \"id\": \"CHG-2024-001\",\n * \"title\": \"Upgrade CRM Database Schema\",\n * \"description\": \"Migrate customer database to new schema version 2.0\",\n * \"type\": \"normal\",\n * \"priority\": \"high\",\n * \"status\": \"approved\",\n * \"requestedBy\": \"user_123\",\n * \"requestedAt\": 1704067200000,\n * \"impact\": {\n * \"level\": \"high\",\n * \"affectedSystems\": [\"crm-api\", \"customer-portal\"],\n * \"affectedUsers\": 5000,\n * \"downtime\": {\n * \"required\": true,\n * \"durationMinutes\": 30\n * }\n * },\n * \"implementation\": {\n * \"description\": \"Execute database migration scripts\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Backup current database\",\n * \"estimatedMinutes\": 10\n * }\n * ],\n * \"testing\": \"Run integration test suite\"\n * },\n * \"rollbackPlan\": {\n * \"description\": \"Restore from backup\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Restore backup\",\n * \"estimatedMinutes\": 15\n * }\n * ]\n * },\n * \"schedule\": {\n * \"plannedStart\": 1704153600000,\n * \"plannedEnd\": 1704155400000\n * }\n * }\n * ```\n */\nexport const ChangeRequestSchema = z.object({\n /**\n * Unique change request identifier\n */\n id: z.string().describe('Change request ID'),\n\n /**\n * Short descriptive title of the change\n */\n title: z.string().describe('Change title'),\n\n /**\n * Detailed description of the change and its purpose\n */\n description: z.string().describe('Change description'),\n\n /**\n * Change classification type\n */\n type: ChangeTypeSchema.describe('Change type'),\n\n /**\n * Priority level for processing\n */\n priority: ChangePrioritySchema.describe('Change priority'),\n\n /**\n * Current status in the change lifecycle\n */\n status: ChangeStatusSchema.describe('Change status'),\n\n /**\n * User ID of the change requester\n */\n requestedBy: z.string().describe('Requester user ID'),\n\n /**\n * Timestamp when change was requested (Unix milliseconds)\n */\n requestedAt: z.number().describe('Request timestamp'),\n\n /**\n * Impact assessment of the change\n */\n impact: ChangeImpactSchema.describe('Impact assessment'),\n\n /**\n * Implementation plan and procedures\n */\n implementation: z.object({\n /**\n * High-level implementation description\n */\n description: z.string().describe('Implementation description'),\n\n /**\n * Sequential implementation steps\n */\n steps: z.array(z.object({\n /**\n * Step execution order\n */\n order: z.number().describe('Step order'),\n\n /**\n * Detailed description of this step\n */\n description: z.string().describe('Step description'),\n\n /**\n * Estimated time to complete this step\n */\n estimatedMinutes: z.number().describe('Estimated duration'),\n })).describe('Implementation steps'),\n\n /**\n * Testing procedures to verify successful implementation\n */\n testing: z.string().optional().describe('Testing procedure'),\n }).describe('Implementation plan'),\n\n /**\n * Rollback plan in case of failure\n */\n rollbackPlan: RollbackPlanSchema.describe('Rollback plan'),\n\n /**\n * Change schedule and timing\n */\n schedule: z.object({\n /**\n * Planned start time (Unix milliseconds)\n */\n plannedStart: z.number().describe('Planned start time'),\n\n /**\n * Planned end time (Unix milliseconds)\n */\n plannedEnd: z.number().describe('Planned end time'),\n\n /**\n * Actual start time (Unix milliseconds)\n */\n actualStart: z.number().optional().describe('Actual start time'),\n\n /**\n * Actual end time (Unix milliseconds)\n */\n actualEnd: z.number().optional().describe('Actual end time'),\n }).optional().describe('Schedule'),\n\n /**\n * Security impact assessment for the change (A.8.32)\n */\n securityImpact: z.object({\n /**\n * Whether a security impact assessment has been performed\n */\n assessed: z.boolean().describe('Whether security impact has been assessed'),\n\n /**\n * Security risk level of this change\n */\n riskLevel: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional()\n .describe('Security risk level'),\n\n /**\n * Data classifications affected by this change\n */\n affectedDataClassifications: z.array(DataClassificationSchema)\n .optional().describe('Affected data classifications'),\n\n /**\n * Whether the change requires security team approval\n */\n requiresSecurityApproval: z.boolean().default(false)\n .describe('Whether security team approval is required'),\n\n /**\n * Security reviewer user ID\n */\n reviewedBy: z.string().optional()\n .describe('Security reviewer user ID'),\n\n /**\n * Security review completion timestamp (Unix milliseconds)\n */\n reviewedAt: z.number().optional()\n .describe('Security review timestamp'),\n\n /**\n * Security review notes or conditions\n */\n reviewNotes: z.string().optional()\n .describe('Security review notes or conditions'),\n }).optional().describe('Security impact assessment per ISO 27001:2022 A.8.32'),\n\n /**\n * Approval workflow configuration\n */\n approval: z.object({\n /**\n * Whether approval is required for this change\n */\n required: z.boolean().describe('Approval required'),\n\n /**\n * List of approvers and their approval status\n */\n approvers: z.array(z.object({\n /**\n * Approver user ID\n */\n userId: z.string().describe('Approver user ID'),\n\n /**\n * Timestamp when approval was granted (Unix milliseconds)\n */\n approvedAt: z.number().optional().describe('Approval timestamp'),\n\n /**\n * Comments from the approver\n */\n comments: z.string().optional().describe('Approver comments'),\n })).describe('Approvers'),\n }).optional().describe('Approval workflow'),\n\n /**\n * Supporting documentation and files\n */\n attachments: z.array(z.object({\n /**\n * Attachment file name\n */\n name: z.string().describe('Attachment name'),\n\n /**\n * URL to download the attachment\n */\n url: z.string().url().describe('Attachment URL'),\n })).optional().describe('Attachments'),\n\n /**\n * Custom metadata key-value pairs for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n});\n\n// Type exports\nexport type ChangeRequest = z.infer;\nexport type ChangeType = z.infer;\nexport type ChangeStatus = z.infer;\nexport type ChangePriority = z.infer;\nexport type ChangeImpact = z.infer;\nexport type RollbackPlan = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from '../data/field.zod';\nimport { ObjectSchema } from '../data/object.zod';\n\n// --- Atomic Operations ---\n\nexport const AddFieldOperation = z.object({\n type: z.literal('add_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to add'),\n field: FieldSchema.describe('Full field definition to add')\n}).describe('Add a new field to an existing object');\n\nexport const ModifyFieldOperation = z.object({\n type: z.literal('modify_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to modify'),\n changes: z.record(z.string(), z.unknown()).describe('Partial field definition updates')\n}).describe('Modify properties of an existing field');\n\nexport const RemoveFieldOperation = z.object({\n type: z.literal('remove_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to remove')\n}).describe('Remove a field from an existing object');\n\nexport const CreateObjectOperation = z.object({\n type: z.literal('create_object'),\n object: ObjectSchema.describe('Full object definition to create')\n}).describe('Create a new object');\n\nexport const RenameObjectOperation = z.object({\n type: z.literal('rename_object'),\n oldName: z.string().describe('Current object name'),\n newName: z.string().describe('New object name')\n}).describe('Rename an existing object');\n\nexport const DeleteObjectOperation = z.object({\n type: z.literal('delete_object'),\n objectName: z.string().describe('Name of the object to delete')\n}).describe('Delete an existing object');\n\nexport const ExecuteSqlOperation = z.object({\n type: z.literal('execute_sql'),\n sql: z.string().describe('Raw SQL statement to execute'),\n description: z.string().optional().describe('Human-readable description of the SQL')\n}).describe('Execute a raw SQL statement');\n\n// Union of all possible operations\nexport const MigrationOperationSchema = z.discriminatedUnion('type', [\n AddFieldOperation,\n ModifyFieldOperation,\n RemoveFieldOperation,\n CreateObjectOperation,\n RenameObjectOperation,\n DeleteObjectOperation,\n ExecuteSqlOperation\n]);\n\n// --- Migration & ChangeSet ---\n\nexport const MigrationDependencySchema = z.object({\n migrationId: z.string().describe('ID of the migration this depends on'),\n package: z.string().optional().describe('Package that owns the dependency migration')\n}).describe('Dependency reference to another migration that must run first');\n\nexport const ChangeSetSchema = z.object({\n id: z.string().uuid().describe('Unique identifier for this change set'),\n name: z.string().describe('Human readable name for the migration'),\n description: z.string().optional().describe('Detailed description of what this migration does'),\n author: z.string().optional().describe('Author who created this migration'),\n createdAt: z.string().datetime().optional().describe('ISO 8601 timestamp when the migration was created'),\n \n // Dependencies ensure migrations run in order\n dependencies: z.array(MigrationDependencySchema).optional().describe('Migrations that must run before this one'),\n \n // The actual atomic operations\n operations: z.array(MigrationOperationSchema).describe('Ordered list of atomic migration operations'),\n \n // Rollback operations (AI should generate these too)\n rollback: z.array(MigrationOperationSchema).optional().describe('Operations to reverse this migration')\n}).describe('A versioned set of atomic schema migration operations');\n\nexport type ChangeSet = z.infer;\nexport type MigrationOperation = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Better-Auth Configuration Protocol\n * \n * Defines the configuration required to initialize the Better-Auth kernel.\n * Used in server-side configuration injection.\n */\n\nexport const AuthProviderConfigSchema = z.object({\n id: z.string().describe('Provider ID (github, google)'),\n clientId: z.string().describe('OAuth Client ID'),\n clientSecret: z.string().describe('OAuth Client Secret'),\n scope: z.array(z.string()).optional().describe('Requested permissions'),\n});\n\nexport const AuthPluginConfigSchema = z.object({\n organization: z.boolean().default(false).describe('Enable Organization/Teams support'),\n twoFactor: z.boolean().default(false).describe('Enable 2FA'),\n passkeys: z.boolean().default(false).describe('Enable Passkey support'),\n magicLink: z.boolean().default(false).describe('Enable Magic Link login'),\n});\n\n/**\n * Mutual TLS (mTLS) Configuration Schema\n * \n * Enables client certificate authentication for zero-trust architectures.\n */\nexport const MutualTLSConfigSchema = z.object({\n /** Enable mutual TLS authentication */\n enabled: z.boolean()\n .default(false)\n .describe('Enable mutual TLS authentication'),\n\n /** Require client certificates for all connections */\n clientCertRequired: z.boolean()\n .default(false)\n .describe('Require client certificates for all connections'),\n\n /** PEM-encoded CA certificates or file paths for trust validation */\n trustedCAs: z.array(z.string())\n .describe('PEM-encoded CA certificates or file paths'),\n\n /** Certificate Revocation List URL */\n crlUrl: z.string()\n .optional()\n .describe('Certificate Revocation List (CRL) URL'),\n\n /** Online Certificate Status Protocol URL */\n ocspUrl: z.string()\n .optional()\n .describe('Online Certificate Status Protocol (OCSP) URL'),\n\n /** Certificate validation strictness level */\n certificateValidation: z.enum(['strict', 'relaxed', 'none'])\n .describe('Certificate validation strictness level'),\n\n /** Allowed Common Names on client certificates */\n allowedCNs: z.array(z.string())\n .optional()\n .describe('Allowed Common Names (CN) on client certificates'),\n\n /** Allowed Organizational Units on client certificates */\n allowedOUs: z.array(z.string())\n .optional()\n .describe('Allowed Organizational Units (OU) on client certificates'),\n\n /** Certificate pinning configuration */\n pinning: z.object({\n /** Enable certificate pinning */\n enabled: z.boolean().describe('Enable certificate pinning'),\n /** Array of pinned certificate hashes */\n pins: z.array(z.string()).describe('Pinned certificate hashes'),\n })\n .optional()\n .describe('Certificate pinning configuration'),\n});\n\nexport type MutualTLSConfig = z.infer;\n\n/**\n * Social / OAuth Provider Configuration\n *\n * Maps provider id → { clientId, clientSecret, ... }.\n * Keys must match Better-Auth built-in provider names (google, github, etc.).\n */\nexport const SocialProviderConfigSchema = z.record(\n z.string(),\n z.object({\n clientId: z.string().describe('OAuth Client ID'),\n clientSecret: z.string().describe('OAuth Client Secret'),\n enabled: z.boolean().optional().default(true).describe('Enable this provider'),\n scope: z.array(z.string()).optional().describe('Additional OAuth scopes'),\n }).catchall(z.unknown()),\n).optional().describe(\n 'Social/OAuth provider map forwarded to better-auth socialProviders. ' +\n 'Keys are provider ids (google, github, apple, …).'\n);\n\n/**\n * Email + Password Configuration\n */\nexport const EmailAndPasswordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable email/password auth'),\n disableSignUp: z.boolean().optional().describe('Disable new user registration via email/password'),\n requireEmailVerification: z.boolean().optional().describe(\n 'Require email verification before creating a session'\n ),\n minPasswordLength: z.number().optional().describe('Minimum password length (default 8)'),\n maxPasswordLength: z.number().optional().describe('Maximum password length (default 128)'),\n resetPasswordTokenExpiresIn: z.number().optional().describe(\n 'Reset-password token TTL in seconds (default 3600)'\n ),\n autoSignIn: z.boolean().optional().describe('Auto sign-in after sign-up (default true)'),\n revokeSessionsOnPasswordReset: z.boolean().optional().describe(\n 'Revoke all other sessions on password reset'\n ),\n}).optional().describe('Email and password authentication options forwarded to better-auth');\n\n/**\n * Email Verification Configuration\n */\nexport const EmailVerificationConfigSchema = z.object({\n sendOnSignUp: z.boolean().optional().describe(\n 'Automatically send verification email after sign-up'\n ),\n sendOnSignIn: z.boolean().optional().describe(\n 'Send verification email on sign-in when not yet verified'\n ),\n autoSignInAfterVerification: z.boolean().optional().describe(\n 'Auto sign-in the user after email verification'\n ),\n expiresIn: z.number().optional().describe(\n 'Verification token TTL in seconds (default 3600)'\n ),\n}).optional().describe('Email verification options forwarded to better-auth');\n\n/**\n * Advanced / Low-level Better-Auth Options\n */\nexport const AdvancedAuthConfigSchema = z.object({\n crossSubDomainCookies: z.object({\n enabled: z.boolean().describe('Enable cross-subdomain cookies'),\n additionalCookies: z.array(z.string()).optional().describe('Extra cookies shared across subdomains'),\n domain: z.string().optional().describe(\n 'Cookie domain override — defaults to root domain derived from baseUrl'\n ),\n }).optional().describe(\n 'Share auth cookies across subdomains (critical for *.example.com multi-tenant)'\n ),\n useSecureCookies: z.boolean().optional().describe('Force Secure flag on cookies'),\n disableCSRFCheck: z.boolean().optional().describe(\n '⚠ Disable CSRF check — security risk, use with caution'\n ),\n cookiePrefix: z.string().optional().describe('Prefix for auth cookie names'),\n}).optional().describe('Advanced / low-level Better-Auth options');\n\nexport const AuthConfigSchema = z.object({\n secret: z.string().optional().describe('Encryption secret'),\n baseUrl: z.string().optional().describe('Base URL for auth routes'),\n databaseUrl: z.string().optional().describe('Database connection string'),\n providers: z.array(AuthProviderConfigSchema).optional(),\n plugins: AuthPluginConfigSchema.optional(),\n session: z.object({\n expiresIn: z.number().default(60 * 60 * 24 * 7).describe('Session duration in seconds'),\n updateAge: z.number().default(60 * 60 * 24).describe('Session update frequency'),\n }).optional(),\n trustedOrigins: z.array(z.string()).optional().describe(\n 'Trusted origins for CSRF protection. Supports wildcards (e.g. \"https://*.example.com\"). ' +\n 'The baseUrl origin is always trusted implicitly.'\n ),\n socialProviders: SocialProviderConfigSchema,\n emailAndPassword: EmailAndPasswordConfigSchema,\n emailVerification: EmailVerificationConfigSchema,\n advanced: AdvancedAuthConfigSchema,\n mutualTls: MutualTLSConfigSchema.optional().describe('Mutual TLS (mTLS) configuration'),\n}).catchall(z.unknown());\n\nexport type AuthProviderConfig = z.infer;\nexport type AuthPluginConfig = z.infer;\nexport type SocialProviderConfig = z.infer;\nexport type EmailAndPasswordConfig = z.infer;\nexport type EmailVerificationConfig = z.infer;\nexport type AdvancedAuthConfig = z.infer;\nexport type AuthConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ComplianceFrameworkSchema } from './security-context.zod';\n\n/**\n * Compliance protocol for GDPR, CCPA, HIPAA, SOX, PCI-DSS\n */\nexport const GDPRConfigSchema = z.object({\n enabled: z.boolean().describe('Enable GDPR compliance controls'),\n dataSubjectRights: z.object({\n rightToAccess: z.boolean().default(true).describe('Allow data subjects to access their data'),\n rightToRectification: z.boolean().default(true).describe('Allow data subjects to correct their data'),\n rightToErasure: z.boolean().default(true).describe('Allow data subjects to request deletion'),\n rightToRestriction: z.boolean().default(true).describe('Allow data subjects to restrict processing'),\n rightToPortability: z.boolean().default(true).describe('Allow data subjects to export their data'),\n rightToObjection: z.boolean().default(true).describe('Allow data subjects to object to processing'),\n }).describe('Data subject rights configuration per GDPR Articles 15-21'),\n legalBasis: z.enum([\n 'consent',\n 'contract',\n 'legal-obligation',\n 'vital-interests',\n 'public-task',\n 'legitimate-interests',\n ]).describe('Legal basis for data processing under GDPR Article 6'),\n consentTracking: z.boolean().default(true).describe('Track and record user consent'),\n dataRetentionDays: z.number().optional().describe('Maximum data retention period in days'),\n dataProcessingAgreement: z.string().optional().describe('URL or reference to the data processing agreement'),\n}).describe('GDPR (General Data Protection Regulation) compliance configuration');\n\nexport type GDPRConfig = z.infer;\nexport type GDPRConfigInput = z.input;\n\nexport const HIPAAConfigSchema = z.object({\n enabled: z.boolean().describe('Enable HIPAA compliance controls'),\n phi: z.object({\n encryption: z.boolean().default(true).describe('Encrypt Protected Health Information at rest'),\n accessControl: z.boolean().default(true).describe('Enforce role-based access to PHI'),\n auditTrail: z.boolean().default(true).describe('Log all PHI access events'),\n backupAndRecovery: z.boolean().default(true).describe('Enable PHI backup and disaster recovery'),\n }).describe('Protected Health Information safeguards'),\n businessAssociateAgreement: z.boolean().default(false).describe('BAA is in place with third-party processors'),\n}).describe('HIPAA (Health Insurance Portability and Accountability Act) compliance configuration');\n\nexport type HIPAAConfig = z.infer;\nexport type HIPAAConfigInput = z.input;\n\nexport const PCIDSSConfigSchema = z.object({\n enabled: z.boolean().describe('Enable PCI-DSS compliance controls'),\n level: z.enum(['1', '2', '3', '4']).describe('PCI-DSS compliance level (1 = highest)'),\n cardDataFields: z.array(z.string()).describe('Field names containing cardholder data'),\n tokenization: z.boolean().default(true).describe('Replace card data with secure tokens'),\n encryptionInTransit: z.boolean().default(true).describe('Encrypt cardholder data during transmission'),\n encryptionAtRest: z.boolean().default(true).describe('Encrypt stored cardholder data'),\n}).describe('PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration');\n\nexport type PCIDSSConfig = z.infer;\nexport type PCIDSSConfigInput = z.input;\n\nexport const AuditLogConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable audit logging'),\n retentionDays: z.number().default(365).describe('Number of days to retain audit logs'),\n immutable: z.boolean().default(true).describe('Prevent modification or deletion of audit logs'),\n signLogs: z.boolean().default(false).describe('Cryptographically sign log entries for tamper detection'),\n events: z.array(z.enum([\n 'create',\n 'read',\n 'update',\n 'delete',\n 'export',\n 'permission-change',\n 'login',\n 'logout',\n 'failed-login',\n ])).describe('Event types to capture in the audit log'),\n}).describe('Audit log configuration for compliance and security monitoring');\n\nexport type AuditLogConfig = z.infer;\nexport type AuditLogConfigInput = z.input;\n\n/**\n * Audit Finding Severity Schema\n *\n * Severity classification for audit findings.\n */\nexport const AuditFindingSeveritySchema = z.enum([\n 'critical', // Immediate remediation required\n 'major', // Significant non-conformity\n 'minor', // Minor non-conformity\n 'observation', // Improvement opportunity\n]);\n\n/**\n * Audit Finding Status Schema\n *\n * Lifecycle status of an audit finding.\n */\nexport const AuditFindingStatusSchema = z.enum([\n 'open', // Finding identified, not yet addressed\n 'in_remediation', // Remediation in progress\n 'remediated', // Remediation completed, pending verification\n 'verified', // Remediation verified and accepted\n 'accepted_risk', // Risk accepted by management\n 'closed', // Finding closed\n]);\n\n/**\n * Audit Finding Schema (A.5.35)\n *\n * Individual finding from a compliance or security audit.\n * Supports tracking from discovery through remediation and verification.\n *\n * @example\n * ```json\n * {\n * \"id\": \"FIND-2024-001\",\n * \"title\": \"Insufficient access logging\",\n * \"description\": \"PHI access events are not being logged for HIPAA compliance\",\n * \"severity\": \"major\",\n * \"status\": \"in_remediation\",\n * \"controlReference\": \"A.8.15\",\n * \"framework\": \"iso27001\",\n * \"identifiedAt\": 1704067200000,\n * \"identifiedBy\": \"external_auditor\",\n * \"remediationPlan\": \"Implement audit logging for all PHI access events\",\n * \"remediationDeadline\": 1706745600000\n * }\n * ```\n */\nexport const AuditFindingSchema = z.object({\n /**\n * Unique finding identifier\n */\n id: z.string().describe('Unique finding identifier'),\n\n /**\n * Short descriptive title\n */\n title: z.string().describe('Finding title'),\n\n /**\n * Detailed description of the finding\n */\n description: z.string().describe('Finding description'),\n\n /**\n * Finding severity\n */\n severity: AuditFindingSeveritySchema.describe('Finding severity'),\n\n /**\n * Current status\n */\n status: AuditFindingStatusSchema.describe('Finding status'),\n\n /**\n * ISO 27001 control reference (e.g., \"A.5.35\", \"A.8.15\")\n */\n controlReference: z.string().optional().describe('ISO 27001 control reference'),\n\n /**\n * Compliance framework\n */\n framework: ComplianceFrameworkSchema.optional()\n .describe('Related compliance framework'),\n\n /**\n * Timestamp when finding was identified (Unix milliseconds)\n */\n identifiedAt: z.number().describe('Identification timestamp'),\n\n /**\n * User or entity who identified the finding\n */\n identifiedBy: z.string().describe('Identifier (auditor name or system)'),\n\n /**\n * Planned remediation actions\n */\n remediationPlan: z.string().optional().describe('Remediation plan'),\n\n /**\n * Remediation deadline (Unix milliseconds)\n */\n remediationDeadline: z.number().optional().describe('Remediation deadline timestamp'),\n\n /**\n * Timestamp when remediation was verified (Unix milliseconds)\n */\n verifiedAt: z.number().optional().describe('Verification timestamp'),\n\n /**\n * Verifier name or role\n */\n verifiedBy: z.string().optional().describe('Verifier name or role'),\n\n /**\n * Notes or comments\n */\n notes: z.string().optional().describe('Additional notes'),\n}).describe('Audit finding with remediation tracking per ISO 27001:2022 A.5.35');\n\nexport type AuditFinding = z.infer;\n\n/**\n * Audit Schedule Schema (A.5.35)\n *\n * Defines audit scheduling for independent information security reviews.\n * Supports recurring audits, scope definition, and assessor assignment.\n *\n * @example\n * ```json\n * {\n * \"id\": \"AUDIT-2024-Q1\",\n * \"title\": \"Q1 ISO 27001 Internal Audit\",\n * \"scope\": [\"access_control\", \"encryption\", \"incident_response\"],\n * \"framework\": \"iso27001\",\n * \"scheduledAt\": 1711929600000,\n * \"assessor\": \"internal_audit_team\",\n * \"recurrenceMonths\": 3\n * }\n * ```\n */\nexport const AuditScheduleSchema = z.object({\n /**\n * Unique audit schedule identifier\n */\n id: z.string().describe('Unique audit schedule identifier'),\n\n /**\n * Audit title or name\n */\n title: z.string().describe('Audit title'),\n\n /**\n * Scope of areas to audit\n */\n scope: z.array(z.string()).describe('Audit scope areas'),\n\n /**\n * Target compliance framework\n */\n framework: ComplianceFrameworkSchema\n .describe('Target compliance framework'),\n\n /**\n * Scheduled audit date (Unix milliseconds)\n */\n scheduledAt: z.number().describe('Scheduled audit timestamp'),\n\n /**\n * Actual completion date (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Completion timestamp'),\n\n /**\n * Assessor name, team, or external firm\n */\n assessor: z.string().describe('Assessor or audit team'),\n\n /**\n * Whether this is an external (independent) audit\n */\n isExternal: z.boolean().default(false).describe('Whether this is an external audit'),\n\n /**\n * Recurrence interval in months (0 = one-time)\n */\n recurrenceMonths: z.number().default(0).describe('Recurrence interval in months (0 = one-time)'),\n\n /**\n * Findings from this audit\n */\n findings: z.array(AuditFindingSchema).optional().describe('Audit findings'),\n}).describe('Audit schedule for independent security reviews per ISO 27001:2022 A.5.35');\n\nexport type AuditSchedule = z.infer;\n\nexport const ComplianceConfigSchema = z.object({\n gdpr: GDPRConfigSchema.optional().describe('GDPR compliance settings'),\n hipaa: HIPAAConfigSchema.optional().describe('HIPAA compliance settings'),\n pciDss: PCIDSSConfigSchema.optional().describe('PCI-DSS compliance settings'),\n auditLog: AuditLogConfigSchema.describe('Audit log configuration'),\n auditSchedules: z.array(AuditScheduleSchema).optional()\n .describe('Scheduled compliance audits (A.5.35)'),\n}).describe('Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance');\n\nexport type ComplianceConfig = z.infer;\nexport type ComplianceConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Incident Response Protocol — ISO 27001:2022 (A.5.24–A.5.28)\n *\n * Defines schemas for information security event management including\n * incident classification, severity grading, response procedures,\n * and notification matrices.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Incident Severity Schema\n *\n * Severity grading for security incidents following ISO 27001 guidelines.\n * Determines response urgency and escalation requirements.\n */\nexport const IncidentSeveritySchema = z.enum([\n 'critical', // Immediate threat to business operations or data integrity\n 'high', // Significant impact requiring urgent response\n 'medium', // Moderate impact with controlled response timeline\n 'low', // Minor impact with standard response procedures\n]);\n\n/**\n * Incident Category Schema\n *\n * Classification of security incidents by type (A.5.25).\n * Used for routing, reporting, and trend analysis.\n */\nexport const IncidentCategorySchema = z.enum([\n 'data_breach', // Unauthorized access or disclosure of data\n 'malware', // Malicious software detection\n 'unauthorized_access', // Unauthorized system or data access\n 'denial_of_service', // Service availability attack\n 'social_engineering', // Phishing, pretexting, or manipulation\n 'insider_threat', // Threat originating from internal actors\n 'physical_security', // Physical security breach\n 'configuration_error', // Security misconfiguration\n 'vulnerability_exploit', // Exploitation of known vulnerability\n 'policy_violation', // Violation of security policies\n 'other', // Other security incidents\n]);\n\n/**\n * Incident Status Schema\n *\n * Current status of a security incident in its lifecycle.\n */\nexport const IncidentStatusSchema = z.enum([\n 'reported', // Initial report received\n 'triaged', // Severity and category assessed\n 'investigating', // Active investigation in progress\n 'containing', // Containment measures being applied\n 'eradicating', // Root cause being removed\n 'recovering', // Systems being restored to normal\n 'resolved', // Incident resolved\n 'closed', // Post-incident review complete\n]);\n\n/**\n * Incident Response Phase Schema\n *\n * Defines structured response phases per NIST SP 800-61 / ISO 27001 (A.5.26).\n */\nexport const IncidentResponsePhaseSchema = z.object({\n /**\n * Phase name identifier\n */\n phase: z.enum([\n 'identification',\n 'containment',\n 'eradication',\n 'recovery',\n 'lessons_learned',\n ]).describe('Response phase name'),\n\n /**\n * Phase description and objectives\n */\n description: z.string().describe('Phase description and objectives'),\n\n /**\n * Responsible team or role for this phase\n */\n assignedTo: z.string().describe('Responsible team or role'),\n\n /**\n * Target completion time in hours from incident start\n */\n targetHours: z.number().min(0).describe('Target completion time in hours'),\n\n /**\n * Actual completion timestamp (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Actual completion timestamp'),\n\n /**\n * Notes and findings during this phase\n */\n notes: z.string().optional().describe('Phase notes and findings'),\n}).describe('Incident response phase with timing and assignment');\n\nexport type IncidentResponsePhase = z.infer;\n\n/**\n * Notification Rule Schema\n *\n * Defines who must be notified and when, based on severity (A.5.27).\n */\nexport const IncidentNotificationRuleSchema = z.object({\n /**\n * Minimum severity level that triggers this notification\n */\n severity: IncidentSeveritySchema.describe('Minimum severity to trigger notification'),\n\n /**\n * Notification channels to use\n */\n channels: z.array(z.enum([\n 'email',\n 'sms',\n 'slack',\n 'pagerduty',\n 'webhook',\n ])).describe('Notification channels'),\n\n /**\n * Roles or teams to notify\n */\n recipients: z.array(z.string()).describe('Roles or teams to notify'),\n\n /**\n * Maximum time in minutes to send notification after incident detection\n */\n withinMinutes: z.number().min(1).describe('Notification deadline in minutes from detection'),\n\n /**\n * Whether to notify external regulators (for data breaches)\n */\n notifyRegulators: z.boolean().default(false)\n .describe('Whether to notify regulatory authorities'),\n\n /**\n * Regulatory notification deadline in hours (e.g., GDPR 72h)\n */\n regulatorDeadlineHours: z.number().optional()\n .describe('Regulatory notification deadline in hours'),\n}).describe('Incident notification rule per severity level');\n\nexport type IncidentNotificationRule = z.infer;\n\n/**\n * Notification Matrix Schema\n *\n * Complete notification matrix mapping severity levels to stakeholder groups (A.5.27).\n */\nexport const IncidentNotificationMatrixSchema = z.object({\n /**\n * Notification rules ordered by severity\n */\n rules: z.array(IncidentNotificationRuleSchema)\n .describe('Notification rules by severity level'),\n\n /**\n * Default escalation timeout in minutes before auto-escalation\n */\n escalationTimeoutMinutes: z.number().default(30)\n .describe('Auto-escalation timeout in minutes'),\n\n /**\n * Escalation chain: ordered list of roles to escalate to\n */\n escalationChain: z.array(z.string()).default([])\n .describe('Ordered escalation chain of roles'),\n}).describe('Incident notification matrix with escalation policies');\n\nexport type IncidentNotificationMatrix = z.infer;\n\n/**\n * Incident Schema\n *\n * Comprehensive security incident record following ISO 27001:2022 (A.5.24–A.5.28).\n * Tracks the full incident lifecycle from detection through post-incident review.\n *\n * @example\n * ```json\n * {\n * \"id\": \"INC-2024-001\",\n * \"title\": \"Unauthorized API Access Detected\",\n * \"description\": \"Multiple failed authentication attempts from unknown IP range\",\n * \"severity\": \"high\",\n * \"category\": \"unauthorized_access\",\n * \"status\": \"investigating\",\n * \"reportedBy\": \"monitoring_system\",\n * \"reportedAt\": 1704067200000,\n * \"affectedSystems\": [\"api-gateway\", \"auth-service\"],\n * \"affectedDataClassifications\": [\"pii\", \"confidential\"],\n * \"responsePhases\": [\n * {\n * \"phase\": \"identification\",\n * \"description\": \"Identify scope of unauthorized access\",\n * \"assignedTo\": \"security_team\",\n * \"targetHours\": 2\n * }\n * ]\n * }\n * ```\n */\nexport const IncidentSchema = z.object({\n /**\n * Unique incident identifier\n */\n id: z.string().describe('Unique incident identifier'),\n\n /**\n * Short descriptive title of the incident\n */\n title: z.string().describe('Incident title'),\n\n /**\n * Detailed description of the security event\n */\n description: z.string().describe('Detailed incident description'),\n\n /**\n * Severity classification\n */\n severity: IncidentSeveritySchema.describe('Incident severity level'),\n\n /**\n * Incident category / type\n */\n category: IncidentCategorySchema.describe('Incident category'),\n\n /**\n * Current status in the incident lifecycle\n */\n status: IncidentStatusSchema.describe('Current incident status'),\n\n /**\n * User or system that reported the incident\n */\n reportedBy: z.string().describe('Reporter user ID or system name'),\n\n /**\n * Timestamp when the incident was reported (Unix milliseconds)\n */\n reportedAt: z.number().describe('Report timestamp'),\n\n /**\n * Timestamp when the incident was detected (may differ from reported)\n */\n detectedAt: z.number().optional().describe('Detection timestamp'),\n\n /**\n * Timestamp when the incident was resolved\n */\n resolvedAt: z.number().optional().describe('Resolution timestamp'),\n\n /**\n * Systems affected by the incident\n */\n affectedSystems: z.array(z.string()).describe('Affected systems'),\n\n /**\n * Data classifications affected (for data breach assessment)\n */\n affectedDataClassifications: z.array(DataClassificationSchema)\n .optional().describe('Affected data classifications'),\n\n /**\n * Structured response phases tracking\n */\n responsePhases: z.array(IncidentResponsePhaseSchema).optional()\n .describe('Incident response phases'),\n\n /**\n * Root cause analysis (completed post-incident)\n */\n rootCause: z.string().optional().describe('Root cause analysis'),\n\n /**\n * Corrective actions taken or planned\n */\n correctiveActions: z.array(z.string()).optional()\n .describe('Corrective actions taken or planned'),\n\n /**\n * Lessons learned from the incident (A.5.28)\n */\n lessonsLearned: z.string().optional()\n .describe('Lessons learned from the incident'),\n\n /**\n * Related change request IDs (if changes resulted from incident)\n */\n relatedChangeRequestIds: z.array(z.string()).optional()\n .describe('Related change request IDs'),\n\n /**\n * Custom metadata for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Custom metadata key-value pairs'),\n}).describe('Security incident record per ISO 27001:2022 A.5.24–A.5.28');\n\n/**\n * Incident Response Policy Schema\n *\n * Organization-level incident response policy configuration (A.5.24).\n */\nexport const IncidentResponsePolicySchema = z.object({\n /**\n * Whether incident response is enabled\n */\n enabled: z.boolean().default(true)\n .describe('Enable incident response management'),\n\n /**\n * Notification matrix configuration\n */\n notificationMatrix: IncidentNotificationMatrixSchema\n .describe('Notification and escalation matrix'),\n\n /**\n * Default response team or role\n */\n defaultResponseTeam: z.string()\n .describe('Default incident response team or role'),\n\n /**\n * Maximum time in hours to begin initial triage\n */\n triageDeadlineHours: z.number().default(1)\n .describe('Maximum hours to begin triage after detection'),\n\n /**\n * Whether to require post-incident review for all incidents\n */\n requirePostIncidentReview: z.boolean().default(true)\n .describe('Require post-incident review for all incidents'),\n\n /**\n * Minimum severity level that requires regulatory notification\n */\n regulatoryNotificationThreshold: IncidentSeveritySchema.default('high')\n .describe('Minimum severity requiring regulatory notification'),\n\n /**\n * Retention period for incident records in days\n */\n retentionDays: z.number().default(2555)\n .describe('Incident record retention period in days (default ~7 years)'),\n}).describe('Organization-level incident response policy per ISO 27001:2022');\n\n// Type exports\nexport type IncidentSeverity = z.infer;\nexport type IncidentCategory = z.infer;\nexport type IncidentStatus = z.infer;\nexport type Incident = z.infer;\nexport type IncidentResponsePolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Supplier Security Protocol — ISO 27001:2022 (A.5.19–A.5.22)\n *\n * Defines schemas for supplier information security management including\n * risk assessment, security requirements, monitoring, and change control.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Supplier Risk Level Schema\n *\n * Risk classification for supplier relationships based on data access\n * and service criticality.\n */\nexport const SupplierRiskLevelSchema = z.enum([\n 'critical', // Direct access to sensitive data or core infrastructure\n 'high', // Significant data processing or service dependency\n 'medium', // Limited data access with moderate dependency\n 'low', // Minimal data access and low service dependency\n]);\n\n/**\n * Supplier Assessment Status Schema\n *\n * Current status of a supplier security assessment.\n */\nexport const SupplierAssessmentStatusSchema = z.enum([\n 'pending', // Assessment not yet started\n 'in_progress', // Assessment currently underway\n 'completed', // Assessment completed\n 'expired', // Assessment past its validity period\n 'failed', // Supplier did not meet security requirements\n]);\n\n/**\n * Supplier Security Requirement Schema\n *\n * Individual security requirement to assess against a supplier (A.5.20).\n */\nexport const SupplierSecurityRequirementSchema = z.object({\n /**\n * Requirement identifier\n */\n id: z.string().describe('Requirement identifier'),\n\n /**\n * Requirement description\n */\n description: z.string().describe('Requirement description'),\n\n /**\n * ISO 27001 control reference (e.g., \"A.5.19\")\n */\n controlReference: z.string().optional()\n .describe('ISO 27001 control reference'),\n\n /**\n * Whether this requirement is mandatory\n */\n mandatory: z.boolean().default(true)\n .describe('Whether this requirement is mandatory'),\n\n /**\n * Compliance status\n */\n compliant: z.boolean().optional()\n .describe('Whether the supplier meets this requirement'),\n\n /**\n * Evidence or notes for compliance assessment\n */\n evidence: z.string().optional()\n .describe('Compliance evidence or assessment notes'),\n}).describe('Individual supplier security requirement');\n\nexport type SupplierSecurityRequirement = z.infer;\n\n/**\n * Supplier Security Assessment Schema\n *\n * Comprehensive supplier security assessment record (A.5.19–A.5.21).\n *\n * @example\n * ```json\n * {\n * \"supplierId\": \"SUP-001\",\n * \"supplierName\": \"Cloud Provider Inc.\",\n * \"riskLevel\": \"critical\",\n * \"status\": \"completed\",\n * \"assessedBy\": \"security_team\",\n * \"assessedAt\": 1704067200000,\n * \"validUntil\": 1735689600000,\n * \"requirements\": [\n * {\n * \"id\": \"REQ-001\",\n * \"description\": \"Data encryption at rest using AES-256\",\n * \"controlReference\": \"A.8.24\",\n * \"mandatory\": true,\n * \"compliant\": true\n * }\n * ],\n * \"overallCompliant\": true,\n * \"dataClassificationsShared\": [\"pii\", \"confidential\"]\n * }\n * ```\n */\nexport const SupplierSecurityAssessmentSchema = z.object({\n /**\n * Unique supplier identifier\n */\n supplierId: z.string().describe('Unique supplier identifier'),\n\n /**\n * Supplier name\n */\n supplierName: z.string().describe('Supplier display name'),\n\n /**\n * Risk classification\n */\n riskLevel: SupplierRiskLevelSchema.describe('Supplier risk classification'),\n\n /**\n * Assessment status\n */\n status: SupplierAssessmentStatusSchema.describe('Assessment status'),\n\n /**\n * User or team who performed the assessment\n */\n assessedBy: z.string().describe('Assessor user ID or team'),\n\n /**\n * Assessment completion timestamp (Unix milliseconds)\n */\n assessedAt: z.number().describe('Assessment timestamp'),\n\n /**\n * Assessment validity expiry (Unix milliseconds)\n */\n validUntil: z.number().describe('Assessment validity expiry timestamp'),\n\n /**\n * Security requirements assessed\n */\n requirements: z.array(SupplierSecurityRequirementSchema)\n .describe('Security requirements and their compliance status'),\n\n /**\n * Overall compliance result\n */\n overallCompliant: z.boolean().describe('Whether supplier meets all mandatory requirements'),\n\n /**\n * Data classifications shared with this supplier\n */\n dataClassificationsShared: z.array(DataClassificationSchema)\n .optional().describe('Data classifications shared with supplier'),\n\n /**\n * Services provided by the supplier\n */\n servicesProvided: z.array(z.string()).optional()\n .describe('Services provided by this supplier'),\n\n /**\n * Certifications held by the supplier\n */\n certifications: z.array(z.string()).optional()\n .describe('Supplier certifications (e.g., ISO 27001, SOC 2)'),\n\n /**\n * Remediation items for non-compliant requirements\n */\n remediationItems: z.array(z.object({\n requirementId: z.string().describe('Non-compliant requirement ID'),\n action: z.string().describe('Required remediation action'),\n deadline: z.number().describe('Remediation deadline timestamp'),\n status: z.enum(['pending', 'in_progress', 'completed']).default('pending')\n .describe('Remediation status'),\n })).optional().describe('Remediation items for non-compliant requirements'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Custom metadata key-value pairs'),\n}).describe('Supplier security assessment record per ISO 27001:2022 A.5.19–A.5.21');\n\n/**\n * Supplier Security Policy Schema\n *\n * Organization-level supplier security management policy (A.5.22).\n */\nexport const SupplierSecurityPolicySchema = z.object({\n /**\n * Whether supplier security management is enabled\n */\n enabled: z.boolean().default(true)\n .describe('Enable supplier security management'),\n\n /**\n * Reassessment interval in days\n */\n reassessmentIntervalDays: z.number().default(365)\n .describe('Supplier reassessment interval in days'),\n\n /**\n * Whether to require supplier security assessment before onboarding\n */\n requirePreOnboardingAssessment: z.boolean().default(true)\n .describe('Require security assessment before supplier onboarding'),\n\n /**\n * Minimum risk level that requires formal assessment\n */\n formalAssessmentThreshold: SupplierRiskLevelSchema.default('medium')\n .describe('Minimum risk level requiring formal assessment'),\n\n /**\n * Whether to monitor supplier security changes (A.5.22)\n */\n monitorChanges: z.boolean().default(true)\n .describe('Monitor supplier security posture changes'),\n\n /**\n * Required certifications for critical suppliers\n */\n requiredCertifications: z.array(z.string()).default([])\n .describe('Required certifications for critical-risk suppliers'),\n}).describe('Organization-level supplier security management policy per ISO 27001:2022');\n\n// Type exports\nexport type SupplierRiskLevel = z.infer;\nexport type SupplierAssessmentStatus = z.infer;\nexport type SupplierSecurityAssessment = z.infer;\nexport type SupplierSecurityPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Information Security Training Protocol — ISO 27001:2022 (A.6.3)\n *\n * Defines schemas for security awareness and training management including\n * course definitions, completion tracking, and organizational training plans.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Training Category Schema\n *\n * Classification of training content by domain.\n */\nexport const TrainingCategorySchema = z.enum([\n 'security_awareness', // General security awareness\n 'data_protection', // Data handling and privacy\n 'incident_response', // Incident reporting and response\n 'access_control', // Access management best practices\n 'phishing_awareness', // Phishing and social engineering\n 'compliance', // Regulatory compliance (GDPR, HIPAA, etc.)\n 'secure_development', // Secure coding and development practices\n 'physical_security', // Physical security awareness\n 'business_continuity', // Business continuity and disaster recovery\n 'other', // Other training categories\n]);\n\n/**\n * Training Completion Status Schema\n */\nexport const TrainingCompletionStatusSchema = z.enum([\n 'not_started', // Training not yet begun\n 'in_progress', // Training currently underway\n 'completed', // Training completed successfully\n 'failed', // Training assessment not passed\n 'expired', // Training certification has expired\n]);\n\n/**\n * Training Course Schema\n *\n * Definition of a security training course or module.\n *\n * @example\n * ```json\n * {\n * \"id\": \"COURSE-SEC-001\",\n * \"title\": \"Information Security Fundamentals\",\n * \"description\": \"Annual security awareness training for all employees\",\n * \"category\": \"security_awareness\",\n * \"durationMinutes\": 60,\n * \"mandatory\": true,\n * \"targetRoles\": [\"all_employees\"],\n * \"validityDays\": 365,\n * \"passingScore\": 80\n * }\n * ```\n */\nexport const TrainingCourseSchema = z.object({\n /**\n * Unique course identifier\n */\n id: z.string().describe('Unique course identifier'),\n\n /**\n * Course title\n */\n title: z.string().describe('Course title'),\n\n /**\n * Course description and objectives\n */\n description: z.string().describe('Course description and learning objectives'),\n\n /**\n * Training category\n */\n category: TrainingCategorySchema.describe('Training category'),\n\n /**\n * Estimated duration in minutes\n */\n durationMinutes: z.number().min(1).describe('Estimated course duration in minutes'),\n\n /**\n * Whether this training is mandatory\n */\n mandatory: z.boolean().default(false).describe('Whether training is mandatory'),\n\n /**\n * Target roles or groups for this training\n */\n targetRoles: z.array(z.string()).describe('Target roles or groups'),\n\n /**\n * Validity period in days before recertification is needed\n */\n validityDays: z.number().optional().describe('Certification validity period in days'),\n\n /**\n * Minimum passing score (percentage) for assessment\n */\n passingScore: z.number().min(0).max(100).optional()\n .describe('Minimum passing score percentage'),\n\n /**\n * Course version for tracking content updates\n */\n version: z.string().optional().describe('Course content version'),\n}).describe('Security training course definition');\n\n/**\n * Training Record Schema\n *\n * Individual employee training completion record.\n */\nexport const TrainingRecordSchema = z.object({\n /**\n * Reference to the course ID\n */\n courseId: z.string().describe('Training course identifier'),\n\n /**\n * User who completed (or is assigned) the training\n */\n userId: z.string().describe('User identifier'),\n\n /**\n * Completion status\n */\n status: TrainingCompletionStatusSchema.describe('Training completion status'),\n\n /**\n * Training assignment date (Unix milliseconds)\n */\n assignedAt: z.number().describe('Assignment timestamp'),\n\n /**\n * Training completion date (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Completion timestamp'),\n\n /**\n * Assessment score (percentage)\n */\n score: z.number().min(0).max(100).optional().describe('Assessment score percentage'),\n\n /**\n * Certification expiry date (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Certification expiry timestamp'),\n\n /**\n * Notes or comments from instructor or system\n */\n notes: z.string().optional().describe('Training notes or comments'),\n}).describe('Individual training completion record');\n\n/**\n * Training Plan Schema\n *\n * Organizational training plan defining schedule and requirements (A.6.3).\n */\nexport const TrainingPlanSchema = z.object({\n /**\n * Whether training management is enabled\n */\n enabled: z.boolean().default(true).describe('Enable training management'),\n\n /**\n * Training courses in the plan\n */\n courses: z.array(TrainingCourseSchema).describe('Training courses'),\n\n /**\n * Default recertification interval in days\n */\n recertificationIntervalDays: z.number().default(365)\n .describe('Default recertification interval in days'),\n\n /**\n * Whether to track training completion for compliance reporting\n */\n trackCompletion: z.boolean().default(true)\n .describe('Track training completion for compliance'),\n\n /**\n * Grace period in days after expiry before non-compliance escalation\n */\n gracePeriodDays: z.number().default(30)\n .describe('Grace period in days after certification expiry'),\n\n /**\n * Whether to send reminders for upcoming training deadlines\n */\n sendReminders: z.boolean().default(true)\n .describe('Send reminders for upcoming training deadlines'),\n\n /**\n * Days before deadline to send first reminder\n */\n reminderDaysBefore: z.number().default(14)\n .describe('Days before deadline to send first reminder'),\n}).describe('Organizational training plan per ISO 27001:2022 A.6.3');\n\n// Type exports\nexport type TrainingCategory = z.infer;\nexport type TrainingCompletionStatus = z.infer;\nexport type TrainingCourse = z.infer;\nexport type TrainingRecord = z.infer;\nexport type TrainingPlan = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Cron Schedule Schema\n * Schedule jobs using cron expressions\n */\nexport const CronScheduleSchema = z.object({\n type: z.literal('cron'),\n expression: z.string().describe('Cron expression (e.g., \"0 0 * * *\" for daily at midnight)'),\n timezone: z.string().optional().default('UTC').describe('Timezone for cron execution (e.g., \"America/New_York\")'),\n});\n\n/**\n * Interval Schedule Schema\n * Schedule jobs at fixed intervals\n */\nexport const IntervalScheduleSchema = z.object({\n type: z.literal('interval'),\n intervalMs: z.number().int().positive().describe('Interval in milliseconds'),\n});\n\n/**\n * Once Schedule Schema\n * Schedule a job to run once at a specific time\n */\nexport const OnceScheduleSchema = z.object({\n type: z.literal('once'),\n at: z.string().datetime().describe('ISO 8601 datetime when to execute'),\n});\n\n/**\n * Schedule Schema\n * Discriminated union of all schedule types\n */\nexport const ScheduleSchema = z.discriminatedUnion('type', [\n CronScheduleSchema,\n IntervalScheduleSchema,\n OnceScheduleSchema,\n]);\n\nexport type Schedule = z.infer;\nexport type CronSchedule = z.infer;\nexport type IntervalSchedule = z.infer;\nexport type OnceSchedule = z.infer;\nexport type JobSchedule = Schedule; // Alias for backwards compatibility\n\n/**\n * Retry Policy Schema\n * Configuration for job retry behavior with exponential backoff\n */\nexport const RetryPolicySchema = z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum number of retry attempts'),\n backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay in milliseconds'),\n backoffMultiplier: z.number().positive().default(2).describe('Multiplier for exponential backoff'),\n});\n\nexport type RetryPolicy = z.infer;\n\n/**\n * Job Schema\n * Defines a scheduled job that executes background logic.\n * \n * @example Metadata Sync Job (Cron)\n * {\n * id: \"job_sync_meta\",\n * name: \"sync_metadata_nightly\",\n * schedule: {\n * type: \"cron\",\n * expression: \"0 0 * * *\", // Midnight\n * timezone: \"UTC\"\n * },\n * handler: \"services/syncStatus.ts:syncAll\", \n * retryPolicy: {\n * maxRetries: 3,\n * backoffMs: 5000\n * }\n * }\n */\nexport const JobSchema = z.object({\n id: z.string().describe('Unique job identifier'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Job name (snake_case)'),\n schedule: ScheduleSchema.describe('Job schedule configuration'),\n handler: z.string().describe('Handler path (e.g. \"path/to/file:functionName\") or script ID'),\n retryPolicy: RetryPolicySchema.optional().describe('Retry policy configuration'),\n timeout: z.number().int().positive().optional().describe('Timeout in milliseconds'),\n enabled: z.boolean().default(true).describe('Whether the job is enabled'),\n});\n\nexport type Job = z.infer;\n\n/**\n * Job Execution Status Enum\n * Status of job execution\n */\nexport const JobExecutionStatus = z.enum([\n 'running',\n 'success',\n 'failed',\n 'timeout',\n]);\n\nexport type JobExecutionStatus = z.infer;\n\n/**\n * Job Execution Schema\n * Logs for job execution\n */\nexport const JobExecutionSchema = z.object({\n jobId: z.string().describe('Job identifier'),\n startedAt: z.string().datetime().describe('ISO 8601 datetime when execution started'),\n completedAt: z.string().datetime().optional().describe('ISO 8601 datetime when execution completed'),\n status: JobExecutionStatus.describe('Execution status'),\n error: z.string().optional().describe('Error message if failed'),\n duration: z.number().int().optional().describe('Execution duration in milliseconds'),\n});\n\nexport type JobExecution = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Worker System Protocol\n * \n * Background task processing system with queues, priorities, and retry logic.\n * Provides a robust foundation for async task execution similar to:\n * - Sidekiq (Ruby)\n * - Celery (Python)\n * - Bull/BullMQ (Node.js)\n * - AWS SQS/Lambda\n * \n * Features:\n * - Task queues with priorities\n * - Task scheduling and retry logic\n * - Batch processing\n * - Dead letter queues\n * - Task monitoring and logging\n * \n * @example Basic task\n * ```typescript\n * const task: Task = {\n * id: 'task-123',\n * type: 'send_email',\n * payload: { to: 'user@example.com', subject: 'Welcome' },\n * queue: 'notifications',\n * priority: 5\n * };\n * ```\n */\n\n// ==========================================\n// Task Priority\n// ==========================================\n\n/**\n * Task Priority Enum\n * Lower numbers = higher priority\n */\nexport const TaskPriority = z.enum([\n 'critical', // 0 - Must execute immediately\n 'high', // 1 - Execute soon\n 'normal', // 2 - Default priority\n 'low', // 3 - Execute when resources available\n 'background', // 4 - Execute during low-traffic periods\n]);\n\nexport type TaskPriority = z.infer;\n\n/**\n * Task Priority Mapping\n * Maps priority names to numeric values for sorting\n */\nexport const TASK_PRIORITY_VALUES: Record = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n background: 4,\n};\n\n// ==========================================\n// Task Status\n// ==========================================\n\n/**\n * Task Status Enum\n * Lifecycle states of a task\n */\nexport const TaskStatus = z.enum([\n 'pending', // Waiting to be processed\n 'queued', // In queue, ready for worker\n 'processing', // Currently being executed\n 'completed', // Successfully completed\n 'failed', // Failed (may retry)\n 'cancelled', // Manually cancelled\n 'timeout', // Exceeded execution timeout\n 'dead', // Moved to dead letter queue\n]);\n\nexport type TaskStatus = z.infer;\n\n// ==========================================\n// Task Schema\n// ==========================================\n\n/**\n * Task Retry Policy Schema\n * Configuration for task retry behavior\n */\nexport const TaskRetryPolicySchema = z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy between retries'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay in milliseconds'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay in milliseconds'),\n backoffMultiplier: z.number().positive().default(2).describe('Multiplier for exponential backoff'),\n});\n\nexport type TaskRetryPolicy = z.infer;\nexport type TaskRetryPolicyInput = z.input;\n\n/**\n * Task Schema\n * Represents a background task to be executed\n * \n * @example\n * {\n * \"id\": \"task-abc123\",\n * \"type\": \"send_email\",\n * \"payload\": { \"to\": \"user@example.com\", \"template\": \"welcome\" },\n * \"queue\": \"notifications\",\n * \"priority\": \"high\",\n * \"retryPolicy\": {\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * }\n * }\n */\nexport const TaskSchema = z.object({\n /**\n * Unique task identifier\n */\n id: z.string().describe('Unique task identifier'),\n \n /**\n * Task type (handler identifier)\n */\n type: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Task type (snake_case)'),\n \n /**\n * Task payload data\n */\n payload: z.unknown().describe('Task payload data'),\n \n /**\n * Queue name\n */\n queue: z.string().default('default').describe('Queue name'),\n \n /**\n * Task priority\n */\n priority: TaskPriority.default('normal').describe('Task priority level'),\n \n /**\n * Retry policy\n */\n retryPolicy: TaskRetryPolicySchema.optional().describe('Retry policy configuration'),\n \n /**\n * Execution timeout in milliseconds\n */\n timeoutMs: z.number().int().positive().optional().describe('Task timeout in milliseconds'),\n \n /**\n * Scheduled execution time\n */\n scheduledAt: z.string().datetime().optional().describe('ISO 8601 datetime to execute task'),\n \n /**\n * Maximum execution attempts\n */\n attempts: z.number().int().min(0).default(0).describe('Number of execution attempts'),\n \n /**\n * Task status\n */\n status: TaskStatus.default('pending').describe('Current task status'),\n \n /**\n * Task metadata\n */\n metadata: z.object({\n createdAt: z.string().datetime().optional().describe('When task was created'),\n updatedAt: z.string().datetime().optional().describe('Last update time'),\n createdBy: z.string().optional().describe('User who created task'),\n tags: z.array(z.string()).optional().describe('Task tags for filtering'),\n }).optional().describe('Task metadata'),\n});\n\nexport type Task = z.infer;\nexport type TaskInput = z.input;\n\n// ==========================================\n// Task Execution Result\n// ==========================================\n\n/**\n * Task Execution Result Schema\n * Result of a task execution attempt\n */\nexport const TaskExecutionResultSchema = z.object({\n /**\n * Task identifier\n */\n taskId: z.string().describe('Task identifier'),\n \n /**\n * Execution status\n */\n status: TaskStatus.describe('Execution status'),\n \n /**\n * Execution result data\n */\n result: z.unknown().optional().describe('Execution result data'),\n \n /**\n * Error information\n */\n error: z.object({\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Error stack trace'),\n code: z.string().optional().describe('Error code'),\n }).optional().describe('Error details if failed'),\n \n /**\n * Execution duration\n */\n durationMs: z.number().int().optional().describe('Execution duration in milliseconds'),\n \n /**\n * Execution timestamps\n */\n startedAt: z.string().datetime().describe('When execution started'),\n completedAt: z.string().datetime().optional().describe('When execution completed'),\n \n /**\n * Retry information\n */\n attempt: z.number().int().min(1).describe('Attempt number (1-indexed)'),\n willRetry: z.boolean().describe('Whether task will be retried'),\n});\n\nexport type TaskExecutionResult = z.infer;\n\n// ==========================================\n// Queue Configuration\n// ==========================================\n\n/**\n * Queue Configuration Schema\n * Configuration for a task queue\n * \n * @example\n * {\n * \"name\": \"notifications\",\n * \"concurrency\": 10,\n * \"rateLimit\": {\n * \"max\": 100,\n * \"duration\": 60000\n * }\n * }\n */\nexport const QueueConfigSchema = z.object({\n /**\n * Queue name\n */\n name: z.string().describe('Queue name (snake_case)'),\n \n /**\n * Maximum concurrent workers\n */\n concurrency: z.number().int().min(1).default(5).describe('Max concurrent task executions'),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n max: z.number().int().positive().describe('Maximum tasks per duration'),\n duration: z.number().int().positive().describe('Duration in milliseconds'),\n }).optional().describe('Rate limit configuration'),\n \n /**\n * Default retry policy\n */\n defaultRetryPolicy: TaskRetryPolicySchema.optional().describe('Default retry policy for tasks'),\n \n /**\n * Dead letter queue\n */\n deadLetterQueue: z.string().optional().describe('Dead letter queue name'),\n \n /**\n * Queue priority\n */\n priority: z.number().int().min(0).default(0).describe('Queue priority (lower = higher priority)'),\n \n /**\n * Auto-scaling configuration\n */\n autoScale: z.object({\n enabled: z.boolean().default(false).describe('Enable auto-scaling'),\n minWorkers: z.number().int().min(1).default(1).describe('Minimum workers'),\n maxWorkers: z.number().int().min(1).default(10).describe('Maximum workers'),\n scaleUpThreshold: z.number().int().positive().default(100).describe('Queue size to scale up'),\n scaleDownThreshold: z.number().int().min(0).default(10).describe('Queue size to scale down'),\n }).optional().describe('Auto-scaling configuration'),\n});\n\nexport type QueueConfig = z.infer;\nexport type QueueConfigInput = z.input;\n\n// ==========================================\n// Batch Processing\n// ==========================================\n\n/**\n * Batch Task Schema\n * Configuration for batch processing multiple items\n * \n * @example\n * {\n * \"id\": \"batch-import-123\",\n * \"type\": \"import_records\",\n * \"items\": [{ \"name\": \"Item 1\" }, { \"name\": \"Item 2\" }],\n * \"batchSize\": 100,\n * \"queue\": \"batch_processing\"\n * }\n */\nexport const BatchTaskSchema = z.object({\n /**\n * Batch job identifier\n */\n id: z.string().describe('Unique batch job identifier'),\n \n /**\n * Task type for processing each item\n */\n type: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Task type (snake_case)'),\n \n /**\n * Items to process\n */\n items: z.array(z.unknown()).describe('Array of items to process'),\n \n /**\n * Batch size (items per task)\n */\n batchSize: z.number().int().min(1).default(100).describe('Number of items per batch'),\n \n /**\n * Queue name\n */\n queue: z.string().default('batch').describe('Queue for batch tasks'),\n \n /**\n * Priority\n */\n priority: TaskPriority.default('normal').describe('Batch task priority'),\n \n /**\n * Parallel processing\n */\n parallel: z.boolean().default(true).describe('Process batches in parallel'),\n \n /**\n * Stop on error\n */\n stopOnError: z.boolean().default(false).describe('Stop batch if any item fails'),\n \n /**\n * Progress callback\n * \n * Called after each batch completes to report progress.\n * Invoked asynchronously and should not throw errors.\n * If the callback throws, the error is logged but batch processing continues.\n * \n * @param progress - Object containing processed count, total count, and failed count\n */\n onProgress: z.function()\n .input(z.tuple([z.object({\n processed: z.number(),\n total: z.number(),\n failed: z.number(),\n })]))\n .output(z.void())\n .optional()\n .describe('Progress callback function (called after each batch)'),\n});\n\nexport type BatchTask = z.infer;\nexport type BatchTaskInput = z.input;\n\n/**\n * Batch Progress Schema\n * Tracks progress of a batch job\n */\nexport const BatchProgressSchema = z.object({\n /**\n * Batch job identifier\n */\n batchId: z.string().describe('Batch job identifier'),\n \n /**\n * Total items\n */\n total: z.number().int().min(0).describe('Total number of items'),\n \n /**\n * Processed items\n */\n processed: z.number().int().min(0).default(0).describe('Items processed'),\n \n /**\n * Successful items\n */\n succeeded: z.number().int().min(0).default(0).describe('Items succeeded'),\n \n /**\n * Failed items\n */\n failed: z.number().int().min(0).default(0).describe('Items failed'),\n \n /**\n * Progress percentage\n */\n percentage: z.number().min(0).max(100).describe('Progress percentage'),\n \n /**\n * Status\n */\n status: z.enum(['pending', 'running', 'completed', 'failed', 'cancelled']).describe('Batch status'),\n \n /**\n * Timestamps\n */\n startedAt: z.string().datetime().optional().describe('When batch started'),\n completedAt: z.string().datetime().optional().describe('When batch completed'),\n});\n\nexport type BatchProgress = z.infer;\nexport type BatchProgressInput = z.input;\n\n// ==========================================\n// Worker Configuration\n// ==========================================\n\n/**\n * Worker Configuration Schema\n * Configuration for a worker instance\n */\nexport const WorkerConfigSchema = z.object({\n /**\n * Worker name\n */\n name: z.string().describe('Worker name'),\n \n /**\n * Queues to process\n */\n queues: z.array(z.string()).min(1).describe('Queue names to process'),\n \n /**\n * Queue configurations\n */\n queueConfigs: z.array(QueueConfigSchema).optional().describe('Queue configurations'),\n \n /**\n * Polling interval\n */\n pollIntervalMs: z.number().int().positive().default(1000).describe('Queue polling interval in milliseconds'),\n \n /**\n * Visibility timeout\n */\n visibilityTimeoutMs: z.number().int().positive().default(30000)\n .describe('How long a task is invisible after being claimed'),\n \n /**\n * Task timeout\n */\n defaultTimeoutMs: z.number().int().positive().default(300000).describe('Default task timeout in milliseconds'),\n \n /**\n * Graceful shutdown timeout\n */\n shutdownTimeoutMs: z.number().int().positive().default(30000)\n .describe('Graceful shutdown timeout in milliseconds'),\n \n /**\n * Task handlers\n */\n handlers: z.record(z.string(), z.function()).optional().describe('Task type handlers'),\n});\n\nexport type WorkerConfig = z.infer;\nexport type WorkerConfigInput = z.input;\n\n// ==========================================\n// Worker Stats\n// ==========================================\n\n/**\n * Worker Stats Schema\n * Runtime statistics for a worker\n */\nexport const WorkerStatsSchema = z.object({\n /**\n * Worker name\n */\n workerName: z.string().describe('Worker name'),\n \n /**\n * Total tasks processed\n */\n totalProcessed: z.number().int().min(0).describe('Total tasks processed'),\n \n /**\n * Successful tasks\n */\n succeeded: z.number().int().min(0).describe('Successful tasks'),\n \n /**\n * Failed tasks\n */\n failed: z.number().int().min(0).describe('Failed tasks'),\n \n /**\n * Active tasks\n */\n active: z.number().int().min(0).describe('Currently active tasks'),\n \n /**\n * Average execution time\n */\n avgExecutionMs: z.number().min(0).optional().describe('Average execution time in milliseconds'),\n \n /**\n * Uptime\n */\n uptimeMs: z.number().int().min(0).describe('Worker uptime in milliseconds'),\n \n /**\n * Queue stats\n */\n queues: z.record(z.string(), z.object({\n pending: z.number().int().min(0).describe('Pending tasks'),\n active: z.number().int().min(0).describe('Active tasks'),\n completed: z.number().int().min(0).describe('Completed tasks'),\n failed: z.number().int().min(0).describe('Failed tasks'),\n })).optional().describe('Per-queue statistics'),\n});\n\nexport type WorkerStats = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create a task\n */\nexport const Task = Object.assign(TaskSchema, {\n create: >(task: T) => task,\n});\n\n/**\n * Helper to create a queue config\n */\nexport const QueueConfig = Object.assign(QueueConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create a worker config\n */\nexport const WorkerConfig = Object.assign(WorkerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create a batch task\n */\nexport const BatchTask = Object.assign(BatchTaskSchema, {\n create: >(batch: T) => batch,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Email Template Schema\n * \n * Defines the structure and content of email notifications.\n * Supports variables for personalization and file attachments.\n * \n * @example\n * ```json\n * {\n * \"id\": \"welcome-email\",\n * \"subject\": \"Welcome to {{company_name}}\",\n * \"body\": \"

Welcome {{user_name}}!

\",\n * \"bodyType\": \"html\",\n * \"variables\": [\"company_name\", \"user_name\"],\n * \"attachments\": [\n * {\n * \"name\": \"guide.pdf\",\n * \"url\": \"https://example.com/guide.pdf\"\n * }\n * ]\n * }\n * ```\n */\nexport const EmailTemplateSchema = z.object({\n /**\n * Unique identifier for the email template\n */\n id: z.string().describe('Template identifier'),\n\n /**\n * Email subject line (supports variable interpolation)\n */\n subject: z.string().describe('Email subject'),\n\n /**\n * Email body content\n */\n body: z.string().describe('Email body content'),\n\n /**\n * Content type of the email body\n * @default 'html'\n */\n bodyType: z.enum(['text', 'html', 'markdown']).optional().default('html').describe('Body content type'),\n\n /**\n * List of template variables for dynamic content\n */\n variables: z.array(z.string()).optional().describe('Template variables'),\n\n /**\n * File attachments to include with the email\n */\n attachments: z.array(z.object({\n name: z.string().describe('Attachment filename'),\n url: z.string().url().describe('Attachment URL'),\n })).optional().describe('Email attachments'),\n});\n\n/**\n * SMS Template Schema\n * \n * Defines the structure of SMS text message notifications.\n * Includes character limits and variable support.\n * \n * @example\n * ```json\n * {\n * \"id\": \"verification-sms\",\n * \"message\": \"Your code is {{code}}\",\n * \"maxLength\": 160,\n * \"variables\": [\"code\"]\n * }\n * ```\n */\nexport const SMSTemplateSchema = z.object({\n /**\n * Unique identifier for the SMS template\n */\n id: z.string().describe('Template identifier'),\n\n /**\n * SMS message content (supports variable interpolation)\n */\n message: z.string().describe('SMS message content'),\n\n /**\n * Maximum character length for the SMS\n * @default 160\n */\n maxLength: z.number().optional().default(160).describe('Maximum message length'),\n\n /**\n * List of template variables for dynamic content\n */\n variables: z.array(z.string()).optional().describe('Template variables'),\n});\n\n/**\n * Push Notification Schema\n * \n * Defines mobile and web push notification structure.\n * Supports rich notifications with actions and badges.\n * \n * @example\n * ```json\n * {\n * \"title\": \"New Message\",\n * \"body\": \"You have a new message from John\",\n * \"icon\": \"https://example.com/icon.png\",\n * \"badge\": 5,\n * \"data\": {\"messageId\": \"msg_123\"},\n * \"actions\": [\n * {\"action\": \"view\", \"title\": \"View\"},\n * {\"action\": \"dismiss\", \"title\": \"Dismiss\"}\n * ]\n * }\n * ```\n */\nexport const PushNotificationSchema = z.object({\n /**\n * Notification title\n */\n title: z.string().describe('Notification title'),\n\n /**\n * Notification body text\n */\n body: z.string().describe('Notification body'),\n\n /**\n * Icon URL to display with notification\n */\n icon: z.string().url().optional().describe('Notification icon URL'),\n\n /**\n * Badge count to display on app icon\n */\n badge: z.number().optional().describe('Badge count'),\n\n /**\n * Custom data payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Custom data'),\n\n /**\n * Action buttons for the notification\n */\n actions: z.array(z.object({\n action: z.string().describe('Action identifier'),\n title: z.string().describe('Action button title'),\n })).optional().describe('Notification actions'),\n});\n\n/**\n * In-App Notification Schema\n * \n * Defines in-application notification banners and toasts.\n * Includes severity levels and auto-dismiss settings.\n * \n * @example\n * ```json\n * {\n * \"title\": \"System Update\",\n * \"message\": \"New features are now available\",\n * \"type\": \"info\",\n * \"actionUrl\": \"/updates\",\n * \"dismissible\": true,\n * \"expiresAt\": 1704067200000\n * }\n * ```\n */\nexport const InAppNotificationSchema = z.object({\n /**\n * Notification title\n */\n title: z.string().describe('Notification title'),\n\n /**\n * Notification message content\n */\n message: z.string().describe('Notification message'),\n\n /**\n * Notification severity type\n */\n type: z.enum(['info', 'success', 'warning', 'error']).describe('Notification type'),\n\n /**\n * Optional URL to navigate to when clicked\n */\n actionUrl: z.string().optional().describe('Action URL'),\n\n /**\n * Whether the notification can be dismissed by the user\n * @default true\n */\n dismissible: z.boolean().optional().default(true).describe('User dismissible'),\n\n /**\n * Timestamp when notification expires (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Expiration timestamp'),\n});\n\n/**\n * Notification Channel Enum\n * \n * Supported notification delivery channels.\n */\nexport const NotificationChannelSchema = z.enum([\n 'email',\n 'sms',\n 'push',\n 'in-app',\n 'slack',\n 'teams',\n 'webhook',\n]);\n\n/**\n * Notification Configuration Schema\n * \n * Unified notification management protocol supporting multiple channels.\n * Includes scheduling, retry policies, and delivery tracking.\n * \n * @example\n * ```json\n * {\n * \"id\": \"welcome-notification\",\n * \"name\": \"Welcome Email\",\n * \"channel\": \"email\",\n * \"template\": {\n * \"id\": \"tpl-001\",\n * \"subject\": \"Welcome!\",\n * \"body\": \"

Welcome

\",\n * \"bodyType\": \"html\"\n * },\n * \"recipients\": {\n * \"to\": [\"user@example.com\"],\n * \"cc\": [\"admin@example.com\"]\n * },\n * \"schedule\": {\n * \"type\": \"immediate\"\n * },\n * \"retryPolicy\": {\n * \"enabled\": true,\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * },\n * \"tracking\": {\n * \"trackOpens\": true,\n * \"trackClicks\": true,\n * \"trackDelivery\": true\n * }\n * }\n * ```\n */\nexport const NotificationConfigSchema = z.object({\n /**\n * Unique identifier for this notification configuration\n */\n id: z.string().describe('Notification ID'),\n\n /**\n * Human-readable name for this notification\n */\n name: z.string().describe('Notification name'),\n\n /**\n * Delivery channel for the notification\n */\n channel: NotificationChannelSchema.describe('Notification channel'),\n\n /**\n * Notification template based on channel type\n */\n template: z.union([\n EmailTemplateSchema,\n SMSTemplateSchema,\n PushNotificationSchema,\n InAppNotificationSchema,\n ]).describe('Notification template'),\n\n /**\n * Recipient configuration\n */\n recipients: z.object({\n /**\n * Primary recipients\n */\n to: z.array(z.string()).describe('Primary recipients'),\n\n /**\n * CC recipients (email only)\n */\n cc: z.array(z.string()).optional().describe('CC recipients'),\n\n /**\n * BCC recipients (email only)\n */\n bcc: z.array(z.string()).optional().describe('BCC recipients'),\n }).describe('Recipients'),\n\n /**\n * Scheduling configuration\n */\n schedule: z.object({\n /**\n * Scheduling type\n */\n type: z.enum(['immediate', 'delayed', 'scheduled']).describe('Schedule type'),\n\n /**\n * Delay in milliseconds (for delayed type)\n */\n delay: z.number().optional().describe('Delay in milliseconds'),\n\n /**\n * Scheduled send time (Unix timestamp in milliseconds)\n */\n scheduledAt: z.number().optional().describe('Scheduled timestamp'),\n }).optional().describe('Scheduling'),\n\n /**\n * Retry policy for failed deliveries\n */\n retryPolicy: z.object({\n /**\n * Enable automatic retries\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Enable retries'),\n\n /**\n * Maximum number of retry attempts\n * @default 3\n */\n maxRetries: z.number().optional().default(3).describe('Max retry attempts'),\n\n /**\n * Backoff strategy for retries\n */\n backoffStrategy: z.enum(['exponential', 'linear', 'fixed']).describe('Backoff strategy'),\n }).optional().describe('Retry policy'),\n\n /**\n * Delivery tracking configuration\n */\n tracking: z.object({\n /**\n * Track when emails are opened\n * @default false\n */\n trackOpens: z.boolean().optional().default(false).describe('Track opens'),\n\n /**\n * Track when links are clicked\n * @default false\n */\n trackClicks: z.boolean().optional().default(false).describe('Track clicks'),\n\n /**\n * Track delivery status\n * @default true\n */\n trackDelivery: z.boolean().optional().default(true).describe('Track delivery'),\n }).optional().describe('Tracking configuration'),\n});\n\n// Type exports\nexport type NotificationConfig = z.infer;\nexport type NotificationChannel = z.infer;\nexport type EmailTemplate = z.infer;\nexport type SMSTemplate = z.infer;\nexport type PushNotification = z.infer;\nexport type InAppNotification = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const LocaleSchema = z.string().describe('BCP-47 Language Tag (e.g. en-US, zh-CN)');\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-level Translation (per-object file)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Field Translation Schema\n * Translation data for a single field.\n */\nexport const FieldTranslationSchema = z.object({\n label: z.string().optional().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n placeholder: z.string().optional().describe('Translated placeholder text for form inputs'),\n options: z.record(z.string(), z.string()).optional().describe('Option value to translated label map'),\n}).describe('Translation data for a single field');\n\nexport type FieldTranslation = z.infer;\n\n/**\n * Object Translation Data Schema\n *\n * Translation data for a **single object** in a **single locale**.\n * Use this schema to validate per-object translation files.\n *\n * File convention: `i18n/{locale}/{object_name}.json`\n *\n * @example\n * ```json\n * // i18n/en/account.json\n * {\n * \"label\": \"Account\",\n * \"pluralLabel\": \"Accounts\",\n * \"fields\": {\n * \"name\": { \"label\": \"Account Name\", \"help\": \"Legal name\" },\n * \"type\": { \"label\": \"Type\", \"options\": { \"customer\": \"Customer\" } }\n * }\n * }\n * ```\n */\nexport const ObjectTranslationDataSchema = z.object({\n /** Translated singular label for the object */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label for the object */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional().describe('Field-level translations'),\n}).describe('Translation data for a single object');\n\nexport type ObjectTranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale-level Translation Data (per-locale aggregate)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Data Schema\n * Supports i18n for labels, messages, and options within a single locale.\n * Example structure:\n * ```json\n * {\n * \"objects\": { \"account\": { \"label\": \"Account\" } },\n * \"apps\": { \"crm\": { \"label\": \"CRM\" } },\n * \"messages\": { \"common.save\": \"Save\" }\n * }\n * ```\n */\nexport const TranslationDataSchema = z.object({\n /** Object translations */\n objects: z.record(z.string(), ObjectTranslationDataSchema).optional().describe('Object translations keyed by object name'),\n \n /** App/Menu translations */\n apps: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** UI Messages */\n messages: z.record(z.string(), z.string()).optional().describe('UI message translations keyed by message ID'),\n \n /** Validation Error Messages */\n validationMessages: z.record(z.string(), z.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {\"discount_limit\": \"折扣不能超过40%\"})'),\n}).describe('Translation data for objects, apps, and UI messages');\n\nexport type TranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Bundle (all locales)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const TranslationBundleSchema = z.record(LocaleSchema, TranslationDataSchema).describe('Map of locale codes to translation data');\n\nexport type TranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// File Organization Convention\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation File Organization Strategy\n *\n * Defines how translation files are organized on disk.\n *\n * - `bundled` — All locales in a single `TranslationBundle` file.\n * Best for small projects with few objects.\n * ```\n * src/translations/\n * crm.translation.ts # { en: {...}, \"zh-CN\": {...} }\n * ```\n *\n * - `per_locale` — One file per locale containing all namespaces.\n * Recommended when a single locale file stays under ~500 lines.\n * ```\n * src/translations/\n * en.ts # TranslationData for English\n * zh-CN.ts # TranslationData for Chinese\n * ```\n *\n * - `per_namespace` — One file per namespace (object) per locale.\n * Recommended for large projects with many objects/languages.\n * Aligns with Salesforce DX and ServiceNow conventions.\n * ```\n * i18n/\n * en/\n * account.json # ObjectTranslationData\n * contact.json\n * common.json # messages + app labels\n * zh-CN/\n * account.json\n * contact.json\n * common.json\n * ```\n */\nexport const TranslationFileOrganizationSchema = z.enum([\n 'bundled',\n 'per_locale',\n 'per_namespace',\n]).describe('Translation file organization strategy');\n\nexport type TranslationFileOrganization = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Configuration\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Configuration Schema\n *\n * Defines internationalization settings for the stack.\n *\n * @example\n * ```typescript\n * export default defineStack({\n * i18n: {\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'zh-CN', 'ja-JP'],\n * fallbackLocale: 'en',\n * fileOrganization: 'per_locale',\n * },\n * translations: [...],\n * });\n * ```\n */\n/**\n * Message format standard used for interpolation, pluralization, and\n * gender-aware translations.\n *\n * - `icu` — ICU MessageFormat (recommended for complex plurals, gender, select).\n * Strings may contain `{count, plural, one {# item} other {# items}}` patterns.\n * - `simple` — Simple `{variable}` interpolation only (default).\n */\nexport const MessageFormatSchema = z.enum([\n 'icu',\n 'simple',\n]).describe('Message interpolation format: ICU MessageFormat or simple {variable} replacement');\n\nexport type MessageFormat = z.infer;\n\nexport const TranslationConfigSchema = z.object({\n /** Default locale for the application */\n defaultLocale: LocaleSchema.describe('Default locale (e.g., \"en\")'),\n /** Supported BCP-47 locale codes */\n supportedLocales: z.array(LocaleSchema).describe('Supported BCP-47 locale codes'),\n /** Fallback locale when translation is not found */\n fallbackLocale: LocaleSchema.optional().describe('Fallback locale code'),\n /** How translation files are organized on disk */\n fileOrganization: TranslationFileOrganizationSchema.default('per_locale')\n .describe('File organization strategy'),\n /**\n * Message interpolation format.\n * When set to `'icu'`, messages and validationMessages are expected to use\n * ICU MessageFormat syntax (plurals, select, number/date skeletons).\n * @default 'simple'\n */\n messageFormat: MessageFormatSchema.default('simple')\n .describe('Message interpolation format (ICU MessageFormat or simple)'),\n /** Load translations on demand instead of eagerly */\n lazyLoad: z.boolean().default(false).describe('Load translations on demand'),\n /** Cache loaded translations in memory */\n cache: z.boolean().default(true).describe('Cache loaded translations'),\n}).describe('Internationalization configuration');\n\nexport type TranslationConfig = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-First Translation Node (object-first aggregated structure)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Translatable option map: option value → translated label */\nconst OptionTranslationMapSchema = z.record(z.string(), z.string())\n .describe('Option value to translated label map');\n\n/**\n * ObjectTranslationNodeSchema\n *\n * Object-first aggregated translation node that groups **all** translatable\n * content for a single object under one key. Aligns with Salesforce / Dynamics\n * conventions where translations are organized per-object rather than per-category.\n *\n * Located at `o.{object_name}` inside an {@link AppTranslationBundle}.\n *\n * @example\n * ```typescript\n * const accountNode: ObjectTranslationNode = {\n * label: '客户',\n * pluralLabel: '客户',\n * description: '客户管理对象',\n * fields: {\n * name: { label: '客户名称', help: '公司或组织的法定名称' },\n * industry: { label: '行业', options: { tech: '科技', finance: '金融' } },\n * },\n * _options: { status: { active: '活跃', inactive: '停用' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: {\n * convert_lead: { label: '转换线索', confirmMessage: '确认转换?' },\n * },\n * };\n * ```\n */\nexport const ObjectTranslationNodeSchema = z.object({\n /** Translated singular label */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Translated object description */\n description: z.string().optional().describe('Translated object description'),\n /** Translated help text shown in tooltips or guidance panels */\n helpText: z.string().optional().describe('Translated help text for the object'),\n\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional()\n .describe('Field translations keyed by field name'),\n\n /**\n * Global picklist / select option overrides scoped to this object.\n * Keyed by field name → { optionValue: translatedLabel }.\n */\n _options: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Object-scoped picklist option translations keyed by field name'),\n\n /** View translations keyed by view name */\n _views: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated view label'),\n description: z.string().optional().describe('Translated view description'),\n })).optional().describe('View translations keyed by view name'),\n\n /** Section (form section / tab) translations keyed by section name */\n _sections: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated section label'),\n })).optional().describe('Section translations keyed by section name'),\n\n /** Action translations keyed by action name */\n _actions: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated action label'),\n confirmMessage: z.string().optional().describe('Translated confirmation message'),\n })).optional().describe('Action translations keyed by action name'),\n\n /** Notification message translations keyed by notification name */\n _notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Notification translations keyed by notification name'),\n\n /** Error message translations keyed by error code */\n _errors: z.record(z.string(), z.string()).optional()\n .describe('Error message translations keyed by error code'),\n}).describe('Object-first aggregated translation node');\n\nexport type ObjectTranslationNode = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// App Translation Bundle (object-first, full application)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * AppTranslationBundleSchema\n *\n * Complete application translation bundle for a **single locale** using\n * the **object-first** convention. All per-object translatable content\n * is aggregated under `o.{object_name}`, while global (non-object-bound)\n * translations are kept in dedicated top-level groups.\n *\n * This schema is designed for:\n * - Translation workbench UIs (object-level editing & coverage)\n * - CLI skeleton generation (`objectstack i18n extract`)\n * - Automated diff/coverage detection\n *\n * @example\n * ```typescript\n * const zh: AppTranslationBundle = {\n * o: {\n * account: {\n * label: '客户',\n * fields: { name: { label: '客户名称' } },\n * _options: { industry: { tech: '科技' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: { convert: { label: '转换' } },\n * },\n * },\n * _globalOptions: { currency: { usd: '美元', eur: '欧元' } },\n * app: { crm: { label: '客户关系管理', description: '管理销售流程' } },\n * nav: { home: '首页', settings: '设置' },\n * dashboard: { sales_overview: { label: '销售概览' } },\n * reports: { pipeline_report: { label: '管道报表' } },\n * pages: { landing: { title: '欢迎' } },\n * messages: { 'common.save': '保存' },\n * validationMessages: { 'discount_limit': '折扣不能超过40%' },\n * };\n * ```\n */\nexport const AppTranslationBundleSchema = z.object({\n /**\n * Bundle-level metadata.\n * Provides locale-aware rendering hints such as text direction (bidi)\n * and the canonical locale code this bundle represents.\n */\n _meta: z.object({\n /** BCP-47 locale code this bundle represents */\n locale: z.string().optional().describe('BCP-47 locale code for this bundle'),\n /** Text direction for the locale */\n direction: z.enum(['ltr', 'rtl']).optional().describe('Text direction: left-to-right or right-to-left'),\n }).optional().describe('Bundle-level metadata (locale, bidi direction)'),\n\n /**\n * Namespace for plugin/extension isolation.\n * When multiple plugins contribute translations, each should use a unique\n * namespace to avoid key collisions (e.g. \"crm\", \"helpdesk\", \"plugin-xyz\").\n */\n namespace: z.string().optional()\n .describe('Namespace for plugin isolation to avoid translation key collisions'),\n\n /** Object-first translations keyed by object name (snake_case) */\n o: z.record(z.string(), ObjectTranslationNodeSchema).optional()\n .describe('Object-first translations keyed by object name'),\n\n /** Global picklist options not bound to any specific object */\n _globalOptions: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Global picklist option translations keyed by option set name'),\n\n /** App-level translations */\n app: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** Navigation menu translations */\n nav: z.record(z.string(), z.string()).optional()\n .describe('Navigation item translations keyed by nav item name'),\n\n /** Dashboard translations keyed by dashboard name */\n dashboard: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated dashboard label'),\n description: z.string().optional().describe('Translated dashboard description'),\n })).optional().describe('Dashboard translations keyed by dashboard name'),\n\n /** Report translations keyed by report name */\n reports: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated report label'),\n description: z.string().optional().describe('Translated report description'),\n })).optional().describe('Report translations keyed by report name'),\n\n /** Page translations keyed by page name */\n pages: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated page title'),\n description: z.string().optional().describe('Translated page description'),\n })).optional().describe('Page translations keyed by page name'),\n\n /** UI message translations (supports ICU MessageFormat when enabled) */\n messages: z.record(z.string(), z.string()).optional()\n .describe('UI message translations keyed by message ID (supports ICU MessageFormat)'),\n\n /** Validation error message translations (supports ICU MessageFormat when enabled) */\n validationMessages: z.record(z.string(), z.string()).optional()\n .describe('Validation error message translations keyed by rule name (supports ICU MessageFormat)'),\n\n /** Global notification translations not bound to a specific object */\n notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Global notification translations keyed by notification name'),\n\n /** Global error message translations not bound to a specific object */\n errors: z.record(z.string(), z.string()).optional()\n .describe('Global error message translations keyed by error code'),\n}).describe('Object-first application translation bundle for a single locale');\n\nexport type AppTranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Diff & Coverage\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Diff Status\n *\n * Status of a single translation entry compared to the source metadata.\n */\nexport const TranslationDiffStatusSchema = z.enum([\n 'missing',\n 'redundant',\n 'stale',\n]).describe('Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)');\n\nexport type TranslationDiffStatus = z.infer;\n\n/**\n * TranslationDiffItemSchema\n *\n * Describes a single translation key that is missing, redundant, or stale\n * relative to the source metadata. Used by CLI/API diff detection.\n *\n * @example\n * ```typescript\n * const item: TranslationDiffItem = {\n * key: 'o.account.fields.website.label',\n * status: 'missing',\n * objectName: 'account',\n * locale: 'zh-CN',\n * };\n * ```\n */\nexport const TranslationDiffItemSchema = z.object({\n /** Dot-path translation key (e.g. \"o.account.fields.website.label\") */\n key: z.string().describe('Dot-path translation key'),\n /** Diff status */\n status: TranslationDiffStatusSchema.describe('Diff status of this translation key'),\n /** Object name if the key belongs to an object translation node */\n objectName: z.string().optional().describe('Associated object name (snake_case)'),\n /** Locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /**\n * Hash of the source metadata value at the time the translation was made.\n * Used by CLI/Workbench to detect stale translations without a full diff.\n */\n sourceHash: z.string().optional().describe('Hash of source metadata for precise stale detection'),\n /**\n * AI-suggested translation text for missing or stale entries.\n * Populated by AI translation hooks or TMS integrations.\n */\n aiSuggested: z.string().optional().describe('AI-suggested translation for this key'),\n /** Confidence score (0-1) for the AI suggestion */\n aiConfidence: z.number().min(0).max(1).optional().describe('AI suggestion confidence score (0–1)'),\n}).describe('A single translation diff item');\n\nexport type TranslationDiffItem = z.infer;\n\n/**\n * TranslationCoverageResultSchema\n *\n * Aggregated coverage result for a locale, optionally scoped to a single object.\n * Returned by the i18n diff detection API.\n *\n * @example\n * ```typescript\n * const result: TranslationCoverageResult = {\n * locale: 'zh-CN',\n * totalKeys: 120,\n * translatedKeys: 105,\n * missingKeys: 12,\n * redundantKeys: 3,\n * staleKeys: 0,\n * coveragePercent: 87.5,\n * items: [ ... ],\n * };\n * ```\n */\n/**\n * Per-group coverage breakdown entry.\n */\nexport const CoverageBreakdownEntrySchema = z.object({\n /** Group category (e.g. \"fields\", \"views\", \"actions\", \"messages\") */\n group: z.string().describe('Translation group category'),\n /** Total translatable keys in this group */\n totalKeys: z.number().int().nonnegative().describe('Total keys in this group'),\n /** Number of translated keys in this group */\n translatedKeys: z.number().int().nonnegative().describe('Translated keys in this group'),\n /** Coverage percentage for this group */\n coveragePercent: z.number().min(0).max(100).describe('Coverage percentage for this group'),\n}).describe('Coverage breakdown for a single translation group');\n\nexport type CoverageBreakdownEntry = z.infer;\n\nexport const TranslationCoverageResultSchema = z.object({\n /** BCP-47 locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /** Optional object name scope */\n objectName: z.string().optional().describe('Object name scope (omit for full bundle)'),\n /** Total translatable keys derived from metadata */\n totalKeys: z.number().int().nonnegative().describe('Total translatable keys from metadata'),\n /** Number of keys that have a translation */\n translatedKeys: z.number().int().nonnegative().describe('Number of translated keys'),\n /** Number of missing translations */\n missingKeys: z.number().int().nonnegative().describe('Number of missing translations'),\n /** Number of redundant (orphaned) translations */\n redundantKeys: z.number().int().nonnegative().describe('Number of redundant translations'),\n /** Number of stale translations */\n staleKeys: z.number().int().nonnegative().describe('Number of stale translations'),\n /** Coverage percentage (0-100) */\n coveragePercent: z.number().min(0).max(100).describe('Translation coverage percentage'),\n /** Individual diff items */\n items: z.array(TranslationDiffItemSchema).describe('Detailed diff items'),\n /**\n * Per-group coverage breakdown for translation project management.\n * Each entry represents a logical group (e.g. \"fields\", \"views\", \"actions\",\n * \"messages\") with its own coverage statistics.\n */\n breakdown: z.array(CoverageBreakdownEntrySchema).optional()\n .describe('Per-group coverage breakdown'),\n}).describe('Aggregated translation coverage result');\n\nexport type TranslationCoverageResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Translation Skeleton Protocol Constants\n *\n * Defines the placeholder convention used in AI-friendly translation\n * skeleton templates. Runtime implementations (skeleton generation,\n * validation) belong in implementation packages (CLI, service-i18n, etc.).\n *\n * @example\n * ```json\n * {\n * \"label\": \"__TRANSLATE__: \\\"Task\\\"\",\n * \"fields\": {\n * \"subject\": { \"label\": \"__TRANSLATE__: \\\"Subject\\\"\" }\n * }\n * }\n * ```\n */\n\n/** Placeholder prefix used in translation skeleton output */\nexport const TRANSLATE_PLACEHOLDER = '__TRANSLATE__';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Real-Time Collaboration Protocol\n * \n * Defines schemas for real-time collaborative editing in ObjectStack.\n * Supports Operational Transformation (OT), CRDT (Conflict-free Replicated Data Types),\n * cursor sharing, and awareness state for collaborative applications.\n * \n * Industry alignment: Google Docs, Figma, VSCode Live Share, Yjs\n */\n\n// ==========================================\n// Operational Transformation (OT)\n// ==========================================\n\n/**\n * OT Operation Type Enum\n * Types of operations in Operational Transformation\n */\nexport const OTOperationType = z.enum([\n 'insert', // Insert characters at position\n 'delete', // Delete characters at position\n 'retain', // Keep characters (used for composing operations)\n]);\n\nexport type OTOperationType = z.infer;\n\n/**\n * OT Operation Component\n * Single component of an OT operation\n */\nexport const OTComponentSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('insert'),\n text: z.string().describe('Text to insert'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Text formatting attributes (e.g., bold, italic)'),\n }),\n z.object({\n type: z.literal('delete'),\n count: z.number().int().positive().describe('Number of characters to delete'),\n }),\n z.object({\n type: z.literal('retain'),\n count: z.number().int().positive().describe('Number of characters to retain'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Attribute changes to apply'),\n }),\n]);\n\nexport type OTComponent = z.infer;\n\n/**\n * OT Operation Schema\n * Represents a complete OT operation\n * Based on the OT algorithm used by Google Docs and other collaborative editors\n */\nexport const OTOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n documentId: z.string().describe('Document identifier'),\n userId: z.string().describe('User who created the operation'),\n sessionId: z.string().uuid().describe('Session identifier'),\n components: z.array(OTComponentSchema).describe('Operation components'),\n baseVersion: z.number().int().nonnegative().describe('Document version this operation is based on'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional operation metadata'),\n});\n\nexport type OTOperation = z.infer;\n\n/**\n * OT Transform Result\n * Result of transforming one operation against another\n */\nexport const OTTransformResultSchema = z.object({\n operation: OTOperationSchema.describe('Transformed operation'),\n transformed: z.boolean().describe('Whether transformation was applied'),\n conflicts: z.array(z.string()).optional().describe('Conflict descriptions if any'),\n});\n\nexport type OTTransformResult = z.infer;\n\n// ==========================================\n// CRDT (Conflict-free Replicated Data Types)\n// ==========================================\n\n/**\n * CRDT Type Enum\n * Types of CRDTs supported\n */\nexport const CRDTType = z.enum([\n 'lww-register', // Last-Write-Wins Register\n 'g-counter', // Grow-only Counter\n 'pn-counter', // Positive-Negative Counter\n 'g-set', // Grow-only Set\n 'or-set', // Observed-Remove Set\n 'lww-map', // Last-Write-Wins Map\n 'text', // CRDT-based Text (e.g., Yjs, Automerge)\n 'tree', // CRDT-based Tree structure\n 'json', // CRDT-based JSON (e.g., Automerge)\n]);\n\nexport type CRDTType = z.infer;\n\n/**\n * Vector Clock Schema\n * Tracks causality in distributed systems\n */\nexport const VectorClockSchema = z.object({\n clock: z.record(z.string(), z.number().int().nonnegative()).describe('Map of replica ID to logical timestamp'),\n});\n\nexport type VectorClock = z.infer;\n\n/**\n * LWW-Register Schema\n * Last-Write-Wins Register CRDT\n */\nexport const LWWRegisterSchema = z.object({\n type: z.literal('lww-register'),\n value: z.unknown().describe('Current register value'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of last write'),\n replicaId: z.string().describe('ID of replica that performed last write'),\n vectorClock: VectorClockSchema.optional().describe('Optional vector clock for causality tracking'),\n});\n\nexport type LWWRegister = z.infer;\n\n/**\n * Counter Operation Schema\n * Operations for Counter CRDTs\n */\nexport const CounterOperationSchema = z.object({\n replicaId: z.string().describe('Replica identifier'),\n delta: z.number().int().describe('Change amount (positive for increment, negative for decrement)'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of operation'),\n});\n\nexport type CounterOperation = z.infer;\n\n/**\n * G-Counter Schema\n * Grow-only Counter CRDT\n */\nexport const GCounterSchema = z.object({\n type: z.literal('g-counter'),\n counts: z.record(z.string(), z.number().int().nonnegative()).describe('Map of replica ID to count'),\n});\n\nexport type GCounter = z.infer;\n\n/**\n * PN-Counter Schema\n * Positive-Negative Counter CRDT (supports increment and decrement)\n */\nexport const PNCounterSchema = z.object({\n type: z.literal('pn-counter'),\n positive: z.record(z.string(), z.number().int().nonnegative()).describe('Positive increments per replica'),\n negative: z.record(z.string(), z.number().int().nonnegative()).describe('Negative increments per replica'),\n});\n\nexport type PNCounter = z.infer;\n\n/**\n * OR-Set Element Schema\n * Element in an Observed-Remove Set\n */\nexport const ORSetElementSchema = z.object({\n value: z.unknown().describe('Element value'),\n timestamp: z.string().datetime().describe('Addition timestamp'),\n replicaId: z.string().describe('Replica that added the element'),\n uid: z.string().uuid().describe('Unique identifier for this addition'),\n removed: z.boolean().optional().default(false).describe('Whether element has been removed'),\n});\n\nexport type ORSetElement = z.infer;\n\n/**\n * OR-Set Schema\n * Observed-Remove Set CRDT\n */\nexport const ORSetSchema = z.object({\n type: z.literal('or-set'),\n elements: z.array(ORSetElementSchema).describe('Set elements with metadata'),\n});\n\nexport type ORSet = z.infer;\n\n/**\n * Text CRDT Operation Schema\n * Operations for text-based CRDTs (e.g., Yjs, Automerge)\n */\nexport const TextCRDTOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n replicaId: z.string().describe('Replica identifier'),\n position: z.number().int().nonnegative().describe('Position in document'),\n insert: z.string().optional().describe('Text to insert'),\n delete: z.number().int().positive().optional().describe('Number of characters to delete'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of operation'),\n lamportTimestamp: z.number().int().nonnegative().describe('Lamport timestamp for ordering'),\n});\n\nexport type TextCRDTOperation = z.infer;\n\n/**\n * Text CRDT State Schema\n * State of a text-based CRDT document\n */\nexport const TextCRDTStateSchema = z.object({\n type: z.literal('text'),\n documentId: z.string().describe('Document identifier'),\n content: z.string().describe('Current text content'),\n operations: z.array(TextCRDTOperationSchema).describe('History of operations'),\n lamportClock: z.number().int().nonnegative().describe('Current Lamport clock value'),\n vectorClock: VectorClockSchema.describe('Vector clock for causality'),\n});\n\nexport type TextCRDTState = z.infer;\n\n/**\n * CRDT State Union\n * Discriminated union of all CRDT types\n */\nexport const CRDTStateSchema = z.discriminatedUnion('type', [\n LWWRegisterSchema,\n GCounterSchema,\n PNCounterSchema,\n ORSetSchema,\n TextCRDTStateSchema,\n]);\n\nexport type CRDTState = z.infer;\n\n/**\n * CRDT Merge Schema\n * Result of merging two CRDT states\n */\nexport const CRDTMergeResultSchema = z.object({\n state: CRDTStateSchema.describe('Merged CRDT state'),\n conflicts: z.array(z.object({\n type: z.string().describe('Conflict type'),\n description: z.string().describe('Conflict description'),\n resolved: z.boolean().describe('Whether conflict was automatically resolved'),\n })).optional().describe('Conflicts encountered during merge'),\n});\n\nexport type CRDTMergeResult = z.infer;\n\n// ==========================================\n// Cursor Sharing\n// ==========================================\n\n/**\n * Cursor Color Preset Enum\n * Standard color presets for cursor visualization\n */\nexport const CursorColorPreset = z.enum([\n 'blue',\n 'green',\n 'red',\n 'yellow',\n 'purple',\n 'orange',\n 'pink',\n 'teal',\n 'indigo',\n 'cyan',\n]);\n\nexport type CursorColorPreset = z.infer;\n\n/**\n * Cursor Style Schema\n * Visual styling for collaborative cursors\n */\nexport const CursorStyleSchema = z.object({\n color: z.union([CursorColorPreset, z.string()]).describe('Cursor color (preset or custom hex)'),\n opacity: z.number().min(0).max(1).optional().default(1).describe('Cursor opacity (0-1)'),\n label: z.string().optional().describe('Label to display with cursor (usually username)'),\n showLabel: z.boolean().optional().default(true).describe('Whether to show label'),\n pulseOnUpdate: z.boolean().optional().default(true).describe('Whether to pulse when cursor moves'),\n});\n\nexport type CursorStyle = z.infer;\n\n/**\n * Cursor Selection Schema\n * Represents a text selection in collaborative editing\n */\nexport const CursorSelectionSchema = z.object({\n anchor: z.object({\n line: z.number().int().nonnegative().describe('Anchor line number'),\n column: z.number().int().nonnegative().describe('Anchor column number'),\n }).describe('Selection anchor (start point)'),\n focus: z.object({\n line: z.number().int().nonnegative().describe('Focus line number'),\n column: z.number().int().nonnegative().describe('Focus column number'),\n }).describe('Selection focus (end point)'),\n direction: z.enum(['forward', 'backward']).optional().describe('Selection direction'),\n});\n\nexport type CursorSelection = z.infer;\n\n/**\n * Collaborative Cursor Schema\n * Complete cursor state for a collaborative user\n */\nexport const CollaborativeCursorSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier'),\n userName: z.string().describe('Display name of user'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Cursor line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Cursor column number (0-indexed)'),\n }).describe('Current cursor position'),\n selection: CursorSelectionSchema.optional().describe('Current text selection'),\n style: CursorStyleSchema.describe('Visual style for this cursor'),\n isTyping: z.boolean().optional().default(false).describe('Whether user is currently typing'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional cursor metadata'),\n});\n\nexport type CollaborativeCursor = z.infer;\n\n/**\n * Cursor Update Schema\n * Update to a collaborative cursor\n */\nexport const CursorUpdateSchema = z.object({\n position: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }).optional().describe('Updated cursor position'),\n selection: CursorSelectionSchema.optional().describe('Updated selection'),\n isTyping: z.boolean().optional().describe('Updated typing state'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type CursorUpdate = z.infer;\n\n// ==========================================\n// Awareness State\n// ==========================================\n\n/**\n * User Activity Status Enum\n * User activity status for awareness\n */\nexport const UserActivityStatus = z.enum([\n 'active', // User is actively editing\n 'idle', // User is idle but connected\n 'viewing', // User is viewing but not editing\n 'disconnected', // User is disconnected\n]);\n\nexport type UserActivityStatus = z.infer;\n\n/**\n * Awareness User State Schema\n * Tracks what a user is doing in the collaborative session\n */\nexport const AwarenessUserStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n userName: z.string().describe('Display name'),\n userAvatar: z.string().optional().describe('User avatar URL'),\n status: UserActivityStatus.describe('Current activity status'),\n currentDocument: z.string().optional().describe('Document ID user is currently editing'),\n currentView: z.string().optional().describe('Current view/page user is on'),\n lastActivity: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n joinedAt: z.string().datetime().describe('ISO 8601 datetime when user joined session'),\n permissions: z.array(z.string()).optional().describe('User permissions in this session'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional user state metadata'),\n});\n\nexport type AwarenessUserState = z.infer;\n\n/**\n * Awareness Session Schema\n * Represents the complete awareness state for a collaboration session\n */\nexport const AwarenessSessionSchema = z.object({\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().optional().describe('Document ID this session is for'),\n users: z.array(AwarenessUserStateSchema).describe('Active users in session'),\n startedAt: z.string().datetime().describe('ISO 8601 datetime when session started'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last update'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Session metadata'),\n});\n\nexport type AwarenessSession = z.infer;\n\n/**\n * Awareness Update Schema\n * Update to awareness state\n */\nexport const AwarenessUpdateSchema = z.object({\n status: UserActivityStatus.optional().describe('Updated status'),\n currentDocument: z.string().optional().describe('Updated current document'),\n currentView: z.string().optional().describe('Updated current view'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type AwarenessUpdate = z.infer;\n\n/**\n * Awareness Event Schema\n * Events that occur in awareness tracking\n */\nexport const AwarenessEventSchema = z.object({\n eventId: z.string().uuid().describe('Event identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n eventType: z.enum([\n 'user.joined',\n 'user.left',\n 'user.updated',\n 'session.created',\n 'session.ended',\n ]).describe('Type of awareness event'),\n userId: z.string().optional().describe('User involved in event'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of event'),\n payload: z.unknown().describe('Event payload'),\n});\n\nexport type AwarenessEvent = z.infer;\n\n// ==========================================\n// Collaboration Session Management\n// ==========================================\n\n/**\n * Collaboration Mode Enum\n * Types of collaboration modes\n */\nexport const CollaborationMode = z.enum([\n 'ot', // Operational Transformation\n 'crdt', // CRDT-based\n 'lock', // Pessimistic locking (turn-based)\n 'hybrid', // Hybrid approach\n]);\n\nexport type CollaborationMode = z.infer;\n\n/**\n * Collaboration Session Config\n * Configuration for a collaboration session\n */\nexport const CollaborationSessionConfigSchema = z.object({\n mode: CollaborationMode.describe('Collaboration mode to use'),\n enableCursorSharing: z.boolean().optional().default(true).describe('Enable cursor sharing'),\n enablePresence: z.boolean().optional().default(true).describe('Enable presence tracking'),\n enableAwareness: z.boolean().optional().default(true).describe('Enable awareness state'),\n maxUsers: z.number().int().positive().optional().describe('Maximum concurrent users'),\n idleTimeout: z.number().int().positive().optional().default(300000).describe('Idle timeout in milliseconds'),\n conflictResolution: z.enum(['ot', 'crdt', 'manual']).optional().default('ot').describe('Conflict resolution strategy'),\n persistence: z.boolean().optional().default(true).describe('Enable operation persistence'),\n snapshot: z.object({\n enabled: z.boolean().describe('Enable periodic snapshots'),\n interval: z.number().int().positive().describe('Snapshot interval in milliseconds'),\n }).optional().describe('Snapshot configuration'),\n});\n\nexport type CollaborationSessionConfig = z.infer;\n\n/**\n * Collaboration Session Schema\n * Complete collaboration session state\n */\nexport const CollaborationSessionSchema = z.object({\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier'),\n config: CollaborationSessionConfigSchema.describe('Session configuration'),\n users: z.array(AwarenessUserStateSchema).describe('Active users'),\n cursors: z.array(CollaborativeCursorSchema).describe('Active cursors'),\n version: z.number().int().nonnegative().describe('Current document version'),\n operations: z.array(z.union([OTOperationSchema, TextCRDTOperationSchema])).optional().describe('Recent operations'),\n createdAt: z.string().datetime().describe('ISO 8601 datetime when session was created'),\n lastActivity: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n status: z.enum(['active', 'idle', 'ended']).describe('Session status'),\n});\n\nexport type CollaborationSession = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metadata Scope Enum\n * Defines the lifecycle and mutability of a metadata item.\n */\nexport const MetadataScopeSchema = z.enum([\n 'system', // Defined in Code (Files). Read-only at runtime. Upgraded via deployment.\n 'platform', // Defined in DB (Global). admin-configured. Overrides system.\n 'user', // Defined in DB (Personal). User-configured. Overrides platform/system.\n]);\n\n/**\n * Metadata Lifecycle State\n */\nexport const MetadataStateSchema = z.enum([\n 'draft', // Work in progress, not active\n 'active', // Live and running\n 'archived', // Soft deleted\n 'deprecated' // Running but flagged for removal\n]);\n\n/**\n * Unified Metadata Persistence Protocol\n * \n * Defines the standardized envelope for storing ANY metadata item (Object, View, Flow)\n * in the database (e.g. `_framework_metadata` or generic `metadata` table).\n * \n * This treats \"Metadata as Data\".\n */\nexport const MetadataRecordSchema = z.object({\n /** Primary Key (UUID) */\n id: z.string(),\n \n /** \n * Machine Name \n * The unique identifier used in code references (e.g. \"account_list_view\").\n */\n name: z.string(),\n \n /**\n * Metadata Type\n * e.g. \"object\", \"view\", \"permission_set\", \"flow\"\n */\n type: z.string(),\n \n /**\n * Namespace / Module\n * Groups metadata into packages (e.g. \"crm\", \"finance\", \"core\").\n */\n namespace: z.string().default('default'),\n\n /**\n * Package Ownership Reference\n * Links this metadata record to the package that delivered it.\n * When set, the record is \"managed\" by the package and should not be\n * directly edited — customizations go through the overlay system.\n * Null/undefined means the record was created independently (not from a package).\n */\n packageId: z.string().optional().describe('Package ID that owns/delivered this metadata'),\n\n /**\n * Managed By Indicator\n * Determines who controls this metadata record's lifecycle.\n * - \"package\": Delivered and upgraded by a plugin package (read-only base)\n * - \"platform\": Created by platform admin via UI\n * - \"user\": Created by end user\n */\n managedBy: z.enum(['package', 'platform', 'user']).optional()\n .describe('Who manages this metadata record lifecycle'),\n \n /**\n * Ownership differentiation\n */\n scope: MetadataScopeSchema.default('platform'),\n \n /**\n * The Payload\n * Stores the actual configuration JSON.\n * This field holds the value of `ViewSchema`, `ObjectSchema`, etc.\n */\n metadata: z.record(z.string(), z.unknown()),\n\n /**\n * Extension / Merge Strategy\n * If this record overrides a system record, how should it be applied?\n */\n extends: z.string().optional().describe('Name of the parent metadata to extend/override'),\n strategy: z.enum(['merge', 'replace']).default('merge'),\n\n /** Owner (for user-scope items) */\n owner: z.string().optional(),\n \n /** State */\n state: MetadataStateSchema.default('active'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant isolation'),\n\n /** Version number for optimistic concurrency */\n version: z.number().default(1).describe('Record version for optimistic concurrency control'),\n\n /** Checksum for change detection */\n checksum: z.string().optional().describe('Content checksum for change detection'),\n\n /** Source origin marker */\n source: z.enum(['filesystem', 'database', 'api', 'migration']).optional().describe('Origin of this metadata record'),\n\n /** Classification tags */\n tags: z.array(z.string()).optional().describe('Classification tags for filtering and grouping'),\n \n /** Package Publishing */\n publishedDefinition: z.unknown().optional()\n .describe('Snapshot of the last published definition'),\n publishedAt: z.string().datetime().optional()\n .describe('When this metadata was last published'),\n publishedBy: z.string().optional()\n .describe('Who published this version'),\n\n /** Audit */\n createdBy: z.string().optional(),\n createdAt: z.string().datetime().optional().describe('Creation timestamp'),\n updatedBy: z.string().optional(),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n});\n\nexport type MetadataRecord = z.infer;\nexport type MetadataScope = z.infer;\n\n/**\n * Package Publish Result\n * Returned by `publishPackage()` after a package-level metadata publish operation.\n */\nexport const PackagePublishResultSchema = z.object({\n success: z.boolean().describe('Whether the publish succeeded'),\n packageId: z.string().describe('The package ID that was published'),\n version: z.number().int().describe('New version number after publish'),\n publishedAt: z.string().datetime().describe('Publish timestamp'),\n itemsPublished: z.number().int().describe('Total metadata items published'),\n validationErrors: z.array(z.object({\n type: z.string().describe('Metadata type that failed validation'),\n name: z.string().describe('Item name that failed validation'),\n message: z.string().describe('Validation error message'),\n })).optional().describe('Validation errors if publish failed'),\n});\n\nexport type PackagePublishResult = z.infer;\n\n/**\n * Metadata Format\n * Supported file formats for metadata serialization.\n */\nexport const MetadataFormatSchema = z.enum([\n 'json', 'yaml', 'yml', 'ts', 'js',\n 'typescript', 'javascript' // Aliases\n]);\n\n/**\n * Metadata Stats\n * Statistics about a metadata item.\n */\nexport const MetadataStatsSchema = z.object({\n path: z.string().optional(),\n size: z.number().optional(),\n mtime: z.string().datetime().optional(),\n hash: z.string().optional(),\n etag: z.string().optional(), // Required by local cache\n modifiedAt: z.string().datetime().optional(), // Alias for mtime\n format: MetadataFormatSchema.optional(), // Required for serialization\n});\n\n/**\n * Metadata Loader Contract\n * Describes the capabilities and identity of a metadata loader.\n */\nexport const MetadataLoaderContractSchema = z.object({\n name: z.string(),\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Loader protocol identifier'),\n description: z.string().optional(),\n supportedFormats: z.array(z.string()).optional(),\n supportsWatch: z.boolean().optional(),\n supportsWrite: z.boolean().optional(),\n supportsCache: z.boolean().optional(),\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n scope: MetadataScopeSchema.optional(),\n namespace: z.string().optional(),\n raw: z.boolean().optional().describe('Return raw file content instead of parsed JSON'),\n cache: z.boolean().optional(),\n useCache: z.boolean().optional(), // Alias for cache\n validate: z.boolean().optional(),\n ifNoneMatch: z.string().optional(), // For caching\n recursive: z.boolean().optional(),\n limit: z.number().optional(),\n patterns: z.array(z.string()).optional(),\n loader: z.string().optional().describe('Specific loader to use (e.g. filesystem, database)'),\n});\n\n/**\n * Metadata Load Result\n */\nexport const MetadataLoadResultSchema = z.object({\n data: z.unknown(),\n stats: MetadataStatsSchema.optional(),\n format: MetadataFormatSchema.optional(),\n source: z.string().optional(), // File path or URL\n fromCache: z.boolean().optional(),\n etag: z.string().optional(),\n notModified: z.boolean().optional(),\n loadTime: z.number().optional(),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n format: MetadataFormatSchema.optional(),\n create: z.boolean().default(true),\n overwrite: z.boolean().default(true),\n path: z.string().optional(),\n prettify: z.boolean().optional(),\n indent: z.number().optional(),\n sortKeys: z.boolean().optional(),\n backup: z.boolean().optional(),\n atomic: z.boolean().optional(),\n loader: z.string().optional().describe('Specific loader to use (e.g. filesystem, database)'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n success: z.boolean(),\n path: z.string().optional(),\n stats: MetadataStatsSchema.optional(),\n etag: z.string().optional(),\n size: z.number().optional(),\n saveTime: z.number().optional(),\n backupPath: z.string().optional(),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n type: z.enum(['add', 'change', 'unlink', 'added', 'changed', 'deleted']),\n path: z.string(),\n name: z.string().optional(),\n stats: MetadataStatsSchema.optional(),\n metadataType: z.string().optional(),\n data: z.unknown().optional(),\n timestamp: z.string().datetime().optional(),\n});\n\n/**\n * Metadata Collection Info\n */\nexport const MetadataCollectionInfoSchema = z.object({\n type: z.string(),\n count: z.number(),\n namespaces: z.array(z.string()),\n});\n\n/**\n * Metadata Export/Import Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n types: z.array(z.string()).optional(),\n namespaces: z.array(z.string()).optional(),\n output: z.string().describe('Output directory or file'),\n format: MetadataFormatSchema.default('json'),\n});\n\nexport const MetadataImportOptionsSchema = z.object({\n source: z.string().describe('Input directory or file'),\n strategy: z.enum(['merge', 'replace', 'skip']).default('merge'),\n validate: z.boolean().default(true),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Source Origin\n * Indicates where a metadata record was loaded from.\n */\nexport const MetadataSourceSchema = z.enum([\n 'filesystem', // Loaded from local files\n 'database', // Loaded from database via datasource\n 'api', // Loaded from remote API\n 'migration', // Created during a migration process\n]);\n\n/**\n * Metadata Manager Config\n * \n * Unified configuration for the MetadataManager.\n * Supports datasource-backed persistence via `datasource` field,\n * which references a DatasourceSchema.name resolved at runtime.\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n * When provided, metadata is persisted to a database table.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory for filesystem-based metadata'),\n\n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).optional().describe('Enabled metadata formats'),\n\n /**\n * Enable file watching\n */\n watch: z.boolean().optional().describe('Enable file watching for filesystem loaders'),\n\n /**\n * Cache configuration\n */\n cache: z.boolean().optional().describe('Enable metadata caching'),\n\n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n }).optional().describe('File watcher options'),\n});\n\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataLoadOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\nexport type MetadataSource = z.infer;\n\n/**\n * Metadata History Record\n *\n * Represents a single version snapshot in the metadata change history.\n * Stored in the sys_metadata_history table for version tracking and rollback.\n */\nexport const MetadataHistoryRecordSchema = z.object({\n /** Primary Key (UUID) */\n id: z.string(),\n\n /** Reference to the parent metadata record ID */\n metadataId: z.string().describe('Foreign key to sys_metadata.id'),\n\n /**\n * Machine Name\n * Denormalized from parent for easier querying.\n */\n name: z.string(),\n\n /**\n * Metadata Type\n * Denormalized from parent for easier querying.\n */\n type: z.string(),\n\n /**\n * Version Number\n * Snapshot of the metadata version at this point in history.\n */\n version: z.number().describe('Version number at this snapshot'),\n\n /**\n * Operation Type\n * Indicates what kind of change triggered this history record.\n */\n operationType: z.enum(['create', 'update', 'publish', 'revert', 'delete']).describe('Type of operation that created this history entry'),\n\n /**\n * Historical Metadata Snapshot\n * Full JSON payload of the metadata definition at this version.\n * May be stored as a raw JSON string in the history table, or as a parsed object\n * in higher-level APIs. When `includeMetadata` is false, this field is null.\n */\n metadata: z\n .union([z.string(), z.record(z.string(), z.unknown())])\n .nullable()\n .optional()\n .describe('Snapshot of metadata definition at this version (raw JSON string or parsed object)'),\n\n /**\n * Content Checksum\n * SHA-256 checksum of the normalized metadata JSON for change detection.\n */\n checksum: z.string().describe('SHA-256 checksum of metadata content'),\n\n /**\n * Previous Checksum\n * Checksum of the previous version for diff optimization.\n */\n previousChecksum: z.string().optional().describe('Checksum of the previous version'),\n\n /**\n * Change Note\n * Human-readable description of what changed in this version.\n */\n changeNote: z.string().optional().describe('Description of changes made in this version'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant isolation'),\n\n /** Audit: who made this change */\n recordedBy: z.string().optional().describe('User who made this change'),\n\n /** Audit: when was this version recorded */\n recordedAt: z.string().datetime().describe('Timestamp when this version was recorded'),\n});\n\nexport type MetadataHistoryRecord = z.infer;\n\n/**\n * Metadata History Query Options\n * Options for retrieving metadata version history.\n */\nexport const MetadataHistoryQueryOptionsSchema = z.object({\n /** Limit number of history records returned */\n limit: z.number().int().positive().optional().describe('Maximum number of history records to return'),\n\n /** Offset for pagination */\n offset: z.number().int().nonnegative().optional().describe('Number of records to skip'),\n\n /** Only return versions after this timestamp */\n since: z.string().datetime().optional().describe('Only return history after this timestamp'),\n\n /** Only return versions before this timestamp */\n until: z.string().datetime().optional().describe('Only return history before this timestamp'),\n\n /** Filter by operation type */\n operationType: z.enum(['create', 'update', 'publish', 'revert', 'delete']).optional().describe('Filter by operation type'),\n\n /** Include full metadata payload in results (default: true) */\n includeMetadata: z.boolean().optional().default(true).describe('Include full metadata payload'),\n});\n\nexport type MetadataHistoryQueryOptions = z.infer;\n\n/**\n * Metadata History Query Result\n * Result of querying metadata version history.\n */\nexport const MetadataHistoryQueryResultSchema = z.object({\n /** Array of history records */\n records: z.array(MetadataHistoryRecordSchema),\n\n /** Total number of history records (for pagination) */\n total: z.number().int().nonnegative(),\n\n /** Whether there are more records available */\n hasMore: z.boolean(),\n});\n\nexport type MetadataHistoryQueryResult = z.infer;\n\n/**\n * Metadata Diff Result\n * Result of comparing two versions of metadata.\n */\nexport const MetadataDiffResultSchema = z.object({\n /** Metadata type */\n type: z.string(),\n\n /** Metadata name */\n name: z.string(),\n\n /** Version 1 (older) */\n version1: z.number(),\n\n /** Version 2 (newer) */\n version2: z.number(),\n\n /** Checksum of version 1 */\n checksum1: z.string(),\n\n /** Checksum of version 2 */\n checksum2: z.string(),\n\n /** Whether the versions are identical */\n identical: z.boolean(),\n\n /** JSON patch operations to transform v1 into v2 */\n patch: z.array(z.unknown()).optional().describe('JSON patch operations'),\n\n /** Human-readable diff summary */\n summary: z.string().optional().describe('Human-readable summary of changes'),\n});\n\nexport type MetadataDiffResult = z.infer;\n\n/**\n * Metadata History Retention Policy\n * Configuration for automatic cleanup of old history records.\n */\nexport const MetadataHistoryRetentionPolicySchema = z.object({\n /** Maximum number of versions to keep per metadata item */\n maxVersions: z.number().int().positive().optional().describe('Maximum number of versions to retain'),\n\n /** Maximum age of history records in days */\n maxAgeDays: z.number().int().positive().optional().describe('Maximum age of history records in days'),\n\n /** Whether to enable automatic cleanup */\n autoCleanup: z.boolean().default(false).describe('Enable automatic cleanup of old history'),\n\n /** Cleanup interval in hours */\n cleanupIntervalHours: z.number().int().positive().default(24).describe('How often to run cleanup (in hours)'),\n});\n\nexport type MetadataHistoryRetentionPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Service Registry Protocol\n * \n * Defines the standard built-in services that constitute the ObjectStack Kernel.\n * This registry is used by the `ObjectKernel` and `HttpDispatcher` to:\n * 1. Verify service availability.\n * 2. Route requests to the correct service handler.\n * 3. Type-check service interactions.\n */\n\n// ==========================================\n// Service Identifiers\n// ==========================================\n\nexport const CoreServiceName = z.enum([\n // Core Data & Metadata\n 'metadata', // Object/Field Definitions\n 'data', // CRUD & Query Engine\n 'auth', // Authentication & Identity\n \n // Infrastructure\n 'file-storage', // Storage Driver (Local/S3)\n 'search', // Search Engine (Elastic/Meili)\n 'cache', // Cache Driver (Redis/Memory)\n 'queue', // Job Queue (BullMQ/Redis)\n \n // Advanced Capabilities\n 'automation', // Flow & Script Engine\n 'graphql', // GraphQL API Engine\n 'analytics', // BI & Semantic Layer\n 'realtime', // WebSocket & PubSub\n 'job', // Background Job Manager\n 'notification', // Email/Push/SMS\n 'ai', // AI Engine (NLQ, Chat, Suggest, Insights)\n 'i18n', // Internationalization Service\n 'ui', // UI Metadata Service (View CRUD)\n 'workflow', // Workflow State Machine Engine\n]);\n\nexport type CoreServiceName = z.infer;\n\n/**\n * Service Criticality Level\n * Defines the startup behavior when a service is missing.\n */\nexport const ServiceCriticalitySchema = z.enum([\n 'required', // System fails to start if missing (Exit Code 1)\n 'core', // System warns if missing, functionality degraded (Warn)\n 'optional', // System ignores if missing, feature disabled (Info)\n]);\n\n/**\n * Service Requirement Definition\n */\nexport const ServiceRequirementDef = {\n // Required: The kernel cannot function without these\n data: 'required',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n metadata: 'core',\n auth: 'core',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n cache: 'core',\n queue: 'core',\n job: 'core',\n i18n: 'core',\n\n // Optional: Add-on capabilities\n 'file-storage': 'optional',\n search: 'optional',\n automation: 'optional',\n graphql: 'optional',\n analytics: 'optional',\n realtime: 'optional',\n notification: 'optional',\n ai: 'optional',\n ui: 'optional',\n workflow: 'optional',\n} as const;\n\n// ==========================================\n// Service Capabilities\n// ==========================================\n\n/**\n * Describes the availability and health of a service\n */\nexport const ServiceStatusSchema = z.object({\n name: CoreServiceName,\n enabled: z.boolean(),\n status: z.enum(['running', 'stopped', 'degraded', 'initializing']),\n version: z.string().optional(),\n provider: z.string().optional().describe('Implementation provider (e.g. \"s3\" for storage)'),\n features: z.array(z.string()).optional().describe('List of supported sub-features'),\n});\n\n/**\n * The Contract definition for what the Kernel MUST expose\n * map\n */\nexport const KernelServiceMapSchema = z.record(\n CoreServiceName, \n z.unknown().describe('Service Instance implementing the protocol interface')\n);\n\n// ==========================================\n// Service Interfaces (Stub definitions)\n// ==========================================\n// Ideally, we would define strict Typescript interfaces here \n// for what methods each service must expose to the Registry.\n// For Zod, we primarily validate configuration and status.\n\n// e.g.\nexport const ServiceConfigSchema = z.object({\n id: z.string(),\n name: CoreServiceName,\n options: z.record(z.string(), z.unknown()).optional(),\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Schema (Multi-Tenant Architecture)\n * \n * Defines the tenant/tenancy model for ObjectStack SaaS deployments.\n * Supports different levels of data isolation to meet varying security,\n * performance, and compliance requirements.\n * \n * Isolation Levels:\n * - shared_schema: All tenants share the same database and schema (row-level isolation)\n * - isolated_schema: Tenants have separate schemas within a shared database\n * - isolated_db: Each tenant has a completely separate database\n */\n\n/**\n * Tenant Isolation Level Enum\n * Defines how tenant data is separated in the system\n */\nexport const TenantIsolationLevel = z.enum([\n 'shared_schema', // Shared DB, shared schema, row-level isolation (most economical)\n 'isolated_schema', // Shared DB, separate schema per tenant (balanced)\n 'isolated_db', // Separate database per tenant (maximum isolation)\n]);\n\nexport type TenantIsolationLevel = z.infer;\n\n/**\n * Database Provider Enum\n * Defines which database backend is used for the tenant\n */\nexport const DatabaseProviderSchema = z.enum([\n 'turso', // Turso/libSQL (DB-per-Tenant, edge-native)\n 'postgres', // PostgreSQL (traditional, self-hosted or managed)\n 'memory', // In-memory (testing/development only)\n]).describe('Database provider for tenant data');\n\nexport type DatabaseProvider = z.infer;\n\n/**\n * Tenant Connection Config Schema\n * Stores the database connection details for a tenant (encrypted at rest)\n */\nexport const TenantConnectionConfigSchema = z.object({\n /** Database connection URL */\n url: z.string().min(1).describe('Database connection URL'),\n /** Authentication token (JWT for Turso, password for Postgres) */\n authToken: z.string().optional().describe('Database auth token (encrypted at rest)'),\n /** Turso database group name */\n group: z.string().optional().describe('Turso database group name'),\n}).describe('Tenant database connection configuration');\n\nexport type TenantConnectionConfig = z.infer;\n\n/**\n * Tenant Quota Schema\n * Defines resource limits and usage quotas for a tenant\n */\nexport const TenantQuotaSchema = z.object({\n /**\n * Maximum number of users allowed for this tenant\n */\n maxUsers: z.number().int().positive().optional().describe('Maximum number of users'),\n \n /**\n * Maximum storage space in bytes\n */\n maxStorage: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n \n /**\n * API rate limit (requests per minute)\n */\n apiRateLimit: z.number().int().positive().optional().describe('API requests per minute'),\n\n /**\n * Maximum number of custom objects the tenant can create\n */\n maxObjects: z.number().int().positive().optional().describe('Maximum number of custom objects'),\n\n /**\n * Maximum records per object/table\n */\n maxRecordsPerObject: z.number().int().positive().optional().describe('Maximum records per object'),\n\n /**\n * Maximum deployments allowed per day\n */\n maxDeploymentsPerDay: z.number().int().positive().optional().describe('Maximum deployments per day'),\n\n /**\n * Maximum storage in bytes\n */\n maxStorageBytes: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n});\n\nexport type TenantQuota = z.infer;\n\n/**\n * Tenant Usage Schema\n * Tracks current resource usage for quota enforcement\n */\nexport const TenantUsageSchema = z.object({\n /** Current number of custom objects */\n currentObjectCount: z.number().int().min(0).default(0).describe('Current number of custom objects'),\n /** Current total record count across all objects */\n currentRecordCount: z.number().int().min(0).default(0).describe('Total records across all objects'),\n /** Current storage usage in bytes */\n currentStorageBytes: z.number().int().min(0).default(0).describe('Current storage usage in bytes'),\n /** Deployments executed today */\n deploymentsToday: z.number().int().min(0).default(0).describe('Deployments executed today'),\n /** Current number of active users */\n currentUsers: z.number().int().min(0).default(0).describe('Current number of active users'),\n /** API requests in the current minute */\n apiRequestsThisMinute: z.number().int().min(0).default(0).describe('API requests in the current minute'),\n /** Last updated timestamp (ISO 8601) */\n lastUpdatedAt: z.string().datetime().optional().describe('Last usage update time'),\n}).describe('Current tenant resource usage');\n\nexport type TenantUsage = z.infer;\n\n/**\n * Quota Enforcement Result\n * Result of checking whether an operation would exceed tenant quotas\n */\nexport const QuotaEnforcementResultSchema = z.object({\n /** Whether the operation is allowed */\n allowed: z.boolean().describe('Whether the operation is within quota'),\n /** Quota that would be exceeded (if not allowed) */\n exceededQuota: z.string().optional().describe('Name of the exceeded quota'),\n /** Current usage value */\n currentUsage: z.number().optional().describe('Current usage value'),\n /** Quota limit value */\n limit: z.number().optional().describe('Quota limit'),\n /** Human-readable message */\n message: z.string().optional().describe('Human-readable quota message'),\n}).describe('Quota enforcement check result');\n\nexport type QuotaEnforcementResult = z.infer;\n\n/**\n * Tenant Schema\n * \n * @deprecated This schema is maintained for backward compatibility only.\n * New implementations should use HubSpaceSchema which embeds tenant concepts.\n * \n * **Migration Guide:**\n * ```typescript\n * // Old approach (deprecated):\n * const tenant: Tenant = {\n * id: 'tenant_123',\n * name: 'My Tenant',\n * isolationLevel: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * };\n * \n * // New approach (recommended):\n * const space: HubSpace = {\n * id: '...uuid...',\n * name: 'My Tenant',\n * slug: 'my-tenant',\n * ownerId: 'user_id',\n * runtime: {\n * isolation: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * },\n * bom: { ... }\n * };\n * ```\n * \n * See HubSpaceSchema in space.zod.ts for the recommended approach.\n */\nexport const TenantSchema = z.object({\n /**\n * Unique tenant identifier\n */\n id: z.string().describe('Unique tenant identifier'),\n \n /**\n * Tenant display name\n */\n name: z.string().describe('Tenant display name'),\n \n /**\n * Data isolation level\n */\n isolationLevel: TenantIsolationLevel,\n\n /**\n * Database provider for this tenant\n */\n databaseProvider: DatabaseProviderSchema.optional().describe('Database provider'),\n\n /**\n * Database connection configuration (encrypted at rest)\n */\n connectionConfig: TenantConnectionConfigSchema.optional().describe('Database connection config'),\n\n /**\n * Current provisioning status\n */\n provisioningStatus: z.enum([\n 'provisioning', 'active', 'suspended', 'failed', 'destroying',\n ]).optional().describe('Current provisioning lifecycle status'),\n\n /**\n * Tenant subscription plan\n */\n plan: z.enum(['free', 'pro', 'enterprise']).optional().describe('Subscription plan'),\n \n /**\n * Custom configuration values\n */\n customizations: z.record(z.string(), z.unknown()).optional().describe('Custom configuration values'),\n \n /**\n * Resource quotas\n */\n quotas: TenantQuotaSchema.optional(),\n});\n\nexport type Tenant = z.infer;\n\n/**\n * Tenant Isolation Strategy Documentation\n * \n * Comprehensive documentation of three isolation strategies for multi-tenant systems.\n * Each strategy has different trade-offs in terms of security, cost, complexity, and compliance.\n */\n\n/**\n * Row-Level Isolation Strategy (shared_schema)\n * \n * Recommended for: Most SaaS applications, cost-sensitive deployments\n * \n * IMPLEMENTATION:\n * - All tenants share the same database and schema\n * - Each table includes a tenant_id column\n * - PostgreSQL Row-Level Security (RLS) enforces isolation\n * - Queries automatically filter by tenant_id via RLS policies\n * \n * ADVANTAGES:\n * ✅ Simple backup and restore (single database)\n * ✅ Cost-effective (shared resources, minimal overhead)\n * ✅ Easy tenant migration (update tenant_id)\n * ✅ Efficient resource utilization (connection pooling)\n * ✅ Simple schema migrations (single schema to update)\n * ✅ Lower operational complexity\n * \n * DISADVANTAGES:\n * ❌ RLS misconfiguration can lead to data leakage\n * ❌ Performance impact from RLS policy evaluation\n * ❌ Noisy neighbor problem (one tenant can affect others)\n * ❌ Cannot easily isolate tenant to different hardware\n * ❌ Compliance challenges for regulated industries\n * \n * SECURITY CONSIDERATIONS:\n * - Requires careful RLS policy configuration\n * - Must validate tenant_id in all queries\n * - Need comprehensive testing of RLS policies\n * - Audit all database access patterns\n * - Implement application-level validation as defense-in-depth\n * \n * EXAMPLE RLS POLICY (PostgreSQL):\n * ```sql\n * -- Example: Apply RLS policy to a table (e.g., \"app_data\")\n * CREATE POLICY tenant_isolation ON app_data\n * USING (tenant_id = current_setting('app.current_tenant')::text);\n * \n * ALTER TABLE app_data ENABLE ROW LEVEL SECURITY;\n * ```\n */\nexport const RowLevelIsolationStrategySchema = z.object({\n strategy: z.literal('shared_schema').describe('Row-level isolation strategy'),\n \n /**\n * Database configuration for row-level isolation\n */\n database: z.object({\n /**\n * Whether to enable Row-Level Security (RLS)\n */\n enableRLS: z.boolean().default(true).describe('Enable PostgreSQL Row-Level Security'),\n \n /**\n * Tenant context setting method\n */\n contextMethod: z.enum([\n 'session_variable', // SET app.current_tenant = 'tenant_123'\n 'search_path', // SET search_path = tenant_123, public\n 'application_name', // SET application_name = 'tenant_123'\n ]).default('session_variable').describe('How to set tenant context'),\n \n /**\n * Session variable name for tenant context\n */\n contextVariable: z.string().default('app.current_tenant').describe('Session variable name'),\n \n /**\n * Whether to validate tenant_id at application level\n */\n applicationValidation: z.boolean().default(true).describe('Application-level tenant validation'),\n }).optional().describe('Database configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use partial indexes for tenant_id\n */\n usePartialIndexes: z.boolean().default(true).describe('Use partial indexes per tenant'),\n \n /**\n * Whether to use table partitioning\n */\n usePartitioning: z.boolean().default(false).describe('Use table partitioning by tenant_id'),\n \n /**\n * Connection pool size per tenant\n */\n poolSizePerTenant: z.number().int().positive().optional().describe('Connection pool size per tenant'),\n }).optional().describe('Performance settings'),\n});\n\nexport type RowLevelIsolationStrategy = z.infer;\nexport type RowLevelIsolationStrategyInput = z.input;\n\n/**\n * Schema-Level Isolation Strategy (isolated_schema)\n * \n * Recommended for: Enterprise SaaS, B2B platforms with compliance needs\n * \n * IMPLEMENTATION:\n * - All tenants share the same database server\n * - Each tenant has a separate database schema\n * - Schema name typically: tenant_\n * - Application switches schema using SET search_path\n * \n * ADVANTAGES:\n * ✅ Better isolation than row-level (schema boundaries)\n * ✅ Easier to debug (separate schemas)\n * ✅ Can grant different database permissions per schema\n * ✅ Reduced risk of data leakage\n * ✅ Performance isolation (indexes, statistics per schema)\n * ✅ Simplified queries (no tenant_id filtering needed)\n * \n * DISADVANTAGES:\n * ❌ More complex backups (must backup all schemas)\n * ❌ Higher migration costs (schema changes across all tenants)\n * ❌ Schema proliferation (PostgreSQL has limits)\n * ❌ Connection overhead (switching schemas)\n * ❌ More complex monitoring and maintenance\n * \n * SECURITY CONSIDERATIONS:\n * - Ensure proper schema permissions (GRANT USAGE ON SCHEMA)\n * - Validate schema name to prevent SQL injection\n * - Implement connection-level schema switching\n * - Audit schema access patterns\n * - Prevent cross-schema queries in application\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant schema\n * CREATE SCHEMA tenant_123;\n * \n * -- Grant access\n * GRANT USAGE ON SCHEMA tenant_123 TO app_user;\n * \n * -- Switch to tenant schema\n * SET search_path TO tenant_123, public;\n * ```\n */\nexport const SchemaLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_schema').describe('Schema-level isolation strategy'),\n \n /**\n * Schema configuration\n */\n schema: z.object({\n /**\n * Schema naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Schema naming pattern'),\n \n /**\n * Whether to include public schema in search_path\n */\n includePublicSchema: z.boolean().default(true).describe('Include public schema'),\n \n /**\n * Default schema for shared resources\n */\n sharedSchema: z.string().default('public').describe('Schema for shared resources'),\n \n /**\n * Whether to automatically create schema on tenant creation\n */\n autoCreateSchema: z.boolean().default(true).describe('Auto-create schema'),\n }).optional().describe('Schema configuration'),\n \n /**\n * Migration configuration\n */\n migrations: z.object({\n /**\n * Migration strategy\n */\n strategy: z.enum([\n 'parallel', // Run migrations on all schemas in parallel\n 'sequential', // Run migrations one schema at a time\n 'on_demand', // Run migrations when tenant accesses system\n ]).default('parallel').describe('Migration strategy'),\n \n /**\n * Maximum concurrent migrations\n */\n maxConcurrent: z.number().int().positive().default(10).describe('Max concurrent migrations'),\n \n /**\n * Whether to rollback on first failure\n */\n rollbackOnError: z.boolean().default(true).describe('Rollback on error'),\n }).optional().describe('Migration configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use connection pooling per schema\n */\n poolPerSchema: z.boolean().default(false).describe('Separate pool per schema'),\n \n /**\n * Schema cache TTL in seconds\n */\n schemaCacheTTL: z.number().int().positive().default(3600).describe('Schema cache TTL'),\n }).optional().describe('Performance settings'),\n});\n\nexport type SchemaLevelIsolationStrategy = z.infer;\nexport type SchemaLevelIsolationStrategyInput = z.input;\n\n/**\n * Database-Level Isolation Strategy (isolated_db)\n * \n * Recommended for: Regulated industries (healthcare, finance), strict compliance requirements\n * \n * IMPLEMENTATION:\n * - Each tenant has a completely separate database\n * - Database name typically: tenant_\n * - Requires separate connection pool per tenant\n * - Complete physical and logical isolation\n * \n * ADVANTAGES:\n * ✅ Perfect data isolation (strongest security)\n * ✅ Meets strict regulatory requirements (HIPAA, SOX, PCI-DSS)\n * ✅ Complete performance isolation (no noisy neighbors)\n * ✅ Can place databases on different hardware\n * ✅ Easy to backup/restore individual tenant\n * ✅ Simplified compliance auditing per tenant\n * ✅ Can apply different encryption keys per database\n * \n * DISADVANTAGES:\n * ❌ Most expensive option (resource overhead)\n * ❌ Complex database server management (many databases)\n * ❌ Connection pool limits (max connections per server)\n * ❌ Difficult cross-tenant analytics\n * ❌ Higher operational complexity\n * ❌ Schema migrations take longer (many databases)\n * \n * SECURITY CONSIDERATIONS:\n * - Each database can have separate credentials\n * - Enables per-tenant encryption at rest\n * - Simplifies compliance and audit trails\n * - Prevents any cross-tenant data access\n * - Supports tenant-specific backup schedules\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant database\n * CREATE DATABASE tenant_123\n * WITH OWNER = tenant_123_user\n * ENCODING = 'UTF8'\n * LC_COLLATE = 'en_US.UTF-8'\n * LC_CTYPE = 'en_US.UTF-8';\n * \n * -- Connect to tenant database\n * \\c tenant_123\n * ```\n */\nexport const DatabaseLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_db').describe('Database-level isolation strategy'),\n \n /**\n * Database configuration\n */\n database: z.object({\n /**\n * Database naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Database naming pattern'),\n \n /**\n * Database server/cluster assignment strategy\n */\n serverStrategy: z.enum([\n 'shared', // All tenant databases on same server\n 'sharded', // Tenant databases distributed across servers\n 'dedicated', // Each tenant gets dedicated server (enterprise)\n ]).default('shared').describe('Server assignment strategy'),\n \n /**\n * Whether to use separate credentials per tenant\n */\n separateCredentials: z.boolean().default(true).describe('Separate credentials per tenant'),\n \n /**\n * Whether to automatically create database on tenant creation\n */\n autoCreateDatabase: z.boolean().default(true).describe('Auto-create database'),\n }).optional().describe('Database configuration'),\n \n /**\n * Connection pooling configuration\n */\n connectionPool: z.object({\n /**\n * Pool size per tenant database\n */\n poolSize: z.number().int().positive().default(10).describe('Connection pool size'),\n \n /**\n * Maximum number of tenant pools to keep active\n */\n maxActivePools: z.number().int().positive().default(100).describe('Max active pools'),\n \n /**\n * Idle pool timeout in seconds\n */\n idleTimeout: z.number().int().positive().default(300).describe('Idle pool timeout'),\n \n /**\n * Whether to use connection pooler (PgBouncer, etc.)\n */\n usePooler: z.boolean().default(true).describe('Use connection pooler'),\n }).optional().describe('Connection pool configuration'),\n \n /**\n * Backup and restore configuration\n */\n backup: z.object({\n /**\n * Backup strategy per tenant\n */\n strategy: z.enum([\n 'individual', // Separate backup per tenant\n 'consolidated', // Combined backup with all tenants\n 'on_demand', // Backup only when requested\n ]).default('individual').describe('Backup strategy'),\n \n /**\n * Backup frequency in hours\n */\n frequencyHours: z.number().int().positive().default(24).describe('Backup frequency'),\n \n /**\n * Retention period in days\n */\n retentionDays: z.number().int().positive().default(30).describe('Backup retention days'),\n }).optional().describe('Backup configuration'),\n \n /**\n * Encryption configuration\n */\n encryption: z.object({\n /**\n * Whether to use per-tenant encryption keys\n */\n perTenantKeys: z.boolean().default(false).describe('Per-tenant encryption keys'),\n \n /**\n * Encryption algorithm\n */\n algorithm: z.string().default('AES-256-GCM').describe('Encryption algorithm'),\n \n /**\n * Key management service\n */\n keyManagement: z.enum(['aws_kms', 'azure_key_vault', 'gcp_kms', 'hashicorp_vault', 'custom']).optional().describe('Key management service'),\n }).optional().describe('Encryption configuration'),\n});\n\nexport type DatabaseLevelIsolationStrategy = z.infer;\nexport type DatabaseLevelIsolationStrategyInput = z.input;\n\n/**\n * Tenant Isolation Configuration Schema\n * \n * Complete configuration for tenant isolation strategy.\n * Supports all three isolation levels with detailed configuration options.\n */\nexport const TenantIsolationConfigSchema = z.discriminatedUnion('strategy', [\n RowLevelIsolationStrategySchema,\n SchemaLevelIsolationStrategySchema,\n DatabaseLevelIsolationStrategySchema,\n]);\n\nexport type TenantIsolationConfig = z.infer;\n\n/**\n * Tenant Security Policy Schema\n * Defines security policies and compliance requirements for tenants\n */\nexport const TenantSecurityPolicySchema = z.object({\n /**\n * Encryption requirements\n */\n encryption: z.object({\n /**\n * Require encryption at rest\n */\n atRest: z.boolean().default(true).describe('Require encryption at rest'),\n \n /**\n * Require encryption in transit\n */\n inTransit: z.boolean().default(true).describe('Require encryption in transit'),\n \n /**\n * Require field-level encryption for sensitive data\n */\n fieldLevel: z.boolean().default(false).describe('Require field-level encryption'),\n }).optional().describe('Encryption requirements'),\n \n /**\n * Access control requirements\n */\n accessControl: z.object({\n /**\n * Require multi-factor authentication\n */\n requireMFA: z.boolean().default(false).describe('Require MFA'),\n \n /**\n * Require SSO/SAML authentication\n */\n requireSSO: z.boolean().default(false).describe('Require SSO'),\n \n /**\n * IP whitelist\n */\n ipWhitelist: z.array(z.string()).optional().describe('Allowed IP addresses'),\n \n /**\n * Session timeout in seconds\n */\n sessionTimeout: z.number().int().positive().default(3600).describe('Session timeout'),\n }).optional().describe('Access control requirements'),\n \n /**\n * Audit and compliance requirements\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox',\n 'hipaa',\n 'gdpr',\n 'pci_dss',\n 'iso_27001',\n 'fedramp',\n ])).optional().describe('Compliance standards'),\n \n /**\n * Require audit logging for all operations\n */\n requireAuditLog: z.boolean().default(true).describe('Require audit logging'),\n \n /**\n * Audit log retention period in days\n */\n auditRetentionDays: z.number().int().positive().default(365).describe('Audit retention days'),\n \n /**\n * Data residency requirements\n */\n dataResidency: z.object({\n /**\n * Required geographic region\n */\n region: z.string().optional().describe('Required region (e.g., US, EU, APAC)'),\n \n /**\n * Prohibited regions\n */\n excludeRegions: z.array(z.string()).optional().describe('Prohibited regions'),\n }).optional().describe('Data residency requirements'),\n }).optional().describe('Compliance requirements'),\n});\n\nexport type TenantSecurityPolicy = z.infer;\nexport type TenantSecurityPolicyInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metric Type Classification\n */\nexport const LicenseMetricType = z.enum([\n 'boolean', // Feature Flag (Enabled/Disabled)\n 'counter', // Usage Count (e.g. API Calls, Records Created) - Accumulates\n 'gauge', // Current Level (e.g. Storage Used, Users Active) - Point in time\n]).describe('License metric type');\nexport type LicenseMetricType = z.infer;\n\n/**\n * Feature/Limit Definition Schema\n * Defines a controllable capability of the system.\n */\nexport const FeatureSchema = z.object({\n code: z.string().regex(/^[a-z_][a-z0-9_.]*$/).describe('Feature code (e.g. core.api_access)'),\n label: z.string(),\n description: z.string().optional(),\n \n type: LicenseMetricType.default('boolean'),\n \n /** For counters/gauges */\n unit: z.enum(['count', 'bytes', 'seconds', 'percent']).optional(),\n \n /** Dependencies (e.g. 'audit_log' requires 'enterprise_tier') */\n requires: z.array(z.string()).optional(),\n});\n\n/**\n * Subscription Plan Schema\n * Defines a tier of service (e.g. \"Free\", \"Pro\", \"Enterprise\").\n */\nexport const PlanSchema = z.object({\n code: z.string().describe('Plan code (e.g. pro_v1)'),\n label: z.string(),\n active: z.boolean().default(true),\n \n /** Feature Entitlements */\n features: z.array(z.string()).describe('List of enabled boolean features'),\n \n /** Limit Quotas */\n limits: z.record(z.string(), z.number()).describe('Map of metric codes to limit values (e.g. { storage_gb: 10 })'),\n \n /** Pricing (Optional Metadata) */\n currency: z.string().default('USD').optional(),\n priceMonthly: z.number().optional(),\n priceYearly: z.number().optional(),\n});\n\n/**\n * License Schema\n * The actual entitlement object assigned to a Space.\n * Often signed as a JWT.\n */\nexport const LicenseSchema = z.object({\n /** Identity */\n spaceId: z.string().describe('Target Space ID'),\n planCode: z.string(),\n \n /** Validity */\n issuedAt: z.string().datetime(),\n expiresAt: z.string().datetime().optional(), // Null = Perpetual\n \n /** Status */\n status: z.enum(['active', 'expired', 'suspended', 'trial']),\n \n /** Overrides (Specific to this space, exceeding the plan) */\n customFeatures: z.array(z.string()).optional(),\n customLimits: z.record(z.string(), z.number()).optional(),\n \n /** Authorized Add-ons */\n plugins: z.array(z.string()).optional().describe('List of enabled plugin package IDs'),\n\n /** Signature */\n signature: z.string().optional().describe('Cryptographic signature of the license'),\n});\n\nexport type Feature = z.infer;\nexport type FeatureInput = z.input;\nexport type Plan = z.infer;\nexport type PlanInput = z.input;\nexport type License = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Registry Configuration Protocol\n * \n * Defines the configuration for the ObjectStack Registry Service.\n * Includes federation, synchronization, and storage settings.\n */\n\n/**\n * Registry Sync Policy\n * Defines how registries synchronize with upstreams\n */\nexport const RegistrySyncPolicySchema = z.enum([\n 'manual', // Manual synchronization only\n 'auto', // Automatic synchronization\n 'proxy', // Proxy requests to upstream without caching\n]).describe('Registry synchronization strategy');\n\n/**\n * Registry Upstream Configuration\n * Configuration for upstream registry connection\n */\nexport const RegistryUpstreamSchema = z.object({\n /**\n * Upstream registry URL\n */\n url: z.string().url()\n .describe('Upstream registry endpoint'),\n \n /**\n * Synchronization policy\n */\n syncPolicy: RegistrySyncPolicySchema.default('auto'),\n \n /**\n * Sync interval in seconds (for auto sync)\n */\n syncInterval: z.number().int().min(60).optional()\n .describe('Auto-sync interval in seconds'),\n \n /**\n * Authentication credentials\n */\n auth: z.object({\n type: z.enum(['none', 'basic', 'bearer', 'api-key', 'oauth2']).default('none'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n }).optional(),\n \n /**\n * TLS/SSL configuration\n */\n tls: z.object({\n enabled: z.boolean().default(true),\n verifyCertificate: z.boolean().default(true),\n certificate: z.string().optional(),\n privateKey: z.string().optional(),\n }).optional(),\n \n /**\n * Timeout settings\n */\n timeout: z.number().int().min(1000).default(30000)\n .describe('Request timeout in milliseconds'),\n \n /**\n * Retry configuration\n */\n retry: z.object({\n maxAttempts: z.number().int().min(0).default(3),\n backoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),\n }).optional(),\n});\n\n/**\n * Registry Configuration\n * Complete registry configuration supporting federation\n */\nexport const RegistryConfigSchema = z.object({\n /**\n * Registry type\n */\n type: z.enum([\n 'public', // Public marketplace (e.g., plugins.objectstack.com)\n 'private', // Private enterprise registry\n 'hybrid', // Hybrid with upstream federation\n ]).describe('Registry deployment type'),\n \n /**\n * Upstream registries (for hybrid/private registries)\n */\n upstream: z.array(RegistryUpstreamSchema).optional()\n .describe('Upstream registries to sync from or proxy to'),\n \n /**\n * Scopes managed by this registry\n */\n scope: z.array(z.string()).optional()\n .describe('npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)'),\n \n /**\n * Default scope for new plugins\n */\n defaultScope: z.string().optional()\n .describe('Default scope prefix for new plugins'),\n \n /**\n * Registry storage configuration\n */\n storage: z.object({\n /**\n * Storage backend type\n */\n backend: z.enum(['local', 's3', 'gcs', 'azure-blob', 'oss']).default('local'),\n \n /**\n * Storage path or bucket name\n */\n path: z.string().optional(),\n \n /**\n * Credentials\n */\n credentials: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n \n /**\n * Registry visibility\n */\n visibility: z.enum(['public', 'private', 'internal']).default('private')\n .describe('Who can access this registry'),\n \n /**\n * Access control\n */\n accessControl: z.object({\n /**\n * Require authentication for read\n */\n requireAuthForRead: z.boolean().default(false),\n \n /**\n * Require authentication for write\n */\n requireAuthForWrite: z.boolean().default(true),\n \n /**\n * Allowed users/teams\n */\n allowedPrincipals: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Caching configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true),\n ttl: z.number().int().min(0).default(3600)\n .describe('Cache TTL in seconds'),\n maxSize: z.number().int().optional()\n .describe('Maximum cache size in bytes'),\n }).optional(),\n \n /**\n * Mirroring configuration (for high availability)\n */\n mirrors: z.array(z.object({\n url: z.string().url(),\n priority: z.number().int().min(1).default(1),\n })).optional()\n .describe('Mirror registries for redundancy'),\n});\n\nexport type RegistrySyncPolicy = z.infer;\nexport type RegistryUpstream = z.infer;\nexport type RegistryConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Provisioning Protocol\n *\n * Defines the schemas for the \"Register → Instant ObjectOS\" provisioning pipeline:\n * 1. User registers → ProvisioningRequest created\n * 2. Turso database created → Schema synced → Seed data applied\n * 3. Tenant status transitions: provisioning → active\n *\n * Provisioning is designed to be:\n * - **Idempotent**: Re-running the same request produces the same result\n * - **Observable**: Each step has explicit status tracking\n * - **Fast**: Target 2-5 seconds for complete provisioning\n */\n\n// ==========================================================================\n// 1. Enums & Constants\n// ==========================================================================\n\n/**\n * Tenant provisioning lifecycle status.\n */\nexport const TenantProvisioningStatusEnum = z.enum([\n 'provisioning', // Database creation in progress\n 'active', // Fully provisioned and operational\n 'suspended', // Temporarily disabled (billing, policy)\n 'failed', // Provisioning failed (requires retry or manual intervention)\n 'destroying', // Deletion in progress\n]).describe('Tenant provisioning lifecycle status');\n\nexport type TenantProvisioningStatus = z.infer;\n\n/**\n * Tenant subscription plan.\n */\nexport const TenantPlanSchema = z.enum([\n 'free', // Free tier with limited quotas\n 'pro', // Professional tier with higher quotas\n 'enterprise', // Enterprise tier with custom quotas and SLAs\n]).describe('Tenant subscription plan');\n\nexport type TenantPlan = z.infer;\n\n/**\n * Available deployment regions.\n */\nexport const TenantRegionSchema = z.enum([\n 'us-east', // US East (Virginia)\n 'us-west', // US West (Oregon)\n 'eu-west', // EU West (Ireland)\n 'eu-central', // EU Central (Frankfurt)\n 'ap-southeast',// Asia Pacific (Singapore)\n 'ap-northeast',// Asia Pacific (Tokyo)\n]).describe('Available deployment region');\n\nexport type TenantRegion = z.infer;\n\n// ==========================================================================\n// 2. Provisioning Step Tracking\n// ==========================================================================\n\n/**\n * Individual provisioning step status.\n * Tracks the progress of each step in the provisioning pipeline.\n */\nexport const ProvisioningStepSchema = z.object({\n /** Step identifier */\n name: z.string().min(1).describe('Step name (e.g., create_database, sync_schema)'),\n\n /** Step execution status */\n status: z.enum(['pending', 'running', 'completed', 'failed', 'skipped']).describe('Step status'),\n\n /** When the step started (ISO 8601) */\n startedAt: z.string().datetime().optional().describe('Step start time'),\n\n /** When the step completed (ISO 8601) */\n completedAt: z.string().datetime().optional().describe('Step completion time'),\n\n /** Duration in milliseconds */\n durationMs: z.number().int().min(0).optional().describe('Step duration in ms'),\n\n /** Error message if the step failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('Individual provisioning step status');\n\nexport type ProvisioningStep = z.infer;\n\n// ==========================================================================\n// 3. Provisioning Request & Result\n// ==========================================================================\n\n/**\n * Tenant Provisioning Request.\n * Input for creating a new tenant with its isolated database.\n */\nexport const TenantProvisioningRequestSchema = z.object({\n /** Organization ID that owns this tenant */\n orgId: z.string().min(1).describe('Organization ID'),\n\n /** Requested subscription plan */\n plan: TenantPlanSchema.default('free'),\n\n /** Preferred deployment region */\n region: TenantRegionSchema.default('us-east'),\n\n /** Optional tenant display name */\n displayName: z.string().optional().describe('Tenant display name'),\n\n /** Optional initial admin user email */\n adminEmail: z.string().email().optional().describe('Initial admin user email'),\n\n /** Optional metadata to attach to the tenant */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n}).describe('Tenant provisioning request');\n\nexport type TenantProvisioningRequest = z.infer;\n\n/**\n * Tenant Provisioning Result.\n * Output after provisioning completes (or fails).\n */\nexport const TenantProvisioningResultSchema = z.object({\n /** Unique tenant identifier */\n tenantId: z.string().min(1).describe('Provisioned tenant ID'),\n\n /** Database connection URL (libsql:// or https://) */\n connectionUrl: z.string().min(1).describe('Database connection URL'),\n\n /** Current provisioning status */\n status: TenantProvisioningStatusEnum,\n\n /** Deployment region */\n region: TenantRegionSchema,\n\n /** Active subscription plan */\n plan: TenantPlanSchema,\n\n /** Provisioning pipeline steps with status */\n steps: z.array(ProvisioningStepSchema).default([]).describe('Pipeline step statuses'),\n\n /** Total provisioning duration in milliseconds */\n totalDurationMs: z.number().int().min(0).optional().describe('Total provisioning duration'),\n\n /** Provisioned timestamp (ISO 8601) */\n provisionedAt: z.string().datetime().optional().describe('Provisioning completion time'),\n\n /** Error message if provisioning failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('Tenant provisioning result');\n\nexport type TenantProvisioningResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Deploy Bundle Protocol\n *\n * Defines the schemas for metadata-driven deployment:\n * Schema Push → Zod Validate → Diff → DDL Sync → Register\n *\n * This eliminates traditional CI/CD pipelines for schema changes.\n * A \"deploy\" is a bundle of metadata (objects, views, flows, permissions)\n * that is validated, diffed against the current state, and applied\n * as DDL migrations directly to the tenant database.\n *\n * Target: 2-5 second deploys vs. 2-15 minute traditional Docker/CI/CD.\n */\n\n// ==========================================================================\n// 1. Deploy Status\n// ==========================================================================\n\n/**\n * Deployment lifecycle status.\n */\nexport const DeployStatusEnum = z.enum([\n 'validating', // Zod schema validation in progress\n 'diffing', // Comparing desired state vs current state\n 'migrating', // Executing DDL statements\n 'registering', // Updating metadata registry\n 'ready', // Deployment complete and live\n 'failed', // Deployment failed at some stage\n 'rolling_back', // Rollback in progress\n]).describe('Deployment lifecycle status');\n\nexport type DeployStatus = z.infer;\n\n// ==========================================================================\n// 2. Deploy Diff\n// ==========================================================================\n\n/**\n * Schema change descriptor for a single entity (object/field).\n */\nexport const SchemaChangeSchema = z.object({\n /** Type of entity being changed */\n entityType: z.enum(['object', 'field', 'index', 'view', 'flow', 'permission']).describe('Entity type'),\n\n /** Name of the entity */\n entityName: z.string().min(1).describe('Entity name'),\n\n /** Parent entity name (e.g., object name for a field change) */\n parentEntity: z.string().optional().describe('Parent entity name'),\n\n /** Type of change */\n changeType: z.enum(['added', 'modified', 'removed']).describe('Change type'),\n\n /** Previous value (for modified/removed) */\n oldValue: z.unknown().optional().describe('Previous value'),\n\n /** New value (for added/modified) */\n newValue: z.unknown().optional().describe('New value'),\n}).describe('Individual schema change');\n\nexport type SchemaChange = z.infer;\n\n/**\n * Deploy Diff — what changed between current and desired state.\n */\nexport const DeployDiffSchema = z.object({\n /** List of all schema changes */\n changes: z.array(SchemaChangeSchema).default([]).describe('List of schema changes'),\n\n /** Summary counts */\n summary: z.object({\n added: z.number().int().min(0).default(0).describe('Number of added entities'),\n modified: z.number().int().min(0).default(0).describe('Number of modified entities'),\n removed: z.number().int().min(0).default(0).describe('Number of removed entities'),\n }).describe('Change summary counts'),\n\n /** Whether the diff contains breaking changes (e.g., column removal) */\n hasBreakingChanges: z.boolean().default(false).describe('Whether diff contains breaking changes'),\n}).describe('Schema diff between current and desired state');\n\nexport type DeployDiff = z.infer;\n\n// ==========================================================================\n// 3. Migration Plan\n// ==========================================================================\n\n/**\n * A single DDL migration statement.\n */\nexport const MigrationStatementSchema = z.object({\n /** SQL DDL statement to execute */\n sql: z.string().min(1).describe('SQL DDL statement'),\n\n /** Whether this statement is reversible */\n reversible: z.boolean().default(true).describe('Whether the statement can be reversed'),\n\n /** Reverse SQL statement (for rollback) */\n rollbackSql: z.string().optional().describe('Reverse SQL for rollback'),\n\n /** Execution order (lower = earlier) */\n order: z.number().int().min(0).describe('Execution order'),\n}).describe('Single DDL migration statement');\n\nexport type MigrationStatement = z.infer;\n\n/**\n * Migration Plan — ordered list of DDL statements to execute.\n */\nexport const MigrationPlanSchema = z.object({\n /** Ordered list of migration statements */\n statements: z.array(MigrationStatementSchema).default([]).describe('Ordered DDL statements'),\n\n /** SQL dialect the statements are written for */\n dialect: z.string().min(1).describe('Target SQL dialect'),\n\n /** Whether the entire plan is reversible */\n reversible: z.boolean().default(true).describe('Whether the plan can be fully rolled back'),\n\n /** Estimated execution time in milliseconds */\n estimatedDurationMs: z.number().int().min(0).optional().describe('Estimated execution time'),\n}).describe('Ordered migration plan');\n\nexport type MigrationPlan = z.infer;\n\n// ==========================================================================\n// 4. Deploy Validation\n// ==========================================================================\n\n/**\n * Validation issue found during bundle validation.\n */\nexport const DeployValidationIssueSchema = z.object({\n /** Severity of the issue */\n severity: z.enum(['error', 'warning', 'info']).describe('Issue severity'),\n\n /** Entity path where the issue was found */\n path: z.string().describe('Entity path (e.g., objects.project_task.fields.name)'),\n\n /** Human-readable issue description */\n message: z.string().describe('Issue description'),\n\n /** Zod error code if applicable */\n code: z.string().optional().describe('Validation error code'),\n}).describe('Validation issue');\n\nexport type DeployValidationIssue = z.infer;\n\n/**\n * Zod validation result for the entire deploy bundle.\n */\nexport const DeployValidationResultSchema = z.object({\n /** Whether the bundle passed validation */\n valid: z.boolean().describe('Whether the bundle is valid'),\n\n /** List of validation issues */\n issues: z.array(DeployValidationIssueSchema).default([]).describe('Validation issues'),\n\n /** Number of errors */\n errorCount: z.number().int().min(0).default(0).describe('Number of errors'),\n\n /** Number of warnings */\n warningCount: z.number().int().min(0).default(0).describe('Number of warnings'),\n}).describe('Bundle validation result');\n\nexport type DeployValidationResult = z.infer;\n\n// ==========================================================================\n// 5. Deploy Bundle & Manifest\n// ==========================================================================\n\n/**\n * Deploy Manifest — metadata about the deployment.\n */\nexport const DeployManifestSchema = z.object({\n /** Deployment version (semver) */\n version: z.string().min(1).describe('Deployment version'),\n\n /** SHA256 checksum of the bundle contents */\n checksum: z.string().optional().describe('SHA256 checksum'),\n\n /** Object definitions included in this deployment */\n objects: z.array(z.string()).default([]).describe('Object names included'),\n\n /** View definitions included */\n views: z.array(z.string()).default([]).describe('View names included'),\n\n /** Flow definitions included */\n flows: z.array(z.string()).default([]).describe('Flow names included'),\n\n /** Permission definitions included */\n permissions: z.array(z.string()).default([]).describe('Permission names included'),\n\n /** Timestamp of bundle creation (ISO 8601) */\n createdAt: z.string().datetime().optional().describe('Bundle creation time'),\n}).describe('Deployment manifest');\n\nexport type DeployManifest = z.infer;\n\n/**\n * Deploy Bundle — container for all metadata being deployed.\n * This is the primary input to the deploy pipeline.\n */\nexport const DeployBundleSchema = z.object({\n /** Bundle manifest with version and contents list */\n manifest: DeployManifestSchema,\n\n /** Object definitions (JSON-serialized ObjectStack objects) */\n objects: z.array(z.record(z.string(), z.unknown())).default([]).describe('Object definitions'),\n\n /** View definitions */\n views: z.array(z.record(z.string(), z.unknown())).default([]).describe('View definitions'),\n\n /** Flow definitions */\n flows: z.array(z.record(z.string(), z.unknown())).default([]).describe('Flow definitions'),\n\n /** Permission definitions */\n permissions: z.array(z.record(z.string(), z.unknown())).default([]).describe('Permission definitions'),\n\n /** Seed data records to populate after schema migration */\n seedData: z.array(z.record(z.string(), z.unknown())).default([]).describe('Seed data records'),\n}).describe('Deploy bundle containing all metadata for deployment');\n\nexport type DeployBundle = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * App Installation Protocol\n *\n * Defines the schemas for installing marketplace apps into tenant databases.\n * An \"app install\" injects metadata (objects, views, flows) + schema sync\n * into a tenant's isolated database.\n *\n * Install pipeline:\n * 1. Check compatibility (kernel version, existing objects, conflicts)\n * 2. Validate app manifest\n * 3. Apply schema changes (via deploy pipeline)\n * 4. Seed initial data\n * 5. Register app in tenant's metadata registry\n */\n\n// ==========================================================================\n// 1. App Manifest\n// ==========================================================================\n\n/**\n * App Manifest — describes an installable app package.\n */\nexport const AppManifestSchema = z.object({\n /** Unique app identifier (snake_case) */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('App identifier (snake_case)'),\n\n /** Display label for the app */\n label: z.string().min(1).describe('App display label'),\n\n /** App version (semver) */\n version: z.string().min(1).describe('App version (semver)'),\n\n /** App description */\n description: z.string().optional().describe('App description'),\n\n /** Minimum kernel version required */\n minKernelVersion: z.string().optional().describe('Minimum required kernel version'),\n\n /** Object definitions provided by this app */\n objects: z.array(z.string()).default([]).describe('Object names provided'),\n\n /** View definitions provided */\n views: z.array(z.string()).default([]).describe('View names provided'),\n\n /** Flow definitions provided */\n flows: z.array(z.string()).default([]).describe('Flow names provided'),\n\n /** Whether seed data is included */\n hasSeedData: z.boolean().default(false).describe('Whether app includes seed data'),\n\n /** Seed data records to populate on install */\n seedData: z.array(z.record(z.string(), z.unknown())).default([]).describe('Seed data records'),\n\n /** App dependencies (other apps that must be installed first) */\n dependencies: z.array(z.string()).default([]).describe('Required app dependencies'),\n}).describe('App manifest for marketplace installation');\n\nexport type AppManifest = z.infer;\n\n// ==========================================================================\n// 2. Compatibility Check\n// ==========================================================================\n\n/**\n * App Compatibility Check Result.\n */\nexport const AppCompatibilityCheckSchema = z.object({\n /** Whether the app is compatible with the current environment */\n compatible: z.boolean().describe('Whether the app is compatible'),\n\n /** Compatibility issues found */\n issues: z.array(z.object({\n /** Issue severity */\n severity: z.enum(['error', 'warning']).describe('Issue severity'),\n /** Issue description */\n message: z.string().describe('Issue description'),\n /** Issue category */\n category: z.enum([\n 'kernel_version', // Kernel version mismatch\n 'object_conflict', // Object name already exists\n 'dependency_missing', // Required dependency not installed\n 'quota_exceeded', // Tenant quota would be exceeded\n ]).describe('Issue category'),\n })).default([]).describe('Compatibility issues'),\n}).describe('App compatibility check result');\n\nexport type AppCompatibilityCheck = z.infer;\n\n// ==========================================================================\n// 3. Install Request & Result\n// ==========================================================================\n\n/**\n * App Install Request.\n */\nexport const AppInstallRequestSchema = z.object({\n /** Target tenant ID */\n tenantId: z.string().min(1).describe('Target tenant ID'),\n\n /** App identifier to install */\n appId: z.string().min(1).describe('App identifier'),\n\n /** Optional configuration overrides */\n configOverrides: z.record(z.string(), z.unknown()).optional().describe('Configuration overrides'),\n\n /** Whether to skip seed data */\n skipSeedData: z.boolean().default(false).describe('Skip seed data population'),\n}).describe('App install request');\n\nexport type AppInstallRequest = z.infer;\n\n/**\n * App Install Result.\n */\nexport const AppInstallResultSchema = z.object({\n /** Whether the installation succeeded */\n success: z.boolean().describe('Whether installation succeeded'),\n\n /** App identifier that was installed */\n appId: z.string().describe('Installed app identifier'),\n\n /** App version installed */\n version: z.string().describe('Installed app version'),\n\n /** Objects created or updated */\n installedObjects: z.array(z.string()).default([]).describe('Objects created/updated'),\n\n /** Tables created in the database */\n createdTables: z.array(z.string()).default([]).describe('Database tables created'),\n\n /** Number of seed records inserted */\n seededRecords: z.number().int().min(0).default(0).describe('Seed records inserted'),\n\n /** Installation duration in milliseconds */\n durationMs: z.number().int().min(0).optional().describe('Installation duration'),\n\n /** Error message if installation failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('App install result');\n\nexport type AppInstallResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Package conventions and directory structure constants.\n * These define the \"Law of Location\" - where things must be in ObjectStack packages.\n * \n * These paths are the source of truth used by:\n * - ObjectOS Runtime (to locate package components)\n * - ObjectStack CLI (to scaffold and validate packages)\n * - ObjectStudio IDE (to provide intelligent navigation and validation)\n */\nexport const PKG_CONVENTIONS = {\n /**\n * Standard directories within ObjectStack packages.\n * All packages MUST follow these conventions for the runtime to locate resources.\n */\n DIRS: {\n /** \n * Location for schema definitions (Zod schemas, JSON schemas).\n * Path: src/schemas\n */\n SCHEMA: 'src/schemas',\n \n /** \n * Location for server-side code and triggers.\n * Path: src/server\n */\n SERVER: 'src/server',\n \n /** \n * Location for server-side trigger functions.\n * Path: src/triggers\n */\n TRIGGERS: 'src/triggers',\n \n /** \n * Location for client-side code.\n * Path: src/client\n */\n CLIENT: 'src/client',\n \n /** \n * Location for client-side page components.\n * Path: src/client/pages\n */\n PAGES: 'src/client/pages',\n \n /** \n * Location for static assets (images, fonts, etc.).\n * Path: assets\n */\n ASSETS: 'assets',\n },\n \n /**\n * Standard file names within ObjectStack packages.\n */\n FILES: {\n /** \n * Package manifest configuration file.\n * File: objectstack.config.ts\n */\n MANIFEST: 'objectstack.config.ts',\n \n /** \n * Main entry point for the package.\n * File: src/index.ts\n */\n ENTRY: 'src/index.ts',\n },\n} as const;\n\n/**\n * Type helper to extract directory path values.\n */\nexport type PackageDirectory = typeof PKG_CONVENTIONS.DIRS[keyof typeof PKG_CONVENTIONS.DIRS];\n\n/**\n * Type helper to extract file path values.\n */\nexport type PackageFile = typeof PKG_CONVENTIONS.FILES[keyof typeof PKG_CONVENTIONS.FILES];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * System Object Names — Protocol Layer Constants\n *\n * These constants define the canonical, protocol-level names for system objects.\n * All API calls, SDK references, permissions checks, and metadata lookups MUST use\n * these names instead of hardcoded strings or physical table names.\n *\n * The actual storage table name may differ via `ObjectSchema.tableName`.\n * The mapping between protocol name and storage name is handled by the\n * ObjectQL Engine / Driver layer.\n *\n * @example\n * ```ts\n * import { SystemObjectName } from '@objectstack/spec/system';\n *\n * // Always use the constant for API / SDK / permission references\n * const users = await engine.find(SystemObjectName.USER, { ... });\n * ```\n */\nexport const SystemObjectName = {\n /** Authentication: user identity */\n USER: 'sys_user',\n /** Authentication: active session */\n SESSION: 'sys_session',\n /** Authentication: OAuth / credential account */\n ACCOUNT: 'sys_account',\n /** Authentication: email / phone verification */\n VERIFICATION: 'sys_verification',\n /** Authentication: organization (multi-org support) */\n ORGANIZATION: 'sys_organization',\n /** Authentication: organization member */\n MEMBER: 'sys_member',\n /** Authentication: organization invitation */\n INVITATION: 'sys_invitation',\n /** Authentication: team within an organization */\n TEAM: 'sys_team',\n /** Authentication: team membership */\n TEAM_MEMBER: 'sys_team_member',\n /** Authentication: API key for programmatic access */\n API_KEY: 'sys_api_key',\n /** Authentication: two-factor authentication credentials */\n TWO_FACTOR: 'sys_two_factor',\n /** Authentication: user preferences (theme, locale, etc.) */\n USER_PREFERENCE: 'sys_user_preference',\n /** Security: role definition for RBAC */\n ROLE: 'sys_role',\n /** Security: permission set grouping */\n PERMISSION_SET: 'sys_permission_set',\n /** Audit: system audit log */\n AUDIT_LOG: 'sys_audit_log',\n /** System metadata storage */\n METADATA: 'sys_metadata',\n /** Realtime: user presence state */\n PRESENCE: 'sys_presence',\n} as const;\n\n/** Union type of all system object names */\nexport type SystemObjectName = typeof SystemObjectName[keyof typeof SystemObjectName];\n\n/**\n * System Field Names — Protocol Layer Constants\n *\n * These constants define the canonical, protocol-level names for common system fields.\n * All API calls, SDK references, and permission checks MUST use these constants\n * instead of hardcoded strings or physical column names.\n *\n * The actual storage column name may differ via `FieldSchema.columnName`.\n *\n * @example\n * ```ts\n * import { SystemFieldName } from '@objectstack/spec/system';\n *\n * // Use the constant to reference the owner field in queries\n * const myRecords = await engine.find('project', {\n * filters: [SystemFieldName.OWNER_ID, '=', currentUserId],\n * });\n * ```\n */\nexport const SystemFieldName = {\n /** Primary key */\n ID: 'id',\n /** Record creation timestamp */\n CREATED_AT: 'created_at',\n /** Record last-updated timestamp */\n UPDATED_AT: 'updated_at',\n /** Record owner (lookup to user) */\n OWNER_ID: 'owner_id',\n /** Tenant isolation key */\n TENANT_ID: 'tenant_id',\n /** Foreign key to user on session / account objects */\n USER_ID: 'user_id',\n /** Soft-delete timestamp */\n DELETED_AT: 'deleted_at',\n} as const;\n\n/** Union type of all system field names */\nexport type SystemFieldName = typeof SystemFieldName[keyof typeof SystemFieldName];\n\n/**\n * Storage Name Mapping — Protocol ↔ Physical Name Resolution\n *\n * Provides pure utility functions for resolving protocol-level names to\n * physical storage names and vice-versa.\n *\n * These helpers are intended for use inside the ObjectQL Engine and Driver layers.\n * They are intentionally stateless — they receive the object definition and return\n * the resolved name.\n */\nexport const StorageNameMapping = {\n /**\n * Resolve the physical table name for an object.\n * Priority: explicit `tableName` → auto-derived `{namespace}_{name}` → `name`.\n *\n * @param object - Object definition (at minimum `{ name: string; namespace?: string; tableName?: string }`)\n * @returns The physical table / collection name to use in storage operations.\n */\n resolveTableName(object: { name: string; namespace?: string; tableName?: string }): string {\n return object.tableName ?? (object.namespace ? `${object.namespace}_${object.name}` : object.name);\n },\n\n /**\n * Resolve the physical column name for a field.\n * Falls back to `fieldKey` when `columnName` is not set on the field.\n *\n * @param fieldKey - The protocol-level field key (snake_case identifier).\n * @param field - Field definition (at minimum `{ columnName?: string }`).\n * @returns The physical column name to use in storage operations.\n */\n resolveColumnName(fieldKey: string, field: { columnName?: string }): string {\n return field.columnName ?? fieldKey;\n },\n\n /**\n * Build a complete field-key → column-name map for an entire object.\n *\n * @param fields - The fields record from an ObjectSchema.\n * @returns A record mapping every protocol field key to its physical column name.\n */\n buildColumnMap(fields: Record): Record {\n const map: Record = {};\n for (const key of Object.keys(fields)) {\n map[key] = fields[key].columnName ?? key;\n }\n return map;\n },\n\n /**\n * Build a reverse column-name → field-key map for an entire object.\n * Useful for translating storage-layer results back to protocol-level field keys.\n *\n * @param fields - The fields record from an ObjectSchema.\n * @returns A record mapping every physical column name back to its protocol field key.\n */\n buildReverseColumnMap(fields: Record): Record {\n const map: Record = {};\n for (const key of Object.keys(fields)) {\n const col = fields[key].columnName ?? key;\n map[col] = key;\n }\n return map;\n },\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './cli-extension.zod';\nexport * from './cli-plugin-commands.zod';\nexport * from './context.zod';\nexport * from './dependency-resolution.zod';\nexport * from './dev-plugin.zod';\nexport * from './events.zod';\nexport * from './feature.zod';\nexport * from './manifest.zod';\nexport * from './metadata-customization.zod';\nexport * from './metadata-loader.zod';\nexport * from './metadata-plugin.zod';\nexport * from './package-artifact.zod';\nexport * from './package-registry.zod';\nexport * from './package-upgrade.zod';\nexport * from './plugin-capability.zod';\nexport * from './plugin-lifecycle-advanced.zod';\nexport * from './plugin-lifecycle-events.zod';\nexport * from './plugin-loading.zod';\nexport * from './plugin-runtime.zod';\nexport * from './plugin-security-advanced.zod';\nexport * from './plugin-structure.zod';\nexport * from './plugin-validator.zod';\nexport * from './plugin-versioning.zod';\nexport * from './plugin.zod';\nexport * from './service-registry.zod';\nexport * from './startup-orchestrator.zod';\nexport * from './plugin-registry.zod';\nexport * from './plugin-security.zod';\nexport * from './execution-context.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # CLI Extension Protocol\n * \n * Defines the contract for plugins that extend the ObjectStack CLI with\n * custom commands. This enables third-party packages (e.g., marketplace,\n * cloud deployment tools) to register new CLI commands via oclif's\n * built-in plugin system.\n * \n * ## How It Works (oclif Plugin Model)\n * \n * 1. **Declare** — Plugin's `package.json` includes an `oclif` config section\n * declaring its commands directory and any topics.\n * 2. **Discover** — The main CLI (`@objectstack/cli`) lists the plugin in its\n * `oclif.plugins` array, or users install it via `os plugins install `.\n * 3. **Load** — oclif automatically discovers and registers all Command classes\n * exported from the plugin's commands directory.\n * \n * ## Plugin Package Contract\n * \n * The plugin must be a valid oclif plugin:\n * \n * ```json\n * // package.json of the plugin\n * {\n * \"name\": \"@acme/plugin-marketplace\",\n * \"oclif\": {\n * \"commands\": {\n * \"strategy\": \"pattern\",\n * \"target\": \"./dist/commands\",\n * \"glob\": \"**\\/*.js\"\n * }\n * }\n * }\n * ```\n * \n * Commands are standard oclif Command classes:\n * \n * ```typescript\n * // src/commands/marketplace/search.ts\n * import { Args, Command, Flags } from '@oclif/core';\n * \n * export default class MarketplaceSearch extends Command {\n * static override description = 'Search marketplace apps';\n * static override args = {\n * query: Args.string({ description: 'Search query', required: true }),\n * };\n * async run() {\n * const { args } = await this.parse(MarketplaceSearch);\n * // ...\n * }\n * }\n * ```\n * \n * ## Migration from Commander.js\n * \n * The previous plugin model required `contributes.commands` in the manifest\n * and exported Commander.js `Command` instances. The new model uses oclif's\n * native plugin system for automatic command discovery and registration.\n * The `objectstack.config.ts` plugins array no longer determines CLI commands.\n */\n\n/**\n * Schema for a CLI Command Contribution declaration in the manifest.\n * \n * This declarative metadata describes CLI commands contributed by a plugin.\n * With the oclif migration, commands are auto-discovered from the plugin's\n * commands directory. This schema is retained for backward compatibility\n * and for describing command metadata in plugin manifests.\n */\nexport const CLICommandContributionSchema = z.object({\n /** \n * CLI command name. Must be a valid identifier: lowercase alphanumeric with hyphens.\n * This becomes a top-level subcommand of the `os` CLI.\n * \n * @example \"marketplace\"\n * @example \"deploy\"\n * @example \"cloud-sync\"\n */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n\n /** Brief description shown in `os --help` output. */\n description: z.string().optional().describe('Command description for help text'),\n\n /** \n * Module path that exports the oclif Command class(es).\n * Relative to the plugin package root. With oclif, this is typically\n * auto-discovered from the `commands` directory, but can be specified\n * for documentation or manifest purposes.\n * \n * @example \"./dist/commands/marketplace.js\"\n * @example \"./dist/commands\"\n */\n module: z.string().optional().describe('Module path exporting oclif Command classes'),\n});\n\n/**\n * Schema for oclif plugin configuration in package.json.\n * Validates the shape of the `oclif` section in a plugin's package.json.\n */\nexport const OclifPluginConfigSchema = z.object({\n /** Command discovery configuration */\n commands: z.object({\n /** Discovery strategy — typically \"pattern\" for file-based discovery */\n strategy: z.enum(['pattern', 'explicit', 'single']).optional()\n .describe('Command discovery strategy'),\n /** Directory path containing compiled command files */\n target: z.string().optional()\n .describe('Target directory for command files'),\n /** Glob pattern for matching command files */\n glob: z.string().optional()\n .describe('Glob pattern for command file matching'),\n }).optional().describe('Command discovery configuration'),\n\n /** Topic separator character (default: space) */\n topicSeparator: z.string().optional()\n .describe('Character separating topic and command names'),\n}).describe('oclif plugin configuration section');\n\n// ─── Types ───────────────────────────────────────────────────────────\n\nexport type CLICommandContribution = z.infer;\nexport type OclifPluginConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Package Artifact Format Protocol\n *\n * Defines the standard structure of a package artifact (.tgz) produced by\n * `os plugin build`. The marketplace uses these schemas to validate, store,\n * and distribute package artifacts.\n *\n * ## Artifact Internal Structure\n * ```\n * ├── manifest.json ← ManifestSchema serialized\n * ├── metadata/ ← 30+ metadata types (JSON)\n * │ ├── objects/ ← *.object.json\n * │ ├── views/ ← *.view.json\n * │ ├── pages/ ← *.page.json\n * │ ├── flows/ ← *.flow.json\n * │ ├── dashboards/ ← *.dashboard.json\n * │ ├── permissions/ ← *.permission.json\n * │ ├── agents/ ← *.agent.json\n * │ └── ... ← Other metadata types\n * ├── assets/ ← Static resources\n * │ ├── icon.svg\n * │ └── screenshots/\n * ├── data/ ← Seed data (DatasetSchema serialized)\n * ├── locales/ ← i18n translation files\n * ├── checksums.json ← SHA256 checksum per file\n * └── signature.sig ← RSA-SHA256 package signature\n * ```\n *\n * ## Architecture Alignment\n * - **Salesforce**: Managed Package .zip with metadata components\n * - **npm**: .tgz with package.json + contents\n * - **Helm**: Chart .tgz with Chart.yaml + templates\n * - **VS Code**: .vsix (zip) with extension manifest + assets\n */\n\n// ==========================================\n// Metadata Category Definitions\n// ==========================================\n\n/**\n * Supported metadata categories within an artifact.\n * Each category maps to a subdirectory under `metadata/`.\n */\nexport const MetadataCategoryEnum = z.enum([\n 'objects',\n 'views',\n 'pages',\n 'flows',\n 'dashboards',\n 'permissions',\n 'agents',\n 'reports',\n 'actions',\n 'translations',\n 'themes',\n 'datasets',\n 'apis',\n 'triggers',\n 'workflows',\n]).describe('Metadata category within the artifact');\n\nexport type MetadataCategory = z.infer;\n\n// ==========================================\n// Artifact File Entry\n// ==========================================\n\n/**\n * A single file entry within the artifact.\n */\nexport const ArtifactFileEntrySchema = z.object({\n /** Relative path within the artifact (e.g. \"metadata/objects/account.object.json\") */\n path: z.string().describe('Relative file path within the artifact'),\n\n /** File size in bytes */\n size: z.number().int().nonnegative().describe('File size in bytes'),\n\n /** Metadata category (if under metadata/) */\n category: MetadataCategoryEnum.optional()\n .describe('Metadata category this file belongs to'),\n}).describe('A single file entry within the artifact');\n\nexport type ArtifactFileEntry = z.infer;\n\n// ==========================================\n// Artifact Checksum\n// ==========================================\n\n/**\n * Checksum map for artifact integrity verification.\n * Maps relative file paths to their SHA256 hash values.\n *\n * @example\n * {\n * \"manifest.json\": \"a1b2c3...\",\n * \"metadata/objects/account.object.json\": \"d4e5f6...\"\n * }\n */\nexport const ArtifactChecksumSchema = z.object({\n /** Hash algorithm used (default: SHA256) */\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm used for checksums'),\n\n /** Map of relative file paths to their hash values */\n files: z.record(z.string(), z.string().regex(/^[a-f0-9]+$/))\n .describe('File path to hash value mapping'),\n}).describe('Checksum manifest for artifact integrity verification');\n\nexport type ArtifactChecksum = z.infer;\n\n// ==========================================\n// Artifact Signature\n// ==========================================\n\n/**\n * Digital signature for artifact authenticity verification.\n * Ensures the artifact was produced by a trusted publisher and has not been tampered with.\n */\nexport const ArtifactSignatureSchema = z.object({\n /** Signature algorithm */\n algorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).default('RSA-SHA256')\n .describe('Signing algorithm used'),\n\n /** Public key reference (URL or fingerprint) for verification */\n publicKeyRef: z.string()\n .describe('Public key reference (URL or fingerprint) for signature verification'),\n\n /** Base64-encoded signature value */\n signature: z.string()\n .describe('Base64-encoded digital signature'),\n\n /** Timestamp of when the artifact was signed */\n signedAt: z.string().datetime().optional()\n .describe('ISO 8601 timestamp of when the artifact was signed'),\n\n /** Signer identity (publisher ID or email) */\n signedBy: z.string().optional()\n .describe('Identity of the signer (publisher ID or email)'),\n}).describe('Digital signature for artifact authenticity verification');\n\nexport type ArtifactSignature = z.infer;\n\n// ==========================================\n// Package Artifact Schema\n// ==========================================\n\n/**\n * Package Artifact Schema\n *\n * Describes the complete structure and metadata of a built package artifact.\n * This schema is used to validate artifacts before upload to the marketplace.\n */\nexport const PackageArtifactSchema = z.object({\n /** Artifact format version (for forward compatibility) */\n formatVersion: z.string().regex(/^\\d+\\.\\d+$/).default('1.0')\n .describe('Artifact format version (e.g. \"1.0\")'),\n\n /** Package ID from the manifest */\n packageId: z.string().describe('Package identifier from manifest'),\n\n /** Package version from the manifest */\n version: z.string().describe('Package version from manifest'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format of the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().positive().optional()\n .describe('Total artifact file size in bytes'),\n\n /** Build timestamp */\n builtAt: z.string().datetime()\n .describe('ISO 8601 timestamp of when the artifact was built'),\n\n /** Build tool and version that produced this artifact */\n builtWith: z.string().optional()\n .describe('Build tool identifier (e.g. \"os-cli@3.2.0\")'),\n\n /** File listing within the artifact */\n files: z.array(ArtifactFileEntrySchema).optional()\n .describe('List of files contained in the artifact'),\n\n /** Metadata categories present in the artifact */\n metadataCategories: z.array(MetadataCategoryEnum).optional()\n .describe('Metadata categories included in this artifact'),\n\n /** Integrity checksums for all files */\n checksums: ArtifactChecksumSchema.optional()\n .describe('SHA256 checksums for artifact integrity verification'),\n\n /** Digital signature for authenticity */\n signature: ArtifactSignatureSchema.optional()\n .describe('Digital signature for artifact authenticity verification'),\n}).describe('Package artifact structure and metadata');\n\nexport type PackageArtifact = z.infer;\nexport type PackageArtifactInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PackageArtifactSchema, ArtifactChecksumSchema, ArtifactSignatureSchema } from './package-artifact.zod';\n\n/**\n * # CLI Plugin Commands Protocol\n *\n * Defines the input/output schemas for the `os plugin` CLI commands\n * that manage the package build → validate → publish lifecycle.\n *\n * ## Commands\n * ```\n * os plugin build — Build a .tgz artifact from the current project\n * os plugin validate — Validate an artifact's structure, checksums, and signature\n * os plugin publish — Upload an artifact to the marketplace\n * ```\n *\n * ## Architecture Alignment\n * - **npm**: `npm pack` → `npm publish`\n * - **Helm**: `helm package` → `helm push`\n * - **VS Code**: `vsce package` → `vsce publish`\n * - **Salesforce**: `sf package version create` → `sf package version promote`\n */\n\n// ==========================================\n// os plugin build\n// ==========================================\n\n/**\n * Options for the `os plugin build` command.\n * Reads the project manifest and produces a .tgz artifact.\n */\nexport const PluginBuildOptionsSchema = z.object({\n /** Project root directory (defaults to cwd) */\n directory: z.string().optional()\n .describe('Project root directory (defaults to current working directory)'),\n\n /** Output directory for the built artifact */\n outDir: z.string().optional()\n .describe('Output directory for the built artifact (defaults to ./dist)'),\n\n /** Archive format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format for the artifact'),\n\n /** Whether to sign the artifact */\n sign: z.boolean().default(false)\n .describe('Whether to digitally sign the artifact'),\n\n /** Path to the private key for signing */\n privateKeyPath: z.string().optional()\n .describe('Path to RSA/ECDSA private key file for signing'),\n\n /** Signing algorithm */\n signAlgorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).optional()\n .describe('Signing algorithm to use'),\n\n /** Checksum algorithm */\n checksumAlgorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm for file checksums'),\n\n /** Whether to include seed data */\n includeData: z.boolean().default(true)\n .describe('Whether to include seed data in the artifact'),\n\n /** Whether to include locale/translation files */\n includeLocales: z.boolean().default(true)\n .describe('Whether to include locale/translation files'),\n}).describe('Options for the os plugin build command');\n\nexport type PluginBuildOptions = z.infer;\n\n/**\n * Result of the `os plugin build` command.\n */\nexport const PluginBuildResultSchema = z.object({\n /** Whether the build succeeded */\n success: z.boolean().describe('Whether the build succeeded'),\n\n /** Path to the generated artifact file */\n artifactPath: z.string().optional()\n .describe('Absolute path to the generated artifact file'),\n\n /** Artifact metadata (validated against PackageArtifactSchema) */\n artifact: PackageArtifactSchema.optional()\n .describe('Artifact metadata'),\n\n /** Total file count in the artifact */\n fileCount: z.number().int().min(0).optional()\n .describe('Total number of files in the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().min(0).optional()\n .describe('Total artifact size in bytes'),\n\n /** Build duration in milliseconds */\n durationMs: z.number().optional()\n .describe('Build duration in milliseconds'),\n\n /** Error message if build failed */\n errorMessage: z.string().optional()\n .describe('Error message if build failed'),\n\n /** Warnings emitted during build */\n warnings: z.array(z.string()).optional()\n .describe('Warnings emitted during build'),\n}).describe('Result of the os plugin build command');\n\nexport type PluginBuildResult = z.infer;\n\n// ==========================================\n// os plugin validate\n// ==========================================\n\n/**\n * Validation severity levels.\n */\nexport const ValidationSeverityEnum = z.enum([\n 'error', // Must fix — artifact is invalid\n 'warning', // Should fix — may cause issues\n 'info', // Informational — suggestion\n]).describe('Validation issue severity');\n\n/**\n * A single validation finding.\n */\nexport const ValidationFindingSchema = z.object({\n /** Finding severity */\n severity: ValidationSeverityEnum.describe('Issue severity level'),\n\n /** Rule or check that produced this finding */\n rule: z.string().describe('Validation rule identifier'),\n\n /** Human-readable message */\n message: z.string().describe('Human-readable finding description'),\n\n /** File path within the artifact (if applicable) */\n path: z.string().optional()\n .describe('Relative file path within the artifact'),\n}).describe('A single validation finding');\n\nexport type ValidationFinding = z.infer;\n\n/**\n * Options for the `os plugin validate` command.\n */\nexport const PluginValidateOptionsSchema = z.object({\n /** Path to the .tgz artifact file to validate */\n artifactPath: z.string()\n .describe('Path to the artifact file to validate'),\n\n /** Whether to verify the digital signature */\n verifySignature: z.boolean().default(true)\n .describe('Whether to verify the digital signature'),\n\n /** Path to the public key for signature verification */\n publicKeyPath: z.string().optional()\n .describe('Path to the public key for signature verification'),\n\n /** Whether to verify SHA256 checksums of all files */\n verifyChecksums: z.boolean().default(true)\n .describe('Whether to verify checksums of all files'),\n\n /** Whether to validate metadata schema compliance */\n validateMetadata: z.boolean().default(true)\n .describe('Whether to validate metadata against schemas'),\n\n /** Target platform version for compatibility check */\n platformVersion: z.string().optional()\n .describe('Platform version for compatibility verification'),\n}).describe('Options for the os plugin validate command');\n\nexport type PluginValidateOptions = z.infer;\n\n/**\n * Result of the `os plugin validate` command.\n */\nexport const PluginValidateResultSchema = z.object({\n /** Whether the artifact is valid (no error-level findings) */\n valid: z.boolean().describe('Whether the artifact passed validation'),\n\n /** Artifact metadata extracted from the archive */\n artifact: PackageArtifactSchema.optional()\n .describe('Extracted artifact metadata'),\n\n /** Checksum verification result */\n checksumVerification: z.object({\n /** Whether all checksums match */\n passed: z.boolean().describe('Whether all checksums match'),\n /** Checksum details */\n checksums: ArtifactChecksumSchema.optional().describe('Verified checksums'),\n /** Files with mismatched checksums */\n mismatches: z.array(z.string()).optional()\n .describe('Files with checksum mismatches'),\n }).optional().describe('Checksum verification result'),\n\n /** Signature verification result */\n signatureVerification: z.object({\n /** Whether the signature is valid */\n passed: z.boolean().describe('Whether the signature is valid'),\n /** Signature details */\n signature: ArtifactSignatureSchema.optional().describe('Signature details'),\n /** Reason for failure */\n failureReason: z.string().optional().describe('Signature verification failure reason'),\n }).optional().describe('Signature verification result'),\n\n /** Platform compatibility result */\n platformCompatibility: z.object({\n /** Whether the artifact is compatible with the target platform */\n compatible: z.boolean().describe('Whether artifact is compatible'),\n /** Required platform version range */\n requiredRange: z.string().optional().describe('Required platform version range'),\n /** Target platform version checked against */\n targetVersion: z.string().optional().describe('Target platform version'),\n }).optional().describe('Platform compatibility check result'),\n\n /** All validation findings */\n findings: z.array(ValidationFindingSchema)\n .describe('All validation findings'),\n\n /** Counts by severity */\n summary: z.object({\n errors: z.number().int().min(0).describe('Error count'),\n warnings: z.number().int().min(0).describe('Warning count'),\n infos: z.number().int().min(0).describe('Info count'),\n }).optional().describe('Finding counts by severity'),\n}).describe('Result of the os plugin validate command');\n\nexport type PluginValidateResult = z.infer;\n\n// ==========================================\n// os plugin publish\n// ==========================================\n\n/**\n * Options for the `os plugin publish` command.\n */\nexport const PluginPublishOptionsSchema = z.object({\n /** Path to the .tgz artifact file to publish */\n artifactPath: z.string()\n .describe('Path to the artifact file to publish'),\n\n /** Marketplace API base URL */\n registryUrl: z.string().url().optional()\n .describe('Marketplace API base URL'),\n\n /** Authentication token for the marketplace API */\n token: z.string().optional()\n .describe('Authentication token for marketplace API'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional()\n .describe('Release notes for this version'),\n\n /** Whether this is a pre-release */\n preRelease: z.boolean().default(false)\n .describe('Whether this is a pre-release version'),\n\n /** Whether to skip validation before publishing */\n skipValidation: z.boolean().default(false)\n .describe('Whether to skip local validation before publish'),\n\n /** Access level for the published package */\n access: z.enum(['public', 'restricted']).default('public')\n .describe('Package access level on the marketplace'),\n\n /** Tags for categorization */\n tags: z.array(z.string()).optional()\n .describe('Tags for marketplace categorization'),\n}).describe('Options for the os plugin publish command');\n\nexport type PluginPublishOptions = z.infer;\n\n/**\n * Result of the `os plugin publish` command.\n */\nexport const PluginPublishResultSchema = z.object({\n /** Whether the publish succeeded */\n success: z.boolean().describe('Whether the publish succeeded'),\n\n /** Package ID that was published */\n packageId: z.string().optional()\n .describe('Published package identifier'),\n\n /** Version that was published */\n version: z.string().optional()\n .describe('Published version string'),\n\n /** Artifact reference in the marketplace */\n artifactUrl: z.string().url().optional()\n .describe('URL of the published artifact in the marketplace'),\n\n /** SHA256 checksum of the uploaded artifact */\n sha256: z.string().optional()\n .describe('SHA256 checksum of the uploaded artifact'),\n\n /** Submission ID for tracking the review process */\n submissionId: z.string().optional()\n .describe('Marketplace submission ID for review tracking'),\n\n /** Error message if publish failed */\n errorMessage: z.string().optional()\n .describe('Error message if publish failed'),\n\n /** Human-readable status message */\n message: z.string().optional()\n .describe('Human-readable status message'),\n}).describe('Result of the os plugin publish command');\n\nexport type PluginPublishResult = z.infer;\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type ValidationSeverity = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TenantQuotaSchema } from '../system/tenant.zod.js';\n\n/**\n * Runtime Mode Enum\n * Defines the operating mode of the kernel\n */\nexport const RuntimeMode = z.enum([\n 'development', // Hot-reload, verbose logging\n 'production', // Optimized, strict security\n 'test', // Mocked interfaces\n 'provisioning', // Setup/Migration mode\n 'preview', // Demo/preview mode — bypass auth, simulate admin identity\n]).describe('Kernel operating mode');\n\nexport type RuntimeMode = z.infer;\n\n/**\n * Preview Mode Configuration Schema\n *\n * Configures the kernel's preview/demo mode behaviour.\n * When `mode` is set to `'preview'`, the platform skips authentication\n * screens and optionally simulates an admin identity so that visitors\n * (e.g. app-marketplace customers) can explore the system without\n * registering or logging in.\n *\n * **Security note:** preview mode should NEVER be used in production.\n * The runtime must enforce this constraint.\n *\n * @example\n * ```ts\n * const ctx = KernelContextSchema.parse({\n * instanceId: '550e8400-e29b-41d4-a716-446655440000',\n * mode: 'preview',\n * version: '1.0.0',\n * cwd: '/app',\n * startTime: Date.now(),\n * previewMode: {\n * autoLogin: true,\n * simulatedRole: 'admin',\n * },\n * });\n * ```\n */\nexport const PreviewModeConfigSchema = z.object({\n /**\n * Automatically log in as a simulated user on startup.\n * When enabled, the frontend skips login/registration screens entirely.\n */\n autoLogin: z.boolean().default(true)\n .describe('Auto-login as simulated user, skipping login/registration pages'),\n\n /**\n * Role of the simulated user.\n * Determines the permission level of the auto-created preview session.\n */\n simulatedRole: z.enum(['admin', 'user', 'viewer']).default('admin')\n .describe('Permission role for the simulated preview user'),\n\n /**\n * Display name for the simulated user shown in the UI.\n */\n simulatedUserName: z.string().default('Preview User')\n .describe('Display name for the simulated preview user'),\n\n /**\n * Whether the preview session is read-only.\n * When true, all write operations (create, update, delete) are blocked.\n */\n readOnly: z.boolean().default(false)\n .describe('Restrict the preview session to read-only operations'),\n\n /**\n * Session duration in seconds. After expiry the preview session ends.\n * 0 means no expiration.\n */\n expiresInSeconds: z.number().int().min(0).default(0)\n .describe('Preview session duration in seconds (0 = no expiration)'),\n\n /**\n * Optional banner message shown in the UI to indicate preview mode.\n * Useful for marketplace demos so visitors know they are in a sandbox.\n */\n bannerMessage: z.string().optional()\n .describe('Banner message displayed in the UI during preview mode'),\n});\n\nexport type PreviewModeConfig = z.infer;\n\n/**\n * Kernel Context Schema\n * Defines the static environment information available to the Kernel at boot.\n */\nexport const KernelContextSchema = z.object({\n /**\n * Instance Identity\n */\n instanceId: z.string().uuid().describe('Unique UUID for this running kernel process'),\n \n /**\n * Environment Metadata\n */\n mode: RuntimeMode.default('production'),\n version: z.string().describe('Kernel version'),\n appName: z.string().optional().describe('Host application name'),\n \n /**\n * Paths\n */\n cwd: z.string().describe('Current working directory'),\n workspaceRoot: z.string().optional().describe('Workspace root if different from cwd'),\n \n /**\n * Telemetry\n */\n startTime: z.number().int().describe('Boot timestamp (ms)'),\n \n /**\n * Feature Flags (Global)\n */\n features: z.record(z.string(), z.boolean()).default({}).describe('Global feature toggles'),\n\n /**\n * Preview Mode Configuration.\n * Only relevant when `mode` is `'preview'`. Configures auto-login,\n * simulated identity, read-only restrictions, and UI banner.\n */\n previewMode: PreviewModeConfigSchema.optional()\n .describe('Preview/demo mode configuration (used when mode is \"preview\")'),\n});\n\nexport type KernelContext = z.infer;\n\n// ==========================================================================\n// Tenant Runtime Context\n// ==========================================================================\n\n/**\n * Tenant Runtime Context Schema.\n *\n * Extends the base KernelContext with tenant-specific information.\n * Constructed per-request from: session → org → tenant lookup.\n * Provides the tenant identity, plan, region, and database URL to all\n * downstream services during request processing.\n */\nexport const TenantRuntimeContextSchema = KernelContextSchema.extend({\n /** Unique tenant identifier resolved from the current session */\n tenantId: z.string().min(1).describe('Resolved tenant identifier'),\n\n /** Tenant subscription plan */\n tenantPlan: z.enum(['free', 'pro', 'enterprise']).describe('Tenant subscription plan'),\n\n /** Tenant deployment region */\n tenantRegion: z.string().optional().describe('Tenant deployment region'),\n\n /** Tenant database connection URL */\n tenantDbUrl: z.string().min(1).describe('Tenant database connection URL'),\n\n /** Optional tenant quotas for the current plan */\n tenantQuotas: TenantQuotaSchema.optional().describe('Tenant resource quotas'),\n}).describe('Tenant-aware kernel runtime context');\n\nexport type TenantRuntimeContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dependency Resolution Protocol\n *\n * Defines schemas for runtime dependency resolution when installing,\n * upgrading, or managing packages. Provides a standardized way to\n * express dependency conflicts, resolution results, and installation order.\n *\n * ## Architecture Alignment\n * - **npm**: Dependency tree resolution with conflict detection\n * - **Helm**: Dependency management with version constraints\n * - **Salesforce**: Package dependency validation at install time\n *\n * ## Resolution Flow\n * ```\n * 1. Parse manifest.dependencies (SemVer ranges)\n * 2. Check installed packages registry\n * 3. Resolve each dependency → satisfied | needs_install | needs_upgrade | conflict\n * 4. Detect circular dependencies\n * 5. Compute topological install order\n * 6. Return resolution result with required actions\n * ```\n */\n\n// ==========================================\n// Dependency Resolution Status\n// ==========================================\n\n/**\n * Resolution status for a single dependency.\n */\nexport const DependencyStatusEnum = z.enum([\n 'satisfied', // Already installed and version compatible\n 'needs_install', // Not installed, needs to be installed\n 'needs_upgrade', // Installed but version incompatible, needs upgrade\n 'conflict', // Conflicts with another package's dependency\n]).describe('Resolution status for a dependency');\n\nexport type DependencyStatus = z.infer;\n\n// ==========================================\n// Resolved Dependency\n// ==========================================\n\n/**\n * Single dependency resolution result.\n * Describes the state of one dependency after resolution.\n */\nexport const ResolvedDependencySchema = z.object({\n /** Package identifier of the dependency */\n packageId: z.string().describe('Dependency package identifier'),\n\n /** SemVer range required by the parent package */\n requiredRange: z.string().describe('SemVer range required (e.g. \"^2.0.0\")'),\n\n /** Actual version resolved (if available) */\n resolvedVersion: z.string().optional()\n .describe('Actual version resolved from registry'),\n\n /** Currently installed version (if any) */\n installedVersion: z.string().optional()\n .describe('Currently installed version'),\n\n /** Resolution status */\n status: DependencyStatusEnum.describe('Resolution status'),\n\n /** Conflict details (when status is \"conflict\") */\n conflictReason: z.string().optional()\n .describe('Explanation of the conflict'),\n}).describe('Resolution result for a single dependency');\n\nexport type ResolvedDependency = z.infer;\n\n// ==========================================\n// Required Action\n// ==========================================\n\n/**\n * An action required before installation can proceed.\n */\nexport const RequiredActionSchema = z.object({\n /** Type of action required */\n type: z.enum(['install', 'upgrade', 'confirm_conflict'])\n .describe('Type of action required'),\n\n /** Target package identifier */\n packageId: z.string().describe('Target package identifier'),\n\n /** Human-readable description of the action */\n description: z.string().describe('Human-readable action description'),\n}).describe('Action required before installation can proceed');\n\nexport type RequiredAction = z.infer;\n\n// ==========================================\n// Dependency Resolution Result\n// ==========================================\n\n/**\n * Complete dependency resolution result.\n * Aggregates all dependency statuses and computes installation feasibility.\n */\nexport const DependencyResolutionResultSchema = z.object({\n /** All dependencies and their resolution results */\n dependencies: z.array(ResolvedDependencySchema)\n .describe('Resolution result for each dependency'),\n\n /** Whether installation can proceed without conflicts */\n canProceed: z.boolean()\n .describe('Whether installation can proceed'),\n\n /** Actions that require user confirmation or system execution */\n requiredActions: z.array(RequiredActionSchema)\n .describe('Actions required before proceeding'),\n\n /** Topologically sorted package IDs for installation order */\n installOrder: z.array(z.string())\n .describe('Topologically sorted package IDs for installation'),\n\n /** Detected circular dependency chains */\n circularDependencies: z.array(z.array(z.string())).optional()\n .describe('Circular dependency chains detected (e.g. [[\"A\", \"B\", \"A\"]])'),\n}).describe('Complete dependency resolution result');\n\nexport type DependencyResolutionResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dev Mode Plugin Protocol\n *\n * Defines the schema for a development-mode plugin that automatically enables\n * all platform services for local simulation. When loaded as a `devPlugin`,\n * the kernel bootstraps every subsystem (data, UI, API, auth, events, jobs, …)\n * using in-memory or stub implementations so that developers can exercise the\n * full stack without external dependencies.\n *\n * Design goals:\n * - Zero-config by default: `devPlugins: ['@objectstack/plugin-dev']`\n * - Every service can be overridden or disabled individually\n * - Preset profiles (minimal / standard / full) for common scenarios\n *\n * Inspired by:\n * - Spring Boot DevTools (auto-configuration)\n * - Next.js Dev Server (HMR + mock APIs)\n * - Vite Plugin Dev Mode (instant startup)\n */\n\n// ============================================================================\n// Dev Service Override\n// ============================================================================\n\n/**\n * Dev Service Override Schema\n *\n * Allows fine-grained control over a single service in development mode.\n * Each override targets a service by name and specifies whether it should\n * be enabled, which implementation strategy to use, and optional config.\n */\nexport const DevServiceOverrideSchema = z.object({\n /** Service identifier (e.g. 'auth', 'eventBus', 'fileStorage') */\n service: z.string().min(1).describe('Target service identifier'),\n\n /** Whether this service is enabled in dev mode */\n enabled: z.boolean().default(true).describe('Enable or disable this service'),\n\n /**\n * Implementation strategy for the service in dev mode.\n * - mock: Use a mock/stub that records calls (for assertions)\n * - memory: Use a real but in-memory implementation (e.g. SQLite, Map)\n * - stub: Use a static/no-op implementation\n * - passthrough: Use the real production implementation (for integration testing)\n */\n strategy: z.enum(['mock', 'memory', 'stub', 'passthrough']).default('memory')\n .describe('Implementation strategy for development'),\n\n /** Optional per-service configuration (strategy-specific) */\n config: z.record(z.string(), z.unknown()).optional()\n .describe('Strategy-specific configuration for this service override'),\n});\n\nexport type DevServiceOverride = z.infer;\n\n// ============================================================================\n// Dev Fixture Configuration\n// ============================================================================\n\n/**\n * Dev Fixture Config Schema\n *\n * Configures automatic seed/fixture data loading in development mode.\n * Fixtures provide a reproducible dataset for local development and demos.\n */\nexport const DevFixtureConfigSchema = z.object({\n /** Whether to load fixtures on startup */\n enabled: z.boolean().default(true).describe('Load fixture data on startup'),\n\n /**\n * Glob patterns pointing to fixture files\n * (e.g. `[\"./fixtures/*.json\", \"./test/data/*.yml\"]`)\n */\n paths: z.array(z.string()).optional()\n .describe('Glob patterns for fixture files'),\n\n /** Whether to reset data before loading fixtures */\n resetBeforeLoad: z.boolean().default(true)\n .describe('Clear existing data before loading fixtures'),\n\n /**\n * Environment tag filter – only load fixtures tagged for these environments.\n * When omitted, all fixtures are loaded.\n */\n envFilter: z.array(z.string()).optional()\n .describe('Only load fixtures matching these environment tags'),\n});\n\nexport type DevFixtureConfig = z.infer;\n\n// ============================================================================\n// Dev Tools Configuration\n// ============================================================================\n\n/**\n * Dev Tools Config Schema\n *\n * Optional developer tooling that can be enabled alongside the dev plugin.\n */\nexport const DevToolsConfigSchema = z.object({\n /** Enable hot-module replacement / live reload */\n hotReload: z.boolean().default(true).describe('Enable HMR / live-reload'),\n\n /** Enable request inspector UI for debugging HTTP traffic */\n requestInspector: z.boolean().default(false).describe('Enable request inspector'),\n\n /** Enable an in-browser database explorer */\n dbExplorer: z.boolean().default(false).describe('Enable database explorer UI'),\n\n /** Enable verbose logging across all services */\n verboseLogging: z.boolean().default(true).describe('Enable verbose logging'),\n\n /** Enable OpenAPI / Swagger documentation endpoint */\n apiDocs: z.boolean().default(true).describe('Serve OpenAPI docs at /_dev/docs'),\n\n /** Enable a mail catcher for outbound email (like MailHog) */\n mailCatcher: z.boolean().default(false).describe('Capture outbound emails in dev'),\n});\n\nexport type DevToolsConfig = z.infer;\n\n// ============================================================================\n// Dev Plugin Preset\n// ============================================================================\n\n/**\n * Dev Plugin Preset\n *\n * Predefined configuration profiles for common development scenarios.\n * - minimal: Only core data services (fast startup, low memory)\n * - standard: Core + API + auth + events (typical full-stack dev)\n * - full: Every service enabled, including background jobs and AI agents\n */\nexport const DevPluginPreset = z.enum([\n 'minimal',\n 'standard',\n 'full',\n]).describe('Predefined dev configuration profile');\n\nexport type DevPluginPreset = z.infer;\n\n// ============================================================================\n// Dev Plugin Configuration\n// ============================================================================\n\n/**\n * Dev Plugin Config Schema\n *\n * Top-level configuration for the development-mode plugin.\n * This is the shape of the configuration payload that\n * `@objectstack/plugin-dev` (or equivalent) understands.\n *\n * The outer wiring (e.g. how a stack declares `devPlugins`) is defined\n * by the stack/manifest schemas; this type only describes the plugin's\n * own config object.\n *\n * @example Minimal usage (zero-config)\n * ```ts\n * const devConfig: DevPluginConfig = {};\n * ```\n *\n * @example With preset\n * ```ts\n * const devConfig: DevPluginConfig = {\n * preset: 'full',\n * };\n * ```\n *\n * @example Fine-grained overrides\n * ```ts\n * const devConfig: DevPluginConfig = {\n * preset: 'standard',\n * services: {\n * auth: { enabled: true, strategy: 'mock' },\n * fileStorage: { enabled: false },\n * },\n * fixtures: { paths: ['./fixtures/*.json'] },\n * tools: { dbExplorer: true },\n * };\n * ```\n */\nexport const DevPluginConfigSchema = z.object({\n /**\n * Configuration preset.\n * When provided, services and tools are pre-configured for the selected\n * profile. Individual `services` and `tools` settings override the preset.\n * @default 'standard'\n */\n preset: DevPluginPreset.default('standard')\n .describe('Base configuration preset'),\n\n /**\n * Per-service overrides.\n * Keys are service names; values configure the dev strategy.\n * Only services explicitly listed here override the preset defaults.\n */\n services: z.record(\n z.string().min(1),\n DevServiceOverrideSchema.omit({ service: true }),\n ).optional().describe('Per-service dev overrides keyed by service name'),\n\n /** Fixture / seed data configuration */\n fixtures: DevFixtureConfigSchema.optional()\n .describe('Fixture data loading configuration'),\n\n /** Developer tooling configuration */\n tools: DevToolsConfigSchema.optional()\n .describe('Developer tooling settings'),\n\n /**\n * Port for the dev-tools UI dashboard.\n * Serves a lightweight web dashboard for inspecting services, events,\n * and request logs during development.\n * @default 4400\n */\n port: z.number().int().min(1).max(65535).default(4400)\n .describe('Port for the dev-tools dashboard'),\n\n /**\n * Auto-open the dev-tools dashboard in the default browser on startup.\n */\n open: z.boolean().default(false)\n .describe('Auto-open dev dashboard in browser'),\n\n /**\n * Seed a default admin user for development.\n * When enabled, the dev plugin creates a pre-authenticated admin user\n * so that developers can bypass login flows.\n */\n seedAdminUser: z.boolean().default(true)\n .describe('Create a default admin user for development'),\n\n /**\n * Simulated latency (ms) to add to service calls.\n * Helps developers build UIs that handle loading states correctly.\n * Set to 0 to disable.\n */\n simulatedLatency: z.number().int().min(0).default(0)\n .describe('Artificial latency (ms) added to service calls'),\n});\n\nexport type DevPluginConfig = z.infer;\nexport type DevPluginConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventNameSchema } from '../../shared/identifiers.zod';\n\n// ==========================================\n// Event Priority\n// ==========================================\n\n/**\n * Event Priority Enum\n * Priority levels for event processing\n * Lower numbers = higher priority\n */\nexport const EventPriority = z.enum([\n 'critical', // 0 - Process immediately, block if necessary\n 'high', // 1 - Process soon, minimal delay\n 'normal', // 2 - Default priority\n 'low', // 3 - Process when resources available\n 'background', // 4 - Process during idle time\n]);\n\nexport type EventPriority = z.infer;\n\n/**\n * Event Priority Values\n * Maps priority names to numeric values for sorting\n */\nexport const EVENT_PRIORITY_VALUES: Record = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n background: 4,\n};\n\n// ==========================================\n// Event Metadata\n// ==========================================\n\n/**\n * Event Metadata Schema\n * Metadata associated with every event\n */\nexport const EventMetadataSchema = z.object({\n source: z.string().describe('Event source (e.g., plugin name, system component)'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when event was created'),\n userId: z.string().optional().describe('User who triggered the event'),\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant systems'),\n correlationId: z.string().optional().describe('Correlation ID for event tracing'),\n causationId: z.string().optional().describe('ID of the event that caused this event'),\n priority: EventPriority.optional().default('normal').describe('Event priority'),\n});\n\n// ==========================================\n// Event Schema\n// ==========================================\n\n/**\n * Event Type Definition Schema\n * Defines the structure of an event type\n * \n * @example\n * {\n * \"name\": \"order.created\",\n * \"version\": \"1.0.0\",\n * \"schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"orderId\": { \"type\": \"string\" },\n * \"customerId\": { \"type\": \"string\" },\n * \"total\": { \"type\": \"number\" }\n * }\n * }\n * }\n */\nexport const EventTypeDefinitionSchema = z.object({\n name: EventNameSchema.describe('Event type name (lowercase with dots)'),\n version: z.string().default('1.0.0').describe('Event schema version'),\n schema: z.unknown().optional().describe('JSON Schema for event payload validation'),\n description: z.string().optional().describe('Event type description'),\n deprecated: z.boolean().optional().default(false).describe('Whether this event type is deprecated'),\n tags: z.array(z.string()).optional().describe('Event type tags'),\n});\n\nexport type EventTypeDefinition = z.infer;\n\n/**\n * Event Schema\n * Base schema for all events in the system\n * \n * Event names follow dot notation for namespacing (e.g., 'user.created', 'order.paid').\n * This aligns with industry standards for event-driven architectures and message queues.\n */\nexport const EventSchema = z.object({\n /**\n * Event identifier (for tracking and deduplication)\n */\n id: z.string().optional().describe('Unique event identifier'),\n \n /**\n * Event name\n */\n name: EventNameSchema.describe('Event name (lowercase with dots, e.g., user.created, order.paid)'),\n \n /**\n * Event payload\n */\n payload: z.unknown().describe('Event payload schema'),\n \n /**\n * Event metadata\n */\n metadata: EventMetadataSchema.describe('Event metadata'),\n});\n\nexport type Event = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Event Handlers\n// ==========================================\n\n/**\n * Event Handler Schema\n * Defines how to handle a specific event\n */\nexport const EventHandlerSchema = z.object({\n /**\n * Handler identifier\n */\n id: z.string().optional().describe('Unique handler identifier'),\n \n /**\n * Event name pattern\n */\n eventName: z.string().describe('Name of event to handle (supports wildcards like user.*)'),\n \n /**\n * Handler function\n */\n handler: z.unknown()\n .describe('Handler function'),\n \n /**\n * Execution priority\n */\n priority: z.number().int().default(0).describe('Execution priority (lower numbers execute first)'),\n \n /**\n * Async execution\n */\n async: z.boolean().default(true).describe('Execute in background (true) or block (false)'),\n \n /**\n * Retry configuration\n */\n retry: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),\n backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay'),\n backoffMultiplier: z.number().positive().default(2).describe('Backoff multiplier'),\n }).optional().describe('Retry policy for failed handlers'),\n \n /**\n * Timeout\n */\n timeoutMs: z.number().int().positive().optional().describe('Handler timeout in milliseconds'),\n \n /**\n * Filter function\n */\n filter: z.unknown()\n .optional()\n .describe('Optional filter to determine if handler should execute'),\n});\n\nexport type EventHandler = z.infer;\n\n/**\n * Event Route Schema\n * Routes events from one pattern to multiple targets with optional transformation\n */\nexport const EventRouteSchema = z.object({\n from: z.string().describe('Source event pattern (supports wildcards, e.g., user.* or *.created)'),\n to: z.array(z.string()).describe('Target event names to route to'),\n transform: z.unknown().optional().describe('Optional function to transform payload'),\n});\n\nexport type EventRoute = z.infer;\n\n/**\n * Event Persistence Schema\n * Configuration for persisting events to storage\n */\nexport const EventPersistenceSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable event persistence'),\n retention: z.number().int().positive().describe('Days to retain persisted events'),\n filter: z.unknown().optional().describe('Optional filter function to select which events to persist'),\n storage: z.enum(['database', 'file', 's3', 'custom']).default('database')\n .describe('Storage backend for persisted events'),\n});\n\nexport type EventPersistence = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Event Queue\n// ==========================================\n\n/**\n * Event Queue Configuration Schema\n * Configuration for async event processing queue\n * \n * @example\n * {\n * \"name\": \"event_queue\",\n * \"concurrency\": 10,\n * \"retryPolicy\": {\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * }\n * }\n */\nexport const EventQueueConfigSchema = z.object({\n /**\n * Queue name\n */\n name: z.string().default('events').describe('Event queue name'),\n \n /**\n * Concurrency\n */\n concurrency: z.number().int().min(1).default(10).describe('Max concurrent event handlers'),\n \n /**\n * Retry policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Max retries for failed events'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay'),\n }).optional().describe('Default retry policy for events'),\n \n /**\n * Dead letter queue\n */\n deadLetterQueue: z.string().optional().describe('Dead letter queue name for failed events'),\n \n /**\n * Enable priority processing\n */\n priorityEnabled: z.boolean().default(true).describe('Process events based on priority'),\n});\n\nexport type EventQueueConfig = z.infer;\n\n// ==========================================\n// Event Replay\n// ==========================================\n\n/**\n * Event Replay Configuration Schema\n * Configuration for replaying historical events\n * \n * @example\n * {\n * \"fromTimestamp\": \"2024-01-01T00:00:00Z\",\n * \"toTimestamp\": \"2024-01-31T23:59:59Z\",\n * \"eventTypes\": [\"order.created\", \"order.updated\"],\n * \"speed\": 10\n * }\n */\nexport const EventReplayConfigSchema = z.object({\n /**\n * Start timestamp\n */\n fromTimestamp: z.string().datetime().describe('Start timestamp for replay (ISO 8601)'),\n \n /**\n * End timestamp\n */\n toTimestamp: z.string().datetime().optional().describe('End timestamp for replay (ISO 8601)'),\n \n /**\n * Event types to replay\n */\n eventTypes: z.array(z.string()).optional().describe('Event types to replay (empty = all)'),\n \n /**\n * Event filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters for event selection'),\n \n /**\n * Replay speed multiplier\n */\n speed: z.number().positive().default(1).describe('Replay speed multiplier (1 = real-time)'),\n \n /**\n * Target handlers\n */\n targetHandlers: z.array(z.string()).optional().describe('Handler IDs to execute (empty = all)'),\n});\n\nexport type EventReplayConfig = z.infer;\n\n// ==========================================\n// Event Sourcing\n// ==========================================\n\n/**\n * Event Sourcing Configuration Schema\n * Configuration for event sourcing pattern\n * \n * Event sourcing stores all changes to application state as a sequence of events.\n * The current state can be reconstructed by replaying the events.\n * \n * @example\n * {\n * \"enabled\": true,\n * \"snapshotInterval\": 100,\n * \"retention\": 365\n * }\n */\nexport const EventSourcingConfigSchema = z.object({\n /**\n * Enable event sourcing\n */\n enabled: z.boolean().default(false).describe('Enable event sourcing'),\n \n /**\n * Snapshot interval\n */\n snapshotInterval: z.number().int().positive().default(100)\n .describe('Create snapshot every N events'),\n \n /**\n * Snapshot retention\n */\n snapshotRetention: z.number().int().positive().default(10)\n .describe('Number of snapshots to retain'),\n \n /**\n * Event retention\n */\n retention: z.number().int().positive().default(365)\n .describe('Days to retain events'),\n \n /**\n * Aggregate types\n */\n aggregateTypes: z.array(z.string()).optional()\n .describe('Aggregate types to enable event sourcing for'),\n \n /**\n * Storage configuration\n */\n storage: z.object({\n type: z.enum(['database', 'file', 's3', 'eventstore']).default('database')\n .describe('Storage backend'),\n options: z.record(z.string(), z.unknown()).optional().describe('Storage-specific options'),\n }).optional().describe('Event store configuration'),\n});\n\nexport type EventSourcingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventSchema } from './core.zod';\n\n// ==========================================\n// Dead Letter Queue\n// ==========================================\n\n/**\n * Dead Letter Queue Entry Schema\n * Represents a failed event in the dead letter queue\n */\nexport const DeadLetterQueueEntrySchema = z.object({\n /**\n * Entry identifier\n */\n id: z.string().describe('Unique entry identifier'),\n \n /**\n * Original event\n */\n event: EventSchema.describe('Original event'),\n \n /**\n * Failure reason\n */\n error: z.object({\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Error stack trace'),\n code: z.string().optional().describe('Error code'),\n }).describe('Failure details'),\n \n /**\n * Retry count\n */\n retries: z.number().int().min(0).describe('Number of retry attempts'),\n \n /**\n * Timestamps\n */\n firstFailedAt: z.string().datetime().describe('When event first failed'),\n lastFailedAt: z.string().datetime().describe('When event last failed'),\n \n /**\n * Handler that failed\n */\n failedHandler: z.string().optional().describe('Handler ID that failed'),\n});\n\nexport type DeadLetterQueueEntry = z.infer;\n\n// ==========================================\n// Event Log\n// ==========================================\n\n/**\n * Event Log Entry Schema\n * Represents a logged event\n */\nexport const EventLogEntrySchema = z.object({\n /**\n * Log entry ID\n */\n id: z.string().describe('Unique log entry identifier'),\n \n /**\n * Event\n */\n event: EventSchema.describe('The event'),\n \n /**\n * Status\n */\n status: z.enum(['pending', 'processing', 'completed', 'failed']).describe('Processing status'),\n \n /**\n * Handlers executed\n */\n handlersExecuted: z.array(z.object({\n handlerId: z.string().describe('Handler identifier'),\n status: z.enum(['success', 'failed', 'timeout']).describe('Handler execution status'),\n durationMs: z.number().int().optional().describe('Execution duration'),\n error: z.string().optional().describe('Error message if failed'),\n })).optional().describe('Handlers that processed this event'),\n \n /**\n * Timestamps\n */\n receivedAt: z.string().datetime().describe('When event was received'),\n processedAt: z.string().datetime().optional().describe('When event was processed'),\n \n /**\n * Total duration\n */\n totalDurationMs: z.number().int().optional().describe('Total processing time'),\n});\n\nexport type EventLogEntry = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Webhook Integration\n// ==========================================\n\n/**\n * Event Webhook Configuration Schema\n * Configuration for sending events to webhooks\n * \n * @example\n * {\n * \"eventPattern\": \"order.*\",\n * \"url\": \"https://api.example.com/webhooks/orders\",\n * \"method\": \"POST\",\n * \"headers\": { \"Authorization\": \"Bearer token\" }\n * }\n */\nexport const EventWebhookConfigSchema = z.object({\n /**\n * Webhook identifier\n */\n id: z.string().optional().describe('Unique webhook identifier'),\n \n /**\n * Event pattern to match\n */\n eventPattern: z.string().describe('Event name pattern (supports wildcards)'),\n \n /**\n * Target URL\n */\n url: z.string().url().describe('Webhook endpoint URL'),\n \n /**\n * HTTP method\n */\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH']).default('POST').describe('HTTP method'),\n \n /**\n * Headers\n */\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n \n /**\n * Authentication\n */\n authentication: z.object({\n type: z.enum(['none', 'bearer', 'basic', 'api-key']).describe('Auth type'),\n credentials: z.record(z.string(), z.string()).optional().describe('Auth credentials'),\n }).optional().describe('Authentication configuration'),\n \n /**\n * Retry policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Max retry attempts'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Max retry delay'),\n }).optional().describe('Retry policy'),\n \n /**\n * Timeout\n */\n timeoutMs: z.number().int().positive().default(30000).describe('Request timeout in milliseconds'),\n \n /**\n * Event transformation\n */\n transform: z.unknown()\n .optional()\n .describe('Transform event before sending'),\n \n /**\n * Enabled\n */\n enabled: z.boolean().default(true).describe('Whether webhook is enabled'),\n});\n\nexport type EventWebhookConfig = z.infer;\n\n// ==========================================\n// Message Queue Integration\n// ==========================================\n\n/**\n * Event Message Queue Configuration Schema\n * Configuration for publishing events to message queues\n * \n * @example\n * {\n * \"provider\": \"kafka\",\n * \"topic\": \"events\",\n * \"eventPattern\": \"*\",\n * \"partitionKey\": \"metadata.tenantId\"\n * }\n */\nexport const EventMessageQueueConfigSchema = z.object({\n /**\n * Provider\n */\n provider: z.enum(['kafka', 'rabbitmq', 'aws-sqs', 'redis-pubsub', 'google-pubsub', 'azure-service-bus'])\n .describe('Message queue provider'),\n \n /**\n * Topic/Queue name\n */\n topic: z.string().describe('Topic or queue name'),\n \n /**\n * Event pattern\n */\n eventPattern: z.string().default('*').describe('Event name pattern to publish (supports wildcards)'),\n \n /**\n * Partition key\n */\n partitionKey: z.string().optional().describe('JSON path for partition key (e.g., \"metadata.tenantId\")'),\n \n /**\n * Message format\n */\n format: z.enum(['json', 'avro', 'protobuf']).default('json').describe('Message serialization format'),\n \n /**\n * Include metadata\n */\n includeMetadata: z.boolean().default(true).describe('Include event metadata in message'),\n \n /**\n * Compression\n */\n compression: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression'),\n \n /**\n * Batch size\n */\n batchSize: z.number().int().min(1).default(1).describe('Batch size for publishing'),\n \n /**\n * Flush interval\n */\n flushIntervalMs: z.number().int().positive().default(1000).describe('Flush interval for batching'),\n});\n\nexport type EventMessageQueueConfig = z.infer;\n\n// ==========================================\n// Real-time Notifications\n// ==========================================\n\n/**\n * Real-time Notification Configuration Schema\n * Configuration for real-time event notifications via WebSocket/SSE\n * \n * @example\n * {\n * \"enabled\": true,\n * \"protocol\": \"websocket\",\n * \"eventPattern\": \"notification.*\",\n * \"userFilter\": true\n * }\n */\nexport const RealTimeNotificationConfigSchema = z.object({\n /**\n * Enable real-time notifications\n */\n enabled: z.boolean().default(true).describe('Enable real-time notifications'),\n \n /**\n * Protocol\n */\n protocol: z.enum(['websocket', 'sse', 'long-polling']).default('websocket')\n .describe('Real-time protocol'),\n \n /**\n * Event pattern\n */\n eventPattern: z.string().default('*').describe('Event pattern to broadcast'),\n \n /**\n * User-specific filtering\n */\n userFilter: z.boolean().default(true).describe('Filter events by user'),\n \n /**\n * Tenant-specific filtering\n */\n tenantFilter: z.boolean().default(true).describe('Filter events by tenant'),\n \n /**\n * Channels\n */\n channels: z.array(z.object({\n name: z.string().describe('Channel name'),\n eventPattern: z.string().describe('Event pattern for channel'),\n filter: z.unknown()\n .optional()\n .describe('Additional filter function'),\n })).optional().describe('Named channels for event broadcasting'),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n maxEventsPerSecond: z.number().int().positive().describe('Max events per second per client'),\n windowMs: z.number().int().positive().default(1000).describe('Rate limit window'),\n }).optional().describe('Rate limiting configuration'),\n});\n\nexport type RealTimeNotificationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventTypeDefinitionSchema } from './core.zod';\nimport { EventHandlerSchema, EventPersistenceSchema } from './handlers.zod';\nimport { EventQueueConfigSchema, EventSourcingConfigSchema } from './queue.zod';\nimport { EventWebhookConfigSchema, EventMessageQueueConfigSchema, RealTimeNotificationConfigSchema } from './integrations.zod';\n\n// ==========================================\n// Complete Event Bus Configuration\n// ==========================================\n\n/**\n * Event Bus Configuration Schema\n * Complete configuration for the event bus system\n * \n * @example\n * {\n * \"persistence\": { \"enabled\": true, \"retention\": 365 },\n * \"queue\": { \"concurrency\": 20 },\n * \"eventSourcing\": { \"enabled\": true },\n * \"webhooks\": [],\n * \"messageQueue\": { \"provider\": \"kafka\", \"topic\": \"events\" },\n * \"realtime\": { \"enabled\": true, \"protocol\": \"websocket\" }\n * }\n */\nexport const EventBusConfigSchema = z.object({\n /**\n * Event persistence\n */\n persistence: EventPersistenceSchema.optional().describe('Event persistence configuration'),\n \n /**\n * Event queue\n */\n queue: EventQueueConfigSchema.optional().describe('Event queue configuration'),\n \n /**\n * Event sourcing\n */\n eventSourcing: EventSourcingConfigSchema.optional().describe('Event sourcing configuration'),\n \n /**\n * Event replay\n */\n replay: z.object({\n enabled: z.boolean().default(true).describe('Enable event replay capability'),\n }).optional().describe('Event replay configuration'),\n \n /**\n * Webhooks\n */\n webhooks: z.array(EventWebhookConfigSchema).optional().describe('Webhook configurations'),\n \n /**\n * Message queue integration\n */\n messageQueue: EventMessageQueueConfigSchema.optional().describe('Message queue integration'),\n \n /**\n * Real-time notifications\n */\n realtime: RealTimeNotificationConfigSchema.optional().describe('Real-time notification configuration'),\n \n /**\n * Event type definitions\n */\n eventTypes: z.array(EventTypeDefinitionSchema).optional().describe('Event type definitions'),\n \n /**\n * Global handlers\n */\n handlers: z.array(EventHandlerSchema).optional().describe('Global event handlers'),\n});\n\nexport type EventBusConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Feature Rollout Strategy\n */\nexport const FeatureStrategy = z.enum([\n 'boolean', // Simple On/Off\n 'percentage', // Gradual rollout (0-100%)\n 'user_list', // Specific users\n 'group', // Specific groups/roles\n 'custom' // Custom constraint/script\n]);\n\n/**\n * Feature Flag Protocol\n * \n * Manages feature toggles and gradual rollouts.\n * Used for CI/CD, A/B Testing, and Trunk-Based Development.\n */\nexport const FeatureFlagSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Feature key (snake_case)'),\n label: z.string().optional().describe('Display label'),\n description: z.string().optional(),\n \n /** Default state */\n enabled: z.boolean().default(false).describe('Is globally enabled'),\n \n /** Rollout Strategy */\n strategy: FeatureStrategy.default('boolean'),\n \n /** Strategy Configuration */\n conditions: z.object({\n percentage: z.number().min(0).max(100).optional(),\n users: z.array(z.string()).optional(),\n groups: z.array(z.string()).optional(),\n expression: z.string().optional().describe('Custom formula expression')\n }).optional(),\n \n /** Integration */\n environment: z.enum(['dev', 'staging', 'prod', 'all']).default('all')\n .describe('Environment validity'),\n \n /** Expiration */\n expiresAt: z.string().datetime().optional().describe('Feature flag expiration date'),\n});\n\nexport const FeatureFlag = Object.assign(FeatureFlagSchema, {\n create: >(config: T) => config,\n});\n\nexport type FeatureFlag = z.infer;\nexport type FeatureFlagInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Capability Protocol\n * \n * Defines the standard way plugins declare their capabilities, implementations,\n * and conformance levels to ensure interoperability across vendors.\n * \n * Based on the Protocol-Oriented Architecture pattern similar to:\n * - Kubernetes CRDs (Custom Resource Definitions)\n * - OSGi Service Registry\n * - Eclipse Extension Points\n */\n\n/**\n * Capability Conformance Level\n * Indicates how completely a plugin implements a given protocol.\n */\nexport const CapabilityConformanceLevelSchema = z.enum([\n 'full', // Complete implementation of all protocol features\n 'partial', // Subset implementation with specific features listed\n 'experimental', // Unstable/preview implementation\n 'deprecated', // Still supported but scheduled for removal\n]).describe('Level of protocol conformance');\n\n/**\n * Protocol Version Schema\n * Uses semantic versioning to track protocol evolution.\n */\nexport const ProtocolVersionSchema = z.object({\n major: z.number().int().min(0),\n minor: z.number().int().min(0),\n patch: z.number().int().min(0),\n}).describe('Semantic version of the protocol');\n\n/**\n * Protocol Reference\n * Uniquely identifies a protocol/interface that a plugin can implement.\n * \n * Examples:\n * - com.objectstack.protocol.storage.v1\n * - com.objectstack.protocol.auth.oauth2.v2\n * - com.acme.protocol.payment.stripe.v1\n */\nexport const ProtocolReferenceSchema = z.object({\n /**\n * Protocol identifier using reverse domain notation.\n * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+protocol\\.[a-z][a-z0-9._]*\\.v\\d+$/)\n .describe('Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)'),\n \n /**\n * Human-readable protocol name\n */\n label: z.string(),\n \n /**\n * Protocol version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Detailed protocol specification URL or file reference\n */\n specification: z.string().optional().describe('URL or path to protocol specification'),\n \n /**\n * Brief description of what this protocol defines\n */\n description: z.string().optional(),\n});\n\n/**\n * Protocol Feature\n * Represents a specific capability within a protocol.\n */\nexport const ProtocolFeatureSchema = z.object({\n name: z.string().describe('Feature identifier within the protocol'),\n enabled: z.boolean().default(true),\n description: z.string().optional(),\n sinceVersion: z.string().optional().describe('Version when this feature was added'),\n deprecatedSince: z.string().optional().describe('Version when deprecated'),\n});\n\n/**\n * Plugin Capability Declaration\n * Documents what protocols a plugin implements and to what extent.\n */\nexport const PluginCapabilitySchema = z.object({\n /**\n * The protocol being implemented\n */\n protocol: ProtocolReferenceSchema,\n \n /**\n * Conformance level\n */\n conformance: CapabilityConformanceLevelSchema.default('full'),\n \n /**\n * Specific features implemented (required if conformance is 'partial')\n */\n implementedFeatures: z.array(z.string()).optional().describe('List of implemented feature names'),\n \n /**\n * Optional feature flags indicating advanced capabilities\n */\n features: z.array(ProtocolFeatureSchema).optional(),\n \n /**\n * Custom metadata for vendor-specific information\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Testing/Certification status\n */\n certified: z.boolean().default(false).describe('Has passed official conformance tests'),\n certificationDate: z.string().datetime().optional(),\n});\n\n/**\n * Plugin Interface Declaration\n * Defines the contract for services this plugin provides to other plugins.\n */\nexport const PluginInterfaceSchema = z.object({\n /**\n * Unique interface identifier\n * Format: {plugin-id}.interface.{name}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+interface\\.[a-z][a-z0-9._]+$/)\n .describe('Unique interface identifier'),\n \n /**\n * Interface name\n */\n name: z.string(),\n \n /**\n * Description of what this interface provides\n */\n description: z.string().optional(),\n \n /**\n * Interface version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Methods exposed by this interface\n */\n methods: z.array(z.object({\n name: z.string().describe('Method name'),\n description: z.string().optional(),\n parameters: z.array(z.object({\n name: z.string(),\n type: z.string().describe('Type notation (e.g., string, number, User)'),\n required: z.boolean().default(true),\n description: z.string().optional(),\n })).optional(),\n returnType: z.string().optional().describe('Return value type'),\n async: z.boolean().default(false).describe('Whether method returns a Promise'),\n })),\n \n /**\n * Events emitted by this interface\n */\n events: z.array(z.object({\n name: z.string().describe('Event name'),\n description: z.string().optional(),\n payload: z.string().optional().describe('Event payload type'),\n })).optional(),\n \n /**\n * Stability level\n */\n stability: z.enum(['stable', 'beta', 'alpha', 'experimental']).default('stable'),\n});\n\n/**\n * Plugin Dependency Declaration\n * Specifies what other plugins or capabilities this plugin requires.\n */\nexport const PluginDependencySchema = z.object({\n /**\n * Plugin ID using reverse domain notation\n */\n pluginId: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Required plugin identifier'),\n \n /**\n * Version constraint (supports semver ranges)\n * Examples: \"1.0.0\", \"^1.2.3\", \">=2.0.0 <3.0.0\"\n */\n version: z.string().describe('Semantic version constraint'),\n \n /**\n * Whether this dependency is optional\n */\n optional: z.boolean().default(false),\n \n /**\n * Reason for the dependency\n */\n reason: z.string().optional(),\n \n /**\n * Minimum required capabilities from the dependency\n */\n requiredCapabilities: z.array(z.string()).optional().describe('Protocol IDs the dependency must support'),\n});\n\n/**\n * Extension Point Declaration\n * Defines hooks where other plugins can extend this plugin's functionality.\n */\nexport const ExtensionPointSchema = z.object({\n /**\n * Extension point identifier\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+extension\\.[a-z][a-z0-9._]+$/)\n .describe('Unique extension point identifier'),\n \n /**\n * Extension point name\n */\n name: z.string(),\n \n /**\n * Description\n */\n description: z.string().optional(),\n \n /**\n * Type of extension point\n */\n type: z.enum([\n 'action', // Plugins can register executable actions\n 'hook', // Plugins can listen to lifecycle events\n 'widget', // Plugins can contribute UI widgets\n 'provider', // Plugins can provide data/services\n 'transformer', // Plugins can transform data\n 'validator', // Plugins can validate data\n 'decorator', // Plugins can enhance/wrap functionality\n ]),\n \n /**\n * Expected interface contract for extensions\n */\n contract: z.object({\n input: z.string().optional().describe('Input type/schema'),\n output: z.string().optional().describe('Output type/schema'),\n signature: z.string().optional().describe('Function signature if applicable'),\n }).optional(),\n \n /**\n * Cardinality\n */\n cardinality: z.enum(['single', 'multiple']).default('multiple')\n .describe('Whether multiple extensions can register to this point'),\n});\n\n/**\n * Complete Plugin Capability Manifest\n * This is included in the main plugin manifest to declare all capabilities.\n */\nexport const PluginCapabilityManifestSchema = z.object({\n /**\n * Protocols this plugin implements\n */\n implements: z.array(PluginCapabilitySchema).optional()\n .describe('List of protocols this plugin conforms to'),\n \n /**\n * Interfaces this plugin exposes to other plugins\n */\n provides: z.array(PluginInterfaceSchema).optional()\n .describe('Services/APIs this plugin offers to others'),\n \n /**\n * Dependencies on other plugins\n */\n requires: z.array(PluginDependencySchema).optional()\n .describe('Required plugins and their capabilities'),\n \n /**\n * Extension points this plugin defines\n */\n extensionPoints: z.array(ExtensionPointSchema).optional()\n .describe('Points where other plugins can extend this plugin'),\n \n /**\n * Extensions this plugin contributes to other plugins\n */\n extensions: z.array(z.object({\n targetPluginId: z.string().describe('Plugin ID being extended'),\n extensionPointId: z.string().describe('Extension point identifier'),\n implementation: z.string().describe('Path to implementation module'),\n priority: z.number().int().default(100).describe('Registration priority (lower = higher priority)'),\n })).optional().describe('Extensions contributed to other plugins'),\n});\n\n// Export types\nexport type CapabilityConformanceLevel = z.infer;\nexport type ProtocolVersion = z.infer;\nexport type ProtocolReference = z.infer;\nexport type ProtocolFeature = z.infer;\nexport type PluginCapability = z.infer;\nexport type PluginInterface = z.infer;\nexport type PluginDependency = z.infer;\nexport type ExtensionPoint = z.infer;\nexport type PluginCapabilityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Loading Protocol\n * \n * Defines the enhanced plugin loading mechanism for the microkernel architecture.\n * Inspired by industry best practices from:\n * - Kubernetes CRDs and Operators\n * - OSGi Dynamic Module System\n * - Eclipse Plugin Framework\n * - Webpack Module Federation\n * \n * This protocol enables:\n * - Lazy loading and code splitting\n * - Dynamic imports and parallel initialization\n * - Capability-based discovery\n * - Hot reload in development\n * - Advanced caching strategies\n */\n\n/**\n * Plugin Loading Strategy\n * Determines how and when a plugin is loaded into memory\n */\nexport const PluginLoadingStrategySchema = z.enum([\n 'eager', // Load immediately during bootstrap (critical plugins)\n 'lazy', // Load on first use (feature plugins)\n 'parallel', // Load in parallel with other plugins\n 'deferred', // Load after initial bootstrap complete\n 'on-demand', // Load only when explicitly requested\n]).describe('Plugin loading strategy');\n\n/**\n * Plugin Preloading Configuration\n * Configures preloading behavior for faster activation\n */\nexport const PluginPreloadConfigSchema = z.object({\n /**\n * Enable preloading for this plugin\n */\n enabled: z.boolean().default(false),\n \n /**\n * Preload priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Resources to preload\n */\n resources: z.array(z.enum([\n 'metadata', // Plugin manifest and metadata\n 'dependencies', // Plugin dependencies\n 'assets', // Static assets (icons, translations)\n 'code', // JavaScript code chunks\n 'services', // Service definitions\n ])).optional(),\n \n /**\n * Conditions for preloading\n */\n conditions: z.object({\n /**\n * Preload only on specific routes\n */\n routes: z.array(z.string()).optional(),\n \n /**\n * Preload only for specific user roles\n */\n roles: z.array(z.string()).optional(),\n \n /**\n * Preload based on device type\n */\n deviceType: z.array(z.enum(['desktop', 'mobile', 'tablet'])).optional(),\n \n /**\n * Network connection quality threshold\n */\n minNetworkSpeed: z.enum(['slow-2g', '2g', '3g', '4g']).optional(),\n }).optional(),\n}).describe('Plugin preloading configuration');\n\n/**\n * Plugin Code Splitting Configuration\n * Configures how plugin code is split for optimal loading\n */\nexport const PluginCodeSplittingSchema = z.object({\n /**\n * Enable code splitting for this plugin\n */\n enabled: z.boolean().default(true),\n \n /**\n * Split strategy\n */\n strategy: z.enum([\n 'route', // Split by UI routes\n 'feature', // Split by feature modules\n 'size', // Split by bundle size threshold\n 'custom', // Custom split points defined by plugin\n ]).default('feature'),\n \n /**\n * Chunk naming strategy\n */\n chunkNaming: z.enum(['hashed', 'named', 'sequential']).default('hashed'),\n \n /**\n * Maximum chunk size in KB\n */\n maxChunkSize: z.number().int().min(10).optional().describe('Max chunk size in KB'),\n \n /**\n * Shared dependencies optimization\n */\n sharedDependencies: z.object({\n enabled: z.boolean().default(true),\n /**\n * Minimum times a module must be shared before extraction\n */\n minChunks: z.number().int().min(1).default(2),\n }).optional(),\n}).describe('Plugin code splitting configuration');\n\n/**\n * Plugin Dynamic Import Configuration\n * Configures dynamic import behavior for runtime module loading\n */\nexport const PluginDynamicImportSchema = z.object({\n /**\n * Enable dynamic imports\n */\n enabled: z.boolean().default(true),\n \n /**\n * Import mode\n */\n mode: z.enum([\n 'async', // Asynchronous import (recommended)\n 'sync', // Synchronous import (blocking)\n 'eager', // Eager evaluation\n 'lazy', // Lazy evaluation\n ]).default('async'),\n \n /**\n * Prefetch strategy\n */\n prefetch: z.boolean().default(false).describe('Prefetch module in idle time'),\n \n /**\n * Preload strategy\n */\n preload: z.boolean().default(false).describe('Preload module in parallel with parent'),\n \n /**\n * Webpack magic comments support\n */\n webpackChunkName: z.string().optional().describe('Custom chunk name for webpack'),\n \n /**\n * Import timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000).describe('Dynamic import timeout (ms)'),\n \n /**\n * Retry configuration on import failure\n */\n retry: z.object({\n enabled: z.boolean().default(true),\n maxAttempts: z.number().int().min(1).max(10).default(3),\n backoffMs: z.number().int().min(0).default(1000).describe('Exponential backoff base delay'),\n }).optional(),\n}).describe('Plugin dynamic import configuration');\n\n/**\n * Plugin Initialization Configuration\n * Configures how plugin initialization is executed\n */\nexport const PluginInitializationSchema = z.object({\n /**\n * Initialization mode\n */\n mode: z.enum([\n 'sync', // Synchronous initialization\n 'async', // Asynchronous initialization\n 'parallel', // Parallel with other plugins\n 'sequential', // Must complete before next plugin\n ]).default('async'),\n \n /**\n * Initialization timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000),\n \n /**\n * Startup priority (lower = higher priority, earlier initialization)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Whether to continue bootstrap if this plugin fails\n */\n critical: z.boolean().default(false).describe('If true, kernel bootstrap fails if plugin fails'),\n \n /**\n * Retry configuration on initialization failure\n */\n retry: z.object({\n enabled: z.boolean().default(false),\n maxAttempts: z.number().int().min(1).max(5).default(3),\n backoffMs: z.number().int().min(0).default(1000),\n }).optional(),\n \n /**\n * Health check interval for monitoring\n */\n healthCheckInterval: z.number().int().min(0).optional().describe('Health check interval in ms (0 = disabled)'),\n}).describe('Plugin initialization configuration');\n\n/**\n * Plugin Dependency Resolution Configuration\n * Advanced dependency resolution using semantic versioning\n */\nexport const PluginDependencyResolutionSchema = z.object({\n /**\n * Dependency resolution strategy\n */\n strategy: z.enum([\n 'strict', // Exact version match required\n 'compatible', // Semver compatible versions (^)\n 'latest', // Always use latest compatible\n 'pinned', // Lock to specific version\n ]).default('compatible'),\n \n /**\n * Peer dependency handling\n */\n peerDependencies: z.object({\n /**\n * Whether to resolve peer dependencies\n */\n resolve: z.boolean().default(true),\n \n /**\n * Action on missing peer dependency\n */\n onMissing: z.enum(['error', 'warn', 'ignore']).default('warn'),\n \n /**\n * Action on peer version mismatch\n */\n onMismatch: z.enum(['error', 'warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Optional dependency handling\n */\n optionalDependencies: z.object({\n /**\n * Whether to attempt loading optional dependencies\n */\n load: z.boolean().default(true),\n \n /**\n * Action on optional dependency load failure\n */\n onFailure: z.enum(['warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Conflict resolution\n */\n conflictResolution: z.enum([\n 'fail', // Fail on any version conflict\n 'latest', // Use latest version\n 'oldest', // Use oldest version\n 'manual', // Require manual resolution\n ]).default('latest'),\n \n /**\n * Circular dependency handling\n */\n circularDependencies: z.enum([\n 'error', // Throw error on circular dependency\n 'warn', // Warn but continue\n 'allow', // Allow circular dependencies\n ]).default('warn'),\n}).describe('Plugin dependency resolution configuration');\n\n/**\n * Plugin Hot Reload Configuration\n * Enables hot module replacement for development and production environments.\n * \n * Production mode adds safety features: health validation, rollback on failure,\n * connection draining, and concurrency control for zero-downtime reloads.\n */\nexport const PluginHotReloadSchema = z.object({\n /**\n * Enable hot reload\n */\n enabled: z.boolean().default(false),\n \n /**\n * Target environment for hot reload behavior\n */\n environment: z.enum([\n 'development', // Fast reload with relaxed safety (file watchers, no health validation)\n 'staging', // Production-like reload with validation but relaxed rollback\n 'production', // Full safety: health validation, rollback, connection draining\n ]).default('development').describe('Target environment controlling safety level'),\n \n /**\n * Hot reload strategy\n */\n strategy: z.enum([\n 'full', // Full plugin reload (destroy and reinitialize)\n 'partial', // Partial reload (update changed modules only)\n 'state-preserve', // Preserve plugin state during reload\n ]).default('full'),\n \n /**\n * Files to watch for changes\n */\n watchPatterns: z.array(z.string()).optional().describe('Glob patterns for files to watch'),\n \n /**\n * Files to ignore\n */\n ignorePatterns: z.array(z.string()).optional().describe('Glob patterns for files to ignore'),\n \n /**\n * Debounce delay in milliseconds\n */\n debounceMs: z.number().int().min(0).default(300),\n \n /**\n * Whether to preserve state during reload\n */\n preserveState: z.boolean().default(false),\n \n /**\n * State serialization\n */\n stateSerialization: z.object({\n enabled: z.boolean().default(false),\n /**\n * Path to state serialization handler\n */\n handler: z.string().optional(),\n }).optional(),\n \n /**\n * Hooks for hot reload lifecycle\n */\n hooks: z.object({\n beforeReload: z.string().optional().describe('Function to call before reload'),\n afterReload: z.string().optional().describe('Function to call after reload'),\n onError: z.string().optional().describe('Function to call on reload error'),\n }).optional(),\n \n /**\n * Production safety configuration\n * Applied when environment is 'staging' or 'production'\n */\n productionSafety: z.object({\n /**\n * Validate plugin health before completing reload\n */\n healthValidation: z.boolean().default(true)\n .describe('Run health checks after reload before accepting traffic'),\n \n /**\n * Automatically rollback to previous version on reload failure\n */\n rollbackOnFailure: z.boolean().default(true)\n .describe('Auto-rollback if reloaded plugin fails health check'),\n \n /**\n * Maximum time to wait for health validation after reload (ms)\n */\n healthTimeout: z.number().int().min(1000).default(30000)\n .describe('Health check timeout after reload in ms'),\n \n /**\n * Drain active connections before reload\n */\n drainConnections: z.boolean().default(true)\n .describe('Gracefully drain active requests before reloading'),\n \n /**\n * Maximum time to wait for connection draining (ms)\n */\n drainTimeout: z.number().int().min(0).default(15000)\n .describe('Max wait time for connection draining in ms'),\n \n /**\n * Maximum number of concurrent plugin reloads\n */\n maxConcurrentReloads: z.number().int().min(1).default(1)\n .describe('Limit concurrent reloads to prevent system instability'),\n \n /**\n * Minimum interval between reloads of the same plugin (ms)\n */\n minReloadInterval: z.number().int().min(1000).default(5000)\n .describe('Cooldown period between reloads of the same plugin'),\n }).optional(),\n}).describe('Plugin hot reload configuration');\n\n/**\n * Plugin Caching Configuration\n * Configures caching strategy for faster subsequent loads\n */\nexport const PluginCachingSchema = z.object({\n /**\n * Enable caching\n */\n enabled: z.boolean().default(true),\n \n /**\n * Cache storage type\n */\n storage: z.enum([\n 'memory', // In-memory cache (fastest, not persistent)\n 'disk', // Disk cache (persistent)\n 'indexeddb', // Browser IndexedDB (persistent, browser only)\n 'hybrid', // Memory + Disk hybrid\n ]).default('memory'),\n \n /**\n * Cache key strategy\n */\n keyStrategy: z.enum([\n 'version', // Cache by plugin version\n 'hash', // Cache by content hash\n 'timestamp', // Cache by last modified timestamp\n ]).default('version'),\n \n /**\n * Cache TTL in seconds\n */\n ttl: z.number().int().min(0).optional().describe('Time to live in seconds (0 = infinite)'),\n \n /**\n * Maximum cache size in MB\n */\n maxSize: z.number().int().min(1).optional().describe('Max cache size in MB'),\n \n /**\n * Cache invalidation triggers\n */\n invalidateOn: z.array(z.enum([\n 'version-change',\n 'dependency-change',\n 'manual',\n 'error',\n ])).optional(),\n \n /**\n * Compression\n */\n compression: z.object({\n enabled: z.boolean().default(false),\n algorithm: z.enum(['gzip', 'brotli', 'deflate']).default('gzip'),\n }).optional(),\n}).describe('Plugin caching configuration');\n\n/**\n * Plugin Sandboxing Configuration\n * Security isolation for plugins with configurable scope.\n * \n * Supports isolation beyond automation scripts: any plugin can be sandboxed\n * with process-level isolation and inter-plugin communication (IPC).\n */\nexport const PluginSandboxingSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(false),\n \n /**\n * Isolation scope - which plugins are subject to sandboxing\n */\n scope: z.enum([\n 'automation-only', // Sandbox automation/scripting plugins only (current behavior)\n 'untrusted-only', // Sandbox plugins below a trust threshold\n 'all-plugins', // Sandbox all plugins (maximum isolation)\n ]).default('automation-only').describe('Which plugins are subject to isolation'),\n \n /**\n * Sandbox isolation level\n */\n isolationLevel: z.enum([\n 'none', // No isolation\n 'process', // Separate process (Node.js worker threads)\n 'vm', // VM context isolation\n 'iframe', // iframe isolation (browser)\n 'web-worker', // Web Worker (browser)\n ]).default('none'),\n \n /**\n * Allowed capabilities\n */\n allowedCapabilities: z.array(z.string()).optional().describe('List of allowed capability IDs'),\n \n /**\n * Resource quotas\n */\n resourceQuotas: z.object({\n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(1).optional(),\n \n /**\n * Maximum CPU time in milliseconds\n */\n maxCpuTimeMs: z.number().int().min(100).optional(),\n \n /**\n * Maximum number of file descriptors\n */\n maxFileDescriptors: z.number().int().min(1).optional(),\n \n /**\n * Maximum network bandwidth in KB/s\n */\n maxNetworkKBps: z.number().int().min(1).optional(),\n }).optional(),\n \n /**\n * Permissions\n */\n permissions: z.object({\n /**\n * Allowed API access\n */\n allowedAPIs: z.array(z.string()).optional(),\n \n /**\n * Allowed file system paths\n */\n allowedPaths: z.array(z.string()).optional(),\n \n /**\n * Allowed network endpoints\n */\n allowedEndpoints: z.array(z.string()).optional(),\n \n /**\n * Allowed environment variables\n */\n allowedEnvVars: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Inter-Plugin Communication (IPC) configuration\n * Enables isolated plugins to communicate with the kernel and other plugins\n */\n ipc: z.object({\n /**\n * Enable IPC for sandboxed plugins\n */\n enabled: z.boolean().default(true)\n .describe('Allow sandboxed plugins to communicate via IPC'),\n \n /**\n * IPC transport mechanism\n */\n transport: z.enum([\n 'message-port', // MessagePort (worker threads / Web Workers)\n 'unix-socket', // Unix domain sockets (process isolation)\n 'tcp', // TCP sockets (container isolation)\n 'memory', // Shared memory channel (in-process VM)\n ]).default('message-port')\n .describe('IPC transport for cross-boundary communication'),\n \n /**\n * Maximum message size in bytes\n */\n maxMessageSize: z.number().int().min(1024).default(1048576)\n .describe('Maximum IPC message size in bytes (default 1MB)'),\n \n /**\n * Message timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000)\n .describe('IPC message response timeout in ms'),\n \n /**\n * Allowed service calls through IPC\n */\n allowedServices: z.array(z.string()).optional()\n .describe('Service names the sandboxed plugin may invoke via IPC'),\n }).optional(),\n}).describe('Plugin sandboxing configuration');\n\n/**\n * Plugin Performance Monitoring Configuration\n * Telemetry and performance tracking\n */\nexport const PluginPerformanceMonitoringSchema = z.object({\n /**\n * Enable performance monitoring\n */\n enabled: z.boolean().default(false),\n \n /**\n * Metrics to collect\n */\n metrics: z.array(z.enum([\n 'load-time',\n 'init-time',\n 'memory-usage',\n 'cpu-usage',\n 'api-calls',\n 'error-rate',\n 'cache-hit-rate',\n ])).optional(),\n \n /**\n * Sampling rate (0-1, where 1 = 100%)\n */\n samplingRate: z.number().min(0).max(1).default(1),\n \n /**\n * Reporting interval in seconds\n */\n reportingInterval: z.number().int().min(1).default(60),\n \n /**\n * Performance budget thresholds\n */\n budgets: z.object({\n /**\n * Maximum load time in milliseconds\n */\n maxLoadTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum init time in milliseconds\n */\n maxInitTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(0).optional(),\n }).optional(),\n \n /**\n * Action on budget violation\n */\n onBudgetViolation: z.enum(['warn', 'error', 'ignore']).default('warn'),\n}).describe('Plugin performance monitoring configuration');\n\n/**\n * Complete Plugin Loading Configuration\n * Combines all loading-related configurations\n */\nexport const PluginLoadingConfigSchema = z.object({\n /**\n * Loading strategy\n */\n strategy: PluginLoadingStrategySchema.default('lazy'),\n \n /**\n * Preloading configuration\n */\n preload: PluginPreloadConfigSchema.optional(),\n \n /**\n * Code splitting configuration\n */\n codeSplitting: PluginCodeSplittingSchema.optional(),\n \n /**\n * Dynamic import configuration\n */\n dynamicImport: PluginDynamicImportSchema.optional(),\n \n /**\n * Initialization configuration\n */\n initialization: PluginInitializationSchema.optional(),\n \n /**\n * Dependency resolution configuration\n */\n dependencyResolution: PluginDependencyResolutionSchema.optional(),\n \n /**\n * Hot reload configuration (development and production)\n */\n hotReload: PluginHotReloadSchema.optional(),\n \n /**\n * Caching configuration\n */\n caching: PluginCachingSchema.optional(),\n \n /**\n * Sandboxing configuration\n */\n sandboxing: PluginSandboxingSchema.optional(),\n \n /**\n * Performance monitoring\n */\n monitoring: PluginPerformanceMonitoringSchema.optional(),\n}).describe('Complete plugin loading configuration');\n\n/**\n * Plugin Loading Event\n * Emitted during plugin loading lifecycle\n */\nexport const PluginLoadingEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'load-started',\n 'load-completed',\n 'load-failed',\n 'init-started',\n 'init-completed',\n 'init-failed',\n 'preload-started',\n 'preload-completed',\n 'cache-hit',\n 'cache-miss',\n 'hot-reload',\n 'dynamic-load', // Plugin loaded at runtime\n 'dynamic-unload', // Plugin unloaded at runtime\n 'dynamic-discover', // Plugin discovered via registry\n ]),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Timestamp\n */\n timestamp: z.number().int().min(0),\n \n /**\n * Duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Error if event represents a failure\n */\n error: z.object({\n message: z.string(),\n code: z.string().optional(),\n stack: z.string().optional(),\n }).optional(),\n}).describe('Plugin loading lifecycle event');\n\n/**\n * Plugin Loading State\n * Tracks the current loading state of a plugin\n */\nexport const PluginLoadingStateSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current state\n */\n state: z.enum([\n 'pending', // Not yet loaded\n 'loading', // Currently loading\n 'loaded', // Code loaded, not initialized\n 'initializing', // Currently initializing\n 'ready', // Fully initialized and ready\n 'failed', // Failed to load or initialize\n 'reloading', // Hot reloading in progress\n 'unloading', // Being unloaded at runtime\n 'unloaded', // Successfully unloaded (dynamic loading)\n ]),\n \n /**\n * Load progress (0-100)\n */\n progress: z.number().min(0).max(100).default(0),\n \n /**\n * Loading start time\n */\n startedAt: z.number().int().min(0).optional(),\n \n /**\n * Loading completion time\n */\n completedAt: z.number().int().min(0).optional(),\n \n /**\n * Last error\n */\n lastError: z.string().optional(),\n \n /**\n * Retry count\n */\n retryCount: z.number().int().min(0).default(0),\n}).describe('Plugin loading state');\n\n// Export types\nexport type PluginLoadingStrategy = z.infer;\nexport type PluginPreloadConfig = z.infer;\nexport type PluginCodeSplitting = z.infer;\nexport type PluginDynamicImport = z.infer;\nexport type PluginInitialization = z.infer;\nexport type PluginDependencyResolution = z.infer;\nexport type PluginHotReload = z.infer;\nexport type PluginCaching = z.infer;\nexport type PluginSandboxing = z.infer;\nexport type PluginPerformanceMonitoring = z.infer;\nexport type PluginLoadingConfig = z.infer;\nexport type PluginLoadingEvent = z.infer;\nexport type PluginLoadingState = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// Service method interfaces use z.function() instead of z.any() for type safety.\n// Generic data fields use z.unknown() for type safety.\nexport const PluginContextSchema = z.object({\n ql: z.object({\n object: z.function().describe('Get object handle for method chaining'),\n query: z.function().describe('Execute a query'),\n }).passthrough().describe('ObjectQL Engine Interface'),\n\n os: z.object({\n getCurrentUser: z.function().describe('Get the current authenticated user'),\n getConfig: z.function().describe('Get platform configuration'),\n }).passthrough().describe('ObjectStack Kernel Interface'),\n\n logger: z.object({\n debug: z.function().describe('Log debug message'),\n info: z.function().describe('Log info message'),\n warn: z.function().describe('Log warning message'),\n error: z.function().describe('Log error message'),\n }).passthrough().describe('Logger Interface'),\n\n storage: z.object({\n get: z.function().describe('Get a value from storage'),\n set: z.function().describe('Set a value in storage'),\n delete: z.function().describe('Delete a value from storage'),\n }).passthrough().describe('Storage Interface'),\n\n i18n: z.object({\n t: z.function().describe('Translate a key'),\n getLocale: z.function().describe('Get current locale'),\n }).passthrough().describe('Internationalization Interface'),\n\n metadata: z.record(z.string(), z.unknown()),\n events: z.record(z.string(), z.unknown()),\n \n app: z.object({\n router: z.object({\n get: z.function().describe('Register GET route handler'),\n post: z.function().describe('Register POST route handler'),\n use: z.function().describe('Register middleware'),\n }).passthrough()\n }).passthrough().describe('App Framework Interface'),\n\n drivers: z.object({\n register: z.function().describe('Register a driver'),\n }).passthrough().describe('Driver Registry'),\n});\n\nexport type PluginContextData = z.infer;\nexport type PluginContext = PluginContextData;\n\n/**\n * Upgrade Context Schema\n *\n * Provides version migration context to the `onUpgrade` lifecycle hook.\n * Enables developers to write conditional migration logic based on\n * the previous and new versions.\n */\nexport const UpgradeContextSchema = z.object({\n /** Version before upgrade */\n previousVersion: z.string().describe('Version before upgrade'),\n\n /** Version after upgrade */\n newVersion: z.string().describe('Version after upgrade'),\n\n /** Whether this is a major version bump */\n isMajorUpgrade: z.boolean().describe('Whether this is a major version bump'),\n\n /** Metadata snapshot before upgrade (for migration logic) */\n previousMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Metadata snapshot before upgrade'),\n}).describe('Version migration context for onUpgrade hook');\n\nexport type UpgradeContext = z.infer;\n\nexport const PluginLifecycleSchema = z.object({\n onInstall: z.function().optional().describe('Called when plugin is installed'),\n \n onEnable: z.function().optional().describe('Called when plugin is enabled'),\n \n onDisable: z.function().optional().describe('Called when plugin is disabled'),\n \n onUninstall: z.function().optional().describe('Called when plugin is uninstalled'),\n \n onUpgrade: z.function().optional().describe('Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade'),\n});\n\nexport type PluginLifecycleHooks = z.infer;\n\n/**\n * Shared Plugin Types\n * These are the specialized plugin types common between Manifest (Package) and Plugin (Runtime).\n */\nexport const CORE_PLUGIN_TYPES = [\n 'ui', // Frontend: Serves static assets/SPA (e.g. Console, Studio)\n 'driver', // Connectivity: Database or Storage adapters (e.g. SQL, S3)\n 'server', // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL)\n 'app', // Business: Vertical Solution Bundle (Metadata + Logic)\n 'theme', // Appearance: UI Overrides & CSS Variables\n 'agent', // AI: Autonomous Agent & Tool Definitions\n 'objectql' // Core: ObjectQL Engine Data Provider\n] as const;\n\nexport const PluginSchema = PluginLifecycleSchema.extend({\n id: z.string().min(1).optional().describe('Unique Plugin ID (e.g. com.example.crm)'),\n type: z.enum([\n 'standard', // Default: General purpose backend logic (Service, Hook, etc.)\n ...CORE_PLUGIN_TYPES\n ]).default('standard').optional().describe('Plugin Type categorization for runtime behavior'),\n \n staticPath: z.string().optional().describe('Absolute path to static assets (Required for type=\"ui-plugin\")'),\n slug: z.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type=\"ui-plugin\")'),\n default: z.boolean().optional().describe('Serve at root path (Only one \"ui-plugin\" can be default)'),\n \n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic Version'),\n description: z.string().optional(),\n author: z.string().optional(),\n homepage: z.string().url().optional(),\n});\n\nexport type PluginDefinition = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\nimport { PluginLoadingConfigSchema } from './plugin-loading.zod';\nimport { CORE_PLUGIN_TYPES } from './plugin.zod';\nimport { DatasetSchema } from '../data/dataset.zod';\n\n/**\n * Schema for the ObjectStack Manifest.\n * This defines the structure of a package configuration in the ObjectStack ecosystem.\n * All packages (apps, plugins, drivers, modules) must conform to this schema.\n * \n * @example App Package\n * ```yaml\n * id: com.acme.crm\n * version: 1.0.0\n * type: app\n * name: Acme CRM\n * description: Customer Relationship Management system\n * permissions:\n * - system.user.read\n * - system.object.create\n * objects:\n * - \"./src/objects/*.object.yml\"\n * ```\n */\nexport const ManifestSchema = z.object({\n /** \n * Unique package identifier using reverse domain notation.\n * Must be unique across the entire ecosystem.\n * \n * @example \"com.steedos.crm\"\n * @example \"org.apache.superset\"\n */\n id: z.string().describe('Unique package identifier (reverse domain style)'),\n \n /**\n * Short namespace identifier for metadata scoping.\n * Used as a prefix for objects and other metadata to prevent naming collisions\n * across packages from different vendors.\n * \n * Rules:\n * - 2-20 characters, lowercase letters, digits, and underscores only.\n * - Must be unique within a running instance.\n * - Platform-reserved namespaces (no prefix applied): \"base\", \"system\".\n * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator).\n * \n * @example \"crm\" → objects become crm__account, crm__deal\n * @example \"todo\" → objects become todo__task\n * @example \"base\" → objects keep short name (platform reserved)\n */\n namespace: z.string()\n .regex(/^[a-z][a-z0-9_]{1,19}$/, 'Namespace must be 2-20 chars, lowercase alphanumeric + underscore')\n .optional()\n .describe('Short namespace identifier for metadata scoping (e.g. \"crm\", \"todo\")'),\n \n /** \n * Package version following semantic versioning (major.minor.patch).\n * \n * @example \"1.0.0\"\n * @example \"2.1.0-beta.1\"\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Package version (semantic versioning)'),\n \n /** \n * Type of the package in the ObjectStack ecosystem.\n * - plugin: General-purpose functionality extension (Runtime: standard)\n * - app: Business application package\n * - driver: Connectivity adapter\n * - server: Protocol gateway (Hono, GraphQL)\n * - ui: Frontend package (Static/SPA)\n * - theme: UI Theme\n * - agent: AI Agent\n * - module: Reusable code library/shared module\n * - objectql: Core engine\n * - adapter: Host adapter (Express, Fastify)\n */\n type: z.enum([\n 'plugin', \n ...CORE_PLUGIN_TYPES,\n 'module', \n 'gateway', // Deprecated: use 'server'\n 'adapter'\n ]).describe('Type of package'),\n \n /** \n * Human-readable name of the package.\n * Displayed in the UI for users.\n * \n * @example \"Project Management\"\n */\n name: z.string().describe('Human-readable package name'),\n \n /** \n * Brief description of the package functionality.\n * Displayed in the marketplace and plugin manager.\n */\n description: z.string().optional().describe('Package description'),\n \n /** \n * Array of permission strings that the package requires.\n * These form the \"Scope\" requested by the package at installation.\n * \n * @example [\"system.user.read\", \"system.data.write\"]\n */\n permissions: z.array(z.string()).optional().describe('Array of required permission strings'),\n \n /** \n * Glob patterns specifying ObjectQL schemas files.\n * Matches `*.object.yml` or `*.object.ts` files to load business objects.\n * \n * @example [\"./src/objects/*.object.yml\"]\n */\n objects: z.array(z.string()).optional().describe('Glob patterns for ObjectQL schemas files'),\n\n /**\n * Defines system level DataSources.\n * Matches `*.datasource.yml` files.\n * \n * @example [\"./src/datasources/*.datasource.mongo.yml\"]\n */\n datasources: z.array(z.string()).optional().describe('Glob patterns for Datasource definitions'),\n\n /**\n * Package Dependencies.\n * Map of package IDs to version requirements.\n * \n * @example { \"@steedos/plugin-auth\": \"^2.0.0\" }\n */\n dependencies: z.record(z.string(), z.string()).optional().describe('Package dependencies'),\n\n /**\n * Plugin Configuration Schema.\n * Defines the settings this plugin exposes to the user via UI/ENV.\n * Uses a simplified JSON Schema format.\n * \n * @example\n * {\n * \"title\": \"Stripe Config\",\n * \"properties\": {\n * \"apiKey\": { \"type\": \"string\", \"secret\": true },\n * \"currency\": { \"type\": \"string\", \"default\": \"USD\" }\n * }\n * }\n */\n configuration: z.object({\n title: z.string().optional(),\n properties: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']).describe('Data type of the setting'),\n default: z.unknown().optional().describe('Default value'),\n description: z.string().optional().describe('Tooltip description'),\n required: z.boolean().optional().describe('Is this setting required?'),\n secret: z.boolean().optional().describe('If true, value is encrypted/masked (e.g. API Keys)'),\n enum: z.array(z.string()).optional().describe('Allowed values for select inputs'),\n })).describe('Map of configuration keys to their definitions')\n }).optional().describe('Plugin configuration settings'),\n\n /**\n * Contribution Points (VS Code Style).\n * formalized way to extend the platform capabilities.\n */\n contributes: z.object({\n /**\n * Register new Metadata Kinds (CRDs).\n * Enables the system to parse and validate new file types.\n * Example: Registering a BI plugin to handle *.report.ts\n */\n kinds: z.array(z.object({\n id: z.string().describe('The generic identifier of the kind (e.g., \"sys.bi.report\")'),\n globs: z.array(z.string()).describe('File patterns to watch (e.g., [\"**/*.report.ts\"])'),\n description: z.string().optional().describe('Description of what this kind represents'),\n })).optional().describe('New Metadata Types to recognize'),\n\n /**\n * Register System Hooks.\n * Declares that this plugin listens to specific system events.\n */\n events: z.array(z.string()).optional().describe('Events this plugin listens to'),\n\n /**\n * Register UI Menus.\n */\n menus: z.record(z.string(), z.array(z.object({\n id: z.string(),\n label: z.string(),\n command: z.string().optional(),\n }))).optional().describe('UI Menu contributions'),\n\n /**\n * Register Custom Themes.\n */\n themes: z.array(z.object({\n id: z.string(),\n label: z.string(),\n path: z.string(),\n })).optional().describe('Theme contributions'),\n\n /**\n * Register Translations.\n * Path to translation files (e.g. \"locales/en.json\").\n */\n translations: z.array(z.object({\n locale: z.string(),\n path: z.string(),\n })).optional().describe('Translation resources'),\n\n /**\n * Register Server Actions.\n * Invocable functions exposed to Flows or API.\n */\n actions: z.array(z.object({\n name: z.string().describe('Unique action name'),\n label: z.string().optional(),\n description: z.string().optional(),\n input: z.unknown().optional().describe('Input validation schema'),\n output: z.unknown().optional().describe('Output schema'),\n })).optional().describe('Exposed server actions'),\n\n /**\n * Register Storage Drivers.\n * Enables connecting to new types of datasources.\n */\n drivers: z.array(z.object({\n id: z.string().describe('Driver unique identifier (e.g. \"postgres\", \"mongo\")'),\n label: z.string().describe('Human readable name'),\n description: z.string().optional(),\n })).optional().describe('Driver contributions'),\n\n /**\n * Register Custom Field Types.\n * Extends the data model with new widget types.\n */\n fieldTypes: z.array(z.object({\n name: z.string().describe('Unique field type name (e.g. \"vector\")'),\n label: z.string().describe('Display label'),\n description: z.string().optional(),\n })).optional().describe('Field Type contributions'),\n \n /**\n * Register Custom Query Operators/Functions.\n * Extends ObjectQL with new functions (e.g. distance()).\n */\n functions: z.array(z.object({\n name: z.string().describe('Function name (e.g. \"distance\")'),\n description: z.string().optional(),\n args: z.array(z.string()).optional().describe('Argument types'),\n returnType: z.string().optional(),\n })).optional().describe('Query Function contributions'),\n\n /**\n * Register API Route Namespaces.\n * Declares the API endpoints this plugin provides to the HttpDispatcher.\n * The kernel routes matching prefixes to this plugin's handler.\n * \n * @example\n * routes: [\n * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] }\n * ]\n */\n routes: z.array(z.object({\n /** URL path prefix (e.g. \"/api/v1/ai\") */\n prefix: z.string().regex(/^\\//).describe('API path prefix'),\n /** Service name this plugin provides */\n service: z.string().describe('Service name this plugin provides'),\n /** Protocol method names implemented */\n methods: z.array(z.string()).optional()\n .describe('Protocol method names implemented (e.g. [\"aiNlq\", \"aiChat\"])'),\n })).optional().describe('API route contributions to HttpDispatcher'),\n\n /**\n * Register CLI Commands.\n * Allows plugins to extend the ObjectStack CLI with custom commands.\n * Each command entry declares metadata; the actual Commander.js command\n * is resolved at runtime by importing the plugin's module.\n * \n * The plugin package must export a `commands` array of Commander.js `Command` instances\n * from its main entry point or from the path specified in `module`.\n * \n * @example\n * ```yaml\n * commands:\n * - name: marketplace\n * description: \"Manage marketplace apps\"\n * module: \"./cli\" # optional, defaults to package main\n * - name: deploy\n * description: \"Deploy to cloud\"\n * ```\n */\n commands: z.array(z.object({\n /** CLI command name (e.g., \"marketplace\", \"deploy\"). Must be a valid CLI identifier. */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n /** Brief description shown in `os --help` */\n description: z.string().optional().describe('Command description for help text'),\n /** \n * Optional module path (relative to package root) that exports the Commander.js commands.\n * If omitted, the CLI will import from the package's main entry point.\n * The module must export a `commands` array of Commander.js `Command` instances,\n * or a single `Command` instance as default export.\n */\n module: z.string().optional().describe('Module path exporting Commander.js commands'),\n })).optional().describe('CLI command contributions'),\n }).optional().describe('Platform contributions'),\n\n /** \n * Initial data seeding configuration.\n * Defines default records to be inserted when the package is installed.\n * \n * Uses the standard DatasetSchema which supports idempotent upsert via\n * `externalId`, environment scoping via `env`, and multiple conflict\n * resolution modes.\n * \n * @deprecated Prefer using the top-level `data` field on the Stack Definition\n * (defineStack({ data: [...] })) for better visibility and metadata registration.\n * This field is retained for backward compatibility with manifest-only packages.\n */\n data: z.array(DatasetSchema).optional().describe('Initial seed data (prefer top-level data field)'),\n\n /**\n * Plugin Capability Manifest.\n * Declares protocols implemented, interfaces provided, dependencies, and extension points.\n * This enables plugin interoperability and automatic discovery.\n */\n capabilities: PluginCapabilityManifestSchema.optional()\n .describe('Plugin capability declarations for interoperability'),\n\n /** \n * Extension points contributed by this package.\n * Allows packages to extend UI components, add functionality, etc.\n */\n extensions: z.record(z.string(), z.unknown()).optional().describe('Extension points and contributions'),\n\n /**\n * Plugin Loading Configuration.\n * Configures how the plugin is loaded, initialized, and managed at runtime.\n * Includes strategies for lazy loading, code splitting, caching, and hot reload.\n */\n loading: PluginLoadingConfigSchema.optional()\n .describe('Plugin loading and runtime behavior configuration'),\n\n /**\n * Platform Compatibility Requirements.\n * Specifies the minimum ObjectStack platform version required to run this package.\n * Used at install time to prevent incompatible packages from being installed.\n *\n * @example\n * ```yaml\n * engine:\n * objectstack: \">=3.0.0\"\n * ```\n */\n engine: z.object({\n /** ObjectStack platform version requirement (SemVer range) */\n objectstack: z.string()\n .regex(/^[><=~^]*\\d+\\.\\d+\\.\\d+/)\n .describe('ObjectStack platform version requirement (SemVer range, e.g. \">=3.0.0\")'),\n }).optional().describe('Platform compatibility requirements'),\n});\n\n/**\n * TypeScript type inferred from the ManifestSchema.\n * Use this type for type-safe manifest handling in TypeScript code.\n */\nexport type ObjectStackManifest = z.infer;\nexport type ObjectStackManifestInput = z.input;\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Customization Layer Protocol\n * \n * Defines the overlay system for managing user customizations on top of\n * package-delivered metadata. This protocol solves the critical challenge\n * of separating \"vendor-managed\" metadata from \"customer-customized\" metadata,\n * enabling safe package upgrades without losing user changes.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed vs Unmanaged metadata components\n * - **ServiceNow**: Update Sets with collision detection\n * - **WordPress**: Parent/child theme overlay model\n * - **Kubernetes**: Strategic merge patch for resource customization\n * \n * ## Three-Layer Model\n * ```\n * ┌─────────────────────────────────┐\n * │ User Layer (scope: user) │ ← Personal overrides (per-user)\n * ├─────────────────────────────────┤\n * │ Platform Layer (scope: platform)│ ← Admin customizations (per-tenant)\n * ├─────────────────────────────────┤\n * │ System Layer (scope: system) │ ← Package-delivered metadata (read-only)\n * └─────────────────────────────────┘\n * ```\n * \n * ## Merge Resolution Order\n * Effective metadata = System ← merge(Platform) ← merge(User)\n * Each layer only stores the delta (changed fields), not the full definition.\n */\n\n// ==========================================\n// Customization Tracking\n// ==========================================\n\n/**\n * Customization Origin\n * Identifies who created the customization.\n */\nexport const CustomizationOriginSchema = z.enum([\n 'package', // Delivered by a plugin package (system layer, read-only)\n 'admin', // Created/modified by platform admin via UI\n 'user', // Created/modified by end user via UI\n 'migration', // Created during data migration\n 'api', // Created via API\n]);\n\n/**\n * Field-Level Change Tracking\n * Records exactly which fields were modified by the customer.\n */\nexport const FieldChangeSchema = z.object({\n /** JSON path to the changed field (e.g. \"fields.status.label\") */\n path: z.string().describe('JSON path to the changed field'),\n\n /** Original value from the package (for diff/rollback) */\n originalValue: z.unknown().optional().describe('Original value from the package'),\n\n /** Current customized value */\n currentValue: z.unknown().describe('Current customized value'),\n\n /** Who made this change */\n changedBy: z.string().optional().describe('User or admin who made this change'),\n\n /** When this change was made */\n changedAt: z.string().datetime().optional().describe('Timestamp of the change'),\n});\n\n/**\n * Metadata Overlay Schema\n * \n * Represents a customization layer on top of package-delivered metadata.\n * Each overlay stores only the delta (changed fields) relative to the base definition.\n * \n * During package upgrades, the system performs a 3-way merge:\n * 1. Old package version (base)\n * 2. New package version (theirs)\n * 3. Customer customizations (ours)\n * \n * @example\n * ```yaml\n * # Package delivers: object \"crm__account\" with field \"status\" label \"Status\"\n * # Admin changes label to \"Account Status\"\n * # Overlay record:\n * baseType: object\n * baseName: crm__account\n * packageId: com.acme.crm\n * packageVersion: \"1.0.0\"\n * changes:\n * - path: \"fields.status.label\"\n * originalValue: \"Status\"\n * currentValue: \"Account Status\"\n * ```\n */\nexport const MetadataOverlaySchema = z.object({\n /** Primary key */\n id: z.string().describe('Overlay record ID (UUID)'),\n\n /** The metadata type being customized (e.g. \"object\", \"view\", \"flow\") */\n baseType: z.string().describe('Metadata type being customized'),\n\n /** The metadata name being customized (e.g. \"crm__account\") */\n baseName: z.string().describe('Metadata name being customized'),\n\n /** Package that owns the base metadata (null for platform-created metadata) */\n packageId: z.string().optional().describe('Package ID that delivered the base metadata'),\n\n /** Package version when the customization was made (for upgrade diffing) */\n packageVersion: z.string().optional().describe('Package version when overlay was created'),\n\n /** Customization scope */\n scope: z.enum(['platform', 'user']).default('platform')\n .describe('Customization scope (platform=admin, user=personal)'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Owner user ID (for user-scope overlays) */\n owner: z.string().optional().describe('Owner user ID for user-scope overlays'),\n\n /**\n * The overlay payload.\n * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396).\n * - To modify a field: include the field with its new value\n * - To delete a field: set its value to null\n * - Omitted fields remain unchanged from base\n */\n patch: z.record(z.string(), z.unknown()).describe('JSON Merge Patch payload (changed fields only)'),\n\n /**\n * Detailed change tracking for each modified field.\n * Enables field-level conflict detection during upgrades.\n */\n changes: z.array(FieldChangeSchema).optional()\n .describe('Field-level change tracking for conflict detection'),\n\n /** Whether this overlay is currently active */\n active: z.boolean().default(true).describe('Whether this overlay is active'),\n\n /** Audit timestamps */\n createdAt: z.string().datetime().optional(),\n createdBy: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n updatedBy: z.string().optional(),\n});\n\n// ==========================================\n// Merge & Conflict Resolution\n// ==========================================\n\n/**\n * Merge Conflict\n * Represents a conflict between package update and customer customization.\n */\nexport const MergeConflictSchema = z.object({\n /** JSON path to the conflicting field */\n path: z.string().describe('JSON path to the conflicting field'),\n\n /** Value in the old package version */\n baseValue: z.unknown().describe('Value in the old package version'),\n\n /** Value in the new package version */\n incomingValue: z.unknown().describe('Value in the new package version'),\n\n /** Customer's customized value */\n customValue: z.unknown().describe('Customer customized value'),\n\n /** Suggested resolution strategy */\n suggestedResolution: z.enum([\n 'keep-custom', // Keep customer's customization\n 'accept-incoming', // Accept package update\n 'manual', // Requires manual resolution\n ]).describe('Suggested resolution strategy'),\n\n /** Reason for the suggested resolution */\n reason: z.string().optional().describe('Explanation for the suggested resolution'),\n});\n\n/**\n * Merge Strategy Configuration\n * Controls how metadata merging behaves during package upgrades.\n */\nexport const MergeStrategyConfigSchema = z.object({\n /** Default strategy when no field-level rule matches */\n defaultStrategy: z.enum([\n 'keep-custom', // Preserve all customer customizations (safe)\n 'accept-incoming', // Accept all package updates (overwrite)\n 'three-way-merge', // Intelligent 3-way merge with conflict detection\n ]).default('three-way-merge').describe('Default merge strategy'),\n\n /** \n * Field paths that should always accept incoming package updates.\n * Use for fields that the package vendor considers \"owned\" and should not be customized.\n * @example [\"fields.*.type\", \"triggers.*\"]\n */\n alwaysAcceptIncoming: z.array(z.string()).optional()\n .describe('Field paths that always accept package updates'),\n\n /**\n * Field paths where customer customizations always win.\n * Use for UI-facing fields like labels, descriptions, help text.\n * @example [\"fields.*.label\", \"fields.*.helpText\", \"description\"]\n */\n alwaysKeepCustom: z.array(z.string()).optional()\n .describe('Field paths where customer customizations always win'),\n\n /** Whether to automatically resolve non-conflicting changes */\n autoResolveNonConflicting: z.boolean().default(true)\n .describe('Auto-resolve changes that do not conflict'),\n});\n\n/**\n * Merge Result\n * Result of a 3-way merge operation during package upgrade.\n */\nexport const MergeResultSchema = z.object({\n /** Whether the merge completed successfully (no unresolved conflicts) */\n success: z.boolean().describe('Whether merge completed without unresolved conflicts'),\n\n /** The merged metadata payload */\n mergedMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Merged metadata result'),\n\n /** Updated overlay with remaining customizations */\n updatedOverlay: z.record(z.string(), z.unknown()).optional()\n .describe('Updated overlay after merge'),\n\n /** List of conflicts that require manual resolution */\n conflicts: z.array(MergeConflictSchema).optional()\n .describe('Unresolved merge conflicts'),\n\n /** Summary of automatically resolved changes */\n autoResolved: z.array(z.object({\n path: z.string(),\n resolution: z.string(),\n description: z.string().optional(),\n })).optional().describe('Summary of auto-resolved changes'),\n\n /** Statistics */\n stats: z.object({\n totalFields: z.number().int().min(0).describe('Total fields evaluated'),\n unchanged: z.number().int().min(0).describe('Fields with no changes'),\n autoResolved: z.number().int().min(0).describe('Fields auto-resolved'),\n conflicts: z.number().int().min(0).describe('Fields with conflicts'),\n }).optional(),\n});\n\n// ==========================================\n// Customization Management\n// ==========================================\n\n/**\n * Customizable Metadata Policy\n * Defines what parts of a metadata item can be customized by admins/users.\n * Package vendors use this to control customization boundaries.\n */\nexport const CustomizationPolicySchema = z.object({\n /** Metadata type this policy applies to */\n metadataType: z.string().describe('Metadata type (e.g. \"object\", \"view\")'),\n\n /** Whether customization is allowed at all for this type */\n allowCustomization: z.boolean().default(true),\n\n /**\n * Field paths that are locked (cannot be customized).\n * @example [\"name\", \"type\", \"fields.*.type\"]\n */\n lockedFields: z.array(z.string()).optional()\n .describe('Field paths that cannot be customized'),\n\n /**\n * Field paths that are customizable.\n * If specified, only these fields can be customized (whitelist mode).\n * @example [\"label\", \"description\", \"fields.*.label\", \"fields.*.helpText\"]\n */\n customizableFields: z.array(z.string()).optional()\n .describe('Field paths that can be customized (whitelist)'),\n\n /**\n * Whether users can add new fields to package objects.\n * When true, admins can extend package objects with custom fields.\n */\n allowAddFields: z.boolean().default(true)\n .describe('Whether admins can add new fields to package objects'),\n\n /**\n * Whether users can delete package-delivered fields.\n * Typically false — fields can only be hidden, not deleted.\n */\n allowDeleteFields: z.boolean().default(false)\n .describe('Whether admins can delete package-delivered fields'),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type CustomizationOrigin = z.infer;\nexport type FieldChange = z.infer;\nexport type MetadataOverlay = z.infer;\nexport type MergeConflict = z.infer;\nexport type MergeStrategyConfig = z.infer;\nexport type MergeResult = z.infer;\nexport type CustomizationPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Loader Protocol\n * \n * Defines the standard interface for loading and saving metadata in ObjectStack.\n * This protocol enables consistent metadata operations across different storage backends\n * (filesystem, HTTP, S3, databases) and serialization formats (JSON, YAML, TypeScript).\n */\n\n/**\n * Metadata Format Enum\n * Supported serialization formats for metadata\n */\nexport const MetadataFormatSchema = z.enum(['json', 'yaml', 'typescript', 'javascript']);\n\n/**\n * Metadata Statistics\n * Information about a metadata item without loading its full content\n */\nexport const MetadataStatsSchema = z.object({\n /**\n * Size of the metadata file in bytes\n */\n size: z.number().int().min(0).describe('File size in bytes'),\n \n /**\n * Last modification timestamp\n */\n modifiedAt: z.string().datetime().describe('Last modified date'),\n \n /**\n * ETag for cache validation\n * Used for conditional requests (If-None-Match header)\n */\n etag: z.string().describe('Entity tag for cache validation'),\n \n /**\n * Serialization format\n */\n format: MetadataFormatSchema.describe('Serialization format'),\n \n /**\n * Full file path (if applicable)\n */\n path: z.string().optional().describe('File system path'),\n \n /**\n * Additional metadata provider-specific properties\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Provider-specific metadata'),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n /**\n * Glob patterns to match files\n * Example: [\"**\\/*.object.ts\", \"**\\/*.object.json\"]\n */\n patterns: z.array(z.string()).optional().describe('File glob patterns'),\n \n /**\n * If-None-Match header for conditional loading\n * Only load if ETag doesn't match\n */\n ifNoneMatch: z.string().optional().describe('ETag for conditional request'),\n \n /**\n * If-Modified-Since header for conditional loading\n */\n ifModifiedSince: z.string().datetime().optional().describe('Only load if modified after this date'),\n \n /**\n * Whether to validate against Zod schema\n */\n validate: z.boolean().default(true).describe('Validate against schema'),\n \n /**\n * Whether to use cache if available\n */\n useCache: z.boolean().default(true).describe('Enable caching'),\n \n /**\n * Filter function (serialized as string)\n * Example: \"(item) => item.name.startsWith('sys_')\"\n */\n filter: z.string().optional().describe('Filter predicate as string'),\n \n /**\n * Maximum number of items to load\n */\n limit: z.number().int().min(1).optional().describe('Maximum items to load'),\n \n /**\n * Recursively search subdirectories\n */\n recursive: z.boolean().default(true).describe('Search subdirectories'),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n /**\n * Serialization format\n */\n format: MetadataFormatSchema.default('typescript').describe('Output format'),\n \n /**\n * Prettify output (formatted with indentation)\n */\n prettify: z.boolean().default(true).describe('Format with indentation'),\n \n /**\n * Indentation size (spaces)\n */\n indent: z.number().int().min(0).max(8).default(2).describe('Indentation spaces'),\n \n /**\n * Sort object keys alphabetically\n */\n sortKeys: z.boolean().default(false).describe('Sort object keys'),\n \n /**\n * Include default values in output\n */\n includeDefaults: z.boolean().default(false).describe('Include default values'),\n \n /**\n * Create backup before overwriting\n */\n backup: z.boolean().default(false).describe('Create backup file'),\n \n /**\n * Overwrite if exists\n */\n overwrite: z.boolean().default(true).describe('Overwrite existing file'),\n \n /**\n * Atomic write (write to temp file, then rename)\n */\n atomic: z.boolean().default(true).describe('Use atomic write operation'),\n \n /**\n * Custom file path (overrides default location)\n */\n path: z.string().optional().describe('Custom output path'),\n});\n\n/**\n * Metadata Export Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n /**\n * Output file path\n */\n output: z.string().describe('Output file path'),\n \n /**\n * Export format\n */\n format: MetadataFormatSchema.default('json').describe('Export format'),\n \n /**\n * Filter predicate as string\n */\n filter: z.string().optional().describe('Filter items to export'),\n \n /**\n * Include statistics in export\n */\n includeStats: z.boolean().default(false).describe('Include metadata statistics'),\n \n /**\n * Compress output\n */\n compress: z.boolean().default(false).describe('Compress output (gzip)'),\n \n /**\n * Pretty print output\n */\n prettify: z.boolean().default(true).describe('Pretty print output'),\n});\n\n/**\n * Metadata Import Options\n */\nexport const MetadataImportOptionsSchema = z.object({\n /**\n * Conflict resolution strategy\n */\n conflictResolution: z.enum(['skip', 'overwrite', 'merge', 'fail'])\n .default('merge')\n .describe('How to handle existing items'),\n \n /**\n * Validate items against schema\n */\n validate: z.boolean().default(true).describe('Validate before import'),\n \n /**\n * Dry run (don't actually save)\n */\n dryRun: z.boolean().default(false).describe('Simulate import without saving'),\n \n /**\n * Continue on errors\n */\n continueOnError: z.boolean().default(false).describe('Continue if validation fails'),\n \n /**\n * Transform function (as string)\n * Example: \"(item) => ({ ...item, imported: true })\"\n */\n transform: z.string().optional().describe('Transform items before import'),\n});\n\n/**\n * Metadata Loader Result\n * Result of a metadata load operation\n */\nexport const MetadataLoadResultSchema = z.object({\n /**\n * Loaded data\n */\n data: z.unknown().nullable().describe('Loaded metadata'),\n \n /**\n * Whether data came from cache (304 Not Modified)\n */\n fromCache: z.boolean().default(false).describe('Loaded from cache'),\n \n /**\n * Not modified (conditional request matched)\n */\n notModified: z.boolean().default(false).describe('Not modified since last request'),\n \n /**\n * ETag of loaded data\n */\n etag: z.string().optional().describe('Entity tag'),\n \n /**\n * Statistics about loaded data\n */\n stats: MetadataStatsSchema.optional().describe('Metadata statistics'),\n \n /**\n * Load time in milliseconds\n */\n loadTime: z.number().min(0).optional().describe('Load duration in ms'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n /**\n * Whether save was successful\n */\n success: z.boolean().describe('Save successful'),\n \n /**\n * Path where file was saved\n */\n path: z.string().describe('Output path'),\n \n /**\n * Generated ETag\n */\n etag: z.string().optional().describe('Generated entity tag'),\n \n /**\n * File size in bytes\n */\n size: z.number().int().min(0).optional().describe('File size'),\n \n /**\n * Save time in milliseconds\n */\n saveTime: z.number().min(0).optional().describe('Save duration in ms'),\n \n /**\n * Backup path (if created)\n */\n backupPath: z.string().optional().describe('Backup file path'),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum(['added', 'changed', 'deleted']).describe('Event type'),\n \n /**\n * Metadata type (e.g., 'object', 'view', 'app')\n */\n metadataType: z.string().describe('Type of metadata'),\n \n /**\n * Item name/identifier\n */\n name: z.string().describe('Item identifier'),\n \n /**\n * Full file path\n */\n path: z.string().describe('File path'),\n \n /**\n * Loaded item data (for added/changed events)\n */\n data: z.unknown().optional().describe('Item data'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\n/**\n * Metadata Collection Info\n * Summary of a metadata collection\n */\nexport const MetadataCollectionInfoSchema = z.object({\n /**\n * Collection type (e.g., 'object', 'view', 'app')\n */\n type: z.string().describe('Collection type'),\n \n /**\n * Total items in collection\n */\n count: z.number().int().min(0).describe('Number of items'),\n \n /**\n * Formats found in collection\n */\n formats: z.array(MetadataFormatSchema).describe('Formats in collection'),\n \n /**\n * Total size in bytes\n */\n totalSize: z.number().int().min(0).optional().describe('Total size in bytes'),\n \n /**\n * Last modified timestamp\n */\n lastModified: z.string().datetime().optional().describe('Last modification date'),\n \n /**\n * Collection location (path or URL)\n */\n location: z.string().optional().describe('Collection location'),\n});\n\n/**\n * Metadata Loader Interface Contract\n * Defines the standard methods all metadata loaders must implement\n */\nexport const MetadataLoaderContractSchema = z.object({\n /**\n * Loader name/identifier\n */\n name: z.string().describe('Loader identifier'),\n\n /**\n * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:')\n */\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Protocol identifier'),\n\n /**\n * Detailed capabilities\n */\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }).describe('Loader capabilities'),\n \n /**\n * Supported formats\n */\n supportedFormats: z.array(MetadataFormatSchema).describe('Supported formats'),\n \n /**\n * Whether loader supports watching for changes\n */\n supportsWatch: z.boolean().default(false).describe('Supports file watching'),\n \n /**\n * Whether loader supports saving\n */\n supportsWrite: z.boolean().default(true).describe('Supports write operations'),\n \n /**\n * Whether loader supports caching\n */\n supportsCache: z.boolean().default(true).describe('Supports caching'),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Manager Configuration\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory path'),\n \n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).default(['typescript', 'json', 'yaml']).describe('Enabled formats'),\n \n /**\n * Cache configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable caching'),\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n maxSize: z.number().int().min(0).optional().describe('Max cache size in bytes'),\n }).optional().describe('Cache settings'),\n \n /**\n * Watch for file changes\n */\n watch: z.boolean().default(false).describe('Enable file watching'),\n \n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n ignoreInitial: z.boolean().default(true).describe('Ignore initial add events'),\n }).optional().describe('File watcher options'),\n \n /**\n * Validation settings\n */\n validation: z.object({\n strict: z.boolean().default(true).describe('Strict validation'),\n throwOnError: z.boolean().default(true).describe('Throw on validation error'),\n }).optional().describe('Validation settings'),\n \n /**\n * Loader-specific options\n */\n loaderOptions: z.record(z.string(), z.unknown()).optional().describe('Loader-specific configuration'),\n});\n\n// Export types\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoadOptions = z.input;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { MetadataManagerConfigSchema } from './metadata-loader.zod';\nimport { MergeStrategyConfigSchema, CustomizationPolicySchema } from './metadata-customization.zod';\n\n/**\n * # Metadata Plugin Protocol\n *\n * Defines the specification for the **Metadata Plugin** — the central authority\n * responsible for managing ALL metadata across the ObjectStack platform.\n *\n * ## Architecture\n * The Metadata Plugin consolidates all scattered metadata operations into a single,\n * cohesive plugin that \"takes over\" the entire platform's metadata management:\n *\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ Metadata Plugin │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Type Registry │ │ Loader │ │ Customization Layer │ │\n * │ │ (all types) │ │ (file/db/s3)│ │ (overlay / merge) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Persistence │ │ Query │ │ Lifecycle │ │\n * │ │ (db records) │ │ (search) │ │ (validate/deploy) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n *\n * ## References\n * - kernel/metadata-loader.zod.ts — Storage backend protocol\n * - kernel/metadata-customization.zod.ts — Overlay/merge protocol\n * - system/metadata-persistence.zod.ts — Database record format\n * - contracts/metadata-service.ts — Service interface\n */\n\n// ==========================================\n// Metadata Type Registry\n// ==========================================\n\n/**\n * Platform Metadata Type Enum\n *\n * The canonical list of all metadata types managed by the platform.\n * Each type maps to a specific Zod schema (e.g., ObjectSchema, ViewSchema).\n * Plugins can extend this registry via `contributes.kinds` in the manifest.\n *\n * ## Naming Convention\n * **IMPORTANT:** All metadata type names are in **SINGULAR** form:\n * - ✅ Use: `'agent'`, `'tool'`, `'skill'`, `'view'`, `'flow'`, `'action'`\n * - ❌ NOT: `'agents'`, `'tools'`, `'skills'`, `'views'`, `'flows'`, `'actions'`\n *\n * This convention applies to:\n * - Protocol definitions (this enum)\n * - UI plugin registrations (`metadataTypes`, `metadataIcons`)\n * - Metadata service operations\n * - File patterns (`*.agent.ts`, `*.tool.ts`)\n *\n * REST API endpoints continue to use plural forms per REST conventions:\n * - `/api/v1/ai/agents`, `/api/v1/ai/conversations`\n */\nexport const MetadataTypeSchema = z.enum([\n // Data Protocol\n 'object', // Business entity definition (ObjectSchema)\n 'field', // Standalone field definition (FieldSchema)\n 'trigger', // Data-layer event triggers (TriggerSchema)\n 'validation', // Validation rules (ValidationSchema)\n 'hook', // Data hooks (HookSchema)\n\n // UI Protocol\n 'view', // List/form views (ViewSchema)\n 'page', // Standalone pages (PageSchema)\n 'dashboard', // Dashboard layouts (DashboardSchema)\n 'app', // Application shell (AppSchema)\n 'action', // UI/Server actions (ActionSchema)\n 'report', // Report definitions (ReportSchema)\n\n // Automation Protocol\n 'flow', // Visual logic flows (FlowSchema)\n 'workflow', // State machines (WorkflowSchema)\n 'approval', // Approval processes (ApprovalSchema)\n\n // System Protocol\n 'datasource', // Data connections (DatasourceSchema)\n 'translation', // i18n resources (TranslationSchema)\n 'router', // API routes\n 'function', // Serverless functions\n 'service', // Service definitions\n\n // Security Protocol\n 'permission', // Permission sets (PermissionSetSchema)\n 'profile', // User profiles (ProfileSchema)\n 'role', // Security roles\n\n // AI Protocol\n 'agent', // AI agent definitions (AgentSchema)\n 'tool', // AI tool definitions (ToolSchema)\n 'skill', // AI skill definitions (SkillSchema)\n]);\n\nexport type MetadataType = z.infer;\n\n// ==========================================\n// Type Registry Entry\n// ==========================================\n\n/**\n * Metadata Type Registry Entry\n *\n * Describes a registered metadata type, including its validation schema,\n * file patterns, and capabilities. Used by the metadata plugin to:\n * 1. Discover metadata files on disk\n * 2. Validate metadata payloads\n * 3. Determine storage behavior\n */\nexport const MetadataTypeRegistryEntrySchema = z.object({\n /** Metadata type identifier (e.g., 'object', 'view') */\n type: MetadataTypeSchema.describe('Metadata type identifier'),\n\n /** Human-readable label */\n label: z.string().describe('Display label for the metadata type'),\n\n /** Brief description */\n description: z.string().optional().describe('Description of the metadata type'),\n\n /**\n * File glob patterns for this type.\n * Used to discover metadata files on disk.\n * @example [\"**\\/*.object.ts\", \"**\\/*.object.yml\"]\n */\n filePatterns: z.array(z.string()).describe('Glob patterns to discover files of this type'),\n\n /**\n * Whether this type supports the customization overlay system.\n * When true, platform/user overlays can be applied on top of package-delivered metadata.\n */\n supportsOverlay: z.boolean().default(true).describe('Whether overlay customization is supported'),\n\n /**\n * Whether metadata of this type can be created at runtime via API.\n * Some types (e.g., 'object') may be restricted to deployment-only.\n */\n allowRuntimeCreate: z.boolean().default(true).describe('Allow runtime creation via API'),\n\n /**\n * Whether this type supports versioning.\n * When true, changes are tracked with version history.\n */\n supportsVersioning: z.boolean().default(false).describe('Whether version history is tracked'),\n\n /**\n * Priority order for loading (lower = earlier).\n * Objects load before views, views before dashboards.\n */\n loadOrder: z.number().int().min(0).default(100).describe('Loading priority (lower = earlier)'),\n\n /** The domain this type belongs to */\n domain: z.enum(['data', 'ui', 'automation', 'system', 'security', 'ai'])\n .describe('Protocol domain'),\n});\n\nexport type MetadataTypeRegistryEntry = z.infer;\n\n// ==========================================\n// Metadata Query Protocol\n// ==========================================\n\n/**\n * Metadata Query Schema\n *\n * Standard protocol for searching and filtering metadata items.\n * Used by the metadata service to support advanced metadata discovery.\n */\nexport const MetadataQuerySchema = z.object({\n /** Filter by metadata type(s) */\n types: z.array(MetadataTypeSchema).optional().describe('Filter by metadata types'),\n\n /** Filter by namespace(s) */\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n\n /** Filter by package ID */\n packageId: z.string().optional().describe('Filter by owning package'),\n\n /** Full-text search across name, label, description */\n search: z.string().optional().describe('Full-text search query'),\n\n /** Filter by scope */\n scope: z.enum(['system', 'platform', 'user']).optional().describe('Filter by scope'),\n\n /** Filter by state */\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional().describe('Filter by lifecycle state'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Sort field */\n sortBy: z.enum(['name', 'type', 'updatedAt', 'createdAt']).default('name').describe('Sort field'),\n\n /** Sort direction */\n sortOrder: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n\n /** Pagination: page number (1-based) */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(500).default(50).describe('Items per page'),\n});\n\nexport type MetadataQuery = z.input;\n\n/**\n * Metadata Query Result\n */\nexport const MetadataQueryResultSchema = z.object({\n /** Matched items */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n namespace: z.string().optional().describe('Namespace'),\n label: z.string().optional().describe('Display label'),\n scope: z.enum(['system', 'platform', 'user']).optional(),\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional(),\n packageId: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n })).describe('Matched metadata items'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching items'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page'),\n\n /** Page size */\n pageSize: z.number().int().min(1).describe('Page size'),\n});\n\nexport type MetadataQueryResult = z.infer;\n\n// ==========================================\n// Metadata Lifecycle Events\n// ==========================================\n\n/**\n * Metadata Event Schema\n *\n * Events emitted by the metadata plugin when metadata changes.\n * Enables reactive patterns across the platform (cache invalidation,\n * UI refresh, dependency tracking, etc.).\n */\nexport const MetadataEventSchema = z.object({\n /** Event type */\n event: z.enum([\n 'metadata.registered',\n 'metadata.updated',\n 'metadata.unregistered',\n 'metadata.validated',\n 'metadata.deployed',\n 'metadata.overlay.applied',\n 'metadata.overlay.removed',\n 'metadata.imported',\n 'metadata.exported',\n ]).describe('Event type'),\n\n /** Metadata type */\n metadataType: MetadataTypeSchema.describe('Metadata type'),\n\n /** Item name */\n name: z.string().describe('Metadata item name'),\n\n /** Namespace */\n namespace: z.string().optional().describe('Namespace'),\n\n /** Package ID (if package-managed) */\n packageId: z.string().optional().describe('Owning package ID'),\n\n /** Timestamp */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /** Actor who caused the event */\n actor: z.string().optional().describe('User or system that triggered the event'),\n\n /** Additional event-specific payload */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event-specific payload'),\n});\n\nexport type MetadataEvent = z.infer;\n\n// ==========================================\n// Metadata Validation\n// ==========================================\n\n/**\n * Metadata Validation Result\n */\nexport const MetadataValidationResultSchema = z.object({\n /** Whether validation passed */\n valid: z.boolean().describe('Whether the metadata is valid'),\n\n /** Validation errors */\n errors: z.array(z.object({\n path: z.string().describe('JSON path to the invalid field'),\n message: z.string().describe('Error description'),\n code: z.string().optional().describe('Error code'),\n })).optional().describe('Validation errors'),\n\n /** Validation warnings (non-blocking) */\n warnings: z.array(z.object({\n path: z.string().describe('JSON path to the field'),\n message: z.string().describe('Warning description'),\n })).optional().describe('Validation warnings'),\n});\n\nexport type MetadataValidationResult = z.infer;\n\n// ==========================================\n// Metadata Plugin Configuration\n// ==========================================\n\n/**\n * Metadata Plugin Configuration\n *\n * The unified configuration for the metadata plugin, combining\n * storage, caching, customization, and type registry settings.\n */\nexport const MetadataPluginConfigSchema = z.object({\n /**\n * Storage configuration.\n * References MetadataManagerConfigSchema for the underlying storage backend.\n */\n storage: MetadataManagerConfigSchema.describe('Storage backend configuration'),\n\n /**\n * Default customization policies per metadata type.\n * Controls what parts of metadata can be customized by admins/users.\n */\n customizationPolicies: z.array(CustomizationPolicySchema).optional()\n .describe('Default customization policies per type'),\n\n /**\n * Merge strategy for package upgrades.\n */\n mergeStrategy: MergeStrategyConfigSchema.optional()\n .describe('Merge strategy for package upgrades'),\n\n /**\n * Additional metadata type registrations.\n * Used by plugins to register custom metadata types beyond the built-in set.\n */\n additionalTypes: z.array(MetadataTypeRegistryEntrySchema.omit({ type: true }).extend({\n type: z.string().describe('Custom metadata type identifier'),\n })).optional().describe('Additional custom metadata types'),\n\n /**\n * Enable metadata change events.\n * When true, the plugin emits events on every metadata change.\n */\n enableEvents: z.boolean().default(true).describe('Emit metadata change events'),\n\n /**\n * Enable metadata validation on write operations.\n * When true, all metadata is validated against its type schema before saving.\n */\n validateOnWrite: z.boolean().default(true).describe('Validate metadata on write'),\n\n /**\n * Enable metadata versioning.\n * When true, changes to metadata are tracked with version history.\n */\n enableVersioning: z.boolean().default(false).describe('Track metadata version history'),\n\n /**\n * Maximum number of metadata items to keep in memory cache.\n */\n cacheMaxItems: z.number().int().min(0).default(10000).describe('Max items in memory cache'),\n});\n\nexport type MetadataPluginConfig = z.input;\n\n// ==========================================\n// Metadata Plugin Manifest\n// ==========================================\n\n/**\n * Metadata Plugin Manifest\n *\n * The complete manifest for the Metadata Plugin, declaring its identity,\n * capabilities, and configuration. This is the \"contract\" between the\n * metadata plugin and the kernel.\n */\nexport const MetadataPluginManifestSchema = z.object({\n /** Plugin identifier */\n id: z.literal('com.objectstack.metadata').describe('Metadata plugin ID'),\n\n /** Plugin name */\n name: z.literal('ObjectStack Metadata Service').describe('Plugin name'),\n\n /** Plugin version */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Plugin version'),\n\n /** Plugin type */\n type: z.literal('standard').describe('Plugin type'),\n\n /** Plugin description */\n description: z.string().default('Core metadata management service for ObjectStack platform')\n .describe('Plugin description'),\n\n /**\n * Capabilities this plugin provides.\n * The kernel uses this to route metadata requests to this plugin.\n */\n capabilities: z.object({\n /** Supports CRUD operations on metadata */\n crud: z.boolean().default(true).describe('Supports metadata CRUD'),\n\n /** Supports metadata query/search */\n query: z.boolean().default(true).describe('Supports metadata query'),\n\n /** Supports the overlay/customization system */\n overlay: z.boolean().default(true).describe('Supports customization overlays'),\n\n /** Supports file watching for hot reload */\n watch: z.boolean().default(false).describe('Supports file watching'),\n\n /** Supports bulk import/export */\n importExport: z.boolean().default(true).describe('Supports import/export'),\n\n /** Supports metadata validation */\n validation: z.boolean().default(true).describe('Supports schema validation'),\n\n /** Supports metadata versioning */\n versioning: z.boolean().default(false).describe('Supports version history'),\n\n /** Supports metadata events */\n events: z.boolean().default(true).describe('Emits metadata events'),\n }).describe('Plugin capabilities'),\n\n /** Plugin configuration */\n config: MetadataPluginConfigSchema.optional().describe('Plugin configuration'),\n});\n\nexport type MetadataPluginManifest = z.input;\n\n// ==========================================\n// Built-in Type Registry Defaults\n// ==========================================\n\n/**\n * Default Type Registry\n *\n * The built-in metadata type registry with default configurations.\n * Plugins extend this via `contributes.kinds` in the manifest.\n */\nexport const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntry[] = [\n // Data Protocol (load first)\n { type: 'object', label: 'Object', filePatterns: ['**/*.object.ts', '**/*.object.yml', '**/*.object.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 10, domain: 'data' },\n { type: 'field', label: 'Field', filePatterns: ['**/*.field.ts', '**/*.field.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 20, domain: 'data' },\n { type: 'trigger', label: 'Trigger', filePatterns: ['**/*.trigger.ts', '**/*.trigger.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'validation', label: 'Validation Rule', filePatterns: ['**/*.validation.ts', '**/*.validation.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'hook', label: 'Hook', filePatterns: ['**/*.hook.ts', '**/*.hook.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n\n // UI Protocol\n { type: 'view', label: 'View', filePatterns: ['**/*.view.ts', '**/*.view.yml', '**/*.view.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'page', label: 'Page', filePatterns: ['**/*.page.ts', '**/*.page.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'dashboard', label: 'Dashboard', filePatterns: ['**/*.dashboard.ts', '**/*.dashboard.yml', '**/*.dashboard.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n { type: 'app', label: 'Application', filePatterns: ['**/*.app.ts', '**/*.app.yml', '**/*.app.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 70, domain: 'ui' },\n { type: 'action', label: 'Action', filePatterns: ['**/*.action.ts', '**/*.action.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'report', label: 'Report', filePatterns: ['**/*.report.ts', '**/*.report.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n\n // Automation Protocol\n { type: 'flow', label: 'Flow', filePatterns: ['**/*.flow.ts', '**/*.flow.yml', '**/*.flow.json'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'workflow', label: 'Workflow', filePatterns: ['**/*.workflow.ts', '**/*.workflow.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'approval', label: 'Approval Process', filePatterns: ['**/*.approval.ts', '**/*.approval.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 80, domain: 'automation' },\n\n // System Protocol\n { type: 'datasource', label: 'Datasource', filePatterns: ['**/*.datasource.ts', '**/*.datasource.yml'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 5, domain: 'system' },\n { type: 'translation', label: 'Translation', filePatterns: ['**/*.translation.ts', '**/*.translation.yml', '**/*.translation.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 90, domain: 'system' },\n { type: 'router', label: 'Router', filePatterns: ['**/*.router.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'function', label: 'Function', filePatterns: ['**/*.function.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'service', label: 'Service', filePatterns: ['**/*.service.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n\n // Security Protocol\n { type: 'permission', label: 'Permission Set', filePatterns: ['**/*.permission.ts', '**/*.permission.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 15, domain: 'security' },\n { type: 'profile', label: 'Profile', filePatterns: ['**/*.profile.ts', '**/*.profile.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n { type: 'role', label: 'Role', filePatterns: ['**/*.role.ts', '**/*.role.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n\n // AI Protocol\n { type: 'agent', label: 'AI Agent', filePatterns: ['**/*.agent.ts', '**/*.agent.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 90, domain: 'ai' },\n { type: 'tool', label: 'AI Tool', filePatterns: ['**/*.tool.ts', '**/*.tool.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 85, domain: 'ai' },\n { type: 'skill', label: 'AI Skill', filePatterns: ['**/*.skill.ts', '**/*.skill.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 88, domain: 'ai' },\n];\n\n// ==========================================\n// Bulk Operation Types\n// ==========================================\n\n/**\n * Bulk Register Request\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n /** Items to register */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Namespace'),\n })).min(1).describe('Items to register'),\n\n /** Continue on individual item failure */\n continueOnError: z.boolean().default(false).describe('Continue if individual item fails'),\n\n /** Validate items before registering */\n validate: z.boolean().default(true).describe('Validate before register'),\n});\n\nexport type MetadataBulkRegisterRequest = z.input;\n\n/**\n * Bulk Operation Result\n */\nexport const MetadataBulkResultSchema = z.object({\n /** Total items processed */\n total: z.number().int().min(0).describe('Total items processed'),\n\n /** Successfully processed items */\n succeeded: z.number().int().min(0).describe('Successfully processed'),\n\n /** Failed items */\n failed: z.number().int().min(0).describe('Failed items'),\n\n /** Per-item error details */\n errors: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n error: z.string().describe('Error message'),\n })).optional().describe('Per-item errors'),\n});\n\nexport type MetadataBulkResult = z.infer;\n\n// ==========================================\n// Metadata Dependency\n// ==========================================\n\n/**\n * Metadata Dependency Schema\n *\n * Tracks dependencies between metadata items.\n * Used for impact analysis and safe deletion checks.\n */\nexport const MetadataDependencySchema = z.object({\n /** Source metadata type */\n sourceType: z.string().describe('Dependent metadata type'),\n\n /** Source metadata name */\n sourceName: z.string().describe('Dependent metadata name'),\n\n /** Target metadata type */\n targetType: z.string().describe('Referenced metadata type'),\n\n /** Target metadata name */\n targetName: z.string().describe('Referenced metadata name'),\n\n /** Dependency kind */\n kind: z.enum(['reference', 'extends', 'includes', 'triggers'])\n .describe('How the dependency is formed'),\n});\n\nexport type MetadataDependency = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\nimport { DependencyResolutionResultSchema } from './dependency-resolution.zod';\n\n/**\n * # Package Registry Protocol\n * \n * Defines the runtime state and lifecycle operations for installed packages.\n * \n * ## Key Distinction: Package vs App\n * - **Package (Manifest)**: The unit of installation — a deployable artifact containing\n * metadata (objects, actions, flows, etc.) and optionally one or more Apps.\n * - **App (AppSchema)**: A UI navigation shell defined inside a package.\n * \n * A package may contain:\n * - Zero apps (pure functionality plugin, e.g. a storage driver)\n * - One app (typical business application)\n * - Multiple apps (suite of applications)\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Packages with install/uninstall lifecycle\n * - **VS Code**: Extension marketplace with enable/disable per-workspace\n * - **Kubernetes**: Helm charts with release state tracking\n * - **npm**: Package registry with install/uninstall/version management\n */\n\n// ==========================================\n// Package Status & Lifecycle\n// ==========================================\n\n/**\n * Package installation status.\n */\nexport const PackageStatusEnum = z.enum([\n 'installed', // Successfully installed and enabled\n 'disabled', // Installed but disabled (metadata not active)\n 'installing', // Installation in progress\n 'upgrading', // Upgrade in progress\n 'uninstalling', // Removal in progress\n 'error', // Installation or runtime error\n]).describe('Package installation status');\nexport type PackageStatus = z.infer;\n\n/**\n * Installed Package Schema\n * \n * Wraps a ManifestSchema with runtime lifecycle state.\n * This is the \"row\" in the installed packages table.\n */\nexport const InstalledPackageSchema = z.object({\n /** \n * The full package manifest (source of truth for package definition).\n */\n manifest: ManifestSchema.describe('Full package manifest'),\n\n /**\n * Current lifecycle status.\n */\n status: PackageStatusEnum.default('installed')\n .describe('Package state: installed, disabled, installing, upgrading, uninstalling, or error'),\n\n /**\n * Whether the package is currently enabled (active).\n * When disabled, the package's metadata is not loaded into the registry.\n */\n enabled: z.boolean().default(true)\n .describe('Whether the package is currently enabled'),\n\n /**\n * ISO 8601 timestamp of when the package was installed.\n */\n installedAt: z.string().datetime().optional()\n .describe('Installation timestamp'),\n\n /**\n * ISO 8601 timestamp of last update.\n */\n updatedAt: z.string().datetime().optional()\n .describe('Last update timestamp'),\n\n /**\n * The currently installed version string.\n * Mirrors manifest.version for quick access without parsing the full manifest.\n */\n installedVersion: z.string().optional()\n .describe('Currently installed version for quick access'),\n\n /**\n * The previously installed version (before last upgrade).\n * Useful for rollback and upgrade tracking.\n */\n previousVersion: z.string().optional()\n .describe('Version before the last upgrade'),\n\n /**\n * ISO 8601 timestamp of when the package was last enabled/disabled.\n */\n statusChangedAt: z.string().datetime().optional()\n .describe('Status change timestamp'),\n\n /**\n * Error message if status is 'error'.\n */\n errorMessage: z.string().optional()\n .describe('Error message when status is error'),\n\n /**\n * Configuration values set by the user for this package.\n * Keys correspond to the package's `configuration.properties`.\n */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided configuration settings'),\n\n /**\n * Upgrade history for this package.\n * Records each version migration with status and optional log.\n */\n upgradeHistory: z.array(z.object({\n /** Previous version before upgrade */\n fromVersion: z.string().describe('Version before upgrade'),\n /** New version after upgrade */\n toVersion: z.string().describe('Version after upgrade'),\n /** Timestamp of the upgrade */\n upgradedAt: z.string().datetime().describe('Upgrade timestamp'),\n /** Outcome of the upgrade */\n status: z.enum(['success', 'failed', 'rolled_back']).describe('Upgrade outcome'),\n /** Migration log entries */\n migrationLog: z.array(z.string()).optional().describe('Migration step logs'),\n })).optional().describe('Version upgrade history'),\n\n /**\n * Namespaces registered by this package.\n * Tracks which namespace prefixes are occupied by this package.\n */\n registeredNamespaces: z.array(z.string()).optional()\n .describe('Namespace prefixes registered by this package'),\n}).describe('Installed package with runtime lifecycle state');\nexport type InstalledPackage = z.infer;\n\n// ==========================================\n// Namespace Registry\n// ==========================================\n\n/**\n * Namespace Registry Entry\n * Tracks namespace ownership within the platform instance.\n */\nexport const NamespaceRegistryEntrySchema = z.object({\n /** Namespace prefix */\n namespace: z.string().describe('Namespace prefix'),\n\n /** Package that owns this namespace */\n packageId: z.string().describe('Owning package ID'),\n\n /** Registration timestamp */\n registeredAt: z.string().datetime().describe('Registration timestamp'),\n\n /** Namespace status */\n status: z.enum(['active', 'disabled', 'reserved'])\n .describe('Namespace status'),\n}).describe('Namespace ownership entry in the registry');\n\nexport type NamespaceRegistryEntry = z.infer;\n\n/**\n * Namespace Conflict Error\n * Describes a namespace collision detected during package installation.\n */\nexport const NamespaceConflictErrorSchema = z.object({\n /** Error type discriminator */\n type: z.literal('namespace_conflict').describe('Error type'),\n\n /** Namespace that was requested */\n requestedNamespace: z.string().describe('Requested namespace'),\n\n /** ID of the package that already owns the namespace */\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n\n /** Name of the conflicting package */\n conflictingPackageName: z.string().describe('Conflicting package display name'),\n\n /** Suggested alternative namespace */\n suggestion: z.string().optional()\n .describe('Suggested alternative namespace'),\n}).describe('Namespace collision error during installation');\n\nexport type NamespaceConflictError = z.infer;\n\n// ==========================================\n// Package Registry Request/Response Schemas\n// ==========================================\n\n/**\n * List Packages Request\n */\nexport const ListPackagesRequestSchema = z.object({\n /** Filter by status */\n status: PackageStatusEnum.optional().describe('Filter by package status'),\n /** Filter by package type */\n type: ManifestSchema.shape.type.optional().describe('Filter by package type'),\n /** Filter by enabled state */\n enabled: z.boolean().optional().describe('Filter by enabled state'),\n}).describe('List packages request');\nexport type ListPackagesRequest = z.infer;\n\n/**\n * List Packages Response\n */\nexport const ListPackagesResponseSchema = z.object({\n packages: z.array(InstalledPackageSchema).describe('List of installed packages'),\n total: z.number().describe('Total package count'),\n}).describe('List packages response');\nexport type ListPackagesResponse = z.infer;\n\n/**\n * Get Package Request\n */\nexport const GetPackageRequestSchema = z.object({\n /** Package ID (reverse domain identifier from manifest) */\n id: z.string().describe('Package identifier'),\n}).describe('Get package request');\nexport type GetPackageRequest = z.infer;\n\n/**\n * Get Package Response\n */\nexport const GetPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Package details'),\n}).describe('Get package response');\nexport type GetPackageResponse = z.infer;\n\n/**\n * Install Package Request\n * \n * Accepts a full manifest to install. In a production system,\n * this might also accept a package ID to fetch from a marketplace.\n */\nexport const InstallPackageRequestSchema = z.object({\n /** The package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n /** Optional: user-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n /** Whether to enable immediately after install (default: true) */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n /**\n * Current platform version for compatibility checking.\n * When provided, the system compares this against the package's\n * `engine.objectstack` requirement to verify compatibility.\n */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n}).describe('Install package request');\nexport type InstallPackageRequest = z.infer;\n\n/**\n * Install Package Response\n */\nexport const InstallPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n message: z.string().optional().describe('Installation status message'),\n /** Dependency resolution result (when dependencies were analyzed) */\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result from install analysis'),\n}).describe('Install package response');\nexport type InstallPackageResponse = z.infer;\n\n/**\n * Uninstall Package Request\n */\nexport const UninstallPackageRequestSchema = z.object({\n /** Package ID to uninstall */\n id: z.string().describe('Package ID to uninstall'),\n}).describe('Uninstall package request');\nexport type UninstallPackageRequest = z.infer;\n\n/**\n * Uninstall Package Response\n */\nexport const UninstallPackageResponseSchema = z.object({\n id: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n}).describe('Uninstall package response');\nexport type UninstallPackageResponse = z.infer;\n\n/**\n * Enable Package Request\n */\nexport const EnablePackageRequestSchema = z.object({\n /** Package ID to enable */\n id: z.string().describe('Package ID to enable'),\n}).describe('Enable package request');\nexport type EnablePackageRequest = z.infer;\n\n/**\n * Enable Package Response\n */\nexport const EnablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Enabled package details'),\n message: z.string().optional().describe('Enable status message'),\n}).describe('Enable package response');\nexport type EnablePackageResponse = z.infer;\n\n/**\n * Disable Package Request\n */\nexport const DisablePackageRequestSchema = z.object({\n /** Package ID to disable */\n id: z.string().describe('Package ID to disable'),\n}).describe('Disable package request');\nexport type DisablePackageRequest = z.infer;\n\n/**\n * Disable Package Response\n */\nexport const DisablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Disabled package details'),\n message: z.string().optional().describe('Disable status message'),\n}).describe('Disable package response');\nexport type DisablePackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\n\n/**\n * # Package Upgrade Protocol\n * \n * Defines the complete lifecycle for upgrading installed packages,\n * including pre-upgrade analysis, snapshot/backup, execution, validation,\n * and rollback capabilities.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Package upgrade with push upgrades and subscriber control\n * - **ServiceNow**: Update Sets with preview, commit, and back-out support\n * - **Helm**: Helm upgrade with rollback to previous release\n * - **Kubernetes**: Rolling update with readiness probes and automatic rollback\n * \n * ## Upgrade Flow\n * ```\n * 1. PreCheck → Validate compatibility, check dependencies\n * 2. Plan → Generate upgrade plan with metadata diff\n * 3. Snapshot → Backup current state (metadata + customizations)\n * 4. Execute → Apply new package metadata with 3-way merge\n * 5. Validate → Run post-upgrade health checks\n * 6. Commit → Finalize upgrade (or Rollback on failure)\n * ```\n */\n\n// ==========================================\n// Upgrade Plan & Analysis\n// ==========================================\n\n/**\n * Metadata Change Type\n * Type of change detected between package versions.\n */\nexport const MetadataChangeTypeSchema = z.enum([\n 'added', // New metadata item added in new version\n 'modified', // Existing metadata item modified\n 'removed', // Metadata item removed in new version\n 'renamed', // Metadata item renamed\n]).describe('Type of metadata change between package versions');\n\n/**\n * Metadata Diff Item\n * Describes a single metadata change between two package versions.\n */\nexport const MetadataDiffItemSchema = z.object({\n /** Metadata type (e.g. \"object\", \"view\", \"flow\") */\n type: z.string().describe('Metadata type'),\n\n /** Metadata name */\n name: z.string().describe('Metadata name'),\n\n /** Type of change */\n changeType: MetadataChangeTypeSchema.describe('Category of metadata modification (added, modified, removed, or renamed)'),\n\n /** Whether this change has potential conflicts with customizations */\n hasConflict: z.boolean().default(false)\n .describe('Whether this change may conflict with customizations'),\n\n /** Human-readable summary of the change */\n summary: z.string().optional().describe('Human-readable change summary'),\n\n /** Previous name (for renames) */\n previousName: z.string().optional().describe('Previous name if renamed'),\n}).describe('Single metadata change between package versions');\n\n/**\n * Upgrade Impact Level\n * Indicates the severity of impact the upgrade will have.\n */\nexport const UpgradeImpactLevelSchema = z.enum([\n 'none', // No impact, seamless upgrade\n 'low', // Minor changes, no user action needed\n 'medium', // Some changes that may affect workflows\n 'high', // Significant changes, user review recommended\n 'critical', // Breaking changes, manual intervention required\n]).describe('Severity of upgrade impact');\n\n/**\n * Upgrade Plan Schema\n * The analysis result before executing an upgrade.\n * Generated by comparing old version metadata with new version metadata.\n */\nexport const UpgradePlanSchema = z.object({\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Current installed version */\n fromVersion: z.string().describe('Currently installed version'),\n\n /** Target version to upgrade to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Overall impact level */\n impactLevel: UpgradeImpactLevelSchema.describe('Severity assessment from none (seamless) to critical (breaking changes)'),\n\n /** List of all metadata changes between versions */\n changes: z.array(MetadataDiffItemSchema).describe('All metadata changes'),\n\n /** Number of customer customizations that may be affected */\n affectedCustomizations: z.number().int().min(0).default(0)\n .describe('Count of customizations that may be affected'),\n\n /** Whether any migration scripts need to run */\n requiresMigration: z.boolean().default(false)\n .describe('Whether data migration scripts are needed'),\n\n /** Migration script paths (relative to package root) */\n migrationScripts: z.array(z.string()).optional()\n .describe('Paths to migration scripts'),\n\n /** Dependencies that also need upgrading */\n dependencyUpgrades: z.array(z.object({\n packageId: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n })).optional().describe('Dependent packages that also need upgrading'),\n\n /** Estimated upgrade duration in seconds */\n estimatedDuration: z.number().int().min(0).optional()\n .describe('Estimated upgrade duration in seconds'),\n\n /** Human-readable summary */\n summary: z.string().optional().describe('Human-readable upgrade summary'),\n}).describe('Upgrade analysis plan generated before execution');\n\n// ==========================================\n// Upgrade Snapshot (Pre-Upgrade Backup)\n// ==========================================\n\n/**\n * Upgrade Snapshot Schema\n * Captures the complete state before an upgrade for rollback capability.\n */\nexport const UpgradeSnapshotSchema = z.object({\n /** Snapshot ID (UUID) */\n id: z.string().describe('Snapshot identifier'),\n\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being upgraded from */\n fromVersion: z.string().describe('Version before upgrade'),\n\n /** Version being upgraded to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Complete manifest of the old package version */\n previousManifest: ManifestSchema.describe('Complete manifest of the previous package version'),\n\n /**\n * Snapshot of all metadata records owned by this package.\n * Stored as array of { type, name, metadata } tuples.\n */\n metadataSnapshot: z.array(z.object({\n type: z.string(),\n name: z.string(),\n metadata: z.record(z.string(), z.unknown()),\n })).describe('Snapshot of all package metadata'),\n\n /**\n * Snapshot of all customer customizations (overlays) for this package's metadata.\n */\n customizationSnapshot: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Snapshot of customer customizations'),\n\n /** When the snapshot was created */\n createdAt: z.string().datetime().describe('Snapshot creation timestamp'),\n\n /** Expiry time for snapshot cleanup */\n expiresAt: z.string().datetime().optional().describe('Snapshot expiry timestamp'),\n}).describe('Pre-upgrade state snapshot for rollback capability');\n\n// ==========================================\n// Upgrade Request/Response\n// ==========================================\n\n/**\n * Upgrade Package Request\n */\nexport const UpgradePackageRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (if omitted, upgrades to latest) */\n targetVersion: z.string().optional().describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional().describe('New manifest (if installing from local)'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum([\n 'keep-custom',\n 'accept-incoming',\n 'three-way-merge',\n ]).default('three-way-merge').describe('How to handle customer customizations'),\n\n /** Whether to run in dry-run mode (preview only, no changes) */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Whether to skip pre-upgrade validation */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\n\n/**\n * Upgrade Phase\n * Current phase of the upgrade process.\n */\nexport const UpgradePhaseSchema = z.enum([\n 'pending', // Upgrade requested but not started\n 'analyzing', // Generating upgrade plan\n 'snapshot', // Creating pre-upgrade snapshot\n 'executing', // Applying metadata changes\n 'migrating', // Running migration scripts\n 'validating', // Post-upgrade validation\n 'completed', // Upgrade completed successfully\n 'failed', // Upgrade failed\n 'rolling-back', // Rollback in progress\n 'rolled-back', // Rollback completed\n]).describe('Current phase of the upgrade process');\n\n/**\n * Upgrade Package Response\n */\nexport const UpgradePackageResponseSchema = z.object({\n /** Whether the upgrade was successful */\n success: z.boolean().describe('Whether the upgrade succeeded'),\n\n /** Current upgrade phase */\n phase: UpgradePhaseSchema.describe('Current upgrade phase'),\n\n /** The upgrade plan that was executed */\n plan: UpgradePlanSchema.optional().describe('Upgrade plan'),\n\n /** Snapshot ID for rollback */\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n\n /** Merge conflicts that need manual resolution (if any) */\n conflicts: z.array(z.object({\n path: z.string(),\n baseValue: z.unknown(),\n incomingValue: z.unknown(),\n customValue: z.unknown(),\n })).optional().describe('Unresolved merge conflicts'),\n\n /** Error message (if failed) */\n errorMessage: z.string().optional().describe('Error message if upgrade failed'),\n\n /** Human-readable summary */\n message: z.string().optional().describe('Human-readable status message'),\n}).describe('Upgrade package response');\n\n// ==========================================\n// Rollback\n// ==========================================\n\n/**\n * Rollback Package Request\n */\nexport const RollbackPackageRequestSchema = z.object({\n /** Package ID to rollback */\n packageId: z.string().describe('Package ID to rollback'),\n\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\n\n/**\n * Rollback Package Response\n */\nexport const RollbackPackageResponseSchema = z.object({\n /** Whether the rollback was successful */\n success: z.boolean().describe('Whether the rollback succeeded'),\n\n /** Restored version */\n restoredVersion: z.string().optional().describe('Version restored to'),\n\n /** Message */\n message: z.string().optional().describe('Rollback status message'),\n}).describe('Rollback package response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type MetadataChangeType = z.infer;\nexport type MetadataDiffItem = z.infer;\nexport type UpgradeImpactLevel = z.infer;\nexport type UpgradePlan = z.infer;\nexport type UpgradeSnapshot = z.infer;\nexport type UpgradePackageRequest = z.infer;\nexport type UpgradePhase = z.infer;\nexport type UpgradePackageResponse = z.infer;\nexport type RollbackPackageRequest = z.infer;\nexport type RollbackPackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Advanced Plugin Lifecycle Protocol\n * \n * Defines advanced lifecycle management capabilities including:\n * - Hot reload and live updates\n * - Graceful degradation and fallback mechanisms\n * - Health monitoring and auto-recovery\n * - State preservation during updates\n * \n * This protocol extends the basic plugin lifecycle with enterprise-grade\n * features for production environments.\n */\n\n/**\n * Plugin Health Status\n * Represents the current operational state of a plugin\n */\nexport const PluginHealthStatusSchema = z.enum([\n 'healthy', // Plugin is operating normally\n 'degraded', // Plugin is operational but with reduced functionality\n 'unhealthy', // Plugin has critical issues but still running\n 'failed', // Plugin has failed and is not operational\n 'recovering', // Plugin is in recovery process\n 'unknown', // Health status cannot be determined\n]).describe('Current health status of the plugin');\n\n/**\n * Plugin Health Check Configuration\n * Defines how to check plugin health\n */\nexport const PluginHealthCheckSchema = z.object({\n /**\n * Health check interval in milliseconds\n */\n interval: z.number().int().min(1000).default(30000)\n .describe('How often to perform health checks (default: 30s)'),\n \n /**\n * Timeout for health check in milliseconds\n */\n timeout: z.number().int().min(100).default(5000)\n .describe('Maximum time to wait for health check response'),\n \n /**\n * Number of consecutive failures before marking as unhealthy\n */\n failureThreshold: z.number().int().min(1).default(3)\n .describe('Consecutive failures needed to mark unhealthy'),\n \n /**\n * Number of consecutive successes to recover from unhealthy state\n */\n successThreshold: z.number().int().min(1).default(1)\n .describe('Consecutive successes needed to mark healthy'),\n \n /**\n * Custom health check function name or endpoint\n */\n checkMethod: z.string().optional()\n .describe('Method name to call for health check'),\n \n /**\n * Enable automatic restart on failure\n */\n autoRestart: z.boolean().default(false)\n .describe('Automatically restart plugin on health check failure'),\n \n /**\n * Maximum number of restart attempts\n */\n maxRestartAttempts: z.number().int().min(0).default(3)\n .describe('Maximum restart attempts before giving up'),\n \n /**\n * Backoff strategy for restarts\n */\n restartBackoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy for restart delays'),\n});\n\n/**\n * Plugin Health Report\n * Detailed health information from a plugin\n */\nexport const PluginHealthReportSchema = z.object({\n /**\n * Overall health status\n */\n status: PluginHealthStatusSchema,\n \n /**\n * Timestamp of the health check\n */\n timestamp: z.string().datetime(),\n \n /**\n * Human-readable message about health status\n */\n message: z.string().optional(),\n \n /**\n * Detailed metrics\n */\n metrics: z.object({\n uptime: z.number().describe('Plugin uptime in milliseconds'),\n memoryUsage: z.number().optional().describe('Memory usage in bytes'),\n cpuUsage: z.number().optional().describe('CPU usage percentage'),\n activeConnections: z.number().optional().describe('Number of active connections'),\n errorRate: z.number().optional().describe('Error rate (errors per minute)'),\n responseTime: z.number().optional().describe('Average response time in ms'),\n }).partial().optional(),\n \n /**\n * List of checks performed\n */\n checks: z.array(z.object({\n name: z.string().describe('Check name'),\n status: z.enum(['passed', 'failed', 'warning']),\n message: z.string().optional(),\n data: z.record(z.string(), z.unknown()).optional(),\n })).optional(),\n \n /**\n * Dependencies health\n */\n dependencies: z.array(z.object({\n pluginId: z.string(),\n status: PluginHealthStatusSchema,\n message: z.string().optional(),\n })).optional(),\n});\n\n/**\n * Distributed State Configuration\n * Configuration for distributed state management in cluster environments\n */\nexport const DistributedStateConfigSchema = z.object({\n /**\n * Distributed cache provider\n */\n provider: z.enum(['redis', 'etcd', 'custom'])\n .describe('Distributed state backend provider'),\n \n /**\n * Connection URL or endpoints\n */\n endpoints: z.array(z.string()).optional()\n .describe('Backend connection endpoints'),\n \n /**\n * Key prefix for namespacing\n */\n keyPrefix: z.string().optional()\n .describe('Prefix for all keys (e.g., \"plugin:my-plugin:\")'),\n \n /**\n * Time to live in seconds\n */\n ttl: z.number().int().min(0).optional()\n .describe('State expiration time in seconds'),\n \n /**\n * Authentication configuration\n */\n auth: z.object({\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n certificate: z.string().optional(),\n }).optional(),\n \n /**\n * Replication settings\n */\n replication: z.object({\n enabled: z.boolean().default(true),\n minReplicas: z.number().int().min(1).default(1),\n }).optional(),\n \n /**\n * Custom provider configuration\n */\n customConfig: z.record(z.string(), z.unknown()).optional()\n .describe('Provider-specific configuration'),\n});\n\n/**\n * Hot Reload Configuration\n * Controls how plugins handle live updates\n */\nexport const HotReloadConfigSchema = z.object({\n /**\n * Enable hot reload capability\n */\n enabled: z.boolean().default(false),\n \n /**\n * Watch file patterns for auto-reload\n */\n watchPatterns: z.array(z.string()).optional()\n .describe('Glob patterns to watch for changes'),\n \n /**\n * Debounce delay before reloading (milliseconds)\n */\n debounceDelay: z.number().int().min(0).default(1000)\n .describe('Wait time after change detection before reload'),\n \n /**\n * Preserve plugin state during reload\n */\n preserveState: z.boolean().default(true)\n .describe('Keep plugin state across reloads'),\n \n /**\n * State serialization strategy\n */\n stateStrategy: z.enum(['memory', 'disk', 'distributed', 'none']).default('memory')\n .describe('How to preserve state during reload'),\n \n /**\n * Distributed state configuration (required when stateStrategy is \"distributed\")\n */\n distributedConfig: DistributedStateConfigSchema.optional()\n .describe('Configuration for distributed state management'),\n \n /**\n * Graceful shutdown timeout\n */\n shutdownTimeout: z.number().int().min(0).default(30000)\n .describe('Maximum time to wait for graceful shutdown'),\n \n /**\n * Pre-reload hooks\n */\n beforeReload: z.array(z.string()).optional()\n .describe('Hook names to call before reload'),\n \n /**\n * Post-reload hooks\n */\n afterReload: z.array(z.string()).optional()\n .describe('Hook names to call after reload'),\n});\n\n/**\n * Graceful Degradation Configuration\n * Defines how plugin degrades when dependencies fail\n */\nexport const GracefulDegradationSchema = z.object({\n /**\n * Enable graceful degradation\n */\n enabled: z.boolean().default(true),\n \n /**\n * Fallback mode when dependencies fail\n */\n fallbackMode: z.enum([\n 'minimal', // Provide minimal functionality\n 'cached', // Use cached data\n 'readonly', // Allow read-only operations\n 'offline', // Offline mode with local data\n 'disabled', // Disable plugin functionality\n ]).default('minimal'),\n \n /**\n * Critical dependencies that must be available\n */\n criticalDependencies: z.array(z.string()).optional()\n .describe('Plugin IDs that are required for operation'),\n \n /**\n * Optional dependencies that can fail\n */\n optionalDependencies: z.array(z.string()).optional()\n .describe('Plugin IDs that are nice to have but not required'),\n \n /**\n * Feature flags for degraded mode\n */\n degradedFeatures: z.array(z.object({\n feature: z.string().describe('Feature name'),\n enabled: z.boolean().describe('Whether feature is available in degraded mode'),\n reason: z.string().optional(),\n })).optional(),\n \n /**\n * Automatic recovery attempts\n */\n autoRecovery: z.object({\n enabled: z.boolean().default(true),\n retryInterval: z.number().int().min(1000).default(60000)\n .describe('Interval between recovery attempts (ms)'),\n maxAttempts: z.number().int().min(0).default(5)\n .describe('Maximum recovery attempts before giving up'),\n }).optional(),\n});\n\n/**\n * Plugin Update Strategy\n * Defines how plugin handles version updates\n */\nexport const PluginUpdateStrategySchema = z.object({\n /**\n * Update mode\n */\n mode: z.enum([\n 'manual', // Manual updates only\n 'automatic', // Automatic updates\n 'scheduled', // Scheduled update windows\n 'rolling', // Rolling updates with zero downtime\n ]).default('manual'),\n \n /**\n * Version constraints for automatic updates\n */\n autoUpdateConstraints: z.object({\n major: z.boolean().default(false).describe('Allow major version updates'),\n minor: z.boolean().default(true).describe('Allow minor version updates'),\n patch: z.boolean().default(true).describe('Allow patch version updates'),\n }).optional(),\n \n /**\n * Update schedule (for scheduled mode)\n */\n schedule: z.object({\n /**\n * Cron expression for update window\n */\n cron: z.string().optional(),\n \n /**\n * Timezone for schedule\n */\n timezone: z.string().default('UTC'),\n \n /**\n * Maintenance window duration in minutes\n */\n maintenanceWindow: z.number().int().min(1).default(60),\n }).optional(),\n \n /**\n * Rollback configuration\n */\n rollback: z.object({\n enabled: z.boolean().default(true),\n \n /**\n * Automatic rollback on failure\n */\n automatic: z.boolean().default(true),\n \n /**\n * Keep N previous versions for rollback\n */\n keepVersions: z.number().int().min(1).default(3),\n \n /**\n * Rollback timeout in milliseconds\n */\n timeout: z.number().int().min(1000).default(30000),\n }).optional(),\n \n /**\n * Pre-update validation\n */\n validation: z.object({\n /**\n * Run compatibility checks before update\n */\n checkCompatibility: z.boolean().default(true),\n \n /**\n * Run tests before applying update\n */\n runTests: z.boolean().default(false),\n \n /**\n * Test suite to run\n */\n testSuite: z.string().optional(),\n }).optional(),\n});\n\n/**\n * Plugin State Snapshot\n * Captures plugin state for preservation during updates/reloads\n */\nexport const PluginStateSnapshotSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Version at time of snapshot\n */\n version: z.string(),\n \n /**\n * Snapshot timestamp\n */\n timestamp: z.string().datetime(),\n \n /**\n * Serialized state data\n */\n state: z.record(z.string(), z.unknown()),\n \n /**\n * State metadata\n */\n metadata: z.object({\n checksum: z.string().optional().describe('State checksum for verification'),\n compressed: z.boolean().default(false),\n encryption: z.string().optional().describe('Encryption algorithm if encrypted'),\n }).optional(),\n});\n\n/**\n * Advanced Plugin Lifecycle Configuration\n * Complete configuration for advanced lifecycle management\n */\nexport const AdvancedPluginLifecycleConfigSchema = z.object({\n /**\n * Health monitoring configuration\n */\n health: PluginHealthCheckSchema.optional(),\n \n /**\n * Hot reload configuration\n */\n hotReload: HotReloadConfigSchema.optional(),\n \n /**\n * Graceful degradation configuration\n */\n degradation: GracefulDegradationSchema.optional(),\n \n /**\n * Update strategy\n */\n updates: PluginUpdateStrategySchema.optional(),\n \n /**\n * Resource limits\n */\n resources: z.object({\n maxMemory: z.number().int().optional().describe('Maximum memory in bytes'),\n maxCpu: z.number().min(0).max(100).optional().describe('Maximum CPU percentage'),\n maxConnections: z.number().int().optional().describe('Maximum concurrent connections'),\n timeout: z.number().int().optional().describe('Operation timeout in milliseconds'),\n }).optional(),\n \n /**\n * Monitoring and observability\n */\n observability: z.object({\n enableMetrics: z.boolean().default(true),\n enableTracing: z.boolean().default(true),\n enableProfiling: z.boolean().default(false),\n metricsInterval: z.number().int().min(1000).default(60000)\n .describe('Metrics collection interval in ms'),\n }).optional(),\n});\n\n// Export types\nexport type PluginHealthStatus = z.infer;\nexport type PluginHealthCheck = z.infer;\nexport type PluginHealthReport = z.infer;\nexport type DistributedStateConfig = z.infer;\nexport type HotReloadConfig = z.infer;\nexport type GracefulDegradation = z.infer;\nexport type PluginUpdateStrategy = z.infer;\nexport type PluginStateSnapshot = z.infer;\nexport type AdvancedPluginLifecycleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Plugin Lifecycle Events Protocol\n * \n * Zod schemas for plugin lifecycle event data structures.\n * These schemas align with the IPluginLifecycleEvents contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Event Payload Schemas\n// ============================================================================\n\n/**\n * Event Phase Enum\n * Lifecycle phase where an error occurred\n */\nexport const EventPhaseSchema = z.enum(['init', 'start', 'destroy'])\n .describe('Plugin lifecycle phase');\n\nexport type EventPhase = z.infer;\n\n/**\n * Plugin Event Base Schema\n * Common fields for all plugin events\n */\nexport const PluginEventBaseSchema = z.object({\n /**\n * Plugin name\n */\n pluginName: z.string().describe('Name of the plugin'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds when event occurred'),\n});\n\n/**\n * Plugin Registered Event Schema\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"version\": \"1.0.0\"\n * }\n */\nexport const PluginRegisteredEventSchema = PluginEventBaseSchema.extend({\n /**\n * Plugin version (optional)\n */\n version: z.string().optional().describe('Plugin version'),\n});\n\nexport type PluginRegisteredEvent = z.infer;\n\n/**\n * Plugin Lifecycle Phase Event Schema\n * For init, start, destroy phases\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"duration\": 1250,\n * \"phase\": \"init\"\n * }\n */\nexport const PluginLifecyclePhaseEventSchema = PluginEventBaseSchema.extend({\n /**\n * Duration of the phase (milliseconds)\n */\n duration: z.number().min(0).optional().describe('Duration of the lifecycle phase in milliseconds'),\n \n /**\n * Lifecycle phase\n */\n phase: EventPhaseSchema.optional().describe('Lifecycle phase'),\n});\n\nexport type PluginLifecyclePhaseEvent = z.infer;\n\n/**\n * Plugin Error Event Schema\n * When a plugin encounters an error\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"error\": Error(\"Connection failed\"),\n * \"phase\": \"start\",\n * \"errorMessage\": \"Connection failed\",\n * \"errorStack\": \"Error: Connection failed\\n at ...\"\n * }\n */\nexport const PluginErrorEventSchema = PluginEventBaseSchema.extend({\n /**\n * Error object\n */\n error: z.object({\n name: z.string().describe('Error class name'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n code: z.string().optional().describe('Error code'),\n }).describe('Serializable error representation'),\n \n /**\n * Lifecycle phase where error occurred\n */\n phase: EventPhaseSchema.describe('Lifecycle phase where error occurred'),\n \n /**\n * Error message (for serialization)\n */\n errorMessage: z.string().optional().describe('Error message'),\n \n /**\n * Error stack trace (for debugging)\n */\n errorStack: z.string().optional().describe('Error stack trace'),\n});\n\nexport type PluginErrorEvent = z.infer;\n\n// ============================================================================\n// Service Event Schemas\n// ============================================================================\n\n/**\n * Service Registered Event Schema\n * \n * @example\n * {\n * \"serviceName\": \"database\",\n * \"timestamp\": 1706659200000,\n * \"serviceType\": \"IDataEngine\"\n * }\n */\nexport const ServiceRegisteredEventSchema = z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Name of the registered service'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Service type (optional)\n */\n serviceType: z.string().optional().describe('Type or interface name of the service'),\n});\n\nexport type ServiceRegisteredEvent = z.infer;\n\n/**\n * Service Unregistered Event Schema\n * \n * @example\n * {\n * \"serviceName\": \"database\",\n * \"timestamp\": 1706659200000\n * }\n */\nexport const ServiceUnregisteredEventSchema = z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Name of the unregistered service'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n});\n\nexport type ServiceUnregisteredEvent = z.infer;\n\n// ============================================================================\n// Hook Event Schemas\n// ============================================================================\n\n/**\n * Hook Registered Event Schema\n * \n * @example\n * {\n * \"hookName\": \"data.beforeInsert\",\n * \"timestamp\": 1706659200000,\n * \"handlerCount\": 3\n * }\n */\nexport const HookRegisteredEventSchema = z.object({\n /**\n * Hook name\n */\n hookName: z.string().describe('Name of the hook'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Number of handlers registered for this hook\n */\n handlerCount: z.number().int().min(0).describe('Number of handlers registered for this hook'),\n});\n\nexport type HookRegisteredEvent = z.infer;\n\n/**\n * Hook Triggered Event Schema\n * \n * @example\n * {\n * \"hookName\": \"data.beforeInsert\",\n * \"timestamp\": 1706659200000,\n * \"args\": [{ \"object\": \"customer\", \"data\": {...} }],\n * \"handlerCount\": 3\n * }\n */\nexport const HookTriggeredEventSchema = z.object({\n /**\n * Hook name\n */\n hookName: z.string().describe('Name of the hook'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Arguments passed to the hook\n */\n args: z.array(z.unknown()).describe('Arguments passed to the hook handlers'),\n \n /**\n * Number of handlers that will handle this event\n */\n handlerCount: z.number().int().min(0).optional().describe('Number of handlers that will handle this event'),\n});\n\nexport type HookTriggeredEvent = z.infer;\n\n// ============================================================================\n// Kernel Event Schemas\n// ============================================================================\n\n/**\n * Kernel Event Base Schema\n * Common fields for kernel events\n */\nexport const KernelEventBaseSchema = z.object({\n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n});\n\n/**\n * Kernel Ready Event Schema\n * \n * @example\n * {\n * \"timestamp\": 1706659200000,\n * \"duration\": 5400,\n * \"pluginCount\": 12\n * }\n */\nexport const KernelReadyEventSchema = KernelEventBaseSchema.extend({\n /**\n * Total initialization duration (milliseconds)\n */\n duration: z.number().min(0).optional().describe('Total initialization duration in milliseconds'),\n \n /**\n * Number of plugins initialized\n */\n pluginCount: z.number().int().min(0).optional().describe('Number of plugins initialized'),\n});\n\nexport type KernelReadyEvent = z.infer;\n\n/**\n * Kernel Shutdown Event Schema\n * \n * @example\n * {\n * \"timestamp\": 1706659200000,\n * \"reason\": \"SIGTERM received\"\n * }\n */\nexport const KernelShutdownEventSchema = KernelEventBaseSchema.extend({\n /**\n * Shutdown reason (optional)\n */\n reason: z.string().optional().describe('Reason for kernel shutdown'),\n});\n\nexport type KernelShutdownEvent = z.infer;\n\n// ============================================================================\n// Event Type Registry\n// ============================================================================\n\n/**\n * Plugin Lifecycle Event Type Enum\n * All possible plugin lifecycle event types\n */\nexport const PluginLifecycleEventType = z.enum([\n 'kernel:ready',\n 'kernel:shutdown',\n 'kernel:before-init',\n 'kernel:after-init',\n 'plugin:registered',\n 'plugin:before-init',\n 'plugin:init',\n 'plugin:after-init',\n 'plugin:before-start',\n 'plugin:started',\n 'plugin:after-start',\n 'plugin:before-destroy',\n 'plugin:destroyed',\n 'plugin:after-destroy',\n 'plugin:error',\n 'service:registered',\n 'service:unregistered',\n 'hook:registered',\n 'hook:triggered',\n]).describe('Plugin lifecycle event type');\n\nexport type PluginLifecycleEventType = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Runtime Management Protocol\n * \n * Defines the protocol for dynamic plugin loading, unloading, and discovery\n * at runtime. Addresses the \"Dynamic Loading\" gap in the microkernel architecture\n * by enabling plugins to be loaded and unloaded without restarting the kernel.\n * \n * Inspired by:\n * - OSGi Dynamic Module System (bundle lifecycle)\n * - Kubernetes Operator pattern (reconciliation loop)\n * - VS Code Extension Host (activation events)\n * \n * This protocol enables:\n * - Runtime load/unload of plugins without kernel restart\n * - Plugin discovery from registries and local filesystem\n * - Activation events (load plugin only when needed)\n * - Safe unload with dependency awareness\n */\n\n/**\n * Dynamic Plugin Operation Type\n * Operations that can be performed on plugins at runtime\n */\nexport const DynamicPluginOperationSchema = z.enum([\n 'load', // Load and initialize a plugin at runtime\n 'unload', // Gracefully unload a running plugin\n 'reload', // Unload then load (e.g., version upgrade)\n 'enable', // Enable a loaded but disabled plugin\n 'disable', // Disable a running plugin without unloading\n]).describe('Runtime plugin operation type');\n\n/**\n * Plugin Source\n * Where to resolve a plugin for dynamic loading\n */\nexport const PluginSourceSchema = z.object({\n /**\n * Source type\n */\n type: z.enum([\n 'npm', // npm registry package\n 'local', // Local filesystem path\n 'url', // Remote URL (tarball or module)\n 'registry', // ObjectStack plugin registry\n 'git', // Git repository\n ]).describe('Plugin source type'),\n \n /**\n * Source location (package name, path, URL, or git repo)\n */\n location: z.string().describe('Package name, file path, URL, or git repository'),\n \n /**\n * Version constraint (semver range)\n */\n version: z.string().optional().describe('Semver version range (e.g., \"^1.0.0\")'),\n \n /**\n * Integrity hash for verification\n */\n integrity: z.string().optional().describe('Subresource Integrity hash (e.g., \"sha384-...\")'),\n}).describe('Plugin source location for dynamic resolution');\n\n/**\n * Activation Event\n * Defines when a dynamically available plugin should be activated.\n * Plugins remain dormant until an activation event fires.\n */\nexport const ActivationEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'onCommand', // Activate when a specific command is executed\n 'onRoute', // Activate when a URL route is matched\n 'onObject', // Activate when a specific object type is accessed\n 'onEvent', // Activate when a system event fires\n 'onService', // Activate when a service is requested\n 'onSchedule', // Activate on a cron schedule\n 'onStartup', // Activate immediately on kernel startup\n ]).describe('Trigger type for lazy activation'),\n \n /**\n * Pattern to match (command name, route glob, object name, event pattern, etc.)\n */\n pattern: z.string().describe('Match pattern for the activation trigger'),\n}).describe('Lazy activation trigger for a dynamic plugin');\n\n/**\n * Dynamic Load Request\n * Request to load a plugin at runtime\n */\nexport const DynamicLoadRequestSchema = z.object({\n /**\n * Plugin identifier to load\n */\n pluginId: z.string().describe('Unique plugin identifier'),\n \n /**\n * Plugin source\n */\n source: PluginSourceSchema,\n \n /**\n * Activation events (if omitted, plugin activates immediately)\n */\n activationEvents: z.array(ActivationEventSchema).optional()\n .describe('Lazy activation triggers; if omitted plugin starts immediately'),\n \n /**\n * Configuration overrides for the plugin\n */\n config: z.record(z.string(), z.unknown()).optional()\n .describe('Runtime configuration overrides'),\n \n /**\n * Loading priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100)\n .describe('Loading priority (lower is higher)'),\n \n /**\n * Whether to enable sandboxing for this dynamically loaded plugin\n */\n sandbox: z.boolean().default(false)\n .describe('Run in an isolated sandbox'),\n \n /**\n * Timeout for the load operation in milliseconds\n */\n timeout: z.number().int().min(1000).default(60000)\n .describe('Maximum time to complete loading in ms'),\n}).describe('Request to dynamically load a plugin at runtime');\n\n/**\n * Dynamic Unload Request\n * Request to unload a plugin at runtime\n */\nexport const DynamicUnloadRequestSchema = z.object({\n /**\n * Plugin identifier to unload\n */\n pluginId: z.string().describe('Plugin to unload'),\n \n /**\n * Unload strategy\n */\n strategy: z.enum([\n 'graceful', // Wait for in-flight requests, then unload\n 'forceful', // Unload immediately, cancel pending work\n 'drain', // Stop accepting new work, finish existing, then unload\n ]).default('graceful').describe('How to handle in-flight work during unload'),\n \n /**\n * Timeout for the unload operation in milliseconds\n */\n timeout: z.number().int().min(1000).default(30000)\n .describe('Maximum time to complete unloading in ms'),\n \n /**\n * Whether to remove cached artifacts\n */\n cleanupCache: z.boolean().default(false)\n .describe('Remove cached code and assets after unload'),\n \n /**\n * Action for dependents: plugins that depend on this one\n */\n dependentAction: z.enum([\n 'cascade', // Also unload dependent plugins\n 'warn', // Warn about dependents but proceed\n 'block', // Block unload if dependents exist\n ]).default('block').describe('How to handle plugins that depend on this one'),\n}).describe('Request to dynamically unload a plugin at runtime');\n\n/**\n * Dynamic Plugin Operation Result\n * Result of a dynamic load/unload/reload operation\n */\nexport const DynamicPluginResultSchema = z.object({\n /**\n * Whether the operation succeeded\n */\n success: z.boolean(),\n \n /**\n * The operation that was performed\n */\n operation: DynamicPluginOperationSchema,\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Operation duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Resulting plugin version (for load/reload)\n */\n version: z.string().optional(),\n \n /**\n * Error details if operation failed\n */\n error: z.object({\n code: z.string().describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n details: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n \n /**\n * Warnings (e.g., dependents affected)\n */\n warnings: z.array(z.string()).optional(),\n}).describe('Result of a dynamic plugin operation');\n\n/**\n * Plugin Discovery Source\n * Defines where to discover available plugins at runtime\n */\nexport const PluginDiscoverySourceSchema = z.object({\n /**\n * Discovery source type\n */\n type: z.enum([\n 'registry', // ObjectStack plugin registry API\n 'npm', // npm registry search\n 'directory', // Local filesystem directory scan\n 'url', // Remote manifest URL\n ]).describe('Discovery source type'),\n \n /**\n * Source endpoint or path\n */\n endpoint: z.string().describe('Registry URL, directory path, or manifest URL'),\n \n /**\n * Polling interval in milliseconds (0 = manual only)\n */\n pollInterval: z.number().int().min(0).default(0)\n .describe('How often to re-scan for new plugins (0 = manual)'),\n \n /**\n * Filter criteria for discovered plugins\n */\n filter: z.object({\n /**\n * Only discover plugins matching these tags\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Only discover plugins from these vendors\n */\n vendors: z.array(z.string()).optional(),\n \n /**\n * Minimum trust level\n */\n minTrustLevel: z.enum(['verified', 'trusted', 'community', 'untrusted']).optional(),\n }).optional(),\n}).describe('Source for runtime plugin discovery');\n\n/**\n * Plugin Discovery Configuration\n * Controls how the kernel discovers available plugins at runtime\n */\nexport const PluginDiscoveryConfigSchema = z.object({\n /**\n * Enable runtime plugin discovery\n */\n enabled: z.boolean().default(false),\n \n /**\n * Discovery sources\n */\n sources: z.array(PluginDiscoverySourceSchema).default([]),\n \n /**\n * Auto-load discovered plugins matching criteria\n */\n autoLoad: z.boolean().default(false)\n .describe('Automatically load newly discovered plugins'),\n \n /**\n * Require approval before loading discovered plugins\n */\n requireApproval: z.boolean().default(true)\n .describe('Require admin approval before loading discovered plugins'),\n}).describe('Runtime plugin discovery configuration');\n\n/**\n * Dynamic Loading Configuration\n * Top-level configuration for the dynamic plugin loading subsystem\n */\nexport const DynamicLoadingConfigSchema = z.object({\n /**\n * Enable dynamic loading/unloading at runtime\n */\n enabled: z.boolean().default(false)\n .describe('Enable runtime load/unload of plugins'),\n \n /**\n * Maximum number of dynamically loaded plugins\n */\n maxDynamicPlugins: z.number().int().min(1).default(50)\n .describe('Upper limit on runtime-loaded plugins'),\n \n /**\n * Plugin discovery configuration\n */\n discovery: PluginDiscoveryConfigSchema.optional(),\n \n /**\n * Default sandbox policy for dynamically loaded plugins\n */\n defaultSandbox: z.boolean().default(true)\n .describe('Sandbox dynamically loaded plugins by default'),\n \n /**\n * Allowed plugin sources (empty = all allowed)\n */\n allowedSources: z.array(z.enum(['npm', 'local', 'url', 'registry', 'git'])).optional()\n .describe('Restrict which source types are permitted'),\n \n /**\n * Require integrity verification for remote plugins\n */\n requireIntegrity: z.boolean().default(true)\n .describe('Require integrity hash verification for remote sources'),\n \n /**\n * Global timeout for dynamic operations in milliseconds\n */\n operationTimeout: z.number().int().min(1000).default(60000)\n .describe('Default timeout for load/unload operations in ms'),\n}).describe('Dynamic plugin loading subsystem configuration');\n\n// Export types\nexport type DynamicPluginOperation = z.infer;\nexport type PluginSource = z.infer;\nexport type ActivationEvent = z.infer;\nexport type DynamicLoadRequest = z.infer;\nexport type DynamicUnloadRequest = z.infer;\nexport type DynamicPluginResult = z.infer;\nexport type PluginDiscoverySource = z.infer;\nexport type PluginDiscoveryConfig = z.infer;\nexport type DynamicLoadingConfig = z.infer;\n\n// Export input types for schemas with defaults\nexport type DynamicLoadRequestInput = z.input;\nexport type DynamicUnloadRequestInput = z.input;\nexport type DynamicLoadingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Security and Sandboxing Protocol\n * \n * Defines comprehensive security mechanisms for plugin isolation, permission\n * management, and threat protection in the ObjectStack ecosystem.\n * \n * Features:\n * - Fine-grained permission system\n * - Resource access control\n * - Sandboxing and isolation\n * - Security scanning and verification\n * - Runtime security monitoring\n */\n\n/**\n * Permission Scope\n * Defines the scope of a permission\n */\nexport const PermissionScopeSchema = z.enum([\n 'global', // Applies to entire system\n 'tenant', // Applies to specific tenant\n 'user', // Applies to specific user\n 'resource', // Applies to specific resource\n 'plugin', // Applies within plugin boundaries\n]).describe('Scope of permission application');\n\n/**\n * Permission Action\n * Standard CRUD + extended actions\n */\nexport const PermissionActionSchema = z.enum([\n 'create', // Create new resources\n 'read', // Read existing resources\n 'update', // Update existing resources\n 'delete', // Delete resources\n 'execute', // Execute operations/functions\n 'manage', // Full management rights\n 'configure', // Configuration changes\n 'share', // Share with others\n 'export', // Export data\n 'import', // Import data\n 'admin', // Administrative access\n]).describe('Type of action being permitted');\n\n/**\n * Resource Type\n * Types of resources that can be accessed\n */\nexport const ResourceTypeSchema = z.enum([\n 'data.object', // ObjectQL objects\n 'data.record', // Individual records\n 'data.field', // Specific fields\n 'ui.view', // UI views\n 'ui.dashboard', // Dashboards\n 'ui.report', // Reports\n 'system.config', // System configuration\n 'system.plugin', // Other plugins\n 'system.api', // API endpoints\n 'system.service', // System services\n 'storage.file', // File storage\n 'storage.database', // Database access\n 'network.http', // HTTP requests\n 'network.websocket', // WebSocket connections\n 'process.spawn', // Process spawning\n 'process.env', // Environment variables\n]).describe('Type of resource being accessed');\n\n/**\n * Permission Definition\n * Defines a single permission requirement\n */\nexport const PermissionSchema = z.object({\n /**\n * Permission identifier\n */\n id: z.string().describe('Unique permission identifier'),\n \n /**\n * Resource type\n */\n resource: ResourceTypeSchema,\n \n /**\n * Allowed actions\n */\n actions: z.array(PermissionActionSchema),\n \n /**\n * Permission scope\n */\n scope: PermissionScopeSchema.default('plugin'),\n \n /**\n * Resource filter\n */\n filter: z.object({\n /**\n * Specific resource IDs\n */\n resourceIds: z.array(z.string()).optional(),\n \n /**\n * Filter condition\n */\n condition: z.string().optional().describe('Filter expression (e.g., owner = currentUser)'),\n \n /**\n * Field-level access\n */\n fields: z.array(z.string()).optional().describe('Allowed fields for data resources'),\n }).optional(),\n \n /**\n * Human-readable description\n */\n description: z.string(),\n \n /**\n * Whether this permission is required or optional\n */\n required: z.boolean().default(true),\n \n /**\n * Justification for permission\n */\n justification: z.string().optional().describe('Why this permission is needed'),\n});\n\n/**\n * Permission Set\n * Collection of permissions for a plugin\n */\nexport const PermissionSetSchema = z.object({\n /**\n * All permissions required by plugin\n */\n permissions: z.array(PermissionSchema),\n \n /**\n * Permission groups for easier management\n */\n groups: z.array(z.object({\n name: z.string().describe('Group name'),\n description: z.string(),\n permissions: z.array(z.string()).describe('Permission IDs in this group'),\n })).optional(),\n \n /**\n * Default grant strategy\n */\n defaultGrant: z.enum([\n 'prompt', // Always prompt user\n 'allow', // Allow by default\n 'deny', // Deny by default\n 'inherit', // Inherit from parent\n ]).default('prompt'),\n});\n\n/**\n * Runtime Configuration\n * Defines the execution environment for plugin isolation\n */\nexport const RuntimeConfigSchema = z.object({\n /**\n * Runtime engine type\n */\n engine: z.enum([\n 'v8-isolate', // V8 isolate-based isolation (lightweight, fast)\n 'wasm', // WebAssembly-based isolation (secure, portable)\n 'container', // Container-based isolation (Docker, podman)\n 'process', // Process-based isolation (traditional)\n ]).default('v8-isolate')\n .describe('Execution environment engine'),\n \n /**\n * Engine-specific configuration\n */\n engineConfig: z.object({\n /**\n * WASM-specific settings (when engine is \"wasm\")\n */\n wasm: z.object({\n /**\n * Maximum memory pages (64KB per page)\n */\n maxMemoryPages: z.number().int().min(1).max(65536).optional()\n .describe('Maximum WASM memory pages (64KB each)'),\n \n /**\n * Instruction execution limit\n */\n instructionLimit: z.number().int().min(1).optional()\n .describe('Maximum instructions before timeout'),\n \n /**\n * Enable SIMD instructions\n */\n enableSimd: z.boolean().default(false)\n .describe('Enable WebAssembly SIMD support'),\n \n /**\n * Enable threads\n */\n enableThreads: z.boolean().default(false)\n .describe('Enable WebAssembly threads'),\n \n /**\n * Enable bulk memory operations\n */\n enableBulkMemory: z.boolean().default(true)\n .describe('Enable bulk memory operations'),\n }).optional(),\n \n /**\n * Container-specific settings (when engine is \"container\")\n */\n container: z.object({\n /**\n * Container image\n */\n image: z.string().optional()\n .describe('Container image to use'),\n \n /**\n * Container runtime\n */\n runtime: z.enum(['docker', 'podman', 'containerd']).default('docker'),\n \n /**\n * Resource limits\n */\n resources: z.object({\n cpuLimit: z.string().optional().describe('CPU limit (e.g., \"0.5\", \"2\")'),\n memoryLimit: z.string().optional().describe('Memory limit (e.g., \"512m\", \"1g\")'),\n }).optional(),\n \n /**\n * Network mode\n */\n networkMode: z.enum(['none', 'bridge', 'host']).default('bridge'),\n }).optional(),\n \n /**\n * V8 Isolate-specific settings (when engine is \"v8-isolate\")\n */\n v8Isolate: z.object({\n /**\n * Heap size limit in MB\n */\n heapSizeMb: z.number().int().min(1).optional(),\n \n /**\n * Enable snapshot\n */\n enableSnapshot: z.boolean().default(true),\n }).optional(),\n }).optional(),\n \n /**\n * General resource limits (applies to all engines)\n */\n resourceLimits: z.object({\n /**\n * Maximum memory in bytes\n */\n maxMemory: z.number().int().optional()\n .describe('Maximum memory allocation'),\n \n /**\n * Maximum CPU percentage\n */\n maxCpu: z.number().min(0).max(100).optional()\n .describe('Maximum CPU usage percentage'),\n \n /**\n * Execution timeout in milliseconds\n */\n timeout: z.number().int().min(0).optional()\n .describe('Maximum execution time'),\n }).optional(),\n});\n\n/**\n * Sandbox Configuration\n * Defines how plugin is isolated\n */\nexport const SandboxConfigSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(true),\n \n /**\n * Sandboxing level\n */\n level: z.enum([\n 'none', // No sandboxing\n 'minimal', // Basic isolation\n 'standard', // Standard sandboxing\n 'strict', // Strict isolation\n 'paranoid', // Maximum isolation\n ]).default('standard'),\n \n /**\n * Runtime environment configuration\n */\n runtime: RuntimeConfigSchema.optional()\n .describe('Execution environment and isolation settings'),\n \n /**\n * File system access\n */\n filesystem: z.object({\n mode: z.enum(['none', 'readonly', 'restricted', 'full']).default('restricted'),\n allowedPaths: z.array(z.string()).optional().describe('Whitelisted paths'),\n deniedPaths: z.array(z.string()).optional().describe('Blacklisted paths'),\n maxFileSize: z.number().int().optional().describe('Maximum file size in bytes'),\n }).optional(),\n \n /**\n * Network access\n */\n network: z.object({\n mode: z.enum(['none', 'local', 'restricted', 'full']).default('restricted'),\n allowedHosts: z.array(z.string()).optional().describe('Whitelisted hosts'),\n deniedHosts: z.array(z.string()).optional().describe('Blacklisted hosts'),\n allowedPorts: z.array(z.number()).optional().describe('Allowed port numbers'),\n maxConnections: z.number().int().optional(),\n }).optional(),\n \n /**\n * Process execution\n */\n process: z.object({\n allowSpawn: z.boolean().default(false).describe('Allow spawning child processes'),\n allowedCommands: z.array(z.string()).optional().describe('Whitelisted commands'),\n timeout: z.number().int().optional().describe('Process timeout in ms'),\n }).optional(),\n \n /**\n * Memory limits\n */\n memory: z.object({\n maxHeap: z.number().int().optional().describe('Maximum heap size in bytes'),\n maxStack: z.number().int().optional().describe('Maximum stack size in bytes'),\n }).optional(),\n \n /**\n * CPU limits\n */\n cpu: z.object({\n maxCpuPercent: z.number().min(0).max(100).optional(),\n maxThreads: z.number().int().optional(),\n }).optional(),\n \n /**\n * Environment variables\n */\n environment: z.object({\n mode: z.enum(['none', 'readonly', 'restricted', 'full']).default('readonly'),\n allowedVars: z.array(z.string()).optional(),\n deniedVars: z.array(z.string()).optional(),\n }).optional(),\n});\n\n/**\n * Security Vulnerability\n * Represents a known security vulnerability\n */\nexport const KernelSecurityVulnerabilitySchema = z.object({\n /**\n * CVE identifier\n */\n cve: z.string().optional(),\n \n /**\n * Vulnerability identifier\n */\n id: z.string(),\n \n /**\n * Severity level\n */\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),\n \n /**\n * Category (e.g., SAST, DAST, Dependency)\n */\n category: z.string().optional(),\n\n /**\n * Title\n */\n title: z.string(),\n \n /**\n * Location of the vulnerability\n */\n location: z.string().optional(),\n\n /**\n * Remediation steps\n */\n remediation: z.string().optional(),\n\n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Affected versions\n */\n affectedVersions: z.array(z.string()),\n \n /**\n * Fixed in versions\n */\n fixedIn: z.array(z.string()).optional(),\n \n /**\n * CVSS score\n */\n cvssScore: z.number().min(0).max(10).optional(),\n \n /**\n * Exploit availability\n */\n exploitAvailable: z.boolean().default(false),\n \n /**\n * Patch available\n */\n patchAvailable: z.boolean().default(false),\n \n /**\n * Workaround\n */\n workaround: z.string().optional(),\n \n /**\n * References\n */\n references: z.array(z.string()).optional(),\n \n /**\n * Discovered date\n */\n discoveredDate: z.string().datetime().optional(),\n \n /**\n * Published date\n */\n publishedDate: z.string().datetime().optional(),\n});\n\n/**\n * Security Scan Result\n * Result of security scanning\n */\nexport const KernelSecurityScanResultSchema = z.object({\n /**\n * Scan timestamp\n */\n timestamp: z.string().datetime(),\n \n /**\n * Scanner information\n */\n scanner: z.object({\n name: z.string(),\n version: z.string(),\n }),\n \n /**\n * Overall status\n */\n status: z.enum(['passed', 'failed', 'warning']),\n \n /**\n * Vulnerabilities found\n */\n vulnerabilities: z.array(KernelSecurityVulnerabilitySchema).optional(),\n \n /**\n * Code quality issues\n */\n codeIssues: z.array(z.object({\n severity: z.enum(['error', 'warning', 'info']),\n type: z.string().describe('Issue type (e.g., sql-injection, xss)'),\n file: z.string(),\n line: z.number().int().optional(),\n message: z.string(),\n suggestion: z.string().optional(),\n })).optional(),\n \n /**\n * Dependency vulnerabilities\n */\n dependencyVulnerabilities: z.array(z.object({\n package: z.string(),\n version: z.string(),\n vulnerability: KernelSecurityVulnerabilitySchema,\n })).optional(),\n \n /**\n * License compliance\n */\n licenseCompliance: z.object({\n status: z.enum(['compliant', 'non-compliant', 'unknown']),\n issues: z.array(z.object({\n package: z.string(),\n license: z.string(),\n reason: z.string(),\n })).optional(),\n }).optional(),\n \n /**\n * Summary statistics\n */\n summary: z.object({\n totalVulnerabilities: z.number().int(),\n criticalCount: z.number().int(),\n highCount: z.number().int(),\n mediumCount: z.number().int(),\n lowCount: z.number().int(),\n infoCount: z.number().int(),\n }),\n});\n\n/**\n * Security Policy\n * Defines security policies for plugin\n */\nexport const KernelSecurityPolicySchema = z.object({\n /**\n * Content Security Policy\n */\n csp: z.object({\n directives: z.record(z.string(), z.array(z.string())).optional(),\n reportOnly: z.boolean().default(false),\n }).optional(),\n \n /**\n * CORS policy\n */\n cors: z.object({\n allowedOrigins: z.array(z.string()),\n allowedMethods: z.array(z.string()),\n allowedHeaders: z.array(z.string()),\n allowCredentials: z.boolean().default(false),\n maxAge: z.number().int().optional(),\n }).optional(),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n enabled: z.boolean().default(true),\n maxRequests: z.number().int(),\n windowMs: z.number().int().describe('Time window in milliseconds'),\n strategy: z.enum(['fixed', 'sliding', 'token-bucket']).default('sliding'),\n }).optional(),\n \n /**\n * Authentication requirements\n */\n authentication: z.object({\n required: z.boolean().default(true),\n methods: z.array(z.enum(['jwt', 'oauth2', 'api-key', 'session', 'certificate'])),\n tokenExpiration: z.number().int().optional().describe('Token expiration in seconds'),\n }).optional(),\n \n /**\n * Encryption requirements\n */\n encryption: z.object({\n dataAtRest: z.boolean().default(false).describe('Encrypt data at rest'),\n dataInTransit: z.boolean().default(true).describe('Enforce HTTPS/TLS'),\n algorithm: z.string().optional().describe('Encryption algorithm'),\n minKeyLength: z.number().int().optional().describe('Minimum key length in bits'),\n }).optional(),\n \n /**\n * Audit logging\n */\n auditLog: z.object({\n enabled: z.boolean().default(true),\n events: z.array(z.string()).optional().describe('Events to log'),\n retention: z.number().int().optional().describe('Log retention in days'),\n }).optional(),\n});\n\n/**\n * Plugin Trust Level\n * Indicates trust level of plugin\n */\nexport const PluginTrustLevelSchema = z.enum([\n 'verified', // Official/verified plugin\n 'trusted', // Trusted third-party\n 'community', // Community plugin\n 'untrusted', // Unverified plugin\n 'blocked', // Blocked/malicious\n]).describe('Trust level of the plugin');\n\n/**\n * Plugin Security Manifest\n * Complete security information for plugin\n */\nexport const PluginSecurityManifestSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Trust level\n */\n trustLevel: PluginTrustLevelSchema,\n \n /**\n * Required permissions\n */\n permissions: PermissionSetSchema,\n \n /**\n * Sandbox configuration\n */\n sandbox: SandboxConfigSchema,\n \n /**\n * Security policy\n */\n policy: KernelSecurityPolicySchema.optional(),\n \n /**\n * Security scan results\n */\n scanResults: z.array(KernelSecurityScanResultSchema).optional(),\n \n /**\n * Known vulnerabilities\n */\n vulnerabilities: z.array(KernelSecurityVulnerabilitySchema).optional(),\n \n /**\n * Code signing\n */\n codeSigning: z.object({\n signed: z.boolean(),\n signature: z.string().optional(),\n certificate: z.string().optional(),\n algorithm: z.string().optional(),\n timestamp: z.string().datetime().optional(),\n }).optional(),\n \n /**\n * Security certifications\n */\n certifications: z.array(z.object({\n name: z.string().describe('Certification name (e.g., SOC 2, ISO 27001)'),\n issuer: z.string(),\n issuedDate: z.string().datetime(),\n expiryDate: z.string().datetime().optional(),\n certificateUrl: z.string().url().optional(),\n })).optional(),\n \n /**\n * Security contact\n */\n securityContact: z.object({\n email: z.string().email().optional(),\n url: z.string().url().optional(),\n pgpKey: z.string().optional(),\n }).optional(),\n \n /**\n * Vulnerability disclosure policy\n */\n vulnerabilityDisclosure: z.object({\n policyUrl: z.string().url().optional(),\n responseTime: z.number().int().optional().describe('Expected response time in hours'),\n bugBounty: z.boolean().default(false),\n }).optional(),\n});\n\n// Export types\nexport type PermissionScope = z.infer;\nexport type PermissionAction = z.infer;\nexport type ResourceType = z.infer;\nexport type Permission = z.infer;\nexport type PermissionSet = z.infer;\nexport type RuntimeConfig = z.infer;\nexport type SandboxConfig = z.infer;\nexport type KernelSecurityVulnerability = z.infer;\nexport type KernelSecurityScanResult = z.infer;\nexport type KernelSecurityPolicy = z.infer;\nexport type PluginTrustLevel = z.infer;\nexport type PluginSecurityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * ObjectStack Plugin Structure Standards (OPS)\n * \n * Formal Zod definitions for the Plugin Directory Structure and File Naming conventions.\n * This can be used by the CLI or IDE extensions to lint project structure.\n * \n * @see PLUGIN_STANDARDS.md\n */\n\n// REGEX: snake_case identifiers\nconst SNAKE_CASE_REGEX = /^[a-z][a-z0-9_]*$/;\n\n// REGEX: Standard File Suffixes\nconst OPS_FILE_SUFFIX_REGEX = /\\.(object|field|trigger|function|view|page|dashboard|flow|app|router|service)\\.ts$/;\n\n/**\n * Validates a single file path against OPS Naming Conventions.\n * \n * @example Valid Paths\n * - \"src/crm/lead.object.ts\"\n * - \"src/finance/invoice_payment.trigger.ts\"\n * - \"src/index.ts\"\n * \n * @example Invalid Paths\n * - \"src/CRM/LeadObject.ts\" (PascalCase)\n * - \"src/utils/helper.js\" (Wrong extension)\n */\nexport const OpsFilePathSchema = z.string().describe('Validates a file path against OPS naming conventions').superRefine((path, ctx) => {\n // 1. Must be in src/\n if (!path.startsWith('src/')) {\n // Non-source files (package.json, config) are ignored by this specific validator\n // or handled separately.\n return; \n }\n\n const parts = path.split('/');\n \n // 2. Validate Domain Directory (src/[domain])\n if (parts.length > 2) {\n const domainDir = parts[1];\n if (!SNAKE_CASE_REGEX.test(domainDir)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Domain directory '${domainDir}' must be lowercase snake_case`\n });\n }\n }\n\n // 3. Validate Filename suffix\n const filename = parts[parts.length - 1];\n \n // Skip index.ts and utility files if they don't match the specific resource pattern\n // But strict OPS encourages explicit suffixes for resources.\n if (filename === 'index.ts' || filename === 'main.ts') return;\n\n if (!SNAKE_CASE_REGEX.test(filename.split('.')[0])) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Filename '${filename}' base name must be lowercase snake_case`\n });\n }\n\n if (!OPS_FILE_SUFFIX_REGEX.test(filename)) {\n // We allow other files, but we warn or mark them as non-standard resources\n // For strict mode:\n // ctx.addIssue({\n // code: z.ZodIssueCode.custom,\n // message: `Filename '${filename}' does not end with a valid semantic suffix (.object.ts, .view.ts, etc.)`\n // });\n }\n});\n\n/**\n * Schema for a \"Scanned Module\" structure.\n * Represents the contents of a domain folder.\n */\nexport const OpsDomainModuleSchema = z.object({\n name: z.string().regex(SNAKE_CASE_REGEX).describe('Module name (snake_case)'),\n files: z.array(z.string()).describe('List of files in this module'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n}).describe('Scanned domain module representing a plugin folder').superRefine((module, ctx) => {\n // Rule: Must have an index.ts\n if (!module.files.includes('index.ts')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Module '${module.name}' is missing an 'index.ts' entry point.`\n });\n }\n});\n\n/**\n * Schema for a full Plugin Project Layout\n */\nexport const OpsPluginStructureSchema = z.object({\n root: z.string().describe('Root directory path of the plugin project'),\n files: z.array(z.string()).describe('List of all file paths relative to root'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n}).describe('Full plugin project layout validated against OPS conventions').superRefine((project, ctx) => {\n // Check for configuration file\n if (!project.files.includes('objectstack.config.ts')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"Missing 'objectstack.config.ts' configuration file.\"\n });\n }\n \n // Validate each source file individually\n project.files.filter(f => f.startsWith('src/')).forEach(file => {\n const result = OpsFilePathSchema.safeParse(file);\n if (!result.success) {\n result.error.issues.forEach(issue => {\n ctx.addIssue({ ...issue, path: [file] });\n })\n }\n });\n});\n\nexport type OpsFilePath = z.infer;\nexport type OpsDomainModule = z.infer;\nexport type OpsPluginStructure = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Plugin Validator Protocol\n * \n * Zod schemas for plugin validation data structures.\n * These schemas align with the IPluginValidator contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Validation Result Schemas\n// ============================================================================\n\n/**\n * Validation Error Schema\n * Represents a single validation error\n * \n * @example\n * {\n * \"field\": \"version\",\n * \"message\": \"Invalid semver format\",\n * \"code\": \"INVALID_VERSION\"\n * }\n */\nexport const ValidationErrorSchema = z.object({\n /**\n * Field that failed validation\n */\n field: z.string().describe('Field name that failed validation'),\n \n /**\n * Human-readable error message\n */\n message: z.string().describe('Human-readable error message'),\n \n /**\n * Machine-readable error code (optional)\n */\n code: z.string().optional().describe('Machine-readable error code'),\n});\n\nexport type ValidationError = z.infer;\n\n/**\n * Validation Warning Schema\n * Represents a non-fatal validation warning\n * \n * @example\n * {\n * \"field\": \"description\",\n * \"message\": \"Description is empty\",\n * \"code\": \"MISSING_DESCRIPTION\"\n * }\n */\nexport const ValidationWarningSchema = z.object({\n /**\n * Field with warning\n */\n field: z.string().describe('Field name with warning'),\n \n /**\n * Human-readable warning message\n */\n message: z.string().describe('Human-readable warning message'),\n \n /**\n * Machine-readable warning code (optional)\n */\n code: z.string().optional().describe('Machine-readable warning code'),\n});\n\nexport type ValidationWarning = z.infer;\n\n/**\n * Validation Result Schema\n * Result of plugin validation operation\n * \n * @example\n * {\n * \"valid\": false,\n * \"errors\": [{\n * \"field\": \"name\",\n * \"message\": \"Plugin name is required\",\n * \"code\": \"REQUIRED_FIELD\"\n * }],\n * \"warnings\": [{\n * \"field\": \"description\",\n * \"message\": \"Description is recommended\",\n * \"code\": \"MISSING_DESCRIPTION\"\n * }]\n * }\n */\nexport const ValidationResultSchema = z.object({\n /**\n * Whether validation passed\n */\n valid: z.boolean().describe('Whether the plugin passed validation'),\n \n /**\n * Validation errors (if any)\n */\n errors: z.array(ValidationErrorSchema).optional().describe('Validation errors'),\n \n /**\n * Validation warnings (non-fatal issues)\n */\n warnings: z.array(ValidationWarningSchema).optional().describe('Validation warnings'),\n});\n\nexport type ValidationResult = z.infer;\n\n// ============================================================================\n// Plugin Metadata Schema\n// ============================================================================\n\n/**\n * Plugin Schema\n * Metadata structure for a plugin\n * \n * This aligns with and extends the existing PluginSchema from plugin.zod.ts\n * \n * @example\n * {\n * \"name\": \"crm-plugin\",\n * \"version\": \"1.0.0\",\n * \"dependencies\": [\"core-plugin\"]\n * }\n */\nexport const PluginMetadataSchema = z.object({\n /**\n * Unique plugin identifier (snake_case)\n */\n name: z.string().min(1).describe('Unique plugin identifier'),\n \n /**\n * Plugin version (semver)\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic version (e.g., 1.0.0)'),\n \n /**\n * Plugin dependencies (array of plugin names)\n */\n dependencies: z.array(z.string()).optional().describe('Array of plugin names this plugin depends on'),\n \n /**\n * Plugin signature for cryptographic verification (optional)\n */\n signature: z.string().optional().describe('Cryptographic signature for plugin verification'),\n \n /**\n * Additional plugin metadata\n */\n}).passthrough().describe('Plugin metadata for validation');\n\nexport type PluginMetadata = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Versioning and Compatibility Protocol\n * \n * Defines comprehensive versioning, compatibility checking, and dependency\n * resolution mechanisms for the plugin ecosystem.\n * \n * Based on semantic versioning (SemVer) with extensions for:\n * - Compatibility matrices\n * - Breaking change detection\n * - Migration paths\n * - Multi-version support\n */\n\n/**\n * Semantic Version Schema\n * Standard SemVer format with optional pre-release and build metadata\n */\nexport const SemanticVersionSchema = z.object({\n major: z.number().int().min(0).describe('Major version (breaking changes)'),\n minor: z.number().int().min(0).describe('Minor version (backward compatible features)'),\n patch: z.number().int().min(0).describe('Patch version (backward compatible fixes)'),\n preRelease: z.string().optional().describe('Pre-release identifier (alpha, beta, rc.1)'),\n build: z.string().optional().describe('Build metadata'),\n}).describe('Semantic version number');\n\n/**\n * Version Constraint Schema\n * Defines version requirements using SemVer ranges\n */\nexport const VersionConstraintSchema = z.union([\n z.string().regex(/^[\\d.]+$/).describe('Exact version: `1.2.3`'),\n z.string().regex(/^\\^[\\d.]+$/).describe('Compatible with: `^1.2.3` (`>=1.2.3 <2.0.0`)'),\n z.string().regex(/^~[\\d.]+$/).describe('Approximately: `~1.2.3` (`>=1.2.3 <1.3.0`)'),\n z.string().regex(/^>=[\\d.]+$/).describe('Greater than or equal: `>=1.2.3`'),\n z.string().regex(/^>[\\d.]+$/).describe('Greater than: `>1.2.3`'),\n z.string().regex(/^<=[\\d.]+$/).describe('Less than or equal: `<=1.2.3`'),\n z.string().regex(/^<[\\d.]+$/).describe('Less than: `<1.2.3`'),\n z.string().regex(/^[\\d.]+ - [\\d.]+$/).describe('Range: `1.2.3 - 2.3.4`'),\n z.literal('*').describe('Any version'),\n z.literal('latest').describe('Latest stable version'),\n]);\n\n/**\n * Compatibility Level\n * Describes the level of compatibility between versions\n */\nexport const CompatibilityLevelSchema = z.enum([\n 'fully-compatible', // 100% compatible, drop-in replacement\n 'backward-compatible', // Backward compatible, new features added\n 'deprecated-compatible', // Compatible but uses deprecated features\n 'breaking-changes', // Breaking changes, migration required\n 'incompatible', // Completely incompatible\n]).describe('Compatibility level between versions');\n\n/**\n * Breaking Change\n * Documents a breaking change in a version\n */\nexport const BreakingChangeSchema = z.object({\n /**\n * Version where the change was introduced\n */\n introducedIn: z.string().describe('Version that introduced this breaking change'),\n \n /**\n * Type of breaking change\n */\n type: z.enum([\n 'api-removed', // API removed\n 'api-renamed', // API renamed\n 'api-signature-changed', // Function signature changed\n 'behavior-changed', // Behavior changed\n 'dependency-changed', // Dependency requirement changed\n 'configuration-changed', // Configuration schema changed\n 'protocol-changed', // Protocol implementation changed\n ]),\n \n /**\n * What was changed\n */\n description: z.string(),\n \n /**\n * Migration guide\n */\n migrationGuide: z.string().optional().describe('How to migrate from old to new'),\n \n /**\n * Deprecated in version\n */\n deprecatedIn: z.string().optional().describe('Version where old API was deprecated'),\n \n /**\n * Will be removed in version\n */\n removedIn: z.string().optional().describe('Version where old API will be removed'),\n \n /**\n * Automated migration available\n */\n automatedMigration: z.boolean().default(false)\n .describe('Whether automated migration tool is available'),\n \n /**\n * Impact severity\n */\n severity: z.enum(['critical', 'major', 'minor']).describe('Impact severity'),\n});\n\n/**\n * Deprecation Notice\n * Information about deprecated features\n */\nexport const DeprecationNoticeSchema = z.object({\n /**\n * Feature or API being deprecated\n */\n feature: z.string().describe('Deprecated feature identifier'),\n \n /**\n * Version when deprecated\n */\n deprecatedIn: z.string(),\n \n /**\n * Planned removal version\n */\n removeIn: z.string().optional(),\n \n /**\n * Reason for deprecation\n */\n reason: z.string(),\n \n /**\n * Recommended alternative\n */\n alternative: z.string().optional().describe('What to use instead'),\n \n /**\n * Migration path\n */\n migrationPath: z.string().optional().describe('How to migrate to alternative'),\n});\n\n/**\n * Compatibility Matrix Entry\n * Maps compatibility between different plugin versions\n */\nexport const CompatibilityMatrixEntrySchema = z.object({\n /**\n * Source version\n */\n from: z.string().describe('Version being upgraded from'),\n \n /**\n * Target version\n */\n to: z.string().describe('Version being upgraded to'),\n \n /**\n * Compatibility level\n */\n compatibility: CompatibilityLevelSchema,\n \n /**\n * Breaking changes list\n */\n breakingChanges: z.array(BreakingChangeSchema).optional(),\n \n /**\n * Migration required\n */\n migrationRequired: z.boolean().default(false),\n \n /**\n * Migration complexity\n */\n migrationComplexity: z.enum(['trivial', 'simple', 'moderate', 'complex', 'major']).optional(),\n \n /**\n * Estimated migration time in hours\n */\n estimatedMigrationTime: z.number().optional(),\n \n /**\n * Migration script available\n */\n migrationScript: z.string().optional().describe('Path to migration script'),\n \n /**\n * Test coverage for migration\n */\n testCoverage: z.number().min(0).max(100).optional()\n .describe('Percentage of migration covered by tests'),\n});\n\n/**\n * Plugin Compatibility Matrix\n * Complete compatibility information for a plugin\n */\nexport const PluginCompatibilityMatrixSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current version\n */\n currentVersion: z.string(),\n \n /**\n * Compatibility entries\n */\n compatibilityMatrix: z.array(CompatibilityMatrixEntrySchema),\n \n /**\n * Supported versions\n */\n supportedVersions: z.array(z.object({\n version: z.string(),\n supported: z.boolean(),\n endOfLife: z.string().datetime().optional().describe('End of support date'),\n securitySupport: z.boolean().default(false).describe('Still receives security updates'),\n })),\n \n /**\n * Minimum compatible version\n */\n minimumCompatibleVersion: z.string().optional()\n .describe('Oldest version that can be directly upgraded'),\n});\n\n/**\n * Dependency Conflict\n * Represents a conflict in plugin dependencies at the kernel level.\n * Models plugin-to-plugin dependency conflicts with typed conflict categories.\n * \n * @see hub/plugin-security.zod.ts DependencyConflictSchema for hub-level package version conflicts\n * which focuses on marketplace registry resolution.\n */\nexport const DependencyConflictSchema = z.object({\n /**\n * Type of conflict\n */\n type: z.enum([\n 'version-mismatch', // Different versions required\n 'missing-dependency', // Required dependency not found\n 'circular-dependency', // Circular dependency detected\n 'incompatible-versions', // Incompatible versions required by different plugins\n 'conflicting-interfaces', // Plugins implement conflicting interfaces\n ]),\n \n /**\n * Plugins involved in conflict\n */\n plugins: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n requirement: z.string().optional().describe('What this plugin requires'),\n })),\n \n /**\n * Conflict description\n */\n description: z.string(),\n \n /**\n * Possible resolutions\n */\n resolutions: z.array(z.object({\n strategy: z.enum([\n 'upgrade', // Upgrade one or more plugins\n 'downgrade', // Downgrade one or more plugins\n 'replace', // Replace with alternative plugin\n 'disable', // Disable conflicting plugin\n 'manual', // Manual intervention required\n ]),\n description: z.string(),\n automaticResolution: z.boolean().default(false),\n riskLevel: z.enum(['low', 'medium', 'high']),\n })).optional(),\n \n /**\n * Severity of conflict\n */\n severity: z.enum(['critical', 'error', 'warning', 'info']),\n});\n\n/**\n * Dependency Resolution Result\n * Result of dependency resolution process\n */\nexport const PluginDependencyResolutionResultSchema = z.object({\n /**\n * Resolution successful\n */\n success: z.boolean(),\n \n /**\n * Resolved plugin versions\n */\n resolved: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n resolvedVersion: z.string(),\n })).optional(),\n \n /**\n * Conflicts found\n */\n conflicts: z.array(DependencyConflictSchema).optional(),\n \n /**\n * Warnings\n */\n warnings: z.array(z.string()).optional(),\n \n /**\n * Installation order (topologically sorted)\n */\n installationOrder: z.array(z.string()).optional()\n .describe('Plugin IDs in order they should be installed'),\n \n /**\n * Dependency graph\n */\n dependencyGraph: z.record(z.string(), z.array(z.string())).optional()\n .describe('Map of plugin ID to its dependencies'),\n});\n\n/**\n * Multi-Version Support Configuration\n * Allows running multiple versions of a plugin simultaneously\n */\nexport const MultiVersionSupportSchema = z.object({\n /**\n * Enable multi-version support\n */\n enabled: z.boolean().default(false),\n \n /**\n * Maximum concurrent versions\n */\n maxConcurrentVersions: z.number().int().min(1).default(2)\n .describe('How many versions can run at the same time'),\n \n /**\n * Version selection strategy\n */\n selectionStrategy: z.enum([\n 'latest', // Always use latest version\n 'stable', // Use latest stable version\n 'compatible', // Use version compatible with dependencies\n 'pinned', // Use pinned version\n 'canary', // Use canary/preview version\n 'custom', // Custom selection logic\n ]).default('latest'),\n \n /**\n * Version routing rules\n */\n routing: z.array(z.object({\n condition: z.string().describe('Routing condition (e.g., tenant, user, feature flag)'),\n version: z.string().describe('Version to use when condition matches'),\n priority: z.number().int().default(100).describe('Rule priority'),\n })).optional(),\n \n /**\n * Gradual rollout configuration\n */\n rollout: z.object({\n enabled: z.boolean().default(false),\n strategy: z.enum(['percentage', 'blue-green', 'canary']),\n percentage: z.number().min(0).max(100).optional()\n .describe('Percentage of traffic to new version'),\n duration: z.number().int().optional()\n .describe('Rollout duration in milliseconds'),\n }).optional(),\n});\n\n/**\n * Plugin Version Metadata\n * Complete version information for a plugin\n */\nexport const PluginVersionMetadataSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Version number\n */\n version: SemanticVersionSchema,\n \n /**\n * Version string (computed)\n */\n versionString: z.string().describe('Full version string (e.g., 1.2.3-beta.1+build.123)'),\n \n /**\n * Release date\n */\n releaseDate: z.string().datetime(),\n \n /**\n * Release notes\n */\n releaseNotes: z.string().optional(),\n \n /**\n * Breaking changes\n */\n breakingChanges: z.array(BreakingChangeSchema).optional(),\n \n /**\n * Deprecations\n */\n deprecations: z.array(DeprecationNoticeSchema).optional(),\n \n /**\n * Compatibility matrix\n */\n compatibilityMatrix: z.array(CompatibilityMatrixEntrySchema).optional(),\n \n /**\n * Security vulnerabilities fixed\n */\n securityFixes: z.array(z.object({\n cve: z.string().optional().describe('CVE identifier'),\n severity: z.enum(['critical', 'high', 'medium', 'low']),\n description: z.string(),\n fixedIn: z.string().describe('Version where vulnerability was fixed'),\n })).optional(),\n \n /**\n * Download statistics\n */\n statistics: z.object({\n downloads: z.number().int().min(0).optional(),\n installations: z.number().int().min(0).optional(),\n ratings: z.number().min(0).max(5).optional(),\n }).optional(),\n \n /**\n * Support status\n */\n support: z.object({\n status: z.enum(['active', 'maintenance', 'deprecated', 'eol']),\n endOfLife: z.string().datetime().optional(),\n securitySupport: z.boolean().default(true),\n }),\n});\n\n// Export types\nexport type SemanticVersion = z.infer;\nexport type VersionConstraint = z.infer;\nexport type CompatibilityLevel = z.infer;\nexport type BreakingChange = z.infer;\nexport type DeprecationNotice = z.infer;\nexport type CompatibilityMatrixEntry = z.infer;\nexport type PluginCompatibilityMatrix = z.infer;\nexport type DependencyConflict = z.infer;\nexport type PluginDependencyResolutionResult = z.infer;\nexport type MultiVersionSupport = z.infer;\nexport type PluginVersionMetadata = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Service Registry Protocol\n * \n * Zod schemas for service registry data structures.\n * These schemas align with the IServiceRegistry contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n * \n * Note: IServiceRegistry itself is a runtime interface (methods only),\n * so it correctly remains a TypeScript interface. This file contains\n * schemas for configuration and metadata related to service registry.\n */\n\n// ============================================================================\n// Service Metadata Schemas\n// ============================================================================\n\n/**\n * Service Scope Type Enum\n * Different service scoping strategies\n */\nexport const ServiceScopeType = z.enum([\n 'singleton', // Single instance shared across the application\n 'transient', // New instance created each time\n 'scoped', // Instance per scope (request, session, transaction, etc.)\n]).describe('Service scope type');\n\nexport type ServiceScopeType = z.infer;\n\n/**\n * Service Metadata Schema\n * Metadata about a registered service\n * \n * @example\n * {\n * \"name\": \"database\",\n * \"scope\": \"singleton\",\n * \"type\": \"IDataEngine\",\n * \"registeredAt\": 1706659200000\n * }\n */\nexport const ServiceMetadataSchema = z.object({\n /**\n * Service name (unique identifier)\n */\n name: z.string().min(1).describe('Unique service name identifier'),\n \n /**\n * Service scope type\n */\n scope: ServiceScopeType.optional().default('singleton')\n .describe('Service scope type'),\n \n /**\n * Service type or interface name (optional)\n */\n type: z.string().optional().describe('Service type or interface name'),\n \n /**\n * Registration timestamp (Unix milliseconds)\n */\n registeredAt: z.number().int().optional()\n .describe('Unix timestamp in milliseconds when service was registered'),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Additional service-specific metadata'),\n});\n\nexport type ServiceMetadata = z.infer;\n\n// ============================================================================\n// Service Registry Configuration Schemas\n// ============================================================================\n\n/**\n * Service Registry Configuration Schema\n * Configuration for service registry behavior\n * \n * @example\n * {\n * \"strictMode\": true,\n * \"allowOverwrite\": false,\n * \"enableLogging\": true,\n * \"scopeTypes\": [\"singleton\", \"transient\", \"request\", \"session\"]\n * }\n */\nexport const ServiceRegistryConfigSchema = z.object({\n /**\n * Strict mode: throw errors on invalid operations\n * @default true\n */\n strictMode: z.boolean().optional().default(true)\n .describe('Throw errors on invalid operations (duplicate registration, service not found, etc.)'),\n \n /**\n * Allow overwriting existing services\n * @default false\n */\n allowOverwrite: z.boolean().optional().default(false)\n .describe('Allow overwriting existing service registrations'),\n \n /**\n * Enable logging for service operations\n * @default false\n */\n enableLogging: z.boolean().optional().default(false)\n .describe('Enable logging for service registration and retrieval'),\n \n /**\n * Custom scope types (beyond singleton, transient, scoped)\n * @default ['singleton', 'transient', 'scoped']\n */\n scopeTypes: z.array(z.string()).optional()\n .describe('Supported scope types'),\n \n /**\n * Maximum number of services (prevent memory leaks)\n */\n maxServices: z.number().int().min(1).optional()\n .describe('Maximum number of services that can be registered'),\n});\n\nexport type ServiceRegistryConfig = z.infer;\nexport type ServiceRegistryConfigInput = z.input;\n\n// ============================================================================\n// Service Factory Schemas\n// ============================================================================\n\n/**\n * Service Factory Registration Schema\n * Configuration for registering a service factory\n * \n * @example\n * {\n * \"name\": \"logger\",\n * \"scope\": \"singleton\",\n * \"factoryType\": \"sync\"\n * }\n */\nexport const ServiceFactoryRegistrationSchema = z.object({\n /**\n * Service name (unique identifier)\n */\n name: z.string().min(1).describe('Unique service name identifier'),\n \n /**\n * Service scope type\n */\n scope: ServiceScopeType.optional().default('singleton')\n .describe('Service scope type'),\n \n /**\n * Factory type (sync or async)\n */\n factoryType: z.enum(['sync', 'async']).optional().default('sync')\n .describe('Whether factory is synchronous or asynchronous'),\n \n /**\n * Whether this is a singleton (cache factory result)\n */\n singleton: z.boolean().optional().default(true)\n .describe('Whether to cache the factory result (singleton pattern)'),\n});\n\nexport type ServiceFactoryRegistration = z.infer;\n\n// ============================================================================\n// Scoped Service Schemas\n// ============================================================================\n\n/**\n * Scope Configuration Schema\n * Configuration for creating a new scope\n * \n * @example\n * {\n * \"scopeType\": \"request\",\n * \"scopeId\": \"req-12345\",\n * \"metadata\": {\n * \"userId\": \"user-123\",\n * \"requestId\": \"req-12345\"\n * }\n * }\n */\nexport const ScopeConfigSchema = z.object({\n /**\n * Type of scope (request, session, transaction, etc.)\n */\n scopeType: z.string().describe('Type of scope'),\n \n /**\n * Scope identifier (optional, auto-generated if not provided)\n */\n scopeId: z.string().optional().describe('Unique scope identifier'),\n \n /**\n * Scope metadata (context information)\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Scope-specific context metadata'),\n});\n\nexport type ScopeConfig = z.infer;\n\n/**\n * Scope Info Schema\n * Information about an active scope\n * \n * @example\n * {\n * \"scopeId\": \"req-12345\",\n * \"scopeType\": \"request\",\n * \"createdAt\": 1706659200000,\n * \"serviceCount\": 5,\n * \"metadata\": {\n * \"userId\": \"user-123\"\n * }\n * }\n */\nexport const ScopeInfoSchema = z.object({\n /**\n * Scope identifier\n */\n scopeId: z.string().describe('Unique scope identifier'),\n \n /**\n * Type of scope\n */\n scopeType: z.string().describe('Type of scope'),\n \n /**\n * Creation timestamp (Unix milliseconds)\n */\n createdAt: z.number().int().describe('Unix timestamp in milliseconds when scope was created'),\n \n /**\n * Number of services in this scope\n */\n serviceCount: z.number().int().min(0).optional()\n .describe('Number of services registered in this scope'),\n \n /**\n * Scope metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Scope-specific context metadata'),\n});\n\nexport type ScopeInfo = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Startup Orchestrator Protocol\n * \n * Zod schemas for plugin startup orchestration data structures.\n * These schemas align with the IStartupOrchestrator contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Startup Configuration Schemas\n// ============================================================================\n\n/**\n * Startup Options Schema\n * Configuration for plugin startup orchestration\n * \n * @example\n * {\n * \"timeout\": 30000,\n * \"rollbackOnFailure\": true,\n * \"healthCheck\": false,\n * \"parallel\": false\n * }\n */\nexport const StartupOptionsSchema = z.object({\n /**\n * Maximum time (ms) to wait for each plugin to start\n * @default 30000 (30 seconds)\n */\n timeout: z.number().int().min(0).optional().default(30000)\n .describe('Maximum time in milliseconds to wait for each plugin to start'),\n \n /**\n * Whether to rollback (destroy) already-started plugins on failure\n * @default true\n */\n rollbackOnFailure: z.boolean().optional().default(true)\n .describe('Whether to rollback already-started plugins if any plugin fails'),\n \n /**\n * Whether to run health checks after startup\n * @default false\n */\n healthCheck: z.boolean().optional().default(false)\n .describe('Whether to run health checks after plugin startup'),\n \n /**\n * Whether to run plugins in parallel (if dependencies allow)\n * @default false (sequential startup)\n */\n parallel: z.boolean().optional().default(false)\n .describe('Whether to start plugins in parallel when dependencies allow'),\n \n /**\n * Custom context to pass to plugin lifecycle methods\n */\n context: z.unknown().optional().describe('Custom context object to pass to plugin lifecycle methods'),\n});\n\nexport type StartupOptions = z.infer;\nexport type StartupOptionsInput = z.input;\n\n// ============================================================================\n// Health Status Schemas\n// ============================================================================\n\n/**\n * Health Status Schema\n * Health status for a plugin\n * \n * @example\n * {\n * \"healthy\": true,\n * \"timestamp\": 1706659200000,\n * \"details\": {\n * \"databaseConnected\": true,\n * \"memoryUsage\": 45.2\n * }\n * }\n */\nexport const HealthStatusSchema = z.object({\n /**\n * Whether the plugin is healthy\n */\n healthy: z.boolean().describe('Whether the plugin is healthy'),\n \n /**\n * Health check timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds when health check was performed'),\n \n /**\n * Optional health details (plugin-specific)\n */\n details: z.record(z.string(), z.unknown()).optional().describe('Optional plugin-specific health details'),\n \n /**\n * Optional error message if unhealthy\n */\n message: z.string().optional().describe('Error message if plugin is unhealthy'),\n});\n\nexport type HealthStatus = z.infer;\n\n// ============================================================================\n// Startup Result Schemas\n// ============================================================================\n\n/**\n * Plugin Startup Result Schema\n * Result of a single plugin startup operation\n * \n * @example\n * {\n * \"plugin\": { \"name\": \"crm-plugin\", \"version\": \"1.0.0\" },\n * \"success\": true,\n * \"duration\": 1250,\n * \"health\": {\n * \"healthy\": true,\n * \"timestamp\": 1706659200000\n * }\n * }\n */\nexport const PluginStartupResultSchema = z.object({\n /**\n * Plugin that was started\n */\n plugin: z.object({\n name: z.string(),\n version: z.string().optional(),\n }).passthrough().describe('Plugin metadata'),\n \n /**\n * Whether startup was successful\n */\n success: z.boolean().describe('Whether the plugin started successfully'),\n \n /**\n * Time taken to start (milliseconds)\n */\n duration: z.number().min(0).describe('Time taken to start the plugin in milliseconds'),\n \n /**\n * Error if startup failed\n */\n error: z.object({\n name: z.string().describe('Error class name'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n code: z.string().optional().describe('Error code'),\n }).optional().describe('Serializable error representation if startup failed'),\n \n /**\n * Health status after startup (if healthCheck enabled)\n */\n health: HealthStatusSchema.optional().describe('Health status after startup if health check was enabled'),\n});\n\nexport type PluginStartupResult = z.infer;\n\n// ============================================================================\n// Startup Orchestration Result Schema\n// ============================================================================\n\n/**\n * Startup Orchestration Result Schema\n * Overall result of orchestrating startup for multiple plugins\n * \n * @example\n * {\n * \"results\": [\n * { \"plugin\": { \"name\": \"plugin1\" }, \"success\": true, \"duration\": 1200 },\n * { \"plugin\": { \"name\": \"plugin2\" }, \"success\": true, \"duration\": 850 }\n * ],\n * \"totalDuration\": 2050,\n * \"allSuccessful\": true\n * }\n */\nexport const StartupOrchestrationResultSchema = z.object({\n /**\n * Individual plugin startup results\n */\n results: z.array(PluginStartupResultSchema).describe('Startup results for each plugin'),\n \n /**\n * Total time taken for all plugins (milliseconds)\n */\n totalDuration: z.number().min(0).describe('Total time taken for all plugins in milliseconds'),\n \n /**\n * Whether all plugins started successfully\n */\n allSuccessful: z.boolean().describe('Whether all plugins started successfully'),\n \n /**\n * Plugins that were rolled back (if rollbackOnFailure was enabled)\n */\n rolledBack: z.array(z.string()).optional().describe('Names of plugins that were rolled back'),\n});\n\nexport type StartupOrchestrationResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\n\n/**\n * # Plugin Registry Protocol\n * \n * Defines the schema for the plugin discovery and registry system.\n * This enables plugins from different vendors to be discovered, validated,\n * and composed together in the ObjectStack ecosystem.\n */\n\n/**\n * Plugin Vendor Information\n */\nexport const PluginVendorSchema = z.object({\n /**\n * Vendor identifier (reverse domain notation)\n * Example: \"com.acme\", \"org.apache\", \"com.objectstack\"\n */\n id: z.string()\n .regex(/^[a-z][a-z0-9]*(\\.[a-z][a-z0-9]*)+$/)\n .describe('Vendor identifier (reverse domain)'),\n \n /**\n * Vendor display name\n */\n name: z.string(),\n \n /**\n * Vendor website\n */\n website: z.string().url().optional(),\n \n /**\n * Contact email\n */\n email: z.string().email().optional(),\n \n /**\n * Verification status\n */\n verified: z.boolean().default(false).describe('Whether vendor is verified by ObjectStack'),\n \n /**\n * Trust level\n */\n trustLevel: z.enum(['official', 'verified', 'community', 'unverified']).default('unverified'),\n});\n\n/**\n * Plugin Quality Metrics\n */\nexport const PluginQualityMetricsSchema = z.object({\n /**\n * Test coverage percentage\n */\n testCoverage: z.number().min(0).max(100).optional(),\n \n /**\n * Documentation score (0-100)\n */\n documentationScore: z.number().min(0).max(100).optional(),\n \n /**\n * Code quality score (0-100)\n */\n codeQuality: z.number().min(0).max(100).optional(),\n \n /**\n * Security scan status\n */\n securityScan: z.object({\n lastScanDate: z.string().datetime().optional(),\n vulnerabilities: z.object({\n critical: z.number().int().min(0).default(0),\n high: z.number().int().min(0).default(0),\n medium: z.number().int().min(0).default(0),\n low: z.number().int().min(0).default(0),\n }).optional(),\n passed: z.boolean().default(false),\n }).optional(),\n \n /**\n * Conformance test results\n */\n conformanceTests: z.array(z.object({\n protocolId: z.string().describe('Protocol being tested'),\n passed: z.boolean(),\n totalTests: z.number().int().min(0),\n passedTests: z.number().int().min(0),\n lastRunDate: z.string().datetime().optional(),\n })).optional(),\n});\n\n/**\n * Plugin Usage Statistics\n */\nexport const PluginStatisticsSchema = z.object({\n /**\n * Total downloads\n */\n downloads: z.number().int().min(0).default(0),\n \n /**\n * Downloads in the last 30 days\n */\n downloadsLastMonth: z.number().int().min(0).default(0),\n \n /**\n * Number of active installations\n */\n activeInstallations: z.number().int().min(0).default(0),\n \n /**\n * User ratings\n */\n ratings: z.object({\n average: z.number().min(0).max(5).default(0),\n count: z.number().int().min(0).default(0),\n distribution: z.object({\n '5': z.number().int().min(0).default(0),\n '4': z.number().int().min(0).default(0),\n '3': z.number().int().min(0).default(0),\n '2': z.number().int().min(0).default(0),\n '1': z.number().int().min(0).default(0),\n }).optional(),\n }).optional(),\n \n /**\n * GitHub stars (if open source)\n */\n stars: z.number().int().min(0).optional(),\n \n /**\n * Number of dependent plugins\n */\n dependents: z.number().int().min(0).default(0),\n});\n\n/**\n * Plugin Registry Entry\n * Complete metadata for a plugin in the registry.\n */\nexport const PluginRegistryEntrySchema = z.object({\n /**\n * Plugin identifier (must match manifest.id)\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Plugin identifier (reverse domain notation)'),\n \n /**\n * Current version\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/),\n \n /**\n * Plugin display name\n */\n name: z.string(),\n \n /**\n * Short description\n */\n description: z.string().optional(),\n \n /**\n * Detailed documentation/README\n */\n readme: z.string().optional(),\n \n /**\n * Plugin type/category\n */\n category: z.enum([\n 'data', // Data management, storage, databases\n 'integration', // External service integrations\n 'ui', // UI components and themes\n 'analytics', // Analytics and reporting\n 'security', // Security, auth, compliance\n 'automation', // Workflows and automation\n 'ai', // AI/ML capabilities\n 'utility', // General utilities\n 'driver', // Database/storage drivers\n 'gateway', // API gateways\n 'adapter', // Runtime adapters\n ]).optional(),\n \n /**\n * Tags for categorization\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Vendor information\n */\n vendor: PluginVendorSchema,\n \n /**\n * Capability manifest (what the plugin implements/provides)\n */\n capabilities: PluginCapabilityManifestSchema.optional(),\n \n /**\n * Compatibility information\n */\n compatibility: z.object({\n /**\n * Minimum ObjectStack version required\n */\n minObjectStackVersion: z.string().optional(),\n \n /**\n * Maximum ObjectStack version supported\n */\n maxObjectStackVersion: z.string().optional(),\n \n /**\n * Node.js version requirement\n */\n nodeVersion: z.string().optional(),\n \n /**\n * Supported platforms\n */\n platforms: z.array(z.enum(['linux', 'darwin', 'win32', 'browser'])).optional(),\n }).optional(),\n \n /**\n * Links and resources\n */\n links: z.object({\n homepage: z.string().url().optional(),\n repository: z.string().url().optional(),\n documentation: z.string().url().optional(),\n bugs: z.string().url().optional(),\n changelog: z.string().url().optional(),\n }).optional(),\n \n /**\n * Media assets\n */\n media: z.object({\n icon: z.string().url().optional(),\n logo: z.string().url().optional(),\n screenshots: z.array(z.string().url()).optional(),\n video: z.string().url().optional(),\n }).optional(),\n \n /**\n * Quality metrics\n */\n quality: PluginQualityMetricsSchema.optional(),\n \n /**\n * Usage statistics\n */\n statistics: PluginStatisticsSchema.optional(),\n \n /**\n * License information\n */\n license: z.string().optional().describe('SPDX license identifier'),\n \n /**\n * Pricing (if commercial)\n */\n pricing: z.object({\n model: z.enum(['free', 'freemium', 'paid', 'enterprise']),\n price: z.number().min(0).optional(),\n currency: z.string().default('USD').optional(),\n billingPeriod: z.enum(['one-time', 'monthly', 'yearly']).optional(),\n }).optional(),\n \n /**\n * Publication dates\n */\n publishedAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n \n /**\n * Deprecation status\n */\n deprecated: z.boolean().default(false),\n deprecationMessage: z.string().optional(),\n replacedBy: z.string().optional().describe('Plugin ID that replaces this one'),\n \n /**\n * Feature flags\n */\n flags: z.object({\n experimental: z.boolean().default(false),\n beta: z.boolean().default(false),\n featured: z.boolean().default(false),\n verified: z.boolean().default(false),\n }).optional(),\n});\n\n/**\n * Plugin Search Filters\n */\nexport const PluginSearchFiltersSchema = z.object({\n /**\n * Search query\n */\n query: z.string().optional(),\n \n /**\n * Filter by category\n */\n category: z.array(z.string()).optional(),\n \n /**\n * Filter by tags\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Filter by vendor trust level\n */\n trustLevel: z.array(z.enum(['official', 'verified', 'community', 'unverified'])).optional(),\n \n /**\n * Filter by protocols implemented\n */\n implementsProtocols: z.array(z.string()).optional(),\n \n /**\n * Filter by pricing model\n */\n pricingModel: z.array(z.enum(['free', 'freemium', 'paid', 'enterprise'])).optional(),\n \n /**\n * Minimum rating\n */\n minRating: z.number().min(0).max(5).optional(),\n \n /**\n * Sort options\n */\n sortBy: z.enum([\n 'relevance',\n 'downloads',\n 'rating',\n 'updated',\n 'name',\n ]).optional(),\n \n /**\n * Sort order\n */\n sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),\n \n /**\n * Pagination\n */\n page: z.number().int().min(1).default(1).optional(),\n limit: z.number().int().min(1).max(100).default(20).optional(),\n});\n\n/**\n * Plugin Installation Configuration\n */\nexport const PluginInstallConfigSchema = z.object({\n /**\n * Plugin identifier to install\n */\n pluginId: z.string(),\n \n /**\n * Version to install (supports semver ranges)\n */\n version: z.string().optional().describe('Defaults to latest'),\n \n /**\n * Plugin-specific configuration values\n */\n config: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Whether to auto-update\n */\n autoUpdate: z.boolean().default(false).optional(),\n \n /**\n * Installation options\n */\n options: z.object({\n /**\n * Skip dependency installation\n */\n skipDependencies: z.boolean().default(false).optional(),\n \n /**\n * Force reinstall\n */\n force: z.boolean().default(false).optional(),\n \n /**\n * Installation target\n */\n target: z.enum(['system', 'space', 'user']).default('space').optional(),\n }).optional(),\n});\n\n// Export types\nexport type PluginVendor = z.infer;\nexport type PluginVendorInput = z.input;\nexport type PluginQualityMetrics = z.infer;\nexport type PluginQualityMetricsInput = z.input;\nexport type PluginStatistics = z.infer;\nexport type PluginStatisticsInput = z.input;\nexport type PluginRegistryEntry = z.infer;\nexport type PluginRegistryEntryInput = z.input;\nexport type PluginSearchFilters = z.infer;\nexport type PluginSearchFiltersInput = z.input;\nexport type PluginInstallConfig = z.infer;\nexport type PluginInstallConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Security & Dependency Resolution Protocol\n * \n * Provides comprehensive security scanning, vulnerability management,\n * and dependency resolution for the ObjectStack plugin ecosystem.\n * \n * Features:\n * - CVE/vulnerability scanning\n * - Dependency graph resolution\n * - Semantic version conflict detection\n * - Supply chain security\n * - Plugin sandboxing policies\n * - Trust and verification workflows\n */\n\n// ============================================================================\n// Security Scanning\n// ============================================================================\n\n/**\n * Vulnerability Severity\n */\nexport const VulnerabilitySeverity = z.enum([\n 'critical',\n 'high',\n 'medium',\n 'low',\n 'info',\n]).describe('Severity level of a security vulnerability');\n\nexport type VulnerabilitySeverity = z.infer;\n\n/**\n * Security Vulnerability\n */\nexport const SecurityVulnerabilitySchema = z.object({\n /**\n * CVE identifier (if applicable)\n */\n cve: z.string().regex(/^CVE-\\d{4}-\\d+$/).optional().describe('CVE identifier'),\n \n /**\n * Vulnerability identifier (GHSA, SNYK, etc.)\n */\n id: z.string().describe('Vulnerability ID'),\n \n /**\n * Title\n */\n title: z.string().describe('Short title summarizing the vulnerability'),\n \n /**\n * Description\n */\n description: z.string().describe('Detailed description of the vulnerability'),\n \n /**\n * Severity\n */\n severity: VulnerabilitySeverity.describe('Severity level of this vulnerability'),\n \n /**\n * CVSS score (0-10)\n */\n cvss: z.number().min(0).max(10).optional().describe('CVSS score ranging from 0 to 10'),\n \n /**\n * Affected package\n */\n package: z.object({\n name: z.string().describe('Name of the affected package'),\n version: z.string().describe('Version of the affected package'),\n ecosystem: z.string().optional().describe('Package ecosystem (e.g., npm, pip, maven)'),\n }).describe('Affected package information'),\n \n /**\n * Vulnerable version range\n */\n vulnerableVersions: z.string().describe('Semver range of vulnerable versions'),\n \n /**\n * Patched versions\n */\n patchedVersions: z.string().optional().describe('Semver range of patched versions'),\n \n /**\n * References\n */\n references: z.array(z.object({\n type: z.enum(['advisory', 'article', 'report', 'web']).describe('Type of reference source'),\n url: z.string().url().describe('URL of the reference'),\n })).default([]).describe('External references related to the vulnerability'),\n \n /**\n * CWE (Common Weakness Enumeration)\n */\n cwe: z.array(z.string()).default([]).describe('CWE identifiers associated with this vulnerability'),\n \n /**\n * Published date\n */\n publishedAt: z.string().datetime().optional().describe('ISO 8601 date when the vulnerability was published'),\n \n /**\n * Mitigation advice\n */\n mitigation: z.string().optional().describe('Recommended steps to mitigate the vulnerability'),\n}).describe('A known security vulnerability in a package dependency');\n\nexport type SecurityVulnerability = z.infer;\n\n/**\n * Security Scan Result\n */\nexport const SecurityScanResultSchema = z.object({\n /**\n * Scan identifier\n */\n scanId: z.string().uuid().describe('Unique identifier for this security scan'),\n \n /**\n * Plugin being scanned\n */\n plugin: z.object({\n id: z.string().describe('Plugin identifier'),\n version: z.string().describe('Plugin version that was scanned'),\n }).describe('Plugin that was scanned'),\n \n /**\n * Scan timestamp\n */\n scannedAt: z.string().datetime().describe('ISO 8601 timestamp when the scan was performed'),\n \n /**\n * Scanner information\n */\n scanner: z.object({\n name: z.string().describe('Scanner name (e.g., snyk, osv, trivy)'),\n version: z.string().describe('Version of the scanner tool'),\n }).describe('Information about the scanner tool used'),\n \n /**\n * Scan status\n */\n status: z.enum(['passed', 'failed', 'warning']).describe('Overall result status of the security scan'),\n \n /**\n * Vulnerabilities found\n */\n vulnerabilities: z.array(SecurityVulnerabilitySchema).describe('List of vulnerabilities discovered during the scan'),\n \n /**\n * Vulnerability summary\n */\n summary: z.object({\n critical: z.number().int().min(0).default(0).describe('Count of critical severity vulnerabilities'),\n high: z.number().int().min(0).default(0).describe('Count of high severity vulnerabilities'),\n medium: z.number().int().min(0).default(0).describe('Count of medium severity vulnerabilities'),\n low: z.number().int().min(0).default(0).describe('Count of low severity vulnerabilities'),\n info: z.number().int().min(0).default(0).describe('Count of informational severity vulnerabilities'),\n total: z.number().int().min(0).default(0).describe('Total count of all vulnerabilities'),\n }).describe('Summary counts of vulnerabilities by severity'),\n \n /**\n * License compliance issues\n */\n licenseIssues: z.array(z.object({\n package: z.string().describe('Name of the package with a license issue'),\n license: z.string().describe('License identifier of the package'),\n reason: z.string().describe('Reason the license is flagged'),\n severity: z.enum(['error', 'warning', 'info']).describe('Severity of the license compliance issue'),\n })).default([]).describe('License compliance issues found during the scan'),\n \n /**\n * Code quality issues\n */\n codeQuality: z.object({\n score: z.number().min(0).max(100).optional().describe('Overall code quality score from 0 to 100'),\n issues: z.array(z.object({\n type: z.enum(['security', 'quality', 'style']).describe('Category of the code quality issue'),\n severity: z.enum(['error', 'warning', 'info']).describe('Severity of the code quality issue'),\n message: z.string().describe('Description of the code quality issue'),\n file: z.string().optional().describe('File path where the issue was found'),\n line: z.number().int().optional().describe('Line number where the issue was found'),\n })).default([]).describe('List of individual code quality issues'),\n }).optional().describe('Code quality analysis results'),\n \n /**\n * Next scan scheduled\n */\n nextScanAt: z.string().datetime().optional().describe('ISO 8601 timestamp for the next scheduled scan'),\n}).describe('Result of a security scan performed on a plugin');\n\nexport type SecurityScanResult = z.infer;\n\n/**\n * Security Policy\n */\nexport const SecurityPolicySchema = z.object({\n /**\n * Policy identifier\n */\n id: z.string().describe('Unique identifier for the security policy'),\n \n /**\n * Policy name\n */\n name: z.string().describe('Human-readable name of the security policy'),\n \n /**\n * Automatic scanning\n */\n autoScan: z.object({\n enabled: z.boolean().default(true).describe('Whether automatic scanning is enabled'),\n frequency: z.enum(['on-publish', 'daily', 'weekly', 'monthly']).default('daily').describe('How often automatic scans are performed'),\n }).describe('Automatic security scanning configuration'),\n \n /**\n * Vulnerability thresholds\n */\n thresholds: z.object({\n /**\n * Block plugin if critical vulnerabilities exceed this\n */\n maxCritical: z.number().int().min(0).default(0).describe('Maximum allowed critical vulnerabilities before blocking'),\n \n /**\n * Block plugin if high vulnerabilities exceed this\n */\n maxHigh: z.number().int().min(0).default(0).describe('Maximum allowed high vulnerabilities before blocking'),\n \n /**\n * Warn if medium vulnerabilities exceed this\n */\n maxMedium: z.number().int().min(0).default(5).describe('Maximum allowed medium vulnerabilities before warning'),\n }).describe('Vulnerability count thresholds for policy enforcement'),\n \n /**\n * Allowed licenses\n */\n allowedLicenses: z.array(z.string()).default([\n 'MIT',\n 'Apache-2.0',\n 'BSD-3-Clause',\n 'BSD-2-Clause',\n 'ISC',\n ]).describe('List of SPDX license identifiers that are permitted'),\n \n /**\n * Prohibited licenses\n */\n prohibitedLicenses: z.array(z.string()).default([\n 'GPL-3.0',\n 'AGPL-3.0',\n ]).describe('List of SPDX license identifiers that are prohibited'),\n \n /**\n * Code signing requirements\n */\n codeSigning: z.object({\n required: z.boolean().default(false).describe('Whether code signing is required for plugins'),\n allowedSigners: z.array(z.string()).default([]).describe('List of trusted signer identities'),\n }).optional().describe('Code signing requirements for plugin artifacts'),\n \n /**\n * Sandbox restrictions\n */\n sandbox: z.object({\n /**\n * Restrict network access\n */\n networkAccess: z.enum(['none', 'localhost', 'allowlist', 'all']).default('all').describe('Level of network access granted to the plugin'),\n \n /**\n * Allowed network destinations (if allowlist)\n */\n allowedDestinations: z.array(z.string()).default([]).describe('Permitted network destinations when using allowlist mode'),\n \n /**\n * File system access\n */\n filesystemAccess: z.enum(['none', 'read-only', 'temp-only', 'full']).default('full').describe('Level of file system access granted to the plugin'),\n \n /**\n * Maximum memory (MB)\n */\n maxMemoryMB: z.number().int().positive().optional().describe('Maximum memory allocation in megabytes'),\n \n /**\n * Maximum CPU time (seconds)\n */\n maxCPUSeconds: z.number().int().positive().optional().describe('Maximum CPU time allowed in seconds'),\n }).optional().describe('Sandbox restrictions for plugin execution'),\n}).describe('Security policy governing plugin scanning and enforcement');\n\nexport type SecurityPolicy = z.infer;\n\n// ============================================================================\n// Dependency Resolution\n// ============================================================================\n\n/**\n * Package Dependency\n */\nexport const PackageDependencySchema = z.object({\n /**\n * Package name/ID\n */\n name: z.string().describe('Package name or identifier'),\n \n /**\n * Version constraint (semver range)\n */\n versionConstraint: z.string().describe('Semver range (e.g., `^1.0.0`, `>=2.0.0 <3.0.0`)'),\n \n /**\n * Dependency type\n */\n type: z.enum(['required', 'optional', 'peer', 'dev']).default('required').describe('Category of the dependency relationship'),\n \n /**\n * Resolved version (filled during resolution)\n */\n resolvedVersion: z.string().optional().describe('Concrete version resolved during dependency resolution'),\n}).describe('A package dependency with its version constraint');\n\nexport type PackageDependency = z.infer;\n\n/**\n * Dependency Graph Node\n */\nexport const DependencyGraphNodeSchema = z.object({\n /**\n * Package identifier\n */\n id: z.string().describe('Unique identifier of the package'),\n \n /**\n * Package version\n */\n version: z.string().describe('Resolved version of the package'),\n \n /**\n * Dependencies of this package\n */\n dependencies: z.array(PackageDependencySchema).default([]).describe('Dependencies required by this package'),\n \n /**\n * Depth in dependency tree\n */\n depth: z.number().int().min(0).describe('Depth level in the dependency tree (0 = root)'),\n \n /**\n * Whether this is a direct dependency\n */\n isDirect: z.boolean().describe('Whether this is a direct (top-level) dependency'),\n \n /**\n * Package metadata\n */\n metadata: z.object({\n name: z.string().describe('Display name of the package'),\n description: z.string().optional().describe('Short description of the package'),\n license: z.string().optional().describe('SPDX license identifier of the package'),\n homepage: z.string().url().optional().describe('Homepage URL of the package'),\n }).optional().describe('Additional metadata about the package'),\n}).describe('A node in the dependency graph representing a resolved package');\n\nexport type DependencyGraphNode = z.infer;\n\n/**\n * Dependency Graph\n */\nexport const DependencyGraphSchema = z.object({\n /**\n * Root package\n */\n root: z.object({\n id: z.string().describe('Identifier of the root package'),\n version: z.string().describe('Version of the root package'),\n }).describe('Root package of the dependency graph'),\n \n /**\n * All nodes in the graph\n */\n nodes: z.array(DependencyGraphNodeSchema).describe('All resolved package nodes in the dependency graph'),\n \n /**\n * Edges (dependency relationships)\n */\n edges: z.array(z.object({\n from: z.string().describe('Package ID'),\n to: z.string().describe('Package ID'),\n constraint: z.string().describe('Version constraint'),\n })).describe('Directed edges representing dependency relationships'),\n \n /**\n * Resolution statistics\n */\n stats: z.object({\n totalDependencies: z.number().int().min(0).describe('Total number of resolved dependencies'),\n directDependencies: z.number().int().min(0).describe('Number of direct (top-level) dependencies'),\n maxDepth: z.number().int().min(0).describe('Maximum depth of the dependency tree'),\n }).describe('Summary statistics for the dependency graph'),\n}).describe('Complete dependency graph for a package and its transitive dependencies');\n\nexport type DependencyGraph = z.infer;\n\n/**\n * Dependency Conflict\n * \n * Hub-level dependency conflict detected during plugin resolution.\n * Focuses on package version conflicts across the marketplace/registry.\n * \n * @see kernel/plugin-versioning.zod.ts DependencyConflictSchema for kernel-level plugin conflicts\n * which models plugin-to-plugin conflicts with richer resolution strategies.\n */\nexport const PackageDependencyConflictSchema = z.object({\n /**\n * Package with conflict\n */\n package: z.string().describe('Name of the package with conflicting version requirements'),\n \n /**\n * Conflicting versions\n */\n conflicts: z.array(z.object({\n version: z.string().describe('Conflicting version of the package'),\n requestedBy: z.array(z.string()).describe('Packages that require this version'),\n constraint: z.string().describe('Semver constraint that produced this version requirement'),\n })).describe('List of conflicting version requirements'),\n \n /**\n * Suggested resolution\n */\n resolution: z.object({\n strategy: z.enum(['pick-highest', 'pick-lowest', 'manual']).describe('Strategy used to resolve the conflict'),\n version: z.string().optional().describe('Resolved version selected by the strategy'),\n reason: z.string().optional().describe('Explanation of why this resolution was chosen'),\n }).optional().describe('Suggested resolution for the conflict'),\n \n /**\n * Severity\n */\n severity: z.enum(['error', 'warning', 'info']).describe('Severity level of the dependency conflict'),\n}).describe('A detected conflict between dependency version requirements');\n\nexport type PackageDependencyConflict = z.infer;\n\n/**\n * Dependency Resolution Result\n */\nexport const PackageDependencyResolutionResultSchema = z.object({\n /**\n * Resolution status\n */\n status: z.enum(['success', 'conflict', 'error']).describe('Overall status of the dependency resolution'),\n \n /**\n * Resolved dependency graph\n */\n graph: DependencyGraphSchema.optional().describe('Resolved dependency graph if resolution succeeded'),\n \n /**\n * Conflicts detected\n */\n conflicts: z.array(PackageDependencyConflictSchema).default([]).describe('List of dependency conflicts detected during resolution'),\n \n /**\n * Errors encountered\n */\n errors: z.array(z.object({\n package: z.string().describe('Name of the package that caused the error'),\n error: z.string().describe('Error message describing what went wrong'),\n })).default([]).describe('Errors encountered during dependency resolution'),\n \n /**\n * Installation order (topological sort)\n */\n installOrder: z.array(z.string()).default([]).describe('Topologically sorted list of package IDs for installation'),\n \n /**\n * Resolution time (ms)\n */\n resolvedIn: z.number().int().min(0).optional().describe('Time taken to resolve dependencies in milliseconds'),\n}).describe('Result of a dependency resolution process');\n\nexport type PackageDependencyResolutionResult = z.infer;\n\n// ============================================================================\n// Supply Chain Security\n// ============================================================================\n\n/**\n * SBOM (Software Bill of Materials) Entry\n */\nexport const SBOMEntrySchema = z.object({\n /**\n * Component name\n */\n name: z.string().describe('Name of the software component'),\n \n /**\n * Component version\n */\n version: z.string().describe('Version of the software component'),\n \n /**\n * Package URL (purl)\n */\n purl: z.string().optional().describe('Package URL identifier'),\n \n /**\n * License\n */\n license: z.string().optional().describe('SPDX license identifier of the component'),\n \n /**\n * Hashes\n */\n hashes: z.object({\n sha256: z.string().optional().describe('SHA-256 hash of the component artifact'),\n sha512: z.string().optional().describe('SHA-512 hash of the component artifact'),\n }).optional().describe('Cryptographic hashes for integrity verification'),\n \n /**\n * Supplier\n */\n supplier: z.object({\n name: z.string().describe('Name of the component supplier'),\n url: z.string().url().optional().describe('URL of the component supplier'),\n }).optional().describe('Supplier information for the component'),\n \n /**\n * External references\n */\n externalRefs: z.array(z.object({\n type: z.enum(['website', 'repository', 'documentation', 'issue-tracker']).describe('Type of external reference'),\n url: z.string().url().describe('URL of the external reference'),\n })).default([]).describe('External references related to the component'),\n}).describe('A single entry in a Software Bill of Materials');\n\nexport type SBOMEntry = z.infer;\n\n/**\n * Software Bill of Materials (SBOM)\n */\nexport const SBOMSchema = z.object({\n /**\n * SBOM format\n */\n format: z.enum(['spdx', 'cyclonedx']).default('cyclonedx').describe('SBOM standard format used'),\n \n /**\n * SBOM version\n */\n version: z.string().describe('Version of the SBOM specification'),\n \n /**\n * Plugin metadata\n */\n plugin: z.object({\n id: z.string().describe('Plugin identifier'),\n version: z.string().describe('Plugin version'),\n name: z.string().describe('Human-readable plugin name'),\n }).describe('Metadata about the plugin this SBOM describes'),\n \n /**\n * Components (dependencies)\n */\n components: z.array(SBOMEntrySchema).describe('List of software components included in the plugin'),\n \n /**\n * Generation timestamp\n */\n generatedAt: z.string().datetime().describe('ISO 8601 timestamp when the SBOM was generated'),\n \n /**\n * Generator tool\n */\n generator: z.object({\n name: z.string().describe('Name of the SBOM generator tool'),\n version: z.string().describe('Version of the SBOM generator tool'),\n }).optional().describe('Tool used to generate this SBOM'),\n}).describe('Software Bill of Materials for a plugin');\n\nexport type SBOM = z.infer;\n\n/**\n * Plugin Provenance\n * Verifiable chain of custody for plugin artifacts\n */\nexport const PluginProvenanceSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string().describe('Unique identifier of the plugin'),\n \n /**\n * Plugin version\n */\n version: z.string().describe('Version of the plugin artifact'),\n \n /**\n * Build information\n */\n build: z.object({\n /**\n * Build timestamp\n */\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the build was produced'),\n \n /**\n * Build environment\n */\n environment: z.object({\n os: z.string().describe('Operating system used for the build'),\n arch: z.string().describe('CPU architecture used for the build'),\n nodeVersion: z.string().describe('Node.js version used for the build'),\n }).optional().describe('Environment details where the build was executed'),\n \n /**\n * Source repository\n */\n source: z.object({\n repository: z.string().url().describe('URL of the source repository'),\n commit: z.string().regex(/^[a-f0-9]{40}$/).describe('Full SHA-1 commit hash of the source'),\n branch: z.string().optional().describe('Branch name the build was produced from'),\n tag: z.string().optional().describe('Git tag associated with the build'),\n }).optional().describe('Source repository information for the build'),\n \n /**\n * Builder identity\n */\n builder: z.object({\n name: z.string().describe('Name of the person or system that produced the build'),\n email: z.string().email().optional().describe('Email address of the builder'),\n }).optional().describe('Identity of the builder who produced the artifact'),\n }).describe('Build provenance information'),\n \n /**\n * Artifact hashes\n */\n artifacts: z.array(z.object({\n filename: z.string().describe('Name of the artifact file'),\n sha256: z.string().describe('SHA-256 hash of the artifact'),\n size: z.number().int().positive().describe('Size of the artifact in bytes'),\n })).describe('List of build artifacts with integrity hashes'),\n \n /**\n * Signatures\n */\n signatures: z.array(z.object({\n algorithm: z.enum(['rsa', 'ecdsa', 'ed25519']).describe('Cryptographic algorithm used for signing'),\n publicKey: z.string().describe('Public key used to verify the signature'),\n signature: z.string().describe('Digital signature value'),\n signedBy: z.string().describe('Identity of the signer'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the signature was created'),\n })).default([]).describe('Cryptographic signatures for the plugin artifact'),\n \n /**\n * Attestations\n */\n attestations: z.array(z.object({\n type: z.enum(['code-review', 'security-scan', 'test-results', 'ci-build']).describe('Type of attestation'),\n status: z.enum(['passed', 'failed']).describe('Result status of the attestation'),\n url: z.string().url().optional().describe('URL with details about the attestation'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the attestation was issued'),\n })).default([]).describe('Verification attestations for the plugin'),\n}).describe('Verifiable provenance and chain of custody for a plugin artifact');\n\nexport type PluginProvenance = z.infer;\n\n// ============================================================================\n// Trust & Verification\n// ============================================================================\n\n/**\n * Plugin Trust Score\n */\nexport const PluginTrustScoreSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string().describe('Unique identifier of the plugin'),\n \n /**\n * Overall trust score (0-100)\n */\n score: z.number().min(0).max(100).describe('Overall trust score from 0 to 100'),\n \n /**\n * Score components\n */\n components: z.object({\n /**\n * Vendor reputation (0-100)\n */\n vendorReputation: z.number().min(0).max(100).describe('Vendor reputation score from 0 to 100'),\n \n /**\n * Security scan results (0-100)\n */\n securityScore: z.number().min(0).max(100).describe('Security scan results score from 0 to 100'),\n \n /**\n * Code quality (0-100)\n */\n codeQuality: z.number().min(0).max(100).describe('Code quality score from 0 to 100'),\n \n /**\n * Community engagement (0-100)\n */\n communityScore: z.number().min(0).max(100).describe('Community engagement score from 0 to 100'),\n \n /**\n * Update frequency (0-100)\n */\n maintenanceScore: z.number().min(0).max(100).describe('Maintenance and update frequency score from 0 to 100'),\n }).describe('Individual score components contributing to the overall trust score'),\n \n /**\n * Trust level\n */\n level: z.enum(['verified', 'trusted', 'neutral', 'untrusted', 'blocked']).describe('Computed trust level based on the overall score'),\n \n /**\n * Verification badges\n */\n badges: z.array(z.enum([\n 'official', // Official ObjectStack plugin\n 'verified-vendor', // Verified vendor\n 'security-scanned', // Passed security scan\n 'code-signed', // Digitally signed\n 'open-source', // Open source\n 'popular', // High downloads\n ])).default([]).describe('Verification badges earned by the plugin'),\n \n /**\n * Last updated\n */\n updatedAt: z.string().datetime().describe('ISO 8601 timestamp when the trust score was last updated'),\n}).describe('Trust score and verification status for a plugin');\n\nexport type PluginTrustScore = z.infer;\n\n// ============================================================================\n// Export All\n// ============================================================================\n\nexport const PluginSecurityProtocol = {\n VulnerabilitySeverity,\n SecurityVulnerability: SecurityVulnerabilitySchema,\n SecurityScanResult: SecurityScanResultSchema,\n SecurityPolicy: SecurityPolicySchema,\n PackageDependency: PackageDependencySchema,\n DependencyGraphNode: DependencyGraphNodeSchema,\n DependencyGraph: DependencyGraphSchema,\n DependencyConflict: PackageDependencyConflictSchema,\n DependencyResolutionResult: PackageDependencyResolutionResultSchema,\n SBOMEntry: SBOMEntrySchema,\n SBOM: SBOMSchema,\n PluginProvenance: PluginProvenanceSchema,\n PluginTrustScore: PluginTrustScoreSchema,\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Cloud Protocol\n *\n * Cloud-specific protocols for the ObjectStack SaaS platform.\n * These schemas define the contract for cloud services like:\n * - Marketplace (listing, publishing, review, search, install)\n * - Developer Portal (developer registration, API keys, publishing analytics)\n * - Marketplace Administration (review workflow, curation, governance)\n * - App Store (customer experience: reviews, recommendations, subscriptions)\n * - Future: Composer, Space, Hub Federation\n */\nexport * from './marketplace.zod';\nexport * from './developer-portal.zod';\nexport * from './marketplace-admin.zod';\nexport * from './app-store.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Marketplace Protocol\n * \n * Defines the core schemas for the plugin marketplace ecosystem, covering:\n * - **Developer Side**: Package publishing, submission, and version releases\n * - **Platform Side**: Marketplace listing, review, approval, and discovery\n * \n * This protocol defines the contract between plugin developers, the marketplace\n * platform, and customers who install plugins.\n * \n * ## Architecture Alignment\n * - **Salesforce AppExchange**: Security review, managed packages, listing profiles\n * - **VS Code Marketplace**: Extension publishing, ratings, verified publishers\n * - **npm Registry**: Package publishing, versioning, scoped packages\n * - **Shopify App Store**: App review process, billing integration, merchant installs\n * \n * ## Developer Publishing Flow\n * ```\n * 1. Develop → Build plugin locally using ObjectStack CLI\n * 2. Validate → Run `os plugin validate` (schema + security checks)\n * 3. Build → Run `os plugin build` (bundle + sign)\n * 4. Submit → Run `os plugin publish` (submit to marketplace)\n * 5. Review → Platform conducts automated + manual review\n * 6. Publish → Approved listing goes live on marketplace\n * ```\n * \n * ## Platform Management Flow\n * ```\n * 1. Receive → Accept submissions from verified publishers\n * 2. Scan → Automated security scan and compatibility check\n * 3. Review → Human review for quality and policy compliance\n * 4. Catalog → Index in marketplace search catalog\n * 5. Monitor → Track installs, ratings, issues, and enforce SLAs\n * ```\n */\n\n// ==========================================\n// Publisher Identity\n// ==========================================\n\n/**\n * Publisher Verification Status\n */\nexport const PublisherVerificationSchema = z.enum([\n 'unverified', // Not yet verified\n 'pending', // Verification in progress\n 'verified', // Identity verified by platform\n 'trusted', // Trusted publisher (track record of quality)\n 'partner', // Official platform partner\n]).describe('Publisher verification status');\n\n/**\n * Publisher Schema\n * Represents a developer or organization that publishes packages.\n */\nexport const PublisherSchema = z.object({\n /** Publisher unique identifier */\n id: z.string().describe('Publisher ID'),\n\n /** Display name */\n name: z.string().describe('Publisher display name'),\n\n /** Publisher type */\n type: z.enum(['individual', 'organization']).describe('Publisher type'),\n\n /** Verification status */\n verification: PublisherVerificationSchema.default('unverified')\n .describe('Publisher verification status'),\n\n /** Contact email */\n email: z.string().email().optional().describe('Contact email'),\n\n /** Website URL */\n website: z.string().url().optional().describe('Publisher website'),\n\n /** Organization logo URL */\n logoUrl: z.string().url().optional().describe('Publisher logo URL'),\n\n /** Short description/bio */\n description: z.string().optional().describe('Publisher description'),\n\n /** Registration date */\n registeredAt: z.string().datetime().optional()\n .describe('Publisher registration timestamp'),\n}).describe('Developer or organization that publishes packages');\n\n// ==========================================\n// Artifact Reference & Distribution\n// ==========================================\n\n/**\n * Artifact Reference Schema\n *\n * Points to a downloadable package artifact with integrity verification.\n * Used in marketplace listings and install workflows.\n */\nexport const ArtifactReferenceSchema = z.object({\n /** Artifact download URL */\n url: z.string().url().describe('Artifact download URL'),\n\n /** SHA256 integrity checksum */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA256 checksum'),\n\n /** File size in bytes */\n size: z.number().int().positive().describe('Artifact size in bytes'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz').describe('Artifact format'),\n\n /** Upload timestamp */\n uploadedAt: z.string().datetime().describe('Upload timestamp'),\n}).describe('Reference to a downloadable package artifact');\n\nexport type ArtifactReference = z.infer;\n\n/**\n * Artifact Download Response Schema\n *\n * Response from the artifact download API endpoint.\n * Provides a time-limited download URL with integrity metadata.\n */\nexport const ArtifactDownloadResponseSchema = z.object({\n /** Pre-signed or direct download URL */\n downloadUrl: z.string().url().describe('Artifact download URL (may be pre-signed)'),\n\n /** SHA256 checksum for download verification */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA256 checksum for verification'),\n\n /** File size in bytes */\n size: z.number().int().positive().describe('Artifact size in bytes'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).describe('Artifact format'),\n\n /** URL expiration time (for pre-signed URLs) */\n expiresAt: z.string().datetime().optional()\n .describe('URL expiration timestamp for pre-signed URLs'),\n}).describe('Artifact download response with integrity metadata');\n\nexport type ArtifactDownloadResponse = z.infer;\n\n// ==========================================\n// Marketplace Listing\n// ==========================================\n\n/**\n * Marketplace Category\n */\nexport const MarketplaceCategorySchema = z.enum([\n 'crm', // Customer Relationship Management\n 'erp', // Enterprise Resource Planning\n 'hr', // Human Resources\n 'finance', // Finance & Accounting\n 'project', // Project Management\n 'collaboration', // Collaboration & Communication\n 'analytics', // Analytics & Reporting\n 'integration', // Integrations & Connectors\n 'automation', // Automation & Workflows\n 'ai', // AI & Machine Learning\n 'security', // Security & Compliance\n 'developer-tools', // Developer Tools\n 'ui-theme', // UI Themes & Appearance\n 'storage', // Storage & Drivers\n 'other', // Other / Uncategorized\n]).describe('Marketplace package category');\n\n/**\n * Listing Status\n */\nexport const ListingStatusSchema = z.enum([\n 'draft', // Not yet submitted\n 'submitted', // Submitted for review\n 'in-review', // Under review\n 'approved', // Approved, ready to publish\n 'published', // Live on marketplace\n 'rejected', // Review rejected\n 'suspended', // Suspended by platform (policy violation)\n 'deprecated', // Deprecated by publisher\n 'unlisted', // Available by direct link only\n]).describe('Marketplace listing status');\n\n/**\n * Pricing Model\n */\nexport const PricingModelSchema = z.enum([\n 'free', // Free to install\n 'freemium', // Free with paid premium features\n 'paid', // Requires purchase\n 'subscription', // Recurring subscription\n 'usage-based', // Pay per usage\n 'contact-sales', // Enterprise pricing, contact for quote\n]).describe('Package pricing model');\n\n/**\n * Marketplace Listing Schema\n * \n * The public-facing profile of a package on the marketplace.\n * Contains marketing information, pricing, and installation metadata.\n */\nexport const MarketplaceListingSchema = z.object({\n /** Listing ID (matches package ID) */\n id: z.string().describe('Listing ID (matches package manifest ID)'),\n\n /** Package ID (reverse domain notation) */\n packageId: z.string().describe('Package identifier'),\n\n /** Publisher information */\n publisherId: z.string().describe('Publisher ID'),\n\n /** Current listing status */\n status: ListingStatusSchema.default('draft')\n .describe('Publication state: draft, published, under-review, suspended, deprecated, or unlisted'),\n\n /** Display name */\n name: z.string().describe('Display name'),\n\n /** Tagline (short description for cards/search results) */\n tagline: z.string().max(120).optional().describe('Short tagline (max 120 chars)'),\n\n /** Full description (supports Markdown) */\n description: z.string().optional().describe('Full description (Markdown)'),\n\n /** Category */\n category: MarketplaceCategorySchema.describe('Package category'),\n\n /** Additional tags for search discovery */\n tags: z.array(z.string()).optional().describe('Search tags'),\n\n /** Icon/logo URL */\n iconUrl: z.string().url().optional().describe('Package icon URL'),\n\n /** Screenshot URLs */\n screenshots: z.array(z.object({\n url: z.string().url(),\n caption: z.string().optional(),\n })).optional().describe('Screenshots'),\n\n /** Documentation URL */\n documentationUrl: z.string().url().optional()\n .describe('Documentation URL'),\n\n /** Support URL */\n supportUrl: z.string().url().optional()\n .describe('Support URL'),\n\n /** Source repository URL (if open source) */\n repositoryUrl: z.string().url().optional()\n .describe('Source repository URL'),\n\n /** Pricing model */\n pricing: PricingModelSchema.default('free')\n .describe('Pricing model'),\n\n /** Price in cents (if paid) */\n priceInCents: z.number().int().min(0).optional()\n .describe('Price in cents (e.g. 999 = $9.99)'),\n\n /** Latest published version */\n latestVersion: z.string().describe('Latest published version'),\n\n /** Minimum platform version required */\n minPlatformVersion: z.string().optional()\n .describe('Minimum ObjectStack platform version'),\n\n /** Available versions for installation */\n versions: z.array(z.object({\n version: z.string().describe('Version string'),\n releaseDate: z.string().datetime().describe('Release date'),\n releaseNotes: z.string().optional().describe('Release notes'),\n minPlatformVersion: z.string().optional().describe('Minimum platform version'),\n deprecated: z.boolean().default(false).describe('Whether this version is deprecated'),\n /** Artifact reference for this version */\n artifact: ArtifactReferenceSchema.optional()\n .describe('Downloadable artifact for this version'),\n })).optional().describe('Published versions'),\n\n /** Aggregate statistics */\n stats: z.object({\n totalInstalls: z.number().int().min(0).default(0).describe('Total installs'),\n activeInstalls: z.number().int().min(0).default(0).describe('Active installs'),\n averageRating: z.number().min(0).max(5).optional().describe('Average user rating (0-5)'),\n totalRatings: z.number().int().min(0).default(0).describe('Total ratings count'),\n totalReviews: z.number().int().min(0).default(0).describe('Total reviews count'),\n }).optional().describe('Aggregate marketplace statistics'),\n\n /** First published date */\n publishedAt: z.string().datetime().optional()\n .describe('First published timestamp'),\n\n /** Last updated date */\n updatedAt: z.string().datetime().optional()\n .describe('Last updated timestamp'),\n}).describe('Public-facing package listing on the marketplace');\n\n// ==========================================\n// Package Submission & Review\n// ==========================================\n\n/**\n * Package Submission Schema\n * A developer's submission of a package version for marketplace review.\n */\nexport const PackageSubmissionSchema = z.object({\n /** Submission ID */\n id: z.string().describe('Submission ID'),\n\n /** Package ID */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being submitted */\n version: z.string().describe('Version being submitted'),\n\n /** Publisher ID */\n publisherId: z.string().describe('Publisher submitting'),\n\n /** Submission status */\n status: z.enum([\n 'pending', // Awaiting review\n 'scanning', // Automated scan in progress\n 'in-review', // Under manual review\n 'changes-requested', // Reviewer requests changes\n 'approved', // Approved for publishing\n 'rejected', // Rejected\n ]).default('pending').describe('Review status'),\n\n /**\n * Package artifact URL or reference.\n * Points to the built package bundle for review.\n */\n artifactUrl: z.string().describe('Package artifact URL for review'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional().describe('Release notes for this version'),\n\n /** Whether this is the first submission (new listing) vs version update */\n isNewListing: z.boolean().default(false).describe('Whether this is a new listing submission'),\n\n /** Automated scan results */\n scanResults: z.object({\n /** Whether automated scan passed */\n passed: z.boolean(),\n /** Security scan score (0-100) */\n securityScore: z.number().min(0).max(100).optional(),\n /** Compatibility check passed */\n compatibilityCheck: z.boolean().optional(),\n /** Issues found during scan */\n issues: z.array(z.object({\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),\n message: z.string(),\n file: z.string().optional(),\n line: z.number().optional(),\n })).optional(),\n }).optional().describe('Automated scan results'),\n\n /** Reviewer notes (from platform reviewer) */\n reviewerNotes: z.string().optional().describe('Notes from the platform reviewer'),\n\n /** Submitted timestamp */\n submittedAt: z.string().datetime().optional().describe('Submission timestamp'),\n\n /** Review completed timestamp */\n reviewedAt: z.string().datetime().optional().describe('Review completion timestamp'),\n}).describe('Developer submission of a package version for review');\n\n// ==========================================\n// Marketplace Search & Discovery\n// ==========================================\n\n/**\n * Marketplace Search Request\n */\nexport const MarketplaceSearchRequestSchema = z.object({\n /** Search query string */\n query: z.string().optional().describe('Full-text search query'),\n\n /** Filter by category */\n category: MarketplaceCategorySchema.optional().describe('Filter by category'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Filter by pricing model */\n pricing: PricingModelSchema.optional().describe('Filter by pricing model'),\n\n /** Filter by publisher verification level */\n publisherVerification: PublisherVerificationSchema.optional()\n .describe('Filter by publisher verification level'),\n\n /** Sort by */\n sortBy: z.enum([\n 'relevance', // Best match (default for search)\n 'popularity', // Most installs\n 'rating', // Highest rated\n 'newest', // Most recently published\n 'updated', // Most recently updated\n 'name', // Alphabetical\n ]).default('relevance').describe('Sort field'),\n\n /** Sort direction */\n sortDirection: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n\n /** Pagination: page number */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(100).default(20).describe('Items per page'),\n\n /** Filter by minimum platform version compatibility */\n platformVersion: z.string().optional()\n .describe('Filter by platform version compatibility'),\n}).describe('Marketplace search request');\n\n/**\n * Marketplace Search Response\n */\nexport const MarketplaceSearchResponseSchema = z.object({\n /** Search results */\n items: z.array(MarketplaceListingSchema).describe('Search result listings'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching results'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page number'),\n\n /** Items per page */\n pageSize: z.number().int().min(1).describe('Items per page'),\n\n /** Facets for filtering */\n facets: z.object({\n categories: z.array(z.object({\n category: MarketplaceCategorySchema,\n count: z.number().int().min(0),\n })).optional(),\n pricing: z.array(z.object({\n model: PricingModelSchema,\n count: z.number().int().min(0),\n })).optional(),\n }).optional().describe('Aggregation facets for refining search'),\n}).describe('Marketplace search response');\n\n// ==========================================\n// Marketplace Install from Marketplace\n// ==========================================\n\n/**\n * Install from Marketplace Request\n * Extends the basic package install with marketplace-specific fields.\n */\nexport const MarketplaceInstallRequestSchema = z.object({\n /** Listing ID to install */\n listingId: z.string().describe('Marketplace listing ID'),\n\n /** Specific version to install (defaults to latest) */\n version: z.string().optional().describe('Version to install'),\n\n /** License key (for paid packages) */\n licenseKey: z.string().optional().describe('License key for paid packages'),\n\n /** User-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n\n /** Whether to enable immediately after install */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n\n /** Artifact reference (resolved from listing version, or provided directly) */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference for direct installation'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n}).describe('Install from marketplace request');\n\n/**\n * Install from Marketplace Response\n */\nexport const MarketplaceInstallResponseSchema = z.object({\n /** Whether installation was successful */\n success: z.boolean().describe('Whether installation succeeded'),\n\n /** Installed package ID */\n packageId: z.string().optional().describe('Installed package identifier'),\n\n /** Installed version */\n version: z.string().optional().describe('Installed version'),\n\n /** Human-readable message */\n message: z.string().optional().describe('Installation status message'),\n}).describe('Install from marketplace response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type PublisherVerification = z.infer;\nexport type Publisher = z.infer;\nexport type MarketplaceCategory = z.infer;\nexport type ListingStatus = z.infer;\nexport type PricingModel = z.infer;\nexport type MarketplaceListing = z.infer;\nexport type PackageSubmission = z.infer;\nexport type MarketplaceSearchRequest = z.infer;\nexport type MarketplaceSearchResponse = z.infer;\nexport type MarketplaceInstallRequest = z.infer;\nexport type MarketplaceInstallResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PublisherVerificationSchema } from './marketplace.zod';\n\n/**\n * # Developer Portal Protocol\n *\n * Defines schemas for the developer-facing side of the marketplace ecosystem.\n * Covers the complete developer journey:\n *\n * ```\n * Register → Create App → Develop → Validate → Build → Submit → Monitor → Iterate\n * ```\n *\n * ## Architecture Alignment\n * - **Salesforce Partner Portal**: ISV registration, AppExchange publishing, Trialforce\n * - **Shopify Partner Dashboard**: App management, analytics, billing\n * - **VS Code Marketplace Management**: Extension publishing, statistics, tokens\n *\n * ## Identity Integration (better-auth)\n * Authentication, organization management, and API keys are handled by the\n * Identity module (`@objectstack/spec` Identity namespace), which follows the\n * better-auth specification. This module only defines marketplace-specific\n * extensions on top of the shared identity layer:\n *\n * - **User & Session** → `Identity.UserSchema`, `Identity.SessionSchema`\n * - **Organization & Members** → `Identity.OrganizationSchema`, `Identity.MemberSchema`\n * - **API Keys** → `Identity.ApiKeySchema` (with marketplace scopes)\n *\n * ## Key Concepts\n * - **Publisher Profile**: Links an Identity Organization to a marketplace publisher\n * - **App Listing Management**: CRUD for marketplace listings (draft → published)\n * - **Version Channels**: alpha / beta / rc / stable release channels\n * - **Publishing Analytics**: Install trends, revenue, ratings over time\n */\n\n// ==========================================\n// Publisher Profile (extends Identity.Organization)\n// ==========================================\n\n/**\n * Publisher Profile Schema\n *\n * Links an Identity Organization to a marketplace publisher identity.\n * The organization itself (name, slug, logo, members) is managed via\n * Identity.OrganizationSchema and Identity.MemberSchema (better-auth aligned).\n *\n * This schema only holds marketplace-specific publisher metadata.\n */\nexport const PublisherProfileSchema = z.object({\n /** Organization ID (references Identity.Organization.id) */\n organizationId: z.string().describe('Identity Organization ID'),\n\n /** Publisher ID (marketplace-assigned identifier) */\n publisherId: z.string().describe('Marketplace publisher ID'),\n\n /** Verification level (marketplace trust tier) */\n verification: PublisherVerificationSchema.default('unverified'),\n\n /** Accepted developer program agreement version */\n agreementVersion: z.string().optional().describe('Accepted developer agreement version'),\n\n /** Publisher-specific website (may differ from org) */\n website: z.string().url().optional().describe('Publisher website'),\n\n /** Publisher-specific support email */\n supportEmail: z.string().email().optional().describe('Publisher support email'),\n\n /** Registration timestamp (when org became a publisher) */\n registeredAt: z.string().datetime(),\n});\n\n// ==========================================\n// Version Channels & Release Management\n// ==========================================\n\n/**\n * Release Channel — allows pre-release distribution\n */\nexport const ReleaseChannelSchema = z.enum([\n 'alpha', // Early development, unstable\n 'beta', // Feature-complete, testing phase\n 'rc', // Release candidate, final testing\n 'stable', // Production-ready, general availability\n]);\n\n/**\n * Version Release Schema\n *\n * A single version release of a package with channel assignment.\n */\nexport const VersionReleaseSchema = z.object({\n /** Semver version string */\n version: z.string().describe('Semver version (e.g., 2.1.0-beta.1)'),\n\n /** Release channel */\n channel: ReleaseChannelSchema.default('stable'),\n\n /** Release notes (Markdown) */\n releaseNotes: z.string().optional().describe('Release notes (Markdown)'),\n\n /** Changelog entries (structured) */\n changelog: z.array(z.object({\n type: z.enum(['added', 'changed', 'fixed', 'removed', 'deprecated', 'security']),\n description: z.string(),\n })).optional().describe('Structured changelog entries'),\n\n /** Minimum platform version required */\n minPlatformVersion: z.string().optional(),\n\n /** Build artifact URL */\n artifactUrl: z.string().optional().describe('Built package artifact URL'),\n\n /** Artifact checksum (integrity) */\n artifactChecksum: z.string().optional().describe('SHA-256 checksum'),\n\n /** Whether this version is deprecated */\n deprecated: z.boolean().default(false),\n\n /** Deprecation message (if deprecated) */\n deprecationMessage: z.string().optional(),\n\n /** Release timestamp */\n releasedAt: z.string().datetime().optional(),\n});\n\n// ==========================================\n// App Listing Management (Developer CRUD)\n// ==========================================\n\n/**\n * Create Listing Request — developer creates a new marketplace listing\n */\nexport const CreateListingRequestSchema = z.object({\n /** Package ID (reverse domain, e.g., com.acme.crm) */\n packageId: z.string().describe('Package identifier'),\n\n /** Display name */\n name: z.string().describe('App display name'),\n\n /** Short tagline (max 120 chars) */\n tagline: z.string().max(120).optional(),\n\n /** Full description (Markdown) */\n description: z.string().optional(),\n\n /** Category */\n category: z.string().describe('Marketplace category'),\n\n /** Additional tags */\n tags: z.array(z.string()).optional(),\n\n /** Icon URL */\n iconUrl: z.string().url().optional(),\n\n /** Screenshots */\n screenshots: z.array(z.object({\n url: z.string().url(),\n caption: z.string().optional(),\n })).optional(),\n\n /** Documentation URL */\n documentationUrl: z.string().url().optional(),\n\n /** Support URL */\n supportUrl: z.string().url().optional(),\n\n /** Source repository URL */\n repositoryUrl: z.string().url().optional(),\n\n /** Pricing model */\n pricing: z.enum([\n 'free', 'freemium', 'paid', 'subscription', 'usage-based', 'contact-sales',\n ]).default('free'),\n\n /** Price in cents (if paid) */\n priceInCents: z.number().int().min(0).optional(),\n});\n\n/**\n * Update Listing Request — developer updates listing metadata\n */\nexport const UpdateListingRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing ID to update'),\n\n /** Updatable fields (all optional, partial update) */\n name: z.string().optional(),\n tagline: z.string().max(120).optional(),\n description: z.string().optional(),\n category: z.string().optional(),\n tags: z.array(z.string()).optional(),\n iconUrl: z.string().url().optional(),\n screenshots: z.array(z.object({\n url: z.string().url(),\n caption: z.string().optional(),\n })).optional(),\n documentationUrl: z.string().url().optional(),\n supportUrl: z.string().url().optional(),\n repositoryUrl: z.string().url().optional(),\n pricing: z.enum([\n 'free', 'freemium', 'paid', 'subscription', 'usage-based', 'contact-sales',\n ]).optional(),\n priceInCents: z.number().int().min(0).optional(),\n});\n\n/**\n * Listing Action Request — lifecycle actions on a listing\n */\nexport const ListingActionRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing ID'),\n\n /** Action to perform */\n action: z.enum([\n 'submit', // Submit for review\n 'unlist', // Remove from public search (keep accessible by direct link)\n 'deprecate', // Mark as deprecated\n 'reactivate', // Reactivate unlisted/deprecated listing\n ]).describe('Action to perform on listing'),\n\n /** Reason for action (e.g., deprecation message) */\n reason: z.string().optional(),\n});\n\n// ==========================================\n// Publishing Analytics (Developer Dashboard)\n// ==========================================\n\n/**\n * Analytics Time Range\n */\nexport const AnalyticsTimeRangeSchema = z.enum([\n 'last_7d',\n 'last_30d',\n 'last_90d',\n 'last_365d',\n 'all_time',\n]);\n\n/**\n * Publishing Analytics Request\n */\nexport const PublishingAnalyticsRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing to get analytics for'),\n\n /** Time range */\n timeRange: AnalyticsTimeRangeSchema.default('last_30d'),\n\n /** Metrics to include */\n metrics: z.array(z.enum([\n 'installs', // Install count over time\n 'uninstalls', // Uninstall count over time\n 'active_installs', // Active install trend\n 'ratings', // Rating distribution\n 'revenue', // Revenue (for paid apps)\n 'page_views', // Listing page views\n ])).optional().describe('Metrics to include (default: all)'),\n});\n\n/**\n * Time Series Data Point\n */\nexport const TimeSeriesPointSchema = z.object({\n /** ISO date string (day granularity) */\n date: z.string(),\n /** Metric value */\n value: z.number(),\n});\n\n/**\n * Publishing Analytics Response\n */\nexport const PublishingAnalyticsResponseSchema = z.object({\n /** Listing ID */\n listingId: z.string(),\n\n /** Time range */\n timeRange: AnalyticsTimeRangeSchema,\n\n /** Summary statistics */\n summary: z.object({\n totalInstalls: z.number().int().min(0),\n activeInstalls: z.number().int().min(0),\n totalUninstalls: z.number().int().min(0),\n averageRating: z.number().min(0).max(5).optional(),\n totalRatings: z.number().int().min(0),\n totalRevenue: z.number().min(0).optional().describe('Revenue in cents'),\n pageViews: z.number().int().min(0),\n }),\n\n /** Time series data by metric */\n timeSeries: z.record(z.string(), z.array(TimeSeriesPointSchema)).optional()\n .describe('Time series keyed by metric name'),\n\n /** Rating distribution (1-5 stars) */\n ratingDistribution: z.object({\n 1: z.number().int().min(0).default(0),\n 2: z.number().int().min(0).default(0),\n 3: z.number().int().min(0).default(0),\n 4: z.number().int().min(0).default(0),\n 5: z.number().int().min(0).default(0),\n }).optional(),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type PublisherProfile = z.infer;\nexport type ReleaseChannel = z.infer;\nexport type VersionRelease = z.infer;\nexport type CreateListingRequest = z.infer;\nexport type UpdateListingRequest = z.infer;\nexport type ListingActionRequest = z.infer;\nexport type AnalyticsTimeRange = z.infer;\nexport type PublishingAnalyticsRequest = z.infer;\nexport type TimeSeriesPoint = z.infer;\nexport type PublishingAnalyticsResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Marketplace Administration Protocol\n *\n * Defines schemas for the platform (Cloud) side of marketplace operations.\n * Covers the administrative workflows for managing and governing the marketplace.\n *\n * ## Architecture Alignment\n * - **Salesforce AppExchange Admin**: Security review, ISV monitoring, partner management\n * - **Apple App Store Connect Review**: Human review process, guidelines, rejection reasons\n * - **Google Play Console**: Policy enforcement, quality gates, content moderation\n *\n * ## Key Concepts\n * - **Review Process**: Structured workflow for submission review (automated + manual)\n * - **Curation**: Featured apps, curated collections, editorial picks\n * - **Governance**: Policy enforcement, takedown, compliance\n * - **Platform Analytics**: Marketplace health, trending, abuse detection\n */\n\n// ==========================================\n// Review Process\n// ==========================================\n\n/**\n * Review Criteria — checklist items for human reviewers\n */\nexport const ReviewCriterionSchema = z.object({\n /** Criterion identifier */\n id: z.string().describe('Criterion ID'),\n\n /** Category of criterion */\n category: z.enum([\n 'security', // Security best practices\n 'performance', // Performance / resource usage\n 'quality', // Code quality / best practices\n 'ux', // User experience standards\n 'documentation', // Documentation completeness\n 'policy', // Policy compliance (no malware, GDPR, etc.)\n 'compatibility', // Platform compatibility\n ]),\n\n /** Description of what to check */\n description: z.string(),\n\n /** Whether this criterion must pass for approval */\n required: z.boolean().default(true),\n\n /** Pass/fail result */\n passed: z.boolean().optional(),\n\n /** Reviewer notes for this criterion */\n notes: z.string().optional(),\n});\n\n/**\n * Review Decision\n */\nexport const ReviewDecisionSchema = z.enum([\n 'approved', // Approved for publishing\n 'rejected', // Rejected (with reasons)\n 'changes-requested', // Needs changes before re-review\n]);\n\n/**\n * Rejection Reason Category\n */\nexport const RejectionReasonSchema = z.enum([\n 'security-vulnerability', // Security issues found\n 'policy-violation', // Violates marketplace policy\n 'quality-below-standard', // Does not meet quality bar\n 'misleading-metadata', // Listing info doesn't match functionality\n 'incompatible', // Incompatible with current platform\n 'duplicate', // Duplicate of existing listing\n 'insufficient-documentation', // Inadequate documentation\n 'other', // Other reason (see notes)\n]);\n\n/**\n * Submission Review Schema\n *\n * The review record attached to a package submission.\n */\nexport const SubmissionReviewSchema = z.object({\n /** Review ID */\n id: z.string().describe('Review ID'),\n\n /** Submission ID being reviewed */\n submissionId: z.string().describe('Submission being reviewed'),\n\n /** Reviewer user ID */\n reviewerId: z.string().describe('Platform reviewer ID'),\n\n /** Review decision */\n decision: ReviewDecisionSchema.optional().describe('Final decision'),\n\n /** Review criteria checklist */\n criteria: z.array(ReviewCriterionSchema).optional()\n .describe('Review checklist results'),\n\n /** Rejection reasons (if rejected) */\n rejectionReasons: z.array(RejectionReasonSchema).optional(),\n\n /** Detailed feedback for the developer */\n feedback: z.string().optional().describe('Detailed review feedback (Markdown)'),\n\n /** Internal notes (not visible to developer) */\n internalNotes: z.string().optional().describe('Internal reviewer notes'),\n\n /** Review started timestamp */\n startedAt: z.string().datetime().optional(),\n\n /** Review completed timestamp */\n completedAt: z.string().datetime().optional(),\n});\n\n// ==========================================\n// Curation: Featured & Collections\n// ==========================================\n\n/**\n * Featured Listing — promoted on marketplace homepage\n */\nexport const FeaturedListingSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Featured listing ID'),\n\n /** Featured position/priority (lower = higher priority) */\n priority: z.number().int().min(0).default(0),\n\n /** Featured banner image URL */\n bannerUrl: z.string().url().optional(),\n\n /** Featured reason / editorial note */\n editorialNote: z.string().optional(),\n\n /** Start date for featured period */\n startDate: z.string().datetime(),\n\n /** End date for featured period */\n endDate: z.string().datetime().optional(),\n\n /** Whether currently active */\n active: z.boolean().default(true),\n});\n\n/**\n * Curated Collection — a themed group of listings\n */\nexport const CuratedCollectionSchema = z.object({\n /** Collection unique identifier */\n id: z.string().describe('Collection ID'),\n\n /** Collection display name */\n name: z.string().describe('Collection name'),\n\n /** Collection description */\n description: z.string().optional(),\n\n /** Cover image URL */\n coverImageUrl: z.string().url().optional(),\n\n /** Listing IDs in this collection (ordered) */\n listingIds: z.array(z.string()).min(1).describe('Ordered listing IDs'),\n\n /** Whether publicly visible */\n published: z.boolean().default(false),\n\n /** Sort order for display among collections */\n sortOrder: z.number().int().min(0).default(0),\n\n /** Created by (admin user ID) */\n createdBy: z.string().optional(),\n\n /** Created at */\n createdAt: z.string().datetime().optional(),\n\n /** Updated at */\n updatedAt: z.string().datetime().optional(),\n});\n\n// ==========================================\n// Governance & Policy\n// ==========================================\n\n/**\n * Policy Violation Type\n */\nexport const PolicyViolationTypeSchema = z.enum([\n 'malware', // Malicious software\n 'data-harvesting', // Unauthorized data collection\n 'spam', // Spammy or misleading content\n 'copyright', // Copyright/IP infringement\n 'inappropriate-content', // Inappropriate or offensive content\n 'terms-of-service', // General ToS violation\n 'security-risk', // Unresolved critical security issues\n 'abandoned', // Abandoned / no longer maintained\n]);\n\n/**\n * Policy Action — enforcement action on a listing\n */\nexport const PolicyActionSchema = z.object({\n /** Action ID */\n id: z.string().describe('Action ID'),\n\n /** Listing ID */\n listingId: z.string().describe('Target listing ID'),\n\n /** Violation type */\n violationType: PolicyViolationTypeSchema,\n\n /** Action taken */\n action: z.enum([\n 'warning', // Warning to publisher\n 'suspend', // Temporarily suspend listing\n 'takedown', // Permanently remove listing\n 'restrict', // Restrict new installs (existing users keep access)\n ]),\n\n /** Detailed reason */\n reason: z.string().describe('Explanation of the violation'),\n\n /** Admin user who took the action */\n actionBy: z.string().describe('Admin user ID'),\n\n /** Timestamp */\n actionAt: z.string().datetime(),\n\n /** Resolution notes (if resolved) */\n resolution: z.string().optional(),\n\n /** Whether resolved */\n resolved: z.boolean().default(false),\n});\n\n// ==========================================\n// Platform Analytics\n// ==========================================\n\n/**\n * Marketplace Health Metrics — overall platform statistics\n */\nexport const MarketplaceHealthMetricsSchema = z.object({\n /** Total number of published listings */\n totalListings: z.number().int().min(0),\n\n /** Listings by status breakdown (partial — only non-zero statuses) */\n listingsByStatus: z.record(z.string(), z.number().int().min(0)).optional(),\n\n /** Listings by category breakdown (partial — only non-zero categories) */\n listingsByCategory: z.record(z.string(), z.number().int().min(0)).optional(),\n\n /** Total registered publishers */\n totalPublishers: z.number().int().min(0),\n\n /** Verified publishers count */\n verifiedPublishers: z.number().int().min(0),\n\n /** Total installs across all listings (all time) */\n totalInstalls: z.number().int().min(0),\n\n /** Average time from submission to review completion (hours) */\n averageReviewTime: z.number().min(0).optional(),\n\n /** Pending review queue size */\n pendingReviews: z.number().int().min(0),\n\n /** Listings by pricing model (partial — only non-zero models) */\n listingsByPricing: z.record(z.string(), z.number().int().min(0)).optional(),\n\n /** Snapshot timestamp */\n snapshotAt: z.string().datetime(),\n});\n\n/**\n * Trending Listing — computed from recent activity\n */\nexport const TrendingListingSchema = z.object({\n /** Listing ID */\n listingId: z.string(),\n\n /** Trending rank (1 = most trending) */\n rank: z.number().int().min(1),\n\n /** Trend score (computed from velocity of installs, ratings, page views) */\n trendScore: z.number().min(0),\n\n /** Install velocity (installs per day over measurement period) */\n installVelocity: z.number().min(0),\n\n /** Measurement period (e.g., \"7d\", \"30d\") */\n period: z.string(),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type ReviewCriterion = z.infer;\nexport type ReviewDecision = z.infer;\nexport type RejectionReason = z.infer;\nexport type SubmissionReview = z.infer;\nexport type FeaturedListing = z.infer;\nexport type CuratedCollection = z.infer;\nexport type PolicyViolationType = z.infer;\nexport type PolicyAction = z.infer;\nexport type MarketplaceHealthMetrics = z.infer;\nexport type TrendingListing = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { MarketplaceCategorySchema, PricingModelSchema } from './marketplace.zod';\n\n/**\n * # App Store Protocol (Customer Experience)\n *\n * Defines schemas for the end-customer experience when browsing, evaluating,\n * installing, and managing marketplace apps from within ObjectOS.\n *\n * ## Architecture Alignment\n * - **Salesforce AppExchange (Customer)**: Browse apps, read reviews, 1-click install\n * - **Shopify App Store (Merchant)**: App evaluation, trial, install, manage subscriptions\n * - **Apple App Store (User)**: Ratings, reviews, featured collections, personalized recs\n *\n * ## Customer Journey\n * ```\n * Discover → Evaluate → Install → Configure → Use → Rate/Review → Manage\n * ```\n *\n * ## Key Concepts\n * - **Reviews & Ratings**: User-submitted ratings and reviews with moderation\n * - **Collections & Recommendations**: Personalized discovery and curated picks\n * - **Subscription Management**: Manage licenses, billing, and renewals\n * - **Installed App Management**: Enable, disable, configure, upgrade, uninstall\n */\n\n// ==========================================\n// User Reviews & Ratings\n// ==========================================\n\n/**\n * Review Moderation Status\n */\nexport const ReviewModerationStatusSchema = z.enum([\n 'pending', // Awaiting moderation\n 'approved', // Approved and visible\n 'flagged', // Flagged for review\n 'rejected', // Rejected (spam, inappropriate)\n]);\n\n/**\n * User Review Schema — a customer's review of an installed app\n */\nexport const UserReviewSchema = z.object({\n /** Review ID */\n id: z.string().describe('Review ID'),\n\n /** Listing ID being reviewed */\n listingId: z.string().describe('Listing being reviewed'),\n\n /** Reviewer user ID */\n userId: z.string().describe('Review author user ID'),\n\n /** Reviewer display name */\n displayName: z.string().optional().describe('Reviewer display name'),\n\n /** Star rating (1-5) */\n rating: z.number().int().min(1).max(5).describe('Star rating (1-5)'),\n\n /** Review title */\n title: z.string().max(200).optional().describe('Review title'),\n\n /** Review body text */\n body: z.string().max(5000).optional().describe('Review text'),\n\n /** Version the reviewer is using */\n appVersion: z.string().optional().describe('App version being reviewed'),\n\n /** Moderation status */\n moderationStatus: ReviewModerationStatusSchema.default('pending'),\n\n /** Number of \"helpful\" votes from other users */\n helpfulCount: z.number().int().min(0).default(0),\n\n /** Publisher's response to this review */\n publisherResponse: z.object({\n body: z.string(),\n respondedAt: z.string().datetime(),\n }).optional().describe('Publisher response to review'),\n\n /** Submitted timestamp */\n submittedAt: z.string().datetime(),\n\n /** Updated timestamp */\n updatedAt: z.string().datetime().optional(),\n});\n\n/**\n * Submit Review Request\n */\nexport const SubmitReviewRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing to review'),\n\n /** Star rating (1-5) */\n rating: z.number().int().min(1).max(5).describe('Star rating'),\n\n /** Review title */\n title: z.string().max(200).optional(),\n\n /** Review body */\n body: z.string().max(5000).optional(),\n});\n\n/**\n * List Reviews Request — customer browsing reviews\n */\nexport const ListReviewsRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing to get reviews for'),\n\n /** Sort by */\n sortBy: z.enum(['newest', 'oldest', 'highest', 'lowest', 'most-helpful'])\n .default('newest'),\n\n /** Filter by rating */\n rating: z.number().int().min(1).max(5).optional(),\n\n /** Pagination */\n page: z.number().int().min(1).default(1),\n pageSize: z.number().int().min(1).max(50).default(10),\n});\n\n/**\n * List Reviews Response\n */\nexport const ListReviewsResponseSchema = z.object({\n /** Reviews */\n items: z.array(UserReviewSchema),\n\n /** Total count */\n total: z.number().int().min(0),\n\n /** Pagination */\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n\n /** Rating summary */\n ratingSummary: z.object({\n averageRating: z.number().min(0).max(5),\n totalRatings: z.number().int().min(0),\n distribution: z.object({\n 1: z.number().int().min(0).default(0),\n 2: z.number().int().min(0).default(0),\n 3: z.number().int().min(0).default(0),\n 4: z.number().int().min(0).default(0),\n 5: z.number().int().min(0).default(0),\n }),\n }).optional(),\n});\n\n// ==========================================\n// App Discovery & Recommendations\n// ==========================================\n\n/**\n * App Recommendation Reason\n */\nexport const RecommendationReasonSchema = z.enum([\n 'popular-in-category', // Popular in your industry/category\n 'similar-users', // Used by similar organizations\n 'complements-installed', // Complements apps you already use\n 'trending', // Currently trending\n 'new-release', // Recently released / major update\n 'editor-pick', // Editorial/curated recommendation\n]);\n\n/**\n * Recommended App\n */\nexport const RecommendedAppSchema = z.object({\n /** Listing ID */\n listingId: z.string(),\n\n /** App name */\n name: z.string(),\n\n /** Short tagline */\n tagline: z.string().optional(),\n\n /** Icon URL */\n iconUrl: z.string().url().optional(),\n\n /** Category */\n category: MarketplaceCategorySchema,\n\n /** Pricing */\n pricing: PricingModelSchema,\n\n /** Average rating */\n averageRating: z.number().min(0).max(5).optional(),\n\n /** Active installs */\n activeInstalls: z.number().int().min(0).optional(),\n\n /** Why this is recommended */\n reason: RecommendationReasonSchema,\n});\n\n/**\n * App Discovery Request — personalized browse/home page\n */\nexport const AppDiscoveryRequestSchema = z.object({\n /** Tenant ID for personalization */\n tenantId: z.string().optional(),\n\n /** Categories the customer is interested in */\n categories: z.array(MarketplaceCategorySchema).optional(),\n\n /** Platform version for compatibility filtering */\n platformVersion: z.string().optional(),\n\n /** Max number of items per section */\n limit: z.number().int().min(1).max(50).default(10),\n});\n\n/**\n * App Discovery Response — structured content for the storefront\n */\nexport const AppDiscoveryResponseSchema = z.object({\n /** Featured apps (editorial picks) */\n featured: z.array(RecommendedAppSchema).optional(),\n\n /** Personalized recommendations */\n recommended: z.array(RecommendedAppSchema).optional(),\n\n /** Trending apps */\n trending: z.array(RecommendedAppSchema).optional(),\n\n /** Recently added */\n newArrivals: z.array(RecommendedAppSchema).optional(),\n\n /** Curated collections */\n collections: z.array(z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().optional(),\n coverImageUrl: z.string().url().optional(),\n apps: z.array(RecommendedAppSchema),\n })).optional(),\n});\n\n// ==========================================\n// Subscription & License Management\n// ==========================================\n\n/**\n * Subscription Status\n */\nexport const SubscriptionStatusSchema = z.enum([\n 'active', // Active and paid\n 'trialing', // Free trial period\n 'past-due', // Payment overdue\n 'cancelled', // Cancelled (still active until period ends)\n 'expired', // Expired / ended\n]);\n\n/**\n * App Subscription Schema — customer's license/subscription for an app\n */\nexport const AppSubscriptionSchema = z.object({\n /** Subscription ID */\n id: z.string().describe('Subscription ID'),\n\n /** Listing ID */\n listingId: z.string().describe('App listing ID'),\n\n /** Tenant ID */\n tenantId: z.string().describe('Customer tenant ID'),\n\n /** Subscription status */\n status: SubscriptionStatusSchema,\n\n /** License key */\n licenseKey: z.string().optional(),\n\n /** Plan/tier name (if multiple plans) */\n plan: z.string().optional().describe('Subscription plan name'),\n\n /** Billing cycle */\n billingCycle: z.enum(['monthly', 'annual']).optional(),\n\n /** Price per billing cycle (in cents) */\n priceInCents: z.number().int().min(0).optional(),\n\n /** Current period start */\n currentPeriodStart: z.string().datetime().optional(),\n\n /** Current period end */\n currentPeriodEnd: z.string().datetime().optional(),\n\n /** Trial end date (if trialing) */\n trialEndDate: z.string().datetime().optional(),\n\n /** Whether auto-renew is on */\n autoRenew: z.boolean().default(true),\n\n /** Created timestamp */\n createdAt: z.string().datetime(),\n});\n\n// ==========================================\n// Installed App Management (Customer Side)\n// ==========================================\n\n/**\n * Installed App Summary — what the customer sees in their \"My Apps\" dashboard\n */\nexport const InstalledAppSummarySchema = z.object({\n /** Listing ID */\n listingId: z.string(),\n\n /** Package ID */\n packageId: z.string(),\n\n /** Display name */\n name: z.string(),\n\n /** Icon URL */\n iconUrl: z.string().url().optional(),\n\n /** Installed version */\n installedVersion: z.string(),\n\n /** Latest available version */\n latestVersion: z.string().optional(),\n\n /** Whether an update is available */\n updateAvailable: z.boolean().default(false),\n\n /** Whether the app is currently enabled */\n enabled: z.boolean().default(true),\n\n /** Subscription status (for paid apps) */\n subscriptionStatus: SubscriptionStatusSchema.optional(),\n\n /** Installed timestamp */\n installedAt: z.string().datetime(),\n});\n\n/**\n * List Installed Apps Request\n */\nexport const ListInstalledAppsRequestSchema = z.object({\n /** Tenant ID */\n tenantId: z.string().optional(),\n\n /** Filter by enabled/disabled */\n enabled: z.boolean().optional(),\n\n /** Filter by update availability */\n updateAvailable: z.boolean().optional(),\n\n /** Sort by */\n sortBy: z.enum(['name', 'installed-date', 'updated-date']).default('name'),\n\n /** Pagination */\n page: z.number().int().min(1).default(1),\n pageSize: z.number().int().min(1).max(100).default(20),\n});\n\n/**\n * List Installed Apps Response\n */\nexport const ListInstalledAppsResponseSchema = z.object({\n /** Installed apps */\n items: z.array(InstalledAppSummarySchema),\n\n /** Total count */\n total: z.number().int().min(0),\n\n /** Pagination */\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type ReviewModerationStatus = z.infer;\nexport type UserReview = z.infer;\nexport type SubmitReviewRequest = z.infer;\nexport type ListReviewsRequest = z.infer;\nexport type ListReviewsResponse = z.infer;\nexport type RecommendationReason = z.infer;\nexport type RecommendedApp = z.infer;\nexport type AppDiscoveryRequest = z.infer;\nexport type AppDiscoveryResponse = z.infer;\nexport type SubscriptionStatus = z.infer;\nexport type AppSubscription = z.infer;\nexport type InstalledAppSummary = z.infer;\nexport type ListInstalledAppsRequest = z.infer;\nexport type ListInstalledAppsResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Quality Assurance (QA) Protocol\n * \n * Defines how business logic and metadata are tested.\n * Includes:\n * - Test Scenarios\n * - Test Cases\n * - Expected Outcomes\n */\n\nexport * from './testing.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// --- Building Blocks ---\n\nexport const TestContextSchema = z.record(z.string(), z.unknown()).describe('Initial context or variables for the test');\n\n// Action Types\nexport const TestActionTypeSchema = z.enum([\n 'create_record',\n 'update_record',\n 'delete_record',\n 'read_record',\n 'query_records',\n 'api_call',\n 'run_script',\n 'wait' // Testing async processes\n]).describe('Type of test action to perform');\n\nexport const TestActionSchema = z.object({\n type: TestActionTypeSchema.describe('The action type to execute'),\n target: z.string().describe('Target Object, API Endpoint, or Function Name'),\n payload: z.record(z.string(), z.unknown()).optional().describe('Data to send or use'),\n user: z.string().optional().describe('Run as specific user/role for impersonation testing')\n}).describe('A single test action to execute against the system');\n\n// Assertion Types\nexport const TestAssertionTypeSchema = z.enum([\n 'equals',\n 'not_equals',\n 'contains',\n 'not_contains',\n 'is_null',\n 'not_null',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'error' // Expecting an error\n]).describe('Comparison operator for test assertions');\n\nexport const TestAssertionSchema = z.object({\n field: z.string().describe('Field path in the result to check (e.g. \"body.data.0.status\")'),\n operator: TestAssertionTypeSchema.describe('Comparison operator to use'),\n expectedValue: z.unknown().describe('Expected value to compare against')\n}).describe('A test assertion that validates the result of a test action');\n\n// --- Test Structure ---\n\nexport const TestStepSchema = z.object({\n name: z.string().describe('Step name for identification in test reports'),\n description: z.string().optional().describe('Human-readable description of what this step tests'),\n action: TestActionSchema.describe('The action to execute in this step'),\n assertions: z.array(TestAssertionSchema).optional().describe('Assertions to validate after the action completes'),\n // Capture outputs to variables for subsequent steps\n capture: z.record(z.string(), z.string()).optional().describe('Map result fields to context variables: { \"newId\": \"body.id\" }')\n}).describe('A single step in a test scenario, consisting of an action and optional assertions');\n\nexport const TestScenarioSchema = z.object({\n id: z.string().describe('Unique scenario identifier'),\n name: z.string().describe('Scenario name for test reports'),\n description: z.string().optional().describe('Detailed description of the test scenario'),\n tags: z.array(z.string()).optional().describe('Tags for filtering and categorization (e.g. \"critical\", \"regression\", \"crm\")'),\n \n setup: z.array(TestStepSchema).optional().describe('Steps to run before main test (preconditions)'),\n steps: z.array(TestStepSchema).describe('Main test sequence to execute'),\n teardown: z.array(TestStepSchema).optional().describe('Steps to cleanup after test execution'),\n \n // Environment requirements\n requires: z.object({\n params: z.array(z.string()).optional().describe('Required environment variables or parameters'),\n plugins: z.array(z.string()).optional().describe('Required plugins that must be loaded')\n }).optional().describe('Environment requirements for this scenario')\n}).describe('A complete test scenario with setup, execution steps, and teardown');\n\nexport const TestSuiteSchema = z.object({\n name: z.string().describe('Test suite name'),\n scenarios: z.array(TestScenarioSchema).describe('List of test scenarios in this suite')\n}).describe('A collection of test scenarios grouped into a test suite');\n\nexport type TestSuite = z.infer;\nexport type TestScenario = z.infer;\nexport type TestStep = z.infer;\nexport type TestAction = z.infer;\nexport type TestAssertion = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './identity.zod';\nexport * from './protocol';\nexport * from './role.zod';\nexport * from './organization.zod';\nexport * from './scim.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Identity & User Model Specification\n * \n * Defines the standard user, account, and session data models for ObjectStack.\n * These schemas represent \"who is logged in\" and their associated data.\n * \n * This is separate from authentication configuration (auth.zod.ts) which\n * defines \"how to login\".\n */\n\n/**\n * User Schema\n * Core user identity data model\n */\nexport const UserSchema = z.object({\n /**\n * Unique user identifier\n */\n id: z.string().describe('Unique user identifier'),\n \n /**\n * User's email address (primary identifier)\n */\n email: z.string().email().describe('User email address'),\n \n /**\n * Email verification status\n */\n emailVerified: z.boolean().default(false).describe('Whether email is verified'),\n \n /**\n * User's display name\n */\n name: z.string().optional().describe('User display name'),\n \n /**\n * User's profile image URL\n */\n image: z.string().url().optional().describe('Profile image URL'),\n \n /**\n * Account creation timestamp\n */\n createdAt: z.string().datetime().describe('Account creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type User = z.infer;\n\n/**\n * Account Schema\n * Links external OAuth/OIDC/SAML accounts to a user\n */\nexport const AccountSchema = z.object({\n /**\n * Unique account identifier\n */\n id: z.string().describe('Unique account identifier'),\n \n /**\n * Associated user ID\n */\n userId: z.string().describe('Associated user ID'),\n \n /**\n * Account type/provider\n */\n type: z.enum([\n 'oauth',\n 'oidc',\n 'email',\n 'credentials',\n 'saml',\n 'ldap',\n ]).describe('Account type'),\n \n /**\n * Provider name (e.g., 'google', 'github', 'okta')\n */\n provider: z.string().describe('Provider name'),\n \n /**\n * Provider account ID\n */\n providerAccountId: z.string().describe('Provider account ID'),\n \n /**\n * OAuth refresh token\n */\n refreshToken: z.string().optional().describe('OAuth refresh token'),\n \n /**\n * OAuth access token\n */\n accessToken: z.string().optional().describe('OAuth access token'),\n \n /**\n * Token expiry timestamp\n */\n expiresAt: z.number().optional().describe('Token expiry timestamp (Unix)'),\n \n /**\n * OAuth token type\n */\n tokenType: z.string().optional().describe('OAuth token type'),\n \n /**\n * OAuth scope\n */\n scope: z.string().optional().describe('OAuth scope'),\n \n /**\n * OAuth ID token\n */\n idToken: z.string().optional().describe('OAuth ID token'),\n \n /**\n * Session state\n */\n sessionState: z.string().optional().describe('Session state'),\n \n /**\n * Account creation timestamp\n */\n createdAt: z.string().datetime().describe('Account creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type Account = z.infer;\n\n/**\n * Session Schema\n * User session data model\n */\nexport const SessionSchema = z.object({\n /**\n * Unique session identifier\n */\n id: z.string().describe('Unique session identifier'),\n \n /**\n * Session token\n */\n sessionToken: z.string().describe('Session token'),\n \n /**\n * Associated user ID\n */\n userId: z.string().describe('Associated user ID'),\n \n /**\n * Active organization ID for this session\n * Used for context switching in multi-tenant applications\n */\n activeOrganizationId: z.string().optional().describe('Active organization ID for context switching'),\n \n /**\n * Session expiry timestamp\n */\n expires: z.string().datetime().describe('Session expiry timestamp'),\n \n /**\n * Session creation timestamp\n */\n createdAt: z.string().datetime().describe('Session creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n \n /**\n * IP address of the session\n */\n ipAddress: z.string().optional().describe('IP address'),\n \n /**\n * User agent string\n */\n userAgent: z.string().optional().describe('User agent string'),\n \n /**\n * Device fingerprint\n */\n fingerprint: z.string().optional().describe('Device fingerprint'),\n});\n\nexport type Session = z.infer;\n\n/**\n * Verification Token Schema\n * Email verification and password reset tokens\n */\nexport const VerificationTokenSchema = z.object({\n /**\n * Token identifier (email or phone)\n */\n identifier: z.string().describe('Token identifier (email or phone)'),\n \n /**\n * Verification token\n */\n token: z.string().describe('Verification token'),\n \n /**\n * Token expiry timestamp\n */\n expires: z.string().datetime().describe('Token expiry timestamp'),\n \n /**\n * Token creation timestamp\n */\n createdAt: z.string().datetime().describe('Token creation timestamp'),\n});\n\nexport type VerificationToken = z.infer;\n\n/**\n * API Key Schema\n *\n * Aligns with better-auth's API key plugin capabilities.\n * Provides programmatic access to ObjectStack APIs (CI/CD, service-to-service, CLI).\n *\n * @see https://www.better-auth.com/docs/plugins/api-key\n */\nexport const ApiKeySchema = z.object({\n /**\n * Unique API key identifier\n */\n id: z.string().describe('API key identifier'),\n\n /**\n * Human-readable name for the key\n */\n name: z.string().describe('API key display name'),\n\n /**\n * Key prefix (visible portion for identification, e.g., \"os_pk_ab\")\n */\n start: z.string().optional().describe('Key prefix for identification'),\n\n /**\n * Custom prefix for the key (e.g., \"os_pk_\")\n */\n prefix: z.string().optional().describe('Custom key prefix'),\n\n /**\n * User ID of the key owner\n */\n userId: z.string().describe('Owner user ID'),\n\n /**\n * Organization ID the key is scoped to (optional)\n */\n organizationId: z.string().optional().describe('Scoped organization ID'),\n\n /**\n * Key expiration timestamp (null = never expires)\n */\n expiresAt: z.string().datetime().optional().describe('Expiration timestamp'),\n\n /**\n * Creation timestamp\n */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n\n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n\n /**\n * Last used timestamp\n */\n lastUsedAt: z.string().datetime().optional().describe('Last used timestamp'),\n\n /**\n * Last refetch timestamp (for cached permission checks)\n */\n lastRefetchAt: z.string().datetime().optional().describe('Last refetch timestamp'),\n\n /**\n * Whether this key is enabled\n */\n enabled: z.boolean().default(true).describe('Whether the key is active'),\n\n /**\n * Rate limiting: enabled flag\n */\n rateLimitEnabled: z.boolean().optional().describe('Whether rate limiting is enabled'),\n\n /**\n * Rate limiting: time window in milliseconds\n */\n rateLimitTimeWindow: z.number().int().min(0).optional().describe('Rate limit window (ms)'),\n\n /**\n * Rate limiting: max requests per window\n */\n rateLimitMax: z.number().int().min(0).optional().describe('Max requests per window'),\n\n /**\n * Rate limiting: remaining requests in current window\n */\n remaining: z.number().int().min(0).optional().describe('Remaining requests'),\n\n /**\n * Permissions assigned to this key (granular access control)\n */\n permissions: z.record(z.string(), z.boolean()).optional()\n .describe('Granular permission flags'),\n\n /**\n * Scopes assigned to this key (high-level access categories)\n */\n scopes: z.array(z.string()).optional()\n .describe('High-level access scopes'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\nexport type ApiKey = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Authentication Wire Protocol & Constants\n * \n * Defines the API contract and constants for authentication communication.\n * These constants ensure consistent behavior across all ObjectStack implementations.\n */\n\n/**\n * Authentication Constants\n * Standard headers, prefixes, and identifiers for auth communication\n */\nexport const AUTH_CONSTANTS = {\n /**\n * HTTP header key for authentication tokens\n */\n HEADER_KEY: 'Authorization',\n \n /**\n * Token prefix for Bearer authentication\n */\n TOKEN_PREFIX: 'Bearer ',\n \n /**\n * Cookie prefix for ObjectStack auth cookies\n */\n COOKIE_PREFIX: 'os_',\n \n /**\n * CSRF token header name\n */\n CSRF_HEADER: 'x-os-csrf-token',\n \n /**\n * Default session cookie name\n */\n SESSION_COOKIE: 'os_session_token',\n \n /**\n * Default CSRF cookie name\n */\n CSRF_COOKIE: 'os_csrf_token',\n \n /**\n * Refresh token cookie name\n */\n REFRESH_TOKEN_COOKIE: 'os_refresh_token',\n} as const;\n\n/**\n * Authentication Headers Interface\n * Standard headers used in authenticated requests\n */\nexport interface AuthHeaders {\n /**\n * Authorization header with Bearer token\n * @example \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n */\n Authorization?: string;\n \n /**\n * CSRF token header\n * @example \"x-os-csrf-token: abc123def456...\"\n */\n 'x-os-csrf-token'?: string;\n \n /**\n * Session ID header (alternative to cookie)\n * @example \"x-os-session-id: session_abc123...\"\n */\n 'x-os-session-id'?: string;\n \n /**\n * API key header (for service-to-service auth)\n * @example \"x-os-api-key: sk_live_abc123...\"\n */\n 'x-os-api-key'?: string;\n}\n\n/**\n * Authentication Response Interface\n * Standard response format for authentication operations\n */\nexport interface AuthResponse {\n /**\n * Access token (JWT or opaque token)\n */\n accessToken: string;\n \n /**\n * Refresh token (for token renewal)\n */\n refreshToken?: string;\n \n /**\n * Token type (usually \"Bearer\")\n */\n tokenType: string;\n \n /**\n * Token expiry in seconds\n */\n expiresIn: number;\n \n /**\n * User information\n */\n user: {\n id: string;\n email: string;\n name?: string;\n image?: string;\n };\n \n /**\n * Session ID\n */\n sessionId?: string;\n}\n\n/**\n * Authentication Error Codes\n * Standard error codes for authentication failures\n */\nexport const AUTH_ERROR_CODES = {\n INVALID_CREDENTIALS: 'invalid_credentials',\n INVALID_TOKEN: 'invalid_token',\n TOKEN_EXPIRED: 'token_expired',\n INSUFFICIENT_PERMISSIONS: 'insufficient_permissions',\n ACCOUNT_LOCKED: 'account_locked',\n ACCOUNT_NOT_VERIFIED: 'account_not_verified',\n TOO_MANY_REQUESTS: 'too_many_requests',\n INVALID_CSRF_TOKEN: 'invalid_csrf_token',\n SESSION_EXPIRED: 'session_expired',\n OAUTH_ERROR: 'oauth_error',\n PROVIDER_ERROR: 'provider_error',\n} as const;\n\n/**\n * Authentication Error Interface\n * Standard error response format\n */\nexport interface AuthError {\n /**\n * Error code from AUTH_ERROR_CODES\n */\n code: typeof AUTH_ERROR_CODES[keyof typeof AUTH_ERROR_CODES];\n \n /**\n * Human-readable error message\n */\n message: string;\n \n /**\n * Additional error details\n */\n details?: Record;\n}\n\n/**\n * Token Payload Interface\n * Standard JWT payload structure\n */\nexport interface TokenPayload {\n /**\n * Subject (user ID)\n */\n sub: string;\n \n /**\n * Issued at timestamp\n */\n iat: number;\n \n /**\n * Expiration timestamp\n */\n exp: number;\n \n /**\n * Session ID\n */\n sid?: string;\n \n /**\n * User email\n */\n email?: string;\n \n /**\n * User roles\n */\n roles?: string[];\n \n /**\n * User permissions\n */\n permissions?: string[];\n \n /**\n * Additional custom claims\n */\n [key: string]: any;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Role Schema (aka Business Unit / Org Unit)\n * Defines the organizational hierarchy (Reporting Structure).\n * \n * COMPARISON:\n * - Salesforce: \"Role\" (Hierarchy for visibility rollup)\n * - Microsoft: \"Business Unit\" (Structural container for data)\n * - Kubernetes/AWS: \"Role\" usually refers to Permissions (we use PermissionSet for that)\n * \n * ROLES IN OBJECTSTACK:\n * Used primarily for \"Reporting Structure\" - Managers see subordinates' data.\n * \n * **NAMING CONVENTION:**\n * Role names MUST be lowercase snake_case to prevent security issues.\n * \n * @example Good role names\n * - 'sales_manager'\n * - 'ceo'\n * - 'region_east_vp'\n * - 'engineering_lead'\n * \n * @example Bad role names (will be rejected)\n * - 'SalesManager' (camelCase)\n * - 'CEO' (uppercase)\n * - 'Region East VP' (spaces and uppercase)\n */\nexport const RoleSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Unique role name (lowercase snake_case)'),\n label: z.string().describe('Display label (e.g. VP of Sales)'),\n \n /** Hierarchy */\n parent: z.string().optional().describe('Parent Role ID (Reports To)'),\n \n /** Description */\n description: z.string().optional(),\n});\n\nexport type Role = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Organization Schema (Multi-Tenant Architecture)\n * \n * Defines the standard organization/workspace model for ObjectStack.\n * Supports B2B SaaS scenarios where users belong to multiple teams/workspaces.\n * \n * This aligns with better-auth's organization plugin capabilities.\n */\n\n/**\n * Organization Schema\n * Represents a team, workspace, or tenant in a multi-tenant application\n */\nexport const OrganizationSchema = z.object({\n /**\n * Unique organization identifier\n */\n id: z.string().describe('Unique organization identifier'),\n \n /**\n * Organization name (display name)\n */\n name: z.string().describe('Organization display name'),\n \n /**\n * Organization slug (URL-friendly identifier)\n * Must be unique across all organizations\n */\n slug: z.string()\n .regex(/^[a-z0-9_-]+$/)\n .describe('Unique URL-friendly slug (lowercase alphanumeric, hyphens, underscores)'),\n \n /**\n * Organization logo URL\n */\n logo: z.string().url().optional().describe('Organization logo URL'),\n \n /**\n * Custom metadata for the organization\n * Can store additional configuration, settings, or custom fields\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n \n /**\n * Organization creation timestamp\n */\n createdAt: z.string().datetime().describe('Organization creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type Organization = z.infer;\n\n/**\n * Organization Member Schema\n * Links users to organizations with specific roles\n */\nexport const MemberSchema = z.object({\n /**\n * Unique member identifier\n */\n id: z.string().describe('Unique member identifier'),\n \n /**\n * Organization ID this membership belongs to\n */\n organizationId: z.string().describe('Organization ID'),\n \n /**\n * User ID of the member\n */\n userId: z.string().describe('User ID'),\n \n /**\n * Member's role within the organization\n * Common roles: 'owner', 'admin', 'member', 'guest'\n * Can be customized per application\n */\n role: z.string().describe('Member role (e.g., owner, admin, member, guest)'),\n \n /**\n * Member creation timestamp\n */\n createdAt: z.string().datetime().describe('Member creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type Member = z.infer;\n\n/**\n * Invitation Status Enum\n */\nexport const InvitationStatus = z.enum(['pending', 'accepted', 'rejected', 'expired']);\n\nexport type InvitationStatus = z.infer;\n\n/**\n * Organization Invitation Schema\n * Represents an invitation to join an organization\n */\nexport const InvitationSchema = z.object({\n /**\n * Unique invitation identifier\n */\n id: z.string().describe('Unique invitation identifier'),\n \n /**\n * Organization ID the invitation is for\n */\n organizationId: z.string().describe('Organization ID'),\n \n /**\n * Email address of the invitee\n */\n email: z.string().email().describe('Invitee email address'),\n \n /**\n * Role the invitee will receive upon accepting\n * Common roles: 'admin', 'member', 'guest'\n */\n role: z.string().describe('Role to assign upon acceptance'),\n \n /**\n * Invitation status\n */\n status: InvitationStatus.default('pending').describe('Invitation status'),\n \n /**\n * Invitation expiration timestamp\n */\n expiresAt: z.string().datetime().describe('Invitation expiry timestamp'),\n \n /**\n * User ID of the person who sent the invitation\n */\n inviterId: z.string().describe('User ID of the inviter'),\n \n /**\n * Invitation creation timestamp\n */\n createdAt: z.string().datetime().describe('Invitation creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type Invitation = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # SCIM 2.0 Protocol Implementation\n * \n * System for Cross-domain Identity Management (SCIM) 2.0 specification\n * implementation for ObjectStack.\n * \n * ## Overview\n * \n * SCIM 2.0 is an HTTP-based protocol for managing user and group identities\n * across domains. It provides a standardized REST API for user provisioning,\n * de-provisioning, and synchronization.\n * \n * ## Use Cases\n * \n * 1. **Enterprise SSO Integration**\n * - Integrate with Okta, Azure AD, OneLogin\n * - Automatic user provisioning from corporate directory\n * - Just-in-Time (JIT) user creation on first login\n * \n * 2. **User Lifecycle Management**\n * - Automatically create users when they join organization\n * - Update user attributes when they change roles\n * - Deactivate users when they leave organization\n * \n * 3. **Group/Department Synchronization**\n * - Sync organizational structure from AD/LDAP\n * - Maintain group memberships automatically\n * - Map corporate roles to application permissions\n * \n * 4. **Compliance & Audit**\n * - Maintain accurate user directory\n * - Track all identity changes\n * - Meet SOX/HIPAA requirements for user management\n * \n * ## Specification References\n * \n * - **RFC 7643**: SCIM Core Schema\n * - **RFC 7644**: SCIM Protocol\n * - **RFC 7642**: SCIM Requirements\n * \n * ## Industry Implementations\n * \n * - **Okta**: Leading SCIM provider\n * - **Azure AD**: Microsoft's identity platform\n * - **OneLogin**: Enterprise SSO provider\n * - **Google Workspace**: Google's identity management\n * \n * @see https://datatracker.ietf.org/doc/html/rfc7643\n * @see https://datatracker.ietf.org/doc/html/rfc7644\n */\n\n/**\n * SCIM Schema URIs\n * Standard schema identifiers defined in RFC 7643\n */\nexport const SCIM_SCHEMAS = {\n USER: 'urn:ietf:params:scim:schemas:core:2.0:User',\n GROUP: 'urn:ietf:params:scim:schemas:core:2.0:Group',\n ENTERPRISE_USER: 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User',\n RESOURCE_TYPE: 'urn:ietf:params:scim:schemas:core:2.0:ResourceType',\n SERVICE_PROVIDER_CONFIG: 'urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig',\n SCHEMA: 'urn:ietf:params:scim:schemas:core:2.0:Schema',\n LIST_RESPONSE: 'urn:ietf:params:scim:api:messages:2.0:ListResponse',\n PATCH_OP: 'urn:ietf:params:scim:api:messages:2.0:PatchOp',\n BULK_REQUEST: 'urn:ietf:params:scim:api:messages:2.0:BulkRequest',\n BULK_RESPONSE: 'urn:ietf:params:scim:api:messages:2.0:BulkResponse',\n ERROR: 'urn:ietf:params:scim:api:messages:2.0:Error',\n} as const;\n\n/**\n * SCIM Meta Schema\n * Common metadata for all SCIM resources\n */\nexport const SCIMMetaSchema = z.object({\n /**\n * Resource type name\n * @example \"User\", \"Group\"\n */\n resourceType: z.string()\n .optional()\n .describe('Resource type'),\n\n /**\n * Resource creation timestamp (ISO 8601)\n */\n created: z.string()\n .datetime()\n .optional()\n .describe('Creation timestamp'),\n\n /**\n * Last modification timestamp (ISO 8601)\n */\n lastModified: z.string()\n .datetime()\n .optional()\n .describe('Last modification timestamp'),\n\n /**\n * Resource location URI\n * Absolute URL to the resource\n */\n location: z.string()\n .url()\n .optional()\n .describe('Resource location URI'),\n\n /**\n * Entity tag for optimistic concurrency control\n * Used with If-Match header for conditional updates\n */\n version: z.string()\n .optional()\n .describe('Entity tag (ETag) for concurrency control'),\n});\n\nexport type SCIMMeta = z.infer;\n\n/**\n * SCIM Name Schema\n * Structured name components\n */\nexport const SCIMNameSchema = z.object({\n /**\n * Full name formatted for display\n * @example \"Ms. Barbara Jane Jensen III\"\n */\n formatted: z.string()\n .optional()\n .describe('Formatted full name'),\n\n /**\n * Family name (surname)\n * @example \"Jensen\"\n */\n familyName: z.string()\n .optional()\n .describe('Family name (last name)'),\n\n /**\n * Given name (first name)\n * @example \"Barbara\"\n */\n givenName: z.string()\n .optional()\n .describe('Given name (first name)'),\n\n /**\n * Middle name\n * @example \"Jane\"\n */\n middleName: z.string()\n .optional()\n .describe('Middle name'),\n\n /**\n * Honorific prefix\n * @example \"Ms.\", \"Dr.\", \"Prof.\"\n */\n honorificPrefix: z.string()\n .optional()\n .describe('Honorific prefix (Mr., Ms., Dr.)'),\n\n /**\n * Honorific suffix\n * @example \"III\", \"Jr.\", \"Sr.\"\n */\n honorificSuffix: z.string()\n .optional()\n .describe('Honorific suffix (Jr., Sr.)'),\n});\n\nexport type SCIMName = z.infer;\n\n/**\n * SCIM Email Schema\n * Multi-valued email address\n */\nexport const SCIMEmailSchema = z.object({\n /**\n * Email address value\n */\n value: z.string()\n .email()\n .describe('Email address'),\n\n /**\n * Email type\n * @example \"work\", \"home\", \"other\"\n */\n type: z.enum(['work', 'home', 'other'])\n .optional()\n .describe('Email type'),\n\n /**\n * Display label for the email\n */\n display: z.string()\n .optional()\n .describe('Display label'),\n\n /**\n * Whether this is the primary email\n */\n primary: z.boolean()\n .optional()\n .default(false)\n .describe('Primary email indicator'),\n});\n\nexport type SCIMEmail = z.infer;\n\n/**\n * SCIM Phone Number Schema\n * Multi-valued phone number\n */\nexport const SCIMPhoneNumberSchema = z.object({\n /**\n * Phone number value\n * Format is not enforced to support international numbers\n */\n value: z.string()\n .describe('Phone number'),\n\n /**\n * Phone type\n */\n type: z.enum(['work', 'home', 'mobile', 'fax', 'pager', 'other'])\n .optional()\n .describe('Phone number type'),\n\n /**\n * Display label for the phone number\n */\n display: z.string()\n .optional()\n .describe('Display label'),\n\n /**\n * Whether this is the primary phone\n */\n primary: z.boolean()\n .optional()\n .default(false)\n .describe('Primary phone indicator'),\n});\n\nexport type SCIMPhoneNumber = z.infer;\n\n/**\n * SCIM Address Schema\n * Multi-valued physical mailing address\n */\nexport const SCIMAddressSchema = z.object({\n /**\n * Full mailing address formatted for display\n */\n formatted: z.string()\n .optional()\n .describe('Formatted address'),\n\n /**\n * Full street address\n */\n streetAddress: z.string()\n .optional()\n .describe('Street address'),\n\n /**\n * City or locality\n */\n locality: z.string()\n .optional()\n .describe('City/Locality'),\n\n /**\n * State or region\n */\n region: z.string()\n .optional()\n .describe('State/Region'),\n\n /**\n * Zip code or postal code\n */\n postalCode: z.string()\n .optional()\n .describe('Postal code'),\n\n /**\n * Country\n */\n country: z.string()\n .optional()\n .describe('Country'),\n\n /**\n * Address type\n */\n type: z.enum(['work', 'home', 'other'])\n .optional()\n .describe('Address type'),\n\n /**\n * Whether this is the primary address\n */\n primary: z.boolean()\n .optional()\n .default(false)\n .describe('Primary address indicator'),\n});\n\nexport type SCIMAddress = z.infer;\n\n/**\n * SCIM Group Reference\n * Reference to a group the user belongs to\n */\nexport const SCIMGroupReferenceSchema = z.object({\n /**\n * Group identifier\n */\n value: z.string()\n .describe('Group ID'),\n\n /**\n * Direct reference to the group resource\n */\n $ref: z.string()\n .url()\n .optional()\n .describe('URI reference to the group'),\n\n /**\n * Human-readable group name\n */\n display: z.string()\n .optional()\n .describe('Group display name'),\n\n /**\n * Type of group\n */\n type: z.enum(['direct', 'indirect'])\n .optional()\n .describe('Membership type'),\n});\n\nexport type SCIMGroupReference = z.infer;\n\n/**\n * SCIM Enterprise User Extension\n * Enterprise-specific user attributes\n */\nexport const SCIMEnterpriseUserSchema = z.object({\n /**\n * Employee number\n */\n employeeNumber: z.string()\n .optional()\n .describe('Employee number'),\n\n /**\n * Cost center\n */\n costCenter: z.string()\n .optional()\n .describe('Cost center'),\n\n /**\n * Organization unit\n */\n organization: z.string()\n .optional()\n .describe('Organization'),\n\n /**\n * Division\n */\n division: z.string()\n .optional()\n .describe('Division'),\n\n /**\n * Department\n */\n department: z.string()\n .optional()\n .describe('Department'),\n\n /**\n * Manager reference\n */\n manager: z.object({\n value: z.string().describe('Manager ID'),\n $ref: z.string().url().optional().describe('Manager URI'),\n displayName: z.string().optional().describe('Manager name'),\n })\n .optional()\n .describe('Manager reference'),\n});\n\nexport type SCIMEnterpriseUser = z.infer;\n\n/**\n * SCIM User Schema (Core)\n * Complete SCIM 2.0 User resource\n */\nexport const SCIMUserSchema = z.object({\n /**\n * SCIM schema URIs\n * Must include at minimum the core User schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.USER),\n 'Must include core User schema URI'\n )\n .default([SCIM_SCHEMAS.USER])\n .describe('SCIM schema URIs (must include User schema)'),\n\n /**\n * Unique identifier\n */\n id: z.string()\n .optional()\n .describe('Unique resource identifier'),\n\n /**\n * External identifier\n * Identifier from the provisioning client\n */\n externalId: z.string()\n .optional()\n .describe('External identifier from client system'),\n\n /**\n * Unique username\n * REQUIRED for user creation\n */\n userName: z.string()\n .describe('Unique username (REQUIRED)'),\n\n /**\n * Structured name\n */\n name: SCIMNameSchema\n .optional()\n .describe('Structured name components'),\n\n /**\n * Display name\n */\n displayName: z.string()\n .optional()\n .describe('Display name for UI'),\n\n /**\n * Nickname or casual name\n */\n nickName: z.string()\n .optional()\n .describe('Nickname'),\n\n /**\n * Profile URL\n */\n profileUrl: z.string()\n .url()\n .optional()\n .describe('Profile page URL'),\n\n /**\n * Job title\n */\n title: z.string()\n .optional()\n .describe('Job title'),\n\n /**\n * User type (employee, contractor, etc.)\n */\n userType: z.string()\n .optional()\n .describe('User type (employee, contractor)'),\n\n /**\n * Preferred language (ISO 639-1)\n */\n preferredLanguage: z.string()\n .optional()\n .describe('Preferred language (ISO 639-1)'),\n\n /**\n * Locale (e.g., en-US)\n */\n locale: z.string()\n .optional()\n .describe('Locale (e.g., en-US)'),\n\n /**\n * Timezone (e.g., America/Los_Angeles)\n */\n timezone: z.string()\n .optional()\n .describe('Timezone'),\n\n /**\n * Account active status\n */\n active: z.boolean()\n .optional()\n .default(true)\n .describe('Account active status'),\n\n /**\n * Password (write-only, never returned)\n */\n password: z.string()\n .optional()\n .describe('Password (write-only)'),\n\n /**\n * Email addresses (multi-valued)\n */\n emails: z.array(SCIMEmailSchema)\n .optional()\n .describe('Email addresses'),\n\n /**\n * Phone numbers (multi-valued)\n */\n phoneNumbers: z.array(SCIMPhoneNumberSchema)\n .optional()\n .describe('Phone numbers'),\n\n /**\n * Instant messaging addresses\n */\n ims: z.array(z.object({\n value: z.string(),\n type: z.string().optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('IM addresses'),\n\n /**\n * Photos (profile pictures)\n */\n photos: z.array(z.object({\n value: z.string().url(),\n type: z.enum(['photo', 'thumbnail']).optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('Photo URLs'),\n\n /**\n * Physical addresses\n */\n addresses: z.array(SCIMAddressSchema)\n .optional()\n .describe('Physical addresses'),\n\n /**\n * Group memberships\n */\n groups: z.array(SCIMGroupReferenceSchema)\n .optional()\n .describe('Group memberships'),\n\n /**\n * User entitlements\n */\n entitlements: z.array(z.object({\n value: z.string(),\n type: z.string().optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('Entitlements'),\n\n /**\n * User roles\n */\n roles: z.array(z.object({\n value: z.string(),\n type: z.string().optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('Roles'),\n\n /**\n * X509 certificates\n */\n x509Certificates: z.array(z.object({\n value: z.string(),\n type: z.string().optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('X509 certificates'),\n\n /**\n * Resource metadata\n */\n meta: SCIMMetaSchema\n .optional()\n .describe('Resource metadata'),\n\n /**\n * Enterprise user extension\n * Only present when enterprise extension is used\n */\n [SCIM_SCHEMAS.ENTERPRISE_USER]: SCIMEnterpriseUserSchema\n .optional()\n .describe('Enterprise user attributes'),\n}).superRefine((data, ctx) => {\n // Validate that enterprise extension schema URI is present when extension data is provided\n const hasEnterpriseExtension = data[SCIM_SCHEMAS.ENTERPRISE_USER] != null;\n if (!hasEnterpriseExtension) {\n return;\n }\n\n const schemas = data.schemas || [];\n if (!schemas.includes(SCIM_SCHEMAS.ENTERPRISE_USER)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['schemas'],\n message: `schemas must include \"${SCIM_SCHEMAS.ENTERPRISE_USER}\" when enterprise user extension attributes are present`,\n });\n }\n});\n\nexport type SCIMUser = z.infer;\n\n/**\n * SCIM Member Reference\n * Reference to a member in a group\n */\nexport const SCIMMemberReferenceSchema = z.object({\n /**\n * Member identifier\n */\n value: z.string()\n .describe('Member ID'),\n\n /**\n * Direct reference to the member resource\n */\n $ref: z.string()\n .url()\n .optional()\n .describe('URI reference to the member'),\n\n /**\n * Member type (User or Group for nested groups)\n */\n type: z.enum(['User', 'Group'])\n .optional()\n .describe('Member type'),\n\n /**\n * Human-readable member name\n */\n display: z.string()\n .optional()\n .describe('Member display name'),\n});\n\nexport type SCIMMemberReference = z.infer;\n\n/**\n * SCIM Group Schema\n * Complete SCIM 2.0 Group resource\n */\nexport const SCIMGroupSchema = z.object({\n /**\n * SCIM schema URIs\n * Must include at minimum the core Group schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.GROUP),\n 'Must include core Group schema URI'\n )\n .default([SCIM_SCHEMAS.GROUP])\n .describe('SCIM schema URIs (must include Group schema)'),\n\n /**\n * Unique identifier\n */\n id: z.string()\n .optional()\n .describe('Unique resource identifier'),\n\n /**\n * External identifier\n */\n externalId: z.string()\n .optional()\n .describe('External identifier from client system'),\n\n /**\n * Group display name\n * REQUIRED for group creation\n */\n displayName: z.string()\n .describe('Group display name (REQUIRED)'),\n\n /**\n * Group members\n */\n members: z.array(SCIMMemberReferenceSchema)\n .optional()\n .describe('Group members'),\n\n /**\n * Resource metadata\n */\n meta: SCIMMetaSchema\n .optional()\n .describe('Resource metadata'),\n});\n\nexport type SCIMGroup = z.infer;\n\n/**\n * SCIM Resource Union Type\n * Known SCIM resource types for type-safe list responses\n */\nexport type SCIMResource = SCIMUser | SCIMGroup;\n\n/**\n * SCIM List Response\n * Paginated list of resources\n * \n * Generic type T allows for type-safe responses when the resource type is known.\n * For mixed resource types, use SCIMResource union.\n */\nexport const SCIMListResponseSchema = z.object({\n /**\n * SCIM schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.LIST_RESPONSE),\n { message: `schemas must include ${SCIM_SCHEMAS.LIST_RESPONSE}` }\n )\n .default([SCIM_SCHEMAS.LIST_RESPONSE])\n .describe('SCIM schema URIs'),\n\n /**\n * Total number of results matching the query\n */\n totalResults: z.number()\n .int()\n .min(0)\n .describe('Total results count'),\n\n /**\n * Resources returned in this response\n * Use SCIMListResponseOf for type-safe responses\n */\n Resources: z.array(z.union([SCIMUserSchema, SCIMGroupSchema, z.record(z.string(), z.unknown())]))\n .describe('Resources array (Users, Groups, or custom resources)'),\n\n /**\n * 1-based index of the first result\n */\n startIndex: z.number()\n .int()\n .min(1)\n .optional()\n .describe('Start index (1-based)'),\n\n /**\n * Number of resources per page\n */\n itemsPerPage: z.number()\n .int()\n .min(0)\n .optional()\n .describe('Items per page'),\n});\n\nexport type SCIMListResponse = z.infer;\n\n/**\n * SCIM Error Response\n * Error response format\n */\nexport const SCIMErrorSchema = z.object({\n /**\n * SCIM schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.ERROR),\n { message: `schemas must include ${SCIM_SCHEMAS.ERROR}` }\n )\n .default([SCIM_SCHEMAS.ERROR])\n .describe('SCIM schema URIs'),\n\n /**\n * HTTP status code\n */\n status: z.number()\n .int()\n .min(400)\n .max(599)\n .describe('HTTP status code'),\n\n /**\n * SCIM error type\n */\n scimType: z.enum([\n 'invalidFilter',\n 'tooMany',\n 'uniqueness',\n 'mutability',\n 'invalidSyntax',\n 'invalidPath',\n 'noTarget',\n 'invalidValue',\n 'invalidVers',\n 'sensitive',\n ])\n .optional()\n .describe('SCIM error type'),\n\n /**\n * Human-readable error description\n */\n detail: z.string()\n .optional()\n .describe('Error detail message'),\n});\n\nexport type SCIMError = z.infer;\n\n/**\n * SCIM Patch Operation\n * For PATCH requests\n */\nexport const SCIMPatchOperationSchema = z.object({\n /**\n * Operation type\n */\n op: z.enum(['add', 'remove', 'replace'])\n .describe('Operation type'),\n\n /**\n * Attribute path to modify\n */\n path: z.string()\n .optional()\n .describe('Attribute path (optional for add)'),\n\n /**\n * Value to set\n */\n value: z.unknown()\n .optional()\n .describe('Value to set'),\n});\n\nexport type SCIMPatchOperation = z.infer;\n\n/**\n * SCIM Patch Request\n */\nexport const SCIMPatchRequestSchema = z.object({\n /**\n * SCIM schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.PATCH_OP),\n { message: 'SCIM PATCH requests must include the PatchOp schema URI' }\n )\n .default([SCIM_SCHEMAS.PATCH_OP])\n .describe('SCIM schema URIs'),\n\n /**\n * Array of patch operations\n */\n Operations: z.array(SCIMPatchOperationSchema)\n .min(1)\n .describe('Patch operations'),\n});\n\nexport type SCIMPatchRequest = z.infer;\n\n/**\n * Helper factory for creating SCIM resources\n */\nexport const SCIM = {\n /**\n * Create a basic SCIM user\n */\n user: (userName: string, email: string, givenName?: string, familyName?: string): SCIMUser => ({\n schemas: [SCIM_SCHEMAS.USER],\n userName,\n emails: [{ value: email, type: 'work', primary: true }],\n name: {\n givenName,\n familyName,\n },\n active: true,\n }),\n\n /**\n * Create a SCIM group\n */\n group: (displayName: string, members?: SCIMMemberReference[]): SCIMGroup => ({\n schemas: [SCIM_SCHEMAS.GROUP],\n displayName,\n members: members || [],\n }),\n\n /**\n * Create a list response\n */\n listResponse: (resources: T[], totalResults?: number): SCIMListResponse => ({\n schemas: [SCIM_SCHEMAS.LIST_RESPONSE],\n totalResults: totalResults ?? resources.length,\n Resources: resources as Array>,\n startIndex: 1,\n itemsPerPage: resources.length,\n }),\n\n /**\n * Create an error response\n */\n error: (\n status: number,\n detail: string,\n scimType?: 'invalidFilter' | 'tooMany' | 'uniqueness' | 'mutability' | \n 'invalidSyntax' | 'invalidPath' | 'noTarget' | 'invalidValue' | \n 'invalidVers' | 'sensitive'\n ): SCIMError => ({\n schemas: [SCIM_SCHEMAS.ERROR],\n status,\n detail,\n scimType,\n }),\n} as const;\n\n// ─── SCIM 2.0 Bulk Operations (RFC 7644 §3.7) ──────────────────────────────\n\n/**\n * SCIM Bulk Operation Schema\n * A single operation within a bulk request\n */\nexport const SCIMBulkOperationSchema = z.object({\n /** HTTP method for this operation */\n method: z.enum(['POST', 'PUT', 'PATCH', 'DELETE'])\n .describe('HTTP method for the bulk operation'),\n\n /** Resource path (e.g. /Users, /Groups/{id}) */\n path: z.string()\n .describe('Resource endpoint path (e.g. /Users, /Groups/{id})'),\n\n /** Client-assigned identifier for cross-referencing operations */\n bulkId: z.string()\n .optional()\n .describe('Client-assigned ID for cross-referencing between operations'),\n\n /** Request body for POST/PUT/PATCH operations */\n data: z.record(z.string(), z.unknown())\n .optional()\n .describe('Request body for POST/PUT/PATCH operations'),\n\n /** ETag value for optimistic concurrency control */\n version: z.string()\n .optional()\n .describe('ETag for optimistic concurrency control'),\n});\n\nexport type SCIMBulkOperation = z.infer;\n\n/**\n * SCIM Bulk Request Schema\n * Batch multiple SCIM operations into a single HTTP request\n */\nexport const SCIMBulkRequestSchema = z.object({\n /** SCIM schema URI for bulk request */\n schemas: z.array(z.literal(SCIM_SCHEMAS.BULK_REQUEST))\n .default([SCIM_SCHEMAS.BULK_REQUEST])\n .describe('SCIM schema URIs (BulkRequest)'),\n\n /** Array of operations to execute */\n operations: z.array(SCIMBulkOperationSchema)\n .min(1)\n .describe('Bulk operations to execute (minimum 1)'),\n\n /** Stop processing after N errors */\n failOnErrors: z.number()\n .int()\n .optional()\n .describe('Stop processing after this many errors'),\n});\n\nexport type SCIMBulkRequest = z.infer;\n\n/**\n * SCIM Bulk Response Operation Schema\n * Result of a single operation within a bulk response\n */\nexport const SCIMBulkResponseOperationSchema = z.object({\n /** HTTP method that was executed */\n method: z.enum(['POST', 'PUT', 'PATCH', 'DELETE'])\n .describe('HTTP method that was executed'),\n\n /** Client-assigned bulk operation ID */\n bulkId: z.string()\n .optional()\n .describe('Client-assigned bulk operation ID'),\n\n /** URL of the created/modified resource */\n location: z.string()\n .optional()\n .describe('URL of the created or modified resource'),\n\n /** HTTP status code as string */\n status: z.string()\n .describe('HTTP status code as string (e.g. \"201\", \"400\")'),\n\n /** Response body, typically present for errors */\n response: z.unknown()\n .optional()\n .describe('Response body (typically present for errors)'),\n});\n\nexport type SCIMBulkResponseOperation = z.infer;\n\n/**\n * SCIM Bulk Response Schema\n * Response to a bulk request containing results for each operation\n */\nexport const SCIMBulkResponseSchema = z.object({\n /** SCIM schema URI for bulk response */\n schemas: z.array(z.literal(SCIM_SCHEMAS.BULK_RESPONSE))\n .default([SCIM_SCHEMAS.BULK_RESPONSE])\n .describe('SCIM schema URIs (BulkResponse)'),\n\n /** Array of operation results */\n operations: z.array(SCIMBulkResponseOperationSchema)\n .describe('Results for each bulk operation'),\n});\n\nexport type SCIMBulkResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * AI Protocol Exports\n * \n * AI/ML Capabilities\n * - Agent Configuration (Agent → Skill → Tool architecture)\n * - Tool Metadata (first-class AI tool definitions)\n * - Skill Metadata (ability groups / capability bundles)\n * - DevOps Agent (Self-iterating Development)\n * - Model Registry & Selection\n * - Model Context Protocol (MCP)\n * - RAG Pipeline\n * - Natural Language Query (NLQ)\n * - Workflow Automation\n * - Predictive Analytics\n * - Conversation Memory & Token Management\n * - Cost Tracking & Budget Management\n * - Plugin Development (AI-assisted)\n * - Runtime Operations (AIOps)\n */\n\nexport * from './agent.zod';\nexport * from './tool.zod';\nexport * from './skill.zod';\nexport * from './agent-action.zod';\nexport * from './devops-agent.zod';\nexport * from './plugin-development.zod';\nexport * from './runtime-ops.zod';\nexport * from './model-registry.zod';\nexport * from './mcp.zod';\nexport * from './rag-pipeline.zod';\nexport * from './nlq.zod';\nexport * from './orchestration.zod';\nexport * from './predictive.zod';\nexport * from './conversation.zod';\nexport * from './cost.zod';\nexport * from './feedback-loop.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\n\n/**\n * AI Model Configuration\n */\nexport const AIModelConfigSchema = z.object({\n provider: z.enum(['openai', 'azure_openai', 'anthropic', 'local']).default('openai'),\n model: z.string().describe('Model name (e.g. gpt-4, claude-3-opus)'),\n temperature: z.number().min(0).max(2).default(0.7),\n maxTokens: z.number().optional(),\n topP: z.number().optional(),\n});\n\n/**\n * AI Tool Definition\n * References to Actions, Flows, or Objects available to the Agent.\n */\nexport const AIToolSchema = z.object({\n type: z.enum(['action', 'flow', 'query', 'vector_search']),\n name: z.string().describe('Reference name (Action Name, Flow Name)'),\n description: z.string().optional().describe('Override description for the LLM'),\n});\n\n/**\n * AI Knowledge Base\n * RAG configuration.\n */\nexport const AIKnowledgeSchema = z.object({\n topics: z.array(z.string()).describe('Topics/Tags to recruit knowledge from'),\n indexes: z.array(z.string()).describe('Vector Store Indexes'),\n});\n\n/**\n * Structured Output Format\n * Defines the expected output format for agent responses\n */\nexport const StructuredOutputFormatSchema = z.enum([\n 'json_object',\n 'json_schema',\n 'regex',\n 'grammar',\n 'xml',\n]).describe('Output format for structured agent responses');\n\n/**\n * Transform Pipeline Step\n * Post-processing steps applied to structured output\n */\nexport const TransformPipelineStepSchema = z.enum([\n 'trim',\n 'parse_json',\n 'validate',\n 'coerce_types',\n]).describe('Post-processing step for structured output');\n\n/**\n * Structured Output Configuration\n * Controls how the agent formats and validates its output\n */\nexport const StructuredOutputConfigSchema = z.object({\n /** Output format type */\n format: StructuredOutputFormatSchema.describe('Expected output format'),\n\n /** JSON Schema definition for output validation */\n schema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema definition for output'),\n\n /** Whether to enforce exact schema compliance */\n strict: z.boolean().default(false).describe('Enforce exact schema compliance'),\n\n /** Retry on validation failure */\n retryOnValidationFailure: z.boolean().default(true).describe('Retry generation when output fails validation'),\n\n /** Maximum retry attempts */\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retries on validation failure'),\n\n /** Fallback format if primary format fails */\n fallbackFormat: StructuredOutputFormatSchema.optional().describe('Fallback format if primary format fails'),\n\n /** Post-processing pipeline steps */\n transformPipeline: z.array(TransformPipelineStepSchema).optional().describe('Post-processing steps applied to output'),\n}).describe('Structured output configuration for agent responses');\n\nexport type StructuredOutputFormat = z.infer;\nexport type TransformPipelineStep = z.infer;\nexport type StructuredOutputConfig = z.infer;\n\n/**\n * AI Agent Schema\n * Definition of an autonomous agent specialized for a domain.\n *\n * The Agent → Skill → Tool three-tier architecture aligns with\n * Salesforce Agentforce, Microsoft Copilot Studio, and ServiceNow\n * Now Assist metadata patterns.\n *\n * - **skills**: Primary capability model — references skill names.\n * - **tools**: Fallback / direct tool references (legacy inline format).\n *\n * @example Agent-Skill Architecture\n * ```ts\n * defineAgent({\n * name: 'support_tier_1',\n * label: 'First Line Support',\n * role: 'Help Desk Assistant',\n * instructions: 'You are a helpful assistant. Always verify user identity first.',\n * skills: ['case_management', 'knowledge_search'],\n * knowledge: { topics: ['faq', 'policies'], indexes: ['support_docs'] },\n * });\n * ```\n *\n * @example Legacy Tool References (backward-compatible)\n * ```ts\n * defineAgent({\n * name: 'support_tier_1',\n * label: 'First Line Support',\n * role: 'Help Desk Assistant',\n * instructions: 'You are a helpful assistant.',\n * tools: [\n * { type: 'flow', name: 'reset_password', description: 'Trigger password reset email' },\n * { type: 'query', name: 'get_order_status', description: 'Check order shipping status' },\n * ],\n * });\n * ```\n */\nexport const AgentSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Agent unique identifier'),\n label: z.string().describe('Agent display name'),\n avatar: z.string().optional(),\n role: z.string().describe('The persona/role (e.g. \"Senior Support Engineer\")'),\n\n /** Cognition */\n instructions: z.string().describe('System Prompt / Prime Directives'),\n model: AIModelConfigSchema.optional(),\n lifecycle: StateMachineSchema.optional().describe('State machine defining the agent conversation follow and constraints'),\n\n /** Capabilities — Skill-based (primary) */\n skills: z.array(z.string().regex(/^[a-z_][a-z0-9_]*$/)).optional().describe('Skill names to attach (Agent→Skill→Tool architecture)'),\n\n /** Capabilities — Direct tool references (fallback / legacy) */\n tools: z.array(AIToolSchema).optional().describe('Direct tool references (legacy fallback)'),\n\n /** Knowledge */\n knowledge: AIKnowledgeSchema.optional().describe('RAG access'),\n\n /** Interface */\n active: z.boolean().default(true),\n access: z.array(z.string()).optional().describe('Who can chat with this agent'),\n\n /** Permission profiles/roles required to use this agent */\n permissions: z.array(z.string()).optional().describe('Required permissions or roles'),\n\n /** Multi-tenancy & Visibility */\n tenantId: z.string().optional().describe('Tenant/Organization ID'),\n visibility: z.enum(['global', 'organization', 'private']).default('organization'),\n\n /** Autonomous Reasoning */\n planning: z.object({\n /** Planning strategy for autonomous reasoning loops */\n strategy: z.enum(['react', 'plan_and_execute', 'reflexion', 'tree_of_thought']).default('react').describe('Autonomous reasoning strategy'),\n\n /** Maximum reasoning iterations before stopping */\n maxIterations: z.number().int().min(1).max(100).default(10).describe('Maximum planning loop iterations'),\n\n /** Whether the agent can revise its own plan mid-execution */\n allowReplan: z.boolean().default(true).describe('Allow dynamic re-planning based on intermediate results'),\n }).optional().describe('Autonomous reasoning and planning configuration'),\n\n /** Memory Management */\n memory: z.object({\n /** Short-term (working) memory configuration */\n shortTerm: z.object({\n /** Maximum number of recent messages to retain */\n maxMessages: z.number().int().min(1).default(50).describe('Max recent messages in working memory'),\n\n /** Maximum token budget for short-term context */\n maxTokens: z.number().int().min(100).optional().describe('Max tokens for short-term context window'),\n }).optional().describe('Short-term / working memory'),\n\n /** Long-term (persistent) memory configuration */\n longTerm: z.object({\n /** Whether long-term memory is enabled */\n enabled: z.boolean().default(false).describe('Enable long-term memory persistence'),\n\n /** Storage backend for long-term memory */\n store: z.enum(['vector', 'database', 'redis']).default('vector').describe('Long-term memory storage backend'),\n\n /** Maximum number of persisted memory entries */\n maxEntries: z.number().int().min(1).optional().describe('Max entries in long-term memory'),\n }).optional().describe('Long-term / persistent memory'),\n\n /** Reflection interval — how often the agent reflects on past actions */\n reflectionInterval: z.number().int().min(1).optional().describe('Reflect every N interactions to improve behavior'),\n }).optional().describe('Agent memory management'),\n\n /** Guardrails */\n guardrails: z.object({\n /** Maximum tokens the agent may consume per invocation */\n maxTokensPerInvocation: z.number().int().min(1).optional().describe('Token budget per single invocation'),\n\n /** Maximum wall-clock time per invocation in seconds */\n maxExecutionTimeSec: z.number().int().min(1).optional().describe('Max execution time in seconds'),\n\n /** Topics or actions the agent must avoid */\n blockedTopics: z.array(z.string()).optional().describe('Forbidden topics or action names'),\n }).optional().describe('Safety guardrails for the agent'),\n\n /** Structured Output */\n structuredOutput: StructuredOutputConfigSchema.optional().describe('Structured output format and validation configuration'),\n});\n\n/**\n * Type-safe factory for creating AI agent definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example Agent-Skill Architecture (recommended)\n * ```ts\n * const supportAgent = defineAgent({\n * name: 'support_agent',\n * label: 'Support Agent',\n * role: 'Senior Support Engineer',\n * instructions: 'You help customers resolve technical issues.',\n * skills: ['case_management', 'knowledge_search'],\n * });\n * ```\n *\n * @example Legacy Tool References (backward-compatible)\n * ```ts\n * const supportAgent = defineAgent({\n * name: 'support_agent',\n * label: 'Support Agent',\n * role: 'Senior Support Engineer',\n * instructions: 'You help customers resolve technical issues.',\n * tools: [{ type: 'action', name: 'create_ticket' }],\n * });\n * ```\n */\nexport function defineAgent(config: z.input): Agent {\n return AgentSchema.parse(config);\n}\n\nexport type Agent = z.infer;\nexport type AITool = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Tool Category\n// ==========================================\n\n/**\n * Tool Category\n * Classifies the tool by its operational domain.\n */\nexport const ToolCategorySchema = z.enum([\n 'data', // CRUD / query operations\n 'action', // Side-effect actions (send email, create record)\n 'flow', // Trigger a visual flow\n 'integration', // External API / webhook calls\n 'vector_search', // RAG / vector search\n 'analytics', // Aggregation & reporting\n 'utility', // Formatters, parsers, helpers\n]).describe('Tool operational category');\n\nexport type ToolCategory = z.infer;\n\n// ==========================================\n// Tool Schema\n// ==========================================\n\n/**\n * Tool Schema\n *\n * First-class metadata definition for an AI-callable tool.\n * Tools are the atomic units of AI capability — each tool\n * represents a single, well-defined operation with strict\n * parameter validation via JSON Schema.\n *\n * Aligned with Salesforce Agentforce, Microsoft Copilot Studio,\n * and ServiceNow Now Assist metadata patterns.\n *\n * @example\n * ```ts\n * const tool = defineTool({\n * name: 'create_case',\n * label: 'Create Support Case',\n * description: 'Creates a new support case record',\n * category: 'action',\n * parameters: {\n * type: 'object',\n * properties: {\n * subject: { type: 'string', description: 'Case subject' },\n * priority: { type: 'string', enum: ['low', 'medium', 'high'] },\n * },\n * required: ['subject'],\n * },\n * objectName: 'support_case',\n * requiresConfirmation: true,\n * });\n * ```\n */\nexport const ToolSchema = z.object({\n /** Machine name (snake_case, globally unique) */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Tool unique identifier (snake_case)'),\n\n /** Human-readable display name */\n label: z.string().describe('Tool display name'),\n\n /** Detailed description for LLM consumption (the model reads this to decide when to call the tool) */\n description: z.string().describe('Tool description for LLM function calling'),\n\n /** Operational category */\n category: ToolCategorySchema.optional().describe('Tool category for grouping and filtering'),\n\n /**\n * JSON Schema describing the tool input parameters.\n * Must be a valid JSON Schema object. The AI model generates\n * arguments conforming to this schema.\n */\n parameters: z.record(z.string(), z.unknown()).describe('JSON Schema for tool parameters'),\n\n /**\n * Optional JSON Schema for the tool output.\n * Used for structured output validation and downstream tool chaining.\n */\n outputSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for tool output'),\n\n /**\n * Associated object name (when the tool operates on a specific data object).\n * @example 'support_case'\n */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object name (snake_case)'),\n\n /** Whether the tool requires human confirmation before execution */\n requiresConfirmation: z.boolean().default(false).describe('Require user confirmation before execution'),\n\n /** Permission profiles/roles required to use this tool */\n permissions: z.array(z.string()).optional().describe('Required permissions or roles'),\n\n /** Whether the tool is enabled */\n active: z.boolean().default(true).describe('Whether the tool is enabled'),\n\n /** Whether this is a platform built-in tool (vs. user-defined) */\n builtIn: z.boolean().default(false).describe('Platform built-in tool flag'),\n});\n\nexport type Tool = z.infer;\n\n// ==========================================\n// Factory\n// ==========================================\n\n/**\n * Type-safe factory for creating AI tool metadata definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const tool = defineTool({\n * name: 'query_orders',\n * label: 'Query Orders',\n * description: 'Search and filter customer orders',\n * category: 'data',\n * parameters: {\n * type: 'object',\n * properties: {\n * customerId: { type: 'string' },\n * status: { type: 'string', enum: ['pending', 'shipped', 'delivered'] },\n * },\n * required: ['customerId'],\n * },\n * });\n * ```\n */\nexport function defineTool(config: z.input): Tool {\n return ToolSchema.parse(config);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Trigger Condition\n// ==========================================\n\n/**\n * Skill Trigger Condition Schema\n *\n * Defines programmatic conditions under which a skill becomes active.\n * Allows context-aware activation based on object type, user role, etc.\n */\nexport const SkillTriggerConditionSchema = z.object({\n /** Condition field (e.g. 'objectName', 'userRole', 'channel') */\n field: z.string().describe('Context field to evaluate'),\n\n /** Comparison operator */\n operator: z.enum(['eq', 'neq', 'in', 'not_in', 'contains']).describe('Comparison operator'),\n\n /** Expected value(s) */\n value: z.union([z.string(), z.array(z.string())]).describe('Expected value or values'),\n});\n\nexport type SkillTriggerCondition = z.infer;\n\n// ==========================================\n// Skill Schema\n// ==========================================\n\n/**\n * Skill Schema\n *\n * An ability group that aggregates related tools by domain.\n * Skills are the middle tier of the Agent → Skill → Tool architecture,\n * providing reusable capability bundles that can be shared across agents.\n *\n * Aligned with Salesforce Agentforce Topics, Microsoft Copilot Studio Topics,\n * and ServiceNow Skill metadata patterns.\n *\n * @example\n * ```ts\n * const skill = defineSkill({\n * name: 'case_management',\n * label: 'Case Management',\n * description: 'Handles support case lifecycle',\n * instructions: 'Use these tools to create, update, and resolve support cases.',\n * tools: ['create_case', 'update_case', 'resolve_case', 'query_cases'],\n * triggerPhrases: ['create a case', 'open a ticket', 'resolve issue'],\n * });\n * ```\n */\nexport const SkillSchema = z.object({\n /** Machine name (snake_case, globally unique) */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Skill unique identifier (snake_case)'),\n\n /** Human-readable display name */\n label: z.string().describe('Skill display name'),\n\n /** Detailed description of the skill's purpose */\n description: z.string().optional().describe('Skill description'),\n\n /**\n * Instructions injected into the system prompt when this skill is active.\n * Guides the LLM on how and when to use the skill's tools.\n */\n instructions: z.string().optional().describe('LLM instructions when skill is active'),\n\n /**\n * References to tool names that belong to this skill.\n * Tools must be registered as first-class metadata (type: 'tool').\n */\n tools: z.array(z.string().regex(/^[a-z_][a-z0-9_]*$/)).describe('Tool names belonging to this skill'),\n\n /**\n * Natural language phrases that trigger skill activation.\n * Used for intent matching and skill routing.\n */\n triggerPhrases: z.array(z.string()).optional().describe('Phrases that activate this skill'),\n\n /**\n * Programmatic conditions for skill activation.\n * Evaluated against the runtime context (object name, user role, etc.).\n */\n triggerConditions: z.array(SkillTriggerConditionSchema).optional().describe('Programmatic activation conditions'),\n\n /** Permission profiles/roles required to use this skill */\n permissions: z.array(z.string()).optional().describe('Required permissions or roles'),\n\n /** Whether the skill is enabled */\n active: z.boolean().default(true).describe('Whether the skill is enabled'),\n});\n\nexport type Skill = z.infer;\n\n// ==========================================\n// Factory\n// ==========================================\n\n/**\n * Type-safe factory for creating AI skill definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const skill = defineSkill({\n * name: 'order_management',\n * label: 'Order Management',\n * description: 'Handles order lifecycle operations',\n * instructions: 'Use these tools to manage customer orders.',\n * tools: ['create_order', 'update_order', 'cancel_order'],\n * triggerPhrases: ['place an order', 'cancel my order'],\n * triggerConditions: [\n * { field: 'objectName', operator: 'eq', value: 'order' },\n * ],\n * });\n * ```\n */\nexport function defineSkill(config: z.input): Skill {\n return SkillSchema.parse(config);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * AI Agent Action Protocol\n * \n * Defines how AI agents can interact with the UI by mapping natural language intents\n * to structured UI actions. This enables agents to not only query data but also\n * manipulate the interface, navigate between views, and trigger workflows.\n * \n * Architecture Alignment:\n * - Salesforce Einstein: Action recommendations and automated UI interactions\n * - ServiceNow Virtual Agent: UI action automation\n * - Microsoft Power Virtual Agents: Bot actions and UI integration\n * \n * Use Cases:\n * - \"Open the new account form\" → Navigate to form view\n * - \"Show me all active opportunities\" → Navigate to list view with filter\n * - \"Create a new task for John\" → Open form with pre-filled data\n * - \"Switch to the kanban view\" → Change view mode\n */\n\n// ==========================================\n// UI Action Types\n// ==========================================\n\n/**\n * Navigation Action Types\n * Actions that change the current view or location\n */\nexport const NavigationActionTypeSchema = z.enum([\n 'navigate_to_object_list', // Navigate to object list view\n 'navigate_to_object_form', // Navigate to object form (new/edit)\n 'navigate_to_record_detail', // Navigate to specific record detail page\n 'navigate_to_dashboard', // Navigate to dashboard\n 'navigate_to_report', // Navigate to report view\n 'navigate_to_app', // Switch to different app\n 'navigate_back', // Go back to previous view\n 'navigate_home', // Go to home page\n 'open_tab', // Open new tab\n 'close_tab', // Close current tab\n]);\n\nexport type NavigationActionType = z.infer;\n\n/**\n * View Manipulation Action Types\n * Actions that change how data is displayed\n */\nexport const ViewActionTypeSchema = z.enum([\n 'change_view_mode', // Switch between list/kanban/calendar/gantt\n 'apply_filter', // Apply filter to current view\n 'clear_filter', // Clear filters\n 'apply_sort', // Apply sorting\n 'change_grouping', // Change grouping (for kanban/pivot)\n 'show_columns', // Show/hide columns\n 'expand_record', // Expand record in list\n 'collapse_record', // Collapse record in list\n 'refresh_view', // Refresh current view\n 'export_data', // Export view data\n]);\n\nexport type ViewActionType = z.infer;\n\n/**\n * Form Action Types\n * Actions that interact with forms\n */\nexport const FormActionTypeSchema = z.enum([\n 'create_record', // Create new record (submit form)\n 'update_record', // Update existing record\n 'delete_record', // Delete record\n 'fill_field', // Fill a specific form field\n 'clear_field', // Clear a form field\n 'submit_form', // Submit the form\n 'cancel_form', // Cancel form editing\n 'validate_form', // Validate form data\n 'save_draft', // Save as draft\n]);\n\nexport type FormActionType = z.infer;\n\n/**\n * Data Action Types\n * Actions that perform data operations\n */\nexport const DataActionTypeSchema = z.enum([\n 'select_record', // Select record(s) in list\n 'deselect_record', // Deselect record(s)\n 'select_all', // Select all records\n 'deselect_all', // Deselect all records\n 'bulk_update', // Bulk update selected records\n 'bulk_delete', // Bulk delete selected records\n 'bulk_export', // Bulk export selected records\n]);\n\nexport type DataActionType = z.infer;\n\n/**\n * Workflow Action Types\n * Actions that trigger workflows or automations\n */\nexport const WorkflowActionTypeSchema = z.enum([\n 'trigger_flow', // Trigger a flow/workflow\n 'trigger_approval', // Start approval process\n 'trigger_webhook', // Trigger webhook\n 'run_report', // Run a report\n 'send_email', // Send email\n 'send_notification', // Send notification\n 'schedule_task', // Schedule a task\n]);\n\nexport type WorkflowActionType = z.infer;\n\n/**\n * UI Component Action Types\n * Actions that interact with UI components\n */\nexport const ComponentActionTypeSchema = z.enum([\n 'open_modal', // Open modal dialog\n 'close_modal', // Close modal dialog\n 'open_sidebar', // Open sidebar panel\n 'close_sidebar', // Close sidebar panel\n 'show_notification', // Show toast/notification\n 'hide_notification', // Hide notification\n 'open_dropdown', // Open dropdown menu\n 'close_dropdown', // Close dropdown menu\n 'toggle_section', // Toggle collapsible section\n]);\n\nexport type ComponentActionType = z.infer;\n\n/**\n * All UI Action Types Combined\n */\nexport const UIActionTypeSchema = z.union([\n NavigationActionTypeSchema,\n ViewActionTypeSchema,\n FormActionTypeSchema,\n DataActionTypeSchema,\n WorkflowActionTypeSchema,\n ComponentActionTypeSchema,\n]);\n\nexport type UIActionType = z.infer;\n\n// ==========================================\n// Action Parameters\n// ==========================================\n\n/**\n * Navigation Action Parameters\n */\nexport const NavigationActionParamsSchema = z.object({\n object: z.string().optional().describe('Object name (for object-specific navigation)'),\n recordId: z.string().optional().describe('Record ID (for detail page)'),\n viewType: z.enum(['list', 'form', 'detail', 'kanban', 'calendar', 'gantt']).optional(),\n dashboardId: z.string().optional().describe('Dashboard ID'),\n reportId: z.string().optional().describe('Report ID'),\n appName: z.string().optional().describe('App name'),\n mode: z.enum(['new', 'edit', 'view']).optional().describe('Form mode'),\n openInNewTab: z.boolean().optional().describe('Open in new tab'),\n});\n\nexport type NavigationActionParams = z.infer;\n\n/**\n * View Action Parameters\n */\nexport const ViewActionParamsSchema = z.object({\n viewMode: z.enum(['list', 'kanban', 'calendar', 'gantt', 'pivot']).optional(),\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter conditions'),\n sort: z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc']),\n })).optional(),\n groupBy: z.string().optional().describe('Field to group by'),\n columns: z.array(z.string()).optional().describe('Columns to show/hide'),\n recordId: z.string().optional().describe('Record to expand/collapse'),\n exportFormat: z.enum(['csv', 'xlsx', 'pdf', 'json']).optional(),\n});\n\nexport type ViewActionParams = z.infer;\n\n/**\n * Form Action Parameters\n */\nexport const FormActionParamsSchema = z.object({\n object: z.string().optional().describe('Object name'),\n recordId: z.string().optional().describe('Record ID (for edit/delete)'),\n fieldValues: z.record(z.string(), z.unknown()).optional().describe('Field name-value pairs'),\n fieldName: z.string().optional().describe('Specific field to fill/clear'),\n fieldValue: z.unknown().optional().describe('Value to set'),\n validateOnly: z.boolean().optional().describe('Validate without saving'),\n});\n\nexport type FormActionParams = z.infer;\n\n/**\n * Data Action Parameters\n */\nexport const DataActionParamsSchema = z.object({\n recordIds: z.array(z.string()).optional().describe('Record IDs to select/operate on'),\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter for bulk operations'),\n updateData: z.record(z.string(), z.unknown()).optional().describe('Data for bulk update'),\n exportFormat: z.enum(['csv', 'xlsx', 'pdf', 'json']).optional(),\n});\n\nexport type DataActionParams = z.infer;\n\n/**\n * Workflow Action Parameters\n */\nexport const WorkflowActionParamsSchema = z.object({\n flowName: z.string().optional().describe('Flow/workflow name'),\n approvalProcessName: z.string().optional().describe('Approval process name'),\n webhookUrl: z.string().optional().describe('Webhook URL'),\n reportName: z.string().optional().describe('Report name'),\n emailTemplate: z.string().optional().describe('Email template'),\n recipients: z.array(z.string()).optional().describe('Email recipients'),\n subject: z.string().optional().describe('Email subject'),\n message: z.string().optional().describe('Notification/email message'),\n taskData: z.record(z.string(), z.unknown()).optional().describe('Task creation data'),\n scheduleTime: z.string().optional().describe('Schedule time (ISO 8601)'),\n contextData: z.record(z.string(), z.unknown()).optional().describe('Additional context data'),\n});\n\nexport type WorkflowActionParams = z.infer;\n\n/**\n * Component Action Parameters\n */\nexport const ComponentActionParamsSchema = z.object({\n componentId: z.string().optional().describe('Component ID'),\n modalConfig: z.object({\n title: z.string().optional(),\n content: z.unknown().optional(),\n size: z.enum(['small', 'medium', 'large', 'fullscreen']).optional(),\n }).optional(),\n notificationConfig: z.object({\n type: z.enum(['info', 'success', 'warning', 'error']).optional(),\n message: z.string(),\n duration: z.number().optional().describe('Duration in ms'),\n }).optional(),\n sidebarConfig: z.object({\n position: z.enum(['left', 'right']).optional(),\n width: z.string().optional(),\n content: z.unknown().optional(),\n }).optional(),\n});\n\nexport type ComponentActionParams = z.infer;\n\n// ==========================================\n// Agent Action Schema\n// ==========================================\n\n/**\n * Agent UI Action Schema\n * Complete definition of an AI agent's UI action\n */\nexport const AgentActionSchema = z.object({\n /**\n * Action identifier (generated)\n */\n id: z.string().optional().describe('Unique action ID'),\n \n /**\n * Action type\n */\n type: UIActionTypeSchema.describe('Type of UI action to perform'),\n \n /**\n * Action parameters (discriminated union based on type)\n */\n params: z.union([\n NavigationActionParamsSchema,\n ViewActionParamsSchema,\n FormActionParamsSchema,\n DataActionParamsSchema,\n WorkflowActionParamsSchema,\n ComponentActionParamsSchema,\n ]).describe('Action-specific parameters'),\n \n /**\n * Confirmation requirement\n */\n requireConfirmation: z.boolean().default(false).describe('Require user confirmation before executing'),\n \n /**\n * Confirmation message\n */\n confirmationMessage: z.string().optional().describe('Message to show in confirmation dialog'),\n \n /**\n * Success message\n */\n successMessage: z.string().optional().describe('Message to show on success'),\n \n /**\n * Error handling\n */\n onError: z.enum(['retry', 'skip', 'abort']).default('abort').describe('Error handling strategy'),\n \n /**\n * Execution metadata\n */\n metadata: z.object({\n intent: z.string().optional().describe('Original user intent/query'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n agentName: z.string().optional().describe('Agent that generated this action'),\n timestamp: z.string().datetime().optional().describe('Generation timestamp (ISO 8601)'),\n }).optional(),\n});\n\n/**\n * Agent Action Typed Schemas\n * Bind params to specific action types for type safety\n */\nexport const NavigationAgentActionSchema = AgentActionSchema.extend({\n type: NavigationActionTypeSchema,\n params: NavigationActionParamsSchema,\n});\n\nexport const ViewAgentActionSchema = AgentActionSchema.extend({\n type: ViewActionTypeSchema,\n params: ViewActionParamsSchema,\n});\n\nexport const FormAgentActionSchema = AgentActionSchema.extend({\n type: FormActionTypeSchema,\n params: FormActionParamsSchema,\n});\n\nexport const DataAgentActionSchema = AgentActionSchema.extend({\n type: DataActionTypeSchema,\n params: DataActionParamsSchema,\n});\n\nexport const WorkflowAgentActionSchema = AgentActionSchema.extend({\n type: WorkflowActionTypeSchema,\n params: WorkflowActionParamsSchema,\n});\n\nexport const ComponentAgentActionSchema = AgentActionSchema.extend({\n type: ComponentActionTypeSchema,\n params: ComponentActionParamsSchema,\n});\n\n/**\n * Typed Agent Action Union\n * Replaces the generic AgentActionSchema for stricter typing where possible\n */\nexport const TypedAgentActionSchema = z.union([\n NavigationAgentActionSchema,\n ViewAgentActionSchema,\n FormAgentActionSchema,\n DataAgentActionSchema,\n WorkflowAgentActionSchema,\n ComponentAgentActionSchema,\n]);\n\nexport type AgentAction = z.infer;\n\n/**\n * Agent Action Sequence Schema\n * Multiple actions to be executed in sequence\n */\nexport const AgentActionSequenceSchema = z.object({\n /**\n * Sequence identifier\n */\n id: z.string().optional().describe('Unique sequence ID'),\n \n /**\n * Actions to execute\n */\n actions: z.array(AgentActionSchema).describe('Ordered list of actions'),\n \n /**\n * Execution mode\n */\n mode: z.enum(['sequential', 'parallel']).default('sequential').describe('Execution mode'),\n \n /**\n * Stop on first error\n */\n stopOnError: z.boolean().default(true).describe('Stop sequence on first error'),\n \n /**\n * Transaction mode (all-or-nothing)\n */\n atomic: z.boolean().default(false).describe('Transaction mode (all-or-nothing)'),\n\n startTime: z.string().datetime().optional().describe('Execution start time (ISO 8601)'),\n\n endTime: z.string().datetime().optional().describe('Execution end time (ISO 8601)'),\n /**\n * Metadata\n */\n metadata: z.object({\n intent: z.string().optional().describe('Original user intent'),\n confidence: z.number().min(0).max(1).optional().describe('Overall confidence score'),\n agentName: z.string().optional().describe('Agent that generated this sequence'),\n }).optional(),\n});\n\nexport type AgentActionSequence = z.infer;\n\n/**\n * Agent Action Result Schema\n * Result of executing an agent action\n */\nexport const AgentActionResultSchema = z.object({\n /**\n * Action ID\n */\n actionId: z.string().describe('ID of the executed action'),\n \n /**\n * Execution status\n */\n status: z.enum(['success', 'error', 'cancelled', 'pending']).describe('Execution status'),\n \n /**\n * Result data\n */\n data: z.unknown().optional().describe('Action result data'),\n \n /**\n * Error information\n */\n error: z.object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n }).optional().describe('Error details if status is \"error\"'),\n \n /**\n * Execution metadata\n */\n metadata: z.object({\n startTime: z.string().optional().describe('Execution start time (ISO 8601)'),\n endTime: z.string().optional().describe('Execution end time (ISO 8601)'),\n duration: z.number().optional().describe('Execution duration in ms'),\n }).optional(),\n});\n\nexport type AgentActionResult = z.infer;\n\n/**\n * Agent Action Sequence Result Schema\n * Result of executing an action sequence\n */\nexport const AgentActionSequenceResultSchema = z.object({\n /**\n * Sequence ID\n */\n sequenceId: z.string().describe('ID of the executed sequence'),\n \n /**\n * Overall status\n */\n status: z.enum(['success', 'partial_success', 'error', 'cancelled']).describe('Overall execution status'),\n \n /**\n * Individual action results\n */\n results: z.array(AgentActionResultSchema).describe('Results for each action'),\n \n /**\n * Summary\n */\n summary: z.object({\n total: z.number().describe('Total number of actions'),\n successful: z.number().describe('Number of successful actions'),\n failed: z.number().describe('Number of failed actions'),\n cancelled: z.number().describe('Number of cancelled actions'),\n }),\n \n /**\n * Execution metadata\n */\n metadata: z.object({\n startTime: z.string().optional(),\n endTime: z.string().optional(),\n totalDuration: z.number().optional().describe('Total execution time in ms'),\n }).optional(),\n});\n\nexport type AgentActionSequenceResult = z.infer;\n\n// ==========================================\n// Helper Schemas\n// ==========================================\n\n/**\n * Intent to Action Mapping Schema\n * Maps natural language intent patterns to UI actions\n */\nexport const IntentActionMappingSchema = z.object({\n /**\n * Intent pattern (regex or exact match)\n */\n intent: z.string().describe('Intent pattern (e.g., \"open_new_record_form\")'),\n \n /**\n * Intent examples (for training)\n */\n examples: z.array(z.string()).optional().describe('Example user queries'),\n \n /**\n * Action template\n */\n actionTemplate: AgentActionSchema.describe('Action to execute'),\n \n /**\n * Parameter extraction rules\n */\n paramExtraction: z.record(z.string(), z.object({\n type: z.enum(['entity', 'slot', 'context']),\n required: z.boolean().default(false),\n default: z.unknown().optional(),\n })).optional().describe('Rules for extracting parameters from user input'),\n \n /**\n * Confidence threshold\n */\n minConfidence: z.number().min(0).max(1).default(0.7).describe('Minimum confidence to execute'),\n});\n\nexport type IntentActionMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { AgentSchema, AIToolSchema } from './agent.zod';\n\n/**\n * DevOps Agent Protocol\n * \n * Defines autonomous DevOps agents that can self-iterate on enterprise\n * management software development using the ObjectStack specification.\n * \n * This agent integrates with GitHub for version control and Vercel for\n * deployment, enabling fully automated development, testing, and release cycles.\n * \n * Architecture:\n * - Self-iterating development based on ObjectStack specifications\n * - Automated code generation following best practices\n * - Continuous integration and deployment\n * - Version management and release automation\n * - Monitoring and rollback capabilities\n * \n * Use Cases:\n * - Automated feature development from specifications\n * - Self-healing code based on test failures\n * - Automated dependency updates\n * - Continuous optimization and refactoring\n * - Automated documentation generation\n * \n * @example\n * ```typescript\n * import { DevOpsAgent } from '@objectstack/spec/ai';\n * \n * const agent: DevOpsAgent = {\n * name: 'devops_automation_agent',\n * label: 'DevOps Automation Agent',\n * role: 'Senior Full-Stack DevOps Engineer',\n * instructions: '...',\n * developmentConfig: {\n * specificationSource: 'packages/spec',\n * codeGeneration: {\n * enabled: true,\n * targets: ['frontend', 'backend', 'api'],\n * },\n * },\n * integrations: {\n * github: {\n * connector: 'github_production',\n * repository: {\n * owner: 'objectstack-ai',\n * name: 'app',\n * },\n * },\n * vercel: {\n * connector: 'vercel_production',\n * project: 'objectstack-app',\n * },\n * },\n * };\n * ```\n */\n\n/**\n * Code Generation Targets\n */\nexport const CodeGenerationTargetSchema = z.enum([\n 'frontend', // Frontend UI components\n 'backend', // Backend services\n 'api', // API endpoints\n 'database', // Database schemas\n 'tests', // Test suites\n 'documentation', // Documentation\n 'infrastructure', // Infrastructure as code\n]).describe('Code generation target');\n\nexport type CodeGenerationTarget = z.infer;\n\n/**\n * Code Generation Configuration\n */\nexport const CodeGenerationConfigSchema = z.object({\n /**\n * Enable code generation\n */\n enabled: z.boolean().optional().default(true).describe('Enable code generation'),\n \n /**\n * Generation targets\n */\n targets: z.array(CodeGenerationTargetSchema).describe('Code generation targets'),\n \n /**\n * Template repository\n */\n templateRepo: z.string().optional().describe('Template repository for scaffolding'),\n \n /**\n * Code style guide\n */\n styleGuide: z.string().optional().describe('Code style guide to follow'),\n \n /**\n * Include tests\n */\n includeTests: z.boolean().optional().default(true).describe('Generate tests with code'),\n \n /**\n * Include documentation\n */\n includeDocumentation: z.boolean().optional().default(true).describe('Generate documentation'),\n \n /**\n * Validation mode\n */\n validationMode: z.enum(['strict', 'moderate', 'permissive']).optional().default('strict').describe('Code validation strictness'),\n});\n\nexport type CodeGenerationConfig = z.infer;\n\n/**\n * Testing Configuration\n */\nexport const TestingConfigSchema = z.object({\n /**\n * Enable automated testing\n */\n enabled: z.boolean().optional().default(true).describe('Enable automated testing'),\n \n /**\n * Test types to run\n */\n testTypes: z.array(z.enum([\n 'unit',\n 'integration',\n 'e2e',\n 'performance',\n 'security',\n 'accessibility',\n ])).optional().default(['unit', 'integration']).describe('Types of tests to run'),\n \n /**\n * Minimum coverage threshold\n */\n coverageThreshold: z.number().min(0).max(100).optional().default(80).describe('Minimum test coverage percentage'),\n \n /**\n * Test framework\n */\n framework: z.string().optional().describe('Testing framework (e.g., vitest, jest, playwright)'),\n \n /**\n * Run tests before commit\n */\n preCommitTests: z.boolean().optional().default(true).describe('Run tests before committing'),\n \n /**\n * Auto-fix failing tests\n */\n autoFix: z.boolean().optional().default(false).describe('Attempt to auto-fix failing tests'),\n});\n\nexport type TestingConfig = z.infer;\n\n/**\n * CI/CD Pipeline Stage\n */\nexport const PipelineStageSchema = z.object({\n /**\n * Stage name\n */\n name: z.string().describe('Pipeline stage name'),\n \n /**\n * Stage type\n */\n type: z.enum([\n 'build',\n 'test',\n 'lint',\n 'security_scan',\n 'deploy',\n 'smoke_test',\n 'rollback',\n ]).describe('Stage type'),\n \n /**\n * Stage order\n */\n order: z.number().int().min(0).describe('Execution order'),\n \n /**\n * Run in parallel\n */\n parallel: z.boolean().optional().default(false).describe('Can run in parallel with other stages'),\n \n /**\n * Commands to execute\n */\n commands: z.array(z.string()).describe('Commands to execute'),\n \n /**\n * Environment variables\n */\n env: z.record(z.string(), z.string()).optional().describe('Stage-specific environment variables'),\n \n /**\n * Timeout in seconds\n */\n timeout: z.number().int().min(60).optional().default(600).describe('Stage timeout in seconds'),\n \n /**\n * Retry on failure\n */\n retryOnFailure: z.boolean().optional().default(false).describe('Retry stage on failure'),\n \n /**\n * Max retry attempts\n */\n maxRetries: z.number().int().min(0).max(5).optional().default(0).describe('Maximum retry attempts'),\n});\n\nexport type PipelineStage = z.infer;\n\n/**\n * CI/CD Pipeline Configuration\n */\nexport const CICDPipelineConfigSchema = z.object({\n /**\n * Pipeline name\n */\n name: z.string().describe('Pipeline name'),\n \n /**\n * Pipeline trigger\n */\n trigger: z.enum([\n 'push',\n 'pull_request',\n 'release',\n 'schedule',\n 'manual',\n ]).describe('Pipeline trigger'),\n \n /**\n * Branch filters\n */\n branches: z.array(z.string()).optional().describe('Branches to run pipeline on'),\n \n /**\n * Pipeline stages\n */\n stages: z.array(PipelineStageSchema).describe('Pipeline stages'),\n \n /**\n * Enable notifications\n */\n notifications: z.object({\n onSuccess: z.boolean().optional().default(false),\n onFailure: z.boolean().optional().default(true),\n channels: z.array(z.string()).optional().describe('Notification channels (e.g., slack, email)'),\n }).optional().describe('Pipeline notifications'),\n});\n\nexport type CICDPipelineConfig = z.infer;\n\n/**\n * Version Management Configuration\n */\nexport const VersionManagementSchema = z.object({\n /**\n * Versioning scheme\n */\n scheme: z.enum(['semver', 'calver', 'custom']).optional().default('semver').describe('Versioning scheme'),\n \n /**\n * Auto-increment strategy\n */\n autoIncrement: z.enum(['major', 'minor', 'patch', 'none']).optional().default('patch').describe('Auto-increment strategy'),\n \n /**\n * Version prefix\n */\n prefix: z.string().optional().default('v').describe('Version tag prefix'),\n \n /**\n * Create changelog\n */\n generateChangelog: z.boolean().optional().default(true).describe('Generate changelog automatically'),\n \n /**\n * Changelog format\n */\n changelogFormat: z.enum(['conventional', 'keepachangelog', 'custom']).optional().default('conventional').describe('Changelog format'),\n \n /**\n * Tag releases\n */\n tagReleases: z.boolean().optional().default(true).describe('Create Git tags for releases'),\n});\n\nexport type VersionManagement = z.infer;\n\n/**\n * Deployment Strategy Configuration\n */\nexport const DeploymentStrategySchema = z.object({\n /**\n * Strategy type\n */\n type: z.enum([\n 'rolling',\n 'blue_green',\n 'canary',\n 'recreate',\n ]).optional().default('rolling').describe('Deployment strategy'),\n \n /**\n * Canary percentage (for canary deployments)\n */\n canaryPercentage: z.number().min(0).max(100).optional().default(10).describe('Canary deployment percentage'),\n \n /**\n * Health check URL\n */\n healthCheckUrl: z.string().optional().describe('Health check endpoint'),\n \n /**\n * Health check timeout\n */\n healthCheckTimeout: z.number().int().min(10).optional().default(60).describe('Health check timeout in seconds'),\n \n /**\n * Rollback on failure\n */\n autoRollback: z.boolean().optional().default(true).describe('Automatically rollback on failure'),\n \n /**\n * Smoke tests\n */\n smokeTests: z.array(z.string()).optional().describe('Smoke test commands to run post-deployment'),\n});\n\nexport type DeploymentStrategy = z.infer;\n\n/**\n * Monitoring Configuration\n */\nexport const MonitoringConfigSchema = z.object({\n /**\n * Enable monitoring\n */\n enabled: z.boolean().optional().default(true).describe('Enable monitoring'),\n \n /**\n * Metrics to track\n */\n metrics: z.array(z.enum([\n 'performance',\n 'errors',\n 'usage',\n 'availability',\n 'latency',\n ])).optional().default(['performance', 'errors', 'availability']).describe('Metrics to monitor'),\n \n /**\n * Alert thresholds\n */\n alerts: z.array(z.object({\n name: z.string().describe('Alert name'),\n metric: z.string().describe('Metric to monitor'),\n threshold: z.number().describe('Alert threshold'),\n severity: z.enum(['info', 'warning', 'critical']).describe('Alert severity'),\n })).optional().describe('Alert configurations'),\n \n /**\n * Monitoring integrations\n */\n integrations: z.array(z.string()).optional().describe('Monitoring service integrations'),\n});\n\nexport type MonitoringConfig = z.infer;\n\n/**\n * Development Configuration\n */\nexport const DevelopmentConfigSchema = z.object({\n /**\n * ObjectStack specification source\n */\n specificationSource: z.string().describe('Path to ObjectStack specification'),\n \n /**\n * Code generation configuration\n */\n codeGeneration: CodeGenerationConfigSchema.describe('Code generation settings'),\n \n /**\n * Testing configuration\n */\n testing: TestingConfigSchema.optional().describe('Testing configuration'),\n \n /**\n * Linting configuration\n */\n linting: z.object({\n enabled: z.boolean().optional().default(true),\n autoFix: z.boolean().optional().default(true),\n rules: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Code linting configuration'),\n \n /**\n * Formatting configuration\n */\n formatting: z.object({\n enabled: z.boolean().optional().default(true),\n autoFormat: z.boolean().optional().default(true),\n config: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Code formatting configuration'),\n});\n\nexport type DevelopmentConfig = z.infer;\n\n/**\n * GitHub Integration Configuration\n */\nexport const GitHubIntegrationSchema = z.object({\n /**\n * GitHub connector reference\n */\n connector: z.string().describe('GitHub connector name'),\n \n /**\n * Repository configuration\n */\n repository: z.object({\n owner: z.string().describe('Repository owner'),\n name: z.string().describe('Repository name'),\n }).describe('Repository configuration'),\n \n /**\n * Default branch for features\n */\n featureBranch: z.string().optional().default('develop').describe('Default feature branch'),\n \n /**\n * Pull request configuration\n */\n pullRequest: z.object({\n autoCreate: z.boolean().optional().default(true).describe('Automatically create PRs'),\n autoMerge: z.boolean().optional().default(false).describe('Automatically merge PRs when checks pass'),\n requireReviews: z.boolean().optional().default(true).describe('Require reviews before merge'),\n deleteBranchOnMerge: z.boolean().optional().default(true).describe('Delete feature branch after merge'),\n }).optional().describe('Pull request settings'),\n});\n\nexport type GitHubIntegration = z.infer;\n\n/**\n * Vercel Integration Configuration\n */\nexport const VercelIntegrationSchema = z.object({\n /**\n * Vercel connector reference\n */\n connector: z.string().describe('Vercel connector name'),\n \n /**\n * Project name\n */\n project: z.string().describe('Vercel project name'),\n \n /**\n * Environment mapping\n */\n environments: z.object({\n production: z.string().optional().default('main').describe('Production branch'),\n preview: z.array(z.string()).optional().default(['develop', 'feature/*']).describe('Preview branches'),\n }).optional().describe('Environment mapping'),\n \n /**\n * Deployment configuration\n */\n deployment: z.object({\n autoDeployProduction: z.boolean().optional().default(false).describe('Auto-deploy to production'),\n autoDeployPreview: z.boolean().optional().default(true).describe('Auto-deploy preview environments'),\n requireApproval: z.boolean().optional().default(true).describe('Require approval for production deployments'),\n }).optional().describe('Deployment settings'),\n});\n\nexport type VercelIntegration = z.infer;\n\n/**\n * Integration Configuration\n */\nexport const IntegrationConfigSchema = z.object({\n /**\n * GitHub integration\n */\n github: GitHubIntegrationSchema.describe('GitHub integration configuration'),\n \n /**\n * Vercel integration\n */\n vercel: VercelIntegrationSchema.describe('Vercel integration configuration'),\n \n /**\n * Additional integrations\n */\n additional: z.record(z.string(), z.unknown()).optional().describe('Additional integration configurations'),\n});\n\nexport type IntegrationConfig = z.infer;\n\n/**\n * DevOps Agent Schema\n * Complete autonomous DevOps agent configuration\n */\nexport const DevOpsAgentSchema = AgentSchema.extend({\n /**\n * Development configuration\n */\n developmentConfig: DevelopmentConfigSchema.describe('Development configuration'),\n \n /**\n * CI/CD pipelines\n */\n pipelines: z.array(CICDPipelineConfigSchema).optional().describe('CI/CD pipelines'),\n \n /**\n * Version management\n */\n versionManagement: VersionManagementSchema.optional().describe('Version management configuration'),\n \n /**\n * Deployment strategy\n */\n deploymentStrategy: DeploymentStrategySchema.optional().describe('Deployment strategy'),\n \n /**\n * Monitoring configuration\n */\n monitoring: MonitoringConfigSchema.optional().describe('Monitoring configuration'),\n \n /**\n * Integration configuration\n */\n integrations: IntegrationConfigSchema.describe('Integration configurations'),\n \n /**\n * Self-iteration configuration\n */\n selfIteration: z.object({\n enabled: z.boolean().optional().default(true).describe('Enable self-iteration'),\n iterationFrequency: z.string().optional().describe('Iteration frequency (cron expression)'),\n optimizationGoals: z.array(z.enum([\n 'performance',\n 'security',\n 'code_quality',\n 'test_coverage',\n 'documentation',\n ])).optional().describe('Optimization goals'),\n learningMode: z.enum(['conservative', 'balanced', 'aggressive']).optional().default('balanced').describe('Learning mode'),\n }).optional().describe('Self-iteration configuration'),\n});\n\nexport type DevOpsAgent = z.infer;\n\n/**\n * DevOps Tools Extension\n * Additional tools available to DevOps agents\n */\nexport const DevOpsToolSchema = AIToolSchema.extend({\n type: z.enum([\n 'action',\n 'flow',\n 'query',\n 'vector_search',\n // DevOps-specific tools\n 'git_operation',\n 'code_generation',\n 'test_execution',\n 'deployment',\n 'monitoring',\n ]),\n});\n\nexport type DevOpsTool = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Full-Stack DevOps Agent\n */\nexport const fullStackDevOpsAgentExample: DevOpsAgent = {\n name: 'devops_automation_agent',\n label: 'DevOps Automation Agent',\n visibility: 'organization',\n avatar: '/avatars/devops-bot.png',\n role: 'Senior Full-Stack DevOps Engineer',\n \n instructions: `You are an autonomous DevOps agent specialized in enterprise management software development.\n\nYour responsibilities:\n1. Generate code based on ObjectStack specifications\n2. Write comprehensive tests for all generated code\n3. Ensure code quality through linting and formatting\n4. Manage Git workflow (commits, branches, PRs)\n5. Deploy applications to Vercel\n6. Monitor deployments and handle rollbacks\n7. Continuously optimize and iterate on the codebase\n\nGuidelines:\n- Follow ObjectStack naming conventions (camelCase for props, snake_case for names)\n- Write clean, maintainable, well-documented code\n- Ensure 80%+ test coverage\n- Use conventional commit messages\n- Create detailed PR descriptions\n- Deploy only after all checks pass\n- Monitor production deployments closely\n- Learn from failures and optimize continuously\n\nAlways prioritize code quality, security, and maintainability.`,\n \n model: {\n provider: 'openai',\n model: 'gpt-4-turbo-preview',\n temperature: 0.3,\n maxTokens: 8192,\n },\n \n tools: [\n {\n type: 'action',\n name: 'generate_from_spec',\n description: 'Generate code from ObjectStack specification',\n },\n {\n type: 'action',\n name: 'run_tests',\n description: 'Execute test suites',\n },\n {\n type: 'action',\n name: 'commit_and_push',\n description: 'Commit changes and push to GitHub',\n },\n {\n type: 'action',\n name: 'create_pull_request',\n description: 'Create pull request on GitHub',\n },\n {\n type: 'action',\n name: 'deploy_to_vercel',\n description: 'Deploy application to Vercel',\n },\n {\n type: 'action',\n name: 'check_deployment_health',\n description: 'Check deployment health status',\n },\n {\n type: 'action',\n name: 'rollback_deployment',\n description: 'Rollback to previous deployment',\n },\n ],\n \n knowledge: {\n topics: [\n 'objectstack_protocol',\n 'typescript_best_practices',\n 'testing_strategies',\n 'ci_cd_patterns',\n 'deployment_strategies',\n ],\n indexes: ['devops_knowledge_base'],\n },\n \n developmentConfig: {\n specificationSource: 'packages/spec',\n \n codeGeneration: {\n enabled: true,\n targets: ['frontend', 'backend', 'api', 'tests', 'documentation'],\n styleGuide: 'objectstack',\n includeTests: true,\n includeDocumentation: true,\n validationMode: 'strict',\n },\n \n testing: {\n enabled: true,\n testTypes: ['unit', 'integration', 'e2e'],\n coverageThreshold: 80,\n framework: 'vitest',\n preCommitTests: true,\n autoFix: false,\n },\n \n linting: {\n enabled: true,\n autoFix: true,\n },\n \n formatting: {\n enabled: true,\n autoFormat: true,\n },\n },\n \n pipelines: [\n {\n name: 'CI Pipeline',\n trigger: 'pull_request',\n branches: ['main', 'develop'],\n stages: [\n {\n name: 'Install Dependencies',\n type: 'build',\n order: 1,\n commands: ['pnpm install'],\n timeout: 300,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Lint',\n type: 'lint',\n order: 2,\n parallel: true,\n commands: ['pnpm run lint'],\n timeout: 180,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Type Check',\n type: 'lint',\n order: 2,\n parallel: true,\n commands: ['pnpm run type-check'],\n timeout: 180,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Test',\n type: 'test',\n order: 3,\n commands: ['pnpm run test:ci'],\n timeout: 600,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Build',\n type: 'build',\n order: 4,\n commands: ['pnpm run build'],\n timeout: 600,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Security Scan',\n type: 'security_scan',\n order: 5,\n commands: ['pnpm audit', 'pnpm run security-scan'],\n timeout: 300,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n ],\n },\n {\n name: 'CD Pipeline',\n trigger: 'push',\n branches: ['main'],\n stages: [\n {\n name: 'Deploy to Production',\n type: 'deploy',\n order: 1,\n commands: ['vercel deploy --prod'],\n timeout: 600,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Smoke Tests',\n type: 'smoke_test',\n order: 2,\n commands: ['pnpm run test:smoke'],\n timeout: 300,\n parallel: false,\n retryOnFailure: true,\n maxRetries: 2,\n },\n ],\n notifications: {\n onSuccess: true,\n onFailure: true,\n channels: ['slack', 'email'],\n },\n },\n ],\n \n versionManagement: {\n scheme: 'semver',\n autoIncrement: 'patch',\n prefix: 'v',\n generateChangelog: true,\n changelogFormat: 'conventional',\n tagReleases: true,\n },\n \n deploymentStrategy: {\n type: 'rolling',\n healthCheckUrl: '/api/health',\n healthCheckTimeout: 60,\n autoRollback: true,\n smokeTests: ['pnpm run test:smoke'],\n canaryPercentage: 10,\n },\n \n monitoring: {\n enabled: true,\n metrics: ['performance', 'errors', 'availability'],\n alerts: [\n {\n name: 'High Error Rate',\n metric: 'error_rate',\n threshold: 0.05,\n severity: 'critical',\n },\n {\n name: 'Slow Response Time',\n metric: 'response_time',\n threshold: 1000,\n severity: 'warning',\n },\n ],\n integrations: ['vercel', 'datadog'],\n },\n \n integrations: {\n github: {\n connector: 'github_production',\n repository: {\n owner: 'objectstack-ai',\n name: 'app',\n },\n featureBranch: 'develop',\n pullRequest: {\n autoCreate: true,\n autoMerge: false,\n requireReviews: true,\n deleteBranchOnMerge: true,\n },\n },\n \n vercel: {\n connector: 'vercel_production',\n project: 'objectstack-app',\n environments: {\n production: 'main',\n preview: ['develop', 'feature/*'],\n },\n deployment: {\n autoDeployProduction: false,\n autoDeployPreview: true,\n requireApproval: true,\n },\n },\n },\n \n selfIteration: {\n enabled: true,\n iterationFrequency: '0 0 * * 0', // Weekly on Sunday\n optimizationGoals: ['code_quality', 'test_coverage', 'performance'],\n learningMode: 'balanced',\n },\n \n active: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # AI-Driven Plugin Development Protocol\n * \n * Defines protocols for AI-powered plugin development including:\n * - Natural language to code generation\n * - Intelligent code scaffolding\n * - Automated testing and validation\n * - AI-powered code review and optimization\n * - Plugin composition and recommendation\n */\n\n/**\n * Code Generation Request\n * Request for AI to generate plugin code\n */\nexport const CodeGenerationRequestSchema = z.object({\n /**\n * Natural language description of desired functionality\n */\n description: z.string().describe('What the plugin should do'),\n \n /**\n * Plugin type to generate\n */\n pluginType: z.enum([\n 'driver', // Data driver plugin\n 'app', // Application plugin\n 'widget', // UI widget\n 'integration', // External integration\n 'automation', // Automation/workflow\n 'analytics', // Analytics plugin\n 'ai-agent', // AI agent plugin\n 'custom', // Custom plugin type\n ]),\n \n /**\n * Output format for generated code\n */\n outputFormat: z.enum([\n 'source-code', // Generate TypeScript/JavaScript source code\n 'low-code-schema', // Generate ObjectStack JSON/YAML schema definitions\n 'dsl', // Generate domain-specific language definitions\n ]).default('source-code')\n .describe('Format of the generated output'),\n \n /**\n * Target programming language (for source-code format)\n */\n language: z.enum(['typescript', 'javascript', 'python']).default('typescript'),\n \n /**\n * Framework preferences\n */\n framework: z.object({\n runtime: z.enum(['node', 'browser', 'edge', 'universal']).optional(),\n uiFramework: z.enum(['react', 'vue', 'svelte', 'none']).optional(),\n testing: z.enum(['vitest', 'jest', 'mocha', 'none']).optional(),\n }).optional(),\n \n /**\n * Required capabilities\n */\n capabilities: z.array(z.string()).optional().describe('Protocol IDs to implement'),\n \n /**\n * Dependencies\n */\n dependencies: z.array(z.string()).optional().describe('Required plugin IDs'),\n \n /**\n * Example usage (helps AI understand intent)\n */\n examples: z.array(z.object({\n input: z.string(),\n expectedOutput: z.string(),\n description: z.string().optional(),\n })).optional(),\n \n /**\n * Code style preferences (for source-code format)\n */\n style: z.object({\n indentation: z.enum(['tab', '2spaces', '4spaces']).default('2spaces'),\n quotes: z.enum(['single', 'double']).default('single'),\n semicolons: z.boolean().default(true),\n trailingComma: z.boolean().default(true),\n }).optional(),\n \n /**\n * Low-code schema preferences (for low-code-schema format)\n */\n schemaOptions: z.object({\n /**\n * Schema format\n */\n format: z.enum(['json', 'yaml', 'typescript']).default('typescript')\n .describe('Output schema format'),\n \n /**\n * Include example data\n */\n includeExamples: z.boolean().default(true),\n \n /**\n * Validation strictness\n */\n strictValidation: z.boolean().default(true),\n \n /**\n * Generate UI definitions\n */\n generateUI: z.boolean().default(true)\n .describe('Generate view, dashboard, and page definitions'),\n \n /**\n * Generate data models\n */\n generateDataModels: z.boolean().default(true)\n .describe('Generate object and field definitions'),\n }).optional(),\n \n /**\n * Additional context\n */\n context: z.object({\n /**\n * Existing code to extend\n */\n existingCode: z.string().optional(),\n \n /**\n * Related documentation URLs\n */\n documentationUrls: z.array(z.string()).optional(),\n \n /**\n * Similar plugins for reference\n */\n referencePlugins: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Generation options\n */\n options: z.object({\n /**\n * Include tests\n */\n generateTests: z.boolean().default(true),\n \n /**\n * Include documentation\n */\n generateDocs: z.boolean().default(true),\n \n /**\n * Include examples\n */\n generateExamples: z.boolean().default(true),\n \n /**\n * Code coverage target\n */\n targetCoverage: z.number().min(0).max(100).default(80),\n \n /**\n * Optimization level\n */\n optimizationLevel: z.enum(['none', 'basic', 'aggressive']).default('basic'),\n }).optional(),\n});\n\n/**\n * Generated Code\n * Result of code generation\n */\nexport const GeneratedCodeSchema = z.object({\n /**\n * Output format used\n */\n outputFormat: z.enum(['source-code', 'low-code-schema', 'dsl']),\n \n /**\n * Main plugin code (for source-code format)\n */\n code: z.string().optional(),\n \n /**\n * Language used (for source-code format)\n */\n language: z.string().optional(),\n \n /**\n * Low-code schema definitions (for low-code-schema format)\n */\n schemas: z.array(z.object({\n type: z.enum(['object', 'view', 'dashboard', 'app', 'workflow', 'api', 'page']),\n path: z.string().describe('File path for the schema'),\n content: z.string().describe('Schema content (JSON/YAML/TypeScript)'),\n description: z.string().optional(),\n })).optional()\n .describe('Generated low-code schema files'),\n \n /**\n * File structure\n */\n files: z.array(z.object({\n path: z.string(),\n content: z.string(),\n description: z.string().optional(),\n })),\n \n /**\n * Generated tests\n */\n tests: z.array(z.object({\n path: z.string(),\n content: z.string(),\n coverage: z.number().min(0).max(100).optional(),\n })).optional(),\n \n /**\n * Documentation\n */\n documentation: z.object({\n readme: z.string().optional(),\n api: z.string().optional(),\n usage: z.string().optional(),\n }).optional(),\n \n /**\n * Package metadata\n */\n package: z.object({\n name: z.string(),\n version: z.string(),\n dependencies: z.record(z.string(), z.string()).optional(),\n devDependencies: z.record(z.string(), z.string()).optional(),\n }).optional(),\n \n /**\n * Quality metrics\n */\n quality: z.object({\n complexity: z.number().optional().describe('Cyclomatic complexity'),\n maintainability: z.number().min(0).max(100).optional(),\n testCoverage: z.number().min(0).max(100).optional(),\n lintScore: z.number().min(0).max(100).optional(),\n }).optional(),\n \n /**\n * AI confidence score\n */\n confidence: z.number().min(0).max(100).describe('AI confidence in generated code'),\n \n /**\n * Suggestions for improvement\n */\n suggestions: z.array(z.string()).optional(),\n \n /**\n * Warnings or caveats\n */\n warnings: z.array(z.string()).optional(),\n});\n\n/**\n * Plugin Scaffolding Template\n * Template for plugin structure\n */\nexport const PluginScaffoldingTemplateSchema = z.object({\n /**\n * Template identifier\n */\n id: z.string(),\n \n /**\n * Template name\n */\n name: z.string(),\n \n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Plugin type\n */\n pluginType: z.string(),\n \n /**\n * File structure\n */\n structure: z.array(z.object({\n type: z.enum(['file', 'directory']),\n path: z.string(),\n template: z.string().optional().describe('Template content with variables'),\n optional: z.boolean().default(false),\n })),\n \n /**\n * Variables to be filled\n */\n variables: z.array(z.object({\n name: z.string(),\n description: z.string(),\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']),\n required: z.boolean().default(true),\n default: z.unknown().optional(),\n validation: z.string().optional().describe('Validation regex or rule'),\n })),\n \n /**\n * Post-scaffold scripts\n */\n scripts: z.array(z.object({\n name: z.string(),\n command: z.string(),\n description: z.string().optional(),\n optional: z.boolean().default(false),\n })).optional(),\n});\n\n/**\n * AI Code Review Result\n * Result of AI-powered code review\n */\nexport const AICodeReviewResultSchema = z.object({\n /**\n * Overall assessment\n */\n assessment: z.enum(['excellent', 'good', 'acceptable', 'needs-improvement', 'poor']),\n \n /**\n * Overall score (0-100)\n */\n score: z.number().min(0).max(100),\n \n /**\n * Issues found\n */\n issues: z.array(z.object({\n severity: z.enum(['critical', 'error', 'warning', 'info', 'style']),\n category: z.enum([\n 'bug',\n 'security',\n 'performance',\n 'maintainability',\n 'style',\n 'documentation',\n 'testing',\n 'type-safety',\n 'best-practice',\n ]),\n file: z.string(),\n line: z.number().int().optional(),\n column: z.number().int().optional(),\n message: z.string(),\n suggestion: z.string().optional(),\n autoFixable: z.boolean().default(false),\n autoFix: z.string().optional().describe('Automated fix code'),\n })),\n \n /**\n * Positive highlights\n */\n highlights: z.array(z.object({\n category: z.string(),\n description: z.string(),\n file: z.string().optional(),\n })).optional(),\n \n /**\n * Quality metrics\n */\n metrics: z.object({\n complexity: z.number().optional(),\n maintainability: z.number().min(0).max(100).optional(),\n testCoverage: z.number().min(0).max(100).optional(),\n duplicateCode: z.number().min(0).max(100).optional(),\n technicalDebt: z.string().optional().describe('Estimated technical debt'),\n }).optional(),\n \n /**\n * Recommendations\n */\n recommendations: z.array(z.object({\n priority: z.enum(['high', 'medium', 'low']),\n title: z.string(),\n description: z.string(),\n effort: z.enum(['trivial', 'small', 'medium', 'large']).optional(),\n })),\n \n /**\n * Security analysis\n */\n security: z.object({\n vulnerabilities: z.array(z.object({\n severity: z.enum(['critical', 'high', 'medium', 'low']),\n type: z.string(),\n description: z.string(),\n remediation: z.string().optional(),\n })).optional(),\n score: z.number().min(0).max(100).optional(),\n }).optional(),\n});\n\n/**\n * Plugin Composition Request\n * Request for AI to compose multiple plugins together\n */\nexport const PluginCompositionRequestSchema = z.object({\n /**\n * Desired outcome\n */\n goal: z.string().describe('What should the composed plugins achieve'),\n \n /**\n * Available plugins\n */\n availablePlugins: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n capabilities: z.array(z.string()).optional(),\n description: z.string().optional(),\n })),\n \n /**\n * Constraints\n */\n constraints: z.object({\n /**\n * Maximum plugins to use\n */\n maxPlugins: z.number().int().min(1).optional(),\n \n /**\n * Required plugins\n */\n requiredPlugins: z.array(z.string()).optional(),\n \n /**\n * Excluded plugins\n */\n excludedPlugins: z.array(z.string()).optional(),\n \n /**\n * Performance requirements\n */\n performance: z.object({\n maxLatency: z.number().optional().describe('Maximum latency in ms'),\n maxMemory: z.number().optional().describe('Maximum memory in bytes'),\n }).optional(),\n }).optional(),\n \n /**\n * Optimization criteria\n */\n optimize: z.enum([\n 'performance',\n 'reliability',\n 'simplicity',\n 'cost',\n 'security',\n ]).optional(),\n});\n\n/**\n * Plugin Composition Result\n * AI-generated plugin composition\n */\nexport const PluginCompositionResultSchema = z.object({\n /**\n * Selected plugins\n */\n plugins: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n role: z.string().describe('Role in the composition'),\n configuration: z.record(z.string(), z.unknown()).optional(),\n })),\n \n /**\n * Integration code\n */\n integration: z.object({\n /**\n * Glue code to connect plugins\n */\n code: z.string(),\n \n /**\n * Configuration\n */\n config: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Initialization order\n */\n initOrder: z.array(z.string()),\n }),\n \n /**\n * Data flow diagram\n */\n dataFlow: z.array(z.object({\n from: z.string(),\n to: z.string(),\n data: z.string().describe('Data type or description'),\n })),\n \n /**\n * Expected performance\n */\n performance: z.object({\n estimatedLatency: z.number().optional().describe('Estimated latency in ms'),\n estimatedMemory: z.number().optional().describe('Estimated memory in bytes'),\n }).optional(),\n \n /**\n * Confidence score\n */\n confidence: z.number().min(0).max(100),\n \n /**\n * Alternative compositions\n */\n alternatives: z.array(z.object({\n description: z.string(),\n plugins: z.array(z.string()),\n tradeoffs: z.string(),\n })).optional(),\n \n /**\n * Warnings and considerations\n */\n warnings: z.array(z.string()).optional(),\n});\n\n/**\n * Plugin Recommendation Request\n * Request for plugin recommendations\n */\nexport const PluginRecommendationRequestSchema = z.object({\n /**\n * User context\n */\n context: z.object({\n /**\n * Current plugins installed\n */\n installedPlugins: z.array(z.string()).optional(),\n \n /**\n * User's industry\n */\n industry: z.string().optional(),\n \n /**\n * Use cases\n */\n useCases: z.array(z.string()).optional(),\n \n /**\n * Team size\n */\n teamSize: z.number().int().optional(),\n \n /**\n * Budget constraints\n */\n budget: z.enum(['free', 'low', 'medium', 'high', 'unlimited']).optional(),\n }),\n \n /**\n * Recommendation criteria\n */\n criteria: z.object({\n /**\n * Prioritize by\n */\n prioritize: z.enum([\n 'popularity',\n 'rating',\n 'compatibility',\n 'features',\n 'cost',\n 'support',\n ]).optional(),\n \n /**\n * Only certified plugins\n */\n certifiedOnly: z.boolean().default(false),\n \n /**\n * Minimum rating\n */\n minRating: z.number().min(0).max(5).optional(),\n \n /**\n * Maximum results\n */\n maxResults: z.number().int().min(1).max(50).default(10),\n }).optional(),\n});\n\n/**\n * Plugin Recommendation\n * AI-generated plugin recommendation\n */\nexport const PluginRecommendationSchema = z.object({\n /**\n * Recommended plugins\n */\n recommendations: z.array(z.object({\n pluginId: z.string(),\n name: z.string(),\n description: z.string(),\n score: z.number().min(0).max(100).describe('Relevance score'),\n reasons: z.array(z.string()).describe('Why this plugin is recommended'),\n benefits: z.array(z.string()),\n considerations: z.array(z.string()).optional(),\n alternatives: z.array(z.string()).optional(),\n estimatedValue: z.string().optional().describe('Expected value/ROI'),\n })),\n \n /**\n * Recommended combinations\n */\n combinations: z.array(z.object({\n plugins: z.array(z.string()),\n description: z.string(),\n synergies: z.array(z.string()).describe('How these plugins work well together'),\n totalScore: z.number().min(0).max(100),\n })).optional(),\n \n /**\n * Learning path\n */\n learningPath: z.array(z.object({\n step: z.number().int(),\n plugin: z.string(),\n reason: z.string(),\n resources: z.array(z.string()).optional(),\n })).optional(),\n});\n\n// Export types\nexport type CodeGenerationRequest = z.infer;\nexport type GeneratedCode = z.infer;\nexport type PluginScaffoldingTemplate = z.infer;\nexport type AICodeReviewResult = z.infer;\nexport type PluginCompositionRequest = z.infer;\nexport type PluginCompositionResult = z.infer;\nexport type PluginRecommendationRequest = z.infer;\nexport type PluginRecommendation = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginHealthStatusSchema } from '../kernel/plugin-lifecycle-advanced.zod';\n\n/**\n * # Runtime AI Operations (AIOps) Protocol\n * \n * Defines protocols for AI-powered runtime operations including:\n * - Self-healing and automatic recovery\n * - Intelligent auto-scaling\n * - Anomaly detection and prediction\n * - Performance optimization\n * - Root cause analysis\n */\n\n/**\n * Anomaly Detection Configuration\n * Configuration for detecting anomalies in plugin behavior\n */\nexport const AnomalyDetectionConfigSchema = z.object({\n /**\n * Enable anomaly detection\n */\n enabled: z.boolean().default(true),\n \n /**\n * Metrics to monitor\n */\n metrics: z.array(z.enum([\n 'cpu-usage',\n 'memory-usage',\n 'response-time',\n 'error-rate',\n 'throughput',\n 'latency',\n 'connection-count',\n 'queue-depth',\n ])),\n \n /**\n * Detection algorithm\n */\n algorithm: z.enum([\n 'statistical', // Statistical thresholds\n 'machine-learning', // ML-based detection\n 'heuristic', // Rule-based heuristics\n 'hybrid', // Combination of methods\n ]).default('hybrid'),\n \n /**\n * Sensitivity level\n */\n sensitivity: z.enum(['low', 'medium', 'high']).default('medium')\n .describe('How aggressively to detect anomalies'),\n \n /**\n * Time window for analysis (seconds)\n */\n timeWindow: z.number().int().min(60).default(300)\n .describe('Historical data window for anomaly detection'),\n \n /**\n * Confidence threshold (0-100)\n */\n confidenceThreshold: z.number().min(0).max(100).default(80)\n .describe('Minimum confidence to flag as anomaly'),\n \n /**\n * Alert on detection\n */\n alertOnDetection: z.boolean().default(true),\n});\n\n/**\n * Self-Healing Action\n * Defines an automated recovery action\n */\nexport const SelfHealingActionSchema = z.object({\n /**\n * Action identifier\n */\n id: z.string(),\n \n /**\n * Action type\n */\n type: z.enum([\n 'restart', // Restart the plugin\n 'scale', // Scale resources\n 'rollback', // Rollback to previous version\n 'clear-cache', // Clear caches\n 'adjust-config', // Adjust configuration\n 'execute-script', // Run custom script\n 'notify', // Notify administrators\n ]),\n \n /**\n * Trigger condition\n */\n trigger: z.object({\n /**\n * Health status that triggers this action\n */\n healthStatus: z.array(PluginHealthStatusSchema).optional(),\n \n /**\n * Anomaly types that trigger this action\n */\n anomalyTypes: z.array(z.string()).optional(),\n \n /**\n * Error patterns that trigger this action\n */\n errorPatterns: z.array(z.string()).optional(),\n \n /**\n * Custom condition expression\n */\n customCondition: z.string().optional()\n .describe('Custom trigger condition (e.g., \"errorRate > 0.1\")'),\n }),\n \n /**\n * Action parameters\n */\n parameters: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Maximum number of attempts\n */\n maxAttempts: z.number().int().min(1).default(3),\n \n /**\n * Cooldown period between attempts (seconds)\n */\n cooldown: z.number().int().min(0).default(60),\n \n /**\n * Timeout for action execution (seconds)\n */\n timeout: z.number().int().min(1).default(300),\n \n /**\n * Require manual approval\n */\n requireApproval: z.boolean().default(false),\n \n /**\n * Priority\n */\n priority: z.number().int().min(1).default(5)\n .describe('Action priority (lower number = higher priority)'),\n});\n\n/**\n * Self-Healing Configuration\n * Complete configuration for self-healing capabilities\n */\nexport const SelfHealingConfigSchema = z.object({\n /**\n * Enable self-healing\n */\n enabled: z.boolean().default(true),\n \n /**\n * Healing strategy\n */\n strategy: z.enum([\n 'conservative', // Only safe, proven actions\n 'moderate', // Balanced approach\n 'aggressive', // Try more recovery options\n ]).default('moderate'),\n \n /**\n * Recovery actions\n */\n actions: z.array(SelfHealingActionSchema),\n \n /**\n * Anomaly detection\n */\n anomalyDetection: AnomalyDetectionConfigSchema.optional(),\n \n /**\n * Maximum concurrent healing operations\n */\n maxConcurrentHealing: z.number().int().min(1).default(1)\n .describe('Maximum number of simultaneous healing attempts'),\n \n /**\n * Learning mode\n */\n learning: z.object({\n enabled: z.boolean().default(true)\n .describe('Learn from successful/failed healing attempts'),\n \n feedbackLoop: z.boolean().default(true)\n .describe('Adjust strategy based on outcomes'),\n }).optional(),\n});\n\n/**\n * Auto-Scaling Policy\n * Defines how to automatically scale plugin resources\n */\nexport const AutoScalingPolicySchema = z.object({\n /**\n * Enable auto-scaling\n */\n enabled: z.boolean().default(false),\n \n /**\n * Scaling metric\n */\n metric: z.enum([\n 'cpu-usage',\n 'memory-usage',\n 'request-rate',\n 'response-time',\n 'queue-depth',\n 'custom',\n ]),\n \n /**\n * Custom metric query (when metric is \"custom\")\n */\n customMetric: z.string().optional(),\n \n /**\n * Target value for the metric\n */\n targetValue: z.number()\n .describe('Desired metric value (e.g., 70 for 70% CPU)'),\n \n /**\n * Scaling bounds\n */\n bounds: z.object({\n /**\n * Minimum instances\n */\n minInstances: z.number().int().min(1).default(1),\n \n /**\n * Maximum instances\n */\n maxInstances: z.number().int().min(1).default(10),\n \n /**\n * Minimum resources per instance\n */\n minResources: z.object({\n cpu: z.string().optional().describe('CPU limit (e.g., \"0.5\", \"1\")'),\n memory: z.string().optional().describe('Memory limit (e.g., \"512Mi\", \"1Gi\")'),\n }).optional(),\n \n /**\n * Maximum resources per instance\n */\n maxResources: z.object({\n cpu: z.string().optional(),\n memory: z.string().optional(),\n }).optional(),\n }),\n \n /**\n * Scale up behavior\n */\n scaleUp: z.object({\n /**\n * Threshold to trigger scale up\n */\n threshold: z.number()\n .describe('Metric value that triggers scale up'),\n \n /**\n * Stabilization window (seconds)\n */\n stabilizationWindow: z.number().int().min(0).default(60)\n .describe('How long metric must exceed threshold'),\n \n /**\n * Cooldown period (seconds)\n */\n cooldown: z.number().int().min(0).default(300)\n .describe('Minimum time between scale-up operations'),\n \n /**\n * Step size\n */\n stepSize: z.number().int().min(1).default(1)\n .describe('Number of instances to add'),\n }),\n \n /**\n * Scale down behavior\n */\n scaleDown: z.object({\n /**\n * Threshold to trigger scale down\n */\n threshold: z.number()\n .describe('Metric value that triggers scale down'),\n \n /**\n * Stabilization window (seconds)\n */\n stabilizationWindow: z.number().int().min(0).default(300)\n .describe('How long metric must be below threshold'),\n \n /**\n * Cooldown period (seconds)\n */\n cooldown: z.number().int().min(0).default(600)\n .describe('Minimum time between scale-down operations'),\n \n /**\n * Step size\n */\n stepSize: z.number().int().min(1).default(1)\n .describe('Number of instances to remove'),\n }),\n \n /**\n * Predictive scaling\n */\n predictive: z.object({\n enabled: z.boolean().default(false)\n .describe('Use ML to predict future load'),\n \n lookAhead: z.number().int().min(60).default(300)\n .describe('How far ahead to predict (seconds)'),\n \n confidence: z.number().min(0).max(100).default(80)\n .describe('Minimum confidence for prediction-based scaling'),\n }).optional(),\n});\n\n/**\n * Root Cause Analysis Request\n * Request for AI to analyze root cause of issues\n */\nexport const RootCauseAnalysisRequestSchema = z.object({\n /**\n * Incident identifier\n */\n incidentId: z.string(),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Symptoms observed\n */\n symptoms: z.array(z.object({\n type: z.string().describe('Symptom type'),\n description: z.string(),\n severity: z.enum(['low', 'medium', 'high', 'critical']),\n timestamp: z.string().datetime(),\n })),\n \n /**\n * Time range for analysis\n */\n timeRange: z.object({\n start: z.string().datetime(),\n end: z.string().datetime(),\n }),\n \n /**\n * Include log analysis\n */\n analyzeLogs: z.boolean().default(true),\n \n /**\n * Include metric analysis\n */\n analyzeMetrics: z.boolean().default(true),\n \n /**\n * Include dependency analysis\n */\n analyzeDependencies: z.boolean().default(true),\n \n /**\n * Context information\n */\n context: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Root Cause Analysis Result\n * Result of root cause analysis\n */\nexport const RootCauseAnalysisResultSchema = z.object({\n /**\n * Analysis identifier\n */\n analysisId: z.string(),\n \n /**\n * Incident identifier\n */\n incidentId: z.string(),\n \n /**\n * Identified root causes\n */\n rootCauses: z.array(z.object({\n /**\n * Cause identifier\n */\n id: z.string(),\n \n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Confidence score (0-100)\n */\n confidence: z.number().min(0).max(100),\n \n /**\n * Category\n */\n category: z.enum([\n 'code-defect',\n 'configuration',\n 'resource-exhaustion',\n 'dependency-failure',\n 'network-issue',\n 'data-corruption',\n 'security-breach',\n 'other',\n ]),\n \n /**\n * Evidence\n */\n evidence: z.array(z.object({\n type: z.enum(['log', 'metric', 'trace', 'event']),\n content: z.string(),\n timestamp: z.string().datetime().optional(),\n })),\n \n /**\n * Impact assessment\n */\n impact: z.enum(['low', 'medium', 'high', 'critical']),\n \n /**\n * Recommended actions\n */\n recommendations: z.array(z.string()),\n })),\n \n /**\n * Contributing factors\n */\n contributingFactors: z.array(z.object({\n description: z.string(),\n confidence: z.number().min(0).max(100),\n })).optional(),\n \n /**\n * Timeline of events\n */\n timeline: z.array(z.object({\n timestamp: z.string().datetime(),\n event: z.string(),\n significance: z.enum(['low', 'medium', 'high']),\n })).optional(),\n \n /**\n * Remediation plan\n */\n remediation: z.object({\n /**\n * Immediate actions\n */\n immediate: z.array(z.string()),\n \n /**\n * Short-term fixes\n */\n shortTerm: z.array(z.string()),\n \n /**\n * Long-term improvements\n */\n longTerm: z.array(z.string()),\n }).optional(),\n \n /**\n * Overall confidence in analysis\n */\n overallConfidence: z.number().min(0).max(100),\n \n /**\n * Analysis timestamp\n */\n timestamp: z.string().datetime(),\n});\n\n/**\n * Performance Optimization Suggestion\n * AI-generated performance optimization suggestion\n */\nexport const PerformanceOptimizationSchema = z.object({\n /**\n * Optimization identifier\n */\n id: z.string(),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Optimization type\n */\n type: z.enum([\n 'caching',\n 'query-optimization',\n 'resource-allocation',\n 'code-refactoring',\n 'architecture-change',\n 'configuration-tuning',\n ]),\n \n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Expected impact\n */\n expectedImpact: z.object({\n /**\n * Performance improvement percentage\n */\n performanceGain: z.number().min(0).max(100)\n .describe('Expected performance improvement (%)'),\n \n /**\n * Resource savings\n */\n resourceSavings: z.object({\n cpu: z.number().optional().describe('CPU reduction (%)'),\n memory: z.number().optional().describe('Memory reduction (%)'),\n network: z.number().optional().describe('Network reduction (%)'),\n }).optional(),\n \n /**\n * Cost reduction\n */\n costReduction: z.number().optional()\n .describe('Estimated cost reduction (%)'),\n }),\n \n /**\n * Implementation difficulty\n */\n difficulty: z.enum(['trivial', 'easy', 'moderate', 'complex', 'very-complex']),\n \n /**\n * Implementation steps\n */\n steps: z.array(z.string()),\n \n /**\n * Risks and considerations\n */\n risks: z.array(z.string()).optional(),\n \n /**\n * Confidence score\n */\n confidence: z.number().min(0).max(100),\n \n /**\n * Priority\n */\n priority: z.enum(['low', 'medium', 'high', 'critical']),\n});\n\n/**\n * AIOps Agent Configuration\n * Configuration for AI operations agent\n */\nexport const AIOpsAgentConfigSchema = z.object({\n /**\n * Agent identifier\n */\n agentId: z.string(),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Self-healing configuration\n */\n selfHealing: SelfHealingConfigSchema.optional(),\n \n /**\n * Auto-scaling policies\n */\n autoScaling: z.array(AutoScalingPolicySchema).optional(),\n \n /**\n * Continuous monitoring\n */\n monitoring: z.object({\n enabled: z.boolean().default(true),\n interval: z.number().int().min(1000).default(60000)\n .describe('Monitoring interval in milliseconds'),\n \n /**\n * Metrics to collect\n */\n metrics: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Proactive optimization\n */\n optimization: z.object({\n enabled: z.boolean().default(true),\n \n /**\n * Scan interval (seconds)\n */\n scanInterval: z.number().int().min(3600).default(86400)\n .describe('How often to scan for optimization opportunities'),\n \n /**\n * Auto-apply optimizations\n */\n autoApply: z.boolean().default(false)\n .describe('Automatically apply low-risk optimizations'),\n }).optional(),\n \n /**\n * Incident response\n */\n incidentResponse: z.object({\n enabled: z.boolean().default(true),\n \n /**\n * Auto-trigger root cause analysis\n */\n autoRCA: z.boolean().default(true),\n \n /**\n * Notification channels\n */\n notifications: z.array(z.object({\n channel: z.enum(['email', 'slack', 'webhook', 'sms']),\n config: z.record(z.string(), z.unknown()),\n })).optional(),\n }).optional(),\n});\n\n// Export types\nexport type AnomalyDetectionConfig = z.infer;\nexport type SelfHealingAction = z.infer;\nexport type SelfHealingConfig = z.infer;\nexport type AutoScalingPolicy = z.infer;\nexport type RootCauseAnalysisRequest = z.infer;\nexport type RootCauseAnalysisResult = z.infer;\nexport type PerformanceOptimization = z.infer;\nexport type AIOpsAgentConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * AI Model Registry Protocol\n * \n * Centralized registry for managing AI models, prompt templates, and model versioning.\n * Enables AI-powered ObjectStack applications to discover and use LLMs consistently.\n */\n\n/**\n * Model Provider Type\n */\nexport const ModelProviderSchema = z.enum([\n 'openai',\n 'azure_openai',\n 'anthropic',\n 'google',\n 'cohere',\n 'huggingface',\n 'local',\n 'custom',\n]);\n\n/**\n * Model Capability\n */\nexport const ModelCapabilitySchema = z.object({\n textGeneration: z.boolean().optional().default(true).describe('Supports text generation'),\n textEmbedding: z.boolean().optional().default(false).describe('Supports text embedding'),\n imageGeneration: z.boolean().optional().default(false).describe('Supports image generation'),\n imageUnderstanding: z.boolean().optional().default(false).describe('Supports image understanding'),\n functionCalling: z.boolean().optional().default(false).describe('Supports function calling'),\n codeGeneration: z.boolean().optional().default(false).describe('Supports code generation'),\n reasoning: z.boolean().optional().default(false).describe('Supports advanced reasoning'),\n});\n\n/**\n * Model Limits\n */\nexport const ModelLimitsSchema = z.object({\n maxTokens: z.number().int().positive().describe('Maximum tokens per request'),\n contextWindow: z.number().int().positive().describe('Context window size'),\n maxOutputTokens: z.number().int().positive().optional().describe('Maximum output tokens'),\n rateLimit: z.object({\n requestsPerMinute: z.number().int().positive().optional(),\n tokensPerMinute: z.number().int().positive().optional(),\n }).optional(),\n});\n\n/**\n * Model Pricing\n */\nexport const ModelPricingSchema = z.object({\n currency: z.string().optional().default('USD'),\n inputCostPer1kTokens: z.number().optional().describe('Cost per 1K input tokens'),\n outputCostPer1kTokens: z.number().optional().describe('Cost per 1K output tokens'),\n embeddingCostPer1kTokens: z.number().optional().describe('Cost per 1K embedding tokens'),\n});\n\n/**\n * Model Configuration\n */\nexport const ModelConfigSchema = z.object({\n /** Identity */\n id: z.string().describe('Unique model identifier'),\n name: z.string().describe('Model display name'),\n version: z.string().describe('Model version (e.g., \"gpt-4-turbo-2024-04-09\")'),\n provider: ModelProviderSchema,\n \n /** Capabilities */\n capabilities: ModelCapabilitySchema,\n limits: ModelLimitsSchema,\n \n /** Pricing */\n pricing: ModelPricingSchema.optional(),\n \n /** Configuration */\n endpoint: z.string().url().optional().describe('Custom API endpoint'),\n apiKey: z.string().optional().describe('API key (Warning: Prefer secretRef)'),\n secretRef: z.string().optional().describe('Reference to stored secret (e.g. system:openai_api_key)'),\n region: z.string().optional().describe('Deployment region (e.g., \"us-east-1\")'),\n \n /** Metadata */\n description: z.string().optional(),\n tags: z.array(z.string()).optional().describe('Tags for categorization'),\n deprecated: z.boolean().optional().default(false),\n recommendedFor: z.array(z.string()).optional().describe('Use case recommendations'),\n});\n\n/**\n * Prompt Template Variable\n */\nexport const PromptVariableSchema = z.object({\n name: z.string().describe('Variable name (e.g., \"user_name\", \"context\")'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).default('string'),\n required: z.boolean().default(false),\n defaultValue: z.unknown().optional(),\n description: z.string().optional(),\n validation: z.object({\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n pattern: z.string().optional(),\n enum: z.array(z.unknown()).optional(),\n }).optional(),\n});\n\n/**\n * Prompt Template\n */\nexport const PromptTemplateSchema = z.object({\n /** Identity */\n id: z.string().describe('Unique template identifier'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Template name (snake_case)'),\n label: z.string().describe('Display name'),\n \n /** Template Content */\n system: z.string().optional().describe('System prompt'),\n user: z.string().describe('User prompt template with variables'),\n assistant: z.string().optional().describe('Assistant message prefix'),\n \n /** Variables */\n variables: z.array(PromptVariableSchema).optional().describe('Template variables'),\n \n /** Model Configuration */\n modelId: z.string().optional().describe('Recommended model ID'),\n temperature: z.number().min(0).max(2).optional(),\n maxTokens: z.number().optional(),\n topP: z.number().optional(),\n frequencyPenalty: z.number().optional(),\n presencePenalty: z.number().optional(),\n stopSequences: z.array(z.string()).optional(),\n \n /** Metadata */\n version: z.string().optional().default('1.0.0'),\n description: z.string().optional(),\n category: z.string().optional().describe('Template category (e.g., \"code_generation\", \"support\")'),\n tags: z.array(z.string()).optional(),\n examples: z.array(z.object({\n input: z.record(z.string(), z.unknown()).describe('Example variable values'),\n output: z.string().describe('Expected output'),\n })).optional(),\n});\n\n/**\n * Model Registry Entry\n */\nexport const ModelRegistryEntrySchema = z.object({\n model: ModelConfigSchema,\n status: z.enum(['active', 'deprecated', 'experimental', 'disabled']).default('active'),\n priority: z.number().int().default(0).describe('Priority for model selection'),\n fallbackModels: z.array(z.string()).optional().describe('Fallback model IDs'),\n healthCheck: z.object({\n enabled: z.boolean().default(true),\n intervalSeconds: z.number().int().default(300),\n lastChecked: z.string().optional().describe('ISO timestamp'),\n status: z.enum(['healthy', 'unhealthy', 'unknown']).default('unknown'),\n }).optional(),\n});\n\n/**\n * Model Registry\n */\nexport const ModelRegistrySchema = z.object({\n name: z.string().describe('Registry name'),\n models: z.record(z.string(), ModelRegistryEntrySchema).describe('Model entries by ID'),\n promptTemplates: z.record(z.string(), PromptTemplateSchema).optional().describe('Prompt templates by name'),\n defaultModel: z.string().optional().describe('Default model ID'),\n enableAutoFallback: z.boolean().default(true).describe('Auto-fallback on errors'),\n});\n\n/**\n * Model Selection Criteria\n */\nexport const ModelSelectionCriteriaSchema = z.object({\n capabilities: z.array(z.string()).optional().describe('Required capabilities'),\n maxCostPer1kTokens: z.number().optional().describe('Maximum acceptable cost'),\n minContextWindow: z.number().optional().describe('Minimum context window size'),\n provider: ModelProviderSchema.optional(),\n tags: z.array(z.string()).optional(),\n excludeDeprecated: z.boolean().default(true),\n});\n\n// Type exports\nexport type ModelProvider = z.infer;\nexport type ModelCapability = z.infer;\nexport type ModelLimits = z.infer;\nexport type ModelPricing = z.infer;\nexport type ModelConfig = z.infer;\nexport type PromptVariable = z.infer;\nexport type PromptTemplate = z.infer;\nexport type ModelRegistryEntry = z.infer;\nexport type ModelRegistry = z.infer;\nexport type ModelSelectionCriteria = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Model Context Protocol (MCP)\n * \n * Defines the protocol for connecting AI assistants to external tools, data sources,\n * and resources. MCP enables AI models to access contextual information, invoke\n * functions, and interact with external systems in a standardized way.\n * \n * Architecture Alignment:\n * - Anthropic Model Context Protocol (MCP)\n * - OpenAI Function Calling / Tools\n * - LangChain Tool Interface\n * - Microsoft Semantic Kernel Plugins\n * \n * Use Cases:\n * - Connect AI agents to ObjectStack data (Objects, Views, Reports)\n * - Expose business logic as callable tools (Workflows, Flows, Actions)\n * - Provide dynamic context to AI models (User profile, Recent activity)\n * - Enable AI to read and modify data through standardized interfaces\n */\n\n// ==========================================\n// MCP Transport Configuration\n// ==========================================\n\n/**\n * MCP Transport Type\n * Defines how the MCP server communicates\n */\nexport const MCPTransportTypeSchema = z.enum([\n 'stdio', // Standard input/output (for local processes)\n 'http', // HTTP REST API\n 'websocket', // WebSocket bidirectional communication\n 'grpc', // gRPC for high-performance communication\n]);\n\n/**\n * MCP Transport Configuration\n */\nexport const MCPTransportConfigSchema = z.object({\n type: MCPTransportTypeSchema,\n \n /** HTTP/WebSocket Configuration */\n url: z.string().url().optional().describe('Server URL (for HTTP/WebSocket/gRPC)'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for requests'),\n \n /** Authentication */\n auth: z.object({\n type: z.enum(['none', 'bearer', 'api_key', 'oauth2', 'custom']).default('none'),\n token: z.string().optional().describe('Bearer token or API key'),\n secretRef: z.string().optional().describe('Reference to stored secret'),\n headerName: z.string().optional().describe('Custom auth header name'),\n }).optional(),\n \n /** Connection Options */\n timeout: z.number().int().positive().optional().default(30000).describe('Request timeout in milliseconds'),\n retryAttempts: z.number().int().min(0).max(5).optional().default(3),\n retryDelay: z.number().int().positive().optional().default(1000).describe('Delay between retries in milliseconds'),\n \n /** STDIO Configuration */\n command: z.string().optional().describe('Command to execute (for stdio transport)'),\n args: z.array(z.string()).optional().describe('Command arguments'),\n env: z.record(z.string(), z.string()).optional().describe('Environment variables'),\n workingDirectory: z.string().optional().describe('Working directory for the process'),\n});\n\n// ==========================================\n// MCP Resource Protocol\n// ==========================================\n\n/**\n * MCP Resource Type\n * Types of resources that can be exposed through MCP\n */\nexport const MCPResourceTypeSchema = z.enum([\n 'text', // Plain text or markdown content\n 'json', // Structured JSON data\n 'binary', // Binary data (files, images, etc.)\n 'stream', // Streaming data\n]);\n\n/**\n * MCP Resource Schema\n * Represents a piece of contextual information available to the AI\n */\nexport const MCPResourceSchema = z.object({\n /** Identity */\n uri: z.string().describe('Unique resource identifier (e.g., \"objectstack://objects/account/ABC123\")'),\n name: z.string().describe('Human-readable resource name'),\n description: z.string().optional().describe('Resource description for AI consumption'),\n \n /** Resource Type */\n mimeType: z.string().optional().describe('MIME type (e.g., \"application/json\", \"text/plain\")'),\n resourceType: MCPResourceTypeSchema.default('json'),\n \n /** Content */\n content: z.unknown().optional().describe('Resource content (for static resources)'),\n contentUrl: z.string().url().optional().describe('URL to fetch content dynamically'),\n \n /** Metadata */\n size: z.number().int().nonnegative().optional().describe('Resource size in bytes'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp (ISO 8601)'),\n tags: z.array(z.string()).optional().describe('Tags for resource categorization'),\n \n /** Access Control */\n permissions: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n delete: z.boolean().default(false),\n }).optional(),\n \n /** Caching */\n cacheable: z.boolean().default(true).describe('Whether this resource can be cached'),\n cacheMaxAge: z.number().int().nonnegative().optional().describe('Cache max age in seconds'),\n});\n\n/**\n * MCP Resource Template\n * Dynamic resource generation pattern\n */\nexport const MCPResourceTemplateSchema = z.object({\n uriPattern: z.string().describe('URI pattern with variables (e.g., \"objectstack://objects/{objectName}/{recordId}\")'),\n name: z.string().describe('Template name'),\n description: z.string().optional(),\n \n /** Parameters */\n parameters: z.array(z.object({\n name: z.string().describe('Parameter name'),\n type: z.enum(['string', 'number', 'boolean']).default('string'),\n required: z.boolean().default(true),\n description: z.string().optional(),\n pattern: z.string().optional().describe('Regex validation pattern'),\n default: z.unknown().optional(),\n })).describe('URI parameters'),\n \n /** Generation Logic */\n handler: z.string().optional().describe('Handler function name for dynamic generation'),\n \n mimeType: z.string().optional(),\n resourceType: MCPResourceTypeSchema.default('json'),\n});\n\n// ==========================================\n// MCP Tool Protocol\n// ==========================================\n\n/**\n * MCP Tool Parameter Schema\n * Defines parameters for MCP tool functions\n */\nexport const MCPToolParameterSchema: z.ZodType = z.object({\n name: z.string().describe('Parameter name'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']),\n description: z.string().describe('Parameter description for AI consumption'),\n required: z.boolean().default(false),\n default: z.unknown().optional(),\n \n /** Validation */\n enum: z.array(z.unknown()).optional().describe('Allowed values'),\n pattern: z.string().optional().describe('Regex validation pattern (for strings)'),\n minimum: z.number().optional().describe('Minimum value (for numbers)'),\n maximum: z.number().optional().describe('Maximum value (for numbers)'),\n minLength: z.number().int().nonnegative().optional().describe('Minimum length (for strings/arrays)'),\n maxLength: z.number().int().nonnegative().optional().describe('Maximum length (for strings/arrays)'),\n \n /** Nested Schema */\n properties: z.record(z.string(), z.lazy(() => MCPToolParameterSchema)).optional().describe('Properties for object types'),\n items: z.lazy(() => MCPToolParameterSchema).optional().describe('Item schema for array types'),\n});\n\n/**\n * MCP Tool Parameter Type (inferred before schema to avoid circular reference)\n */\nexport type MCPToolParameter = {\n name: string;\n type: 'string' | 'number' | 'boolean' | 'object' | 'array';\n description: string;\n required?: boolean;\n default?: unknown;\n enum?: unknown[];\n pattern?: string;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n properties?: Record;\n items?: MCPToolParameter;\n};\n\n/**\n * MCP Tool Schema\n * Represents a callable function or action available to the AI\n */\nexport const MCPToolSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Tool function name (snake_case)'),\n description: z.string().describe('Tool description for AI consumption (be detailed and specific)'),\n \n /** Parameters */\n parameters: z.array(MCPToolParameterSchema).describe('Tool parameters'),\n \n /** Return Type */\n returns: z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array', 'void']),\n description: z.string().optional(),\n schema: MCPToolParameterSchema.optional().describe('Return value schema'),\n }).optional(),\n \n /** Execution Configuration */\n handler: z.string().describe('Handler function or endpoint reference'),\n async: z.boolean().default(true).describe('Whether the tool executes asynchronously'),\n timeout: z.number().int().positive().optional().describe('Execution timeout in milliseconds'),\n \n /** Side Effects */\n sideEffects: z.enum(['none', 'read', 'write', 'delete']).default('read').describe('Tool side effects'),\n requiresConfirmation: z.boolean().default(false).describe('Require user confirmation before execution'),\n confirmationMessage: z.string().optional(),\n \n /** Examples */\n examples: z.array(z.object({\n description: z.string(),\n parameters: z.record(z.string(), z.unknown()),\n result: z.unknown().optional(),\n })).optional().describe('Usage examples for AI learning'),\n \n /** Metadata */\n category: z.string().optional().describe('Tool category (e.g., \"data\", \"workflow\", \"analytics\")'),\n tags: z.array(z.string()).optional(),\n deprecated: z.boolean().default(false),\n version: z.string().optional().default('1.0.0'),\n});\n\n// ==========================================\n// MCP Prompt Protocol\n// ==========================================\n\n/**\n * MCP Prompt Argument\n * Dynamic arguments for prompt templates\n */\nexport const MCPPromptArgumentSchema = z.object({\n name: z.string().describe('Argument name'),\n description: z.string().optional(),\n type: z.enum(['string', 'number', 'boolean']).default('string'),\n required: z.boolean().default(false),\n default: z.unknown().optional(),\n});\n\n/**\n * MCP Prompt Message\n * Individual message in a prompt template\n */\nexport const MCPPromptMessageSchema = z.object({\n role: z.enum(['system', 'user', 'assistant']).describe('Message role'),\n content: z.string().describe('Message content (can include {{variable}} placeholders)'),\n});\n\n/**\n * MCP Prompt Schema\n * Predefined prompt templates available to the AI\n */\nexport const MCPPromptSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Prompt template name (snake_case)'),\n description: z.string().optional().describe('Prompt description'),\n \n /** Template */\n messages: z.array(MCPPromptMessageSchema).describe('Prompt message sequence'),\n \n /** Arguments */\n arguments: z.array(MCPPromptArgumentSchema).optional().describe('Dynamic arguments for the prompt'),\n \n /** Metadata */\n category: z.string().optional(),\n tags: z.array(z.string()).optional(),\n version: z.string().optional().default('1.0.0'),\n});\n\n// ==========================================\n// MCP Streaming Configuration\n// ==========================================\n\n/**\n * MCP Streaming Configuration\n * Controls streaming behavior for MCP server communication\n */\nexport const MCPStreamingConfigSchema = z.object({\n /** Whether streaming is enabled */\n enabled: z.boolean().describe('Enable streaming for MCP communication'),\n\n /** Size of each streamed chunk in bytes */\n chunkSize: z.number().int().positive().optional().describe('Size of each streamed chunk in bytes'),\n\n /** Heartbeat interval to keep connection alive */\n heartbeatIntervalMs: z.number().int().positive().optional().default(30000).describe('Heartbeat interval in milliseconds'),\n\n /** Backpressure handling strategy */\n backpressure: z.enum(['drop', 'buffer', 'block']).optional().describe('Backpressure handling strategy'),\n}).describe('Streaming configuration for MCP communication');\n\n// ==========================================\n// MCP Tool Approval Configuration\n// ==========================================\n\n/**\n * MCP Tool Approval Configuration\n * Controls approval requirements for tool execution\n */\nexport const MCPToolApprovalSchema = z.object({\n /** Whether tool execution requires approval */\n requireApproval: z.boolean().default(false).describe('Require approval before tool execution'),\n\n /** Strategy for handling approvals */\n approvalStrategy: z.enum(['human_in_loop', 'auto_approve', 'policy_based']).describe('Approval strategy for tool execution'),\n\n /** Regex patterns matching tool names that require approval */\n dangerousToolPatterns: z.array(z.string()).optional().describe('Regex patterns for tools needing approval'),\n\n /** Timeout in seconds for auto-approval */\n autoApproveTimeout: z.number().int().positive().optional().describe('Auto-approve timeout in seconds'),\n}).describe('Tool approval configuration for MCP');\n\n// ==========================================\n// MCP Sampling Configuration\n// ==========================================\n\n/**\n * MCP Sampling Configuration\n * Controls LLM sampling behavior for MCP servers\n */\nexport const MCPSamplingConfigSchema = z.object({\n /** Whether sampling is enabled */\n enabled: z.boolean().describe('Enable LLM sampling'),\n\n /** Maximum tokens to generate */\n maxTokens: z.number().int().positive().describe('Maximum tokens to generate'),\n\n /** Sampling temperature */\n temperature: z.number().min(0).max(2).optional().describe('Sampling temperature'),\n\n /** Stop sequences to end generation */\n stopSequences: z.array(z.string()).optional().describe('Stop sequences to end generation'),\n\n /** Preferred model IDs in priority order */\n modelPreferences: z.array(z.string()).optional().describe('Preferred model IDs in priority order'),\n\n /** System prompt for sampling context */\n systemPrompt: z.string().optional().describe('System prompt for sampling context'),\n}).describe('Sampling configuration for MCP');\n\n// ==========================================\n// MCP Roots Configuration\n// ==========================================\n\n/**\n * MCP Root Entry\n * A single root directory or resource available to the MCP client\n */\nexport const MCPRootEntrySchema = z.object({\n /** Root URI */\n uri: z.string().describe('Root URI (e.g., file:///path/to/project)'),\n\n /** Human-readable name for the root */\n name: z.string().optional().describe('Human-readable root name'),\n\n /** Whether the root is read-only */\n readOnly: z.boolean().optional().describe('Whether the root is read-only'),\n}).describe('A single root directory or resource');\n\n/**\n * MCP Roots Configuration\n * Controls filesystem/resource roots available to the MCP client\n */\nexport const MCPRootsConfigSchema = z.object({\n /** Root directories/resources */\n roots: z.array(MCPRootEntrySchema).describe('Root directories or resources available to the client'),\n\n /** Watch roots for changes */\n watchForChanges: z.boolean().default(false).describe('Watch root directories for filesystem changes'),\n\n /** Notify server on root changes */\n notifyOnChange: z.boolean().default(true).describe('Notify server when root contents change'),\n}).describe('Roots configuration for MCP client');\n\n// ==========================================\n// MCP Server Configuration\n// ==========================================\n\n/**\n * MCP Capability\n * Features supported by the MCP server\n */\nexport const MCPCapabilitySchema = z.object({\n resources: z.boolean().default(false).describe('Supports resource listing and retrieval'),\n resourceTemplates: z.boolean().default(false).describe('Supports dynamic resource templates'),\n tools: z.boolean().default(false).describe('Supports tool/function calling'),\n prompts: z.boolean().default(false).describe('Supports prompt templates'),\n sampling: z.boolean().default(false).describe('Supports sampling from LLMs'),\n logging: z.boolean().default(false).describe('Supports logging and debugging'),\n});\n\n/**\n * MCP Server Info\n * Server metadata and capabilities\n */\nexport const MCPServerInfoSchema = z.object({\n name: z.string().describe('Server name'),\n version: z.string().describe('Server version (semver)'),\n description: z.string().optional(),\n capabilities: MCPCapabilitySchema,\n \n /** Protocol Version */\n protocolVersion: z.string().default('2024-11-05').describe('MCP protocol version'),\n \n /** Metadata */\n vendor: z.string().optional().describe('Server vendor/provider'),\n homepage: z.string().url().optional().describe('Server homepage URL'),\n documentation: z.string().url().optional().describe('Documentation URL'),\n});\n\n/**\n * MCP Server Configuration\n * Complete MCP server definition\n */\nexport const MCPServerConfigSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Server unique identifier (snake_case)'),\n label: z.string().describe('Display name'),\n description: z.string().optional(),\n \n /** Server Info */\n serverInfo: MCPServerInfoSchema,\n \n /** Transport */\n transport: MCPTransportConfigSchema,\n \n /** Resources */\n resources: z.array(MCPResourceSchema).optional().describe('Static resources'),\n resourceTemplates: z.array(MCPResourceTemplateSchema).optional().describe('Dynamic resource templates'),\n \n /** Tools */\n tools: z.array(MCPToolSchema).optional().describe('Available tools'),\n \n /** Prompts */\n prompts: z.array(MCPPromptSchema).optional().describe('Prompt templates'),\n \n /** Lifecycle */\n autoStart: z.boolean().default(false).describe('Auto-start server on system boot'),\n restartOnFailure: z.boolean().default(true).describe('Auto-restart on failure'),\n healthCheck: z.object({\n enabled: z.boolean().default(true),\n interval: z.number().int().positive().default(60000).describe('Health check interval in milliseconds'),\n timeout: z.number().int().positive().default(5000).describe('Health check timeout in milliseconds'),\n endpoint: z.string().optional().describe('Health check endpoint (for HTTP servers)'),\n }).optional(),\n \n /** Access Control */\n permissions: z.object({\n allowedAgents: z.array(z.string()).optional().describe('Agent names allowed to use this server'),\n allowedUsers: z.array(z.string()).optional().describe('User IDs allowed to use this server'),\n requireAuth: z.boolean().default(true),\n }).optional(),\n \n /** Rate Limiting */\n rateLimit: z.object({\n enabled: z.boolean().default(false),\n requestsPerMinute: z.number().int().positive().optional(),\n requestsPerHour: z.number().int().positive().optional(),\n burstSize: z.number().int().positive().optional(),\n }).optional(),\n \n /** Metadata */\n tags: z.array(z.string()).optional(),\n status: z.enum(['active', 'inactive', 'maintenance', 'deprecated']).default('active'),\n version: z.string().optional().default('1.0.0'),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n\n /** Streaming */\n streaming: MCPStreamingConfigSchema.optional().describe('Streaming configuration'),\n\n /** Tool Approval */\n toolApproval: MCPToolApprovalSchema.optional().describe('Tool approval configuration'),\n\n /** Sampling */\n sampling: MCPSamplingConfigSchema.optional().describe('LLM sampling configuration'),\n});\n\n// ==========================================\n// MCP Request/Response Schemas\n// ==========================================\n\n/**\n * MCP Resource Request\n */\nexport const MCPResourceRequestSchema = z.object({\n uri: z.string().describe('Resource URI to fetch'),\n parameters: z.record(z.string(), z.unknown()).optional().describe('URI template parameters'),\n});\n\n/**\n * MCP Resource Response\n */\nexport const MCPResourceResponseSchema = z.object({\n resource: MCPResourceSchema,\n content: z.unknown().describe('Resource content'),\n});\n\n/**\n * MCP Tool Call Request\n */\nexport const MCPToolCallRequestSchema = z.object({\n toolName: z.string().describe('Tool to invoke'),\n parameters: z.record(z.string(), z.unknown()).describe('Tool parameters'),\n \n /** Execution Options */\n timeout: z.number().int().positive().optional(),\n confirmationProvided: z.boolean().optional().describe('User confirmation for tools that require it'),\n \n /** Context */\n context: z.object({\n userId: z.string().optional(),\n sessionId: z.string().optional(),\n agentName: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n});\n\n/**\n * MCP Tool Call Response\n */\nexport const MCPToolCallResponseSchema = z.object({\n toolName: z.string(),\n status: z.enum(['success', 'error', 'timeout', 'cancelled']),\n \n /** Result */\n result: z.unknown().optional().describe('Tool execution result'),\n \n /** Error */\n error: z.object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n }).optional(),\n \n /** Metrics */\n executionTime: z.number().nonnegative().optional().describe('Execution time in milliseconds'),\n timestamp: z.string().datetime().optional(),\n});\n\n/**\n * MCP Prompt Request\n */\nexport const MCPPromptRequestSchema = z.object({\n promptName: z.string().describe('Prompt template to use'),\n arguments: z.record(z.string(), z.unknown()).optional().describe('Prompt arguments'),\n});\n\n/**\n * MCP Prompt Response\n */\nexport const MCPPromptResponseSchema = z.object({\n promptName: z.string(),\n messages: z.array(MCPPromptMessageSchema).describe('Rendered prompt messages'),\n});\n\n// ==========================================\n// MCP Client Configuration\n// ==========================================\n\n/**\n * MCP Client Configuration\n * Configuration for AI clients connecting to MCP servers\n */\nexport const MCPClientConfigSchema = z.object({\n /** Server Connection */\n servers: z.array(MCPServerConfigSchema).describe('MCP servers to connect to'),\n \n /** Client Settings */\n defaultTimeout: z.number().int().positive().default(30000).describe('Default timeout for requests'),\n enableCaching: z.boolean().default(true).describe('Enable client-side caching'),\n cacheMaxAge: z.number().int().nonnegative().default(300).describe('Cache max age in seconds'),\n \n /** Retry Logic */\n retryAttempts: z.number().int().min(0).max(5).default(3),\n retryDelay: z.number().int().positive().default(1000),\n \n /** Logging */\n enableLogging: z.boolean().default(true),\n logLevel: z.enum(['debug', 'info', 'warn', 'error']).default('info'),\n\n /** Roots */\n roots: MCPRootsConfigSchema.optional().describe('Root directories/resources configuration'),\n});\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type MCPTransportType = z.infer;\nexport type MCPTransportConfig = z.infer;\nexport type MCPResourceType = z.infer;\nexport type MCPResource = z.infer;\nexport type MCPResourceTemplate = z.infer;\n// MCPToolParameter type is exported above with the schema\nexport type MCPTool = z.infer;\nexport type MCPPromptArgument = z.infer;\nexport type MCPPromptMessage = z.infer;\nexport type MCPPrompt = z.infer;\nexport type MCPCapability = z.infer;\nexport type MCPServerInfo = z.infer;\nexport type MCPServerConfig = z.infer;\nexport type MCPResourceRequest = z.infer;\nexport type MCPResourceResponse = z.infer;\nexport type MCPToolCallRequest = z.infer;\nexport type MCPToolCallResponse = z.infer;\nexport type MCPPromptRequest = z.infer;\nexport type MCPPromptResponse = z.infer;\nexport type MCPClientConfig = z.infer;\nexport type MCPStreamingConfig = z.infer;\nexport type MCPToolApproval = z.infer;\nexport type MCPSamplingConfig = z.infer;\nexport type MCPRootEntry = z.infer;\nexport type MCPRootsConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * AI Cost Tracking Protocol\n * \n * Monitor and control AI API costs with budgets, alerts, and analytics.\n * Provides cost optimization, budget enforcement, and financial reporting.\n */\n\n/**\n * Token Usage Schema\n * Standardized across all AI operations\n */\nexport const TokenUsageSchema = z.object({\n prompt: z.number().int().nonnegative().describe('Input tokens'),\n completion: z.number().int().nonnegative().describe('Output tokens'),\n total: z.number().int().nonnegative().describe('Total tokens'),\n});\n\nexport type TokenUsage = z.infer;\n\n/**\n * AI Operation Cost Schema\n * Unified cost tracking for all AI operations\n */\nexport const AIOperationCostSchema = z.object({\n operationId: z.string(),\n operationType: z.enum(['conversation', 'orchestration', 'prediction', 'rag', 'nlq']),\n agentName: z.string().optional().describe('Agent that performed the operation'),\n modelId: z.string(),\n tokens: TokenUsageSchema,\n cost: z.number().nonnegative().describe('Cost in USD'),\n timestamp: z.string().datetime(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type AIOperationCost = z.infer;\n\n/**\n * Cost Metric Type\n */\nexport const CostMetricTypeSchema = z.enum([\n 'token', // Cost per token\n 'request', // Cost per API request\n 'character', // Cost per character (e.g., TTS)\n 'second', // Cost per second (e.g., speech)\n 'image', // Cost per image\n 'embedding', // Cost per embedding\n]);\n\n/**\n * Billing Period\n */\nexport const BillingPeriodSchema = z.enum([\n 'hourly',\n 'daily',\n 'weekly',\n 'monthly',\n 'quarterly',\n 'yearly',\n 'custom',\n]);\n\n/**\n * Cost Entry\n * Extended from AIOperationCostSchema with additional tracking fields\n */\nexport const CostEntrySchema = z.object({\n /** Identity */\n id: z.string().describe('Unique cost entry ID'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Request Details */\n modelId: z.string().describe('AI model used'),\n provider: z.string().describe('AI provider (e.g., \"openai\", \"anthropic\")'),\n operation: z.string().describe('Operation type (e.g., \"chat_completion\", \"embedding\")'),\n \n /** Usage Metrics - Standardized */\n tokens: TokenUsageSchema.optional().describe('Standardized token usage'),\n requestCount: z.number().int().positive().default(1),\n \n /** Cost Calculation */\n promptCost: z.number().nonnegative().optional().describe('Cost of prompt tokens'),\n completionCost: z.number().nonnegative().optional().describe('Cost of completion tokens'),\n totalCost: z.number().nonnegative().describe('Total cost in base currency'),\n currency: z.string().default('USD'),\n \n /** Context */\n sessionId: z.string().optional().describe('Conversation session ID'),\n userId: z.string().optional().describe('User who triggered the request'),\n agentId: z.string().optional().describe('AI agent ID'),\n object: z.string().optional().describe('Related object (e.g., \"case\", \"project\")'),\n recordId: z.string().optional().describe('Related record ID'),\n \n /** Metadata */\n tags: z.array(z.string()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Budget Type\n */\nexport const BudgetTypeSchema = z.enum([\n 'global', // Organization-wide budget\n 'user', // Per-user budget\n 'agent', // Per-agent budget\n 'object', // Per-object budget (e.g., per case)\n 'project', // Per-project budget\n 'department', // Per-department budget\n]);\n\n/**\n * Budget Limit\n */\nexport const BudgetLimitSchema = z.object({\n /** Limit Configuration */\n type: BudgetTypeSchema,\n scope: z.string().optional().describe('Scope identifier (userId, agentId, etc.)'),\n \n /** Limit Amount */\n maxCost: z.number().nonnegative().describe('Maximum cost limit'),\n currency: z.string().default('USD'),\n \n /** Period */\n period: BillingPeriodSchema,\n customPeriodDays: z.number().int().positive().optional().describe('Custom period in days'),\n \n /** Soft Limits & Warnings */\n softLimit: z.number().nonnegative().optional().describe('Soft limit for warnings'),\n warnThresholds: z.array(z.number().min(0).max(1)).optional().describe('Warning thresholds (e.g., [0.5, 0.8, 0.95])'),\n \n /** Enforcement */\n enforced: z.boolean().default(true).describe('Block requests when exceeded'),\n gracePeriodSeconds: z.number().int().nonnegative().default(0).describe('Grace period after limit exceeded'),\n \n /** Rollover */\n allowRollover: z.boolean().default(false).describe('Allow unused budget to rollover'),\n maxRolloverPercentage: z.number().min(0).max(1).optional().describe('Max rollover as % of limit'),\n \n /** Metadata */\n name: z.string().optional().describe('Budget name'),\n description: z.string().optional(),\n active: z.boolean().default(true),\n tags: z.array(z.string()).optional(),\n});\n\n/**\n * Budget Status\n */\nexport const BudgetStatusSchema = z.object({\n /** Budget Reference */\n budgetId: z.string(),\n type: BudgetTypeSchema,\n scope: z.string().optional(),\n \n /** Current Period */\n periodStart: z.string().datetime().describe('ISO 8601 timestamp'),\n periodEnd: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Usage */\n currentCost: z.number().nonnegative().default(0),\n maxCost: z.number().nonnegative(),\n currency: z.string().default('USD'),\n \n /** Status */\n percentageUsed: z.number().nonnegative().describe('Usage as percentage (can exceed 1.0 if over budget)'),\n remainingCost: z.number().describe('Remaining budget (can be negative if exceeded)'),\n isExceeded: z.boolean().default(false),\n isWarning: z.boolean().default(false),\n \n /** Projections */\n projectedCost: z.number().nonnegative().optional().describe('Projected cost for period'),\n projectedOverage: z.number().nonnegative().optional().describe('Projected overage'),\n \n /** Last Update */\n lastUpdated: z.string().datetime().describe('ISO 8601 timestamp'),\n});\n\n/**\n * Cost Alert Type\n */\nexport const CostAlertTypeSchema = z.enum([\n 'threshold_warning', // Warning threshold reached\n 'threshold_critical', // Critical threshold reached\n 'limit_exceeded', // Budget limit exceeded\n 'anomaly_detected', // Unusual spending pattern\n 'projection_exceeded', // Projected to exceed budget\n]);\n\n/**\n * Cost Alert\n */\nexport const CostAlertSchema = z.object({\n /** Alert Details */\n id: z.string(),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n type: CostAlertTypeSchema,\n severity: z.enum(['info', 'warning', 'critical']),\n \n /** Budget Context */\n budgetId: z.string().optional(),\n budgetType: BudgetTypeSchema.optional(),\n scope: z.string().optional(),\n \n /** Alert Information */\n message: z.string().describe('Alert message'),\n currentCost: z.number().nonnegative(),\n maxCost: z.number().nonnegative().optional(),\n threshold: z.number().min(0).max(1).optional(),\n currency: z.string().default('USD'),\n \n /** Recommendations */\n recommendations: z.array(z.string()).optional(),\n \n /** Status */\n acknowledged: z.boolean().default(false),\n acknowledgedBy: z.string().optional(),\n acknowledgedAt: z.string().datetime().optional(),\n resolved: z.boolean().default(false),\n \n /** Metadata */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Cost Breakdown Dimension\n */\nexport const CostBreakdownDimensionSchema = z.enum([\n 'model',\n 'provider',\n 'user',\n 'agent',\n 'object',\n 'operation',\n 'date',\n 'hour',\n 'tag',\n]);\n\n/**\n * Cost Breakdown Entry\n */\nexport const CostBreakdownEntrySchema = z.object({\n dimension: CostBreakdownDimensionSchema,\n value: z.string().describe('Dimension value (e.g., model ID, user ID)'),\n \n /** Metrics */\n totalCost: z.number().nonnegative(),\n requestCount: z.number().int().nonnegative(),\n totalTokens: z.number().int().nonnegative().optional(),\n \n /** Share */\n percentageOfTotal: z.number().min(0).max(1),\n \n /** Time Range */\n periodStart: z.string().datetime().optional(),\n periodEnd: z.string().datetime().optional(),\n});\n\n/**\n * Cost Analytics\n */\nexport const CostAnalyticsSchema = z.object({\n /** Time Range */\n periodStart: z.string().datetime().describe('ISO 8601 timestamp'),\n periodEnd: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Summary Metrics */\n totalCost: z.number().nonnegative(),\n totalRequests: z.number().int().nonnegative(),\n totalTokens: z.number().int().nonnegative().optional(),\n currency: z.string().default('USD'),\n \n /** Averages */\n averageCostPerRequest: z.number().nonnegative(),\n averageCostPerToken: z.number().nonnegative().optional(),\n averageRequestsPerDay: z.number().nonnegative(),\n \n /** Trends */\n costTrend: z.enum(['increasing', 'decreasing', 'stable']).optional(),\n trendPercentage: z.number().optional().describe('% change vs previous period'),\n \n /** Breakdowns */\n byModel: z.array(CostBreakdownEntrySchema).optional(),\n byProvider: z.array(CostBreakdownEntrySchema).optional(),\n byUser: z.array(CostBreakdownEntrySchema).optional(),\n byAgent: z.array(CostBreakdownEntrySchema).optional(),\n byOperation: z.array(CostBreakdownEntrySchema).optional(),\n byDate: z.array(CostBreakdownEntrySchema).optional(),\n \n /** Top Consumers */\n topModels: z.array(CostBreakdownEntrySchema).optional(),\n topUsers: z.array(CostBreakdownEntrySchema).optional(),\n topAgents: z.array(CostBreakdownEntrySchema).optional(),\n \n /** Efficiency Metrics */\n tokensPerDollar: z.number().nonnegative().optional(),\n requestsPerDollar: z.number().nonnegative().optional(),\n});\n\n/**\n * Cost Optimization Recommendation\n */\nexport const CostOptimizationRecommendationSchema = z.object({\n /** Recommendation Details */\n id: z.string(),\n type: z.enum([\n 'switch_model',\n 'reduce_tokens',\n 'batch_requests',\n 'cache_results',\n 'adjust_parameters',\n 'limit_usage',\n ]),\n \n /** Impact */\n title: z.string(),\n description: z.string(),\n estimatedSavings: z.number().nonnegative().optional(),\n savingsPercentage: z.number().min(0).max(1).optional(),\n \n /** Implementation */\n priority: z.enum(['low', 'medium', 'high']),\n effort: z.enum(['low', 'medium', 'high']),\n actionable: z.boolean().default(true),\n actionSteps: z.array(z.string()).optional(),\n \n /** Context */\n targetModel: z.string().optional(),\n alternativeModel: z.string().optional(),\n affectedUsers: z.array(z.string()).optional(),\n \n /** Status */\n status: z.enum(['pending', 'accepted', 'rejected', 'implemented']).default('pending'),\n implementedAt: z.string().datetime().optional(),\n});\n\n/**\n * Cost Report\n */\nexport const CostReportSchema = z.object({\n /** Report Metadata */\n id: z.string(),\n name: z.string(),\n generatedAt: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Time Range */\n periodStart: z.string().datetime().describe('ISO 8601 timestamp'),\n periodEnd: z.string().datetime().describe('ISO 8601 timestamp'),\n period: BillingPeriodSchema,\n \n /** Analytics */\n analytics: CostAnalyticsSchema,\n \n /** Budgets */\n budgets: z.array(BudgetStatusSchema).optional(),\n \n /** Alerts */\n alerts: z.array(CostAlertSchema).optional(),\n activeAlertCount: z.number().int().nonnegative().default(0),\n \n /** Recommendations */\n recommendations: z.array(CostOptimizationRecommendationSchema).optional(),\n \n /** Comparisons */\n previousPeriodCost: z.number().nonnegative().optional(),\n costChange: z.number().optional().describe('Change vs previous period'),\n costChangePercentage: z.number().optional(),\n \n /** Forecasting */\n forecastedCost: z.number().nonnegative().optional(),\n forecastedBudgetStatus: z.enum(['under', 'at', 'over']).optional(),\n \n /** Export */\n format: z.enum(['summary', 'detailed', 'executive']).default('summary'),\n currency: z.string().default('USD'),\n});\n\n/**\n * Cost Query Filters\n */\nexport const CostQueryFiltersSchema = z.object({\n /** Time Range */\n startDate: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n endDate: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n \n /** Dimensions */\n modelIds: z.array(z.string()).optional(),\n providers: z.array(z.string()).optional(),\n userIds: z.array(z.string()).optional(),\n agentIds: z.array(z.string()).optional(),\n operations: z.array(z.string()).optional(),\n sessionIds: z.array(z.string()).optional(),\n \n /** Cost Range */\n minCost: z.number().nonnegative().optional(),\n maxCost: z.number().nonnegative().optional(),\n \n /** Tags */\n tags: z.array(z.string()).optional(),\n \n /** Aggregation */\n groupBy: z.array(CostBreakdownDimensionSchema).optional(),\n \n /** Sorting */\n orderBy: z.enum(['timestamp', 'cost', 'tokens']).optional().default('timestamp'),\n orderDirection: z.enum(['asc', 'desc']).optional().default('desc'),\n \n /** Pagination */\n limit: z.number().int().positive().optional(),\n offset: z.number().int().nonnegative().optional(),\n});\n\n// Type exports\nexport type CostMetricType = z.infer;\nexport type BillingPeriod = z.infer;\nexport type CostEntry = z.infer;\nexport type BudgetType = z.infer;\nexport type BudgetLimit = z.infer;\nexport type BudgetStatus = z.infer;\nexport type CostAlertType = z.infer;\nexport type CostAlert = z.infer;\nexport type CostBreakdownDimension = z.infer;\nexport type CostBreakdownEntry = z.infer;\nexport type CostAnalytics = z.infer;\nexport type CostOptimizationRecommendation = z.infer;\nexport type CostReport = z.infer;\nexport type CostQueryFilters = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * RAG (Retrieval-Augmented Generation) Pipeline Protocol\n * \n * Defines schemas for building context-aware AI assistants using RAG techniques.\n * Enables vector search, document chunking, embeddings, and retrieval configuration.\n */\n\n/**\n * Vector Store Provider\n */\nexport const VectorStoreProviderSchema = z.enum([\n 'pinecone',\n 'weaviate',\n 'qdrant',\n 'milvus',\n 'chroma',\n 'pgvector',\n 'redis',\n 'opensearch',\n 'elasticsearch',\n 'custom',\n]);\n\n/**\n * Embedding Model\n */\nexport const EmbeddingModelSchema = z.object({\n provider: z.enum(['openai', 'cohere', 'huggingface', 'azure_openai', 'local', 'custom']),\n model: z.string().describe('Model name (e.g., \"text-embedding-3-large\")'),\n dimensions: z.number().int().positive().describe('Embedding vector dimensions'),\n maxTokens: z.number().int().positive().optional().describe('Maximum tokens per embedding'),\n batchSize: z.number().int().positive().optional().default(100).describe('Batch size for embedding'),\n endpoint: z.string().url().optional().describe('Custom endpoint URL'),\n apiKey: z.string().optional().describe('API key'),\n secretRef: z.string().optional().describe('Reference to stored secret'),\n});\n\n/**\n * Text Chunking Strategy\n */\nexport const ChunkingStrategySchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('fixed'),\n chunkSize: z.number().int().positive().describe('Fixed chunk size in tokens/chars'),\n chunkOverlap: z.number().int().min(0).default(0).describe('Overlap between chunks'),\n unit: z.enum(['tokens', 'characters']).default('tokens'),\n }),\n z.object({\n type: z.literal('semantic'),\n model: z.string().optional().describe('Model for semantic chunking'),\n minChunkSize: z.number().int().positive().default(100),\n maxChunkSize: z.number().int().positive().default(1000),\n }),\n z.object({\n type: z.literal('recursive'),\n separators: z.array(z.string()).default(['\\n\\n', '\\n', ' ', '']),\n chunkSize: z.number().int().positive(),\n chunkOverlap: z.number().int().min(0).default(0),\n }),\n z.object({\n type: z.literal('markdown'),\n maxChunkSize: z.number().int().positive().default(1000),\n respectHeaders: z.boolean().default(true).describe('Keep headers with content'),\n respectCodeBlocks: z.boolean().default(true).describe('Keep code blocks intact'),\n }),\n]);\n\n/**\n * Document Metadata Schema\n */\nexport const DocumentMetadataSchema = z.object({\n source: z.string().describe('Document source (file path, URL, etc.)'),\n sourceType: z.enum(['file', 'url', 'api', 'database', 'custom']).optional(),\n title: z.string().optional(),\n author: z.string().optional().describe('Document author'),\n createdAt: z.string().datetime().optional().describe('ISO timestamp'),\n updatedAt: z.string().datetime().optional().describe('ISO timestamp'),\n tags: z.array(z.string()).optional(),\n category: z.string().optional(),\n language: z.string().optional().describe('Document language (ISO 639-1 code)'),\n custom: z.record(z.string(), z.unknown()).optional().describe('Custom metadata fields'),\n});\n\n/**\n * Document Chunk\n */\nexport const DocumentChunkSchema = z.object({\n id: z.string().describe('Unique chunk identifier'),\n content: z.string().describe('Chunk text content'),\n embedding: z.array(z.number()).optional().describe('Embedding vector'),\n metadata: DocumentMetadataSchema,\n chunkIndex: z.number().int().min(0).describe('Chunk position in document'),\n tokens: z.number().int().optional().describe('Token count'),\n});\n\n/**\n * Retrieval Strategy\n */\nexport const RetrievalStrategySchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('similarity'),\n topK: z.number().int().positive().default(5).describe('Number of results to retrieve'),\n scoreThreshold: z.number().min(0).max(1).optional().describe('Minimum similarity score'),\n }),\n z.object({\n type: z.literal('mmr'),\n topK: z.number().int().positive().default(5),\n fetchK: z.number().int().positive().default(20).describe('Initial fetch size'),\n lambda: z.number().min(0).max(1).default(0.5).describe('Diversity vs relevance (0=diverse, 1=relevant)'),\n }),\n z.object({\n type: z.literal('hybrid'),\n topK: z.number().int().positive().default(5),\n vectorWeight: z.number().min(0).max(1).default(0.7).describe('Weight for vector search'),\n keywordWeight: z.number().min(0).max(1).default(0.3).describe('Weight for keyword search'),\n }),\n z.object({\n type: z.literal('parent_document'),\n topK: z.number().int().positive().default(5),\n retrieveParent: z.boolean().default(true).describe('Retrieve full parent document'),\n }),\n]);\n\n/**\n * Reranking Configuration\n */\nexport const RerankingConfigSchema = z.object({\n enabled: z.boolean().default(false),\n model: z.string().optional().describe('Reranking model name'),\n provider: z.enum(['cohere', 'huggingface', 'custom']).optional(),\n topK: z.number().int().positive().default(3).describe('Final number of results after reranking'),\n});\n\n/**\n * Vector Store Configuration\n */\nexport const VectorStoreConfigSchema = z.object({\n provider: VectorStoreProviderSchema,\n indexName: z.string().describe('Index/collection name'),\n namespace: z.string().optional().describe('Namespace for multi-tenancy'),\n \n /** Connection */\n host: z.string().optional().describe('Vector store host'),\n port: z.number().int().optional().describe('Vector store port'),\n secretRef: z.string().optional().describe('Reference to stored secret'),\n apiKey: z.string().optional().describe('API key or reference to secret'),\n \n /** Configuration */\n dimensions: z.number().int().positive().describe('Vector dimensions'),\n metric: z.enum(['cosine', 'euclidean', 'dotproduct']).optional().default('cosine'),\n \n /** Performance */\n batchSize: z.number().int().positive().optional().default(100),\n connectionPoolSize: z.number().int().positive().optional().default(10),\n timeout: z.number().int().positive().optional().default(30000).describe('Timeout in milliseconds'),\n});\n\n/**\n * Document Loader Configuration\n */\nexport const DocumentLoaderConfigSchema = z.object({\n type: z.enum(['file', 'directory', 'url', 'api', 'database', 'custom']),\n \n /** Source */\n source: z.string().describe('Source path, URL, or identifier'),\n \n /** File Types */\n fileTypes: z.array(z.string()).optional().describe('Accepted file extensions (e.g., [\".pdf\", \".md\"])'),\n \n /** Processing */\n recursive: z.boolean().optional().default(false).describe('Process directories recursively'),\n maxFileSize: z.number().int().optional().describe('Maximum file size in bytes'),\n excludePatterns: z.array(z.string()).optional().describe('Patterns to exclude'),\n \n /** Text Extraction */\n extractImages: z.boolean().optional().default(false).describe('Extract text from images (OCR)'),\n extractTables: z.boolean().optional().default(false).describe('Extract and format tables'),\n \n /** Custom Loader */\n loaderConfig: z.record(z.string(), z.unknown()).optional().describe('Custom loader-specific config'),\n});\n\n/**\n * Filter Expression Schema\n */\nexport const FilterExpressionSchema = z.object({\n field: z.string().describe('Metadata field to filter'),\n operator: z.enum(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'in', 'nin', 'contains']).default('eq'),\n value: z.union([z.string(), z.number(), z.boolean(), z.array(z.union([z.string(), z.number()]))]).describe('Filter value'),\n});\n\nexport type FilterGroup = {\n logic: 'and' | 'or';\n filters: (z.infer | FilterGroup)[];\n};\n\nexport const FilterGroupSchema: z.ZodType = z.object({\n logic: z.enum(['and', 'or']).default('and'),\n filters: z.array(z.union([FilterExpressionSchema, z.lazy(() => FilterGroupSchema)])),\n});\n\n/**\n * Standardized Metadata Filter\n */\nexport const MetadataFilterSchema = z.union([\n FilterExpressionSchema,\n FilterGroupSchema,\n // Legacy support for simple key-value map\n z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.union([z.string(), z.number()]))]))\n]);\n\n/**\n * RAG Pipeline Configuration\n */\nexport const RAGPipelineConfigSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Pipeline name (snake_case)'),\n label: z.string().describe('Display name'),\n description: z.string().optional(),\n \n /** Components */\n embedding: EmbeddingModelSchema,\n vectorStore: VectorStoreConfigSchema,\n chunking: ChunkingStrategySchema,\n retrieval: RetrievalStrategySchema,\n reranking: RerankingConfigSchema.optional(),\n \n /** Document Loading */\n loaders: z.array(DocumentLoaderConfigSchema).optional().describe('Document loaders'),\n \n /** Context Management */\n maxContextTokens: z.number().int().positive().default(4000).describe('Maximum tokens in context'),\n contextWindow: z.number().int().positive().optional().describe('LLM context window size'),\n \n /** Metadata Filtering */\n metadataFilters: MetadataFilterSchema.optional().describe('Global filters for retrieval'),\n \n /** Caching */\n enableCache: z.boolean().default(true),\n cacheTTL: z.number().int().positive().default(3600).describe('Cache TTL in seconds'),\n cacheInvalidationStrategy: z.enum(['time_based', 'manual', 'on_update']).default('time_based').optional(),\n});\n\n/**\n * RAG Query Request\n */\nexport const RAGQueryRequestSchema = z.object({\n query: z.string().describe('User query'),\n pipelineName: z.string().describe('Pipeline to use'),\n \n /** Override defaults */\n topK: z.number().int().positive().optional(),\n metadataFilters: z.record(z.string(), z.unknown()).optional(),\n \n /** Context */\n conversationHistory: z.array(z.object({\n role: z.enum(['user', 'assistant', 'system']),\n content: z.string(),\n })).optional(),\n \n /** Options */\n includeMetadata: z.boolean().default(true),\n includeSources: z.boolean().default(true),\n});\n\n/**\n * RAG Query Response\n */\nexport const RAGQueryResponseSchema = z.object({\n query: z.string(),\n results: z.array(z.object({\n content: z.string(),\n score: z.number(),\n metadata: DocumentMetadataSchema.optional(),\n chunkId: z.string().optional(),\n })),\n context: z.string().describe('Assembled context for LLM'),\n tokens: TokenUsageSchema.optional().describe('Token usage for this query'),\n cost: z.number().nonnegative().optional().describe('Cost for this query in USD'),\n retrievalTime: z.number().optional().describe('Retrieval time in milliseconds'),\n});\n\n/**\n * RAG Pipeline Status\n */\nexport const RAGPipelineStatusSchema = z.object({\n name: z.string(),\n status: z.enum(['active', 'indexing', 'error', 'disabled']),\n documentsIndexed: z.number().int().min(0),\n lastIndexed: z.string().datetime().optional().describe('ISO timestamp'),\n errorMessage: z.string().optional(),\n health: z.object({\n vectorStore: z.enum(['healthy', 'unhealthy', 'unknown']),\n embeddingService: z.enum(['healthy', 'unhealthy', 'unknown']),\n }).optional(),\n});\n\n// Type exports\nexport type VectorStoreProvider = z.infer;\nexport type EmbeddingModel = z.infer;\nexport type ChunkingStrategy = z.infer;\nexport type DocumentMetadata = z.infer;\nexport type DocumentChunk = z.infer;\nexport type RetrievalStrategy = z.infer;\nexport type RerankingConfig = z.infer;\nexport type VectorStoreConfig = z.infer;\nexport type DocumentLoaderConfig = z.infer;\nexport type RAGPipelineConfig = z.infer;\nexport type RAGQueryRequest = z.infer;\nexport type RAGQueryResponse = z.infer;\nexport type RAGPipelineStatus = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * Natural Language Query (NLQ) Protocol\n * \n * Transforms natural language queries into ObjectQL AST (Abstract Syntax Tree).\n * Enables business users to query data using natural language instead of writing code.\n */\n\n/**\n * Query Intent Type\n */\nexport const QueryIntentSchema = z.enum([\n 'select', // Retrieve data (e.g., \"show me all accounts\")\n 'aggregate', // Aggregation (e.g., \"total revenue by region\")\n 'filter', // Filter data (e.g., \"accounts created last month\")\n 'sort', // Sort data (e.g., \"top 10 opportunities by value\")\n 'compare', // Compare values (e.g., \"compare this quarter vs last quarter\")\n 'trend', // Analyze trends (e.g., \"sales trend over time\")\n 'insight', // Generate insights (e.g., \"what's unusual about this data\")\n 'create', // Create record (e.g., \"create a new task\")\n 'update', // Update record (e.g., \"mark this as complete\")\n 'delete', // Delete record (e.g., \"remove this contact\")\n]);\n\n/**\n * Entity Recognition\n */\nexport const EntitySchema = z.object({\n type: z.enum(['object', 'field', 'value', 'operator', 'function', 'timeframe']),\n text: z.string().describe('Original text from query'),\n value: z.unknown().describe('Normalized value'),\n confidence: z.number().min(0).max(1).describe('Confidence score'),\n span: z.tuple([z.number(), z.number()]).optional().describe('Character span in query'),\n});\n\n/**\n * Timeframe Detection\n */\nexport const TimeframeSchema = z.object({\n type: z.enum(['absolute', 'relative']),\n start: z.string().optional().describe('Start date (ISO format)'),\n end: z.string().optional().describe('End date (ISO format)'),\n relative: z.object({\n unit: z.enum(['hour', 'day', 'week', 'month', 'quarter', 'year']),\n value: z.number().int(),\n direction: z.enum(['past', 'future', 'current']).default('past'),\n }).optional(),\n text: z.string().describe('Original timeframe text'),\n});\n\n/**\n * NLQ Field Mapping\n * Maps natural language field names to actual object fields\n */\nexport const NLQFieldMappingSchema = z.object({\n naturalLanguage: z.string().describe('NL field name (e.g., \"customer name\")'),\n objectField: z.string().describe('Actual field name (e.g., \"account.name\")'),\n object: z.string().describe('Object name'),\n field: z.string().describe('Field name'),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Query Context\n */\nexport const QueryContextSchema = z.object({\n /** User Information */\n userId: z.string().optional(),\n userRole: z.string().optional(),\n \n /** Current Context */\n currentObject: z.string().optional().describe('Current object being viewed'),\n currentRecordId: z.string().optional().describe('Current record ID'),\n \n /** Conversation History */\n conversationHistory: z.array(z.object({\n query: z.string(),\n timestamp: z.string(),\n intent: QueryIntentSchema.optional(),\n })).optional(),\n \n /** Preferences */\n defaultLimit: z.number().int().default(100),\n timezone: z.string().default('UTC'),\n locale: z.string().default('en-US'),\n});\n\n/**\n * NLQ Parse Result\n */\nexport const NLQParseResultSchema = z.object({\n /** Original Query */\n originalQuery: z.string(),\n \n /** Intent Detection */\n intent: QueryIntentSchema,\n intentConfidence: z.number().min(0).max(1),\n \n /** Entity Recognition */\n entities: z.array(EntitySchema),\n \n /** Object & Field Resolution */\n targetObject: z.string().optional().describe('Primary object to query'),\n fields: z.array(NLQFieldMappingSchema).optional(),\n \n /** Temporal Information */\n timeframe: TimeframeSchema.optional(),\n \n /** Query AST */\n ast: z.record(z.string(), z.unknown()).describe('Generated ObjectQL AST'),\n \n /** Metadata */\n confidence: z.number().min(0).max(1).describe('Overall confidence'),\n ambiguities: z.array(z.object({\n type: z.string(),\n description: z.string(),\n suggestions: z.array(z.string()).optional(),\n })).optional().describe('Detected ambiguities requiring clarification'),\n \n /** Alternative Interpretations */\n alternatives: z.array(z.object({\n interpretation: z.string(),\n confidence: z.number(),\n ast: z.unknown(),\n })).optional(),\n});\n\n/**\n * NLQ Request\n */\nexport const NLQRequestSchema = z.object({\n /** Query */\n query: z.string().describe('Natural language query'),\n \n /** Context */\n context: QueryContextSchema.optional(),\n \n /** Options */\n includeAlternatives: z.boolean().default(false).describe('Include alternative interpretations'),\n maxAlternatives: z.number().int().default(3),\n minConfidence: z.number().min(0).max(1).default(0.5).describe('Minimum confidence threshold'),\n \n /** Execution */\n executeQuery: z.boolean().default(false).describe('Execute query and return results'),\n maxResults: z.number().int().optional().describe('Maximum results to return'),\n});\n\n/**\n * NLQ Response\n */\nexport const NLQResponseSchema = z.object({\n /** Parse Result */\n parseResult: NLQParseResultSchema,\n \n /** Query Results (if executeQuery = true) */\n results: z.array(z.record(z.string(), z.unknown())).optional().describe('Query results'),\n totalCount: z.number().int().optional(),\n \n /** Execution Metadata */\n executionTime: z.number().optional().describe('Execution time in milliseconds'),\n needsClarification: z.boolean().describe('Whether query needs clarification'),\n \n /** Cost Tracking */\n tokens: TokenUsageSchema.optional().describe('Token usage for this query'),\n cost: z.number().nonnegative().optional().describe('Cost for this query in USD'),\n \n /** Suggestions */\n suggestions: z.array(z.string()).optional().describe('Query refinement suggestions'),\n});\n\n/**\n * NLQ Training Example\n */\nexport const NLQTrainingExampleSchema = z.object({\n /** Input */\n query: z.string().describe('Natural language query'),\n context: QueryContextSchema.optional(),\n \n /** Expected Output */\n expectedIntent: QueryIntentSchema,\n expectedObject: z.string().optional(),\n expectedAST: z.record(z.string(), z.unknown()).describe('Expected ObjectQL AST'),\n \n /** Metadata */\n category: z.string().optional().describe('Example category'),\n tags: z.array(z.string()).optional(),\n notes: z.string().optional(),\n});\n\n/**\n * NLQ Model Configuration\n */\nexport const NLQModelConfigSchema = z.object({\n /** Model */\n modelId: z.string().describe('Model from registry'),\n \n /** Prompt Engineering */\n systemPrompt: z.string().optional().describe('System prompt override'),\n includeSchema: z.boolean().default(true).describe('Include object schema in prompt'),\n includeExamples: z.boolean().default(true).describe('Include examples in prompt'),\n \n /** Intent Detection */\n enableIntentDetection: z.boolean().default(true),\n intentThreshold: z.number().min(0).max(1).default(0.7),\n \n /** Entity Recognition */\n enableEntityRecognition: z.boolean().default(true),\n entityRecognitionModel: z.string().optional(),\n \n /** Field Resolution */\n enableFuzzyMatching: z.boolean().default(true).describe('Fuzzy match field names'),\n fuzzyMatchThreshold: z.number().min(0).max(1).default(0.8),\n \n /** Temporal Processing */\n enableTimeframeDetection: z.boolean().default(true),\n defaultTimeframe: z.string().optional().describe('Default timeframe if not specified'),\n \n /** Performance */\n enableCaching: z.boolean().default(true),\n cacheTTL: z.number().int().default(3600).describe('Cache TTL in seconds'),\n});\n\n/**\n * NLQ Analytics\n */\nexport const NLQAnalyticsSchema = z.object({\n /** Query Metrics */\n totalQueries: z.number().int(),\n successfulQueries: z.number().int(),\n failedQueries: z.number().int(),\n averageConfidence: z.number().min(0).max(1),\n \n /** Intent Distribution */\n intentDistribution: z.record(z.string(), z.number().int()).describe('Count by intent type'),\n \n /** Common Patterns */\n topQueries: z.array(z.object({\n query: z.string(),\n count: z.number().int(),\n averageConfidence: z.number(),\n })),\n \n /** Performance */\n averageParseTime: z.number().describe('Average parse time in milliseconds'),\n averageExecutionTime: z.number().optional(),\n \n /** Issues */\n lowConfidenceQueries: z.array(z.object({\n query: z.string(),\n confidence: z.number(),\n timestamp: z.string().datetime(),\n })),\n \n /** Timeframe */\n startDate: z.string().datetime().describe('ISO timestamp'),\n endDate: z.string().datetime().describe('ISO timestamp'),\n});\n\n/**\n * Field Synonym Configuration\n */\nexport const FieldSynonymConfigSchema = z.object({\n object: z.string().describe('Object name'),\n field: z.string().describe('Field name'),\n synonyms: z.array(z.string()).describe('Natural language synonyms'),\n examples: z.array(z.string()).optional().describe('Example queries using synonyms'),\n});\n\n/**\n * Query Template\n */\nexport const QueryTemplateSchema = z.object({\n id: z.string(),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Template name (snake_case)'),\n label: z.string(),\n \n /** Template */\n pattern: z.string().describe('Query pattern with placeholders'),\n variables: z.array(z.object({\n name: z.string(),\n type: z.enum(['object', 'field', 'value', 'timeframe']),\n required: z.boolean().default(false),\n })),\n \n /** Generated AST */\n astTemplate: z.record(z.string(), z.unknown()).describe('AST template with variable placeholders'),\n \n /** Metadata */\n category: z.string().optional(),\n examples: z.array(z.string()).optional(),\n tags: z.array(z.string()).optional(),\n});\n\n// Type exports\nexport type QueryIntent = z.infer;\nexport type Entity = z.infer;\nexport type Timeframe = z.infer;\nexport type NLQFieldMapping = z.infer;\nexport type QueryContext = z.infer;\nexport type NLQParseResult = z.infer;\nexport type NLQRequest = z.infer;\nexport type NLQResponse = z.infer;\nexport type NLQTrainingExample = z.infer;\nexport type NLQModelConfig = z.infer;\nexport type NLQAnalytics = z.infer;\nexport type FieldSynonymConfig = z.infer;\nexport type QueryTemplate = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * AI Agentic Orchestration Protocol\n * \n * Defines intelligent orchestration flows where AI Agents leverage cognitive skills\n * to automate business processes with dynamic reasoning, planning, and execution.\n * \n * Distinction from Standard Workflows:\n * - Standard Workflow: Deterministic (If X then Y). defined in src/data/workflow.zod.ts\n * - AI Orchestration: Probabilistic & Agentic (Goal -> Plan -> Execute).\n * \n * Use Cases:\n * - Complex Support Triage (Analyze sentiment + intent -> Draft response -> Route)\n * - Intelligent Document Processing (OCR -> Extract Entities -> Validate -> Entry)\n * - Research Agent (Search Web -> Summarize -> Generate Report)\n */\n\n/**\n * Orchestration Trigger Types\n * Defines when an AI Agentic Flow should be initiated\n */\nexport const AIOrchestrationTriggerSchema = z.enum([\n 'record_created', // When a new record is created\n 'record_updated', // When a record is updated\n 'field_changed', // When specific field(s) change\n 'scheduled', // Time-based trigger (cron)\n 'manual', // User-initiated trigger\n 'webhook', // External system trigger\n 'batch', // Batch processing trigger\n]);\n\n/**\n * AI Task Types\n * Cognitive operations that can be performed by AI\n */\nexport const AITaskTypeSchema = z.enum([\n 'classify', // Categorize content into predefined classes\n 'extract', // Extract structured data from unstructured content\n 'summarize', // Generate concise summaries of text\n 'generate', // Generate new content (text, code, etc.)\n 'predict', // Make predictions based on historical data\n 'translate', // Translate text between languages\n 'sentiment', // Analyze sentiment (positive, negative, neutral)\n 'entity_recognition', // Identify named entities (people, places, etc.)\n 'anomaly_detection', // Detect outliers or unusual patterns\n 'recommendation', // Recommend items or actions\n]);\n\n/**\n * AI Task Configuration\n * Individual AI task within a workflow\n */\nexport const AITaskSchema = z.object({\n /** Task Identity */\n id: z.string().optional().describe('Optional task ID for referencing'),\n name: z.string().describe('Human-readable task name'),\n type: AITaskTypeSchema,\n \n /** Model Configuration */\n model: z.string().optional().describe('Model ID from registry (uses default if not specified)'),\n promptTemplate: z.string().optional().describe('Prompt template ID for this task'),\n \n /** Input Configuration */\n inputFields: z.array(z.string()).describe('Source fields to process (e.g., [\"description\", \"comments\"])'),\n inputSchema: z.record(z.string(), z.unknown()).optional().describe('Validation schema for inputs'),\n inputContext: z.record(z.string(), z.unknown()).optional().describe('Additional context for the AI model'),\n \n /** Output Configuration */\n outputField: z.string().describe('Target field to store the result'),\n outputSchema: z.record(z.string(), z.unknown()).optional().describe('Validation schema for output'),\n outputFormat: z.enum(['text', 'json', 'number', 'boolean', 'array']).optional().default('text'),\n \n /** Classification-specific options */\n classes: z.array(z.string()).optional().describe('Valid classes for classification tasks'),\n multiClass: z.boolean().optional().default(false).describe('Allow multiple classes to be selected'),\n \n /** Extraction-specific options */\n extractionSchema: z.record(z.string(), z.unknown()).optional().describe('JSON schema for structured extraction'),\n \n /** Generation-specific options */\n maxLength: z.number().optional().describe('Maximum length for generated content'),\n temperature: z.number().min(0).max(2).optional().describe('Model temperature override'),\n \n /** Error Handling */\n fallbackValue: z.unknown().optional().describe('Fallback value if AI task fails'),\n retryAttempts: z.number().int().min(0).max(5).optional().default(1),\n \n /** Conditional Execution */\n condition: z.string().optional().describe('Formula condition - task only runs if TRUE'),\n \n /** Task Metadata */\n description: z.string().optional(),\n active: z.boolean().optional().default(true),\n});\n\n/**\n * Workflow Field Condition\n * Specifies which field changes trigger the workflow\n */\nexport const WorkflowFieldConditionSchema = z.object({\n field: z.string().describe('Field name to monitor'),\n operator: z.enum(['changed', 'changed_to', 'changed_from', 'is', 'is_not']).optional().default('changed'),\n value: z.unknown().optional().describe('Value to compare against (for changed_to/changed_from/is/is_not)'),\n});\n\n/**\n * Workflow Schedule Configuration\n * For time-based workflow execution\n */\nexport const WorkflowScheduleSchema = z.object({\n type: z.enum(['cron', 'interval', 'daily', 'weekly', 'monthly']).default('cron'),\n cron: z.string().optional().describe('Cron expression (required if type is \"cron\")'),\n interval: z.number().optional().describe('Interval in minutes (required if type is \"interval\")'),\n time: z.string().optional().describe('Time of day for daily schedules (HH:MM format)'),\n dayOfWeek: z.number().int().min(0).max(6).optional().describe('Day of week for weekly (0=Sunday)'),\n dayOfMonth: z.number().int().min(1).max(31).optional().describe('Day of month for monthly'),\n timezone: z.string().optional().default('UTC'),\n});\n\n/**\n * Post-Processing Action\n * Actions to execute after AI tasks complete\n */\nexport const PostProcessingActionSchema = z.object({\n type: z.enum(['field_update', 'send_email', 'create_record', 'update_related', 'trigger_flow', 'webhook']),\n name: z.string().describe('Action name'),\n config: z.record(z.string(), z.unknown()).describe('Action-specific configuration'),\n condition: z.string().optional().describe('Execute only if condition is TRUE'),\n});\n\n/**\n * AI Agentic Orchestration Schema\n * Complete workflow definition with AI-powered tasks\n */\nexport const AIOrchestrationSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Orchestration unique identifier (snake_case)'),\n label: z.string().describe('Display name'),\n description: z.string().optional(),\n \n /** Target Object */\n objectName: z.string().describe('Target object for this orchestration'),\n \n /** Trigger Configuration */\n trigger: AIOrchestrationTriggerSchema,\n \n /** Trigger-specific configuration */\n fieldConditions: z.array(WorkflowFieldConditionSchema).optional().describe('Fields to monitor (for field_changed trigger)'),\n schedule: WorkflowScheduleSchema.optional().describe('Schedule configuration (for scheduled trigger)'),\n webhookConfig: z.object({\n secret: z.string().optional().describe('Webhook verification secret'),\n headers: z.record(z.string(), z.string()).optional().describe('Expected headers'),\n }).optional().describe('Webhook configuration (for webhook trigger)'),\n \n /** Entry Criteria */\n entryCriteria: z.string().optional().describe('Formula condition - workflow only runs if TRUE'),\n \n /** AI Tasks */\n aiTasks: z.array(AITaskSchema).describe('AI tasks to execute in sequence'),\n \n /** Post-Processing */\n postActions: z.array(PostProcessingActionSchema).optional().describe('Actions after AI tasks complete'),\n \n /** Execution Options */\n executionMode: z.enum(['sequential', 'parallel']).optional().default('sequential').describe('How to execute multiple AI tasks'),\n stopOnError: z.boolean().optional().default(false).describe('Stop workflow if any task fails'),\n \n /** Performance & Limits */\n timeout: z.number().optional().describe('Maximum execution time in seconds'),\n priority: z.enum(['low', 'normal', 'high', 'critical']).optional().default('normal'),\n \n /** Monitoring & Logging */\n enableLogging: z.boolean().optional().default(true),\n enableMetrics: z.boolean().optional().default(true),\n notifyOnFailure: z.array(z.string()).optional().describe('User IDs to notify on failure'),\n \n /** Status */\n active: z.boolean().optional().default(true),\n version: z.string().optional().default('1.0.0'),\n \n /** Metadata */\n tags: z.array(z.string()).optional(),\n category: z.string().optional().describe('Workflow category (e.g., \"support\", \"sales\", \"hr\")'),\n owner: z.string().optional().describe('User ID of workflow owner'),\n createdAt: z.string().datetime().optional().describe('ISO timestamp'),\n updatedAt: z.string().datetime().optional().describe('ISO timestamp'),\n});\n\n/**\n * Batch AI Orchestration Execution Request\n * For processing multiple records at once\n */\nexport const BatchAIOrchestrationExecutionSchema = z.object({\n workflowName: z.string().describe('Orchestration to execute'),\n recordIds: z.array(z.string()).describe('Records to process'),\n batchSize: z.number().int().min(1).max(1000).optional().default(10),\n parallelism: z.number().int().min(1).max(10).optional().default(3),\n priority: z.enum(['low', 'normal', 'high']).optional().default('normal'),\n});\n\n/**\n * AI Orchestration Execution Result\n * Result of a single execution\n */\nexport const AIOrchestrationExecutionResultSchema = z.object({\n workflowName: z.string(),\n recordId: z.string(),\n status: z.enum(['success', 'partial_success', 'failed', 'skipped']),\n executionTime: z.number().describe('Execution time in milliseconds'),\n tasksExecuted: z.number().int().describe('Number of tasks executed'),\n tasksSucceeded: z.number().int().describe('Number of tasks succeeded'),\n tasksFailed: z.number().int().describe('Number of tasks failed'),\n taskResults: z.array(z.object({\n taskId: z.string().optional(),\n taskName: z.string(),\n status: z.enum(['success', 'failed', 'skipped']),\n output: z.unknown().optional(),\n error: z.string().optional(),\n executionTime: z.number().optional().describe('Task execution time in milliseconds'),\n modelUsed: z.string().optional(),\n tokensUsed: z.number().optional(),\n })).optional(),\n tokens: TokenUsageSchema.optional().describe('Total token usage for this execution'),\n cost: z.number().nonnegative().optional().describe('Total cost for this execution in USD'),\n error: z.string().optional(),\n startedAt: z.string().datetime().describe('ISO timestamp'),\n completedAt: z.string().datetime().optional().describe('ISO timestamp'),\n});\n\n// Type exports\nexport type AIOrchestrationTrigger = z.infer;\nexport type AITaskType = z.infer;\nexport type AITask = z.infer;\nexport type WorkflowFieldCondition = z.infer;\nexport type WorkflowSchedule = z.infer;\nexport type PostProcessingAction = z.infer;\nexport type AIOrchestration = z.infer;\nexport type BatchAIOrchestrationExecution = z.infer;\nexport type AIOrchestrationExecutionResult = z.infer;\n\n// ==========================================\n// Multi-Agent Coordination\n// ==========================================\n\n/**\n * Multi-Agent Communication Protocol\n * \n * Defines how agents communicate with each other in a group.\n */\nexport const AgentCommunicationProtocolSchema = z.enum([\n 'message_passing', // Direct message exchange between agents\n 'shared_memory', // Agents read/write to a shared context store\n 'blackboard', // Centralized workspace agents contribute to\n]);\n\nexport type AgentCommunicationProtocol = z.infer;\n\n/**\n * Agent Role in a Multi-Agent Group\n * \n * Defines the function an agent plays within a coordinated group.\n */\nexport const AgentGroupRoleSchema = z.enum([\n 'coordinator', // Orchestrates other agents and delegates tasks\n 'specialist', // Domain expert performing specific tasks\n 'critic', // Reviews and validates other agents' outputs\n 'executor', // Carries out actions in the real world (APIs, DB writes)\n]);\n\nexport type AgentGroupRole = z.infer;\n\n/**\n * Agent Group Member Schema\n * \n * Configuration for a single agent within a multi-agent group.\n */\nexport const AgentGroupMemberSchema = z.object({\n /** Reference to agent name (must match an existing AgentSchema name) */\n agentId: z.string().describe('Agent identifier (reference to AgentSchema.name)'),\n\n /** Role this agent plays in the group */\n role: AgentGroupRoleSchema.describe('Agent role within the group'),\n\n /** Capabilities / skills this agent contributes */\n capabilities: z.array(z.string()).optional().describe('List of capabilities this agent contributes'),\n\n /** Dependencies on other agents in the group */\n dependencies: z.array(z.string()).optional().describe('Agent IDs this agent depends on for input'),\n\n /** Priority order within the group (lower = higher priority) */\n priority: z.number().int().min(0).optional().describe('Execution priority (0 = highest)'),\n});\n\nexport type AgentGroupMember = z.infer;\n\n/**\n * Multi-Agent Group Schema\n * \n * Defines a coordinated group of agents that collaborate to solve\n * complex problems exceeding the capability of a single agent.\n * \n * @example Multi-Agent Code Review Group\n * ```typescript\n * const codeReviewGroup: MultiAgentGroup = {\n * name: 'code_review_team',\n * label: 'Code Review Team',\n * strategy: 'sequential',\n * agents: [\n * { agentId: 'code_analyzer', role: 'specialist', capabilities: ['static_analysis'] },\n * { agentId: 'security_scanner', role: 'specialist', capabilities: ['vulnerability_detection'] },\n * { agentId: 'code_reviewer', role: 'critic', capabilities: ['code_quality'] },\n * { agentId: 'merge_agent', role: 'executor', capabilities: ['git_operations'], dependencies: ['code_reviewer'] },\n * ],\n * communication: { protocol: 'blackboard' },\n * conflictResolution: 'voting',\n * };\n * ```\n */\nexport const MultiAgentGroupSchema = z.object({\n /** Group identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Group unique identifier (snake_case)'),\n label: z.string().describe('Group display name'),\n description: z.string().optional(),\n\n /** Orchestration strategy */\n strategy: z.enum([\n 'sequential', // Agents execute one after another\n 'parallel', // Agents execute concurrently\n 'debate', // Agents propose, argue, and converge on a solution\n 'hierarchical', // Coordinator delegates to specialists\n 'swarm', // Agents self-organize dynamically\n ]).describe('Multi-agent orchestration strategy'),\n\n /** Agents in this group */\n agents: z.array(AgentGroupMemberSchema).min(2).describe('Agent members (minimum 2)'),\n\n /** Inter-agent communication */\n communication: z.object({\n /** Communication protocol */\n protocol: AgentCommunicationProtocolSchema.describe('Inter-agent communication protocol'),\n\n /** Message queue name (for message_passing) */\n messageQueue: z.string().optional().describe('Message queue identifier for async communication'),\n\n /** Maximum rounds of communication */\n maxRounds: z.number().int().min(1).optional().describe('Maximum communication rounds before forced termination'),\n }).describe('Communication configuration'),\n\n /** Conflict resolution strategy */\n conflictResolution: z.enum([\n 'voting', // Majority vote decides\n 'priorityBased', // Highest-priority agent decides\n 'consensusBased', // All agents must agree\n 'coordinatorDecides', // Coordinator agent has final say\n ]).optional().describe('How conflicts between agents are resolved'),\n\n /** Timeout for the entire group execution in seconds */\n timeout: z.number().int().min(1).optional().describe('Maximum execution time in seconds for the group'),\n\n /** Whether the group is active */\n active: z.boolean().default(true).describe('Whether this agent group is active'),\n});\n\nexport type MultiAgentGroup = z.infer;\nexport type MultiAgentGroupInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * Predictive Analytics Protocol\n * \n * Defines predictive models and machine learning configurations for\n * data-driven decision making and forecasting in ObjectStack applications.\n * \n * Use Cases:\n * - Lead scoring and conversion prediction\n * - Customer churn prediction\n * - Sales forecasting\n * - Demand forecasting\n * - Anomaly detection in operational data\n * - Customer segmentation and clustering\n * - Price optimization\n * - Recommendation systems\n */\n\n/**\n * Predictive Model Types\n */\nexport const PredictiveModelTypeSchema = z.enum([\n 'classification', // Binary or multi-class classification\n 'regression', // Numerical prediction\n 'clustering', // Unsupervised grouping\n 'forecasting', // Time-series prediction\n 'anomaly_detection', // Outlier detection\n 'recommendation', // Item or action recommendation\n 'ranking', // Ordering items by relevance\n]);\n\n/**\n * Model Feature Definition\n * Describes an input feature for a predictive model\n */\nexport const ModelFeatureSchema = z.object({\n /** Feature Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Feature name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n \n /** Data Source */\n field: z.string().describe('Source field name'),\n object: z.string().optional().describe('Source object (if different from target)'),\n \n /** Feature Type */\n dataType: z.enum(['numeric', 'categorical', 'text', 'datetime', 'boolean']).describe('Feature data type'),\n \n /** Feature Engineering */\n transformation: z.enum([\n 'none',\n 'normalize', // Normalize to 0-1 range\n 'standardize', // Z-score standardization\n 'one_hot_encode', // One-hot encoding for categorical\n 'label_encode', // Label encoding for categorical\n 'log_transform', // Logarithmic transformation\n 'binning', // Discretize continuous values\n 'embedding', // Text/categorical embedding\n ]).optional().default('none'),\n \n /** Configuration */\n required: z.boolean().optional().default(true),\n defaultValue: z.unknown().optional(),\n \n /** Metadata */\n description: z.string().optional(),\n importance: z.number().optional().describe('Feature importance score (0-1)'),\n});\n\n/**\n * Model Hyperparameters\n * Configuration specific to model algorithms\n */\nexport const HyperparametersSchema = z.object({\n /** General Parameters */\n learningRate: z.number().optional().describe('Learning rate for training'),\n epochs: z.number().int().optional().describe('Number of training epochs'),\n batchSize: z.number().int().optional().describe('Training batch size'),\n \n /** Tree-based Models (Random Forest, XGBoost, etc.) */\n maxDepth: z.number().int().optional().describe('Maximum tree depth'),\n numTrees: z.number().int().optional().describe('Number of trees in ensemble'),\n minSamplesSplit: z.number().int().optional().describe('Minimum samples to split node'),\n minSamplesLeaf: z.number().int().optional().describe('Minimum samples in leaf node'),\n \n /** Neural Networks */\n hiddenLayers: z.array(z.number().int()).optional().describe('Hidden layer sizes'),\n activation: z.string().optional().describe('Activation function'),\n dropout: z.number().optional().describe('Dropout rate'),\n \n /** Regularization */\n l1Regularization: z.number().optional().describe('L1 regularization strength'),\n l2Regularization: z.number().optional().describe('L2 regularization strength'),\n \n /** Clustering */\n numClusters: z.number().int().optional().describe('Number of clusters (k-means, etc.)'),\n \n /** Time Series */\n seasonalPeriod: z.number().int().optional().describe('Seasonal period for time series'),\n forecastHorizon: z.number().int().optional().describe('Number of periods to forecast'),\n \n /** Additional custom parameters */\n custom: z.record(z.string(), z.unknown()).optional().describe('Algorithm-specific parameters'),\n});\n\n/**\n * Model Training Configuration\n */\nexport const TrainingConfigSchema = z.object({\n /** Data Split */\n trainingDataRatio: z.number().min(0).max(1).optional().default(0.8).describe('Proportion of data for training'),\n validationDataRatio: z.number().min(0).max(1).optional().default(0.1).describe('Proportion for validation'),\n testDataRatio: z.number().min(0).max(1).optional().default(0.1).describe('Proportion for testing'),\n \n /** Data Filtering */\n dataFilter: z.string().optional().describe('Formula to filter training data'),\n minRecords: z.number().int().optional().default(100).describe('Minimum records required'),\n maxRecords: z.number().int().optional().describe('Maximum records to use'),\n \n /** Training Strategy */\n strategy: z.enum(['full', 'incremental', 'online', 'transfer_learning']).optional().default('full'),\n crossValidation: z.boolean().optional().default(true),\n folds: z.number().int().min(2).max(10).optional().default(5).describe('Cross-validation folds'),\n \n /** Early Stopping */\n earlyStoppingEnabled: z.boolean().optional().default(true),\n earlyStoppingPatience: z.number().int().optional().default(10).describe('Epochs without improvement before stopping'),\n \n /** Resource Limits */\n maxTrainingTime: z.number().optional().describe('Maximum training time in seconds'),\n gpuEnabled: z.boolean().optional().default(false),\n \n /** Reproducibility */\n randomSeed: z.number().int().optional().describe('Random seed for reproducibility'),\n}).superRefine((data, ctx) => {\n if (data.trainingDataRatio && data.validationDataRatio && data.testDataRatio) {\n const sum = data.trainingDataRatio + data.validationDataRatio + data.testDataRatio;\n if (Math.abs(sum - 1) > 0.01) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Data split ratios must sum to 1. Current sum: ${sum}`,\n path: ['trainingDataRatio'],\n });\n }\n }\n});\n\n/**\n * Model Evaluation Metrics\n */\nexport const EvaluationMetricsSchema = z.object({\n /** Classification Metrics */\n accuracy: z.number().optional(),\n precision: z.number().optional(),\n recall: z.number().optional(),\n f1Score: z.number().optional(),\n auc: z.number().optional().describe('Area Under ROC Curve'),\n \n /** Regression Metrics */\n mse: z.number().optional().describe('Mean Squared Error'),\n rmse: z.number().optional().describe('Root Mean Squared Error'),\n mae: z.number().optional().describe('Mean Absolute Error'),\n r2Score: z.number().optional().describe('R-squared score'),\n \n /** Clustering Metrics */\n silhouetteScore: z.number().optional(),\n daviesBouldinIndex: z.number().optional(),\n \n /** Time Series Metrics */\n mape: z.number().optional().describe('Mean Absolute Percentage Error'),\n smape: z.number().optional().describe('Symmetric MAPE'),\n \n /** Additional Metrics */\n custom: z.record(z.string(), z.number()).optional(),\n});\n\n/**\n * Predictive Model Schema\n * Complete definition of a predictive model\n */\nexport const PredictiveModelSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Model unique identifier (snake_case)'),\n label: z.string().describe('Model display name'),\n description: z.string().optional(),\n \n /** Model Type */\n type: PredictiveModelTypeSchema,\n algorithm: z.string().optional().describe('Specific algorithm (e.g., \"random_forest\", \"xgboost\", \"lstm\")'),\n \n /** Target Object & Field */\n objectName: z.string().describe('Target object for predictions'),\n target: z.string().describe('Target field to predict'),\n targetType: z.enum(['numeric', 'categorical', 'binary']).optional().describe('Target field type'),\n \n /** Features */\n features: z.array(ModelFeatureSchema).describe('Input features for the model'),\n \n /** Hyperparameters */\n hyperparameters: HyperparametersSchema.optional(),\n \n /** Training Configuration */\n training: TrainingConfigSchema.optional(),\n \n /** Model Performance */\n metrics: EvaluationMetricsSchema.optional().describe('Evaluation metrics from last training'),\n \n /** Deployment */\n deploymentStatus: z.enum(['draft', 'training', 'trained', 'deployed', 'deprecated']).optional().default('draft'),\n version: z.string().optional().default('1.0.0'),\n \n /** Prediction Configuration */\n predictionField: z.string().optional().describe('Field to store predictions'),\n confidenceField: z.string().optional().describe('Field to store confidence scores'),\n updateTrigger: z.enum(['on_create', 'on_update', 'manual', 'scheduled']).optional().default('on_create'),\n \n /** Retraining */\n autoRetrain: z.boolean().optional().default(false),\n retrainSchedule: z.string().optional().describe('Cron expression for auto-retraining'),\n retrainThreshold: z.number().optional().describe('Performance threshold to trigger retraining'),\n \n /** Explainability */\n enableExplainability: z.boolean().optional().default(false).describe('Generate feature importance & explanations'),\n \n /** Monitoring */\n enableMonitoring: z.boolean().optional().default(true),\n alertOnDrift: z.boolean().optional().default(true).describe('Alert when model drift is detected'),\n \n /** Access Control */\n active: z.boolean().optional().default(true),\n owner: z.string().optional().describe('User ID of model owner'),\n permissions: z.array(z.string()).optional().describe('User/group IDs with access'),\n \n /** Metadata */\n tags: z.array(z.string()).optional(),\n category: z.string().optional().describe('Model category (e.g., \"sales\", \"marketing\", \"operations\")'),\n lastTrainedAt: z.string().datetime().optional().describe('ISO timestamp'),\n createdAt: z.string().datetime().optional().describe('ISO timestamp'),\n updatedAt: z.string().datetime().optional().describe('ISO timestamp'),\n});\n\n/**\n * Prediction Request\n * Request for making predictions using a trained model\n */\nexport const PredictionRequestSchema = z.object({\n modelName: z.string().describe('Model to use for prediction'),\n recordIds: z.array(z.string()).optional().describe('Specific records to predict (if not provided, uses all)'),\n inputData: z.record(z.string(), z.unknown()).optional().describe('Direct input data (alternative to recordIds)'),\n returnConfidence: z.boolean().optional().default(true),\n returnExplanation: z.boolean().optional().default(false),\n});\n\n/**\n * Prediction Result\n * Result of a prediction request\n */\nexport const PredictionResultSchema = z.object({\n modelName: z.string(),\n modelVersion: z.string(),\n recordId: z.string().optional(),\n prediction: z.unknown().describe('The predicted value'),\n confidence: z.number().optional().describe('Confidence score (0-1)'),\n probabilities: z.record(z.string(), z.number()).optional().describe('Class probabilities (for classification)'),\n explanation: z.object({\n topFeatures: z.array(z.object({\n feature: z.string(),\n importance: z.number(),\n value: z.unknown(),\n })).optional(),\n reasoning: z.string().optional(),\n }).optional(),\n tokens: TokenUsageSchema.optional().describe('Token usage for this prediction (if AI-powered)'),\n cost: z.number().nonnegative().optional().describe('Cost for this prediction in USD'),\n metadata: z.object({\n executionTime: z.number().optional().describe('Execution time in milliseconds'),\n timestamp: z.string().datetime().optional().describe('ISO timestamp'),\n }).optional(),\n});\n\n/**\n * Model Drift Detection\n * Monitoring for model performance degradation\n */\nexport const ModelDriftSchema = z.object({\n modelName: z.string(),\n driftType: z.enum(['feature_drift', 'prediction_drift', 'performance_drift']),\n severity: z.enum(['low', 'medium', 'high', 'critical']),\n detectedAt: z.string().datetime().describe('ISO timestamp'),\n metrics: z.object({\n driftScore: z.number().describe('Drift magnitude (0-1)'),\n affectedFeatures: z.array(z.string()).optional(),\n performanceChange: z.number().optional().describe('Change in performance metric'),\n }),\n recommendation: z.string().optional(),\n autoRetrainTriggered: z.boolean().optional().default(false),\n});\n\n// Type exports\nexport type PredictiveModelType = z.infer;\nexport type ModelFeature = z.infer;\nexport type Hyperparameters = z.infer;\nexport type TrainingConfig = z.infer;\nexport type EvaluationMetrics = z.infer;\nexport type PredictiveModel = z.infer;\nexport type PredictionRequest = z.infer;\nexport type PredictionResult = z.infer;\nexport type ModelDrift = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * AI Conversation Memory Protocol\n * \n * Multi-turn AI conversations with token budget management.\n * Enables context preservation, conversation history, and token optimization.\n */\n\n/**\n * Message Role\n */\nexport const MessageRoleSchema = z.enum([\n 'system',\n 'user',\n 'assistant',\n 'function',\n 'tool',\n]);\n\n/**\n * Message Content Type\n */\nexport const MessageContentTypeSchema = z.enum([\n 'text',\n 'image',\n 'file',\n 'code',\n 'structured',\n]);\n\n/**\n * Message Content - Discriminated Union\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n text: z.string().describe('Text content'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n imageUrl: z.string().url().describe('Image URL'),\n detail: z.enum(['low', 'high', 'auto']).optional().default('auto'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const FileContentSchema = z.object({\n type: z.literal('file'),\n fileUrl: z.string().url().describe('File attachment URL'),\n mimeType: z.string().describe('MIME type'),\n fileName: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const CodeContentSchema = z.object({\n type: z.literal('code'),\n text: z.string().describe('Code snippet'),\n language: z.string().optional().default('text'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const MessageContentSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n FileContentSchema,\n CodeContentSchema\n]);\n\n/**\n * Function Call\n */\nexport const FunctionCallSchema = z.object({\n name: z.string().describe('Function name'),\n arguments: z.string().describe('JSON string of function arguments'),\n result: z.string().optional().describe('Function execution result'),\n});\n\n/**\n * Tool Call\n */\nexport const ToolCallSchema = z.object({\n id: z.string().describe('Tool call ID'),\n type: z.enum(['function']).default('function'),\n function: FunctionCallSchema,\n});\n\n/**\n * Conversation Message\n */\nexport const ConversationMessageSchema = z.object({\n /** Identity */\n id: z.string().describe('Unique message ID'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Content */\n role: MessageRoleSchema,\n content: z.array(MessageContentSchema).describe('Message content (multimodal array)'),\n \n /** Function/Tool Calls */\n functionCall: FunctionCallSchema.optional().describe('Legacy function call'),\n toolCalls: z.array(ToolCallSchema).optional().describe('Tool calls'),\n toolCallId: z.string().optional().describe('Tool call ID this message responds to'),\n \n /** Metadata */\n name: z.string().optional().describe('Name of the function/user'),\n tokens: TokenUsageSchema.optional().describe('Token usage for this message'),\n cost: z.number().nonnegative().optional().describe('Cost for this message in USD'),\n \n /** Context Management */\n pinned: z.boolean().optional().default(false).describe('Prevent removal during pruning'),\n importance: z.number().min(0).max(1).optional().describe('Importance score for pruning'),\n embedding: z.array(z.number()).optional().describe('Vector embedding for semantic search'),\n \n /** Annotations */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Token Budget Strategy\n */\nexport const TokenBudgetStrategySchema = z.enum([\n 'fifo', // First-in-first-out (oldest messages dropped)\n 'importance', // Drop by importance score\n 'semantic', // Keep semantically relevant messages\n 'sliding_window', // Fixed window of recent messages\n 'summary', // Summarize old context\n]);\n\n/**\n * Token Budget Configuration\n */\nexport const TokenBudgetConfigSchema = z.object({\n /** Budget Limits */\n maxTokens: z.number().int().positive().describe('Maximum total tokens'),\n maxPromptTokens: z.number().int().positive().optional().describe('Max tokens for prompt'),\n maxCompletionTokens: z.number().int().positive().optional().describe('Max tokens for completion'),\n \n /** Buffer & Reserves */\n reserveTokens: z.number().int().nonnegative().default(500).describe('Reserve tokens for system messages'),\n bufferPercentage: z.number().min(0).max(1).default(0.1).describe('Buffer percentage (0.1 = 10%)'),\n \n /** Pruning Strategy */\n strategy: TokenBudgetStrategySchema.default('sliding_window'),\n \n /** Strategy-Specific Options */\n slidingWindowSize: z.number().int().positive().optional().describe('Number of recent messages to keep'),\n minImportanceScore: z.number().min(0).max(1).optional().describe('Minimum importance to keep'),\n semanticThreshold: z.number().min(0).max(1).optional().describe('Semantic similarity threshold'),\n \n /** Summarization */\n enableSummarization: z.boolean().default(false).describe('Enable context summarization'),\n summarizationThreshold: z.number().int().positive().optional().describe('Trigger summarization at N tokens'),\n summaryModel: z.string().optional().describe('Model ID for summarization'),\n \n /** Monitoring */\n warnThreshold: z.number().min(0).max(1).default(0.8).describe('Warn at % of budget (0.8 = 80%)'),\n});\n\n/**\n * Token Usage Stats\n */\nexport const TokenUsageStatsSchema = z.object({\n promptTokens: z.number().int().nonnegative().default(0),\n completionTokens: z.number().int().nonnegative().default(0),\n totalTokens: z.number().int().nonnegative().default(0),\n \n /** Budget Status */\n budgetLimit: z.number().int().positive(),\n budgetUsed: z.number().int().nonnegative().default(0),\n budgetRemaining: z.number().int().nonnegative(),\n budgetPercentage: z.number().min(0).max(1).describe('Usage as percentage of budget'),\n \n /** Message Stats */\n messageCount: z.number().int().nonnegative().default(0),\n prunedMessageCount: z.number().int().nonnegative().default(0),\n summarizedMessageCount: z.number().int().nonnegative().default(0),\n});\n\n/**\n * Conversation Context\n */\nexport const ConversationContextSchema = z.object({\n /** Identity */\n sessionId: z.string().describe('Conversation session ID'),\n userId: z.string().optional().describe('User identifier'),\n agentId: z.string().optional().describe('AI agent identifier'),\n \n /** Context Data */\n object: z.string().optional().describe('Related object (e.g., \"case\", \"project\")'),\n recordId: z.string().optional().describe('Related record ID'),\n scope: z.record(z.string(), z.unknown()).optional().describe('Additional context scope'),\n \n /** System Instructions */\n systemMessage: z.string().optional().describe('System prompt/instructions'),\n \n /** Metadata */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Conversation Session\n */\nexport const ConversationSessionSchema = z.object({\n /** Identity */\n id: z.string().describe('Unique session ID'),\n name: z.string().optional().describe('Session name/title'),\n \n /** Configuration */\n context: ConversationContextSchema,\n modelId: z.string().optional().describe('AI model ID'),\n tokenBudget: TokenBudgetConfigSchema,\n \n /** Messages */\n messages: z.array(ConversationMessageSchema).default([]),\n \n /** Token Tracking */\n tokens: TokenUsageStatsSchema.optional(),\n totalTokens: TokenUsageSchema.optional().describe('Total tokens across all messages'),\n totalCost: z.number().nonnegative().optional().describe('Total cost for this session in USD'),\n \n /** Session Status */\n status: z.enum(['active', 'paused', 'completed', 'archived']).default('active'),\n \n /** Timestamps */\n createdAt: z.string().datetime().describe('ISO 8601 timestamp'),\n updatedAt: z.string().datetime().describe('ISO 8601 timestamp'),\n expiresAt: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Conversation Summary\n */\nexport const ConversationSummarySchema = z.object({\n /** Summary Content */\n summary: z.string().describe('Conversation summary'),\n keyPoints: z.array(z.string()).optional().describe('Key discussion points'),\n \n /** Token Savings */\n originalTokens: z.number().int().nonnegative().describe('Original token count'),\n summaryTokens: z.number().int().nonnegative().describe('Summary token count'),\n tokensSaved: z.number().int().nonnegative().describe('Tokens saved'),\n \n /** Source Messages */\n messageRange: z.object({\n startIndex: z.number().int().nonnegative(),\n endIndex: z.number().int().nonnegative(),\n }).describe('Range of messages summarized'),\n \n /** Metadata */\n generatedAt: z.string().datetime().describe('ISO 8601 timestamp'),\n modelId: z.string().optional().describe('Model used for summarization'),\n});\n\n/**\n * Message Pruning Event\n */\nexport const MessagePruningEventSchema = z.object({\n /** Event Details */\n timestamp: z.string().datetime().describe('Event timestamp'),\n /** Pruned Messages */\n prunedMessages: z.array(z.object({\n messageId: z.string(),\n role: MessageRoleSchema,\n tokens: z.number().int().nonnegative(),\n importance: z.number().min(0).max(1).optional(),\n })),\n \n /** Impact */\n tokensFreed: z.number().int().nonnegative(),\n messagesRemoved: z.number().int().nonnegative(),\n \n /** Post-Pruning State */\n remainingTokens: z.number().int().nonnegative(),\n remainingMessages: z.number().int().nonnegative(),\n});\n\n/**\n * Conversation Analytics\n */\nexport const ConversationAnalyticsSchema = z.object({\n /** Session Info */\n sessionId: z.string(),\n \n /** Message Statistics */\n totalMessages: z.number().int().nonnegative(),\n userMessages: z.number().int().nonnegative(),\n assistantMessages: z.number().int().nonnegative(),\n systemMessages: z.number().int().nonnegative(),\n \n /** Token Statistics */\n totalTokens: z.number().int().nonnegative(),\n averageTokensPerMessage: z.number().nonnegative(),\n peakTokenUsage: z.number().int().nonnegative(),\n \n /** Efficiency Metrics */\n pruningEvents: z.number().int().nonnegative().default(0),\n summarizationEvents: z.number().int().nonnegative().default(0),\n tokensSavedByPruning: z.number().int().nonnegative().default(0),\n tokensSavedBySummarization: z.number().int().nonnegative().default(0),\n \n /** Duration */\n duration: z.number().nonnegative().optional().describe('Session duration in seconds'),\n firstMessageAt: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n lastMessageAt: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n});\n\nexport type MessageRole = z.infer;\nexport type MessageContentType = z.infer;\nexport type MessageContent = z.infer;\nexport type FunctionCall = z.infer;\nexport type ToolCall = z.infer;\nexport type ConversationMessage = z.infer;\nexport type TokenBudgetStrategy = z.infer;\nexport type TokenBudgetConfig = z.infer;\nexport type TokenUsageStats = z.infer;\nexport type ConversationContext = z.infer;\nexport type ConversationSession = z.infer;\nexport type ConversationSummary = z.infer;\nexport type MessagePruningEvent = z.infer;\nexport type ConversationAnalytics = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ChangeSetSchema } from '../system/migration.zod';\n\n// Identifying the source of truth\nexport const MetadataSourceSchema = z.object({\n file: z.string().optional(),\n line: z.number().optional(),\n column: z.number().optional(),\n // Logic references\n package: z.string().optional(),\n object: z.string().optional(),\n field: z.string().optional(),\n component: z.string().optional() // specific UI component or flow node\n});\n\n// The Runtime Issue\nexport const IssueSchema = z.object({\n id: z.string(),\n severity: z.enum(['critical', 'error', 'warning', 'info']),\n message: z.string(),\n stackTrace: z.string().optional(),\n timestamp: z.string().datetime(),\n userId: z.string().optional(),\n \n // Context snapshot\n context: z.record(z.string(), z.unknown()).optional(),\n \n // The suspected metadata culprit\n source: MetadataSourceSchema.optional()\n});\n\n// The AI's proposed resolution\nexport const ResolutionSchema = z.object({\n issueId: z.string(),\n reasoning: z.string().describe('Explanation of why this fix is needed'),\n confidence: z.number().min(0).max(1),\n \n // Actionable change to fix the issue\n fix: z.discriminatedUnion('type', [\n z.object({\n type: z.literal('metadata_change'),\n changeSet: ChangeSetSchema\n }),\n z.object({\n type: z.literal('manual_intervention'),\n instructions: z.string()\n })\n ])\n});\n\n// Complete Feedback Loop Record\nexport const FeedbackLoopSchema = z.object({\n issue: IssueSchema,\n analysis: z.string().optional().describe('AI analysis of the root cause'),\n resolutions: z.array(ResolutionSchema).optional(),\n status: z.enum(['open', 'analyzing', 'resolved', 'ignored']).default('open')\n});\n\nexport type FeedbackLoop = z.infer;\nexport type Issue = z.infer;\nexport type Resolution = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * API Protocol Exports\n * \n * API Contracts & Envelopes\n * - Request/Response schemas\n * - Error handling\n * - OData v4 compatibility\n * - Batch operations\n * - Metadata caching\n * - HttpDispatcher routing\n * - API versioning\n */\n\nexport * from './contract.zod';\nexport * from './endpoint.zod';\nexport * from './discovery.zod';\nexport * from './events.zod';\nexport * from './realtime-shared.zod';\nexport * from './realtime.zod';\nexport * from './websocket.zod';\nexport * from './router.zod';\nexport * from './odata.zod';\nexport * from './graphql.zod';\nexport * from './batch.zod';\nexport * from './http-cache.zod';\nexport * from './errors.zod';\nexport * from './protocol.zod';\nexport * from './rest-server.zod';\nexport * from './registry.zod';\nexport * from './documentation.zod';\nexport * from './analytics.zod';\nexport * from './versioning.zod';\n\n// Legacy interface export (deprecated)\n// export type { IObjectStackProtocol } from './protocol';\n\nexport * from './auth.zod';\nexport * from './auth-endpoints.zod';\nexport * from './storage.zod';\nexport * from './metadata.zod';\nexport * from './dispatcher.zod';\nexport * from './plugin-rest-api.zod';\nexport * from './query-adapter.zod';\nexport * from './feed-api.zod';\nexport * from './export.zod';\nexport * from './automation-api.zod';\nexport * from './package-api.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { QuerySchema } from '../data/query.zod';\n\n// ==========================================\n// 1. Base Envelopes\n// ==========================================\n\nexport const ApiErrorSchema = z.object({\n code: z.string().describe('Error code (e.g. validation_error)'),\n message: z.string().describe('Readable error message'),\n category: z.string().optional().describe('Error category (e.g. validation, authorization)'),\n details: z.unknown().optional().describe('Additional error context (e.g. field validation errors)'),\n requestId: z.string().optional().describe('Request ID for tracking'),\n});\n\nexport const BaseResponseSchema = z.object({\n success: z.boolean().describe('Operation success status'),\n error: ApiErrorSchema.optional().describe('Error details if success is false'),\n meta: z.object({\n timestamp: z.string(),\n duration: z.number().optional(),\n requestId: z.string().optional(),\n traceId: z.string().optional(),\n }).optional().describe('Response metadata'),\n});\n\n// ==========================================\n// 2. Request Payloads (Inputs)\n// ==========================================\n\nexport const RecordDataSchema = z.record(z.string(), z.unknown()).describe('Key-value map of record data');\n\n/**\n * Standard Create Request\n */\nexport const CreateRequestSchema = z.object({\n data: RecordDataSchema.describe('Record data to insert'),\n});\n\n/**\n * Standard Update Request\n */\nexport const UpdateRequestSchema = z.object({\n data: RecordDataSchema.describe('Partial record data to update'),\n});\n\n/**\n * Standard Bulk Request\n */\nexport const BulkRequestSchema = z.object({\n records: z.array(RecordDataSchema).describe('Array of records to process'),\n allOrNone: z.boolean().default(true).describe('If true, rollback entire transaction on any failure'),\n});\n\n/**\n * Export Request\n */\nexport const ExportRequestSchema = z.intersection(\n QuerySchema,\n z.object({\n format: z.enum(['csv', 'json', 'xlsx']).default('csv'),\n })\n);\n\n// ==========================================\n// 3. Response Payloads (Outputs)\n// ==========================================\n\n/**\n * Single Record Response (Get/Create/Update)\n */\nexport const SingleRecordResponseSchema = BaseResponseSchema.extend({\n data: RecordDataSchema.describe('The requested or modified record'),\n});\n\n/**\n * List/Query Response\n */\nexport const ListRecordResponseSchema = BaseResponseSchema.extend({\n data: z.array(RecordDataSchema).describe('Array of matching records'),\n pagination: z.object({\n total: z.number().optional().describe('Total matching records count'),\n limit: z.number().optional().describe('Page size'),\n offset: z.number().optional().describe('Page offset'),\n cursor: z.string().optional().describe('Cursor for next page'),\n nextCursor: z.string().optional().describe('Next cursor for pagination'),\n hasMore: z.boolean().describe('Are there more pages?'),\n }).describe('Pagination info'),\n});\n\n/**\n * ID Request (Get/Delete)\n */\nexport const IdRequestSchema = z.object({\n id: z.string().describe('Record ID'),\n});\n\n/**\n * Modification Result (for Batch/Bulk operations)\n */\nexport const ModificationResultSchema = z.object({\n id: z.string().optional().describe('Record ID if processed'),\n success: z.boolean(),\n errors: z.array(ApiErrorSchema).optional(),\n index: z.number().optional().describe('Index in original request'),\n data: z.unknown().optional().describe('Result data (e.g. created record)'),\n});\n\n/**\n * Bulk Operation Response\n */\nexport const BulkResponseSchema = BaseResponseSchema.extend({\n data: z.array(ModificationResultSchema).describe('Results for each item in the batch'),\n});\n\n/**\n * Delete Response\n */\nexport const DeleteResponseSchema = BaseResponseSchema.extend({\n id: z.string().describe('ID of the deleted record'),\n});\n\n// ==========================================\n// 4. API Contract Registry\n// ==========================================\n\n/**\n * Standard API Contracts map\n * Used for generating SDKs and Documentation\n */\nexport const StandardApiContracts = {\n create: {\n input: CreateRequestSchema,\n output: SingleRecordResponseSchema\n },\n delete: {\n input: IdRequestSchema,\n output: DeleteResponseSchema\n },\n get: {\n input: IdRequestSchema,\n output: SingleRecordResponseSchema\n },\n update: {\n input: UpdateRequestSchema,\n output: SingleRecordResponseSchema\n },\n list: {\n input: QuerySchema,\n output: ListRecordResponseSchema\n },\n bulkCreate: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkUpdate: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkUpsert: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkDelete: {\n input: z.object({ ids: z.array(z.string()) }),\n output: BulkResponseSchema\n }\n};\n\n// ==========================================\n// 5. DataLoader / N+1 Query Prevention\n// ==========================================\n\n/**\n * DataLoader Configuration Schema\n * Batch loading configuration to prevent N+1 query problems\n */\nexport const DataLoaderConfigSchema = z.object({\n maxBatchSize: z.number().int().default(100).describe('Maximum number of keys per batch load'),\n batchScheduleFn: z.enum(['microtask', 'timeout', 'manual']).default('microtask')\n .describe('Scheduling strategy for collecting batch keys'),\n cacheEnabled: z.boolean().default(true).describe('Enable per-request result caching'),\n cacheKeyFn: z.string().optional().describe('Name or identifier of the cache key function'),\n cacheTtl: z.number().min(0).optional().describe('Cache time-to-live in seconds (0 = no expiration)'),\n coalesceRequests: z.boolean().default(true).describe('Deduplicate identical requests within a batch window'),\n maxConcurrency: z.number().int().optional().describe('Maximum parallel batch requests'),\n});\n\n/**\n * Batch Loading Strategy Schema\n * Defines how batched data loading is orchestrated\n */\nexport const BatchLoadingStrategySchema = z.object({\n strategy: z.enum(['dataloader', 'windowed', 'prefetch']).describe('Batch loading strategy type'),\n windowMs: z.number().optional().describe('Collection window duration in milliseconds (for windowed strategy)'),\n prefetchDepth: z.number().int().optional().describe('Depth of relation prefetching (for prefetch strategy)'),\n associationLoading: z.enum(['lazy', 'eager', 'batch']).default('batch')\n .describe('How to load related associations'),\n});\n\n/**\n * Query Optimization Configuration Schema\n * Top-level configuration for N+1 prevention and query optimization\n */\nexport const QueryOptimizationConfigSchema = z.object({\n preventNPlusOne: z.boolean().describe('Enable N+1 query detection and prevention'),\n dataLoader: DataLoaderConfigSchema.optional().describe('DataLoader batch loading configuration'),\n batchStrategy: BatchLoadingStrategySchema.optional().describe('Batch loading strategy configuration'),\n maxQueryDepth: z.number().int().describe('Maximum depth for nested relation queries'),\n queryComplexityLimit: z.number().optional().describe('Maximum allowed query complexity score'),\n enableQueryPlan: z.boolean().default(false).describe('Log query execution plans for debugging'),\n});\n\nexport type ApiError = z.infer;\nexport type BaseResponse = z.infer;\nexport type RecordData = z.infer;\nexport type CreateRequest = z.infer;\nexport type UpdateRequest = z.infer;\nexport type BulkRequest = z.infer;\nexport type ExportRequest = z.infer;\nexport type SingleRecordResponse = z.infer;\nexport type ListRecordResponse = z.infer;\nexport type IdRequest = z.infer;\nexport type ModificationResult = z.infer;\nexport type BulkResponse = z.infer;\nexport type DeleteResponse = z.infer;\nexport type DataLoaderConfig = z.infer;\nexport type BatchLoadingStrategy = z.infer;\nexport type QueryOptimizationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, RateLimitConfigSchema } from '../shared/http.zod';\n\n/**\n * API Mapping Schema\n * Transform input/output data.\n */\nexport const ApiMappingSchema = z.object({\n source: z.string().describe('Source field/path'),\n target: z.string().describe('Target field/path'),\n transform: z.string().optional().describe('Transformation function name'),\n});\n\n/**\n * API Endpoint Schema\n * Defines an external facing API contract.\n */\nexport const ApiEndpointSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique endpoint ID'),\n path: z.string().regex(/^\\//).describe('URL Path (e.g. /api/v1/customers)'),\n method: HttpMethod.describe('HTTP Method'),\n \n /** Documentation */\n summary: z.string().optional(),\n description: z.string().optional(),\n \n /** Execution Logic */\n type: z.enum(['flow', 'script', 'object_operation', 'proxy']).describe('Implementation type'),\n target: z.string().describe('Target Flow ID, Script Name, or Proxy URL'),\n \n /** Logic Config */\n objectParams: z.object({\n object: z.string().optional(),\n operation: z.enum(['find', 'get', 'create', 'update', 'delete']).optional(),\n }).optional().describe('For object_operation type'),\n \n /** Data Transformation */\n inputMapping: z.array(ApiMappingSchema).optional().describe('Map Request Body to Internal Params'),\n outputMapping: z.array(ApiMappingSchema).optional().describe('Map Internal Result to Response Body'),\n \n /** Policies */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n rateLimit: RateLimitConfigSchema.optional().describe('Rate limiting policy'),\n cacheTtl: z.number().optional().describe('Response cache TTL in seconds'),\n});\n\nexport const ApiEndpoint = Object.assign(ApiEndpointSchema, {\n create: >(config: T) => config,\n});\n\nexport type ApiEndpoint = z.infer;\nexport type ApiEndpointInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\n\n/**\n * Service Status Enum\n * Describes the operational state of a service in the discovery response.\n *\n * - `available` – Fully operational: service is registered AND HTTP handler is verified.\n * - `registered` – Route is declared in the dispatcher table but the HTTP handler has\n * not been verified (may 501 at runtime).\n * - `unavailable` – Service is not installed / not registered in the kernel.\n * - `degraded` – Partially working (e.g., in-memory fallback, missing persistence).\n * - `stub` – Placeholder handler that always returns 501 Not Implemented.\n */\nexport const ServiceStatus = z.enum([\n 'available',\n 'registered',\n 'unavailable',\n 'degraded',\n 'stub',\n]).describe(\n 'available = fully operational, registered = route declared but handler unverified, '\n + 'unavailable = not installed, degraded = partial, stub = placeholder that returns 501'\n);\n\nexport type ServiceStatus = z.infer;\n\n/**\n * Service Status in Discovery Response\n * Reports per-service availability so clients can adapt their UI accordingly.\n */\nexport const ServiceInfoSchema = z.object({\n /** Whether the service is enabled and available */\n enabled: z.boolean(),\n /** Current operational status */\n status: ServiceStatus,\n /**\n * Whether the HTTP handler for this service is confirmed to be mounted.\n *\n * Semantics:\n * - `undefined` (omitted) = handler readiness is unknown / not yet verified.\n * - `true` = handler is registered in the adapter / dispatcher (safe to call).\n * - `false` = route is declared but no handler exists or only a stub is present\n * — requests are expected to receive 501 Not Implemented.\n *\n * Clients SHOULD check this flag before displaying or invoking a service endpoint and may\n * distinguish between \"unknown\" (omitted) and \"known missing\" (`false`).\n */\n handlerReady: z.boolean().optional().describe(\n 'Whether the HTTP handler is confirmed to be mounted. '\n + 'Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501).'\n ),\n /** Route path (only present if enabled) */\n route: z.string().optional().describe('e.g. /api/v1/analytics'),\n /** Implementation provider name */\n provider: z.string().optional().describe('e.g. \"objectql\", \"plugin-redis\", \"driver-memory\"'),\n /** Service version */\n version: z.string().optional().describe('Semantic version of the service implementation (e.g. \"3.0.6\")'),\n /** Human-readable reason if unavailable */\n message: z.string().optional().describe('e.g. \"Install plugin-workflow to enable\"'),\n /** Rate limit configuration for this service */\n rateLimit: z.object({\n requestsPerMinute: z.number().int().optional().describe('Maximum requests per minute'),\n requestsPerHour: z.number().int().optional().describe('Maximum requests per hour'),\n burstLimit: z.number().int().optional().describe('Maximum burst request count'),\n retryAfterMs: z.number().int().optional().describe('Suggested retry-after delay in milliseconds when rate-limited'),\n }).optional().describe('Rate limit and quota info for this service'),\n});\n\n/**\n * API Routes Schema\n * The \"Map\" for the frontend to know where to send requests.\n * This decouples the frontend from hardcoded URL paths.\n */\nexport const ApiRoutesSchema = z.object({\n /** Base URL for Object CRUD (Data Protocol) */\n data: z.string().describe('e.g. /api/v1/data'),\n \n /** Base URL for Schema Definitions (Metadata Protocol) */\n metadata: z.string().describe('e.g. /api/v1/meta'),\n\n /** Base URL for API Discovery endpoint */\n discovery: z.string().optional().describe('e.g. /api/v1/discovery'),\n\n /** Base URL for UI Configurations (Views, Menus) */\n ui: z.string().optional().describe('e.g. /api/v1/ui'),\n \n /** Base URL for Authentication (plugin-provided) */\n auth: z.string().optional().describe('e.g. /api/v1/auth'),\n \n /** Base URL for Automation (Flows/Scripts) */\n automation: z.string().optional().describe('e.g. /api/v1/automation'),\n \n /** Base URL for File/Storage operations */\n storage: z.string().optional().describe('e.g. /api/v1/storage'),\n \n /** Base URL for Analytics/BI operations */\n analytics: z.string().optional().describe('e.g. /api/v1/analytics'),\n \n /** GraphQL Endpoint (if enabled) */\n graphql: z.string().optional().describe('e.g. /graphql'),\n\n /** Base URL for Package Management */\n packages: z.string().optional().describe('e.g. /api/v1/packages'),\n\n /** Base URL for Workflow Engine */\n workflow: z.string().optional().describe('e.g. /api/v1/workflow'),\n\n /** Base URL for Realtime (WebSocket/SSE) */\n realtime: z.string().optional().describe('e.g. /api/v1/realtime'),\n\n /** Base URL for Notification Service */\n notifications: z.string().optional().describe('e.g. /api/v1/notifications'),\n\n /** Base URL for AI Engine (NLQ, Chat, Suggest) */\n ai: z.string().optional().describe('e.g. /api/v1/ai'),\n\n /** Base URL for Internationalization */\n i18n: z.string().optional().describe('e.g. /api/v1/i18n'),\n\n /** Base URL for Feed / Chatter API */\n feed: z.string().optional().describe('e.g. /api/v1/feed'),\n});\n\n/**\n * Discovery Response Schema\n * The root object returned by the Metadata Discovery Endpoint.\n * \n * Design rationale:\n * - `services` is the single source of truth for service availability.\n * Each service entry includes `enabled`, `status`, `route`, and `provider`.\n * - `routes` is a convenience shortcut: a flat map of service-name → route-path\n * so that clients can resolve endpoints without iterating the services map.\n * - `capabilities`/`features` was removed because it was fully derivable\n * from `services[x].enabled`. Use `services` to determine feature availability.\n */\nexport const DiscoverySchema = z.object({\n /** System Identity */\n name: z.string(),\n version: z.string(),\n environment: z.enum(['production', 'sandbox', 'development']),\n \n /** Dynamic Routing — convenience shortcut for client routing */\n routes: ApiRoutesSchema,\n \n /** Localization Info (helping frontend init i18n) */\n locale: z.object({\n default: z.string(),\n supported: z.array(z.string()),\n timezone: z.string(),\n }),\n \n /**\n * Per-service status map.\n * This is the **single source of truth** for service availability.\n * Clients use this to determine which features are available,\n * show/hide UI elements, and display appropriate messages.\n */\n services: z.record(z.string(), ServiceInfoSchema).describe(\n 'Per-service availability map keyed by CoreServiceName'\n ),\n\n /**\n * Hierarchical capability descriptors.\n * Declares platform features so clients can adapt UI without probing individual services.\n * Each key is a capability domain (e.g., \"comments\", \"automation\", \"search\"),\n * and its value describes what sub-features are available.\n */\n capabilities: z.record(z.string(), z.object({\n enabled: z.boolean().describe('Whether this capability is available'),\n features: z.record(z.string(), z.boolean()).optional()\n .describe('Sub-feature flags within this capability'),\n description: z.string().optional()\n .describe('Human-readable capability description'),\n })).optional().describe('Hierarchical capability descriptors for frontend intelligent adaptation'),\n\n /**\n * Schema discovery URLs for cross-ecosystem interoperability.\n */\n schemaDiscovery: z.object({\n openapi: z.string().optional().describe('URL to OpenAPI (Swagger) specification (e.g., \"/api/v1/openapi.json\")'),\n graphql: z.string().optional().describe('URL to GraphQL schema endpoint (e.g., \"/graphql\")'),\n jsonSchema: z.string().optional().describe('URL to JSON Schema definitions'),\n }).optional().describe('Schema discovery endpoints for API toolchain integration'),\n\n /**\n * Custom metadata key-value pairs for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n});\n\n/**\n * Well-Known Capabilities Schema\n * Flat boolean flags for quick feature detection by clients (ObjectUI).\n * Each flag indicates whether the backend supports a specific capability.\n * Clients can use these to show/hide UI elements without probing individual endpoints.\n */\nexport const WellKnownCapabilitiesSchema = z.object({\n /** Whether the backend supports Feed / Chatter API */\n feed: z.boolean().describe('Whether the backend supports Feed / Chatter API'),\n /** Whether the backend supports comments (a subset of Feed) */\n comments: z.boolean().describe('Whether the backend supports comments (a subset of Feed)'),\n /** Whether the backend supports Automation CRUD (flows, triggers) */\n automation: z.boolean().describe('Whether the backend supports Automation CRUD (flows, triggers)'),\n /** Whether the backend supports cron scheduling */\n cron: z.boolean().describe('Whether the backend supports cron scheduling'),\n /** Whether the backend supports full-text search */\n search: z.boolean().describe('Whether the backend supports full-text search'),\n /** Whether the backend supports async export */\n export: z.boolean().describe('Whether the backend supports async export'),\n /** Whether the backend supports chunked (multipart) uploads */\n chunkedUpload: z.boolean().describe('Whether the backend supports chunked (multipart) uploads'),\n}).describe('Well-known capability flags for frontend intelligent adaptation');\n\nexport type WellKnownCapabilities = z.infer;\nexport type DiscoveryResponse = z.infer;\nexport type ApiRoutes = z.infer;\nexport type ServiceInfo = z.infer;\n\n// ============================================================================\n// Route Health Report\n// ============================================================================\n\n/**\n * Single route health entry for the coverage report.\n */\nexport const RouteHealthEntrySchema = z.object({\n /** Route path (e.g. /api/v1/analytics) */\n route: z.string().describe('Route path pattern'),\n /** HTTP method */\n method: HttpMethod.describe('HTTP method (GET, POST, etc.)'),\n /** Target service name */\n service: z.string().describe('Target service name'),\n /** Whether the route is declared in discovery */\n declared: z.boolean().describe('Whether the route is declared in discovery/metadata'),\n /** Whether the handler is actually registered in the adapter/dispatcher */\n handlerRegistered: z.boolean().describe('Whether the HTTP handler is registered'),\n /**\n * Health check result:\n * - `pass` – Handler exists and responds (2xx/4xx — i.e., not 404/501/503)\n * - `fail` – Handler returned 501 or 503\n * - `missing` – No handler registered (404)\n * - `skip` – Health check was not performed\n */\n healthStatus: z.enum(['pass', 'fail', 'missing', 'skip']).describe(\n 'pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked'\n ),\n /** Optional diagnostic message */\n message: z.string().optional().describe('Diagnostic message'),\n});\n\nexport type RouteHealthEntry = z.infer;\n\n/**\n * Route Health Report Schema\n * Aggregated route coverage report produced at startup or on demand.\n *\n * This report enables automated detection of routes that are declared\n * in discovery metadata but have no corresponding HTTP handler.\n */\nexport const RouteHealthReportSchema = z.object({\n /** ISO 8601 timestamp of when the report was generated */\n timestamp: z.string().describe('ISO 8601 timestamp of report generation'),\n /** Adapter name that generated the report (e.g. \"hono\", \"express\", \"nextjs\") */\n adapter: z.string().describe('Adapter or runtime that produced this report'),\n /** Total routes declared in discovery / dispatcher table */\n totalDeclared: z.number().int().describe('Total routes declared in discovery'),\n /** Routes with a confirmed handler registration */\n totalRegistered: z.number().int().describe('Routes with confirmed handler'),\n /** Routes missing a handler */\n totalMissing: z.number().int().describe('Routes missing a handler'),\n /** Per-route health entries */\n routes: z.array(RouteHealthEntrySchema).describe('Per-route health entries'),\n});\n\nexport type RouteHealthReport = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metadata Event Types\n *\n * Triggered when metadata items are created, updated, or deleted.\n * Follows the pattern: `metadata.{type}.{action}`\n *\n * Examples:\n * - `metadata.object.created` - A new object was created\n * - `metadata.view.updated` - A view was updated\n * - `metadata.agent.deleted` - An agent was deleted\n */\nexport const MetadataEventType = z.enum([\n 'metadata.object.created',\n 'metadata.object.updated',\n 'metadata.object.deleted',\n 'metadata.field.created',\n 'metadata.field.updated',\n 'metadata.field.deleted',\n 'metadata.view.created',\n 'metadata.view.updated',\n 'metadata.view.deleted',\n 'metadata.app.created',\n 'metadata.app.updated',\n 'metadata.app.deleted',\n 'metadata.agent.created',\n 'metadata.agent.updated',\n 'metadata.agent.deleted',\n 'metadata.tool.created',\n 'metadata.tool.updated',\n 'metadata.tool.deleted',\n 'metadata.flow.created',\n 'metadata.flow.updated',\n 'metadata.flow.deleted',\n 'metadata.action.created',\n 'metadata.action.updated',\n 'metadata.action.deleted',\n 'metadata.workflow.created',\n 'metadata.workflow.updated',\n 'metadata.workflow.deleted',\n 'metadata.dashboard.created',\n 'metadata.dashboard.updated',\n 'metadata.dashboard.deleted',\n 'metadata.report.created',\n 'metadata.report.updated',\n 'metadata.report.deleted',\n 'metadata.role.created',\n 'metadata.role.updated',\n 'metadata.role.deleted',\n 'metadata.permission.created',\n 'metadata.permission.updated',\n 'metadata.permission.deleted',\n]);\n\nexport type MetadataEventType = z.infer;\n\n/**\n * Data Event Types\n *\n * Triggered when data records are created, updated, or deleted.\n * Follows the pattern: `data.record.{action}`\n */\nexport const DataEventType = z.enum([\n 'data.record.created',\n 'data.record.updated',\n 'data.record.deleted',\n 'data.field.changed',\n]);\n\nexport type DataEventType = z.infer;\n\n/**\n * Metadata Event Payload\n *\n * Represents a metadata change event (create, update, delete).\n * Used for real-time synchronization of metadata across clients.\n */\nexport const MetadataEventSchema = z.object({\n /** Unique event identifier */\n id: z.string().uuid().describe('Unique event identifier'),\n\n /** Event type (metadata.{type}.{action}) */\n type: MetadataEventType.describe('Event type'),\n\n /** Metadata type (object, view, agent, tool, etc.) */\n metadataType: z.string().describe('Metadata type (object, view, agent, etc.)'),\n\n /** Metadata item name */\n name: z.string().describe('Metadata item name'),\n\n /** Package ID (if applicable) */\n packageId: z.string().optional().describe('Package ID'),\n\n /** Full definition (only for create/update events) */\n definition: z.unknown().optional().describe('Full definition (create/update only)'),\n\n /** User who triggered the event */\n userId: z.string().optional().describe('User who triggered the event'),\n\n /** Event timestamp (ISO 8601) */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\nexport type MetadataEvent = z.infer;\n\n/**\n * Data Event Payload\n *\n * Represents a data record change event (create, update, delete).\n * Used for real-time synchronization of data records across clients.\n */\nexport const DataEventSchema = z.object({\n /** Unique event identifier */\n id: z.string().uuid().describe('Unique event identifier'),\n\n /** Event type (data.record.{action}) */\n type: DataEventType.describe('Event type'),\n\n /** Object name */\n object: z.string().describe('Object name'),\n\n /** Record ID */\n recordId: z.string().describe('Record ID'),\n\n /** Changed fields (update events only) */\n changes: z.record(z.string(), z.unknown()).optional().describe('Changed fields'),\n\n /** Record before update (update events only) */\n before: z.record(z.string(), z.unknown()).optional().describe('Before state'),\n\n /** Record after update (create/update events) */\n after: z.record(z.string(), z.unknown()).optional().describe('After state'),\n\n /** User who triggered the event */\n userId: z.string().optional().describe('User who triggered the event'),\n\n /** Event timestamp (ISO 8601) */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\nexport type DataEvent = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Realtime Shared Protocol\n * \n * Shared schemas and types for real-time communication protocols.\n * This module consolidates overlapping definitions between the transport-level\n * realtime protocol (SSE/Polling/WebSocket) and the WebSocket collaboration protocol.\n * \n * **Architecture:**\n * - `realtime-shared.zod.ts` — Shared base schemas (Presence, Event types)\n * - `realtime.zod.ts` — Transport-layer protocol (Channel, Subscription, Transport selection)\n * - `websocket.zod.ts` — Collaboration protocol (Cursor, OT editing, Advanced presence)\n * \n * @see realtime.zod.ts for transport-layer configuration\n * @see websocket.zod.ts for collaborative editing protocol\n */\n\n// ==========================================\n// Shared Presence Status\n// ==========================================\n\n/**\n * Presence Status Enum (Unified)\n * \n * Canonical user presence status shared across all realtime protocols.\n * Used by both transport-level presence tracking (realtime.zod.ts)\n * and WebSocket collaboration presence (websocket.zod.ts).\n * \n * @example\n * ```typescript\n * import { PresenceStatus } from './realtime-shared.zod';\n * const status = PresenceStatus.parse('online'); // ✅\n * ```\n */\nexport const PresenceStatus = z.enum([\n 'online', // User is actively connected\n 'away', // User is idle/inactive\n 'busy', // User is busy (do not disturb)\n 'offline', // User is disconnected\n]);\n\nexport type PresenceStatus = z.infer;\n\n// ==========================================\n// Shared Realtime Actions\n// ==========================================\n\n/**\n * Realtime Record Action Enum (Unified)\n * \n * Canonical action types for real-time record change events.\n * Shared between transport-level events and WebSocket event messages.\n */\nexport const RealtimeRecordAction = z.enum([\n 'created',\n 'updated',\n 'deleted',\n]);\n\nexport type RealtimeRecordAction = z.infer;\n\n// ==========================================\n// Shared Base Presence Schema\n// ==========================================\n\n/**\n * Base Presence Schema (Unified)\n * \n * Core presence fields shared across all realtime protocols.\n * Transport-level (realtime.zod.ts) and collaboration-level (websocket.zod.ts)\n * presence schemas extend this base with protocol-specific fields.\n * \n * @example\n * ```typescript\n * const presence = BasePresenceSchema.parse({\n * userId: 'user-123',\n * status: 'online',\n * lastSeen: '2024-01-15T10:30:00Z',\n * });\n * ```\n */\nexport const BasePresenceSchema = z.object({\n /** User identifier */\n userId: z.string().describe('User identifier'),\n\n /** Current presence status */\n status: PresenceStatus.describe('Current presence status'),\n\n /** Last activity timestamp */\n lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n\n /** Custom metadata */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom presence data (e.g., current page, custom status)'),\n});\n\nexport type BasePresence = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { RealtimeRecordAction, BasePresenceSchema } from './realtime-shared.zod';\n\n// Re-export shared types for backward compatibility\nexport { PresenceStatus, RealtimeRecordAction, BasePresenceSchema } from './realtime-shared.zod';\nexport type { BasePresence } from './realtime-shared.zod';\n\n/**\n * Transport Protocol Enum\n * Defines the communication protocol for realtime data synchronization\n */\nexport const TransportProtocol = z.enum([\n 'websocket', // Full-duplex, low latency communication\n 'sse', // Server-Sent Events, unidirectional push\n 'polling', // Short polling, best compatibility\n]);\n\nexport type TransportProtocol = z.infer;\n\n/**\n * Event Type Enum\n * Types of realtime events that can be subscribed to\n */\nexport const RealtimeEventType = z.enum([\n 'record.created',\n 'record.updated',\n 'record.deleted',\n 'field.changed',\n]);\n\nexport type RealtimeEventType = z.infer;\n\n/**\n * Subscription Event Configuration\n * Defines what events to subscribe to with optional filtering\n */\nexport const SubscriptionEventSchema = z.object({\n type: RealtimeEventType.describe('Type of event to subscribe to'),\n object: z.string().optional().describe('Object name to subscribe to'),\n filters: z.unknown().optional().describe('Filter conditions'),\n});\n\n/**\n * Subscription Schema\n * Configuration for subscribing to realtime events\n */\nexport const SubscriptionSchema = z.object({\n id: z.string().uuid().describe('Unique subscription identifier'),\n events: z.array(SubscriptionEventSchema).describe('Array of events to subscribe to'),\n transport: TransportProtocol.describe('Transport protocol to use'),\n channel: z.string().optional().describe('Optional channel name for grouping subscriptions'),\n});\n\nexport type Subscription = z.infer;\n\n/**\n * Presence Schema\n * Tracks user online status and metadata.\n * Extends the shared BasePresenceSchema for transport-level presence tracking.\n */\nexport const RealtimePresenceSchema = BasePresenceSchema;\n\nexport type RealtimePresence = z.infer;\n\n/**\n * Realtime Event Schema\n * Represents a realtime synchronization event\n */\nexport const RealtimeEventSchema = z.object({\n id: z.string().uuid().describe('Unique event identifier'),\n type: z.string().describe('Event type (e.g., record.created, record.updated)'),\n object: z.string().optional().describe('Object name the event relates to'),\n action: RealtimeRecordAction.optional().describe('Action performed'),\n payload: z.record(z.string(), z.unknown()).describe('Event payload data'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when event occurred'),\n userId: z.string().optional().describe('User who triggered the event'),\n sessionId: z.string().optional().describe('Session identifier'),\n});\n\nexport type RealtimeEvent = z.infer;\n\n/**\n * Realtime Configuration Schema\n * \n * Configuration for enabling realtime data synchronization.\n */\nexport const RealtimeConfigSchema = z.object({\n /** Enable realtime sync */\n enabled: z.boolean().default(true).describe('Enable realtime synchronization'),\n \n /** Transport protocol */\n transport: TransportProtocol.default('websocket').describe('Transport protocol'),\n \n /** Default subscriptions */\n subscriptions: z.array(SubscriptionSchema).optional().describe('Default subscriptions'),\n}).passthrough(); // Allow additional properties\n\nexport type RealtimeConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventNameSchema } from '../shared/identifiers.zod';\nimport { PresenceStatus } from './realtime-shared.zod';\n\n// Re-export shared PresenceStatus for backward compatibility\nexport { PresenceStatus } from './realtime-shared.zod';\n\n/**\n * WebSocket Event Protocol\n * \n * Defines the schema for WebSocket-based real-time communication in ObjectStack.\n * Supports event subscriptions, filtering, presence tracking, and collaborative editing.\n * \n * Industry alignment: Firebase Realtime Database, Socket.IO, Pusher\n */\n\n// ==========================================\n// Message Types\n// ==========================================\n\n/**\n * WebSocket Message Type Enum\n * Defines the types of messages that can be sent over WebSocket\n */\nexport const WebSocketMessageType = z.enum([\n 'subscribe', // Client subscribes to events\n 'unsubscribe', // Client unsubscribes from events\n 'event', // Server sends event to client\n 'ping', // Keepalive ping\n 'pong', // Keepalive pong response\n 'ack', // Acknowledgment of message receipt\n 'error', // Error message\n 'presence', // Presence update (user status)\n 'cursor', // Cursor position update (collaborative editing)\n 'edit', // Document edit operation (collaborative editing)\n]);\n\nexport type WebSocketMessageType = z.infer;\n\n// ==========================================\n// Event Subscription\n// ==========================================\n\n/**\n * Event Filter Operator Enum\n * SQL-like filter operators for event filtering\n */\nexport const FilterOperator = z.enum([\n 'eq', // Equal\n 'ne', // Not equal\n 'gt', // Greater than\n 'gte', // Greater than or equal\n 'lt', // Less than\n 'lte', // Less than or equal\n 'in', // In array\n 'nin', // Not in array\n 'contains', // String contains\n 'startsWith', // String starts with\n 'endsWith', // String ends with\n 'exists', // Field exists\n 'regex', // Regex match\n]);\n\nexport type FilterOperator = z.infer;\n\n/**\n * Event Filter Condition\n * Defines a single filter condition for event filtering\n */\nexport const EventFilterCondition = z.object({\n field: z.string().describe('Field path to filter on (supports dot notation, e.g., \"user.email\")'),\n operator: FilterOperator.describe('Comparison operator'),\n value: z.unknown().optional().describe('Value to compare against (not needed for \"exists\" operator)'),\n});\n\nexport type EventFilterCondition = z.infer;\n\n/**\n * Event Filter Schema\n * Logical combination of filter conditions\n */\nexport const EventFilterSchema: z.ZodType<{\n conditions?: EventFilterCondition[];\n and?: EventFilter[];\n or?: EventFilter[];\n not?: EventFilter;\n}> = z.object({\n conditions: z.array(EventFilterCondition).optional().describe('Array of filter conditions'),\n and: z.lazy(() => z.array(EventFilterSchema)).optional().describe('AND logical combination of filters'),\n or: z.lazy(() => z.array(EventFilterSchema)).optional().describe('OR logical combination of filters'),\n not: z.lazy(() => EventFilterSchema).optional().describe('NOT logical negation of filter'),\n});\n\nexport type EventFilter = z.infer;\n\n/**\n * Event Pattern Schema\n * Event name pattern that supports wildcards for subscriptions\n */\nexport const EventPatternSchema = z\n .string()\n .min(1)\n .regex(/^[a-z*][a-z0-9_.*]*$/, {\n message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., \"record.*\", \"*.created\", \"user.login\")',\n })\n .describe('Event pattern (supports wildcards like \"record.*\" or \"*.created\")');\n\nexport type EventPattern = z.infer;\n\n/**\n * Event Subscription Config\n * Configuration for subscribing to specific events\n */\nexport const EventSubscriptionSchema = z.object({\n subscriptionId: z.string().uuid().describe('Unique subscription identifier'),\n events: z.array(EventPatternSchema).describe('Event patterns to subscribe to (supports wildcards, e.g., \"record.*\", \"user.created\")'),\n objects: z.array(z.string()).optional().describe('Object names to filter events by (e.g., [\"account\", \"contact\"])'),\n filters: EventFilterSchema.optional().describe('Advanced filter conditions for event payloads'),\n channels: z.array(z.string()).optional().describe('Channel names for scoped subscriptions'),\n});\n\nexport type EventSubscription = z.infer;\n\n/**\n * Unsubscribe Request\n * Request to unsubscribe from events\n */\nexport const UnsubscribeRequestSchema = z.object({\n subscriptionId: z.string().uuid().describe('Subscription ID to unsubscribe from'),\n});\n\nexport type UnsubscribeRequest = z.infer;\n\n// ==========================================\n// Presence Tracking\n// ==========================================\n\n/**\n * Presence Status Enum\n * Re-exported from realtime-shared.zod.ts for backward compatibility\n */\nexport const WebSocketPresenceStatus = PresenceStatus;\n\nexport type WebSocketPresenceStatus = z.infer;\n\n/**\n * Presence State Schema\n * Tracks real-time user presence and activity\n */\nexport const PresenceStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Unique session identifier'),\n status: WebSocketPresenceStatus.describe('Current presence status'),\n lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n currentLocation: z.string().optional().describe('Current page/route user is viewing'),\n device: z.enum(['desktop', 'mobile', 'tablet', 'other']).optional().describe('Device type'),\n customStatus: z.string().optional().describe('Custom user status message'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional custom presence data'),\n});\n\nexport type PresenceState = z.infer;\n\n/**\n * Presence Update Request\n * Client request to update presence status\n */\nexport const PresenceUpdateSchema = z.object({\n status: WebSocketPresenceStatus.optional().describe('Updated presence status'),\n currentLocation: z.string().optional().describe('Updated current location'),\n customStatus: z.string().optional().describe('Updated custom status message'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type PresenceUpdate = z.infer;\n\n// ==========================================\n// Collaborative Editing Protocol\n// ==========================================\n\n/**\n * Cursor Position Schema\n * Represents a cursor position in a document\n */\nexport const CursorPositionSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier being edited'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Column number (0-indexed)'),\n }).optional().describe('Cursor position in document'),\n selection: z.object({\n start: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }),\n end: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }),\n }).optional().describe('Selection range (if text is selected)'),\n color: z.string().optional().describe('Cursor color for visual representation'),\n userName: z.string().optional().describe('Display name of user'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),\n});\n\nexport type CursorPosition = z.infer;\n\n/**\n * Edit Operation Type Enum\n * Types of edit operations for collaborative editing\n */\nexport const EditOperationType = z.enum([\n 'insert', // Insert text at position\n 'delete', // Delete text from range\n 'replace', // Replace text in range\n]);\n\nexport type EditOperationType = z.infer;\n\n/**\n * Edit Operation Schema\n * Represents a single edit operation on a document\n * Supports Operational Transformation (OT) for conflict resolution\n */\nexport const EditOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n documentId: z.string().describe('Document identifier'),\n userId: z.string().describe('User who performed the edit'),\n sessionId: z.string().uuid().describe('Session identifier'),\n type: EditOperationType.describe('Type of edit operation'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Column number (0-indexed)'),\n }).describe('Starting position of the operation'),\n endPosition: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }).optional().describe('Ending position (for delete/replace operations)'),\n content: z.string().optional().describe('Content to insert/replace'),\n version: z.number().int().nonnegative().describe('Document version before this operation'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),\n baseOperationId: z.string().uuid().optional().describe('Previous operation ID this builds upon (for OT)'),\n});\n\nexport type EditOperation = z.infer;\n\n/**\n * Document State Schema\n * Represents the current state of a collaborative document\n */\nexport const DocumentStateSchema = z.object({\n documentId: z.string().describe('Document identifier'),\n version: z.number().int().nonnegative().describe('Current document version'),\n content: z.string().describe('Current document content'),\n lastModified: z.string().datetime().describe('ISO 8601 datetime of last modification'),\n activeSessions: z.array(z.string().uuid()).describe('Active editing session IDs'),\n checksum: z.string().optional().describe('Content checksum for integrity verification'),\n});\n\nexport type DocumentState = z.infer;\n\n// ==========================================\n// WebSocket Messages\n// ==========================================\n\n/**\n * Base WebSocket Message\n * All WebSocket messages extend this base structure\n */\nconst BaseWebSocketMessage = z.object({\n messageId: z.string().uuid().describe('Unique message identifier'),\n type: WebSocketMessageType.describe('Message type'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when message was sent'),\n});\n\n/**\n * Subscribe Message\n * Client sends this to subscribe to events\n */\nexport const SubscribeMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('subscribe'),\n subscription: EventSubscriptionSchema.describe('Subscription configuration'),\n});\n\nexport type SubscribeMessage = z.infer;\n\n/**\n * Unsubscribe Message\n * Client sends this to unsubscribe from events\n */\nexport const UnsubscribeMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('unsubscribe'),\n request: UnsubscribeRequestSchema.describe('Unsubscribe request'),\n});\n\nexport type UnsubscribeMessage = z.infer;\n\n/**\n * Event Message\n * Server sends this when a subscribed event occurs\n */\nexport const EventMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('event'),\n subscriptionId: z.string().uuid().describe('Subscription ID this event belongs to'),\n eventName: EventNameSchema.describe('Event name'),\n object: z.string().optional().describe('Object name the event relates to'),\n payload: z.unknown().describe('Event payload data'),\n userId: z.string().optional().describe('User who triggered the event'),\n});\n\nexport type EventMessage = z.infer;\n\n/**\n * Presence Message\n * Presence update message\n */\nexport const PresenceMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('presence'),\n presence: PresenceStateSchema.describe('Presence state'),\n});\n\nexport type PresenceMessage = z.infer;\n\n/**\n * Cursor Message\n * Cursor position update for collaborative editing\n */\nexport const CursorMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('cursor'),\n cursor: CursorPositionSchema.describe('Cursor position'),\n});\n\nexport type CursorMessage = z.infer;\n\n/**\n * Edit Message\n * Document edit operation for collaborative editing\n */\nexport const EditMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('edit'),\n operation: EditOperationSchema.describe('Edit operation'),\n});\n\nexport type EditMessage = z.infer;\n\n/**\n * Acknowledgment Message\n * Server acknowledges receipt of a message\n */\nexport const AckMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('ack'),\n ackMessageId: z.string().uuid().describe('ID of the message being acknowledged'),\n success: z.boolean().describe('Whether the operation was successful'),\n error: z.string().optional().describe('Error message if operation failed'),\n});\n\nexport type AckMessage = z.infer;\n\n/**\n * Error Message\n * Server sends error information\n */\nexport const ErrorMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('error'),\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n details: z.unknown().optional().describe('Additional error details'),\n});\n\nexport type ErrorMessage = z.infer;\n\n/**\n * Ping Message\n * Keepalive ping from client or server\n */\nexport const PingMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('ping'),\n});\n\nexport type PingMessage = z.infer;\n\n/**\n * Pong Message\n * Keepalive pong response\n */\nexport const PongMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('pong'),\n pingMessageId: z.string().uuid().optional().describe('ID of ping message being responded to'),\n});\n\nexport type PongMessage = z.infer;\n\n/**\n * WebSocket Message Union\n * Discriminated union of all WebSocket message types\n */\nexport const WebSocketMessageSchema = z.discriminatedUnion('type', [\n SubscribeMessageSchema,\n UnsubscribeMessageSchema,\n EventMessageSchema,\n PresenceMessageSchema,\n CursorMessageSchema,\n EditMessageSchema,\n AckMessageSchema,\n ErrorMessageSchema,\n PingMessageSchema,\n PongMessageSchema,\n]);\n\nexport type WebSocketMessage = z.infer;\n\n// ==========================================\n// Connection Configuration\n// ==========================================\n\n/**\n * WebSocket Connection Config\n * Configuration for WebSocket connections\n */\nexport const WebSocketConfigSchema = z.object({\n url: z.string().url().describe('WebSocket server URL'),\n protocols: z.array(z.string()).optional().describe('WebSocket sub-protocols'),\n reconnect: z.boolean().optional().default(true).describe('Enable automatic reconnection'),\n reconnectInterval: z.number().int().positive().optional().default(1000).describe('Reconnection interval in milliseconds'),\n maxReconnectAttempts: z.number().int().positive().optional().default(5).describe('Maximum reconnection attempts'),\n pingInterval: z.number().int().positive().optional().default(30000).describe('Ping interval in milliseconds'),\n timeout: z.number().int().positive().optional().default(5000).describe('Message timeout in milliseconds'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for WebSocket handshake'),\n});\n\nexport type WebSocketConfig = z.infer;\n\n// ==========================================\n// Simplified Collaboration API\n// ==========================================\n\n/**\n * Simplified WebSocket Event Schema\n * \n * A simplified event schema for basic WebSocket communication.\n * Complements the comprehensive WebSocketMessageSchema above for simpler use cases.\n * \n * @example Subscribe to channel\n * ```typescript\n * {\n * type: 'subscribe',\n * channel: 'record.account.123',\n * payload: { events: ['created', 'updated'] },\n * timestamp: Date.now()\n * }\n * ```\n * \n * @example Data change notification\n * ```typescript\n * {\n * type: 'data-change',\n * channel: 'record.account.123',\n * payload: { id: '123', action: 'updated', data: {...} },\n * timestamp: Date.now()\n * }\n * ```\n */\nexport const WebSocketEventSchema = z.object({\n type: z.enum([\n 'subscribe', // Client subscribes to channel\n 'unsubscribe', // Client unsubscribes from channel\n 'data-change', // Data modification event\n 'presence-update', // User presence change\n 'cursor-update', // Cursor position change (collaborative editing)\n 'error', // Error message\n ]).describe('Event type'),\n channel: z.string().describe('Channel identifier (e.g., \"record.account.123\", \"user.456\")'),\n payload: z.unknown().describe('Event payload data'),\n timestamp: z.number().describe('Unix timestamp in milliseconds'),\n});\n\nexport type WebSocketEvent = z.infer;\n\n/**\n * Simplified Presence State Schema\n * \n * A simplified presence schema for basic user presence tracking.\n * Complements the comprehensive PresenceStateSchema for simpler integrations.\n * \n * Use this for basic presence features. For advanced features like device tracking,\n * custom status, and session management, use the comprehensive PresenceStateSchema above.\n * \n * @example User online\n * ```typescript\n * {\n * userId: 'user123',\n * userName: 'John Doe',\n * status: 'online',\n * lastSeen: Date.now(),\n * metadata: { currentPage: '/dashboard' }\n * }\n * ```\n */\nexport const SimplePresenceStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n userName: z.string().describe('User display name'),\n status: z.enum(['online', 'away', 'offline']).describe('User presence status'),\n lastSeen: z.number().describe('Unix timestamp of last activity in milliseconds'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional presence metadata (e.g., current page, custom status)'),\n});\n\nexport type SimplePresenceState = z.infer;\n\n/**\n * Simplified Cursor Position Schema\n * \n * A simplified cursor position schema for basic collaborative editing.\n * Complements the comprehensive CursorPositionSchema for simpler use cases.\n * \n * Use this for basic cursor sharing. For advanced features like selections,\n * color coding, and document versioning, use the comprehensive CursorPositionSchema above.\n * \n * @example Cursor in text field\n * ```typescript\n * {\n * userId: 'user123',\n * recordId: 'account_456',\n * fieldName: 'description',\n * position: 42,\n * selection: { start: 42, end: 57 }\n * }\n * ```\n */\nexport const SimpleCursorPositionSchema = z.object({\n userId: z.string().describe('User identifier'),\n recordId: z.string().describe('Record identifier being edited'),\n fieldName: z.string().describe('Field name being edited'),\n position: z.number().describe('Cursor position (character offset from start)'),\n selection: z.object({\n start: z.number().describe('Selection start position'),\n end: z.number().describe('Selection end position'),\n }).optional().describe('Text selection range (if text is selected)'),\n});\n\nexport type SimpleCursorPosition = z.infer;\n\n/**\n * WebSocket Server Configuration Schema\n * \n * Server-side configuration for WebSocket services.\n * Controls features like presence tracking, cursor sharing, and connection management.\n * \n * @example Production configuration\n * ```typescript\n * {\n * enabled: true,\n * path: '/ws',\n * heartbeatInterval: 30000,\n * reconnectAttempts: 5,\n * presence: true,\n * cursorSharing: true\n * }\n * ```\n */\nexport const WebSocketServerConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable WebSocket server'),\n path: z.string().default('/ws').describe('WebSocket endpoint path'),\n heartbeatInterval: z.number().default(30000).describe('Heartbeat interval in milliseconds'),\n reconnectAttempts: z.number().default(5).describe('Maximum reconnection attempts for clients'),\n presence: z.boolean().default(false).describe('Enable presence tracking'),\n cursorSharing: z.boolean().default(false).describe('Enable collaborative cursor sharing'),\n});\n\nexport type WebSocketServerConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { CorsConfigSchema, StaticMountSchema, HttpMethod } from '../shared/http.zod';\n\n// Re-export HttpMethod for convenience\nexport { HttpMethod };\n\n/**\n * Route Category Enum\n * Classifies routes for middleware application and security policies.\n */\nexport const RouteCategory = z.enum([\n 'system', // Health, Metrics, Info (No Auth usually)\n 'api', // Business Logic API (Auth required)\n 'auth', // Login/Callback endpoints\n 'static', // Asset serving\n 'webhook', // External callbacks\n 'plugin' // Plugin extensions\n]);\n\nexport type RouteCategory = z.infer;\n\n/**\n * Route Definition Schema\n * Describes a single routable endpoint in the Kernel.\n */\nexport const RouteDefinitionSchema = z.object({\n /**\n * HTTP Method\n */\n method: HttpMethod,\n \n /**\n * URL Path Pattern (supports parameters like /user/:id)\n */\n path: z.string().describe('URL Path pattern'),\n \n /**\n * Route Type/Category\n */\n category: RouteCategory.default('api'),\n \n /**\n * Handler Identifier\n * References an internal function or plugin action ID.\n */\n handler: z.string().describe('Unique handler identifier'),\n \n /**\n * Route specific metadata\n */\n summary: z.string().optional().describe('OpenAPI summary'),\n description: z.string().optional().describe('OpenAPI description'),\n \n /**\n * Security constraints\n */\n public: z.boolean().default(false).describe('Is publicly accessible'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /**\n * Performance hints\n */\n timeout: z.number().int().optional().describe('Execution timeout in ms'),\n rateLimit: z.string().optional().describe('Rate limit policy name'),\n});\n\nexport type RouteDefinition = z.infer;\n\n/**\n * Router Configuration Schema\n * Global routing table configuration.\n */\nexport const RouterConfigSchema = z.object({\n /**\n * URL Prefix for all kernel routes\n */\n basePath: z.string().default('/api').describe('Global API prefix'),\n \n /**\n * Standard Protocol Mounts (Relative to basePath)\n */\n mounts: z.object({\n data: z.string().default('/data').describe('Data Protocol (CRUD)'),\n metadata: z.string().default('/meta').describe('Metadata Protocol (Schemas)'),\n auth: z.string().default('/auth').describe('Auth Protocol'),\n automation: z.string().default('/automation').describe('Automation Protocol'),\n storage: z.string().default('/storage').describe('Storage Protocol'),\n analytics: z.string().default('/analytics').describe('Analytics Protocol'),\n graphql: z.string().default('/graphql').describe('GraphQL Endpoint'),\n ui: z.string().default('/ui').describe('UI Metadata Protocol (Views, Layouts)'),\n workflow: z.string().default('/workflow').describe('Workflow Engine Protocol'),\n realtime: z.string().default('/realtime').describe('Realtime/WebSocket Protocol'),\n notifications: z.string().default('/notifications').describe('Notification Protocol'),\n ai: z.string().default('/ai').describe('AI Engine Protocol (NLQ, Chat, Suggest)'),\n i18n: z.string().default('/i18n').describe('Internationalization Protocol'),\n packages: z.string().default('/packages').describe('Package Management Protocol'),\n }).default({\n data: '/data',\n metadata: '/meta',\n auth: '/auth',\n automation: '/automation',\n storage: '/storage',\n analytics: '/analytics',\n graphql: '/graphql',\n ui: '/ui',\n workflow: '/workflow',\n realtime: '/realtime',\n notifications: '/notifications',\n ai: '/ai',\n i18n: '/i18n',\n packages: '/packages',\n }), // Defaults match standardized spec\n\n /**\n * Cross-Origin Resource Sharing\n */\n cors: CorsConfigSchema.optional(),\n \n /**\n * Static asset mounts\n */\n staticMounts: z.array(StaticMountSchema).optional(),\n});\n\nexport type RouterConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * OData v4 Protocol Support\n * \n * Open Data Protocol (OData) v4 is an industry-standard protocol for building\n * and consuming RESTful APIs. It provides a uniform way to expose, structure,\n * query, and manipulate data.\n * \n * ## Overview\n * \n * OData v4 provides standardized URL conventions for querying data including:\n * - $select: Choose which fields to return\n * - $filter: Filter results with complex expressions\n * - $orderby: Sort results\n * - $top/$skip: Pagination\n * - $expand: Include related entities\n * - $count: Get total count\n * \n * ## Use Cases\n * \n * 1. **Enterprise Integration**\n * - Integrate with Microsoft Dynamics 365\n * - Connect to SharePoint Online\n * - SAP OData services\n * \n * 2. **API Standardization**\n * - Provide consistent query interface\n * - Standard pagination and filtering\n * - Industry-recognized protocol\n * \n * 3. **External Data Sources**\n * - Connect to OData-compliant systems\n * - Federated queries\n * - Data virtualization\n * \n * @see https://www.odata.org/documentation/\n * @see https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html\n * \n * @example OData Query\n * ```\n * GET /api/odata/customers?\n * $select=name,email&\n * $filter=country eq 'US' and revenue gt 100000&\n * $orderby=revenue desc&\n * $top=10&\n * $skip=20&\n * $expand=orders&\n * $count=true\n * ```\n * \n * @example Programmatic Use\n * ```typescript\n * const query: ODataQuery = {\n * select: ['name', 'email'],\n * filter: \"country eq 'US' and revenue gt 100000\",\n * orderby: 'revenue desc',\n * top: 10,\n * skip: 20,\n * expand: ['orders'],\n * count: true\n * }\n * ```\n */\n\n/**\n * OData Query Options Schema\n * \n * System query options defined by OData v4 specification.\n * These are URL query parameters that control the query execution.\n * \n * @see https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html#sec_SystemQueryOptions\n */\nexport const ODataQuerySchema = z.object({\n /**\n * $select - Select specific fields to return\n * \n * Comma-separated list of field names to include in the response.\n * Reduces payload size and improves performance.\n * \n * @example \"name,email,phone\"\n * @example \"id,customer/name\" - With navigation path\n */\n $select: z.union([\n z.string(), // \"name,email\"\n z.array(z.string()), // [\"name\", \"email\"]\n ]).optional().describe('Fields to select'),\n\n /**\n * $filter - Filter results with conditions\n * \n * OData filter expression using comparison operators, logical operators,\n * and functions.\n * \n * Comparison: eq, ne, lt, le, gt, ge\n * Logical: and, or, not\n * Functions: contains, startswith, endswith, length, indexof, substring, etc.\n * \n * @example \"age gt 18\"\n * @example \"country eq 'US' and revenue gt 100000\"\n * @example \"contains(name, 'Smith')\"\n * @example \"startswith(email, 'admin') and isActive eq true\"\n */\n $filter: z.string().optional().describe('Filter expression (OData filter syntax)'),\n\n /**\n * $orderby - Sort results\n * \n * Comma-separated list of fields with optional asc/desc.\n * Default is ascending.\n * \n * @example \"name\"\n * @example \"revenue desc\"\n * @example \"country asc, revenue desc\"\n */\n $orderby: z.union([\n z.string(), // \"name desc\"\n z.array(z.string()), // [\"name desc\", \"email asc\"]\n ]).optional().describe('Sort order'),\n\n /**\n * $top - Limit number of results\n * \n * Maximum number of results to return.\n * Equivalent to SQL LIMIT or FETCH FIRST.\n * \n * @example 10\n * @example 100\n */\n $top: z.number().int().min(0).optional().describe('Max results to return'),\n\n /**\n * $skip - Skip results for pagination\n * \n * Number of results to skip before returning results.\n * Equivalent to SQL OFFSET.\n * \n * @example 20\n * @example 100\n */\n $skip: z.number().int().min(0).optional().describe('Results to skip'),\n\n /**\n * $expand - Include related entities (lookup/master_detail fields)\n * \n * Comma-separated list of navigation properties (relationship field names) to expand.\n * Loads related data in the same request by resolving lookup and master_detail fields.\n * The engine replaces foreign key IDs with full related objects via batch $in queries.\n * Supports nested expand via OData parenthetical syntax.\n * \n * Behavior:\n * - Only fields with `type: 'lookup'` or `type: 'master_detail'` and a valid `reference` are expanded.\n * - Fields without a schema or reference definition are silently skipped (ID returned as-is).\n * - Maximum expand depth defaults to 3 (configurable via QueryAdapterConfig).\n * \n * @example \"orders\"\n * @example \"customer,products\"\n * @example \"orders($select=id,total)\" - With nested query options\n */\n $expand: z.union([\n z.string(), // \"orders\"\n z.array(z.string()), // [\"orders\", \"customer\"]\n ]).optional().describe('Navigation properties to expand (lookup/master_detail fields)'),\n\n /**\n * $count - Include total count\n * \n * When true, includes totalResults count in response.\n * Useful for pagination UI.\n * \n * @example true\n */\n $count: z.boolean().optional().describe('Include total count'),\n\n /**\n * $search - Full-text search\n * \n * Free-text search expression.\n * Search implementation is service-specific.\n * \n * @example \"John Smith\"\n * @example \"urgent AND support\"\n */\n $search: z.string().optional().describe('Search expression'),\n\n /**\n * $format - Response format\n * \n * Preferred response format.\n * \n * @example \"json\"\n * @example \"xml\"\n */\n $format: z.enum(['json', 'xml', 'atom']).optional().describe('Response format'),\n\n /**\n * $apply - Data aggregation\n * \n * Aggregation transformations (groupby, aggregate, etc.)\n * Part of OData aggregation extension.\n * \n * @example \"groupby((country),aggregate(revenue with sum as totalRevenue))\"\n */\n $apply: z.string().optional().describe('Aggregation expression'),\n});\n\nexport type ODataQuery = z.infer;\n\n/**\n * OData Filter Operator\n * \n * Standard comparison and logical operators in OData filter expressions.\n */\nexport const ODataFilterOperatorSchema = z.enum([\n // Comparison Operators\n 'eq', // Equal to\n 'ne', // Not equal to\n 'lt', // Less than\n 'le', // Less than or equal to\n 'gt', // Greater than\n 'ge', // Greater than or equal to\n\n // Logical Operators\n 'and', // Logical AND\n 'or', // Logical OR\n 'not', // Logical NOT\n\n // Grouping\n '(', // Left parenthesis\n ')', // Right parenthesis\n\n // Other\n 'in', // Value in list\n 'has', // Has flag (for enum flags)\n]);\n\nexport type ODataFilterOperator = z.infer;\n\n/**\n * OData Filter Function\n * \n * Standard functions available in OData filter expressions.\n */\nexport const ODataFilterFunctionSchema = z.enum([\n // String Functions\n 'contains', // contains(field, 'value')\n 'startswith', // startswith(field, 'value')\n 'endswith', // endswith(field, 'value')\n 'length', // length(field)\n 'indexof', // indexof(field, 'substring')\n 'substring', // substring(field, start, length)\n 'tolower', // tolower(field)\n 'toupper', // toupper(field)\n 'trim', // trim(field)\n 'concat', // concat(field1, field2)\n\n // Date/Time Functions\n 'year', // year(dateField)\n 'month', // month(dateField)\n 'day', // day(dateField)\n 'hour', // hour(datetimeField)\n 'minute', // minute(datetimeField)\n 'second', // second(datetimeField)\n 'date', // date(datetimeField)\n 'time', // time(datetimeField)\n 'now', // now()\n 'maxdatetime', // maxdatetime()\n 'mindatetime', // mindatetime()\n\n // Math Functions\n 'round', // round(numField)\n 'floor', // floor(numField)\n 'ceiling', // ceiling(numField)\n\n // Type Functions\n 'cast', // cast(field, 'Edm.String')\n 'isof', // isof(field, 'Type')\n\n // Collection Functions\n 'any', // collection/any(d:d/prop eq value)\n 'all', // collection/all(d:d/prop eq value)\n]);\n\nexport type ODataFilterFunction = z.infer;\n\n/**\n * OData Response Schema\n * \n * Standard OData JSON response format.\n */\nexport const ODataResponseSchema = z.object({\n /**\n * OData context URL\n * Describes the payload structure\n */\n '@odata.context': z.string().url().optional().describe('Metadata context URL'),\n\n /**\n * Total count (when $count=true)\n */\n '@odata.count': z.number().int().optional().describe('Total results count'),\n\n /**\n * Next link for pagination\n */\n '@odata.nextLink': z.string().url().optional().describe('Next page URL'),\n\n /**\n * Result array\n */\n value: z.array(z.record(z.string(), z.unknown())).describe('Results array'),\n});\n\nexport type ODataResponse = z.infer;\n\n/**\n * OData Error Response Schema\n * \n * Standard OData error format.\n */\nexport const ODataErrorSchema = z.object({\n error: z.object({\n /**\n * Error code\n */\n code: z.string().describe('Error code'),\n\n /**\n * Error message\n */\n message: z.string().describe('Error message'),\n\n /**\n * Target of the error (field name, etc.)\n */\n target: z.string().optional().describe('Error target'),\n\n /**\n * Additional error details\n */\n details: z.array(z.object({\n code: z.string(),\n message: z.string(),\n target: z.string().optional(),\n })).optional().describe('Error details'),\n\n /**\n * Inner error for debugging\n */\n innererror: z.record(z.string(), z.unknown()).optional().describe('Inner error details'),\n }),\n});\n\nexport type ODataError = z.infer;\n\n/**\n * OData Metadata Configuration\n * \n * Configuration for OData metadata endpoint ($metadata).\n */\nexport const ODataMetadataSchema = z.object({\n /**\n * Service namespace\n */\n namespace: z.string().describe('Service namespace'),\n\n /**\n * Entity types to expose\n */\n entityTypes: z.array(z.object({\n name: z.string().describe('Entity type name'),\n key: z.array(z.string()).describe('Key fields'),\n properties: z.array(z.object({\n name: z.string(),\n type: z.string().describe('OData type (Edm.String, Edm.Int32, etc.)'),\n nullable: z.boolean().default(true),\n })),\n navigationProperties: z.array(z.object({\n name: z.string(),\n type: z.string(),\n partner: z.string().optional(),\n })).optional(),\n })).describe('Entity types'),\n\n /**\n * Entity sets\n */\n entitySets: z.array(z.object({\n name: z.string().describe('Entity set name'),\n entityType: z.string().describe('Entity type'),\n })).describe('Entity sets'),\n});\n\nexport type ODataMetadata = z.infer;\n\n/**\n * Helper functions for OData operations\n */\nexport const OData = {\n /**\n * Build OData query URL\n */\n buildUrl: (baseUrl: string, query: ODataQuery): string => {\n const params = new URLSearchParams();\n\n if (query.$select) {\n params.append('$select', Array.isArray(query.$select) ? query.$select.join(',') : query.$select);\n }\n if (query.$filter) {\n params.append('$filter', query.$filter);\n }\n if (query.$orderby) {\n params.append('$orderby', Array.isArray(query.$orderby) ? query.$orderby.join(',') : query.$orderby);\n }\n if (query.$top !== undefined) {\n params.append('$top', query.$top.toString());\n }\n if (query.$skip !== undefined) {\n params.append('$skip', query.$skip.toString());\n }\n if (query.$expand) {\n params.append('$expand', Array.isArray(query.$expand) ? query.$expand.join(',') : query.$expand);\n }\n if (query.$count !== undefined) {\n params.append('$count', query.$count.toString());\n }\n if (query.$search) {\n params.append('$search', query.$search);\n }\n if (query.$format) {\n params.append('$format', query.$format);\n }\n if (query.$apply) {\n params.append('$apply', query.$apply);\n }\n\n const queryString = params.toString();\n return queryString ? `${baseUrl}?${queryString}` : baseUrl;\n },\n\n /**\n * Create a simple filter expression\n */\n filter: {\n eq: (field: string, value: string | number | boolean) => \n `${field} eq ${typeof value === 'string' ? `'${value}'` : value}`,\n ne: (field: string, value: string | number | boolean) => \n `${field} ne ${typeof value === 'string' ? `'${value}'` : value}`,\n gt: (field: string, value: number) => `${field} gt ${value}`,\n lt: (field: string, value: number) => `${field} lt ${value}`,\n contains: (field: string, value: string) => `contains(${field}, '${value}')`,\n and: (...expressions: string[]) => expressions.join(' and '),\n or: (...expressions: string[]) => expressions.join(' or '),\n },\n} as const;\n\n/**\n * OData Configuration Schema\n * \n * Configuration for enabling OData v4 API endpoint.\n */\nexport const ODataConfigSchema = z.object({\n /** Enable OData endpoint */\n enabled: z.boolean().default(true).describe('Enable OData API'),\n \n /** OData endpoint path */\n path: z.string().default('/odata').describe('OData endpoint path'),\n \n /** Metadata configuration */\n metadata: ODataMetadataSchema.optional().describe('OData metadata configuration'),\n}).passthrough(); // Allow additional properties for flexibility\n\nexport type ODataConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\n\n/**\n * GraphQL Protocol Support\n * \n * GraphQL is a query language for APIs and a runtime for executing those queries.\n * It provides a complete and understandable description of the data in your API,\n * gives clients the power to ask for exactly what they need, and enables powerful\n * developer tools.\n * \n * ## Overview\n * \n * GraphQL provides:\n * - Type-safe schema definition\n * - Precise data fetching (no over/under-fetching)\n * - Introspection and documentation\n * - Real-time subscriptions\n * - Batched queries with DataLoader\n * \n * ## Use Cases\n * \n * 1. **Modern API Development**\n * - Mobile and web applications\n * - Microservices federation\n * - Real-time dashboards\n * \n * 2. **Data Aggregation**\n * - Multi-source data integration\n * - Complex nested queries\n * - Efficient data loading\n * \n * 3. **Developer Experience**\n * - Self-documenting API\n * - Type safety and validation\n * - GraphQL playground\n * \n * @see https://graphql.org/\n * @see https://spec.graphql.org/\n * \n * @example GraphQL Query\n * ```graphql\n * query GetCustomer($id: ID!) {\n * customer(id: $id) {\n * id\n * name\n * email\n * orders(limit: 10, status: \"active\") {\n * id\n * total\n * items {\n * product {\n * name\n * price\n * }\n * }\n * }\n * }\n * }\n * ```\n * \n * @example GraphQL Mutation\n * ```graphql\n * mutation CreateOrder($input: CreateOrderInput!) {\n * createOrder(input: $input) {\n * id\n * orderNumber\n * status\n * }\n * }\n * ```\n */\n\n// ==========================================\n// 1. GraphQL Type System\n// ==========================================\n\n/**\n * GraphQL Scalar Types\n * \n * Built-in scalar types in GraphQL plus custom scalars.\n */\nexport const GraphQLScalarType = z.enum([\n // Built-in GraphQL Scalars\n 'ID',\n 'String',\n 'Int',\n 'Float',\n 'Boolean',\n \n // Extended Scalars (common custom types)\n 'DateTime',\n 'Date',\n 'Time',\n 'JSON',\n 'JSONObject',\n 'Upload',\n 'URL',\n 'Email',\n 'PhoneNumber',\n 'Currency',\n 'Decimal',\n 'BigInt',\n 'Long',\n 'UUID',\n 'Base64',\n 'Void',\n]);\n\nexport type GraphQLScalarType = z.infer;\n\n/**\n * GraphQL Type Configuration\n * \n * Configuration for generating GraphQL types from Object definitions.\n */\nexport const GraphQLTypeConfigSchema = z.object({\n /** Type name in GraphQL schema */\n name: z.string().describe('GraphQL type name (PascalCase recommended)'),\n \n /** Source Object name */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Description for GraphQL schema documentation */\n description: z.string().optional().describe('Type description'),\n \n /** Fields to include/exclude */\n fields: z.object({\n /** Include only these fields (allow list) */\n include: z.array(z.string()).optional().describe('Fields to include'),\n \n /** Exclude these fields (deny list) */\n exclude: z.array(z.string()).optional().describe('Fields to exclude (e.g., sensitive fields)'),\n \n /** Custom field mappings */\n mappings: z.record(z.string(), z.object({\n graphqlName: z.string().optional().describe('Custom GraphQL field name'),\n graphqlType: z.string().optional().describe('Override GraphQL type'),\n description: z.string().optional().describe('Field description'),\n deprecationReason: z.string().optional().describe('Why field is deprecated'),\n nullable: z.boolean().optional().describe('Override nullable'),\n })).optional().describe('Field-level customizations'),\n }).optional().describe('Field configuration'),\n \n /** Interfaces this type implements */\n interfaces: z.array(z.string()).optional().describe('GraphQL interface names'),\n \n /** Whether this is an interface definition */\n isInterface: z.boolean().optional().default(false).describe('Define as GraphQL interface'),\n \n /** Custom directives */\n directives: z.array(z.object({\n name: z.string().describe('Directive name'),\n args: z.record(z.string(), z.unknown()).optional().describe('Directive arguments'),\n })).optional().describe('GraphQL directives'),\n});\n\nexport type GraphQLTypeConfig = z.infer;\nexport type GraphQLTypeConfigInput = z.input;\n\n// ==========================================\n// 2. Query Generation Configuration\n// ==========================================\n\n/**\n * GraphQL Query Configuration\n * \n * Configuration for auto-generating query fields from Objects.\n */\nexport const GraphQLQueryConfigSchema = z.object({\n /** Query name */\n name: z.string().describe('Query field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Query type: single record or list */\n type: z.enum(['get', 'list', 'search']).describe('Query type'),\n \n /** Description */\n description: z.string().optional().describe('Query description'),\n \n /** Input arguments */\n args: z.record(z.string(), z.object({\n type: z.string().describe('GraphQL type (e.g., \"ID!\", \"String\", \"Int\")'),\n description: z.string().optional().describe('Argument description'),\n defaultValue: z.unknown().optional().describe('Default value'),\n })).optional().describe('Query arguments'),\n \n /** Filtering configuration */\n filtering: z.object({\n enabled: z.boolean().default(true).describe('Allow filtering'),\n fields: z.array(z.string()).optional().describe('Filterable fields'),\n operators: z.array(z.enum([\n 'eq', 'ne', 'gt', 'gte', 'lt', 'lte',\n 'in', 'notIn', 'contains', 'startsWith', 'endsWith',\n 'isNull', 'isNotNull',\n ])).optional().describe('Allowed filter operators'),\n }).optional().describe('Filtering capabilities'),\n \n /** Sorting configuration */\n sorting: z.object({\n enabled: z.boolean().default(true).describe('Allow sorting'),\n fields: z.array(z.string()).optional().describe('Sortable fields'),\n defaultSort: z.object({\n field: z.string(),\n direction: z.enum(['ASC', 'DESC']),\n }).optional().describe('Default sort order'),\n }).optional().describe('Sorting capabilities'),\n \n /** Pagination configuration */\n pagination: z.object({\n enabled: z.boolean().default(true).describe('Enable pagination'),\n type: z.enum(['offset', 'cursor', 'relay']).default('offset').describe('Pagination style'),\n defaultLimit: z.number().int().min(1).default(20).describe('Default page size'),\n maxLimit: z.number().int().min(1).default(100).describe('Maximum page size'),\n cursors: z.object({\n field: z.string().default('id').describe('Field to use for cursor pagination'),\n }).optional(),\n }).optional().describe('Pagination configuration'),\n \n /** Field selection */\n fields: z.object({\n /** Always include these fields */\n required: z.array(z.string()).optional().describe('Required fields (always returned)'),\n \n /** Allow selecting these fields */\n selectable: z.array(z.string()).optional().describe('Selectable fields'),\n }).optional().describe('Field selection configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(false).describe('Enable caching'),\n ttl: z.number().int().min(0).optional().describe('Cache TTL in seconds'),\n key: z.string().optional().describe('Cache key template'),\n }).optional().describe('Query caching'),\n});\n\nexport type GraphQLQueryConfig = z.infer;\nexport type GraphQLQueryConfigInput = z.input;\n\n// ==========================================\n// 3. Mutation Generation Configuration\n// ==========================================\n\n/**\n * GraphQL Mutation Configuration\n * \n * Configuration for auto-generating mutation fields from Objects.\n */\nexport const GraphQLMutationConfigSchema = z.object({\n /** Mutation name */\n name: z.string().describe('Mutation field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Mutation type */\n type: z.enum(['create', 'update', 'delete', 'upsert', 'custom']).describe('Mutation type'),\n \n /** Description */\n description: z.string().optional().describe('Mutation description'),\n \n /** Input type configuration */\n input: z.object({\n /** Input type name */\n typeName: z.string().optional().describe('Custom input type name'),\n \n /** Fields to include in input */\n fields: z.object({\n include: z.array(z.string()).optional().describe('Fields to include'),\n exclude: z.array(z.string()).optional().describe('Fields to exclude'),\n required: z.array(z.string()).optional().describe('Required input fields'),\n }).optional().describe('Input field configuration'),\n \n /** Validation */\n validation: z.object({\n enabled: z.boolean().default(true).describe('Enable input validation'),\n rules: z.array(z.string()).optional().describe('Custom validation rules'),\n }).optional().describe('Input validation'),\n }).optional().describe('Input configuration'),\n \n /** Return type configuration */\n output: z.object({\n /** Type of output */\n type: z.enum(['object', 'payload', 'boolean', 'custom']).default('object').describe('Output type'),\n \n /** Include success/error envelope */\n includeEnvelope: z.boolean().optional().default(false).describe('Wrap in success/error payload'),\n \n /** Custom output type */\n customType: z.string().optional().describe('Custom output type name'),\n }).optional().describe('Output configuration'),\n \n /** Transaction handling */\n transaction: z.object({\n enabled: z.boolean().default(true).describe('Use database transaction'),\n isolationLevel: z.enum(['read_uncommitted', 'read_committed', 'repeatable_read', 'serializable']).optional().describe('Transaction isolation level'),\n }).optional().describe('Transaction configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Hooks */\n hooks: z.object({\n before: z.array(z.string()).optional().describe('Pre-mutation hooks'),\n after: z.array(z.string()).optional().describe('Post-mutation hooks'),\n }).optional().describe('Lifecycle hooks'),\n});\n\nexport type GraphQLMutationConfig = z.infer;\nexport type GraphQLMutationConfigInput = z.input;\n\n// ==========================================\n// 4. Subscription Configuration\n// ==========================================\n\n/**\n * GraphQL Subscription Configuration\n * \n * Configuration for real-time GraphQL subscriptions.\n */\nexport const GraphQLSubscriptionConfigSchema = z.object({\n /** Subscription name */\n name: z.string().describe('Subscription field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Subscription trigger events */\n events: z.array(z.enum(['created', 'updated', 'deleted', 'custom'])).describe('Events to subscribe to'),\n \n /** Description */\n description: z.string().optional().describe('Subscription description'),\n \n /** Filtering */\n filter: z.object({\n enabled: z.boolean().default(true).describe('Allow filtering subscriptions'),\n fields: z.array(z.string()).optional().describe('Filterable fields'),\n }).optional().describe('Subscription filtering'),\n \n /** Payload configuration */\n payload: z.object({\n /** Include the modified entity */\n includeEntity: z.boolean().default(true).describe('Include entity in payload'),\n \n /** Include previous values (for updates) */\n includePreviousValues: z.boolean().optional().default(false).describe('Include previous field values'),\n \n /** Include mutation metadata */\n includeMeta: z.boolean().optional().default(true).describe('Include metadata (timestamp, user, etc.)'),\n }).optional().describe('Payload configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Rate limiting for subscriptions */\n rateLimit: z.object({\n enabled: z.boolean().default(true).describe('Enable rate limiting'),\n maxSubscriptionsPerUser: z.number().int().min(1).default(10).describe('Max concurrent subscriptions per user'),\n throttleMs: z.number().int().min(0).optional().describe('Throttle interval in milliseconds'),\n }).optional().describe('Subscription rate limiting'),\n});\n\nexport type GraphQLSubscriptionConfig = z.infer;\nexport type GraphQLSubscriptionConfigInput = z.input;\n\n// ==========================================\n// 5. Resolver Configuration\n// ==========================================\n\n/**\n * GraphQL Resolver Configuration\n * \n * Configuration for custom resolver logic.\n */\nexport const GraphQLResolverConfigSchema = z.object({\n /** Field path (e.g., \"Query.users\", \"Mutation.createUser\") */\n path: z.string().describe('Resolver path (Type.field)'),\n \n /** Resolver implementation type */\n type: z.enum(['datasource', 'computed', 'script', 'proxy']).describe('Resolver implementation type'),\n \n /** Implementation details */\n implementation: z.object({\n /** For datasource type */\n datasource: z.string().optional().describe('Datasource ID'),\n query: z.string().optional().describe('Query/SQL to execute'),\n \n /** For computed type */\n expression: z.string().optional().describe('Computation expression'),\n dependencies: z.array(z.string()).optional().describe('Dependent fields'),\n \n /** For script type */\n script: z.string().optional().describe('Script ID or inline code'),\n \n /** For proxy type */\n url: z.string().optional().describe('Proxy URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).optional().describe('HTTP method'),\n }).optional().describe('Implementation configuration'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(false).describe('Enable resolver caching'),\n ttl: z.number().int().min(0).optional().describe('Cache TTL in seconds'),\n keyArgs: z.array(z.string()).optional().describe('Arguments to include in cache key'),\n }).optional().describe('Resolver caching'),\n});\n\nexport type GraphQLResolverConfig = z.infer;\nexport type GraphQLResolverConfigInput = z.input;\n\n// ==========================================\n// 6. DataLoader Configuration\n// ==========================================\n\n/**\n * GraphQL DataLoader Configuration\n * \n * Configuration for batching and caching with DataLoader pattern.\n * Prevents N+1 query problems in GraphQL.\n */\nexport const GraphQLDataLoaderConfigSchema = z.object({\n /** Loader name */\n name: z.string().describe('DataLoader name'),\n \n /** Source Object or datasource */\n source: z.string().describe('Source object or datasource'),\n \n /** Batch function configuration */\n batchFunction: z.object({\n /** Type of batch operation */\n type: z.enum(['findByIds', 'query', 'script', 'custom']).describe('Batch function type'),\n \n /** For findByIds */\n keyField: z.string().optional().describe('Field to batch on (e.g., \"id\")'),\n \n /** For query */\n query: z.string().optional().describe('Query template'),\n \n /** For script */\n script: z.string().optional().describe('Script ID'),\n \n /** Maximum batch size */\n maxBatchSize: z.number().int().min(1).optional().default(100).describe('Maximum batch size'),\n }).describe('Batch function configuration'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable per-request caching'),\n \n /** Cache key function */\n keyFn: z.string().optional().describe('Custom cache key function'),\n }).optional().describe('DataLoader caching'),\n \n /** Options */\n options: z.object({\n /** Batch multiple requests in single tick */\n batch: z.boolean().default(true).describe('Enable batching'),\n \n /** Cache loaded values */\n cache: z.boolean().default(true).describe('Enable caching'),\n \n /** Maximum cache size */\n maxCacheSize: z.number().int().min(0).optional().describe('Max cache entries'),\n }).optional().describe('DataLoader options'),\n});\n\nexport type GraphQLDataLoaderConfig = z.infer;\nexport type GraphQLDataLoaderConfigInput = z.input;\n\n// ==========================================\n// 7. GraphQL Directive Schema\n// ==========================================\n\n/**\n * GraphQL Directive Location\n * \n * Where a directive can be used in the schema.\n */\nexport const GraphQLDirectiveLocation = z.enum([\n // Executable Directive Locations\n 'QUERY',\n 'MUTATION',\n 'SUBSCRIPTION',\n 'FIELD',\n 'FRAGMENT_DEFINITION',\n 'FRAGMENT_SPREAD',\n 'INLINE_FRAGMENT',\n 'VARIABLE_DEFINITION',\n \n // Type System Directive Locations\n 'SCHEMA',\n 'SCALAR',\n 'OBJECT',\n 'FIELD_DEFINITION',\n 'ARGUMENT_DEFINITION',\n 'INTERFACE',\n 'UNION',\n 'ENUM',\n 'ENUM_VALUE',\n 'INPUT_OBJECT',\n 'INPUT_FIELD_DEFINITION',\n]);\n\nexport type GraphQLDirectiveLocation = z.infer;\n\n/**\n * GraphQL Directive Configuration\n * \n * Custom directives for schema metadata and behavior.\n */\nexport const GraphQLDirectiveConfigSchema = z.object({\n /** Directive name */\n name: z.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe('Directive name (camelCase)'),\n \n /** Description */\n description: z.string().optional().describe('Directive description'),\n \n /** Where directive can be used */\n locations: z.array(GraphQLDirectiveLocation).describe('Directive locations'),\n \n /** Arguments */\n args: z.record(z.string(), z.object({\n type: z.string().describe('Argument type'),\n description: z.string().optional().describe('Argument description'),\n defaultValue: z.unknown().optional().describe('Default value'),\n })).optional().describe('Directive arguments'),\n \n /** Is repeatable */\n repeatable: z.boolean().optional().default(false).describe('Can be applied multiple times'),\n \n /** Implementation */\n implementation: z.object({\n /** Directive behavior type */\n type: z.enum(['auth', 'validation', 'transform', 'cache', 'deprecation', 'custom']).describe('Directive type'),\n \n /** Handler function */\n handler: z.string().optional().describe('Handler function name or script'),\n }).optional().describe('Directive implementation'),\n});\n\nexport type GraphQLDirectiveConfig = z.infer;\nexport type GraphQLDirectiveConfigInput = z.input;\n\n// ==========================================\n// 8. GraphQL Security - Query Depth Limiting\n// ==========================================\n\n/**\n * Query Depth Limiting Configuration\n * \n * Prevents deeply nested queries that could cause performance issues.\n */\nexport const GraphQLQueryDepthLimitSchema = z.object({\n /** Enable depth limiting */\n enabled: z.boolean().default(true).describe('Enable query depth limiting'),\n \n /** Maximum allowed depth */\n maxDepth: z.number().int().min(1).default(10).describe('Maximum query depth'),\n \n /** Fields to ignore in depth calculation */\n ignoreFields: z.array(z.string()).optional().describe('Fields excluded from depth calculation'),\n \n /** Callback on depth exceeded */\n onDepthExceeded: z.enum(['reject', 'log', 'warn']).default('reject').describe('Action when depth exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for depth violations'),\n});\n\nexport type GraphQLQueryDepthLimit = z.infer;\nexport type GraphQLQueryDepthLimitInput = z.input;\n\n// ==========================================\n// 9. GraphQL Security - Query Complexity\n// ==========================================\n\n/**\n * Query Complexity Calculation Configuration\n * \n * Assigns complexity scores to fields and limits total query complexity.\n * Prevents expensive queries from overloading the server.\n */\nexport const GraphQLQueryComplexitySchema = z.object({\n /** Enable complexity limiting */\n enabled: z.boolean().default(true).describe('Enable query complexity limiting'),\n \n /** Maximum allowed complexity score */\n maxComplexity: z.number().int().min(1).default(1000).describe('Maximum query complexity'),\n \n /** Default field complexity */\n defaultFieldComplexity: z.number().int().min(0).default(1).describe('Default complexity per field'),\n \n /** Field-specific complexity scores */\n fieldComplexity: z.record(z.string(), z.union([\n z.number().int().min(0),\n z.object({\n /** Base complexity */\n base: z.number().int().min(0).describe('Base complexity'),\n \n /** Multiplier based on arguments */\n multiplier: z.string().optional().describe('Argument multiplier (e.g., \"limit\")'),\n \n /** Custom complexity calculation */\n calculator: z.string().optional().describe('Custom calculator function'),\n }),\n ])).optional().describe('Per-field complexity configuration'),\n \n /** List multiplier */\n listMultiplier: z.number().min(0).default(10).describe('Multiplier for list fields'),\n \n /** Callback on complexity exceeded */\n onComplexityExceeded: z.enum(['reject', 'log', 'warn']).default('reject').describe('Action when complexity exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for complexity violations'),\n});\n\nexport type GraphQLQueryComplexity = z.infer;\nexport type GraphQLQueryComplexityInput = z.input;\n\n// ==========================================\n// 10. GraphQL Security - Rate Limiting\n// ==========================================\n\n/**\n * GraphQL Rate Limiting Configuration\n * \n * Rate limiting for GraphQL operations.\n */\nexport const GraphQLRateLimitSchema = z.object({\n /** Enable rate limiting */\n enabled: z.boolean().default(true).describe('Enable rate limiting'),\n \n /** Rate limit strategy */\n strategy: z.enum(['token_bucket', 'fixed_window', 'sliding_window', 'cost_based']).default('token_bucket').describe('Rate limiting strategy'),\n \n /** Global rate limits */\n global: z.object({\n /** Requests per time window */\n maxRequests: z.number().int().min(1).default(1000).describe('Maximum requests per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n }).optional().describe('Global rate limits'),\n \n /** Per-user rate limits */\n perUser: z.object({\n /** Requests per time window */\n maxRequests: z.number().int().min(1).default(100).describe('Maximum requests per user per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n }).optional().describe('Per-user rate limits'),\n \n /** Cost-based rate limiting */\n costBased: z.object({\n /** Enable cost-based limiting */\n enabled: z.boolean().default(false).describe('Enable cost-based rate limiting'),\n \n /** Maximum cost per time window */\n maxCost: z.number().int().min(1).default(10000).describe('Maximum cost per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n \n /** Use complexity as cost */\n useComplexityAsCost: z.boolean().default(true).describe('Use query complexity as cost'),\n }).optional().describe('Cost-based rate limiting'),\n \n /** Operation-specific limits */\n operations: z.record(z.string(), z.object({\n maxRequests: z.number().int().min(1).describe('Max requests for this operation'),\n windowMs: z.number().int().min(1000).describe('Time window'),\n })).optional().describe('Per-operation rate limits'),\n \n /** Callback on limit exceeded */\n onLimitExceeded: z.enum(['reject', 'queue', 'log']).default('reject').describe('Action when rate limit exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for rate limit violations'),\n \n /** Headers to include in response */\n includeHeaders: z.boolean().default(true).describe('Include rate limit headers in response'),\n});\n\nexport type GraphQLRateLimit = z.infer;\nexport type GraphQLRateLimitInput = z.input;\n\n// ==========================================\n// 11. GraphQL Security - Persisted Queries\n// ==========================================\n\n/**\n * Persisted Queries Configuration\n * \n * Only allow pre-registered queries to execute (allow list approach).\n * Improves security and performance.\n */\nexport const GraphQLPersistedQuerySchema = z.object({\n /** Enable persisted queries */\n enabled: z.boolean().default(false).describe('Enable persisted queries'),\n \n /** Enforcement mode */\n mode: z.enum(['optional', 'required']).default('optional').describe('Persisted query mode (optional: allow both, required: only persisted)'),\n \n /** Query store configuration */\n store: z.object({\n /** Store type */\n type: z.enum(['memory', 'redis', 'database', 'file']).default('memory').describe('Query store type'),\n \n /** Store connection string */\n connection: z.string().optional().describe('Store connection string or path'),\n \n /** TTL for cached queries */\n ttl: z.number().int().min(0).optional().describe('TTL in seconds for stored queries'),\n }).optional().describe('Query store configuration'),\n \n /** Automatic Persisted Queries (APQ) */\n apq: z.object({\n /** Enable APQ */\n enabled: z.boolean().default(true).describe('Enable Automatic Persisted Queries'),\n \n /** Hash algorithm */\n hashAlgorithm: z.enum(['sha256', 'sha1', 'md5']).default('sha256').describe('Hash algorithm for query IDs'),\n \n /** Cache control */\n cache: z.object({\n /** Cache TTL */\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n \n /** Max cache size */\n maxSize: z.number().int().min(1).optional().describe('Maximum number of cached queries'),\n }).optional().describe('APQ cache configuration'),\n }).optional().describe('Automatic Persisted Queries configuration'),\n \n /** Query allow list */\n allowlist: z.object({\n /** Enable allow list mode */\n enabled: z.boolean().default(false).describe('Enable query allow list (reject queries not in list)'),\n \n /** Allowed query IDs */\n queries: z.array(z.object({\n id: z.string().describe('Query ID or hash'),\n operation: z.string().optional().describe('Operation name'),\n query: z.string().optional().describe('Query string'),\n })).optional().describe('Allowed queries'),\n \n /** External allow list source */\n source: z.string().optional().describe('External allow list source (file path or URL)'),\n }).optional().describe('Query allow list configuration'),\n \n /** Security */\n security: z.object({\n /** Maximum query size */\n maxQuerySize: z.number().int().min(1).optional().describe('Maximum query string size in bytes'),\n \n /** Reject introspection in production */\n rejectIntrospection: z.boolean().default(false).describe('Reject introspection queries'),\n }).optional().describe('Security configuration'),\n});\n\nexport type GraphQLPersistedQuery = z.infer;\nexport type GraphQLPersistedQueryInput = z.input;\n\n// ==========================================\n// 12. GraphQL Federation\n// ==========================================\n\n/**\n * Federation Entity Key Definition\n * \n * Defines how entities are uniquely identified across subgraphs.\n * Corresponds to the `@key` directive in Apollo Federation.\n * \n * @see https://www.apollographql.com/docs/federation/entities\n */\nexport const FederationEntityKeySchema = z.object({\n /** Fields composing the key (e.g., \"id\" or \"sku packageId\") */\n fields: z.string().describe('Selection set of fields composing the entity key'),\n\n /** Whether this key can be used for resolution across subgraphs */\n resolvable: z.boolean().optional().default(true).describe('Whether entities can be resolved from this subgraph'),\n});\n\nexport type FederationEntityKey = z.infer;\n\n/**\n * Federation External Field\n * \n * Marks a field as owned by another subgraph (`@external`).\n */\nexport const FederationExternalFieldSchema = z.object({\n /** Field name */\n field: z.string().describe('Field name marked as external'),\n\n /** The subgraph that owns this field */\n ownerSubgraph: z.string().optional().describe('Subgraph that owns this field'),\n});\n\nexport type FederationExternalField = z.infer;\n\n/**\n * Federation Requires Directive\n * \n * Specifies fields that must be fetched from other subgraphs\n * before resolving a computed field.\n * Corresponds to the `@requires` directive in Apollo Federation.\n */\nexport const FederationRequiresSchema = z.object({\n /** The field that has this requirement */\n field: z.string().describe('Field with the requirement'),\n\n /** Selection set of external fields required for resolution */\n fields: z.string().describe('Selection set of required fields (e.g., \"price weight\")'),\n});\n\nexport type FederationRequires = z.infer;\n\n/**\n * Federation Provides Directive\n * \n * Indicates that a field resolution provides additional fields\n * of a returned entity type.\n * Corresponds to the `@provides` directive in Apollo Federation.\n */\nexport const FederationProvidesSchema = z.object({\n /** The field that provides additional data */\n field: z.string().describe('Field that provides additional entity fields'),\n\n /** Selection set of fields provided during resolution */\n fields: z.string().describe('Selection set of provided fields (e.g., \"name price\")'),\n});\n\nexport type FederationProvides = z.infer;\n\n/**\n * Federation Entity Configuration\n * \n * Configures a type as a federated entity that can be referenced\n * and extended across multiple subgraphs.\n */\nexport const FederationEntitySchema = z.object({\n /** Type/Object name */\n typeName: z.string().describe('GraphQL type name for this entity'),\n\n /** Entity keys (`@key` directive) */\n keys: z.array(FederationEntityKeySchema).min(1).describe('Entity key definitions'),\n\n /** External fields (`@external`) */\n externalFields: z.array(FederationExternalFieldSchema).optional().describe('Fields owned by other subgraphs'),\n\n /** Requires directives (`@requires`) */\n requires: z.array(FederationRequiresSchema).optional().describe('Required external fields for computed fields'),\n\n /** Provides directives (`@provides`) */\n provides: z.array(FederationProvidesSchema).optional().describe('Fields provided during resolution'),\n\n /** Whether this subgraph owns this entity */\n owner: z.boolean().optional().default(false).describe('Whether this subgraph is the owner of this entity'),\n});\n\nexport type FederationEntity = z.infer;\n\n/**\n * Subgraph Configuration\n * \n * Configuration for an individual subgraph in a federated architecture.\n */\nexport const SubgraphConfigSchema = z.object({\n /** Subgraph name */\n name: z.string().describe('Unique subgraph identifier'),\n\n /** Subgraph URL */\n url: z.string().describe('Subgraph endpoint URL'),\n\n /** Schema source */\n schemaSource: z.enum(['introspection', 'file', 'registry']).default('introspection').describe('How to obtain the subgraph schema'),\n\n /** Schema file path (when schemaSource is \"file\") */\n schemaPath: z.string().optional().describe('Path to schema file (SDL format)'),\n\n /** Federated entities defined by this subgraph */\n entities: z.array(FederationEntitySchema).optional().describe('Entity definitions for this subgraph'),\n\n /** Health check endpoint */\n healthCheck: z.object({\n enabled: z.boolean().default(true).describe('Enable health checking'),\n path: z.string().default('/health').describe('Health check endpoint path'),\n intervalMs: z.number().int().min(1000).default(30000).describe('Health check interval in milliseconds'),\n }).optional().describe('Subgraph health check configuration'),\n\n /** Request headers to forward */\n forwardHeaders: z.array(z.string()).optional().describe('HTTP headers to forward to this subgraph'),\n});\n\nexport type SubgraphConfig = z.infer;\nexport type SubgraphConfigInput = z.input;\n\n/**\n * Federation Gateway Configuration\n * \n * Root-level gateway configuration for Apollo Federation or similar.\n * Manages query planning, routing, and composition across subgraphs.\n */\nexport const FederationGatewaySchema = z.object({\n /** Enable federation mode */\n enabled: z.boolean().default(false).describe('Enable GraphQL Federation gateway mode'),\n\n /** Federation specification version */\n version: z.enum(['v1', 'v2']).default('v2').describe('Federation specification version'),\n\n /** Registered subgraphs */\n subgraphs: z.array(SubgraphConfigSchema).describe('Subgraph configurations'),\n\n /** Service discovery */\n serviceDiscovery: z.object({\n /** Discovery mode */\n type: z.enum(['static', 'dns', 'consul', 'kubernetes']).default('static').describe('Service discovery method'),\n\n /** Poll interval for dynamic discovery */\n pollIntervalMs: z.number().int().min(1000).optional().describe('Discovery poll interval in milliseconds'),\n\n /** Kubernetes namespace (when type is \"kubernetes\") */\n namespace: z.string().optional().describe('Kubernetes namespace for subgraph discovery'),\n }).optional().describe('Service discovery configuration'),\n\n /** Query planning */\n queryPlanning: z.object({\n /** Execution strategy */\n strategy: z.enum(['parallel', 'sequential', 'adaptive']).default('parallel').describe('Query execution strategy across subgraphs'),\n\n /** Maximum query depth across subgraphs */\n maxDepth: z.number().int().min(1).optional().describe('Max query depth in federated execution'),\n\n /** Dry-run mode for debugging query plans */\n dryRun: z.boolean().optional().default(false).describe('Log query plans without executing'),\n }).optional().describe('Query planning configuration'),\n\n /** Schema composition settings */\n composition: z.object({\n /** How schema conflicts are resolved */\n conflictResolution: z.enum(['error', 'first_wins', 'last_wins']).default('error').describe('Strategy for resolving schema conflicts'),\n\n /** Whether to validate composed schema */\n validate: z.boolean().default(true).describe('Validate composed supergraph schema'),\n }).optional().describe('Schema composition configuration'),\n\n /** Gateway-level error handling */\n errorHandling: z.object({\n /** Whether to include subgraph names in errors */\n includeSubgraphName: z.boolean().default(false).describe('Include subgraph name in error responses'),\n\n /** Partial error behavior */\n partialErrors: z.enum(['propagate', 'nullify', 'reject']).default('propagate').describe('Behavior when a subgraph returns partial errors'),\n }).optional().describe('Error handling configuration'),\n});\n\nexport type FederationGateway = z.infer;\nexport type FederationGatewayInput = z.input;\n\n// ==========================================\n// 13. Complete GraphQL Configuration\n// ==========================================\n\n/**\n * Complete GraphQL Configuration\n * \n * Root configuration for GraphQL API generation and security.\n */\nexport const GraphQLConfigSchema = z.object({\n /** Enable GraphQL API */\n enabled: z.boolean().default(true).describe('Enable GraphQL API'),\n \n /** GraphQL endpoint path */\n path: z.string().default('/graphql').describe('GraphQL endpoint path'),\n \n /** GraphQL Playground */\n playground: z.object({\n enabled: z.boolean().default(true).describe('Enable GraphQL Playground'),\n path: z.string().default('/playground').describe('Playground path'),\n }).optional().describe('GraphQL Playground configuration'),\n \n /** Schema generation */\n schema: z.object({\n /** Auto-generate types from Objects */\n autoGenerateTypes: z.boolean().default(true).describe('Auto-generate types from Objects'),\n \n /** Type configurations */\n types: z.array(GraphQLTypeConfigSchema).optional().describe('Type configurations'),\n \n /** Query configurations */\n queries: z.array(GraphQLQueryConfigSchema).optional().describe('Query configurations'),\n \n /** Mutation configurations */\n mutations: z.array(GraphQLMutationConfigSchema).optional().describe('Mutation configurations'),\n \n /** Subscription configurations */\n subscriptions: z.array(GraphQLSubscriptionConfigSchema).optional().describe('Subscription configurations'),\n \n /** Custom resolvers */\n resolvers: z.array(GraphQLResolverConfigSchema).optional().describe('Custom resolver configurations'),\n \n /** Custom directives */\n directives: z.array(GraphQLDirectiveConfigSchema).optional().describe('Custom directive configurations'),\n }).optional().describe('Schema generation configuration'),\n \n /** DataLoader configurations */\n dataLoaders: z.array(GraphQLDataLoaderConfigSchema).optional().describe('DataLoader configurations'),\n \n /** Security configuration */\n security: z.object({\n /** Query depth limiting */\n depthLimit: GraphQLQueryDepthLimitSchema.optional().describe('Query depth limiting'),\n \n /** Query complexity */\n complexity: GraphQLQueryComplexitySchema.optional().describe('Query complexity calculation'),\n \n /** Rate limiting */\n rateLimit: GraphQLRateLimitSchema.optional().describe('Rate limiting'),\n \n /** Persisted queries */\n persistedQueries: GraphQLPersistedQuerySchema.optional().describe('Persisted queries'),\n }).optional().describe('Security configuration'),\n\n /** Federation configuration */\n federation: FederationGatewaySchema.optional().describe('GraphQL Federation gateway configuration'),\n});\n\nexport const GraphQLConfig = Object.assign(GraphQLConfigSchema, {\n create: >(config: T) => config,\n});\n\nexport type GraphQLConfig = z.infer;\nexport type GraphQLConfigInput = z.input;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to map ObjectQL field type to GraphQL scalar type\n */\nexport const mapFieldTypeToGraphQL = (fieldType: z.infer): string => {\n const mapping: Record = {\n // Core Text\n 'text': 'String',\n 'textarea': 'String',\n 'email': 'Email',\n 'url': 'URL',\n 'phone': 'PhoneNumber',\n 'password': 'String',\n \n // Rich Content\n 'markdown': 'String',\n 'html': 'String',\n 'richtext': 'String',\n \n // Numbers\n 'number': 'Float',\n 'currency': 'Currency',\n 'percent': 'Float',\n \n // Date & Time\n 'date': 'Date',\n 'datetime': 'DateTime',\n 'time': 'Time',\n \n // Logic\n 'boolean': 'Boolean',\n 'toggle': 'Boolean',\n \n // Selection\n 'select': 'String',\n 'multiselect': '[String]',\n 'radio': 'String',\n 'checkboxes': '[String]',\n \n // Relational\n 'lookup': 'ID',\n 'master_detail': 'ID',\n 'tree': 'ID',\n \n // Media\n 'image': 'URL',\n 'file': 'URL',\n 'avatar': 'URL',\n 'video': 'URL',\n 'audio': 'URL',\n \n // Calculated\n 'formula': 'String',\n 'summary': 'Float',\n 'autonumber': 'String',\n \n // Enhanced Types\n 'location': 'JSONObject',\n 'address': 'JSONObject',\n 'code': 'String',\n 'json': 'JSON',\n 'color': 'String',\n 'rating': 'Float',\n 'slider': 'Float',\n 'signature': 'String',\n 'qrcode': 'String',\n 'progress': 'Float',\n 'tags': '[String]',\n \n // AI/ML\n 'vector': '[Float]',\n };\n \n return mapping[fieldType] || 'String';\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ApiErrorSchema, BaseResponseSchema, RecordDataSchema } from './contract.zod';\n\n/**\n * Batch Operations API\n * \n * Provides efficient bulk data operations with transaction support.\n * Implements P0/P1 requirements for ObjectStack kernel.\n * \n * Features:\n * - Batch create/update/delete operations\n * - Atomic transaction support (all-or-none)\n * - Partial success handling\n * - Detailed error reporting per record\n * \n * Industry alignment: Salesforce Bulk API, Microsoft Dynamics Bulk Operations\n */\n\n// ==========================================\n// Batch Operation Types\n// ==========================================\n\n/**\n * Batch Operation Type Enum\n * Defines the type of batch operation to perform\n */\nexport const BatchOperationType = z.enum([\n 'create', // Batch insert\n 'update', // Batch update\n 'upsert', // Batch upsert (insert or update based on external ID)\n 'delete', // Batch delete\n]);\n\nexport type BatchOperationType = z.infer;\n\n// ==========================================\n// Batch Request Schemas\n// ==========================================\n\n/**\n * Batch Record Schema\n * Individual record in a batch operation\n */\nexport const BatchRecordSchema = z.object({\n id: z.string().optional().describe('Record ID (required for update/delete)'),\n data: RecordDataSchema.optional().describe('Record data (required for create/update/upsert)'),\n externalId: z.string().optional().describe('External ID for upsert matching'),\n});\n\nexport type BatchRecord = z.infer;\n\n/**\n * Batch Operation Options Schema\n * Configuration options for batch operations\n */\nexport const BatchOptionsSchema = z.object({\n atomic: z.boolean().optional().default(true).describe('If true, rollback entire batch on any failure (transaction mode)'),\n returnRecords: z.boolean().optional().default(false).describe('If true, return full record data in response'),\n continueOnError: z.boolean().optional().default(false).describe('If true (and atomic=false), continue processing remaining records after errors'),\n validateOnly: z.boolean().optional().default(false).describe('If true, validate records without persisting changes (dry-run mode)'),\n});\n\nexport type BatchOptions = z.infer;\n\n/**\n * Batch Update Request Schema\n * Request payload for batch update operations\n * \n * @example\n * // POST /api/v1/data/{object}/batch\n * {\n * \"operation\": \"update\",\n * \"records\": [\n * { \"id\": \"1\", \"data\": { \"name\": \"Updated Name 1\", \"status\": \"active\" } },\n * { \"id\": \"2\", \"data\": { \"name\": \"Updated Name 2\", \"status\": \"active\" } }\n * ],\n * \"options\": {\n * \"atomic\": true,\n * \"returnRecords\": true\n * }\n * }\n */\nexport const BatchUpdateRequestSchema = z.object({\n operation: BatchOperationType.describe('Type of batch operation'),\n records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to process (max 200 per batch)'),\n options: BatchOptionsSchema.optional().describe('Batch operation options'),\n});\n\nexport type BatchUpdateRequest = z.input;\n\n/**\n * Simplified Batch Update Request (for updateMany API)\n * Simplified request for batch updates without operation field\n * \n * @example\n * // POST /api/v1/data/{object}/updateMany\n * {\n * \"records\": [\n * { \"id\": \"1\", \"data\": { \"name\": \"Updated Name 1\" } },\n * { \"id\": \"2\", \"data\": { \"name\": \"Updated Name 2\" } }\n * ],\n * \"options\": { \"atomic\": true }\n * }\n */\nexport const UpdateManyRequestSchema = z.object({\n records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to update (max 200 per batch)'),\n options: BatchOptionsSchema.optional().describe('Update options'),\n});\n\nexport type UpdateManyRequest = z.input;\n\n// ==========================================\n// Batch Response Schemas\n// ==========================================\n\n/**\n * Batch Operation Result Schema\n * Result for a single record in a batch operation\n */\nexport const BatchOperationResultSchema = z.object({\n id: z.string().optional().describe('Record ID if operation succeeded'),\n success: z.boolean().describe('Whether this record was processed successfully'),\n errors: z.array(ApiErrorSchema).optional().describe('Array of errors if operation failed'),\n data: RecordDataSchema.optional().describe('Full record data (if returnRecords=true)'),\n index: z.number().optional().describe('Index of the record in the request array'),\n});\n\nexport type BatchOperationResult = z.infer;\n\n/**\n * Batch Update Response Schema\n * Response payload for batch operations\n * \n * @example Success Response\n * {\n * \"success\": true,\n * \"operation\": \"update\",\n * \"total\": 2,\n * \"succeeded\": 2,\n * \"failed\": 0,\n * \"results\": [\n * { \"id\": \"1\", \"success\": true, \"index\": 0 },\n * { \"id\": \"2\", \"success\": true, \"index\": 1 }\n * ],\n * \"meta\": {\n * \"timestamp\": \"2026-01-29T12:00:00Z\",\n * \"duration\": 150\n * }\n * }\n * \n * @example Partial Success Response (atomic=false)\n * {\n * \"success\": false,\n * \"operation\": \"update\",\n * \"total\": 2,\n * \"succeeded\": 1,\n * \"failed\": 1,\n * \"results\": [\n * { \"id\": \"1\", \"success\": true, \"index\": 0 },\n * { \n * \"success\": false, \n * \"index\": 1,\n * \"errors\": [{ \"code\": \"validation_error\", \"message\": \"Invalid email format\" }]\n * }\n * ],\n * \"meta\": {\n * \"timestamp\": \"2026-01-29T12:00:00Z\"\n * }\n * }\n */\nexport const BatchUpdateResponseSchema = BaseResponseSchema.extend({\n operation: BatchOperationType.optional().describe('Operation type that was performed'),\n total: z.number().describe('Total number of records in the batch'),\n succeeded: z.number().describe('Number of records that succeeded'),\n failed: z.number().describe('Number of records that failed'),\n results: z.array(BatchOperationResultSchema).describe('Detailed results for each record'),\n});\n\nexport type BatchUpdateResponse = z.infer;\n\n// ==========================================\n// Batch Delete Schemas\n// ==========================================\n\n/**\n * Batch Delete Request Schema\n * Simplified request for batch delete operations\n * \n * @example\n * // POST /api/v1/data/{object}/deleteMany\n * {\n * \"ids\": [\"1\", \"2\", \"3\"],\n * \"options\": { \"atomic\": true }\n * }\n */\nexport const DeleteManyRequestSchema = z.object({\n ids: z.array(z.string()).min(1).max(200).describe('Array of record IDs to delete (max 200)'),\n options: BatchOptionsSchema.optional().describe('Delete options'),\n});\n\nexport type DeleteManyRequest = z.infer;\n\n// ==========================================\n// API Contract Exports\n// ==========================================\n\n/**\n * Batch API Contracts\n * Standardized contracts for batch operations\n */\nexport const BatchApiContracts = {\n batchOperation: {\n input: BatchUpdateRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n updateMany: {\n input: UpdateManyRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n deleteMany: {\n input: DeleteManyRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n};\n\n/**\n * Batch Configuration Schema\n * \n * Configuration for enabling batch operations API.\n */\nexport const BatchConfigSchema = z.object({\n /** Enable batch operations */\n enabled: z.boolean().default(true).describe('Enable batch operations'),\n \n /** Maximum records per batch */\n maxRecordsPerBatch: z.number().int().min(1).max(1000).default(200).describe('Maximum records per batch'),\n \n /** Default options */\n defaultOptions: BatchOptionsSchema.optional().describe('Default batch options'),\n}).passthrough(); // Allow additional properties\n\nexport type BatchConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * HTTP Metadata Cache Protocol\n * \n * Implements efficient HTTP-level metadata caching with ETag support.\n * Implements P0 requirement for ObjectStack kernel.\n * \n * ## Caching in ObjectStack\n * \n * **HTTP Cache (`api/http-cache.zod.ts`) - This File**\n * - **Purpose**: Cache API responses at HTTP protocol level\n * - **Technologies**: HTTP headers (ETag, Last-Modified, Cache-Control), CDN\n * - **Configuration**: Cache-Control headers, validation tokens\n * - **Use case**: Reduce API response time for repeated metadata requests\n * - **Scope**: HTTP layer, client-server communication\n * \n * **Application Cache (`system/cache.zod.ts`)**\n * - **Purpose**: Cache computed data, query results, aggregations\n * - **Technologies**: Redis, Memcached, in-memory LRU\n * - **Configuration**: TTL, eviction policies, cache warming\n * - **Use case**: Cache expensive database queries, computed values\n * - **Scope**: Application layer, server-side data storage\n * \n * ## Features\n * - ETag-based conditional requests (HTTP 304 Not Modified)\n * - Cache-Control directives\n * - Metadata versioning\n * - Selective cache invalidation\n * \n * Industry alignment: HTTP Caching (RFC 7234), Salesforce Metadata API\n * \n * @see ../../system/cache.zod.ts for application-level caching\n */\n\n// ==========================================\n// Cache Control Headers\n// ==========================================\n\n/**\n * Cache Control Directive Enum\n * Standard HTTP cache control directives\n */\nexport const CacheDirective = z.enum([\n 'public', // Cacheable by any cache\n 'private', // Cacheable only by user-agent\n 'no-cache', // Must revalidate with server\n 'no-store', // Never cache\n 'must-revalidate', // Must revalidate stale responses\n 'max-age', // Maximum cache age in seconds\n]);\n\nexport type CacheDirective = z.infer;\n\n/**\n * Cache Control Schema\n * HTTP cache control configuration\n * \n * @example\n * {\n * \"directives\": [\"public\", \"max-age\"],\n * \"maxAge\": 3600,\n * \"staleWhileRevalidate\": 86400\n * }\n */\nexport const CacheControlSchema = z.object({\n directives: z.array(CacheDirective).describe('Cache control directives'),\n maxAge: z.number().optional().describe('Maximum cache age in seconds'),\n staleWhileRevalidate: z.number().optional().describe('Allow serving stale content while revalidating (seconds)'),\n staleIfError: z.number().optional().describe('Allow serving stale content on error (seconds)'),\n});\n\nexport type CacheControl = z.infer;\n\n// ==========================================\n// ETag Support\n// ==========================================\n\n/**\n * ETag Schema\n * Entity tag for cache validation\n * \n * ETags can be:\n * - Strong: Exact match required (e.g., \"686897696a7c876b7e\")\n * - Weak: Semantic equivalence (e.g., W/\"686897696a7c876b7e\")\n */\nexport const ETagSchema = z.object({\n value: z.string().describe('ETag value (hash or version identifier)'),\n weak: z.boolean().optional().default(false).describe('Whether this is a weak ETag'),\n});\n\nexport type ETag = z.infer;\n\n// ==========================================\n// Metadata Cache Request\n// ==========================================\n\n/**\n * Metadata Cache Request Schema\n * Request with cache validation headers\n * \n * @example\n * // GET /api/v1/metadata/objects/account\n * // Headers:\n * // If-None-Match: \"686897696a7c876b7e\"\n * // If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT\n */\nexport const MetadataCacheRequestSchema = z.object({\n ifNoneMatch: z.string().optional().describe('ETag value for conditional request (If-None-Match header)'),\n ifModifiedSince: z.string().datetime().optional().describe('Timestamp for conditional request (If-Modified-Since header)'),\n cacheControl: CacheControlSchema.optional().describe('Client cache control preferences'),\n});\n\nexport type MetadataCacheRequest = z.infer;\n\n// ==========================================\n// Metadata Cache Response\n// ==========================================\n\n/**\n * Metadata Cache Response Schema\n * Response with cache control headers\n * \n * @example Success Response (200 OK)\n * {\n * \"data\": { \"object\": \"account\" },\n * \"etag\": {\n * \"value\": \"686897696a7c876b7e\",\n * \"weak\": false\n * },\n * \"lastModified\": \"2026-01-29T12:00:00Z\",\n * \"cacheControl\": {\n * \"directives\": [\"public\", \"max-age\"],\n * \"maxAge\": 3600\n * }\n * }\n * \n * @example Not Modified Response (304 Not Modified)\n * {\n * \"notModified\": true,\n * \"etag\": {\n * \"value\": \"686897696a7c876b7e\"\n * }\n * }\n */\nexport const MetadataCacheResponseSchema = z.object({\n data: z.unknown().optional().describe('Metadata payload (omitted for 304 Not Modified)'),\n etag: ETagSchema.optional().describe('ETag for this resource version'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n cacheControl: CacheControlSchema.optional().describe('Cache control directives'),\n notModified: z.boolean().optional().default(false).describe('True if resource has not been modified (304 response)'),\n version: z.string().optional().describe('Metadata version identifier'),\n});\n\nexport type MetadataCacheResponse = z.infer;\n\n// ==========================================\n// Metadata Cache Invalidation\n// ==========================================\n\n/**\n * Cache Invalidation Target Enum\n * Specifies what to invalidate\n */\nexport const CacheInvalidationTarget = z.enum([\n 'all', // Invalidate all cached metadata\n 'object', // Invalidate specific object metadata\n 'field', // Invalidate specific field metadata\n 'permission', // Invalidate permission metadata\n 'layout', // Invalidate layout metadata\n 'custom', // Custom invalidation pattern\n]);\n\nexport type CacheInvalidationTarget = z.infer;\n\n/**\n * Cache Invalidation Request Schema\n * Request to invalidate cached metadata\n * \n * @example\n * // POST /api/v1/metadata/cache/invalidate\n * {\n * \"target\": \"object\",\n * \"identifiers\": [\"account\", \"contact\"],\n * \"cascade\": true\n * }\n */\nexport const CacheInvalidationRequestSchema = z.object({\n target: CacheInvalidationTarget.describe('What to invalidate'),\n identifiers: z.array(z.string()).optional().describe('Specific resources to invalidate (e.g., object names)'),\n cascade: z.boolean().optional().default(false).describe('If true, invalidate dependent resources'),\n pattern: z.string().optional().describe('Pattern for custom invalidation (supports wildcards)'),\n});\n\nexport type CacheInvalidationRequest = z.infer;\n\n/**\n * Cache Invalidation Response Schema\n * Response for cache invalidation\n * \n * @example\n * {\n * \"success\": true,\n * \"invalidated\": 5,\n * \"targets\": [\"account\", \"contact\", \"opportunity\"]\n * }\n */\nexport const CacheInvalidationResponseSchema = z.object({\n success: z.boolean().describe('Whether invalidation succeeded'),\n invalidated: z.number().describe('Number of cache entries invalidated'),\n targets: z.array(z.string()).optional().describe('List of invalidated resources'),\n});\n\nexport type CacheInvalidationResponse = z.infer;\n\n// ==========================================\n// Metadata Cache API Methods\n// ==========================================\n\n/**\n * Metadata Cache API Client Interface\n * \n * @example Usage\n * // Get metadata with cache support\n * const response = await client.meta.getCached('account', {\n * ifNoneMatch: '\"686897696a7c876b7e\"'\n * });\n * \n * if (response.notModified) {\n * // Use cached version\n * } else {\n * // Update cache with response.data\n * cache.set('account', response.data, {\n * etag: response.etag?.value,\n * maxAge: response.cacheControl?.maxAge\n * });\n * }\n */\nexport const MetadataCacheApi = {\n getCached: {\n input: MetadataCacheRequestSchema,\n output: MetadataCacheResponseSchema,\n },\n invalidate: {\n input: CacheInvalidationRequestSchema,\n output: CacheInvalidationResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Standardized Error Codes Protocol\n * \n * Implements P0 requirement for ObjectStack kernel.\n * Provides consistent, machine-readable error codes across the platform.\n * \n * Features:\n * - Categorized error codes (validation, authentication, authorization, etc.)\n * - HTTP status code mapping\n * - Localization support\n * - Retry guidance\n * \n * Industry alignment: Google Cloud Errors, AWS Error Codes, Stripe API Errors\n */\n\n// ==========================================\n// Error Code Categories\n// ==========================================\n\n/**\n * Error Category Enum\n * High-level categorization of errors\n */\nexport const ErrorCategory = z.enum([\n 'validation', // Input validation errors (400)\n 'authentication', // Authentication failures (401)\n 'authorization', // Permission denied errors (403)\n 'not_found', // Resource not found (404)\n 'conflict', // Resource conflict (409)\n 'rate_limit', // Rate limiting (429)\n 'server', // Internal server errors (500)\n 'external', // External service errors (502/503)\n 'maintenance', // Planned maintenance (503)\n]);\n\nexport type ErrorCategory = z.infer;\n\n// ==========================================\n// Standard Error Codes\n// ==========================================\n\n/**\n * Standard Error Code Enum\n * Machine-readable error codes for common error scenarios\n */\nexport const StandardErrorCode = z.enum([\n // Validation Errors (400)\n 'validation_error', // Generic validation failure\n 'invalid_field', // Invalid field value\n 'missing_required_field', // Required field missing\n 'invalid_format', // Field format invalid (e.g., email, date)\n 'value_too_long', // Field value exceeds max length\n 'value_too_short', // Field value below min length\n 'value_out_of_range', // Numeric value out of range\n 'invalid_reference', // Invalid foreign key reference\n 'duplicate_value', // Unique constraint violation\n 'invalid_query', // Malformed query syntax\n 'invalid_filter', // Invalid filter expression\n 'invalid_sort', // Invalid sort specification\n 'max_records_exceeded', // Query would return too many records\n \n // Authentication Errors (401)\n 'unauthenticated', // No valid authentication provided\n 'invalid_credentials', // Wrong username/password\n 'expired_token', // Authentication token expired\n 'invalid_token', // Authentication token invalid\n 'session_expired', // User session expired\n 'mfa_required', // Multi-factor authentication required\n 'email_not_verified', // Email verification required\n \n // Authorization Errors (403)\n 'permission_denied', // User lacks required permission\n 'insufficient_privileges', // Operation requires higher privileges\n 'field_not_accessible', // Field-level security restriction\n 'record_not_accessible', // Sharing rule restriction\n 'license_required', // Feature requires license\n 'ip_restricted', // IP address not allowed\n 'time_restricted', // Access outside allowed time window\n \n // Not Found Errors (404)\n 'resource_not_found', // Generic resource not found\n 'object_not_found', // Object/table not found\n 'record_not_found', // Record with given ID not found\n 'field_not_found', // Field not found in object\n 'endpoint_not_found', // API endpoint not found\n \n // Conflict Errors (409)\n 'resource_conflict', // Generic resource conflict\n 'concurrent_modification', // Record modified by another user\n 'delete_restricted', // Cannot delete due to dependencies\n 'duplicate_record', // Record already exists\n 'lock_conflict', // Record is locked by another process\n \n // Rate Limiting (429)\n 'rate_limit_exceeded', // Too many requests\n 'quota_exceeded', // API quota exceeded\n 'concurrent_limit_exceeded', // Too many concurrent requests\n \n // Server Errors (500)\n 'internal_error', // Generic internal server error\n 'database_error', // Database operation failed\n 'timeout', // Operation timed out\n 'service_unavailable', // Service temporarily unavailable\n 'not_implemented', // Feature not yet implemented\n \n // External Service Errors (502/503)\n 'external_service_error', // External API call failed\n 'integration_error', // Integration service error\n 'webhook_delivery_failed', // Webhook delivery failed\n \n // Batch Operation Errors\n 'batch_partial_failure', // Batch operation partially succeeded\n 'batch_complete_failure', // Batch operation completely failed\n 'transaction_failed', // Transaction rolled back\n]);\n\nexport type StandardErrorCode = z.infer;\n\n// ==========================================\n// Enhanced Error Schema\n// ==========================================\n\n/**\n * HTTP Status Code mapping for error categories\n */\nexport const ErrorHttpStatusMap: Record = {\n validation: 400,\n authentication: 401,\n authorization: 403,\n not_found: 404,\n conflict: 409,\n rate_limit: 429,\n server: 500,\n external: 502,\n maintenance: 503,\n};\n\n/**\n * Retry Strategy Enum\n * Guidance on whether to retry failed requests\n */\nexport const RetryStrategy = z.enum([\n 'no_retry', // Do not retry (permanent failure)\n 'retry_immediate', // Retry immediately\n 'retry_backoff', // Retry with exponential backoff\n 'retry_after', // Retry after specified delay\n]);\n\nexport type RetryStrategy = z.infer;\n\n/**\n * Field Error Schema\n * Detailed error for a specific field\n */\nexport const FieldErrorSchema = z.object({\n field: z.string().describe('Field path (supports dot notation)'),\n code: StandardErrorCode.describe('Error code for this field'),\n message: z.string().describe('Human-readable error message'),\n value: z.unknown().optional().describe('The invalid value that was provided'),\n constraint: z.unknown().optional().describe('The constraint that was violated (e.g., max length)'),\n});\n\nexport type FieldError = z.infer;\n\n/**\n * Enhanced API Error Schema\n * Standardized error response with detailed metadata\n * \n * @example Validation Error\n * {\n * \"code\": \"validation_error\",\n * \"message\": \"Validation failed for 2 fields\",\n * \"category\": \"validation\",\n * \"httpStatus\": 400,\n * \"retryable\": false,\n * \"retryStrategy\": \"no_retry\",\n * \"details\": {\n * \"fieldErrors\": [\n * {\n * \"field\": \"email\",\n * \"code\": \"invalid_format\",\n * \"message\": \"Email format is invalid\",\n * \"value\": \"not-an-email\"\n * },\n * {\n * \"field\": \"age\",\n * \"code\": \"value_out_of_range\",\n * \"message\": \"Age must be between 0 and 120\",\n * \"value\": 150,\n * \"constraint\": { \"min\": 0, \"max\": 120 }\n * }\n * ]\n * },\n * \"timestamp\": \"2026-01-29T12:00:00Z\",\n * \"requestId\": \"req_123456\",\n * \"documentation\": \"https://docs.objectstack.dev/errors/validation_error\"\n * }\n * \n * @example Rate Limit Error\n * {\n * \"code\": \"rate_limit_exceeded\",\n * \"message\": \"Rate limit exceeded. Try again in 60 seconds.\",\n * \"category\": \"rate_limit\",\n * \"httpStatus\": 429,\n * \"retryable\": true,\n * \"retryStrategy\": \"retry_after\",\n * \"retryAfter\": 60,\n * \"details\": {\n * \"limit\": 1000,\n * \"remaining\": 0,\n * \"resetAt\": \"2026-01-29T13:00:00Z\"\n * }\n * }\n */\nexport const EnhancedApiErrorSchema = z.object({\n code: StandardErrorCode.describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n category: ErrorCategory.optional().describe('Error category'),\n httpStatus: z.number().optional().describe('HTTP status code'),\n retryable: z.boolean().default(false).describe('Whether the request can be retried'),\n retryStrategy: RetryStrategy.optional().describe('Recommended retry strategy'),\n retryAfter: z.number().optional().describe('Seconds to wait before retrying'),\n details: z.unknown().optional().describe('Additional error context'),\n fieldErrors: z.array(FieldErrorSchema).optional().describe('Field-specific validation errors'),\n timestamp: z.string().datetime().optional().describe('When the error occurred'),\n requestId: z.string().optional().describe('Request ID for tracking'),\n traceId: z.string().optional().describe('Distributed trace ID'),\n documentation: z.string().url().optional().describe('URL to error documentation'),\n helpText: z.string().optional().describe('Suggested actions to resolve the error'),\n});\n\nexport type EnhancedApiError = z.infer;\n\n// ==========================================\n// Error Response Schema\n// ==========================================\n\n/**\n * Standardized Error Response Schema\n * Complete error response envelope\n * \n * @example\n * {\n * \"success\": false,\n * \"error\": {\n * \"code\": \"permission_denied\",\n * \"message\": \"You do not have permission to update this record\",\n * \"category\": \"authorization\",\n * \"httpStatus\": 403,\n * \"retryable\": false\n * }\n * }\n */\nexport const ErrorResponseSchema = z.object({\n success: z.literal(false).describe('Always false for error responses'),\n error: EnhancedApiErrorSchema.describe('Error details'),\n meta: z.object({\n timestamp: z.string().datetime().optional(),\n requestId: z.string().optional(),\n traceId: z.string().optional(),\n }).optional().describe('Response metadata'),\n});\n\nexport type ErrorResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Trigger events for workflow automation\n */\nexport const WorkflowTriggerType = z.enum([\n 'on_create', // When record is created\n 'on_update', // When record is updated\n 'on_create_or_update', // Both\n 'on_delete', // When record is deleted\n 'schedule' // Time-based (cron)\n]);\n\n/**\n * Schema for Workflow Field Update Action\n * @example\n * {\n * name: \"update_status\",\n * type: \"field_update\",\n * field: \"status\",\n * value: \"approved\"\n * }\n */\nexport const FieldUpdateActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('field_update'),\n field: z.string().describe('Field to update'),\n value: z.unknown().describe('Value or Formula to set'),\n});\n\n/**\n * Schema for Workflow Email Alert Action\n * @example\n * {\n * name: \"send_approval_email\",\n * type: \"email_alert\",\n * template: \"approval_request_email\",\n * recipients: [\"user_id_123\", \"manager_field\"]\n * }\n */\nexport const EmailAlertActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('email_alert'),\n template: z.string().describe('Email template ID/DevName'),\n recipients: z.array(z.string()).describe('List of recipient emails or user IDs'),\n});\n\n/**\n * Schema for Connector Action Reference\n * Executes a capability defined in an integration connector.\n * Replaces hardcoded vendor actions (Slack, Twilio, etc).\n * \n * @example Send Slack Message\n * {\n * name: \"notify_slack\",\n * type: \"connector_action\",\n * connectorId: \"slack\",\n * actionId: \"post_message\",\n * input: {\n * channel: \"#general\",\n * text: \"New deal closed: {name}\"\n * }\n * }\n */\nexport const ConnectorActionRefSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('connector_action'),\n connectorId: z.string().describe('Target Connector ID (e.g. slack, twilio)'),\n actionId: z.string().describe('Target Action ID (e.g. send_message)'),\n input: z.record(z.string(), z.unknown()).describe('Input parameters matching the action schema'),\n});\n\n/**\n * Schema for HTTP Callout Action\n * Makes a REST API call to an external service.\n * @example\n * {\n * name: \"sync_to_erp\",\n * type: \"http_call\",\n * url: \"https://erp.api/orders\",\n * method: \"POST\",\n * headers: { \"Authorization\": \"Bearer {token}\" },\n * body: \"{ ... }\"\n * }\n */\nexport const HttpCallActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('http_call'),\n url: z.string().describe('Target URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).default('POST').describe('HTTP Method'),\n headers: z.record(z.string(), z.string()).optional().describe('HTTP Headers'),\n body: z.string().optional().describe('Request body (JSON or text)'),\n});\n\n/**\n * Schema for Workflow Task Creation Action\n * @example\n * {\n * name: \"create_followup_task\",\n * type: \"task_creation\",\n * taskObject: \"tasks\",\n * subject: \"Follow up with client\",\n * dueDate: \"TODAY() + 3\"\n * }\n */\nexport const TaskCreationActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('task_creation'),\n taskObject: z.string().describe('Task object name (e.g., \"task\", \"project_task\")'),\n subject: z.string().describe('Task subject/title'),\n description: z.string().optional().describe('Task description'),\n assignedTo: z.string().optional().describe('User ID or field reference for assignee'),\n dueDate: z.string().optional().describe('Due date (ISO string or formula)'),\n priority: z.string().optional().describe('Task priority'),\n relatedTo: z.string().optional().describe('Related record ID or field reference'),\n additionalFields: z.record(z.string(), z.unknown()).optional().describe('Additional custom fields'),\n});\n\n/**\n * Schema for Workflow Push Notification Action\n */\nexport const PushNotificationActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('push_notification'),\n title: z.string().describe('Notification title'),\n body: z.string().describe('Notification body text'),\n recipients: z.array(z.string()).describe('User IDs or device tokens'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data payload'),\n badge: z.number().optional().describe('Badge count (iOS)'),\n sound: z.string().optional().describe('Notification sound'),\n clickAction: z.string().optional().describe('Action/URL when notification is clicked'),\n});\n\n/**\n * Schema for Workflow Custom Script Action\n */\nexport const CustomScriptActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('custom_script'),\n language: z.enum(['javascript', 'typescript', 'python']).default('javascript').describe('Script language'),\n code: z.string().describe('Script code to execute'),\n timeout: z.number().default(30000).describe('Execution timeout in milliseconds'),\n context: z.record(z.string(), z.unknown()).optional().describe('Additional context variables'),\n});\n\n/**\n * Universal Workflow Action Schema\n * Union of all supported action types.\n */\nexport const WorkflowActionSchema = z.discriminatedUnion('type', [\n FieldUpdateActionSchema,\n EmailAlertActionSchema,\n HttpCallActionSchema,\n ConnectorActionRefSchema,\n TaskCreationActionSchema,\n PushNotificationActionSchema,\n CustomScriptActionSchema,\n]);\n\nexport type WorkflowAction = z.infer;\n\n/**\n * Time Trigger Definition\n * Schedules actions to run relative to a specific time or date field.\n */\nexport const TimeTriggerSchema = z.object({\n id: z.string().optional().describe('Unique identifier'),\n \n /** Timing Logic */\n timeLength: z.number().int().describe('Duration amount (e.g. 1, 30)'),\n timeUnit: z.enum(['minutes', 'hours', 'days']).describe('Unit of time'),\n \n /** Reference Point */\n offsetDirection: z.enum(['before', 'after']).describe('Before or After the reference date'),\n offsetFrom: z.enum(['trigger_date', 'date_field']).describe('Basis for calculation'),\n dateField: z.string().optional().describe('Date field to calculate from (required if offsetFrom is date_field)'),\n \n /** Actions */\n actions: z.array(WorkflowActionSchema).describe('Actions to execute at the scheduled time'),\n});\n\n/**\n * Schema for Workflow Rules (Automation)\n * \n * **NAMING CONVENTION:**\n * Workflow names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good workflow names\n * - 'send_welcome_email'\n * - 'update_lead_status'\n * - 'notify_manager_on_close'\n * - 'calculate_discount'\n * \n * @example Bad workflow names (will be rejected)\n * - 'SendWelcomeEmail' (PascalCase)\n * - 'updateLeadStatus' (camelCase)\n * - 'Send Welcome Email' (spaces)\n * \n * @example Complete Workflow\n * {\n * name: \"new_lead_process\",\n * objectName: \"lead\",\n * triggerType: \"on_create\",\n * criteria: \"amount > 1000\",\n * active: true,\n * actions: [\n * {\n * name: \"set_status\",\n * type: \"field_update\",\n * field: \"status\",\n * value: \"new\"\n * },\n * {\n * name: \"notify_team\",\n * type: \"connector_action\",\n * connectorId: \"slack\",\n * actionId: \"post_message\",\n * input: { channel: \"#sales\", text: \"New high value lead!\" }\n * }\n * ],\n * timeTriggers: [\n * {\n * timeLength: 2,\n * timeUnit: \"days\",\n * offsetDirection: \"after\",\n * offsetFrom: \"trigger_date\",\n * actions: [\n * {\n * name: \"followup_check\",\n * type: \"task_creation\",\n * taskObject: \"task\",\n * subject: \"Follow up lead\",\n * dueDate: \"TODAY()\"\n * }\n * ]\n * }\n * ]\n * }\n */\nexport const WorkflowRuleSchema = z.object({\n /** Machine name */\n name: SnakeCaseIdentifierSchema.describe('Unique workflow name (lowercase snake_case)'),\n \n /** Target Object */\n objectName: z.string().describe('Target Object'),\n \n /** When to evaluate the rule */\n triggerType: WorkflowTriggerType.describe('When to evaluate'),\n \n /** \n * Condition to start the workflow.\n * If empty, runs on every trigger event.\n */\n criteria: z.string().optional().describe('Formula condition. If TRUE, actions execute.'),\n \n /** Actions to execute immediately */\n actions: z.array(WorkflowActionSchema).optional().describe('Immediate actions'),\n \n /** \n * Time-Dependent Actions \n * Actions scheduled to run in the future.\n */\n timeTriggers: z.array(TimeTriggerSchema).optional().describe('Scheduled actions relative to trigger or date field'),\n \n /** Active status */\n active: z.boolean().default(true).describe('Whether this workflow is active'),\n\n /** Execution Order */\n executionOrder: z.number().int().min(0).default(100).describe('Deterministic execution order when multiple workflows match (lower runs first)'),\n \n /** Recursion Control */\n reevaluateOnChange: z.boolean().default(false).describe('Re-evaluate rule if field updates change the record validity'),\n});\n\nexport type WorkflowRule = z.infer;\nexport type TimeTrigger = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ViewSchema } from '../ui/view.zod';\nimport { DiscoverySchema } from './discovery.zod';\nimport { BatchUpdateRequestSchema, BatchUpdateResponseSchema, BatchOptionsSchema } from './batch.zod';\nimport { MetadataCacheRequestSchema, MetadataCacheResponseSchema } from './http-cache.zod';\nimport { QuerySchema } from '../data/query.zod';\nimport { \n AnalyticsQueryRequestSchema, \n AnalyticsResultResponseSchema, \n GetAnalyticsMetaRequestSchema, \n AnalyticsMetadataResponseSchema \n} from './analytics.zod';\nimport { RealtimePresenceSchema, TransportProtocol } from './realtime.zod';\nimport { ObjectPermissionSchema, FieldPermissionSchema } from '../security/permission.zod';\nimport { WorkflowRuleSchema } from '../automation/workflow.zod';\nimport { TranslationDataSchema } from '../system/translation.zod';\nimport type {\n GetFeedRequest,\n GetFeedResponse,\n CreateFeedItemRequest,\n CreateFeedItemResponse,\n UpdateFeedItemRequest,\n UpdateFeedItemResponse,\n DeleteFeedItemRequest,\n DeleteFeedItemResponse,\n AddReactionRequest,\n AddReactionResponse,\n RemoveReactionRequest,\n RemoveReactionResponse,\n PinFeedItemRequest,\n PinFeedItemResponse,\n UnpinFeedItemRequest,\n UnpinFeedItemResponse,\n StarFeedItemRequest,\n StarFeedItemResponse,\n UnstarFeedItemRequest,\n UnstarFeedItemResponse,\n SearchFeedRequest,\n SearchFeedResponse,\n GetChangelogRequest,\n GetChangelogResponse,\n SubscribeRequest,\n SubscribeResponse,\n FeedUnsubscribeRequest,\n UnsubscribeResponse,\n} from './feed-api.zod';\nimport {\n ListPackagesRequestSchema,\n ListPackagesResponseSchema,\n GetPackageRequestSchema,\n GetPackageResponseSchema,\n InstallPackageRequestSchema,\n InstallPackageResponseSchema,\n UninstallPackageRequestSchema,\n UninstallPackageResponseSchema,\n EnablePackageRequestSchema,\n EnablePackageResponseSchema,\n DisablePackageRequestSchema,\n DisablePackageResponseSchema,\n} from '../kernel/package-registry.zod';\nimport type {\n ListPackagesRequest,\n ListPackagesResponse,\n GetPackageRequest,\n GetPackageResponse,\n InstallPackageRequest,\n InstallPackageResponse,\n UninstallPackageRequest,\n UninstallPackageResponse,\n EnablePackageRequest,\n EnablePackageResponse,\n DisablePackageRequest,\n DisablePackageResponse,\n InstalledPackage,\n PackageStatus,\n} from '../kernel/package-registry.zod';\n\nexport const AutomationTriggerRequestSchema = z.object({\n trigger: z.string(),\n payload: z.record(z.string(), z.unknown())\n});\n\nexport const AutomationTriggerResponseSchema = z.object({\n success: z.boolean(),\n jobId: z.string().optional(),\n result: z.unknown().optional()\n});\n\n/**\n * ObjectStack Protocol - Zod Schema Definitions\n * \n * Defines the runtime-validated contract for interacting with ObjectStack metadata and data.\n * Used by API adapters (HTTP, WebSocket, gRPC) to fetch data/metadata without knowing engine internals.\n * \n * This protocol enables:\n * - Runtime request/response validation at API gateway level\n * - Automatic API documentation generation\n * - Type-safe RPC communication between microservices\n * - Client SDK generation from schemas\n * \n * Architecture Alignment:\n * - Salesforce: REST API Request/Response schemas\n * - Kubernetes: API Resource schemas with runtime validation\n * - GraphQL: Schema-first API design\n */\n\n// ==========================================\n// Discovery & Metadata Operations\n// ==========================================\n\n/**\n * Get API Discovery Request\n * No parameters needed\n */\nexport const GetDiscoveryRequestSchema = z.object({});\n\n/**\n * Get API Discovery Response\n * Derived from DiscoverySchema (single source of truth) for protocol-level use.\n * \n * All fields from DiscoverySchema are available but made optional (except `version`)\n * to support progressive disclosure and backward compatibility with existing clients.\n * \n * - `routes` provides a flat endpoint map for client routing.\n * - `services` is the single source of truth for service availability.\n * - `apiName` is kept as an optional alias for `name` for backward compatibility.\n * \n * @see DiscoverySchema in ./discovery.zod.ts — the canonical definition.\n */\nexport const GetDiscoveryResponseSchema = DiscoverySchema\n .partial()\n .required({ version: true })\n .extend({\n /** @deprecated Use `name` instead. Kept for backward compatibility. */\n apiName: z.string().optional().describe('API name (deprecated — use name)'),\n });\n\n/**\n * Get Metadata Types Request\n */\nexport const GetMetaTypesRequestSchema = z.object({});\n\n/**\n * Get Metadata Types Response\n */\nexport const GetMetaTypesResponseSchema = z.object({\n types: z.array(z.string()).describe('Available metadata type names (e.g., \"object\", \"plugin\", \"view\")'),\n});\n\n/**\n * Get Metadata Items Request\n * Get all items of a specific metadata type\n */\nexport const GetMetaItemsRequestSchema = z.object({\n type: z.string().describe('Metadata type name (e.g., \"object\", \"plugin\")'),\n packageId: z.string().optional().describe('Optional package ID to filter items by'),\n});\n\n/**\n * Get Metadata Items Response\n */\nexport const GetMetaItemsResponseSchema = z.object({\n type: z.string().describe('Metadata type name'),\n items: z.array(z.unknown()).describe('Array of metadata items'),\n});\n\n/**\n * Get Metadata Item Request\n * Get a specific metadata item by type and name\n */\nexport const GetMetaItemRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name (snake_case identifier)'),\n packageId: z.string().optional().describe('Optional package ID to filter items by'),\n});\n\n/**\n * Get Metadata Item Response\n */\nexport const GetMetaItemResponseSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n item: z.unknown().describe('Metadata item definition'),\n});\n\n/**\n * Save Metadata Item Request\n * Create or update a metadata item\n */\nexport const SaveMetaItemRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n item: z.unknown().describe('Metadata item definition'),\n});\n\n/**\n * Save Metadata Item Response\n */\nexport const SaveMetaItemResponseSchema = z.object({\n success: z.boolean(),\n message: z.string().optional(),\n});\n\n/**\n * Get Metadata Item with Cache Request\n * Get a specific metadata item with HTTP cache validation support\n */\nexport const GetMetaItemCachedRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n cacheRequest: MetadataCacheRequestSchema.optional().describe('Cache validation parameters'),\n});\n\n/**\n * Get Metadata Item with Cache Response\n * Uses MetadataCacheResponse from http-cache.zod.ts\n */\nexport const GetMetaItemCachedResponseSchema = MetadataCacheResponseSchema;\n\n/**\n * Get UI View Request\n * Resolves the appropriate UI view for an object based on context.\n * Unlike getMetaItem, this does not require a specific View ID.\n */\nexport const GetUiViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n type: z.enum(['list', 'form']).describe('View type'),\n});\n\n/**\n * Get UI View Response\n */\nexport const GetUiViewResponseSchema = ViewSchema;\n\n// ==========================================\n// Data Operations\n// ==========================================\n\n/**\n * Find Data Request\n * Defines a query to retrieve records from a specific object.\n * Supports filtering, sorting, pagination, and field selection.\n * \n * @example\n * {\n * \"object\": \"customers\",\n * \"query\": {\n * \"where\": { \"status\": \"active\", \"revenue\": { \"$gt\": 10000 } },\n * \"orderBy\": [{ \"field\": \"name\", \"order\": \"desc\" }],\n * \"limit\": 10\n * }\n * }\n */\nexport const FindDataRequestSchema = z.object({\n object: z.string().describe('The unique machine name of the object to query (e.g. \"account\").'),\n query: QuerySchema.optional().describe('Structured query definition (filter, sort, select, pagination).'),\n});\n\n/**\n * Find Data Response\n * Returns a list of records matching the query criteria.\n */\nexport const FindDataResponseSchema = z.object({\n object: z.string().describe('The object name for the returned records.'),\n records: z.array(z.record(z.string(), z.unknown())).describe('The list of matching records.'),\n total: z.number().optional().describe('Total number of records matching the filter (if requested).'),\n nextCursor: z.string().optional().describe('Cursor for the next page of results (cursor-based pagination).'),\n hasMore: z.boolean().optional().describe('True if there are more records available (pagination).'),\n});\n\n/**\n * HTTP Find Query Parameters\n * \n * Canonical HTTP query parameter names for GET /data/:object list endpoints.\n * The canonical filter parameter is `filter` (singular). The plural `filters` is\n * accepted for backward compatibility but `filter` is the standard going forward.\n * \n * This schema defines the allowlisted query parameters for HTTP GET list requests.\n * Server-side parsers (protocol.ts) should accept both `filter` and `filters` and\n * normalize to `filter` (singular) internally.\n * \n * @example\n * GET /api/v1/data/contacts?filter={\"status\":\"active\"}&select=name,email&top=10&sort=name\n */\nexport const HttpFindQueryParamsSchema = z.object({\n /** @canonical Singular form — the standard going forward. JSON string of filter expression or AST. */\n filter: z.string().optional().describe('JSON-encoded filter expression (canonical, singular).'),\n /** @deprecated Use `filter` (singular). Accepted for backward compatibility. */\n filters: z.string().optional().describe('JSON-encoded filter expression (deprecated plural alias).'),\n select: z.string().optional().describe('Comma-separated list of fields to retrieve.'),\n sort: z.string().optional().describe('Sort expression (e.g. \"name asc,created_at desc\" or \"-created_at\").'),\n orderBy: z.string().optional().describe('Alias for sort (OData compatibility).'),\n top: z.coerce.number().optional().describe('Max records to return (limit).'),\n skip: z.coerce.number().optional().describe('Records to skip (offset).'),\n expand: z.string().optional().describe(\n 'Comma-separated list of lookup/master_detail field names to expand. '\n + 'Resolved to populate array and passed to the engine for batch $in expansion.'\n ),\n search: z.string().optional().describe('Full-text search query.'),\n distinct: z.coerce.boolean().optional().describe('SELECT DISTINCT flag.'),\n count: z.coerce.boolean().optional().describe('Include total count in response.'),\n});\n\n/**\n * Get Data Request\n * Retrieval of a single record by its unique identifier.\n * Only `select` and `expand` are permitted as additional query parameters.\n * All other query parameters should be discarded to prevent parameter pollution.\n * \n * @example\n * {\n * \"object\": \"contracts\",\n * \"id\": \"cnt_123456\",\n * \"select\": [\"name\", \"status\", \"amount\"],\n * \"expand\": [\"owner\", \"account\"]\n * }\n */\nexport const GetDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The unique record identifier (primary key).'),\n select: z.array(z.string()).optional().describe('Fields to include in the response (allowlisted query param).'),\n expand: z.array(z.string()).optional().describe(\n 'Lookup/master_detail field names to expand. '\n + 'The engine resolves these via batch $in queries, replacing foreign key IDs with full objects.'\n ),\n});\n\n/**\n * Get Data Response\n */\nexport const GetDataResponseSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The record ID.'),\n record: z.record(z.string(), z.unknown()).describe('The complete record data.'),\n});\n\n/**\n * Create Data Request\n * Creation of a new record.\n * \n * @example\n * {\n * \"object\": \"leads\",\n * \"data\": {\n * \"first_name\": \"John\",\n * \"last_name\": \"Doe\",\n * \"company\": \"Acme Inc\"\n * }\n * }\n */\nexport const CreateDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n data: z.record(z.string(), z.unknown()).describe('The dictionary of field values to insert.'),\n});\n\n/**\n * Create Data Response\n */\nexport const CreateDataResponseSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The ID of the newly created record.'),\n record: z.record(z.string(), z.unknown()).describe('The created record, including server-generated fields (created_at, owner).'),\n});\n\n/**\n * Update Data Request\n * Modification of an existing record.\n * \n * @example\n * {\n * \"object\": \"tasks\",\n * \"id\": \"tsk_001\",\n * \"data\": {\n * \"status\": \"completed\",\n * \"percent_complete\": 100\n * }\n * }\n */\nexport const UpdateDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The ID of the record to update.'),\n data: z.record(z.string(), z.unknown()).describe('The fields to update (partial update).'),\n});\n\n/**\n * Update Data Response\n */\nexport const UpdateDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Updated record ID'),\n record: z.record(z.string(), z.unknown()).describe('Updated record'),\n});\n\n/**\n * Delete Data Request\n */\nexport const DeleteDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Record ID to delete'),\n});\n\n/**\n * Delete Data Response\n */\nexport const DeleteDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Deleted record ID'),\n success: z.boolean().describe('Whether deletion succeeded'),\n});\n\n// ==========================================\n// Batch Operations\n// ==========================================\n\n/**\n * Batch Data Request\n */\nexport const BatchDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n request: BatchUpdateRequestSchema.describe('Batch operation request'),\n});\n\n/**\n * Batch Data Response\n * Uses BatchUpdateResponse from batch.zod.ts\n */\nexport const BatchDataResponseSchema = BatchUpdateResponseSchema;\n\n/**\n * Create Many Data Request\n */\nexport const CreateManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.record(z.string(), z.unknown())).describe('Array of records to create'),\n});\n\n/**\n * Create Many Data Response\n */\nexport const CreateManyDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.record(z.string(), z.unknown())).describe('Created records'),\n count: z.number().describe('Number of records created'),\n});\n\n/**\n * Update Many Data Request\n */\nexport const UpdateManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.object({\n id: z.string().describe('Record ID'),\n data: z.record(z.string(), z.unknown()).describe('Fields to update'),\n })).describe('Array of updates'),\n options: BatchOptionsSchema.optional().describe('Update options'),\n});\n\n/**\n * Update Many Data Response\n * Uses BatchUpdateResponse for consistency\n */\nexport const UpdateManyDataResponseSchema = BatchUpdateResponseSchema;\n\n/**\n * Delete Many Data Request\n */\nexport const DeleteManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n ids: z.array(z.string()).describe('Array of record IDs to delete'),\n options: BatchOptionsSchema.optional().describe('Delete options'),\n});\n\n/**\n * Delete Many Data Response\n */\nexport const DeleteManyDataResponseSchema = BatchUpdateResponseSchema;\n\n// ==========================================\n// Package Management Operations\n// ==========================================\n\n/**\n * Re-export Package Management Request/Response schemas from kernel.\n * These define the contract for package lifecycle management:\n * - List installed packages (with filters)\n * - Get a specific package by ID\n * - Install a new package (from manifest)\n * - Uninstall a package\n * - Enable/Disable a package\n * \n * Key distinction: Package (ManifestSchema) is the unit of installation.\n * An App (AppSchema) is a UI navigation entity within a package.\n * A package may contain 0, 1, or many apps.\n */\nexport {\n ListPackagesRequestSchema,\n ListPackagesResponseSchema,\n GetPackageRequestSchema,\n GetPackageResponseSchema,\n InstallPackageRequestSchema,\n InstallPackageResponseSchema,\n UninstallPackageRequestSchema,\n UninstallPackageResponseSchema,\n EnablePackageRequestSchema,\n EnablePackageResponseSchema,\n DisablePackageRequestSchema,\n DisablePackageResponseSchema,\n};\n\n// ==========================================\n// View Management Operations\n// ==========================================\n\nexport const ListViewsRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n type: z.enum(['list', 'form']).optional().describe('Filter by view type'),\n});\n\nexport const ListViewsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n views: z.array(ViewSchema).describe('Array of view definitions'),\n});\n\nexport const GetViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier'),\n});\n\nexport const GetViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n view: ViewSchema.describe('View definition'),\n});\n\nexport const CreateViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n data: ViewSchema.describe('View definition to create'),\n});\n\nexport const CreateViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Created view identifier'),\n view: ViewSchema.describe('Created view definition'),\n});\n\nexport const UpdateViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier'),\n data: ViewSchema.partial().describe('Partial view data to update'),\n});\n\nexport const UpdateViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Updated view identifier'),\n view: ViewSchema.describe('Updated view definition'),\n});\n\nexport const DeleteViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier to delete'),\n});\n\nexport const DeleteViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Deleted view identifier'),\n success: z.boolean().describe('Whether deletion succeeded'),\n});\n\n// ==========================================\n// Permission Operations\n// ==========================================\n\nexport const CheckPermissionRequestSchema = z.object({\n object: z.string().describe('Object name to check permissions for'),\n action: z.enum(['create', 'read', 'edit', 'delete', 'transfer', 'restore', 'purge']).describe('Action to check'),\n recordId: z.string().optional().describe('Specific record ID (for record-level checks)'),\n field: z.string().optional().describe('Specific field name (for field-level checks)'),\n});\n\nexport const CheckPermissionResponseSchema = z.object({\n allowed: z.boolean().describe('Whether the action is permitted'),\n reason: z.string().optional().describe('Reason if denied'),\n});\n\nexport const GetObjectPermissionsRequestSchema = z.object({\n object: z.string().describe('Object name to get permissions for'),\n});\n\nexport const GetObjectPermissionsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n permissions: ObjectPermissionSchema.describe('Object-level permissions'),\n fieldPermissions: z.record(z.string(), FieldPermissionSchema).optional().describe('Field-level permissions keyed by field name'),\n});\n\nexport const GetEffectivePermissionsRequestSchema = z.object({});\n\nexport const GetEffectivePermissionsResponseSchema = z.object({\n objects: z.record(z.string(), ObjectPermissionSchema).describe('Effective object permissions keyed by object name'),\n systemPermissions: z.array(z.string()).describe('Effective system-level permissions'),\n});\n\n// ==========================================\n// Workflow Operations\n// ==========================================\n\nexport const GetWorkflowConfigRequestSchema = z.object({\n object: z.string().describe('Object name to get workflow config for'),\n});\n\nexport const GetWorkflowConfigResponseSchema = z.object({\n object: z.string().describe('Object name'),\n workflows: z.array(WorkflowRuleSchema).describe('Active workflow rules for this object'),\n});\n\nexport const WorkflowStateSchema = z.object({\n currentState: z.string().describe('Current workflow state name'),\n availableTransitions: z.array(z.object({\n name: z.string().describe('Transition name'),\n targetState: z.string().describe('Target state after transition'),\n label: z.string().optional().describe('Display label'),\n requiresApproval: z.boolean().default(false).describe('Whether transition requires approval'),\n })).describe('Available transitions from current state'),\n history: z.array(z.object({\n fromState: z.string().describe('Previous state'),\n toState: z.string().describe('New state'),\n action: z.string().describe('Action that triggered the transition'),\n userId: z.string().describe('User who performed the action'),\n timestamp: z.string().datetime().describe('When the transition occurred'),\n comment: z.string().optional().describe('Optional comment'),\n })).optional().describe('State transition history'),\n});\n\nexport const GetWorkflowStateRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID to get workflow state for'),\n});\n\nexport const GetWorkflowStateResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n state: WorkflowStateSchema.describe('Current workflow state and available transitions'),\n});\n\nexport const WorkflowTransitionRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n transition: z.string().describe('Transition name to execute'),\n comment: z.string().optional().describe('Optional comment for the transition'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data for the transition'),\n});\n\nexport const WorkflowTransitionResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the transition succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after transition'),\n});\n\nexport const WorkflowApproveRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n comment: z.string().optional().describe('Approval comment'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data'),\n});\n\nexport const WorkflowApproveResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the approval succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after approval'),\n});\n\nexport const WorkflowRejectRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n reason: z.string().describe('Rejection reason'),\n comment: z.string().optional().describe('Additional comment'),\n});\n\nexport const WorkflowRejectResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the rejection succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after rejection'),\n});\n\n// ==========================================\n// Realtime Operations\n// ==========================================\n\nexport const RealtimeConnectRequestSchema = z.object({\n transport: TransportProtocol.optional().describe('Preferred transport protocol'),\n channels: z.array(z.string()).optional().describe('Channels to subscribe to on connect'),\n token: z.string().optional().describe('Authentication token'),\n});\n\nexport const RealtimeConnectResponseSchema = z.object({\n connectionId: z.string().describe('Unique connection identifier'),\n transport: TransportProtocol.describe('Negotiated transport protocol'),\n url: z.string().optional().describe('WebSocket/SSE endpoint URL'),\n});\n\nexport const RealtimeDisconnectRequestSchema = z.object({\n connectionId: z.string().optional().describe('Connection ID to disconnect'),\n});\n\nexport const RealtimeDisconnectResponseSchema = z.object({\n success: z.boolean().describe('Whether disconnection succeeded'),\n});\n\nexport const RealtimeSubscribeRequestSchema = z.object({\n channel: z.string().describe('Channel name to subscribe to'),\n events: z.array(z.string()).optional().describe('Specific event types to listen for'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Event filter criteria'),\n});\n\nexport const RealtimeSubscribeResponseSchema = z.object({\n subscriptionId: z.string().describe('Unique subscription identifier'),\n channel: z.string().describe('Subscribed channel name'),\n});\n\nexport const RealtimeUnsubscribeRequestSchema = z.object({\n subscriptionId: z.string().describe('Subscription ID to cancel'),\n});\n\nexport const RealtimeUnsubscribeResponseSchema = z.object({\n success: z.boolean().describe('Whether unsubscription succeeded'),\n});\n\nexport const SetPresenceRequestSchema = z.object({\n channel: z.string().describe('Channel to set presence in'),\n state: RealtimePresenceSchema.describe('Presence state to set'),\n});\n\nexport const SetPresenceResponseSchema = z.object({\n success: z.boolean().describe('Whether presence was set'),\n});\n\nexport const GetPresenceRequestSchema = z.object({\n channel: z.string().describe('Channel to get presence for'),\n});\n\nexport const GetPresenceResponseSchema = z.object({\n channel: z.string().describe('Channel name'),\n members: z.array(RealtimePresenceSchema).describe('Active members and their presence state'),\n});\n\n// ==========================================\n// Notification Operations\n// ==========================================\n\nexport const RegisterDeviceRequestSchema = z.object({\n token: z.string().describe('Device push notification token'),\n platform: z.enum(['ios', 'android', 'web']).describe('Device platform'),\n deviceId: z.string().optional().describe('Unique device identifier'),\n name: z.string().optional().describe('Device friendly name'),\n});\n\nexport const RegisterDeviceResponseSchema = z.object({\n deviceId: z.string().describe('Registered device ID'),\n success: z.boolean().describe('Whether registration succeeded'),\n});\n\nexport const UnregisterDeviceRequestSchema = z.object({\n deviceId: z.string().describe('Device ID to unregister'),\n});\n\nexport const UnregisterDeviceResponseSchema = z.object({\n success: z.boolean().describe('Whether unregistration succeeded'),\n});\n\nexport const NotificationPreferencesSchema = z.object({\n email: z.boolean().default(true).describe('Receive email notifications'),\n push: z.boolean().default(true).describe('Receive push notifications'),\n inApp: z.boolean().default(true).describe('Receive in-app notifications'),\n digest: z.enum(['none', 'daily', 'weekly']).default('none').describe('Email digest frequency'),\n channels: z.record(z.string(), z.object({\n enabled: z.boolean().default(true).describe('Whether this channel is enabled'),\n email: z.boolean().optional().describe('Override email setting'),\n push: z.boolean().optional().describe('Override push setting'),\n })).optional().describe('Per-channel notification preferences'),\n});\n\nexport const GetNotificationPreferencesRequestSchema = z.object({});\n\nexport const GetNotificationPreferencesResponseSchema = z.object({\n preferences: NotificationPreferencesSchema.describe('Current notification preferences'),\n});\n\nexport const UpdateNotificationPreferencesRequestSchema = z.object({\n preferences: NotificationPreferencesSchema.partial().describe('Preferences to update'),\n});\n\nexport const UpdateNotificationPreferencesResponseSchema = z.object({\n preferences: NotificationPreferencesSchema.describe('Updated notification preferences'),\n});\n\nexport const NotificationSchema = z.object({\n id: z.string().describe('Notification ID'),\n type: z.string().describe('Notification type'),\n title: z.string().describe('Notification title'),\n body: z.string().describe('Notification body text'),\n read: z.boolean().default(false).describe('Whether notification has been read'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional notification data'),\n actionUrl: z.string().optional().describe('URL to navigate to when clicked'),\n createdAt: z.string().datetime().describe('When notification was created'),\n});\n\nexport const ListNotificationsRequestSchema = z.object({\n read: z.boolean().optional().describe('Filter by read status'),\n type: z.string().optional().describe('Filter by notification type'),\n limit: z.number().default(20).describe('Maximum number of notifications to return'),\n cursor: z.string().optional().describe('Pagination cursor'),\n});\n\nexport const ListNotificationsResponseSchema = z.object({\n notifications: z.array(NotificationSchema).describe('List of notifications'),\n unreadCount: z.number().describe('Total number of unread notifications'),\n cursor: z.string().optional().describe('Next page cursor'),\n});\n\nexport const MarkNotificationsReadRequestSchema = z.object({\n ids: z.array(z.string()).describe('Notification IDs to mark as read'),\n});\n\nexport const MarkNotificationsReadResponseSchema = z.object({\n success: z.boolean().describe('Whether the operation succeeded'),\n readCount: z.number().describe('Number of notifications marked as read'),\n});\n\nexport const MarkAllNotificationsReadRequestSchema = z.object({});\n\nexport const MarkAllNotificationsReadResponseSchema = z.object({\n success: z.boolean().describe('Whether the operation succeeded'),\n readCount: z.number().describe('Number of notifications marked as read'),\n});\n\n// ==========================================\n// AI Operations\n// ==========================================\n\nexport const AiNlqRequestSchema = z.object({\n query: z.string().describe('Natural language query string'),\n object: z.string().optional().describe('Target object context'),\n conversationId: z.string().optional().describe('Conversation ID for multi-turn queries'),\n});\n\nexport const AiNlqResponseSchema = z.object({\n query: z.unknown().describe('Generated structured query (AST)'),\n explanation: z.string().optional().describe('Human-readable explanation of the query'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n suggestions: z.array(z.string()).optional().describe('Suggested follow-up queries'),\n});\n\n// AiChatRequestSchema and AiChatResponseSchema have been removed.\n// The AI chat wire protocol is now fully aligned with the Vercel AI SDK (`ai`).\n// Frontend consumers should use `@ai-sdk/react/useChat` directly.\n// See: https://ai-sdk.dev/docs\n\nexport const AiSuggestRequestSchema = z.object({\n object: z.string().describe('Object name for context'),\n field: z.string().optional().describe('Field to suggest values for'),\n recordId: z.string().optional().describe('Record ID for context'),\n partial: z.string().optional().describe('Partial input for completion'),\n});\n\nexport const AiSuggestResponseSchema = z.object({\n suggestions: z.array(z.object({\n value: z.unknown().describe('Suggested value'),\n label: z.string().describe('Display label'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n reason: z.string().optional().describe('Reason for this suggestion'),\n })).describe('Suggested values'),\n});\n\nexport const AiInsightsRequestSchema = z.object({\n object: z.string().describe('Object name to analyze'),\n recordId: z.string().optional().describe('Specific record to analyze'),\n type: z.enum(['summary', 'trends', 'anomalies', 'recommendations']).optional().describe('Type of insight'),\n});\n\nexport const AiInsightsResponseSchema = z.object({\n insights: z.array(z.object({\n type: z.string().describe('Insight type'),\n title: z.string().describe('Insight title'),\n description: z.string().describe('Detailed description'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n data: z.record(z.string(), z.unknown()).optional().describe('Supporting data'),\n })).describe('Generated insights'),\n});\n\n// ==========================================\n// i18n Operations\n// ==========================================\n\nexport const GetLocalesRequestSchema = z.object({});\n\nexport const GetLocalesResponseSchema = z.object({\n locales: z.array(z.object({\n code: z.string().describe('BCP-47 locale code (e.g., en-US, zh-CN)'),\n label: z.string().describe('Display name of the locale'),\n isDefault: z.boolean().default(false).describe('Whether this is the default locale'),\n })).describe('Available locales'),\n});\n\nexport const GetTranslationsRequestSchema = z.object({\n locale: z.string().describe('BCP-47 locale code'),\n namespace: z.string().optional().describe('Translation namespace (e.g., objects, apps, messages)'),\n keys: z.array(z.string()).optional().describe('Specific translation keys to fetch'),\n});\n\nexport const GetTranslationsResponseSchema = z.object({\n locale: z.string().describe('Locale code'),\n translations: TranslationDataSchema.describe('Translation data'),\n});\n\nexport const GetFieldLabelsRequestSchema = z.object({\n object: z.string().describe('Object name'),\n locale: z.string().describe('BCP-47 locale code'),\n});\n\nexport const GetFieldLabelsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n locale: z.string().describe('Locale code'),\n labels: z.record(z.string(), z.object({\n label: z.string().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n options: z.record(z.string(), z.string()).optional().describe('Translated option labels'),\n })).describe('Field labels keyed by field name'),\n});\n\n// ==========================================\n// Protocol Interface Schema\n// ==========================================\n\n/**\n * ObjectStack Protocol Contract\n * \n * This schema defines the complete API contract as a Zod schema.\n * Unlike the old TypeScript interface, this provides runtime validation\n * and can be used for:\n * - API Gateway validation\n * - RPC call validation\n * - Client SDK generation\n * - API documentation generation\n * \n * Each method is defined with its request and response schemas.\n */\nexport const ObjectStackProtocolSchema = z.object({\n // Discovery & Metadata\n getDiscovery: z.function()\n .describe('Get API discovery information'),\n\n getMetaTypes: z.function()\n .describe('Get available metadata types'),\n\n getMetaItems: z.function()\n .describe('Get all items of a metadata type'),\n\n getMetaItem: z.function()\n .describe('Get a specific metadata item'),\n saveMetaItem: z.function()\n .describe('Save metadata item'),\n getMetaItemCached: z.function()\n .describe('Get a metadata item with cache validation'),\n\n getUiView: z.function()\n .describe('Get UI view definition'),\n\n // Analytics Operations\n analyticsQuery: z.function()\n .describe('Execute analytics query'),\n\n getAnalyticsMeta: z.function()\n .describe('Get analytics metadata (cubes)'),\n\n // Automation Operations\n triggerAutomation: z.function()\n .describe('Trigger an automation flow or script'),\n\n // Package Management Operations\n listPackages: z.function()\n .describe('List installed packages with optional filters'),\n\n getPackage: z.function()\n .describe('Get a specific installed package by ID'),\n\n installPackage: z.function()\n .describe('Install a new package from manifest'),\n\n uninstallPackage: z.function()\n .describe('Uninstall a package by ID'),\n\n enablePackage: z.function()\n .describe('Enable a disabled package'),\n\n disablePackage: z.function()\n .describe('Disable an installed package'),\n\n // Data Operations\n findData: z.function()\n .describe('Find data records'),\n\n getData: z.function()\n .describe('Get single data record'),\n\n createData: z.function()\n .describe('Create a data record'),\n\n updateData: z.function()\n .describe('Update a data record'),\n\n deleteData: z.function()\n .describe('Delete a data record'),\n\n // Batch Operations\n batchData: z.function()\n .describe('Perform batch operations'),\n\n createManyData: z.function()\n .describe('Create multiple records'),\n\n updateManyData: z.function()\n .describe('Update multiple records'),\n\n deleteManyData: z.function()\n .describe('Delete multiple records'),\n\n // View Management Operations\n listViews: z.function()\n .describe('List views for an object'),\n getView: z.function()\n .describe('Get a specific view'),\n createView: z.function()\n .describe('Create a new view'),\n updateView: z.function()\n .describe('Update an existing view'),\n deleteView: z.function()\n .describe('Delete a view'),\n\n // Permission Operations\n checkPermission: z.function()\n .describe('Check if an action is permitted'),\n getObjectPermissions: z.function()\n .describe('Get permissions for an object'),\n getEffectivePermissions: z.function()\n .describe('Get effective permissions for current user'),\n\n // Workflow Operations\n getWorkflowConfig: z.function()\n .describe('Get workflow configuration for an object'),\n getWorkflowState: z.function()\n .describe('Get workflow state for a record'),\n workflowTransition: z.function()\n .describe('Execute a workflow state transition'),\n workflowApprove: z.function()\n .describe('Approve a workflow step'),\n workflowReject: z.function()\n .describe('Reject a workflow step'),\n\n // Realtime Operations\n realtimeConnect: z.function()\n .describe('Establish realtime connection'),\n realtimeDisconnect: z.function()\n .describe('Close realtime connection'),\n realtimeSubscribe: z.function()\n .describe('Subscribe to a realtime channel'),\n realtimeUnsubscribe: z.function()\n .describe('Unsubscribe from a realtime channel'),\n setPresence: z.function()\n .describe('Set user presence state'),\n getPresence: z.function()\n .describe('Get channel presence information'),\n\n // Notification Operations\n registerDevice: z.function()\n .describe('Register a device for push notifications'),\n unregisterDevice: z.function()\n .describe('Unregister a device'),\n getNotificationPreferences: z.function()\n .describe('Get notification preferences'),\n updateNotificationPreferences: z.function()\n .describe('Update notification preferences'),\n listNotifications: z.function()\n .describe('List notifications'),\n markNotificationsRead: z.function()\n .describe('Mark specific notifications as read'),\n markAllNotificationsRead: z.function()\n .describe('Mark all notifications as read'),\n\n // AI Operations\n aiNlq: z.function()\n .describe('Natural language query'),\n aiChat: z.function()\n .describe('AI chat interaction'),\n aiSuggest: z.function()\n .describe('Get AI-powered suggestions'),\n aiInsights: z.function()\n .describe('Get AI-generated insights'),\n\n // i18n Operations\n getLocales: z.function()\n .describe('Get available locales'),\n getTranslations: z.function()\n .describe('Get translations for a locale'),\n getFieldLabels: z.function()\n .describe('Get translated field labels for an object'),\n\n // Feed Operations\n listFeed: z.function()\n .describe('List feed items for a record'),\n createFeedItem: z.function()\n .describe('Create a new feed item'),\n updateFeedItem: z.function()\n .describe('Update an existing feed item'),\n deleteFeedItem: z.function()\n .describe('Delete a feed item'),\n addReaction: z.function()\n .describe('Add an emoji reaction to a feed item'),\n removeReaction: z.function()\n .describe('Remove an emoji reaction from a feed item'),\n pinFeedItem: z.function()\n .describe('Pin a feed item'),\n unpinFeedItem: z.function()\n .describe('Unpin a feed item'),\n starFeedItem: z.function()\n .describe('Star a feed item'),\n unstarFeedItem: z.function()\n .describe('Unstar a feed item'),\n searchFeed: z.function()\n .describe('Search feed items'),\n getChangelog: z.function()\n .describe('Get field-level changelog for a record'),\n feedSubscribe: z.function()\n .describe('Subscribe to record notifications'),\n feedUnsubscribe: z.function()\n .describe('Unsubscribe from record notifications'),\n});\n\n/**\n * TypeScript Types\n * Derived from Zod schemas using z.infer\n */\nexport type GetDiscoveryRequest = z.infer;\nexport type GetDiscoveryResponse = z.infer;\nexport type GetMetaTypesRequest = z.infer;\nexport type GetMetaTypesResponse = z.infer;\nexport type GetMetaItemsRequest = z.infer;\nexport type GetMetaItemsResponse = z.infer;\nexport type GetMetaItemRequest = z.infer;\nexport type GetMetaItemResponse = z.infer;\nexport type SaveMetaItemRequest = z.infer;\nexport type SaveMetaItemResponse = z.infer;\nexport type GetMetaItemCachedRequest = z.infer;\nexport type GetMetaItemCachedResponse = z.infer;\nexport type GetUiViewRequest = z.infer;\nexport type GetUiViewResponse = z.infer;\n\ntype AnalyticsQueryRequest = z.infer;\ntype AnalyticsResultResponse = z.infer;\ntype GetAnalyticsMetaRequest = z.infer;\ntype GetAnalyticsMetaResponse = z.infer;\n\nexport type AutomationTriggerRequest = z.infer;\nexport type AutomationTriggerResponse = z.infer;\n\nexport type FindDataRequest = z.input;\nexport type FindDataResponse = z.infer;\nexport type GetDataRequest = z.input;\nexport type GetDataResponse = z.infer;\nexport type CreateDataRequest = z.input;\nexport type CreateDataResponse = z.infer;\nexport type UpdateDataRequest = z.input;\nexport type UpdateDataResponse = z.infer;\nexport type DeleteDataRequest = z.input;\nexport type DeleteDataResponse = z.infer;\n\nexport type BatchDataRequest = z.input;\nexport type BatchDataResponse = z.infer;\nexport type CreateManyDataRequest = z.input;\nexport type CreateManyDataResponse = z.infer;\nexport type UpdateManyDataRequest = z.input;\nexport type UpdateManyDataResponse = z.infer;\nexport type DeleteManyDataRequest = z.input;\nexport type DeleteManyDataResponse = z.infer;\n\n// View Management Types\nexport type ListViewsRequest = z.input;\nexport type ListViewsResponse = z.infer;\nexport type GetViewRequest = z.input;\nexport type GetViewResponse = z.infer;\nexport type CreateViewRequest = z.input;\nexport type CreateViewResponse = z.infer;\nexport type UpdateViewRequest = z.input;\nexport type UpdateViewResponse = z.infer;\nexport type DeleteViewRequest = z.input;\nexport type DeleteViewResponse = z.infer;\n\n// Permission Types\nexport type CheckPermissionRequest = z.input;\nexport type CheckPermissionResponse = z.infer;\nexport type GetObjectPermissionsRequest = z.input;\nexport type GetObjectPermissionsResponse = z.infer;\nexport type GetEffectivePermissionsRequest = z.input;\nexport type GetEffectivePermissionsResponse = z.infer;\n\n// Workflow Types\nexport type GetWorkflowConfigRequest = z.input;\nexport type GetWorkflowConfigResponse = z.infer;\nexport type WorkflowState = z.infer;\nexport type GetWorkflowStateRequest = z.input;\nexport type GetWorkflowStateResponse = z.infer;\nexport type WorkflowTransitionRequest = z.input;\nexport type WorkflowTransitionResponse = z.infer;\nexport type WorkflowApproveRequest = z.input;\nexport type WorkflowApproveResponse = z.infer;\nexport type WorkflowRejectRequest = z.input;\nexport type WorkflowRejectResponse = z.infer;\n\n// Realtime Types\nexport type RealtimeConnectRequest = z.input;\nexport type RealtimeConnectResponse = z.infer;\nexport type RealtimeDisconnectRequest = z.input;\nexport type RealtimeDisconnectResponse = z.infer;\nexport type RealtimeSubscribeRequest = z.input;\nexport type RealtimeSubscribeResponse = z.infer;\nexport type RealtimeUnsubscribeRequest = z.input;\nexport type RealtimeUnsubscribeResponse = z.infer;\nexport type SetPresenceRequest = z.input;\nexport type SetPresenceResponse = z.infer;\nexport type GetPresenceRequest = z.input;\nexport type GetPresenceResponse = z.infer;\n\n// Notification Types\nexport type RegisterDeviceRequest = z.input;\nexport type RegisterDeviceResponse = z.infer;\nexport type UnregisterDeviceRequest = z.input;\nexport type UnregisterDeviceResponse = z.infer;\nexport type NotificationPreferences = z.infer;\nexport type NotificationPreferencesInput = z.input;\nexport type GetNotificationPreferencesRequest = z.input;\nexport type GetNotificationPreferencesResponse = z.infer;\nexport type UpdateNotificationPreferencesRequest = z.input;\nexport type UpdateNotificationPreferencesResponse = z.infer;\nexport type Notification = z.infer;\nexport type NotificationInput = z.input;\nexport type ListNotificationsRequest = z.input;\nexport type ListNotificationsResponse = z.infer;\nexport type MarkNotificationsReadRequest = z.input;\nexport type MarkNotificationsReadResponse = z.infer;\nexport type MarkAllNotificationsReadRequest = z.input;\nexport type MarkAllNotificationsReadResponse = z.infer;\n\n// AI Types\nexport type AiNlqRequest = z.input;\nexport type AiNlqResponse = z.infer;\nexport type AiSuggestRequest = z.input;\nexport type AiSuggestResponse = z.infer;\nexport type AiInsightsRequest = z.input;\nexport type AiInsightsResponse = z.infer;\n\n// i18n Types\nexport type GetLocalesRequest = z.input;\nexport type GetLocalesResponse = z.infer;\nexport type GetTranslationsRequest = z.input;\nexport type GetTranslationsResponse = z.infer;\nexport type GetFieldLabelsRequest = z.input;\nexport type GetFieldLabelsResponse = z.infer;\n\n// Feed Types (re-exported from feed-api.zod.ts for convenience)\nexport type {\n GetFeedRequest,\n GetFeedResponse,\n CreateFeedItemRequest,\n CreateFeedItemResponse,\n UpdateFeedItemRequest,\n UpdateFeedItemResponse,\n DeleteFeedItemRequest,\n DeleteFeedItemResponse,\n AddReactionRequest,\n AddReactionResponse,\n RemoveReactionRequest,\n RemoveReactionResponse,\n PinFeedItemRequest,\n PinFeedItemResponse,\n UnpinFeedItemRequest,\n UnpinFeedItemResponse,\n StarFeedItemRequest,\n StarFeedItemResponse,\n UnstarFeedItemRequest,\n UnstarFeedItemResponse,\n SearchFeedRequest,\n SearchFeedResponse,\n GetChangelogRequest,\n GetChangelogResponse,\n SubscribeRequest,\n SubscribeResponse,\n FeedUnsubscribeRequest,\n UnsubscribeResponse,\n} from './feed-api.zod';\n\n// Package Management Types (re-exported from kernel for convenience)\nexport type { \n ListPackagesRequest,\n ListPackagesResponse,\n GetPackageRequest,\n GetPackageResponse,\n InstallPackageRequest,\n InstallPackageResponse,\n UninstallPackageRequest,\n UninstallPackageResponse,\n EnablePackageRequest,\n EnablePackageResponse,\n DisablePackageRequest,\n DisablePackageResponse,\n InstalledPackage,\n PackageStatus,\n};\n\n/**\n * Zod-inferred protocol type (for runtime validation only).\n * Use ObjectStackProtocol interface for implementation contracts.\n */\nexport type ObjectStackProtocolZod = z.infer;\n\n/**\n * ObjectStack Protocol Interface\n * \n * Properly typed interface for implementing the ObjectStack API protocol.\n * The Zod schema (ObjectStackProtocolSchema) is used for runtime validation,\n * while this interface provides compile-time type safety for implementations.\n */\nexport interface ObjectStackProtocol {\n // Discovery & Metadata (core)\n getDiscovery(request?: GetDiscoveryRequest): Promise;\n getMetaTypes(request?: GetMetaTypesRequest): Promise;\n getMetaItems(request: GetMetaItemsRequest): Promise;\n getMetaItem(request: GetMetaItemRequest): Promise;\n saveMetaItem(request: SaveMetaItemRequest): Promise;\n getMetaItemCached?(request: GetMetaItemCachedRequest): Promise;\n getUiView?(request: GetUiViewRequest): Promise;\n \n // Analytics (optional)\n analyticsQuery?(request: AnalyticsQueryRequest): Promise;\n getAnalyticsMeta?(request: GetAnalyticsMetaRequest): Promise;\n\n // Automation (optional)\n triggerAutomation?(request: AutomationTriggerRequest): Promise;\n\n // Package Management (optional)\n listPackages?(request: ListPackagesRequest): Promise;\n getPackage?(request: GetPackageRequest): Promise;\n installPackage?(request: InstallPackageRequest): Promise;\n uninstallPackage?(request: UninstallPackageRequest): Promise;\n enablePackage?(request: EnablePackageRequest): Promise;\n disablePackage?(request: DisablePackageRequest): Promise;\n\n // Data Operations (core)\n findData(request: FindDataRequest): Promise;\n getData(request: GetDataRequest): Promise;\n createData(request: CreateDataRequest): Promise;\n updateData(request: UpdateDataRequest): Promise;\n deleteData(request: DeleteDataRequest): Promise;\n \n // Batch Operations (optional)\n batchData?(request: BatchDataRequest): Promise;\n createManyData?(request: CreateManyDataRequest): Promise;\n updateManyData?(request: UpdateManyDataRequest): Promise;\n deleteManyData?(request: DeleteManyDataRequest): Promise;\n\n // View Management (optional)\n listViews?(request: ListViewsRequest): Promise;\n getView?(request: GetViewRequest): Promise;\n createView?(request: CreateViewRequest): Promise;\n updateView?(request: UpdateViewRequest): Promise;\n deleteView?(request: DeleteViewRequest): Promise;\n\n // Permissions (optional)\n checkPermission?(request: CheckPermissionRequest): Promise;\n getObjectPermissions?(request: GetObjectPermissionsRequest): Promise;\n getEffectivePermissions?(request: GetEffectivePermissionsRequest): Promise;\n\n // Workflows (optional)\n getWorkflowConfig?(request: GetWorkflowConfigRequest): Promise;\n getWorkflowState?(request: GetWorkflowStateRequest): Promise;\n workflowTransition?(request: WorkflowTransitionRequest): Promise;\n workflowApprove?(request: WorkflowApproveRequest): Promise;\n workflowReject?(request: WorkflowRejectRequest): Promise;\n\n // Realtime (optional)\n realtimeConnect?(request: RealtimeConnectRequest): Promise;\n realtimeDisconnect?(request: RealtimeDisconnectRequest): Promise;\n realtimeSubscribe?(request: RealtimeSubscribeRequest): Promise;\n realtimeUnsubscribe?(request: RealtimeUnsubscribeRequest): Promise;\n setPresence?(request: SetPresenceRequest): Promise;\n getPresence?(request: GetPresenceRequest): Promise;\n\n // Notifications (optional)\n registerDevice?(request: RegisterDeviceRequest): Promise;\n unregisterDevice?(request: UnregisterDeviceRequest): Promise;\n getNotificationPreferences?(request: GetNotificationPreferencesRequest): Promise;\n updateNotificationPreferences?(request: UpdateNotificationPreferencesRequest): Promise;\n listNotifications?(request: ListNotificationsRequest): Promise;\n markNotificationsRead?(request: MarkNotificationsReadRequest): Promise;\n markAllNotificationsRead?(request: MarkAllNotificationsReadRequest): Promise;\n\n // AI (optional — chat is now handled by Vercel AI SDK wire protocol)\n aiNlq?(request: AiNlqRequest): Promise;\n aiSuggest?(request: AiSuggestRequest): Promise;\n aiInsights?(request: AiInsightsRequest): Promise;\n\n // i18n (optional)\n getLocales?(request: GetLocalesRequest): Promise;\n getTranslations?(request: GetTranslationsRequest): Promise;\n getFieldLabels?(request: GetFieldLabelsRequest): Promise;\n\n // Feed (optional)\n listFeed?(request: GetFeedRequest): Promise;\n createFeedItem?(request: CreateFeedItemRequest): Promise;\n updateFeedItem?(request: UpdateFeedItemRequest): Promise;\n deleteFeedItem?(request: DeleteFeedItemRequest): Promise;\n addReaction?(request: AddReactionRequest): Promise;\n removeReaction?(request: RemoveReactionRequest): Promise;\n pinFeedItem?(request: PinFeedItemRequest): Promise;\n unpinFeedItem?(request: UnpinFeedItemRequest): Promise;\n starFeedItem?(request: StarFeedItemRequest): Promise;\n unstarFeedItem?(request: UnstarFeedItemRequest): Promise;\n searchFeed?(request: SearchFeedRequest): Promise;\n getChangelog?(request: GetChangelogRequest): Promise;\n feedSubscribe?(request: SubscribeRequest): Promise;\n feedUnsubscribe?(request: FeedUnsubscribeRequest): Promise;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\n\n/**\n * REST API Server Protocol\n * \n * Defines the REST API server configuration for automatically generating\n * RESTful CRUD endpoints, metadata endpoints, and batch operations.\n * \n * Features:\n * - Automatic CRUD endpoint generation from Object definitions\n * - Standard REST conventions (GET, POST, PUT, PATCH, DELETE)\n * - Metadata API endpoints\n * - Batch operation endpoints\n * - OpenAPI/Swagger documentation generation\n * \n * Architecture alignment:\n * - Salesforce: REST API with Object CRUD\n * - Microsoft Dynamics: Web API with entity operations\n * - Strapi: Auto-generated REST endpoints\n */\n\n// ==========================================\n// REST API Configuration\n// ==========================================\n\n/**\n * REST API Configuration Schema\n * Core configuration for REST API server\n * \n * @example\n * {\n * \"version\": \"v1\",\n * \"basePath\": \"/api\",\n * \"enableCrud\": true,\n * \"enableMetadata\": true,\n * \"enableBatch\": true,\n * \"documentation\": {\n * \"enabled\": true,\n * \"title\": \"ObjectStack API\"\n * }\n * }\n */\nexport const RestApiConfigSchema = z.object({\n /**\n * API version identifier\n */\n version: z.string().regex(/^[a-zA-Z0-9_\\-\\.]+$/).default('v1').describe('API version (e.g., v1, v2, 2024-01)'),\n \n /**\n * Base path for all API routes\n */\n basePath: z.string().default('/api').describe('Base URL path for API'),\n \n /**\n * Full API path (combines basePath and version)\n */\n apiPath: z.string().optional().describe('Full API path (defaults to {basePath}/{version})'),\n \n /**\n * Enable automatic CRUD endpoints\n */\n enableCrud: z.boolean().default(true).describe('Enable automatic CRUD endpoint generation'),\n \n /**\n * Enable metadata endpoints\n */\n enableMetadata: z.boolean().default(true).describe('Enable metadata API endpoints'),\n \n /**\n * Enable UI API endpoints\n */\n enableUi: z.boolean().default(true).describe('Enable UI API endpoints (Views, Menus, Layouts)'),\n \n /**\n * Enable batch operation endpoints\n */\n enableBatch: z.boolean().default(true).describe('Enable batch operation endpoints'),\n \n /**\n * Enable discovery endpoint\n */\n enableDiscovery: z.boolean().default(true).describe('Enable API discovery endpoint'),\n\n /**\n * API documentation configuration\n */\n documentation: z.object({\n enabled: z.boolean().default(true).describe('Enable API documentation'),\n title: z.string().default('ObjectStack API').describe('API documentation title'),\n description: z.string().optional().describe('API description'),\n version: z.string().optional().describe('Documentation version'),\n termsOfService: z.string().optional().describe('Terms of service URL'),\n contact: z.object({\n name: z.string().optional(),\n url: z.string().optional(),\n email: z.string().optional(),\n }).optional(),\n license: z.object({\n name: z.string(),\n url: z.string().optional(),\n }).optional(),\n }).optional().describe('OpenAPI/Swagger documentation config'),\n \n /**\n * Response format configuration\n */\n responseFormat: z.object({\n envelope: z.boolean().default(true).describe('Wrap responses in standard envelope'),\n includeMetadata: z.boolean().default(true).describe('Include response metadata (timestamp, requestId)'),\n includePagination: z.boolean().default(true).describe('Include pagination info in list responses'),\n }).optional().describe('Response format options'),\n});\n\nexport type RestApiConfig = z.infer;\nexport type RestApiConfigInput = z.input;\n\n// ==========================================\n// CRUD Endpoint Configuration\n// ==========================================\n\n/**\n * CRUD Operation Type Enum\n */\nexport const CrudOperation = z.enum([\n 'create', // POST /api/v1/data/{object}\n 'read', // GET /api/v1/data/{object}/:id\n 'update', // PATCH /api/v1/data/{object}/:id\n 'delete', // DELETE /api/v1/data/{object}/:id\n 'list', // GET /api/v1/data/{object}\n]);\n\nexport type CrudOperation = z.infer;\n\n/**\n * CRUD Endpoint Pattern Schema\n * Defines the URL pattern for CRUD operations\n * \n * @example\n * {\n * \"create\": { \"method\": \"POST\", \"path\": \"/data/{object}\" },\n * \"read\": { \"method\": \"GET\", \"path\": \"/data/{object}/:id\" },\n * \"update\": { \"method\": \"PATCH\", \"path\": \"/data/{object}/:id\" },\n * \"delete\": { \"method\": \"DELETE\", \"path\": \"/data/{object}/:id\" },\n * \"list\": { \"method\": \"GET\", \"path\": \"/data/{object}\" }\n * }\n */\nexport const CrudEndpointPatternSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (relative to API base)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Operation summary for documentation\n */\n summary: z.string().optional().describe('Operation summary'),\n \n /**\n * Operation description\n */\n description: z.string().optional().describe('Operation description'),\n});\n\nexport type CrudEndpointPattern = z.infer;\n\n/**\n * CRUD Endpoints Configuration Schema\n * Configuration for automatic CRUD endpoint generation\n */\nexport const CrudEndpointsConfigSchema = z.object({\n /**\n * Enable/disable specific CRUD operations\n */\n operations: z.object({\n create: z.boolean().default(true).describe('Enable create operation'),\n read: z.boolean().default(true).describe('Enable read operation'),\n update: z.boolean().default(true).describe('Enable update operation'),\n delete: z.boolean().default(true).describe('Enable delete operation'),\n list: z.boolean().default(true).describe('Enable list operation'),\n }).optional().describe('Enable/disable operations'),\n \n /**\n * Custom endpoint patterns (override defaults)\n */\n patterns: z.record(CrudOperation, CrudEndpointPatternSchema.optional()).optional()\n .describe('Custom URL patterns for operations'),\n \n /**\n * Path prefix for data operations\n */\n dataPrefix: z.string().default('/data').describe('URL prefix for data endpoints'),\n \n /**\n * Object name parameter style\n */\n objectParamStyle: z.enum(['path', 'query']).default('path')\n .describe('How object name is passed (path param or query param)'),\n});\n\nexport type CrudEndpointsConfig = z.infer;\nexport type CrudEndpointsConfigInput = z.input;\n\n// ==========================================\n// Metadata Endpoint Configuration\n// ==========================================\n\n/**\n * Metadata Endpoint Configuration Schema\n * Configuration for metadata API endpoints\n * \n * @example\n * {\n * \"prefix\": \"/meta\",\n * \"enableCache\": true,\n * \"endpoints\": {\n * \"types\": true,\n * \"objects\": true,\n * \"fields\": true\n * }\n * }\n */\nexport const MetadataEndpointsConfigSchema = z.object({\n /**\n * Path prefix for metadata operations\n */\n prefix: z.string().default('/meta').describe('URL prefix for metadata endpoints'),\n \n /**\n * Enable HTTP caching for metadata\n */\n enableCache: z.boolean().default(true).describe('Enable HTTP cache headers (ETag, Last-Modified)'),\n \n /**\n * Cache TTL in seconds\n */\n cacheTtl: z.number().int().default(3600).describe('Cache TTL in seconds'),\n \n /**\n * Enable specific metadata endpoints\n */\n endpoints: z.object({\n types: z.boolean().default(true).describe('GET /meta - List all metadata types'),\n items: z.boolean().default(true).describe('GET /meta/:type - List items of type'),\n item: z.boolean().default(true).describe('GET /meta/:type/:name - Get specific item'),\n schema: z.boolean().default(true).describe('GET /meta/:type/:name/schema - Get JSON schema'),\n }).optional().describe('Enable/disable specific endpoints'),\n});\n\nexport type MetadataEndpointsConfig = z.infer;\nexport type MetadataEndpointsConfigInput = z.input;\n\n// ==========================================\n// Batch Operation Endpoint Configuration\n// ==========================================\n\n/**\n * Batch Operation Endpoint Configuration Schema\n * Configuration for batch/bulk operation endpoints\n * \n * @example\n * {\n * \"maxBatchSize\": 200,\n * \"enableBatchEndpoint\": true,\n * \"enableCreateMany\": true,\n * \"enableUpdateMany\": true,\n * \"enableDeleteMany\": true\n * }\n */\nexport const BatchEndpointsConfigSchema = z.object({\n /**\n * Maximum batch size\n */\n maxBatchSize: z.number().int().min(1).max(1000).default(200)\n .describe('Maximum records per batch operation'),\n \n /**\n * Enable generic batch endpoint\n */\n enableBatchEndpoint: z.boolean().default(true)\n .describe('Enable POST /data/:object/batch endpoint'),\n \n /**\n * Enable specific batch operations\n */\n operations: z.object({\n createMany: z.boolean().default(true).describe('Enable POST /data/:object/createMany'),\n updateMany: z.boolean().default(true).describe('Enable POST /data/:object/updateMany'),\n deleteMany: z.boolean().default(true).describe('Enable POST /data/:object/deleteMany'),\n upsertMany: z.boolean().default(true).describe('Enable POST /data/:object/upsertMany'),\n }).optional().describe('Enable/disable specific batch operations'),\n \n /**\n * Transaction mode default\n */\n defaultAtomic: z.boolean().default(true)\n .describe('Default atomic/transaction mode for batch operations'),\n});\n\nexport type BatchEndpointsConfig = z.infer;\nexport type BatchEndpointsConfigInput = z.input;\n\n// ==========================================\n// Route Generation Configuration\n// ==========================================\n\n/**\n * Route Generation Configuration Schema\n * Controls automatic route generation for objects\n */\nexport const RouteGenerationConfigSchema = z.object({\n /**\n * Objects to include (if empty, include all)\n */\n includeObjects: z.array(z.string()).optional()\n .describe('Specific objects to generate routes for (empty = all)'),\n \n /**\n * Objects to exclude\n */\n excludeObjects: z.array(z.string()).optional()\n .describe('Objects to exclude from route generation'),\n \n /**\n * Object name transformations\n */\n nameTransform: z.enum(['none', 'plural', 'kebab-case', 'camelCase']).default('none')\n .describe('Transform object names in URLs'),\n \n /**\n * Custom route overrides per object\n */\n overrides: z.record(z.string(), z.object({\n enabled: z.boolean().optional().describe('Enable/disable routes for this object'),\n basePath: z.string().optional().describe('Custom base path'),\n operations: z.record(CrudOperation, z.boolean()).optional()\n .describe('Enable/disable specific operations'),\n })).optional().describe('Per-object route customization'),\n});\n\nexport type RouteGenerationConfig = z.infer;\nexport type RouteGenerationConfigInput = z.input;\n\n// ==========================================\n// OpenAPI 3.1 Webhooks & Callbacks\n// ==========================================\n\n/**\n * Webhook Event Schema\n * Defines an event that can trigger a webhook delivery\n */\nexport const WebhookEventSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Webhook event identifier (snake_case)'),\n description: z.string().describe('Human-readable event description'),\n method: HttpMethod.default('POST').describe('HTTP method for webhook delivery'),\n payloadSchema: z.string().describe('JSON Schema $ref for the webhook payload'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers to include in webhook delivery'),\n security: z.array(\n z.enum(['hmac_sha256', 'basic', 'bearer', 'api_key'])\n ).describe('Supported authentication methods for webhook verification'),\n});\n\nexport type WebhookEvent = z.infer;\n\n/**\n * Webhook Configuration Schema\n * Top-level webhook configuration for the REST API\n */\nexport const WebhookConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable webhook support'),\n events: z.array(WebhookEventSchema).describe('Registered webhook events'),\n deliveryConfig: z.object({\n maxRetries: z.number().int().default(3).describe('Maximum delivery retry attempts'),\n retryIntervalMs: z.number().int().default(5000).describe('Milliseconds between retry attempts'),\n timeoutMs: z.number().int().default(30000).describe('Delivery request timeout in milliseconds'),\n signatureHeader: z.string().default('X-Signature-256').describe('Header name for webhook signature'),\n }).describe('Webhook delivery configuration'),\n registrationEndpoint: z.string().default('/webhooks').describe('URL path for webhook registration'),\n});\n\nexport type WebhookConfig = z.infer;\n\n/**\n * Callback Schema\n * OpenAPI 3.1 callback definition for asynchronous API responses\n */\nexport const CallbackSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Callback identifier (snake_case)'),\n expression: z.string().describe('Runtime expression (e.g., {$request.body#/callbackUrl})'),\n method: HttpMethod.describe('HTTP method for callback request'),\n url: z.string().describe('Callback URL template with runtime expressions'),\n});\n\nexport type Callback = z.infer;\n\n/**\n * OpenAPI 3.1 Extensions Schema\n * Extensions specific to OpenAPI 3.1 specification\n */\nexport const OpenApi31ExtensionsSchema = z.object({\n webhooks: z.record(z.string(), WebhookEventSchema).optional()\n .describe('OpenAPI 3.1 webhooks (top-level webhook definitions)'),\n callbacks: z.record(z.string(), z.array(CallbackSchema)).optional()\n .describe('OpenAPI 3.1 callbacks (async response definitions)'),\n jsonSchemaDialect: z.string().default('https://json-schema.org/draft/2020-12/schema')\n .describe('JSON Schema dialect for schema definitions'),\n pathItemReferences: z.boolean().default(false)\n .describe('Allow $ref in path items (OpenAPI 3.1 feature)'),\n});\n\nexport type OpenApi31Extensions = z.infer;\n\n// ==========================================\n// Complete REST Server Configuration\n// ==========================================\n\n/**\n * REST Server Configuration Schema\n * Complete configuration for REST API server with auto-generated endpoints\n * \n * @example\n * {\n * \"api\": {\n * \"version\": \"v1\",\n * \"basePath\": \"/api\",\n * \"enableCrud\": true,\n * \"enableMetadata\": true,\n * \"enableBatch\": true\n * },\n * \"crud\": {\n * \"dataPrefix\": \"/data\"\n * },\n * \"metadata\": {\n * \"prefix\": \"/meta\",\n * \"enableCache\": true\n * },\n * \"batch\": {\n * \"maxBatchSize\": 200\n * },\n * \"routes\": {\n * \"excludeObjects\": [\"system_log\"]\n * }\n * }\n */\nexport const RestServerConfigSchema = z.object({\n /**\n * API configuration\n */\n api: RestApiConfigSchema.optional().describe('REST API configuration'),\n \n /**\n * CRUD endpoints configuration\n */\n crud: CrudEndpointsConfigSchema.optional().describe('CRUD endpoints configuration'),\n \n /**\n * Metadata endpoints configuration\n */\n metadata: MetadataEndpointsConfigSchema.optional().describe('Metadata endpoints configuration'),\n \n /**\n * Batch endpoints configuration\n */\n batch: BatchEndpointsConfigSchema.optional().describe('Batch endpoints configuration'),\n \n /**\n * Route generation configuration\n */\n routes: RouteGenerationConfigSchema.optional().describe('Route generation configuration'),\n \n /**\n * OpenAPI 3.1 extensions (webhooks, callbacks)\n */\n openApi31: OpenApi31ExtensionsSchema.optional().describe('OpenAPI 3.1 extensions configuration'),\n});\n\nexport type RestServerConfig = z.infer;\nexport type RestServerConfigInput = z.input;\n\n// ==========================================\n// Endpoint Registry\n// ==========================================\n\n/**\n * Generated Endpoint Schema\n * Represents a generated REST endpoint\n */\nexport const GeneratedEndpointSchema = z.object({\n /**\n * Endpoint identifier\n */\n id: z.string().describe('Unique endpoint identifier'),\n \n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * Full URL path\n */\n path: z.string().describe('Full URL path'),\n \n /**\n * Object this endpoint operates on\n */\n object: z.string().describe('Object name (snake_case)'),\n \n /**\n * Operation type\n */\n operation: z.union([CrudOperation, z.string()]).describe('Operation type'),\n \n /**\n * Handler reference\n */\n handler: z.string().describe('Handler function identifier'),\n \n /**\n * Endpoint metadata\n */\n metadata: z.object({\n summary: z.string().optional(),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n deprecated: z.boolean().optional(),\n }).optional(),\n});\n\nexport type GeneratedEndpoint = z.infer;\n\n/**\n * Endpoint Registry Schema\n * Registry of all generated endpoints\n */\nexport const EndpointRegistrySchema = z.object({\n /**\n * Generated endpoints\n */\n endpoints: z.array(GeneratedEndpointSchema).describe('All generated endpoints'),\n \n /**\n * Total endpoint count\n */\n total: z.number().int().describe('Total number of endpoints'),\n \n /**\n * Endpoints by object\n */\n byObject: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()\n .describe('Endpoints grouped by object'),\n \n /**\n * Endpoints by operation\n */\n byOperation: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()\n .describe('Endpoints grouped by operation'),\n});\n\nexport type EndpointRegistry = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create REST API configuration\n */\nexport const RestApiConfig = Object.assign(RestApiConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create REST server configuration\n */\nexport const RestServerConfig = Object.assign(RestServerConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, RateLimitConfigSchema } from '../shared/http.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Unified API Registry Protocol\n * \n * Provides a centralized registry for managing all API endpoints across different\n * API types (REST, GraphQL, OData, WebSocket, Auth, File, Plugin-registered).\n * \n * This enables:\n * - Unified API discovery and documentation (similar to Swagger/OpenAPI)\n * - API testing interfaces\n * - API governance and monitoring\n * - Plugin API registration\n * - Multi-protocol support\n * \n * Architecture Alignment:\n * - Kubernetes: Service Discovery & API Server\n * - AWS API Gateway: Unified API Management\n * - Kong Gateway: Plugin-based API Management\n * \n * @example API Registry Entry\n * ```typescript\n * const apiEntry: ApiRegistryEntry = {\n * id: 'customer_crud',\n * name: 'Customer CRUD API',\n * type: 'rest',\n * version: 'v1',\n * basePath: '/api/v1/data/customer',\n * endpoints: [...],\n * metadata: {\n * owner: 'sales_team',\n * tags: ['customer', 'crm']\n * }\n * }\n * ```\n */\n\n// ==========================================\n// API Type Enumeration\n// ==========================================\n\n/**\n * API Protocol Type\n * \n * Defines the different types of APIs supported by ObjectStack.\n */\nexport const ApiProtocolType = z.enum([\n 'rest', // RESTful API (CRUD operations)\n 'graphql', // GraphQL API (flexible queries)\n 'odata', // OData v4 API (enterprise integration)\n 'websocket', // WebSocket API (real-time)\n 'file', // File/Storage API (uploads/downloads)\n 'auth', // Authentication/Authorization API\n 'metadata', // Metadata/Schema API\n 'plugin', // Plugin-registered custom API\n 'webhook', // Webhook endpoints\n 'rpc', // JSON-RPC or similar\n]);\n\nexport type ApiProtocolType = z.infer;\n\n// ==========================================\n// API Endpoint Registration\n// ==========================================\n\n/**\n * HTTP Status Code\n */\nexport const HttpStatusCode = z.union([\n z.number().int().min(100).max(599),\n z.enum(['2xx', '3xx', '4xx', '5xx']), // Pattern matching\n]);\n\nexport type HttpStatusCode = z.infer;\n\n// ==========================================\n// Schema Reference Types\n// ==========================================\n\n/**\n * ObjectQL Reference Schema\n * \n * Allows referencing ObjectStack data objects instead of static JSON schemas.\n * When an API parameter or response references an ObjectQL object, the schema\n * is dynamically derived from the object definition, enabling automatic updates\n * when the object schema changes.\n * \n * **IMPORTANT - Schema Resolution Responsibility:**\n * The API Registry STORES these references as metadata but does NOT resolve them.\n * Schema resolution (expanding references into actual JSON Schema) is performed by:\n * - **API Gateway**: For runtime request/response validation\n * - **OpenAPI Generator**: For Swagger/OpenAPI documentation\n * - **GraphQL Schema Builder**: For GraphQL type generation\n * - **Documentation Tools**: For developer documentation\n * \n * This separation allows the Registry to remain lightweight and focused on\n * registration/discovery, while specialized tools handle schema transformation.\n * \n * **Benefits:**\n * - Auto-updating API documentation when object schemas change\n * - Consistent type definitions across API and database\n * - Reduced duplication and maintenance\n * - Registry remains protocol-agnostic and lightweight\n * \n * @example Reference Customer object\n * ```json\n * {\n * \"objectId\": \"customer\",\n * \"includeFields\": [\"id\", \"name\", \"email\"],\n * \"excludeFields\": [\"internal_notes\"]\n * }\n * ```\n */\nexport const ObjectQLReferenceSchema = z.object({\n /** Referenced object name (snake_case) */\n objectId: SnakeCaseIdentifierSchema.describe('Object name to reference'),\n \n /** Include only specific fields (optional) */\n includeFields: z.array(z.string()).optional()\n .describe('Include only these fields in the schema'),\n \n /** Exclude specific fields (optional) */\n excludeFields: z.array(z.string()).optional()\n .describe('Exclude these fields from the schema'),\n \n /** Include related objects via lookup fields */\n includeRelated: z.array(z.string()).optional()\n .describe('Include related objects via lookup fields'),\n});\n\nexport type ObjectQLReference = z.infer;\n\n/**\n * Schema Definition\n * \n * Unified schema definition that supports both:\n * 1. Static JSON Schema (traditional approach)\n * 2. Dynamic ObjectQL reference (linked to object definitions)\n * \n * When using ObjectQL references, the API documentation and validation\n * automatically update when object schemas change, eliminating the need\n * to manually sync API schemas with data models.\n */\nexport const SchemaDefinition = z.union([\n z.unknown().describe('Static JSON Schema definition'),\n z.object({\n $ref: ObjectQLReferenceSchema.describe('Dynamic reference to ObjectQL object'),\n }).describe('Dynamic ObjectQL reference'),\n]);\n\nexport type SchemaDefinition = z.infer;\n\n// ==========================================\n// API Parameter & Response Schemas\n// ==========================================\n\n/**\n * API Parameter Schema\n * \n * Defines a single API parameter (path, query, header, or body).\n * \n * **Enhancement: Dynamic Schema Linking**\n * - Supports both static JSON Schema and dynamic ObjectQL references\n * - When using ObjectQL references, parameter validation automatically updates\n * when the referenced object schema changes\n * \n * @example Static schema\n * ```json\n * {\n * \"name\": \"customer_id\",\n * \"in\": \"path\",\n * \"schema\": {\n * \"type\": \"string\",\n * \"format\": \"uuid\"\n * }\n * }\n * ```\n * \n * @example Dynamic ObjectQL reference\n * ```json\n * {\n * \"name\": \"customer\",\n * \"in\": \"body\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\",\n * \"excludeFields\": [\"internal_notes\"]\n * }\n * }\n * }\n * ```\n */\nexport const ApiParameterSchema = z.object({\n /** Parameter name */\n name: z.string().describe('Parameter name'),\n \n /** Parameter location */\n in: z.enum(['path', 'query', 'header', 'body', 'cookie']).describe('Parameter location'),\n \n /** Parameter description */\n description: z.string().optional().describe('Parameter description'),\n \n /** Required flag */\n required: z.boolean().default(false).describe('Whether parameter is required'),\n \n /** Parameter type/schema - supports static or dynamic (ObjectQL) schemas */\n schema: z.union([\n z.object({\n type: z.enum(['string', 'number', 'integer', 'boolean', 'array', 'object']).describe('Parameter type'),\n format: z.string().optional().describe('Format (e.g., date-time, email, uuid)'),\n enum: z.array(z.unknown()).optional().describe('Allowed values'),\n default: z.unknown().optional().describe('Default value'),\n items: z.unknown().optional().describe('Array item schema'),\n properties: z.record(z.string(), z.unknown()).optional().describe('Object properties'),\n }).describe('Static JSON Schema'),\n z.object({\n $ref: ObjectQLReferenceSchema,\n }).describe('Dynamic ObjectQL reference'),\n ]).describe('Parameter schema definition'),\n \n /** Example value */\n example: z.unknown().optional().describe('Example value'),\n});\n\nexport type ApiParameter = z.infer;\n\n/**\n * API Response Schema\n * \n * Defines an API response for a specific status code.\n * \n * **Enhancement: Dynamic Schema Linking**\n * - Response schema can reference ObjectQL objects\n * - When object definitions change, response documentation auto-updates\n * \n * @example Response with ObjectQL reference\n * ```json\n * {\n * \"statusCode\": 200,\n * \"description\": \"Customer retrieved successfully\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\",\n * \"excludeFields\": [\"password_hash\"]\n * }\n * }\n * }\n * ```\n */\nexport const ApiResponseSchema = z.object({\n /** HTTP status code */\n statusCode: HttpStatusCode.describe('HTTP status code'),\n \n /** Response description */\n description: z.string().describe('Response description'),\n \n /** Response content type */\n contentType: z.string().default('application/json').describe('Response content type'),\n \n /** Response schema - supports static or dynamic (ObjectQL) schemas */\n schema: z.union([\n z.unknown().describe('Static JSON Schema'),\n z.object({\n $ref: ObjectQLReferenceSchema,\n }).describe('Dynamic ObjectQL reference'),\n ]).optional().describe('Response body schema'),\n \n /** Response headers */\n headers: z.record(z.string(), z.object({\n description: z.string().optional(),\n schema: z.unknown(),\n })).optional().describe('Response headers'),\n \n /** Example response */\n example: z.unknown().optional().describe('Example response'),\n});\n\nexport type ApiResponse = z.infer;\nexport type ApiResponseInput = z.input;\n\n/**\n * API Endpoint Registration Schema\n * \n * Represents a single API endpoint registration with complete metadata.\n * \n * **Enhancements:**\n * 1. **RBAC Integration**: `requiredPermissions` field for automatic permission checking\n * 2. **Dynamic Schema Linking**: Parameters and responses can reference ObjectQL objects\n * 3. **Route Priority**: `priority` field for conflict resolution\n * 4. **Protocol Config**: `protocolConfig` for protocol-specific extensions\n * \n * @example REST Endpoint with RBAC\n * ```json\n * {\n * \"id\": \"get_customer_by_id\",\n * \"method\": \"GET\",\n * \"path\": \"/api/v1/data/customer/:id\",\n * \"summary\": \"Get customer by ID\",\n * \"requiredPermissions\": [\"customer.read\"],\n * \"parameters\": [\n * {\n * \"name\": \"id\",\n * \"in\": \"path\",\n * \"required\": true,\n * \"schema\": { \"type\": \"string\" }\n * }\n * ],\n * \"responses\": [\n * {\n * \"statusCode\": 200,\n * \"description\": \"Customer found\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\"\n * }\n * }\n * }\n * ],\n * \"priority\": 100\n * }\n * ```\n * \n * @example Plugin Endpoint with Protocol Config\n * ```json\n * {\n * \"id\": \"grpc_service_method\",\n * \"path\": \"/grpc/ServiceName/MethodName\",\n * \"summary\": \"gRPC service method\",\n * \"protocolConfig\": {\n * \"subProtocol\": \"grpc\",\n * \"serviceName\": \"CustomerService\",\n * \"methodName\": \"GetCustomer\"\n * },\n * \"priority\": 50\n * }\n * ```\n */\nexport const ApiEndpointRegistrationSchema = z.object({\n /** Unique endpoint identifier */\n id: z.string().describe('Unique endpoint identifier'),\n \n /** HTTP method (for HTTP-based APIs) */\n method: HttpMethod.optional().describe('HTTP method'),\n \n /** URL path pattern */\n path: z.string().describe('URL path pattern'),\n \n /** Short summary */\n summary: z.string().optional().describe('Short endpoint summary'),\n \n /** Detailed description */\n description: z.string().optional().describe('Detailed endpoint description'),\n \n /** Operation ID (OpenAPI) */\n operationId: z.string().optional().describe('Unique operation identifier'),\n \n /** Tags for grouping */\n tags: z.array(z.string()).optional().default([]).describe('Tags for categorization'),\n \n /** Parameters */\n parameters: z.array(ApiParameterSchema).optional().default([]).describe('Endpoint parameters'),\n \n /** Request body schema */\n requestBody: z.object({\n description: z.string().optional(),\n required: z.boolean().default(false),\n contentType: z.string().default('application/json'),\n schema: z.unknown().optional(),\n example: z.unknown().optional(),\n }).optional().describe('Request body specification'),\n \n /** Response definitions */\n responses: z.array(ApiResponseSchema).optional().default([]).describe('Possible responses'),\n \n /** Rate Limiting */\n rateLimit: RateLimitConfigSchema.optional().describe('Endpoint specific rate limiting'),\n\n /** Security Requirements */\n security: z.array(z.record(z.string(), z.array(z.string()))).optional().describe('Security requirements (e.g. [{\"bearerAuth\": []}])'),\n \n /**\n * Required Permissions (RBAC Integration)\n * \n * Array of permission names required to access this endpoint.\n * The gateway layer automatically validates these permissions before\n * allowing the request to proceed, eliminating the need for permission\n * checks in individual API handlers.\n * \n * **Format:** `.` or system permission name\n * \n * **Object Permissions:**\n * - `customer.read` - Read customer records\n * - `customer.create` - Create customer records\n * - `customer.edit` - Update customer records\n * - `customer.delete` - Delete customer records\n * - `customer.viewAll` - View all customer records (bypass sharing)\n * - `customer.modifyAll` - Modify all customer records (bypass sharing)\n * \n * **System Permissions:**\n * - `manage_users` - User management\n * - `view_setup` - Access to system setup\n * - `customize_application` - Modify metadata\n * - `api_enabled` - API access\n * \n * @example Object-level permissions\n * ```json\n * {\n * \"requiredPermissions\": [\"customer.read\"]\n * }\n * ```\n * \n * @example Multiple permissions (ALL required)\n * ```json\n * {\n * \"requiredPermissions\": [\"customer.read\", \"account.read\"]\n * }\n * ```\n * \n * @example System permission\n * ```json\n * {\n * \"requiredPermissions\": [\"manage_users\"]\n * }\n * ```\n * \n * @see {@link file://../../permission/permission.zod.ts} for permission definitions\n */\n requiredPermissions: z.array(z.string()).optional().default([])\n .describe('Required RBAC permissions (e.g., \"customer.read\", \"manage_users\")'),\n \n /**\n * Route Priority\n * \n * Priority level for route conflict resolution. Higher priority routes\n * are registered first and take precedence when multiple routes match\n * the same path pattern.\n * \n * **Default:** 100 (medium priority)\n * **Range:** 0-1000 (higher = more important)\n * \n * **Use Cases:**\n * - Core system APIs: 900-1000\n * - Plugin APIs: 100-500\n * - Custom/override APIs: 500-900\n * - Fallback routes: 0-100\n * \n * @example High priority core endpoint\n * ```json\n * {\n * \"path\": \"/api/v1/data/:object/:id\",\n * \"priority\": 950\n * }\n * ```\n * \n * @example Medium priority plugin endpoint\n * ```json\n * {\n * \"path\": \"/api/v1/custom/action\",\n * \"priority\": 300\n * }\n * ```\n */\n priority: z.number().int().min(0).max(1000).optional().default(100)\n .describe('Route priority for conflict resolution (0-1000, higher = more important)'),\n \n /**\n * Protocol-Specific Configuration\n * \n * Allows plugins and custom APIs to define protocol-specific metadata\n * that can be used for specialized handling or documentation generation.\n * \n * **Examples:**\n * - gRPC: Service and method names\n * - tRPC: Procedure type (query/mutation)\n * - WebSocket: Event names and handlers\n * - Custom protocols: Any metadata needed\n * \n * @example gRPC configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"grpc\",\n * \"serviceName\": \"CustomerService\",\n * \"methodName\": \"GetCustomer\",\n * \"streaming\": false\n * }\n * }\n * ```\n * \n * @example tRPC configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"trpc\",\n * \"procedureType\": \"query\",\n * \"router\": \"customer\"\n * }\n * }\n * ```\n * \n * @example WebSocket configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"websocket\",\n * \"eventName\": \"customer.updated\",\n * \"direction\": \"server-to-client\"\n * }\n * }\n * ```\n */\n protocolConfig: z.record(z.string(), z.unknown()).optional()\n .describe('Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)'),\n \n /** Deprecation flag */\n deprecated: z.boolean().default(false).describe('Whether endpoint is deprecated'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation link'),\n});\n\nexport type ApiEndpointRegistration = z.infer;\nexport type ApiEndpointRegistrationInput = z.input;\n\n// ==========================================\n// API Registry Entry\n// ==========================================\n\n/**\n * API Metadata Schema\n * \n * Additional metadata for an API registration.\n */\nexport const ApiMetadataSchema = z.object({\n /** API owner/team */\n owner: z.string().optional().describe('Owner team or person'),\n \n /** API status */\n status: z.enum(['active', 'deprecated', 'experimental', 'beta']).default('active')\n .describe('API lifecycle status'),\n \n /** Categorization tags */\n tags: z.array(z.string()).optional().default([]).describe('Classification tags'),\n \n /** Plugin source (if plugin-registered) */\n pluginSource: z.string().optional().describe('Source plugin name'),\n \n /** Custom metadata */\n custom: z.record(z.string(), z.unknown()).optional().describe('Custom metadata fields'),\n});\n\nexport type ApiMetadata = z.infer;\nexport type ApiMetadataInput = z.input;\n\n/**\n * API Registry Entry Schema\n * \n * Complete registration entry for an API in the unified registry.\n * \n * @example REST API Entry\n * ```json\n * {\n * \"id\": \"customer_api\",\n * \"name\": \"Customer Management API\",\n * \"type\": \"rest\",\n * \"version\": \"v1\",\n * \"basePath\": \"/api/v1/data/customer\",\n * \"description\": \"CRUD operations for customer records\",\n * \"endpoints\": [...],\n * \"metadata\": {\n * \"owner\": \"sales_team\",\n * \"status\": \"active\",\n * \"tags\": [\"customer\", \"crm\"]\n * }\n * }\n * ```\n * \n * @example Plugin API Entry\n * ```json\n * {\n * \"id\": \"payment_webhook\",\n * \"name\": \"Payment Webhook API\",\n * \"type\": \"plugin\",\n * \"version\": \"1.0.0\",\n * \"basePath\": \"/plugins/payment/webhook\",\n * \"endpoints\": [...],\n * \"metadata\": {\n * \"pluginSource\": \"payment_gateway_plugin\",\n * \"status\": \"active\"\n * }\n * }\n * ```\n */\nexport const ApiRegistryEntrySchema = z.object({\n /** Unique API identifier */\n id: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique API identifier (snake_case)'),\n \n /** Human-readable name */\n name: z.string().describe('API display name'),\n \n /** API protocol type */\n type: ApiProtocolType.describe('API protocol type'),\n \n /** API version */\n version: z.string().describe('API version (e.g., v1, 2024-01)'),\n \n /** Base URL path */\n basePath: z.string().describe('Base URL path for this API'),\n \n /** API description */\n description: z.string().optional().describe('API description'),\n \n /** Endpoints in this API */\n endpoints: z.array(ApiEndpointRegistrationSchema).describe('Registered endpoints'),\n \n /** OpenAPI/GraphQL/OData specific configuration */\n config: z.record(z.string(), z.unknown()).optional().describe('Protocol-specific configuration'),\n \n /** API metadata */\n metadata: ApiMetadataSchema.optional().describe('Additional metadata'),\n \n /** Terms of service URL */\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n \n /** Contact information */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('Contact information'),\n \n /** License information */\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional().describe('License information'),\n});\n\nexport type ApiRegistryEntry = z.infer;\nexport type ApiRegistryEntryInput = z.input;\n\n// ==========================================\n// API Registry\n// ==========================================\n\n/**\n * Route Conflict Resolution Strategy\n * \n * Defines how to handle conflicts when multiple endpoints register\n * the same or overlapping URL patterns.\n */\nexport const ConflictResolutionStrategy = z.enum([\n 'error', // Throw error on conflict (safest, default)\n 'priority', // Use priority field to resolve (highest priority wins)\n 'first-wins', // First registered endpoint wins\n 'last-wins', // Last registered endpoint wins (override mode)\n]);\n\nexport type ConflictResolutionStrategy = z.infer;\n\n/**\n * API Registry Schema\n * \n * Central registry containing all registered APIs.\n * \n * **Enhancement: Route Conflict Detection**\n * - `conflictResolution`: Strategy for handling route conflicts\n * - Prevents silent overwrites and unexpected routing behavior\n * \n * @example\n * ```json\n * {\n * \"version\": \"1.0.0\",\n * \"conflictResolution\": \"priority\",\n * \"apis\": [\n * { \"id\": \"customer_api\", \"type\": \"rest\", ... },\n * { \"id\": \"graphql_api\", \"type\": \"graphql\", ... },\n * { \"id\": \"file_upload_api\", \"type\": \"file\", ... }\n * ],\n * \"totalApis\": 3,\n * \"totalEndpoints\": 47\n * }\n * ```\n * \n * @example Priority-based conflict resolution\n * ```json\n * {\n * \"conflictResolution\": \"priority\",\n * \"apis\": [\n * {\n * \"id\": \"core_api\",\n * \"endpoints\": [\n * {\n * \"path\": \"/api/v1/data/:object\",\n * \"priority\": 950\n * }\n * ]\n * },\n * {\n * \"id\": \"plugin_api\",\n * \"endpoints\": [\n * {\n * \"path\": \"/api/v1/data/custom\",\n * \"priority\": 300\n * }\n * ]\n * }\n * ]\n * }\n * ```\n */\nexport const ApiRegistrySchema = z.object({\n /** Registry version */\n version: z.string().describe('Registry version'),\n \n /**\n * Conflict Resolution Strategy\n * \n * Defines how to handle route conflicts when multiple endpoints\n * register the same or overlapping URL patterns.\n * \n * **Strategies:**\n * - `error`: Throw error on conflict (safest, prevents silent overwrites)\n * - `priority`: Use endpoint priority field (highest priority wins)\n * - `first-wins`: First registered endpoint wins (stable, predictable)\n * - `last-wins`: Last registered endpoint wins (allows overrides)\n * \n * **Default:** `error`\n * \n * **Best Practices:**\n * - Use `error` in production to catch configuration issues\n * - Use `priority` when mixing core and plugin APIs\n * - Use `last-wins` for development/testing overrides\n * \n * @example Prevent accidental conflicts\n * ```json\n * {\n * \"conflictResolution\": \"error\"\n * }\n * ```\n * \n * @example Allow plugin overrides with priority\n * ```json\n * {\n * \"conflictResolution\": \"priority\"\n * }\n * ```\n */\n conflictResolution: ConflictResolutionStrategy.optional().default('error')\n .describe('Strategy for handling route conflicts'),\n \n /** Registered APIs */\n apis: z.array(ApiRegistryEntrySchema).describe('All registered APIs'),\n \n /** Total API count */\n totalApis: z.number().int().describe('Total number of registered APIs'),\n \n /** Total endpoint count across all APIs */\n totalEndpoints: z.number().int().describe('Total number of endpoints'),\n \n /** APIs grouped by type */\n byType: z.record(ApiProtocolType, z.array(ApiRegistryEntrySchema)).optional()\n .describe('APIs grouped by protocol type'),\n \n /** APIs grouped by status */\n byStatus: z.record(z.string(), z.array(ApiRegistryEntrySchema)).optional()\n .describe('APIs grouped by status'),\n \n /** Last updated timestamp */\n updatedAt: z.string().datetime().optional().describe('Last registry update time'),\n});\n\nexport type ApiRegistry = z.infer;\n\n// ==========================================\n// API Discovery & Query\n// ==========================================\n\n/**\n * API Discovery Query Schema\n * \n * Query parameters for discovering/filtering APIs in the registry.\n * \n * @example\n * ```json\n * {\n * \"type\": \"rest\",\n * \"tags\": [\"customer\"],\n * \"status\": \"active\"\n * }\n * ```\n */\nexport const ApiDiscoveryQuerySchema = z.object({\n /** Filter by API type */\n type: ApiProtocolType.optional().describe('Filter by API protocol type'),\n \n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags (ANY match)'),\n \n /** Filter by status */\n status: z.enum(['active', 'deprecated', 'experimental', 'beta']).optional()\n .describe('Filter by lifecycle status'),\n \n /** Filter by plugin source */\n pluginSource: z.string().optional().describe('Filter by plugin name'),\n \n /** Search in name/description */\n search: z.string().optional().describe('Full-text search in name/description'),\n \n /** Filter by version */\n version: z.string().optional().describe('Filter by specific version'),\n});\n\nexport type ApiDiscoveryQuery = z.infer;\n\n/**\n * API Discovery Response Schema\n * \n * Response for API discovery queries.\n */\nexport const ApiDiscoveryResponseSchema = z.object({\n /** Matching APIs */\n apis: z.array(ApiRegistryEntrySchema).describe('Matching API entries'),\n \n /** Total matches */\n total: z.number().int().describe('Total matching APIs'),\n \n /** Applied filters */\n filters: ApiDiscoveryQuerySchema.optional().describe('Applied query filters'),\n});\n\nexport type ApiDiscoveryResponse = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create API endpoint registration\n */\nexport const ApiEndpointRegistration = Object.assign(ApiEndpointRegistrationSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API registry entry\n */\nexport const ApiRegistryEntry = Object.assign(ApiRegistryEntrySchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API registry\n */\nexport const ApiRegistry = Object.assign(ApiRegistrySchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * API Documentation & Testing Interface Protocol\n * \n * Provides schemas for generating interactive API documentation and testing\n * interfaces similar to Swagger UI, GraphQL Playground, Postman, etc.\n * \n * Features:\n * - OpenAPI/Swagger specification generation\n * - Interactive API testing playground\n * - API versioning and changelog\n * - Code generation templates\n * - Mock server configuration\n * \n * Architecture Alignment:\n * - Swagger UI: Interactive API documentation\n * - Postman: API testing collections\n * - GraphQL Playground: GraphQL-specific testing\n * - Redoc: Documentation rendering\n * \n * @example Documentation Config\n * ```typescript\n * const docConfig: ApiDocumentationConfig = {\n * enabled: true,\n * title: 'ObjectStack API',\n * version: '1.0.0',\n * servers: [{ url: 'https://api.example.com', description: 'Production' }],\n * ui: {\n * type: 'swagger-ui',\n * theme: 'light',\n * enableTryItOut: true\n * }\n * }\n * ```\n */\n\n// ==========================================\n// OpenAPI Specification\n// ==========================================\n\n/**\n * OpenAPI Server Schema\n * \n * Server configuration for OpenAPI specification.\n */\nexport const OpenApiServerSchema = z.object({\n /** Server URL */\n url: z.string().url().describe('Server base URL'),\n \n /** Server description */\n description: z.string().optional().describe('Server description'),\n \n /** Server variables */\n variables: z.record(z.string(), z.object({\n default: z.string(),\n description: z.string().optional(),\n enum: z.array(z.string()).optional(),\n })).optional().describe('URL template variables'),\n});\n\nexport type OpenApiServer = z.infer;\n\n/**\n * OpenAPI Security Scheme Schema\n * \n * Security scheme definition for OpenAPI.\n */\nexport const OpenApiSecuritySchemeSchema = z.object({\n /** Security scheme type */\n type: z.enum(['apiKey', 'http', 'oauth2', 'openIdConnect']).describe('Security type'),\n \n /** Scheme name */\n scheme: z.string().optional().describe('HTTP auth scheme (bearer, basic, etc.)'),\n \n /** Bearer format */\n bearerFormat: z.string().optional().describe('Bearer token format (e.g., JWT)'),\n \n /** API key name */\n name: z.string().optional().describe('API key parameter name'),\n \n /** API key location */\n in: z.enum(['header', 'query', 'cookie']).optional().describe('API key location'),\n \n /** OAuth flows */\n flows: z.object({\n implicit: z.unknown().optional(),\n password: z.unknown().optional(),\n clientCredentials: z.unknown().optional(),\n authorizationCode: z.unknown().optional(),\n }).optional().describe('OAuth2 flows'),\n \n /** OpenID Connect URL */\n openIdConnectUrl: z.string().url().optional().describe('OpenID Connect discovery URL'),\n \n /** Description */\n description: z.string().optional().describe('Security scheme description'),\n});\n\nexport type OpenApiSecurityScheme = z.infer;\n\n/**\n * OpenAPI Specification Schema\n * \n * Complete OpenAPI 3.0 specification structure.\n * \n * @see https://swagger.io/specification/\n * \n * @example\n * ```json\n * {\n * \"openapi\": \"3.0.0\",\n * \"info\": {\n * \"title\": \"ObjectStack API\",\n * \"version\": \"1.0.0\",\n * \"description\": \"ObjectStack unified API\"\n * },\n * \"servers\": [\n * { \"url\": \"https://api.example.com\" }\n * ],\n * \"paths\": { ... },\n * \"components\": { ... }\n * }\n * ```\n */\nexport const OpenApiSpecSchema = z.object({\n /** OpenAPI version */\n openapi: z.string().default('3.0.0').describe('OpenAPI specification version'),\n \n /** API information */\n info: z.object({\n title: z.string().describe('API title'),\n version: z.string().describe('API version'),\n description: z.string().optional().describe('API description'),\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional(),\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional(),\n }).describe('API metadata'),\n \n /** Servers */\n servers: z.array(OpenApiServerSchema).optional().default([]).describe('API servers'),\n \n /** API paths */\n paths: z.record(z.string(), z.unknown()).describe('API paths and operations'),\n \n /** Reusable components */\n components: z.object({\n schemas: z.record(z.string(), z.unknown()).optional(),\n responses: z.record(z.string(), z.unknown()).optional(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n examples: z.record(z.string(), z.unknown()).optional(),\n requestBodies: z.record(z.string(), z.unknown()).optional(),\n headers: z.record(z.string(), z.unknown()).optional(),\n securitySchemes: z.record(z.string(), OpenApiSecuritySchemeSchema).optional(),\n links: z.record(z.string(), z.unknown()).optional(),\n callbacks: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Reusable components'),\n \n /** Security requirements */\n security: z.array(z.record(z.string(), z.array(z.string()))).optional()\n .describe('Global security requirements'),\n \n /** Tags */\n tags: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional(),\n })).optional().describe('Tag definitions'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation'),\n});\n\nexport type OpenApiSpec = z.infer;\n\n// ==========================================\n// API Testing Playground\n// ==========================================\n\n/**\n * API Testing UI Type\n */\nexport const ApiTestingUiType = z.enum([\n 'swagger-ui', // Swagger UI\n 'redoc', // Redoc\n 'rapidoc', // RapiDoc\n 'stoplight', // Stoplight Elements\n 'scalar', // Scalar API Reference\n 'graphql-playground', // GraphQL Playground\n 'graphiql', // GraphiQL\n 'postman', // Postman-like interface\n 'custom', // Custom implementation\n]);\n\nexport type ApiTestingUiType = z.infer;\n\n/**\n * API Testing UI Configuration Schema\n * \n * Configuration for interactive API testing interface.\n * \n * @example Swagger UI Config\n * ```json\n * {\n * \"type\": \"swagger-ui\",\n * \"path\": \"/api-docs\",\n * \"theme\": \"light\",\n * \"enableTryItOut\": true,\n * \"enableFilter\": true,\n * \"enableCors\": true,\n * \"defaultModelsExpandDepth\": 1\n * }\n * ```\n */\nexport const ApiTestingUiConfigSchema = z.object({\n /** UI type */\n type: ApiTestingUiType.describe('Testing UI implementation'),\n \n /** UI path */\n path: z.string().default('/api-docs').describe('URL path for documentation UI'),\n \n /** UI theme */\n theme: z.enum(['light', 'dark', 'auto']).default('light').describe('UI color theme'),\n \n /** Enable try-it-out feature */\n enableTryItOut: z.boolean().default(true).describe('Enable interactive API testing'),\n \n /** Enable filtering */\n enableFilter: z.boolean().default(true).describe('Enable endpoint filtering'),\n \n /** Enable CORS for testing */\n enableCors: z.boolean().default(true).describe('Enable CORS for browser testing'),\n \n /** Default expand depth for models */\n defaultModelsExpandDepth: z.number().int().min(-1).default(1)\n .describe('Default expand depth for schemas (-1 = fully expand)'),\n \n /** Display request duration */\n displayRequestDuration: z.boolean().default(true).describe('Show request duration'),\n \n /** Syntax highlighting */\n syntaxHighlighting: z.boolean().default(true).describe('Enable syntax highlighting'),\n \n /** Custom CSS URL */\n customCssUrl: z.string().url().optional().describe('Custom CSS stylesheet URL'),\n \n /** Custom JavaScript URL */\n customJsUrl: z.string().url().optional().describe('Custom JavaScript URL'),\n \n /** Layout options */\n layout: z.object({\n showExtensions: z.boolean().default(false).describe('Show vendor extensions'),\n showCommonExtensions: z.boolean().default(false).describe('Show common extensions'),\n deepLinking: z.boolean().default(true).describe('Enable deep linking'),\n displayOperationId: z.boolean().default(false).describe('Display operation IDs'),\n defaultModelRendering: z.enum(['example', 'model']).default('example')\n .describe('Default model rendering mode'),\n defaultModelsExpandDepth: z.number().int().default(1).describe('Models expand depth'),\n defaultModelExpandDepth: z.number().int().default(1).describe('Single model expand depth'),\n docExpansion: z.enum(['list', 'full', 'none']).default('list')\n .describe('Documentation expansion mode'),\n }).optional().describe('Layout configuration'),\n});\n\nexport type ApiTestingUiConfig = z.infer;\n\n/**\n * API Test Request Schema\n * \n * Represents a saved/example API test request.\n * \n * @example\n * ```json\n * {\n * \"name\": \"Get Customer by ID\",\n * \"description\": \"Retrieves a customer record\",\n * \"method\": \"GET\",\n * \"url\": \"/api/v1/data/customer/123\",\n * \"headers\": {\n * \"Authorization\": \"Bearer {{token}}\"\n * },\n * \"variables\": {\n * \"token\": \"sample_token\"\n * }\n * }\n * ```\n */\nexport const ApiTestRequestSchema = z.object({\n /** Request name */\n name: z.string().describe('Test request name'),\n \n /** Request description */\n description: z.string().optional().describe('Request description'),\n \n /** HTTP method */\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])\n .describe('HTTP method'),\n \n /** Request URL */\n url: z.string().describe('Request URL (can include variables)'),\n \n /** Request headers */\n headers: z.record(z.string(), z.string()).optional().default({})\n .describe('Request headers'),\n \n /** Query parameters */\n queryParams: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional().default({}).describe('Query parameters'),\n \n /** Request body */\n body: z.unknown().optional().describe('Request body'),\n \n /** Environment variables */\n variables: z.record(z.string(), z.unknown()).optional().default({})\n .describe('Template variables'),\n \n /** Expected response */\n expectedResponse: z.object({\n statusCode: z.number().int(),\n body: z.unknown().optional(),\n }).optional().describe('Expected response for validation'),\n});\n\nexport type ApiTestRequest = z.infer;\n\n/**\n * API Test Collection Schema\n * \n * Collection of test requests (similar to Postman collections).\n * \n * @example\n * ```json\n * {\n * \"name\": \"Customer API Tests\",\n * \"description\": \"Test collection for customer endpoints\",\n * \"variables\": {\n * \"baseUrl\": \"https://api.example.com\",\n * \"apiKey\": \"test_key\"\n * },\n * \"requests\": [...]\n * }\n * ```\n */\nexport const ApiTestCollectionSchema = z.object({\n /** Collection name */\n name: z.string().describe('Collection name'),\n \n /** Collection description */\n description: z.string().optional().describe('Collection description'),\n \n /** Collection variables */\n variables: z.record(z.string(), z.unknown()).optional().default({})\n .describe('Shared variables'),\n \n /** Test requests */\n requests: z.array(ApiTestRequestSchema).describe('Test requests in this collection'),\n \n /** Folders/grouping */\n folders: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n requests: z.array(ApiTestRequestSchema),\n })).optional().describe('Request folders for organization'),\n});\n\nexport type ApiTestCollection = z.infer;\n\n// ==========================================\n// API Documentation Configuration\n// ==========================================\n\n/**\n * API Changelog Entry Schema\n * \n * Documents changes in API versions.\n */\nexport const ApiChangelogEntrySchema = z.object({\n /** Version */\n version: z.string().describe('API version'),\n \n /** Release date */\n date: z.string().date().describe('Release date'),\n \n /** Changes */\n changes: z.object({\n added: z.array(z.string()).optional().default([]).describe('New features'),\n changed: z.array(z.string()).optional().default([]).describe('Changes'),\n deprecated: z.array(z.string()).optional().default([]).describe('Deprecations'),\n removed: z.array(z.string()).optional().default([]).describe('Removed features'),\n fixed: z.array(z.string()).optional().default([]).describe('Bug fixes'),\n security: z.array(z.string()).optional().default([]).describe('Security fixes'),\n }).describe('Version changes'),\n \n /** Migration guide */\n migrationGuide: z.string().optional().describe('Migration guide URL or text'),\n});\n\nexport type ApiChangelogEntry = z.infer;\n\n/**\n * Code Generation Template Schema\n * \n * Templates for generating client code.\n */\nexport const CodeGenerationTemplateSchema = z.object({\n /** Language/framework */\n language: z.string().describe('Target language/framework (e.g., typescript, python, curl)'),\n \n /** Template name */\n name: z.string().describe('Template name'),\n \n /** Template content */\n template: z.string().describe('Code template with placeholders'),\n \n /** Template variables */\n variables: z.array(z.string()).optional().describe('Required template variables'),\n});\n\nexport type CodeGenerationTemplate = z.infer;\n\n/**\n * API Documentation Configuration Schema\n * \n * Complete configuration for API documentation and testing interface.\n * \n * @example\n * ```json\n * {\n * \"enabled\": true,\n * \"title\": \"ObjectStack API Documentation\",\n * \"version\": \"1.0.0\",\n * \"description\": \"Unified API for ObjectStack platform\",\n * \"servers\": [\n * { \"url\": \"https://api.example.com\", \"description\": \"Production\" }\n * ],\n * \"ui\": {\n * \"type\": \"swagger-ui\",\n * \"theme\": \"light\",\n * \"enableTryItOut\": true\n * },\n * \"generateOpenApi\": true,\n * \"generateTestCollections\": true\n * }\n * ```\n */\nexport const ApiDocumentationConfigSchema = z.object({\n /** Enable documentation */\n enabled: z.boolean().default(true).describe('Enable API documentation'),\n \n /** Documentation title */\n title: z.string().default('API Documentation').describe('Documentation title'),\n \n /** API version */\n version: z.string().describe('API version'),\n \n /** API description */\n description: z.string().optional().describe('API description'),\n \n /** Server configurations */\n servers: z.array(OpenApiServerSchema).optional().default([])\n .describe('API server URLs'),\n \n /** UI configuration */\n ui: ApiTestingUiConfigSchema.optional().describe('Testing UI configuration'),\n \n /** Generate OpenAPI spec */\n generateOpenApi: z.boolean().default(true).describe('Generate OpenAPI 3.0 specification'),\n \n /** Generate test collections */\n generateTestCollections: z.boolean().default(true)\n .describe('Generate API test collections'),\n \n /** Test collections */\n testCollections: z.array(ApiTestCollectionSchema).optional().default([])\n .describe('Predefined test collections'),\n \n /** API changelog */\n changelog: z.array(ApiChangelogEntrySchema).optional().default([])\n .describe('API version changelog'),\n \n /** Code generation templates */\n codeTemplates: z.array(CodeGenerationTemplateSchema).optional().default([])\n .describe('Code generation templates'),\n \n /** Terms of service */\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n \n /** Contact information */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('Contact information'),\n \n /** License */\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional().describe('API license'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation link'),\n \n /** Security schemes */\n securitySchemes: z.record(z.string(), OpenApiSecuritySchemeSchema).optional()\n .describe('Security scheme definitions'),\n \n /** Global tags */\n tags: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional(),\n })).optional().describe('Global tag definitions'),\n});\n\nexport type ApiDocumentationConfig = z.infer;\n\n// ==========================================\n// API Documentation Generation\n// ==========================================\n\n/**\n * Generated API Documentation Schema\n * \n * Output of documentation generation process.\n */\nexport const GeneratedApiDocumentationSchema = z.object({\n /** OpenAPI specification */\n openApiSpec: OpenApiSpecSchema.optional().describe('Generated OpenAPI specification'),\n \n /** Test collections */\n testCollections: z.array(ApiTestCollectionSchema).optional()\n .describe('Generated test collections'),\n \n /** Markdown documentation */\n markdown: z.string().optional().describe('Generated markdown documentation'),\n \n /** HTML documentation */\n html: z.string().optional().describe('Generated HTML documentation'),\n \n /** Generation timestamp */\n generatedAt: z.string().datetime().describe('Generation timestamp'),\n \n /** Source APIs */\n sourceApis: z.array(z.string()).describe('Source API IDs used for generation'),\n});\n\nexport type GeneratedApiDocumentation = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create API documentation config\n */\nexport const ApiDocumentationConfig = Object.assign(ApiDocumentationConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API test collection\n */\nexport const ApiTestCollection = Object.assign(ApiTestCollectionSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create OpenAPI specification\n */\nexport const OpenApiSpec = Object.assign(OpenApiSpecSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { AnalyticsQuerySchema, CubeSchema } from '../data/analytics.zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Analytics API Protocol\n * \n * Defines the HTTP interface for the Semantic Layer.\n * Provides endpoints for executing analytical queries and discovering metadata.\n */\n\n// ==========================================\n// 1. API Endpoints\n// ==========================================\n\nexport const AnalyticsEndpoint = z.enum([\n '/api/v1/analytics/query', // Execute analysis\n '/api/v1/analytics/meta', // Discover cubes/metrics\n '/api/v1/analytics/sql', // Dry-run SQL generation\n]);\n\n// ==========================================\n// 2. Query Execution\n// ==========================================\n\n/**\n * Query Request Body\n */\nexport const AnalyticsQueryRequestSchema = z.object({\n query: AnalyticsQuerySchema.describe('The analytic query definition'),\n cube: z.string().describe('Target cube name'),\n format: z.enum(['json', 'csv', 'xlsx']).default('json').describe('Response format'),\n});\n\n/**\n * Query Response (JSON)\n */\nexport const AnalyticsResultResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n rows: z.array(z.record(z.string(), z.unknown())).describe('Result rows'),\n fields: z.array(z.object({\n name: z.string(),\n type: z.string(),\n })).describe('Column metadata'),\n sql: z.string().optional().describe('Executed SQL (if debug enabled)'),\n }),\n});\n\n// ==========================================\n// 3. Metadata Discovery\n// ==========================================\n\n/**\n * Meta Request\n */\nexport const GetAnalyticsMetaRequestSchema = z.object({\n cube: z.string().optional().describe('Optional cube name to filter'),\n});\n\n/**\n * Meta Response\n * Returns available cubes, metrics, and dimensions.\n */\nexport const AnalyticsMetadataResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n cubes: z.array(CubeSchema).describe('Available cubes'),\n }),\n});\n\n// ==========================================\n// 4. SQL Dry-Run\n// ==========================================\n\nexport const AnalyticsSqlResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n sql: z.string(),\n params: z.array(z.unknown()),\n }),\n});\n\nexport type AnalyticsEndpoint = z.infer;\nexport type AnalyticsQueryRequest = z.infer;\nexport type AnalyticsMetadataResponse = z.infer;\nexport type AnalyticsSqlResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # API Versioning Protocol\n * \n * Defines how API versions are negotiated between client and server.\n * Supports multiple versioning strategies and deprecation lifecycle management.\n * \n * Architecture Alignment:\n * - Salesforce: URL path versioning (v57.0, v58.0)\n * - Stripe: Date-based versioning (2024-01-01)\n * - Kubernetes: API group versioning (v1, v1beta1)\n * - GitHub: Accept header versioning (application/vnd.github.v3+json)\n * - Microsoft Graph: URL path versioning (v1.0, beta)\n */\n\n// ==========================================\n// Versioning Strategy\n// ==========================================\n\n/**\n * API Versioning Strategy\n * Determines how the API version is specified by clients.\n * \n * - `urlPath`: Version in URL path (e.g., /api/v1/data) — Most common, easy to understand\n * - `header`: Version in Accept header (e.g., Accept: application/vnd.objectstack.v1+json)\n * - `queryParam`: Version in query parameter (e.g., /api/data?version=v1)\n * - `dateBased`: Date-based version in header (e.g., ObjectStack-Version: 2025-01-01) — Stripe-style\n */\nexport const VersioningStrategy = z.enum([\n 'urlPath',\n 'header',\n 'queryParam',\n 'dateBased',\n]);\n\nexport type VersioningStrategy = z.infer;\n\n// ==========================================\n// Version Lifecycle\n// ==========================================\n\n/**\n * API Version Status\n * Lifecycle state of an API version.\n * \n * - `preview`: Available for testing, may change without notice (e.g., v2beta1)\n * - `current`: The recommended stable version\n * - `supported`: Older but still maintained (receives security fixes)\n * - `deprecated`: Scheduled for removal, clients should migrate\n * - `retired`: No longer available, requests return 410 Gone\n */\nexport const VersionStatus = z.enum([\n 'preview',\n 'current',\n 'supported',\n 'deprecated',\n 'retired',\n]);\n\nexport type VersionStatus = z.infer;\n\n// ==========================================\n// Version Definition\n// ==========================================\n\n/**\n * API Version Definition Schema\n * Describes a single API version and its lifecycle metadata.\n * \n * @example\n * {\n * \"version\": \"v1\",\n * \"status\": \"current\",\n * \"releasedAt\": \"2025-01-15\",\n * \"description\": \"Initial stable release\"\n * }\n * \n * @example Deprecated version\n * {\n * \"version\": \"v0\",\n * \"status\": \"deprecated\",\n * \"releasedAt\": \"2024-06-01\",\n * \"deprecatedAt\": \"2025-01-15\",\n * \"sunsetAt\": \"2025-07-15\",\n * \"migrationGuide\": \"https://docs.objectstack.dev/migrate/v0-to-v1\",\n * \"description\": \"Legacy API version\"\n * }\n */\nexport const VersionDefinitionSchema = z.object({\n /** Version identifier (e.g., \"v1\", \"v2beta1\", \"2025-01-01\") */\n version: z.string().describe('Version identifier (e.g., \"v1\", \"v2beta1\", \"2025-01-01\")'),\n\n /** Current lifecycle status */\n status: VersionStatus.describe('Lifecycle status of this version'),\n\n /** Date this version was released (ISO 8601 date) */\n releasedAt: z.string().describe('Release date (ISO 8601, e.g., \"2025-01-15\")'),\n\n /** Date this version was deprecated (ISO 8601 date) */\n deprecatedAt: z.string().optional()\n .describe('Deprecation date (ISO 8601). Only set for deprecated/retired versions'),\n\n /** Date this version will be retired (ISO 8601 date) */\n sunsetAt: z.string().optional()\n .describe('Sunset date (ISO 8601). After this date, the version returns 410 Gone'),\n\n /** URL to migration guide for moving to a newer version */\n migrationGuide: z.string().url().optional()\n .describe('URL to migration guide for upgrading from this version'),\n\n /** Human-readable description of this version */\n description: z.string().optional()\n .describe('Human-readable description or release notes summary'),\n\n /** Breaking changes introduced in or since this version */\n breakingChanges: z.array(z.string()).optional()\n .describe('List of breaking changes (for preview/new versions)'),\n});\n\nexport type VersionDefinition = z.infer;\n\n// ==========================================\n// Versioning Configuration\n// ==========================================\n\n/**\n * API Versioning Configuration Schema\n * Complete configuration for API version management.\n * \n * @example\n * {\n * \"strategy\": \"urlPath\",\n * \"current\": \"v1\",\n * \"default\": \"v1\",\n * \"versions\": [\n * { \"version\": \"v1\", \"status\": \"current\", \"releasedAt\": \"2025-01-15\" },\n * { \"version\": \"v2beta1\", \"status\": \"preview\", \"releasedAt\": \"2025-06-01\" }\n * ],\n * \"deprecation\": {\n * \"warnHeader\": true,\n * \"sunsetHeader\": true\n * }\n * }\n */\nexport const VersioningConfigSchema = z.object({\n /** Versioning strategy */\n strategy: VersioningStrategy.default('urlPath')\n .describe('How the API version is specified by clients'),\n\n /** Current (recommended) API version */\n current: z.string().describe('The current/recommended API version identifier'),\n\n /** Default version when none specified by client */\n default: z.string().describe('Fallback version when client does not specify one'),\n\n /** All available API versions */\n versions: z.array(VersionDefinitionSchema)\n .min(1)\n .describe('All available API versions with lifecycle metadata'),\n\n /** Header name for header-based versioning */\n headerName: z.string().default('ObjectStack-Version')\n .describe('HTTP header name for version negotiation (header/dateBased strategies)'),\n\n /** Query parameter name for queryParam strategy */\n queryParamName: z.string().default('version')\n .describe('Query parameter name for version specification (queryParam strategy)'),\n\n /** URL prefix pattern for urlPath strategy */\n urlPrefix: z.string().default('/api')\n .describe('URL prefix before version segment (urlPath strategy)'),\n\n /** Deprecation behavior */\n deprecation: z.object({\n /** Include Deprecation header in responses for deprecated versions */\n warnHeader: z.boolean().default(true)\n .describe('Include Deprecation header (RFC 8594) in responses'),\n\n /** Include Sunset header with retirement date */\n sunsetHeader: z.boolean().default(true)\n .describe('Include Sunset header (RFC 8594) with retirement date'),\n\n /** Include Link header pointing to migration guide */\n linkHeader: z.boolean().default(true)\n .describe('Include Link header pointing to migration guide URL'),\n\n /** Whether to reject requests to retired versions */\n rejectRetired: z.boolean().default(true)\n .describe('Return 410 Gone for retired API versions'),\n\n /** Custom deprecation warning message */\n warningMessage: z.string().optional()\n .describe('Custom warning message for deprecated version responses'),\n }).optional().describe('Deprecation lifecycle behavior'),\n\n /** Whether to include version info in discovery response */\n includeInDiscovery: z.boolean().default(true)\n .describe('Include version information in the API discovery endpoint'),\n});\n\nexport type VersioningConfig = z.infer;\nexport type VersioningConfigInput = z.input;\n\n// ==========================================\n// Version Negotiation Response\n// ==========================================\n\n/**\n * Version Negotiation Response Schema\n * Returned when a client requests version information or\n * included in the discovery endpoint response.\n * \n * @example\n * {\n * \"current\": \"v1\",\n * \"requested\": \"v1\",\n * \"resolved\": \"v1\",\n * \"supported\": [\"v1\", \"v2beta1\"],\n * \"deprecated\": [\"v0\"],\n * \"versions\": [...]\n * }\n */\nexport const VersionNegotiationResponseSchema = z.object({\n /** The current/recommended version */\n current: z.string().describe('Current recommended API version'),\n\n /** The version the client requested (if any) */\n requested: z.string().optional().describe('Version requested by the client'),\n\n /** The version actually being used for this request */\n resolved: z.string().describe('Resolved API version for this request'),\n\n /** All supported (non-retired) version identifiers */\n supported: z.array(z.string()).describe('All supported version identifiers'),\n\n /** Deprecated version identifiers (still functional but will be removed) */\n deprecated: z.array(z.string()).optional()\n .describe('Deprecated version identifiers'),\n\n /** Full version definitions (optional, for detailed clients) */\n versions: z.array(VersionDefinitionSchema).optional()\n .describe('Full version definitions with lifecycle metadata'),\n});\n\nexport type VersionNegotiationResponse = z.infer;\n\n// ==========================================\n// Default Versioning Configuration\n// ==========================================\n\n/**\n * Default versioning configuration for ObjectStack.\n * Uses URL path strategy with v1 as the current/default version.\n */\nexport const DEFAULT_VERSIONING_CONFIG: VersioningConfigInput = {\n strategy: 'urlPath',\n current: 'v1',\n default: 'v1',\n versions: [\n {\n version: 'v1',\n status: 'current',\n releasedAt: '2025-01-15',\n description: 'ObjectStack API v1 — Initial stable release',\n },\n ],\n deprecation: {\n warnHeader: true,\n sunsetHeader: true,\n linkHeader: true,\n rejectRetired: true,\n },\n includeInDiscovery: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Authentication Service Protocol\n * \n * Defines the standard API contracts for Identity, Session Management,\n * and Access Control.\n */\n\n// ==========================================\n// Authentication Types\n// ==========================================\n\nexport const AuthProvider = z.enum([\n 'local',\n 'google',\n 'github',\n 'microsoft',\n 'ldap',\n 'saml'\n]);\n\nexport const SessionUserSchema = z.object({\n id: z.string().describe('User ID'),\n email: z.string().email().describe('Email address'),\n emailVerified: z.boolean().default(false).describe('Is email verified?'),\n name: z.string().describe('Display name'),\n image: z.string().optional().describe('Avatar URL'),\n username: z.string().optional().describe('Username (optional)'),\n roles: z.array(z.string()).optional().default([]).describe('Assigned role IDs'),\n tenantId: z.string().optional().describe('Current tenant ID'),\n language: z.string().default('en').describe('Preferred language'),\n timezone: z.string().optional().describe('Preferred timezone'),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n});\n\nexport const SessionSchema = z.object({\n id: z.string(),\n expiresAt: z.string().datetime(),\n token: z.string().optional(),\n ipAddress: z.string().optional(),\n userAgent: z.string().optional(),\n userId: z.string(),\n});\n\n// ==========================================\n// Requests\n// ==========================================\n\nexport const LoginType = z.enum(['email', 'username', 'phone', 'magic-link', 'social']);\n\nexport const LoginRequestSchema = z.object({\n type: LoginType.default('email').describe('Login method'),\n email: z.string().email().optional().describe('Required for email/magic-link'),\n username: z.string().optional().describe('Required for username login'),\n password: z.string().optional().describe('Required for password login'),\n provider: z.string().optional().describe('Required for social (google, github)'),\n redirectTo: z.string().optional().describe('Redirect URL after successful login'),\n});\n\nexport const RegisterRequestSchema = z.object({\n email: z.string().email(),\n password: z.string(),\n name: z.string(),\n image: z.string().optional(),\n});\n\nexport const RefreshTokenRequestSchema = z.object({\n refreshToken: z.string().describe('Refresh token'),\n});\n\n// ==========================================\n// Responses\n// ==========================================\n\nexport const SessionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n session: SessionSchema.describe('Active Session Info'),\n user: SessionUserSchema.describe('Current User Details'),\n token: z.string().optional().describe('Bearer token if not using cookies'),\n }),\n});\n\nexport const UserProfileResponseSchema = BaseResponseSchema.extend({\n data: SessionUserSchema,\n});\n\nexport type AuthProvider = z.infer;\nexport type SessionUser = z.infer;\nexport type SessionUserInput = z.input;\nexport type Session = z.infer;\nexport type LoginType = z.infer;\nexport type LoginRequest = z.infer;\nexport type LoginRequestInput = z.input;\nexport type RegisterRequest = z.infer;\nexport type RefreshTokenRequest = z.infer;\nexport type SessionResponse = z.infer;\nexport type UserProfileResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Authentication Endpoint Specification\n * \n * Defines the canonical HTTP endpoints for the authentication service.\n * Based on better-auth v1.4.18 endpoint conventions.\n * \n * NOTE: ObjectStack's auth implementation uses better-auth library which has\n * established endpoint conventions. This spec documents those conventions as\n * the canonical API contract.\n */\n\n// ==========================================\n// Endpoint Path Definitions\n// ==========================================\n\n/**\n * Authentication Endpoint Paths\n * \n * These are the paths relative to the auth base route (e.g., /api/v1/auth).\n * Based on better-auth's endpoint structure.\n */\nexport const AuthEndpointPaths = {\n // Email/Password Authentication\n signInEmail: '/sign-in/email',\n signUpEmail: '/sign-up/email',\n signOut: '/sign-out',\n \n // Session Management\n getSession: '/get-session',\n \n // Password Management\n forgetPassword: '/forget-password',\n resetPassword: '/reset-password',\n \n // Email Verification\n sendVerificationEmail: '/send-verification-email',\n verifyEmail: '/verify-email',\n \n // OAuth (dynamic based on provider)\n // authorize: '/authorize/:provider'\n // callback: '/callback/:provider'\n \n // 2FA (when enabled)\n twoFactorEnable: '/two-factor/enable',\n twoFactorVerify: '/two-factor/verify',\n \n // Passkeys (when enabled)\n passkeyRegister: '/passkey/register',\n passkeyAuthenticate: '/passkey/authenticate',\n \n // Magic Links (when enabled)\n magicLinkSend: '/magic-link/send',\n magicLinkVerify: '/magic-link/verify',\n} as const;\n\n/**\n * HTTP Method + Path Specification\n * \n * Defines the complete HTTP contract for each endpoint.\n */\nexport const AuthEndpointSchema = z.object({\n /** Sign in with email and password */\n signInEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signInEmail),\n description: z.literal('Sign in with email and password'),\n }),\n \n /** Register new user with email and password */\n signUpEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signUpEmail),\n description: z.literal('Register new user with email and password'),\n }),\n \n /** Sign out current user */\n signOut: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signOut),\n description: z.literal('Sign out current user'),\n }),\n \n /** Get current user session */\n getSession: z.object({\n method: z.literal('GET'),\n path: z.literal(AuthEndpointPaths.getSession),\n description: z.literal('Get current user session'),\n }),\n \n /** Request password reset email */\n forgetPassword: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.forgetPassword),\n description: z.literal('Request password reset email'),\n }),\n \n /** Reset password with token */\n resetPassword: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.resetPassword),\n description: z.literal('Reset password with token'),\n }),\n \n /** Send email verification */\n sendVerificationEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.sendVerificationEmail),\n description: z.literal('Send email verification link'),\n }),\n \n /** Verify email with token */\n verifyEmail: z.object({\n method: z.literal('GET'),\n path: z.literal(AuthEndpointPaths.verifyEmail),\n description: z.literal('Verify email with token'),\n }),\n});\n\n/**\n * Endpoint Aliases\n * \n * Common aliases for better developer experience.\n * These map to the canonical better-auth endpoints.\n */\nexport const AuthEndpointAliases = {\n login: AuthEndpointPaths.signInEmail,\n register: AuthEndpointPaths.signUpEmail,\n logout: AuthEndpointPaths.signOut,\n me: AuthEndpointPaths.getSession,\n} as const;\n\n/**\n * Full Endpoint URLs\n * \n * Helper to construct full endpoint URLs given a base path.\n */\nexport function getAuthEndpointUrl(basePath: string, endpoint: keyof typeof AuthEndpointPaths): string {\n const cleanBase = basePath.replace(/\\/$/, '');\n return `${cleanBase}${AuthEndpointPaths[endpoint]}`;\n}\n\n/**\n * Endpoint Mapping\n * \n * Maps common/legacy endpoint names to canonical better-auth paths.\n * This allows clients to use simpler names while maintaining compatibility.\n */\nexport const EndpointMapping = {\n '/login': AuthEndpointPaths.signInEmail,\n '/register': AuthEndpointPaths.signUpEmail,\n '/logout': AuthEndpointPaths.signOut,\n '/me': AuthEndpointPaths.getSession,\n '/refresh': AuthEndpointPaths.getSession, // Session refresh handled by better-auth automatically\n} as const;\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type AuthEndpoint = z.infer;\nexport type AuthEndpointPath = typeof AuthEndpointPaths[keyof typeof AuthEndpointPaths];\nexport type AuthEndpointAlias = keyof typeof AuthEndpointAliases;\nexport type EndpointMappingKey = keyof typeof EndpointMapping;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { FileMetadataSchema } from '../system/object-storage.zod';\n\n/**\n * Storage Service Protocol\n * \n * Defines the API contract for client-side file operations.\n * Focuses on secure, direct-to-cloud uploads (Presigned URLs)\n * rather than proxying bytes through the API server.\n */\n\n// ==========================================\n// Requests\n// ==========================================\n\nexport const GetPresignedUrlRequestSchema = z.object({\n filename: z.string().describe('Original filename'),\n mimeType: z.string().describe('File MIME type'),\n size: z.number().describe('File size in bytes'),\n scope: z.string().default('user').describe('Target storage scope (e.g. user, private, public)'),\n bucket: z.string().optional().describe('Specific bucket override (admin only)'),\n});\n\nexport const CompleteUploadRequestSchema = z.object({\n fileId: z.string().describe('File ID returned from presigned request'),\n eTag: z.string().optional().describe('S3 ETag verification'),\n});\n\n// ==========================================\n// Responses\n// ==========================================\n\nexport const PresignedUrlResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadUrl: z.string().describe('PUT/POST URL for direct upload'),\n downloadUrl: z.string().optional().describe('Public/Private preview URL'),\n fileId: z.string().describe('Temporary File ID'),\n method: z.enum(['PUT', 'POST']).describe('HTTP Method to use'),\n headers: z.record(z.string(), z.string()).optional().describe('Required headers for upload'),\n expiresIn: z.number().describe('URL expiry in seconds'),\n }),\n});\n\nexport const FileUploadResponseSchema = BaseResponseSchema.extend({\n data: FileMetadataSchema.describe('Uploaded file metadata'),\n});\n\nexport type GetPresignedUrlRequest = z.infer;\nexport type CompleteUploadRequest = z.infer;\nexport type PresignedUrlResponse = z.infer;\nexport type FileUploadResponse = z.infer;\n\n// ==========================================\n// Chunked / Resumable Upload Protocol\n// ==========================================\n\n/**\n * File Type Validation Schema\n * Configures allowed and blocked file types for upload endpoints.\n *\n * @example Allow images only\n * { mode: 'whitelist', mimeTypes: ['image/jpeg', 'image/png', 'image/webp'], maxFileSize: 10485760 }\n */\nexport const FileTypeValidationSchema = z.object({\n mode: z.enum(['whitelist', 'blacklist'])\n .describe('whitelist = only allow listed types, blacklist = block listed types'),\n mimeTypes: z.array(z.string()).min(1)\n .describe('List of MIME types to allow or block (e.g., \"image/jpeg\", \"application/pdf\")'),\n extensions: z.array(z.string()).optional()\n .describe('List of file extensions to allow or block (e.g., \".jpg\", \".pdf\")'),\n maxFileSize: z.number().int().min(1).optional()\n .describe('Maximum file size in bytes'),\n minFileSize: z.number().int().min(0).optional()\n .describe('Minimum file size in bytes (e.g., reject empty files)'),\n});\nexport type FileTypeValidation = z.infer;\n\n/**\n * Initiate Chunked Upload Request\n * Starts a resumable multipart upload session.\n *\n * @example POST /api/v1/storage/upload/chunked\n * { filename: 'large-video.mp4', mimeType: 'video/mp4', totalSize: 1073741824, chunkSize: 5242880 }\n */\nexport const InitiateChunkedUploadRequestSchema = z.object({\n filename: z.string().describe('Original filename'),\n mimeType: z.string().describe('File MIME type'),\n totalSize: z.number().int().min(1).describe('Total file size in bytes'),\n chunkSize: z.number().int().min(5242880).default(5242880)\n .describe('Size of each chunk in bytes (minimum 5MB per S3 spec)'),\n scope: z.string().default('user').describe('Target storage scope'),\n bucket: z.string().optional().describe('Specific bucket override (admin only)'),\n metadata: z.record(z.string(), z.string()).optional().describe('Custom metadata key-value pairs'),\n});\nexport type InitiateChunkedUploadRequest = z.infer;\n\n/**\n * Initiate Chunked Upload Response\n * Returns a resume token and upload session details.\n */\nexport const InitiateChunkedUploadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n resumeToken: z.string().describe('Opaque token for resuming interrupted uploads'),\n fileId: z.string().describe('Assigned file ID'),\n totalChunks: z.number().int().min(1).describe('Expected number of chunks'),\n chunkSize: z.number().int().describe('Chunk size in bytes'),\n expiresAt: z.string().datetime().describe('Upload session expiration timestamp'),\n }),\n});\nexport type InitiateChunkedUploadResponse = z.infer;\n\n/**\n * Upload Chunk Request\n * Uploads a single chunk of a multipart upload.\n *\n * @example PUT /api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex\n */\nexport const UploadChunkRequestSchema = z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n chunkIndex: z.number().int().min(0).describe('Zero-based chunk index'),\n resumeToken: z.string().describe('Resume token from initiate response'),\n});\nexport type UploadChunkRequest = z.infer;\n\n/**\n * Upload Chunk Response\n * Confirms a single chunk upload with ETag for assembly.\n */\nexport const UploadChunkResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n chunkIndex: z.number().int().describe('Chunk index that was uploaded'),\n eTag: z.string().describe('Chunk ETag for multipart completion'),\n bytesReceived: z.number().int().describe('Bytes received for this chunk'),\n }),\n});\nexport type UploadChunkResponse = z.infer;\n\n/**\n * Complete Chunked Upload Request\n * Assembles all uploaded chunks into a final file.\n *\n * @example POST /api/v1/storage/upload/chunked/:uploadId/complete\n */\nexport const CompleteChunkedUploadRequestSchema = z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n parts: z.array(z.object({\n chunkIndex: z.number().int().describe('Chunk index'),\n eTag: z.string().describe('ETag returned from chunk upload'),\n })).min(1).describe('Ordered list of uploaded parts for assembly'),\n});\nexport type CompleteChunkedUploadRequest = z.infer;\n\n/**\n * Complete Chunked Upload Response\n * Confirms that all chunks have been assembled into the final file.\n */\nexport const CompleteChunkedUploadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n fileId: z.string().describe('Final file ID'),\n key: z.string().describe('Storage key/path of the assembled file'),\n size: z.number().int().describe('Total file size in bytes'),\n mimeType: z.string().describe('File MIME type'),\n eTag: z.string().optional().describe('Final ETag of the assembled file'),\n url: z.string().optional().describe('Download URL for the assembled file'),\n }),\n});\nexport type CompleteChunkedUploadResponse = z.infer;\n\n/**\n * Upload Progress Schema\n * Represents the current progress of an active upload session.\n *\n * @example GET /api/v1/storage/upload/chunked/:uploadId/progress\n */\nexport const UploadProgressSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n fileId: z.string().describe('Assigned file ID'),\n filename: z.string().describe('Original filename'),\n totalSize: z.number().int().describe('Total file size in bytes'),\n uploadedSize: z.number().int().describe('Bytes uploaded so far'),\n totalChunks: z.number().int().describe('Total expected chunks'),\n uploadedChunks: z.number().int().describe('Number of chunks uploaded'),\n percentComplete: z.number().min(0).max(100).describe('Upload progress percentage'),\n status: z.enum(['in_progress', 'completing', 'completed', 'failed', 'expired'])\n .describe('Current upload session status'),\n startedAt: z.string().datetime().describe('Upload session start timestamp'),\n expiresAt: z.string().datetime().describe('Session expiration timestamp'),\n }),\n});\nexport type UploadProgress = z.infer;\n\n// ==========================================\n// Storage API Contract Registry\n// ==========================================\n\n/**\n * Standard Storage API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const StorageApiContracts = {\n getPresignedUrl: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/presigned',\n input: GetPresignedUrlRequestSchema,\n output: PresignedUrlResponseSchema,\n },\n completeUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/complete',\n input: CompleteUploadRequestSchema,\n output: FileUploadResponseSchema,\n },\n initiateChunkedUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/chunked',\n input: InitiateChunkedUploadRequestSchema,\n output: InitiateChunkedUploadResponseSchema,\n },\n uploadChunk: {\n method: 'PUT' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex',\n input: UploadChunkRequestSchema,\n output: UploadChunkResponseSchema,\n },\n completeChunkedUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/complete',\n input: CompleteChunkedUploadRequestSchema,\n output: CompleteChunkedUploadResponseSchema,\n },\n getUploadProgress: {\n method: 'GET' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/progress',\n output: UploadProgressSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { ObjectSchema } from '../data/object.zod';\nimport { AppSchema } from '../ui/app.zod';\nimport { MetadataTypeSchema, MetadataQuerySchema, MetadataQueryResultSchema, MetadataValidationResultSchema, MetadataBulkResultSchema, MetadataDependencySchema } from '../kernel/metadata-plugin.zod';\nimport { MetadataOverlaySchema } from '../kernel/metadata-customization.zod';\n\n/**\n * Metadata Service Protocol\n *\n * Defines the standard API contracts for the **@objectstack/metadata** package.\n * This is the single authority for ALL metadata-related services and APIs across\n * the entire platform, including Hono, Next.js, and NestJS adapters.\n *\n * ## Architecture\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ @objectstack/metadata — API Contracts │\n * │ │\n * │ CRUD │ Query/Search │ Bulk Ops │ Overlay │ Watch │\n * │ Import/Export│ Validation │ Type Reg │ Deps │ │\n * ├──────────────────────────────────────────────────────────────────┤\n * │ Hono Adapter │ Next.js Adapter │ NestJS Adapter │ CLI │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n */\n\n// ==========================================\n// 1. Legacy Responses (existing)\n// ==========================================\n\n/**\n * Single Object Definition Response\n * Returns the full JSON schema for an Entity (Fields, Actions, Config).\n */\nexport const ObjectDefinitionResponseSchema = BaseResponseSchema.extend({\n data: ObjectSchema.describe('Full Object Schema'),\n});\n\n/**\n * App Definition Response\n * Returns the navigation, branding, and layout for an App.\n */\nexport const AppDefinitionResponseSchema = BaseResponseSchema.extend({\n data: AppSchema.describe('Full App Configuration'),\n});\n\n/**\n * All Concepts Response\n * Bulk load lightweight definitions for autocomplete/pickers.\n */\nexport const ConceptListResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.object({\n name: z.string(),\n label: z.string(),\n icon: z.string().optional(),\n description: z.string().optional(),\n })).describe('List of available concepts (Objects, Apps, Flows)'),\n});\n\n// ==========================================\n// 2. CRUD Request / Response Schemas\n// ==========================================\n\n/**\n * Register (Create/Update) Metadata Request\n * POST /api/meta/:type\n * PUT /api/meta/:type/:name\n */\nexport const MetadataRegisterRequestSchema = z.object({\n type: MetadataTypeSchema.describe('Metadata type'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Item name (snake_case)'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Optional namespace'),\n});\n\n/**\n * Single Metadata Item Response\n * GET /api/meta/:type/:name\n */\nexport const MetadataItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n definition: z.record(z.string(), z.unknown()).describe('Metadata definition payload'),\n }).describe('Metadata item'),\n});\n\n/**\n * Metadata List Response\n * GET /api/meta/:type\n */\nexport const MetadataListResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.record(z.string(), z.unknown())).describe('Array of metadata definitions'),\n});\n\n/**\n * Metadata Names Response\n * GET /api/meta/:type/names\n */\nexport const MetadataNamesResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.string()).describe('Array of metadata item names'),\n});\n\n/**\n * Metadata Exists Response\n * GET /api/meta/:type/:name/exists\n */\nexport const MetadataExistsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n exists: z.boolean().describe('Whether the item exists'),\n }),\n});\n\n/**\n * Metadata Delete Response\n * DELETE /api/meta/:type/:name\n */\nexport const MetadataDeleteResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Deleted item name'),\n }),\n});\n\n// ==========================================\n// 3. Query / Search\n// ==========================================\n\n/**\n * Metadata Query Request\n * POST /api/meta/query\n */\nexport const MetadataQueryRequestSchema = MetadataQuerySchema.describe(\n 'Metadata query with filtering, sorting, and pagination',\n);\n\n/**\n * Metadata Query Response\n * POST /api/meta/query\n */\nexport const MetadataQueryResponseSchema = BaseResponseSchema.extend({\n data: MetadataQueryResultSchema.describe('Paginated query result'),\n});\n\n// ==========================================\n// 4. Bulk Operations\n// ==========================================\n\n/**\n * Bulk Register Request\n * POST /api/meta/bulk/register\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n })).min(1).describe('Items to register'),\n continueOnError: z.boolean().default(false).describe('Continue on individual failure'),\n validate: z.boolean().default(true).describe('Validate before registering'),\n});\n\n/**\n * Bulk Unregister Request\n * POST /api/meta/bulk/unregister\n */\nexport const MetadataBulkUnregisterRequestSchema = z.object({\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n })).min(1).describe('Items to unregister'),\n});\n\n/**\n * Bulk Operation Response\n * POST /api/meta/bulk/*\n */\nexport const MetadataBulkResponseSchema = BaseResponseSchema.extend({\n data: MetadataBulkResultSchema.describe('Bulk operation result'),\n});\n\n// ==========================================\n// 5. Overlay / Customization\n// ==========================================\n\n/**\n * Get Overlay Response\n * GET /api/meta/:type/:name/overlay\n */\nexport const MetadataOverlayResponseSchema = BaseResponseSchema.extend({\n data: MetadataOverlaySchema.optional().describe('Overlay definition, undefined if none'),\n});\n\n/**\n * Save Overlay Request\n * PUT /api/meta/:type/:name/overlay\n */\nexport const MetadataOverlaySaveRequestSchema = MetadataOverlaySchema.describe(\n 'Overlay to save',\n);\n\n/**\n * Get Effective (merged) Response\n * GET /api/meta/:type/:name/effective\n */\nexport const MetadataEffectiveResponseSchema = BaseResponseSchema.extend({\n data: z.record(z.string(), z.unknown()).optional()\n .describe('Effective metadata with all overlays applied'),\n});\n\n// ==========================================\n// 6. Import / Export\n// ==========================================\n\n/**\n * Export Metadata Request\n * POST /api/meta/export\n */\nexport const MetadataExportRequestSchema = z.object({\n types: z.array(z.string()).optional().describe('Filter by metadata types'),\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n format: z.enum(['json', 'yaml']).default('json').describe('Export format'),\n});\n\n/**\n * Export Metadata Response\n * POST /api/meta/export\n */\nexport const MetadataExportResponseSchema = BaseResponseSchema.extend({\n data: z.unknown().describe('Exported metadata bundle'),\n});\n\n/**\n * Import Metadata Request\n * POST /api/meta/import\n */\nexport const MetadataImportRequestSchema = z.object({\n data: z.unknown().describe('Metadata bundle to import'),\n conflictResolution: z.enum(['skip', 'overwrite', 'merge']).default('skip')\n .describe('Conflict resolution strategy'),\n validate: z.boolean().default(true).describe('Validate before import'),\n dryRun: z.boolean().default(false).describe('Dry run (no save)'),\n});\n\n/**\n * Import Metadata Response\n * POST /api/meta/import\n */\nexport const MetadataImportResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n total: z.number().int().min(0),\n imported: z.number().int().min(0),\n skipped: z.number().int().min(0),\n failed: z.number().int().min(0),\n errors: z.array(z.object({\n type: z.string(),\n name: z.string(),\n error: z.string(),\n })).optional(),\n }).describe('Import result'),\n});\n\n// ==========================================\n// 7. Validation\n// ==========================================\n\n/**\n * Validate Metadata Request\n * POST /api/meta/validate\n */\nexport const MetadataValidateRequestSchema = z.object({\n type: z.string().describe('Metadata type to validate against'),\n data: z.unknown().describe('Metadata payload to validate'),\n});\n\n/**\n * Validate Metadata Response\n * POST /api/meta/validate\n */\nexport const MetadataValidateResponseSchema = BaseResponseSchema.extend({\n data: MetadataValidationResultSchema.describe('Validation result'),\n});\n\n// ==========================================\n// 8. Type Registry\n// ==========================================\n\n/**\n * List Registered Types Response\n * GET /api/meta/types\n */\nexport const MetadataTypesResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.string()).describe('Registered metadata type identifiers'),\n});\n\n/**\n * Type Info Response\n * GET /api/meta/types/:type\n */\nexport const MetadataTypeInfoResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type identifier'),\n label: z.string().describe('Display label'),\n description: z.string().optional().describe('Description'),\n filePatterns: z.array(z.string()).describe('File glob patterns'),\n supportsOverlay: z.boolean().describe('Overlay support'),\n domain: z.string().describe('Protocol domain'),\n }).optional().describe('Type info'),\n});\n\n// ==========================================\n// 9. Dependency Tracking\n// ==========================================\n\n/**\n * Dependencies Response\n * GET /api/meta/:type/:name/dependencies\n */\nexport const MetadataDependenciesResponseSchema = BaseResponseSchema.extend({\n data: z.array(MetadataDependencySchema).describe('Items this item depends on'),\n});\n\n/**\n * Dependents Response\n * GET /api/meta/:type/:name/dependents\n */\nexport const MetadataDependentsResponseSchema = BaseResponseSchema.extend({\n data: z.array(MetadataDependencySchema).describe('Items that depend on this item'),\n});\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type ObjectDefinitionResponse = z.infer;\nexport type AppDefinitionResponse = z.infer;\nexport type ConceptListResponse = z.infer;\nexport type MetadataRegisterRequest = z.infer;\nexport type MetadataItemResponse = z.infer;\nexport type MetadataListResponse = z.infer;\nexport type MetadataNamesResponse = z.infer;\nexport type MetadataExistsResponse = z.infer;\nexport type MetadataDeleteResponse = z.infer;\nexport type MetadataQueryResponse = z.infer;\nexport type MetadataBulkResponse = z.infer;\nexport type MetadataOverlayResponse = z.infer;\nexport type MetadataEffectiveResponse = z.infer;\nexport type MetadataExportResponse = z.infer;\nexport type MetadataImportResponse = z.infer;\nexport type MetadataValidateResponse = z.infer;\nexport type MetadataTypesResponse = z.infer;\nexport type MetadataTypeInfoResponse = z.infer;\nexport type MetadataDependenciesResponse = z.infer;\nexport type MetadataDependentsResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { CoreServiceName, ServiceCriticalitySchema } from '../system/core-services.zod';\n\n/**\n * # HttpDispatcher Protocol\n * \n * Defines how the ObjectStack HttpDispatcher routes incoming API requests\n * to the correct kernel service based on URL prefix matching.\n * \n * The dispatcher is the central routing component that:\n * 1. Matches incoming request URLs against registered route prefixes\n * 2. Delegates to the corresponding CoreService implementation\n * 3. Returns 503 Service Unavailable when a service is not registered\n * 4. Supports dynamic route registration from plugins via contributes.routes\n * \n * Architecture alignment:\n * - Kubernetes: API server aggregation layer\n * - Eclipse: Extension registry routing\n * - VS Code: Command palette routing\n */\n\n// ============================================================================\n// Route Definition\n// ============================================================================\n\n/**\n * Dispatcher Route Schema\n * Maps a URL prefix to a kernel service.\n * \n * @example\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"authRequired\": true,\n * \"criticality\": \"required\"\n * }\n */\nexport const DispatcherRouteSchema = z.object({\n /**\n * URL path prefix for routing.\n * Incoming requests matching this prefix are routed to the target service.\n * Must start with '/'.\n */\n prefix: z.string().regex(/^\\//).describe('URL path prefix for routing (e.g. /api/v1/data)'),\n \n /**\n * Target core service name.\n * The service that handles requests matching this prefix.\n */\n service: CoreServiceName.describe('Target core service name'),\n \n /**\n * Whether requests to this route require authentication.\n * Discovery endpoint is typically public; most others require auth.\n * @default true\n */\n authRequired: z.boolean().default(true).describe('Whether authentication is required'),\n \n /**\n * Service criticality level.\n * Determines behavior when the service is unavailable:\n * - required: return 500 Internal Server Error\n * - core: return 503 with degraded notice\n * - optional: return 503 Service Unavailable\n * @default 'optional'\n */\n criticality: ServiceCriticalitySchema.default('optional')\n .describe('Service criticality level for unavailability handling'),\n \n /**\n * Required permissions for accessing this route namespace.\n * Applied as a baseline before individual endpoint permission checks.\n */\n permissions: z.array(z.string()).optional()\n .describe('Required permissions for this route namespace'),\n});\n\nexport type DispatcherRoute = z.infer;\nexport type DispatcherRouteInput = z.input;\n\n// ============================================================================\n// Dispatcher Configuration\n// ============================================================================\n\n/**\n * Dispatcher Configuration Schema\n * Complete configuration for the HttpDispatcher routing table.\n * \n * @example\n * {\n * \"routes\": [\n * { \"prefix\": \"/api/v1/discovery\", \"service\": \"metadata\", \"authRequired\": false },\n * { \"prefix\": \"/api/v1/meta\", \"service\": \"metadata\" },\n * { \"prefix\": \"/api/v1/data\", \"service\": \"data\", \"criticality\": \"required\" },\n * { \"prefix\": \"/api/v1/auth\", \"service\": \"auth\", \"criticality\": \"required\" },\n * { \"prefix\": \"/api/v1/ai\", \"service\": \"ai\" }\n * ],\n * \"fallback\": \"404\"\n * }\n */\nexport const DispatcherConfigSchema = z.object({\n /**\n * Registered route mappings.\n * Routes are matched by longest-prefix-first strategy.\n */\n routes: z.array(DispatcherRouteSchema).describe('Route-to-service mappings'),\n \n /**\n * Behavior when no route matches the request.\n * - 404: Return 404 Not Found (default)\n * - proxy: Forward to a configured proxy target\n * - custom: Delegate to a custom handler\n * @default '404'\n */\n fallback: z.enum(['404', 'proxy', 'custom']).default('404')\n .describe('Behavior when no route matches'),\n \n /**\n * Proxy target URL for fallback: 'proxy' mode.\n */\n proxyTarget: z.string().url().optional()\n .describe('Proxy target URL when fallback is \"proxy\"'),\n});\n\nexport type DispatcherConfig = z.infer;\nexport type DispatcherConfigInput = z.input;\n\n// ============================================================================\n// Default Route Table\n// ============================================================================\n\n/**\n * Default route table for the ObjectStack HttpDispatcher.\n * Maps all Protocol namespaces to their corresponding services.\n * \n * This is the recommended baseline configuration. Plugins can extend\n * this table by declaring routes in their manifest's contributes.routes.\n */\nexport const DEFAULT_DISPATCHER_ROUTES: DispatcherRouteInput[] = [\n // Discovery (public)\n { prefix: '/api/v1/discovery', service: 'metadata', authRequired: false, criticality: 'required' },\n \n // Health (public)\n { prefix: '/api/v1/health', service: 'metadata', authRequired: false, criticality: 'required' },\n \n // Required Services\n { prefix: '/api/v1/meta', service: 'metadata', criticality: 'required' },\n { prefix: '/api/v1/data', service: 'data', criticality: 'required' },\n { prefix: '/api/v1/auth', service: 'auth', criticality: 'required' },\n \n // Optional Services (plugin-provided)\n { prefix: '/api/v1/packages', service: 'metadata' },\n { prefix: '/api/v1/ui', service: 'ui' }, // @deprecated — use /api/v1/meta/view and /api/v1/meta/dashboard instead\n { prefix: '/api/v1/workflow', service: 'workflow' },\n { prefix: '/api/v1/analytics', service: 'analytics' },\n { prefix: '/api/v1/automation', service: 'automation' },\n { prefix: '/api/v1/storage', service: 'file-storage' },\n { prefix: '/api/v1/feed', service: 'data' },\n { prefix: '/api/v1/i18n', service: 'i18n' },\n { prefix: '/api/v1/notifications', service: 'notification' },\n { prefix: '/api/v1/realtime', service: 'realtime' },\n { prefix: '/api/v1/ai', service: 'ai' },\n];\n\n// ============================================================================\n// Dispatcher Error Codes\n// ============================================================================\n\n/**\n * Semantic HTTP error codes used by the Dispatcher.\n *\n * The dispatcher MUST distinguish between these four failure modes so that\n * clients (and developers) can understand *why* an API call failed:\n *\n * - `404` – Route Not Found: no route is registered for this path.\n * - `405` – Method Not Allowed: route exists but the HTTP method is not supported.\n * - `501` – Not Implemented: route is declared but the handler is a stub / not yet coded.\n * - `503` – Service Unavailable: service exists but is temporarily down or not loaded.\n *\n * Note: These are string representations of HTTP status codes for use in enum\n * matching. The `DispatcherErrorResponseSchema.error.code` field carries the\n * numeric HTTP status code for direct use in HTTP responses.\n */\nexport const DispatcherErrorCode = z.enum(['404', '405', '501', '503']).describe(\n '404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable'\n);\n\nexport type DispatcherErrorCode = z.infer;\n\n/**\n * Dispatcher Error Response Schema\n *\n * Standardised error envelope returned by the dispatcher when a request cannot\n * be fulfilled. Adapters MUST use this shape (or a superset) for all non-2xx\n * responses so that clients can programmatically distinguish failure modes.\n */\nexport const DispatcherErrorResponseSchema = z.object({\n /** Always `false` for error responses */\n success: z.literal(false),\n error: z.object({\n /** HTTP status code */\n code: z.number().int().describe('HTTP status code (404, 405, 501, 503, …)'),\n /** Human-readable error message */\n message: z.string().describe('Human-readable error message'),\n /**\n * Machine-readable error type for programmatic branching.\n */\n type: z.enum([\n 'ROUTE_NOT_FOUND',\n 'METHOD_NOT_ALLOWED',\n 'NOT_IMPLEMENTED',\n 'SERVICE_UNAVAILABLE',\n ]).optional().describe('Machine-readable error type'),\n /** Route that was requested */\n route: z.string().optional().describe('Requested route path'),\n /** Service that the route maps to (if known) */\n service: z.string().optional().describe('Target service name, if resolvable'),\n /** Guidance for the developer */\n hint: z.string().optional().describe('Actionable hint for the developer (e.g., \"Install plugin-workflow\")'),\n }),\n});\n\nexport type DispatcherErrorResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\nimport { MiddlewareConfigSchema } from '../system/http-server.zod';\n\n/**\n * REST API Plugin Protocol\n * \n * Defines the schema for REST API plugins that register Discovery, Metadata,\n * Data CRUD, Batch, and Permission routes with the HTTP Dispatcher.\n * \n * This plugin type implements Phase 2 of the API Protocol implementation plan,\n * providing standardized REST endpoints with:\n * - Request validation middleware using Zod schemas\n * - Response envelope wrapping with BaseResponseSchema\n * - Error handling using ApiErrorSchema\n * - OpenAPI documentation auto-generation\n * \n * Features:\n * - Route registration for core API endpoints\n * - Automatic schema-based validation\n * - Standardized request/response envelopes\n * - OpenAPI/Swagger documentation generation\n * \n * Architecture Alignment:\n * - Salesforce: REST API with metadata and data CRUD\n * - Microsoft Dynamics: Web API with entity operations\n * - Strapi: Auto-generated REST endpoints from schemas\n * \n * @example Plugin Manifest\n * ```typescript\n * {\n * \"name\": \"rest_api\",\n * \"version\": \"1.0.0\",\n * \"type\": \"server\",\n * \"contributes\": {\n * \"routes\": [\n * {\n * \"prefix\": \"/api/v1/discovery\",\n * \"service\": \"metadata\",\n * \"methods\": [\"getDiscovery\"],\n * \"middleware\": [\n * { \"name\": \"response_envelope\", \"type\": \"transformation\", \"enabled\": true }\n * ]\n * },\n * {\n * \"prefix\": \"/api/v1/meta\",\n * \"service\": \"metadata\",\n * \"methods\": [\"getMetaTypes\", \"getMetaItems\", \"getMetaItem\", \"saveMetaItem\"],\n * \"middleware\": [\n * { \"name\": \"auth\", \"type\": \"authentication\", \"enabled\": true },\n * { \"name\": \"request_validation\", \"type\": \"validation\", \"enabled\": true }\n * ]\n * },\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"methods\": [\"findData\", \"getData\", \"createData\", \"updateData\", \"deleteData\"]\n * }\n * ]\n * }\n * }\n * ```\n */\n\n// ==========================================\n// REST API Route Categories\n// ==========================================\n\n/**\n * REST API Route Category Enum\n * Categorizes REST API routes by their primary function\n */\nexport const RestApiRouteCategory = z.enum([\n 'discovery', // API discovery and capabilities\n 'metadata', // Metadata operations (objects, fields, views)\n 'data', // Data CRUD operations\n 'batch', // Batch/bulk operations\n 'permission', // Permission/authorization checks\n 'analytics', // Analytics and reporting\n 'automation', // Automation triggers and flows\n 'workflow', // Workflow state management\n 'ui', // UI metadata (views, layouts)\n 'realtime', // Realtime/WebSocket\n 'notification', // Notification management\n 'ai', // AI operations (NLQ, chat)\n 'i18n', // Internationalization\n]);\n\nexport type RestApiRouteCategory = z.infer;\n\n// ==========================================\n// Route Registration Schema\n// ==========================================\n\n/**\n * Handler Implementation Status\n * Shared enum for tracking whether an endpoint has a real handler.\n * Used by both `RestApiEndpointSchema` and `RouteCoverageEntrySchema`.\n *\n * - `implemented` – A real handler is coded and registered.\n * - `stub` – A placeholder handler exists that returns 501 Not Implemented.\n * - `planned` – Declared in the protocol spec but not yet implemented.\n */\nexport const HandlerStatusSchema = z.enum(['implemented', 'stub', 'planned']);\nexport type HandlerStatus = z.infer;\n\n/**\n * REST API Endpoint Schema\n * Defines a single REST API endpoint with its metadata\n * \n * @example Discovery Endpoint\n * {\n * \"method\": \"GET\",\n * \"path\": \"/api/v1/discovery\",\n * \"handler\": \"getDiscovery\",\n * \"category\": \"discovery\",\n * \"public\": true,\n * \"description\": \"Get API discovery information\"\n * }\n */\nexport const RestApiEndpointSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method for this endpoint'),\n \n /**\n * URL path pattern (supports parameters like :id)\n */\n path: z.string().describe('URL path pattern (e.g., /api/v1/data/:object/:id)'),\n \n /**\n * Handler reference (protocol method name)\n */\n handler: z.string().describe('Protocol method name or handler identifier'),\n \n /**\n * Route category\n */\n category: RestApiRouteCategory.describe('Route category'),\n \n /**\n * Whether endpoint is publicly accessible (no auth required)\n */\n public: z.boolean().default(false).describe('Is publicly accessible without authentication'),\n \n /**\n * Required permissions\n */\n permissions: z.array(z.string()).optional().describe('Required permissions (e.g., [\"data.read\", \"object.account.read\"])'),\n \n /**\n * OpenAPI documentation metadata\n */\n summary: z.string().optional().describe('Short description for OpenAPI'),\n description: z.string().optional().describe('Detailed description for OpenAPI'),\n tags: z.array(z.string()).optional().describe('OpenAPI tags for grouping'),\n \n /**\n * Request/Response schema references\n */\n requestSchema: z.string().optional().describe('Request schema name (for validation)'),\n responseSchema: z.string().optional().describe('Response schema name (for documentation)'),\n \n /**\n * Performance and reliability settings\n */\n timeout: z.number().int().optional().describe('Request timeout in milliseconds'),\n rateLimit: z.string().optional().describe('Rate limit policy name'),\n cacheable: z.boolean().default(false).describe('Whether response can be cached'),\n cacheTtl: z.number().int().optional().describe('Cache TTL in seconds'),\n\n /**\n * Handler implementation status.\n * Tracks whether this endpoint has a real handler or is only declared.\n *\n * - `implemented` – A real handler is coded and registered.\n * - `stub` – A placeholder handler exists that returns 501 Not Implemented.\n * - `planned` – Declared in the protocol spec but not yet implemented.\n * @default 'implemented'\n */\n handlerStatus: HandlerStatusSchema.optional()\n .describe('Handler implementation status: implemented (default if omitted), stub, or planned'),\n});\n\nexport type RestApiEndpoint = z.infer;\n\n/**\n * REST API Route Registration Schema\n * Registers a group of related endpoints under a common prefix\n * \n * @example Data CRUD Routes\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"category\": \"data\",\n * \"endpoints\": [\n * { \"method\": \"GET\", \"path\": \"/:object\", \"handler\": \"findData\" },\n * { \"method\": \"GET\", \"path\": \"/:object/:id\", \"handler\": \"getData\" },\n * { \"method\": \"POST\", \"path\": \"/:object\", \"handler\": \"createData\" },\n * { \"method\": \"PATCH\", \"path\": \"/:object/:id\", \"handler\": \"updateData\" },\n * { \"method\": \"DELETE\", \"path\": \"/:object/:id\", \"handler\": \"deleteData\" }\n * ],\n * \"middleware\": [\n * { \"name\": \"auth\", \"type\": \"authentication\", \"enabled\": true },\n * { \"name\": \"validation\", \"type\": \"validation\", \"enabled\": true },\n * { \"name\": \"response_envelope\", \"type\": \"transformation\", \"enabled\": true }\n * ]\n * }\n */\nexport const RestApiRouteRegistrationSchema = z.object({\n /**\n * URL prefix for this route group (e.g., /api/v1/data)\n */\n prefix: z.string().regex(/^\\//).describe('URL path prefix for this route group'),\n \n /**\n * Service name that handles these routes\n */\n service: z.string().describe('Core service name (metadata, data, auth, etc.)'),\n \n /**\n * Route category\n */\n category: RestApiRouteCategory.describe('Primary category for this route group'),\n \n /**\n * Protocol methods implemented\n */\n methods: z.array(z.string()).optional().describe('Protocol method names implemented'),\n \n /**\n * Detailed endpoint definitions\n */\n endpoints: z.array(RestApiEndpointSchema).optional().describe('Endpoint definitions'),\n \n /**\n * Middleware applied to all routes in this group\n */\n middleware: z.array(MiddlewareConfigSchema).optional().describe('Middleware stack for this route group'),\n \n /**\n * Whether authentication is required for all routes\n */\n authRequired: z.boolean().default(true).describe('Whether authentication is required by default'),\n \n /**\n * OpenAPI documentation\n */\n documentation: z.object({\n title: z.string().optional().describe('Route group title'),\n description: z.string().optional().describe('Route group description'),\n tags: z.array(z.string()).optional().describe('OpenAPI tags'),\n }).optional().describe('Documentation metadata for this route group'),\n});\n\nexport type RestApiRouteRegistration = z.infer;\n\n// ==========================================\n// Request Validation Configuration\n// ==========================================\n\n/**\n * Request Validation Mode Enum\n * Defines how validation errors are handled\n */\nexport const ValidationMode = z.enum([\n 'strict', // Reject requests with validation errors (400 Bad Request)\n 'permissive', // Log validation errors but allow request to proceed\n 'strip', // Remove invalid fields and continue with valid data\n]);\n\nexport type ValidationMode = z.infer;\n\n/**\n * Request Validation Configuration Schema\n * Configures Zod-based request validation middleware\n * \n * @example\n * {\n * \"enabled\": true,\n * \"mode\": \"strict\",\n * \"validateBody\": true,\n * \"validateQuery\": true,\n * \"validateParams\": true,\n * \"includeFieldErrors\": true\n * }\n */\nexport const RequestValidationConfigSchema = z.object({\n /**\n * Enable request validation\n */\n enabled: z.boolean().default(true).describe('Enable automatic request validation'),\n \n /**\n * Validation mode\n */\n mode: ValidationMode.default('strict').describe('How to handle validation errors'),\n \n /**\n * Validate request body\n */\n validateBody: z.boolean().default(true).describe('Validate request body against schema'),\n \n /**\n * Validate query parameters\n */\n validateQuery: z.boolean().default(true).describe('Validate query string parameters'),\n \n /**\n * Validate URL parameters\n */\n validateParams: z.boolean().default(true).describe('Validate URL path parameters'),\n \n /**\n * Validate request headers\n */\n validateHeaders: z.boolean().default(false).describe('Validate request headers'),\n \n /**\n * Include detailed field errors in response\n */\n includeFieldErrors: z.boolean().default(true).describe('Include field-level error details in response'),\n \n /**\n * Custom error message prefix\n */\n errorPrefix: z.string().optional().describe('Custom prefix for validation error messages'),\n \n /**\n * Schema registry reference\n */\n schemaRegistry: z.string().optional().describe('Schema registry name to use for validation'),\n});\n\nexport type RequestValidationConfig = z.infer;\nexport type RequestValidationConfigInput = z.input;\n\n// ==========================================\n// Response Envelope Configuration\n// ==========================================\n\n/**\n * Response Envelope Configuration Schema\n * Configures automatic response wrapping with BaseResponseSchema\n * \n * @example\n * {\n * \"enabled\": true,\n * \"includeMetadata\": true,\n * \"includeTimestamp\": true,\n * \"includeRequestId\": true,\n * \"includeDuration\": true\n * }\n */\nexport const ResponseEnvelopeConfigSchema = z.object({\n /**\n * Enable response envelope wrapping\n */\n enabled: z.boolean().default(true).describe('Enable automatic response envelope wrapping'),\n \n /**\n * Include metadata object\n */\n includeMetadata: z.boolean().default(true).describe('Include meta object in responses'),\n \n /**\n * Include timestamp in metadata\n */\n includeTimestamp: z.boolean().default(true).describe('Include timestamp in response metadata'),\n \n /**\n * Include request ID in metadata\n */\n includeRequestId: z.boolean().default(true).describe('Include requestId in response metadata'),\n \n /**\n * Include request duration in metadata\n */\n includeDuration: z.boolean().default(false).describe('Include request duration in ms'),\n \n /**\n * Include trace ID for distributed tracing\n */\n includeTraceId: z.boolean().default(false).describe('Include distributed traceId'),\n \n /**\n * Custom metadata fields\n */\n customMetadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata fields to include'),\n \n /**\n * Whether to wrap already-wrapped responses\n */\n skipIfWrapped: z.boolean().default(true).describe('Skip wrapping if response already has success field'),\n});\n\nexport type ResponseEnvelopeConfig = z.infer;\nexport type ResponseEnvelopeConfigInput = z.input;\n\n// ==========================================\n// Error Handling Configuration\n// ==========================================\n\n/**\n * Error Handling Configuration Schema\n * Configures error handling and ApiErrorSchema formatting\n * \n * @example\n * {\n * \"enabled\": true,\n * \"includeStackTrace\": false,\n * \"logErrors\": true,\n * \"exposeInternalErrors\": false,\n * \"customErrorMessages\": {\n * \"validation_error\": \"The request data is invalid. Please check your input.\"\n * }\n * }\n */\nexport const ErrorHandlingConfigSchema = z.object({\n /**\n * Enable standardized error handling\n */\n enabled: z.boolean().default(true).describe('Enable standardized error handling'),\n \n /**\n * Include stack traces in error responses (dev only)\n */\n includeStackTrace: z.boolean().default(false).describe('Include stack traces in error responses'),\n \n /**\n * Log errors to logger\n */\n logErrors: z.boolean().default(true).describe('Log errors to system logger'),\n \n /**\n * Expose internal error details\n */\n exposeInternalErrors: z.boolean().default(false).describe('Expose internal error details in responses'),\n \n /**\n * Include request ID in errors\n */\n includeRequestId: z.boolean().default(true).describe('Include requestId in error responses'),\n \n /**\n * Include timestamp in errors\n */\n includeTimestamp: z.boolean().default(true).describe('Include timestamp in error responses'),\n \n /**\n * Include error documentation URLs\n */\n includeDocumentation: z.boolean().default(true).describe('Include documentation URLs for errors'),\n \n /**\n * Documentation base URL\n */\n documentationBaseUrl: z.string().url().optional().describe('Base URL for error documentation'),\n \n /**\n * Custom error messages by code\n */\n customErrorMessages: z.record(z.string(), z.string()).optional()\n .describe('Custom error messages by error code'),\n \n /**\n * Sensitive fields to redact from error details\n */\n redactFields: z.array(z.string()).optional().describe('Field names to redact from error details'),\n});\n\nexport type ErrorHandlingConfig = z.infer;\nexport type ErrorHandlingConfigInput = z.input;\n\n// ==========================================\n// OpenAPI Documentation Configuration\n// ==========================================\n\n/**\n * OpenAPI Generation Configuration Schema\n * Configures automatic OpenAPI documentation generation\n * \n * @example\n * {\n * \"enabled\": true,\n * \"version\": \"3.0.0\",\n * \"title\": \"ObjectStack API\",\n * \"description\": \"ObjectStack REST API\",\n * \"outputPath\": \"/api/docs/openapi.json\",\n * \"uiPath\": \"/api/docs\",\n * \"includeInternal\": false,\n * \"generateSchemas\": true\n * }\n */\nexport const OpenApiGenerationConfigSchema = z.object({\n /**\n * Enable OpenAPI generation\n */\n enabled: z.boolean().default(true).describe('Enable automatic OpenAPI documentation generation'),\n \n /**\n * OpenAPI specification version\n */\n version: z.enum(['3.0.0', '3.0.1', '3.0.2', '3.0.3', '3.1.0']).default('3.0.3')\n .describe('OpenAPI specification version'),\n \n /**\n * API title\n */\n title: z.string().default('ObjectStack API').describe('API title'),\n \n /**\n * API description\n */\n description: z.string().optional().describe('API description'),\n \n /**\n * API version\n */\n apiVersion: z.string().default('1.0.0').describe('API version'),\n \n /**\n * Output path for OpenAPI spec\n */\n outputPath: z.string().default('/api/docs/openapi.json').describe('URL path to serve OpenAPI JSON'),\n \n /**\n * UI path for Swagger/Redoc\n */\n uiPath: z.string().default('/api/docs').describe('URL path to serve documentation UI'),\n \n /**\n * UI framework to use\n */\n uiFramework: z.enum(['swagger-ui', 'redoc', 'rapidoc', 'elements']).default('swagger-ui')\n .describe('Documentation UI framework'),\n \n /**\n * Include internal/admin endpoints\n */\n includeInternal: z.boolean().default(false).describe('Include internal endpoints in documentation'),\n \n /**\n * Generate JSON schemas from Zod\n */\n generateSchemas: z.boolean().default(true).describe('Auto-generate schemas from Zod definitions'),\n \n /**\n * Include examples in documentation\n */\n includeExamples: z.boolean().default(true).describe('Include request/response examples'),\n \n /**\n * Server URLs\n */\n servers: z.array(z.object({\n url: z.string().describe('Server URL'),\n description: z.string().optional().describe('Server description'),\n })).optional().describe('Server URLs for API'),\n \n /**\n * Contact information\n */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('API contact information'),\n \n /**\n * License information\n */\n license: z.object({\n name: z.string().describe('License name'),\n url: z.string().url().optional().describe('License URL'),\n }).optional().describe('API license information'),\n \n /**\n * Security schemes\n */\n securitySchemes: z.record(z.string(), z.object({\n type: z.enum(['apiKey', 'http', 'oauth2', 'openIdConnect']),\n scheme: z.string().optional(),\n bearerFormat: z.string().optional(),\n })).optional().describe('Security scheme definitions'),\n});\n\nexport type OpenApiGenerationConfig = z.infer;\nexport type OpenApiGenerationConfigInput = z.input;\n\n// ==========================================\n// REST API Plugin Configuration\n// ==========================================\n\n/**\n * REST API Plugin Configuration Schema\n * Complete configuration for REST API plugin\n * \n * @example\n * {\n * \"enabled\": true,\n * \"basePath\": \"/api\",\n * \"version\": \"v1\",\n * \"routes\": [...],\n * \"validation\": { \"enabled\": true, \"mode\": \"strict\" },\n * \"responseEnvelope\": { \"enabled\": true, \"includeMetadata\": true },\n * \"errorHandling\": { \"enabled\": true, \"includeStackTrace\": false },\n * \"openApi\": { \"enabled\": true, \"title\": \"ObjectStack API\" }\n * }\n */\nexport const RestApiPluginConfigSchema = z.object({\n /**\n * Enable REST API plugin\n */\n enabled: z.boolean().default(true).describe('Enable REST API plugin'),\n \n /**\n * API base path\n */\n basePath: z.string().default('/api').describe('Base path for all API routes'),\n \n /**\n * API version\n */\n version: z.string().default('v1').describe('API version identifier'),\n \n /**\n * Route registrations\n */\n routes: z.array(RestApiRouteRegistrationSchema).describe('Route registrations'),\n \n /**\n * Request validation configuration\n */\n validation: RequestValidationConfigSchema.optional().describe('Request validation configuration'),\n \n /**\n * Response envelope configuration\n */\n responseEnvelope: ResponseEnvelopeConfigSchema.optional().describe('Response envelope configuration'),\n \n /**\n * Error handling configuration\n */\n errorHandling: ErrorHandlingConfigSchema.optional().describe('Error handling configuration'),\n \n /**\n * OpenAPI documentation configuration\n */\n openApi: OpenApiGenerationConfigSchema.optional().describe('OpenAPI documentation configuration'),\n \n /**\n * Global middleware applied to all routes\n */\n globalMiddleware: z.array(MiddlewareConfigSchema).optional().describe('Global middleware stack'),\n \n /**\n * CORS configuration\n */\n cors: z.object({\n enabled: z.boolean().default(true),\n origins: z.array(z.string()).optional(),\n methods: z.array(HttpMethod).optional(),\n credentials: z.boolean().default(true),\n }).optional().describe('CORS configuration'),\n \n /**\n * Performance settings\n */\n performance: z.object({\n enableCompression: z.boolean().default(true).describe('Enable response compression'),\n enableETag: z.boolean().default(true).describe('Enable ETag generation'),\n enableCaching: z.boolean().default(true).describe('Enable HTTP caching'),\n defaultCacheTtl: z.number().int().default(300).describe('Default cache TTL in seconds'),\n }).optional().describe('Performance optimization settings'),\n});\n\nexport type RestApiPluginConfig = z.infer;\nexport type RestApiPluginConfigInput = z.input;\n\n// ==========================================\n// Default Route Registrations\n// ==========================================\n\n/**\n * Default Discovery Routes\n * Standard routes for API discovery endpoint\n */\nexport const DEFAULT_DISCOVERY_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/discovery',\n service: 'metadata',\n category: 'discovery',\n methods: ['getDiscovery'],\n authRequired: false,\n endpoints: [{\n method: 'GET',\n path: '',\n handler: 'getDiscovery',\n category: 'discovery',\n public: true,\n summary: 'Get API discovery information',\n description: 'Returns API version, capabilities, and available routes',\n tags: ['Discovery'],\n responseSchema: 'GetDiscoveryResponseSchema',\n cacheable: true,\n cacheTtl: 3600, // Cache for 1 hour as discovery info rarely changes\n }],\n middleware: [\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n/**\n * Default Metadata Routes\n * Standard routes for metadata operations\n * \n * Note: getMetaItemCached is not a separate endpoint - it's handled by the getMetaItem\n * endpoint with HTTP cache headers (ETag, If-None-Match, etc.) for conditional requests.\n */\nexport const DEFAULT_METADATA_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/meta',\n service: 'metadata',\n category: 'metadata',\n methods: ['getMetaTypes', 'getMetaItems', 'getMetaItem', 'saveMetaItem'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '',\n handler: 'getMetaTypes',\n category: 'metadata',\n public: false,\n summary: 'List all metadata types',\n description: 'Returns available metadata types (object, field, view, etc.)',\n tags: ['Metadata'],\n responseSchema: 'GetMetaTypesResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:type',\n handler: 'getMetaItems',\n category: 'metadata',\n public: false,\n summary: 'List metadata items of a type',\n description: 'Returns all items of the specified metadata type',\n tags: ['Metadata'],\n responseSchema: 'GetMetaItemsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:type/:name',\n handler: 'getMetaItem',\n category: 'metadata',\n public: false,\n summary: 'Get specific metadata item',\n description: 'Returns a specific metadata item by type and name',\n tags: ['Metadata'],\n requestSchema: 'GetMetaItemRequestSchema',\n responseSchema: 'GetMetaItemResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'PUT',\n path: '/:type/:name',\n handler: 'saveMetaItem',\n category: 'metadata',\n public: false,\n summary: 'Create or update metadata item',\n description: 'Creates or updates a metadata item',\n tags: ['Metadata'],\n requestSchema: 'SaveMetaItemRequestSchema',\n responseSchema: 'SaveMetaItemResponseSchema',\n permissions: ['metadata.write'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n/**\n * Default Data CRUD Routes\n * Standard routes for data operations\n */\nexport const DEFAULT_DATA_CRUD_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/data',\n service: 'data',\n category: 'data',\n methods: ['findData', 'getData', 'createData', 'updateData', 'deleteData'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/:object',\n handler: 'findData',\n category: 'data',\n public: false,\n summary: 'Query records',\n description: 'Query records with filtering, sorting, and pagination',\n tags: ['Data'],\n requestSchema: 'FindDataRequestSchema',\n responseSchema: 'ListRecordResponseSchema',\n permissions: ['data.read'],\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/:object/:id',\n handler: 'getData',\n category: 'data',\n public: false,\n summary: 'Get record by ID',\n description: 'Retrieve a single record by its ID',\n tags: ['Data'],\n requestSchema: 'IdRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.read'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object',\n handler: 'createData',\n category: 'data',\n public: false,\n summary: 'Create record',\n description: 'Create a new record',\n tags: ['Data'],\n requestSchema: 'CreateRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.create'],\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/:object/:id',\n handler: 'updateData',\n category: 'data',\n public: false,\n summary: 'Update record',\n description: 'Update an existing record',\n tags: ['Data'],\n requestSchema: 'UpdateRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.update'],\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/:object/:id',\n handler: 'deleteData',\n category: 'data',\n public: false,\n summary: 'Delete record',\n description: 'Delete a record by ID',\n tags: ['Data'],\n requestSchema: 'IdRequestSchema',\n responseSchema: 'DeleteResponseSchema',\n permissions: ['data.delete'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n/**\n * Default Batch Routes\n * Standard routes for batch operations\n */\nexport const DEFAULT_BATCH_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/data/:object',\n service: 'data',\n category: 'batch',\n methods: ['batchData', 'createManyData', 'updateManyData', 'deleteManyData'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/batch',\n handler: 'batchData',\n category: 'batch',\n public: false,\n summary: 'Batch operation',\n description: 'Execute a batch operation (create, update, upsert, delete)',\n tags: ['Batch'],\n requestSchema: 'BatchUpdateRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.batch'],\n timeout: 60000, // 60 seconds for batch operations\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/createMany',\n handler: 'createManyData',\n category: 'batch',\n public: false,\n summary: 'Batch create',\n description: 'Create multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'CreateManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.create', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/updateMany',\n handler: 'updateManyData',\n category: 'batch',\n public: false,\n summary: 'Batch update',\n description: 'Update multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'UpdateManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.update', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/deleteMany',\n handler: 'deleteManyData',\n category: 'batch',\n public: false,\n summary: 'Batch delete',\n description: 'Delete multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'DeleteManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.delete', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n/**\n * Default Permission Routes\n * Standard routes for permission checking\n */\nexport const DEFAULT_PERMISSION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/auth',\n service: 'auth',\n category: 'permission',\n methods: ['checkPermission', 'getObjectPermissions', 'getEffectivePermissions'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/check',\n handler: 'checkPermission',\n category: 'permission',\n public: false,\n summary: 'Check permission',\n description: 'Check if current user has a specific permission',\n tags: ['Permission'],\n requestSchema: 'CheckPermissionRequestSchema',\n responseSchema: 'CheckPermissionResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/permissions/:object',\n handler: 'getObjectPermissions',\n category: 'permission',\n public: false,\n summary: 'Get object permissions',\n description: 'Get all permissions for a specific object',\n tags: ['Permission'],\n responseSchema: 'ObjectPermissionsResponseSchema',\n cacheable: true,\n cacheTtl: 300,\n },\n {\n method: 'GET',\n path: '/permissions/effective',\n handler: 'getEffectivePermissions',\n category: 'permission',\n public: false,\n summary: 'Get effective permissions',\n description: 'Get all effective permissions for current user',\n tags: ['Permission'],\n responseSchema: 'EffectivePermissionsResponseSchema',\n cacheable: true,\n cacheTtl: 300,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// View Management Routes\n// ==========================================\n\n/**\n * Default View Management Routes\n * Standard routes for UI view CRUD operations\n */\nexport const DEFAULT_VIEW_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/ui',\n service: 'ui',\n category: 'ui',\n methods: ['listViews', 'getView', 'createView', 'updateView', 'deleteView'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/views/:object',\n handler: 'listViews',\n category: 'ui',\n public: false,\n summary: 'List views for an object',\n description: 'Returns all views (list, form) for the specified object',\n tags: ['Views', 'UI'],\n responseSchema: 'ListViewsResponseSchema',\n cacheable: true,\n cacheTtl: 1800,\n },\n {\n method: 'GET',\n path: '/views/:object/:viewId',\n handler: 'getView',\n category: 'ui',\n public: false,\n summary: 'Get a specific view',\n description: 'Returns a specific view definition by object and view ID',\n tags: ['Views', 'UI'],\n responseSchema: 'GetViewResponseSchema',\n cacheable: true,\n cacheTtl: 1800,\n },\n {\n method: 'POST',\n path: '/views/:object',\n handler: 'createView',\n category: 'ui',\n public: false,\n summary: 'Create a new view',\n description: 'Creates a new view definition for the specified object',\n tags: ['Views', 'UI'],\n requestSchema: 'CreateViewRequestSchema',\n responseSchema: 'CreateViewResponseSchema',\n permissions: ['ui.view.create'],\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/views/:object/:viewId',\n handler: 'updateView',\n category: 'ui',\n public: false,\n summary: 'Update a view',\n description: 'Updates an existing view definition',\n tags: ['Views', 'UI'],\n requestSchema: 'UpdateViewRequestSchema',\n responseSchema: 'UpdateViewResponseSchema',\n permissions: ['ui.view.update'],\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/views/:object/:viewId',\n handler: 'deleteView',\n category: 'ui',\n public: false,\n summary: 'Delete a view',\n description: 'Deletes a view definition',\n tags: ['Views', 'UI'],\n responseSchema: 'DeleteViewResponseSchema',\n permissions: ['ui.view.delete'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Workflow Routes\n// ==========================================\n\n/**\n * Default Workflow Routes\n * Standard routes for workflow state management and transitions\n */\nexport const DEFAULT_WORKFLOW_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/workflow',\n service: 'workflow',\n category: 'workflow',\n methods: ['getWorkflowConfig', 'getWorkflowState', 'workflowTransition', 'workflowApprove', 'workflowReject'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/:object/config',\n handler: 'getWorkflowConfig',\n category: 'workflow',\n public: false,\n summary: 'Get workflow configuration',\n description: 'Returns workflow rules and state machine configuration for an object',\n tags: ['Workflow'],\n responseSchema: 'GetWorkflowConfigResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:object/:recordId/state',\n handler: 'getWorkflowState',\n category: 'workflow',\n public: false,\n summary: 'Get workflow state',\n description: 'Returns current workflow state and available transitions for a record',\n tags: ['Workflow'],\n responseSchema: 'GetWorkflowStateResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/transition',\n handler: 'workflowTransition',\n category: 'workflow',\n public: false,\n summary: 'Execute workflow transition',\n description: 'Transitions a record to a new workflow state',\n tags: ['Workflow'],\n requestSchema: 'WorkflowTransitionRequestSchema',\n responseSchema: 'WorkflowTransitionResponseSchema',\n permissions: ['workflow.transition'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/approve',\n handler: 'workflowApprove',\n category: 'workflow',\n public: false,\n summary: 'Approve workflow step',\n description: 'Approves a pending workflow approval step',\n tags: ['Workflow'],\n requestSchema: 'WorkflowApproveRequestSchema',\n responseSchema: 'WorkflowApproveResponseSchema',\n permissions: ['workflow.approve'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/reject',\n handler: 'workflowReject',\n category: 'workflow',\n public: false,\n summary: 'Reject workflow step',\n description: 'Rejects a pending workflow approval step',\n tags: ['Workflow'],\n requestSchema: 'WorkflowRejectRequestSchema',\n responseSchema: 'WorkflowRejectResponseSchema',\n permissions: ['workflow.reject'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Realtime Routes\n// ==========================================\n\n/**\n * Default Realtime Routes\n * Standard routes for realtime connection management and subscriptions\n */\nexport const DEFAULT_REALTIME_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/realtime',\n service: 'realtime',\n category: 'realtime',\n methods: ['realtimeConnect', 'realtimeDisconnect', 'realtimeSubscribe', 'realtimeUnsubscribe', 'setPresence', 'getPresence'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/connect',\n handler: 'realtimeConnect',\n category: 'realtime',\n public: false,\n summary: 'Establish realtime connection',\n description: 'Negotiates a realtime connection (WebSocket/SSE) and returns connection details',\n tags: ['Realtime'],\n requestSchema: 'RealtimeConnectRequestSchema',\n responseSchema: 'RealtimeConnectResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/disconnect',\n handler: 'realtimeDisconnect',\n category: 'realtime',\n public: false,\n summary: 'Close realtime connection',\n description: 'Closes an active realtime connection',\n tags: ['Realtime'],\n requestSchema: 'RealtimeDisconnectRequestSchema',\n responseSchema: 'RealtimeDisconnectResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/subscribe',\n handler: 'realtimeSubscribe',\n category: 'realtime',\n public: false,\n summary: 'Subscribe to channel',\n description: 'Subscribes to a realtime channel for receiving events',\n tags: ['Realtime'],\n requestSchema: 'RealtimeSubscribeRequestSchema',\n responseSchema: 'RealtimeSubscribeResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/unsubscribe',\n handler: 'realtimeUnsubscribe',\n category: 'realtime',\n public: false,\n summary: 'Unsubscribe from channel',\n description: 'Unsubscribes from a realtime channel',\n tags: ['Realtime'],\n requestSchema: 'RealtimeUnsubscribeRequestSchema',\n responseSchema: 'RealtimeUnsubscribeResponseSchema',\n cacheable: false,\n },\n {\n method: 'PUT',\n path: '/presence/:channel',\n handler: 'setPresence',\n category: 'realtime',\n public: false,\n summary: 'Set presence state',\n description: 'Sets the current user\\'s presence state in a channel',\n tags: ['Realtime'],\n requestSchema: 'SetPresenceRequestSchema',\n responseSchema: 'SetPresenceResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/presence/:channel',\n handler: 'getPresence',\n category: 'realtime',\n public: false,\n summary: 'Get channel presence',\n description: 'Returns all active members and their presence state in a channel',\n tags: ['Realtime'],\n responseSchema: 'GetPresenceResponseSchema',\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Notification Routes\n// ==========================================\n\n/**\n * Default Notification Routes\n * Standard routes for notification management (device registration, preferences, listing)\n */\nexport const DEFAULT_NOTIFICATION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/notifications',\n service: 'notification',\n category: 'notification',\n methods: [\n 'registerDevice', 'unregisterDevice',\n 'getNotificationPreferences', 'updateNotificationPreferences',\n 'listNotifications', 'markNotificationsRead', 'markAllNotificationsRead',\n ],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/devices',\n handler: 'registerDevice',\n category: 'notification',\n public: false,\n summary: 'Register device for push notifications',\n description: 'Registers a device token for receiving push notifications',\n tags: ['Notifications'],\n requestSchema: 'RegisterDeviceRequestSchema',\n responseSchema: 'RegisterDeviceResponseSchema',\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/devices/:deviceId',\n handler: 'unregisterDevice',\n category: 'notification',\n public: false,\n summary: 'Unregister device',\n description: 'Removes a device from push notification registration',\n tags: ['Notifications'],\n responseSchema: 'UnregisterDeviceResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/preferences',\n handler: 'getNotificationPreferences',\n category: 'notification',\n public: false,\n summary: 'Get notification preferences',\n description: 'Returns current user notification preferences',\n tags: ['Notifications'],\n responseSchema: 'GetNotificationPreferencesResponseSchema',\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/preferences',\n handler: 'updateNotificationPreferences',\n category: 'notification',\n public: false,\n summary: 'Update notification preferences',\n description: 'Updates user notification preferences',\n tags: ['Notifications'],\n requestSchema: 'UpdateNotificationPreferencesRequestSchema',\n responseSchema: 'UpdateNotificationPreferencesResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '',\n handler: 'listNotifications',\n category: 'notification',\n public: false,\n summary: 'List notifications',\n description: 'Returns paginated list of notifications for the current user',\n tags: ['Notifications'],\n responseSchema: 'ListNotificationsResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/read',\n handler: 'markNotificationsRead',\n category: 'notification',\n public: false,\n summary: 'Mark notifications as read',\n description: 'Marks specific notifications as read by their IDs',\n tags: ['Notifications'],\n requestSchema: 'MarkNotificationsReadRequestSchema',\n responseSchema: 'MarkNotificationsReadResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/read/all',\n handler: 'markAllNotificationsRead',\n category: 'notification',\n public: false,\n summary: 'Mark all notifications as read',\n description: 'Marks all notifications as read for the current user',\n tags: ['Notifications'],\n responseSchema: 'MarkAllNotificationsReadResponseSchema',\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// AI Routes\n// ==========================================\n\n/**\n * Default AI Routes\n * Standard routes for AI operations (NLQ, Chat, Suggest, Insights)\n */\nexport const DEFAULT_AI_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/ai',\n service: 'ai',\n category: 'ai',\n methods: ['aiNlq', 'aiSuggest', 'aiInsights'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/nlq',\n handler: 'aiNlq',\n category: 'ai',\n public: false,\n summary: 'Natural language query',\n description: 'Converts a natural language query to a structured query AST',\n tags: ['AI'],\n requestSchema: 'AiNlqRequestSchema',\n responseSchema: 'AiNlqResponseSchema',\n timeout: 30000,\n cacheable: false,\n },\n // AI chat route removed — wire protocol aligned with Vercel AI SDK.\n // The chat endpoint should use Vercel's `toDataStreamResponse()` directly.\n {\n method: 'POST',\n path: '/suggest',\n handler: 'aiSuggest',\n category: 'ai',\n public: false,\n summary: 'Get AI-powered suggestions',\n description: 'Returns AI-generated field value suggestions based on context',\n tags: ['AI'],\n requestSchema: 'AiSuggestRequestSchema',\n responseSchema: 'AiSuggestResponseSchema',\n timeout: 15000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/insights',\n handler: 'aiInsights',\n category: 'ai',\n public: false,\n summary: 'Get AI-generated insights',\n description: 'Returns AI-generated insights (summaries, trends, anomalies, recommendations)',\n tags: ['AI'],\n requestSchema: 'AiInsightsRequestSchema',\n responseSchema: 'AiInsightsResponseSchema',\n timeout: 60000,\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// i18n Routes\n// ==========================================\n\n/**\n * Default i18n Routes\n * Standard routes for internationalization operations\n */\nexport const DEFAULT_I18N_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/i18n',\n service: 'i18n',\n category: 'i18n',\n methods: ['getLocales', 'getTranslations', 'getFieldLabels'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/locales',\n handler: 'getLocales',\n category: 'i18n',\n public: false,\n summary: 'Get available locales',\n description: 'Returns all available locales with their metadata',\n tags: ['i18n'],\n responseSchema: 'GetLocalesResponseSchema',\n cacheable: true,\n cacheTtl: 86400, // 24 hours — locales change very rarely\n },\n {\n method: 'GET',\n path: '/translations/:locale',\n handler: 'getTranslations',\n category: 'i18n',\n public: false,\n summary: 'Get translations for a locale',\n description: 'Returns translation strings for the specified locale and optional namespace',\n tags: ['i18n'],\n responseSchema: 'GetTranslationsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/labels/:object/:locale',\n handler: 'getFieldLabels',\n category: 'i18n',\n public: false,\n summary: 'Get translated field labels',\n description: 'Returns translated field labels, help text, and option labels for an object',\n tags: ['i18n'],\n responseSchema: 'GetFieldLabelsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Analytics Routes\n// ==========================================\n\n/**\n * Default Analytics Routes\n * Standard routes for analytics and BI operations\n */\nexport const DEFAULT_ANALYTICS_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/analytics',\n service: 'analytics',\n category: 'analytics',\n methods: ['analyticsQuery', 'getAnalyticsMeta'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/query',\n handler: 'analyticsQuery',\n category: 'analytics',\n public: false,\n summary: 'Execute analytics query',\n description: 'Executes a structured analytics query against the semantic layer',\n tags: ['Analytics'],\n requestSchema: 'AnalyticsQueryRequestSchema',\n responseSchema: 'AnalyticsResultResponseSchema',\n permissions: ['analytics.query'],\n timeout: 120000, // 2 minutes for analytics queries\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/meta',\n handler: 'getAnalyticsMeta',\n category: 'analytics',\n public: false,\n summary: 'Get analytics metadata',\n description: 'Returns available cubes, dimensions, measures, and segments',\n tags: ['Analytics'],\n responseSchema: 'AnalyticsMetadataResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Automation Routes\n// ==========================================\n\n/**\n * Default Automation Routes\n * Standard routes for automation triggers\n */\nexport const DEFAULT_AUTOMATION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/automation',\n service: 'automation',\n category: 'automation',\n methods: ['triggerAutomation'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/trigger',\n handler: 'triggerAutomation',\n category: 'automation',\n public: false,\n summary: 'Trigger automation',\n description: 'Triggers an automation flow or script by name',\n tags: ['Automation'],\n requestSchema: 'AutomationTriggerRequestSchema',\n responseSchema: 'AutomationTriggerResponseSchema',\n permissions: ['automation.trigger'],\n timeout: 120000, // 2 minutes for long-running automations\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create REST API plugin configuration\n */\nexport const RestApiPluginConfig = Object.assign(RestApiPluginConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create route registration\n */\nexport const RestApiRouteRegistration = Object.assign(RestApiRouteRegistrationSchema, {\n create: >(registration: T) => registration,\n});\n\n/**\n * Get all default route registrations.\n * Returns the complete set of standard REST API routes covering all protocol namespaces.\n * \n * Route groups (13 total):\n * 1. Discovery - API capabilities and routing info\n * 2. Metadata - Object/field schema CRUD\n * 3. Data CRUD - Record operations\n * 4. Batch - Bulk operations\n * 5. Permission - Authorization checks\n * 6. Views - UI view CRUD\n * 7. Workflow - State machine transitions\n * 8. Realtime - WebSocket/SSE connections\n * 9. Notification - Push notifications and preferences\n * 10. AI - NLQ, chat, suggestions, insights\n * 11. i18n - Locales and translations\n * 12. Analytics - BI queries and metadata\n * 13. Automation - Trigger flows and scripts\n */\nexport function getDefaultRouteRegistrations(): RestApiRouteRegistration[] {\n return [\n DEFAULT_DISCOVERY_ROUTES,\n DEFAULT_METADATA_ROUTES,\n DEFAULT_DATA_CRUD_ROUTES,\n DEFAULT_BATCH_ROUTES,\n DEFAULT_PERMISSION_ROUTES,\n DEFAULT_VIEW_ROUTES,\n DEFAULT_WORKFLOW_ROUTES,\n DEFAULT_REALTIME_ROUTES,\n DEFAULT_NOTIFICATION_ROUTES,\n DEFAULT_AI_ROUTES,\n DEFAULT_I18N_ROUTES,\n DEFAULT_ANALYTICS_ROUTES,\n DEFAULT_AUTOMATION_ROUTES,\n ];\n}\n\n// ==========================================\n// Route Coverage Report\n// ==========================================\n\n/**\n * Route Coverage Entry Schema\n * Reports the coverage status of a single declared endpoint.\n */\nexport const RouteCoverageEntrySchema = z.object({\n /** Full URL path of the endpoint */\n path: z.string().describe('Full URL path (e.g. /api/v1/analytics/query)'),\n /** HTTP method */\n method: HttpMethod.describe('HTTP method (GET, POST, etc.)'),\n /** Route category */\n category: RestApiRouteCategory.describe('Route category'),\n /** Handler implementation status */\n handlerStatus: HandlerStatusSchema.describe('Handler status'),\n /** Target service */\n service: z.string().describe('Target service name'),\n /** Whether the handler was successfully called during health check */\n healthCheckPassed: z.boolean().optional().describe('Whether the health check probe succeeded'),\n});\n\nexport type RouteCoverageEntry = z.infer;\n\n/**\n * Route Coverage Report Schema\n *\n * Aggregated report generated by the adapter/dispatcher at startup.\n * Lists every declared endpoint and whether a handler is confirmed.\n *\n * Adapters SHOULD log a warning for every endpoint where\n * `handlerStatus !== 'implemented'` and emit this report as part\n * of the startup health diagnostics.\n */\nexport const RouteCoverageReportSchema = z.object({\n /** ISO 8601 timestamp of report generation */\n timestamp: z.string().describe('ISO 8601 timestamp'),\n /** Adapter that generated the report */\n adapter: z.string().describe('Adapter name (e.g. \"hono\", \"express\", \"nextjs\")'),\n /** Summary counters */\n summary: z.object({\n total: z.number().int().describe('Total declared endpoints'),\n implemented: z.number().int().describe('Endpoints with real handlers'),\n stub: z.number().int().describe('Endpoints with stub handlers (501)'),\n planned: z.number().int().describe('Endpoints not yet implemented'),\n }),\n /** Per-endpoint entries */\n entries: z.array(RouteCoverageEntrySchema).describe('Per-endpoint coverage entries'),\n});\n\nexport type RouteCoverageReport = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * API Query DSL Adapter Protocol\n * \n * Defines mapping rules between the internal unified query DSL\n * (defined in `data/query.zod.ts`) and external API protocol formats:\n * REST, GraphQL, and OData.\n * \n * This enables ObjectStack to expose a single internal query representation\n * while supporting multiple API standards for external consumers.\n * \n * @see data/query.zod.ts - Unified internal query DSL\n * @see api/rest-server.zod.ts - REST API configuration\n * @see api/graphql.zod.ts - GraphQL API configuration\n * @see api/odata.zod.ts - OData API configuration\n */\n\n// ==========================================\n// 1. Shared Adapter Types\n// ==========================================\n\n/**\n * Query Adapter Target Protocol\n */\nexport const QueryAdapterTargetSchema = z.enum([\n 'rest', // REST API (?filter[field][op]=value)\n 'graphql', // GraphQL (where: \\{ field: \\{ op: value \\}\\})\n 'odata', // OData ($filter=field op value)\n]);\n\nexport type QueryAdapterTarget = z.infer;\n\n/**\n * Operator Mapping Entry\n * \n * Maps a unified DSL operator to its protocol-specific syntax.\n */\nexport const OperatorMappingSchema = z.object({\n /** Unified DSL operator (e.g., 'eq', 'gt', 'contains') */\n operator: z.string().describe('Unified DSL operator'),\n\n /** REST query parameter format (e.g., 'filter[{field}][{op}]') */\n rest: z.string().optional().describe('REST query parameter template'),\n\n /** GraphQL where clause format (e.g., '{field}: { {op}: $value }') */\n graphql: z.string().optional().describe('GraphQL where clause template'),\n\n /** OData $filter expression format (e.g., '{field} {op} {value}') */\n odata: z.string().optional().describe('OData $filter expression template'),\n});\n\nexport type OperatorMapping = z.infer;\n\n// ==========================================\n// 2. REST Adapter Configuration\n// ==========================================\n\n/**\n * REST Query Adapter Configuration\n * \n * Defines how unified query DSL maps to REST query parameters.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10 }\n * REST: ?filter[status][eq]=active&limit=10\n */\nexport const RestQueryAdapterSchema = z.object({\n /** Filter parameter style */\n filterStyle: z.enum([\n 'bracket', // ?filter[field][op]=value (JSON API style)\n 'dot', // ?filter.field.op=value\n 'flat', // ?field=value (simple equality)\n 'rsql', // ?filter=field==value;field=gt=10 (RSQL / FIQL)\n ]).default('bracket').describe('REST filter parameter encoding style'),\n\n /** Pagination parameter names */\n pagination: z.object({\n /** Page size parameter name */\n limitParam: z.string().default('limit').describe('Page size parameter name'),\n\n /** Offset parameter name */\n offsetParam: z.string().default('offset').describe('Offset parameter name'),\n\n /** Cursor parameter name (for cursor-based pagination) */\n cursorParam: z.string().default('cursor').describe('Cursor parameter name'),\n\n /** Page number parameter name (for page-based pagination) */\n pageParam: z.string().default('page').describe('Page number parameter name'),\n }).optional().describe('Pagination parameter name mappings'),\n\n /** Sort parameter name and format */\n sorting: z.object({\n /** Sort parameter name */\n param: z.string().default('sort').describe('Sort parameter name'),\n\n /** Sort format */\n format: z.enum([\n 'comma', // ?sort=field1,-field2\n 'array', // ?sort[]=field1&sort[]=-field2\n 'pipe', // ?sort=field1|asc,field2|desc\n ]).default('comma').describe('Sort parameter encoding format'),\n }).optional().describe('Sort parameter mapping'),\n\n /** Field selection parameter name */\n fieldsParam: z.string().default('fields').describe('Field selection parameter name'),\n});\n\nexport type RestQueryAdapter = z.infer;\nexport type RestQueryAdapterInput = z.input;\n\n// ==========================================\n// 3. GraphQL Adapter Configuration\n// ==========================================\n\n/**\n * GraphQL Query Adapter Configuration\n * \n * Defines how unified query DSL maps to GraphQL arguments.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10, sort: [{ field: 'name', order: 'asc' }] }\n * GraphQL: query { items(where: { status: { eq: \"active\" } }, limit: 10, orderBy: { name: ASC }) { ... } }\n */\nexport const GraphQLQueryAdapterSchema = z.object({\n /** Filter argument name in GraphQL queries */\n filterArgName: z.string().default('where').describe('GraphQL filter argument name'),\n\n /** Filter nesting style */\n filterStyle: z.enum([\n 'nested', // where: { field: { op: value } } (Prisma style)\n 'flat', // where: { field_op: value } (Hasura style)\n 'array', // where: [{ field, op, value }] (Array of conditions)\n ]).default('nested').describe('GraphQL filter nesting style'),\n\n /** Pagination argument names */\n pagination: z.object({\n limitArg: z.string().default('limit').describe('Page size argument name'),\n offsetArg: z.string().default('offset').describe('Offset argument name'),\n firstArg: z.string().default('first').describe('Relay \"first\" argument name'),\n afterArg: z.string().default('after').describe('Relay \"after\" cursor argument name'),\n }).optional().describe('Pagination argument name mappings'),\n\n /** Sort argument configuration */\n sorting: z.object({\n argName: z.string().default('orderBy').describe('Sort argument name'),\n format: z.enum([\n 'enum', // orderBy: { field: ASC }\n 'array', // orderBy: [{ field: \"name\", direction: \"ASC\" }]\n ]).default('enum').describe('Sort argument format'),\n }).optional().describe('Sort argument mapping'),\n});\n\nexport type GraphQLQueryAdapter = z.infer;\nexport type GraphQLQueryAdapterInput = z.input;\n\n// ==========================================\n// 4. OData Adapter Configuration\n// ==========================================\n\n/**\n * OData Query Adapter Configuration\n * \n * Defines how unified query DSL maps to OData system query options.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10, sort: [{ field: 'name', order: 'asc' }] }\n * OData: ?$filter=status eq 'active'&$top=10&$orderby=name asc\n */\nexport const ODataQueryAdapterSchema = z.object({\n /** OData version */\n version: z.enum(['v2', 'v4']).default('v4').describe('OData version'),\n\n /** System query option prefixes */\n usePrefix: z.boolean().default(true).describe('Use $ prefix for system query options ($filter vs filter)'),\n\n /** String function support */\n stringFunctions: z.array(z.enum([\n 'contains',\n 'startswith',\n 'endswith',\n 'tolower',\n 'toupper',\n 'trim',\n 'concat',\n 'substring',\n 'length',\n ])).optional().describe('Supported OData string functions'),\n\n /** Expand (nested resource) configuration */\n expand: z.object({\n enabled: z.boolean().default(true).describe('Enable $expand support'),\n maxDepth: z.number().int().min(1).default(3).describe('Maximum expand depth'),\n }).optional().describe('$expand configuration'),\n});\n\nexport type ODataQueryAdapter = z.infer;\nexport type ODataQueryAdapterInput = z.input;\n\n// ==========================================\n// 5. Complete Query Adapter Configuration\n// ==========================================\n\n/**\n * Query Adapter Configuration\n * \n * Root configuration for query DSL adapters across all supported protocols.\n * Controls how the internal unified DSL is translated to external API formats.\n */\nexport const QueryAdapterConfigSchema = z.object({\n /** Default operator mappings */\n operatorMappings: z.array(OperatorMappingSchema).optional().describe('Custom operator mappings'),\n\n /** REST adapter configuration */\n rest: RestQueryAdapterSchema.optional().describe('REST query adapter configuration'),\n\n /** GraphQL adapter configuration */\n graphql: GraphQLQueryAdapterSchema.optional().describe('GraphQL query adapter configuration'),\n\n /** OData adapter configuration */\n odata: ODataQueryAdapterSchema.optional().describe('OData query adapter configuration'),\n});\n\nexport type QueryAdapterConfig = z.infer;\nexport type QueryAdapterConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport {\n FeedItemType,\n FeedItemSchema,\n FeedVisibility,\n MentionSchema,\n ReactionSchema,\n FieldChangeEntrySchema,\n} from '../data/feed.zod';\nimport {\n SubscriptionEventType,\n NotificationChannel,\n RecordSubscriptionSchema,\n} from '../data/subscription.zod';\n\n/**\n * Feed / Chatter API Protocol\n *\n * Defines the HTTP interface for the unified activity timeline (Feed).\n * Covers Feed CRUD, Emoji Reactions, Pin/Star, Search, Changelog,\n * and Record Subscription endpoints.\n *\n * Base path: /api/data/{object}/{recordId}/feed\n *\n * @example Endpoints\n * GET /api/data/{object}/{recordId}/feed — List feed items\n * POST /api/data/{object}/{recordId}/feed — Create feed item\n * PUT /api/data/{object}/{recordId}/feed/{feedId} — Update feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId} — Delete feed item\n * POST /api/data/{object}/{recordId}/feed/{feedId}/reactions — Add reaction\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/reactions/{emoji} — Remove reaction\n * POST /api/data/{object}/{recordId}/feed/{feedId}/pin — Pin feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/pin — Unpin feed item\n * POST /api/data/{object}/{recordId}/feed/{feedId}/star — Star feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/star — Unstar feed item\n * GET /api/data/{object}/{recordId}/feed/search — Search feed items\n * GET /api/data/{object}/{recordId}/changelog — Get field-level changelog\n * POST /api/data/{object}/{recordId}/subscribe — Subscribe\n * DELETE /api/data/{object}/{recordId}/subscribe — Unsubscribe\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Common path parameters shared across all feed endpoints.\n */\nexport const FeedPathParamsSchema = z.object({\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID'),\n});\nexport type FeedPathParams = z.infer;\n\n/**\n * Path parameters for single-feed-item operations (update, delete).\n */\nexport const FeedItemPathParamsSchema = FeedPathParamsSchema.extend({\n feedId: z.string().describe('Feed item ID'),\n});\nexport type FeedItemPathParams = z.infer;\n\n// ==========================================\n// 2. Feed List (GET)\n// ==========================================\n\n/**\n * Feed filter type for the list query.\n * Maps to FeedFilterMode: all | comments_only | changes_only | tasks_only\n */\nexport const FeedListFilterType = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\n\n/**\n * Query parameters for listing feed items.\n *\n * @example GET /api/data/account/rec_123/feed?type=all&limit=20&cursor=xxx\n */\nexport const GetFeedRequestSchema = FeedPathParamsSchema.extend({\n type: FeedListFilterType.default('all')\n .describe('Filter by feed item category'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of items to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination (opaque string from previous response)'),\n});\nexport type GetFeedRequest = z.infer;\n\n/**\n * Response for the feed list endpoint.\n */\nexport const GetFeedResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n items: z.array(FeedItemSchema).describe('Feed items in reverse chronological order'),\n total: z.number().int().optional().describe('Total feed items matching filter'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more items are available'),\n }),\n});\nexport type GetFeedResponse = z.infer;\n\n// ==========================================\n// 3. Feed Create (POST)\n// ==========================================\n\n/**\n * Request body for creating a new feed item (comment, note, task, etc.).\n *\n * @example POST /api/data/account/rec_123/feed\n * { type: 'comment', body: 'Great progress! @jane can you follow up?', mentions: [...] }\n */\nexport const CreateFeedItemRequestSchema = FeedPathParamsSchema.extend({\n type: FeedItemType.describe('Type of feed item to create'),\n body: z.string().optional()\n .describe('Rich text body (Markdown supported)'),\n mentions: z.array(MentionSchema).optional()\n .describe('Mentioned users, teams, or records'),\n parentId: z.string().optional()\n .describe('Parent feed item ID for threaded replies'),\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public, internal, or private'),\n});\nexport type CreateFeedItemRequest = z.infer;\n\n/**\n * Response after creating a feed item.\n */\nexport const CreateFeedItemResponseSchema = BaseResponseSchema.extend({\n data: FeedItemSchema.describe('The created feed item'),\n});\nexport type CreateFeedItemResponse = z.infer;\n\n// ==========================================\n// 4. Feed Update (PUT)\n// ==========================================\n\n/**\n * Request body for updating an existing feed item (e.g., editing a comment).\n *\n * @example PUT /api/data/account/rec_123/feed/feed_001\n * { body: 'Updated comment text', mentions: [...] }\n */\nexport const UpdateFeedItemRequestSchema = FeedItemPathParamsSchema.extend({\n body: z.string().optional()\n .describe('Updated rich text body'),\n mentions: z.array(MentionSchema).optional()\n .describe('Updated mentions'),\n visibility: FeedVisibility.optional()\n .describe('Updated visibility'),\n});\nexport type UpdateFeedItemRequest = z.infer;\n\n/**\n * Response after updating a feed item.\n */\nexport const UpdateFeedItemResponseSchema = BaseResponseSchema.extend({\n data: FeedItemSchema.describe('The updated feed item'),\n});\nexport type UpdateFeedItemResponse = z.infer;\n\n// ==========================================\n// 5. Feed Delete (DELETE)\n// ==========================================\n\n/**\n * Request parameters for deleting a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001\n */\nexport const DeleteFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type DeleteFeedItemRequest = z.infer;\n\n/**\n * Response after deleting a feed item.\n */\nexport const DeleteFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the deleted feed item'),\n }),\n});\nexport type DeleteFeedItemResponse = z.infer;\n\n// ==========================================\n// 6. Reactions (POST / DELETE)\n// ==========================================\n\n/**\n * Request for adding an emoji reaction to a feed item.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/reactions\n * { emoji: '👍' }\n */\nexport const AddReactionRequestSchema = FeedItemPathParamsSchema.extend({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n});\nexport type AddReactionRequest = z.infer;\n\n/**\n * Response after adding a reaction.\n */\nexport const AddReactionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n reactions: z.array(ReactionSchema).describe('Updated reaction list for the feed item'),\n }),\n});\nexport type AddReactionResponse = z.infer;\n\n/**\n * Request for removing an emoji reaction from a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/reactions/👍\n */\nexport const RemoveReactionRequestSchema = FeedItemPathParamsSchema.extend({\n emoji: z.string().describe('Emoji character or shortcode to remove'),\n});\nexport type RemoveReactionRequest = z.infer;\n\n/**\n * Response after removing a reaction.\n */\nexport const RemoveReactionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n reactions: z.array(ReactionSchema).describe('Updated reaction list for the feed item'),\n }),\n});\nexport type RemoveReactionResponse = z.infer;\n\n// ==========================================\n// 7. Pin / Star\n// ==========================================\n\n/**\n * Request for pinning a feed item to the top of the timeline.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/pin\n */\nexport const PinFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type PinFeedItemRequest = z.infer;\n\n/**\n * Response after pinning a feed item.\n */\nexport const PinFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the pinned feed item'),\n pinned: z.boolean().describe('Whether the item is now pinned'),\n pinnedAt: z.string().datetime().describe('Timestamp when pinned'),\n }),\n});\nexport type PinFeedItemResponse = z.infer;\n\n/**\n * Request for unpinning a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/pin\n */\nexport const UnpinFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type UnpinFeedItemRequest = z.infer;\n\n/**\n * Response after unpinning a feed item.\n */\nexport const UnpinFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the unpinned feed item'),\n pinned: z.boolean().describe('Whether the item is now pinned (should be false)'),\n }),\n});\nexport type UnpinFeedItemResponse = z.infer;\n\n/**\n * Request for starring (bookmarking) a feed item.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/star\n */\nexport const StarFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type StarFeedItemRequest = z.infer;\n\n/**\n * Response after starring a feed item.\n */\nexport const StarFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the starred feed item'),\n starred: z.boolean().describe('Whether the item is now starred'),\n starredAt: z.string().datetime().describe('Timestamp when starred'),\n }),\n});\nexport type StarFeedItemResponse = z.infer;\n\n/**\n * Request for unstarring a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/star\n */\nexport const UnstarFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type UnstarFeedItemRequest = z.infer;\n\n/**\n * Response after unstarring a feed item.\n */\nexport const UnstarFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the unstarred feed item'),\n starred: z.boolean().describe('Whether the item is now starred (should be false)'),\n }),\n});\nexport type UnstarFeedItemResponse = z.infer;\n\n// ==========================================\n// 8. Activity Feed Search & Filter\n// ==========================================\n\n/**\n * Request for searching feed items with full-text query and advanced filters.\n *\n * @example GET /api/data/account/rec_123/feed/search?query=follow+up&actorId=user_456&dateFrom=2026-01-01T00:00:00Z\n */\nexport const SearchFeedRequestSchema = FeedPathParamsSchema.extend({\n query: z.string().min(1).describe('Full-text search query against feed body content'),\n type: FeedListFilterType.optional()\n .describe('Filter by feed item category'),\n actorId: z.string().optional()\n .describe('Filter by actor user ID'),\n dateFrom: z.string().datetime().optional()\n .describe('Filter feed items created after this timestamp'),\n dateTo: z.string().datetime().optional()\n .describe('Filter feed items created before this timestamp'),\n hasAttachments: z.boolean().optional()\n .describe('Filter for items with file attachments'),\n pinnedOnly: z.boolean().optional()\n .describe('Return only pinned items'),\n starredOnly: z.boolean().optional()\n .describe('Return only starred items'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of items to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type SearchFeedRequest = z.infer;\n\n/**\n * Response for the feed search endpoint.\n */\nexport const SearchFeedResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n items: z.array(FeedItemSchema).describe('Matching feed items sorted by relevance'),\n total: z.number().int().optional().describe('Total matching items'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more items are available'),\n }),\n});\nexport type SearchFeedResponse = z.infer;\n\n// ==========================================\n// 9. Changelog (Field-Level Audit Trail)\n// ==========================================\n\n/**\n * Request for retrieving the field-level changelog of a record.\n *\n * @example GET /api/data/account/rec_123/changelog?field=status&limit=50\n */\nexport const GetChangelogRequestSchema = FeedPathParamsSchema.extend({\n field: z.string().optional()\n .describe('Filter changelog to a specific field name'),\n actorId: z.string().optional()\n .describe('Filter changelog by actor user ID'),\n dateFrom: z.string().datetime().optional()\n .describe('Filter changes after this timestamp'),\n dateTo: z.string().datetime().optional()\n .describe('Filter changes before this timestamp'),\n limit: z.number().int().min(1).max(200).default(50)\n .describe('Maximum number of changelog entries to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type GetChangelogRequest = z.infer;\n\n/**\n * A single changelog entry representing one or more field changes at a point in time.\n */\nexport const ChangelogEntrySchema = z.object({\n id: z.string().describe('Changelog entry ID'),\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n actor: z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n }).describe('Who made the change'),\n changes: z.array(FieldChangeEntrySchema).min(1).describe('Field-level changes'),\n timestamp: z.string().datetime().describe('When the change occurred'),\n source: z.string().optional().describe('Change source (e.g., \"API\", \"UI\", \"automation\")'),\n});\nexport type ChangelogEntry = z.infer;\n\n/**\n * Response for the changelog endpoint.\n */\nexport const GetChangelogResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n entries: z.array(ChangelogEntrySchema).describe('Changelog entries in reverse chronological order'),\n total: z.number().int().optional().describe('Total changelog entries matching filter'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more entries are available'),\n }),\n});\nexport type GetChangelogResponse = z.infer;\n\n// ==========================================\n// 10. Record Subscription (POST / DELETE)\n// ==========================================\n\n/**\n * Request for subscribing to record notifications.\n *\n * @example POST /api/data/account/rec_123/subscribe\n * { events: ['comment', 'field_change'], channels: ['in_app', 'email'] }\n */\nexport const SubscribeRequestSchema = FeedPathParamsSchema.extend({\n events: z.array(SubscriptionEventType).default(['all'])\n .describe('Event types to subscribe to'),\n channels: z.array(NotificationChannel).default(['in_app'])\n .describe('Notification delivery channels'),\n});\nexport type SubscribeRequest = z.infer;\n\n/**\n * Response after subscribing.\n */\nexport const SubscribeResponseSchema = BaseResponseSchema.extend({\n data: RecordSubscriptionSchema.describe('The created or updated subscription'),\n});\nexport type SubscribeResponse = z.infer;\n\n/**\n * Request for unsubscribing from record notifications.\n *\n * @example DELETE /api/data/account/rec_123/subscribe\n */\nexport const FeedUnsubscribeRequestSchema = FeedPathParamsSchema;\nexport type FeedUnsubscribeRequest = z.infer;\n\n/**\n * Response after unsubscribing.\n */\nexport const UnsubscribeResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n unsubscribed: z.boolean().describe('Whether the user was unsubscribed'),\n }),\n});\nexport type UnsubscribeResponse = z.infer;\n\n// ==========================================\n// 11. Feed API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Feed/Chatter operations.\n */\nexport const FeedApiErrorCode = z.enum([\n 'feed_item_not_found',\n 'feed_permission_denied',\n 'feed_item_not_editable',\n 'feed_invalid_parent',\n 'reaction_already_exists',\n 'reaction_not_found',\n 'subscription_already_exists',\n 'subscription_not_found',\n 'invalid_feed_type',\n 'feed_already_pinned',\n 'feed_not_pinned',\n 'feed_already_starred',\n 'feed_not_starred',\n 'feed_search_query_too_short',\n]);\nexport type FeedApiErrorCode = z.infer;\n\n// ==========================================\n// 12. Feed API Contract Registry\n// ==========================================\n\n/**\n * Standard Feed API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const FeedApiContracts = {\n listFeed: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/feed',\n input: GetFeedRequestSchema,\n output: GetFeedResponseSchema,\n },\n createFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed',\n input: CreateFeedItemRequestSchema,\n output: CreateFeedItemResponseSchema,\n },\n updateFeedItem: {\n method: 'PUT' as const,\n path: '/api/data/:object/:recordId/feed/:feedId',\n input: UpdateFeedItemRequestSchema,\n output: UpdateFeedItemResponseSchema,\n },\n deleteFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId',\n input: DeleteFeedItemRequestSchema,\n output: DeleteFeedItemResponseSchema,\n },\n addReaction: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/reactions',\n input: AddReactionRequestSchema,\n output: AddReactionResponseSchema,\n },\n removeReaction: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/reactions/:emoji',\n input: RemoveReactionRequestSchema,\n output: RemoveReactionResponseSchema,\n },\n pinFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/pin',\n input: PinFeedItemRequestSchema,\n output: PinFeedItemResponseSchema,\n },\n unpinFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/pin',\n input: UnpinFeedItemRequestSchema,\n output: UnpinFeedItemResponseSchema,\n },\n starFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/star',\n input: StarFeedItemRequestSchema,\n output: StarFeedItemResponseSchema,\n },\n unstarFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/star',\n input: UnstarFeedItemRequestSchema,\n output: UnstarFeedItemResponseSchema,\n },\n searchFeed: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/feed/search',\n input: SearchFeedRequestSchema,\n output: SearchFeedResponseSchema,\n },\n getChangelog: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/changelog',\n input: GetChangelogRequestSchema,\n output: GetChangelogResponseSchema,\n },\n subscribe: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/subscribe',\n input: SubscribeRequestSchema,\n output: SubscribeResponseSchema,\n },\n unsubscribe: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/subscribe',\n input: FeedUnsubscribeRequestSchema,\n output: UnsubscribeResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Data Export & Import Protocol\n *\n * Defines schemas for streaming data export, import validation,\n * template-based field mapping, and scheduled export jobs.\n *\n * Industry alignment: Salesforce Data Export, Airtable CSV Export,\n * Dynamics 365 Data Management.\n *\n * Base path: /api/v1/data/{object}/export\n */\n\n// ==========================================\n// 1. Export Format & Configuration\n// ==========================================\n\n/**\n * Export Format Enum\n * Supported file formats for data export.\n */\nexport const ExportFormat = z.enum([\n 'csv',\n 'json',\n 'jsonl',\n 'xlsx',\n 'parquet',\n]);\nexport type ExportFormat = z.infer;\n\n/**\n * Export Job Status\n */\nexport const ExportJobStatus = z.enum([\n 'pending',\n 'processing',\n 'completed',\n 'failed',\n 'cancelled',\n 'expired',\n]);\nexport type ExportJobStatus = z.infer;\n\n// ==========================================\n// 2. Export Job Request / Response\n// ==========================================\n\n/**\n * Create Export Job Request\n * Initiates an asynchronous streaming export.\n *\n * @example POST /api/v1/data/account/export\n * { format: 'csv', fields: ['name', 'email', 'status'], filter: { status: 'active' }, limit: 10000 }\n */\nexport const CreateExportJobRequestSchema = z.object({\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional()\n .describe('Specific fields to include (omit for all fields)'),\n filter: z.record(z.string(), z.unknown()).optional()\n .describe('Filter criteria for records to export'),\n sort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n direction: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n })).optional().describe('Sort order for exported records'),\n limit: z.number().int().min(1).optional()\n .describe('Maximum number of records to export'),\n includeHeaders: z.boolean().default(true)\n .describe('Include header row (CSV/XLSX)'),\n encoding: z.string().default('utf-8')\n .describe('Character encoding for the export file'),\n templateId: z.string().optional()\n .describe('Export template ID for predefined field mappings'),\n});\nexport type CreateExportJobRequest = z.infer;\n\n/**\n * Export Job Response\n * Returns the created export job with tracking info.\n */\nexport const CreateExportJobResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n status: ExportJobStatus.describe('Initial job status'),\n estimatedRecords: z.number().int().optional().describe('Estimated total records'),\n createdAt: z.string().datetime().describe('Job creation timestamp'),\n }),\n});\nexport type CreateExportJobResponse = z.infer;\n\n/**\n * Export Job Progress\n * Tracks the progress of an active export job.\n *\n * @example GET /api/v1/data/export/:jobId\n */\nexport const ExportJobProgressSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n status: ExportJobStatus.describe('Current job status'),\n format: ExportFormat.describe('Export format'),\n totalRecords: z.number().int().optional().describe('Total records to export'),\n processedRecords: z.number().int().describe('Records processed so far'),\n percentComplete: z.number().min(0).max(100).describe('Export progress percentage'),\n fileSize: z.number().int().optional().describe('Current file size in bytes'),\n downloadUrl: z.string().optional()\n .describe('Presigned download URL (available when status is \"completed\")'),\n downloadExpiresAt: z.string().datetime().optional()\n .describe('Download URL expiration timestamp'),\n error: z.object({\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n }).optional().describe('Error details if job failed'),\n startedAt: z.string().datetime().optional().describe('Processing start timestamp'),\n completedAt: z.string().datetime().optional().describe('Completion timestamp'),\n }),\n});\nexport type ExportJobProgress = z.infer;\n\n// ==========================================\n// 3. Import Validation & Deduplication\n// ==========================================\n\n/**\n * Import Validation Mode\n */\nexport const ImportValidationMode = z.enum([\n 'strict', // Reject entire import on any validation error\n 'lenient', // Skip invalid records, import valid ones\n 'dry_run', // Validate all records without persisting\n]);\nexport type ImportValidationMode = z.infer;\n\n/**\n * Deduplication Strategy\n * How to handle duplicate records during import.\n */\nexport const DeduplicationStrategy = z.enum([\n 'skip', // Skip duplicates (keep existing)\n 'update', // Update existing with import data\n 'create_new', // Create new record even if duplicate\n 'fail', // Fail the import if duplicates found\n]);\nexport type DeduplicationStrategy = z.infer;\n\n/**\n * Import Validation Config Schema\n * Configuration for validating and deduplicating imported data.\n *\n * @example\n * {\n * mode: 'lenient',\n * deduplication: { strategy: 'update', matchFields: ['email', 'external_id'] },\n * maxErrors: 50,\n * trimWhitespace: true,\n * }\n */\nexport const ImportValidationConfigSchema = z.object({\n mode: ImportValidationMode.default('strict')\n .describe('Validation mode for the import'),\n deduplication: z.object({\n strategy: DeduplicationStrategy.default('skip')\n .describe('How to handle duplicate records'),\n matchFields: z.array(z.string()).min(1)\n .describe('Fields used to identify duplicates (e.g., \"email\", \"external_id\")'),\n }).optional().describe('Deduplication configuration'),\n maxErrors: z.number().int().min(1).default(100)\n .describe('Maximum validation errors before aborting'),\n trimWhitespace: z.boolean().default(true)\n .describe('Trim leading/trailing whitespace from string fields'),\n dateFormat: z.string().optional()\n .describe('Expected date format in import data (e.g., \"YYYY-MM-DD\")'),\n nullValues: z.array(z.string()).optional()\n .describe('Strings to treat as null (e.g., [\"\", \"N/A\", \"null\"])'),\n});\nexport type ImportValidationConfig = z.infer;\n\n/**\n * Import Validation Result Schema\n * Summary of the import validation pass.\n */\nexport const ImportValidationResultSchema = BaseResponseSchema.extend({\n data: z.object({\n totalRecords: z.number().int().describe('Total records in import file'),\n validRecords: z.number().int().describe('Records that passed validation'),\n invalidRecords: z.number().int().describe('Records that failed validation'),\n duplicateRecords: z.number().int().describe('Duplicate records detected'),\n errors: z.array(z.object({\n row: z.number().int().describe('Row number in the import file'),\n field: z.string().optional().describe('Field that failed validation'),\n code: z.string().describe('Validation error code'),\n message: z.string().describe('Validation error message'),\n })).describe('List of validation errors'),\n preview: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Preview of first N valid records (for dry_run mode)'),\n }),\n});\nexport type ImportValidationResult = z.infer;\n\n// ==========================================\n// 4. Export/Import Template\n// ==========================================\n\n/**\n * Field Mapping Entry Schema\n * Maps a source field to a target field with optional transformation.\n */\nexport const FieldMappingEntrySchema = z.object({\n sourceField: z.string().describe('Field name in the source data (import) or object (export)'),\n targetField: z.string().describe('Field name in the target object (import) or file column (export)'),\n targetLabel: z.string().optional().describe('Display label for the target column (export)'),\n transform: z.enum(['none', 'uppercase', 'lowercase', 'trim', 'date_format', 'lookup'])\n .default('none')\n .describe('Transformation to apply during mapping'),\n defaultValue: z.unknown().optional()\n .describe('Default value if source field is null/empty'),\n required: z.boolean().default(false)\n .describe('Whether this field is required (import validation)'),\n});\nexport type FieldMappingEntry = z.infer;\n\n/**\n * Export/Import Template Schema\n * Reusable template for predefined field mappings.\n *\n * @example\n * {\n * name: 'account_export_v1',\n * label: 'Account Export (Standard)',\n * object: 'account',\n * direction: 'export',\n * mappings: [\n * { sourceField: 'name', targetField: 'Company Name' },\n * { sourceField: 'email', targetField: 'Email', transform: 'lowercase' },\n * ],\n * }\n */\nexport const ExportImportTemplateSchema = z.object({\n id: z.string().optional().describe('Template ID (generated on save)'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Template machine name (snake_case)'),\n label: z.string().describe('Human-readable template label'),\n description: z.string().optional().describe('Template description'),\n object: z.string().describe('Target object name'),\n direction: z.enum(['import', 'export', 'bidirectional'])\n .describe('Template direction'),\n format: ExportFormat.optional().describe('Default file format for this template'),\n mappings: z.array(FieldMappingEntrySchema).min(1)\n .describe('Field mapping entries'),\n createdAt: z.string().datetime().optional().describe('Template creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n createdBy: z.string().optional().describe('User who created the template'),\n});\nexport type ExportImportTemplate = z.infer;\n\n// ==========================================\n// 5. Scheduled Export Jobs\n// ==========================================\n\n/**\n * Scheduled Export Schema\n * Defines a recurring data export job.\n *\n * @example\n * {\n * name: 'weekly_account_export',\n * object: 'account',\n * format: 'csv',\n * schedule: { cronExpression: '0 6 * * MON', timezone: 'America/New_York' },\n * delivery: { method: 'email', recipients: ['admin@example.com'] },\n * }\n */\nexport const ScheduledExportSchema = z.object({\n id: z.string().optional().describe('Scheduled export ID'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Schedule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional().describe('Fields to include'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Record filter criteria'),\n templateId: z.string().optional().describe('Export template ID for field mappings'),\n schedule: z.object({\n cronExpression: z.string().describe('Cron expression for schedule'),\n timezone: z.string().default('UTC').describe('IANA timezone'),\n }).describe('Schedule timing configuration'),\n delivery: z.object({\n method: z.enum(['email', 'storage', 'webhook'])\n .describe('How to deliver the export file'),\n recipients: z.array(z.string()).optional()\n .describe('Email recipients (for email delivery)'),\n storagePath: z.string().optional()\n .describe('Storage path (for storage delivery)'),\n webhookUrl: z.string().optional()\n .describe('Webhook URL (for webhook delivery)'),\n }).describe('Export delivery configuration'),\n enabled: z.boolean().default(true).describe('Whether the scheduled export is active'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution'),\n createdAt: z.string().datetime().optional().describe('Creation timestamp'),\n createdBy: z.string().optional().describe('User who created the schedule'),\n});\nexport type ScheduledExport = z.infer;\n\n// ==========================================\n// 6. Get Export Job Download\n// ==========================================\n\n/**\n * Get Export Job Download Request\n * Retrieves a presigned download link for a completed export job.\n *\n * @example GET /api/v1/data/export/:jobId/download\n */\nexport const GetExportJobDownloadRequestSchema = z.object({\n jobId: z.string().describe('Export job ID'),\n});\nexport type GetExportJobDownloadRequest = z.infer;\n\n/**\n * Get Export Job Download Response\n * Returns the presigned download URL and metadata.\n */\nexport const GetExportJobDownloadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n downloadUrl: z.string().describe('Presigned download URL'),\n fileName: z.string().describe('Suggested file name'),\n fileSize: z.number().int().describe('File size in bytes'),\n format: ExportFormat.describe('Export file format'),\n expiresAt: z.string().datetime().describe('Download URL expiration timestamp'),\n checksum: z.string().optional().describe('File checksum (SHA-256)'),\n }),\n});\nexport type GetExportJobDownloadResponse = z.infer;\n\n// ==========================================\n// 7. List Export Jobs\n// ==========================================\n\n/**\n * List Export Jobs Request\n * Retrieves a paginated list of historical export jobs.\n *\n * @example GET /api/v1/data/export?object=account&status=completed&limit=20\n */\nexport const ListExportJobsRequestSchema = z.object({\n object: z.string().optional().describe('Filter by object name'),\n status: ExportJobStatus.optional().describe('Filter by job status'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of jobs to return'),\n cursor: z.string().optional()\n .describe('Pagination cursor from a previous response'),\n});\nexport type ListExportJobsRequest = z.infer;\n\n/**\n * Export Job Summary\n * Compact representation of an export job for list views.\n */\nexport const ExportJobSummarySchema = z.object({\n jobId: z.string().describe('Export job ID'),\n object: z.string().describe('Object name that was exported'),\n status: ExportJobStatus.describe('Current job status'),\n format: ExportFormat.describe('Export file format'),\n totalRecords: z.number().int().optional().describe('Total records exported'),\n fileSize: z.number().int().optional().describe('File size in bytes'),\n createdAt: z.string().datetime().describe('Job creation timestamp'),\n completedAt: z.string().datetime().optional().describe('Completion timestamp'),\n createdBy: z.string().optional().describe('User who initiated the export'),\n});\nexport type ExportJobSummary = z.infer;\n\n/**\n * List Export Jobs Response\n * Paginated list of export jobs with cursor-based pagination.\n */\nexport const ListExportJobsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobs: z.array(ExportJobSummarySchema).describe('List of export jobs'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more jobs are available'),\n }),\n});\nexport type ListExportJobsResponse = z.infer;\n\n// ==========================================\n// 8. Schedule Export Request/Response\n// ==========================================\n\n/**\n * Schedule Export Request\n * Creates a new scheduled (recurring) export job.\n *\n * @example POST /api/v1/data/export/schedules\n */\nexport const ScheduleExportRequestSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Schedule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional().describe('Fields to include'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Record filter criteria'),\n templateId: z.string().optional().describe('Export template ID for field mappings'),\n schedule: z.object({\n cronExpression: z.string().describe('Cron expression for schedule'),\n timezone: z.string().default('UTC').describe('IANA timezone'),\n }).describe('Schedule timing configuration'),\n delivery: z.object({\n method: z.enum(['email', 'storage', 'webhook'])\n .describe('How to deliver the export file'),\n recipients: z.array(z.string()).optional()\n .describe('Email recipients (for email delivery)'),\n storagePath: z.string().optional()\n .describe('Storage path (for storage delivery)'),\n webhookUrl: z.string().optional()\n .describe('Webhook URL (for webhook delivery)'),\n }).describe('Export delivery configuration'),\n});\nexport type ScheduleExportRequest = z.infer;\n\n/**\n * Schedule Export Response\n * Returns the created scheduled export with generated ID and next run info.\n */\nexport const ScheduleExportResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n id: z.string().describe('Scheduled export ID'),\n name: z.string().describe('Schedule name'),\n enabled: z.boolean().describe('Whether the schedule is active'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution'),\n createdAt: z.string().datetime().describe('Creation timestamp'),\n }),\n});\nexport type ScheduleExportResponse = z.infer;\n\n// ==========================================\n// 9. Export API Contracts\n// ==========================================\n\n/**\n * Export API Contract Registry\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const ExportApiContracts = {\n createExportJob: {\n method: 'POST' as const,\n path: '/api/v1/data/:object/export',\n input: CreateExportJobRequestSchema,\n output: CreateExportJobResponseSchema,\n },\n getExportJobProgress: {\n method: 'GET' as const,\n path: '/api/v1/data/export/:jobId',\n input: z.object({ jobId: z.string() }),\n output: ExportJobProgressSchema,\n },\n getExportJobDownload: {\n method: 'GET' as const,\n path: '/api/v1/data/export/:jobId/download',\n input: GetExportJobDownloadRequestSchema,\n output: GetExportJobDownloadResponseSchema,\n },\n listExportJobs: {\n method: 'GET' as const,\n path: '/api/v1/data/export',\n input: ListExportJobsRequestSchema,\n output: ListExportJobsResponseSchema,\n },\n scheduleExport: {\n method: 'POST' as const,\n path: '/api/v1/data/export/schedules',\n input: ScheduleExportRequestSchema,\n output: ScheduleExportResponseSchema,\n },\n cancelExportJob: {\n method: 'POST' as const,\n path: '/api/v1/data/export/:jobId/cancel',\n input: z.object({ jobId: z.string() }),\n output: BaseResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Flow Node Types\n */\nexport const FlowNodeAction = z.enum([\n 'start', // Trigger\n 'end', // Return/Stop\n 'decision', // If/Else logic\n 'assignment', // Set Variable\n 'loop', // For Each\n 'create_record', // CRUD: Create\n 'update_record', // CRUD: Update\n 'delete_record', // CRUD: Delete\n 'get_record', // CRUD: Get/Query\n 'http_request', // Webhook/API Call\n 'script', // Custom Script (JS/TS)\n 'screen', // Screen / User-Input Element\n 'wait', // Delay/Sleep\n 'subflow', // Call another flow\n 'connector_action', // Zapier-style integration action\n 'parallel_gateway', // BPMN Parallel Gateway — AND-split (all outgoing branches execute concurrently)\n 'join_gateway', // BPMN Join Gateway — AND-join (waits for all incoming branches to complete)\n 'boundary_event', // BPMN Boundary Event — attached to a host node for timer/error/signal interrupts\n]);\n\n/**\n * Flow Variable Schema\n * Variables available within the flow execution context.\n */\nexport const FlowVariableSchema = z.object({\n name: z.string().describe('Variable name'),\n type: z.string().describe('Data type (text, number, boolean, object, list)'),\n isInput: z.boolean().default(false).describe('Is input parameter'),\n isOutput: z.boolean().default(false).describe('Is output parameter'),\n});\n\n/**\n * Flow Node Schema\n * A single step in the visual logic graph.\n * \n * @example Decision Node\n * {\n * id: \"dec_1\",\n * type: \"decision\",\n * label: \"Is High Value?\",\n * config: {\n * conditions: [\n * { label: \"Yes\", expression: \"{amount} > 10000\" },\n * { label: \"No\", expression: \"true\" } // default\n * ]\n * },\n * position: { x: 300, y: 200 }\n * }\n */\nexport const FlowNodeSchema = z.object({\n id: z.string().describe('Node unique ID'),\n type: FlowNodeAction.describe('Action type'),\n label: z.string().describe('Node label'),\n \n /** Node Configuration Options (Specific to type) */\n config: z.record(z.string(), z.unknown()).optional().describe('Node configuration'),\n \n /** \n * Connector Action Configuration\n * Used when type is 'connector_action'\n */\n connectorConfig: z.object({\n connectorId: z.string(),\n actionId: z.string(),\n input: z.record(z.string(), z.unknown()).describe('Mapped inputs for the action'),\n }).optional(),\n\n /** UI Position (for the canvas) */\n position: z.object({ x: z.number(), y: z.number() }).optional(),\n\n /** Node-level execution timeout */\n timeoutMs: z.number().int().min(0).optional().describe('Maximum execution time for this node in milliseconds'),\n\n /** Node input schema declaration for Studio form generation and runtime validation */\n inputSchema: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).describe('Parameter type'),\n required: z.boolean().default(false).describe('Whether the parameter is required'),\n description: z.string().optional().describe('Parameter description'),\n })).optional().describe('Input parameter schema for this node'),\n\n /** Node output schema declaration */\n outputSchema: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).describe('Output type'),\n description: z.string().optional().describe('Output description'),\n })).optional().describe('Output schema declaration for this node'),\n\n /**\n * Wait Event Configuration (for 'wait' nodes)\n * Defines what external event or condition should resume the paused execution.\n * Industry alignment: BPMN Intermediate Catch Events, Temporal Signals.\n */\n waitEventConfig: z.object({\n /** Type of event to wait for */\n eventType: z.enum(['timer', 'signal', 'webhook', 'manual', 'condition'])\n .describe('What kind of event resumes the execution'),\n /** Duration to wait (ISO 8601 duration or milliseconds) — for timer events */\n timerDuration: z.string().optional().describe('ISO 8601 duration (e.g., \"PT1H\") or wait time for timer events'),\n /** Signal name to listen for — for signal/webhook events */\n signalName: z.string().optional().describe('Named signal or webhook event to wait for'),\n /** Timeout before auto-failing or continuing — optional guard */\n timeoutMs: z.number().int().min(0).optional().describe('Maximum wait time before timeout (ms)'),\n /** Action to take on timeout */\n onTimeout: z.enum(['fail', 'continue']).default('fail').describe('Behavior when the wait times out'),\n }).optional().describe('Configuration for wait node event resumption'),\n\n /**\n * Boundary Event Configuration (for 'boundary_event' nodes)\n * Attaches an event handler to a host activity node (BPMN Boundary Event pattern).\n * Industry alignment: BPMN Boundary Error/Timer/Signal Events.\n */\n boundaryConfig: z.object({\n /** ID of the host node this boundary event is attached to */\n attachedToNodeId: z.string().describe('Host node ID this boundary event monitors'),\n /** Type of boundary event */\n eventType: z.enum(['error', 'timer', 'signal', 'cancel'])\n .describe('Boundary event trigger type'),\n /** Whether the boundary event interrupts the host activity */\n interrupting: z.boolean().default(true)\n .describe('If true, the host activity is cancelled when this event fires'),\n /** Error code filter — only for error boundary events */\n errorCode: z.string().optional().describe('Specific error code to catch (empty = catch all errors)'),\n /** Timer duration — only for timer boundary events */\n timerDuration: z.string().optional().describe('ISO 8601 duration for timer boundary events'),\n /** Signal name — only for signal boundary events */\n signalName: z.string().optional().describe('Named signal to catch'),\n }).optional().describe('Configuration for boundary events attached to host nodes'),\n});\n\n/**\n * Flow Edge Schema\n * Connections between nodes.\n */\nexport const FlowEdgeSchema = z.object({\n id: z.string().describe('Edge unique ID'),\n source: z.string().describe('Source Node ID'),\n target: z.string().describe('Target Node ID'),\n \n /** Condition for this path (only for decision/branch nodes) */\n condition: z.string().optional().describe('Expression returning boolean used for branching'),\n \n type: z.enum(['default', 'fault', 'conditional']).default('default')\n .describe('Connection type: default (normal flow), fault (error path), or conditional (expression-guarded)'),\n label: z.string().optional().describe('Label on the connector'),\n\n /**\n * Default Sequence Flow marker (BPMN Default Flow semantics).\n * When true, this edge is taken when no sibling conditional edges match.\n * Only meaningful on outgoing edges of decision/gateway nodes.\n */\n isDefault: z.boolean().default(false)\n .describe('Marks this edge as the default path when no other conditions match'),\n});\n\n/**\n * Flow Schema\n * Visual Business Logic Orchestration.\n * \n * @example Simple Approval Logic\n * {\n * name: \"approve_order_flow\",\n * label: \"Approve Large Orders\",\n * type: \"record_change\",\n * status: \"active\",\n * nodes: [\n * { id: \"start\", type: \"start\", label: \"Start\", position: {x: 0, y: 0} },\n * { id: \"check_amount\", type: \"decision\", label: \"Check Amount\", position: {x: 0, y: 100} },\n * { id: \"auto_approve\", type: \"update_record\", label: \"Auto Approve\", position: {x: -100, y: 200} },\n * { id: \"submit_for_approval\", type: \"connector_action\", label: \"Submit\", position: {x: 100, y: 200} }\n * ],\n * edges: [\n * { id: \"e1\", source: \"start\", target: \"check_amount\" },\n * { id: \"e2\", source: \"check_amount\", target: \"auto_approve\", condition: \"{amount} < 500\" },\n * { id: \"e3\", source: \"check_amount\", target: \"submit_for_approval\", condition: \"{amount} >= 500\" }\n * ]\n * }\n */\nexport const FlowSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name'),\n label: z.string().describe('Flow label'),\n description: z.string().optional(),\n \n /** Metadata & Versioning */\n version: z.number().int().default(1).describe('Version number'),\n status: z.enum(['draft', 'active', 'obsolete', 'invalid']).default('draft').describe('Deployment status'),\n template: z.boolean().default(false).describe('Is logic template (Subflow)'),\n\n /** Trigger Type */\n type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).describe('Flow type'),\n \n /** Configuration Variables */\n variables: z.array(FlowVariableSchema).optional().describe('Flow variables'),\n \n /** Graph Definition */\n nodes: z.array(FlowNodeSchema).describe('Flow nodes'),\n edges: z.array(FlowEdgeSchema).describe('Flow connections'),\n \n /** Execution Config */\n active: z.boolean().default(false).describe('Is active (Deprecated: use status)'),\n runAs: z.enum(['system', 'user']).default('user').describe('Execution context'),\n\n /** Error Handling Strategy */\n errorHandling: z.object({\n strategy: z.enum(['fail', 'retry', 'continue']).default('fail').describe('How to handle node execution errors'),\n maxRetries: z.number().int().min(0).max(10).default(0).describe('Number of retry attempts (only for retry strategy)'),\n retryDelayMs: z.number().int().min(0).default(1000).describe('Delay between retries in milliseconds'),\n backoffMultiplier: z.number().min(1).default(1).describe('Multiplier for exponential backoff between retries'),\n maxRetryDelayMs: z.number().int().min(0).default(30000).describe('Maximum delay between retries in milliseconds'),\n jitter: z.boolean().default(false).describe('Add random jitter to retry delay to avoid thundering herd'),\n fallbackNodeId: z.string().optional().describe('Node ID to jump to on unrecoverable error'),\n }).optional().describe('Flow-level error handling configuration'),\n});\n\n/**\n * Type-safe factory for creating flow definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const onCreateFlow = defineFlow({\n * name: 'on_task_create',\n * label: 'On Task Create',\n * type: 'record_change',\n * nodes: [\n * { id: 'start', type: 'start', label: 'Start' },\n * { id: 'end', type: 'end', label: 'End' },\n * ],\n * edges: [{ id: 'e1', source: 'start', target: 'end' }],\n * });\n * ```\n */\nexport function defineFlow(config: z.input): FlowParsed {\n return FlowSchema.parse(config);\n}\n\nexport type Flow = z.input;\nexport type FlowParsed = z.infer;\nexport type FlowNode = z.input;\nexport type FlowNodeParsed = z.infer;\nexport type FlowEdge = z.input;\nexport type FlowEdgeParsed = z.infer;\n\n/**\n * Flow Version History Schema\n * Tracks historical versions of flow definitions for rollback support.\n *\n * Industry alignment: Salesforce Flow Versions, n8n Workflow History.\n */\nexport const FlowVersionHistorySchema = z.object({\n flowName: z.string().describe('Flow machine name'),\n version: z.number().int().min(1).describe('Version number'),\n definition: FlowSchema.describe('Complete flow definition snapshot'),\n createdAt: z.string().datetime().describe('When this version was created'),\n createdBy: z.string().optional().describe('User who created this version'),\n changeNote: z.string().optional().describe('Description of what changed in this version'),\n});\n\nexport type FlowVersionHistory = z.input;\nexport type FlowVersionHistoryParsed = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Automation Execution Protocol\n *\n * Defines schemas for execution logging, error tracking, checkpointing,\n * concurrency control, and scheduled execution persistence.\n *\n * Industry alignment: Salesforce Flow Interviews, Temporal Workflow History,\n * AWS Step Functions execution logs.\n */\n\n// ==========================================\n// 1. Execution Status\n// ==========================================\n\n/**\n * Execution Status Enum\n * Tracks the lifecycle of a flow execution instance.\n */\nexport const ExecutionStatus = z.enum([\n 'pending', // Queued, not yet started\n 'running', // Currently executing\n 'paused', // Paused at a wait/checkpoint node\n 'completed', // Successfully finished\n 'failed', // Terminated with error\n 'cancelled', // Manually cancelled\n 'timed_out', // Exceeded max execution time\n 'retrying', // Failed and retrying\n]);\nexport type ExecutionStatus = z.infer;\n\n// ==========================================\n// 2. Execution Log\n// ==========================================\n\n/**\n * Execution Step Log Entry\n * Records the result of executing a single node in the flow graph.\n */\nexport const ExecutionStepLogSchema = z.object({\n nodeId: z.string().describe('Node ID that was executed'),\n nodeType: z.string().describe('Node action type (e.g., \"decision\", \"http_request\")'),\n nodeLabel: z.string().optional().describe('Human-readable node label'),\n status: z.enum(['success', 'failure', 'skipped']).describe('Step execution result'),\n startedAt: z.string().datetime().describe('When the step started'),\n completedAt: z.string().datetime().optional().describe('When the step completed'),\n durationMs: z.number().int().min(0).optional().describe('Step execution duration in milliseconds'),\n input: z.record(z.string(), z.unknown()).optional().describe('Input data passed to the node'),\n output: z.record(z.string(), z.unknown()).optional().describe('Output data produced by the node'),\n error: z.object({\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n }).optional().describe('Error details if step failed'),\n retryAttempt: z.number().int().min(0).optional().describe('Retry attempt number (0 = first try)'),\n});\nexport type ExecutionStepLog = z.infer;\n\n/**\n * Execution Log Schema\n * Full execution history for a single flow run.\n *\n * @example\n * {\n * id: 'exec_001',\n * flowName: 'approve_order_flow',\n * flowVersion: 1,\n * status: 'completed',\n * trigger: { type: 'record_change', recordId: 'rec_123', object: 'order' },\n * steps: [\n * { nodeId: 'start', nodeType: 'start', status: 'success', startedAt: '...', durationMs: 1 },\n * { nodeId: 'check_amount', nodeType: 'decision', status: 'success', startedAt: '...', durationMs: 5 },\n * ],\n * startedAt: '2026-02-01T10:00:00Z',\n * completedAt: '2026-02-01T10:00:01Z',\n * durationMs: 1050,\n * }\n */\nexport const ExecutionLogSchema = z.object({\n /** Unique execution ID */\n id: z.string().describe('Execution instance ID'),\n\n /** Flow reference */\n flowName: z.string().describe('Machine name of the executed flow'),\n flowVersion: z.number().int().optional().describe('Version of the flow that was executed'),\n\n /** Execution status */\n status: ExecutionStatus.describe('Current execution status'),\n\n /** Trigger context */\n trigger: z.object({\n type: z.string().describe('Trigger type (e.g., \"record_change\", \"schedule\", \"api\", \"manual\")'),\n recordId: z.string().optional().describe('Triggering record ID'),\n object: z.string().optional().describe('Triggering object name'),\n userId: z.string().optional().describe('User who triggered the execution'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional trigger context'),\n }).describe('What triggered this execution'),\n\n /** Step-by-step execution history */\n steps: z.array(ExecutionStepLogSchema).describe('Ordered list of executed steps'),\n\n /** Execution variables snapshot */\n variables: z.record(z.string(), z.unknown()).optional().describe('Final state of flow variables'),\n\n /** Timing */\n startedAt: z.string().datetime().describe('Execution start timestamp'),\n completedAt: z.string().datetime().optional().describe('Execution completion timestamp'),\n durationMs: z.number().int().min(0).optional().describe('Total execution duration in milliseconds'),\n\n /** Context */\n runAs: z.enum(['system', 'user']).optional().describe('Execution context identity'),\n tenantId: z.string().optional().describe('Tenant ID for multi-tenant isolation'),\n});\nexport type ExecutionLog = z.infer;\n\n// ==========================================\n// 3. Execution Error Tracking & Diagnostics\n// ==========================================\n\n/**\n * Execution Error Severity\n */\nexport const ExecutionErrorSeverity = z.enum([\n 'warning', // Non-fatal issue (e.g., deprecated node type)\n 'error', // Node-level failure (may be retried)\n 'critical', // Flow-level failure (execution terminated)\n]);\nexport type ExecutionErrorSeverity = z.infer;\n\n/**\n * Execution Error Schema\n * Detailed error record for diagnostics and troubleshooting.\n */\nexport const ExecutionErrorSchema = z.object({\n id: z.string().describe('Error record ID'),\n executionId: z.string().describe('Parent execution ID'),\n nodeId: z.string().optional().describe('Node where the error occurred'),\n severity: ExecutionErrorSeverity.describe('Error severity level'),\n code: z.string().describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n stack: z.string().optional().describe('Stack trace for debugging'),\n context: z.record(z.string(), z.unknown()).optional()\n .describe('Additional diagnostic context (input data, config snapshot)'),\n timestamp: z.string().datetime().describe('When the error occurred'),\n retryable: z.boolean().default(false).describe('Whether this error can be retried'),\n resolvedAt: z.string().datetime().optional().describe('When the error was resolved (e.g., after successful retry)'),\n});\nexport type ExecutionError = z.infer;\n\n// ==========================================\n// 4. Checkpointing / Resume\n// ==========================================\n\n/**\n * Checkpoint Schema\n * Captures the execution state at a specific node for pause/resume.\n *\n * Used by wait nodes, user-input screens, and crash recovery.\n */\nexport const CheckpointSchema = z.object({\n /** Unique checkpoint ID */\n id: z.string().describe('Checkpoint ID'),\n\n /** Execution reference */\n executionId: z.string().describe('Parent execution ID'),\n flowName: z.string().describe('Flow machine name'),\n\n /** State snapshot */\n currentNodeId: z.string().describe('Node ID where execution is paused'),\n variables: z.record(z.string(), z.unknown()).describe('Flow variable state at checkpoint'),\n completedNodeIds: z.array(z.string()).describe('List of node IDs already executed'),\n\n /** Timing */\n createdAt: z.string().datetime().describe('Checkpoint creation timestamp'),\n expiresAt: z.string().datetime().optional().describe('Checkpoint expiration (auto-cleanup)'),\n\n /** Reason */\n reason: z.enum(['wait', 'screen_input', 'approval', 'error', 'manual_pause', 'parallel_join', 'boundary_event'])\n .describe('Why the execution was checkpointed'),\n});\nexport type Checkpoint = z.infer;\n\n// ==========================================\n// 5. Concurrency Control\n// ==========================================\n\n/**\n * Concurrency Policy Schema\n * Controls how concurrent executions of the same flow are handled.\n *\n * Industry alignment: Salesforce \"Allow multiple instances\", Temporal \"Workflow ID reuse policy\"\n */\nexport const ConcurrencyPolicySchema = z.object({\n /** Maximum concurrent executions of this flow */\n maxConcurrent: z.number().int().min(1).default(1)\n .describe('Maximum number of concurrent executions allowed'),\n\n /** What to do when max concurrency is reached */\n onConflict: z.enum(['queue', 'reject', 'cancel_existing'])\n .default('queue')\n .describe('queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance'),\n\n /** Lock scope for concurrency */\n lockScope: z.enum(['global', 'per_record', 'per_user'])\n .default('global')\n .describe('Scope of the concurrency lock'),\n\n /** Queue timeout (only when onConflict is \"queue\") */\n queueTimeoutMs: z.number().int().min(0).optional()\n .describe('Maximum time to wait in queue before timing out (ms)'),\n});\nexport type ConcurrencyPolicy = z.infer;\n\n// ==========================================\n// 6. Scheduled Execution Persistence\n// ==========================================\n\n/**\n * Schedule State Schema\n * Tracks the runtime state of scheduled flow executions.\n *\n * Persists next-run times, pause/resume state, and execution history references.\n */\nexport const ScheduleStateSchema = z.object({\n /** Unique schedule ID */\n id: z.string().describe('Schedule instance ID'),\n\n /** Flow reference */\n flowName: z.string().describe('Flow machine name'),\n\n /** Schedule configuration */\n cronExpression: z.string().describe('Cron expression (e.g., \"0 9 * * MON-FRI\")'),\n timezone: z.string().default('UTC').describe('IANA timezone for cron evaluation'),\n\n /** Runtime state */\n status: z.enum(['active', 'paused', 'disabled', 'expired'])\n .default('active')\n .describe('Current schedule status'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution timestamp'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n lastExecutionId: z.string().optional().describe('Execution ID of the last run'),\n lastRunStatus: ExecutionStatus.optional().describe('Status of the last run'),\n\n /** Execution tracking */\n totalRuns: z.number().int().min(0).default(0).describe('Total number of executions'),\n consecutiveFailures: z.number().int().min(0).default(0).describe('Consecutive failed executions'),\n\n /** Bounds */\n startDate: z.string().datetime().optional().describe('Schedule effective start date'),\n endDate: z.string().datetime().optional().describe('Schedule expiration date'),\n maxRuns: z.number().int().min(1).optional().describe('Maximum total executions before auto-disable'),\n\n /** Metadata */\n createdAt: z.string().datetime().describe('Schedule creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n createdBy: z.string().optional().describe('User who created the schedule'),\n});\nexport type ScheduleState = z.infer;\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type ExecutionStepLogParsed = z.infer;\nexport type ExecutionLogParsed = z.infer;\nexport type ExecutionErrorParsed = z.infer;\nexport type CheckpointParsed = z.infer;\nexport type ConcurrencyPolicyParsed = z.infer;\nexport type ScheduleStateParsed = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { FlowSchema } from '../automation/flow.zod';\nimport { ExecutionLogSchema } from '../automation/execution.zod';\n\n/**\n * Automation API Protocol\n *\n * Defines REST CRUD endpoint schemas for managing automation flows,\n * triggering executions, and querying execution history.\n *\n * Base path: /api/automation\n *\n * @example Endpoints\n * GET /api/automation — List flows\n * GET /api/automation/:name — Get flow\n * POST /api/automation — Create flow\n * PUT /api/automation/:name — Update flow\n * DELETE /api/automation/:name — Delete flow\n * POST /api/automation/:name/trigger — Trigger flow execution\n * POST /api/automation/:name/toggle — Enable/disable flow\n * GET /api/automation/:name/runs — List execution runs\n * GET /api/automation/:name/runs/:runId — Get single execution run\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Path parameters for flow-level operations.\n */\nexport const AutomationFlowPathParamsSchema = z.object({\n name: z.string().describe('Flow machine name (snake_case)'),\n});\nexport type AutomationFlowPathParams = z.infer;\n\n/**\n * Path parameters for run-level operations.\n */\nexport const AutomationRunPathParamsSchema = AutomationFlowPathParamsSchema.extend({\n runId: z.string().describe('Execution run ID'),\n});\nexport type AutomationRunPathParams = z.infer;\n\n// ==========================================\n// 2. List Flows (GET /api/automation)\n// ==========================================\n\n/**\n * Query parameters for listing automation flows.\n *\n * @example GET /api/automation?status=active&limit=20\n */\nexport const ListFlowsRequestSchema = z.object({\n status: z.enum(['draft', 'active', 'obsolete', 'invalid']).optional()\n .describe('Filter by flow status'),\n type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).optional()\n .describe('Filter by flow type'),\n limit: z.number().int().min(1).max(100).default(50)\n .describe('Maximum number of flows to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type ListFlowsRequest = z.infer;\n\n/**\n * Summary information for a flow in list results.\n */\nexport const FlowSummarySchema = z.object({\n name: z.string().describe('Flow machine name'),\n label: z.string().describe('Flow display label'),\n type: z.string().describe('Flow type'),\n status: z.string().describe('Flow deployment status'),\n version: z.number().int().describe('Flow version number'),\n enabled: z.boolean().describe('Whether the flow is enabled for execution'),\n nodeCount: z.number().int().optional().describe('Number of nodes in the flow'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n});\nexport type FlowSummary = z.infer;\n\n/**\n * Response for the list flows endpoint.\n */\nexport const ListFlowsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n flows: z.array(FlowSummarySchema).describe('Flow summaries'),\n total: z.number().int().optional().describe('Total matching flows'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more flows are available'),\n }),\n});\nexport type ListFlowsResponse = z.infer;\n\n// ==========================================\n// 3. Get Flow (GET /api/automation/:name)\n// ==========================================\n\n/**\n * Request parameters for getting a single flow.\n */\nexport const GetFlowRequestSchema = AutomationFlowPathParamsSchema;\nexport type GetFlowRequest = z.infer;\n\n/**\n * Response for the get flow endpoint.\n */\nexport const GetFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('Full flow definition'),\n});\nexport type GetFlowResponse = z.infer;\n\n// ==========================================\n// 4. Create Flow (POST /api/automation)\n// ==========================================\n\n/**\n * Request body for creating a new flow.\n *\n * @example POST /api/automation\n * { name: 'approval_flow', label: 'Approval Flow', type: 'autolaunched', ... }\n */\nexport const CreateFlowRequestSchema = FlowSchema;\nexport type CreateFlowRequest = z.input;\n\n/**\n * Response after creating a flow.\n */\nexport const CreateFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('The created flow definition'),\n});\nexport type CreateFlowResponse = z.infer;\n\n// ==========================================\n// 5. Update Flow (PUT /api/automation/:name)\n// ==========================================\n\n/**\n * Request body for updating an existing flow.\n *\n * @example PUT /api/automation/approval_flow\n * { label: 'Updated Label', nodes: [...], edges: [...] }\n */\nexport const UpdateFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n definition: FlowSchema.partial().describe('Partial flow definition to update'),\n});\nexport type UpdateFlowRequest = z.infer;\n\n/**\n * Response after updating a flow.\n */\nexport const UpdateFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('The updated flow definition'),\n});\nexport type UpdateFlowResponse = z.infer;\n\n// ==========================================\n// 6. Delete Flow (DELETE /api/automation/:name)\n// ==========================================\n\n/**\n * Request parameters for deleting a flow.\n */\nexport const DeleteFlowRequestSchema = AutomationFlowPathParamsSchema;\nexport type DeleteFlowRequest = z.infer;\n\n/**\n * Response after deleting a flow.\n */\nexport const DeleteFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n name: z.string().describe('Name of the deleted flow'),\n deleted: z.boolean().describe('Whether the flow was deleted'),\n }),\n});\nexport type DeleteFlowResponse = z.infer;\n\n// ==========================================\n// 7. Trigger Flow (POST /api/automation/:name/trigger)\n// ==========================================\n\n/**\n * Request body for triggering a flow execution.\n *\n * @example POST /api/automation/approval_flow/trigger\n * { record: { id: 'rec-1' }, object: 'account', event: 'on_create' }\n */\nexport const TriggerFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n record: z.record(z.string(), z.unknown()).optional()\n .describe('Record that triggered the automation'),\n object: z.string().optional()\n .describe('Object name the record belongs to'),\n event: z.string().optional()\n .describe('Trigger event type'),\n userId: z.string().optional()\n .describe('User who triggered the automation'),\n params: z.record(z.string(), z.unknown()).optional()\n .describe('Additional contextual data'),\n});\nexport type TriggerFlowRequest = z.infer;\n\n/**\n * Response after triggering a flow execution.\n */\nexport const TriggerFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the automation completed successfully'),\n output: z.unknown().optional().describe('Output data from the automation'),\n error: z.string().optional().describe('Error message if execution failed'),\n durationMs: z.number().optional().describe('Execution duration in milliseconds'),\n }),\n});\nexport type TriggerFlowResponse = z.infer;\n\n// ==========================================\n// 8. Toggle Flow (POST /api/automation/:name/toggle)\n// ==========================================\n\n/**\n * Request body for enabling/disabling a flow.\n *\n * @example POST /api/automation/approval_flow/toggle\n * { enabled: true }\n */\nexport const ToggleFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n enabled: z.boolean().describe('Whether to enable (true) or disable (false) the flow'),\n});\nexport type ToggleFlowRequest = z.infer;\n\n/**\n * Response after toggling a flow.\n */\nexport const ToggleFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n name: z.string().describe('Flow name'),\n enabled: z.boolean().describe('New enabled state'),\n }),\n});\nexport type ToggleFlowResponse = z.infer;\n\n// ==========================================\n// 9. List Runs (GET /api/automation/:name/runs)\n// ==========================================\n\n/**\n * Query parameters for listing execution runs.\n *\n * @example GET /api/automation/approval_flow/runs?status=completed&limit=10\n */\nexport const ListRunsRequestSchema = AutomationFlowPathParamsSchema.extend({\n status: z.enum(['pending', 'running', 'paused', 'completed', 'failed', 'cancelled', 'timed_out', 'retrying']).optional()\n .describe('Filter by execution status'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of runs to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type ListRunsRequest = z.infer;\n\n/**\n * Response for the list runs endpoint.\n */\nexport const ListRunsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n runs: z.array(ExecutionLogSchema).describe('Execution run logs'),\n total: z.number().int().optional().describe('Total matching runs'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more runs are available'),\n }),\n});\nexport type ListRunsResponse = z.infer;\n\n// ==========================================\n// 10. Get Run (GET /api/automation/:name/runs/:runId)\n// ==========================================\n\n/**\n * Request parameters for getting a single execution run.\n */\nexport const GetRunRequestSchema = AutomationRunPathParamsSchema;\nexport type GetRunRequest = z.infer;\n\n/**\n * Response for the get run endpoint.\n */\nexport const GetRunResponseSchema = BaseResponseSchema.extend({\n data: ExecutionLogSchema.describe('Full execution log with step details'),\n});\nexport type GetRunResponse = z.infer;\n\n// ==========================================\n// 11. Automation API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Automation operations.\n */\nexport const AutomationApiErrorCode = z.enum([\n 'flow_not_found',\n 'flow_already_exists',\n 'flow_validation_failed',\n 'flow_disabled',\n 'execution_not_found',\n 'execution_failed',\n 'execution_timeout',\n 'node_executor_not_found',\n 'concurrent_execution_limit',\n]);\nexport type AutomationApiErrorCode = z.infer;\n\n// ==========================================\n// 12. Automation API Contract Registry\n// ==========================================\n\n/**\n * Standard Automation API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const AutomationApiContracts = {\n listFlows: {\n method: 'GET' as const,\n path: '/api/automation',\n input: ListFlowsRequestSchema,\n output: ListFlowsResponseSchema,\n },\n getFlow: {\n method: 'GET' as const,\n path: '/api/automation/:name',\n input: GetFlowRequestSchema,\n output: GetFlowResponseSchema,\n },\n createFlow: {\n method: 'POST' as const,\n path: '/api/automation',\n input: CreateFlowRequestSchema,\n output: CreateFlowResponseSchema,\n },\n updateFlow: {\n method: 'PUT' as const,\n path: '/api/automation/:name',\n input: UpdateFlowRequestSchema,\n output: UpdateFlowResponseSchema,\n },\n deleteFlow: {\n method: 'DELETE' as const,\n path: '/api/automation/:name',\n input: DeleteFlowRequestSchema,\n output: DeleteFlowResponseSchema,\n },\n triggerFlow: {\n method: 'POST' as const,\n path: '/api/automation/:name/trigger',\n input: TriggerFlowRequestSchema,\n output: TriggerFlowResponseSchema,\n },\n toggleFlow: {\n method: 'POST' as const,\n path: '/api/automation/:name/toggle',\n input: ToggleFlowRequestSchema,\n output: ToggleFlowResponseSchema,\n },\n listRuns: {\n method: 'GET' as const,\n path: '/api/automation/:name/runs',\n input: ListRunsRequestSchema,\n output: ListRunsResponseSchema,\n },\n getRun: {\n method: 'GET' as const,\n path: '/api/automation/:name/runs/:runId',\n input: GetRunRequestSchema,\n output: GetRunResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { InstalledPackageSchema } from '../kernel/package-registry.zod';\nimport { DependencyResolutionResultSchema } from '../kernel/dependency-resolution.zod';\nimport { UpgradePlanSchema } from '../kernel/package-upgrade.zod';\nimport { PackageArtifactSchema } from '../kernel/package-artifact.zod';\nimport { ManifestSchema } from '../kernel/manifest.zod';\nimport { ArtifactReferenceSchema } from '../cloud/marketplace.zod';\n\n/**\n * # Package API Protocol\n *\n * REST API endpoint schemas for package lifecycle management.\n *\n * Base path: /api/v1/packages\n *\n * @example Endpoints\n * POST /api/v1/packages/install — Install a package\n * POST /api/v1/packages/upgrade — Upgrade a package\n * POST /api/v1/packages/resolve-dependencies — Resolve dependencies\n * POST /api/v1/packages/upload — Upload an artifact\n * GET /api/v1/packages — List installed packages\n * GET /api/v1/packages/:packageId — Get package details\n * POST /api/v1/packages/:packageId/rollback — Rollback a package\n * DELETE /api/v1/packages/:packageId — Uninstall a package\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Path parameters for package-level operations.\n */\nexport const PackagePathParamsSchema = z.object({\n packageId: z.string().describe('Package identifier'),\n});\nexport type PackagePathParams = z.infer;\n\n// ==========================================\n// 2. List Packages (GET /api/v1/packages)\n// ==========================================\n\n/**\n * Query parameters for listing installed packages.\n */\nexport const ListInstalledPackagesRequestSchema = z.object({\n /** Filter by package status */\n status: z.enum(['installed', 'disabled', 'installing', 'upgrading', 'uninstalling', 'error']).optional()\n .describe('Filter by package status'),\n /** Filter by enabled state */\n enabled: z.boolean().optional()\n .describe('Filter by enabled state'),\n /** Maximum number of packages to return */\n limit: z.number().int().min(1).max(100).default(50)\n .describe('Maximum number of packages to return'),\n /** Cursor for pagination */\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n}).describe('List installed packages request');\nexport type ListInstalledPackagesRequest = z.infer;\n\n/**\n * Response for listing installed packages.\n */\nexport const ListInstalledPackagesResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n packages: z.array(InstalledPackageSchema).describe('Installed packages'),\n total: z.number().int().optional().describe('Total matching packages'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more packages are available'),\n }),\n}).describe('List installed packages response');\nexport type ListInstalledPackagesResponse = z.infer;\n\n// ==========================================\n// 3. Get Package (GET /api/v1/packages/:packageId)\n// ==========================================\n\n/**\n * Request for getting a single installed package.\n */\nexport const GetInstalledPackageRequestSchema = PackagePathParamsSchema;\nexport type GetInstalledPackageRequest = z.infer;\n\n/**\n * Response for getting a single installed package.\n */\nexport const GetInstalledPackageResponseSchema = BaseResponseSchema.extend({\n data: InstalledPackageSchema.describe('Installed package details'),\n}).describe('Get installed package response');\nexport type GetInstalledPackageResponse = z.infer;\n\n// ==========================================\n// 4. Install Package (POST /api/v1/packages/install)\n// ==========================================\n\n/**\n * Request body for installing a package.\n *\n * @example POST /api/v1/packages/install\n * { manifest: {...}, platformVersion: '3.2.0', enableOnInstall: true }\n */\nexport const PackageInstallRequestSchema = z.object({\n /** Package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n\n /** User-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n\n /** Whether to enable immediately after install */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n\n /** Current platform version for compatibility verification */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n\n /** Artifact reference for the package (if installing from marketplace) */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference for marketplace installation'),\n}).describe('Install package request');\nexport type PackageInstallRequest = z.infer;\n\n/**\n * Response after installing a package.\n */\nexport const PackageInstallResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result'),\n namespaceConflicts: z.array(z.object({\n type: z.literal('namespace_conflict').describe('Error type'),\n requestedNamespace: z.string().describe('Requested namespace'),\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n conflictingPackageName: z.string().describe('Conflicting package name'),\n suggestion: z.string().optional().describe('Suggested alternative'),\n })).optional().describe('Namespace conflicts detected'),\n message: z.string().optional().describe('Installation status message'),\n }),\n}).describe('Install package response');\nexport type PackageInstallResponse = z.infer;\n\n// ==========================================\n// 5. Upgrade Package (POST /api/v1/packages/upgrade)\n// ==========================================\n\n/**\n * Request body for upgrading a package.\n *\n * @example POST /api/v1/packages/upgrade\n * { packageId: 'com.acme.crm', targetVersion: '2.0.0', createSnapshot: true }\n */\nexport const PackageUpgradeRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (defaults to latest) */\n targetVersion: z.string().optional()\n .describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional()\n .describe('New manifest for the target version'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum(['keep-custom', 'accept-incoming', 'three-way-merge'])\n .default('three-way-merge')\n .describe('How to handle customer customizations'),\n\n /** Preview upgrade without making changes */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Skip pre-upgrade compatibility checks */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\nexport type PackageUpgradeRequest = z.infer;\n\n/**\n * Response after upgrading a package.\n */\nexport const PackageUpgradeResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the upgrade succeeded'),\n phase: z.string().describe('Current upgrade phase'),\n plan: UpgradePlanSchema.optional().describe('Upgrade plan that was executed'),\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n conflicts: z.array(z.object({\n path: z.string().describe('Conflict path'),\n baseValue: z.unknown().describe('Base value'),\n incomingValue: z.unknown().describe('Incoming value'),\n customValue: z.unknown().describe('Custom value'),\n })).optional().describe('Unresolved merge conflicts'),\n errorMessage: z.string().optional().describe('Error message if failed'),\n message: z.string().optional().describe('Human-readable status message'),\n }),\n}).describe('Upgrade package response');\nexport type PackageUpgradeResponse = z.infer;\n\n// ==========================================\n// 6. Resolve Dependencies (POST /api/v1/packages/resolve-dependencies)\n// ==========================================\n\n/**\n * Request body for resolving package dependencies.\n *\n * @example POST /api/v1/packages/resolve-dependencies\n * { manifest: {...}, platformVersion: '3.2.0' }\n */\nexport const ResolveDependenciesRequestSchema = z.object({\n /** Package manifest whose dependencies to resolve */\n manifest: ManifestSchema.describe('Package manifest to resolve dependencies for'),\n\n /** Current platform version for compatibility checking */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility filtering'),\n}).describe('Resolve dependencies request');\nexport type ResolveDependenciesRequest = z.infer;\n\n/**\n * Response with dependency resolution results.\n */\nexport const ResolveDependenciesResponseSchema = BaseResponseSchema.extend({\n data: DependencyResolutionResultSchema.describe('Dependency resolution result with topological sort'),\n}).describe('Resolve dependencies response');\nexport type ResolveDependenciesResponse = z.infer;\n\n// ==========================================\n// 7. Upload Artifact (POST /api/v1/packages/upload)\n// ==========================================\n\n/**\n * Request body for uploading a package artifact.\n *\n * @example POST /api/v1/packages/upload\n * Content-Type: multipart/form-data\n * { artifact: , file: }\n */\nexport const UploadArtifactRequestSchema = z.object({\n /** Artifact metadata */\n artifact: PackageArtifactSchema.describe('Package artifact metadata'),\n\n /** SHA256 checksum of the uploaded file (for verification) */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).optional()\n .describe('SHA256 checksum of the uploaded file'),\n\n /** Publisher authentication token */\n token: z.string().optional()\n .describe('Publisher authentication token'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional()\n .describe('Release notes for this version'),\n}).describe('Upload artifact request');\nexport type UploadArtifactRequest = z.infer;\n\n/**\n * Response after uploading a package artifact.\n */\nexport const UploadArtifactResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n /** Whether the upload succeeded */\n success: z.boolean().describe('Whether the upload succeeded'),\n /** Artifact reference for the uploaded package */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference in the registry'),\n /** Submission ID for review tracking */\n submissionId: z.string().optional()\n .describe('Marketplace submission ID for review tracking'),\n /** Message */\n message: z.string().optional().describe('Upload status message'),\n }),\n}).describe('Upload artifact response');\nexport type UploadArtifactResponse = z.infer;\n\n// ==========================================\n// 8. Rollback Package (POST /api/v1/packages/:packageId/rollback)\n// ==========================================\n\n/**\n * Request body for rolling back a package upgrade.\n */\nexport const PackageRollbackRequestSchema = PackagePathParamsSchema.extend({\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\nexport type PackageRollbackRequest = z.infer;\n\n/**\n * Response after rolling back a package.\n */\nexport const PackageRollbackResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the rollback succeeded'),\n restoredVersion: z.string().optional().describe('Restored version'),\n message: z.string().optional().describe('Rollback status message'),\n }),\n}).describe('Rollback package response');\nexport type PackageRollbackResponse = z.infer;\n\n// ==========================================\n// 9. Uninstall Package (DELETE /api/v1/packages/:packageId)\n// ==========================================\n\n/**\n * Request for uninstalling a package.\n */\nexport const UninstallPackageApiRequestSchema = PackagePathParamsSchema;\nexport type UninstallPackageApiRequest = z.infer;\n\n/**\n * Response after uninstalling a package.\n */\nexport const UninstallPackageApiResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n packageId: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n }),\n}).describe('Uninstall package response');\nexport type UninstallPackageApiResponse = z.infer;\n\n// ==========================================\n// 10. Package API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Package operations.\n */\nexport const PackageApiErrorCode = z.enum([\n 'package_not_found',\n 'package_already_installed',\n 'version_not_found',\n 'dependency_conflict',\n 'namespace_conflict',\n 'platform_incompatible',\n 'artifact_invalid',\n 'checksum_mismatch',\n 'signature_invalid',\n 'upgrade_failed',\n 'rollback_failed',\n 'snapshot_not_found',\n 'upload_failed',\n]);\nexport type PackageApiErrorCode = z.infer;\n\n// ==========================================\n// 11. Package API Contract Registry\n// ==========================================\n\n/**\n * Standard Package API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const PackageApiContracts = {\n listPackages: {\n method: 'GET' as const,\n path: '/api/v1/packages',\n input: ListInstalledPackagesRequestSchema,\n output: ListInstalledPackagesResponseSchema,\n },\n getPackage: {\n method: 'GET' as const,\n path: '/api/v1/packages/:packageId',\n input: GetInstalledPackageRequestSchema,\n output: GetInstalledPackageResponseSchema,\n },\n installPackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/install',\n input: PackageInstallRequestSchema,\n output: PackageInstallResponseSchema,\n },\n upgradePackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/upgrade',\n input: PackageUpgradeRequestSchema,\n output: PackageUpgradeResponseSchema,\n },\n resolveDependencies: {\n method: 'POST' as const,\n path: '/api/v1/packages/resolve-dependencies',\n input: ResolveDependenciesRequestSchema,\n output: ResolveDependenciesResponseSchema,\n },\n uploadArtifact: {\n method: 'POST' as const,\n path: '/api/v1/packages/upload',\n input: UploadArtifactRequestSchema,\n output: UploadArtifactResponseSchema,\n },\n rollbackPackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/:packageId/rollback',\n input: PackageRollbackRequestSchema,\n output: PackageRollbackResponseSchema,\n },\n uninstallPackage: {\n method: 'DELETE' as const,\n path: '/api/v1/packages/:packageId',\n input: UninstallPackageApiRequestSchema,\n output: UninstallPackageApiResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n\nexport * from './workflow.zod';\nexport * from './flow.zod';\nexport * from './execution.zod';\nexport * from './webhook.zod';\nexport * from './approval.zod';\nexport * from './etl.zod';\nexport * from './trigger-registry.zod';\nexport * from './sync.zod';\nexport * from './state-machine.zod';\nexport * from './node-executor.zod';\nexport * from './bpmn-interop.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Webhook Trigger Event\n * When should this webhook fire?\n */\nexport const WebhookTriggerType = z.enum([\n 'create', \n 'update', \n 'delete', \n 'undelete',\n 'api' // Manually triggered\n]);\n\n/**\n * CANONICAL WEBHOOK DEFINITION\n * \n * This is the single source of truth for webhook configuration across ObjectStack.\n * All other protocols (workflow, connector, etc.) should import and reference this schema.\n * \n * Webhook Protocol - Outbound HTTP Integration\n * Push data to external URLs when events occur in the system.\n * \n * **NAMING CONVENTION:**\n * Webhook names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good webhook names\n * - 'stripe_payment_sync'\n * - 'slack_notification'\n * - 'crm_lead_export'\n * \n * @example Bad webhook names (will be rejected)\n * - 'StripePaymentSync' (PascalCase)\n * - 'slackNotification' (camelCase)\n * \n * @example Basic webhook configuration\n * ```typescript\n * const webhook: Webhook = {\n * name: 'slack_notification',\n * label: 'Slack Order Notification',\n * object: 'order',\n * triggers: ['create', 'update'],\n * url: 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX',\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * authentication: {\n * type: 'bearer',\n * credentials: { token: process.env.SLACK_TOKEN }\n * },\n * retryPolicy: {\n * maxRetries: 3,\n * backoffStrategy: 'exponential'\n * }\n * }\n * ```\n */\nexport const WebhookSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Webhook unique name (lowercase snake_case)'),\n label: z.string().optional().describe('Human-readable webhook label'),\n \n /** Scope */\n object: z.string().optional().describe('Object to listen to (optional for manual webhooks)'),\n triggers: z.array(WebhookTriggerType).optional().describe('Events that trigger execution'),\n \n /** Target */\n url: z.string().url().describe('External webhook endpoint URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).default('POST').describe('HTTP method'),\n \n /** Headers */\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n \n /** Body/Payload */\n body: z.unknown().optional().describe('Request body payload (if not using default record data)'),\n \n /** Payload Configuration */\n payloadFields: z.array(z.string()).optional().describe('Fields to include. Empty = All'),\n includeSession: z.boolean().default(false).describe('Include user session info'),\n \n /** Authentication */\n authentication: z.object({\n type: z.enum(['none', 'bearer', 'basic', 'api-key']).describe('Authentication type'),\n credentials: z.record(z.string(), z.string()).optional().describe('Authentication credentials'),\n }).optional().describe('Authentication configuration'),\n \n /** Retry Policy */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).max(10).default(3).describe('Maximum retry attempts'),\n backoffStrategy: z.enum(['exponential', 'linear', 'fixed']).default('exponential').describe('Backoff strategy'),\n initialDelayMs: z.number().int().min(100).default(1000).describe('Initial retry delay in milliseconds'),\n maxDelayMs: z.number().int().min(1000).default(60000).describe('Maximum retry delay in milliseconds'),\n }).optional().describe('Retry policy configuration'),\n \n /** Timeout */\n timeoutMs: z.number().int().min(1000).max(300000).default(30000).describe('Request timeout in milliseconds'),\n \n /** Security */\n secret: z.string().optional().describe('Signing secret for HMAC signature verification'),\n \n /** Status */\n isActive: z.boolean().default(true).describe('Whether webhook is active'),\n \n /** Metadata */\n description: z.string().optional().describe('Webhook description'),\n tags: z.array(z.string()).optional().describe('Tags for organization'),\n});\n\n/**\n * Webhook Receiver Schema (Inbound)\n * Handling incoming HTTP hooks from Stripe, Slack, etc.\n * \n * **NAMING CONVENTION:**\n * Webhook receiver names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good names\n * - 'stripe_webhook_handler'\n * - 'github_events'\n * - 'twilio_status_callback'\n * \n * @example Bad names (will be rejected)\n * - 'StripeWebhookHandler' (PascalCase)\n */\nexport const WebhookReceiverSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Webhook receiver unique name (lowercase snake_case)'),\n path: z.string().describe('URL Path (e.g. /webhooks/stripe)'),\n \n /** Verification */\n verificationType: z.enum(['none', 'header_token', 'hmac', 'ip_whitelist']).default('none'),\n verificationParams: z.object({\n header: z.string().optional(),\n secret: z.string().optional(),\n ips: z.array(z.string()).optional()\n }).optional(),\n \n /** Action */\n action: z.enum(['trigger_flow', 'script', 'upsert_record']).default('trigger_flow'),\n target: z.string().describe('Flow ID or Script name'),\n});\n\nexport type Webhook = z.infer;\nexport type WebhookReceiver = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Approval Step Approver Type\n */\nexport const ApproverType = z.enum([\n 'user', // Specific user(s)\n 'role', // Users with specific role\n 'manager', // Submitter's manager\n 'field', // User ID defined in a record field\n 'queue' // Data ownership queue\n]);\n\n/**\n * Approval Action Type\n * Actions to execute on transition\n */\nexport const ApprovalActionType = z.enum([\n 'field_update',\n 'email_alert',\n 'webhook',\n 'script',\n 'connector_action' // Added for Zapier-style integrations\n]);\n\n/**\n * definition of an action to perform\n */\nexport const ApprovalActionSchema = z.object({\n type: ApprovalActionType,\n name: z.string().describe('Action name'),\n config: z.record(z.string(), z.unknown()).describe('Action configuration'),\n \n /** For connector actions */\n connectorId: z.string().optional(),\n actionId: z.string().optional(),\n});\n\n/**\n * Approval Process Step\n */\nexport const ApprovalStepSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Step machine name'),\n label: z.string().describe('Step display label'),\n description: z.string().optional(),\n \n /** Entry criteria for this step */\n entryCriteria: z.string().optional().describe('Formula expression to enter this step'),\n \n /** Who can approve */\n approvers: z.array(z.object({\n type: ApproverType,\n value: z.string().describe('User ID, Role Name, or Field Name')\n })).min(1).describe('List of allowed approvers'),\n \n /** Approval Logic */\n behavior: z.enum(['first_response', 'unanimous']).default('first_response')\n .describe('How to handle multiple approvers'),\n \n /** Rejection behavior */\n rejectionBehavior: z.enum(['reject_process', 'back_to_previous'])\n .default('reject_process').describe('What happens if rejected'),\n\n /** Actions */\n onApprove: z.array(ApprovalActionSchema).optional().describe('Actions on step approval'),\n onReject: z.array(ApprovalActionSchema).optional().describe('Actions on step rejection'),\n});\n\n/**\n * Approval Process Protocol\n * \n * Defines a complex review and approval cycle for a record.\n * Manages state locking, notifications, and transition logic.\n */\nexport const ApprovalProcessSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Unique process name'),\n label: z.string().describe('Human readable label'),\n object: z.string().describe('Target Object Name'),\n \n active: z.boolean().default(false),\n description: z.string().optional(),\n \n /** Entry Criteria for the entire process */\n entryCriteria: z.string().optional().describe('Formula to allow submission'),\n \n /** Record Locking */\n lockRecord: z.boolean().default(true).describe('Lock record from editing during approval'),\n \n /** Steps */\n steps: z.array(ApprovalStepSchema).min(1).describe('Sequence of approval steps'),\n\n /** Escalation Configuration (SLA-based auto-escalation) */\n escalation: z.object({\n enabled: z.boolean().default(false).describe('Enable SLA-based escalation'),\n timeoutHours: z.number().min(1).describe('Hours before escalation triggers'),\n action: z.enum(['reassign', 'auto_approve', 'auto_reject', 'notify']).default('notify').describe('Action to take on escalation timeout'),\n escalateTo: z.string().optional().describe('User ID, role, or manager level to escalate to'),\n notifySubmitter: z.boolean().default(true).describe('Notify the original submitter on escalation'),\n }).optional().describe('SLA escalation configuration for pending approval steps'),\n \n /** Global Actions */\n onSubmit: z.array(ApprovalActionSchema).optional().describe('Actions on initial submission'),\n onFinalApprove: z.array(ApprovalActionSchema).optional().describe('Actions on final approval'),\n onFinalReject: z.array(ApprovalActionSchema).optional().describe('Actions on final rejection'),\n onRecall: z.array(ApprovalActionSchema).optional().describe('Actions on recall'),\n});\n\nexport const ApprovalProcess = Object.assign(ApprovalProcessSchema, {\n create: >(config: T) => config,\n});\n\nexport type ApprovalProcess = z.infer;\nexport type ApprovalStep = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * ETL (Extract, Transform, Load) Pipeline Protocol - LEVEL 2: Data Engineering\n * \n * Inspired by modern data integration platforms like Airbyte, Fivetran, and Apache NiFi.\n * \n * **Positioning in 3-Layer Architecture:**\n * - **L1: Simple Sync** (automation/sync.zod.ts) - Business users - Sync Salesforce to Sheets\n * - **L2: ETL Pipeline** (THIS FILE) - Data engineers - Aggregate 10 sources to warehouse\n * - **L3: Enterprise Connector** (integration/connector.zod.ts) - System integrators - Full SAP integration\n * \n * ETL pipelines enable automated data synchronization between systems, transforming\n * data as it moves from source to destination.\n * \n * **SCOPE: Advanced multi-source, multi-stage transformations.**\n * Supports complex operations: joins, aggregations, filtering, custom SQL.\n * \n * ## When to Use This Layer\n * \n * **Use ETL Pipeline when:**\n * - Combining data from multiple sources\n * - Need aggregations, joins, transformations\n * - Building data warehouses or analytics platforms\n * - Complex data transformations required\n * \n * **Examples:**\n * - Sales data from Salesforce + Marketing from HubSpot → Data Warehouse\n * - Multi-region databases → Consolidated reporting\n * - Legacy system migration with transformation\n * \n * **When to downgrade:**\n * - Simple 1:1 sync → Use {@link file://./sync.zod.ts | Simple Sync}\n * \n * **When to upgrade:**\n * - Need full connector lifecycle (auth, webhooks, rate limits) → Use {@link file://../integration/connector.zod.ts | Enterprise Connector}\n * \n * @see {@link file://./sync.zod.ts} for Level 1 (simple sync)\n * @see {@link file://../integration/connector.zod.ts} for Level 3 (enterprise integration)\n * \n * ## Use Cases\n * \n * 1. **Data Warehouse Population**\n * - Extract from multiple operational systems\n * - Transform to analytical schema\n * - Load into data warehouse\n * \n * 2. **System Integration**\n * - Sync data between CRM and Marketing Automation\n * - Keep product catalog synchronized across e-commerce platforms\n * - Replicate data for backup/disaster recovery\n * \n * 3. **Data Migration**\n * - Move data from legacy systems to modern platforms\n * - Consolidate data from multiple sources\n * - Split monolithic databases into microservices\n * \n * @see https://airbyte.com/\n * @see https://docs.fivetran.com/\n * @see https://nifi.apache.org/\n * \n * @example\n * ```typescript\n * const salesforceToDB: ETLPipeline = {\n * name: 'salesforce_to_postgres',\n * label: 'Salesforce Accounts to PostgreSQL',\n * source: {\n * type: 'api',\n * connector: 'salesforce',\n * config: { object: 'Account' }\n * },\n * destination: {\n * type: 'database',\n * connector: 'postgres',\n * config: { table: 'accounts' }\n * },\n * transformations: [\n * { type: 'map', config: { 'Name': 'account_name' } }\n * ],\n * schedule: '0 2 * * *' // Daily at 2 AM\n * }\n * ```\n */\n\n/**\n * ETL Source/Destination Type\n */\nexport const ETLEndpointTypeSchema = z.enum([\n 'database', // SQL/NoSQL databases\n 'api', // REST/GraphQL APIs\n 'file', // CSV, JSON, XML, Excel files\n 'stream', // Kafka, RabbitMQ, Kinesis\n 'object', // ObjectStack object\n 'warehouse', // Data warehouse (Snowflake, BigQuery, Redshift)\n 'storage', // S3, Azure Blob, Google Cloud Storage\n 'spreadsheet', // Google Sheets, Excel Online\n]);\n\nexport type ETLEndpointType = z.infer;\n\n/**\n * ETL Source Configuration\n */\nexport const ETLSourceSchema = z.object({\n /**\n * Source type\n */\n type: ETLEndpointTypeSchema.describe('Source type'),\n\n /**\n * Connector identifier\n * References a registered connector\n * \n * @example \"salesforce\", \"postgres\", \"mysql\", \"s3\"\n */\n connector: z.string().optional().describe('Connector ID'),\n\n /**\n * Source-specific configuration\n * Structure varies by source type\n * \n * @example For database: { table: 'customers', schema: 'public' }\n * @example For API: { endpoint: '/api/users', method: 'GET' }\n * @example For file: { path: 's3://bucket/data.csv', format: 'csv' }\n */\n config: z.record(z.string(), z.unknown()).describe('Source configuration'),\n\n /**\n * Incremental sync configuration\n * Allows extracting only changed data\n */\n incremental: z.object({\n enabled: z.boolean().default(false),\n cursorField: z.string().describe('Field to track progress (e.g., updated_at)'),\n cursorValue: z.unknown().optional().describe('Last processed value'),\n }).optional().describe('Incremental extraction config'),\n});\n\nexport type ETLSource = z.infer;\n\n/**\n * ETL Destination Configuration\n */\nexport const ETLDestinationSchema = z.object({\n /**\n * Destination type\n */\n type: ETLEndpointTypeSchema.describe('Destination type'),\n\n /**\n * Connector identifier\n */\n connector: z.string().optional().describe('Connector ID'),\n\n /**\n * Destination-specific configuration\n */\n config: z.record(z.string(), z.unknown()).describe('Destination configuration'),\n\n /**\n * Write mode\n */\n writeMode: z.enum([\n 'append', // Add new records\n 'overwrite', // Replace all data\n 'upsert', // Insert or update based on key\n 'merge', // Smart merge based on business rules\n ]).default('append').describe('How to write data'),\n\n /**\n * Primary key fields for upsert/merge\n */\n primaryKey: z.array(z.string()).optional().describe('Primary key fields'),\n});\n\nexport type ETLDestination = z.infer;\n\n/**\n * ETL Transformation Type\n */\nexport const ETLTransformationTypeSchema = z.enum([\n 'map', // Field mapping/renaming\n 'filter', // Row filtering\n 'aggregate', // Aggregation/grouping\n 'join', // Joining with other data\n 'script', // Custom JavaScript/Python script\n 'lookup', // Enrich with lookup data\n 'split', // Split one record into multiple\n 'merge', // Merge multiple records into one\n 'normalize', // Data normalization\n 'deduplicate', // Remove duplicates\n]);\n\nexport type ETLTransformationType = z.infer;\n\n/**\n * ETL Transformation Configuration\n */\nexport const ETLTransformationSchema = z.object({\n /**\n * Transformation name\n */\n name: z.string().optional().describe('Transformation name'),\n\n /**\n * Transformation type\n */\n type: ETLTransformationTypeSchema.describe('Transformation type'),\n\n /**\n * Transformation-specific configuration\n * \n * @example For map: { oldField: 'newField' }\n * @example For filter: { condition: 'status == \"active\"' }\n * @example For script: { language: 'javascript', code: '...' }\n */\n config: z.record(z.string(), z.unknown()).describe('Transformation config'),\n\n /**\n * Whether to continue on error\n */\n continueOnError: z.boolean().default(false).describe('Continue on error'),\n});\n\nexport type ETLTransformation = z.infer;\n\n/**\n * ETL Sync Mode\n */\nexport const ETLSyncModeSchema = z.enum([\n 'full', // Full refresh - extract all data every time\n 'incremental', // Only extract changed data\n 'cdc', // Change Data Capture - real-time streaming\n]);\n\nexport type ETLSyncMode = z.infer;\n\n/**\n * ETL Pipeline Schema\n * \n * Complete definition of a data pipeline from source to destination with transformations.\n */\nexport const ETLPipelineSchema = z.object({\n /**\n * Pipeline identifier (snake_case)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Pipeline identifier (snake_case)'),\n\n /**\n * Human-readable pipeline name\n */\n label: z.string().optional().describe('Pipeline display name'),\n\n /**\n * Pipeline description\n */\n description: z.string().optional().describe('Pipeline description'),\n\n /**\n * Data source configuration\n */\n source: ETLSourceSchema.describe('Data source'),\n\n /**\n * Data destination configuration\n */\n destination: ETLDestinationSchema.describe('Data destination'),\n\n /**\n * Transformation steps\n * Applied in order from source to destination\n */\n transformations: z.array(ETLTransformationSchema)\n .optional()\n .describe('Transformation pipeline'),\n\n /**\n * Sync mode\n */\n syncMode: ETLSyncModeSchema.default('full').describe('Sync mode'),\n\n /**\n * Execution schedule (cron expression)\n * \n * @example \"0 2 * * *\" - Daily at 2 AM\n * @example \"0 *\\/4 * * *\" - Every 4 hours\n * @example \"0 0 * * 0\" - Weekly on Sunday\n */\n schedule: z.string().optional().describe('Cron schedule expression'),\n\n /**\n * Whether pipeline is enabled\n */\n enabled: z.boolean().default(true).describe('Pipeline enabled status'),\n\n /**\n * Retry configuration for failed runs\n */\n retry: z.object({\n maxAttempts: z.number().int().min(0).default(3).describe('Max retry attempts'),\n backoffMs: z.number().int().min(0).default(60000).describe('Backoff in milliseconds'),\n }).optional().describe('Retry configuration'),\n\n /**\n * Notification configuration\n */\n notifications: z.object({\n onSuccess: z.array(z.string()).optional().describe('Email addresses for success notifications'),\n onFailure: z.array(z.string()).optional().describe('Email addresses for failure notifications'),\n }).optional().describe('Notification settings'),\n\n /**\n * Pipeline tags for organization\n */\n tags: z.array(z.string()).optional().describe('Pipeline tags'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\nexport type ETLPipeline = z.infer;\n\n/**\n * ETL Run Status\n */\nexport const ETLRunStatusSchema = z.enum([\n 'pending', // Queued for execution\n 'running', // Currently executing\n 'succeeded', // Completed successfully\n 'failed', // Failed with errors\n 'cancelled', // Manually cancelled\n 'timeout', // Timed out\n]);\n\nexport type ETLRunStatus = z.infer;\n\n/**\n * ETL Pipeline Run Result\n * \n * Result of a pipeline execution\n */\nexport const ETLPipelineRunSchema = z.object({\n /**\n * Run ID\n */\n id: z.string().describe('Run identifier'),\n\n /**\n * Pipeline name\n */\n pipelineName: z.string().describe('Pipeline name'),\n\n /**\n * Run status\n */\n status: ETLRunStatusSchema.describe('Run status'),\n\n /**\n * Start timestamp\n */\n startedAt: z.string().datetime().describe('Start time'),\n\n /**\n * End timestamp\n */\n completedAt: z.string().datetime().optional().describe('Completion time'),\n\n /**\n * Duration in milliseconds\n */\n durationMs: z.number().optional().describe('Duration in ms'),\n\n /**\n * Statistics\n */\n stats: z.object({\n recordsRead: z.number().int().default(0).describe('Records extracted'),\n recordsWritten: z.number().int().default(0).describe('Records loaded'),\n recordsErrored: z.number().int().default(0).describe('Records with errors'),\n bytesProcessed: z.number().int().default(0).describe('Bytes processed'),\n }).optional().describe('Run statistics'),\n\n /**\n * Error information\n */\n error: z.object({\n message: z.string().describe('Error message'),\n code: z.string().optional().describe('Error code'),\n details: z.unknown().optional().describe('Error details'),\n }).optional().describe('Error information'),\n\n /**\n * Execution logs\n */\n logs: z.array(z.string()).optional().describe('Execution logs'),\n});\n\nexport type ETLPipelineRun = z.infer;\n\n/**\n * Helper factory for creating ETL pipelines\n */\nexport const ETL = {\n /**\n * Create a simple database-to-database pipeline\n */\n databaseSync: (params: {\n name: string;\n sourceTable: string;\n destTable: string;\n schedule?: string;\n }): ETLPipeline => ({\n name: params.name,\n source: {\n type: 'database',\n config: { table: params.sourceTable },\n },\n destination: {\n type: 'database',\n config: { table: params.destTable },\n writeMode: 'upsert',\n },\n syncMode: 'incremental',\n schedule: params.schedule,\n enabled: true,\n }),\n\n /**\n * Create an API to database pipeline\n */\n apiToDatabase: (params: {\n name: string;\n apiConnector: string;\n destTable: string;\n schedule?: string;\n }): ETLPipeline => ({\n name: params.name,\n source: {\n type: 'api',\n connector: params.apiConnector,\n config: {},\n },\n destination: {\n type: 'database',\n config: { table: params.destTable },\n writeMode: 'append',\n },\n syncMode: 'full',\n schedule: params.schedule,\n enabled: true,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Trigger Registry Protocol\n * \n * Lightweight automation triggers for simple integrations.\n * Inspired by Zapier, n8n, and Workato connector architectures.\n * \n * ## When to use Trigger Registry vs. Integration Connector?\n * \n * **Use `automation/trigger-registry.zod.ts` when:**\n * - Building simple automation triggers (e.g., \"when Slack message received, create task\")\n * - No complex authentication needed (simple API keys, basic auth)\n * - Lightweight, single-purpose integrations\n * - Quick setup with minimal configuration\n * - Webhook-based or polling triggers for automation workflows\n * \n * **Use `integration/connector.zod.ts` when:**\n * - Building enterprise-grade connectors (e.g., Salesforce, SAP, Oracle)\n * - Complex OAuth2/SAML authentication required\n * - Bidirectional sync with field mapping and transformations\n * - Webhook management and rate limiting required\n * - Full CRUD operations and data synchronization\n * \n * ## Use Cases\n * \n * 1. **Simple Automation Triggers**\n * - Slack notifications on record updates\n * - Twilio SMS on workflow events\n * - SendGrid email templates\n * \n * 2. **Lightweight Operations**\n * - Single-action integrations (send, notify, log)\n * - No bidirectional sync required\n * - Webhook receivers for incoming events\n * \n * 3. **Quick Integrations**\n * - Payment webhooks (Stripe, PayPal)\n * - Communication triggers (Twilio, SendGrid, Slack)\n * - Simple API calls to third-party services\n * \n * @see https://zapier.com/developer/documentation/v2/\n * @see https://docs.n8n.io/integrations/creating-nodes/\n * @see ../../integration/connector.zod.ts for enterprise connectors\n * \n * @example\n * ```typescript\n * const slackNotifier: Connector = {\n * id: 'slack_notify',\n * name: 'Slack Notification',\n * category: 'communication',\n * authentication: {\n * type: 'apiKey',\n * fields: [{ name: 'webhook_url', label: 'Webhook URL', type: 'url' }]\n * },\n * operations: [\n * { id: 'send_message', name: 'Send Message', type: 'action' }\n * ]\n * }\n * ```\n */\n\n/**\n * Connector Category\n */\nexport const ConnectorCategorySchema = z.enum([\n 'crm', // Customer Relationship Management\n 'payment', // Payment processors\n 'communication', // Email, SMS, Chat\n 'storage', // File storage\n 'analytics', // Analytics platforms\n 'database', // Databases\n 'marketing', // Marketing automation\n 'accounting', // Accounting software\n 'hr', // Human resources\n 'productivity', // Productivity tools\n 'ecommerce', // E-commerce platforms\n 'support', // Customer support\n 'devtools', // Developer tools\n 'social', // Social media\n 'other', // Other category\n]);\n\nexport type ConnectorCategory = z.infer;\n\n/**\n * Authentication Type\n */\nexport const AuthenticationTypeSchema = z.enum([\n 'none', // No authentication\n 'apiKey', // API key\n 'basic', // Basic auth (username/password)\n 'bearer', // Bearer token\n 'oauth1', // OAuth 1.0\n 'oauth2', // OAuth 2.0\n 'custom', // Custom authentication\n]);\n\nexport type AuthenticationType = z.infer;\n\n/**\n * Authentication Field Schema\n */\nexport const AuthFieldSchema = z.object({\n /**\n * Field name (machine name)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Field name (snake_case)'),\n\n /**\n * Field label\n */\n label: z.string().describe('Field label'),\n\n /**\n * Field type\n */\n type: z.enum(['text', 'password', 'url', 'select'])\n .default('text')\n .describe('Field type'),\n\n /**\n * Field description\n */\n description: z.string().optional().describe('Field description'),\n\n /**\n * Whether field is required\n */\n required: z.boolean().default(true).describe('Required field'),\n\n /**\n * Default value\n */\n default: z.string().optional().describe('Default value'),\n\n /**\n * Options for select fields\n */\n options: z.array(z.object({\n label: z.string(),\n value: z.string(),\n })).optional().describe('Select field options'),\n\n /**\n * Placeholder text\n */\n placeholder: z.string().optional().describe('Placeholder text'),\n});\n\nexport type AuthField = z.infer;\n\n/**\n * OAuth 2.0 Configuration\n */\nexport const OAuth2ConfigSchema = z.object({\n /**\n * Authorization URL\n */\n authorizationUrl: z.string().url().describe('Authorization endpoint URL'),\n\n /**\n * Token URL\n */\n tokenUrl: z.string().url().describe('Token endpoint URL'),\n\n /**\n * Scopes to request\n */\n scopes: z.array(z.string()).optional().describe('OAuth scopes'),\n\n /**\n * Client ID field name\n */\n clientIdField: z.string().default('client_id').describe('Client ID field name'),\n\n /**\n * Client secret field name\n */\n clientSecretField: z.string().default('client_secret').describe('Client secret field name'),\n});\n\nexport type OAuth2Config = z.infer;\n\n/**\n * Authentication Configuration\n */\nexport const AuthenticationSchema = z.object({\n /**\n * Authentication type\n */\n type: AuthenticationTypeSchema.describe('Authentication type'),\n\n /**\n * Authentication fields\n * Configuration fields needed for this auth type\n */\n fields: z.array(AuthFieldSchema).optional().describe('Authentication fields'),\n\n /**\n * OAuth 2.0 configuration (when type is oauth2)\n */\n oauth2: OAuth2ConfigSchema.optional().describe('OAuth 2.0 configuration'),\n\n /**\n * Test authentication instructions\n */\n test: z.object({\n url: z.string().optional().describe('Test endpoint URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).default('GET').describe('HTTP method'),\n }).optional().describe('Authentication test configuration'),\n});\n\nexport type Authentication = z.infer;\n\n/**\n * Connector Operation Type\n */\nexport const OperationTypeSchema = z.enum([\n 'read', // Read/query data\n 'write', // Create/update data\n 'delete', // Delete data\n 'search', // Search operation\n 'trigger', // Webhook/polling trigger\n 'action', // Custom action\n]);\n\nexport type OperationType = z.infer;\n\n/**\n * Operation Parameter Schema\n */\nexport const OperationParameterSchema = z.object({\n /**\n * Parameter name\n */\n name: z.string().describe('Parameter name'),\n\n /**\n * Parameter label\n */\n label: z.string().describe('Parameter label'),\n\n /**\n * Parameter description\n */\n description: z.string().optional().describe('Parameter description'),\n\n /**\n * Parameter type\n */\n type: z.enum(['string', 'number', 'boolean', 'array', 'object', 'date', 'file'])\n .describe('Parameter type'),\n\n /**\n * Whether parameter is required\n */\n required: z.boolean().default(false).describe('Required parameter'),\n\n /**\n * Default value\n */\n default: z.unknown().optional().describe('Default value'),\n\n /**\n * Validation schema\n */\n validation: z.record(z.string(), z.unknown()).optional().describe('Validation rules'),\n\n /**\n * Dynamic options function\n */\n dynamicOptions: z.string().optional().describe('Function to load dynamic options'),\n});\n\nexport type OperationParameter = z.infer;\n\n/**\n * Connector Operation Schema\n */\nexport const ConnectorOperationSchema = z.object({\n /**\n * Operation identifier\n */\n id: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Operation ID (snake_case)'),\n\n /**\n * Operation name\n */\n name: z.string().describe('Operation name'),\n\n /**\n * Operation description\n */\n description: z.string().optional().describe('Operation description'),\n\n /**\n * Operation type\n */\n type: OperationTypeSchema.describe('Operation type'),\n\n /**\n * Input parameters\n */\n inputSchema: z.array(OperationParameterSchema)\n .optional()\n .describe('Input parameters'),\n\n /**\n * Output schema\n */\n outputSchema: z.record(z.string(), z.unknown())\n .optional()\n .describe('Output schema'),\n\n /**\n * Sample output for documentation\n */\n sampleOutput: z.unknown().optional().describe('Sample output'),\n\n /**\n * Whether operation supports pagination\n */\n supportsPagination: z.boolean().default(false).describe('Supports pagination'),\n\n /**\n * Whether operation supports filtering\n */\n supportsFiltering: z.boolean().default(false).describe('Supports filtering'),\n});\n\nexport type ConnectorOperation = z.infer;\n\n/**\n * Connector Trigger Schema\n * \n * Triggers are special operations that watch for events and initiate workflows.\n */\nexport const ConnectorTriggerSchema = z.object({\n /**\n * Trigger identifier\n */\n id: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Trigger ID (snake_case)'),\n\n /**\n * Trigger name\n */\n name: z.string().describe('Trigger name'),\n\n /**\n * Trigger description\n */\n description: z.string().optional().describe('Trigger description'),\n\n /**\n * Trigger type\n */\n type: z.enum(['webhook', 'polling', 'stream'])\n .describe('Trigger mechanism'),\n\n /**\n * Trigger configuration\n */\n config: z.record(z.string(), z.unknown())\n .optional()\n .describe('Trigger configuration'),\n\n /**\n * Output schema\n */\n outputSchema: z.record(z.string(), z.unknown())\n .optional()\n .describe('Event payload schema'),\n\n /**\n * Polling interval (for polling triggers)\n * In milliseconds\n */\n pollingIntervalMs: z.number().int().min(1000)\n .optional()\n .describe('Polling interval in ms'),\n});\n\nexport type ConnectorTrigger = z.infer;\n\n/**\n * Connector Schema\n * \n * Complete definition of a connector to an external system.\n */\nexport const ConnectorSchema = z.object({\n /**\n * Connector identifier\n * Must be globally unique\n */\n id: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Connector ID (snake_case)'),\n\n /**\n * Connector name\n */\n name: z.string().describe('Connector name'),\n\n /**\n * Connector description\n */\n description: z.string().optional().describe('Connector description'),\n\n /**\n * Connector version (semver)\n */\n version: z.string().optional().describe('Connector version'),\n\n /**\n * Connector icon URL or name\n */\n icon: z.string().optional().describe('Connector icon'),\n\n /**\n * Connector category\n */\n category: ConnectorCategorySchema.describe('Connector category'),\n\n /**\n * Base URL for API calls\n */\n baseUrl: z.string().url().optional().describe('API base URL'),\n\n /**\n * Authentication configuration\n */\n authentication: AuthenticationSchema.describe('Authentication config'),\n\n /**\n * Available operations\n */\n operations: z.array(ConnectorOperationSchema)\n .optional()\n .describe('Connector operations'),\n\n /**\n * Available triggers\n */\n triggers: z.array(ConnectorTriggerSchema)\n .optional()\n .describe('Connector triggers'),\n\n /**\n * Rate limiting information\n */\n rateLimit: z.object({\n requestsPerSecond: z.number().optional().describe('Max requests per second'),\n requestsPerMinute: z.number().optional().describe('Max requests per minute'),\n requestsPerHour: z.number().optional().describe('Max requests per hour'),\n }).optional().describe('Rate limiting'),\n\n /**\n * Connector author\n */\n author: z.string().optional().describe('Connector author'),\n\n /**\n * Documentation URL\n */\n documentation: z.string().url().optional().describe('Documentation URL'),\n\n /**\n * Homepage URL\n */\n homepage: z.string().url().optional().describe('Homepage URL'),\n\n /**\n * License\n */\n license: z.string().optional().describe('License (SPDX identifier)'),\n\n /**\n * Tags for discovery\n */\n tags: z.array(z.string()).optional().describe('Connector tags'),\n\n /**\n * Whether connector is verified/certified\n */\n verified: z.boolean().default(false).describe('Verified connector'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\nexport type Connector = z.infer;\n\n/**\n * Connector Instance Schema\n * \n * A configured instance of a connector with credentials.\n */\nexport const ConnectorInstanceSchema = z.object({\n /**\n * Instance ID\n */\n id: z.string().describe('Instance ID'),\n\n /**\n * Connector ID this instance uses\n */\n connectorId: z.string().describe('Connector ID'),\n\n /**\n * Instance name\n */\n name: z.string().describe('Instance name'),\n\n /**\n * Instance description\n */\n description: z.string().optional().describe('Instance description'),\n\n /**\n * Authentication credentials (encrypted)\n */\n credentials: z.record(z.string(), z.unknown()).describe('Encrypted credentials'),\n\n /**\n * Additional configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Additional config'),\n\n /**\n * Whether instance is active\n */\n active: z.boolean().default(true).describe('Instance active status'),\n\n /**\n * Created timestamp\n */\n createdAt: z.string().datetime().optional().describe('Creation time'),\n\n /**\n * Last tested timestamp\n */\n lastTestedAt: z.string().datetime().optional().describe('Last test time'),\n\n /**\n * Test status\n */\n testStatus: z.enum(['unknown', 'success', 'failed'])\n .default('unknown')\n .describe('Connection test status'),\n});\n\nexport type ConnectorInstance = z.infer;\n\n/**\n * Helper factory for creating connectors\n */\nexport const Connector = {\n /**\n * Create a basic API key connector\n */\n apiKey: (params: {\n id: string;\n name: string;\n category: ConnectorCategory;\n baseUrl: string;\n }): Connector => ({\n id: params.id,\n name: params.name,\n category: params.category,\n baseUrl: params.baseUrl,\n authentication: {\n type: 'apiKey',\n fields: [\n {\n name: 'api_key',\n label: 'API Key',\n type: 'password',\n required: true,\n },\n ],\n },\n verified: false,\n }),\n\n /**\n * Create an OAuth 2.0 connector\n */\n oauth2: (params: {\n id: string;\n name: string;\n category: ConnectorCategory;\n baseUrl: string;\n authUrl: string;\n tokenUrl: string;\n scopes?: string[];\n }): Connector => ({\n id: params.id,\n name: params.name,\n category: params.category,\n baseUrl: params.baseUrl,\n authentication: {\n type: 'oauth2',\n oauth2: {\n authorizationUrl: params.authUrl,\n tokenUrl: params.tokenUrl,\n clientIdField: 'client_id',\n clientSecretField: 'client_secret',\n scopes: params.scopes,\n },\n },\n verified: false,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldMappingSchema } from '../shared/mapping.zod';\n\n/**\n * Data Sync Protocol - LEVEL 1: Simple Synchronization\n * \n * Inspired by Salesforce Connect, Segment Sync, and Census Reverse ETL.\n * \n * **Positioning in 3-Layer Architecture:**\n * - **L1: Simple Sync** (THIS FILE) - Business users - Sync Salesforce to Sheets\n * - **L2: ETL Pipeline** (automation/etl.zod.ts) - Data engineers - Aggregate 10 sources to warehouse\n * - **L3: Enterprise Connector** (integration/connector.zod.ts) - System integrators - Full SAP integration\n * \n * Data sync provides bidirectional or unidirectional data synchronization\n * between ObjectStack and external systems, maintaining data consistency\n * across platforms.\n * \n * **SCOPE: Simple field mappings only. NO complex transformations.**\n * For complex transformations (joins, aggregates, custom SQL), use ETL Pipeline (Level 2).\n * \n * ## When to Use This Layer\n * \n * **Use Simple Sync when:**\n * - Syncing 1:1 fields between two systems\n * - Simple field transformations (uppercase, cast, etc.)\n * - No complex logic required\n * - Business users need to configure integrations\n * \n * **Examples:**\n * - Salesforce Contact ↔ Google Sheets\n * - HubSpot Company ↔ CRM Account\n * - Shopify Orders → Accounting System\n * \n * **When to upgrade:**\n * - Need multi-source joins → Use {@link file://./etl.zod.ts | ETL Pipeline}\n * - Need complex authentication/webhooks → Use {@link file://../integration/connector.zod.ts | Enterprise Connector}\n * - Need aggregations or data warehousing → Use {@link file://./etl.zod.ts | ETL Pipeline}\n * \n * @see {@link file://./etl.zod.ts} for Level 2 (data engineering)\n * @see {@link file://../integration/connector.zod.ts} for Level 3 (enterprise integration)\n * \n * ## Use Cases\n * \n * 1. **CRM Integration**\n * - Sync contacts between ObjectStack and Salesforce\n * - Keep opportunity data synchronized\n * - Bidirectional updates\n * \n * 2. **Customer Data Platform (CDP)**\n * - Sync user profiles to Segment\n * - Enrichment data from Clearbit\n * - Marketing automation sync\n * \n * 3. **Operational Analytics**\n * - Sync production data to analytics warehouse\n * - Real-time dashboards\n * - Business intelligence\n * \n * @see https://help.salesforce.com/s/articleView?id=sf.platform_connect_about.htm\n * @see https://segment.com/docs/connections/sync/\n * @see https://www.getcensus.com/\n * \n * @example\n * ```typescript\n * const contactSync: DataSyncConfig = {\n * name: 'salesforce_contact_sync',\n * label: 'Salesforce Contact Sync',\n * source: {\n * object: 'contact',\n * filters: { status: 'active' }\n * },\n * destination: {\n * connector: 'salesforce',\n * operation: 'upsert_contact',\n * mapping: {\n * first_name: 'FirstName',\n * last_name: 'LastName',\n * email: 'Email'\n * }\n * },\n * syncMode: 'incremental',\n * schedule: '0 * * * *' // Hourly\n * }\n * ```\n */\n\n/**\n * Sync Direction\n */\nexport const SyncDirectionSchema = z.enum([\n 'push', // ObjectStack -> External (one-way)\n 'pull', // External -> ObjectStack (one-way)\n 'bidirectional', // Both directions\n]);\n\nexport type SyncDirection = z.infer;\n\n/**\n * Sync Mode\n */\nexport const SyncModeSchema = z.enum([\n 'full', // Full refresh every time\n 'incremental', // Only sync changed records\n 'realtime', // Real-time streaming sync\n]);\n\nexport type SyncMode = z.infer;\n\n/**\n * Conflict Resolution Strategy\n */\nexport const ConflictResolutionSchema = z.enum([\n 'source_wins', // Source system always wins\n 'destination_wins', // Destination system always wins\n 'latest_wins', // Most recently modified wins\n 'manual', // Flag for manual resolution\n 'merge', // Smart merge (custom logic)\n]);\n\nexport type ConflictResolution = z.infer;\n\n/**\n * Field Mapping for Data Sync\n * \n * Uses the canonical field mapping protocol from shared/mapping.zod.ts\n * for simple 1:1 field transformations.\n * \n * @see {@link FieldMappingSchema} for the base field mapping schema\n */\n\n/**\n * Data Source Configuration\n */\nexport const DataSourceConfigSchema = z.object({\n /**\n * Source object name\n * For ObjectStack objects\n */\n object: z.string().optional().describe('ObjectStack object name'),\n\n /**\n * Filter conditions\n * Only sync records matching these filters\n */\n filters: z.unknown().optional().describe('Filter conditions'),\n\n /**\n * Fields to include\n * If not specified, all fields are synced\n */\n fields: z.array(z.string()).optional().describe('Fields to sync'),\n\n /**\n * External connector instance ID\n * For external data sources\n */\n connectorInstanceId: z.string().optional().describe('Connector instance ID'),\n\n /**\n * External resource identifier\n * e.g., Salesforce object name, database table, API endpoint\n */\n externalResource: z.string().optional().describe('External resource ID'),\n});\n\nexport type DataSourceConfig = z.infer;\n\n/**\n * Data Destination Configuration\n */\nexport const DataDestinationConfigSchema = z.object({\n /**\n * Destination object name\n * For ObjectStack objects\n */\n object: z.string().optional().describe('ObjectStack object name'),\n\n /**\n * Connector instance ID\n * For external destinations\n */\n connectorInstanceId: z.string().optional().describe('Connector instance ID'),\n\n /**\n * Operation to perform\n */\n operation: z.enum([\n 'insert', // Create new records only\n 'update', // Update existing records only\n 'upsert', // Insert or update based on key\n 'delete', // Delete records\n 'sync', // Full synchronization\n ]).describe('Sync operation'),\n\n /**\n * Field mappings\n * Maps source fields to destination fields\n */\n mapping: z.union([\n z.record(z.string(), z.string()), // Simple mapping: { sourceField: 'destField' }\n z.array(FieldMappingSchema), // Advanced mapping with transformations\n ]).optional().describe('Field mappings'),\n\n /**\n * External resource identifier\n */\n externalResource: z.string().optional().describe('External resource ID'),\n\n /**\n * Match key for upsert operations\n * Fields to use for matching existing records\n */\n matchKey: z.array(z.string()).optional().describe('Match key fields'),\n});\n\nexport type DataDestinationConfig = z.infer;\n\n/**\n * Data Sync Configuration Schema\n * \n * Complete definition of a data synchronization between systems.\n */\nexport const DataSyncConfigSchema = z.object({\n /**\n * Sync configuration name (snake_case)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Sync configuration name (snake_case)'),\n\n /**\n * Human-readable label\n */\n label: z.string().optional().describe('Sync display name'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('Sync description'),\n\n /**\n * Source configuration\n */\n source: DataSourceConfigSchema.describe('Data source'),\n\n /**\n * Destination configuration\n */\n destination: DataDestinationConfigSchema.describe('Data destination'),\n\n /**\n * Sync direction\n */\n direction: SyncDirectionSchema.default('push').describe('Sync direction'),\n\n /**\n * Sync mode\n */\n syncMode: SyncModeSchema.default('incremental').describe('Sync mode'),\n\n /**\n * Conflict resolution strategy\n */\n conflictResolution: ConflictResolutionSchema\n .default('latest_wins')\n .describe('Conflict resolution'),\n\n /**\n * Execution schedule (cron expression)\n * For scheduled syncs\n * \n * @example \"0 * * * *\" - Hourly\n * @example \"*\\/15 * * * *\" - Every 15 minutes\n */\n schedule: z.string().optional().describe('Cron schedule'),\n\n /**\n * Whether sync is enabled\n */\n enabled: z.boolean().default(true).describe('Sync enabled'),\n\n /**\n * Change tracking field\n * Field to track when records were last modified\n * Used for incremental sync\n * \n * @example \"updated_at\", \"modified_date\"\n */\n changeTrackingField: z.string()\n .optional()\n .describe('Field for change tracking'),\n\n /**\n * Batch size\n * Number of records to process per batch\n */\n batchSize: z.number().int().min(1).max(10000)\n .default(100)\n .describe('Batch size for processing'),\n\n /**\n * Retry configuration\n */\n retry: z.object({\n maxAttempts: z.number().int().min(0).default(3).describe('Max retries'),\n backoffMs: z.number().int().min(0).default(30000).describe('Backoff duration'),\n }).optional().describe('Retry configuration'),\n\n /**\n * Pre-sync validation rules\n */\n validation: z.object({\n required: z.array(z.string()).optional().describe('Required fields'),\n unique: z.array(z.string()).optional().describe('Unique constraint fields'),\n custom: z.array(z.object({\n name: z.string(),\n condition: z.string().describe('Validation condition'),\n message: z.string().describe('Error message'),\n })).optional().describe('Custom validation rules'),\n }).optional().describe('Validation rules'),\n\n /**\n * Error handling configuration\n */\n errorHandling: z.object({\n onValidationError: z.enum(['skip', 'fail', 'log']).default('skip'),\n onSyncError: z.enum(['skip', 'fail', 'retry']).default('retry'),\n notifyOnError: z.array(z.string()).optional().describe('Email notifications'),\n }).optional().describe('Error handling'),\n\n /**\n * Performance optimization\n */\n optimization: z.object({\n parallelBatches: z.boolean().default(false).describe('Process batches in parallel'),\n cacheEnabled: z.boolean().default(true).describe('Enable caching'),\n compressionEnabled: z.boolean().default(false).describe('Enable compression'),\n }).optional().describe('Performance optimization'),\n\n /**\n * Audit and logging\n */\n audit: z.object({\n logLevel: z.enum(['none', 'error', 'warn', 'info', 'debug']).default('info'),\n retainLogsForDays: z.number().int().min(1).default(30),\n trackChanges: z.boolean().default(true).describe('Track all changes'),\n }).optional().describe('Audit configuration'),\n\n /**\n * Tags for organization\n */\n tags: z.array(z.string()).optional().describe('Sync tags'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\nexport type DataSyncConfig = z.infer;\n\n/**\n * Sync Execution Status\n */\nexport const SyncExecutionStatusSchema = z.enum([\n 'pending', // Queued\n 'running', // Currently executing\n 'completed', // Successfully completed\n 'partial', // Completed with some errors\n 'failed', // Failed\n 'cancelled', // Manually cancelled\n]);\n\nexport type SyncExecutionStatus = z.infer;\n\n/**\n * Sync Execution Result Schema\n * \n * Result of a sync execution.\n */\nexport const SyncExecutionResultSchema = z.object({\n /**\n * Execution ID\n */\n id: z.string().describe('Execution ID'),\n\n /**\n * Sync configuration name\n */\n syncName: z.string().describe('Sync name'),\n\n /**\n * Execution status\n */\n status: SyncExecutionStatusSchema.describe('Execution status'),\n\n /**\n * Start timestamp\n */\n startedAt: z.string().datetime().describe('Start time'),\n\n /**\n * End timestamp\n */\n completedAt: z.string().datetime().optional().describe('Completion time'),\n\n /**\n * Duration in milliseconds\n */\n durationMs: z.number().optional().describe('Duration in ms'),\n\n /**\n * Statistics\n */\n stats: z.object({\n recordsProcessed: z.number().int().default(0).describe('Total records processed'),\n recordsInserted: z.number().int().default(0).describe('Records inserted'),\n recordsUpdated: z.number().int().default(0).describe('Records updated'),\n recordsDeleted: z.number().int().default(0).describe('Records deleted'),\n recordsSkipped: z.number().int().default(0).describe('Records skipped'),\n recordsErrored: z.number().int().default(0).describe('Records with errors'),\n conflictsDetected: z.number().int().default(0).describe('Conflicts detected'),\n conflictsResolved: z.number().int().default(0).describe('Conflicts resolved'),\n }).optional().describe('Execution statistics'),\n\n /**\n * Errors encountered\n */\n errors: z.array(z.object({\n recordId: z.string().optional().describe('Record ID'),\n field: z.string().optional().describe('Field name'),\n message: z.string().describe('Error message'),\n code: z.string().optional().describe('Error code'),\n })).optional().describe('Errors'),\n\n /**\n * Execution logs\n */\n logs: z.array(z.string()).optional().describe('Execution logs'),\n});\n\nexport type SyncExecutionResult = z.infer;\n\n/**\n * Helper factory for creating sync configurations\n */\nexport const Sync = {\n /**\n * Create a simple object-to-object sync\n */\n objectSync: (params: {\n name: string;\n sourceObject: string;\n destObject: string;\n mapping: Record;\n schedule?: string;\n }): DataSyncConfig => ({\n name: params.name,\n source: {\n object: params.sourceObject,\n },\n destination: {\n object: params.destObject,\n operation: 'upsert',\n mapping: params.mapping,\n },\n direction: 'push',\n syncMode: 'incremental',\n conflictResolution: 'latest_wins',\n batchSize: 100,\n schedule: params.schedule,\n enabled: true,\n }),\n\n /**\n * Create a connector sync\n */\n connectorSync: (params: {\n name: string;\n sourceObject: string;\n connectorInstanceId: string;\n externalResource: string;\n mapping: Record;\n schedule?: string;\n }): DataSyncConfig => ({\n name: params.name,\n source: {\n object: params.sourceObject,\n },\n destination: {\n connectorInstanceId: params.connectorInstanceId,\n externalResource: params.externalResource,\n operation: 'upsert',\n mapping: params.mapping,\n },\n direction: 'push',\n syncMode: 'incremental',\n conflictResolution: 'latest_wins',\n batchSize: 100,\n schedule: params.schedule,\n enabled: true,\n }),\n\n /**\n * Create a bidirectional sync\n */\n bidirectionalSync: (params: {\n name: string;\n object: string;\n connectorInstanceId: string;\n externalResource: string;\n mapping: Record;\n schedule?: string;\n }): DataSyncConfig => ({\n name: params.name,\n source: {\n object: params.object,\n },\n destination: {\n connectorInstanceId: params.connectorInstanceId,\n externalResource: params.externalResource,\n operation: 'sync',\n mapping: params.mapping,\n },\n direction: 'bidirectional',\n syncMode: 'incremental',\n conflictResolution: 'latest_wins',\n batchSize: 100,\n schedule: params.schedule,\n enabled: true,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module automation/node-executor\n *\n * Node Executor Plugin Protocol — Wait Node Pause/Resume\n *\n * Defines the specification for node executor plugins, with a focus on\n * the `wait` node executor that supports flow pause and external-event\n * resume (signal, manual, webhook, condition).\n *\n * The protocol covers:\n * - **WaitResumePayload**: The payload delivered when a paused flow is resumed\n * - **WaitExecutorConfig**: Configuration for the wait executor plugin\n * - **NodeExecutorDescriptor**: Generic node executor plugin descriptor\n */\n\nimport { z } from 'zod';\n\n// ─── Wait Event Types ────────────────────────────────────────────────\n\n/**\n * Wait event type — determines how a wait node is resumed.\n * Mirrors the `waitEventConfig.eventType` in flow.zod.ts.\n */\nexport const WaitEventTypeSchema = z.enum([\n 'timer', // Resume after duration/datetime\n 'signal', // Resume on named signal dispatch\n 'webhook', // Resume on incoming webhook call\n 'manual', // Resume by manual operator action\n 'condition', // Resume when a data condition is met (polling)\n]).describe('Wait event type determining how a paused flow is resumed');\n\nexport type WaitEventType = z.infer;\n\n// ─── Wait Resume Payload ─────────────────────────────────────────────\n\n/**\n * Payload delivered when a paused wait node is resumed by an external event.\n * The runtime engine passes this to the flow executor to continue execution.\n */\nexport const WaitResumePayloadSchema = z.object({\n /** The execution id of the paused flow */\n executionId: z.string().describe('Execution ID of the paused flow'),\n\n /** The checkpoint id being resumed */\n checkpointId: z.string().describe('Checkpoint ID to resume from'),\n\n /** The node id of the wait node being resumed */\n nodeId: z.string().describe('Wait node ID being resumed'),\n\n /** The event type that triggered the resume */\n eventType: WaitEventTypeSchema.describe('Event type that triggered resume'),\n\n /** Signal name (for signal events) */\n signalName: z.string().optional().describe('Signal name (when eventType is signal)'),\n\n /** Webhook payload data (for webhook events) */\n webhookPayload: z.record(z.string(), z.unknown()).optional()\n .describe('Webhook request payload (when eventType is webhook)'),\n\n /** Who/what triggered the resume */\n resumedBy: z.string().optional().describe('User ID or system identifier that triggered resume'),\n\n /** Timestamp of the resume event */\n resumedAt: z.string().datetime().describe('ISO 8601 timestamp of the resume event'),\n\n /** Additional variables to merge into flow context on resume */\n variables: z.record(z.string(), z.unknown()).optional()\n .describe('Variables to merge into flow context upon resume'),\n}).describe('Payload for resuming a paused wait node');\n\nexport type WaitResumePayload = z.infer;\n\n// ─── Wait Executor Config ────────────────────────────────────────────\n\n/**\n * Timeout behavior when a wait node exceeds its timeout.\n */\nexport const WaitTimeoutBehaviorSchema = z.enum([\n 'fail', // Mark execution as failed\n 'continue', // Continue to next node (skip wait)\n 'fallback', // Execute a fallback edge\n]).describe('Behavior when a wait node exceeds its timeout');\n\nexport type WaitTimeoutBehavior = z.infer;\n\n/**\n * Configuration for the wait node executor plugin.\n * Controls polling intervals, webhook endpoint patterns, and timeout behavior.\n */\nexport const WaitExecutorConfigSchema = z.object({\n /** Default timeout for wait nodes without explicit timeout (ms) */\n defaultTimeoutMs: z.number().int().min(0).default(86400000)\n .describe('Default timeout in ms (default: 24 hours)'),\n\n /** Default timeout behavior */\n defaultTimeoutBehavior: WaitTimeoutBehaviorSchema.default('fail')\n .describe('Default behavior when wait timeout is exceeded'),\n\n /** Polling interval for condition-based waits (ms) */\n conditionPollIntervalMs: z.number().int().min(1000).default(30000)\n .describe('Polling interval for condition waits in ms (default: 30s)'),\n\n /** Maximum polling attempts for condition waits (0 = unlimited until timeout) */\n conditionMaxPolls: z.number().int().min(0).default(0)\n .describe('Max polling attempts for condition waits (0 = unlimited)'),\n\n /** Webhook endpoint URL pattern (runtime fills in execution/node ids) */\n webhookUrlPattern: z.string().default('/api/v1/automation/resume/{executionId}/{nodeId}')\n .describe('URL pattern for webhook resume endpoints'),\n\n /** Whether to persist checkpoints to durable storage */\n persistCheckpoints: z.boolean().default(true)\n .describe('Persist wait checkpoints to durable storage'),\n\n /** Maximum concurrent paused executions (0 = unlimited) */\n maxPausedExecutions: z.number().int().min(0).default(0)\n .describe('Max concurrent paused executions (0 = unlimited)'),\n}).describe('Wait node executor plugin configuration');\n\nexport type WaitExecutorConfig = z.infer;\n\n// ─── Node Executor Descriptor ────────────────────────────────────────\n\n/**\n * Generic node executor plugin descriptor.\n * Each node type (wait, script, http_request, etc.) can register\n * a custom executor via this descriptor.\n */\nexport const NodeExecutorDescriptorSchema = z.object({\n /** Unique executor identifier */\n id: z.string().describe('Unique executor plugin identifier'),\n\n /** Human-readable name */\n name: z.string().describe('Display name'),\n\n /** The FlowNodeAction types this executor handles */\n nodeTypes: z.array(z.string()).min(1)\n .describe('FlowNodeAction types this executor handles'),\n\n /** Executor plugin version (semver) */\n version: z.string().describe('Plugin version (semver)'),\n\n /** Description of the executor */\n description: z.string().optional().describe('Executor description'),\n\n /** Whether this executor supports async pause/resume */\n supportsPause: z.boolean().default(false)\n .describe('Whether the executor supports async pause/resume'),\n\n /** Whether this executor supports cancellation mid-execution */\n supportsCancellation: z.boolean().default(false)\n .describe('Whether the executor supports mid-execution cancellation'),\n\n /** Whether this executor supports retry on failure */\n supportsRetry: z.boolean().default(true)\n .describe('Whether the executor supports retry on failure'),\n\n /** Executor-specific configuration schema (JSON Schema reference) */\n configSchemaRef: z.string().optional()\n .describe('JSON Schema $ref for executor-specific config'),\n}).describe('Node executor plugin descriptor');\n\nexport type NodeExecutorDescriptor = z.infer;\n\n// ─── Built-in Wait Executor Descriptor ───────────────────────────────\n\n/**\n * Built-in descriptor for the wait node executor.\n * Runtime implementations should register this or a compatible executor.\n */\nexport const WAIT_EXECUTOR_DESCRIPTOR: NodeExecutorDescriptor = {\n id: 'objectstack:wait-executor',\n name: 'Wait Node Executor',\n nodeTypes: ['wait'],\n version: '1.0.0',\n description: 'Pauses flow execution and resumes on timer, signal, webhook, manual action, or condition events.',\n supportsPause: true,\n supportsCancellation: true,\n supportsRetry: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module automation/bpmn-interop\n *\n * BPMN XML Interoperability Protocol\n *\n * Defines the specification for importing and exporting BPMN 2.0 XML\n * process definitions. This enables interoperability with external BPM\n * tools (Camunda, Activiti, jBPM, etc.) via a plugin-based approach.\n *\n * **Priority:** Low — long-term planning, not a core requirement.\n */\n\nimport { z } from 'zod';\n\n// ─── BPMN Element Mapping ────────────────────────────────────────────\n\n/**\n * Mapping between a BPMN XML element type and an ObjectStack FlowNodeAction.\n * Used during import/export to translate between the two models.\n */\nexport const BpmnElementMappingSchema = z.object({\n /** BPMN XML element type (e.g., \"bpmn:parallelGateway\", \"bpmn:serviceTask\") */\n bpmnType: z.string().describe('BPMN XML element type (e.g., \"bpmn:parallelGateway\")'),\n\n /** Corresponding ObjectStack FlowNodeAction */\n flowNodeAction: z.string().describe('ObjectStack FlowNodeAction value'),\n\n /** Whether this mapping is bidirectional (supports both import and export) */\n bidirectional: z.boolean().default(true).describe('Whether the mapping supports both import and export'),\n\n /** Notes about mapping limitations or special handling */\n notes: z.string().optional().describe('Notes about mapping limitations'),\n}).describe('Mapping between BPMN XML element and ObjectStack FlowNodeAction');\n\nexport type BpmnElementMapping = z.infer;\n\n// ─── BPMN Import Options ─────────────────────────────────────────────\n\n/**\n * Strategy for handling BPMN elements that have no direct ObjectStack mapping.\n */\nexport const BpmnUnmappedStrategySchema = z.enum([\n 'skip', // Skip unmapped elements silently\n 'warn', // Import with warnings\n 'error', // Fail on unmapped elements\n 'comment', // Import as annotation/comment nodes\n]).describe('Strategy for unmapped BPMN elements during import');\n\nexport type BpmnUnmappedStrategy = z.infer;\n\n/**\n * Options for importing a BPMN 2.0 XML process definition into an ObjectStack flow.\n */\nexport const BpmnImportOptionsSchema = z.object({\n /** Strategy for unmapped BPMN elements */\n unmappedStrategy: BpmnUnmappedStrategySchema.default('warn')\n .describe('How to handle unmapped BPMN elements'),\n\n /** Custom element mappings (override or extend built-in mappings) */\n customMappings: z.array(BpmnElementMappingSchema).optional()\n .describe('Custom element mappings to override or extend defaults'),\n\n /** Whether to import BPMN DI (diagram interchange) layout positions */\n importLayout: z.boolean().default(true)\n .describe('Import BPMN DI layout positions into canvas node coordinates'),\n\n /** Whether to import BPMN documentation as node descriptions */\n importDocumentation: z.boolean().default(true)\n .describe('Import BPMN documentation elements as node descriptions'),\n\n /** Target flow name (if not derived from BPMN process name) */\n flowName: z.string().optional()\n .describe('Override flow name (defaults to BPMN process name)'),\n\n /** Whether to validate the imported flow against ObjectStack schema */\n validateAfterImport: z.boolean().default(true)\n .describe('Validate imported flow against FlowSchema after import'),\n}).describe('Options for importing BPMN 2.0 XML into an ObjectStack flow');\n\nexport type BpmnImportOptions = z.infer;\n\n// ─── BPMN Export Options ─────────────────────────────────────────────\n\n/**\n * BPMN XML target version for export.\n */\nexport const BpmnVersionSchema = z.enum([\n '2.0', // BPMN 2.0 (most common, default)\n '2.0.2', // BPMN 2.0.2 (latest revision)\n]).describe('BPMN specification version for export');\n\nexport type BpmnVersion = z.infer;\n\n/**\n * Options for exporting an ObjectStack flow as BPMN 2.0 XML.\n */\nexport const BpmnExportOptionsSchema = z.object({\n /** Target BPMN version */\n version: BpmnVersionSchema.default('2.0')\n .describe('Target BPMN specification version'),\n\n /** Whether to include BPMN DI (diagram interchange) layout data */\n includeLayout: z.boolean().default(true)\n .describe('Include BPMN DI layout data from canvas positions'),\n\n /** Whether to include ObjectStack-specific extensions as BPMN extension elements */\n includeExtensions: z.boolean().default(false)\n .describe('Include ObjectStack extensions in BPMN extensionElements'),\n\n /** Custom element mappings (override built-in for export) */\n customMappings: z.array(BpmnElementMappingSchema).optional()\n .describe('Custom element mappings for export'),\n\n /** Whether to pretty-print the XML output */\n prettyPrint: z.boolean().default(true)\n .describe('Pretty-print XML output with indentation'),\n\n /** XML namespace prefix for BPMN elements */\n namespacePrefix: z.string().default('bpmn')\n .describe('XML namespace prefix for BPMN elements'),\n}).describe('Options for exporting an ObjectStack flow as BPMN 2.0 XML');\n\nexport type BpmnExportOptions = z.infer;\n\n// ─── BPMN Import/Export Result ───────────────────────────────────────\n\n/**\n * Diagnostic message from BPMN import/export operations.\n */\nexport const BpmnDiagnosticSchema = z.object({\n /** Severity level */\n severity: z.enum(['info', 'warning', 'error']).describe('Diagnostic severity'),\n\n /** Human-readable message */\n message: z.string().describe('Diagnostic message'),\n\n /** BPMN element ID (if applicable) */\n bpmnElementId: z.string().optional().describe('BPMN element ID related to this diagnostic'),\n\n /** ObjectStack node ID (if applicable) */\n nodeId: z.string().optional().describe('ObjectStack node ID related to this diagnostic'),\n}).describe('Diagnostic message from BPMN import/export');\n\nexport type BpmnDiagnostic = z.infer;\n\n/**\n * Result of a BPMN import or export operation.\n */\nexport const BpmnInteropResultSchema = z.object({\n /** Whether the operation completed successfully */\n success: z.boolean().describe('Whether the operation completed successfully'),\n\n /** Diagnostic messages (warnings, errors, info) */\n diagnostics: z.array(BpmnDiagnosticSchema).default([])\n .describe('Diagnostic messages from the operation'),\n\n /** Number of elements successfully mapped */\n mappedCount: z.number().int().min(0).default(0)\n .describe('Number of elements successfully mapped'),\n\n /** Number of elements skipped or unmapped */\n unmappedCount: z.number().int().min(0).default(0)\n .describe('Number of elements that could not be mapped'),\n}).describe('Result of a BPMN import/export operation');\n\nexport type BpmnInteropResult = z.infer;\n\n// ─── Built-in Element Mappings ───────────────────────────────────────\n\n/**\n * Built-in element mappings between BPMN 2.0 XML types and ObjectStack FlowNodeAction.\n * Import/export plugins should use these as defaults, with user overrides applied on top.\n */\nexport const BUILT_IN_BPMN_MAPPINGS: BpmnElementMapping[] = [\n { bpmnType: 'bpmn:startEvent', flowNodeAction: 'start', bidirectional: true },\n { bpmnType: 'bpmn:endEvent', flowNodeAction: 'end', bidirectional: true },\n { bpmnType: 'bpmn:exclusiveGateway', flowNodeAction: 'decision', bidirectional: true },\n { bpmnType: 'bpmn:parallelGateway', flowNodeAction: 'parallel_gateway', bidirectional: true },\n { bpmnType: 'bpmn:serviceTask', flowNodeAction: 'http_request', bidirectional: true, notes: 'Maps HTTP/connector tasks' },\n { bpmnType: 'bpmn:scriptTask', flowNodeAction: 'script', bidirectional: true },\n { bpmnType: 'bpmn:userTask', flowNodeAction: 'screen', bidirectional: true },\n { bpmnType: 'bpmn:callActivity', flowNodeAction: 'subflow', bidirectional: true },\n { bpmnType: 'bpmn:intermediateCatchEvent', flowNodeAction: 'wait', bidirectional: true, notes: 'Timer/signal/message catch events' },\n { bpmnType: 'bpmn:boundaryEvent', flowNodeAction: 'boundary_event', bidirectional: true },\n { bpmnType: 'bpmn:task', flowNodeAction: 'assignment', bidirectional: true, notes: 'Generic BPMN task maps to assignment' },\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Integration Protocol Exports\n * \n * External System Connection Protocols\n * - Connector configurations for SaaS, databases, file storage, message queues\n * - GitHub integration (version control, CI/CD)\n * - Vercel integration (deployment, hosting)\n * - Authentication methods (OAuth2, API Key, JWT, SAML)\n * - Data synchronization and field mapping\n * - Webhooks, rate limiting, and retry strategies\n */\n\n// Core Connector Protocol\nexport * from './connector.zod';\n\n// Connector Templates\nexport * from './connector/saas.zod';\nexport * from './connector/database.zod';\nexport * from './connector/file-storage.zod';\nexport * from './connector/message-queue.zod';\nexport * from './connector/github.zod';\nexport * from './connector/vercel.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * SHARED CONNECTOR AUTHENTICATION SCHEMAS\n * These schemas are used by connectors and integrations for external auth.\n * They define \"How we authenticate TO other systems\", not \"How users authenticate TO us\".\n */\n\n/**\n * OAuth2 Authentication Schema\n */\nexport const ConnectorOAuth2Schema = z.object({\n type: z.literal('oauth2'),\n authorizationUrl: z.string().url().describe('OAuth2 authorization endpoint'),\n tokenUrl: z.string().url().describe('OAuth2 token endpoint'),\n clientId: z.string().describe('OAuth2 client ID'),\n clientSecret: z.string().describe('OAuth2 client secret (typically from ENV)'),\n scopes: z.array(z.string()).optional().describe('Requested OAuth2 scopes'),\n redirectUri: z.string().url().optional().describe('OAuth2 redirect URI'),\n refreshToken: z.string().optional().describe('Refresh token for token renewal'),\n tokenExpiry: z.number().optional().describe('Token expiry timestamp'),\n});\n\n/**\n * API Key Authentication Schema\n */\nexport const ConnectorAPIKeySchema = z.object({\n type: z.literal('api-key'),\n key: z.string().describe('API key value'),\n headerName: z.string().default('X-API-Key').describe('HTTP header name for API key'),\n paramName: z.string().optional().describe('Query parameter name (alternative to header)'),\n});\n\n/**\n * Basic Authentication Schema\n */\nexport const ConnectorBasicAuthSchema = z.object({\n type: z.literal('basic'),\n username: z.string().describe('Username'),\n password: z.string().describe('Password'),\n});\n\n/**\n * Bearer Token Authentication Schema\n */\nexport const ConnectorBearerAuthSchema = z.object({\n type: z.literal('bearer'),\n token: z.string().describe('Bearer token'),\n});\n\n/**\n * No Authentication Schema\n */\nexport const ConnectorNoAuthSchema = z.object({\n type: z.literal('none'),\n});\n\n/**\n * Unified Connector Auth Configuration Schema\n */\nexport const ConnectorAuthConfigSchema = z.discriminatedUnion('type', [\n ConnectorOAuth2Schema,\n ConnectorAPIKeySchema,\n ConnectorBasicAuthSchema,\n ConnectorBearerAuthSchema,\n ConnectorNoAuthSchema,\n]);\n\nexport type ConnectorAuthConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { WebhookSchema } from '../automation/webhook.zod';\nimport { ConnectorAuthConfigSchema } from '../shared/connector-auth.zod';\nimport { FieldMappingSchema as BaseFieldMappingSchema } from '../shared/mapping.zod';\n\n/**\n * Connector Protocol - LEVEL 3: Enterprise Connector\n * \n * Defines the standard connector specification for external system integration.\n * Connectors enable ObjectStack to sync data with SaaS apps, databases, file storage,\n * and message queues through a unified protocol.\n * \n * **Positioning in 3-Layer Architecture:**\n * - **L1: Simple Sync** (automation/sync.zod.ts) - Business users - Sync Salesforce to Sheets\n * - **L2: ETL Pipeline** (automation/etl.zod.ts) - Data engineers - Aggregate 10 sources to warehouse\n * - **L3: Enterprise Connector** (THIS FILE) - System integrators - Full SAP integration\n * \n * **SCOPE: Most comprehensive integration layer.**\n * Includes authentication, webhooks, rate limiting, field mapping, bidirectional sync,\n * retry policies, and complete lifecycle management.\n * \n * This protocol supports multiple authentication strategies, bidirectional sync,\n * field mapping, webhooks, and comprehensive rate limiting.\n * \n * Authentication is now imported from the canonical auth/config.zod.ts.\n * \n * ## When to Use This Layer\n * \n * **Use Enterprise Connector when:**\n * - Building enterprise-grade connectors (e.g., Salesforce, SAP, Oracle)\n * - Complex OAuth2/SAML authentication required\n * - Bidirectional sync with field mapping and transformations\n * - Webhook management and rate limiting required\n * - Full CRUD operations and data synchronization\n * - Need comprehensive retry strategies and error handling\n * \n * **Examples:**\n * - Full Salesforce integration with webhooks\n * - SAP ERP connector with CDC (Change Data Capture)\n * - Microsoft Dynamics 365 connector\n * \n * **When to downgrade:**\n * - Simple field sync → Use {@link file://../automation/sync.zod.ts | Simple Sync}\n * - Data transformation only → Use {@link file://../automation/etl.zod.ts | ETL Pipeline}\n * \n * @see {@link file://../automation/sync.zod.ts} for Level 1 (simple sync)\n * @see {@link file://../automation/etl.zod.ts} for Level 2 (data engineering)\n * \n * ## When to use Integration Connector vs. Trigger Registry?\n * \n * **Use `integration/connector.zod.ts` when:**\n * - Building enterprise-grade connectors (e.g., Salesforce, SAP, Oracle)\n * - Complex OAuth2/SAML authentication required\n * - Bidirectional sync with field mapping and transformations\n * - Webhook management and rate limiting required\n * - Full CRUD operations and data synchronization\n * - Need comprehensive retry strategies and error handling\n * \n * **Use `automation/trigger-registry.zod.ts` when:**\n * - Building simple automation triggers (e.g., \"when Slack message received, create task\")\n * - No complex authentication needed (simple API keys, basic auth)\n * - Lightweight, single-purpose integrations\n * - Quick setup with minimal configuration\n * \n * @see ../../automation/trigger-registry.zod.ts for lightweight automation triggers\n */\n\n// ============================================================================\n// Authentication Schemas - IMPORTED FROM CANONICAL SOURCE\n// Use ConnectorAuthConfigSchema from shared/connector-auth.zod.ts\n// ============================================================================\n\n// ============================================================================\n// Field Mapping Schema\n// Uses the canonical field mapping protocol from shared/mapping.zod.ts\n// Extended with connector-specific features\n// ============================================================================\n\n/**\n * Connector Field Mapping Configuration\n * \n * Extends the base field mapping with connector-specific features\n * like bidirectional sync modes and data type mapping.\n */\nexport const FieldMappingSchema = BaseFieldMappingSchema.extend({\n /**\n * Data type mapping (connector-specific)\n */\n dataType: z.enum([\n 'string',\n 'number',\n 'boolean',\n 'date',\n 'datetime',\n 'json',\n 'array',\n ]).optional().describe('Target data type'),\n \n /**\n * Is this field required?\n */\n required: z.boolean().default(false).describe('Field is required'),\n \n /**\n * Bidirectional sync mode (connector-specific)\n */\n syncMode: z.enum([\n 'read_only', // Only sync from external to ObjectStack\n 'write_only', // Only sync from ObjectStack to external\n 'bidirectional', // Sync both ways\n ]).default('bidirectional').describe('Sync mode'),\n});\n\nexport type FieldMapping = z.infer;\n\n// ============================================================================\n// Data Synchronization Configuration\n// ============================================================================\n\n/**\n * Sync Strategy Schema\n */\nexport const SyncStrategySchema = z.enum([\n 'full', // Full refresh (delete all and re-import)\n 'incremental', // Only sync changes since last sync\n 'upsert', // Insert new, update existing\n 'append_only', // Only insert new records\n]).describe('Synchronization strategy');\n\nexport type SyncStrategy = z.infer;\n\n/**\n * Conflict Resolution Strategy\n */\nexport const ConflictResolutionSchema = z.enum([\n 'source_wins', // External system data takes precedence\n 'target_wins', // ObjectStack data takes precedence\n 'latest_wins', // Most recently modified wins\n 'manual', // Flag for manual resolution\n]).describe('Conflict resolution strategy');\n\nexport type ConflictResolution = z.infer;\n\n/**\n * Data Synchronization Configuration\n */\nexport const DataSyncConfigSchema = z.object({\n /**\n * Sync strategy\n */\n strategy: SyncStrategySchema.optional().default('incremental'),\n \n /**\n * Sync direction\n */\n direction: z.enum([\n 'import', // External → ObjectStack\n 'export', // ObjectStack → External\n 'bidirectional', // Both ways\n ]).optional().default('import').describe('Sync direction'),\n \n /**\n * Sync frequency (cron expression)\n */\n schedule: z.string().optional().describe('Cron expression for scheduled sync'),\n \n /**\n * Enable real-time sync via webhooks\n */\n realtimeSync: z.boolean().optional().default(false).describe('Enable real-time sync'),\n \n /**\n * Field to track last sync timestamp\n */\n timestampField: z.string().optional().describe('Field to track last modification time'),\n \n /**\n * Conflict resolution strategy\n */\n conflictResolution: ConflictResolutionSchema.optional().default('latest_wins'),\n \n /**\n * Batch size for bulk operations\n */\n batchSize: z.number().min(1).max(10000).optional().default(1000).describe('Records per batch'),\n \n /**\n * Delete handling\n */\n deleteMode: z.enum([\n 'hard_delete', // Permanently delete\n 'soft_delete', // Mark as deleted\n 'ignore', // Don't sync deletions\n ]).optional().default('soft_delete').describe('Delete handling mode'),\n \n /**\n * Filter criteria for selective sync\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter criteria for selective sync'),\n});\n\nexport type DataSyncConfig = z.infer;\n\n// ============================================================================\n// Webhook Configuration\n// ============================================================================\n\n/**\n * Webhook Event Schema\n */\nexport const WebhookEventSchema = z.enum([\n 'record.created',\n 'record.updated',\n 'record.deleted',\n 'sync.started',\n 'sync.completed',\n 'sync.failed',\n 'auth.expired',\n 'rate_limit.exceeded',\n]).describe('Webhook event type');\n\nexport type WebhookEvent = z.infer;\n\n/**\n * Webhook Signature Algorithm\n */\nexport const WebhookSignatureAlgorithmSchema = z.enum([\n 'hmac_sha256',\n 'hmac_sha512',\n 'none',\n]).describe('Webhook signature algorithm');\n\nexport type WebhookSignatureAlgorithm = z.infer;\n\n/**\n * Webhook Configuration Schema\n * \n * Extends the canonical WebhookSchema with connector-specific event types.\n * This allows connectors to subscribe to both data events and connector lifecycle events.\n */\nexport const WebhookConfigSchema = WebhookSchema.extend({\n /**\n * Events to listen for\n * Connector-specific events like sync completion, auth expiry, etc.\n */\n events: z.array(WebhookEventSchema).optional().describe('Connector events to subscribe to'),\n \n /**\n * Signature algorithm for webhook security\n */\n signatureAlgorithm: WebhookSignatureAlgorithmSchema.optional().default('hmac_sha256'),\n});\n\nexport type WebhookConfig = z.infer;\n\n// ============================================================================\n// Rate Limiting and Retry Configuration\n// ============================================================================\n\n/**\n * Rate Limiting Strategy\n */\nexport const RateLimitStrategySchema = z.enum([\n 'fixed_window', // Fixed time window\n 'sliding_window', // Sliding time window\n 'token_bucket', // Token bucket algorithm\n 'leaky_bucket', // Leaky bucket algorithm\n]).describe('Rate limiting strategy');\n\nexport type RateLimitStrategy = z.infer;\n\n/**\n * Rate Limiting Configuration\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Rate limiting strategy\n */\n strategy: RateLimitStrategySchema.optional().default('token_bucket'),\n \n /**\n * Maximum requests per window\n */\n maxRequests: z.number().min(1).describe('Maximum requests per window'),\n \n /**\n * Time window in seconds\n */\n windowSeconds: z.number().min(1).describe('Time window in seconds'),\n \n /**\n * Burst capacity (for token bucket)\n */\n burstCapacity: z.number().min(1).optional().describe('Burst capacity'),\n \n /**\n * Respect external system rate limits\n */\n respectUpstreamLimits: z.boolean().optional().default(true).describe('Respect external rate limit headers'),\n \n /**\n * Custom rate limit headers to check\n */\n rateLimitHeaders: z.object({\n remaining: z.string().optional().default('X-RateLimit-Remaining').describe('Header for remaining requests'),\n limit: z.string().optional().default('X-RateLimit-Limit').describe('Header for rate limit'),\n reset: z.string().optional().default('X-RateLimit-Reset').describe('Header for reset time'),\n }).optional().describe('Custom rate limit headers'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n/**\n * Retry Strategy\n */\nexport const RetryStrategySchema = z.enum([\n 'exponential_backoff',\n 'linear_backoff',\n 'fixed_delay',\n 'no_retry',\n]).describe('Retry strategy');\n\nexport type RetryStrategy = z.infer;\n\n/**\n * Retry Configuration\n */\nexport const RetryConfigSchema = z.object({\n /**\n * Retry strategy\n */\n strategy: RetryStrategySchema.optional().default('exponential_backoff'),\n \n /**\n * Maximum retry attempts\n */\n maxAttempts: z.number().min(0).max(10).optional().default(3).describe('Maximum retry attempts'),\n \n /**\n * Initial delay in milliseconds\n */\n initialDelayMs: z.number().min(100).optional().default(1000).describe('Initial retry delay in ms'),\n \n /**\n * Maximum delay in milliseconds\n */\n maxDelayMs: z.number().min(1000).optional().default(60000).describe('Maximum retry delay in ms'),\n \n /**\n * Backoff multiplier (for exponential backoff)\n */\n backoffMultiplier: z.number().min(1).optional().default(2).describe('Exponential backoff multiplier'),\n \n /**\n * HTTP status codes to retry\n */\n retryableStatusCodes: z.array(z.number()).optional().default([408, 429, 500, 502, 503, 504]).describe('HTTP status codes to retry'),\n \n /**\n * Retry on network errors\n */\n retryOnNetworkError: z.boolean().optional().default(true).describe('Retry on network errors'),\n \n /**\n * Jitter to add randomness to retry delays\n */\n jitter: z.boolean().optional().default(true).describe('Add jitter to retry delays'),\n});\n\nexport type RetryConfig = z.infer;\n\n// ============================================================================\n// Error Mapping Configuration\n// ============================================================================\n\n/**\n * Error Category\n */\nexport const ErrorCategorySchema = z.enum([\n 'validation',\n 'authorization',\n 'not_found',\n 'conflict',\n 'rate_limit',\n 'timeout',\n 'server_error',\n 'integration_error',\n]).describe('Standard error category');\n\nexport type ErrorCategory = z.infer;\n\n/**\n * Error Mapping Rule\n * \n * Maps an external system error code to an ObjectStack standard error.\n */\nexport const ErrorMappingRuleSchema = z.object({\n sourceCode: z.union([z.string(), z.number()]).describe('External system error code'),\n sourceMessage: z.string().optional().describe('Pattern to match against error message'),\n targetCode: z.string().describe('ObjectStack standard error code'),\n targetCategory: ErrorCategorySchema.describe('Error category'),\n severity: z.enum(['low', 'medium', 'high', 'critical']).describe('Error severity level'),\n retryable: z.boolean().describe('Whether the error is retryable'),\n userMessage: z.string().optional().describe('Human-readable message to show users'),\n}).describe('Error mapping rule');\n\nexport type ErrorMappingRule = z.infer;\n\n/**\n * Error Mapping Configuration\n * \n * Configures how external system errors are mapped to ObjectStack standard errors.\n */\nexport const ErrorMappingConfigSchema = z.object({\n rules: z.array(ErrorMappingRuleSchema).describe('Error mapping rules'),\n defaultCategory: ErrorCategorySchema.optional().default('integration_error').describe('Default category for unmapped errors'),\n unmappedBehavior: z.enum(['passthrough', 'generic_error', 'throw']).describe('What to do with unmapped errors'),\n logUnmapped: z.boolean().optional().default(true).describe('Log unmapped errors'),\n}).describe('Error mapping configuration');\n\nexport type ErrorMappingConfig = z.infer;\n\n// ============================================================================\n// Health Check & Circuit Breaker Configuration\n// ============================================================================\n\n/**\n * Health Check Configuration\n * \n * Configures periodic health checks for connector endpoints.\n */\nexport const HealthCheckConfigSchema = z.object({\n enabled: z.boolean().describe('Enable health checks'),\n intervalMs: z.number().optional().default(60000).describe('Health check interval in milliseconds'),\n timeoutMs: z.number().optional().default(5000).describe('Health check timeout in milliseconds'),\n endpoint: z.string().optional().describe('Health check endpoint path'),\n method: z.enum(['GET', 'HEAD', 'OPTIONS']).optional().describe('HTTP method for health check'),\n expectedStatus: z.number().optional().default(200).describe('Expected HTTP status code'),\n unhealthyThreshold: z.number().optional().default(3).describe('Consecutive failures before marking unhealthy'),\n healthyThreshold: z.number().optional().default(1).describe('Consecutive successes before marking healthy'),\n}).describe('Health check configuration');\n\nexport type HealthCheckConfig = z.infer;\n\n/**\n * Circuit Breaker Configuration\n * \n * Implements the circuit breaker pattern to prevent cascading failures.\n */\nexport const CircuitBreakerConfigSchema = z.object({\n enabled: z.boolean().describe('Enable circuit breaker'),\n failureThreshold: z.number().optional().default(5).describe('Failures before opening circuit'),\n resetTimeoutMs: z.number().optional().default(30000).describe('Time in open state before half-open'),\n halfOpenMaxRequests: z.number().optional().default(1).describe('Requests allowed in half-open state'),\n monitoringWindow: z.number().optional().default(60000).describe('Rolling window for failure count in ms'),\n fallbackStrategy: z.enum(['cache', 'default_value', 'error', 'queue']).optional().describe('Fallback strategy when circuit is open'),\n}).describe('Circuit breaker configuration');\n\nexport type CircuitBreakerConfig = z.infer;\n\n/**\n * Connector Health Configuration\n * \n * Combines health check and circuit breaker for connector resilience.\n */\nexport const ConnectorHealthSchema = z.object({\n healthCheck: HealthCheckConfigSchema.optional().describe('Health check configuration'),\n circuitBreaker: CircuitBreakerConfigSchema.optional().describe('Circuit breaker configuration'),\n}).describe('Connector health configuration');\n\nexport type ConnectorHealth = z.infer;\n\n// ============================================================================\n// Base Connector Schema\n// ============================================================================\n\n/**\n * Connector Type\n */\nexport const ConnectorTypeSchema = z.enum([\n 'saas', // SaaS application connector\n 'database', // Database connector\n 'file_storage', // File storage connector\n 'message_queue', // Message queue connector\n 'api', // Generic REST/GraphQL API\n 'custom', // Custom connector\n]).describe('Connector type');\n\nexport type ConnectorType = z.infer;\n\n/**\n * Connector Status\n */\nexport const ConnectorStatusSchema = z.enum([\n 'active', // Connector is active and syncing\n 'inactive', // Connector is configured but disabled\n 'error', // Connector has errors\n 'configuring', // Connector is being set up\n]).describe('Connector status');\n\nexport type ConnectorStatus = z.infer;\n\n/**\n * Connector Action Definition\n */\nexport const ConnectorActionSchema = z.object({\n key: z.string().describe('Action key (machine name)'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n inputSchema: z.record(z.string(), z.unknown()).optional().describe('Input parameters schema (JSON Schema)'),\n outputSchema: z.record(z.string(), z.unknown()).optional().describe('Output schema (JSON Schema)'),\n});\n\n/**\n * Connector Trigger Definition\n */\nexport const ConnectorTriggerSchema = z.object({\n key: z.string().describe('Trigger key'),\n label: z.string().describe('Trigger label'),\n description: z.string().optional(),\n type: z.enum(['polling', 'webhook']).describe('Trigger type'),\n interval: z.number().optional().describe('Polling interval in seconds'),\n});\n\n/**\n * Base Connector Schema\n * Core connector configuration shared across all connector types\n */\nexport const ConnectorSchema = z.object({\n /**\n * Machine name (snake_case)\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique connector identifier'),\n \n /**\n * Human-readable label\n */\n label: z.string().describe('Display label'),\n \n /**\n * Connector type\n */\n type: ConnectorTypeSchema.describe('Connector type'),\n \n /**\n * Description\n */\n description: z.string().optional().describe('Connector description'),\n \n /**\n * Icon identifier\n */\n icon: z.string().optional().describe('Icon identifier'),\n \n /**\n * Authentication configuration\n */\n authentication: ConnectorAuthConfigSchema.describe('Authentication configuration'),\n\n /** Zapier-style Capabilities */\n actions: z.array(ConnectorActionSchema).optional(),\n triggers: z.array(ConnectorTriggerSchema).optional(),\n \n /**\n * Data synchronization configuration\n */\n syncConfig: DataSyncConfigSchema.optional().describe('Data sync configuration'),\n \n \n /**\n * Field mappings\n */\n fieldMappings: z.array(FieldMappingSchema).optional().describe('Field mapping rules'),\n \n /**\n * Webhook configuration\n */\n webhooks: z.array(WebhookConfigSchema).optional().describe('Webhook configurations'),\n \n /**\n * Rate limiting configuration\n */\n rateLimitConfig: RateLimitConfigSchema.optional().describe('Rate limiting configuration'),\n \n /**\n * Retry configuration\n */\n retryConfig: RetryConfigSchema.optional().describe('Retry configuration'),\n \n /**\n * Connection timeout in milliseconds\n */\n connectionTimeoutMs: z.number().min(1000).max(300000).optional().default(30000).describe('Connection timeout in ms'),\n \n /**\n * Request timeout in milliseconds\n */\n requestTimeoutMs: z.number().min(1000).max(300000).optional().default(30000).describe('Request timeout in ms'),\n \n /**\n * Connector status\n */\n status: ConnectorStatusSchema.optional().default('inactive').describe('Connector status'),\n \n /**\n * Enable connector\n */\n enabled: z.boolean().optional().default(true).describe('Enable connector'),\n \n /**\n * Error mapping configuration\n */\n errorMapping: ErrorMappingConfigSchema.optional().describe('Error mapping configuration'),\n \n /**\n * Health check and circuit breaker configuration\n */\n health: ConnectorHealthSchema.optional().describe('Health and resilience configuration'),\n \n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom connector metadata'),\n});\n\nexport type Connector = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n FieldMappingSchema,\n} from '../connector.zod';\n\n/**\n * SaaS Connector Protocol Template\n * \n * Specialized connector for SaaS applications (Salesforce, HubSpot, Stripe, etc.)\n * Extends the base connector with SaaS-specific features like OAuth flows,\n * object type discovery, and API version management.\n */\n\n/**\n * SaaS Provider Types\n */\nexport const SaasProviderSchema = z.enum([\n 'salesforce',\n 'hubspot',\n 'stripe',\n 'shopify',\n 'zendesk',\n 'intercom',\n 'mailchimp',\n 'slack',\n 'microsoft_dynamics',\n 'servicenow',\n 'netsuite',\n 'custom',\n]).describe('SaaS provider type');\n\nexport type SaasProvider = z.infer;\n\n/**\n * API Version Configuration\n */\nexport const ApiVersionConfigSchema = z.object({\n version: z.string().describe('API version (e.g., \"v2\", \"2023-10-01\")'),\n isDefault: z.boolean().default(false).describe('Is this the default version'),\n deprecationDate: z.string().optional().describe('API version deprecation date (ISO 8601)'),\n sunsetDate: z.string().optional().describe('API version sunset date (ISO 8601)'),\n});\n\nexport type ApiVersionConfig = z.infer;\n\n/**\n * SaaS Object Type Schema\n * Represents a syncable entity in the SaaS system (e.g., Account, Contact, Deal)\n */\nexport const SaasObjectTypeSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Object type name (snake_case)'),\n label: z.string().describe('Display label'),\n apiName: z.string().describe('API name in external system'),\n enabled: z.boolean().default(true).describe('Enable sync for this object'),\n supportsCreate: z.boolean().default(true).describe('Supports record creation'),\n supportsUpdate: z.boolean().default(true).describe('Supports record updates'),\n supportsDelete: z.boolean().default(true).describe('Supports record deletion'),\n fieldMappings: z.array(FieldMappingSchema).optional().describe('Object-specific field mappings'),\n});\n\nexport type SaasObjectType = z.infer;\n\n/**\n * SaaS Connector Configuration Schema\n */\nexport const SaasConnectorSchema = ConnectorSchema.extend({\n type: z.literal('saas'),\n \n /**\n * SaaS provider\n */\n provider: SaasProviderSchema.describe('SaaS provider type'),\n \n /**\n * Base URL for API requests\n */\n baseUrl: z.string().url().describe('API base URL'),\n \n /**\n * API version configuration\n */\n apiVersion: ApiVersionConfigSchema.optional().describe('API version configuration'),\n \n /**\n * Supported object types to sync\n */\n objectTypes: z.array(SaasObjectTypeSchema).describe('Syncable object types'),\n \n /**\n * OAuth-specific settings\n */\n oauthSettings: z.object({\n scopes: z.array(z.string()).describe('Required OAuth scopes'),\n refreshTokenUrl: z.string().url().optional().describe('Token refresh endpoint'),\n revokeTokenUrl: z.string().url().optional().describe('Token revocation endpoint'),\n autoRefresh: z.boolean().default(true).describe('Automatically refresh expired tokens'),\n }).optional().describe('OAuth-specific configuration'),\n \n /**\n * Pagination settings\n */\n paginationConfig: z.object({\n type: z.enum(['cursor', 'offset', 'page']).default('cursor').describe('Pagination type'),\n defaultPageSize: z.number().min(1).max(1000).default(100).describe('Default page size'),\n maxPageSize: z.number().min(1).max(10000).default(1000).describe('Maximum page size'),\n }).optional().describe('Pagination configuration'),\n \n /**\n * Sandbox/test environment settings\n */\n sandboxConfig: z.object({\n enabled: z.boolean().default(false).describe('Use sandbox environment'),\n baseUrl: z.string().url().optional().describe('Sandbox API base URL'),\n }).optional().describe('Sandbox environment configuration'),\n \n /**\n * Custom request headers\n */\n customHeaders: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers for all requests'),\n});\n\nexport type SaasConnector = z.infer;\nexport type SaaSConnector = SaasConnector; // Alias for alternative capitalization\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Salesforce Connector Configuration\n */\nexport const salesforceConnectorExample = {\n name: 'salesforce_production',\n label: 'Salesforce Production',\n type: 'saas',\n provider: 'salesforce',\n baseUrl: 'https://example.my.salesforce.com',\n apiVersion: {\n version: 'v59.0',\n isDefault: true,\n },\n authentication: {\n type: 'oauth2',\n clientId: '${SALESFORCE_CLIENT_ID}',\n clientSecret: '${SALESFORCE_CLIENT_SECRET}',\n authorizationUrl: 'https://login.salesforce.com/services/oauth2/authorize',\n tokenUrl: 'https://login.salesforce.com/services/oauth2/token',\n grantType: 'authorization_code',\n scopes: ['api', 'refresh_token', 'offline_access'],\n },\n objectTypes: [\n {\n name: 'account',\n label: 'Account',\n apiName: 'Account',\n enabled: true,\n supportsCreate: true,\n supportsUpdate: true,\n supportsDelete: true,\n },\n {\n name: 'contact',\n label: 'Contact',\n apiName: 'Contact',\n enabled: true,\n supportsCreate: true,\n supportsUpdate: true,\n supportsDelete: true,\n },\n ],\n syncConfig: {\n strategy: 'incremental',\n direction: 'bidirectional',\n schedule: '0 */6 * * *', // Every 6 hours\n realtimeSync: true,\n conflictResolution: 'latest_wins',\n batchSize: 200,\n deleteMode: 'soft_delete',\n },\n rateLimitConfig: {\n strategy: 'token_bucket',\n maxRequests: 100,\n windowSeconds: 20,\n respectUpstreamLimits: true,\n },\n retryConfig: {\n strategy: 'exponential_backoff',\n maxAttempts: 3,\n initialDelayMs: 1000,\n maxDelayMs: 30000,\n backoffMultiplier: 2,\n retryableStatusCodes: [408, 429, 500, 502, 503, 504],\n retryOnNetworkError: true,\n jitter: true,\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: HubSpot Connector Configuration\n */\nexport const hubspotConnectorExample = {\n name: 'hubspot_crm',\n label: 'HubSpot CRM',\n type: 'saas',\n provider: 'hubspot',\n baseUrl: 'https://api.hubapi.com',\n authentication: {\n type: 'api_key',\n apiKey: '${HUBSPOT_API_KEY}',\n headerName: 'Authorization',\n },\n objectTypes: [\n {\n name: 'company',\n label: 'Company',\n apiName: 'companies',\n enabled: true,\n supportsCreate: true,\n supportsUpdate: true,\n supportsDelete: true,\n },\n {\n name: 'deal',\n label: 'Deal',\n apiName: 'deals',\n enabled: true,\n supportsCreate: true,\n supportsUpdate: true,\n supportsDelete: true,\n },\n ],\n syncConfig: {\n strategy: 'incremental',\n direction: 'import',\n schedule: '0 */4 * * *', // Every 4 hours\n conflictResolution: 'source_wins',\n batchSize: 100,\n },\n rateLimitConfig: {\n strategy: 'token_bucket',\n maxRequests: 100,\n windowSeconds: 10,\n },\n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n FieldMappingSchema,\n} from '../connector.zod';\n\n/**\n * Database Connector Protocol Template\n * \n * Specialized connector for database systems (PostgreSQL, MySQL, SQL Server, etc.)\n * Extends the base connector with database-specific features like schema discovery,\n * CDC (Change Data Capture), and connection pooling.\n */\n\n/**\n * Database Provider Types\n */\nexport const DatabaseProviderSchema = z.enum([\n 'postgresql',\n 'mysql',\n 'mariadb',\n 'mssql',\n 'oracle',\n 'mongodb',\n 'redis',\n 'cassandra',\n 'snowflake',\n 'bigquery',\n 'redshift',\n 'custom',\n]).describe('Database provider type');\n\nexport type DatabaseProvider = z.infer;\n\n/**\n * Database Connection Pool Configuration\n */\nexport const DatabasePoolConfigSchema = z.object({\n min: z.number().min(0).default(2).describe('Minimum connections in pool'),\n max: z.number().min(1).default(10).describe('Maximum connections in pool'),\n idleTimeoutMs: z.number().min(1000).default(30000).describe('Idle connection timeout in ms'),\n connectionTimeoutMs: z.number().min(1000).default(10000).describe('Connection establishment timeout in ms'),\n acquireTimeoutMs: z.number().min(1000).default(30000).describe('Connection acquisition timeout in ms'),\n evictionRunIntervalMs: z.number().min(1000).default(30000).describe('Connection eviction check interval in ms'),\n testOnBorrow: z.boolean().default(true).describe('Test connection before use'),\n});\n\nexport type DatabasePoolConfig = z.infer;\n\n/**\n * SSL/TLS Configuration\n */\nexport const SslConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable SSL/TLS'),\n rejectUnauthorized: z.boolean().default(true).describe('Reject unauthorized certificates'),\n ca: z.string().optional().describe('Certificate Authority certificate'),\n cert: z.string().optional().describe('Client certificate'),\n key: z.string().optional().describe('Client private key'),\n});\n\nexport type SslConfig = z.infer;\n\n/**\n * Change Data Capture (CDC) Configuration\n */\nexport const CdcConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable CDC'),\n \n method: z.enum([\n 'log_based', // Transaction log parsing (e.g., PostgreSQL logical replication)\n 'trigger_based', // Database triggers for change tracking\n 'query_based', // Timestamp-based queries\n 'custom', // Custom CDC implementation\n ]).describe('CDC method'),\n \n slotName: z.string().optional().describe('Replication slot name (for log-based CDC)'),\n \n publicationName: z.string().optional().describe('Publication name (for PostgreSQL)'),\n \n startPosition: z.string().optional().describe('Starting position/LSN for CDC stream'),\n \n batchSize: z.number().min(1).max(10000).default(1000).describe('CDC batch size'),\n \n pollIntervalMs: z.number().min(100).default(1000).describe('CDC polling interval in ms'),\n});\n\nexport type CdcConfig = z.infer;\n\n/**\n * Database Table Configuration\n */\nexport const DatabaseTableSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Table name in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n schema: z.string().optional().describe('Database schema name'),\n tableName: z.string().describe('Actual table name in database'),\n primaryKey: z.string().describe('Primary key column'),\n enabled: z.boolean().default(true).describe('Enable sync for this table'),\n fieldMappings: z.array(FieldMappingSchema).optional().describe('Table-specific field mappings'),\n whereClause: z.string().optional().describe('SQL WHERE clause for filtering'),\n});\n\nexport type DatabaseTable = z.infer;\n\n/**\n * Database Connector Configuration Schema\n */\nexport const DatabaseConnectorSchema = ConnectorSchema.extend({\n type: z.literal('database'),\n \n /**\n * Database provider\n */\n provider: DatabaseProviderSchema.describe('Database provider type'),\n \n /**\n * Connection configuration\n */\n connectionConfig: z.object({\n host: z.string().describe('Database host'),\n port: z.number().min(1).max(65535).describe('Database port'),\n database: z.string().describe('Database name'),\n username: z.string().describe('Database username'),\n password: z.string().describe('Database password (typically from ENV)'),\n options: z.record(z.string(), z.unknown()).optional().describe('Driver-specific connection options'),\n }).describe('Database connection configuration'),\n \n /**\n * Connection pool configuration\n */\n poolConfig: DatabasePoolConfigSchema.optional().describe('Connection pool configuration'),\n \n /**\n * SSL/TLS configuration\n */\n sslConfig: SslConfigSchema.optional().describe('SSL/TLS configuration'),\n \n /**\n * Tables to sync\n */\n tables: z.array(DatabaseTableSchema).describe('Tables to sync'),\n \n /**\n * Change Data Capture configuration\n */\n cdcConfig: CdcConfigSchema.optional().describe('CDC configuration'),\n \n /**\n * Read replica configuration\n */\n readReplicaConfig: z.object({\n enabled: z.boolean().default(false).describe('Use read replicas'),\n hosts: z.array(z.object({\n host: z.string().describe('Replica host'),\n port: z.number().min(1).max(65535).describe('Replica port'),\n weight: z.number().min(0).max(1).default(1).describe('Load balancing weight'),\n })).describe('Read replica hosts'),\n }).optional().describe('Read replica configuration'),\n \n /**\n * Query timeout\n */\n queryTimeoutMs: z.number().min(1000).max(300000).optional().default(30000).describe('Query timeout in ms'),\n \n /**\n * Enable query logging\n */\n enableQueryLogging: z.boolean().optional().default(false).describe('Enable SQL query logging'),\n});\n\nexport type DatabaseConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: PostgreSQL Connector Configuration\n */\nexport const postgresConnectorExample = {\n name: 'postgres_production',\n label: 'Production PostgreSQL',\n type: 'database',\n provider: 'postgresql',\n authentication: {\n type: 'basic',\n username: '${DB_USERNAME}',\n password: '${DB_PASSWORD}',\n },\n connectionConfig: {\n host: 'db.example.com',\n port: 5432,\n database: 'production',\n username: '${DB_USERNAME}',\n password: '${DB_PASSWORD}',\n },\n poolConfig: {\n min: 2,\n max: 20,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 10000,\n acquireTimeoutMs: 30000,\n evictionRunIntervalMs: 30000,\n testOnBorrow: true,\n },\n sslConfig: {\n enabled: true,\n rejectUnauthorized: true,\n },\n tables: [\n {\n name: 'customer',\n label: 'Customer',\n schema: 'public',\n tableName: 'customers',\n primaryKey: 'id',\n enabled: true,\n },\n {\n name: 'order',\n label: 'Order',\n schema: 'public',\n tableName: 'orders',\n primaryKey: 'id',\n enabled: true,\n whereClause: 'status != \\'archived\\'',\n },\n ],\n cdcConfig: {\n enabled: true,\n method: 'log_based',\n slotName: 'objectstack_replication_slot',\n publicationName: 'objectstack_publication',\n batchSize: 1000,\n pollIntervalMs: 1000,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'bidirectional',\n realtimeSync: true,\n conflictResolution: 'latest_wins',\n batchSize: 1000,\n deleteMode: 'soft_delete',\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: MongoDB Connector Configuration\n */\nexport const mongoConnectorExample = {\n name: 'mongodb_analytics',\n label: 'MongoDB Analytics',\n type: 'database',\n provider: 'mongodb',\n authentication: {\n type: 'basic',\n username: '${MONGO_USERNAME}',\n password: '${MONGO_PASSWORD}',\n },\n connectionConfig: {\n host: 'mongodb.example.com',\n port: 27017,\n database: 'analytics',\n username: '${MONGO_USERNAME}',\n password: '${MONGO_PASSWORD}',\n options: {\n authSource: 'admin',\n replicaSet: 'rs0',\n },\n },\n tables: [\n {\n name: 'event',\n label: 'Event',\n tableName: 'events',\n primaryKey: 'id',\n enabled: true,\n },\n ],\n cdcConfig: {\n enabled: true,\n method: 'log_based',\n batchSize: 1000,\n pollIntervalMs: 500,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'import',\n batchSize: 1000,\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Snowflake Connector Configuration\n */\nexport const snowflakeConnectorExample = {\n name: 'snowflake_warehouse',\n label: 'Snowflake Data Warehouse',\n type: 'database',\n provider: 'snowflake',\n authentication: {\n type: 'basic',\n username: '${SNOWFLAKE_USERNAME}',\n password: '${SNOWFLAKE_PASSWORD}',\n },\n connectionConfig: {\n host: 'account.snowflakecomputing.com',\n port: 443,\n database: 'ANALYTICS_DB',\n username: '${SNOWFLAKE_USERNAME}',\n password: '${SNOWFLAKE_PASSWORD}',\n options: {\n warehouse: 'COMPUTE_WH',\n schema: 'PUBLIC',\n role: 'ANALYST',\n },\n },\n tables: [\n {\n name: 'sales_summary',\n label: 'Sales Summary',\n schema: 'PUBLIC',\n tableName: 'SALES_SUMMARY',\n primaryKey: 'ID',\n enabled: true,\n },\n ],\n syncConfig: {\n strategy: 'full',\n direction: 'import',\n schedule: '0 2 * * *', // Daily at 2 AM\n batchSize: 5000,\n },\n queryTimeoutMs: 60000,\n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n} from '../connector.zod';\n\n/**\n * File Storage Connector Protocol Template\n * \n * Specialized connector for file storage systems (S3, Azure Blob, Google Cloud Storage, etc.)\n * Extends the base connector with file-specific features like multipart uploads,\n * versioning, and metadata extraction.\n */\n\n/**\n * File Storage Provider Types\n */\nexport const FileStorageProviderSchema = z.enum([\n 's3', // Amazon S3\n 'azure_blob', // Azure Blob Storage\n 'gcs', // Google Cloud Storage\n 'dropbox', // Dropbox\n 'box', // Box\n 'onedrive', // Microsoft OneDrive\n 'google_drive', // Google Drive\n 'sharepoint', // SharePoint\n 'ftp', // FTP/SFTP\n 'local', // Local file system\n 'custom', // Custom file storage\n]).describe('File storage provider type');\n\nexport type FileStorageProvider = z.infer;\n\n/**\n * File Access Pattern\n */\nexport const FileAccessPatternSchema = z.enum([\n 'public_read', // Public read access\n 'private', // Private access\n 'authenticated_read', // Requires authentication\n 'bucket_owner_read', // Bucket owner has read access\n 'bucket_owner_full', // Bucket owner has full control\n]).describe('File access pattern');\n\nexport type FileAccessPattern = z.infer;\n\n/**\n * File Metadata Configuration\n */\nexport const FileMetadataConfigSchema = z.object({\n extractMetadata: z.boolean().default(true).describe('Extract file metadata'),\n \n metadataFields: z.array(z.enum([\n 'content_type',\n 'file_size',\n 'last_modified',\n 'etag',\n 'checksum',\n 'creator',\n 'created_at',\n 'custom',\n ])).optional().describe('Metadata fields to extract'),\n \n customMetadata: z.record(z.string(), z.string()).optional().describe('Custom metadata key-value pairs'),\n});\n\nexport type FileMetadataConfig = z.infer;\n\n/**\n * Multipart Upload Configuration\n */\nexport const MultipartUploadConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable multipart uploads'),\n \n partSize: z.number().min(5 * 1024 * 1024).default(5 * 1024 * 1024).describe('Part size in bytes (min 5MB)'),\n \n maxConcurrentParts: z.number().min(1).max(10).default(5).describe('Maximum concurrent part uploads'),\n \n threshold: z.number().min(5 * 1024 * 1024).default(100 * 1024 * 1024).describe('File size threshold for multipart upload in bytes'),\n});\n\nexport type MultipartUploadConfig = z.infer;\n\n/**\n * File Versioning Configuration\n */\nexport const FileVersioningConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable file versioning'),\n \n maxVersions: z.number().min(1).max(100).optional().describe('Maximum versions to retain'),\n \n retentionDays: z.number().min(1).optional().describe('Version retention period in days'),\n});\n\nexport type FileVersioningConfig = z.infer;\n\n/**\n * File Filter Configuration\n */\nexport const FileFilterConfigSchema = z.object({\n includePatterns: z.array(z.string()).optional().describe('File patterns to include (glob)'),\n \n excludePatterns: z.array(z.string()).optional().describe('File patterns to exclude (glob)'),\n \n minFileSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n \n maxFileSize: z.number().min(1).optional().describe('Maximum file size in bytes'),\n \n allowedExtensions: z.array(z.string()).optional().describe('Allowed file extensions'),\n \n blockedExtensions: z.array(z.string()).optional().describe('Blocked file extensions'),\n});\n\nexport type FileFilterConfig = z.infer;\n\n/**\n * File Storage Bucket/Container Configuration\n */\nexport const StorageBucketSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Bucket identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n bucketName: z.string().describe('Actual bucket/container name in storage system'),\n region: z.string().optional().describe('Storage region'),\n enabled: z.boolean().default(true).describe('Enable sync for this bucket'),\n prefix: z.string().optional().describe('Prefix/path within bucket'),\n accessPattern: FileAccessPatternSchema.optional().describe('Access pattern'),\n fileFilters: FileFilterConfigSchema.optional().describe('File filter configuration'),\n});\n\nexport type StorageBucket = z.infer;\n\n/**\n * File Storage Connector Configuration Schema\n */\nexport const FileStorageConnectorSchema = ConnectorSchema.extend({\n type: z.literal('file_storage'),\n \n /**\n * File storage provider\n */\n provider: FileStorageProviderSchema.describe('File storage provider type'),\n \n /**\n * Storage configuration\n */\n storageConfig: z.object({\n endpoint: z.string().url().optional().describe('Custom endpoint URL'),\n region: z.string().optional().describe('Default region'),\n pathStyle: z.boolean().optional().default(false).describe('Use path-style URLs (for S3-compatible)'),\n }).optional().describe('Storage configuration'),\n \n /**\n * Buckets/containers to sync\n */\n buckets: z.array(StorageBucketSchema).describe('Buckets/containers to sync'),\n \n /**\n * File metadata configuration\n */\n metadataConfig: FileMetadataConfigSchema.optional().describe('Metadata extraction configuration'),\n \n /**\n * Multipart upload configuration\n */\n multipartConfig: MultipartUploadConfigSchema.optional().describe('Multipart upload configuration'),\n \n /**\n * File versioning configuration\n */\n versioningConfig: FileVersioningConfigSchema.optional().describe('File versioning configuration'),\n \n /**\n * Enable server-side encryption\n */\n encryption: z.object({\n enabled: z.boolean().default(false).describe('Enable server-side encryption'),\n algorithm: z.enum(['AES256', 'aws:kms', 'custom']).optional().describe('Encryption algorithm'),\n kmsKeyId: z.string().optional().describe('KMS key ID (for aws:kms)'),\n }).optional().describe('Encryption configuration'),\n \n /**\n * Lifecycle policy\n */\n lifecyclePolicy: z.object({\n enabled: z.boolean().default(false).describe('Enable lifecycle policy'),\n deleteAfterDays: z.number().min(1).optional().describe('Delete files after N days'),\n archiveAfterDays: z.number().min(1).optional().describe('Archive files after N days'),\n }).optional().describe('Lifecycle policy'),\n \n /**\n * Content processing configuration\n */\n contentProcessing: z.object({\n extractText: z.boolean().default(false).describe('Extract text from documents'),\n generateThumbnails: z.boolean().default(false).describe('Generate image thumbnails'),\n thumbnailSizes: z.array(z.object({\n width: z.number().min(1),\n height: z.number().min(1),\n })).optional().describe('Thumbnail sizes'),\n virusScan: z.boolean().default(false).describe('Scan for viruses'),\n }).optional().describe('Content processing configuration'),\n \n /**\n * Download/upload buffer size\n */\n bufferSize: z.number().min(1024).default(64 * 1024).describe('Buffer size in bytes'),\n \n /**\n * Enable transfer acceleration (for supported providers)\n */\n transferAcceleration: z.boolean().default(false).describe('Enable transfer acceleration'),\n});\n\nexport type FileStorageConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Amazon S3 Connector Configuration\n */\nexport const s3ConnectorExample = {\n name: 's3_production_assets',\n label: 'Production S3 Assets',\n type: 'file_storage',\n provider: 's3',\n authentication: {\n type: 'api_key',\n apiKey: '${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}',\n headerName: 'Authorization',\n },\n storageConfig: {\n region: 'us-east-1',\n pathStyle: false,\n },\n buckets: [\n {\n name: 'product_images',\n label: 'Product Images',\n bucketName: 'my-company-product-images',\n region: 'us-east-1',\n enabled: true,\n prefix: 'products/',\n accessPattern: 'public_read',\n fileFilters: {\n allowedExtensions: ['.jpg', '.jpeg', '.png', '.webp'],\n maxFileSize: 10 * 1024 * 1024, // 10MB\n },\n },\n {\n name: 'customer_documents',\n label: 'Customer Documents',\n bucketName: 'my-company-customer-docs',\n region: 'us-east-1',\n enabled: true,\n accessPattern: 'private',\n fileFilters: {\n allowedExtensions: ['.pdf', '.docx', '.xlsx'],\n maxFileSize: 50 * 1024 * 1024, // 50MB\n },\n },\n ],\n metadataConfig: {\n extractMetadata: true,\n metadataFields: ['content_type', 'file_size', 'last_modified', 'etag'],\n },\n multipartConfig: {\n enabled: true,\n partSize: 5 * 1024 * 1024, // 5MB\n maxConcurrentParts: 5,\n threshold: 100 * 1024 * 1024, // 100MB\n },\n versioningConfig: {\n enabled: true,\n maxVersions: 10,\n },\n encryption: {\n enabled: true,\n algorithm: 'aws:kms',\n kmsKeyId: '${AWS_KMS_KEY_ID}',\n },\n contentProcessing: {\n extractText: true,\n generateThumbnails: true,\n thumbnailSizes: [\n { width: 150, height: 150 },\n { width: 300, height: 300 },\n { width: 600, height: 600 },\n ],\n virusScan: true,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'bidirectional',\n realtimeSync: true,\n conflictResolution: 'latest_wins',\n batchSize: 100,\n },\n transferAcceleration: true,\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Google Drive Connector Configuration\n */\nexport const googleDriveConnectorExample = {\n name: 'google_drive_team',\n label: 'Google Drive Team Folder',\n type: 'file_storage',\n provider: 'google_drive',\n authentication: {\n type: 'oauth2',\n clientId: '${GOOGLE_CLIENT_ID}',\n clientSecret: '${GOOGLE_CLIENT_SECRET}',\n authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n tokenUrl: 'https://oauth2.googleapis.com/token',\n grantType: 'authorization_code',\n scopes: ['https://www.googleapis.com/auth/drive.file'],\n },\n buckets: [\n {\n name: 'team_drive',\n label: 'Team Drive',\n bucketName: 'shared-team-drive',\n enabled: true,\n fileFilters: {\n excludePatterns: ['*.tmp', '~$*'],\n },\n },\n ],\n metadataConfig: {\n extractMetadata: true,\n metadataFields: ['content_type', 'file_size', 'last_modified', 'creator', 'created_at'],\n },\n versioningConfig: {\n enabled: true,\n maxVersions: 5,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'bidirectional',\n realtimeSync: true,\n conflictResolution: 'latest_wins',\n batchSize: 50,\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Azure Blob Storage Connector Configuration\n */\nexport const azureBlobConnectorExample = {\n name: 'azure_blob_storage',\n label: 'Azure Blob Storage',\n type: 'file_storage',\n provider: 'azure_blob',\n authentication: {\n type: 'api_key',\n apiKey: '${AZURE_STORAGE_ACCOUNT_KEY}',\n headerName: 'x-ms-blob-type',\n },\n storageConfig: {\n endpoint: 'https://myaccount.blob.core.windows.net',\n },\n buckets: [\n {\n name: 'archive_container',\n label: 'Archive Container',\n bucketName: 'archive',\n enabled: true,\n accessPattern: 'private',\n },\n ],\n metadataConfig: {\n extractMetadata: true,\n metadataFields: ['content_type', 'file_size', 'last_modified', 'etag'],\n },\n encryption: {\n enabled: true,\n algorithm: 'AES256',\n },\n lifecyclePolicy: {\n enabled: true,\n archiveAfterDays: 90,\n deleteAfterDays: 365,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'import',\n schedule: '0 1 * * *', // Daily at 1 AM\n batchSize: 200,\n },\n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n} from '../connector.zod';\n\n/**\n * Message Queue Connector Protocol Template\n * \n * Specialized connector for message queue systems (RabbitMQ, Kafka, SQS, etc.)\n * Extends the base connector with message queue-specific features like topics,\n * consumer groups, and message acknowledgment patterns.\n */\n\n/**\n * Message Queue Provider Types\n */\nexport const MessageQueueProviderSchema = z.enum([\n 'rabbitmq', // RabbitMQ\n 'kafka', // Apache Kafka\n 'redis_pubsub', // Redis Pub/Sub\n 'redis_streams', // Redis Streams\n 'aws_sqs', // Amazon SQS\n 'aws_sns', // Amazon SNS\n 'google_pubsub', // Google Cloud Pub/Sub\n 'azure_service_bus', // Azure Service Bus\n 'azure_event_hubs', // Azure Event Hubs\n 'nats', // NATS\n 'pulsar', // Apache Pulsar\n 'activemq', // Apache ActiveMQ\n 'custom', // Custom message queue\n]).describe('Message queue provider type');\n\nexport type MessageQueueProvider = z.infer;\n\n/**\n * Message Format\n */\nexport const MessageFormatSchema = z.enum([\n 'json',\n 'xml',\n 'protobuf',\n 'avro',\n 'text',\n 'binary',\n]).describe('Message format/serialization');\n\nexport type MessageFormat = z.infer;\n\n/**\n * Message Acknowledgment Mode\n */\nexport const AckModeSchema = z.enum([\n 'auto', // Auto-acknowledge\n 'manual', // Manual acknowledge after processing\n 'client', // Client-controlled acknowledge\n]).describe('Message acknowledgment mode');\n\nexport type AckMode = z.infer;\n\n/**\n * Delivery Guarantee\n */\nexport const DeliveryGuaranteeSchema = z.enum([\n 'at_most_once', // Fire and forget\n 'at_least_once', // May deliver duplicates\n 'exactly_once', // Guaranteed exactly once delivery\n]).describe('Message delivery guarantee');\n\nexport type DeliveryGuarantee = z.infer;\n\n/**\n * Consumer Configuration\n */\nexport const ConsumerConfigSchema = z.object({\n enabled: z.boolean().optional().default(true).describe('Enable consumer'),\n \n consumerGroup: z.string().optional().describe('Consumer group ID'),\n \n concurrency: z.number().min(1).max(100).optional().default(1).describe('Number of concurrent consumers'),\n \n prefetchCount: z.number().min(1).max(1000).optional().default(10).describe('Prefetch count'),\n \n ackMode: AckModeSchema.optional().default('manual'),\n \n autoCommit: z.boolean().optional().default(false).describe('Auto-commit offsets'),\n \n autoCommitIntervalMs: z.number().min(100).optional().default(5000).describe('Auto-commit interval in ms'),\n \n sessionTimeoutMs: z.number().min(1000).optional().default(30000).describe('Session timeout in ms'),\n \n rebalanceTimeoutMs: z.number().min(1000).optional().describe('Rebalance timeout in ms'),\n});\n\nexport type ConsumerConfig = z.infer;\n\n/**\n * Producer Configuration\n */\nexport const ProducerConfigSchema = z.object({\n enabled: z.boolean().optional().default(true).describe('Enable producer'),\n \n acks: z.enum(['0', '1', 'all']).optional().default('all').describe('Acknowledgment level'),\n \n compressionType: z.enum(['none', 'gzip', 'snappy', 'lz4', 'zstd']).optional().default('none').describe('Compression type'),\n \n batchSize: z.number().min(1).optional().default(16384).describe('Batch size in bytes'),\n \n lingerMs: z.number().min(0).optional().default(0).describe('Linger time in ms'),\n \n maxInFlightRequests: z.number().min(1).optional().default(5).describe('Max in-flight requests'),\n \n idempotence: z.boolean().optional().default(true).describe('Enable idempotent producer'),\n \n transactional: z.boolean().optional().default(false).describe('Enable transactional producer'),\n \n transactionTimeoutMs: z.number().min(1000).optional().describe('Transaction timeout in ms'),\n});\n\nexport type ProducerConfig = z.infer;\n\n/**\n * Dead Letter Queue Configuration\n */\nexport const DlqConfigSchema = z.object({\n enabled: z.boolean().optional().default(false).describe('Enable DLQ'),\n \n queueName: z.string().describe('Dead letter queue/topic name'),\n \n maxRetries: z.number().min(0).max(100).optional().default(3).describe('Max retries before DLQ'),\n \n retryDelayMs: z.number().min(0).optional().default(60000).describe('Retry delay in ms'),\n});\n\nexport type DlqConfig = z.infer;\n\n/**\n * Topic/Queue Configuration\n */\nexport const TopicQueueSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Topic/queue identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n topicName: z.string().describe('Actual topic/queue name in message queue system'),\n enabled: z.boolean().optional().default(true).describe('Enable sync for this topic/queue'),\n \n /**\n * Consumer or Producer\n */\n mode: z.enum(['consumer', 'producer', 'both']).optional().default('both').describe('Consumer, producer, or both'),\n \n /**\n * Message format\n */\n messageFormat: MessageFormatSchema.optional().default('json'),\n \n /**\n * Partition/shard configuration\n */\n partitions: z.number().min(1).optional().describe('Number of partitions (for Kafka)'),\n \n /**\n * Replication factor\n */\n replicationFactor: z.number().min(1).optional().describe('Replication factor (for Kafka)'),\n \n /**\n * Consumer configuration\n */\n consumerConfig: ConsumerConfigSchema.optional().describe('Consumer-specific configuration'),\n \n /**\n * Producer configuration\n */\n producerConfig: ProducerConfigSchema.optional().describe('Producer-specific configuration'),\n \n /**\n * Dead letter queue configuration\n */\n dlqConfig: DlqConfigSchema.optional().describe('Dead letter queue configuration'),\n \n /**\n * Message routing key (for RabbitMQ)\n */\n routingKey: z.string().optional().describe('Routing key pattern'),\n \n /**\n * Message filter\n */\n messageFilter: z.object({\n headers: z.record(z.string(), z.string()).optional().describe('Filter by message headers'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Filter by message attributes'),\n }).optional().describe('Message filter criteria'),\n});\n\nexport type TopicQueue = z.infer;\n\n/**\n * Message Queue Connector Configuration Schema\n */\nexport const MessageQueueConnectorSchema = ConnectorSchema.extend({\n type: z.literal('message_queue'),\n \n /**\n * Message queue provider\n */\n provider: MessageQueueProviderSchema.describe('Message queue provider type'),\n \n /**\n * Broker configuration\n */\n brokerConfig: z.object({\n brokers: z.array(z.string()).describe('Broker addresses (host:port)'),\n clientId: z.string().optional().describe('Client ID'),\n connectionTimeoutMs: z.number().min(1000).optional().default(30000).describe('Connection timeout in ms'),\n requestTimeoutMs: z.number().min(1000).optional().default(30000).describe('Request timeout in ms'),\n }).describe('Broker connection configuration'),\n \n /**\n * Topics/queues to sync\n */\n topics: z.array(TopicQueueSchema).describe('Topics/queues to sync'),\n \n /**\n * Delivery guarantee\n */\n deliveryGuarantee: DeliveryGuaranteeSchema.optional().default('at_least_once'),\n \n /**\n * SSL/TLS configuration\n */\n sslConfig: z.object({\n enabled: z.boolean().optional().default(false).describe('Enable SSL/TLS'),\n rejectUnauthorized: z.boolean().optional().default(true).describe('Reject unauthorized certificates'),\n ca: z.string().optional().describe('CA certificate'),\n cert: z.string().optional().describe('Client certificate'),\n key: z.string().optional().describe('Client private key'),\n }).optional().describe('SSL/TLS configuration'),\n \n /**\n * SASL authentication (for Kafka)\n */\n saslConfig: z.object({\n mechanism: z.enum(['plain', 'scram-sha-256', 'scram-sha-512', 'aws']).describe('SASL mechanism'),\n username: z.string().optional().describe('SASL username'),\n password: z.string().optional().describe('SASL password'),\n }).optional().describe('SASL authentication configuration'),\n \n /**\n * Schema registry configuration (for Kafka/Avro)\n */\n schemaRegistry: z.object({\n url: z.string().url().describe('Schema registry URL'),\n auth: z.object({\n username: z.string().optional(),\n password: z.string().optional(),\n }).optional(),\n }).optional().describe('Schema registry configuration'),\n \n /**\n * Message ordering\n */\n preserveOrder: z.boolean().optional().default(true).describe('Preserve message ordering'),\n \n /**\n * Enable metrics\n */\n enableMetrics: z.boolean().optional().default(true).describe('Enable message queue metrics'),\n \n /**\n * Enable distributed tracing\n */\n enableTracing: z.boolean().optional().default(false).describe('Enable distributed tracing'),\n});\n\nexport type MessageQueueConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Apache Kafka Connector Configuration\n */\nexport const kafkaConnectorExample = {\n name: 'kafka_production',\n label: 'Production Kafka Cluster',\n type: 'message_queue',\n provider: 'kafka',\n authentication: {\n type: 'none',\n },\n brokerConfig: {\n brokers: ['kafka-1.example.com:9092', 'kafka-2.example.com:9092', 'kafka-3.example.com:9092'],\n clientId: 'objectstack-client',\n connectionTimeoutMs: 30000,\n requestTimeoutMs: 30000,\n },\n topics: [\n {\n name: 'order_events',\n label: 'Order Events',\n topicName: 'orders',\n enabled: true,\n mode: 'consumer',\n messageFormat: 'json',\n partitions: 10,\n replicationFactor: 3,\n consumerConfig: {\n enabled: true,\n consumerGroup: 'objectstack-consumer-group',\n concurrency: 5,\n prefetchCount: 100,\n ackMode: 'manual',\n autoCommit: false,\n sessionTimeoutMs: 30000,\n },\n dlqConfig: {\n enabled: true,\n queueName: 'orders-dlq',\n maxRetries: 3,\n retryDelayMs: 60000,\n },\n },\n {\n name: 'user_activity',\n label: 'User Activity',\n topicName: 'user-activity',\n enabled: true,\n mode: 'producer',\n messageFormat: 'json',\n partitions: 5,\n replicationFactor: 3,\n producerConfig: {\n enabled: true,\n acks: 'all',\n compressionType: 'snappy',\n batchSize: 16384,\n lingerMs: 10,\n maxInFlightRequests: 5,\n idempotence: true,\n },\n },\n ],\n deliveryGuarantee: 'at_least_once',\n saslConfig: {\n mechanism: 'scram-sha-256',\n username: '${KAFKA_USERNAME}',\n password: '${KAFKA_PASSWORD}',\n },\n sslConfig: {\n enabled: true,\n rejectUnauthorized: true,\n },\n preserveOrder: true,\n enableMetrics: true,\n enableTracing: true,\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: RabbitMQ Connector Configuration\n */\nexport const rabbitmqConnectorExample = {\n name: 'rabbitmq_events',\n label: 'RabbitMQ Event Bus',\n type: 'message_queue',\n provider: 'rabbitmq',\n authentication: {\n type: 'basic',\n username: '${RABBITMQ_USERNAME}',\n password: '${RABBITMQ_PASSWORD}',\n },\n brokerConfig: {\n brokers: ['amqp://rabbitmq.example.com:5672'],\n clientId: 'objectstack-rabbitmq-client',\n },\n topics: [\n {\n name: 'notifications',\n label: 'Notifications',\n topicName: 'notifications',\n enabled: true,\n mode: 'both',\n messageFormat: 'json',\n routingKey: 'notification.*',\n consumerConfig: {\n enabled: true,\n prefetchCount: 10,\n ackMode: 'manual',\n },\n producerConfig: {\n enabled: true,\n },\n dlqConfig: {\n enabled: true,\n queueName: 'notifications-dlq',\n maxRetries: 3,\n retryDelayMs: 30000,\n },\n },\n ],\n deliveryGuarantee: 'at_least_once',\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: AWS SQS Connector Configuration\n */\nexport const sqsConnectorExample = {\n name: 'aws_sqs_queue',\n label: 'AWS SQS Queue',\n type: 'message_queue',\n provider: 'aws_sqs',\n authentication: {\n type: 'api_key',\n apiKey: '${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}',\n headerName: 'Authorization',\n },\n brokerConfig: {\n brokers: ['https://sqs.us-east-1.amazonaws.com'],\n },\n topics: [\n {\n name: 'task_queue',\n label: 'Task Queue',\n topicName: 'task-queue',\n enabled: true,\n mode: 'consumer',\n messageFormat: 'json',\n consumerConfig: {\n enabled: true,\n concurrency: 10,\n prefetchCount: 10,\n ackMode: 'manual',\n },\n dlqConfig: {\n enabled: true,\n queueName: 'task-queue-dlq',\n maxRetries: 3,\n retryDelayMs: 120000,\n },\n },\n ],\n deliveryGuarantee: 'at_least_once',\n retryConfig: {\n strategy: 'exponential_backoff',\n maxAttempts: 3,\n initialDelayMs: 1000,\n maxDelayMs: 60000,\n backoffMultiplier: 2,\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Google Cloud Pub/Sub Connector Configuration\n */\nexport const pubsubConnectorExample = {\n name: 'gcp_pubsub',\n label: 'Google Cloud Pub/Sub',\n type: 'message_queue',\n provider: 'google_pubsub',\n authentication: {\n type: 'oauth2',\n clientId: '${GCP_CLIENT_ID}',\n clientSecret: '${GCP_CLIENT_SECRET}',\n authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n tokenUrl: 'https://oauth2.googleapis.com/token',\n grantType: 'client_credentials',\n scopes: ['https://www.googleapis.com/auth/pubsub'],\n },\n brokerConfig: {\n brokers: ['pubsub.googleapis.com'],\n },\n topics: [\n {\n name: 'analytics_events',\n label: 'Analytics Events',\n topicName: 'projects/my-project/topics/analytics-events',\n enabled: true,\n mode: 'both',\n messageFormat: 'json',\n consumerConfig: {\n enabled: true,\n consumerGroup: 'objectstack-subscription',\n concurrency: 5,\n prefetchCount: 100,\n ackMode: 'manual',\n },\n },\n ],\n deliveryGuarantee: 'at_least_once',\n enableMetrics: true,\n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n} from '../connector.zod';\n\n/**\n * GitHub Connector Protocol\n * \n * Specialized connector for GitHub integration enabling automated\n * version control operations, CI/CD workflows, and release management.\n * \n * Use Cases:\n * - Automated code commits and pull requests\n * - GitHub Actions workflow management\n * - Issue and project tracking\n * - Release and tag management\n * - Repository administration\n * \n * @example\n * ```typescript\n * import { GitHubConnector } from '@objectstack/spec/integration';\n * \n * const githubConnector: GitHubConnector = {\n * name: 'github_enterprise',\n * label: 'GitHub Enterprise',\n * type: 'saas',\n * provider: 'github',\n * baseUrl: 'https://api.github.com',\n * authentication: {\n * type: 'oauth2',\n * clientId: '${GITHUB_CLIENT_ID}',\n * clientSecret: '${GITHUB_CLIENT_SECRET}',\n * authorizationUrl: 'https://github.com/login/oauth/authorize',\n * tokenUrl: 'https://github.com/login/oauth/access_token',\n * grantType: 'authorization_code',\n * scopes: ['repo', 'workflow', 'admin:org'],\n * },\n * repositories: [\n * {\n * owner: 'objectstack-ai',\n * name: 'spec',\n * defaultBranch: 'main',\n * autoMerge: false,\n * },\n * ],\n * };\n * ```\n */\n\n/**\n * GitHub Provider Type\n */\nexport const GitHubProviderSchema = z.enum([\n 'github', // GitHub.com\n 'github_enterprise', // GitHub Enterprise Server\n]).describe('GitHub provider type');\n\nexport type GitHubProvider = z.infer;\n\n/**\n * GitHub Repository Configuration\n * Defines a repository to integrate with\n */\nexport const GitHubRepositorySchema = z.object({\n /**\n * Repository owner (organization or user)\n */\n owner: z.string().describe('Repository owner (organization or username)'),\n \n /**\n * Repository name\n */\n name: z.string().describe('Repository name'),\n \n /**\n * Default branch name\n */\n defaultBranch: z.string().optional().default('main').describe('Default branch name'),\n \n /**\n * Enable auto-merge for PRs\n */\n autoMerge: z.boolean().optional().default(false).describe('Enable auto-merge for pull requests'),\n \n /**\n * Branch protection rules\n */\n branchProtection: z.object({\n requiredReviewers: z.number().int().min(0).optional().default(1).describe('Required number of reviewers'),\n requireStatusChecks: z.boolean().optional().default(true).describe('Require status checks to pass'),\n enforceAdmins: z.boolean().optional().default(false).describe('Enforce protections for admins'),\n allowForcePushes: z.boolean().optional().default(false).describe('Allow force pushes'),\n allowDeletions: z.boolean().optional().default(false).describe('Allow branch deletions'),\n }).optional().describe('Branch protection configuration'),\n \n /**\n * Repository topics/tags\n */\n topics: z.array(z.string()).optional().describe('Repository topics'),\n});\n\nexport type GitHubRepository = z.infer;\n\n/**\n * GitHub Commit Configuration\n */\nexport const GitHubCommitConfigSchema = z.object({\n /**\n * Commit author name\n */\n authorName: z.string().optional().describe('Commit author name'),\n \n /**\n * Commit author email\n */\n authorEmail: z.string().email().optional().describe('Commit author email'),\n \n /**\n * GPG sign commits\n */\n signCommits: z.boolean().optional().default(false).describe('Sign commits with GPG'),\n \n /**\n * Commit message template\n */\n messageTemplate: z.string().optional().describe('Commit message template'),\n \n /**\n * Conventional commits format\n */\n useConventionalCommits: z.boolean().optional().default(true).describe('Use conventional commits format'),\n});\n\nexport type GitHubCommitConfig = z.infer;\n\n/**\n * GitHub Pull Request Configuration\n */\nexport const GitHubPullRequestConfigSchema = z.object({\n /**\n * Default PR title template\n */\n titleTemplate: z.string().optional().describe('PR title template'),\n \n /**\n * Default PR body template\n */\n bodyTemplate: z.string().optional().describe('PR body template'),\n \n /**\n * Default reviewers\n */\n defaultReviewers: z.array(z.string()).optional().describe('Default reviewers (usernames)'),\n \n /**\n * Default assignees\n */\n defaultAssignees: z.array(z.string()).optional().describe('Default assignees (usernames)'),\n \n /**\n * Default labels\n */\n defaultLabels: z.array(z.string()).optional().describe('Default labels'),\n \n /**\n * Enable draft PRs by default\n */\n draftByDefault: z.boolean().optional().default(false).describe('Create draft PRs by default'),\n \n /**\n * Auto-delete head branch after merge\n */\n deleteHeadBranch: z.boolean().optional().default(true).describe('Delete head branch after merge'),\n});\n\nexport type GitHubPullRequestConfig = z.infer;\n\n/**\n * GitHub Actions Workflow Configuration\n */\nexport const GitHubActionsWorkflowSchema = z.object({\n /**\n * Workflow name\n */\n name: z.string().describe('Workflow name'),\n \n /**\n * Workflow file path\n */\n path: z.string().describe('Workflow file path (e.g., .github/workflows/ci.yml)'),\n \n /**\n * Enable workflow\n */\n enabled: z.boolean().optional().default(true).describe('Enable workflow'),\n \n /**\n * Workflow triggers\n */\n triggers: z.array(z.enum([\n 'push',\n 'pull_request',\n 'release',\n 'schedule',\n 'workflow_dispatch',\n 'repository_dispatch',\n ])).optional().describe('Workflow triggers'),\n \n /**\n * Environment variables\n */\n env: z.record(z.string(), z.string()).optional().describe('Environment variables'),\n \n /**\n * Secrets required\n */\n secrets: z.array(z.string()).optional().describe('Required secrets'),\n});\n\nexport type GitHubActionsWorkflow = z.infer;\n\n/**\n * GitHub Release Configuration\n */\nexport const GitHubReleaseConfigSchema = z.object({\n /**\n * Tag name pattern\n */\n tagPattern: z.string().optional().default('v*').describe('Tag name pattern (e.g., v*, release/*)'),\n \n /**\n * Use semantic versioning\n */\n semanticVersioning: z.boolean().optional().default(true).describe('Use semantic versioning'),\n \n /**\n * Generate release notes automatically\n */\n autoReleaseNotes: z.boolean().optional().default(true).describe('Generate release notes automatically'),\n \n /**\n * Release name template\n */\n releaseNameTemplate: z.string().optional().describe('Release name template'),\n \n /**\n * Pre-release pattern\n */\n preReleasePattern: z.string().optional().describe('Pre-release pattern (e.g., *-alpha, *-beta)'),\n \n /**\n * Create draft releases\n */\n draftByDefault: z.boolean().optional().default(false).describe('Create draft releases by default'),\n});\n\nexport type GitHubReleaseConfig = z.infer;\n\n/**\n * GitHub Issue Tracking Configuration\n */\nexport const GitHubIssueTrackingSchema = z.object({\n /**\n * Enable issue tracking\n */\n enabled: z.boolean().optional().default(true).describe('Enable issue tracking'),\n \n /**\n * Default issue labels\n */\n defaultLabels: z.array(z.string()).optional().describe('Default issue labels'),\n \n /**\n * Issue template paths\n */\n templatePaths: z.array(z.string()).optional().describe('Issue template paths'),\n \n /**\n * Auto-assign issues\n */\n autoAssign: z.boolean().optional().default(false).describe('Auto-assign issues'),\n \n /**\n * Auto-close stale issues\n */\n autoCloseStale: z.object({\n enabled: z.boolean().default(false),\n daysBeforeStale: z.number().int().min(1).optional().default(60),\n daysBeforeClose: z.number().int().min(1).optional().default(7),\n staleLabel: z.string().optional().default('stale'),\n }).optional().describe('Auto-close stale issues configuration'),\n});\n\nexport type GitHubIssueTracking = z.infer;\n\n/**\n * GitHub Connector Schema\n * Complete GitHub integration configuration\n */\nexport const GitHubConnectorSchema = ConnectorSchema.extend({\n type: z.literal('saas'),\n \n /**\n * GitHub provider type\n */\n provider: GitHubProviderSchema.describe('GitHub provider'),\n \n /**\n * GitHub API base URL\n */\n baseUrl: z.string().url().optional().default('https://api.github.com').describe('GitHub API base URL'),\n \n /**\n * Repositories to integrate\n */\n repositories: z.array(GitHubRepositorySchema).describe('Repositories to manage'),\n \n /**\n * Commit configuration\n */\n commitConfig: GitHubCommitConfigSchema.optional().describe('Commit configuration'),\n \n /**\n * Pull request configuration\n */\n pullRequestConfig: GitHubPullRequestConfigSchema.optional().describe('Pull request configuration'),\n \n /**\n * GitHub Actions workflows\n */\n workflows: z.array(GitHubActionsWorkflowSchema).optional().describe('GitHub Actions workflows'),\n \n /**\n * Release configuration\n */\n releaseConfig: GitHubReleaseConfigSchema.optional().describe('Release configuration'),\n \n /**\n * Issue tracking configuration\n */\n issueTracking: GitHubIssueTrackingSchema.optional().describe('Issue tracking configuration'),\n \n /**\n * Enable webhooks\n */\n enableWebhooks: z.boolean().optional().default(true).describe('Enable GitHub webhooks'),\n \n /**\n * Webhook events to subscribe\n */\n webhookEvents: z.array(z.enum([\n 'push',\n 'pull_request',\n 'issues',\n 'issue_comment',\n 'release',\n 'workflow_run',\n 'deployment',\n 'deployment_status',\n 'check_run',\n 'check_suite',\n 'status',\n ])).optional().describe('Webhook events to subscribe to'),\n});\n\nexport type GitHubConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: GitHub.com Connector Configuration\n */\nexport const githubPublicConnectorExample = {\n name: 'github_public',\n label: 'GitHub.com',\n type: 'saas',\n provider: 'github',\n baseUrl: 'https://api.github.com',\n \n authentication: {\n type: 'oauth2',\n clientId: '${GITHUB_CLIENT_ID}',\n clientSecret: '${GITHUB_CLIENT_SECRET}',\n authorizationUrl: 'https://github.com/login/oauth/authorize',\n tokenUrl: 'https://github.com/login/oauth/access_token',\n scopes: ['repo', 'workflow', 'write:packages'],\n },\n \n repositories: [\n {\n owner: 'objectstack-ai',\n name: 'spec',\n defaultBranch: 'main',\n autoMerge: false,\n branchProtection: {\n requiredReviewers: 1,\n requireStatusChecks: true,\n enforceAdmins: false,\n allowForcePushes: false,\n allowDeletions: false,\n },\n topics: ['objectstack', 'low-code', 'metadata-driven'],\n },\n ],\n \n commitConfig: {\n authorName: 'ObjectStack Bot',\n authorEmail: 'bot@objectstack.ai',\n signCommits: false,\n useConventionalCommits: true,\n },\n \n pullRequestConfig: {\n titleTemplate: '{{type}}: {{description}}',\n defaultReviewers: ['team-lead'],\n defaultLabels: ['automated', 'ai-generated'],\n draftByDefault: false,\n deleteHeadBranch: true,\n },\n \n workflows: [\n {\n name: 'CI',\n path: '.github/workflows/ci.yml',\n enabled: true,\n triggers: ['push', 'pull_request'],\n },\n {\n name: 'Release',\n path: '.github/workflows/release.yml',\n enabled: true,\n triggers: ['release'],\n },\n ],\n \n releaseConfig: {\n tagPattern: 'v*',\n semanticVersioning: true,\n autoReleaseNotes: true,\n releaseNameTemplate: 'Release {{version}}',\n draftByDefault: false,\n },\n \n issueTracking: {\n enabled: true,\n defaultLabels: ['needs-triage'],\n autoAssign: false,\n autoCloseStale: {\n enabled: true,\n daysBeforeStale: 60,\n daysBeforeClose: 7,\n staleLabel: 'stale',\n },\n },\n \n enableWebhooks: true,\n webhookEvents: ['push', 'pull_request', 'release', 'workflow_run'],\n \n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: GitHub Enterprise Connector Configuration\n */\nexport const githubEnterpriseConnectorExample = {\n name: 'github_enterprise',\n label: 'GitHub Enterprise',\n type: 'saas',\n provider: 'github_enterprise',\n baseUrl: 'https://github.enterprise.com/api/v3',\n \n authentication: {\n type: 'oauth2',\n clientId: '${GITHUB_ENTERPRISE_CLIENT_ID}',\n clientSecret: '${GITHUB_ENTERPRISE_CLIENT_SECRET}',\n authorizationUrl: 'https://github.enterprise.com/login/oauth/authorize',\n tokenUrl: 'https://github.enterprise.com/login/oauth/access_token',\n scopes: ['repo', 'admin:org', 'workflow'],\n },\n \n repositories: [\n {\n owner: 'enterprise-org',\n name: 'internal-app',\n defaultBranch: 'develop',\n autoMerge: true,\n branchProtection: {\n requiredReviewers: 2,\n requireStatusChecks: true,\n enforceAdmins: true,\n allowForcePushes: false,\n allowDeletions: false,\n },\n },\n ],\n \n commitConfig: {\n authorName: 'CI Bot',\n authorEmail: 'ci-bot@enterprise.com',\n signCommits: true,\n useConventionalCommits: true,\n },\n \n pullRequestConfig: {\n titleTemplate: '[{{branch}}] {{description}}',\n bodyTemplate: `## Changes\\n\\n{{changes}}\\n\\n## Testing\\n\\n{{testing}}`,\n defaultReviewers: ['tech-lead', 'security-team'],\n defaultLabels: ['automated'],\n draftByDefault: true,\n deleteHeadBranch: true,\n },\n \n releaseConfig: {\n tagPattern: 'release/*',\n semanticVersioning: true,\n autoReleaseNotes: true,\n preReleasePattern: '*-rc*',\n draftByDefault: true,\n },\n \n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n} from '../connector.zod';\n\n/**\n * Vercel Connector Protocol\n * \n * Specialized connector for Vercel deployment platform enabling automated\n * deployments, preview environments, and production releases.\n * \n * Use Cases:\n * - Automated deployments from Git\n * - Preview deployments for pull requests\n * - Production releases\n * - Environment variable management\n * - Domain and SSL configuration\n * - Edge function deployment\n * \n * @example\n * ```typescript\n * import { VercelConnector } from '@objectstack/spec/integration';\n * \n * const vercelConnector: VercelConnector = {\n * name: 'vercel_production',\n * label: 'Vercel Production',\n * type: 'saas',\n * provider: 'vercel',\n * baseUrl: 'https://api.vercel.com',\n * authentication: {\n * type: 'bearer',\n * token: '${VERCEL_TOKEN}',\n * },\n * projects: [\n * {\n * name: 'objectstack-app',\n * framework: 'nextjs',\n * gitRepository: {\n * type: 'github',\n * repo: 'objectstack-ai/app',\n * },\n * },\n * ],\n * };\n * ```\n */\n\n/**\n * Vercel Provider Type\n */\nexport const VercelProviderSchema = z.enum([\n 'vercel',\n]).describe('Vercel provider type');\n\nexport type VercelProvider = z.infer;\n\n/**\n * Vercel Framework Types\n */\nexport const VercelFrameworkSchema = z.enum([\n 'nextjs',\n 'react',\n 'vue',\n 'nuxtjs',\n 'gatsby',\n 'remix',\n 'astro',\n 'sveltekit',\n 'solid',\n 'angular',\n 'static',\n 'other',\n]).describe('Frontend framework');\n\nexport type VercelFramework = z.infer;\n\n/**\n * Git Repository Configuration\n */\nexport const GitRepositoryConfigSchema = z.object({\n /**\n * Git provider type\n */\n type: z.enum(['github', 'gitlab', 'bitbucket']).describe('Git provider'),\n \n /**\n * Repository identifier (owner/repo)\n */\n repo: z.string().describe('Repository identifier (e.g., owner/repo)'),\n \n /**\n * Production branch\n */\n productionBranch: z.string().optional().default('main').describe('Production branch name'),\n \n /**\n * Auto-deploy production branch\n */\n autoDeployProduction: z.boolean().optional().default(true).describe('Auto-deploy production branch'),\n \n /**\n * Auto-deploy preview branches\n */\n autoDeployPreview: z.boolean().optional().default(true).describe('Auto-deploy preview branches'),\n});\n\nexport type GitRepositoryConfig = z.infer;\n\n/**\n * Build Configuration\n */\nexport const BuildConfigSchema = z.object({\n /**\n * Build command\n */\n buildCommand: z.string().optional().describe('Build command (e.g., npm run build)'),\n \n /**\n * Output directory\n */\n outputDirectory: z.string().optional().describe('Output directory (e.g., .next, dist)'),\n \n /**\n * Install command\n */\n installCommand: z.string().optional().describe('Install command (e.g., npm install, pnpm install)'),\n \n /**\n * Development command\n */\n devCommand: z.string().optional().describe('Development command (e.g., npm run dev)'),\n \n /**\n * Node.js version\n */\n nodeVersion: z.string().optional().describe('Node.js version (e.g., 18.x, 20.x)'),\n \n /**\n * Environment variables\n */\n env: z.record(z.string(), z.string()).optional().describe('Build environment variables'),\n});\n\nexport type BuildConfig = z.infer;\n\n/**\n * Deployment Configuration\n */\nexport const DeploymentConfigSchema = z.object({\n /**\n * Enable automatic deployments\n */\n autoDeployment: z.boolean().optional().default(true).describe('Enable automatic deployments'),\n \n /**\n * Deployment regions\n */\n regions: z.array(z.enum([\n 'iad1', // US East (Washington, D.C.)\n 'sfo1', // US West (San Francisco)\n 'gru1', // South America (São Paulo)\n 'lhr1', // Europe West (London)\n 'fra1', // Europe Central (Frankfurt)\n 'sin1', // Asia (Singapore)\n 'syd1', // Australia (Sydney)\n 'hnd1', // Asia (Tokyo)\n 'icn1', // Asia (Seoul)\n ])).optional().describe('Deployment regions'),\n \n /**\n * Enable preview deployments\n */\n enablePreview: z.boolean().optional().default(true).describe('Enable preview deployments'),\n \n /**\n * Preview deployment comments on PRs\n */\n previewComments: z.boolean().optional().default(true).describe('Post preview URLs in PR comments'),\n \n /**\n * Production deployment protection\n */\n productionProtection: z.boolean().optional().default(true).describe('Require approval for production deployments'),\n \n /**\n * Deploy hooks\n */\n deployHooks: z.array(z.object({\n name: z.string().describe('Hook name'),\n url: z.string().url().describe('Deploy hook URL'),\n branch: z.string().optional().describe('Target branch'),\n })).optional().describe('Deploy hooks'),\n});\n\nexport type DeploymentConfig = z.infer;\n\n/**\n * Domain Configuration\n */\nexport const DomainConfigSchema = z.object({\n /**\n * Domain name\n */\n domain: z.string().describe('Domain name (e.g., app.example.com)'),\n \n /**\n * Enable HTTPS redirect\n */\n httpsRedirect: z.boolean().optional().default(true).describe('Redirect HTTP to HTTPS'),\n \n /**\n * Custom SSL certificate\n */\n customCertificate: z.object({\n cert: z.string().describe('SSL certificate'),\n key: z.string().describe('Private key'),\n ca: z.string().optional().describe('Certificate authority'),\n }).optional().describe('Custom SSL certificate'),\n \n /**\n * Git branch for this domain\n */\n gitBranch: z.string().optional().describe('Git branch to deploy to this domain'),\n});\n\nexport type DomainConfig = z.infer;\n\n/**\n * Environment Variables Configuration\n */\nexport const EnvironmentVariablesSchema = z.object({\n /**\n * Variable name\n */\n key: z.string().describe('Environment variable name'),\n \n /**\n * Variable value\n */\n value: z.string().describe('Environment variable value'),\n \n /**\n * Target environments\n */\n target: z.array(z.enum(['production', 'preview', 'development'])).describe('Target environments'),\n \n /**\n * Is secret (encrypted)\n */\n isSecret: z.boolean().optional().default(false).describe('Encrypt this variable'),\n \n /**\n * Git branch (for preview/development)\n */\n gitBranch: z.string().optional().describe('Specific git branch'),\n});\n\nexport type EnvironmentVariables = z.infer;\n\n/**\n * Edge Function Configuration\n */\nexport const EdgeFunctionConfigSchema = z.object({\n /**\n * Function name\n */\n name: z.string().describe('Edge function name'),\n \n /**\n * Function path\n */\n path: z.string().describe('Function path (e.g., /api/*)'),\n \n /**\n * Regions to deploy\n */\n regions: z.array(z.string()).optional().describe('Specific regions for this function'),\n \n /**\n * Memory limit (MB)\n */\n memoryLimit: z.number().int().min(128).max(3008).optional().default(1024).describe('Memory limit in MB'),\n \n /**\n * Timeout (seconds)\n */\n timeout: z.number().int().min(1).max(300).optional().default(10).describe('Timeout in seconds'),\n});\n\nexport type EdgeFunctionConfig = z.infer;\n\n/**\n * Vercel Project Configuration\n */\nexport const VercelProjectSchema = z.object({\n /**\n * Project name\n */\n name: z.string().describe('Vercel project name'),\n \n /**\n * Framework\n */\n framework: VercelFrameworkSchema.optional().describe('Frontend framework'),\n \n /**\n * Git repository\n */\n gitRepository: GitRepositoryConfigSchema.optional().describe('Git repository configuration'),\n \n /**\n * Build configuration\n */\n buildConfig: BuildConfigSchema.optional().describe('Build configuration'),\n \n /**\n * Deployment configuration\n */\n deploymentConfig: DeploymentConfigSchema.optional().describe('Deployment configuration'),\n \n /**\n * Custom domains\n */\n domains: z.array(DomainConfigSchema).optional().describe('Custom domains'),\n \n /**\n * Environment variables\n */\n environmentVariables: z.array(EnvironmentVariablesSchema).optional().describe('Environment variables'),\n \n /**\n * Edge functions\n */\n edgeFunctions: z.array(EdgeFunctionConfigSchema).optional().describe('Edge functions'),\n \n /**\n * Root directory\n */\n rootDirectory: z.string().optional().describe('Root directory (for monorepos)'),\n});\n\nexport type VercelProject = z.infer;\n\n/**\n * Vercel Monitoring Configuration\n */\nexport const VercelMonitoringSchema = z.object({\n /**\n * Enable Web Analytics\n */\n enableWebAnalytics: z.boolean().optional().default(false).describe('Enable Vercel Web Analytics'),\n \n /**\n * Enable Speed Insights\n */\n enableSpeedInsights: z.boolean().optional().default(false).describe('Enable Vercel Speed Insights'),\n \n /**\n * Enable Log Drains\n */\n logDrains: z.array(z.object({\n name: z.string().describe('Log drain name'),\n url: z.string().url().describe('Log drain URL'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers'),\n sources: z.array(z.enum(['static', 'lambda', 'edge'])).optional().describe('Log sources'),\n })).optional().describe('Log drains configuration'),\n});\n\nexport type VercelMonitoring = z.infer;\n\n/**\n * Vercel Team Configuration\n */\nexport const VercelTeamSchema = z.object({\n /**\n * Team ID or slug\n */\n teamId: z.string().optional().describe('Team ID or slug'),\n \n /**\n * Team name\n */\n teamName: z.string().optional().describe('Team name'),\n});\n\nexport type VercelTeam = z.infer;\n\n/**\n * Vercel Connector Schema\n * Complete Vercel integration configuration\n */\nexport const VercelConnectorSchema = ConnectorSchema.extend({\n type: z.literal('saas'),\n \n /**\n * Vercel provider\n */\n provider: VercelProviderSchema.describe('Vercel provider'),\n \n /**\n * Vercel API base URL\n */\n baseUrl: z.string().url().optional().default('https://api.vercel.com').describe('Vercel API base URL'),\n \n /**\n * Team configuration\n */\n team: VercelTeamSchema.optional().describe('Vercel team configuration'),\n \n /**\n * Projects to manage\n */\n projects: z.array(VercelProjectSchema).describe('Vercel projects'),\n \n /**\n * Monitoring configuration\n */\n monitoring: VercelMonitoringSchema.optional().describe('Monitoring configuration'),\n \n /**\n * Enable webhooks\n */\n enableWebhooks: z.boolean().optional().default(true).describe('Enable Vercel webhooks'),\n \n /**\n * Webhook events to subscribe\n */\n webhookEvents: z.array(z.enum([\n 'deployment.created',\n 'deployment.succeeded',\n 'deployment.failed',\n 'deployment.ready',\n 'deployment.error',\n 'deployment.canceled',\n 'deployment-checks-completed',\n 'deployment-prepared',\n 'project.created',\n 'project.removed',\n ])).optional().describe('Webhook events to subscribe to'),\n});\n\nexport type VercelConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Vercel Next.js Project Configuration\n */\nexport const vercelNextJsConnectorExample = {\n name: 'vercel_production',\n label: 'Vercel Production',\n type: 'saas',\n provider: 'vercel',\n baseUrl: 'https://api.vercel.com',\n \n authentication: {\n type: 'bearer',\n token: '${VERCEL_TOKEN}',\n },\n \n projects: [\n {\n name: 'objectstack-app',\n framework: 'nextjs',\n \n gitRepository: {\n type: 'github',\n repo: 'objectstack-ai/app',\n productionBranch: 'main',\n autoDeployProduction: true,\n autoDeployPreview: true,\n },\n \n buildConfig: {\n buildCommand: 'npm run build',\n outputDirectory: '.next',\n installCommand: 'npm ci',\n devCommand: 'npm run dev',\n nodeVersion: '20.x',\n env: {\n NEXT_PUBLIC_API_URL: 'https://api.objectstack.ai',\n },\n },\n \n deploymentConfig: {\n autoDeployment: true,\n regions: ['iad1', 'sfo1', 'fra1'],\n enablePreview: true,\n previewComments: true,\n productionProtection: true,\n },\n \n domains: [\n {\n domain: 'app.objectstack.ai',\n httpsRedirect: true,\n gitBranch: 'main',\n },\n {\n domain: 'staging.objectstack.ai',\n httpsRedirect: true,\n gitBranch: 'develop',\n },\n ],\n \n environmentVariables: [\n {\n key: 'DATABASE_URL',\n value: '${DATABASE_URL}',\n target: ['production', 'preview'],\n isSecret: true,\n },\n {\n key: 'NEXT_PUBLIC_ANALYTICS_ID',\n value: 'UA-XXXXXXXX-X',\n target: ['production'],\n isSecret: false,\n },\n ],\n \n edgeFunctions: [\n {\n name: 'api-middleware',\n path: '/api/*',\n regions: ['iad1', 'sfo1'],\n memoryLimit: 1024,\n timeout: 10,\n },\n ],\n },\n ],\n \n monitoring: {\n enableWebAnalytics: true,\n enableSpeedInsights: true,\n logDrains: [\n {\n name: 'datadog-logs',\n url: 'https://http-intake.logs.datadoghq.com/api/v2/logs',\n headers: {\n 'DD-API-KEY': '${DATADOG_API_KEY}',\n },\n sources: ['lambda', 'edge'],\n },\n ],\n },\n \n enableWebhooks: true,\n webhookEvents: [\n 'deployment.succeeded',\n 'deployment.failed',\n 'deployment.ready',\n ],\n \n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Vercel Static Site Configuration\n */\nexport const vercelStaticSiteConnectorExample = {\n name: 'vercel_docs',\n label: 'Vercel Documentation',\n type: 'saas',\n provider: 'vercel',\n baseUrl: 'https://api.vercel.com',\n \n authentication: {\n type: 'bearer',\n token: '${VERCEL_TOKEN}',\n },\n \n team: {\n teamId: 'team_xxxxxx',\n teamName: 'ObjectStack',\n },\n \n projects: [\n {\n name: 'objectstack-docs',\n framework: 'static',\n \n gitRepository: {\n type: 'github',\n repo: 'objectstack-ai/docs',\n productionBranch: 'main',\n autoDeployProduction: true,\n autoDeployPreview: true,\n },\n \n buildConfig: {\n buildCommand: 'npm run build',\n outputDirectory: 'dist',\n installCommand: 'npm ci',\n nodeVersion: '18.x',\n },\n \n deploymentConfig: {\n autoDeployment: true,\n regions: ['iad1', 'lhr1', 'sin1'],\n enablePreview: true,\n previewComments: true,\n productionProtection: false,\n },\n \n domains: [\n {\n domain: 'docs.objectstack.ai',\n httpsRedirect: true,\n },\n ],\n \n environmentVariables: [\n {\n key: 'ALGOLIA_APP_ID',\n value: '${ALGOLIA_APP_ID}',\n target: ['production', 'preview'],\n isSecret: false,\n },\n {\n key: 'ALGOLIA_API_KEY',\n value: '${ALGOLIA_API_KEY}',\n target: ['production', 'preview'],\n isSecret: true,\n },\n ],\n },\n ],\n \n monitoring: {\n enableWebAnalytics: true,\n enableSpeedInsights: false,\n },\n \n enableWebhooks: false,\n \n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * ObjectStack Contracts\n * \n * Core interface definitions following \"Protocol First\" principle.\n * All interfaces should be defined in @objectstack/spec to avoid circular dependencies.\n */\n\nexport * from './logger.js';\nexport * from './data-engine.js';\nexport * from './data-driver.js';\nexport * from './http-server.js';\nexport * from './service-registry.js';\nexport * from './plugin-validator.js';\nexport * from './startup-orchestrator.js';\nexport * from './plugin-lifecycle-events.js';\nexport * from './schema-driver.js';\nexport * from './cache-service.js';\nexport * from './search-service.js';\nexport * from './queue-service.js';\nexport * from './notification-service.js';\nexport * from './storage-service.js';\nexport * from './metadata-service.js';\nexport * from './auth-service.js';\nexport * from './automation-service.js';\nexport * from './graphql-service.js';\nexport * from './analytics-service.js';\nexport * from './realtime-service.js';\nexport * from './job-service.js';\nexport * from './ai-service.js';\nexport * from './llm-adapter.js';\nexport * from './i18n-service.js';\nexport * from './ui-service.js';\nexport * from './workflow-service.js';\nexport * from './feed-service.js';\nexport * from './export-service.js';\nexport * from './package-service.js';\n\n// Provisioning & Deployment\nexport * from './turso-platform.js';\nexport * from './provisioning-service.js';\nexport * from './schema-diff-service.js';\nexport * from './deploy-pipeline-service.js';\nexport * from './tenant-router.js';\nexport * from './app-lifecycle-service.js';\nexport * from './seed-loader-service.js';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio\n * \n * Studio Protocol — Plugin system for ObjectStack Studio\n * \n * Defines the extension model that allows metadata types to contribute\n * custom viewers, designers, sidebar groups, actions, and commands.\n * Also includes the Object Designer protocol for visual field editing,\n * relationship mapping, and ER diagram configuration.\n */\n\nexport {\n // Schemas\n ViewModeSchema,\n MetadataViewerContributionSchema,\n SidebarGroupContributionSchema,\n ActionContributionSchema,\n ActionLocationSchema,\n MetadataIconContributionSchema,\n PanelContributionSchema,\n PanelLocationSchema,\n CommandContributionSchema,\n StudioPluginContributionsSchema,\n ActivationEventSchema,\n StudioPluginManifestSchema,\n\n // Types\n type ViewMode,\n type MetadataViewerContribution,\n type SidebarGroupContribution,\n type ActionContribution,\n type MetadataIconContribution,\n type PanelContribution,\n type CommandContribution,\n type StudioPluginContributions,\n type StudioPluginManifest,\n\n // Helpers\n defineStudioPlugin,\n} from './plugin.zod';\n\nexport {\n // Object Designer Schemas\n FieldPropertySectionSchema,\n FieldGroupSchema,\n FieldEditorConfigSchema,\n RelationshipDisplaySchema,\n RelationshipMapperConfigSchema,\n ERLayoutAlgorithmSchema,\n ERNodeDisplaySchema,\n ERDiagramConfigSchema,\n ObjectListDisplayModeSchema,\n ObjectSortFieldSchema,\n ObjectFilterSchema,\n ObjectManagerConfigSchema,\n ObjectPreviewTabSchema,\n ObjectPreviewConfigSchema,\n ObjectDesignerDefaultViewSchema,\n ObjectDesignerConfigSchema,\n\n // Object Designer Types\n type FieldPropertySection,\n type FieldGroup,\n type FieldEditorConfig,\n type RelationshipDisplay,\n type RelationshipMapperConfig,\n type ERLayoutAlgorithm,\n type ERNodeDisplay,\n type ERDiagramConfig,\n type ObjectListDisplayMode,\n type ObjectSortField,\n type ObjectFilter,\n type ObjectManagerConfig,\n type ObjectPreviewTab,\n type ObjectPreviewConfig,\n type ObjectDesignerDefaultView,\n type ObjectDesignerConfig,\n\n // Object Designer Helpers\n defineObjectDesignerConfig,\n} from './object-designer.zod';\n\nexport {\n // Page Builder Schemas\n CanvasSnapSettingsSchema,\n CanvasZoomSettingsSchema,\n ElementPaletteItemSchema,\n PageBuilderConfigSchema,\n /** @deprecated Use PageBuilderConfigSchema instead */\n InterfaceBuilderConfigSchema,\n\n // Page Builder Types\n type CanvasSnapSettings,\n type CanvasZoomSettings,\n type ElementPaletteItem,\n type PageBuilderConfig,\n /** @deprecated Use PageBuilderConfig instead */\n type InterfaceBuilderConfig,\n} from './page-builder.zod';\n\nexport {\n // Flow Builder Schemas\n FlowNodeShapeSchema,\n FlowNodeRenderDescriptorSchema,\n FlowCanvasNodeSchema,\n FlowCanvasEdgeStyleSchema,\n FlowCanvasEdgeSchema,\n FlowLayoutAlgorithmSchema,\n FlowLayoutDirectionSchema,\n FlowBuilderConfigSchema,\n BUILT_IN_NODE_DESCRIPTORS,\n\n // Flow Builder Types\n type FlowNodeShape,\n type FlowNodeRenderDescriptor,\n type FlowCanvasNode,\n type FlowCanvasEdgeStyle,\n type FlowCanvasEdge,\n type FlowLayoutAlgorithm,\n type FlowLayoutDirection,\n type FlowBuilderConfig,\n\n // Flow Builder Helpers\n defineFlowBuilderConfig,\n} from './flow-builder.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio/plugin\n * \n * Studio Plugin Protocol\n * \n * Defines the specification for Studio plugins — a VS Code-like extension model\n * that allows each metadata type to contribute custom viewers, designers, \n * sidebar groups, actions, and commands.\n * \n * ## Architecture\n * \n * Like VS Code extensions, Studio plugins have two layers:\n * 1. **Manifest (Declarative)** — JSON-serializable contribution points\n * 2. **Activation (Imperative)** — Runtime registration of React components & handlers\n * \n * ```\n * ┌─────────────────────────────────────────────────────────┐\n * │ Studio Host │\n * │ ┌───────────────────────────────────────────────────┐ │\n * │ │ Plugin Registry │ │\n * │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │\n * │ │ │ Object │ │ Flow │ │ Agent │ ... │ │\n * │ │ │ Plugin │ │ Plugin │ │ Plugin │ │ │\n * │ │ └──────────┘ └──────────┘ └──────────┘ │ │\n * │ └───────────────────────────────────────────────────┘ │\n * │ │\n * │ ┌─── Sidebar ───┐ ┌──── Main Panel ────────────────┐ │\n * │ │ [plugin icons] │ │ PluginHost renders viewer │ │\n * │ │ [plugin groups]│ │ from highest-priority plugin │ │\n * │ └────────────────┘ └────────────────────────────────┘ │\n * └─────────────────────────────────────────────────────────┘\n * ```\n * \n * @example\n * ```typescript\n * import { StudioPluginManifestSchema } from '@objectstack/spec/studio';\n * \n * const manifest = StudioPluginManifestSchema.parse({\n * id: 'objectstack.object-designer',\n * name: 'Object Designer',\n * version: '1.0.0',\n * contributes: {\n * metadataViewers: [{\n * id: 'object-explorer',\n * metadataTypes: ['object', 'objects'],\n * label: 'Object Explorer',\n * priority: 100,\n * modes: ['preview', 'design', 'data'],\n * }],\n * },\n * });\n * ```\n */\n\nimport { z } from 'zod';\n\n// ─── View Mode ───────────────────────────────────────────────────────\n\n/** Supported view modes for metadata viewers */\nexport const ViewModeSchema = z.enum(['preview', 'design', 'code', 'data']);\nexport type ViewMode = z.infer;\n\n// ─── Metadata Viewer Contribution ────────────────────────────────────\n\n/**\n * Declares a metadata viewer/designer component.\n * The runtime component is registered imperatively during plugin activation.\n */\nexport const MetadataViewerContributionSchema = z.object({\n /** Unique viewer ID (namespaced: `pluginId.viewerId`) */\n id: z.string().describe('Unique viewer identifier'),\n\n /** Metadata type(s) this viewer handles (e.g., \"object\", \"flow\", \"agent\") */\n metadataTypes: z.array(z.string()).min(1).describe('Metadata types this viewer can handle'),\n\n /** Human-readable label shown in the view switcher */\n label: z.string().describe('Viewer display label'),\n\n /** Priority — highest-priority viewer becomes default. Built-in default = 0 */\n priority: z.number().default(0).describe('Viewer priority (higher wins)'),\n\n /** View modes this viewer supports */\n modes: z.array(ViewModeSchema).default(['preview']).describe('Supported view modes'),\n});\n\nexport type MetadataViewerContribution = z.infer;\n\n// ─── Sidebar Group Contribution ──────────────────────────────────────\n\n/**\n * Declares a sidebar group that organizes metadata types.\n * Plugins can add new groups or extend existing ones.\n */\nexport const SidebarGroupContributionSchema = z.object({\n /** Unique group key */\n key: z.string().describe('Unique group key'),\n\n /** Display label */\n label: z.string().describe('Group display label'),\n\n /** Lucide icon name (e.g., \"database\", \"workflow\") */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Metadata types belonging to this group */\n metadataTypes: z.array(z.string()).describe('Metadata types in this group'),\n\n /** Sort order — lower values appear first */\n order: z.number().default(100).describe('Sort order (lower = higher)'),\n});\n\nexport type SidebarGroupContribution = z.infer;\n\n// ─── Action Contribution ─────────────────────────────────────────────\n\n/** Where an action can appear in the UI */\nexport const ActionLocationSchema = z.enum(['toolbar', 'contextMenu', 'commandPalette']);\n\n/**\n * Declares an action that can be triggered on metadata items.\n * The handler is registered imperatively during activation.\n */\nexport const ActionContributionSchema = z.object({\n /** Unique action ID */\n id: z.string().describe('Unique action identifier'),\n\n /** Display label */\n label: z.string().describe('Action display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Where this action appears */\n location: ActionLocationSchema.describe('UI location'),\n\n /** Metadata types this action applies to (empty = all types) */\n metadataTypes: z.array(z.string()).default([]).describe('Applicable metadata types'),\n});\n\nexport type ActionContribution = z.infer;\n\n// ─── Metadata Icon Contribution ──────────────────────────────────────\n\n/**\n * Declares an icon and label for a metadata type.\n * Used by the sidebar and breadcrumbs.\n */\nexport const MetadataIconContributionSchema = z.object({\n /** Metadata type this icon represents */\n metadataType: z.string().describe('Metadata type'),\n\n /** Human-readable label */\n label: z.string().describe('Display label'),\n\n /** Lucide icon name */\n icon: z.string().describe('Lucide icon name'),\n});\n\nexport type MetadataIconContribution = z.infer;\n\n// ─── Panel Contribution ──────────────────────────────────────────────\n\n/** Where a panel can be placed */\nexport const PanelLocationSchema = z.enum(['bottom', 'right', 'modal']);\n\n/**\n * Declares an auxiliary panel (like VS Code's Terminal, Problems, Output panels).\n */\nexport const PanelContributionSchema = z.object({\n /** Unique panel ID */\n id: z.string().describe('Unique panel identifier'),\n\n /** Display label */\n label: z.string().describe('Panel display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Panel placement */\n location: PanelLocationSchema.default('bottom').describe('Panel location'),\n});\n\nexport type PanelContribution = z.infer;\n\n// ─── Command Contribution ────────────────────────────────────────────\n\n/**\n * Declares a command that can be invoked from the command palette\n * or programmatically by other plugins.\n */\nexport const CommandContributionSchema = z.object({\n /** Unique command ID (namespaced: `pluginId.commandName`) */\n id: z.string().describe('Unique command identifier'),\n\n /** Display label */\n label: z.string().describe('Command display label'),\n\n /** Keyboard shortcut (e.g., \"Ctrl+Shift+P\") */\n shortcut: z.string().optional().describe('Keyboard shortcut'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n});\n\nexport type CommandContribution = z.infer;\n\n// ─── Studio Plugin Contributions ─────────────────────────────────────\n\n/**\n * All contribution points a Studio plugin can declare.\n * Analogous to VS Code's `contributes` section in `package.json`.\n */\nexport const StudioPluginContributionsSchema = z.object({\n /** Metadata viewer/designer components */\n metadataViewers: z.array(MetadataViewerContributionSchema).default([]),\n\n /** Sidebar navigation groups */\n sidebarGroups: z.array(SidebarGroupContributionSchema).default([]),\n\n /** Toolbar / context menu / command palette actions */\n actions: z.array(ActionContributionSchema).default([]),\n\n /** Metadata type icons & labels */\n metadataIcons: z.array(MetadataIconContributionSchema).default([]),\n\n /** Auxiliary panels */\n panels: z.array(PanelContributionSchema).default([]),\n\n /** Command palette entries */\n commands: z.array(CommandContributionSchema).default([]),\n});\n\nexport type StudioPluginContributions = z.infer;\n\n// ─── Activation Events ───────────────────────────────────────────────\n\n/**\n * Events that trigger plugin activation.\n * Similar to VS Code's `activationEvents`.\n * \n * Patterns:\n * - `*` — Activate immediately (eager)\n * - `onMetadataType:object` — Activate when metadata type \"object\" is loaded\n * - `onCommand:myPlugin.doSomething` — Activate when command is invoked\n * - `onView:myPlugin.myPanel` — Activate when panel is opened\n */\nexport const ActivationEventSchema = z.string().describe('Activation event pattern');\n\n// ─── Studio Plugin Manifest ──────────────────────────────────────────\n\n/**\n * The declarative manifest for a Studio plugin.\n * \n * This is the \"package.json\" equivalent for Studio extensions.\n * All contribution points are declared here; runtime components\n * are registered imperatively during the `activate()` call.\n */\nexport const StudioPluginManifestSchema = z.object({\n /** \n * Unique plugin ID using reverse-domain notation.\n * @example \"objectstack.object-designer\"\n */\n id: z.string()\n .regex(/^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)*$/)\n .describe('Plugin ID (dot-separated lowercase)'),\n\n /** Human-readable plugin name */\n name: z.string().describe('Plugin display name'),\n\n /** Semantic version */\n version: z.string().default('0.0.1').describe('Plugin version'),\n\n /** Plugin description */\n description: z.string().optional().describe('Plugin description'),\n\n /** Author name */\n author: z.string().optional().describe('Author'),\n\n /** Declarative contribution points */\n contributes: StudioPluginContributionsSchema.default({\n metadataViewers: [],\n sidebarGroups: [],\n actions: [],\n metadataIcons: [],\n panels: [],\n commands: [],\n }),\n\n /** \n * Activation events — when to load this plugin.\n * Default `['*']` means eager activation.\n */\n activationEvents: z.array(ActivationEventSchema).default(['*']),\n});\n\nexport type StudioPluginManifest = z.infer;\n\n// ─── Helper: defineStudioPlugin ──────────────────────────────────────\n\n/**\n * Type-safe helper for defining a Studio plugin manifest.\n * \n * @example\n * ```typescript\n * const manifest = defineStudioPlugin({\n * id: 'objectstack.flow-designer',\n * name: 'Flow Designer',\n * contributes: {\n * metadataViewers: [{\n * id: 'flow-canvas',\n * metadataTypes: ['flows'],\n * label: 'Flow Canvas',\n * priority: 100,\n * modes: ['design', 'code'],\n * }],\n * },\n * });\n * ```\n */\nexport function defineStudioPlugin(\n input: z.input\n): StudioPluginManifest {\n return StudioPluginManifestSchema.parse(input);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio/object-designer\n *\n * Object Designer Protocol — Visual Field Editor, Relationship Mapper & ER Diagram\n *\n * Defines the specification for the Object Designer experience within ObjectStack Studio,\n * including:\n * - **Field Editor**: Visual field creation/editing with type-aware property panels\n * - **Relationship Mapper**: Visual lookup/master-detail relationship configuration\n * - **ER Diagram**: Entity-Relationship diagram rendering and interaction\n * - **Object Manager**: Unified object list with search, filtering, and bulk operations\n *\n * ## Architecture\n *\n * The Object Designer is composed of four interconnected panels:\n *\n * ```\n * ┌─────────────────────────────────────────────────────────────────┐\n * │ Object Manager (list / search) │\n * ├──────────────┬──────────────────────────┬──────────────────────┤\n * │ Object List │ Field Editor │ Property Panel │\n * │ (sidebar) │ (table + inline edit) │ (type-specific) │\n * │ │ │ │\n * │ ─ search │ ─ drag-to-reorder │ ─ constraints │\n * │ ─ filter │ ─ inline type picker │ ─ validation │\n * │ ─ group │ ─ batch add/remove │ ─ security │\n * │ ─ create │ ─ field groups │ ─ relationships │\n * ├──────────────┴──────────────────────────┴──────────────────────┤\n * │ ER Diagram (toggle panel) │\n * │ ─ auto-layout (force / hierarchy / grid) │\n * │ ─ interactive: click node → navigate to object │\n * │ ─ hover: highlight connected relationships │\n * │ ─ zoom/pan/minimap │\n * └─────────────────────────────────────────────────────────────────┘\n * ```\n *\n * @example\n * ```typescript\n * import {\n * ObjectDesignerConfigSchema,\n * ERDiagramConfigSchema,\n * } from '@objectstack/spec/studio';\n *\n * const config = ObjectDesignerConfigSchema.parse({\n * defaultView: 'field-editor',\n * fieldEditor: {\n * inlineEditing: true,\n * dragReorder: true,\n * showFieldGroups: true,\n * },\n * erDiagram: {\n * enabled: true,\n * layout: 'force',\n * showFieldDetails: true,\n * },\n * });\n * ```\n */\n\nimport { z } from 'zod';\n\n// ─── Field Editor ────────────────────────────────────────────────────\n\n/**\n * Field property panel section — groups related field properties\n * in the right-side property inspector.\n */\nexport const FieldPropertySectionSchema = z.object({\n /** Unique section key */\n key: z.string().describe('Section key (e.g., \"basics\", \"constraints\", \"security\")'),\n\n /** Display label */\n label: z.string().describe('Section display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Whether section is expanded by default */\n defaultExpanded: z.boolean().default(true).describe('Whether section is expanded by default'),\n\n /** Sort order — lower values appear first */\n order: z.number().default(0).describe('Sort order (lower = higher)'),\n});\n\nexport type FieldPropertySection = z.infer;\n\n/**\n * Field grouping configuration — organizes fields into collapsible groups\n * within the field editor table (e.g., \"Contact Info\", \"Billing\", \"System\").\n */\nexport const FieldGroupSchema = z.object({\n /** Group key (matches field.group value) */\n key: z.string().describe('Group key matching field.group values'),\n\n /** Display label */\n label: z.string().describe('Group display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Whether group is expanded by default */\n defaultExpanded: z.boolean().default(true).describe('Whether group is expanded by default'),\n\n /** Sort order — lower values appear first */\n order: z.number().default(0).describe('Sort order (lower = higher)'),\n});\n\nexport type FieldGroup = z.infer;\n\n/**\n * Field Editor configuration — controls the visual field editing experience.\n */\nexport const FieldEditorConfigSchema = z.object({\n /** Enable inline editing of field properties in the table */\n inlineEditing: z.boolean().default(true).describe('Enable inline editing of field properties'),\n\n /** Enable drag-and-drop field reordering */\n dragReorder: z.boolean().default(true).describe('Enable drag-and-drop field reordering'),\n\n /** Show field group headers for organizing fields */\n showFieldGroups: z.boolean().default(true).describe('Show field group headers'),\n\n /** Show the type-specific property panel on the right */\n showPropertyPanel: z.boolean().default(true).describe('Show the right-side property panel'),\n\n /** Default property panel sections to display */\n propertySections: z.array(FieldPropertySectionSchema).default([\n { key: 'basics', label: 'Basic Properties', defaultExpanded: true, order: 0 },\n { key: 'constraints', label: 'Constraints & Validation', defaultExpanded: true, order: 10 },\n { key: 'relationship', label: 'Relationship Config', defaultExpanded: true, order: 20 },\n { key: 'display', label: 'Display & UI', defaultExpanded: false, order: 30 },\n { key: 'security', label: 'Security & Compliance', defaultExpanded: false, order: 40 },\n { key: 'advanced', label: 'Advanced', defaultExpanded: false, order: 50 },\n ]).describe('Property panel section definitions'),\n\n /** Field groups for organizing fields in the editor */\n fieldGroups: z.array(FieldGroupSchema).default([]).describe('Field group definitions'),\n\n /** Maximum fields before pagination kicks in */\n paginationThreshold: z.number().default(50).describe('Number of fields before pagination is enabled'),\n\n /** Enable batch field operations (add multiple fields at once) */\n batchOperations: z.boolean().default(true).describe('Enable batch add/remove field operations'),\n\n /** Show field usage statistics (views, formulas, relationships referencing this field) */\n showUsageStats: z.boolean().default(false).describe('Show field usage statistics'),\n});\n\nexport type FieldEditorConfig = z.infer;\n\n// ─── Relationship Mapper ─────────────────────────────────────────────\n\n/**\n * Relationship display configuration — controls how relationships\n * are visualized in the mapper and ER diagram.\n */\nexport const RelationshipDisplaySchema = z.object({\n /** Relationship type to configure */\n type: z.enum(['lookup', 'master_detail', 'tree']).describe('Relationship type'),\n\n /** Line style for this relationship type */\n lineStyle: z.enum(['solid', 'dashed', 'dotted']).default('solid').describe('Line style in diagrams'),\n\n /** Line color (CSS color value) */\n color: z.string().default('#94a3b8').describe('Line color (CSS value)'),\n\n /** Highlighted color on hover/select */\n highlightColor: z.string().default('#0891b2').describe('Highlighted color on hover/select'),\n\n /** Cardinality label to display */\n cardinalityLabel: z.string().default('1:N').describe('Cardinality label (e.g., \"1:N\", \"1:1\", \"N:M\")'),\n});\n\nexport type RelationshipDisplay = z.infer;\n\n/**\n * Relationship Mapper configuration — controls the relationship\n * editing and visualization experience.\n */\nexport const RelationshipMapperConfigSchema = z.object({\n /** Enable visual relationship creation (drag from source to target) */\n visualCreation: z.boolean().default(true).describe('Enable drag-to-create relationships'),\n\n /** Show reverse relationships (child → parent) */\n showReverseRelationships: z.boolean().default(true).describe('Show reverse/child-to-parent relationships'),\n\n /** Show cascade delete warnings */\n showCascadeWarnings: z.boolean().default(true).describe('Show cascade delete behavior warnings'),\n\n /** Relationship display configuration by type */\n displayConfig: z.array(RelationshipDisplaySchema).default([\n { type: 'lookup', lineStyle: 'dashed', color: '#0891b2', highlightColor: '#06b6d4', cardinalityLabel: '1:N' },\n { type: 'master_detail', lineStyle: 'solid', color: '#ea580c', highlightColor: '#f97316', cardinalityLabel: '1:N' },\n { type: 'tree', lineStyle: 'dotted', color: '#8b5cf6', highlightColor: '#a78bfa', cardinalityLabel: '1:N' },\n ]).describe('Visual config per relationship type'),\n});\n\nexport type RelationshipMapperConfig = z.infer;\n\n// ─── ER Diagram ──────────────────────────────────────────────────────\n\n/** Layout algorithm for ER diagram */\nexport const ERLayoutAlgorithmSchema = z.enum([\n 'force', // Force-directed graph (natural clustering)\n 'hierarchy', // Top-down hierarchy (master → detail)\n 'grid', // Uniform grid layout\n 'circular', // Circular arrangement\n]).describe('ER diagram layout algorithm');\n\nexport type ERLayoutAlgorithm = z.infer;\n\n/**\n * Node display options — controls what information is shown\n * on each entity node in the ER diagram.\n */\nexport const ERNodeDisplaySchema = z.object({\n /** Show field list within the node */\n showFields: z.boolean().default(true).describe('Show field list inside entity nodes'),\n\n /** Maximum fields to show before collapsing (0 = no limit) */\n maxFieldsVisible: z.number().default(8).describe('Max fields visible before \"N more...\" collapse'),\n\n /** Show field types alongside field names */\n showFieldTypes: z.boolean().default(true).describe('Show field type badges'),\n\n /** Show required field indicators */\n showRequiredIndicator: z.boolean().default(true).describe('Show required field indicators'),\n\n /** Show record count on each node (requires data access) */\n showRecordCount: z.boolean().default(false).describe('Show live record count on nodes'),\n\n /** Show object icon */\n showIcon: z.boolean().default(true).describe('Show object icon on node header'),\n\n /** Show object description on hover tooltip */\n showDescription: z.boolean().default(true).describe('Show description tooltip on hover'),\n});\n\nexport type ERNodeDisplay = z.infer;\n\n/**\n * ER Diagram configuration — controls the entity-relationship\n * diagram rendering, interaction, and layout.\n */\nexport const ERDiagramConfigSchema = z.object({\n /** Enable the ER diagram panel */\n enabled: z.boolean().default(true).describe('Enable ER diagram panel'),\n\n /** Default layout algorithm */\n layout: ERLayoutAlgorithmSchema.default('force').describe('Default layout algorithm'),\n\n /** Node display options */\n nodeDisplay: ERNodeDisplaySchema.default({\n showFields: true,\n maxFieldsVisible: 8,\n showFieldTypes: true,\n showRequiredIndicator: true,\n showRecordCount: false,\n showIcon: true,\n showDescription: true,\n }).describe('Node display configuration'),\n\n /** Show minimap for navigation */\n showMinimap: z.boolean().default(true).describe('Show minimap for large diagrams'),\n\n /** Enable zoom controls */\n zoomControls: z.boolean().default(true).describe('Show zoom in/out/fit controls'),\n\n /** Minimum zoom level */\n minZoom: z.number().default(0.1).describe('Minimum zoom level'),\n\n /** Maximum zoom level */\n maxZoom: z.number().default(3).describe('Maximum zoom level'),\n\n /** Show relationship labels (cardinality) on edges */\n showEdgeLabels: z.boolean().default(true).describe('Show cardinality labels on relationship edges'),\n\n /** Highlight connected entities on hover */\n highlightOnHover: z.boolean().default(true).describe('Highlight connected entities on node hover'),\n\n /** Click behavior: navigate to object designer */\n clickToNavigate: z.boolean().default(true).describe('Click node to navigate to object detail'),\n\n /** Enable drag-and-drop to create relationships */\n dragToConnect: z.boolean().default(true).describe('Drag between nodes to create relationships'),\n\n /** Filter to show only objects with relationships (hide orphans) */\n hideOrphans: z.boolean().default(false).describe('Hide objects with no relationships'),\n\n /** Auto-fit diagram to viewport on initial load */\n autoFit: z.boolean().default(true).describe('Auto-fit diagram to viewport on load'),\n\n /** Export diagram options */\n exportFormats: z.array(z.enum(['png', 'svg', 'json'])).default(['png', 'svg']).describe('Available export formats for diagram'),\n});\n\nexport type ERDiagramConfig = z.infer;\n\n// ─── Object Manager ──────────────────────────────────────────────────\n\n/** Object list display mode */\nexport const ObjectListDisplayModeSchema = z.enum([\n 'table', // Traditional table with columns\n 'cards', // Card grid (visual overview)\n 'tree', // Hierarchical tree (grouped by package/namespace)\n]).describe('Object list display mode');\n\nexport type ObjectListDisplayMode = z.infer;\n\n/** Object list sort field */\nexport const ObjectSortFieldSchema = z.enum([\n 'name', // Sort by API name\n 'label', // Sort by display label\n 'fieldCount', // Sort by number of fields\n 'updatedAt', // Sort by last modified\n]).describe('Object list sort field');\n\nexport type ObjectSortField = z.infer;\n\n/** Object filter criteria */\nexport const ObjectFilterSchema = z.object({\n /** Filter by package/namespace */\n package: z.string().optional().describe('Filter by owning package'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by object tags'),\n\n /** Show system objects */\n includeSystem: z.boolean().default(true).describe('Include system-level objects'),\n\n /** Show abstract objects */\n includeAbstract: z.boolean().default(false).describe('Include abstract base objects'),\n\n /** Show only objects with specific field types */\n hasFieldType: z.string().optional().describe('Filter to objects containing a specific field type'),\n\n /** Show only objects with relationships */\n hasRelationships: z.boolean().optional().describe('Filter to objects with lookup/master_detail fields'),\n\n /** Text search across name, label, description */\n searchQuery: z.string().optional().describe('Free-text search across name, label, and description'),\n});\n\nexport type ObjectFilter = z.infer;\n\n/**\n * Object Manager configuration — controls the unified object list,\n * search, and management experience.\n */\nexport const ObjectManagerConfigSchema = z.object({\n /** Default display mode */\n defaultDisplayMode: ObjectListDisplayModeSchema.default('table').describe('Default list display mode'),\n\n /** Default sort field */\n defaultSortField: ObjectSortFieldSchema.default('label').describe('Default sort field'),\n\n /** Default sort direction */\n defaultSortDirection: z.enum(['asc', 'desc']).default('asc').describe('Default sort direction'),\n\n /** Default filters */\n defaultFilter: ObjectFilterSchema.default({\n includeSystem: true,\n includeAbstract: false,\n }).describe('Default filter configuration'),\n\n /** Show field count badge on each object row */\n showFieldCount: z.boolean().default(true).describe('Show field count badge'),\n\n /** Show relationship count badge */\n showRelationshipCount: z.boolean().default(true).describe('Show relationship count badge'),\n\n /** Show quick-preview tooltip with field list on hover */\n showQuickPreview: z.boolean().default(true).describe('Show quick field preview tooltip on hover'),\n\n /** Enable object comparison (diff two objects side-by-side) */\n enableComparison: z.boolean().default(false).describe('Enable side-by-side object comparison'),\n\n /** Show ER diagram toggle button in the toolbar */\n showERDiagramToggle: z.boolean().default(true).describe('Show ER diagram toggle in toolbar'),\n\n /** Show \"Create Object\" quick action */\n showCreateAction: z.boolean().default(true).describe('Show create object action'),\n\n /** Show object statistics summary bar (total objects, fields, relationships) */\n showStatsSummary: z.boolean().default(true).describe('Show statistics summary bar'),\n});\n\nexport type ObjectManagerConfig = z.infer;\n\n// ─── Object Preview ──────────────────────────────────────────────────\n\n/**\n * Preview tab configuration — defines the tabs available\n * when viewing a single object.\n */\nexport const ObjectPreviewTabSchema = z.object({\n /** Tab key */\n key: z.string().describe('Tab key'),\n\n /** Tab display label */\n label: z.string().describe('Tab display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Whether this tab is enabled */\n enabled: z.boolean().default(true).describe('Whether this tab is available'),\n\n /** Sort order */\n order: z.number().default(0).describe('Sort order (lower = higher)'),\n});\n\nexport type ObjectPreviewTab = z.infer;\n\n/**\n * Object Preview configuration — defines the tabs and layout\n * when viewing/editing a single object's metadata.\n */\nexport const ObjectPreviewConfigSchema = z.object({\n /** Tabs to show in the object detail view */\n tabs: z.array(ObjectPreviewTabSchema).default([\n { key: 'fields', label: 'Fields', icon: 'list', enabled: true, order: 0 },\n { key: 'relationships', label: 'Relationships', icon: 'link', enabled: true, order: 10 },\n { key: 'indexes', label: 'Indexes', icon: 'zap', enabled: true, order: 20 },\n { key: 'validations', label: 'Validations', icon: 'shield-check', enabled: true, order: 30 },\n { key: 'capabilities', label: 'Capabilities', icon: 'settings', enabled: true, order: 40 },\n { key: 'data', label: 'Data', icon: 'table-2', enabled: true, order: 50 },\n { key: 'api', label: 'API', icon: 'globe', enabled: true, order: 60 },\n { key: 'code', label: 'Code', icon: 'code-2', enabled: true, order: 70 },\n ]).describe('Object detail preview tabs'),\n\n /** Default active tab */\n defaultTab: z.string().default('fields').describe('Default active tab key'),\n\n /** Show object header with summary info */\n showHeader: z.boolean().default(true).describe('Show object summary header'),\n\n /** Show breadcrumbs */\n showBreadcrumbs: z.boolean().default(true).describe('Show navigation breadcrumbs'),\n});\n\nexport type ObjectPreviewConfig = z.infer;\n\n// ─── Top-Level Object Designer Config ────────────────────────────────\n\n/** Default view when entering the Object Designer */\nexport const ObjectDesignerDefaultViewSchema = z.enum([\n 'field-editor', // Field table editor (default)\n 'relationship-mapper', // Visual relationship view\n 'er-diagram', // Full ER diagram\n 'object-manager', // Object list/manager\n]).describe('Default view when entering the Object Designer');\n\nexport type ObjectDesignerDefaultView = z.infer;\n\n/**\n * Object Designer configuration — top-level config that composes\n * all sub-configurations for the visual object design experience.\n *\n * @example\n * ```typescript\n * const config = ObjectDesignerConfigSchema.parse({\n * defaultView: 'field-editor',\n * fieldEditor: {\n * inlineEditing: true,\n * dragReorder: true,\n * showFieldGroups: true,\n * },\n * erDiagram: {\n * enabled: true,\n * layout: 'force',\n * },\n * objectManager: {\n * defaultDisplayMode: 'table',\n * showERDiagramToggle: true,\n * },\n * });\n * ```\n */\nexport const ObjectDesignerConfigSchema = z.object({\n /** Default view when opening the designer */\n defaultView: ObjectDesignerDefaultViewSchema.default('field-editor').describe('Default view'),\n\n /** Field editor configuration */\n fieldEditor: FieldEditorConfigSchema.default({\n inlineEditing: true,\n dragReorder: true,\n showFieldGroups: true,\n showPropertyPanel: true,\n propertySections: [\n { key: 'basics', label: 'Basic Properties', defaultExpanded: true, order: 0 },\n { key: 'constraints', label: 'Constraints & Validation', defaultExpanded: true, order: 10 },\n { key: 'relationship', label: 'Relationship Config', defaultExpanded: true, order: 20 },\n { key: 'display', label: 'Display & UI', defaultExpanded: false, order: 30 },\n { key: 'security', label: 'Security & Compliance', defaultExpanded: false, order: 40 },\n { key: 'advanced', label: 'Advanced', defaultExpanded: false, order: 50 },\n ],\n fieldGroups: [],\n paginationThreshold: 50,\n batchOperations: true,\n showUsageStats: false,\n }).describe('Field editor configuration'),\n\n /** Relationship mapper configuration */\n relationshipMapper: RelationshipMapperConfigSchema.default({\n visualCreation: true,\n showReverseRelationships: true,\n showCascadeWarnings: true,\n displayConfig: [\n { type: 'lookup', lineStyle: 'dashed', color: '#0891b2', highlightColor: '#06b6d4', cardinalityLabel: '1:N' },\n { type: 'master_detail', lineStyle: 'solid', color: '#ea580c', highlightColor: '#f97316', cardinalityLabel: '1:N' },\n { type: 'tree', lineStyle: 'dotted', color: '#8b5cf6', highlightColor: '#a78bfa', cardinalityLabel: '1:N' },\n ],\n }).describe('Relationship mapper configuration'),\n\n /** ER diagram configuration */\n erDiagram: ERDiagramConfigSchema.default({\n enabled: true,\n layout: 'force',\n nodeDisplay: {\n showFields: true,\n maxFieldsVisible: 8,\n showFieldTypes: true,\n showRequiredIndicator: true,\n showRecordCount: false,\n showIcon: true,\n showDescription: true,\n },\n showMinimap: true,\n zoomControls: true,\n minZoom: 0.1,\n maxZoom: 3,\n showEdgeLabels: true,\n highlightOnHover: true,\n clickToNavigate: true,\n dragToConnect: true,\n hideOrphans: false,\n autoFit: true,\n exportFormats: ['png', 'svg'],\n }).describe('ER diagram configuration'),\n\n /** Object manager configuration */\n objectManager: ObjectManagerConfigSchema.default({\n defaultDisplayMode: 'table',\n defaultSortField: 'label',\n defaultSortDirection: 'asc',\n defaultFilter: {\n includeSystem: true,\n includeAbstract: false,\n },\n showFieldCount: true,\n showRelationshipCount: true,\n showQuickPreview: true,\n enableComparison: false,\n showERDiagramToggle: true,\n showCreateAction: true,\n showStatsSummary: true,\n }).describe('Object manager configuration'),\n\n /** Object preview configuration */\n objectPreview: ObjectPreviewConfigSchema.default({\n tabs: [\n { key: 'fields', label: 'Fields', icon: 'list', enabled: true, order: 0 },\n { key: 'relationships', label: 'Relationships', icon: 'link', enabled: true, order: 10 },\n { key: 'indexes', label: 'Indexes', icon: 'zap', enabled: true, order: 20 },\n { key: 'validations', label: 'Validations', icon: 'shield-check', enabled: true, order: 30 },\n { key: 'capabilities', label: 'Capabilities', icon: 'settings', enabled: true, order: 40 },\n { key: 'data', label: 'Data', icon: 'table-2', enabled: true, order: 50 },\n { key: 'api', label: 'API', icon: 'globe', enabled: true, order: 60 },\n { key: 'code', label: 'Code', icon: 'code-2', enabled: true, order: 70 },\n ],\n defaultTab: 'fields',\n showHeader: true,\n showBreadcrumbs: true,\n }).describe('Object preview configuration'),\n});\n\nexport type ObjectDesignerConfig = z.infer;\n\n// ─── Helper: defineObjectDesignerConfig ──────────────────────────────\n\n/**\n * Type-safe helper for defining Object Designer configuration.\n *\n * @example\n * ```typescript\n * const config = defineObjectDesignerConfig({\n * defaultView: 'er-diagram',\n * erDiagram: {\n * layout: 'hierarchy',\n * showMinimap: true,\n * },\n * objectManager: {\n * defaultDisplayMode: 'cards',\n * },\n * });\n * ```\n */\nexport function defineObjectDesignerConfig(\n input: z.input,\n): ObjectDesignerConfig {\n return ObjectDesignerConfigSchema.parse(input);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio/page-builder\n *\n * Studio Page Builder Protocol\n *\n * Defines the specification for the drag-and-drop Page Builder UI.\n * The builder allows visual composition of blank pages by placing\n * elements on a grid canvas with snapping, alignment, and layer ordering.\n */\n\nimport { z } from 'zod';\n\n/**\n * Canvas Snap Settings Schema\n * Controls grid snapping behavior during element placement.\n */\nexport const CanvasSnapSettingsSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable snap-to-grid'),\n gridSize: z.number().int().min(1).default(8).describe('Snap grid size in pixels'),\n showGrid: z.boolean().default(true).describe('Show grid overlay on canvas'),\n showGuides: z.boolean().default(true).describe('Show alignment guides when dragging'),\n});\n\n/**\n * Canvas Zoom Settings Schema\n * Controls zoom behavior for the builder canvas.\n */\nexport const CanvasZoomSettingsSchema = z.object({\n min: z.number().min(0.1).default(0.25).describe('Minimum zoom level'),\n max: z.number().max(10).default(3).describe('Maximum zoom level'),\n default: z.number().default(1).describe('Default zoom level'),\n step: z.number().default(0.1).describe('Zoom step increment'),\n});\n\n/**\n * Element Palette Item Schema\n * An element available in the builder palette for drag-and-drop placement.\n */\nexport const ElementPaletteItemSchema = z.object({\n type: z.string().describe('Component type (e.g. \"element:button\", \"element:text\")'),\n label: z.string().describe('Display label in palette'),\n icon: z.string().optional().describe('Icon name for palette display'),\n category: z.enum(['content', 'interactive', 'data', 'layout'])\n .describe('Palette category grouping'),\n defaultWidth: z.number().int().min(1).default(4).describe('Default width in grid columns'),\n defaultHeight: z.number().int().min(1).default(2).describe('Default height in grid rows'),\n});\n\n/**\n * Page Builder Config Schema\n * Configuration for the Studio Page Builder.\n */\nexport const PageBuilderConfigSchema = z.object({\n snap: CanvasSnapSettingsSchema.optional().describe('Canvas snap settings'),\n zoom: CanvasZoomSettingsSchema.optional().describe('Canvas zoom settings'),\n palette: z.array(ElementPaletteItemSchema).optional()\n .describe('Custom element palette (defaults to all registered elements)'),\n showLayerPanel: z.boolean().default(true).describe('Show layer ordering panel'),\n showPropertyPanel: z.boolean().default(true).describe('Show property inspector panel'),\n undoLimit: z.number().int().min(1).default(50).describe('Maximum undo history steps'),\n});\n\n// Backward compatibility alias\n/** @deprecated Use PageBuilderConfigSchema instead */\nexport const InterfaceBuilderConfigSchema = PageBuilderConfigSchema;\n\n// Type Exports\nexport type CanvasSnapSettings = z.infer;\nexport type CanvasZoomSettings = z.infer;\nexport type ElementPaletteItem = z.infer;\n/** @deprecated Use PageBuilderConfig instead */\nexport type InterfaceBuilderConfig = z.infer;\nexport type PageBuilderConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio/flow-builder\n *\n * Studio Flow Builder Protocol\n *\n * Defines the specification for the visual Flow Builder (automation canvas)\n * within ObjectStack Studio. Covers:\n * - **Node Shape Registry**: Shape and visual style per FlowNodeAction type\n * - **Canvas Node**: Position, size, and rendering hints for each node on canvas\n * - **Canvas Edge**: Visual properties for sequence flows (normal, default, fault)\n * - **Flow Builder Config**: Canvas settings, palette, minimap, and toolbar\n *\n * ## Architecture\n *\n * ```\n * ┌──────────────────────────────────────────────────────────────┐\n * │ Toolbar (run / save / undo / zoom / layout) │\n * ├──────────┬───────────────────────────────────┬───────────────┤\n * │ Node │ Canvas │ Property │\n * │ Palette │ ┌─────┐ ┌──────────┐ │ Panel │\n * │ │ │start│───▶│ decision │──▶ ... │ (node-aware) │\n * │ ─ BPMN │ └─────┘ └──────────┘ │ │\n * │ ─ CRUD │ ┌──────────┐ │ ─ config │\n * │ ─ Logic │ │parallel │ │ ─ edges │\n * │ ─ HTTP │ │ gateway │ │ ─ validation │\n * ├──────────┴───────────────────────────────────┴───────────────┤\n * │ Minimap / Zoom Controls │\n * └──────────────────────────────────────────────────────────────┘\n * ```\n */\n\nimport { z } from 'zod';\n\n// ─── Node Shape ──────────────────────────────────────────────────────\n\n/**\n * Shape used to render a flow node on the canvas.\n * Matches BPMN conventions where applicable.\n */\nexport const FlowNodeShapeSchema = z.enum([\n 'rounded_rect', // Default activity shape (assignments, CRUD, HTTP, script, subflow)\n 'circle', // Start / End events\n 'diamond', // Decision (XOR gateway)\n 'parallelogram', // Loop / iteration\n 'hexagon', // Wait / timer event\n 'diamond_thick', // Parallel gateway (AND-split) & Join gateway (AND-join)\n 'attached_circle', // Boundary event (attached to host node)\n 'screen_rect', // Screen / user-interaction node\n]).describe('Visual shape for rendering a flow node on the canvas');\n\nexport type FlowNodeShape = z.infer;\n\n/**\n * Maps each FlowNodeAction to its canvas rendering descriptor.\n * Used by the Studio flow canvas to determine shape, icon, and default size.\n */\nexport const FlowNodeRenderDescriptorSchema = z.object({\n /** The node action type this descriptor applies to */\n action: z.string().describe('FlowNodeAction value (e.g., \"parallel_gateway\")'),\n\n /** Visual shape on the canvas */\n shape: FlowNodeShapeSchema.describe('Shape to render'),\n\n /** Lucide icon name displayed inside the node */\n icon: z.string().describe('Lucide icon name'),\n\n /** Default label shown on the node when no user label is set */\n defaultLabel: z.string().describe('Default display label'),\n\n /** Default width in canvas pixels */\n defaultWidth: z.number().int().min(20).default(120).describe('Default width in pixels'),\n\n /** Default height in canvas pixels */\n defaultHeight: z.number().int().min(20).default(60).describe('Default height in pixels'),\n\n /** CSS color for the node fill */\n fillColor: z.string().default('#ffffff').describe('Node fill color (CSS value)'),\n\n /** CSS color for the node border */\n borderColor: z.string().default('#94a3b8').describe('Node border color (CSS value)'),\n\n /** Whether this node type can have boundary events attached */\n allowBoundaryEvents: z.boolean().default(false)\n .describe('Whether boundary events can be attached to this node type'),\n\n /** Category for palette grouping */\n paletteCategory: z.enum(['event', 'gateway', 'activity', 'data', 'subflow'])\n .describe('Palette category for grouping'),\n}).describe('Visual render descriptor for a flow node type');\n\nexport type FlowNodeRenderDescriptor = z.infer;\n\n// ─── Canvas Node ─────────────────────────────────────────────────────\n\n/**\n * A node instance on the flow canvas, containing position and visual overrides.\n */\nexport const FlowCanvasNodeSchema = z.object({\n /** Reference to the flow node id */\n nodeId: z.string().describe('Corresponding FlowNode.id'),\n\n /** X position on the canvas (pixels) */\n x: z.number().describe('X position on canvas'),\n\n /** Y position on the canvas (pixels) */\n y: z.number().describe('Y position on canvas'),\n\n /** Width override (pixels, optional — uses descriptor default) */\n width: z.number().int().min(20).optional().describe('Width override in pixels'),\n\n /** Height override (pixels, optional — uses descriptor default) */\n height: z.number().int().min(20).optional().describe('Height override in pixels'),\n\n /** Whether the node is collapsed (hides internal details) */\n collapsed: z.boolean().default(false).describe('Whether the node is collapsed'),\n\n /** Custom fill color override */\n fillColor: z.string().optional().describe('Fill color override'),\n\n /** Custom border color override */\n borderColor: z.string().optional().describe('Border color override'),\n\n /** User-defined comment/annotation visible on canvas */\n annotation: z.string().optional().describe('User annotation displayed near the node'),\n}).describe('Canvas layout data for a flow node');\n\nexport type FlowCanvasNode = z.infer;\n\n// ─── Canvas Edge ─────────────────────────────────────────────────────\n\n/**\n * Visual style for a sequence flow edge on the canvas.\n */\nexport const FlowCanvasEdgeStyleSchema = z.enum([\n 'solid', // Normal sequence flow\n 'dashed', // Default sequence flow (isDefault: true)\n 'dotted', // Conditional edge\n 'bold', // Fault / error edge\n]).describe('Edge line style');\n\nexport type FlowCanvasEdgeStyle = z.infer;\n\n/**\n * A sequence-flow edge on the flow canvas with visual properties.\n */\nexport const FlowCanvasEdgeSchema = z.object({\n /** Reference to the flow edge id */\n edgeId: z.string().describe('Corresponding FlowEdge.id'),\n\n /** Line style */\n style: FlowCanvasEdgeStyleSchema.default('solid').describe('Line style'),\n\n /** Line color (CSS value) */\n color: z.string().default('#94a3b8').describe('Edge line color'),\n\n /** Label position along the edge (0–1, 0.5 = midpoint) */\n labelPosition: z.number().min(0).max(1).default(0.5)\n .describe('Position of the condition label along the edge'),\n\n /** Optional waypoints for routing the edge around nodes */\n waypoints: z.array(z.object({\n x: z.number().describe('Waypoint X'),\n y: z.number().describe('Waypoint Y'),\n })).optional().describe('Manual waypoints for edge routing'),\n\n /** Whether to show an animated flow indicator */\n animated: z.boolean().default(false).describe('Show animated flow indicator'),\n}).describe('Canvas layout and visual data for a flow edge');\n\nexport type FlowCanvasEdge = z.infer;\n\n// ─── Flow Canvas Layout ──────────────────────────────────────────────\n\n/**\n * Auto-layout algorithm for the flow canvas.\n */\nexport const FlowLayoutAlgorithmSchema = z.enum([\n 'dagre', // Directed acyclic graph layout (top-down or left-right)\n 'elk', // Eclipse Layout Kernel (advanced hierarchical)\n 'force', // Force-directed graph\n 'manual', // User-positioned (no auto-layout)\n]).describe('Auto-layout algorithm for the flow canvas');\n\nexport type FlowLayoutAlgorithm = z.infer;\n\n/**\n * Direction for the auto-layout.\n */\nexport const FlowLayoutDirectionSchema = z.enum([\n 'TB', // Top to bottom\n 'BT', // Bottom to top\n 'LR', // Left to right\n 'RL', // Right to left\n]).describe('Auto-layout direction');\n\nexport type FlowLayoutDirection = z.infer;\n\n// ─── Flow Builder Config ─────────────────────────────────────────────\n\n/**\n * Flow Builder configuration — top-level config for the Studio\n * automation flow canvas editor.\n */\nexport const FlowBuilderConfigSchema = z.object({\n /** Canvas snap settings */\n snap: z.object({\n enabled: z.boolean().default(true).describe('Enable snap-to-grid'),\n gridSize: z.number().int().min(1).default(16).describe('Snap grid size in pixels'),\n showGrid: z.boolean().default(true).describe('Show grid overlay'),\n }).default({ enabled: true, gridSize: 16, showGrid: true })\n .describe('Canvas snap-to-grid settings'),\n\n /** Canvas zoom settings */\n zoom: z.object({\n min: z.number().min(0.1).default(0.25).describe('Minimum zoom level'),\n max: z.number().max(10).default(3).describe('Maximum zoom level'),\n default: z.number().default(1).describe('Default zoom level'),\n step: z.number().default(0.1).describe('Zoom step'),\n }).default({ min: 0.25, max: 3, default: 1, step: 0.1 })\n .describe('Canvas zoom settings'),\n\n /** Auto-layout algorithm */\n layoutAlgorithm: FlowLayoutAlgorithmSchema.default('dagre')\n .describe('Default auto-layout algorithm'),\n\n /** Auto-layout direction */\n layoutDirection: FlowLayoutDirectionSchema.default('TB')\n .describe('Default auto-layout direction'),\n\n /** Node render descriptors (override defaults per node type) */\n nodeDescriptors: z.array(FlowNodeRenderDescriptorSchema).optional()\n .describe('Custom node render descriptors (merged with built-in defaults)'),\n\n /** Show minimap for navigation */\n showMinimap: z.boolean().default(true).describe('Show minimap panel'),\n\n /** Show the node property panel */\n showPropertyPanel: z.boolean().default(true).describe('Show property panel'),\n\n /** Show the node palette sidebar */\n showPalette: z.boolean().default(true).describe('Show node palette sidebar'),\n\n /** Maximum undo history steps */\n undoLimit: z.number().int().min(1).default(50).describe('Maximum undo history steps'),\n\n /** Enable edge animation during execution preview */\n animateExecution: z.boolean().default(true)\n .describe('Animate edges during execution preview'),\n\n /** Connection validation — prevent invalid edges (e.g., duplicate, self-loop) */\n connectionValidation: z.boolean().default(true)\n .describe('Validate connections before creating edges'),\n}).describe('Studio Flow Builder configuration');\n\nexport type FlowBuilderConfig = z.infer;\n\n// ─── Built-in Node Descriptors ───────────────────────────────────────\n\n/**\n * Built-in node render descriptors for all standard FlowNodeAction types.\n * Studio implementations should merge user overrides on top of these defaults.\n */\nexport const BUILT_IN_NODE_DESCRIPTORS: FlowNodeRenderDescriptor[] = [\n { action: 'start', shape: 'circle', icon: 'play', defaultLabel: 'Start', defaultWidth: 60, defaultHeight: 60, fillColor: '#dcfce7', borderColor: '#16a34a', allowBoundaryEvents: false, paletteCategory: 'event' },\n { action: 'end', shape: 'circle', icon: 'square', defaultLabel: 'End', defaultWidth: 60, defaultHeight: 60, fillColor: '#fee2e2', borderColor: '#dc2626', allowBoundaryEvents: false, paletteCategory: 'event' },\n { action: 'decision', shape: 'diamond', icon: 'git-branch', defaultLabel: 'Decision', defaultWidth: 80, defaultHeight: 80, fillColor: '#fef9c3', borderColor: '#ca8a04', allowBoundaryEvents: false, paletteCategory: 'gateway' },\n { action: 'parallel_gateway', shape: 'diamond_thick', icon: 'git-fork', defaultLabel: 'Parallel Gateway', defaultWidth: 80, defaultHeight: 80, fillColor: '#dbeafe', borderColor: '#2563eb', allowBoundaryEvents: false, paletteCategory: 'gateway' },\n { action: 'join_gateway', shape: 'diamond_thick', icon: 'git-merge', defaultLabel: 'Join Gateway', defaultWidth: 80, defaultHeight: 80, fillColor: '#dbeafe', borderColor: '#2563eb', allowBoundaryEvents: false, paletteCategory: 'gateway' },\n { action: 'wait', shape: 'hexagon', icon: 'clock', defaultLabel: 'Wait', defaultWidth: 100, defaultHeight: 60, fillColor: '#f3e8ff', borderColor: '#7c3aed', allowBoundaryEvents: true, paletteCategory: 'event' },\n { action: 'boundary_event', shape: 'attached_circle', icon: 'alert-circle', defaultLabel: 'Boundary Event', defaultWidth: 40, defaultHeight: 40, fillColor: '#fff7ed', borderColor: '#ea580c', allowBoundaryEvents: false, paletteCategory: 'event' },\n { action: 'assignment', shape: 'rounded_rect', icon: 'pen-line', defaultLabel: 'Assignment', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'activity' },\n { action: 'create_record', shape: 'rounded_rect', icon: 'plus-circle', defaultLabel: 'Create Record', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'data' },\n { action: 'update_record', shape: 'rounded_rect', icon: 'edit', defaultLabel: 'Update Record', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'data' },\n { action: 'delete_record', shape: 'rounded_rect', icon: 'trash-2', defaultLabel: 'Delete Record', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'data' },\n { action: 'get_record', shape: 'rounded_rect', icon: 'search', defaultLabel: 'Get Record', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'data' },\n { action: 'http_request', shape: 'rounded_rect', icon: 'globe', defaultLabel: 'HTTP Request', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'activity' },\n { action: 'script', shape: 'rounded_rect', icon: 'code', defaultLabel: 'Script', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'activity' },\n { action: 'screen', shape: 'screen_rect', icon: 'monitor', defaultLabel: 'Screen', defaultWidth: 140, defaultHeight: 80, fillColor: '#f0f9ff', borderColor: '#0284c7', allowBoundaryEvents: false, paletteCategory: 'activity' },\n { action: 'loop', shape: 'parallelogram', icon: 'repeat', defaultLabel: 'Loop', defaultWidth: 120, defaultHeight: 60, fillColor: '#fef3c7', borderColor: '#d97706', allowBoundaryEvents: true, paletteCategory: 'activity' },\n { action: 'subflow', shape: 'rounded_rect', icon: 'layers', defaultLabel: 'Subflow', defaultWidth: 140, defaultHeight: 70, fillColor: '#ede9fe', borderColor: '#7c3aed', allowBoundaryEvents: true, paletteCategory: 'subflow' },\n { action: 'connector_action', shape: 'rounded_rect', icon: 'plug', defaultLabel: 'Connector', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'activity' },\n];\n\n// ─── Helper: defineFlowBuilderConfig ─────────────────────────────────\n\n/**\n * Type-safe helper for defining Flow Builder configuration.\n *\n * @example\n * ```typescript\n * const config = defineFlowBuilderConfig({\n * layoutAlgorithm: 'dagre',\n * layoutDirection: 'LR',\n * showMinimap: true,\n * snap: { gridSize: 20 },\n * });\n * ```\n */\nexport function defineFlowBuilderConfig(\n input: z.input,\n): FlowBuilderConfig {\n return FlowBuilderConfigSchema.parse(input);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\nimport { ManifestSchema } from './kernel/manifest.zod';\nimport { DatasourceSchema } from './data/datasource.zod';\nimport { TranslationBundleSchema, TranslationConfigSchema } from './system/translation.zod';\nimport { objectStackErrorMap, formatZodError } from './shared/error-map.zod';\nimport { normalizeStackInput, type MetadataCollectionInput, type MapSupportedField } from './shared/metadata-collection.zod';\n\n// Data Protocol\nimport { ObjectSchema, ObjectExtensionSchema } from './data/object.zod';\nimport { DatasetSchema } from './data/dataset.zod';\n\n// UI Protocol\nimport { AppSchema } from './ui/app.zod';\nimport { ViewSchema } from './ui/view.zod';\nimport { PageSchema } from './ui/page.zod';\nimport { DashboardSchema } from './ui/dashboard.zod';\nimport { ReportSchema } from './ui/report.zod';\nimport { ActionSchema } from './ui/action.zod';\nimport { ThemeSchema } from './ui/theme.zod';\n\n// Automation Protocol\nimport { ApprovalProcessSchema } from './automation/approval.zod';\nimport { WorkflowRuleSchema } from './automation/workflow.zod';\nimport { FlowSchema } from './automation/flow.zod';\n\n// Security Protocol\nimport { RoleSchema } from './identity/role.zod';\nimport { PermissionSetSchema } from './security/permission.zod';\nimport { SharingRuleSchema } from './security/sharing.zod';\nimport { PolicySchema } from './security/policy.zod';\n\nimport { ApiEndpointSchema } from './api/endpoint.zod';\nimport { FeatureFlagSchema } from './kernel/feature.zod';\n\n// AI Protocol\nimport { AgentSchema } from './ai/agent.zod';\nimport { RAGPipelineConfigSchema } from './ai/rag-pipeline.zod';\n\n// Data Protocol (additional)\nimport { HookSchema } from './data/hook.zod';\nimport { MappingSchema } from './data/mapping.zod';\nimport { CubeSchema } from './data/analytics.zod';\n\n// Automation Protocol (additional)\nimport { WebhookSchema } from './automation/webhook.zod';\n\n// Integration Protocol\nimport { ConnectorSchema } from './integration/connector.zod';\n\n/**\n * ObjectStack Ecosystem Definition\n * \n * This schema represents the \"Full Stack\" definition of a project or environment.\n * It is used for:\n * 1. Project Export/Import (YAML/JSON dumps)\n * 2. IDE Validation (IntelliSense)\n * 3. Runtime Bootstrapping (In-memory loading)\n * 4. Platform Reflection (API & Capabilities Discovery)\n */\n/**\n * 1. DEFINITION PROTOCOL (Static)\n * ----------------------------------------------------------------------\n * Describes the \"Blueprint\" or \"Source Code\" of an ObjectStack Plugin/Project.\n * This represents the complete declarative state of the application.\n * \n * Usage:\n * - Developers write this in files locally.\n * - AI Agents generate this to create apps.\n * - CI Tools deploy this to the server.\n */\nexport const ObjectStackDefinitionSchema = z.object({\n /** System Configuration */\n manifest: ManifestSchema.optional().describe('Project Package Configuration'),\n datasources: z.array(DatasourceSchema).optional().describe('External Data Connections'),\n translations: z.array(TranslationBundleSchema).optional().describe('I18n Translation Bundles'),\n i18n: TranslationConfigSchema.optional().describe('Internationalization configuration'),\n\n /** \n * ObjectQL: Data Layer \n * All business objects and entities.\n */\n objects: z.array(ObjectSchema).optional().describe('Business Objects definition (owned by this package)'),\n\n /**\n * Object Extensions: fields/config to merge into objects owned by other packages.\n * Use this instead of redefining an object when you want to add fields to\n * an existing object from another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact',\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\n objectExtensions: z.array(ObjectExtensionSchema).optional().describe('Extensions to objects owned by other packages'),\n\n /** \n * ObjectUI: User Interface Layer \n * Apps, Menus, Pages, and Visualizations.\n */\n apps: z.array(AppSchema).optional().describe('Applications'),\n views: z.array(ViewSchema).optional().describe('List Views'),\n pages: z.array(PageSchema).optional().describe('Custom Pages'),\n dashboards: z.array(DashboardSchema).optional().describe('Dashboards'),\n reports: z.array(ReportSchema).optional().describe('Analytics Reports'),\n actions: z.array(ActionSchema).optional().describe('Global and Object Actions'),\n themes: z.array(ThemeSchema).optional().describe('UI Themes'),\n\n /** \n * ObjectFlow: Automation Layer \n * Business logic, approvals, and workflows.\n */\n workflows: z.array(WorkflowRuleSchema).optional().describe('Event-driven workflows'),\n approvals: z.array(ApprovalProcessSchema).optional().describe('Approval processes'),\n flows: z.array(FlowSchema).optional().describe('Screen Flows'),\n\n /**\n * ObjectGuard: Security Layer\n */\n roles: z.array(RoleSchema).optional().describe('User Roles hierarchy'),\n permissions: z.array(PermissionSetSchema).optional().describe('Permission Sets and Profiles'),\n sharingRules: z.array(SharingRuleSchema).optional().describe('Record Sharing Rules'),\n policies: z.array(PolicySchema).optional().describe('Security & Compliance Policies'),\n\n /**\n * ObjectAPI: API Layer\n */\n apis: z.array(ApiEndpointSchema).optional().describe('API Endpoints'),\n webhooks: z.array(WebhookSchema).optional().describe('Outbound Webhooks'),\n\n /**\n * ObjectAI: Artificial Intelligence Layer\n */\n agents: z.array(AgentSchema).optional().describe('AI Agents and Assistants'),\n ragPipelines: z.array(RAGPipelineConfigSchema).optional().describe('RAG Pipelines'),\n\n /**\n * ObjectQL: Data Extensions\n * Hooks, mappings, and analytics cubes.\n */\n hooks: z.array(HookSchema).optional().describe('Object Lifecycle Hooks'),\n mappings: z.array(MappingSchema).optional().describe('Data Import/Export Mappings'),\n analyticsCubes: z.array(CubeSchema).optional().describe('Analytics Semantic Layer Cubes'),\n\n /**\n * Integration Protocol\n */\n connectors: z.array(ConnectorSchema).optional().describe('External System Connectors'),\n\n /**\n * Data Seeding Protocol\n * \n * Declarative seed data for bootstrapping, demos, and testing.\n * Each entry targets a specific object and provides records to load\n * using the specified conflict resolution strategy.\n * \n * Uses the standard DatasetSchema which supports:\n * - `externalId`: Idempotency key for upsert matching (default: 'name')\n * - `mode`: Conflict resolution (upsert, insert, ignore, replace)\n * - `env`: Environment scoping (prod, dev, test)\n * \n * @example\n * ```ts\n * data: [\n * {\n * object: 'account',\n * mode: 'upsert',\n * externalId: 'name',\n * records: [\n * { name: 'Acme Corp', type: 'customer', industry: 'technology' },\n * ]\n * }\n * ]\n * ```\n */\n data: z.array(DatasetSchema).optional().describe('Seed Data / Fixtures for bootstrapping'),\n\n /**\n * Plugins: External Capabilities\n * List of plugins to load. Can be a Manifest object, a package name string, or a Runtime Plugin instance.\n */\n plugins: z.array(z.unknown()).optional().describe('Plugins to load'),\n\n /**\n * DevPlugins: Development Capabilities\n * List of plugins to load ONLY in development environment.\n * Equivalent to `devDependencies` in package.json.\n * Useful for loading dev-tools, mock data generators, or referencing local sibling packages for debugging.\n */\n devPlugins: z.array(z.union([ManifestSchema, z.string()])).optional().describe('Plugins to load only in development (CLI dev command)'),\n});\n\nexport type ObjectStackDefinition = z.infer;\n\n/**\n * Extract the element type from an array type.\n * @internal\n */\ntype ExtractArrayItem = T extends (infer Item)[] ? Item : never;\n\n/**\n * Input type for `defineStack()` that accepts both array and map format\n * for all named metadata collections.\n * \n * Map format allows defining metadata using the key as the `name` field:\n * ```ts\n * // Array format (traditional)\n * objects: [{ name: 'task', fields: { ... } }]\n * \n * // Map format (key becomes name)\n * objects: { task: { fields: { ... } } }\n * ```\n * \n * The output type is always arrays (`ObjectStackDefinition`).\n */\nexport type ObjectStackDefinitionInput =\n Omit, MapSupportedField> & {\n [K in MapSupportedField]?: MetadataCollectionInput<\n ExtractArrayItem[K]>>\n >;\n };\n\n// Alias for backward compatibility\nexport const ObjectStackSchema = ObjectStackDefinitionSchema;\nexport type ObjectStack = ObjectStackDefinition;\n\n/**\n * Options for `defineStack()`.\n */\nexport interface DefineStackOptions {\n /**\n * When `true` (default), enables strict validation:\n * - All Zod schemas are validated (field names, types, etc.)\n * - Cross-reference validation runs (views/actions/workflows reference valid objects)\n * - Ensures data integrity and catches errors early\n *\n * When `false`, validation is skipped for maximum flexibility\n * (e.g., when views reference objects provided by other plugins).\n * Use this ONLY when you need to bypass validation for advanced use cases.\n *\n * @default true\n */\n strict?: boolean;\n}\n\n/**\n * Collect all object names defined in a stack definition.\n */\nfunction collectObjectNames(config: ObjectStackDefinition): Set {\n const names = new Set();\n if (config.objects) {\n for (const obj of config.objects) {\n names.add(obj.name);\n }\n }\n return names;\n}\n\n/**\n * Perform strict cross-reference validation on a parsed stack definition.\n * Returns an array of error messages (empty if valid).\n */\nfunction validateCrossReferences(config: ObjectStackDefinition): string[] {\n const errors: string[] = [];\n const objectNames = collectObjectNames(config);\n\n if (objectNames.size === 0) return errors;\n\n // Validate workflow → object references (uses `objectName`)\n if (config.workflows) {\n for (const workflow of config.workflows) {\n if (workflow.objectName && !objectNames.has(workflow.objectName)) {\n errors.push(\n `Workflow '${workflow.name}' references object '${workflow.objectName}' which is not defined in objects.`,\n );\n }\n }\n }\n\n // Validate approval → object references\n if (config.approvals) {\n for (const approval of config.approvals) {\n if (approval.object && !objectNames.has(approval.object)) {\n errors.push(\n `Approval '${approval.name}' references object '${approval.object}' which is not defined in objects.`,\n );\n }\n }\n }\n\n // Validate hook → object references\n if (config.hooks) {\n for (const hook of config.hooks) {\n if (hook.object) {\n const hookObjects = Array.isArray(hook.object) ? hook.object : [hook.object];\n for (const obj of hookObjects) {\n if (!objectNames.has(obj)) {\n errors.push(\n `Hook '${hook.name}' references object '${obj}' which is not defined in objects.`,\n );\n }\n }\n }\n }\n }\n\n // Validate view data source → object references (nested in data.object)\n if (config.views) {\n for (const [i, view] of config.views.entries()) {\n const checkViewData = (data: unknown, viewLabel: string) => {\n if (data && typeof data === 'object' && 'provider' in data && 'object' in data) {\n const d = data as { provider: string; object: string };\n if (d.provider === 'object' && d.object && !objectNames.has(d.object)) {\n errors.push(\n `${viewLabel} references object '${d.object}' which is not defined in objects.`,\n );\n }\n }\n };\n\n if (view.list?.data) {\n checkViewData(view.list.data, `View[${i}].list`);\n }\n if (view.form?.data) {\n checkViewData(view.form.data, `View[${i}].form`);\n }\n }\n }\n\n // Validate seed data → object references\n if (config.data) {\n for (const dataset of config.data) {\n if (dataset.object && !objectNames.has(dataset.object)) {\n errors.push(\n `Seed data references object '${dataset.object}' which is not defined in objects.`,\n );\n }\n }\n }\n\n // Validate app navigation → object/dashboard/page/report references\n if (config.apps) {\n const dashboardNames = new Set();\n if (config.dashboards) {\n for (const d of config.dashboards) {\n dashboardNames.add(d.name);\n }\n }\n const pageNames = new Set();\n if (config.pages) {\n for (const p of config.pages) {\n pageNames.add(p.name);\n }\n }\n const reportNames = new Set();\n if (config.reports) {\n for (const r of config.reports) {\n reportNames.add(r.name);\n }\n }\n\n for (const app of config.apps) {\n if (!app.navigation) continue;\n const checkNavItems = (items: unknown[], appName: string) => {\n for (const item of items) {\n if (!item || typeof item !== 'object') continue;\n const nav = item as Record;\n if (nav.type === 'object' && typeof nav.objectName === 'string' && !objectNames.has(nav.objectName)) {\n errors.push(\n `App '${appName}' navigation references object '${nav.objectName}' which is not defined in objects.`,\n );\n }\n if (nav.type === 'dashboard' && typeof nav.dashboardName === 'string' && dashboardNames.size > 0 && !dashboardNames.has(nav.dashboardName)) {\n errors.push(\n `App '${appName}' navigation references dashboard '${nav.dashboardName}' which is not defined in dashboards.`,\n );\n }\n if (nav.type === 'page' && typeof nav.pageName === 'string' && pageNames.size > 0 && !pageNames.has(nav.pageName)) {\n errors.push(\n `App '${appName}' navigation references page '${nav.pageName}' which is not defined in pages.`,\n );\n }\n if (nav.type === 'report' && typeof nav.reportName === 'string' && reportNames.size > 0 && !reportNames.has(nav.reportName)) {\n errors.push(\n `App '${appName}' navigation references report '${nav.reportName}' which is not defined in reports.`,\n );\n }\n // Recurse into group children\n if (nav.type === 'group' && Array.isArray(nav.children)) {\n checkNavItems(nav.children, appName);\n }\n }\n };\n checkNavItems(app.navigation, app.name);\n }\n }\n\n // Validate action → flow/modal cross-references\n // Note: When no flows/pages are defined (size === 0), targets are not validated\n // because the referenced items may be provided by a plugin.\n // This is consistent with dashboard/page/report validation in navigation.\n if (config.actions) {\n const flowNames = new Set();\n if (config.flows) {\n for (const flow of config.flows) {\n flowNames.add(flow.name);\n }\n }\n\n const pageNames = new Set();\n if (config.pages) {\n for (const page of config.pages) {\n pageNames.add(page.name);\n }\n }\n\n for (const action of config.actions) {\n // Validate flow-type actions reference a defined flow\n if (action.type === 'flow' && action.target && flowNames.size > 0 && !flowNames.has(action.target)) {\n errors.push(\n `Action '${action.name}' references flow '${action.target}' which is not defined in flows.`,\n );\n }\n\n // Validate modal-type actions reference a defined page\n if (action.type === 'modal' && action.target && pageNames.size > 0 && !pageNames.has(action.target)) {\n errors.push(\n `Action '${action.name}' references page '${action.target}' (via modal target) which is not defined in pages.`,\n );\n }\n\n // Validate action → object references (objectName)\n if (action.objectName && !objectNames.has(action.objectName)) {\n errors.push(\n `Action '${action.name}' references object '${action.objectName}' which is not defined in objects.`,\n );\n }\n }\n }\n\n return errors;\n}\n\n/**\n * Merge top-level actions into their target objects based on `objectName`.\n * \n * Actions with `objectName` are appended to the corresponding object's `actions` array.\n * Actions without `objectName` (global actions) are left untouched.\n * The top-level `actions` array is preserved for global access (e.g., platform overview, search).\n * \n * This aligns with Salesforce/ServiceNow patterns where object metadata includes its actions,\n * so API responses like `/api/v1/meta/objects/:name` include actions without downstream merge.\n * \n * @internal\n */\nfunction mergeActionsIntoObjects(config: ObjectStackDefinition): ObjectStackDefinition {\n if (!config.actions || !config.objects || config.objects.length === 0) {\n return config;\n }\n\n // Build map: objectName → actions[]\n const actionsByObject = new Map>();\n for (const action of config.actions) {\n if (action.objectName) {\n const list = actionsByObject.get(action.objectName) ?? [];\n list.push(action);\n actionsByObject.set(action.objectName, list);\n }\n }\n\n if (actionsByObject.size === 0) return config;\n\n // Merge into objects (shallow copy — only the `actions` field is modified;\n // other fields are shared references, consistent with mergeObjects() and Zod output)\n const newObjects = config.objects.map((obj) => {\n const objActions = actionsByObject.get(obj.name);\n if (!objActions) return obj;\n return {\n ...obj,\n actions: [...(obj.actions ?? []), ...objActions],\n };\n });\n\n return { ...config, objects: newObjects };\n}\n\n/**\n * Type-safe helper to define a generic stack.\n *\n * In ObjectStack, the concept of \"Project\" and \"Plugin\" is fluid:\n * - A **Project** is simply a Stack that is currently being executed (the `cwd`).\n * - A **Plugin** is a Stack that is being loaded by another Stack.\n *\n * This unified definition allows any \"Project\" (e.g., Todo App) to be imported\n * as a \"Plugin\" into a larger system (e.g., Company PaaS) without code changes.\n *\n * @param config - The stack definition object\n * @param options - Optional settings. Use `{ strict: true }` to validate cross-references.\n * @returns The validated stack definition\n *\n * @example\n * ```ts\n * // Basic usage (pass-through, backward compatible)\n * const stack = defineStack({ manifest: { ... }, objects: [...] });\n *\n * // Map format — key becomes `name` field\n * const stack = defineStack({\n * objects: {\n * task: { fields: { title: { type: 'text' } } },\n * project: { fields: { name: { type: 'text' } } },\n * },\n * apps: {\n * project_manager: { label: 'Project Manager', objects: ['task', 'project'] },\n * },\n * });\n *\n * // Strict mode — validates that views/workflows reference defined objects\n * const stack = defineStack({ manifest: { ... }, objects: [...], views: [...] }, { strict: true });\n * ```\n */\nexport function defineStack(\n config: ObjectStackDefinitionInput,\n options?: DefineStackOptions,\n): ObjectStackDefinition {\n // Default to strict=true for safety (validate by default)\n const strict = options?.strict !== false;\n\n // Normalize map-formatted collections to arrays (key → name injection)\n const normalized = normalizeStackInput(config as Record);\n\n if (!strict) {\n // Non-strict mode: skip validation (advanced use cases only)\n return mergeActionsIntoObjects(normalized as ObjectStackDefinition);\n }\n\n // Strict mode (default): parse with custom error map, then cross-reference validate\n const result = ObjectStackDefinitionSchema.safeParse(normalized, {\n error: objectStackErrorMap,\n });\n\n if (!result.success) {\n throw new Error(formatZodError(result.error, 'defineStack validation failed'));\n }\n\n const crossRefErrors = validateCrossReferences(result.data);\n if (crossRefErrors.length > 0) {\n const header = `defineStack cross-reference validation failed (${crossRefErrors.length} issue${crossRefErrors.length === 1 ? '' : 's'}):`;\n const lines = crossRefErrors.map((e) => ` ✗ ${e}`);\n throw new Error(`${header}\\n\\n${lines.join('\\n')}`);\n }\n\n return mergeActionsIntoObjects(result.data);\n}\n\n\n// ─── composeStacks ──────────────────────────────────────────────────\n\n/**\n * Strategy for resolving conflicts when multiple stacks define the same named item.\n *\n * - `'error'` — Throw an error when a duplicate name is detected (default).\n * - `'override'` — Last stack wins; later definitions replace earlier ones.\n * - `'merge'` — Shallow-merge items with the same name (later fields win).\n */\nexport const ConflictStrategySchema = z.enum(['error', 'override', 'merge']);\nexport type ConflictStrategy = z.infer;\n\n/**\n * Options for {@link composeStacks}.\n */\nexport const ComposeStacksOptionsSchema = z.object({\n /**\n * How to handle same-name objects across stacks.\n * @default 'error'\n */\n objectConflict: ConflictStrategySchema.default('error'),\n\n /**\n * Which manifest to keep when multiple stacks provide one.\n * - `'first'` — Use the first manifest found.\n * - `'last'` — Use the last manifest found (default).\n * - A number — Use the manifest from the stack at the given index.\n * @default 'last'\n */\n manifest: z.union([z.enum(['first', 'last']), z.number().int().min(0)]).default('last'),\n\n /**\n * Optional namespace prefix (reserved for Phase 2 — Marketplace isolation).\n * When set, object names from this composition are prefixed for isolation.\n */\n namespace: z.string().optional(),\n});\n\nexport type ComposeStacksOptions = z.input;\n\n/**\n * All array fields on `ObjectStackDefinition` that are simply concatenated.\n * @internal\n */\nconst CONCAT_ARRAY_FIELDS = [\n 'datasources',\n 'translations',\n 'objectExtensions',\n 'apps',\n 'views',\n 'pages',\n 'dashboards',\n 'reports',\n 'actions',\n 'themes',\n 'workflows',\n 'approvals',\n 'flows',\n 'roles',\n 'permissions',\n 'sharingRules',\n 'policies',\n 'apis',\n 'webhooks',\n 'agents',\n 'ragPipelines',\n 'hooks',\n 'mappings',\n 'analyticsCubes',\n 'connectors',\n 'data',\n 'plugins',\n 'devPlugins',\n] as const satisfies readonly (keyof ObjectStackDefinition)[];\n\n/**\n * Merge objects from multiple stacks according to the chosen conflict strategy.\n * @internal\n */\nfunction mergeObjects(\n stacks: ObjectStackDefinition[],\n strategy: ConflictStrategy,\n): ObjectStackDefinition['objects'] {\n type Obj = NonNullable[number];\n const map = new Map();\n const result: Obj[] = [];\n\n for (const stack of stacks) {\n if (!stack.objects) continue;\n for (const obj of stack.objects) {\n const existing = map.get(obj.name);\n if (!existing) {\n map.set(obj.name, obj);\n result.push(obj);\n continue;\n }\n\n switch (strategy) {\n case 'error':\n throw new Error(\n `composeStacks conflict: object '${obj.name}' is defined in multiple stacks. ` +\n `Use { objectConflict: 'override' } or { objectConflict: 'merge' } to resolve.`,\n );\n case 'override': {\n // Replace in-place in the result array\n const idx = result.indexOf(existing);\n result[idx] = obj;\n map.set(obj.name, obj);\n break;\n }\n case 'merge': {\n const merged = { ...existing, ...obj, fields: { ...existing.fields, ...obj.fields } } as Obj;\n const idx = result.indexOf(existing);\n result[idx] = merged;\n map.set(obj.name, merged);\n break;\n }\n }\n }\n }\n\n return result.length > 0 ? result : undefined;\n}\n\n/**\n * Select the manifest to use from multiple stacks.\n * @internal\n */\nfunction selectManifest(\n stacks: ObjectStackDefinition[],\n strategy: 'first' | 'last' | number,\n): ObjectStackDefinition['manifest'] {\n if (typeof strategy === 'number') {\n return stacks[strategy]?.manifest;\n }\n if (strategy === 'first') {\n for (const s of stacks) {\n if (s.manifest) return s.manifest;\n }\n return undefined;\n }\n // 'last' (default)\n for (let i = stacks.length - 1; i >= 0; i--) {\n if (stacks[i].manifest) return stacks[i].manifest;\n }\n return undefined;\n}\n\n/**\n * Declaratively compose multiple stack definitions into a single unified stack.\n *\n * This eliminates the manual `...spread` merging pattern when combining\n * multiple applications (e.g., CRM + Todo + BI) into a single project.\n *\n * **Array fields** (apps, views, dashboards, etc.) are concatenated in order.\n * **Objects** are merged according to the `objectConflict` strategy.\n * **Manifest** is selected based on the `manifest` option.\n *\n * @param stacks - Stack definitions to compose (order matters for conflict resolution)\n * @param options - Composition options (conflict strategy, manifest selection, etc.)\n * @returns A single merged `ObjectStackDefinition`\n *\n * @example\n * ```ts\n * import { composeStacks, defineStack } from '@objectstack/spec';\n *\n * const crm = defineStack({ ... });\n * const todo = defineStack({ ... });\n *\n * // Simple composition — throws on duplicate objects\n * const combined = composeStacks([crm, todo]);\n *\n * // Override strategy — later stacks win\n * const combined = composeStacks([crm, todo], { objectConflict: 'override' });\n *\n * // Merge strategy — fields from later stacks are shallow-merged\n * const combined = composeStacks([crm, todo], { objectConflict: 'merge' });\n * ```\n */\nexport function composeStacks(\n stacks: ObjectStackDefinition[],\n options?: ComposeStacksOptions,\n): ObjectStackDefinition {\n if (stacks.length === 0) return {} as ObjectStackDefinition;\n if (stacks.length === 1) return stacks[0];\n\n const opts = ComposeStacksOptionsSchema.parse(options ?? {});\n\n const composed: Record = {};\n\n // 1. Manifest — pick based on strategy\n composed.manifest = selectManifest(stacks, opts.manifest);\n\n // 2. i18n — last-wins (single object, not array)\n for (let i = stacks.length - 1; i >= 0; i--) {\n if (stacks[i].i18n) {\n composed.i18n = stacks[i].i18n;\n break;\n }\n }\n\n // 3. Objects — use conflict strategy\n const objects = mergeObjects(stacks, opts.objectConflict);\n if (objects) {\n composed.objects = objects;\n }\n\n // 4. All other array fields — simple concatenation\n for (const field of CONCAT_ARRAY_FIELDS) {\n const arrays = stacks\n .map((s) => (s as Record)[field])\n .filter((v): v is unknown[] => Array.isArray(v));\n if (arrays.length > 0) {\n composed[field] = arrays.flat();\n }\n }\n\n return mergeActionsIntoObjects(composed as ObjectStackDefinition);\n}\n\n\n/**\n * 2. RUNTIME CAPABILITIES PROTOCOL (Dynamic)\n * ----------------------------------------------------------------------\n * Describes what the ObjectOS Platform *is* and *can do*.\n * AI Agents read this to understand:\n * - What APIs are available?\n * - What features are enabled?\n * - What limits exist?\n * \n * The capabilities are organized by subsystem for clarity:\n * - ObjectQL: Data Layer capabilities\n * - ObjectUI: User Interface Layer capabilities \n * - ObjectOS: System Layer capabilities\n */\n\n/**\n * ObjectQL Capabilities Schema\n * \n * Defines capabilities related to the Data Layer:\n * - Query operations and advanced SQL features\n * - Data validation and business logic\n * - Database driver support\n * - AI/ML data features\n */\nexport const ObjectQLCapabilitiesSchema = z.object({\n /** Query Capabilities */\n queryFilters: z.boolean().default(true).describe('Supports WHERE clause filtering'),\n queryAggregations: z.boolean().default(true).describe('Supports GROUP BY and aggregation functions'),\n querySorting: z.boolean().default(true).describe('Supports ORDER BY sorting'),\n queryPagination: z.boolean().default(true).describe('Supports LIMIT/OFFSET pagination'),\n queryWindowFunctions: z.boolean().default(false).describe('Supports window functions with OVER clause'),\n querySubqueries: z.boolean().default(false).describe('Supports subqueries'),\n queryDistinct: z.boolean().default(true).describe('Supports SELECT DISTINCT'),\n queryHaving: z.boolean().default(false).describe('Supports HAVING clause for aggregations'),\n queryJoins: z.boolean().default(false).describe('Supports SQL-style joins'),\n \n /** Advanced Data Features */\n fullTextSearch: z.boolean().default(false).describe('Supports full-text search'),\n vectorSearch: z.boolean().default(false).describe('Supports vector embeddings and similarity search for AI/RAG'),\n geoSpatial: z.boolean().default(false).describe('Supports geospatial queries and location fields'),\n \n /** Field Type Support */\n jsonFields: z.boolean().default(true).describe('Supports JSON field types'),\n arrayFields: z.boolean().default(false).describe('Supports array field types'),\n \n /** Data Validation & Logic */\n validationRules: z.boolean().default(true).describe('Supports validation rules'),\n workflows: z.boolean().default(true).describe('Supports workflow automation'),\n triggers: z.boolean().default(true).describe('Supports database triggers'),\n formulas: z.boolean().default(true).describe('Supports formula fields'),\n \n /** Transaction & Performance */\n transactions: z.boolean().default(true).describe('Supports database transactions'),\n bulkOperations: z.boolean().default(true).describe('Supports bulk create/update/delete'),\n \n /** Driver Support */\n supportedDrivers: z.array(z.string()).optional().describe('Available database drivers (e.g., postgresql, mongodb, excel)'),\n});\n\n/**\n * ObjectUI Capabilities Schema\n * \n * Defines capabilities related to the UI Layer:\n * - View rendering (List, Form, Calendar, etc.)\n * - Dashboard and reporting\n * - Theming and customization\n * - UI actions and interactions\n */\nexport const ObjectUICapabilitiesSchema = z.object({\n /** View Types */\n listView: z.boolean().default(true).describe('Supports list/grid views'),\n formView: z.boolean().default(true).describe('Supports form views'),\n kanbanView: z.boolean().default(false).describe('Supports kanban board views'),\n calendarView: z.boolean().default(false).describe('Supports calendar views'),\n ganttView: z.boolean().default(false).describe('Supports Gantt chart views'),\n \n /** Analytics & Reporting */\n dashboards: z.boolean().default(true).describe('Supports dashboard creation'),\n reports: z.boolean().default(true).describe('Supports report generation'),\n charts: z.boolean().default(true).describe('Supports chart widgets'),\n \n /** Customization */\n customPages: z.boolean().default(true).describe('Supports custom page creation'),\n customThemes: z.boolean().default(false).describe('Supports custom theme creation'),\n customComponents: z.boolean().default(false).describe('Supports custom UI components/widgets'),\n \n /** Actions & Interactions */\n customActions: z.boolean().default(true).describe('Supports custom button actions'),\n screenFlows: z.boolean().default(false).describe('Supports interactive screen flows'),\n \n /** Responsive & Accessibility */\n mobileOptimized: z.boolean().default(false).describe('UI optimized for mobile devices'),\n accessibility: z.boolean().default(false).describe('WCAG accessibility support'),\n});\n\n/**\n * ObjectOS Capabilities Schema\n * \n * Defines capabilities related to the System Layer:\n * - Runtime environment and platform features\n * - API and integration capabilities\n * - Security and multi-tenancy\n * - System services (events, jobs, audit)\n */\nexport const ObjectOSCapabilitiesSchema = z.object({\n /** System Identity */\n version: z.string().describe('ObjectOS Kernel Version'),\n environment: z.enum(['development', 'test', 'staging', 'production']),\n \n /** API Surface */\n restApi: z.boolean().default(true).describe('REST API available'),\n graphqlApi: z.boolean().default(false).describe('GraphQL API available'),\n odataApi: z.boolean().default(false).describe('OData API available'),\n \n /** Real-time & Events */\n websockets: z.boolean().default(false).describe('WebSocket support for real-time updates'),\n serverSentEvents: z.boolean().default(false).describe('Server-Sent Events support'),\n eventBus: z.boolean().default(false).describe('Internal event bus for pub/sub'),\n \n /** Integration */\n webhooks: z.boolean().default(true).describe('Outbound webhook support'),\n apiContracts: z.boolean().default(false).describe('API contract definitions'),\n \n /** Security & Access Control */\n authentication: z.boolean().default(true).describe('Authentication system'),\n rbac: z.boolean().default(true).describe('Role-Based Access Control'),\n fieldLevelSecurity: z.boolean().default(false).describe('Field-level permissions'),\n rowLevelSecurity: z.boolean().default(false).describe('Row-level security/sharing rules'),\n \n /** Multi-tenancy */\n multiTenant: z.boolean().default(false).describe('Multi-tenant architecture support'),\n \n /** Platform Services */\n backgroundJobs: z.boolean().default(false).describe('Background job scheduling'),\n auditLogging: z.boolean().default(false).describe('Audit trail logging'),\n fileStorage: z.boolean().default(true).describe('File upload and storage'),\n \n /** Internationalization */\n i18n: z.boolean().default(true).describe('Internationalization support'),\n \n /** Plugin System */\n pluginSystem: z.boolean().default(false).describe('Plugin/extension system'),\n \n /** Active Features & Flags */\n features: z.array(FeatureFlagSchema).optional().describe('Active Feature Flags'),\n \n /** Available APIs */\n apis: z.array(ApiEndpointSchema).optional().describe('Available System & Business APIs'),\n network: z.object({\n graphql: z.boolean().default(false),\n search: z.boolean().default(false),\n websockets: z.boolean().default(false),\n files: z.boolean().default(true),\n analytics: z.boolean().default(false).describe('Is the Analytics/BI engine enabled?'),\n ai: z.boolean().default(false).describe('Is the AI engine enabled?'),\n workflow: z.boolean().default(false).describe('Is the Workflow engine enabled?'),\n notifications: z.boolean().default(false).describe('Is the Notification service enabled?'),\n i18n: z.boolean().default(false).describe('Is the i18n service enabled?'),\n }).optional().describe('Network Capabilities (GraphQL, WS, etc.)'),\n\n /** Introspection */\n systemObjects: z.array(z.string()).optional().describe('List of globally available System Objects'),\n \n /** Constraints (for AI Generation) */\n limits: z.object({\n maxObjects: z.number().optional(),\n maxFieldsPerObject: z.number().optional(),\n maxRecordsPerQuery: z.number().optional(),\n apiRateLimit: z.number().optional(),\n fileUploadSizeLimit: z.number().optional().describe('Max file size in bytes'),\n }).optional()\n});\n\n/**\n * Unified ObjectStack Capabilities Schema\n * \n * Complete capability descriptor for an ObjectStack instance.\n * Organized by architectural layer for clarity and maintainability.\n */\nexport const ObjectStackCapabilitiesSchema = z.object({\n /** Data Layer Capabilities (ObjectQL) */\n data: ObjectQLCapabilitiesSchema.describe('Data Layer capabilities'),\n \n /** User Interface Layer Capabilities (ObjectUI) */\n ui: ObjectUICapabilitiesSchema.describe('UI Layer capabilities'),\n \n /** System/Runtime Layer Capabilities (ObjectOS) */\n system: ObjectOSCapabilitiesSchema.describe('System/Runtime Layer capabilities'),\n});\n\nexport type ObjectQLCapabilities = z.infer;\nexport type ObjectUICapabilities = z.infer;\nexport type ObjectOSCapabilities = z.infer;\nexport type ObjectStackCapabilities = z.infer;\n\n\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Object Definitions Barrel\n * \n * Re-exports all *.object.ts definitions for auto-registration.\n * Hooks (*.hook.ts) and state machines (*.state.ts) are excluded \u2014\n * they are auto-associated by naming convention at runtime.\n */\nexport { Account } from './account.object';\nexport { Campaign } from './campaign.object';\nexport { Case } from './case.object';\nexport { Contact } from './contact.object';\nexport { Contract } from './contract.object';\nexport { Lead } from './lead.object';\nexport { Opportunity } from './opportunity.object';\nexport { Product } from './product.object';\nexport { Quote } from './quote.object';\nexport { Task } from './task.object';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Account = ObjectSchema.create({\n name: 'account',\n label: 'Account',\n pluralLabel: 'Accounts',\n icon: 'building',\n description: 'Companies and organizations doing business with us',\n titleFormat: '{account_number} - {name}',\n compactLayout: ['account_number', 'name', 'type', 'owner'],\n \n fields: {\n // AutoNumber field - Unique account identifier\n account_number: Field.autonumber({\n label: 'Account Number',\n format: 'ACC-{0000}',\n }),\n \n // Basic Information\n name: Field.text({ \n label: 'Account Name', \n required: true, \n searchable: true,\n maxLength: 255,\n }),\n \n // Select fields with custom options\n type: Field.select({\n label: 'Account Type',\n options: [\n { label: 'Prospect', value: 'prospect', color: '#FFA500', default: true },\n { label: 'Customer', value: 'customer', color: '#00AA00' },\n { label: 'Partner', value: 'partner', color: '#0000FF' },\n { label: 'Former Customer', value: 'former', color: '#999999' },\n ]\n }),\n \n industry: Field.select({\n label: 'Industry',\n options: [\n { label: 'Technology', value: 'technology' },\n { label: 'Finance', value: 'finance' },\n { label: 'Healthcare', value: 'healthcare' },\n { label: 'Retail', value: 'retail' },\n { label: 'Manufacturing', value: 'manufacturing' },\n { label: 'Education', value: 'education' },\n ]\n }),\n \n // Number fields\n annual_revenue: Field.currency({ \n label: 'Annual Revenue',\n scale: 2,\n min: 0,\n }),\n \n number_of_employees: Field.number({\n label: 'Employees',\n min: 0,\n }),\n \n // Contact Information\n phone: Field.text({ \n label: 'Phone',\n format: 'phone',\n }),\n \n website: Field.url({\n label: 'Website',\n }),\n \n // Structured Address field (new field type)\n billing_address: Field.address({\n label: 'Billing Address',\n addressFormat: 'international',\n }),\n \n // Office Location (new field type)\n office_location: Field.location({\n label: 'Office Location',\n displayMap: true,\n allowGeocoding: true,\n }),\n \n // Relationship fields\n owner: Field.lookup('user', {\n label: 'Account Owner',\n required: true,\n }),\n \n parent_account: Field.lookup('account', {\n label: 'Parent Account',\n description: 'Parent company in hierarchy',\n }),\n \n // Rich text field\n description: Field.markdown({\n label: 'Description',\n }),\n \n // Boolean field\n is_active: Field.boolean({\n label: 'Active',\n defaultValue: true,\n }),\n \n // Date field\n last_activity_date: Field.date({\n label: 'Last Activity Date',\n readonly: true,\n }),\n \n // Brand color (new field type)\n brand_color: Field.color({\n label: 'Brand Color',\n colorFormat: 'hex',\n presetColors: ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'],\n }),\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['name'] },\n { fields: ['owner'] },\n { fields: ['type', 'is_active'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true, // Track field changes\n searchable: true, // Include in global search\n apiEnabled: true, // Expose via REST/GraphQL\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search', 'export'], // Whitelist allowed API operations\n files: true, // Allow file attachments\n feeds: true, // Enable activity feed/chatter (Chatter-like)\n activities: true, // Enable tasks and events tracking\n trash: true, // Recycle bin support\n mru: true, // Track Most Recently Used\n },\n \n // Validation Rules\n validations: [\n {\n name: 'revenue_positive',\n type: 'script',\n severity: 'error',\n message: 'Annual Revenue must be positive',\n condition: 'annual_revenue < 0',\n },\n {\n name: 'account_name_unique',\n type: 'unique',\n severity: 'error',\n message: 'Account name must be unique',\n fields: ['name'],\n caseSensitive: false,\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'update_last_activity',\n objectName: 'account',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(owner) OR ISCHANGED(type)',\n actions: [\n {\n name: 'set_activity_date',\n type: 'field_update',\n field: 'last_activity_date',\n value: 'TODAY()',\n }\n ],\n active: true,\n }\n ],\n});", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * Campaign Object\n * Represents marketing campaigns\n */\nexport const Campaign = ObjectSchema.create({\n name: 'campaign',\n label: 'Campaign',\n pluralLabel: 'Campaigns',\n icon: 'megaphone',\n description: 'Marketing campaigns and initiatives',\n titleFormat: '{campaign_code} - {name}',\n compactLayout: ['campaign_code', 'name', 'type', 'status', 'start_date'],\n \n fields: {\n // AutoNumber field\n campaign_code: Field.autonumber({\n label: 'Campaign Code',\n format: 'CPG-{0000}',\n }),\n \n // Basic Information\n name: Field.text({ \n label: 'Campaign Name', \n required: true, \n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Type & Channel\n type: Field.select({\n label: 'Campaign Type',\n options: [\n { label: 'Email', value: 'email', default: true },\n { label: 'Webinar', value: 'webinar' },\n { label: 'Trade Show', value: 'trade_show' },\n { label: 'Conference', value: 'conference' },\n { label: 'Direct Mail', value: 'direct_mail' },\n { label: 'Social Media', value: 'social_media' },\n { label: 'Content Marketing', value: 'content' },\n { label: 'Partner Marketing', value: 'partner' },\n ]\n }),\n \n channel: Field.select({\n label: 'Primary Channel',\n options: [\n { label: 'Digital', value: 'digital' },\n { label: 'Social', value: 'social' },\n { label: 'Email', value: 'email' },\n { label: 'Events', value: 'events' },\n { label: 'Partner', value: 'partner' },\n ]\n }),\n \n // Status\n status: Field.select({\n label: 'Status',\n options: [\n { label: 'Planning', value: 'planning', color: '#999999', default: true },\n { label: 'In Progress', value: 'in_progress', color: '#FFA500' },\n { label: 'Completed', value: 'completed', color: '#00AA00' },\n { label: 'Aborted', value: 'aborted', color: '#FF0000' },\n ],\n required: true,\n }),\n \n // Dates\n start_date: Field.date({\n label: 'Start Date',\n required: true,\n }),\n \n end_date: Field.date({\n label: 'End Date',\n required: true,\n }),\n \n // Budget & ROI\n budgeted_cost: Field.currency({ \n label: 'Budgeted Cost',\n scale: 2,\n min: 0,\n }),\n \n actual_cost: Field.currency({ \n label: 'Actual Cost',\n scale: 2,\n min: 0,\n }),\n \n expected_revenue: Field.currency({ \n label: 'Expected Revenue',\n scale: 2,\n min: 0,\n }),\n \n actual_revenue: Field.currency({ \n label: 'Actual Revenue',\n scale: 2,\n min: 0,\n readonly: true,\n }),\n \n // Metrics\n target_size: Field.number({\n label: 'Target Size',\n description: 'Target number of leads/contacts',\n min: 0,\n }),\n \n num_sent: Field.number({\n label: 'Number Sent',\n min: 0,\n readonly: true,\n }),\n \n num_responses: Field.number({\n label: 'Number of Responses',\n min: 0,\n readonly: true,\n }),\n \n num_leads: Field.number({\n label: 'Number of Leads',\n min: 0,\n readonly: true,\n }),\n \n num_converted_leads: Field.number({\n label: 'Converted Leads',\n min: 0,\n readonly: true,\n }),\n \n num_opportunities: Field.number({\n label: 'Opportunities Created',\n min: 0,\n readonly: true,\n }),\n \n num_won_opportunities: Field.number({\n label: 'Won Opportunities',\n min: 0,\n readonly: true,\n }),\n \n // Calculated Metrics (Formula Fields)\n response_rate: Field.formula({\n label: 'Response Rate %',\n expression: 'IF(num_sent > 0, (num_responses / num_sent) * 100, 0)',\n scale: 2,\n }),\n \n roi: Field.formula({\n label: 'ROI %',\n expression: 'IF(actual_cost > 0, ((actual_revenue - actual_cost) / actual_cost) * 100, 0)',\n scale: 2,\n }),\n \n // Relationships\n parent_campaign: Field.lookup('campaign', {\n label: 'Parent Campaign',\n description: 'Parent campaign in hierarchy',\n }),\n \n owner: Field.lookup('user', {\n label: 'Campaign Owner',\n required: true,\n }),\n \n // Campaign Assets\n landing_page_url: Field.url({\n label: 'Landing Page',\n }),\n \n is_active: Field.boolean({\n label: 'Active',\n defaultValue: true,\n }),\n },\n \n // Database indexes\n indexes: [\n { fields: ['name'] },\n { fields: ['type'] },\n { fields: ['status'] },\n { fields: ['start_date'] },\n { fields: ['owner'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search', 'export'],\n files: true,\n feeds: true,\n activities: true,\n trash: true,\n mru: true,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'end_after_start',\n type: 'script',\n severity: 'error',\n message: 'End Date must be after Start Date',\n condition: 'end_date < start_date',\n },\n {\n name: 'actual_cost_within_budget',\n type: 'script',\n severity: 'warning',\n message: 'Actual Cost exceeds Budgeted Cost',\n condition: 'actual_cost > budgeted_cost',\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'campaign_completion_check',\n objectName: 'campaign',\n triggerType: 'on_read',\n criteria: 'end_date < TODAY() AND status = \"in_progress\"',\n actions: [\n {\n name: 'mark_completed',\n type: 'field_update',\n field: 'status',\n value: '\"completed\"',\n }\n ],\n active: true,\n }\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Case = ObjectSchema.create({\n name: 'case',\n label: 'Case',\n pluralLabel: 'Cases',\n icon: 'life-buoy',\n description: 'Customer support cases and service requests',\n \n fields: {\n // Case Information\n case_number: Field.autonumber({\n label: 'Case Number',\n format: 'CASE-{00000}',\n }),\n \n subject: Field.text({\n label: 'Subject',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n required: true,\n }),\n \n // Relationships\n account: Field.lookup('account', {\n label: 'Account',\n }),\n \n contact: Field.lookup('contact', {\n label: 'Contact',\n required: true,\n referenceFilters: ['account = {case.account}'],\n }),\n \n // Case Management\n status: Field.select({\n label: 'Status',\n required: true,\n options: [\n { label: 'New', value: 'new', color: '#808080', default: true },\n { label: 'In Progress', value: 'in_progress', color: '#FFA500' },\n { label: 'Waiting on Customer', value: 'waiting_customer', color: '#FFD700' },\n { label: 'Waiting on Support', value: 'waiting_support', color: '#4169E1' },\n { label: 'Escalated', value: 'escalated', color: '#FF0000' },\n { label: 'Resolved', value: 'resolved', color: '#00AA00' },\n { label: 'Closed', value: 'closed', color: '#006400' },\n ]\n }),\n \n priority: Field.select({\n label: 'Priority',\n required: true,\n options: [\n { label: 'Low', value: 'low', color: '#4169E1', default: true },\n { label: 'Medium', value: 'medium', color: '#FFA500' },\n { label: 'High', value: 'high', color: '#FF4500' },\n { label: 'Critical', value: 'critical', color: '#FF0000' },\n ]\n }),\n \n type: Field.select({\n label: 'Case Type',\n options: [\n { label: 'Question', value: 'question' },\n { label: 'Problem', value: 'problem' },\n { label: 'Feature Request', value: 'feature_request' },\n { label: 'Bug', value: 'bug' },\n ]\n }),\n \n origin: Field.select({\n label: 'Case Origin',\n options: [\n { label: 'Email', value: 'email' },\n { label: 'Phone', value: 'phone' },\n { label: 'Web', value: 'web' },\n { label: 'Chat', value: 'chat' },\n { label: 'Social Media', value: 'social_media' },\n ]\n }),\n \n // Assignment\n owner: Field.lookup('user', {\n label: 'Case Owner',\n required: true,\n }),\n \n // SLA and Metrics\n created_date: Field.datetime({\n label: 'Created Date',\n readonly: true,\n }),\n \n closed_date: Field.datetime({\n label: 'Closed Date',\n readonly: true,\n }),\n \n first_response_date: Field.datetime({\n label: 'First Response Date',\n readonly: true,\n }),\n \n resolution_time_hours: Field.number({\n label: 'Resolution Time (Hours)',\n readonly: true,\n scale: 2,\n }),\n \n sla_due_date: Field.datetime({\n label: 'SLA Due Date',\n }),\n \n is_sla_violated: Field.boolean({\n label: 'SLA Violated',\n defaultValue: false,\n readonly: true,\n }),\n \n // Escalation\n is_escalated: Field.boolean({\n label: 'Escalated',\n defaultValue: false,\n }),\n \n escalation_reason: Field.textarea({\n label: 'Escalation Reason',\n }),\n \n // Related case\n parent_case: Field.lookup('case', {\n label: 'Parent Case',\n description: 'Related parent case',\n }),\n \n // Resolution\n resolution: Field.markdown({\n label: 'Resolution',\n }),\n \n // Customer satisfaction\n customer_rating: Field.rating(5, {\n label: 'Customer Satisfaction',\n description: 'Customer satisfaction rating (1-5 stars)',\n }),\n \n customer_feedback: Field.textarea({\n label: 'Customer Feedback',\n }),\n \n // Customer signature (for case resolution acknowledgment)\n customer_signature: Field.signature({\n label: 'Customer Signature',\n description: 'Digital signature acknowledging case resolution',\n }),\n \n // Internal notes\n internal_notes: Field.markdown({\n label: 'Internal Notes',\n description: 'Internal notes not visible to customer',\n }),\n \n // Flags\n is_closed: Field.boolean({\n label: 'Is Closed',\n defaultValue: false,\n readonly: true,\n }),\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['case_number'], unique: true },\n { fields: ['account'] },\n { fields: ['owner'] },\n { fields: ['status'] },\n { fields: ['priority'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true, // Enable social feed, comments, and mentions\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n titleFormat: '{case_number} - {subject}',\n compactLayout: ['case_number', 'subject', 'account', 'status', 'priority'],\n \n // Removed: list_views and form_views belong in UI configuration, not object definition\n \n validations: [\n {\n name: 'resolution_required_for_closed',\n type: 'script',\n severity: 'error',\n message: 'Resolution is required when closing a case',\n condition: 'status = \"closed\" AND ISBLANK(resolution)',\n },\n {\n name: 'escalation_reason_required',\n type: 'script',\n severity: 'error',\n message: 'Escalation reason is required when escalating a case',\n condition: 'is_escalated = true AND ISBLANK(escalation_reason)',\n },\n {\n name: 'case_status_progression',\n type: 'state_machine',\n severity: 'warning',\n message: 'Invalid status transition',\n field: 'status',\n transitions: {\n 'new': ['in_progress', 'waiting_customer', 'closed'],\n 'in_progress': ['waiting_customer', 'waiting_support', 'escalated', 'resolved'],\n 'waiting_customer': ['in_progress', 'closed'],\n 'waiting_support': ['in_progress', 'escalated'],\n 'escalated': ['in_progress', 'resolved'],\n 'resolved': ['closed', 'in_progress'], // Can reopen\n 'closed': ['in_progress'], // Can reopen\n }\n },\n ],\n \n workflows: [\n {\n name: 'set_closed_flag',\n objectName: 'case',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(status)',\n active: true,\n actions: [\n {\n name: 'update_closed_flag',\n type: 'field_update',\n field: 'is_closed',\n value: 'status = \"closed\"',\n }\n ],\n },\n {\n name: 'set_closed_date',\n objectName: 'case',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(status) AND status = \"closed\"',\n active: true,\n actions: [\n {\n name: 'set_date',\n type: 'field_update',\n field: 'closed_date',\n value: 'NOW()',\n }\n ],\n },\n {\n name: 'calculate_resolution_time',\n objectName: 'case',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(closed_date) AND NOT(ISBLANK(closed_date))',\n active: true,\n actions: [\n {\n name: 'calc_time',\n type: 'field_update',\n field: 'resolution_time_hours',\n value: 'HOURS(created_date, closed_date)',\n }\n ],\n },\n {\n name: 'notify_on_critical',\n objectName: 'case',\n triggerType: 'on_create_or_update',\n criteria: 'priority = \"critical\"',\n active: true,\n actions: [\n {\n name: 'email_support_manager',\n type: 'email_alert',\n template: 'critical_case_alert',\n recipients: ['support_manager@example.com'],\n }\n ],\n },\n {\n name: 'notify_on_escalation',\n objectName: 'case',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(is_escalated) AND is_escalated = true',\n active: true,\n actions: [\n {\n name: 'email_escalation_team',\n type: 'email_alert',\n template: 'case_escalation_alert',\n recipients: ['escalation_team@example.com'],\n }\n ],\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Contact = ObjectSchema.create({\n name: 'contact',\n label: 'Contact',\n pluralLabel: 'Contacts',\n icon: 'user',\n description: 'People associated with accounts',\n \n fields: {\n // Name fields\n salutation: Field.select({\n label: 'Salutation',\n options: [\n { label: 'Mr.', value: 'mr' },\n { label: 'Ms.', value: 'ms' },\n { label: 'Mrs.', value: 'mrs' },\n { label: 'Dr.', value: 'dr' },\n { label: 'Prof.', value: 'prof' },\n ]\n }),\n first_name: Field.text({ \n label: 'First Name',\n required: true,\n searchable: true,\n }),\n last_name: Field.text({ \n label: 'Last Name',\n required: true,\n searchable: true,\n }),\n \n // Formula field - Full name\n full_name: Field.formula({\n label: 'Full Name',\n expression: 'CONCAT(salutation, \" \", first_name, \" \", last_name)',\n }),\n \n // Relationship: Link to Account (Master-Detail)\n account: Field.masterDetail('account', {\n label: 'Account',\n required: true,\n writeRequiresMasterRead: true,\n deleteBehavior: 'cascade', // Delete contacts when account is deleted\n }),\n \n // Contact Information\n email: Field.email({ \n label: 'Email',\n required: true,\n unique: true,\n }),\n \n phone: Field.text({ \n label: 'Phone',\n format: 'phone',\n }),\n \n mobile: Field.text({\n label: 'Mobile',\n format: 'phone',\n }),\n \n // Professional Information\n title: Field.text({\n label: 'Job Title',\n }),\n \n department: Field.select({\n label: 'Department',\n options: [\n { label: 'Executive', value: 'executive' },\n { label: 'Sales', value: 'sales' },\n { label: 'Marketing', value: 'marketing' },\n { label: 'Engineering', value: 'engineering' },\n { label: 'Support', value: 'support' },\n { label: 'Finance', value: 'finance' },\n { label: 'HR', value: 'hr' },\n { label: 'Operations', value: 'operations' },\n ]\n }),\n \n // Relationship fields\n reports_to: Field.lookup('contact', {\n label: 'Reports To',\n description: 'Direct manager/supervisor',\n }),\n \n owner: Field.lookup('user', {\n label: 'Contact Owner',\n required: true,\n }),\n \n // Mailing Address\n mailing_street: Field.textarea({ label: 'Mailing Street' }),\n mailing_city: Field.text({ label: 'Mailing City' }),\n mailing_state: Field.text({ label: 'Mailing State/Province' }),\n mailing_postal_code: Field.text({ label: 'Mailing Postal Code' }),\n mailing_country: Field.text({ label: 'Mailing Country' }),\n \n // Additional Information\n birthdate: Field.date({\n label: 'Birthdate',\n }),\n \n lead_source: Field.select({\n label: 'Lead Source',\n options: [\n { label: 'Web', value: 'web' },\n { label: 'Referral', value: 'referral' },\n { label: 'Event', value: 'event' },\n { label: 'Partner', value: 'partner' },\n { label: 'Advertisement', value: 'advertisement' },\n ]\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Flags\n is_primary: Field.boolean({\n label: 'Primary Contact',\n defaultValue: false,\n description: 'Is this the main contact for the account?',\n }),\n \n do_not_call: Field.boolean({\n label: 'Do Not Call',\n defaultValue: false,\n }),\n \n email_opt_out: Field.boolean({\n label: 'Email Opt Out',\n defaultValue: false,\n }),\n \n // Avatar field\n avatar: Field.avatar({\n label: 'Profile Picture',\n }),\n },\n \n // Enable features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true, // Enable social feed, comments, and mentions\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['account'] },\n { fields: ['email'], unique: true },\n { fields: ['owner'] },\n { fields: ['last_name', 'first_name'] },\n ],\n \n // Display configuration\n titleFormat: '{full_name}',\n compactLayout: ['full_name', 'email', 'account', 'phone'],\n \n // Validation Rules\n validations: [\n {\n name: 'email_required_for_opt_in',\n type: 'script',\n severity: 'error',\n message: 'Email is required when Email Opt Out is not checked',\n condition: 'email_opt_out = false AND ISBLANK(email)',\n },\n {\n name: 'email_unique_per_account',\n type: 'unique',\n severity: 'error',\n message: 'Email must be unique within an account',\n fields: ['email', 'account'],\n caseSensitive: false,\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'welcome_email',\n objectName: 'contact',\n triggerType: 'on_create',\n active: true,\n actions: [\n {\n name: 'send_welcome',\n type: 'email_alert',\n template: 'contact_welcome',\n recipients: ['{contact.email}'],\n }\n ],\n }\n ],\n});", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * Contract Object\n * Represents legal contracts with customers\n */\nexport const Contract = ObjectSchema.create({\n name: 'contract',\n label: 'Contract',\n pluralLabel: 'Contracts',\n icon: 'file-signature',\n description: 'Legal contracts and agreements',\n titleFormat: '{contract_number} - {account.name}',\n compactLayout: ['contract_number', 'account', 'status', 'start_date', 'end_date'],\n \n fields: {\n // AutoNumber field\n contract_number: Field.autonumber({\n label: 'Contract Number',\n format: 'CTR-{0000}',\n }),\n \n // Relationships\n account: Field.lookup('account', {\n label: 'Account',\n required: true,\n }),\n \n contact: Field.lookup('contact', {\n label: 'Primary Contact',\n required: true,\n referenceFilters: [\n 'account = {account}',\n ]\n }),\n \n opportunity: Field.lookup('opportunity', {\n label: 'Related Opportunity',\n referenceFilters: [\n 'account = {account}',\n ]\n }),\n \n owner: Field.lookup('user', {\n label: 'Contract Owner',\n required: true,\n }),\n \n // Status\n status: Field.select({\n label: 'Status',\n options: [\n { label: 'Draft', value: 'draft', color: '#999999', default: true },\n { label: 'In Approval', value: 'in_approval', color: '#FFA500' },\n { label: 'Activated', value: 'activated', color: '#00AA00' },\n { label: 'Expired', value: 'expired', color: '#FF0000' },\n { label: 'Terminated', value: 'terminated', color: '#666666' },\n ],\n required: true,\n }),\n \n // Contract Terms\n contract_term_months: Field.number({\n label: 'Contract Term (Months)',\n required: true,\n min: 1,\n }),\n \n start_date: Field.date({\n label: 'Start Date',\n required: true,\n }),\n \n end_date: Field.date({\n label: 'End Date',\n required: true,\n }),\n \n // Financial\n contract_value: Field.currency({ \n label: 'Contract Value',\n scale: 2,\n min: 0,\n required: true,\n }),\n \n billing_frequency: Field.select({\n label: 'Billing Frequency',\n options: [\n { label: 'Monthly', value: 'monthly', default: true },\n { label: 'Quarterly', value: 'quarterly' },\n { label: 'Annually', value: 'annually' },\n { label: 'One-time', value: 'one_time' },\n ]\n }),\n \n payment_terms: Field.select({\n label: 'Payment Terms',\n options: [\n { label: 'Net 15', value: 'net_15' },\n { label: 'Net 30', value: 'net_30', default: true },\n { label: 'Net 60', value: 'net_60' },\n { label: 'Net 90', value: 'net_90' },\n ]\n }),\n \n // Renewal\n auto_renewal: Field.boolean({\n label: 'Auto Renewal',\n defaultValue: false,\n }),\n \n renewal_notice_days: Field.number({\n label: 'Renewal Notice (Days)',\n min: 0,\n defaultValue: 30,\n }),\n \n // Legal\n contract_type: Field.select({\n label: 'Contract Type',\n options: [\n { label: 'Subscription', value: 'subscription' },\n { label: 'Service Agreement', value: 'service' },\n { label: 'License', value: 'license' },\n { label: 'Partnership', value: 'partnership' },\n { label: 'NDA', value: 'nda' },\n { label: 'MSA', value: 'msa' },\n ]\n }),\n \n signed_date: Field.date({\n label: 'Signed Date',\n }),\n \n signed_by: Field.text({\n label: 'Signed By',\n maxLength: 255,\n }),\n \n document_url: Field.url({\n label: 'Contract Document',\n }),\n \n // Terms & Conditions\n special_terms: Field.markdown({\n label: 'Special Terms',\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Billing Address\n billing_address: Field.address({\n label: 'Billing Address',\n addressFormat: 'international',\n }),\n },\n \n // Database indexes\n indexes: [\n { fields: ['account'] },\n { fields: ['status'] },\n { fields: ['start_date'] },\n { fields: ['end_date'] },\n { fields: ['owner'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search', 'export'],\n files: true,\n feeds: true,\n activities: true,\n trash: true,\n mru: true,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'end_after_start',\n type: 'script',\n severity: 'error',\n message: 'End Date must be after Start Date',\n condition: 'end_date <= start_date',\n },\n {\n name: 'valid_contract_term',\n type: 'script',\n severity: 'error',\n message: 'Contract Term must match date range',\n condition: 'MONTH_DIFF(end_date, start_date) != contract_term_months',\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'contract_expiration_check',\n objectName: 'contract',\n triggerType: 'scheduled',\n schedule: '0 0 * * *', // Daily at midnight\n criteria: 'end_date <= TODAY() AND status = \"activated\"',\n actions: [\n {\n name: 'mark_expired',\n type: 'field_update',\n field: 'status',\n value: '\"expired\"',\n },\n {\n name: 'notify_owner',\n type: 'email_alert',\n template: 'contract_expired',\n recipients: ['{owner}'],\n }\n ],\n active: true,\n },\n {\n name: 'renewal_reminder',\n objectName: 'contract',\n triggerType: 'scheduled',\n schedule: '0 0 * * *', // Daily at midnight\n criteria: 'DAYS_UNTIL(end_date) <= renewal_notice_days AND status = \"activated\"',\n actions: [\n {\n name: 'notify_renewal',\n type: 'email_alert',\n template: 'contract_renewal_reminder',\n recipients: ['{owner}', '{account.owner}'],\n }\n ],\n active: true,\n }\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\nimport { LeadStateMachine } from './lead.state';\n\nexport const Lead = ObjectSchema.create({\n name: 'lead',\n label: 'Lead',\n pluralLabel: 'Leads',\n icon: 'user-plus',\n description: 'Potential customers not yet qualified',\n \n fields: {\n // Personal Information\n salutation: Field.select({\n label: 'Salutation',\n options: [\n { label: 'Mr.', value: 'mr' },\n { label: 'Ms.', value: 'ms' },\n { label: 'Mrs.', value: 'mrs' },\n { label: 'Dr.', value: 'dr' },\n ]\n }),\n \n first_name: Field.text({\n label: 'First Name',\n required: true,\n searchable: true,\n }),\n \n last_name: Field.text({\n label: 'Last Name',\n required: true,\n searchable: true,\n }),\n \n full_name: Field.formula({\n label: 'Full Name',\n expression: 'CONCAT(salutation, \" \", first_name, \" \", last_name)',\n }),\n \n // Company Information\n company: Field.text({\n label: 'Company',\n required: true,\n searchable: true,\n }),\n \n title: Field.text({\n label: 'Job Title',\n }),\n \n industry: Field.select({\n label: 'Industry',\n options: [\n { label: 'Technology', value: 'technology' },\n { label: 'Finance', value: 'finance' },\n { label: 'Healthcare', value: 'healthcare' },\n { label: 'Retail', value: 'retail' },\n { label: 'Manufacturing', value: 'manufacturing' },\n { label: 'Education', value: 'education' },\n ]\n }),\n \n // Contact Information\n email: Field.email({\n label: 'Email',\n required: true,\n unique: true,\n }),\n \n phone: Field.text({\n label: 'Phone',\n format: 'phone',\n }),\n \n mobile: Field.text({\n label: 'Mobile',\n format: 'phone',\n }),\n \n website: Field.url({\n label: 'Website',\n }),\n \n // Lead Qualification\n status: Field.select({\n label: 'Lead Status',\n required: true,\n options: [\n { label: 'New', value: 'new', color: '#808080', default: true },\n { label: 'Contacted', value: 'contacted', color: '#FFA500' },\n { label: 'Qualified', value: 'qualified', color: '#4169E1' },\n { label: 'Unqualified', value: 'unqualified', color: '#FF0000' },\n { label: 'Converted', value: 'converted', color: '#00AA00' },\n ]\n }),\n \n rating: Field.rating(5, {\n label: 'Lead Score',\n description: 'Lead quality score (1-5 stars)',\n allowHalf: true,\n }),\n \n lead_source: Field.select({\n label: 'Lead Source',\n options: [\n { label: 'Web', value: 'web' },\n { label: 'Referral', value: 'referral' },\n { label: 'Event', value: 'event' },\n { label: 'Partner', value: 'partner' },\n { label: 'Advertisement', value: 'advertisement' },\n { label: 'Cold Call', value: 'cold_call' },\n ]\n }),\n \n // Assignment\n owner: Field.lookup('user', {\n label: 'Lead Owner',\n required: true,\n }),\n \n // Conversion tracking\n is_converted: Field.boolean({\n label: 'Converted',\n defaultValue: false,\n readonly: true,\n }),\n \n converted_account: Field.lookup('account', {\n label: 'Converted Account',\n readonly: true,\n }),\n \n converted_contact: Field.lookup('contact', {\n label: 'Converted Contact',\n readonly: true,\n }),\n \n converted_opportunity: Field.lookup('opportunity', {\n label: 'Converted Opportunity',\n readonly: true,\n }),\n \n converted_date: Field.datetime({\n label: 'Converted Date',\n readonly: true,\n }),\n \n // Address (using new address field type)\n address: Field.address({\n label: 'Address',\n addressFormat: 'international',\n }),\n \n // Additional Info\n annual_revenue: Field.currency({\n label: 'Annual Revenue',\n scale: 2,\n }),\n \n number_of_employees: Field.number({\n label: 'Number of Employees',\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Custom notes with rich text formatting\n notes: Field.richtext({\n label: 'Notes',\n description: 'Rich text notes with formatting',\n }),\n \n // Flags\n do_not_call: Field.boolean({\n label: 'Do Not Call',\n defaultValue: false,\n }),\n \n email_opt_out: Field.boolean({\n label: 'Email Opt Out',\n defaultValue: false,\n }),\n },\n\n // Lifecycle State Machine(s)\n // Enforces valid status transitions to prevent AI hallucinations\n // Using `stateMachines` (plural) for future extensibility.\n // For simple objects with one lifecycle, `stateMachine` (singular) is also supported.\n stateMachines: {\n lifecycle: LeadStateMachine,\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['email'], unique: true },\n { fields: ['owner'] },\n { fields: ['status'] },\n { fields: ['company'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true, // Enable social feed, comments, and mentions\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n titleFormat: '{full_name} - {company}',\n compactLayout: ['full_name', 'company', 'email', 'status', 'owner'],\n \n // Removed: list_views and form_views belong in UI configuration, not object definition\n \n validations: [\n {\n name: 'email_required',\n type: 'script',\n severity: 'error',\n message: 'Email is required',\n condition: 'ISBLANK(email)',\n },\n {\n name: 'cannot_edit_converted',\n type: 'script',\n severity: 'error',\n message: 'Cannot edit a converted lead',\n condition: 'is_converted = true AND ISCHANGED(company, email, first_name, last_name)',\n },\n ],\n \n workflows: [\n {\n name: 'auto_qualify_high_score_leads',\n objectName: 'lead',\n triggerType: 'on_create_or_update',\n criteria: 'rating >= 4 AND status = \"new\"',\n active: true,\n actions: [\n {\n name: 'set_status',\n type: 'field_update',\n field: 'status',\n value: 'contacted',\n }\n ],\n },\n {\n name: 'notify_owner_on_high_score_lead',\n objectName: 'lead',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(rating) AND rating >= 4.5',\n active: true,\n actions: [\n {\n name: 'email_owner',\n type: 'email_alert',\n template: 'high_score_lead_notification',\n recipients: ['{owner.email}'],\n }\n ],\n }\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { StateMachineConfig } from '@objectstack/spec/automation';\n\n/**\n * Lead Lifecycle State Machine\n * \n * Defines the strict status transitions for Leads to prevent invalid operations\n * and guide AI agents.\n */\nexport const LeadStateMachine: StateMachineConfig = {\n id: 'lead_process',\n initial: 'new',\n states: {\n new: {\n on: {\n CONTACT: { target: 'contacted', description: 'Log initial contact' },\n DISQUALIFY: { target: 'unqualified', description: 'Mark as unqualified early' }\n },\n meta: {\n aiInstructions: 'New lead. Verify email and phone before contacting. Do not change status until contact is made.'\n }\n },\n contacted: {\n on: {\n QUALIFY: { target: 'qualified', cond: 'has_budget_and_authority' },\n DISQUALIFY: { target: 'unqualified' }\n },\n meta: {\n aiInstructions: 'Engage with the lead. Qualify by asking about budget, authority, need, and timeline (BANT).'\n }\n },\n qualified: {\n on: {\n CONVERT: { target: 'converted', cond: 'is_ready_to_buy' },\n DISQUALIFY: { target: 'unqualified' }\n },\n meta: {\n aiInstructions: 'Lead is qualified. Prepare for conversion to Deal/Opportunity. Check for existing accounts.'\n }\n },\n unqualified: {\n on: {\n REOPEN: { target: 'new', description: 'Re-evaluate lead' }\n },\n meta: {\n aiInstructions: 'Lead is dead. Do not contact unless new information surfaces.'\n }\n },\n converted: {\n type: 'final',\n meta: {\n aiInstructions: 'Lead is converted. No further actions allowed on this record.'\n }\n }\n }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\nimport { OpportunityStateMachine } from './opportunity.state';\n\nexport const Opportunity = ObjectSchema.create({\n name: 'opportunity',\n label: 'Opportunity',\n pluralLabel: 'Opportunities',\n icon: 'dollar-sign',\n description: 'Sales opportunities and deals in the pipeline',\n titleFormat: '{name} - {stage}',\n compactLayout: ['name', 'account', 'amount', 'stage', 'owner'],\n \n fields: {\n // Basic Information\n name: Field.text({ \n label: 'Opportunity Name',\n required: true,\n searchable: true,\n }),\n \n // Relationships\n account: Field.lookup('account', { \n label: 'Account',\n required: true,\n }),\n \n primary_contact: Field.lookup('contact', {\n label: 'Primary Contact',\n referenceFilters: ['account = {opportunity.account}'], // Filter contacts by account\n }),\n \n owner: Field.lookup('user', {\n label: 'Opportunity Owner',\n required: true,\n }),\n \n // Financial Information\n amount: Field.currency({\n label: 'Amount',\n required: true,\n scale: 2,\n min: 0,\n }),\n \n expected_revenue: Field.currency({\n label: 'Expected Revenue',\n scale: 2,\n readonly: true, // Calculated field\n }),\n \n // Sales Process\n stage: Field.select({\n label: 'Stage',\n required: true,\n options: [\n { label: 'Prospecting', value: 'prospecting', color: '#808080', default: true },\n { label: 'Qualification', value: 'qualification', color: '#FFA500' },\n { label: 'Needs Analysis', value: 'needs_analysis', color: '#FFD700' },\n { label: 'Proposal', value: 'proposal', color: '#4169E1' },\n { label: 'Negotiation', value: 'negotiation', color: '#9370DB' },\n { label: 'Closed Won', value: 'closed_won', color: '#00AA00' },\n { label: 'Closed Lost', value: 'closed_lost', color: '#FF0000' },\n ]\n }),\n \n probability: Field.percent({\n label: 'Probability (%)',\n min: 0,\n max: 100,\n defaultValue: 10,\n }),\n \n // Important Dates\n close_date: Field.date({\n label: 'Close Date',\n required: true,\n }),\n \n created_date: Field.datetime({\n label: 'Created Date',\n readonly: true,\n }),\n \n // Additional Classification\n type: Field.select({\n label: 'Opportunity Type',\n options: [\n { label: 'New Business', value: 'new_business' },\n { label: 'Existing Customer - Upgrade', value: 'existing_upgrade' },\n { label: 'Existing Customer - Renewal', value: 'existing_renewal' },\n { label: 'Existing Customer - Expansion', value: 'existing_expansion' },\n ]\n }),\n \n lead_source: Field.select({\n label: 'Lead Source',\n options: [\n { label: 'Web', value: 'web' },\n { label: 'Referral', value: 'referral' },\n { label: 'Event', value: 'event' },\n { label: 'Partner', value: 'partner' },\n { label: 'Advertisement', value: 'advertisement' },\n { label: 'Cold Call', value: 'cold_call' },\n ]\n }),\n \n // Competitor Analysis\n competitors: Field.select({\n label: 'Competitors',\n multiple: true,\n options: [\n { label: 'Competitor A', value: 'competitor_a' },\n { label: 'Competitor B', value: 'competitor_b' },\n { label: 'Competitor C', value: 'competitor_c' },\n ]\n }),\n \n // Campaign tracking\n campaign: Field.lookup('campaign', {\n label: 'Campaign',\n description: 'Marketing campaign that generated this opportunity',\n }),\n \n // Sales cycle metrics\n days_in_stage: Field.number({\n label: 'Days in Current Stage',\n readonly: true,\n }),\n \n // Additional information\n description: Field.markdown({\n label: 'Description',\n }),\n \n next_step: Field.textarea({\n label: 'Next Steps',\n }),\n \n // Flags\n is_private: Field.boolean({\n label: 'Private',\n defaultValue: false,\n }),\n \n forecast_category: Field.select({\n label: 'Forecast Category',\n options: [\n { label: 'Pipeline', value: 'pipeline' },\n { label: 'Best Case', value: 'best_case' },\n { label: 'Commit', value: 'commit' },\n { label: 'Omitted', value: 'omitted' },\n { label: 'Closed', value: 'closed' },\n ]\n }),\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['name'] },\n { fields: ['account'] },\n { fields: ['owner'] },\n { fields: ['stage'] },\n { fields: ['close_date'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true, // Critical for tracking stage changes\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'aggregate', 'search'], // Whitelist allowed API operations\n files: true, // Attach proposals, contracts\n feeds: true, // Team collaboration (Chatter-like)\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n // Removed: list_views and form_views belong in UI configuration, not object definition\n \n // Lifecycle State Machine(s)\n stateMachines: {\n lifecycle: OpportunityStateMachine,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'close_date_future',\n type: 'script',\n severity: 'warning',\n message: 'Close date should not be in the past unless opportunity is closed',\n condition: 'close_date < TODAY() AND stage != \"closed_won\" AND stage != \"closed_lost\"',\n },\n {\n name: 'amount_positive',\n type: 'script',\n severity: 'error',\n message: 'Amount must be greater than zero',\n condition: 'amount <= 0',\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'update_probability_by_stage',\n objectName: 'opportunity',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(stage)',\n active: true,\n actions: [\n {\n name: 'set_probability',\n type: 'field_update',\n field: 'probability',\n value: `CASE(stage,\n \"prospecting\", 10,\n \"qualification\", 25,\n \"needs_analysis\", 40,\n \"proposal\", 60,\n \"negotiation\", 80,\n \"closed_won\", 100,\n \"closed_lost\", 0,\n probability\n )`,\n },\n {\n name: 'set_forecast_category',\n type: 'field_update',\n field: 'forecast_category',\n value: `CASE(stage,\n \"prospecting\", \"pipeline\",\n \"qualification\", \"pipeline\",\n \"needs_analysis\", \"best_case\",\n \"proposal\", \"commit\",\n \"negotiation\", \"commit\",\n \"closed_won\", \"closed\",\n \"closed_lost\", \"omitted\",\n forecast_category\n )`,\n }\n ],\n },\n {\n name: 'calculate_expected_revenue',\n objectName: 'opportunity',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(amount) OR ISCHANGED(probability)',\n active: true,\n actions: [\n {\n name: 'update_expected_revenue',\n type: 'field_update',\n field: 'expected_revenue',\n value: 'amount * (probability / 100)',\n }\n ],\n },\n {\n name: 'notify_on_large_deal_won',\n objectName: 'opportunity',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(stage) AND stage = \"closed_won\" AND amount > 100000',\n active: true,\n actions: [\n {\n name: 'notify_management',\n type: 'email_alert',\n template: 'large_deal_won',\n recipients: ['sales_management@example.com'],\n }\n ],\n }\n ],\n});", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { StateMachineConfig } from '@objectstack/spec/automation';\n\n/**\n * Opportunity Sales Pipeline State Machine\n * \n * Defines the strict stage transitions for Opportunities to enforce\n * a valid sales process and guide AI agents.\n */\nexport const OpportunityStateMachine: StateMachineConfig = {\n id: 'opportunity_pipeline',\n initial: 'prospecting',\n states: {\n prospecting: {\n on: {\n QUALIFY: { target: 'qualification', description: 'Initial qualification passed' },\n LOSE: { target: 'closed_lost', description: 'Lost at prospecting stage' },\n },\n meta: {\n aiInstructions: 'New opportunity. Identify decision makers and confirm budget exists before advancing.',\n },\n },\n qualification: {\n on: {\n ANALYZE: { target: 'needs_analysis', description: 'Begin needs analysis' },\n LOSE: { target: 'closed_lost', description: 'Lost at qualification stage' },\n },\n meta: {\n aiInstructions: 'Qualifying opportunity. Gather BANT (Budget, Authority, Need, Timeline) details.',\n },\n },\n needs_analysis: {\n on: {\n PROPOSE: { target: 'proposal', description: 'Submit proposal' },\n LOSE: { target: 'closed_lost', description: 'Lost during needs analysis' },\n },\n meta: {\n aiInstructions: 'Analyzing customer needs. Document requirements and pain points before proposing.',\n },\n },\n proposal: {\n on: {\n NEGOTIATE: { target: 'negotiation', description: 'Enter negotiation' },\n LOSE: { target: 'closed_lost', description: 'Proposal rejected' },\n },\n meta: {\n aiInstructions: 'Proposal submitted. Follow up on pricing and terms. Prepare for negotiation.',\n },\n },\n negotiation: {\n on: {\n WIN: { target: 'closed_won', description: 'Deal won' },\n LOSE: { target: 'closed_lost', description: 'Lost in negotiation' },\n },\n meta: {\n aiInstructions: 'In negotiation. Focus on closing. Escalate blockers to management if needed.',\n },\n },\n closed_won: {\n type: 'final',\n meta: {\n aiInstructions: 'Deal won. No further stage changes allowed. Trigger contract creation.',\n },\n },\n closed_lost: {\n type: 'final',\n meta: {\n aiInstructions: 'Deal lost. Record loss reason. No further stage changes allowed.',\n },\n },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * Product Object\n * Represents products/services offered by the company\n */\nexport const Product = ObjectSchema.create({\n name: 'product',\n label: 'Product',\n pluralLabel: 'Products',\n icon: 'box',\n description: 'Products and services offered by the company',\n titleFormat: '{product_code} - {name}',\n compactLayout: ['product_code', 'name', 'category', 'is_active'],\n \n fields: {\n // AutoNumber field - Unique product identifier\n product_code: Field.autonumber({\n label: 'Product Code',\n format: 'PRD-{0000}',\n }),\n \n // Basic Information\n name: Field.text({ \n label: 'Product Name', \n required: true, \n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Categorization\n category: Field.select({\n label: 'Category',\n options: [\n { label: 'Software', value: 'software', default: true },\n { label: 'Hardware', value: 'hardware' },\n { label: 'Service', value: 'service' },\n { label: 'Subscription', value: 'subscription' },\n { label: 'Support', value: 'support' },\n ]\n }),\n \n family: Field.select({\n label: 'Product Family',\n options: [\n { label: 'Enterprise Solutions', value: 'enterprise' },\n { label: 'SMB Solutions', value: 'smb' },\n { label: 'Professional Services', value: 'services' },\n { label: 'Cloud Services', value: 'cloud' },\n ]\n }),\n \n // Pricing\n list_price: Field.currency({ \n label: 'List Price',\n scale: 2,\n min: 0,\n required: true,\n }),\n \n cost: Field.currency({ \n label: 'Cost',\n scale: 2,\n min: 0,\n }),\n \n // SKU and Inventory\n sku: Field.text({\n label: 'SKU',\n maxLength: 50,\n unique: true,\n }),\n \n quantity_on_hand: Field.number({\n label: 'Quantity on Hand',\n min: 0,\n defaultValue: 0,\n }),\n \n reorder_point: Field.number({\n label: 'Reorder Point',\n min: 0,\n }),\n \n // Status\n is_active: Field.boolean({\n label: 'Active',\n defaultValue: true,\n }),\n \n is_taxable: Field.boolean({\n label: 'Taxable',\n defaultValue: true,\n }),\n \n // Relationships\n product_manager: Field.lookup('user', {\n label: 'Product Manager',\n }),\n \n // Images and Assets\n image_url: Field.url({\n label: 'Product Image',\n }),\n \n datasheet_url: Field.url({\n label: 'Datasheet URL',\n }),\n },\n \n // Database indexes\n indexes: [\n { fields: ['name'] },\n { fields: ['sku'], unique: true },\n { fields: ['category'] },\n { fields: ['is_active'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search'],\n files: true,\n feeds: true,\n trash: true,\n mru: true,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'price_positive',\n type: 'script',\n severity: 'error',\n message: 'List Price must be positive',\n condition: 'list_price < 0',\n },\n {\n name: 'cost_less_than_price',\n type: 'script',\n severity: 'warning',\n message: 'Cost should be less than List Price',\n condition: 'cost >= list_price',\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * Quote Object\n * Represents price quotes sent to customers\n */\nexport const Quote = ObjectSchema.create({\n name: 'quote',\n label: 'Quote',\n pluralLabel: 'Quotes',\n icon: 'file-text',\n description: 'Price quotes for customers',\n titleFormat: '{quote_number} - {name}',\n compactLayout: ['quote_number', 'name', 'account', 'status', 'total_price'],\n \n fields: {\n // AutoNumber field\n quote_number: Field.autonumber({\n label: 'Quote Number',\n format: 'QTE-{0000}',\n }),\n \n // Basic Information\n name: Field.text({ \n label: 'Quote Name', \n required: true, \n searchable: true,\n maxLength: 255,\n }),\n \n // Relationships\n account: Field.lookup('account', {\n label: 'Account',\n required: true,\n }),\n \n contact: Field.lookup('contact', {\n label: 'Contact',\n required: true,\n referenceFilters: [\n 'account = {account}',\n ]\n }),\n \n opportunity: Field.lookup('opportunity', {\n label: 'Opportunity',\n referenceFilters: [\n 'account = {account}',\n ]\n }),\n \n owner: Field.lookup('user', {\n label: 'Quote Owner',\n required: true,\n }),\n \n // Status\n status: Field.select({\n label: 'Status',\n options: [\n { label: 'Draft', value: 'draft', color: '#999999', default: true },\n { label: 'In Review', value: 'in_review', color: '#FFA500' },\n { label: 'Presented', value: 'presented', color: '#4169E1' },\n { label: 'Accepted', value: 'accepted', color: '#00AA00' },\n { label: 'Rejected', value: 'rejected', color: '#FF0000' },\n { label: 'Expired', value: 'expired', color: '#666666' },\n ],\n required: true,\n }),\n \n // Dates\n quote_date: Field.date({\n label: 'Quote Date',\n required: true,\n defaultValue: 'TODAY()',\n }),\n \n expiration_date: Field.date({\n label: 'Expiration Date',\n required: true,\n }),\n \n // Pricing\n subtotal: Field.currency({ \n label: 'Subtotal',\n scale: 2,\n readonly: true,\n }),\n \n discount: Field.percent({\n label: 'Discount %',\n scale: 2,\n min: 0,\n max: 100,\n }),\n \n discount_amount: Field.currency({ \n label: 'Discount Amount',\n scale: 2,\n readonly: true,\n }),\n \n tax: Field.currency({ \n label: 'Tax',\n scale: 2,\n }),\n \n shipping_handling: Field.currency({ \n label: 'Shipping & Handling',\n scale: 2,\n }),\n \n total_price: Field.currency({ \n label: 'Total Price',\n scale: 2,\n readonly: true,\n }),\n \n // Terms\n payment_terms: Field.select({\n label: 'Payment Terms',\n options: [\n { label: 'Net 15', value: 'net_15' },\n { label: 'Net 30', value: 'net_30', default: true },\n { label: 'Net 60', value: 'net_60' },\n { label: 'Net 90', value: 'net_90' },\n { label: 'Due on Receipt', value: 'due_on_receipt' },\n ]\n }),\n \n shipping_terms: Field.text({\n label: 'Shipping Terms',\n maxLength: 255,\n }),\n \n // Billing & Shipping Address\n billing_address: Field.address({\n label: 'Billing Address',\n addressFormat: 'international',\n }),\n \n shipping_address: Field.address({\n label: 'Shipping Address',\n addressFormat: 'international',\n }),\n \n // Notes\n description: Field.markdown({\n label: 'Description',\n }),\n \n internal_notes: Field.textarea({\n label: 'Internal Notes',\n }),\n },\n \n // Database indexes\n indexes: [\n { fields: ['account'] },\n { fields: ['opportunity'] },\n { fields: ['owner'] },\n { fields: ['status'] },\n { fields: ['quote_date'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search', 'export'],\n files: true,\n feeds: true,\n activities: true,\n trash: true,\n mru: true,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'expiration_after_quote',\n type: 'script',\n severity: 'error',\n message: 'Expiration Date must be after Quote Date',\n condition: 'expiration_date <= quote_date',\n },\n {\n name: 'valid_discount',\n type: 'script',\n severity: 'error',\n message: 'Discount cannot exceed 100%',\n condition: 'discount > 100',\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'quote_expired_check',\n objectName: 'quote',\n triggerType: 'on_read',\n criteria: 'expiration_date < TODAY() AND status NOT IN (\"accepted\", \"rejected\", \"expired\")',\n actions: [\n {\n name: 'mark_expired',\n type: 'field_update',\n field: 'status',\n value: '\"expired\"',\n }\n ],\n active: true,\n }\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Task = ObjectSchema.create({\n name: 'task',\n label: 'Task',\n pluralLabel: 'Tasks',\n icon: 'check-square',\n description: 'Activities and to-do items',\n \n fields: {\n // Task Information\n subject: Field.text({\n label: 'Subject',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Task Management\n status: Field.select({\n label: 'Status',\n required: true,\n options: [\n { label: 'Not Started', value: 'not_started', color: '#808080', default: true },\n { label: 'In Progress', value: 'in_progress', color: '#FFA500' },\n { label: 'Waiting', value: 'waiting', color: '#FFD700' },\n { label: 'Completed', value: 'completed', color: '#00AA00' },\n { label: 'Deferred', value: 'deferred', color: '#999999' },\n ]\n }),\n \n priority: Field.select({\n label: 'Priority',\n required: true,\n options: [\n { label: 'Low', value: 'low', color: '#4169E1', default: true },\n { label: 'Normal', value: 'normal', color: '#00AA00' },\n { label: 'High', value: 'high', color: '#FFA500' },\n { label: 'Urgent', value: 'urgent', color: '#FF0000' },\n ]\n }),\n \n type: Field.select({\n label: 'Task Type',\n options: [\n { label: 'Call', value: 'call' },\n { label: 'Email', value: 'email' },\n { label: 'Meeting', value: 'meeting' },\n { label: 'Follow-up', value: 'follow_up' },\n { label: 'Demo', value: 'demo' },\n { label: 'Other', value: 'other' },\n ]\n }),\n \n // Dates\n due_date: Field.date({\n label: 'Due Date',\n }),\n \n reminder_date: Field.datetime({\n label: 'Reminder Date/Time',\n }),\n \n completed_date: Field.datetime({\n label: 'Completed Date',\n readonly: true,\n }),\n \n // Assignment\n owner: Field.lookup('user', {\n label: 'Assigned To',\n required: true,\n }),\n \n // Related To (Polymorphic relationship - can link to multiple object types)\n related_to_type: Field.select({\n label: 'Related To Type',\n options: [\n { label: 'Account', value: 'account' },\n { label: 'Contact', value: 'contact' },\n { label: 'Opportunity', value: 'opportunity' },\n { label: 'Lead', value: 'lead' },\n { label: 'Case', value: 'case' },\n ]\n }),\n \n related_to_account: Field.lookup('account', {\n label: 'Related Account',\n }),\n \n related_to_contact: Field.lookup('contact', {\n label: 'Related Contact',\n }),\n \n related_to_opportunity: Field.lookup('opportunity', {\n label: 'Related Opportunity',\n }),\n \n related_to_lead: Field.lookup('lead', {\n label: 'Related Lead',\n }),\n \n related_to_case: Field.lookup('case', {\n label: 'Related Case',\n }),\n \n // Recurrence (for recurring tasks)\n is_recurring: Field.boolean({\n label: 'Recurring Task',\n defaultValue: false,\n }),\n \n recurrence_type: Field.select({\n label: 'Recurrence Type',\n options: [\n { label: 'Daily', value: 'daily' },\n { label: 'Weekly', value: 'weekly' },\n { label: 'Monthly', value: 'monthly' },\n { label: 'Yearly', value: 'yearly' },\n ]\n }),\n \n recurrence_interval: Field.number({\n label: 'Recurrence Interval',\n defaultValue: 1,\n min: 1,\n }),\n \n recurrence_end_date: Field.date({\n label: 'Recurrence End Date',\n }),\n \n // Flags\n is_completed: Field.boolean({\n label: 'Is Completed',\n defaultValue: false,\n readonly: true,\n }),\n \n is_overdue: Field.boolean({\n label: 'Is Overdue',\n defaultValue: false,\n readonly: true,\n }),\n \n // Progress\n progress_percent: Field.percent({\n label: 'Progress (%)',\n min: 0,\n max: 100,\n defaultValue: 0,\n }),\n \n // Time tracking\n estimated_hours: Field.number({\n label: 'Estimated Hours',\n scale: 2,\n min: 0,\n }),\n \n actual_hours: Field.number({\n label: 'Actual Hours',\n scale: 2,\n min: 0,\n }),\n },\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true, // Enable social feed, comments, and mentions\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['status'] },\n { fields: ['priority'] },\n { fields: ['owner'] },\n { fields: ['due_date'] },\n ],\n \n titleFormat: '{subject}',\n compactLayout: ['subject', 'status', 'priority', 'due_date', 'owner'],\n \n // Removed: list_views and form_views belong in UI configuration, not object definition\n \n validations: [\n {\n name: 'completed_date_required',\n type: 'script',\n severity: 'error',\n message: 'Completed date is required when status is Completed',\n condition: 'status = \"completed\" AND ISBLANK(completed_date)',\n },\n {\n name: 'recurrence_fields_required',\n type: 'script',\n severity: 'error',\n message: 'Recurrence type is required for recurring tasks',\n condition: 'is_recurring = true AND ISBLANK(recurrence_type)',\n },\n {\n name: 'related_to_required',\n type: 'script',\n severity: 'warning',\n message: 'At least one related record should be selected',\n condition: 'ISBLANK(related_to_account) AND ISBLANK(related_to_contact) AND ISBLANK(related_to_opportunity) AND ISBLANK(related_to_lead) AND ISBLANK(related_to_case)',\n },\n ],\n \n workflows: [\n {\n name: 'set_completed_flag',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(status)',\n active: true,\n actions: [\n {\n name: 'update_completed_flag',\n type: 'field_update',\n field: 'is_completed',\n value: 'status = \"completed\"',\n }\n ],\n },\n {\n name: 'set_completed_date',\n objectName: 'task',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(status) AND status = \"completed\"',\n active: true,\n actions: [\n {\n name: 'set_date',\n type: 'field_update',\n field: 'completed_date',\n value: 'NOW()',\n },\n {\n name: 'set_progress',\n type: 'field_update',\n field: 'progress_percent',\n value: '100',\n }\n ],\n },\n {\n name: 'check_overdue',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'due_date < TODAY() AND is_completed = false',\n active: true,\n actions: [\n {\n name: 'set_overdue_flag',\n type: 'field_update',\n field: 'is_overdue',\n value: 'true',\n }\n ],\n },\n {\n name: 'notify_on_urgent',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'priority = \"urgent\" AND is_completed = false',\n active: true,\n actions: [\n {\n name: 'email_owner',\n type: 'email_alert',\n template: 'urgent_task_alert',\n recipients: ['{owner.email}'],\n }\n ],\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * API Definitions Barrel\n */\nexport { LeadConvertApi } from './lead-convert.api';\nexport { PipelineStatsApi } from './pipeline-stats.api';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ApiEndpoint } from '@objectstack/spec/api';\n\n/** POST /api/v1/crm/leads/convert */\nexport const LeadConvertApi = ApiEndpoint.create({\n name: 'lead_convert',\n path: '/api/v1/crm/leads/convert',\n method: 'POST',\n summary: 'Convert Lead to Account/Contact',\n type: 'flow',\n target: 'flow_lead_conversion_v2',\n inputMapping: [\n { source: 'body.leadId', target: 'leadRecordId' },\n { source: 'body.ownerId', target: 'newOwnerId' },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ApiEndpoint } from '@objectstack/spec/api';\n\n/** GET /api/v1/crm/stats/pipeline */\nexport const PipelineStatsApi = ApiEndpoint.create({\n name: 'get_pipeline_stats',\n path: '/api/v1/crm/stats/pipeline',\n method: 'GET',\n summary: 'Get Pipeline Statistics',\n description: 'Returns the total value of open opportunities grouped by stage',\n type: 'script',\n target: 'server/scripts/pipeline_stats.ts',\n authRequired: true,\n cacheTtl: 300,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Action Definitions Barrel\n *\n * Exports action metadata definitions only. Used by `Object.values()` in\n * objectstack.config.ts to auto-collect all action declarations for defineStack().\n *\n * **Handler functions** are exported from `./handlers/` \u2014 see register-handlers.ts\n * for the complete registration flow.\n */\nexport { EscalateCaseAction, CloseCaseAction } from './case.actions';\nexport { MarkPrimaryContactAction, SendEmailAction } from './contact.actions';\nexport { LogCallAction, ExportToCsvAction } from './global.actions';\nexport { ConvertLeadAction, CreateCampaignAction } from './lead.actions';\nexport { CloneOpportunityAction, MassUpdateStageAction } from './opportunity.actions';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Escalate Case */\nexport const EscalateCaseAction: Action = {\n name: 'escalate_case',\n label: 'Escalate Case',\n objectName: 'case',\n icon: 'alert-triangle',\n type: 'modal',\n target: 'escalate_case_modal',\n locations: ['record_header', 'list_item'],\n visible: 'is_escalated = false AND is_closed = false',\n params: [\n {\n name: 'reason',\n label: 'Escalation Reason',\n type: 'textarea',\n required: true,\n }\n ],\n confirmText: 'This will escalate the case to the escalation team. Continue?',\n successMessage: 'Case escalated successfully!',\n refreshAfter: true,\n};\n\n/** Close Case */\nexport const CloseCaseAction: Action = {\n name: 'close_case',\n label: 'Close Case',\n objectName: 'case',\n icon: 'check-circle',\n type: 'modal',\n target: 'close_case_modal',\n locations: ['record_header'],\n visible: 'is_closed = false',\n params: [\n {\n name: 'resolution',\n label: 'Resolution',\n type: 'textarea',\n required: true,\n }\n ],\n confirmText: 'Are you sure you want to close this case?',\n successMessage: 'Case closed successfully!',\n refreshAfter: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Mark Contact as Primary */\nexport const MarkPrimaryContactAction: Action = {\n name: 'mark_primary',\n label: 'Mark as Primary Contact',\n objectName: 'contact',\n icon: 'star',\n type: 'script',\n target: 'markAsPrimaryContact',\n locations: ['record_header', 'list_item'],\n visible: 'is_primary = false',\n confirmText: 'Mark this contact as the primary contact for the account?',\n successMessage: 'Contact marked as primary!',\n refreshAfter: true,\n};\n\n/** Send Email to Contact */\nexport const SendEmailAction: Action = {\n name: 'send_email',\n label: 'Send Email',\n objectName: 'contact',\n icon: 'mail',\n type: 'modal',\n target: 'email_composer',\n locations: ['record_header', 'list_item'],\n visible: 'email_opt_out = false',\n refreshAfter: false,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Log a Call */\nexport const LogCallAction: Action = {\n name: 'log_call',\n label: 'Log a Call',\n icon: 'phone',\n type: 'modal',\n target: 'call_log_modal',\n locations: ['record_header', 'list_item', 'record_related'],\n params: [\n {\n name: 'subject',\n label: 'Call Subject',\n type: 'text',\n required: true,\n },\n {\n name: 'duration',\n label: 'Duration (minutes)',\n type: 'number',\n required: true,\n },\n {\n name: 'notes',\n label: 'Call Notes',\n type: 'textarea',\n required: false,\n }\n ],\n successMessage: 'Call logged successfully!',\n refreshAfter: true,\n};\n\n/** Export to CSV */\nexport const ExportToCsvAction: Action = {\n name: 'export_csv',\n label: 'Export to CSV',\n icon: 'download',\n type: 'script',\n target: 'exportToCSV',\n locations: ['list_toolbar'],\n successMessage: 'Export completed!',\n refreshAfter: false,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Convert Lead to Account, Contact, and Opportunity */\nexport const ConvertLeadAction: Action = {\n name: 'convert_lead',\n label: 'Convert Lead',\n objectName: 'lead',\n icon: 'arrow-right-circle',\n type: 'flow',\n target: 'lead_conversion',\n locations: ['record_header', 'list_item'],\n visible: 'status = \"qualified\" AND is_converted = false',\n confirmText: 'Are you sure you want to convert this lead?',\n successMessage: 'Lead converted successfully!',\n refreshAfter: true,\n};\n\n/** Create Campaign from Leads */\nexport const CreateCampaignAction: Action = {\n name: 'create_campaign',\n label: 'Add to Campaign',\n objectName: 'lead',\n icon: 'send',\n type: 'modal',\n target: 'add_to_campaign_modal',\n locations: ['list_toolbar'],\n params: [\n {\n name: 'campaign',\n label: 'Campaign',\n type: 'lookup',\n required: true,\n }\n ],\n successMessage: 'Leads added to campaign!',\n refreshAfter: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Clone Opportunity */\nexport const CloneOpportunityAction: Action = {\n name: 'clone_opportunity',\n label: 'Clone Opportunity',\n objectName: 'opportunity',\n icon: 'copy',\n type: 'script',\n target: 'cloneRecord',\n locations: ['record_header', 'record_more'],\n successMessage: 'Opportunity cloned successfully!',\n refreshAfter: true,\n};\n\n/** Mass Update Opportunity Stage */\nexport const MassUpdateStageAction: Action = {\n name: 'mass_update_stage',\n label: 'Update Stage',\n objectName: 'opportunity',\n icon: 'layers',\n type: 'modal',\n target: 'mass_update_stage_modal',\n locations: ['list_toolbar'],\n params: [\n {\n name: 'stage',\n label: 'New Stage',\n type: 'select',\n required: true,\n options: [\n { label: 'Prospecting', value: 'prospecting' },\n { label: 'Qualification', value: 'qualification' },\n { label: 'Needs Analysis', value: 'needs_analysis' },\n { label: 'Proposal', value: 'proposal' },\n { label: 'Negotiation', value: 'negotiation' },\n { label: 'Closed Won', value: 'closed_won' },\n { label: 'Closed Lost', value: 'closed_lost' },\n ]\n }\n ],\n successMessage: 'Opportunities updated successfully!',\n refreshAfter: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Dashboard Definitions Barrel\n */\nexport { ExecutiveDashboard } from './executive.dashboard';\nexport { SalesDashboard } from './sales.dashboard';\nexport { ServiceDashboard } from './service.dashboard';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Dashboard } from '@objectstack/spec/ui';\n\nexport const ExecutiveDashboard: Dashboard = {\n name: 'executive_dashboard',\n label: 'Executive Overview',\n description: 'High-level business metrics',\n \n widgets: [\n // Row 1: Revenue Metrics\n {\n id: 'total_revenue_ytd',\n title: 'Total Revenue (YTD)',\n type: 'metric',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{current_year_start}' } },\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 0, w: 3, h: 2 },\n options: { prefix: '$', color: '#00AA00' }\n },\n {\n id: 'total_accounts',\n title: 'Total Accounts',\n type: 'metric',\n object: 'account',\n filter: { is_active: true },\n aggregate: 'count',\n layout: { x: 3, y: 0, w: 3, h: 2 },\n options: { color: '#4169E1' }\n },\n {\n id: 'total_contacts',\n title: 'Total Contacts',\n type: 'metric',\n object: 'contact',\n aggregate: 'count',\n layout: { x: 6, y: 0, w: 3, h: 2 },\n options: { color: '#9370DB' }\n },\n {\n id: 'total_leads',\n title: 'Total Leads',\n type: 'metric',\n object: 'lead',\n filter: { is_converted: false },\n aggregate: 'count',\n layout: { x: 9, y: 0, w: 3, h: 2 },\n options: { color: '#FFA500' }\n },\n \n // Row 2: Revenue Analysis\n {\n id: 'revenue_by_industry',\n title: 'Revenue by Industry',\n type: 'bar',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{current_year_start}' } },\n categoryField: 'account.industry',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 2, w: 6, h: 4 },\n },\n {\n id: 'quarterly_revenue_trend',\n title: 'Quarterly Revenue Trend',\n type: 'line',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{last_4_quarters}' } },\n categoryField: 'close_date',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 6, y: 2, w: 6, h: 4 },\n options: { dateGranularity: 'quarter' }\n },\n \n // Row 3: Customer & Activity Metrics\n {\n id: 'new_accounts_by_month',\n title: 'New Accounts by Month',\n type: 'bar',\n object: 'account',\n filter: { created_date: { $gte: '{last_6_months}' } },\n categoryField: 'created_date',\n aggregate: 'count',\n layout: { x: 0, y: 6, w: 4, h: 4 },\n options: { dateGranularity: 'month' }\n },\n {\n id: 'lead_conversion_rate',\n title: 'Lead Conversion Rate',\n type: 'metric',\n object: 'lead',\n valueField: 'is_converted',\n aggregate: 'avg',\n layout: { x: 4, y: 6, w: 4, h: 4 },\n options: { suffix: '%', color: '#00AA00' }\n },\n {\n id: 'top_accounts_by_revenue',\n title: 'Top Accounts by Revenue',\n type: 'table',\n object: 'account',\n aggregate: 'count',\n layout: { x: 8, y: 6, w: 4, h: 4 },\n options: {\n columns: ['name', 'annual_revenue', 'type'],\n sortBy: 'annual_revenue',\n sortOrder: 'desc',\n limit: 10,\n }\n },\n ]\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Dashboard } from '@objectstack/spec/ui';\n\nexport const SalesDashboard: Dashboard = {\n name: 'sales_dashboard',\n label: 'Sales Performance',\n description: 'Key sales metrics and pipeline overview',\n \n widgets: [\n // Row 1: Key Metrics\n {\n id: 'total_pipeline_value',\n title: 'Total Pipeline Value',\n type: 'metric',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 0, w: 3, h: 2 },\n options: { prefix: '$', color: '#4169E1' }\n },\n {\n id: 'closed_won_this_quarter',\n title: 'Closed Won This Quarter',\n type: 'metric',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{current_quarter_start}' } },\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 3, y: 0, w: 3, h: 2 },\n options: { prefix: '$', color: '#00AA00' }\n },\n {\n id: 'open_opportunities',\n title: 'Open Opportunities',\n type: 'metric',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n aggregate: 'count',\n layout: { x: 6, y: 0, w: 3, h: 2 },\n options: { color: '#FFA500' }\n },\n {\n id: 'win_rate',\n title: 'Win Rate',\n type: 'metric',\n object: 'opportunity',\n filter: { close_date: { $gte: '{current_quarter_start}' } },\n valueField: 'stage',\n aggregate: 'count',\n layout: { x: 9, y: 0, w: 3, h: 2 },\n options: { suffix: '%', color: '#9370DB' }\n },\n \n // Row 2: Pipeline Analysis\n {\n id: 'pipeline_by_stage',\n title: 'Pipeline by Stage',\n type: 'funnel',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n categoryField: 'stage',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 2, w: 6, h: 4 },\n options: { showValues: true }\n },\n {\n id: 'opportunities_by_owner',\n title: 'Opportunities by Owner',\n type: 'bar',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n categoryField: 'owner',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 6, y: 2, w: 6, h: 4 },\n options: { horizontal: true }\n },\n \n // Row 3: Trends\n {\n id: 'monthly_revenue_trend',\n title: 'Monthly Revenue Trend',\n type: 'line',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{last_12_months}' } },\n categoryField: 'close_date',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 6, w: 8, h: 4 },\n options: { dateGranularity: 'month', showTrend: true }\n },\n {\n id: 'top_opportunities',\n title: 'Top Opportunities',\n type: 'table',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n aggregate: 'count',\n layout: { x: 8, y: 6, w: 4, h: 4 },\n options: {\n columns: ['name', 'amount', 'stage', 'close_date'],\n sortBy: 'amount',\n sortOrder: 'desc',\n limit: 10,\n }\n },\n ]\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Dashboard } from '@objectstack/spec/ui';\n\nexport const ServiceDashboard: Dashboard = {\n name: 'service_dashboard',\n label: 'Customer Service',\n description: 'Support case metrics and performance',\n \n widgets: [\n // Row 1: Key Metrics\n {\n id: 'open_cases',\n title: 'Open Cases',\n type: 'metric',\n object: 'case',\n filter: { is_closed: false },\n aggregate: 'count',\n layout: { x: 0, y: 0, w: 3, h: 2 },\n options: { color: '#FFA500' }\n },\n {\n id: 'critical_cases',\n title: 'Critical Cases',\n type: 'metric',\n object: 'case',\n filter: { priority: 'critical', is_closed: false },\n aggregate: 'count',\n layout: { x: 3, y: 0, w: 3, h: 2 },\n options: { color: '#FF0000' }\n },\n {\n id: 'avg_resolution_time',\n title: 'Avg Resolution Time (hrs)',\n type: 'metric',\n object: 'case',\n filter: { is_closed: true },\n valueField: 'resolution_time_hours',\n aggregate: 'avg',\n layout: { x: 6, y: 0, w: 3, h: 2 },\n options: { suffix: 'h', color: '#4169E1' }\n },\n {\n id: 'sla_violations',\n title: 'SLA Violations',\n type: 'metric',\n object: 'case',\n filter: { is_sla_violated: true },\n aggregate: 'count',\n layout: { x: 9, y: 0, w: 3, h: 2 },\n options: { color: '#FF4500' }\n },\n \n // Row 2: Case Distribution\n {\n id: 'cases_by_status',\n title: 'Cases by Status',\n type: 'pie',\n object: 'case',\n filter: { is_closed: false },\n categoryField: 'status',\n aggregate: 'count',\n layout: { x: 0, y: 2, w: 4, h: 4 },\n options: { showLegend: true }\n },\n {\n id: 'cases_by_priority',\n title: 'Cases by Priority',\n type: 'pie',\n object: 'case',\n filter: { is_closed: false },\n categoryField: 'priority',\n aggregate: 'count',\n layout: { x: 4, y: 2, w: 4, h: 4 },\n options: { showLegend: true }\n },\n {\n id: 'cases_by_origin',\n title: 'Cases by Origin',\n type: 'bar',\n object: 'case',\n categoryField: 'origin',\n aggregate: 'count',\n layout: { x: 8, y: 2, w: 4, h: 4 },\n },\n \n // Row 3: Trends and Lists\n {\n id: 'daily_case_volume',\n title: 'Daily Case Volume',\n type: 'line',\n object: 'case',\n filter: { created_date: { $gte: '{last_30_days}' } },\n categoryField: 'created_date',\n aggregate: 'count',\n layout: { x: 0, y: 6, w: 8, h: 4 },\n options: { dateGranularity: 'day' }\n },\n {\n id: 'my_open_cases',\n title: 'My Open Cases',\n type: 'table',\n object: 'case',\n filter: { owner: '{current_user}', is_closed: false },\n aggregate: 'count',\n layout: { x: 8, y: 6, w: 4, h: 4 },\n options: {\n columns: ['case_number', 'subject', 'priority', 'status'],\n sortBy: 'priority',\n sortOrder: 'desc',\n limit: 10,\n }\n },\n ]\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Report Definitions Barrel\n */\nexport { AccountsByIndustryTypeReport } from './account.report';\nexport { CasesByStatusPriorityReport, SlaPerformanceReport } from './case.report';\nexport { ContactsByAccountReport } from './contact.report';\nexport { LeadsBySourceReport } from './lead.report';\nexport { OpportunitiesByStageReport, WonOpportunitiesByOwnerReport } from './opportunity.report';\nexport { TasksByOwnerReport } from './task.report';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const AccountsByIndustryTypeReport: ReportInput = {\n name: 'accounts_by_industry_type',\n label: 'Accounts by Industry and Type',\n description: 'Matrix report showing accounts by industry and type',\n objectName: 'account',\n type: 'matrix',\n columns: [\n { field: 'name', aggregate: 'count' },\n { field: 'annual_revenue', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'industry', sortOrder: 'asc' }],\n groupingsAcross: [{ field: 'type', sortOrder: 'asc' }],\n filter: { is_active: true },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const CasesByStatusPriorityReport: ReportInput = {\n name: 'cases_by_status_priority',\n label: 'Cases by Status and Priority',\n description: 'Summary of cases by status and priority',\n objectName: 'case',\n type: 'summary',\n columns: [\n { field: 'case_number', label: 'Case Number' },\n { field: 'subject', label: 'Subject' },\n { field: 'account', label: 'Account' },\n { field: 'owner', label: 'Owner' },\n { field: 'resolution_time_hours', label: 'Resolution Time', aggregate: 'avg' },\n ],\n groupingsDown: [\n { field: 'status', sortOrder: 'asc' },\n { field: 'priority', sortOrder: 'desc' },\n ],\n chart: { type: 'bar', title: 'Cases by Status', showLegend: true, xAxis: 'status', yAxis: 'case_number' }\n};\n\nexport const SlaPerformanceReport: ReportInput = {\n name: 'sla_performance',\n label: 'SLA Performance Report',\n description: 'Analysis of SLA compliance',\n objectName: 'case',\n type: 'summary',\n columns: [\n { field: 'case_number', aggregate: 'count' },\n { field: 'is_sla_violated', label: 'SLA Violated', aggregate: 'count' },\n { field: 'resolution_time_hours', label: 'Avg Resolution Time', aggregate: 'avg' },\n ],\n groupingsDown: [{ field: 'priority', sortOrder: 'desc' }],\n filter: { is_closed: true },\n chart: { type: 'column', title: 'SLA Violations by Priority', showLegend: false, xAxis: 'priority', yAxis: 'is_sla_violated' }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const ContactsByAccountReport: ReportInput = {\n name: 'contacts_by_account',\n label: 'Contacts by Account',\n description: 'List of contacts grouped by account',\n objectName: 'contact',\n type: 'summary',\n columns: [\n { field: 'full_name', label: 'Name' },\n { field: 'title', label: 'Title' },\n { field: 'email', label: 'Email' },\n { field: 'phone', label: 'Phone' },\n { field: 'is_primary', label: 'Primary Contact' },\n ],\n groupingsDown: [{ field: 'account', sortOrder: 'asc' }],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const LeadsBySourceReport: ReportInput = {\n name: 'leads_by_source',\n label: 'Leads by Source and Status',\n description: 'Lead pipeline analysis',\n objectName: 'lead',\n type: 'summary',\n columns: [\n { field: 'full_name', label: 'Name' },\n { field: 'company', label: 'Company' },\n { field: 'rating', label: 'Rating' },\n ],\n groupingsDown: [\n { field: 'lead_source', sortOrder: 'asc' },\n { field: 'status', sortOrder: 'asc' },\n ],\n filter: { is_converted: false },\n chart: { type: 'pie', title: 'Leads by Source', showLegend: true, xAxis: 'lead_source', yAxis: 'full_name' }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const OpportunitiesByStageReport: ReportInput = {\n name: 'opportunities_by_stage',\n label: 'Opportunities by Stage',\n description: 'Summary of opportunities grouped by stage',\n objectName: 'opportunity',\n type: 'summary',\n columns: [\n { field: 'name', label: 'Opportunity Name' },\n { field: 'account', label: 'Account' },\n { field: 'amount', label: 'Amount', aggregate: 'sum' },\n { field: 'close_date', label: 'Close Date' },\n { field: 'probability', label: 'Probability', aggregate: 'avg' },\n ],\n groupingsDown: [{ field: 'stage', sortOrder: 'asc' }],\n filter: { stage: { $ne: 'closed_lost' }, close_date: { $gte: '{current_year_start}' } },\n chart: { type: 'bar', title: 'Pipeline by Stage', showLegend: true, xAxis: 'stage', yAxis: 'amount' }\n};\n\nexport const WonOpportunitiesByOwnerReport: ReportInput = {\n name: 'won_opportunities_by_owner',\n label: 'Won Opportunities by Owner',\n description: 'Closed won opportunities grouped by owner',\n objectName: 'opportunity',\n type: 'summary',\n columns: [\n { field: 'name', label: 'Opportunity Name' },\n { field: 'account', label: 'Account' },\n { field: 'amount', label: 'Amount', aggregate: 'sum' },\n { field: 'close_date', label: 'Close Date' },\n ],\n groupingsDown: [{ field: 'owner', sortOrder: 'desc' }],\n filter: { stage: 'closed_won' },\n chart: { type: 'column', title: 'Revenue by Sales Rep', showLegend: false, xAxis: 'owner', yAxis: 'amount' }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const TasksByOwnerReport: ReportInput = {\n name: 'tasks_by_owner',\n label: 'Tasks by Owner',\n description: 'Task summary by owner',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'status', label: 'Status' },\n { field: 'priority', label: 'Priority' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'actual_hours', label: 'Hours', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'owner', sortOrder: 'asc' }],\n filter: { is_completed: false },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Campaign Enrollment \u2014 scheduled flow to bulk enroll leads */\nexport const CampaignEnrollmentFlow: Flow = {\n name: 'campaign_enrollment',\n label: 'Enroll Leads in Campaign',\n description: 'Bulk enroll leads into marketing campaigns',\n type: 'schedule',\n\n variables: [\n { name: 'campaignId', type: 'text', isInput: true, isOutput: false },\n { name: 'leadStatus', type: 'text', isInput: true, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start (Monday 9 AM)', config: { schedule: '0 9 * * 1' } },\n {\n id: 'get_campaign', type: 'get_record', label: 'Get Campaign',\n config: { objectName: 'campaign', filter: { id: '{campaignId}' }, outputVariable: 'campaignRecord' },\n },\n {\n id: 'query_leads', type: 'get_record', label: 'Find Eligible Leads',\n config: { objectName: 'lead', filter: { status: '{leadStatus}', is_converted: false, email: { $ne: null } }, limit: 1000, outputVariable: 'leadList' },\n },\n {\n id: 'loop_leads', type: 'loop', label: 'Process Each Lead',\n config: { collection: '{leadList}', iteratorVariable: 'currentLead' },\n },\n {\n id: 'create_campaign_member', type: 'create_record', label: 'Add to Campaign',\n config: {\n objectName: 'campaign_member',\n fields: { campaign: '{campaignId}', lead: '{currentLead.id}', status: 'sent', added_date: '{NOW()}' },\n },\n },\n {\n id: 'update_campaign_stats', type: 'update_record', label: 'Update Campaign Stats',\n config: { objectName: 'campaign', filter: { id: '{campaignId}' }, fields: { num_sent: '{leadList.length}' } },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_campaign', type: 'default' },\n { id: 'e2', source: 'get_campaign', target: 'query_leads', type: 'default' },\n { id: 'e3', source: 'query_leads', target: 'loop_leads', type: 'default' },\n { id: 'e4', source: 'loop_leads', target: 'create_campaign_member', type: 'default' },\n { id: 'e5', source: 'create_campaign_member', target: 'update_campaign_stats', type: 'default' },\n { id: 'e6', source: 'update_campaign_stats', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Case Escalation \u2014 auto-escalate high-priority cases */\nexport const CaseEscalationFlow: Flow = {\n name: 'case_escalation',\n label: 'Case Escalation Process',\n description: 'Automatically escalate high-priority cases',\n type: 'record_change',\n\n variables: [\n { name: 'caseId', type: 'text', isInput: true, isOutput: false },\n ],\n\n nodes: [\n {\n id: 'start', type: 'start', label: 'Start',\n config: { objectName: 'case', criteria: 'priority = \"critical\" OR (priority = \"high\" AND account.type = \"customer\")' },\n },\n {\n id: 'get_case', type: 'get_record', label: 'Get Case Record',\n config: { objectName: 'case', filter: { id: '{caseId}' }, outputVariable: 'caseRecord' },\n },\n {\n id: 'assign_senior_agent', type: 'update_record', label: 'Assign to Senior Agent',\n config: {\n objectName: 'case', filter: { id: '{caseId}' },\n fields: { owner: '{caseRecord.owner.manager}', is_escalated: true, escalated_date: '{NOW()}' },\n },\n },\n {\n id: 'create_task', type: 'create_record', label: 'Create Follow-up Task',\n config: {\n objectName: 'task',\n fields: {\n subject: 'Follow up on escalated case: {caseRecord.case_number}',\n related_to: '{caseId}', owner: '{caseRecord.owner}',\n priority: 'high', status: 'not_started', due_date: '{TODAY() + 1}',\n },\n },\n },\n {\n id: 'notify_team', type: 'script', label: 'Notify Support Team',\n config: {\n actionType: 'email',\n template: 'case_escalated',\n recipients: ['{caseRecord.owner}', '{caseRecord.owner.manager}', 'support-team@example.com'],\n variables: {\n caseNumber: '{caseRecord.case_number}',\n priority: '{caseRecord.priority}',\n accountName: '{caseRecord.account.name}',\n },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_case', type: 'default' },\n { id: 'e2', source: 'get_case', target: 'assign_senior_agent', type: 'default' },\n { id: 'e3', source: 'assign_senior_agent', target: 'create_task', type: 'default' },\n { id: 'e4', source: 'create_task', target: 'notify_team', type: 'default' },\n { id: 'e5', source: 'notify_team', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Lead Conversion \u2014 multi-step screen flow to convert qualified leads */\nexport const LeadConversionFlow: Flow = {\n name: 'lead_conversion',\n label: 'Lead Conversion Process',\n description: 'Automated flow to convert qualified leads to accounts, contacts, and opportunities',\n type: 'screen',\n\n variables: [\n { name: 'leadId', type: 'text', isInput: true, isOutput: false },\n { name: 'createOpportunity', type: 'boolean', isInput: true, isOutput: false },\n { name: 'opportunityName', type: 'text', isInput: true, isOutput: false },\n { name: 'opportunityAmount', type: 'text', isInput: true, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start', config: { objectName: 'lead' } },\n {\n id: 'screen_1', type: 'screen', label: 'Conversion Details',\n config: {\n fields: [\n { name: 'createOpportunity', label: 'Create Opportunity?', type: 'boolean', required: true },\n { name: 'opportunityName', label: 'Opportunity Name', type: 'text', required: true, visibleWhen: '{createOpportunity} == true' },\n { name: 'opportunityAmount', label: 'Opportunity Amount', type: 'currency', visibleWhen: '{createOpportunity} == true' },\n ],\n },\n },\n {\n id: 'get_lead', type: 'get_record', label: 'Get Lead Record',\n config: { objectName: 'lead', filter: { id: '{leadId}' }, outputVariable: 'leadRecord' },\n },\n {\n id: 'create_account', type: 'create_record', label: 'Create Account',\n config: {\n objectName: 'account',\n fields: {\n name: '{leadRecord.company}', phone: '{leadRecord.phone}',\n website: '{leadRecord.website}', industry: '{leadRecord.industry}',\n annual_revenue: '{leadRecord.annual_revenue}',\n number_of_employees: '{leadRecord.number_of_employees}',\n billing_address: '{leadRecord.address}',\n owner: '{$User.Id}', is_active: true,\n },\n outputVariable: 'accountId',\n },\n },\n {\n id: 'create_contact', type: 'create_record', label: 'Create Contact',\n config: {\n objectName: 'contact',\n fields: {\n first_name: '{leadRecord.first_name}', last_name: '{leadRecord.last_name}',\n email: '{leadRecord.email}', phone: '{leadRecord.phone}',\n title: '{leadRecord.title}', account: '{accountId}',\n is_primary: true, owner: '{$User.Id}',\n },\n outputVariable: 'contactId',\n },\n },\n {\n id: 'decision_opportunity', type: 'decision', label: 'Create Opportunity?',\n config: { condition: '{createOpportunity} == true' },\n },\n {\n id: 'create_opportunity', type: 'create_record', label: 'Create Opportunity',\n config: {\n objectName: 'opportunity',\n fields: {\n name: '{opportunityName}', account: '{accountId}', contact: '{contactId}',\n amount: '{opportunityAmount}', stage: 'prospecting', probability: 10,\n lead_source: '{leadRecord.lead_source}', close_date: '{TODAY() + 90}', owner: '{$User.Id}',\n },\n outputVariable: 'opportunityId',\n },\n },\n {\n id: 'mark_converted', type: 'update_record', label: 'Mark Lead as Converted',\n config: {\n objectName: 'lead', filter: { id: '{leadId}' },\n fields: {\n is_converted: true, converted_date: '{NOW()}',\n converted_account: '{accountId}', converted_contact: '{contactId}',\n converted_opportunity: '{opportunityId}',\n },\n },\n },\n {\n id: 'send_notification', type: 'script', label: 'Send Confirmation Email',\n config: {\n actionType: 'email', template: 'lead_converted_notification',\n recipients: ['{$User.Email}'],\n variables: { leadName: '{leadRecord.full_name}', accountName: '{accountId.name}', contactName: '{contactId.full_name}' },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'screen_1', type: 'default' },\n { id: 'e2', source: 'screen_1', target: 'get_lead', type: 'default' },\n { id: 'e3', source: 'get_lead', target: 'create_account', type: 'default' },\n { id: 'e4', source: 'create_account', target: 'create_contact', type: 'default' },\n { id: 'e5', source: 'create_contact', target: 'decision_opportunity', type: 'default' },\n { id: 'e6', source: 'decision_opportunity', target: 'create_opportunity', type: 'default', condition: '{createOpportunity} == true', label: 'Yes' },\n { id: 'e7', source: 'decision_opportunity', target: 'mark_converted', type: 'default', condition: '{createOpportunity} != true', label: 'No' },\n { id: 'e8', source: 'create_opportunity', target: 'mark_converted', type: 'default' },\n { id: 'e9', source: 'mark_converted', target: 'send_notification', type: 'default' },\n { id: 'e10', source: 'send_notification', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Opportunity Approval \u2014 multi-level approval for deals over $100K */\nexport const OpportunityApprovalFlow: Flow = {\n name: 'opportunity_approval',\n label: 'Large Deal Approval',\n description: 'Approval process for opportunities over $100K',\n type: 'record_change',\n\n variables: [\n { name: 'opportunityId', type: 'text', isInput: true, isOutput: false },\n ],\n\n nodes: [\n {\n id: 'start', type: 'start', label: 'Start',\n config: { objectName: 'opportunity', criteria: 'amount > 100000 AND stage = \"proposal\"' },\n },\n {\n id: 'get_opportunity', type: 'get_record', label: 'Get Opportunity',\n config: { objectName: 'opportunity', filter: { id: '{opportunityId}' }, outputVariable: 'oppRecord' },\n },\n {\n id: 'approval_step_manager', type: 'connector_action', label: 'Sales Manager Approval',\n config: {\n actionType: 'approval',\n approver: '{oppRecord.owner.manager}',\n emailTemplate: 'opportunity_approval_request',\n comments: 'required',\n },\n },\n {\n id: 'decision_manager', type: 'decision', label: 'Manager Approved?',\n config: { condition: '{approval_step_manager.result} == \"approved\"' },\n },\n {\n id: 'approval_step_director', type: 'connector_action', label: 'Sales Director Approval',\n config: {\n actionType: 'approval',\n approver: '{oppRecord.owner.manager.manager}',\n emailTemplate: 'opportunity_approval_request',\n },\n },\n {\n id: 'decision_director', type: 'decision', label: 'Director Approved?',\n config: { condition: '{approval_step_director.result} == \"approved\"' },\n },\n {\n id: 'mark_approved', type: 'update_record', label: 'Mark as Approved',\n config: {\n objectName: 'opportunity', filter: { id: '{opportunityId}' },\n fields: { approval_status: 'approved', approved_date: '{NOW()}' },\n },\n },\n {\n id: 'notify_approval', type: 'script', label: 'Send Approval Notification',\n config: { actionType: 'email', template: 'opportunity_approved', recipients: ['{oppRecord.owner}'] },\n },\n {\n id: 'notify_rejection', type: 'script', label: 'Send Rejection Notification',\n config: { actionType: 'email', template: 'opportunity_rejected', recipients: ['{oppRecord.owner}'] },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_opportunity', type: 'default' },\n { id: 'e2', source: 'get_opportunity', target: 'approval_step_manager', type: 'default' },\n { id: 'e3', source: 'approval_step_manager', target: 'decision_manager', type: 'default' },\n { id: 'e4', source: 'decision_manager', target: 'approval_step_director', type: 'default', condition: '{approval_step_manager.result} == \"approved\"', label: 'Approved' },\n { id: 'e5', source: 'decision_manager', target: 'notify_rejection', type: 'default', condition: '{approval_step_manager.result} != \"approved\"', label: 'Rejected' },\n { id: 'e6', source: 'approval_step_director', target: 'decision_director', type: 'default' },\n { id: 'e7', source: 'decision_director', target: 'mark_approved', type: 'default', condition: '{approval_step_director.result} == \"approved\"', label: 'Approved' },\n { id: 'e8', source: 'decision_director', target: 'notify_rejection', type: 'default', condition: '{approval_step_director.result} != \"approved\"', label: 'Rejected' },\n { id: 'e9', source: 'mark_approved', target: 'notify_approval', type: 'default' },\n { id: 'e10', source: 'notify_approval', target: 'end', type: 'default' },\n { id: 'e11', source: 'notify_rejection', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Quote Generation \u2014 screen flow to create a quote from an opportunity */\nexport const QuoteGenerationFlow: Flow = {\n name: 'quote_generation',\n label: 'Generate Quote from Opportunity',\n description: 'Create a quote based on opportunity details',\n type: 'screen',\n\n variables: [\n { name: 'opportunityId', type: 'text', isInput: true, isOutput: false },\n { name: 'quoteName', type: 'text', isInput: true, isOutput: false },\n { name: 'expirationDays', type: 'number', isInput: true, isOutput: false },\n { name: 'discount', type: 'number', isInput: true, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start', config: { objectName: 'opportunity' } },\n {\n id: 'screen_1', type: 'screen', label: 'Quote Details',\n config: {\n fields: [\n { name: 'quoteName', label: 'Quote Name', type: 'text', required: true },\n { name: 'expirationDays', label: 'Valid For (Days)', type: 'number', required: true, defaultValue: 30 },\n { name: 'discount', label: 'Discount %', type: 'percent', defaultValue: 0 },\n ],\n },\n },\n {\n id: 'get_opportunity', type: 'get_record', label: 'Get Opportunity',\n config: { objectName: 'opportunity', filter: { id: '{opportunityId}' }, outputVariable: 'oppRecord' },\n },\n {\n id: 'create_quote', type: 'create_record', label: 'Create Quote',\n config: {\n objectName: 'quote',\n fields: {\n name: '{quoteName}', opportunity: '{opportunityId}',\n account: '{oppRecord.account}', contact: '{oppRecord.contact}',\n owner: '{$User.Id}', status: 'draft',\n quote_date: '{TODAY()}', expiration_date: '{TODAY() + expirationDays}',\n subtotal: '{oppRecord.amount}', discount: '{discount}',\n discount_amount: '{oppRecord.amount * (discount / 100)}',\n total_price: '{oppRecord.amount * (1 - discount / 100)}',\n payment_terms: 'net_30',\n },\n outputVariable: 'quoteId',\n },\n },\n {\n id: 'update_opportunity', type: 'update_record', label: 'Update Opportunity',\n config: {\n objectName: 'opportunity', filter: { id: '{opportunityId}' },\n fields: { stage: 'proposal', last_activity_date: '{TODAY()}' },\n },\n },\n {\n id: 'notify_owner', type: 'script', label: 'Send Notification',\n config: {\n actionType: 'email', template: 'quote_created',\n recipients: ['{$User.Email}'],\n variables: { quoteName: '{quoteName}', quoteId: '{quoteId}' },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'screen_1', type: 'default' },\n { id: 'e2', source: 'screen_1', target: 'get_opportunity', type: 'default' },\n { id: 'e3', source: 'get_opportunity', target: 'create_quote', type: 'default' },\n { id: 'e4', source: 'create_quote', target: 'update_opportunity', type: 'default' },\n { id: 'e5', source: 'update_opportunity', target: 'notify_owner', type: 'default' },\n { id: 'e6', source: 'notify_owner', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Flow } from '@objectstack/spec/automation';\n\n/**\n * Flow Definitions Barrel\n */\nexport { CampaignEnrollmentFlow } from './campaign-enrollment.flow';\nexport { CaseEscalationFlow } from './case-escalation.flow';\nexport { LeadConversionFlow } from './lead-conversion.flow';\nexport { OpportunityApprovalFlow } from './opportunity-approval.flow';\nexport { QuoteGenerationFlow } from './quote-generation.flow';\n\nimport { CampaignEnrollmentFlow } from './campaign-enrollment.flow';\nimport { CaseEscalationFlow } from './case-escalation.flow';\nimport { LeadConversionFlow } from './lead-conversion.flow';\nimport { OpportunityApprovalFlow } from './opportunity-approval.flow';\nimport { QuoteGenerationFlow } from './quote-generation.flow';\n\n/** All flow definitions as a typed array for defineStack() */\nexport const allFlows: Flow[] = [\n CampaignEnrollmentFlow,\n CaseEscalationFlow,\n LeadConversionFlow,\n OpportunityApprovalFlow,\n QuoteGenerationFlow,\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Email Campaign Agent \u2014 creates and optimizes email campaigns */\nexport const EmailCampaignAgent = {\n name: 'email_campaign',\n label: 'Email Campaign Agent',\n role: 'creator',\n\n instructions: `You are an email marketing AI that creates and optimizes email campaigns.\n\nYour responsibilities:\n1. Write compelling email copy\n2. Optimize subject lines for open rates\n3. Personalize content based on recipient data\n4. A/B test different variations\n5. Analyze campaign performance\n6. Suggest improvements\n\nFollow email marketing best practices and maintain brand voice.`,\n\n model: { provider: 'anthropic', model: 'claude-3-opus', temperature: 0.8, maxTokens: 2000 },\n\n tools: [\n { type: 'action' as const, name: 'generate_email_copy', description: 'Generate email campaign copy' },\n { type: 'action' as const, name: 'optimize_subject_line', description: 'Optimize email subject line' },\n { type: 'action' as const, name: 'personalize_content', description: 'Personalize email content' },\n ],\n\n knowledge: {\n topics: ['email_marketing', 'brand_guidelines', 'campaign_templates'],\n indexes: ['sales_knowledge'],\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Lead Enrichment Agent \u2014 automatically enriches lead data from external sources */\nexport const LeadEnrichmentAgent = {\n name: 'lead_enrichment',\n label: 'Lead Enrichment Agent',\n role: 'worker',\n\n instructions: `You are a lead enrichment AI that enhances lead records with additional data.\n\nYour responsibilities:\n1. Look up company information from external databases\n2. Enrich contact details (job title, LinkedIn, etc.)\n3. Add firmographic data (industry, size, revenue)\n4. Research company technology stack\n5. Find social media profiles\n6. Validate email addresses and phone numbers\n\nAlways use reputable data sources and maintain data quality.`,\n\n model: { provider: 'openai', model: 'gpt-3.5-turbo', temperature: 0.3, maxTokens: 1000 },\n\n tools: [\n { type: 'action' as const, name: 'lookup_company', description: 'Look up company information' },\n { type: 'action' as const, name: 'enrich_contact', description: 'Enrich contact information' },\n { type: 'action' as const, name: 'validate_email', description: 'Validate email address' },\n ],\n\n knowledge: {\n topics: ['lead_enrichment', 'company_data'],\n indexes: ['sales_knowledge'],\n },\n\n triggers: [\n { type: 'object_create', objectName: 'lead' },\n ],\n\n schedule: { type: 'cron', expression: '0 */4 * * *', timezone: 'UTC' },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Revenue Intelligence Agent \u2014 analyzes pipeline and provides revenue insights */\nexport const RevenueIntelligenceAgent = {\n name: 'revenue_intelligence',\n label: 'Revenue Intelligence Agent',\n role: 'analyst',\n\n instructions: `You are a revenue intelligence AI that analyzes sales data and provides insights.\n\nYour responsibilities:\n1. Analyze pipeline health and quality\n2. Identify at-risk deals\n3. Forecast revenue with confidence intervals\n4. Detect anomalies and trends\n5. Suggest coaching opportunities\n6. Generate executive summaries\n\nUse statistical analysis and machine learning to provide data-driven insights.`,\n\n model: { provider: 'openai', model: 'gpt-4', temperature: 0.2, maxTokens: 3000 },\n\n tools: [\n { type: 'query' as const, name: 'analyze_pipeline', description: 'Analyze sales pipeline health' },\n { type: 'query' as const, name: 'identify_at_risk', description: 'Identify at-risk opportunities' },\n { type: 'query' as const, name: 'forecast_revenue', description: 'Generate revenue forecast' },\n ],\n\n knowledge: {\n topics: ['pipeline_analytics', 'revenue_forecasting', 'deal_risk'],\n indexes: ['sales_knowledge'],\n },\n\n schedule: { type: 'cron', expression: '0 8 * * 1', timezone: 'America/Los_Angeles' },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Sales Assistant \u2014 helps reps with lead qualification and opportunity management */\nexport const SalesAssistantAgent = {\n name: 'sales_assistant',\n label: 'Sales Assistant',\n role: 'assistant',\n\n instructions: `You are a sales assistant AI helping sales representatives manage their pipeline.\n\nYour responsibilities:\n1. Qualify incoming leads based on BANT criteria (Budget, Authority, Need, Timeline)\n2. Suggest next best actions for opportunities\n3. Draft personalized email templates\n4. Analyze win/loss patterns\n5. Provide competitive intelligence\n6. Generate sales forecasts\n\nAlways be professional, data-driven, and focused on helping close deals.`,\n\n model: { provider: 'openai', model: 'gpt-4', temperature: 0.7, maxTokens: 2000 },\n\n tools: [\n { type: 'action' as const, name: 'analyze_lead', description: 'Analyze a lead and provide qualification score' },\n { type: 'action' as const, name: 'suggest_next_action', description: 'Suggest next best action for an opportunity' },\n { type: 'action' as const, name: 'generate_email', description: 'Generate a personalized email template' },\n ],\n\n knowledge: {\n topics: ['sales_playbook', 'product_catalog', 'lead_qualification'],\n indexes: ['sales_knowledge'],\n },\n\n triggers: [\n { type: 'object_create', objectName: 'lead', condition: 'rating = \"hot\"' },\n { type: 'object_update', objectName: 'opportunity', condition: 'ISCHANGED(stage)' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Customer Service Agent \u2014 assists with case triage and resolution */\nexport const ServiceAgent = {\n name: 'service_agent',\n label: 'Customer Service Agent',\n role: 'assistant',\n\n instructions: `You are a customer service AI agent helping support representatives resolve customer issues.\n\nYour responsibilities:\n1. Triage incoming cases based on priority and category\n2. Suggest relevant knowledge articles\n3. Draft response templates\n4. Escalate critical issues\n5. Identify common problems and patterns\n6. Recommend process improvements\n\nAlways be empathetic, solution-focused, and customer-centric.`,\n\n model: { provider: 'openai', model: 'gpt-4', temperature: 0.5, maxTokens: 1500 },\n\n tools: [\n { type: 'action' as const, name: 'triage_case', description: 'Analyze case and assign priority' },\n { type: 'vector_search' as const, name: 'search_knowledge', description: 'Search knowledge base for solutions' },\n { type: 'action' as const, name: 'generate_response', description: 'Generate customer response' },\n ],\n\n knowledge: {\n topics: ['support_kb', 'sla_policies', 'case_resolution'],\n indexes: ['support_knowledge'],\n },\n\n triggers: [\n { type: 'object_create', objectName: 'case' },\n { type: 'object_update', objectName: 'case', condition: 'priority = \"critical\"' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Agent } from '@objectstack/spec/ai';\n\n/**\n * Agent Definitions Barrel\n */\nexport { EmailCampaignAgent } from './email-campaign.agent';\nexport { LeadEnrichmentAgent } from './lead-enrichment.agent';\nexport { RevenueIntelligenceAgent } from './revenue-intelligence.agent';\nexport { SalesAssistantAgent } from './sales.agent';\nexport { ServiceAgent } from './service.agent';\n\nimport { EmailCampaignAgent } from './email-campaign.agent';\nimport { LeadEnrichmentAgent } from './lead-enrichment.agent';\nimport { RevenueIntelligenceAgent } from './revenue-intelligence.agent';\nimport { SalesAssistantAgent } from './sales.agent';\nimport { ServiceAgent } from './service.agent';\n\n/** All agent definitions as a typed array for defineStack() */\nexport const allAgents: Agent[] = [\n EmailCampaignAgent,\n LeadEnrichmentAgent,\n RevenueIntelligenceAgent,\n SalesAssistantAgent,\n ServiceAgent,\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * RAG Pipeline Definitions Barrel\n */\nexport { CompetitiveIntelRAG } from './competitive-intel.rag';\nexport { ProductInfoRAG } from './product-info.rag';\nexport { SalesKnowledgeRAG } from './sales-knowledge.rag';\nexport { SupportKnowledgeRAG } from './support-knowledge.rag';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const CompetitiveIntelRAG = {\n name: 'competitive_intel',\n label: 'Competitive Intelligence Pipeline',\n description: 'RAG pipeline for competitive analysis and market insights',\n\n embedding: {\n provider: 'openai',\n model: 'text-embedding-3-large',\n dimensions: 1536,\n },\n\n vectorStore: {\n provider: 'pgvector',\n indexName: 'competitive_index',\n dimensions: 1536,\n metric: 'cosine',\n },\n\n chunking: {\n type: 'semantic',\n maxChunkSize: 1200,\n },\n\n retrieval: {\n type: 'similarity',\n topK: 7,\n scoreThreshold: 0.65,\n },\n\n reranking: {\n enabled: true,\n provider: 'cohere',\n model: 'cohere-rerank',\n topK: 5,\n },\n\n loaders: [\n { type: 'directory', source: '/knowledge/competitive', fileTypes: ['.md'], recursive: true },\n { type: 'directory', source: '/knowledge/market-research', fileTypes: ['.pdf'], recursive: true },\n ],\n\n maxContextTokens: 5000,\n enableCache: true,\n cacheTTL: 1800,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const ProductInfoRAG = {\n name: 'product_info',\n label: 'Product Information Pipeline',\n description: 'RAG pipeline for product catalog and specifications',\n\n embedding: {\n provider: 'openai',\n model: 'text-embedding-3-small',\n dimensions: 768,\n },\n\n vectorStore: {\n provider: 'pgvector',\n indexName: 'product_catalog_index',\n dimensions: 768,\n metric: 'cosine',\n },\n\n chunking: {\n type: 'semantic',\n maxChunkSize: 800,\n },\n\n retrieval: {\n type: 'hybrid',\n topK: 8,\n vectorWeight: 0.6,\n keywordWeight: 0.4,\n },\n\n loaders: [\n { type: 'directory', source: '/knowledge/products', fileTypes: ['.md', '.pdf'], recursive: true },\n ],\n\n maxContextTokens: 2000,\n enableCache: true,\n cacheTTL: 3600,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SalesKnowledgeRAG = {\n name: 'sales_knowledge',\n label: 'Sales Knowledge Pipeline',\n description: 'RAG pipeline for sales team knowledge and best practices',\n\n embedding: {\n provider: 'openai',\n model: 'text-embedding-3-large',\n dimensions: 1536,\n },\n\n vectorStore: {\n provider: 'pgvector',\n indexName: 'sales_playbook_index',\n dimensions: 1536,\n metric: 'cosine',\n },\n\n chunking: {\n type: 'semantic',\n maxChunkSize: 1000,\n },\n\n retrieval: {\n type: 'hybrid',\n topK: 10,\n vectorWeight: 0.7,\n keywordWeight: 0.3,\n },\n\n reranking: {\n enabled: true,\n provider: 'cohere',\n model: 'cohere-rerank',\n topK: 5,\n },\n\n loaders: [\n { type: 'directory', source: '/knowledge/sales', fileTypes: ['.md'], recursive: true },\n { type: 'directory', source: '/knowledge/products', fileTypes: ['.pdf'], recursive: true },\n ],\n\n maxContextTokens: 4000,\n enableCache: true,\n cacheTTL: 3600,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SupportKnowledgeRAG = {\n name: 'support_knowledge',\n label: 'Support Knowledge Pipeline',\n description: 'RAG pipeline for customer support knowledge base',\n\n embedding: {\n provider: 'openai',\n model: 'text-embedding-3-small',\n dimensions: 768,\n },\n\n vectorStore: {\n provider: 'pgvector',\n indexName: 'support_kb_index',\n dimensions: 768,\n metric: 'cosine',\n },\n\n chunking: {\n type: 'fixed',\n chunkSize: 512,\n chunkOverlap: 100,\n unit: 'tokens',\n },\n\n retrieval: {\n type: 'similarity',\n topK: 5,\n scoreThreshold: 0.75,\n },\n\n loaders: [\n { type: 'directory', source: '/knowledge/support', fileTypes: ['.md'], recursive: true },\n ],\n\n maxContextTokens: 3000,\n enableCache: true,\n cacheTTL: 3600,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Profile Definitions Barrel\n */\nexport { MarketingUserProfile } from './marketing-user.profile';\nexport { SalesManagerProfile } from './sales-manager.profile';\nexport { SalesRepProfile } from './sales-rep.profile';\nexport { ServiceAgentProfile } from './service-agent.profile';\nexport { SystemAdminProfile } from './system-admin.profile';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const MarketingUserProfile = {\n name: 'marketing_user',\n label: 'Marketing User',\n isProfile: true,\n objects: {\n lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n account: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n opportunity: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SalesManagerProfile = {\n name: 'sales_manager',\n label: 'Sales Manager',\n isProfile: true,\n objects: {\n lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n contract: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n product: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n case: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SalesRepProfile = {\n name: 'sales_rep',\n label: 'Sales Representative',\n isProfile: true,\n objects: {\n lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n contract: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n product: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n campaign: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n case: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: false, modifyAllRecords: false },\n },\n fields: {\n 'account.annual_revenue': { readable: true, editable: false },\n 'account.description': { readable: true, editable: true },\n 'opportunity.amount': { readable: true, editable: true },\n 'opportunity.probability': { readable: true, editable: true },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const ServiceAgentProfile = {\n name: 'service_agent',\n label: 'Service Agent',\n isProfile: true,\n objects: {\n lead: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n account: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n contact: { allowCreate: false, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n opportunity: { allowCreate: false, allowRead: false, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n case: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: false, modifyAllRecords: false },\n product: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n },\n fields: {\n 'case.is_sla_violated': { readable: true, editable: false },\n 'case.resolution_time_hours': { readable: true, editable: false },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SystemAdminProfile = {\n name: 'system_admin',\n label: 'System Administrator',\n isProfile: true,\n objects: {\n lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n contract: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n product: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n case: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n },\n systemPermissions: [\n 'view_setup', 'manage_users', 'customize_application',\n 'view_all_data', 'modify_all_data', 'manage_profiles',\n 'manage_roles', 'manage_sharing',\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * App Definitions Barrel\n */\nexport { CrmApp } from './crm.app';\nexport { CrmAppModern } from './crm_modern.app';\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { App } from '@objectstack/spec/ui';\n\nexport const CrmApp = App.create({\n name: 'crm_enterprise',\n label: 'Enterprise CRM',\n icon: 'briefcase',\n branding: {\n primaryColor: '#4169E1',\n secondaryColor: '#00AA00',\n logo: '/assets/crm-logo.png',\n favicon: '/assets/crm-favicon.ico',\n },\n \n navigation: [\n {\n id: 'group_sales',\n type: 'group',\n label: 'Sales',\n icon: 'chart-line',\n children: [\n { id: 'nav_lead', type: 'object', objectName: 'lead', label: 'Leads', icon: 'user-plus' },\n { id: 'nav_account', type: 'object', objectName: 'account', label: 'Accounts', icon: 'building' },\n { id: 'nav_contact', type: 'object', objectName: 'contact', label: 'Contacts', icon: 'user' },\n { id: 'nav_opportunity', type: 'object', objectName: 'opportunity', label: 'Opportunities', icon: 'bullseye' },\n { id: 'nav_quote', type: 'object', objectName: 'quote', label: 'Quotes', icon: 'file-invoice' },\n { id: 'nav_contract', type: 'object', objectName: 'contract', label: 'Contracts', icon: 'file-signature' },\n { id: 'nav_sales_dashboard', type: 'dashboard', dashboardName: 'sales_dashboard', label: 'Sales Dashboard', icon: 'chart-bar' },\n ]\n },\n {\n id: 'group_service',\n type: 'group',\n label: 'Service',\n icon: 'headset',\n children: [\n { id: 'nav_case', type: 'object', objectName: 'case', label: 'Cases', icon: 'life-ring' },\n { id: 'nav_task', type: 'object', objectName: 'task', label: 'Tasks', icon: 'tasks' },\n { id: 'nav_service_dashboard', type: 'dashboard', dashboardName: 'service_dashboard', label: 'Service Dashboard', icon: 'chart-pie' },\n ]\n },\n {\n id: 'group_marketing',\n type: 'group',\n label: 'Marketing',\n icon: 'megaphone',\n children: [\n { id: 'nav_campaign', type: 'object', objectName: 'campaign', label: 'Campaigns', icon: 'bullhorn' },\n { id: 'nav_lead_marketing', type: 'object', objectName: 'lead', label: 'Leads', icon: 'user-plus' },\n ]\n },\n {\n id: 'group_products',\n type: 'group',\n label: 'Products',\n icon: 'box',\n children: [\n { id: 'nav_product', type: 'object', objectName: 'product', label: 'Products', icon: 'box-open' },\n ]\n },\n {\n id: 'group_analytics',\n type: 'group',\n label: 'Analytics',\n icon: 'chart-area',\n children: [\n { id: 'nav_exec_dashboard', type: 'dashboard', dashboardName: 'executive_dashboard', label: 'Executive Dashboard', icon: 'tachometer-alt' },\n { id: 'nav_analytics_sales_db', type: 'dashboard', dashboardName: 'sales_dashboard', label: 'Sales Analytics', icon: 'chart-line' },\n { id: 'nav_analytics_service_db', type: 'dashboard', dashboardName: 'service_dashboard', label: 'Service Analytics', icon: 'chart-pie' },\n ]\n }\n ]\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { defineApp } from '@objectstack/spec/ui';\n\n/**\n * CRM App with full navigation tree\n * \n * Demonstrates:\n * - Unlimited nesting depth via `type: 'group'` items\n * - Pages referenced by name via `type: 'page'` items\n * - Sub-groups within groups (Lead Review nested under Sales Cloud)\n * - Global utility entries (Settings, Help) at sidebar bottom\n */\nexport const CrmApp = defineApp({\n name: 'crm',\n label: 'Sales CRM',\n description: 'Enterprise CRM with nested navigation tree',\n icon: 'briefcase',\n\n branding: {\n primaryColor: '#4169E1',\n logo: '/assets/crm-logo.png',\n favicon: '/assets/crm-favicon.ico',\n },\n\n navigation: [\n // \u2500\u2500 Sales Cloud \u2500\u2500\n {\n id: 'grp_sales',\n type: 'group',\n label: 'Sales Cloud',\n icon: 'briefcase',\n expanded: true,\n children: [\n { id: 'nav_pipeline', type: 'page', label: 'Pipeline', icon: 'columns', pageName: 'page_pipeline' },\n { id: 'nav_accounts', type: 'page', label: 'Accounts', icon: 'building', pageName: 'page_accounts' },\n { id: 'nav_leads', type: 'page', label: 'Leads', icon: 'user-plus', pageName: 'page_leads' },\n // Nested sub-group \u2014 impossible with the old Interface model\n {\n id: 'grp_review',\n type: 'group',\n label: 'Lead Review',\n icon: 'clipboard-check',\n expanded: false,\n children: [\n { id: 'nav_review_queue', type: 'page', label: 'Review Queue', icon: 'check-square', pageName: 'page_review_queue' },\n { id: 'nav_qualified', type: 'page', label: 'Qualified', icon: 'check-circle', pageName: 'page_qualified' },\n ],\n },\n ],\n },\n\n // \u2500\u2500 Analytics \u2500\u2500\n {\n id: 'grp_analytics',\n type: 'group',\n label: 'Analytics',\n icon: 'chart-line',\n expanded: false,\n children: [\n { id: 'nav_overview', type: 'page', label: 'Overview', icon: 'gauge', pageName: 'page_overview' },\n { id: 'nav_pipeline_report', type: 'page', label: 'Pipeline Report', icon: 'chart-bar', pageName: 'page_pipeline_report' },\n ],\n },\n\n // \u2500\u2500 Global Utility \u2500\u2500\n { id: 'nav_settings', type: 'page', label: 'Settings', icon: 'settings', pageName: 'admin_settings' },\n { id: 'nav_help', type: 'url', label: 'Help', icon: 'help-circle', url: 'https://help.example.com', target: '_blank' },\n ],\n\n homePageId: 'nav_pipeline',\n requiredPermissions: ['app.access.crm'],\n isDefault: true,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Translation Definitions Barrel\n */\nexport { CrmTranslations } from './crm.translation';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * English (en) \u2014 CRM App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n * Each file exports a single `TranslationData` object for its locale.\n */\nexport const en: TranslationData = {\n objects: {\n account: {\n label: 'Account',\n pluralLabel: 'Accounts',\n fields: {\n account_number: { label: 'Account Number' },\n name: { label: 'Account Name', help: 'Legal name of the company or organization' },\n type: {\n label: 'Type',\n options: { prospect: 'Prospect', customer: 'Customer', partner: 'Partner', former: 'Former' },\n },\n industry: {\n label: 'Industry',\n options: {\n technology: 'Technology', finance: 'Finance', healthcare: 'Healthcare',\n retail: 'Retail', manufacturing: 'Manufacturing', education: 'Education',\n },\n },\n annual_revenue: { label: 'Annual Revenue' },\n number_of_employees: { label: 'Number of Employees' },\n phone: { label: 'Phone' },\n website: { label: 'Website' },\n billing_address: { label: 'Billing Address' },\n office_location: { label: 'Office Location' },\n owner: { label: 'Account Owner' },\n parent_account: { label: 'Parent Account' },\n description: { label: 'Description' },\n is_active: { label: 'Active' },\n last_activity_date: { label: 'Last Activity Date' },\n },\n },\n\n contact: {\n label: 'Contact',\n pluralLabel: 'Contacts',\n fields: {\n salutation: { label: 'Salutation' },\n first_name: { label: 'First Name' },\n last_name: { label: 'Last Name' },\n full_name: { label: 'Full Name' },\n account: { label: 'Account' },\n email: { label: 'Email' },\n phone: { label: 'Phone' },\n mobile: { label: 'Mobile' },\n title: { label: 'Title' },\n department: {\n label: 'Department',\n options: {\n Executive: 'Executive', Sales: 'Sales', Marketing: 'Marketing',\n Engineering: 'Engineering', Support: 'Support', Finance: 'Finance',\n HR: 'Human Resources', Operations: 'Operations',\n },\n },\n owner: { label: 'Contact Owner' },\n description: { label: 'Description' },\n is_primary: { label: 'Primary Contact' },\n },\n },\n\n lead: {\n label: 'Lead',\n pluralLabel: 'Leads',\n fields: {\n first_name: { label: 'First Name' },\n last_name: { label: 'Last Name' },\n company: { label: 'Company' },\n title: { label: 'Title' },\n email: { label: 'Email' },\n phone: { label: 'Phone' },\n status: {\n label: 'Status',\n options: {\n new: 'New', contacted: 'Contacted', qualified: 'Qualified',\n unqualified: 'Unqualified', converted: 'Converted',\n },\n },\n lead_source: {\n label: 'Lead Source',\n options: {\n Web: 'Web', Referral: 'Referral', Event: 'Event',\n Partner: 'Partner', Advertisement: 'Advertisement', 'Cold Call': 'Cold Call',\n },\n },\n owner: { label: 'Lead Owner' },\n is_converted: { label: 'Converted' },\n description: { label: 'Description' },\n },\n },\n\n opportunity: {\n label: 'Opportunity',\n pluralLabel: 'Opportunities',\n fields: {\n name: { label: 'Opportunity Name' },\n account: { label: 'Account' },\n primary_contact: { label: 'Primary Contact' },\n owner: { label: 'Opportunity Owner' },\n amount: { label: 'Amount' },\n expected_revenue: { label: 'Expected Revenue' },\n stage: {\n label: 'Stage',\n options: {\n prospecting: 'Prospecting', qualification: 'Qualification',\n needs_analysis: 'Needs Analysis', proposal: 'Proposal',\n negotiation: 'Negotiation', closed_won: 'Closed Won', closed_lost: 'Closed Lost',\n },\n },\n probability: { label: 'Probability (%)' },\n close_date: { label: 'Close Date' },\n type: {\n label: 'Type',\n options: {\n 'New Business': 'New Business',\n 'Existing Customer - Upgrade': 'Existing Customer - Upgrade',\n 'Existing Customer - Renewal': 'Existing Customer - Renewal',\n 'Existing Customer - Expansion': 'Existing Customer - Expansion',\n },\n },\n forecast_category: {\n label: 'Forecast Category',\n options: {\n Pipeline: 'Pipeline', 'Best Case': 'Best Case',\n Commit: 'Commit', Omitted: 'Omitted', Closed: 'Closed',\n },\n },\n description: { label: 'Description' },\n next_step: { label: 'Next Step' },\n },\n },\n },\n\n apps: {\n crm_enterprise: {\n label: 'Enterprise CRM',\n description: 'Customer relationship management for sales, service, and marketing',\n },\n },\n\n messages: {\n 'common.save': 'Save',\n 'common.cancel': 'Cancel',\n 'common.delete': 'Delete',\n 'common.edit': 'Edit',\n 'common.create': 'Create',\n 'common.search': 'Search',\n 'common.filter': 'Filter',\n 'common.export': 'Export',\n 'common.back': 'Back',\n 'common.confirm': 'Confirm',\n 'nav.sales': 'Sales',\n 'nav.service': 'Service',\n 'nav.marketing': 'Marketing',\n 'nav.products': 'Products',\n 'nav.analytics': 'Analytics',\n 'success.saved': 'Record saved successfully',\n 'success.converted': 'Lead converted successfully',\n 'confirm.delete': 'Are you sure you want to delete this record?',\n 'confirm.convert_lead': 'Convert this lead to account, contact, and opportunity?',\n 'error.required': 'This field is required',\n 'error.load_failed': 'Failed to load data',\n },\n\n validationMessages: {\n amount_required_for_closed: 'Amount is required when stage is Closed Won',\n close_date_required: 'Close date is required for opportunities',\n discount_limit: 'Discount cannot exceed 40%',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * \u7B80\u4F53\u4E2D\u6587 (zh-CN) \u2014 CRM App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const zhCN: TranslationData = {\n objects: {\n account: {\n label: '\u5BA2\u6237',\n pluralLabel: '\u5BA2\u6237',\n fields: {\n account_number: { label: '\u5BA2\u6237\u7F16\u53F7' },\n name: { label: '\u5BA2\u6237\u540D\u79F0', help: '\u516C\u53F8\u6216\u7EC4\u7EC7\u7684\u6CD5\u5B9A\u540D\u79F0' },\n type: {\n label: '\u7C7B\u578B',\n options: { prospect: '\u6F5C\u5728\u5BA2\u6237', customer: '\u6B63\u5F0F\u5BA2\u6237', partner: '\u5408\u4F5C\u4F19\u4F34', former: '\u524D\u5BA2\u6237' },\n },\n industry: {\n label: '\u884C\u4E1A',\n options: {\n technology: '\u79D1\u6280', finance: '\u91D1\u878D', healthcare: '\u533B\u7597',\n retail: '\u96F6\u552E', manufacturing: '\u5236\u9020', education: '\u6559\u80B2',\n },\n },\n annual_revenue: { label: '\u5E74\u8425\u6536' },\n number_of_employees: { label: '\u5458\u5DE5\u4EBA\u6570' },\n phone: { label: '\u7535\u8BDD' },\n website: { label: '\u7F51\u7AD9' },\n billing_address: { label: '\u8D26\u5355\u5730\u5740' },\n office_location: { label: '\u529E\u516C\u5730\u70B9' },\n owner: { label: '\u5BA2\u6237\u8D1F\u8D23\u4EBA' },\n parent_account: { label: '\u6BCD\u516C\u53F8' },\n description: { label: '\u63CF\u8FF0' },\n is_active: { label: '\u662F\u5426\u6D3B\u8DC3' },\n last_activity_date: { label: '\u6700\u8FD1\u6D3B\u52A8\u65E5\u671F' },\n },\n },\n\n contact: {\n label: '\u8054\u7CFB\u4EBA',\n pluralLabel: '\u8054\u7CFB\u4EBA',\n fields: {\n salutation: { label: '\u79F0\u8C13' },\n first_name: { label: '\u540D' },\n last_name: { label: '\u59D3' },\n full_name: { label: '\u5168\u540D' },\n account: { label: '\u6240\u5C5E\u5BA2\u6237' },\n email: { label: '\u90AE\u7BB1' },\n phone: { label: '\u7535\u8BDD' },\n mobile: { label: '\u624B\u673A' },\n title: { label: '\u804C\u4F4D' },\n department: {\n label: '\u90E8\u95E8',\n options: {\n Executive: '\u7BA1\u7406\u5C42', Sales: '\u9500\u552E\u90E8', Marketing: '\u5E02\u573A\u90E8',\n Engineering: '\u5DE5\u7A0B\u90E8', Support: '\u652F\u6301\u90E8', Finance: '\u8D22\u52A1\u90E8',\n HR: '\u4EBA\u529B\u8D44\u6E90', Operations: '\u8FD0\u8425\u90E8',\n },\n },\n owner: { label: '\u8054\u7CFB\u4EBA\u8D1F\u8D23\u4EBA' },\n description: { label: '\u63CF\u8FF0' },\n is_primary: { label: '\u4E3B\u8981\u8054\u7CFB\u4EBA' },\n },\n },\n\n lead: {\n label: '\u7EBF\u7D22',\n pluralLabel: '\u7EBF\u7D22',\n fields: {\n first_name: { label: '\u540D' },\n last_name: { label: '\u59D3' },\n company: { label: '\u516C\u53F8' },\n title: { label: '\u804C\u4F4D' },\n email: { label: '\u90AE\u7BB1' },\n phone: { label: '\u7535\u8BDD' },\n status: {\n label: '\u72B6\u6001',\n options: {\n new: '\u65B0\u5EFA', contacted: '\u5DF2\u8054\u7CFB', qualified: '\u5DF2\u786E\u8BA4',\n unqualified: '\u4E0D\u5408\u683C', converted: '\u5DF2\u8F6C\u5316',\n },\n },\n lead_source: {\n label: '\u7EBF\u7D22\u6765\u6E90',\n options: {\n Web: '\u7F51\u7AD9', Referral: '\u63A8\u8350', Event: '\u6D3B\u52A8',\n Partner: '\u5408\u4F5C\u4F19\u4F34', Advertisement: '\u5E7F\u544A', 'Cold Call': '\u964C\u751F\u62DC\u8BBF',\n },\n },\n owner: { label: '\u7EBF\u7D22\u8D1F\u8D23\u4EBA' },\n is_converted: { label: '\u5DF2\u8F6C\u5316' },\n description: { label: '\u63CF\u8FF0' },\n },\n },\n\n opportunity: {\n label: '\u5546\u673A',\n pluralLabel: '\u5546\u673A',\n fields: {\n name: { label: '\u5546\u673A\u540D\u79F0' },\n account: { label: '\u6240\u5C5E\u5BA2\u6237' },\n primary_contact: { label: '\u4E3B\u8981\u8054\u7CFB\u4EBA' },\n owner: { label: '\u5546\u673A\u8D1F\u8D23\u4EBA' },\n amount: { label: '\u91D1\u989D' },\n expected_revenue: { label: '\u9884\u671F\u6536\u5165' },\n stage: {\n label: '\u9636\u6BB5',\n options: {\n prospecting: '\u5BFB\u627E\u5BA2\u6237', qualification: '\u8D44\u683C\u5BA1\u67E5',\n needs_analysis: '\u9700\u6C42\u5206\u6790', proposal: '\u63D0\u6848',\n negotiation: '\u8C08\u5224', closed_won: '\u6210\u4EA4', closed_lost: '\u5931\u8D25',\n },\n },\n probability: { label: '\u6210\u4EA4\u6982\u7387 (%)' },\n close_date: { label: '\u9884\u8BA1\u6210\u4EA4\u65E5\u671F' },\n type: {\n label: '\u7C7B\u578B',\n options: {\n 'New Business': '\u65B0\u4E1A\u52A1',\n 'Existing Customer - Upgrade': '\u8001\u5BA2\u6237\u5347\u7EA7',\n 'Existing Customer - Renewal': '\u8001\u5BA2\u6237\u7EED\u7EA6',\n 'Existing Customer - Expansion': '\u8001\u5BA2\u6237\u62D3\u5C55',\n },\n },\n forecast_category: {\n label: '\u9884\u6D4B\u7C7B\u522B',\n options: {\n Pipeline: '\u7BA1\u9053', 'Best Case': '\u6700\u4F73\u60C5\u51B5',\n Commit: '\u627F\u8BFA', Omitted: '\u5DF2\u6392\u9664', Closed: '\u5DF2\u5173\u95ED',\n },\n },\n description: { label: '\u63CF\u8FF0' },\n next_step: { label: '\u4E0B\u4E00\u6B65' },\n },\n },\n },\n\n apps: {\n crm_enterprise: {\n label: '\u4F01\u4E1A CRM',\n description: '\u6DB5\u76D6\u9500\u552E\u3001\u670D\u52A1\u548C\u5E02\u573A\u8425\u9500\u7684\u5BA2\u6237\u5173\u7CFB\u7BA1\u7406\u7CFB\u7EDF',\n },\n },\n\n messages: {\n 'common.save': '\u4FDD\u5B58',\n 'common.cancel': '\u53D6\u6D88',\n 'common.delete': '\u5220\u9664',\n 'common.edit': '\u7F16\u8F91',\n 'common.create': '\u65B0\u5EFA',\n 'common.search': '\u641C\u7D22',\n 'common.filter': '\u7B5B\u9009',\n 'common.export': '\u5BFC\u51FA',\n 'common.back': '\u8FD4\u56DE',\n 'common.confirm': '\u786E\u8BA4',\n 'nav.sales': '\u9500\u552E',\n 'nav.service': '\u670D\u52A1',\n 'nav.marketing': '\u8425\u9500',\n 'nav.products': '\u4EA7\u54C1',\n 'nav.analytics': '\u6570\u636E\u5206\u6790',\n 'success.saved': '\u8BB0\u5F55\u4FDD\u5B58\u6210\u529F',\n 'success.converted': '\u7EBF\u7D22\u8F6C\u5316\u6210\u529F',\n 'confirm.delete': '\u786E\u5B9A\u8981\u5220\u9664\u6B64\u8BB0\u5F55\u5417\uFF1F',\n 'confirm.convert_lead': '\u5C06\u6B64\u7EBF\u7D22\u8F6C\u5316\u4E3A\u5BA2\u6237\u3001\u8054\u7CFB\u4EBA\u548C\u5546\u673A\uFF1F',\n 'error.required': '\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879',\n 'error.load_failed': '\u6570\u636E\u52A0\u8F7D\u5931\u8D25',\n },\n\n validationMessages: {\n amount_required_for_closed: '\u9636\u6BB5\u4E3A\"\u6210\u4EA4\"\u65F6\uFF0C\u91D1\u989D\u4E3A\u5FC5\u586B\u9879',\n close_date_required: '\u5546\u673A\u5FC5\u987B\u586B\u5199\u9884\u8BA1\u6210\u4EA4\u65E5\u671F',\n discount_limit: '\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * \u65E5\u672C\u8A9E (ja-JP) \u2014 CRM App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const jaJP: TranslationData = {\n objects: {\n account: {\n label: '\u53D6\u5F15\u5148',\n pluralLabel: '\u53D6\u5F15\u5148',\n fields: {\n account_number: { label: '\u53D6\u5F15\u5148\u756A\u53F7' },\n name: { label: '\u53D6\u5F15\u5148\u540D', help: '\u4F1A\u793E\u307E\u305F\u306F\u7D44\u7E54\u306E\u6B63\u5F0F\u540D\u79F0' },\n type: {\n label: '\u30BF\u30A4\u30D7',\n options: { prospect: '\u898B\u8FBC\u307F\u5BA2', customer: '\u9867\u5BA2', partner: '\u30D1\u30FC\u30C8\u30CA\u30FC', former: '\u904E\u53BB\u306E\u53D6\u5F15\u5148' },\n },\n industry: {\n label: '\u696D\u7A2E',\n options: {\n technology: '\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC', finance: '\u91D1\u878D', healthcare: '\u30D8\u30EB\u30B9\u30B1\u30A2',\n retail: '\u5C0F\u58F2', manufacturing: '\u88FD\u9020', education: '\u6559\u80B2',\n },\n },\n annual_revenue: { label: '\u5E74\u9593\u58F2\u4E0A' },\n number_of_employees: { label: '\u5F93\u696D\u54E1\u6570' },\n phone: { label: '\u96FB\u8A71\u756A\u53F7' },\n website: { label: 'Web\u30B5\u30A4\u30C8' },\n billing_address: { label: '\u8ACB\u6C42\u5148\u4F4F\u6240' },\n office_location: { label: '\u30AA\u30D5\u30A3\u30B9\u6240\u5728\u5730' },\n owner: { label: '\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005' },\n parent_account: { label: '\u89AA\u53D6\u5F15\u5148' },\n description: { label: '\u8AAC\u660E' },\n is_active: { label: '\u6709\u52B9' },\n last_activity_date: { label: '\u6700\u7D42\u6D3B\u52D5\u65E5' },\n },\n },\n\n contact: {\n label: '\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005',\n pluralLabel: '\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005',\n fields: {\n salutation: { label: '\u656C\u79F0' },\n first_name: { label: '\u540D' },\n last_name: { label: '\u59D3' },\n full_name: { label: '\u6C0F\u540D' },\n account: { label: '\u53D6\u5F15\u5148' },\n email: { label: '\u30E1\u30FC\u30EB' },\n phone: { label: '\u96FB\u8A71' },\n mobile: { label: '\u643A\u5E2F\u96FB\u8A71' },\n title: { label: '\u5F79\u8077' },\n department: {\n label: '\u90E8\u9580',\n options: {\n Executive: '\u7D4C\u55B6\u5C64', Sales: '\u55B6\u696D\u90E8', Marketing: '\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u90E8',\n Engineering: '\u30A8\u30F3\u30B8\u30CB\u30A2\u30EA\u30F3\u30B0\u90E8', Support: '\u30B5\u30DD\u30FC\u30C8\u90E8', Finance: '\u7D4C\u7406\u90E8',\n HR: '\u4EBA\u4E8B\u90E8', Operations: '\u30AA\u30DA\u30EC\u30FC\u30B7\u30E7\u30F3\u90E8',\n },\n },\n owner: { label: '\u6240\u6709\u8005' },\n description: { label: '\u8AAC\u660E' },\n is_primary: { label: '\u4E3B\u62C5\u5F53\u8005' },\n },\n },\n\n lead: {\n label: '\u30EA\u30FC\u30C9',\n pluralLabel: '\u30EA\u30FC\u30C9',\n fields: {\n first_name: { label: '\u540D' },\n last_name: { label: '\u59D3' },\n company: { label: '\u4F1A\u793E\u540D' },\n title: { label: '\u5F79\u8077' },\n email: { label: '\u30E1\u30FC\u30EB' },\n phone: { label: '\u96FB\u8A71' },\n status: {\n label: '\u30B9\u30C6\u30FC\u30BF\u30B9',\n options: {\n new: '\u65B0\u898F', contacted: '\u30B3\u30F3\u30BF\u30AF\u30C8\u6E08\u307F', qualified: '\u9069\u683C',\n unqualified: '\u4E0D\u9069\u683C', converted: '\u53D6\u5F15\u958B\u59CB\u6E08\u307F',\n },\n },\n lead_source: {\n label: '\u30EA\u30FC\u30C9\u30BD\u30FC\u30B9',\n options: {\n Web: 'Web', Referral: '\u7D39\u4ECB', Event: '\u30A4\u30D9\u30F3\u30C8',\n Partner: '\u30D1\u30FC\u30C8\u30CA\u30FC', Advertisement: '\u5E83\u544A', 'Cold Call': '\u30B3\u30FC\u30EB\u30C9\u30B3\u30FC\u30EB',\n },\n },\n owner: { label: '\u30EA\u30FC\u30C9\u6240\u6709\u8005' },\n is_converted: { label: '\u53D6\u5F15\u958B\u59CB\u6E08\u307F' },\n description: { label: '\u8AAC\u660E' },\n },\n },\n\n opportunity: {\n label: '\u5546\u8AC7',\n pluralLabel: '\u5546\u8AC7',\n fields: {\n name: { label: '\u5546\u8AC7\u540D' },\n account: { label: '\u53D6\u5F15\u5148' },\n primary_contact: { label: '\u4E3B\u62C5\u5F53\u8005' },\n owner: { label: '\u5546\u8AC7\u6240\u6709\u8005' },\n amount: { label: '\u91D1\u984D' },\n expected_revenue: { label: '\u671F\u5F85\u53CE\u76CA' },\n stage: {\n label: '\u30D5\u30A7\u30FC\u30BA',\n options: {\n prospecting: '\u898B\u8FBC\u307F\u8ABF\u67FB', qualification: '\u9078\u5B9A',\n needs_analysis: '\u30CB\u30FC\u30BA\u5206\u6790', proposal: '\u63D0\u6848',\n negotiation: '\u4EA4\u6E09', closed_won: '\u6210\u7ACB', closed_lost: '\u4E0D\u6210\u7ACB',\n },\n },\n probability: { label: '\u78BA\u5EA6 (%)' },\n close_date: { label: '\u5B8C\u4E86\u4E88\u5B9A\u65E5' },\n type: {\n label: '\u30BF\u30A4\u30D7',\n options: {\n 'New Business': '\u65B0\u898F\u30D3\u30B8\u30CD\u30B9',\n 'Existing Customer - Upgrade': '\u65E2\u5B58\u9867\u5BA2 - \u30A2\u30C3\u30D7\u30B0\u30EC\u30FC\u30C9',\n 'Existing Customer - Renewal': '\u65E2\u5B58\u9867\u5BA2 - \u66F4\u65B0',\n 'Existing Customer - Expansion': '\u65E2\u5B58\u9867\u5BA2 - \u62E1\u5927',\n },\n },\n forecast_category: {\n label: '\u58F2\u4E0A\u4E88\u6E2C\u30AB\u30C6\u30B4\u30EA',\n options: {\n Pipeline: '\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3', 'Best Case': '\u6700\u826F\u30B1\u30FC\u30B9',\n Commit: '\u30B3\u30DF\u30C3\u30C8', Omitted: '\u9664\u5916', Closed: '\u5B8C\u4E86',\n },\n },\n description: { label: '\u8AAC\u660E' },\n next_step: { label: '\u6B21\u306E\u30B9\u30C6\u30C3\u30D7' },\n },\n },\n },\n\n apps: {\n crm_enterprise: {\n label: '\u30A8\u30F3\u30BF\u30FC\u30D7\u30E9\u30A4\u30BA CRM',\n description: '\u55B6\u696D\u30FB\u30B5\u30FC\u30D3\u30B9\u30FB\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u5411\u3051\u9867\u5BA2\u95A2\u4FC2\u7BA1\u7406\u30B7\u30B9\u30C6\u30E0',\n },\n },\n\n messages: {\n 'common.save': '\u4FDD\u5B58',\n 'common.cancel': '\u30AD\u30E3\u30F3\u30BB\u30EB',\n 'common.delete': '\u524A\u9664',\n 'common.edit': '\u7DE8\u96C6',\n 'common.create': '\u65B0\u898F\u4F5C\u6210',\n 'common.search': '\u691C\u7D22',\n 'common.filter': '\u30D5\u30A3\u30EB\u30BF\u30FC',\n 'common.export': '\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8',\n 'common.back': '\u623B\u308B',\n 'common.confirm': '\u78BA\u8A8D',\n 'nav.sales': '\u55B6\u696D',\n 'nav.service': '\u30B5\u30FC\u30D3\u30B9',\n 'nav.marketing': '\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0',\n 'nav.products': '\u88FD\u54C1',\n 'nav.analytics': '\u30A2\u30CA\u30EA\u30C6\u30A3\u30AF\u30B9',\n 'success.saved': '\u30EC\u30B3\u30FC\u30C9\u3092\u4FDD\u5B58\u3057\u307E\u3057\u305F',\n 'success.converted': '\u30EA\u30FC\u30C9\u3092\u53D6\u5F15\u958B\u59CB\u3057\u307E\u3057\u305F',\n 'confirm.delete': '\u3053\u306E\u30EC\u30B3\u30FC\u30C9\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F',\n 'confirm.convert_lead': '\u3053\u306E\u30EA\u30FC\u30C9\u3092\u53D6\u5F15\u5148\u30FB\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005\u30FB\u5546\u8AC7\u306B\u5909\u63DB\u3057\u307E\u3059\u304B\uFF1F',\n 'error.required': '\u3053\u306E\u9805\u76EE\u306F\u5FC5\u9808\u3067\u3059',\n 'error.load_failed': '\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F',\n },\n\n validationMessages: {\n amount_required_for_closed: '\u30D5\u30A7\u30FC\u30BA\u304C\u300C\u6210\u7ACB\u300D\u306E\u5834\u5408\u3001\u91D1\u984D\u306F\u5FC5\u9808\u3067\u3059',\n close_date_required: '\u5546\u8AC7\u306B\u306F\u5B8C\u4E86\u4E88\u5B9A\u65E5\u304C\u5FC5\u8981\u3067\u3059',\n discount_limit: '\u5272\u5F15\u306F40%\u3092\u8D85\u3048\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * Espa\u00F1ol (es-ES) \u2014 CRM App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const esES: TranslationData = {\n objects: {\n account: {\n label: 'Cuenta',\n pluralLabel: 'Cuentas',\n fields: {\n account_number: { label: 'N\u00FAmero de Cuenta' },\n name: { label: 'Nombre de Cuenta', help: 'Nombre legal de la empresa u organizaci\u00F3n' },\n type: {\n label: 'Tipo',\n options: { prospect: 'Prospecto', customer: 'Cliente', partner: 'Socio', former: 'Anterior' },\n },\n industry: {\n label: 'Industria',\n options: {\n technology: 'Tecnolog\u00EDa', finance: 'Finanzas', healthcare: 'Salud',\n retail: 'Comercio', manufacturing: 'Manufactura', education: 'Educaci\u00F3n',\n },\n },\n annual_revenue: { label: 'Ingresos Anuales' },\n number_of_employees: { label: 'N\u00FAmero de Empleados' },\n phone: { label: 'Tel\u00E9fono' },\n website: { label: 'Sitio Web' },\n billing_address: { label: 'Direcci\u00F3n de Facturaci\u00F3n' },\n office_location: { label: 'Ubicaci\u00F3n de Oficina' },\n owner: { label: 'Propietario de Cuenta' },\n parent_account: { label: 'Cuenta Matriz' },\n description: { label: 'Descripci\u00F3n' },\n is_active: { label: 'Activo' },\n last_activity_date: { label: 'Fecha de \u00DAltima Actividad' },\n },\n },\n\n contact: {\n label: 'Contacto',\n pluralLabel: 'Contactos',\n fields: {\n salutation: { label: 'T\u00EDtulo' },\n first_name: { label: 'Nombre' },\n last_name: { label: 'Apellido' },\n full_name: { label: 'Nombre Completo' },\n account: { label: 'Cuenta' },\n email: { label: 'Correo Electr\u00F3nico' },\n phone: { label: 'Tel\u00E9fono' },\n mobile: { label: 'M\u00F3vil' },\n title: { label: 'Cargo' },\n department: {\n label: 'Departamento',\n options: {\n Executive: 'Ejecutivo', Sales: 'Ventas', Marketing: 'Marketing',\n Engineering: 'Ingenier\u00EDa', Support: 'Soporte', Finance: 'Finanzas',\n HR: 'Recursos Humanos', Operations: 'Operaciones',\n },\n },\n owner: { label: 'Propietario de Contacto' },\n description: { label: 'Descripci\u00F3n' },\n is_primary: { label: 'Contacto Principal' },\n },\n },\n\n lead: {\n label: 'Prospecto',\n pluralLabel: 'Prospectos',\n fields: {\n first_name: { label: 'Nombre' },\n last_name: { label: 'Apellido' },\n company: { label: 'Empresa' },\n title: { label: 'Cargo' },\n email: { label: 'Correo Electr\u00F3nico' },\n phone: { label: 'Tel\u00E9fono' },\n status: {\n label: 'Estado',\n options: {\n new: 'Nuevo', contacted: 'Contactado', qualified: 'Calificado',\n unqualified: 'No Calificado', converted: 'Convertido',\n },\n },\n lead_source: {\n label: 'Origen del Prospecto',\n options: {\n Web: 'Web', Referral: 'Referencia', Event: 'Evento',\n Partner: 'Socio', Advertisement: 'Publicidad', 'Cold Call': 'Llamada en Fr\u00EDo',\n },\n },\n owner: { label: 'Propietario' },\n is_converted: { label: 'Convertido' },\n description: { label: 'Descripci\u00F3n' },\n },\n },\n\n opportunity: {\n label: 'Oportunidad',\n pluralLabel: 'Oportunidades',\n fields: {\n name: { label: 'Nombre de Oportunidad' },\n account: { label: 'Cuenta' },\n primary_contact: { label: 'Contacto Principal' },\n owner: { label: 'Propietario de Oportunidad' },\n amount: { label: 'Monto' },\n expected_revenue: { label: 'Ingreso Esperado' },\n stage: {\n label: 'Etapa',\n options: {\n prospecting: 'Prospecci\u00F3n', qualification: 'Calificaci\u00F3n',\n needs_analysis: 'An\u00E1lisis de Necesidades', proposal: 'Propuesta',\n negotiation: 'Negociaci\u00F3n', closed_won: 'Cerrada Ganada', closed_lost: 'Cerrada Perdida',\n },\n },\n probability: { label: 'Probabilidad (%)' },\n close_date: { label: 'Fecha de Cierre' },\n type: {\n label: 'Tipo',\n options: {\n 'New Business': 'Nuevo Negocio',\n 'Existing Customer - Upgrade': 'Cliente Existente - Mejora',\n 'Existing Customer - Renewal': 'Cliente Existente - Renovaci\u00F3n',\n 'Existing Customer - Expansion': 'Cliente Existente - Expansi\u00F3n',\n },\n },\n forecast_category: {\n label: 'Categor\u00EDa de Pron\u00F3stico',\n options: {\n Pipeline: 'Pipeline', 'Best Case': 'Mejor Caso',\n Commit: 'Compromiso', Omitted: 'Omitida', Closed: 'Cerrada',\n },\n },\n description: { label: 'Descripci\u00F3n' },\n next_step: { label: 'Pr\u00F3ximo Paso' },\n },\n },\n },\n\n apps: {\n crm_enterprise: {\n label: 'CRM Empresarial',\n description: 'Gesti\u00F3n de relaciones con clientes para ventas, servicio y marketing',\n },\n },\n\n messages: {\n 'common.save': 'Guardar',\n 'common.cancel': 'Cancelar',\n 'common.delete': 'Eliminar',\n 'common.edit': 'Editar',\n 'common.create': 'Crear',\n 'common.search': 'Buscar',\n 'common.filter': 'Filtrar',\n 'common.export': 'Exportar',\n 'common.back': 'Volver',\n 'common.confirm': 'Confirmar',\n 'nav.sales': 'Ventas',\n 'nav.service': 'Servicio',\n 'nav.marketing': 'Marketing',\n 'nav.products': 'Productos',\n 'nav.analytics': 'Anal\u00EDtica',\n 'success.saved': 'Registro guardado exitosamente',\n 'success.converted': 'Prospecto convertido exitosamente',\n 'confirm.delete': '\u00BFEst\u00E1 seguro de que desea eliminar este registro?',\n 'confirm.convert_lead': '\u00BFConvertir este prospecto en cuenta, contacto y oportunidad?',\n 'error.required': 'Este campo es obligatorio',\n 'error.load_failed': 'Error al cargar los datos',\n },\n\n validationMessages: {\n amount_required_for_closed: 'El monto es obligatorio cuando la etapa es Cerrada Ganada',\n close_date_required: 'La fecha de cierre es obligatoria para las oportunidades',\n discount_limit: 'El descuento no puede superar el 40%',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationBundle } from '@objectstack/spec/system';\nimport { en } from './en';\nimport { zhCN } from './zh-CN';\nimport { jaJP } from './ja-JP';\nimport { esES } from './es-ES';\n\n/**\n * CRM App \u2014 Internationalization (i18n)\n *\n * Demonstrates **per-locale file splitting** convention:\n * each language is defined in its own file (`en.ts`, `zh-CN.ts`, `ja-JP.ts`, `es-ES.ts`)\n * and assembled into a single `TranslationBundle` here.\n *\n * Enterprise-grade multi-language translations covering:\n * - Core CRM objects: Account, Contact, Lead, Opportunity\n * - Select-field option labels for each object\n * - App & navigation group labels\n * - Common UI messages, validation messages\n *\n * Supported locales: en, zh-CN, ja-JP, es-ES\n */\nexport const CrmTranslations: TranslationBundle = {\n en,\n 'zh-CN': zhCN,\n 'ja-JP': jaJP,\n 'es-ES': esES,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * CRM Seed Data\n * \n * Demo records for all core CRM objects.\n * Uses the DatasetSchema format with upsert mode for idempotent loading.\n */\nimport type { DatasetInput } from '@objectstack/spec/data';\n\n// \u2500\u2500\u2500 Accounts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst accounts: DatasetInput = {\n object: 'account',\n mode: 'upsert',\n externalId: 'name',\n records: [\n {\n name: 'Acme Corporation',\n type: 'customer',\n industry: 'technology',\n annual_revenue: 5000000,\n number_of_employees: 250,\n phone: '+1-415-555-0100',\n website: 'https://acme.example.com',\n },\n {\n name: 'Globex Industries',\n type: 'prospect',\n industry: 'manufacturing',\n annual_revenue: 12000000,\n number_of_employees: 800,\n phone: '+1-312-555-0200',\n website: 'https://globex.example.com',\n },\n {\n name: 'Initech Solutions',\n type: 'customer',\n industry: 'finance',\n annual_revenue: 3500000,\n number_of_employees: 150,\n phone: '+1-212-555-0300',\n website: 'https://initech.example.com',\n },\n {\n name: 'Stark Medical',\n type: 'partner',\n industry: 'healthcare',\n annual_revenue: 8000000,\n number_of_employees: 400,\n phone: '+1-617-555-0400',\n website: 'https://starkmed.example.com',\n },\n {\n name: 'Wayne Enterprises',\n type: 'customer',\n industry: 'technology',\n annual_revenue: 25000000,\n number_of_employees: 2000,\n phone: '+1-650-555-0500',\n website: 'https://wayne.example.com',\n },\n ]\n};\n\n// \u2500\u2500\u2500 Contacts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst contacts: DatasetInput = {\n object: 'contact',\n mode: 'upsert',\n externalId: 'email',\n records: [\n {\n salutation: 'Mr.',\n first_name: 'John',\n last_name: 'Smith',\n email: 'john.smith@acme.example.com',\n phone: '+1-415-555-0101',\n title: 'VP of Engineering',\n department: 'Engineering',\n },\n {\n salutation: 'Ms.',\n first_name: 'Sarah',\n last_name: 'Johnson',\n email: 'sarah.j@globex.example.com',\n phone: '+1-312-555-0201',\n title: 'Chief Procurement Officer',\n department: 'Executive',\n },\n {\n salutation: 'Dr.',\n first_name: 'Michael',\n last_name: 'Chen',\n email: 'mchen@initech.example.com',\n phone: '+1-212-555-0301',\n title: 'Director of Operations',\n department: 'Operations',\n },\n {\n salutation: 'Ms.',\n first_name: 'Emily',\n last_name: 'Davis',\n email: 'emily.d@starkmed.example.com',\n phone: '+1-617-555-0401',\n title: 'Head of Partnerships',\n department: 'Sales',\n },\n {\n salutation: 'Mr.',\n first_name: 'Robert',\n last_name: 'Wilson',\n email: 'rwilson@wayne.example.com',\n phone: '+1-650-555-0501',\n title: 'CTO',\n department: 'Engineering',\n },\n ]\n};\n\n// \u2500\u2500\u2500 Leads \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst leads: DatasetInput = {\n object: 'lead',\n mode: 'upsert',\n externalId: 'email',\n records: [\n {\n first_name: 'Alice',\n last_name: 'Martinez',\n company: 'NextGen Retail',\n email: 'alice@nextgenretail.example.com',\n phone: '+1-503-555-0600',\n status: 'new',\n source: 'website',\n industry: 'Retail',\n },\n {\n first_name: 'David',\n last_name: 'Kim',\n company: 'EduTech Labs',\n email: 'dkim@edutechlabs.example.com',\n phone: '+1-408-555-0700',\n status: 'contacted',\n source: 'referral',\n industry: 'Education',\n },\n {\n first_name: 'Lisa',\n last_name: 'Thompson',\n company: 'CloudFirst Inc',\n email: 'lisa.t@cloudfirst.example.com',\n phone: '+1-206-555-0800',\n status: 'qualified',\n source: 'trade_show',\n industry: 'Technology',\n },\n ]\n};\n\n// \u2500\u2500\u2500 Opportunities \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst opportunities: DatasetInput = {\n object: 'opportunity',\n mode: 'upsert',\n externalId: 'name',\n records: [\n {\n name: 'Acme Platform Upgrade',\n amount: 150000,\n stage: 'proposal',\n probability: 60,\n close_date: new Date(Date.now() + 86400000 * 30),\n type: 'existing_business',\n forecast_category: 'pipeline',\n },\n {\n name: 'Globex Manufacturing Suite',\n amount: 500000,\n stage: 'qualification',\n probability: 30,\n close_date: new Date(Date.now() + 86400000 * 60),\n type: 'new_business',\n forecast_category: 'pipeline',\n },\n {\n name: 'Wayne Enterprise License',\n amount: 1200000,\n stage: 'negotiation',\n probability: 75,\n close_date: new Date(Date.now() + 86400000 * 14),\n type: 'new_business',\n forecast_category: 'commit',\n },\n {\n name: 'Initech Cloud Migration',\n amount: 80000,\n stage: 'needs_analysis',\n probability: 25,\n close_date: new Date(Date.now() + 86400000 * 45),\n type: 'existing_business',\n forecast_category: 'best_case',\n },\n ]\n};\n\n// \u2500\u2500\u2500 Products \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst products: DatasetInput = {\n object: 'product',\n mode: 'upsert',\n externalId: 'name',\n records: [\n {\n name: 'ObjectStack Platform',\n category: 'software',\n family: 'enterprise',\n list_price: 50000,\n is_active: true,\n },\n {\n name: 'Cloud Hosting (Annual)',\n category: 'subscription',\n family: 'cloud',\n list_price: 12000,\n is_active: true,\n },\n {\n name: 'Premium Support',\n category: 'support',\n family: 'services',\n list_price: 25000,\n is_active: true,\n },\n {\n name: 'Implementation Services',\n category: 'service',\n family: 'services',\n list_price: 75000,\n is_active: true,\n },\n ]\n};\n\n// \u2500\u2500\u2500 Tasks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst tasks: DatasetInput = {\n object: 'task',\n mode: 'upsert',\n externalId: 'subject',\n records: [\n {\n subject: 'Follow up with Acme on proposal',\n status: 'not_started',\n priority: 'high',\n due_date: new Date(Date.now() + 86400000 * 2),\n },\n {\n subject: 'Schedule demo for Globex team',\n status: 'in_progress',\n priority: 'normal',\n due_date: new Date(Date.now() + 86400000 * 5),\n },\n {\n subject: 'Prepare contract for Wayne Enterprises',\n status: 'not_started',\n priority: 'urgent',\n due_date: new Date(Date.now() + 86400000),\n },\n {\n subject: 'Send welcome package to Stark Medical',\n status: 'completed',\n priority: 'low',\n },\n {\n subject: 'Update CRM pipeline report',\n status: 'not_started',\n priority: 'normal',\n due_date: new Date(Date.now() + 86400000 * 7),\n },\n ]\n};\n\n/** All CRM seed datasets */\nexport const CrmSeedData: DatasetInput[] = [\n accounts,\n contacts,\n leads,\n opportunities,\n products,\n tasks,\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Share accounts with sales managers/directors based on customer status */\nexport const AccountTeamSharingRule = {\n name: 'account_team_sharing',\n label: 'Account Team Sharing',\n object: 'account',\n type: 'criteria' as const,\n condition: 'type = \"customer\" AND is_active = true',\n accessLevel: 'edit',\n sharedWith: { type: 'role', value: 'sales_manager' },\n};\n\n/** Territory-Based Sharing (criteria-based, by billing country) */\nexport const TerritorySharingRules = [\n {\n name: 'north_america_territory',\n label: 'North America Territory',\n object: 'account',\n type: 'criteria' as const,\n condition: 'billing_country IN (\"US\", \"CA\", \"MX\")',\n accessLevel: 'edit',\n sharedWith: { type: 'role', value: 'na_sales_team' },\n },\n {\n name: 'europe_territory',\n label: 'Europe Territory',\n object: 'account',\n type: 'criteria' as const,\n condition: 'billing_country IN (\"UK\", \"DE\", \"FR\", \"IT\", \"ES\")',\n accessLevel: 'edit',\n sharedWith: { type: 'role', value: 'eu_sales_team' },\n },\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Share escalated/critical cases with service managers */\nexport const CaseEscalationSharingRule = {\n name: 'case_escalation_sharing',\n label: 'Escalated Cases Sharing',\n object: 'case',\n type: 'criteria' as const,\n condition: 'priority = \"critical\" AND is_closed = false',\n accessLevel: 'edit',\n sharedWith: { type: 'role_and_subordinates', value: 'service_manager' },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Share high-value open opportunities with management */\nexport const OpportunitySalesSharingRule = {\n name: 'opportunity_sales_sharing',\n label: 'Opportunity Sales Team Sharing',\n object: 'opportunity',\n type: 'criteria' as const,\n condition: 'stage NOT IN (\"closed_won\", \"closed_lost\") AND amount >= 100000',\n accessLevel: 'read',\n sharedWith: { type: 'role_and_subordinates', value: 'sales_director' },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** CRM Role Hierarchy */\nexport const RoleHierarchy = {\n name: 'crm_role_hierarchy',\n label: 'CRM Role Hierarchy',\n roles: [\n { name: 'executive', label: 'Executive', parentRole: null },\n { name: 'sales_director', label: 'Sales Director', parentRole: 'executive' },\n { name: 'sales_manager', label: 'Sales Manager', parentRole: 'sales_director' },\n { name: 'sales_rep', label: 'Sales Representative', parentRole: 'sales_manager' },\n { name: 'service_director', label: 'Service Director', parentRole: 'executive' },\n { name: 'service_manager', label: 'Service Manager', parentRole: 'service_director' },\n { name: 'service_agent', label: 'Service Agent', parentRole: 'service_manager' },\n { name: 'marketing_director', label: 'Marketing Director', parentRole: 'executive' },\n { name: 'marketing_manager', label: 'Marketing Manager', parentRole: 'marketing_director' },\n { name: 'marketing_user', label: 'Marketing User', parentRole: 'marketing_manager' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { defineStack } from '@objectstack/spec';\n\n// \u2500\u2500\u2500 Barrel Imports (one per metadata type) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nimport * as objects from './src/objects';\nimport * as apis from './src/apis';\nimport * as actions from './src/actions';\nimport * as dashboards from './src/dashboards';\nimport * as reports from './src/reports';\nimport { allFlows } from './src/flows';\nimport { allAgents } from './src/agents';\nimport * as ragPipelines from './src/rag';\nimport * as profiles from './src/profiles';\nimport * as apps from './src/apps';\nimport * as translations from './src/translations';\nimport { CrmSeedData } from './src/data';\n\n// \u2500\u2500\u2500 Sharing & Security (special: mixed single/array values) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\nimport {\n AccountTeamSharingRule, TerritorySharingRules,\n OpportunitySalesSharingRule,\n CaseEscalationSharingRule,\n RoleHierarchy,\n} from './src/sharing';\n\n// \u2500\u2500\u2500 Action Handler Registration (runtime lifecycle) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Handlers are wired separately from metadata. The `onEnable` export\n// is called by the kernel's AppPlugin after the engine is ready.\n// See: src/actions/register-handlers.ts for the full registration flow.\nimport { registerCrmActionHandlers } from './src/actions/register-handlers';\n\n/**\n * Plugin lifecycle hook \u2014 called by AppPlugin when the engine is ready.\n * This is where action handlers are registered on the ObjectQL engine.\n */\nexport const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {\n registerCrmActionHandlers(ctx.ql);\n};\n\nexport default defineStack({\n manifest: {\n id: 'com.example.crm',\n namespace: 'crm',\n version: '3.0.0',\n type: 'app',\n name: 'Enterprise CRM',\n description: 'Comprehensive enterprise CRM demonstrating all ObjectStack Protocol features including AI, security, and automation',\n },\n\n // Auto-collected from barrel index files via Object.values()\n objects: Object.values(objects),\n apis: Object.values(apis),\n actions: Object.values(actions),\n dashboards: Object.values(dashboards),\n reports: Object.values(reports),\n flows: allFlows,\n agents: allAgents,\n ragPipelines: Object.values(ragPipelines),\n permissions: Object.values(profiles),\n apps: Object.values(apps),\n\n // Seed Data (top-level, registered as metadata)\n data: CrmSeedData,\n\n // I18n Configuration \u2014 per-locale file organization\n i18n: {\n defaultLocale: 'en',\n supportedLocales: ['en', 'zh-CN', 'ja-JP', 'es-ES'],\n fallbackLocale: 'en',\n fileOrganization: 'per_locale',\n },\n\n // I18n Translation Bundles (en, zh-CN, ja-JP, es-ES)\n translations: Object.values(translations),\n\n // Sharing & security\n sharingRules: [\n AccountTeamSharingRule,\n OpportunitySalesSharingRule,\n CaseEscalationSharingRule,\n ...TerritorySharingRules,\n ],\n roles: RoleHierarchy.roles.map((r: { name: string; label: string; parentRole: string | null }) => ({\n name: r.name,\n label: r.label,\n parent: r.parentRole ?? undefined,\n })),\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Object Definitions Barrel\n */\nexport { Task } from './task.object';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Task = ObjectSchema.create({\n name: 'task',\n label: 'Task',\n pluralLabel: 'Tasks',\n icon: 'check-square',\n description: 'Personal tasks and to-do items',\n \n fields: {\n // Task Information\n subject: Field.text({\n label: 'Subject',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Task Management\n status: Field.select({\n label: 'Status',\n required: true,\n options: [\n { label: 'Not Started', value: 'not_started', color: '#808080', default: true },\n { label: 'In Progress', value: 'in_progress', color: '#3B82F6' },\n { label: 'Waiting', value: 'waiting', color: '#F59E0B' },\n { label: 'Completed', value: 'completed', color: '#10B981' },\n { label: 'Deferred', value: 'deferred', color: '#6B7280' },\n ]\n }),\n \n priority: Field.select({\n label: 'Priority',\n required: true,\n options: [\n { label: 'Low', value: 'low', color: '#60A5FA', default: true },\n { label: 'Normal', value: 'normal', color: '#10B981' },\n { label: 'High', value: 'high', color: '#F59E0B' },\n { label: 'Urgent', value: 'urgent', color: '#EF4444' },\n ]\n }),\n \n category: Field.select({\n label: 'Category',\n options: [\n { label: 'Personal', value: 'personal' },\n { label: 'Work', value: 'work' },\n { label: 'Shopping', value: 'shopping' },\n { label: 'Health', value: 'health' },\n { label: 'Finance', value: 'finance' },\n { label: 'Other', value: 'other' },\n ]\n }),\n \n // Dates\n due_date: Field.date({\n label: 'Due Date',\n }),\n \n reminder_date: Field.datetime({\n label: 'Reminder Date/Time',\n }),\n \n completed_date: Field.datetime({\n label: 'Completed Date',\n readonly: true,\n }),\n \n // Assignment\n owner: Field.lookup('user', {\n label: 'Assigned To',\n required: true,\n }),\n \n // Tags\n tags: Field.select({\n label: 'Tags',\n multiple: true,\n options: [\n { label: 'Important', value: 'important', color: '#EF4444' },\n { label: 'Quick Win', value: 'quick_win', color: '#10B981' },\n { label: 'Blocked', value: 'blocked', color: '#F59E0B' },\n { label: 'Follow Up', value: 'follow_up', color: '#3B82F6' },\n { label: 'Review', value: 'review', color: '#8B5CF6' },\n ]\n }),\n \n // Recurrence\n is_recurring: Field.boolean({\n label: 'Recurring Task',\n defaultValue: false,\n }),\n \n recurrence_type: Field.select({\n label: 'Recurrence Type',\n options: [\n { label: 'Daily', value: 'daily' },\n { label: 'Weekly', value: 'weekly' },\n { label: 'Monthly', value: 'monthly' },\n { label: 'Yearly', value: 'yearly' },\n ]\n }),\n \n recurrence_interval: Field.number({\n label: 'Recurrence Interval',\n defaultValue: 1,\n min: 1,\n }),\n \n // Flags\n is_completed: Field.boolean({\n label: 'Is Completed',\n defaultValue: false,\n readonly: true,\n }),\n \n is_overdue: Field.boolean({\n label: 'Is Overdue',\n defaultValue: false,\n readonly: true,\n }),\n \n // Progress\n progress_percent: Field.percent({\n label: 'Progress (%)',\n min: 0,\n max: 100,\n defaultValue: 0,\n }),\n \n // Time Tracking\n estimated_hours: Field.number({\n label: 'Estimated Hours',\n scale: 2,\n min: 0,\n }),\n \n actual_hours: Field.number({\n label: 'Actual Hours',\n scale: 2,\n min: 0,\n }),\n \n // Additional fields\n notes: Field.richtext({\n label: 'Notes',\n description: 'Rich text notes with formatting',\n }),\n \n category_color: Field.color({\n label: 'Category Color',\n colorFormat: 'hex',\n presetColors: ['#EF4444', '#F59E0B', '#10B981', '#3B82F6', '#8B5CF6'],\n }),\n },\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true,\n activities: true,\n trash: true,\n mru: true,\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['status'] },\n { fields: ['priority'] },\n { fields: ['owner'] },\n { fields: ['due_date'] },\n { fields: ['category'] },\n ],\n \n titleFormat: '{subject}',\n compactLayout: ['subject', 'status', 'priority', 'due_date', 'owner'],\n \n validations: [\n {\n name: 'completed_date_required',\n type: 'script',\n severity: 'error',\n message: 'Completed date is required when status is Completed',\n condition: 'status = \"completed\" AND ISBLANK(completed_date)',\n },\n {\n name: 'recurrence_fields_required',\n type: 'script',\n severity: 'error',\n message: 'Recurrence type is required for recurring tasks',\n condition: 'is_recurring = true AND ISBLANK(recurrence_type)',\n },\n ],\n \n workflows: [\n {\n name: 'set_completed_flag',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(status)',\n active: true,\n actions: [\n {\n name: 'update_completed_flag',\n type: 'field_update',\n field: 'is_completed',\n value: 'status = \"completed\"',\n }\n ],\n },\n {\n name: 'set_completed_date',\n objectName: 'task',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(status) AND status = \"completed\"',\n active: true,\n actions: [\n {\n name: 'set_date',\n type: 'field_update',\n field: 'completed_date',\n value: 'NOW()',\n },\n {\n name: 'set_progress',\n type: 'field_update',\n field: 'progress_percent',\n value: '100',\n }\n ],\n },\n {\n name: 'check_overdue',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'due_date < TODAY() AND is_completed = false',\n active: true,\n actions: [\n {\n name: 'set_overdue_flag',\n type: 'field_update',\n field: 'is_overdue',\n value: 'true',\n }\n ],\n },\n {\n name: 'notify_on_urgent',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'priority = \"urgent\" AND is_completed = false',\n active: true,\n actions: [\n {\n name: 'email_owner',\n type: 'email_alert',\n template: 'urgent_task_alert',\n recipients: ['{owner.email}'],\n }\n ],\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Action Definitions Barrel\n *\n * Exports action metadata definitions only. Used by `Object.values()` in\n * objectstack.config.ts to auto-collect all action declarations for defineStack().\n *\n * **Handler functions** are exported from `./handlers/` \u2014 see register-handlers.ts\n * for the complete registration flow.\n */\nexport {\n CompleteTaskAction,\n StartTaskAction,\n DeferTaskAction,\n SetReminderAction,\n CloneTaskAction,\n MassCompleteTasksAction,\n DeleteCompletedAction,\n ExportToCsvAction,\n} from './task.actions';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Mark Task as Complete */\nexport const CompleteTaskAction: Action = {\n name: 'complete_task',\n label: 'Mark Complete',\n objectName: 'task',\n icon: 'check-circle',\n type: 'script',\n target: 'completeTask',\n locations: ['record_header', 'list_item'],\n successMessage: 'Task marked as complete!',\n refreshAfter: true,\n};\n\n/** Mark Task as In Progress */\nexport const StartTaskAction: Action = {\n name: 'start_task',\n label: 'Start Task',\n objectName: 'task',\n icon: 'play-circle',\n type: 'script',\n target: 'startTask',\n locations: ['record_header', 'list_item'],\n successMessage: 'Task started!',\n refreshAfter: true,\n};\n\n/** Defer Task */\nexport const DeferTaskAction: Action = {\n name: 'defer_task',\n label: 'Defer Task',\n objectName: 'task',\n icon: 'clock',\n type: 'modal',\n target: 'defer_task_modal',\n locations: ['record_header'],\n params: [\n {\n name: 'new_due_date',\n label: 'New Due Date',\n type: 'date',\n required: true,\n },\n {\n name: 'reason',\n label: 'Reason for Deferral',\n type: 'textarea',\n required: false,\n }\n ],\n successMessage: 'Task deferred successfully!',\n refreshAfter: true,\n};\n\n/** Set Reminder */\nexport const SetReminderAction: Action = {\n name: 'set_reminder',\n label: 'Set Reminder',\n objectName: 'task',\n icon: 'bell',\n type: 'modal',\n target: 'set_reminder_modal',\n locations: ['record_header', 'list_item'],\n params: [\n {\n name: 'reminder_date',\n label: 'Reminder Date/Time',\n type: 'datetime',\n required: true,\n }\n ],\n successMessage: 'Reminder set!',\n refreshAfter: true,\n};\n\n/** Clone Task */\nexport const CloneTaskAction: Action = {\n name: 'clone_task',\n label: 'Clone Task',\n objectName: 'task',\n icon: 'copy',\n type: 'script',\n target: 'cloneTask',\n locations: ['record_header'],\n successMessage: 'Task cloned successfully!',\n refreshAfter: true,\n};\n\n/** Mass Complete Tasks */\nexport const MassCompleteTasksAction: Action = {\n name: 'mass_complete',\n label: 'Complete Selected',\n objectName: 'task',\n icon: 'check-square',\n type: 'script',\n target: 'massCompleteTasks',\n locations: ['list_toolbar'],\n successMessage: 'Selected tasks marked as complete!',\n refreshAfter: true,\n};\n\n/** Delete Completed Tasks */\nexport const DeleteCompletedAction: Action = {\n name: 'delete_completed',\n label: 'Delete Completed',\n objectName: 'task',\n icon: 'trash-2',\n type: 'script',\n target: 'deleteCompletedTasks',\n locations: ['list_toolbar'],\n successMessage: 'Completed tasks deleted!',\n refreshAfter: true,\n};\n\n/** Export Tasks to CSV */\nexport const ExportToCsvAction: Action = {\n name: 'export_csv',\n label: 'Export to CSV',\n objectName: 'task',\n icon: 'download',\n type: 'script',\n target: 'exportTasksToCSV',\n locations: ['list_toolbar'],\n successMessage: 'Export completed!',\n refreshAfter: false,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Dashboard Definitions Barrel\n */\nexport { TaskDashboard } from './task.dashboard';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Dashboard } from '@objectstack/spec/ui';\n\nexport const TaskDashboard: Dashboard = {\n name: 'task_dashboard',\n label: 'Task Overview',\n description: 'Key task metrics and productivity overview',\n \n widgets: [\n // Row 1: Key Metrics\n {\n id: 'total_tasks',\n title: 'Total Tasks',\n type: 'metric',\n object: 'task',\n aggregate: 'count',\n layout: { x: 0, y: 0, w: 3, h: 2 },\n options: { color: '#3B82F6' }\n },\n {\n id: 'completed_today',\n title: 'Completed Today',\n type: 'metric',\n object: 'task',\n filter: { is_completed: true, completed_date: { $gte: '{today_start}' } },\n aggregate: 'count',\n layout: { x: 3, y: 0, w: 3, h: 2 },\n options: { color: '#10B981' }\n },\n {\n id: 'overdue_tasks',\n title: 'Overdue Tasks',\n type: 'metric',\n object: 'task',\n filter: { is_overdue: true, is_completed: false },\n aggregate: 'count',\n layout: { x: 6, y: 0, w: 3, h: 2 },\n options: { color: '#EF4444' }\n },\n {\n id: 'completion_rate',\n title: 'Completion Rate',\n type: 'metric',\n object: 'task',\n filter: { created_date: { $gte: '{current_week_start}' } },\n valueField: 'is_completed',\n aggregate: 'count',\n layout: { x: 9, y: 0, w: 3, h: 2 },\n options: { suffix: '%', color: '#8B5CF6' }\n },\n \n // Row 2: Task Distribution\n {\n id: 'tasks_by_status',\n title: 'Tasks by Status',\n type: 'pie',\n object: 'task',\n filter: { is_completed: false },\n categoryField: 'status',\n aggregate: 'count',\n layout: { x: 0, y: 2, w: 6, h: 4 },\n options: { showLegend: true }\n },\n {\n id: 'tasks_by_priority',\n title: 'Tasks by Priority',\n type: 'bar',\n object: 'task',\n filter: { is_completed: false },\n categoryField: 'priority',\n aggregate: 'count',\n layout: { x: 6, y: 2, w: 6, h: 4 },\n options: { horizontal: true }\n },\n \n // Row 3: Trends\n {\n id: 'weekly_task_completion',\n title: 'Weekly Task Completion',\n type: 'line',\n object: 'task',\n filter: { is_completed: true, completed_date: { $gte: '{last_4_weeks}' } },\n categoryField: 'completed_date',\n aggregate: 'count',\n layout: { x: 0, y: 6, w: 8, h: 4 },\n options: { showDataLabels: true }\n },\n {\n id: 'tasks_by_category',\n title: 'Tasks by Category',\n type: 'donut',\n object: 'task',\n filter: { is_completed: false },\n categoryField: 'category',\n aggregate: 'count',\n layout: { x: 8, y: 6, w: 4, h: 4 },\n options: { showLegend: true }\n },\n \n // Row 4: Tables\n {\n id: 'overdue_tasks_table',\n title: 'Overdue Tasks',\n type: 'table',\n object: 'task',\n filter: { is_overdue: true, is_completed: false },\n aggregate: 'count',\n layout: { x: 0, y: 10, w: 6, h: 4 },\n },\n {\n id: 'due_today',\n title: 'Due Today',\n type: 'table',\n object: 'task',\n filter: { due_date: '{today}', is_completed: false },\n aggregate: 'count',\n layout: { x: 6, y: 10, w: 6, h: 4 },\n },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Report Definitions Barrel\n */\nexport {\n TasksByStatusReport,\n TasksByPriorityReport,\n TasksByOwnerReport,\n OverdueTasksReport,\n CompletedTasksReport,\n TimeTrackingReport,\n} from './task.report';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\n/** Tasks by Status Report */\nexport const TasksByStatusReport: ReportInput = {\n name: 'tasks_by_status',\n label: 'Tasks by Status',\n description: 'Summary of tasks grouped by status',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'priority', label: 'Priority' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'owner', label: 'Assigned To' },\n ],\n groupingsDown: [{ field: 'status', sortOrder: 'asc' }],\n};\n\n/** Tasks by Priority Report */\nexport const TasksByPriorityReport: ReportInput = {\n name: 'tasks_by_priority',\n label: 'Tasks by Priority',\n description: 'Summary of tasks grouped by priority level',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'status', label: 'Status' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'category', label: 'Category' },\n ],\n groupingsDown: [{ field: 'priority', sortOrder: 'desc' }],\n filter: { is_completed: false },\n};\n\n/** Tasks by Owner Report */\nexport const TasksByOwnerReport: ReportInput = {\n name: 'tasks_by_owner',\n label: 'Tasks by Owner',\n description: 'Task summary by assignee',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'status', label: 'Status' },\n { field: 'priority', label: 'Priority' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'estimated_hours', label: 'Est. Hours', aggregate: 'sum' },\n { field: 'actual_hours', label: 'Actual Hours', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'owner', sortOrder: 'asc' }],\n filter: { is_completed: false },\n};\n\n/** Overdue Tasks Report */\nexport const OverdueTasksReport: ReportInput = {\n name: 'overdue_tasks',\n label: 'Overdue Tasks',\n description: 'All overdue tasks that need attention',\n objectName: 'task',\n type: 'tabular',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'priority', label: 'Priority' },\n { field: 'owner', label: 'Assigned To' },\n { field: 'category', label: 'Category' },\n ],\n filter: { is_overdue: true, is_completed: false },\n};\n\n/** Completed Tasks Report */\nexport const CompletedTasksReport: ReportInput = {\n name: 'completed_tasks',\n label: 'Completed Tasks',\n description: 'All completed tasks with time tracking',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'completed_date', label: 'Completed Date' },\n { field: 'estimated_hours', label: 'Est. Hours', aggregate: 'sum' },\n { field: 'actual_hours', label: 'Actual Hours', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'category', sortOrder: 'asc' }],\n filter: { is_completed: true },\n};\n\n/** Time Tracking Report */\nexport const TimeTrackingReport: ReportInput = {\n name: 'time_tracking',\n label: 'Time Tracking Report',\n description: 'Estimated vs actual hours analysis',\n objectName: 'task',\n type: 'matrix',\n columns: [\n { field: 'estimated_hours', label: 'Estimated Hours', aggregate: 'sum' },\n { field: 'actual_hours', label: 'Actual Hours', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'owner', sortOrder: 'asc' }],\n groupingsAcross: [{ field: 'category', sortOrder: 'asc' }],\n filter: { is_completed: true },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Flow } from '@objectstack/spec/automation';\n\n/** Task Reminder Flow \u2014 scheduled flow to send reminders for upcoming tasks */\nexport const TaskReminderFlow: Flow = {\n name: 'task_reminder',\n label: 'Task Reminder Notification',\n description: 'Automated flow to send reminders for tasks approaching their due date',\n type: 'schedule',\n\n variables: [\n { name: 'tasksToRemind', type: 'record_collection', isInput: false, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start (Daily 8 AM)', config: { schedule: '0 8 * * *', objectName: 'task' } },\n {\n id: 'get_upcoming_tasks', type: 'get_record', label: 'Get Tasks Due Tomorrow',\n config: { objectName: 'task', filter: { due_date: '{tomorrow}', is_completed: false }, outputVariable: 'tasksToRemind', getAll: true },\n },\n {\n id: 'loop_tasks', type: 'loop', label: 'Loop Through Tasks',\n config: { collection: '{tasksToRemind}', iteratorVariable: 'currentTask' },\n },\n {\n id: 'send_reminder', type: 'script', label: 'Send Reminder Email',\n config: {\n actionType: 'email',\n inputs: {\n to: '{currentTask.owner.email}',\n subject: 'Task Due Tomorrow: {currentTask.subject}',\n template: 'task_reminder_email',\n data: { taskSubject: '{currentTask.subject}', dueDate: '{currentTask.due_date}', priority: '{currentTask.priority}' },\n },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_upcoming_tasks', type: 'default' },\n { id: 'e2', source: 'get_upcoming_tasks', target: 'loop_tasks', type: 'default' },\n { id: 'e3', source: 'loop_tasks', target: 'send_reminder', type: 'default' },\n { id: 'e4', source: 'send_reminder', target: 'end', type: 'default' },\n ],\n};\n\n/** Overdue Task Escalation Flow */\nexport const OverdueEscalationFlow: Flow = {\n name: 'overdue_escalation',\n label: 'Overdue Task Escalation',\n description: 'Escalates tasks that have been overdue for more than 3 days',\n type: 'schedule',\n\n variables: [\n { name: 'overdueTasks', type: 'record_collection', isInput: false, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start (Daily 9 AM)', config: { schedule: '0 9 * * *', objectName: 'task' } },\n {\n id: 'get_overdue_tasks', type: 'get_record', label: 'Get Severely Overdue Tasks',\n config: {\n objectName: 'task',\n filter: { due_date: { $lt: '{3_days_ago}' }, is_completed: false, is_overdue: true },\n outputVariable: 'overdueTasks', getAll: true,\n },\n },\n {\n id: 'loop_overdue', type: 'loop', label: 'Loop Through Overdue Tasks',\n config: { collection: '{overdueTasks}', iteratorVariable: 'currentTask' },\n },\n {\n id: 'update_priority', type: 'update_record', label: 'Escalate Priority',\n config: {\n objectName: 'task',\n filter: { id: '{currentTask.id}' },\n fields: { priority: 'urgent', tags: ['important', 'follow_up'] },\n },\n },\n {\n id: 'notify_owner', type: 'script', label: 'Notify Task Owner',\n config: {\n actionType: 'email',\n inputs: {\n to: '{currentTask.owner.email}',\n subject: 'URGENT: Task Overdue - {currentTask.subject}',\n template: 'overdue_escalation_email',\n data: { taskSubject: '{currentTask.subject}', dueDate: '{currentTask.due_date}', daysOverdue: '{currentTask.days_overdue}' },\n },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_overdue_tasks', type: 'default' },\n { id: 'e2', source: 'get_overdue_tasks', target: 'loop_overdue', type: 'default' },\n { id: 'e3', source: 'loop_overdue', target: 'update_priority', type: 'default' },\n { id: 'e4', source: 'update_priority', target: 'notify_owner', type: 'default' },\n { id: 'e5', source: 'notify_owner', target: 'end', type: 'default' },\n ],\n};\n\n/** Task Completion Flow */\nexport const TaskCompletionFlow: Flow = {\n name: 'task_completion',\n label: 'Task Completion Process',\n description: 'Flow triggered when a task is marked as complete',\n type: 'record_change',\n\n variables: [\n { name: 'taskId', type: 'text', isInput: true, isOutput: false },\n { name: 'completedTask', type: 'record', isInput: false, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start', config: { objectName: 'task', triggerCondition: 'ISCHANGED(status) AND status = \"completed\"' } },\n {\n id: 'get_task', type: 'get_record', label: 'Get Completed Task',\n config: { objectName: 'task', filter: { id: '{taskId}' }, outputVariable: 'completedTask' },\n },\n {\n id: 'check_recurring', type: 'decision', label: 'Is Recurring Task?',\n config: { condition: '{completedTask.is_recurring} == true' },\n },\n {\n id: 'create_next_task', type: 'create_record', label: 'Create Next Recurring Task',\n config: {\n objectName: 'task',\n fields: {\n subject: '{completedTask.subject}', description: '{completedTask.description}',\n priority: '{completedTask.priority}', category: '{completedTask.category}',\n owner: '{completedTask.owner}', is_recurring: true,\n recurrence_type: '{completedTask.recurrence_type}',\n recurrence_interval: '{completedTask.recurrence_interval}',\n due_date: 'DATEADD({completedTask.due_date}, {completedTask.recurrence_interval}, \"{completedTask.recurrence_type}\")',\n status: 'not_started', is_completed: false,\n },\n outputVariable: 'newTaskId',\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_task', type: 'default' },\n { id: 'e2', source: 'get_task', target: 'check_recurring', type: 'default' },\n { id: 'e3', source: 'check_recurring', target: 'create_next_task', type: 'default', condition: '{completedTask.is_recurring} == true', label: 'Yes' },\n { id: 'e4', source: 'check_recurring', target: 'end', type: 'default', condition: '{completedTask.is_recurring} != true', label: 'No' },\n { id: 'e5', source: 'create_next_task', target: 'end', type: 'default' },\n ],\n};\n\n/** Quick Add Task Flow \u2014 screen flow for quickly adding tasks */\nexport const QuickAddTaskFlow: Flow = {\n name: 'quick_add_task',\n label: 'Quick Add Task',\n description: 'Screen flow for quickly creating a new task',\n type: 'screen',\n\n variables: [\n { name: 'subject', type: 'text', isInput: true, isOutput: false },\n { name: 'priority', type: 'text', isInput: true, isOutput: false },\n { name: 'dueDate', type: 'date', isInput: true, isOutput: false },\n { name: 'newTaskId', type: 'text', isInput: false, isOutput: true },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start' },\n {\n id: 'screen_1', type: 'screen', label: 'Task Details',\n config: {\n fields: [\n { name: 'subject', label: 'Task Subject', type: 'text', required: true },\n { name: 'priority', label: 'Priority', type: 'select', options: ['low', 'normal', 'high', 'urgent'], defaultValue: 'normal' },\n { name: 'dueDate', label: 'Due Date', type: 'date', required: false },\n { name: 'category', label: 'Category', type: 'select', options: ['personal', 'work', 'shopping', 'health', 'finance', 'other'] },\n ],\n },\n },\n {\n id: 'create_task', type: 'create_record', label: 'Create Task',\n config: {\n objectName: 'task',\n fields: { subject: '{subject}', priority: '{priority}', due_date: '{dueDate}', category: '{category}', status: 'not_started', owner: '{$User.Id}' },\n outputVariable: 'newTaskId',\n },\n },\n {\n id: 'success_screen', type: 'screen', label: 'Success',\n config: {\n message: 'Task \"{subject}\" created successfully!',\n buttons: [\n { label: 'Create Another', action: 'restart' },\n { label: 'View Task', action: 'navigate', target: '/task/{newTaskId}' },\n { label: 'Done', action: 'finish' },\n ],\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'screen_1', type: 'default' },\n { id: 'e2', source: 'screen_1', target: 'create_task', type: 'default' },\n { id: 'e3', source: 'create_task', target: 'success_screen', type: 'default' },\n { id: 'e4', source: 'success_screen', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Flow } from '@objectstack/spec/automation';\n\n/**\n * Flow Definitions Barrel\n */\nexport {\n TaskReminderFlow,\n OverdueEscalationFlow,\n TaskCompletionFlow,\n QuickAddTaskFlow,\n} from './task.flow';\n\nimport {\n TaskReminderFlow,\n OverdueEscalationFlow,\n TaskCompletionFlow,\n QuickAddTaskFlow,\n} from './task.flow';\n\n/** All flow definitions as a typed array for defineStack() */\nexport const allFlows: Flow[] = [\n TaskReminderFlow,\n OverdueEscalationFlow,\n TaskCompletionFlow,\n QuickAddTaskFlow,\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * App Definitions Barrel\n */\nexport { TodoApp } from './todo.app';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { App } from '@objectstack/spec/ui';\n\nexport const TodoApp = App.create({\n name: 'todo_app',\n label: 'Todo Manager',\n icon: 'check-square',\n branding: {\n primaryColor: '#10B981',\n secondaryColor: '#3B82F6',\n logo: '/assets/todo-logo.png',\n favicon: '/assets/todo-favicon.ico',\n },\n \n navigation: [\n {\n id: 'group_tasks',\n type: 'group',\n label: 'Tasks',\n icon: 'check-square',\n children: [\n { id: 'nav_all_tasks', type: 'object', objectName: 'task', label: 'All Tasks', icon: 'list' },\n { id: 'nav_my_tasks', type: 'object', objectName: 'task', label: 'My Tasks', icon: 'user-check' },\n { id: 'nav_overdue', type: 'object', objectName: 'task', label: 'Overdue', icon: 'alert-circle' },\n { id: 'nav_today', type: 'object', objectName: 'task', label: 'Due Today', icon: 'calendar' },\n { id: 'nav_upcoming', type: 'object', objectName: 'task', label: 'Upcoming', icon: 'calendar-plus' },\n ]\n },\n {\n id: 'group_analytics',\n type: 'group',\n label: 'Analytics',\n icon: 'chart-bar',\n children: [\n { id: 'nav_dashboard', type: 'dashboard', dashboardName: 'task_dashboard', label: 'Dashboard', icon: 'layout-dashboard' },\n ]\n },\n ]\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Translation Definitions Barrel\n */\nexport { TodoTranslations } from './todo.translation';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * English (en) \u2014 Todo App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n * Each file exports a single `TranslationData` object for its locale.\n */\nexport const en: TranslationData = {\n objects: {\n task: {\n label: 'Task',\n pluralLabel: 'Tasks',\n fields: {\n subject: { label: 'Subject', help: 'Brief title of the task' },\n description: { label: 'Description' },\n status: {\n label: 'Status',\n options: {\n not_started: 'Not Started',\n in_progress: 'In Progress',\n waiting: 'Waiting',\n completed: 'Completed',\n deferred: 'Deferred',\n },\n },\n priority: {\n label: 'Priority',\n options: {\n low: 'Low',\n normal: 'Normal',\n high: 'High',\n urgent: 'Urgent',\n },\n },\n category: {\n label: 'Category',\n options: {\n personal: 'Personal',\n work: 'Work',\n shopping: 'Shopping',\n health: 'Health',\n finance: 'Finance',\n other: 'Other',\n },\n },\n due_date: { label: 'Due Date' },\n reminder_date: { label: 'Reminder Date/Time' },\n completed_date: { label: 'Completed Date' },\n owner: { label: 'Assigned To' },\n tags: {\n label: 'Tags',\n options: {\n important: 'Important',\n quick_win: 'Quick Win',\n blocked: 'Blocked',\n follow_up: 'Follow Up',\n review: 'Review',\n },\n },\n is_recurring: { label: 'Recurring Task' },\n recurrence_type: {\n label: 'Recurrence Type',\n options: {\n daily: 'Daily',\n weekly: 'Weekly',\n monthly: 'Monthly',\n yearly: 'Yearly',\n },\n },\n recurrence_interval: { label: 'Recurrence Interval' },\n is_completed: { label: 'Is Completed' },\n is_overdue: { label: 'Is Overdue' },\n progress_percent: { label: 'Progress (%)' },\n estimated_hours: { label: 'Estimated Hours' },\n actual_hours: { label: 'Actual Hours' },\n notes: { label: 'Notes' },\n category_color: { label: 'Category Color' },\n },\n },\n },\n apps: {\n todo_app: {\n label: 'Todo Manager',\n description: 'Personal task management application',\n },\n },\n messages: {\n 'common.save': 'Save',\n 'common.cancel': 'Cancel',\n 'common.delete': 'Delete',\n 'common.edit': 'Edit',\n 'common.create': 'Create',\n 'common.search': 'Search',\n 'common.filter': 'Filter',\n 'common.sort': 'Sort',\n 'common.refresh': 'Refresh',\n 'common.export': 'Export',\n 'common.back': 'Back',\n 'common.confirm': 'Confirm',\n 'success.saved': 'Successfully saved',\n 'success.deleted': 'Successfully deleted',\n 'success.completed': 'Task marked as completed',\n 'confirm.delete': 'Are you sure you want to delete this task?',\n 'confirm.complete': 'Mark this task as completed?',\n 'error.required': 'This field is required',\n 'error.load_failed': 'Failed to load data',\n },\n validationMessages: {\n completed_date_required: 'Completed date is required when status is Completed',\n recurrence_fields_required: 'Recurrence type is required for recurring tasks',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\nimport type { StrictObjectTranslation } from '@objectstack/spec/system';\nimport { Task } from '../objects/task.object';\n\ntype TaskTranslation = StrictObjectTranslation;\n\n/**\n * \u7B80\u4F53\u4E2D\u6587 (zh-CN) \u2014 Todo App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const zhCN: TranslationData = {\n objects: {\n task: {\n label: '\u4EFB\u52A1',\n pluralLabel: '\u4EFB\u52A1',\n fields: {\n subject: { label: '\u4E3B\u9898', help: '\u4EFB\u52A1\u7684\u7B80\u8981\u6807\u9898' },\n description: { label: '\u63CF\u8FF0' },\n status: {\n label: '\u72B6\u6001',\n options: {\n not_started: '\u672A\u5F00\u59CB',\n in_progress: '\u8FDB\u884C\u4E2D',\n waiting: '\u7B49\u5F85\u4E2D',\n completed: '\u5DF2\u5B8C\u6210',\n deferred: '\u5DF2\u63A8\u8FDF',\n },\n },\n priority: {\n label: '\u4F18\u5148\u7EA7',\n options: {\n low: '\u4F4E',\n normal: '\u666E\u901A',\n high: '\u9AD8',\n urgent: '\u7D27\u6025',\n },\n },\n category: {\n label: '\u5206\u7C7B',\n options: {\n personal: '\u4E2A\u4EBA',\n work: '\u5DE5\u4F5C',\n shopping: '\u8D2D\u7269',\n health: '\u5065\u5EB7',\n finance: '\u8D22\u52A1',\n other: '\u5176\u4ED6',\n },\n },\n due_date: { label: '\u622A\u6B62\u65E5\u671F' },\n reminder_date: { label: '\u63D0\u9192\u65E5\u671F/\u65F6\u95F4' },\n completed_date: { label: '\u5B8C\u6210\u65E5\u671F' },\n owner: { label: '\u8D1F\u8D23\u4EBA' },\n tags: {\n label: '\u6807\u7B7E',\n options: {\n important: '\u91CD\u8981',\n quick_win: '\u901F\u80DC',\n blocked: '\u53D7\u963B',\n follow_up: '\u5F85\u8DDF\u8FDB',\n review: '\u5F85\u5BA1\u6838',\n },\n },\n is_recurring: { label: '\u5468\u671F\u6027\u4EFB\u52A1' },\n recurrence_type: {\n label: '\u91CD\u590D\u7C7B\u578B',\n options: {\n daily: '\u6BCF\u5929',\n weekly: '\u6BCF\u5468',\n monthly: '\u6BCF\u6708',\n yearly: '\u6BCF\u5E74',\n },\n },\n recurrence_interval: { label: '\u91CD\u590D\u95F4\u9694' },\n is_completed: { label: '\u662F\u5426\u5B8C\u6210' },\n is_overdue: { label: '\u662F\u5426\u903E\u671F' },\n progress_percent: { label: '\u8FDB\u5EA6 (%)' },\n estimated_hours: { label: '\u9884\u4F30\u5DE5\u65F6' },\n actual_hours: { label: '\u5B9E\u9645\u5DE5\u65F6' },\n notes: { label: '\u5907\u6CE8' },\n category_color: { label: '\u5206\u7C7B\u989C\u8272' },\n },\n } satisfies TaskTranslation,\n },\n apps: {\n todo_app: {\n label: '\u5F85\u529E\u7BA1\u7406',\n description: '\u4E2A\u4EBA\u4EFB\u52A1\u7BA1\u7406\u5E94\u7528',\n },\n },\n messages: {\n 'common.save': '\u4FDD\u5B58',\n 'common.cancel': '\u53D6\u6D88',\n 'common.delete': '\u5220\u9664',\n 'common.edit': '\u7F16\u8F91',\n 'common.create': '\u65B0\u5EFA',\n 'common.search': '\u641C\u7D22',\n 'common.filter': '\u7B5B\u9009',\n 'common.sort': '\u6392\u5E8F',\n 'common.refresh': '\u5237\u65B0',\n 'common.export': '\u5BFC\u51FA',\n 'common.back': '\u8FD4\u56DE',\n 'common.confirm': '\u786E\u8BA4',\n 'success.saved': '\u4FDD\u5B58\u6210\u529F',\n 'success.deleted': '\u5220\u9664\u6210\u529F',\n 'success.completed': '\u4EFB\u52A1\u5DF2\u6807\u8BB0\u4E3A\u5B8C\u6210',\n 'confirm.delete': '\u786E\u5B9A\u8981\u5220\u9664\u6B64\u4EFB\u52A1\u5417\uFF1F',\n 'confirm.complete': '\u786E\u5B9A\u5C06\u6B64\u4EFB\u52A1\u6807\u8BB0\u4E3A\u5B8C\u6210\uFF1F',\n 'error.required': '\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879',\n 'error.load_failed': '\u6570\u636E\u52A0\u8F7D\u5931\u8D25',\n },\n validationMessages: {\n completed_date_required: '\u72B6\u6001\u4E3A\"\u5DF2\u5B8C\u6210\"\u65F6\uFF0C\u5B8C\u6210\u65E5\u671F\u4E3A\u5FC5\u586B\u9879',\n recurrence_fields_required: '\u5468\u671F\u6027\u4EFB\u52A1\u5FC5\u987B\u6307\u5B9A\u91CD\u590D\u7C7B\u578B',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * \u65E5\u672C\u8A9E (ja-JP) \u2014 Todo App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const jaJP: TranslationData = {\n objects: {\n task: {\n label: '\u30BF\u30B9\u30AF',\n pluralLabel: '\u30BF\u30B9\u30AF',\n fields: {\n subject: { label: '\u4EF6\u540D', help: '\u30BF\u30B9\u30AF\u306E\u7C21\u5358\u306A\u30BF\u30A4\u30C8\u30EB' },\n description: { label: '\u8AAC\u660E' },\n status: {\n label: '\u30B9\u30C6\u30FC\u30BF\u30B9',\n options: {\n not_started: '\u672A\u7740\u624B',\n in_progress: '\u9032\u884C\u4E2D',\n waiting: '\u5F85\u6A5F\u4E2D',\n completed: '\u5B8C\u4E86',\n deferred: '\u5EF6\u671F',\n },\n },\n priority: {\n label: '\u512A\u5148\u5EA6',\n options: {\n low: '\u4F4E',\n normal: '\u901A\u5E38',\n high: '\u9AD8',\n urgent: '\u7DCA\u6025',\n },\n },\n category: {\n label: '\u30AB\u30C6\u30B4\u30EA',\n options: {\n personal: '\u500B\u4EBA',\n work: '\u4ED5\u4E8B',\n shopping: '\u8CB7\u3044\u7269',\n health: '\u5065\u5EB7',\n finance: '\u8CA1\u52D9',\n other: '\u305D\u306E\u4ED6',\n },\n },\n due_date: { label: '\u671F\u65E5' },\n reminder_date: { label: '\u30EA\u30DE\u30A4\u30F3\u30C0\u30FC\u65E5\u6642' },\n completed_date: { label: '\u5B8C\u4E86\u65E5' },\n owner: { label: '\u62C5\u5F53\u8005' },\n tags: {\n label: '\u30BF\u30B0',\n options: {\n important: '\u91CD\u8981',\n quick_win: '\u30AF\u30A4\u30C3\u30AF\u30A6\u30A3\u30F3',\n blocked: '\u30D6\u30ED\u30C3\u30AF\u4E2D',\n follow_up: '\u30D5\u30A9\u30ED\u30FC\u30A2\u30C3\u30D7',\n review: '\u30EC\u30D3\u30E5\u30FC',\n },\n },\n is_recurring: { label: '\u7E70\u308A\u8FD4\u3057\u30BF\u30B9\u30AF' },\n recurrence_type: {\n label: '\u7E70\u308A\u8FD4\u3057\u30BF\u30A4\u30D7',\n options: {\n daily: '\u6BCE\u65E5',\n weekly: '\u6BCE\u9031',\n monthly: '\u6BCE\u6708',\n yearly: '\u6BCE\u5E74',\n },\n },\n recurrence_interval: { label: '\u7E70\u308A\u8FD4\u3057\u9593\u9694' },\n is_completed: { label: '\u5B8C\u4E86\u6E08\u307F' },\n is_overdue: { label: '\u671F\u9650\u8D85\u904E' },\n progress_percent: { label: '\u9032\u6357\u7387 (%)' },\n estimated_hours: { label: '\u898B\u7A4D\u6642\u9593' },\n actual_hours: { label: '\u5B9F\u7E3E\u6642\u9593' },\n notes: { label: '\u30E1\u30E2' },\n category_color: { label: '\u30AB\u30C6\u30B4\u30EA\u8272' },\n },\n },\n },\n apps: {\n todo_app: {\n label: 'ToDo \u30DE\u30CD\u30FC\u30B8\u30E3\u30FC',\n description: '\u500B\u4EBA\u30BF\u30B9\u30AF\u7BA1\u7406\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3',\n },\n },\n messages: {\n 'common.save': '\u4FDD\u5B58',\n 'common.cancel': '\u30AD\u30E3\u30F3\u30BB\u30EB',\n 'common.delete': '\u524A\u9664',\n 'common.edit': '\u7DE8\u96C6',\n 'common.create': '\u65B0\u898F\u4F5C\u6210',\n 'common.search': '\u691C\u7D22',\n 'common.filter': '\u30D5\u30A3\u30EB\u30BF\u30FC',\n 'common.sort': '\u4E26\u3079\u66FF\u3048',\n 'common.refresh': '\u66F4\u65B0',\n 'common.export': '\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8',\n 'common.back': '\u623B\u308B',\n 'common.confirm': '\u78BA\u8A8D',\n 'success.saved': '\u4FDD\u5B58\u3057\u307E\u3057\u305F',\n 'success.deleted': '\u524A\u9664\u3057\u307E\u3057\u305F',\n 'success.completed': '\u30BF\u30B9\u30AF\u3092\u5B8C\u4E86\u306B\u3057\u307E\u3057\u305F',\n 'confirm.delete': '\u3053\u306E\u30BF\u30B9\u30AF\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F',\n 'confirm.complete': '\u3053\u306E\u30BF\u30B9\u30AF\u3092\u5B8C\u4E86\u306B\u3057\u307E\u3059\u304B\uFF1F',\n 'error.required': '\u3053\u306E\u9805\u76EE\u306F\u5FC5\u9808\u3067\u3059',\n 'error.load_failed': '\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F',\n },\n validationMessages: {\n completed_date_required: '\u30B9\u30C6\u30FC\u30BF\u30B9\u304C\u300C\u5B8C\u4E86\u300D\u306E\u5834\u5408\u3001\u5B8C\u4E86\u65E5\u306F\u5FC5\u9808\u3067\u3059',\n recurrence_fields_required: '\u7E70\u308A\u8FD4\u3057\u30BF\u30B9\u30AF\u306B\u306F\u7E70\u308A\u8FD4\u3057\u30BF\u30A4\u30D7\u304C\u5FC5\u8981\u3067\u3059',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationBundle } from '@objectstack/spec/system';\nimport { en } from './en';\nimport { zhCN } from './zh-CN';\nimport { jaJP } from './ja-JP';\n\n/**\n * Todo App \u2014 Internationalization (i18n)\n *\n * Demonstrates **per-locale file splitting** convention:\n * each language is defined in its own file (`en.ts`, `zh-CN.ts`, `ja-JP.ts`)\n * and assembled into a single `TranslationBundle` here.\n *\n * For large projects with many objects, use `per_namespace` organization\n * to further split each locale into per-object files (see i18n-standard docs).\n *\n * Supported locales: en (English), zh-CN (Chinese), ja-JP (Japanese)\n */\nexport const TodoTranslations: TranslationBundle = {\n en,\n 'zh-CN': zhCN,\n 'ja-JP': jaJP,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { defineStack } from '@objectstack/spec';\n\n// \u2500\u2500\u2500 Barrel Imports (one per metadata type) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nimport * as objects from './src/objects';\nimport * as actions from './src/actions';\nimport * as dashboards from './src/dashboards';\nimport * as reports from './src/reports';\nimport { allFlows } from './src/flows';\nimport * as apps from './src/apps';\nimport * as translations from './src/translations';\n\n// \u2500\u2500\u2500 Action Handler Registration (runtime lifecycle) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Handlers are wired separately from metadata. The `onEnable` export\n// is called by the kernel's AppPlugin after the engine is ready.\n// See: src/actions/register-handlers.ts for the full registration flow.\nimport { registerTaskActionHandlers } from './src/actions/register-handlers';\n\n/**\n * Plugin lifecycle hook \u2014 called by AppPlugin when the engine is ready.\n * This is where action handlers are registered on the ObjectQL engine.\n */\nexport const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {\n registerTaskActionHandlers(ctx.ql);\n};\n\nexport default defineStack({\n manifest: {\n id: 'com.example.todo',\n namespace: 'todo',\n version: '2.0.0',\n type: 'app',\n name: 'Todo Manager',\n description: 'A comprehensive Todo app demonstrating ObjectStack Protocol features including automation, dashboards, and reports',\n },\n\n // Seed Data (top-level, registered as metadata)\n data: [\n {\n object: 'task',\n mode: 'upsert' as const,\n externalId: 'subject',\n records: [\n { subject: 'Learn ObjectStack', status: 'completed', priority: 'high', category: 'work' },\n { subject: 'Build a cool app', status: 'in_progress', priority: 'normal', category: 'work', due_date: new Date(Date.now() + 86400000 * 3) },\n { subject: 'Review PR #102', status: 'completed', priority: 'high', category: 'work' },\n { subject: 'Write Documentation', status: 'not_started', priority: 'normal', category: 'work', due_date: new Date(Date.now() + 86400000) },\n { subject: 'Fix Server bug', status: 'waiting', priority: 'urgent', category: 'work' },\n { subject: 'Buy groceries', status: 'not_started', priority: 'low', category: 'shopping', due_date: new Date() },\n { subject: 'Schedule dentist appointment', status: 'not_started', priority: 'normal', category: 'health', due_date: new Date(Date.now() + 86400000 * 7) },\n { subject: 'Pay utility bills', status: 'not_started', priority: 'high', category: 'finance', due_date: new Date(Date.now() + 86400000 * 2) },\n ]\n }\n ],\n\n // Auto-collected from barrel index files via Object.values()\n objects: Object.values(objects),\n actions: Object.values(actions),\n dashboards: Object.values(dashboards),\n reports: Object.values(reports),\n flows: allFlows,\n apps: Object.values(apps),\n\n // I18n Configuration \u2014 per-locale file organization\n i18n: {\n defaultLocale: 'en',\n supportedLocales: ['en', 'zh-CN', 'ja-JP'],\n fallbackLocale: 'en',\n fileOrganization: 'per_locale',\n },\n\n // I18n Translation Bundles (en, zh-CN, ja-JP)\n translations: Object.values(translations),\n});\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { defineStack } from '@objectstack/spec';\n\n/**\n * BI Plugin - Business Intelligence Dashboard\n * \n * This plugin provides analytics and reporting capabilities.\n * (Placeholder - to be implemented)\n */\nexport default defineStack({\n manifest: {\n id: 'com.example.bi',\n namespace: 'bi',\n version: '1.0.0',\n type: 'plugin',\n name: 'BI Plugin',\n description: 'Business Intelligence dashboards and analytics',\n },\n \n // Placeholder - no objects or dashboards yet\n objects: [],\n dashboards: [],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Vercel Serverless API Entrypoint for App Host Example\n *\n * Boots the ObjectStack kernel lazily on the first request and delegates\n * all /api/* traffic to the ObjectStack Hono adapter.\n *\n * Uses `getRequestListener()` from `@hono/node-server` to handle Vercel's\n * pre-buffered request body properly.\n */\n\nimport { ObjectKernel, DriverPlugin, AppPlugin } from '@objectstack/runtime';\nimport { ObjectQLPlugin } from '@objectstack/objectql';\nimport { InMemoryDriver } from '@objectstack/driver-memory';\nimport { createHonoApp } from '@objectstack/hono';\nimport { AuthPlugin } from '@objectstack/plugin-auth';\nimport { getRequestListener } from '@hono/node-server';\nimport type { Hono } from 'hono';\nimport CrmApp from '@example/app-crm';\nimport TodoApp from '@example/app-todo';\nimport BiPluginManifest from '@example/plugin-bi';\n\n// ---------------------------------------------------------------------------\n// Singleton state \u2014 persists across warm Vercel invocations\n// ---------------------------------------------------------------------------\n\nlet _kernel: ObjectKernel | null = null;\nlet _app: Hono | null = null;\n\n/** Shared boot promise \u2014 prevents concurrent cold-start races. */\nlet _bootPromise: Promise | null = null;\n\n// ---------------------------------------------------------------------------\n// Kernel bootstrap\n// ---------------------------------------------------------------------------\n\n/**\n * Boot the ObjectStack kernel (one-time cold-start cost).\n *\n * Uses a shared promise so that concurrent requests during a cold start\n * wait for the same boot sequence rather than starting duplicates.\n */\nasync function ensureKernel(): Promise {\n if (_kernel) return _kernel;\n if (_bootPromise) return _bootPromise;\n\n _bootPromise = (async () => {\n console.log('[Vercel] Booting ObjectStack Kernel (app-host)...');\n\n try {\n const kernel = new ObjectKernel();\n\n // Register ObjectQL engine\n await kernel.use(new ObjectQLPlugin());\n\n // Database driver (in-memory for demo)\n await kernel.use(new DriverPlugin(new InMemoryDriver()));\n\n // Auth plugin \u2014 uses environment variables for configuration\n // Prefer VERCEL_PROJECT_PRODUCTION_URL (stable across deployments)\n // over VERCEL_URL (unique per deployment, causes origin mismatch).\n const vercelUrl = process.env.VERCEL_PROJECT_PRODUCTION_URL\n ? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`\n : process.env.VERCEL_URL\n ? `https://${process.env.VERCEL_URL}`\n : 'http://localhost:3000';\n\n await kernel.use(new AuthPlugin({\n secret: process.env.AUTH_SECRET || 'dev-secret-please-change-in-production-min-32-chars',\n baseUrl: vercelUrl,\n }));\n\n // Load app manifests\n await kernel.use(new AppPlugin(CrmApp));\n await kernel.use(new AppPlugin(TodoApp));\n await kernel.use(new AppPlugin(BiPluginManifest));\n\n await kernel.bootstrap();\n\n _kernel = kernel;\n console.log('[Vercel] Kernel ready.');\n return kernel;\n } catch (err) {\n // Clear the lock so the next request can retry\n _bootPromise = null;\n console.error('[Vercel] Kernel boot failed:', (err as any)?.message || err);\n throw err;\n }\n })();\n\n return _bootPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Hono app factory\n// ---------------------------------------------------------------------------\n\n/**\n * Get (or create) the Hono application backed by the ObjectStack kernel.\n * The prefix `/api/v1` matches the client SDK's default API path.\n */\nasync function ensureApp(): Promise {\n if (_app) return _app;\n\n const kernel = await ensureKernel();\n _app = createHonoApp({ kernel, prefix: '/api/v1' });\n return _app;\n}\n\n// ---------------------------------------------------------------------------\n// Body extraction \u2014 reads Vercel's pre-buffered request body.\n// ---------------------------------------------------------------------------\n\n/** Shape of the Vercel-augmented IncomingMessage passed via `env.incoming`. */\ninterface VercelIncomingMessage {\n rawBody?: Buffer | string;\n body?: unknown;\n headers?: Record;\n}\n\n/** Shape of the env object provided by `getRequestListener` on Vercel. */\ninterface VercelEnv {\n incoming?: VercelIncomingMessage;\n}\n\nfunction extractBody(\n incoming: VercelIncomingMessage,\n method: string,\n contentType: string | undefined,\n): BodyInit | null {\n if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return null;\n\n if (incoming.rawBody != null) {\n return incoming.rawBody;\n }\n\n if (incoming.body != null) {\n if (typeof incoming.body === 'string') return incoming.body;\n if (contentType?.includes('application/json')) return JSON.stringify(incoming.body);\n return String(incoming.body);\n }\n\n return null;\n}\n\n/**\n * Derive the correct public URL for the request, fixing the protocol when\n * running behind a reverse proxy such as Vercel's edge network.\n */\nfunction resolvePublicUrl(\n requestUrl: string,\n incoming: VercelIncomingMessage | undefined,\n): string {\n if (!incoming) return requestUrl;\n const fwdProto = incoming.headers?.['x-forwarded-proto'];\n const rawProto = Array.isArray(fwdProto) ? fwdProto[0] : fwdProto;\n // Accept only well-known protocol values to prevent header-injection attacks.\n const proto = rawProto === 'https' || rawProto === 'http' ? rawProto : undefined;\n if (proto === 'https' && requestUrl.startsWith('http:')) {\n return requestUrl.replace(/^http:/, 'https:');\n }\n return requestUrl;\n}\n\n// ---------------------------------------------------------------------------\n// Vercel Node.js serverless handler via @hono/node-server getRequestListener.\n// ---------------------------------------------------------------------------\n\nexport default getRequestListener(async (request, env) => {\n let app: Hono;\n try {\n app = await ensureApp();\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n console.error('[Vercel] Handler error \u2014 bootstrap did not complete:', message);\n return new Response(\n JSON.stringify({\n success: false,\n error: {\n message: 'Service Unavailable \u2014 kernel bootstrap failed.',\n code: 503,\n },\n }),\n { status: 503, headers: { 'content-type': 'application/json' } },\n );\n }\n\n const method = request.method.toUpperCase();\n const incoming = (env as VercelEnv)?.incoming;\n\n // Fix URL protocol using x-forwarded-proto (Vercel sets this to 'https').\n const url = resolvePublicUrl(request.url, incoming);\n\n console.log(`[Vercel] ${method} ${url}`);\n\n if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && incoming) {\n const contentType = incoming.headers?.['content-type'];\n const contentTypeStr = Array.isArray(contentType) ? contentType[0] : contentType;\n const body = extractBody(incoming, method, contentTypeStr);\n if (body != null) {\n return await app.fetch(\n new Request(url, { method, headers: request.headers, body }),\n );\n }\n }\n\n // For GET/HEAD/OPTIONS (or body-less requests): pass through with corrected URL.\n return await app.fetch(\n new Request(url, { method, headers: request.headers }),\n );\n});\n\n/**\n * Vercel per-function configuration.\n */\nexport const config = {\n memory: 1024,\n maxDuration: 60,\n};\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIgC,SAAS,aAAa,MAAMA,cAAa,QAAQ;AAC7E,WAASC,MAAK,MAAM,KAAK;AACrB,QAAI,CAAC,KAAK,MAAM;AACZ,aAAO,eAAe,MAAM,QAAQ;AAAA,QAChC,OAAO;AAAA,UACH;AAAA,UACA,QAAQ;AAAA,UACR,QAAQ,oBAAI,IAAI;AAAA,QACpB;AAAA,QACA,YAAY;AAAA,MAChB,CAAC;AAAA,IACL;AACA,QAAI,KAAK,KAAK,OAAO,IAA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AAAA,MACpD,KAAK;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,KAAK;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,KAAK;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,MAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAAA;;;ACpNA,SAAS,sBAAsB,KAAK;AACnC,SAAO,IAAI,OAAO,CAAC,EAAE,YAAY,IAAI,IAAI,MAAM,CAAC;AACjD;AAHA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA,IAEI,kBAFJC,UAAAC,mBAAAC,MAAAC,cAAAC,MAkBI,iBAlBJF,MAAAE,MAmDI,qBAnDJC,WAAAC,WAAAF,MAiEIG,kBAjEJL,MAAA,kCAAAM,sBAAAJ,MAiFI,uBAsCA,wBAvHJJ,WAAAI,MAqII;AArIJ;AAAA;AAAA,IAAAK;AAEA,IAAI,mBAAmB,MAAM;AAAA,MAC5B,IAAI,4BAA4B;AAC/B,eAAO;AAAA,MACR;AAAA,MACA,IAAI,2BAA2B;AAC9B,eAAO;AAAA,MAC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"assert", "isObject", "array", "set", "match", "object", "schema", "path", "_params", "Class", "_a", "message", "config", "base64", "base64url", "hex", "error", "issue", "path", "_a", "_b", "_path", "schema", "_params", "time", "version", "_a", "inst", "_b", "result", "line", "base64", "algorithm", "r", "_a", "checks", "checkResult", "canary", "result", "_", "url", "isDate", "isValidDate", "isObject", "schema", "allowsEval", "results", "map", "left", "right", "keyResult", "valueResult", "output", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "number", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "schema", "meta", "Class", "_emoji", "_undefined", "_null", "schema", "_params", "issue", "codec", "_payload", "process", "schema", "_params", "_a", "meta", "id", "_cached", "_schema", "registry", "ctx", "schema", "process", "_params", "json", "_schema", "file", "schema", "_params", "process", "core_exports", "_emoji", "_null", "_undefined", "process", "init_core", "checks_exports", "init_checks", "init_core", "date", "datetime", "duration", "time", "init_core", "init_schemas", "initializer", "init_errors", "init_core", "issue", "issues", "parse", "parseAsync", "safeParse", "safeParseAsync", "encode", "decode", "encodeAsync", "decodeAsync", "safeEncode", "safeDecode", "safeEncodeAsync", "safeDecodeAsync", "init_parse", "init_core", "init_errors", "schemas_exports", "_default", "base64", "base64url", "bigint", "boolean", "_catch", "cidrv4", "cidrv6", "cuid", "cuid2", "date", "describe", "e164", "email", "emoji", "_enum", "guid", "hex", "hostname", "intersection", "ipv4", "ipv6", "ksuid", "mac", "meta", "nanoid", "_null", "nullish", "number", "string", "ulid", "_undefined", "uuid", "_void", "xid", "_emoji", "_params", "alg", "enc", "schema", "init_schemas", "init_core", "init_checks", "init_parse", "def", "parse", "safeParse", "parseAsync", "safeParseAsync", "encode", "decode", "encodeAsync", "decodeAsync", "safeEncode", "safeDecode", "safeEncodeAsync", "safeDecodeAsync", "check", "json", "datetime", "time", "duration", "issue", "output", "map", "init_core", "ZodFirstPartyTypeKind", "schema", "path", "zodSchema", "objectSchema", "version", "init_checks", "init_schemas", "schemas_exports", "checks_exports", "bigint", "boolean", "date", "number", "string", "init_core", "init_schemas", "_default", "base64", "base64url", "bigint", "boolean", "_catch", "cidrv4", "cidrv6", "core_exports", "cuid", "cuid2", "date", "decode", "decodeAsync", "describe", "e164", "email", "emoji", "encode", "encodeAsync", "_enum", "guid", "hex", "hostname", "intersection", "ipv4", "ipv6", "ksuid", "mac", "meta", "nanoid", "_null", "nullish", "number", "parse", "parseAsync", "safeDecode", "safeDecodeAsync", "safeEncode", "safeEncodeAsync", "safeParse", "safeParseAsync", "string", "ulid", "_undefined", "uuid", "_void", "xid", "init_core", "init_schemas", "init_checks", "init_errors", "init_parse", "_default", "base64", "base64url", "bigint", "boolean", "_catch", "cidrv4", "cidrv6", "core_exports", "cuid", "cuid2", "date", "decode", "decodeAsync", "describe", "e164", "email", "emoji", "encode", "encodeAsync", "_enum", "guid", "hex", "hostname", "intersection", "ipv4", "ipv6", "ksuid", "mac", "meta", "nanoid", "_null", "nullish", "number", "parse", "parseAsync", "safeDecode", "safeDecodeAsync", "safeEncode", "safeEncodeAsync", "safeParse", "safeParseAsync", "string", "ulid", "_undefined", "uuid", "_void", "xid", "snakeCaseToLabel", "FieldReferenceSchema", "FieldOperatorsSchema", "FilterConditionSchema", "NormalizedFilterSchema", "SortNodeSchema", "AggregationFunction", "AggregationNodeSchema", "JoinType", "JoinStrategy", "JoinNodeSchema", "WindowFunction", "WindowSpecSchema", "WindowFunctionNodeSchema", "FieldNodeSchema", "FullTextSearchSchema", "BaseQuerySchema", "QuerySchema", "SystemIdentifierSchema", "SnakeCaseIdentifierSchema", "EncryptionAlgorithmSchema", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "MaskingStrategySchema", "MaskingRuleSchema", "FieldType", "SelectOptionSchema", "CurrencyConfigSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "FieldSchema", "BaseValidationSchema", "ScriptValidationSchema", "UniquenessValidationSchema", "StateMachineValidationSchema", "FormatValidationSchema", "CrossFieldValidationSchema", "JSONValidationSchema", "AsyncValidationSchema", "CustomValidatorSchema", "ValidationRuleSchema", "ConditionalValidationSchema", "ActionRefSchema", "GuardRefSchema", "TransitionSchema", "StateNodeSchema", "StateMachineSchema", "I18nLabelSchema", "AriaPropsSchema", "NumberFormatSchema", "DateFormatSchema", "ActionParamSchema", "ActionType", "TARGET_REQUIRED_TYPES", "ActionSchema", "ApiMethod", "ObjectCapabilities", "IndexSchema", "SearchConfigSchema", "TenancyConfigSchema", "SoftDeleteConfigSchema", "VersioningConfigSchema", "PartitioningConfigSchema", "CDCConfigSchema", "ObjectSchemaBase", "ObjectSchema", "DatasetMode", "DatasetSchema", "FieldMappingSchema", "AggregationMetricType", "DimensionType", "TimeUpdateInterval", "MetricSchema", "DimensionSchema", "CubeJoinSchema", "CubeSchema", "AnalyticsQuerySchema", "FeedItemType", "MentionSchema", "FieldChangeEntrySchema", "ReactionSchema", "FeedActorSchema", "FeedVisibility", "FeedItemSchema", "SubscriptionEventType", "NotificationChannel", "RecordSubscriptionSchema", "z", "config", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "hashCode", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "HashMap", "MingoError", "assert", "cloneDeep", "compare", "ensureArray", "findInsertIndex", "flatten", "groupBy", "has", "import_hash2", "intersection", "isArray", "isBoolean", "isDate", "isEmpty", "isEqual", "isFunction", "isInteger", "isNil", "isNumber", "isObject", "isObjectLike", "isOperator", "isRegExp", "isString", "isSymbol", "normalize", "removeValue", "resolve", "setValue", "typeOf", "unique", "import_hash", "hash", "flatten2", "unwrap", "path", "resolve2", "path2", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "util_exports", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "Context", "OpType", "ProcessingMode", "computeValue", "evalExpr", "import_util", "ProcessingMode2", "OpType2", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "concat", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "Aggregator", "import_util", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_expr", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "message", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "_expr", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_accumulator", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "sign", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "tag", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_first", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_firstN", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$in", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_last", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_lastN", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_maxN", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_minN", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "meta", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "meta", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "OPERATORS", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "Query", "import_util", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$eq", "$gt", "$gte", "$in", "$lt", "$lte", "$ne", "$nin", "wrap", "_options", "compare", "match", "isNull", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$eq", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$gt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$gte", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$lt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$lte", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$ne", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "date", "match", "year", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "date", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "date", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "date", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "require_median", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_expr", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_mergeObjects", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_percentile", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "map", "set", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "map", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "re", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_type", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_count", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "cached", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "window", "config", "array", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "map", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "map", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "import_expression", "map", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "require_set", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "path", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_slice", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_elemMatch", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_size", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_array", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$bitsAllClear", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$bitsAllSet", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$bitsAnyClear", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$bitsAnySet", "_options", "require_bitwise", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_eq", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$eq", "require_gt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$gt", "require_gte", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$gte", "require_in", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$in", "require_lt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$lt", "require_lte", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$lte", "require_ne", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$ne", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$nin", "require_comparison", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_lt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "path", "require_type", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "schema", "require_mod", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_and", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_or", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_not", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_query", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_internal", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__export", "__copyProps", "__toESM", "clone", "path", "require_addToSet", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "set", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_max", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_min", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "wrap", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_push", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_set", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "path", "require_unset", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__export", "__copyProps", "__toESM", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "core_exports", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__export", "__copyProps", "__toESM", "Aggregator", "import_core", "Query", "index_default", "env", "createLogger", "message", "args", "message", "APIError", "init_error", "message", "error", "schema", "date", "_reject", "isCompatible", "_a", "_b", "logger", "DiagComponentLogger", "DiagLogLevel", "logger", "DiagAPI", "logger", "__spreadArray", "__read", "_a", "_b", "BaseContext", "NoopContextManager", "_context", "__spreadArray", "__read", "API_NAME", "init_context", "ContextAPI", "_a", "__spreadArray", "__read", "TraceFlags", "NonRecordingSpan", "_status", "_a", "init_context", "init_context", "NoopTracer", "ProxyTracer", "version", "_options", "_context", "tracer", "NoopTracerProvider", "_options", "ProxyTracerProvider", "version", "_a", "SpanStatusCode", "API_NAME", "init_trace", "TraceAPI", "success", "version", "init_trace", "init_esm", "init_esm", "init_id", "init_error", "schema", "m", "init_error", "schema", "f", "init_id", "schema", "init_error", "schema", "schema", "schema", "transactionId", "init_error", "config", "schema", "logger", "createLogger", "join", "data", "unsafe_model", "select", "transformedData", "error", "file", "log", "config", "clone", "error", "join", "record", "isString", "isNumber", "isBoolean", "isDate", "isFunction", "isObject", "schema", "schema", "schema", "schema", "isObject", "isFunction", "isObject", "isString", "isString", "isObject", "isString", "sql", "message", "isString", "schema", "isNumber", "isBoolean", "isBoolean", "isString", "groupBy", "join", "fetch", "_props", "_props", "isFunction", "isString", "isFunction", "isFunction", "_props", "isNumber", "_props", "error", "_a", "_props", "error", "_a", "_props", "join_fn", "error", "_props", "isFunction", "randomString", "randomString", "_queryId", "schema", "join", "schema", "isString", "_promise", "resolve", "_props", "error", "set", "_props", "schema", "groupBy", "groupBy", "isFunction", "isFunction", "_node", "isNumber", "_a", "_props", "join_fn", "_alias", "groupBy", "error", "_props", "_alias", "isString", "_props", "_node", "_alias", "binary", "schema", "isFunction", "isObject", "isString", "_table", "_alias", "isString", "trim", "schema", "_node", "_node", "_props", "_props", "_props", "_props", "_node", "_node", "_node", "_props", "_props", "_props", "_props", "_props", "_props", "_props", "createView", "_transformer", "_props", "_props", "_props", "_props", "trim", "createView", "_props", "schema", "isFunction", "_driver", "_a", "_b", "error", "config", "isFunction", "isObject", "isFunction", "isObject", "_props", "_executor", "_state", "schema", "error", "_props", "_alias", "sql", "array", "isString", "isBoolean", "isNumber", "isDate", "sql", "_connection", "_db", "_promise", "_resolve", "config", "isFunction", "sql", "resolve", "_db", "_a", "sql", "_db", "_config", "config", "ID_WRAP_REGEX", "_db", "schema", "_db", "isObject", "isString", "isObject", "_config", "_connections", "isFunction", "sql", "resolve", "ID_WRAP_REGEX", "_db", "parseTableMetadata_fn", "LOCK_ID", "_config", "config", "PRIVATE_RELEASE_METHOD", "_config", "_connections", "_pool", "config", "isFunction", "sql", "_config", "config", "_config", "_pool", "_connection", "_tedious", "config", "resolve", "error", "randomString", "isString", "isNumber", "isBoolean", "isDate", "_db", "join", "_config", "config", "init_esm", "_config", "_connectionMutex", "_db", "_connection", "_a", "_promise", "_resolve", "ConnectionMutex", "getTableMetadata_fn", "init_esm", "config", "sql", "resolve", "_config", "_connectionMutex", "_db", "_connection", "_a", "_promise", "_resolve", "ConnectionMutex", "getTableMetadata_fn", "init_esm", "config", "sql", "resolve", "_config", "_connection", "_a", "_db", "init_esm", "config", "insensitiveIn", "insensitiveNotIn", "init_dist", "init_esm", "config", "BunSqliteDialect", "error", "NodeSqliteDialect", "D1SqliteDialect", "db", "schema", "join", "entry", "eb", "init_dist", "z", "config", "z", "SearchConfigSchema", "config", "z", "config", "z", "z", "HttpMethod", "HttpMethodSchema", "CorsConfigSchema", "RateLimitConfigSchema", "StaticMountSchema", "config", "SystemIdentifierSchema", "SnakeCaseIdentifierSchema", "z", "config", "z", "z", "z", "z", "I18nLabelSchema", "AriaPropsSchema", "NumberFormatSchema", "DateFormatSchema", "SnakeCaseIdentifierSchema", "LocaleSchema", "FieldTranslationSchema", "ObjectTranslationDataSchema", "TranslationDataSchema", "TranslationFileOrganizationSchema", "MessageFormatSchema", "OptionTranslationMapSchema", "ObjectTranslationNodeSchema", "TranslationDiffStatusSchema", "TranslationDiffItemSchema", "CoverageBreakdownEntrySchema", "z", "z", "z", "z", "z", "TranslationDataSchema", "HttpMethod", "config", "SnakeCaseIdentifierSchema", "RateLimitConfigSchema", "VersioningConfigSchema", "z", "StorageScopeSchema", "z", "FileMetadataSchema", "StorageProviderSchema", "StorageAclSchema", "StorageClassSchema", "LifecycleActionSchema", "MultipartUploadConfigSchema", "AccessControlConfigSchema", "LifecyclePolicyRuleSchema", "SystemIdentifierSchema", "LifecyclePolicyConfigSchema", "BucketConfigSchema", "StorageConnectionSchema", "ObjectStorageConfigSchema", "EncryptionAlgorithmSchema", "z", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "MaskingStrategySchema", "MaskingRuleSchema", "FieldType", "SelectOptionSchema", "SystemIdentifierSchema", "CurrencyConfigSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "FieldSchema", "BaseValidationSchema", "ScriptValidationSchema", "UniquenessValidationSchema", "StateMachineValidationSchema", "FormatValidationSchema", "CrossFieldValidationSchema", "JSONValidationSchema", "AsyncValidationSchema", "CustomValidatorSchema", "ValidationRuleSchema", "ConditionalValidationSchema", "ActionRefSchema", "GuardRefSchema", "TransitionSchema", "StateNodeSchema", "StateMachineSchema", "SnakeCaseIdentifierSchema", "ActionParamSchema", "I18nLabelSchema", "ActionType", "TARGET_REQUIRED_TYPES", "ActionSchema", "AriaPropsSchema", "ApiMethod", "ObjectCapabilities", "IndexSchema", "SearchConfigSchema", "TenancyConfigSchema", "SoftDeleteConfigSchema", "VersioningConfigSchema", "PartitioningConfigSchema", "CDCConfigSchema", "ObjectSchemaBase", "snakeCaseToLabel", "ObjectSchema", "config", "MetadataFormatSchema", "MetadataStatsSchema", "MetadataFallbackStrategySchema", "MetadataManagerConfigSchema", "MetadataBulkRegisterRequestSchema", "CoreServiceName", "ServiceCriticalitySchema", "z", "HttpServerConfigSchema", "CorsConfigSchema", "RateLimitConfigSchema", "StaticMountSchema", "HttpMethod", "MiddlewareType", "MiddlewareConfigSchema", "ServerEventType", "config", "config", "z", "HttpMethod", "z", "z", "z", "z", "z", "z", "z", "z", "z", "z", "z", "z", "config", "error", "message", "levelColors", "meta", "resolve", "logger", "logger", "error", "path", "version", "config", "map", "service", "duration", "__export", "path", "_context", "resolve", "url", "_PluginSandboxRuntime", "logger", "config", "allowed", "url", "SystemIdentifierSchema", "SnakeCaseIdentifierSchema", "EventNameSchema", "TransformTypeSchema", "z", "FieldMappingSchema", "HttpMethod", "HttpMethodSchema", "HttpRequestSchema", "CorsConfigSchema", "RateLimitConfigSchema", "StaticMountSchema", "SortDirectionEnum", "IsolationLevelEnum", "MetadataFormatSchema", "EncryptionAlgorithmSchema", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "MaskingStrategySchema", "MaskingRuleSchema", "FieldType", "SelectOptionSchema", "CurrencyConfigSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "logger", "config", "record", "error", "path", "env", "map", "sys", "appId", "SeedLoaderRequestSchema", "meta", "message", "method", "data", "expand", "_context", "labels", "registry", "success", "file", "info", "result", "object", "MetadataCategoryEnum", "z", "ArtifactFileEntrySchema", "ArtifactChecksumSchema", "ArtifactSignatureSchema", "PackageArtifactSchema", "TenantIsolationLevel", "DatabaseProviderSchema", "TenantConnectionConfigSchema", "TenantQuotaSchema", "RowLevelIsolationStrategySchema", "SchemaLevelIsolationStrategySchema", "DatabaseLevelIsolationStrategySchema", "DependencyStatusEnum", "ResolvedDependencySchema", "RequiredActionSchema", "DependencyResolutionResultSchema", "SnakeCaseIdentifierSchema", "EventNameSchema", "z", "EventNameSchema", "SnakeCaseIdentifierSchema", "config", "CapabilityConformanceLevelSchema", "ProtocolVersionSchema", "ProtocolReferenceSchema", "ProtocolFeatureSchema", "PluginCapabilitySchema", "PluginInterfaceSchema", "PluginDependencySchema", "ExtensionPointSchema", "PluginCapabilityManifestSchema", "PluginLoadingStrategySchema", "PluginPreloadConfigSchema", "PluginCodeSplittingSchema", "PluginDynamicImportSchema", "PluginInitializationSchema", "PluginDependencyResolutionSchema", "PluginHotReloadSchema", "PluginCachingSchema", "PluginSandboxingSchema", "PluginPerformanceMonitoringSchema", "PluginLoadingConfigSchema", "PluginLifecycleSchema", "CORE_PLUGIN_TYPES", "DatasetMode", "DatasetSchema", "ManifestSchema", "FieldChangeSchema", "MetadataOverlaySchema", "MergeConflictSchema", "MergeStrategyConfigSchema", "CustomizationPolicySchema", "MetadataFormatSchema", "MetadataStatsSchema", "MetadataLoadOptionsSchema", "MetadataSaveOptionsSchema", "MetadataExportOptionsSchema", "MetadataImportOptionsSchema", "MetadataLoadResultSchema", "MetadataSaveResultSchema", "MetadataWatchEventSchema", "MetadataCollectionInfoSchema", "MetadataLoaderContractSchema", "MetadataFallbackStrategySchema", "MetadataManagerConfigSchema", "MetadataTypeSchema", "MetadataTypeRegistryEntrySchema", "MetadataQuerySchema", "MetadataQueryResultSchema", "MetadataEventSchema", "MetadataValidationResultSchema", "MetadataPluginConfigSchema", "z", "MetadataBulkResultSchema", "MetadataDependencySchema", "PackageStatusEnum", "InstalledPackageSchema", "ManifestSchema", "ListPackagesRequestSchema", "ListPackagesResponseSchema", "GetPackageRequestSchema", "GetPackageResponseSchema", "InstallPackageRequestSchema", "InstallPackageResponseSchema", "DependencyResolutionResultSchema", "UninstallPackageRequestSchema", "UninstallPackageResponseSchema", "EnablePackageRequestSchema", "EnablePackageResponseSchema", "DisablePackageRequestSchema", "DisablePackageResponseSchema", "MetadataChangeTypeSchema", "MetadataDiffItemSchema", "UpgradeImpactLevelSchema", "UpgradePlanSchema", "UpgradePhaseSchema", "path", "file", "issue", "PluginCapabilityManifestSchema", "ExecutionContextSchema", "z", "I18nLabelSchema", "AriaPropsSchema", "NumberFormatSchema", "DateFormatSchema", "z", "BreakpointName", "BreakpointColumnMapSchema", "BreakpointOrderMapSchema", "ResponsiveConfigSchema", "PerformanceConfigSchema", "SystemIdentifierSchema", "SnakeCaseIdentifierSchema", "SharingConfigSchema", "EmbedConfigSchema", "BaseNavItemSchema", "ObjectNavItemSchema", "DashboardNavItemSchema", "PageNavItemSchema", "UrlNavItemSchema", "ReportNavItemSchema", "ActionNavItemSchema", "GroupNavItemSchema", "NavigationItemSchema", "AppBrandingSchema", "NavigationAreaSchema", "AppSchema", "config", "HttpMethod", "HttpMethodSchema", "HttpRequestSchema", "ViewDataSchema", "ViewFilterRuleSchema", "ColumnSummarySchema", "ListColumnSchema", "SelectionConfigSchema", "PaginationConfigSchema", "RowHeightSchema", "GroupingFieldSchema", "GroupingConfigSchema", "GalleryConfigSchema", "TimelineConfigSchema", "ViewSharingSchema", "RowColorConfigSchema", "VisualizationTypeSchema", "UserActionsConfigSchema", "AppearanceConfigSchema", "ViewTabSchema", "AddRecordConfigSchema", "KanbanConfigSchema", "CalendarConfigSchema", "GanttConfigSchema", "NavigationModeSchema", "NavigationConfigSchema", "ListViewSchema", "FormFieldSchema", "FormSectionSchema", "FormViewSchema", "ViewSchema", "FieldReferenceSchema", "z", "FieldOperatorsSchema", "FilterConditionSchema", "NormalizedFilterSchema", "I18nLabelSchema", "SnakeCaseIdentifierSchema", "ResponsiveConfigSchema", "AriaPropsSchema", "PerformanceConfigSchema", "z", "I18nLabelSchema", "ResponsiveConfigSchema", "SnakeCaseIdentifierSchema", "FilterConditionSchema", "AriaPropsSchema", "PerformanceConfigSchema", "EncryptionAlgorithmSchema", "z", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "MaskingStrategySchema", "MaskingRuleSchema", "FieldType", "SelectOptionSchema", "SystemIdentifierSchema", "CurrencyConfigSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "FieldSchema", "ActionParamSchema", "I18nLabelSchema", "ActionType", "TARGET_REQUIRED_TYPES", "ActionSchema", "SnakeCaseIdentifierSchema", "AriaPropsSchema", "z", "SortDirectionEnum", "SortItemSchema", "FilterConditionSchema", "I18nLabelSchema", "ResponsiveConfigSchema", "AriaPropsSchema", "ViewFilterRuleSchema", "AppearanceConfigSchema", "ViewTabSchema", "UserActionsConfigSchema", "AddRecordConfigSchema", "SnakeCaseIdentifierSchema", "PerformanceConfigSchema", "FieldSchema", "FeedItemType", "MentionSchema", "FieldChangeEntrySchema", "ReactionSchema", "FeedActorSchema", "FeedVisibility", "FeedFilterMode", "z", "z", "z", "SnakeCaseIdentifierSchema", "I18nLabelSchema", "AriaPropsSchema", "NotificationSchema", "NotificationConfigSchema", "schema", "cached", "ObjectSchema", "AppSchema", "InstalledPackageSchema", "ManifestSchema", "now", "hash", "config", "record", "error", "object", "groupBy", "map", "_request", "_ObjectQL", "expand", "ExecutionContextSchema", "ql", "__export", "__esm", "_LocalStoragePersistenceAdapter", "raw", "json", "path", "_InMemoryDriver", "config", "record", "object", "groupBy", "schema", "env", "LocalStoragePersistenceAdapter", "FileSystemPersistenceAdapter", "path", "paths", "match", "cacheKey", "decoder", "url", "path", "url", "_a", "path", "raw", "init", "_matchResult", "_a", "Context", "object", "html", "html2", "_res", "_path", "_notFoundHandler", "_a", "path", "url", "clone", "env", "Context", "path", "path2", "_a", "_a", "path", "path", "map", "_a", "re", "paths", "path2", "_routes", "_a", "init", "path", "router", "_children", "_a", "Node", "path", "_a", "Node", "path", "Hono", "Hono", "message", "toResponse", "encoder", "path", "file", "url", "transform", "init_error", "url", "error", "path", "config", "message", "info", "hash", "message", "hash", "info", "isLE", "decode", "encode", "encode", "string", "CHUNK_SIZE", "binary", "decode", "encode", "algorithm", "hash", "alg", "alg", "message", "_a", "alg", "enc", "tag", "algorithm", "decode", "algorithm", "isObjectLike", "isObject", "alg", "algorithm", "encode", "getCryptoKey", "alg", "encode", "deriveKey", "wrap", "unwrap", "alg", "algorithm", "hash", "subtleAlgorithm", "alg", "encrypt", "decrypt", "algorithm", "alg", "freeze", "cached", "hash", "decode", "alg", "isObject", "decode", "encode", "alg", "use", "wrap", "alg", "encode", "unwrap", "tag", "alg", "isObject", "decrypt", "unwrap", "tag", "enc", "encode", "encrypt", "wrap", "alg", "isObject", "protectedHeader", "decode", "alg", "enc", "tag", "encode", "tag", "alg", "enc", "encode", "tag", "isObject", "decode", "alg", "encode", "date", "isObject", "now", "jwt", "jwt", "_payload", "_protectedHeader", "_unprotectedHeader", "alg", "encode", "_flattened", "_protectedHeader", "_jwt", "_cek", "_iv", "_keyManagementParameters", "_protectedHeader", "_jwt", "enc", "check", "encode", "alg", "isObject", "jwk", "error", "_cached", "cache", "cached", "set", "VERSION", "url", "isObject", "_url", "json", "set", "decode", "isObject", "jwt", "decode", "isObject", "version", "config", "resolve", "hash", "hash", "base64", "algorithm", "encoder", "base64", "isBytes", "anumber", "abytes", "message", "aexists", "aoutput", "clean", "createView", "abytes", "hex", "error", "array", "abytes", "mac", "isLE", "anumber", "createView", "randomBytes", "anumber", "abytes", "clean", "abytes", "clean", "aexists", "aoutput", "abytes", "clean", "tag", "version", "hex", "init_error", "cache", "cacheKey", "schema", "APIError", "schema", "logger", "REGEX", "parse", "match", "parse", "init_error", "encoder", "decoder", "hex", "algorithm", "hmac", "hex", "base64", "domain", "version", "cleanCookies", "init_error", "string", "number", "boolean", "message", "stateCookie", "error", "symbol", "ensureAsyncStorage", "ensureAsyncStorage", "ensureAsyncStorage", "ensureAsyncStorage", "error", "init_error", "APIError", "error", "init_error", "allowed", "error", "tryDecode", "promise", "init", "body", "headers", "getCryptoKey", "tryDecode", "error", "path", "error", "getCryptoKey", "options", "url", "headers", "json", "path", "required", "config", "splitPath", "path", "match", "_a", "path", "splitPath", "match", "createRouter", "config", "schema", "router", "createRou3Router", "methods", "path", "url", "error", "isAPIError", "error", "APIError", "path", "url", "init_error", "message", "logger", "logBackwardCompatWarning", "url", "APIError", "ipv4", "ipv6", "path", "window", "now", "path", "_path", "config", "init_error", "APIError", "session", "parsedSession", "parsedUser", "updateAge", "shouldSkipSessionRefresh", "error", "isAPIError", "config", "string", "hash", "config", "init_id", "now", "logger", "cached", "options", "ctx", "sessions", "session", "email", "accounts", "isPlainObject", "object", "init_error", "init_error", "getDate", "now", "hash", "authorizationEndpoint", "duration", "url", "error", "url", "_a", "_b", "isJSONSerializable", "isFunction", "isJSONSerializable", "getBody", "url", "_a", "ValidationError", "message", "schema", "getURL", "url", "path", "_url", "_a", "_b", "fetch", "getBody", "clearTimeout", "parser", "isJSONResponse", "resolve", "refreshToken", "base64", "tokenEndpoint", "error", "now", "base64", "tokenEndpoint", "error", "tokenEndpoint", "refreshToken", "APIError", "init_error", "tokenEndpoint", "refreshToken", "error", "init_error", "authorizationEndpoint", "tokenEndpoint", "url", "refreshToken", "error", "APIError", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "refreshToken", "profile", "userMap", "error", "init_error", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "error", "refreshToken", "authorizationEndpoint", "tokenEndpoint", "userinfoEndpoint", "refreshToken", "error", "init_error", "refreshToken", "APIError", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "refreshToken", "error", "authorizationEndpoint", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "authorizationEndpoint", "tokenEndpoint", "refreshToken", "error", "init_error", "authorizationEndpoint", "tokenEndpoint", "error", "base64", "refreshToken", "APIError", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "init_error", "authorizationEndpoint", "tokenEndpoint", "refreshToken", "init_error", "authorizationEndpoint", "tokenEndpoint", "base64", "error", "refreshToken", "tokenEndpoint", "refreshToken", "error", "refreshToken", "error", "error", "base64", "refreshToken", "tokenEndpoint", "refreshToken", "error", "init_error", "authorizationEndpoint", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "url", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "tokenEndpoint", "refreshToken", "init_error", "error", "tokenEndpoint", "refreshToken", "error", "url", "error", "refreshToken", "url", "refreshToken", "error", "_enum", "string", "accounts", "string", "boolean", "APIError", "url", "refreshToken", "info", "init_error", "email", "APIError", "url", "string", "error", "jwt", "updatedUser", "url", "isAPIError", "string", "error", "url", "toRedirectTo", "custom", "error", "url", "init_error", "APIError", "init_error", "init_id", "url", "email", "string", "APIError", "verifyPassword", "init_error", "string", "boolean", "number", "APIError", "url", "email", "init_error", "init_id", "string", "email", "boolean", "APIError", "now", "hash", "isAPIError", "url", "init_error", "string", "APIError", "init_error", "string", "APIError", "boolean", "revokeOtherSessions", "account", "url", "email", "token", "init_error", "key", "isAPIError", "error", "APIError", "init_error", "logger", "path", "methods", "verifyPassword", "error", "rateLimitResponse", "isAPIError", "memoryAdapter", "init_error", "createKyselyAdapter", "kyselyAdapter", "config", "schema", "key", "init_dist", "init_esm", "map", "normalize", "config", "logger", "createLogger", "error", "init_error", "unique", "version", "logger", "init_error", "init_id", "fs", "path", "base64", "generateId", "raw", "path", "json", "env", "fs", "version", "noop", "estimateEntropy", "unique", "logger", "createLogger", "config", "url", "promise", "init_error", "init_dist", "init_error", "init_error", "init_id", "date", "match", "year", "day", "hour", "minute", "value", "error", "init_error", "organization", "user", "role", "member", "email", "init_error", "success", "role", "role", "string", "APIError", "version", "version", "schema", "string", "number", "init_error", "role", "string", "APIError", "defaultRoles", "member", "error", "init_error", "string", "boolean", "APIError", "email", "role", "organization", "teamIds", "init_error", "string", "APIError", "organization", "member", "updatedMember", "number", "_enum", "boolean", "init_error", "string", "boolean", "APIError", "options", "organization", "number", "init_id", "string", "_enum", "date", "defaultRoles", "init_error", "string", "APIError", "organization", "updatedTeam", "init_error", "string", "_undefined", "APIError", "teamSchema", "schema", "init_error", "APIError", "ctx", "session", "init_error", "string", "boolean", "twoFactor", "APIError", "defaultKeyHasher", "hash", "init_error", "string", "boolean", "defaultKeyHasher", "APIError", "schema", "init_error", "getAlphabet", "hex", "hash", "window", "string", "boolean", "APIError", "twoFactor", "init_error", "string", "APIError", "schema", "path", "defaultKeyHasher", "hash", "email", "string", "defaultKeyHasher", "url", "error", "path", "record", "SystemObjectName", "config", "email", "url", "ObjectSchema", "Field", "error", "crypto", "message", "Request", "url", "init", "error", "url2", "_a", "cache", "crypto", "isPromise", "resolve", "__export", "AggregationFunctionEnum", "AppNameSchema", "BaseMetadataRecordSchema", "CacheStrategyEnum", "CorsConfigSchema", "EventNameSchema", "FieldMappingSchema", "FieldNameSchema", "FlowNameSchema", "HttpMethod", "HttpMethodSchema", "HttpRequestSchema", "IsolationLevelEnum", "MetadataFormatSchema", "MutationEventEnum", "ObjectNameSchema", "PLURAL_TO_SINGULAR", "RateLimitConfigSchema", "RoleNameSchema", "SINGULAR_TO_PLURAL", "SnakeCaseIdentifierSchema", "SortDirectionEnum", "SortItemSchema", "StaticMountSchema", "SystemIdentifierSchema", "TransformTypeSchema", "ViewNameSchema", "pluralToSingular", "z", "EncryptionAlgorithmSchema", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "FieldEncryptionSchema", "MaskingStrategySchema", "MaskingRuleSchema", "MaskingConfigSchema", "FieldType", "SelectOptionSchema", "LocationCoordinatesSchema", "CurrencyConfigSchema", "CurrencyValueSchema", "AddressSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "FieldSchema", "Field", "config", "issue", "suggestions", "suggestion", "base", "path", "error", "schema", "data_exports", "ALL_OPERATORS", "AggregationFunction", "AggregationMetricType", "AggregationNodeSchema", "AggregationPipelineSchema", "AggregationStageSchema", "AnalyticsQuerySchema", "ApiMethod", "AsyncValidationSchema", "BaseEngineOptionsSchema", "CDCConfigSchema", "ComparisonOperatorSchema", "ConditionalValidationSchema", "ConsistencyLevelSchema", "CrossFieldValidationSchema", "CubeJoinSchema", "CubeSchema", "CustomValidatorSchema", "DataEngineAggregateOptionsSchema", "DataEngineAggregateRequestSchema", "DataEngineBatchRequestSchema", "DataEngineContractSchema", "DataEngineCountOptionsSchema", "DataEngineCountRequestSchema", "DataEngineDeleteOptionsSchema", "DataEngineDeleteRequestSchema", "DataEngineExecuteRequestSchema", "DataEngineFilterSchema", "DataEngineFindOneRequestSchema", "DataEngineFindRequestSchema", "DataEngineInsertOptionsSchema", "DataEngineInsertRequestSchema", "DataEngineQueryOptionsSchema", "DataEngineRequestSchema", "DataEngineSortSchema", "DataEngineUpdateOptionsSchema", "DataEngineUpdateRequestSchema", "DataEngineVectorFindRequestSchema", "DataTypeMappingSchema", "DatasetLoadResultSchema", "DatasetMode", "DatasetSchema", "DatasourceCapabilities", "DatasourceSchema", "DimensionSchema", "DimensionType", "DocumentSchema", "DocumentSchemaValidationSchema", "DocumentTemplateSchema", "DocumentVersionSchema", "DriverCapabilitiesSchema", "DriverConfigSchema", "DriverDefinitionSchema", "DriverInterfaceSchema", "DriverOptionsSchema", "DriverType", "ESignatureConfigSchema", "EngineAggregateOptionsSchema", "EngineCountOptionsSchema", "EngineDeleteOptionsSchema", "EngineQueryOptionsSchema", "EngineUpdateOptionsSchema", "EqualityOperatorSchema", "ExternalDataSourceSchema", "ExternalFieldMappingSchema", "ExternalLookupSchema", "FILTER_OPERATORS", "FeedActorSchema", "FeedFilterMode", "FeedItemSchema", "FeedItemType", "FeedVisibility", "FieldChangeEntrySchema", "FieldNodeSchema", "FieldOperatorsSchema", "FieldReferenceSchema", "FilterConditionSchema", "FormatValidationSchema", "FullTextSearchSchema", "HookContextSchema", "HookEvent", "HookSchema", "IndexSchema", "JSONValidationSchema", "JoinNodeSchema", "JoinStrategy", "JoinType", "LOGICAL_OPERATORS", "MappingSchema", "MentionSchema", "MetricSchema", "NoSQLDataTypeMappingSchema", "NoSQLDatabaseTypeSchema", "NoSQLDriverConfigSchema", "NoSQLIndexSchema", "NoSQLIndexTypeSchema", "NoSQLOperationTypeSchema", "NoSQLQueryOptionsSchema", "NoSQLTransactionOptionsSchema", "NormalizedFilterSchema", "NotificationChannel", "ObjectCapabilities", "ObjectDependencyGraphSchema", "ObjectDependencyNodeSchema", "ObjectExtensionSchema", "ObjectOwnershipEnum", "ObjectSchema", "PartitioningConfigSchema", "PoolConfigSchema", "QueryFilterSchema", "QuerySchema", "RangeOperatorSchema", "ReactionSchema", "RecordSubscriptionSchema", "ReferenceResolutionErrorSchema", "ReferenceResolutionSchema", "ReplicationConfigSchema", "SQLDialectSchema", "SQLDriverConfigSchema", "SQLiteAlterTableLimitations", "SQLiteDataTypeMappingDefaults", "SSLConfigSchema", "ScriptValidationSchema", "SearchConfigSchema", "SeedLoaderConfigSchema", "SeedLoaderRequestSchema", "SeedLoaderResultSchema", "SetOperatorSchema", "ShardingConfigSchema", "SoftDeleteConfigSchema", "SortNodeSchema", "SpecialOperatorSchema", "StateMachineValidationSchema", "StringOperatorSchema", "SubscriptionEventType", "TenancyConfigSchema", "TenantDatabaseLifecycleSchema", "TenantResolverStrategySchema", "TimeUpdateInterval", "TransformType", "TursoGroupSchema", "TursoMultiTenantConfigSchema", "UniquenessValidationSchema", "VALID_AST_OPERATORS", "ValidationRuleSchema", "VersioningConfigSchema", "WindowFunction", "WindowFunctionNodeSchema", "WindowSpecSchema", "isFilterAST", "parseFilterAST", "AST_OPERATOR_MAP", "convertComparison", "BaseQuerySchema", "BaseValidationSchema", "ActionRefSchema", "GuardRefSchema", "TransitionSchema", "EventSchema", "StateNodeSchema", "StateMachineSchema", "I18nObjectSchema", "I18nLabelSchema", "AriaPropsSchema", "PluralRuleSchema", "NumberFormatSchema", "DateFormatSchema", "LocaleConfigSchema", "ActionParamSchema", "ActionType", "TARGET_REQUIRED_TYPES", "ActionSchema", "ObjectSchemaBase", "snakeCaseToLabel", "ExecutionContextSchema", "RpcLegacyFilterMixin", "RpcQueryOptionsSchema", "FieldPermissionSchema", "ObjectPermissionSchema", "PermissionSetSchema", "RLSAuditConfigSchema", "RLSOperation", "RowLevelSecurityPolicySchema", "object", "AIChatWindowProps", "ActionNavItemSchema", "AddRecordConfigSchema", "AnimationSchema", "AnimationTriggerSchema", "App", "AppBrandingSchema", "AppSchema", "AppearanceConfigSchema", "BlankPageLayoutItemSchema", "BlankPageLayoutSchema", "BorderRadiusSchema", "BreakpointColumnMapSchema", "BreakpointName", "BreakpointOrderMapSchema", "BreakpointsSchema", "CalendarConfigSchema", "ChartAnnotationSchema", "ChartAxisSchema", "ChartConfigSchema", "ChartInteractionSchema", "ChartSeriesSchema", "ChartTypeSchema", "ColorPaletteSchema", "ColumnSummarySchema", "ComponentAnimationSchema", "ComponentPropsMap", "ConflictResolutionSchema", "DashboardHeaderActionSchema", "DashboardHeaderSchema", "DashboardNavItemSchema", "DashboardSchema", "DashboardWidgetSchema", "DensityModeSchema", "DndConfigSchema", "DragConstraintSchema", "DragHandleSchema", "DragItemSchema", "DropEffectSchema", "DropZoneSchema", "EasingFunctionSchema", "ElementButtonPropsSchema", "ElementDataSourceSchema", "ElementFilterPropsSchema", "ElementFormPropsSchema", "ElementImagePropsSchema", "ElementNumberPropsSchema", "ElementRecordPickerPropsSchema", "ElementTextPropsSchema", "EmbedConfigSchema", "EvictionPolicySchema", "FieldWidgetPropsSchema", "FocusManagementSchema", "FocusTrapConfigSchema", "FormFieldSchema", "FormSectionSchema", "FormViewSchema", "GalleryConfigSchema", "GanttConfigSchema", "GestureConfigSchema", "GestureTypeSchema", "GlobalFilterOptionsFromSchema", "GlobalFilterSchema", "GroupNavItemSchema", "GroupingConfigSchema", "GroupingFieldSchema", "InterfacePageConfigSchema", "KanbanConfigSchema", "KeyboardNavigationConfigSchema", "KeyboardShortcutSchema", "ListColumnSchema", "ListViewSchema", "LongPressGestureConfigSchema", "MotionConfigSchema", "NavigationAreaSchema", "NavigationConfigSchema", "NavigationItemSchema", "NavigationModeSchema", "NotificationActionSchema", "NotificationConfigSchema", "NotificationPositionSchema", "NotificationSchema", "NotificationSeveritySchema", "NotificationTypeSchema", "ObjectNavItemSchema", "OfflineCacheConfigSchema", "OfflineConfigSchema", "OfflineStrategySchema", "PageAccordionProps", "PageCardProps", "PageComponentSchema", "PageComponentType", "PageHeaderProps", "PageNavItemSchema", "PageRegionSchema", "PageSchema", "PageTabsProps", "PageTransitionSchema", "PageTypeSchema", "PageVariableSchema", "PaginationConfigSchema", "PerformanceConfigSchema", "PersistStorageSchema", "PinchGestureConfigSchema", "RecordActivityProps", "RecordChatterProps", "RecordDetailsProps", "RecordHighlightsProps", "RecordPathProps", "RecordRelatedListProps", "RecordReviewConfigSchema", "ReportChartSchema", "ReportColumnSchema", "ReportGroupingSchema", "ReportNavItemSchema", "ReportSchema", "ReportType", "ResponsiveConfigSchema", "RowColorConfigSchema", "RowHeightSchema", "SelectionConfigSchema", "ShadowSchema", "SharingConfigSchema", "SpacingSchema", "SwipeDirectionSchema", "SwipeGestureConfigSchema", "SyncConfigSchema", "ThemeModeSchema", "ThemeSchema", "TimelineConfigSchema", "TouchInteractionSchema", "TouchTargetConfigSchema", "TransitionConfigSchema", "TransitionPresetSchema", "TypographySchema", "UrlNavItemSchema", "UserActionsConfigSchema", "ViewDataSchema", "ViewFilterRuleSchema", "ViewSchema", "ViewSharingSchema", "ViewTabSchema", "VisualizationTypeSchema", "WcagContrastLevelSchema", "WidgetActionTypeSchema", "WidgetColorVariantSchema", "WidgetEventSchema", "WidgetLifecycleSchema", "WidgetManifestSchema", "WidgetMeasureSchema", "WidgetPropertySchema", "WidgetSourceSchema", "ZIndexSchema", "defineApp", "BaseNavItemSchema", "EmptyProps", "AccessControlConfigSchema", "AddFieldOperation", "AdvancedAuthConfigSchema", "AnalyzerConfigSchema", "AppCompatibilityCheckSchema", "AppInstallRequestSchema", "AppInstallResultSchema", "AppManifestSchema", "AppTranslationBundleSchema", "AuditConfigSchema", "AuditEventActorSchema", "AuditEventChangeSchema", "AuditEventFilterSchema", "AuditEventSchema", "AuditEventSeverity", "AuditEventTargetSchema", "AuditEventType", "AuditFindingSchema", "AuditFindingSeveritySchema", "AuditFindingStatusSchema", "AuditLogConfigSchema", "AuditRetentionPolicySchema", "AuditScheduleSchema", "AuditStorageConfigSchema", "AuthConfigSchema", "AuthPluginConfigSchema", "AuthProviderConfigSchema", "AwarenessEventSchema", "AwarenessSessionSchema", "AwarenessUpdateSchema", "AwarenessUserStateSchema", "BackupConfigSchema", "BackupRetentionSchema", "BackupStrategySchema", "BatchProgressSchema", "BatchTask", "BatchTaskSchema", "BucketConfigSchema", "CRDTMergeResultSchema", "CRDTStateSchema", "CRDTType", "CacheAvalanchePreventionSchema", "CacheConfigSchema", "CacheConsistencySchema", "CacheInvalidationSchema", "CacheStrategySchema", "CacheTierSchema", "CacheWarmupSchema", "ChangeImpactSchema", "ChangePrioritySchema", "ChangeRequestSchema", "ChangeSetSchema", "ChangeStatusSchema", "ChangeTypeSchema", "CollaborationMode", "CollaborationSessionConfigSchema", "CollaborationSessionSchema", "CollaborativeCursorSchema", "ComplianceAuditRequirementSchema", "ComplianceConfigSchema", "ComplianceEncryptionRequirementSchema", "ComplianceFrameworkSchema", "ConsoleDestinationConfigSchema", "ConsumerConfigSchema", "CoreServiceName", "CounterOperationSchema", "CoverageBreakdownEntrySchema", "CreateObjectOperation", "CronScheduleSchema", "CursorColorPreset", "CursorSelectionSchema", "CursorStyleSchema", "CursorUpdateSchema", "DataClassificationPolicySchema", "DataClassificationSchema", "DatabaseLevelIsolationStrategySchema", "DatabaseProviderSchema", "DeadLetterQueueSchema", "DeleteObjectOperation", "DeployBundleSchema", "DeployDiffSchema", "DeployManifestSchema", "DeployStatusEnum", "DeployValidationIssueSchema", "DeployValidationResultSchema", "DisasterRecoveryPlanSchema", "DistributedCacheConfigSchema", "EmailAndPasswordConfigSchema", "EmailTemplateSchema", "EmailVerificationConfigSchema", "ExecuteSqlOperation", "ExtendedLogLevel", "ExternalServiceDestinationConfigSchema", "FacetConfigSchema", "FailoverConfigSchema", "FailoverModeSchema", "FeatureSchema", "FieldTranslationSchema", "FileDestinationConfigSchema", "FileMetadataSchema", "GCounterSchema", "GDPRConfigSchema", "HIPAAConfigSchema", "HistogramBucketConfigSchema", "HttpDestinationConfigSchema", "HttpServerConfig", "HttpServerConfigSchema", "InAppNotificationSchema", "IncidentCategorySchema", "IncidentNotificationMatrixSchema", "IncidentNotificationRuleSchema", "IncidentResponsePhaseSchema", "IncidentResponsePolicySchema", "IncidentSchema", "IncidentSeveritySchema", "IncidentStatusSchema", "IntervalScheduleSchema", "JobExecutionSchema", "JobExecutionStatus", "JobSchema", "KernelServiceMapSchema", "LWWRegisterSchema", "LicenseMetricType", "LicenseSchema", "LifecycleActionSchema", "LifecyclePolicyConfigSchema", "LifecyclePolicyRuleSchema", "LocaleSchema", "LogDestinationSchema", "LogDestinationType", "LogEnrichmentConfigSchema", "LogEntrySchema", "LogFormat", "LogLevel", "LoggerConfigSchema", "LoggingConfigSchema", "MaskingVisibilityRuleSchema", "MessageFormatSchema", "MessageQueueConfigSchema", "MessageQueueProviderSchema", "MetadataCollectionInfoSchema", "MetadataDiffResultSchema", "MetadataExportOptionsSchema", "MetadataFallbackStrategySchema", "MetadataHistoryQueryOptionsSchema", "MetadataHistoryQueryResultSchema", "MetadataHistoryRecordSchema", "MetadataHistoryRetentionPolicySchema", "MetadataImportOptionsSchema", "MetadataLoadOptionsSchema", "MetadataLoadResultSchema", "MetadataLoaderContractSchema", "MetadataManagerConfigSchema", "MetadataRecordSchema", "MetadataSaveOptionsSchema", "MetadataSaveResultSchema", "MetadataScopeSchema", "MetadataSourceSchema", "MetadataStateSchema", "MetadataStatsSchema", "MetadataWatchEventSchema", "MetricAggregationConfigSchema", "MetricAggregationType", "MetricDataPointSchema", "MetricDefinitionSchema", "MetricExportConfigSchema", "MetricLabelsSchema", "MetricType", "MetricUnit", "MetricsConfigSchema", "MiddlewareConfig", "MiddlewareConfigSchema", "MiddlewareType", "MigrationDependencySchema", "MigrationOperationSchema", "MigrationPlanSchema", "MigrationStatementSchema", "ModifyFieldOperation", "MultipartUploadConfigSchema", "MutualTLSConfigSchema", "NotificationChannelSchema", "ORSetElementSchema", "ORSetSchema", "OTComponentSchema", "OTOperationSchema", "OTOperationType", "OTTransformResultSchema", "ObjectMetadataSchema", "ObjectStorageConfigSchema", "ObjectTranslationDataSchema", "ObjectTranslationNodeSchema", "OnceScheduleSchema", "OpenTelemetryCompatibilitySchema", "OtelExporterType", "PCIDSSConfigSchema", "PNCounterSchema", "PackagePublishResultSchema", "PlanSchema", "PresignedUrlConfigSchema", "ProvisioningStepSchema", "PushNotificationSchema", "QueueConfig", "QueueConfigSchema", "QuotaEnforcementResultSchema", "RPOSchema", "RTOSchema", "RegistryConfigSchema", "RegistrySyncPolicySchema", "RegistryUpstreamSchema", "RemoveFieldOperation", "RenameObjectOperation", "RetryPolicySchema", "RollbackPlanSchema", "RouteHandlerMetadataSchema", "RowLevelIsolationStrategySchema", "SMSTemplateSchema", "SamplingDecision", "SamplingStrategyType", "ScheduleSchema", "SchemaChangeSchema", "SchemaLevelIsolationStrategySchema", "SearchIndexConfigSchema", "SearchProviderSchema", "SecurityContextConfigSchema", "SecurityEventCorrelationSchema", "ServerCapabilitiesSchema", "ServerEventSchema", "ServerEventType", "ServerStatusSchema", "ServiceConfigSchema", "ServiceCriticalitySchema", "ServiceLevelIndicatorSchema", "ServiceLevelObjectiveSchema", "ServiceRequirementDef", "ServiceStatusSchema", "SocialProviderConfigSchema", "SpanAttributeValueSchema", "SpanAttributesSchema", "SpanEventSchema", "SpanKind", "SpanLinkSchema", "SpanSchema", "SpanStatus", "StorageAclSchema", "StorageClassSchema", "StorageConnectionSchema", "StorageProviderSchema", "StorageScopeSchema", "StructuredLogEntrySchema", "SupplierAssessmentStatusSchema", "SupplierRiskLevelSchema", "SupplierSecurityAssessmentSchema", "SupplierSecurityPolicySchema", "SupplierSecurityRequirementSchema", "SuspiciousActivityRuleSchema", "SystemObjectName", "Task", "TaskExecutionResultSchema", "TaskPriority", "TaskRetryPolicySchema", "TaskSchema", "TaskStatus", "TenantConnectionConfigSchema", "TenantIsolationConfigSchema", "TenantIsolationLevel", "TenantPlanSchema", "TenantProvisioningRequestSchema", "TenantProvisioningResultSchema", "TenantProvisioningStatusEnum", "TenantQuotaSchema", "TenantRegionSchema", "TenantSchema", "TenantSecurityPolicySchema", "TenantUsageSchema", "TextCRDTOperationSchema", "TextCRDTStateSchema", "TimeSeriesDataPointSchema", "TimeSeriesSchema", "TopicConfigSchema", "TraceContextPropagationSchema", "TraceContextSchema", "TraceFlagsSchema", "TracePropagationFormat", "TraceSamplingConfigSchema", "TraceStateSchema", "TracingConfigSchema", "TrainingCategorySchema", "TrainingCompletionStatusSchema", "TrainingCourseSchema", "TrainingPlanSchema", "TrainingRecordSchema", "TranslationBundleSchema", "TranslationConfigSchema", "TranslationCoverageResultSchema", "TranslationDataSchema", "TranslationDiffItemSchema", "TranslationDiffStatusSchema", "TranslationFileOrganizationSchema", "UserActivityStatus", "VectorClockSchema", "WorkerConfig", "WorkerConfigSchema", "WorkerStatsSchema", "azureBlobStorageExample", "gcsStorageExample", "minioStorageExample", "s3StorageExample", "OptionTranslationMapSchema", "map", "ActivationEventSchema", "AdvancedPluginLifecycleConfigSchema", "ArtifactChecksumSchema", "ArtifactFileEntrySchema", "ArtifactSignatureSchema", "BreakingChangeSchema", "CLICommandContributionSchema", "CORE_PLUGIN_TYPES", "CapabilityConformanceLevelSchema", "CompatibilityLevelSchema", "CompatibilityMatrixEntrySchema", "CustomizationOriginSchema", "CustomizationPolicySchema", "DeadLetterQueueEntrySchema", "DependencyConflictSchema", "DependencyGraphNodeSchema", "DependencyGraphSchema", "DependencyResolutionResultSchema", "DependencyStatusEnum", "DeprecationNoticeSchema", "DevFixtureConfigSchema", "DevPluginConfigSchema", "DevPluginPreset", "DevServiceOverrideSchema", "DevToolsConfigSchema", "DisablePackageRequestSchema", "DisablePackageResponseSchema", "DistributedStateConfigSchema", "DynamicLoadRequestSchema", "DynamicLoadingConfigSchema", "DynamicPluginOperationSchema", "DynamicPluginResultSchema", "DynamicUnloadRequestSchema", "EnablePackageRequestSchema", "EnablePackageResponseSchema", "EventBusConfigSchema", "EventHandlerSchema", "EventLogEntrySchema", "EventMessageQueueConfigSchema", "EventMetadataSchema", "EventPersistenceSchema", "EventPhaseSchema", "EventPriority", "EventQueueConfigSchema", "EventReplayConfigSchema", "EventRouteSchema", "EventSourcingConfigSchema", "EventTypeDefinitionSchema", "EventWebhookConfigSchema", "ExtensionPointSchema", "FeatureFlag", "FeatureFlagSchema", "FeatureStrategy", "FieldChangeSchema", "GetPackageRequestSchema", "GetPackageResponseSchema", "GracefulDegradationSchema", "HealthStatusSchema", "HookRegisteredEventSchema", "HookTriggeredEventSchema", "HotReloadConfigSchema", "InstallPackageRequestSchema", "InstallPackageResponseSchema", "InstalledPackageSchema", "KernelContextSchema", "KernelEventBaseSchema", "KernelReadyEventSchema", "KernelSecurityPolicySchema", "KernelSecurityScanResultSchema", "KernelSecurityVulnerabilitySchema", "KernelShutdownEventSchema", "ListPackagesRequestSchema", "ListPackagesResponseSchema", "ManifestSchema", "MergeConflictSchema", "MergeResultSchema", "MergeStrategyConfigSchema", "MetadataBulkRegisterRequestSchema", "MetadataBulkResultSchema", "MetadataCategoryEnum", "MetadataChangeTypeSchema", "MetadataDependencySchema", "MetadataDiffItemSchema", "MetadataEventSchema", "MetadataOverlaySchema", "MetadataPluginConfigSchema", "MetadataPluginManifestSchema", "MetadataQueryResultSchema", "MetadataQuerySchema", "MetadataTypeRegistryEntrySchema", "MetadataTypeSchema", "MetadataValidationResultSchema", "MultiVersionSupportSchema", "NamespaceConflictErrorSchema", "NamespaceRegistryEntrySchema", "OclifPluginConfigSchema", "OpsDomainModuleSchema", "OpsFilePathSchema", "OpsPluginStructureSchema", "PackageArtifactSchema", "PackageDependencyConflictSchema", "PackageDependencyResolutionResultSchema", "PackageDependencySchema", "PackageStatusEnum", "PermissionActionSchema", "PermissionSchema", "PermissionScopeSchema", "PluginBuildOptionsSchema", "PluginBuildResultSchema", "PluginCachingSchema", "PluginCapabilityManifestSchema", "PluginCapabilitySchema", "PluginCodeSplittingSchema", "PluginCompatibilityMatrixSchema", "PluginContextSchema", "PluginDependencyResolutionResultSchema", "PluginDependencyResolutionSchema", "PluginDependencySchema", "PluginDiscoveryConfigSchema", "PluginDiscoverySourceSchema", "PluginDynamicImportSchema", "PluginErrorEventSchema", "PluginEventBaseSchema", "PluginHealthCheckSchema", "PluginHealthReportSchema", "PluginHealthStatusSchema", "PluginHotReloadSchema", "PluginInitializationSchema", "PluginInstallConfigSchema", "PluginInterfaceSchema", "PluginLifecycleEventType", "PluginLifecyclePhaseEventSchema", "PluginLifecycleSchema", "PluginLoadingConfigSchema", "PluginLoadingEventSchema", "PluginLoadingStateSchema", "PluginLoadingStrategySchema", "PluginMetadataSchema", "PluginPerformanceMonitoringSchema", "PluginPreloadConfigSchema", "PluginProvenanceSchema", "PluginPublishOptionsSchema", "PluginPublishResultSchema", "PluginQualityMetricsSchema", "PluginRegisteredEventSchema", "PluginRegistryEntrySchema", "PluginSandboxingSchema", "PluginSchema", "PluginSearchFiltersSchema", "PluginSecurityManifestSchema", "PluginSourceSchema", "PluginStartupResultSchema", "PluginStateSnapshotSchema", "PluginStatisticsSchema", "PluginTrustLevelSchema", "PluginTrustScoreSchema", "PluginUpdateStrategySchema", "PluginValidateOptionsSchema", "PluginValidateResultSchema", "PluginVendorSchema", "PluginVersionMetadataSchema", "PreviewModeConfigSchema", "ProtocolFeatureSchema", "ProtocolReferenceSchema", "ProtocolVersionSchema", "RealTimeNotificationConfigSchema", "RequiredActionSchema", "ResolvedDependencySchema", "ResourceTypeSchema", "RollbackPackageRequestSchema", "RollbackPackageResponseSchema", "RuntimeConfigSchema", "RuntimeMode", "SBOMEntrySchema", "SBOMSchema", "SandboxConfigSchema", "ScopeConfigSchema", "ScopeInfoSchema", "SecurityPolicySchema", "SecurityScanResultSchema", "SecurityVulnerabilitySchema", "SemanticVersionSchema", "ServiceFactoryRegistrationSchema", "ServiceMetadataSchema", "ServiceRegisteredEventSchema", "ServiceRegistryConfigSchema", "ServiceScopeType", "ServiceUnregisteredEventSchema", "StartupOptionsSchema", "StartupOrchestrationResultSchema", "TenantRuntimeContextSchema", "UninstallPackageRequestSchema", "UninstallPackageResponseSchema", "UpgradeContextSchema", "UpgradeImpactLevelSchema", "UpgradePackageRequestSchema", "UpgradePackageResponseSchema", "UpgradePhaseSchema", "UpgradePlanSchema", "UpgradeSnapshotSchema", "ValidationErrorSchema", "ValidationFindingSchema", "ValidationResultSchema", "ValidationSeverityEnum", "ValidationWarningSchema", "VersionConstraintSchema", "VulnerabilitySeverity", "SNAKE_CASE_REGEX", "file", "ArtifactReferenceSchema", "ListingStatusSchema", "MarketplaceCategorySchema", "MarketplaceListingSchema", "PricingModelSchema", "PublisherVerificationSchema", "qa_exports", "SessionSchema", "email", "AckMessageSchema", "AddReactionRequestSchema", "AddReactionResponseSchema", "AiInsightsRequestSchema", "AiInsightsResponseSchema", "AiNlqRequestSchema", "AiNlqResponseSchema", "AiSuggestRequestSchema", "AiSuggestResponseSchema", "AnalyticsEndpoint", "AnalyticsMetadataResponseSchema", "AnalyticsQueryRequestSchema", "AnalyticsResultResponseSchema", "AnalyticsSqlResponseSchema", "ApiChangelogEntrySchema", "ApiDiscoveryQuerySchema", "ApiDiscoveryResponseSchema", "ApiDocumentationConfig", "ApiDocumentationConfigSchema", "ApiEndpoint", "ApiEndpointRegistration", "ApiEndpointRegistrationSchema", "ApiEndpointSchema", "ApiErrorSchema", "ApiMappingSchema", "ApiMetadataSchema", "ApiParameterSchema", "ApiProtocolType", "ApiRegistry", "ApiRegistryEntry", "ApiRegistryEntrySchema", "ApiRegistrySchema", "ApiResponseSchema", "ApiRoutesSchema", "ApiTestCollection", "ApiTestCollectionSchema", "ApiTestRequestSchema", "ApiTestingUiConfigSchema", "ApiTestingUiType", "AppDefinitionResponseSchema", "AuthEndpointAliases", "AuthEndpointPaths", "AuthEndpointSchema", "AuthProvider", "AutomationApiErrorCode", "AutomationFlowPathParamsSchema", "AutomationRunPathParamsSchema", "AutomationTriggerRequestSchema", "AutomationTriggerResponseSchema", "BasePresenceSchema", "BaseResponseSchema", "BatchConfigSchema", "BatchDataRequestSchema", "BatchEndpointsConfigSchema", "BatchLoadingStrategySchema", "BatchOperationResultSchema", "BatchOperationType", "BatchOptionsSchema", "BatchRecordSchema", "BatchUpdateRequestSchema", "BatchUpdateResponseSchema", "BulkRequestSchema", "BulkResponseSchema", "CacheControlSchema", "CacheDirective", "CacheInvalidationRequestSchema", "CacheInvalidationResponseSchema", "CacheInvalidationTarget", "CallbackSchema", "ChangelogEntrySchema", "CheckPermissionRequestSchema", "CheckPermissionResponseSchema", "CodeGenerationTemplateSchema", "CompleteChunkedUploadRequestSchema", "CompleteChunkedUploadResponseSchema", "CompleteUploadRequestSchema", "ConceptListResponseSchema", "ConflictResolutionStrategy", "CreateDataRequestSchema", "CreateDataResponseSchema", "CreateExportJobRequestSchema", "CreateExportJobResponseSchema", "CreateFeedItemRequestSchema", "CreateFeedItemResponseSchema", "CreateFlowResponseSchema", "CreateManyDataRequestSchema", "CreateManyDataResponseSchema", "CreateRequestSchema", "CreateViewRequestSchema", "CreateViewResponseSchema", "CrudEndpointPatternSchema", "CrudEndpointsConfigSchema", "CrudOperation", "CursorMessageSchema", "CursorPositionSchema", "DataEventSchema", "DataEventType", "DataLoaderConfigSchema", "DeduplicationStrategy", "DeleteDataRequestSchema", "DeleteDataResponseSchema", "DeleteFeedItemResponseSchema", "DeleteFlowResponseSchema", "DeleteManyDataRequestSchema", "DeleteManyRequestSchema", "DeleteResponseSchema", "DeleteViewRequestSchema", "DeleteViewResponseSchema", "DiscoverySchema", "DispatcherConfigSchema", "DispatcherErrorCode", "DispatcherErrorResponseSchema", "DispatcherRouteSchema", "DocumentStateSchema", "ETagSchema", "EditMessageSchema", "EditOperationSchema", "EditOperationType", "EndpointMapping", "EndpointRegistrySchema", "EnhancedApiErrorSchema", "ErrorCategory", "ErrorHandlingConfigSchema", "ErrorMessageSchema", "ErrorResponseSchema", "EventFilterCondition", "EventFilterSchema", "EventMessageSchema", "EventPatternSchema", "EventSubscriptionSchema", "ExportApiContracts", "ExportFormat", "ExportImportTemplateSchema", "ExportJobProgressSchema", "ExportJobStatus", "ExportJobSummarySchema", "ExportRequestSchema", "FederationEntityKeySchema", "FederationEntitySchema", "FederationExternalFieldSchema", "FederationGatewaySchema", "FederationProvidesSchema", "FederationRequiresSchema", "FeedApiErrorCode", "FeedItemPathParamsSchema", "FeedListFilterType", "FeedPathParamsSchema", "FieldErrorSchema", "FieldMappingEntrySchema", "FileTypeValidationSchema", "FileUploadResponseSchema", "FilterOperator", "FindDataRequestSchema", "FindDataResponseSchema", "FlowSummarySchema", "GeneratedApiDocumentationSchema", "GeneratedEndpointSchema", "GetAnalyticsMetaRequestSchema", "GetChangelogRequestSchema", "GetChangelogResponseSchema", "GetDataRequestSchema", "GetDataResponseSchema", "GetDiscoveryRequestSchema", "GetDiscoveryResponseSchema", "GetEffectivePermissionsRequestSchema", "GetEffectivePermissionsResponseSchema", "GetExportJobDownloadRequestSchema", "GetExportJobDownloadResponseSchema", "GetFeedRequestSchema", "GetFeedResponseSchema", "GetFieldLabelsRequestSchema", "GetFieldLabelsResponseSchema", "GetFlowResponseSchema", "GetInstalledPackageResponseSchema", "GetLocalesRequestSchema", "GetLocalesResponseSchema", "GetMetaItemCachedRequestSchema", "GetMetaItemRequestSchema", "GetMetaItemResponseSchema", "GetMetaItemsRequestSchema", "GetMetaItemsResponseSchema", "GetMetaTypesRequestSchema", "GetMetaTypesResponseSchema", "GetNotificationPreferencesRequestSchema", "GetNotificationPreferencesResponseSchema", "GetObjectPermissionsRequestSchema", "GetObjectPermissionsResponseSchema", "GetPresenceRequestSchema", "GetPresenceResponseSchema", "GetPresignedUrlRequestSchema", "GetRunResponseSchema", "GetTranslationsRequestSchema", "GetTranslationsResponseSchema", "GetUiViewRequestSchema", "GetViewRequestSchema", "GetViewResponseSchema", "GetWorkflowConfigRequestSchema", "GetWorkflowConfigResponseSchema", "GetWorkflowStateRequestSchema", "GetWorkflowStateResponseSchema", "GraphQLConfig", "GraphQLConfigSchema", "GraphQLDataLoaderConfigSchema", "GraphQLDirectiveConfigSchema", "GraphQLDirectiveLocation", "GraphQLMutationConfigSchema", "GraphQLPersistedQuerySchema", "GraphQLQueryAdapterSchema", "GraphQLQueryComplexitySchema", "GraphQLQueryConfigSchema", "GraphQLQueryDepthLimitSchema", "GraphQLRateLimitSchema", "GraphQLResolverConfigSchema", "GraphQLScalarType", "GraphQLSubscriptionConfigSchema", "GraphQLTypeConfigSchema", "HandlerStatusSchema", "HttpFindQueryParamsSchema", "HttpStatusCode", "IdRequestSchema", "ImportValidationConfigSchema", "ImportValidationMode", "ImportValidationResultSchema", "InitiateChunkedUploadRequestSchema", "InitiateChunkedUploadResponseSchema", "ListExportJobsRequestSchema", "ListExportJobsResponseSchema", "ListFlowsRequestSchema", "ListFlowsResponseSchema", "ListInstalledPackagesRequestSchema", "ListInstalledPackagesResponseSchema", "ListNotificationsRequestSchema", "ListNotificationsResponseSchema", "ListRecordResponseSchema", "ListRunsRequestSchema", "ListRunsResponseSchema", "ListViewsRequestSchema", "ListViewsResponseSchema", "LoginRequestSchema", "LoginType", "MarkAllNotificationsReadRequestSchema", "MarkAllNotificationsReadResponseSchema", "MarkNotificationsReadRequestSchema", "MarkNotificationsReadResponseSchema", "MetadataBulkResponseSchema", "MetadataBulkUnregisterRequestSchema", "MetadataCacheRequestSchema", "MetadataCacheResponseSchema", "MetadataDeleteResponseSchema", "MetadataDependenciesResponseSchema", "MetadataDependentsResponseSchema", "MetadataEffectiveResponseSchema", "MetadataEndpointsConfigSchema", "MetadataEventType", "MetadataExistsResponseSchema", "MetadataExportRequestSchema", "MetadataExportResponseSchema", "MetadataImportRequestSchema", "MetadataImportResponseSchema", "MetadataItemResponseSchema", "MetadataListResponseSchema", "MetadataNamesResponseSchema", "MetadataOverlayResponseSchema", "MetadataOverlaySaveRequestSchema", "MetadataQueryRequestSchema", "MetadataQueryResponseSchema", "MetadataRegisterRequestSchema", "MetadataTypeInfoResponseSchema", "MetadataTypesResponseSchema", "MetadataValidateRequestSchema", "MetadataValidateResponseSchema", "ModificationResultSchema", "NotificationPreferencesSchema", "ODataConfigSchema", "ODataErrorSchema", "ODataFilterFunctionSchema", "ODataFilterOperatorSchema", "ODataMetadataSchema", "ODataQueryAdapterSchema", "ODataQuerySchema", "ODataResponseSchema", "ObjectDefinitionResponseSchema", "ObjectQLReferenceSchema", "ObjectStackProtocolSchema", "OpenApi31ExtensionsSchema", "OpenApiGenerationConfigSchema", "OpenApiSecuritySchemeSchema", "OpenApiServerSchema", "OpenApiSpec", "OpenApiSpecSchema", "OperatorMappingSchema", "PackageApiErrorCode", "PackageInstallRequestSchema", "PackageInstallResponseSchema", "PackagePathParamsSchema", "PackageRollbackRequestSchema", "PackageRollbackResponseSchema", "PackageUpgradeRequestSchema", "PackageUpgradeResponseSchema", "PinFeedItemResponseSchema", "PingMessageSchema", "PongMessageSchema", "PresenceMessageSchema", "PresenceStateSchema", "PresenceStatus", "PresenceUpdateSchema", "PresignedUrlResponseSchema", "QueryAdapterConfigSchema", "QueryAdapterTargetSchema", "QueryOptimizationConfigSchema", "RealtimeConfigSchema", "RealtimeConnectRequestSchema", "RealtimeConnectResponseSchema", "RealtimeDisconnectRequestSchema", "RealtimeDisconnectResponseSchema", "RealtimeEventSchema", "RealtimeEventType", "RealtimePresenceSchema", "RealtimeRecordAction", "RealtimeSubscribeRequestSchema", "RealtimeSubscribeResponseSchema", "RealtimeUnsubscribeRequestSchema", "RealtimeUnsubscribeResponseSchema", "RecordDataSchema", "RefreshTokenRequestSchema", "RegisterDeviceRequestSchema", "RegisterDeviceResponseSchema", "RegisterRequestSchema", "RemoveReactionRequestSchema", "RemoveReactionResponseSchema", "RequestValidationConfigSchema", "ResolveDependenciesRequestSchema", "ResolveDependenciesResponseSchema", "ResponseEnvelopeConfigSchema", "RestApiConfig", "RestApiConfigSchema", "RestApiEndpointSchema", "RestApiPluginConfig", "RestApiPluginConfigSchema", "RestApiRouteCategory", "RestApiRouteRegistration", "RestApiRouteRegistrationSchema", "RestQueryAdapterSchema", "RestServerConfig", "RestServerConfigSchema", "RetryStrategy", "RouteCategory", "RouteCoverageEntrySchema", "RouteCoverageReportSchema", "RouteDefinitionSchema", "RouteGenerationConfigSchema", "RouteHealthEntrySchema", "RouteHealthReportSchema", "RouterConfigSchema", "SaveMetaItemRequestSchema", "SaveMetaItemResponseSchema", "ScheduleExportRequestSchema", "ScheduleExportResponseSchema", "ScheduledExportSchema", "SchemaDefinition", "SearchFeedRequestSchema", "SearchFeedResponseSchema", "ServiceInfoSchema", "ServiceStatus", "SessionResponseSchema", "SessionUserSchema", "SetPresenceRequestSchema", "SetPresenceResponseSchema", "SimpleCursorPositionSchema", "SimplePresenceStateSchema", "SingleRecordResponseSchema", "StandardApiContracts", "StandardErrorCode", "StarFeedItemResponseSchema", "SubgraphConfigSchema", "SubscribeMessageSchema", "SubscribeRequestSchema", "SubscribeResponseSchema", "SubscriptionEventSchema", "SubscriptionSchema", "ToggleFlowRequestSchema", "ToggleFlowResponseSchema", "TransportProtocol", "TriggerFlowRequestSchema", "TriggerFlowResponseSchema", "UninstallPackageApiResponseSchema", "UnpinFeedItemResponseSchema", "UnregisterDeviceRequestSchema", "UnregisterDeviceResponseSchema", "UnstarFeedItemResponseSchema", "UnsubscribeMessageSchema", "UnsubscribeRequestSchema", "UnsubscribeResponseSchema", "UpdateDataRequestSchema", "UpdateDataResponseSchema", "UpdateFeedItemRequestSchema", "UpdateFeedItemResponseSchema", "UpdateFlowRequestSchema", "UpdateFlowResponseSchema", "UpdateManyDataRequestSchema", "UpdateManyRequestSchema", "UpdateNotificationPreferencesRequestSchema", "UpdateNotificationPreferencesResponseSchema", "UpdateRequestSchema", "UpdateViewRequestSchema", "UpdateViewResponseSchema", "UploadArtifactRequestSchema", "UploadArtifactResponseSchema", "UploadChunkRequestSchema", "UploadChunkResponseSchema", "UploadProgressSchema", "UserProfileResponseSchema", "ValidationMode", "VersionDefinitionSchema", "VersionNegotiationResponseSchema", "VersionStatus", "VersioningStrategy", "WebSocketConfigSchema", "WebSocketEventSchema", "WebSocketMessageSchema", "WebSocketMessageType", "WebSocketPresenceStatus", "WebSocketServerConfigSchema", "WebhookConfigSchema", "WebhookEventSchema", "WellKnownCapabilitiesSchema", "WorkflowApproveRequestSchema", "WorkflowApproveResponseSchema", "WorkflowRejectRequestSchema", "WorkflowRejectResponseSchema", "WorkflowStateSchema", "WorkflowTransitionRequestSchema", "WorkflowTransitionResponseSchema", "BaseWebSocketMessage", "WorkflowTriggerType", "FieldUpdateActionSchema", "EmailAlertActionSchema", "ConnectorActionRefSchema", "HttpCallActionSchema", "TaskCreationActionSchema", "PushNotificationActionSchema", "CustomScriptActionSchema", "WorkflowActionSchema", "TimeTriggerSchema", "WorkflowRuleSchema", "FlowNodeAction", "FlowVariableSchema", "FlowNodeSchema", "FlowEdgeSchema", "FlowSchema", "ExecutionStatus", "ExecutionStepLogSchema", "ExecutionLogSchema", "ExecutionErrorSeverity", "ConnectorSchema", "ConnectorTriggerSchema", "DataSyncConfigSchema", "__export", "ActivationEventSchema", "z", "ManifestSchema", "DatasourceSchema", "TranslationBundleSchema", "TranslationConfigSchema", "ObjectSchema", "ObjectExtensionSchema", "AppSchema", "ViewSchema", "PageSchema", "DashboardSchema", "ReportSchema", "ActionSchema", "ThemeSchema", "WorkflowRuleSchema", "FlowSchema", "PermissionSetSchema", "ApiEndpointSchema", "HookSchema", "MappingSchema", "CubeSchema", "ConnectorSchema", "DatasetSchema", "config", "z", "z", "FeatureFlagSchema", "ApiEndpointSchema", "Task", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "Task", "ObjectSchema", "CrmApp", "objects_exports", "Task", "Task", "ObjectSchema", "actions_exports", "ExportToCsvAction", "ExportToCsvAction", "dashboards_exports", "reports_exports", "TasksByOwnerReport", "TasksByOwnerReport", "allFlows", "apps_exports", "translations_exports", "en", "zhCN", "jaJP", "en", "zhCN", "jaJP", "objectstack_config_default", "objects_exports", "actions_exports", "dashboards_exports", "reports_exports", "allFlows", "apps_exports", "translations_exports", "objectstack_config_default", "objectstack_config_default", "env", "message", "url", "config"] +} diff --git a/examples/app-host/package.json b/examples/app-host/package.json index 3c6118813..f0bef2a2b 100644 --- a/examples/app-host/package.json +++ b/examples/app-host/package.json @@ -16,16 +16,21 @@ "@example/app-crm": "workspace:*", "@example/app-todo": "workspace:*", "@example/plugin-bi": "workspace:*", + "@hono/node-server": "^1.19.14", "@objectstack/driver-memory": "workspace:*", + "@objectstack/hono": "workspace:*", "@objectstack/metadata": "workspace:*", "@objectstack/objectql": "workspace:*", "@objectstack/plugin-auth": "workspace:*", "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/runtime": "workspace:*", - "@objectstack/spec": "workspace:*" + "@objectstack/spec": "workspace:*", + "better-sqlite3": "^11.8.1", + "hono": "^4.12.12" }, "devDependencies": { "@objectstack/cli": "workspace:*", + "esbuild": "^0.24.2", "ts-node": "^10.9.2", "tsx": "^4.21.0", "typescript": "^6.0.2" diff --git a/examples/app-host/scripts/build-vercel.sh b/examples/app-host/scripts/build-vercel.sh new file mode 100755 index 000000000..a7e8460fc --- /dev/null +++ b/examples/app-host/scripts/build-vercel.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Build script for Vercel deployment of @example/app-host. +# +# Follows the Vercel deployment pattern: +# - api/[[...route]].js is committed to the repo (Vercel detects it pre-build) +# - esbuild bundles server/index.ts → api/_handler.js (self-contained bundle) +# - The committed .js wrapper re-exports from _handler.js at runtime +# +# Steps: +# 1. Build the project with turbo +# 2. Bundle the API serverless function (→ api/_handler.js) +# 3. Copy native/external modules into local node_modules for Vercel packaging + +echo "[build-vercel] Starting app-host build..." + +# 1. Build the project with turbo (from monorepo root) +cd ../.. +pnpm turbo run build --filter=@example/app-host +cd examples/app-host + +# 2. Bundle API serverless function +node scripts/bundle-api.mjs + +# 3. Copy native/external modules into local node_modules for Vercel packaging. +# +# This monorepo uses pnpm's default strict node_modules structure. Transitive +# native dependencies like better-sqlite3 only exist in the monorepo root's +# node_modules/.pnpm/ virtual store — they're NOT symlinked into +# examples/app-host/node_modules/. +# +# The vercel.json includeFiles pattern references node_modules/ relative to +# examples/app-host/, so we must copy the actual module files here for Vercel +# to include them in the serverless function's deployment package. +echo "[build-vercel] Copying external native modules to local node_modules..." +for mod in better-sqlite3; do + src="../../node_modules/$mod" + if [ -e "$src" ]; then + dest="node_modules/$mod" + mkdir -p "$(dirname "$dest")" + cp -rL "$src" "$dest" + echo "[build-vercel] ✓ Copied $mod" + else + echo "[build-vercel] ⚠ $mod not found at $src (skipped)" + fi +done + +echo "[build-vercel] Done. Serverless function in api/[[...route]].js → api/_handler.js" diff --git a/examples/app-host/scripts/bundle-api.mjs b/examples/app-host/scripts/bundle-api.mjs new file mode 100644 index 000000000..c252a084e --- /dev/null +++ b/examples/app-host/scripts/bundle-api.mjs @@ -0,0 +1,62 @@ +/** + * Pre-bundles the Vercel serverless API function. + * + * Vercel's @vercel/node builder resolves pnpm workspace packages via symlinks, + * which can cause esbuild to resolve to TypeScript source files rather than + * compiled dist output — producing ERR_MODULE_NOT_FOUND at runtime. + * + * This script bundles server/index.ts with ALL dependencies inlined (including + * npm packages), so the deployed function is self-contained. Only packages + * with native bindings are kept external. + * + * Run from the examples/app-host directory during the Vercel build step. + */ + +import { build } from 'esbuild'; + +// Packages that cannot be bundled (native bindings / optional drivers) +const EXTERNAL = [ + 'better-sqlite3', + // Optional knex database drivers — never used at runtime, but knex requires() them + 'pg', + 'pg-native', + 'pg-query-stream', + 'mysql', + 'mysql2', + 'sqlite3', + 'oracledb', + 'tedious', + // macOS-only native file watcher + 'fsevents', +]; + +await build({ + entryPoints: ['server/index.ts'], + bundle: true, + platform: 'node', + format: 'esm', + target: 'es2020', + outfile: 'api/_handler.js', + sourcemap: true, + external: EXTERNAL, + // Silence warnings about optional/unused require() calls in knex drivers + logOverride: { 'require-resolve-not-external': 'silent' }, + // Vercel resolves ESM .js files correctly when "type": "module" is set. + // CJS format would conflict with the project's "type": "module" setting, + // causing Node.js to fail parsing require()/module.exports as ESM syntax. + // + // The createRequire banner provides a real `require` function in the ESM + // scope. esbuild's __require shim (generated for CJS→ESM conversion) + // checks `typeof require !== "undefined"` and uses it when available, + // which fixes "Dynamic require of is not supported" errors + // from CJS dependencies like knex/tarn that require() Node.js built-ins. + banner: { + js: [ + '// Bundled by esbuild — see scripts/bundle-api.mjs', + 'import { createRequire } from "module";', + 'const require = createRequire(import.meta.url);', + ].join('\n'), + }, +}); + +console.log('[bundle-api] Bundled server/index.ts → api/_handler.js'); diff --git a/examples/app-host/server/index.ts b/examples/app-host/server/index.ts new file mode 100644 index 000000000..0f296a485 --- /dev/null +++ b/examples/app-host/server/index.ts @@ -0,0 +1,220 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Vercel Serverless API Entrypoint for App Host Example + * + * Boots the ObjectStack kernel lazily on the first request and delegates + * all /api/* traffic to the ObjectStack Hono adapter. + * + * Uses `getRequestListener()` from `@hono/node-server` to handle Vercel's + * pre-buffered request body properly. + */ + +import { ObjectKernel, DriverPlugin, AppPlugin } from '@objectstack/runtime'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { InMemoryDriver } from '@objectstack/driver-memory'; +import { createHonoApp } from '@objectstack/hono'; +import { AuthPlugin } from '@objectstack/plugin-auth'; +import { getRequestListener } from '@hono/node-server'; +import type { Hono } from 'hono'; +import CrmApp from '@example/app-crm'; +import TodoApp from '@example/app-todo'; +import BiPluginManifest from '@example/plugin-bi'; + +// --------------------------------------------------------------------------- +// Singleton state — persists across warm Vercel invocations +// --------------------------------------------------------------------------- + +let _kernel: ObjectKernel | null = null; +let _app: Hono | null = null; + +/** Shared boot promise — prevents concurrent cold-start races. */ +let _bootPromise: Promise | null = null; + +// --------------------------------------------------------------------------- +// Kernel bootstrap +// --------------------------------------------------------------------------- + +/** + * Boot the ObjectStack kernel (one-time cold-start cost). + * + * Uses a shared promise so that concurrent requests during a cold start + * wait for the same boot sequence rather than starting duplicates. + */ +async function ensureKernel(): Promise { + if (_kernel) return _kernel; + if (_bootPromise) return _bootPromise; + + _bootPromise = (async () => { + console.log('[Vercel] Booting ObjectStack Kernel (app-host)...'); + + try { + const kernel = new ObjectKernel(); + + // Register ObjectQL engine + await kernel.use(new ObjectQLPlugin()); + + // Database driver (in-memory for demo) + await kernel.use(new DriverPlugin(new InMemoryDriver())); + + // Auth plugin — uses environment variables for configuration + // Prefer VERCEL_PROJECT_PRODUCTION_URL (stable across deployments) + // over VERCEL_URL (unique per deployment, causes origin mismatch). + const vercelUrl = process.env.VERCEL_PROJECT_PRODUCTION_URL + ? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` + : process.env.VERCEL_URL + ? `https://${process.env.VERCEL_URL}` + : 'http://localhost:3000'; + + await kernel.use(new AuthPlugin({ + secret: process.env.AUTH_SECRET || 'dev-secret-please-change-in-production-min-32-chars', + baseUrl: vercelUrl, + })); + + // Load app manifests + await kernel.use(new AppPlugin(CrmApp)); + await kernel.use(new AppPlugin(TodoApp)); + await kernel.use(new AppPlugin(BiPluginManifest)); + + await kernel.bootstrap(); + + _kernel = kernel; + console.log('[Vercel] Kernel ready.'); + return kernel; + } catch (err) { + // Clear the lock so the next request can retry + _bootPromise = null; + console.error('[Vercel] Kernel boot failed:', (err as any)?.message || err); + throw err; + } + })(); + + return _bootPromise; +} + +// --------------------------------------------------------------------------- +// Hono app factory +// --------------------------------------------------------------------------- + +/** + * Get (or create) the Hono application backed by the ObjectStack kernel. + * The prefix `/api/v1` matches the client SDK's default API path. + */ +async function ensureApp(): Promise { + if (_app) return _app; + + const kernel = await ensureKernel(); + _app = createHonoApp({ kernel, prefix: '/api/v1' }); + return _app; +} + +// --------------------------------------------------------------------------- +// Body extraction — reads Vercel's pre-buffered request body. +// --------------------------------------------------------------------------- + +/** Shape of the Vercel-augmented IncomingMessage passed via `env.incoming`. */ +interface VercelIncomingMessage { + rawBody?: Buffer | string; + body?: unknown; + headers?: Record; +} + +/** Shape of the env object provided by `getRequestListener` on Vercel. */ +interface VercelEnv { + incoming?: VercelIncomingMessage; +} + +function extractBody( + incoming: VercelIncomingMessage, + method: string, + contentType: string | undefined, +): BodyInit | null { + if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return null; + + if (incoming.rawBody != null) { + return incoming.rawBody; + } + + if (incoming.body != null) { + if (typeof incoming.body === 'string') return incoming.body; + if (contentType?.includes('application/json')) return JSON.stringify(incoming.body); + return String(incoming.body); + } + + return null; +} + +/** + * Derive the correct public URL for the request, fixing the protocol when + * running behind a reverse proxy such as Vercel's edge network. + */ +function resolvePublicUrl( + requestUrl: string, + incoming: VercelIncomingMessage | undefined, +): string { + if (!incoming) return requestUrl; + const fwdProto = incoming.headers?.['x-forwarded-proto']; + const rawProto = Array.isArray(fwdProto) ? fwdProto[0] : fwdProto; + // Accept only well-known protocol values to prevent header-injection attacks. + const proto = rawProto === 'https' || rawProto === 'http' ? rawProto : undefined; + if (proto === 'https' && requestUrl.startsWith('http:')) { + return requestUrl.replace(/^http:/, 'https:'); + } + return requestUrl; +} + +// --------------------------------------------------------------------------- +// Vercel Node.js serverless handler via @hono/node-server getRequestListener. +// --------------------------------------------------------------------------- + +export default getRequestListener(async (request, env) => { + let app: Hono; + try { + app = await ensureApp(); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : String(err); + console.error('[Vercel] Handler error — bootstrap did not complete:', message); + return new Response( + JSON.stringify({ + success: false, + error: { + message: 'Service Unavailable — kernel bootstrap failed.', + code: 503, + }, + }), + { status: 503, headers: { 'content-type': 'application/json' } }, + ); + } + + const method = request.method.toUpperCase(); + const incoming = (env as VercelEnv)?.incoming; + + // Fix URL protocol using x-forwarded-proto (Vercel sets this to 'https'). + const url = resolvePublicUrl(request.url, incoming); + + console.log(`[Vercel] ${method} ${url}`); + + if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && incoming) { + const contentType = incoming.headers?.['content-type']; + const contentTypeStr = Array.isArray(contentType) ? contentType[0] : contentType; + const body = extractBody(incoming, method, contentTypeStr); + if (body != null) { + return await app.fetch( + new Request(url, { method, headers: request.headers, body }), + ); + } + } + + // For GET/HEAD/OPTIONS (or body-less requests): pass through with corrected URL. + return await app.fetch( + new Request(url, { method, headers: request.headers }), + ); +}); + +/** + * Vercel per-function configuration. + */ +export const config = { + memory: 1024, + maxDuration: 60, +}; diff --git a/examples/app-host/vercel.json b/examples/app-host/vercel.json index 51142ab0a..74cb1e609 100644 --- a/examples/app-host/vercel.json +++ b/examples/app-host/vercel.json @@ -1,10 +1,16 @@ { "$schema": "https://openapi.vercel.sh/vercel.json", + "framework": null, "installCommand": "cd ../.. && pnpm install", - "buildCommand": "cd ../.. && pnpm turbo run build --filter=@example/app-host", - "outputDirectory": "dist", - "env": { - "AUTH_SECRET": "@auth_secret", - "VERCEL_URL": "@vercel_url" - } + "buildCommand": "bash scripts/build-vercel.sh", + "functions": { + "api/**/*.js": { + "memory": 1024, + "maxDuration": 60, + "includeFiles": "node_modules/better-sqlite3/**" + } + }, + "rewrites": [ + { "source": "/api/:path*", "destination": "/api/[[...route]]" } + ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 560a03771..71b307939 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -339,9 +339,15 @@ importers: '@example/plugin-bi': specifier: workspace:* version: link:../plugin-bi + '@hono/node-server': + specifier: ^1.19.14 + version: 1.19.14(hono@4.12.12) '@objectstack/driver-memory': specifier: workspace:* version: link:../../packages/plugins/driver-memory + '@objectstack/hono': + specifier: workspace:* + version: link:../../packages/adapters/hono '@objectstack/metadata': specifier: workspace:* version: link:../../packages/metadata @@ -360,10 +366,19 @@ importers: '@objectstack/spec': specifier: workspace:* version: link:../../packages/spec + better-sqlite3: + specifier: ^11.8.1 + version: 11.10.0 + hono: + specifier: ^4.12.12 + version: 4.12.12 devDependencies: '@objectstack/cli': specifier: workspace:* version: link:../../packages/cli + esbuild: + specifier: ^0.24.2 + version: 0.24.2 ts-node: specifier: ^10.9.2 version: 10.9.2(@types/node@25.6.0)(typescript@6.0.2) @@ -1676,6 +1691,12 @@ packages: '@emnapi/wasi-threads@1.2.1': resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} + '@esbuild/aix-ppc64@0.24.2': + resolution: {integrity: sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + '@esbuild/aix-ppc64@0.27.4': resolution: {integrity: sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==} engines: {node: '>=18'} @@ -1688,6 +1709,12 @@ packages: cpu: [ppc64] os: [aix] + '@esbuild/android-arm64@0.24.2': + resolution: {integrity: sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + '@esbuild/android-arm64@0.27.4': resolution: {integrity: sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==} engines: {node: '>=18'} @@ -1700,6 +1727,12 @@ packages: cpu: [arm64] os: [android] + '@esbuild/android-arm@0.24.2': + resolution: {integrity: sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + '@esbuild/android-arm@0.27.4': resolution: {integrity: sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==} engines: {node: '>=18'} @@ -1712,6 +1745,12 @@ packages: cpu: [arm] os: [android] + '@esbuild/android-x64@0.24.2': + resolution: {integrity: sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + '@esbuild/android-x64@0.27.4': resolution: {integrity: sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==} engines: {node: '>=18'} @@ -1724,6 +1763,12 @@ packages: cpu: [x64] os: [android] + '@esbuild/darwin-arm64@0.24.2': + resolution: {integrity: sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + '@esbuild/darwin-arm64@0.27.4': resolution: {integrity: sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==} engines: {node: '>=18'} @@ -1736,6 +1781,12 @@ packages: cpu: [arm64] os: [darwin] + '@esbuild/darwin-x64@0.24.2': + resolution: {integrity: sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + '@esbuild/darwin-x64@0.27.4': resolution: {integrity: sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==} engines: {node: '>=18'} @@ -1748,6 +1799,12 @@ packages: cpu: [x64] os: [darwin] + '@esbuild/freebsd-arm64@0.24.2': + resolution: {integrity: sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + '@esbuild/freebsd-arm64@0.27.4': resolution: {integrity: sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==} engines: {node: '>=18'} @@ -1760,6 +1817,12 @@ packages: cpu: [arm64] os: [freebsd] + '@esbuild/freebsd-x64@0.24.2': + resolution: {integrity: sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + '@esbuild/freebsd-x64@0.27.4': resolution: {integrity: sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==} engines: {node: '>=18'} @@ -1772,6 +1835,12 @@ packages: cpu: [x64] os: [freebsd] + '@esbuild/linux-arm64@0.24.2': + resolution: {integrity: sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + '@esbuild/linux-arm64@0.27.4': resolution: {integrity: sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==} engines: {node: '>=18'} @@ -1784,6 +1853,12 @@ packages: cpu: [arm64] os: [linux] + '@esbuild/linux-arm@0.24.2': + resolution: {integrity: sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + '@esbuild/linux-arm@0.27.4': resolution: {integrity: sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==} engines: {node: '>=18'} @@ -1796,6 +1871,12 @@ packages: cpu: [arm] os: [linux] + '@esbuild/linux-ia32@0.24.2': + resolution: {integrity: sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + '@esbuild/linux-ia32@0.27.4': resolution: {integrity: sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==} engines: {node: '>=18'} @@ -1808,6 +1889,12 @@ packages: cpu: [ia32] os: [linux] + '@esbuild/linux-loong64@0.24.2': + resolution: {integrity: sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + '@esbuild/linux-loong64@0.27.4': resolution: {integrity: sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==} engines: {node: '>=18'} @@ -1820,6 +1907,12 @@ packages: cpu: [loong64] os: [linux] + '@esbuild/linux-mips64el@0.24.2': + resolution: {integrity: sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + '@esbuild/linux-mips64el@0.27.4': resolution: {integrity: sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==} engines: {node: '>=18'} @@ -1832,6 +1925,12 @@ packages: cpu: [mips64el] os: [linux] + '@esbuild/linux-ppc64@0.24.2': + resolution: {integrity: sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + '@esbuild/linux-ppc64@0.27.4': resolution: {integrity: sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==} engines: {node: '>=18'} @@ -1844,6 +1943,12 @@ packages: cpu: [ppc64] os: [linux] + '@esbuild/linux-riscv64@0.24.2': + resolution: {integrity: sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + '@esbuild/linux-riscv64@0.27.4': resolution: {integrity: sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==} engines: {node: '>=18'} @@ -1856,6 +1961,12 @@ packages: cpu: [riscv64] os: [linux] + '@esbuild/linux-s390x@0.24.2': + resolution: {integrity: sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + '@esbuild/linux-s390x@0.27.4': resolution: {integrity: sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==} engines: {node: '>=18'} @@ -1868,6 +1979,12 @@ packages: cpu: [s390x] os: [linux] + '@esbuild/linux-x64@0.24.2': + resolution: {integrity: sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + '@esbuild/linux-x64@0.27.4': resolution: {integrity: sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==} engines: {node: '>=18'} @@ -1880,6 +1997,12 @@ packages: cpu: [x64] os: [linux] + '@esbuild/netbsd-arm64@0.24.2': + resolution: {integrity: sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + '@esbuild/netbsd-arm64@0.27.4': resolution: {integrity: sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==} engines: {node: '>=18'} @@ -1892,6 +2015,12 @@ packages: cpu: [arm64] os: [netbsd] + '@esbuild/netbsd-x64@0.24.2': + resolution: {integrity: sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + '@esbuild/netbsd-x64@0.27.4': resolution: {integrity: sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==} engines: {node: '>=18'} @@ -1904,6 +2033,12 @@ packages: cpu: [x64] os: [netbsd] + '@esbuild/openbsd-arm64@0.24.2': + resolution: {integrity: sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + '@esbuild/openbsd-arm64@0.27.4': resolution: {integrity: sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==} engines: {node: '>=18'} @@ -1916,6 +2051,12 @@ packages: cpu: [arm64] os: [openbsd] + '@esbuild/openbsd-x64@0.24.2': + resolution: {integrity: sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + '@esbuild/openbsd-x64@0.27.4': resolution: {integrity: sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==} engines: {node: '>=18'} @@ -1940,6 +2081,12 @@ packages: cpu: [arm64] os: [openharmony] + '@esbuild/sunos-x64@0.24.2': + resolution: {integrity: sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + '@esbuild/sunos-x64@0.27.4': resolution: {integrity: sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==} engines: {node: '>=18'} @@ -1952,6 +2099,12 @@ packages: cpu: [x64] os: [sunos] + '@esbuild/win32-arm64@0.24.2': + resolution: {integrity: sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + '@esbuild/win32-arm64@0.27.4': resolution: {integrity: sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==} engines: {node: '>=18'} @@ -1964,6 +2117,12 @@ packages: cpu: [arm64] os: [win32] + '@esbuild/win32-ia32@0.24.2': + resolution: {integrity: sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + '@esbuild/win32-ia32@0.27.4': resolution: {integrity: sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==} engines: {node: '>=18'} @@ -1976,6 +2135,12 @@ packages: cpu: [ia32] os: [win32] + '@esbuild/win32-x64@0.24.2': + resolution: {integrity: sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + '@esbuild/win32-x64@0.27.4': resolution: {integrity: sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==} engines: {node: '>=18'} @@ -4091,6 +4256,9 @@ packages: resolution: {integrity: sha512-pbnl5XzGBdrFU/wT4jqmJVPn2B6UHPBOhzMQkY/SPUPB6QtUXtmBHBIwCbXJol93mOpGMnQyP/+BB19q04xj7g==} engines: {node: '>=4'} + better-sqlite3@11.10.0: + resolution: {integrity: sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==} + better-sqlite3@12.9.0: resolution: {integrity: sha512-wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==} engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x} @@ -4688,6 +4856,11 @@ packages: esast-util-from-js@2.0.1: resolution: {integrity: sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw==} + esbuild@0.24.2: + resolution: {integrity: sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==} + engines: {node: '>=18'} + hasBin: true + esbuild@0.27.4: resolution: {integrity: sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==} engines: {node: '>=18'} @@ -8053,126 +8226,189 @@ snapshots: tslib: 2.8.1 optional: true + '@esbuild/aix-ppc64@0.24.2': + optional: true + '@esbuild/aix-ppc64@0.27.4': optional: true '@esbuild/aix-ppc64@0.28.0': optional: true + '@esbuild/android-arm64@0.24.2': + optional: true + '@esbuild/android-arm64@0.27.4': optional: true '@esbuild/android-arm64@0.28.0': optional: true + '@esbuild/android-arm@0.24.2': + optional: true + '@esbuild/android-arm@0.27.4': optional: true '@esbuild/android-arm@0.28.0': optional: true + '@esbuild/android-x64@0.24.2': + optional: true + '@esbuild/android-x64@0.27.4': optional: true '@esbuild/android-x64@0.28.0': optional: true + '@esbuild/darwin-arm64@0.24.2': + optional: true + '@esbuild/darwin-arm64@0.27.4': optional: true '@esbuild/darwin-arm64@0.28.0': optional: true + '@esbuild/darwin-x64@0.24.2': + optional: true + '@esbuild/darwin-x64@0.27.4': optional: true '@esbuild/darwin-x64@0.28.0': optional: true + '@esbuild/freebsd-arm64@0.24.2': + optional: true + '@esbuild/freebsd-arm64@0.27.4': optional: true '@esbuild/freebsd-arm64@0.28.0': optional: true + '@esbuild/freebsd-x64@0.24.2': + optional: true + '@esbuild/freebsd-x64@0.27.4': optional: true '@esbuild/freebsd-x64@0.28.0': optional: true + '@esbuild/linux-arm64@0.24.2': + optional: true + '@esbuild/linux-arm64@0.27.4': optional: true '@esbuild/linux-arm64@0.28.0': optional: true + '@esbuild/linux-arm@0.24.2': + optional: true + '@esbuild/linux-arm@0.27.4': optional: true '@esbuild/linux-arm@0.28.0': optional: true + '@esbuild/linux-ia32@0.24.2': + optional: true + '@esbuild/linux-ia32@0.27.4': optional: true '@esbuild/linux-ia32@0.28.0': optional: true + '@esbuild/linux-loong64@0.24.2': + optional: true + '@esbuild/linux-loong64@0.27.4': optional: true '@esbuild/linux-loong64@0.28.0': optional: true + '@esbuild/linux-mips64el@0.24.2': + optional: true + '@esbuild/linux-mips64el@0.27.4': optional: true '@esbuild/linux-mips64el@0.28.0': optional: true + '@esbuild/linux-ppc64@0.24.2': + optional: true + '@esbuild/linux-ppc64@0.27.4': optional: true '@esbuild/linux-ppc64@0.28.0': optional: true + '@esbuild/linux-riscv64@0.24.2': + optional: true + '@esbuild/linux-riscv64@0.27.4': optional: true '@esbuild/linux-riscv64@0.28.0': optional: true + '@esbuild/linux-s390x@0.24.2': + optional: true + '@esbuild/linux-s390x@0.27.4': optional: true '@esbuild/linux-s390x@0.28.0': optional: true + '@esbuild/linux-x64@0.24.2': + optional: true + '@esbuild/linux-x64@0.27.4': optional: true '@esbuild/linux-x64@0.28.0': optional: true + '@esbuild/netbsd-arm64@0.24.2': + optional: true + '@esbuild/netbsd-arm64@0.27.4': optional: true '@esbuild/netbsd-arm64@0.28.0': optional: true + '@esbuild/netbsd-x64@0.24.2': + optional: true + '@esbuild/netbsd-x64@0.27.4': optional: true '@esbuild/netbsd-x64@0.28.0': optional: true + '@esbuild/openbsd-arm64@0.24.2': + optional: true + '@esbuild/openbsd-arm64@0.27.4': optional: true '@esbuild/openbsd-arm64@0.28.0': optional: true + '@esbuild/openbsd-x64@0.24.2': + optional: true + '@esbuild/openbsd-x64@0.27.4': optional: true @@ -8185,24 +8421,36 @@ snapshots: '@esbuild/openharmony-arm64@0.28.0': optional: true + '@esbuild/sunos-x64@0.24.2': + optional: true + '@esbuild/sunos-x64@0.27.4': optional: true '@esbuild/sunos-x64@0.28.0': optional: true + '@esbuild/win32-arm64@0.24.2': + optional: true + '@esbuild/win32-arm64@0.27.4': optional: true '@esbuild/win32-arm64@0.28.0': optional: true + '@esbuild/win32-ia32@0.24.2': + optional: true + '@esbuild/win32-ia32@0.27.4': optional: true '@esbuild/win32-ia32@0.28.0': optional: true + '@esbuild/win32-x64@0.24.2': + optional: true + '@esbuild/win32-x64@0.27.4': optional: true @@ -10244,6 +10492,11 @@ snapshots: dependencies: is-windows: 1.0.2 + better-sqlite3@11.10.0: + dependencies: + bindings: 1.5.0 + prebuild-install: 7.1.3 + better-sqlite3@12.9.0: dependencies: bindings: 1.5.0 @@ -10743,6 +10996,34 @@ snapshots: esast-util-from-estree: 2.0.0 vfile-message: 4.0.3 + esbuild@0.24.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.24.2 + '@esbuild/android-arm': 0.24.2 + '@esbuild/android-arm64': 0.24.2 + '@esbuild/android-x64': 0.24.2 + '@esbuild/darwin-arm64': 0.24.2 + '@esbuild/darwin-x64': 0.24.2 + '@esbuild/freebsd-arm64': 0.24.2 + '@esbuild/freebsd-x64': 0.24.2 + '@esbuild/linux-arm': 0.24.2 + '@esbuild/linux-arm64': 0.24.2 + '@esbuild/linux-ia32': 0.24.2 + '@esbuild/linux-loong64': 0.24.2 + '@esbuild/linux-mips64el': 0.24.2 + '@esbuild/linux-ppc64': 0.24.2 + '@esbuild/linux-riscv64': 0.24.2 + '@esbuild/linux-s390x': 0.24.2 + '@esbuild/linux-x64': 0.24.2 + '@esbuild/netbsd-arm64': 0.24.2 + '@esbuild/netbsd-x64': 0.24.2 + '@esbuild/openbsd-arm64': 0.24.2 + '@esbuild/openbsd-x64': 0.24.2 + '@esbuild/sunos-x64': 0.24.2 + '@esbuild/win32-arm64': 0.24.2 + '@esbuild/win32-ia32': 0.24.2 + '@esbuild/win32-x64': 0.24.2 + esbuild@0.27.4: optionalDependencies: '@esbuild/aix-ppc64': 0.27.4 From 475941215080e30148c24ef6014f81b369bdb1bf Mon Sep 17 00:00:00 2001 From: "anthropic-code-agent[bot]" <242468646+Claude@users.noreply.github.com> Date: Mon, 13 Apr 2026 10:11:42 +0000 Subject: [PATCH 2/8] docs: add deployment documentation and Vercel deploy button Agent-Logs-Url: https://github.com/objectstack-ai/framework/sessions/cc91e2f2-a734-4a52-b865-5fa83a86e934 Co-authored-by: xuyushun441-sys <255036401+xuyushun441-sys@users.noreply.github.com> --- examples/app-host/.vercelignore | 24 ++++++ examples/app-host/DEPLOYMENT.md | 141 ++++++++++++++++++++++++++++++++ examples/app-host/README.md | 7 ++ 3 files changed, 172 insertions(+) create mode 100644 examples/app-host/.vercelignore create mode 100644 examples/app-host/DEPLOYMENT.md diff --git a/examples/app-host/.vercelignore b/examples/app-host/.vercelignore new file mode 100644 index 000000000..97d9553bc --- /dev/null +++ b/examples/app-host/.vercelignore @@ -0,0 +1,24 @@ +# Ignore build artifacts +dist/ +.turbo/ + +# Ignore test files +test/ +*.test.ts +*.spec.ts + +# Ignore development files +debug-registry.ts +src/ + +# Ignore source files (only need the bundle) +server/ +scripts/bundle-api.mjs + +# Ignore metadata (using in-memory driver) +metadata/ + +# Keep only the bundled API handler +!api/_handler.js +!api/_handler.js.map +!api/[[...route]].js diff --git a/examples/app-host/DEPLOYMENT.md b/examples/app-host/DEPLOYMENT.md new file mode 100644 index 000000000..fe2f6938e --- /dev/null +++ b/examples/app-host/DEPLOYMENT.md @@ -0,0 +1,141 @@ +# Deploying App Host to Vercel + +This example demonstrates how to deploy the ObjectStack app-host to Vercel using Hono. + +## Prerequisites + +1. A Vercel account +2. Vercel CLI installed (optional): `npm i -g vercel` + +## Environment Variables + +Set the following environment variables in your Vercel project: + +- `AUTH_SECRET`: A secure random string (minimum 32 characters) for authentication + +## Deployment Steps + +### Option 1: Using Vercel CLI + +1. Install Vercel CLI: + ```bash + npm i -g vercel + ``` + +2. Navigate to the app-host directory: + ```bash + cd examples/app-host + ``` + +3. Deploy to Vercel: + ```bash + vercel + ``` + +4. Set environment variables: + ```bash + vercel env add AUTH_SECRET + ``` + +### Option 2: Using Vercel Dashboard + +1. Import the repository to Vercel +2. Set the root directory to `examples/app-host` +3. Add environment variables in the project settings +4. Deploy + +## Build Configuration + +The build is configured in `vercel.json`: + +- **Install Command**: `cd ../.. && pnpm install` (installs monorepo dependencies) +- **Build Command**: `bash scripts/build-vercel.sh` (builds and bundles the application) +- **Framework**: `null` (uses custom build setup) + +## How It Works + +1. **Build Process** (`scripts/build-vercel.sh`): + - Builds the TypeScript project using Turbo + - Bundles the server code using esbuild (`scripts/bundle-api.mjs`) + - Copies native dependencies (like better-sqlite3) to local node_modules + +2. **API Handler** (`api/[[...route]].js`): + - Committed catch-all route handler that Vercel detects pre-build + - Delegates to the bundled handler (`api/_handler.js`) + +3. **Server Entrypoint** (`server/index.ts`): + - Boots ObjectStack kernel with Hono adapter + - Uses `@hono/node-server`'s `getRequestListener()` for Vercel compatibility + - Handles Vercel's pre-buffered request body properly + +4. **Hono Integration**: + - Uses `@objectstack/hono` adapter to create the HTTP application + - Provides REST API at `/api/v1` prefix + - Includes authentication via AuthPlugin + +## Architecture + +The deployment follows Vercel's serverless function pattern: + +``` +examples/app-host/ +├── api/ +│ ├── [[...route]].js # Committed entry point +│ └── _handler.js # Generated bundle (not committed) +├── server/ +│ └── index.ts # Server implementation +├── scripts/ +│ ├── build-vercel.sh # Build script +│ └── bundle-api.mjs # Bundler configuration +├── .npmrc # pnpm configuration (node-linker=hoisted) +└── vercel.json # Vercel configuration +``` + +## Testing Locally + +Before deploying, you can test locally: + +```bash +# Build the application +pnpm build + +# Run in development mode +pnpm dev + +# Test the API +curl http://localhost:3000/api/v1/discovery +``` + +## Accessing the API + +After deployment, your API will be available at: + +- Discovery: `https://your-app.vercel.app/api/v1/discovery` +- Data API: `https://your-app.vercel.app/api/v1/data/:object` +- Meta API: `https://your-app.vercel.app/api/v1/meta/:type` + +## Troubleshooting + +### Build Fails + +- Ensure all dependencies are installed: `pnpm install` +- Check build logs in Vercel dashboard +- Verify `build-vercel.sh` is executable: `chmod +x scripts/build-vercel.sh` + +### Runtime Errors + +- Check function logs in Vercel dashboard +- Verify environment variables are set correctly +- Ensure `AUTH_SECRET` is at least 32 characters + +### Module Not Found + +- The build script copies native modules to local node_modules +- Check that `better-sqlite3` is in dependencies +- Verify `vercel.json` includeFiles pattern matches the module + +## References + +- [Vercel Hono Documentation](https://vercel.com/docs/frameworks/backend/hono) +- [ObjectStack Documentation](../../README.md) +- [Hono Documentation](https://hono.dev/) diff --git a/examples/app-host/README.md b/examples/app-host/README.md index d16943fcc..3e0dbe0e9 100644 --- a/examples/app-host/README.md +++ b/examples/app-host/README.md @@ -3,6 +3,12 @@ This is a reference implementation of the ObjectStack Server Protocol (Kernel). It demonstrates how to build a metadata-driven backend that dynamically loads object definitions from plugins and automatically generates REST APIs. +## Deployment + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/objectstack-ai/framework/tree/main/examples/app-host&project-name=objectstack-app-host&repository-name=objectstack-app-host) + +See [DEPLOYMENT.md](./DEPLOYMENT.md) for detailed deployment instructions. + ## Features - **Dynamic Schema Loading**: Loads `crm` and `todo` apps as plugins. @@ -10,6 +16,7 @@ It demonstrates how to build a metadata-driven backend that dynamically loads ob - **Unified Data API**: `/api/v1/data/:object` (CRUD) - **Zero-Code Backend**: No creating routes or controllers per object. - **Preview Mode**: Run in demo mode — bypass login, auto-simulate admin identity. +- **Vercel Deployment**: Ready-to-deploy to Vercel with Hono adapter. ## Setup From c5424cd1b1bb789222a4211f5db1e46dd66e6098 Mon Sep 17 00:00:00 2001 From: "anthropic-code-agent[bot]" <242468646+Claude@users.noreply.github.com> Date: Mon, 13 Apr 2026 11:23:32 +0000 Subject: [PATCH 3/8] fix: exclude bundled API handler from git (build artifact) Agent-Logs-Url: https://github.com/objectstack-ai/framework/sessions/b62bdefa-1175-4e27-b791-d526cae03b4b Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com> --- examples/app-host/.gitignore | 19 + examples/app-host/api/_handler.js | 167931 ----------------------- examples/app-host/api/_handler.js.map | 7 - 3 files changed, 19 insertions(+), 167938 deletions(-) create mode 100644 examples/app-host/.gitignore delete mode 100644 examples/app-host/api/_handler.js delete mode 100644 examples/app-host/api/_handler.js.map diff --git a/examples/app-host/.gitignore b/examples/app-host/.gitignore new file mode 100644 index 000000000..7b9ccd07e --- /dev/null +++ b/examples/app-host/.gitignore @@ -0,0 +1,19 @@ +# Build artifacts +dist/ +.turbo/ + +# Bundled API handler (generated during Vercel build) +api/_handler.js +api/_handler.js.map + +# Node modules +node_modules/ + +# Environment files +.env +.env.local +.env.*.local + +# OS files +.DS_Store +Thumbs.db diff --git a/examples/app-host/api/_handler.js b/examples/app-host/api/_handler.js deleted file mode 100644 index 43f1ae53b..000000000 --- a/examples/app-host/api/_handler.js +++ /dev/null @@ -1,167931 +0,0 @@ -// Bundled by esbuild — see scripts/bundle-api.mjs -import { createRequire } from "module"; -const require = createRequire(import.meta.url); -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __typeError = (msg) => { - throw TypeError(msg); -}; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); -var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); -var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); -var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); -var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); -var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); -var __privateWrapper = (obj, member, setter, getter) => ({ - set _(value) { - __privateSet(obj, member, value, setter); - }, - get _() { - return __privateGet(obj, member, getter); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init2(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(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 _a30; - const inst = params?.Parent ? new Definition() : this; - init2(inst, def); - (_a30 = inst._zod).deferred ?? (_a30.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init2 }); - 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 NEVER, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig; -var init_core = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js"() { - NEVER = Object.freeze({ - status: "aborted" - }); - $brand = Symbol("zod_brand"); - $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } - }; - $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } - }; - globalConfig = {}; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js -var util_exports = {}; -__export(util_exports, { - BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, - Class: () => Class, - NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, - aborted: () => aborted, - allowsEval: () => allowsEval, - assert: () => assert2, - assertEqual: () => assertEqual, - assertIs: () => assertIs, - assertNever: () => assertNever, - assertNotEqual: () => assertNotEqual, - assignProp: () => assignProp, - base64ToUint8Array: () => base64ToUint8Array, - base64urlToUint8Array: () => base64urlToUint8Array, - cached: () => cached, - captureStackTrace: () => captureStackTrace, - cleanEnum: () => cleanEnum, - cleanRegex: () => cleanRegex, - clone: () => clone, - cloneDef: () => cloneDef, - createTransparentProxy: () => createTransparentProxy, - defineLazy: () => defineLazy, - esc: () => esc, - escapeRegex: () => escapeRegex, - extend: () => extend, - finalizeIssue: () => finalizeIssue, - floatSafeRemainder: () => floatSafeRemainder, - getElementAtPath: () => getElementAtPath, - getEnumValues: () => getEnumValues, - getLengthableOrigin: () => getLengthableOrigin, - getParsedType: () => getParsedType, - getSizableOrigin: () => getSizableOrigin, - hexToUint8Array: () => hexToUint8Array, - isObject: () => isObject2, - isPlainObject: () => isPlainObject, - issue: () => issue, - joinValues: () => joinValues, - jsonStringifyReplacer: () => jsonStringifyReplacer, - merge: () => merge, - mergeDefs: () => mergeDefs, - normalizeParams: () => normalizeParams, - nullish: () => nullish, - numKeys: () => numKeys, - objectClone: () => objectClone, - omit: () => omit, - optionalKeys: () => optionalKeys, - parsedType: () => parsedType, - partial: () => partial, - pick: () => pick, - prefixIssues: () => prefixIssues, - primitiveTypes: () => primitiveTypes, - promiseAllObject: () => promiseAllObject, - propertyKeyTypes: () => propertyKeyTypes, - randomString: () => randomString, - required: () => required, - safeExtend: () => safeExtend, - shallowClone: () => shallowClone, - slugify: () => slugify, - stringifyPrimitive: () => stringifyPrimitive, - uint8ArrayToBase64: () => uint8ArrayToBase64, - uint8ArrayToBase64url: () => uint8ArrayToBase64url, - uint8ArrayToHex: () => uint8ArrayToHex, - unwrapMessage: () => unwrapMessage -}); -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function assertIs(_arg) { -} -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert2(_) { -} -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(array2, separator = "|") { - return array2.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - } - }; -} -function nullish(input) { - return input === null || input === void 0; -} -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 stepString = step.toString(); - let stepDecCount = (stepString.split(".")[1] || "").length; - if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { - const match2 = stepString.match(/\d?e-(\d?)/); - if (match2?.[1]) { - stepDecCount = Number.parseInt(match2[1]); - } - } - 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(object2, key, getter) { - let value = void 0; - Object.defineProperty(object2, key, { - get() { - if (value === EVALUATING) { - return void 0; - } - if (value === void 0) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object2, key, { - value: v - // configurable: true, - }); - }, - configurable: true - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -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 cloneDef(schema3) { - return mergeDefs(schema3._zod.def); -} -function getElementAtPath(obj, path3) { - if (!path3) - return obj; - return path3.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); -} -function isObject2(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -function isPlainObject(o) { - if (isObject2(o) === false) - return false; - const ctor = o.constructor; - if (ctor === void 0) - return true; - if (typeof ctor !== "function") - return true; - const prot = ctor.prototype; - if (isObject2(prot) === false) - return false; - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -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(_params2) { - const params = _params2; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== void 0) { - if (params?.error !== void 0) - 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 createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - } - }); -} -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"; - }); -} -function pick(schema3, mask) { - const currDef = schema3._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema3._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(schema3, def); -} -function omit(schema3, mask) { - const currDef = schema3._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema3._zod.def, { - get shape() { - const newShape = { ...schema3._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(schema3, def); -} -function extend(schema3, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema3._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - const existingShape = schema3._zod.def.shape; - for (const key in shape) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema3._zod.def, { - get shape() { - const _shape = { ...schema3._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema3, def); -} -function safeExtend(schema3, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema3._zod.def, { - get shape() { - const _shape = { ...schema3._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema3, 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); - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: [] - // delete existing checks - }); - return clone(a, def); -} -function partial(Class2, schema3, mask) { - const currDef = schema3._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(schema3._zod.def, { - get shape() { - const oldShape = schema3._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] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema3, def); -} -function required(Class2, schema3, mask) { - const def = mergeDefs(schema3._zod.def, { - get shape() { - const oldShape = schema3._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 Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema3, def); -} -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -function prefixIssues(path3, issues) { - return issues.map((iss) => { - var _a30; - (_a30 = iss).path ?? (_a30.path = []); - iss.path.unshift(path3); - return iss; - }); -} -function unwrapMessage(message2) { - return typeof message2 === "string" ? message2 : message2?.message; -} -function finalizeIssue(iss, ctx, config4) { - const full = { ...iss, path: iss.path ?? [] }; - if (!iss.message) { - const message2 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config4.customError?.(iss)) ?? unwrapMessage(config4.localeError?.(iss)) ?? "Invalid input"; - full.message = message2; - } - delete full.inst; - delete full.continue; - if (!ctx?.reportInput) { - delete full.input; - } - return full; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - if (input instanceof File) - return "file"; - return "unknown"; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - 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") { - return { - message: iss, - code: "custom", - input, - inst - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj).filter(([k, _]) => { - return Number.isNaN(Number.parseInt(k, 10)); - }).map((el) => el[1]); -} -function base64ToUint8Array(base644) { - const binaryString = atob(base644); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url3) { - const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - base644.length % 4) % 4); - return base64ToUint8Array(base644 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex4) { - const cleanHex = hex4.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); -} -var EVALUATING, captureStackTrace, allowsEval, getParsedType, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class; -var init_util = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js"() { - EVALUATING = Symbol("evaluating"); - captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { - }; - allowsEval = cached(() => { - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } catch (_) { - return false; - } - }); - getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } - }; - propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); - primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); - NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-34028234663852886e22, 34028234663852886e22], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE] - }; - BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], - uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] - }; - Class = class { - constructor(..._args) { - } - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js -function flattenError(error49, mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error49.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(error49, mapper = (issue2) => issue2.message) { - const fieldErrors = { _errors: [] }; - const processError = (error50) => { - for (const issue2 of error50.issues) { - if (issue2.code === "invalid_union" && issue2.errors.length) { - issue2.errors.map((issues) => processError({ issues })); - } else if (issue2.code === "invalid_key") { - processError({ issues: issue2.issues }); - } else if (issue2.code === "invalid_element") { - processError({ issues: issue2.issues }); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(error49); - return fieldErrors; -} -function treeifyError(error49, mapper = (issue2) => issue2.message) { - const result = { errors: [] }; - const processError = (error50, path3 = []) => { - var _a30, _b2; - for (const issue2 of error50.issues) { - if (issue2.code === "invalid_union" && issue2.errors.length) { - issue2.errors.map((issues) => processError({ issues }, issue2.path)); - } else if (issue2.code === "invalid_key") { - processError({ issues: issue2.issues }, issue2.path); - } else if (issue2.code === "invalid_element") { - processError({ issues: issue2.issues }, issue2.path); - } else { - const fullpath = [...path3, ...issue2.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue2)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - (_a30 = curr.properties)[el] ?? (_a30[el] = { errors: [] }); - curr = curr.properties[el]; - } else { - curr.items ?? (curr.items = []); - (_b2 = curr.items)[el] ?? (_b2[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue2)); - } - i++; - } - } - } - }; - processError(error49); - return result; -} -function toDotPath(_path3) { - const segs = []; - const path3 = _path3.map((seg) => typeof seg === "object" ? seg.key : seg); - for (const seg of path3) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error49) { - const lines = []; - const issues = [...error49.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - for (const issue2 of issues) { - lines.push(`\u2716 ${issue2.message}`); - if (issue2.path?.length) - lines.push(` \u2192 at ${toDotPath(issue2.path)}`); - } - return lines.join("\n"); -} -var initializer, $ZodError, $ZodRealError; -var init_errors = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js"() { - init_core(); - init_util(); - 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 - }); - }; - $ZodError = $constructor("$ZodError", initializer); - $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js -var _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, encode, _decode, decode, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync; -var init_parse = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js"() { - init_core(); - init_errors(); - init_util(); - _parse = (_Err) => (schema3, value, _ctx, _params2) => { - const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; - const result = schema3._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params2?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params2?.callee); - throw e; - } - return result.value; - }; - parse = /* @__PURE__ */ _parse($ZodRealError); - _parseAsync = (_Err) => async (schema3, value, _ctx, params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema3._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; - }; - parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); - _safeParse = (_Err) => (schema3, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema3._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 = /* @__PURE__ */ _safeParse($ZodRealError); - _safeParseAsync = (_Err) => async (schema3, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema3._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 = /* @__PURE__ */ _safeParseAsync($ZodRealError); - _encode = (_Err) => (schema3, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parse(_Err)(schema3, value, ctx); - }; - encode = /* @__PURE__ */ _encode($ZodRealError); - _decode = (_Err) => (schema3, value, _ctx) => { - return _parse(_Err)(schema3, value, _ctx); - }; - decode = /* @__PURE__ */ _decode($ZodRealError); - _encodeAsync = (_Err) => async (schema3, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parseAsync(_Err)(schema3, value, ctx); - }; - encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); - _decodeAsync = (_Err) => async (schema3, value, _ctx) => { - return _parseAsync(_Err)(schema3, value, _ctx); - }; - decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); - _safeEncode = (_Err) => (schema3, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParse(_Err)(schema3, value, ctx); - }; - safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); - _safeDecode = (_Err) => (schema3, value, _ctx) => { - return _safeParse(_Err)(schema3, value, _ctx); - }; - safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); - _safeEncodeAsync = (_Err) => async (schema3, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParseAsync(_Err)(schema3, value, ctx); - }; - safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); - _safeDecodeAsync = (_Err) => async (schema3, value, _ctx) => { - return _safeParseAsync(_Err)(schema3, value, _ctx); - }; - safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js -var regexes_exports = {}; -__export(regexes_exports, { - base64: () => base64, - base64url: () => base64url, - bigint: () => bigint, - boolean: () => boolean, - browserEmail: () => browserEmail, - cidrv4: () => cidrv4, - cidrv6: () => cidrv6, - cuid: () => cuid, - cuid2: () => cuid2, - date: () => date, - datetime: () => datetime, - domain: () => domain, - duration: () => duration, - e164: () => e164, - email: () => email, - emoji: () => emoji, - extendedDuration: () => extendedDuration, - guid: () => guid, - hex: () => hex, - hostname: () => hostname, - html5Email: () => html5Email, - idnEmail: () => idnEmail, - integer: () => integer, - ipv4: () => ipv4, - ipv6: () => ipv6, - ksuid: () => ksuid, - lowercase: () => lowercase, - mac: () => mac, - md5_base64: () => md5_base64, - md5_base64url: () => md5_base64url, - md5_hex: () => md5_hex, - nanoid: () => nanoid, - null: () => _null, - number: () => number, - rfc5322Email: () => rfc5322Email, - sha1_base64: () => sha1_base64, - sha1_base64url: () => sha1_base64url, - sha1_hex: () => sha1_hex, - sha256_base64: () => sha256_base64, - sha256_base64url: () => sha256_base64url, - sha256_hex: () => sha256_hex, - sha384_base64: () => sha384_base64, - sha384_base64url: () => sha384_base64url, - sha384_hex: () => sha384_hex, - sha512_base64: () => sha512_base64, - sha512_base64url: () => sha512_base64url, - sha512_hex: () => sha512_hex, - string: () => string, - time: () => time, - ulid: () => ulid, - undefined: () => _undefined, - unicodeEmail: () => unicodeEmail, - uppercase: () => uppercase, - uuid: () => uuid, - uuid4: () => uuid4, - uuid6: () => uuid6, - uuid7: () => uuid7, - xid: () => xid -}); -function emoji() { - return new RegExp(_emoji, "u"); -} -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(args) { - return new RegExp(`^${timeSource(args)}$`); -} -function datetime(args) { - const time3 = 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 = `${time3}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url; -var init_regexes = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js"() { - init_util(); - cuid = /^[cC][^\s-]{8,}$/; - cuid2 = /^[0-9a-z]+$/; - ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; - 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)?)?)$/; - extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; - 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})$/; - uuid = (version3) => { - if (!version3) - 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}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); - }; - uuid4 = /* @__PURE__ */ uuid(4); - uuid6 = /* @__PURE__ */ uuid(6); - uuid7 = /* @__PURE__ */ uuid(7); - email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; - html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; - rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; - idnEmail = unicodeEmail; - browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; - _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; - 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}|:))$/; - mac = (delimiter) => { - const escapedDelim = escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); - }; - 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])$/; - base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; - base64url = /^[A-Za-z0-9_-]*$/; - hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; - domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; - e164 = /^\+[1-9]\d{6,14}$/; - 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 = /* @__PURE__ */ new RegExp(`^${dateSource}$`); - string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); - }; - bigint = /^-?\d+n?$/; - integer = /^-?\d+$/; - number = /^-?\d+(?:\.\d+)?$/; - boolean = /^(?:true|false)$/i; - _null = /^null$/i; - _undefined = /^undefined$/i; - lowercase = /^[^A-Z]*$/; - uppercase = /^[^a-z]*$/; - hex = /^[0-9a-fA-F]*$/; - md5_hex = /^[0-9a-fA-F]{32}$/; - md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); - md5_base64url = /* @__PURE__ */ fixedBase64url(22); - sha1_hex = /^[0-9a-fA-F]{40}$/; - sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); - sha1_base64url = /* @__PURE__ */ fixedBase64url(27); - sha256_hex = /^[0-9a-fA-F]{64}$/; - sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); - sha256_base64url = /* @__PURE__ */ fixedBase64url(43); - sha384_hex = /^[0-9a-fA-F]{96}$/; - sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); - sha384_base64url = /* @__PURE__ */ fixedBase64url(64); - sha512_hex = /^[0-9a-fA-F]{128}$/; - sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); - sha512_base64url = /* @__PURE__ */ fixedBase64url(86); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...prefixIssues(property, result.issues)); - } -} -var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite; -var init_checks = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js"() { - init_core(); - init_regexes(); - init_util(); - $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { - var _a30; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a30 = inst._zod).onattach ?? (_a30.onattach = []); - }); - numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date" - }; - $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._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: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._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: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a30; - (_a30 = inst2._zod.bag).multipleOf ?? (_a30.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 - }); - }; - }); - $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); - 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((inst2) => { - const bag = inst2._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)) { - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst - }); - return; - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort - }); - } else { - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - 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, - inclusive: true, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); - const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { - var _a30; - $ZodCheck.init(inst, def); - (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { - var _a30; - $ZodCheck.init(inst, def); - (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a30; - $ZodCheck.init(inst, def); - (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: getSizableOrigin(input), - ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a30; - $ZodCheck.init(inst, def); - (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._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 - }); - }; - }); - $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a30; - $ZodCheck.init(inst, def); - (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._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 - }); - }; - }); - $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a30; - $ZodCheck.init(inst, def); - (_a30 = inst._zod.def).when ?? (_a30.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._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 - }); - }; - }); - $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a30, _b2; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a30 = inst._zod).check ?? (_a30.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 - (_b2 = inst._zod).check ?? (_b2.check = () => { - }); - }); - $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 - }); - }; - }); - $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); - }); - $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); - }); - $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((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 - }); - }; - }); - $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((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 - }); - }; - }); - $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((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 - }); - }; - }); - $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [] - }, {}); - if (result instanceof Promise) { - return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; - }); - $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; - }); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js -var Doc; -var init_doc = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js"() { - Doc = class { - 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 line2 of dedented) { - this.content.push(line2); - } - } - compile() { - const F = Function; - const args = this?.args; - const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); - } - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js -var version; -var init_versions = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js"() { - version = { - major: 4, - minor: 3, - patch: 6 - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js -function isValidBase64(data) { - if (data === "") - return true; - if (data.length % 4 !== 0) - return false; - try { - atob(data); - return true; - } catch { - return false; - } -} -function isValidBase64URL(data) { - if (!base64url.test(data)) - return false; - const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); - const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "="); - return isValidBase64(padded); -} -function isValidJWT(token, algorithm2 = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm2 && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm2)) - return false; - return true; - } catch { - return false; - } -} -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handlePropertyResult(result, final, key, input, isOptionalOut) { - if (result.issues.length) { - if (isOptionalOut && !(key in input)) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (result.value === void 0) { - if (key in input) { - final.value[key] = void 0; - } - } else { - final.value[key] = result.value; - } -} -function normalizeDef(def) { - const keys = Object.keys(def.shape); - for (const k of keys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys) - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (keySet.has(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((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); - } else { - handlePropertyResult(r, payload, key, input, isOptionalOut); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - }); - return final; -} -function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; - return final; - } - if (successes.length === 0) { - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - }); - } else { - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false - }); - } - return final; -} -function mergeValues(a, b) { - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath] - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath] - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - const unrecKeys = /* @__PURE__ */ new Map(); - let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { - unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } - } else { - 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 { - 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 (aborted(result)) - return result; - const merged = mergeValues(left.value, right.value); - if (!merged.valid) { - throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, keyResult.issues)); - } else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }); - } - } - if (valueResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, valueResult.issues)); - } else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key, - issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -function handleOptionalResult(result, input) { - if (result.issues.length && input === void 0) { - return { issues: [], value: void 0 }; - } - return result; -} -function handleDefaultResult(payload, def) { - if (payload.value === void 0) { - payload.value = def.defaultValue; - } - return payload; -} -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === void 0) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst - }); - } - return payload; -} -function handlePipeResult(left, next, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); - return payload; -} -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, - // incorporates params.error into issue reporting - path: [...inst._zod.def.path ?? []], - // incorporates params.error into issue reporting - continue: !inst._zod.def.abort - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - 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, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom; -var init_schemas = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js"() { - init_checks(); - init_core(); - init_doc(); - init_parse(); - init_regexes(); - init_util(); - init_versions(); - init_util(); - $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { - var _a30; - 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); - } - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - (_a30 = inst._zod).deferred ?? (_a30.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } else { - const runChecks = (payload, checks2, ctx) => { - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks2) { - 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; - }; - const handleCanaryResult = (canary, payload, ctx) => { - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary2) => { - return handleCanaryResult(canary2, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result2) => runChecks(result2, checks, ctx)); - } - 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 - })); - }); - $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } catch (_2) { - } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; - }); - $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); - }); - $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); - }); - $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 = versionMap[def.version]; - if (v === void 0) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); - }); - $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); - }); - $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - const trimmed = payload.value.trim(); - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.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) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; - } - return; - } catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); - }); - $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); - $ZodStringFormat.init(inst, def); - }); - $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); - }); - $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); - }); - $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); - }); - $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); - }); - $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); - }); - $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - }); - $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date); - $ZodStringFormat.init(inst, def); - }); - $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time(def)); - $ZodStringFormat.init(inst, def); - }); - $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); - }); - $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; - }); - $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 { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; - }); - $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); - }); - $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 { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); - }); - $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } catch (_) { - } - const input = payload.value; - 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" : void 0 : void 0; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...received ? { received } : {} - }); - return payload; - }; - }); - $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); - }); - $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } catch (_) { - } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } catch (_) { - } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; - }); - $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { - $ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); - }); - $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _undefined; - inst._zod.values = /* @__PURE__ */ new Set([void 0]); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = /* @__PURE__ */ new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; - }); - $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; - }); - $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; - }); - $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } catch (_err) { - } - } - const input = payload.value; - const isDate3 = input instanceof Date; - const isValidDate2 = isDate3 && !Number.isNaN(input.getTime()); - if (isValidDate2) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...isDate3 ? { received: "Invalid Date" } : {}, - inst - }); - return payload; - }; - }); - $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst - }); - return payload; - } - payload.value = Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); - } else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; - }); - $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 _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); - for (const v of field.values) - propValues[key].add(v); - } - } - return propValues; - }); - const isObject5 = isObject2; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject5(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - payload.value = {}; - const proms = []; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); - } else { - handlePropertyResult(r, payload, key, input, isOptionalOut); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; - }); - $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = cached(() => normalizeDef(def)); - 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)`; - }; - doc.write(`const input = payload.value;`); - const ids = /* @__PURE__ */ Object.create(null); - let counter = 0; - for (const key of normalized.keys) { - ids[key] = `key_${counter++}`; - } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { - const id = ids[key]; - const k = esc(key); - const schema3 = shape[key]; - const isOptionalOut = schema3?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); - if (isOptionalOut) { - 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}] - }))); - } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - 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 { - newResult[${k}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); - }; - let fastpass; - const isObject5 = isObject2; - const jit = !globalConfig.jitless; - const allowsEval2 = allowsEval; - const fastEnabled = jit && allowsEval2.value; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject5(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - 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" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - } - return void 0; - }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return void 0; - }); - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload, ctx) => { - if (single) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [] - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results2) => { - return handleUnionResults(results2, payload, inst, ctx); - }); - }; - }); - $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload, ctx) => { - if (single) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [] - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results2) => { - return handleExclusiveUnionResults(results2, payload, inst, ctx); - }); - }; - }); - $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of 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)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - const disc = cached(() => { - const opts = def.options; - const map3 = /* @__PURE__ */ 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 (map3.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map3.set(v, o); - } - } - return map3; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - if (def.unionFallback) { - return _super(payload, ctx); - } - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - input, - path: [def.discriminator], - inst - }); - return payload; - }; - }); - $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left2, right2]) => { - return handleIntersectionResults(payload, left2, right2); - }); - } - return handleIntersectionResults(payload, left, right); - }; - }); - $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type" - }); - return payload; - } - payload.value = []; - const proms = []; - const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); - const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; - if (!def.rest) { - const tooBig = input.length > items.length; - const tooSmall = input.length < optStart - 1; - if (tooBig || tooSmall) { - payload.issues.push({ - ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length }, - input, - inst, - origin: "array" - }); - return payload; - } - } - let i = -1; - for (const item of items) { - i++; - if (i >= input.length) { - if (i >= optStart) - continue; - } - const result = item._zod.run({ - value: input[i], - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); - } else { - handleTupleResult(result, payload, i); - } - } - if (def.rest) { - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ - value: el, - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); - } else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; - }); - $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values) { - payload.value = {}; - const recordKeys = /* @__PURE__ */ 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); - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload.issues.push(...prefixIssues(key, result2.issues)); - } - payload.value[key] = result2.value; - })); - } else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized - }); - } - } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - payload.value[key] = input[key]; - } else { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - } - continue; - } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload.issues.push(...prefixIssues(key, result2.issues)); - } - payload.value[keyResult.value] = result2.value; - })); - } else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; - }); - $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst - }); - return payload; - } - const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); - })); - } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; - }); - $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type" - }); - return payload; - } - const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleSetResult(result2, payload))); - } else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; - }); - $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(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("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst - }); - return payload; - }; - }); - $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("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst - }); - return payload; - }; - }); - $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; - }); - $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, payload.value)); - return handleOptionalResult(result, payload.value); - } - if (payload.value === void 0) { - return payload; - } - 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); - 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; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - if (payload.value === void 0) { - payload.value = def.defaultValue; - return payload; - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleDefaultResult(result2, def)); - } - return handleDefaultResult(result, def); - }; - }); - $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - if (payload.value === void 0) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleNonOptionalResult(result2, inst)); - } - return handleNonOptionalResult(result, inst); - }; - }); - $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; - }); - $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (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, "values", () => 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); - if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - } - 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 = []; - } - return payload; - }; - }); - $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type" - }); - return payload; - } - return payload; - }; - }); - $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); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right2) => handlePipeResult(right2, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left2) => handlePipeResult(left2, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; - }); - $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (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); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left2) => handleCodecAResult(left2, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right2) => handleCodecAResult(right2, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; - }); - $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); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; - }); - $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } else if (part === null || primitiveTypes.has(typeof part)) { - regexParts.push(escapeRegex(`${part}`)); - } else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "string", - code: "invalid_type" - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source - }); - return payload; - } - return payload; - }; - }); - $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - inst._def = def; - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - return function(...args) { - const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse(inst._def.output, result); - } - return result; - }; - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return async function(...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }; - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst - }); - return payload; - } - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1] - }), - output: inst._def.output - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output - }); - }; - return inst; - }); - $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; - }); - $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "innerType", () => def.getter()); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; - }); - $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; - }); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js -function ar_default() { - return { - localeError: error() - }; -} -var error; -var init_ar = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"() { - init_util(); - error = () => { - const Sizable = { - string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0645\u062F\u062E\u0644", - email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", - url: "\u0631\u0627\u0628\u0637", - emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", - date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", - time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", - duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", - ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", - ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", - cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", - cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", - base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", - base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", - json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", - e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", - jwt: "JWT", - template_literal: "\u0645\u062F\u062E\u0644" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; - } - return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; - return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; - return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; - if (_issue.format === "ends_with") - return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; - } - case "not_multiple_of": - return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; - case "unrecognized_keys": - return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; - case "invalid_key": - return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; - case "invalid_union": - return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; - case "invalid_element": - return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; - default: - return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js -function az_default() { - return { - localeError: error2() - }; -} -var error2; -var init_az = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"() { - init_util(); - error2 = () => { - const Sizable = { - string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, - file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, - array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } - }; - 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", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; - } - return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; - return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; - return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; - if (_issue.format === "ends_with") - return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; - if (_issue.format === "includes") - return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; - if (_issue.format === "regex") - return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; - return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; - case "unrecognized_keys": - return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; - case "invalid_union": - return "Yanl\u0131\u015F d\u0259y\u0259r"; - case "invalid_element": - return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; - default: - return `Yanl\u0131\u015F d\u0259y\u0259r`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js -function getBelarusianPlural(count, one, few, many) { - const absCount = Math.abs(count); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -function be_default() { - return { - localeError: error3() - }; -} -var error3; -var init_be = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"() { - init_util(); - error3 = () => { - const Sizable = { - string: { - unit: { - one: "\u0441\u0456\u043C\u0432\u0430\u043B", - few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", - many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" - }, - verb: "\u043C\u0435\u0446\u044C" - }, - array: { - unit: { - one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", - few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", - many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" - }, - verb: "\u043C\u0435\u0446\u044C" - }, - set: { - unit: { - one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", - few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", - many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" - }, - verb: "\u043C\u0435\u0446\u044C" - }, - file: { - unit: { - one: "\u0431\u0430\u0439\u0442", - few: "\u0431\u0430\u0439\u0442\u044B", - many: "\u0431\u0430\u0439\u0442\u0430\u045E" - }, - verb: "\u043C\u0435\u0446\u044C" - } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0443\u0432\u043E\u0434", - email: "email \u0430\u0434\u0440\u0430\u0441", - url: "URL", - emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", - date: "ISO \u0434\u0430\u0442\u0430", - time: "ISO \u0447\u0430\u0441", - duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", - ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", - ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", - cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", - cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", - base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", - base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", - json_string: "JSON \u0440\u0430\u0434\u043E\u043A", - e164: "\u043D\u0443\u043C\u0430\u0440 E.164", - jwt: "JWT", - template_literal: "\u0443\u0432\u043E\u0434" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u043B\u0456\u043A", - array: "\u043C\u0430\u0441\u0456\u045E" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; - } - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const maxValue = Number(issue2.maximum); - const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; - } - return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const minValue = Number(issue2.minimum); - const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; - } - return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; - case "unrecognized_keys": - return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; - case "invalid_union": - return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; - case "invalid_element": - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; - default: - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js -function bg_default() { - return { - localeError: error4() - }; -} -var error4; -var init_bg = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"() { - init_util(); - error4 = () => { - const Sizable = { - string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0432\u0445\u043E\u0434", - email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", - url: "URL", - emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0432\u0440\u0435\u043C\u0435", - date: "ISO \u0434\u0430\u0442\u0430", - time: "ISO \u0432\u0440\u0435\u043C\u0435", - duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", - ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", - ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", - cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", - cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", - base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", - base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", - json_string: "JSON \u043D\u0438\u0437", - e164: "E.164 \u043D\u043E\u043C\u0435\u0440", - jwt: "JWT", - template_literal: "\u0432\u0445\u043E\u0434" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0447\u0438\u0441\u043B\u043E", - array: "\u043C\u0430\u0441\u0438\u0432" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; - } - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; - return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; - let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; - if (_issue.format === "emoji") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; - if (_issue.format === "datetime") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; - if (_issue.format === "date") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; - if (_issue.format === "time") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; - if (_issue.format === "duration") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; - return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; - case "unrecognized_keys": - return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; - case "invalid_union": - return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; - case "invalid_element": - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; - default: - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js -function ca_default() { - return { - localeError: error5() - }; -} -var error5; -var init_ca = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"() { - init_util(); - error5 = () => { - const Sizable = { - string: { unit: "car\xE0cters", verb: "contenir" }, - file: { unit: "bytes", verb: "contenir" }, - array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entrada", - email: "adre\xE7a electr\xF2nica", - 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: "data i hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "durada ISO", - ipv4: "adre\xE7a IPv4", - ipv6: "adre\xE7a IPv6", - cidrv4: "rang IPv4", - cidrv6: "rang IPv6", - base64: "cadena codificada en base64", - base64url: "cadena codificada en base64url", - json_string: "cadena JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; - } - return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; - return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; - case "too_big": { - const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; - return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; - case "unrecognized_keys": - return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Clau inv\xE0lida a ${issue2.origin}`; - case "invalid_union": - return "Entrada inv\xE0lida"; - // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general - case "invalid_element": - return `Element inv\xE0lid a ${issue2.origin}`; - default: - return `Entrada inv\xE0lida`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js -function cs_default() { - return { - localeError: error6() - }; -} -var error6; -var init_cs = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"() { - init_util(); - error6 = () => { - const Sizable = { - string: { unit: "znak\u016F", verb: "m\xEDt" }, - file: { unit: "bajt\u016F", verb: "m\xEDt" }, - array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "regul\xE1rn\xED v\xFDraz", - email: "e-mailov\xE1 adresa", - 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: "datum a \u010Das ve form\xE1tu ISO", - date: "datum ve form\xE1tu ISO", - time: "\u010Das ve form\xE1tu ISO", - duration: "doba trv\xE1n\xED ISO", - ipv4: "IPv4 adresa", - ipv6: "IPv6 adresa", - cidrv4: "rozsah IPv4", - cidrv6: "rozsah IPv6", - base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", - base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", - json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", - e164: "\u010D\xEDslo E.164", - jwt: "JWT", - template_literal: "vstup" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u010D\xEDslo", - string: "\u0159et\u011Bzec", - function: "funkce", - array: "pole" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; - } - return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; - return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; - } - return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; - } - return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; - return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; - case "unrecognized_keys": - return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; - case "invalid_union": - return "Neplatn\xFD vstup"; - case "invalid_element": - return `Neplatn\xE1 hodnota v ${issue2.origin}`; - default: - return `Neplatn\xFD vstup`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js -function da_default() { - return { - localeError: error7() - }; -} -var error7; -var init_da = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"() { - init_util(); - error7 = () => { - const Sizable = { - string: { unit: "tegn", verb: "havde" }, - file: { unit: "bytes", verb: "havde" }, - array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "e-mailadresse", - 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 dato- og klokkesl\xE6t", - date: "ISO-dato", - time: "ISO-klokkesl\xE6t", - duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodet streng", - base64url: "base64url-kodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - string: "streng", - number: "tal", - boolean: "boolean", - array: "liste", - object: "objekt", - set: "s\xE6t", - file: "fil" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; - } - return `Ugyldigt input: forventede ${expected}, fik ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; - return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - if (sizing) - return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - if (sizing) { - return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Ugyldig streng: skal starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: skal ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: skal indeholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; - return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ugyldig n\xF8gle i ${issue2.origin}`; - case "invalid_union": - return "Ugyldigt input: matcher ingen af de tilladte typer"; - case "invalid_element": - return `Ugyldig v\xE6rdi i ${issue2.origin}`; - default: - return `Ugyldigt input`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js -function de_default() { - return { - localeError: error8() - }; -} -var error8; -var init_de = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"() { - init_util(); - error8 = () => { - const Sizable = { - string: { unit: "Zeichen", verb: "zu haben" }, - file: { unit: "Bytes", verb: "zu haben" }, - array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "Eingabe", - email: "E-Mail-Adresse", - 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-Datum und -Uhrzeit", - date: "ISO-Datum", - time: "ISO-Uhrzeit", - duration: "ISO-Dauer", - ipv4: "IPv4-Adresse", - ipv6: "IPv6-Adresse", - cidrv4: "IPv4-Bereich", - cidrv6: "IPv6-Bereich", - base64: "Base64-codierter String", - base64url: "Base64-URL-codierter String", - json_string: "JSON-String", - e164: "E.164-Nummer", - jwt: "JWT", - template_literal: "Eingabe" - }; - const TypeDictionary = { - nan: "NaN", - number: "Zahl", - array: "Array" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; - } - return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; - return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; - return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; - } - return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; - if (_issue.format === "ends_with") - return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; - if (_issue.format === "includes") - return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; - if (_issue.format === "regex") - return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; - return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; - case "invalid_union": - return "Ung\xFCltige Eingabe"; - case "invalid_element": - return `Ung\xFCltiger Wert in ${issue2.origin}`; - default: - return `Ung\xFCltige Eingabe`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js -function en_default() { - return { - localeError: error9() - }; -} -var error9; -var init_en = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"() { - init_util(); - error9 = () => { - 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", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN" - // All other type names omitted - they fall back to raw values via ?? operator - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - 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] ?? issue2.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue2.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue2.origin}`; - case "invalid_union": - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue2.origin}`; - default: - return `Invalid input`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js -function eo_default() { - return { - localeError: error10() - }; -} -var error10; -var init_eo = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"() { - init_util(); - error10 = () => { - const Sizable = { - string: { unit: "karaktrojn", verb: "havi" }, - file: { unit: "bajtojn", verb: "havi" }, - array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "enigo", - email: "retadreso", - url: "URL", - emoji: "emo\u011Dio", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datotempo", - date: "ISO-dato", - time: "ISO-tempo", - duration: "ISO-da\u016Dro", - ipv4: "IPv4-adreso", - ipv6: "IPv6-adreso", - cidrv4: "IPv4-rango", - cidrv6: "IPv6-rango", - base64: "64-ume kodita karaktraro", - base64url: "URL-64-ume kodita karaktraro", - json_string: "JSON-karaktraro", - e164: "E.164-nombro", - jwt: "JWT", - template_literal: "enigo" - }; - const TypeDictionary = { - nan: "NaN", - number: "nombro", - array: "tabelo", - null: "senvalora" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; - } - return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; - return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; - return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; - return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Nevalida \u015Dlosilo en ${issue2.origin}`; - case "invalid_union": - return "Nevalida enigo"; - case "invalid_element": - return `Nevalida valoro en ${issue2.origin}`; - default: - return `Nevalida enigo`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js -function es_default() { - return { - localeError: error11() - }; -} -var error11; -var init_es = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"() { - init_util(); - error11 = () => { - const Sizable = { - string: { unit: "caracteres", verb: "tener" }, - file: { unit: "bytes", verb: "tener" }, - array: { unit: "elementos", verb: "tener" }, - set: { unit: "elementos", verb: "tener" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entrada", - email: "direcci\xF3n de correo electr\xF3nico", - 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: "fecha y hora ISO", - date: "fecha ISO", - time: "hora ISO", - duration: "duraci\xF3n ISO", - ipv4: "direcci\xF3n IPv4", - ipv6: "direcci\xF3n IPv6", - cidrv4: "rango IPv4", - cidrv6: "rango IPv6", - base64: "cadena codificada en base64", - base64url: "URL codificada en base64", - json_string: "cadena JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" - }; - const TypeDictionary = { - nan: "NaN", - string: "texto", - number: "n\xFAmero", - boolean: "booleano", - array: "arreglo", - object: "objeto", - set: "conjunto", - file: "archivo", - date: "fecha", - bigint: "n\xFAmero grande", - symbol: "s\xEDmbolo", - undefined: "indefinido", - null: "nulo", - function: "funci\xF3n", - map: "mapa", - record: "registro", - tuple: "tupla", - enum: "enumeraci\xF3n", - union: "uni\xF3n", - literal: "literal", - promise: "promesa", - void: "vac\xEDo", - never: "nunca", - unknown: "desconocido", - any: "cualquiera" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; - } - return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; - return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - if (sizing) - return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - if (sizing) { - return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; - return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; - case "invalid_union": - return "Entrada inv\xE1lida"; - case "invalid_element": - return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; - default: - return `Entrada inv\xE1lida`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js -function fa_default() { - return { - localeError: error12() - }; -} -var error12; -var init_fa = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"() { - init_util(); - error12 = () => { - const Sizable = { - string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0648\u0631\u0648\u062F\u06CC", - email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", - url: "URL", - emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", - date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", - time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", - duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", - ipv4: "IPv4 \u0622\u062F\u0631\u0633", - ipv6: "IPv6 \u0622\u062F\u0631\u0633", - cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", - cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", - base64: "base64-encoded \u0631\u0634\u062A\u0647", - base64url: "base64url-encoded \u0631\u0634\u062A\u0647", - json_string: "JSON \u0631\u0634\u062A\u0647", - e164: "E.164 \u0639\u062F\u062F", - jwt: "JWT", - template_literal: "\u0648\u0631\u0648\u062F\u06CC" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0639\u062F\u062F", - array: "\u0622\u0631\u0627\u06CC\u0647" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; - } - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; - } - case "invalid_value": - if (issue2.values.length === 1) { - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; - } - return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; - } - return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; - } - return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; - } - if (_issue.format === "ends_with") { - return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; - } - if (_issue.format === "includes") { - return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; - } - if (_issue.format === "regex") { - return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; - } - return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; - } - case "not_multiple_of": - return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; - case "unrecognized_keys": - return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; - case "invalid_union": - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; - case "invalid_element": - return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; - default: - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js -function fi_default() { - return { - localeError: error13() - }; -} -var error13; -var init_fi = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"() { - init_util(); - error13 = () => { - const Sizable = { - string: { unit: "merkki\xE4", subject: "merkkijonon" }, - file: { unit: "tavua", subject: "tiedoston" }, - array: { unit: "alkiota", subject: "listan" }, - set: { unit: "alkiota", subject: "joukon" }, - number: { unit: "", subject: "luvun" }, - bigint: { unit: "", subject: "suuren kokonaisluvun" }, - int: { unit: "", subject: "kokonaisluvun" }, - date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "s\xE4\xE4nn\xF6llinen lauseke", - email: "s\xE4hk\xF6postiosoite", - url: "URL-osoite", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-aikaleima", - date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", - time: "ISO-aika", - duration: "ISO-kesto", - ipv4: "IPv4-osoite", - ipv6: "IPv6-osoite", - cidrv4: "IPv4-alue", - cidrv6: "IPv6-alue", - base64: "base64-koodattu merkkijono", - base64url: "base64url-koodattu merkkijono", - json_string: "JSON-merkkijono", - e164: "E.164-luku", - jwt: "JWT", - template_literal: "templaattimerkkijono" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; - } - return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; - return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); - } - return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); - } - return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; - if (_issue.format === "regex") { - return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; - } - return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return "Virheellinen avain tietueessa"; - case "invalid_union": - return "Virheellinen unioni"; - case "invalid_element": - return "Virheellinen arvo joukossa"; - default: - return `Virheellinen sy\xF6te`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js -function fr_default() { - return { - localeError: error14() - }; -} -var error14; -var init_fr = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"() { - init_util(); - error14 = () => { - const Sizable = { - string: { unit: "caract\xE8res", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entr\xE9e", - email: "adresse e-mail", - 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: "date et heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "dur\xE9e ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", - jwt: "JWT", - template_literal: "entr\xE9e" - }; - const TypeDictionary = { - nan: "NaN", - number: "nombre", - array: "tableau" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; - } - return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; - return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; - return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; - } - case "not_multiple_of": - return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; - case "unrecognized_keys": - return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Cl\xE9 invalide dans ${issue2.origin}`; - case "invalid_union": - return "Entr\xE9e invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue2.origin}`; - default: - return `Entr\xE9e invalide`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js -function fr_CA_default() { - return { - localeError: error15() - }; -} -var error15; -var init_fr_CA = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"() { - init_util(); - error15 = () => { - const Sizable = { - string: { unit: "caract\xE8res", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entr\xE9e", - email: "adresse courriel", - 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: "date-heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "dur\xE9e ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", - jwt: "JWT", - template_literal: "entr\xE9e" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; - } - return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; - return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "\u2264" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; - return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? "\u2265" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; - } - case "not_multiple_of": - return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; - case "unrecognized_keys": - return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Cl\xE9 invalide dans ${issue2.origin}`; - case "invalid_union": - return "Entr\xE9e invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue2.origin}`; - default: - return `Entr\xE9e invalide`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js -function he_default() { - return { - localeError: error16() - }; -} -var error16; -var init_he = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"() { - init_util(); - error16 = () => { - const TypeNames = { - string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, - number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, - boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, - bigint: { label: "BigInt", gender: "m" }, - date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, - array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, - object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, - null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, - undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, - symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, - function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, - map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, - set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, - file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, - promise: { label: "Promise", gender: "m" }, - NaN: { label: "NaN", gender: "m" }, - unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, - value: { label: "\u05E2\u05E8\u05DA", gender: "m" } - }; - const Sizable = { - string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, - file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, - array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, - set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, - number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } - // no unit - }; - const typeEntry = (t) => t ? TypeNames[t] : void 0; - const typeLabel = (t) => { - const e = typeEntry(t); - if (e) - return e.label; - return t ?? TypeNames.unknown.label; - }; - const withDefinite = (t) => `\u05D4${typeLabel(t)}`; - const verbFor = (t) => { - const e = typeEntry(t); - const gender = e?.gender ?? "m"; - return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; - }; - const getSizing = (origin) => { - if (!origin) - return null; - return Sizable[origin] ?? null; - }; - const FormatDictionary = { - regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, - url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, - emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, - uuid: { label: "UUID", gender: "m" }, - nanoid: { label: "nanoid", gender: "m" }, - guid: { label: "GUID", gender: "m" }, - cuid: { label: "cuid", gender: "m" }, - cuid2: { label: "cuid2", gender: "m" }, - ulid: { label: "ULID", gender: "m" }, - xid: { label: "XID", gender: "m" }, - ksuid: { label: "KSUID", gender: "m" }, - datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, - date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, - time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, - duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, - ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, - ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, - cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, - cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, - base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, - base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, - json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, - e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, - jwt: { label: "JWT", gender: "m" }, - ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expectedKey = issue2.expected; - const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; - } - return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; - } - case "invalid_value": { - if (issue2.values.length === 1) { - return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; - } - const stringified = issue2.values.map((v) => stringifyPrimitive(v)); - if (issue2.values.length === 2) { - return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; - } - const lastValue = stringified[stringified.length - 1]; - const restValues = stringified.slice(0, -1).join(", "); - return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; - } - case "too_big": { - const sizing = getSizing(issue2.origin); - const subject = withDefinite(issue2.origin ?? "value"); - if (issue2.origin === "string") { - return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); - } - if (issue2.origin === "number") { - const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; - return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; - } - if (issue2.origin === "array" || issue2.origin === "set") { - const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; - const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`; - return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); - } - const adj = issue2.inclusive ? "<=" : "<"; - const be = verbFor(issue2.origin ?? "value"); - if (sizing?.unit) { - return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; - } - return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const sizing = getSizing(issue2.origin); - const subject = withDefinite(issue2.origin ?? "value"); - if (issue2.origin === "string") { - return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); - } - if (issue2.origin === "number") { - const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; - return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; - } - if (issue2.origin === "array" || issue2.origin === "set") { - const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; - if (issue2.minimum === 1 && issue2.inclusive) { - const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; - return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; - } - const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`; - return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); - } - const adj = issue2.inclusive ? ">=" : ">"; - const be = verbFor(issue2.origin ?? "value"); - if (sizing?.unit) { - return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; - const nounEntry = FormatDictionary[_issue.format]; - const noun = nounEntry?.label ?? _issue.format; - const gender = nounEntry?.gender ?? "m"; - const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; - return `${noun} \u05DC\u05D0 ${adjective}`; - } - case "not_multiple_of": - return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; - case "unrecognized_keys": - return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": { - return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; - } - case "invalid_union": - return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; - case "invalid_element": { - const place = withDefinite(issue2.origin ?? "array"); - return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; - } - default: - return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js -function hu_default() { - return { - localeError: error17() - }; -} -var error17; -var init_hu = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"() { - init_util(); - error17 = () => { - const Sizable = { - string: { unit: "karakter", verb: "legyen" }, - file: { unit: "byte", verb: "legyen" }, - array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "bemenet", - email: "email c\xEDm", - 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 id\u0151b\xE9lyeg", - date: "ISO d\xE1tum", - time: "ISO id\u0151", - duration: "ISO id\u0151intervallum", - ipv4: "IPv4 c\xEDm", - ipv6: "IPv6 c\xEDm", - cidrv4: "IPv4 tartom\xE1ny", - cidrv6: "IPv6 tartom\xE1ny", - base64: "base64-k\xF3dolt string", - base64url: "base64url-k\xF3dolt string", - json_string: "JSON string", - e164: "E.164 sz\xE1m", - jwt: "JWT", - template_literal: "bemenet" - }; - const TypeDictionary = { - nan: "NaN", - number: "sz\xE1m", - array: "t\xF6mb" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; - } - return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; - return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; - return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; - if (_issue.format === "ends_with") - return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; - if (_issue.format === "includes") - return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; - if (_issue.format === "regex") - return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; - return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; - case "unrecognized_keys": - return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; - case "invalid_union": - return "\xC9rv\xE9nytelen bemenet"; - case "invalid_element": - return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; - default: - return `\xC9rv\xE9nytelen bemenet`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js -function getArmenianPlural(count, one, many) { - return Math.abs(count) === 1 ? one : many; -} -function withDefiniteArticle(word) { - if (!word) - return ""; - const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; - const lastChar = word[word.length - 1]; - return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); -} -function hy_default() { - return { - localeError: error18() - }; -} -var error18; -var init_hy = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"() { - init_util(); - error18 = () => { - const Sizable = { - string: { - unit: { - one: "\u0576\u0577\u0561\u0576", - many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" - }, - verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" - }, - file: { - unit: { - one: "\u0562\u0561\u0575\u0569", - many: "\u0562\u0561\u0575\u0569\u0565\u0580" - }, - verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" - }, - array: { - unit: { - one: "\u057F\u0561\u0580\u0580", - many: "\u057F\u0561\u0580\u0580\u0565\u0580" - }, - verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" - }, - set: { - unit: { - one: "\u057F\u0561\u0580\u0580", - many: "\u057F\u0561\u0580\u0580\u0565\u0580" - }, - verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" - } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0574\u0578\u0582\u057F\u0584", - email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", - url: "URL", - emoji: "\u0567\u0574\u0578\u057B\u056B", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", - date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", - time: "ISO \u056A\u0561\u0574", - duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", - ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", - ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", - cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", - cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", - base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", - base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", - json_string: "JSON \u057F\u0578\u0572", - e164: "E.164 \u0570\u0561\u0574\u0561\u0580", - jwt: "JWT", - template_literal: "\u0574\u0578\u0582\u057F\u0584" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0569\u056B\u057E", - array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; - } - return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; - return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const maxValue = Number(issue2.maximum); - const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); - return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; - } - return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const minValue = Number(issue2.minimum); - const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); - return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; - } - return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; - if (_issue.format === "ends_with") - return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; - if (_issue.format === "includes") - return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; - return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; - case "unrecognized_keys": - return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; - case "invalid_union": - return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; - case "invalid_element": - return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; - default: - return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js -function id_default() { - return { - localeError: error19() - }; -} -var error19; -var init_id = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"() { - init_util(); - error19 = () => { - const Sizable = { - string: { unit: "karakter", verb: "memiliki" }, - file: { unit: "byte", verb: "memiliki" }, - array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "alamat email", - 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: "tanggal dan waktu format ISO", - date: "tanggal format ISO", - time: "jam format ISO", - duration: "durasi format ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "rentang alamat IPv4", - cidrv6: "rentang alamat IPv6", - base64: "string dengan enkode base64", - base64url: "string dengan enkode base64url", - json_string: "string JSON", - e164: "angka E.164", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; - } - return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; - return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak valid: harus menyertakan "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak valid: harus sesuai pola ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`; - } - case "not_multiple_of": - return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak valid di ${issue2.origin}`; - case "invalid_union": - return "Input tidak valid"; - case "invalid_element": - return `Nilai tidak valid di ${issue2.origin}`; - default: - return `Input tidak valid`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js -function is_default() { - return { - localeError: error20() - }; -} -var error20; -var init_is = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"() { - init_util(); - error20 = () => { - const Sizable = { - string: { unit: "stafi", verb: "a\xF0 hafa" }, - file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, - array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "gildi", - email: "netfang", - url: "vefsl\xF3\xF0", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dagsetning og t\xEDmi", - date: "ISO dagsetning", - time: "ISO t\xEDmi", - duration: "ISO t\xEDmalengd", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded strengur", - base64url: "base64url-encoded strengur", - json_string: "JSON strengur", - e164: "E.164 t\xF6lugildi", - jwt: "JWT", - template_literal: "gildi" - }; - const TypeDictionary = { - nan: "NaN", - number: "n\xFAmer", - array: "fylki" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; - } - return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; - return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`; - return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; - if (_issue.format === "regex") - return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; - return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; - case "unrecognized_keys": - return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Rangur lykill \xED ${issue2.origin}`; - case "invalid_union": - return "Rangt gildi"; - case "invalid_element": - return `Rangt gildi \xED ${issue2.origin}`; - default: - return `Rangt gildi`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js -function it_default() { - return { - localeError: error21() - }; -} -var error21; -var init_it = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"() { - init_util(); - error21 = () => { - const Sizable = { - string: { unit: "caratteri", verb: "avere" }, - file: { unit: "byte", verb: "avere" }, - array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "indirizzo email", - 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: "data e ora ISO", - date: "data ISO", - time: "ora ISO", - duration: "durata ISO", - ipv4: "indirizzo IPv4", - ipv6: "indirizzo IPv6", - cidrv4: "intervallo IPv4", - cidrv6: "intervallo IPv6", - base64: "stringa codificata in base64", - base64url: "URL codificata in base64", - json_string: "stringa JSON", - e164: "numero E.164", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - number: "numero", - array: "vettore" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; - } - return `Input non valido: atteso ${expected}, ricevuto ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; - return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; - return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Stringa non valida: deve terminare con "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Stringa non valida: deve includere "${_issue.includes}"`; - if (_issue.format === "regex") - return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; - case "unrecognized_keys": - return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Chiave non valida in ${issue2.origin}`; - case "invalid_union": - return "Input non valido"; - case "invalid_element": - return `Valore non valido in ${issue2.origin}`; - default: - return `Input non valido`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js -function ja_default() { - return { - localeError: error22() - }; -} -var error22; -var init_ja = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"() { - init_util(); - error22 = () => { - const Sizable = { - string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, - file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, - array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u5165\u529B\u5024", - email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", - url: "URL", - emoji: "\u7D75\u6587\u5B57", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO\u65E5\u6642", - date: "ISO\u65E5\u4ED8", - time: "ISO\u6642\u523B", - duration: "ISO\u671F\u9593", - ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", - ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", - cidrv4: "IPv4\u7BC4\u56F2", - cidrv6: "IPv6\u7BC4\u56F2", - base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", - base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", - json_string: "JSON\u6587\u5B57\u5217", - e164: "E.164\u756A\u53F7", - jwt: "JWT", - template_literal: "\u5165\u529B\u5024" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u6570\u5024", - array: "\u914D\u5217" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; - } - return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; - return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - case "too_big": { - const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - } - case "too_small": { - const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - if (_issue.format === "ends_with") - return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - if (_issue.format === "includes") - return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - if (_issue.format === "regex") - return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - case "unrecognized_keys": - return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; - case "invalid_key": - return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; - case "invalid_union": - return "\u7121\u52B9\u306A\u5165\u529B"; - case "invalid_element": - return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; - default: - return `\u7121\u52B9\u306A\u5165\u529B`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js -function ka_default() { - return { - localeError: error23() - }; -} -var error23; -var init_ka = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"() { - init_util(); - error23 = () => { - const Sizable = { - string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", - email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", - url: "URL", - emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", - date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", - time: "\u10D3\u10E0\u10DD", - duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", - ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", - ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", - cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", - cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", - base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", - base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", - json_string: "JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", - e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", - jwt: "JWT", - template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", - string: "\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", - boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", - function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", - array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; - } - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; - return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; - } - if (_issue.format === "ends_with") - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; - if (_issue.format === "includes") - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; - if (_issue.format === "regex") - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; - case "unrecognized_keys": - return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; - case "invalid_union": - return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; - case "invalid_element": - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; - default: - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js -function km_default() { - return { - localeError: error24() - }; -} -var error24; -var init_km = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"() { - init_util(); - error24 = () => { - const Sizable = { - string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", - email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", - url: "URL", - emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", - date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", - time: "\u1798\u17C9\u17C4\u1784 ISO", - duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", - ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", - ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", - cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", - cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", - base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", - base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", - json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", - e164: "\u179B\u17C1\u1781 E.164", - jwt: "JWT", - template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u179B\u17C1\u1781", - array: "\u17A2\u17B6\u179A\u17C1 (Array)", - null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; - } - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; - return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; - return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; - return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; - case "unrecognized_keys": - return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; - case "invalid_union": - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; - case "invalid_element": - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; - default: - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js -function kh_default() { - return km_default(); -} -var init_kh = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js"() { - init_km(); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js -function ko_default() { - return { - localeError: error25() - }; -} -var error25; -var init_ko = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"() { - init_util(); - error25 = () => { - const Sizable = { - string: { unit: "\uBB38\uC790", verb: "to have" }, - file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, - array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\uC785\uB825", - email: "\uC774\uBA54\uC77C \uC8FC\uC18C", - url: "URL", - emoji: "\uC774\uBAA8\uC9C0", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", - date: "ISO \uB0A0\uC9DC", - time: "ISO \uC2DC\uAC04", - duration: "ISO \uAE30\uAC04", - ipv4: "IPv4 \uC8FC\uC18C", - ipv6: "IPv6 \uC8FC\uC18C", - cidrv4: "IPv4 \uBC94\uC704", - cidrv6: "IPv6 \uBC94\uC704", - base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", - base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", - json_string: "JSON \uBB38\uC790\uC5F4", - e164: "E.164 \uBC88\uD638", - jwt: "JWT", - template_literal: "\uC785\uB825" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; - } - return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; - return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; - case "too_big": { - const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; - const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; - const sizing = getSizing(issue2.origin); - const unit = sizing?.unit ?? "\uC694\uC18C"; - if (sizing) - return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; - return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; - } - case "too_small": { - const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; - const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; - const sizing = getSizing(issue2.origin); - const unit = sizing?.unit ?? "\uC694\uC18C"; - if (sizing) { - return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; - } - return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; - } - if (_issue.format === "ends_with") - return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; - if (_issue.format === "includes") - return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; - if (_issue.format === "regex") - return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; - return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; - case "unrecognized_keys": - return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; - case "invalid_union": - return `\uC798\uBABB\uB41C \uC785\uB825`; - case "invalid_element": - return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; - default: - return `\uC798\uBABB\uB41C \uC785\uB825`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js -function getUnitTypeFromNumber(number4) { - const abs = Math.abs(number4); - const last = abs % 10; - const last2 = abs % 100; - if (last2 >= 11 && last2 <= 19 || last === 0) - return "many"; - if (last === 1) - return "one"; - return "few"; -} -function lt_default() { - return { - localeError: error26() - }; -} -var capitalizeFirstCharacter, error26; -var init_lt = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"() { - init_util(); - capitalizeFirstCharacter = (text) => { - return text.charAt(0).toUpperCase() + text.slice(1); - }; - error26 = () => { - const Sizable = { - string: { - unit: { - one: "simbolis", - few: "simboliai", - many: "simboli\u0173" - }, - verb: { - smaller: { - inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", - notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" - }, - bigger: { - inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", - notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" - } - } - }, - file: { - unit: { - one: "baitas", - few: "baitai", - many: "bait\u0173" - }, - verb: { - smaller: { - inclusive: "turi b\u016Bti ne didesnis kaip", - notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" - }, - bigger: { - inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", - notInclusive: "turi b\u016Bti didesnis kaip" - } - } - }, - array: { - unit: { - one: "element\u0105", - few: "elementus", - many: "element\u0173" - }, - verb: { - smaller: { - inclusive: "turi tur\u0117ti ne daugiau kaip", - notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" - }, - bigger: { - inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", - notInclusive: "turi tur\u0117ti daugiau kaip" - } - } - }, - set: { - unit: { - one: "element\u0105", - few: "elementus", - many: "element\u0173" - }, - verb: { - smaller: { - inclusive: "turi tur\u0117ti ne daugiau kaip", - notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" - }, - bigger: { - inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", - notInclusive: "turi tur\u0117ti daugiau kaip" - } - } - } - }; - function getSizing(origin, unitType, inclusive, targetShouldBe) { - const result = Sizable[origin] ?? null; - if (result === null) - return result; - return { - unit: result.unit[unitType], - verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] - }; - } - const FormatDictionary = { - regex: "\u012Fvestis", - email: "el. pa\u0161to adresas", - url: "URL", - emoji: "jaustukas", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO data ir laikas", - date: "ISO data", - time: "ISO laikas", - duration: "ISO trukm\u0117", - ipv4: "IPv4 adresas", - ipv6: "IPv6 adresas", - cidrv4: "IPv4 tinklo prefiksas (CIDR)", - cidrv6: "IPv6 tinklo prefiksas (CIDR)", - base64: "base64 u\u017Ekoduota eilut\u0117", - base64url: "base64url u\u017Ekoduota eilut\u0117", - json_string: "JSON eilut\u0117", - e164: "E.164 numeris", - jwt: "JWT", - template_literal: "\u012Fvestis" - }; - const TypeDictionary = { - nan: "NaN", - number: "skai\u010Dius", - bigint: "sveikasis skai\u010Dius", - string: "eilut\u0117", - boolean: "login\u0117 reik\u0161m\u0117", - undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", - function: "funkcija", - symbol: "simbolis", - array: "masyvas", - object: "objektas", - null: "nulin\u0117 reik\u0161m\u0117" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; - } - return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; - return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; - case "too_big": { - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller"); - if (sizing?.verb) - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; - const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`; - } - case "too_small": { - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger"); - if (sizing?.verb) - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; - const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; - if (_issue.format === "regex") - return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; - return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; - case "unrecognized_keys": - return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return "Rastas klaidingas raktas"; - case "invalid_union": - return "Klaidinga \u012Fvestis"; - case "invalid_element": { - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; - } - default: - return "Klaidinga \u012Fvestis"; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js -function mk_default() { - return { - localeError: error27() - }; -} -var error27; -var init_mk = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"() { - init_util(); - error27 = () => { - const Sizable = { - string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0432\u043D\u0435\u0441", - email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", - url: "URL", - emoji: "\u0435\u043C\u043E\u045F\u0438", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", - date: "ISO \u0434\u0430\u0442\u0443\u043C", - time: "ISO \u0432\u0440\u0435\u043C\u0435", - duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", - ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", - ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", - cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", - cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", - base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", - base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", - json_string: "JSON \u043D\u0438\u0437\u0430", - e164: "E.164 \u0431\u0440\u043E\u0458", - jwt: "JWT", - template_literal: "\u0432\u043D\u0435\u0441" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0431\u0440\u043E\u0458", - array: "\u043D\u0438\u0437\u0430" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; - } - return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; - return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; - return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; - case "invalid_union": - return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; - case "invalid_element": - return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; - default: - return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js -function ms_default() { - return { - localeError: error28() - }; -} -var error28; -var init_ms = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"() { - init_util(); - error28 = () => { - const Sizable = { - string: { unit: "aksara", verb: "mempunyai" }, - file: { unit: "bait", verb: "mempunyai" }, - array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "alamat e-mel", - 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: "tarikh masa ISO", - date: "tarikh ISO", - time: "masa ISO", - duration: "tempoh ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "julat IPv4", - cidrv6: "julat IPv6", - base64: "string dikodkan base64", - base64url: "string dikodkan base64url", - json_string: "string JSON", - e164: "nombor E.164", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - number: "nombor" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; - } - return `Input tidak sah: dijangka ${expected}, diterima ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; - return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak sah: mesti mengandungi "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`; - } - case "not_multiple_of": - return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak sah dalam ${issue2.origin}`; - case "invalid_union": - return "Input tidak sah"; - case "invalid_element": - return `Nilai tidak sah dalam ${issue2.origin}`; - default: - return `Input tidak sah`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js -function nl_default() { - return { - localeError: error29() - }; -} -var error29; -var init_nl = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"() { - init_util(); - error29 = () => { - const Sizable = { - string: { unit: "tekens", verb: "heeft" }, - file: { unit: "bytes", verb: "heeft" }, - array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "invoer", - email: "emailadres", - 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 datum en tijd", - date: "ISO datum", - time: "ISO tijd", - duration: "ISO duur", - ipv4: "IPv4-adres", - ipv6: "IPv6-adres", - cidrv4: "IPv4-bereik", - cidrv6: "IPv6-bereik", - base64: "base64-gecodeerde tekst", - base64url: "base64 URL-gecodeerde tekst", - json_string: "JSON string", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "invoer" - }; - const TypeDictionary = { - nan: "NaN", - number: "getal" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; - } - return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; - return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; - if (sizing) - return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; - return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; - if (sizing) { - return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; - } - return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; - } - if (_issue.format === "ends_with") - return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; - if (_issue.format === "includes") - return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; - if (_issue.format === "regex") - return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; - return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; - case "unrecognized_keys": - return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ongeldige key in ${issue2.origin}`; - case "invalid_union": - return "Ongeldige invoer"; - case "invalid_element": - return `Ongeldige waarde in ${issue2.origin}`; - default: - return `Ongeldige invoer`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js -function no_default() { - return { - localeError: error30() - }; -} -var error30; -var init_no = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"() { - init_util(); - error30 = () => { - const Sizable = { - string: { unit: "tegn", verb: "\xE5 ha" }, - file: { unit: "bytes", verb: "\xE5 ha" }, - array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "e-postadresse", - 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 dato- og klokkeslett", - date: "ISO-dato", - time: "ISO-klokkeslett", - duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", - cidrv4: "IPv4-spekter", - cidrv6: "IPv6-spekter", - base64: "base64-enkodet streng", - base64url: "base64url-enkodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - number: "tall", - array: "liste" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; - } - return `Ugyldig input: forventet ${expected}, fikk ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; - return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; - return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ugyldig n\xF8kkel i ${issue2.origin}`; - case "invalid_union": - return "Ugyldig input"; - case "invalid_element": - return `Ugyldig verdi i ${issue2.origin}`; - default: - return `Ugyldig input`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js -function ota_default() { - return { - localeError: error31() - }; -} -var error31; -var init_ota = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"() { - init_util(); - error31 = () => { - const Sizable = { - string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, - file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, - array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "giren", - email: "epostag\xE2h", - 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 heng\xE2m\u0131", - date: "ISO tarihi", - time: "ISO zaman\u0131", - duration: "ISO m\xFCddeti", - ipv4: "IPv4 ni\u015F\xE2n\u0131", - ipv6: "IPv6 ni\u015F\xE2n\u0131", - cidrv4: "IPv4 menzili", - cidrv6: "IPv6 menzili", - base64: "base64-\u015Fifreli metin", - base64url: "base64url-\u015Fifreli metin", - json_string: "JSON metin", - e164: "E.164 say\u0131s\u0131", - jwt: "JWT", - template_literal: "giren" - }; - const TypeDictionary = { - nan: "NaN", - number: "numara", - array: "saf", - null: "gayb" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; - } - return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; - return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; - return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; - } - return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; - if (_issue.format === "ends_with") - return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; - if (_issue.format === "includes") - return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; - if (_issue.format === "regex") - return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; - return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; - case "unrecognized_keys": - return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; - case "invalid_union": - return "Giren tan\u0131namad\u0131."; - case "invalid_element": - return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; - default: - return `K\u0131ymet tan\u0131namad\u0131.`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js -function ps_default() { - return { - localeError: error32() - }; -} -var error32; -var init_ps = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"() { - init_util(); - error32 = () => { - const Sizable = { - string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, - array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0648\u0631\u0648\u062F\u064A", - email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", - url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", - emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", - date: "\u0646\u06D0\u067C\u0647", - time: "\u0648\u062E\u062A", - duration: "\u0645\u0648\u062F\u0647", - ipv4: "\u062F IPv4 \u067E\u062A\u0647", - ipv6: "\u062F IPv6 \u067E\u062A\u0647", - cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", - cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", - base64: "base64-encoded \u0645\u062A\u0646", - base64url: "base64url-encoded \u0645\u062A\u0646", - json_string: "JSON \u0645\u062A\u0646", - e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", - jwt: "JWT", - template_literal: "\u0648\u0631\u0648\u062F\u064A" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0639\u062F\u062F", - array: "\u0627\u0631\u06D0" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; - } - return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; - } - case "invalid_value": - if (issue2.values.length === 1) { - return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; - } - return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; - } - return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; - } - return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; - } - if (_issue.format === "ends_with") { - return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; - } - if (_issue.format === "includes") { - return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; - } - if (_issue.format === "regex") { - return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; - } - return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; - } - case "not_multiple_of": - return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; - case "unrecognized_keys": - return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; - case "invalid_union": - return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; - case "invalid_element": - return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; - default: - return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js -function pl_default() { - return { - localeError: error33() - }; -} -var error33; -var init_pl = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"() { - init_util(); - error33 = () => { - const Sizable = { - string: { unit: "znak\xF3w", verb: "mie\u0107" }, - file: { unit: "bajt\xF3w", verb: "mie\u0107" }, - array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "wyra\u017Cenie", - email: "adres email", - 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: "data i godzina w formacie ISO", - date: "data w formacie ISO", - time: "godzina w formacie ISO", - duration: "czas trwania ISO", - ipv4: "adres IPv4", - ipv6: "adres IPv6", - cidrv4: "zakres IPv4", - cidrv6: "zakres IPv6", - base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", - base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", - json_string: "ci\u0105g znak\xF3w w formacie JSON", - e164: "liczba E.164", - jwt: "JWT", - template_literal: "wej\u015Bcie" - }; - const TypeDictionary = { - nan: "NaN", - number: "liczba", - array: "tablica" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; - } - return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; - return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; - } - return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; - } - return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; - return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; - case "unrecognized_keys": - return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Nieprawid\u0142owy klucz w ${issue2.origin}`; - case "invalid_union": - return "Nieprawid\u0142owe dane wej\u015Bciowe"; - case "invalid_element": - return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; - default: - return `Nieprawid\u0142owe dane wej\u015Bciowe`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js -function pt_default() { - return { - localeError: error34() - }; -} -var error34; -var init_pt = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"() { - init_util(); - error34 = () => { - const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - 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: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" - }; - const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; - } - case "not_multiple_of": - return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; - case "invalid_union": - return "Entrada inv\xE1lida"; - case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; - default: - return `Campo inv\xE1lido`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js -function getRussianPlural(count, one, few, many) { - const absCount = Math.abs(count); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -function ru_default() { - return { - localeError: error35() - }; -} -var error35; -var init_ru = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"() { - init_util(); - error35 = () => { - const Sizable = { - string: { - unit: { - one: "\u0441\u0438\u043C\u0432\u043E\u043B", - few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", - many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" - }, - verb: "\u0438\u043C\u0435\u0442\u044C" - }, - file: { - unit: { - one: "\u0431\u0430\u0439\u0442", - few: "\u0431\u0430\u0439\u0442\u0430", - many: "\u0431\u0430\u0439\u0442" - }, - verb: "\u0438\u043C\u0435\u0442\u044C" - }, - array: { - unit: { - one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", - few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", - many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" - }, - verb: "\u0438\u043C\u0435\u0442\u044C" - }, - set: { - unit: { - one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", - few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", - many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" - }, - verb: "\u0438\u043C\u0435\u0442\u044C" - } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0432\u0432\u043E\u0434", - email: "email \u0430\u0434\u0440\u0435\u0441", - url: "URL", - emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", - date: "ISO \u0434\u0430\u0442\u0430", - time: "ISO \u0432\u0440\u0435\u043C\u044F", - duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", - ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", - ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", - cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", - cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", - base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", - base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", - json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", - e164: "\u043D\u043E\u043C\u0435\u0440 E.164", - jwt: "JWT", - template_literal: "\u0432\u0432\u043E\u0434" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0447\u0438\u0441\u043B\u043E", - array: "\u043C\u0430\u0441\u0441\u0438\u0432" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; - } - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const maxValue = Number(issue2.maximum); - const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; - } - return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const minValue = Number(issue2.minimum); - const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; - } - return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; - case "unrecognized_keys": - return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; - case "invalid_union": - return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; - case "invalid_element": - return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; - default: - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js -function sl_default() { - return { - localeError: error36() - }; -} -var error36; -var init_sl = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"() { - init_util(); - error36 = () => { - const Sizable = { - string: { unit: "znakov", verb: "imeti" }, - file: { unit: "bajtov", verb: "imeti" }, - array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "vnos", - email: "e-po\u0161tni naslov", - 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 datum in \u010Das", - date: "ISO datum", - time: "ISO \u010Das", - duration: "ISO trajanje", - ipv4: "IPv4 naslov", - ipv6: "IPv6 naslov", - cidrv4: "obseg IPv4", - cidrv6: "obseg IPv6", - base64: "base64 kodiran niz", - base64url: "base64url kodiran niz", - json_string: "JSON niz", - e164: "E.164 \u0161tevilka", - jwt: "JWT", - template_literal: "vnos" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0161tevilo", - array: "tabela" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; - } - return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; - return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; - return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; - return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; - case "unrecognized_keys": - return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Neveljaven klju\u010D v ${issue2.origin}`; - case "invalid_union": - return "Neveljaven vnos"; - case "invalid_element": - return `Neveljavna vrednost v ${issue2.origin}`; - default: - return "Neveljaven vnos"; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js -function sv_default() { - return { - localeError: error37() - }; -} -var error37; -var init_sv = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"() { - init_util(); - error37 = () => { - const Sizable = { - string: { unit: "tecken", verb: "att ha" }, - file: { unit: "bytes", verb: "att ha" }, - array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "regulj\xE4rt uttryck", - email: "e-postadress", - 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-datum och tid", - date: "ISO-datum", - time: "ISO-tid", - duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodad str\xE4ng", - base64url: "base64url-kodad str\xE4ng", - json_string: "JSON-str\xE4ng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "mall-literal" - }; - const TypeDictionary = { - nan: "NaN", - number: "antal", - array: "lista" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; - } - return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; - return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; - } - return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; - return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; - case "invalid_union": - return "Ogiltig input"; - case "invalid_element": - return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; - default: - return `Ogiltig input`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js -function ta_default() { - return { - localeError: error38() - }; -} -var error38; -var init_ta = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"() { - init_util(); - error38 = () => { - const Sizable = { - string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", - email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", - 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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", - date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", - time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", - duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", - ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", - ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", - cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", - cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", - base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", - base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", - json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", - e164: "E.164 \u0B8E\u0BA3\u0BCD", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0B8E\u0BA3\u0BCD", - array: "\u0B85\u0BA3\u0BBF", - null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; - } - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - } - return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - } - return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - if (_issue.format === "ends_with") - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - if (_issue.format === "includes") - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - if (_issue.format === "regex") - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - case "unrecognized_keys": - return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; - case "invalid_union": - return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; - case "invalid_element": - return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; - default: - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js -function th_default() { - return { - localeError: error39() - }; -} -var error39; -var init_th = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"() { - init_util(); - error39 = () => { - const Sizable = { - string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", - email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", - url: "URL", - emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", - date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", - time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", - duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", - ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", - ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", - cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", - cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", - base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", - base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", - json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", - e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", - jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", - template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", - array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", - null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; - } - return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; - return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; - return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; - if (_issue.format === "regex") - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; - case "unrecognized_keys": - return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; - case "invalid_union": - return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; - case "invalid_element": - return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; - default: - return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js -function tr_default() { - return { - localeError: error40() - }; -} -var error40; -var init_tr = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"() { - init_util(); - error40 = () => { - const Sizable = { - string: { unit: "karakter", verb: "olmal\u0131" }, - file: { unit: "bayt", verb: "olmal\u0131" }, - array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "girdi", - email: "e-posta adresi", - 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 tarih ve saat", - date: "ISO tarih", - time: "ISO saat", - duration: "ISO s\xFCre", - ipv4: "IPv4 adresi", - ipv6: "IPv6 adresi", - cidrv4: "IPv4 aral\u0131\u011F\u0131", - cidrv6: "IPv6 aral\u0131\u011F\u0131", - base64: "base64 ile \u015Fifrelenmi\u015F metin", - base64url: "base64url ile \u015Fifrelenmi\u015F metin", - json_string: "JSON dizesi", - e164: "E.164 say\u0131s\u0131", - jwt: "JWT", - template_literal: "\u015Eablon dizesi" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; - } - return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; - return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; - return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; - if (_issue.format === "ends_with") - return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; - if (_issue.format === "includes") - return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; - if (_issue.format === "regex") - return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; - return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; - case "unrecognized_keys": - return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; - case "invalid_union": - return "Ge\xE7ersiz de\u011Fer"; - case "invalid_element": - return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; - default: - return `Ge\xE7ersiz de\u011Fer`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js -function uk_default() { - return { - localeError: error41() - }; -} -var error41; -var init_uk = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"() { - init_util(); - error41 = () => { - const Sizable = { - string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", - email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", - url: "URL", - emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", - date: "\u0434\u0430\u0442\u0430 ISO", - time: "\u0447\u0430\u0441 ISO", - duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", - ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", - ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", - cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", - cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", - base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", - base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", - json_string: "\u0440\u044F\u0434\u043E\u043A JSON", - e164: "\u043D\u043E\u043C\u0435\u0440 E.164", - jwt: "JWT", - template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0447\u0438\u0441\u043B\u043E", - array: "\u043C\u0430\u0441\u0438\u0432" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; - } - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; - return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; - case "unrecognized_keys": - return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; - case "invalid_union": - return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; - case "invalid_element": - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; - default: - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js -function ua_default() { - return uk_default(); -} -var init_ua = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js"() { - init_uk(); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js -function ur_default() { - return { - localeError: error42() - }; -} -var error42; -var init_ur = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"() { - init_util(); - error42 = () => { - const Sizable = { - string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, - file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, - array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0627\u0646 \u067E\u0679", - email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", - url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", - emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", - uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", - uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", - uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", - nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", - guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", - cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", - cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", - ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", - xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", - ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", - datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", - date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", - time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", - duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", - ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", - ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", - cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", - cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", - base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", - base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", - json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", - e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", - jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", - template_literal: "\u0627\u0646 \u067E\u0679" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0646\u0645\u0628\u0631", - array: "\u0622\u0631\u06D2", - null: "\u0646\u0644" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; - } - return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; - return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; - return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; - } - return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - } - if (_issue.format === "ends_with") - return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - if (_issue.format === "includes") - return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - if (_issue.format === "regex") - return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - case "unrecognized_keys": - return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; - case "invalid_key": - return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; - case "invalid_union": - return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; - case "invalid_element": - return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; - default: - return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js -function uz_default() { - return { - localeError: error43() - }; -} -var error43; -var init_uz = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"() { - init_util(); - error43 = () => { - const Sizable = { - string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, - file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, - array: { unit: "element", verb: "bo\u2018lishi kerak" }, - set: { unit: "element", verb: "bo\u2018lishi kerak" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "kirish", - email: "elektron pochta manzili", - 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 sana va vaqti", - date: "ISO sana", - time: "ISO vaqt", - duration: "ISO davomiylik", - ipv4: "IPv4 manzil", - ipv6: "IPv6 manzil", - mac: "MAC manzil", - cidrv4: "IPv4 diapazon", - cidrv6: "IPv6 diapazon", - base64: "base64 kodlangan satr", - base64url: "base64url kodlangan satr", - json_string: "JSON satr", - e164: "E.164 raqam", - jwt: "JWT", - template_literal: "kirish" - }; - const TypeDictionary = { - nan: "NaN", - number: "raqam", - array: "massiv" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; - } - return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; - return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; - return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; - } - return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; - if (_issue.format === "ends_with") - return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; - if (_issue.format === "includes") - return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; - if (_issue.format === "regex") - return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; - return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; - case "unrecognized_keys": - return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; - case "invalid_union": - return "Noto\u2018g\u2018ri kirish"; - case "invalid_element": - return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; - default: - return `Noto\u2018g\u2018ri kirish`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js -function vi_default() { - return { - localeError: error44() - }; -} -var error44; -var init_vi = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"() { - init_util(); - error44 = () => { - const Sizable = { - string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, - file: { unit: "byte", verb: "c\xF3" }, - array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0111\u1EA7u v\xE0o", - email: "\u0111\u1ECBa ch\u1EC9 email", - 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: "ng\xE0y gi\u1EDD ISO", - date: "ng\xE0y ISO", - time: "gi\u1EDD ISO", - duration: "kho\u1EA3ng th\u1EDDi gian ISO", - ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", - ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", - cidrv4: "d\u1EA3i IPv4", - cidrv6: "d\u1EA3i IPv6", - base64: "chu\u1ED7i m\xE3 h\xF3a base64", - base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", - json_string: "chu\u1ED7i JSON", - e164: "s\u1ED1 E.164", - jwt: "JWT", - template_literal: "\u0111\u1EA7u v\xE0o" - }; - const TypeDictionary = { - nan: "NaN", - number: "s\u1ED1", - array: "m\u1EA3ng" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; - } - return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; - return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; - return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; - } - case "not_multiple_of": - return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; - case "unrecognized_keys": - return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; - case "invalid_union": - return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; - case "invalid_element": - return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; - default: - return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js -function zh_CN_default() { - return { - localeError: error45() - }; -} -var error45; -var init_zh_CN = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"() { - init_util(); - error45 = () => { - const Sizable = { - string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, - file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, - array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u8F93\u5165", - email: "\u7535\u5B50\u90AE\u4EF6", - url: "URL", - emoji: "\u8868\u60C5\u7B26\u53F7", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO\u65E5\u671F\u65F6\u95F4", - date: "ISO\u65E5\u671F", - time: "ISO\u65F6\u95F4", - duration: "ISO\u65F6\u957F", - ipv4: "IPv4\u5730\u5740", - ipv6: "IPv6\u5730\u5740", - cidrv4: "IPv4\u7F51\u6BB5", - cidrv6: "IPv6\u7F51\u6BB5", - base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", - base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", - json_string: "JSON\u5B57\u7B26\u4E32", - e164: "E.164\u53F7\u7801", - jwt: "JWT", - template_literal: "\u8F93\u5165" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u6570\u5B57", - array: "\u6570\u7EC4", - null: "\u7A7A\u503C(null)" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; - } - return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; - return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; - return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; - if (_issue.format === "ends_with") - return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; - if (_issue.format === "includes") - return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; - return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; - case "unrecognized_keys": - return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; - case "invalid_union": - return "\u65E0\u6548\u8F93\u5165"; - case "invalid_element": - return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; - default: - return `\u65E0\u6548\u8F93\u5165`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js -function zh_TW_default() { - return { - localeError: error46() - }; -} -var error46; -var init_zh_TW = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"() { - init_util(); - error46 = () => { - const Sizable = { - string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, - file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, - array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u8F38\u5165", - email: "\u90F5\u4EF6\u5730\u5740", - 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 \u65E5\u671F\u6642\u9593", - date: "ISO \u65E5\u671F", - time: "ISO \u6642\u9593", - duration: "ISO \u671F\u9593", - ipv4: "IPv4 \u4F4D\u5740", - ipv6: "IPv6 \u4F4D\u5740", - cidrv4: "IPv4 \u7BC4\u570D", - cidrv6: "IPv6 \u7BC4\u570D", - base64: "base64 \u7DE8\u78BC\u5B57\u4E32", - base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", - json_string: "JSON \u5B57\u4E32", - e164: "E.164 \u6578\u503C", - jwt: "JWT", - template_literal: "\u8F38\u5165" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; - } - return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; - return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; - return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; - } - if (_issue.format === "ends_with") - return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; - if (_issue.format === "includes") - return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; - return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; - case "unrecognized_keys": - return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; - case "invalid_key": - return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; - case "invalid_union": - return "\u7121\u6548\u7684\u8F38\u5165\u503C"; - case "invalid_element": - return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; - default: - return `\u7121\u6548\u7684\u8F38\u5165\u503C`; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js -function yo_default() { - return { - localeError: error47() - }; -} -var error47; -var init_yo = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"() { - init_util(); - error47 = () => { - const Sizable = { - string: { unit: "\xE0mi", verb: "n\xED" }, - file: { unit: "bytes", verb: "n\xED" }, - array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", - email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", - 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: "\xE0k\xF3k\xF2 ISO", - date: "\u1ECDj\u1ECD\u0301 ISO", - time: "\xE0k\xF3k\xF2 ISO", - duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", - ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", - ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", - cidrv4: "\xE0gb\xE8gb\xE8 IPv4", - cidrv6: "\xE0gb\xE8gb\xE8 IPv6", - base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", - base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", - json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", - e164: "n\u1ECD\u0301mb\xE0 E.164", - jwt: "JWT", - template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" - }; - const TypeDictionary = { - nan: "NaN", - number: "n\u1ECD\u0301mb\xE0", - array: "akop\u1ECD" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; - } - return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; - return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; - return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; - return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; - return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; - case "unrecognized_keys": - return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; - case "invalid_union": - return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; - case "invalid_element": - return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; - default: - return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; - } - }; - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js -var locales_exports = {}; -__export(locales_exports, { - ar: () => ar_default, - az: () => az_default, - be: () => be_default, - bg: () => bg_default, - ca: () => ca_default, - cs: () => cs_default, - da: () => da_default, - de: () => de_default, - en: () => en_default, - eo: () => eo_default, - es: () => es_default, - fa: () => fa_default, - fi: () => fi_default, - fr: () => fr_default, - frCA: () => fr_CA_default, - he: () => he_default, - hu: () => hu_default, - hy: () => hy_default, - id: () => id_default, - is: () => is_default, - it: () => it_default, - ja: () => ja_default, - ka: () => ka_default, - kh: () => kh_default, - km: () => km_default, - ko: () => ko_default, - lt: () => lt_default, - mk: () => mk_default, - ms: () => ms_default, - nl: () => nl_default, - no: () => no_default, - ota: () => ota_default, - pl: () => pl_default, - ps: () => ps_default, - pt: () => pt_default, - ru: () => ru_default, - sl: () => sl_default, - sv: () => sv_default, - ta: () => ta_default, - th: () => th_default, - tr: () => tr_default, - ua: () => ua_default, - uk: () => uk_default, - ur: () => ur_default, - uz: () => uz_default, - vi: () => vi_default, - yo: () => yo_default, - zhCN: () => zh_CN_default, - zhTW: () => zh_TW_default -}); -var init_locales = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js"() { - init_ar(); - init_az(); - init_be(); - init_bg(); - init_ca(); - init_cs(); - init_da(); - init_de(); - init_en(); - init_eo(); - init_es(); - init_fa(); - init_fi(); - init_fr(); - init_fr_CA(); - init_he(); - init_hu(); - init_hy(); - init_id(); - init_is(); - init_it(); - init_ja(); - init_ka(); - init_kh(); - init_km(); - init_ko(); - init_lt(); - init_mk(); - init_ms(); - init_nl(); - init_no(); - init_ota(); - init_ps(); - init_pl(); - init_pt(); - init_ru(); - init_sl(); - init_sv(); - init_ta(); - init_th(); - init_tr(); - init_ua(); - init_uk(); - init_ur(); - init_uz(); - init_vi(); - init_zh_CN(); - init_zh_TW(); - init_yo(); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js -function registry() { - return new $ZodRegistry(); -} -var _a, $output, $input, $ZodRegistry, globalRegistry; -var init_registries = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js"() { - $output = Symbol("ZodOutput"); - $input = Symbol("ZodInput"); - $ZodRegistry = class { - constructor() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - } - add(schema3, ..._meta) { - const meta3 = _meta[0]; - this._map.set(schema3, meta3); - if (meta3 && typeof meta3 === "object" && "id" in meta3) { - this._idmap.set(meta3.id, schema3); - } - return this; - } - clear() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - return this; - } - remove(schema3) { - const meta3 = this._map.get(schema3); - if (meta3 && typeof meta3 === "object" && "id" in meta3) { - this._idmap.delete(meta3.id); - } - this._map.delete(schema3); - return this; - } - get(schema3) { - const p = schema3._zod.parent; - if (p) { - const pm = { ...this.get(p) ?? {} }; - delete pm.id; - const f = { ...pm, ...this._map.get(schema3) }; - return Object.keys(f).length ? f : void 0; - } - return this._map.get(schema3); - } - has(schema3) { - return this._map.has(schema3); - } - }; - (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); - globalRegistry = globalThis.__zod_globalRegistry; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js -// @__NO_SIDE_EFFECTS__ -function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class2, params) { - return new Class2({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class2, params) { - return new Class2({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class2, params) { - return new Class2({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _emoji2(Class2, params) { - return new Class2({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class2, params) { - return new Class2({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid(Class2, params) { - return new Class2({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class2, params) { - return new Class2({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class2, params) { - return new Class2({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class2, params) { - return new Class2({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class2, params) { - return new Class2({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class2, params) { - return new Class2({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class2, params) { - return new Class2({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class2, params) { - return new Class2({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class2, params) { - return new Class2({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class2, params) { - return new Class2({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class2, params) { - return new Class2({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class2, params) { - return new Class2({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class2, params) { - return new Class2({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class2, params) { - return new Class2({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class2, params) { - return new Class2({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class2, params) { - return new Class2({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class2, params) { - return new Class2({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class2, params) { - return new Class2({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class2, params) { - return new Class2({ - type: "boolean", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class2, params) { - return new Class2({ - type: "boolean", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class2, params) { - return new Class2({ - type: "bigint", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class2, params) { - return new Class2({ - type: "bigint", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class2, params) { - return new Class2({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class2, params) { - return new Class2({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class2, params) { - return new Class2({ - type: "symbol", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _undefined2(Class2, params) { - return new Class2({ - type: "undefined", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _null2(Class2, params) { - return new Class2({ - type: "null", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class2) { - return new Class2({ - type: "any" - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class2) { - return new Class2({ - type: "unknown" - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class2, params) { - return new Class2({ - type: "never", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class2, params) { - return new Class2({ - type: "void", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class2, params) { - return new Class2({ - type: "date", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class2, params) { - return new Class2({ - type: "date", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class2, params) { - return new Class2({ - type: "nan", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true - }); -} -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true - }); -} -// @__NO_SIDE_EFFECTS__ -function _positive(params) { - return /* @__PURE__ */ _gt(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return /* @__PURE__ */ _lt(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return /* @__PURE__ */ _lte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return /* @__PURE__ */ _gte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxSize(maximum, params) { - return new $ZodCheckMaxSize({ - check: "max_size", - ...normalizeParams(params), - maximum - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new $ZodCheckMinSize({ - check: "min_size", - ...normalizeParams(params), - minimum - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size, params) { - return new $ZodCheckSizeEquals({ - check: "size_equals", - ...normalizeParams(params), - size - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix - }); -} -// @__NO_SIDE_EFFECTS__ -function _property(property, schema3, params) { - return new $ZodCheckProperty({ - check: "property", - property, - schema: schema3, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types, params) { - return new $ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx - }); -} -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); -} -// @__NO_SIDE_EFFECTS__ -function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); -} -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); -} -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); -} -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class2, element, params) { - return new Class2({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _union(Class2, options, params) { - return new Class2({ - type: "union", - options, - ...normalizeParams(params) - }); -} -function _xor(Class2, options, params) { - return new Class2({ - type: "union", - options, - inclusive: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _discriminatedUnion(Class2, discriminator, options, params) { - return new Class2({ - type: "union", - options, - discriminator, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _intersection(Class2, left, right) { - return new Class2({ - type: "intersection", - left, - right - }); -} -// @__NO_SIDE_EFFECTS__ -function _tuple(Class2, items, _paramsOrRest, _params2) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params2 : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class2({ - type: "tuple", - items, - rest, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _record(Class2, keyType, valueType, params) { - return new Class2({ - type: "record", - keyType, - valueType, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _map(Class2, keyType, valueType, params) { - return new Class2({ - type: "map", - keyType, - valueType, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _set(Class2, valueType, params) { - return new Class2({ - type: "set", - valueType, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _enum(Class2, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new Class2({ - type: "enum", - entries, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nativeEnum(Class2, entries, params) { - return new Class2({ - type: "enum", - entries, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _literal(Class2, value, params) { - return new Class2({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class2, params) { - return new Class2({ - type: "file", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _transform(Class2, fn) { - return new Class2({ - type: "transform", - transform: fn - }); -} -// @__NO_SIDE_EFFECTS__ -function _optional(Class2, innerType) { - return new Class2({ - type: "optional", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _nullable(Class2, innerType) { - return new Class2({ - type: "nullable", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _default(Class2, innerType, defaultValue) { - return new Class2({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - } - }); -} -// @__NO_SIDE_EFFECTS__ -function _nonoptional(Class2, innerType, params) { - return new Class2({ - type: "nonoptional", - innerType, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _success(Class2, innerType) { - return new Class2({ - type: "success", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _catch(Class2, innerType, catchValue) { - return new Class2({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); -} -// @__NO_SIDE_EFFECTS__ -function _pipe(Class2, in_, out) { - return new Class2({ - type: "pipe", - in: in_, - out - }); -} -// @__NO_SIDE_EFFECTS__ -function _readonly(Class2, innerType) { - return new Class2({ - type: "readonly", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _templateLiteral(Class2, parts, params) { - return new Class2({ - type: "template_literal", - parts, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _lazy(Class2, getter) { - return new Class2({ - type: "lazy", - getter - }); -} -// @__NO_SIDE_EFFECTS__ -function _promise(Class2, innerType) { - return new Class2({ - type: "promise", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class2, fn, _params2) { - const norm = normalizeParams(_params2); - norm.abort ?? (norm.abort = true); - const schema3 = new Class2({ - type: "custom", - check: "custom", - fn, - ...norm - }); - return schema3; -} -// @__NO_SIDE_EFFECTS__ -function _refine(Class2, fn, _params2) { - const schema3 = new Class2({ - type: "custom", - check: "custom", - fn, - ...normalizeParams(_params2) - }); - return schema3; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn) { - const ch = /* @__PURE__ */ _check((payload) => { - payload.addIssue = (issue2) => { - if (typeof issue2 === "string") { - payload.issues.push(issue(issue2, payload.value, ch._zod.def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload.issues.push(issue(_issue)); - } - }; - return fn(payload.value, payload); - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params) - }); - ch._zod.check = fn; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - } - ]; - ch._zod.check = () => { - }; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - } - ]; - ch._zod.check = () => { - }; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params2) { - const params = normalizeParams(_params2); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); - falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? $ZodCodec; - const _Boolean = Classes.Boolean ?? $ZodBoolean; - const _String = Classes.String ?? $ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec2 = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: (input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } else if (falsySet.has(data)) { - return false; - } else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec2, - continue: false - }); - return {}; - } - }, - reverseTransform: (input, _payload3) => { - if (input === true) { - return truthyArray[0] || "true"; - } else { - return falsyArray[0] || "false"; - } - }, - error: params.error - }); - return codec2; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class2, format, fnOrRegex, _params2 = {}) { - const params = normalizeParams(_params2); - const def = { - ...normalizeParams(_params2), - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class2(def); - return inst; -} -var TimePrecision; -var init_api = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js"() { - init_checks(); - init_registries(); - init_schemas(); - init_util(); - TimePrecision = { - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6 - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js -function initializeContext(params) { - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { - }), - io: params?.io ?? "output", - counter: 0, - seen: /* @__PURE__ */ new Map(), - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - external: params?.external ?? void 0 - }; -} -function process2(schema3, ctx, _params2 = { path: [], schemaPath: [] }) { - var _a30; - const def = schema3._zod.def; - const seen = ctx.seen.get(schema3); - if (seen) { - seen.count++; - const isCycle = _params2.schemaPath.includes(schema3); - if (isCycle) { - seen.cycle = _params2.path; - } - return seen.schema; - } - const result = { schema: {}, count: 1, cycle: void 0, path: _params2.path }; - ctx.seen.set(schema3, result); - const overrideSchema = schema3._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } else { - const params = { - ..._params2, - schemaPath: [..._params2.schemaPath, schema3], - path: _params2.path - }; - if (schema3._zod.processJSONSchema) { - schema3._zod.processJSONSchema(ctx, result.schema, params); - } else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema3, ctx, _json, params); - } - const parent = schema3._zod.parent; - if (parent) { - if (!result.ref) - result.ref = parent; - process2(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - const meta3 = ctx.metadataRegistry.get(schema3); - if (meta3) - Object.assign(result.schema, meta3); - if (ctx.io === "input" && isTransforming(schema3)) { - delete result.schema.examples; - delete result.schema.default; - } - if (ctx.io === "input" && result.schema._prefault) - (_a30 = result.schema).default ?? (_a30.default = result.schema._prefault); - delete result.schema._prefault; - const _result = ctx.seen.get(schema3); - return _result.schema; -} -function extractDefs(ctx, schema3) { - const root = ctx.seen.get(schema3); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const idToSchema = /* @__PURE__ */ new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - const makeURI = (entry) => { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; - const uriGenerator = ctx.external.uri ?? ((id2) => id2); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - 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: "#" }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; - }; - const extractToDef = (entry) => { - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - if (defId) - seen.defId = defId; - const schema4 = seen.schema; - for (const key in schema4) { - delete schema4[key]; - } - schema4.$ref = ref; - }; - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); - } - } - } - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (schema3 === entry[0]) { - extractToDef(entry); - continue; - } - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema3 !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - if (seen.cycle) { - extractToDef(entry); - continue; - } - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - continue; - } - } - } -} -function finalize(ctx, schema3) { - const root = ctx.seen.get(schema3); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - if (seen.ref === null) - return; - const schema4 = seen.def ?? seen.schema; - const _cached2 = { ...schema4 }; - const ref = seen.ref; - seen.ref = null; - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - schema4.allOf = schema4.allOf ?? []; - schema4.allOf.push(refSchema); - } else { - Object.assign(schema4, refSchema); - } - Object.assign(schema4, _cached2); - const isParentRef = zodSchema._zod.parent === ref; - if (isParentRef) { - for (const key in schema4) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached2)) { - delete schema4[key]; - } - } - } - if (refSchema.$ref && refSeen.def) { - for (const key in schema4) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema4[key]) === JSON.stringify(refSeen.def[key])) { - delete schema4[key]; - } - } - } - } - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema4.$ref = parentSeen.schema.$ref; - if (parentSeen.def) { - for (const key in schema4) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema4[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema4[key]; - } - } - } - } - } - ctx.override({ - zodSchema, - jsonSchema: schema4, - path: seen.path ?? [] - }); - }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } else if (ctx.target === "openapi-3.0") { - } else { - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema3)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - Object.assign(result, root.def ?? root.schema); - const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - defs[seen.defId] = seen.def; - } - } - if (ctx.external) { - } else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } else { - result.definitions = defs; - } - } - } - try { - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema3["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema3, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema3, "output", ctx.processors) - } - }, - enumerable: false, - writable: false - }); - return finalized; - } catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema2, _ctx) { - const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; - if (ctx.seen.has(_schema2)) - return false; - ctx.seen.add(_schema2); - const def = _schema2._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - 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") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -var createToJSONSchemaMethod, createStandardJSONSchemaMethod; -var init_to_json_schema = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"() { - init_registries(); - createToJSONSchemaMethod = (schema3, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - process2(schema3, ctx); - extractDefs(ctx, schema3); - return finalize(ctx, schema3); - }; - createStandardJSONSchemaMethod = (schema3, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema3, ctx); - extractDefs(ctx, schema3); - return finalize(ctx, schema3); - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; - const ctx2 = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - for (const entry of registry2._idmap.entries()) { - const [_, schema3] = entry; - process2(schema3, ctx2); - } - const schemas = {}; - const external = { - registry: registry2, - uri: params?.uri, - defs - }; - ctx2.external = external; - for (const entry of registry2._idmap.entries()) { - const [key, schema3] = entry; - extractDefs(ctx2, schema3); - schemas[key] = finalize(ctx2, schema3); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs - }; - } - return { schemas }; - } - const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} -var formatMap, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, recordProcessor, nullableProcessor, nonoptionalProcessor, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors; -var init_json_schema_processors = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"() { - init_to_json_schema(); - init_util(); - formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "" - // do not set - }; - stringProcessor = (schema3, ctx, _json, _params2) => { - const json2 = _json; - json2.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema3._zod.bag; - if (typeof minimum === "number") - json2.minLength = minimum; - if (typeof maximum === "number") - json2.maxLength = maximum; - if (format) { - json2.format = formatMap[format] ?? format; - if (json2.format === "") - delete json2.format; - if (format === "time") { - delete json2.format; - } - } - if (contentEncoding) - json2.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json2.pattern = regexes[0].source; - else if (regexes.length > 1) { - json2.allOf = [ - ...regexes.map((regex) => ({ - ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, - pattern: regex.source - })) - ]; - } - } - }; - numberProcessor = (schema3, ctx, _json, _params2) => { - const json2 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema3._zod.bag; - if (typeof format === "string" && format.includes("int")) - json2.type = "integer"; - else - json2.type = "number"; - if (typeof exclusiveMinimum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json2.minimum = exclusiveMinimum; - json2.exclusiveMinimum = true; - } else { - json2.exclusiveMinimum = exclusiveMinimum; - } - } - if (typeof minimum === "number") { - json2.minimum = minimum; - if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { - if (exclusiveMinimum >= minimum) - delete json2.minimum; - else - delete json2.exclusiveMinimum; - } - } - if (typeof exclusiveMaximum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json2.maximum = exclusiveMaximum; - json2.exclusiveMaximum = true; - } else { - json2.exclusiveMaximum = exclusiveMaximum; - } - } - if (typeof maximum === "number") { - json2.maximum = maximum; - if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { - if (exclusiveMaximum <= maximum) - delete json2.maximum; - else - delete json2.exclusiveMaximum; - } - } - if (typeof multipleOf === "number") - json2.multipleOf = multipleOf; - }; - booleanProcessor = (_schema2, _ctx, json2, _params2) => { - json2.type = "boolean"; - }; - bigintProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } - }; - symbolProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } - }; - nullProcessor = (_schema2, ctx, json2, _params2) => { - if (ctx.target === "openapi-3.0") { - json2.type = "string"; - json2.nullable = true; - json2.enum = [null]; - } else { - json2.type = "null"; - } - }; - undefinedProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } - }; - voidProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } - }; - neverProcessor = (_schema2, _ctx, json2, _params2) => { - json2.not = {}; - }; - anyProcessor = (_schema2, _ctx, _json, _params2) => { - }; - unknownProcessor = (_schema2, _ctx, _json, _params2) => { - }; - dateProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } - }; - enumProcessor = (schema3, _ctx, json2, _params2) => { - const def = schema3._zod.def; - const values = getEnumValues(def.entries); - if (values.every((v) => typeof v === "number")) - json2.type = "number"; - if (values.every((v) => typeof v === "string")) - json2.type = "string"; - json2.enum = values; - }; - literalProcessor = (schema3, ctx, json2, _params2) => { - const def = schema3._zod.def; - const vals = []; - for (const val of def.values) { - if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } - } 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)); - } - } else { - vals.push(val); - } - } - if (vals.length === 0) { - } else if (vals.length === 1) { - const val = vals[0]; - json2.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json2.enum = [val]; - } else { - json2.const = val; - } - } else { - if (vals.every((v) => typeof v === "number")) - json2.type = "number"; - if (vals.every((v) => typeof v === "string")) - json2.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json2.type = "boolean"; - if (vals.every((v) => v === null)) - json2.type = "null"; - json2.enum = vals; - } - }; - nanProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } - }; - templateLiteralProcessor = (schema3, _ctx, json2, _params2) => { - const _json = json2; - const pattern = schema3._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; - }; - fileProcessor = (schema3, _ctx, json2, _params2) => { - const _json = json2; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema3._zod.bag; - if (minimum !== void 0) - file2.minLength = minimum; - if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } - }; - successProcessor = (_schema2, _ctx, json2, _params2) => { - json2.type = "boolean"; - }; - customProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } - }; - functionProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } - }; - transformProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } - }; - mapProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } - }; - setProcessor = (_schema2, ctx, _json, _params2) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } - }; - arrayProcessor = (schema3, ctx, _json, params) => { - const json2 = _json; - const def = schema3._zod.def; - const { minimum, maximum } = schema3._zod.bag; - if (typeof minimum === "number") - json2.minItems = minimum; - if (typeof maximum === "number") - json2.maxItems = maximum; - json2.type = "array"; - json2.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); - }; - objectProcessor = (schema3, ctx, _json, params) => { - const json2 = _json; - const def = schema3._zod.def; - json2.type = "object"; - json2.properties = {}; - const shape = def.shape; - for (const key in shape) { - json2.properties[key] = process2(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 === void 0; - } else { - return v.optout === void 0; - } - })); - if (requiredKeys.size > 0) { - json2.required = Array.from(requiredKeys); - } - if (def.catchall?._zod.def.type === "never") { - json2.additionalProperties = false; - } else if (!def.catchall) { - if (ctx.io === "output") - json2.additionalProperties = false; - } else if (def.catchall) { - json2.additionalProperties = process2(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - }; - unionProcessor = (schema3, ctx, json2, params) => { - const def = schema3._zod.def; - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] - })); - if (isExclusive) { - json2.oneOf = options; - } else { - json2.anyOf = options; - } - }; - intersectionProcessor = (schema3, ctx, json2, params) => { - const def = schema3._zod.def; - const a = process2(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0] - }); - const b = process2(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1] - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...isSimpleIntersection(a) ? a.allOf : [a], - ...isSimpleIntersection(b) ? b.allOf : [b] - ]; - json2.allOf = allOf; - }; - tupleProcessor = (schema3, ctx, _json, params) => { - const json2 = _json; - const def = schema3._zod.def; - json2.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { - ...params, - path: [...params.path, prefixPath, i] - })); - const rest = def.rest ? process2(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] - }) : null; - if (ctx.target === "draft-2020-12") { - json2.prefixItems = prefixItems; - if (rest) { - json2.items = rest; - } - } else if (ctx.target === "openapi-3.0") { - json2.items = { - anyOf: prefixItems - }; - if (rest) { - json2.items.anyOf.push(rest); - } - json2.minItems = prefixItems.length; - if (!rest) { - json2.maxItems = prefixItems.length; - } - } else { - json2.items = prefixItems; - if (rest) { - json2.additionalItems = rest; - } - } - const { minimum, maximum } = schema3._zod.bag; - if (typeof minimum === "number") - json2.minItems = minimum; - if (typeof maximum === "number") - json2.maxItems = maximum; - }; - recordProcessor = (schema3, ctx, _json, params) => { - const json2 = _json; - const def = schema3._zod.def; - json2.type = "object"; - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"] - }); - json2.patternProperties = {}; - for (const pattern of patterns) { - json2.patternProperties[pattern.source] = valueSchema; - } - } else { - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json2.propertyNames = process2(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"] - }); - } - json2.additionalProperties = process2(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - const keyValues = keyType._zod.values; - if (keyValues) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json2.required = validKeyValues; - } - } - }; - nullableProcessor = (schema3, ctx, json2, params) => { - const def = schema3._zod.def; - const inner = process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema3); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json2.nullable = true; - } else { - json2.anyOf = [inner, { type: "null" }]; - } - }; - nonoptionalProcessor = (schema3, ctx, _json, params) => { - const def = schema3._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = def.innerType; - }; - defaultProcessor = (schema3, ctx, json2, params) => { - const def = schema3._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = def.innerType; - json2.default = JSON.parse(JSON.stringify(def.defaultValue)); - }; - prefaultProcessor = (schema3, ctx, json2, params) => { - const def = schema3._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = def.innerType; - if (ctx.io === "input") - json2._prefault = JSON.parse(JSON.stringify(def.defaultValue)); - }; - catchProcessor = (schema3, ctx, json2, params) => { - const def = schema3._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(void 0); - } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - json2.default = catchValue; - }; - pipeProcessor = (schema3, ctx, _json, params) => { - const def = schema3._zod.def; - const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; - process2(innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = innerType; - }; - readonlyProcessor = (schema3, ctx, json2, params) => { - const def = schema3._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = def.innerType; - json2.readOnly = true; - }; - promiseProcessor = (schema3, ctx, _json, params) => { - const def = schema3._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = def.innerType; - }; - optionalProcessor = (schema3, ctx, _json, params) => { - const def = schema3._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = def.innerType; - }; - lazyProcessor = (schema3, ctx, _json, params) => { - const innerType = schema3._zod.innerType; - process2(innerType, ctx, params); - const seen = ctx.seen.get(schema3); - seen.ref = innerType; - }; - allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js -var JSONSchemaGenerator; -var init_json_schema_generator = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"() { - init_json_schema_processors(); - init_to_json_schema(); - JSONSchemaGenerator = class { - /** @deprecated Access via ctx instead */ - get metadataRegistry() { - return this.ctx.metadataRegistry; - } - /** @deprecated Access via ctx instead */ - get target() { - return this.ctx.target; - } - /** @deprecated Access via ctx instead */ - get unrepresentable() { - return this.ctx.unrepresentable; - } - /** @deprecated Access via ctx instead */ - get override() { - return this.ctx.override; - } - /** @deprecated Access via ctx instead */ - get io() { - return this.ctx.io; - } - /** @deprecated Access via ctx instead */ - get counter() { - return this.ctx.counter; - } - set counter(value) { - this.ctx.counter = value; - } - /** @deprecated Access via ctx instead */ - get seen() { - return this.ctx.seen; - } - constructor(params) { - let normalizedTarget = params?.target ?? "draft-2020-12"; - if (normalizedTarget === "draft-4") - normalizedTarget = "draft-04"; - if (normalizedTarget === "draft-7") - normalizedTarget = "draft-07"; - this.ctx = initializeContext({ - processors: allProcessors, - target: normalizedTarget, - ...params?.metadata && { metadata: params.metadata }, - ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, - ...params?.override && { override: params.override }, - ...params?.io && { io: params.io } - }); - } - /** - * Process a schema to prepare it for JSON Schema generation. - * This must be called before emit(). - */ - process(schema3, _params2 = { path: [], schemaPath: [] }) { - return process2(schema3, this.ctx, _params2); - } - /** - * Emit the final JSON Schema after processing. - * Must call process() first. - */ - emit(schema3, _params2) { - if (_params2) { - if (_params2.cycles) - this.ctx.cycles = _params2.cycles; - if (_params2.reused) - this.ctx.reused = _params2.reused; - if (_params2.external) - this.ctx.external = _params2.external; - } - extractDefs(this.ctx, schema3); - const result = finalize(this.ctx, schema3); - const { "~standard": _, ...plainResult } = result; - return plainResult; - } - }; - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js -var json_schema_exports = {}; -var init_json_schema = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"() { - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js -var core_exports2 = {}; -__export(core_exports2, { - $ZodAny: () => $ZodAny, - $ZodArray: () => $ZodArray, - $ZodAsyncError: () => $ZodAsyncError, - $ZodBase64: () => $ZodBase64, - $ZodBase64URL: () => $ZodBase64URL, - $ZodBigInt: () => $ZodBigInt, - $ZodBigIntFormat: () => $ZodBigIntFormat, - $ZodBoolean: () => $ZodBoolean, - $ZodCIDRv4: () => $ZodCIDRv4, - $ZodCIDRv6: () => $ZodCIDRv6, - $ZodCUID: () => $ZodCUID, - $ZodCUID2: () => $ZodCUID2, - $ZodCatch: () => $ZodCatch, - $ZodCheck: () => $ZodCheck, - $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, - $ZodCheckEndsWith: () => $ZodCheckEndsWith, - $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, - $ZodCheckIncludes: () => $ZodCheckIncludes, - $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, - $ZodCheckLessThan: () => $ZodCheckLessThan, - $ZodCheckLowerCase: () => $ZodCheckLowerCase, - $ZodCheckMaxLength: () => $ZodCheckMaxLength, - $ZodCheckMaxSize: () => $ZodCheckMaxSize, - $ZodCheckMimeType: () => $ZodCheckMimeType, - $ZodCheckMinLength: () => $ZodCheckMinLength, - $ZodCheckMinSize: () => $ZodCheckMinSize, - $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, - $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, - $ZodCheckOverwrite: () => $ZodCheckOverwrite, - $ZodCheckProperty: () => $ZodCheckProperty, - $ZodCheckRegex: () => $ZodCheckRegex, - $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, - $ZodCheckStartsWith: () => $ZodCheckStartsWith, - $ZodCheckStringFormat: () => $ZodCheckStringFormat, - $ZodCheckUpperCase: () => $ZodCheckUpperCase, - $ZodCodec: () => $ZodCodec, - $ZodCustom: () => $ZodCustom, - $ZodCustomStringFormat: () => $ZodCustomStringFormat, - $ZodDate: () => $ZodDate, - $ZodDefault: () => $ZodDefault, - $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, - $ZodE164: () => $ZodE164, - $ZodEmail: () => $ZodEmail, - $ZodEmoji: () => $ZodEmoji, - $ZodEncodeError: () => $ZodEncodeError, - $ZodEnum: () => $ZodEnum, - $ZodError: () => $ZodError, - $ZodExactOptional: () => $ZodExactOptional, - $ZodFile: () => $ZodFile, - $ZodFunction: () => $ZodFunction, - $ZodGUID: () => $ZodGUID, - $ZodIPv4: () => $ZodIPv4, - $ZodIPv6: () => $ZodIPv6, - $ZodISODate: () => $ZodISODate, - $ZodISODateTime: () => $ZodISODateTime, - $ZodISODuration: () => $ZodISODuration, - $ZodISOTime: () => $ZodISOTime, - $ZodIntersection: () => $ZodIntersection, - $ZodJWT: () => $ZodJWT, - $ZodKSUID: () => $ZodKSUID, - $ZodLazy: () => $ZodLazy, - $ZodLiteral: () => $ZodLiteral, - $ZodMAC: () => $ZodMAC, - $ZodMap: () => $ZodMap, - $ZodNaN: () => $ZodNaN, - $ZodNanoID: () => $ZodNanoID, - $ZodNever: () => $ZodNever, - $ZodNonOptional: () => $ZodNonOptional, - $ZodNull: () => $ZodNull, - $ZodNullable: () => $ZodNullable, - $ZodNumber: () => $ZodNumber, - $ZodNumberFormat: () => $ZodNumberFormat, - $ZodObject: () => $ZodObject, - $ZodObjectJIT: () => $ZodObjectJIT, - $ZodOptional: () => $ZodOptional, - $ZodPipe: () => $ZodPipe, - $ZodPrefault: () => $ZodPrefault, - $ZodPromise: () => $ZodPromise, - $ZodReadonly: () => $ZodReadonly, - $ZodRealError: () => $ZodRealError, - $ZodRecord: () => $ZodRecord, - $ZodRegistry: () => $ZodRegistry, - $ZodSet: () => $ZodSet, - $ZodString: () => $ZodString, - $ZodStringFormat: () => $ZodStringFormat, - $ZodSuccess: () => $ZodSuccess, - $ZodSymbol: () => $ZodSymbol, - $ZodTemplateLiteral: () => $ZodTemplateLiteral, - $ZodTransform: () => $ZodTransform, - $ZodTuple: () => $ZodTuple, - $ZodType: () => $ZodType, - $ZodULID: () => $ZodULID, - $ZodURL: () => $ZodURL, - $ZodUUID: () => $ZodUUID, - $ZodUndefined: () => $ZodUndefined, - $ZodUnion: () => $ZodUnion, - $ZodUnknown: () => $ZodUnknown, - $ZodVoid: () => $ZodVoid, - $ZodXID: () => $ZodXID, - $ZodXor: () => $ZodXor, - $brand: () => $brand, - $constructor: () => $constructor, - $input: () => $input, - $output: () => $output, - Doc: () => Doc, - JSONSchema: () => json_schema_exports, - JSONSchemaGenerator: () => JSONSchemaGenerator, - NEVER: () => NEVER, - TimePrecision: () => TimePrecision, - _any: () => _any, - _array: () => _array, - _base64: () => _base64, - _base64url: () => _base64url, - _bigint: () => _bigint, - _boolean: () => _boolean, - _catch: () => _catch, - _check: () => _check, - _cidrv4: () => _cidrv4, - _cidrv6: () => _cidrv6, - _coercedBigint: () => _coercedBigint, - _coercedBoolean: () => _coercedBoolean, - _coercedDate: () => _coercedDate, - _coercedNumber: () => _coercedNumber, - _coercedString: () => _coercedString, - _cuid: () => _cuid, - _cuid2: () => _cuid2, - _custom: () => _custom, - _date: () => _date, - _decode: () => _decode, - _decodeAsync: () => _decodeAsync, - _default: () => _default, - _discriminatedUnion: () => _discriminatedUnion, - _e164: () => _e164, - _email: () => _email, - _emoji: () => _emoji2, - _encode: () => _encode, - _encodeAsync: () => _encodeAsync, - _endsWith: () => _endsWith, - _enum: () => _enum, - _file: () => _file, - _float32: () => _float32, - _float64: () => _float64, - _gt: () => _gt, - _gte: () => _gte, - _guid: () => _guid, - _includes: () => _includes, - _int: () => _int, - _int32: () => _int32, - _int64: () => _int64, - _intersection: () => _intersection, - _ipv4: () => _ipv4, - _ipv6: () => _ipv6, - _isoDate: () => _isoDate, - _isoDateTime: () => _isoDateTime, - _isoDuration: () => _isoDuration, - _isoTime: () => _isoTime, - _jwt: () => _jwt, - _ksuid: () => _ksuid, - _lazy: () => _lazy, - _length: () => _length, - _literal: () => _literal, - _lowercase: () => _lowercase, - _lt: () => _lt, - _lte: () => _lte, - _mac: () => _mac, - _map: () => _map, - _max: () => _lte, - _maxLength: () => _maxLength, - _maxSize: () => _maxSize, - _mime: () => _mime, - _min: () => _gte, - _minLength: () => _minLength, - _minSize: () => _minSize, - _multipleOf: () => _multipleOf, - _nan: () => _nan, - _nanoid: () => _nanoid, - _nativeEnum: () => _nativeEnum, - _negative: () => _negative, - _never: () => _never, - _nonnegative: () => _nonnegative, - _nonoptional: () => _nonoptional, - _nonpositive: () => _nonpositive, - _normalize: () => _normalize, - _null: () => _null2, - _nullable: () => _nullable, - _number: () => _number, - _optional: () => _optional, - _overwrite: () => _overwrite, - _parse: () => _parse, - _parseAsync: () => _parseAsync, - _pipe: () => _pipe, - _positive: () => _positive, - _promise: () => _promise, - _property: () => _property, - _readonly: () => _readonly, - _record: () => _record, - _refine: () => _refine, - _regex: () => _regex, - _safeDecode: () => _safeDecode, - _safeDecodeAsync: () => _safeDecodeAsync, - _safeEncode: () => _safeEncode, - _safeEncodeAsync: () => _safeEncodeAsync, - _safeParse: () => _safeParse, - _safeParseAsync: () => _safeParseAsync, - _set: () => _set, - _size: () => _size, - _slugify: () => _slugify, - _startsWith: () => _startsWith, - _string: () => _string, - _stringFormat: () => _stringFormat, - _stringbool: () => _stringbool, - _success: () => _success, - _superRefine: () => _superRefine, - _symbol: () => _symbol, - _templateLiteral: () => _templateLiteral, - _toLowerCase: () => _toLowerCase, - _toUpperCase: () => _toUpperCase, - _transform: () => _transform, - _trim: () => _trim, - _tuple: () => _tuple, - _uint32: () => _uint32, - _uint64: () => _uint64, - _ulid: () => _ulid, - _undefined: () => _undefined2, - _union: () => _union, - _unknown: () => _unknown, - _uppercase: () => _uppercase, - _url: () => _url, - _uuid: () => _uuid, - _uuidv4: () => _uuidv4, - _uuidv6: () => _uuidv6, - _uuidv7: () => _uuidv7, - _void: () => _void, - _xid: () => _xid, - _xor: () => _xor, - clone: () => clone, - config: () => config, - createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, - createToJSONSchemaMethod: () => createToJSONSchemaMethod, - decode: () => decode, - decodeAsync: () => decodeAsync, - describe: () => describe, - encode: () => encode, - encodeAsync: () => encodeAsync, - extractDefs: () => extractDefs, - finalize: () => finalize, - flattenError: () => flattenError, - formatError: () => formatError, - globalConfig: () => globalConfig, - globalRegistry: () => globalRegistry, - initializeContext: () => initializeContext, - isValidBase64: () => isValidBase64, - isValidBase64URL: () => isValidBase64URL, - isValidJWT: () => isValidJWT, - locales: () => locales_exports, - meta: () => meta, - parse: () => parse, - parseAsync: () => parseAsync, - prettifyError: () => prettifyError, - process: () => process2, - regexes: () => regexes_exports, - registry: () => registry, - safeDecode: () => safeDecode, - safeDecodeAsync: () => safeDecodeAsync, - safeEncode: () => safeEncode, - safeEncodeAsync: () => safeEncodeAsync, - safeParse: () => safeParse, - safeParseAsync: () => safeParseAsync, - toDotPath: () => toDotPath, - toJSONSchema: () => toJSONSchema, - treeifyError: () => treeifyError, - util: () => util_exports, - version: () => version -}); -var init_core2 = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"() { - init_core(); - init_parse(); - init_errors(); - init_schemas(); - init_checks(); - init_versions(); - init_util(); - init_regexes(); - init_locales(); - init_registries(); - init_doc(); - init_api(); - init_to_json_schema(); - init_json_schema_processors(); - init_json_schema_generator(); - init_json_schema(); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js -var checks_exports2 = {}; -__export(checks_exports2, { - endsWith: () => _endsWith, - gt: () => _gt, - gte: () => _gte, - includes: () => _includes, - length: () => _length, - lowercase: () => _lowercase, - lt: () => _lt, - lte: () => _lte, - maxLength: () => _maxLength, - maxSize: () => _maxSize, - mime: () => _mime, - minLength: () => _minLength, - minSize: () => _minSize, - multipleOf: () => _multipleOf, - negative: () => _negative, - nonnegative: () => _nonnegative, - nonpositive: () => _nonpositive, - normalize: () => _normalize, - overwrite: () => _overwrite, - positive: () => _positive, - property: () => _property, - regex: () => _regex, - size: () => _size, - slugify: () => _slugify, - startsWith: () => _startsWith, - toLowerCase: () => _toLowerCase, - toUpperCase: () => _toUpperCase, - trim: () => _trim, - uppercase: () => _uppercase -}); -var init_checks2 = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"() { - init_core2(); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -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({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"() { - 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/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js -var initializer2, ZodError, ZodRealError; -var init_errors2 = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"() { - init_core2(); - init_core2(); - init_util(); - initializer2 = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, - } - }); - }; - ZodError = $constructor("ZodError", initializer2); - ZodRealError = $constructor("ZodError", initializer2, { - Parent: Error - }); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js -var parse2, parseAsync2, safeParse2, safeParseAsync2, encode2, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2; -var init_parse2 = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"() { - init_core2(); - init_errors2(); - parse2 = /* @__PURE__ */ _parse(ZodRealError); - parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); - safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); - safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); - encode2 = /* @__PURE__ */ _encode(ZodRealError); - decode2 = /* @__PURE__ */ _decode(ZodRealError); - encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); - decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); - safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); - safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); - safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); - safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js -var schemas_exports2 = {}; -__export(schemas_exports2, { - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBase64: () => ZodBase64, - ZodBase64URL: () => ZodBase64URL, - ZodBigInt: () => ZodBigInt, - ZodBigIntFormat: () => ZodBigIntFormat, - ZodBoolean: () => ZodBoolean, - ZodCIDRv4: () => ZodCIDRv4, - ZodCIDRv6: () => ZodCIDRv6, - ZodCUID: () => ZodCUID, - ZodCUID2: () => ZodCUID2, - ZodCatch: () => ZodCatch, - ZodCodec: () => ZodCodec, - ZodCustom: () => ZodCustom, - ZodCustomStringFormat: () => ZodCustomStringFormat, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodE164: () => ZodE164, - ZodEmail: () => ZodEmail, - ZodEmoji: () => ZodEmoji, - ZodEnum: () => ZodEnum, - ZodExactOptional: () => ZodExactOptional, - ZodFile: () => ZodFile, - ZodFunction: () => ZodFunction, - ZodGUID: () => ZodGUID, - ZodIPv4: () => ZodIPv4, - ZodIPv6: () => ZodIPv6, - ZodIntersection: () => ZodIntersection, - ZodJWT: () => ZodJWT, - ZodKSUID: () => ZodKSUID, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMAC: () => ZodMAC, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNanoID: () => ZodNanoID, - ZodNever: () => ZodNever, - ZodNonOptional: () => ZodNonOptional, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodNumberFormat: () => ZodNumberFormat, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodPipe: () => ZodPipe, - ZodPrefault: () => ZodPrefault, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodStringFormat: () => ZodStringFormat, - ZodSuccess: () => ZodSuccess, - ZodSymbol: () => ZodSymbol, - ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodTransform: () => ZodTransform, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodULID: () => ZodULID, - ZodURL: () => ZodURL, - ZodUUID: () => ZodUUID, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - ZodXID: () => ZodXID, - ZodXor: () => ZodXor, - _ZodString: () => _ZodString, - _default: () => _default2, - _function: () => _function, - any: () => any, - array: () => array, - base64: () => base642, - base64url: () => base64url2, - bigint: () => bigint2, - boolean: () => boolean2, - catch: () => _catch2, - check: () => check, - cidrv4: () => cidrv42, - cidrv6: () => cidrv62, - codec: () => codec, - cuid: () => cuid3, - cuid2: () => cuid22, - custom: () => custom, - date: () => date3, - describe: () => describe2, - discriminatedUnion: () => discriminatedUnion, - e164: () => e1642, - email: () => email2, - emoji: () => emoji2, - enum: () => _enum2, - exactOptional: () => exactOptional, - file: () => file, - float32: () => float32, - float64: () => float64, - function: () => _function, - guid: () => guid2, - hash: () => hash, - hex: () => hex2, - hostname: () => hostname2, - httpUrl: () => httpUrl, - instanceof: () => _instanceof, - int: () => int, - int32: () => int32, - int64: () => int64, - intersection: () => intersection2, - ipv4: () => ipv42, - ipv6: () => ipv62, - json: () => json, - jwt: () => jwt, - keyof: () => keyof, - ksuid: () => ksuid2, - lazy: () => lazy, - literal: () => literal, - looseObject: () => looseObject, - looseRecord: () => looseRecord, - mac: () => mac2, - map: () => map, - meta: () => meta2, - nan: () => nan, - nanoid: () => nanoid2, - nativeEnum: () => nativeEnum, - never: () => never, - nonoptional: () => nonoptional, - null: () => _null3, - nullable: () => nullable, - nullish: () => nullish2, - number: () => number2, - object: () => object, - optional: () => optional, - partialRecord: () => partialRecord, - pipe: () => pipe, - prefault: () => prefault, - preprocess: () => preprocess, - promise: () => promise, - readonly: () => readonly, - record: () => record, - refine: () => refine, - set: () => set, - strictObject: () => strictObject, - string: () => string2, - stringFormat: () => stringFormat, - stringbool: () => stringbool, - success: () => success, - superRefine: () => superRefine, - symbol: () => symbol, - templateLiteral: () => templateLiteral, - transform: () => transform, - tuple: () => tuple, - uint32: () => uint32, - uint64: () => uint64, - ulid: () => ulid2, - undefined: () => _undefined3, - union: () => union, - unknown: () => unknown, - url: () => url, - uuid: () => uuid2, - uuidv4: () => uuidv4, - uuidv6: () => uuidv6, - uuidv7: () => uuidv7, - void: () => _void2, - xid: () => xid2, - xor: () => xor -}); -function string2(params) { - return _string(ZodString, params); -} -function email2(params) { - return _email(ZodEmail, params); -} -function guid2(params) { - return _guid(ZodGUID, params); -} -function uuid2(params) { - return _uuid(ZodUUID, params); -} -function uuidv4(params) { - return _uuidv4(ZodUUID, params); -} -function uuidv6(params) { - return _uuidv6(ZodUUID, params); -} -function uuidv7(params) { - return _uuidv7(ZodUUID, params); -} -function url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return _url(ZodURL, { - protocol: /^https?$/, - hostname: regexes_exports.domain, - ...util_exports.normalizeParams(params) - }); -} -function emoji2(params) { - return _emoji2(ZodEmoji, params); -} -function nanoid2(params) { - return _nanoid(ZodNanoID, params); -} -function cuid3(params) { - return _cuid(ZodCUID, params); -} -function cuid22(params) { - return _cuid2(ZodCUID2, params); -} -function ulid2(params) { - return _ulid(ZodULID, params); -} -function xid2(params) { - return _xid(ZodXID, params); -} -function ksuid2(params) { - return _ksuid(ZodKSUID, params); -} -function ipv42(params) { - return _ipv4(ZodIPv4, params); -} -function mac2(params) { - return _mac(ZodMAC, params); -} -function ipv62(params) { - return _ipv6(ZodIPv6, params); -} -function cidrv42(params) { - return _cidrv4(ZodCIDRv4, params); -} -function cidrv62(params) { - return _cidrv6(ZodCIDRv6, params); -} -function base642(params) { - return _base64(ZodBase64, params); -} -function base64url2(params) { - return _base64url(ZodBase64URL, params); -} -function e1642(params) { - return _e164(ZodE164, params); -} -function jwt(params) { - return _jwt(ZodJWT, params); -} -function stringFormat(format, fnOrRegex, _params2 = {}) { - return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params2); -} -function hostname2(_params2) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params2); -} -function hex2(_params2) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params2); -} -function hash(alg2, params) { - const enc2 = params?.enc ?? "hex"; - const format = `${alg2}_${enc2}`; - const regex = regexes_exports[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return _stringFormat(ZodCustomStringFormat, format, regex, params); -} -function number2(params) { - return _number(ZodNumber, params); -} -function int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return _float32(ZodNumberFormat, params); -} -function float64(params) { - return _float64(ZodNumberFormat, params); -} -function int32(params) { - return _int32(ZodNumberFormat, params); -} -function uint32(params) { - return _uint32(ZodNumberFormat, params); -} -function boolean2(params) { - return _boolean(ZodBoolean, params); -} -function bigint2(params) { - return _bigint(ZodBigInt, params); -} -function int64(params) { - return _int64(ZodBigIntFormat, params); -} -function uint64(params) { - return _uint64(ZodBigIntFormat, params); -} -function symbol(params) { - return _symbol(ZodSymbol, params); -} -function _undefined3(params) { - return _undefined2(ZodUndefined, params); -} -function _null3(params) { - return _null2(ZodNull, params); -} -function any() { - return _any(ZodAny); -} -function unknown() { - return _unknown(ZodUnknown); -} -function never(params) { - return _never(ZodNever, params); -} -function _void2(params) { - return _void(ZodVoid, params); -} -function date3(params) { - return _date(ZodDate, params); -} -function array(element, params) { - return _array(ZodArray, element, params); -} -function keyof(schema3) { - const shape = schema3._zod.def.shape; - return _enum2(Object.keys(shape)); -} -function object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...util_exports.normalizeParams(params) - }; - return new ZodObject(def); -} -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...util_exports.normalizeParams(params) - }); -} -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...util_exports.normalizeParams(params) - }); -} -function union(options, params) { - return new ZodUnion({ - type: "union", - options, - ...util_exports.normalizeParams(params) - }); -} -function xor(options, params) { - return new ZodXor({ - type: "union", - options, - inclusive: false, - ...util_exports.normalizeParams(params) - }); -} -function discriminatedUnion(discriminator, options, params) { - return new ZodDiscriminatedUnion({ - type: "union", - options, - discriminator, - ...util_exports.normalizeParams(params) - }); -} -function intersection2(left, right) { - return new ZodIntersection({ - type: "intersection", - left, - right - }); -} -function tuple(items, _paramsOrRest, _params2) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params2 : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items, - rest, - ...util_exports.normalizeParams(params) - }); -} -function record(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; - return new ZodRecord({ - type: "record", - keyType: k, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType, - mode: "loose", - ...util_exports.normalizeParams(params) - }); -} -function map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function set(valueType, params) { - return new ZodSet({ - type: "set", - valueType, - ...util_exports.normalizeParams(params) - }); -} -function _enum2(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...util_exports.normalizeParams(params) - }); -} -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...util_exports.normalizeParams(params) - }); -} -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util_exports.normalizeParams(params) - }); -} -function file(params) { - return _file(ZodFile, params); -} -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn - }); -} -function optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType - }); -} -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType - }); -} -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType - }); -} -function nullish2(innerType) { - return optional(nullable(innerType)); -} -function _default2(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); - } - }); -} -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); - } - }); -} -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType, - ...util_exports.normalizeParams(params) - }); -} -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType - }); -} -function _catch2(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); -} -function nan(params) { - return _nan(ZodNaN, params); -} -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out - // ...util.normalizeParams(params), - }); -} -function codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out, - transform: params.decode, - reverseTransform: params.encode - }); -} -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType - }); -} -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util_exports.normalizeParams(params) - }); -} -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter - }); -} -function promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType - }); -} -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), - output: params?.output ?? unknown() - }); -} -function check(fn) { - const ch = new $ZodCheck({ - check: "custom" - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params2) { - return _custom(ZodCustom, fn ?? (() => true), _params2); -} -function refine(fn, _params2 = {}) { - return _refine(ZodCustom, fn, _params2); -} -function superRefine(fn) { - return _superRefine(fn); -} -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util_exports.normalizeParams(params) - }); - inst._zod.bag.Class = cls; - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) { - payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...inst._zod.def.path ?? []] - }); - } - }; - return inst; -} -function json(params) { - const jsonSchema = lazy(() => { - return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); - }); - return jsonSchema; -} -function preprocess(fn, schema3) { - return pipe(transform(fn), schema3); -} -var ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodXor, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodCodec, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodFunction, ZodCustom, describe2, meta2, stringbool; -var init_schemas2 = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"() { - init_core2(); - init_core2(); - init_json_schema_processors(); - init_to_json_schema(); - init_checks2(); - init_iso(); - init_parse2(); - ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { - $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.check = (...checks) => { - return inst.clone(util_exports.mergeDefs(def, { - checks: [ - ...def.checks ?? [], - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { - parent: true - }); - }; - inst.with = inst.check; - inst.clone = (def2, params) => clone(inst, def2, params); - inst.brand = () => inst; - inst.register = (reg, meta3) => { - reg.add(inst, meta3); - return inst; - }; - inst.parse = (data, params) => parse2(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) => encode2(inst, data, params); - inst.decode = (data, params) => decode2(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - inst.refine = (check3, params) => inst.check(refine(check3, params)); - inst.superRefine = (refinement) => inst.check(superRefine(refinement)); - inst.overwrite = (fn) => inst.check(_overwrite(fn)); - inst.optional = () => optional(inst); - inst.exactOptional = () => exactOptional(inst); - inst.nullable = () => nullable(inst); - inst.nullish = () => optional(nullable(inst)); - inst.nonoptional = (params) => nonoptional(inst, params); - inst.array = () => array(inst); - inst.or = (arg) => union([inst, arg]); - inst.and = (arg) => intersection2(inst, arg); - inst.transform = (tx) => pipe(inst, transform(tx)); - inst.default = (def2) => _default2(inst, def2); - inst.prefault = (def2) => prefault(inst, def2); - inst.catch = (params) => _catch2(inst, params); - inst.pipe = (target) => pipe(inst, target); - inst.readonly = () => readonly(inst); - inst.describe = (description) => { - const cl = inst.clone(); - globalRegistry.add(cl, { description }); - return cl; - }; - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); - inst.meta = (...args) => { - if (args.length === 0) { - return globalRegistry.get(inst); - } - const cl = inst.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }; - inst.isOptional = () => inst.safeParse(void 0).success; - inst.isNullable = () => inst.safeParse(null).success; - inst.apply = (fn) => fn(inst); - return inst; - }); - _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - inst.regex = (...args) => inst.check(_regex(...args)); - inst.includes = (...args) => inst.check(_includes(...args)); - inst.startsWith = (...args) => inst.check(_startsWith(...args)); - inst.endsWith = (...args) => inst.check(_endsWith(...args)); - inst.min = (...args) => inst.check(_minLength(...args)); - inst.max = (...args) => inst.check(_maxLength(...args)); - inst.length = (...args) => inst.check(_length(...args)); - inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); - inst.lowercase = (params) => inst.check(_lowercase(params)); - inst.uppercase = (params) => inst.check(_uppercase(params)); - inst.trim = () => inst.check(_trim()); - inst.normalize = (...args) => inst.check(_normalize(...args)); - inst.toLowerCase = () => inst.check(_toLowerCase()); - inst.toUpperCase = () => inst.check(_toUpperCase()); - inst.slugify = () => inst.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)); - }); - ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); - }); - ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { - $ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { - $ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.int = (params) => inst.check(int(params)); - inst.safe = (params) => inst.check(int(params)); - inst.positive = (params) => inst.check(_gt(0, params)); - inst.nonnegative = (params) => inst.check(_gte(0, params)); - inst.negative = (params) => inst.check(_lt(0, params)); - inst.nonpositive = (params) => inst.check(_lte(0, params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - inst.step = (value, params) => inst.check(_multipleOf(value, params)); - inst.finite = () => inst; - 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; - }); - ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); - }); - ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); - }); - ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; - }); - ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { - $ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); - }); - ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { - $ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); - }); - ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { - $ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); - }); - ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); - }); - ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); - }); - ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); - }); - ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); - }); - ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { - $ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); - }); - ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; - }); - ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); - inst.element = def.element; - inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); - inst.nonempty = (params) => inst.check(_minLength(1, params)); - inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); - inst.length = (len, params) => inst.check(_length(len, params)); - inst.unwrap = () => inst.element; - }); - ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); - inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); - inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); - inst.extend = (incoming) => { - return util_exports.extend(inst, incoming); - }; - inst.safeExtend = (incoming) => { - return util_exports.safeExtend(inst, incoming); - }; - inst.merge = (other) => util_exports.merge(inst, other); - inst.pick = (mask) => util_exports.pick(inst, mask); - inst.omit = (mask) => util_exports.omit(inst, mask); - inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]); - inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); - }); - ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); - inst.options = def.options; - }); - ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - $ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); - inst.options = def.options; - }); - ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); - }); - ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); - }); - ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { - $ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); - }); - ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - }); - ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { - $ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); - }); - ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { - $ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); - }); - ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...util_exports.normalizeParams(params), - entries: newEntries - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...util_exports.normalizeParams(params), - entries: newEntries - }); - }; - }); - ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - } - }); - }); - ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { - $ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); - inst.min = (size, params) => inst.check(_minSize(size, params)); - inst.max = (size, params) => inst.check(_maxSize(size, params)); - inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); - }); - ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue2) => { - if (typeof issue2 === "string") { - payload.issues.push(util_exports.issue(issue2, payload.value, def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - payload.issues.push(util_exports.issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - return payload; - }); - } - payload.value = output; - return payload; - }; - }); - ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; - }); - ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { - $ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; - }); - ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { - $ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); - }); - ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); - inst.in = def.in; - inst.out = def.out; - }); - ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - $ZodCodec.init(inst, def); - }); - ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { - $ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); - }); - ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.getter(); - }); - ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { - $ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { - $ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); - }); - ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); - }); - describe2 = describe; - meta2 = meta; - stringbool = (...args) => _stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString - }, ...args); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js -function setErrorMap(map3) { - config({ - customError: map3 - }); -} -function getErrorMap() { - return config().customError; -} -var ZodIssueCode, ZodFirstPartyTypeKind; -var init_compat = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"() { - init_core2(); - init_core2(); - ZodIssueCode = { - invalid_type: "invalid_type", - too_big: "too_big", - too_small: "too_small", - invalid_format: "invalid_format", - not_multiple_of: "not_multiple_of", - unrecognized_keys: "unrecognized_keys", - invalid_union: "invalid_union", - invalid_key: "invalid_key", - invalid_element: "invalid_element", - invalid_value: "invalid_value", - custom: "custom" - }; - /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { - })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js -function detectVersion(schema3, defaultTarget) { - const $schema = schema3.$schema; - if ($schema === "https://json-schema.org/draft/2020-12/schema") { - return "draft-2020-12"; - } - if ($schema === "http://json-schema.org/draft-07/schema#") { - return "draft-7"; - } - if ($schema === "http://json-schema.org/draft-04/schema#") { - return "draft-4"; - } - return defaultTarget ?? "draft-2020-12"; -} -function resolveRef(ref, ctx) { - if (!ref.startsWith("#")) { - throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); - } - const path3 = ref.slice(1).split("/").filter(Boolean); - if (path3.length === 0) { - return ctx.rootSchema; - } - const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; - if (path3[0] === defsKey) { - const key = path3[1]; - if (!key || !ctx.defs[key]) { - throw new Error(`Reference not found: ${ref}`); - } - return ctx.defs[key]; - } - throw new Error(`Reference not found: ${ref}`); -} -function convertBaseSchema(schema3, ctx) { - if (schema3.not !== void 0) { - if (typeof schema3.not === "object" && Object.keys(schema3.not).length === 0) { - return z.never(); - } - throw new Error("not is not supported in Zod (except { not: {} } for never)"); - } - if (schema3.unevaluatedItems !== void 0) { - throw new Error("unevaluatedItems is not supported"); - } - if (schema3.unevaluatedProperties !== void 0) { - throw new Error("unevaluatedProperties is not supported"); - } - if (schema3.if !== void 0 || schema3.then !== void 0 || schema3.else !== void 0) { - throw new Error("Conditional schemas (if/then/else) are not supported"); - } - if (schema3.dependentSchemas !== void 0 || schema3.dependentRequired !== void 0) { - throw new Error("dependentSchemas and dependentRequired are not supported"); - } - if (schema3.$ref) { - const refPath = schema3.$ref; - if (ctx.refs.has(refPath)) { - return ctx.refs.get(refPath); - } - if (ctx.processing.has(refPath)) { - return z.lazy(() => { - if (!ctx.refs.has(refPath)) { - throw new Error(`Circular reference not resolved: ${refPath}`); - } - return ctx.refs.get(refPath); - }); - } - ctx.processing.add(refPath); - const resolved = resolveRef(refPath, ctx); - const zodSchema2 = convertSchema(resolved, ctx); - ctx.refs.set(refPath, zodSchema2); - ctx.processing.delete(refPath); - return zodSchema2; - } - if (schema3.enum !== void 0) { - const enumValues = schema3.enum; - if (ctx.version === "openapi-3.0" && schema3.nullable === true && enumValues.length === 1 && enumValues[0] === null) { - return z.null(); - } - if (enumValues.length === 0) { - return z.never(); - } - if (enumValues.length === 1) { - return z.literal(enumValues[0]); - } - if (enumValues.every((v) => typeof v === "string")) { - return z.enum(enumValues); - } - const literalSchemas = enumValues.map((v) => z.literal(v)); - if (literalSchemas.length < 2) { - return literalSchemas[0]; - } - return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); - } - if (schema3.const !== void 0) { - return z.literal(schema3.const); - } - const type = schema3.type; - if (Array.isArray(type)) { - const typeSchemas = type.map((t) => { - const typeSchema = { ...schema3, type: t }; - return convertBaseSchema(typeSchema, ctx); - }); - if (typeSchemas.length === 0) { - return z.never(); - } - if (typeSchemas.length === 1) { - return typeSchemas[0]; - } - return z.union(typeSchemas); - } - if (!type) { - return z.any(); - } - let zodSchema; - switch (type) { - case "string": { - let stringSchema = z.string(); - if (schema3.format) { - const format = schema3.format; - if (format === "email") { - stringSchema = stringSchema.check(z.email()); - } else if (format === "uri" || format === "uri-reference") { - stringSchema = stringSchema.check(z.url()); - } else if (format === "uuid" || format === "guid") { - stringSchema = stringSchema.check(z.uuid()); - } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); - } else if (format === "date") { - stringSchema = stringSchema.check(z.iso.date()); - } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); - } else if (format === "duration") { - stringSchema = stringSchema.check(z.iso.duration()); - } else if (format === "ipv4") { - stringSchema = stringSchema.check(z.ipv4()); - } else if (format === "ipv6") { - stringSchema = stringSchema.check(z.ipv6()); - } else if (format === "mac") { - stringSchema = stringSchema.check(z.mac()); - } else if (format === "cidr") { - stringSchema = stringSchema.check(z.cidrv4()); - } else if (format === "cidr-v6") { - stringSchema = stringSchema.check(z.cidrv6()); - } else if (format === "base64") { - stringSchema = stringSchema.check(z.base64()); - } else if (format === "base64url") { - stringSchema = stringSchema.check(z.base64url()); - } else if (format === "e164") { - stringSchema = stringSchema.check(z.e164()); - } else if (format === "jwt") { - stringSchema = stringSchema.check(z.jwt()); - } else if (format === "emoji") { - stringSchema = stringSchema.check(z.emoji()); - } else if (format === "nanoid") { - stringSchema = stringSchema.check(z.nanoid()); - } else if (format === "cuid") { - stringSchema = stringSchema.check(z.cuid()); - } else if (format === "cuid2") { - stringSchema = stringSchema.check(z.cuid2()); - } else if (format === "ulid") { - stringSchema = stringSchema.check(z.ulid()); - } else if (format === "xid") { - stringSchema = stringSchema.check(z.xid()); - } else if (format === "ksuid") { - stringSchema = stringSchema.check(z.ksuid()); - } - } - if (typeof schema3.minLength === "number") { - stringSchema = stringSchema.min(schema3.minLength); - } - if (typeof schema3.maxLength === "number") { - stringSchema = stringSchema.max(schema3.maxLength); - } - if (schema3.pattern) { - stringSchema = stringSchema.regex(new RegExp(schema3.pattern)); - } - zodSchema = stringSchema; - break; - } - case "number": - case "integer": { - let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema3.minimum === "number") { - numberSchema = numberSchema.min(schema3.minimum); - } - if (typeof schema3.maximum === "number") { - numberSchema = numberSchema.max(schema3.maximum); - } - if (typeof schema3.exclusiveMinimum === "number") { - numberSchema = numberSchema.gt(schema3.exclusiveMinimum); - } else if (schema3.exclusiveMinimum === true && typeof schema3.minimum === "number") { - numberSchema = numberSchema.gt(schema3.minimum); - } - if (typeof schema3.exclusiveMaximum === "number") { - numberSchema = numberSchema.lt(schema3.exclusiveMaximum); - } else if (schema3.exclusiveMaximum === true && typeof schema3.maximum === "number") { - numberSchema = numberSchema.lt(schema3.maximum); - } - if (typeof schema3.multipleOf === "number") { - numberSchema = numberSchema.multipleOf(schema3.multipleOf); - } - zodSchema = numberSchema; - break; - } - case "boolean": { - zodSchema = z.boolean(); - break; - } - case "null": { - zodSchema = z.null(); - break; - } - case "object": { - const shape = {}; - const properties = schema3.properties || {}; - const requiredSet = new Set(schema3.required || []); - for (const [key, propSchema] of Object.entries(properties)) { - const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema3.propertyNames) { - const keySchema = convertSchema(schema3.propertyNames, ctx); - const valueSchema = schema3.additionalProperties && typeof schema3.additionalProperties === "object" ? convertSchema(schema3.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; - } - if (schema3.patternProperties) { - const patternProps = schema3.patternProperties; - const patternKeys = Object.keys(patternProps); - const looseRecords = []; - for (const pattern of patternKeys) { - const patternValue = convertSchema(patternProps[pattern], ctx); - const keySchema = z.string().regex(new RegExp(pattern)); - looseRecords.push(z.looseRecord(keySchema, patternValue)); - } - const schemasToIntersect = []; - if (Object.keys(shape).length > 0) { - schemasToIntersect.push(z.object(shape).passthrough()); - } - schemasToIntersect.push(...looseRecords); - if (schemasToIntersect.length === 0) { - zodSchema = z.object({}).passthrough(); - } else if (schemasToIntersect.length === 1) { - zodSchema = schemasToIntersect[0]; - } else { - let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]); - for (let i = 2; i < schemasToIntersect.length; i++) { - result = z.intersection(result, schemasToIntersect[i]); - } - zodSchema = result; - } - break; - } - const objectSchema = z.object(shape); - if (schema3.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema3.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema3.additionalProperties, ctx)); - } else { - zodSchema = objectSchema.passthrough(); - } - break; - } - case "array": { - const prefixItems = schema3.prefixItems; - const items = schema3.items; - if (prefixItems && Array.isArray(prefixItems)) { - const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } - if (typeof schema3.minItems === "number") { - zodSchema = zodSchema.check(z.minLength(schema3.minItems)); - } - if (typeof schema3.maxItems === "number") { - zodSchema = zodSchema.check(z.maxLength(schema3.maxItems)); - } - } else if (Array.isArray(items)) { - const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema3.additionalItems && typeof schema3.additionalItems === "object" ? convertSchema(schema3.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } - if (typeof schema3.minItems === "number") { - zodSchema = zodSchema.check(z.minLength(schema3.minItems)); - } - if (typeof schema3.maxItems === "number") { - zodSchema = zodSchema.check(z.maxLength(schema3.maxItems)); - } - } else if (items !== void 0) { - const element = convertSchema(items, ctx); - let arraySchema = z.array(element); - if (typeof schema3.minItems === "number") { - arraySchema = arraySchema.min(schema3.minItems); - } - if (typeof schema3.maxItems === "number") { - arraySchema = arraySchema.max(schema3.maxItems); - } - zodSchema = arraySchema; - } else { - zodSchema = z.array(z.any()); - } - break; - } - default: - throw new Error(`Unsupported type: ${type}`); - } - if (schema3.description) { - zodSchema = zodSchema.describe(schema3.description); - } - if (schema3.default !== void 0) { - zodSchema = zodSchema.default(schema3.default); - } - return zodSchema; -} -function convertSchema(schema3, ctx) { - if (typeof schema3 === "boolean") { - return schema3 ? z.any() : z.never(); - } - let baseSchema = convertBaseSchema(schema3, ctx); - const hasExplicitType = schema3.type || schema3.enum !== void 0 || schema3.const !== void 0; - if (schema3.anyOf && Array.isArray(schema3.anyOf)) { - const options = schema3.anyOf.map((s) => convertSchema(s, ctx)); - const anyOfUnion = z.union(options); - baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion; - } - if (schema3.oneOf && Array.isArray(schema3.oneOf)) { - const options = schema3.oneOf.map((s) => convertSchema(s, ctx)); - const oneOfUnion = z.xor(options); - baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion; - } - if (schema3.allOf && Array.isArray(schema3.allOf)) { - if (schema3.allOf.length === 0) { - baseSchema = hasExplicitType ? baseSchema : z.any(); - } else { - let result = hasExplicitType ? baseSchema : convertSchema(schema3.allOf[0], ctx); - const startIdx = hasExplicitType ? 0 : 1; - for (let i = startIdx; i < schema3.allOf.length; i++) { - result = z.intersection(result, convertSchema(schema3.allOf[i], ctx)); - } - baseSchema = result; - } - } - if (schema3.nullable === true && ctx.version === "openapi-3.0") { - baseSchema = z.nullable(baseSchema); - } - if (schema3.readOnly === true) { - baseSchema = z.readonly(baseSchema); - } - const extraMeta = {}; - const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; - for (const key of coreMetadataKeys) { - if (key in schema3) { - extraMeta[key] = schema3[key]; - } - } - const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; - for (const key of contentMetadataKeys) { - if (key in schema3) { - extraMeta[key] = schema3[key]; - } - } - for (const key of Object.keys(schema3)) { - if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema3[key]; - } - } - if (Object.keys(extraMeta).length > 0) { - ctx.registry.add(baseSchema, extraMeta); - } - return baseSchema; -} -function fromJSONSchema(schema3, params) { - if (typeof schema3 === "boolean") { - return schema3 ? z.any() : z.never(); - } - const version3 = detectVersion(schema3, params?.defaultTarget); - const defs = schema3.$defs || schema3.definitions || {}; - const ctx = { - version: version3, - defs, - refs: /* @__PURE__ */ new Map(), - processing: /* @__PURE__ */ new Set(), - rootSchema: schema3, - registry: params?.registry ?? globalRegistry - }; - return convertSchema(schema3, ctx); -} -var z, RECOGNIZED_KEYS; -var init_from_json_schema = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"() { - init_registries(); - init_checks2(); - init_iso(); - init_schemas2(); - z = { - ...schemas_exports2, - ...checks_exports2, - iso: iso_exports - }; - RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ - // Schema identification - "$schema", - "$ref", - "$defs", - "definitions", - // Core schema keywords - "$id", - "id", - "$comment", - "$anchor", - "$vocabulary", - "$dynamicRef", - "$dynamicAnchor", - // Type - "type", - "enum", - "const", - // Composition - "anyOf", - "oneOf", - "allOf", - "not", - // Object - "properties", - "required", - "additionalProperties", - "patternProperties", - "propertyNames", - "minProperties", - "maxProperties", - // Array - "items", - "prefixItems", - "additionalItems", - "minItems", - "maxItems", - "uniqueItems", - "contains", - "minContains", - "maxContains", - // String - "minLength", - "maxLength", - "pattern", - "format", - // Number - "minimum", - "maximum", - "exclusiveMinimum", - "exclusiveMaximum", - "multipleOf", - // Already handled metadata - "description", - "default", - // Content - "contentEncoding", - "contentMediaType", - "contentSchema", - // Unsupported (error-throwing) - "unevaluatedItems", - "unevaluatedProperties", - "if", - "then", - "else", - "dependentSchemas", - "dependentRequired", - // OpenAPI - "nullable", - "readOnly" - ]); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js -var coerce_exports = {}; -__export(coerce_exports, { - bigint: () => bigint3, - boolean: () => boolean3, - date: () => date4, - number: () => number3, - string: () => string3 -}); -function string3(params) { - return _coercedString(ZodString, params); -} -function number3(params) { - return _coercedNumber(ZodNumber, params); -} -function boolean3(params) { - return _coercedBoolean(ZodBoolean, params); -} -function bigint3(params) { - return _coercedBigint(ZodBigInt, params); -} -function date4(params) { - return _coercedDate(ZodDate, params); -} -var init_coerce = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"() { - init_core2(); - init_schemas2(); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js -var external_exports = {}; -__export(external_exports, { - $brand: () => $brand, - $input: () => $input, - $output: () => $output, - NEVER: () => NEVER, - TimePrecision: () => TimePrecision, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBase64: () => ZodBase64, - ZodBase64URL: () => ZodBase64URL, - ZodBigInt: () => ZodBigInt, - ZodBigIntFormat: () => ZodBigIntFormat, - ZodBoolean: () => ZodBoolean, - ZodCIDRv4: () => ZodCIDRv4, - ZodCIDRv6: () => ZodCIDRv6, - ZodCUID: () => ZodCUID, - ZodCUID2: () => ZodCUID2, - ZodCatch: () => ZodCatch, - ZodCodec: () => ZodCodec, - ZodCustom: () => ZodCustom, - ZodCustomStringFormat: () => ZodCustomStringFormat, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodE164: () => ZodE164, - ZodEmail: () => ZodEmail, - ZodEmoji: () => ZodEmoji, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodExactOptional: () => ZodExactOptional, - ZodFile: () => ZodFile, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodGUID: () => ZodGUID, - ZodIPv4: () => ZodIPv4, - ZodIPv6: () => ZodIPv6, - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodJWT: () => ZodJWT, - ZodKSUID: () => ZodKSUID, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMAC: () => ZodMAC, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNanoID: () => ZodNanoID, - ZodNever: () => ZodNever, - ZodNonOptional: () => ZodNonOptional, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodNumberFormat: () => ZodNumberFormat, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodPipe: () => ZodPipe, - ZodPrefault: () => ZodPrefault, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRealError: () => ZodRealError, - ZodRecord: () => ZodRecord, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodStringFormat: () => ZodStringFormat, - ZodSuccess: () => ZodSuccess, - ZodSymbol: () => ZodSymbol, - ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodTransform: () => ZodTransform, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodULID: () => ZodULID, - ZodURL: () => ZodURL, - ZodUUID: () => ZodUUID, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - ZodXID: () => ZodXID, - ZodXor: () => ZodXor, - _ZodString: () => _ZodString, - _default: () => _default2, - _function: () => _function, - any: () => any, - array: () => array, - base64: () => base642, - base64url: () => base64url2, - bigint: () => bigint2, - boolean: () => boolean2, - catch: () => _catch2, - check: () => check, - cidrv4: () => cidrv42, - cidrv6: () => cidrv62, - clone: () => clone, - codec: () => codec, - coerce: () => coerce_exports, - config: () => config, - core: () => core_exports2, - cuid: () => cuid3, - cuid2: () => cuid22, - custom: () => custom, - date: () => date3, - decode: () => decode2, - decodeAsync: () => decodeAsync2, - describe: () => describe2, - discriminatedUnion: () => discriminatedUnion, - e164: () => e1642, - email: () => email2, - emoji: () => emoji2, - encode: () => encode2, - encodeAsync: () => encodeAsync2, - endsWith: () => _endsWith, - enum: () => _enum2, - exactOptional: () => exactOptional, - file: () => file, - flattenError: () => flattenError, - float32: () => float32, - float64: () => float64, - formatError: () => formatError, - fromJSONSchema: () => fromJSONSchema, - function: () => _function, - getErrorMap: () => getErrorMap, - globalRegistry: () => globalRegistry, - gt: () => _gt, - gte: () => _gte, - guid: () => guid2, - hash: () => hash, - hex: () => hex2, - hostname: () => hostname2, - httpUrl: () => httpUrl, - includes: () => _includes, - instanceof: () => _instanceof, - int: () => int, - int32: () => int32, - int64: () => int64, - intersection: () => intersection2, - ipv4: () => ipv42, - ipv6: () => ipv62, - iso: () => iso_exports, - json: () => json, - jwt: () => jwt, - keyof: () => keyof, - ksuid: () => ksuid2, - lazy: () => lazy, - length: () => _length, - literal: () => literal, - locales: () => locales_exports, - looseObject: () => looseObject, - looseRecord: () => looseRecord, - lowercase: () => _lowercase, - lt: () => _lt, - lte: () => _lte, - mac: () => mac2, - map: () => map, - maxLength: () => _maxLength, - maxSize: () => _maxSize, - meta: () => meta2, - mime: () => _mime, - minLength: () => _minLength, - minSize: () => _minSize, - multipleOf: () => _multipleOf, - nan: () => nan, - nanoid: () => nanoid2, - nativeEnum: () => nativeEnum, - negative: () => _negative, - never: () => never, - nonnegative: () => _nonnegative, - nonoptional: () => nonoptional, - nonpositive: () => _nonpositive, - normalize: () => _normalize, - null: () => _null3, - nullable: () => nullable, - nullish: () => nullish2, - number: () => number2, - object: () => object, - optional: () => optional, - overwrite: () => _overwrite, - parse: () => parse2, - parseAsync: () => parseAsync2, - partialRecord: () => partialRecord, - pipe: () => pipe, - positive: () => _positive, - prefault: () => prefault, - preprocess: () => preprocess, - prettifyError: () => prettifyError, - promise: () => promise, - property: () => _property, - readonly: () => readonly, - record: () => record, - refine: () => refine, - regex: () => _regex, - regexes: () => regexes_exports, - registry: () => registry, - safeDecode: () => safeDecode2, - safeDecodeAsync: () => safeDecodeAsync2, - safeEncode: () => safeEncode2, - safeEncodeAsync: () => safeEncodeAsync2, - safeParse: () => safeParse2, - safeParseAsync: () => safeParseAsync2, - set: () => set, - setErrorMap: () => setErrorMap, - size: () => _size, - slugify: () => _slugify, - startsWith: () => _startsWith, - strictObject: () => strictObject, - string: () => string2, - stringFormat: () => stringFormat, - stringbool: () => stringbool, - success: () => success, - superRefine: () => superRefine, - symbol: () => symbol, - templateLiteral: () => templateLiteral, - toJSONSchema: () => toJSONSchema, - toLowerCase: () => _toLowerCase, - toUpperCase: () => _toUpperCase, - transform: () => transform, - treeifyError: () => treeifyError, - trim: () => _trim, - tuple: () => tuple, - uint32: () => uint32, - uint64: () => uint64, - ulid: () => ulid2, - undefined: () => _undefined3, - union: () => union, - unknown: () => unknown, - uppercase: () => _uppercase, - url: () => url, - util: () => util_exports, - uuid: () => uuid2, - uuidv4: () => uuidv4, - uuidv6: () => uuidv6, - uuidv7: () => uuidv7, - void: () => _void2, - xid: () => xid2, - xor: () => xor -}); -var init_external = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"() { - init_core2(); - init_schemas2(); - init_checks2(); - init_errors2(); - init_parse2(); - init_compat(); - init_core2(); - init_en(); - init_core2(); - init_json_schema_processors(); - init_from_json_schema(); - init_locales(); - init_iso(); - init_iso(); - init_coerce(); - config(en_default()); - } -}); - -// ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js -var zod_exports = {}; -__export(zod_exports, { - $brand: () => $brand, - $input: () => $input, - $output: () => $output, - NEVER: () => NEVER, - TimePrecision: () => TimePrecision, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBase64: () => ZodBase64, - ZodBase64URL: () => ZodBase64URL, - ZodBigInt: () => ZodBigInt, - ZodBigIntFormat: () => ZodBigIntFormat, - ZodBoolean: () => ZodBoolean, - ZodCIDRv4: () => ZodCIDRv4, - ZodCIDRv6: () => ZodCIDRv6, - ZodCUID: () => ZodCUID, - ZodCUID2: () => ZodCUID2, - ZodCatch: () => ZodCatch, - ZodCodec: () => ZodCodec, - ZodCustom: () => ZodCustom, - ZodCustomStringFormat: () => ZodCustomStringFormat, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodE164: () => ZodE164, - ZodEmail: () => ZodEmail, - ZodEmoji: () => ZodEmoji, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodExactOptional: () => ZodExactOptional, - ZodFile: () => ZodFile, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodGUID: () => ZodGUID, - ZodIPv4: () => ZodIPv4, - ZodIPv6: () => ZodIPv6, - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodJWT: () => ZodJWT, - ZodKSUID: () => ZodKSUID, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMAC: () => ZodMAC, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNanoID: () => ZodNanoID, - ZodNever: () => ZodNever, - ZodNonOptional: () => ZodNonOptional, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodNumberFormat: () => ZodNumberFormat, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodPipe: () => ZodPipe, - ZodPrefault: () => ZodPrefault, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRealError: () => ZodRealError, - ZodRecord: () => ZodRecord, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodStringFormat: () => ZodStringFormat, - ZodSuccess: () => ZodSuccess, - ZodSymbol: () => ZodSymbol, - ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodTransform: () => ZodTransform, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodULID: () => ZodULID, - ZodURL: () => ZodURL, - ZodUUID: () => ZodUUID, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - ZodXID: () => ZodXID, - ZodXor: () => ZodXor, - _ZodString: () => _ZodString, - _default: () => _default2, - _function: () => _function, - any: () => any, - array: () => array, - base64: () => base642, - base64url: () => base64url2, - bigint: () => bigint2, - boolean: () => boolean2, - catch: () => _catch2, - check: () => check, - cidrv4: () => cidrv42, - cidrv6: () => cidrv62, - clone: () => clone, - codec: () => codec, - coerce: () => coerce_exports, - config: () => config, - core: () => core_exports2, - cuid: () => cuid3, - cuid2: () => cuid22, - custom: () => custom, - date: () => date3, - decode: () => decode2, - decodeAsync: () => decodeAsync2, - default: () => zod_default, - describe: () => describe2, - discriminatedUnion: () => discriminatedUnion, - e164: () => e1642, - email: () => email2, - emoji: () => emoji2, - encode: () => encode2, - encodeAsync: () => encodeAsync2, - endsWith: () => _endsWith, - enum: () => _enum2, - exactOptional: () => exactOptional, - file: () => file, - flattenError: () => flattenError, - float32: () => float32, - float64: () => float64, - formatError: () => formatError, - fromJSONSchema: () => fromJSONSchema, - function: () => _function, - getErrorMap: () => getErrorMap, - globalRegistry: () => globalRegistry, - gt: () => _gt, - gte: () => _gte, - guid: () => guid2, - hash: () => hash, - hex: () => hex2, - hostname: () => hostname2, - httpUrl: () => httpUrl, - includes: () => _includes, - instanceof: () => _instanceof, - int: () => int, - int32: () => int32, - int64: () => int64, - intersection: () => intersection2, - ipv4: () => ipv42, - ipv6: () => ipv62, - iso: () => iso_exports, - json: () => json, - jwt: () => jwt, - keyof: () => keyof, - ksuid: () => ksuid2, - lazy: () => lazy, - length: () => _length, - literal: () => literal, - locales: () => locales_exports, - looseObject: () => looseObject, - looseRecord: () => looseRecord, - lowercase: () => _lowercase, - lt: () => _lt, - lte: () => _lte, - mac: () => mac2, - map: () => map, - maxLength: () => _maxLength, - maxSize: () => _maxSize, - meta: () => meta2, - mime: () => _mime, - minLength: () => _minLength, - minSize: () => _minSize, - multipleOf: () => _multipleOf, - nan: () => nan, - nanoid: () => nanoid2, - nativeEnum: () => nativeEnum, - negative: () => _negative, - never: () => never, - nonnegative: () => _nonnegative, - nonoptional: () => nonoptional, - nonpositive: () => _nonpositive, - normalize: () => _normalize, - null: () => _null3, - nullable: () => nullable, - nullish: () => nullish2, - number: () => number2, - object: () => object, - optional: () => optional, - overwrite: () => _overwrite, - parse: () => parse2, - parseAsync: () => parseAsync2, - partialRecord: () => partialRecord, - pipe: () => pipe, - positive: () => _positive, - prefault: () => prefault, - preprocess: () => preprocess, - prettifyError: () => prettifyError, - promise: () => promise, - property: () => _property, - readonly: () => readonly, - record: () => record, - refine: () => refine, - regex: () => _regex, - regexes: () => regexes_exports, - registry: () => registry, - safeDecode: () => safeDecode2, - safeDecodeAsync: () => safeDecodeAsync2, - safeEncode: () => safeEncode2, - safeEncodeAsync: () => safeEncodeAsync2, - safeParse: () => safeParse2, - safeParseAsync: () => safeParseAsync2, - set: () => set, - setErrorMap: () => setErrorMap, - size: () => _size, - slugify: () => _slugify, - startsWith: () => _startsWith, - strictObject: () => strictObject, - string: () => string2, - stringFormat: () => stringFormat, - stringbool: () => stringbool, - success: () => success, - superRefine: () => superRefine, - symbol: () => symbol, - templateLiteral: () => templateLiteral, - toJSONSchema: () => toJSONSchema, - toLowerCase: () => _toLowerCase, - toUpperCase: () => _toUpperCase, - transform: () => transform, - treeifyError: () => treeifyError, - trim: () => _trim, - tuple: () => tuple, - uint32: () => uint32, - uint64: () => uint64, - ulid: () => ulid2, - undefined: () => _undefined3, - union: () => union, - unknown: () => unknown, - uppercase: () => _uppercase, - url: () => url, - util: () => util_exports, - uuid: () => uuid2, - uuidv4: () => uuidv4, - uuidv6: () => uuidv6, - uuidv7: () => uuidv7, - void: () => _void2, - xid: () => xid2, - xor: () => xor, - z: () => external_exports -}); -var zod_default; -var init_zod = __esm({ - "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js"() { - init_external(); - init_external(); - zod_default = external_exports; - } -}); - -// ../../packages/spec/dist/data/index.mjs -var data_exports = {}; -__export(data_exports, { - ALL_OPERATORS: () => ALL_OPERATORS, - AddressSchema: () => AddressSchema, - AggregationFunction: () => AggregationFunction2, - AggregationMetricType: () => AggregationMetricType2, - AggregationNodeSchema: () => AggregationNodeSchema2, - AggregationPipelineSchema: () => AggregationPipelineSchema, - AggregationStageSchema: () => AggregationStageSchema, - AnalyticsQuerySchema: () => AnalyticsQuerySchema2, - ApiMethod: () => ApiMethod3, - AsyncValidationSchema: () => AsyncValidationSchema3, - BaseEngineOptionsSchema: () => BaseEngineOptionsSchema, - CDCConfigSchema: () => CDCConfigSchema3, - ComparisonOperatorSchema: () => ComparisonOperatorSchema, - ComputedFieldCacheSchema: () => ComputedFieldCacheSchema3, - ConditionalValidationSchema: () => ConditionalValidationSchema3, - ConsistencyLevelSchema: () => ConsistencyLevelSchema, - CrossFieldValidationSchema: () => CrossFieldValidationSchema3, - CubeJoinSchema: () => CubeJoinSchema2, - CubeSchema: () => CubeSchema2, - CurrencyConfigSchema: () => CurrencyConfigSchema3, - CurrencyValueSchema: () => CurrencyValueSchema, - CustomValidatorSchema: () => CustomValidatorSchema3, - DataEngineAggregateOptionsSchema: () => DataEngineAggregateOptionsSchema, - DataEngineAggregateRequestSchema: () => DataEngineAggregateRequestSchema, - DataEngineBatchRequestSchema: () => DataEngineBatchRequestSchema, - DataEngineContractSchema: () => DataEngineContractSchema, - DataEngineCountOptionsSchema: () => DataEngineCountOptionsSchema, - DataEngineCountRequestSchema: () => DataEngineCountRequestSchema, - DataEngineDeleteOptionsSchema: () => DataEngineDeleteOptionsSchema, - DataEngineDeleteRequestSchema: () => DataEngineDeleteRequestSchema, - DataEngineExecuteRequestSchema: () => DataEngineExecuteRequestSchema, - DataEngineFilterSchema: () => DataEngineFilterSchema, - DataEngineFindOneRequestSchema: () => DataEngineFindOneRequestSchema, - DataEngineFindRequestSchema: () => DataEngineFindRequestSchema, - DataEngineInsertOptionsSchema: () => DataEngineInsertOptionsSchema, - DataEngineInsertRequestSchema: () => DataEngineInsertRequestSchema, - DataEngineQueryOptionsSchema: () => DataEngineQueryOptionsSchema, - DataEngineRequestSchema: () => DataEngineRequestSchema, - DataEngineSortSchema: () => DataEngineSortSchema, - DataEngineUpdateOptionsSchema: () => DataEngineUpdateOptionsSchema, - DataEngineUpdateRequestSchema: () => DataEngineUpdateRequestSchema, - DataEngineVectorFindRequestSchema: () => DataEngineVectorFindRequestSchema, - DataQualityRulesSchema: () => DataQualityRulesSchema3, - DataTypeMappingSchema: () => DataTypeMappingSchema, - DatasetLoadResultSchema: () => DatasetLoadResultSchema, - DatasetMode: () => DatasetMode2, - DatasetSchema: () => DatasetSchema2, - DatasourceCapabilities: () => DatasourceCapabilities, - DatasourceSchema: () => DatasourceSchema, - DimensionSchema: () => DimensionSchema2, - DimensionType: () => DimensionType2, - DocumentSchema: () => DocumentSchema, - DocumentSchemaValidationSchema: () => DocumentSchemaValidationSchema, - DocumentTemplateSchema: () => DocumentTemplateSchema, - DocumentVersionSchema: () => DocumentVersionSchema, - DriverCapabilitiesSchema: () => DriverCapabilitiesSchema, - DriverConfigSchema: () => DriverConfigSchema, - DriverDefinitionSchema: () => DriverDefinitionSchema, - DriverInterfaceSchema: () => DriverInterfaceSchema, - DriverOptionsSchema: () => DriverOptionsSchema, - DriverType: () => DriverType, - ESignatureConfigSchema: () => ESignatureConfigSchema, - EngineAggregateOptionsSchema: () => EngineAggregateOptionsSchema, - EngineCountOptionsSchema: () => EngineCountOptionsSchema, - EngineDeleteOptionsSchema: () => EngineDeleteOptionsSchema, - EngineQueryOptionsSchema: () => EngineQueryOptionsSchema, - EngineUpdateOptionsSchema: () => EngineUpdateOptionsSchema, - EqualityOperatorSchema: () => EqualityOperatorSchema, - ExternalDataSourceSchema: () => ExternalDataSourceSchema, - ExternalFieldMappingSchema: () => ExternalFieldMappingSchema, - ExternalLookupSchema: () => ExternalLookupSchema, - FILTER_OPERATORS: () => FILTER_OPERATORS, - FeedActorSchema: () => FeedActorSchema2, - FeedFilterMode: () => FeedFilterMode, - FeedItemSchema: () => FeedItemSchema2, - FeedItemType: () => FeedItemType2, - FeedVisibility: () => FeedVisibility2, - Field: () => Field, - FieldChangeEntrySchema: () => FieldChangeEntrySchema2, - FieldMappingSchema: () => FieldMappingSchema, - FieldNodeSchema: () => FieldNodeSchema2, - FieldOperatorsSchema: () => FieldOperatorsSchema2, - FieldReferenceSchema: () => FieldReferenceSchema2, - FieldSchema: () => FieldSchema3, - FieldType: () => FieldType3, - FileAttachmentConfigSchema: () => FileAttachmentConfigSchema3, - FilterConditionSchema: () => FilterConditionSchema2, - FormatValidationSchema: () => FormatValidationSchema3, - FullTextSearchSchema: () => FullTextSearchSchema2, - HookContextSchema: () => HookContextSchema, - HookEvent: () => HookEvent, - HookSchema: () => HookSchema, - IndexSchema: () => IndexSchema3, - JSONValidationSchema: () => JSONValidationSchema3, - JoinNodeSchema: () => JoinNodeSchema2, - JoinStrategy: () => JoinStrategy2, - JoinType: () => JoinType2, - LOGICAL_OPERATORS: () => LOGICAL_OPERATORS, - LocationCoordinatesSchema: () => LocationCoordinatesSchema, - MappingSchema: () => MappingSchema, - MentionSchema: () => MentionSchema2, - MetricSchema: () => MetricSchema2, - NoSQLDataTypeMappingSchema: () => NoSQLDataTypeMappingSchema, - NoSQLDatabaseTypeSchema: () => NoSQLDatabaseTypeSchema, - NoSQLDriverConfigSchema: () => NoSQLDriverConfigSchema, - NoSQLIndexSchema: () => NoSQLIndexSchema, - NoSQLIndexTypeSchema: () => NoSQLIndexTypeSchema, - NoSQLOperationTypeSchema: () => NoSQLOperationTypeSchema, - NoSQLQueryOptionsSchema: () => NoSQLQueryOptionsSchema, - NoSQLTransactionOptionsSchema: () => NoSQLTransactionOptionsSchema, - NormalizedFilterSchema: () => NormalizedFilterSchema2, - NotificationChannel: () => NotificationChannel2, - ObjectCapabilities: () => ObjectCapabilities3, - ObjectDependencyGraphSchema: () => ObjectDependencyGraphSchema, - ObjectDependencyNodeSchema: () => ObjectDependencyNodeSchema, - ObjectExtensionSchema: () => ObjectExtensionSchema, - ObjectOwnershipEnum: () => ObjectOwnershipEnum, - ObjectSchema: () => ObjectSchema3, - PartitioningConfigSchema: () => PartitioningConfigSchema3, - PoolConfigSchema: () => PoolConfigSchema, - QueryFilterSchema: () => QueryFilterSchema, - QuerySchema: () => QuerySchema2, - RangeOperatorSchema: () => RangeOperatorSchema, - ReactionSchema: () => ReactionSchema2, - RecordSubscriptionSchema: () => RecordSubscriptionSchema2, - ReferenceResolutionErrorSchema: () => ReferenceResolutionErrorSchema, - ReferenceResolutionSchema: () => ReferenceResolutionSchema, - ReplicationConfigSchema: () => ReplicationConfigSchema, - SQLDialectSchema: () => SQLDialectSchema, - SQLDriverConfigSchema: () => SQLDriverConfigSchema, - SQLiteAlterTableLimitations: () => SQLiteAlterTableLimitations, - SQLiteDataTypeMappingDefaults: () => SQLiteDataTypeMappingDefaults, - SSLConfigSchema: () => SSLConfigSchema, - ScriptValidationSchema: () => ScriptValidationSchema3, - SearchConfigSchema: () => SearchConfigSchema4, - SeedLoaderConfigSchema: () => SeedLoaderConfigSchema, - SeedLoaderRequestSchema: () => SeedLoaderRequestSchema, - SeedLoaderResultSchema: () => SeedLoaderResultSchema, - SelectOptionSchema: () => SelectOptionSchema3, - SetOperatorSchema: () => SetOperatorSchema, - ShardingConfigSchema: () => ShardingConfigSchema, - SoftDeleteConfigSchema: () => SoftDeleteConfigSchema3, - SortNodeSchema: () => SortNodeSchema2, - SpecialOperatorSchema: () => SpecialOperatorSchema, - StateMachineValidationSchema: () => StateMachineValidationSchema3, - StringOperatorSchema: () => StringOperatorSchema, - SubscriptionEventType: () => SubscriptionEventType2, - TenancyConfigSchema: () => TenancyConfigSchema3, - TenantDatabaseLifecycleSchema: () => TenantDatabaseLifecycleSchema, - TenantResolverStrategySchema: () => TenantResolverStrategySchema, - TimeUpdateInterval: () => TimeUpdateInterval2, - TransformType: () => TransformType, - TursoGroupSchema: () => TursoGroupSchema, - TursoMultiTenantConfigSchema: () => TursoMultiTenantConfigSchema, - UniquenessValidationSchema: () => UniquenessValidationSchema3, - VALID_AST_OPERATORS: () => VALID_AST_OPERATORS, - ValidationRuleSchema: () => ValidationRuleSchema3, - VectorConfigSchema: () => VectorConfigSchema3, - VersioningConfigSchema: () => VersioningConfigSchema3, - WindowFunction: () => WindowFunction2, - WindowFunctionNodeSchema: () => WindowFunctionNodeSchema2, - WindowSpecSchema: () => WindowSpecSchema2, - isFilterAST: () => isFilterAST, - parseFilterAST: () => parseFilterAST -}); -function isFilterAST(filter) { - if (!Array.isArray(filter) || filter.length === 0) return false; - const first = filter[0]; - if (typeof first === "string") { - const lower = first.toLowerCase(); - if (lower === "and" || lower === "or") { - return filter.length >= 2 && filter.slice(1).every((child) => isFilterAST(child)); - } - if (filter.length >= 2 && typeof filter[1] === "string") { - return VALID_AST_OPERATORS.has(filter[1].toLowerCase()); - } - } - if (filter.every((item) => isFilterAST(item))) { - return filter.length > 0; - } - return false; -} -function convertComparison(node) { - const [field, operator, value] = node; - const op = operator.toLowerCase(); - if (op === "=" || op === "==") { - return { [field]: value }; - } - if (op === "is_null") { - return { [field]: { $null: true } }; - } - if (op === "is_not_null") { - return { [field]: { $null: false } }; - } - const mapped = AST_OPERATOR_MAP[op]; - if (mapped) { - return { [field]: { [mapped]: value } }; - } - return { [field]: { [`$${op}`]: value } }; -} -function parseFilterAST(filter) { - if (filter == null) return void 0; - if (!Array.isArray(filter)) return filter; - if (filter.length === 0) return void 0; - const first = filter[0]; - if (typeof first === "string" && (first.toLowerCase() === "and" || first.toLowerCase() === "or")) { - const logicOp = `$${first.toLowerCase()}`; - const children = filter.slice(1).map((child) => parseFilterAST(child)).filter(Boolean); - if (children.length === 0) return void 0; - if (children.length === 1) return children[0]; - return { [logicOp]: children }; - } - if (filter.length >= 2 && typeof first === "string") { - return convertComparison(filter); - } - if (filter.every((item) => Array.isArray(item))) { - const children = filter.map((child) => parseFilterAST(child)).filter(Boolean); - if (children.length === 0) return void 0; - if (children.length === 1) return children[0]; - return { $and: children }; - } - return void 0; -} -function snakeCaseToLabel3(name) { - return name.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); -} -var FieldReferenceSchema2, EqualityOperatorSchema, ComparisonOperatorSchema, SetOperatorSchema, RangeOperatorSchema, StringOperatorSchema, SpecialOperatorSchema, FieldOperatorsSchema2, FilterConditionSchema2, QueryFilterSchema, NormalizedFilterSchema2, VALID_AST_OPERATORS, AST_OPERATOR_MAP, FILTER_OPERATORS, LOGICAL_OPERATORS, ALL_OPERATORS, SortNodeSchema2, AggregationFunction2, AggregationNodeSchema2, JoinType2, JoinStrategy2, JoinNodeSchema2, WindowFunction2, WindowSpecSchema2, WindowFunctionNodeSchema2, FieldNodeSchema2, FullTextSearchSchema2, BaseQuerySchema2, QuerySchema2, SystemIdentifierSchema3, SnakeCaseIdentifierSchema3, EncryptionAlgorithmSchema3, KeyManagementProviderSchema3, KeyRotationPolicySchema3, EncryptionConfigSchema3, MaskingStrategySchema3, MaskingRuleSchema3, FieldType3, SelectOptionSchema3, LocationCoordinatesSchema, CurrencyConfigSchema3, CurrencyValueSchema, AddressSchema, VectorConfigSchema3, FileAttachmentConfigSchema3, DataQualityRulesSchema3, ComputedFieldCacheSchema3, FieldSchema3, Field, BaseValidationSchema3, ScriptValidationSchema3, UniquenessValidationSchema3, StateMachineValidationSchema3, FormatValidationSchema3, CrossFieldValidationSchema3, JSONValidationSchema3, AsyncValidationSchema3, CustomValidatorSchema3, ValidationRuleSchema3, ConditionalValidationSchema3, ActionRefSchema3, GuardRefSchema3, TransitionSchema3, StateNodeSchema3, StateMachineSchema3, I18nLabelSchema3, AriaPropsSchema3, NumberFormatSchema3, DateFormatSchema3, ActionParamSchema3, ActionType3, TARGET_REQUIRED_TYPES3, ActionSchema3, ApiMethod3, ObjectCapabilities3, IndexSchema3, SearchConfigSchema4, TenancyConfigSchema3, SoftDeleteConfigSchema3, VersioningConfigSchema3, PartitioningConfigSchema3, CDCConfigSchema3, ObjectSchemaBase3, ObjectSchema3, ObjectOwnershipEnum, ObjectExtensionSchema, HookEvent, HookSchema, HookContextSchema, TransformType, FieldMappingSchema, MappingSchema, ExecutionContextSchema, DataEngineFilterSchema, DataEngineSortSchema, BaseEngineOptionsSchema, EngineQueryOptionsSchema, DataEngineQueryOptionsSchema, DataEngineInsertOptionsSchema, EngineUpdateOptionsSchema, DataEngineUpdateOptionsSchema, EngineDeleteOptionsSchema, DataEngineDeleteOptionsSchema, EngineAggregateOptionsSchema, DataEngineAggregateOptionsSchema, EngineCountOptionsSchema, DataEngineCountOptionsSchema, DataEngineContractSchema, RpcLegacyFilterMixin, RpcQueryOptionsSchema, DataEngineFindRequestSchema, DataEngineFindOneRequestSchema, DataEngineInsertRequestSchema, DataEngineUpdateRequestSchema, DataEngineDeleteRequestSchema, DataEngineCountRequestSchema, DataEngineAggregateRequestSchema, DataEngineExecuteRequestSchema, DataEngineVectorFindRequestSchema, DataEngineBatchRequestSchema, DataEngineRequestSchema, SortDirectionEnum, IsolationLevelEnum, DriverOptionsSchema, DriverCapabilitiesSchema, DriverInterfaceSchema, PoolConfigSchema, DriverConfigSchema, SQLDialectSchema, DataTypeMappingSchema, SSLConfigSchema, SQLDriverConfigSchema, SQLiteDataTypeMappingDefaults, SQLiteAlterTableLimitations, NoSQLDatabaseTypeSchema, NoSQLOperationTypeSchema, ConsistencyLevelSchema, NoSQLIndexTypeSchema, ShardingConfigSchema, ReplicationConfigSchema, DocumentSchemaValidationSchema, NoSQLDataTypeMappingSchema, NoSQLDriverConfigSchema, NoSQLQueryOptionsSchema, AggregationStageSchema, AggregationPipelineSchema, NoSQLIndexSchema, NoSQLTransactionOptionsSchema, DatasetMode2, DatasetSchema2, ReferenceResolutionSchema, ObjectDependencyNodeSchema, ObjectDependencyGraphSchema, ReferenceResolutionErrorSchema, SeedLoaderConfigSchema, DatasetLoadResultSchema, SeedLoaderResultSchema, SeedLoaderRequestSchema, DocumentVersionSchema, DocumentTemplateSchema, ESignatureConfigSchema, DocumentSchema, TransformTypeSchema, FieldMappingSchema2, ExternalDataSourceSchema, ExternalFieldMappingSchema, ExternalLookupSchema, DriverType, DriverDefinitionSchema, DatasourceCapabilities, DatasourceSchema, AggregationMetricType2, DimensionType2, TimeUpdateInterval2, MetricSchema2, DimensionSchema2, CubeJoinSchema2, CubeSchema2, AnalyticsQuerySchema2, FeedItemType2, MentionSchema2, FieldChangeEntrySchema2, ReactionSchema2, FeedActorSchema2, FeedVisibility2, FeedItemSchema2, FeedFilterMode, SubscriptionEventType2, NotificationChannel2, RecordSubscriptionSchema2, TenantResolverStrategySchema, TursoGroupSchema, TenantDatabaseLifecycleSchema, TursoMultiTenantConfigSchema; -var init_data = __esm({ - "../../packages/spec/dist/data/index.mjs"() { - "use strict"; - init_zod(); - FieldReferenceSchema2 = external_exports.object({ - $field: external_exports.string().describe("Field Reference/Column Name") - }); - EqualityOperatorSchema = external_exports.object({ - /** Equal to (default) - SQL: = | MongoDB: $eq */ - $eq: external_exports.any().optional(), - /** Not equal to - SQL: <> or != | MongoDB: $ne */ - $ne: external_exports.any().optional() - }); - ComparisonOperatorSchema = external_exports.object({ - /** Greater than - SQL: > | MongoDB: $gt */ - $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), - /** Greater than or equal to - SQL: >= | MongoDB: $gte */ - $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), - /** Less than - SQL: < | MongoDB: $lt */ - $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), - /** Less than or equal to - SQL: <= | MongoDB: $lte */ - $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional() - }); - SetOperatorSchema = external_exports.object({ - /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */ - $in: external_exports.array(external_exports.any()).optional(), - /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */ - $nin: external_exports.array(external_exports.any()).optional() - }); - RangeOperatorSchema = external_exports.object({ - /** Between (inclusive) - takes [min, max] array */ - $between: external_exports.tuple([ - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]), - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]) - ]).optional() - }); - StringOperatorSchema = external_exports.object({ - /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */ - $contains: external_exports.string().optional(), - /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */ - $notContains: external_exports.string().optional(), - /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */ - $startsWith: external_exports.string().optional(), - /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */ - $endsWith: external_exports.string().optional() - }); - SpecialOperatorSchema = external_exports.object({ - /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */ - $null: external_exports.boolean().optional(), - /** Field exists check (primarily for NoSQL) - MongoDB: $exists */ - $exists: external_exports.boolean().optional() - }); - FieldOperatorsSchema2 = external_exports.object({ - // Equality - $eq: external_exports.any().optional(), - $ne: external_exports.any().optional(), - // Comparison (numeric/date) - $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), - $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), - $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), - $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]).optional(), - // Set & Range - $in: external_exports.array(external_exports.any()).optional(), - $nin: external_exports.array(external_exports.any()).optional(), - $between: external_exports.tuple([ - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]), - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema2]) - ]).optional(), - // String-specific - $contains: external_exports.string().optional(), - $notContains: external_exports.string().optional(), - $startsWith: external_exports.string().optional(), - $endsWith: external_exports.string().optional(), - // Special - $null: external_exports.boolean().optional(), - $exists: external_exports.boolean().optional() - }); - FilterConditionSchema2 = external_exports.lazy( - () => external_exports.record(external_exports.string(), external_exports.unknown()).and( - external_exports.object({ - $and: external_exports.array(FilterConditionSchema2).optional(), - $or: external_exports.array(FilterConditionSchema2).optional(), - $not: FilterConditionSchema2.optional() - }) - ) - ); - QueryFilterSchema = external_exports.object({ - where: FilterConditionSchema2.optional() - }); - NormalizedFilterSchema2 = external_exports.lazy( - () => external_exports.object({ - $and: external_exports.array( - external_exports.union([ - // Field condition: { field: { $op: value } } - external_exports.record(external_exports.string(), FieldOperatorsSchema2), - // Nested logical group - NormalizedFilterSchema2 - ]) - ).optional(), - $or: external_exports.array( - external_exports.union([ - external_exports.record(external_exports.string(), FieldOperatorsSchema2), - NormalizedFilterSchema2 - ]) - ).optional(), - $not: external_exports.union([ - external_exports.record(external_exports.string(), FieldOperatorsSchema2), - NormalizedFilterSchema2 - ]).optional() - }) - ); - VALID_AST_OPERATORS = /* @__PURE__ */ new Set([ - "=", - "==", - "!=", - "<>", - ">", - ">=", - "<", - "<=", - "in", - "nin", - "not_in", - "contains", - "notcontains", - "not_contains", - "like", - "startswith", - "starts_with", - "endswith", - "ends_with", - "between", - "is_null", - "is_not_null" - ]); - AST_OPERATOR_MAP = { - "=": "$eq", - "==": "$eq", - "!=": "$ne", - "<>": "$ne", - ">": "$gt", - ">=": "$gte", - "<": "$lt", - "<=": "$lte", - "in": "$in", - "nin": "$nin", - "not_in": "$nin", - "contains": "$contains", - "notcontains": "$notContains", - "not_contains": "$notContains", - "like": "$contains", - "startswith": "$startsWith", - "starts_with": "$startsWith", - "endswith": "$endsWith", - "ends_with": "$endsWith", - "between": "$between", - "is_null": "$null", - "is_not_null": "$null" - }; - FILTER_OPERATORS = [ - // Equality - "$eq", - "$ne", - // Comparison - "$gt", - "$gte", - "$lt", - "$lte", - // Set & Range - "$in", - "$nin", - "$between", - // String - "$contains", - "$notContains", - "$startsWith", - "$endsWith", - // Special - "$null", - "$exists" - ]; - LOGICAL_OPERATORS = ["$and", "$or", "$not"]; - ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS]; - SortNodeSchema2 = external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]).default("asc") - }); - AggregationFunction2 = external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "array_agg", - "string_agg" - ]); - AggregationNodeSchema2 = external_exports.object({ - function: AggregationFunction2.describe("Aggregation function"), - field: external_exports.string().optional().describe("Field to aggregate (optional for COUNT(*))"), - alias: external_exports.string().describe("Result column alias"), - distinct: external_exports.boolean().optional().describe("Apply DISTINCT before aggregation"), - filter: FilterConditionSchema2.optional().describe("Filter/Condition to apply to the aggregation (FILTER WHERE clause)") - }); - JoinType2 = external_exports.enum(["inner", "left", "right", "full"]); - JoinStrategy2 = external_exports.enum(["auto", "database", "hash", "loop"]); - JoinNodeSchema2 = external_exports.lazy( - () => external_exports.object({ - type: JoinType2.describe("Join type"), - strategy: JoinStrategy2.optional().describe("Execution strategy hint"), - object: external_exports.string().describe("Object/table to join"), - alias: external_exports.string().optional().describe("Table alias"), - on: FilterConditionSchema2.describe("Join condition"), - subquery: external_exports.lazy(() => QuerySchema2).optional().describe("Subquery instead of object") - }) - ); - WindowFunction2 = external_exports.enum([ - "row_number", - "rank", - "dense_rank", - "percent_rank", - "lag", - "lead", - "first_value", - "last_value", - "sum", - "avg", - "count", - "min", - "max" - ]); - WindowSpecSchema2 = external_exports.object({ - partitionBy: external_exports.array(external_exports.string()).optional().describe("PARTITION BY fields"), - orderBy: external_exports.array(SortNodeSchema2).optional().describe("ORDER BY specification"), - frame: external_exports.object({ - type: external_exports.enum(["rows", "range"]).optional(), - start: external_exports.string().optional().describe('Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")'), - end: external_exports.string().optional().describe('Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")') - }).optional().describe("Window frame specification") - }); - WindowFunctionNodeSchema2 = external_exports.object({ - function: WindowFunction2.describe("Window function name"), - field: external_exports.string().optional().describe("Field to operate on (for aggregate window functions)"), - alias: external_exports.string().describe("Result column alias"), - over: WindowSpecSchema2.describe("Window specification (OVER clause)") - }); - FieldNodeSchema2 = external_exports.lazy( - () => external_exports.union([ - external_exports.string(), - // Primitive field: "name" - external_exports.object({ - field: external_exports.string(), - // Relationship field: "owner" - fields: external_exports.array(FieldNodeSchema2).optional(), - // Nested select: ["name", "email"] - alias: external_exports.string().optional() - }) - ]) - ); - FullTextSearchSchema2 = external_exports.object({ - query: external_exports.string().describe("Search query text"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to search in (if not specified, searches all text fields)"), - fuzzy: external_exports.boolean().optional().default(false).describe("Enable fuzzy matching (tolerates typos)"), - operator: external_exports.enum(["and", "or"]).optional().default("or").describe("Logical operator between terms"), - boost: external_exports.record(external_exports.string(), external_exports.number()).optional().describe("Field-specific relevance boosting (field name -> boost factor)"), - minScore: external_exports.number().optional().describe("Minimum relevance score threshold"), - language: external_exports.string().optional().describe('Language for text analysis (e.g., "en", "zh", "es")'), - highlight: external_exports.boolean().optional().default(false).describe("Enable search result highlighting") - }); - BaseQuerySchema2 = external_exports.object({ - /** Target Entity */ - object: external_exports.string().describe("Object name (e.g. account)"), - /** Select Clause */ - fields: external_exports.array(FieldNodeSchema2).optional().describe("Fields to retrieve"), - /** Where Clause (Filtering) */ - where: FilterConditionSchema2.optional().describe("Filtering criteria (WHERE)"), - /** Full-Text Search */ - search: FullTextSearchSchema2.optional().describe("Full-text search configuration ($search parameter)"), - /** Order By Clause (Sorting) */ - orderBy: external_exports.array(SortNodeSchema2).optional().describe("Sorting instructions (ORDER BY)"), - /** Pagination */ - limit: external_exports.number().optional().describe("Max records to return (LIMIT)"), - offset: external_exports.number().optional().describe("Records to skip (OFFSET)"), - top: external_exports.number().optional().describe("Alias for limit (OData compatibility)"), - cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Cursor for keyset pagination"), - /** Joins */ - joins: external_exports.array(JoinNodeSchema2).optional().describe("Explicit Table Joins"), - /** Aggregations */ - aggregations: external_exports.array(AggregationNodeSchema2).optional().describe("Aggregation functions"), - /** Group By Clause */ - groupBy: external_exports.array(external_exports.string()).optional().describe("GROUP BY fields"), - /** Having Clause */ - having: FilterConditionSchema2.optional().describe("HAVING clause for aggregation filtering"), - /** Window Functions */ - windowFunctions: external_exports.array(WindowFunctionNodeSchema2).optional().describe("Window functions with OVER clause"), - /** Subquery flag */ - distinct: external_exports.boolean().optional().describe("SELECT DISTINCT flag") - }); - QuerySchema2 = BaseQuerySchema2.extend({ - expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema2)).optional().describe( - "Recursive relation loading map. Keys are lookup/master_detail field names; values are nested QueryAST objects that control select, filter, sort, and further expansion on the related object. The engine resolves expand via batch $in queries (driver-agnostic) with a default max depth of 3." - ) - }); - SystemIdentifierSchema3 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' - }).describe("System identifier (lowercase with underscores or dots)"); - SnakeCaseIdentifierSchema3 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { - message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' - }).describe("Snake case identifier (lowercase with underscores only)"); - external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' - }).describe("Event name (lowercase with dot notation for namespacing)"); - EncryptionAlgorithmSchema3 = external_exports.enum([ - "aes-256-gcm", - "aes-256-cbc", - "chacha20-poly1305" - ]).describe("Supported encryption algorithm"); - KeyManagementProviderSchema3 = external_exports.enum([ - "local", - "aws-kms", - "azure-key-vault", - "gcp-kms", - "hashicorp-vault" - ]).describe("Key management service provider"); - KeyRotationPolicySchema3 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), - frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), - retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), - autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") - }).describe("Policy for automatic encryption key rotation"); - EncryptionConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), - algorithm: EncryptionAlgorithmSchema3.default("aes-256-gcm").describe("Encryption algorithm"), - keyManagement: external_exports.object({ - provider: KeyManagementProviderSchema3.describe("Key management service provider"), - keyId: external_exports.string().optional().describe("Key identifier in the provider"), - rotationPolicy: KeyRotationPolicySchema3.optional().describe("Key rotation policy") - }).describe("Key management configuration"), - scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), - deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), - searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") - }).describe("Field-level encryption configuration"); - external_exports.object({ - fieldName: external_exports.string().describe("Name of the field to encrypt"), - encryptionConfig: EncryptionConfigSchema3.describe("Encryption settings for this field"), - indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") - }).describe("Per-field encryption assignment"); - MaskingStrategySchema3 = external_exports.enum([ - "redact", - // Complete redaction: **** - "partial", - // Partial masking: 138****5678 - "hash", - // Hash value: sha256(value) - "tokenize", - // Tokenization: token-12345 - "randomize", - // Randomize: generate random value - "nullify", - // Null value: null - "substitute" - // Substitute with dummy data - ]).describe("Data masking strategy for PII protection"); - MaskingRuleSchema3 = external_exports.object({ - field: external_exports.string().describe("Field name to apply masking to"), - strategy: MaskingStrategySchema3.describe("Masking strategy to use"), - pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), - preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), - preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), - roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), - exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") - }).describe("Masking rule for a single field"); - external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable data masking"), - rules: external_exports.array(MaskingRuleSchema3).describe("List of field-level masking rules"), - auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") - }).describe("Top-level data masking configuration for PII protection"); - FieldType3 = external_exports.enum([ - // Core Text - "text", - "textarea", - "email", - "url", - "phone", - "password", - // Rich Content - "markdown", - "html", - "richtext", - // Numbers - "number", - "currency", - "percent", - // Date & Time - "date", - "datetime", - "time", - // Logic - "boolean", - "toggle", - // Toggle is a distinct UI from checkbox - // Selection - "select", - // Single select dropdown - "multiselect", - // Multi select (often tags) - "radio", - // Radio group - "checkboxes", - // Checkbox group - // Relational - "lookup", - "master_detail", - // Dynamic reference - "tree", - // Hierarchical reference - // Media - "image", - "file", - "avatar", - "video", - "audio", - // Calculated / System - "formula", - "summary", - "autonumber", - // Enhanced Types - "location", - // GPS coordinates - "address", - // Structured address - "code", - // Code editor (JSON/SQL/JS) - "json", - // Structured JSON data - "color", - // Color picker - "rating", - // Star rating - "slider", - // Numeric slider - "signature", - // Digital signature - "qrcode", - // QR code / Barcode - "progress", - // Progress bar - "tags", - // Simple tag list - // AI/ML Types - "vector" - // Vector embeddings for AI/ML (semantic search, RAG) - ]); - SelectOptionSchema3 = external_exports.object({ - label: external_exports.string().describe("Display label (human-readable, any case allowed)"), - value: SystemIdentifierSchema3.describe("Stored value (lowercase machine identifier)"), - color: external_exports.string().optional().describe("Color code for badges/charts"), - default: external_exports.boolean().optional().describe("Is default option") - }); - LocationCoordinatesSchema = external_exports.object({ - latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), - longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), - altitude: external_exports.number().optional().describe("Altitude in meters"), - accuracy: external_exports.number().optional().describe("Accuracy in meters") - }); - CurrencyConfigSchema3 = external_exports.object({ - precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), - currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), - defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") - }); - CurrencyValueSchema = external_exports.object({ - value: external_exports.number().describe("Monetary amount"), - currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") - }); - AddressSchema = external_exports.object({ - street: external_exports.string().optional().describe("Street address"), - city: external_exports.string().optional().describe("City name"), - state: external_exports.string().optional().describe("State/Province"), - postalCode: external_exports.string().optional().describe("Postal/ZIP code"), - country: external_exports.string().optional().describe("Country name or code"), - countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), - formatted: external_exports.string().optional().describe("Formatted address string") - }); - VectorConfigSchema3 = external_exports.object({ - dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), - distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), - normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), - indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), - indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") - }); - FileAttachmentConfigSchema3 = external_exports.object({ - /** File Size Limits */ - minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), - maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), - /** File Type Restrictions */ - allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), - blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), - allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), - blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), - /** Virus Scanning */ - virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), - virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), - virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), - quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), - /** Storage Configuration */ - storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), - storageBucket: external_exports.string().optional().describe("Target bucket name"), - storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), - /** Image-Specific Validation */ - imageValidation: external_exports.object({ - minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), - maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), - minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), - maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), - aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), - generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), - thumbnailSizes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), - width: external_exports.number().min(1).describe("Thumbnail width in pixels"), - height: external_exports.number().min(1).describe("Thumbnail height in pixels"), - crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") - })).optional().describe("Thumbnail size configurations"), - preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), - autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") - }).optional().describe("Image-specific validation rules"), - /** Upload Behavior */ - allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), - allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), - allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), - requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), - /** Metadata Extraction */ - extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), - extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), - /** Versioning */ - versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), - maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), - /** Access Control */ - publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), - presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") - }).refine((data) => { - if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { - return false; - } - return true; - }, { - message: "minSize must be less than or equal to maxSize" - }).refine((data) => { - if (data.virusScanProvider !== void 0 && data.virusScan !== true) { - return false; - } - return true; - }, { - message: "virusScanProvider requires virusScan to be enabled" - }); - DataQualityRulesSchema3 = external_exports.object({ - /** Enforce uniqueness constraint */ - uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), - /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ - completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), - /** Accuracy validation against authoritative source */ - accuracy: external_exports.object({ - source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), - threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") - }).optional().describe("Accuracy validation configuration") - }); - ComputedFieldCacheSchema3 = external_exports.object({ - /** Enable caching for this computed field */ - enabled: external_exports.boolean().describe("Enable caching for computed field results"), - /** Time-to-live in seconds */ - ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), - /** Array of field paths that trigger cache invalidation when changed */ - invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') - }); - FieldSchema3 = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), - label: external_exports.string().optional().describe("Human readable label"), - type: FieldType3.describe("Field Data Type"), - description: external_exports.string().optional().describe("Tooltip/Help text"), - format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), - /** Storage Layer Mapping */ - columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), - /** Database Constraints */ - required: external_exports.boolean().default(false).describe("Is required"), - searchable: external_exports.boolean().default(false).describe("Is searchable"), - multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), - unique: external_exports.boolean().default(false).describe("Is unique constraint"), - defaultValue: external_exports.unknown().optional().describe("Default value"), - /** Text/String Constraints */ - maxLength: external_exports.number().optional().describe("Max character length"), - minLength: external_exports.number().optional().describe("Min character length"), - /** Number Constraints */ - precision: external_exports.number().optional().describe("Total digits"), - scale: external_exports.number().optional().describe("Decimal places"), - min: external_exports.number().optional().describe("Minimum value"), - max: external_exports.number().optional().describe("Maximum value"), - /** Selection Options */ - options: external_exports.array(SelectOptionSchema3).optional().describe("Static options for select/multiselect"), - /** - * Relationship Config - * - * Used by `lookup` and `master_detail` field types to define cross-object references. - * The `reference` property is **required** for these types — it identifies the target - * object whose records this field links to. The engine uses `reference` during $expand - * post-processing to resolve foreign key IDs into full related objects via batch queries. - * - * For `master_detail` fields, the parent record controls the lifecycle of child records - * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. - */ - reference: external_exports.string().optional().describe( - "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." - ), - referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), - writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), - deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), - /** Calculation */ - expression: external_exports.string().optional().describe("Formula expression"), - summaryOperations: external_exports.object({ - object: external_exports.string().describe("Source child object name for roll-up"), - field: external_exports.string().describe("Field on child object to aggregate"), - function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") - }).optional().describe("Roll-up summary definition"), - /** Enhanced Field Type Configurations */ - // Code field config - language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), - theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), - lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), - // Rating field config - maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), - allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), - // Location field config - displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), - allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), - // Address field config - addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), - // Color field config - colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), - allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), - presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), - // Slider field config - step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), - showValue: external_exports.boolean().optional().describe("Display current value on slider"), - marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), - // QR Code / Barcode field config - // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' - // Runtime validation should enforce this constraint - barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), - qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), - displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), - allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), - // Currency field config - currencyConfig: CurrencyConfigSchema3.optional().describe("Configuration for currency field type"), - // Vector field config - vectorConfig: VectorConfigSchema3.optional().describe("Configuration for vector field type (AI/ML embeddings)"), - // File attachment field config - fileAttachmentConfig: FileAttachmentConfigSchema3.optional().describe("Configuration for file and attachment field types"), - /** Enhanced Security & Compliance */ - // Encryption configuration - encryptionConfig: EncryptionConfigSchema3.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), - // Data masking rules - maskingRule: MaskingRuleSchema3.optional().describe("Data masking rules for PII protection"), - // Audit trail - auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), - /** Field Dependencies & Relationships */ - // Field dependencies - dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), - /** Computed Field Optimization */ - // Computed field caching - cached: ComputedFieldCacheSchema3.optional().describe("Caching configuration for computed/formula fields"), - /** Data Quality & Governance */ - // Data quality rules - dataQuality: DataQualityRulesSchema3.optional().describe("Data quality validation and monitoring rules"), - /** Layout & Grouping */ - group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), - /** Conditional Requirements */ - conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), - /** Security & Visibility */ - hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), - readonly: external_exports.boolean().default(false).describe("Read-only in UI"), - sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), - inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), - trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), - caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), - autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), - /** Indexing */ - index: external_exports.boolean().default(false).describe("Create standard database index"), - externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") - }); - Field = { - text: (config4 = {}) => ({ type: "text", ...config4 }), - textarea: (config4 = {}) => ({ type: "textarea", ...config4 }), - number: (config4 = {}) => ({ type: "number", ...config4 }), - boolean: (config4 = {}) => ({ type: "boolean", ...config4 }), - date: (config4 = {}) => ({ type: "date", ...config4 }), - datetime: (config4 = {}) => ({ type: "datetime", ...config4 }), - currency: (config4 = {}) => ({ type: "currency", ...config4 }), - percent: (config4 = {}) => ({ type: "percent", ...config4 }), - url: (config4 = {}) => ({ type: "url", ...config4 }), - email: (config4 = {}) => ({ type: "email", ...config4 }), - phone: (config4 = {}) => ({ type: "phone", ...config4 }), - image: (config4 = {}) => ({ type: "image", ...config4 }), - file: (config4 = {}) => ({ type: "file", ...config4 }), - avatar: (config4 = {}) => ({ type: "avatar", ...config4 }), - formula: (config4 = {}) => ({ type: "formula", ...config4 }), - summary: (config4 = {}) => ({ type: "summary", ...config4 }), - autonumber: (config4 = {}) => ({ type: "autonumber", ...config4 }), - markdown: (config4 = {}) => ({ type: "markdown", ...config4 }), - html: (config4 = {}) => ({ type: "html", ...config4 }), - password: (config4 = {}) => ({ type: "password", ...config4 }), - /** - * Select field helper with backward-compatible API - * - * Automatically converts option values to lowercase to enforce naming conventions. - * - * @example Old API (array first) - auto-converts to lowercase - * Field.select(['High', 'Low'], { label: 'Priority' }) - * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }] - * - * @example New API (config object) - enforces lowercase - * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' }) - * - * @example Multi-word values - converts to snake_case - * Field.select(['In Progress', 'Closed Won'], { label: 'Status' }) - * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }] - */ - select: (optionsOrConfig, config4) => { - const toSnakeCase = (str) => { - return str.toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, ""); - }; - let options; - let finalConfig; - if (Array.isArray(optionsOrConfig)) { - options = optionsOrConfig.map( - (o) => typeof o === "string" ? { label: o, value: toSnakeCase(o) } : { ...o, value: o.value.toLowerCase() } - // Ensure value is lowercase - ); - finalConfig = config4 || {}; - } else { - options = (optionsOrConfig.options || []).map( - (o) => typeof o === "string" ? { label: o, value: toSnakeCase(o) } : { ...o, value: o.value.toLowerCase() } - // Ensure value is lowercase - ); - const { options: _, ...restConfig } = optionsOrConfig; - finalConfig = restConfig; - } - return { type: "select", options, ...finalConfig }; - }, - lookup: (reference, config4 = {}) => ({ - type: "lookup", - reference, - ...config4 - }), - masterDetail: (reference, config4 = {}) => ({ - type: "master_detail", - reference, - ...config4 - }), - // Enhanced Field Type Helpers - location: (config4 = {}) => ({ - type: "location", - ...config4 - }), - address: (config4 = {}) => ({ - type: "address", - ...config4 - }), - richtext: (config4 = {}) => ({ - type: "richtext", - ...config4 - }), - code: (language, config4 = {}) => ({ - type: "code", - language, - ...config4 - }), - color: (config4 = {}) => ({ - type: "color", - ...config4 - }), - rating: (maxRating = 5, config4 = {}) => ({ - type: "rating", - maxRating, - ...config4 - }), - signature: (config4 = {}) => ({ - type: "signature", - ...config4 - }), - slider: (config4 = {}) => ({ - type: "slider", - ...config4 - }), - qrcode: (config4 = {}) => ({ - type: "qrcode", - ...config4 - }), - json: (config4 = {}) => ({ - type: "json", - ...config4 - }), - vector: (dimensions, config4 = {}) => ({ - type: "vector", - vectorConfig: { - dimensions, - distanceMetric: "cosine", - normalized: false, - indexed: true, - ...config4.vectorConfig - }, - ...config4 - }) - }; - BaseValidationSchema3 = external_exports.object({ - // Identification - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label for the rule listing"), - description: external_exports.string().optional().describe("Administrative notes explaining the business reason"), - // Execution Control - active: external_exports.boolean().default(true), - events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).default(["insert", "update"]).describe("Validation contexts"), - priority: external_exports.number().int().min(0).max(9999).default(100).describe("Execution priority (lower runs first, default: 100)"), - // Classification - tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g., "compliance", "billing")'), - // Feedback - severity: external_exports.enum(["error", "warning", "info"]).default("error"), - message: external_exports.string().describe("Error message to display to the user") - }); - ScriptValidationSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("script"), - condition: external_exports.string().describe("Formula expression. If TRUE, validation fails. (e.g. amount < 0)") - }); - UniquenessValidationSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("unique"), - fields: external_exports.array(external_exports.string()).describe("Fields that must be combined unique"), - scope: external_exports.string().optional().describe("Formula condition for scope (e.g. active = true)"), - caseSensitive: external_exports.boolean().default(true) - }); - StateMachineValidationSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("state_machine"), - field: external_exports.string().describe("State field (e.g. status)"), - transitions: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).describe("Map of { OldState: [AllowedNewStates] }") - }); - FormatValidationSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("format"), - field: external_exports.string(), - regex: external_exports.string().optional(), - format: external_exports.enum(["email", "url", "phone", "json"]).optional() - }); - CrossFieldValidationSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("cross_field"), - condition: external_exports.string().describe('Formula expression comparing fields (e.g. "end_date > start_date")'), - fields: external_exports.array(external_exports.string()).describe("Fields involved in the validation") - }); - JSONValidationSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("json_schema"), - field: external_exports.string().describe("JSON field to validate"), - schema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema object definition") - }); - AsyncValidationSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("async"), - field: external_exports.string().describe("Field to validate"), - validatorUrl: external_exports.string().optional().describe("External API endpoint for validation"), - method: external_exports.enum(["GET", "POST"]).default("GET").describe("HTTP method for external call"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for the request"), - validatorFunction: external_exports.string().optional().describe("Reference to custom validator function"), - timeout: external_exports.number().optional().default(5e3).describe("Timeout in milliseconds"), - debounce: external_exports.number().optional().describe("Debounce delay in milliseconds"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional parameters to pass to validator") - }); - CustomValidatorSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("custom"), - handler: external_exports.string().describe("Name of the custom validation function registered in the system"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the custom handler") - }); - ValidationRuleSchema3 = external_exports.lazy( - () => external_exports.discriminatedUnion("type", [ - ScriptValidationSchema3, - UniquenessValidationSchema3, - StateMachineValidationSchema3, - FormatValidationSchema3, - CrossFieldValidationSchema3, - JSONValidationSchema3, - AsyncValidationSchema3, - CustomValidatorSchema3, - ConditionalValidationSchema3 - ]) - ); - ConditionalValidationSchema3 = BaseValidationSchema3.extend({ - type: external_exports.literal("conditional"), - when: external_exports.string().describe(`Condition formula (e.g. "type = 'enterprise'")`), - then: ValidationRuleSchema3.describe("Validation rule to apply when condition is true"), - otherwise: ValidationRuleSchema3.optional().describe("Validation rule to apply when condition is false") - }); - ActionRefSchema3 = external_exports.union([ - external_exports.string().describe("Action Name"), - external_exports.object({ - type: external_exports.string(), - // e.g., 'xstate.assign', 'log', 'email' - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }) - ]); - GuardRefSchema3 = external_exports.union([ - external_exports.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'), - external_exports.object({ - type: external_exports.string(), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }) - ]); - TransitionSchema3 = external_exports.object({ - target: external_exports.string().optional().describe("Target State ID"), - cond: GuardRefSchema3.optional().describe("Condition (Guard) required to take this path"), - actions: external_exports.array(ActionRefSchema3).optional().describe("Actions to execute during transition"), - description: external_exports.string().optional().describe("Human readable description of this rule") - }); - external_exports.object({ - type: external_exports.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'), - // Payload validation schema could go here if we want deep validation - schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Expected event payload structure") - }); - StateNodeSchema3 = external_exports.lazy(() => external_exports.object({ - /** Type of state */ - type: external_exports.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"), - /** Entry/Exit Actions */ - entry: external_exports.array(ActionRefSchema3).optional().describe("Actions to run when entering this state"), - exit: external_exports.array(ActionRefSchema3).optional().describe("Actions to run when leaving this state"), - /** Transitions (Events) */ - on: external_exports.record(external_exports.string(), external_exports.union([ - external_exports.string(), - // Shorthand target - TransitionSchema3, - external_exports.array(TransitionSchema3) - ])).optional().describe("Map of Event Type -> Transition Definition"), - /** Always Transitions (Eventless) */ - always: external_exports.array(TransitionSchema3).optional(), - /** Nesting (Hierarchical States) */ - initial: external_exports.string().optional().describe("Initial child state (if compound)"), - states: external_exports.record(external_exports.string(), StateNodeSchema3).optional(), - /** Metadata for UI/AI */ - meta: external_exports.object({ - label: external_exports.string().optional(), - description: external_exports.string().optional(), - color: external_exports.string().optional(), - // For UI diagrams - // Instructions for AI Agent when in this state - aiInstructions: external_exports.string().optional().describe("Specific instructions for AI when in this state") - }).optional() - })); - StateMachineSchema3 = external_exports.object({ - id: SnakeCaseIdentifierSchema3.describe("Unique Machine ID"), - description: external_exports.string().optional(), - /** Context (Memory) Schema */ - contextSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Zod Schema for the machine context/memory"), - /** Initial State */ - initial: external_exports.string().describe("Initial State ID"), - /** State Definitions */ - states: external_exports.record(external_exports.string(), StateNodeSchema3).describe("State Nodes"), - /** Global Listeners */ - on: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), TransitionSchema3, external_exports.array(TransitionSchema3)])).optional() - }); - external_exports.object({ - /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ - key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), - /** Default value when translation is not available */ - defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), - /** Interpolation parameters for dynamic translations */ - params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") - }); - I18nLabelSchema3 = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); - AriaPropsSchema3 = external_exports.object({ - /** Accessible label for screen readers */ - ariaLabel: I18nLabelSchema3.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), - /** ID of element that describes this component */ - ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), - /** WAI-ARIA role override */ - role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') - }).describe("ARIA accessibility attributes"); - external_exports.object({ - /** Translation key for the plural form */ - key: external_exports.string().describe("Translation key"), - /** Form for zero quantity */ - zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), - /** Form for singular (1) */ - one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), - /** Form for dual (2) — used in Arabic, Welsh, etc. */ - two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), - /** Form for few (2-4 in Slavic languages) */ - few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), - /** Form for many (5+ in Slavic languages) */ - many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), - /** Default/fallback form */ - other: external_exports.string().describe('Default plural form (e.g., "{count} items")') - }).describe("ICU plural rules for a translation key"); - NumberFormatSchema3 = external_exports.object({ - style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), - currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), - unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), - minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), - maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), - useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") - }).describe("Number formatting rules"); - DateFormatSchema3 = external_exports.object({ - dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), - timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), - timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), - hour12: external_exports.boolean().optional().describe("Use 12-hour format") - }).describe("Date/time formatting rules"); - external_exports.object({ - /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ - code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), - /** Ordered fallback chain for missing translations */ - fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), - /** Text direction */ - direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), - /** Default number formatting */ - numberFormat: NumberFormatSchema3.optional().describe("Default number formatting rules"), - /** Default date formatting */ - dateFormat: DateFormatSchema3.optional().describe("Default date/time formatting rules") - }).describe("Locale configuration"); - ActionParamSchema3 = external_exports.object({ - name: external_exports.string(), - label: I18nLabelSchema3, - type: FieldType3, - required: external_exports.boolean().default(false), - options: external_exports.array(external_exports.object({ label: I18nLabelSchema3, value: external_exports.string() })).optional() - }); - ActionType3 = external_exports.enum(["script", "url", "modal", "flow", "api"]); - TARGET_REQUIRED_TYPES3 = new Set( - ActionType3.options.filter((t) => t !== "script") - ); - ActionSchema3 = external_exports.object({ - /** Machine name of the action */ - name: SnakeCaseIdentifierSchema3.describe("Machine name (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema3.describe("Display label"), - /** Target object this action belongs to (optional, snake_case) */ - objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Icon name"), - /** Where does this action appear? */ - locations: external_exports.array(external_exports.enum([ - "list_toolbar", - "list_item", - "record_header", - "record_more", - "record_related", - "global_nav" - ])).optional().describe("Locations where this action is visible"), - /** - * Visual Component Type - * Defaults to 'button' or 'menu_item' based on location, - * but can be overridden. - */ - component: external_exports.enum([ - "action:button", - // Standard Button - "action:icon", - // Icon only - "action:menu", - // Dropdown menu - "action:group" - // Button Group - ]).optional().describe("Visual component override"), - /** What type of interaction? */ - type: ActionType3.default("script").describe("Action functionality type"), - /** - * Payload / Target — the canonical binding for the action handler. - * Required for url, flow, modal, and api types. - * Recommended for script type. - */ - target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), - /** - * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. - */ - execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), - /** User Input Requirements */ - params: external_exports.array(ActionParamSchema3).optional().describe("Input parameters required from user"), - /** Visual Style */ - variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), - /** UX Behavior */ - confirmText: I18nLabelSchema3.optional().describe("Confirmation message before execution"), - successMessage: I18nLabelSchema3.optional().describe("Success message to show after execution"), - refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), - /** Access */ - visible: external_exports.string().optional().describe("Formula returning boolean"), - disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), - /** Keyboard Shortcut */ - shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), - /** Bulk Operations */ - bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), - /** Execution */ - timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema3.optional().describe("ARIA accessibility attributes") - }).transform((data) => { - if (data.execute && !data.target) { - return { ...data, target: data.execute }; - } - return data; - }).refine((data) => { - if (TARGET_REQUIRED_TYPES3.has(data.type) && !data.target) { - return false; - } - return true; - }, { - message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", - path: ["target"] - }); - ApiMethod3 = external_exports.enum([ - "get", - "list", - // Read - "create", - "update", - "delete", - // Write - "upsert", - // Idempotent Write - "bulk", - // Batch operations - "aggregate", - // Analytics (count, sum) - "history", - // Audit access - "search", - // Search access - "restore", - "purge", - // Trash management - "import", - "export" - // Data portability - ]); - ObjectCapabilities3 = external_exports.object({ - /** Enable history tracking (Audit Trail) */ - trackHistory: external_exports.boolean().default(false).describe("Enable field history tracking for audit compliance"), - /** Enable global search indexing */ - searchable: external_exports.boolean().default(true).describe("Index records for global search"), - /** Enable REST/GraphQL API access */ - apiEnabled: external_exports.boolean().default(true).describe("Expose object via automatic APIs"), - /** - * API Supported Operations - * Granular control over API exposure. - */ - apiMethods: external_exports.array(ApiMethod3).optional().describe("Whitelist of allowed API operations"), - /** Enable standard attachments/files engine */ - files: external_exports.boolean().default(false).describe("Enable file attachments and document management"), - /** Enable social collaboration (Comments, Mentions, Feeds) */ - feeds: external_exports.boolean().default(false).describe("Enable social feed, comments, and mentions (Chatter-like)"), - /** Enable standard Activity suite (Tasks, Calendars, Events) */ - activities: external_exports.boolean().default(false).describe("Enable standard tasks and events tracking"), - /** Enable Recycle Bin / Soft Delete */ - trash: external_exports.boolean().default(true).describe("Enable soft-delete with restore capability"), - /** Enable "Recently Viewed" tracking */ - mru: external_exports.boolean().default(true).describe("Track Most Recently Used (MRU) list for users"), - /** Allow cloning records */ - clone: external_exports.boolean().default(true).describe("Allow record deep cloning") - }); - IndexSchema3 = external_exports.object({ - name: external_exports.string().optional().describe("Index name (auto-generated if not provided)"), - fields: external_exports.array(external_exports.string()).describe("Fields included in the index"), - type: external_exports.enum(["btree", "hash", "gin", "gist", "fulltext"]).optional().default("btree").describe("Index algorithm type"), - unique: external_exports.boolean().optional().default(false).describe("Whether the index enforces uniqueness"), - partial: external_exports.string().optional().describe("Partial index condition (SQL WHERE clause for conditional indexes)") - }); - SearchConfigSchema4 = external_exports.object({ - fields: external_exports.array(external_exports.string()).describe("Fields to index for full-text search weighting"), - displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display in search result cards"), - filters: external_exports.array(external_exports.string()).optional().describe("Default filters for search results") - }); - TenancyConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable multi-tenancy for this object"), - strategy: external_exports.enum(["shared", "isolated", "hybrid"]).describe("Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)"), - tenantField: external_exports.string().default("tenant_id").describe("Field name for tenant identifier"), - crossTenantAccess: external_exports.boolean().default(false).describe("Allow cross-tenant data access (with explicit permission)") - }); - SoftDeleteConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable soft delete (trash/recycle bin)"), - field: external_exports.string().default("deleted_at").describe("Field name for soft delete timestamp"), - cascadeDelete: external_exports.boolean().default(false).describe("Cascade soft delete to related records") - }); - VersioningConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable record versioning"), - strategy: external_exports.enum(["snapshot", "delta", "event-sourcing"]).describe("Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)"), - retentionDays: external_exports.number().min(1).optional().describe("Number of days to retain old versions (undefined = infinite)"), - versionField: external_exports.string().default("version").describe("Field name for version number/timestamp") - }); - PartitioningConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable table partitioning"), - strategy: external_exports.enum(["range", "hash", "list"]).describe("Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)"), - key: external_exports.string().describe("Field name to partition by"), - interval: external_exports.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")') - }).refine((data) => { - if (data.strategy === "range" && !data.interval) { - return false; - } - return true; - }, { - message: 'interval is required when strategy is "range"' - }); - CDCConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable Change Data Capture"), - events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).describe("Event types to capture"), - destination: external_exports.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")') - }); - ObjectSchemaBase3 = external_exports.object({ - /** - * Identity & Metadata - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine unique key (snake_case). Immutable."), - label: external_exports.string().optional().describe('Human readable singular label (e.g. "Account")'), - pluralLabel: external_exports.string().optional().describe('Human readable plural label (e.g. "Accounts")'), - description: external_exports.string().optional().describe("Developer documentation / description"), - icon: external_exports.string().optional().describe("Icon name (Lucide/Material) for UI representation"), - /** - * Namespace & Domain Classification - * - * Groups objects into logical domains for routing, permissions, and discovery. - * System objects use `'sys'`; business packages use their own namespace. - * - * When set, `tableName` is auto-derived as `{namespace}_{name}` by - * `ObjectSchema.create()` unless an explicit `tableName` is provided. - * - * Namespace must be a single lowercase word (no underscores or hyphens) - * to ensure clean auto-derivation of `{namespace}_{name}` table names. - * - * @example namespace: 'sys' → tableName defaults to 'sys_user' - * @example namespace: 'crm' → tableName defaults to 'crm_account' - */ - namespace: external_exports.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace \u2014 single lowercase word (e.g. "sys", "crm"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'), - /** - * Taxonomy & Organization - */ - tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'), - active: external_exports.boolean().optional().default(true).describe("Is the object active and usable"), - isSystem: external_exports.boolean().optional().default(false).describe("Is system object (protected from deletion)"), - abstract: external_exports.boolean().optional().default(false).describe("Is abstract base object (cannot be instantiated)"), - /** - * Storage & Virtualization - */ - datasource: external_exports.string().optional().default("default").describe('Target Datasource ID. "default" is the primary DB.'), - tableName: external_exports.string().optional().describe("Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set."), - /** - * Data Model - */ - fields: external_exports.record(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/, { - message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")' - }), FieldSchema3).describe("Field definitions map. Keys must be snake_case identifiers."), - indexes: external_exports.array(IndexSchema3).optional().describe("Database performance indexes"), - /** - * Advanced Data Management - */ - // Multi-tenancy configuration - tenancy: TenancyConfigSchema3.optional().describe("Multi-tenancy configuration for SaaS applications"), - // Soft delete configuration - softDelete: SoftDeleteConfigSchema3.optional().describe("Soft delete (trash/recycle bin) configuration"), - // Versioning configuration - versioning: VersioningConfigSchema3.optional().describe("Record versioning and history tracking configuration"), - // Partitioning strategy - partitioning: PartitioningConfigSchema3.optional().describe("Table partitioning configuration for performance"), - // Change Data Capture - cdc: CDCConfigSchema3.optional().describe("Change Data Capture (CDC) configuration for real-time data streaming"), - /** - * Logic & Validation (Co-located) - * Best Practice: Define rules close to data. - */ - validations: external_exports.array(ValidationRuleSchema3).optional().describe("Object-level validation rules"), - /** - * State Machine(s) - * Named record of state machines, where each key is a unique machine identifier. - * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status). - * - * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} } - */ - stateMachines: external_exports.record(external_exports.string(), StateMachineSchema3).optional().describe("Named state machines for parallel lifecycles (e.g., status, payment, approval)"), - /** - * Display & UI Hints (Data-Layer) - */ - displayNameField: external_exports.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'), - recordName: external_exports.object({ - type: external_exports.enum(["text", "autonumber"]).describe("Record name type: text (user-entered) or autonumber (system-generated)"), - displayFormat: external_exports.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'), - startNumber: external_exports.number().int().min(0).optional().describe("Starting number for autonumber (default: 1)") - }).optional().describe("Record name generation configuration (Salesforce pattern)"), - titleFormat: external_exports.string().optional().describe('Title expression (e.g. "{name} - {code}"). Overrides displayNameField.'), - compactLayout: external_exports.array(external_exports.string()).optional().describe("Primary fields for hover/cards/lookups"), - /** - * Search Engine Config - */ - search: SearchConfigSchema4.optional().describe("Search engine configuration"), - /** - * System Capabilities - */ - enable: ObjectCapabilities3.optional().describe("Enabled system features modules"), - /** Record Types */ - recordTypes: external_exports.array(external_exports.string()).optional().describe("Record type names for this object"), - /** Sharing Model */ - sharingModel: external_exports.enum(["private", "read", "read_write", "full"]).optional().describe("Default sharing model"), - /** Key Prefix */ - keyPrefix: external_exports.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'), - /** - * Object Actions - * - * Actions associated with this object. Populated automatically by `defineStack()` - * when top-level actions specify `objectName` matching this object. - * Can also be defined directly on the object. - * - * Aligns with Salesforce/ServiceNow patterns where actions are part of the - * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`) - * include the action list without requiring downstream merge. - */ - actions: external_exports.array(ActionSchema3).optional().describe("Actions associated with this object (auto-populated from top-level actions via objectName)") - }); - ObjectSchema3 = Object.assign(ObjectSchemaBase3, { - /** - * Type-safe factory for creating business object definitions. - * - * Enhancements over raw schema: - * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case). - * - **Validation**: Runs Zod `.parse()` to validate the config at creation time. - * - * @example - * ```ts - * const Task = ObjectSchema.create({ - * name: 'project_task', - * // label auto-generated as 'Project Task' - * fields: { - * subject: { type: 'text', label: 'Subject', required: true }, - * }, - * }); - * ``` - */ - create: (config4) => { - const withDefaults = { - ...config4, - label: config4.label ?? snakeCaseToLabel3(config4.name), - // Auto-derive tableName as {namespace}_{name} when namespace is set - tableName: config4.tableName ?? (config4.namespace ? `${config4.namespace}_${config4.name}` : void 0) - }; - return ObjectSchemaBase3.parse(withDefaults); - } - }); - ObjectOwnershipEnum = external_exports.enum(["own", "extend"]); - ObjectExtensionSchema = external_exports.object({ - /** The target object name (FQN) to extend */ - extend: external_exports.string().describe("Target object name (FQN) to extend"), - /** Fields to merge into the target object (additive) */ - fields: external_exports.record(external_exports.string(), FieldSchema3).optional().describe("Fields to add/override"), - /** Override label */ - label: external_exports.string().optional().describe("Override label for the extended object"), - /** Override plural label */ - pluralLabel: external_exports.string().optional().describe("Override plural label for the extended object"), - /** Override description */ - description: external_exports.string().optional().describe("Override description for the extended object"), - /** Additional validation rules to add */ - validations: external_exports.array(ValidationRuleSchema3).optional().describe("Additional validation rules to merge into the target object"), - /** Additional indexes to add */ - indexes: external_exports.array(IndexSchema3).optional().describe("Additional indexes to merge into the target object"), - /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ - priority: external_exports.number().int().min(0).max(999).default(200).describe("Merge priority (higher = applied later)") - }); - HookEvent = external_exports.enum([ - // Read Operations - "beforeFind", - "afterFind", - "beforeFindOne", - "afterFindOne", - "beforeCount", - "afterCount", - "beforeAggregate", - "afterAggregate", - // Write Operations - "beforeInsert", - "afterInsert", - "beforeUpdate", - "afterUpdate", - "beforeDelete", - "afterDelete", - // Bulk Operations (Query-based) - "beforeUpdateMany", - "afterUpdateMany", - "beforeDeleteMany", - "afterDeleteMany" - ]); - HookSchema = external_exports.object({ - /** - * Unique identifier for the hook - * Required for debugging and overriding. - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Hook unique name (snake_case)"), - /** - * Human readable label - */ - label: external_exports.string().optional().describe("Description of what this hook does"), - /** - * Target Object(s) - * can be: - * - Single object: "account" - * - List of objects: ["account", "contact"] - * - Wildcard: "*" (All objects) - */ - object: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Target object(s)"), - /** - * Events to subscribe to - * Combinations of timing (before/after) and action (find/insert/update/delete/etc) - */ - events: external_exports.array(HookEvent).describe("Lifecycle events"), - /** - * Handler Logic - * Reference to a registered function in the plugin system OR a direct function (runtime only). - */ - handler: external_exports.union([external_exports.string(), external_exports.function()]).optional().describe("Handler function name (string) or inline function reference"), - /** - * Execution Order - * Lower numbers run first. - * - System Hooks: 0-99 - * - App Hooks: 100-999 - * - User Hooks: 1000+ - */ - priority: external_exports.number().default(100).describe("Execution priority"), - /** - * Async / Background Execution - * If true, the hook runs in the background and does not block the transaction. - * Only applicable for 'after*' events. - * Default: false (Blocking) - */ - async: external_exports.boolean().default(false).describe("Run specifically as fire-and-forget"), - /** - * Declarative Condition - * Formula expression evaluated before the handler runs. - * If provided and evaluates to FALSE, the hook is skipped entirely. - * Useful for filtering by record data without writing handler code. - * - * @example "status = 'active' AND amount > 1000" - */ - condition: external_exports.string().optional().describe(`Formula expression; hook runs only when TRUE (e.g., "status = 'closed' AND amount > 1000")`), - /** - * Human-readable description - */ - description: external_exports.string().optional().describe("Human-readable description of what this hook does"), - /** - * Retry Policy - */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().default(3).describe("Maximum retry attempts on failure"), - backoffMs: external_exports.number().default(1e3).describe("Backoff delay between retries in milliseconds") - }).optional().describe("Retry policy for failed hook executions"), - /** - * Execution Timeout - */ - timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds before the hook is aborted"), - /** - * Error Policy - * What to do if the hook throws an exception? - * - abort: Rollback transaction (if blocking) - * - log: Log error and continue - */ - onError: external_exports.enum(["abort", "log"]).default("abort").describe("Error handling strategy") - }); - HookContextSchema = external_exports.object({ - /** Tracing ID */ - id: external_exports.string().optional().describe("Unique execution ID for tracing"), - /** Target Object Name */ - object: external_exports.string(), - /** Current Lifecycle Event */ - event: HookEvent, - /** - * Input Parameters (Mutable) - * Modify this to change the behavior of the operation. - * - * - find: { query: QueryAST, options: DriverOptions } - * - insert: { doc: Record, options: DriverOptions } - * - update: { id: ID, doc: Record, options: DriverOptions } - * - delete: { id: ID, options: DriverOptions } - * - updateMany: { query: QueryAST, doc: Record, options: DriverOptions } - * - deleteMany: { query: QueryAST, options: DriverOptions } - */ - input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Mutable input parameters"), - /** - * Operation Result (Mutable) - * Available in 'after*' events. Modify this to transform the output. - */ - result: external_exports.unknown().optional().describe("Operation result (After hooks only)"), - /** - * Data Snapshot - * The state of the record BEFORE the operation (for update/delete). - */ - previous: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record state before operation"), - /** - * Execution Session - * Contains authentication and tenancy information. - */ - session: external_exports.object({ - userId: external_exports.string().optional(), - tenantId: external_exports.string().optional(), - roles: external_exports.array(external_exports.string()).optional(), - accessToken: external_exports.string().optional() - }).optional().describe("Current session context"), - /** - * Transaction Handle - * If the operation is part of a transaction, use this handle for side-effects. - */ - transaction: external_exports.unknown().optional().describe("Database transaction handle"), - /** - * Engine Access - * Reference to the ObjectQL engine for performing side effects. - */ - ql: external_exports.unknown().describe("ObjectQL Engine Reference"), - /** - * Cross-Object API - * Provides a scoped data access interface for performing CRUD operations - * on other objects within hooks. Bound to the current execution context - * (userId, tenantId, transaction). - * - * Usage in hooks: - * const users = ctx.api.object('user'); - * const admin = await users.findOne({ filter: { role: 'admin' } }); - */ - api: external_exports.unknown().optional().describe("Cross-object data access (ScopedContext)"), - /** - * Current User Info - * Convenience shortcut for session.userId + additional user metadata. - * Populated by the engine when available. - */ - user: external_exports.object({ - id: external_exports.string().optional(), - name: external_exports.string().optional(), - email: external_exports.string().optional() - }).optional().describe("Current user info shortcut") - }); - TransformType = external_exports.enum([ - "none", - // Direct copy - "constant", - // Use a hardcoded value - "lookup", - // Resolve FK (Name -> ID) - "split", - // "John Doe" -> ["John", "Doe"] - "join", - // ["John", "Doe"] -> "John Doe" - "javascript", - // Custom script (Review security!) - "map" - // Value mapping (e.g. "Active" -> "active") - ]); - FieldMappingSchema = external_exports.object({ - /** Source Column */ - source: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Source column header(s)"), - /** Target Field */ - target: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Target object field(s)"), - /** Transformation */ - transform: TransformType.default("none"), - /** Configuration for transform */ - params: external_exports.object({ - // Constant - value: external_exports.unknown().optional(), - // Lookup - object: external_exports.string().optional(), - // Lookup Object - fromField: external_exports.string().optional(), - // Match on (e.g. "name") - toField: external_exports.string().optional(), - // Value to take (e.g. "id") - autoCreate: external_exports.boolean().optional(), - // Create if missing - // Map - valueMap: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - // { "Open": "draft" } - // Split/Join - separator: external_exports.string().optional() - }).optional() - }); - MappingSchema = external_exports.object({ - /** Identity */ - name: SnakeCaseIdentifierSchema3.describe("Mapping unique name (lowercase snake_case)"), - label: external_exports.string().optional(), - /** Scope */ - sourceFormat: external_exports.enum(["csv", "json", "xml", "sql"]).default("csv"), - targetObject: external_exports.string().describe("Target Object Name"), - /** Column Mappings */ - fieldMapping: external_exports.array(FieldMappingSchema), - /** Upsert Logic */ - mode: external_exports.enum(["insert", "update", "upsert"]).default("insert"), - upsertKey: external_exports.array(external_exports.string()).optional().describe("Fields to match for upsert (e.g. email)"), - /** Extract Logic (For Export) */ - extractQuery: QuerySchema2.optional().describe("Query to run for export only"), - /** Error Handling */ - errorPolicy: external_exports.enum(["skip", "abort", "retry"]).default("skip"), - batchSize: external_exports.number().default(1e3) - }); - ExecutionContextSchema = external_exports.object({ - /** Current user ID (resolved from session) */ - userId: external_exports.string().optional(), - /** Current organization/tenant ID (resolved from session.activeOrganizationId) */ - tenantId: external_exports.string().optional(), - /** User role names (resolved from Member + Role) */ - roles: external_exports.array(external_exports.string()).default([]), - /** Aggregated permission names (resolved from PermissionSet) */ - permissions: external_exports.array(external_exports.string()).default([]), - /** Whether this is a system-level operation (bypasses permission checks) */ - isSystem: external_exports.boolean().default(false), - /** Raw access token (for external API call pass-through) */ - accessToken: external_exports.string().optional(), - /** Database transaction handle */ - transaction: external_exports.unknown().optional(), - /** Request trace ID (for distributed tracing) */ - traceId: external_exports.string().optional() - }); - DataEngineFilterSchema = external_exports.union([ - external_exports.record(external_exports.string(), external_exports.unknown()), - FilterConditionSchema2 - ]).describe("Data Engine query filter conditions"); - DataEngineSortSchema = external_exports.union([ - external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])), - external_exports.record(external_exports.string(), external_exports.union([external_exports.literal(1), external_exports.literal(-1)])), - external_exports.array(SortNodeSchema2) - ]).describe("Sort order definition"); - BaseEngineOptionsSchema = external_exports.object({ - /** Execution context (identity, tenant, transaction) */ - context: ExecutionContextSchema.optional() - }); - EngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({ - /** Filter conditions (WHERE) — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), - /** Fields to retrieve (SELECT) — standard QueryAST `fields` */ - fields: external_exports.array(FieldNodeSchema2).optional(), - /** Sorting instructions (ORDER BY) — standard QueryAST `orderBy` */ - orderBy: external_exports.array(SortNodeSchema2).optional(), - /** Max records to return (LIMIT) */ - limit: external_exports.number().optional(), - /** Records to skip (OFFSET) — standard QueryAST `offset` */ - offset: external_exports.number().optional(), - /** Alias for limit (OData compatibility) */ - top: external_exports.number().optional(), - /** Cursor for keyset pagination */ - cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** Full-text search configuration */ - search: FullTextSearchSchema2.optional(), - /** - * Recursive relation loading map (expand). - * - * Keys are lookup/master_detail field names; values are nested QueryAST - * objects that control select, filter, sort, and further expansion on - * the related object. The engine resolves expand via batch $in queries - * (driver-agnostic) with a default max depth of 3. - */ - expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema2)).optional(), - /** SELECT DISTINCT flag */ - distinct: external_exports.boolean().optional() - }).describe("QueryAST-aligned query options for IDataEngine.find() operations"); - DataEngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({ - /** @deprecated Use `where` (EngineQueryOptionsSchema) */ - filter: DataEngineFilterSchema.optional(), - /** @deprecated Use `fields` (EngineQueryOptionsSchema) */ - select: external_exports.array(external_exports.string()).optional(), - /** @deprecated Use `orderBy` (EngineQueryOptionsSchema) */ - sort: DataEngineSortSchema.optional(), - limit: external_exports.number().int().min(1).optional(), - /** @deprecated Use `offset` (EngineQueryOptionsSchema) */ - skip: external_exports.number().int().min(0).optional(), - top: external_exports.number().int().min(1).optional(), - /** @deprecated Use `expand` (EngineQueryOptionsSchema) */ - populate: external_exports.array(external_exports.string()).optional() - }).describe("Query options for IDataEngine.find() operations"); - DataEngineInsertOptionsSchema = BaseEngineOptionsSchema.extend({ - /** - * Return the inserted record(s)? - * Some drivers support RETURNING clause for efficiency. - * Default: true - */ - returning: external_exports.boolean().default(true).optional() - }).describe("Options for DataEngine.insert operations"); - EngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({ - /** Filter conditions to identify records to update — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), - /** Perform an upsert? If true, insert if not found. */ - upsert: external_exports.boolean().default(false).optional(), - /** Update multiple records? If false, only the first match is updated. Default: false */ - multi: external_exports.boolean().default(false).optional(), - /** Return the updated record(s)? Default: false (returns update count/status) */ - returning: external_exports.boolean().default(false).optional() - }).describe("QueryAST-aligned options for DataEngine.update operations"); - DataEngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({ - /** @deprecated Use `where` (EngineUpdateOptionsSchema) */ - filter: DataEngineFilterSchema.optional(), - upsert: external_exports.boolean().default(false).optional(), - multi: external_exports.boolean().default(false).optional(), - returning: external_exports.boolean().default(false).optional() - }).describe("Options for DataEngine.update operations"); - EngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({ - /** Filter conditions to identify records to delete — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), - /** Delete multiple records? If false, only the first match is deleted. Default: false */ - multi: external_exports.boolean().default(false).optional() - }).describe("QueryAST-aligned options for DataEngine.delete operations"); - DataEngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({ - /** @deprecated Use `where` (EngineDeleteOptionsSchema) */ - filter: DataEngineFilterSchema.optional(), - multi: external_exports.boolean().default(false).optional() - }).describe("Options for DataEngine.delete operations"); - EngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({ - /** Filter conditions (WHERE) — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), - /** Group By fields */ - groupBy: external_exports.array(external_exports.string()).optional(), - /** - * Aggregation definitions — uses standard AggregationNodeSchema (`function` key). - * e.g. [{ function: 'sum', field: 'amount', alias: 'total' }] - */ - aggregations: external_exports.array(AggregationNodeSchema2).optional() - }).describe("QueryAST-aligned options for DataEngine.aggregate operations"); - DataEngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({ - /** @deprecated Use `where` (EngineAggregateOptionsSchema) */ - filter: DataEngineFilterSchema.optional(), - groupBy: external_exports.array(external_exports.string()).optional(), - /** - * @deprecated Use `EngineAggregateOptionsSchema` with standard AggregationNodeSchema (`function` key). - */ - aggregations: external_exports.array(external_exports.object({ - field: external_exports.string(), - method: external_exports.enum(["count", "sum", "avg", "min", "max", "count_distinct"]), - alias: external_exports.string().optional() - })).optional() - }).describe("Options for DataEngine.aggregate operations"); - EngineCountOptionsSchema = BaseEngineOptionsSchema.extend({ - /** Filter conditions — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional() - }).describe("QueryAST-aligned options for DataEngine.count operations"); - DataEngineCountOptionsSchema = BaseEngineOptionsSchema.extend({ - /** @deprecated Use `where` (EngineCountOptionsSchema) */ - filter: DataEngineFilterSchema.optional() - }).describe("Options for DataEngine.count operations"); - DataEngineContractSchema = external_exports.object({ - find: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineQueryOptionsSchema.optional()])).output(external_exports.promise(external_exports.array(external_exports.unknown()))), - findOne: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineQueryOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())), - insert: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown()))]), DataEngineInsertOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())), - update: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), EngineUpdateOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())), - delete: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineDeleteOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())), - count: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineCountOptionsSchema.optional()])).output(external_exports.promise(external_exports.number())), - aggregate: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineAggregateOptionsSchema])).output(external_exports.promise(external_exports.array(external_exports.unknown()))) - }).describe("Standard Data Engine Contract"); - RpcLegacyFilterMixin = { - /** @deprecated Use `where` */ - filter: DataEngineFilterSchema.optional() - }; - RpcQueryOptionsSchema = EngineQueryOptionsSchema.extend({ - ...RpcLegacyFilterMixin, - /** @deprecated Use `fields` */ - select: external_exports.array(external_exports.string()).optional(), - /** @deprecated Use `orderBy` */ - sort: DataEngineSortSchema.optional(), - /** @deprecated Use `offset` */ - skip: external_exports.number().int().min(0).optional(), - /** @deprecated Use `expand` */ - populate: external_exports.array(external_exports.string()).optional() - }); - DataEngineFindRequestSchema = external_exports.object({ - method: external_exports.literal("find"), - object: external_exports.string(), - query: RpcQueryOptionsSchema.optional() - }); - DataEngineFindOneRequestSchema = external_exports.object({ - method: external_exports.literal("findOne"), - object: external_exports.string(), - query: RpcQueryOptionsSchema.optional() - }); - DataEngineInsertRequestSchema = external_exports.object({ - method: external_exports.literal("insert"), - object: external_exports.string(), - data: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown()))]), - options: DataEngineInsertOptionsSchema.optional() - }); - DataEngineUpdateRequestSchema = external_exports.object({ - method: external_exports.literal("update"), - object: external_exports.string(), - data: external_exports.record(external_exports.string(), external_exports.unknown()), - id: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("ID for single update, or use where in options"), - options: EngineUpdateOptionsSchema.extend(RpcLegacyFilterMixin).optional() - }); - DataEngineDeleteRequestSchema = external_exports.object({ - method: external_exports.literal("delete"), - object: external_exports.string(), - id: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("ID for single delete, or use where in options"), - options: EngineDeleteOptionsSchema.extend(RpcLegacyFilterMixin).optional() - }); - DataEngineCountRequestSchema = external_exports.object({ - method: external_exports.literal("count"), - object: external_exports.string(), - query: EngineCountOptionsSchema.extend(RpcLegacyFilterMixin).optional() - }); - DataEngineAggregateRequestSchema = external_exports.object({ - method: external_exports.literal("aggregate"), - object: external_exports.string(), - query: EngineAggregateOptionsSchema.extend(RpcLegacyFilterMixin) - }); - DataEngineExecuteRequestSchema = external_exports.object({ - method: external_exports.literal("execute"), - /** The abstract command (string SQL, or JSON object) */ - command: external_exports.unknown(), - /** Optional options */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }); - DataEngineVectorFindRequestSchema = external_exports.object({ - method: external_exports.literal("vectorFind"), - object: external_exports.string(), - /** The vector embedding to search for */ - vector: external_exports.array(external_exports.number()), - /** Optional pre-filter (Metadata filtering) — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema2]).optional(), - /** Fields to retrieve — standard QueryAST `fields` */ - fields: external_exports.array(external_exports.string()).optional(), - /** Number of results */ - limit: external_exports.number().int().default(5).optional(), - /** Minimum similarity score (0-1) or distance threshold */ - threshold: external_exports.number().optional() - }); - DataEngineBatchRequestSchema = external_exports.object({ - method: external_exports.literal("batch"), - requests: external_exports.array(external_exports.discriminatedUnion("method", [ - DataEngineFindRequestSchema, - DataEngineFindOneRequestSchema, - DataEngineInsertRequestSchema, - DataEngineUpdateRequestSchema, - DataEngineDeleteRequestSchema, - DataEngineCountRequestSchema, - DataEngineAggregateRequestSchema, - DataEngineExecuteRequestSchema, - DataEngineVectorFindRequestSchema - ])), - /** - * Transaction Mode - * - true: All or nothing (Atomic) - * - false: Best effort, continue on error - */ - transaction: external_exports.boolean().default(true).optional() - }); - DataEngineRequestSchema = external_exports.discriminatedUnion("method", [ - DataEngineFindRequestSchema, - DataEngineFindOneRequestSchema, - DataEngineInsertRequestSchema, - DataEngineUpdateRequestSchema, - DataEngineDeleteRequestSchema, - DataEngineCountRequestSchema, - DataEngineAggregateRequestSchema, - DataEngineBatchRequestSchema, - DataEngineExecuteRequestSchema, - DataEngineVectorFindRequestSchema - ]).describe("Virtual ObjectQL Request Protocol"); - external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "percentile", - "median", - "stddev", - "variance" - ]).describe("Standard aggregation functions"); - SortDirectionEnum = external_exports.enum(["asc", "desc"]).describe("Sort order direction"); - external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - order: SortDirectionEnum.describe("Sort direction") - }).describe("Sort field and direction pair"); - external_exports.enum([ - "insert", - "update", - "delete", - "upsert" - ]).describe("Data mutation event types"); - IsolationLevelEnum = external_exports.enum([ - "read_uncommitted", - "read_committed", - "repeatable_read", - "serializable", - "snapshot" - ]).describe("Transaction isolation levels (snake_case standard)"); - external_exports.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy"); - DriverOptionsSchema = external_exports.object({ - /** - * Transaction handle/identifier. - * If provided, the operation must run within this transaction. - */ - transaction: external_exports.unknown().optional().describe("Transaction handle"), - /** - * Operation timeout in milliseconds. - */ - timeout: external_exports.number().optional().describe("Timeout in ms"), - /** - * Whether to bypass cache and force a fresh read. - */ - skipCache: external_exports.boolean().optional().describe("Bypass cache"), - /** - * Distributed Tracing Context. - * Used for passing OpenTelemetry span context or request IDs for observability. - */ - traceContext: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("OpenTelemetry context or request ID"), - /** - * Tenant Identifier. - * For multi-tenant databases (row-level security or schema-per-tenant). - */ - tenantId: external_exports.string().optional().describe("Tenant Isolation identifier") - }); - DriverCapabilitiesSchema = external_exports.object({ - // ============================================================================ - // Basic CRUD Operations - // ============================================================================ - /** - * Whether the driver supports create operations. - */ - create: external_exports.boolean().default(true).describe("Supports CREATE operations"), - /** - * Whether the driver supports read operations. - */ - read: external_exports.boolean().default(true).describe("Supports READ operations"), - /** - * Whether the driver supports update operations. - */ - update: external_exports.boolean().default(true).describe("Supports UPDATE operations"), - /** - * Whether the driver supports delete operations. - */ - delete: external_exports.boolean().default(true).describe("Supports DELETE operations"), - // ============================================================================ - // Bulk Operations - // ============================================================================ - /** - * Whether the driver supports bulk create operations. - */ - bulkCreate: external_exports.boolean().default(false).describe("Supports bulk CREATE operations"), - /** - * Whether the driver supports bulk update operations. - */ - bulkUpdate: external_exports.boolean().default(false).describe("Supports bulk UPDATE operations"), - /** - * Whether the driver supports bulk delete operations. - */ - bulkDelete: external_exports.boolean().default(false).describe("Supports bulk DELETE operations"), - // ============================================================================ - // Transaction & Connection Management - // ============================================================================ - /** - * Whether the driver supports database transactions. - * If true, beginTransaction, commit, and rollback must be implemented. - */ - transactions: external_exports.boolean().default(false).describe("Supports ACID transactions"), - /** - * Whether the driver supports savepoints within transactions. - */ - savepoints: external_exports.boolean().default(false).describe("Supports transaction savepoints"), - /** - * Supported transaction isolation levels. - */ - isolationLevels: external_exports.array(IsolationLevelEnum).optional().describe("Supported isolation levels"), - // ============================================================================ - // Query Operations - // ============================================================================ - /** - * Whether the driver supports WHERE clause filters. - * If false, ObjectQL will fetch all records and filter in memory. - * - * Example: Memory driver might not support complex filter conditions. - */ - queryFilters: external_exports.boolean().default(true).describe("Supports WHERE clause filtering"), - /** - * Whether the driver supports aggregation functions (COUNT, SUM, AVG, etc.). - * If false, ObjectQL will compute aggregations in memory. - */ - queryAggregations: external_exports.boolean().default(false).describe("Supports GROUP BY and aggregation functions"), - /** - * Whether the driver supports ORDER BY sorting. - * If false, ObjectQL will sort results in memory. - */ - querySorting: external_exports.boolean().default(true).describe("Supports ORDER BY sorting"), - /** - * Whether the driver supports LIMIT/OFFSET pagination. - * If false, ObjectQL will fetch all records and paginate in memory. - */ - queryPagination: external_exports.boolean().default(true).describe("Supports LIMIT/OFFSET pagination"), - /** - * Whether the driver supports window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.). - * If false, ObjectQL will compute window functions in memory. - */ - queryWindowFunctions: external_exports.boolean().default(false).describe("Supports window functions with OVER clause"), - /** - * Whether the driver supports subqueries (nested SELECT statements). - * If false, ObjectQL will execute queries separately and combine results. - */ - querySubqueries: external_exports.boolean().default(false).describe("Supports subqueries"), - /** - * Whether the driver supports Common Table Expressions (WITH clause). - */ - queryCTE: external_exports.boolean().default(false).describe("Supports Common Table Expressions (WITH clause)"), - /** - * Whether the driver supports SQL-style joins. - * If false, ObjectQL will fetch related data separately and join in memory. - */ - joins: external_exports.boolean().default(false).describe("Supports SQL joins"), - // ============================================================================ - // Advanced Features - // ============================================================================ - /** - * Whether the driver supports full-text search. - * If true, text search queries can be pushed to the database. - */ - fullTextSearch: external_exports.boolean().default(false).describe("Supports full-text search"), - /** - * Whether the driver supports JSON querying capabilities. - */ - jsonQuery: external_exports.boolean().default(false).describe("Supports JSON field querying"), - /** - * Whether the driver supports geospatial queries. - */ - geospatialQuery: external_exports.boolean().default(false).describe("Supports geospatial queries"), - /** - * Whether the driver supports streaming large result sets. - */ - streaming: external_exports.boolean().default(false).describe("Supports result streaming (cursors/iterators)"), - /** - * Whether the driver supports JSON field types. - * If false, JSON data will be serialized as strings. - */ - jsonFields: external_exports.boolean().default(false).describe("Supports JSON field types"), - /** - * Whether the driver supports array field types. - * If false, arrays will be stored as JSON strings or in separate tables. - */ - arrayFields: external_exports.boolean().default(false).describe("Supports array field types"), - /** - * Whether the driver supports vector embeddings and similarity search. - * Required for RAG (Retrieval-Augmented Generation) and AI features. - */ - vectorSearch: external_exports.boolean().default(false).describe("Supports vector embeddings and similarity search"), - // ============================================================================ - // Schema Management - // ============================================================================ - /** - * Whether the driver supports automatic schema synchronization. - */ - schemaSync: external_exports.boolean().default(false).describe("Supports automatic schema synchronization"), - /** - * Whether the driver supports batching multiple schema sync operations - * into a single (or fewer) round-trips for the DDL phase. When true, - * the engine may call `syncSchemasBatch()` instead of calling - * `syncSchema()` per object, reducing network round-trips for remote drivers. - */ - batchSchemaSync: external_exports.boolean().default(false).describe("Supports batched schema sync to reduce schema DDL round-trips"), - /** - * Whether the driver supports database migrations. - */ - migrations: external_exports.boolean().default(false).describe("Supports database migrations"), - /** - * Whether the driver supports index management. - */ - indexes: external_exports.boolean().default(false).describe("Supports index creation and management"), - // ============================================================================ - // Performance & Optimization - // ============================================================================ - /** - * Whether the driver supports connection pooling. - */ - connectionPooling: external_exports.boolean().default(false).describe("Supports connection pooling"), - /** - * Whether the driver supports prepared statements. - */ - preparedStatements: external_exports.boolean().default(false).describe("Supports prepared statements (SQL injection prevention)"), - /** - * Whether the driver supports query result caching. - */ - queryCache: external_exports.boolean().default(false).describe("Supports query result caching") - }); - DriverInterfaceSchema = external_exports.object({ - /** - * Driver name (e.g., 'postgresql', 'mongodb', 'rest_api'). - */ - name: external_exports.string().describe("Driver unique name"), - /** - * Driver version. - */ - version: external_exports.string().describe("Driver version"), - /** - * Capabilities descriptor. - */ - supports: DriverCapabilitiesSchema, - // ============================================================================ - // Lifecycle Management - // ============================================================================ - /** - * Initialize connection pool or authenticate. - */ - connect: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.void())).describe("Establish connection"), - /** - * Close connections and cleanup resources. - */ - disconnect: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.void())).describe("Close connection"), - /** - * Check connection health. - * @returns true if healthy, false otherwise. - */ - checkHealth: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.boolean())).describe("Health check"), - /** - * Get Connection Pool Statistics. - * Useful for monitoring database load. - */ - getPoolStats: external_exports.function().input(external_exports.tuple([])).output(external_exports.object({ - total: external_exports.number(), - idle: external_exports.number(), - active: external_exports.number(), - waiting: external_exports.number() - }).optional()).optional().describe("Get connection pool statistics"), - // ============================================================================ - // Raw Execution (Escape Hatch) - // ============================================================================ - /** - * Execute a raw command/query native to the driver. - * Useful for complex reports, stored procedures, or DDL not covered by standard sync. - * - * @param command - The raw command (e.g., SQL string, shell command, or remote API payload). - * @param parameters - Optional array of bound parameters for safe execution (prevention of injection). - * @param options - Driver options (transaction context, timeout). - * @returns Promise resolving to the raw result from the driver. - * - * @example - * // SQL Driver - * await driver.execute('SELECT * FROM complex_view WHERE id = ?', [123]); - * - * // Mongo Driver - * await driver.execute({ aggregate: 'orders', pipeline: [...] }); - */ - execute: external_exports.function().input(external_exports.tuple([external_exports.unknown(), external_exports.array(external_exports.unknown()).optional(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())).describe("Execute raw command"), - // ============================================================================ - // CRUD Operations - // ============================================================================ - /** - * Find multiple records matching the structured query. - * Parsing the QueryAST is the responsibility of the driver implementation. - * - * @param object - The name of the object/table to query (e.g. 'account'). - * @param query - The structured QueryAST (filters, sorts, joins, pagination). - * @param options - Driver options. - * @returns Array of records. - * - * @example - * await driver.find('account', { - * filters: [['status', '=', 'active'], 'and', ['amount', '>', 500]], - * sort: [{ field: 'created_at', order: 'desc' }], - * top: 10 - * }); - * @returns Array of records. - * MUST return `id` as string. MUST NOT return implementation details like `_id`. - */ - find: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))).describe("Find records"), - /** - * Stream records matching the structured query. - * Optimized for large datasets to avoid memory overflow. - * - * @param object - The name of the object. - * @param query - The structured QueryAST. - * @param options - Driver options. - * @returns AsyncIterable/ReadableStream of records. - */ - findStream: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.unknown()).describe("Stream records (AsyncIterable)"), - /** - * Find a single record by query. - * Similar to find(), but returns only the first match or null. - * - * @param object - The name of the object. - * @param query - QueryAST. - * @param options - Driver options. - * @returns The record or null. - * MUST return `id` as string. MUST NOT return implementation details like `_id`. - */ - findOne: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()).nullable())).describe("Find one record"), - /** - * Create a new record. - * - * @param object - The object name. - * @param data - Key-value map of field data. - * @param options - Driver options. - * @returns The created record, including server-generated fields (id, created_at, etc.). - * MUST return `id` as string. MUST NOT return implementation details like `_id`. - */ - create: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Create record"), - /** - * Update an existing record by ID. - * - * @param object - The object name. - * @param id - The unique identifier of the record. - * @param data - The fields to update. - * @param options - Driver options. - * @returns The updated record. - * MUST return `id` as string. MUST NOT return implementation details like `_id`. - */ - update: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.string().or(external_exports.number()), external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Update record"), - /** - * Upsert (Update or Insert) a record. - * - * @param object - The object name. - * @param data - The data to upsert. - * @param conflictKeys - Fields to check for conflict (uniqueness). - * @param options - Driver options. - * @returns The created or updated record. - */ - upsert: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.string()).optional(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Upsert record"), - /** - * Delete a record by ID. - * - * @param object - The object name. - * @param id - The unique identifier of the record. - * @param options - Driver options. - * @returns True if deleted, false if not found. - */ - delete: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.string().or(external_exports.number()), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.boolean())).describe("Delete record"), - /** - * Count records matching a query. - * - * @param object - The object name. - * @param query - Optional filtering criteria. - * @param options - Driver options. - * @returns Total count. - */ - count: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2.optional(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.number())).describe("Count records"), - // ============================================================================ - // Bulk Operations - // ============================================================================ - /** - * Create multiple records in a single batch. - * Optimized for performance. - * - * @param object - The object name. - * @param dataArray - Array of record data. - * @returns Array of created records. - */ - bulkCreate: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))), - /** - * Update multiple records in a single batch. - * - * @param object - The object name. - * @param updates - Array of objects containing {id, data}. - * @returns Array of updated records. - */ - bulkUpdate: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.object({ id: external_exports.string().or(external_exports.number()), data: external_exports.record(external_exports.string(), external_exports.unknown()) })), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))), - /** - * Delete multiple records in a single batch. - * - * @param object - The object name. - * @param ids - Array of record IDs. - */ - bulkDelete: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.string().or(external_exports.number())), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.void())), - /** - * Update multiple records matching a query. - * Direct database push-down. DOES NOT trigger per-record hooks. - * - * @param object - The object name. - * @param query - The filtering criteria. - * @param data - The data to update. - * @returns Count of modified records. - */ - updateMany: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.number())).optional(), - /** - * Delete multiple records matching a query. - * Direct database push-down. DOES NOT trigger per-record hooks. - * - * @param object - The object name. - * @param query - The filtering criteria. - * @returns Count of deleted records. - */ - deleteMany: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.number())).optional(), - // ============================================================================ - // Transaction Management - // ============================================================================ - /** - * Begin a new database transaction. - * @param options - Isolation level and other settings. - * @returns A transaction handle to be passed to subsequent operations via `options.transaction`. - */ - beginTransaction: external_exports.function().input(external_exports.tuple([external_exports.object({ - isolationLevel: IsolationLevelEnum.optional() - }).optional()])).output(external_exports.promise(external_exports.unknown())).describe("Start transaction"), - /** - * Commit the transaction. - * @param transaction - The transaction handle. - */ - commit: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.promise(external_exports.void())).describe("Commit transaction"), - /** - * Rollback the transaction. - * @param transaction - The transaction handle. - */ - rollback: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.promise(external_exports.void())).describe("Rollback transaction"), - // ============================================================================ - // Schema Management - // ============================================================================ - /** - * Synchronize the database schema with the Object definition. - * This is an idempotent operation: it should create tables if missing, - * add columns if missing, and update indexes. - * - * @param object - The object name. - * @param schema - The full Object Schema (fields, indexes, etc). - * @param options - Driver options. - */ - syncSchema: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.unknown(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.void())).describe("Sync object schema to DB"), - /** - * Batch-synchronize multiple object schemas with fewer round-trips. - * - * Drivers that advertise `supports.batchSchemaSync = true` MUST implement - * this method. The engine will call it once with every - * `{ object, schema }` pair instead of calling `syncSchema()` N times. - * - * @param schemas - Array of `{ object: string; schema: unknown }` pairs. - * @param options - Driver options. - */ - syncSchemasBatch: external_exports.function().input(external_exports.tuple([ - external_exports.array(external_exports.object({ object: external_exports.string(), schema: external_exports.unknown() })), - DriverOptionsSchema.optional() - ])).output(external_exports.promise(external_exports.void())).optional().describe("Batch sync multiple schemas in one round-trip"), - /** - * Drop the underlying table or collection for an object. - * WARNING: Destructive operation. - * - * @param object - The object name. - */ - dropTable: external_exports.function().input(external_exports.tuple([external_exports.string(), DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.void())), - /** - * Analyze query performance. - * Returns execution plan without executing the query (where possible). - * - * @param object - The object name. - * @param query - The query to explain. - * @returns The execution plan details. - */ - explain: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema2, DriverOptionsSchema.optional()])).output(external_exports.promise(external_exports.unknown())).optional() - }); - PoolConfigSchema = external_exports.object({ - min: external_exports.number().min(0).default(2).describe("Minimum number of connections in pool"), - max: external_exports.number().min(1).default(10).describe("Maximum number of connections in pool"), - idleTimeoutMillis: external_exports.number().min(0).default(3e4).describe("Time in ms before idle connection is closed"), - connectionTimeoutMillis: external_exports.number().min(0).default(5e3).describe("Time in ms to wait for available connection") - }); - DriverConfigSchema = external_exports.object({ - name: external_exports.string().describe("Driver instance name"), - type: external_exports.enum(["sql", "nosql", "cache", "search", "graph", "timeseries"]).describe("Driver type category"), - capabilities: DriverCapabilitiesSchema.describe("Driver capability flags"), - connectionString: external_exports.string().optional().describe("Database connection string (driver-specific format)"), - poolConfig: PoolConfigSchema.optional().describe("Connection pool configuration") - }); - SQLDialectSchema = external_exports.enum([ - "postgresql", - "mysql", - "sqlite", - "mssql", - "oracle", - "mariadb" - ]); - DataTypeMappingSchema = external_exports.object({ - text: external_exports.string().describe("SQL type for text fields (e.g., VARCHAR, TEXT)"), - number: external_exports.string().describe("SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)"), - boolean: external_exports.string().describe("SQL type for boolean fields (e.g., BOOLEAN, BIT)"), - date: external_exports.string().describe("SQL type for date fields (e.g., DATE)"), - datetime: external_exports.string().describe("SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)"), - json: external_exports.string().optional().describe("SQL type for JSON fields (e.g., JSON, JSONB)"), - uuid: external_exports.string().optional().describe("SQL type for UUID fields (e.g., UUID, CHAR(36))"), - binary: external_exports.string().optional().describe("SQL type for binary fields (e.g., BLOB, BYTEA)") - }); - SSLConfigSchema = external_exports.object({ - rejectUnauthorized: external_exports.boolean().default(true).describe("Reject connections with invalid certificates"), - ca: external_exports.string().optional().describe("CA certificate file path or content"), - cert: external_exports.string().optional().describe("Client certificate file path or content"), - key: external_exports.string().optional().describe("Client private key file path or content") - }).refine((data) => { - const hasCert = data.cert !== void 0; - const hasKey = data.key !== void 0; - return hasCert === hasKey; - }, { - message: "Client certificate (cert) and private key (key) must be provided together" - }); - SQLDriverConfigSchema = DriverConfigSchema.extend({ - type: external_exports.literal("sql").describe('Driver type must be "sql"'), - dialect: SQLDialectSchema.describe("SQL database dialect"), - dataTypeMapping: DataTypeMappingSchema.describe("SQL data type mapping configuration"), - ssl: external_exports.boolean().default(false).describe("Enable SSL/TLS connection"), - sslConfig: SSLConfigSchema.optional().describe("SSL/TLS configuration (required when ssl is true)") - }).refine((data) => { - if (data.ssl && !data.sslConfig) { - return false; - } - return true; - }, { - message: "sslConfig is required when ssl is true" - }); - SQLiteDataTypeMappingDefaults = { - text: "TEXT", - number: "REAL", - boolean: "INTEGER", - date: "TEXT", - datetime: "TEXT", - json: "TEXT", - uuid: "TEXT", - binary: "BLOB" - }; - SQLiteAlterTableLimitations = { - /** SQLite supports ADD COLUMN */ - supportsAddColumn: true, - /** SQLite supports RENAME COLUMN (3.25.0+) */ - supportsRenameColumn: true, - /** SQLite supports DROP COLUMN (3.35.0+) */ - supportsDropColumn: true, - /** SQLite does NOT support MODIFY/ALTER COLUMN type */ - supportsModifyColumn: false, - /** SQLite does NOT support adding constraints to existing columns */ - supportsAddConstraint: false, - /** - * When an unsupported alteration is needed, the migration planner - * must use the 12-step table rebuild strategy: - * 1. CREATE new table with desired schema - * 2. Copy data from old table - * 3. DROP old table - * 4. RENAME new table to old name - */ - rebuildStrategy: "create_copy_drop_rename" - }; - NoSQLDatabaseTypeSchema = external_exports.enum([ - "mongodb", - "couchdb", - "dynamodb", - "cassandra", - "redis", - "elasticsearch", - "neo4j", - "orientdb" - ]); - NoSQLOperationTypeSchema = external_exports.enum([ - "find", - // Query documents/records - "findOne", - // Get single document - "insert", - // Insert document - "update", - // Update document - "delete", - // Delete document - "aggregate", - // Aggregation pipeline - "mapReduce", - // MapReduce operation - "count", - // Count documents - "distinct", - // Get distinct values - "createIndex", - // Create index - "dropIndex" - // Drop index - ]); - ConsistencyLevelSchema = external_exports.enum([ - "all", - "quorum", - "one", - "local_quorum", - "each_quorum", - "eventual" - ]); - NoSQLIndexTypeSchema = external_exports.enum([ - "single", - // Single field index - "compound", - // Multiple fields index - "unique", - // Unique constraint - "text", - // Full-text search index - "geospatial", - // Geospatial index (2d, 2dsphere) - "hashed", - // Hashed index for sharding - "ttl", - // Time-to-live index (auto-deletion) - "sparse" - // Sparse index (only indexed documents with field) - ]); - ShardingConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable sharding"), - shardKey: external_exports.string().optional().describe("Field to use as shard key"), - shardingStrategy: external_exports.enum(["hash", "range", "zone"]).optional().describe("Sharding strategy"), - numShards: external_exports.number().int().positive().optional().describe("Number of shards") - }); - ReplicationConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable replication"), - replicaSetName: external_exports.string().optional().describe("Replica set name"), - replicas: external_exports.number().int().positive().optional().describe("Number of replicas"), - readPreference: external_exports.enum(["primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"]).optional().describe("Read preference for replica set"), - writeConcern: external_exports.enum(["majority", "acknowledged", "unacknowledged"]).optional().describe("Write concern level") - }); - DocumentSchemaValidationSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable schema validation"), - validationLevel: external_exports.enum(["strict", "moderate", "off"]).optional().describe("Validation strictness"), - validationAction: external_exports.enum(["error", "warn"]).optional().describe("Action on validation failure"), - jsonSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON Schema for validation") - }); - NoSQLDataTypeMappingSchema = external_exports.object({ - text: external_exports.string().describe("NoSQL type for text fields"), - number: external_exports.string().describe("NoSQL type for number fields"), - boolean: external_exports.string().describe("NoSQL type for boolean fields"), - date: external_exports.string().describe("NoSQL type for date fields"), - datetime: external_exports.string().describe("NoSQL type for datetime fields"), - json: external_exports.string().optional().describe("NoSQL type for JSON/object fields"), - uuid: external_exports.string().optional().describe("NoSQL type for UUID fields"), - binary: external_exports.string().optional().describe("NoSQL type for binary fields"), - array: external_exports.string().optional().describe("NoSQL type for array fields"), - objectId: external_exports.string().optional().describe("NoSQL type for ObjectID fields (MongoDB)"), - geopoint: external_exports.string().optional().describe("NoSQL type for geospatial point fields") - }); - NoSQLDriverConfigSchema = DriverConfigSchema.extend({ - type: external_exports.literal("nosql").describe('Driver type must be "nosql"'), - databaseType: NoSQLDatabaseTypeSchema.describe("Specific NoSQL database type"), - dataTypeMapping: NoSQLDataTypeMappingSchema.describe("NoSQL data type mapping configuration"), - /** - * Consistency level for reads/writes - */ - consistency: ConsistencyLevelSchema.optional().describe("Consistency level for operations"), - /** - * Replication configuration - */ - replication: ReplicationConfigSchema.optional().describe("Replication configuration"), - /** - * Sharding configuration - */ - sharding: ShardingConfigSchema.optional().describe("Sharding configuration"), - /** - * Schema validation rules (for document databases) - */ - schemaValidation: DocumentSchemaValidationSchema.optional().describe("Document schema validation"), - /** - * AWS Region (for DynamoDB, DocumentDB, etc.) - */ - region: external_exports.string().optional().describe("AWS region (for managed NoSQL services)"), - /** - * AWS Access Key ID (for DynamoDB, DocumentDB, etc.) - */ - accessKeyId: external_exports.string().optional().describe("AWS access key ID"), - /** - * AWS Secret Access Key (for DynamoDB, DocumentDB, etc.) - */ - secretAccessKey: external_exports.string().optional().describe("AWS secret access key"), - /** - * Time-to-live (TTL) field name - * Automatically delete documents after a specified time - */ - ttlField: external_exports.string().optional().describe("Field name for TTL (auto-deletion)"), - /** - * Maximum document size in bytes - */ - maxDocumentSize: external_exports.number().int().positive().optional().describe("Maximum document size in bytes"), - /** - * Collection/Table name prefix - * Useful for multi-tenancy or environment isolation - */ - collectionPrefix: external_exports.string().optional().describe("Prefix for collection/table names") - }); - NoSQLQueryOptionsSchema = external_exports.object({ - /** - * Consistency level for this query - */ - consistency: ConsistencyLevelSchema.optional().describe("Consistency level override"), - /** - * Read from secondary replicas - */ - readFromSecondary: external_exports.boolean().optional().describe("Allow reading from secondary replicas"), - /** - * Projection (fields to include/exclude) - */ - projection: external_exports.record(external_exports.string(), external_exports.union([external_exports.literal(0), external_exports.literal(1)])).optional().describe("Field projection"), - /** - * Query timeout in milliseconds - */ - timeout: external_exports.number().int().positive().optional().describe("Query timeout (ms)"), - /** - * Use cursor for large result sets - */ - useCursor: external_exports.boolean().optional().describe("Use cursor instead of loading all results"), - /** - * Batch size for cursor iteration - */ - batchSize: external_exports.number().int().positive().optional().describe("Cursor batch size"), - /** - * Enable query profiling - */ - profile: external_exports.boolean().optional().describe("Enable query profiling"), - /** - * Use hinted index - */ - hint: external_exports.string().optional().describe("Index hint for query optimization") - }); - AggregationStageSchema = external_exports.object({ - /** - * Stage operator (e.g., $match, $group, $sort, $project) - */ - operator: external_exports.string().describe("Aggregation operator (e.g., $match, $group, $sort)"), - /** - * Stage parameters/options - */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Stage-specific options") - }); - AggregationPipelineSchema = external_exports.object({ - /** - * Collection/Table to aggregate - */ - collection: external_exports.string().describe("Collection/table name"), - /** - * Pipeline stages - */ - stages: external_exports.array(AggregationStageSchema).describe("Aggregation pipeline stages"), - /** - * Additional options - */ - options: NoSQLQueryOptionsSchema.optional().describe("Query options") - }); - NoSQLIndexSchema = external_exports.object({ - /** - * Index name - */ - name: external_exports.string().describe("Index name"), - /** - * Index type - */ - type: NoSQLIndexTypeSchema.describe("Index type"), - /** - * Fields to index - * For compound indexes, order matters - */ - fields: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name"), - order: external_exports.enum(["asc", "desc", "text", "2dsphere"]).optional().describe("Index order or type") - })).describe("Fields to index"), - /** - * Unique constraint - */ - unique: external_exports.boolean().default(false).describe("Enforce uniqueness"), - /** - * Sparse index (only index documents with the field) - */ - sparse: external_exports.boolean().default(false).describe("Sparse index"), - /** - * TTL in seconds (for TTL indexes) - */ - expireAfterSeconds: external_exports.number().int().positive().optional().describe("TTL in seconds"), - /** - * Partial index filter - */ - partialFilterExpression: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Partial index filter"), - /** - * Background index creation - */ - background: external_exports.boolean().default(false).describe("Create index in background") - }); - NoSQLTransactionOptionsSchema = external_exports.object({ - /** - * Read concern level - */ - readConcern: external_exports.enum(["local", "majority", "linearizable", "snapshot"]).optional().describe("Read concern level"), - /** - * Write concern level - */ - writeConcern: external_exports.enum(["majority", "acknowledged", "unacknowledged"]).optional().describe("Write concern level"), - /** - * Read preference - */ - readPreference: external_exports.enum(["primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"]).optional().describe("Read preference"), - /** - * Transaction timeout in milliseconds - */ - maxCommitTimeMS: external_exports.number().int().positive().optional().describe("Transaction commit timeout (ms)") - }); - DatasetMode2 = external_exports.enum([ - "insert", - // Try to insert, fail on duplicate - "update", - // Only update found records, ignore new - "upsert", - // Create new or Update existing (Standard) - "replace", - // Delete ALL records in object then insert (Dangerous - use for cache tables) - "ignore" - // Try to insert, silently skip duplicates - ]); - DatasetSchema2 = external_exports.object({ - /** - * Target Object - * The machine name of the object to populate. - */ - object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target Object Name"), - /** - * Idempotency Key (The "Upsert" Key) - * The field used to check if a record already exists. - * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'. - * Standard: 'id' is rarely used for portable seed data — prefer natural keys. - */ - externalId: external_exports.string().default("name").describe("Field match for uniqueness check"), - /** - * Import Strategy - */ - mode: DatasetMode2.default("upsert").describe("Conflict resolution strategy"), - /** - * Environment Scope - * - 'all': Always load - * - 'dev': Only for development/demo - * - 'test': Only for CI/CD tests - */ - env: external_exports.array(external_exports.enum(["prod", "dev", "test"])).default(["prod", "dev", "test"]).describe("Applicable environments"), - /** - * The Payload - * Array of raw JSON objects matching the Object Schema. - */ - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Data records") - }); - ReferenceResolutionSchema = external_exports.object({ - /** The field name on the source object (e.g., 'account_id') */ - field: external_exports.string().describe("Source field name containing the reference value"), - /** The target object being referenced (e.g., 'account') */ - targetObject: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target object name (snake_case)"), - /** - * The field on the target object used to match the reference value. - * Defaults to the target object's externalId (usually 'name'). - */ - targetField: external_exports.string().default("name").describe("Field on target object used for matching"), - /** The field type that triggered this resolution (lookup or master_detail) */ - fieldType: external_exports.enum(["lookup", "master_detail"]).describe("Relationship field type") - }).describe("Describes how a field reference is resolved during seed loading"); - ObjectDependencyNodeSchema = external_exports.object({ - /** Object machine name */ - object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Object name (snake_case)"), - /** - * Objects that this object depends on (via lookup/master_detail fields). - * These must be loaded before this object. - */ - dependsOn: external_exports.array(external_exports.string()).describe("Objects this object depends on"), - /** - * Field-level reference details for each dependency. - * Maps field name → reference resolution info. - */ - references: external_exports.array(ReferenceResolutionSchema).describe("Field-level reference details") - }).describe("Object node in the seed data dependency graph"); - ObjectDependencyGraphSchema = external_exports.object({ - /** All object nodes in the graph */ - nodes: external_exports.array(ObjectDependencyNodeSchema).describe("All objects in the dependency graph"), - /** - * Topologically sorted object names for insertion order. - * Parent objects appear before child objects. - */ - insertOrder: external_exports.array(external_exports.string()).describe("Topologically sorted insert order"), - /** - * Circular dependency chains detected in the graph. - * Each chain is an array of object names forming a cycle. - * When present, the loader must use a multi-pass strategy. - * - * @example [['project', 'task', 'project']] - */ - circularDependencies: external_exports.array(external_exports.array(external_exports.string())).default([]).describe('Circular dependency chains (e.g., [["a", "b", "a"]])') - }).describe("Complete object dependency graph for seed data loading"); - ReferenceResolutionErrorSchema = external_exports.object({ - /** The source object containing the broken reference */ - sourceObject: external_exports.string().describe("Object with the broken reference"), - /** The field containing the unresolved value */ - field: external_exports.string().describe("Field name with unresolved reference"), - /** The target object that was searched */ - targetObject: external_exports.string().describe("Target object searched for the reference"), - /** The externalId field used for matching on the target object */ - targetField: external_exports.string().describe("ExternalId field used for matching"), - /** The value that could not be resolved */ - attemptedValue: external_exports.unknown().describe("Value that failed to resolve"), - /** The index of the record in the dataset's records array */ - recordIndex: external_exports.number().int().min(0).describe("Index of the record in the dataset"), - /** Human-readable error message */ - message: external_exports.string().describe("Human-readable error description") - }).describe("Actionable error for a failed reference resolution"); - SeedLoaderConfigSchema = external_exports.object({ - /** - * Dry-run mode: validate all references without writing data. - * Surfaces broken references before any mutations occur. - * @default false - */ - dryRun: external_exports.boolean().default(false).describe("Validate references without writing data"), - /** - * Whether to halt on the first reference resolution error. - * When false, collects all errors and continues loading. - * @default false - */ - haltOnError: external_exports.boolean().default(false).describe("Stop on first reference resolution error"), - /** - * Enable multi-pass loading for circular dependencies. - * Pass 1: Insert records with null for circular references. - * Pass 2: Update records to fill deferred references. - * @default true - */ - multiPass: external_exports.boolean().default(true).describe("Enable multi-pass loading for circular dependencies"), - /** - * Default dataset mode when not specified per-dataset. - * @default 'upsert' - */ - defaultMode: DatasetMode2.default("upsert").describe("Default conflict resolution strategy"), - /** - * Maximum number of records to process in a single batch. - * Controls memory usage for large datasets. - * @default 1000 - */ - batchSize: external_exports.number().int().min(1).default(1e3).describe("Maximum records per batch insert/upsert"), - /** - * Whether to wrap the entire load operation in a transaction. - * When true, all-or-nothing semantics apply. - * @default false - */ - transaction: external_exports.boolean().default(false).describe("Wrap entire load in a transaction (all-or-nothing)"), - /** - * Environment filter. Only datasets matching this environment are loaded. - * When not specified, all datasets are loaded regardless of env scope. - */ - env: external_exports.enum(["prod", "dev", "test"]).optional().describe("Only load datasets matching this environment") - }).describe("Seed data loader configuration"); - DatasetLoadResultSchema = external_exports.object({ - /** Target object name */ - object: external_exports.string().describe("Object that was loaded"), - /** Import mode used */ - mode: DatasetMode2.describe("Import mode used"), - /** Number of records successfully inserted */ - inserted: external_exports.number().int().min(0).describe("Records inserted"), - /** Number of records successfully updated (upsert matched existing) */ - updated: external_exports.number().int().min(0).describe("Records updated"), - /** Number of records skipped (mode: ignore, or already exists) */ - skipped: external_exports.number().int().min(0).describe("Records skipped"), - /** Number of records with errors */ - errored: external_exports.number().int().min(0).describe("Records with errors"), - /** Total records in the dataset */ - total: external_exports.number().int().min(0).describe("Total records in dataset"), - /** Number of references resolved via externalId */ - referencesResolved: external_exports.number().int().min(0).describe("References resolved via externalId"), - /** Number of references deferred to pass 2 (circular dependencies) */ - referencesDeferred: external_exports.number().int().min(0).describe("References deferred to second pass"), - /** Reference resolution errors for this object */ - errors: external_exports.array(ReferenceResolutionErrorSchema).default([]).describe("Reference resolution errors") - }).describe("Result of loading a single dataset"); - SeedLoaderResultSchema = external_exports.object({ - /** Whether the overall load operation succeeded */ - success: external_exports.boolean().describe("Overall success status"), - /** Was this a dry-run (validation only, no writes)? */ - dryRun: external_exports.boolean().describe("Whether this was a dry-run"), - /** The dependency graph used for ordering */ - dependencyGraph: ObjectDependencyGraphSchema.describe("Object dependency graph"), - /** Per-object load results, in the order they were processed */ - results: external_exports.array(DatasetLoadResultSchema).describe("Per-object load results"), - /** All reference resolution errors across all objects */ - errors: external_exports.array(ReferenceResolutionErrorSchema).describe("All reference resolution errors"), - /** Summary statistics */ - summary: external_exports.object({ - /** Total objects processed */ - objectsProcessed: external_exports.number().int().min(0).describe("Total objects processed"), - /** Total records across all objects */ - totalRecords: external_exports.number().int().min(0).describe("Total records across all objects"), - /** Total records inserted */ - totalInserted: external_exports.number().int().min(0).describe("Total records inserted"), - /** Total records updated */ - totalUpdated: external_exports.number().int().min(0).describe("Total records updated"), - /** Total records skipped */ - totalSkipped: external_exports.number().int().min(0).describe("Total records skipped"), - /** Total records with errors */ - totalErrored: external_exports.number().int().min(0).describe("Total records with errors"), - /** Total references resolved via externalId */ - totalReferencesResolved: external_exports.number().int().min(0).describe("Total references resolved"), - /** Total references deferred to second pass */ - totalReferencesDeferred: external_exports.number().int().min(0).describe("Total references deferred"), - /** Number of circular dependency chains detected */ - circularDependencyCount: external_exports.number().int().min(0).describe("Circular dependency chains detected"), - /** Duration of the load operation in milliseconds */ - durationMs: external_exports.number().min(0).describe("Load duration in milliseconds") - }).describe("Summary statistics") - }).describe("Complete seed loader result"); - SeedLoaderRequestSchema = external_exports.object({ - /** Datasets to load */ - datasets: external_exports.array(DatasetSchema2).min(1).describe("Datasets to load"), - /** Loader configuration */ - config: external_exports.preprocess((val) => val ?? {}, SeedLoaderConfigSchema).describe("Loader configuration") - }).describe("Seed loader request with datasets and configuration"); - DocumentVersionSchema = external_exports.object({ - /** - * Sequential version number (increments with each new version) - */ - versionNumber: external_exports.number().describe("Version number"), - /** - * Timestamp when this version was created (Unix milliseconds) - */ - createdAt: external_exports.number().describe("Creation timestamp"), - /** - * User ID who created this version - */ - createdBy: external_exports.string().describe("Creator user ID"), - /** - * File size in bytes - */ - size: external_exports.number().describe("File size in bytes"), - /** - * Checksum/hash of the file content (for integrity verification) - */ - checksum: external_exports.string().describe("File checksum"), - /** - * URL to download this specific version - */ - downloadUrl: external_exports.string().url().describe("Download URL"), - /** - * Whether this is the latest version - * @default false - */ - isLatest: external_exports.boolean().optional().default(false).describe("Is latest version") - }); - DocumentTemplateSchema = external_exports.object({ - /** - * Unique identifier for the template - */ - id: external_exports.string().describe("Template ID"), - /** - * Human-readable name of the template - */ - name: external_exports.string().describe("Template name"), - /** - * Optional description of the template's purpose - */ - description: external_exports.string().optional().describe("Template description"), - /** - * URL to the template file - */ - fileUrl: external_exports.string().url().describe("Template file URL"), - /** - * MIME type of the template file - */ - fileType: external_exports.string().describe("File MIME type"), - /** - * List of dynamic placeholders in the template - */ - placeholders: external_exports.array(external_exports.object({ - /** - * Placeholder identifier (used in template) - */ - key: external_exports.string().describe("Placeholder key"), - /** - * Human-readable label for the placeholder - */ - label: external_exports.string().describe("Placeholder label"), - /** - * Data type of the placeholder value - */ - type: external_exports.enum(["text", "number", "date", "image"]).describe("Placeholder type"), - /** - * Whether this placeholder must be filled - * @default false - */ - required: external_exports.boolean().optional().default(false).describe("Is required") - })).describe("Template placeholders") - }); - ESignatureConfigSchema = external_exports.object({ - /** - * E-signature service provider - */ - provider: external_exports.enum(["docusign", "adobe-sign", "hellosign", "custom"]).describe("E-signature provider"), - /** - * Whether e-signature is enabled for this document - * @default false - */ - enabled: external_exports.boolean().optional().default(false).describe("E-signature enabled"), - /** - * List of signers in signing order - */ - signers: external_exports.array(external_exports.object({ - /** - * Signer's email address - */ - email: external_exports.string().email().describe("Signer email"), - /** - * Signer's full name - */ - name: external_exports.string().describe("Signer name"), - /** - * Signer's role in the document - */ - role: external_exports.string().describe("Signer role"), - /** - * Signing order (lower numbers sign first) - */ - order: external_exports.number().describe("Signing order") - })).describe("Document signers"), - /** - * Days until signature request expires - * @default 30 - */ - expirationDays: external_exports.number().optional().default(30).describe("Expiration days"), - /** - * Days between reminder emails - * @default 7 - */ - reminderDays: external_exports.number().optional().default(7).describe("Reminder interval days") - }); - DocumentSchema = external_exports.object({ - /** - * Unique document identifier - */ - id: external_exports.string().describe("Document ID"), - /** - * Document name - */ - name: external_exports.string().describe("Document name"), - /** - * Optional document description - */ - description: external_exports.string().optional().describe("Document description"), - /** - * MIME type of the document - */ - fileType: external_exports.string().describe("File MIME type"), - /** - * File size in bytes - */ - fileSize: external_exports.number().describe("File size in bytes"), - /** - * Document category for organization - */ - category: external_exports.string().optional().describe("Document category"), - /** - * Tags for searchability and organization - */ - tags: external_exports.array(external_exports.string()).optional().describe("Document tags"), - /** - * Version control configuration - */ - versioning: external_exports.object({ - /** - * Whether versioning is enabled - */ - enabled: external_exports.boolean().describe("Versioning enabled"), - /** - * List of all document versions - */ - versions: external_exports.array(DocumentVersionSchema).describe("Version history"), - /** - * Current major version number - */ - majorVersion: external_exports.number().describe("Major version"), - /** - * Current minor version number - */ - minorVersion: external_exports.number().describe("Minor version") - }).optional().describe("Version control"), - /** - * Template configuration (if document is generated from template) - */ - template: DocumentTemplateSchema.optional().describe("Document template"), - /** - * E-signature configuration - */ - eSignature: ESignatureConfigSchema.optional().describe("E-signature config"), - /** - * Access control settings - */ - access: external_exports.object({ - /** - * Whether document is publicly accessible - * @default false - */ - isPublic: external_exports.boolean().optional().default(false).describe("Public access"), - /** - * List of user/team IDs with access - */ - sharedWith: external_exports.array(external_exports.string()).optional().describe("Shared with"), - /** - * Timestamp when access expires (Unix milliseconds) - */ - expiresAt: external_exports.number().optional().describe("Access expiration") - }).optional().describe("Access control"), - /** - * Custom metadata fields - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") - }); - TransformTypeSchema = external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("constant"), - value: external_exports.unknown().describe("Constant value to use") - }).describe("Set a constant value"), - external_exports.object({ - type: external_exports.literal("cast"), - targetType: external_exports.enum(["string", "number", "boolean", "date"]).describe("Target data type") - }).describe("Cast to a specific data type"), - external_exports.object({ - type: external_exports.literal("lookup"), - table: external_exports.string().describe("Lookup table name"), - keyField: external_exports.string().describe("Field to match on"), - valueField: external_exports.string().describe("Field to retrieve") - }).describe("Lookup value from another table"), - external_exports.object({ - type: external_exports.literal("javascript"), - expression: external_exports.string().describe('JavaScript expression (e.g., "value.toUpperCase()")') - }).describe("Custom JavaScript transformation"), - external_exports.object({ - type: external_exports.literal("map"), - mappings: external_exports.record(external_exports.string(), external_exports.unknown()).describe('Value mappings (e.g., {"Active": "active"})') - }).describe("Map values using a dictionary") - ]); - FieldMappingSchema2 = external_exports.object({ - /** - * Source field name - */ - source: external_exports.string().describe("Source field name"), - /** - * Target field name (should be snake_case for ObjectStack) - */ - target: external_exports.string().describe("Target field name"), - /** - * Transformation to apply - */ - transform: TransformTypeSchema.optional().describe("Transformation to apply"), - /** - * Default value if source is null/undefined - */ - defaultValue: external_exports.unknown().optional().describe("Default if source is null/undefined") - }); - ExternalDataSourceSchema = external_exports.object({ - /** - * Unique identifier for the external data source - */ - id: external_exports.string().describe("Data source ID"), - /** - * Human-readable name of the data source - */ - name: external_exports.string().describe("Data source name"), - /** - * Protocol type for connecting to the data source - */ - type: external_exports.enum(["odata", "rest-api", "graphql", "custom"]).describe("Protocol type"), - /** - * Base URL endpoint for the external system - */ - endpoint: external_exports.string().url().describe("API endpoint URL"), - /** - * Authentication configuration - */ - authentication: external_exports.object({ - /** - * Authentication method - */ - type: external_exports.enum(["oauth2", "api-key", "basic", "none"]).describe("Auth type"), - /** - * Authentication-specific configuration - * Structure varies based on auth type - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Auth configuration") - }).describe("Authentication") - }); - ExternalFieldMappingSchema = FieldMappingSchema2.extend({ - /** - * Field data type - */ - type: external_exports.string().optional().describe("Field type"), - /** - * Whether the field is read-only - * @default true - */ - readonly: external_exports.boolean().optional().default(true).describe("Read-only field") - }); - ExternalLookupSchema = external_exports.object({ - /** - * Name of the field that uses external lookup - */ - fieldName: external_exports.string().describe("Field name"), - /** - * External data source configuration - */ - dataSource: ExternalDataSourceSchema.describe("External data source"), - /** - * Query configuration for fetching external data - */ - query: external_exports.object({ - /** - * API endpoint path (relative to base endpoint) - */ - endpoint: external_exports.string().describe("Query endpoint path"), - /** - * HTTP method for the query - * @default 'GET' - */ - method: external_exports.enum(["GET", "POST"]).optional().default("GET").describe("HTTP method"), - /** - * Query parameters or request body - */ - parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters") - }).describe("Query configuration"), - /** - * Mapping between external and local fields - */ - fieldMappings: external_exports.array(ExternalFieldMappingSchema).describe("Field mappings"), - /** - * Cache configuration for external data - */ - caching: external_exports.object({ - /** - * Whether caching is enabled - * @default true - */ - enabled: external_exports.boolean().optional().default(true).describe("Cache enabled"), - /** - * Time-to-live in seconds - * @default 300 - */ - ttl: external_exports.number().optional().default(300).describe("Cache TTL (seconds)"), - /** - * Cache eviction strategy - * @default 'ttl' - */ - strategy: external_exports.enum(["lru", "lfu", "ttl"]).optional().default("ttl").describe("Cache strategy") - }).optional().describe("Caching configuration"), - /** - * Fallback behavior when external system is unavailable - */ - fallback: external_exports.object({ - /** - * Whether fallback is enabled - * @default true - */ - enabled: external_exports.boolean().optional().default(true).describe("Fallback enabled"), - /** - * Default value to use when external system fails - */ - defaultValue: external_exports.unknown().optional().describe("Default fallback value"), - /** - * Whether to show error message to user - * @default true - */ - showError: external_exports.boolean().optional().default(true).describe("Show error to user") - }).optional().describe("Fallback configuration"), - /** - * Rate limiting to prevent overwhelming external system - */ - rateLimit: external_exports.object({ - /** - * Maximum requests per second - */ - requestsPerSecond: external_exports.number().describe("Requests per second limit"), - /** - * Burst size for handling spikes - */ - burstSize: external_exports.number().optional().describe("Burst size") - }).optional().describe("Rate limiting"), - /** - * Retry configuration with exponential backoff - * - * @example - * ```json - * { - * "maxRetries": 3, - * "initialDelayMs": 1000, - * "maxDelayMs": 30000, - * "backoffMultiplier": 2, - * "retryableStatusCodes": [429, 500, 502, 503, 504] - * } - * ``` - */ - retry: external_exports.object({ - /** Maximum number of retry attempts */ - maxRetries: external_exports.number().min(0).default(3).describe("Maximum retry attempts"), - /** Initial delay before first retry (ms) */ - initialDelayMs: external_exports.number().default(1e3).describe("Initial retry delay in milliseconds"), - /** Maximum delay between retries (ms) */ - maxDelayMs: external_exports.number().default(3e4).describe("Maximum retry delay in milliseconds"), - /** Backoff multiplier for exponential backoff */ - backoffMultiplier: external_exports.number().default(2).describe("Exponential backoff multiplier"), - /** HTTP status codes that trigger a retry */ - retryableStatusCodes: external_exports.array(external_exports.number()).default([429, 500, 502, 503, 504]).describe("HTTP status codes that are retryable") - }).optional().describe("Retry configuration with exponential backoff"), - /** - * Request/response transformation pipeline - * - * Allows transforming request parameters and response data - * before they are processed by the external lookup system. - */ - transform: external_exports.object({ - /** Transform request parameters before sending */ - request: external_exports.object({ - /** Header transformations (key-value additions) */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Additional request headers"), - /** Query parameter transformations */ - queryParams: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Additional query parameters") - }).optional().describe("Request transformation"), - /** Transform response data after receiving */ - response: external_exports.object({ - /** JSONPath expression to extract data from response */ - dataPath: external_exports.string().optional().describe('JSONPath to extract data (e.g., "$.data.results")'), - /** JSONPath expression to extract total count for pagination */ - totalPath: external_exports.string().optional().describe('JSONPath to extract total count (e.g., "$.meta.total")') - }).optional().describe("Response transformation") - }).optional().describe("Request/response transformation pipeline"), - /** Pagination support for external data sources */ - pagination: external_exports.object({ - /** Pagination type */ - type: external_exports.enum(["offset", "cursor", "page"]).default("offset").describe("Pagination type"), - /** Page size */ - pageSize: external_exports.number().default(100).describe("Items per page"), - /** Maximum pages to fetch */ - maxPages: external_exports.number().optional().describe("Maximum number of pages to fetch") - }).optional().describe("Pagination configuration for external data") - }); - DriverType = external_exports.string().describe("Underlying driver identifier"); - DriverDefinitionSchema = external_exports.object({ - id: external_exports.string().describe('Unique driver identifier (e.g. "postgres")'), - label: external_exports.string().describe('Display label (e.g. "PostgreSQL")'), - description: external_exports.string().optional(), - icon: external_exports.string().optional(), - /** - * Configuration Schema (JSON Schema) - * Describes the structure of the `config` object needed for this driver. - * Used by the UI to generate the connection form. - */ - configSchema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema for connection configuration"), - /** - * Default Capabilities - * What this driver supports out-of-the-box. - */ - capabilities: external_exports.lazy(() => DatasourceCapabilities).optional() - }); - DatasourceCapabilities = external_exports.object({ - // ============================================================================ - // Transaction & Connection Management - // ============================================================================ - /** Can handle ACID transactions? */ - transactions: external_exports.boolean().default(false), - // ============================================================================ - // Query Operations - // ============================================================================ - /** Can execute WHERE clause filters natively? */ - queryFilters: external_exports.boolean().default(false), - /** Can perform aggregation (group by, sum, avg)? */ - queryAggregations: external_exports.boolean().default(false), - /** Can perform ORDER BY sorting? */ - querySorting: external_exports.boolean().default(false), - /** Can perform LIMIT/OFFSET pagination? */ - queryPagination: external_exports.boolean().default(false), - /** Can perform window functions? */ - queryWindowFunctions: external_exports.boolean().default(false), - /** Can perform subqueries? */ - querySubqueries: external_exports.boolean().default(false), - /** Can execute SQL-like joins natively? */ - joins: external_exports.boolean().default(false), - // ============================================================================ - // Advanced Features - // ============================================================================ - /** Can perform full-text search? */ - fullTextSearch: external_exports.boolean().default(false), - /** Is read-only? */ - readOnly: external_exports.boolean().default(false), - /** Is scheme-less (needs schema inference)? */ - dynamicSchema: external_exports.boolean().default(false) - }); - DatasourceSchema = external_exports.object({ - /** Machine Name */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique datasource identifier"), - /** Human Label */ - label: external_exports.string().optional().describe("Display label"), - /** Driver */ - driver: DriverType.describe("Underlying driver type"), - /** - * Connection Configuration - * Specific to the driver (e.g., host, port, user, password, bucket, etc.) - * Stored securely (passwords usually interpolated from ENV). - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Driver specific configuration"), - /** - * Connection Pool Configuration - * Standard connection pooling settings. - */ - pool: external_exports.object({ - min: external_exports.number().default(0).describe("Minimum connections"), - max: external_exports.number().default(10).describe("Maximum connections"), - idleTimeoutMillis: external_exports.number().default(3e4).describe("Idle timeout"), - connectionTimeoutMillis: external_exports.number().default(3e3).describe("Connection establishment timeout") - }).optional().describe("Connection pool settings"), - /** - * Read Replicas - * Optional list of duplicate configurations for read-only operations. - * Useful for scaling read throughput. - */ - readReplicas: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Read-only replica configurations"), - /** - * Capability Overrides - * Manually override what the driver claims to support. - */ - capabilities: DatasourceCapabilities.optional().describe("Capability overrides"), - /** Health Check */ - healthCheck: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable health check endpoint"), - intervalMs: external_exports.number().default(3e4).describe("Health check interval in milliseconds"), - timeoutMs: external_exports.number().default(5e3).describe("Health check timeout in milliseconds") - }).optional().describe("Datasource health check configuration"), - /** SSL/TLS Configuration */ - ssl: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable SSL/TLS for database connection"), - rejectUnauthorized: external_exports.boolean().default(true).describe("Reject connections with invalid/self-signed certificates"), - ca: external_exports.string().optional().describe("CA certificate (PEM format or path to file)"), - cert: external_exports.string().optional().describe("Client certificate (PEM format or path to file)"), - key: external_exports.string().optional().describe("Client private key (PEM format or path to file)") - }).optional().describe("SSL/TLS configuration for secure database connections"), - /** Retry Policy */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().default(3).describe("Maximum number of retry attempts"), - baseDelayMs: external_exports.number().default(1e3).describe("Base delay between retries in milliseconds"), - maxDelayMs: external_exports.number().default(3e4).describe("Maximum delay between retries in milliseconds"), - backoffMultiplier: external_exports.number().default(2).describe("Exponential backoff multiplier") - }).optional().describe("Connection retry policy for transient failures"), - /** Description */ - description: external_exports.string().optional().describe("Internal description"), - /** Is enabled? */ - active: external_exports.boolean().default(true).describe("Is datasource enabled") - }); - AggregationMetricType2 = external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "number", - // Custom SQL expression returning a number - "string", - // Custom SQL expression returning a string - "boolean" - // Custom SQL expression returning a boolean - ]); - DimensionType2 = external_exports.enum([ - "string", - "number", - "boolean", - "time", - "geo" - ]); - TimeUpdateInterval2 = external_exports.enum([ - "second", - "minute", - "hour", - "day", - "week", - "month", - "quarter", - "year" - ]); - MetricSchema2 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique metric ID"), - label: external_exports.string().describe("Human readable label"), - description: external_exports.string().optional(), - type: AggregationMetricType2, - /** Source Calculation */ - sql: external_exports.string().describe("SQL expression or field reference"), - /** Filtering for this specific metric (e.g. "Revenue from Premium Users") */ - filters: external_exports.array(external_exports.object({ - sql: external_exports.string() - })).optional(), - /** Format for display (e.g. "currency", "percent") */ - format: external_exports.string().optional() - }); - DimensionSchema2 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique dimension ID"), - label: external_exports.string().describe("Human readable label"), - description: external_exports.string().optional(), - type: DimensionType2, - /** Source Column */ - sql: external_exports.string().describe("SQL expression or column reference"), - /** For Time Dimensions: Supported Granularities */ - granularities: external_exports.array(TimeUpdateInterval2).optional() - }); - CubeJoinSchema2 = external_exports.object({ - name: external_exports.string().describe("Target cube name"), - relationship: external_exports.enum(["one_to_one", "one_to_many", "many_to_one"]).default("many_to_one"), - sql: external_exports.string().describe("Join condition (ON clause)") - }); - CubeSchema2 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Cube name (snake_case)"), - title: external_exports.string().optional(), - description: external_exports.string().optional(), - /** Physical Data Source */ - sql: external_exports.string().describe("Base SQL statement or Table Name"), - /** Semantic Definitions */ - measures: external_exports.record(external_exports.string(), MetricSchema2).describe("Quantitative metrics"), - dimensions: external_exports.record(external_exports.string(), DimensionSchema2).describe("Qualitative attributes"), - /** Relationships */ - joins: external_exports.record(external_exports.string(), CubeJoinSchema2).optional(), - /** Pre-aggregations / Caching */ - refreshKey: external_exports.object({ - every: external_exports.string().optional(), - // e.g. "1 hour" - sql: external_exports.string().optional() - // SQL to check for data changes - }).optional(), - /** Access Control */ - public: external_exports.boolean().default(false) - }); - AnalyticsQuerySchema2 = external_exports.object({ - cube: external_exports.string().optional().describe("Target cube name (optional when provided externally, e.g. in API request wrapper)"), - measures: external_exports.array(external_exports.string()).describe("List of metrics to calculate"), - dimensions: external_exports.array(external_exports.string()).optional().describe("List of dimensions to group by"), - filters: external_exports.array(external_exports.object({ - member: external_exports.string().describe("Dimension or Measure"), - operator: external_exports.enum(["equals", "notEquals", "contains", "notContains", "gt", "gte", "lt", "lte", "set", "notSet", "inDateRange"]), - values: external_exports.array(external_exports.string()).optional() - })).optional(), - timeDimensions: external_exports.array(external_exports.object({ - dimension: external_exports.string(), - granularity: TimeUpdateInterval2.optional(), - dateRange: external_exports.union([ - external_exports.string(), - // "Last 7 days" - external_exports.array(external_exports.string()) - // ["2023-01-01", "2023-01-31"] - ]).optional() - })).optional(), - order: external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])).optional(), - limit: external_exports.number().optional(), - offset: external_exports.number().optional(), - timezone: external_exports.string().optional().default("UTC") - }); - FeedItemType2 = external_exports.enum([ - "comment", - "field_change", - "task", - "event", - "email", - "call", - "note", - "file", - "record_create", - "record_delete", - "approval", - "sharing", - "system" - ]); - MentionSchema2 = external_exports.object({ - type: external_exports.enum(["user", "team", "record"]).describe("Mention target type"), - id: external_exports.string().describe("Target ID"), - name: external_exports.string().describe("Display name for rendering"), - offset: external_exports.number().int().min(0).describe("Character offset in body text"), - length: external_exports.number().int().min(1).describe("Length of mention token in body text") - }); - FieldChangeEntrySchema2 = external_exports.object({ - field: external_exports.string().describe("Field machine name"), - fieldLabel: external_exports.string().optional().describe("Field display label"), - oldValue: external_exports.unknown().optional().describe("Previous value"), - newValue: external_exports.unknown().optional().describe("New value"), - oldDisplayValue: external_exports.string().optional().describe("Human-readable old value"), - newDisplayValue: external_exports.string().optional().describe("Human-readable new value") - }); - ReactionSchema2 = external_exports.object({ - emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")'), - userIds: external_exports.array(external_exports.string()).describe("Users who reacted"), - count: external_exports.number().int().min(1).describe("Total reaction count") - }); - FeedActorSchema2 = external_exports.object({ - type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), - id: external_exports.string().describe("Actor ID"), - name: external_exports.string().optional().describe("Actor display name"), - avatarUrl: external_exports.string().url().optional().describe("Actor avatar URL"), - source: external_exports.string().optional().describe('Source application (e.g., "Omni", "API", "Studio")') - }); - FeedVisibility2 = external_exports.enum(["public", "internal", "private"]); - FeedItemSchema2 = external_exports.object({ - /** Unique identifier */ - id: external_exports.string().describe("Feed item ID"), - /** Feed item type */ - type: FeedItemType2.describe("Activity type"), - /** Target record reference */ - object: external_exports.string().describe('Object name (e.g., "account")'), - recordId: external_exports.string().describe("Record ID this feed item belongs to"), - /** Actor (who performed the action) */ - actor: FeedActorSchema2.describe("Who performed this action"), - /** Content (for comments/notes) */ - body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), - /** @Mentions */ - mentions: external_exports.array(MentionSchema2).optional().describe("Mentioned users/teams/records"), - /** Field changes (for field_change type) */ - changes: external_exports.array(FieldChangeEntrySchema2).optional().describe("Field-level changes"), - /** Reactions */ - reactions: external_exports.array(ReactionSchema2).optional().describe("Emoji reactions on this item"), - /** Reply threading */ - parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), - replyCount: external_exports.number().int().min(0).default(0).describe("Number of replies"), - /** Pin / Star */ - pinned: external_exports.boolean().default(false).describe("Whether the feed item is pinned to the top of the timeline"), - pinnedAt: external_exports.string().datetime().optional().describe("Timestamp when the item was pinned"), - pinnedBy: external_exports.string().optional().describe("User ID who pinned the item"), - starred: external_exports.boolean().default(false).describe("Whether the feed item is starred/bookmarked by the current user"), - starredAt: external_exports.string().datetime().optional().describe("Timestamp when the item was starred"), - /** Visibility */ - visibility: FeedVisibility2.default("public").describe("Visibility: public (all users), internal (team only), private (author + mentioned)"), - /** Timestamps */ - createdAt: external_exports.string().datetime().describe("Creation timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - editedAt: external_exports.string().datetime().optional().describe("When comment was last edited"), - isEdited: external_exports.boolean().default(false).describe("Whether comment has been edited") - }); - FeedFilterMode = external_exports.enum([ - "all", - "comments_only", - "changes_only", - "tasks_only" - ]); - SubscriptionEventType2 = external_exports.enum([ - "comment", - "mention", - "field_change", - "task", - "approval", - "all" - ]); - NotificationChannel2 = external_exports.enum([ - "in_app", - "email", - "push", - "slack" - ]); - RecordSubscriptionSchema2 = external_exports.object({ - /** Target */ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - /** Subscriber */ - userId: external_exports.string().describe("Subscribing user ID"), - /** Events to subscribe to */ - events: external_exports.array(SubscriptionEventType2).default(["all"]).describe("Event types to receive notifications for"), - /** Notification channels */ - channels: external_exports.array(NotificationChannel2).default(["in_app"]).describe("Notification delivery channels"), - /** Active */ - active: external_exports.boolean().default(true).describe("Whether the subscription is active"), - /** Timestamps */ - createdAt: external_exports.string().datetime().describe("Subscription creation timestamp") - }); - TenantResolverStrategySchema = external_exports.enum([ - "header", - // Resolve from X-Tenant-ID request header - "subdomain", - // Resolve from subdomain (e.g., acme.app.com → acme) - "path", - // Resolve from URL path segment (e.g., /api/acme/...) - "token", - // Resolve from JWT claim (e.g., tenant_id in access token) - "lookup" - // Resolve from control-plane database lookup - ]).describe("Strategy for resolving tenant identity from request context"); - TursoGroupSchema = external_exports.object({ - /** - * Group name identifier. - * Used to reference the group when creating new tenant databases. - */ - name: external_exports.string().min(1).describe("Turso database group name"), - /** - * Primary location for the group (Turso region code). - * Example: 'iad' (US East), 'lhr' (London), 'nrt' (Tokyo) - */ - primaryLocation: external_exports.string().min(2).describe("Primary Turso region code (e.g., iad, lhr, nrt)"), - /** - * Additional replica locations for read performance. - * Databases in this group will have read replicas in these regions. - */ - replicaLocations: external_exports.array(external_exports.string().min(2)).default([]).describe("Additional replica region codes"), - /** - * Schema database name within the group. - * When using multi-db schemas, this is the "parent" database - * whose schema is shared by all child (tenant) databases. - */ - schemaDatabase: external_exports.string().optional().describe("Schema database name for multi-db schemas") - }).describe("Turso database group configuration"); - TenantDatabaseLifecycleSchema = external_exports.object({ - /** - * Hook executed when a new tenant is created. - * Defines how the tenant database is provisioned. - */ - onTenantCreate: external_exports.object({ - /** Whether to automatically create a Turso database */ - autoCreate: external_exports.boolean().default(true).describe("Auto-create database on tenant registration"), - /** Database group to create the database in */ - group: external_exports.string().optional().describe("Turso group for the new database"), - /** Whether to apply schema from the group schema database */ - applyGroupSchema: external_exports.boolean().default(true).describe("Apply shared schema from group"), - /** Seed data to populate on creation */ - seedData: external_exports.boolean().default(false).describe("Populate seed data on creation") - }).describe("Tenant creation hook"), - /** - * Hook executed when a tenant is deleted/destroyed. - */ - onTenantDelete: external_exports.object({ - /** Whether to destroy the database immediately or schedule for deletion */ - immediate: external_exports.boolean().default(false).describe("Destroy database immediately"), - /** Grace period in hours before permanent deletion (soft-delete) */ - gracePeriodHours: external_exports.number().int().min(0).default(72).describe("Grace period before permanent deletion"), - /** Whether to create a final backup before deletion */ - createBackup: external_exports.boolean().default(true).describe("Create backup before deletion") - }).describe("Tenant deletion hook"), - /** - * Hook executed when a tenant is suspended (e.g., unpaid, policy violation). - */ - onTenantSuspend: external_exports.object({ - /** Whether to revoke auth tokens on suspension */ - revokeTokens: external_exports.boolean().default(true).describe("Revoke auth tokens on suspension"), - /** Whether to set database to read-only mode */ - readOnly: external_exports.boolean().default(true).describe("Set database to read-only on suspension") - }).describe("Tenant suspension hook") - }).describe("Tenant database lifecycle hooks"); - TursoMultiTenantConfigSchema = external_exports.object({ - /** - * Turso organization slug. - * Used for Platform API calls and URL construction. - */ - organizationSlug: external_exports.string().min(1).describe("Turso organization slug"), - /** - * URL template for constructing tenant database URLs. - * Use `{tenant_id}` as placeholder for the tenant identifier. - * - * Example: 'libsql://{tenant_id}-myorg.turso.io' - */ - urlTemplate: external_exports.string().min(1).describe("URL template with {tenant_id} placeholder"), - /** - * Group-level auth token for Turso Platform API operations. - * Used for database creation, deletion, and management. - * This token has full access to all databases in the group. - */ - groupAuthToken: external_exports.string().min(1).describe("Group-level auth token for platform operations"), - /** - * Strategy for resolving tenant identity from the request context. - */ - tenantResolverStrategy: TenantResolverStrategySchema.default("token"), - /** - * Turso database group configuration. - */ - group: TursoGroupSchema.optional().describe("Database group configuration"), - /** - * Lifecycle hooks for tenant database management. - */ - lifecycle: TenantDatabaseLifecycleSchema.optional().describe("Lifecycle hooks"), - /** - * Maximum number of cached tenant database connections. - * Connections are evicted using LRU strategy when the limit is reached. - */ - maxCachedConnections: external_exports.number().int().min(1).default(100).describe("Max cached tenant connections (LRU)"), - /** - * Connection cache TTL in seconds. - * Cached connections are refreshed after this period. - */ - connectionCacheTTL: external_exports.number().int().min(0).default(300).describe("Connection cache TTL in seconds") - }).describe("Turso multi-tenant router configuration"); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_hash.js -var require_hash = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_hash.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var hash_exports = {}; - __export5(hash_exports, { - hashCode: () => hashCode2 - }); - module.exports = __toCommonJS(hash_exports); - var MULTIPLIER = 16777619; - function mix(h, x) { - return h * MULTIPLIER ^ x >>> 0; - } - function hashNumber(n) { - if (Number.isNaN(n)) return 2143289344; - if (!Number.isFinite(n)) return n > 0 ? 2139095040 : 4286578688; - const intPart = Math.trunc(n); - const frac = n - intPart; - let h = intPart | 0; - if (frac !== 0) { - const scaled = Math.floor(frac * 4294967296); - h = mix(h, scaled | 0); - } - return h >>> 0; - } - function hashString(str) { - let h = 0; - for (let i = 0; i < str.length; i++) { - h = mix(h, str.charCodeAt(i)); - } - return h >>> 0; - } - function hashBigInt(b) { - let h = 0; - const isNegative = b < 0n; - let x = isNegative ? -b : b; - if (x === 0n) { - h = mix(h, 0); - } else { - while (x > 0n) { - const byte = Number(x & 0xffn); - h = mix(h, byte); - x >>= 8n; - } - } - return mix(h, +isNegative) >>> 0; - } - function hashFunction(fn) { - let h = hashString((fn.name || "") + fn.toString()); - h = mix(h, fn.length); - return h >>> 0; - } - function hashBytes(bytes) { - let h = 0; - for (let i = 0; i < bytes.length; i++) { - h = mix(h, bytes[i]); - } - return h >>> 0; - } - function hashTypedArray(view) { - let h = hashString(view.constructor.name); - const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength); - h = mix(h, hashBytes(bytes)); - return h >>> 0; - } - function hashArray(arr, seen) { - if (seen.has(arr)) return 13; - seen.add(arr); - let h = 1; - for (let i = 0; i < arr.length; i++) { - h = mix(h, internalHash(arr[i], seen)); - } - seen.delete(arr); - return h >>> 0; - } - function hashObject(obj, seen) { - if (seen.has(obj)) return 13; - seen.add(obj); - const keys = Object.keys(obj).sort(); - let h = hashString(obj?.constructor?.name); - for (const k of keys) { - h = mix(h, hashString(k)); - h = mix(h, internalHash(obj[k], seen)); - } - seen.delete(obj); - return h >>> 0; - } - var BOOLEAN_HASH = [3735928559, 305441741].map((b) => mix(3, b)); - var NULL_HASH = mix(1, 0); - var UNDEF_HASH = mix(2, 0); - function internalHash(value, seen) { - if (value === null) return NULL_HASH; - const t = typeof value; - switch (t) { - case "undefined": - return UNDEF_HASH; - case "boolean": - return BOOLEAN_HASH[+value]; - case "number": - return mix(4, hashNumber(value)); - case "string": - return mix(5, hashString(value)); - case "bigint": - return mix(6, hashBigInt(value)); - case "function": - return mix(7, hashFunction(value)); - default: { - if (ArrayBuffer.isView(value) && !(value instanceof DataView)) - return mix(12, hashTypedArray(value)); - if (value instanceof Date) - return mix(10, hashNumber(value.getTime())); - if (value instanceof RegExp) { - const h = hashString(value.source); - return mix(11, mix(h, hashString(value.flags))); - } - if (Array.isArray(value)) return mix(8, hashArray(value, seen)); - return mix( - 9, - hashObject(value, seen) - ); - } - } - } - function hashCode2(value) { - return internalHash(value, /* @__PURE__ */ new WeakSet()) >>> 0; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_internal.js -var require_internal = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - HashMap: () => HashMap2, - MISSING: () => MISSING, - MingoError: () => MingoError2, - PathValidator: () => PathValidator, - assert: () => assert3, - cloneDeep: () => cloneDeep2, - compare: () => compare2, - ensureArray: () => ensureArray2, - filterMissing: () => filterMissing, - findInsertIndex: () => findInsertIndex2, - flatten: () => flatten2, - groupBy: () => groupBy2, - has: () => has2, - hashCode: () => import_hash22.hashCode, - intersection: () => intersection3, - isArray: () => isArray2, - isBoolean: () => isBoolean3, - isDate: () => isDate3, - isEmpty: () => isEmpty2, - isEqual: () => isEqual2, - isFunction: () => isFunction4, - isInteger: () => isInteger2, - isNil: () => isNil2, - isNumber: () => isNumber3, - isObject: () => isObject5, - isObjectLike: () => isObjectLike3, - isOperator: () => isOperator2, - isPrimitive: () => isPrimitive, - isRegExp: () => isRegExp2, - isString: () => isString3, - isSymbol: () => isSymbol2, - normalize: () => normalize2, - removeValue: () => removeValue2, - resolve: () => resolve2, - resolveGraph: () => resolveGraph, - setValue: () => setValue2, - simpleCmp: () => simpleCmp, - truthy: () => truthy, - typeOf: () => typeOf2, - unique: () => unique2, - walk: () => walk - }); - module.exports = __toCommonJS(internal_exports); - var import_hash6 = require_hash(); - var import_hash22 = require_hash(); - var MingoError2 = class extends Error { - }; - var MISSING = /* @__PURE__ */ Symbol("missing"); - var ERR_CYCLE_FOUND = "mingo: cycle detected while processing object/array"; - var isPrimitive = (v) => typeof v !== "object" && typeof v !== "function" || v === null; - var isScalar = (v) => isPrimitive(v) || isDate3(v) || isRegExp2(v); - var SORT_ORDER = { - undefined: 1, - null: 2, - number: 3, - string: 4, - symbol: 5, - object: 6, - array: 7, - arraybuffer: 8, - boolean: 9, - date: 10, - regexp: 11, - function: 12 - }; - var simpleCmp = (a, b) => a < b ? -1 : a > b ? 1 : 0; - var typedArraysCmp = (a, b) => { - const bytesA = new Uint8Array(a.buffer, a.byteOffset, a.byteLength); - const bytesB = new Uint8Array(b.buffer, b.byteOffset, b.byteLength); - const size = Math.min(bytesA.length, bytesB.length); - for (let i = 0; i < size; i++) { - const order = simpleCmp(bytesA[i], bytesB[i]); - if (order !== 0) return order; - } - return simpleCmp(bytesA.length, bytesB.length); - }; - function mingoCmp(a, b, descendArray = false) { - if (a === MISSING) a = void 0; - if (b === MISSING) b = void 0; - if (a === b || Object.is(a, b)) return 0; - const typeA = typeOf2(a); - const typeB = typeOf2(b); - let neq = 0; - if (typeA === typeB) { - switch (typeA) { - case "number": - case "string": - case "boolean": - return simpleCmp(a, b); - case "date": - return simpleCmp(+a, +b); - case "regexp": - if (neq = simpleCmp(a.source, b.source)) - return neq; - return simpleCmp(a.flags, b.flags); - case "arraybuffer": - return typedArraysCmp(a, b); - case "array": { - const xs = a.slice().sort(mingoCmp); - const ys = b.slice().sort(mingoCmp); - const size = Math.min(xs.length, ys.length); - for (let i = 0; i < size; i++) - if (neq = mingoCmp(xs[i], ys[i])) return neq; - return simpleCmp(xs.length, ys.length); - } - default: { - if (typeA !== "object") { - const isSameType = a?.constructor === b?.constructor; - if (isSameType && hasCustomString(a)) - return simpleCmp(a.toString(), b.toString()); - if (neq = simpleCmp(a?.constructor?.name, b?.constructor?.name)) - return neq; - } - const keysA = Object.keys(a).sort(); - const keysB = Object.keys(b).sort(); - if (neq = mingoCmp(keysA, keysB)) return neq; - for (const k of keysA) - if (neq = mingoCmp(a[k], b[k])) - return neq; - return 0; - } - } - } - if (typeA == "undefined") return -1; - if (typeB == "undefined") return 1; - if (descendArray) { - if (typeA == "array") { - const xs = a; - if (!xs.length) return -1; - const sorted = xs.slice().sort(mingoCmp); - neq = 1; - for (const v of sorted) - if ((neq = Math.min(neq, mingoCmp(v, b))) < 0) return neq; - return neq; - } - if (typeB == "array") { - const ys = b; - if (!ys.length) return 1; - const sorted = ys.slice().sort(mingoCmp); - neq = -1; - for (const v of sorted) - if ((neq = Math.max(neq, mingoCmp(a, v))) > 0) return neq; - return neq; - } - } - const orderA = SORT_ORDER[typeA] ?? Number.MAX_VALUE; - const orderB = SORT_ORDER[typeB] ?? Number.MAX_VALUE; - return orderA !== orderB ? simpleCmp(orderA, orderB) : simpleCmp(typeA, typeB); - } - var compare2 = (a, b) => mingoCmp(a, b, true); - var hasCustomString = (o) => o !== null && o !== void 0 && o["toString"] !== Object.prototype.toString; - function isEqual2(a, b) { - if (a === b || Object.is(a, b)) return true; - if (a === null || b === null) return false; - if (typeof a !== typeof b) return false; - if (typeof a !== "object") return false; - if (a.constructor !== b?.constructor) return false; - if (isDate3(a)) return isDate3(b) && +a === +b; - if (isRegExp2(a)) - return isRegExp2(b) && a.source === b.source && a.flags === b.flags; - if (isArray2(a) && isArray2(b)) { - return a.length === b.length && a.every((v, i) => isEqual2(v, b[i])); - } - if (a?.constructor !== Object && hasCustomString(a)) { - return a?.toString() === b?.toString(); - } - const objA = a; - const objB = b; - const keysA = Object.keys(objA); - const keysB = Object.keys(objB); - if (keysA.length !== keysB.length) return false; - return keysA.every((k) => has2(objB, k) && isEqual2(objA[k], objB[k])); - } - var _keyMap, _unpack; - var _HashMap = class _HashMap extends Map { - constructor() { - super(); - // maps the hashcode to key set - __privateAdd(this, _keyMap, /* @__PURE__ */ new Map()); - // returns a tuple of [, ]. Expects an object key. - __privateAdd(this, _unpack, (key) => { - const hash2 = (0, import_hash6.hashCode)(key); - const items = __privateGet(this, _keyMap).get(hash2) ?? []; - return [items.find((k) => isEqual2(k, key)), hash2]; - }); - } - /** - * Returns a new {@link HashMap} object. - * @param fn An optional custom hash function - */ - static init() { - return new _HashMap(); - } - clear() { - super.clear(); - __privateGet(this, _keyMap).clear(); - } - /** - * @returns true if an element in the Map existed and has been removed, or false if the element does not exist. - */ - delete(key) { - if (isPrimitive(key)) return super.delete(key); - const [masterKey, hash2] = __privateGet(this, _unpack).call(this, key); - if (!super.delete(masterKey)) return false; - __privateGet(this, _keyMap).set( - hash2, - __privateGet(this, _keyMap).get(hash2).filter((k) => !isEqual2(k, masterKey)) - ); - return true; - } - /** - * Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map. - * @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. - */ - get(key) { - if (isPrimitive(key)) return super.get(key); - const [masterKey, _] = __privateGet(this, _unpack).call(this, key); - return super.get(masterKey); - } - /** - * @returns boolean indicating whether an element with the specified key exists or not. - */ - has(key) { - if (isPrimitive(key)) return super.has(key); - const [masterKey, _] = __privateGet(this, _unpack).call(this, key); - return super.has(masterKey); - } - /** - * Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated. - */ - set(key, value) { - if (isPrimitive(key)) return super.set(key, value); - const [masterKey, hash2] = __privateGet(this, _unpack).call(this, key); - if (super.has(masterKey)) { - super.set(masterKey, value); - } else { - super.set(key, value); - const keys = __privateGet(this, _keyMap).get(hash2) || []; - keys.push(key); - __privateGet(this, _keyMap).set(hash2, keys); - } - return this; - } - /** - * @returns the number of elements in the Map. - */ - get size() { - return super.size; - } - }; - _keyMap = new WeakMap(); - _unpack = new WeakMap(); - var HashMap2 = _HashMap; - function assert3(condition, msg) { - if (!condition) throw new MingoError2(msg); - } - function typeOf2(v) { - const t = typeof v; - switch (t) { - case "number": - case "string": - case "boolean": - case "undefined": - case "function": - case "symbol": - return t; - } - if (v === null) return "null"; - if (isArray2(v)) return "array"; - if (isDate3(v)) return "date"; - if (isRegExp2(v)) return "regexp"; - if (isTypedArray(v)) return "arraybuffer"; - if (v?.constructor === Object) return "object"; - return v?.constructor?.name?.toLowerCase() ?? "object"; - } - var isBoolean3 = (v) => typeof v === "boolean"; - var isString3 = (v) => typeof v === "string"; - var isSymbol2 = (v) => typeof v === "symbol"; - var isNumber3 = (v) => !Number.isNaN(v) && typeof v === "number"; - var isInteger2 = Number.isInteger; - var isArray2 = Array.isArray; - var isObject5 = (v) => typeOf2(v) === "object"; - var isObjectLike3 = (v) => !isPrimitive(v); - var isDate3 = (v) => v instanceof Date; - var isRegExp2 = (v) => v instanceof RegExp; - var isFunction4 = (v) => typeof v === "function"; - var isNil2 = (v) => v === null || v === void 0; - var truthy = (arg, strict = true) => !!arg || strict && arg === ""; - var isEmpty2 = (x) => isNil2(x) || isString3(x) && !x || isArray2(x) && x.length === 0 || isObject5(x) && Object.keys(x).length === 0; - var ensureArray2 = (x) => isArray2(x) ? x : [x]; - var has2 = (obj, ...props) => !!obj && props.every((p) => Object.prototype.hasOwnProperty.call(obj, p)); - var isTypedArray = (v) => typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(v); - var cloneDeep2 = (v, refs) => { - if (isNil2(v) || isBoolean3(v) || isNumber3(v) || isString3(v)) return v; - if (isDate3(v)) return new Date(v); - if (isRegExp2(v)) return new RegExp(v); - if (isTypedArray(v)) { - const ctor = v.constructor; - return new ctor(v); - } - if (!(refs instanceof WeakSet)) refs = /* @__PURE__ */ new WeakSet(); - if (refs.has(v)) throw new Error(ERR_CYCLE_FOUND); - refs.add(v); - try { - if (isArray2(v)) { - const arr = new Array(v.length); - for (let i = 0; i < v.length; i++) arr[i] = cloneDeep2(v[i], refs); - return arr; - } - if (isObject5(v)) { - const obj = {}; - for (const k of Object.keys(v)) obj[k] = cloneDeep2(v[k], refs); - return obj; - } - } finally { - refs.delete(v); - } - return v; - }; - function intersection3(input) { - if (input.length === 0) return []; - if (input.length === 1) return input[0].slice(); - for (const arr of input) if (arr.length === 0) return []; - const maps = [HashMap2.init(), HashMap2.init()]; - let index = 0; - for (const v of input[input.length - 1]) maps[0].set(v, true); - for (let i = input.length - 2; i >= 0; i--) { - for (let j = 0; j < input[i].length; j++) { - const v = input[i][j]; - if (maps[index].has(v)) maps[index ^ 1].set(v, true); - } - if (maps[index ^ 1].size === 0) return []; - maps[index].clear(); - index = index ^ 1; - } - return Array.from(maps[index].keys()); - } - function flatten2(xs, depth = 1) { - const arr = new Array(); - function flatten22(ys, n) { - for (let i = 0, len = ys.length; i < len; i++) { - if (isArray2(ys[i]) && (n > 0 || n < 0)) { - flatten22(ys[i], Math.max(-1, n - 1)); - } else { - arr.push(ys[i]); - } - } - } - flatten22(xs, depth); - return arr; - } - function unique2(input) { - const m = HashMap2.init(); - for (const v of input) m.set(v, true); - return Array.from(m.keys()); - } - function groupBy2(collection, keyFunc) { - if (collection.length < 1) return /* @__PURE__ */ new Map(); - const result = HashMap2.init(); - for (let i = 0; i < collection.length; i++) { - const obj = collection[i]; - const key = keyFunc(obj, i) ?? null; - let a = result.get(key); - if (!a) { - a = [obj]; - result.set(key, a); - } else { - a.push(obj); - } - } - return result; - } - function getValue(obj, key) { - return isObjectLike3(obj) ? obj[key] : void 0; - } - function unwrap4(arr, depth) { - if (depth < 1) return arr; - while (depth-- && arr.length === 1 && isArray2(arr[0])) arr = arr[0]; - return arr; - } - function resolve2(obj, selector, options) { - if (isScalar(obj)) return obj; - const path3 = options?.pathArray ?? selector.split("."); - if (path3.length === 1 && !isArray2(obj)) { - return getValue(obj, path3[0]); - } - if (path3.length === 2 && !isArray2(obj)) { - const first = getValue(obj, path3[0]); - if (first == null) return void 0; - if (!isArray2(first)) return getValue(first, path3[1]); - } - let depth = 0; - function resolve22(o, path22) { - let value = o; - for (let i = 0; i < path22.length; i++) { - const field = path22[i]; - const isText = !DIGITS_RE.test(field); - if (isText && isArray2(value)) { - if (i === 0 && depth > 0) break; - depth += 1; - const subpath = path22.slice(i); - value = value.reduce((acc, item) => { - const v = resolve22(item, subpath); - if (v !== void 0) acc.push(v); - return acc; - }, []); - break; - } else { - value = getValue(value, field); - } - if (value === void 0) break; - } - return value; - } - const res = resolve22(obj, path3); - return isArray2(res) && options?.unwrapArray ? unwrap4(res, depth) : res; - } - function resolveGraph(obj, selector, options) { - const sep = selector.indexOf("."); - const key = sep == -1 ? selector : selector.substring(0, sep); - const next = selector.substring(sep + 1); - const hasNext = sep != -1; - if (isArray2(obj)) { - const isIndex = /^\d+$/.test(key); - const arr = isIndex && options?.preserveIndex ? obj.slice() : []; - if (isIndex) { - const index = parseInt(key); - let value2 = getValue(obj, index); - if (hasNext) { - value2 = resolveGraph(value2, next, options); - } - if (options?.preserveIndex) { - arr[index] = value2; - } else { - arr.push(value2); - } - } else { - for (const item of obj) { - const value2 = resolveGraph(item, selector, options); - if (options?.preserveMissing) { - arr.push(value2 == void 0 ? MISSING : value2); - } else if (value2 != void 0 || options?.preserveIndex) { - arr.push(value2); - } - } - } - return arr; - } - const res = options?.preserveKeys ? { ...obj } : {}; - let value = getValue(obj, key); - if (hasNext) { - value = resolveGraph(value, next, options); - } - if (value === void 0) return void 0; - res[key] = value; - return res; - } - function filterMissing(obj) { - if (isArray2(obj)) { - for (let i = obj.length - 1; i >= 0; i--) { - if (obj[i] === MISSING) { - obj.splice(i, 1); - } else { - filterMissing(obj[i]); - } - } - } else if (isObject5(obj)) { - for (const k of Object.keys(obj)) { - if (has2(obj, k)) { - filterMissing(obj[k]); - } - } - } - } - var DIGITS_RE = /^\d+$/; - function walk(obj, selector, fn, options) { - const names = selector.split("."); - const key = names[0]; - const next = names.slice(1).join("."); - if (names.length === 1) { - if (isObject5(obj) || isArray2(obj) && DIGITS_RE.test(key)) { - fn(obj, key); - } - } else { - if (options?.buildGraph && isNil2(obj[key])) { - obj[key] = {}; - } - const item = obj[key]; - if (!item) return; - const isNextArrayIndex = !!(names.length > 1 && DIGITS_RE.test(names[1])); - if (isArray2(item) && options?.descendArray && !isNextArrayIndex) { - item.forEach((e) => walk(e, next, fn, options)); - } else { - walk(item, next, fn, options); - } - } - } - function setValue2(obj, selector, value) { - walk(obj, selector, (item, key) => item[key] = value, { - buildGraph: true - }); - } - function removeValue2(obj, selector, options) { - walk( - obj, - selector, - (item, key) => { - if (isArray2(item)) { - item.splice(parseInt(key), 1); - } else if (isObject5(item)) { - delete item[key]; - } - }, - options - ); - } - var isOperator2 = (name) => !!name && name[0] === "$" && /^\$[a-zA-Z0-9_]+$/.test(name); - function normalize2(expr) { - if (isScalar(expr)) { - return isRegExp2(expr) ? { $regex: expr } : { $eq: expr }; - } - if (isObjectLike3(expr)) { - if (!Object.keys(expr).some(isOperator2)) return { $eq: expr }; - if (isObject5(expr) && has2(expr, "$regex")) { - const newExpr = { ...expr }; - newExpr["$regex"] = new RegExp( - expr["$regex"], - expr["$options"] - ); - delete newExpr["$options"]; - return newExpr; - } - } - return expr; - } - function findInsertIndex2(sorted, item, comparator = compare2) { - let lo = 0; - let hi = sorted.length - 1; - while (lo <= hi) { - const mid = Math.round(lo + (hi - lo) / 2); - if (comparator(item, sorted[mid]) < 0) { - hi = mid - 1; - } else if (comparator(item, sorted[mid]) > 0) { - lo = mid + 1; - } else { - return mid; - } - } - return lo; - } - var PathValidator = class { - constructor() { - this.root = { - children: /* @__PURE__ */ new Map(), - isTerminal: false - }; - } - add(selector) { - const parts = selector.split("."); - let current = this.root; - for (const part of parts) { - if (current.isTerminal) return false; - if (!current.children.has(part)) { - current.children.set(part, { - children: /* @__PURE__ */ new Map(), - isTerminal: false - }); - } - current = current.children.get(part); - } - if (current.isTerminal || current.children.size) return false; - return current.isTerminal = true; - } - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/index.js -var require_util = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var util_exports2 = {}; - __export5(util_exports2, { - HashMap: () => import_internal.HashMap, - MingoError: () => import_internal.MingoError, - assert: () => import_internal.assert, - cloneDeep: () => import_internal.cloneDeep, - compare: () => import_internal.compare, - ensureArray: () => import_internal.ensureArray, - findInsertIndex: () => import_internal.findInsertIndex, - flatten: () => import_internal.flatten, - groupBy: () => import_internal.groupBy, - has: () => import_internal.has, - hashCode: () => import_internal.hashCode, - intersection: () => import_internal.intersection, - isArray: () => import_internal.isArray, - isBoolean: () => import_internal.isBoolean, - isDate: () => import_internal.isDate, - isEmpty: () => import_internal.isEmpty, - isEqual: () => import_internal.isEqual, - isFunction: () => import_internal.isFunction, - isInteger: () => import_internal.isInteger, - isNil: () => import_internal.isNil, - isNumber: () => import_internal.isNumber, - isObject: () => import_internal.isObject, - isObjectLike: () => import_internal.isObjectLike, - isOperator: () => import_internal.isOperator, - isRegExp: () => import_internal.isRegExp, - isString: () => import_internal.isString, - isSymbol: () => import_internal.isSymbol, - normalize: () => import_internal.normalize, - removeValue: () => import_internal.removeValue, - resolve: () => import_internal.resolve, - setValue: () => import_internal.setValue, - typeOf: () => import_internal.typeOf, - unique: () => import_internal.unique - }); - module.exports = __toCommonJS(util_exports2); - var import_internal = require_internal(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/_internal.js -var require_internal2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - ComputeOptions: () => ComputeOptions, - Context: () => Context3, - OpType: () => OpType2, - ProcessingMode: () => ProcessingMode2, - computeValue: () => computeValue2, - evalExpr: () => evalExpr2 - }); - module.exports = __toCommonJS(internal_exports); - var import_util3 = require_util(); - var ProcessingMode2 = /* @__PURE__ */ ((ProcessingMode22) => { - ProcessingMode22[ProcessingMode22["CLONE_OFF"] = 0] = "CLONE_OFF"; - ProcessingMode22[ProcessingMode22["CLONE_INPUT"] = 1] = "CLONE_INPUT"; - ProcessingMode22[ProcessingMode22["CLONE_OUTPUT"] = 2] = "CLONE_OUTPUT"; - ProcessingMode22[ProcessingMode22["CLONE_ALL"] = 3] = "CLONE_ALL"; - return ProcessingMode22; - })(ProcessingMode2 || {}); - var _locals; - var _ComputeOptions = class _ComputeOptions { - constructor(options, locals) { - __privateAdd(this, _locals); - this.options = options; - __privateSet(this, _locals, locals ? { ...locals } : {}); - } - /** - * Initializes a new instance of the `ComputeOptions` class with the provided options. - * - * @param options - A partial set of options to configure the `ComputeOptions` instance. - * If an instance of `ComputeOptions` is provided, its internal options and locals are used. - * @returns A new `ComputeOptions` instance configured with the provided options and root. - */ - static init(options) { - return options instanceof _ComputeOptions ? new _ComputeOptions(options.options, __privateGet(options, _locals)) : new _ComputeOptions({ - idKey: "_id", - scriptEnabled: true, - useStrictMode: true, - failOnError: true, - processingMode: 0, - ...options, - context: options?.context ? Context3.from(options?.context) : Context3.init() - }); - } - update(locals) { - Object.assign(__privateGet(this, _locals), locals, { - // DO NOT override timestamp - timestamp: __privateGet(this, _locals).timestamp, - // merge variables. - variables: { ...__privateGet(this, _locals)?.variables, ...locals?.variables } - }); - return this; - } - get local() { - return __privateGet(this, _locals); - } - get now() { - let timestamp = __privateGet(this, _locals).timestamp ?? 0; - if (!timestamp) { - timestamp = Date.now(); - Object.assign(__privateGet(this, _locals), { timestamp }); - } - return new Date(timestamp); - } - get idKey() { - return this.options.idKey; - } - get collation() { - return this.options?.collation; - } - get processingMode() { - return this.options?.processingMode; - } - get useStrictMode() { - return this.options?.useStrictMode; - } - get scriptEnabled() { - return this.options?.scriptEnabled; - } - get failOnError() { - return this.options?.failOnError; - } - get collectionResolver() { - return this.options?.collectionResolver; - } - get jsonSchemaValidator() { - return this.options?.jsonSchemaValidator; - } - get variables() { - return this.options?.variables; - } - get context() { - return this.options?.context; - } - }; - _locals = new WeakMap(); - var ComputeOptions = _ComputeOptions; - var OpType2 = /* @__PURE__ */ ((OpType22) => { - OpType22["ACCUMULATOR"] = "accumulator"; - OpType22["EXPRESSION"] = "expression"; - OpType22["PIPELINE"] = "pipeline"; - OpType22["PROJECTION"] = "projection"; - OpType22["QUERY"] = "query"; - OpType22["WINDOW"] = "window"; - return OpType22; - })(OpType2 || {}); - var _operators; - var _Context = class _Context { - constructor() { - __privateAdd(this, _operators); - __privateSet(this, _operators, { - [ - "accumulator" - /* ACCUMULATOR */ - ]: {}, - [ - "expression" - /* EXPRESSION */ - ]: {}, - [ - "pipeline" - /* PIPELINE */ - ]: {}, - [ - "projection" - /* PROJECTION */ - ]: {}, - [ - "query" - /* QUERY */ - ]: {}, - [ - "window" - /* WINDOW */ - ]: {} - }); - } - static init(ops = {}) { - const ctx = new _Context(); - for (const type of Object.keys(ops)) { - __privateGet(ctx, _operators)[type] = { ...ops[type] }; - } - return ctx; - } - /** Returns a new context with the operators from the provided contexts merged left to right. */ - static from(...ctx) { - if (ctx.length === 1) return _Context.init(__privateGet(ctx[0], _operators)); - const newCtx = new _Context(); - for (const context of ctx) { - for (const type of Object.values(OpType2)) { - newCtx.addOps(type, __privateGet(context, _operators)[type]); - } - } - return newCtx; - } - addOps(type, operators) { - __privateGet(this, _operators)[type] = Object.assign({}, operators, __privateGet(this, _operators)[type]); - return this; - } - getOperator(type, name) { - return __privateGet(this, _operators)[type][name] ?? null; - } - addAccumulatorOps(ops) { - return this.addOps("accumulator", ops); - } - addExpressionOps(ops) { - return this.addOps("expression", ops); - } - addQueryOps(ops) { - return this.addOps("query", ops); - } - addPipelineOps(ops) { - return this.addOps("pipeline", ops); - } - addProjectionOps(ops) { - return this.addOps("projection", ops); - } - addWindowOps(ops) { - return this.addOps("window", ops); - } - }; - _operators = new WeakMap(); - var Context3 = _Context; - function computeValue2(obj, expr, operator, options) { - return evalExpr2(obj, { [operator]: expr }, options); - } - function evalExpr2(obj, expr, options) { - const copts = !(options instanceof ComputeOptions) || (0, import_util3.isNil)(options.local.root) ? ComputeOptions.init(options).update({ root: obj }) : options; - return computeExpression(obj, expr, copts); - } - var SYSTEM_VARS = /* @__PURE__ */ new Set(["$$ROOT", "$$CURRENT", "$$REMOVE", "$$NOW"]); - function computeExpression(obj, expr, options) { - if ((0, import_util3.isString)(expr) && expr.length > 0 && expr[0] === "$") { - if (expr === "$$KEEP" || expr === "$$PRUNE" || expr === "$$DESCEND") - return expr; - let ctx = options.local.root; - const arr = expr.split("."); - const dotIdx = expr.indexOf("."); - const prefix = dotIdx === -1 ? expr : expr.substring(0, dotIdx); - if (SYSTEM_VARS.has(arr[0])) { - switch (prefix) { - case "$$ROOT": - break; - case "$$CURRENT": - ctx = obj; - break; - case "$$REMOVE": - ctx = void 0; - break; - case "$$NOW": - ctx = new Date(options.now); - break; - } - expr = dotIdx === -1 ? "" : expr.substring(dotIdx + 1); - } else if (prefix.length >= 2 && prefix[1] === "$") { - ctx = Object.assign( - {}, - // global vars - options.variables, - // current item is added before local variables because the binding may be changed. - { this: obj }, - // local vars - options?.local?.variables - ); - const name = prefix.substring(2); - (0, import_util3.assert)((0, import_util3.has)(ctx, name), `Use of undefined variable: ${name}`); - expr = expr.substring(2); - } else { - expr = expr.substring(1); - } - return expr === "" ? ctx : (0, import_util3.resolve)(ctx, expr); - } - if ((0, import_util3.isArray)(expr)) { - return expr.map((item) => computeExpression(obj, item, options)); - } - if ((0, import_util3.isObject)(expr)) { - const keys = Object.keys(expr); - if ((0, import_util3.isOperator)(keys[0])) { - (0, import_util3.assert)(keys.length === 1, "Expression must contain a single operator."); - return computeOperator(obj, expr[keys[0]], keys[0], options); - } - const result = {}; - for (let i = 0; i < keys.length; i++) { - result[keys[i]] = computeExpression(obj, expr[keys[i]], options); - } - return result; - } - return expr; - } - function computeOperator(obj, expr, operator, options) { - const context = options.context; - const fn = context.getOperator("expression", operator); - if (fn) return fn(obj, expr, options); - const accFn = context.getOperator("accumulator", operator); - (0, import_util3.assert)(!!accFn, `accumulator '${operator}' is not registered.`); - if (!(0, import_util3.isArray)(obj)) { - obj = computeExpression(obj, expr, options); - expr = null; - } - (0, import_util3.assert)((0, import_util3.isArray)(obj), `arguments must resolve to array for ${operator}.`); - return accFn(obj, expr, options); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/lazy.js -var require_lazy = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/lazy.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var lazy_exports = {}; - __export5(lazy_exports, { - Iterator: () => Iterator, - Lazy: () => Lazy, - concat: () => concat2 - }); - module.exports = __toCommonJS(lazy_exports); - var import_util3 = require_util(); - function Lazy(source) { - return new Iterator(source); - } - function concat2(...iterators) { - let index = 0; - return Lazy(() => { - while (index < iterators.length) { - const o = iterators[index].next(); - if (!o.done) return o; - index++; - } - return { done: true, value: void 0 }; - }); - } - function isGenerator(o) { - return !!o && typeof o === "object" && typeof o?.next === "function"; - } - function isIterable(o) { - return !!o && (typeof o === "object" || typeof o === "function") && typeof o[Symbol.iterator] === "function"; - } - var _iteratees, _buffer, _getNext, _done; - var Iterator = class { - constructor(source) { - __privateAdd(this, _iteratees, []); - __privateAdd(this, _buffer, []); - __privateAdd(this, _getNext); - __privateAdd(this, _done, false); - let iter; - if (isIterable(source)) - iter = source[Symbol.iterator](); - else if (isGenerator(source)) iter = source; - else if (typeof source === "function") iter = { next: source }; - else - (0, import_util3.assert)(0, "mingo: iterator requires an iterable, generator or function"); - let index = -1; - __privateSet(this, _getNext, () => { - while (true) { - let { value, done } = iter.next(); - if (done) return { done }; - let ok2 = true; - index++; - for (let i = 0; i < __privateGet(this, _iteratees).length; i++) { - const { op, fn } = __privateGet(this, _iteratees)[i]; - const res = fn(value, index); - if (op === "map") { - value = res; - } else if (!res) { - ok2 = false; - break; - } - } - if (ok2) return { value, done }; - } - }); - } - /** - * Add an iteratee to this lazy sequence - */ - push(op, fn) { - __privateGet(this, _iteratees).push({ op, fn }); - return this; - } - next() { - return __privateGet(this, _getNext).call(this); - } - // Iteratees methods - /** - * Transform each item in the sequence to a new value - * @param {Function} f - */ - map(f) { - return this.push("map", f); - } - /** - * Select only items matching the given predicate - * @param {Function} f - */ - filter(f) { - return this.push("filter", f); - } - /** - * Take given numbe for values from sequence - * @param {Number} n A number greater than 0 - */ - take(n) { - (0, import_util3.assert)(n >= 0, "value must be a non-negative integer"); - return this.filter((_) => n-- > 0); - } - /** - * Drop a number of values from the sequence - * @param {Number} n Number of items to drop greater than 0 - */ - drop(n) { - (0, import_util3.assert)(n >= 0, "value must be a non-negative integer"); - return this.filter((_) => n-- <= 0); - } - // Transformations - /** - * Returns a new lazy object with results of the transformation - * The entire sequence is realized. - * - * @param {Callback} f Tranform function of type (Array) => (Any) - */ - transform(f) { - const self = this; - let iter; - return Lazy(() => { - if (!iter) iter = f(self.collect()); - return iter.next(); - }); - } - /** - * Retrieves all remaining values from the lazy evaluation and returns them as an array. - * This method processes the underlying iterator until it is exhausted, storing the results - * in an internal buffer to ensure subsequent calls return the same data. - */ - collect() { - while (!__privateGet(this, _done)) { - const { done, value } = __privateGet(this, _getNext).call(this); - if (!done) __privateGet(this, _buffer).push(value); - __privateSet(this, _done, done); - } - return __privateGet(this, _buffer); - } - /** - * Execute the callback for each value. - * @param f The callback function. - */ - each(f) { - for (let o = this.next(); o.done !== true; o = this.next()) f(o.value); - } - /** - * Returns the reduction of sequence according the reducing function - * - * @param f The reducing function - * @param initialValue The initial value - */ - reduce(f, initialValue) { - let o = this.next(); - if (initialValue === void 0 && !o.done) { - initialValue = o.value; - o = this.next(); - } - while (!o.done) { - initialValue = f(initialValue, o.value); - o = this.next(); - } - return initialValue; - } - /** - * Returns the number of matched items in the sequence. - * The stream is realized and buffered for later retrieval with {@link collect}. - */ - size() { - return this.collect().length; - } - [Symbol.iterator]() { - return this; - } - }; - _iteratees = new WeakMap(); - _buffer = new WeakMap(); - _getNext = new WeakMap(); - _done = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/aggregator.js -var require_aggregator = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/aggregator.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var aggregator_exports = {}; - __export5(aggregator_exports, { - Aggregator: () => Aggregator2 - }); - module.exports = __toCommonJS(aggregator_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - var _pipeline, _options2; - var Aggregator2 = class { - /** - * Creates an instance of the Aggregator class. - * - * @param pipeline - An array of objects representing the aggregation pipeline stages. - * @param options - Optional configuration settings for the aggregator. - */ - constructor(pipeline, options) { - __privateAdd(this, _pipeline); - __privateAdd(this, _options2); - __privateSet(this, _pipeline, pipeline); - __privateSet(this, _options2, import_internal.ComputeOptions.init(options)); - } - /** - * Processes a collection through an aggregation pipeline and returns an iterator - * for the transformed results. - * - * @param collection - The input collection to process. This can be any source - * that implements the `Source` interface. - * @param options - Optional configuration for processing. If not provided, the - * default options of the aggregator instance will be used. - * @returns An iterator that yields the results of the aggregation pipeline. - * - * @throws Will throw an error if: - * - A pipeline stage contains more than one operator. - * - The `$documents` operator is not the first stage in the pipeline. - * - An unregistered pipeline operator is encountered. - */ - stream(collection, options) { - let iter = (0, import_lazy.Lazy)(collection); - const opts = options ?? __privateGet(this, _options2); - const mode = opts.processingMode; - if (mode & import_internal.ProcessingMode.CLONE_INPUT) iter.map((o) => (0, import_util3.cloneDeep)(o)); - iter = __privateGet(this, _pipeline).map((stage, i) => { - const keys = Object.keys(stage); - (0, import_util3.assert)( - keys.length === 1, - `aggregation stage must have single operator, got ${keys.toString()}.` - ); - const name = keys[0]; - (0, import_util3.assert)( - name !== "$documents" || i == 0, - "$documents must be first stage in pipeline." - ); - const op = opts.context.getOperator(import_internal.OpType.PIPELINE, name); - (0, import_util3.assert)(!!op, `unregistered pipeline operator ${name}.`); - return [op, stage[name]]; - }).reduce((acc, [op, expr]) => op(acc, expr, opts), iter); - if (mode & import_internal.ProcessingMode.CLONE_OUTPUT) iter.map((o) => (0, import_util3.cloneDeep)(o)); - return iter; - } - /** - * Executes the aggregation pipeline on the provided collection and returns the resulting array. - * - * @template T - The type of the objects in the resulting array. - * @param collection - The input data source to run the aggregation on. - * @param options - Optional settings to customize the aggregation behavior. - * @returns An array of objects of type `T` resulting from the aggregation. - */ - run(collection, options) { - return this.stream(collection, options).collect(); - } - }; - _pipeline = new WeakMap(); - _options2 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/push.js -var require_push = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/push.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var push_exports = {}; - __export5(push_exports, { - $push: () => $push - }); - module.exports = __toCommonJS(push_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $push = (coll, expr, options) => { - if ((0, import_util3.isNil)(expr)) return coll; - const copts = import_internal.ComputeOptions.init(options); - const result = new Array(coll.length); - for (let i = 0; i < coll.length; i++) { - const root = coll[i]; - result[i] = (0, import_internal.evalExpr)(root, expr, copts.update({ root })) ?? null; - } - return result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/accumulator.js -var require_accumulator = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/accumulator.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var accumulator_exports = {}; - __export5(accumulator_exports, { - $accumulator: () => $accumulator - }); - module.exports = __toCommonJS(accumulator_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_push = require_push(); - var $accumulator = (coll, expr, options) => { - (0, import_util3.assert)( - options.scriptEnabled, - "$accumulator requires 'scriptEnabled' option to be true" - ); - const copts = import_internal.ComputeOptions.init(options); - const input = expr; - const initArgs = (0, import_internal.evalExpr)( - copts?.local?.groupId, - input.initArgs || [], - copts.update({ root: copts?.local?.groupId }) - ); - const args = (0, import_push.$push)(coll, input.accumulateArgs, copts); - for (let i = 0; i < args.length; i++) { - for (let j = 0; j < args[i].length; j++) { - args[i][j] = args[i][j] ?? null; - } - } - const initialValue = input.init.apply(null, initArgs); - const f = input.accumulate; - let result = initialValue; - for (let i = 0; i < args.length; i++) { - result = f.apply(null, [result, ...args[i]]); - } - if (input.finalize) result = input.finalize.call(null, result); - return result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/addToSet.js -var require_addToSet = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/addToSet.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var addToSet_exports = {}; - __export5(addToSet_exports, { - $addToSet: () => $addToSet - }); - module.exports = __toCommonJS(addToSet_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var $addToSet = (coll, expr, options) => (0, import_util3.unique)((0, import_push.$push)(coll, expr, options)); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/avg.js -var require_avg = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/avg.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var avg_exports = {}; - __export5(avg_exports, { - $avg: () => $avg - }); - module.exports = __toCommonJS(avg_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var $avg = (coll, expr, options) => { - const data = (0, import_push.$push)(coll, expr, options).filter(import_util3.isNumber); - if (data.length === 0) return null; - const sum = data.reduce((acc, n) => acc + n, 0); - return sum / data.length; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sort.js -var require_sort = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sort.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sort_exports = {}; - __export5(sort_exports, { - $sort: () => $sort - }); - module.exports = __toCommonJS(sort_exports); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - function $sort(coll, sortKeys, options) { - (0, import_util3.assert)( - (0, import_util3.isObject)(sortKeys) && Object.keys(sortKeys).length > 0, - "$sort specification is invalid" - ); - let cmp = import_util3.compare; - const collationSpec = options.collation; - if ((0, import_util3.isObject)(collationSpec) && (0, import_util3.isString)(collationSpec.locale)) { - cmp = collationComparator(collationSpec); - } - return coll.transform((coll2) => { - const modifiers = Object.keys(sortKeys); - for (const key of modifiers.reverse()) { - const groups = (0, import_util3.groupBy)(coll2, (obj) => (0, import_util3.resolve)(obj, key)); - const sortedKeys = Array.from(groups.keys()); - let nativeSorted = false; - if (cmp === import_util3.compare) { - let t_str = true; - let t_num = true; - for (const v of sortedKeys) { - t_str && (t_str = (0, import_util3.isString)(v)); - t_num && (t_num = (0, import_util3.isNumber)(v)); - if (!t_str && !t_num) break; - } - nativeSorted = t_str || t_num; - if (t_str) sortedKeys.sort(); - else if (t_num) { - const numbers = new Float64Array(sortedKeys).sort(); - for (let i2 = 0; i2 < numbers.length; i2++) { - sortedKeys[i2] = numbers[i2]; - } - } - } - if (!nativeSorted) sortedKeys.sort(cmp); - if (sortKeys[key] === -1) sortedKeys.reverse(); - let i = 0; - for (const k of sortedKeys) for (const v of groups.get(k)) coll2[i++] = v; - (0, import_util3.assert)(i == coll2.length, "bug: counter must match collection size."); - } - return (0, import_lazy.Lazy)(coll2); - }); - } - var COLLATION_STRENGTH = { - // Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A. - 1: "base", - // Only strings that differ in base letters or accents and other diacritic marks compare as unequal. - // Examples: a ≠ b, a ≠ á, a = A. - 2: "accent", - // Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. - // Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A - 3: "variant" - // case - Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A. - }; - function collationComparator(spec) { - const localeOpt = { - sensitivity: COLLATION_STRENGTH[spec.strength || 3], - caseFirst: spec.caseFirst === "off" ? "false" : spec.caseFirst, - numeric: spec.numericOrdering || false, - ignorePunctuation: spec.alternate === "shifted" - }; - if (spec.caseLevel === true) { - if (localeOpt.sensitivity === "base") localeOpt.sensitivity = "case"; - if (localeOpt.sensitivity === "accent") localeOpt.sensitivity = "variant"; - } - const collator = new Intl.Collator(spec.locale, localeOpt); - return (a, b) => (0, import_util3.isString)(a) && (0, import_util3.isString)(b) ? collator.compare(a, b) : (0, import_util3.compare)(a, b); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottomN.js -var require_bottomN = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottomN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bottomN_exports = {}; - __export5(bottomN_exports, { - $bottomN: () => $bottomN - }); - module.exports = __toCommonJS(bottomN_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_sort = require_sort(); - var import_push = require_push(); - var $bottomN = (coll, expr, options) => { - const copts = options; - const args = expr; - const n = (0, import_internal.evalExpr)(copts?.local?.groupId, args.n, copts); - const result = (0, import_sort.$sort)((0, import_lazy.Lazy)(coll), args.sortBy, options).collect(); - const m = result.length; - return (0, import_push.$push)(m <= n ? result : result.slice(m - n), args.output, copts); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottom.js -var require_bottom = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottom.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bottom_exports = {}; - __export5(bottom_exports, { - $bottom: () => $bottom - }); - module.exports = __toCommonJS(bottom_exports); - var import_bottomN = require_bottomN(); - var $bottom = (coll, expr, options) => { - return (0, import_bottomN.$bottomN)(coll, { ...expr, n: 1 }, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/count.js -var require_count = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/count.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var count_exports = {}; - __export5(count_exports, { - $count: () => $count - }); - module.exports = __toCommonJS(count_exports); - var $count = (coll, _expr2, _opts) => coll.length; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/_internal.js -var require_internal3 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - covariance: () => covariance, - stddev: () => stddev - }); - module.exports = __toCommonJS(internal_exports); - function stddev(data, sampled = true) { - const sum = data.reduce((acc, n) => acc + n, 0); - const N = Math.max(data.length, 1); - const avg = sum / N; - return Math.sqrt( - data.reduce((acc, n) => acc + Math.pow(n - avg, 2), 0) / (N - Number(sampled)) - ); - } - function covariance(dataset, sampled = true) { - if (dataset.length < 2) return sampled ? null : 0; - let meanX = 0; - let meanY = 0; - for (const [x, y] of dataset) { - meanX += x; - meanY += y; - } - meanX /= dataset.length; - meanY /= dataset.length; - let result = 0; - for (const [x, y] of dataset) { - result += (x - meanX) * (y - meanY); - } - return result / (dataset.length - Number(sampled)); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covariancePop.js -var require_covariancePop = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covariancePop.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var covariancePop_exports = {}; - __export5(covariancePop_exports, { - $covariancePop: () => $covariancePop - }); - module.exports = __toCommonJS(covariancePop_exports); - var import_internal = require_internal3(); - var import_push = require_push(); - var $covariancePop = (coll, expr, options) => (0, import_internal.covariance)((0, import_push.$push)(coll, expr, options), false); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covarianceSamp.js -var require_covarianceSamp = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covarianceSamp.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var covarianceSamp_exports = {}; - __export5(covarianceSamp_exports, { - $covarianceSamp: () => $covarianceSamp - }); - module.exports = __toCommonJS(covarianceSamp_exports); - var import_internal = require_internal3(); - var import_push = require_push(); - var $covarianceSamp = (coll, expr, options) => (0, import_internal.covariance)((0, import_push.$push)(coll, expr, options), true); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/first.js -var require_first = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/first.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var first_exports = {}; - __export5(first_exports, { - $first: () => $first - }); - module.exports = __toCommonJS(first_exports); - var import_internal = require_internal2(); - var $first = (coll, expr, options) => { - const obj = coll[0]; - const copts = import_internal.ComputeOptions.init(options).update({ root: obj }); - return (0, import_internal.evalExpr)(obj, expr, copts) ?? null; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/_internal.js -var require_internal4 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - ARR_OPTS: () => ARR_OPTS, - INT_OPTS: () => INT_OPTS, - errExpectArray: () => errExpectArray, - errExpectNumber: () => errExpectNumber, - errExpectObject: () => errExpectObject, - errExpectString: () => errExpectString, - errInvalidArgs: () => errInvalidArgs - }); - module.exports = __toCommonJS(internal_exports); - var import_util3 = require_util(); - var INT_OPTS = { - int: { int: true }, - // (-∞, ∞) - pos: { min: 1, int: true }, - // [1, ∞] - index: { min: 0, int: true }, - // [0, ∞] - nzero: { min: 0, max: 0, int: true } - // non-zero - }; - var ARR_OPTS = { - int: { type: "integers" }, - obj: { type: "objects" } - }; - function errInvalidArgs(failOnError, message2) { - (0, import_util3.assert)(!failOnError, message2); - return null; - } - function errExpectObject(failOnError, prefix) { - const msg = `${prefix} expression must resolve to object`; - (0, import_util3.assert)(!failOnError, msg); - return null; - } - function errExpectString(failOnError, prefix) { - const msg = `${prefix} expression must resolve to string`; - (0, import_util3.assert)(!failOnError, msg); - return null; - } - function errExpectNumber(failOnError, name, opts) { - const type = opts?.int ? "integer" : "number"; - const min = opts?.min ?? -Infinity; - const max = opts?.max ?? Infinity; - let msg; - if (min === 0 && max === 0) { - msg = `${name} expression must resolve to non-zero ${type}`; - } else if (min === 0 && max === Infinity) { - msg = `${name} expression must resolve to non-negative ${type}`; - } else if (min !== -Infinity && max !== Infinity) { - msg = `${name} expression must resolve to ${type} in range [${min}, ${max}]`; - } else if (min > 0) { - msg = `${name} expression must resolve to positive ${type}`; - } else { - msg = `${name} expression must resolve to ${type}`; - } - (0, import_util3.assert)(!failOnError, msg); - return null; - } - function errExpectArray(failOnError, prefix, opts) { - let suffix = "array"; - if (!(0, import_util3.isNil)(opts?.size) && opts?.size >= 0) - suffix = opts.size === 0 ? "non-zero array" : `array(${opts.size})`; - if (opts?.type) suffix = `array of ${opts.type}`; - const msg = `${prefix} expression must resolve to ${suffix}`; - (0, import_util3.assert)(!failOnError, msg); - return null; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/firstN.js -var require_firstN = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/firstN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var firstN_exports = {}; - __export5(firstN_exports, { - $firstN: () => $firstN - }); - module.exports = __toCommonJS(firstN_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var import_push = require_push(); - var $firstN = (coll, expr, options) => { - const foe = options.failOnError; - const copts = options; - const m = coll.length; - const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts); - if (!(0, import_util3.isInteger)(n) || n < 1) - return (0, import_internal2.errExpectNumber)(foe, "$firstN 'n'", import_internal2.INT_OPTS.pos); - return (0, import_push.$push)(m <= n ? coll : coll.slice(0, n), expr.input, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/last.js -var require_last = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/last.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var last_exports = {}; - __export5(last_exports, { - $last: () => $last - }); - module.exports = __toCommonJS(last_exports); - var import_internal = require_internal2(); - var $last = (coll, expr, options) => { - const obj = coll[coll.length - 1]; - const copts = import_internal.ComputeOptions.init(options).update({ root: obj }); - return (0, import_internal.evalExpr)(obj, expr, copts) ?? null; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/lastN.js -var require_lastN = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/lastN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var lastN_exports = {}; - __export5(lastN_exports, { - $lastN: () => $lastN - }); - module.exports = __toCommonJS(lastN_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var import_push = require_push(); - var $lastN = (coll, expr, options) => { - const copts = options; - const m = coll.length; - const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts); - const foe = options.failOnError; - if (!(0, import_util3.isInteger)(n) || n < 1) { - return (0, import_internal2.errExpectNumber)(foe, "$lastN 'n'", import_internal2.INT_OPTS.pos); - } - return (0, import_push.$push)(m <= n ? coll : coll.slice(m - n), expr.input, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/max.js -var require_max = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/max.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var max_exports = {}; - __export5(max_exports, { - $max: () => $max - }); - module.exports = __toCommonJS(max_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var $max = (coll, expr, options) => { - const items = (0, import_push.$push)(coll, expr, options).filter((v) => !(0, import_util3.isNil)(v)); - if (!items.length) return null; - return items.reduce((r, v) => (0, import_util3.compare)(r, v) >= 0 ? r : v); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/maxN.js -var require_maxN = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/maxN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var maxN_exports = {}; - __export5(maxN_exports, { - $maxN: () => $maxN - }); - module.exports = __toCommonJS(maxN_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var import_push = require_push(); - var $maxN = (coll, expr, options) => { - const copts = options; - const m = coll.length; - const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts); - if (!(0, import_util3.isInteger)(n) || n < 1) { - return (0, import_internal2.errExpectNumber)(options.failOnError, "$maxN 'n'", import_internal2.INT_OPTS.pos); - } - const arr = (0, import_push.$push)(coll, expr.input, options).filter((o) => !(0, import_util3.isNil)(o)); - arr.sort((a, b) => -1 * (0, import_util3.compare)(a, b)); - return m <= n ? arr : arr.slice(0, n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/percentile.js -var require_percentile = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/percentile.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var percentile_exports = {}; - __export5(percentile_exports, { - $percentile: () => $percentile - }); - module.exports = __toCommonJS(percentile_exports); - var import_util3 = require_util(); - var import_internal = require_internal4(); - var import_push = require_push(); - var $percentile = (coll, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "p") && (0, import_util3.isArray)(expr.p), - "$percentile expects object { input, p }" - ); - const X = (0, import_push.$push)(coll, expr.input, options).filter(import_util3.isNumber).sort(); - const centiles = (0, import_push.$push)(expr.p, "$$CURRENT", options); - const method = expr.method || "approximate"; - for (const n of centiles) { - if (!(0, import_util3.isNumber)(n) || n < 0 || n > 1) { - return (0, import_internal.errInvalidArgs)( - options.failOnError, - "$percentile 'p' must resolve to array of numbers between [0.0, 1.0]" - ); - } - } - return centiles.map((p) => { - const r = p * (X.length - 1) + 1; - const ri = Math.floor(r); - const result = r === ri ? X[r - 1] : X[ri - 1] + r % 1 * (X[ri] - X[ri - 1]); - switch (method) { - case "exact": - return result; - case "approximate": { - const i = (0, import_util3.findInsertIndex)(X, result); - return i / X.length >= p ? X[Math.max(i - 1, 0)] : X[i]; - } - } - }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/median.js -var require_median = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/median.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var median_exports = {}; - __export5(median_exports, { - $median: () => $median - }); - module.exports = __toCommonJS(median_exports); - var import_percentile = require_percentile(); - var $median = (coll, expr, options) => (0, import_percentile.$percentile)(coll, { ...expr, p: [0.5] }, options)?.pop(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/mergeObjects.js -var require_mergeObjects = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/mergeObjects.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var mergeObjects_exports = {}; - __export5(mergeObjects_exports, { - $mergeObjects: () => $mergeObjects - }); - module.exports = __toCommonJS(mergeObjects_exports); - var import_util3 = require_util(); - var $mergeObjects = (coll, _expr2, _options2) => { - const acc = {}; - for (const o of coll) { - if ((0, import_util3.isNil)(o)) continue; - for (const k of Object.keys(o)) { - if (o[k] !== void 0) acc[k] = o[k]; - } - } - return acc; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/min.js -var require_min = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/min.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var min_exports = {}; - __export5(min_exports, { - $min: () => $min - }); - module.exports = __toCommonJS(min_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var $min = (coll, expr, options) => { - const items = (0, import_push.$push)(coll, expr, options).filter((v) => !(0, import_util3.isNil)(v)); - if (!items.length) return null; - return items.reduce((r, v) => (0, import_util3.compare)(r, v) <= 0 ? r : v); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/minN.js -var require_minN = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/minN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var minN_exports = {}; - __export5(minN_exports, { - $minN: () => $minN - }); - module.exports = __toCommonJS(minN_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var import_push = require_push(); - var $minN = (coll, expr, options) => { - const copts = options; - const m = coll.length; - const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts); - if (!(0, import_util3.isInteger)(n) || n < 1) { - return (0, import_internal2.errExpectNumber)(options.failOnError, "$minN 'n'", import_internal2.INT_OPTS.pos); - } - const arr = (0, import_push.$push)(coll, expr.input, options).filter((o) => !(0, import_util3.isNil)(o)); - arr.sort(import_util3.compare); - return m <= n ? arr : arr.slice(0, n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevPop.js -var require_stdDevPop = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevPop.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var stdDevPop_exports = {}; - __export5(stdDevPop_exports, { - $stdDevPop: () => $stdDevPop - }); - module.exports = __toCommonJS(stdDevPop_exports); - var import_util3 = require_util(); - var import_internal = require_internal3(); - var import_push = require_push(); - var $stdDevPop = (coll, expr, options) => (0, import_internal.stddev)((0, import_push.$push)(coll, expr, options).filter(import_util3.isNumber), false); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevSamp.js -var require_stdDevSamp = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevSamp.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var stdDevSamp_exports = {}; - __export5(stdDevSamp_exports, { - $stdDevSamp: () => $stdDevSamp - }); - module.exports = __toCommonJS(stdDevSamp_exports); - var import_util3 = require_util(); - var import_internal = require_internal3(); - var import_push = require_push(); - var $stdDevSamp = (coll, expr, options) => (0, import_internal.stddev)((0, import_push.$push)(coll, expr, options).filter(import_util3.isNumber), true); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/sum.js -var require_sum = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/sum.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sum_exports = {}; - __export5(sum_exports, { - $sum: () => $sum - }); - module.exports = __toCommonJS(sum_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var $sum = (coll, expr, options) => { - if ((0, import_util3.isNumber)(expr)) return coll.length * expr; - const nums = (0, import_push.$push)(coll, expr, options).filter(import_util3.isNumber); - return nums.reduce((r, n) => r + n, 0); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/topN.js -var require_topN = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/topN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var topN_exports = {}; - __export5(topN_exports, { - $topN: () => $topN - }); - module.exports = __toCommonJS(topN_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_sort = require_sort(); - var import_push = require_push(); - var $topN = (coll, expr, options) => { - const copts = options; - const { n, sortBy } = (0, import_internal.evalExpr)(copts?.local?.groupId, expr, copts); - const result = (0, import_sort.$sort)((0, import_lazy.Lazy)(coll), sortBy, options).take(n).collect(); - return (0, import_push.$push)(result, expr.output, copts); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/top.js -var require_top = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/top.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var top_exports = {}; - __export5(top_exports, { - $top: () => $top - }); - module.exports = __toCommonJS(top_exports); - var import_topN = require_topN(); - var $top = (coll, expr, options) => (0, import_topN.$topN)(coll, { ...expr, n: 1 }, options); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/index.js -var require_accumulator2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var accumulator_exports = {}; - module.exports = __toCommonJS(accumulator_exports); - __reExport(accumulator_exports, require_accumulator(), module.exports); - __reExport(accumulator_exports, require_addToSet(), module.exports); - __reExport(accumulator_exports, require_avg(), module.exports); - __reExport(accumulator_exports, require_bottom(), module.exports); - __reExport(accumulator_exports, require_bottomN(), module.exports); - __reExport(accumulator_exports, require_count(), module.exports); - __reExport(accumulator_exports, require_covariancePop(), module.exports); - __reExport(accumulator_exports, require_covarianceSamp(), module.exports); - __reExport(accumulator_exports, require_first(), module.exports); - __reExport(accumulator_exports, require_firstN(), module.exports); - __reExport(accumulator_exports, require_last(), module.exports); - __reExport(accumulator_exports, require_lastN(), module.exports); - __reExport(accumulator_exports, require_max(), module.exports); - __reExport(accumulator_exports, require_maxN(), module.exports); - __reExport(accumulator_exports, require_median(), module.exports); - __reExport(accumulator_exports, require_mergeObjects(), module.exports); - __reExport(accumulator_exports, require_min(), module.exports); - __reExport(accumulator_exports, require_minN(), module.exports); - __reExport(accumulator_exports, require_percentile(), module.exports); - __reExport(accumulator_exports, require_push(), module.exports); - __reExport(accumulator_exports, require_stdDevPop(), module.exports); - __reExport(accumulator_exports, require_stdDevSamp(), module.exports); - __reExport(accumulator_exports, require_sum(), module.exports); - __reExport(accumulator_exports, require_top(), module.exports); - __reExport(accumulator_exports, require_topN(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/abs.js -var require_abs = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/abs.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var abs_exports = {}; - __export5(abs_exports, { - $abs: () => $abs - }); - module.exports = __toCommonJS(abs_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $abs = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(n)) return null; - if (typeof n !== "number") - return (0, import_internal2.errExpectNumber)(options.failOnError, "$abs"); - return Math.abs(n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/add.js -var require_add = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/add.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var add_exports = {}; - __export5(add_exports, { - $add: () => $add - }); - module.exports = __toCommonJS(add_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var err = "$add expression must resolve to array of numbers."; - var $add = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - const failOnError = options.failOnError; - let dateFound = false; - let result = 0; - if (!(0, import_util3.isArray)(args)) return (0, import_internal2.errInvalidArgs)(failOnError, err); - for (const n of args) { - if ((0, import_util3.isNil)(n)) return null; - if (typeof n === "number") { - result += n; - } else if ((0, import_util3.isDate)(n)) { - if (dateFound) { - return (0, import_internal2.errInvalidArgs)(failOnError, "$add must only have one date"); - } - dateFound = true; - result += +n; - } else { - return (0, import_internal2.errInvalidArgs)(failOnError, err); - } - } - return dateFound ? new Date(result) : result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ceil.js -var require_ceil = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ceil.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var ceil_exports = {}; - __export5(ceil_exports, { - $ceil: () => $ceil - }); - module.exports = __toCommonJS(ceil_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $ceil = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(n)) return null; - if (typeof n !== "number") - return (0, import_internal2.errExpectNumber)(options.failOnError, "$ceil"); - return Math.ceil(n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/divide.js -var require_divide = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/divide.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var divide_exports = {}; - __export5(divide_exports, { - $divide: () => $divide - }); - module.exports = __toCommonJS(divide_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $divide = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), "$divide expects array(2)"); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - let t_num = true; - for (const v of args) { - if ((0, import_util3.isNil)(v)) return null; - t_num && (t_num = (0, import_util3.isNumber)(v)); - } - if (!t_num) { - return (0, import_internal2.errExpectArray)(foe, "$divide", { - size: 2, - type: "number" - }); - } - if (args[1] === 0) - return (0, import_internal2.errInvalidArgs)(foe, "$divide cannot divide by zero"); - return args[0] / args[1]; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/exp.js -var require_exp = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/exp.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var exp_exports = {}; - __export5(exp_exports, { - $exp: () => $exp - }); - module.exports = __toCommonJS(exp_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $exp = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(n)) return null; - if (typeof n !== "number") { - return (0, import_internal2.errExpectNumber)(options.failOnError, "$exp"); - } - return Math.exp(n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/floor.js -var require_floor = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/floor.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var floor_exports = {}; - __export5(floor_exports, { - $floor: () => $floor - }); - module.exports = __toCommonJS(floor_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $floor = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(n)) return null; - if (typeof n !== "number") { - return (0, import_internal2.errExpectNumber)(options.failOnError, "$floor"); - } - return Math.floor(n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ln.js -var require_ln = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ln.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var ln_exports = {}; - __export5(ln_exports, { - $ln: () => $ln - }); - module.exports = __toCommonJS(ln_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $ln = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(n)) return null; - if (typeof n !== "number") { - return (0, import_internal2.errExpectNumber)(options.failOnError, "$ln"); - } - return Math.log(n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log.js -var require_log = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var log_exports = {}; - __export5(log_exports, { - $log: () => $log - }); - module.exports = __toCommonJS(log_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $log = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isArray)(args) && args.length == 2) { - let t_num = true; - for (const v of args) { - if ((0, import_util3.isNil)(v)) return null; - t_num && (t_num = typeof v === "number"); - } - if (t_num) return Math.log10(args[0]) / Math.log10(args[1]); - } - return (0, import_internal2.errExpectArray)(options.failOnError, "$log", { - size: 2, - type: "number" - }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log10.js -var require_log10 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log10.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var log10_exports = {}; - __export5(log10_exports, { - $log10: () => $log10 - }); - module.exports = __toCommonJS(log10_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $log10 = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(n)) return null; - if (typeof n === "number") return Math.log10(n); - return (0, import_internal2.errExpectNumber)(options.failOnError, "$log10"); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/mod.js -var require_mod = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/mod.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var mod_exports = {}; - __export5(mod_exports, { - $mod: () => $mod - }); - module.exports = __toCommonJS(mod_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $mod = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - let invalid = !(0, import_util3.isArray)(args) || args.length != 2; - invalid || (invalid = !args.every((v) => typeof v === "number")); - if (invalid) - return (0, import_internal2.errExpectArray)(options.failOnError, "$mod", { - size: 2, - type: "number" - }); - return args[0] % args[1]; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/multiply.js -var require_multiply = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/multiply.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var multiply_exports = {}; - __export5(multiply_exports, { - $multiply: () => $multiply - }); - module.exports = __toCommonJS(multiply_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $multiply = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), "$multiply expects array"); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - if (args.some(import_util3.isNil)) return null; - let res = 1; - for (const n of args) { - if (!(0, import_util3.isNumber)(n)) - return (0, import_internal2.errExpectArray)(foe, "$multiply", { type: "number" }); - res *= n; - } - return res; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/pow.js -var require_pow = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/pow.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var pow_exports = {}; - __export5(pow_exports, { - $pow: () => $pow - }); - module.exports = __toCommonJS(pow_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $pow = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, "$pow expects array(2)"); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - let t_num = true; - for (const v of args) { - if ((0, import_util3.isNil)(v)) return null; - t_num && (t_num = (0, import_util3.isNumber)(v)); - } - if (!t_num) { - return (0, import_internal2.errExpectArray)(foe, "$pow", { - size: 2, - type: "number" - }); - } - if (args[0] === 0 && args[1] < 0) - (0, import_internal2.errInvalidArgs)(foe, "$pow cannot raise 0 to a negative exponent"); - return Math.pow(args[0], args[1]); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/_internal.js -var require_internal5 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - truncate: () => truncate - }); - module.exports = __toCommonJS(internal_exports); - var import_util3 = require_util(); - var import_internal = require_internal4(); - function truncate(num, precision, opts) { - const { name, roundOff, failOnError } = opts; - if ((0, import_util3.isNil)(num)) return null; - if (Number.isNaN(num) || Math.abs(num) === Infinity) return num; - if (!(0, import_util3.isNumber)(num)) { - return (0, import_internal.errExpectNumber)(failOnError, `${name} arg1 `); - } - if (!(0, import_util3.isInteger)(precision) || precision < -20 || precision > 100) { - return (0, import_internal.errExpectNumber)(failOnError, `${name} arg2 `, { - min: -20, - max: 100, - int: true - }); - } - const sign2 = Math.abs(num) === num ? 1 : -1; - num = Math.abs(num); - let result = Math.trunc(num); - const decimals = parseFloat((num - result).toFixed(Math.abs(precision) + 1)); - if (precision === 0) { - const firstDigit = Math.trunc(10 * decimals); - if (roundOff && ((result & 1) === 1 && firstDigit >= 5 || firstDigit > 5)) { - result++; - } - } else if (precision > 0) { - const offset = Math.pow(10, precision); - let remainder = Math.trunc(decimals * offset); - const lastDigit = Math.trunc(decimals * offset * 10) % 10; - if (roundOff && lastDigit > 5) { - remainder += 1; - } - result = (result * offset + remainder) / offset; - } else if (precision < 0) { - const offset = Math.pow(10, -1 * precision); - let excess = result % offset; - result = Math.max(0, result - excess); - if (roundOff && sign2 === -1) { - while (excess > 10) { - excess -= excess / 10; - } - if (result > 0 && excess >= 5) { - result += offset; - } - } - } - return result * sign2; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/round.js -var require_round = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/round.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var round_exports = {}; - __export5(round_exports, { - $round: () => $round - }); - module.exports = __toCommonJS(round_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal5(); - var $round = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), "$round expects array(2)"); - const [n, precision] = (0, import_internal.evalExpr)(obj, expr, options); - return (0, import_internal2.truncate)(n, precision ?? 0, { - name: "$round", - roundOff: true, - failOnError: options.failOnError - }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sigmoid.js -var require_sigmoid = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sigmoid.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sigmoid_exports = {}; - __export5(sigmoid_exports, { - $sigmoid: () => $sigmoid - }); - module.exports = __toCommonJS(sigmoid_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var PRECISION = 1e10; - var $sigmoid = (obj, expr, options) => { - if ((0, import_util3.isNil)(expr)) return null; - const args = (0, import_internal.evalExpr)(obj, expr, options); - const { input, onNull } = (0, import_util3.isObject)(args) ? args : { input: args }; - if ((0, import_util3.isNil)(input)) return (0, import_util3.isNumber)(onNull) ? onNull : null; - if ((0, import_util3.isNumber)(input)) { - const result = 1 / (1 + Math.exp(-input)); - return Math.round(result * PRECISION) / PRECISION; - } - return (0, import_internal2.errExpectNumber)(options.failOnError, "$sigmoid"); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sqrt.js -var require_sqrt = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sqrt.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sqrt_exports = {}; - __export5(sqrt_exports, { - $sqrt: () => $sqrt - }); - module.exports = __toCommonJS(sqrt_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $sqrt = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - const skip = !options.failOnError; - if ((0, import_util3.isNil)(n)) return null; - if (typeof n !== "number" || n < 0) { - (0, import_util3.assert)(skip, "$sqrt expression must resolve to non-negative number."); - return null; - } - return Math.sqrt(n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/subtract.js -var require_subtract = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/subtract.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var subtract_exports = {}; - __export5(subtract_exports, { - $subtract: () => $subtract - }); - module.exports = __toCommonJS(subtract_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $subtract = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), "$subtract expects array(2)"); - const args = (0, import_internal.evalExpr)(obj, expr, options); - if (args.some(import_util3.isNil)) return null; - const foe = options.failOnError; - const [a, b] = args; - if ((0, import_util3.isDate)(a) && (0, import_util3.isNumber)(b)) return new Date(+a - Math.round(b)); - if ((0, import_util3.isDate)(a) && (0, import_util3.isDate)(b)) return +a - +b; - if (args.every((v) => typeof v === "number")) return a - b; - if ((0, import_util3.isNumber)(a) && (0, import_util3.isDate)(b)) { - return (0, import_internal2.errInvalidArgs)(foe, "$subtract cannot subtract date from number"); - } - return (0, import_internal2.errExpectArray)(foe, "$subtract", { - size: 2, - type: "number|date" - }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/trunc.js -var require_trunc = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/trunc.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var trunc_exports = {}; - __export5(trunc_exports, { - $trunc: () => $trunc - }); - module.exports = __toCommonJS(trunc_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal5(); - var $trunc = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), "$trunc expects array(2)"); - const [n, precision] = (0, import_internal.evalExpr)(obj, expr, options); - return (0, import_internal2.truncate)(n, precision ?? 0, { - name: "$trunc", - roundOff: false, - failOnError: options.failOnError - }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/index.js -var require_arithmetic = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var arithmetic_exports = {}; - module.exports = __toCommonJS(arithmetic_exports); - __reExport(arithmetic_exports, require_abs(), module.exports); - __reExport(arithmetic_exports, require_add(), module.exports); - __reExport(arithmetic_exports, require_ceil(), module.exports); - __reExport(arithmetic_exports, require_divide(), module.exports); - __reExport(arithmetic_exports, require_exp(), module.exports); - __reExport(arithmetic_exports, require_floor(), module.exports); - __reExport(arithmetic_exports, require_ln(), module.exports); - __reExport(arithmetic_exports, require_log(), module.exports); - __reExport(arithmetic_exports, require_log10(), module.exports); - __reExport(arithmetic_exports, require_mod(), module.exports); - __reExport(arithmetic_exports, require_multiply(), module.exports); - __reExport(arithmetic_exports, require_pow(), module.exports); - __reExport(arithmetic_exports, require_round(), module.exports); - __reExport(arithmetic_exports, require_sigmoid(), module.exports); - __reExport(arithmetic_exports, require_sqrt(), module.exports); - __reExport(arithmetic_exports, require_subtract(), module.exports); - __reExport(arithmetic_exports, require_trunc(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayElemAt.js -var require_arrayElemAt = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayElemAt.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var arrayElemAt_exports = {}; - __export5(arrayElemAt_exports, { - $arrayElemAt: () => $arrayElemAt - }); - module.exports = __toCommonJS(arrayElemAt_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$arrayElemAt"; - var $arrayElemAt = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, `${OP} expects array(2)`); - const args = (0, import_internal.evalExpr)(obj, expr, options); - if (args.some(import_util3.isNil)) return null; - const foe = options.failOnError; - const [arr, index] = args; - if (!(0, import_util3.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, `${OP} arg1 `); - if (!(0, import_util3.isInteger)(index)) - return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `, import_internal2.INT_OPTS.int); - if (index < 0 && Math.abs(index) <= arr.length) { - return arr[(index + arr.length) % arr.length]; - } else if (index >= 0 && index < arr.length) { - return arr[index]; - } - return void 0; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayToObject.js -var require_arrayToObject = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayToObject.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var arrayToObject_exports = {}; - __export5(arrayToObject_exports, { - $arrayToObject: () => $arrayToObject - }); - module.exports = __toCommonJS(arrayToObject_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var ERR_OPTS = { - generic: { type: "key-value pairs" }, - array: { type: "[k,v]" }, - object: { type: "{k,v}" } - }; - var $arrayToObject = (obj, expr, options) => { - const foe = options.failOnError; - const arr = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(arr)) return null; - if (!(0, import_util3.isArray)(arr)) - return (0, import_internal2.errExpectArray)(foe, "$arrayToObject", ERR_OPTS.generic); - let tag2 = 0; - const newObj = {}; - for (const item of arr) { - if ((0, import_util3.isArray)(item)) { - const val = (0, import_util3.flatten)(item); - if (!tag2) tag2 = 1; - if (tag2 !== 1) { - return (0, import_internal2.errExpectArray)(foe, "$arrayToObject", ERR_OPTS.object); - } - const [k, v] = val; - newObj[k] = v; - } else if ((0, import_util3.isObject)(item) && (0, import_util3.has)(item, "k", "v")) { - if (!tag2) tag2 = 2; - if (tag2 !== 2) { - return (0, import_internal2.errExpectArray)(foe, "$arrayToObject", ERR_OPTS.array); - } - const { k, v } = item; - newObj[k] = v; - } else { - return (0, import_internal2.errExpectArray)(foe, "$arrayToObject", ERR_OPTS.generic); - } - } - return newObj; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/concatArrays.js -var require_concatArrays = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/concatArrays.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var concatArrays_exports = {}; - __export5(concatArrays_exports, { - $concatArrays: () => $concatArrays - }); - module.exports = __toCommonJS(concatArrays_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $concatArrays = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - if ((0, import_util3.isNil)(args)) return null; - if (!(0, import_util3.isArray)(args)) return (0, import_internal2.errExpectArray)(foe, "$concatArrays"); - let size = 0; - for (const arr of args) { - if ((0, import_util3.isNil)(arr)) return null; - if (!(0, import_util3.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, "$concatArrays"); - size += arr.length; - } - const result = new Array(size); - let i = 0; - for (const arr of args) for (const item of arr) result[i++] = item; - return result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/filter.js -var require_filter = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/filter.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var filter_exports = {}; - __export5(filter_exports, { - $filter: () => $filter - }); - module.exports = __toCommonJS(filter_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var import_internal3 = require_internal4(); - var $filter = (obj, expr, options) => { - (0, import_internal2.assert)( - (0, import_internal2.isObject)(expr) && (0, import_internal2.has)(expr, "input", "cond"), - "$filter expects object { input, as, cond, limit }" - ); - const input = (0, import_internal.evalExpr)(obj, expr.input, options); - const foe = options.failOnError; - if ((0, import_internal2.isNil)(input)) return null; - if (!(0, import_internal2.isArray)(input)) return (0, import_internal3.errExpectArray)(foe, "$filter 'input'"); - const limit = expr.limit ?? Math.max(input.length, 1); - if (!(0, import_internal2.isInteger)(limit) || limit < 1) - return (0, import_internal3.errExpectNumber)(foe, "$filter 'limit'", { min: 1, int: true }); - if (input.length === 0) return []; - const copts = import_internal.ComputeOptions.init(options); - const k = expr?.as || "this"; - const locals = { variables: {} }; - const res = []; - for (let i = 0, j = 0; i < input.length && j < limit; i++) { - locals.variables[k] = input[i]; - const cond = (0, import_internal.evalExpr)(obj, expr.cond, copts.update(locals)); - if ((0, import_internal2.truthy)(cond, options.useStrictMode)) { - res.push(input[i]); - j++; - } - } - return res; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/first.js -var require_first2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/first.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var first_exports = {}; - __export5(first_exports, { - $first: () => $first - }); - module.exports = __toCommonJS(first_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_first = require_first(); - var import_internal2 = require_internal4(); - var $first = (obj, expr, options) => { - if ((0, import_util3.isArray)(obj)) return (0, import_first.$first)(obj, expr, options); - const arr = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(arr)) return null; - if (!(0, import_util3.isArray)(arr)) { - return (0, import_internal2.errExpectArray)(options.failOnError, "$first"); - } - return (0, import_util3.flatten)(arr)[0]; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/firstN.js -var require_firstN2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/firstN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var firstN_exports = {}; - __export5(firstN_exports, { - $firstN: () => $firstN - }); - module.exports = __toCommonJS(firstN_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_firstN = require_firstN(); - var import_internal2 = require_internal4(); - var $firstN = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "n"), - "$firstN expects object { input, n }" - ); - if ((0, import_util3.isArray)(obj)) return (0, import_firstN.$firstN)(obj, expr, options); - const { input, n } = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(input)) return null; - if (!(0, import_util3.isArray)(input)) - return (0, import_internal2.errExpectArray)(options.failOnError, "$firstN 'input'"); - return (0, import_firstN.$firstN)(input, { n, input: "$$this" }, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/in.js -var require_in = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/in.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var in_exports = {}; - __export5(in_exports, { - $in: () => $in2 - }); - module.exports = __toCommonJS(in_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $in2 = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, "$in expects array(2)"); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const [item, arr] = args; - if (!(0, import_util3.isArray)(arr)) - return (0, import_internal2.errInvalidArgs)(options.failOnError, "$in arg2 "); - for (const v of arr) if ((0, import_util3.isEqual)(v, item)) return true; - return false; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/indexOfArray.js -var require_indexOfArray = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/indexOfArray.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var indexOfArray_exports = {}; - __export5(indexOfArray_exports, { - $indexOfArray: () => $indexOfArray - }); - module.exports = __toCommonJS(indexOfArray_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var import_internal3 = require_internal4(); - var OP = "$indexOfArray"; - var $indexOfArray = (obj, expr, options) => { - (0, import_internal2.assert)( - (0, import_internal2.isArray)(expr) && expr.length > 1 && expr.length < 5, - `${OP} expects array(4)` - ); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - const arr = args[0]; - if ((0, import_internal2.isNil)(arr)) return null; - if (!(0, import_internal2.isArray)(arr)) return (0, import_internal3.errExpectArray)(foe, `${OP} arg1 `); - const search = args[1]; - const start = args[2] ?? 0; - const end = args[3] ?? arr.length; - if (!(0, import_internal2.isInteger)(start) || start < 0) - return (0, import_internal3.errExpectNumber)(foe, `${OP} arg3 `, import_internal3.INT_OPTS.pos); - if (!(0, import_internal2.isInteger)(end) || end < 0) - return (0, import_internal3.errExpectNumber)(foe, `${OP} arg4 `, import_internal3.INT_OPTS.pos); - if (start > end) return -1; - const input = start > 0 || end < arr.length ? arr.slice(start, end) : arr; - return input.findIndex((v) => (0, import_internal2.isEqual)(v, search)) + start; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/isArray.js -var require_isArray = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/isArray.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var isArray_exports = {}; - __export5(isArray_exports, { - $isArray: () => $isArray - }); - module.exports = __toCommonJS(isArray_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $isArray = (obj, expr, options) => { - let input = expr; - if ((0, import_util3.isArray)(expr)) { - (0, import_util3.assert)(expr.length === 1, "$isArray expects array(1)"); - input = expr[0]; - } - return (0, import_util3.isArray)((0, import_internal.evalExpr)(obj, input, options)); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/last.js -var require_last2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/last.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var last_exports = {}; - __export5(last_exports, { - $last: () => $last - }); - module.exports = __toCommonJS(last_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_last = require_last(); - var import_internal2 = require_internal4(); - var $last = (obj, expr, options) => { - if ((0, import_util3.isArray)(obj)) return (0, import_last.$last)(obj, expr, options); - const arr = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(arr)) return null; - if (!(0, import_util3.isArray)(arr) || arr.length === 0) { - return (0, import_internal2.errExpectArray)(options.failOnError, "$last", { size: 0 }); - } - return (0, import_util3.flatten)(arr)[arr.length - 1]; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/lastN.js -var require_lastN2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/lastN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var lastN_exports = {}; - __export5(lastN_exports, { - $lastN: () => $lastN - }); - module.exports = __toCommonJS(lastN_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_lastN = require_lastN(); - var import_internal2 = require_internal4(); - var $lastN = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "n"), - "$lastN expects object { input, n }" - ); - if ((0, import_util3.isArray)(obj)) return (0, import_lastN.$lastN)(obj, expr, options); - const { input, n } = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(input)) return null; - if (!(0, import_util3.isArray)(input)) { - return (0, import_internal2.errExpectArray)(options.failOnError, "$lastN 'input'"); - } - return (0, import_lastN.$lastN)(input, { n, input: "$$this" }, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/map.js -var require_map = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/map.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var map_exports = {}; - __export5(map_exports, { - $map: () => $map - }); - module.exports = __toCommonJS(map_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $map = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "in"), - "$map expects object { input, as, in }" - ); - const input = (0, import_internal.evalExpr)(obj, expr.input, options); - const foe = options.failOnError; - if ((0, import_util3.isNil)(input)) return null; - if (!(0, import_util3.isArray)(input)) return (0, import_internal2.errExpectArray)(foe, "$map 'input'"); - if (!(0, import_util3.isNil)(expr.as) && !(0, import_util3.isString)(expr.as)) - return (0, import_internal2.errExpectString)(foe, "$map 'as'"); - const copts = import_internal.ComputeOptions.init(options); - const k = expr.as || "this"; - const locals = { variables: {} }; - return input.map((o) => { - locals.variables[k] = o; - return (0, import_internal.evalExpr)(obj, expr.in, copts.update(locals)); - }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/maxN.js -var require_maxN2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/maxN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var maxN_exports = {}; - __export5(maxN_exports, { - $maxN: () => $maxN - }); - module.exports = __toCommonJS(maxN_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_maxN = require_maxN(); - var import_internal2 = require_internal4(); - var $maxN = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "n"), - "$maxN expects object { input, n }" - ); - if ((0, import_util3.isArray)(obj)) return (0, import_maxN.$maxN)(obj, expr, options); - const { input, n } = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(input)) return null; - if (!(0, import_util3.isArray)(input)) - return (0, import_internal2.errExpectArray)(options.failOnError, "$maxN 'input'"); - return (0, import_maxN.$maxN)(input, { n, input: "$$this" }, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/minN.js -var require_minN2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/minN.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var minN_exports = {}; - __export5(minN_exports, { - $minN: () => $minN - }); - module.exports = __toCommonJS(minN_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_minN = require_minN(); - var import_internal2 = require_internal4(); - var $minN = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "n"), - "$minN expects object { input, n }" - ); - if ((0, import_util3.isArray)(obj)) return (0, import_minN.$minN)(obj, expr, options); - const { input, n } = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(input)) return null; - if (!(0, import_util3.isArray)(input)) - return (0, import_internal2.errExpectArray)(options.failOnError, "$minN 'input'"); - return (0, import_minN.$minN)(input, { n, input: "$$this" }, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/range.js -var require_range = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/range.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var range_exports = {}; - __export5(range_exports, { - $range: () => $range - }); - module.exports = __toCommonJS(range_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $range = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isArray)(expr) && expr.length > 1 && expr.length < 4, - "$range expects array(3)" - ); - const [start, end, arg3] = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - const step = arg3 ?? 1; - if (!(0, import_util3.isInteger)(start)) - return (0, import_internal2.errExpectNumber)(foe, `$range arg1 `, import_internal2.INT_OPTS.int); - if (!(0, import_util3.isInteger)(end)) - return (0, import_internal2.errExpectNumber)(foe, `$range arg2 `, import_internal2.INT_OPTS.int); - if (!(0, import_util3.isInteger)(step) || step === 0) - return (0, import_internal2.errExpectNumber)(foe, `$range arg3 `, import_internal2.INT_OPTS.nzero); - const result = new Array(); - let counter = start; - while (counter < end && step > 0 || counter > end && step < 0) { - result.push(counter); - counter += step; - } - return result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reduce.js -var require_reduce = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reduce.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var reduce_exports = {}; - __export5(reduce_exports, { - $reduce: () => $reduce - }); - module.exports = __toCommonJS(reduce_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - function $reduce(obj, expr, options) { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "initialValue", "in"), - "$reduce expects object { input, initialValue, in }" - ); - const input = (0, import_internal.evalExpr)(obj, expr.input, options); - const initialValue = (0, import_internal.evalExpr)(obj, expr.initialValue, options); - const inExpr = expr["in"]; - if ((0, import_util3.isNil)(input)) return null; - if (!(0, import_util3.isArray)(input)) - return (0, import_internal2.errExpectArray)(options.failOnError, "$reduce 'input'"); - const copts = import_internal.ComputeOptions.init(options); - const locals = { variables: { value: null } }; - let result = initialValue; - for (let i = 0; i < input.length; i++) { - locals.variables.value = result; - result = (0, import_internal.evalExpr)(input[i], inExpr, copts.update(locals)); - } - return result; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reverseArray.js -var require_reverseArray = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reverseArray.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var reverseArray_exports = {}; - __export5(reverseArray_exports, { - $reverseArray: () => $reverseArray - }); - module.exports = __toCommonJS(reverseArray_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $reverseArray = (obj, expr, options) => { - const arr = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(arr)) return null; - if (!(0, import_util3.isArray)(arr)) - return (0, import_internal2.errExpectArray)(options.failOnError, "$reverseArray"); - return arr.slice().reverse(); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/size.js -var require_size = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/size.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var size_exports = {}; - __export5(size_exports, { - $size: () => $size - }); - module.exports = __toCommonJS(size_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $size = (obj, expr, options) => { - const value = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(value)) return null; - return (0, import_util3.isArray)(value) ? value.length : (0, import_internal2.errExpectNumber)(options.failOnError, "$size"); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/slice.js -var require_slice = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/slice.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var slice_exports = {}; - __export5(slice_exports, { - $slice: () => $slice - }); - module.exports = __toCommonJS(slice_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $slice = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isArray)(expr) && expr.length > 1 && expr.length < 4, - "$slice expects array(3)" - ); - const foe = options.failOnError; - const args = (0, import_internal.evalExpr)(obj, expr, options); - const arr = args[0]; - let skip = args[1]; - let limit = args[2]; - if (!(0, import_util3.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, "$slice arg1 "); - if (!(0, import_util3.isInteger)(skip)) - return (0, import_internal2.errExpectNumber)(foe, "$slice arg2 ", import_internal2.INT_OPTS.int); - if (!(0, import_util3.isNil)(limit) && !(0, import_util3.isInteger)(limit)) - return (0, import_internal2.errExpectNumber)(foe, "$slice arg3 ", import_internal2.INT_OPTS.int); - if ((0, import_util3.isNil)(limit)) { - if (skip < 0) { - skip = Math.max(0, arr.length + skip); - } else { - limit = skip; - skip = 0; - } - } else { - if (skip < 0) { - skip = Math.max(0, arr.length + skip); - } - if (limit < 1) { - return (0, import_internal2.errExpectNumber)(foe, "$slice arg3 ", import_internal2.INT_OPTS.pos); - } - limit += skip; - } - return arr.slice(skip, limit); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/sortArray.js -var require_sortArray = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/sortArray.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sortArray_exports = {}; - __export5(sortArray_exports, { - $sortArray: () => $sortArray - }); - module.exports = __toCommonJS(sortArray_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - var import_sort = require_sort(); - var import_internal2 = require_internal4(); - var $sortArray = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && "input" in expr && "sortBy" in expr, - "$sortArray expects object { input, sortBy }" - ); - const { input, sortBy } = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(input)) return null; - if (!(0, import_util3.isArray)(input)) - return (0, import_internal2.errExpectArray)(options.failOnError, "$sortArray 'input'"); - if ((0, import_util3.isObject)(sortBy)) { - return (0, import_sort.$sort)((0, import_lazy.Lazy)(input), sortBy, options).collect(); - } - const result = input.slice().sort(import_util3.compare); - if (sortBy === -1) result.reverse(); - return result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/zip.js -var require_zip = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/zip.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var zip_exports = {}; - __export5(zip_exports, { - $zip: () => $zip - }); - module.exports = __toCommonJS(zip_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $zip = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "inputs"), - "$zip received invalid arguments" - ); - const inputs = (0, import_internal.evalExpr)(obj, expr.inputs, options); - const defaults = (0, import_internal.evalExpr)(obj, expr.defaults, options) ?? []; - const useLongestLength = expr.useLongestLength ?? false; - const foe = options.failOnError; - if ((0, import_util3.isNil)(inputs)) return null; - if (!(0, import_util3.isArray)(inputs)) return (0, import_internal2.errExpectArray)(foe, "$zip 'inputs'"); - let invalid = 0; - for (const elem of inputs) { - if ((0, import_util3.isNil)(elem)) return null; - if (!(0, import_util3.isArray)(elem)) invalid++; - } - if (invalid) return (0, import_internal2.errExpectArray)(foe, "$zip elements of 'inputs'"); - if (!(0, import_util3.isBoolean)(useLongestLength)) - (0, import_internal2.errInvalidArgs)(foe, "$zip 'useLongestLength' must be boolean"); - if ((0, import_util3.isArray)(defaults) && defaults.length > 0) { - (0, import_util3.assert)( - useLongestLength && defaults.length === inputs.length, - "$zip 'useLongestLength' must be set to true to use 'defaults'" - ); - } - let zipCount = 0; - for (const arr of inputs) { - zipCount = useLongestLength ? Math.max(zipCount, arr.length) : Math.min(zipCount || arr.length, arr.length); - } - const result = []; - for (let i = 0; i < zipCount; i++) { - const temp = inputs.map((val, index) => { - return (0, import_util3.isNil)(val[i]) ? defaults[index] ?? null : val[i]; - }); - result.push(temp); - } - return result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/index.js -var require_array = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var array_exports = {}; - module.exports = __toCommonJS(array_exports); - __reExport(array_exports, require_arrayElemAt(), module.exports); - __reExport(array_exports, require_arrayToObject(), module.exports); - __reExport(array_exports, require_concatArrays(), module.exports); - __reExport(array_exports, require_filter(), module.exports); - __reExport(array_exports, require_first2(), module.exports); - __reExport(array_exports, require_firstN2(), module.exports); - __reExport(array_exports, require_in(), module.exports); - __reExport(array_exports, require_indexOfArray(), module.exports); - __reExport(array_exports, require_isArray(), module.exports); - __reExport(array_exports, require_last2(), module.exports); - __reExport(array_exports, require_lastN2(), module.exports); - __reExport(array_exports, require_map(), module.exports); - __reExport(array_exports, require_maxN2(), module.exports); - __reExport(array_exports, require_minN2(), module.exports); - __reExport(array_exports, require_range(), module.exports); - __reExport(array_exports, require_reduce(), module.exports); - __reExport(array_exports, require_reverseArray(), module.exports); - __reExport(array_exports, require_size(), module.exports); - __reExport(array_exports, require_slice(), module.exports); - __reExport(array_exports, require_sortArray(), module.exports); - __reExport(array_exports, require_zip(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/_internal.js -var require_internal6 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - processBitwise: () => processBitwise - }); - module.exports = __toCommonJS(internal_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - function processBitwise(obj, expr, options, operator, fn) { - (0, import_util3.assert)((0, import_util3.isArray)(expr), `${operator} expects array as argument`); - const nums = (0, import_internal.evalExpr)(obj, expr, options); - let t_num = true; - for (const v of nums) { - if ((0, import_util3.isNil)(v)) return null; - t_num && (t_num = (0, import_util3.isInteger)(v)); - } - if (t_num) return fn(nums); - return (0, import_internal2.errInvalidArgs)( - options.failOnError, - `${operator} array elements must resolve to integers` - ); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitAnd.js -var require_bitAnd = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitAnd.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitAnd_exports = {}; - __export5(bitAnd_exports, { - $bitAnd: () => $bitAnd - }); - module.exports = __toCommonJS(bitAnd_exports); - var import_internal = require_internal6(); - var $bitAnd = (obj, expr, options) => (0, import_internal.processBitwise)( - obj, - expr, - options, - "$bitAnd", - (nums) => nums.reduce((a, b) => a & b, -1) - ); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitNot.js -var require_bitNot = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitNot.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitNot_exports = {}; - __export5(bitNot_exports, { - $bitNot: () => $bitNot - }); - module.exports = __toCommonJS(bitNot_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $bitNot = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(n)) return null; - if (!(0, import_util3.isInteger)(n)) - return (0, import_internal2.errExpectNumber)(options.failOnError, "$bitNot", import_internal2.INT_OPTS.int); - return ~n; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitOr.js -var require_bitOr = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitOr.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitOr_exports = {}; - __export5(bitOr_exports, { - $bitOr: () => $bitOr - }); - module.exports = __toCommonJS(bitOr_exports); - var import_internal = require_internal6(); - var $bitOr = (obj, expr, options) => (0, import_internal.processBitwise)( - obj, - expr, - options, - "$bitOr", - (nums) => nums.reduce((a, b) => a | b, 0) - ); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitXor.js -var require_bitXor = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitXor.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitXor_exports = {}; - __export5(bitXor_exports, { - $bitXor: () => $bitXor - }); - module.exports = __toCommonJS(bitXor_exports); - var import_internal = require_internal6(); - var $bitXor = (obj, expr, options) => (0, import_internal.processBitwise)( - obj, - expr, - options, - "$bitXor", - (nums) => nums.reduce((a, b) => a ^ b, 0) - ); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/index.js -var require_bitwise = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitwise_exports = {}; - module.exports = __toCommonJS(bitwise_exports); - __reExport(bitwise_exports, require_bitAnd(), module.exports); - __reExport(bitwise_exports, require_bitNot(), module.exports); - __reExport(bitwise_exports, require_bitOr(), module.exports); - __reExport(bitwise_exports, require_bitXor(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/and.js -var require_and = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/and.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var and_exports = {}; - __export5(and_exports, { - $and: () => $and - }); - module.exports = __toCommonJS(and_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var $and = (obj, expr, options) => { - (0, import_internal2.assert)((0, import_internal2.isArray)(expr), "$and expects array"); - const mode = options.useStrictMode; - return expr.every((e) => (0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, e, options), mode)); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/not.js -var require_not = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/not.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var not_exports = {}; - __export5(not_exports, { - $not: () => $not - }); - module.exports = __toCommonJS(not_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $not = (obj, expr, options) => { - const booleanExpr = (0, import_util3.ensureArray)(expr); - if (booleanExpr.length === 0) return false; - if (booleanExpr.length > 1) - return (0, import_internal2.errExpectArray)(options.failOnError, "$not", { size: 1 }); - return !(0, import_internal.evalExpr)(obj, booleanExpr[0], options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/or.js -var require_or = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/or.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var or_exports = {}; - __export5(or_exports, { - $or: () => $or - }); - module.exports = __toCommonJS(or_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var $or = (obj, expr, options) => { - (0, import_internal2.assert)((0, import_internal2.isArray)(expr), "$or expects array of expressions"); - const strict = options.useStrictMode; - for (const v of expr) - if ((0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, v, options), strict)) return true; - return false; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/index.js -var require_boolean = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var boolean_exports = {}; - module.exports = __toCommonJS(boolean_exports); - __reExport(boolean_exports, require_and(), module.exports); - __reExport(boolean_exports, require_not(), module.exports); - __reExport(boolean_exports, require_or(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/cmp.js -var require_cmp = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/cmp.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var cmp_exports = {}; - __export5(cmp_exports, { - $cmp: () => $cmp - }); - module.exports = __toCommonJS(cmp_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $cmp = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, "$cmp expects array(2)"); - const [a, b] = (0, import_internal.evalExpr)(obj, expr, options); - return (0, import_util3.compare)(a, b); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/limit.js -var require_limit = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/limit.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var limit_exports = {}; - __export5(limit_exports, { - $limit: () => $limit - }); - module.exports = __toCommonJS(limit_exports); - function $limit(coll, expr, _options2) { - return coll.take(expr); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/documents.js -var require_documents = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/documents.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var documents_exports = {}; - __export5(documents_exports, { - $documents: () => $documents - }); - module.exports = __toCommonJS(documents_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - function $documents(_, expr, options) { - const docs = (0, import_internal.evalExpr)(null, expr, options); - (0, import_util3.assert)((0, import_util3.isArray)(docs), "$documents expression must resolve to an array."); - const iter = (0, import_lazy.Lazy)(docs); - const mode = options.processingMode; - return mode & import_internal.ProcessingMode.CLONE_ALL ? iter.map((o) => (0, import_util3.cloneDeep)(o)) : iter; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/_internal.js -var require_internal7 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - filterDocumentsStage: () => filterDocumentsStage, - resolveCollection: () => resolveCollection, - validateProjection: () => validateProjection - }); - module.exports = __toCommonJS(internal_exports); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - var import_internal = require_internal(); - var import_documents = require_documents(); - var EMPTY = (0, import_lazy.Lazy)([]); - function filterDocumentsStage(pipeline, options) { - if (!pipeline) return {}; - const docs = pipeline[0]?.$documents; - if (!docs) return { pipeline }; - return { - documents: (0, import_documents.$documents)(EMPTY, docs, options).collect(), - pipeline: pipeline.slice(1) - }; - } - function validateProjection(expr, options, isRoot = true) { - const res = { - exclusions: [], - inclusions: [], - positional: 0 - }; - const keys = Object.keys(expr); - (0, import_internal.assert)(keys.length, "Invalid empty sub-projection"); - const idKey = options?.idKey; - let idKeyExcluded = false; - for (const k of keys) { - if (k.startsWith("$")) { - (0, import_internal.assert)( - !isRoot && keys.length === 1, - `FieldPath field names may not start with '$', given '${k}'.` - ); - return res; - } - if (k.endsWith(".$")) res.positional++; - const v = expr[k]; - if (v === false || (0, import_util3.isNumber)(v) && v === 0) { - if (k === idKey) { - idKeyExcluded = true; - } else res.exclusions.push(k); - } else if (!(0, import_util3.isObject)(v)) { - res.inclusions.push(k); - } else { - const meta3 = validateProjection(v, options, false); - if (!meta3.inclusions.length && !meta3.exclusions.length) { - if (!res.inclusions.includes(k)) res.inclusions.push(k); - } else { - for (const n of meta3.exclusions) res.exclusions.push(`${k}.${n}`); - for (const n of meta3.inclusions) res.inclusions.push(`${k}.${n}`); - } - res.positional += meta3.positional; - } - (0, import_internal.assert)( - !(res.exclusions.length && res.inclusions.length), - "Cannot do exclusion and inclusion in projection." - ); - (0, import_internal.assert)( - res.positional <= 1, - "Cannot specify more than one positional projection." - ); - } - if (idKeyExcluded) { - res.exclusions.push(idKey); - } - if (isRoot) { - const p = new import_internal.PathValidator(); - for (const k of res.exclusions) (0, import_internal.assert)(p.add(k), `Path collision at ${k}.`); - for (const k of res.inclusions) (0, import_internal.assert)(p.add(k), `Path collision at ${k}.`); - res.exclusions.sort(); - res.inclusions.sort(); - } - return res; - } - function resolveCollection(op, expr, options) { - if ((0, import_internal.isString)(expr)) { - (0, import_internal.assert)( - options.collectionResolver, - `${op} requires 'collectionResolver' option to resolve named collection` - ); - } - const coll = (0, import_internal.isString)(expr) ? options.collectionResolver(expr) : expr; - (0, import_internal.assert)((0, import_internal.isArray)(coll), `${op} could not resolve input collection`); - return coll; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/project.js -var require_project = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/project.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var project_exports = {}; - __export5(project_exports, { - $project: () => $project - }); - module.exports = __toCommonJS(project_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var import_internal3 = require_internal7(); - var OP = "$project"; - function $project(coll, expr, options) { - if ((0, import_internal2.isEmpty)(expr)) return coll; - const meta3 = (0, import_internal3.validateProjection)(expr, options); - const handler = createHandler(expr, import_internal.ComputeOptions.init(options), meta3); - return coll.map(handler); - } - function createHandler(expr, options, meta3) { - const idKey = options.idKey; - const { exclusions, inclusions } = meta3; - const handlers = {}; - const resolveOpts = { - preserveMissing: true - }; - for (const k of exclusions) { - handlers[k] = (t, _) => { - (0, import_internal2.removeValue)(t, k, { descendArray: true }); - }; - } - for (const selector of inclusions) { - const v = (0, import_internal2.resolve)(expr, selector) ?? expr[selector]; - if (selector.endsWith(".$") && v === 1) { - const cond = options?.local?.condition ?? {}; - (0, import_internal2.assert)(cond, `${OP}: positional operator '.$' requires array condition.`); - const field = selector.slice(0, -2); - handlers[field] = getPositionalFilter(field, cond, options); - continue; - } - if ((0, import_internal2.isArray)(v)) { - handlers[selector] = (t, o) => { - options.update({ root: o }); - const newVal = v.map((e) => (0, import_internal.evalExpr)(o, e, options) ?? null); - (0, import_internal2.setValue)(t, selector, newVal); - }; - } else if ((0, import_internal2.isNumber)(v) || v === true) { - handlers[selector] = (t, o) => { - options.update({ root: o }); - const extractedVal = (0, import_internal2.resolveGraph)(o, selector, resolveOpts); - mergeInto(t, extractedVal); - }; - } else if (!(0, import_internal2.isObject)(v)) { - handlers[selector] = (t, o) => { - options.update({ root: o }); - const newVal = (0, import_internal.evalExpr)(o, v, options); - (0, import_internal2.setValue)(t, selector, newVal); - }; - } else { - const opKeys = Object.keys(v); - (0, import_internal2.assert)( - opKeys.length === 1 && (0, import_internal2.isOperator)(opKeys[0]), - "Not a valid operator" - ); - const operator = opKeys[0]; - const opExpr = v[operator]; - const fn = options.context.getOperator(import_internal.OpType.PROJECTION, operator); - const foundSlice = operator === "$slice"; - if (!fn || foundSlice && !(0, import_internal2.ensureArray)(opExpr).every(import_internal2.isNumber)) { - handlers[selector] = (t, o) => { - options.update({ root: o }); - const newval = (0, import_internal.evalExpr)(o, v, options); - (0, import_internal2.setValue)(t, selector, newval); - }; - } else { - handlers[selector] = (t, o) => { - options.update({ root: o }); - const newval = fn(o, opExpr, selector, options); - (0, import_internal2.setValue)(t, selector, newval); - }; - } - } - } - const onlyIdKeyExcluded = exclusions.length === 1 && exclusions.includes(idKey); - const noIdKeyExcluded = !exclusions.includes(idKey); - const noInclusions = !inclusions.length; - const allKeysIncluded = noInclusions && onlyIdKeyExcluded || noInclusions && exclusions.length && !onlyIdKeyExcluded; - return (o) => { - const newObj = {}; - if (allKeysIncluded) Object.assign(newObj, o); - for (const k in handlers) { - handlers[k](newObj, o); - } - if (!noInclusions) (0, import_internal2.filterMissing)(newObj); - if (noIdKeyExcluded && !(0, import_internal2.has)(newObj, idKey) && (0, import_internal2.has)(o, idKey)) { - newObj[idKey] = (0, import_internal2.resolve)(o, idKey); - } - return newObj; - }; - } - var findMatches = (o, key, leaf, pred) => { - let arr = (0, import_internal2.resolve)(o, key); - if (!(0, import_internal2.isArray)(arr)) arr = (0, import_internal2.resolve)(arr, leaf); - (0, import_internal2.assert)((0, import_internal2.isArray)(arr), `${OP}: field '${key}' must resolve to array`); - const matches = []; - for (let i = 0; i < arr.length; i++) { - if (pred({ [leaf]: [arr[i]] })) matches.push(i); - } - return matches; - }; - var complement = (p) => (e) => !p(e); - var COMPOUND_OPS = { $and: 1, $or: 1, $nor: 1 }; - function getPositionalFilter(field, condition, options) { - const stack = Object.entries(condition).slice(); - const selectors = { - $and: [], - $or: [] - }; - for (let i = 0; i < stack.length; i++) { - const [key, val, op] = stack[i]; - if (key === field || key.startsWith(field + ".")) { - const normalizedExpr = (0, import_internal2.normalize)(val); - const operator = Object.keys(normalizedExpr)[0]; - const expr = normalizedExpr[operator]; - const fn = options.context.getOperator( - import_internal.OpType.QUERY, - operator - ); - const leaf2 = key.substring(key.lastIndexOf(".") + 1); - const pred = fn(leaf2, expr, options); - if (!op || op === "$and") { - selectors.$and.push([key, pred, leaf2]); - } else if (op === "$nor") { - selectors.$and.push([key, complement(pred), leaf2]); - } else if (op === "$or") { - selectors.$or.push([key, pred, leaf2]); - } - } else if ((0, import_internal2.isOperator)(key)) { - (0, import_internal2.assert)( - !!COMPOUND_OPS[key], - `${OP}: '${key}' is not allowed in this context` - ); - for (const item of val) { - for (const k of Object.keys(item)) stack.push([k, item[k], key]); - } - } - } - const sep = field.lastIndexOf("."); - const parent = field.substring(0, sep) || field; - const leaf = field.substring(sep + 1); - return (t, o) => { - const matches = []; - for (const [key, pred, leaf2] of selectors.$and) { - matches.push(findMatches(o, key, leaf2, pred)); - } - if (selectors.$or.length) { - const orMatches = []; - for (const [key, pred, leaf2] of selectors.$or) { - orMatches.push(...findMatches(o, key, leaf2, pred)); - } - matches.push((0, import_internal2.unique)(orMatches)); - } - const i = (0, import_internal2.intersection)(matches).sort()[0]; - let first = (0, import_internal2.resolve)(o, field)[i]; - if (parent != leaf && !(0, import_internal2.isObject)(first)) { - first = { [leaf]: first }; - } - (0, import_internal2.setValue)(t, parent, [first]); - }; - } - function mergeInto(target, input) { - if (target === import_internal2.MISSING || (0, import_internal2.isNil)(target)) return input; - if ((0, import_internal2.isNil)(input)) return target; - const out = target; - const src = input; - for (const k of Object.keys(input)) { - out[k] = mergeInto(out[k], src[k]); - } - return out; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/skip.js -var require_skip = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/skip.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var skip_exports = {}; - __export5(skip_exports, { - $skip: () => $skip - }); - module.exports = __toCommonJS(skip_exports); - var import_util3 = require_util(); - function $skip(coll, expr, _options2) { - (0, import_util3.assert)(expr >= 0, "$skip value must be a non-negative integer"); - return coll.drop(expr); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/cursor.js -var require_cursor = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/cursor.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var cursor_exports = {}; - __export5(cursor_exports, { - Cursor: () => Cursor - }); - module.exports = __toCommonJS(cursor_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_limit = require_limit(); - var import_project = require_project(); - var import_skip = require_skip(); - var import_sort = require_sort(); - var import_util3 = require_util(); - var OPERATORS2 = { $sort: import_sort.$sort, $skip: import_skip.$skip, $limit: import_limit.$limit }; - var _source, _predicate, _projection, _options2, _operators, _result, _buffer; - var Cursor = class { - /** - * Creates an instance of the Cursor class. - * - * @param source - The source of data to be iterated over. - * @param predicate - A function or condition to filter the data. - * @param projection - An object specifying the fields to include or exclude in the result. - * @param options - Optional settings to customize the behavior of the cursor. - */ - constructor(source, predicate, projection, options) { - __privateAdd(this, _source); - __privateAdd(this, _predicate); - __privateAdd(this, _projection); - __privateAdd(this, _options2); - __privateAdd(this, _operators, {}); - __privateAdd(this, _result, null); - __privateAdd(this, _buffer, []); - __privateSet(this, _source, source); - __privateSet(this, _predicate, predicate); - __privateSet(this, _projection, projection); - __privateSet(this, _options2, options); - } - /** Returns the iterator from running the query */ - fetch() { - if (__privateGet(this, _result)) return __privateGet(this, _result); - __privateSet(this, _result, (0, import_lazy.Lazy)(__privateGet(this, _source)).filter(__privateGet(this, _predicate))); - const mode = __privateGet(this, _options2).processingMode; - if (mode & import_internal.ProcessingMode.CLONE_INPUT) __privateGet(this, _result).map((o) => (0, import_util3.cloneDeep)(o)); - for (const op of Object.keys(OPERATORS2)) { - if ((0, import_util3.has)(__privateGet(this, _operators), op)) { - const f = OPERATORS2[op]; - __privateSet(this, _result, f(__privateGet(this, _result), __privateGet(this, _operators)[op], __privateGet(this, _options2))); - } - } - if (Object.keys(__privateGet(this, _projection)).length) { - __privateSet(this, _result, (0, import_project.$project)(__privateGet(this, _result), __privateGet(this, _projection), __privateGet(this, _options2))); - } - if (mode & import_internal.ProcessingMode.CLONE_OUTPUT) __privateGet(this, _result).map((o) => (0, import_util3.cloneDeep)(o)); - return __privateGet(this, _result); - } - /** Returns an iterator with the buffered data included */ - fetchAll() { - const buffered = (0, import_lazy.Lazy)(Array.from(__privateGet(this, _buffer))); - __privateGet(this, _buffer).length = 0; - return (0, import_lazy.concat)(buffered, this.fetch()); - } - /** - * Return remaining objects in the cursor as an array. This method exhausts the cursor - * @returns {Array} - */ - all() { - return this.fetchAll().collect(); - } - /** - * Returns a cursor that begins returning results only after passing or skipping a number of documents. - * @param {Number} n the number of results to skip. - * @return {Cursor} Returns the cursor, so you can chain this call. - */ - skip(n) { - __privateGet(this, _operators)["$skip"] = n; - return this; - } - /** - * Limits the number of items returned by the cursor. - * - * @param n - The maximum number of items to return. - * @returns The current cursor instance for chaining. - */ - limit(n) { - __privateGet(this, _operators)["$limit"] = n; - return this; - } - /** - * Returns results ordered according to a sort specification. - * @param {AnyObject} modifier an object of key and values specifying the sort order. 1 for ascending and -1 for descending - * @return {Cursor} Returns the cursor, so you can chain this call. - */ - sort(modifier) { - __privateGet(this, _operators)["$sort"] = modifier; - return this; - } - /** - * Sets the collation options for the cursor. - * Collation allows users to specify language-specific rules for string comparison, - * such as case sensitivity and accent marks. - * - * @param spec - The collation specification to apply. - * @returns The current cursor instance for chaining. - */ - collation(spec) { - __privateSet(this, _options2, { ...__privateGet(this, _options2), collation: spec }); - return this; - } - /** - * Retrieves the next item in the cursor. - */ - next() { - if (__privateGet(this, _buffer).length > 0) { - return __privateGet(this, _buffer).pop(); - } - const o = this.fetch().next(); - if (o.done) return void 0; - return o.value; - } - /** - * Determines if there are more elements available in the cursor. - * - * @returns {boolean} `true` if there are more elements to iterate over, otherwise `false`. - */ - hasNext() { - if (__privateGet(this, _buffer).length > 0) return true; - const o = this.fetch().next(); - if (o.done) return false; - __privateGet(this, _buffer).push(o.value); - return true; - } - /** - * Returns an iterator for the cursor, allowing it to be used in `for...of` loops. - * The iterator fetches all the results from the cursor. - * - * @returns {Iterator} An iterator over the fetched results. - */ - [Symbol.iterator]() { - return this.fetchAll(); - } - }; - _source = new WeakMap(); - _predicate = new WeakMap(); - _projection = new WeakMap(); - _options2 = new WeakMap(); - _operators = new WeakMap(); - _result = new WeakMap(); - _buffer = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/query.js -var require_query = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/query.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var query_exports = {}; - __export5(query_exports, { - Query: () => Query2 - }); - module.exports = __toCommonJS(query_exports); - var import_internal = require_internal2(); - var import_cursor = require_cursor(); - var import_util3 = require_util(); - var TOP_LEVEL_OPS = /* @__PURE__ */ new Set(["$and", "$or", "$nor", "$expr", "$jsonSchema"]); - var _compiled, _condition, _options2; - var Query2 = class { - /** - * Creates an instance of the query with the specified condition and options. - * This object is preloaded with all query and projection operators. - * - * @param condition - The query condition object used to define the criteria for matching documents. - * @param options - Optional configuration settings to customize the query behavior. - */ - constructor(condition, options) { - __privateAdd(this, _compiled); - __privateAdd(this, _condition); - __privateAdd(this, _options2); - __privateSet(this, _condition, (0, import_util3.cloneDeep)(condition)); - __privateSet(this, _options2, import_internal.ComputeOptions.init(options).update({ - condition - })); - __privateSet(this, _compiled, []); - this.compile(); - } - compile() { - (0, import_util3.assert)( - (0, import_util3.isObject)(__privateGet(this, _condition)), - `query criteria must be an object: ${JSON.stringify(__privateGet(this, _condition))}` - ); - const whereOperator = {}; - for (const field of Object.keys(__privateGet(this, _condition))) { - const expr = __privateGet(this, _condition)[field]; - if ("$where" === field) { - (0, import_util3.assert)( - __privateGet(this, _options2).scriptEnabled, - "$where operator requires 'scriptEnabled' option to be true." - ); - Object.assign(whereOperator, { field, expr }); - } else if (TOP_LEVEL_OPS.has(field)) { - this.processOperator(field, field, expr); - } else { - (0, import_util3.assert)(!(0, import_util3.isOperator)(field), `unknown top level operator: ${field}`); - const normalizedExpr = (0, import_util3.normalize)(expr); - for (const operator of Object.keys(normalizedExpr)) { - this.processOperator(field, operator, normalizedExpr[operator]); - } - } - if (whereOperator.field) { - this.processOperator( - whereOperator.field, - whereOperator.field, - whereOperator.expr - ); - } - } - } - processOperator(field, operator, value) { - const fn = __privateGet(this, _options2).context.getOperator( - import_internal.OpType.QUERY, - operator - ); - (0, import_util3.assert)(!!fn, `unknown query operator ${operator}`); - __privateGet(this, _compiled).push(fn(field, value, __privateGet(this, _options2))); - } - /** - * Tests whether the given object satisfies all compiled predicates. - * - * @template T - The type of the object to test. - * @param obj - The object to be tested against the compiled predicates. - * @returns `true` if the object satisfies all predicates, otherwise `false`. - */ - test(obj) { - return __privateGet(this, _compiled).every((p) => p(obj)); - } - /** - * Returns a cursor for iterating over the items in the given collection that match the query criteria. - * - * @typeParam T - The type of the items in the resulting cursor. - * @param collection - The source collection to search through. - * @param projection - An optional object specifying fields to include or exclude - * in the returned items. - * @returns A `Cursor` instance for iterating over the matching items. - */ - find(collection, projection) { - return new import_cursor.Cursor( - collection, - (o) => this.test(o), - projection || {}, - __privateGet(this, _options2) - ); - } - }; - _compiled = new WeakMap(); - _condition = new WeakMap(); - _options2 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/_predicates.js -var require_predicates = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/_predicates.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var predicates_exports = {}; - __export5(predicates_exports, { - $all: () => $all, - $elemMatch: () => $elemMatch, - $eq: () => $eq2, - $gt: () => $gt2, - $gte: () => $gte2, - $in: () => $in2, - $lt: () => $lt2, - $lte: () => $lte2, - $mod: () => $mod, - $ne: () => $ne2, - $nin: () => $nin2, - $regex: () => $regex, - $size: () => $size, - $type: () => $type, - processExpression: () => processExpression, - processQuery: () => processQuery - }); - module.exports = __toCommonJS(predicates_exports); - var import_internal = require_internal2(); - var import_query = require_query(); - var import_internal2 = require_internal(); - function elemMatchPredicate(criteria, options) { - let format = (x) => x; - let wrap4 = true; - for (const k of Object.keys(criteria)) { - wrap4 && (wrap4 = (0, import_internal2.isOperator)(k) && "$and" !== k && "$or" !== k && "$nor" !== k); - if (!wrap4) break; - } - if (wrap4) { - criteria = { field: criteria }; - format = (x) => ({ field: x }); - } - const q = new import_query.Query(criteria, options); - return (v) => q.test(format(v)); - } - function processQuery(selector, value, options, predicate) { - const pathArray = selector.split("."); - const depth = Math.max(1, pathArray.length - 1); - const copts = import_internal.ComputeOptions.init(options).update({ depth }); - const opts = { unwrapArray: true, pathArray }; - if (predicate === $elemMatch) { - value = elemMatchPredicate(value, options); - } - return (o) => { - const lhs = (0, import_internal2.resolve)(o, selector, opts); - return predicate(lhs, value, copts); - }; - } - function processExpression(obj, expr, options, predicate) { - (0, import_internal2.assert)( - (0, import_internal2.isArray)(expr) && expr.length === 2, - `${predicate.name} expects array(2)` - ); - const [lhs, rhs] = (0, import_internal.evalExpr)(obj, expr, options); - return predicate(lhs, rhs, options); - } - function $eq2(a, b, options) { - if ((0, import_internal2.isEqual)(a, b)) return true; - if ((0, import_internal2.isNil)(a) && (0, import_internal2.isNil)(b)) return true; - if ((0, import_internal2.isArray)(a)) { - const depth = options?.local?.depth ?? 1; - return a.some((v) => (0, import_internal2.isEqual)(v, b)) || (0, import_internal2.flatten)(a, depth).some((v) => (0, import_internal2.isEqual)(v, b)); - } - return false; - } - function $ne2(a, b, options) { - return !$eq2(a, b, options); - } - function $in2(a, b, _options2) { - if ((0, import_internal2.isNil)(a)) return b.some((v) => v === null); - return (0, import_internal2.intersection)([(0, import_internal2.ensureArray)(a), b]).length > 0; - } - function $nin2(a, b, options) { - return !$in2(a, b, options); - } - function $lt2(a, b, _options2) { - return compare2(a, b, (x, y) => (0, import_internal2.compare)(x, y) < 0); - } - function $lte2(a, b, _options2) { - return compare2(a, b, (x, y) => (0, import_internal2.compare)(x, y) <= 0); - } - function $gt2(a, b, _options2) { - return compare2(a, b, (x, y) => (0, import_internal2.compare)(x, y) > 0); - } - function $gte2(a, b, _options2) { - return compare2(a, b, (x, y) => (0, import_internal2.compare)(x, y) >= 0); - } - function $mod(a, b, _options2) { - return (0, import_internal2.ensureArray)(a).some( - (x) => b.length === 2 && x % b[0] === b[1] - ); - } - function $regex(a, b, options) { - const lhs = (0, import_internal2.ensureArray)(a); - const match2 = (x) => (0, import_internal2.isString)(x) && (0, import_internal2.truthy)(b.exec(x), options?.useStrictMode); - return lhs.some(match2) || (0, import_internal2.flatten)(lhs, 1).some(match2); - } - function $all(values, rhs, options) { - if (!(0, import_internal2.isArray)(values) || !(0, import_internal2.isArray)(rhs) || !values.length || !rhs.length) { - return false; - } - let matched = true; - for (const expr of rhs) { - if (!matched) break; - if ((0, import_internal2.isObject)(expr) && Object.keys(expr)[0] === "$elemMatch") { - const criteria = expr["$elemMatch"]; - const pred = elemMatchPredicate(criteria, options); - matched = $elemMatch(values, pred, options); - } else if ((0, import_internal2.isRegExp)(expr)) { - matched = values.some((s) => (0, import_internal2.isString)(s) && expr.test(s)); - } else { - matched = values.some((v) => (0, import_internal2.isEqual)(expr, v)); - } - } - return matched; - } - function $size(a, b, _options2) { - return Array.isArray(a) && a.length === b; - } - function $elemMatch(a, b, _options2) { - if ((0, import_internal2.isArray)(a) && !(0, import_internal2.isEmpty)(a)) { - for (let i = 0, len = a.length; i < len; i++) if (b(a[i])) return true; - } - return false; - } - var isNull2 = (a) => a === null; - var compareFuncs = { - array: import_internal2.isArray, - boolean: import_internal2.isBoolean, - bool: import_internal2.isBoolean, - date: import_internal2.isDate, - number: import_internal2.isNumber, - int: import_internal2.isNumber, - long: import_internal2.isNumber, - double: import_internal2.isNumber, - decimal: import_internal2.isNumber, - null: isNull2, - object: import_internal2.isObject, - regexp: import_internal2.isRegExp, - regex: import_internal2.isRegExp, - string: import_internal2.isString, - // added for completeness - undefined: import_internal2.isNil, - // deprecated - // Mongo identifiers - 1: import_internal2.isNumber, - //double - 2: import_internal2.isString, - 3: import_internal2.isObject, - 4: import_internal2.isArray, - 6: import_internal2.isNil, - // deprecated - 8: import_internal2.isBoolean, - 9: import_internal2.isDate, - 10: isNull2, - 11: import_internal2.isRegExp, - 16: import_internal2.isNumber, - //int - 18: import_internal2.isNumber, - //long - 19: import_internal2.isNumber - //decimal - }; - function compareType(a, b, _) { - const f = compareFuncs[b]; - return f ? f(a) : false; - } - function $type(a, b, options) { - return (0, import_internal2.isArray)(b) ? b.findIndex((t) => compareType(a, t, options)) >= 0 : compareType(a, b, options); - } - function compare2(a, b, f) { - for (const v of (0, import_internal2.ensureArray)(a)) { - if ((0, import_internal2.typeOf)(v) === (0, import_internal2.typeOf)(b) && f(v, b)) return true; - } - return false; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/eq.js -var require_eq = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/eq.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var eq_exports = {}; - __export5(eq_exports, { - $eq: () => $eq2 - }); - module.exports = __toCommonJS(eq_exports); - var import_predicates = require_predicates(); - var $eq2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$eq); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gt.js -var require_gt = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gt.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var gt_exports = {}; - __export5(gt_exports, { - $gt: () => $gt2 - }); - module.exports = __toCommonJS(gt_exports); - var import_predicates = require_predicates(); - var $gt2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$gt); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gte.js -var require_gte = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gte.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var gte_exports = {}; - __export5(gte_exports, { - $gte: () => $gte2 - }); - module.exports = __toCommonJS(gte_exports); - var import_predicates = require_predicates(); - var $gte2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$gte); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lt.js -var require_lt = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lt.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var lt_exports = {}; - __export5(lt_exports, { - $lt: () => $lt2 - }); - module.exports = __toCommonJS(lt_exports); - var import_predicates = require_predicates(); - var $lt2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$lt); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lte.js -var require_lte = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lte.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var lte_exports = {}; - __export5(lte_exports, { - $lte: () => $lte2 - }); - module.exports = __toCommonJS(lte_exports); - var import_predicates = require_predicates(); - var $lte2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$lte); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/ne.js -var require_ne = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/ne.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var ne_exports = {}; - __export5(ne_exports, { - $ne: () => $ne2 - }); - module.exports = __toCommonJS(ne_exports); - var import_predicates = require_predicates(); - var $ne2 = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$ne); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/index.js -var require_comparison = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var comparison_exports = {}; - module.exports = __toCommonJS(comparison_exports); - __reExport(comparison_exports, require_cmp(), module.exports); - __reExport(comparison_exports, require_eq(), module.exports); - __reExport(comparison_exports, require_gt(), module.exports); - __reExport(comparison_exports, require_gte(), module.exports); - __reExport(comparison_exports, require_lt(), module.exports); - __reExport(comparison_exports, require_lte(), module.exports); - __reExport(comparison_exports, require_ne(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/cond.js -var require_cond = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/cond.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var cond_exports = {}; - __export5(cond_exports, { - $cond: () => $cond - }); - module.exports = __toCommonJS(cond_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var err = "$cond expects array(3) or object with 'if-then-else' expressions"; - var $cond = (obj, expr, options) => { - let ifExpr; - let thenExpr; - let elseExpr; - if ((0, import_internal2.isArray)(expr)) { - (0, import_internal2.assert)(expr.length === 3, err); - ifExpr = expr[0]; - thenExpr = expr[1]; - elseExpr = expr[2]; - } else { - (0, import_internal2.assert)((0, import_internal2.isObject)(expr), err); - ifExpr = expr.if; - thenExpr = expr.then; - elseExpr = expr.else; - } - const condition = (0, import_internal2.truthy)( - (0, import_internal.evalExpr)(obj, ifExpr, options), - options.useStrictMode - ); - return (0, import_internal.evalExpr)(obj, condition ? thenExpr : elseExpr, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/ifNull.js -var require_ifNull = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/ifNull.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var ifNull_exports = {}; - __export5(ifNull_exports, { - $ifNull: () => $ifNull - }); - module.exports = __toCommonJS(ifNull_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $ifNull = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), "$ifNull expects an array"); - let val = void 0; - for (const input of expr) { - val = (0, import_internal.evalExpr)(obj, input, options); - if (!(0, import_util3.isNil)(val)) return val; - } - return val; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/switch.js -var require_switch = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/switch.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var switch_exports = {}; - __export5(switch_exports, { - $switch: () => $switch - }); - module.exports = __toCommonJS(switch_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var $switch = (obj, expr, options) => { - (0, import_internal2.assert)((0, import_internal2.isObject)(expr), "$switch received invalid arguments"); - for (const { case: caseExpr, then } of expr.branches) { - const condition = (0, import_internal2.truthy)( - (0, import_internal.evalExpr)(obj, caseExpr, options), - options.useStrictMode - ); - if (condition) return (0, import_internal.evalExpr)(obj, then, options); - } - return (0, import_internal.evalExpr)(obj, expr.default, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/index.js -var require_conditional = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var conditional_exports = {}; - module.exports = __toCommonJS(conditional_exports); - __reExport(conditional_exports, require_cond(), module.exports); - __reExport(conditional_exports, require_ifNull(), module.exports); - __reExport(conditional_exports, require_switch(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/function.js -var require_function = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/function.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var function_exports = {}; - __export5(function_exports, { - $function: () => $function - }); - module.exports = __toCommonJS(function_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $function = (obj, expr, options) => { - (0, import_util3.assert)( - options.scriptEnabled, - "$function requires 'scriptEnabled' option to be true" - ); - const fn = (0, import_internal.evalExpr)(obj, expr, options); - return fn.body.apply(null, fn.args); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/index.js -var require_custom = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var custom_exports = {}; - module.exports = __toCommonJS(custom_exports); - __reExport(custom_exports, require_function(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/_internal.js -var require_internal8 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - DATE_FORMAT: () => DATE_FORMAT, - DATE_FORMAT_SEP_RE: () => DATE_FORMAT_SEP_RE, - DATE_FORMAT_SYM_RE: () => DATE_FORMAT_SYM_RE, - DATE_PART_INTERVAL: () => DATE_PART_INTERVAL, - DATE_SYM_TABLE: () => DATE_SYM_TABLE, - DAYS_PER_WEEK: () => DAYS_PER_WEEK, - LEAP_YEAR_REF_POINT: () => LEAP_YEAR_REF_POINT, - MINUTES_PER_HOUR: () => MINUTES_PER_HOUR, - MONTHS: () => MONTHS, - TIMEUNIT_IN_MILLIS: () => TIMEUNIT_IN_MILLIS, - TIME_UNITS: () => TIME_UNITS, - adjustDate: () => adjustDate, - computeDate: () => computeDate, - dateAdd: () => dateAdd, - dateDiffDay: () => dateDiffDay, - dateDiffHour: () => dateDiffHour, - dateDiffMonth: () => dateDiffMonth, - dateDiffQuarter: () => dateDiffQuarter, - dateDiffWeek: () => dateDiffWeek, - dateDiffYear: () => dateDiffYear, - dayOfYear: () => dayOfYear, - daysBetweenYears: () => daysBetweenYears, - formatTimezone: () => formatTimezone, - isDST: () => isDST, - isLeapYear: () => isLeapYear, - isoWeek: () => isoWeek, - isoWeekYear: () => isoWeekYear, - isoWeekday: () => isoWeekday, - padDigits: () => padDigits, - parseTimezone: () => parseTimezone, - weekOfYear: () => weekOfYear - }); - module.exports = __toCommonJS(internal_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var TIME_UNITS = [ - "year", - "quarter", - "month", - "week", - "day", - "hour", - "minute", - "second", - "millisecond" - ]; - var ISO_WEEKDAYS = { - mon: 1, - tue: 2, - wed: 3, - thu: 4, - fri: 5, - sat: 6, - sun: 7 - }; - var LEAP_YEAR_REF_POINT = -1e9; - var DAYS_PER_WEEK = 7; - var isLeapYear = (y) => (y & 3) == 0 && (y % 100 != 0 || y % 400 == 0); - function isDST(date5) { - const jan = new Date(date5.getFullYear(), 0, 1).getTimezoneOffset(); - const jul = new Date(date5.getFullYear(), 6, 1).getTimezoneOffset(); - return Math.max(jan, jul) !== date5.getTimezoneOffset(); - } - var DAYS_IN_YEAR = [ - 365, - 366 - /*leap*/ - ]; - var YEAR_DAYS_OFFSET = [ - [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], - [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] - /*leap*/ - ]; - var dayOfYear = (d) => YEAR_DAYS_OFFSET[+isLeapYear(d.getUTCFullYear())][d.getUTCMonth()] + d.getUTCDate(); - var isoWeekday = (date5, startOfWeek) => { - const dow = date5.getUTCDay() || 7; - const name = startOfWeek.toLowerCase().substring(0, 3); - return (dow - ISO_WEEKDAYS[name] + DAYS_PER_WEEK) % DAYS_PER_WEEK; - }; - var p = (y) => (y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400)) % 7; - var weeks = (y) => 52 + Number(p(y) == 4 || p(y - 1) == 3); - function isoWeek(d) { - const dow = d.getUTCDay() || 7; - const w = Math.floor((10 + dayOfYear(d) - dow) / 7); - if (w < 1) return weeks(d.getUTCFullYear() - 1); - if (w > weeks(d.getUTCFullYear())) return 1; - return w; - } - function weekOfYear(d) { - const result = isoWeek(d); - if (d.getUTCDay() > 0 && d.getUTCDate() == 1 && d.getUTCMonth() == 0) - return 0; - if (d.getUTCDay() == 0) return result + 1; - return result; - } - function isoWeekYear(d) { - return d.getUTCFullYear() - Number(d.getUTCMonth() === 0 && d.getUTCDate() == 1 && d.getUTCDay() < 1); - } - var MINUTES_PER_HOUR = 60; - var TIMEUNIT_IN_MILLIS = { - week: 6048e5, - day: 864e5, - hour: 36e5, - minute: 6e4, - second: 1e3, - millisecond: 1 - }; - var DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%LZ"; - var DATE_PART_INTERVAL = [ - ["year", 0, 9999], - ["month", 1, 12], - ["day", 1, 31], - ["hour", 0, 23], - ["minute", 0, 59], - ["second", 0, 59], - ["millisecond", 0, 999] - ]; - var MONTHS = { - jan: 1, - feb: 2, - mar: 3, - apr: 4, - may: 5, - jun: 6, - jul: 7, - aug: 8, - sep: 9, - oct: 10, - nov: 11, - dec: 12 - }; - var DATE_SYM_TABLE = { - "%b": { - name: "abbr_month", - padding: 3, - re: /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i - }, - "%B": { - name: "full_month", - padding: 0, - re: /(January|February|March|April|May|June|July|August|September|October|November|December)/i - }, - "%Y": { name: "year", padding: 4, re: /([0-9]{4})/ }, - "%G": { name: "year", padding: 4, re: /([0-9]{4})/ }, - "%m": { name: "month", padding: 2, re: /(0[1-9]|1[012])/ }, - "%d": { name: "day", padding: 2, re: /(0[1-9]|[12][0-9]|3[01])/ }, - "%j": { - name: "day_of_year", - padding: 3, - re: /(0[0-9][1-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-6])/ - }, - "%H": { name: "hour", padding: 2, re: /([01][0-9]|2[0-3])/ }, - "%M": { name: "minute", padding: 2, re: /([0-5][0-9])/ }, - "%S": { name: "second", padding: 2, re: /([0-5][0-9]|60)/ }, - "%L": { name: "millisecond", padding: 3, re: /([0-9]{3})/ }, - "%w": { name: "day_of_week", padding: 1, re: /([0-6])/ }, - "%u": { name: "day_of_week_iso", padding: 1, re: /([1-7])/ }, - "%U": { name: "week_of_year", padding: 2, re: /([1-4][0-9]?|5[0-3]?)/ }, - "%V": { name: "week_of_year_iso", padding: 2, re: /([1-4][0-9]?|5[0-3]?)/ }, - "%z": { - name: "timezone", - padding: 2, - re: /(([+-][01][0-9]|2[0-3]):?([0-5][0-9])?)/ - }, - "%Z": { name: "minute_offset", padding: 3, re: /([+-][0-9]{3})/ }, - "%%": { name: "percent_literal", padding: 1, re: /%%/ } - }; - var DATE_FORMAT_SYM_RE = /(%[bBYGmdjHMSLwuUVzZ%])/g; - var DATE_FORMAT_SEP_RE = /%[bBYGmdjHMSLwuUVzZ%]/; - var TIMEZONE_RE = /^[a-zA-Z_]+\/[a-zA-Z_]+$/; - function parseTimezone(timeZone, date5) { - if (timeZone === void 0) return 0; - if (TIMEZONE_RE.test(timeZone)) { - const utcDate = new Date(date5.toLocaleString("en-US", { timeZone: "UTC" })); - const tzDate = new Date(date5.toLocaleString("en-US", { timeZone })); - return Math.round((tzDate.getTime() - utcDate.getTime()) / 6e4); - } - const match2 = DATE_SYM_TABLE["%z"].re.exec(timeZone) ?? []; - (0, import_util3.assert)(!!match2, `timezone '${timeZone}' is invalid or not supported.`); - const hr = parseInt(match2[2]) || 0; - const min = parseInt(match2[3]) || 0; - return (Math.abs(hr * MINUTES_PER_HOUR) + min) * (hr < 0 ? -1 : 1); - } - function formatTimezone(minuteOffset) { - return (minuteOffset < 0 ? "-" : "+") + padDigits(Math.abs(Math.floor(minuteOffset / MINUTES_PER_HOUR)), 2) + padDigits(Math.abs(minuteOffset) % MINUTES_PER_HOUR, 2); - } - function adjustDate(d, minuteOffset) { - d.setUTCMinutes(d.getUTCMinutes() + minuteOffset); - } - function computeDate(obj, expr, options) { - if ((0, import_util3.isDate)(obj)) return obj; - const d = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isDate)(d)) return new Date(d); - if ((0, import_util3.isNumber)(d)) return new Date(d * 1e3); - (0, import_util3.assert)(!!d?.date, `cannot convert ${JSON.stringify(expr)} to date`); - const date5 = (0, import_util3.isDate)(d.date) ? new Date(d.date) : new Date(d.date * 1e3); - if (d.timezone) adjustDate(date5, parseTimezone(d.timezone, date5)); - return date5; - } - function padDigits(n, digits) { - return new Array(Math.max(digits - String(n).length + 1, 0)).join("0") + n.toString(); - } - var leapYearsSinceReferencePoint = (year2) => { - const yearsSinceReferencePoint = year2 - LEAP_YEAR_REF_POINT; - return Math.trunc(yearsSinceReferencePoint / 4) - Math.trunc(yearsSinceReferencePoint / 100) + Math.trunc(yearsSinceReferencePoint / 400); - }; - function daysBetweenYears(startYear, endYear) { - return Math.trunc( - leapYearsSinceReferencePoint(endYear - 1) - leapYearsSinceReferencePoint(startYear - 1) + (endYear - startYear) * DAYS_IN_YEAR[0] - ); - } - var dateDiffYear = (start, end) => end.getUTCFullYear() - start.getUTCFullYear(); - var dateDiffMonth = (start, end) => end.getUTCMonth() - start.getUTCMonth() + dateDiffYear(start, end) * 12; - var dateDiffQuarter = (start, end) => { - const a = Math.trunc(start.getUTCMonth() / 3); - const b = Math.trunc(end.getUTCMonth() / 3); - return b - a + dateDiffYear(start, end) * 4; - }; - var dateDiffDay = (start, end) => dayOfYear(end) - dayOfYear(start) + daysBetweenYears(start.getUTCFullYear(), end.getUTCFullYear()); - var dateDiffWeek = (start, end, startOfWeek) => { - const wk = (startOfWeek || "sun").substring(0, 3); - return Math.trunc( - (dateDiffDay(start, end) + isoWeekday(start, wk) - isoWeekday(end, wk)) / DAYS_PER_WEEK - ); - }; - var dateDiffHour = (start, end) => end.getUTCHours() - start.getUTCHours() + dateDiffDay(start, end) * 24; - var addMonth = (d, amount) => { - const m = d.getUTCMonth() + amount; - const yearOffset = Math.floor(m / 12); - if (m < 0) { - const month = m % 12 + 12; - d.setUTCFullYear(d.getUTCFullYear() + yearOffset, month, d.getUTCDate()); - } else { - d.setUTCFullYear(d.getUTCFullYear() + yearOffset, m % 12, d.getUTCDate()); - } - }; - var dateAdd = (date5, unit, amount, _timezone) => { - const d = new Date(date5); - switch (unit) { - case "year": - d.setUTCFullYear(d.getUTCFullYear() + amount); - break; - case "quarter": - addMonth(d, 3 * amount); - break; - case "month": - addMonth(d, amount); - break; - default: - d.setTime(d.getTime() + TIMEUNIT_IN_MILLIS[unit] * amount); - } - return d; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateAdd.js -var require_dateAdd = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateAdd.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dateAdd_exports = {}; - __export5(dateAdd_exports, { - $dateAdd: () => $dateAdd - }); - module.exports = __toCommonJS(dateAdd_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal8(); - var $dateAdd = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - return (0, import_internal2.dateAdd)(args.startDate, args.unit, args.amount, args.timezone); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateDiff.js -var require_dateDiff = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateDiff.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dateDiff_exports = {}; - __export5(dateDiff_exports, { - $dateDiff: () => $dateDiff - }); - module.exports = __toCommonJS(dateDiff_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal8(); - var $dateDiff = (obj, expr, options) => { - const { startDate, endDate, unit, timezone, startOfWeek } = (0, import_internal.evalExpr)( - obj, - expr, - options - ); - const d1 = new Date(startDate); - const d2 = new Date(endDate); - (0, import_internal2.adjustDate)(d1, (0, import_internal2.parseTimezone)(timezone, d1)); - (0, import_internal2.adjustDate)(d2, (0, import_internal2.parseTimezone)(timezone, d2)); - switch (unit) { - case "year": - return (0, import_internal2.dateDiffYear)(d1, d2); - case "quarter": - return (0, import_internal2.dateDiffQuarter)(d1, d2); - case "month": - return (0, import_internal2.dateDiffMonth)(d1, d2); - case "week": - return (0, import_internal2.dateDiffWeek)(d1, d2, startOfWeek); - case "day": - return (0, import_internal2.dateDiffDay)(d1, d2); - case "hour": - return (0, import_internal2.dateDiffHour)(d1, d2); - case "minute": - d1.setUTCSeconds(0); - d1.setUTCMilliseconds(0); - d2.setUTCSeconds(0); - d2.setUTCMilliseconds(0); - return Math.round( - (d2.getTime() - d1.getTime()) / import_internal2.TIMEUNIT_IN_MILLIS[unit] - ); - default: - return Math.round( - (d2.getTime() - d1.getTime()) / import_internal2.TIMEUNIT_IN_MILLIS[unit] - ); - } - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromParts.js -var require_dateFromParts = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromParts.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dateFromParts_exports = {}; - __export5(dateFromParts_exports, { - $dateFromParts: () => $dateFromParts - }); - module.exports = __toCommonJS(dateFromParts_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal8(); - var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - var getDaysInMonth = (date5) => { - return date5.month == 2 && (0, import_internal2.isLeapYear)(date5.year) ? 29 : DAYS_IN_MONTH[date5.month - 1]; - }; - var $dateFromParts = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - const minuteOffset = (0, import_internal2.parseTimezone)(args.timezone, /* @__PURE__ */ new Date()); - for (let i = import_internal2.DATE_PART_INTERVAL.length - 1, remainder = 0; i >= 0; i--) { - const datePartInterval = import_internal2.DATE_PART_INTERVAL[i]; - const k = datePartInterval[0]; - const min = datePartInterval[1]; - const max = datePartInterval[2]; - let part = (args[k] || 0) + remainder; - remainder = 0; - const limit = max + 1; - if (k == "hour") part += Math.floor(minuteOffset / import_internal2.MINUTES_PER_HOUR) * -1; - if (k == "minute") part += minuteOffset % import_internal2.MINUTES_PER_HOUR * -1; - if (part < min) { - const delta = min - part; - remainder = -1 * Math.ceil(delta / limit); - part = limit - delta % limit; - } else if (part > max) { - part += min; - remainder = Math.trunc(part / limit); - part %= limit; - } - args[k] = part; - } - args.day = Math.min(args.day, getDaysInMonth(args)); - return new Date( - Date.UTC( - args.year, - args.month - 1, - args.day, - args.hour, - args.minute, - args.second, - args.millisecond - ) - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromString.js -var require_dateFromString = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromString.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dateFromString_exports = {}; - __export5(dateFromString_exports, { - $dateFromString: () => $dateFromString - }); - module.exports = __toCommonJS(dateFromString_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal8(); - function tzLetterOffset(c) { - if (c === "Z") return 0; - if (c >= "A" && c < "N") return c.charCodeAt(0) - 64; - return 77 - c.charCodeAt(0); - } - var regexStrip = (s) => s.replace(/^\//, "").replace(/\/$/, "").replace(/\/i/, ""); - var REGEX_SPECIAL_CHARS = ["^", ".", "-", "*", "?", "$"]; - function regexQuote(s) { - for (const c of REGEX_SPECIAL_CHARS) s = s.replace(c, `\\${c}`); - return s; - } - function $dateFromString(obj, expr, options) { - const args = (0, import_internal.evalExpr)(obj, expr, options); - const format = args.format || import_internal2.DATE_FORMAT; - const onNull = args.onNull || null; - let dateString = args.dateString; - if ((0, import_util3.isNil)(dateString)) return onNull; - const separators = format.split(import_internal2.DATE_FORMAT_SEP_RE); - separators.reverse(); - const matches = format.match(import_internal2.DATE_FORMAT_SYM_RE); - const dateParts = {}; - let expectedPattern = ""; - for (let i = 0, len = matches.length; i < len; i++) { - const formatSpecifier = matches[i]; - const props = import_internal2.DATE_SYM_TABLE[formatSpecifier]; - if ((0, import_util3.isObject)(props)) { - const m2 = props.re.exec(dateString); - const delimiter = separators.pop() || ""; - if (m2 !== null) { - dateParts[props.name] = /^\d+$/.exec(m2[0]) ? parseInt(m2[0]) : m2[0]; - dateString = dateString.substring(m2.index + m2[0].length + 1); - expectedPattern += regexQuote(delimiter) + regexStrip(props.re.toString()); - } else { - dateParts[props.name] = null; - } - } - } - if ((0, import_util3.isNil)(dateParts.month)) { - const abbrMonth = (dateParts.full_month?.slice(0, 3) ?? dateParts.abbr_month ?? "").toLowerCase(); - if (import_internal2.MONTHS[abbrMonth]) { - dateParts.month = import_internal2.MONTHS[abbrMonth]; - } - } - if ((0, import_util3.isNil)(dateParts.year) || (0, import_util3.isNil)(dateParts.month) || (0, import_util3.isNil)(dateParts.day) || !new RegExp("^" + expectedPattern + "[A-Z]?$").test(args.dateString)) { - return args.onError; - } - const m = args.dateString.match(/([A-Z])$/); - (0, import_util3.assert)( - // only one of in-date timeone or timezone argument but not both. - !(m && args.timezone), - `$dateFromString: you cannot pass in a date/time string with time zone information ('${m && m[0]}') together with a timezone argument` - ); - const minuteOffset = m ? tzLetterOffset(m[0]) * import_internal2.MINUTES_PER_HOUR : (0, import_internal2.parseTimezone)(args.timezone, /* @__PURE__ */ new Date()); - const d = new Date( - Date.UTC(dateParts.year, dateParts.month - 1, dateParts.day, 0, 0, 0) - ); - if (!(0, import_util3.isNil)(dateParts.hour)) d.setUTCHours(dateParts.hour); - if (!(0, import_util3.isNil)(dateParts.minute)) d.setUTCMinutes(dateParts.minute); - if (!(0, import_util3.isNil)(dateParts.second)) d.setUTCSeconds(dateParts.second); - if (!(0, import_util3.isNil)(dateParts.millisecond)) - d.setUTCMilliseconds(dateParts.millisecond); - (0, import_internal2.adjustDate)(d, -minuteOffset); - return d; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateSubtract.js -var require_dateSubtract = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateSubtract.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dateSubtract_exports = {}; - __export5(dateSubtract_exports, { - $dateSubtract: () => $dateSubtract - }); - module.exports = __toCommonJS(dateSubtract_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal8(); - var $dateSubtract = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - return (0, import_internal2.dateAdd)(args.startDate, args.unit, -args.amount, args.timezone); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToParts.js -var require_dateToParts = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToParts.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dateToParts_exports = {}; - __export5(dateToParts_exports, { - $dateToParts: () => $dateToParts - }); - module.exports = __toCommonJS(dateToParts_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal8(); - var $dateToParts = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - const d = new Date(args.date); - (0, import_internal2.adjustDate)(d, (0, import_internal2.parseTimezone)(args.timezone, d)); - const timePart = { - hour: d.getUTCHours(), - minute: d.getUTCMinutes(), - second: d.getUTCSeconds(), - millisecond: d.getUTCMilliseconds() - }; - if (args.iso8601 == true) { - return Object.assign(timePart, { - isoWeekYear: (0, import_internal2.isoWeekYear)(d), - isoWeek: (0, import_internal2.isoWeek)(d), - isoDayOfWeek: d.getUTCDay() || 7 - }); - } - return Object.assign(timePart, { - year: d.getUTCFullYear(), - month: d.getUTCMonth() + 1, - day: d.getUTCDate() - }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToString.js -var require_dateToString = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToString.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dateToString_exports = {}; - __export5(dateToString_exports, { - $dateToString: () => $dateToString - }); - module.exports = __toCommonJS(dateToString_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal8(); - var DATE_FUNCTIONS = { - "%Y": (d) => d.getUTCFullYear(), - //year - "%G": (d) => d.getUTCFullYear(), - //year - "%m": (d) => d.getUTCMonth() + 1, - //month - "%d": (d) => d.getUTCDate(), - //dayOfMonth - "%H": (d) => d.getUTCHours(), - //hour - "%M": (d) => d.getUTCMinutes(), - //minutes - "%S": (d) => d.getUTCSeconds(), - //seconds - "%L": (d) => d.getUTCMilliseconds(), - //milliseconds - "%u": (d) => d.getUTCDay() || 7, - //isoDayOfWeek - "%U": import_internal2.weekOfYear, - "%V": import_internal2.isoWeek, - "%j": import_internal2.dayOfYear, - "%w": (d) => d.getUTCDay() - //dayOfWeek - }; - var $dateToString = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(args.onNull)) args.onNull = null; - if ((0, import_util3.isNil)(args.date)) return args.onNull; - const date5 = (0, import_internal2.computeDate)(obj, args.date, options); - let format = args.format ?? import_internal2.DATE_FORMAT; - const minuteOffset = (0, import_internal2.parseTimezone)(args.timezone, date5); - const matches = format.match(import_internal2.DATE_FORMAT_SYM_RE); - if (!matches) return format; - (0, import_internal2.adjustDate)(date5, minuteOffset); - for (let i = 0, len = matches.length; i < len; i++) { - const formatSpec = matches[i]; - (0, import_util3.assert)( - formatSpec in import_internal2.DATE_SYM_TABLE, - `$dateToString: invalid format specifier ${formatSpec}` - ); - const { name, padding } = import_internal2.DATE_SYM_TABLE[formatSpec]; - const fn = DATE_FUNCTIONS[formatSpec]; - let value = ""; - if (fn) { - value = (0, import_internal2.padDigits)(fn(date5), padding); - } else { - switch (name) { - case "timezone": - value = (0, import_internal2.formatTimezone)(minuteOffset); - break; - case "minute_offset": - value = minuteOffset.toString(); - break; - case "abbr_month": - case "full_month": { - const format2 = name.startsWith("abbr") ? "short" : "long"; - value = date5.toLocaleString("en-US", { month: format2 }); - break; - } - } - } - format = format.replace(formatSpec, value); - } - return format; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateTrunc.js -var require_dateTrunc = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateTrunc.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dateTrunc_exports = {}; - __export5(dateTrunc_exports, { - $dateTrunc: () => $dateTrunc - }); - module.exports = __toCommonJS(dateTrunc_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal8(); - var REF_DATE_MILLIS = 9466848e5; - var distanceToBinLowerBound = (value, binSize) => { - let remainder = value % binSize; - if (remainder < 0) { - remainder += binSize; - } - return remainder; - }; - var DATE_DIFF_FN = { - day: import_internal2.dateDiffDay, - month: import_internal2.dateDiffMonth, - quarter: import_internal2.dateDiffQuarter, - year: import_internal2.dateDiffYear - }; - var DAYS_OF_WEEK_RE = /(mon(day)?|tue(sday)?|wed(nesday)?|thu(rsday)?|fri(day)?|sat(urday)?|sun(day)?)/i; - var $dateTrunc = (obj, expr, options) => { - const { - date: date5, - unit, - binSize: optBinSize, - timezone, - startOfWeek: optStartOfWeek - } = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(date5) || (0, import_util3.isNil)(unit)) return null; - const startOfWeek = (optStartOfWeek ?? "sun").toLowerCase().substring(0, 3); - (0, import_util3.assert)( - (0, import_util3.isDate)(date5), - "$dateTrunc: 'date' must resolve to a valid Date object." - ); - (0, import_util3.assert)(import_internal2.TIME_UNITS.includes(unit), "$dateTrunc: unit is invalid."); - (0, import_util3.assert)( - unit != "week" || DAYS_OF_WEEK_RE.test(startOfWeek), - `$dateTrunc: startOfWeek '${startOfWeek}' is not a valid.` - ); - (0, import_util3.assert)( - (0, import_util3.isNil)(optBinSize) || optBinSize > 0, - "$dateTrunc requires 'binSize' to be greater than 0, but got value 0." - ); - const binSize = optBinSize ?? 1; - switch (unit) { - case "millisecond": - case "second": - case "minute": - case "hour": { - const binSizeMillis = binSize * import_internal2.TIMEUNIT_IN_MILLIS[unit]; - const shiftedDate = date5.getTime() - REF_DATE_MILLIS; - return new Date( - date5.getTime() - distanceToBinLowerBound(shiftedDate, binSizeMillis) - ); - } - default: { - (0, import_util3.assert)(binSize <= 1e11, "dateTrunc unsupported binSize value"); - const d = new Date(date5); - const refPointDate = new Date(REF_DATE_MILLIS); - let distanceFromRefPoint = 0; - if (unit == "week") { - const refPointDayOfWeek = (0, import_internal2.isoWeekday)(refPointDate, startOfWeek); - const daysToAdjustBy = (import_internal2.DAYS_PER_WEEK - refPointDayOfWeek) % import_internal2.DAYS_PER_WEEK; - refPointDate.setTime( - refPointDate.getTime() + daysToAdjustBy * import_internal2.TIMEUNIT_IN_MILLIS.day - ); - distanceFromRefPoint = (0, import_internal2.dateDiffWeek)(refPointDate, d, startOfWeek); - } else { - distanceFromRefPoint = DATE_DIFF_FN[unit](refPointDate, d); - } - const binLowerBoundFromRefPoint = distanceFromRefPoint - distanceToBinLowerBound(distanceFromRefPoint, binSize); - const newDate = (0, import_internal2.dateAdd)( - refPointDate, - unit, - binLowerBoundFromRefPoint, - timezone - ); - const minuteOffset = (0, import_internal2.parseTimezone)(timezone, newDate); - (0, import_internal2.adjustDate)(newDate, -minuteOffset); - return newDate; - } - } - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfMonth.js -var require_dayOfMonth = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfMonth.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dayOfMonth_exports = {}; - __export5(dayOfMonth_exports, { - $dayOfMonth: () => $dayOfMonth - }); - module.exports = __toCommonJS(dayOfMonth_exports); - var import_internal = require_internal8(); - var $dayOfMonth = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDate(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfWeek.js -var require_dayOfWeek = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfWeek.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dayOfWeek_exports = {}; - __export5(dayOfWeek_exports, { - $dayOfWeek: () => $dayOfWeek - }); - module.exports = __toCommonJS(dayOfWeek_exports); - var import_internal = require_internal8(); - var $dayOfWeek = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDay() + 1; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfYear.js -var require_dayOfYear = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfYear.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var dayOfYear_exports = {}; - __export5(dayOfYear_exports, { - $dayOfYear: () => $dayOfYear - }); - module.exports = __toCommonJS(dayOfYear_exports); - var import_internal = require_internal8(); - var $dayOfYear = (obj, expr, options) => (0, import_internal.dayOfYear)((0, import_internal.computeDate)(obj, expr, options)); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/hour.js -var require_hour = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/hour.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var hour_exports = {}; - __export5(hour_exports, { - $hour: () => $hour - }); - module.exports = __toCommonJS(hour_exports); - var import_internal = require_internal8(); - var $hour = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCHours(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoDayOfWeek.js -var require_isoDayOfWeek = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoDayOfWeek.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var isoDayOfWeek_exports = {}; - __export5(isoDayOfWeek_exports, { - $isoDayOfWeek: () => $isoDayOfWeek - }); - module.exports = __toCommonJS(isoDayOfWeek_exports); - var import_internal = require_internal8(); - var $isoDayOfWeek = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDay() || 7; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeek.js -var require_isoWeek = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeek.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var isoWeek_exports = {}; - __export5(isoWeek_exports, { - $isoWeek: () => $isoWeek - }); - module.exports = __toCommonJS(isoWeek_exports); - var import_internal = require_internal8(); - var $isoWeek = (obj, expr, options) => (0, import_internal.isoWeek)((0, import_internal.computeDate)(obj, expr, options)); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeekYear.js -var require_isoWeekYear = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeekYear.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var isoWeekYear_exports = {}; - __export5(isoWeekYear_exports, { - $isoWeekYear: () => $isoWeekYear - }); - module.exports = __toCommonJS(isoWeekYear_exports); - var import_internal = require_internal8(); - var $isoWeekYear = (obj, expr, options) => (0, import_internal.isoWeekYear)((0, import_internal.computeDate)(obj, expr, options)); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/millisecond.js -var require_millisecond = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/millisecond.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var millisecond_exports = {}; - __export5(millisecond_exports, { - $millisecond: () => $millisecond - }); - module.exports = __toCommonJS(millisecond_exports); - var import_internal = require_internal8(); - var $millisecond = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMilliseconds(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/minute.js -var require_minute = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/minute.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var minute_exports = {}; - __export5(minute_exports, { - $minute: () => $minute - }); - module.exports = __toCommonJS(minute_exports); - var import_internal = require_internal8(); - var $minute = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMinutes(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/month.js -var require_month = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/month.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var month_exports = {}; - __export5(month_exports, { - $month: () => $month - }); - module.exports = __toCommonJS(month_exports); - var import_internal = require_internal8(); - var $month = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMonth() + 1; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/second.js -var require_second = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/second.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var second_exports = {}; - __export5(second_exports, { - $second: () => $second - }); - module.exports = __toCommonJS(second_exports); - var import_internal = require_internal8(); - var $second = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCSeconds(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/week.js -var require_week = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/week.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var week_exports = {}; - __export5(week_exports, { - $week: () => $week - }); - module.exports = __toCommonJS(week_exports); - var import_internal = require_internal8(); - var $week = (obj, expr, options) => (0, import_internal.weekOfYear)((0, import_internal.computeDate)(obj, expr, options)); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/year.js -var require_year = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/year.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var year_exports = {}; - __export5(year_exports, { - $year: () => $year - }); - module.exports = __toCommonJS(year_exports); - var import_internal = require_internal8(); - var $year = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCFullYear(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/index.js -var require_date = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var date_exports = {}; - module.exports = __toCommonJS(date_exports); - __reExport(date_exports, require_dateAdd(), module.exports); - __reExport(date_exports, require_dateDiff(), module.exports); - __reExport(date_exports, require_dateFromParts(), module.exports); - __reExport(date_exports, require_dateFromString(), module.exports); - __reExport(date_exports, require_dateSubtract(), module.exports); - __reExport(date_exports, require_dateToParts(), module.exports); - __reExport(date_exports, require_dateToString(), module.exports); - __reExport(date_exports, require_dateTrunc(), module.exports); - __reExport(date_exports, require_dayOfMonth(), module.exports); - __reExport(date_exports, require_dayOfWeek(), module.exports); - __reExport(date_exports, require_dayOfYear(), module.exports); - __reExport(date_exports, require_hour(), module.exports); - __reExport(date_exports, require_isoDayOfWeek(), module.exports); - __reExport(date_exports, require_isoWeek(), module.exports); - __reExport(date_exports, require_isoWeekYear(), module.exports); - __reExport(date_exports, require_millisecond(), module.exports); - __reExport(date_exports, require_minute(), module.exports); - __reExport(date_exports, require_month(), module.exports); - __reExport(date_exports, require_second(), module.exports); - __reExport(date_exports, require_week(), module.exports); - __reExport(date_exports, require_year(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/literal.js -var require_literal = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/literal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var literal_exports = {}; - __export5(literal_exports, { - $literal: () => $literal - }); - module.exports = __toCommonJS(literal_exports); - var $literal = (_obj, expr, _options2) => expr; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/median.js -var require_median2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/median.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var median_exports = {}; - __export5(median_exports, { - $median: () => $median - }); - module.exports = __toCommonJS(median_exports); - var import_internal = require_internal2(); - var import_median = require_median(); - var $median = (obj, expr, options) => { - const input = (0, import_internal.evalExpr)(obj, expr.input, options); - return (0, import_median.$median)(input, { input: "$$CURRENT", method: expr.method }, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/getField.js -var require_getField = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/getField.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var getField_exports = {}; - __export5(getField_exports, { - $getField: () => $getField - }); - module.exports = __toCommonJS(getField_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $getField = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - const { field, input } = (0, import_util3.isString)(args) ? { field: args, input: obj } : { field: args.field, input: args.input ?? obj }; - return input[field]; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/rand.js -var require_rand = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/rand.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var rand_exports = {}; - __export5(rand_exports, { - $rand: () => $rand - }); - module.exports = __toCommonJS(rand_exports); - var $rand = (_obj, _expr2, _options2) => Math.random(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/sampleRate.js -var require_sampleRate = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/sampleRate.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sampleRate_exports = {}; - __export5(sampleRate_exports, { - $sampleRate: () => $sampleRate - }); - module.exports = __toCommonJS(sampleRate_exports); - var import_internal = require_internal2(); - var $sampleRate = (obj, expr, options) => Math.random() <= (0, import_internal.evalExpr)(obj, expr, options); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/index.js -var require_misc = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var misc_exports = {}; - module.exports = __toCommonJS(misc_exports); - __reExport(misc_exports, require_getField(), module.exports); - __reExport(misc_exports, require_rand(), module.exports); - __reExport(misc_exports, require_sampleRate(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/mergeObjects.js -var require_mergeObjects2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/mergeObjects.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var mergeObjects_exports = {}; - __export5(mergeObjects_exports, { - $mergeObjects: () => $mergeObjects - }); - module.exports = __toCommonJS(mergeObjects_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_mergeObjects = require_mergeObjects(); - var import_internal2 = require_internal4(); - var $mergeObjects = (obj, expr, options) => { - const docs = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(docs)) return {}; - if (!(0, import_util3.isArray)(docs)) - return (0, import_internal2.errExpectArray)(options.failOnError, "$mergeObjects", import_internal2.ARR_OPTS.obj); - return (0, import_mergeObjects.$mergeObjects)(docs, expr, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/objectToArray.js -var require_objectToArray = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/objectToArray.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var objectToArray_exports = {}; - __export5(objectToArray_exports, { - $objectToArray: () => $objectToArray - }); - module.exports = __toCommonJS(objectToArray_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $objectToArray = (obj, expr, options) => { - const val = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(val)) return null; - if (!(0, import_util3.isObject)(val)) - return (0, import_internal2.errExpectObject)(options.failOnError, "$objectToArray"); - const keys = Object.keys(val); - const result = new Array(keys.length); - let i = 0; - for (const k of keys) { - result[i++] = { k, v: val[k] }; - } - return result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/setField.js -var require_setField = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/setField.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var setField_exports = {}; - __export5(setField_exports, { - $setField: () => $setField - }); - module.exports = __toCommonJS(setField_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$setField"; - var $setField = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "field", "value"), - "$setField expects object { input, field, value }" - ); - const { input, field, value } = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(input)) return null; - const foe = options.failOnError; - if (!(0, import_util3.isObject)(input)) return (0, import_internal2.errExpectObject)(foe, `${OP} 'input'`); - if (!(0, import_util3.isString)(field)) return (0, import_internal2.errExpectString)(foe, `${OP} 'field'`); - const newObj = { ...input }; - if (expr.value == "$$REMOVE") { - delete newObj[field]; - } else { - newObj[field] = value; - } - return newObj; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/unsetField.js -var require_unsetField = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/unsetField.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var unsetField_exports = {}; - __export5(unsetField_exports, { - $unsetField: () => $unsetField - }); - module.exports = __toCommonJS(unsetField_exports); - var import_setField = require_setField(); - var $unsetField = (obj, expr, options) => { - return (0, import_setField.$setField)(obj, { ...expr, value: "$$REMOVE" }, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/index.js -var require_object = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var object_exports = {}; - module.exports = __toCommonJS(object_exports); - __reExport(object_exports, require_mergeObjects2(), module.exports); - __reExport(object_exports, require_objectToArray(), module.exports); - __reExport(object_exports, require_setField(), module.exports); - __reExport(object_exports, require_unsetField(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/percentile.js -var require_percentile2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/percentile.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var percentile_exports = {}; - __export5(percentile_exports, { - $percentile: () => $percentile - }); - module.exports = __toCommonJS(percentile_exports); - var import_internal = require_internal2(); - var import_percentile = require_percentile(); - var $percentile = (obj, expr, options) => { - const input = (0, import_internal.evalExpr)(obj, expr.input, options); - return (0, import_percentile.$percentile)( - input, - { ...expr, input: "$$CURRENT" }, - options - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/allElementsTrue.js -var require_allElementsTrue = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/allElementsTrue.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var allElementsTrue_exports = {}; - __export5(allElementsTrue_exports, { - $allElementsTrue: () => $allElementsTrue - }); - module.exports = __toCommonJS(allElementsTrue_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var import_internal3 = require_internal4(); - var $allElementsTrue = (obj, expr, options) => { - if ((0, import_internal2.isArray)(expr)) { - if (expr.length === 0) return true; - (0, import_internal2.assert)(expr.length === 1, "$allElementsTrue expects array(1)"); - expr = expr[0]; - } - const foe = options.failOnError; - const args = (0, import_internal.evalExpr)(obj, expr, options); - if (!(0, import_internal2.isArray)(args)) return (0, import_internal3.errExpectArray)(foe, `$allElementsTrue argument`); - for (const v of args) if (!(0, import_internal2.truthy)(v, options.useStrictMode)) return false; - return true; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/anyElementTrue.js -var require_anyElementTrue = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/anyElementTrue.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var anyElementTrue_exports = {}; - __export5(anyElementTrue_exports, { - $anyElementTrue: () => $anyElementTrue - }); - module.exports = __toCommonJS(anyElementTrue_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var import_internal3 = require_internal4(); - var $anyElementTrue = (obj, expr, options) => { - if ((0, import_internal2.isArray)(expr)) { - if (expr.length === 0) return false; - (0, import_internal2.assert)(expr.length === 1, "$anyElementTrue expects array(1)"); - expr = expr[0]; - } - const foe = options.failOnError; - const args = (0, import_internal.evalExpr)(obj, expr, options); - if (!(0, import_internal2.isArray)(args)) return (0, import_internal3.errExpectArray)(foe, `$anyElementTrue argument`); - for (const v of args) if ((0, import_internal2.truthy)(v, options.useStrictMode)) return true; - return false; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setDifference.js -var require_setDifference = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setDifference.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var setDifference_exports = {}; - __export5(setDifference_exports, { - $setDifference: () => $setDifference - }); - module.exports = __toCommonJS(setDifference_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$setDifference"; - var $setDifference = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length == 2, `${OP} expects array(2)`); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - let ok2 = true; - for (const v of args) { - if ((0, import_util3.isNil)(v)) return null; - ok2 && (ok2 = (0, import_util3.isArray)(v)); - } - if (!ok2) return (0, import_internal2.errExpectArray)(foe, `${OP} arguments`); - const m = import_util3.HashMap.init(); - for (const v of args[0]) m.set(v, true); - for (const v of args[1]) m.delete(v); - return Array.from(m.keys()); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setEquals.js -var require_setEquals = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setEquals.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var setEquals_exports = {}; - __export5(setEquals_exports, { - $setEquals: () => $setEquals - }); - module.exports = __toCommonJS(setEquals_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $setEquals = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), "$setEquals expects array"); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - if (!args.every(import_util3.isArray)) return (0, import_internal2.errExpectArray)(foe, "$setEquals arguments"); - const map3 = import_util3.HashMap.init(); - const first = args[0]; - for (let i = 0; i < first.length; i++) map3.set(first[i], i); - for (let i = 1; i < args.length; i++) { - const arr = args[i]; - const set2 = /* @__PURE__ */ new Set(); - for (let j = 0; j < arr.length; j++) { - const n = map3.get(arr[j]) ?? -1; - if (n === -1) return false; - set2.add(n); - } - if (set2.size !== map3.size) return false; - } - return true; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIntersection.js -var require_setIntersection = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIntersection.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var setIntersection_exports = {}; - __export5(setIntersection_exports, { - $setIntersection: () => $setIntersection - }); - module.exports = __toCommonJS(setIntersection_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$setIntersection"; - var $setIntersection = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), `${OP} expects array`); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - let ok2 = true; - for (const v of args) { - if ((0, import_util3.isNil)(v)) return null; - ok2 && (ok2 = (0, import_util3.isArray)(v)); - } - if (!ok2) return (0, import_internal2.errExpectArray)(foe, `${OP} arguments`); - return (0, import_util3.intersection)(args); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIsSubset.js -var require_setIsSubset = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIsSubset.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var setIsSubset_exports = {}; - __export5(setIsSubset_exports, { - $setIsSubset: () => $setIsSubset - }); - module.exports = __toCommonJS(setIsSubset_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$setIsSubset"; - var $setIsSubset = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, `${OP} expects array(2)`); - const args = (0, import_internal.evalExpr)(obj, expr, options); - if (!args.every(import_util3.isArray)) - return (0, import_internal2.errExpectArray)(options.failOnError, `${OP} arguments`); - const [first, second] = args; - const map3 = import_util3.HashMap.init(); - for (const v of second) map3.set(v, 0); - for (const v of first) if (!map3.has(v)) return false; - return true; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setUnion.js -var require_setUnion = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setUnion.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var setUnion_exports = {}; - __export5(setUnion_exports, { - $setUnion: () => $setUnion - }); - module.exports = __toCommonJS(setUnion_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $setUnion = (obj, expr, options) => { - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - if ((0, import_util3.isNil)(args)) return null; - if (!(0, import_util3.isArray)(args)) return (0, import_internal2.errExpectArray)(foe, "$setUnion"); - if ((0, import_util3.isArray)(expr)) { - if (!args.every(import_util3.isArray)) return (0, import_internal2.errExpectArray)(foe, "$setUnion arguments"); - return (0, import_util3.unique)((0, import_util3.flatten)(args)); - } - return (0, import_util3.unique)(args); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/index.js -var require_set = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var set_exports = {}; - module.exports = __toCommonJS(set_exports); - __reExport(set_exports, require_allElementsTrue(), module.exports); - __reExport(set_exports, require_anyElementTrue(), module.exports); - __reExport(set_exports, require_setDifference(), module.exports); - __reExport(set_exports, require_setEquals(), module.exports); - __reExport(set_exports, require_setIntersection(), module.exports); - __reExport(set_exports, require_setIsSubset(), module.exports); - __reExport(set_exports, require_setUnion(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/concat.js -var require_concat = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/concat.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var concat_exports = {}; - __export5(concat_exports, { - $concat: () => $concat - }); - module.exports = __toCommonJS(concat_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $concat = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr), "$concat expects array"); - const foe = options.failOnError; - const args = (0, import_internal.evalExpr)(obj, expr, options); - let ok2 = true; - for (const s of args) { - if ((0, import_util3.isNil)(s)) return null; - ok2 && (ok2 = (0, import_util3.isString)(s)); - } - if (!ok2) return (0, import_internal2.errExpectArray)(foe, "$concat", { type: "string" }); - return args.join(""); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/indexOfBytes.js -var require_indexOfBytes = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/indexOfBytes.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var indexOfBytes_exports = {}; - __export5(indexOfBytes_exports, { - $indexOfBytes: () => $indexOfBytes - }); - module.exports = __toCommonJS(indexOfBytes_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var import_internal3 = require_internal4(); - var OP = "$indexOfBytes"; - var $indexOfBytes = (obj, expr, options) => { - (0, import_internal2.assert)( - (0, import_internal2.isArray)(expr) && expr.length > 1 && expr.length < 5, - `${OP} expects array(4)` - ); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - const str = args[0]; - if ((0, import_internal2.isNil)(str)) return null; - if (!(0, import_internal2.isString)(str)) return (0, import_internal3.errExpectString)(foe, `${OP} arg1 `); - const search = args[1]; - if (!(0, import_internal2.isString)(search)) return (0, import_internal3.errExpectString)(foe, `${OP} arg2 `); - const start = args[2] ?? 0; - const end = args[3] ?? str.length; - if (!(0, import_internal2.isInteger)(start) || start < 0) - return (0, import_internal3.errExpectNumber)(foe, `${OP} arg3 `, import_internal3.INT_OPTS.index); - if (!(0, import_internal2.isInteger)(end) || end < 0) - return (0, import_internal3.errExpectNumber)(foe, `${OP} arg4 `, import_internal3.INT_OPTS.index); - if (start > end) return -1; - const index = str.substring(start, end).indexOf(search); - return index > -1 ? index + start : index; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/_internal.js -var require_internal9 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - regexSearch: () => regexSearch, - trimString: () => trimString - }); - module.exports = __toCommonJS(internal_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var WHITESPACE_CHARS = [ - 0, - // '\0' Null character - 32, - // ' ', Space - 9, - // '\t' Horizontal tab - 10, - // '\n' Line feed/new line - 11, - // '\v' Vertical tab - 12, - // '\f' Form feed - 13, - // '\r' Carriage return - 160, - // Non-breaking space - 5760, - // Ogham space mark - 8192, - // En quad - 8193, - // Em quad - 8194, - // En space - 8195, - // Em space - 8196, - // Three-per-em space - 8197, - // Four-per-em space - 8198, - // Six-per-em space - 8199, - // Figure space - 8200, - // Punctuation space - 8201, - // Thin space - 8202 - // Hair space - ]; - function trimString(obj, expr, options, trimOpts) { - const val = (0, import_internal.evalExpr)(obj, expr, options); - const s = val.input; - if ((0, import_util3.isNil)(s)) return null; - const codepoints = (0, import_util3.isNil)(val.chars) ? WHITESPACE_CHARS : val.chars.split("").map((c) => c.codePointAt(0)); - let i = 0; - let j = s.length - 1; - while (trimOpts.left && i <= j && codepoints.indexOf(s[i].codePointAt(0)) !== -1) - i++; - while (trimOpts.right && i <= j && codepoints.indexOf(s[j].codePointAt(0)) !== -1) - j--; - return s.substring(i, j + 1); - } - function regexSearch(obj, expr, options, reOpts) { - const val = (0, import_internal.evalExpr)(obj, expr, options); - if (!(0, import_util3.isString)(val.input)) return []; - const regexOptions = val.options; - if (regexOptions) { - (0, import_util3.assert)( - regexOptions.indexOf("x") === -1, - "extended capability option 'x' not supported" - ); - (0, import_util3.assert)(regexOptions.indexOf("g") === -1, "global option 'g' not supported"); - } - let input = val.input; - const re2 = new RegExp(val.regex, regexOptions); - let m; - const matches = new Array(); - let offset = 0; - while (m = re2.exec(input)) { - const result = { - match: m[0], - idx: m.index + offset, - captures: [] - }; - for (let i = 1; i < m.length; i++) result.captures.push(m[i] || null); - matches.push(result); - if (!reOpts.global) break; - offset = m.index + m[0].length; - input = input.substring(offset); - } - return matches; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/ltrim.js -var require_ltrim = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/ltrim.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var ltrim_exports = {}; - __export5(ltrim_exports, { - $ltrim: () => $ltrim - }); - module.exports = __toCommonJS(ltrim_exports); - var import_internal = require_internal9(); - var $ltrim = (obj, expr, options) => { - return (0, import_internal.trimString)(obj, expr, options, { left: true, right: false }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFind.js -var require_regexFind = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFind.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var regexFind_exports = {}; - __export5(regexFind_exports, { - $regexFind: () => $regexFind - }); - module.exports = __toCommonJS(regexFind_exports); - var import_util3 = require_util(); - var import_internal = require_internal9(); - var $regexFind = (obj, expr, options) => { - const result = (0, import_internal.regexSearch)(obj, expr, options, { global: false }); - return (0, import_util3.isArray)(result) && result.length > 0 ? result[0] : null; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFindAll.js -var require_regexFindAll = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFindAll.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var regexFindAll_exports = {}; - __export5(regexFindAll_exports, { - $regexFindAll: () => $regexFindAll - }); - module.exports = __toCommonJS(regexFindAll_exports); - var import_internal = require_internal9(); - var $regexFindAll = (obj, expr, options) => { - return (0, import_internal.regexSearch)(obj, expr, options, { global: true }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexMatch.js -var require_regexMatch = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexMatch.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var regexMatch_exports = {}; - __export5(regexMatch_exports, { - $regexMatch: () => $regexMatch - }); - module.exports = __toCommonJS(regexMatch_exports); - var import_internal = require_internal9(); - var $regexMatch = (obj, expr, options) => { - return (0, import_internal.regexSearch)(obj, expr, options, { global: false })?.length != 0; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceAll.js -var require_replaceAll = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceAll.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var replaceAll_exports = {}; - __export5(replaceAll_exports, { - $replaceAll: () => $replaceAll - }); - module.exports = __toCommonJS(replaceAll_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$replaceAll"; - var $replaceAll = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isObject)(expr), `${OP} expects an object argument`); - const foe = options.failOnError; - const args = (0, import_internal.evalExpr)(obj, expr, options); - const { input, find, replacement } = args; - if ((0, import_util3.isNil)(input) || (0, import_util3.isNil)(find) || (0, import_util3.isNil)(replacement)) return null; - if (!(0, import_util3.isString)(input)) return (0, import_internal2.errExpectString)(foe, `${OP} 'input'`); - if (!(0, import_util3.isString)(find)) return (0, import_internal2.errExpectString)(foe, `${OP} 'find'`); - if (!(0, import_util3.isString)(replacement)) - return (0, import_internal2.errExpectString)(foe, `${OP} 'replacement'`); - return input.replace(new RegExp(find, "g"), replacement); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceOne.js -var require_replaceOne = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceOne.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var replaceOne_exports = {}; - __export5(replaceOne_exports, { - $replaceOne: () => $replaceOne - }); - module.exports = __toCommonJS(replaceOne_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$replaceOne"; - var $replaceOne = (obj, expr, options) => { - const foe = options.failOnError; - const args = (0, import_internal.evalExpr)(obj, expr, options); - const { input, find, replacement } = args; - if ((0, import_util3.isNil)(input) || (0, import_util3.isNil)(find) || (0, import_util3.isNil)(replacement)) return null; - if (!(0, import_util3.isString)(input)) return (0, import_internal2.errExpectString)(foe, `${OP} 'input'`); - if (!(0, import_util3.isString)(find)) return (0, import_internal2.errExpectString)(foe, `${OP} 'find'`); - if (!(0, import_util3.isString)(replacement)) - return (0, import_internal2.errExpectString)(foe, `${OP} 'replacement'`); - return args.input.replace(args.find, args.replacement); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/rtrim.js -var require_rtrim = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/rtrim.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var rtrim_exports = {}; - __export5(rtrim_exports, { - $rtrim: () => $rtrim - }); - module.exports = __toCommonJS(rtrim_exports); - var import_internal = require_internal9(); - var $rtrim = (obj, expr, options) => { - return (0, import_internal.trimString)(obj, expr, options, { left: false, right: true }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/split.js -var require_split = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/split.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var split_exports = {}; - __export5(split_exports, { - $split: () => $split - }); - module.exports = __toCommonJS(split_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $split = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 2, `$split expects array(2)`); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - if ((0, import_util3.isNil)(args[0])) return null; - if (!args.every(import_util3.isString)) - return (0, import_internal2.errExpectArray)(foe, `$split `, { size: 2, type: "string" }); - return args[0].split(args[1]); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strcasecmp.js -var require_strcasecmp = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strcasecmp.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var strcasecmp_exports = {}; - __export5(strcasecmp_exports, { - $strcasecmp: () => $strcasecmp - }); - module.exports = __toCommonJS(strcasecmp_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal(); - var import_internal3 = require_internal4(); - var $strcasecmp = (obj, expr, options) => { - (0, import_internal2.assert)((0, import_util3.isArray)(expr) && expr.length === 2, `$strcasecmp expects array(2)`); - const args = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - let t_nil = true; - let t_str = true; - for (const v of args) { - t_nil && (t_nil = (0, import_util3.isNil)(v)); - t_str && (t_str = (0, import_util3.isString)(v)); - } - if (t_nil) return 0; - if (!t_str) - return (0, import_internal3.errExpectArray)(foe, `$strcasecmp arguments`, { type: "string" }); - return (0, import_internal2.simpleCmp)(args[0].toLowerCase(), args[1].toLowerCase()); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenBytes.js -var require_strLenBytes = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenBytes.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var strLenBytes_exports = {}; - __export5(strLenBytes_exports, { - $strLenBytes: () => $strLenBytes - }); - module.exports = __toCommonJS(strLenBytes_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $strLenBytes = (obj, expr, options) => { - const s = (0, import_internal.evalExpr)(obj, expr, options); - if (!(0, import_util3.isString)(s)) return (0, import_internal2.errExpectString)(options.failOnError, "$strLenBytes"); - return ~-encodeURI(s).split(/%..|./).length; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenCP.js -var require_strLenCP = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenCP.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var strLenCP_exports = {}; - __export5(strLenCP_exports, { - $strLenCP: () => $strLenCP - }); - module.exports = __toCommonJS(strLenCP_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var $strLenCP = (obj, expr, options) => { - const s = (0, import_internal.evalExpr)(obj, expr, options); - if (!(0, import_util3.isString)(s)) return (0, import_internal2.errExpectString)(options.failOnError, "$strLenCP"); - return s.length; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrBytes.js -var require_substrBytes = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrBytes.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var substrBytes_exports = {}; - __export5(substrBytes_exports, { - $substrBytes: () => $substrBytes - }); - module.exports = __toCommonJS(substrBytes_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$substrBytes"; - var $substrBytes = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 3, `${OP} expects array(3)`); - const [s, index, count] = (0, import_internal.evalExpr)(obj, expr, options); - const foe = options.failOnError; - const nil = (0, import_util3.isNil)(s); - if (!nil && !(0, import_util3.isString)(s)) return (0, import_internal2.errExpectString)(foe, `${OP} arg1 `); - if (!(0, import_util3.isInteger)(index) || index < 0) - return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `, import_internal2.INT_OPTS.index); - if (!(0, import_util3.isInteger)(count) || count < 0) - return (0, import_internal2.errExpectNumber)(foe, `${OP} arg3 `, import_internal2.INT_OPTS.index); - if (nil) return ""; - let utf8Pos = 0; - let start16 = null; - let end16 = null; - const err = `${OP} UTF-8 boundary falls inside a continuation byte`; - for (let i = 0; i < s.length; ) { - const cp = s.codePointAt(i); - if (cp === void 0) - return (0, import_internal2.errInvalidArgs)(foe, `${OP} byte index out of range`); - const utf8Len = cp < 128 ? 1 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4; - const utf16Len = cp > 65535 ? 2 : 1; - if (start16 === null) { - if (index > utf8Pos && index < utf8Pos + utf8Len) - return (0, import_internal2.errInvalidArgs)(foe, err); - if (utf8Pos === index) { - start16 = i; - } - } - const endByte = index + count; - if (start16 !== null && end16 === null) { - if (endByte > utf8Pos && endByte < utf8Pos + utf8Len) - return (0, import_internal2.errInvalidArgs)(foe, err); - if (utf8Pos === endByte) { - end16 = i; - break; - } - } - utf8Pos += utf8Len; - i += utf16Len; - } - if (start16 === null) { - if (index === utf8Pos) return ""; - return (0, import_internal2.errInvalidArgs)(foe, `${OP} byte index out of range`); - } - if (end16 === null) { - const endByte = index + count; - if (endByte !== utf8Pos) - return (0, import_internal2.errInvalidArgs)(foe, `${OP} count extends beyond UTF-8 length`); - end16 = s.length; - } - return s.slice(start16, end16); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substr.js -var require_substr = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substr.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var substr_exports = {}; - __export5(substr_exports, { - $substr: () => $substr - }); - module.exports = __toCommonJS(substr_exports); - var import_substrBytes = require_substrBytes(); - var $substr = import_substrBytes.$substrBytes; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrCP.js -var require_substrCP = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrCP.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var substrCP_exports = {}; - __export5(substrCP_exports, { - $substrCP: () => $substrCP - }); - module.exports = __toCommonJS(substrCP_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var OP = "$substrCP"; - var $substrCP = (obj, expr, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(expr) && expr.length === 3, `${OP} expects array(3)`); - const [s, index, count] = (0, import_internal.evalExpr)(obj, expr, options); - const nil = (0, import_util3.isNil)(s); - const foe = options.failOnError; - if (!nil && !(0, import_util3.isString)(s)) return (0, import_internal2.errExpectString)(foe, `${OP} arg1 `); - if (!(0, import_util3.isInteger)(index)) return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `); - if (!(0, import_util3.isInteger)(count)) return (0, import_internal2.errExpectNumber)(foe, `${OP} arg3 `); - if (nil) return ""; - if (index < 0) return ""; - if (count < 0) return s.substring(index); - return s.substring(index, index + count); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toBool.js -var require_toBool = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toBool.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toBool_exports = {}; - __export5(toBool_exports, { - $toBool: () => $toBool - }); - module.exports = __toCommonJS(toBool_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $toBool = (obj, expr, options) => { - const val = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(val)) return null; - if ((0, import_util3.isString)(val)) return true; - return Boolean(val); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDate.js -var require_toDate = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDate.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toDate_exports = {}; - __export5(toDate_exports, { - $toDate: () => $toDate - }); - module.exports = __toCommonJS(toDate_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $toDate = (obj, expr, options) => { - const val = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isDate)(val)) return val; - if ((0, import_util3.isNil)(val)) return null; - const d = new Date(val); - (0, import_util3.assert)(!isNaN(d.getTime()), `cannot convert '${val}' to date`); - return d; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDouble.js -var require_toDouble = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDouble.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toDouble_exports = {}; - __export5(toDouble_exports, { - $toDouble: () => $toDouble - }); - module.exports = __toCommonJS(toDouble_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $toDouble = (obj, expr, options) => { - const val = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_util3.isNil)(val)) return null; - if ((0, import_util3.isDate)(val)) return val.getTime(); - if (val === true) return 1; - if (val === false) return 0; - const n = Number(val); - (0, import_util3.assert)((0, import_util3.isNumber)(n), `cannot convert '${val}' to double/decimal`); - return n; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/_internal.js -var require_internal10 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - MAX_INT: () => MAX_INT, - MAX_LONG: () => MAX_LONG, - MIN_INT: () => MIN_INT, - MIN_LONG: () => MIN_LONG, - toInteger: () => toInteger - }); - module.exports = __toCommonJS(internal_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var MAX_INT = 2147483647; - var MIN_INT = -2147483648; - var MAX_LONG = 9007199254740991; - var MIN_LONG = -9007199254740991; - function toInteger(obj, expr, options, min, max) { - const val = (0, import_internal.evalExpr)(obj, expr, options); - if (val === true) return 1; - if (val === false) return 0; - if ((0, import_util3.isNil)(val)) return null; - if ((0, import_util3.isDate)(val)) return val.getTime(); - const n = Number(val); - (0, import_util3.assert)( - (0, import_util3.isNumber)(n) && n >= min && n <= max && (!(0, import_util3.isString)(val) || n.toString().indexOf(".") === -1), - `cannot convert '${val}' to ${max == MAX_INT ? "int" : "long"}` - ); - return Math.trunc(n); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toInt.js -var require_toInt = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toInt.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toInt_exports = {}; - __export5(toInt_exports, { - $toInt: () => $toInt - }); - module.exports = __toCommonJS(toInt_exports); - var import_internal = require_internal10(); - var $toInt = (obj, expr, options) => (0, import_internal.toInteger)(obj, expr, options, import_internal.MIN_INT, import_internal.MAX_INT); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toLong.js -var require_toLong = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toLong.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toLong_exports = {}; - __export5(toLong_exports, { - $toLong: () => $toLong - }); - module.exports = __toCommonJS(toLong_exports); - var import_internal = require_internal10(); - var $toLong = (obj, expr, options) => (0, import_internal.toInteger)(obj, expr, options, import_internal.MIN_LONG, import_internal.MAX_LONG); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toString.js -var require_toString = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toString.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toString_exports = {}; - __export5(toString_exports, { - $toString: () => $toString - }); - module.exports = __toCommonJS(toString_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - var import_internal3 = require_internal4(); - var $toString = (obj, expr, options) => { - const val = (0, import_internal.evalExpr)(obj, expr, options); - if ((0, import_internal2.isNil)(val)) return null; - if ((0, import_internal2.isDate)(val)) return val.toISOString(); - if ((0, import_internal2.isPrimitive)(val) || (0, import_internal2.isRegExp)(val)) return String(val); - return (0, import_internal3.errInvalidArgs)( - options.failOnError, - "$toString cannot convert from object to string" - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/convert.js -var require_convert = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/convert.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var convert_exports = {}; - __export5(convert_exports, { - $convert: () => $convert - }); - module.exports = __toCommonJS(convert_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - var import_toBool = require_toBool(); - var import_toDate = require_toDate(); - var import_toDouble = require_toDouble(); - var import_toInt = require_toInt(); - var import_toLong = require_toLong(); - var import_toString = require_toString(); - var $convert = (obj, expr, options) => { - (0, import_util3.assert)( - (0, import_util3.isObject)(expr) && (0, import_util3.has)(expr, "input", "to"), - "$convert expects object { input, to, onError, onNull }" - ); - const input = (0, import_internal.evalExpr)(obj, expr.input, options); - if ((0, import_util3.isNil)(input)) return (0, import_internal.evalExpr)(obj, expr.onNull, options) ?? null; - const toExpr = (0, import_internal.evalExpr)(obj, expr.to, options); - try { - switch (toExpr) { - case 2: - case "string": - return (0, import_toString.$toString)(obj, input, options); - case 8: - case "boolean": - case "bool": - return (0, import_toBool.$toBool)(obj, input, options); - case 9: - case "date": - return (0, import_toDate.$toDate)(obj, input, options); - case 1: - case 19: - case "double": - case "decimal": - case "number": - return (0, import_toDouble.$toDouble)(obj, input, options); - case 16: - case "int": - return (0, import_toInt.$toInt)(obj, input, options); - case 18: - case "long": - return (0, import_toLong.$toLong)(obj, input, options); - } - } catch { - } - if (expr.onError === void 0) - return (0, import_internal2.errInvalidArgs)( - options.failOnError, - `$convert cannot convert from object to ${expr.to} with no onError value` - ); - return (0, import_internal.evalExpr)(obj, expr.onError, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/isNumber.js -var require_isNumber = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/isNumber.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var isNumber_exports = {}; - __export5(isNumber_exports, { - $isNumber: () => $isNumber - }); - module.exports = __toCommonJS(isNumber_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $isNumber = (obj, expr, options) => { - const n = (0, import_internal.evalExpr)(obj, expr, options); - return (0, import_util3.isNumber)(n); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDecimal.js -var require_toDecimal = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDecimal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toDecimal_exports = {}; - __export5(toDecimal_exports, { - $toDecimal: () => $toDecimal - }); - module.exports = __toCommonJS(toDecimal_exports); - var import_toDouble = require_toDouble(); - var $toDecimal = import_toDouble.$toDouble; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/type.js -var require_type = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/type.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var type_exports = {}; - __export5(type_exports, { - $type: () => $type - }); - module.exports = __toCommonJS(type_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal10(); - var $type = (obj, expr, options) => { - const v = (0, import_internal.evalExpr)(obj, expr, options); - if (options.useStrictMode) { - if (v === void 0) return "missing"; - if (v === true || v === false) return "bool"; - if ((0, import_util3.isNumber)(v)) { - if (v % 1 != 0) return "double"; - return v >= import_internal2.MIN_INT && v <= import_internal2.MAX_INT ? "int" : "long"; - } - if ((0, import_util3.isRegExp)(v)) return "regex"; - } - return (0, import_util3.typeOf)(v); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/index.js -var require_type2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var type_exports = {}; - module.exports = __toCommonJS(type_exports); - __reExport(type_exports, require_convert(), module.exports); - __reExport(type_exports, require_isNumber(), module.exports); - __reExport(type_exports, require_toBool(), module.exports); - __reExport(type_exports, require_toDate(), module.exports); - __reExport(type_exports, require_toDecimal(), module.exports); - __reExport(type_exports, require_toDouble(), module.exports); - __reExport(type_exports, require_toInt(), module.exports); - __reExport(type_exports, require_toLong(), module.exports); - __reExport(type_exports, require_toString(), module.exports); - __reExport(type_exports, require_type(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toLower.js -var require_toLower = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toLower.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toLower_exports = {}; - __export5(toLower_exports, { - $toLower: () => $toLower - }); - module.exports = __toCommonJS(toLower_exports); - var import_internal = require_internal(); - var import_type = require_type2(); - var $toLower = (obj, expr, options) => { - if ((0, import_internal.isArray)(expr) && expr.length === 1) expr = expr[0]; - const s = (0, import_type.$toString)(obj, expr, options); - return s === null ? s : s.toLowerCase(); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toUpper.js -var require_toUpper = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toUpper.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toUpper_exports = {}; - __export5(toUpper_exports, { - $toUpper: () => $toUpper - }); - module.exports = __toCommonJS(toUpper_exports); - var import_util3 = require_util(); - var import_type = require_type2(); - var $toUpper = (obj, expr, options) => { - if ((0, import_util3.isArray)(expr) && expr.length === 1) expr = expr[0]; - const s = (0, import_type.$toString)(obj, expr, options); - return s === null ? s : s.toUpperCase(); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/trim.js -var require_trim = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/trim.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var trim_exports = {}; - __export5(trim_exports, { - $trim: () => $trim - }); - module.exports = __toCommonJS(trim_exports); - var import_internal = require_internal9(); - var $trim = (obj, expr, options) => { - return (0, import_internal.trimString)(obj, expr, options, { left: true, right: true }); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/index.js -var require_string = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var string_exports = {}; - module.exports = __toCommonJS(string_exports); - __reExport(string_exports, require_concat(), module.exports); - __reExport(string_exports, require_indexOfBytes(), module.exports); - __reExport(string_exports, require_ltrim(), module.exports); - __reExport(string_exports, require_regexFind(), module.exports); - __reExport(string_exports, require_regexFindAll(), module.exports); - __reExport(string_exports, require_regexMatch(), module.exports); - __reExport(string_exports, require_replaceAll(), module.exports); - __reExport(string_exports, require_replaceOne(), module.exports); - __reExport(string_exports, require_rtrim(), module.exports); - __reExport(string_exports, require_split(), module.exports); - __reExport(string_exports, require_strcasecmp(), module.exports); - __reExport(string_exports, require_strLenBytes(), module.exports); - __reExport(string_exports, require_strLenCP(), module.exports); - __reExport(string_exports, require_substr(), module.exports); - __reExport(string_exports, require_substrBytes(), module.exports); - __reExport(string_exports, require_substrCP(), module.exports); - __reExport(string_exports, require_toLower(), module.exports); - __reExport(string_exports, require_toUpper(), module.exports); - __reExport(string_exports, require_trim(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/toHashedIndexKey.js -var require_toHashedIndexKey = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/toHashedIndexKey.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var toHashedIndexKey_exports = {}; - __export5(toHashedIndexKey_exports, { - $toHashedIndexKey: () => $toHashedIndexKey - }); - module.exports = __toCommonJS(toHashedIndexKey_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $toHashedIndexKey = (obj, expr, options) => (0, import_util3.hashCode)((0, import_internal.evalExpr)(obj, expr, options)); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/_internal.js -var require_internal11 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - processOperator: () => processOperator - }); - module.exports = __toCommonJS(internal_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal4(); - function processOperator(obj, expr, options, fn, fixedPoints) { - const fp = { - undefined: null, - null: null, - NaN: NaN, - Infinity: new Error(), - "-Infinity": new Error(), - ...fixedPoints - }; - const foe = options.failOnError; - const op = fn.name; - const n = (0, import_internal.evalExpr)(obj, expr, options); - if (n in fp) { - const res = fp[n]; - if (res instanceof Error) - return (0, import_internal2.errExpectNumber)(foe, `$${op} invalid input '${n}'`); - return res; - } - if (!(0, import_util3.isNumber)(n)) return (0, import_internal2.errExpectNumber)(foe, `$${op}`); - return fn(n); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acos.js -var require_acos = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acos.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var acos_exports = {}; - __export5(acos_exports, { - $acos: () => $acos - }); - module.exports = __toCommonJS(acos_exports); - var import_internal = require_internal11(); - var $acos = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.acos, { - Infinity: Infinity, - 0: new Error() - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acosh.js -var require_acosh = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acosh.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var acosh_exports = {}; - __export5(acosh_exports, { - $acosh: () => $acosh - }); - module.exports = __toCommonJS(acosh_exports); - var import_internal = require_internal11(); - var $acosh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.acosh, { - Infinity: Infinity, - 0: new Error() - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asin.js -var require_asin = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asin.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var asin_exports = {}; - __export5(asin_exports, { - $asin: () => $asin - }); - module.exports = __toCommonJS(asin_exports); - var import_internal = require_internal11(); - var $asin = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.asin); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asinh.js -var require_asinh = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asinh.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var asinh_exports = {}; - __export5(asinh_exports, { - $asinh: () => $asinh - }); - module.exports = __toCommonJS(asinh_exports); - var import_internal = require_internal11(); - var $asinh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.asinh, { - Infinity: Infinity, - "-Infinity": -Infinity - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan.js -var require_atan = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var atan_exports = {}; - __export5(atan_exports, { - $atan: () => $atan - }); - module.exports = __toCommonJS(atan_exports); - var import_internal = require_internal11(); - var $atan = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.atan); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan2.js -var require_atan2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan2.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var atan2_exports = {}; - __export5(atan2_exports, { - $atan2: () => $atan2 - }); - module.exports = __toCommonJS(atan2_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var $atan2 = (obj, expr, options) => { - const [y, x] = (0, import_internal.evalExpr)(obj, expr, options); - if (isNaN(y) || (0, import_util3.isNil)(y)) return y; - if (isNaN(x) || (0, import_util3.isNil)(x)) return x; - return Math.atan2(y, x); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atanh.js -var require_atanh = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atanh.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var atanh_exports = {}; - __export5(atanh_exports, { - $atanh: () => $atanh - }); - module.exports = __toCommonJS(atanh_exports); - var import_internal = require_internal11(); - var $atanh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.atanh, { - 1: Infinity, - "-1": -Infinity - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cos.js -var require_cos = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cos.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var cos_exports = {}; - __export5(cos_exports, { - $cos: () => $cos - }); - module.exports = __toCommonJS(cos_exports); - var import_internal = require_internal11(); - var $cos = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.cos); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cosh.js -var require_cosh = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cosh.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var cosh_exports = {}; - __export5(cosh_exports, { - $cosh: () => $cosh - }); - module.exports = __toCommonJS(cosh_exports); - var import_internal = require_internal11(); - var $cosh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.cosh, { - "-Infinity": Infinity, - Infinity: Infinity - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/degreesToRadians.js -var require_degreesToRadians = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/degreesToRadians.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var degreesToRadians_exports = {}; - __export5(degreesToRadians_exports, { - $degreesToRadians: () => $degreesToRadians - }); - module.exports = __toCommonJS(degreesToRadians_exports); - var import_internal = require_internal11(); - var degreesToRadians = (n) => n * (Math.PI / 180); - var $degreesToRadians = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, degreesToRadians, { - Infinity: Infinity, - "-Infinity": Infinity - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/radiansToDegrees.js -var require_radiansToDegrees = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/radiansToDegrees.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var radiansToDegrees_exports = {}; - __export5(radiansToDegrees_exports, { - $radiansToDegrees: () => $radiansToDegrees - }); - module.exports = __toCommonJS(radiansToDegrees_exports); - var import_internal = require_internal11(); - var radiansToDegrees = (n) => n * (180 / Math.PI); - var $radiansToDegrees = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, radiansToDegrees, { - Infinity: Infinity, - "-Infinity": Infinity - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sin.js -var require_sin = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sin.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sin_exports = {}; - __export5(sin_exports, { - $sin: () => $sin - }); - module.exports = __toCommonJS(sin_exports); - var import_internal = require_internal11(); - var $sin = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.sin); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sinh.js -var require_sinh = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sinh.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sinh_exports = {}; - __export5(sinh_exports, { - $sinh: () => $sinh - }); - module.exports = __toCommonJS(sinh_exports); - var import_internal = require_internal11(); - var $sinh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.sinh, { - "-Infinity": -Infinity, - Infinity: Infinity - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tan.js -var require_tan = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tan.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var tan_exports = {}; - __export5(tan_exports, { - $tan: () => $tan - }); - module.exports = __toCommonJS(tan_exports); - var import_internal = require_internal11(); - var $tan = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.tan); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tanh.js -var require_tanh = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tanh.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var tanh_exports = {}; - __export5(tanh_exports, { - $tanh: () => $tanh - }); - module.exports = __toCommonJS(tanh_exports); - var import_internal = require_internal11(); - var $tanh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.tanh, { - Infinity: 1, - "-Infinity": -1 - }); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/index.js -var require_trignometry = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var trignometry_exports = {}; - module.exports = __toCommonJS(trignometry_exports); - __reExport(trignometry_exports, require_acos(), module.exports); - __reExport(trignometry_exports, require_acosh(), module.exports); - __reExport(trignometry_exports, require_asin(), module.exports); - __reExport(trignometry_exports, require_asinh(), module.exports); - __reExport(trignometry_exports, require_atan(), module.exports); - __reExport(trignometry_exports, require_atan2(), module.exports); - __reExport(trignometry_exports, require_atanh(), module.exports); - __reExport(trignometry_exports, require_cos(), module.exports); - __reExport(trignometry_exports, require_cosh(), module.exports); - __reExport(trignometry_exports, require_degreesToRadians(), module.exports); - __reExport(trignometry_exports, require_radiansToDegrees(), module.exports); - __reExport(trignometry_exports, require_sin(), module.exports); - __reExport(trignometry_exports, require_sinh(), module.exports); - __reExport(trignometry_exports, require_tan(), module.exports); - __reExport(trignometry_exports, require_tanh(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/let.js -var require_let = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/let.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var let_exports = {}; - __export5(let_exports, { - $let: () => $let - }); - module.exports = __toCommonJS(let_exports); - var import_internal = require_internal2(); - var $let = (obj, expr, options) => { - const variables = {}; - for (const key of Object.keys(expr.vars)) { - variables[key] = (0, import_internal.evalExpr)(obj, expr.vars[key], options); - } - return (0, import_internal.evalExpr)( - obj, - expr.in, - import_internal.ComputeOptions.init(options).update({ variables }) - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/index.js -var require_variable = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var variable_exports = {}; - module.exports = __toCommonJS(variable_exports); - __reExport(variable_exports, require_let(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/index.js -var require_expression = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var expression_exports = {}; - module.exports = __toCommonJS(expression_exports); - __reExport(expression_exports, require_arithmetic(), module.exports); - __reExport(expression_exports, require_array(), module.exports); - __reExport(expression_exports, require_bitwise(), module.exports); - __reExport(expression_exports, require_boolean(), module.exports); - __reExport(expression_exports, require_comparison(), module.exports); - __reExport(expression_exports, require_conditional(), module.exports); - __reExport(expression_exports, require_custom(), module.exports); - __reExport(expression_exports, require_date(), module.exports); - __reExport(expression_exports, require_literal(), module.exports); - __reExport(expression_exports, require_median2(), module.exports); - __reExport(expression_exports, require_misc(), module.exports); - __reExport(expression_exports, require_object(), module.exports); - __reExport(expression_exports, require_percentile2(), module.exports); - __reExport(expression_exports, require_set(), module.exports); - __reExport(expression_exports, require_string(), module.exports); - __reExport(expression_exports, require_toHashedIndexKey(), module.exports); - __reExport(expression_exports, require_trignometry(), module.exports); - __reExport(expression_exports, require_type2(), module.exports); - __reExport(expression_exports, require_variable(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/addFields.js -var require_addFields = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/addFields.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var addFields_exports = {}; - __export5(addFields_exports, { - $addFields: () => $addFields - }); - module.exports = __toCommonJS(addFields_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - function $addFields(coll, expr, options) { - const newFields = Object.keys(expr); - if (newFields.length === 0) return coll; - return coll.map((obj) => { - const newObj = { ...obj }; - for (const field of newFields) { - const newValue = (0, import_internal.evalExpr)(obj, expr[field], options); - if (newValue !== void 0) { - (0, import_util3.setValue)(newObj, field, newValue); - } else { - (0, import_util3.removeValue)(newObj, field); - } - } - return newObj; - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucket.js -var require_bucket = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucket.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bucket_exports = {}; - __export5(bucket_exports, { - $bucket: () => $bucket - }); - module.exports = __toCommonJS(bucket_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - function $bucket(coll, expr, options) { - const bounds = expr.boundaries.slice(); - const defaultKey = expr.default; - const lower = bounds[0]; - const upper = bounds[bounds.length - 1]; - const outputExpr = expr.output || { count: { $sum: 1 } }; - (0, import_util3.assert)(bounds.length > 1, "$bucket: must specify at least two boundaries."); - const isValid = bounds.every( - (v, i) => i === 0 || (0, import_util3.typeOf)(v) === (0, import_util3.typeOf)(bounds[i - 1]) && (0, import_util3.compare)(v, bounds[i - 1]) > 0 - ); - (0, import_util3.assert)( - isValid, - `$bucket: bounds must be of same type and in ascending order` - ); - (0, import_util3.assert)( - (0, import_util3.isNil)(defaultKey) || (0, import_util3.typeOf)(defaultKey) !== (0, import_util3.typeOf)(lower) || (0, import_util3.compare)(defaultKey, upper) >= 0 || (0, import_util3.compare)(defaultKey, lower) < 0, - "$bucket: 'default' expression must be out of boundaries range" - ); - const createBuckets = () => { - const buckets = /* @__PURE__ */ new Map(); - for (let i = 0; i < bounds.length - 1; i++) { - buckets.set(bounds[i], []); - } - if (!(0, import_util3.isNil)(defaultKey)) buckets.set(defaultKey, []); - coll.each((obj) => { - const key = (0, import_internal.evalExpr)(obj, expr.groupBy, options); - if ((0, import_util3.isNil)(key) || (0, import_util3.compare)(key, lower) < 0 || (0, import_util3.compare)(key, upper) >= 0) { - (0, import_util3.assert)( - !(0, import_util3.isNil)(defaultKey), - "$bucket require a default for out of range values" - ); - buckets.get(defaultKey)?.push(obj); - } else { - (0, import_util3.assert)( - (0, import_util3.compare)(key, lower) >= 0 && (0, import_util3.compare)(key, upper) < 0, - "$bucket 'groupBy' expression must resolve to a value in range of boundaries" - ); - const index = (0, import_util3.findInsertIndex)(bounds, key); - const boundKey = bounds[Math.max(0, index - 1)]; - buckets.get(boundKey)?.push(obj); - } - }); - bounds.pop(); - if (!(0, import_util3.isNil)(defaultKey)) { - if (buckets.get(defaultKey)?.length) bounds.push(defaultKey); - else buckets.delete(defaultKey); - } - (0, import_util3.assert)( - buckets.size === bounds.length, - "bounds and groups must be of equal size." - ); - return (0, import_lazy.Lazy)(bounds).map((key) => { - return { - ...(0, import_internal.evalExpr)(buckets.get(key), outputExpr, options), - _id: key - }; - }); - }; - let iterator; - return (0, import_lazy.Lazy)(() => { - if (!iterator) iterator = createBuckets(); - return iterator.next(); - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucketAuto.js -var require_bucketAuto = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucketAuto.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bucketAuto_exports = {}; - __export5(bucketAuto_exports, { - $bucketAuto: () => $bucketAuto - }); - module.exports = __toCommonJS(bucketAuto_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - function $bucketAuto(coll, expr, options) { - const { - buckets: bucketCount, - groupBy: groupByExpr, - output: optOutputExpr, - // Available only if the all groupBy values are numeric and none of them are NaN. - granularity - } = expr; - const outputExpr = optOutputExpr ?? { count: { $sum: 1 } }; - (0, import_util3.assert)( - bucketCount > 0, - `$bucketAuto: 'buckets' field must be greater than 0, but found: ${bucketCount}` - ); - if (granularity) { - (0, import_util3.assert)( - /^(POWERSOF2|1-2-5|E(6|12|24|48|96|192)|R(5|10|20|40|80))$/.test( - granularity - ), - `$bucketAuto: invalid granularity '${granularity}'.` - ); - } - const keyMap = /* @__PURE__ */ new Map(); - const setKey = !granularity ? (o, k) => keyMap.set(o, k) : (_, _2) => { - }; - const sorted = coll.map((o) => { - const k = (0, import_internal.evalExpr)(o, groupByExpr, options) ?? null; - (0, import_util3.assert)( - !granularity || (0, import_util3.isNumber)(k), - "$bucketAuto: groupBy values must be numeric when granularity is specified." - ); - setKey(o, k ?? null); - return [k ?? null, o]; - }).collect(); - sorted.sort((x, y) => { - if ((0, import_util3.isNil)(x[0])) return -1; - if ((0, import_util3.isNil)(y[0])) return 1; - return (0, import_util3.compare)(x[0], y[0]); - }); - let getNext; - if (!granularity) { - getNext = granularityDefault(sorted, bucketCount, keyMap); - } else if (granularity == "POWERSOF2") { - getNext = granularityPowerOfTwo( - sorted, - bucketCount - ); - } else { - getNext = granularityPreferredSeries( - sorted, - bucketCount, - granularity - ); - } - let terminate = false; - return (0, import_lazy.Lazy)(() => { - if (terminate) return { done: true }; - const { min, max, bucket, done } = getNext(); - terminate = done; - const outFields = (0, import_internal.evalExpr)(bucket, outputExpr, options); - for (const k of Object.keys(outFields)) { - const v = outFields[k]; - if ((0, import_util3.isArray)(v)) outFields[k] = v.filter((v2) => !(0, import_util3.isNil)(v2)); - } - return { - done: false, - value: { - ...outFields, - _id: { min, max } - } - }; - }); - } - function granularityDefault(sorted, bucketCount, keyMap) { - const size = sorted.length; - const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount)); - let index = 0; - let nBuckets = 0; - return () => { - const isLastBucket = ++nBuckets == bucketCount; - const bucket = new Array(); - while (index < size && (isLastBucket || bucket.length < approxBucketSize || index > 0 && (0, import_util3.isEqual)(sorted[index - 1][0], sorted[index][0]))) { - bucket.push(sorted[index++][1]); - } - const min = keyMap.get(bucket[0]); - let max; - if (index < size) { - max = sorted[index][0]; - } else { - max = keyMap.get(bucket[bucket.length - 1]); - } - (0, import_util3.assert)( - (0, import_util3.isNil)(max) || (0, import_util3.isNil)(min) || (0, import_util3.compare)(min, max) <= 0, - `error: $bucketAuto boundary must be in order.` - ); - return { - min, - max, - bucket, - done: index >= size - }; - }; - } - function granularityPowerOfTwo(sorted, bucketCount) { - const size = sorted.length; - const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount)); - const roundUp2 = (n) => n === 0 ? 0 : 2 ** (Math.floor(Math.log2(n)) + 1); - let index = 0; - let min = 0; - let max = 0; - return () => { - const bucket = new Array(); - const boundValue = roundUp2(max); - min = index > 0 ? max : 0; - while (bucket.length < approxBucketSize && index < size && (max === 0 || sorted[index][0] < boundValue)) { - bucket.push(sorted[index++][1]); - } - max = max == 0 ? roundUp2(sorted[index - 1][0]) : boundValue; - while (index < size && sorted[index][0] < max) { - bucket.push(sorted[index++][1]); - } - return { - min, - max, - bucket, - done: index >= size - }; - }; - } - var PREFERRED_NUMBERS = { - // "Least rounded" Renard number series, taken from Wikipedia page on preferred - // numbers: https://en.wikipedia.org/wiki/Preferred_number#Renard_numbers - R5: [10, 16, 25, 40, 63], - R10: [100, 125, 160, 200, 250, 315, 400, 500, 630, 800], - R20: [ - 100, - 112, - 125, - 140, - 160, - 180, - 200, - 224, - 250, - 280, - 315, - 355, - 400, - 450, - 500, - 560, - 630, - 710, - 800, - 900 - ], - R40: [ - 100, - 106, - 112, - 118, - 125, - 132, - 140, - 150, - 160, - 170, - 180, - 190, - 200, - 212, - 224, - 236, - 250, - 265, - 280, - 300, - 315, - 355, - 375, - 400, - 425, - 450, - 475, - 500, - 530, - 560, - 600, - 630, - 670, - 710, - 750, - 800, - 850, - 900, - 950 - ], - R80: [ - 103, - 109, - 115, - 122, - 128, - 136, - 145, - 155, - 165, - 175, - 185, - 195, - 206, - 218, - 230, - 243, - 258, - 272, - 290, - 307, - 325, - 345, - 365, - 387, - 412, - 437, - 462, - 487, - 515, - 545, - 575, - 615, - 650, - 690, - 730, - 775, - 825, - 875, - 925, - 975 - ], - // https://en.wikipedia.org/wiki/Preferred_number#1-2-5_series - "1-2-5": [10, 20, 50], - // E series, taken from Wikipedia page on preferred numbers: - // https://en.wikipedia.org/wiki/Preferred_number#E_series - E6: [10, 15, 22, 33, 47, 68], - E12: [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82], - E24: [ - 10, - 11, - 12, - 13, - 15, - 16, - 18, - 20, - 22, - 24, - 27, - 30, - 33, - 36, - 39, - 43, - 47, - 51, - 56, - 62, - 68, - 75, - 82, - 91 - ], - E48: [ - 100, - 105, - 110, - 115, - 121, - 127, - 133, - 140, - 147, - 154, - 162, - 169, - 178, - 187, - 196, - 205, - 215, - 226, - 237, - 249, - 261, - 274, - 287, - 301, - 316, - 332, - 348, - 365, - 383, - 402, - 422, - 442, - 464, - 487, - 511, - 536, - 562, - 590, - 619, - 649, - 681, - 715, - 750, - 787, - 825, - 866, - 909, - 953 - ], - E96: [ - 100, - 102, - 105, - 107, - 110, - 113, - 115, - 118, - 121, - 124, - 127, - 130, - 133, - 137, - 140, - 143, - 147, - 150, - 154, - 158, - 162, - 165, - 169, - 174, - 178, - 182, - 187, - 191, - 196, - 200, - 205, - 210, - 215, - 221, - 226, - 232, - 237, - 243, - 249, - 255, - 261, - 267, - 274, - 280, - 287, - 294, - 301, - 309, - 316, - 324, - 332, - 340, - 348, - 357, - 365, - 374, - 383, - 392, - 402, - 412, - 422, - 432, - 442, - 453, - 464, - 475, - 487, - 499, - 511, - 523, - 536, - 549, - 562, - 576, - 590, - 604, - 619, - 634, - 649, - 665, - 681, - 698, - 715, - 732, - 750, - 768, - 787, - 806, - 825, - 845, - 866, - 887, - 909, - 931, - 953, - 976 - ], - E192: [ - 100, - 101, - 102, - 104, - 105, - 106, - 107, - 109, - 110, - 111, - 113, - 114, - 115, - 117, - 118, - 120, - 121, - 123, - 124, - 126, - 127, - 129, - 130, - 132, - 133, - 135, - 137, - 138, - 140, - 142, - 143, - 145, - 147, - 149, - 150, - 152, - 154, - 156, - 158, - 160, - 162, - 164, - 165, - 167, - 169, - 172, - 174, - 176, - 178, - 180, - 182, - 184, - 187, - 189, - 191, - 193, - 196, - 198, - 200, - 203, - 205, - 208, - 210, - 213, - 215, - 218, - 221, - 223, - 226, - 229, - 232, - 234, - 237, - 240, - 243, - 246, - 249, - 252, - 255, - 258, - 261, - 264, - 267, - 271, - 274, - 277, - 280, - 284, - 287, - 291, - 294, - 298, - 301, - 305, - 309, - 312, - 316, - 320, - 324, - 328, - 332, - 336, - 340, - 344, - 348, - 352, - 357, - 361, - 365, - 370, - 374, - 379, - 383, - 388, - 392, - 397, - 402, - 407, - 412, - 417, - 422, - 427, - 432, - 437, - 442, - 448, - 453, - 459, - 464, - 470, - 475, - 481, - 487, - 493, - 499, - 505, - 511, - 517, - 523, - 530, - 536, - 542, - 549, - 556, - 562, - 569, - 576, - 583, - 590, - 597, - 604, - 612, - 619, - 626, - 634, - 642, - 649, - 657, - 665, - 673, - 681, - 690, - 698, - 706, - 715, - 723, - 732, - 741, - 750, - 759, - 768, - 777, - 787, - 796, - 806, - 816, - 825, - 835, - 845, - 856, - 866, - 876, - 887, - 898, - 909, - 920, - 931, - 942, - 953, - 965, - 976, - 988 - ] - }; - var roundUp = (n, granularity) => { - if (n == 0) return 0; - const series = PREFERRED_NUMBERS[granularity]; - const first = series[0]; - const last = series[series.length - 1]; - let multiplier = 1; - while (n >= last * multiplier) { - multiplier *= 10; - } - let previousMin = 0; - while (n < first * multiplier) { - previousMin = first * multiplier; - multiplier /= 10; - if (n >= last * multiplier) { - return previousMin; - } - } - (0, import_util3.assert)( - n >= first * multiplier && n < last * multiplier, - "$bucketAuto: number out of range of series." - ); - const i = (0, import_util3.findInsertIndex)(series, n, (a, b) => { - b *= multiplier; - if (a < b) return -1; - if (a > b) return 1; - return 0; - }); - const seriesNumber = series[i] * multiplier; - return n == seriesNumber ? series[i + 1] * multiplier : seriesNumber; - }; - function granularityPreferredSeries(sorted, bucketCount, granularity) { - const size = sorted.length; - const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount)); - let index = 0; - let nBuckets = 0; - let min = 0; - let max = 0; - return () => { - const isLastBucket = ++nBuckets == bucketCount; - const bucket = new Array(); - min = index > 0 ? max : 0; - while (index < size && (isLastBucket || bucket.length < approxBucketSize)) { - bucket.push(sorted[index++][1]); - } - max = roundUp(sorted[index - 1][0], granularity); - const nItems = bucket.length; - while (index < size && (isLastBucket || sorted[index][0] < max)) { - bucket.push(sorted[index++][1]); - } - if (nItems != bucket.length) { - max = roundUp(sorted[index - 1][0], granularity); - } - (0, import_util3.assert)(min < max, `$bucketAuto: ${min} < ${max}.`); - return { min, max, bucket, done: index >= size }; - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/count.js -var require_count2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/count.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var count_exports = {}; - __export5(count_exports, { - $count: () => $count - }); - module.exports = __toCommonJS(count_exports); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - function $count(coll, expr, _options2) { - (0, import_util3.assert)( - (0, import_util3.isString)(expr) && expr.trim().length > 0 && !expr.includes(".") && expr[0] !== "$", - "$count expression must evaluate to valid field name" - ); - let i = 0; - return (0, import_lazy.Lazy)(() => { - if (i++ == 0) return { value: { [expr]: coll.size() }, done: false }; - return { done: true }; - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/densify.js -var require_densify = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/densify.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var densify_exports = {}; - __export5(densify_exports, { - $densify: () => $densify - }); - module.exports = __toCommonJS(densify_exports); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - var import_internal = require_internal8(); - var import_dateAdd = require_dateAdd(); - var import_sort = require_sort(); - var OP = "$densify"; - function $densify(coll, expr, options) { - const { step, bounds, unit } = expr.range; - if (unit) { - (0, import_util3.assert)( - import_internal.TIME_UNITS.includes(unit), - `${OP} 'range.unit' value is not supported.` - ); - (0, import_util3.assert)( - (0, import_util3.isInteger)(step) && step > 0, - `${OP} 'range.step' must resolve to integer if 'range.unit' is specified.` - ); - } else { - (0, import_util3.assert)((0, import_util3.isNumber)(step), `${OP} 'range.step' must resolve to number.`); - } - if ((0, import_util3.isArray)(bounds)) { - (0, import_util3.assert)( - !!bounds && bounds.length === 2, - `${OP} 'range.bounds' must have exactly two elements.` - ); - (0, import_util3.assert)( - (bounds.every(import_util3.isNumber) || bounds.every(import_util3.isDate)) && bounds[0] < bounds[1], - `${OP} 'range.bounds' must be ordered lower then upper.` - ); - if (unit) { - (0, import_util3.assert)( - bounds.every(import_util3.isDate), - `${OP} 'range.bounds' must be dates if 'range.unit' is specified.` - ); - } - } - if (expr.partitionByFields) { - (0, import_util3.assert)( - (0, import_util3.isArray)(expr.partitionByFields), - `${OP} 'partitionByFields' must resolve to array of strings.` - ); - } - const partitionByFields = expr.partitionByFields ?? []; - coll = (0, import_sort.$sort)(coll, { [expr.field]: 1 }, options); - const computeNextValue = (value) => { - return (0, import_util3.isNumber)(value) ? value + step : (0, import_dateAdd.$dateAdd)({}, { startDate: value, unit, amount: step }, options); - }; - const isValidUnit = !!unit && import_internal.TIME_UNITS.includes(unit); - const getFieldValue = (o) => { - const v = (0, import_util3.resolve)(o, expr.field); - (0, import_util3.assert)( - (0, import_util3.isNil)(v) || (0, import_util3.isDate)(v) && isValidUnit || (0, import_util3.isNumber)(v) && !isValidUnit, - `${OP} Densify field type must be numeric with 'unit' unspecified, or a date with 'unit' specified.` - ); - return v; - }; - const peekItem = new Array(); - const nilFieldsIterator = (0, import_lazy.Lazy)(() => { - const item = coll.next(); - const fieldValue = getFieldValue(item.value); - if ((0, import_util3.isNil)(fieldValue)) return item; - peekItem.push(item); - return { done: true }; - }); - const nextDensifyValueMap = import_util3.HashMap.init(); - const [lower, upper] = (0, import_util3.isArray)(bounds) ? bounds : [bounds, bounds]; - let maxFieldValue; - const updateMaxFieldValue = (value) => { - maxFieldValue = maxFieldValue === void 0 || maxFieldValue < value ? value : maxFieldValue; - }; - const rootKey = []; - const densifyIterator = (0, import_lazy.Lazy)(() => { - const item = peekItem.pop() || coll.next(); - if (item.done) return item; - let partitionKey = rootKey; - if ((0, import_util3.isArray)(partitionByFields)) { - partitionKey = partitionByFields.map( - (k) => (0, import_util3.resolve)(item.value, k) - ); - (0, import_util3.assert)( - partitionKey.every(import_util3.isString), - "$densify: Partition fields must evaluate to string values." - ); - } - (0, import_util3.assert)((0, import_util3.isObject)(item.value), "$densify: collection must contain documents"); - const itemValue = getFieldValue(item.value); - if (!nextDensifyValueMap.has(partitionKey)) { - if (lower == "full") { - if (!nextDensifyValueMap.has(rootKey)) { - nextDensifyValueMap.set(rootKey, itemValue); - } - nextDensifyValueMap.set( - partitionKey, - nextDensifyValueMap.get(rootKey) - ); - } else if (lower == "partition") { - nextDensifyValueMap.set(partitionKey, itemValue); - } else { - nextDensifyValueMap.set(partitionKey, lower); - } - } - const densifyValue = nextDensifyValueMap.get(partitionKey); - if ( - // current item field value is lower than current densify value. - itemValue <= densifyValue || // range value equals or exceeds upper bound - upper != "full" && upper != "partition" && densifyValue >= upper - ) { - if (densifyValue <= itemValue) { - nextDensifyValueMap.set(partitionKey, computeNextValue(densifyValue)); - } - updateMaxFieldValue(itemValue); - return item; - } - nextDensifyValueMap.set(partitionKey, computeNextValue(densifyValue)); - updateMaxFieldValue(densifyValue); - const denseObj = { [expr.field]: densifyValue }; - if (partitionKey) { - for (let i = 0; i < partitionKey.length; i++) { - denseObj[partitionByFields[i]] = partitionKey[i]; - } - } - peekItem.push(item); - return { done: false, value: denseObj }; - }); - if (lower !== "full") return (0, import_lazy.concat)(nilFieldsIterator, densifyIterator); - let paritionIndex = -1; - let partitionKeysSet; - const fullBoundsIterator = (0, import_lazy.Lazy)(() => { - if (paritionIndex === -1) { - const fullDensifyValue = nextDensifyValueMap.get(rootKey); - nextDensifyValueMap.delete(rootKey); - partitionKeysSet = Array.from(nextDensifyValueMap.keys()); - if (partitionKeysSet.length === 0) { - partitionKeysSet.push(rootKey); - nextDensifyValueMap.set(rootKey, fullDensifyValue); - } - paritionIndex++; - } - do { - const partitionKey = partitionKeysSet[paritionIndex]; - const partitionMaxValue = nextDensifyValueMap.get(partitionKey); - if (partitionMaxValue < maxFieldValue) { - nextDensifyValueMap.set( - partitionKey, - computeNextValue(partitionMaxValue) - ); - const denseObj = { [expr.field]: partitionMaxValue }; - for (let i = 0; i < partitionKey.length; i++) { - denseObj[partitionByFields[i]] = partitionKey[i]; - } - return { done: false, value: denseObj }; - } - paritionIndex++; - } while (paritionIndex < partitionKeysSet.length); - return { done: true }; - }); - return (0, import_lazy.concat)(nilFieldsIterator, densifyIterator, fullBoundsIterator); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/facet.js -var require_facet = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/facet.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var facet_exports = {}; - __export5(facet_exports, { - $facet: () => $facet - }); - module.exports = __toCommonJS(facet_exports); - var import_aggregator = require_aggregator(); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - function $facet(coll, expr, options) { - if (!(options.processingMode & import_internal.ProcessingMode.CLONE_INPUT)) { - options = { - ...import_internal.ComputeOptions.init(options).options, - processingMode: import_internal.ProcessingMode.CLONE_INPUT - }; - } - return coll.transform((arr) => { - const o = {}; - for (const k of Object.keys(expr)) { - o[k] = new import_aggregator.Aggregator(expr[k], options).run(arr); - } - return (0, import_lazy.Lazy)([o]); - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/_internal.js -var require_internal12 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - cached: () => cached2, - rank: () => rank, - withMemo: () => withMemo - }); - module.exports = __toCommonJS(internal_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var memo = /* @__PURE__ */ new WeakMap(); - var cached2 = (xs) => memo.has(xs); - function withMemo(collection, expr, initialize, fn) { - if (!memo.has(collection)) { - memo.set(collection, {}); - } - const data = memo.get(collection); - if (!(expr.field in data)) { - data[expr.field] = initialize(); - } - let ok2 = false; - try { - const res = fn(data[expr.field]); - ok2 = true; - return res; - } finally { - if (!ok2) { - memo.delete(collection); - } else if (expr.documentNumber === collection.length) { - delete data[expr.field]; - if (Object.keys(data).length === 0) memo.delete(collection); - } - } - } - function rank(_, collection, expr, options, dense) { - return withMemo( - collection, - expr, - () => { - const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0]; - const values = (0, import_push.$push)(collection, sortKey, options); - const groups = (0, import_util3.groupBy)( - values, - (_2, n) => values[n] - ); - let i = 0; - let offset = 0; - for (const key of groups.keys()) { - const len = groups.get(key).length; - groups.set(key, [i++, offset]); - offset += len; - } - return { values, groups }; - }, - ({ values, groups }) => { - if (groups.size == collection.length) return expr.documentNumber; - const current = values[expr.documentNumber - 1]; - const [i, n] = groups.get(current); - return (dense ? i : n) + 1; - } - ); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/linearFill.js -var require_linearFill = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/linearFill.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var linearFill_exports = {}; - __export5(linearFill_exports, { - $linearFill: () => $linearFill - }); - module.exports = __toCommonJS(linearFill_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var import_internal = require_internal12(); - var interpolate = (x1, y1, x2, y2, x) => y1 + (x - x1) * ((y2 - y1) / (x2 - x1)); - var $linearFill = (_, coll, expr, options) => { - return (0, import_internal.withMemo)( - coll, - expr, - () => { - const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0]; - const points = (0, import_push.$push)(coll, [sortKey, expr.inputExpr], options).filter(([ - x, - _2 - ]) => (0, import_util3.isNumber)(+x)); - let lindex = -1; - let rindex = 0; - while (rindex < points.length) { - while (lindex + 1 < points.length && (0, import_util3.isNumber)(points[lindex + 1][1])) { - lindex++; - rindex = lindex; - } - while (rindex + 1 < points.length && !(0, import_util3.isNumber)(points[rindex + 1][1])) { - rindex++; - } - if (rindex + 1 >= points.length) break; - rindex++; - while (lindex + 1 < rindex) { - points[lindex + 1][1] = interpolate( - points[lindex][0], - points[lindex][1], - points[rindex][0], - points[rindex][1], - points[lindex + 1][0] - ); - lindex++; - } - lindex = rindex; - } - return points.map(([_2, y]) => y); - }, - (values) => values[expr.documentNumber - 1] - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/locf.js -var require_locf = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/locf.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var locf_exports = {}; - __export5(locf_exports, { - $locf: () => $locf - }); - module.exports = __toCommonJS(locf_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var import_internal = require_internal12(); - var $locf = (_, coll, expr, options) => { - return (0, import_internal.withMemo)( - coll, - expr, - () => { - const values = (0, import_push.$push)(coll, expr.inputExpr, options); - for (let i = 1; i < values.length; i++) { - if ((0, import_util3.isNil)(values[i])) values[i] = values[i - 1]; - } - return values; - }, - (series) => series[expr.documentNumber - 1] - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/group.js -var require_group = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/group.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var group_exports = {}; - __export5(group_exports, { - $group: () => $group - }); - module.exports = __toCommonJS(group_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - var ID_KEY = "_id"; - function $group(coll, expr, options) { - (0, import_util3.assert)((0, import_util3.has)(expr, ID_KEY), "$group specification must include an '_id'"); - const idExpr = expr[ID_KEY]; - const copts = import_internal.ComputeOptions.init(options); - const newFields = Object.keys(expr).filter((k) => k != ID_KEY); - return coll.transform((items) => { - const partitions = (0, import_util3.groupBy)(items, (obj) => (0, import_internal.evalExpr)(obj, idExpr, options)); - let i = -1; - const partitionKeys = Array.from(partitions.keys()); - return (0, import_lazy.Lazy)(() => { - if (++i === partitions.size) return { done: true }; - const groupId = partitionKeys[i]; - const obj = {}; - if (groupId !== void 0) { - obj[ID_KEY] = groupId; - } - for (const key of newFields) { - obj[key] = (0, import_internal.evalExpr)( - partitions.get(groupId), - expr[key], - copts.update({ root: null, groupId }) - ); - } - return { value: obj, done: false }; - }); - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/setWindowFields.js -var require_setWindowFields = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/setWindowFields.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var setWindowFields_exports = {}; - __export5(setWindowFields_exports, { - $setWindowFields: () => $setWindowFields - }); - module.exports = __toCommonJS(setWindowFields_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - var import_function = require_function(); - var import_dateAdd = require_dateAdd(); - var import_addFields = require_addFields(); - var import_group = require_group(); - var import_sort = require_sort(); - var SORT_REQUIRED_OPS = [ - "$denseRank", - "$documentNumber", - "$first", - "$last", - "$linearFill", - "$rank", - "$shift" - ]; - var WINDOW_UNBOUNDED_OPS = [ - "$denseRank", - "$expMovingAvg", - "$linearFill", - "$locf", - "$rank", - "$shift" - ]; - var isUnbounded = (window2) => { - const boundary = window2?.documents || window2?.range; - return !boundary || boundary[0] === "unbounded" && boundary[1] === "unbounded"; - }; - var OP = "$setWindowFields"; - function $setWindowFields(coll, expr, options) { - options = import_internal.ComputeOptions.init(options); - options.context.addExpressionOps({ $function: import_function.$function }); - const operators = {}; - const outputFields = Object.keys(expr.output); - for (const field of outputFields) { - const outputExpr = expr.output[field]; - const keys = Object.keys(outputExpr); - const op = keys.find(import_util3.isOperator); - const context = options.context; - (0, import_util3.assert)( - op && (!!context.getOperator(import_internal.OpType.WINDOW, op) || !!context.getOperator(import_internal.OpType.ACCUMULATOR, op)), - `${OP} '${op}' is not a valid window operator` - ); - (0, import_util3.assert)( - keys.length > 0 && keys.length <= 2 && (keys.length == 1 || keys.includes("window")), - `${OP} 'output' option should have a single window operator.` - ); - if (outputExpr?.window) { - const { documents, range } = outputExpr.window; - (0, import_util3.assert)( - (+!!documents ^ +!!range) === 1, - "'window' option supports only one of 'documents' or 'range'." - ); - } - operators[field] = op; - } - if (expr.sortBy) { - coll = (0, import_sort.$sort)(coll, expr.sortBy, options); - } - coll = (0, import_group.$group)( - coll, - { - _id: expr.partitionBy, - items: { $push: "$$CURRENT" } - }, - options - ); - return coll.transform((partitions) => { - const iterators = []; - const outputConfig = []; - for (const field of outputFields) { - const outputExpr = expr.output[field]; - const op = operators[field]; - const config4 = { - operatorName: op, - func: { - left: options.context.getOperator(import_internal.OpType.ACCUMULATOR, op), - right: options.context.getOperator(import_internal.OpType.WINDOW, op) - }, - args: outputExpr[op], - field, - window: outputExpr.window - }; - const unbounded = isUnbounded(config4.window); - if (unbounded == false || SORT_REQUIRED_OPS.includes(op)) { - const suffix = unbounded ? `'${op}'` : "bounded window operations"; - (0, import_util3.assert)(expr.sortBy, `${OP} 'sortBy' is required for ${suffix}.`); - } - (0, import_util3.assert)( - unbounded || !WINDOW_UNBOUNDED_OPS.includes(op), - `${OP} cannot use bounded window for operator '${op}'.` - ); - outputConfig.push(config4); - } - for (const group of partitions) { - const items = group.items; - let iterator = (0, import_lazy.Lazy)(items); - const windowResultMap = {}; - for (const config4 of outputConfig) { - const { func, args, field, window: window2 } = config4; - const makeResultFunc = (getItemsFn) => { - let index = -1; - return (obj) => { - ++index; - if (func.left) { - return func.left(getItemsFn(obj, index), args, options); - } else if (func.right) { - return func.right( - obj, - getItemsFn(obj, index), - { - parentExpr: expr, - inputExpr: args, - documentNumber: index + 1, - field - }, - // must use raw options only since it operates over a collection. - options - ); - } - }; - }; - if (window2) { - const { documents, range, unit } = window2; - const boundary = documents || range; - if (!isUnbounded(window2)) { - const [begin, end] = boundary; - const toBeginIndex = (currentIndex) => { - if (begin == "current") return currentIndex; - if (begin == "unbounded") return 0; - return Math.max(begin + currentIndex, 0); - }; - const toEndIndex = (currentIndex) => { - if (end == "current") return currentIndex + 1; - if (end == "unbounded") return items.length; - return end + currentIndex + 1; - }; - const getItems = (current, index) => { - if (!!documents || boundary?.every(import_util3.isString)) { - return items.slice(toBeginIndex(index), toEndIndex(index)); - } - const sortKey = Object.keys(expr.sortBy)[0]; - let lower; - let upper; - if (unit) { - const startDate = new Date(current[sortKey]); - const getTime = (amount) => { - const addExpr = { startDate, unit, amount }; - const d = (0, import_dateAdd.$dateAdd)(current, addExpr, options); - return d.getTime(); - }; - lower = (0, import_util3.isNumber)(begin) ? getTime(begin) : -Infinity; - upper = (0, import_util3.isNumber)(end) ? getTime(end) : Infinity; - } else { - const currentValue = current[sortKey]; - lower = (0, import_util3.isNumber)(begin) ? currentValue + begin : -Infinity; - upper = (0, import_util3.isNumber)(end) ? currentValue + end : Infinity; - } - let i = begin == "current" ? index : 0; - const sliceEnd = end == "current" ? index + 1 : items.length; - const array2 = new Array(); - while (i < sliceEnd) { - const o = items[i++]; - const n = +o[sortKey]; - if (n >= lower && n <= upper) array2.push(o); - } - return array2; - }; - windowResultMap[field] = makeResultFunc(getItems); - } - } - if (!windowResultMap[field]) { - windowResultMap[field] = makeResultFunc((_) => items); - } - iterator = (0, import_addFields.$addFields)( - iterator, - { - [field]: { - $function: { - body: (obj) => windowResultMap[field](obj), - args: ["$$CURRENT"] - } - } - }, - options - ); - } - iterators.push(iterator); - } - return (0, import_lazy.concat)(...iterators); - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/fill.js -var require_fill = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/fill.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var fill_exports = {}; - __export5(fill_exports, { - $fill: () => $fill - }); - module.exports = __toCommonJS(fill_exports); - var import_util3 = require_util(); - var import_ifNull = require_ifNull(); - var import_linearFill = require_linearFill(); - var import_locf = require_locf(); - var import_addFields = require_addFields(); - var import_setWindowFields = require_setWindowFields(); - var FILL_METHODS = { locf: "$locf", linear: "$linearFill" }; - function $fill(coll, expr, options) { - (0, import_util3.assert)(!expr.sortBy || (0, import_util3.isObject)(expr.sortBy), "sortBy must be an object."); - (0, import_util3.assert)( - !!expr.sortBy || Object.values(expr.output).every((m) => (0, import_util3.has)(m, "value")), - "sortBy required if any output field specifies a 'method'." - ); - (0, import_util3.assert)( - !(expr.partitionBy && expr.partitionByFields), - "specify either partitionBy or partitionByFields." - ); - (0, import_util3.assert)( - !expr.partitionByFields || expr?.partitionByFields?.every((s) => s[0] !== "$"), - "fields in partitionByFields cannot begin with '$'." - ); - options.context.addExpressionOps({ $ifNull: import_ifNull.$ifNull }); - options.context.addWindowOps({ $locf: import_locf.$locf, $linearFill: import_linearFill.$linearFill }); - const partitionExpr = expr.partitionBy || expr?.partitionByFields?.map((s) => "$" + s); - const valueExpr = {}; - const methodExpr = {}; - for (const k of Object.keys(expr.output)) { - const m = expr.output[k]; - if ((0, import_util3.has)(m, "value")) { - const out = m; - valueExpr[k] = { $ifNull: [`$$CURRENT.${k}`, out.value] }; - } else { - const out = m; - const fillOp = FILL_METHODS[out.method]; - (0, import_util3.assert)(!!fillOp, `invalid fill method '${out.method}'.`); - methodExpr[k] = { [fillOp]: "$" + k }; - } - } - if (Object.keys(methodExpr).length > 0) { - coll = (0, import_setWindowFields.$setWindowFields)( - coll, - { - sortBy: expr.sortBy || {}, - partitionBy: partitionExpr, - output: methodExpr - }, - options - ); - } - if (Object.keys(valueExpr).length > 0) { - coll = (0, import_addFields.$addFields)(coll, valueExpr, options); - } - return coll; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/lookup.js -var require_lookup = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/lookup.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var lookup_exports = {}; - __export5(lookup_exports, { - $lookup: () => $lookup - }); - module.exports = __toCommonJS(lookup_exports); - var import_aggregator = require_aggregator(); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_internal2 = require_internal7(); - function $lookup(coll, expr, options) { - const { let: letExpr, foreignField, localField } = expr; - let lookupEq = (_) => [true, []]; - let joinColl = (0, import_util3.isString)(expr.from) ? (0, import_internal2.resolveCollection)("$lookup", expr.from, options) : expr.from; - const { documents, pipeline } = (0, import_internal2.filterDocumentsStage)( - expr.pipeline ?? [], - options - ); - (0, import_util3.assert)( - !joinColl !== !documents, - "$lookup: must specify single join input with `expr.from` or `expr.pipeline`." - ); - joinColl = joinColl ?? documents; - (0, import_util3.assert)( - (0, import_util3.isArray)(joinColl), - "$lookup: join collection must resolve to an array." - ); - if (foreignField && localField) { - const map3 = import_util3.HashMap.init(); - for (const doc of joinColl) { - for (const v of (0, import_util3.ensureArray)((0, import_util3.resolve)(doc, foreignField) ?? null)) { - const xs = map3.get(v); - const arr = xs ?? []; - arr.push(doc); - if (arr !== xs) map3.set(v, arr); - } - } - lookupEq = (o) => { - const local = (0, import_util3.resolve)(o, localField) ?? null; - if ((0, import_util3.isArray)(local)) { - if (pipeline?.length) { - return [local.some((v) => map3.has(v)), []]; - } - const result2 = Array.from(new Set((0, import_util3.flatten)(local.map((v) => map3.get(v))))); - return [result2.length > 0, result2]; - } - const result = map3.get(local) ?? null; - return [result !== null, result ?? []]; - }; - if (pipeline?.length === 0) { - return coll.map((obj) => { - return { ...obj, [expr.as]: lookupEq(obj).pop() }; - }); - } - } - const agg = new import_aggregator.Aggregator(pipeline ?? [], options); - const opts = import_internal.ComputeOptions.init(options); - return coll.map((obj) => { - const vars = (0, import_internal.evalExpr)(obj, letExpr, options); - opts.update({ root: null, variables: vars }); - const [ok2, res] = lookupEq(obj); - return { ...obj, [expr.as]: ok2 ? agg.run(joinColl, opts) : res }; - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/graphLookup.js -var require_graphLookup = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/graphLookup.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var graphLookup_exports = {}; - __export5(graphLookup_exports, { - $graphLookup: () => $graphLookup - }); - module.exports = __toCommonJS(graphLookup_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - var import_internal2 = require_internal7(); - var import_lookup = require_lookup(); - function $graphLookup(coll, expr, options) { - const fromColl = (0, import_internal2.resolveCollection)("$graphLookup", expr.from, options); - (0, import_util3.assert)( - (0, import_util3.isArray)(fromColl), - "$graphLookup: expression 'from' must resolve to array" - ); - const { - connectFromField, - connectToField, - as: asField, - maxDepth, - depthField, - restrictSearchWithMatch: matchExpr - } = expr; - const pipelineExpr = matchExpr ? { pipeline: [{ $match: matchExpr }] } : {}; - return coll.map((obj) => { - const matchObj = {}; - (0, import_util3.setValue)( - matchObj, - connectFromField, - (0, import_internal.evalExpr)(obj, expr.startWith, options) - ); - let matches = [matchObj]; - let i = -1; - const map3 = import_util3.HashMap.init(); - do { - i++; - matches = (0, import_util3.flatten)( - (0, import_lookup.$lookup)( - (0, import_lazy.Lazy)(matches), - { - from: fromColl, - localField: connectFromField, - foreignField: connectToField, - as: asField, - ...pipelineExpr - }, - options - ).map((o) => o[asField]).collect() - ); - const oldSize = map3.size; - for (const k of matches) map3.set(k, map3.get(k) ?? i); - if (oldSize == map3.size) break; - } while ((0, import_util3.isNil)(maxDepth) || i < maxDepth); - const result = new Array(map3.size); - let n = 0; - for (const [k, v] of map3.entries()) { - result[n++] = Object.assign(depthField ? { [depthField]: v } : {}, k); - } - return { ...obj, [asField]: result }; - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/match.js -var require_match = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/match.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var match_exports = {}; - __export5(match_exports, { - $match: () => $match - }); - module.exports = __toCommonJS(match_exports); - var import_query = require_query(); - function $match(coll, expr, options) { - const q = new import_query.Query(expr, options); - return coll.filter((o) => q.test(o)); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/merge.js -var require_merge = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/merge.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var merge_exports = {}; - __export5(merge_exports, { - $merge: () => $merge - }); - module.exports = __toCommonJS(merge_exports); - var import_aggregator = require_aggregator(); - var import_internal = require_internal2(); - var import_util3 = require_util(); - var import_expression3 = require_expression(); - var import_internal2 = require_internal7(); - function $merge(coll, expr, options) { - const output = (0, import_internal2.resolveCollection)("$merge", expr.into, options); - (0, import_util3.assert)((0, import_util3.isArray)(output), `$merge: expression 'into' must resolve to an array`); - const onField = expr.on || options.idKey; - const getHash = (0, import_util3.isString)(onField) ? (o) => (0, import_util3.hashCode)((0, import_util3.resolve)(o, onField)) : (o) => (0, import_util3.hashCode)(onField.map((s) => (0, import_util3.resolve)(o, s))); - const map3 = import_util3.HashMap.init(); - for (let i = 0; i < output.length; i++) { - const obj = output[i]; - const k = getHash(obj); - (0, import_util3.assert)( - !map3.has(k), - "$merge: 'into' collection must have unique entries for the 'on' field." - ); - map3.set(k, [obj, i]); - } - const copts = import_internal.ComputeOptions.init(options); - return coll.map((o) => { - const k = getHash(o); - if (map3.has(k)) { - const [target, i] = map3.get(k); - const variables = (0, import_internal.evalExpr)( - target, - expr.let || { new: "$$ROOT" }, - // 'root' is the item from the iteration. - copts.update({ root: o }) - ); - if ((0, import_util3.isArray)(expr.whenMatched)) { - const aggregator = new import_aggregator.Aggregator( - expr.whenMatched, - copts.update({ root: null, variables }) - ); - output[i] = aggregator.run([target])[0]; - } else { - switch (expr.whenMatched) { - case "replace": - output[i] = o; - break; - case "fail": - throw new import_util3.MingoError( - "$merge: failed due to matching as specified by 'whenMatched' option." - ); - case "keepExisting": - break; - case "merge": - default: - output[i] = (0, import_expression3.$mergeObjects)( - target, - [target, o], - // 'root' is the item from the iteration. - copts.update({ root: o, variables }) - ); - break; - } - } - } else { - switch (expr.whenNotMatched) { - case "discard": - break; - case "fail": - throw new import_util3.MingoError( - "$merge: failed due to matching as specified by 'whenMatched' option." - ); - case "insert": - default: - output.push(o); - break; - } - } - return o; - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/out.js -var require_out = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/out.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var out_exports = {}; - __export5(out_exports, { - $out: () => $out - }); - module.exports = __toCommonJS(out_exports); - var import_util3 = require_util(); - var import_internal = require_internal7(); - function $out(coll, expr, options) { - const out = (0, import_internal.resolveCollection)("$out", expr, options); - (0, import_util3.assert)((0, import_util3.isArray)(out), `$out: expression must resolve to an array`); - return coll.map((o) => { - out.push((0, import_util3.cloneDeep)(o)); - return o; - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/redact.js -var require_redact = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/redact.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var redact_exports = {}; - __export5(redact_exports, { - $redact: () => $redact - }); - module.exports = __toCommonJS(redact_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - function $redact(coll, expr, options) { - const copts = import_internal.ComputeOptions.init(options); - return coll.map( - (root) => redact(root, expr, copts.update({ root })) - ); - } - function redact(obj, expr, options) { - const action = (0, import_internal.evalExpr)(obj, expr, options); - switch (action) { - case "$$KEEP": - return obj; - case "$$PRUNE": - return void 0; - case "$$DESCEND": { - if (!(0, import_util3.has)(expr, "$cond")) return obj; - const output = {}; - for (const key of Object.keys(obj)) { - const value = obj[key]; - if ((0, import_util3.isArray)(value)) { - const res = new Array(); - for (let elem of value) { - if ((0, import_util3.isObject)(elem)) { - elem = redact(elem, expr, options.update({ root: elem })); - } - if (!(0, import_util3.isNil)(elem)) res.push(elem); - } - output[key] = res; - } else if ((0, import_util3.isObject)(value)) { - const res = redact( - value, - expr, - options.update({ root: value }) - ); - if (!(0, import_util3.isNil)(res)) output[key] = res; - } else { - output[key] = value; - } - } - return output; - } - default: - return action; - } - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceRoot.js -var require_replaceRoot = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceRoot.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var replaceRoot_exports = {}; - __export5(replaceRoot_exports, { - $replaceRoot: () => $replaceRoot - }); - module.exports = __toCommonJS(replaceRoot_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - function $replaceRoot(coll, expr, options) { - return coll.map((obj) => { - obj = (0, import_internal.evalExpr)(obj, expr.newRoot, options); - (0, import_util3.assert)((0, import_util3.isObject)(obj), "$replaceRoot expression must return an object"); - return obj; - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceWith.js -var require_replaceWith = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceWith.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var replaceWith_exports = {}; - __export5(replaceWith_exports, { - $replaceWith: () => $replaceWith - }); - module.exports = __toCommonJS(replaceWith_exports); - var import_internal = require_internal2(); - var import_util3 = require_util(); - function $replaceWith(coll, expr, options) { - return coll.map((obj) => { - obj = (0, import_internal.evalExpr)(obj, expr, options); - (0, import_util3.assert)((0, import_util3.isObject)(obj), "$replaceWith expression must return an object"); - return obj; - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sample.js -var require_sample = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sample.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sample_exports = {}; - __export5(sample_exports, { - $sample: () => $sample - }); - module.exports = __toCommonJS(sample_exports); - var import_lazy = require_lazy(); - function $sample(coll, expr, _options2) { - return coll.transform((xs) => { - const len = xs.length; - let i = -1; - return (0, import_lazy.Lazy)(() => { - if (++i === expr.size) return { done: true }; - const n = Math.floor(Math.random() * len); - return { value: xs[n], done: false }; - }); - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/set.js -var require_set2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/set.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var set_exports = {}; - __export5(set_exports, { - $set: () => $set - }); - module.exports = __toCommonJS(set_exports); - var import_addFields = require_addFields(); - var $set = import_addFields.$addFields; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sortByCount.js -var require_sortByCount = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sortByCount.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var sortByCount_exports = {}; - __export5(sortByCount_exports, { - $sortByCount: () => $sortByCount - }); - module.exports = __toCommonJS(sortByCount_exports); - var import_group = require_group(); - var import_sort = require_sort(); - function $sortByCount(coll, expr, options) { - return (0, import_sort.$sort)( - (0, import_group.$group)(coll, { _id: expr, count: { $sum: 1 } }, options), - { count: -1 }, - options - ); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unionWith.js -var require_unionWith = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unionWith.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var unionWith_exports = {}; - __export5(unionWith_exports, { - $unionWith: () => $unionWith - }); - module.exports = __toCommonJS(unionWith_exports); - var import_aggregator = require_aggregator(); - var import_lazy = require_lazy(); - var import_util3 = require_util(); - var import_internal = require_internal7(); - function $unionWith(collection, expr, options) { - const { coll: inputColl, pipeline: stages } = (0, import_util3.isString)(expr) || (0, import_util3.isArray)(expr) ? { coll: expr } : expr; - const docsFromInput = (0, import_util3.isString)(inputColl) ? (0, import_internal.resolveCollection)("$unionWith", inputColl, options) : inputColl; - const { documents, pipeline } = (0, import_internal.filterDocumentsStage)(stages, options); - (0, import_util3.assert)( - docsFromInput || documents, - "$unionWith must specify single collection input with `expr.coll` or `expr.pipeline`." - ); - const xs = docsFromInput ?? documents; - return (0, import_lazy.concat)( - collection, - pipeline ? new import_aggregator.Aggregator(pipeline, options).stream(xs) : (0, import_lazy.Lazy)(xs) - ); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unset.js -var require_unset = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unset.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var unset_exports = {}; - __export5(unset_exports, { - $unset: () => $unset - }); - module.exports = __toCommonJS(unset_exports); - var import_util3 = require_util(); - var import_project = require_project(); - function $unset(coll, expr, options) { - expr = (0, import_util3.ensureArray)(expr); - const doc = {}; - for (const k of expr) doc[k] = 0; - return (0, import_project.$project)(coll, doc, options); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unwind.js -var require_unwind = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unwind.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var unwind_exports = {}; - __export5(unwind_exports, { - $unwind: () => $unwind - }); - module.exports = __toCommonJS(unwind_exports); - var import_lazy = require_lazy(); - var import_internal = require_internal(); - function $unwind(coll, expr, _options2) { - if ((0, import_internal.isString)(expr)) expr = { path: expr }; - const path3 = expr.path; - const field = path3.substring(1); - const includeArrayIndex = expr?.includeArrayIndex || false; - const preserveNullAndEmptyArrays = expr.preserveNullAndEmptyArrays || false; - const format = (o, i) => { - if (includeArrayIndex !== false) o[includeArrayIndex] = i; - return o; - }; - let value; - return (0, import_lazy.Lazy)(() => { - for (; ; ) { - if (value instanceof import_lazy.Iterator) { - const tmp = value.next(); - if (!tmp.done) return tmp; - } - const wrapper = coll.next(); - if (wrapper.done) return wrapper; - const obj = wrapper.value; - value = (0, import_internal.resolve)(obj, field); - if ((0, import_internal.isArray)(value)) { - if (value.length === 0 && preserveNullAndEmptyArrays === true) { - value = null; - (0, import_internal.removeValue)(obj, field); - return { value: format(obj, null), done: false }; - } else { - value = (0, import_lazy.Lazy)(value).map((item, i) => { - const newObj = (0, import_internal.resolveGraph)(obj, field, { - preserveKeys: true - }); - (0, import_internal.setValue)(newObj, field, item); - return format(newObj, i); - }); - } - } else if (!(0, import_internal.isEmpty)(value) || preserveNullAndEmptyArrays === true) { - return { value: format(obj, null), done: false }; - } - } - }); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/index.js -var require_pipeline = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var pipeline_exports = {}; - module.exports = __toCommonJS(pipeline_exports); - __reExport(pipeline_exports, require_addFields(), module.exports); - __reExport(pipeline_exports, require_bucket(), module.exports); - __reExport(pipeline_exports, require_bucketAuto(), module.exports); - __reExport(pipeline_exports, require_count2(), module.exports); - __reExport(pipeline_exports, require_densify(), module.exports); - __reExport(pipeline_exports, require_documents(), module.exports); - __reExport(pipeline_exports, require_facet(), module.exports); - __reExport(pipeline_exports, require_fill(), module.exports); - __reExport(pipeline_exports, require_graphLookup(), module.exports); - __reExport(pipeline_exports, require_group(), module.exports); - __reExport(pipeline_exports, require_limit(), module.exports); - __reExport(pipeline_exports, require_lookup(), module.exports); - __reExport(pipeline_exports, require_match(), module.exports); - __reExport(pipeline_exports, require_merge(), module.exports); - __reExport(pipeline_exports, require_out(), module.exports); - __reExport(pipeline_exports, require_project(), module.exports); - __reExport(pipeline_exports, require_redact(), module.exports); - __reExport(pipeline_exports, require_replaceRoot(), module.exports); - __reExport(pipeline_exports, require_replaceWith(), module.exports); - __reExport(pipeline_exports, require_sample(), module.exports); - __reExport(pipeline_exports, require_set2(), module.exports); - __reExport(pipeline_exports, require_setWindowFields(), module.exports); - __reExport(pipeline_exports, require_skip(), module.exports); - __reExport(pipeline_exports, require_sort(), module.exports); - __reExport(pipeline_exports, require_sortByCount(), module.exports); - __reExport(pipeline_exports, require_unionWith(), module.exports); - __reExport(pipeline_exports, require_unset(), module.exports); - __reExport(pipeline_exports, require_unwind(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/elemMatch.js -var require_elemMatch = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/elemMatch.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var elemMatch_exports = {}; - __export5(elemMatch_exports, { - $elemMatch: () => $elemMatch - }); - module.exports = __toCommonJS(elemMatch_exports); - var import_query = require_query(); - var import_util3 = require_util(); - var $elemMatch = (obj, expr, field, options) => { - const arr = (0, import_util3.resolve)(obj, field); - const query = new import_query.Query(expr, options); - if (!(0, import_util3.isArray)(arr)) return void 0; - const result = []; - for (let i = 0; i < arr.length; i++) { - if (query.test(arr[i])) { - if (options.useStrictMode) return [arr[i]]; - result.push(arr[i]); - } - } - return result.length > 0 ? result : void 0; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/slice.js -var require_slice2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/slice.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var slice_exports = {}; - __export5(slice_exports, { - $slice: () => $slice - }); - module.exports = __toCommonJS(slice_exports); - var import_util3 = require_util(); - var import_slice = require_slice(); - var $slice = (obj, expr, field, options) => { - const xs = (0, import_util3.resolve)(obj, field); - if (!(0, import_util3.isArray)(xs)) return xs; - return (0, import_slice.$slice)( - obj, - (0, import_util3.isArray)(expr) ? [xs, ...expr] : [xs, expr], - options - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/index.js -var require_projection = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var projection_exports = {}; - module.exports = __toCommonJS(projection_exports); - __reExport(projection_exports, require_elemMatch(), module.exports); - __reExport(projection_exports, require_slice2(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/all.js -var require_all = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/all.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var all_exports = {}; - __export5(all_exports, { - $all: () => $all - }); - module.exports = __toCommonJS(all_exports); - var import_predicates = require_predicates(); - var $all = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$all); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/elemMatch.js -var require_elemMatch2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/elemMatch.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var elemMatch_exports = {}; - __export5(elemMatch_exports, { - $elemMatch: () => $elemMatch - }); - module.exports = __toCommonJS(elemMatch_exports); - var import_predicates = require_predicates(); - var $elemMatch = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$elemMatch); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/size.js -var require_size2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/size.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var size_exports = {}; - __export5(size_exports, { - $size: () => $size - }); - module.exports = __toCommonJS(size_exports); - var import_predicates = require_predicates(); - var $size = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$size); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/index.js -var require_array2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var array_exports = {}; - module.exports = __toCommonJS(array_exports); - __reExport(array_exports, require_all(), module.exports); - __reExport(array_exports, require_elemMatch2(), module.exports); - __reExport(array_exports, require_size2(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/_internal.js -var require_internal13 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/_internal.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - processBitwiseQuery: () => processBitwiseQuery - }); - module.exports = __toCommonJS(internal_exports); - var import_util3 = require_util(); - var import_predicates = require_predicates(); - var processBitwiseQuery = (selector, value, predicate) => { - return (0, import_predicates.processQuery)( - selector, - value, - null, - (value2, mask) => { - let b = 0; - if ((0, import_util3.isArray)(mask)) { - for (const n of mask) b = b | 1 << n; - } else { - b = mask; - } - return predicate(value2 & b, b); - } - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllClear.js -var require_bitsAllClear = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllClear.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitsAllClear_exports = {}; - __export5(bitsAllClear_exports, { - $bitsAllClear: () => $bitsAllClear2 - }); - module.exports = __toCommonJS(bitsAllClear_exports); - var import_internal = require_internal13(); - var $bitsAllClear2 = (selector, value, _options2) => (0, import_internal.processBitwiseQuery)(selector, value, (result, _) => result == 0); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllSet.js -var require_bitsAllSet = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllSet.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitsAllSet_exports = {}; - __export5(bitsAllSet_exports, { - $bitsAllSet: () => $bitsAllSet2 - }); - module.exports = __toCommonJS(bitsAllSet_exports); - var import_internal = require_internal13(); - var $bitsAllSet2 = (selector, value, _options2) => (0, import_internal.processBitwiseQuery)(selector, value, (result, mask) => result == mask); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnyClear.js -var require_bitsAnyClear = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnyClear.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitsAnyClear_exports = {}; - __export5(bitsAnyClear_exports, { - $bitsAnyClear: () => $bitsAnyClear2 - }); - module.exports = __toCommonJS(bitsAnyClear_exports); - var import_internal = require_internal13(); - var $bitsAnyClear2 = (selector, value, _options2) => (0, import_internal.processBitwiseQuery)(selector, value, (result, mask) => result < mask); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnySet.js -var require_bitsAnySet = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnySet.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitsAnySet_exports = {}; - __export5(bitsAnySet_exports, { - $bitsAnySet: () => $bitsAnySet2 - }); - module.exports = __toCommonJS(bitsAnySet_exports); - var import_internal = require_internal13(); - var $bitsAnySet2 = (selector, value, _options2) => (0, import_internal.processBitwiseQuery)(selector, value, (result, _) => result > 0); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/index.js -var require_bitwise2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bitwise_exports = {}; - __export5(bitwise_exports, { - $bitsAllClear: () => import_bitsAllClear.$bitsAllClear, - $bitsAllSet: () => import_bitsAllSet.$bitsAllSet, - $bitsAnyClear: () => import_bitsAnyClear.$bitsAnyClear, - $bitsAnySet: () => import_bitsAnySet.$bitsAnySet - }); - module.exports = __toCommonJS(bitwise_exports); - var import_bitsAllClear = require_bitsAllClear(); - var import_bitsAllSet = require_bitsAllSet(); - var import_bitsAnyClear = require_bitsAnyClear(); - var import_bitsAnySet = require_bitsAnySet(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/eq.js -var require_eq2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/eq.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var eq_exports = {}; - __export5(eq_exports, { - $eq: () => $eq2 - }); - module.exports = __toCommonJS(eq_exports); - var import_predicates = require_predicates(); - var $eq2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$eq); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gt.js -var require_gt2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gt.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var gt_exports = {}; - __export5(gt_exports, { - $gt: () => $gt2 - }); - module.exports = __toCommonJS(gt_exports); - var import_predicates = require_predicates(); - var $gt2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$gt); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gte.js -var require_gte2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gte.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var gte_exports = {}; - __export5(gte_exports, { - $gte: () => $gte2 - }); - module.exports = __toCommonJS(gte_exports); - var import_predicates = require_predicates(); - var $gte2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$gte); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/in.js -var require_in2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/in.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var in_exports = {}; - __export5(in_exports, { - $in: () => $in2 - }); - module.exports = __toCommonJS(in_exports); - var import_predicates = require_predicates(); - var $in2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$in); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lt.js -var require_lt2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lt.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var lt_exports = {}; - __export5(lt_exports, { - $lt: () => $lt2 - }); - module.exports = __toCommonJS(lt_exports); - var import_predicates = require_predicates(); - var $lt2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$lt); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lte.js -var require_lte2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lte.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var lte_exports = {}; - __export5(lte_exports, { - $lte: () => $lte2 - }); - module.exports = __toCommonJS(lte_exports); - var import_predicates = require_predicates(); - var $lte2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$lte); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/ne.js -var require_ne2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/ne.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var ne_exports = {}; - __export5(ne_exports, { - $ne: () => $ne2 - }); - module.exports = __toCommonJS(ne_exports); - var import_predicates = require_predicates(); - var $ne2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$ne); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/nin.js -var require_nin = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/nin.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var nin_exports = {}; - __export5(nin_exports, { - $nin: () => $nin2 - }); - module.exports = __toCommonJS(nin_exports); - var import_predicates = require_predicates(); - var $nin2 = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$nin); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/index.js -var require_comparison2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var comparison_exports = {}; - __export5(comparison_exports, { - $eq: () => import_eq.$eq, - $gt: () => import_gt.$gt, - $gte: () => import_gte.$gte, - $in: () => import_in.$in, - $lt: () => import_lt2.$lt, - $lte: () => import_lte.$lte, - $ne: () => import_ne.$ne, - $nin: () => import_nin.$nin - }); - module.exports = __toCommonJS(comparison_exports); - var import_eq = require_eq2(); - var import_gt = require_gt2(); - var import_gte = require_gte2(); - var import_in = require_in2(); - var import_lt2 = require_lt2(); - var import_lte = require_lte2(); - var import_ne = require_ne2(); - var import_nin = require_nin(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/exists.js -var require_exists = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/exists.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var exists_exports = {}; - __export5(exists_exports, { - $exists: () => $exists - }); - module.exports = __toCommonJS(exists_exports); - var import_internal = require_internal(); - var $exists = (selector, value, _options2) => { - const nested = selector.includes("."); - const b = !!value; - if (!nested || selector.match(/\.\d+$/)) { - const opts2 = { pathArray: selector.split(".") }; - return (o) => (0, import_internal.resolve)(o, selector, opts2) !== void 0 === b; - } - const parentSelector = selector.substring(0, selector.lastIndexOf(".")); - const opts = { pathArray: parentSelector.split("."), preserveIndex: true }; - return (o) => { - const path3 = (0, import_internal.resolveGraph)(o, selector, opts); - const val = (0, import_internal.resolve)(path3, parentSelector, opts); - return (0, import_internal.isArray)(val) ? val.some((v) => v !== void 0) === b : val !== void 0 === b; - }; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/type.js -var require_type3 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/type.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var type_exports = {}; - __export5(type_exports, { - $type: () => $type - }); - module.exports = __toCommonJS(type_exports); - var import_predicates = require_predicates(); - var $type = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$type); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/index.js -var require_element = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var element_exports = {}; - module.exports = __toCommonJS(element_exports); - __reExport(element_exports, require_exists(), module.exports); - __reExport(element_exports, require_type3(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/expr.js -var require_expr = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/expr.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var expr_exports = {}; - __export5(expr_exports, { - $expr: () => $expr - }); - module.exports = __toCommonJS(expr_exports); - var import_internal = require_internal2(); - var import_internal2 = require_internal(); - function $expr(_, expr, options) { - return (obj) => (0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, expr, options), options.useStrictMode); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/jsonSchema.js -var require_jsonSchema = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/jsonSchema.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var jsonSchema_exports = {}; - __export5(jsonSchema_exports, { - $jsonSchema: () => $jsonSchema - }); - module.exports = __toCommonJS(jsonSchema_exports); - var import_util3 = require_util(); - function $jsonSchema(_, schema3, options) { - (0, import_util3.assert)( - !!options?.jsonSchemaValidator, - "$jsonSchema requires 'jsonSchemaValidator' option to be defined." - ); - const validate = options.jsonSchemaValidator(schema3); - return (obj) => validate(obj); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/mod.js -var require_mod2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/mod.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var mod_exports = {}; - __export5(mod_exports, { - $mod: () => $mod - }); - module.exports = __toCommonJS(mod_exports); - var import_predicates = require_predicates(); - var $mod = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$mod); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/regex.js -var require_regex = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/regex.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var regex_exports = {}; - __export5(regex_exports, { - $regex: () => $regex - }); - module.exports = __toCommonJS(regex_exports); - var import_predicates = require_predicates(); - var $regex = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$regex); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/where.js -var require_where = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/where.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var where_exports = {}; - __export5(where_exports, { - $where: () => $where - }); - module.exports = __toCommonJS(where_exports); - var import_internal = require_internal(); - function $where(_, rhs, opts) { - (0, import_internal.assert)( - opts.scriptEnabled, - "$where requires 'scriptEnabled' option to be true" - ); - const f = rhs; - (0, import_internal.assert)((0, import_internal.isFunction)(f), "$where only accepts a Function objects"); - return (obj) => (0, import_internal.truthy)(f.call(obj), opts?.useStrictMode); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/index.js -var require_evaluation = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var evaluation_exports = {}; - module.exports = __toCommonJS(evaluation_exports); - __reExport(evaluation_exports, require_expr(), module.exports); - __reExport(evaluation_exports, require_jsonSchema(), module.exports); - __reExport(evaluation_exports, require_mod2(), module.exports); - __reExport(evaluation_exports, require_regex(), module.exports); - __reExport(evaluation_exports, require_where(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/and.js -var require_and2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/and.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var and_exports = {}; - __export5(and_exports, { - $and: () => $and - }); - module.exports = __toCommonJS(and_exports); - var import_query = require_query(); - var import_util3 = require_util(); - var $and = (_, rhs, options) => { - (0, import_util3.assert)((0, import_util3.isArray)(rhs), "$and expects value to be an Array."); - const queries = rhs.map((expr) => new import_query.Query(expr, options)); - return (obj) => queries.every((q) => q.test(obj)); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/or.js -var require_or2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/or.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var or_exports = {}; - __export5(or_exports, { - $or: () => $or - }); - module.exports = __toCommonJS(or_exports); - var import_query = require_query(); - var import_util3 = require_util(); - function $or(_, rhs, options) { - (0, import_util3.assert)((0, import_util3.isArray)(rhs), "Invalid expression. $or expects value to be an Array"); - const queries = rhs.map((expr) => new import_query.Query(expr, options)); - return (obj) => queries.some((q) => q.test(obj)); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/nor.js -var require_nor = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/nor.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var nor_exports = {}; - __export5(nor_exports, { - $nor: () => $nor - }); - module.exports = __toCommonJS(nor_exports); - var import_util3 = require_util(); - var import_or = require_or2(); - function $nor(_, rhs, options) { - (0, import_util3.assert)( - (0, import_util3.isArray)(rhs), - "Invalid expression. $nor expects value to be an array." - ); - const f = (0, import_or.$or)("$or", rhs, options); - return (obj) => !f(obj); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/not.js -var require_not2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/not.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var not_exports = {}; - __export5(not_exports, { - $not: () => $not - }); - module.exports = __toCommonJS(not_exports); - var import_query = require_query(); - var import_util3 = require_util(); - function $not(selector, rhs, options) { - const criteria = {}; - criteria[selector] = (0, import_util3.normalize)(rhs); - const query = new import_query.Query(criteria, options); - return (obj) => !query.test(obj); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/index.js -var require_logical = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var logical_exports = {}; - module.exports = __toCommonJS(logical_exports); - __reExport(logical_exports, require_and2(), module.exports); - __reExport(logical_exports, require_nor(), module.exports); - __reExport(logical_exports, require_not2(), module.exports); - __reExport(logical_exports, require_or2(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/index.js -var require_query2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var query_exports = {}; - module.exports = __toCommonJS(query_exports); - __reExport(query_exports, require_array2(), module.exports); - __reExport(query_exports, require_bitwise2(), module.exports); - __reExport(query_exports, require_comparison2(), module.exports); - __reExport(query_exports, require_element(), module.exports); - __reExport(query_exports, require_evaluation(), module.exports); - __reExport(query_exports, require_logical(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/denseRank.js -var require_denseRank = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/denseRank.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var denseRank_exports = {}; - __export5(denseRank_exports, { - $denseRank: () => $denseRank - }); - module.exports = __toCommonJS(denseRank_exports); - var import_internal = require_internal12(); - var $denseRank = (obj, coll, expr, options) => (0, import_internal.rank)( - obj, - coll, - expr, - options, - true - /*dense*/ - ); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/derivative.js -var require_derivative = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/derivative.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var derivative_exports = {}; - __export5(derivative_exports, { - $derivative: () => $derivative - }); - module.exports = __toCommonJS(derivative_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var import_internal = require_internal8(); - var $derivative = (_, coll, expr, options) => { - if (coll.length < 2) return null; - const { input, unit } = expr.inputExpr; - const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0]; - const values = [coll[0], coll[coll.length - 1]]; - const points = (0, import_push.$push)(values, [sortKey, input], options).filter( - ([x, y]) => (0, import_util3.isNumber)(+x) && (0, import_util3.isNumber)(+y) - ); - (0, import_util3.assert)(points.length === 2, "$derivative arguments must resolve to numeric"); - const [[x1, y1], [x2, y2]] = points; - const deltaX = (x2 - x1) / import_internal.TIMEUNIT_IN_MILLIS[unit ?? "millisecond"]; - return (y2 - y1) / deltaX; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/documentNumber.js -var require_documentNumber = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/documentNumber.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var documentNumber_exports = {}; - __export5(documentNumber_exports, { - $documentNumber: () => $documentNumber - }); - module.exports = __toCommonJS(documentNumber_exports); - var $documentNumber = (_obj, _coll, expr, _options2) => expr.documentNumber; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/expMovingAvg.js -var require_expMovingAvg = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/expMovingAvg.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var expMovingAvg_exports = {}; - __export5(expMovingAvg_exports, { - $expMovingAvg: () => $expMovingAvg - }); - module.exports = __toCommonJS(expMovingAvg_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var import_internal = require_internal12(); - var $expMovingAvg = (_, coll, expr, options) => { - const { input, N, alpha } = expr.inputExpr; - (0, import_util3.assert)( - !(N && alpha), - `$expMovingAvg: must provide either 'N' or 'alpha' field.` - ); - (0, import_util3.assert)( - !N || (0, import_util3.isNumber)(N) && N > 0, - `$expMovingAvg: 'N' must be greater than zero. Got ${N}.` - ); - (0, import_util3.assert)( - !alpha || (0, import_util3.isNumber)(alpha) && alpha > 0 && alpha < 1, - `$expMovingAvg: 'alpha' must be between 0 and 1 (exclusive), found alpha: ${alpha}` - ); - return (0, import_internal.withMemo)( - coll, - expr, - () => { - const weight = N != void 0 ? 2 / (N + 1) : alpha; - const values = (0, import_push.$push)(coll, input, options); - for (let i = 0; i < values.length; i++) { - if (i === 0) { - if (!(0, import_util3.isNumber)(values[i])) values[i] = null; - continue; - } - if (!(0, import_util3.isNumber)(values[i])) { - values[i] = values[i - 1]; - continue; - } - if (!(0, import_util3.isNumber)(values[i - 1])) continue; - values[i] = values[i] * weight + values[i - 1] * (1 - weight); - } - return values; - }, - (series) => series[expr.documentNumber - 1] - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/integral.js -var require_integral = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/integral.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var integral_exports = {}; - __export5(integral_exports, { - $integral: () => $integral - }); - module.exports = __toCommonJS(integral_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var import_internal = require_internal8(); - var $integral = (_, coll, expr, options) => { - const { input, unit } = expr.inputExpr; - const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0]; - const points = (0, import_push.$push)(coll, [sortKey, input], options).filter( - ([x, y]) => (0, import_util3.isNumber)(+x) && (0, import_util3.isNumber)(+y) - ); - const size = points.length; - (0, import_util3.assert)(coll.length === size, "$integral expects an array of numeric values"); - let result = 0; - for (let k = 1; k < size; k++) { - const [x1, y1] = points[k - 1]; - const [x2, y2] = points[k]; - const deltaX = (x2 - x1) / import_internal.TIMEUNIT_IN_MILLIS[unit ?? "millisecond"]; - result += 0.5 * (y1 + y2) * deltaX; - } - return result; - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/minMaxScaler.js -var require_minMaxScaler = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/minMaxScaler.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var minMaxScaler_exports = {}; - __export5(minMaxScaler_exports, { - $minMaxScaler: () => $minMaxScaler - }); - module.exports = __toCommonJS(minMaxScaler_exports); - var import_util3 = require_util(); - var import_push = require_push(); - var import_internal = require_internal12(); - var $minMaxScaler = (_, coll, expr, options) => { - return (0, import_internal.withMemo)( - coll, - expr, - () => { - const args = expr.inputExpr; - const min = args.min || 0; - const max = args.max || 1; - const nums = (0, import_push.$push)( - coll, - args.input || expr.inputExpr, - options - ); - (0, import_util3.assert)( - (0, import_util3.isArray)(nums) && nums.length > 0 && nums.every(import_util3.isNumber), - "$minMaxScaler: input must be a numeric array" - ); - let rmin = nums[0]; - let rmax = nums[0]; - for (const n of nums) { - if (n < rmin) rmin = n; - else if (n > rmax) rmax = n; - } - const scale = max - min; - const range = rmax - rmin; - (0, import_util3.assert)(range !== 0, "$minMaxScaler: input range must not be zero"); - return { - min, - scale, - rmin, - range, - nums - }; - }, - (data) => { - const { min, rmin, scale, range, nums } = data; - return (nums[expr.documentNumber - 1] - rmin) / range * scale + min; - } - ); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/rank.js -var require_rank = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/rank.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var rank_exports = {}; - __export5(rank_exports, { - $rank: () => $rank - }); - module.exports = __toCommonJS(rank_exports); - var import_internal = require_internal12(); - var $rank = (obj, coll, expr, options) => (0, import_internal.rank)( - obj, - coll, - expr, - options, - false - /*dense*/ - ); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/shift.js -var require_shift = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/shift.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var shift_exports = {}; - __export5(shift_exports, { - $shift: () => $shift - }); - module.exports = __toCommonJS(shift_exports); - var import_internal = require_internal2(); - var $shift = (obj, coll, expr, options) => { - const input = expr.inputExpr; - const shiftedIndex = expr.documentNumber - 1 + input.by; - if (shiftedIndex < 0 || shiftedIndex > coll.length - 1) { - return (0, import_internal.evalExpr)(obj, input.default, options) ?? null; - } - return (0, import_internal.evalExpr)(coll[shiftedIndex], input.output, options); - }; - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/index.js -var require_window = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var window_exports = {}; - module.exports = __toCommonJS(window_exports); - __reExport(window_exports, require_denseRank(), module.exports); - __reExport(window_exports, require_derivative(), module.exports); - __reExport(window_exports, require_documentNumber(), module.exports); - __reExport(window_exports, require_expMovingAvg(), module.exports); - __reExport(window_exports, require_integral(), module.exports); - __reExport(window_exports, require_linearFill(), module.exports); - __reExport(window_exports, require_locf(), module.exports); - __reExport(window_exports, require_minMaxScaler(), module.exports); - __reExport(window_exports, require_rank(), module.exports); - __reExport(window_exports, require_shift(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/_internal.js -var require_internal14 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/_internal.js"(exports, module) { - var __create2 = Object.create; - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp6(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var internal_exports = {}; - __export5(internal_exports, { - DEFAULT_OPTIONS: () => DEFAULT_OPTIONS, - applyUpdate: () => applyUpdate, - buildParams: () => buildParams, - clone: () => clone2, - walkExpression: () => walkExpression - }); - module.exports = __toCommonJS(internal_exports); - var import_internal = require_internal2(); - var booleanOperators = __toESM2(require_boolean()); - var comparisonOperators = __toESM2(require_comparison()); - var queryOperators = __toESM2(require_query2()); - var import_query = require_query(); - var import_internal2 = require_internal(); - var DEFAULT_OPTIONS = import_internal.ComputeOptions.init({ - context: import_internal.Context.init().addQueryOps(queryOperators).addExpressionOps(booleanOperators).addExpressionOps(comparisonOperators) - }).update({ updateConfig: { cloneMode: "copy" } }); - var clone2 = (val, opts) => { - const mode = opts?.local?.updateConfig?.cloneMode; - switch (mode) { - case "deep": - return (0, import_internal2.cloneDeep)(val); - case "copy": { - if ((0, import_internal2.isDate)(val)) return new Date(val); - if ((0, import_internal2.isArray)(val)) return val.slice(); - if ((0, import_internal2.isObject)(val)) return Object.assign({}, val); - if ((0, import_internal2.isRegExp)(val)) return new RegExp(val); - return val; - } - } - return val; - }; - var FIRST_ONLY = "$"; - var ARRAY_WIDE = "$[]"; - var applyUpdate = (o, n, q, f, opts) => { - const { selector, position: c, next } = n; - if (!c) { - let b = false; - const g = (u, k) => b = Boolean(f(u, k)) || b; - (0, import_internal2.walk)(o, selector, g, opts); - return b; - } - const arr = (0, import_internal2.resolve)(o, selector); - if (!(0, import_internal2.isArray)(arr) || !arr.length) return false; - if (c === FIRST_ONLY) { - const i = arr.findIndex((e) => q[selector].test({ [selector]: [e] })); - (0, import_internal2.assert)(i > -1, "BUG: positional operator found no match for " + selector); - return next ? applyUpdate(arr[i], next, q, f, opts) : f(arr, i); - } - return arr.map((e, i) => { - if (c !== ARRAY_WIDE && q[c] && !q[c].test({ [c]: [e] })) return false; - return next ? applyUpdate(e, next, q, f, opts) : f(arr, i); - }).some((v) => !!v); - }; - var ERR_MISSING_FIELD = "You must include the array field for '.$' as part of the query document."; - var ERR_IMMUTABLE_FIELD = (path3, idKey) => `Performing an update on the path '${path3}' would modify the immutable field '${idKey}'.`; - function walkExpression(expr, arrayFilters, options, callback) { - const opts = options; - const params = opts.local.updateParams ?? buildParams([expr], arrayFilters, opts); - const modified = []; - for (const key of Object.keys(expr)) { - const { node, queries } = params[key]; - if (callback(expr[key], node, queries)) modified.push(node.selector); - } - return modified.sort(); - } - function buildParams(exprList, arrayFilters, options) { - const params = {}; - arrayFilters || (arrayFilters = []); - const filterIndexMap = arrayFilters.reduce( - (res, filter) => { - for (const k of Object.keys(filter)) { - const parent = k.split(".")[0]; - if (res[parent]) { - res[parent][k] = filter[k]; - } else { - res[parent] = { [k]: filter[k] }; - } - } - return res; - }, - {} - ); - let { condition } = options.local; - condition = condition ?? {}; - const queryKeys = Object.keys(condition); - const conflictDetector = new import_internal2.PathValidator(); - for (const expr of exprList) { - for (const selector of Object.keys(expr)) { - const identifiers = []; - const node = selector.includes("$") ? { selector: "" } : { selector }; - if (!node.selector) { - selector.split(".").reduce((n, v) => { - if (v === FIRST_ONLY || v === ARRAY_WIDE) { - n.position = v; - } else if (v.startsWith("$[") && v.endsWith("]")) { - const id = v.slice(2, -1); - (0, import_internal2.assert)( - /^[a-z]+\w*$/.test(id), - `The filter must begin with a lowercase letter and contain only alphanumeric characters. '${v}' is invalid.` - ); - identifiers.push(id); - n.position = id; - } else if (!n.selector) { - n.selector = v; - } else if (!n.position) { - n.selector += "." + v; - } else { - n.next = { selector: v }; - return n.next; - } - return n; - }, node); - } - const queries = {}; - if (identifiers.length) { - const filters = {}; - for (const v of identifiers) filters[v] = filterIndexMap[v]; - for (const k of Object.keys(filters)) { - queries[k] = new import_query.Query(filters[k], options); - } - } - if (node.position === FIRST_ONLY) { - const field = node.selector; - (0, import_internal2.assert)(queryKeys && queryKeys.length, ERR_MISSING_FIELD); - const matches = queryKeys.filter( - (k2) => k2 === field || k2.startsWith(field + ".") - ); - (0, import_internal2.assert)(matches.length === 1, ERR_MISSING_FIELD); - const k = matches[0]; - queries[field] = new import_query.Query({ [k]: condition[k] }, options); - } - const idKey = options.idKey; - (0, import_internal2.assert)( - node.selector !== idKey && !node.selector.startsWith(`${idKey}.`), - ERR_IMMUTABLE_FIELD(node.selector, idKey) - ); - (0, import_internal2.assert)( - conflictDetector.add(node.selector), - `updating the path '${node.selector}' would create a conflict at '${node.selector}'` - ); - params[selector] = { node, queries }; - } - } - return params; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/addToSet.js -var require_addToSet2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/addToSet.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var addToSet_exports = {}; - __export5(addToSet_exports, { - $addToSet: () => $addToSet - }); - module.exports = __toCommonJS(addToSet_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $addToSet(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { - const args = { $each: [val] }; - if ((0, import_util3.isObject)(val) && (0, import_util3.has)(val, "$each")) { - Object.assign(args, val); - } - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - const prev = o[k]; - if ((0, import_util3.isArray)(prev)) { - const set2 = (0, import_util3.unique)(prev.concat(args.$each)); - if (set2.length === prev.length) return false; - o[k] = (0, import_internal.clone)(set2, options); - } else if (prev === void 0) { - o[k] = (0, import_internal.clone)(args.$each, options); - } else { - return false; - } - return true; - }, - { buildGraph: true } - ); - }); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/bit.js -var require_bit = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/bit.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var bit_exports = {}; - __export5(bit_exports, { - $bit: () => $bit - }); - module.exports = __toCommonJS(bit_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - var BIT_OPS = ["and", "or", "xor"]; - function $bit(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - for (const vals of Object.values(expr)) { - (0, import_util3.assert)((0, import_util3.isObject)(vals), `$bit operator expression must be an object.`); - const op = Object.keys(vals); - (0, import_util3.assert)( - op.length === 1 && BIT_OPS.includes(op[0]), - `$bit spec is invalid '${op[0]}'. Must be one of 'and', 'or', or 'xor'.` - ); - (0, import_util3.assert)( - (0, import_util3.isNumber)(vals[op[0]]), - `$bit expression value must be a number. Got ${typeof vals[op[0]]}` - ); - } - return (obj) => { - return (0, import_internal.walkExpression)( - expr, - arrayFilters, - options, - (val, node, queries) => { - const op = Object.keys(val); - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - let n = o[k]; - const v = val[op[0]]; - if (n !== void 0 && !((0, import_util3.isNumber)(n) && (0, import_util3.isNumber)(v))) return false; - n = n || 0; - switch (op[0]) { - case "and": - return (o[k] = n & v) !== n; - case "or": - return (o[k] = n | v) !== n; - case "xor": - return (o[k] = n ^ v) !== n; - } - }, - { buildGraph: true } - ); - } - ); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/currentDate.js -var require_currentDate = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/currentDate.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var currentDate_exports = {}; - __export5(currentDate_exports, { - $currentDate: () => $currentDate - }); - module.exports = __toCommonJS(currentDate_exports); - var import_internal = require_internal14(); - function $currentDate(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)( - expr, - arrayFilters, - options, - (val, node, queries) => { - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - o[k] = val === true || val.$type === "date" ? options.now : options.now.getTime(); - return true; - }, - { buildGraph: true } - ); - } - ); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/inc.js -var require_inc = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/inc.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var inc_exports = {}; - __export5(inc_exports, { - $inc: () => $inc - }); - module.exports = __toCommonJS(inc_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $inc(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)( - expr, - arrayFilters, - options, - (val, node, queries) => { - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - if ((0, import_util3.isNumber)(o[k]) || o[k] === void 0) { - o[k] || (o[k] = 0); - o[k] += val; - return true; - } - return false; - }, - { buildGraph: true } - ); - } - ); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/max.js -var require_max2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/max.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var max_exports = {}; - __export5(max_exports, { - $max: () => $max - }); - module.exports = __toCommonJS(max_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $max(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - if ((0, import_util3.compare)(o[k], val) > -1) return false; - o[k] = val; - return true; - }, - { buildGraph: true } - ); - }); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/min.js -var require_min2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/min.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var min_exports = {}; - __export5(min_exports, { - $min: () => $min - }); - module.exports = __toCommonJS(min_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $min(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - if ((0, import_util3.compare)(o[k], val) < 1) return false; - o[k] = val; - return true; - }, - { buildGraph: true } - ); - }); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/mul.js -var require_mul = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/mul.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var mul_exports = {}; - __export5(mul_exports, { - $mul: () => $mul - }); - module.exports = __toCommonJS(mul_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $mul(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)( - expr, - arrayFilters, - options, - (val, node, queries) => { - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - const prev = o[k]; - if ((0, import_util3.isNumber)(o[k])) o[k] = o[k] * val; - else if (o[k] === void 0) o[k] = 0; - return o[k] !== prev; - }, - { buildGraph: true } - ); - } - ); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pop.js -var require_pop = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pop.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var pop_exports = {}; - __export5(pop_exports, { - $pop: () => $pop - }); - module.exports = __toCommonJS(pop_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $pop(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)( - expr, - arrayFilters, - options, - (val, node, queries) => { - return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => { - const arr = o[k]; - if (!(0, import_util3.isArray)(arr) || !arr.length) return false; - if (val === -1) arr.splice(0, 1); - else arr.pop(); - return true; - }); - } - ); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pull.js -var require_pull = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pull.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var pull_exports = {}; - __export5(pull_exports, { - $pull: () => $pull - }); - module.exports = __toCommonJS(pull_exports); - var import_query = require_query(); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $pull(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { - const wrap4 = !(0, import_util3.isObject)(val) || Object.keys(val).some(import_util3.isOperator); - const query = new import_query.Query(wrap4 ? { k: val } : val, options); - const pred = wrap4 ? (v) => query.test({ k: v }) : (v) => query.test(v); - return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => { - const prev = o[k]; - if (!(0, import_util3.isArray)(prev) || !prev.length) return false; - const curr = new Array(); - let ok2 = false; - for (const v of prev) { - const b = pred(v); - if (!b) curr.push(v); - ok2 || (ok2 = b); - } - if (!ok2) return false; - o[k] = curr; - return true; - }); - }); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pullAll.js -var require_pullAll = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pullAll.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var pullAll_exports = {}; - __export5(pullAll_exports, { - $pullAll: () => $pullAll - }); - module.exports = __toCommonJS(pullAll_exports); - var import_internal = require_internal14(); - var import_pull = require_pull(); - function $pullAll(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - const pullExpr = {}; - for (const k of Object.keys(expr)) { - pullExpr[k] = { $in: expr[k] }; - } - return (0, import_pull.$pull)(pullExpr, arrayFilters, options); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/push.js -var require_push2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/push.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var push_exports = {}; - __export5(push_exports, { - $push: () => $push - }); - module.exports = __toCommonJS(push_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - var MODIFIERS = ["$each", "$slice", "$sort", "$position"]; - function $push(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { - const args = { - $each: [val] - }; - if ((0, import_util3.isObject)(val) && MODIFIERS.some((m) => (0, import_util3.has)(val, m))) { - Object.assign(args, val); - } - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - const arr = o[k]; - if (!(0, import_util3.isArray)(arr)) { - if (arr === void 0) { - o[k] = (0, import_internal.clone)(args.$each, options); - return true; - } - return false; - } - const prev = arr.slice(0, args.$slice || arr.length); - const oldsize = arr.length; - const pos = (0, import_util3.isNumber)(args.$position) ? args.$position : arr.length; - arr.splice(pos, 0, ...(0, import_internal.clone)(args.$each, options)); - if (args.$sort) { - const sortKey = (0, import_util3.isObject)(args.$sort) ? Object.keys(args.$sort)[0] : ""; - const order = !sortKey ? args.$sort : args.$sort[sortKey]; - const f = !sortKey ? (a) => a : (a) => (0, import_util3.resolve)(a, sortKey); - arr.sort((a, b) => order * (0, import_util3.compare)(f(a), f(b))); - } - if ((0, import_util3.isNumber)(args.$slice)) { - if (args.$slice < 0) arr.splice(0, arr.length + args.$slice); - else arr.splice(args.$slice); - } - return oldsize != arr.length || !(0, import_util3.isEqual)(prev, arr); - }, - { descendArray: true, buildGraph: true } - ); - }); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/set.js -var require_set3 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/set.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var set_exports = {}; - __export5(set_exports, { - $set: () => $set - }); - module.exports = __toCommonJS(set_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $set(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => { - return (0, import_internal.applyUpdate)( - obj, - node, - queries, - (o, k) => { - if ((0, import_util3.isEqual)(o[k], val)) return false; - o[k] = (0, import_internal.clone)(val, options); - return true; - }, - { buildGraph: true } - ); - }); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/rename.js -var require_rename = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/rename.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var rename_exports = {}; - __export5(rename_exports, { - $rename: () => $rename - }); - module.exports = __toCommonJS(rename_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - var import_set = require_set3(); - var isIdPath = (path3, idKey) => path3 === idKey || path3.startsWith(`${idKey}.`); - function $rename(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - const idKey = options.idKey; - for (const target of Object.values(expr)) { - (0, import_util3.assert)( - !isIdPath(target, idKey), - `Performing an update on the path '${target}' would modify the immutable field '${idKey}'.` - ); - } - return (obj) => { - const res = []; - const changed = (0, import_internal.walkExpression)( - expr, - arrayFilters, - options, - (val, node, queries) => { - return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => { - if (!(0, import_util3.has)(o, k)) return false; - Array.prototype.push.apply( - res, - (0, import_set.$set)({ [val]: o[k] }, arrayFilters, options)(obj) - ); - delete o[k]; - return true; - }); - } - ); - return Array.from(new Set(changed.concat(res))); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/unset.js -var require_unset2 = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/unset.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var unset_exports = {}; - __export5(unset_exports, { - $unset: () => $unset - }); - module.exports = __toCommonJS(unset_exports); - var import_util3 = require_util(); - var import_internal = require_internal14(); - function $unset(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) { - return (obj) => { - return (0, import_internal.walkExpression)(expr, arrayFilters, options, (_, node, queries) => { - return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => { - if (!(0, import_util3.has)(o, k)) return false; - const prev = o[k]; - if ((0, import_util3.isArray)(o)) o[k] = null; - else delete o[k]; - return !(0, import_util3.isEqual)(prev, o[k]); - }); - }); - }; - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/index.js -var require_update = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var update_exports = {}; - module.exports = __toCommonJS(update_exports); - __reExport(update_exports, require_addToSet2(), module.exports); - __reExport(update_exports, require_bit(), module.exports); - __reExport(update_exports, require_currentDate(), module.exports); - __reExport(update_exports, require_inc(), module.exports); - __reExport(update_exports, require_max2(), module.exports); - __reExport(update_exports, require_min2(), module.exports); - __reExport(update_exports, require_mul(), module.exports); - __reExport(update_exports, require_pop(), module.exports); - __reExport(update_exports, require_pull(), module.exports); - __reExport(update_exports, require_pullAll(), module.exports); - __reExport(update_exports, require_push2(), module.exports); - __reExport(update_exports, require_rename(), module.exports); - __reExport(update_exports, require_set3(), module.exports); - __reExport(update_exports, require_unset2(), module.exports); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/updater.js -var require_updater = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/updater.js"(exports, module) { - var __create2 = Object.create; - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp6(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var updater_exports = {}; - __export5(updater_exports, { - update: () => update, - updateMany: () => updateMany, - updateOne: () => updateOne - }); - module.exports = __toCommonJS(updater_exports); - var import_internal = require_internal2(); - var import_lazy = require_lazy(); - var booleanOperators = __toESM2(require_boolean()); - var comparisonOperators = __toESM2(require_comparison()); - var import_addFields = require_addFields(); - var import_project = require_project(); - var import_replaceRoot = require_replaceRoot(); - var import_replaceWith = require_replaceWith(); - var import_set = require_set2(); - var import_sort = require_sort(); - var import_unset = require_unset(); - var queryOperators = __toESM2(require_query2()); - var updateOperators = __toESM2(require_update()); - var import_internal2 = require_internal14(); - var import_query = require_query(); - var import_internal3 = require_internal(); - var UPDATE_OPERATORS = updateOperators; - var PIPELINE_OPERATORS = { - $addFields: import_addFields.$addFields, - $set: import_set.$set, - $project: import_project.$project, - $unset: import_unset.$unset, - $replaceRoot: import_replaceRoot.$replaceRoot, - $replaceWith: import_replaceWith.$replaceWith - }; - function update(obj, modifier, arrayFilters, condition, options) { - const docs = [obj]; - const res = updateOne( - docs, - condition || {}, - modifier, - { arrayFilters, cloneMode: options?.cloneMode ?? "copy" }, - options?.queryOptions - ); - return res.modifiedFields ?? []; - } - function updateMany(documents, condition, modifier, updateConfig = {}, options) { - const { modifiedCount, matchedCount } = updateDocuments( - documents, - condition, - modifier, - updateConfig, - options - ); - return { modifiedCount, matchedCount }; - } - function updateOne(documents, condition, modifier, updateConfig = {}, options) { - return updateDocuments(documents, condition, modifier, updateConfig, { - ...options, - firstOnly: true - }); - } - function updateDocuments(documents, condition, modifier, updateConfig = {}, options) { - options || (options = {}); - const firstOnly = options?.firstOnly ?? false; - const opts = import_internal.ComputeOptions.init({ - ...options, - collation: Object.assign({}, options?.collation, updateConfig?.collation) - }).update({ - condition, - updateConfig: { cloneMode: "copy", ...updateConfig }, - variables: updateConfig.let, - updateParams: {} - }); - opts.context.addExpressionOps(booleanOperators).addExpressionOps(comparisonOperators).addQueryOps(queryOperators).addPipelineOps(PIPELINE_OPERATORS); - const filterExists = Object.keys(condition).length > 0; - const matchedDocs = /* @__PURE__ */ new Map(); - let docsIter = (0, import_lazy.Lazy)(documents); - if (filterExists) { - const query = new import_query.Query(condition, opts); - docsIter = docsIter.filter((o, i) => { - if (query.test(o)) { - matchedDocs.set(o, i); - return true; - } - return false; - }); - } - let modifiedIndex = -1; - if (firstOnly) { - const indexes = /* @__PURE__ */ new Map(); - if (updateConfig.sort) { - if (!filterExists) { - docsIter = docsIter.map((o, i) => { - indexes.set(o, i); - return o; - }); - } - docsIter = (0, import_sort.$sort)(docsIter, updateConfig.sort, opts); - } - docsIter = docsIter.take(1); - const firstDoc = docsIter.collect()[0]; - modifiedIndex = matchedDocs.get(firstDoc) ?? indexes.get(firstDoc) ?? 0; - } - const foundDocs = docsIter.collect(); - if (foundDocs.length === 0) return { matchedCount: 0, modifiedCount: 0 }; - if ((0, import_internal3.isArray)(modifier)) { - const indexes = firstOnly ? [modifiedIndex] : Array.from(matchedDocs.values()); - const hashes = indexes.length ? indexes.map((i) => (0, import_internal3.hashCode)(documents[i])) : foundDocs.map((o) => (0, import_internal3.hashCode)(o)); - const output2 = { matchedCount: hashes.length, modifiedCount: 0 }; - const oldFirstDoc = firstOnly ? (0, import_internal3.cloneDeep)(documents[indexes[0]]) : void 0; - let updateIter = (0, import_lazy.Lazy)(foundDocs); - for (const stage of modifier) { - const [op, expr] = Object.entries(stage)[0]; - const pipelineOp = PIPELINE_OPERATORS[op]; - (0, import_internal3.assert)(pipelineOp, `Unknown pipeline operator: '${op}'.`); - updateIter = pipelineOp(updateIter, expr, opts); - } - const matches = updateIter.collect(); - if (indexes.length) { - (0, import_internal3.assert)( - indexes.length === matches.length, - "bug: indexes and result size must match." - ); - for (let i = 0; i < indexes.length; i++) { - if ((0, import_internal3.hashCode)(matches[i]) !== hashes[i]) { - documents[indexes[i]] = matches[i]; - output2.modifiedCount++; - } - } - } else { - for (let i = 0; i < documents.length; i++) { - if ((0, import_internal3.hashCode)(matches[i]) !== hashes[i]) { - documents[i] = matches[i]; - output2.modifiedCount++; - } - } - } - if (firstOnly && output2.modifiedCount && oldFirstDoc) { - const newDoc = documents[indexes[0]]; - const modifiedFields2 = getModifiedFields( - modifier, - oldFirstDoc, - newDoc - ); - (0, import_internal3.assert)(modifiedFields2.length, "bug: failed to retrieve modified fields"); - Object.assign(output2, { modifiedFields: modifiedFields2, modifiedIndex }); - } - return output2; - } - const unknownOp = Object.keys(modifier).find((op) => !UPDATE_OPERATORS[op]); - (0, import_internal3.assert)(!unknownOp, `Unknown update operator: '${unknownOp}'.`); - const arrayFilters = updateConfig?.arrayFilters ?? []; - opts.update({ - updateParams: (0, import_internal2.buildParams)( - Object.values(modifier), - arrayFilters, - opts - ) - }); - const matchedCount = foundDocs.length; - const output = { matchedCount, modifiedCount: 0 }; - const modifiedFields = []; - const fns = []; - for (const op of Object.keys(modifier)) { - const fn = UPDATE_OPERATORS[op]; - const expr = modifier[op]; - fns.push(fn(expr, arrayFilters, opts)); - } - for (const doc of foundDocs) { - let modified = false; - for (const mutate of fns) { - const fields = mutate(doc); - if (fields.length) { - modified = true; - if (firstOnly) Array.prototype.push.apply(modifiedFields, fields); - } - } - output.modifiedCount += +modified; - } - if (firstOnly && modifiedFields.length) { - modifiedFields.sort(); - Object.assign(output, { modifiedFields, modifiedIndex }); - } - return output; - } - function getModifiedFields(pipeline, oldDoc, newDoc) { - const stageFields = []; - for (const stage of pipeline) { - const op = Object.keys(stage)[0]; - const expr = stage[op]; - switch (op) { - case "$addFields": - case "$set": - case "$project": - case "$replaceWith": - stageFields.push(...Object.keys(expr)); - break; - case "$unset": - stageFields.push(...(0, import_internal3.ensureArray)(expr)); - break; - case "$replaceRoot": - stageFields.length = 0; - stageFields.push( - ...Object.keys(expr?.newRoot) - ); - break; - } - } - const stageFieldsSet = new Set(stageFields.sort()); - const pathValidator = new import_internal3.PathValidator(); - const modifiedFields = []; - for (const key of stageFieldsSet) { - if (pathValidator.add(key) && !(0, import_internal3.isEqual)((0, import_internal3.resolve)(newDoc, key), (0, import_internal3.resolve)(oldDoc, key))) { - modifiedFields.push(key); - } - } - for (const key of Object.keys(oldDoc)) { - if (stageFieldsSet.has(key)) continue; - if (!pathValidator.add(key) || !(0, import_internal3.isEqual)(newDoc[key], oldDoc[key])) { - modifiedFields.push(key); - } - } - const topLevelValidator = new import_internal3.PathValidator(); - return modifiedFields.sort().filter((key) => topLevelValidator.add(key)); - } - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/index.js -var require_core = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/index.js"(exports, module) { - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var core_exports3 = {}; - __export5(core_exports3, { - Context: () => import_internal.Context, - OpType: () => import_internal.OpType, - ProcessingMode: () => import_internal.ProcessingMode, - computeValue: () => import_internal.computeValue, - evalExpr: () => import_internal.evalExpr - }); - module.exports = __toCommonJS(core_exports3); - var import_internal = require_internal2(); - } -}); - -// ../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/index.js -var require_cjs = __commonJS({ - "../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/index.js"(exports, module) { - var __create2 = Object.create; - var __defProp6 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp3 = Object.prototype.hasOwnProperty; - var __export5 = (target, all) => { - for (var name in all) - __defProp6(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp3.call(to, key) && key !== except) - __defProp6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp6(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS = (mod) => __copyProps2(__defProp6({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export5(index_exports, { - Aggregator: () => Aggregator2, - Context: () => import_core15.Context, - ProcessingMode: () => import_core15.ProcessingMode, - Query: () => Query2, - aggregate: () => aggregate, - default: () => index_default2, - find: () => find, - update: () => update, - updateMany: () => updateMany, - updateOne: () => updateOne - }); - module.exports = __toCommonJS(index_exports); - var import_aggregator = require_aggregator(); - var import_internal = require_internal2(); - var accumulatorOperators = __toESM2(require_accumulator2()); - var expressionOperators = __toESM2(require_expression()); - var pipelineOperators = __toESM2(require_pipeline()); - var projectionOperators = __toESM2(require_projection()); - var queryOperators = __toESM2(require_query2()); - var windowOperators = __toESM2(require_window()); - var import_query = require_query(); - var updater = __toESM2(require_updater()); - var import_core15 = require_core(); - var CONTEXT = import_internal.Context.init({ - accumulator: accumulatorOperators, - expression: expressionOperators, - pipeline: pipelineOperators, - projection: projectionOperators, - query: queryOperators, - window: windowOperators - }); - var makeOpts = (options) => Object.assign({ - ...options, - context: options?.context ? import_internal.Context.from(CONTEXT, options?.context) : CONTEXT - }); - var Query2 = class extends import_query.Query { - constructor(condition, options) { - super(condition, makeOpts(options)); - } - }; - var Aggregator2 = class extends import_aggregator.Aggregator { - constructor(pipeline, options) { - super(pipeline, makeOpts(options)); - } - }; - function find(collection, condition, projection, options) { - return new Query2(condition, makeOpts(options)).find( - collection, - projection - ); - } - function aggregate(collection, pipeline, options) { - return new Aggregator2(pipeline, makeOpts(options)).run(collection); - } - function update(obj, modifier, arrayFilters, condition, options) { - return updater.update(obj, modifier, arrayFilters, condition, { - cloneMode: options?.cloneMode, - queryOptions: makeOpts(options?.queryOptions) - }); - } - function updateMany(documents, condition, modifer, updateConfig = {}, options) { - return updater.updateMany( - documents, - condition, - modifer, - updateConfig, - makeOpts(options) - ); - } - function updateOne(documents, condition, modifier, updateConfig = {}, options) { - return updater.updateOne( - documents, - condition, - modifier, - updateConfig, - makeOpts(options) - ); - } - var index_default2 = { - Aggregator: Aggregator2, - Context: import_internal.Context, - ProcessingMode: import_internal.ProcessingMode, - Query: Query2, - aggregate, - find, - update, - updateMany, - updateOne - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/env-impl.mjs -function toBoolean(val) { - return val ? val !== "false" : false; -} -function getEnvVar(key, fallback) { - if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback; - if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback; - if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback; - return fallback; -} -function getBooleanEnvVar(key, fallback = true) { - const value = getEnvVar(key); - if (!value) return fallback; - return value !== "0" && value.toLowerCase() !== "false" && value !== ""; -} -var _envShim, _getEnv, env, nodeENV, isProduction, isDevelopment, isTest, ENV; -var init_env_impl = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/env-impl.mjs"() { - _envShim = /* @__PURE__ */ Object.create(null); - _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis); - env = new Proxy(_envShim, { - get(_, prop) { - return _getEnv()[prop] ?? _envShim[prop]; - }, - has(_, prop) { - return prop in _getEnv() || prop in _envShim; - }, - set(_, prop, value) { - const env2 = _getEnv(true); - env2[prop] = value; - return true; - }, - deleteProperty(_, prop) { - if (!prop) return false; - const env2 = _getEnv(true); - delete env2[prop]; - return true; - }, - ownKeys() { - const env2 = _getEnv(true); - return Object.keys(env2); - } - }); - nodeENV = typeof process !== "undefined" && process.env && process.env.NODE_ENV || ""; - isProduction = nodeENV === "production"; - isDevelopment = () => nodeENV === "dev" || nodeENV === "development"; - isTest = () => nodeENV === "test" || toBoolean(env.TEST); - ENV = Object.freeze({ - get BETTER_AUTH_SECRET() { - return getEnvVar("BETTER_AUTH_SECRET"); - }, - get AUTH_SECRET() { - return getEnvVar("AUTH_SECRET"); - }, - get BETTER_AUTH_TELEMETRY() { - return getEnvVar("BETTER_AUTH_TELEMETRY"); - }, - get BETTER_AUTH_TELEMETRY_ID() { - return getEnvVar("BETTER_AUTH_TELEMETRY_ID"); - }, - get NODE_ENV() { - return getEnvVar("NODE_ENV", "development"); - }, - get PACKAGE_VERSION() { - return getEnvVar("PACKAGE_VERSION", "0.0.0"); - }, - get BETTER_AUTH_TELEMETRY_ENDPOINT() { - return getEnvVar("BETTER_AUTH_TELEMETRY_ENDPOINT", ""); - } - }); - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/color-depth.mjs -function getColorDepth() { - if (getEnvVar("FORCE_COLOR") !== void 0) switch (getEnvVar("FORCE_COLOR")) { - case "": - case "1": - case "true": - return COLORS_16; - case "2": - return COLORS_256; - case "3": - return COLORS_16m; - default: - return COLORS_2; - } - if (getEnvVar("NODE_DISABLE_COLORS") !== void 0 && getEnvVar("NODE_DISABLE_COLORS") !== "" || getEnvVar("NO_COLOR") !== void 0 && getEnvVar("NO_COLOR") !== "" || getEnvVar("TERM") === "dumb") return COLORS_2; - if (getEnvVar("TMUX")) return COLORS_16m; - if ("TF_BUILD" in env && "AGENT_NAME" in env) return COLORS_16; - if ("CI" in env) { - for (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors; - if (getEnvVar("CI_NAME") === "codeship") return COLORS_256; - return COLORS_2; - } - if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(getEnvVar("TEAMCITY_VERSION")) !== null ? COLORS_16 : COLORS_2; - switch (getEnvVar("TERM_PROGRAM")) { - case "iTerm.app": - if (!getEnvVar("TERM_PROGRAM_VERSION") || /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null) return COLORS_256; - return COLORS_16m; - case "HyperTerm": - case "MacTerm": - return COLORS_16m; - case "Apple_Terminal": - return COLORS_256; - } - if (getEnvVar("COLORTERM") === "truecolor" || getEnvVar("COLORTERM") === "24bit") return COLORS_16m; - if (getEnvVar("TERM")) { - if (/truecolor/.exec(getEnvVar("TERM")) !== null) return COLORS_16m; - if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) return COLORS_256; - const termEnv = getEnvVar("TERM").toLowerCase(); - if (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv]; - if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16; - } - if (getEnvVar("COLORTERM")) return COLORS_16; - return COLORS_2; -} -var COLORS_2, COLORS_16, COLORS_256, COLORS_16m, TERM_ENVS, CI_ENVS_MAP, TERM_ENVS_REG_EXP; -var init_color_depth = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/color-depth.mjs"() { - init_env_impl(); - COLORS_2 = 1; - COLORS_16 = 4; - COLORS_256 = 8; - COLORS_16m = 24; - TERM_ENVS = { - eterm: COLORS_16, - cons25: COLORS_16, - console: COLORS_16, - cygwin: COLORS_16, - dtterm: COLORS_16, - gnome: COLORS_16, - hurd: COLORS_16, - jfbterm: COLORS_16, - konsole: COLORS_16, - kterm: COLORS_16, - mlterm: COLORS_16, - mosh: COLORS_16m, - putty: COLORS_16, - st: COLORS_16, - "rxvt-unicode-24bit": COLORS_16m, - terminator: COLORS_16m, - "xterm-kitty": COLORS_16m - }; - CI_ENVS_MAP = new Map(Object.entries({ - APPVEYOR: COLORS_256, - BUILDKITE: COLORS_256, - CIRCLECI: COLORS_16m, - DRONE: COLORS_256, - GITEA_ACTIONS: COLORS_16m, - GITHUB_ACTIONS: COLORS_16m, - GITLAB_CI: COLORS_256, - TRAVIS: COLORS_256 - })); - TERM_ENVS_REG_EXP = [ - /ansi/, - /color/, - /linux/, - /direct/, - /^con[0-9]*x[0-9]/, - /^rxvt/, - /^screen/, - /^xterm/, - /^vt100/, - /^vt220/ - ]; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/logger.mjs -function shouldPublishLog(currentLogLevel, logLevel) { - return levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel); -} -var TTY_COLORS, levels, levelColors, formatMessage, createLogger2, logger; -var init_logger = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/logger.mjs"() { - init_color_depth(); - TTY_COLORS = { - reset: "\x1B[0m", - bright: "\x1B[1m", - dim: "\x1B[2m", - undim: "\x1B[22m", - underscore: "\x1B[4m", - blink: "\x1B[5m", - reverse: "\x1B[7m", - hidden: "\x1B[8m", - fg: { - black: "\x1B[30m", - red: "\x1B[31m", - green: "\x1B[32m", - yellow: "\x1B[33m", - blue: "\x1B[34m", - magenta: "\x1B[35m", - cyan: "\x1B[36m", - white: "\x1B[37m" - }, - bg: { - black: "\x1B[40m", - red: "\x1B[41m", - green: "\x1B[42m", - yellow: "\x1B[43m", - blue: "\x1B[44m", - magenta: "\x1B[45m", - cyan: "\x1B[46m", - white: "\x1B[47m" - } - }; - levels = [ - "debug", - "info", - "success", - "warn", - "error" - ]; - levelColors = { - info: TTY_COLORS.fg.blue, - success: TTY_COLORS.fg.green, - warn: TTY_COLORS.fg.yellow, - error: TTY_COLORS.fg.red, - debug: TTY_COLORS.fg.magenta - }; - formatMessage = (level, message2, colorsEnabled) => { - const timestamp = (/* @__PURE__ */ new Date()).toISOString(); - if (colorsEnabled) return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message2}`; - return `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message2}`; - }; - createLogger2 = (options) => { - const enabled = options?.disabled !== true; - const logLevel = options?.level ?? "warn"; - const colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1; - const LogFunc = (level, message2, args = []) => { - if (!enabled || !shouldPublishLog(logLevel, level)) return; - const formattedMessage = formatMessage(level, message2, colorsEnabled); - if (!options || typeof options.log !== "function") { - if (level === "error") console.error(formattedMessage, ...args); - else if (level === "warn") console.warn(formattedMessage, ...args); - else console.log(formattedMessage, ...args); - return; - } - options.log(level === "success" ? "info" : level, message2, ...args); - }; - return { - ...Object.fromEntries(levels.map((level) => [level, (...[message2, ...args]) => LogFunc(level, message2, args)])), - get level() { - return logLevel; - } - }; - }; - logger = createLogger2(); - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/index.mjs -var init_env = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/index.mjs"() { - init_env_impl(); - init_logger(); - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/error-codes.mjs -function defineErrorCodes(codes) { - return Object.fromEntries(Object.entries(codes).map(([key, value]) => [key, { - code: key, - message: value, - toString: () => key - }])); -} -var init_error_codes = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/error-codes.mjs"() { - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/codes.mjs -var BASE_ERROR_CODES; -var init_codes = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/codes.mjs"() { - init_error_codes(); - BASE_ERROR_CODES = defineErrorCodes({ - USER_NOT_FOUND: "User not found", - FAILED_TO_CREATE_USER: "Failed to create user", - FAILED_TO_CREATE_SESSION: "Failed to create session", - FAILED_TO_UPDATE_USER: "Failed to update user", - FAILED_TO_GET_SESSION: "Failed to get session", - INVALID_PASSWORD: "Invalid password", - INVALID_EMAIL: "Invalid email", - INVALID_EMAIL_OR_PASSWORD: "Invalid email or password", - INVALID_USER: "Invalid user", - SOCIAL_ACCOUNT_ALREADY_LINKED: "Social account already linked", - PROVIDER_NOT_FOUND: "Provider not found", - INVALID_TOKEN: "Invalid token", - TOKEN_EXPIRED: "Token expired", - ID_TOKEN_NOT_SUPPORTED: "id_token not supported", - FAILED_TO_GET_USER_INFO: "Failed to get user info", - USER_EMAIL_NOT_FOUND: "User email not found", - EMAIL_NOT_VERIFIED: "Email not verified", - PASSWORD_TOO_SHORT: "Password too short", - PASSWORD_TOO_LONG: "Password too long", - USER_ALREADY_EXISTS: "User already exists.", - USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "User already exists. Use another email.", - EMAIL_CAN_NOT_BE_UPDATED: "Email can not be updated", - CREDENTIAL_ACCOUNT_NOT_FOUND: "Credential account not found", - SESSION_EXPIRED: "Session expired. Re-authenticate to perform this action.", - FAILED_TO_UNLINK_LAST_ACCOUNT: "You can't unlink your last account", - ACCOUNT_NOT_FOUND: "Account not found", - USER_ALREADY_HAS_PASSWORD: "User already has a password. Provide that to delete the account.", - CROSS_SITE_NAVIGATION_LOGIN_BLOCKED: "Cross-site navigation login blocked. This request appears to be a CSRF attack.", - VERIFICATION_EMAIL_NOT_ENABLED: "Verification email isn't enabled", - EMAIL_ALREADY_VERIFIED: "Email is already verified", - EMAIL_MISMATCH: "Email mismatch", - SESSION_NOT_FRESH: "Session is not fresh", - LINKED_ACCOUNT_ALREADY_EXISTS: "Linked account already exists", - INVALID_ORIGIN: "Invalid origin", - INVALID_CALLBACK_URL: "Invalid callbackURL", - INVALID_REDIRECT_URL: "Invalid redirectURL", - INVALID_ERROR_CALLBACK_URL: "Invalid errorCallbackURL", - INVALID_NEW_USER_CALLBACK_URL: "Invalid newUserCallbackURL", - MISSING_OR_NULL_ORIGIN: "Missing or null Origin", - CALLBACK_URL_REQUIRED: "callbackURL is required", - FAILED_TO_CREATE_VERIFICATION: "Unable to create verification", - FIELD_NOT_ALLOWED: "Field not allowed to be set", - ASYNC_VALIDATION_NOT_SUPPORTED: "Async validation is not supported", - VALIDATION_ERROR: "Validation Error", - MISSING_FIELD: "Field is required", - METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED: "POST method requires deferSessionRefresh to be enabled in session config", - BODY_MUST_BE_AN_OBJECT: "Body must be an object", - PASSWORD_ALREADY_SET: "User already has a password set" - }); - } -}); - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/error.mjs -function isErrorStackTraceLimitWritable() { - const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); - if (desc === void 0) return Object.isExtensible(Error); - return Object.prototype.hasOwnProperty.call(desc, "writable") ? desc.writable : desc.set !== void 0; -} -function hideInternalStackFrames(stack) { - const lines = stack.split("\n at "); - if (lines.length <= 1) return stack; - lines.splice(1, 1); - return lines.join("\n at "); -} -function makeErrorForHideStackFrame(Base, clazz) { - var _hiddenStack; - class HideStackFramesError extends Base { - constructor(...args2) { - var __super = (...args) => { - super(...args); - __privateAdd(this, _hiddenStack); - return this; - }; - if (isErrorStackTraceLimitWritable()) { - const limit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - __super(...args2); - Error.stackTraceLimit = limit; - } else __super(...args2); - const stack = (/* @__PURE__ */ new Error()).stack; - if (stack) __privateSet(this, _hiddenStack, hideInternalStackFrames(stack.replace(/^Error/, this.name))); - } - get errorStack() { - return __privateGet(this, _hiddenStack); - } - } - _hiddenStack = new WeakMap(); - Object.defineProperty(HideStackFramesError.prototype, "constructor", { - get() { - return clazz; - }, - enumerable: false, - configurable: true - }); - return HideStackFramesError; -} -var statusCodes, InternalAPIError, ValidationError, BetterCallError, kAPIErrorHeaderSymbol, APIError; -var init_error = __esm({ - "../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/error.mjs"() { - statusCodes = { - OK: 200, - CREATED: 201, - ACCEPTED: 202, - NO_CONTENT: 204, - MULTIPLE_CHOICES: 300, - MOVED_PERMANENTLY: 301, - FOUND: 302, - SEE_OTHER: 303, - NOT_MODIFIED: 304, - TEMPORARY_REDIRECT: 307, - BAD_REQUEST: 400, - UNAUTHORIZED: 401, - PAYMENT_REQUIRED: 402, - FORBIDDEN: 403, - NOT_FOUND: 404, - METHOD_NOT_ALLOWED: 405, - NOT_ACCEPTABLE: 406, - PROXY_AUTHENTICATION_REQUIRED: 407, - REQUEST_TIMEOUT: 408, - CONFLICT: 409, - GONE: 410, - LENGTH_REQUIRED: 411, - PRECONDITION_FAILED: 412, - PAYLOAD_TOO_LARGE: 413, - URI_TOO_LONG: 414, - UNSUPPORTED_MEDIA_TYPE: 415, - RANGE_NOT_SATISFIABLE: 416, - EXPECTATION_FAILED: 417, - "I'M_A_TEAPOT": 418, - MISDIRECTED_REQUEST: 421, - UNPROCESSABLE_ENTITY: 422, - LOCKED: 423, - FAILED_DEPENDENCY: 424, - TOO_EARLY: 425, - UPGRADE_REQUIRED: 426, - PRECONDITION_REQUIRED: 428, - TOO_MANY_REQUESTS: 429, - REQUEST_HEADER_FIELDS_TOO_LARGE: 431, - UNAVAILABLE_FOR_LEGAL_REASONS: 451, - INTERNAL_SERVER_ERROR: 500, - NOT_IMPLEMENTED: 501, - BAD_GATEWAY: 502, - SERVICE_UNAVAILABLE: 503, - GATEWAY_TIMEOUT: 504, - HTTP_VERSION_NOT_SUPPORTED: 505, - VARIANT_ALSO_NEGOTIATES: 506, - INSUFFICIENT_STORAGE: 507, - LOOP_DETECTED: 508, - NOT_EXTENDED: 510, - NETWORK_AUTHENTICATION_REQUIRED: 511 - }; - InternalAPIError = class extends Error { - constructor(status = "INTERNAL_SERVER_ERROR", body = void 0, headers = {}, statusCode = typeof status === "number" ? status : statusCodes[status]) { - super(body?.message, body?.cause ? { cause: body.cause } : void 0); - this.status = status; - this.body = body; - this.headers = headers; - this.statusCode = statusCode; - this.name = "APIError"; - this.status = status; - this.headers = headers; - this.statusCode = statusCode; - this.body = body; - } - }; - ValidationError = class extends InternalAPIError { - constructor(message2, issues) { - super(400, { - message: message2, - code: "VALIDATION_ERROR" - }); - this.message = message2; - this.issues = issues; - this.issues = issues; - } - }; - BetterCallError = class extends Error { - constructor(message2) { - super(message2); - this.name = "BetterCallError"; - } - }; - kAPIErrorHeaderSymbol = Symbol.for("better-call:api-error-headers"); - APIError = makeErrorForHideStackFrame(InternalAPIError, Error); - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/index.mjs -var BetterAuthError, APIError2; -var init_error2 = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/index.mjs"() { - init_codes(); - init_error(); - BetterAuthError = class extends Error { - constructor(message2, options) { - super(message2, options); - this.name = "BetterAuthError"; - this.message = message2; - this.stack = ""; - } - }; - APIError2 = class APIError3 extends APIError { - constructor(...args) { - super(...args); - } - static fromStatus(status, body) { - return new APIError3(status, body); - } - static from(status, error49) { - return new APIError3(status, { - message: error49.message, - code: error49.code - }); - } - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/random.mjs -function expandAlphabet(alphabet) { - switch (alphabet) { - case "a-z": - return "abcdefghijklmnopqrstuvwxyz"; - case "A-Z": - return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - case "0-9": - return "0123456789"; - case "-_": - return "-_"; - default: - throw new Error(`Unsupported alphabet: ${alphabet}`); - } -} -function createRandomStringGenerator(...baseAlphabets) { - const baseCharSet = baseAlphabets.map(expandAlphabet).join(""); - if (baseCharSet.length === 0) { - throw new Error( - "No valid characters provided for random string generation." - ); - } - const baseCharSetLength = baseCharSet.length; - return (length, ...alphabets) => { - if (length <= 0) { - throw new Error("Length must be a positive integer."); - } - let charSet = baseCharSet; - let charSetLength = baseCharSetLength; - if (alphabets.length > 0) { - charSet = alphabets.map(expandAlphabet).join(""); - charSetLength = charSet.length; - } - const maxValid = Math.floor(256 / charSetLength) * charSetLength; - const buf = new Uint8Array(length * 2); - const bufLength = buf.length; - let result = ""; - let bufIndex = bufLength; - let rand; - while (result.length < length) { - if (bufIndex >= bufLength) { - crypto.getRandomValues(buf); - bufIndex = 0; - } - rand = buf[bufIndex++]; - if (rand < maxValid) { - result += charSet[rand % charSetLength]; - } - } - return result; - }; -} -var init_random = __esm({ - "../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/random.mjs"() { - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/get-tables.mjs -var getAuthTables; -var init_get_tables = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/get-tables.mjs"() { - getAuthTables = (options) => { - const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => { - const schema3 = plugin.schema; - if (!schema3) return acc; - for (const [key, value] of Object.entries(schema3)) acc[key] = { - fields: { - ...acc[key]?.fields, - ...value.fields - }, - modelName: value.modelName || key - }; - return acc; - }, {}); - const shouldAddRateLimitTable = options.rateLimit?.storage === "database"; - const rateLimitTable = { rateLimit: { - modelName: options.rateLimit?.modelName || "rateLimit", - fields: { - key: { - type: "string", - unique: true, - required: true, - fieldName: options.rateLimit?.fields?.key || "key" - }, - count: { - type: "number", - required: true, - fieldName: options.rateLimit?.fields?.count || "count" - }, - lastRequest: { - type: "number", - bigint: true, - required: true, - fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest", - defaultValue: () => Date.now() - } - } - } }; - const { user, session, account, verification, ...pluginTables } = pluginSchema; - const verificationTable = { verification: { - modelName: options.verification?.modelName || "verification", - fields: { - identifier: { - type: "string", - required: true, - fieldName: options.verification?.fields?.identifier || "identifier", - index: true - }, - value: { - type: "string", - required: true, - fieldName: options.verification?.fields?.value || "value" - }, - expiresAt: { - type: "date", - required: true, - fieldName: options.verification?.fields?.expiresAt || "expiresAt" - }, - createdAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - fieldName: options.verification?.fields?.createdAt || "createdAt" - }, - updatedAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - onUpdate: () => /* @__PURE__ */ new Date(), - fieldName: options.verification?.fields?.updatedAt || "updatedAt" - }, - ...verification?.fields, - ...options.verification?.additionalFields - }, - order: 4 - } }; - const sessionTable = { session: { - modelName: options.session?.modelName || "session", - fields: { - expiresAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.expiresAt || "expiresAt" - }, - token: { - type: "string", - required: true, - fieldName: options.session?.fields?.token || "token", - unique: true - }, - createdAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.createdAt || "createdAt", - defaultValue: () => /* @__PURE__ */ new Date() - }, - updatedAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.updatedAt || "updatedAt", - onUpdate: () => /* @__PURE__ */ new Date() - }, - ipAddress: { - type: "string", - required: false, - fieldName: options.session?.fields?.ipAddress || "ipAddress" - }, - userAgent: { - type: "string", - required: false, - fieldName: options.session?.fields?.userAgent || "userAgent" - }, - userId: { - type: "string", - fieldName: options.session?.fields?.userId || "userId", - references: { - model: options.user?.modelName || "user", - field: "id", - onDelete: "cascade" - }, - required: true, - index: true - }, - ...session?.fields, - ...options.session?.additionalFields - }, - order: 2 - } }; - return { - user: { - modelName: options.user?.modelName || "user", - fields: { - name: { - type: "string", - required: true, - fieldName: options.user?.fields?.name || "name", - sortable: true - }, - email: { - type: "string", - unique: true, - required: true, - fieldName: options.user?.fields?.email || "email", - sortable: true - }, - emailVerified: { - type: "boolean", - defaultValue: false, - required: true, - fieldName: options.user?.fields?.emailVerified || "emailVerified", - input: false - }, - image: { - type: "string", - required: false, - fieldName: options.user?.fields?.image || "image" - }, - createdAt: { - type: "date", - defaultValue: () => /* @__PURE__ */ new Date(), - required: true, - fieldName: options.user?.fields?.createdAt || "createdAt" - }, - updatedAt: { - type: "date", - defaultValue: () => /* @__PURE__ */ new Date(), - onUpdate: () => /* @__PURE__ */ new Date(), - required: true, - fieldName: options.user?.fields?.updatedAt || "updatedAt" - }, - ...user?.fields, - ...options.user?.additionalFields - }, - order: 1 - }, - ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {}, - account: { - modelName: options.account?.modelName || "account", - fields: { - accountId: { - type: "string", - required: true, - fieldName: options.account?.fields?.accountId || "accountId" - }, - providerId: { - type: "string", - required: true, - fieldName: options.account?.fields?.providerId || "providerId" - }, - userId: { - type: "string", - references: { - model: options.user?.modelName || "user", - field: "id", - onDelete: "cascade" - }, - required: true, - fieldName: options.account?.fields?.userId || "userId", - index: true - }, - accessToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.accessToken || "accessToken" - }, - refreshToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.refreshToken || "refreshToken" - }, - idToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.idToken || "idToken" - }, - accessTokenExpiresAt: { - type: "date", - required: false, - returned: false, - fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt" - }, - refreshTokenExpiresAt: { - type: "date", - required: false, - returned: false, - fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt" - }, - scope: { - type: "string", - required: false, - fieldName: options.account?.fields?.scope || "scope" - }, - password: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.password || "password" - }, - createdAt: { - type: "date", - required: true, - fieldName: options.account?.fields?.createdAt || "createdAt", - defaultValue: () => /* @__PURE__ */ new Date() - }, - updatedAt: { - type: "date", - required: true, - fieldName: options.account?.fields?.updatedAt || "updatedAt", - onUpdate: () => /* @__PURE__ */ new Date() - }, - ...account?.fields, - ...options.account?.additionalFields - }, - order: 3 - }, - ...!options.secondaryStorage || options.verification?.storeInDatabase ? verificationTable : {}, - ...pluginTables, - ...shouldAddRateLimitTable ? rateLimitTable : {} - }; - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/json.mjs -function reviveDate(value) { - if (typeof value === "string" && iso8601Regex.test(value)) { - const date5 = new Date(value); - if (!isNaN(date5.getTime())) return date5; - } - return value; -} -function reviveDates(value) { - if (value === null || value === void 0) return value; - if (typeof value === "string") return reviveDate(value); - if (value instanceof Date) return value; - if (Array.isArray(value)) return value.map(reviveDates); - if (typeof value === "object") { - const result = {}; - for (const key of Object.keys(value)) result[key] = reviveDates(value[key]); - return result; - } - return value; -} -function safeJSONParse(data) { - try { - if (typeof data !== "string") { - if (data === null || data === void 0) return null; - return reviveDates(data); - } - return JSON.parse(data, (_, value) => reviveDate(value)); - } catch (e) { - logger.error("Error parsing JSON", { error: e }); - return null; - } -} -var iso8601Regex; -var init_json = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/json.mjs"() { - init_logger(); - iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/; - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js -var init_SemanticAttributes = __esm({ - "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js"() { - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js -var init_trace = __esm({ - "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js"() { - init_SemanticAttributes(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js -var init_SemanticResourceAttributes = __esm({ - "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js"() { - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js -var init_resource = __esm({ - "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js"() { - init_SemanticResourceAttributes(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js -var ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE; -var init_stable_attributes = __esm({ - "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js"() { - ATTR_DB_COLLECTION_NAME = "db.collection.name"; - ATTR_DB_OPERATION_NAME = "db.operation.name"; - ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; - ATTR_HTTP_ROUTE = "http.route"; - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.js -var init_stable_metrics = __esm({ - "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.js"() { - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.js -var init_stable_events = __esm({ - "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.js"() { - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/index.js -var init_esm = __esm({ - "../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/build/esm/index.js"() { - init_trace(); - init_resource(); - init_stable_attributes(); - init_stable_metrics(); - init_stable_events(); - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/attributes.mjs -var ATTR_OPERATION_ID, ATTR_HOOK_TYPE, ATTR_CONTEXT; -var init_attributes = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/attributes.mjs"() { - init_esm(); - ATTR_OPERATION_ID = "better_auth.operation_id"; - ATTR_HOOK_TYPE = "better_auth.hook.type"; - ATTR_CONTEXT = "better_auth.context"; - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js -var _globalThis; -var init_globalThis = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js"() { - _globalThis = typeof globalThis === "object" ? globalThis : global; - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/index.js -var init_node = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/index.js"() { - init_globalThis(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/index.js -var init_platform = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/index.js"() { - init_node(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/version.js -var VERSION; -var init_version = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/version.js"() { - VERSION = "1.9.0"; - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/semver.js -function _makeCompatibilityCheck(ownVersion) { - var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); - var rejectedVersions = /* @__PURE__ */ new Set(); - var myVersionMatch = ownVersion.match(re); - if (!myVersionMatch) { - return function() { - return false; - }; - } - var ownVersionParsed = { - major: +myVersionMatch[1], - minor: +myVersionMatch[2], - patch: +myVersionMatch[3], - prerelease: myVersionMatch[4] - }; - if (ownVersionParsed.prerelease != null) { - return function isExactmatch(globalVersion) { - return globalVersion === ownVersion; - }; - } - function _reject2(v) { - rejectedVersions.add(v); - return false; - } - function _accept(v) { - acceptedVersions.add(v); - return true; - } - return function isCompatible2(globalVersion) { - if (acceptedVersions.has(globalVersion)) { - return true; - } - if (rejectedVersions.has(globalVersion)) { - return false; - } - var globalVersionMatch = globalVersion.match(re); - if (!globalVersionMatch) { - return _reject2(globalVersion); - } - var globalVersionParsed = { - major: +globalVersionMatch[1], - minor: +globalVersionMatch[2], - patch: +globalVersionMatch[3], - prerelease: globalVersionMatch[4] - }; - if (globalVersionParsed.prerelease != null) { - return _reject2(globalVersion); - } - if (ownVersionParsed.major !== globalVersionParsed.major) { - return _reject2(globalVersion); - } - if (ownVersionParsed.major === 0) { - if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { - return _accept(globalVersion); - } - return _reject2(globalVersion); - } - if (ownVersionParsed.minor <= globalVersionParsed.minor) { - return _accept(globalVersion); - } - return _reject2(globalVersion); - }; -} -var re, isCompatible; -var init_semver = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/semver.js"() { - init_version(); - re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; - isCompatible = _makeCompatibilityCheck(VERSION); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js -function registerGlobal(type, instance, diag, allowOverride) { - var _a30; - if (allowOverride === void 0) { - allowOverride = false; - } - var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a30 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a30 !== void 0 ? _a30 : { - version: VERSION - }; - if (!allowOverride && api[type]) { - var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); - diag.error(err.stack || err.message); - return false; - } - if (api.version !== VERSION) { - var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION); - diag.error(err.stack || err.message); - return false; - } - api[type] = instance; - diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + "."); - return true; -} -function getGlobal(type) { - var _a30, _b2; - var globalVersion = (_a30 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a30 === void 0 ? void 0 : _a30.version; - if (!globalVersion || !isCompatible(globalVersion)) { - return; - } - return (_b2 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b2 === void 0 ? void 0 : _b2[type]; -} -function unregisterGlobal(type, diag) { - diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + "."); - var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; - if (api) { - delete api[type]; - } -} -var major, GLOBAL_OPENTELEMETRY_API_KEY, _global; -var init_global_utils = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js"() { - init_platform(); - init_version(); - init_semver(); - major = VERSION.split(".")[0]; - GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); - _global = _globalThis; - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js -function logProxy(funcName, namespace, args) { - var logger2 = getGlobal("diag"); - if (!logger2) { - return; - } - args.unshift(namespace); - return logger2[funcName].apply(logger2, __spreadArray([], __read(args), false)); -} -var __read, __spreadArray, DiagComponentLogger; -var init_ComponentLogger = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js"() { - init_global_utils(); - __read = function(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error49) { - e = { error: error49 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; - }; - __spreadArray = function(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - DiagComponentLogger = /** @class */ - function() { - function DiagComponentLogger2(props) { - this._namespace = props.namespace || "DiagComponentLogger"; - } - DiagComponentLogger2.prototype.debug = function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return logProxy("debug", this._namespace, args); - }; - DiagComponentLogger2.prototype.error = function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return logProxy("error", this._namespace, args); - }; - DiagComponentLogger2.prototype.info = function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return logProxy("info", this._namespace, args); - }; - DiagComponentLogger2.prototype.warn = function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return logProxy("warn", this._namespace, args); - }; - DiagComponentLogger2.prototype.verbose = function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return logProxy("verbose", this._namespace, args); - }; - return DiagComponentLogger2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/types.js -var DiagLogLevel; -var init_types = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/types.js"() { - (function(DiagLogLevel2) { - DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE"; - DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR"; - DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN"; - DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO"; - DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG"; - DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE"; - DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL"; - })(DiagLogLevel || (DiagLogLevel = {})); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger2) { - if (maxLevel < DiagLogLevel.NONE) { - maxLevel = DiagLogLevel.NONE; - } else if (maxLevel > DiagLogLevel.ALL) { - maxLevel = DiagLogLevel.ALL; - } - logger2 = logger2 || {}; - function _filterFunc(funcName, theLevel) { - var theFunc = logger2[funcName]; - if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger2); - } - return function() { - }; - } - return { - error: _filterFunc("error", DiagLogLevel.ERROR), - warn: _filterFunc("warn", DiagLogLevel.WARN), - info: _filterFunc("info", DiagLogLevel.INFO), - debug: _filterFunc("debug", DiagLogLevel.DEBUG), - verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE) - }; -} -var init_logLevelLogger = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js"() { - init_types(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/diag.js -var __read2, __spreadArray2, API_NAME, DiagAPI; -var init_diag = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/diag.js"() { - init_ComponentLogger(); - init_logLevelLogger(); - init_types(); - init_global_utils(); - __read2 = function(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error49) { - e = { error: error49 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; - }; - __spreadArray2 = function(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - API_NAME = "diag"; - DiagAPI = /** @class */ - function() { - function DiagAPI2() { - function _logProxy(funcName) { - return function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var logger2 = getGlobal("diag"); - if (!logger2) - return; - return logger2[funcName].apply(logger2, __spreadArray2([], __read2(args), false)); - }; - } - var self = this; - var setLogger = function(logger2, optionsOrLogLevel) { - var _a30, _b2, _c; - if (optionsOrLogLevel === void 0) { - optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }; - } - if (logger2 === self) { - var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); - self.error((_a30 = err.stack) !== null && _a30 !== void 0 ? _a30 : err.message); - return false; - } - if (typeof optionsOrLogLevel === "number") { - optionsOrLogLevel = { - logLevel: optionsOrLogLevel - }; - } - var oldLogger = getGlobal("diag"); - var newLogger = createLogLevelDiagLogger((_b2 = optionsOrLogLevel.logLevel) !== null && _b2 !== void 0 ? _b2 : DiagLogLevel.INFO, logger2); - if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { - var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; - oldLogger.warn("Current logger will be overwritten from " + stack); - newLogger.warn("Current logger will overwrite one already registered from " + stack); - } - return registerGlobal("diag", newLogger, self, true); - }; - self.setLogger = setLogger; - self.disable = function() { - unregisterGlobal(API_NAME, self); - }; - self.createComponentLogger = function(options) { - return new DiagComponentLogger(options); - }; - self.verbose = _logProxy("verbose"); - self.debug = _logProxy("debug"); - self.info = _logProxy("info"); - self.warn = _logProxy("warn"); - self.error = _logProxy("error"); - } - DiagAPI2.instance = function() { - if (!this._instance) { - this._instance = new DiagAPI2(); - } - return this._instance; - }; - return DiagAPI2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/context.js -function createContextKey(description) { - return Symbol.for(description); -} -var BaseContext, ROOT_CONTEXT; -var init_context = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/context.js"() { - BaseContext = /** @class */ - /* @__PURE__ */ function() { - function BaseContext2(parentContext) { - var self = this; - self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); - self.getValue = function(key) { - return self._currentContext.get(key); - }; - self.setValue = function(key, value) { - var context = new BaseContext2(self._currentContext); - context._currentContext.set(key, value); - return context; - }; - self.deleteValue = function(key) { - var context = new BaseContext2(self._currentContext); - context._currentContext.delete(key); - return context; - }; - } - return BaseContext2; - }(); - ROOT_CONTEXT = new BaseContext(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js -var __read3, __spreadArray3, NoopContextManager; -var init_NoopContextManager = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js"() { - init_context(); - __read3 = function(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error49) { - e = { error: error49 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; - }; - __spreadArray3 = function(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - NoopContextManager = /** @class */ - function() { - function NoopContextManager2() { - } - NoopContextManager2.prototype.active = function() { - return ROOT_CONTEXT; - }; - NoopContextManager2.prototype.with = function(_context2, fn, thisArg) { - var args = []; - for (var _i = 3; _i < arguments.length; _i++) { - args[_i - 3] = arguments[_i]; - } - return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false)); - }; - NoopContextManager2.prototype.bind = function(_context2, target) { - return target; - }; - NoopContextManager2.prototype.enable = function() { - return this; - }; - NoopContextManager2.prototype.disable = function() { - return this; - }; - return NoopContextManager2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/context.js -var __read4, __spreadArray4, API_NAME2, NOOP_CONTEXT_MANAGER, ContextAPI; -var init_context2 = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/context.js"() { - init_NoopContextManager(); - init_global_utils(); - init_diag(); - __read4 = function(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error49) { - e = { error: error49 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; - }; - __spreadArray4 = function(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - API_NAME2 = "context"; - NOOP_CONTEXT_MANAGER = new NoopContextManager(); - ContextAPI = /** @class */ - function() { - function ContextAPI2() { - } - ContextAPI2.getInstance = function() { - if (!this._instance) { - this._instance = new ContextAPI2(); - } - return this._instance; - }; - ContextAPI2.prototype.setGlobalContextManager = function(contextManager) { - return registerGlobal(API_NAME2, contextManager, DiagAPI.instance()); - }; - ContextAPI2.prototype.active = function() { - return this._getContextManager().active(); - }; - ContextAPI2.prototype.with = function(context, fn, thisArg) { - var _a30; - var args = []; - for (var _i = 3; _i < arguments.length; _i++) { - args[_i - 3] = arguments[_i]; - } - return (_a30 = this._getContextManager()).with.apply(_a30, __spreadArray4([context, fn, thisArg], __read4(args), false)); - }; - ContextAPI2.prototype.bind = function(context, target) { - return this._getContextManager().bind(context, target); - }; - ContextAPI2.prototype._getContextManager = function() { - return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER; - }; - ContextAPI2.prototype.disable = function() { - this._getContextManager().disable(); - unregisterGlobal(API_NAME2, DiagAPI.instance()); - }; - return ContextAPI2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js -var TraceFlags; -var init_trace_flags = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js"() { - (function(TraceFlags2) { - TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE"; - TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED"; - })(TraceFlags || (TraceFlags = {})); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js -var INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT; -var init_invalid_span_constants = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js"() { - init_trace_flags(); - INVALID_SPANID = "0000000000000000"; - INVALID_TRACEID = "00000000000000000000000000000000"; - INVALID_SPAN_CONTEXT = { - traceId: INVALID_TRACEID, - spanId: INVALID_SPANID, - traceFlags: TraceFlags.NONE - }; - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js -var NonRecordingSpan; -var init_NonRecordingSpan = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js"() { - init_invalid_span_constants(); - NonRecordingSpan = /** @class */ - function() { - function NonRecordingSpan2(_spanContext) { - if (_spanContext === void 0) { - _spanContext = INVALID_SPAN_CONTEXT; - } - this._spanContext = _spanContext; - } - NonRecordingSpan2.prototype.spanContext = function() { - return this._spanContext; - }; - NonRecordingSpan2.prototype.setAttribute = function(_key, _value) { - return this; - }; - NonRecordingSpan2.prototype.setAttributes = function(_attributes) { - return this; - }; - NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) { - return this; - }; - NonRecordingSpan2.prototype.addLink = function(_link) { - return this; - }; - NonRecordingSpan2.prototype.addLinks = function(_links) { - return this; - }; - NonRecordingSpan2.prototype.setStatus = function(_status2) { - return this; - }; - NonRecordingSpan2.prototype.updateName = function(_name) { - return this; - }; - NonRecordingSpan2.prototype.end = function(_endTime) { - }; - NonRecordingSpan2.prototype.isRecording = function() { - return false; - }; - NonRecordingSpan2.prototype.recordException = function(_exception, _time) { - }; - return NonRecordingSpan2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js -function getSpan(context) { - return context.getValue(SPAN_KEY) || void 0; -} -function getActiveSpan() { - return getSpan(ContextAPI.getInstance().active()); -} -function setSpan(context, span) { - return context.setValue(SPAN_KEY, span); -} -function deleteSpan(context) { - return context.deleteValue(SPAN_KEY); -} -function setSpanContext(context, spanContext) { - return setSpan(context, new NonRecordingSpan(spanContext)); -} -function getSpanContext(context) { - var _a30; - return (_a30 = getSpan(context)) === null || _a30 === void 0 ? void 0 : _a30.spanContext(); -} -var SPAN_KEY; -var init_context_utils = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js"() { - init_context(); - init_NonRecordingSpan(); - init_context2(); - SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN"); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js -function isValidTraceId(traceId) { - return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID; -} -function isValidSpanId(spanId) { - return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID; -} -function isSpanContextValid(spanContext) { - return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); -} -function wrapSpanContext(spanContext) { - return new NonRecordingSpan(spanContext); -} -var VALID_TRACEID_REGEX, VALID_SPANID_REGEX; -var init_spancontext_utils = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js"() { - init_invalid_span_constants(); - init_NonRecordingSpan(); - VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; - VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js -function isSpanContext(spanContext) { - return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number"; -} -var contextApi, NoopTracer; -var init_NoopTracer = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js"() { - init_context2(); - init_context_utils(); - init_NonRecordingSpan(); - init_spancontext_utils(); - contextApi = ContextAPI.getInstance(); - NoopTracer = /** @class */ - function() { - function NoopTracer2() { - } - NoopTracer2.prototype.startSpan = function(name, options, context) { - if (context === void 0) { - context = contextApi.active(); - } - var root = Boolean(options === null || options === void 0 ? void 0 : options.root); - if (root) { - return new NonRecordingSpan(); - } - var parentFromContext = context && getSpanContext(context); - if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) { - return new NonRecordingSpan(parentFromContext); - } else { - return new NonRecordingSpan(); - } - }; - NoopTracer2.prototype.startActiveSpan = function(name, arg2, arg3, arg4) { - var opts; - var ctx; - var fn; - if (arguments.length < 2) { - return; - } else if (arguments.length === 2) { - fn = arg2; - } else if (arguments.length === 3) { - opts = arg2; - fn = arg3; - } else { - opts = arg2; - ctx = arg3; - fn = arg4; - } - var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); - var span = this.startSpan(name, opts, parentContext); - var contextWithSpanSet = setSpan(parentContext, span); - return contextApi.with(contextWithSpanSet, fn, void 0, span); - }; - return NoopTracer2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js -var NOOP_TRACER, ProxyTracer; -var init_ProxyTracer = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js"() { - init_NoopTracer(); - NOOP_TRACER = new NoopTracer(); - ProxyTracer = /** @class */ - function() { - function ProxyTracer2(_provider, name, version3, options) { - this._provider = _provider; - this.name = name; - this.version = version3; - this.options = options; - } - ProxyTracer2.prototype.startSpan = function(name, options, context) { - return this._getTracer().startSpan(name, options, context); - }; - ProxyTracer2.prototype.startActiveSpan = function(_name, _options2, _context2, _fn) { - var tracer2 = this._getTracer(); - return Reflect.apply(tracer2.startActiveSpan, tracer2, arguments); - }; - ProxyTracer2.prototype._getTracer = function() { - if (this._delegate) { - return this._delegate; - } - var tracer2 = this._provider.getDelegateTracer(this.name, this.version, this.options); - if (!tracer2) { - return NOOP_TRACER; - } - this._delegate = tracer2; - return this._delegate; - }; - return ProxyTracer2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js -var NoopTracerProvider; -var init_NoopTracerProvider = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js"() { - init_NoopTracer(); - NoopTracerProvider = /** @class */ - function() { - function NoopTracerProvider2() { - } - NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options2) { - return new NoopTracer(); - }; - return NoopTracerProvider2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js -var NOOP_TRACER_PROVIDER, ProxyTracerProvider; -var init_ProxyTracerProvider = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js"() { - init_ProxyTracer(); - init_NoopTracerProvider(); - NOOP_TRACER_PROVIDER = new NoopTracerProvider(); - ProxyTracerProvider = /** @class */ - function() { - function ProxyTracerProvider2() { - } - ProxyTracerProvider2.prototype.getTracer = function(name, version3, options) { - var _a30; - return (_a30 = this.getDelegateTracer(name, version3, options)) !== null && _a30 !== void 0 ? _a30 : new ProxyTracer(this, name, version3, options); - }; - ProxyTracerProvider2.prototype.getDelegate = function() { - var _a30; - return (_a30 = this._delegate) !== null && _a30 !== void 0 ? _a30 : NOOP_TRACER_PROVIDER; - }; - ProxyTracerProvider2.prototype.setDelegate = function(delegate) { - this._delegate = delegate; - }; - ProxyTracerProvider2.prototype.getDelegateTracer = function(name, version3, options) { - var _a30; - return (_a30 = this._delegate) === null || _a30 === void 0 ? void 0 : _a30.getTracer(name, version3, options); - }; - return ProxyTracerProvider2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js -var SpanStatusCode; -var init_status = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"() { - (function(SpanStatusCode2) { - SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET"; - SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK"; - SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR"; - })(SpanStatusCode || (SpanStatusCode = {})); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/trace.js -var API_NAME3, TraceAPI; -var init_trace2 = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/trace.js"() { - init_global_utils(); - init_ProxyTracerProvider(); - init_spancontext_utils(); - init_context_utils(); - init_diag(); - API_NAME3 = "trace"; - TraceAPI = /** @class */ - function() { - function TraceAPI2() { - this._proxyTracerProvider = new ProxyTracerProvider(); - this.wrapSpanContext = wrapSpanContext; - this.isSpanContextValid = isSpanContextValid; - this.deleteSpan = deleteSpan; - this.getSpan = getSpan; - this.getActiveSpan = getActiveSpan; - this.getSpanContext = getSpanContext; - this.setSpan = setSpan; - this.setSpanContext = setSpanContext; - } - TraceAPI2.getInstance = function() { - if (!this._instance) { - this._instance = new TraceAPI2(); - } - return this._instance; - }; - TraceAPI2.prototype.setGlobalTracerProvider = function(provider) { - var success2 = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance()); - if (success2) { - this._proxyTracerProvider.setDelegate(provider); - } - return success2; - }; - TraceAPI2.prototype.getTracerProvider = function() { - return getGlobal(API_NAME3) || this._proxyTracerProvider; - }; - TraceAPI2.prototype.getTracer = function(name, version3) { - return this.getTracerProvider().getTracer(name, version3); - }; - TraceAPI2.prototype.disable = function() { - unregisterGlobal(API_NAME3, DiagAPI.instance()); - this._proxyTracerProvider = new ProxyTracerProvider(); - }; - return TraceAPI2; - }(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js -var trace; -var init_trace_api = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"() { - init_trace2(); - trace = TraceAPI.getInstance(); - } -}); - -// ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/index.js -var init_esm2 = __esm({ - "../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/index.js"() { - init_status(); - init_trace_api(); - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/tracer.mjs -function isRedirectError(err) { - if (err != null && typeof err === "object" && "name" in err && err.name === "APIError" && "statusCode" in err) { - const status = err.statusCode; - return status >= 300 && status < 400; - } - return false; -} -function endSpanWithError(span, err) { - if (isRedirectError(err)) { - span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, err.statusCode); - span.setStatus({ code: SpanStatusCode.OK }); - } else { - span.recordException(err); - span.setStatus({ - code: SpanStatusCode.ERROR, - message: String(err?.message ?? err) - }); - } - span.end(); -} -function withSpan(name, attributes, fn) { - return tracer.startActiveSpan(name, { attributes }, (span) => { - try { - const result = fn(); - if (result instanceof Promise) return result.then((value) => { - span.end(); - return value; - }).catch((err) => { - endSpanWithError(span, err); - throw err; - }); - span.end(); - return result; - } catch (err) { - endSpanWithError(span, err); - throw err; - } - }); -} -var tracer; -var init_tracer = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/tracer.mjs"() { - init_attributes(); - init_esm2(); - tracer = trace.getTracer("better-auth", "1.6.2"); - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/id.mjs -var generateId; -var init_id2 = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/id.mjs"() { - init_random(); - generateId = (size) => { - return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32); - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs -var initGetDefaultModelName; -var init_get_default_model_name = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs"() { - init_error2(); - initGetDefaultModelName = ({ usePlural, schema: schema3 }) => { - const getDefaultModelName = (model) => { - if (usePlural && model.charAt(model.length - 1) === "s") { - const pluralessModel = model.slice(0, -1); - let m2 = schema3[pluralessModel] ? pluralessModel : void 0; - if (!m2) m2 = Object.entries(schema3).find(([_, f]) => f.modelName === pluralessModel)?.[0]; - if (m2) return m2; - } - let m = schema3[model] ? model : void 0; - if (!m) m = Object.entries(schema3).find(([_, f]) => f.modelName === model)?.[0]; - if (!m) throw new BetterAuthError(`Model "${model}" not found in schema`); - return m; - }; - return getDefaultModelName; - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs -var initGetDefaultFieldName; -var init_get_default_field_name = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs"() { - init_error2(); - init_get_default_model_name(); - initGetDefaultFieldName = ({ schema: schema3, usePlural }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema: schema3, - usePlural - }); - const getDefaultFieldName = ({ field, model: unsafeModel }) => { - if (field === "id" || field === "_id") return "id"; - const model = getDefaultModelName(unsafeModel); - let f = schema3[model]?.fields[field]; - if (!f) { - const result = Object.entries(schema3[model].fields).find(([_, f2]) => f2.fieldName === field); - if (result) { - f = result[1]; - field = result[0]; - } - } - if (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`); - return field; - }; - return getDefaultFieldName; - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs -var initGetIdField; -var init_get_id_field = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs"() { - init_logger(); - init_id2(); - init_get_default_model_name(); - initGetIdField = ({ usePlural, schema: schema3, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => { - const getDefaultModelName = initGetDefaultModelName({ - usePlural, - schema: schema3 - }); - const idField = ({ customModelName, forceAllowId }) => { - const useNumberId = options.advanced?.database?.generateId === "serial"; - const useUUIDs = options.advanced?.database?.generateId === "uuid"; - const shouldGenerateId = (() => { - if (disableIdGeneration) return false; - else if (useNumberId && !forceAllowId) return false; - else if (useUUIDs) return !supportsUUIDs; - else return true; - })(); - const model = getDefaultModelName(customModelName ?? "id"); - return { - type: useNumberId ? "number" : "string", - required: shouldGenerateId ? true : false, - ...shouldGenerateId ? { defaultValue() { - if (disableIdGeneration) return void 0; - const generateId$1 = options.advanced?.database?.generateId; - if (generateId$1 === false || generateId$1 === "serial") return void 0; - if (typeof generateId$1 === "function") return generateId$1({ model }); - if (generateId$1 === "uuid") return crypto.randomUUID(); - if (customIdGenerator) return customIdGenerator({ model }); - return generateId(); - } } : {}, - transform: { - input: (value) => { - if (!value) return void 0; - if (useNumberId) { - const numberValue = Number(value); - if (isNaN(numberValue)) return; - return numberValue; - } - if (useUUIDs) { - if (shouldGenerateId && !forceAllowId) return value; - if (disableIdGeneration) return void 0; - if (supportsUUIDs) return void 0; - if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value; - else { - const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", ""); - logger.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack); - } - if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID(); - return; - } - return value; - }, - output: (value) => { - if (!value) return void 0; - return String(value); - } - } - }; - }; - return idField; - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs -var initGetFieldAttributes; -var init_get_field_attributes = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs"() { - init_error2(); - init_get_default_model_name(); - init_get_default_field_name(); - init_get_id_field(); - initGetFieldAttributes = ({ usePlural, schema: schema3, options, customIdGenerator, disableIdGeneration }) => { - const getDefaultModelName = initGetDefaultModelName({ - usePlural, - schema: schema3 - }); - const getDefaultFieldName = initGetDefaultFieldName({ - usePlural, - schema: schema3 - }); - const idField = initGetIdField({ - usePlural, - schema: schema3, - options, - customIdGenerator, - disableIdGeneration - }); - const getFieldAttributes = ({ model, field }) => { - const defaultModelName = getDefaultModelName(model); - const defaultFieldName = getDefaultFieldName({ - field, - model: defaultModelName - }); - const fields = schema3[defaultModelName].fields; - fields.id = idField({ customModelName: defaultModelName }); - const fieldAttributes = fields[defaultFieldName]; - if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`); - return fieldAttributes; - }; - return getFieldAttributes; - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs -var initGetFieldName; -var init_get_field_name = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs"() { - init_get_default_model_name(); - init_get_default_field_name(); - initGetFieldName = ({ schema: schema3, usePlural }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema: schema3, - usePlural - }); - const getDefaultFieldName = initGetDefaultFieldName({ - schema: schema3, - usePlural - }); - function getFieldName({ model: modelName, field: fieldName }) { - const model = getDefaultModelName(modelName); - const field = getDefaultFieldName({ - model, - field: fieldName - }); - return schema3[model]?.fields[field]?.fieldName || field; - } - return getFieldName; - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs -var initGetModelName; -var init_get_model_name = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs"() { - init_get_default_model_name(); - initGetModelName = ({ usePlural, schema: schema3 }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema: schema3, - usePlural - }); - const getModelName = (model) => { - const defaultModelKey = getDefaultModelName(model); - if (schema3 && schema3[defaultModelKey] && schema3[defaultModelKey].modelName !== model) return usePlural ? `${schema3[defaultModelKey].modelName}s` : schema3[defaultModelKey].modelName; - return usePlural ? `${model}s` : model; - }; - return getModelName; - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/utils.mjs -function withApplyDefault(value, field, action) { - if (action === "update") { - if (value === void 0 && field.onUpdate !== void 0) { - if (typeof field.onUpdate === "function") return field.onUpdate(); - return field.onUpdate; - } - return value; - } - if (action === "create") { - if (value === void 0 || field.required === true && value === null) { - if (field.defaultValue !== void 0) { - if (typeof field.defaultValue === "function") return field.defaultValue(); - return field.defaultValue; - } - } - } - return value; -} -var init_utils = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/utils.mjs"() { - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/factory.mjs -function formatTransactionId(transactionId2) { - if (getColorDepth() < 8) return `#${transactionId2}`; - return `${TTY_COLORS.fg.magenta}#${transactionId2}${TTY_COLORS.reset}`; -} -function formatStep(step, total) { - return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`; -} -function formatMethod(method) { - return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`; -} -function formatAction(action) { - return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`; -} -var debugLogs, transactionId, createAsIsTransaction, createAdapterFactory; -var init_factory = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/factory.mjs"() { - init_get_tables(); - init_color_depth(); - init_logger(); - init_error2(); - init_attributes(); - init_tracer(); - init_json(); - init_get_default_model_name(); - init_get_default_field_name(); - init_get_id_field(); - init_get_field_attributes(); - init_get_field_name(); - init_get_model_name(); - init_utils(); - debugLogs = []; - transactionId = -1; - createAsIsTransaction = (adapter) => (fn) => fn(adapter); - createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => { - const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15); - const config4 = { - ...cfg, - supportsBooleans: cfg.supportsBooleans ?? true, - supportsDates: cfg.supportsDates ?? true, - supportsJSON: cfg.supportsJSON ?? false, - adapterName: cfg.adapterName ?? cfg.adapterId, - supportsNumericIds: cfg.supportsNumericIds ?? true, - supportsUUIDs: cfg.supportsUUIDs ?? false, - supportsArrays: cfg.supportsArrays ?? false, - transaction: cfg.transaction ?? false, - disableTransformInput: cfg.disableTransformInput ?? false, - disableTransformOutput: cfg.disableTransformOutput ?? false, - disableTransformJoin: cfg.disableTransformJoin ?? false - }; - if (options.advanced?.database?.generateId === "serial" && config4.supportsNumericIds === false) throw new BetterAuthError(`[${config4.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`); - const schema3 = getAuthTables(options); - const debugLog = (...args) => { - if (config4.debugLogs === true || typeof config4.debugLogs === "object") { - const logger3 = createLogger2({ level: "info" }); - if (typeof config4.debugLogs === "object" && "isRunningAdapterTests" in config4.debugLogs) { - if (config4.debugLogs.isRunningAdapterTests) { - args.shift(); - debugLogs.push({ - instance: uniqueAdapterFactoryInstanceId, - args - }); - } - return; - } - if (typeof config4.debugLogs === "object" && config4.debugLogs.logCondition && !config4.debugLogs.logCondition?.()) return; - if (typeof args[0] === "object" && "method" in args[0]) { - const method = args.shift().method; - if (typeof config4.debugLogs === "object") { - if (method === "create" && !config4.debugLogs.create) return; - else if (method === "update" && !config4.debugLogs.update) return; - else if (method === "updateMany" && !config4.debugLogs.updateMany) return; - else if (method === "findOne" && !config4.debugLogs.findOne) return; - else if (method === "findMany" && !config4.debugLogs.findMany) return; - else if (method === "delete" && !config4.debugLogs.delete) return; - else if (method === "deleteMany" && !config4.debugLogs.deleteMany) return; - else if (method === "count" && !config4.debugLogs.count) return; - } - logger3.info(`[${config4.adapterName}]`, ...args); - } else logger3.info(`[${config4.adapterName}]`, ...args); - } - }; - const logger2 = createLogger2(options.logger); - const getDefaultModelName = initGetDefaultModelName({ - usePlural: config4.usePlural, - schema: schema3 - }); - const getDefaultFieldName = initGetDefaultFieldName({ - usePlural: config4.usePlural, - schema: schema3 - }); - const getModelName = initGetModelName({ - usePlural: config4.usePlural, - schema: schema3 - }); - const getFieldName = initGetFieldName({ - schema: schema3, - usePlural: config4.usePlural - }); - const idField = initGetIdField({ - schema: schema3, - options, - usePlural: config4.usePlural, - disableIdGeneration: config4.disableIdGeneration, - customIdGenerator: config4.customIdGenerator, - supportsUUIDs: config4.supportsUUIDs - }); - const getFieldAttributes = initGetFieldAttributes({ - schema: schema3, - options, - usePlural: config4.usePlural, - disableIdGeneration: config4.disableIdGeneration, - customIdGenerator: config4.customIdGenerator - }); - const transformInput = async (data, defaultModelName, action, forceAllowId) => { - const transformedData = {}; - const fields = schema3[defaultModelName].fields; - const newMappedKeys = config4.mapKeysTransformInput ?? {}; - const useNumberId = options.advanced?.database?.generateId === "serial"; - fields.id = idField({ - customModelName: defaultModelName, - forceAllowId: forceAllowId && "id" in data - }); - for (const field in fields) { - let value = data[field]; - const fieldAttributes = fields[field]; - const newFieldName = newMappedKeys[field] || fields[field].fieldName || field; - if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue; - if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try { - value = new Date(value); - } catch { - logger2.error("[Adapter Factory] Failed to convert string to date", { - value, - field - }); - } - let newValue = withApplyDefault(value, fieldAttributes, action); - if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue); - if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null); - else newValue = newValue !== null ? Number(newValue) : null; - else if (config4.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue); - else if (config4.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue); - else if (config4.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString(); - else if (config4.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0; - if (config4.customTransformInput) newValue = config4.customTransformInput({ - data: newValue, - action, - field: newFieldName, - fieldAttributes, - model: getModelName(defaultModelName), - schema: schema3, - options - }); - if (newValue !== void 0) transformedData[newFieldName] = newValue; - } - return transformedData; - }; - const transformOutput = async (data, unsafe_model, select = [], join2) => { - const transformSingleOutput = async (data2, unsafe_model2, select2 = []) => { - if (!data2) return null; - const newMappedKeys = config4.mapKeysTransformOutput ?? {}; - const transformedData2 = {}; - const tableSchema = schema3[getDefaultModelName(unsafe_model2)].fields; - const idKey = Object.entries(newMappedKeys).find(([_, v]) => v === "id")?.[0]; - tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.generateId === "serial" ? "number" : "string" }; - for (const key in tableSchema) { - if (select2.length && !select2.includes(key)) continue; - const field = tableSchema[key]; - if (field) { - const originalKey = field.fieldName || key; - let newValue = data2[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey]; - if (field.transform?.output) newValue = await field.transform.output(newValue); - const newFieldName = newMappedKeys[key] || key; - if (originalKey === "id" || field.references?.field === "id") { - if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue); - } else if (config4.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue); - else if (config4.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue); - else if (config4.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue); - else if (config4.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1; - if (config4.customTransformOutput) newValue = config4.customTransformOutput({ - data: newValue, - field: newFieldName, - fieldAttributes: field, - select: select2, - model: getModelName(unsafe_model2), - schema: schema3, - options - }); - transformedData2[newFieldName] = newValue; - } - } - return transformedData2; - }; - if (!join2 || Object.keys(join2).length === 0) return await transformSingleOutput(data, unsafe_model, select); - unsafe_model = getDefaultModelName(unsafe_model); - const transformedData = await transformSingleOutput(data, unsafe_model, select); - const requiredModels = Object.entries(join2).map(([model, joinConfig]) => ({ - modelName: getModelName(model), - defaultModelName: getDefaultModelName(model), - joinConfig - })); - if (!data) return null; - for (const { modelName, defaultModelName, joinConfig } of requiredModels) { - let joinedData = await (async () => { - if (options.experimental?.joins) return data[modelName]; - else return await handleFallbackJoin({ - baseModel: unsafe_model, - baseData: transformedData, - joinModel: modelName, - specificJoinConfig: joinConfig - }); - })(); - if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : []; - if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData]; - const transformed = []; - if (Array.isArray(joinedData)) for (const item of joinedData) { - const transformedItem = await transformSingleOutput(item, modelName, []); - transformed.push(transformedItem); - } - else { - const transformedItem = await transformSingleOutput(joinedData, modelName, []); - transformed.push(transformedItem); - } - transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null; - } - return transformedData; - }; - const transformWhereClause = ({ model, where, action }) => { - if (!where) return void 0; - const newMappedKeys = config4.mapKeysTransformInput ?? {}; - return where.map((w) => { - const { field: unsafe_field, value, operator = "eq", connector = "AND", mode = "sensitive" } = w; - if (operator === "in") { - if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array"); - } - let newValue = value; - const defaultModelName = getDefaultModelName(model); - const defaultFieldName = getDefaultFieldName({ - field: unsafe_field, - model - }); - const fieldName = newMappedKeys[defaultFieldName] || getFieldName({ - field: defaultFieldName, - model: defaultModelName - }); - const fieldAttr = getFieldAttributes({ - field: defaultFieldName, - model: defaultModelName - }); - const useNumberId = options.advanced?.database?.generateId === "serial"; - if (defaultFieldName === "id" || fieldAttr.references?.field === "id") { - if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number); - else newValue = Number(value); - } - if (fieldAttr.type === "date" && value instanceof Date && !config4.supportsDates) newValue = value.toISOString(); - if (fieldAttr.type === "boolean" && typeof newValue === "string") newValue = newValue === "true"; - if (fieldAttr.type === "number") { - if (typeof newValue === "string" && newValue.trim() !== "") { - const parsed = Number(newValue); - if (!Number.isNaN(parsed)) newValue = parsed; - } else if (Array.isArray(newValue)) { - const parsed = newValue.map((v) => typeof v === "string" && v.trim() !== "" ? Number(v) : NaN); - if (parsed.every((n) => !Number.isNaN(n))) newValue = parsed; - } - } - if (fieldAttr.type === "boolean" && typeof newValue === "boolean" && !config4.supportsBooleans) newValue = newValue ? 1 : 0; - if (fieldAttr.type === "json" && typeof value === "object" && !config4.supportsJSON) try { - newValue = JSON.stringify(value); - } catch (error49) { - throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error49 }); - } - if (config4.customTransformInput) newValue = config4.customTransformInput({ - data: newValue, - fieldAttributes: fieldAttr, - field: fieldName, - model: getModelName(model), - schema: schema3, - options, - action - }); - return { - operator, - connector, - field: fieldName, - value: newValue, - mode - }; - }); - }; - const transformJoinClause = (baseModel, unsanitizedJoin, select) => { - if (!unsanitizedJoin) return void 0; - if (Object.keys(unsanitizedJoin).length === 0) return void 0; - const transformedJoin = {}; - for (const [model, join2] of Object.entries(unsanitizedJoin)) { - if (!join2) continue; - const defaultModelName = getDefaultModelName(model); - const defaultBaseModelName = getDefaultModelName(baseModel); - let foreignKeys = Object.entries(schema3[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName); - let isForwardJoin = true; - if (!foreignKeys.length) { - foreignKeys = Object.entries(schema3[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName); - isForwardJoin = false; - } - if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`); - else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`); - const [foreignKey, foreignKeyAttributes] = foreignKeys[0]; - if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`); - let from; - let to; - let requiredSelectField; - if (isForwardJoin) { - requiredSelectField = foreignKeyAttributes.references.field; - from = getFieldName({ - model: baseModel, - field: requiredSelectField - }); - to = getFieldName({ - model, - field: foreignKey - }); - } else { - requiredSelectField = foreignKey; - from = getFieldName({ - model: baseModel, - field: requiredSelectField - }); - to = getFieldName({ - model, - field: foreignKeyAttributes.references.field - }); - } - if (select && !select.includes(requiredSelectField)) select.push(requiredSelectField); - const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false; - let limit = options.advanced?.database?.defaultFindManyLimit ?? 100; - if (isUnique) limit = 1; - else if (typeof join2 === "object" && typeof join2.limit === "number") limit = join2.limit; - transformedJoin[getModelName(model)] = { - on: { - from, - to - }, - limit, - relation: isUnique ? "one-to-one" : "one-to-many" - }; - } - return { - join: transformedJoin, - select - }; - }; - const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => { - if (!baseData) return baseData; - const modelName = getModelName(joinModel); - const field = joinConfig.on.to; - const value = baseData[getDefaultFieldName({ - field: joinConfig.on.from, - model: baseModel - })]; - if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : []; - let result; - const where = transformWhereClause({ - model: modelName, - where: [{ - field, - value, - operator: "eq", - connector: "AND" - }], - action: "findOne" - }); - try { - if (joinConfig.relation === "one-to-one") result = await withSpan(`db findOne ${modelName}`, { - [ATTR_DB_OPERATION_NAME]: "findOne", - [ATTR_DB_COLLECTION_NAME]: modelName - }, () => adapterInstance.findOne({ - model: modelName, - where - })); - else { - const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - result = await withSpan(`db findMany ${modelName}`, { - [ATTR_DB_OPERATION_NAME]: "findMany", - [ATTR_DB_COLLECTION_NAME]: modelName - }, () => adapterInstance.findMany({ - model: modelName, - where, - limit - })); - } - } catch (error49) { - logger2.error(`Failed to query fallback join for model ${modelName}:`, { - where, - limit: joinConfig.limit - }); - console.error(error49); - throw error49; - } - return result; - }; - const adapterInstance = customAdapter({ - options, - schema: schema3, - debugLog, - getFieldName, - getModelName, - getDefaultModelName, - getDefaultFieldName, - getFieldAttributes, - transformInput, - transformOutput, - transformWhereClause - }); - let lazyLoadTransaction = null; - const adapter = { - transaction: async (cb) => { - if (!lazyLoadTransaction) if (!config4.transaction) lazyLoadTransaction = createAsIsTransaction(adapter); - else { - logger2.debug(`[${config4.adapterName}] - Using provided transaction implementation.`); - lazyLoadTransaction = config4.transaction; - } - return lazyLoadTransaction(cb); - }, - create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - unsafeModel = getDefaultModelName(unsafeModel); - if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) { - logger2.warn(`[${config4.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`); - const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "Create method with `id` being called at:"); - console.log(stack); - unsafeData.id = void 0; - } - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config4.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create", forceAllowId); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const res = await withSpan(`db create ${model}`, { - [ATTR_DB_OPERATION_NAME]: "create", - [ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.create({ - data, - model - })); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, { - model, - res - }); - let transformed = res; - if (!config4.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { - transactionId++; - const thisTransactionId = transactionId; - unsafeModel = getDefaultModelName(unsafeModel); - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "update" - }); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config4.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const res = await withSpan(`db update ${model}`, { - [ATTR_DB_OPERATION_NAME]: "update", - [ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.update({ - model, - where, - update: data - })); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config4.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "updateMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config4.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const updatedCount = await withSpan(`db updateMany ${model}`, { - [ATTR_DB_OPERATION_NAME]: "updateMany", - [ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.updateMany({ - model, - where, - update: data - })); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, { - model, - data: updatedCount - }); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, { - model, - data: updatedCount - }); - return updatedCount; - }, - findOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "findOne" - }); - unsafeModel = getDefaultModelName(unsafeModel); - let join2; - let passJoinToAdapter = true; - if (!config4.disableTransformJoin) { - const result = transformJoinClause(unsafeModel, unsafeJoin, select); - if (result) { - join2 = result.join; - select = result.select; - } - if (!options.experimental?.joins && join2 && Object.keys(join2).length > 0) passJoinToAdapter = false; - } else join2 = unsafeJoin; - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, { - model, - where, - select, - join: join2 - }); - const res = await withSpan(`db findOne ${model}`, { - [ATTR_DB_OPERATION_NAME]: "findOne", - [ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.findOne({ - model, - where, - select, - join: passJoinToAdapter ? join2 : void 0 - })); - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config4.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join2); - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, select, sortBy, offset, join: unsafeJoin }) => { - transactionId++; - const thisTransactionId = transactionId; - const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "findMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - let join2; - let passJoinToAdapter = true; - if (!config4.disableTransformJoin) { - const result = transformJoinClause(unsafeModel, unsafeJoin, select); - if (result) { - join2 = result.join; - select = result.select; - } - if (!options.experimental?.joins && join2 && Object.keys(join2).length > 0) passJoinToAdapter = false; - } else join2 = unsafeJoin; - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, { - model, - where, - limit, - sortBy, - offset, - join: join2 - }); - const res = await withSpan(`db findMany ${model}`, { - [ATTR_DB_OPERATION_NAME]: "findMany", - [ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.findMany({ - model, - where, - limit, - select, - sortBy, - offset, - join: passJoinToAdapter ? join2 : void 0 - })); - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config4.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => { - return await transformOutput(r, unsafeModel, void 0, join2); - })); - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - delete: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "delete" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, { - model, - where - }); - await withSpan(`db delete ${model}`, { - [ATTR_DB_OPERATION_NAME]: "delete", - [ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.delete({ - model, - where - })); - debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model }); - }, - deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "deleteMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, { - model, - where - }); - const res = await withSpan(`db deleteMany ${model}`, { - [ATTR_DB_OPERATION_NAME]: "deleteMany", - [ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.deleteMany({ - model, - where - })); - debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - return res; - }, - count: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "count" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, { - model, - where - }); - const res = await withSpan(`db count ${model}`, { - [ATTR_DB_OPERATION_NAME]: "count", - [ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.count({ - model, - where - })); - debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, { - model, - data: res - }); - return res; - }, - createSchema: adapterInstance.createSchema ? async (_, file2) => { - const tables = getAuthTables(options); - if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session; - return adapterInstance.createSchema({ - file: file2, - tables - }); - } : void 0, - options: { - adapterConfig: config4, - ...adapterInstance.options ?? {} - }, - id: config4.adapterId, - ...config4.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: { - resetDebugLogs() { - debugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId); - }, - printDebugLogs() { - const separator = `\u2500`.repeat(80); - const logs = debugLogs.filter((log2) => log2.instance === uniqueAdapterFactoryInstanceId); - if (logs.length === 0) return; - const log = logs.reverse().map((log2) => { - log2.args[0] = ` -${log2.args[0]}`; - return [...log2.args, "\n"]; - }).reduce((prev, curr) => { - return [...curr, ...prev]; - }, [` -${separator}`]); - console.log(...log); - } - } } : {} - }; - return adapter; - }; - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/index.mjs -var whereOperators; -var init_adapter = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/index.mjs"() { - init_get_field_name(); - init_get_model_name(); - init_factory(); - whereOperators = [ - "eq", - "ne", - "lt", - "lte", - "gt", - "gte", - "in", - "not_in", - "contains", - "starts_with", - "ends_with" - ]; - } -}); - -// ../../node_modules/.pnpm/@better-auth+memory-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_9b6e7edc5b5cf527f9fdae30e619266b/node_modules/@better-auth/memory-adapter/dist/index.mjs -var dist_exports = {}; -__export(dist_exports, { - memoryAdapter: () => memoryAdapter -}); -function insensitiveCompare(a, b) { - if (typeof a === "string" && typeof b === "string") return a.toLowerCase() === b.toLowerCase(); - return a === b; -} -function insensitiveIn(recordVal, values) { - if (typeof recordVal !== "string") return values.includes(recordVal); - return values.some((v) => typeof v === "string" && recordVal.toLowerCase() === v.toLowerCase()); -} -function insensitiveNotIn(recordVal, values) { - return !insensitiveIn(recordVal, values); -} -function insensitiveContains(recordVal, value) { - if (typeof recordVal !== "string" || typeof value !== "string") return false; - return recordVal.toLowerCase().includes(value.toLowerCase()); -} -function insensitiveStartsWith(recordVal, value) { - if (typeof recordVal !== "string" || typeof value !== "string") return false; - return recordVal.toLowerCase().startsWith(value.toLowerCase()); -} -function insensitiveEndsWith(recordVal, value) { - if (typeof recordVal !== "string" || typeof value !== "string") return false; - return recordVal.toLowerCase().endsWith(value.toLowerCase()); -} -var memoryAdapter; -var init_dist = __esm({ - "../../node_modules/.pnpm/@better-auth+memory-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_9b6e7edc5b5cf527f9fdae30e619266b/node_modules/@better-auth/memory-adapter/dist/index.mjs"() { - init_adapter(); - init_env(); - memoryAdapter = (db, config4) => { - let lazyOptions = null; - const adapterCreator = createAdapterFactory({ - config: { - adapterId: "memory", - adapterName: "Memory Adapter", - usePlural: false, - debugLogs: config4?.debugLogs || false, - supportsArrays: true, - customTransformInput(props) { - if (props.options.advanced?.database?.generateId === "serial" && props.field === "id" && props.action === "create") return db[props.model].length + 1; - return props.data; - }, - transaction: async (cb) => { - const clone2 = structuredClone(db); - try { - return await cb(adapterCreator(lazyOptions)); - } catch (error49) { - Object.keys(db).forEach((key) => { - db[key] = clone2[key]; - }); - throw error49; - } - } - }, - adapter: ({ getFieldName, getDefaultFieldName, options, getModelName }) => { - const applySortToRecords = (records, sortBy, model) => { - if (!sortBy) return records; - return records.sort((a, b) => { - const field = getFieldName({ - model, - field: sortBy.field - }); - const aValue = a[field]; - const bValue = b[field]; - let comparison = 0; - if (aValue == null && bValue == null) comparison = 0; - else if (aValue == null) comparison = -1; - else if (bValue == null) comparison = 1; - else if (typeof aValue === "string" && typeof bValue === "string") comparison = aValue.localeCompare(bValue); - else if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime(); - else if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue; - else if (typeof aValue === "boolean" && typeof bValue === "boolean") comparison = aValue === bValue ? 0 : aValue ? 1 : -1; - else comparison = String(aValue).localeCompare(String(bValue)); - return sortBy.direction === "asc" ? comparison : -comparison; - }); - }; - function convertWhereClause(where, model, join2, select) { - const baseRecords = (() => { - const table = db[model]; - if (!table) { - logger.error(`[MemoryAdapter] Model ${model} not found in the DB`, Object.keys(db)); - throw new Error(`Model ${model} not found`); - } - const evalClause = (record2, clause) => { - const { field, value, operator, mode = "sensitive" } = clause; - const isInsensitive = mode === "insensitive" && (typeof value === "string" || Array.isArray(value) && value.every((v) => typeof v === "string")); - switch (operator) { - case "in": - if (!Array.isArray(value)) throw new Error("Value must be an array"); - if (isInsensitive) return insensitiveIn(record2[field], value); - return value.includes(record2[field]); - case "not_in": - if (!Array.isArray(value)) throw new Error("Value must be an array"); - if (isInsensitive) return insensitiveNotIn(record2[field], value); - return !value.includes(record2[field]); - case "contains": - if (isInsensitive) return insensitiveContains(record2[field], value); - return record2[field]?.includes(value); - case "starts_with": - if (isInsensitive) return insensitiveStartsWith(record2[field], value); - return record2[field].startsWith(value); - case "ends_with": - if (isInsensitive) return insensitiveEndsWith(record2[field], value); - return record2[field].endsWith(value); - case "ne": - return isInsensitive ? !insensitiveCompare(record2[field], value) : record2[field] !== value; - case "gt": - return value != null && Boolean(record2[field] > value); - case "gte": - return value != null && Boolean(record2[field] >= value); - case "lt": - return value != null && Boolean(record2[field] < value); - case "lte": - return value != null && Boolean(record2[field] <= value); - default: - return isInsensitive ? insensitiveCompare(record2[field], value) : record2[field] === value; - } - }; - let records = table.filter((record2) => { - if (!where.length || where.length === 0) return true; - let result = evalClause(record2, where[0]); - for (const clause of where) { - const clauseResult = evalClause(record2, clause); - if (clause.connector === "OR") result = result || clauseResult; - else result = result && clauseResult; - } - return result; - }); - if (select?.length && select.length > 0) records = records.map((record2) => Object.fromEntries(Object.entries(record2).filter(([key]) => select.includes(getDefaultFieldName({ - model, - field: key - }))))); - return records; - })(); - if (!join2) return baseRecords; - const grouped = /* @__PURE__ */ new Map(); - const seenIds = /* @__PURE__ */ new Map(); - for (const baseRecord of baseRecords) { - const baseId = String(baseRecord.id); - if (!grouped.has(baseId)) { - const nested = { ...baseRecord }; - for (const [joinModel, joinAttr] of Object.entries(join2)) { - const joinModelName = getModelName(joinModel); - if (joinAttr.relation === "one-to-one") nested[joinModelName] = null; - else { - nested[joinModelName] = []; - seenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set()); - } - } - grouped.set(baseId, nested); - } - const nestedEntry = grouped.get(baseId); - for (const [joinModel, joinAttr] of Object.entries(join2)) { - const joinModelName = getModelName(joinModel); - const joinTable = db[joinModelName]; - if (!joinTable) { - logger.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db)); - throw new Error(`JoinOption model ${joinModelName} not found`); - } - const matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]); - if (joinAttr.relation === "one-to-one") nestedEntry[joinModelName] = matchingRecords[0] || null; - else { - const seenSet = seenIds.get(`${baseId}-${joinModel}`); - const limit = joinAttr.limit ?? 100; - let count = 0; - for (const matchingRecord of matchingRecords) { - if (count >= limit) break; - if (!seenSet.has(matchingRecord.id)) { - nestedEntry[joinModelName].push(matchingRecord); - seenSet.add(matchingRecord.id); - count++; - } - } - } - } - } - return Array.from(grouped.values()); - } - return { - create: async ({ model, data }) => { - if (options.advanced?.database?.generateId === "serial") data.id = db[getModelName(model)].length + 1; - if (!db[model]) db[model] = []; - db[model].push(data); - return data; - }, - findOne: async ({ model, where, select, join: join2 }) => { - const res = convertWhereClause(where, model, join2, select); - if (join2) { - const resArray = res; - if (!resArray.length) return null; - return resArray[0]; - } - return res[0] || null; - }, - findMany: async ({ model, where, sortBy, limit, select, offset, join: join2 }) => { - const res = convertWhereClause(where || [], model, join2, select); - if (join2) { - const resArray = res; - if (!resArray.length) return []; - applySortToRecords(resArray, sortBy, model); - let paginatedRecords = resArray; - if (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset); - if (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit); - return paginatedRecords; - } - let table = applySortToRecords(res, sortBy, model); - if (offset !== void 0) table = table.slice(offset); - if (limit !== void 0) table = table.slice(0, limit); - return table || []; - }, - count: async ({ model, where }) => { - if (where) return convertWhereClause(where, model).length; - return db[model].length; - }, - update: async ({ model, where, update }) => { - const res = convertWhereClause(where, model); - res.forEach((record2) => { - Object.assign(record2, update); - }); - return res[0] || null; - }, - delete: async ({ model, where }) => { - const table = db[model]; - const res = convertWhereClause(where, model); - db[model] = table.filter((record2) => !res.includes(record2)); - }, - deleteMany: async ({ model, where }) => { - const table = db[model]; - const res = convertWhereClause(where, model); - let count = 0; - db[model] = table.filter((record2) => { - if (res.includes(record2)) { - count++; - return false; - } - return !res.includes(record2); - }); - return count; - }, - updateMany({ model, where, update }) { - const res = convertWhereClause(where, model); - res.forEach((record2) => { - Object.assign(record2, update); - }); - return res[0] || null; - } - }; - } - }); - return (options) => { - lazyOptions = options; - return adapterCreator(options); - }; - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js -function isUndefined(obj) { - return typeof obj === "undefined" || obj === void 0; -} -function isString2(obj) { - return typeof obj === "string"; -} -function isNumber2(obj) { - return typeof obj === "number"; -} -function isBoolean2(obj) { - return typeof obj === "boolean"; -} -function isNull(obj) { - return obj === null; -} -function isDate2(obj) { - return obj instanceof Date; -} -function isBigInt(obj) { - return typeof obj === "bigint"; -} -function isBuffer(obj) { - return typeof Buffer !== "undefined" && Buffer.isBuffer(obj); -} -function isFunction3(obj) { - return typeof obj === "function"; -} -function isObject4(obj) { - return typeof obj === "object" && obj !== null; -} -function freeze(obj) { - return Object.freeze(obj); -} -function asArray(arg) { - if (isReadonlyArray(arg)) { - return arg; - } else { - return [arg]; - } -} -function isReadonlyArray(arg) { - return Array.isArray(arg); -} -function noop(obj) { - return obj; -} -var init_object_utils = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js -var AlterTableNode; -var init_alter_table_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js"() { - init_object_utils(); - AlterTableNode = freeze({ - is(node) { - return node.kind === "AlterTableNode"; - }, - create(table) { - return freeze({ - kind: "AlterTableNode", - table - }); - }, - cloneWithTableProps(node, props) { - return freeze({ - ...node, - ...props - }); - }, - cloneWithColumnAlteration(node, columnAlteration) { - return freeze({ - ...node, - columnAlterations: node.columnAlterations ? [...node.columnAlterations, columnAlteration] : [columnAlteration] - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js -var IdentifierNode; -var init_identifier_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js"() { - init_object_utils(); - IdentifierNode = freeze({ - is(node) { - return node.kind === "IdentifierNode"; - }, - create(name) { - return freeze({ - kind: "IdentifierNode", - name - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js -var CreateIndexNode; -var init_create_index_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js"() { - init_object_utils(); - init_identifier_node(); - CreateIndexNode = freeze({ - is(node) { - return node.kind === "CreateIndexNode"; - }, - create(name) { - return freeze({ - kind: "CreateIndexNode", - name: IdentifierNode.create(name) - }); - }, - cloneWith(node, props) { - return freeze({ - ...node, - ...props - }); - }, - cloneWithColumns(node, columns) { - return freeze({ - ...node, - columns: [...node.columns || [], ...columns] - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js -var CreateSchemaNode; -var init_create_schema_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js"() { - init_object_utils(); - init_identifier_node(); - CreateSchemaNode = freeze({ - is(node) { - return node.kind === "CreateSchemaNode"; - }, - create(schema3, params) { - return freeze({ - kind: "CreateSchemaNode", - schema: IdentifierNode.create(schema3), - ...params - }); - }, - cloneWith(createSchema, params) { - return freeze({ - ...createSchema, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js -var ON_COMMIT_ACTIONS, CreateTableNode; -var init_create_table_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js"() { - init_object_utils(); - ON_COMMIT_ACTIONS = ["preserve rows", "delete rows", "drop"]; - CreateTableNode = freeze({ - is(node) { - return node.kind === "CreateTableNode"; - }, - create(table) { - return freeze({ - kind: "CreateTableNode", - table, - columns: freeze([]) - }); - }, - cloneWithColumn(createTable, column) { - return freeze({ - ...createTable, - columns: freeze([...createTable.columns, column]) - }); - }, - cloneWithConstraint(createTable, constraint) { - return freeze({ - ...createTable, - constraints: createTable.constraints ? freeze([...createTable.constraints, constraint]) : freeze([constraint]) - }); - }, - cloneWithFrontModifier(createTable, modifier) { - return freeze({ - ...createTable, - frontModifiers: createTable.frontModifiers ? freeze([...createTable.frontModifiers, modifier]) : freeze([modifier]) - }); - }, - cloneWithEndModifier(createTable, modifier) { - return freeze({ - ...createTable, - endModifiers: createTable.endModifiers ? freeze([...createTable.endModifiers, modifier]) : freeze([modifier]) - }); - }, - cloneWith(createTable, params) { - return freeze({ - ...createTable, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js -var SchemableIdentifierNode; -var init_schemable_identifier_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js"() { - init_object_utils(); - init_identifier_node(); - SchemableIdentifierNode = freeze({ - is(node) { - return node.kind === "SchemableIdentifierNode"; - }, - create(identifier) { - return freeze({ - kind: "SchemableIdentifierNode", - identifier: IdentifierNode.create(identifier) - }); - }, - createWithSchema(schema3, identifier) { - return freeze({ - kind: "SchemableIdentifierNode", - schema: IdentifierNode.create(schema3), - identifier: IdentifierNode.create(identifier) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js -var DropIndexNode; -var init_drop_index_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - DropIndexNode = freeze({ - is(node) { - return node.kind === "DropIndexNode"; - }, - create(name, params) { - return freeze({ - kind: "DropIndexNode", - name: SchemableIdentifierNode.create(name), - ...params - }); - }, - cloneWith(dropIndex, props) { - return freeze({ - ...dropIndex, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js -var DropSchemaNode; -var init_drop_schema_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js"() { - init_object_utils(); - init_identifier_node(); - DropSchemaNode = freeze({ - is(node) { - return node.kind === "DropSchemaNode"; - }, - create(schema3, params) { - return freeze({ - kind: "DropSchemaNode", - schema: IdentifierNode.create(schema3), - ...params - }); - }, - cloneWith(dropSchema, params) { - return freeze({ - ...dropSchema, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js -var DropTableNode; -var init_drop_table_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js"() { - init_object_utils(); - DropTableNode = freeze({ - is(node) { - return node.kind === "DropTableNode"; - }, - create(table, params) { - return freeze({ - kind: "DropTableNode", - table, - ...params - }); - }, - cloneWith(dropIndex, params) { - return freeze({ - ...dropIndex, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js -var AliasNode; -var init_alias_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js"() { - init_object_utils(); - AliasNode = freeze({ - is(node) { - return node.kind === "AliasNode"; - }, - create(node, alias) { - return freeze({ - kind: "AliasNode", - node, - alias - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js -var TableNode; -var init_table_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - TableNode = freeze({ - is(node) { - return node.kind === "TableNode"; - }, - create(table) { - return freeze({ - kind: "TableNode", - table: SchemableIdentifierNode.create(table) - }); - }, - createWithSchema(schema3, table) { - return freeze({ - kind: "TableNode", - table: SchemableIdentifierNode.createWithSchema(schema3, table) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js -function isOperationNodeSource(obj) { - return isObject4(obj) && isFunction3(obj.toOperationNode); -} -var init_operation_node_source = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js"() { - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js -function isExpression(obj) { - return isObject4(obj) && "expressionType" in obj && isOperationNodeSource(obj); -} -function isAliasedExpression(obj) { - return isObject4(obj) && "expression" in obj && isString2(obj.alias) && isOperationNodeSource(obj); -} -var init_expression = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js"() { - init_operation_node_source(); - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js -var SelectModifierNode; -var init_select_modifier_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js"() { - init_object_utils(); - SelectModifierNode = freeze({ - is(node) { - return node.kind === "SelectModifierNode"; - }, - create(modifier, of) { - return freeze({ - kind: "SelectModifierNode", - modifier, - of - }); - }, - createWithExpression(modifier) { - return freeze({ - kind: "SelectModifierNode", - rawModifier: modifier - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js -var AndNode; -var init_and_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js"() { - init_object_utils(); - AndNode = freeze({ - is(node) { - return node.kind === "AndNode"; - }, - create(left, right) { - return freeze({ - kind: "AndNode", - left, - right - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js -var OrNode; -var init_or_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js"() { - init_object_utils(); - OrNode = freeze({ - is(node) { - return node.kind === "OrNode"; - }, - create(left, right) { - return freeze({ - kind: "OrNode", - left, - right - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js -var OnNode; -var init_on_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js"() { - init_object_utils(); - init_and_node(); - init_or_node(); - OnNode = freeze({ - is(node) { - return node.kind === "OnNode"; - }, - create(filter) { - return freeze({ - kind: "OnNode", - on: filter - }); - }, - cloneWithOperation(onNode, operator, operation) { - return freeze({ - ...onNode, - on: operator === "And" ? AndNode.create(onNode.on, operation) : OrNode.create(onNode.on, operation) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js -var JoinNode; -var init_join_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js"() { - init_object_utils(); - init_on_node(); - JoinNode = freeze({ - is(node) { - return node.kind === "JoinNode"; - }, - create(joinType, table) { - return freeze({ - kind: "JoinNode", - joinType, - table, - on: void 0 - }); - }, - createWithOn(joinType, table, on) { - return freeze({ - kind: "JoinNode", - joinType, - table, - on: OnNode.create(on) - }); - }, - cloneWithOn(joinNode, operation) { - return freeze({ - ...joinNode, - on: joinNode.on ? OnNode.cloneWithOperation(joinNode.on, "And", operation) : OnNode.create(operation) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js -var BinaryOperationNode; -var init_binary_operation_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js"() { - init_object_utils(); - BinaryOperationNode = freeze({ - is(node) { - return node.kind === "BinaryOperationNode"; - }, - create(leftOperand, operator, rightOperand) { - return freeze({ - kind: "BinaryOperationNode", - leftOperand, - operator, - rightOperand - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js -function isJSONOperator(op) { - return isString2(op) && JSON_OPERATORS.includes(op); -} -var COMPARISON_OPERATORS, ARITHMETIC_OPERATORS, JSON_OPERATORS, BINARY_OPERATORS, UNARY_FILTER_OPERATORS, UNARY_OPERATORS, OPERATORS, OperatorNode; -var init_operator_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js"() { - init_object_utils(); - COMPARISON_OPERATORS = [ - "=", - "==", - "!=", - "<>", - ">", - ">=", - "<", - "<=", - "in", - "not in", - "is", - "is not", - "like", - "not like", - "match", - "ilike", - "not ilike", - "@>", - "<@", - "^@", - "&&", - "?", - "?&", - "?|", - "!<", - "!>", - "<=>", - "!~", - "~", - "~*", - "!~*", - "@@", - "@@@", - "!!", - "<->", - "regexp", - "is distinct from", - "is not distinct from" - ]; - ARITHMETIC_OPERATORS = [ - "+", - "-", - "*", - "/", - "%", - "^", - "&", - "|", - "#", - "<<", - ">>" - ]; - JSON_OPERATORS = ["->", "->>"]; - BINARY_OPERATORS = [ - ...COMPARISON_OPERATORS, - ...ARITHMETIC_OPERATORS, - "&&", - "||" - ]; - UNARY_FILTER_OPERATORS = ["exists", "not exists"]; - UNARY_OPERATORS = ["not", "-", ...UNARY_FILTER_OPERATORS]; - OPERATORS = [ - ...BINARY_OPERATORS, - ...JSON_OPERATORS, - ...UNARY_OPERATORS, - "between", - "between symmetric" - ]; - OperatorNode = freeze({ - is(node) { - return node.kind === "OperatorNode"; - }, - create(operator) { - return freeze({ - kind: "OperatorNode", - operator - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js -var ColumnNode; -var init_column_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js"() { - init_object_utils(); - init_identifier_node(); - ColumnNode = freeze({ - is(node) { - return node.kind === "ColumnNode"; - }, - create(column) { - return freeze({ - kind: "ColumnNode", - column: IdentifierNode.create(column) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js -var SelectAllNode; -var init_select_all_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js"() { - init_object_utils(); - SelectAllNode = freeze({ - is(node) { - return node.kind === "SelectAllNode"; - }, - create() { - return freeze({ - kind: "SelectAllNode" - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js -var ReferenceNode; -var init_reference_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js"() { - init_select_all_node(); - init_object_utils(); - ReferenceNode = freeze({ - is(node) { - return node.kind === "ReferenceNode"; - }, - create(column, table) { - return freeze({ - kind: "ReferenceNode", - table, - column - }); - }, - createSelectAll(table) { - return freeze({ - kind: "ReferenceNode", - table, - column: SelectAllNode.create() - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js -function isDynamicReferenceBuilder(obj) { - return isObject4(obj) && isOperationNodeSource(obj) && isString2(obj.dynamicReference); -} -var _dynamicReference, DynamicReferenceBuilder; -var init_dynamic_reference_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js"() { - init_operation_node_source(); - init_reference_parser(); - init_object_utils(); - DynamicReferenceBuilder = class { - constructor(reference) { - __privateAdd(this, _dynamicReference); - __privateSet(this, _dynamicReference, reference); - } - get dynamicReference() { - return __privateGet(this, _dynamicReference); - } - /** - * @private - * - * This needs to be here just so that the typings work. Without this - * the generated .d.ts file contains no reference to the type param R - * which causes this type to be equal to DynamicReferenceBuilder with - * any R. - */ - get refType() { - return void 0; - } - toOperationNode() { - return parseSimpleReferenceExpression(__privateGet(this, _dynamicReference)); - } - }; - _dynamicReference = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js -var OrderByItemNode; -var init_order_by_item_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js"() { - init_object_utils(); - OrderByItemNode = freeze({ - is(node) { - return node.kind === "OrderByItemNode"; - }, - create(orderBy, direction) { - return freeze({ - kind: "OrderByItemNode", - orderBy, - direction - }); - }, - cloneWith(node, props) { - return freeze({ - ...node, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js -var RawNode; -var init_raw_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js"() { - init_object_utils(); - RawNode = freeze({ - is(node) { - return node.kind === "RawNode"; - }, - create(sqlFragments, parameters) { - return freeze({ - kind: "RawNode", - sqlFragments: freeze(sqlFragments), - parameters: freeze(parameters) - }); - }, - createWithSql(sql2) { - return RawNode.create([sql2], []); - }, - createWithChild(child) { - return RawNode.create(["", ""], [child]); - }, - createWithChildren(children) { - return RawNode.create(new Array(children.length + 1).fill(""), children); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js -var CollateNode; -var init_collate_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js"() { - init_object_utils(); - init_identifier_node(); - CollateNode = freeze({ - is(node) { - return node.kind === "CollateNode"; - }, - create(collation) { - return freeze({ - kind: "CollateNode", - collation: IdentifierNode.create(collation) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js -var _props, _OrderByItemBuilder, OrderByItemBuilder; -var init_order_by_item_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js"() { - init_collate_node(); - init_order_by_item_node(); - init_raw_node(); - init_object_utils(); - _OrderByItemBuilder = class _OrderByItemBuilder { - constructor(props) { - __privateAdd(this, _props); - __privateSet(this, _props, freeze(props)); - } - /** - * Adds `desc` to the `order by` item. - * - * See {@link asc} for the opposite. - */ - desc() { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { - direction: RawNode.createWithSql("desc") - }) - }); - } - /** - * Adds `asc` to the `order by` item. - * - * See {@link desc} for the opposite. - */ - asc() { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { - direction: RawNode.createWithSql("asc") - }) - }); - } - /** - * Adds `nulls last` to the `order by` item. - * - * This is only supported by some dialects like PostgreSQL and SQLite. - * - * See {@link nullsFirst} for the opposite. - */ - nullsLast() { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { nulls: "last" }) - }); - } - /** - * Adds `nulls first` to the `order by` item. - * - * This is only supported by some dialects like PostgreSQL and SQLite. - * - * See {@link nullsLast} for the opposite. - */ - nullsFirst() { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { nulls: "first" }) - }); - } - /** - * Adds `collate ` to the `order by` item. - */ - collate(collation) { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(__privateGet(this, _props).node, { - collation: CollateNode.create(collation) - }) - }); - } - toOperationNode() { - return __privateGet(this, _props).node; - } - }; - _props = new WeakMap(); - OrderByItemBuilder = _OrderByItemBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js -function logOnce(message2) { - if (LOGGED_MESSAGES.has(message2)) { - return; - } - LOGGED_MESSAGES.add(message2); - console.log(message2); -} -var LOGGED_MESSAGES; -var init_log_once = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js"() { - LOGGED_MESSAGES = /* @__PURE__ */ new Set(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js -function isOrderByDirection(thing) { - return thing === "asc" || thing === "desc"; -} -function parseOrderBy(args) { - if (args.length === 2) { - return [parseOrderByItem(args[0], args[1])]; - } - if (args.length === 1) { - const [orderBy] = args; - if (Array.isArray(orderBy)) { - logOnce("orderBy(array) is deprecated, use multiple orderBy calls instead."); - return orderBy.map((item) => parseOrderByItem(item)); - } - return [parseOrderByItem(orderBy)]; - } - throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`); -} -function parseOrderByItem(expr, modifiers) { - const parsedRef = parseOrderByExpression(expr); - if (OrderByItemNode.is(parsedRef)) { - if (modifiers) { - throw new Error("Cannot specify direction twice!"); - } - return parsedRef; - } - return parseOrderByWithModifiers(parsedRef, modifiers); -} -function parseOrderByExpression(expr) { - if (isExpressionOrFactory(expr)) { - return parseExpression(expr); - } - if (isDynamicReferenceBuilder(expr)) { - return expr.toOperationNode(); - } - const [ref, direction] = expr.split(" "); - if (direction) { - logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."); - return parseOrderByWithModifiers(parseStringReference(ref), direction); - } - return parseStringReference(expr); -} -function parseOrderByWithModifiers(expr, modifiers) { - if (typeof modifiers === "string") { - if (!isOrderByDirection(modifiers)) { - throw new Error(`Invalid order by direction: ${modifiers}`); - } - return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers)); - } - if (isExpression(modifiers)) { - logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."); - return OrderByItemNode.create(expr, modifiers.toOperationNode()); - } - const node = OrderByItemNode.create(expr); - if (!modifiers) { - return node; - } - return modifiers(new OrderByItemBuilder({ node })).toOperationNode(); -} -var init_order_by_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js"() { - init_dynamic_reference_builder(); - init_expression(); - init_order_by_item_node(); - init_raw_node(); - init_order_by_item_builder(); - init_log_once(); - init_expression_parser(); - init_reference_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js -var JSONReferenceNode; -var init_json_reference_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js"() { - init_object_utils(); - JSONReferenceNode = freeze({ - is(node) { - return node.kind === "JSONReferenceNode"; - }, - create(reference, traversal) { - return freeze({ - kind: "JSONReferenceNode", - reference, - traversal - }); - }, - cloneWithTraversal(node, traversal) { - return freeze({ - ...node, - traversal - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js -var JSONOperatorChainNode; -var init_json_operator_chain_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js"() { - init_object_utils(); - JSONOperatorChainNode = freeze({ - is(node) { - return node.kind === "JSONOperatorChainNode"; - }, - create(operator) { - return freeze({ - kind: "JSONOperatorChainNode", - operator, - values: freeze([]) - }); - }, - cloneWithValue(node, value) { - return freeze({ - ...node, - values: freeze([...node.values, value]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js -var JSONPathNode; -var init_json_path_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js"() { - init_object_utils(); - JSONPathNode = freeze({ - is(node) { - return node.kind === "JSONPathNode"; - }, - create(inOperator) { - return freeze({ - kind: "JSONPathNode", - inOperator, - pathLegs: freeze([]) - }); - }, - cloneWithLeg(jsonPathNode, pathLeg) { - return freeze({ - ...jsonPathNode, - pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js -function parseSimpleReferenceExpression(exp) { - if (isString2(exp)) { - return parseStringReference(exp); - } - return exp.toOperationNode(); -} -function parseReferenceExpressionOrList(arg) { - if (isReadonlyArray(arg)) { - return arg.map((it) => parseReferenceExpression(it)); - } else { - return [parseReferenceExpression(arg)]; - } -} -function parseReferenceExpression(exp) { - if (isExpressionOrFactory(exp)) { - return parseExpression(exp); - } - return parseSimpleReferenceExpression(exp); -} -function parseJSONReference(ref, op) { - const referenceNode = parseStringReference(ref); - if (isJSONOperator(op)) { - return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op))); - } - const opWithoutLastChar = op.slice(0, -1); - if (isJSONOperator(opWithoutLastChar)) { - return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar))); - } - throw new Error(`Invalid JSON operator: ${op}`); -} -function parseStringReference(ref) { - const COLUMN_SEPARATOR = "."; - if (!ref.includes(COLUMN_SEPARATOR)) { - return ReferenceNode.create(ColumnNode.create(ref)); - } - const parts = ref.split(COLUMN_SEPARATOR).map(trim); - if (parts.length === 3) { - return parseStringReferenceWithTableAndSchema(parts); - } - if (parts.length === 2) { - return parseStringReferenceWithTable(parts); - } - throw new Error(`invalid column reference ${ref}`); -} -function parseAliasedStringReference(ref) { - const ALIAS_SEPARATOR = " as "; - if (ref.includes(ALIAS_SEPARATOR)) { - const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim); - return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias)); - } else { - return parseStringReference(ref); - } -} -function parseColumnName(column) { - return ColumnNode.create(column); -} -function parseOrderedColumnName(column) { - const ORDER_SEPARATOR = " "; - if (column.includes(ORDER_SEPARATOR)) { - const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim); - if (!isOrderByDirection(order)) { - throw new Error(`invalid order direction "${order}" next to "${columnName}"`); - } - return parseOrderBy([columnName, order])[0]; - } else { - return parseColumnName(column); - } -} -function parseStringReferenceWithTableAndSchema(parts) { - const [schema3, table, column] = parts; - return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema3, table)); -} -function parseStringReferenceWithTable(parts) { - const [table, column] = parts; - return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table)); -} -function trim(str) { - return str.trim(); -} -var init_reference_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js"() { - init_alias_node(); - init_column_node(); - init_reference_node(); - init_table_node(); - init_object_utils(); - init_expression_parser(); - init_identifier_node(); - init_order_by_parser(); - init_operator_node(); - init_json_reference_node(); - init_json_operator_chain_node(); - init_json_path_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js -var PrimitiveValueListNode; -var init_primitive_value_list_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js"() { - init_object_utils(); - PrimitiveValueListNode = freeze({ - is(node) { - return node.kind === "PrimitiveValueListNode"; - }, - create(values) { - return freeze({ - kind: "PrimitiveValueListNode", - values: freeze([...values]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js -var ValueListNode; -var init_value_list_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js"() { - init_object_utils(); - ValueListNode = freeze({ - is(node) { - return node.kind === "ValueListNode"; - }, - create(values) { - return freeze({ - kind: "ValueListNode", - values: freeze(values) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js -var ValueNode; -var init_value_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js"() { - init_object_utils(); - ValueNode = freeze({ - is(node) { - return node.kind === "ValueNode"; - }, - create(value) { - return freeze({ - kind: "ValueNode", - value - }); - }, - createImmediate(value) { - return freeze({ - kind: "ValueNode", - value, - immediate: true - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js -function parseValueExpressionOrList(arg) { - if (isReadonlyArray(arg)) { - return parseValueExpressionList(arg); - } - return parseValueExpression(arg); -} -function parseValueExpression(exp) { - if (isExpressionOrFactory(exp)) { - return parseExpression(exp); - } - return ValueNode.create(exp); -} -function isSafeImmediateValue(value) { - return isNumber2(value) || isBoolean2(value) || isNull(value); -} -function parseSafeImmediateValue(value) { - if (!isSafeImmediateValue(value)) { - throw new Error(`unsafe immediate value ${JSON.stringify(value)}`); - } - return ValueNode.createImmediate(value); -} -function parseValueExpressionList(arg) { - if (arg.some(isExpressionOrFactory)) { - return ValueListNode.create(arg.map((it) => parseValueExpression(it))); - } - return PrimitiveValueListNode.create(arg); -} -var init_value_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js"() { - init_primitive_value_list_node(); - init_value_list_node(); - init_value_node(); - init_object_utils(); - init_expression_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js -var ParensNode; -var init_parens_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js"() { - init_object_utils(); - ParensNode = freeze({ - is(node) { - return node.kind === "ParensNode"; - }, - create(node) { - return freeze({ - kind: "ParensNode", - node - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js -function parseValueBinaryOperationOrExpression(args) { - if (args.length === 3) { - return parseValueBinaryOperation(args[0], args[1], args[2]); - } else if (args.length === 1) { - return parseValueExpression(args[0]); - } - throw new Error(`invalid arguments: ${JSON.stringify(args)}`); -} -function parseValueBinaryOperation(left, operator, right) { - if (isIsOperator(operator) && needsIsOperator(right)) { - return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right)); - } - return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right)); -} -function parseReferentialBinaryOperation(left, operator, right) { - return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right)); -} -function parseFilterObject(obj, combinator) { - return parseFilterList(Object.entries(obj).filter(([, v]) => !isUndefined(v)).map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? "is" : "=", v)), combinator); -} -function parseFilterList(list, combinator, withParens = true) { - const combine = combinator === "and" ? AndNode.create : OrNode.create; - if (list.length === 0) { - return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create("="), ValueNode.createImmediate(combinator === "and" ? 1 : 0)); - } - let node = toOperationNode(list[0]); - for (let i = 1; i < list.length; ++i) { - node = combine(node, toOperationNode(list[i])); - } - if (list.length > 1 && withParens) { - return ParensNode.create(node); - } - return node; -} -function isIsOperator(operator) { - return operator === "is" || operator === "is not"; -} -function needsIsOperator(value) { - return isNull(value) || isBoolean2(value); -} -function parseOperator(operator) { - if (isString2(operator) && OPERATORS.includes(operator)) { - return OperatorNode.create(operator); - } - if (isOperationNodeSource(operator)) { - return operator.toOperationNode(); - } - throw new Error(`invalid operator ${JSON.stringify(operator)}`); -} -function toOperationNode(nodeOrSource) { - return isOperationNodeSource(nodeOrSource) ? nodeOrSource.toOperationNode() : nodeOrSource; -} -var init_binary_operation_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js"() { - init_binary_operation_node(); - init_object_utils(); - init_operation_node_source(); - init_operator_node(); - init_reference_parser(); - init_value_parser(); - init_value_node(); - init_and_node(); - init_parens_node(); - init_or_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js -var OrderByNode; -var init_order_by_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js"() { - init_object_utils(); - OrderByNode = freeze({ - is(node) { - return node.kind === "OrderByNode"; - }, - create(items) { - return freeze({ - kind: "OrderByNode", - items: freeze([...items]) - }); - }, - cloneWithItems(orderBy, items) { - return freeze({ - ...orderBy, - items: freeze([...orderBy.items, ...items]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js -var PartitionByNode; -var init_partition_by_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js"() { - init_object_utils(); - PartitionByNode = freeze({ - is(node) { - return node.kind === "PartitionByNode"; - }, - create(items) { - return freeze({ - kind: "PartitionByNode", - items: freeze(items) - }); - }, - cloneWithItems(partitionBy, items) { - return freeze({ - ...partitionBy, - items: freeze([...partitionBy.items, ...items]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js -var OverNode; -var init_over_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js"() { - init_object_utils(); - init_order_by_node(); - init_partition_by_node(); - OverNode = freeze({ - is(node) { - return node.kind === "OverNode"; - }, - create() { - return freeze({ - kind: "OverNode" - }); - }, - cloneWithOrderByItems(overNode, items) { - return freeze({ - ...overNode, - orderBy: overNode.orderBy ? OrderByNode.cloneWithItems(overNode.orderBy, items) : OrderByNode.create(items) - }); - }, - cloneWithPartitionByItems(overNode, items) { - return freeze({ - ...overNode, - partitionBy: overNode.partitionBy ? PartitionByNode.cloneWithItems(overNode.partitionBy, items) : PartitionByNode.create(items) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js -var FromNode; -var init_from_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js"() { - init_object_utils(); - FromNode = freeze({ - is(node) { - return node.kind === "FromNode"; - }, - create(froms) { - return freeze({ - kind: "FromNode", - froms: freeze(froms) - }); - }, - cloneWithFroms(from, froms) { - return freeze({ - ...from, - froms: freeze([...from.froms, ...froms]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js -var GroupByNode; -var init_group_by_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js"() { - init_object_utils(); - GroupByNode = freeze({ - is(node) { - return node.kind === "GroupByNode"; - }, - create(items) { - return freeze({ - kind: "GroupByNode", - items: freeze(items) - }); - }, - cloneWithItems(groupBy2, items) { - return freeze({ - ...groupBy2, - items: freeze([...groupBy2.items, ...items]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js -var HavingNode; -var init_having_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js"() { - init_object_utils(); - init_and_node(); - init_or_node(); - HavingNode = freeze({ - is(node) { - return node.kind === "HavingNode"; - }, - create(filter) { - return freeze({ - kind: "HavingNode", - having: filter - }); - }, - cloneWithOperation(havingNode, operator, operation) { - return freeze({ - ...havingNode, - having: operator === "And" ? AndNode.create(havingNode.having, operation) : OrNode.create(havingNode.having, operation) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js -var InsertQueryNode; -var init_insert_query_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js"() { - init_object_utils(); - InsertQueryNode = freeze({ - is(node) { - return node.kind === "InsertQueryNode"; - }, - create(into, withNode, replace) { - return freeze({ - kind: "InsertQueryNode", - into, - ...withNode && { with: withNode }, - replace - }); - }, - createWithoutInto() { - return freeze({ - kind: "InsertQueryNode" - }); - }, - cloneWith(insertQuery, props) { - return freeze({ - ...insertQuery, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js -var ListNode; -var init_list_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js"() { - init_object_utils(); - ListNode = freeze({ - is(node) { - return node.kind === "ListNode"; - }, - create(items) { - return freeze({ - kind: "ListNode", - items: freeze(items) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js -var UpdateQueryNode; -var init_update_query_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js"() { - init_object_utils(); - init_from_node(); - init_list_node(); - UpdateQueryNode = freeze({ - is(node) { - return node.kind === "UpdateQueryNode"; - }, - create(tables, withNode) { - return freeze({ - kind: "UpdateQueryNode", - // For backwards compatibility, use the raw table node when there's only one table - // and don't rename the property to something like `tables`. - table: tables.length === 1 ? tables[0] : ListNode.create(tables), - ...withNode && { with: withNode } - }); - }, - createWithoutTable() { - return freeze({ - kind: "UpdateQueryNode" - }); - }, - cloneWithFromItems(updateQuery, fromItems) { - return freeze({ - ...updateQuery, - from: updateQuery.from ? FromNode.cloneWithFroms(updateQuery.from, fromItems) : FromNode.create(fromItems) - }); - }, - cloneWithUpdates(updateQuery, updates) { - return freeze({ - ...updateQuery, - updates: updateQuery.updates ? freeze([...updateQuery.updates, ...updates]) : updates - }); - }, - cloneWithLimit(updateQuery, limit) { - return freeze({ - ...updateQuery, - limit - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js -var UsingNode; -var init_using_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js"() { - init_object_utils(); - UsingNode = freeze({ - is(node) { - return node.kind === "UsingNode"; - }, - create(tables) { - return freeze({ - kind: "UsingNode", - tables: freeze(tables) - }); - }, - cloneWithTables(using, tables) { - return freeze({ - ...using, - tables: freeze([...using.tables, ...tables]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js -var DeleteQueryNode; -var init_delete_query_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js"() { - init_object_utils(); - init_from_node(); - init_using_node(); - init_query_node(); - DeleteQueryNode = freeze({ - is(node) { - return node.kind === "DeleteQueryNode"; - }, - create(fromItems, withNode) { - return freeze({ - kind: "DeleteQueryNode", - from: FromNode.create(fromItems), - ...withNode && { with: withNode } - }); - }, - // TODO: remove in v0.29 - /** - * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. - */ - cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items), - // TODO: remove in v0.29 - /** - * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. - */ - cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node), - cloneWithLimit(deleteNode, limit) { - return freeze({ - ...deleteNode, - limit - }); - }, - cloneWithoutLimit(deleteNode) { - return freeze({ - ...deleteNode, - limit: void 0 - }); - }, - cloneWithUsing(deleteNode, tables) { - return freeze({ - ...deleteNode, - using: deleteNode.using !== void 0 ? UsingNode.cloneWithTables(deleteNode.using, tables) : UsingNode.create(tables) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js -var WhereNode; -var init_where_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js"() { - init_object_utils(); - init_and_node(); - init_or_node(); - WhereNode = freeze({ - is(node) { - return node.kind === "WhereNode"; - }, - create(filter) { - return freeze({ - kind: "WhereNode", - where: filter - }); - }, - cloneWithOperation(whereNode, operator, operation) { - return freeze({ - ...whereNode, - where: operator === "And" ? AndNode.create(whereNode.where, operation) : OrNode.create(whereNode.where, operation) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js -var ReturningNode; -var init_returning_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js"() { - init_object_utils(); - ReturningNode = freeze({ - is(node) { - return node.kind === "ReturningNode"; - }, - create(selections) { - return freeze({ - kind: "ReturningNode", - selections: freeze(selections) - }); - }, - cloneWithSelections(returning, selections) { - return freeze({ - ...returning, - selections: returning.selections ? freeze([...returning.selections, ...selections]) : freeze(selections) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js -var ExplainNode; -var init_explain_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js"() { - init_object_utils(); - ExplainNode = freeze({ - is(node) { - return node.kind === "ExplainNode"; - }, - create(format, options) { - return freeze({ - kind: "ExplainNode", - format, - options - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js -var WhenNode; -var init_when_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js"() { - init_object_utils(); - WhenNode = freeze({ - is(node) { - return node.kind === "WhenNode"; - }, - create(condition) { - return freeze({ - kind: "WhenNode", - condition - }); - }, - cloneWithResult(whenNode, result) { - return freeze({ - ...whenNode, - result - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js -var MergeQueryNode; -var init_merge_query_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js"() { - init_object_utils(); - init_when_node(); - MergeQueryNode = freeze({ - is(node) { - return node.kind === "MergeQueryNode"; - }, - create(into, withNode) { - return freeze({ - kind: "MergeQueryNode", - into, - ...withNode && { with: withNode } - }); - }, - cloneWithUsing(mergeNode, using) { - return freeze({ - ...mergeNode, - using - }); - }, - cloneWithWhen(mergeNode, when) { - return freeze({ - ...mergeNode, - whens: mergeNode.whens ? freeze([...mergeNode.whens, when]) : freeze([when]) - }); - }, - cloneWithThen(mergeNode, then) { - return freeze({ - ...mergeNode, - whens: mergeNode.whens ? freeze([ - ...mergeNode.whens.slice(0, -1), - WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then) - ]) : void 0 - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js -var OutputNode; -var init_output_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js"() { - init_object_utils(); - OutputNode = freeze({ - is(node) { - return node.kind === "OutputNode"; - }, - create(selections) { - return freeze({ - kind: "OutputNode", - selections: freeze(selections) - }); - }, - cloneWithSelections(output, selections) { - return freeze({ - ...output, - selections: output.selections ? freeze([...output.selections, ...selections]) : freeze(selections) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js -var QueryNode; -var init_query_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js"() { - init_insert_query_node(); - init_select_query_node(); - init_update_query_node(); - init_delete_query_node(); - init_where_node(); - init_object_utils(); - init_returning_node(); - init_explain_node(); - init_merge_query_node(); - init_output_node(); - init_order_by_node(); - QueryNode = freeze({ - is(node) { - return SelectQueryNode.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node) || MergeQueryNode.is(node); - }, - cloneWithEndModifier(node, modifier) { - return freeze({ - ...node, - endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : freeze([modifier]) - }); - }, - cloneWithWhere(node, operation) { - return freeze({ - ...node, - where: node.where ? WhereNode.cloneWithOperation(node.where, "And", operation) : WhereNode.create(operation) - }); - }, - cloneWithJoin(node, join2) { - return freeze({ - ...node, - joins: node.joins ? freeze([...node.joins, join2]) : freeze([join2]) - }); - }, - cloneWithReturning(node, selections) { - return freeze({ - ...node, - returning: node.returning ? ReturningNode.cloneWithSelections(node.returning, selections) : ReturningNode.create(selections) - }); - }, - cloneWithoutReturning(node) { - return freeze({ - ...node, - returning: void 0 - }); - }, - cloneWithoutWhere(node) { - return freeze({ - ...node, - where: void 0 - }); - }, - cloneWithExplain(node, format, options) { - return freeze({ - ...node, - explain: ExplainNode.create(format, options?.toOperationNode()) - }); - }, - cloneWithTop(node, top) { - return freeze({ - ...node, - top - }); - }, - cloneWithOutput(node, selections) { - return freeze({ - ...node, - output: node.output ? OutputNode.cloneWithSelections(node.output, selections) : OutputNode.create(selections) - }); - }, - cloneWithOrderByItems(node, items) { - return freeze({ - ...node, - orderBy: node.orderBy ? OrderByNode.cloneWithItems(node.orderBy, items) : OrderByNode.create(items) - }); - }, - cloneWithoutOrderBy(node) { - return freeze({ - ...node, - orderBy: void 0 - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js -var SelectQueryNode; -var init_select_query_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js"() { - init_object_utils(); - init_from_node(); - init_group_by_node(); - init_having_node(); - init_query_node(); - SelectQueryNode = freeze({ - is(node) { - return node.kind === "SelectQueryNode"; - }, - create(withNode) { - return freeze({ - kind: "SelectQueryNode", - ...withNode && { with: withNode } - }); - }, - createFrom(fromItems, withNode) { - return freeze({ - kind: "SelectQueryNode", - from: FromNode.create(fromItems), - ...withNode && { with: withNode } - }); - }, - cloneWithSelections(select, selections) { - return freeze({ - ...select, - selections: select.selections ? freeze([...select.selections, ...selections]) : freeze(selections) - }); - }, - cloneWithDistinctOn(select, expressions) { - return freeze({ - ...select, - distinctOn: select.distinctOn ? freeze([...select.distinctOn, ...expressions]) : freeze(expressions) - }); - }, - cloneWithFrontModifier(select, modifier) { - return freeze({ - ...select, - frontModifiers: select.frontModifiers ? freeze([...select.frontModifiers, modifier]) : freeze([modifier]) - }); - }, - // TODO: remove in v0.29 - /** - * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. - */ - cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items), - cloneWithGroupByItems(selectNode, items) { - return freeze({ - ...selectNode, - groupBy: selectNode.groupBy ? GroupByNode.cloneWithItems(selectNode.groupBy, items) : GroupByNode.create(items) - }); - }, - cloneWithLimit(selectNode, limit) { - return freeze({ - ...selectNode, - limit - }); - }, - cloneWithOffset(selectNode, offset) { - return freeze({ - ...selectNode, - offset - }); - }, - cloneWithFetch(selectNode, fetch2) { - return freeze({ - ...selectNode, - fetch: fetch2 - }); - }, - cloneWithHaving(selectNode, operation) { - return freeze({ - ...selectNode, - having: selectNode.having ? HavingNode.cloneWithOperation(selectNode.having, "And", operation) : HavingNode.create(operation) - }); - }, - cloneWithSetOperations(selectNode, setOperations) { - return freeze({ - ...selectNode, - setOperations: selectNode.setOperations ? freeze([...selectNode.setOperations, ...setOperations]) : freeze([...setOperations]) - }); - }, - cloneWithoutSelections(select) { - return freeze({ - ...select, - selections: [] - }); - }, - cloneWithoutLimit(select) { - return freeze({ - ...select, - limit: void 0 - }); - }, - cloneWithoutOffset(select) { - return freeze({ - ...select, - offset: void 0 - }); - }, - // TODO: remove in v0.29 - /** - * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. - */ - cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node), - cloneWithoutGroupBy(select) { - return freeze({ - ...select, - groupBy: void 0 - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js -var _props2, _JoinBuilder, JoinBuilder; -var init_join_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js"() { - init_join_node(); - init_raw_node(); - init_binary_operation_parser(); - init_object_utils(); - _JoinBuilder = class _JoinBuilder { - constructor(props) { - __privateAdd(this, _props2); - __privateSet(this, _props2, freeze(props)); - } - on(...args) { - return new _JoinBuilder({ - ...__privateGet(this, _props2), - joinNode: JoinNode.cloneWithOn(__privateGet(this, _props2).joinNode, parseValueBinaryOperationOrExpression(args)) - }); - } - /** - * Just like {@link WhereInterface.whereRef} but adds an item to the join's - * `on` clause instead. - * - * See {@link WhereInterface.whereRef} for documentation and examples. - */ - onRef(lhs, op, rhs) { - return new _JoinBuilder({ - ...__privateGet(this, _props2), - joinNode: JoinNode.cloneWithOn(__privateGet(this, _props2).joinNode, parseReferentialBinaryOperation(lhs, op, rhs)) - }); - } - /** - * Adds `on true`. - */ - onTrue() { - return new _JoinBuilder({ - ...__privateGet(this, _props2), - joinNode: JoinNode.cloneWithOn(__privateGet(this, _props2).joinNode, RawNode.createWithSql("true")) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props2).joinNode; - } - }; - _props2 = new WeakMap(); - JoinBuilder = _JoinBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js -var PartitionByItemNode; -var init_partition_by_item_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js"() { - init_object_utils(); - PartitionByItemNode = freeze({ - is(node) { - return node.kind === "PartitionByItemNode"; - }, - create(partitionBy) { - return freeze({ - kind: "PartitionByItemNode", - partitionBy - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js -function parsePartitionBy(partitionBy) { - return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create); -} -var init_partition_by_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js"() { - init_partition_by_item_node(); - init_reference_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js -var _props3, _OverBuilder, OverBuilder; -var init_over_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js"() { - init_over_node(); - init_query_node(); - init_order_by_parser(); - init_partition_by_parser(); - init_object_utils(); - _OverBuilder = class _OverBuilder { - constructor(props) { - __privateAdd(this, _props3); - __privateSet(this, _props3, freeze(props)); - } - orderBy(...args) { - return new _OverBuilder({ - overNode: OverNode.cloneWithOrderByItems(__privateGet(this, _props3).overNode, parseOrderBy(args)) - }); - } - clearOrderBy() { - return new _OverBuilder({ - overNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props3).overNode) - }); - } - partitionBy(partitionBy) { - return new _OverBuilder({ - overNode: OverNode.cloneWithPartitionByItems(__privateGet(this, _props3).overNode, parsePartitionBy(partitionBy)) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props3).overNode; - } - }; - _props3 = new WeakMap(); - OverBuilder = _OverBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js -var SelectionNode; -var init_selection_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js"() { - init_object_utils(); - init_reference_node(); - init_select_all_node(); - SelectionNode = freeze({ - is(node) { - return node.kind === "SelectionNode"; - }, - create(selection) { - return freeze({ - kind: "SelectionNode", - selection - }); - }, - createSelectAll() { - return freeze({ - kind: "SelectionNode", - selection: SelectAllNode.create() - }); - }, - createSelectAllFromTable(table) { - return freeze({ - kind: "SelectionNode", - selection: ReferenceNode.createSelectAll(table) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js -function parseSelectArg(selection) { - if (isFunction3(selection)) { - return parseSelectArg(selection(expressionBuilder())); - } else if (isReadonlyArray(selection)) { - return selection.map((it) => parseSelectExpression(it)); - } else { - return [parseSelectExpression(selection)]; - } -} -function parseSelectExpression(selection) { - if (isString2(selection)) { - return SelectionNode.create(parseAliasedStringReference(selection)); - } else if (isDynamicReferenceBuilder(selection)) { - return SelectionNode.create(selection.toOperationNode()); - } else { - return SelectionNode.create(parseAliasedExpression(selection)); - } -} -function parseSelectAll(table) { - if (!table) { - return [SelectionNode.createSelectAll()]; - } else if (Array.isArray(table)) { - return table.map(parseSelectAllArg); - } else { - return [parseSelectAllArg(table)]; - } -} -function parseSelectAllArg(table) { - if (isString2(table)) { - return SelectionNode.createSelectAllFromTable(parseTable(table)); - } - throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`); -} -var init_select_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js"() { - init_object_utils(); - init_selection_node(); - init_reference_parser(); - init_dynamic_reference_builder(); - init_expression_parser(); - init_table_parser(); - init_expression_builder(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js -var ValuesNode; -var init_values_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js"() { - init_object_utils(); - ValuesNode = freeze({ - is(node) { - return node.kind === "ValuesNode"; - }, - create(values) { - return freeze({ - kind: "ValuesNode", - values: freeze(values) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js -var DefaultInsertValueNode; -var init_default_insert_value_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js"() { - init_object_utils(); - DefaultInsertValueNode = freeze({ - is(node) { - return node.kind === "DefaultInsertValueNode"; - }, - create() { - return freeze({ - kind: "DefaultInsertValueNode" - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js -function parseInsertExpression(arg) { - const objectOrList = isFunction3(arg) ? arg(expressionBuilder()) : arg; - const list = isReadonlyArray(objectOrList) ? objectOrList : freeze([objectOrList]); - return parseInsertColumnsAndValues(list); -} -function parseInsertColumnsAndValues(rows) { - const columns = parseColumnNamesAndIndexes(rows); - return [ - freeze([...columns.keys()].map(ColumnNode.create)), - ValuesNode.create(rows.map((row) => parseRowValues(row, columns))) - ]; -} -function parseColumnNamesAndIndexes(rows) { - const columns = /* @__PURE__ */ new Map(); - for (const row of rows) { - const cols = Object.keys(row); - for (const col of cols) { - if (!columns.has(col) && row[col] !== void 0) { - columns.set(col, columns.size); - } - } - } - return columns; -} -function parseRowValues(row, columns) { - const rowColumns = Object.keys(row); - const rowValues = Array.from({ - length: columns.size - }); - let hasUndefinedOrComplexColumns = false; - let indexedRowColumns = rowColumns.length; - for (const col of rowColumns) { - const columnIdx = columns.get(col); - if (isUndefined(columnIdx)) { - indexedRowColumns--; - continue; - } - const value = row[col]; - if (isUndefined(value) || isExpressionOrFactory(value)) { - hasUndefinedOrComplexColumns = true; - } - rowValues[columnIdx] = value; - } - const hasMissingColumns = indexedRowColumns < columns.size; - if (hasMissingColumns || hasUndefinedOrComplexColumns) { - const defaultValue = DefaultInsertValueNode.create(); - return ValueListNode.create(rowValues.map((it) => isUndefined(it) ? defaultValue : parseValueExpression(it))); - } - return PrimitiveValueListNode.create(rowValues); -} -var init_insert_values_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js"() { - init_column_node(); - init_primitive_value_list_node(); - init_value_list_node(); - init_object_utils(); - init_value_parser(); - init_values_node(); - init_expression_parser(); - init_default_insert_value_node(); - init_expression_builder(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js -var ColumnUpdateNode; -var init_column_update_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js"() { - init_object_utils(); - ColumnUpdateNode = freeze({ - is(node) { - return node.kind === "ColumnUpdateNode"; - }, - create(column, value) { - return freeze({ - kind: "ColumnUpdateNode", - column, - value - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js -function parseUpdate(...args) { - if (args.length === 2) { - return [ - ColumnUpdateNode.create(parseReferenceExpression(args[0]), parseValueExpression(args[1])) - ]; - } - return parseUpdateObjectExpression(args[0]); -} -function parseUpdateObjectExpression(update) { - const updateObj = isFunction3(update) ? update(expressionBuilder()) : update; - return Object.entries(updateObj).filter(([_, value]) => value !== void 0).map(([key, value]) => { - return ColumnUpdateNode.create(ColumnNode.create(key), parseValueExpression(value)); - }); -} -var init_update_set_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js"() { - init_column_node(); - init_column_update_node(); - init_expression_builder(); - init_object_utils(); - init_value_parser(); - init_reference_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js -var OnDuplicateKeyNode; -var init_on_duplicate_key_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js"() { - init_object_utils(); - OnDuplicateKeyNode = freeze({ - is(node) { - return node.kind === "OnDuplicateKeyNode"; - }, - create(updates) { - return freeze({ - kind: "OnDuplicateKeyNode", - updates - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js -var InsertResult; -var init_insert_result = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js"() { - InsertResult = class { - constructor(insertId, numInsertedOrUpdatedRows) { - /** - * The auto incrementing primary key of the inserted row. - * - * This property can be undefined when the query contains an `on conflict` - * clause that makes the query succeed even when nothing gets inserted. - * - * This property is always undefined on dialects like PostgreSQL that - * don't return the inserted id by default. On those dialects you need - * to use the {@link ReturningInterface.returning | returning} method. - */ - __publicField(this, "insertId"); - /** - * Affected rows count. - */ - __publicField(this, "numInsertedOrUpdatedRows"); - this.insertId = insertId; - this.numInsertedOrUpdatedRows = numInsertedOrUpdatedRows; - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js -function isNoResultErrorConstructor(fn) { - return Object.prototype.hasOwnProperty.call(fn, "prototype"); -} -var NoResultError; -var init_no_result_error = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js"() { - NoResultError = class extends Error { - constructor(node) { - super("no result"); - /** - * The operation node tree of the query that was executed. - */ - __publicField(this, "node"); - this.node = node; - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js -var OnConflictNode; -var init_on_conflict_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js"() { - init_object_utils(); - init_where_node(); - OnConflictNode = freeze({ - is(node) { - return node.kind === "OnConflictNode"; - }, - create() { - return freeze({ - kind: "OnConflictNode" - }); - }, - cloneWith(node, props) { - return freeze({ - ...node, - ...props - }); - }, - cloneWithIndexWhere(node, operation) { - return freeze({ - ...node, - indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "And", operation) : WhereNode.create(operation) - }); - }, - cloneWithIndexOrWhere(node, operation) { - return freeze({ - ...node, - indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "Or", operation) : WhereNode.create(operation) - }); - }, - cloneWithUpdateWhere(node, operation) { - return freeze({ - ...node, - updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "And", operation) : WhereNode.create(operation) - }); - }, - cloneWithUpdateOrWhere(node, operation) { - return freeze({ - ...node, - updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "Or", operation) : WhereNode.create(operation) - }); - }, - cloneWithoutIndexWhere(node) { - return freeze({ - ...node, - indexWhere: void 0 - }); - }, - cloneWithoutUpdateWhere(node) { - return freeze({ - ...node, - updateWhere: void 0 - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js -var _props4, _OnConflictBuilder, OnConflictBuilder, _props5, OnConflictDoNothingBuilder, _props6, _OnConflictUpdateBuilder, OnConflictUpdateBuilder; -var init_on_conflict_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js"() { - init_column_node(); - init_identifier_node(); - init_on_conflict_node(); - init_binary_operation_parser(); - init_update_set_parser(); - init_object_utils(); - _OnConflictBuilder = class _OnConflictBuilder { - constructor(props) { - __privateAdd(this, _props4); - __privateSet(this, _props4, freeze(props)); - } - /** - * Specify a single column as the conflict target. - * - * Also see the {@link columns}, {@link constraint} and {@link expression} - * methods for alternative ways to specify the conflict target. - */ - column(column) { - const columnNode = ColumnNode.create(column); - return new _OnConflictBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { - columns: __privateGet(this, _props4).onConflictNode.columns ? freeze([...__privateGet(this, _props4).onConflictNode.columns, columnNode]) : freeze([columnNode]) - }) - }); - } - /** - * Specify a list of columns as the conflict target. - * - * Also see the {@link column}, {@link constraint} and {@link expression} - * methods for alternative ways to specify the conflict target. - */ - columns(columns) { - const columnNodes = columns.map(ColumnNode.create); - return new _OnConflictBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { - columns: __privateGet(this, _props4).onConflictNode.columns ? freeze([...__privateGet(this, _props4).onConflictNode.columns, ...columnNodes]) : freeze(columnNodes) - }) - }); - } - /** - * Specify a specific constraint by name as the conflict target. - * - * Also see the {@link column}, {@link columns} and {@link expression} - * methods for alternative ways to specify the conflict target. - */ - constraint(constraintName) { - return new _OnConflictBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { - constraint: IdentifierNode.create(constraintName) - }) - }); - } - /** - * Specify an expression as the conflict target. - * - * This can be used if the unique index is an expression index. - * - * Also see the {@link column}, {@link columns} and {@link constraint} - * methods for alternative ways to specify the conflict target. - */ - expression(expression) { - return new _OnConflictBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { - indexExpression: expression.toOperationNode() - }) - }); - } - where(...args) { - return new _OnConflictBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWithIndexWhere(__privateGet(this, _props4).onConflictNode, parseValueBinaryOperationOrExpression(args)) - }); - } - whereRef(lhs, op, rhs) { - return new _OnConflictBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWithIndexWhere(__privateGet(this, _props4).onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs)) - }); - } - clearWhere() { - return new _OnConflictBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWithoutIndexWhere(__privateGet(this, _props4).onConflictNode) - }); - } - /** - * Adds the "do nothing" conflict action. - * - * ### Examples - * - * ```ts - * const id = 1 - * const first_name = 'John' - * - * await db - * .insertInto('person') - * .values({ first_name, id }) - * .onConflict((oc) => oc - * .column('id') - * .doNothing() - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "id") - * values ($1, $2) - * on conflict ("id") do nothing - * ``` - */ - doNothing() { - return new OnConflictDoNothingBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { - doNothing: true - }) - }); - } - /** - * Adds the "do update set" conflict action. - * - * ### Examples - * - * ```ts - * const id = 1 - * const first_name = 'John' - * - * await db - * .insertInto('person') - * .values({ first_name, id }) - * .onConflict((oc) => oc - * .column('id') - * .doUpdateSet({ first_name }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "id") - * values ($1, $2) - * on conflict ("id") - * do update set "first_name" = $3 - * ``` - * - * In the next example we use the `ref` method to reference - * columns of the virtual table `excluded` in a type-safe way - * to create an upsert operation: - * - * ```ts - * import type { NewPerson } from 'type-editor' // imaginary module - * - * async function upsertPerson(person: NewPerson): Promise { - * await db.insertInto('person') - * .values(person) - * .onConflict((oc) => oc - * .column('id') - * .doUpdateSet((eb) => ({ - * first_name: eb.ref('excluded.first_name'), - * last_name: eb.ref('excluded.last_name') - * }) - * ) - * ) - * .execute() - * } - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name") - * values ($1, $2) - * on conflict ("id") - * do update set - * "first_name" = excluded."first_name", - * "last_name" = excluded."last_name" - * ``` - */ - doUpdateSet(update) { - return new OnConflictUpdateBuilder({ - ...__privateGet(this, _props4), - onConflictNode: OnConflictNode.cloneWith(__privateGet(this, _props4).onConflictNode, { - updates: parseUpdateObjectExpression(update) - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - }; - _props4 = new WeakMap(); - OnConflictBuilder = _OnConflictBuilder; - OnConflictDoNothingBuilder = class { - constructor(props) { - __privateAdd(this, _props5); - __privateSet(this, _props5, freeze(props)); - } - toOperationNode() { - return __privateGet(this, _props5).onConflictNode; - } - }; - _props5 = new WeakMap(); - _OnConflictUpdateBuilder = class _OnConflictUpdateBuilder { - constructor(props) { - __privateAdd(this, _props6); - __privateSet(this, _props6, freeze(props)); - } - where(...args) { - return new _OnConflictUpdateBuilder({ - ...__privateGet(this, _props6), - onConflictNode: OnConflictNode.cloneWithUpdateWhere(__privateGet(this, _props6).onConflictNode, parseValueBinaryOperationOrExpression(args)) - }); - } - /** - * Specify a where condition for the update operation. - * - * See {@link WhereInterface.whereRef} for more info. - */ - whereRef(lhs, op, rhs) { - return new _OnConflictUpdateBuilder({ - ...__privateGet(this, _props6), - onConflictNode: OnConflictNode.cloneWithUpdateWhere(__privateGet(this, _props6).onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs)) - }); - } - clearWhere() { - return new _OnConflictUpdateBuilder({ - ...__privateGet(this, _props6), - onConflictNode: OnConflictNode.cloneWithoutUpdateWhere(__privateGet(this, _props6).onConflictNode) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props6).onConflictNode; - } - }; - _props6 = new WeakMap(); - OnConflictUpdateBuilder = _OnConflictUpdateBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js -var TopNode; -var init_top_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js"() { - init_object_utils(); - TopNode = freeze({ - is(node) { - return node.kind === "TopNode"; - }, - create(expression, modifiers) { - return freeze({ - kind: "TopNode", - expression, - modifiers - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js -function parseTop(expression, modifiers) { - if (!isNumber2(expression) && !isBigInt(expression)) { - throw new Error(`Invalid top expression: ${expression}`); - } - if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) { - throw new Error(`Invalid top modifiers: ${modifiers}`); - } - return TopNode.create(expression, modifiers); -} -function isTopModifiers(modifiers) { - return modifiers === "percent" || modifiers === "with ties" || modifiers === "percent with ties"; -} -var init_top_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js"() { - init_top_node(); - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js -var OrActionNode; -var init_or_action_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js"() { - init_object_utils(); - OrActionNode = freeze({ - is(node) { - return node.kind === "OrActionNode"; - }, - create(action) { - return freeze({ - kind: "OrActionNode", - action - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js -var _props7, _InsertQueryBuilder, InsertQueryBuilder; -var init_insert_query_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js"() { - init_select_parser(); - init_insert_values_parser(); - init_insert_query_node(); - init_query_node(); - init_update_set_parser(); - init_object_utils(); - init_on_duplicate_key_node(); - init_insert_result(); - init_no_result_error(); - init_expression_parser(); - init_column_node(); - init_on_conflict_builder(); - init_on_conflict_node(); - init_top_parser(); - init_or_action_node(); - _InsertQueryBuilder = class _InsertQueryBuilder { - constructor(props) { - __privateAdd(this, _props7); - __privateSet(this, _props7, freeze(props)); - } - /** - * Sets the values to insert for an {@link Kysely.insertInto | insert} query. - * - * This method takes an object whose keys are column names and values are - * values to insert. In addition to the column's type, the values can be - * raw {@link sql} snippets or select queries. - * - * You must provide all fields you haven't explicitly marked as nullable - * or optional using {@link Generated} or {@link ColumnType}. - * - * The return value of an `insert` query is an instance of {@link InsertResult}. The - * {@link InsertResult.insertId | insertId} field holds the auto incremented primary - * key if the database returned one. - * - * On PostgreSQL and some other dialects, you need to call `returning` to get - * something out of the query. - * - * Also see the {@link expression} method for inserting the result of a select - * query or any other expression. - * - * ### Examples - * - * - * - * Insert a single row: - * - * ```ts - * const result = await db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40 - * }) - * .executeTakeFirst() - * - * // `insertId` is only available on dialects that - * // automatically return the id of the inserted row - * // such as MySQL and SQLite. On PostgreSQL, for example, - * // you need to add a `returning` clause to the query to - * // get anything out. See the "returning data" example. - * console.log(result.insertId) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert into `person` (`first_name`, `last_name`, `age`) values (?, ?, ?) - * ``` - * - * - * - * On dialects that support it (for example PostgreSQL) you can insert multiple - * rows by providing an array. Note that the return value is once again very - * dialect-specific. Some databases may only return the id of the *last* inserted - * row and some return nothing at all unless you call `returning`. - * - * ```ts - * await db - * .insertInto('person') - * .values([{ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }, { - * first_name: 'Arnold', - * last_name: 'Schwarzenegger', - * age: 70, - * }]) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name", "age") values (($1, $2, $3), ($4, $5, $6)) - * ``` - * - * - * - * On supported dialects like PostgreSQL you need to chain `returning` to the query to get - * the inserted row's columns (or any other expression) as the return value. `returning` - * works just like `select`. Refer to `select` method's examples and documentation for - * more info. - * - * ```ts - * const result = await db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }) - * .returning(['id', 'first_name as name']) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name", "age") values ($1, $2, $3) returning "id", "first_name" as "name" - * ``` - * - * - * - * In addition to primitives, the values can also be arbitrary expressions. - * You can build the expressions by using a callback and calling the methods - * on the expression builder passed to it: - * - * ```ts - * import { sql } from 'kysely' - * - * const ani = "Ani" - * const ston = "ston" - * - * const result = await db - * .insertInto('person') - * .values(({ ref, selectFrom, fn }) => ({ - * first_name: 'Jennifer', - * last_name: sql`concat(${ani}, ${ston})`, - * middle_name: ref('first_name'), - * age: selectFrom('person') - * .select(fn.avg('age').as('avg_age')), - * })) - * .executeTakeFirst() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ( - * "first_name", - * "last_name", - * "middle_name", - * "age" - * ) - * values ( - * $1, - * concat($2, $3), - * "first_name", - * (select avg("age") as "avg_age" from "person") - * ) - * ``` - * - * You can also use the callback version of subqueries or raw expressions: - * - * ```ts - * await db.with('jennifer', (db) => db - * .selectFrom('person') - * .where('first_name', '=', 'Jennifer') - * .select(['id', 'first_name', 'gender']) - * .limit(1) - * ).insertInto('pet').values((eb) => ({ - * owner_id: eb.selectFrom('jennifer').select('id'), - * name: eb.selectFrom('jennifer').select('first_name'), - * species: 'cat', - * })) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * with "jennifer" as ( - * select "id", "first_name", "gender" - * from "person" - * where "first_name" = $1 - * limit $2 - * ) - * insert into "pet" ("owner_id", "name", "species") - * values ( - * (select "id" from "jennifer"), - * (select "first_name" from "jennifer"), - * $3 - * ) - * ``` - */ - values(insert) { - const [columns, values] = parseInsertExpression(insert); - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - columns, - values - }) - }); - } - /** - * Sets the columns to insert. - * - * The {@link values} method sets both the columns and the values and this method - * is not needed. But if you are using the {@link expression} method, you can use - * this method to set the columns to insert. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .columns(['first_name']) - * .expression((eb) => eb.selectFrom('pet').select('pet.name')) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name") - * select "pet"."name" from "pet" - * ``` - */ - columns(columns) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - columns: freeze(columns.map(ColumnNode.create)) - }) - }); - } - /** - * Insert an arbitrary expression. For example the result of a select query. - * - * ### Examples - * - * - * - * You can create an `INSERT INTO SELECT FROM` query using the `expression` method. - * This API doesn't follow our WYSIWYG principles and might be a bit difficult to - * remember. The reasons for this design stem from implementation difficulties. - * - * ```ts - * const result = await db.insertInto('person') - * .columns(['first_name', 'last_name', 'age']) - * .expression((eb) => eb - * .selectFrom('pet') - * .select((eb) => [ - * 'pet.name', - * eb.val('Petson').as('last_name'), - * eb.lit(7).as('age'), - * ]) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name", "age") - * select "pet"."name", $1 as "last_name", 7 as "age from "pet" - * ``` - */ - expression(expression) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - values: parseExpression(expression) - }) - }); - } - /** - * Creates an `insert into "person" default values` query. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .defaultValues() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" default values - * ``` - */ - defaultValues() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - defaultValues: true - }) - }); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.insertInto('person') - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * }) - * .modifyEnd(sql`-- This is a comment`) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert into `person` ("first_name", "last_name", "gender") - * values (?, ?, ?) -- This is a comment - * ``` - */ - modifyEnd(modifier) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props7).queryNode, modifier.toOperationNode()) - }); - } - /** - * Changes an `insert into` query to an `insert ignore into` query. - * - * This is only supported by some dialects like MySQL. - * - * To avoid a footgun, when invoked with the SQLite dialect, this method will - * be handled like {@link orIgnore}. See also, {@link orAbort}, {@link orFail}, - * {@link orReplace}, and {@link orRollback}. - * - * If you use the ignore modifier, ignorable errors that occur while executing the - * insert statement are ignored. For example, without ignore, a row that duplicates - * an existing unique index or primary key value in the table causes a duplicate-key - * error and the statement is aborted. With ignore, the row is discarded and no error - * occurs. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .ignore() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?) - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - ignore() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - orAction: OrActionNode.create("ignore") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or ignore into` query. - * - * This is only supported by some dialects like SQLite. - * - * To avoid a footgun, when invoked with the MySQL dialect, this method will - * be handled like {@link ignore}. - * - * See also, {@link orAbort}, {@link orFail}, {@link orReplace}, and {@link orRollback}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orIgnore() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?) - * ``` - */ - orIgnore() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - orAction: OrActionNode.create("ignore") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or abort into` query. - * - * This is only supported by some dialects like SQLite. - * - * See also, {@link orIgnore}, {@link orFail}, {@link orReplace}, and {@link orRollback}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orAbort() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or abort into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - orAbort() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - orAction: OrActionNode.create("abort") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or fail into` query. - * - * This is only supported by some dialects like SQLite. - * - * See also, {@link orIgnore}, {@link orAbort}, {@link orReplace}, and {@link orRollback}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orFail() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or fail into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - orFail() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - orAction: OrActionNode.create("fail") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or replace into` query. - * - * This is only supported by some dialects like SQLite. - * - * You can also use {@link Kysely.replaceInto} to achieve the same result. - * - * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orRollback}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orReplace() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or replace into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - orReplace() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - orAction: OrActionNode.create("replace") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or rollback into` query. - * - * This is only supported by some dialects like SQLite. - * - * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orReplace}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orRollback() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or rollback into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - orRollback() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - orAction: OrActionNode.create("rollback") - }) - }); - } - /** - * Changes an `insert into` query to an `insert top into` query. - * - * `top` clause is only supported by some dialects like MS SQL Server. - * - * ### Examples - * - * Insert the first 5 rows: - * - * ```ts - * import { sql } from 'kysely' - * - * await db.insertInto('person') - * .top(5) - * .columns(['first_name', 'gender']) - * .expression( - * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')]) - * ) - * .execute() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * insert top(5) into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet" - * ``` - * - * Insert the first 50 percent of rows: - * - * ```ts - * import { sql } from 'kysely' - * - * await db.insertInto('person') - * .top(50, 'percent') - * .columns(['first_name', 'gender']) - * .expression( - * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')]) - * ) - * .execute() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * insert top(50) percent into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet" - * ``` - */ - top(expression, modifiers) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: QueryNode.cloneWithTop(__privateGet(this, _props7).queryNode, parseTop(expression, modifiers)) - }); - } - /** - * Adds an `on conflict` clause to the query. - * - * `on conflict` is only supported by some dialects like PostgreSQL and SQLite. On MySQL - * you can use {@link ignore} and {@link onDuplicateKeyUpdate} to achieve similar results. - * - * ### Examples - * - * ```ts - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .column('name') - * .doUpdateSet({ species: 'hamster' }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict ("name") - * do update set "species" = $4 - * ``` - * - * You can provide the name of the constraint instead of a column name: - * - * ```ts - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .constraint('pet_name_key') - * .doUpdateSet({ species: 'hamster' }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict on constraint "pet_name_key" - * do update set "species" = $4 - * ``` - * - * You can also specify an expression as the conflict target in case - * the unique index is an expression index: - * - * ```ts - * import { sql } from 'kysely' - * - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .expression(sql`lower(name)`) - * .doUpdateSet({ species: 'hamster' }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict (lower(name)) - * do update set "species" = $4 - * ``` - * - * You can add a filter for the update statement like this: - * - * ```ts - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .column('name') - * .doUpdateSet({ species: 'hamster' }) - * .where('excluded.name', '!=', 'Catto') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict ("name") - * do update set "species" = $4 - * where "excluded"."name" != $5 - * ``` - * - * You can create an `on conflict do nothing` clauses like this: - * - * ```ts - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .column('name') - * .doNothing() - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict ("name") do nothing - * ``` - * - * You can refer to the columns of the virtual `excluded` table - * in a type-safe way using a callback and the `ref` method of - * `ExpressionBuilder`: - * - * ```ts - * await db.insertInto('person') - * .values({ - * id: 1, - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * }) - * .onConflict(oc => oc - * .column('id') - * .doUpdateSet({ - * first_name: (eb) => eb.ref('excluded.first_name'), - * last_name: (eb) => eb.ref('excluded.last_name') - * }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("id", "first_name", "last_name", "gender") - * values ($1, $2, $3, $4) - * on conflict ("id") - * do update set - * "first_name" = "excluded"."first_name", - * "last_name" = "excluded"."last_name" - * ``` - */ - onConflict(callback) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - onConflict: callback(new OnConflictBuilder({ - onConflictNode: OnConflictNode.create() - })).toOperationNode() - }) - }); - } - /** - * Adds `on duplicate key update` to the query. - * - * If you specify `on duplicate key update`, and a row is inserted that would cause - * a duplicate value in a unique index or primary key, an update of the old row occurs. - * - * This is only implemented by some dialects like MySQL. On most dialects you should - * use {@link onConflict} instead. - * - * ### Examples - * - * ```ts - * await db - * .insertInto('person') - * .values({ - * id: 1, - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * }) - * .onDuplicateKeyUpdate({ updated_at: new Date().toISOString() }) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert into `person` (`id`, `first_name`, `last_name`, `gender`) - * values (?, ?, ?, ?) - * on duplicate key update `updated_at` = ? - * ``` - */ - onDuplicateKeyUpdate(update) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: InsertQueryNode.cloneWith(__privateGet(this, _props7).queryNode, { - onDuplicateKey: OnDuplicateKeyNode.create(parseUpdateObjectExpression(update)) - }) - }); - } - returning(selection) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props7).queryNode, parseSelectArg(selection)) - }); - } - returningAll() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props7).queryNode, parseSelectAll()) - }); - } - output(args) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props7).queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props7).queryNode, parseSelectAll(table)) - }); - } - /** - * Clears all `returning` clauses from the query. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .values({ first_name: 'James', last_name: 'Smith', gender: 'male' }) - * .returning(['first_name']) - * .clearReturning() - * .execute() - * ``` - * - * The generated SQL(PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name", "gender") values ($1, $2, $3) - * ``` - */ - clearReturning() { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: QueryNode.cloneWithoutReturning(__privateGet(this, _props7).queryNode) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - * - * If you want to conditionally call a method on `this`, see - * the {@link $if} method. - * - * ### Examples - * - * The next example uses a helper function `log` to log a query: - * - * ```ts - * import type { Compilable } from 'kysely' - * - * function log(qb: T): T { - * console.log(qb.compile()) - * return qb - * } - * - * await db.insertInto('person') - * .values({ first_name: 'John', last_name: 'Doe', gender: 'male' }) - * .$call(log) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - /** - * Call `func(this)` if `condition` is true. - * - * This method is especially handy with optional selects. Any `returning` or `returningAll` - * method calls add columns as optional fields to the output type when called inside - * the `func` callback. This is because we can't know if those selections were actually - * made before running the code. - * - * You can also call any other methods inside the callback. - * - * ### Examples - * - * ```ts - * import type { NewPerson } from 'type-editor' // imaginary module - * - * async function insertPerson(values: NewPerson, returnLastName: boolean) { - * return await db - * .insertInto('person') - * .values(values) - * .returning(['id', 'first_name']) - * .$if(returnLastName, (qb) => qb.returning('last_name')) - * .executeTakeFirstOrThrow() - * } - * ``` - * - * Any selections added inside the `if` callback will be added as optional fields to the - * output type since we can't know if the selections were actually made before running - * the code. In the example above the return type of the `insertPerson` function is: - * - * ```ts - * Promise<{ - * id: number - * first_name: string - * last_name?: string - * }> - * ``` - */ - $if(condition, func) { - if (condition) { - return func(this); - } - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7) - }); - } - /** - * Change the output type of the query. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `InsertQueryBuilder` with a new output type. - */ - $castTo() { - return new _InsertQueryBuilder(__privateGet(this, _props7)); - } - /** - * Narrows (parts of) the output type of the query. - * - * Kysely tries to be as type-safe as possible, but in some cases we have to make - * compromises for better maintainability and compilation performance. At present, - * Kysely doesn't narrow the output type of the query based on {@link values} input - * when using {@link returning} or {@link returningAll}. - * - * This utility method is very useful for these situations, as it removes unncessary - * runtime assertion/guard code. Its input type is limited to the output type - * of the query, so you can't add a column that doesn't exist, or change a column's - * type to something that doesn't exist in its union type. - * - * ### Examples - * - * Turn this code: - * - * ```ts - * import type { Person } from 'type-editor' // imaginary module - * - * const person = await db.insertInto('person') - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * nullable_column: 'hell yeah!' - * }) - * .returningAll() - * .executeTakeFirstOrThrow() - * - * if (isWithNoNullValue(person)) { - * functionThatExpectsPersonWithNonNullValue(person) - * } - * - * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { - * return person.nullable_column != null - * } - * ``` - * - * Into this: - * - * ```ts - * import type { NotNull } from 'kysely' - * - * const person = await db.insertInto('person') - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * nullable_column: 'hell yeah!' - * }) - * .returningAll() - * .$narrowType<{ nullable_column: NotNull }>() - * .executeTakeFirstOrThrow() - * - * functionThatExpectsPersonWithNonNullValue(person) - * ``` - */ - $narrowType() { - return new _InsertQueryBuilder(__privateGet(this, _props7)); - } - /** - * Asserts that query's output row type equals the given type `T`. - * - * This method can be used to simplify excessively complex types to make TypeScript happy - * and much faster. - * - * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much - * for TypeScript and you get errors like this: - * - * ``` - * error TS2589: Type instantiation is excessively deep and possibly infinite. - * ``` - * - * In these case you can often use this method to help TypeScript a little bit. When you use this - * method to assert the output type of a query, Kysely can drop the complex output type that - * consists of multiple nested helper types and replace it with the simple asserted type. - * - * Using this method doesn't reduce type safety at all. You have to pass in a type that is - * structurally equal to the current type. - * - * ### Examples - * - * ```ts - * import type { NewPerson, NewPet, Species } from 'type-editor' // imaginary module - * - * async function insertPersonAndPet(person: NewPerson, pet: Omit) { - * return await db - * .with('new_person', (qb) => qb - * .insertInto('person') - * .values(person) - * .returning('id') - * .$assertType<{ id: number }>() - * ) - * .with('new_pet', (qb) => qb - * .insertInto('pet') - * .values((eb) => ({ - * owner_id: eb.selectFrom('new_person').select('id'), - * ...pet - * })) - * .returning(['name as pet_name', 'species']) - * .$assertType<{ pet_name: string, species: Species }>() - * ) - * .selectFrom(['new_person', 'new_pet']) - * .selectAll() - * .executeTakeFirstOrThrow() - * } - * ``` - */ - $assertType() { - return new _InsertQueryBuilder(__privateGet(this, _props7)); - } - /** - * Returns a copy of this InsertQueryBuilder instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - executor: __privateGet(this, _props7).executor.withPlugin(plugin) - }); - } - toOperationNode() { - return __privateGet(this, _props7).executor.transformQuery(__privateGet(this, _props7).queryNode, __privateGet(this, _props7).queryId); - } - compile() { - return __privateGet(this, _props7).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props7).queryId); - } - /** - * Executes the query and returns an array of rows. - * - * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. - */ - async execute() { - const compiledQuery = this.compile(); - const result = await __privateGet(this, _props7).executor.executeQuery(compiledQuery); - const { adapter } = __privateGet(this, _props7).executor; - const query = compiledQuery.query; - if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { - return result.rows; - } - return [ - new InsertResult(result.insertId, result.numAffectedRows ?? BigInt(0)) - ]; - } - /** - * Executes the query and returns the first result or undefined if - * the query returned no result. - */ - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - /** - * Executes the query and returns the first result or throws if - * the query returned no result. - * - * By default an instance of {@link NoResultError} is thrown, but you can - * provide a custom error class, or callback as the only argument to throw a different - * error. - */ - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error49; - } - return result; - } - async *stream(chunkSize = 100) { - const compiledQuery = this.compile(); - const stream = __privateGet(this, _props7).executor.stream(compiledQuery, chunkSize); - for await (const item of stream) { - yield* item.rows; - } - } - async explain(format, options) { - const builder = new _InsertQueryBuilder({ - ...__privateGet(this, _props7), - queryNode: QueryNode.cloneWithExplain(__privateGet(this, _props7).queryNode, format, options) - }); - return await builder.execute(); - } - }; - _props7 = new WeakMap(); - InsertQueryBuilder = _InsertQueryBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js -var DeleteResult; -var init_delete_result = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js"() { - DeleteResult = class { - constructor(numDeletedRows) { - __publicField(this, "numDeletedRows"); - this.numDeletedRows = numDeletedRows; - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js -var LimitNode; -var init_limit_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js"() { - init_object_utils(); - LimitNode = freeze({ - is(node) { - return node.kind === "LimitNode"; - }, - create(limit) { - return freeze({ - kind: "LimitNode", - limit - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js -var _a12, _props8, _DeleteQueryBuilder_instances, join_fn, DeleteQueryBuilder; -var init_delete_query_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js"() { - init_join_parser(); - init_table_parser(); - init_select_parser(); - init_query_node(); - init_object_utils(); - init_no_result_error(); - init_delete_result(); - init_delete_query_node(); - init_limit_node(); - init_order_by_parser(); - init_binary_operation_parser(); - init_value_parser(); - init_top_parser(); - DeleteQueryBuilder = class { - constructor(props) { - __privateAdd(this, _DeleteQueryBuilder_instances); - __privateAdd(this, _props8); - __privateSet(this, _props8, freeze(props)); - } - where(...args) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props8).queryNode, parseValueBinaryOperationOrExpression(args)) - }); - } - whereRef(lhs, op, rhs) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props8).queryNode, parseReferentialBinaryOperation(lhs, op, rhs)) - }); - } - clearWhere() { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithoutWhere(__privateGet(this, _props8).queryNode) - }); - } - /** - * Changes a `delete from` query into a `delete top from` query. - * - * `top` clause is only supported by some dialects like MS SQL Server. - * - * ### Examples - * - * Delete the first 5 rows: - * - * ```ts - * await db - * .deleteFrom('person') - * .top(5) - * .where('age', '>', 18) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * delete top(5) from "person" where "age" > @1 - * ``` - * - * Delete the first 50% of rows: - * - * ```ts - * await db - * .deleteFrom('person') - * .top(50, 'percent') - * .where('age', '>', 18) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * delete top(50) percent from "person" where "age" > @1 - * ``` - */ - top(expression, modifiers) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithTop(__privateGet(this, _props8).queryNode, parseTop(expression, modifiers)) - }); - } - using(tables) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: DeleteQueryNode.cloneWithUsing(__privateGet(this, _props8).queryNode, parseTableExpressionOrList(tables)) - }); - } - innerJoin(...args) { - return __privateMethod(this, _DeleteQueryBuilder_instances, join_fn).call(this, "InnerJoin", args); - } - leftJoin(...args) { - return __privateMethod(this, _DeleteQueryBuilder_instances, join_fn).call(this, "LeftJoin", args); - } - rightJoin(...args) { - return __privateMethod(this, _DeleteQueryBuilder_instances, join_fn).call(this, "RightJoin", args); - } - fullJoin(...args) { - return __privateMethod(this, _DeleteQueryBuilder_instances, join_fn).call(this, "FullJoin", args); - } - returning(selection) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props8).queryNode, parseSelectArg(selection)) - }); - } - returningAll(table) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props8).queryNode, parseSelectAll(table)) - }); - } - output(args) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props8).queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props8).queryNode, parseSelectAll(table)) - }); - } - /** - * Clears all `returning` clauses from the query. - * - * ### Examples - * - * ```ts - * await db.deleteFrom('pet') - * .returningAll() - * .where('name', '=', 'Max') - * .clearReturning() - * .execute() - * ``` - * - * The generated SQL(PostgreSQL): - * - * ```sql - * delete from "pet" where "name" = "Max" - * ``` - */ - clearReturning() { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithoutReturning(__privateGet(this, _props8).queryNode) - }); - } - /** - * Clears the `limit` clause from the query. - * - * ### Examples - * - * ```ts - * await db.deleteFrom('pet') - * .returningAll() - * .where('name', '=', 'Max') - * .limit(5) - * .clearLimit() - * .execute() - * ``` - * - * The generated SQL(PostgreSQL): - * - * ```sql - * delete from "pet" where "name" = "Max" returning * - * ``` - */ - clearLimit() { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: DeleteQueryNode.cloneWithoutLimit(__privateGet(this, _props8).queryNode) - }); - } - orderBy(...args) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithOrderByItems(__privateGet(this, _props8).queryNode, parseOrderBy(args)) - }); - } - clearOrderBy() { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props8).queryNode) - }); - } - /** - * Adds a limit clause to the query. - * - * A limit clause in a delete query is only supported by some dialects - * like MySQL. - * - * ### Examples - * - * Delete 5 oldest items in a table: - * - * ```ts - * await db - * .deleteFrom('pet') - * .orderBy('created_at') - * .limit(5) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * delete from `pet` order by `created_at` limit ? - * ``` - */ - limit(limit) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: DeleteQueryNode.cloneWithLimit(__privateGet(this, _props8).queryNode, LimitNode.create(parseValueExpression(limit))) - }); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.deleteFrom('person') - * .where('first_name', '=', 'John') - * .modifyEnd(sql`-- This is a comment`) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * delete from `person` - * where `first_name` = "John" -- This is a comment - * ``` - */ - modifyEnd(modifier) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props8).queryNode, modifier.toOperationNode()) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - * - * If you want to conditionally call a method on `this`, see - * the {@link $if} method. - * - * ### Examples - * - * The next example uses a helper function `log` to log a query: - * - * ```ts - * import type { Compilable } from 'kysely' - * - * function log(qb: T): T { - * console.log(qb.compile()) - * return qb - * } - * - * await db.deleteFrom('person') - * .$call(log) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - /** - * Call `func(this)` if `condition` is true. - * - * This method is especially handy with optional selects. Any `returning` or `returningAll` - * method calls add columns as optional fields to the output type when called inside - * the `func` callback. This is because we can't know if those selections were actually - * made before running the code. - * - * You can also call any other methods inside the callback. - * - * ### Examples - * - * ```ts - * async function deletePerson(id: number, returnLastName: boolean) { - * return await db - * .deleteFrom('person') - * .where('id', '=', id) - * .returning(['id', 'first_name']) - * .$if(returnLastName, (qb) => qb.returning('last_name')) - * .executeTakeFirstOrThrow() - * } - * ``` - * - * Any selections added inside the `if` callback will be added as optional fields to the - * output type since we can't know if the selections were actually made before running - * the code. In the example above the return type of the `deletePerson` function is: - * - * ```ts - * Promise<{ - * id: number - * first_name: string - * last_name?: string - * }> - * ``` - */ - $if(condition, func) { - if (condition) { - return func(this); - } - return new _a12({ - ...__privateGet(this, _props8) - }); - } - /** - * Change the output type of the query. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `DeleteQueryBuilder` with a new output type. - */ - $castTo() { - return new _a12(__privateGet(this, _props8)); - } - /** - * Narrows (parts of) the output type of the query. - * - * Kysely tries to be as type-safe as possible, but in some cases we have to make - * compromises for better maintainability and compilation performance. At present, - * Kysely doesn't narrow the output type of the query when using {@link where} and {@link returning} or {@link returningAll}. - * - * This utility method is very useful for these situations, as it removes unncessary - * runtime assertion/guard code. Its input type is limited to the output type - * of the query, so you can't add a column that doesn't exist, or change a column's - * type to something that doesn't exist in its union type. - * - * ### Examples - * - * Turn this code: - * - * ```ts - * import type { Person } from 'type-editor' // imaginary module - * - * const person = await db.deleteFrom('person') - * .where('id', '=', 3) - * .where('nullable_column', 'is not', null) - * .returningAll() - * .executeTakeFirstOrThrow() - * - * if (isWithNoNullValue(person)) { - * functionThatExpectsPersonWithNonNullValue(person) - * } - * - * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { - * return person.nullable_column != null - * } - * ``` - * - * Into this: - * - * ```ts - * import type { NotNull } from 'kysely' - * - * const person = await db.deleteFrom('person') - * .where('id', '=', 3) - * .where('nullable_column', 'is not', null) - * .returningAll() - * .$narrowType<{ nullable_column: NotNull }>() - * .executeTakeFirstOrThrow() - * - * functionThatExpectsPersonWithNonNullValue(person) - * ``` - */ - $narrowType() { - return new _a12(__privateGet(this, _props8)); - } - /** - * Asserts that query's output row type equals the given type `T`. - * - * This method can be used to simplify excessively complex types to make TypeScript happy - * and much faster. - * - * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much - * for TypeScript and you get errors like this: - * - * ``` - * error TS2589: Type instantiation is excessively deep and possibly infinite. - * ``` - * - * In these case you can often use this method to help TypeScript a little bit. When you use this - * method to assert the output type of a query, Kysely can drop the complex output type that - * consists of multiple nested helper types and replace it with the simple asserted type. - * - * Using this method doesn't reduce type safety at all. You have to pass in a type that is - * structurally equal to the current type. - * - * ### Examples - * - * ```ts - * import type { Species } from 'type-editor' // imaginary module - * - * async function deletePersonAndPets(personId: number) { - * return await db - * .with('deleted_person', (qb) => qb - * .deleteFrom('person') - * .where('id', '=', personId) - * .returning('first_name') - * .$assertType<{ first_name: string }>() - * ) - * .with('deleted_pets', (qb) => qb - * .deleteFrom('pet') - * .where('owner_id', '=', personId) - * .returning(['name as pet_name', 'species']) - * .$assertType<{ pet_name: string, species: Species }>() - * ) - * .selectFrom(['deleted_person', 'deleted_pets']) - * .selectAll() - * .execute() - * } - * ``` - */ - $assertType() { - return new _a12(__privateGet(this, _props8)); - } - /** - * Returns a copy of this DeleteQueryBuilder instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _a12({ - ...__privateGet(this, _props8), - executor: __privateGet(this, _props8).executor.withPlugin(plugin) - }); - } - toOperationNode() { - return __privateGet(this, _props8).executor.transformQuery(__privateGet(this, _props8).queryNode, __privateGet(this, _props8).queryId); - } - compile() { - return __privateGet(this, _props8).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props8).queryId); - } - /** - * Executes the query and returns an array of rows. - * - * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. - */ - async execute() { - const compiledQuery = this.compile(); - const result = await __privateGet(this, _props8).executor.executeQuery(compiledQuery); - const { adapter } = __privateGet(this, _props8).executor; - const query = compiledQuery.query; - if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { - return result.rows; - } - return [new DeleteResult(result.numAffectedRows ?? BigInt(0))]; - } - /** - * Executes the query and returns the first result or undefined if - * the query returned no result. - */ - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - /** - * Executes the query and returns the first result or throws if - * the query returned no result. - * - * By default an instance of {@link NoResultError} is thrown, but you can - * provide a custom error class, or callback as the only argument to throw a different - * error. - */ - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error49; - } - return result; - } - async *stream(chunkSize = 100) { - const compiledQuery = this.compile(); - const stream = __privateGet(this, _props8).executor.stream(compiledQuery, chunkSize); - for await (const item of stream) { - yield* item.rows; - } - } - async explain(format, options) { - const builder = new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithExplain(__privateGet(this, _props8).queryNode, format, options) - }); - return await builder.execute(); - } - }; - _props8 = new WeakMap(); - _DeleteQueryBuilder_instances = new WeakSet(); - join_fn = function(joinType, args) { - return new _a12({ - ...__privateGet(this, _props8), - queryNode: QueryNode.cloneWithJoin(__privateGet(this, _props8).queryNode, parseJoin(joinType, args)) - }); - }; - _a12 = DeleteQueryBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js -var UpdateResult; -var init_update_result = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js"() { - UpdateResult = class { - constructor(numUpdatedRows, numChangedRows) { - /** - * The number of rows the update query updated (even if not changed). - */ - __publicField(this, "numUpdatedRows"); - /** - * The number of rows the update query changed. - * - * This is **optional** and only supported in dialects such as MySQL. - * You would probably use {@link numUpdatedRows} in most cases. - */ - __publicField(this, "numChangedRows"); - this.numUpdatedRows = numUpdatedRows; - this.numChangedRows = numChangedRows; - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js -var _a13, _props9, _UpdateQueryBuilder_instances, join_fn2, UpdateQueryBuilder; -var init_update_query_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js"() { - init_join_parser(); - init_table_parser(); - init_select_parser(); - init_query_node(); - init_update_query_node(); - init_update_set_parser(); - init_object_utils(); - init_update_result(); - init_no_result_error(); - init_binary_operation_parser(); - init_value_parser(); - init_limit_node(); - init_top_parser(); - init_order_by_parser(); - UpdateQueryBuilder = class { - constructor(props) { - __privateAdd(this, _UpdateQueryBuilder_instances); - __privateAdd(this, _props9); - __privateSet(this, _props9, freeze(props)); - } - where(...args) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props9).queryNode, parseValueBinaryOperationOrExpression(args)) - }); - } - whereRef(lhs, op, rhs) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props9).queryNode, parseReferentialBinaryOperation(lhs, op, rhs)) - }); - } - clearWhere() { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithoutWhere(__privateGet(this, _props9).queryNode) - }); - } - /** - * Changes an `update` query into a `update top` query. - * - * `top` clause is only supported by some dialects like MS SQL Server. - * - * ### Examples - * - * Update the first row: - * - * ```ts - * await db.updateTable('person') - * .top(1) - * .set({ first_name: 'Foo' }) - * .where('age', '>', 18) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * update top(1) "person" set "first_name" = @1 where "age" > @2 - * ``` - * - * Update the 50% first rows: - * - * ```ts - * await db.updateTable('person') - * .top(50, 'percent') - * .set({ first_name: 'Foo' }) - * .where('age', '>', 18) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * update top(50) percent "person" set "first_name" = @1 where "age" > @2 - * ``` - */ - top(expression, modifiers) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithTop(__privateGet(this, _props9).queryNode, parseTop(expression, modifiers)) - }); - } - from(from) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: UpdateQueryNode.cloneWithFromItems(__privateGet(this, _props9).queryNode, parseTableExpressionOrList(from)) - }); - } - innerJoin(...args) { - return __privateMethod(this, _UpdateQueryBuilder_instances, join_fn2).call(this, "InnerJoin", args); - } - leftJoin(...args) { - return __privateMethod(this, _UpdateQueryBuilder_instances, join_fn2).call(this, "LeftJoin", args); - } - rightJoin(...args) { - return __privateMethod(this, _UpdateQueryBuilder_instances, join_fn2).call(this, "RightJoin", args); - } - fullJoin(...args) { - return __privateMethod(this, _UpdateQueryBuilder_instances, join_fn2).call(this, "FullJoin", args); - } - orderBy(...args) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithOrderByItems(__privateGet(this, _props9).queryNode, parseOrderBy(args)) - }); - } - clearOrderBy() { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props9).queryNode) - }); - } - /** - * Adds a limit clause to the update query for supported databases, such as MySQL. - * - * ### Examples - * - * Update the first 2 rows in the 'person' table: - * - * ```ts - * await db - * .updateTable('person') - * .set({ first_name: 'Foo' }) - * .limit(2) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * update `person` set `first_name` = ? limit ? - * ``` - */ - limit(limit) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: UpdateQueryNode.cloneWithLimit(__privateGet(this, _props9).queryNode, LimitNode.create(parseValueExpression(limit))) - }); - } - set(...args) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: UpdateQueryNode.cloneWithUpdates(__privateGet(this, _props9).queryNode, parseUpdate(...args)) - }); - } - returning(selection) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props9).queryNode, parseSelectArg(selection)) - }); - } - returningAll(table) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props9).queryNode, parseSelectAll(table)) - }); - } - output(args) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props9).queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props9).queryNode, parseSelectAll(table)) - }); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.updateTable('person') - * .set({ age: 39 }) - * .where('first_name', '=', 'John') - * .modifyEnd(sql.raw('-- This is a comment')) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * update `person` - * set `age` = 39 - * where `first_name` = "John" -- This is a comment - * ``` - */ - modifyEnd(modifier) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props9).queryNode, modifier.toOperationNode()) - }); - } - /** - * Clears all `returning` clauses from the query. - * - * ### Examples - * - * ```ts - * db.updateTable('person') - * .returningAll() - * .set({ age: 39 }) - * .where('first_name', '=', 'John') - * .clearReturning() - * ``` - * - * The generated SQL(PostgreSQL): - * - * ```sql - * update "person" set "age" = 39 where "first_name" = "John" - * ``` - */ - clearReturning() { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithoutReturning(__privateGet(this, _props9).queryNode) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - * - * If you want to conditionally call a method on `this`, see - * the {@link $if} method. - * - * ### Examples - * - * The next example uses a helper function `log` to log a query: - * - * ```ts - * import type { Compilable } from 'kysely' - * import type { PersonUpdate } from 'type-editor' // imaginary module - * - * function log(qb: T): T { - * console.log(qb.compile()) - * return qb - * } - * - * const values = { - * first_name: 'John', - * } satisfies PersonUpdate - * - * db.updateTable('person') - * .set(values) - * .$call(log) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - /** - * Call `func(this)` if `condition` is true. - * - * This method is especially handy with optional selects. Any `returning` or `returningAll` - * method calls add columns as optional fields to the output type when called inside - * the `func` callback. This is because we can't know if those selections were actually - * made before running the code. - * - * You can also call any other methods inside the callback. - * - * ### Examples - * - * ```ts - * import type { PersonUpdate } from 'type-editor' // imaginary module - * - * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) { - * return await db - * .updateTable('person') - * .set(updates) - * .where('id', '=', id) - * .returning(['id', 'first_name']) - * .$if(returnLastName, (qb) => qb.returning('last_name')) - * .executeTakeFirstOrThrow() - * } - * ``` - * - * Any selections added inside the `if` callback will be added as optional fields to the - * output type since we can't know if the selections were actually made before running - * the code. In the example above the return type of the `updatePerson` function is: - * - * ```ts - * Promise<{ - * id: number - * first_name: string - * last_name?: string - * }> - * ``` - */ - $if(condition, func) { - if (condition) { - return func(this); - } - return new _a13({ - ...__privateGet(this, _props9) - }); - } - /** - * Change the output type of the query. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `UpdateQueryBuilder` with a new output type. - */ - $castTo() { - return new _a13(__privateGet(this, _props9)); - } - /** - * Narrows (parts of) the output type of the query. - * - * Kysely tries to be as type-safe as possible, but in some cases we have to make - * compromises for better maintainability and compilation performance. At present, - * Kysely doesn't narrow the output type of the query based on {@link set} input - * when using {@link where} and/or {@link returning} or {@link returningAll}. - * - * This utility method is very useful for these situations, as it removes unncessary - * runtime assertion/guard code. Its input type is limited to the output type - * of the query, so you can't add a column that doesn't exist, or change a column's - * type to something that doesn't exist in its union type. - * - * ### Examples - * - * Turn this code: - * - * ```ts - * import type { Person } from 'type-editor' // imaginary module - * - * const id = 1 - * const now = new Date().toISOString() - * - * const person = await db.updateTable('person') - * .set({ deleted_at: now }) - * .where('id', '=', id) - * .where('nullable_column', 'is not', null) - * .returningAll() - * .executeTakeFirstOrThrow() - * - * if (isWithNoNullValue(person)) { - * functionThatExpectsPersonWithNonNullValue(person) - * } - * - * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { - * return person.nullable_column != null - * } - * ``` - * - * Into this: - * - * ```ts - * import type { NotNull } from 'kysely' - * - * const id = 1 - * const now = new Date().toISOString() - * - * const person = await db.updateTable('person') - * .set({ deleted_at: now }) - * .where('id', '=', id) - * .where('nullable_column', 'is not', null) - * .returningAll() - * .$narrowType<{ deleted_at: Date; nullable_column: NotNull }>() - * .executeTakeFirstOrThrow() - * - * functionThatExpectsPersonWithNonNullValue(person) - * ``` - */ - $narrowType() { - return new _a13(__privateGet(this, _props9)); - } - /** - * Asserts that query's output row type equals the given type `T`. - * - * This method can be used to simplify excessively complex types to make TypeScript happy - * and much faster. - * - * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much - * for TypeScript and you get errors like this: - * - * ``` - * error TS2589: Type instantiation is excessively deep and possibly infinite. - * ``` - * - * In these case you can often use this method to help TypeScript a little bit. When you use this - * method to assert the output type of a query, Kysely can drop the complex output type that - * consists of multiple nested helper types and replace it with the simple asserted type. - * - * Using this method doesn't reduce type safety at all. You have to pass in a type that is - * structurally equal to the current type. - * - * ### Examples - * - * ```ts - * import type { PersonUpdate, PetUpdate, Species } from 'type-editor' // imaginary module - * - * const person = { - * id: 1, - * gender: 'other', - * } satisfies PersonUpdate - * - * const pet = { - * name: 'Fluffy', - * } satisfies PetUpdate - * - * const result = await db - * .with('updated_person', (qb) => qb - * .updateTable('person') - * .set(person) - * .where('id', '=', person.id) - * .returning('first_name') - * .$assertType<{ first_name: string }>() - * ) - * .with('updated_pet', (qb) => qb - * .updateTable('pet') - * .set(pet) - * .where('owner_id', '=', person.id) - * .returning(['name as pet_name', 'species']) - * .$assertType<{ pet_name: string, species: Species }>() - * ) - * .selectFrom(['updated_person', 'updated_pet']) - * .selectAll() - * .executeTakeFirstOrThrow() - * ``` - */ - $assertType() { - return new _a13(__privateGet(this, _props9)); - } - /** - * Returns a copy of this UpdateQueryBuilder instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _a13({ - ...__privateGet(this, _props9), - executor: __privateGet(this, _props9).executor.withPlugin(plugin) - }); - } - toOperationNode() { - return __privateGet(this, _props9).executor.transformQuery(__privateGet(this, _props9).queryNode, __privateGet(this, _props9).queryId); - } - compile() { - return __privateGet(this, _props9).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props9).queryId); - } - /** - * Executes the query and returns an array of rows. - * - * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. - */ - async execute() { - const compiledQuery = this.compile(); - const result = await __privateGet(this, _props9).executor.executeQuery(compiledQuery); - const { adapter } = __privateGet(this, _props9).executor; - const query = compiledQuery.query; - if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { - return result.rows; - } - return [ - new UpdateResult(result.numAffectedRows ?? BigInt(0), result.numChangedRows) - ]; - } - /** - * Executes the query and returns the first result or undefined if - * the query returned no result. - */ - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - /** - * Executes the query and returns the first result or throws if - * the query returned no result. - * - * By default an instance of {@link NoResultError} is thrown, but you can - * provide a custom error class, or callback as the only argument to throw a different - * error. - */ - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error49; - } - return result; - } - async *stream(chunkSize = 100) { - const compiledQuery = this.compile(); - const stream = __privateGet(this, _props9).executor.stream(compiledQuery, chunkSize); - for await (const item of stream) { - yield* item.rows; - } - } - async explain(format, options) { - const builder = new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithExplain(__privateGet(this, _props9).queryNode, format, options) - }); - return await builder.execute(); - } - }; - _props9 = new WeakMap(); - _UpdateQueryBuilder_instances = new WeakSet(); - join_fn2 = function(joinType, args) { - return new _a13({ - ...__privateGet(this, _props9), - queryNode: QueryNode.cloneWithJoin(__privateGet(this, _props9).queryNode, parseJoin(joinType, args)) - }); - }; - _a13 = UpdateQueryBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js -var CommonTableExpressionNameNode; -var init_common_table_expression_name_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js"() { - init_object_utils(); - init_column_node(); - init_table_node(); - CommonTableExpressionNameNode = freeze({ - is(node) { - return node.kind === "CommonTableExpressionNameNode"; - }, - create(tableName, columnNames) { - return freeze({ - kind: "CommonTableExpressionNameNode", - table: TableNode.create(tableName), - columns: columnNames ? freeze(columnNames.map(ColumnNode.create)) : void 0 - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js -var CommonTableExpressionNode; -var init_common_table_expression_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js"() { - init_object_utils(); - CommonTableExpressionNode = freeze({ - is(node) { - return node.kind === "CommonTableExpressionNode"; - }, - create(name, expression) { - return freeze({ - kind: "CommonTableExpressionNode", - name, - expression - }); - }, - cloneWith(node, props) { - return freeze({ - ...node, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js -var _props10, _CTEBuilder, CTEBuilder; -var init_cte_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js"() { - init_common_table_expression_node(); - init_object_utils(); - _CTEBuilder = class _CTEBuilder { - constructor(props) { - __privateAdd(this, _props10); - __privateSet(this, _props10, freeze(props)); - } - /** - * Makes the common table expression materialized. - */ - materialized() { - return new _CTEBuilder({ - ...__privateGet(this, _props10), - node: CommonTableExpressionNode.cloneWith(__privateGet(this, _props10).node, { - materialized: true - }) - }); - } - /** - * Makes the common table expression not materialized. - */ - notMaterialized() { - return new _CTEBuilder({ - ...__privateGet(this, _props10), - node: CommonTableExpressionNode.cloneWith(__privateGet(this, _props10).node, { - materialized: false - }) - }); - } - toOperationNode() { - return __privateGet(this, _props10).node; - } - }; - _props10 = new WeakMap(); - CTEBuilder = _CTEBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js -function parseCommonTableExpression(nameOrBuilderCallback, expression) { - const expressionNode = expression(createQueryCreator()).toOperationNode(); - if (isFunction3(nameOrBuilderCallback)) { - return nameOrBuilderCallback(cteBuilderFactory(expressionNode)).toOperationNode(); - } - return CommonTableExpressionNode.create(parseCommonTableExpressionName(nameOrBuilderCallback), expressionNode); -} -function cteBuilderFactory(expressionNode) { - return (name) => { - return new CTEBuilder({ - node: CommonTableExpressionNode.create(parseCommonTableExpressionName(name), expressionNode) - }); - }; -} -function parseCommonTableExpressionName(name) { - if (name.includes("(")) { - const parts = name.split(/[\(\)]/); - const table = parts[0]; - const columns = parts[1].split(",").map((it) => it.trim()); - return CommonTableExpressionNameNode.create(table, columns); - } else { - return CommonTableExpressionNameNode.create(name); - } -} -var init_with_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js"() { - init_common_table_expression_name_node(); - init_parse_utils(); - init_object_utils(); - init_cte_builder(); - init_common_table_expression_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js -var WithNode; -var init_with_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js"() { - init_object_utils(); - WithNode = freeze({ - is(node) { - return node.kind === "WithNode"; - }, - create(expression, params) { - return freeze({ - kind: "WithNode", - expressions: freeze([expression]), - ...params - }); - }, - cloneWithExpression(withNode, expression) { - return freeze({ - ...withNode, - expressions: freeze([...withNode.expressions, expression]) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js -function randomString2(length) { - let chars = ""; - for (let i = 0; i < length; ++i) { - chars += randomChar(); - } - return chars; -} -function randomChar() { - return CHARS[~~(Math.random() * CHARS.length)]; -} -var CHARS; -var init_random_string = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js"() { - CHARS = [ - "A", - "B", - "C", - "D", - "E", - "F", - "G", - "H", - "I", - "J", - "K", - "L", - "M", - "N", - "O", - "P", - "Q", - "R", - "S", - "T", - "U", - "V", - "W", - "X", - "Y", - "Z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9" - ]; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js -function createQueryId() { - return new LazyQueryId(); -} -var _queryId, LazyQueryId; -var init_query_id = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js"() { - init_random_string(); - LazyQueryId = class { - constructor() { - __privateAdd(this, _queryId); - } - get queryId() { - if (__privateGet(this, _queryId) === void 0) { - __privateSet(this, _queryId, randomString2(8)); - } - return __privateGet(this, _queryId); - } - }; - _queryId = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js -function requireAllProps(obj) { - return obj; -} -var init_require_all_props = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js -var _transformers, OperationNodeTransformer; -var init_operation_node_transformer = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js"() { - init_object_utils(); - init_require_all_props(); - OperationNodeTransformer = class { - constructor() { - __publicField(this, "nodeStack", []); - __privateAdd(this, _transformers, freeze({ - AliasNode: this.transformAlias.bind(this), - ColumnNode: this.transformColumn.bind(this), - IdentifierNode: this.transformIdentifier.bind(this), - SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this), - RawNode: this.transformRaw.bind(this), - ReferenceNode: this.transformReference.bind(this), - SelectQueryNode: this.transformSelectQuery.bind(this), - SelectionNode: this.transformSelection.bind(this), - TableNode: this.transformTable.bind(this), - FromNode: this.transformFrom.bind(this), - SelectAllNode: this.transformSelectAll.bind(this), - AndNode: this.transformAnd.bind(this), - OrNode: this.transformOr.bind(this), - ValueNode: this.transformValue.bind(this), - ValueListNode: this.transformValueList.bind(this), - PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this), - ParensNode: this.transformParens.bind(this), - JoinNode: this.transformJoin.bind(this), - OperatorNode: this.transformOperator.bind(this), - WhereNode: this.transformWhere.bind(this), - InsertQueryNode: this.transformInsertQuery.bind(this), - DeleteQueryNode: this.transformDeleteQuery.bind(this), - ReturningNode: this.transformReturning.bind(this), - CreateTableNode: this.transformCreateTable.bind(this), - AddColumnNode: this.transformAddColumn.bind(this), - ColumnDefinitionNode: this.transformColumnDefinition.bind(this), - DropTableNode: this.transformDropTable.bind(this), - DataTypeNode: this.transformDataType.bind(this), - OrderByNode: this.transformOrderBy.bind(this), - OrderByItemNode: this.transformOrderByItem.bind(this), - GroupByNode: this.transformGroupBy.bind(this), - GroupByItemNode: this.transformGroupByItem.bind(this), - UpdateQueryNode: this.transformUpdateQuery.bind(this), - ColumnUpdateNode: this.transformColumnUpdate.bind(this), - LimitNode: this.transformLimit.bind(this), - OffsetNode: this.transformOffset.bind(this), - OnConflictNode: this.transformOnConflict.bind(this), - OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this), - CreateIndexNode: this.transformCreateIndex.bind(this), - DropIndexNode: this.transformDropIndex.bind(this), - ListNode: this.transformList.bind(this), - PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this), - UniqueConstraintNode: this.transformUniqueConstraint.bind(this), - ReferencesNode: this.transformReferences.bind(this), - CheckConstraintNode: this.transformCheckConstraint.bind(this), - WithNode: this.transformWith.bind(this), - CommonTableExpressionNode: this.transformCommonTableExpression.bind(this), - CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this), - HavingNode: this.transformHaving.bind(this), - CreateSchemaNode: this.transformCreateSchema.bind(this), - DropSchemaNode: this.transformDropSchema.bind(this), - AlterTableNode: this.transformAlterTable.bind(this), - DropColumnNode: this.transformDropColumn.bind(this), - RenameColumnNode: this.transformRenameColumn.bind(this), - AlterColumnNode: this.transformAlterColumn.bind(this), - ModifyColumnNode: this.transformModifyColumn.bind(this), - AddConstraintNode: this.transformAddConstraint.bind(this), - DropConstraintNode: this.transformDropConstraint.bind(this), - RenameConstraintNode: this.transformRenameConstraint.bind(this), - ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this), - CreateViewNode: this.transformCreateView.bind(this), - RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this), - DropViewNode: this.transformDropView.bind(this), - GeneratedNode: this.transformGenerated.bind(this), - DefaultValueNode: this.transformDefaultValue.bind(this), - OnNode: this.transformOn.bind(this), - ValuesNode: this.transformValues.bind(this), - SelectModifierNode: this.transformSelectModifier.bind(this), - CreateTypeNode: this.transformCreateType.bind(this), - DropTypeNode: this.transformDropType.bind(this), - ExplainNode: this.transformExplain.bind(this), - DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this), - AggregateFunctionNode: this.transformAggregateFunction.bind(this), - OverNode: this.transformOver.bind(this), - PartitionByNode: this.transformPartitionBy.bind(this), - PartitionByItemNode: this.transformPartitionByItem.bind(this), - SetOperationNode: this.transformSetOperation.bind(this), - BinaryOperationNode: this.transformBinaryOperation.bind(this), - UnaryOperationNode: this.transformUnaryOperation.bind(this), - UsingNode: this.transformUsing.bind(this), - FunctionNode: this.transformFunction.bind(this), - CaseNode: this.transformCase.bind(this), - WhenNode: this.transformWhen.bind(this), - JSONReferenceNode: this.transformJSONReference.bind(this), - JSONPathNode: this.transformJSONPath.bind(this), - JSONPathLegNode: this.transformJSONPathLeg.bind(this), - JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this), - TupleNode: this.transformTuple.bind(this), - MergeQueryNode: this.transformMergeQuery.bind(this), - MatchedNode: this.transformMatched.bind(this), - AddIndexNode: this.transformAddIndex.bind(this), - CastNode: this.transformCast.bind(this), - FetchNode: this.transformFetch.bind(this), - TopNode: this.transformTop.bind(this), - OutputNode: this.transformOutput.bind(this), - OrActionNode: this.transformOrAction.bind(this), - CollateNode: this.transformCollate.bind(this) - })); - } - transformNode(node, queryId) { - if (!node) { - return node; - } - this.nodeStack.push(node); - const out = this.transformNodeImpl(node, queryId); - this.nodeStack.pop(); - return freeze(out); - } - transformNodeImpl(node, queryId) { - return __privateGet(this, _transformers)[node.kind](node, queryId); - } - transformNodeList(list, queryId) { - if (!list) { - return list; - } - return freeze(list.map((node) => this.transformNode(node, queryId))); - } - transformSelectQuery(node, queryId) { - return requireAllProps({ - kind: "SelectQueryNode", - from: this.transformNode(node.from, queryId), - selections: this.transformNodeList(node.selections, queryId), - distinctOn: this.transformNodeList(node.distinctOn, queryId), - joins: this.transformNodeList(node.joins, queryId), - groupBy: this.transformNode(node.groupBy, queryId), - orderBy: this.transformNode(node.orderBy, queryId), - where: this.transformNode(node.where, queryId), - frontModifiers: this.transformNodeList(node.frontModifiers, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - limit: this.transformNode(node.limit, queryId), - offset: this.transformNode(node.offset, queryId), - with: this.transformNode(node.with, queryId), - having: this.transformNode(node.having, queryId), - explain: this.transformNode(node.explain, queryId), - setOperations: this.transformNodeList(node.setOperations, queryId), - fetch: this.transformNode(node.fetch, queryId), - top: this.transformNode(node.top, queryId) - }); - } - transformSelection(node, queryId) { - return requireAllProps({ - kind: "SelectionNode", - selection: this.transformNode(node.selection, queryId) - }); - } - transformColumn(node, queryId) { - return requireAllProps({ - kind: "ColumnNode", - column: this.transformNode(node.column, queryId) - }); - } - transformAlias(node, queryId) { - return requireAllProps({ - kind: "AliasNode", - node: this.transformNode(node.node, queryId), - alias: this.transformNode(node.alias, queryId) - }); - } - transformTable(node, queryId) { - return requireAllProps({ - kind: "TableNode", - table: this.transformNode(node.table, queryId) - }); - } - transformFrom(node, queryId) { - return requireAllProps({ - kind: "FromNode", - froms: this.transformNodeList(node.froms, queryId) - }); - } - transformReference(node, queryId) { - return requireAllProps({ - kind: "ReferenceNode", - column: this.transformNode(node.column, queryId), - table: this.transformNode(node.table, queryId) - }); - } - transformAnd(node, queryId) { - return requireAllProps({ - kind: "AndNode", - left: this.transformNode(node.left, queryId), - right: this.transformNode(node.right, queryId) - }); - } - transformOr(node, queryId) { - return requireAllProps({ - kind: "OrNode", - left: this.transformNode(node.left, queryId), - right: this.transformNode(node.right, queryId) - }); - } - transformValueList(node, queryId) { - return requireAllProps({ - kind: "ValueListNode", - values: this.transformNodeList(node.values, queryId) - }); - } - transformParens(node, queryId) { - return requireAllProps({ - kind: "ParensNode", - node: this.transformNode(node.node, queryId) - }); - } - transformJoin(node, queryId) { - return requireAllProps({ - kind: "JoinNode", - joinType: node.joinType, - table: this.transformNode(node.table, queryId), - on: this.transformNode(node.on, queryId) - }); - } - transformRaw(node, queryId) { - return requireAllProps({ - kind: "RawNode", - sqlFragments: freeze([...node.sqlFragments]), - parameters: this.transformNodeList(node.parameters, queryId) - }); - } - transformWhere(node, queryId) { - return requireAllProps({ - kind: "WhereNode", - where: this.transformNode(node.where, queryId) - }); - } - transformInsertQuery(node, queryId) { - return requireAllProps({ - kind: "InsertQueryNode", - into: this.transformNode(node.into, queryId), - columns: this.transformNodeList(node.columns, queryId), - values: this.transformNode(node.values, queryId), - returning: this.transformNode(node.returning, queryId), - onConflict: this.transformNode(node.onConflict, queryId), - onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - with: this.transformNode(node.with, queryId), - ignore: node.ignore, - orAction: this.transformNode(node.orAction, queryId), - replace: node.replace, - explain: this.transformNode(node.explain, queryId), - defaultValues: node.defaultValues, - top: this.transformNode(node.top, queryId), - output: this.transformNode(node.output, queryId) - }); - } - transformValues(node, queryId) { - return requireAllProps({ - kind: "ValuesNode", - values: this.transformNodeList(node.values, queryId) - }); - } - transformDeleteQuery(node, queryId) { - return requireAllProps({ - kind: "DeleteQueryNode", - from: this.transformNode(node.from, queryId), - using: this.transformNode(node.using, queryId), - joins: this.transformNodeList(node.joins, queryId), - where: this.transformNode(node.where, queryId), - returning: this.transformNode(node.returning, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - with: this.transformNode(node.with, queryId), - orderBy: this.transformNode(node.orderBy, queryId), - limit: this.transformNode(node.limit, queryId), - explain: this.transformNode(node.explain, queryId), - top: this.transformNode(node.top, queryId), - output: this.transformNode(node.output, queryId) - }); - } - transformReturning(node, queryId) { - return requireAllProps({ - kind: "ReturningNode", - selections: this.transformNodeList(node.selections, queryId) - }); - } - transformCreateTable(node, queryId) { - return requireAllProps({ - kind: "CreateTableNode", - table: this.transformNode(node.table, queryId), - columns: this.transformNodeList(node.columns, queryId), - constraints: this.transformNodeList(node.constraints, queryId), - temporary: node.temporary, - ifNotExists: node.ifNotExists, - onCommit: node.onCommit, - frontModifiers: this.transformNodeList(node.frontModifiers, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - selectQuery: this.transformNode(node.selectQuery, queryId) - }); - } - transformColumnDefinition(node, queryId) { - return requireAllProps({ - kind: "ColumnDefinitionNode", - column: this.transformNode(node.column, queryId), - dataType: this.transformNode(node.dataType, queryId), - references: this.transformNode(node.references, queryId), - primaryKey: node.primaryKey, - autoIncrement: node.autoIncrement, - unique: node.unique, - notNull: node.notNull, - unsigned: node.unsigned, - defaultTo: this.transformNode(node.defaultTo, queryId), - check: this.transformNode(node.check, queryId), - generated: this.transformNode(node.generated, queryId), - frontModifiers: this.transformNodeList(node.frontModifiers, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - nullsNotDistinct: node.nullsNotDistinct, - identity: node.identity, - ifNotExists: node.ifNotExists - }); - } - transformAddColumn(node, queryId) { - return requireAllProps({ - kind: "AddColumnNode", - column: this.transformNode(node.column, queryId) - }); - } - transformDropTable(node, queryId) { - return requireAllProps({ - kind: "DropTableNode", - table: this.transformNode(node.table, queryId), - ifExists: node.ifExists, - cascade: node.cascade - }); - } - transformOrderBy(node, queryId) { - return requireAllProps({ - kind: "OrderByNode", - items: this.transformNodeList(node.items, queryId) - }); - } - transformOrderByItem(node, queryId) { - return requireAllProps({ - kind: "OrderByItemNode", - orderBy: this.transformNode(node.orderBy, queryId), - direction: this.transformNode(node.direction, queryId), - collation: this.transformNode(node.collation, queryId), - nulls: node.nulls - }); - } - transformGroupBy(node, queryId) { - return requireAllProps({ - kind: "GroupByNode", - items: this.transformNodeList(node.items, queryId) - }); - } - transformGroupByItem(node, queryId) { - return requireAllProps({ - kind: "GroupByItemNode", - groupBy: this.transformNode(node.groupBy, queryId) - }); - } - transformUpdateQuery(node, queryId) { - return requireAllProps({ - kind: "UpdateQueryNode", - table: this.transformNode(node.table, queryId), - from: this.transformNode(node.from, queryId), - joins: this.transformNodeList(node.joins, queryId), - where: this.transformNode(node.where, queryId), - updates: this.transformNodeList(node.updates, queryId), - returning: this.transformNode(node.returning, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - with: this.transformNode(node.with, queryId), - explain: this.transformNode(node.explain, queryId), - limit: this.transformNode(node.limit, queryId), - top: this.transformNode(node.top, queryId), - output: this.transformNode(node.output, queryId), - orderBy: this.transformNode(node.orderBy, queryId) - }); - } - transformColumnUpdate(node, queryId) { - return requireAllProps({ - kind: "ColumnUpdateNode", - column: this.transformNode(node.column, queryId), - value: this.transformNode(node.value, queryId) - }); - } - transformLimit(node, queryId) { - return requireAllProps({ - kind: "LimitNode", - limit: this.transformNode(node.limit, queryId) - }); - } - transformOffset(node, queryId) { - return requireAllProps({ - kind: "OffsetNode", - offset: this.transformNode(node.offset, queryId) - }); - } - transformOnConflict(node, queryId) { - return requireAllProps({ - kind: "OnConflictNode", - columns: this.transformNodeList(node.columns, queryId), - constraint: this.transformNode(node.constraint, queryId), - indexExpression: this.transformNode(node.indexExpression, queryId), - indexWhere: this.transformNode(node.indexWhere, queryId), - updates: this.transformNodeList(node.updates, queryId), - updateWhere: this.transformNode(node.updateWhere, queryId), - doNothing: node.doNothing - }); - } - transformOnDuplicateKey(node, queryId) { - return requireAllProps({ - kind: "OnDuplicateKeyNode", - updates: this.transformNodeList(node.updates, queryId) - }); - } - transformCreateIndex(node, queryId) { - return requireAllProps({ - kind: "CreateIndexNode", - name: this.transformNode(node.name, queryId), - table: this.transformNode(node.table, queryId), - columns: this.transformNodeList(node.columns, queryId), - unique: node.unique, - using: this.transformNode(node.using, queryId), - ifNotExists: node.ifNotExists, - where: this.transformNode(node.where, queryId), - nullsNotDistinct: node.nullsNotDistinct - }); - } - transformList(node, queryId) { - return requireAllProps({ - kind: "ListNode", - items: this.transformNodeList(node.items, queryId) - }); - } - transformDropIndex(node, queryId) { - return requireAllProps({ - kind: "DropIndexNode", - name: this.transformNode(node.name, queryId), - table: this.transformNode(node.table, queryId), - ifExists: node.ifExists, - cascade: node.cascade - }); - } - transformPrimaryKeyConstraint(node, queryId) { - return requireAllProps({ - kind: "PrimaryKeyConstraintNode", - columns: this.transformNodeList(node.columns, queryId), - name: this.transformNode(node.name, queryId), - deferrable: node.deferrable, - initiallyDeferred: node.initiallyDeferred - }); - } - transformUniqueConstraint(node, queryId) { - return requireAllProps({ - kind: "UniqueConstraintNode", - columns: this.transformNodeList(node.columns, queryId), - name: this.transformNode(node.name, queryId), - nullsNotDistinct: node.nullsNotDistinct, - deferrable: node.deferrable, - initiallyDeferred: node.initiallyDeferred - }); - } - transformForeignKeyConstraint(node, queryId) { - return requireAllProps({ - kind: "ForeignKeyConstraintNode", - columns: this.transformNodeList(node.columns, queryId), - references: this.transformNode(node.references, queryId), - name: this.transformNode(node.name, queryId), - onDelete: node.onDelete, - onUpdate: node.onUpdate, - deferrable: node.deferrable, - initiallyDeferred: node.initiallyDeferred - }); - } - transformSetOperation(node, queryId) { - return requireAllProps({ - kind: "SetOperationNode", - operator: node.operator, - expression: this.transformNode(node.expression, queryId), - all: node.all - }); - } - transformReferences(node, queryId) { - return requireAllProps({ - kind: "ReferencesNode", - table: this.transformNode(node.table, queryId), - columns: this.transformNodeList(node.columns, queryId), - onDelete: node.onDelete, - onUpdate: node.onUpdate - }); - } - transformCheckConstraint(node, queryId) { - return requireAllProps({ - kind: "CheckConstraintNode", - expression: this.transformNode(node.expression, queryId), - name: this.transformNode(node.name, queryId) - }); - } - transformWith(node, queryId) { - return requireAllProps({ - kind: "WithNode", - expressions: this.transformNodeList(node.expressions, queryId), - recursive: node.recursive - }); - } - transformCommonTableExpression(node, queryId) { - return requireAllProps({ - kind: "CommonTableExpressionNode", - name: this.transformNode(node.name, queryId), - materialized: node.materialized, - expression: this.transformNode(node.expression, queryId) - }); - } - transformCommonTableExpressionName(node, queryId) { - return requireAllProps({ - kind: "CommonTableExpressionNameNode", - table: this.transformNode(node.table, queryId), - columns: this.transformNodeList(node.columns, queryId) - }); - } - transformHaving(node, queryId) { - return requireAllProps({ - kind: "HavingNode", - having: this.transformNode(node.having, queryId) - }); - } - transformCreateSchema(node, queryId) { - return requireAllProps({ - kind: "CreateSchemaNode", - schema: this.transformNode(node.schema, queryId), - ifNotExists: node.ifNotExists - }); - } - transformDropSchema(node, queryId) { - return requireAllProps({ - kind: "DropSchemaNode", - schema: this.transformNode(node.schema, queryId), - ifExists: node.ifExists, - cascade: node.cascade - }); - } - transformAlterTable(node, queryId) { - return requireAllProps({ - kind: "AlterTableNode", - table: this.transformNode(node.table, queryId), - renameTo: this.transformNode(node.renameTo, queryId), - setSchema: this.transformNode(node.setSchema, queryId), - columnAlterations: this.transformNodeList(node.columnAlterations, queryId), - addConstraint: this.transformNode(node.addConstraint, queryId), - dropConstraint: this.transformNode(node.dropConstraint, queryId), - renameConstraint: this.transformNode(node.renameConstraint, queryId), - addIndex: this.transformNode(node.addIndex, queryId), - dropIndex: this.transformNode(node.dropIndex, queryId) - }); - } - transformDropColumn(node, queryId) { - return requireAllProps({ - kind: "DropColumnNode", - column: this.transformNode(node.column, queryId) - }); - } - transformRenameColumn(node, queryId) { - return requireAllProps({ - kind: "RenameColumnNode", - column: this.transformNode(node.column, queryId), - renameTo: this.transformNode(node.renameTo, queryId) - }); - } - transformAlterColumn(node, queryId) { - return requireAllProps({ - kind: "AlterColumnNode", - column: this.transformNode(node.column, queryId), - dataType: this.transformNode(node.dataType, queryId), - dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId), - setDefault: this.transformNode(node.setDefault, queryId), - dropDefault: node.dropDefault, - setNotNull: node.setNotNull, - dropNotNull: node.dropNotNull - }); - } - transformModifyColumn(node, queryId) { - return requireAllProps({ - kind: "ModifyColumnNode", - column: this.transformNode(node.column, queryId) - }); - } - transformAddConstraint(node, queryId) { - return requireAllProps({ - kind: "AddConstraintNode", - constraint: this.transformNode(node.constraint, queryId) - }); - } - transformDropConstraint(node, queryId) { - return requireAllProps({ - kind: "DropConstraintNode", - constraintName: this.transformNode(node.constraintName, queryId), - ifExists: node.ifExists, - modifier: node.modifier - }); - } - transformRenameConstraint(node, queryId) { - return requireAllProps({ - kind: "RenameConstraintNode", - oldName: this.transformNode(node.oldName, queryId), - newName: this.transformNode(node.newName, queryId) - }); - } - transformCreateView(node, queryId) { - return requireAllProps({ - kind: "CreateViewNode", - name: this.transformNode(node.name, queryId), - temporary: node.temporary, - orReplace: node.orReplace, - ifNotExists: node.ifNotExists, - materialized: node.materialized, - columns: this.transformNodeList(node.columns, queryId), - as: this.transformNode(node.as, queryId) - }); - } - transformRefreshMaterializedView(node, queryId) { - return requireAllProps({ - kind: "RefreshMaterializedViewNode", - name: this.transformNode(node.name, queryId), - concurrently: node.concurrently, - withNoData: node.withNoData - }); - } - transformDropView(node, queryId) { - return requireAllProps({ - kind: "DropViewNode", - name: this.transformNode(node.name, queryId), - ifExists: node.ifExists, - materialized: node.materialized, - cascade: node.cascade - }); - } - transformGenerated(node, queryId) { - return requireAllProps({ - kind: "GeneratedNode", - byDefault: node.byDefault, - always: node.always, - identity: node.identity, - stored: node.stored, - expression: this.transformNode(node.expression, queryId) - }); - } - transformDefaultValue(node, queryId) { - return requireAllProps({ - kind: "DefaultValueNode", - defaultValue: this.transformNode(node.defaultValue, queryId) - }); - } - transformOn(node, queryId) { - return requireAllProps({ - kind: "OnNode", - on: this.transformNode(node.on, queryId) - }); - } - transformSelectModifier(node, queryId) { - return requireAllProps({ - kind: "SelectModifierNode", - modifier: node.modifier, - rawModifier: this.transformNode(node.rawModifier, queryId), - of: this.transformNodeList(node.of, queryId) - }); - } - transformCreateType(node, queryId) { - return requireAllProps({ - kind: "CreateTypeNode", - name: this.transformNode(node.name, queryId), - enum: this.transformNode(node.enum, queryId) - }); - } - transformDropType(node, queryId) { - return requireAllProps({ - kind: "DropTypeNode", - name: this.transformNode(node.name, queryId), - ifExists: node.ifExists - }); - } - transformExplain(node, queryId) { - return requireAllProps({ - kind: "ExplainNode", - format: node.format, - options: this.transformNode(node.options, queryId) - }); - } - transformSchemableIdentifier(node, queryId) { - return requireAllProps({ - kind: "SchemableIdentifierNode", - schema: this.transformNode(node.schema, queryId), - identifier: this.transformNode(node.identifier, queryId) - }); - } - transformAggregateFunction(node, queryId) { - return requireAllProps({ - kind: "AggregateFunctionNode", - func: node.func, - aggregated: this.transformNodeList(node.aggregated, queryId), - distinct: node.distinct, - orderBy: this.transformNode(node.orderBy, queryId), - withinGroup: this.transformNode(node.withinGroup, queryId), - filter: this.transformNode(node.filter, queryId), - over: this.transformNode(node.over, queryId) - }); - } - transformOver(node, queryId) { - return requireAllProps({ - kind: "OverNode", - orderBy: this.transformNode(node.orderBy, queryId), - partitionBy: this.transformNode(node.partitionBy, queryId) - }); - } - transformPartitionBy(node, queryId) { - return requireAllProps({ - kind: "PartitionByNode", - items: this.transformNodeList(node.items, queryId) - }); - } - transformPartitionByItem(node, queryId) { - return requireAllProps({ - kind: "PartitionByItemNode", - partitionBy: this.transformNode(node.partitionBy, queryId) - }); - } - transformBinaryOperation(node, queryId) { - return requireAllProps({ - kind: "BinaryOperationNode", - leftOperand: this.transformNode(node.leftOperand, queryId), - operator: this.transformNode(node.operator, queryId), - rightOperand: this.transformNode(node.rightOperand, queryId) - }); - } - transformUnaryOperation(node, queryId) { - return requireAllProps({ - kind: "UnaryOperationNode", - operator: this.transformNode(node.operator, queryId), - operand: this.transformNode(node.operand, queryId) - }); - } - transformUsing(node, queryId) { - return requireAllProps({ - kind: "UsingNode", - tables: this.transformNodeList(node.tables, queryId) - }); - } - transformFunction(node, queryId) { - return requireAllProps({ - kind: "FunctionNode", - func: node.func, - arguments: this.transformNodeList(node.arguments, queryId) - }); - } - transformCase(node, queryId) { - return requireAllProps({ - kind: "CaseNode", - value: this.transformNode(node.value, queryId), - when: this.transformNodeList(node.when, queryId), - else: this.transformNode(node.else, queryId), - isStatement: node.isStatement - }); - } - transformWhen(node, queryId) { - return requireAllProps({ - kind: "WhenNode", - condition: this.transformNode(node.condition, queryId), - result: this.transformNode(node.result, queryId) - }); - } - transformJSONReference(node, queryId) { - return requireAllProps({ - kind: "JSONReferenceNode", - reference: this.transformNode(node.reference, queryId), - traversal: this.transformNode(node.traversal, queryId) - }); - } - transformJSONPath(node, queryId) { - return requireAllProps({ - kind: "JSONPathNode", - inOperator: this.transformNode(node.inOperator, queryId), - pathLegs: this.transformNodeList(node.pathLegs, queryId) - }); - } - transformJSONPathLeg(node, _queryId2) { - return requireAllProps({ - kind: "JSONPathLegNode", - type: node.type, - value: node.value - }); - } - transformJSONOperatorChain(node, queryId) { - return requireAllProps({ - kind: "JSONOperatorChainNode", - operator: this.transformNode(node.operator, queryId), - values: this.transformNodeList(node.values, queryId) - }); - } - transformTuple(node, queryId) { - return requireAllProps({ - kind: "TupleNode", - values: this.transformNodeList(node.values, queryId) - }); - } - transformMergeQuery(node, queryId) { - return requireAllProps({ - kind: "MergeQueryNode", - into: this.transformNode(node.into, queryId), - using: this.transformNode(node.using, queryId), - whens: this.transformNodeList(node.whens, queryId), - with: this.transformNode(node.with, queryId), - top: this.transformNode(node.top, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - output: this.transformNode(node.output, queryId), - returning: this.transformNode(node.returning, queryId) - }); - } - transformMatched(node, _queryId2) { - return requireAllProps({ - kind: "MatchedNode", - not: node.not, - bySource: node.bySource - }); - } - transformAddIndex(node, queryId) { - return requireAllProps({ - kind: "AddIndexNode", - name: this.transformNode(node.name, queryId), - columns: this.transformNodeList(node.columns, queryId), - unique: node.unique, - using: this.transformNode(node.using, queryId), - ifNotExists: node.ifNotExists - }); - } - transformCast(node, queryId) { - return requireAllProps({ - kind: "CastNode", - expression: this.transformNode(node.expression, queryId), - dataType: this.transformNode(node.dataType, queryId) - }); - } - transformFetch(node, queryId) { - return requireAllProps({ - kind: "FetchNode", - rowCount: this.transformNode(node.rowCount, queryId), - modifier: node.modifier - }); - } - transformTop(node, _queryId2) { - return requireAllProps({ - kind: "TopNode", - expression: node.expression, - modifiers: node.modifiers - }); - } - transformOutput(node, queryId) { - return requireAllProps({ - kind: "OutputNode", - selections: this.transformNodeList(node.selections, queryId) - }); - } - transformDataType(node, _queryId2) { - return node; - } - transformSelectAll(node, _queryId2) { - return node; - } - transformIdentifier(node, _queryId2) { - return node; - } - transformValue(node, _queryId2) { - return node; - } - transformPrimitiveValueList(node, _queryId2) { - return node; - } - transformOperator(node, _queryId2) { - return node; - } - transformDefaultInsertValue(node, _queryId2) { - return node; - } - transformOrAction(node, _queryId2) { - return node; - } - transformCollate(node, _queryId2) { - return node; - } - }; - _transformers = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js -var ROOT_OPERATION_NODES, SCHEMALESS_FUNCTIONS, _schema, _schemableIds, _ctes, _WithSchemaTransformer_instances, transformTableArgsWithoutSchemas_fn, isRootOperationNode_fn, collectSchemableIds_fn, collectCTEs_fn, collectSchemableIdsFromTableExpr_fn, collectSchemableId_fn, collectCTEIds_fn, WithSchemaTransformer; -var init_with_schema_transformer = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js"() { - init_alias_node(); - init_identifier_node(); - init_join_node(); - init_list_node(); - init_operation_node_transformer(); - init_schemable_identifier_node(); - init_table_node(); - init_using_node(); - init_object_utils(); - ROOT_OPERATION_NODES = freeze({ - AlterTableNode: true, - CreateIndexNode: true, - CreateSchemaNode: true, - CreateTableNode: true, - CreateTypeNode: true, - CreateViewNode: true, - RefreshMaterializedViewNode: true, - DeleteQueryNode: true, - DropIndexNode: true, - DropSchemaNode: true, - DropTableNode: true, - DropTypeNode: true, - DropViewNode: true, - InsertQueryNode: true, - RawNode: true, - SelectQueryNode: true, - UpdateQueryNode: true, - MergeQueryNode: true - }); - SCHEMALESS_FUNCTIONS = { - json_agg: true, - to_json: true - }; - WithSchemaTransformer = class extends OperationNodeTransformer { - constructor(schema3) { - super(); - __privateAdd(this, _WithSchemaTransformer_instances); - __privateAdd(this, _schema); - __privateAdd(this, _schemableIds, /* @__PURE__ */ new Set()); - __privateAdd(this, _ctes, /* @__PURE__ */ new Set()); - __privateSet(this, _schema, schema3); - } - transformNodeImpl(node, queryId) { - if (!__privateMethod(this, _WithSchemaTransformer_instances, isRootOperationNode_fn).call(this, node)) { - return super.transformNodeImpl(node, queryId); - } - const ctes = __privateMethod(this, _WithSchemaTransformer_instances, collectCTEs_fn).call(this, node); - for (const cte of ctes) { - __privateGet(this, _ctes).add(cte); - } - const tables = __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIds_fn).call(this, node); - for (const table of tables) { - __privateGet(this, _schemableIds).add(table); - } - const transformed = super.transformNodeImpl(node, queryId); - for (const table of tables) { - __privateGet(this, _schemableIds).delete(table); - } - for (const cte of ctes) { - __privateGet(this, _ctes).delete(cte); - } - return transformed; - } - transformSchemableIdentifier(node, queryId) { - const transformed = super.transformSchemableIdentifier(node, queryId); - if (transformed.schema || !__privateGet(this, _schemableIds).has(node.identifier.name)) { - return transformed; - } - return { - ...transformed, - schema: IdentifierNode.create(__privateGet(this, _schema)) - }; - } - transformReferences(node, queryId) { - const transformed = super.transformReferences(node, queryId); - if (transformed.table.table.schema) { - return transformed; - } - return { - ...transformed, - table: TableNode.createWithSchema(__privateGet(this, _schema), transformed.table.table.identifier.name) - }; - } - transformAggregateFunction(node, queryId) { - return { - ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId), - aggregated: __privateMethod(this, _WithSchemaTransformer_instances, transformTableArgsWithoutSchemas_fn).call(this, node, queryId, "aggregated") - }; - } - transformFunction(node, queryId) { - return { - ...super.transformFunction({ ...node, arguments: [] }, queryId), - arguments: __privateMethod(this, _WithSchemaTransformer_instances, transformTableArgsWithoutSchemas_fn).call(this, node, queryId, "arguments") - }; - } - transformSelectModifier(node, queryId) { - return { - ...super.transformSelectModifier({ ...node, of: void 0 }, queryId), - of: node.of?.map((item) => TableNode.is(item) && !item.table.schema ? { - ...item, - table: this.transformIdentifier(item.table.identifier, queryId) - } : this.transformNode(item, queryId)) - }; - } - }; - _schema = new WeakMap(); - _schemableIds = new WeakMap(); - _ctes = new WeakMap(); - _WithSchemaTransformer_instances = new WeakSet(); - transformTableArgsWithoutSchemas_fn = function(node, queryId, argsKey) { - return SCHEMALESS_FUNCTIONS[node.func] ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema ? this.transformNode(arg, queryId) : { - ...arg, - table: this.transformIdentifier(arg.table.identifier, queryId) - }) : this.transformNodeList(node[argsKey], queryId); - }; - isRootOperationNode_fn = function(node) { - return node.kind in ROOT_OPERATION_NODES; - }; - collectSchemableIds_fn = function(node) { - const schemableIds = /* @__PURE__ */ new Set(); - if ("name" in node && node.name && SchemableIdentifierNode.is(node.name)) { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableId_fn).call(this, node.name, schemableIds); - } - if ("from" in node && node.from) { - for (const from of node.from.froms) { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, from, schemableIds); - } - } - if ("into" in node && node.into) { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, node.into, schemableIds); - } - if ("table" in node && node.table) { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, node.table, schemableIds); - } - if ("joins" in node && node.joins) { - for (const join2 of node.joins) { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, join2.table, schemableIds); - } - } - if ("using" in node && node.using) { - if (JoinNode.is(node.using)) { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, node.using.table, schemableIds); - } else { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, node.using, schemableIds); - } - } - return schemableIds; - }; - collectCTEs_fn = function(node) { - const ctes = /* @__PURE__ */ new Set(); - if ("with" in node && node.with) { - __privateMethod(this, _WithSchemaTransformer_instances, collectCTEIds_fn).call(this, node.with, ctes); - } - return ctes; - }; - collectSchemableIdsFromTableExpr_fn = function(node, schemableIds) { - if (TableNode.is(node)) { - return __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableId_fn).call(this, node.table, schemableIds); - } - if (AliasNode.is(node) && TableNode.is(node.node)) { - return __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableId_fn).call(this, node.node.table, schemableIds); - } - if (ListNode.is(node)) { - for (const table of node.items) { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, table, schemableIds); - } - return; - } - if (UsingNode.is(node)) { - for (const table of node.tables) { - __privateMethod(this, _WithSchemaTransformer_instances, collectSchemableIdsFromTableExpr_fn).call(this, table, schemableIds); - } - return; - } - }; - collectSchemableId_fn = function(node, schemableIds) { - const id = node.identifier.name; - if (!__privateGet(this, _schemableIds).has(id) && !__privateGet(this, _ctes).has(id)) { - schemableIds.add(id); - } - }; - collectCTEIds_fn = function(node, ctes) { - for (const expr of node.expressions) { - const cteId = expr.name.table.table.identifier.name; - if (!__privateGet(this, _ctes).has(cteId)) { - ctes.add(cteId); - } - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js -var _transformer, WithSchemaPlugin; -var init_with_schema_plugin = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js"() { - init_with_schema_transformer(); - WithSchemaPlugin = class { - constructor(schema3) { - __privateAdd(this, _transformer); - __privateSet(this, _transformer, new WithSchemaTransformer(schema3)); - } - transformQuery(args) { - return __privateGet(this, _transformer).transformNode(args.node, args.queryId); - } - async transformResult(args) { - return args.result; - } - }; - _transformer = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js -var MatchedNode; -var init_matched_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js"() { - init_object_utils(); - MatchedNode = freeze({ - is(node) { - return node.kind === "MatchedNode"; - }, - create(not, bySource = false) { - return freeze({ - kind: "MatchedNode", - not, - bySource - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js -function parseMergeWhen(type, args, refRight) { - return WhenNode.create(parseFilterList([ - MatchedNode.create(!type.isMatched, type.bySource), - ...args && args.length > 0 ? [ - args.length === 3 && refRight ? parseReferentialBinaryOperation(args[0], args[1], args[2]) : parseValueBinaryOperationOrExpression(args) - ] : [] - ], "and", false)); -} -function parseMergeThen(result) { - if (isString2(result)) { - return RawNode.create([result], []); - } - if (isOperationNodeSource(result)) { - return result.toOperationNode(); - } - return result; -} -var init_merge_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js"() { - init_matched_node(); - init_operation_node_source(); - init_raw_node(); - init_when_node(); - init_object_utils(); - init_binary_operation_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js -var _promise2, _resolve, _reject, Deferred; -var init_deferred = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js"() { - Deferred = class { - constructor() { - __privateAdd(this, _promise2); - __privateAdd(this, _resolve); - __privateAdd(this, _reject); - __publicField(this, "resolve", (value) => { - if (__privateGet(this, _resolve)) { - __privateGet(this, _resolve).call(this, value); - } - }); - __publicField(this, "reject", (reason) => { - if (__privateGet(this, _reject)) { - __privateGet(this, _reject).call(this, reason); - } - }); - __privateSet(this, _promise2, new Promise((resolve2, reject) => { - __privateSet(this, _reject, reject); - __privateSet(this, _resolve, resolve2); - })); - } - get promise() { - return __privateGet(this, _promise2); - } - }; - _promise2 = new WeakMap(); - _resolve = new WeakMap(); - _reject = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js -async function provideControlledConnection(connectionProvider) { - const connectionDefer = new Deferred(); - const connectionReleaseDefer = new Deferred(); - connectionProvider.provideConnection(async (connection) => { - connectionDefer.resolve(connection); - return await connectionReleaseDefer.promise; - }).catch((ex) => connectionDefer.reject(ex)); - return freeze({ - connection: await connectionDefer.promise, - release: connectionReleaseDefer.resolve - }); -} -var init_provide_controlled_connection = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js"() { - init_deferred(); - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js -var NO_PLUGINS, _plugins, _QueryExecutorBase_instances, transformResult_fn, QueryExecutorBase; -var init_query_executor_base = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js"() { - init_object_utils(); - init_provide_controlled_connection(); - init_log_once(); - NO_PLUGINS = freeze([]); - QueryExecutorBase = class { - constructor(plugins = NO_PLUGINS) { - __privateAdd(this, _QueryExecutorBase_instances); - __privateAdd(this, _plugins); - __privateSet(this, _plugins, plugins); - } - get plugins() { - return __privateGet(this, _plugins); - } - transformQuery(node, queryId) { - for (const plugin of __privateGet(this, _plugins)) { - const transformedNode = plugin.transformQuery({ node, queryId }); - if (transformedNode.kind === node.kind) { - node = transformedNode; - } else { - throw new Error([ - `KyselyPlugin.transformQuery must return a node`, - `of the same kind that was given to it.`, - `The plugin was given a ${node.kind}`, - `but it returned a ${transformedNode.kind}` - ].join(" ")); - } - } - return node; - } - async executeQuery(compiledQuery) { - return await this.provideConnection(async (connection) => { - const result = await connection.executeQuery(compiledQuery); - if ("numUpdatedOrDeletedRows" in result) { - logOnce("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`."); - } - return await __privateMethod(this, _QueryExecutorBase_instances, transformResult_fn).call(this, result, compiledQuery.queryId); - }); - } - async *stream(compiledQuery, chunkSize) { - const { connection, release } = await provideControlledConnection(this); - try { - for await (const result of connection.streamQuery(compiledQuery, chunkSize)) { - yield await __privateMethod(this, _QueryExecutorBase_instances, transformResult_fn).call(this, result, compiledQuery.queryId); - } - } finally { - release(); - } - } - }; - _plugins = new WeakMap(); - _QueryExecutorBase_instances = new WeakSet(); - transformResult_fn = async function(result, queryId) { - for (const plugin of __privateGet(this, _plugins)) { - result = await plugin.transformResult({ result, queryId }); - } - return result; - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js -var NoopQueryExecutor, NOOP_QUERY_EXECUTOR; -var init_noop_query_executor = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js"() { - init_query_executor_base(); - NoopQueryExecutor = class _NoopQueryExecutor extends QueryExecutorBase { - get adapter() { - throw new Error("this query cannot be compiled to SQL"); - } - compileQuery() { - throw new Error("this query cannot be compiled to SQL"); - } - provideConnection() { - throw new Error("this query cannot be executed"); - } - withConnectionProvider() { - throw new Error("this query cannot have a connection provider"); - } - withPlugin(plugin) { - return new _NoopQueryExecutor([...this.plugins, plugin]); - } - withPlugins(plugins) { - return new _NoopQueryExecutor([...this.plugins, ...plugins]); - } - withPluginAtFront(plugin) { - return new _NoopQueryExecutor([plugin, ...this.plugins]); - } - withoutPlugins() { - return new _NoopQueryExecutor([]); - } - }; - NOOP_QUERY_EXECUTOR = new NoopQueryExecutor(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js -var MergeResult; -var init_merge_result = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js"() { - MergeResult = class { - constructor(numChangedRows) { - __publicField(this, "numChangedRows"); - this.numChangedRows = numChangedRows; - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js -var _props11, _MergeQueryBuilder, MergeQueryBuilder, _props12, _WheneableMergeQueryBuilder_instances, whenMatched_fn, whenNotMatched_fn, _WheneableMergeQueryBuilder, WheneableMergeQueryBuilder, _props13, MatchedThenableMergeQueryBuilder, _props14, NotMatchedThenableMergeQueryBuilder; -var init_merge_query_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js"() { - init_insert_query_node(); - init_merge_query_node(); - init_query_node(); - init_update_query_node(); - init_insert_values_parser(); - init_join_parser(); - init_merge_parser(); - init_select_parser(); - init_top_parser(); - init_noop_query_executor(); - init_object_utils(); - init_merge_result(); - init_no_result_error(); - init_update_query_builder(); - _MergeQueryBuilder = class _MergeQueryBuilder { - constructor(props) { - __privateAdd(this, _props11); - __privateSet(this, _props11, freeze(props)); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db - * .mergeInto('person') - * .using('pet', 'pet.owner_id', 'person.id') - * .whenMatched() - * .thenDelete() - * .modifyEnd(sql.raw('-- this is a comment')) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment - * ``` - */ - modifyEnd(modifier) { - return new _MergeQueryBuilder({ - ...__privateGet(this, _props11), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props11).queryNode, modifier.toOperationNode()) - }); - } - /** - * Changes a `merge into` query to an `merge top into` query. - * - * `top` clause is only supported by some dialects like MS SQL Server. - * - * ### Examples - * - * Affect 5 matched rows at most: - * - * ```ts - * await db.mergeInto('person') - * .top(5) - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDelete() - * .execute() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * merge top(5) into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * delete - * ``` - * - * Affect 50% of matched rows: - * - * ```ts - * await db.mergeInto('person') - * .top(50, 'percent') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDelete() - * .execute() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * merge top(50) percent into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * delete - * ``` - */ - top(expression, modifiers) { - return new _MergeQueryBuilder({ - ...__privateGet(this, _props11), - queryNode: QueryNode.cloneWithTop(__privateGet(this, _props11).queryNode, parseTop(expression, modifiers)) - }); - } - using(...args) { - return new WheneableMergeQueryBuilder({ - ...__privateGet(this, _props11), - queryNode: MergeQueryNode.cloneWithUsing(__privateGet(this, _props11).queryNode, parseJoin("Using", args)) - }); - } - returning(args) { - return new _MergeQueryBuilder({ - ...__privateGet(this, _props11), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props11).queryNode, parseSelectArg(args)) - }); - } - returningAll(table) { - return new _MergeQueryBuilder({ - ...__privateGet(this, _props11), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props11).queryNode, parseSelectAll(table)) - }); - } - output(args) { - return new _MergeQueryBuilder({ - ...__privateGet(this, _props11), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props11).queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _MergeQueryBuilder({ - ...__privateGet(this, _props11), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props11).queryNode, parseSelectAll(table)) - }); - } - }; - _props11 = new WeakMap(); - MergeQueryBuilder = _MergeQueryBuilder; - _WheneableMergeQueryBuilder = class _WheneableMergeQueryBuilder { - constructor(props) { - __privateAdd(this, _WheneableMergeQueryBuilder_instances); - __privateAdd(this, _props12); - __privateSet(this, _props12, freeze(props)); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db - * .mergeInto('person') - * .using('pet', 'pet.owner_id', 'person.id') - * .whenMatched() - * .thenDelete() - * .modifyEnd(sql.raw('-- this is a comment')) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment - * ``` - */ - modifyEnd(modifier) { - return new _WheneableMergeQueryBuilder({ - ...__privateGet(this, _props12), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props12).queryNode, modifier.toOperationNode()) - }); - } - /** - * See {@link MergeQueryBuilder.top}. - */ - top(expression, modifiers) { - return new _WheneableMergeQueryBuilder({ - ...__privateGet(this, _props12), - queryNode: QueryNode.cloneWithTop(__privateGet(this, _props12).queryNode, parseTop(expression, modifiers)) - }); - } - /** - * Adds a simple `when matched` clause to the query. - * - * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}. - * - * For a simple `when not matched` clause, see {@link whenNotMatched}. - * - * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDelete() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * delete - * ``` - */ - whenMatched() { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenMatched_fn).call(this, []); - } - whenMatchedAnd(...args) { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenMatched_fn).call(this, args); - } - /** - * Adds the `when matched` clause to the query with an `and` condition. But unlike - * {@link whenMatchedAnd}, this method accepts a column reference as the 3rd argument. - * - * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation - * for that method for more examples. - */ - whenMatchedAndRef(lhs, op, rhs) { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenMatched_fn).call(this, [lhs, op, rhs], true); - } - /** - * Adds a simple `when not matched` clause to the query. - * - * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}. - * - * For a simple `when matched` clause, see {@link whenMatched}. - * - * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenNotMatched() - * .thenInsertValues({ - * first_name: 'John', - * last_name: 'Doe', - * }) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when not matched then - * insert ("first_name", "last_name") values ($1, $2) - * ``` - */ - whenNotMatched() { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, []); - } - whenNotMatchedAnd(...args) { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, args); - } - /** - * Adds the `when not matched` clause to the query with an `and` condition. But unlike - * {@link whenNotMatchedAnd}, this method accepts a column reference as the 3rd argument. - * - * Unlike {@link whenMatchedAndRef}, you cannot reference columns from the target table. - * - * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation - * for that method for more examples. - */ - whenNotMatchedAndRef(lhs, op, rhs) { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, [lhs, op, rhs], true); - } - /** - * Adds a simple `when not matched by source` clause to the query. - * - * Supported in MS SQL Server. - * - * Similar to {@link whenNotMatched}, but returns a {@link MatchedThenableMergeQueryBuilder}. - */ - whenNotMatchedBySource() { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, [], false, true); - } - whenNotMatchedBySourceAnd(...args) { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, args, false, true); - } - /** - * Adds the `when not matched by source` clause to the query with an `and` condition. - * - * Similar to {@link whenNotMatchedAndRef}, but you can reference columns from - * the target table, and not from source table and returns a {@link MatchedThenableMergeQueryBuilder}. - */ - whenNotMatchedBySourceAndRef(lhs, op, rhs) { - return __privateMethod(this, _WheneableMergeQueryBuilder_instances, whenNotMatched_fn).call(this, [lhs, op, rhs], true, true); - } - returning(args) { - return new _WheneableMergeQueryBuilder({ - ...__privateGet(this, _props12), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props12).queryNode, parseSelectArg(args)) - }); - } - returningAll(table) { - return new _WheneableMergeQueryBuilder({ - ...__privateGet(this, _props12), - queryNode: QueryNode.cloneWithReturning(__privateGet(this, _props12).queryNode, parseSelectAll(table)) - }); - } - output(args) { - return new _WheneableMergeQueryBuilder({ - ...__privateGet(this, _props12), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props12).queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _WheneableMergeQueryBuilder({ - ...__privateGet(this, _props12), - queryNode: QueryNode.cloneWithOutput(__privateGet(this, _props12).queryNode, parseSelectAll(table)) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - * - * If you want to conditionally call a method on `this`, see - * the {@link $if} method. - * - * ### Examples - * - * The next example uses a helper function `log` to log a query: - * - * ```ts - * import type { Compilable } from 'kysely' - * - * function log(qb: T): T { - * console.log(qb.compile()) - * return qb - * } - * - * await db.updateTable('person') - * .set({ first_name: 'John' }) - * .$call(log) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - /** - * Call `func(this)` if `condition` is true. - * - * This method is especially handy with optional selects. Any `returning` or `returningAll` - * method calls add columns as optional fields to the output type when called inside - * the `func` callback. This is because we can't know if those selections were actually - * made before running the code. - * - * You can also call any other methods inside the callback. - * - * ### Examples - * - * ```ts - * import type { PersonUpdate } from 'type-editor' // imaginary module - * - * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) { - * return await db - * .updateTable('person') - * .set(updates) - * .where('id', '=', id) - * .returning(['id', 'first_name']) - * .$if(returnLastName, (qb) => qb.returning('last_name')) - * .executeTakeFirstOrThrow() - * } - * ``` - * - * Any selections added inside the `if` callback will be added as optional fields to the - * output type since we can't know if the selections were actually made before running - * the code. In the example above the return type of the `updatePerson` function is: - * - * ```ts - * Promise<{ - * id: number - * first_name: string - * last_name?: string - * }> - * ``` - */ - $if(condition, func) { - if (condition) { - return func(this); - } - return new _WheneableMergeQueryBuilder({ - ...__privateGet(this, _props12) - }); - } - toOperationNode() { - return __privateGet(this, _props12).executor.transformQuery(__privateGet(this, _props12).queryNode, __privateGet(this, _props12).queryId); - } - compile() { - return __privateGet(this, _props12).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props12).queryId); - } - /** - * Executes the query and returns an array of rows. - * - * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. - */ - async execute() { - const compiledQuery = this.compile(); - const result = await __privateGet(this, _props12).executor.executeQuery(compiledQuery); - const { adapter } = __privateGet(this, _props12).executor; - const query = compiledQuery.query; - if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { - return result.rows; - } - return [new MergeResult(result.numAffectedRows)]; - } - /** - * Executes the query and returns the first result or undefined if - * the query returned no result. - */ - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - /** - * Executes the query and returns the first result or throws if - * the query returned no result. - * - * By default an instance of {@link NoResultError} is thrown, but you can - * provide a custom error class, or callback as the only argument to throw a different - * error. - */ - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error49; - } - return result; - } - }; - _props12 = new WeakMap(); - _WheneableMergeQueryBuilder_instances = new WeakSet(); - whenMatched_fn = function(args, refRight) { - return new MatchedThenableMergeQueryBuilder({ - ...__privateGet(this, _props12), - queryNode: MergeQueryNode.cloneWithWhen(__privateGet(this, _props12).queryNode, parseMergeWhen({ isMatched: true }, args, refRight)) - }); - }; - whenNotMatched_fn = function(args, refRight = false, bySource = false) { - const props = { - ...__privateGet(this, _props12), - queryNode: MergeQueryNode.cloneWithWhen(__privateGet(this, _props12).queryNode, parseMergeWhen({ isMatched: false, bySource }, args, refRight)) - }; - const Builder = bySource ? MatchedThenableMergeQueryBuilder : NotMatchedThenableMergeQueryBuilder; - return new Builder(props); - }; - WheneableMergeQueryBuilder = _WheneableMergeQueryBuilder; - MatchedThenableMergeQueryBuilder = class { - constructor(props) { - __privateAdd(this, _props13); - __privateSet(this, _props13, freeze(props)); - } - /** - * Performs the `delete` action. - * - * To perform the `do nothing` action, see {@link thenDoNothing}. - * - * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDelete() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * delete - * ``` - */ - thenDelete() { - return new WheneableMergeQueryBuilder({ - ...__privateGet(this, _props13), - queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props13).queryNode, parseMergeThen("delete")) - }); - } - /** - * Performs the `do nothing` action. - * - * This is supported in PostgreSQL. - * - * To perform the `delete` action, see {@link thenDelete}. - * - * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDoNothing() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * do nothing - * ``` - */ - thenDoNothing() { - return new WheneableMergeQueryBuilder({ - ...__privateGet(this, _props13), - queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props13).queryNode, parseMergeThen("do nothing")) - }); - } - /** - * Perform an `update` operation with a full-fledged {@link UpdateQueryBuilder}. - * This is handy when multiple `set` invocations are needed. - * - * For a shorthand version of this method, see {@link thenUpdateSet}. - * - * To perform the `delete` action, see {@link thenDelete}. - * - * To perform the `do nothing` action, see {@link thenDoNothing}. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenUpdate((ub) => ub - * .set(sql`metadata['has_pets']`, 'Y') - * .set({ - * updated_at: new Date().toISOString(), - * }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * update set metadata['has_pets'] = $1, "updated_at" = $2 - * ``` - */ - thenUpdate(set2) { - return new WheneableMergeQueryBuilder({ - ...__privateGet(this, _props13), - queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props13).queryNode, parseMergeThen(set2(new UpdateQueryBuilder({ - queryId: __privateGet(this, _props13).queryId, - executor: NOOP_QUERY_EXECUTOR, - queryNode: UpdateQueryNode.createWithoutTable() - })))) - }); - } - thenUpdateSet(...args) { - return this.thenUpdate((ub) => ub.set(...args)); - } - }; - _props13 = new WeakMap(); - NotMatchedThenableMergeQueryBuilder = class { - constructor(props) { - __privateAdd(this, _props14); - __privateSet(this, _props14, freeze(props)); - } - /** - * Performs the `do nothing` action. - * - * This is supported in PostgreSQL. - * - * To perform the `insert` action, see {@link thenInsertValues}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenNotMatched() - * .thenDoNothing() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when not matched then - * do nothing - * ``` - */ - thenDoNothing() { - return new WheneableMergeQueryBuilder({ - ...__privateGet(this, _props14), - queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props14).queryNode, parseMergeThen("do nothing")) - }); - } - thenInsertValues(insert) { - const [columns, values] = parseInsertExpression(insert); - return new WheneableMergeQueryBuilder({ - ...__privateGet(this, _props14), - queryNode: MergeQueryNode.cloneWithThen(__privateGet(this, _props14).queryNode, parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(), { - columns, - values - }))) - }); - } - }; - _props14 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js -var _props15, _QueryCreator, QueryCreator; -var init_query_creator = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js"() { - init_select_query_builder(); - init_insert_query_builder(); - init_delete_query_builder(); - init_update_query_builder(); - init_delete_query_node(); - init_insert_query_node(); - init_select_query_node(); - init_update_query_node(); - init_table_parser(); - init_with_parser(); - init_with_node(); - init_query_id(); - init_with_schema_plugin(); - init_object_utils(); - init_select_parser(); - init_merge_query_builder(); - init_merge_query_node(); - _QueryCreator = class _QueryCreator { - constructor(props) { - __privateAdd(this, _props15); - __privateSet(this, _props15, freeze(props)); - } - /** - * Creates a `select` query builder for the given table or tables. - * - * The tables passed to this method are built as the query's `from` clause. - * - * ### Examples - * - * Create a select query for one table: - * - * ```ts - * db.selectFrom('person').selectAll() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select * from "person" - * ``` - * - * Create a select query for one table with an alias: - * - * ```ts - * const persons = await db.selectFrom('person as p') - * .select(['p.id', 'first_name']) - * .execute() - * - * console.log(persons[0].id) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "p"."id", "first_name" from "person" as "p" - * ``` - * - * Create a select query from a subquery: - * - * ```ts - * const persons = await db.selectFrom( - * (eb) => eb.selectFrom('person').select('person.id as identifier').as('p') - * ) - * .select('p.identifier') - * .execute() - * - * console.log(persons[0].identifier) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "p"."identifier", - * from ( - * select "person"."id" as "identifier" from "person" - * ) as p - * ``` - * - * Create a select query from raw sql: - * - * ```ts - * import { sql } from 'kysely' - * - * const items = await db - * .selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q')) - * .select('q.one') - * .execute() - * - * console.log(items[0].one) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "q"."one", - * from ( - * select 1 as one - * ) as q - * ``` - * - * When you use the `sql` tag you need to also provide the result type of the - * raw snippet / query so that Kysely can figure out what columns are - * available for the rest of the query. - * - * The `selectFrom` method also accepts an array for multiple tables. All - * the above examples can also be used in an array. - * - * ```ts - * import { sql } from 'kysely' - * - * const items = await db.selectFrom([ - * 'person as p', - * db.selectFrom('pet').select('pet.species').as('a'), - * sql<{ one: number }>`(select 1 as one)`.as('q') - * ]) - * .select(['p.id', 'a.species', 'q.one']) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "p".id, "a"."species", "q"."one" - * from - * "person" as "p", - * (select "pet"."species" from "pet") as a, - * (select 1 as one) as "q" - * ``` - */ - selectFrom(from) { - return createSelectQueryBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _props15).executor, - queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(from), __privateGet(this, _props15).withNode) - }); - } - selectNoFrom(selection) { - return createSelectQueryBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _props15).executor, - queryNode: SelectQueryNode.cloneWithSelections(SelectQueryNode.create(__privateGet(this, _props15).withNode), parseSelectArg(selection)) - }); - } - /** - * Creates an insert query. - * - * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult} - * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of - * the inserted row if the db returned one. - * - * See the {@link InsertQueryBuilder.values | values} method for more info and examples. Also see - * the {@link ReturningInterface.returning | returning} method for a way to return columns - * on supported databases like PostgreSQL. - * - * ### Examples - * - * ```ts - * const result = await db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston' - * }) - * .executeTakeFirst() - * - * console.log(result.insertId) - * ``` - * - * Some databases like PostgreSQL support the `returning` method: - * - * ```ts - * const { id } = await db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston' - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * ``` - */ - insertInto(table) { - return new InsertQueryBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _props15).executor, - queryNode: InsertQueryNode.create(parseTable(table), __privateGet(this, _props15).withNode) - }); - } - /** - * Creates a "replace into" query. - * - * This is only supported by some dialects like MySQL or SQLite. - * - * Similar to MySQL's {@link InsertQueryBuilder.onDuplicateKeyUpdate} that deletes - * and inserts values on collision instead of updating existing rows. - * - * An alias of SQLite's {@link InsertQueryBuilder.orReplace}. - * - * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult} - * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of - * the inserted row if the db returned one. - * - * See the {@link InsertQueryBuilder.values | values} method for more info and examples. - * - * ### Examples - * - * ```ts - * const result = await db - * .replaceInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston' - * }) - * .executeTakeFirstOrThrow() - * - * console.log(result.insertId) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * replace into `person` (`first_name`, `last_name`) values (?, ?) - * ``` - */ - replaceInto(table) { - return new InsertQueryBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _props15).executor, - queryNode: InsertQueryNode.create(parseTable(table), __privateGet(this, _props15).withNode, true) - }); - } - /** - * Creates a delete query. - * - * See the {@link DeleteQueryBuilder.where} method for examples on how to specify - * a where clause for the delete operation. - * - * The return value of the query is an instance of {@link DeleteResult}. - * - * ### Examples - * - * - * - * Delete a single row: - * - * ```ts - * const result = await db - * .deleteFrom('person') - * .where('person.id', '=', 1) - * .executeTakeFirst() - * - * console.log(result.numDeletedRows) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * delete from "person" where "person"."id" = $1 - * ``` - * - * Some databases such as MySQL support deleting from multiple tables: - * - * ```ts - * const result = await db - * .deleteFrom(['person', 'pet']) - * .using('person') - * .innerJoin('pet', 'pet.owner_id', 'person.id') - * .where('person.id', '=', 1) - * .executeTakeFirst() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * delete from `person`, `pet` - * using `person` - * inner join `pet` on `pet`.`owner_id` = `person`.`id` - * where `person`.`id` = ? - * ``` - */ - deleteFrom(from) { - return new DeleteQueryBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _props15).executor, - queryNode: DeleteQueryNode.create(parseTableExpressionOrList(from), __privateGet(this, _props15).withNode) - }); - } - /** - * Creates an update query. - * - * See the {@link UpdateQueryBuilder.where} method for examples on how to specify - * a where clause for the update operation. - * - * See the {@link UpdateQueryBuilder.set} method for examples on how to - * specify the updates. - * - * The return value of the query is an {@link UpdateResult}. - * - * ### Examples - * - * ```ts - * const result = await db - * .updateTable('person') - * .set({ first_name: 'Jennifer' }) - * .where('person.id', '=', 1) - * .executeTakeFirst() - * - * console.log(result.numUpdatedRows) - * ``` - */ - updateTable(tables) { - return new UpdateQueryBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _props15).executor, - queryNode: UpdateQueryNode.create(parseTableExpressionOrList(tables), __privateGet(this, _props15).withNode) - }); - } - /** - * Creates a merge query. - * - * The return value of the query is a {@link MergeResult}. - * - * See the {@link MergeQueryBuilder.using} method for examples on how to specify - * the other table. - * - * ### Examples - * - * - * - * Update a target column based on the existence of a source row: - * - * ```ts - * const result = await db - * .mergeInto('person as target') - * .using('pet as source', 'source.owner_id', 'target.id') - * .whenMatchedAnd('target.has_pets', '!=', 'Y') - * .thenUpdateSet({ has_pets: 'Y' }) - * .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y') - * .thenUpdateSet({ has_pets: 'N' }) - * .executeTakeFirstOrThrow() - * - * console.log(result.numChangedRows) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" - * on "pet"."owner_id" = "person"."id" - * when matched and "has_pets" != $1 - * then update set "has_pets" = $2 - * when not matched by source and "has_pets" = $3 - * then update set "has_pets" = $4 - * ``` - * - * - * - * Merge new entries from a temporary changes table: - * - * ```ts - * const result = await db - * .mergeInto('wine as target') - * .using( - * 'wine_stock_change as source', - * 'source.wine_name', - * 'target.name', - * ) - * .whenNotMatchedAnd('source.stock_delta', '>', 0) - * .thenInsertValues(({ ref }) => ({ - * name: ref('source.wine_name'), - * stock: ref('source.stock_delta'), - * })) - * .whenMatchedAnd( - * (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')), - * '>', - * 0, - * ) - * .thenUpdateSet('stock', (eb) => - * eb('target.stock', '+', eb.ref('source.stock_delta')), - * ) - * .whenMatched() - * .thenDelete() - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "wine" as "target" - * using "wine_stock_change" as "source" - * on "source"."wine_name" = "target"."name" - * when not matched and "source"."stock_delta" > $1 - * then insert ("name", "stock") values ("source"."wine_name", "source"."stock_delta") - * when matched and "target"."stock" + "source"."stock_delta" > $2 - * then update set "stock" = "target"."stock" + "source"."stock_delta" - * when matched - * then delete - * ``` - */ - mergeInto(targetTable) { - return new MergeQueryBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _props15).executor, - queryNode: MergeQueryNode.create(parseAliasedTable(targetTable), __privateGet(this, _props15).withNode) - }); - } - /** - * Creates a `with` query (Common Table Expression). - * - * ### Examples - * - * - * - * Common table expressions (CTE) are a great way to modularize complex queries. - * Essentially they allow you to run multiple separate queries within a - * single roundtrip to the DB. - * - * Since CTEs are a part of the main query, query optimizers inside DB - * engines are able to optimize the overall query. For example, postgres - * is able to inline the CTEs inside the using queries if it decides it's - * faster. - * - * ```ts - * const result = await db - * // Create a CTE called `jennifers` that selects all - * // persons named 'Jennifer'. - * .with('jennifers', (db) => db - * .selectFrom('person') - * .where('first_name', '=', 'Jennifer') - * .select(['id', 'age']) - * ) - * // Select all rows from the `jennifers` CTE and - * // further filter it. - * .with('adult_jennifers', (db) => db - * .selectFrom('jennifers') - * .where('age', '>', 18) - * .select(['id', 'age']) - * ) - * // Finally select all adult jennifers that are - * // also younger than 60. - * .selectFrom('adult_jennifers') - * .where('age', '<', 60) - * .selectAll() - * .execute() - * ``` - * - * - * - * Some databases like postgres also allow you to run other queries than selects - * in CTEs. On these databases CTEs are extremely powerful: - * - * ```ts - * const result = await db - * .with('new_person', (db) => db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * age: 35, - * }) - * .returning('id') - * ) - * .with('new_pet', (db) => db - * .insertInto('pet') - * .values({ - * name: 'Doggo', - * species: 'dog', - * is_favorite: true, - * // Use the id of the person we just inserted. - * owner_id: db - * .selectFrom('new_person') - * .select('id') - * }) - * .returning('id') - * ) - * .selectFrom(['new_person', 'new_pet']) - * .select([ - * 'new_person.id as person_id', - * 'new_pet.id as pet_id' - * ]) - * .execute() - * ``` - * - * The CTE name can optionally specify column names in addition to - * a name. In that case Kysely requires the expression to retun - * rows with the same columns. - * - * ```ts - * await db - * .with('jennifers(id, age)', (db) => db - * .selectFrom('person') - * .where('first_name', '=', 'Jennifer') - * // This is ok since we return columns with the same - * // names as specified by `jennifers(id, age)`. - * .select(['id', 'age']) - * ) - * .selectFrom('jennifers') - * .selectAll() - * .execute() - * ``` - * - * The first argument can also be a callback. The callback is passed - * a `CTEBuilder` instance that can be used to configure the CTE: - * - * ```ts - * await db - * .with( - * (cte) => cte('jennifers').materialized(), - * (db) => db - * .selectFrom('person') - * .where('first_name', '=', 'Jennifer') - * .select(['id', 'age']) - * ) - * .selectFrom('jennifers') - * .selectAll() - * .execute() - * ``` - */ - with(nameOrBuilder, expression) { - const cte = parseCommonTableExpression(nameOrBuilder, expression); - return new _QueryCreator({ - ...__privateGet(this, _props15), - withNode: __privateGet(this, _props15).withNode ? WithNode.cloneWithExpression(__privateGet(this, _props15).withNode, cte) : WithNode.create(cte) - }); - } - /** - * Creates a recursive `with` query (Common Table Expression). - * - * Note that recursiveness is a property of the whole `with` statement. - * You cannot have recursive and non-recursive CTEs in a same `with` statement. - * Therefore the recursiveness is determined by the **first** `with` or - * `withRecusive` call you make. - * - * See the {@link with} method for examples and more documentation. - */ - withRecursive(nameOrBuilder, expression) { - const cte = parseCommonTableExpression(nameOrBuilder, expression); - return new _QueryCreator({ - ...__privateGet(this, _props15), - withNode: __privateGet(this, _props15).withNode ? WithNode.cloneWithExpression(__privateGet(this, _props15).withNode, cte) : WithNode.create(cte, { recursive: true }) - }); - } - /** - * Returns a copy of this query creator instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _QueryCreator({ - ...__privateGet(this, _props15), - executor: __privateGet(this, _props15).executor.withPlugin(plugin) - }); - } - /** - * Returns a copy of this query creator instance without any plugins. - */ - withoutPlugins() { - return new _QueryCreator({ - ...__privateGet(this, _props15), - executor: __privateGet(this, _props15).executor.withoutPlugins() - }); - } - /** - * Sets the schema to be used for all table references that don't explicitly - * specify a schema. - * - * This only affects the query created through the builder returned from - * this method and doesn't modify the `db` instance. - * - * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0007-schemas.md) - * for a more detailed explanation. - * - * ### Examples - * - * ``` - * await db - * .withSchema('mammals') - * .selectFrom('pet') - * .selectAll() - * .innerJoin('public.person', 'public.person.id', 'pet.owner_id') - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select * from "mammals"."pet" - * inner join "public"."person" - * on "public"."person"."id" = "mammals"."pet"."owner_id" - * ``` - * - * `withSchema` is smart enough to not add schema for aliases, - * common table expressions or other places where the schema - * doesn't belong to: - * - * ``` - * await db - * .withSchema('mammals') - * .selectFrom('pet as p') - * .select('p.name') - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "p"."name" from "mammals"."pet" as "p" - * ``` - */ - withSchema(schema3) { - return new _QueryCreator({ - ...__privateGet(this, _props15), - executor: __privateGet(this, _props15).executor.withPluginAtFront(new WithSchemaPlugin(schema3)) - }); - } - }; - _props15 = new WeakMap(); - QueryCreator = _QueryCreator; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js -function createQueryCreator() { - return new QueryCreator({ - executor: NOOP_QUERY_EXECUTOR - }); -} -function createJoinBuilder(joinType, table) { - return new JoinBuilder({ - joinNode: JoinNode.create(joinType, parseTableExpression(table)) - }); -} -function createOverBuilder() { - return new OverBuilder({ - overNode: OverNode.create() - }); -} -var init_parse_utils = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js"() { - init_join_node(); - init_over_node(); - init_join_builder(); - init_over_builder(); - init_query_creator(); - init_noop_query_executor(); - init_table_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js -function parseJoin(joinType, args) { - if (args.length === 3) { - return parseSingleOnJoin(joinType, args[0], args[1], args[2]); - } else if (args.length === 2) { - return parseCallbackJoin(joinType, args[0], args[1]); - } else if (args.length === 1) { - return parseOnlessJoin(joinType, args[0]); - } else { - throw new Error("not implemented"); - } -} -function parseCallbackJoin(joinType, from, callback) { - return callback(createJoinBuilder(joinType, from)).toOperationNode(); -} -function parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) { - return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, "=", rhsColumn)); -} -function parseOnlessJoin(joinType, from) { - return JoinNode.create(joinType, parseTableExpression(from)); -} -var init_join_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js"() { - init_join_node(); - init_binary_operation_parser(); - init_parse_utils(); - init_table_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js -var OffsetNode; -var init_offset_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js"() { - init_object_utils(); - OffsetNode = freeze({ - is(node) { - return node.kind === "OffsetNode"; - }, - create(offset) { - return freeze({ - kind: "OffsetNode", - offset - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js -var GroupByItemNode; -var init_group_by_item_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js"() { - init_object_utils(); - GroupByItemNode = freeze({ - is(node) { - return node.kind === "GroupByItemNode"; - }, - create(groupBy2) { - return freeze({ - kind: "GroupByItemNode", - groupBy: groupBy2 - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js -function parseGroupBy(groupBy2) { - groupBy2 = isFunction3(groupBy2) ? groupBy2(expressionBuilder()) : groupBy2; - return parseReferenceExpressionOrList(groupBy2).map(GroupByItemNode.create); -} -var init_group_by_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js"() { - init_group_by_item_node(); - init_expression_builder(); - init_object_utils(); - init_reference_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js -var SetOperationNode; -var init_set_operation_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js"() { - init_object_utils(); - SetOperationNode = freeze({ - is(node) { - return node.kind === "SetOperationNode"; - }, - create(operator, expression, all) { - return freeze({ - kind: "SetOperationNode", - operator, - expression, - all - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js -function parseSetOperations(operator, expression, all) { - if (isFunction3(expression)) { - expression = expression(createExpressionBuilder()); - } - if (!isReadonlyArray(expression)) { - expression = [expression]; - } - return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all)); -} -var init_set_operation_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js"() { - init_expression_builder(); - init_set_operation_node(); - init_object_utils(); - init_expression_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js -var _node2, _ExpressionWrapper, ExpressionWrapper, _expr, _alias, AliasedExpressionWrapper, _node3, _OrWrapper, OrWrapper, _node4, _AndWrapper, AndWrapper; -var init_expression_wrapper = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js"() { - init_alias_node(); - init_and_node(); - init_identifier_node(); - init_operation_node_source(); - init_or_node(); - init_parens_node(); - init_binary_operation_parser(); - _ExpressionWrapper = class _ExpressionWrapper { - constructor(node) { - __privateAdd(this, _node2); - __privateSet(this, _node2, node); - } - /** @private */ - get expressionType() { - return void 0; - } - as(alias) { - return new AliasedExpressionWrapper(this, alias); - } - or(...args) { - return new OrWrapper(OrNode.create(__privateGet(this, _node2), parseValueBinaryOperationOrExpression(args))); - } - and(...args) { - return new AndWrapper(AndNode.create(__privateGet(this, _node2), parseValueBinaryOperationOrExpression(args))); - } - /** - * Change the output type of the expression. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `ExpressionWrapper` with a new output type. - */ - $castTo() { - return new _ExpressionWrapper(__privateGet(this, _node2)); - } - /** - * Omit null from the expression's type. - * - * This function can be useful in cases where you know an expression can't be - * null, but Kysely is unable to infer it. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of `this` with a new output type. - */ - $notNull() { - return new _ExpressionWrapper(__privateGet(this, _node2)); - } - toOperationNode() { - return __privateGet(this, _node2); - } - }; - _node2 = new WeakMap(); - ExpressionWrapper = _ExpressionWrapper; - AliasedExpressionWrapper = class { - constructor(expr, alias) { - __privateAdd(this, _expr); - __privateAdd(this, _alias); - __privateSet(this, _expr, expr); - __privateSet(this, _alias, alias); - } - /** @private */ - get expression() { - return __privateGet(this, _expr); - } - /** @private */ - get alias() { - return __privateGet(this, _alias); - } - toOperationNode() { - return AliasNode.create(__privateGet(this, _expr).toOperationNode(), isOperationNodeSource(__privateGet(this, _alias)) ? __privateGet(this, _alias).toOperationNode() : IdentifierNode.create(__privateGet(this, _alias))); - } - }; - _expr = new WeakMap(); - _alias = new WeakMap(); - _OrWrapper = class _OrWrapper { - constructor(node) { - __privateAdd(this, _node3); - __privateSet(this, _node3, node); - } - /** @private */ - get expressionType() { - return void 0; - } - as(alias) { - return new AliasedExpressionWrapper(this, alias); - } - or(...args) { - return new _OrWrapper(OrNode.create(__privateGet(this, _node3), parseValueBinaryOperationOrExpression(args))); - } - /** - * Change the output type of the expression. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `OrWrapper` with a new output type. - */ - $castTo() { - return new _OrWrapper(__privateGet(this, _node3)); - } - toOperationNode() { - return ParensNode.create(__privateGet(this, _node3)); - } - }; - _node3 = new WeakMap(); - OrWrapper = _OrWrapper; - _AndWrapper = class _AndWrapper { - constructor(node) { - __privateAdd(this, _node4); - __privateSet(this, _node4, node); - } - /** @private */ - get expressionType() { - return void 0; - } - as(alias) { - return new AliasedExpressionWrapper(this, alias); - } - and(...args) { - return new _AndWrapper(AndNode.create(__privateGet(this, _node4), parseValueBinaryOperationOrExpression(args))); - } - /** - * Change the output type of the expression. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `AndWrapper` with a new output type. - */ - $castTo() { - return new _AndWrapper(__privateGet(this, _node4)); - } - toOperationNode() { - return ParensNode.create(__privateGet(this, _node4)); - } - }; - _node4 = new WeakMap(); - AndWrapper = _AndWrapper; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js -var FetchNode; -var init_fetch_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js"() { - init_object_utils(); - init_value_node(); - FetchNode = freeze({ - is(node) { - return node.kind === "FetchNode"; - }, - create(rowCount, modifier) { - return { - kind: "FetchNode", - rowCount: ValueNode.create(rowCount), - modifier - }; - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js -function parseFetch(rowCount, modifier) { - if (!isNumber2(rowCount) && !isBigInt(rowCount)) { - throw new Error(`Invalid fetch row count: ${rowCount}`); - } - if (!isFetchModifier(modifier)) { - throw new Error(`Invalid fetch modifier: ${modifier}`); - } - return FetchNode.create(rowCount, modifier); -} -function isFetchModifier(value) { - return value === "only" || value === "with ties"; -} -var init_fetch_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js"() { - init_fetch_node(); - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js -function createSelectQueryBuilder(props) { - return new SelectQueryBuilderImpl(props); -} -var _a14, _props16, _SelectQueryBuilderImpl_instances, join_fn3, SelectQueryBuilderImpl, _queryBuilder, _alias2, AliasedSelectQueryBuilderImpl; -var init_select_query_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js"() { - init_alias_node(); - init_select_modifier_node(); - init_join_parser(); - init_table_parser(); - init_select_parser(); - init_reference_parser(); - init_select_query_node(); - init_query_node(); - init_order_by_parser(); - init_limit_node(); - init_offset_node(); - init_object_utils(); - init_group_by_parser(); - init_no_result_error(); - init_identifier_node(); - init_set_operation_parser(); - init_binary_operation_parser(); - init_expression_wrapper(); - init_value_parser(); - init_fetch_parser(); - init_top_parser(); - SelectQueryBuilderImpl = class { - constructor(props) { - __privateAdd(this, _SelectQueryBuilderImpl_instances); - __privateAdd(this, _props16); - __privateSet(this, _props16, freeze(props)); - } - get expressionType() { - return void 0; - } - get isSelectQueryBuilder() { - return true; - } - where(...args) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props16).queryNode, parseValueBinaryOperationOrExpression(args)) - }); - } - whereRef(lhs, op, rhs) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithWhere(__privateGet(this, _props16).queryNode, parseReferentialBinaryOperation(lhs, op, rhs)) - }); - } - having(...args) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithHaving(__privateGet(this, _props16).queryNode, parseValueBinaryOperationOrExpression(args)) - }); - } - havingRef(lhs, op, rhs) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithHaving(__privateGet(this, _props16).queryNode, parseReferentialBinaryOperation(lhs, op, rhs)) - }); - } - select(selection) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithSelections(__privateGet(this, _props16).queryNode, parseSelectArg(selection)) - }); - } - distinctOn(selection) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithDistinctOn(__privateGet(this, _props16).queryNode, parseReferenceExpressionOrList(selection)) - }); - } - modifyFront(modifier) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithFrontModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())) - }); - } - modifyEnd(modifier) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())) - }); - } - distinct() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithFrontModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("Distinct")) - }); - } - forUpdate(of) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("ForUpdate", of ? asArray(of).map(parseTable) : void 0)) - }); - } - forShare(of) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("ForShare", of ? asArray(of).map(parseTable) : void 0)) - }); - } - forKeyShare(of) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("ForKeyShare", of ? asArray(of).map(parseTable) : void 0)) - }); - } - forNoKeyUpdate(of) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("ForNoKeyUpdate", of ? asArray(of).map(parseTable) : void 0)) - }); - } - skipLocked() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("SkipLocked")) - }); - } - noWait() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithEndModifier(__privateGet(this, _props16).queryNode, SelectModifierNode.create("NoWait")) - }); - } - selectAll(table) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithSelections(__privateGet(this, _props16).queryNode, parseSelectAll(table)) - }); - } - innerJoin(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "InnerJoin", args); - } - leftJoin(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "LeftJoin", args); - } - rightJoin(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "RightJoin", args); - } - fullJoin(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "FullJoin", args); - } - crossJoin(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "CrossJoin", args); - } - innerJoinLateral(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "LateralInnerJoin", args); - } - leftJoinLateral(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "LateralLeftJoin", args); - } - crossJoinLateral(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "LateralCrossJoin", args); - } - crossApply(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "CrossApply", args); - } - outerApply(...args) { - return __privateMethod(this, _SelectQueryBuilderImpl_instances, join_fn3).call(this, "OuterApply", args); - } - orderBy(...args) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithOrderByItems(__privateGet(this, _props16).queryNode, parseOrderBy(args)) - }); - } - groupBy(groupBy2) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithGroupByItems(__privateGet(this, _props16).queryNode, parseGroupBy(groupBy2)) - }); - } - limit(limit) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithLimit(__privateGet(this, _props16).queryNode, LimitNode.create(parseValueExpression(limit))) - }); - } - offset(offset) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithOffset(__privateGet(this, _props16).queryNode, OffsetNode.create(parseValueExpression(offset))) - }); - } - fetch(rowCount, modifier = "only") { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithFetch(__privateGet(this, _props16).queryNode, parseFetch(rowCount, modifier)) - }); - } - top(expression, modifiers) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithTop(__privateGet(this, _props16).queryNode, parseTop(expression, modifiers)) - }); - } - union(expression) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("union", expression, false)) - }); - } - unionAll(expression) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("union", expression, true)) - }); - } - intersect(expression) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("intersect", expression, false)) - }); - } - intersectAll(expression) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("intersect", expression, true)) - }); - } - except(expression) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("except", expression, false)) - }); - } - exceptAll(expression) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithSetOperations(__privateGet(this, _props16).queryNode, parseSetOperations("except", expression, true)) - }); - } - as(alias) { - return new AliasedSelectQueryBuilderImpl(this, alias); - } - clearSelect() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithoutSelections(__privateGet(this, _props16).queryNode) - }); - } - clearWhere() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithoutWhere(__privateGet(this, _props16).queryNode) - }); - } - clearLimit() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithoutLimit(__privateGet(this, _props16).queryNode) - }); - } - clearOffset() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithoutOffset(__privateGet(this, _props16).queryNode) - }); - } - clearOrderBy() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props16).queryNode) - }); - } - clearGroupBy() { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: SelectQueryNode.cloneWithoutGroupBy(__privateGet(this, _props16).queryNode) - }); - } - $call(func) { - return func(this); - } - $if(condition, func) { - if (condition) { - return func(this); - } - return new _a14({ - ...__privateGet(this, _props16) - }); - } - $castTo() { - return new _a14(__privateGet(this, _props16)); - } - $narrowType() { - return new _a14(__privateGet(this, _props16)); - } - $assertType() { - return new _a14(__privateGet(this, _props16)); - } - $asTuple() { - return new ExpressionWrapper(this.toOperationNode()); - } - $asScalar() { - return new ExpressionWrapper(this.toOperationNode()); - } - withPlugin(plugin) { - return new _a14({ - ...__privateGet(this, _props16), - executor: __privateGet(this, _props16).executor.withPlugin(plugin) - }); - } - toOperationNode() { - return __privateGet(this, _props16).executor.transformQuery(__privateGet(this, _props16).queryNode, __privateGet(this, _props16).queryId); - } - compile() { - return __privateGet(this, _props16).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props16).queryId); - } - async execute() { - const compiledQuery = this.compile(); - const result = await __privateGet(this, _props16).executor.executeQuery(compiledQuery); - return result.rows; - } - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error49 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error49; - } - return result; - } - async *stream(chunkSize = 100) { - const compiledQuery = this.compile(); - const stream = __privateGet(this, _props16).executor.stream(compiledQuery, chunkSize); - for await (const item of stream) { - yield* item.rows; - } - } - async explain(format, options) { - const builder = new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithExplain(__privateGet(this, _props16).queryNode, format, options) - }); - return await builder.execute(); - } - }; - _props16 = new WeakMap(); - _SelectQueryBuilderImpl_instances = new WeakSet(); - join_fn3 = function(joinType, args) { - return new _a14({ - ...__privateGet(this, _props16), - queryNode: QueryNode.cloneWithJoin(__privateGet(this, _props16).queryNode, parseJoin(joinType, args)) - }); - }; - _a14 = SelectQueryBuilderImpl; - AliasedSelectQueryBuilderImpl = class { - constructor(queryBuilder, alias) { - __privateAdd(this, _queryBuilder); - __privateAdd(this, _alias2); - __privateSet(this, _queryBuilder, queryBuilder); - __privateSet(this, _alias2, alias); - } - get expression() { - return __privateGet(this, _queryBuilder); - } - get alias() { - return __privateGet(this, _alias2); - } - get isAliasedSelectQueryBuilder() { - return true; - } - toOperationNode() { - return AliasNode.create(__privateGet(this, _queryBuilder).toOperationNode(), IdentifierNode.create(__privateGet(this, _alias2))); - } - }; - _queryBuilder = new WeakMap(); - _alias2 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js -var AggregateFunctionNode; -var init_aggregate_function_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js"() { - init_object_utils(); - init_where_node(); - init_order_by_node(); - AggregateFunctionNode = freeze({ - is(node) { - return node.kind === "AggregateFunctionNode"; - }, - create(aggregateFunction, aggregated = []) { - return freeze({ - kind: "AggregateFunctionNode", - func: aggregateFunction, - aggregated - }); - }, - cloneWithDistinct(aggregateFunctionNode) { - return freeze({ - ...aggregateFunctionNode, - distinct: true - }); - }, - cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) { - const prop = withinGroup ? "withinGroup" : "orderBy"; - return freeze({ - ...aggregateFunctionNode, - [prop]: aggregateFunctionNode[prop] ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems) : OrderByNode.create(orderItems) - }); - }, - cloneWithFilter(aggregateFunctionNode, filter) { - return freeze({ - ...aggregateFunctionNode, - filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "And", filter) : WhereNode.create(filter) - }); - }, - cloneWithOrFilter(aggregateFunctionNode, filter) { - return freeze({ - ...aggregateFunctionNode, - filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "Or", filter) : WhereNode.create(filter) - }); - }, - cloneWithOver(aggregateFunctionNode, over) { - return freeze({ - ...aggregateFunctionNode, - over - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js -var FunctionNode; -var init_function_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js"() { - init_object_utils(); - FunctionNode = freeze({ - is(node) { - return node.kind === "FunctionNode"; - }, - create(func, args) { - return freeze({ - kind: "FunctionNode", - func, - arguments: args - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js -var _props17, _AggregateFunctionBuilder, AggregateFunctionBuilder, _aggregateFunctionBuilder, _alias3, AliasedAggregateFunctionBuilder; -var init_aggregate_function_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js"() { - init_object_utils(); - init_aggregate_function_node(); - init_alias_node(); - init_identifier_node(); - init_parse_utils(); - init_binary_operation_parser(); - init_order_by_parser(); - init_query_node(); - _AggregateFunctionBuilder = class _AggregateFunctionBuilder { - constructor(props) { - __privateAdd(this, _props17); - __privateSet(this, _props17, freeze(props)); - } - /** @private */ - get expressionType() { - return void 0; - } - /** - * Returns an aliased version of the function. - * - * In addition to slapping `as "the_alias"` to the end of the SQL, - * this method also provides strict typing: - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select( - * (eb) => eb.fn.count('id').as('person_count') - * ) - * .executeTakeFirstOrThrow() - * - * // `person_count: number` field exists in the result type. - * console.log(result.person_count) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select count("id") as "person_count" - * from "person" - * ``` - */ - as(alias) { - return new AliasedAggregateFunctionBuilder(this, alias); - } - /** - * Adds a `distinct` clause inside the function. - * - * ### Examples - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select((eb) => - * eb.fn.count('first_name').distinct().as('first_name_count') - * ) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select count(distinct "first_name") as "first_name_count" - * from "person" - * ``` - */ - distinct() { - return new _AggregateFunctionBuilder({ - ...__privateGet(this, _props17), - aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(__privateGet(this, _props17).aggregateFunctionNode) - }); - } - orderBy(...args) { - return new _AggregateFunctionBuilder({ - ...__privateGet(this, _props17), - aggregateFunctionNode: QueryNode.cloneWithOrderByItems(__privateGet(this, _props17).aggregateFunctionNode, parseOrderBy(args)) - }); - } - clearOrderBy() { - return new _AggregateFunctionBuilder({ - ...__privateGet(this, _props17), - aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(__privateGet(this, _props17).aggregateFunctionNode) - }); - } - withinGroupOrderBy(...args) { - return new _AggregateFunctionBuilder({ - ...__privateGet(this, _props17), - aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(__privateGet(this, _props17).aggregateFunctionNode, parseOrderBy(args), true) - }); - } - filterWhere(...args) { - return new _AggregateFunctionBuilder({ - ...__privateGet(this, _props17), - aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(__privateGet(this, _props17).aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)) - }); - } - /** - * Adds a `filter` clause with a nested `where` clause after the function, where - * both sides of the operator are references to columns. - * - * Similar to {@link WhereInterface}'s `whereRef` method. - * - * ### Examples - * - * Count people with same first and last names versus general public: - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select((eb) => [ - * eb.fn - * .count('id') - * .filterWhereRef('first_name', '=', 'last_name') - * .as('repeat_name_count'), - * eb.fn.count('id').as('total_count'), - * ]) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select - * count("id") filter(where "first_name" = "last_name") as "repeat_name_count", - * count("id") as "total_count" - * from "person" - * ``` - */ - filterWhereRef(lhs, op, rhs) { - return new _AggregateFunctionBuilder({ - ...__privateGet(this, _props17), - aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(__privateGet(this, _props17).aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs)) - }); - } - /** - * Adds an `over` clause (window functions) after the function. - * - * ### Examples - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select( - * (eb) => eb.fn.avg('age').over().as('average_age') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select avg("age") over() as "average_age" - * from "person" - * ``` - * - * Also supports passing a callback that returns an over builder, - * allowing to add partition by and sort by clauses inside over. - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select( - * (eb) => eb.fn.avg('age').over( - * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc') - * ).as('average_age') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select avg("age") over(partition by "last_name" order by "first_name" asc) as "average_age" - * from "person" - * ``` - */ - over(over) { - const builder = createOverBuilder(); - return new _AggregateFunctionBuilder({ - ...__privateGet(this, _props17), - aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(__privateGet(this, _props17).aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - /** - * Casts the expression to the given type. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `AggregateFunctionBuilder` with a new output type. - */ - $castTo() { - return new _AggregateFunctionBuilder(__privateGet(this, _props17)); - } - /** - * Omit null from the expression's type. - * - * This function can be useful in cases where you know an expression can't be - * null, but Kysely is unable to infer it. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of `this` with a new output type. - */ - $notNull() { - return new _AggregateFunctionBuilder(__privateGet(this, _props17)); - } - toOperationNode() { - return __privateGet(this, _props17).aggregateFunctionNode; - } - }; - _props17 = new WeakMap(); - AggregateFunctionBuilder = _AggregateFunctionBuilder; - AliasedAggregateFunctionBuilder = class { - constructor(aggregateFunctionBuilder, alias) { - __privateAdd(this, _aggregateFunctionBuilder); - __privateAdd(this, _alias3); - __privateSet(this, _aggregateFunctionBuilder, aggregateFunctionBuilder); - __privateSet(this, _alias3, alias); - } - /** @private */ - get expression() { - return __privateGet(this, _aggregateFunctionBuilder); - } - /** @private */ - get alias() { - return __privateGet(this, _alias3); - } - toOperationNode() { - return AliasNode.create(__privateGet(this, _aggregateFunctionBuilder).toOperationNode(), IdentifierNode.create(__privateGet(this, _alias3))); - } - }; - _aggregateFunctionBuilder = new WeakMap(); - _alias3 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js -function createFunctionModule() { - const fn = (name, args) => { - return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? []))); - }; - const agg = (name, args) => { - return new AggregateFunctionBuilder({ - aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : void 0) - }); - }; - return Object.assign(fn, { - agg, - avg(column) { - return agg("avg", [column]); - }, - coalesce(...values) { - return fn("coalesce", values); - }, - count(column) { - return agg("count", [column]); - }, - countAll(table) { - return new AggregateFunctionBuilder({ - aggregateFunctionNode: AggregateFunctionNode.create("count", parseSelectAll(table)) - }); - }, - max(column) { - return agg("max", [column]); - }, - min(column) { - return agg("min", [column]); - }, - sum(column) { - return agg("sum", [column]); - }, - any(column) { - return fn("any", [column]); - }, - jsonAgg(table) { - return new AggregateFunctionBuilder({ - aggregateFunctionNode: AggregateFunctionNode.create("json_agg", [ - isString2(table) ? parseTable(table) : table.toOperationNode() - ]) - }); - }, - toJson(table) { - return new ExpressionWrapper(FunctionNode.create("to_json", [ - isString2(table) ? parseTable(table) : table.toOperationNode() - ])); - } - }); -} -var init_function_module = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js"() { - init_expression_wrapper(); - init_aggregate_function_node(); - init_function_node(); - init_reference_parser(); - init_select_parser(); - init_aggregate_function_builder(); - init_object_utils(); - init_table_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js -var UnaryOperationNode; -var init_unary_operation_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js"() { - init_object_utils(); - UnaryOperationNode = freeze({ - is(node) { - return node.kind === "UnaryOperationNode"; - }, - create(operator, operand) { - return freeze({ - kind: "UnaryOperationNode", - operator, - operand - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js -function parseUnaryOperation(operator, operand) { - return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand)); -} -var init_unary_operation_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js"() { - init_operator_node(); - init_unary_operation_node(); - init_reference_parser(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js -var CaseNode; -var init_case_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js"() { - init_object_utils(); - init_when_node(); - CaseNode = freeze({ - is(node) { - return node.kind === "CaseNode"; - }, - create(value) { - return freeze({ - kind: "CaseNode", - value - }); - }, - cloneWithWhen(caseNode, when) { - return freeze({ - ...caseNode, - when: freeze(caseNode.when ? [...caseNode.when, when] : [when]) - }); - }, - cloneWithThen(caseNode, then) { - return freeze({ - ...caseNode, - when: caseNode.when ? freeze([ - ...caseNode.when.slice(0, -1), - WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then) - ]) : void 0 - }); - }, - cloneWith(caseNode, props) { - return freeze({ - ...caseNode, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js -var _props18, CaseBuilder, _props19, CaseThenBuilder, _props20, CaseWhenBuilder, _props21, CaseEndBuilder; -var init_case_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js"() { - init_expression_wrapper(); - init_object_utils(); - init_case_node(); - init_when_node(); - init_binary_operation_parser(); - init_value_parser(); - CaseBuilder = class { - constructor(props) { - __privateAdd(this, _props18); - __privateSet(this, _props18, freeze(props)); - } - when(...args) { - return new CaseThenBuilder({ - ...__privateGet(this, _props18), - node: CaseNode.cloneWithWhen(__privateGet(this, _props18).node, WhenNode.create(parseValueBinaryOperationOrExpression(args))) - }); - } - }; - _props18 = new WeakMap(); - CaseThenBuilder = class { - constructor(props) { - __privateAdd(this, _props19); - __privateSet(this, _props19, freeze(props)); - } - then(valueExpression) { - return new CaseWhenBuilder({ - ...__privateGet(this, _props19), - node: CaseNode.cloneWithThen(__privateGet(this, _props19).node, isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression)) - }); - } - }; - _props19 = new WeakMap(); - CaseWhenBuilder = class { - constructor(props) { - __privateAdd(this, _props20); - __privateSet(this, _props20, freeze(props)); - } - when(...args) { - return new CaseThenBuilder({ - ...__privateGet(this, _props20), - node: CaseNode.cloneWithWhen(__privateGet(this, _props20).node, WhenNode.create(parseValueBinaryOperationOrExpression(args))) - }); - } - else(valueExpression) { - return new CaseEndBuilder({ - ...__privateGet(this, _props20), - node: CaseNode.cloneWith(__privateGet(this, _props20).node, { - else: isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression) - }) - }); - } - end() { - return new ExpressionWrapper(CaseNode.cloneWith(__privateGet(this, _props20).node, { isStatement: false })); - } - endCase() { - return new ExpressionWrapper(CaseNode.cloneWith(__privateGet(this, _props20).node, { isStatement: true })); - } - }; - _props20 = new WeakMap(); - CaseEndBuilder = class { - constructor(props) { - __privateAdd(this, _props21); - __privateSet(this, _props21, freeze(props)); - } - end() { - return new ExpressionWrapper(CaseNode.cloneWith(__privateGet(this, _props21).node, { isStatement: false })); - } - endCase() { - return new ExpressionWrapper(CaseNode.cloneWith(__privateGet(this, _props21).node, { isStatement: true })); - } - }; - _props21 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js -var JSONPathLegNode; -var init_json_path_leg_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js"() { - init_object_utils(); - JSONPathLegNode = freeze({ - is(node) { - return node.kind === "JSONPathLegNode"; - }, - create(type, value) { - return freeze({ - kind: "JSONPathLegNode", - type, - value - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js -var _node5, _JSONPathBuilder_instances, createBuilderWithPathLeg_fn, JSONPathBuilder, _node6, _TraversedJSONPathBuilder, TraversedJSONPathBuilder, _jsonPath, _alias4, AliasedJSONPathBuilder; -var init_json_path_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js"() { - init_alias_node(); - init_identifier_node(); - init_json_operator_chain_node(); - init_json_path_leg_node(); - init_json_path_node(); - init_json_reference_node(); - init_operation_node_source(); - init_value_node(); - JSONPathBuilder = class { - constructor(node) { - __privateAdd(this, _JSONPathBuilder_instances); - __privateAdd(this, _node5); - __privateSet(this, _node5, node); - } - /** - * Access an element of a JSON array in a specific location. - * - * Since there's no guarantee an element exists in the given array location, the - * resulting type is always nullable. If you're sure the element exists, you - * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely. - * - * See also {@link key} to access properties of JSON objects. - * - * ### Examples - * - * ```ts - * await db.selectFrom('person') - * .select(eb => - * eb.ref('nicknames', '->').at(0).as('primary_nickname') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "nicknames"->0 as "primary_nickname" from "person" - *``` - * - * Combined with {@link key}: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('experience', '->').at(0).key('role').as('first_role') - * ) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "experience"->0->'role' as "first_role" from "person" - * ``` - * - * You can use `'last'` to access the last element of the array in MySQL: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('nicknames', '->$').at('last').as('last_nickname') - * ) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * select `nicknames`->'$[last]' as `last_nickname` from `person` - * ``` - * - * Or `'#-1'` in SQLite: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname') - * ) - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * select "nicknames"->>'$[#-1]' as `last_nickname` from `person` - * ``` - */ - at(index) { - return __privateMethod(this, _JSONPathBuilder_instances, createBuilderWithPathLeg_fn).call(this, "ArrayLocation", index); - } - /** - * Access a property of a JSON object. - * - * If a field is optional, the resulting type will be nullable. - * - * See also {@link at} to access elements of JSON arrays. - * - * ### Examples - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('address', '->').key('city').as('city') - * ) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "address"->'city' as "city" from "person" - * ``` - * - * Going deeper: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('profile', '->$').key('website').key('url').as('website_url') - * ) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * select `profile`->'$.website.url' as `website_url` from `person` - * ``` - * - * Combined with {@link at}: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city') - * ) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "profile"->'addresses'->0->'city' as "city" from "person" - * ``` - */ - key(key) { - return __privateMethod(this, _JSONPathBuilder_instances, createBuilderWithPathLeg_fn).call(this, "Member", key); - } - }; - _node5 = new WeakMap(); - _JSONPathBuilder_instances = new WeakSet(); - createBuilderWithPathLeg_fn = function(legType, value) { - if (JSONReferenceNode.is(__privateGet(this, _node5))) { - return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(__privateGet(this, _node5), JSONPathNode.is(__privateGet(this, _node5).traversal) ? JSONPathNode.cloneWithLeg(__privateGet(this, _node5).traversal, JSONPathLegNode.create(legType, value)) : JSONOperatorChainNode.cloneWithValue(__privateGet(this, _node5).traversal, ValueNode.createImmediate(value)))); - } - return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(__privateGet(this, _node5), JSONPathLegNode.create(legType, value))); - }; - _TraversedJSONPathBuilder = class _TraversedJSONPathBuilder extends JSONPathBuilder { - constructor(node) { - super(node); - __privateAdd(this, _node6); - __privateSet(this, _node6, node); - } - /** @private */ - get expressionType() { - return void 0; - } - as(alias) { - return new AliasedJSONPathBuilder(this, alias); - } - /** - * Change the output type of the json path. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `JSONPathBuilder` with a new output type. - */ - $castTo() { - return new _TraversedJSONPathBuilder(__privateGet(this, _node6)); - } - $notNull() { - return new _TraversedJSONPathBuilder(__privateGet(this, _node6)); - } - toOperationNode() { - return __privateGet(this, _node6); - } - }; - _node6 = new WeakMap(); - TraversedJSONPathBuilder = _TraversedJSONPathBuilder; - AliasedJSONPathBuilder = class { - constructor(jsonPath, alias) { - __privateAdd(this, _jsonPath); - __privateAdd(this, _alias4); - __privateSet(this, _jsonPath, jsonPath); - __privateSet(this, _alias4, alias); - } - /** @private */ - get expression() { - return __privateGet(this, _jsonPath); - } - /** @private */ - get alias() { - return __privateGet(this, _alias4); - } - toOperationNode() { - return AliasNode.create(__privateGet(this, _jsonPath).toOperationNode(), isOperationNodeSource(__privateGet(this, _alias4)) ? __privateGet(this, _alias4).toOperationNode() : IdentifierNode.create(__privateGet(this, _alias4))); - } - }; - _jsonPath = new WeakMap(); - _alias4 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js -var TupleNode; -var init_tuple_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js"() { - init_object_utils(); - TupleNode = freeze({ - is(node) { - return node.kind === "TupleNode"; - }, - create(values) { - return freeze({ - kind: "TupleNode", - values: freeze(values) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js -function isColumnDataType(dataType) { - if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) { - return true; - } - if (COLUMN_DATA_TYPE_REGEX.some((r) => r.test(dataType))) { - return true; - } - return false; -} -var SIMPLE_COLUMN_DATA_TYPES, COLUMN_DATA_TYPE_REGEX, DataTypeNode; -var init_data_type_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js"() { - init_object_utils(); - SIMPLE_COLUMN_DATA_TYPES = [ - "varchar", - "char", - "text", - "integer", - "int2", - "int4", - "int8", - "smallint", - "bigint", - "boolean", - "real", - "double precision", - "float4", - "float8", - "decimal", - "numeric", - "binary", - "bytea", - "date", - "datetime", - "time", - "timetz", - "timestamp", - "timestamptz", - "serial", - "bigserial", - "uuid", - "json", - "jsonb", - "blob", - "varbinary", - "int4range", - "int4multirange", - "int8range", - "int8multirange", - "numrange", - "nummultirange", - "tsrange", - "tsmultirange", - "tstzrange", - "tstzmultirange", - "daterange", - "datemultirange" - ]; - COLUMN_DATA_TYPE_REGEX = [ - /^varchar\(\d+\)$/, - /^char\(\d+\)$/, - /^decimal\(\d+, \d+\)$/, - /^numeric\(\d+, \d+\)$/, - /^binary\(\d+\)$/, - /^datetime\(\d+\)$/, - /^time\(\d+\)$/, - /^timetz\(\d+\)$/, - /^timestamp\(\d+\)$/, - /^timestamptz\(\d+\)$/, - /^varbinary\(\d+\)$/ - ]; - DataTypeNode = freeze({ - is(node) { - return node.kind === "DataTypeNode"; - }, - create(dataType) { - return freeze({ - kind: "DataTypeNode", - dataType - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js -function parseDataTypeExpression(dataType) { - if (isOperationNodeSource(dataType)) { - return dataType.toOperationNode(); - } - if (isColumnDataType(dataType)) { - return DataTypeNode.create(dataType); - } - throw new Error(`invalid column data type ${JSON.stringify(dataType)}`); -} -var init_data_type_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js"() { - init_data_type_node(); - init_operation_node_source(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js -var CastNode; -var init_cast_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js"() { - init_object_utils(); - CastNode = freeze({ - is(node) { - return node.kind === "CastNode"; - }, - create(expression, dataType) { - return freeze({ - kind: "CastNode", - expression, - dataType - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js -function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) { - function binary2(lhs, op, rhs) { - return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs)); - } - function unary(op, expr) { - return new ExpressionWrapper(parseUnaryOperation(op, expr)); - } - const eb = Object.assign(binary2, { - fn: void 0, - eb: void 0, - selectFrom(table) { - return createSelectQueryBuilder({ - queryId: createQueryId(), - executor, - queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)) - }); - }, - case(reference) { - return new CaseBuilder({ - node: CaseNode.create(isUndefined(reference) ? void 0 : parseReferenceExpression(reference)) - }); - }, - ref(reference, op) { - if (isUndefined(op)) { - return new ExpressionWrapper(parseStringReference(reference)); - } - return new JSONPathBuilder(parseJSONReference(reference, op)); - }, - jsonPath() { - return new JSONPathBuilder(JSONPathNode.create()); - }, - table(table) { - return new ExpressionWrapper(parseTable(table)); - }, - val(value) { - return new ExpressionWrapper(parseValueExpression(value)); - }, - refTuple(...values) { - return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression))); - }, - tuple(...values) { - return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression))); - }, - lit(value) { - return new ExpressionWrapper(parseSafeImmediateValue(value)); - }, - unary, - not(expr) { - return unary("not", expr); - }, - exists(expr) { - return unary("exists", expr); - }, - neg(expr) { - return unary("-", expr); - }, - between(expr, start, end) { - return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between"), AndNode.create(parseValueExpression(start), parseValueExpression(end)))); - }, - betweenSymmetric(expr, start, end) { - return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between symmetric"), AndNode.create(parseValueExpression(start), parseValueExpression(end)))); - }, - and(exprs) { - if (isReadonlyArray(exprs)) { - return new ExpressionWrapper(parseFilterList(exprs, "and")); - } - return new ExpressionWrapper(parseFilterObject(exprs, "and")); - }, - or(exprs) { - if (isReadonlyArray(exprs)) { - return new ExpressionWrapper(parseFilterList(exprs, "or")); - } - return new ExpressionWrapper(parseFilterObject(exprs, "or")); - }, - parens(...args) { - const node = parseValueBinaryOperationOrExpression(args); - if (ParensNode.is(node)) { - return new ExpressionWrapper(node); - } else { - return new ExpressionWrapper(ParensNode.create(node)); - } - }, - cast(expr, dataType) { - return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType))); - }, - withSchema(schema3) { - return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema3))); - } - }); - eb.fn = createFunctionModule(); - eb.eb = eb; - return eb; -} -function expressionBuilder(_) { - return createExpressionBuilder(); -} -var init_expression_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js"() { - init_select_query_builder(); - init_select_query_node(); - init_table_parser(); - init_with_schema_plugin(); - init_query_id(); - init_function_module(); - init_reference_parser(); - init_binary_operation_parser(); - init_parens_node(); - init_expression_wrapper(); - init_operator_node(); - init_unary_operation_parser(); - init_value_parser(); - init_noop_query_executor(); - init_case_builder(); - init_case_node(); - init_object_utils(); - init_json_path_builder(); - init_binary_operation_node(); - init_and_node(); - init_tuple_node(); - init_json_path_node(); - init_data_type_parser(); - init_cast_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js -function parseExpression(exp) { - if (isOperationNodeSource(exp)) { - return exp.toOperationNode(); - } else if (isFunction3(exp)) { - return exp(expressionBuilder()).toOperationNode(); - } - throw new Error(`invalid expression: ${JSON.stringify(exp)}`); -} -function parseAliasedExpression(exp) { - if (isOperationNodeSource(exp)) { - return exp.toOperationNode(); - } else if (isFunction3(exp)) { - return exp(expressionBuilder()).toOperationNode(); - } - throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`); -} -function isExpressionOrFactory(obj) { - return isExpression(obj) || isAliasedExpression(obj) || isFunction3(obj); -} -var init_expression_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js"() { - init_expression(); - init_operation_node_source(); - init_expression_builder(); - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js -function isAliasedDynamicTableBuilder(obj) { - return isObject4(obj) && isOperationNodeSource(obj) && isString2(obj.table) && isString2(obj.alias); -} -var _table, DynamicTableBuilder, _table2, _alias5, AliasedDynamicTableBuilder; -var init_dynamic_table_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js"() { - init_alias_node(); - init_identifier_node(); - init_operation_node_source(); - init_table_parser(); - init_object_utils(); - DynamicTableBuilder = class { - constructor(table) { - __privateAdd(this, _table); - __privateSet(this, _table, table); - } - get table() { - return __privateGet(this, _table); - } - as(alias) { - return new AliasedDynamicTableBuilder(__privateGet(this, _table), alias); - } - }; - _table = new WeakMap(); - AliasedDynamicTableBuilder = class { - constructor(table, alias) { - __privateAdd(this, _table2); - __privateAdd(this, _alias5); - __privateSet(this, _table2, table); - __privateSet(this, _alias5, alias); - } - get table() { - return __privateGet(this, _table2); - } - get alias() { - return __privateGet(this, _alias5); - } - toOperationNode() { - return AliasNode.create(parseTable(__privateGet(this, _table2)), IdentifierNode.create(__privateGet(this, _alias5))); - } - }; - _table2 = new WeakMap(); - _alias5 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js -function parseTableExpressionOrList(table) { - if (isReadonlyArray(table)) { - return table.map((it) => parseTableExpression(it)); - } else { - return [parseTableExpression(table)]; - } -} -function parseTableExpression(table) { - if (isString2(table)) { - return parseAliasedTable(table); - } else if (isAliasedDynamicTableBuilder(table)) { - return table.toOperationNode(); - } else { - return parseAliasedExpression(table); - } -} -function parseAliasedTable(from) { - const ALIAS_SEPARATOR = " as "; - if (from.includes(ALIAS_SEPARATOR)) { - const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim2); - return AliasNode.create(parseTable(table), IdentifierNode.create(alias)); - } else { - return parseTable(from); - } -} -function parseTable(from) { - const SCHEMA_SEPARATOR = "."; - if (from.includes(SCHEMA_SEPARATOR)) { - const [schema3, table] = from.split(SCHEMA_SEPARATOR).map(trim2); - return TableNode.createWithSchema(schema3, table); - } else { - return TableNode.create(from); - } -} -function trim2(str) { - return str.trim(); -} -var init_table_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js"() { - init_object_utils(); - init_alias_node(); - init_table_node(); - init_expression_parser(); - init_identifier_node(); - init_dynamic_table_builder(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js -var AddColumnNode; -var init_add_column_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js"() { - init_object_utils(); - AddColumnNode = freeze({ - is(node) { - return node.kind === "AddColumnNode"; - }, - create(column) { - return freeze({ - kind: "AddColumnNode", - column - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js -var ColumnDefinitionNode; -var init_column_definition_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js"() { - init_object_utils(); - init_column_node(); - ColumnDefinitionNode = freeze({ - is(node) { - return node.kind === "ColumnDefinitionNode"; - }, - create(column, dataType) { - return freeze({ - kind: "ColumnDefinitionNode", - column: ColumnNode.create(column), - dataType - }); - }, - cloneWithFrontModifier(node, modifier) { - return freeze({ - ...node, - frontModifiers: node.frontModifiers ? freeze([...node.frontModifiers, modifier]) : [modifier] - }); - }, - cloneWithEndModifier(node, modifier) { - return freeze({ - ...node, - endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : [modifier] - }); - }, - cloneWith(node, props) { - return freeze({ - ...node, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js -var DropColumnNode; -var init_drop_column_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js"() { - init_object_utils(); - init_column_node(); - DropColumnNode = freeze({ - is(node) { - return node.kind === "DropColumnNode"; - }, - create(column) { - return freeze({ - kind: "DropColumnNode", - column: ColumnNode.create(column) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js -var RenameColumnNode; -var init_rename_column_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js"() { - init_object_utils(); - init_column_node(); - RenameColumnNode = freeze({ - is(node) { - return node.kind === "RenameColumnNode"; - }, - create(column, newColumn) { - return freeze({ - kind: "RenameColumnNode", - column: ColumnNode.create(column), - renameTo: ColumnNode.create(newColumn) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js -var CheckConstraintNode; -var init_check_constraint_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js"() { - init_object_utils(); - init_identifier_node(); - CheckConstraintNode = freeze({ - is(node) { - return node.kind === "CheckConstraintNode"; - }, - create(expression, constraintName) { - return freeze({ - kind: "CheckConstraintNode", - expression, - name: constraintName ? IdentifierNode.create(constraintName) : void 0 - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js -var ON_MODIFY_FOREIGN_ACTIONS, ReferencesNode; -var init_references_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js"() { - init_object_utils(); - ON_MODIFY_FOREIGN_ACTIONS = [ - "no action", - "restrict", - "cascade", - "set null", - "set default" - ]; - ReferencesNode = freeze({ - is(node) { - return node.kind === "ReferencesNode"; - }, - create(table, columns) { - return freeze({ - kind: "ReferencesNode", - table, - columns: freeze([...columns]) - }); - }, - cloneWithOnDelete(references, onDelete) { - return freeze({ - ...references, - onDelete - }); - }, - cloneWithOnUpdate(references, onUpdate) { - return freeze({ - ...references, - onUpdate - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js -function parseDefaultValueExpression(value) { - return isOperationNodeSource(value) ? value.toOperationNode() : ValueNode.createImmediate(value); -} -var init_default_value_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js"() { - init_operation_node_source(); - init_value_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js -var GeneratedNode; -var init_generated_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js"() { - init_object_utils(); - GeneratedNode = freeze({ - is(node) { - return node.kind === "GeneratedNode"; - }, - create(params) { - return freeze({ - kind: "GeneratedNode", - ...params - }); - }, - createWithExpression(expression) { - return freeze({ - kind: "GeneratedNode", - always: true, - expression - }); - }, - cloneWith(node, params) { - return freeze({ - ...node, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js -var DefaultValueNode; -var init_default_value_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js"() { - init_object_utils(); - DefaultValueNode = freeze({ - is(node) { - return node.kind === "DefaultValueNode"; - }, - create(defaultValue) { - return freeze({ - kind: "DefaultValueNode", - defaultValue - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js -function parseOnModifyForeignAction(action) { - if (ON_MODIFY_FOREIGN_ACTIONS.includes(action)) { - return action; - } - throw new Error(`invalid OnModifyForeignAction ${action}`); -} -var init_on_modify_action_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js"() { - init_references_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js -var _node7, _ColumnDefinitionBuilder, ColumnDefinitionBuilder; -var init_column_definition_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js"() { - init_check_constraint_node(); - init_references_node(); - init_select_all_node(); - init_reference_parser(); - init_column_definition_node(); - init_default_value_parser(); - init_generated_node(); - init_default_value_node(); - init_on_modify_action_parser(); - _ColumnDefinitionBuilder = class _ColumnDefinitionBuilder { - constructor(node) { - __privateAdd(this, _node7); - __privateSet(this, _node7, node); - } - /** - * Adds `auto_increment` or `autoincrement` to the column definition - * depending on the dialect. - * - * Some dialects like PostgreSQL don't support this. On PostgreSQL - * you can use the `serial` or `bigserial` data type instead. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.autoIncrement().primaryKey()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key auto_increment - * ) - * ``` - */ - autoIncrement() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { autoIncrement: true })); - } - /** - * Makes the column an identity column. - * - * This only works on some dialects like MS SQL Server (MSSQL). - * - * For PostgreSQL's `generated always as identity` use {@link generatedAlwaysAsIdentity}. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.identity().primaryKey()) - * .execute() - * ``` - * - * The generated SQL (MSSQL): - * - * ```sql - * create table "person" ( - * "id" integer identity primary key - * ) - * ``` - */ - identity() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { identity: true })); - } - /** - * Makes the column the primary key. - * - * If you want to specify a composite primary key use the - * {@link CreateTableBuilder.addPrimaryKeyConstraint} method. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key - * ) - */ - primaryKey() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { primaryKey: true })); - } - /** - * Adds a foreign key constraint for the column. - * - * If your database engine doesn't support foreign key constraints in the - * column definition (like MySQL 5) you need to call the table level - * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('owner_id', 'integer', (col) => col.references('person.id')) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "pet" ( - * "owner_id" integer references "person" ("id") - * ) - * ``` - */ - references(ref) { - const references = parseStringReference(ref); - if (!references.table || SelectAllNode.is(references.column)) { - throw new Error(`invalid call references('${ref}'). The reference must have format table.column or schema.table.column`); - } - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - references: ReferencesNode.create(references.table, [ - references.column - ]) - })); - } - /** - * Adds an `on delete` constraint for the foreign key column. - * - * If your database engine doesn't support foreign key constraints in the - * column definition (like MySQL 5) you need to call the table level - * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn( - * 'owner_id', - * 'integer', - * (col) => col.references('person.id').onDelete('cascade') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "pet" ( - * "owner_id" integer references "person" ("id") on delete cascade - * ) - * ``` - */ - onDelete(onDelete) { - if (!__privateGet(this, _node7).references) { - throw new Error("on delete constraint can only be added for foreign keys"); - } - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - references: ReferencesNode.cloneWithOnDelete(__privateGet(this, _node7).references, parseOnModifyForeignAction(onDelete)) - })); - } - /** - * Adds an `on update` constraint for the foreign key column. - * - * If your database engine doesn't support foreign key constraints in the - * column definition (like MySQL 5) you need to call the table level - * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn( - * 'owner_id', - * 'integer', - * (col) => col.references('person.id').onUpdate('cascade') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "pet" ( - * "owner_id" integer references "person" ("id") on update cascade - * ) - * ``` - */ - onUpdate(onUpdate) { - if (!__privateGet(this, _node7).references) { - throw new Error("on update constraint can only be added for foreign keys"); - } - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - references: ReferencesNode.cloneWithOnUpdate(__privateGet(this, _node7).references, parseOnModifyForeignAction(onUpdate)) - })); - } - /** - * Adds a unique constraint for the column. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('email', 'varchar(255)', col => col.unique()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `email` varchar(255) unique - * ) - * ``` - */ - unique() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { unique: true })); - } - /** - * Adds a `not null` constraint for the column. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('first_name', 'varchar(255)', col => col.notNull()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `first_name` varchar(255) not null - * ) - * ``` - */ - notNull() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { notNull: true })); - } - /** - * Adds a `unsigned` modifier for the column. - * - * This only works on some dialects like MySQL. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('age', 'integer', col => col.unsigned()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `age` integer unsigned - * ) - * ``` - */ - unsigned() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { unsigned: true })); - } - /** - * Adds a default value constraint for the column. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('number_of_legs', 'integer', (col) => col.defaultTo(4)) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `pet` ( - * `number_of_legs` integer default 4 - * ) - * ``` - * - * Values passed to `defaultTo` are interpreted as value literals by default. You can define - * an arbitrary SQL expression using the {@link sql} template tag: - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('pet') - * .addColumn( - * 'created_at', - * 'timestamp', - * (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`) - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `pet` ( - * `created_at` timestamp default CURRENT_TIMESTAMP - * ) - * ``` - */ - defaultTo(value) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - defaultTo: DefaultValueNode.create(parseDefaultValueExpression(value)) - })); - } - /** - * Adds a check constraint for the column. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('pet') - * .addColumn('number_of_legs', 'integer', (col) => - * col.check(sql`number_of_legs < 5`) - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `pet` ( - * `number_of_legs` integer check (number_of_legs < 5) - * ) - * ``` - */ - check(expression) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - check: CheckConstraintNode.create(expression.toOperationNode()) - })); - } - /** - * Makes the column a generated column using a `generated always as` statement. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('full_name', 'varchar(255)', - * (col) => col.generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`) - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) - * ) - * ``` - */ - generatedAlwaysAs(expression) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - generated: GeneratedNode.createWithExpression(expression.toOperationNode()) - })); - } - /** - * Adds the `generated always as identity` specifier. - * - * This only works on some dialects like PostgreSQL. - * - * For MS SQL Server (MSSQL)'s identity column use {@link identity}. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.generatedAlwaysAsIdentity().primaryKey()) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "person" ( - * "id" integer generated always as identity primary key - * ) - * ``` - */ - generatedAlwaysAsIdentity() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - generated: GeneratedNode.create({ identity: true, always: true }) - })); - } - /** - * Adds the `generated by default as identity` specifier on supported dialects. - * - * This only works on some dialects like PostgreSQL. - * - * For MS SQL Server (MSSQL)'s identity column use {@link identity}. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.generatedByDefaultAsIdentity().primaryKey()) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "person" ( - * "id" integer generated by default as identity primary key - * ) - * ``` - */ - generatedByDefaultAsIdentity() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - generated: GeneratedNode.create({ identity: true, byDefault: true }) - })); - } - /** - * Makes a generated column stored instead of virtual. This method can only - * be used with {@link generatedAlwaysAs} - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('full_name', 'varchar(255)', (col) => col - * .generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`) - * .stored() - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) stored - * ) - * ``` - */ - stored() { - if (!__privateGet(this, _node7).generated) { - throw new Error("stored() can only be called after generatedAlwaysAs"); - } - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { - generated: GeneratedNode.cloneWith(__privateGet(this, _node7).generated, { - stored: true - }) - })); - } - /** - * This can be used to add any additional SQL right after the column's data type. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn( - * 'first_name', - * 'varchar(36)', - * (col) => col.modifyFront(sql`collate utf8mb4_general_ci`).notNull() - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key, - * `first_name` varchar(36) collate utf8mb4_general_ci not null - * ) - * ``` - */ - modifyFront(modifier) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(__privateGet(this, _node7), modifier.toOperationNode())); - } - /** - * Adds `nulls not distinct` specifier. - * Should be used with `unique` constraint. - * - * This only works on some dialects like PostgreSQL. - * - * ### Examples - * - * ```ts - * db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn('first_name', 'varchar(30)', col => col.unique().nullsNotDistinct()) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "person" ( - * "id" integer primary key, - * "first_name" varchar(30) unique nulls not distinct - * ) - * ``` - */ - nullsNotDistinct() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { nullsNotDistinct: true })); - } - /** - * Adds `if not exists` specifier. This only works for PostgreSQL. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .addColumn('email', 'varchar(255)', col => col.unique().ifNotExists()) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * alter table "person" add column if not exists "email" varchar(255) unique - * ``` - */ - ifNotExists() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(__privateGet(this, _node7), { ifNotExists: true })); - } - /** - * This can be used to add any additional SQL to the end of the column definition. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn( - * 'age', - * 'integer', - * col => col.unsigned() - * .notNull() - * .modifyEnd(sql`comment ${sql.lit('it is not polite to ask a woman her age')}`) - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key, - * `age` integer unsigned not null comment 'it is not polite to ask a woman her age' - * ) - * ``` - */ - modifyEnd(modifier) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(__privateGet(this, _node7), modifier.toOperationNode())); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _node7); - } - }; - _node7 = new WeakMap(); - ColumnDefinitionBuilder = _ColumnDefinitionBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js -var ModifyColumnNode; -var init_modify_column_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js"() { - init_object_utils(); - ModifyColumnNode = freeze({ - is(node) { - return node.kind === "ModifyColumnNode"; - }, - create(column) { - return freeze({ - kind: "ModifyColumnNode", - column - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js -var ForeignKeyConstraintNode; -var init_foreign_key_constraint_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js"() { - init_object_utils(); - init_identifier_node(); - init_references_node(); - ForeignKeyConstraintNode = freeze({ - is(node) { - return node.kind === "ForeignKeyConstraintNode"; - }, - create(sourceColumns, targetTable, targetColumns, constraintName) { - return freeze({ - kind: "ForeignKeyConstraintNode", - columns: sourceColumns, - references: ReferencesNode.create(targetTable, targetColumns), - name: constraintName ? IdentifierNode.create(constraintName) : void 0 - }); - }, - cloneWith(node, props) { - return freeze({ - ...node, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js -var _node8, _ForeignKeyConstraintBuilder, ForeignKeyConstraintBuilder; -var init_foreign_key_constraint_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js"() { - init_foreign_key_constraint_node(); - init_on_modify_action_parser(); - _ForeignKeyConstraintBuilder = class _ForeignKeyConstraintBuilder { - constructor(node) { - __privateAdd(this, _node8); - __privateSet(this, _node8, node); - } - onDelete(onDelete) { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { - onDelete: parseOnModifyForeignAction(onDelete) - })); - } - onUpdate(onUpdate) { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { - onUpdate: parseOnModifyForeignAction(onUpdate) - })); - } - deferrable() { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { deferrable: true })); - } - notDeferrable() { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { deferrable: false })); - } - initiallyDeferred() { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { - initiallyDeferred: true - })); - } - initiallyImmediate() { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(__privateGet(this, _node8), { - initiallyDeferred: false - })); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _node8); - } - }; - _node8 = new WeakMap(); - ForeignKeyConstraintBuilder = _ForeignKeyConstraintBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js -var AddConstraintNode; -var init_add_constraint_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js"() { - init_object_utils(); - AddConstraintNode = freeze({ - is(node) { - return node.kind === "AddConstraintNode"; - }, - create(constraint) { - return freeze({ - kind: "AddConstraintNode", - constraint - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js -var UniqueConstraintNode; -var init_unique_constraint_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js"() { - init_object_utils(); - init_column_node(); - init_identifier_node(); - UniqueConstraintNode = freeze({ - is(node) { - return node.kind === "UniqueConstraintNode"; - }, - create(columns, constraintName, nullsNotDistinct) { - return freeze({ - kind: "UniqueConstraintNode", - columns: freeze(columns.map(ColumnNode.create)), - name: constraintName ? IdentifierNode.create(constraintName) : void 0, - nullsNotDistinct - }); - }, - cloneWith(node, props) { - return freeze({ - ...node, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js -var DropConstraintNode; -var init_drop_constraint_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js"() { - init_object_utils(); - init_identifier_node(); - DropConstraintNode = freeze({ - is(node) { - return node.kind === "DropConstraintNode"; - }, - create(constraintName) { - return freeze({ - kind: "DropConstraintNode", - constraintName: IdentifierNode.create(constraintName) - }); - }, - cloneWith(dropConstraint, props) { - return freeze({ - ...dropConstraint, - ...props - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js -var AlterColumnNode; -var init_alter_column_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js"() { - init_object_utils(); - init_column_node(); - AlterColumnNode = freeze({ - is(node) { - return node.kind === "AlterColumnNode"; - }, - create(column, prop, value) { - return freeze({ - kind: "AlterColumnNode", - column: ColumnNode.create(column), - [prop]: value - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js -var _column, AlterColumnBuilder, _alterColumnNode, AlteredColumnBuilder; -var init_alter_column_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js"() { - init_alter_column_node(); - init_data_type_parser(); - init_default_value_parser(); - AlterColumnBuilder = class { - constructor(column) { - __privateAdd(this, _column); - __privateSet(this, _column, column); - } - setDataType(dataType) { - return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "dataType", parseDataTypeExpression(dataType))); - } - setDefault(value) { - return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "setDefault", parseDefaultValueExpression(value))); - } - dropDefault() { - return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "dropDefault", true)); - } - setNotNull() { - return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "setNotNull", true)); - } - dropNotNull() { - return new AlteredColumnBuilder(AlterColumnNode.create(__privateGet(this, _column), "dropNotNull", true)); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - }; - _column = new WeakMap(); - AlteredColumnBuilder = class { - constructor(alterColumnNode) { - __privateAdd(this, _alterColumnNode); - __privateSet(this, _alterColumnNode, alterColumnNode); - } - toOperationNode() { - return __privateGet(this, _alterColumnNode); - } - }; - _alterColumnNode = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js -var _props22, AlterTableExecutor; -var init_alter_table_executor = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js"() { - init_object_utils(); - AlterTableExecutor = class { - constructor(props) { - __privateAdd(this, _props22); - __privateSet(this, _props22, freeze(props)); - } - toOperationNode() { - return __privateGet(this, _props22).executor.transformQuery(__privateGet(this, _props22).node, __privateGet(this, _props22).queryId); - } - compile() { - return __privateGet(this, _props22).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props22).queryId); - } - async execute() { - await __privateGet(this, _props22).executor.executeQuery(this.compile()); - } - }; - _props22 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js -var _props23, _AlterTableAddForeignKeyConstraintBuilder, AlterTableAddForeignKeyConstraintBuilder; -var init_alter_table_add_foreign_key_constraint_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js"() { - init_add_constraint_node(); - init_alter_table_node(); - init_object_utils(); - _AlterTableAddForeignKeyConstraintBuilder = class _AlterTableAddForeignKeyConstraintBuilder { - constructor(props) { - __privateAdd(this, _props23); - __privateSet(this, _props23, freeze(props)); - } - onDelete(onDelete) { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...__privateGet(this, _props23), - constraintBuilder: __privateGet(this, _props23).constraintBuilder.onDelete(onDelete) - }); - } - onUpdate(onUpdate) { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...__privateGet(this, _props23), - constraintBuilder: __privateGet(this, _props23).constraintBuilder.onUpdate(onUpdate) - }); - } - deferrable() { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...__privateGet(this, _props23), - constraintBuilder: __privateGet(this, _props23).constraintBuilder.deferrable() - }); - } - notDeferrable() { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...__privateGet(this, _props23), - constraintBuilder: __privateGet(this, _props23).constraintBuilder.notDeferrable() - }); - } - initiallyDeferred() { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...__privateGet(this, _props23), - constraintBuilder: __privateGet(this, _props23).constraintBuilder.initiallyDeferred() - }); - } - initiallyImmediate() { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...__privateGet(this, _props23), - constraintBuilder: __privateGet(this, _props23).constraintBuilder.initiallyImmediate() - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props23).executor.transformQuery(AlterTableNode.cloneWithTableProps(__privateGet(this, _props23).node, { - addConstraint: AddConstraintNode.create(__privateGet(this, _props23).constraintBuilder.toOperationNode()) - }), __privateGet(this, _props23).queryId); - } - compile() { - return __privateGet(this, _props23).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props23).queryId); - } - async execute() { - await __privateGet(this, _props23).executor.executeQuery(this.compile()); - } - }; - _props23 = new WeakMap(); - AlterTableAddForeignKeyConstraintBuilder = _AlterTableAddForeignKeyConstraintBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js -var _props24, _AlterTableDropConstraintBuilder, AlterTableDropConstraintBuilder; -var init_alter_table_drop_constraint_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js"() { - init_alter_table_node(); - init_drop_constraint_node(); - init_object_utils(); - _AlterTableDropConstraintBuilder = class _AlterTableDropConstraintBuilder { - constructor(props) { - __privateAdd(this, _props24); - __privateSet(this, _props24, freeze(props)); - } - ifExists() { - return new _AlterTableDropConstraintBuilder({ - ...__privateGet(this, _props24), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props24).node, { - dropConstraint: DropConstraintNode.cloneWith(__privateGet(this, _props24).node.dropConstraint, { - ifExists: true - }) - }) - }); - } - cascade() { - return new _AlterTableDropConstraintBuilder({ - ...__privateGet(this, _props24), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props24).node, { - dropConstraint: DropConstraintNode.cloneWith(__privateGet(this, _props24).node.dropConstraint, { - modifier: "cascade" - }) - }) - }); - } - restrict() { - return new _AlterTableDropConstraintBuilder({ - ...__privateGet(this, _props24), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props24).node, { - dropConstraint: DropConstraintNode.cloneWith(__privateGet(this, _props24).node.dropConstraint, { - modifier: "restrict" - }) - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props24).executor.transformQuery(__privateGet(this, _props24).node, __privateGet(this, _props24).queryId); - } - compile() { - return __privateGet(this, _props24).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props24).queryId); - } - async execute() { - await __privateGet(this, _props24).executor.executeQuery(this.compile()); - } - }; - _props24 = new WeakMap(); - AlterTableDropConstraintBuilder = _AlterTableDropConstraintBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js -var PrimaryKeyConstraintNode; -var init_primary_key_constraint_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js"() { - init_object_utils(); - init_column_node(); - init_identifier_node(); - PrimaryKeyConstraintNode = freeze({ - is(node) { - return node.kind === "PrimaryKeyConstraintNode"; - }, - create(columns, constraintName) { - return freeze({ - kind: "PrimaryKeyConstraintNode", - columns: freeze(columns.map(ColumnNode.create)), - name: constraintName ? IdentifierNode.create(constraintName) : void 0 - }); - }, - cloneWith(node, props) { - return freeze({ ...node, ...props }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js -var AddIndexNode; -var init_add_index_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js"() { - init_object_utils(); - init_identifier_node(); - AddIndexNode = freeze({ - is(node) { - return node.kind === "AddIndexNode"; - }, - create(name) { - return freeze({ - kind: "AddIndexNode", - name: IdentifierNode.create(name) - }); - }, - cloneWith(node, props) { - return freeze({ - ...node, - ...props - }); - }, - cloneWithColumns(node, columns) { - return freeze({ - ...node, - columns: [...node.columns || [], ...columns] - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js -var _props25, _AlterTableAddIndexBuilder, AlterTableAddIndexBuilder; -var init_alter_table_add_index_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js"() { - init_add_index_node(); - init_alter_table_node(); - init_raw_node(); - init_reference_parser(); - init_object_utils(); - _AlterTableAddIndexBuilder = class _AlterTableAddIndexBuilder { - constructor(props) { - __privateAdd(this, _props25); - __privateSet(this, _props25, freeze(props)); - } - /** - * Makes the index unique. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .addIndex('person_first_name_index') - * .unique() - * .column('email') - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add unique index `person_first_name_index` (`email`) - * ``` - */ - unique() { - return new _AlterTableAddIndexBuilder({ - ...__privateGet(this, _props25), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { - addIndex: AddIndexNode.cloneWith(__privateGet(this, _props25).node.addIndex, { - unique: true - }) - }) - }); - } - /** - * Adds a column to the index. - * - * Also see {@link columns} for adding multiple columns at once or {@link expression} - * for specifying an arbitrary expression. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .addIndex('person_first_name_and_age_index') - * .column('first_name') - * .column('age desc') - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc) - * ``` - */ - column(column) { - return new _AlterTableAddIndexBuilder({ - ...__privateGet(this, _props25), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { - addIndex: AddIndexNode.cloneWithColumns(__privateGet(this, _props25).node.addIndex, [ - parseOrderedColumnName(column) - ]) - }) - }); - } - /** - * Specifies a list of columns for the index. - * - * Also see {@link column} for adding a single column or {@link expression} for - * specifying an arbitrary expression. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .addIndex('person_first_name_and_age_index') - * .columns(['first_name', 'age desc']) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc) - * ``` - */ - columns(columns) { - return new _AlterTableAddIndexBuilder({ - ...__privateGet(this, _props25), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { - addIndex: AddIndexNode.cloneWithColumns(__privateGet(this, _props25).node.addIndex, columns.map(parseOrderedColumnName)) - }) - }); - } - /** - * Specifies an arbitrary expression for the index. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .alterTable('person') - * .addIndex('person_first_name_index') - * .expression(sql`(first_name < 'Sami')`) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add index `person_first_name_index` ((first_name < 'Sami')) - * ``` - */ - expression(expression) { - return new _AlterTableAddIndexBuilder({ - ...__privateGet(this, _props25), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { - addIndex: AddIndexNode.cloneWithColumns(__privateGet(this, _props25).node.addIndex, [ - expression.toOperationNode() - ]) - }) - }); - } - using(indexType) { - return new _AlterTableAddIndexBuilder({ - ...__privateGet(this, _props25), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props25).node, { - addIndex: AddIndexNode.cloneWith(__privateGet(this, _props25).node.addIndex, { - using: RawNode.createWithSql(indexType) - }) - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props25).executor.transformQuery(__privateGet(this, _props25).node, __privateGet(this, _props25).queryId); - } - compile() { - return __privateGet(this, _props25).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props25).queryId); - } - async execute() { - await __privateGet(this, _props25).executor.executeQuery(this.compile()); - } - }; - _props25 = new WeakMap(); - AlterTableAddIndexBuilder = _AlterTableAddIndexBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js -var _node9, _UniqueConstraintNodeBuilder, UniqueConstraintNodeBuilder; -var init_unique_constraint_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js"() { - init_unique_constraint_node(); - _UniqueConstraintNodeBuilder = class _UniqueConstraintNodeBuilder { - constructor(node) { - __privateAdd(this, _node9); - __privateSet(this, _node9, node); - } - /** - * Adds `nulls not distinct` to the unique constraint definition - * - * Supported by PostgreSQL dialect only - */ - nullsNotDistinct() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { nullsNotDistinct: true })); - } - deferrable() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { deferrable: true })); - } - notDeferrable() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { deferrable: false })); - } - initiallyDeferred() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { - initiallyDeferred: true - })); - } - initiallyImmediate() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(__privateGet(this, _node9), { - initiallyDeferred: false - })); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _node9); - } - }; - _node9 = new WeakMap(); - UniqueConstraintNodeBuilder = _UniqueConstraintNodeBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js -var _node10, _PrimaryKeyConstraintBuilder, PrimaryKeyConstraintBuilder; -var init_primary_key_constraint_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js"() { - init_primary_key_constraint_node(); - _PrimaryKeyConstraintBuilder = class _PrimaryKeyConstraintBuilder { - constructor(node) { - __privateAdd(this, _node10); - __privateSet(this, _node10, node); - } - deferrable() { - return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(__privateGet(this, _node10), { deferrable: true })); - } - notDeferrable() { - return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(__privateGet(this, _node10), { deferrable: false })); - } - initiallyDeferred() { - return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(__privateGet(this, _node10), { - initiallyDeferred: true - })); - } - initiallyImmediate() { - return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(__privateGet(this, _node10), { - initiallyDeferred: false - })); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _node10); - } - }; - _node10 = new WeakMap(); - PrimaryKeyConstraintBuilder = _PrimaryKeyConstraintBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js -var _node11, CheckConstraintBuilder; -var init_check_constraint_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js"() { - CheckConstraintBuilder = class { - constructor(node) { - __privateAdd(this, _node11); - __privateSet(this, _node11, node); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _node11); - } - }; - _node11 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js -var RenameConstraintNode; -var init_rename_constraint_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js"() { - init_object_utils(); - init_identifier_node(); - RenameConstraintNode = freeze({ - is(node) { - return node.kind === "RenameConstraintNode"; - }, - create(oldName, newName) { - return freeze({ - kind: "RenameConstraintNode", - oldName: IdentifierNode.create(oldName), - newName: IdentifierNode.create(newName) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js -var _props26, AlterTableBuilder, _props27, _AlterTableColumnAlteringBuilder, AlterTableColumnAlteringBuilder; -var init_alter_table_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js"() { - init_add_column_node(); - init_alter_table_node(); - init_column_definition_node(); - init_drop_column_node(); - init_identifier_node(); - init_rename_column_node(); - init_object_utils(); - init_column_definition_builder(); - init_modify_column_node(); - init_data_type_parser(); - init_foreign_key_constraint_builder(); - init_add_constraint_node(); - init_unique_constraint_node(); - init_check_constraint_node(); - init_foreign_key_constraint_node(); - init_column_node(); - init_table_parser(); - init_drop_constraint_node(); - init_alter_column_builder(); - init_alter_table_executor(); - init_alter_table_add_foreign_key_constraint_builder(); - init_alter_table_drop_constraint_builder(); - init_primary_key_constraint_node(); - init_drop_index_node(); - init_add_index_node(); - init_alter_table_add_index_builder(); - init_unique_constraint_builder(); - init_primary_key_constraint_builder(); - init_check_constraint_builder(); - init_rename_constraint_node(); - AlterTableBuilder = class { - constructor(props) { - __privateAdd(this, _props26); - __privateSet(this, _props26, freeze(props)); - } - renameTo(newTableName) { - return new AlterTableExecutor({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - renameTo: parseTable(newTableName) - }) - }); - } - setSchema(newSchema) { - return new AlterTableExecutor({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - setSchema: IdentifierNode.create(newSchema) - }) - }); - } - alterColumn(column, alteration) { - const builder = alteration(new AlterColumnBuilder(column)); - return new AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, builder.toOperationNode()) - }); - } - dropColumn(column) { - return new AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, DropColumnNode.create(column)) - }); - } - renameColumn(column, newColumn) { - return new AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, RenameColumnNode.create(column, newColumn)) - }); - } - addColumn(columnName, dataType, build = noop) { - const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, AddColumnNode.create(builder.toOperationNode())) - }); - } - modifyColumn(columnName, dataType, build = noop) { - const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props26).node, ModifyColumnNode.create(builder.toOperationNode())) - }); - } - /** - * See {@link CreateTableBuilder.addUniqueConstraint} - */ - addUniqueConstraint(constraintName, columns, build = noop) { - const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName))); - return new AlterTableExecutor({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - addConstraint: AddConstraintNode.create(uniqueConstraintBuilder.toOperationNode()) - }) - }); - } - /** - * See {@link CreateTableBuilder.addCheckConstraint} - */ - addCheckConstraint(constraintName, checkExpression, build = noop) { - const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName))); - return new AlterTableExecutor({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) - }) - }); - } - /** - * See {@link CreateTableBuilder.addForeignKeyConstraint} - * - * Unlike {@link CreateTableBuilder.addForeignKeyConstraint} this method returns - * the constraint builder and doesn't take a callback as the last argument. This - * is because you can only add one column per `ALTER TABLE` query. - */ - addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) { - const constraintBuilder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName))); - return new AlterTableAddForeignKeyConstraintBuilder({ - ...__privateGet(this, _props26), - constraintBuilder - }); - } - /** - * See {@link CreateTableBuilder.addPrimaryKeyConstraint} - */ - addPrimaryKeyConstraint(constraintName, columns, build = noop) { - const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName))); - return new AlterTableExecutor({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) - }) - }); - } - dropConstraint(constraintName) { - return new AlterTableDropConstraintBuilder({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - dropConstraint: DropConstraintNode.create(constraintName) - }) - }); - } - renameConstraint(oldName, newName) { - return new AlterTableDropConstraintBuilder({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - renameConstraint: RenameConstraintNode.create(oldName, newName) - }) - }); - } - /** - * This can be used to add index to table. - * - * ### Examples - * - * ```ts - * db.schema.alterTable('person') - * .addIndex('person_email_index') - * .column('email') - * .unique() - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add unique index `person_email_index` (`email`) - * ``` - */ - addIndex(indexName) { - return new AlterTableAddIndexBuilder({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - addIndex: AddIndexNode.create(indexName) - }) - }); - } - /** - * This can be used to drop index from table. - * - * ### Examples - * - * ```ts - * db.schema.alterTable('person') - * .dropIndex('person_email_index') - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` drop index `test_first_name_index` - * ``` - */ - dropIndex(indexName) { - return new AlterTableExecutor({ - ...__privateGet(this, _props26), - node: AlterTableNode.cloneWithTableProps(__privateGet(this, _props26).node, { - dropIndex: DropIndexNode.create(indexName) - }) - }); - } - /** - * Calls the given function passing `this` as the only argument. - * - * See {@link CreateTableBuilder.$call} - */ - $call(func) { - return func(this); - } - }; - _props26 = new WeakMap(); - _AlterTableColumnAlteringBuilder = class _AlterTableColumnAlteringBuilder { - constructor(props) { - __privateAdd(this, _props27); - __privateSet(this, _props27, freeze(props)); - } - alterColumn(column, alteration) { - const builder = alteration(new AlterColumnBuilder(column)); - return new _AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props27), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, builder.toOperationNode()) - }); - } - dropColumn(column) { - return new _AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props27), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, DropColumnNode.create(column)) - }); - } - renameColumn(column, newColumn) { - return new _AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props27), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, RenameColumnNode.create(column, newColumn)) - }); - } - addColumn(columnName, dataType, build = noop) { - const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new _AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props27), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, AddColumnNode.create(builder.toOperationNode())) - }); - } - modifyColumn(columnName, dataType, build = noop) { - const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new _AlterTableColumnAlteringBuilder({ - ...__privateGet(this, _props27), - node: AlterTableNode.cloneWithColumnAlteration(__privateGet(this, _props27).node, ModifyColumnNode.create(builder.toOperationNode())) - }); - } - toOperationNode() { - return __privateGet(this, _props27).executor.transformQuery(__privateGet(this, _props27).node, __privateGet(this, _props27).queryId); - } - compile() { - return __privateGet(this, _props27).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props27).queryId); - } - async execute() { - await __privateGet(this, _props27).executor.executeQuery(this.compile()); - } - }; - _props27 = new WeakMap(); - AlterTableColumnAlteringBuilder = _AlterTableColumnAlteringBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js -var ImmediateValueTransformer; -var init_immediate_value_transformer = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js"() { - init_operation_node_transformer(); - init_value_list_node(); - init_value_node(); - ImmediateValueTransformer = class extends OperationNodeTransformer { - transformPrimitiveValueList(node) { - return ValueListNode.create(node.values.map(ValueNode.createImmediate)); - } - transformValue(node) { - return ValueNode.createImmediate(node.value); - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js -var _props28, _CreateIndexBuilder, CreateIndexBuilder; -var init_create_index_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js"() { - init_create_index_node(); - init_raw_node(); - init_reference_parser(); - init_table_parser(); - init_object_utils(); - init_binary_operation_parser(); - init_query_node(); - init_immediate_value_transformer(); - _CreateIndexBuilder = class _CreateIndexBuilder { - constructor(props) { - __privateAdd(this, _props28); - __privateSet(this, _props28, freeze(props)); - } - /** - * Adds the "if not exists" modifier. - * - * If the index already exists, no error is thrown if this method has been called. - */ - ifNotExists() { - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { - ifNotExists: true - }) - }); - } - /** - * Makes the index unique. - */ - unique() { - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { - unique: true - }) - }); - } - /** - * Adds `nulls not distinct` specifier to index. - * This only works on some dialects like PostgreSQL. - * - * ### Examples - * - * ```ts - * db.schema.createIndex('person_first_name_index') - * .on('person') - * .column('first_name') - * .nullsNotDistinct() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create index "person_first_name_index" - * on "test" ("first_name") - * nulls not distinct; - * ``` - */ - nullsNotDistinct() { - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { - nullsNotDistinct: true - }) - }); - } - /** - * Specifies the table for the index. - */ - on(table) { - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { - table: parseTable(table) - }) - }); - } - /** - * Adds a column to the index. - * - * Also see {@link columns} for adding multiple columns at once or {@link expression} - * for specifying an arbitrary expression. - * - * ### Examples - * - * ```ts - * await db.schema - * .createIndex('person_first_name_and_age_index') - * .on('person') - * .column('first_name') - * .column('age desc') - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc) - * ``` - */ - column(column) { - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: CreateIndexNode.cloneWithColumns(__privateGet(this, _props28).node, [ - parseOrderedColumnName(column) - ]) - }); - } - /** - * Specifies a list of columns for the index. - * - * Also see {@link column} for adding a single column or {@link expression} for - * specifying an arbitrary expression. - * - * ### Examples - * - * ```ts - * await db.schema - * .createIndex('person_first_name_and_age_index') - * .on('person') - * .columns(['first_name', 'age desc']) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc) - * ``` - */ - columns(columns) { - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: CreateIndexNode.cloneWithColumns(__privateGet(this, _props28).node, columns.map(parseOrderedColumnName)) - }); - } - /** - * Specifies an arbitrary expression for the index. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createIndex('person_first_name_index') - * .on('person') - * .expression(sql`first_name COLLATE "fi_FI"`) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create index "person_first_name_index" on "person" (first_name COLLATE "fi_FI") - * ``` - */ - expression(expression) { - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: CreateIndexNode.cloneWithColumns(__privateGet(this, _props28).node, [ - expression.toOperationNode() - ]) - }); - } - using(indexType) { - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: CreateIndexNode.cloneWith(__privateGet(this, _props28).node, { - using: RawNode.createWithSql(indexType) - }) - }); - } - where(...args) { - const transformer = new ImmediateValueTransformer(); - return new _CreateIndexBuilder({ - ...__privateGet(this, _props28), - node: QueryNode.cloneWithWhere(__privateGet(this, _props28).node, transformer.transformNode(parseValueBinaryOperationOrExpression(args), __privateGet(this, _props28).queryId)) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props28).executor.transformQuery(__privateGet(this, _props28).node, __privateGet(this, _props28).queryId); - } - compile() { - return __privateGet(this, _props28).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props28).queryId); - } - async execute() { - await __privateGet(this, _props28).executor.executeQuery(this.compile()); - } - }; - _props28 = new WeakMap(); - CreateIndexBuilder = _CreateIndexBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js -var _props29, _CreateSchemaBuilder, CreateSchemaBuilder; -var init_create_schema_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js"() { - init_create_schema_node(); - init_object_utils(); - _CreateSchemaBuilder = class _CreateSchemaBuilder { - constructor(props) { - __privateAdd(this, _props29); - __privateSet(this, _props29, freeze(props)); - } - ifNotExists() { - return new _CreateSchemaBuilder({ - ...__privateGet(this, _props29), - node: CreateSchemaNode.cloneWith(__privateGet(this, _props29).node, { ifNotExists: true }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props29).executor.transformQuery(__privateGet(this, _props29).node, __privateGet(this, _props29).queryId); - } - compile() { - return __privateGet(this, _props29).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props29).queryId); - } - async execute() { - await __privateGet(this, _props29).executor.executeQuery(this.compile()); - } - }; - _props29 = new WeakMap(); - CreateSchemaBuilder = _CreateSchemaBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js -function parseOnCommitAction(action) { - if (ON_COMMIT_ACTIONS.includes(action)) { - return action; - } - throw new Error(`invalid OnCommitAction ${action}`); -} -var init_on_commit_action_parse = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js"() { - init_create_table_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js -var _props30, _CreateTableBuilder, CreateTableBuilder; -var init_create_table_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js"() { - init_column_definition_node(); - init_create_table_node(); - init_column_definition_builder(); - init_object_utils(); - init_foreign_key_constraint_node(); - init_column_node(); - init_foreign_key_constraint_builder(); - init_data_type_parser(); - init_primary_key_constraint_node(); - init_unique_constraint_node(); - init_check_constraint_node(); - init_table_parser(); - init_on_commit_action_parse(); - init_unique_constraint_builder(); - init_expression_parser(); - init_primary_key_constraint_builder(); - init_check_constraint_builder(); - _CreateTableBuilder = class _CreateTableBuilder { - constructor(props) { - __privateAdd(this, _props30); - __privateSet(this, _props30, freeze(props)); - } - /** - * Adds the "temporary" modifier. - * - * Use this to create a temporary table. - */ - temporary() { - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWith(__privateGet(this, _props30).node, { - temporary: true - }) - }); - } - /** - * Adds an "on commit" statement. - * - * This can be used in conjunction with temporary tables on supported databases - * like PostgreSQL. - */ - onCommit(onCommit) { - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWith(__privateGet(this, _props30).node, { - onCommit: parseOnCommitAction(onCommit) - }) - }); - } - /** - * Adds the "if not exists" modifier. - * - * If the table already exists, no error is thrown if this method has been called. - */ - ifNotExists() { - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWith(__privateGet(this, _props30).node, { - ifNotExists: true - }) - }); - } - /** - * Adds a column to the table. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', (col) => col.autoIncrement().primaryKey()) - * .addColumn('first_name', 'varchar(50)', (col) => col.notNull()) - * .addColumn('last_name', 'varchar(255)') - * .addColumn('bank_balance', 'numeric(8, 2)') - * // You can specify any data type using the `sql` tag if the types - * // don't include it. - * .addColumn('data', sql`any_type_here`) - * .addColumn('parent_id', 'integer', (col) => - * col.references('person.id').onDelete('cascade') - * ) - * ``` - * - * With this method, it's once again good to remember that Kysely just builds the - * query and doesn't provide the same API for all databases. For example, some - * databases like older MySQL don't support the `references` statement in the - * column definition. Instead foreign key constraints need to be defined in the - * `create table` query. See the next example: - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', (col) => col.primaryKey()) - * .addColumn('parent_id', 'integer') - * .addForeignKeyConstraint( - * 'person_parent_id_fk', - * ['parent_id'], - * 'person', - * ['id'], - * (cb) => cb.onDelete('cascade') - * ) - * .execute() - * ``` - * - * Another good example is that PostgreSQL doesn't support the `auto_increment` - * keyword and you need to define an autoincrementing column for example using - * `serial`: - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'serial', (col) => col.primaryKey()) - * .execute() - * ``` - */ - addColumn(columnName, dataType, build = noop) { - const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWithColumn(__privateGet(this, _props30).node, columnBuilder.toOperationNode()) - }); - } - /** - * Adds a primary key constraint for one or more columns. - * - * The constraint name can be anything you want, but it must be unique - * across the whole database. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('first_name', 'varchar(64)') - * .addColumn('last_name', 'varchar(64)') - * .addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name']) - * .execute() - * ``` - */ - addPrimaryKeyConstraint(constraintName, columns, build = noop) { - const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName))); - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWithConstraint(__privateGet(this, _props30).node, constraintBuilder.toOperationNode()) - }); - } - /** - * Adds a unique constraint for one or more columns. - * - * The constraint name can be anything you want, but it must be unique - * across the whole database. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('first_name', 'varchar(64)') - * .addColumn('last_name', 'varchar(64)') - * .addUniqueConstraint( - * 'first_name_last_name_unique', - * ['first_name', 'last_name'] - * ) - * .execute() - * ``` - * - * In dialects such as PostgreSQL you can specify `nulls not distinct` as follows: - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('first_name', 'varchar(64)') - * .addColumn('last_name', 'varchar(64)') - * .addUniqueConstraint( - * 'first_name_last_name_unique', - * ['first_name', 'last_name'], - * (cb) => cb.nullsNotDistinct() - * ) - * .execute() - * ``` - */ - addUniqueConstraint(constraintName, columns, build = noop) { - const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName))); - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWithConstraint(__privateGet(this, _props30).node, uniqueConstraintBuilder.toOperationNode()) - }); - } - /** - * Adds a check constraint. - * - * The constraint name can be anything you want, but it must be unique - * across the whole database. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('animal') - * .addColumn('number_of_legs', 'integer') - * .addCheckConstraint('check_legs', sql`number_of_legs < 5`) - * .execute() - * ``` - */ - addCheckConstraint(constraintName, checkExpression, build = noop) { - const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName))); - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWithConstraint(__privateGet(this, _props30).node, constraintBuilder.toOperationNode()) - }); - } - /** - * Adds a foreign key constraint. - * - * The constraint name can be anything you want, but it must be unique - * across the whole database. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('owner_id', 'integer') - * .addForeignKeyConstraint( - * 'owner_id_foreign', - * ['owner_id'], - * 'person', - * ['id'], - * ) - * .execute() - * ``` - * - * Add constraint for multiple columns: - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('owner_id1', 'integer') - * .addColumn('owner_id2', 'integer') - * .addForeignKeyConstraint( - * 'owner_id_foreign', - * ['owner_id1', 'owner_id2'], - * 'person', - * ['id1', 'id2'], - * (cb) => cb.onDelete('cascade') - * ) - * .execute() - * ``` - */ - addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) { - const builder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName))); - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWithConstraint(__privateGet(this, _props30).node, builder.toOperationNode()) - }); - } - /** - * This can be used to add any additional SQL to the front of the query __after__ the `create` keyword. - * - * Also see {@link temporary}. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .modifyFront(sql`global temporary`) - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn('first_name', 'varchar(64)', col => col.notNull()) - * .addColumn('last_name', 'varchar(64)', col => col.notNull()) - * .execute() - * ``` - * - * The generated SQL (Postgres): - * - * ```sql - * create global temporary table "person" ( - * "id" integer primary key, - * "first_name" varchar(64) not null, - * "last_name" varchar(64) not null - * ) - * ``` - */ - modifyFront(modifier) { - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWithFrontModifier(__privateGet(this, _props30).node, modifier.toOperationNode()) - }); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * Also see {@link onCommit}. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn('first_name', 'varchar(64)', col => col.notNull()) - * .addColumn('last_name', 'varchar(64)', col => col.notNull()) - * .modifyEnd(sql`collate utf8_unicode_ci`) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key, - * `first_name` varchar(64) not null, - * `last_name` varchar(64) not null - * ) collate utf8_unicode_ci - * ``` - */ - modifyEnd(modifier) { - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWithEndModifier(__privateGet(this, _props30).node, modifier.toOperationNode()) - }); - } - /** - * Allows to create table from `select` query. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('copy') - * .temporary() - * .as(db.selectFrom('person').select(['first_name', 'last_name'])) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create temporary table "copy" as - * select "first_name", "last_name" from "person" - * ``` - */ - as(expression) { - return new _CreateTableBuilder({ - ...__privateGet(this, _props30), - node: CreateTableNode.cloneWith(__privateGet(this, _props30).node, { - selectQuery: parseExpression(expression) - }) - }); - } - /** - * Calls the given function passing `this` as the only argument. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('test') - * .$call((builder) => builder.addColumn('id', 'integer')) - * .execute() - * ``` - * - * This is useful for creating reusable functions that can be called with a builder. - * - * ```ts - * import { type CreateTableBuilder, sql } from 'kysely' - * - * const addDefaultColumns = (ctb: CreateTableBuilder) => { - * return ctb - * .addColumn('id', 'integer', (col) => col.notNull()) - * .addColumn('created_at', 'date', (col) => - * col.notNull().defaultTo(sql`now()`) - * ) - * .addColumn('updated_at', 'date', (col) => - * col.notNull().defaultTo(sql`now()`) - * ) - * } - * - * await db.schema - * .createTable('test') - * .$call(addDefaultColumns) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props30).executor.transformQuery(__privateGet(this, _props30).node, __privateGet(this, _props30).queryId); - } - compile() { - return __privateGet(this, _props30).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props30).queryId); - } - async execute() { - await __privateGet(this, _props30).executor.executeQuery(this.compile()); - } - }; - _props30 = new WeakMap(); - CreateTableBuilder = _CreateTableBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js -var _props31, _DropIndexBuilder, DropIndexBuilder; -var init_drop_index_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js"() { - init_drop_index_node(); - init_table_parser(); - init_object_utils(); - _DropIndexBuilder = class _DropIndexBuilder { - constructor(props) { - __privateAdd(this, _props31); - __privateSet(this, _props31, freeze(props)); - } - /** - * Specifies the table the index was created for. This is not needed - * in all dialects. - */ - on(table) { - return new _DropIndexBuilder({ - ...__privateGet(this, _props31), - node: DropIndexNode.cloneWith(__privateGet(this, _props31).node, { - table: parseTable(table) - }) - }); - } - ifExists() { - return new _DropIndexBuilder({ - ...__privateGet(this, _props31), - node: DropIndexNode.cloneWith(__privateGet(this, _props31).node, { - ifExists: true - }) - }); - } - cascade() { - return new _DropIndexBuilder({ - ...__privateGet(this, _props31), - node: DropIndexNode.cloneWith(__privateGet(this, _props31).node, { - cascade: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props31).executor.transformQuery(__privateGet(this, _props31).node, __privateGet(this, _props31).queryId); - } - compile() { - return __privateGet(this, _props31).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props31).queryId); - } - async execute() { - await __privateGet(this, _props31).executor.executeQuery(this.compile()); - } - }; - _props31 = new WeakMap(); - DropIndexBuilder = _DropIndexBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js -var _props32, _DropSchemaBuilder, DropSchemaBuilder; -var init_drop_schema_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js"() { - init_drop_schema_node(); - init_object_utils(); - _DropSchemaBuilder = class _DropSchemaBuilder { - constructor(props) { - __privateAdd(this, _props32); - __privateSet(this, _props32, freeze(props)); - } - ifExists() { - return new _DropSchemaBuilder({ - ...__privateGet(this, _props32), - node: DropSchemaNode.cloneWith(__privateGet(this, _props32).node, { - ifExists: true - }) - }); - } - cascade() { - return new _DropSchemaBuilder({ - ...__privateGet(this, _props32), - node: DropSchemaNode.cloneWith(__privateGet(this, _props32).node, { - cascade: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props32).executor.transformQuery(__privateGet(this, _props32).node, __privateGet(this, _props32).queryId); - } - compile() { - return __privateGet(this, _props32).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props32).queryId); - } - async execute() { - await __privateGet(this, _props32).executor.executeQuery(this.compile()); - } - }; - _props32 = new WeakMap(); - DropSchemaBuilder = _DropSchemaBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js -var _props33, _DropTableBuilder, DropTableBuilder; -var init_drop_table_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js"() { - init_drop_table_node(); - init_object_utils(); - _DropTableBuilder = class _DropTableBuilder { - constructor(props) { - __privateAdd(this, _props33); - __privateSet(this, _props33, freeze(props)); - } - ifExists() { - return new _DropTableBuilder({ - ...__privateGet(this, _props33), - node: DropTableNode.cloneWith(__privateGet(this, _props33).node, { - ifExists: true - }) - }); - } - cascade() { - return new _DropTableBuilder({ - ...__privateGet(this, _props33), - node: DropTableNode.cloneWith(__privateGet(this, _props33).node, { - cascade: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props33).executor.transformQuery(__privateGet(this, _props33).node, __privateGet(this, _props33).queryId); - } - compile() { - return __privateGet(this, _props33).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props33).queryId); - } - async execute() { - await __privateGet(this, _props33).executor.executeQuery(this.compile()); - } - }; - _props33 = new WeakMap(); - DropTableBuilder = _DropTableBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js -var CreateViewNode; -var init_create_view_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - CreateViewNode = freeze({ - is(node) { - return node.kind === "CreateViewNode"; - }, - create(name) { - return freeze({ - kind: "CreateViewNode", - name: SchemableIdentifierNode.create(name) - }); - }, - cloneWith(createView3, params) { - return freeze({ - ...createView3, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js -var _transformer2, ImmediateValuePlugin; -var init_immediate_value_plugin = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js"() { - init_immediate_value_transformer(); - ImmediateValuePlugin = class { - constructor() { - __privateAdd(this, _transformer2, new ImmediateValueTransformer()); - } - transformQuery(args) { - return __privateGet(this, _transformer2).transformNode(args.node, args.queryId); - } - transformResult(args) { - return Promise.resolve(args.result); - } - }; - _transformer2 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js -var _props34, _CreateViewBuilder, CreateViewBuilder; -var init_create_view_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js"() { - init_object_utils(); - init_create_view_node(); - init_reference_parser(); - init_immediate_value_plugin(); - _CreateViewBuilder = class _CreateViewBuilder { - constructor(props) { - __privateAdd(this, _props34); - __privateSet(this, _props34, freeze(props)); - } - /** - * Adds the "temporary" modifier. - * - * Use this to create a temporary view. - */ - temporary() { - return new _CreateViewBuilder({ - ...__privateGet(this, _props34), - node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { - temporary: true - }) - }); - } - materialized() { - return new _CreateViewBuilder({ - ...__privateGet(this, _props34), - node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { - materialized: true - }) - }); - } - /** - * Only implemented on some dialects like SQLite. On most dialects, use {@link orReplace}. - */ - ifNotExists() { - return new _CreateViewBuilder({ - ...__privateGet(this, _props34), - node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { - ifNotExists: true - }) - }); - } - orReplace() { - return new _CreateViewBuilder({ - ...__privateGet(this, _props34), - node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { - orReplace: true - }) - }); - } - columns(columns) { - return new _CreateViewBuilder({ - ...__privateGet(this, _props34), - node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { - columns: columns.map(parseColumnName) - }) - }); - } - /** - * Sets the select query or a `values` statement that creates the view. - * - * WARNING! - * Some dialects don't support parameterized queries in DDL statements and therefore - * the query or raw {@link sql } expression passed here is interpolated into a single - * string opening an SQL injection vulnerability. DO NOT pass unchecked user input - * into the query or raw expression passed to this method! - */ - as(query) { - const queryNode = query.withPlugin(new ImmediateValuePlugin()).toOperationNode(); - return new _CreateViewBuilder({ - ...__privateGet(this, _props34), - node: CreateViewNode.cloneWith(__privateGet(this, _props34).node, { - as: queryNode - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props34).executor.transformQuery(__privateGet(this, _props34).node, __privateGet(this, _props34).queryId); - } - compile() { - return __privateGet(this, _props34).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props34).queryId); - } - async execute() { - await __privateGet(this, _props34).executor.executeQuery(this.compile()); - } - }; - _props34 = new WeakMap(); - CreateViewBuilder = _CreateViewBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js -var DropViewNode; -var init_drop_view_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - DropViewNode = freeze({ - is(node) { - return node.kind === "DropViewNode"; - }, - create(name) { - return freeze({ - kind: "DropViewNode", - name: SchemableIdentifierNode.create(name) - }); - }, - cloneWith(dropView, params) { - return freeze({ - ...dropView, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js -var _props35, _DropViewBuilder, DropViewBuilder; -var init_drop_view_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js"() { - init_object_utils(); - init_drop_view_node(); - _DropViewBuilder = class _DropViewBuilder { - constructor(props) { - __privateAdd(this, _props35); - __privateSet(this, _props35, freeze(props)); - } - materialized() { - return new _DropViewBuilder({ - ...__privateGet(this, _props35), - node: DropViewNode.cloneWith(__privateGet(this, _props35).node, { - materialized: true - }) - }); - } - ifExists() { - return new _DropViewBuilder({ - ...__privateGet(this, _props35), - node: DropViewNode.cloneWith(__privateGet(this, _props35).node, { - ifExists: true - }) - }); - } - cascade() { - return new _DropViewBuilder({ - ...__privateGet(this, _props35), - node: DropViewNode.cloneWith(__privateGet(this, _props35).node, { - cascade: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props35).executor.transformQuery(__privateGet(this, _props35).node, __privateGet(this, _props35).queryId); - } - compile() { - return __privateGet(this, _props35).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props35).queryId); - } - async execute() { - await __privateGet(this, _props35).executor.executeQuery(this.compile()); - } - }; - _props35 = new WeakMap(); - DropViewBuilder = _DropViewBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js -var CreateTypeNode; -var init_create_type_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js"() { - init_object_utils(); - init_value_list_node(); - init_value_node(); - CreateTypeNode = freeze({ - is(node) { - return node.kind === "CreateTypeNode"; - }, - create(name) { - return freeze({ - kind: "CreateTypeNode", - name - }); - }, - cloneWithEnum(createType, values) { - return freeze({ - ...createType, - enum: ValueListNode.create(values.map(ValueNode.createImmediate)) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js -var _props36, _CreateTypeBuilder, CreateTypeBuilder; -var init_create_type_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js"() { - init_object_utils(); - init_create_type_node(); - _CreateTypeBuilder = class _CreateTypeBuilder { - constructor(props) { - __privateAdd(this, _props36); - __privateSet(this, _props36, freeze(props)); - } - toOperationNode() { - return __privateGet(this, _props36).executor.transformQuery(__privateGet(this, _props36).node, __privateGet(this, _props36).queryId); - } - /** - * Creates an anum type. - * - * ### Examples - * - * ```ts - * db.schema.createType('species').asEnum(['cat', 'dog', 'frog']) - * ``` - */ - asEnum(values) { - return new _CreateTypeBuilder({ - ...__privateGet(this, _props36), - node: CreateTypeNode.cloneWithEnum(__privateGet(this, _props36).node, values) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - compile() { - return __privateGet(this, _props36).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props36).queryId); - } - async execute() { - await __privateGet(this, _props36).executor.executeQuery(this.compile()); - } - }; - _props36 = new WeakMap(); - CreateTypeBuilder = _CreateTypeBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js -var DropTypeNode; -var init_drop_type_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js"() { - init_object_utils(); - DropTypeNode = freeze({ - is(node) { - return node.kind === "DropTypeNode"; - }, - create(name) { - return freeze({ - kind: "DropTypeNode", - name - }); - }, - cloneWith(dropType, params) { - return freeze({ - ...dropType, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js -var _props37, _DropTypeBuilder, DropTypeBuilder; -var init_drop_type_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js"() { - init_drop_type_node(); - init_object_utils(); - _DropTypeBuilder = class _DropTypeBuilder { - constructor(props) { - __privateAdd(this, _props37); - __privateSet(this, _props37, freeze(props)); - } - ifExists() { - return new _DropTypeBuilder({ - ...__privateGet(this, _props37), - node: DropTypeNode.cloneWith(__privateGet(this, _props37).node, { - ifExists: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props37).executor.transformQuery(__privateGet(this, _props37).node, __privateGet(this, _props37).queryId); - } - compile() { - return __privateGet(this, _props37).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props37).queryId); - } - async execute() { - await __privateGet(this, _props37).executor.executeQuery(this.compile()); - } - }; - _props37 = new WeakMap(); - DropTypeBuilder = _DropTypeBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js -function parseSchemableIdentifier(id) { - const SCHEMA_SEPARATOR = "."; - if (id.includes(SCHEMA_SEPARATOR)) { - const parts = id.split(SCHEMA_SEPARATOR).map(trim3); - if (parts.length === 2) { - return SchemableIdentifierNode.createWithSchema(parts[0], parts[1]); - } else { - throw new Error(`invalid schemable identifier ${id}`); - } - } else { - return SchemableIdentifierNode.create(id); - } -} -function trim3(str) { - return str.trim(); -} -var init_identifier_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js"() { - init_schemable_identifier_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js -var RefreshMaterializedViewNode; -var init_refresh_materialized_view_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - RefreshMaterializedViewNode = freeze({ - is(node) { - return node.kind === "RefreshMaterializedViewNode"; - }, - create(name) { - return freeze({ - kind: "RefreshMaterializedViewNode", - name: SchemableIdentifierNode.create(name) - }); - }, - cloneWith(createView3, params) { - return freeze({ - ...createView3, - ...params - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js -var _props38, _RefreshMaterializedViewBuilder, RefreshMaterializedViewBuilder; -var init_refresh_materialized_view_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js"() { - init_object_utils(); - init_refresh_materialized_view_node(); - _RefreshMaterializedViewBuilder = class _RefreshMaterializedViewBuilder { - constructor(props) { - __privateAdd(this, _props38); - __privateSet(this, _props38, freeze(props)); - } - /** - * Adds the "concurrently" modifier. - * - * Use this to refresh the view without locking out concurrent selects on the materialized view. - * - * WARNING! - * This cannot be used with the "with no data" modifier. - */ - concurrently() { - return new _RefreshMaterializedViewBuilder({ - ...__privateGet(this, _props38), - node: RefreshMaterializedViewNode.cloneWith(__privateGet(this, _props38).node, { - concurrently: true, - withNoData: false - }) - }); - } - /** - * Adds the "with data" modifier. - * - * If specified (or defaults) the backing query is executed to provide the new data, and the materialized view is left in a scannable state - */ - withData() { - return new _RefreshMaterializedViewBuilder({ - ...__privateGet(this, _props38), - node: RefreshMaterializedViewNode.cloneWith(__privateGet(this, _props38).node, { - withNoData: false - }) - }); - } - /** - * Adds the "with no data" modifier. - * - * If specified, no new data is generated and the materialized view is left in an unscannable state. - * - * WARNING! - * This cannot be used with the "concurrently" modifier. - */ - withNoData() { - return new _RefreshMaterializedViewBuilder({ - ...__privateGet(this, _props38), - node: RefreshMaterializedViewNode.cloneWith(__privateGet(this, _props38).node, { - withNoData: true, - concurrently: false - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return __privateGet(this, _props38).executor.transformQuery(__privateGet(this, _props38).node, __privateGet(this, _props38).queryId); - } - compile() { - return __privateGet(this, _props38).executor.compileQuery(this.toOperationNode(), __privateGet(this, _props38).queryId); - } - async execute() { - await __privateGet(this, _props38).executor.executeQuery(this.compile()); - } - }; - _props38 = new WeakMap(); - RefreshMaterializedViewBuilder = _RefreshMaterializedViewBuilder; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js -var _executor, _SchemaModule, SchemaModule; -var init_schema = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js"() { - init_alter_table_node(); - init_create_index_node(); - init_create_schema_node(); - init_create_table_node(); - init_drop_index_node(); - init_drop_schema_node(); - init_drop_table_node(); - init_table_parser(); - init_alter_table_builder(); - init_create_index_builder(); - init_create_schema_builder(); - init_create_table_builder(); - init_drop_index_builder(); - init_drop_schema_builder(); - init_drop_table_builder(); - init_query_id(); - init_with_schema_plugin(); - init_create_view_builder(); - init_create_view_node(); - init_drop_view_builder(); - init_drop_view_node(); - init_create_type_builder(); - init_drop_type_builder(); - init_create_type_node(); - init_drop_type_node(); - init_identifier_parser(); - init_refresh_materialized_view_builder(); - init_refresh_materialized_view_node(); - _SchemaModule = class _SchemaModule { - constructor(executor) { - __privateAdd(this, _executor); - __privateSet(this, _executor, executor); - } - /** - * Create a new table. - * - * ### Examples - * - * This example creates a new table with columns `id`, `first_name`, - * `last_name` and `gender`: - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) - * .addColumn('first_name', 'varchar', col => col.notNull()) - * .addColumn('last_name', 'varchar', col => col.notNull()) - * .addColumn('gender', 'varchar') - * .execute() - * ``` - * - * This example creates a table with a foreign key. Not all database - * engines support column-level foreign key constraint definitions. - * For example if you are using MySQL 5.X see the next example after - * this one. - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) - * .addColumn('owner_id', 'integer', col => col - * .references('person.id') - * .onDelete('cascade') - * ) - * .execute() - * ``` - * - * This example adds a foreign key constraint for a columns just - * like the previous example, but using a table-level statement. - * On MySQL 5.X you need to define foreign key constraints like - * this: - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) - * .addColumn('owner_id', 'integer') - * .addForeignKeyConstraint( - * 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'], - * (constraint) => constraint.onDelete('cascade') - * ) - * .execute() - * ``` - */ - createTable(table) { - return new CreateTableBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: CreateTableNode.create(parseTable(table)) - }); - } - /** - * Drop a table. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropTable('person') - * .execute() - * ``` - */ - dropTable(table) { - return new DropTableBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: DropTableNode.create(parseTable(table)) - }); - } - /** - * Create a new index. - * - * ### Examples - * - * ```ts - * await db.schema - * .createIndex('person_full_name_unique_index') - * .on('person') - * .columns(['first_name', 'last_name']) - * .execute() - * ``` - */ - createIndex(indexName) { - return new CreateIndexBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: CreateIndexNode.create(indexName) - }); - } - /** - * Drop an index. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropIndex('person_full_name_unique_index') - * .execute() - * ``` - */ - dropIndex(indexName) { - return new DropIndexBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: DropIndexNode.create(indexName) - }); - } - /** - * Create a new schema. - * - * ### Examples - * - * ```ts - * await db.schema - * .createSchema('some_schema') - * .execute() - * ``` - */ - createSchema(schema3) { - return new CreateSchemaBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: CreateSchemaNode.create(schema3) - }); - } - /** - * Drop a schema. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropSchema('some_schema') - * .execute() - * ``` - */ - dropSchema(schema3) { - return new DropSchemaBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: DropSchemaNode.create(schema3) - }); - } - /** - * Alter a table. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .alterColumn('first_name', (ac) => ac.setDataType('text')) - * .execute() - * ``` - */ - alterTable(table) { - return new AlterTableBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: AlterTableNode.create(parseTable(table)) - }); - } - /** - * Create a new view. - * - * ### Examples - * - * ```ts - * await db.schema - * .createView('dogs') - * .orReplace() - * .as(db.selectFrom('pet').selectAll().where('species', '=', 'dog')) - * .execute() - * ``` - */ - createView(viewName) { - return new CreateViewBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: CreateViewNode.create(viewName) - }); - } - /** - * Refresh a materialized view. - * - * ### Examples - * - * ```ts - * await db.schema - * .refreshMaterializedView('my_view') - * .concurrently() - * .execute() - * ``` - */ - refreshMaterializedView(viewName) { - return new RefreshMaterializedViewBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: RefreshMaterializedViewNode.create(viewName) - }); - } - /** - * Drop a view. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropView('dogs') - * .ifExists() - * .execute() - * ``` - */ - dropView(viewName) { - return new DropViewBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: DropViewNode.create(viewName) - }); - } - /** - * Create a new type. - * - * Only some dialects like PostgreSQL have user-defined types. - * - * ### Examples - * - * ```ts - * await db.schema - * .createType('species') - * .asEnum(['dog', 'cat', 'frog']) - * .execute() - * ``` - */ - createType(typeName) { - return new CreateTypeBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: CreateTypeNode.create(parseSchemableIdentifier(typeName)) - }); - } - /** - * Drop a type. - * - * Only some dialects like PostgreSQL have user-defined types. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropType('species') - * .ifExists() - * .execute() - * ``` - */ - dropType(typeName) { - return new DropTypeBuilder({ - queryId: createQueryId(), - executor: __privateGet(this, _executor), - node: DropTypeNode.create(parseSchemableIdentifier(typeName)) - }); - } - /** - * Returns a copy of this schema module with the given plugin installed. - */ - withPlugin(plugin) { - return new _SchemaModule(__privateGet(this, _executor).withPlugin(plugin)); - } - /** - * Returns a copy of this schema module without any plugins. - */ - withoutPlugins() { - return new _SchemaModule(__privateGet(this, _executor).withoutPlugins()); - } - /** - * See {@link QueryCreator.withSchema} - */ - withSchema(schema3) { - return new _SchemaModule(__privateGet(this, _executor).withPluginAtFront(new WithSchemaPlugin(schema3))); - } - }; - _executor = new WeakMap(); - SchemaModule = _SchemaModule; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js -var DynamicModule; -var init_dynamic = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js"() { - init_dynamic_reference_builder(); - init_dynamic_table_builder(); - DynamicModule = class { - /** - * Creates a dynamic reference to a column that is not know at compile time. - * - * Kysely is built in a way that by default you can't refer to tables or columns - * that are not actually visible in the current query and context. This is all - * done by TypeScript at compile time, which means that you need to know the - * columns and tables at compile time. This is not always the case of course. - * - * This method is meant to be used in those cases where the column names - * come from the user input or are not otherwise known at compile time. - * - * WARNING! Unlike values, column names are not escaped by the database engine - * or Kysely and if you pass in unchecked column names using this method, you - * create an SQL injection vulnerability. Always __always__ validate the user - * input before passing it to this method. - * - * There are couple of examples below for some use cases, but you can pass - * `ref` to other methods as well. If the types allow you to pass a `ref` - * value to some place, it should work. - * - * ### Examples - * - * Filter by a column not know at compile time: - * - * ```ts - * async function someQuery(filterColumn: string, filterValue: string) { - * const { ref } = db.dynamic - * - * return await db - * .selectFrom('person') - * .selectAll() - * .where(ref(filterColumn), '=', filterValue) - * .execute() - * } - * - * someQuery('first_name', 'Arnold') - * someQuery('person.last_name', 'Aniston') - * ``` - * - * Order by a column not know at compile time: - * - * ```ts - * async function someQuery(orderBy: string) { - * const { ref } = db.dynamic - * - * return await db - * .selectFrom('person') - * .select('person.first_name as fn') - * .orderBy(ref(orderBy)) - * .execute() - * } - * - * someQuery('fn') - * ``` - * - * In this example we add selections dynamically: - * - * ```ts - * const { ref } = db.dynamic - * - * // Some column name provided by the user. Value not known at compile time. - * const columnFromUserInput: PossibleColumns = 'birthdate'; - * - * // A type that lists all possible values `columnFromUserInput` can have. - * // You can use `keyof Person` if any column of an interface is allowed. - * type PossibleColumns = 'last_name' | 'first_name' | 'birthdate' - * - * const [person] = await db.selectFrom('person') - * .select([ - * ref(columnFromUserInput), - * 'id' - * ]) - * .execute() - * - * // The resulting type contains all `PossibleColumns` as optional fields - * // because we cannot know which field was actually selected before - * // running the code. - * const lastName: string | null | undefined = person?.last_name - * const firstName: string | undefined = person?.first_name - * const birthDate: Date | null | undefined = person?.birthdate - * - * // The result type also contains the compile time selection `id`. - * person?.id - * ``` - */ - ref(reference) { - return new DynamicReferenceBuilder(reference); - } - /** - * Creates a table reference to a table that's not fully known at compile time. - * - * The type `T` is allowed to be a union of multiple tables. - * - * - * - * A generic type-safe helper function for finding a row by a column value: - * - * ```ts - * import { SelectType } from 'kysely' - * import { Database } from 'type-editor' - * - * async function getRowByColumn< - * T extends keyof Database, - * C extends keyof Database[T] & string, - * V extends SelectType, - * >(t: T, c: C, v: V) { - * // We need to use the dynamic module since the table name - * // is not known at compile time. - * const { table, ref } = db.dynamic - * - * return await db - * .selectFrom(table(t).as('t')) - * .selectAll() - * .where(ref(c), '=', v) - * .orderBy('t.id') - * .executeTakeFirstOrThrow() - * } - * - * const person = await getRowByColumn('person', 'first_name', 'Arnold') - * ``` - */ - table(table) { - return new DynamicTableBuilder(table); - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js -var _driver, DefaultConnectionProvider; -var init_default_connection_provider = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js"() { - DefaultConnectionProvider = class { - constructor(driver) { - __privateAdd(this, _driver); - __privateSet(this, _driver, driver); - } - async provideConnection(consumer) { - const connection = await __privateGet(this, _driver).acquireConnection(); - try { - return await consumer(connection); - } finally { - await __privateGet(this, _driver).releaseConnection(connection); - } - } - }; - _driver = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js -var _compiler, _adapter, _connectionProvider, _DefaultQueryExecutor, DefaultQueryExecutor; -var init_default_query_executor = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js"() { - init_query_executor_base(); - _DefaultQueryExecutor = class _DefaultQueryExecutor extends QueryExecutorBase { - constructor(compiler, adapter, connectionProvider, plugins = []) { - super(plugins); - __privateAdd(this, _compiler); - __privateAdd(this, _adapter); - __privateAdd(this, _connectionProvider); - __privateSet(this, _compiler, compiler); - __privateSet(this, _adapter, adapter); - __privateSet(this, _connectionProvider, connectionProvider); - } - get adapter() { - return __privateGet(this, _adapter); - } - compileQuery(node, queryId) { - return __privateGet(this, _compiler).compileQuery(node, queryId); - } - provideConnection(consumer) { - return __privateGet(this, _connectionProvider).provideConnection(consumer); - } - withPlugins(plugins) { - return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), __privateGet(this, _connectionProvider), [...this.plugins, ...plugins]); - } - withPlugin(plugin) { - return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), __privateGet(this, _connectionProvider), [...this.plugins, plugin]); - } - withPluginAtFront(plugin) { - return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), __privateGet(this, _connectionProvider), [plugin, ...this.plugins]); - } - withConnectionProvider(connectionProvider) { - return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), connectionProvider, [...this.plugins]); - } - withoutPlugins() { - return new _DefaultQueryExecutor(__privateGet(this, _compiler), __privateGet(this, _adapter), __privateGet(this, _connectionProvider), []); - } - }; - _compiler = new WeakMap(); - _adapter = new WeakMap(); - _connectionProvider = new WeakMap(); - DefaultQueryExecutor = _DefaultQueryExecutor; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js -function performanceNow() { - if (typeof performance !== "undefined" && isFunction3(performance.now)) { - return performance.now(); - } else { - return Date.now(); - } -} -var init_performance_now = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js"() { - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js -var _driver2, _log, _initPromise, _initDone, _destroyPromise, _connections, _RuntimeDriver_instances, needsLogging_fn, addLogging_fn, logError_fn, logQuery_fn, calculateDurationMillis_fn, RuntimeDriver; -var init_runtime_driver = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js"() { - init_performance_now(); - RuntimeDriver = class { - constructor(driver, log) { - __privateAdd(this, _RuntimeDriver_instances); - __privateAdd(this, _driver2); - __privateAdd(this, _log); - __privateAdd(this, _initPromise); - __privateAdd(this, _initDone); - __privateAdd(this, _destroyPromise); - __privateAdd(this, _connections, /* @__PURE__ */ new WeakSet()); - __privateSet(this, _initDone, false); - __privateSet(this, _driver2, driver); - __privateSet(this, _log, log); - } - async init() { - if (__privateGet(this, _destroyPromise)) { - throw new Error("driver has already been destroyed"); - } - if (!__privateGet(this, _initPromise)) { - __privateSet(this, _initPromise, __privateGet(this, _driver2).init().then(() => { - __privateSet(this, _initDone, true); - }).catch((err) => { - __privateSet(this, _initPromise, void 0); - return Promise.reject(err); - })); - } - await __privateGet(this, _initPromise); - } - async acquireConnection() { - if (__privateGet(this, _destroyPromise)) { - throw new Error("driver has already been destroyed"); - } - if (!__privateGet(this, _initDone)) { - await this.init(); - } - const connection = await __privateGet(this, _driver2).acquireConnection(); - if (!__privateGet(this, _connections).has(connection)) { - if (__privateMethod(this, _RuntimeDriver_instances, needsLogging_fn).call(this)) { - __privateMethod(this, _RuntimeDriver_instances, addLogging_fn).call(this, connection); - } - __privateGet(this, _connections).add(connection); - } - return connection; - } - async releaseConnection(connection) { - await __privateGet(this, _driver2).releaseConnection(connection); - } - beginTransaction(connection, settings) { - return __privateGet(this, _driver2).beginTransaction(connection, settings); - } - commitTransaction(connection) { - return __privateGet(this, _driver2).commitTransaction(connection); - } - rollbackTransaction(connection) { - return __privateGet(this, _driver2).rollbackTransaction(connection); - } - savepoint(connection, savepointName, compileQuery) { - if (__privateGet(this, _driver2).savepoint) { - return __privateGet(this, _driver2).savepoint(connection, savepointName, compileQuery); - } - throw new Error("The `savepoint` method is not supported by this driver"); - } - rollbackToSavepoint(connection, savepointName, compileQuery) { - if (__privateGet(this, _driver2).rollbackToSavepoint) { - return __privateGet(this, _driver2).rollbackToSavepoint(connection, savepointName, compileQuery); - } - throw new Error("The `rollbackToSavepoint` method is not supported by this driver"); - } - releaseSavepoint(connection, savepointName, compileQuery) { - if (__privateGet(this, _driver2).releaseSavepoint) { - return __privateGet(this, _driver2).releaseSavepoint(connection, savepointName, compileQuery); - } - throw new Error("The `releaseSavepoint` method is not supported by this driver"); - } - async destroy() { - if (!__privateGet(this, _initPromise)) { - return; - } - await __privateGet(this, _initPromise); - if (!__privateGet(this, _destroyPromise)) { - __privateSet(this, _destroyPromise, __privateGet(this, _driver2).destroy().catch((err) => { - __privateSet(this, _destroyPromise, void 0); - return Promise.reject(err); - })); - } - await __privateGet(this, _destroyPromise); - } - }; - _driver2 = new WeakMap(); - _log = new WeakMap(); - _initPromise = new WeakMap(); - _initDone = new WeakMap(); - _destroyPromise = new WeakMap(); - _connections = new WeakMap(); - _RuntimeDriver_instances = new WeakSet(); - needsLogging_fn = function() { - return __privateGet(this, _log).isLevelEnabled("query") || __privateGet(this, _log).isLevelEnabled("error"); - }; - // This method monkey patches the database connection's executeQuery method - // by adding logging code around it. Monkey patching is not pretty, but it's - // the best option in this case. - addLogging_fn = function(connection) { - const executeQuery = connection.executeQuery; - const streamQuery = connection.streamQuery; - const dis = this; - connection.executeQuery = async (compiledQuery) => { - var _a30, _b2; - let caughtError; - const startTime = performanceNow(); - try { - return await executeQuery.call(connection, compiledQuery); - } catch (error49) { - caughtError = error49; - await __privateMethod(_a30 = dis, _RuntimeDriver_instances, logError_fn).call(_a30, error49, compiledQuery, startTime); - throw error49; - } finally { - if (!caughtError) { - await __privateMethod(_b2 = dis, _RuntimeDriver_instances, logQuery_fn).call(_b2, compiledQuery, startTime); - } - } - }; - connection.streamQuery = async function* (compiledQuery, chunkSize) { - var _a30, _b2; - let caughtError; - const startTime = performanceNow(); - try { - for await (const result of streamQuery.call(connection, compiledQuery, chunkSize)) { - yield result; - } - } catch (error49) { - caughtError = error49; - await __privateMethod(_a30 = dis, _RuntimeDriver_instances, logError_fn).call(_a30, error49, compiledQuery, startTime); - throw error49; - } finally { - if (!caughtError) { - await __privateMethod(_b2 = dis, _RuntimeDriver_instances, logQuery_fn).call(_b2, compiledQuery, startTime, true); - } - } - }; - }; - logError_fn = async function(error49, compiledQuery, startTime) { - await __privateGet(this, _log).error(() => ({ - level: "error", - error: error49, - query: compiledQuery, - queryDurationMillis: __privateMethod(this, _RuntimeDriver_instances, calculateDurationMillis_fn).call(this, startTime) - })); - }; - logQuery_fn = async function(compiledQuery, startTime, isStream = false) { - await __privateGet(this, _log).query(() => ({ - level: "query", - isStream, - query: compiledQuery, - queryDurationMillis: __privateMethod(this, _RuntimeDriver_instances, calculateDurationMillis_fn).call(this, startTime) - })); - }; - calculateDurationMillis_fn = function(startTime) { - return performanceNow() - startTime; - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js -var ignoreError, _connection, _runningPromise, _SingleConnectionProvider_instances, run_fn, SingleConnectionProvider; -var init_single_connection_provider = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js"() { - ignoreError = () => { - }; - SingleConnectionProvider = class { - constructor(connection) { - __privateAdd(this, _SingleConnectionProvider_instances); - __privateAdd(this, _connection); - __privateAdd(this, _runningPromise); - __privateSet(this, _connection, connection); - } - async provideConnection(consumer) { - while (__privateGet(this, _runningPromise)) { - await __privateGet(this, _runningPromise).catch(ignoreError); - } - __privateSet(this, _runningPromise, __privateMethod(this, _SingleConnectionProvider_instances, run_fn).call(this, consumer).finally(() => { - __privateSet(this, _runningPromise, void 0); - })); - return __privateGet(this, _runningPromise); - } - }; - _connection = new WeakMap(); - _runningPromise = new WeakMap(); - _SingleConnectionProvider_instances = new WeakSet(); - run_fn = async function(runner) { - return await runner(__privateGet(this, _connection)); - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js -function validateTransactionSettings(settings) { - if (settings.accessMode && !TRANSACTION_ACCESS_MODES.includes(settings.accessMode)) { - throw new Error(`invalid transaction access mode ${settings.accessMode}`); - } - if (settings.isolationLevel && !TRANSACTION_ISOLATION_LEVELS.includes(settings.isolationLevel)) { - throw new Error(`invalid transaction isolation level ${settings.isolationLevel}`); - } -} -var TRANSACTION_ACCESS_MODES, TRANSACTION_ISOLATION_LEVELS; -var init_driver = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js"() { - TRANSACTION_ACCESS_MODES = ["read only", "read write"]; - TRANSACTION_ISOLATION_LEVELS = [ - "read uncommitted", - "read committed", - "repeatable read", - "serializable", - "snapshot" - ]; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js -function defaultLogger(event) { - if (event.level === "query") { - const prefix = `kysely:query:${event.isStream ? "stream:" : ""}`; - console.log(`${prefix} ${event.query.sql}`); - console.log(`${prefix} duration: ${event.queryDurationMillis.toFixed(1)}ms`); - } else if (event.level === "error") { - if (event.error instanceof Error) { - console.error(`kysely:error: ${event.error.stack ?? event.error.message}`); - } else { - console.error(`kysely:error: ${JSON.stringify({ - error: event.error, - query: event.query.sql, - queryDurationMillis: event.queryDurationMillis - })}`); - } - } -} -var logLevels, LOG_LEVELS, _levels, _logger, Log; -var init_log = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js"() { - init_object_utils(); - logLevels = ["query", "error"]; - LOG_LEVELS = freeze(logLevels); - Log = class { - constructor(config4) { - __privateAdd(this, _levels); - __privateAdd(this, _logger); - if (isFunction3(config4)) { - __privateSet(this, _logger, config4); - __privateSet(this, _levels, freeze({ - query: true, - error: true - })); - } else { - __privateSet(this, _logger, defaultLogger); - __privateSet(this, _levels, freeze({ - query: config4.includes("query"), - error: config4.includes("error") - })); - } - } - isLevelEnabled(level) { - return __privateGet(this, _levels)[level]; - } - async query(getEvent) { - if (__privateGet(this, _levels).query) { - await __privateGet(this, _logger).call(this, getEvent()); - } - } - async error(getEvent) { - if (__privateGet(this, _levels).error) { - await __privateGet(this, _logger).call(this, getEvent()); - } - } - }; - _levels = new WeakMap(); - _logger = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js -function isCompilable(value) { - return isObject4(value) && isFunction3(value.compile); -} -var init_compilable = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js"() { - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js -function isKyselyProps(obj) { - return isObject4(obj) && isObject4(obj.config) && isObject4(obj.driver) && isObject4(obj.executor) && isObject4(obj.dialect); -} -function assertNotCommittedOrRolledBack(state) { - if (state.isCommitted) { - throw new Error("Transaction is already committed"); - } - if (state.isRolledBack) { - throw new Error("Transaction is already rolled back"); - } -} -var _props39, _Kysely, Kysely, _props40, _Transaction, Transaction, _props41, ConnectionBuilder, _props42, _TransactionBuilder, TransactionBuilder, _props43, _ControlledTransactionBuilder, ControlledTransactionBuilder, _props44, _compileQuery, _state, _ControlledTransaction, ControlledTransaction, _cb, Command, _executor2, _state2, _NotCommittedOrRolledBackAssertingExecutor, NotCommittedOrRolledBackAssertingExecutor; -var init_kysely = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js"() { - init_schema(); - init_dynamic(); - init_default_connection_provider(); - init_query_creator(); - init_default_query_executor(); - init_object_utils(); - init_runtime_driver(); - init_single_connection_provider(); - init_driver(); - init_function_module(); - init_log(); - init_query_id(); - init_compilable(); - init_case_builder(); - init_case_node(); - init_expression_parser(); - init_with_schema_plugin(); - init_provide_controlled_connection(); - init_log_once(); - Symbol.asyncDispose ?? (Symbol.asyncDispose = Symbol("Symbol.asyncDispose")); - _Kysely = class _Kysely extends QueryCreator { - constructor(args) { - let superProps; - let props; - if (isKyselyProps(args)) { - superProps = { executor: args.executor }; - props = { ...args }; - } else { - const dialect = args.dialect; - const driver = dialect.createDriver(); - const compiler = dialect.createQueryCompiler(); - const adapter = dialect.createAdapter(); - const log = new Log(args.log ?? []); - const runtimeDriver = new RuntimeDriver(driver, log); - const connectionProvider = new DefaultConnectionProvider(runtimeDriver); - const executor = new DefaultQueryExecutor(compiler, adapter, connectionProvider, args.plugins ?? []); - superProps = { executor }; - props = { - config: args, - executor, - dialect, - driver: runtimeDriver - }; - } - super(superProps); - __privateAdd(this, _props39); - __privateSet(this, _props39, freeze(props)); - } - /** - * Returns the {@link SchemaModule} module for building database schema. - */ - get schema() { - return new SchemaModule(__privateGet(this, _props39).executor); - } - /** - * Returns a the {@link DynamicModule} module. - * - * The {@link DynamicModule} module can be used to bypass strict typing and - * passing in dynamic values for the queries. - */ - get dynamic() { - return new DynamicModule(); - } - /** - * Returns a {@link DatabaseIntrospector | database introspector}. - */ - get introspection() { - return __privateGet(this, _props39).dialect.createIntrospector(this.withoutPlugins()); - } - case(value) { - return new CaseBuilder({ - node: CaseNode.create(isUndefined(value) ? void 0 : parseExpression(value)) - }); - } - /** - * Returns a {@link FunctionModule} that can be used to write somewhat type-safe function - * calls. - * - * ```ts - * const { count } = db.fn - * - * await db.selectFrom('person') - * .innerJoin('pet', 'pet.owner_id', 'person.id') - * .select([ - * 'id', - * count('pet.id').as('person_count'), - * ]) - * .groupBy('person.id') - * .having(count('pet.id'), '>', 10) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "person"."id", count("pet"."id") as "person_count" - * from "person" - * inner join "pet" on "pet"."owner_id" = "person"."id" - * group by "person"."id" - * having count("pet"."id") > $1 - * ``` - * - * Why "somewhat" type-safe? Because the function calls are not bound to the - * current query context. They allow you to reference columns and tables that - * are not in the current query. E.g. remove the `innerJoin` from the previous - * query and TypeScript won't even complain. - * - * If you want to make the function calls fully type-safe, you can use the - * {@link ExpressionBuilder.fn} getter for a query context-aware, stricter {@link FunctionModule}. - * - * ```ts - * await db.selectFrom('person') - * .innerJoin('pet', 'pet.owner_id', 'person.id') - * .select((eb) => [ - * 'person.id', - * eb.fn.count('pet.id').as('pet_count') - * ]) - * .groupBy('person.id') - * .having((eb) => eb.fn.count('pet.id'), '>', 10) - * .execute() - * ``` - */ - get fn() { - return createFunctionModule(); - } - /** - * Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction. - * - * The returned {@link TransactionBuilder} can be used to configure the transaction. The - * {@link TransactionBuilder.execute} method can then be called to run the transaction. - * {@link TransactionBuilder.execute} takes a function that is run inside the - * transaction. If the function throws an exception, - * 1. the exception is caught, - * 2. the transaction is rolled back, and - * 3. the exception is thrown again. - * Otherwise the transaction is committed. - * - * The callback function passed to the {@link TransactionBuilder.execute | execute} - * method gets the transaction object as its only argument. The transaction is - * of type {@link Transaction} which inherits {@link Kysely}. Any query - * started through the transaction object is executed inside the transaction. - * - * To run a controlled transaction, allowing you to commit and rollback manually, - * use {@link startTransaction} instead. - * - * ### Examples - * - * - * - * This example inserts two rows in a transaction. If an exception is thrown inside - * the callback passed to the `execute` method, - * 1. the exception is caught, - * 2. the transaction is rolled back, and - * 3. the exception is thrown again. - * Otherwise the transaction is committed. - * - * ```ts - * const catto = await db.transaction().execute(async (trx) => { - * const jennifer = await trx.insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * - * return await trx.insertInto('pet') - * .values({ - * owner_id: jennifer.id, - * name: 'Catto', - * species: 'cat', - * is_favorite: false, - * }) - * .returningAll() - * .executeTakeFirst() - * }) - * ``` - * - * Setting the isolation level: - * - * ```ts - * import type { Kysely } from 'kysely' - * - * await db - * .transaction() - * .setIsolationLevel('serializable') - * .execute(async (trx) => { - * await doStuff(trx) - * }) - * - * async function doStuff(kysely: typeof db) { - * // ... - * } - * ``` - */ - transaction() { - return new TransactionBuilder({ ...__privateGet(this, _props39) }); - } - /** - * Creates a {@link ControlledTransactionBuilder} that can be used to run queries inside a controlled transaction. - * - * The returned {@link ControlledTransactionBuilder} can be used to configure the transaction. - * The {@link ControlledTransactionBuilder.execute} method can then be called - * to start the transaction and return a {@link ControlledTransaction}. - * - * A {@link ControlledTransaction} allows you to commit and rollback manually, - * execute savepoint commands. It extends {@link Transaction} which extends {@link Kysely}, - * so you can run queries inside the transaction. Once the transaction is committed, - * or rolled back, it can't be used anymore - all queries will throw an error. - * This is to prevent accidentally running queries outside the transaction - where - * atomicity is not guaranteed anymore. - * - * ### Examples - * - * - * - * A controlled transaction allows you to commit and rollback manually, execute - * savepoint commands, and queries in general. - * - * In this example we start a transaction, use it to insert two rows and then commit - * the transaction. If an error is thrown, we catch it and rollback the transaction. - * - * ```ts - * const trx = await db.startTransaction().execute() - * - * try { - * const jennifer = await trx.insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * - * const catto = await trx.insertInto('pet') - * .values({ - * owner_id: jennifer.id, - * name: 'Catto', - * species: 'cat', - * is_favorite: false, - * }) - * .returningAll() - * .executeTakeFirstOrThrow() - * - * await trx.commit().execute() - * - * // ... - * } catch (error) { - * await trx.rollback().execute() - * } - * ``` - * - * - * - * A controlled transaction allows you to commit and rollback manually, execute - * savepoint commands, and queries in general. - * - * In this example we start a transaction, insert a person, create a savepoint, - * try inserting a toy and a pet, and if an error is thrown, we rollback to the - * savepoint. Eventually we release the savepoint, insert an audit record and - * commit the transaction. If an error is thrown, we catch it and rollback the - * transaction. - * - * ```ts - * const trx = await db.startTransaction().execute() - * - * try { - * const jennifer = await trx - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * - * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() - * - * try { - * const catto = await trxAfterJennifer - * .insertInto('pet') - * .values({ - * owner_id: jennifer.id, - * name: 'Catto', - * species: 'cat', - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * - * await trxAfterJennifer - * .insertInto('toy') - * .values({ name: 'Bone', price: 1.99, pet_id: catto.id }) - * .execute() - * } catch (error) { - * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() - * } - * - * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() - * - * await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute() - * - * await trx.commit().execute() - * } catch (error) { - * await trx.rollback().execute() - * } - * ``` - */ - startTransaction() { - return new ControlledTransactionBuilder({ ...__privateGet(this, _props39) }); - } - /** - * Provides a kysely instance bound to a single database connection. - * - * ### Examples - * - * ```ts - * await db - * .connection() - * .execute(async (db) => { - * // `db` is an instance of `Kysely` that's bound to a single - * // database connection. All queries executed through `db` use - * // the same connection. - * await doStuff(db) - * }) - * - * async function doStuff(kysely: typeof db) { - * // ... - * } - * ``` - */ - connection() { - return new ConnectionBuilder({ ...__privateGet(this, _props39) }); - } - /** - * Returns a copy of this Kysely instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _Kysely({ - ...__privateGet(this, _props39), - executor: __privateGet(this, _props39).executor.withPlugin(plugin) - }); - } - /** - * Returns a copy of this Kysely instance without any plugins. - */ - withoutPlugins() { - return new _Kysely({ - ...__privateGet(this, _props39), - executor: __privateGet(this, _props39).executor.withoutPlugins() - }); - } - /** - * @override - */ - withSchema(schema3) { - return new _Kysely({ - ...__privateGet(this, _props39), - executor: __privateGet(this, _props39).executor.withPluginAtFront(new WithSchemaPlugin(schema3)) - }); - } - /** - * Returns a copy of this Kysely instance with tables added to its - * database type. - * - * This method only modifies the types and doesn't affect any of the - * executed queries in any way. - * - * ### Examples - * - * The following example adds and uses a temporary table: - * - * ```ts - * await db.schema - * .createTable('temp_table') - * .temporary() - * .addColumn('some_column', 'integer') - * .execute() - * - * const tempDb = db.withTables<{ - * temp_table: { - * some_column: number - * } - * }>() - * - * await tempDb - * .insertInto('temp_table') - * .values({ some_column: 100 }) - * .execute() - * ``` - */ - withTables() { - return new _Kysely({ ...__privateGet(this, _props39) }); - } - /** - * Releases all resources and disconnects from the database. - * - * You need to call this when you are done using the `Kysely` instance. - */ - async destroy() { - await __privateGet(this, _props39).driver.destroy(); - } - /** - * Returns true if this `Kysely` instance is a transaction. - * - * You can also use `db instanceof Transaction`. - */ - get isTransaction() { - return false; - } - /** - * @internal - * @private - */ - getExecutor() { - return __privateGet(this, _props39).executor; - } - /** - * Executes a given compiled query or query builder. - * - * See {@link https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0004-splitting-query-building-and-execution.md#execute-compiled-queries splitting build, compile and execute code recipe} for more information. - */ - executeQuery(query, queryId) { - if (queryId !== void 0) { - logOnce("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future."); - } - const compiledQuery = isCompilable(query) ? query.compile() : query; - return this.getExecutor().executeQuery(compiledQuery); - } - async [Symbol.asyncDispose]() { - await this.destroy(); - } - }; - _props39 = new WeakMap(); - Kysely = _Kysely; - _Transaction = class _Transaction extends Kysely { - constructor(props) { - super(props); - __privateAdd(this, _props40); - __privateSet(this, _props40, props); - } - // The return type is `true` instead of `boolean` to make Kysely - // unassignable to Transaction while allowing assignment the - // other way around. - get isTransaction() { - return true; - } - transaction() { - throw new Error("calling the transaction method for a Transaction is not supported"); - } - connection() { - throw new Error("calling the connection method for a Transaction is not supported"); - } - async destroy() { - throw new Error("calling the destroy method for a Transaction is not supported"); - } - withPlugin(plugin) { - return new _Transaction({ - ...__privateGet(this, _props40), - executor: __privateGet(this, _props40).executor.withPlugin(plugin) - }); - } - withoutPlugins() { - return new _Transaction({ - ...__privateGet(this, _props40), - executor: __privateGet(this, _props40).executor.withoutPlugins() - }); - } - withSchema(schema3) { - return new _Transaction({ - ...__privateGet(this, _props40), - executor: __privateGet(this, _props40).executor.withPluginAtFront(new WithSchemaPlugin(schema3)) - }); - } - withTables() { - return new _Transaction({ ...__privateGet(this, _props40) }); - } - }; - _props40 = new WeakMap(); - Transaction = _Transaction; - ConnectionBuilder = class { - constructor(props) { - __privateAdd(this, _props41); - __privateSet(this, _props41, freeze(props)); - } - async execute(callback) { - return __privateGet(this, _props41).executor.provideConnection(async (connection) => { - const executor = __privateGet(this, _props41).executor.withConnectionProvider(new SingleConnectionProvider(connection)); - const db = new Kysely({ - ...__privateGet(this, _props41), - executor - }); - return await callback(db); - }); - } - }; - _props41 = new WeakMap(); - _TransactionBuilder = class _TransactionBuilder { - constructor(props) { - __privateAdd(this, _props42); - __privateSet(this, _props42, freeze(props)); - } - setAccessMode(accessMode) { - return new _TransactionBuilder({ - ...__privateGet(this, _props42), - accessMode - }); - } - setIsolationLevel(isolationLevel) { - return new _TransactionBuilder({ - ...__privateGet(this, _props42), - isolationLevel - }); - } - async execute(callback) { - const { isolationLevel, accessMode, ...kyselyProps } = __privateGet(this, _props42); - const settings = { isolationLevel, accessMode }; - validateTransactionSettings(settings); - return __privateGet(this, _props42).executor.provideConnection(async (connection) => { - const state = { isCommitted: false, isRolledBack: false }; - const executor = new NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _props42).executor.withConnectionProvider(new SingleConnectionProvider(connection)), state); - const transaction = new Transaction({ - ...kyselyProps, - executor - }); - let transactionBegun = false; - try { - await __privateGet(this, _props42).driver.beginTransaction(connection, settings); - transactionBegun = true; - const result = await callback(transaction); - await __privateGet(this, _props42).driver.commitTransaction(connection); - state.isCommitted = true; - return result; - } catch (error49) { - if (transactionBegun) { - await __privateGet(this, _props42).driver.rollbackTransaction(connection); - state.isRolledBack = true; - } - throw error49; - } - }); - } - }; - _props42 = new WeakMap(); - TransactionBuilder = _TransactionBuilder; - _ControlledTransactionBuilder = class _ControlledTransactionBuilder { - constructor(props) { - __privateAdd(this, _props43); - __privateSet(this, _props43, freeze(props)); - } - setAccessMode(accessMode) { - return new _ControlledTransactionBuilder({ - ...__privateGet(this, _props43), - accessMode - }); - } - setIsolationLevel(isolationLevel) { - return new _ControlledTransactionBuilder({ - ...__privateGet(this, _props43), - isolationLevel - }); - } - async execute() { - const { isolationLevel, accessMode, ...props } = __privateGet(this, _props43); - const settings = { isolationLevel, accessMode }; - validateTransactionSettings(settings); - const connection = await provideControlledConnection(__privateGet(this, _props43).executor); - await __privateGet(this, _props43).driver.beginTransaction(connection.connection, settings); - return new ControlledTransaction({ - ...props, - connection, - executor: __privateGet(this, _props43).executor.withConnectionProvider(new SingleConnectionProvider(connection.connection)) - }); - } - }; - _props43 = new WeakMap(); - ControlledTransactionBuilder = _ControlledTransactionBuilder; - _ControlledTransaction = class _ControlledTransaction extends Transaction { - constructor(props) { - const state = { isCommitted: false, isRolledBack: false }; - props = { - ...props, - executor: new NotCommittedOrRolledBackAssertingExecutor(props.executor, state) - }; - const { connection, ...transactionProps } = props; - super(transactionProps); - __privateAdd(this, _props44); - __privateAdd(this, _compileQuery); - __privateAdd(this, _state); - __privateSet(this, _props44, freeze(props)); - __privateSet(this, _state, state); - const queryId = createQueryId(); - __privateSet(this, _compileQuery, (node) => props.executor.compileQuery(node, queryId)); - } - get isCommitted() { - return __privateGet(this, _state).isCommitted; - } - get isRolledBack() { - return __privateGet(this, _state).isRolledBack; - } - /** - * Commits the transaction. - * - * See {@link rollback}. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * try { - * await doSomething(trx) - * - * await trx.commit().execute() - * } catch (error) { - * await trx.rollback().execute() - * } - * - * async function doSomething(kysely: Kysely) {} - * ``` - */ - commit() { - assertNotCommittedOrRolledBack(__privateGet(this, _state)); - return new Command(async () => { - await __privateGet(this, _props44).driver.commitTransaction(__privateGet(this, _props44).connection.connection); - __privateGet(this, _state).isCommitted = true; - __privateGet(this, _props44).connection.release(); - }); - } - /** - * Rolls back the transaction. - * - * See {@link commit} and {@link rollbackToSavepoint}. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * try { - * await doSomething(trx) - * - * await trx.commit().execute() - * } catch (error) { - * await trx.rollback().execute() - * } - * - * async function doSomething(kysely: Kysely) {} - * ``` - */ - rollback() { - assertNotCommittedOrRolledBack(__privateGet(this, _state)); - return new Command(async () => { - await __privateGet(this, _props44).driver.rollbackTransaction(__privateGet(this, _props44).connection.connection); - __privateGet(this, _state).isRolledBack = true; - __privateGet(this, _props44).connection.release(); - }); - } - /** - * Creates a savepoint with a given name. - * - * See {@link rollbackToSavepoint} and {@link releaseSavepoint}. - * - * For a type-safe experience, you should use the returned instance from now on. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * await insertJennifer(trx) - * - * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() - * - * try { - * await doSomething(trxAfterJennifer) - * } catch (error) { - * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() - * } - * - * async function insertJennifer(kysely: Kysely) {} - * async function doSomething(kysely: Kysely) {} - * ``` - */ - savepoint(savepointName) { - assertNotCommittedOrRolledBack(__privateGet(this, _state)); - return new Command(async () => { - await __privateGet(this, _props44).driver.savepoint?.(__privateGet(this, _props44).connection.connection, savepointName, __privateGet(this, _compileQuery)); - return new _ControlledTransaction({ ...__privateGet(this, _props44) }); - }); - } - /** - * Rolls back to a savepoint with a given name. - * - * See {@link savepoint} and {@link releaseSavepoint}. - * - * You must use the same instance returned by {@link savepoint}, or - * escape the type-check by using `as any`. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * await insertJennifer(trx) - * - * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() - * - * try { - * await doSomething(trxAfterJennifer) - * } catch (error) { - * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() - * } - * - * async function insertJennifer(kysely: Kysely) {} - * async function doSomething(kysely: Kysely) {} - * ``` - */ - rollbackToSavepoint(savepointName) { - assertNotCommittedOrRolledBack(__privateGet(this, _state)); - return new Command(async () => { - await __privateGet(this, _props44).driver.rollbackToSavepoint?.(__privateGet(this, _props44).connection.connection, savepointName, __privateGet(this, _compileQuery)); - return new _ControlledTransaction({ ...__privateGet(this, _props44) }); - }); - } - /** - * Releases a savepoint with a given name. - * - * See {@link savepoint} and {@link rollbackToSavepoint}. - * - * You must use the same instance returned by {@link savepoint}, or - * escape the type-check by using `as any`. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * await insertJennifer(trx) - * - * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() - * - * try { - * await doSomething(trxAfterJennifer) - * } catch (error) { - * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() - * } - * - * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() - * - * await doSomethingElse(trx) - * - * async function insertJennifer(kysely: Kysely) {} - * async function doSomething(kysely: Kysely) {} - * async function doSomethingElse(kysely: Kysely) {} - * ``` - */ - releaseSavepoint(savepointName) { - assertNotCommittedOrRolledBack(__privateGet(this, _state)); - return new Command(async () => { - await __privateGet(this, _props44).driver.releaseSavepoint?.(__privateGet(this, _props44).connection.connection, savepointName, __privateGet(this, _compileQuery)); - return new _ControlledTransaction({ ...__privateGet(this, _props44) }); - }); - } - withPlugin(plugin) { - return new _ControlledTransaction({ - ...__privateGet(this, _props44), - executor: __privateGet(this, _props44).executor.withPlugin(plugin) - }); - } - withoutPlugins() { - return new _ControlledTransaction({ - ...__privateGet(this, _props44), - executor: __privateGet(this, _props44).executor.withoutPlugins() - }); - } - withSchema(schema3) { - return new _ControlledTransaction({ - ...__privateGet(this, _props44), - executor: __privateGet(this, _props44).executor.withPluginAtFront(new WithSchemaPlugin(schema3)) - }); - } - withTables() { - return new _ControlledTransaction({ ...__privateGet(this, _props44) }); - } - }; - _props44 = new WeakMap(); - _compileQuery = new WeakMap(); - _state = new WeakMap(); - ControlledTransaction = _ControlledTransaction; - Command = class { - constructor(cb) { - __privateAdd(this, _cb); - __privateSet(this, _cb, cb); - } - /** - * Executes the command. - */ - async execute() { - return await __privateGet(this, _cb).call(this); - } - }; - _cb = new WeakMap(); - _NotCommittedOrRolledBackAssertingExecutor = class _NotCommittedOrRolledBackAssertingExecutor { - constructor(executor, state) { - __privateAdd(this, _executor2); - __privateAdd(this, _state2); - if (executor instanceof _NotCommittedOrRolledBackAssertingExecutor) { - __privateSet(this, _executor2, __privateGet(executor, _executor2)); - } else { - __privateSet(this, _executor2, executor); - } - __privateSet(this, _state2, state); - } - get adapter() { - return __privateGet(this, _executor2).adapter; - } - get plugins() { - return __privateGet(this, _executor2).plugins; - } - transformQuery(node, queryId) { - return __privateGet(this, _executor2).transformQuery(node, queryId); - } - compileQuery(node, queryId) { - return __privateGet(this, _executor2).compileQuery(node, queryId); - } - provideConnection(consumer) { - return __privateGet(this, _executor2).provideConnection(consumer); - } - executeQuery(compiledQuery) { - assertNotCommittedOrRolledBack(__privateGet(this, _state2)); - return __privateGet(this, _executor2).executeQuery(compiledQuery); - } - stream(compiledQuery, chunkSize) { - assertNotCommittedOrRolledBack(__privateGet(this, _state2)); - return __privateGet(this, _executor2).stream(compiledQuery, chunkSize); - } - withConnectionProvider(connectionProvider) { - return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withConnectionProvider(connectionProvider), __privateGet(this, _state2)); - } - withPlugin(plugin) { - return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withPlugin(plugin), __privateGet(this, _state2)); - } - withPlugins(plugins) { - return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withPlugins(plugins), __privateGet(this, _state2)); - } - withPluginAtFront(plugin) { - return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withPluginAtFront(plugin), __privateGet(this, _state2)); - } - withoutPlugins() { - return new _NotCommittedOrRolledBackAssertingExecutor(__privateGet(this, _executor2).withoutPlugins(), __privateGet(this, _state2)); - } - }; - _executor2 = new WeakMap(); - _state2 = new WeakMap(); - NotCommittedOrRolledBackAssertingExecutor = _NotCommittedOrRolledBackAssertingExecutor; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js -var init_where_interface = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js -var init_returning_interface = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js -var init_output_interface = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js -var init_having_interface = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js -var init_order_by_interface = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js -function createRawBuilder(props) { - return new RawBuilderImpl(props); -} -var _props45, _RawBuilderImpl_instances, getExecutor_fn, toOperationNode_fn, compile_fn, _RawBuilderImpl, RawBuilderImpl, _rawBuilder, _alias6, AliasedRawBuilderImpl; -var init_raw_builder = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js"() { - init_alias_node(); - init_object_utils(); - init_noop_query_executor(); - init_identifier_node(); - init_operation_node_source(); - _RawBuilderImpl = class _RawBuilderImpl { - constructor(props) { - __privateAdd(this, _RawBuilderImpl_instances); - __privateAdd(this, _props45); - __privateSet(this, _props45, freeze(props)); - } - get expressionType() { - return void 0; - } - get isRawBuilder() { - return true; - } - as(alias) { - return new AliasedRawBuilderImpl(this, alias); - } - $castTo() { - return new _RawBuilderImpl({ ...__privateGet(this, _props45) }); - } - $notNull() { - return new _RawBuilderImpl(__privateGet(this, _props45)); - } - withPlugin(plugin) { - return new _RawBuilderImpl({ - ...__privateGet(this, _props45), - plugins: __privateGet(this, _props45).plugins !== void 0 ? freeze([...__privateGet(this, _props45).plugins, plugin]) : freeze([plugin]) - }); - } - toOperationNode() { - return __privateMethod(this, _RawBuilderImpl_instances, toOperationNode_fn).call(this, __privateMethod(this, _RawBuilderImpl_instances, getExecutor_fn).call(this)); - } - compile(executorProvider) { - return __privateMethod(this, _RawBuilderImpl_instances, compile_fn).call(this, __privateMethod(this, _RawBuilderImpl_instances, getExecutor_fn).call(this, executorProvider)); - } - async execute(executorProvider) { - const executor = __privateMethod(this, _RawBuilderImpl_instances, getExecutor_fn).call(this, executorProvider); - return executor.executeQuery(__privateMethod(this, _RawBuilderImpl_instances, compile_fn).call(this, executor)); - } - }; - _props45 = new WeakMap(); - _RawBuilderImpl_instances = new WeakSet(); - getExecutor_fn = function(executorProvider) { - const executor = executorProvider !== void 0 ? executorProvider.getExecutor() : NOOP_QUERY_EXECUTOR; - return __privateGet(this, _props45).plugins !== void 0 ? executor.withPlugins(__privateGet(this, _props45).plugins) : executor; - }; - toOperationNode_fn = function(executor) { - return executor.transformQuery(__privateGet(this, _props45).rawNode, __privateGet(this, _props45).queryId); - }; - compile_fn = function(executor) { - return executor.compileQuery(__privateMethod(this, _RawBuilderImpl_instances, toOperationNode_fn).call(this, executor), __privateGet(this, _props45).queryId); - }; - RawBuilderImpl = _RawBuilderImpl; - AliasedRawBuilderImpl = class { - constructor(rawBuilder, alias) { - __privateAdd(this, _rawBuilder); - __privateAdd(this, _alias6); - __privateSet(this, _rawBuilder, rawBuilder); - __privateSet(this, _alias6, alias); - } - get expression() { - return __privateGet(this, _rawBuilder); - } - get alias() { - return __privateGet(this, _alias6); - } - get rawBuilder() { - return __privateGet(this, _rawBuilder); - } - toOperationNode() { - return AliasNode.create(__privateGet(this, _rawBuilder).toOperationNode(), isOperationNodeSource(__privateGet(this, _alias6)) ? __privateGet(this, _alias6).toOperationNode() : IdentifierNode.create(__privateGet(this, _alias6))); - } - }; - _rawBuilder = new WeakMap(); - _alias6 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js -function parseParameter(param) { - if (isOperationNodeSource(param)) { - return param.toOperationNode(); - } - return parseValueExpression(param); -} -var sql; -var init_sql = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js"() { - init_identifier_node(); - init_operation_node_source(); - init_raw_node(); - init_value_node(); - init_reference_parser(); - init_table_parser(); - init_value_parser(); - init_query_id(); - init_raw_builder(); - sql = Object.assign((sqlFragments, ...parameters) => { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []) - }); - }, { - ref(columnReference) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChild(parseStringReference(columnReference)) - }); - }, - val(value) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChild(parseValueExpression(value)) - }); - }, - value(value) { - return this.val(value); - }, - table(tableReference) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChild(parseTable(tableReference)) - }); - }, - id(...ids) { - const fragments = new Array(ids.length + 1).fill("."); - fragments[0] = ""; - fragments[fragments.length - 1] = ""; - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)) - }); - }, - lit(value) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)) - }); - }, - literal(value) { - return this.lit(value); - }, - raw(sql2) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithSql(sql2) - }); - }, - join(array2, separator = sql`, `) { - const nodes = new Array(Math.max(2 * array2.length - 1, 0)); - const sep = separator.toOperationNode(); - for (let i = 0; i < array2.length; ++i) { - nodes[2 * i] = parseParameter(array2[i]); - if (i !== array2.length - 1) { - nodes[2 * i + 1] = sep; - } - } - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChildren(nodes) - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js -var init_query_executor = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js -var init_query_executor_provider = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js -var _visitors, OperationNodeVisitor; -var init_operation_node_visitor = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js"() { - init_object_utils(); - OperationNodeVisitor = class { - constructor() { - __publicField(this, "nodeStack", []); - __privateAdd(this, _visitors, freeze({ - AliasNode: this.visitAlias.bind(this), - ColumnNode: this.visitColumn.bind(this), - IdentifierNode: this.visitIdentifier.bind(this), - SchemableIdentifierNode: this.visitSchemableIdentifier.bind(this), - RawNode: this.visitRaw.bind(this), - ReferenceNode: this.visitReference.bind(this), - SelectQueryNode: this.visitSelectQuery.bind(this), - SelectionNode: this.visitSelection.bind(this), - TableNode: this.visitTable.bind(this), - FromNode: this.visitFrom.bind(this), - SelectAllNode: this.visitSelectAll.bind(this), - AndNode: this.visitAnd.bind(this), - OrNode: this.visitOr.bind(this), - ValueNode: this.visitValue.bind(this), - ValueListNode: this.visitValueList.bind(this), - PrimitiveValueListNode: this.visitPrimitiveValueList.bind(this), - ParensNode: this.visitParens.bind(this), - JoinNode: this.visitJoin.bind(this), - OperatorNode: this.visitOperator.bind(this), - WhereNode: this.visitWhere.bind(this), - InsertQueryNode: this.visitInsertQuery.bind(this), - DeleteQueryNode: this.visitDeleteQuery.bind(this), - ReturningNode: this.visitReturning.bind(this), - CreateTableNode: this.visitCreateTable.bind(this), - AddColumnNode: this.visitAddColumn.bind(this), - ColumnDefinitionNode: this.visitColumnDefinition.bind(this), - DropTableNode: this.visitDropTable.bind(this), - DataTypeNode: this.visitDataType.bind(this), - OrderByNode: this.visitOrderBy.bind(this), - OrderByItemNode: this.visitOrderByItem.bind(this), - GroupByNode: this.visitGroupBy.bind(this), - GroupByItemNode: this.visitGroupByItem.bind(this), - UpdateQueryNode: this.visitUpdateQuery.bind(this), - ColumnUpdateNode: this.visitColumnUpdate.bind(this), - LimitNode: this.visitLimit.bind(this), - OffsetNode: this.visitOffset.bind(this), - OnConflictNode: this.visitOnConflict.bind(this), - OnDuplicateKeyNode: this.visitOnDuplicateKey.bind(this), - CreateIndexNode: this.visitCreateIndex.bind(this), - DropIndexNode: this.visitDropIndex.bind(this), - ListNode: this.visitList.bind(this), - PrimaryKeyConstraintNode: this.visitPrimaryKeyConstraint.bind(this), - UniqueConstraintNode: this.visitUniqueConstraint.bind(this), - ReferencesNode: this.visitReferences.bind(this), - CheckConstraintNode: this.visitCheckConstraint.bind(this), - WithNode: this.visitWith.bind(this), - CommonTableExpressionNode: this.visitCommonTableExpression.bind(this), - CommonTableExpressionNameNode: this.visitCommonTableExpressionName.bind(this), - HavingNode: this.visitHaving.bind(this), - CreateSchemaNode: this.visitCreateSchema.bind(this), - DropSchemaNode: this.visitDropSchema.bind(this), - AlterTableNode: this.visitAlterTable.bind(this), - DropColumnNode: this.visitDropColumn.bind(this), - RenameColumnNode: this.visitRenameColumn.bind(this), - AlterColumnNode: this.visitAlterColumn.bind(this), - ModifyColumnNode: this.visitModifyColumn.bind(this), - AddConstraintNode: this.visitAddConstraint.bind(this), - DropConstraintNode: this.visitDropConstraint.bind(this), - RenameConstraintNode: this.visitRenameConstraint.bind(this), - ForeignKeyConstraintNode: this.visitForeignKeyConstraint.bind(this), - CreateViewNode: this.visitCreateView.bind(this), - RefreshMaterializedViewNode: this.visitRefreshMaterializedView.bind(this), - DropViewNode: this.visitDropView.bind(this), - GeneratedNode: this.visitGenerated.bind(this), - DefaultValueNode: this.visitDefaultValue.bind(this), - OnNode: this.visitOn.bind(this), - ValuesNode: this.visitValues.bind(this), - SelectModifierNode: this.visitSelectModifier.bind(this), - CreateTypeNode: this.visitCreateType.bind(this), - DropTypeNode: this.visitDropType.bind(this), - ExplainNode: this.visitExplain.bind(this), - DefaultInsertValueNode: this.visitDefaultInsertValue.bind(this), - AggregateFunctionNode: this.visitAggregateFunction.bind(this), - OverNode: this.visitOver.bind(this), - PartitionByNode: this.visitPartitionBy.bind(this), - PartitionByItemNode: this.visitPartitionByItem.bind(this), - SetOperationNode: this.visitSetOperation.bind(this), - BinaryOperationNode: this.visitBinaryOperation.bind(this), - UnaryOperationNode: this.visitUnaryOperation.bind(this), - UsingNode: this.visitUsing.bind(this), - FunctionNode: this.visitFunction.bind(this), - CaseNode: this.visitCase.bind(this), - WhenNode: this.visitWhen.bind(this), - JSONReferenceNode: this.visitJSONReference.bind(this), - JSONPathNode: this.visitJSONPath.bind(this), - JSONPathLegNode: this.visitJSONPathLeg.bind(this), - JSONOperatorChainNode: this.visitJSONOperatorChain.bind(this), - TupleNode: this.visitTuple.bind(this), - MergeQueryNode: this.visitMergeQuery.bind(this), - MatchedNode: this.visitMatched.bind(this), - AddIndexNode: this.visitAddIndex.bind(this), - CastNode: this.visitCast.bind(this), - FetchNode: this.visitFetch.bind(this), - TopNode: this.visitTop.bind(this), - OutputNode: this.visitOutput.bind(this), - OrActionNode: this.visitOrAction.bind(this), - CollateNode: this.visitCollate.bind(this) - })); - __publicField(this, "visitNode", (node) => { - this.nodeStack.push(node); - __privateGet(this, _visitors)[node.kind](node); - this.nodeStack.pop(); - }); - } - get parentNode() { - return this.nodeStack[this.nodeStack.length - 2]; - } - }; - _visitors = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js -var LIT_WRAP_REGEX, _sql, _parameters, DefaultQueryCompiler, SELECT_MODIFIER_SQL, SELECT_MODIFIER_PRIORITY, JOIN_TYPE_SQL; -var init_default_query_compiler = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js"() { - init_create_table_node(); - init_insert_query_node(); - init_operation_node_visitor(); - init_operator_node(); - init_parens_node(); - init_raw_node(); - init_object_utils(); - init_create_view_node(); - init_set_operation_node(); - init_when_node(); - init_log_once(); - LIT_WRAP_REGEX = /'/g; - DefaultQueryCompiler = class extends OperationNodeVisitor { - constructor() { - super(...arguments); - __privateAdd(this, _sql, ""); - __privateAdd(this, _parameters, []); - } - get numParameters() { - return __privateGet(this, _parameters).length; - } - compileQuery(node, queryId) { - __privateSet(this, _sql, ""); - __privateSet(this, _parameters, []); - this.nodeStack.splice(0, this.nodeStack.length); - this.visitNode(node); - return freeze({ - query: node, - queryId, - sql: this.getSql(), - parameters: [...__privateGet(this, _parameters)] - }); - } - getSql() { - return __privateGet(this, _sql); - } - visitSelectQuery(node) { - const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !InsertQueryNode.is(this.parentNode) && !CreateTableNode.is(this.parentNode) && !CreateViewNode.is(this.parentNode) && !SetOperationNode.is(this.parentNode); - if (this.parentNode === void 0 && node.explain) { - this.visitNode(node.explain); - this.append(" "); - } - if (wrapInParens) { - this.append("("); - } - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append("select"); - if (node.distinctOn) { - this.append(" "); - this.compileDistinctOn(node.distinctOn); - } - if (node.frontModifiers?.length) { - this.append(" "); - this.compileList(node.frontModifiers, " "); - } - if (node.top) { - this.append(" "); - this.visitNode(node.top); - } - if (node.selections) { - this.append(" "); - this.compileList(node.selections); - } - if (node.from) { - this.append(" "); - this.visitNode(node.from); - } - if (node.joins) { - this.append(" "); - this.compileList(node.joins, " "); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - if (node.groupBy) { - this.append(" "); - this.visitNode(node.groupBy); - } - if (node.having) { - this.append(" "); - this.visitNode(node.having); - } - if (node.setOperations) { - this.append(" "); - this.compileList(node.setOperations, " "); - } - if (node.orderBy) { - this.append(" "); - this.visitNode(node.orderBy); - } - if (node.limit) { - this.append(" "); - this.visitNode(node.limit); - } - if (node.offset) { - this.append(" "); - this.visitNode(node.offset); - } - if (node.fetch) { - this.append(" "); - this.visitNode(node.fetch); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(this.sortSelectModifiers([...node.endModifiers]), " "); - } - if (wrapInParens) { - this.append(")"); - } - } - visitFrom(node) { - this.append("from "); - this.compileList(node.froms); - } - visitSelection(node) { - this.visitNode(node.selection); - } - visitColumn(node) { - this.visitNode(node.column); - } - compileDistinctOn(expressions) { - this.append("distinct on ("); - this.compileList(expressions); - this.append(")"); - } - compileList(nodes, separator = ", ") { - const lastIndex = nodes.length - 1; - for (let i = 0; i <= lastIndex; i++) { - this.visitNode(nodes[i]); - if (i < lastIndex) { - this.append(separator); - } - } - } - visitWhere(node) { - this.append("where "); - this.visitNode(node.where); - } - visitHaving(node) { - this.append("having "); - this.visitNode(node.having); - } - visitInsertQuery(node) { - const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode); - if (this.parentNode === void 0 && node.explain) { - this.visitNode(node.explain); - this.append(" "); - } - if (wrapInParens) { - this.append("("); - } - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append(node.replace ? "replace" : "insert"); - if (node.ignore) { - logOnce("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."); - this.append(" ignore"); - } - if (node.orAction) { - this.append(" "); - this.visitNode(node.orAction); - } - if (node.top) { - this.append(" "); - this.visitNode(node.top); - } - if (node.into) { - this.append(" into "); - this.visitNode(node.into); - } - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } - if (node.output) { - this.append(" "); - this.visitNode(node.output); - } - if (node.values) { - this.append(" "); - this.visitNode(node.values); - } - if (node.defaultValues) { - this.append(" "); - this.append("default values"); - } - if (node.onConflict) { - this.append(" "); - this.visitNode(node.onConflict); - } - if (node.onDuplicateKey) { - this.append(" "); - this.visitNode(node.onDuplicateKey); - } - if (node.returning) { - this.append(" "); - this.visitNode(node.returning); - } - if (wrapInParens) { - this.append(")"); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - visitValues(node) { - this.append("values "); - this.compileList(node.values); - } - visitDeleteQuery(node) { - const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode); - if (this.parentNode === void 0 && node.explain) { - this.visitNode(node.explain); - this.append(" "); - } - if (wrapInParens) { - this.append("("); - } - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append("delete "); - if (node.top) { - this.visitNode(node.top); - this.append(" "); - } - this.visitNode(node.from); - if (node.output) { - this.append(" "); - this.visitNode(node.output); - } - if (node.using) { - this.append(" "); - this.visitNode(node.using); - } - if (node.joins) { - this.append(" "); - this.compileList(node.joins, " "); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - if (node.orderBy) { - this.append(" "); - this.visitNode(node.orderBy); - } - if (node.limit) { - this.append(" "); - this.visitNode(node.limit); - } - if (node.returning) { - this.append(" "); - this.visitNode(node.returning); - } - if (wrapInParens) { - this.append(")"); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - visitReturning(node) { - this.append("returning "); - this.compileList(node.selections); - } - visitAlias(node) { - this.visitNode(node.node); - this.append(" as "); - this.visitNode(node.alias); - } - visitReference(node) { - if (node.table) { - this.visitNode(node.table); - this.append("."); - } - this.visitNode(node.column); - } - visitSelectAll(_) { - this.append("*"); - } - visitIdentifier(node) { - this.append(this.getLeftIdentifierWrapper()); - this.compileUnwrappedIdentifier(node); - this.append(this.getRightIdentifierWrapper()); - } - compileUnwrappedIdentifier(node) { - if (!isString2(node.name)) { - throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier."); - } - this.append(this.sanitizeIdentifier(node.name)); - } - visitAnd(node) { - this.visitNode(node.left); - this.append(" and "); - this.visitNode(node.right); - } - visitOr(node) { - this.visitNode(node.left); - this.append(" or "); - this.visitNode(node.right); - } - visitValue(node) { - if (node.immediate) { - this.appendImmediateValue(node.value); - } else { - this.appendValue(node.value); - } - } - visitValueList(node) { - this.append("("); - this.compileList(node.values); - this.append(")"); - } - visitTuple(node) { - this.append("("); - this.compileList(node.values); - this.append(")"); - } - visitPrimitiveValueList(node) { - this.append("("); - const { values } = node; - for (let i = 0; i < values.length; ++i) { - this.appendValue(values[i]); - if (i !== values.length - 1) { - this.append(", "); - } - } - this.append(")"); - } - visitParens(node) { - this.append("("); - this.visitNode(node.node); - this.append(")"); - } - visitJoin(node) { - this.append(JOIN_TYPE_SQL[node.joinType]); - this.append(" "); - this.visitNode(node.table); - if (node.on) { - this.append(" "); - this.visitNode(node.on); - } - } - visitOn(node) { - this.append("on "); - this.visitNode(node.on); - } - visitRaw(node) { - const { sqlFragments, parameters: params } = node; - for (let i = 0; i < sqlFragments.length; ++i) { - this.append(sqlFragments[i]); - if (params.length > i) { - this.visitNode(params[i]); - } - } - } - visitOperator(node) { - this.append(node.operator); - } - visitTable(node) { - this.visitNode(node.table); - } - visitSchemableIdentifier(node) { - if (node.schema) { - this.visitNode(node.schema); - this.append("."); - } - this.visitNode(node.identifier); - } - visitCreateTable(node) { - this.append("create "); - if (node.frontModifiers?.length) { - this.compileList(node.frontModifiers, " "); - this.append(" "); - } - if (node.temporary) { - this.append("temporary "); - } - this.append("table "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.table); - if (!node.selectQuery) { - this.append(" ("); - this.compileList([...node.columns, ...node.constraints ?? []]); - this.append(")"); - } - if (node.onCommit) { - this.append(" on commit "); - this.append(node.onCommit); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - if (node.selectQuery) { - this.append(" as "); - this.visitNode(node.selectQuery); - } - } - visitColumnDefinition(node) { - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.column); - this.append(" "); - this.visitNode(node.dataType); - if (node.unsigned) { - this.append(" unsigned"); - } - if (node.frontModifiers && node.frontModifiers.length > 0) { - this.append(" "); - this.compileList(node.frontModifiers, " "); - } - if (node.generated) { - this.append(" "); - this.visitNode(node.generated); - } - if (node.identity) { - this.append(" identity"); - } - if (node.defaultTo) { - this.append(" "); - this.visitNode(node.defaultTo); - } - if (node.notNull) { - this.append(" not null"); - } - if (node.unique) { - this.append(" unique"); - } - if (node.nullsNotDistinct) { - this.append(" nulls not distinct"); - } - if (node.primaryKey) { - this.append(" primary key"); - } - if (node.autoIncrement) { - this.append(" "); - this.append(this.getAutoIncrement()); - } - if (node.references) { - this.append(" "); - this.visitNode(node.references); - } - if (node.check) { - this.append(" "); - this.visitNode(node.check); - } - if (node.endModifiers && node.endModifiers.length > 0) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - getAutoIncrement() { - return "auto_increment"; - } - visitReferences(node) { - this.append("references "); - this.visitNode(node.table); - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - if (node.onDelete) { - this.append(" on delete "); - this.append(node.onDelete); - } - if (node.onUpdate) { - this.append(" on update "); - this.append(node.onUpdate); - } - } - visitDropTable(node) { - this.append("drop table "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.table); - if (node.cascade) { - this.append(" cascade"); - } - } - visitDataType(node) { - this.append(node.dataType); - } - visitOrderBy(node) { - this.append("order by "); - this.compileList(node.items); - } - visitOrderByItem(node) { - this.visitNode(node.orderBy); - if (node.collation) { - this.append(" "); - this.visitNode(node.collation); - } - if (node.direction) { - this.append(" "); - this.visitNode(node.direction); - } - if (node.nulls) { - this.append(" nulls "); - this.append(node.nulls); - } - } - visitGroupBy(node) { - this.append("group by "); - this.compileList(node.items); - } - visitGroupByItem(node) { - this.visitNode(node.groupBy); - } - visitUpdateQuery(node) { - const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode); - if (this.parentNode === void 0 && node.explain) { - this.visitNode(node.explain); - this.append(" "); - } - if (wrapInParens) { - this.append("("); - } - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append("update "); - if (node.top) { - this.visitNode(node.top); - this.append(" "); - } - if (node.table) { - this.visitNode(node.table); - this.append(" "); - } - this.append("set "); - if (node.updates) { - this.compileList(node.updates); - } - if (node.output) { - this.append(" "); - this.visitNode(node.output); - } - if (node.from) { - this.append(" "); - this.visitNode(node.from); - } - if (node.joins) { - if (!node.from) { - throw new Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins"); - } - this.append(" "); - this.compileList(node.joins, " "); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - if (node.returning) { - this.append(" "); - this.visitNode(node.returning); - } - if (node.orderBy) { - this.append(" "); - this.visitNode(node.orderBy); - } - if (node.limit) { - this.append(" "); - this.visitNode(node.limit); - } - if (wrapInParens) { - this.append(")"); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - visitColumnUpdate(node) { - this.visitNode(node.column); - this.append(" = "); - this.visitNode(node.value); - } - visitLimit(node) { - this.append("limit "); - this.visitNode(node.limit); - } - visitOffset(node) { - this.append("offset "); - this.visitNode(node.offset); - } - visitOnConflict(node) { - this.append("on conflict"); - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } else if (node.constraint) { - this.append(" on constraint "); - this.visitNode(node.constraint); - } else if (node.indexExpression) { - this.append(" ("); - this.visitNode(node.indexExpression); - this.append(")"); - } - if (node.indexWhere) { - this.append(" "); - this.visitNode(node.indexWhere); - } - if (node.doNothing === true) { - this.append(" do nothing"); - } else if (node.updates) { - this.append(" do update set "); - this.compileList(node.updates); - if (node.updateWhere) { - this.append(" "); - this.visitNode(node.updateWhere); - } - } - } - visitOnDuplicateKey(node) { - this.append("on duplicate key update "); - this.compileList(node.updates); - } - visitCreateIndex(node) { - this.append("create "); - if (node.unique) { - this.append("unique "); - } - this.append("index "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.name); - if (node.table) { - this.append(" on "); - this.visitNode(node.table); - } - if (node.using) { - this.append(" using "); - this.visitNode(node.using); - } - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } - if (node.nullsNotDistinct) { - this.append(" nulls not distinct"); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - } - visitDropIndex(node) { - this.append("drop index "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.name); - if (node.table) { - this.append(" on "); - this.visitNode(node.table); - } - if (node.cascade) { - this.append(" cascade"); - } - } - visitCreateSchema(node) { - this.append("create schema "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.schema); - } - visitDropSchema(node) { - this.append("drop schema "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.schema); - if (node.cascade) { - this.append(" cascade"); - } - } - visitPrimaryKeyConstraint(node) { - if (node.name) { - this.append("constraint "); - this.visitNode(node.name); - this.append(" "); - } - this.append("primary key ("); - this.compileList(node.columns); - this.append(")"); - this.buildDeferrable(node); - } - buildDeferrable(node) { - if (node.deferrable !== void 0) { - if (node.deferrable) { - this.append(" deferrable"); - } else { - this.append(" not deferrable"); - } - } - if (node.initiallyDeferred !== void 0) { - if (node.initiallyDeferred) { - this.append(" initially deferred"); - } else { - this.append(" initially immediate"); - } - } - } - visitUniqueConstraint(node) { - if (node.name) { - this.append("constraint "); - this.visitNode(node.name); - this.append(" "); - } - this.append("unique"); - if (node.nullsNotDistinct) { - this.append(" nulls not distinct"); - } - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - this.buildDeferrable(node); - } - visitCheckConstraint(node) { - if (node.name) { - this.append("constraint "); - this.visitNode(node.name); - this.append(" "); - } - this.append("check ("); - this.visitNode(node.expression); - this.append(")"); - } - visitForeignKeyConstraint(node) { - if (node.name) { - this.append("constraint "); - this.visitNode(node.name); - this.append(" "); - } - this.append("foreign key ("); - this.compileList(node.columns); - this.append(") "); - this.visitNode(node.references); - if (node.onDelete) { - this.append(" on delete "); - this.append(node.onDelete); - } - if (node.onUpdate) { - this.append(" on update "); - this.append(node.onUpdate); - } - this.buildDeferrable(node); - } - visitList(node) { - this.compileList(node.items); - } - visitWith(node) { - this.append("with "); - if (node.recursive) { - this.append("recursive "); - } - this.compileList(node.expressions); - } - visitCommonTableExpression(node) { - this.visitNode(node.name); - this.append(" as "); - if (isBoolean2(node.materialized)) { - if (!node.materialized) { - this.append("not "); - } - this.append("materialized "); - } - this.visitNode(node.expression); - } - visitCommonTableExpressionName(node) { - this.visitNode(node.table); - if (node.columns) { - this.append("("); - this.compileList(node.columns); - this.append(")"); - } - } - visitAlterTable(node) { - this.append("alter table "); - this.visitNode(node.table); - this.append(" "); - if (node.renameTo) { - this.append("rename to "); - this.visitNode(node.renameTo); - } - if (node.setSchema) { - this.append("set schema "); - this.visitNode(node.setSchema); - } - if (node.addConstraint) { - this.visitNode(node.addConstraint); - } - if (node.dropConstraint) { - this.visitNode(node.dropConstraint); - } - if (node.renameConstraint) { - this.visitNode(node.renameConstraint); - } - if (node.columnAlterations) { - this.compileColumnAlterations(node.columnAlterations); - } - if (node.addIndex) { - this.visitNode(node.addIndex); - } - if (node.dropIndex) { - this.visitNode(node.dropIndex); - } - } - visitAddColumn(node) { - this.append("add column "); - this.visitNode(node.column); - } - visitRenameColumn(node) { - this.append("rename column "); - this.visitNode(node.column); - this.append(" to "); - this.visitNode(node.renameTo); - } - visitDropColumn(node) { - this.append("drop column "); - this.visitNode(node.column); - } - visitAlterColumn(node) { - this.append("alter column "); - this.visitNode(node.column); - this.append(" "); - if (node.dataType) { - if (this.announcesNewColumnDataType()) { - this.append("type "); - } - this.visitNode(node.dataType); - if (node.dataTypeExpression) { - this.append("using "); - this.visitNode(node.dataTypeExpression); - } - } - if (node.setDefault) { - this.append("set default "); - this.visitNode(node.setDefault); - } - if (node.dropDefault) { - this.append("drop default"); - } - if (node.setNotNull) { - this.append("set not null"); - } - if (node.dropNotNull) { - this.append("drop not null"); - } - } - visitModifyColumn(node) { - this.append("modify column "); - this.visitNode(node.column); - } - visitAddConstraint(node) { - this.append("add "); - this.visitNode(node.constraint); - } - visitDropConstraint(node) { - this.append("drop constraint "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.constraintName); - if (node.modifier === "cascade") { - this.append(" cascade"); - } else if (node.modifier === "restrict") { - this.append(" restrict"); - } - } - visitRenameConstraint(node) { - this.append("rename constraint "); - this.visitNode(node.oldName); - this.append(" to "); - this.visitNode(node.newName); - } - visitSetOperation(node) { - this.append(node.operator); - this.append(" "); - if (node.all) { - this.append("all "); - } - this.visitNode(node.expression); - } - visitCreateView(node) { - this.append("create "); - if (node.orReplace) { - this.append("or replace "); - } - if (node.materialized) { - this.append("materialized "); - } - if (node.temporary) { - this.append("temporary "); - } - this.append("view "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.name); - this.append(" "); - if (node.columns) { - this.append("("); - this.compileList(node.columns); - this.append(") "); - } - if (node.as) { - this.append("as "); - this.visitNode(node.as); - } - } - visitRefreshMaterializedView(node) { - this.append("refresh materialized view "); - if (node.concurrently) { - this.append("concurrently "); - } - this.visitNode(node.name); - if (node.withNoData) { - this.append(" with no data"); - } else { - this.append(" with data"); - } - } - visitDropView(node) { - this.append("drop "); - if (node.materialized) { - this.append("materialized "); - } - this.append("view "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.name); - if (node.cascade) { - this.append(" cascade"); - } - } - visitGenerated(node) { - this.append("generated "); - if (node.always) { - this.append("always "); - } - if (node.byDefault) { - this.append("by default "); - } - this.append("as "); - if (node.identity) { - this.append("identity"); - } - if (node.expression) { - this.append("("); - this.visitNode(node.expression); - this.append(")"); - } - if (node.stored) { - this.append(" stored"); - } - } - visitDefaultValue(node) { - this.append("default "); - this.visitNode(node.defaultValue); - } - visitSelectModifier(node) { - if (node.rawModifier) { - this.visitNode(node.rawModifier); - } else { - this.append(SELECT_MODIFIER_SQL[node.modifier]); - } - if (node.of) { - this.append(" of "); - this.compileList(node.of, ", "); - } - } - visitCreateType(node) { - this.append("create type "); - this.visitNode(node.name); - if (node.enum) { - this.append(" as enum "); - this.visitNode(node.enum); - } - } - visitDropType(node) { - this.append("drop type "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.name); - } - visitExplain(node) { - this.append("explain"); - if (node.options || node.format) { - this.append(" "); - this.append(this.getLeftExplainOptionsWrapper()); - if (node.options) { - this.visitNode(node.options); - if (node.format) { - this.append(this.getExplainOptionsDelimiter()); - } - } - if (node.format) { - this.append("format"); - this.append(this.getExplainOptionAssignment()); - this.append(node.format); - } - this.append(this.getRightExplainOptionsWrapper()); - } - } - visitDefaultInsertValue(_) { - this.append("default"); - } - visitAggregateFunction(node) { - this.append(node.func); - this.append("("); - if (node.distinct) { - this.append("distinct "); - } - this.compileList(node.aggregated); - if (node.orderBy) { - this.append(" "); - this.visitNode(node.orderBy); - } - this.append(")"); - if (node.withinGroup) { - this.append(" within group ("); - this.visitNode(node.withinGroup); - this.append(")"); - } - if (node.filter) { - this.append(" filter("); - this.visitNode(node.filter); - this.append(")"); - } - if (node.over) { - this.append(" "); - this.visitNode(node.over); - } - } - visitOver(node) { - this.append("over("); - if (node.partitionBy) { - this.visitNode(node.partitionBy); - if (node.orderBy) { - this.append(" "); - } - } - if (node.orderBy) { - this.visitNode(node.orderBy); - } - this.append(")"); - } - visitPartitionBy(node) { - this.append("partition by "); - this.compileList(node.items); - } - visitPartitionByItem(node) { - this.visitNode(node.partitionBy); - } - visitBinaryOperation(node) { - this.visitNode(node.leftOperand); - this.append(" "); - this.visitNode(node.operator); - this.append(" "); - this.visitNode(node.rightOperand); - } - visitUnaryOperation(node) { - this.visitNode(node.operator); - if (!this.isMinusOperator(node.operator)) { - this.append(" "); - } - this.visitNode(node.operand); - } - isMinusOperator(node) { - return OperatorNode.is(node) && node.operator === "-"; - } - visitUsing(node) { - this.append("using "); - this.compileList(node.tables); - } - visitFunction(node) { - this.append(node.func); - this.append("("); - this.compileList(node.arguments); - this.append(")"); - } - visitCase(node) { - this.append("case"); - if (node.value) { - this.append(" "); - this.visitNode(node.value); - } - if (node.when) { - this.append(" "); - this.compileList(node.when, " "); - } - if (node.else) { - this.append(" else "); - this.visitNode(node.else); - } - this.append(" end"); - if (node.isStatement) { - this.append(" case"); - } - } - visitWhen(node) { - this.append("when "); - this.visitNode(node.condition); - if (node.result) { - this.append(" then "); - this.visitNode(node.result); - } - } - visitJSONReference(node) { - this.visitNode(node.reference); - this.visitNode(node.traversal); - } - visitJSONPath(node) { - if (node.inOperator) { - this.visitNode(node.inOperator); - } - this.append("'$"); - for (const pathLeg of node.pathLegs) { - this.visitNode(pathLeg); - } - this.append("'"); - } - visitJSONPathLeg(node) { - const isArrayLocation = node.type === "ArrayLocation"; - this.append(isArrayLocation ? "[" : "."); - this.append(typeof node.value === "string" ? this.sanitizeStringLiteral(node.value) : String(node.value)); - if (isArrayLocation) { - this.append("]"); - } - } - visitJSONOperatorChain(node) { - for (let i = 0, len = node.values.length; i < len; i++) { - if (i === len - 1) { - this.visitNode(node.operator); - } else { - this.append("->"); - } - this.visitNode(node.values[i]); - } - } - visitMergeQuery(node) { - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append("merge "); - if (node.top) { - this.visitNode(node.top); - this.append(" "); - } - this.append("into "); - this.visitNode(node.into); - if (node.using) { - this.append(" "); - this.visitNode(node.using); - } - if (node.whens) { - this.append(" "); - this.compileList(node.whens, " "); - } - if (node.returning) { - this.append(" "); - this.visitNode(node.returning); - } - if (node.output) { - this.append(" "); - this.visitNode(node.output); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - visitMatched(node) { - if (node.not) { - this.append("not "); - } - this.append("matched"); - if (node.bySource) { - this.append(" by source"); - } - } - visitAddIndex(node) { - this.append("add "); - if (node.unique) { - this.append("unique "); - } - this.append("index "); - this.visitNode(node.name); - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } - if (node.using) { - this.append(" using "); - this.visitNode(node.using); - } - } - visitCast(node) { - this.append("cast("); - this.visitNode(node.expression); - this.append(" as "); - this.visitNode(node.dataType); - this.append(")"); - } - visitFetch(node) { - this.append("fetch next "); - this.visitNode(node.rowCount); - this.append(` rows ${node.modifier}`); - } - visitOutput(node) { - this.append("output "); - this.compileList(node.selections); - } - visitTop(node) { - this.append(`top(${node.expression})`); - if (node.modifiers) { - this.append(` ${node.modifiers}`); - } - } - visitOrAction(node) { - this.append(node.action); - } - visitCollate(node) { - this.append("collate "); - this.visitNode(node.collation); - } - append(str) { - __privateSet(this, _sql, __privateGet(this, _sql) + str); - } - appendValue(parameter) { - this.addParameter(parameter); - this.append(this.getCurrentParameterPlaceholder()); - } - getLeftIdentifierWrapper() { - return '"'; - } - getRightIdentifierWrapper() { - return '"'; - } - getCurrentParameterPlaceholder() { - return "$" + this.numParameters; - } - getLeftExplainOptionsWrapper() { - return "("; - } - getExplainOptionAssignment() { - return " "; - } - getExplainOptionsDelimiter() { - return ", "; - } - getRightExplainOptionsWrapper() { - return ")"; - } - sanitizeIdentifier(identifier) { - const leftWrap = this.getLeftIdentifierWrapper(); - const rightWrap = this.getRightIdentifierWrapper(); - let sanitized = ""; - for (const c of identifier) { - sanitized += c; - if (c === leftWrap) { - sanitized += leftWrap; - } else if (c === rightWrap) { - sanitized += rightWrap; - } - } - return sanitized; - } - sanitizeStringLiteral(value) { - return value.replace(LIT_WRAP_REGEX, "''"); - } - addParameter(parameter) { - __privateGet(this, _parameters).push(parameter); - } - appendImmediateValue(value) { - if (isString2(value)) { - this.appendStringLiteral(value); - } else if (isNumber2(value) || isBoolean2(value) || isBigInt(value)) { - this.append(value.toString()); - } else if (isNull(value)) { - this.append("null"); - } else if (isDate2(value)) { - this.appendImmediateValue(value.toISOString()); - } else { - throw new Error(`invalid immediate value ${value}`); - } - } - appendStringLiteral(value) { - this.append("'"); - this.append(this.sanitizeStringLiteral(value)); - this.append("'"); - } - sortSelectModifiers(arr) { - arr.sort((left, right) => left.modifier && right.modifier ? SELECT_MODIFIER_PRIORITY[left.modifier] - SELECT_MODIFIER_PRIORITY[right.modifier] : 1); - return freeze(arr); - } - compileColumnAlterations(columnAlterations) { - this.compileList(columnAlterations); - } - /** - * controls whether the dialect adds a "type" keyword before a column's new data - * type in an ALTER TABLE statement. - */ - announcesNewColumnDataType() { - return true; - } - }; - _sql = new WeakMap(); - _parameters = new WeakMap(); - SELECT_MODIFIER_SQL = freeze({ - ForKeyShare: "for key share", - ForNoKeyUpdate: "for no key update", - ForUpdate: "for update", - ForShare: "for share", - NoWait: "nowait", - SkipLocked: "skip locked", - Distinct: "distinct" - }); - SELECT_MODIFIER_PRIORITY = freeze({ - ForKeyShare: 1, - ForNoKeyUpdate: 1, - ForUpdate: 1, - ForShare: 1, - NoWait: 2, - SkipLocked: 2, - Distinct: 0 - }); - JOIN_TYPE_SQL = freeze({ - InnerJoin: "inner join", - LeftJoin: "left join", - RightJoin: "right join", - FullJoin: "full join", - CrossJoin: "cross join", - LateralInnerJoin: "inner join lateral", - LateralLeftJoin: "left join lateral", - LateralCrossJoin: "cross join lateral", - OuterApply: "outer apply", - CrossApply: "cross apply", - Using: "using" - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js -var CompiledQuery; -var init_compiled_query = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js"() { - init_raw_node(); - init_object_utils(); - init_query_id(); - CompiledQuery = freeze({ - raw(sql2, parameters = []) { - return freeze({ - sql: sql2, - query: RawNode.createWithSql(sql2), - parameters: freeze(parameters), - queryId: createQueryId() - }); - } - }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js -var init_database_connection = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js -var init_connection_provider = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js -var init_dummy_driver = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js -var init_dialect = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js -var init_dialect_adapter = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js -var DialectAdapterBase; -var init_dialect_adapter_base = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js"() { - DialectAdapterBase = class { - get supportsCreateIfNotExists() { - return true; - } - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return false; - } - get supportsOutput() { - return false; - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js -var init_database_introspector = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js -function parseSavepointCommand(command, savepointName) { - return RawNode.createWithChildren([ - RawNode.createWithSql(`${command} `), - IdentifierNode.create(savepointName) - // ensures savepointName gets sanitized - ]); -} -var init_savepoint_parser = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js"() { - init_identifier_node(); - init_raw_node(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js -var _config, _connectionMutex, _db, _connection2, SqliteDriver, _db2, SqliteConnection, _promise3, _resolve2, ConnectionMutex; -var init_sqlite_driver = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js"() { - init_select_query_node(); - init_savepoint_parser(); - init_compiled_query(); - init_object_utils(); - init_query_id(); - SqliteDriver = class { - constructor(config4) { - __privateAdd(this, _config); - __privateAdd(this, _connectionMutex, new ConnectionMutex()); - __privateAdd(this, _db); - __privateAdd(this, _connection2); - __privateSet(this, _config, freeze({ ...config4 })); - } - async init() { - __privateSet(this, _db, isFunction3(__privateGet(this, _config).database) ? await __privateGet(this, _config).database() : __privateGet(this, _config).database); - __privateSet(this, _connection2, new SqliteConnection(__privateGet(this, _db))); - if (__privateGet(this, _config).onCreateConnection) { - await __privateGet(this, _config).onCreateConnection(__privateGet(this, _connection2)); - } - } - async acquireConnection() { - await __privateGet(this, _connectionMutex).lock(); - return __privateGet(this, _connection2); - } - async beginTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("begin")); - } - async commitTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("rollback")); - } - async savepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); - } - async rollbackToSavepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); - } - async releaseSavepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId())); - } - async releaseConnection() { - __privateGet(this, _connectionMutex).unlock(); - } - async destroy() { - __privateGet(this, _db)?.close(); - } - }; - _config = new WeakMap(); - _connectionMutex = new WeakMap(); - _db = new WeakMap(); - _connection2 = new WeakMap(); - SqliteConnection = class { - constructor(db) { - __privateAdd(this, _db2); - __privateSet(this, _db2, db); - } - executeQuery(compiledQuery) { - const { sql: sql2, parameters } = compiledQuery; - const stmt = __privateGet(this, _db2).prepare(sql2); - if (stmt.reader) { - return Promise.resolve({ - rows: stmt.all(parameters) - }); - } - const { changes, lastInsertRowid } = stmt.run(parameters); - return Promise.resolve({ - numAffectedRows: changes !== void 0 && changes !== null ? BigInt(changes) : void 0, - insertId: lastInsertRowid !== void 0 && lastInsertRowid !== null ? BigInt(lastInsertRowid) : void 0, - rows: [] - }); - } - async *streamQuery(compiledQuery, _chunkSize) { - const { sql: sql2, parameters, query } = compiledQuery; - const stmt = __privateGet(this, _db2).prepare(sql2); - if (SelectQueryNode.is(query)) { - const iter = stmt.iterate(parameters); - for (const row of iter) { - yield { - rows: [row] - }; - } - } else { - throw new Error("Sqlite driver only supports streaming of select queries"); - } - } - }; - _db2 = new WeakMap(); - ConnectionMutex = class { - constructor() { - __privateAdd(this, _promise3); - __privateAdd(this, _resolve2); - } - async lock() { - while (__privateGet(this, _promise3)) { - await __privateGet(this, _promise3); - } - __privateSet(this, _promise3, new Promise((resolve2) => { - __privateSet(this, _resolve2, resolve2); - })); - } - unlock() { - const resolve2 = __privateGet(this, _resolve2); - __privateSet(this, _promise3, void 0); - __privateSet(this, _resolve2, void 0); - resolve2?.(); - } - }; - _promise3 = new WeakMap(); - _resolve2 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js -var ID_WRAP_REGEX, SqliteQueryCompiler; -var init_sqlite_query_compiler = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js"() { - init_default_query_compiler(); - ID_WRAP_REGEX = /"/g; - SqliteQueryCompiler = class extends DefaultQueryCompiler { - visitOrAction(node) { - this.append("or "); - this.append(node.action); - } - getCurrentParameterPlaceholder() { - return "?"; - } - getLeftExplainOptionsWrapper() { - return ""; - } - getRightExplainOptionsWrapper() { - return ""; - } - getLeftIdentifierWrapper() { - return '"'; - } - getRightIdentifierWrapper() { - return '"'; - } - getAutoIncrement() { - return "autoincrement"; - } - sanitizeIdentifier(identifier) { - return identifier.replace(ID_WRAP_REGEX, '""'); - } - visitDefaultInsertValue(_) { - this.append("null"); - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js -var DEFAULT_MIGRATION_TABLE, DEFAULT_MIGRATION_LOCK_TABLE, NO_MIGRATIONS; -var init_migrator = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js"() { - init_object_utils(); - DEFAULT_MIGRATION_TABLE = "kysely_migration"; - DEFAULT_MIGRATION_LOCK_TABLE = "kysely_migration_lock"; - NO_MIGRATIONS = freeze({ __noMigrations__: true }); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js -var _db3, _SqliteIntrospector_instances, tablesQuery_fn, getTableMetadata_fn, SqliteIntrospector; -var init_sqlite_introspector = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js"() { - init_migrator(); - init_sql(); - SqliteIntrospector = class { - constructor(db) { - __privateAdd(this, _SqliteIntrospector_instances); - __privateAdd(this, _db3); - __privateSet(this, _db3, db); - } - async getSchemas() { - return []; - } - async getTables(options = { withInternalKyselyTables: false }) { - return await __privateMethod(this, _SqliteIntrospector_instances, getTableMetadata_fn).call(this, options); - } - async getMetadata(options) { - return { - tables: await this.getTables(options) - }; - } - }; - _db3 = new WeakMap(); - _SqliteIntrospector_instances = new WeakSet(); - tablesQuery_fn = function(qb, options) { - let tablesQuery = qb.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").select(["name", "sql", "type"]).orderBy("name"); - if (!options.withInternalKyselyTables) { - tablesQuery = tablesQuery.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - } - return tablesQuery; - }; - getTableMetadata_fn = async function(options) { - var _a30; - const tablesResult = await __privateMethod(this, _SqliteIntrospector_instances, tablesQuery_fn).call(this, __privateGet(this, _db3), options).execute(); - const tableMetadata = await __privateGet(this, _db3).with("table_list", (qb) => __privateMethod(this, _SqliteIntrospector_instances, tablesQuery_fn).call(this, qb, options)).selectFrom([ - "table_list as tl", - sql`pragma_table_info(tl.name)`.as("p") - ]).select([ - "tl.name as table", - "p.cid", - "p.name", - "p.type", - "p.notnull", - "p.dflt_value", - "p.pk" - ]).orderBy("tl.name").orderBy("p.cid").execute(); - const columnsByTable = {}; - for (const row of tableMetadata) { - columnsByTable[_a30 = row.table] ?? (columnsByTable[_a30] = []); - columnsByTable[row.table].push(row); - } - return tablesResult.map(({ name, sql: sql2, type }) => { - let autoIncrementCol = sql2?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); - const columns = columnsByTable[name] ?? []; - if (!autoIncrementCol) { - const pkCols = columns.filter((r) => r.pk > 0); - if (pkCols.length === 1 && pkCols[0].type.toLowerCase() === "integer") { - autoIncrementCol = pkCols[0].name; - } - } - return { - name, - isView: type === "view", - columns: columns.map((col) => ({ - name: col.name, - dataType: col.type, - isNullable: !col.notnull, - isAutoIncrementing: col.name === autoIncrementCol, - hasDefaultValue: col.dflt_value != null, - comment: void 0 - })) - }; - }); - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js -var SqliteAdapter; -var init_sqlite_adapter = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js"() { - init_dialect_adapter_base(); - SqliteAdapter = class extends DialectAdapterBase { - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return true; - } - async acquireMigrationLock(_db15, _opt) { - } - async releaseMigrationLock(_db15, _opt) { - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js -var _config2, SqliteDialect; -var init_sqlite_dialect = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js"() { - init_sqlite_driver(); - init_sqlite_query_compiler(); - init_sqlite_introspector(); - init_sqlite_adapter(); - init_object_utils(); - SqliteDialect = class { - constructor(config4) { - __privateAdd(this, _config2); - __privateSet(this, _config2, freeze({ ...config4 })); - } - createDriver() { - return new SqliteDriver(__privateGet(this, _config2)); - } - createQueryCompiler() { - return new SqliteQueryCompiler(); - } - createAdapter() { - return new SqliteAdapter(); - } - createIntrospector(db) { - return new SqliteIntrospector(db); - } - }; - _config2 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js -var init_sqlite_dialect_config = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js -var ID_WRAP_REGEX2, PostgresQueryCompiler; -var init_postgres_query_compiler = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js"() { - init_default_query_compiler(); - ID_WRAP_REGEX2 = /"/g; - PostgresQueryCompiler = class extends DefaultQueryCompiler { - sanitizeIdentifier(identifier) { - return identifier.replace(ID_WRAP_REGEX2, '""'); - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js -var _db4, _PostgresIntrospector_instances, parseTableMetadata_fn, PostgresIntrospector; -var init_postgres_introspector = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js"() { - init_migrator(); - init_object_utils(); - init_sql(); - PostgresIntrospector = class { - constructor(db) { - __privateAdd(this, _PostgresIntrospector_instances); - __privateAdd(this, _db4); - __privateSet(this, _db4, db); - } - async getSchemas() { - let rawSchemas = await __privateGet(this, _db4).selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute(); - return rawSchemas.map((it) => ({ name: it.nspname })); - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = __privateGet(this, _db4).selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c", "a.attrelid", "c.oid").innerJoin("pg_catalog.pg_namespace as ns", "c.relnamespace", "ns.oid").innerJoin("pg_catalog.pg_type as typ", "a.atttypid", "typ.oid").innerJoin("pg_catalog.pg_namespace as dtns", "typ.typnamespace", "dtns.oid").select([ - "a.attname as column", - "a.attnotnull as not_null", - "a.atthasdef as has_default", - "c.relname as table", - "c.relkind as table_type", - "ns.nspname as schema", - "typ.typname as type", - "dtns.nspname as type_schema", - sql`col_description(a.attrelid, a.attnum)`.as("column_description"), - sql`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing") - ]).where("c.relkind", "in", [ - "r", - "v", - "p" - ]).where("ns.nspname", "!~", "^pg_").where("ns.nspname", "!=", "information_schema").where("ns.nspname", "!=", "crdb_internal").where(sql`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum", ">=", 0).where("a.attisdropped", "!=", true).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo(); - if (!options.withInternalKyselyTables) { - query = query.where("c.relname", "!=", DEFAULT_MIGRATION_TABLE).where("c.relname", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - } - const rawColumns = await query.execute(); - return __privateMethod(this, _PostgresIntrospector_instances, parseTableMetadata_fn).call(this, rawColumns); - } - async getMetadata(options) { - return { - tables: await this.getTables(options) - }; - } - }; - _db4 = new WeakMap(); - _PostgresIntrospector_instances = new WeakSet(); - parseTableMetadata_fn = function(columns) { - const tableDictionary = /* @__PURE__ */ new Map(); - for (let i = 0, len = columns.length; i < len; i++) { - const column = columns[i]; - const { schema: schema3, table } = column; - const tableKey = `schema:${schema3};table:${table}`; - if (!tableDictionary.has(tableKey)) { - tableDictionary.set(tableKey, freeze({ - columns: [], - isView: column.table_type === "v", - name: table, - schema: schema3 - })); - } - tableDictionary.get(tableKey).columns.push(freeze({ - comment: column.column_description ?? void 0, - dataType: column.type, - dataTypeSchema: column.type_schema, - hasDefaultValue: column.has_default, - isAutoIncrementing: column.auto_incrementing !== null, - isNullable: !column.not_null, - name: column.column - })); - } - return Array.from(tableDictionary.values()); - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js -var LOCK_ID, PostgresAdapter; -var init_postgres_adapter = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js"() { - init_sql(); - init_dialect_adapter_base(); - LOCK_ID = BigInt("3853314791062309107"); - PostgresAdapter = class extends DialectAdapterBase { - get supportsTransactionalDdl() { - return true; - } - get supportsReturning() { - return true; - } - async acquireMigrationLock(db, _opt) { - await sql`select pg_advisory_xact_lock(${sql.lit(LOCK_ID)})`.execute(db); - } - async releaseMigrationLock(_db15, _opt) { - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js -function extendStackTrace(err, stackError) { - if (isStackHolder(err) && stackError.stack) { - const stackExtension = stackError.stack.split("\n").slice(1).join("\n"); - err.stack += ` -${stackExtension}`; - return err; - } - return err; -} -function isStackHolder(obj) { - return isObject4(obj) && isString2(obj.stack); -} -var init_stack_trace_utils = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js"() { - init_object_utils(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js -function isOkPacket(obj) { - return isObject4(obj) && "insertId" in obj && "affectedRows" in obj; -} -var PRIVATE_RELEASE_METHOD, _config3, _connections2, _pool, _MysqlDriver_instances, acquireConnection_fn, MysqlDriver, _rawConnection, _MysqlConnection_instances, executeQuery_fn, MysqlConnection; -var init_mysql_driver = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js"() { - init_savepoint_parser(); - init_compiled_query(); - init_object_utils(); - init_query_id(); - init_stack_trace_utils(); - PRIVATE_RELEASE_METHOD = Symbol(); - MysqlDriver = class { - constructor(configOrPool) { - __privateAdd(this, _MysqlDriver_instances); - __privateAdd(this, _config3); - __privateAdd(this, _connections2, /* @__PURE__ */ new WeakMap()); - __privateAdd(this, _pool); - __privateSet(this, _config3, freeze({ ...configOrPool })); - } - async init() { - __privateSet(this, _pool, isFunction3(__privateGet(this, _config3).pool) ? await __privateGet(this, _config3).pool() : __privateGet(this, _config3).pool); - } - async acquireConnection() { - const rawConnection = await __privateMethod(this, _MysqlDriver_instances, acquireConnection_fn).call(this); - let connection = __privateGet(this, _connections2).get(rawConnection); - if (!connection) { - connection = new MysqlConnection(rawConnection); - __privateGet(this, _connections2).set(rawConnection, connection); - if (__privateGet(this, _config3)?.onCreateConnection) { - await __privateGet(this, _config3).onCreateConnection(connection); - } - } - if (__privateGet(this, _config3)?.onReserveConnection) { - await __privateGet(this, _config3).onReserveConnection(connection); - } - return connection; - } - async beginTransaction(connection, settings) { - if (settings.isolationLevel || settings.accessMode) { - const parts = []; - if (settings.isolationLevel) { - parts.push(`isolation level ${settings.isolationLevel}`); - } - if (settings.accessMode) { - parts.push(settings.accessMode); - } - const sql2 = `set transaction ${parts.join(", ")}`; - await connection.executeQuery(CompiledQuery.raw(sql2)); - } - await connection.executeQuery(CompiledQuery.raw("begin")); - } - async commitTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("rollback")); - } - async savepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); - } - async rollbackToSavepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); - } - async releaseSavepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("release savepoint", savepointName), createQueryId())); - } - async releaseConnection(connection) { - connection[PRIVATE_RELEASE_METHOD](); - } - async destroy() { - return new Promise((resolve2, reject) => { - __privateGet(this, _pool).end((err) => { - if (err) { - reject(err); - } else { - resolve2(); - } - }); - }); - } - }; - _config3 = new WeakMap(); - _connections2 = new WeakMap(); - _pool = new WeakMap(); - _MysqlDriver_instances = new WeakSet(); - acquireConnection_fn = async function() { - return new Promise((resolve2, reject) => { - __privateGet(this, _pool).getConnection(async (err, rawConnection) => { - if (err) { - reject(err); - } else { - resolve2(rawConnection); - } - }); - }); - }; - MysqlConnection = class { - constructor(rawConnection) { - __privateAdd(this, _MysqlConnection_instances); - __privateAdd(this, _rawConnection); - __privateSet(this, _rawConnection, rawConnection); - } - async executeQuery(compiledQuery) { - try { - const result = await __privateMethod(this, _MysqlConnection_instances, executeQuery_fn).call(this, compiledQuery); - if (isOkPacket(result)) { - const { insertId, affectedRows, changedRows } = result; - return { - insertId: insertId !== void 0 && insertId !== null && insertId.toString() !== "0" ? BigInt(insertId) : void 0, - numAffectedRows: affectedRows !== void 0 && affectedRows !== null ? BigInt(affectedRows) : void 0, - numChangedRows: changedRows !== void 0 && changedRows !== null ? BigInt(changedRows) : void 0, - rows: [] - }; - } else if (Array.isArray(result)) { - return { - rows: result - }; - } - return { - rows: [] - }; - } catch (err) { - throw extendStackTrace(err, new Error()); - } - } - async *streamQuery(compiledQuery, _chunkSize) { - const stream = __privateGet(this, _rawConnection).query(compiledQuery.sql, compiledQuery.parameters).stream({ - objectMode: true - }); - try { - for await (const row of stream) { - yield { - rows: [row] - }; - } - } catch (ex) { - if (ex && typeof ex === "object" && "code" in ex && // @ts-ignore - ex.code === "ERR_STREAM_PREMATURE_CLOSE") { - return; - } - throw ex; - } - } - [PRIVATE_RELEASE_METHOD]() { - __privateGet(this, _rawConnection).release(); - } - }; - _rawConnection = new WeakMap(); - _MysqlConnection_instances = new WeakSet(); - executeQuery_fn = function(compiledQuery) { - return new Promise((resolve2, reject) => { - __privateGet(this, _rawConnection).query(compiledQuery.sql, compiledQuery.parameters, (err, result) => { - if (err) { - reject(err); - } else { - resolve2(result); - } - }); - }); - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js -var LITERAL_ESCAPE_REGEX, ID_WRAP_REGEX3, MysqlQueryCompiler; -var init_mysql_query_compiler = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js"() { - init_default_query_compiler(); - LITERAL_ESCAPE_REGEX = /\\|'/g; - ID_WRAP_REGEX3 = /`/g; - MysqlQueryCompiler = class extends DefaultQueryCompiler { - getCurrentParameterPlaceholder() { - return "?"; - } - getLeftExplainOptionsWrapper() { - return ""; - } - getExplainOptionAssignment() { - return "="; - } - getExplainOptionsDelimiter() { - return " "; - } - getRightExplainOptionsWrapper() { - return ""; - } - getLeftIdentifierWrapper() { - return ID_WRAP_REGEX3.source; - } - getRightIdentifierWrapper() { - return ID_WRAP_REGEX3.source; - } - sanitizeIdentifier(identifier) { - return identifier.replace(ID_WRAP_REGEX3, "``"); - } - /** - * MySQL requires escaping backslashes in string literals when using the - * default NO_BACKSLASH_ESCAPES=OFF mode. Without this, a backslash - * followed by a quote (\') can break out of the string literal. - * - * @see https://dev.mysql.com/doc/refman/9.6/en/string-literals.html - */ - sanitizeStringLiteral(value) { - return value.replace(LITERAL_ESCAPE_REGEX, (char) => char === "\\" ? "\\\\" : "''"); - } - visitCreateIndex(node) { - this.append("create "); - if (node.unique) { - this.append("unique "); - } - this.append("index "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.name); - if (node.using) { - this.append(" using "); - this.visitNode(node.using); - } - if (node.table) { - this.append(" on "); - this.visitNode(node.table); - } - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js -var _db5, _MysqlIntrospector_instances, parseTableMetadata_fn2, MysqlIntrospector; -var init_mysql_introspector = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js"() { - init_migrator(); - init_object_utils(); - init_sql(); - MysqlIntrospector = class { - constructor(db) { - __privateAdd(this, _MysqlIntrospector_instances); - __privateAdd(this, _db5); - __privateSet(this, _db5, db); - } - async getSchemas() { - let rawSchemas = await __privateGet(this, _db5).selectFrom("information_schema.schemata").select("schema_name").$castTo().execute(); - return rawSchemas.map((it) => ({ name: it.SCHEMA_NAME })); - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = __privateGet(this, _db5).selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables", (b) => b.onRef("columns.TABLE_CATALOG", "=", "tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA", "=", "tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME", "=", "tables.TABLE_NAME")).select([ - "columns.COLUMN_NAME", - "columns.COLUMN_DEFAULT", - "columns.TABLE_NAME", - "columns.TABLE_SCHEMA", - "tables.TABLE_TYPE", - "columns.IS_NULLABLE", - "columns.DATA_TYPE", - "columns.EXTRA", - "columns.COLUMN_COMMENT" - ]).where("columns.TABLE_SCHEMA", "=", sql`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo(); - if (!options.withInternalKyselyTables) { - query = query.where("columns.TABLE_NAME", "!=", DEFAULT_MIGRATION_TABLE).where("columns.TABLE_NAME", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - } - const rawColumns = await query.execute(); - return __privateMethod(this, _MysqlIntrospector_instances, parseTableMetadata_fn2).call(this, rawColumns); - } - async getMetadata(options) { - return { - tables: await this.getTables(options) - }; - } - }; - _db5 = new WeakMap(); - _MysqlIntrospector_instances = new WeakSet(); - parseTableMetadata_fn2 = function(columns) { - return columns.reduce((tables, it) => { - let table = tables.find((tbl) => tbl.name === it.TABLE_NAME); - if (!table) { - table = freeze({ - name: it.TABLE_NAME, - isView: it.TABLE_TYPE === "VIEW", - schema: it.TABLE_SCHEMA, - columns: [] - }); - tables.push(table); - } - table.columns.push(freeze({ - name: it.COLUMN_NAME, - dataType: it.DATA_TYPE, - isNullable: it.IS_NULLABLE === "YES", - isAutoIncrementing: it.EXTRA.toLowerCase().includes("auto_increment"), - hasDefaultValue: it.COLUMN_DEFAULT !== null, - comment: it.COLUMN_COMMENT === "" ? void 0 : it.COLUMN_COMMENT - })); - return tables; - }, []); - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js -var LOCK_ID2, LOCK_TIMEOUT_SECONDS, MysqlAdapter; -var init_mysql_adapter = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js"() { - init_sql(); - init_dialect_adapter_base(); - LOCK_ID2 = "ea586330-2c93-47c8-908d-981d9d270f9d"; - LOCK_TIMEOUT_SECONDS = 60 * 60; - MysqlAdapter = class extends DialectAdapterBase { - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return false; - } - async acquireMigrationLock(db, _opt) { - await sql`select get_lock(${sql.lit(LOCK_ID2)}, ${sql.lit(LOCK_TIMEOUT_SECONDS)})`.execute(db); - } - async releaseMigrationLock(db, _opt) { - await sql`select release_lock(${sql.lit(LOCK_ID2)})`.execute(db); - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js -var _config4, MysqlDialect; -var init_mysql_dialect = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js"() { - init_mysql_driver(); - init_mysql_query_compiler(); - init_mysql_introspector(); - init_mysql_adapter(); - MysqlDialect = class { - constructor(config4) { - __privateAdd(this, _config4); - __privateSet(this, _config4, config4); - } - createDriver() { - return new MysqlDriver(__privateGet(this, _config4)); - } - createQueryCompiler() { - return new MysqlQueryCompiler(); - } - createAdapter() { - return new MysqlAdapter(); - } - createIntrospector(db) { - return new MysqlIntrospector(db); - } - }; - _config4 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js -var init_mysql_dialect_config = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js -var PRIVATE_RELEASE_METHOD2, _config5, _connections3, _pool2, PostgresDriver, _client, _options, PostgresConnection; -var init_postgres_driver = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js"() { - init_savepoint_parser(); - init_compiled_query(); - init_object_utils(); - init_query_id(); - init_stack_trace_utils(); - PRIVATE_RELEASE_METHOD2 = Symbol(); - PostgresDriver = class { - constructor(config4) { - __privateAdd(this, _config5); - __privateAdd(this, _connections3, /* @__PURE__ */ new WeakMap()); - __privateAdd(this, _pool2); - __privateSet(this, _config5, freeze({ ...config4 })); - } - async init() { - __privateSet(this, _pool2, isFunction3(__privateGet(this, _config5).pool) ? await __privateGet(this, _config5).pool() : __privateGet(this, _config5).pool); - } - async acquireConnection() { - const client = await __privateGet(this, _pool2).connect(); - let connection = __privateGet(this, _connections3).get(client); - if (!connection) { - connection = new PostgresConnection(client, { - cursor: __privateGet(this, _config5).cursor ?? null - }); - __privateGet(this, _connections3).set(client, connection); - if (__privateGet(this, _config5).onCreateConnection) { - await __privateGet(this, _config5).onCreateConnection(connection); - } - } - if (__privateGet(this, _config5).onReserveConnection) { - await __privateGet(this, _config5).onReserveConnection(connection); - } - return connection; - } - async beginTransaction(connection, settings) { - if (settings.isolationLevel || settings.accessMode) { - let sql2 = "start transaction"; - if (settings.isolationLevel) { - sql2 += ` isolation level ${settings.isolationLevel}`; - } - if (settings.accessMode) { - sql2 += ` ${settings.accessMode}`; - } - await connection.executeQuery(CompiledQuery.raw(sql2)); - } else { - await connection.executeQuery(CompiledQuery.raw("begin")); - } - } - async commitTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("rollback")); - } - async savepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); - } - async rollbackToSavepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); - } - async releaseSavepoint(connection, savepointName, compileQuery) { - await connection.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId())); - } - async releaseConnection(connection) { - connection[PRIVATE_RELEASE_METHOD2](); - } - async destroy() { - if (__privateGet(this, _pool2)) { - const pool = __privateGet(this, _pool2); - __privateSet(this, _pool2, void 0); - await pool.end(); - } - } - }; - _config5 = new WeakMap(); - _connections3 = new WeakMap(); - _pool2 = new WeakMap(); - PostgresConnection = class { - constructor(client, options) { - __privateAdd(this, _client); - __privateAdd(this, _options); - __privateSet(this, _client, client); - __privateSet(this, _options, options); - } - async executeQuery(compiledQuery) { - try { - const { command, rowCount, rows } = await __privateGet(this, _client).query(compiledQuery.sql, [...compiledQuery.parameters]); - return { - numAffectedRows: command === "INSERT" || command === "UPDATE" || command === "DELETE" || command === "MERGE" ? BigInt(rowCount) : void 0, - rows: rows ?? [] - }; - } catch (err) { - throw extendStackTrace(err, new Error()); - } - } - async *streamQuery(compiledQuery, chunkSize) { - if (!__privateGet(this, _options).cursor) { - throw new Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres."); - } - if (!Number.isInteger(chunkSize) || chunkSize <= 0) { - throw new Error("chunkSize must be a positive integer"); - } - const cursor = __privateGet(this, _client).query(new (__privateGet(this, _options)).cursor(compiledQuery.sql, compiledQuery.parameters.slice())); - try { - while (true) { - const rows = await cursor.read(chunkSize); - if (rows.length === 0) { - break; - } - yield { - rows - }; - } - } finally { - await cursor.close(); - } - } - [PRIVATE_RELEASE_METHOD2]() { - __privateGet(this, _client).release(); - } - }; - _client = new WeakMap(); - _options = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js -var init_postgres_dialect_config = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js -var _config6, PostgresDialect; -var init_postgres_dialect = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js"() { - init_postgres_driver(); - init_postgres_introspector(); - init_postgres_query_compiler(); - init_postgres_adapter(); - PostgresDialect = class { - constructor(config4) { - __privateAdd(this, _config6); - __privateSet(this, _config6, config4); - } - createDriver() { - return new PostgresDriver(__privateGet(this, _config6)); - } - createQueryCompiler() { - return new PostgresQueryCompiler(); - } - createAdapter() { - return new PostgresAdapter(); - } - createIntrospector(db) { - return new PostgresIntrospector(db); - } - }; - _config6 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js -var MssqlAdapter; -var init_mssql_adapter = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js"() { - init_migrator(); - init_sql(); - init_dialect_adapter_base(); - MssqlAdapter = class extends DialectAdapterBase { - get supportsCreateIfNotExists() { - return false; - } - get supportsTransactionalDdl() { - return true; - } - get supportsOutput() { - return true; - } - async acquireMigrationLock(db) { - await sql`exec sp_getapplock @DbPrincipal = ${sql.lit("dbo")}, @Resource = ${sql.lit(DEFAULT_MIGRATION_TABLE)}, @LockMode = ${sql.lit("Exclusive")}`.execute(db); - } - async releaseMigrationLock() { - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js -var init_mssql_dialect_config = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js -var PRIVATE_RESET_METHOD, PRIVATE_DESTROY_METHOD, PRIVATE_VALIDATE_METHOD, _config7, _pool3, MssqlDriver, _connection3, _hasSocketError, _tedious, _MssqlConnection_instances, getTediousIsolationLevel_fn, cancelRequest_fn, isConnectionClosed_fn, MssqlConnection, _request, _rows, _streamChunkSize, _subscribers, _tedious2, _rowCount, _MssqlRequest_instances, addParametersToRequest_fn, attachListeners_fn, getTediousDataType_fn, MssqlRequest; -var init_mssql_driver = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js"() { - init_object_utils(); - init_compiled_query(); - init_stack_trace_utils(); - init_random_string(); - init_deferred(); - PRIVATE_RESET_METHOD = Symbol(); - PRIVATE_DESTROY_METHOD = Symbol(); - PRIVATE_VALIDATE_METHOD = Symbol(); - MssqlDriver = class { - constructor(config4) { - __privateAdd(this, _config7); - __privateAdd(this, _pool3); - __privateSet(this, _config7, freeze({ ...config4 })); - const { tarn, tedious, validateConnections } = __privateGet(this, _config7); - const { validateConnections: deprecatedValidateConnections, ...poolOptions } = tarn.options; - __privateSet(this, _pool3, new tarn.Pool({ - ...poolOptions, - create: async () => { - const connection = await tedious.connectionFactory(); - return await new MssqlConnection(connection, tedious).connect(); - }, - destroy: async (connection) => { - await connection[PRIVATE_DESTROY_METHOD](); - }, - // @ts-ignore `tarn` accepts a function that returns a promise here, but - // the types are not aligned and it type errors. - validate: validateConnections === false || deprecatedValidateConnections === false ? void 0 : (connection) => connection[PRIVATE_VALIDATE_METHOD]() - })); - } - async init() { - } - async acquireConnection() { - return await __privateGet(this, _pool3).acquire().promise; - } - async beginTransaction(connection, settings) { - await connection.beginTransaction(settings); - } - async commitTransaction(connection) { - await connection.commitTransaction(); - } - async rollbackTransaction(connection) { - await connection.rollbackTransaction(); - } - async savepoint(connection, savepointName) { - await connection.savepoint(savepointName); - } - async rollbackToSavepoint(connection, savepointName) { - await connection.rollbackTransaction(savepointName); - } - async releaseConnection(connection) { - if (__privateGet(this, _config7).resetConnectionsOnRelease || __privateGet(this, _config7).tedious.resetConnectionOnRelease) { - await connection[PRIVATE_RESET_METHOD](); - } - __privateGet(this, _pool3).release(connection); - } - async destroy() { - await __privateGet(this, _pool3).destroy(); - } - }; - _config7 = new WeakMap(); - _pool3 = new WeakMap(); - MssqlConnection = class { - constructor(connection, tedious) { - __privateAdd(this, _MssqlConnection_instances); - __privateAdd(this, _connection3); - __privateAdd(this, _hasSocketError); - __privateAdd(this, _tedious); - __privateSet(this, _connection3, connection); - __privateSet(this, _hasSocketError, false); - __privateSet(this, _tedious, tedious); - } - async beginTransaction(settings) { - const { isolationLevel } = settings; - await new Promise((resolve2, reject) => __privateGet(this, _connection3).beginTransaction((error49) => { - if (error49) - reject(error49); - else - resolve2(void 0); - }, isolationLevel ? randomString2(8) : void 0, isolationLevel ? __privateMethod(this, _MssqlConnection_instances, getTediousIsolationLevel_fn).call(this, isolationLevel) : void 0)); - } - async commitTransaction() { - await new Promise((resolve2, reject) => __privateGet(this, _connection3).commitTransaction((error49) => { - if (error49) - reject(error49); - else - resolve2(void 0); - })); - } - async connect() { - const { promise: waitForConnected, reject, resolve: resolve2 } = new Deferred(); - __privateGet(this, _connection3).connect((error49) => { - if (error49) { - return reject(error49); - } - resolve2(); - }); - __privateGet(this, _connection3).on("error", (error49) => { - if (error49 instanceof Error && "code" in error49 && error49.code === "ESOCKET") { - __privateSet(this, _hasSocketError, true); - } - console.error(error49); - reject(error49); - }); - function endListener() { - reject(new Error("The connection ended without ever completing the connection")); - } - __privateGet(this, _connection3).once("end", endListener); - await waitForConnected; - __privateGet(this, _connection3).off("end", endListener); - return this; - } - async executeQuery(compiledQuery) { - try { - const deferred = new Deferred(); - const request = new MssqlRequest({ - compiledQuery, - tedious: __privateGet(this, _tedious), - onDone: deferred - }); - __privateGet(this, _connection3).execSql(request.request); - const { rowCount, rows } = await deferred.promise; - return { - numAffectedRows: rowCount !== void 0 ? BigInt(rowCount) : void 0, - rows - }; - } catch (err) { - throw extendStackTrace(err, new Error()); - } - } - async rollbackTransaction(savepointName) { - await new Promise((resolve2, reject) => __privateGet(this, _connection3).rollbackTransaction((error49) => { - if (error49) - reject(error49); - else - resolve2(void 0); - }, savepointName)); - } - async savepoint(savepointName) { - await new Promise((resolve2, reject) => __privateGet(this, _connection3).saveTransaction((error49) => { - if (error49) - reject(error49); - else - resolve2(void 0); - }, savepointName)); - } - async *streamQuery(compiledQuery, chunkSize) { - if (!Number.isInteger(chunkSize) || chunkSize <= 0) { - throw new Error("chunkSize must be a positive integer"); - } - const request = new MssqlRequest({ - compiledQuery, - streamChunkSize: chunkSize, - tedious: __privateGet(this, _tedious) - }); - __privateGet(this, _connection3).execSql(request.request); - try { - while (true) { - const rows = await request.readChunk(); - if (rows.length === 0) { - break; - } - yield { rows }; - if (rows.length < chunkSize) { - break; - } - } - } finally { - await __privateMethod(this, _MssqlConnection_instances, cancelRequest_fn).call(this, request); - } - } - [PRIVATE_DESTROY_METHOD]() { - if ("closed" in __privateGet(this, _connection3) && __privateGet(this, _connection3).closed) { - return Promise.resolve(); - } - return new Promise((resolve2) => { - __privateGet(this, _connection3).once("end", resolve2); - __privateGet(this, _connection3).close(); - }); - } - async [PRIVATE_RESET_METHOD]() { - await new Promise((resolve2, reject) => { - __privateGet(this, _connection3).reset((error49) => { - if (error49) { - return reject(error49); - } - resolve2(); - }); - }); - } - async [PRIVATE_VALIDATE_METHOD]() { - if (__privateGet(this, _hasSocketError) || __privateMethod(this, _MssqlConnection_instances, isConnectionClosed_fn).call(this)) { - return false; - } - try { - const deferred = new Deferred(); - const request = new MssqlRequest({ - compiledQuery: CompiledQuery.raw("select 1"), - onDone: deferred, - tedious: __privateGet(this, _tedious) - }); - __privateGet(this, _connection3).execSql(request.request); - await deferred.promise; - return true; - } catch { - return false; - } - } - }; - _connection3 = new WeakMap(); - _hasSocketError = new WeakMap(); - _tedious = new WeakMap(); - _MssqlConnection_instances = new WeakSet(); - getTediousIsolationLevel_fn = function(isolationLevel) { - const { ISOLATION_LEVEL } = __privateGet(this, _tedious); - const mapper = { - "read committed": ISOLATION_LEVEL.READ_COMMITTED, - "read uncommitted": ISOLATION_LEVEL.READ_UNCOMMITTED, - "repeatable read": ISOLATION_LEVEL.REPEATABLE_READ, - serializable: ISOLATION_LEVEL.SERIALIZABLE, - snapshot: ISOLATION_LEVEL.SNAPSHOT - }; - const tediousIsolationLevel = mapper[isolationLevel]; - if (tediousIsolationLevel === void 0) { - throw new Error(`Unknown isolation level: ${isolationLevel}`); - } - return tediousIsolationLevel; - }; - cancelRequest_fn = function(request) { - return new Promise((resolve2) => { - request.request.once("requestCompleted", resolve2); - const wasCanceled = __privateGet(this, _connection3).cancel(); - if (!wasCanceled) { - request.request.off("requestCompleted", resolve2); - resolve2(); - } - }); - }; - isConnectionClosed_fn = function() { - return "closed" in __privateGet(this, _connection3) && Boolean(__privateGet(this, _connection3).closed); - }; - MssqlRequest = class { - constructor(props) { - __privateAdd(this, _MssqlRequest_instances); - __privateAdd(this, _request); - __privateAdd(this, _rows); - __privateAdd(this, _streamChunkSize); - __privateAdd(this, _subscribers); - __privateAdd(this, _tedious2); - __privateAdd(this, _rowCount); - const { compiledQuery, onDone, streamChunkSize, tedious } = props; - __privateSet(this, _rows, []); - __privateSet(this, _streamChunkSize, streamChunkSize); - __privateSet(this, _subscribers, {}); - __privateSet(this, _tedious2, tedious); - if (onDone) { - const subscriptionKey = "onDone"; - __privateGet(this, _subscribers)[subscriptionKey] = (event, error49) => { - if (event === "chunkReady") { - return; - } - delete __privateGet(this, _subscribers)[subscriptionKey]; - if (event === "error") { - return onDone.reject(error49); - } - onDone.resolve({ - rowCount: __privateGet(this, _rowCount), - rows: __privateGet(this, _rows) - }); - }; - } - __privateSet(this, _request, new (__privateGet(this, _tedious2)).Request(compiledQuery.sql, (err, rowCount) => { - if (err) { - return Object.values(__privateGet(this, _subscribers)).forEach((subscriber) => subscriber("error", err instanceof AggregateError ? err.errors : err)); - } - __privateSet(this, _rowCount, rowCount); - })); - __privateMethod(this, _MssqlRequest_instances, addParametersToRequest_fn).call(this, compiledQuery.parameters); - __privateMethod(this, _MssqlRequest_instances, attachListeners_fn).call(this); - } - get request() { - return __privateGet(this, _request); - } - readChunk() { - const subscriptionKey = this.readChunk.name; - return new Promise((resolve2, reject) => { - __privateGet(this, _subscribers)[subscriptionKey] = (event, error49) => { - delete __privateGet(this, _subscribers)[subscriptionKey]; - if (event === "error") { - return reject(error49); - } - resolve2(__privateGet(this, _rows).splice(0, __privateGet(this, _streamChunkSize))); - }; - __privateGet(this, _request).resume(); - }); - } - }; - _request = new WeakMap(); - _rows = new WeakMap(); - _streamChunkSize = new WeakMap(); - _subscribers = new WeakMap(); - _tedious2 = new WeakMap(); - _rowCount = new WeakMap(); - _MssqlRequest_instances = new WeakSet(); - addParametersToRequest_fn = function(parameters) { - for (let i = 0; i < parameters.length; i++) { - const parameter = parameters[i]; - __privateGet(this, _request).addParameter(String(i + 1), __privateMethod(this, _MssqlRequest_instances, getTediousDataType_fn).call(this, parameter), parameter); - } - }; - attachListeners_fn = function() { - const pauseAndEmitChunkReady = __privateGet(this, _streamChunkSize) ? () => { - if (__privateGet(this, _streamChunkSize) <= __privateGet(this, _rows).length) { - __privateGet(this, _request).pause(); - Object.values(__privateGet(this, _subscribers)).forEach((subscriber) => subscriber("chunkReady")); - } - } : () => { - }; - const rowListener = (columns) => { - const row = {}; - for (const column of columns) { - row[column.metadata.colName] = column.value; - } - __privateGet(this, _rows).push(row); - pauseAndEmitChunkReady(); - }; - __privateGet(this, _request).on("row", rowListener); - __privateGet(this, _request).once("requestCompleted", () => { - Object.values(__privateGet(this, _subscribers)).forEach((subscriber) => subscriber("completed")); - __privateGet(this, _request).off("row", rowListener); - }); - }; - getTediousDataType_fn = function(value) { - if (isNull(value) || isUndefined(value) || isString2(value)) { - return __privateGet(this, _tedious2).TYPES.NVarChar; - } - if (isBigInt(value) || isNumber2(value) && value % 1 === 0) { - if (value < -2147483648 || value > 2147483647) { - return __privateGet(this, _tedious2).TYPES.BigInt; - } else { - return __privateGet(this, _tedious2).TYPES.Int; - } - } - if (isNumber2(value)) { - return __privateGet(this, _tedious2).TYPES.Float; - } - if (isBoolean2(value)) { - return __privateGet(this, _tedious2).TYPES.Bit; - } - if (isDate2(value)) { - return __privateGet(this, _tedious2).TYPES.DateTime; - } - if (isBuffer(value)) { - return __privateGet(this, _tedious2).TYPES.VarBinary; - } - return __privateGet(this, _tedious2).TYPES.NVarChar; - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js -var _db6, MssqlIntrospector; -var init_mssql_introspector = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js"() { - init_migrator(); - init_object_utils(); - MssqlIntrospector = class { - constructor(db) { - __privateAdd(this, _db6); - __privateSet(this, _db6, db); - } - async getSchemas() { - return await __privateGet(this, _db6).selectFrom("sys.schemas").select("name").execute(); - } - async getTables(options = { withInternalKyselyTables: false }) { - const rawColumns = await __privateGet(this, _db6).selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas", "table_schemas.schema_id", "tables.schema_id").innerJoin("sys.columns as columns", "columns.object_id", "tables.object_id").innerJoin("sys.types as types", "types.user_type_id", "columns.user_type_id").leftJoin("sys.schemas as type_schemas", "type_schemas.schema_id", "types.schema_id").leftJoin("sys.extended_properties as comments", (join2) => join2.onRef("comments.major_id", "=", "tables.object_id").onRef("comments.minor_id", "=", "columns.column_id").on("comments.name", "=", "MS_Description")).$if(!options.withInternalKyselyTables, (qb) => qb.where("tables.name", "!=", DEFAULT_MIGRATION_TABLE).where("tables.name", "!=", DEFAULT_MIGRATION_LOCK_TABLE)).select([ - "tables.name as table_name", - (eb) => eb.ref("tables.type").$castTo().as("table_type"), - "table_schemas.name as table_schema_name", - "columns.default_object_id as column_default_object_id", - "columns.generated_always_type_desc as column_generated_always_type", - "columns.is_computed as column_is_computed", - "columns.is_identity as column_is_identity", - "columns.is_nullable as column_is_nullable", - "columns.is_rowguidcol as column_is_rowguidcol", - "columns.name as column_name", - "types.is_nullable as type_is_nullable", - "types.name as type_name", - "type_schemas.name as type_schema_name", - "comments.value as column_comment" - ]).unionAll(__privateGet(this, _db6).selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas", "view_schemas.schema_id", "views.schema_id").innerJoin("sys.columns as columns", "columns.object_id", "views.object_id").innerJoin("sys.types as types", "types.user_type_id", "columns.user_type_id").leftJoin("sys.schemas as type_schemas", "type_schemas.schema_id", "types.schema_id").leftJoin("sys.extended_properties as comments", (join2) => join2.onRef("comments.major_id", "=", "views.object_id").onRef("comments.minor_id", "=", "columns.column_id").on("comments.name", "=", "MS_Description")).select([ - "views.name as table_name", - "views.type as table_type", - "view_schemas.name as table_schema_name", - "columns.default_object_id as column_default_object_id", - "columns.generated_always_type_desc as column_generated_always_type", - "columns.is_computed as column_is_computed", - "columns.is_identity as column_is_identity", - "columns.is_nullable as column_is_nullable", - "columns.is_rowguidcol as column_is_rowguidcol", - "columns.name as column_name", - "types.is_nullable as type_is_nullable", - "types.name as type_name", - "type_schemas.name as type_schema_name", - "comments.value as column_comment" - ])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(); - const tableDictionary = {}; - for (const rawColumn of rawColumns) { - const key = `${rawColumn.table_schema_name}.${rawColumn.table_name}`; - const table = tableDictionary[key] = tableDictionary[key] || freeze({ - columns: [], - isView: rawColumn.table_type === "V ", - name: rawColumn.table_name, - schema: rawColumn.table_schema_name ?? void 0 - }); - table.columns.push(freeze({ - dataType: rawColumn.type_name, - dataTypeSchema: rawColumn.type_schema_name ?? void 0, - hasDefaultValue: rawColumn.column_default_object_id > 0 || rawColumn.column_generated_always_type !== "NOT_APPLICABLE" || rawColumn.column_is_identity || rawColumn.column_is_computed || rawColumn.column_is_rowguidcol, - isAutoIncrementing: rawColumn.column_is_identity, - isNullable: rawColumn.column_is_nullable && rawColumn.type_is_nullable, - name: rawColumn.column_name, - comment: rawColumn.column_comment ?? void 0 - })); - } - return Object.values(tableDictionary); - } - async getMetadata(options) { - return { - tables: await this.getTables(options) - }; - } - }; - _db6 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js -var COLLATION_CHAR_REGEX, MssqlQueryCompiler; -var init_mssql_query_compiler = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js"() { - init_default_query_compiler(); - COLLATION_CHAR_REGEX = /^[a-z0-9_]$/i; - MssqlQueryCompiler = class extends DefaultQueryCompiler { - getCurrentParameterPlaceholder() { - return `@${this.numParameters}`; - } - visitOffset(node) { - super.visitOffset(node); - this.append(" rows"); - } - // mssql allows multi-column alterations in a single statement, - // but you can only use the command keyword/s once. - // it also doesn't support multiple kinds of commands in the same - // alter table statement, but we compile that anyway for the sake - // of WYSIWYG. - compileColumnAlterations(columnAlterations) { - const nodesByKind = {}; - for (const columnAlteration of columnAlterations) { - if (!nodesByKind[columnAlteration.kind]) { - nodesByKind[columnAlteration.kind] = []; - } - nodesByKind[columnAlteration.kind].push(columnAlteration); - } - let first = true; - if (nodesByKind.AddColumnNode) { - this.append("add "); - this.compileList(nodesByKind.AddColumnNode); - first = false; - } - if (nodesByKind.AlterColumnNode) { - if (!first) - this.append(", "); - this.compileList(nodesByKind.AlterColumnNode); - } - if (nodesByKind.DropColumnNode) { - if (!first) - this.append(", "); - this.append("drop column "); - this.compileList(nodesByKind.DropColumnNode); - } - if (nodesByKind.ModifyColumnNode) { - if (!first) - this.append(", "); - this.compileList(nodesByKind.ModifyColumnNode); - } - if (nodesByKind.RenameColumnNode) { - if (!first) - this.append(", "); - this.compileList(nodesByKind.RenameColumnNode); - } - } - visitAddColumn(node) { - this.visitNode(node.column); - } - visitDropColumn(node) { - this.visitNode(node.column); - } - visitMergeQuery(node) { - super.visitMergeQuery(node); - this.append(";"); - } - visitCollate(node) { - this.append("collate "); - const { name } = node.collation; - for (const char of name) { - if (!COLLATION_CHAR_REGEX.test(char)) { - throw new Error(`Invalid collation: ${name}`); - } - } - this.append(name); - } - announcesNewColumnDataType() { - return false; - } - }; - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js -var _config8, MssqlDialect; -var init_mssql_dialect = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js"() { - init_mssql_adapter(); - init_mssql_driver(); - init_mssql_introspector(); - init_mssql_query_compiler(); - MssqlDialect = class { - constructor(config4) { - __privateAdd(this, _config8); - __privateSet(this, _config8, config4); - } - createDriver() { - return new MssqlDriver(__privateGet(this, _config8)); - } - createQueryCompiler() { - return new MssqlQueryCompiler(); - } - createAdapter() { - return new MssqlAdapter(); - } - createIntrospector(db) { - return new MssqlIntrospector(db); - } - }; - _config8 = new WeakMap(); - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js -var init_query_compiler = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js -var init_file_migration_provider = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js -var init_kysely_plugin = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js -var init_camel_case_plugin = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js -var init_deduplicate_joins_plugin = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js -var init_parse_json_results_plugin = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js -var init_handle_empty_in_lists_plugin = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js -var init_handle_empty_in_lists = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js -var init_constraint_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js -var init_operation_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js -var init_simple_reference_expression_node = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js -var init_column_type = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js -var init_explainable = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js -var init_streamable = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js -var init_infer_result = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js"() { - } -}); - -// ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js -var init_esm3 = __esm({ - "../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js"() { - init_kysely(); - init_query_creator(); - init_expression(); - init_expression_wrapper(); - init_where_interface(); - init_returning_interface(); - init_output_interface(); - init_having_interface(); - init_order_by_interface(); - init_select_query_builder(); - init_insert_query_builder(); - init_update_query_builder(); - init_delete_query_builder(); - init_no_result_error(); - init_join_builder(); - init_function_module(); - init_insert_result(); - init_delete_result(); - init_update_result(); - init_on_conflict_builder(); - init_aggregate_function_builder(); - init_case_builder(); - init_json_path_builder(); - init_merge_query_builder(); - init_merge_result(); - init_order_by_item_builder(); - init_raw_builder(); - init_sql(); - init_query_executor(); - init_default_query_executor(); - init_noop_query_executor(); - init_query_executor_provider(); - init_default_query_compiler(); - init_compiled_query(); - init_schema(); - init_create_table_builder(); - init_create_type_builder(); - init_drop_table_builder(); - init_drop_type_builder(); - init_create_index_builder(); - init_drop_index_builder(); - init_create_schema_builder(); - init_drop_schema_builder(); - init_column_definition_builder(); - init_foreign_key_constraint_builder(); - init_alter_table_builder(); - init_create_view_builder(); - init_refresh_materialized_view_builder(); - init_drop_view_builder(); - init_alter_column_builder(); - init_dynamic(); - init_dynamic_reference_builder(); - init_dynamic_table_builder(); - init_driver(); - init_database_connection(); - init_connection_provider(); - init_default_connection_provider(); - init_single_connection_provider(); - init_dummy_driver(); - init_dialect(); - init_dialect_adapter(); - init_dialect_adapter_base(); - init_database_introspector(); - init_sqlite_dialect(); - init_sqlite_dialect_config(); - init_sqlite_driver(); - init_postgres_query_compiler(); - init_postgres_introspector(); - init_postgres_adapter(); - init_mysql_dialect(); - init_mysql_dialect_config(); - init_mysql_driver(); - init_mysql_query_compiler(); - init_mysql_introspector(); - init_mysql_adapter(); - init_postgres_driver(); - init_postgres_dialect_config(); - init_postgres_dialect(); - init_sqlite_query_compiler(); - init_sqlite_introspector(); - init_sqlite_adapter(); - init_mssql_adapter(); - init_mssql_dialect_config(); - init_mssql_dialect(); - init_mssql_driver(); - init_mssql_introspector(); - init_mssql_query_compiler(); - init_default_query_compiler(); - init_query_compiler(); - init_migrator(); - init_file_migration_provider(); - init_kysely_plugin(); - init_camel_case_plugin(); - init_deduplicate_joins_plugin(); - init_with_schema_plugin(); - init_parse_json_results_plugin(); - init_handle_empty_in_lists_plugin(); - init_handle_empty_in_lists(); - init_add_column_node(); - init_add_constraint_node(); - init_add_index_node(); - init_aggregate_function_node(); - init_alias_node(); - init_alter_column_node(); - init_alter_table_node(); - init_and_node(); - init_binary_operation_node(); - init_case_node(); - init_cast_node(); - init_check_constraint_node(); - init_collate_node(); - init_column_definition_node(); - init_column_node(); - init_column_update_node(); - init_common_table_expression_name_node(); - init_common_table_expression_node(); - init_constraint_node(); - init_create_index_node(); - init_create_schema_node(); - init_create_table_node(); - init_create_type_node(); - init_create_view_node(); - init_refresh_materialized_view_node(); - init_data_type_node(); - init_default_insert_value_node(); - init_default_value_node(); - init_delete_query_node(); - init_drop_column_node(); - init_drop_constraint_node(); - init_drop_index_node(); - init_drop_schema_node(); - init_drop_table_node(); - init_drop_type_node(); - init_drop_view_node(); - init_explain_node(); - init_fetch_node(); - init_foreign_key_constraint_node(); - init_from_node(); - init_function_node(); - init_generated_node(); - init_group_by_item_node(); - init_group_by_node(); - init_having_node(); - init_identifier_node(); - init_insert_query_node(); - init_join_node(); - init_json_operator_chain_node(); - init_json_path_leg_node(); - init_json_path_node(); - init_json_reference_node(); - init_limit_node(); - init_list_node(); - init_matched_node(); - init_merge_query_node(); - init_modify_column_node(); - init_offset_node(); - init_on_conflict_node(); - init_on_duplicate_key_node(); - init_on_node(); - init_operation_node_source(); - init_operation_node_transformer(); - init_operation_node_visitor(); - init_operation_node(); - init_operator_node(); - init_or_action_node(); - init_or_node(); - init_order_by_item_node(); - init_order_by_node(); - init_output_node(); - init_over_node(); - init_parens_node(); - init_partition_by_item_node(); - init_partition_by_node(); - init_primary_key_constraint_node(); - init_primitive_value_list_node(); - init_query_node(); - init_raw_node(); - init_reference_node(); - init_references_node(); - init_rename_column_node(); - init_rename_constraint_node(); - init_returning_node(); - init_schemable_identifier_node(); - init_select_all_node(); - init_select_modifier_node(); - init_select_query_node(); - init_selection_node(); - init_set_operation_node(); - init_simple_reference_expression_node(); - init_table_node(); - init_top_node(); - init_tuple_node(); - init_unary_operation_node(); - init_unique_constraint_node(); - init_update_query_node(); - init_using_node(); - init_value_list_node(); - init_value_node(); - init_values_node(); - init_when_node(); - init_where_node(); - init_with_node(); - init_column_type(); - init_compilable(); - init_explainable(); - init_streamable(); - init_log(); - init_infer_result(); - } -}); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/string.mjs -function capitalizeFirstLetter(str) { - return str.charAt(0).toUpperCase() + str.slice(1); -} -var init_string = __esm({ - "../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/string.mjs"() { - } -}); - -// ../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/bun-sqlite-dialect-na--YwnN.mjs -var bun_sqlite_dialect_na_YwnN_exports = {}; -__export(bun_sqlite_dialect_na_YwnN_exports, { - BunSqliteDialect: () => BunSqliteDialect -}); -var BunSqliteAdapter, _config9, _connectionMutex2, _db7, _connection4, _a15, BunSqliteDriver, _db8, _a16, BunSqliteConnection, _promise4, _resolve3, _a17, ConnectionMutex2, _db9, _BunSqliteIntrospector_instances, getTableMetadata_fn2, _a18, BunSqliteIntrospector, BunSqliteQueryCompiler, _config10, _a19, BunSqliteDialect; -var init_bun_sqlite_dialect_na_YwnN = __esm({ - "../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/bun-sqlite-dialect-na--YwnN.mjs"() { - init_esm3(); - BunSqliteAdapter = class { - get supportsCreateIfNotExists() { - return true; - } - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return true; - } - async acquireMigrationLock() { - } - async releaseMigrationLock() { - } - get supportsOutput() { - return true; - } - }; - BunSqliteDriver = (_a15 = class { - constructor(config4) { - __privateAdd(this, _config9); - __privateAdd(this, _connectionMutex2, new ConnectionMutex2()); - __privateAdd(this, _db7); - __privateAdd(this, _connection4); - __privateSet(this, _config9, { ...config4 }); - } - async init() { - __privateSet(this, _db7, __privateGet(this, _config9).database); - __privateSet(this, _connection4, new BunSqliteConnection(__privateGet(this, _db7))); - if (__privateGet(this, _config9).onCreateConnection) await __privateGet(this, _config9).onCreateConnection(__privateGet(this, _connection4)); - } - async acquireConnection() { - await __privateGet(this, _connectionMutex2).lock(); - return __privateGet(this, _connection4); - } - async beginTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("begin")); - } - async commitTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("rollback")); - } - async releaseConnection() { - __privateGet(this, _connectionMutex2).unlock(); - } - async destroy() { - __privateGet(this, _db7)?.close(); - } - }, _config9 = new WeakMap(), _connectionMutex2 = new WeakMap(), _db7 = new WeakMap(), _connection4 = new WeakMap(), _a15); - BunSqliteConnection = (_a16 = class { - constructor(db) { - __privateAdd(this, _db8); - __privateSet(this, _db8, db); - } - executeQuery(compiledQuery) { - const { sql: sql2, parameters } = compiledQuery; - const stmt = __privateGet(this, _db8).prepare(sql2); - return Promise.resolve({ rows: stmt.all(parameters) }); - } - async *streamQuery() { - throw new Error("Streaming query is not supported by SQLite driver."); - } - }, _db8 = new WeakMap(), _a16); - ConnectionMutex2 = (_a17 = class { - constructor() { - __privateAdd(this, _promise4); - __privateAdd(this, _resolve3); - } - async lock() { - while (__privateGet(this, _promise4) !== void 0) await __privateGet(this, _promise4); - __privateSet(this, _promise4, new Promise((resolve2) => { - __privateSet(this, _resolve3, resolve2); - })); - } - unlock() { - const resolve2 = __privateGet(this, _resolve3); - __privateSet(this, _promise4, void 0); - __privateSet(this, _resolve3, void 0); - resolve2?.(); - } - }, _promise4 = new WeakMap(), _resolve3 = new WeakMap(), _a17); - BunSqliteIntrospector = (_a18 = class { - constructor(db) { - __privateAdd(this, _BunSqliteIntrospector_instances); - __privateAdd(this, _db9); - __privateSet(this, _db9, db); - } - async getSchemas() { - return []; - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = __privateGet(this, _db9).selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo(); - if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - const tables = await query.execute(); - return Promise.all(tables.map(({ name }) => __privateMethod(this, _BunSqliteIntrospector_instances, getTableMetadata_fn2).call(this, name))); - } - async getMetadata(options) { - return { tables: await this.getTables(options) }; - } - }, _db9 = new WeakMap(), _BunSqliteIntrospector_instances = new WeakSet(), getTableMetadata_fn2 = async function(table) { - const db = __privateGet(this, _db9); - const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); - return { - name: table, - columns: (await db.selectFrom(sql`pragma_table_info(${table})`.as("table_info")).select([ - "name", - "type", - "notnull", - "dflt_value" - ]).execute()).map((col) => ({ - name: col.name, - dataType: col.type, - isNullable: !col.notnull, - isAutoIncrementing: col.name === autoIncrementCol, - hasDefaultValue: col.dflt_value != null - })), - isView: true - }; - }, _a18); - BunSqliteQueryCompiler = class extends DefaultQueryCompiler { - getCurrentParameterPlaceholder() { - return "?"; - } - getLeftIdentifierWrapper() { - return '"'; - } - getRightIdentifierWrapper() { - return '"'; - } - getAutoIncrement() { - return "autoincrement"; - } - }; - BunSqliteDialect = (_a19 = class { - constructor(config4) { - __privateAdd(this, _config10); - __privateSet(this, _config10, { ...config4 }); - } - createDriver() { - return new BunSqliteDriver(__privateGet(this, _config10)); - } - createQueryCompiler() { - return new BunSqliteQueryCompiler(); - } - createAdapter() { - return new BunSqliteAdapter(); - } - createIntrospector(db) { - return new BunSqliteIntrospector(db); - } - }, _config10 = new WeakMap(), _a19); - } -}); - -// ../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/node-sqlite-dialect.mjs -var node_sqlite_dialect_exports = {}; -__export(node_sqlite_dialect_exports, { - NodeSqliteDialect: () => NodeSqliteDialect -}); -var NodeSqliteAdapter, _config11, _connectionMutex3, _db10, _connection5, _a20, NodeSqliteDriver, _db11, _a21, NodeSqliteConnection, _promise5, _resolve4, _a22, ConnectionMutex3, _db12, _NodeSqliteIntrospector_instances, getTableMetadata_fn3, _a23, NodeSqliteIntrospector, NodeSqliteQueryCompiler, _config12, _a24, NodeSqliteDialect; -var init_node_sqlite_dialect = __esm({ - "../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/node-sqlite-dialect.mjs"() { - init_esm3(); - NodeSqliteAdapter = class { - get supportsCreateIfNotExists() { - return true; - } - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return true; - } - async acquireMigrationLock() { - } - async releaseMigrationLock() { - } - get supportsOutput() { - return true; - } - }; - NodeSqliteDriver = (_a20 = class { - constructor(config4) { - __privateAdd(this, _config11); - __privateAdd(this, _connectionMutex3, new ConnectionMutex3()); - __privateAdd(this, _db10); - __privateAdd(this, _connection5); - __privateSet(this, _config11, { ...config4 }); - } - async init() { - __privateSet(this, _db10, __privateGet(this, _config11).database); - __privateSet(this, _connection5, new NodeSqliteConnection(__privateGet(this, _db10))); - if (__privateGet(this, _config11).onCreateConnection) await __privateGet(this, _config11).onCreateConnection(__privateGet(this, _connection5)); - } - async acquireConnection() { - await __privateGet(this, _connectionMutex3).lock(); - return __privateGet(this, _connection5); - } - async beginTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("begin")); - } - async commitTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection) { - await connection.executeQuery(CompiledQuery.raw("rollback")); - } - async releaseConnection() { - __privateGet(this, _connectionMutex3).unlock(); - } - async destroy() { - __privateGet(this, _db10)?.close(); - } - }, _config11 = new WeakMap(), _connectionMutex3 = new WeakMap(), _db10 = new WeakMap(), _connection5 = new WeakMap(), _a20); - NodeSqliteConnection = (_a21 = class { - constructor(db) { - __privateAdd(this, _db11); - __privateSet(this, _db11, db); - } - executeQuery(compiledQuery) { - const { sql: sql2, parameters } = compiledQuery; - const rows = __privateGet(this, _db11).prepare(sql2).all(...parameters); - return Promise.resolve({ rows }); - } - async *streamQuery() { - throw new Error("Streaming query is not supported by SQLite driver."); - } - }, _db11 = new WeakMap(), _a21); - ConnectionMutex3 = (_a22 = class { - constructor() { - __privateAdd(this, _promise5); - __privateAdd(this, _resolve4); - } - async lock() { - while (__privateGet(this, _promise5) !== void 0) await __privateGet(this, _promise5); - __privateSet(this, _promise5, new Promise((resolve2) => { - __privateSet(this, _resolve4, resolve2); - })); - } - unlock() { - const resolve2 = __privateGet(this, _resolve4); - __privateSet(this, _promise5, void 0); - __privateSet(this, _resolve4, void 0); - resolve2?.(); - } - }, _promise5 = new WeakMap(), _resolve4 = new WeakMap(), _a22); - NodeSqliteIntrospector = (_a23 = class { - constructor(db) { - __privateAdd(this, _NodeSqliteIntrospector_instances); - __privateAdd(this, _db12); - __privateSet(this, _db12, db); - } - async getSchemas() { - return []; - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = __privateGet(this, _db12).selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo(); - if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - const tables = await query.execute(); - return Promise.all(tables.map(({ name }) => __privateMethod(this, _NodeSqliteIntrospector_instances, getTableMetadata_fn3).call(this, name))); - } - async getMetadata(options) { - return { tables: await this.getTables(options) }; - } - }, _db12 = new WeakMap(), _NodeSqliteIntrospector_instances = new WeakSet(), getTableMetadata_fn3 = async function(table) { - const db = __privateGet(this, _db12); - const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); - return { - name: table, - columns: (await db.selectFrom(sql`pragma_table_info(${table})`.as("table_info")).select([ - "name", - "type", - "notnull", - "dflt_value" - ]).execute()).map((col) => ({ - name: col.name, - dataType: col.type, - isNullable: !col.notnull, - isAutoIncrementing: col.name === autoIncrementCol, - hasDefaultValue: col.dflt_value != null - })), - isView: true - }; - }, _a23); - NodeSqliteQueryCompiler = class extends DefaultQueryCompiler { - getCurrentParameterPlaceholder() { - return "?"; - } - getLeftIdentifierWrapper() { - return '"'; - } - getRightIdentifierWrapper() { - return '"'; - } - getAutoIncrement() { - return "autoincrement"; - } - }; - NodeSqliteDialect = (_a24 = class { - constructor(config4) { - __privateAdd(this, _config12); - __privateSet(this, _config12, { ...config4 }); - } - createDriver() { - return new NodeSqliteDriver(__privateGet(this, _config12)); - } - createQueryCompiler() { - return new NodeSqliteQueryCompiler(); - } - createAdapter() { - return new NodeSqliteAdapter(); - } - createIntrospector(db) { - return new NodeSqliteIntrospector(db); - } - }, _config12 = new WeakMap(), _a24); - } -}); - -// ../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/d1-sqlite-dialect-C2B7YsIT.mjs -var d1_sqlite_dialect_C2B7YsIT_exports = {}; -__export(d1_sqlite_dialect_C2B7YsIT_exports, { - D1SqliteDialect: () => D1SqliteDialect -}); -var D1SqliteAdapter, _config13, _connection6, _a25, D1SqliteDriver, _db13, _a26, D1SqliteConnection, _db14, _d1, _a27, D1SqliteIntrospector, D1SqliteQueryCompiler, _config14, _a28, D1SqliteDialect; -var init_d1_sqlite_dialect_C2B7YsIT = __esm({ - "../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/d1-sqlite-dialect-C2B7YsIT.mjs"() { - init_esm3(); - D1SqliteAdapter = class extends SqliteAdapter { - }; - D1SqliteDriver = (_a25 = class { - constructor(config4) { - __privateAdd(this, _config13); - __privateAdd(this, _connection6); - __privateSet(this, _config13, { ...config4 }); - } - async init() { - __privateSet(this, _connection6, new D1SqliteConnection(__privateGet(this, _config13).database)); - if (__privateGet(this, _config13).onCreateConnection) await __privateGet(this, _config13).onCreateConnection(__privateGet(this, _connection6)); - } - async acquireConnection() { - return __privateGet(this, _connection6); - } - async beginTransaction() { - throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead."); - } - async commitTransaction() { - throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead."); - } - async rollbackTransaction() { - throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead."); - } - async releaseConnection() { - } - async destroy() { - } - }, _config13 = new WeakMap(), _connection6 = new WeakMap(), _a25); - D1SqliteConnection = (_a26 = class { - constructor(db) { - __privateAdd(this, _db13); - __privateSet(this, _db13, db); - } - async executeQuery(compiledQuery) { - const results = await __privateGet(this, _db13).prepare(compiledQuery.sql).bind(...compiledQuery.parameters).all(); - const numAffectedRows = results.meta.changes != null ? BigInt(results.meta.changes) : void 0; - return { - insertId: results.meta.last_row_id === void 0 || results.meta.last_row_id === null ? void 0 : BigInt(results.meta.last_row_id), - rows: results?.results || [], - numAffectedRows - }; - } - async *streamQuery() { - throw new Error("D1 does not support streaming queries."); - } - }, _db13 = new WeakMap(), _a26); - D1SqliteIntrospector = (_a27 = class { - constructor(db, d1) { - __privateAdd(this, _db14); - __privateAdd(this, _d1); - __privateSet(this, _db14, db); - __privateSet(this, _d1, d1); - } - async getSchemas() { - return []; - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = __privateGet(this, _db14).selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").where("name", "not like", "_cf_%").select([ - "name", - "type", - "sql" - ]).$castTo(); - if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - const tables = await query.execute(); - if (tables.length === 0) return []; - const statements = tables.map((table) => __privateGet(this, _d1).prepare("SELECT * FROM pragma_table_info(?)").bind(table.name)); - const batchResults = await __privateGet(this, _d1).batch(statements); - return tables.map((table, index) => { - const columnInfo = batchResults[index]?.results ?? []; - let autoIncrementCol = table.sql?.split(/[(),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.filter(Boolean)?.[0]?.replace(/["`]/g, ""); - if (!autoIncrementCol) { - const pkCols = columnInfo.filter((r) => r.pk > 0); - const singlePk = pkCols.length === 1 ? pkCols[0] : void 0; - if (singlePk && singlePk.type.toLowerCase() === "integer") autoIncrementCol = singlePk.name; - } - return { - name: table.name, - isView: table.type === "view", - columns: columnInfo.map((col) => ({ - name: col.name, - dataType: col.type, - isNullable: !col.notnull, - isAutoIncrementing: col.name === autoIncrementCol, - hasDefaultValue: col.dflt_value != null - })) - }; - }); - } - async getMetadata(options) { - return { tables: await this.getTables(options) }; - } - }, _db14 = new WeakMap(), _d1 = new WeakMap(), _a27); - D1SqliteQueryCompiler = class extends SqliteQueryCompiler { - }; - D1SqliteDialect = (_a28 = class { - constructor(config4) { - __privateAdd(this, _config14); - __privateSet(this, _config14, { ...config4 }); - } - createDriver() { - return new D1SqliteDriver(__privateGet(this, _config14)); - } - createQueryCompiler() { - return new D1SqliteQueryCompiler(); - } - createAdapter() { - return new D1SqliteAdapter(); - } - createIntrospector(db) { - return new D1SqliteIntrospector(db, __privateGet(this, _config14).database); - } - }, _config14 = new WeakMap(), _a28); - } -}); - -// ../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/index.mjs -function getKyselyDatabaseType(db) { - if (!db) return null; - if ("dialect" in db) return getKyselyDatabaseType(db.dialect); - if ("createDriver" in db) { - if (db instanceof SqliteDialect) return "sqlite"; - if (db instanceof MysqlDialect) return "mysql"; - if (db instanceof PostgresDialect) return "postgres"; - if (db instanceof MssqlDialect) return "mssql"; - } - if ("aggregate" in db) return "sqlite"; - if ("getConnection" in db) return "mysql"; - if ("connect" in db) return "postgres"; - if ("fileControl" in db) return "sqlite"; - if ("open" in db && "close" in db && "prepare" in db) return "sqlite"; - if ("batch" in db && "exec" in db && "prepare" in db) return "sqlite"; - return null; -} -function insensitiveIlike(columnRef, pattern, dbType) { - return dbType === "postgres" ? sql`${sql.ref(columnRef)} ILIKE ${pattern}` : sql`LOWER(${sql.ref(columnRef)}) LIKE LOWER(${pattern})`; -} -function insensitiveIn2(columnRef, values) { - return { - lhs: sql`LOWER(${sql.ref(columnRef)})`, - values: values.map((v) => v.toLowerCase()) - }; -} -function insensitiveNotIn2(columnRef, values) { - return { - lhs: sql`LOWER(${sql.ref(columnRef)})`, - values: values.map((v) => v.toLowerCase()) - }; -} -function insensitiveEq(columnRef, value) { - return { - lhs: sql`LOWER(${sql.ref(columnRef)})`, - value: value.toLowerCase() - }; -} -function insensitiveNe(columnRef, value) { - return { - lhs: sql`LOWER(${sql.ref(columnRef)})`, - value: value.toLowerCase() - }; -} -var createKyselyAdapter, kyselyAdapter; -var init_dist2 = __esm({ - "../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/index.mjs"() { - init_esm3(); - init_adapter(); - init_string(); - createKyselyAdapter = async (config4) => { - const db = config4.database; - if (!db) return { - kysely: null, - databaseType: null, - transaction: void 0 - }; - if ("db" in db) return { - kysely: db.db, - databaseType: db.type, - transaction: db.transaction - }; - if ("dialect" in db) return { - kysely: new Kysely({ dialect: db.dialect }), - databaseType: db.type, - transaction: db.transaction - }; - let dialect = void 0; - const databaseType = getKyselyDatabaseType(db); - if ("createDriver" in db) dialect = db; - if ("aggregate" in db && !("createSession" in db)) dialect = new SqliteDialect({ database: db }); - if ("getConnection" in db) dialect = new MysqlDialect(db); - if ("connect" in db) dialect = new PostgresDialect({ pool: db }); - if ("fileControl" in db) { - const { BunSqliteDialect: BunSqliteDialect2 } = await Promise.resolve().then(() => (init_bun_sqlite_dialect_na_YwnN(), bun_sqlite_dialect_na_YwnN_exports)); - dialect = new BunSqliteDialect2({ database: db }); - } - if ("createSession" in db) { - let DatabaseSync = void 0; - try { - const nodeSqlite = "node:sqlite"; - ({ DatabaseSync } = await import( - /* @vite-ignore */ - /* webpackIgnore: true */ - nodeSqlite - )); - } catch (error49) { - if (error49 !== null && typeof error49 === "object" && "code" in error49 && error49.code !== "ERR_UNKNOWN_BUILTIN_MODULE") throw error49; - } - if (DatabaseSync && db instanceof DatabaseSync) { - const { NodeSqliteDialect: NodeSqliteDialect2 } = await Promise.resolve().then(() => (init_node_sqlite_dialect(), node_sqlite_dialect_exports)); - dialect = new NodeSqliteDialect2({ database: db }); - } - } - if ("batch" in db && "exec" in db && "prepare" in db) { - const { D1SqliteDialect: D1SqliteDialect2 } = await Promise.resolve().then(() => (init_d1_sqlite_dialect_C2B7YsIT(), d1_sqlite_dialect_C2B7YsIT_exports)); - dialect = new D1SqliteDialect2({ database: db }); - } - return { - kysely: dialect ? new Kysely({ dialect }) : null, - databaseType, - transaction: void 0 - }; - }; - kyselyAdapter = (db, config4) => { - let lazyOptions = null; - const createCustomAdapter = (db2) => { - return ({ getFieldName, schema: schema3, getDefaultFieldName, getDefaultModelName, getFieldAttributes, getModelName }) => { - const selectAllJoins = (join2) => { - const allSelects = []; - const allSelectsStr = []; - if (join2) for (const [joinModel, _] of Object.entries(join2)) { - const fields = schema3[getDefaultModelName(joinModel)]?.fields; - const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; - if (!fields) continue; - fields.id = { type: "string" }; - for (const [field, fieldAttr] of Object.entries(fields)) { - allSelects.push(sql`${sql.ref(`join_${joinModelName}`)}.${sql.ref(fieldAttr.fieldName || field)} as ${sql.ref(`_joined_${joinModelName}_${fieldAttr.fieldName || field}`)}`); - allSelectsStr.push({ - joinModel, - joinModelRef: joinModelName, - fieldName: fieldAttr.fieldName || field - }); - } - } - return { - allSelectsStr, - allSelects - }; - }; - const withReturning = async (values, builder, model, where) => { - let res; - if (config4?.type === "mysql") { - await builder.execute(); - const field = values.id ? "id" : where.length > 0 && where[0]?.field ? where[0].field : "id"; - if (!values.id && where.length === 0) { - res = await db2.selectFrom(model).selectAll().orderBy(getFieldName({ - model, - field - }), "desc").limit(1).executeTakeFirst(); - return res; - } - const value = values[field] !== void 0 ? values[field] : where[0]?.value; - res = await db2.selectFrom(model).selectAll().orderBy(getFieldName({ - model, - field - }), "desc").where(getFieldName({ - model, - field - }), value === null ? "is" : "=", value).limit(1).executeTakeFirst(); - return res; - } - if (config4?.type === "mssql") { - res = await builder.outputAll("inserted").executeTakeFirst(); - return res; - } - res = await builder.returningAll().executeTakeFirst(); - return res; - }; - function convertWhereClause(model, w) { - if (!w) return { - and: null, - or: null - }; - const conditions = { - and: [], - or: [] - }; - w.forEach((condition) => { - const { field: _field, value: _value, operator = "eq", connector = "AND", mode = "sensitive" } = condition; - const value = _value; - const field = getFieldName({ - model, - field: _field - }); - const isInsensitive = mode === "insensitive" && (typeof value === "string" || Array.isArray(value) && value.every((v) => typeof v === "string")); - const expr = (eb) => { - const f = `${model}.${field}`; - if (operator.toLowerCase() === "in") { - if (isInsensitive) { - const { lhs, values } = insensitiveIn2(f, Array.isArray(value) ? value : [value]); - return eb(lhs, "in", values); - } - return eb(f, "in", Array.isArray(value) ? value : [value]); - } - if (operator.toLowerCase() === "not_in") { - if (isInsensitive) { - const { lhs, values } = insensitiveNotIn2(f, Array.isArray(value) ? value : [value]); - return eb(lhs, "not in", values); - } - return eb(f, "not in", Array.isArray(value) ? value : [value]); - } - if (operator === "contains") { - if (isInsensitive && typeof value === "string") return insensitiveIlike(f, `%${value}%`, config4?.type); - return eb(f, "like", `%${value}%`); - } - if (operator === "starts_with") { - if (isInsensitive && typeof value === "string") return insensitiveIlike(f, `${value}%`, config4?.type); - return eb(f, "like", `${value}%`); - } - if (operator === "ends_with") { - if (isInsensitive && typeof value === "string") return insensitiveIlike(f, `%${value}`, config4?.type); - return eb(f, "like", `%${value}`); - } - if (operator === "eq") { - if (value === null) return eb(f, "is", null); - if (isInsensitive && typeof value === "string") { - const { lhs, value: v } = insensitiveEq(f, value); - return eb(lhs, "=", v); - } - return eb(f, "=", value); - } - if (operator === "ne") { - if (value === null) return eb(f, "is not", null); - if (isInsensitive && typeof value === "string") { - const { lhs, value: v } = insensitiveNe(f, value); - return eb(lhs, "<>", v); - } - return eb(f, "<>", value); - } - if (operator === "gt") return eb(f, ">", value); - if (operator === "gte") return eb(f, ">=", value); - if (operator === "lt") return eb(f, "<", value); - if (operator === "lte") return eb(f, "<=", value); - return eb(f, operator, value); - }; - if (connector === "OR") conditions.or.push(expr); - else conditions.and.push(expr); - }); - return { - and: conditions.and.length ? conditions.and : null, - or: conditions.or.length ? conditions.or : null - }; - } - function processJoinedResults(rows, joinConfig, allSelectsStr) { - if (!joinConfig || !rows.length) return rows; - const groupedByMainId = /* @__PURE__ */ new Map(); - for (const currentRow of rows) { - const mainModelFields = {}; - const joinedModelFields = {}; - for (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[getModelName(joinModel)] = {}; - for (const [key, value] of Object.entries(currentRow)) { - const keyStr = String(key); - let assigned = false; - for (const { joinModel, fieldName, joinModelRef } of allSelectsStr) if (keyStr === `_joined_${joinModelRef}_${fieldName}` || keyStr === `_Joined${capitalizeFirstLetter(joinModelRef)}${capitalizeFirstLetter(fieldName)}`) { - joinedModelFields[getModelName(joinModel)][getFieldName({ - model: joinModel, - field: fieldName - })] = value; - assigned = true; - break; - } - if (!assigned) mainModelFields[key] = value; - } - const mainId = mainModelFields.id; - if (!mainId) continue; - if (!groupedByMainId.has(mainId)) { - const entry2 = { ...mainModelFields }; - for (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry2[getModelName(joinModel)] = joinAttr.relation === "one-to-one" ? null : []; - groupedByMainId.set(mainId, entry2); - } - const entry = groupedByMainId.get(mainId); - for (const [joinModel, joinAttr] of Object.entries(joinConfig)) { - const isUnique = joinAttr.relation === "one-to-one"; - const limit = joinAttr.limit ?? 100; - const joinedObj = joinedModelFields[getModelName(joinModel)]; - const hasData = joinedObj && Object.keys(joinedObj).length > 0 && Object.values(joinedObj).some((value) => value !== null && value !== void 0); - if (isUnique) entry[getModelName(joinModel)] = hasData ? joinedObj : null; - else { - const joinModelName = getModelName(joinModel); - if (Array.isArray(entry[joinModelName]) && hasData) { - if (entry[joinModelName].length >= limit) continue; - const idFieldName = getFieldName({ - model: joinModel, - field: "id" - }); - const joinedId = joinedObj[idFieldName]; - if (joinedId) { - if (!entry[joinModelName].some((item) => item[idFieldName] === joinedId) && entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj); - } else if (entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj); - } - } - } - } - const result = Array.from(groupedByMainId.values()); - for (const entry of result) for (const [joinModel, joinAttr] of Object.entries(joinConfig)) if (joinAttr.relation !== "one-to-one") { - const joinModelName = getModelName(joinModel); - if (Array.isArray(entry[joinModelName])) { - const limit = joinAttr.limit ?? 100; - if (entry[joinModelName].length > limit) entry[joinModelName] = entry[joinModelName].slice(0, limit); - } - } - return result; - } - return { - async create({ data, model }) { - return await withReturning(data, db2.insertInto(model).values(data), model, []); - }, - async findOne({ model, where, select, join: join2 }) { - const { and, or } = convertWhereClause(model, where); - let query = db2.selectFrom((eb) => { - let b = eb.selectFrom(model); - if (and) b = b.where((eb2) => eb2.and(and.map((expr) => expr(eb2)))); - if (or) b = b.where((eb2) => eb2.or(or.map((expr) => expr(eb2)))); - if (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({ - model, - field - }))); - else b = b.selectAll(); - return b.as("primary"); - }).selectAll("primary"); - if (join2) for (const [joinModel, joinAttr] of Object.entries(join2)) { - const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; - query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join3) => join3.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`)); - } - const { allSelectsStr, allSelects } = selectAllJoins(join2); - query = query.select(allSelects); - const res = await query.execute(); - if (!res || !Array.isArray(res) || res.length === 0) return null; - const row = res[0]; - if (join2) return processJoinedResults(res, join2, allSelectsStr)[0]; - return row; - }, - async findMany({ model, where, limit, select, offset, sortBy, join: join2 }) { - const { and, or } = convertWhereClause(model, where); - let query = db2.selectFrom((eb) => { - let b = eb.selectFrom(model); - if (config4?.type === "mssql") { - if (offset !== void 0) { - if (!sortBy) b = b.orderBy(getFieldName({ - model, - field: "id" - })); - b = b.offset(offset).fetch(limit || 100); - } else if (limit !== void 0) b = b.top(limit); - } else { - if (limit !== void 0) b = b.limit(limit); - if (offset !== void 0) b = b.offset(offset); - } - if (sortBy?.field) b = b.orderBy(`${getFieldName({ - model, - field: sortBy.field - })}`, sortBy.direction); - if (and) b = b.where((eb2) => eb2.and(and.map((expr) => expr(eb2)))); - if (or) b = b.where((eb2) => eb2.or(or.map((expr) => expr(eb2)))); - if (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({ - model, - field - }))); - else b = b.selectAll(); - return b.as("primary"); - }).selectAll("primary"); - if (join2) for (const [joinModel, joinAttr] of Object.entries(join2)) { - const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; - query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join3) => join3.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`)); - } - const { allSelectsStr, allSelects } = selectAllJoins(join2); - query = query.select(allSelects); - if (sortBy?.field) query = query.orderBy(`${getFieldName({ - model, - field: sortBy.field - })}`, sortBy.direction); - const res = await query.execute(); - if (!res) return []; - if (join2) return processJoinedResults(res, join2, allSelectsStr); - return res; - }, - async update({ model, where, update: values }) { - const { and, or } = convertWhereClause(model, where); - let query = db2.updateTable(model).set(values); - if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); - if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); - return await withReturning(values, query, model, where); - }, - async updateMany({ model, where, update: values }) { - const { and, or } = convertWhereClause(model, where); - let query = db2.updateTable(model).set(values); - if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); - if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); - const res = (await query.executeTakeFirst()).numUpdatedRows; - return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res); - }, - async count({ model, where }) { - const { and, or } = convertWhereClause(model, where); - let query = db2.selectFrom(model).select(db2.fn.count("id").as("count")); - if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); - if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); - const res = await query.execute(); - if (typeof res[0].count === "number") return res[0].count; - if (typeof res[0].count === "bigint") return Number(res[0].count); - return parseInt(res[0].count); - }, - async delete({ model, where }) { - const { and, or } = convertWhereClause(model, where); - let query = db2.deleteFrom(model); - if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); - if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); - await query.execute(); - }, - async deleteMany({ model, where }) { - const { and, or } = convertWhereClause(model, where); - let query = db2.deleteFrom(model); - if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb)))); - if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb)))); - const res = (await query.executeTakeFirst()).numDeletedRows; - return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res); - }, - options: config4 - }; - }; - }; - let adapterOptions = null; - adapterOptions = { - config: { - adapterId: "kysely", - adapterName: "Kysely Adapter", - usePlural: config4?.usePlural, - debugLogs: config4?.debugLogs, - supportsBooleans: config4?.type === "sqlite" || config4?.type === "mssql" || config4?.type === "mysql" || !config4?.type ? false : true, - supportsDates: config4?.type === "sqlite" || config4?.type === "mssql" || !config4?.type ? false : true, - supportsJSON: config4?.type === "postgres" ? true : false, - supportsArrays: false, - supportsUUIDs: config4?.type === "postgres" ? true : false, - transaction: config4?.transaction ? (cb) => db.transaction().execute((trx) => { - return cb(createAdapterFactory({ - config: adapterOptions.config, - adapter: createCustomAdapter(trx) - })(lazyOptions)); - }) : false - }, - adapter: createCustomAdapter(db) - }; - const adapter = createAdapterFactory(adapterOptions); - return (options) => { - lazyOptions = options; - return adapter(options); - }; - }; - } -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs -var kysely_adapter_exports = {}; -__export(kysely_adapter_exports, { - createKyselyAdapter: () => createKyselyAdapter, - getKyselyDatabaseType: () => getKyselyDatabaseType, - kyselyAdapter: () => kyselyAdapter -}); -var init_kysely_adapter = __esm({ - "../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs"() { - init_dist2(); - } -}); - -// ../../packages/spec/dist/system/index.mjs -init_zod(); -var CacheStrategySchema = external_exports.enum([ - "lru", - // Least Recently Used - "lfu", - // Least Frequently Used - "fifo", - // First In First Out - "ttl", - // Time To Live only - "adaptive" - // Dynamic strategy selection -]).describe("Cache eviction strategy"); -var CacheTierSchema = external_exports.object({ - name: external_exports.string().describe("Unique cache tier name"), - type: external_exports.enum(["memory", "redis", "memcached", "cdn"]).describe("Cache backend type"), - maxSize: external_exports.number().optional().describe("Max size in MB"), - ttl: external_exports.number().default(300).describe("Default TTL in seconds"), - strategy: CacheStrategySchema.default("lru").describe("Eviction strategy"), - warmup: external_exports.boolean().default(false).describe("Pre-populate cache on startup") -}).describe("Configuration for a single cache tier in the hierarchy"); -var CacheInvalidationSchema = external_exports.object({ - trigger: external_exports.enum(["create", "update", "delete", "manual"]).describe("Event that triggers invalidation"), - scope: external_exports.enum(["key", "pattern", "tag", "all"]).describe("Invalidation scope"), - pattern: external_exports.string().optional().describe("Key pattern for pattern-based invalidation"), - tags: external_exports.array(external_exports.string()).optional().describe("Cache tags to invalidate") -}).describe("Rule defining when and how cached entries are invalidated"); -var CacheConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable application-level caching"), - tiers: external_exports.array(CacheTierSchema).describe("Ordered cache tier hierarchy"), - invalidation: external_exports.array(CacheInvalidationSchema).describe("Cache invalidation rules"), - prefetch: external_exports.boolean().default(false).describe("Enable cache prefetching"), - compression: external_exports.boolean().default(false).describe("Enable data compression in cache"), - encryption: external_exports.boolean().default(false).describe("Enable encryption for cached data") -}).describe("Top-level application cache configuration"); -var CacheConsistencySchema = external_exports.enum([ - "write_through", - "write_behind", - "write_around", - "refresh_ahead" -]).describe("Distributed cache write consistency strategy"); -var CacheAvalanchePreventionSchema = external_exports.object({ - /** TTL jitter to stagger cache expiration */ - jitterTtl: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Add random jitter to TTL values"), - maxJitterSeconds: external_exports.number().default(60).describe("Maximum jitter added to TTL in seconds") - }).optional().describe("TTL jitter to prevent simultaneous expiration"), - /** Circuit breaker to protect backend under cache pressure */ - circuitBreaker: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable circuit breaker for backend protection"), - failureThreshold: external_exports.number().default(5).describe("Failures before circuit opens"), - resetTimeout: external_exports.number().default(30).describe("Seconds before half-open state") - }).optional().describe("Circuit breaker for backend protection"), - /** Cache lock to prevent thundering herd on key miss */ - lockout: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable cache locking for key regeneration"), - lockTimeoutMs: external_exports.number().default(5e3).describe("Maximum lock wait time in milliseconds") - }).optional().describe("Lock-based stampede prevention") -}).describe("Cache avalanche/stampede prevention configuration"); -var CacheWarmupSchema = external_exports.object({ - /** Enable cache warming */ - enabled: external_exports.boolean().default(false).describe("Enable cache warmup"), - /** Warmup strategy */ - strategy: external_exports.enum(["eager", "lazy", "scheduled"]).default("lazy").describe("Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)"), - /** Cron schedule for scheduled warmup */ - schedule: external_exports.string().optional().describe("Cron expression for scheduled warmup"), - /** Keys/patterns to warm up */ - patterns: external_exports.array(external_exports.string()).optional().describe('Key patterns to warm up (e.g., "user:*", "config:*")'), - /** Maximum concurrent warmup operations */ - concurrency: external_exports.number().default(10).describe("Maximum concurrent warmup operations") -}).describe("Cache warmup strategy"); -var DistributedCacheConfigSchema = CacheConfigSchema.extend({ - /** Distributed write consistency strategy */ - consistency: CacheConsistencySchema.optional().describe("Distributed cache consistency strategy"), - /** Avalanche/stampede prevention settings */ - avalanchePrevention: CacheAvalanchePreventionSchema.optional().describe("Cache avalanche and stampede prevention"), - /** Cache warmup configuration */ - warmup: CacheWarmupSchema.optional().describe("Cache warmup strategy") -}).describe("Distributed cache configuration with consistency and avalanche prevention"); -var BackupStrategySchema = external_exports.enum([ - "full", - "incremental", - "differential" -]).describe("Backup strategy type"); -var BackupRetentionSchema = external_exports.object({ - /** Number of days to retain backups */ - days: external_exports.number().min(1).describe("Retention period in days"), - /** Minimum number of backup copies to keep regardless of age */ - minCopies: external_exports.number().min(1).default(3).describe("Minimum backup copies to retain"), - /** Maximum number of backup copies */ - maxCopies: external_exports.number().optional().describe("Maximum backup copies to store") -}).describe("Backup retention policy"); -var BackupConfigSchema = external_exports.object({ - /** Backup strategy */ - strategy: BackupStrategySchema.default("incremental").describe("Backup strategy"), - /** Cron schedule for automated backups */ - schedule: external_exports.string().optional().describe('Cron expression for backup schedule (e.g., "0 2 * * *")'), - /** Retention policy */ - retention: BackupRetentionSchema.describe("Backup retention policy"), - /** Storage destination */ - destination: external_exports.object({ - type: external_exports.enum(["s3", "gcs", "azure_blob", "local"]).describe("Storage backend type"), - bucket: external_exports.string().optional().describe("Cloud storage bucket/container name"), - path: external_exports.string().optional().describe("Storage path prefix"), - region: external_exports.string().optional().describe("Cloud storage region") - }).describe("Backup storage destination"), - /** Encryption settings */ - encryption: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable backup encryption"), - algorithm: external_exports.enum(["AES-256-GCM", "AES-256-CBC", "ChaCha20-Poly1305"]).default("AES-256-GCM").describe("Encryption algorithm"), - keyId: external_exports.string().optional().describe("KMS key ID for encryption") - }).optional().describe("Backup encryption settings"), - /** Compression settings */ - compression: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable backup compression"), - algorithm: external_exports.enum(["gzip", "zstd", "lz4", "snappy"]).default("zstd").describe("Compression algorithm") - }).optional().describe("Backup compression settings"), - /** Verify backup integrity after creation */ - verifyAfterBackup: external_exports.boolean().default(true).describe("Verify backup integrity after creation") -}).describe("Backup configuration"); -var FailoverModeSchema = external_exports.enum([ - "active_passive", - "active_active", - "pilot_light", - "warm_standby" -]).describe("Failover mode"); -var FailoverConfigSchema = external_exports.object({ - /** Failover mode */ - mode: FailoverModeSchema.default("active_passive").describe("Failover mode"), - /** Automatic failover enabled */ - autoFailover: external_exports.boolean().default(true).describe("Enable automatic failover"), - /** Health check interval in seconds */ - healthCheckInterval: external_exports.number().default(30).describe("Health check interval in seconds"), - /** Number of consecutive failures before triggering failover */ - failureThreshold: external_exports.number().default(3).describe("Consecutive failures before failover"), - /** Regions/zones for disaster recovery */ - regions: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Region identifier (e.g., "us-east-1", "eu-west-1")'), - role: external_exports.enum(["primary", "secondary", "witness"]).describe("Region role"), - endpoint: external_exports.string().optional().describe("Region endpoint URL"), - priority: external_exports.number().optional().describe("Failover priority (lower = higher priority)") - })).min(2).describe("Multi-region configuration (minimum 2 regions)"), - /** DNS failover configuration */ - dns: external_exports.object({ - ttl: external_exports.number().default(60).describe("DNS TTL in seconds for failover"), - provider: external_exports.enum(["route53", "cloudflare", "azure_dns", "custom"]).optional().describe("DNS provider for automatic failover") - }).optional().describe("DNS failover settings") -}).describe("Failover configuration"); -var RPOSchema = external_exports.object({ - /** RPO value */ - value: external_exports.number().min(0).describe("RPO value"), - /** RPO time unit */ - unit: external_exports.enum(["seconds", "minutes", "hours"]).default("minutes").describe("RPO time unit") -}).describe("Recovery Point Objective (maximum acceptable data loss)"); -var RTOSchema = external_exports.object({ - /** RTO value */ - value: external_exports.number().min(0).describe("RTO value"), - /** RTO time unit */ - unit: external_exports.enum(["seconds", "minutes", "hours"]).default("minutes").describe("RTO time unit") -}).describe("Recovery Time Objective (maximum acceptable downtime)"); -var DisasterRecoveryPlanSchema = external_exports.object({ - /** Enable disaster recovery */ - enabled: external_exports.boolean().default(false).describe("Enable disaster recovery plan"), - /** Recovery Point Objective */ - rpo: RPOSchema.describe("Recovery Point Objective"), - /** Recovery Time Objective */ - rto: RTOSchema.describe("Recovery Time Objective"), - /** Backup configuration */ - backup: BackupConfigSchema.describe("Backup configuration"), - /** Failover configuration */ - failover: FailoverConfigSchema.optional().describe("Multi-region failover configuration"), - /** Data replication settings */ - replication: external_exports.object({ - /** Replication mode */ - mode: external_exports.enum(["synchronous", "asynchronous", "semi_synchronous"]).default("asynchronous").describe("Data replication mode"), - /** Maximum replication lag allowed (seconds) */ - maxLagSeconds: external_exports.number().optional().describe("Maximum acceptable replication lag in seconds"), - /** Objects/tables to replicate (empty = all) */ - includeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to replicate (empty = all)"), - /** Objects/tables to exclude from replication */ - excludeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to exclude from replication") - }).optional().describe("Data replication settings"), - /** Automated recovery testing */ - testing: external_exports.object({ - /** Enable periodic DR testing */ - enabled: external_exports.boolean().default(false).describe("Enable automated DR testing"), - /** Cron schedule for DR tests */ - schedule: external_exports.string().optional().describe("Cron expression for DR test schedule"), - /** Notification channel for test results */ - notificationChannel: external_exports.string().optional().describe("Notification channel for DR test results") - }).optional().describe("Automated disaster recovery testing"), - /** Runbook URL for manual procedures */ - runbookUrl: external_exports.string().optional().describe("URL to disaster recovery runbook/playbook"), - /** Contact list for DR incidents */ - contacts: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Contact name"), - role: external_exports.string().describe('Contact role (e.g., "DBA", "SRE Lead")'), - email: external_exports.string().optional().describe("Contact email"), - phone: external_exports.string().optional().describe("Contact phone") - })).optional().describe("Emergency contact list for DR incidents") -}).describe("Complete disaster recovery plan configuration"); -var MessageQueueProviderSchema = external_exports.enum([ - "kafka", - "rabbitmq", - "aws-sqs", - "redis-pubsub", - "google-pubsub", - "azure-service-bus" -]).describe("Supported message queue backend provider"); -var TopicConfigSchema = external_exports.object({ - name: external_exports.string().describe("Topic name identifier"), - partitions: external_exports.number().default(1).describe("Number of partitions for parallel consumption"), - replicationFactor: external_exports.number().default(1).describe("Number of replicas for fault tolerance"), - retentionMs: external_exports.number().optional().describe("Message retention period in milliseconds"), - compressionType: external_exports.enum(["none", "gzip", "snappy", "lz4"]).default("none").describe("Message compression algorithm") -}).describe("Configuration for a message queue topic"); -var ConsumerConfigSchema = external_exports.object({ - groupId: external_exports.string().describe("Consumer group identifier"), - autoOffsetReset: external_exports.enum(["earliest", "latest"]).default("latest").describe("Where to start reading when no offset exists"), - enableAutoCommit: external_exports.boolean().default(true).describe("Automatically commit consumed offsets"), - maxPollRecords: external_exports.number().default(500).describe("Maximum records returned per poll") -}).describe("Consumer group configuration for topic consumption"); -var DeadLetterQueueSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable dead letter queue for failed messages"), - maxRetries: external_exports.number().default(3).describe("Maximum delivery attempts before sending to DLQ"), - queueName: external_exports.string().describe("Name of the dead letter queue") -}).describe("Dead letter queue configuration for unprocessable messages"); -var MessageQueueConfigSchema = external_exports.object({ - provider: MessageQueueProviderSchema.describe("Message queue backend provider"), - topics: external_exports.array(TopicConfigSchema).describe("List of topic configurations"), - consumers: external_exports.array(ConsumerConfigSchema).optional().describe("Consumer group configurations"), - deadLetterQueue: DeadLetterQueueSchema.optional().describe("Dead letter queue for failed messages"), - ssl: external_exports.boolean().default(false).describe("Enable SSL/TLS for broker connections"), - sasl: external_exports.object({ - mechanism: external_exports.enum(["plain", "scram-sha-256", "scram-sha-512"]).describe("SASL authentication mechanism"), - username: external_exports.string().describe("SASL username"), - password: external_exports.string().describe("SASL password") - }).optional().describe("SASL authentication configuration") -}).describe("Top-level message queue configuration"); -var SystemIdentifierSchema = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' -}).describe("System identifier (lowercase with underscores or dots)"); -var SnakeCaseIdentifierSchema = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { - message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' -}).describe("Snake case identifier (lowercase with underscores only)"); -external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' -}).describe("Event name (lowercase with dot notation for namespacing)"); -var StorageScopeSchema = external_exports.enum([ - "global", - // Global application-wide storage - "tenant", - // Tenant-scoped storage (multi-tenant apps) - "user", - // User-scoped storage - "session", - // Session-scoped storage (ephemeral) - "temp", - // Ephemeral, cleared on restart - "cache", - // Ephemeral, survives restarts, cleared on LRU/Expiration - "data", - // Persistent, backed up - "logs", - // Append-only, rotated - "config", - // Read-heavy, versioned - "public" - // Publicly accessible static assets -]).describe("Storage scope classification"); -var FileMetadataSchema = external_exports.object({ - path: external_exports.string().describe("File path"), - name: external_exports.string().describe("File name"), - size: external_exports.number().int().describe("File size in bytes"), - mimeType: external_exports.string().describe("MIME type"), - lastModified: external_exports.string().datetime().describe("Last modified timestamp"), - created: external_exports.string().datetime().describe("Creation timestamp"), - etag: external_exports.string().optional().describe("Entity tag") -}); -var StorageProviderSchema = external_exports.enum([ - "s3", - // Amazon S3 - "azure_blob", - // Azure Blob Storage - "gcs", - // Google Cloud Storage - "minio", - // MinIO (self-hosted S3-compatible) - "r2", - // Cloudflare R2 - "spaces", - // DigitalOcean Spaces - "wasabi", - // Wasabi Hot Cloud Storage - "backblaze", - // Backblaze B2 - "local" - // Local filesystem (development only) -]).describe("Storage provider type"); -var StorageAclSchema = external_exports.enum([ - "private", - // Owner has full control, no one else has access - "public_read", - // Owner has full control, everyone can read - "public_read_write", - // Owner has full control, everyone can read/write (not recommended) - "authenticated_read", - // Owner has full control, authenticated users can read - "bucket_owner_read", - // Object owner has full control, bucket owner can read - "bucket_owner_full_control" - // Both object and bucket owner have full control -]).describe("Storage access control level"); -var StorageClassSchema = external_exports.enum([ - "standard", - // Standard/hot storage for frequently accessed data - "intelligent", - // Intelligent tiering (auto-moves between hot/cool) - "infrequent_access", - // Infrequent access/cool storage - "glacier", - // Archive/cold storage (slower retrieval) - "deep_archive" - // Deep archive (cheapest, slowest retrieval) -]).describe("Storage class/tier for cost optimization"); -var LifecycleActionSchema = external_exports.enum([ - "transition", - // Move to different storage class - "delete", - // Delete the object - "abort" - // Abort incomplete multipart uploads -]).describe("Lifecycle policy action type"); -var ObjectMetadataSchema = external_exports.object({ - contentType: external_exports.string().describe("MIME type (e.g., image/jpeg, application/pdf)"), - contentLength: external_exports.number().min(0).describe("File size in bytes"), - contentEncoding: external_exports.string().optional().describe("Content encoding (e.g., gzip)"), - contentDisposition: external_exports.string().optional().describe("Content disposition header"), - contentLanguage: external_exports.string().optional().describe("Content language"), - cacheControl: external_exports.string().optional().describe("Cache control directives"), - etag: external_exports.string().optional().describe("Entity tag for versioning/caching"), - lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), - versionId: external_exports.string().optional().describe("Object version identifier"), - storageClass: StorageClassSchema.optional().describe("Storage class/tier"), - encryption: external_exports.object({ - algorithm: external_exports.string().describe("Encryption algorithm (e.g., AES256, aws:kms)"), - keyId: external_exports.string().optional().describe("KMS key ID if using managed encryption") - }).optional().describe("Server-side encryption configuration"), - custom: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom user-defined metadata") -}); -var PresignedUrlConfigSchema = external_exports.object({ - operation: external_exports.enum(["get", "put", "delete", "head"]).describe("Allowed operation"), - expiresIn: external_exports.number().min(1).max(604800).describe("Expiration time in seconds (max 7 days)"), - contentType: external_exports.string().optional().describe("Required content type for PUT operations"), - maxSize: external_exports.number().min(0).optional().describe("Maximum file size in bytes for PUT operations"), - responseContentType: external_exports.string().optional().describe("Override content-type for GET operations"), - responseContentDisposition: external_exports.string().optional().describe("Override content-disposition for GET operations") -}); -var MultipartUploadConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable multipart uploads"), - partSize: external_exports.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe("Part size in bytes (min 5MB, max 5GB)"), - maxParts: external_exports.number().min(1).max(1e4).default(1e4).describe("Maximum number of parts (max 10,000)"), - threshold: external_exports.number().min(0).default(100 * 1024 * 1024).describe("File size threshold to trigger multipart upload (bytes)"), - maxConcurrent: external_exports.number().min(1).max(100).default(4).describe("Maximum concurrent part uploads"), - abortIncompleteAfterDays: external_exports.number().min(1).optional().describe("Auto-abort incomplete uploads after N days") -}); -var AccessControlConfigSchema = external_exports.object({ - acl: StorageAclSchema.default("private").describe("Default access control level"), - allowedOrigins: external_exports.array(external_exports.string()).optional().describe("CORS allowed origins"), - allowedMethods: external_exports.array(external_exports.enum(["GET", "PUT", "POST", "DELETE", "HEAD"])).optional().describe("CORS allowed HTTP methods"), - allowedHeaders: external_exports.array(external_exports.string()).optional().describe("CORS allowed headers"), - exposeHeaders: external_exports.array(external_exports.string()).optional().describe("CORS exposed headers"), - maxAge: external_exports.number().min(0).optional().describe("CORS preflight cache duration in seconds"), - corsEnabled: external_exports.boolean().default(false).describe("Enable CORS configuration"), - publicAccess: external_exports.object({ - allowPublicRead: external_exports.boolean().default(false).describe("Allow public read access"), - allowPublicWrite: external_exports.boolean().default(false).describe("Allow public write access"), - allowPublicList: external_exports.boolean().default(false).describe("Allow public bucket listing") - }).optional().describe("Public access control"), - allowedIps: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses/CIDR blocks"), - blockedIps: external_exports.array(external_exports.string()).optional().describe("Blocked IP addresses/CIDR blocks") -}); -var LifecyclePolicyRuleSchema = external_exports.object({ - id: SystemIdentifierSchema.describe("Rule identifier"), - enabled: external_exports.boolean().default(true).describe("Enable this rule"), - action: LifecycleActionSchema.describe("Action to perform"), - prefix: external_exports.string().optional().describe('Object key prefix filter (e.g., "uploads/")'), - tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Object tag filters"), - daysAfterCreation: external_exports.number().min(0).optional().describe("Days after object creation"), - daysAfterModification: external_exports.number().min(0).optional().describe("Days after last modification"), - targetStorageClass: StorageClassSchema.optional().describe("Target storage class for transition action") -}).refine((data) => { - if (data.action === "transition" && !data.targetStorageClass) { - return false; - } - return true; -}, { - message: 'targetStorageClass is required when action is "transition"' -}); -var LifecyclePolicyConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable lifecycle policies"), - rules: external_exports.array(LifecyclePolicyRuleSchema).default([]).describe("Lifecycle rules") -}); -var BucketConfigSchema = external_exports.object({ - name: SystemIdentifierSchema.describe("Bucket identifier in ObjectStack (snake_case)"), - label: external_exports.string().describe("Display label"), - bucketName: external_exports.string().describe("Actual bucket/container name in storage provider"), - region: external_exports.string().optional().describe("Storage region (e.g., us-east-1, westus)"), - provider: StorageProviderSchema.describe("Storage provider"), - endpoint: external_exports.string().optional().describe("Custom endpoint URL (for S3-compatible providers)"), - pathStyle: external_exports.boolean().default(false).describe("Use path-style URLs (for S3-compatible providers)"), - versioning: external_exports.boolean().default(false).describe("Enable object versioning"), - encryption: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable server-side encryption"), - algorithm: external_exports.enum(["AES256", "aws:kms", "azure:kms", "gcp:kms"]).default("AES256").describe("Encryption algorithm"), - kmsKeyId: external_exports.string().optional().describe("KMS key ID for managed encryption") - }).optional().describe("Server-side encryption configuration"), - accessControl: AccessControlConfigSchema.optional().describe("Access control configuration"), - lifecyclePolicy: LifecyclePolicyConfigSchema.optional().describe("Lifecycle policy configuration"), - multipartConfig: MultipartUploadConfigSchema.optional().describe("Multipart upload configuration"), - tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Bucket tags for organization"), - description: external_exports.string().optional().describe("Bucket description"), - enabled: external_exports.boolean().default(true).describe("Enable this bucket") -}); -var StorageConnectionSchema = external_exports.object({ - // AWS S3 / MinIO - accessKeyId: external_exports.string().optional().describe("AWS access key ID or MinIO access key"), - secretAccessKey: external_exports.string().optional().describe("AWS secret access key or MinIO secret key"), - sessionToken: external_exports.string().optional().describe("AWS session token for temporary credentials"), - // Azure Blob Storage - accountName: external_exports.string().optional().describe("Azure storage account name"), - accountKey: external_exports.string().optional().describe("Azure storage account key"), - sasToken: external_exports.string().optional().describe("Azure SAS token"), - // Google Cloud Storage - projectId: external_exports.string().optional().describe("GCP project ID"), - credentials: external_exports.string().optional().describe("GCP service account credentials JSON"), - // Common - endpoint: external_exports.string().optional().describe("Custom endpoint URL"), - region: external_exports.string().optional().describe("Default region"), - useSSL: external_exports.boolean().default(true).describe("Use SSL/TLS for connections"), - timeout: external_exports.number().min(0).optional().describe("Connection timeout in milliseconds") -}); -var ObjectStorageConfigSchema = external_exports.object({ - name: SystemIdentifierSchema.describe("Storage configuration identifier"), - label: external_exports.string().describe("Display label"), - provider: StorageProviderSchema.describe("Primary storage provider"), - /** - * Storage scope - * Defines the lifecycle and access pattern for this storage - */ - scope: StorageScopeSchema.optional().default("global").describe("Storage scope"), - connection: StorageConnectionSchema.describe("Connection credentials"), - buckets: external_exports.array(BucketConfigSchema).default([]).describe("Configured buckets"), - defaultBucket: external_exports.string().optional().describe("Default bucket name for operations"), - /** - * Base path or location - * For local/scoped storage configurations - */ - location: external_exports.string().optional().describe("Root path (local) or base location"), - /** - * Storage quota in bytes - */ - quota: external_exports.number().int().positive().optional().describe("Max size in bytes"), - /** - * Provider-specific options - */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration options"), - enabled: external_exports.boolean().default(true).describe("Enable this storage configuration"), - description: external_exports.string().optional().describe("Configuration description") -}); -var s3StorageExample = ObjectStorageConfigSchema.parse({ - name: "aws_s3_storage", - label: "AWS S3 Production Storage", - provider: "s3", - connection: { - accessKeyId: "${AWS_ACCESS_KEY_ID}", - secretAccessKey: "${AWS_SECRET_ACCESS_KEY}", - region: "us-east-1" - }, - buckets: [ - { - name: "user_uploads", - label: "User Uploads", - bucketName: "my-app-user-uploads", - region: "us-east-1", - provider: "s3", - versioning: true, - encryption: { - enabled: true, - algorithm: "aws:kms", - kmsKeyId: "${AWS_KMS_KEY_ID}" - }, - accessControl: { - acl: "private", - corsEnabled: true, - allowedOrigins: ["https://app.example.com"], - allowedMethods: ["GET", "PUT", "POST"] - }, - lifecyclePolicy: { - enabled: true, - rules: [ - { - id: "archive_old_uploads", - enabled: true, - action: "transition", - daysAfterCreation: 90, - targetStorageClass: "glacier" - } - ] - }, - multipartConfig: { - enabled: true, - partSize: 10 * 1024 * 1024, - threshold: 100 * 1024 * 1024, - maxConcurrent: 4 - } - } - ], - defaultBucket: "user_uploads", - enabled: true -}); -var minioStorageExample = ObjectStorageConfigSchema.parse({ - name: "minio_local", - label: "MinIO Local Storage", - provider: "minio", - connection: { - accessKeyId: "minioadmin", - secretAccessKey: "minioadmin", - endpoint: "http://localhost:9000", - useSSL: false - }, - buckets: [ - { - name: "development_files", - label: "Development Files", - bucketName: "dev-files", - provider: "minio", - endpoint: "http://localhost:9000", - pathStyle: true, - accessControl: { - acl: "private" - } - } - ], - defaultBucket: "development_files", - enabled: true -}); -var azureBlobStorageExample = ObjectStorageConfigSchema.parse({ - name: "azure_blob_storage", - label: "Azure Blob Storage", - provider: "azure_blob", - connection: { - accountName: "mystorageaccount", - accountKey: "${AZURE_STORAGE_KEY}", - endpoint: "https://mystorageaccount.blob.core.windows.net" - }, - buckets: [ - { - name: "media_files", - label: "Media Files", - bucketName: "media", - provider: "azure_blob", - region: "eastus", - accessControl: { - acl: "public_read", - publicAccess: { - allowPublicRead: true, - allowPublicWrite: false, - allowPublicList: false - } - } - } - ], - defaultBucket: "media_files", - enabled: true -}); -var gcsStorageExample = ObjectStorageConfigSchema.parse({ - name: "gcs_storage", - label: "Google Cloud Storage", - provider: "gcs", - connection: { - projectId: "my-gcp-project", - credentials: "${GCP_SERVICE_ACCOUNT_JSON}" - }, - buckets: [ - { - name: "backup_storage", - label: "Backup Storage", - bucketName: "my-app-backups", - region: "us-central1", - provider: "gcs", - lifecyclePolicy: { - enabled: true, - rules: [ - { - id: "delete_old_backups", - enabled: true, - action: "delete", - daysAfterCreation: 30 - } - ] - } - } - ], - defaultBucket: "backup_storage", - enabled: true -}); -var SearchProviderSchema = external_exports.enum([ - "elasticsearch", - "algolia", - "meilisearch", - "typesense", - "opensearch" -]).describe("Supported full-text search engine provider"); -var AnalyzerConfigSchema = external_exports.object({ - type: external_exports.enum(["standard", "simple", "whitespace", "keyword", "pattern", "language"]).describe("Text analyzer type"), - language: external_exports.string().optional().describe("Language for language-specific analysis"), - stopwords: external_exports.array(external_exports.string()).optional().describe("Custom stopwords to filter during analysis"), - customFilters: external_exports.array(external_exports.string()).optional().describe("Additional token filter names to apply") -}).describe("Text analyzer configuration for index tokenization and normalization"); -var SearchIndexConfigSchema = external_exports.object({ - indexName: external_exports.string().describe("Name of the search index"), - objectName: external_exports.string().describe("Source ObjectQL object"), - fields: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Field name to index"), - type: external_exports.enum(["text", "keyword", "number", "date", "boolean", "geo"]).describe("Index field data type"), - analyzer: external_exports.string().optional().describe("Named analyzer to use for this field"), - searchable: external_exports.boolean().default(true).describe("Include field in full-text search"), - filterable: external_exports.boolean().default(false).describe("Allow filtering on this field"), - sortable: external_exports.boolean().default(false).describe("Allow sorting by this field"), - boost: external_exports.number().default(1).describe("Relevance boost factor for this field") - })).describe("Fields to include in the search index"), - replicas: external_exports.number().default(1).describe("Number of index replicas for availability"), - shards: external_exports.number().default(1).describe("Number of index shards for distribution") -}).describe("Search index definition mapping an ObjectQL object to a search engine index"); -var FacetConfigSchema = external_exports.object({ - field: external_exports.string().describe("Field name to generate facets from"), - maxValues: external_exports.number().default(10).describe("Maximum number of facet values to return"), - sort: external_exports.enum(["count", "alpha"]).default("count").describe("Facet value sort order") -}).describe("Faceted search configuration for a single field"); -var SearchConfigSchema = external_exports.object({ - provider: SearchProviderSchema.describe("Search engine backend provider"), - indexes: external_exports.array(SearchIndexConfigSchema).describe("Search index definitions"), - analyzers: external_exports.record(external_exports.string(), AnalyzerConfigSchema).optional().describe("Named text analyzer configurations"), - facets: external_exports.array(FacetConfigSchema).optional().describe("Faceted search configurations"), - typoTolerance: external_exports.boolean().default(true).describe("Enable typo-tolerant search"), - synonyms: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional().describe("Synonym mappings for search expansion"), - ranking: external_exports.array(external_exports.enum(["typo", "geo", "words", "filters", "proximity", "attribute", "exact", "custom"])).optional().describe("Custom ranking rule order") -}).describe("Top-level full-text search engine configuration"); -var HttpMethod = external_exports.enum([ - "GET", - "POST", - "PUT", - "DELETE", - "PATCH", - "HEAD", - "OPTIONS" -]); -var HttpMethodSchema = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); -external_exports.object({ - url: external_exports.string().describe("API endpoint URL"), - method: HttpMethodSchema.optional().default("GET").describe("HTTP method"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), - body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") -}); -var CorsConfigSchema = external_exports.object({ - /** - * Enable CORS - */ - enabled: external_exports.boolean().default(true).describe("Enable CORS"), - /** - * Allowed origins (* for all) - */ - origins: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.string()) - ]).default("*").describe("Allowed origins (* for all)"), - /** - * Allowed HTTP methods - */ - methods: external_exports.array(HttpMethod).optional().describe("Allowed HTTP methods"), - /** - * Allow credentials (cookies, authorization headers) - */ - credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), - /** - * Preflight cache duration in seconds - */ - maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") -}); -var RateLimitConfigSchema = external_exports.object({ - /** - * Enable rate limiting - */ - enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), - /** - * Time window in milliseconds - */ - windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), - /** - * Max requests per window - */ - maxRequests: external_exports.number().int().default(100).describe("Max requests per window") -}); -var StaticMountSchema = external_exports.object({ - /** - * URL path to serve from - */ - path: external_exports.string().describe("URL path to serve from"), - /** - * Physical directory to serve - */ - directory: external_exports.string().describe("Physical directory to serve"), - /** - * Cache-Control header value - */ - cacheControl: external_exports.string().optional().describe("Cache-Control header value") -}); -var HttpServerConfigSchema = external_exports.object({ - /** - * Server port number - */ - port: external_exports.number().int().min(1).max(65535).default(3e3).describe("Port number to listen on"), - /** - * Server host address - */ - host: external_exports.string().default("0.0.0.0").describe("Host address to bind to"), - /** - * CORS configuration - */ - cors: CorsConfigSchema.optional().describe("CORS configuration"), - /** - * Request handling options - */ - requestTimeout: external_exports.number().int().default(3e4).describe("Request timeout in milliseconds"), - bodyLimit: external_exports.string().default("10mb").describe("Maximum request body size"), - /** - * Compression settings - */ - compression: external_exports.boolean().default(true).describe("Enable response compression"), - /** - * Security headers - */ - security: external_exports.object({ - helmet: external_exports.boolean().default(true).describe("Enable security headers via helmet"), - rateLimit: RateLimitConfigSchema.optional().describe("Global rate limiting configuration") - }).optional().describe("Security configuration"), - /** - * Static file serving - */ - static: external_exports.array(StaticMountSchema).optional().describe("Static file serving configuration"), - /** - * Trust proxy settings - */ - trustProxy: external_exports.boolean().default(false).describe("Trust X-Forwarded-* headers") -}); -var RouteHandlerMetadataSchema = external_exports.object({ - /** - * HTTP method - */ - method: HttpMethod.describe("HTTP method"), - /** - * URL path pattern (supports parameters like /api/users/:id) - */ - path: external_exports.string().describe("URL path pattern"), - /** - * Handler function name or identifier - */ - handler: external_exports.string().describe("Handler identifier or name"), - /** - * Route metadata - */ - metadata: external_exports.object({ - summary: external_exports.string().optional().describe("Route summary for documentation"), - description: external_exports.string().optional().describe("Route description"), - tags: external_exports.array(external_exports.string()).optional().describe("Tags for grouping"), - operationId: external_exports.string().optional().describe("Unique operation identifier") - }).optional(), - /** - * Security requirements - */ - security: external_exports.object({ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - rateLimit: external_exports.string().optional().describe("Rate limit policy override") - }).optional() -}); -var MiddlewareType = external_exports.enum([ - "authentication", - // Authentication middleware - "authorization", - // Authorization/permission checks - "logging", - // Request/response logging - "validation", - // Input validation - "transformation", - // Request/response transformation - "error", - // Error handling - "custom" - // Custom middleware -]); -var MiddlewareConfigSchema = external_exports.object({ - /** - * Middleware identifier - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Middleware name (snake_case)"), - /** - * Middleware type - */ - type: MiddlewareType.describe("Middleware type"), - /** - * Enable/disable middleware - */ - enabled: external_exports.boolean().default(true).describe("Whether middleware is enabled"), - /** - * Execution order (lower numbers execute first) - */ - order: external_exports.number().int().default(100).describe("Execution order priority"), - /** - * Middleware-specific configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Middleware configuration object"), - /** - * Path patterns to apply middleware to - */ - paths: external_exports.object({ - include: external_exports.array(external_exports.string()).optional().describe("Include path patterns (glob)"), - exclude: external_exports.array(external_exports.string()).optional().describe("Exclude path patterns (glob)") - }).optional().describe("Path filtering") -}); -var ServerEventType = external_exports.enum([ - "starting", - // Server is starting - "started", - // Server has started and is listening - "stopping", - // Server is stopping - "stopped", - // Server has stopped - "request", - // Request received - "response", - // Response sent - "error" - // Error occurred -]); -var ServerEventSchema = external_exports.object({ - /** - * Event type - */ - type: ServerEventType.describe("Event type"), - /** - * Timestamp - */ - timestamp: external_exports.string().datetime().describe("Event timestamp (ISO 8601)"), - /** - * Event payload - */ - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific data") -}); -var ServerCapabilitiesSchema = external_exports.object({ - /** - * Supported HTTP versions - */ - httpVersions: external_exports.array(external_exports.enum(["1.0", "1.1", "2.0", "3.0"])).default(["1.1"]).describe("Supported HTTP versions"), - /** - * WebSocket support - */ - websocket: external_exports.boolean().default(false).describe("WebSocket support"), - /** - * Server-Sent Events support - */ - sse: external_exports.boolean().default(false).describe("Server-Sent Events support"), - /** - * HTTP/2 Server Push - */ - serverPush: external_exports.boolean().default(false).describe("HTTP/2 Server Push support"), - /** - * Streaming support - */ - streaming: external_exports.boolean().default(true).describe("Response streaming support"), - /** - * Middleware support - */ - middleware: external_exports.boolean().default(true).describe("Middleware chain support"), - /** - * Route parameterization - */ - routeParams: external_exports.boolean().default(true).describe("URL parameter support (/users/:id)"), - /** - * Built-in compression - */ - compression: external_exports.boolean().default(true).describe("Built-in compression support") -}); -var ServerStatusSchema = external_exports.object({ - /** - * Server state - */ - state: external_exports.enum(["stopped", "starting", "running", "stopping", "error"]).describe("Current server state"), - /** - * Uptime in milliseconds - */ - uptime: external_exports.number().int().optional().describe("Server uptime in milliseconds"), - /** - * Server information - */ - server: external_exports.object({ - port: external_exports.number().int().describe("Listening port"), - host: external_exports.string().describe("Bound host"), - url: external_exports.string().optional().describe("Full server URL") - }).optional(), - /** - * Connection metrics - */ - connections: external_exports.object({ - active: external_exports.number().int().describe("Active connections"), - total: external_exports.number().int().describe("Total connections handled") - }).optional(), - /** - * Request metrics - */ - requests: external_exports.object({ - total: external_exports.number().int().describe("Total requests processed"), - success: external_exports.number().int().describe("Successful requests"), - errors: external_exports.number().int().describe("Failed requests") - }).optional() -}); -var HttpServerConfig = Object.assign(HttpServerConfigSchema, { - create: (config4) => config4 -}); -var MiddlewareConfig = Object.assign(MiddlewareConfigSchema, { - create: (config4) => config4 -}); -var AuditEventType = external_exports.enum([ - // Data Operations (CRUD) - "data.create", - // Record creation - "data.read", - // Record retrieval/viewing - "data.update", - // Record modification - "data.delete", - // Record deletion - "data.export", - // Data export operations - "data.import", - // Data import operations - "data.bulk_update", - // Bulk update operations - "data.bulk_delete", - // Bulk delete operations - // Authentication Events - "auth.login", - // Successful login - "auth.login_failed", - // Failed login attempt - "auth.logout", - // User logout - "auth.session_created", - // New session created - "auth.session_expired", - // Session expiration - "auth.password_reset", - // Password reset initiated - "auth.password_changed", - // Password successfully changed - "auth.email_verified", - // Email verification completed - "auth.mfa_enabled", - // Multi-factor auth enabled - "auth.mfa_disabled", - // Multi-factor auth disabled - "auth.account_locked", - // Account locked (too many failures) - "auth.account_unlocked", - // Account unlocked - // Authorization Events - "authz.permission_granted", - // Permission granted to user - "authz.permission_revoked", - // Permission revoked from user - "authz.role_assigned", - // Role assigned to user - "authz.role_removed", - // Role removed from user - "authz.role_created", - // New role created - "authz.role_updated", - // Role permissions modified - "authz.role_deleted", - // Role deleted - "authz.policy_created", - // Security policy created - "authz.policy_updated", - // Security policy updated - "authz.policy_deleted", - // Security policy deleted - // System Events - "system.config_changed", - // System configuration modified - "system.plugin_installed", - // Plugin installed - "system.plugin_uninstalled", - // Plugin uninstalled - "system.backup_created", - // Backup created - "system.backup_restored", - // Backup restored - "system.integration_added", - // External integration added - "system.integration_removed", - // External integration removed - // Security Events - "security.access_denied", - // Access denied (authorization failure) - "security.suspicious_activity", - // Suspicious activity detected - "security.data_breach", - // Potential data breach detected - "security.api_key_created", - // API key created - "security.api_key_revoked" - // API key revoked -]); -var AuditEventSeverity = external_exports.enum([ - "debug", - // Diagnostic information - "info", - // Informational events (normal operations) - "notice", - // Normal but significant events - "warning", - // Warning conditions - "error", - // Error conditions - "critical", - // Critical conditions requiring immediate attention - "alert", - // Action must be taken immediately - "emergency" - // System is unusable -]); -var AuditEventActorSchema = external_exports.object({ - /** - * Actor type (user, system, service, api_client, etc.) - */ - type: external_exports.enum(["user", "system", "service", "api_client", "integration"]).describe("Actor type"), - /** - * Unique identifier for the actor - */ - id: external_exports.string().describe("Actor identifier"), - /** - * Display name of the actor - */ - name: external_exports.string().optional().describe("Actor display name"), - /** - * Email address (for user actors) - */ - email: external_exports.string().email().optional().describe("Actor email address"), - /** - * IP address of the actor - */ - ipAddress: external_exports.string().optional().describe("Actor IP address"), - /** - * User agent string (for web/API requests) - */ - userAgent: external_exports.string().optional().describe("User agent string") -}); -var AuditEventTargetSchema = external_exports.object({ - /** - * Target type (e.g., 'object', 'record', 'user', 'role', 'config') - */ - type: external_exports.string().describe("Target type"), - /** - * Unique identifier for the target - */ - id: external_exports.string().describe("Target identifier"), - /** - * Display name of the target - */ - name: external_exports.string().optional().describe("Target display name"), - /** - * Additional metadata about the target - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Target metadata") -}); -var AuditEventChangeSchema = external_exports.object({ - /** - * Field/property that changed - */ - field: external_exports.string().describe("Changed field name"), - /** - * Value before the change - */ - oldValue: external_exports.unknown().optional().describe("Previous value"), - /** - * Value after the change - */ - newValue: external_exports.unknown().optional().describe("New value") -}); -var AuditEventSchema = external_exports.object({ - /** - * Unique identifier for this audit event - */ - id: external_exports.string().describe("Audit event ID"), - /** - * Type of event being audited - */ - eventType: AuditEventType.describe("Event type"), - /** - * Severity level of the event - */ - severity: AuditEventSeverity.default("info").describe("Event severity"), - /** - * Timestamp when the event occurred (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("Event timestamp"), - /** - * Who/what performed the action - */ - actor: AuditEventActorSchema.describe("Event actor"), - /** - * What was acted upon - */ - target: AuditEventTargetSchema.optional().describe("Event target"), - /** - * Human-readable description of the action - */ - description: external_exports.string().describe("Event description"), - /** - * Detailed changes (for update operations) - */ - changes: external_exports.array(AuditEventChangeSchema).optional().describe("List of changes"), - /** - * Result of the action (success, failure, partial) - */ - result: external_exports.enum(["success", "failure", "partial"]).default("success").describe("Action result"), - /** - * Error message (if result is failure) - */ - errorMessage: external_exports.string().optional().describe("Error message"), - /** - * Tenant identifier (for multi-tenant systems) - */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** - * Request/trace ID for correlation - */ - requestId: external_exports.string().optional().describe("Request ID for tracing"), - /** - * Additional context and metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata"), - /** - * Geographic location (if available) - */ - location: external_exports.object({ - country: external_exports.string().optional(), - region: external_exports.string().optional(), - city: external_exports.string().optional() - }).optional().describe("Geographic location") -}); -var AuditRetentionPolicySchema = external_exports.object({ - /** - * Retention period in days - * Default: 180 days (GDPR 6-month requirement) - */ - retentionDays: external_exports.number().int().min(1).default(180).describe("Retention period in days"), - /** - * Whether to archive logs after retention period - * If true, logs are moved to cold storage; if false, they are deleted - */ - archiveAfterRetention: external_exports.boolean().default(true).describe("Archive logs after retention period"), - /** - * Archive storage configuration - */ - archiveStorage: external_exports.object({ - type: external_exports.enum(["s3", "gcs", "azure_blob", "filesystem"]).describe("Archive storage type"), - endpoint: external_exports.string().optional().describe("Storage endpoint URL"), - bucket: external_exports.string().optional().describe("Storage bucket/container name"), - path: external_exports.string().optional().describe("Storage path prefix"), - credentials: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage credentials") - }).optional().describe("Archive storage configuration"), - /** - * Event types that have different retention periods - * Overrides the default retentionDays for specific event types - */ - customRetention: external_exports.record(external_exports.string(), external_exports.number().int().positive()).optional().describe("Custom retention by event type"), - /** - * Minimum retention period for compliance - * Prevents accidental deletion below compliance requirements - */ - minimumRetentionDays: external_exports.number().int().positive().optional().describe("Minimum retention for compliance") -}); -var SuspiciousActivityRuleSchema = external_exports.object({ - /** - * Unique identifier for the rule - */ - id: external_exports.string().describe("Rule identifier"), - /** - * Rule name - */ - name: external_exports.string().describe("Rule name"), - /** - * Rule description - */ - description: external_exports.string().optional().describe("Rule description"), - /** - * Whether the rule is enabled - */ - enabled: external_exports.boolean().default(true).describe("Rule enabled status"), - /** - * Event types to monitor - */ - eventTypes: external_exports.array(AuditEventType).describe("Event types to monitor"), - /** - * Detection condition - */ - condition: external_exports.object({ - /** - * Number of events that trigger the rule - */ - threshold: external_exports.number().int().positive().describe("Event threshold"), - /** - * Time window in seconds - */ - windowSeconds: external_exports.number().int().positive().describe("Time window in seconds"), - /** - * Grouping criteria (e.g., by actor.id, by ipAddress) - */ - groupBy: external_exports.array(external_exports.string()).optional().describe("Grouping criteria"), - /** - * Additional filters - */ - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional filters") - }).describe("Detection condition"), - /** - * Actions to take when rule is triggered - */ - actions: external_exports.array(external_exports.enum([ - "alert", - // Send alert notification - "lock_account", - // Lock the user account - "block_ip", - // Block the IP address - "require_mfa", - // Require multi-factor authentication - "log_critical", - // Log as critical event - "webhook" - // Call webhook - ])).describe("Actions to take"), - /** - * Severity level for triggered alerts - */ - alertSeverity: AuditEventSeverity.default("warning").describe("Alert severity"), - /** - * Notification configuration - */ - notifications: external_exports.object({ - /** - * Email addresses to notify - */ - email: external_exports.array(external_exports.string().email()).optional().describe("Email recipients"), - /** - * Slack webhook URL - */ - slack: external_exports.string().url().optional().describe("Slack webhook URL"), - /** - * Custom webhook URL - */ - webhook: external_exports.string().url().optional().describe("Custom webhook URL") - }).optional().describe("Notification configuration") -}); -var AuditStorageConfigSchema = external_exports.object({ - /** - * Storage backend type - */ - type: external_exports.enum([ - "database", - // Store in database (PostgreSQL, MySQL, etc.) - "elasticsearch", - // Store in Elasticsearch - "mongodb", - // Store in MongoDB - "clickhouse", - // Store in ClickHouse (for analytics) - "s3", - // Store in S3-compatible storage - "gcs", - // Store in Google Cloud Storage - "azure_blob", - // Store in Azure Blob Storage - "custom" - // Custom storage implementation - ]).describe("Storage backend type"), - /** - * Connection string or configuration - */ - connectionString: external_exports.string().optional().describe("Connection string"), - /** - * Storage configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage-specific configuration"), - /** - * Whether to enable buffering/batching - */ - bufferEnabled: external_exports.boolean().default(true).describe("Enable buffering"), - /** - * Buffer size (number of events before flush) - */ - bufferSize: external_exports.number().int().positive().default(100).describe("Buffer size"), - /** - * Buffer flush interval in seconds - */ - flushIntervalSeconds: external_exports.number().int().positive().default(5).describe("Flush interval in seconds"), - /** - * Whether to compress stored data - */ - compression: external_exports.boolean().default(true).describe("Enable compression") -}); -var AuditEventFilterSchema = external_exports.object({ - /** - * Filter by event types - */ - eventTypes: external_exports.array(AuditEventType).optional().describe("Event types to include"), - /** - * Filter by severity levels - */ - severities: external_exports.array(AuditEventSeverity).optional().describe("Severity levels to include"), - /** - * Filter by actor ID - */ - actorId: external_exports.string().optional().describe("Actor identifier"), - /** - * Filter by tenant ID - */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** - * Filter by time range - */ - timeRange: external_exports.object({ - from: external_exports.string().datetime().describe("Start time"), - to: external_exports.string().datetime().describe("End time") - }).optional().describe("Time range filter"), - /** - * Filter by result status - */ - result: external_exports.enum(["success", "failure", "partial"]).optional().describe("Result status"), - /** - * Search query (full-text search) - */ - searchQuery: external_exports.string().optional().describe("Search query"), - /** - * Custom filters - */ - customFilters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom filters") -}); -var AuditConfigSchema = external_exports.object({ - /** - * Unique identifier for this audit configuration - * Must be in snake_case following ObjectStack conventions - * Maximum length: 64 characters - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), - /** - * Human-readable label - */ - label: external_exports.string().describe("Display label"), - /** - * Whether audit logging is enabled - */ - enabled: external_exports.boolean().default(true).describe("Enable audit logging"), - /** - * Event types to audit - * If not specified, all event types are audited - */ - eventTypes: external_exports.array(AuditEventType).optional().describe("Event types to audit"), - /** - * Event types to exclude from auditing - */ - excludeEventTypes: external_exports.array(AuditEventType).optional().describe("Event types to exclude"), - /** - * Minimum severity level to log - * Events below this level are not logged - */ - minimumSeverity: AuditEventSeverity.default("info").describe("Minimum severity level"), - /** - * Storage configuration - */ - storage: AuditStorageConfigSchema.describe("Storage configuration"), - /** - * Retention policy - */ - retentionPolicy: AuditRetentionPolicySchema.optional().describe("Retention policy"), - /** - * Suspicious activity detection rules - */ - suspiciousActivityRules: external_exports.array(SuspiciousActivityRuleSchema).default([]).describe("Suspicious activity rules"), - /** - * Whether to include sensitive data in audit logs - * If false, sensitive fields are redacted/masked - */ - includeSensitiveData: external_exports.boolean().default(false).describe("Include sensitive data"), - /** - * Fields to redact from audit logs - */ - redactFields: external_exports.array(external_exports.string()).default([ - "password", - "passwordHash", - "token", - "apiKey", - "secret", - "creditCard", - "ssn" - ]).describe("Fields to redact"), - /** - * Whether to log successful read operations - * Can be disabled to reduce log volume - */ - logReads: external_exports.boolean().default(false).describe("Log read operations"), - /** - * Sampling rate for read operations (0.0 to 1.0) - * Only applies if logReads is true - */ - readSamplingRate: external_exports.number().min(0).max(1).default(0.1).describe("Read sampling rate"), - /** - * Whether to log system/internal operations - */ - logSystemEvents: external_exports.boolean().default(true).describe("Log system events"), - /** - * Custom audit event handlers - * Note: Function handlers are for runtime configuration only and will not be serialized to JSON Schema - */ - customHandlers: external_exports.array(external_exports.object({ - eventType: AuditEventType.describe("Event type to handle"), - handlerId: external_exports.string().describe("Unique identifier for the handler") - })).optional().describe("Custom event handler references"), - /** - * Compliance mode configuration - */ - compliance: external_exports.object({ - /** - * Compliance standards to enforce - */ - standards: external_exports.array(external_exports.enum([ - "sox", - // Sarbanes-Oxley Act - "hipaa", - // Health Insurance Portability and Accountability Act - "gdpr", - // General Data Protection Regulation - "pci_dss", - // Payment Card Industry Data Security Standard - "iso_27001", - // ISO/IEC 27001 - "fedramp" - // Federal Risk and Authorization Management Program - ])).optional().describe("Compliance standards"), - /** - * Whether to enforce immutable audit logs - */ - immutableLogs: external_exports.boolean().default(true).describe("Enforce immutable logs"), - /** - * Whether to require cryptographic signing - */ - requireSigning: external_exports.boolean().default(false).describe("Require log signing"), - /** - * Signing key configuration - */ - signingKey: external_exports.string().optional().describe("Signing key") - }).optional().describe("Compliance configuration") -}); -var LogLevel = external_exports.enum([ - "debug", - "info", - "warn", - "error", - "fatal", - "silent" -]).describe("Log severity level"); -var LogFormat = external_exports.enum([ - "json", - // Structured JSON for machine parsing - "text", - // Simple text format - "pretty" - // Colored human-readable output for CLI/console -]).describe("Log output format"); -var LoggerConfigSchema = external_exports.object({ - /** - * Logger name - */ - name: external_exports.string().optional().describe("Logger name identifier"), - /** - * Minimum level to log - */ - level: LogLevel.optional().default("info"), - /** - * Output format - */ - format: LogFormat.optional().default("json"), - /** - * Redact sensitive keys - */ - redact: external_exports.array(external_exports.string()).optional().default(["password", "token", "secret", "key"]).describe("Keys to redact from log context"), - /** - * Enable source location (file/line) - */ - sourceLocation: external_exports.boolean().optional().default(false).describe("Include file and line number"), - /** - * Log to file (optional) - */ - file: external_exports.string().optional().describe("Path to log file"), - /** - * Log rotation config (if file is set) - */ - rotation: external_exports.object({ - maxSize: external_exports.string().optional().default("10m"), - maxFiles: external_exports.number().optional().default(5) - }).optional() -}); -var LogEntrySchema = external_exports.object({ - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), - level: LogLevel, - message: external_exports.string().describe("Log message"), - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Structured context data"), - error: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Error object if present"), - /** Tracing */ - traceId: external_exports.string().optional().describe("Distributed trace ID"), - spanId: external_exports.string().optional().describe("Span ID"), - /** Source */ - service: external_exports.string().optional().describe("Service name"), - component: external_exports.string().optional().describe("Component name (e.g. plugin id)") -}); -var ExtendedLogLevel = external_exports.enum([ - "trace", - // Very detailed debugging information - "debug", - // Debugging information - "info", - // Informational messages - "warn", - // Warning messages - "error", - // Error messages - "fatal" - // Fatal errors causing shutdown -]).describe("Extended log severity level"); -var LogDestinationType = external_exports.enum([ - "console", - // Standard output/error - "file", - // File system - "syslog", - // System logger - "elasticsearch", - // Elasticsearch - "cloudwatch", - // AWS CloudWatch - "stackdriver", - // Google Cloud Logging - "azure_monitor", - // Azure Monitor - "datadog", - // Datadog - "splunk", - // Splunk - "loki", - // Grafana Loki - "http", - // HTTP endpoint - "kafka", - // Apache Kafka - "redis", - // Redis streams - "custom" - // Custom implementation -]).describe("Log destination type"); -var ConsoleDestinationConfigSchema = external_exports.object({ - /** - * Output stream - */ - stream: external_exports.enum(["stdout", "stderr"]).optional().default("stdout"), - /** - * Enable colored output - */ - colors: external_exports.boolean().optional().default(true), - /** - * Pretty print JSON - */ - prettyPrint: external_exports.boolean().optional().default(false) -}).describe("Console destination configuration"); -var FileDestinationConfigSchema = external_exports.object({ - /** - * File path - */ - path: external_exports.string().describe("Log file path"), - /** - * Enable log rotation - */ - rotation: external_exports.object({ - /** - * Maximum file size before rotation (e.g., '10m', '100k', '1g') - */ - maxSize: external_exports.string().optional().default("10m"), - /** - * Maximum number of files to keep - */ - maxFiles: external_exports.number().int().positive().optional().default(5), - /** - * Compress rotated files - */ - compress: external_exports.boolean().optional().default(true), - /** - * Rotation interval (e.g., 'daily', 'weekly') - */ - interval: external_exports.enum(["hourly", "daily", "weekly", "monthly"]).optional() - }).optional(), - /** - * File encoding - */ - encoding: external_exports.string().optional().default("utf8"), - /** - * Append to existing file - */ - append: external_exports.boolean().optional().default(true) -}).describe("File destination configuration"); -var HttpDestinationConfigSchema = external_exports.object({ - /** - * HTTP endpoint URL - */ - url: external_exports.string().url().describe("HTTP endpoint URL"), - /** - * HTTP method - */ - method: external_exports.enum(["POST", "PUT"]).optional().default("POST"), - /** - * Headers to include - */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional(), - /** - * Authentication - */ - auth: external_exports.object({ - type: external_exports.enum(["basic", "bearer", "api_key"]).describe("Auth type"), - username: external_exports.string().optional(), - password: external_exports.string().optional(), - token: external_exports.string().optional(), - apiKey: external_exports.string().optional(), - apiKeyHeader: external_exports.string().optional().default("X-API-Key") - }).optional(), - /** - * Batch configuration - */ - batch: external_exports.object({ - /** - * Maximum batch size - */ - maxSize: external_exports.number().int().positive().optional().default(100), - /** - * Flush interval in milliseconds - */ - flushInterval: external_exports.number().int().positive().optional().default(5e3) - }).optional(), - /** - * Retry configuration - */ - retry: external_exports.object({ - /** - * Maximum retry attempts - */ - maxAttempts: external_exports.number().int().positive().optional().default(3), - /** - * Initial retry delay in milliseconds - */ - initialDelay: external_exports.number().int().positive().optional().default(1e3), - /** - * Backoff multiplier - */ - backoffMultiplier: external_exports.number().positive().optional().default(2) - }).optional(), - /** - * Timeout in milliseconds - */ - timeout: external_exports.number().int().positive().optional().default(3e4) -}).describe("HTTP destination configuration"); -var ExternalServiceDestinationConfigSchema = external_exports.object({ - /** - * Service-specific endpoint - */ - endpoint: external_exports.string().url().optional(), - /** - * Region (for cloud services) - */ - region: external_exports.string().optional(), - /** - * Credentials - */ - credentials: external_exports.object({ - accessKeyId: external_exports.string().optional(), - secretAccessKey: external_exports.string().optional(), - apiKey: external_exports.string().optional(), - projectId: external_exports.string().optional() - }).optional(), - /** - * Log group/stream/index name - */ - logGroup: external_exports.string().optional(), - logStream: external_exports.string().optional(), - index: external_exports.string().optional(), - /** - * Service-specific configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}).describe("External service destination configuration"); -var LogDestinationSchema = external_exports.object({ - /** - * Destination name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Destination name (snake_case)"), - /** - * Destination type - */ - type: LogDestinationType.describe("Destination type"), - /** - * Minimum log level for this destination - */ - level: ExtendedLogLevel.optional().default("info"), - /** - * Enabled flag - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Console configuration - */ - console: ConsoleDestinationConfigSchema.optional(), - /** - * File configuration - */ - file: FileDestinationConfigSchema.optional(), - /** - * HTTP configuration - */ - http: HttpDestinationConfigSchema.optional(), - /** - * External service configuration - */ - externalService: ExternalServiceDestinationConfigSchema.optional(), - /** - * Format for this destination - */ - format: external_exports.enum(["json", "text", "pretty"]).optional().default("json"), - /** - * Filter function reference (runtime only) - */ - filterId: external_exports.string().optional().describe("Filter function identifier") -}).describe("Log destination configuration"); -var LogEnrichmentConfigSchema = external_exports.object({ - /** - * Static fields to add to all logs - */ - staticFields: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Static fields added to every log"), - /** - * Dynamic field enrichers (runtime only) - * References to functions that add dynamic context - */ - dynamicEnrichers: external_exports.array(external_exports.string()).optional().describe("Dynamic enricher function IDs"), - /** - * Add hostname - */ - addHostname: external_exports.boolean().optional().default(true), - /** - * Add process ID - */ - addProcessId: external_exports.boolean().optional().default(true), - /** - * Add environment info - */ - addEnvironment: external_exports.boolean().optional().default(true), - /** - * Add timestamp in additional formats - */ - addTimestampFormats: external_exports.object({ - unix: external_exports.boolean().optional().default(false), - iso: external_exports.boolean().optional().default(true) - }).optional(), - /** - * Add caller information (file, line, function) - */ - addCaller: external_exports.boolean().optional().default(false), - /** - * Add correlation IDs - */ - addCorrelationIds: external_exports.boolean().optional().default(true) -}).describe("Log enrichment configuration"); -var StructuredLogEntrySchema = external_exports.object({ - /** - * Timestamp (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), - /** - * Log level - */ - level: ExtendedLogLevel.describe("Log severity level"), - /** - * Log message - */ - message: external_exports.string().describe("Log message"), - /** - * Structured context data - */ - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Structured context"), - /** - * Error information - */ - error: external_exports.object({ - name: external_exports.string().optional(), - message: external_exports.string().optional(), - stack: external_exports.string().optional(), - code: external_exports.string().optional(), - details: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional().describe("Error details"), - /** - * Trace context - */ - trace: external_exports.object({ - traceId: external_exports.string().describe("Trace ID"), - spanId: external_exports.string().describe("Span ID"), - parentSpanId: external_exports.string().optional().describe("Parent span ID"), - traceFlags: external_exports.number().int().optional().describe("Trace flags") - }).optional().describe("Distributed tracing context"), - /** - * Source information - */ - source: external_exports.object({ - service: external_exports.string().optional().describe("Service name"), - component: external_exports.string().optional().describe("Component name"), - file: external_exports.string().optional().describe("Source file"), - line: external_exports.number().int().optional().describe("Line number"), - function: external_exports.string().optional().describe("Function name") - }).optional().describe("Source information"), - /** - * Host information - */ - host: external_exports.object({ - hostname: external_exports.string().optional(), - pid: external_exports.number().int().optional(), - ip: external_exports.string().optional() - }).optional().describe("Host information"), - /** - * Environment - */ - environment: external_exports.string().optional().describe("Environment (e.g., production, staging)"), - /** - * User information - */ - user: external_exports.object({ - id: external_exports.string().optional(), - username: external_exports.string().optional(), - email: external_exports.string().optional() - }).optional().describe("User context"), - /** - * Request information - */ - request: external_exports.object({ - id: external_exports.string().optional(), - method: external_exports.string().optional(), - path: external_exports.string().optional(), - userAgent: external_exports.string().optional(), - ip: external_exports.string().optional() - }).optional().describe("Request context"), - /** - * Custom labels/tags - */ - labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom labels"), - /** - * Additional metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata") -}).describe("Structured log entry"); -var LoggingConfigSchema = external_exports.object({ - /** - * Configuration name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Enable logging - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Global minimum log level - */ - level: ExtendedLogLevel.optional().default("info"), - /** - * Default logger configuration - * Basic logger config for the kernel - */ - default: LoggerConfigSchema.optional().describe("Default logger configuration"), - /** - * Named logger configurations - * Map of logger name to logger config for different components/modules - */ - loggers: external_exports.record(external_exports.string(), LoggerConfigSchema).optional().describe("Named logger configurations"), - /** - * Log destinations - */ - destinations: external_exports.array(LogDestinationSchema).describe("Log destinations"), - /** - * Log enrichment configuration - */ - enrichment: LogEnrichmentConfigSchema.optional(), - /** - * Fields to redact from logs - */ - redact: external_exports.array(external_exports.string()).optional().default([ - "password", - "passwordHash", - "token", - "apiKey", - "secret", - "creditCard", - "ssn", - "authorization" - ]).describe("Fields to redact"), - /** - * Sampling configuration - */ - sampling: external_exports.object({ - /** - * Enable sampling - */ - enabled: external_exports.boolean().optional().default(false), - /** - * Sample rate (0.0 to 1.0) - */ - rate: external_exports.number().min(0).max(1).optional().default(1), - /** - * Sample rate by level - */ - rateByLevel: external_exports.record(external_exports.string(), external_exports.number().min(0).max(1)).optional() - }).optional(), - /** - * Buffer configuration - */ - buffer: external_exports.object({ - /** - * Enable buffering - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Buffer size - */ - size: external_exports.number().int().positive().optional().default(1e3), - /** - * Flush interval in milliseconds - */ - flushInterval: external_exports.number().int().positive().optional().default(1e3), - /** - * Flush on shutdown - */ - flushOnShutdown: external_exports.boolean().optional().default(true) - }).optional(), - /** - * Performance configuration - */ - performance: external_exports.object({ - /** - * Async logging - */ - async: external_exports.boolean().optional().default(true), - /** - * Worker threads for async logging - */ - workers: external_exports.number().int().positive().optional().default(1) - }).optional() -}).describe("Logging configuration"); -var MetricType = external_exports.enum([ - "counter", - // Monotonically increasing value - "gauge", - // Value that can go up and down - "histogram", - // Observations bucketed by configurable ranges - "summary" - // Observations with quantiles -]).describe("Metric type"); -var MetricUnit = external_exports.enum([ - // Time units - "nanoseconds", - "microseconds", - "milliseconds", - "seconds", - "minutes", - "hours", - "days", - // Size units - "bytes", - "kilobytes", - "megabytes", - "gigabytes", - "terabytes", - // Rate units - "requests_per_second", - "events_per_second", - "bytes_per_second", - // Percentage - "percent", - "ratio", - // Count - "count", - "operations", - // Custom - "custom" -]).describe("Metric unit"); -var MetricAggregationType = external_exports.enum([ - "sum", - // Sum of all values - "avg", - // Average of all values - "min", - // Minimum value - "max", - // Maximum value - "count", - // Count of observations - "p50", - // 50th percentile (median) - "p75", - // 75th percentile - "p90", - // 90th percentile - "p95", - // 95th percentile - "p99", - // 99th percentile - "p999", - // 99.9th percentile - "rate", - // Rate of change - "stddev" - // Standard deviation -]).describe("Metric aggregation type"); -var HistogramBucketConfigSchema = external_exports.object({ - /** - * Bucket type - */ - type: external_exports.enum(["linear", "exponential", "explicit"]).describe("Bucket type"), - /** - * Linear bucket configuration - */ - linear: external_exports.object({ - start: external_exports.number().describe("Start value"), - width: external_exports.number().positive().describe("Bucket width"), - count: external_exports.number().int().positive().describe("Number of buckets") - }).optional(), - /** - * Exponential bucket configuration - */ - exponential: external_exports.object({ - start: external_exports.number().positive().describe("Start value"), - factor: external_exports.number().positive().describe("Growth factor"), - count: external_exports.number().int().positive().describe("Number of buckets") - }).optional(), - /** - * Explicit bucket boundaries - */ - explicit: external_exports.object({ - boundaries: external_exports.array(external_exports.number()).describe("Bucket boundaries") - }).optional() -}).describe("Histogram bucket configuration"); -var MetricLabelsSchema = external_exports.record(external_exports.string(), external_exports.string()).describe("Metric labels"); -var MetricDefinitionSchema = external_exports.object({ - /** - * Metric name (snake_case) - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Metric name (snake_case)"), - /** - * Display label - */ - label: external_exports.string().optional().describe("Display label"), - /** - * Metric type - */ - type: MetricType.describe("Metric type"), - /** - * Metric unit - */ - unit: MetricUnit.optional().describe("Metric unit"), - /** - * Description - */ - description: external_exports.string().optional().describe("Metric description"), - /** - * Label names for this metric - */ - labelNames: external_exports.array(external_exports.string()).optional().default([]).describe("Label names"), - /** - * Histogram configuration (for histogram type) - */ - histogram: HistogramBucketConfigSchema.optional(), - /** - * Summary configuration (for summary type) - */ - summary: external_exports.object({ - /** - * Quantiles to track - */ - quantiles: external_exports.array(external_exports.number().min(0).max(1)).optional().default([0.5, 0.9, 0.99]), - /** - * Max age of observations in seconds - */ - maxAge: external_exports.number().int().positive().optional().default(600), - /** - * Number of age buckets - */ - ageBuckets: external_exports.number().int().positive().optional().default(5) - }).optional(), - /** - * Enabled flag - */ - enabled: external_exports.boolean().optional().default(true) -}).describe("Metric definition"); -var MetricDataPointSchema = external_exports.object({ - /** - * Metric name - */ - name: external_exports.string().describe("Metric name"), - /** - * Metric type - */ - type: MetricType.describe("Metric type"), - /** - * Timestamp (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("Observation timestamp"), - /** - * Value (for counter and gauge) - */ - value: external_exports.number().optional().describe("Metric value"), - /** - * Labels - */ - labels: MetricLabelsSchema.optional().describe("Metric labels"), - /** - * Histogram data - */ - histogram: external_exports.object({ - count: external_exports.number().int().nonnegative().describe("Total count"), - sum: external_exports.number().describe("Sum of all values"), - buckets: external_exports.array(external_exports.object({ - upperBound: external_exports.number().describe("Upper bound of bucket"), - count: external_exports.number().int().nonnegative().describe("Count in bucket") - })).describe("Histogram buckets") - }).optional(), - /** - * Summary data - */ - summary: external_exports.object({ - count: external_exports.number().int().nonnegative().describe("Total count"), - sum: external_exports.number().describe("Sum of all values"), - quantiles: external_exports.array(external_exports.object({ - quantile: external_exports.number().min(0).max(1).describe("Quantile (0-1)"), - value: external_exports.number().describe("Quantile value") - })).describe("Summary quantiles") - }).optional() -}).describe("Metric data point"); -var TimeSeriesDataPointSchema = external_exports.object({ - /** - * Timestamp (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("Timestamp"), - /** - * Value - */ - value: external_exports.number().describe("Value"), - /** - * Labels/tags - */ - labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Labels") -}).describe("Time series data point"); -var TimeSeriesSchema = external_exports.object({ - /** - * Series name - */ - name: external_exports.string().describe("Series name"), - /** - * Series labels - */ - labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Series labels"), - /** - * Data points - */ - dataPoints: external_exports.array(TimeSeriesDataPointSchema).describe("Data points"), - /** - * Start time - */ - startTime: external_exports.string().datetime().optional().describe("Start time"), - /** - * End time - */ - endTime: external_exports.string().datetime().optional().describe("End time") -}).describe("Time series"); -var MetricAggregationConfigSchema = external_exports.object({ - /** - * Aggregation type - */ - type: MetricAggregationType.describe("Aggregation type"), - /** - * Time window for aggregation - */ - window: external_exports.object({ - /** - * Window size in seconds - */ - size: external_exports.number().int().positive().describe("Window size in seconds"), - /** - * Sliding window (true) or tumbling window (false) - */ - sliding: external_exports.boolean().optional().default(false), - /** - * Slide interval for sliding windows - */ - slideInterval: external_exports.number().int().positive().optional() - }).optional(), - /** - * Group by labels - */ - groupBy: external_exports.array(external_exports.string()).optional().describe("Group by label names"), - /** - * Filters - */ - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria") -}).describe("Metric aggregation configuration"); -var ServiceLevelIndicatorSchema = external_exports.object({ - /** - * SLI name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("SLI name (snake_case)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Description - */ - description: external_exports.string().optional().describe("SLI description"), - /** - * Metric name this SLI is based on - */ - metric: external_exports.string().describe("Base metric name"), - /** - * SLI type - */ - type: external_exports.enum([ - "availability", - // Percentage of successful requests - "latency", - // Response time percentile - "throughput", - // Requests per second - "error_rate", - // Error percentage - "saturation", - // Resource utilization - "custom" - // Custom calculation - ]).describe("SLI type"), - /** - * Success criteria - */ - successCriteria: external_exports.object({ - /** - * Threshold value - */ - threshold: external_exports.number().describe("Threshold value"), - /** - * Comparison operator - */ - operator: external_exports.enum(["lt", "lte", "gt", "gte", "eq"]).describe("Comparison operator"), - /** - * Percentile (for latency SLIs) - */ - percentile: external_exports.number().min(0).max(1).optional().describe("Percentile (0-1)") - }).describe("Success criteria"), - /** - * Measurement window - */ - window: external_exports.object({ - /** - * Window size in seconds - */ - size: external_exports.number().int().positive().describe("Window size in seconds"), - /** - * Rolling window (true) or calendar-aligned (false) - */ - rolling: external_exports.boolean().optional().default(true) - }).describe("Measurement window"), - /** - * Enabled flag - */ - enabled: external_exports.boolean().optional().default(true) -}).describe("Service Level Indicator"); -var ServiceLevelObjectiveSchema = external_exports.object({ - /** - * SLO name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("SLO name (snake_case)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Description - */ - description: external_exports.string().optional().describe("SLO description"), - /** - * SLI this SLO is based on - */ - sli: external_exports.string().describe("SLI name"), - /** - * Target percentage (0-100) - */ - target: external_exports.number().min(0).max(100).describe("Target percentage"), - /** - * Time period for SLO - */ - period: external_exports.object({ - /** - * Period type - */ - type: external_exports.enum(["rolling", "calendar"]).describe("Period type"), - /** - * Duration in seconds (for rolling) - */ - duration: external_exports.number().int().positive().optional().describe("Duration in seconds"), - /** - * Calendar period (for calendar) - */ - calendar: external_exports.enum(["daily", "weekly", "monthly", "quarterly", "yearly"]).optional() - }).describe("Time period"), - /** - * Error budget configuration - */ - errorBudget: external_exports.object({ - /** - * Auto-calculated budget (1 - target) - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Alert when budget consumed percentage exceeds threshold - */ - alertThreshold: external_exports.number().min(0).max(100).optional().default(80), - /** - * Burn rate alert windows - */ - burnRateWindows: external_exports.array(external_exports.object({ - /** - * Window size in seconds - */ - window: external_exports.number().int().positive().describe("Window size"), - /** - * Burn rate multiplier threshold - */ - threshold: external_exports.number().positive().describe("Burn rate threshold") - })).optional() - }).optional(), - /** - * Alert configuration - */ - alerts: external_exports.array(external_exports.object({ - /** - * Alert name - */ - name: external_exports.string().describe("Alert name"), - /** - * Severity - */ - severity: external_exports.enum(["info", "warning", "critical"]).describe("Alert severity"), - /** - * Condition - */ - condition: external_exports.object({ - type: external_exports.enum(["slo_breach", "error_budget", "burn_rate"]).describe("Condition type"), - threshold: external_exports.number().optional().describe("Threshold value") - }).describe("Alert condition") - })).optional().default([]), - /** - * Enabled flag - */ - enabled: external_exports.boolean().optional().default(true) -}).describe("Service Level Objective"); -var MetricExportConfigSchema = external_exports.object({ - /** - * Export type - */ - type: external_exports.enum([ - "prometheus", - // Prometheus exposition format - "openmetrics", - // OpenMetrics format - "graphite", - // Graphite plaintext protocol - "statsd", - // StatsD protocol - "influxdb", - // InfluxDB line protocol - "datadog", - // Datadog agent - "cloudwatch", - // AWS CloudWatch - "stackdriver", - // Google Cloud Monitoring - "azure_monitor", - // Azure Monitor - "http", - // HTTP push - "custom" - // Custom exporter - ]).describe("Export type"), - /** - * Endpoint configuration - */ - endpoint: external_exports.string().optional().describe("Export endpoint"), - /** - * Export interval in seconds - */ - interval: external_exports.number().int().positive().optional().default(60), - /** - * Batch configuration - */ - batch: external_exports.object({ - enabled: external_exports.boolean().optional().default(true), - size: external_exports.number().int().positive().optional().default(1e3) - }).optional(), - /** - * Authentication - */ - auth: external_exports.object({ - type: external_exports.enum(["none", "basic", "bearer", "api_key"]).describe("Auth type"), - username: external_exports.string().optional(), - password: external_exports.string().optional(), - token: external_exports.string().optional(), - apiKey: external_exports.string().optional() - }).optional(), - /** - * Additional configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional configuration") -}).describe("Metric export configuration"); -var MetricsConfigSchema = external_exports.object({ - /** - * Configuration name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Enable metrics collection - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Metric definitions - */ - metrics: external_exports.array(MetricDefinitionSchema).optional().default([]), - /** - * Default labels applied to all metrics - */ - defaultLabels: MetricLabelsSchema.optional().default({}), - /** - * Aggregation configurations - */ - aggregations: external_exports.array(MetricAggregationConfigSchema).optional().default([]), - /** - * Service Level Indicators - */ - slis: external_exports.array(ServiceLevelIndicatorSchema).optional().default([]), - /** - * Service Level Objectives - */ - slos: external_exports.array(ServiceLevelObjectiveSchema).optional().default([]), - /** - * Export configurations - */ - exports: external_exports.array(MetricExportConfigSchema).optional().default([]), - /** - * Collection interval in seconds - */ - collectionInterval: external_exports.number().int().positive().optional().default(15), - /** - * Retention configuration - */ - retention: external_exports.object({ - /** - * Retention period in seconds - */ - period: external_exports.number().int().positive().optional().default(604800), - // 7 days - /** - * Downsampling configuration - */ - downsampling: external_exports.array(external_exports.object({ - /** - * After this duration, downsample to this resolution - */ - afterSeconds: external_exports.number().int().positive().describe("Downsample after seconds"), - /** - * Resolution in seconds - */ - resolution: external_exports.number().int().positive().describe("Downsampled resolution") - })).optional() - }).optional(), - /** - * Cardinality limits - */ - cardinalityLimits: external_exports.object({ - /** - * Maximum unique label combinations per metric - */ - maxLabelCombinations: external_exports.number().int().positive().optional().default(1e4), - /** - * Action when limit exceeded - */ - onLimitExceeded: external_exports.enum(["drop", "sample", "alert"]).optional().default("alert") - }).optional() -}).describe("Metrics configuration"); -var TraceStateSchema = external_exports.object({ - /** - * Vendor-specific key-value pairs - */ - entries: external_exports.record(external_exports.string(), external_exports.string()).describe("Trace state entries") -}).describe("Trace state"); -var TraceFlagsSchema = external_exports.number().int().min(0).max(255).describe("Trace flags bitmap"); -var TraceContextSchema = external_exports.object({ - /** - * Trace ID (128-bit identifier, 32 hex chars) - */ - traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).describe("Trace ID (32 hex chars)"), - /** - * Span ID (64-bit identifier, 16 hex chars) - */ - spanId: external_exports.string().regex(/^[0-9a-f]{16}$/).describe("Span ID (16 hex chars)"), - /** - * Trace flags (8-bit) - */ - traceFlags: TraceFlagsSchema.optional().default(1), - /** - * Trace state (vendor-specific) - */ - traceState: TraceStateSchema.optional(), - /** - * Parent span ID - */ - parentSpanId: external_exports.string().regex(/^[0-9a-f]{16}$/).optional().describe("Parent span ID (16 hex chars)"), - /** - * Is sampled - */ - sampled: external_exports.boolean().optional().default(true), - /** - * Remote context (from incoming request) - */ - remote: external_exports.boolean().optional().default(false) -}).describe("Trace context (W3C Trace Context)"); -var SpanKind = external_exports.enum([ - "internal", - // Internal operation - "server", - // Server-side request handling - "client", - // Client-side request - "producer", - // Message producer - "consumer" - // Message consumer -]).describe("Span kind"); -var SpanStatus = external_exports.enum([ - "unset", - // Default status - "ok", - // Successful operation - "error" - // Error occurred -]).describe("Span status"); -var SpanAttributeValueSchema = external_exports.union([ - external_exports.string(), - external_exports.number(), - external_exports.boolean(), - external_exports.array(external_exports.string()), - external_exports.array(external_exports.number()), - external_exports.array(external_exports.boolean()) -]).describe("Span attribute value"); -var SpanAttributesSchema = external_exports.record(external_exports.string(), SpanAttributeValueSchema).describe("Span attributes"); -var SpanEventSchema = external_exports.object({ - /** - * Event name - */ - name: external_exports.string().describe("Event name"), - /** - * Event timestamp (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("Event timestamp"), - /** - * Event attributes - */ - attributes: SpanAttributesSchema.optional().describe("Event attributes") -}).describe("Span event"); -var SpanLinkSchema = external_exports.object({ - /** - * Linked trace context - */ - context: TraceContextSchema.describe("Linked trace context"), - /** - * Link attributes - */ - attributes: SpanAttributesSchema.optional().describe("Link attributes") -}).describe("Span link"); -var SpanSchema = external_exports.object({ - /** - * Trace context - */ - context: TraceContextSchema.describe("Trace context"), - /** - * Span name - */ - name: external_exports.string().describe("Span name"), - /** - * Span kind - */ - kind: SpanKind.optional().default("internal"), - /** - * Start time (ISO 8601) - */ - startTime: external_exports.string().datetime().describe("Span start time"), - /** - * End time (ISO 8601) - */ - endTime: external_exports.string().datetime().optional().describe("Span end time"), - /** - * Duration in milliseconds - */ - duration: external_exports.number().nonnegative().optional().describe("Duration in milliseconds"), - /** - * Span status - */ - status: external_exports.object({ - code: SpanStatus.describe("Status code"), - message: external_exports.string().optional().describe("Status message") - }).optional(), - /** - * Span attributes - */ - attributes: SpanAttributesSchema.optional().default({}), - /** - * Span events - */ - events: external_exports.array(SpanEventSchema).optional().default([]), - /** - * Span links - */ - links: external_exports.array(SpanLinkSchema).optional().default([]), - /** - * Resource attributes - */ - resource: SpanAttributesSchema.optional().describe("Resource attributes"), - /** - * Instrumentation library - */ - instrumentationLibrary: external_exports.object({ - name: external_exports.string().describe("Library name"), - version: external_exports.string().optional().describe("Library version") - }).optional() -}).describe("OpenTelemetry span"); -var SamplingDecision = external_exports.enum([ - "drop", - // Do not record or export - "record_only", - // Record but do not export - "record_and_sample" - // Record and export -]).describe("Sampling decision"); -var SamplingStrategyType = external_exports.enum([ - "always_on", - // Always sample - "always_off", - // Never sample - "trace_id_ratio", - // Sample based on trace ID ratio - "rate_limiting", - // Rate-limited sampling - "parent_based", - // Respect parent span sampling decision - "probability", - // Probability-based sampling - "composite", - // Combine multiple strategies - "custom" - // Custom sampling logic -]).describe("Sampling strategy type"); -var TraceSamplingConfigSchema = external_exports.object({ - /** - * Sampling strategy type - */ - type: SamplingStrategyType.describe("Sampling strategy"), - /** - * Sample ratio (0.0 to 1.0) for trace_id_ratio and probability strategies - */ - ratio: external_exports.number().min(0).max(1).optional().describe("Sample ratio (0-1)"), - /** - * Rate limit (traces per second) for rate_limiting strategy - */ - rateLimit: external_exports.number().positive().optional().describe("Traces per second"), - /** - * Parent-based configuration - */ - parentBased: external_exports.object({ - /** - * Sampler to use when parent is sampled - */ - whenParentSampled: SamplingStrategyType.optional().default("always_on"), - /** - * Sampler to use when parent is not sampled - */ - whenParentNotSampled: SamplingStrategyType.optional().default("always_off"), - /** - * Sampler to use when there is no parent (root span) - */ - root: SamplingStrategyType.optional().default("trace_id_ratio"), - /** - * Root sampler ratio - */ - rootRatio: external_exports.number().min(0).max(1).optional().default(0.1) - }).optional(), - /** - * Composite sampling (multiple strategies) - */ - composite: external_exports.array(external_exports.object({ - strategy: SamplingStrategyType.describe("Strategy type"), - ratio: external_exports.number().min(0).max(1).optional(), - condition: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Condition for this strategy") - })).optional(), - /** - * Sampling rules - */ - rules: external_exports.array(external_exports.object({ - /** - * Rule name - */ - name: external_exports.string().describe("Rule name"), - /** - * Match condition - */ - match: external_exports.object({ - /** - * Service name pattern - */ - service: external_exports.string().optional(), - /** - * Span name pattern (regex) - */ - spanName: external_exports.string().optional(), - /** - * Attribute filters - */ - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional(), - /** - * Sampling decision for matching spans - */ - decision: SamplingDecision.describe("Sampling decision"), - /** - * Sample rate for this rule - */ - rate: external_exports.number().min(0).max(1).optional() - })).optional().default([]), - /** - * Custom sampler ID (for custom strategy) - */ - customSamplerId: external_exports.string().optional().describe("Custom sampler identifier") -}).describe("Trace sampling configuration"); -var TracePropagationFormat = external_exports.enum([ - "w3c", - // W3C Trace Context - "b3", - // Zipkin B3 (single header) - "b3_multi", - // Zipkin B3 (multi header) - "jaeger", - // Jaeger propagation - "xray", - // AWS X-Ray - "ottrace", - // OpenTracing - "custom" - // Custom format -]).describe("Trace propagation format"); -var TraceContextPropagationSchema = external_exports.object({ - /** - * Propagation formats (in priority order) - */ - formats: external_exports.array(TracePropagationFormat).optional().default(["w3c"]), - /** - * Extract context from incoming requests - */ - extract: external_exports.boolean().optional().default(true), - /** - * Inject context into outgoing requests - */ - inject: external_exports.boolean().optional().default(true), - /** - * Custom header mappings - */ - headers: external_exports.object({ - /** - * Trace ID header name - */ - traceId: external_exports.string().optional(), - /** - * Span ID header name - */ - spanId: external_exports.string().optional(), - /** - * Trace flags header name - */ - traceFlags: external_exports.string().optional(), - /** - * Trace state header name - */ - traceState: external_exports.string().optional() - }).optional(), - /** - * Baggage propagation - */ - baggage: external_exports.object({ - /** - * Enable baggage propagation - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Maximum baggage size in bytes - */ - maxSize: external_exports.number().int().positive().optional().default(8192), - /** - * Allowed baggage keys (whitelist) - */ - allowedKeys: external_exports.array(external_exports.string()).optional() - }).optional() -}).describe("Trace context propagation"); -var OtelExporterType = external_exports.enum([ - "otlp_http", - // OTLP over HTTP - "otlp_grpc", - // OTLP over gRPC - "jaeger", - // Jaeger - "zipkin", - // Zipkin - "console", - // Console (for debugging) - "datadog", - // Datadog - "honeycomb", - // Honeycomb - "lightstep", - // Lightstep - "newrelic", - // New Relic - "custom" - // Custom exporter -]).describe("OpenTelemetry exporter type"); -var OpenTelemetryCompatibilitySchema = external_exports.object({ - /** - * OpenTelemetry SDK version - */ - sdkVersion: external_exports.string().optional().describe("OTel SDK version"), - /** - * Exporter configuration - */ - exporter: external_exports.object({ - /** - * Exporter type - */ - type: OtelExporterType.describe("Exporter type"), - /** - * Endpoint URL - */ - endpoint: external_exports.string().url().optional().describe("Exporter endpoint"), - /** - * Protocol version - */ - protocol: external_exports.string().optional().describe("Protocol version"), - /** - * Headers - */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP headers"), - /** - * Timeout in milliseconds - */ - timeout: external_exports.number().int().positive().optional().default(1e4), - /** - * Compression - */ - compression: external_exports.enum(["none", "gzip"]).optional().default("none"), - /** - * Batch configuration - */ - batch: external_exports.object({ - /** - * Maximum batch size - */ - maxBatchSize: external_exports.number().int().positive().optional().default(512), - /** - * Maximum queue size - */ - maxQueueSize: external_exports.number().int().positive().optional().default(2048), - /** - * Export timeout in milliseconds - */ - exportTimeout: external_exports.number().int().positive().optional().default(3e4), - /** - * Scheduled delay in milliseconds - */ - scheduledDelay: external_exports.number().int().positive().optional().default(5e3) - }).optional() - }).describe("Exporter configuration"), - /** - * Resource attributes (service identification) - */ - resource: external_exports.object({ - /** - * Service name - */ - serviceName: external_exports.string().describe("Service name"), - /** - * Service version - */ - serviceVersion: external_exports.string().optional().describe("Service version"), - /** - * Service instance ID - */ - serviceInstanceId: external_exports.string().optional().describe("Service instance ID"), - /** - * Service namespace - */ - serviceNamespace: external_exports.string().optional().describe("Service namespace"), - /** - * Deployment environment - */ - deploymentEnvironment: external_exports.string().optional().describe("Deployment environment"), - /** - * Additional resource attributes - */ - attributes: SpanAttributesSchema.optional().describe("Additional resource attributes") - }).describe("Resource attributes"), - /** - * Instrumentation configuration - */ - instrumentation: external_exports.object({ - /** - * Auto-instrumentation enabled - */ - autoInstrumentation: external_exports.boolean().optional().default(true), - /** - * Instrumentation libraries to enable - */ - libraries: external_exports.array(external_exports.string()).optional().describe("Enabled libraries"), - /** - * Instrumentation libraries to disable - */ - disabledLibraries: external_exports.array(external_exports.string()).optional().describe("Disabled libraries") - }).optional(), - /** - * Semantic conventions version - */ - semanticConventionsVersion: external_exports.string().optional().describe("Semantic conventions version") -}).describe("OpenTelemetry compatibility configuration"); -var TracingConfigSchema = external_exports.object({ - /** - * Configuration name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Enable tracing - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Sampling configuration - */ - sampling: TraceSamplingConfigSchema.optional().default({ type: "always_on", rules: [] }), - /** - * Context propagation - */ - propagation: TraceContextPropagationSchema.optional().default({ formats: ["w3c"], extract: true, inject: true }), - /** - * OpenTelemetry configuration - */ - openTelemetry: OpenTelemetryCompatibilitySchema.optional(), - /** - * Span limits - */ - spanLimits: external_exports.object({ - /** - * Maximum number of attributes per span - */ - maxAttributes: external_exports.number().int().positive().optional().default(128), - /** - * Maximum number of events per span - */ - maxEvents: external_exports.number().int().positive().optional().default(128), - /** - * Maximum number of links per span - */ - maxLinks: external_exports.number().int().positive().optional().default(128), - /** - * Maximum attribute value length - */ - maxAttributeValueLength: external_exports.number().int().positive().optional().default(4096) - }).optional(), - /** - * Trace ID generator - */ - traceIdGenerator: external_exports.enum(["random", "uuid", "custom"]).optional().default("random"), - /** - * Custom trace ID generator ID - */ - customTraceIdGeneratorId: external_exports.string().optional().describe("Custom generator identifier"), - /** - * Performance configuration - */ - performance: external_exports.object({ - /** - * Async span export - */ - asyncExport: external_exports.boolean().optional().default(true), - /** - * Background export interval in milliseconds - */ - exportInterval: external_exports.number().int().positive().optional().default(5e3) - }).optional() -}).describe("Tracing configuration"); -var DataClassificationSchema = external_exports.enum([ - "pii", - "phi", - "pci", - "financial", - "confidential", - "internal", - "public" -]).describe("Data classification level"); -var ComplianceFrameworkSchema = external_exports.enum([ - "gdpr", - "hipaa", - "sox", - "pci_dss", - "ccpa", - "iso27001" -]).describe("Compliance framework identifier"); -var ComplianceAuditRequirementSchema = external_exports.object({ - framework: ComplianceFrameworkSchema.describe("Compliance framework identifier"), - requiredEvents: external_exports.array(external_exports.string()).describe('Audit event types required by this framework (e.g., "data.delete", "auth.login")'), - retentionDays: external_exports.number().min(1).describe("Minimum audit log retention period required by this framework (in days)"), - alertOnMissing: external_exports.boolean().default(true).describe("Raise alert if a required audit event is not being captured") -}).describe("Compliance framework audit event requirements"); -var ComplianceEncryptionRequirementSchema = external_exports.object({ - framework: ComplianceFrameworkSchema.describe("Compliance framework identifier"), - dataClassifications: external_exports.array(DataClassificationSchema).describe("Data classifications that must be encrypted under this framework"), - minimumAlgorithm: external_exports.enum(["aes-256-gcm", "aes-256-cbc", "chacha20-poly1305"]).default("aes-256-gcm").describe("Minimum encryption algorithm strength required"), - keyRotationMaxDays: external_exports.number().min(1).default(90).describe("Maximum key rotation interval required (in days)") -}).describe("Compliance framework encryption requirements"); -var MaskingVisibilityRuleSchema = external_exports.object({ - dataClassification: DataClassificationSchema.describe("Data classification this rule applies to"), - defaultMasked: external_exports.boolean().default(true).describe("Whether data is masked by default"), - unmaskRoles: external_exports.array(external_exports.string()).optional().describe("Roles allowed to view unmasked data"), - auditUnmask: external_exports.boolean().default(true).describe("Log an audit event when data is unmasked"), - requireApproval: external_exports.boolean().default(false).describe("Require explicit approval before unmasking"), - approvalRoles: external_exports.array(external_exports.string()).optional().describe("Roles that can approve unmasking requests") -}).describe("Masking visibility and audit rule per data classification"); -var SecurityEventCorrelationSchema = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable cross-subsystem security event correlation"), - correlationId: external_exports.boolean().default(true).describe("Inject a shared correlation ID into audit, encryption, and masking events"), - linkAuthToAudit: external_exports.boolean().default(true).describe("Link authentication events to subsequent data operation audit trails"), - linkEncryptionToAudit: external_exports.boolean().default(true).describe("Log encryption/decryption operations in the audit trail"), - linkMaskingToAudit: external_exports.boolean().default(true).describe("Log masking/unmasking operations in the audit trail") -}).describe("Cross-subsystem security event correlation configuration"); -var DataClassificationPolicySchema = external_exports.object({ - classification: DataClassificationSchema.describe("Data classification level"), - requireEncryption: external_exports.boolean().default(false).describe("Encryption required for this classification"), - requireMasking: external_exports.boolean().default(false).describe("Masking required for this classification"), - requireAudit: external_exports.boolean().default(false).describe("Audit trail required for access to this classification"), - retentionDays: external_exports.number().optional().describe("Data retention limit in days (for compliance)") -}).describe("Security policy for a specific data classification level"); -var SecurityContextConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable unified security context governance"), - complianceAuditRequirements: external_exports.array(ComplianceAuditRequirementSchema).optional().describe("Compliance-driven audit event requirements"), - complianceEncryptionRequirements: external_exports.array(ComplianceEncryptionRequirementSchema).optional().describe("Compliance-driven encryption requirements by data classification"), - maskingVisibility: external_exports.array(MaskingVisibilityRuleSchema).optional().describe("Masking visibility rules per data classification"), - dataClassifications: external_exports.array(DataClassificationPolicySchema).optional().describe("Data classification policies for unified security enforcement"), - eventCorrelation: SecurityEventCorrelationSchema.optional().describe("Cross-subsystem security event correlation settings"), - enforceOnWrite: external_exports.boolean().default(true).describe("Enforce encryption and masking requirements on data write operations"), - enforceOnRead: external_exports.boolean().default(true).describe("Enforce masking and audit requirements on data read operations"), - failOpen: external_exports.boolean().default(false).describe("When false (default), deny access if security context cannot be evaluated") -}).describe("Unified security context governance configuration"); -var ChangeTypeSchema = external_exports.enum([ - "standard", - // Pre-approved, low-risk changes - "normal", - // Requires standard approval process - "emergency", - // Fast-track approval for critical issues - "major" - // Requires CAB (Change Advisory Board) approval -]); -var ChangePrioritySchema = external_exports.enum([ - "critical", - "high", - "medium", - "low" -]); -var ChangeStatusSchema = external_exports.enum([ - "draft", - "submitted", - "in-review", - "approved", - "scheduled", - "in-progress", - "completed", - "failed", - "rolled-back", - "cancelled" -]); -var ChangeImpactSchema = external_exports.object({ - /** - * Overall impact level of the change - */ - level: external_exports.enum(["low", "medium", "high", "critical"]).describe("Impact level"), - /** - * List of systems affected by this change - */ - affectedSystems: external_exports.array(external_exports.string()).describe("Affected systems"), - /** - * Estimated number of users affected - */ - affectedUsers: external_exports.number().optional().describe("Affected user count"), - /** - * Downtime requirements - */ - downtime: external_exports.object({ - /** - * Whether downtime is required - */ - required: external_exports.boolean().describe("Downtime required"), - /** - * Duration of downtime in minutes - */ - durationMinutes: external_exports.number().optional().describe("Downtime duration") - }).optional().describe("Downtime information") -}); -var RollbackPlanSchema = external_exports.object({ - /** - * High-level description of the rollback approach - */ - description: external_exports.string().describe("Rollback description"), - /** - * Sequential steps to execute rollback - */ - steps: external_exports.array(external_exports.object({ - /** - * Step execution order - */ - order: external_exports.number().describe("Step order"), - /** - * Detailed description of this step - */ - description: external_exports.string().describe("Step description"), - /** - * Estimated time to complete this step - */ - estimatedMinutes: external_exports.number().describe("Estimated duration") - })).describe("Rollback steps"), - /** - * Testing procedure to verify successful rollback - */ - testProcedure: external_exports.string().optional().describe("Test procedure") -}); -var ChangeRequestSchema = external_exports.object({ - /** - * Unique change request identifier - */ - id: external_exports.string().describe("Change request ID"), - /** - * Short descriptive title of the change - */ - title: external_exports.string().describe("Change title"), - /** - * Detailed description of the change and its purpose - */ - description: external_exports.string().describe("Change description"), - /** - * Change classification type - */ - type: ChangeTypeSchema.describe("Change type"), - /** - * Priority level for processing - */ - priority: ChangePrioritySchema.describe("Change priority"), - /** - * Current status in the change lifecycle - */ - status: ChangeStatusSchema.describe("Change status"), - /** - * User ID of the change requester - */ - requestedBy: external_exports.string().describe("Requester user ID"), - /** - * Timestamp when change was requested (Unix milliseconds) - */ - requestedAt: external_exports.number().describe("Request timestamp"), - /** - * Impact assessment of the change - */ - impact: ChangeImpactSchema.describe("Impact assessment"), - /** - * Implementation plan and procedures - */ - implementation: external_exports.object({ - /** - * High-level implementation description - */ - description: external_exports.string().describe("Implementation description"), - /** - * Sequential implementation steps - */ - steps: external_exports.array(external_exports.object({ - /** - * Step execution order - */ - order: external_exports.number().describe("Step order"), - /** - * Detailed description of this step - */ - description: external_exports.string().describe("Step description"), - /** - * Estimated time to complete this step - */ - estimatedMinutes: external_exports.number().describe("Estimated duration") - })).describe("Implementation steps"), - /** - * Testing procedures to verify successful implementation - */ - testing: external_exports.string().optional().describe("Testing procedure") - }).describe("Implementation plan"), - /** - * Rollback plan in case of failure - */ - rollbackPlan: RollbackPlanSchema.describe("Rollback plan"), - /** - * Change schedule and timing - */ - schedule: external_exports.object({ - /** - * Planned start time (Unix milliseconds) - */ - plannedStart: external_exports.number().describe("Planned start time"), - /** - * Planned end time (Unix milliseconds) - */ - plannedEnd: external_exports.number().describe("Planned end time"), - /** - * Actual start time (Unix milliseconds) - */ - actualStart: external_exports.number().optional().describe("Actual start time"), - /** - * Actual end time (Unix milliseconds) - */ - actualEnd: external_exports.number().optional().describe("Actual end time") - }).optional().describe("Schedule"), - /** - * Security impact assessment for the change (A.8.32) - */ - securityImpact: external_exports.object({ - /** - * Whether a security impact assessment has been performed - */ - assessed: external_exports.boolean().describe("Whether security impact has been assessed"), - /** - * Security risk level of this change - */ - riskLevel: external_exports.enum(["none", "low", "medium", "high", "critical"]).optional().describe("Security risk level"), - /** - * Data classifications affected by this change - */ - affectedDataClassifications: external_exports.array(DataClassificationSchema).optional().describe("Affected data classifications"), - /** - * Whether the change requires security team approval - */ - requiresSecurityApproval: external_exports.boolean().default(false).describe("Whether security team approval is required"), - /** - * Security reviewer user ID - */ - reviewedBy: external_exports.string().optional().describe("Security reviewer user ID"), - /** - * Security review completion timestamp (Unix milliseconds) - */ - reviewedAt: external_exports.number().optional().describe("Security review timestamp"), - /** - * Security review notes or conditions - */ - reviewNotes: external_exports.string().optional().describe("Security review notes or conditions") - }).optional().describe("Security impact assessment per ISO 27001:2022 A.8.32"), - /** - * Approval workflow configuration - */ - approval: external_exports.object({ - /** - * Whether approval is required for this change - */ - required: external_exports.boolean().describe("Approval required"), - /** - * List of approvers and their approval status - */ - approvers: external_exports.array(external_exports.object({ - /** - * Approver user ID - */ - userId: external_exports.string().describe("Approver user ID"), - /** - * Timestamp when approval was granted (Unix milliseconds) - */ - approvedAt: external_exports.number().optional().describe("Approval timestamp"), - /** - * Comments from the approver - */ - comments: external_exports.string().optional().describe("Approver comments") - })).describe("Approvers") - }).optional().describe("Approval workflow"), - /** - * Supporting documentation and files - */ - attachments: external_exports.array(external_exports.object({ - /** - * Attachment file name - */ - name: external_exports.string().describe("Attachment name"), - /** - * URL to download the attachment - */ - url: external_exports.string().url().describe("Attachment URL") - })).optional().describe("Attachments"), - /** - * Custom metadata key-value pairs for extensibility - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") -}); -var EncryptionAlgorithmSchema = external_exports.enum([ - "aes-256-gcm", - "aes-256-cbc", - "chacha20-poly1305" -]).describe("Supported encryption algorithm"); -var KeyManagementProviderSchema = external_exports.enum([ - "local", - "aws-kms", - "azure-key-vault", - "gcp-kms", - "hashicorp-vault" -]).describe("Key management service provider"); -var KeyRotationPolicySchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), - frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), - retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), - autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") -}).describe("Policy for automatic encryption key rotation"); -var EncryptionConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), - algorithm: EncryptionAlgorithmSchema.default("aes-256-gcm").describe("Encryption algorithm"), - keyManagement: external_exports.object({ - provider: KeyManagementProviderSchema.describe("Key management service provider"), - keyId: external_exports.string().optional().describe("Key identifier in the provider"), - rotationPolicy: KeyRotationPolicySchema.optional().describe("Key rotation policy") - }).describe("Key management configuration"), - scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), - deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), - searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") -}).describe("Field-level encryption configuration"); -var FieldEncryptionSchema = external_exports.object({ - fieldName: external_exports.string().describe("Name of the field to encrypt"), - encryptionConfig: EncryptionConfigSchema.describe("Encryption settings for this field"), - indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") -}).describe("Per-field encryption assignment"); -var MaskingStrategySchema = external_exports.enum([ - "redact", - // Complete redaction: **** - "partial", - // Partial masking: 138****5678 - "hash", - // Hash value: sha256(value) - "tokenize", - // Tokenization: token-12345 - "randomize", - // Randomize: generate random value - "nullify", - // Null value: null - "substitute" - // Substitute with dummy data -]).describe("Data masking strategy for PII protection"); -var MaskingRuleSchema = external_exports.object({ - field: external_exports.string().describe("Field name to apply masking to"), - strategy: MaskingStrategySchema.describe("Masking strategy to use"), - pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), - preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), - preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), - roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), - exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") -}).describe("Masking rule for a single field"); -var MaskingConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable data masking"), - rules: external_exports.array(MaskingRuleSchema).describe("List of field-level masking rules"), - auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") -}).describe("Top-level data masking configuration for PII protection"); -var FieldType = external_exports.enum([ - // Core Text - "text", - "textarea", - "email", - "url", - "phone", - "password", - // Rich Content - "markdown", - "html", - "richtext", - // Numbers - "number", - "currency", - "percent", - // Date & Time - "date", - "datetime", - "time", - // Logic - "boolean", - "toggle", - // Toggle is a distinct UI from checkbox - // Selection - "select", - // Single select dropdown - "multiselect", - // Multi select (often tags) - "radio", - // Radio group - "checkboxes", - // Checkbox group - // Relational - "lookup", - "master_detail", - // Dynamic reference - "tree", - // Hierarchical reference - // Media - "image", - "file", - "avatar", - "video", - "audio", - // Calculated / System - "formula", - "summary", - "autonumber", - // Enhanced Types - "location", - // GPS coordinates - "address", - // Structured address - "code", - // Code editor (JSON/SQL/JS) - "json", - // Structured JSON data - "color", - // Color picker - "rating", - // Star rating - "slider", - // Numeric slider - "signature", - // Digital signature - "qrcode", - // QR code / Barcode - "progress", - // Progress bar - "tags", - // Simple tag list - // AI/ML Types - "vector" - // Vector embeddings for AI/ML (semantic search, RAG) -]); -var SelectOptionSchema = external_exports.object({ - label: external_exports.string().describe("Display label (human-readable, any case allowed)"), - value: SystemIdentifierSchema.describe("Stored value (lowercase machine identifier)"), - color: external_exports.string().optional().describe("Color code for badges/charts"), - default: external_exports.boolean().optional().describe("Is default option") -}); -external_exports.object({ - latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), - longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), - altitude: external_exports.number().optional().describe("Altitude in meters"), - accuracy: external_exports.number().optional().describe("Accuracy in meters") -}); -var CurrencyConfigSchema = external_exports.object({ - precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), - currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), - defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") -}); -external_exports.object({ - value: external_exports.number().describe("Monetary amount"), - currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") -}); -external_exports.object({ - street: external_exports.string().optional().describe("Street address"), - city: external_exports.string().optional().describe("City name"), - state: external_exports.string().optional().describe("State/Province"), - postalCode: external_exports.string().optional().describe("Postal/ZIP code"), - country: external_exports.string().optional().describe("Country name or code"), - countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), - formatted: external_exports.string().optional().describe("Formatted address string") -}); -var VectorConfigSchema = external_exports.object({ - dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), - distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), - normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), - indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), - indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") -}); -var FileAttachmentConfigSchema = external_exports.object({ - /** File Size Limits */ - minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), - maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), - /** File Type Restrictions */ - allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), - blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), - allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), - blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), - /** Virus Scanning */ - virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), - virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), - virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), - quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), - /** Storage Configuration */ - storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), - storageBucket: external_exports.string().optional().describe("Target bucket name"), - storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), - /** Image-Specific Validation */ - imageValidation: external_exports.object({ - minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), - maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), - minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), - maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), - aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), - generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), - thumbnailSizes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), - width: external_exports.number().min(1).describe("Thumbnail width in pixels"), - height: external_exports.number().min(1).describe("Thumbnail height in pixels"), - crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") - })).optional().describe("Thumbnail size configurations"), - preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), - autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") - }).optional().describe("Image-specific validation rules"), - /** Upload Behavior */ - allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), - allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), - allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), - requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), - /** Metadata Extraction */ - extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), - extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), - /** Versioning */ - versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), - maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), - /** Access Control */ - publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), - presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") -}).refine((data) => { - if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { - return false; - } - return true; -}, { - message: "minSize must be less than or equal to maxSize" -}).refine((data) => { - if (data.virusScanProvider !== void 0 && data.virusScan !== true) { - return false; - } - return true; -}, { - message: "virusScanProvider requires virusScan to be enabled" -}); -var DataQualityRulesSchema = external_exports.object({ - /** Enforce uniqueness constraint */ - uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), - /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ - completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), - /** Accuracy validation against authoritative source */ - accuracy: external_exports.object({ - source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), - threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") - }).optional().describe("Accuracy validation configuration") -}); -var ComputedFieldCacheSchema = external_exports.object({ - /** Enable caching for this computed field */ - enabled: external_exports.boolean().describe("Enable caching for computed field results"), - /** Time-to-live in seconds */ - ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), - /** Array of field paths that trigger cache invalidation when changed */ - invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') -}); -var FieldSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), - label: external_exports.string().optional().describe("Human readable label"), - type: FieldType.describe("Field Data Type"), - description: external_exports.string().optional().describe("Tooltip/Help text"), - format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), - /** Storage Layer Mapping */ - columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), - /** Database Constraints */ - required: external_exports.boolean().default(false).describe("Is required"), - searchable: external_exports.boolean().default(false).describe("Is searchable"), - multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), - unique: external_exports.boolean().default(false).describe("Is unique constraint"), - defaultValue: external_exports.unknown().optional().describe("Default value"), - /** Text/String Constraints */ - maxLength: external_exports.number().optional().describe("Max character length"), - minLength: external_exports.number().optional().describe("Min character length"), - /** Number Constraints */ - precision: external_exports.number().optional().describe("Total digits"), - scale: external_exports.number().optional().describe("Decimal places"), - min: external_exports.number().optional().describe("Minimum value"), - max: external_exports.number().optional().describe("Maximum value"), - /** Selection Options */ - options: external_exports.array(SelectOptionSchema).optional().describe("Static options for select/multiselect"), - /** - * Relationship Config - * - * Used by `lookup` and `master_detail` field types to define cross-object references. - * The `reference` property is **required** for these types — it identifies the target - * object whose records this field links to. The engine uses `reference` during $expand - * post-processing to resolve foreign key IDs into full related objects via batch queries. - * - * For `master_detail` fields, the parent record controls the lifecycle of child records - * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. - */ - reference: external_exports.string().optional().describe( - "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." - ), - referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), - writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), - deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), - /** Calculation */ - expression: external_exports.string().optional().describe("Formula expression"), - summaryOperations: external_exports.object({ - object: external_exports.string().describe("Source child object name for roll-up"), - field: external_exports.string().describe("Field on child object to aggregate"), - function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") - }).optional().describe("Roll-up summary definition"), - /** Enhanced Field Type Configurations */ - // Code field config - language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), - theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), - lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), - // Rating field config - maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), - allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), - // Location field config - displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), - allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), - // Address field config - addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), - // Color field config - colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), - allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), - presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), - // Slider field config - step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), - showValue: external_exports.boolean().optional().describe("Display current value on slider"), - marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), - // QR Code / Barcode field config - // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' - // Runtime validation should enforce this constraint - barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), - qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), - displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), - allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), - // Currency field config - currencyConfig: CurrencyConfigSchema.optional().describe("Configuration for currency field type"), - // Vector field config - vectorConfig: VectorConfigSchema.optional().describe("Configuration for vector field type (AI/ML embeddings)"), - // File attachment field config - fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe("Configuration for file and attachment field types"), - /** Enhanced Security & Compliance */ - // Encryption configuration - encryptionConfig: EncryptionConfigSchema.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), - // Data masking rules - maskingRule: MaskingRuleSchema.optional().describe("Data masking rules for PII protection"), - // Audit trail - auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), - /** Field Dependencies & Relationships */ - // Field dependencies - dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), - /** Computed Field Optimization */ - // Computed field caching - cached: ComputedFieldCacheSchema.optional().describe("Caching configuration for computed/formula fields"), - /** Data Quality & Governance */ - // Data quality rules - dataQuality: DataQualityRulesSchema.optional().describe("Data quality validation and monitoring rules"), - /** Layout & Grouping */ - group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), - /** Conditional Requirements */ - conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), - /** Security & Visibility */ - hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), - readonly: external_exports.boolean().default(false).describe("Read-only in UI"), - sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), - inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), - trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), - caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), - autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), - /** Indexing */ - index: external_exports.boolean().default(false).describe("Create standard database index"), - externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") -}); -var BaseValidationSchema = external_exports.object({ - // Identification - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label for the rule listing"), - description: external_exports.string().optional().describe("Administrative notes explaining the business reason"), - // Execution Control - active: external_exports.boolean().default(true), - events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).default(["insert", "update"]).describe("Validation contexts"), - priority: external_exports.number().int().min(0).max(9999).default(100).describe("Execution priority (lower runs first, default: 100)"), - // Classification - tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g., "compliance", "billing")'), - // Feedback - severity: external_exports.enum(["error", "warning", "info"]).default("error"), - message: external_exports.string().describe("Error message to display to the user") -}); -var ScriptValidationSchema = BaseValidationSchema.extend({ - type: external_exports.literal("script"), - condition: external_exports.string().describe("Formula expression. If TRUE, validation fails. (e.g. amount < 0)") -}); -var UniquenessValidationSchema = BaseValidationSchema.extend({ - type: external_exports.literal("unique"), - fields: external_exports.array(external_exports.string()).describe("Fields that must be combined unique"), - scope: external_exports.string().optional().describe("Formula condition for scope (e.g. active = true)"), - caseSensitive: external_exports.boolean().default(true) -}); -var StateMachineValidationSchema = BaseValidationSchema.extend({ - type: external_exports.literal("state_machine"), - field: external_exports.string().describe("State field (e.g. status)"), - transitions: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).describe("Map of { OldState: [AllowedNewStates] }") -}); -var FormatValidationSchema = BaseValidationSchema.extend({ - type: external_exports.literal("format"), - field: external_exports.string(), - regex: external_exports.string().optional(), - format: external_exports.enum(["email", "url", "phone", "json"]).optional() -}); -var CrossFieldValidationSchema = BaseValidationSchema.extend({ - type: external_exports.literal("cross_field"), - condition: external_exports.string().describe('Formula expression comparing fields (e.g. "end_date > start_date")'), - fields: external_exports.array(external_exports.string()).describe("Fields involved in the validation") -}); -var JSONValidationSchema = BaseValidationSchema.extend({ - type: external_exports.literal("json_schema"), - field: external_exports.string().describe("JSON field to validate"), - schema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema object definition") -}); -var AsyncValidationSchema = BaseValidationSchema.extend({ - type: external_exports.literal("async"), - field: external_exports.string().describe("Field to validate"), - validatorUrl: external_exports.string().optional().describe("External API endpoint for validation"), - method: external_exports.enum(["GET", "POST"]).default("GET").describe("HTTP method for external call"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for the request"), - validatorFunction: external_exports.string().optional().describe("Reference to custom validator function"), - timeout: external_exports.number().optional().default(5e3).describe("Timeout in milliseconds"), - debounce: external_exports.number().optional().describe("Debounce delay in milliseconds"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional parameters to pass to validator") -}); -var CustomValidatorSchema = BaseValidationSchema.extend({ - type: external_exports.literal("custom"), - handler: external_exports.string().describe("Name of the custom validation function registered in the system"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the custom handler") -}); -var ValidationRuleSchema = external_exports.lazy( - () => external_exports.discriminatedUnion("type", [ - ScriptValidationSchema, - UniquenessValidationSchema, - StateMachineValidationSchema, - FormatValidationSchema, - CrossFieldValidationSchema, - JSONValidationSchema, - AsyncValidationSchema, - CustomValidatorSchema, - ConditionalValidationSchema - ]) -); -var ConditionalValidationSchema = BaseValidationSchema.extend({ - type: external_exports.literal("conditional"), - when: external_exports.string().describe(`Condition formula (e.g. "type = 'enterprise'")`), - then: ValidationRuleSchema.describe("Validation rule to apply when condition is true"), - otherwise: ValidationRuleSchema.optional().describe("Validation rule to apply when condition is false") -}); -var ActionRefSchema = external_exports.union([ - external_exports.string().describe("Action Name"), - external_exports.object({ - type: external_exports.string(), - // e.g., 'xstate.assign', 'log', 'email' - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }) -]); -var GuardRefSchema = external_exports.union([ - external_exports.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'), - external_exports.object({ - type: external_exports.string(), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }) -]); -var TransitionSchema = external_exports.object({ - target: external_exports.string().optional().describe("Target State ID"), - cond: GuardRefSchema.optional().describe("Condition (Guard) required to take this path"), - actions: external_exports.array(ActionRefSchema).optional().describe("Actions to execute during transition"), - description: external_exports.string().optional().describe("Human readable description of this rule") -}); -external_exports.object({ - type: external_exports.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'), - // Payload validation schema could go here if we want deep validation - schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Expected event payload structure") -}); -var StateNodeSchema = external_exports.lazy(() => external_exports.object({ - /** Type of state */ - type: external_exports.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"), - /** Entry/Exit Actions */ - entry: external_exports.array(ActionRefSchema).optional().describe("Actions to run when entering this state"), - exit: external_exports.array(ActionRefSchema).optional().describe("Actions to run when leaving this state"), - /** Transitions (Events) */ - on: external_exports.record(external_exports.string(), external_exports.union([ - external_exports.string(), - // Shorthand target - TransitionSchema, - external_exports.array(TransitionSchema) - ])).optional().describe("Map of Event Type -> Transition Definition"), - /** Always Transitions (Eventless) */ - always: external_exports.array(TransitionSchema).optional(), - /** Nesting (Hierarchical States) */ - initial: external_exports.string().optional().describe("Initial child state (if compound)"), - states: external_exports.record(external_exports.string(), StateNodeSchema).optional(), - /** Metadata for UI/AI */ - meta: external_exports.object({ - label: external_exports.string().optional(), - description: external_exports.string().optional(), - color: external_exports.string().optional(), - // For UI diagrams - // Instructions for AI Agent when in this state - aiInstructions: external_exports.string().optional().describe("Specific instructions for AI when in this state") - }).optional() -})); -var StateMachineSchema = external_exports.object({ - id: SnakeCaseIdentifierSchema.describe("Unique Machine ID"), - description: external_exports.string().optional(), - /** Context (Memory) Schema */ - contextSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Zod Schema for the machine context/memory"), - /** Initial State */ - initial: external_exports.string().describe("Initial State ID"), - /** State Definitions */ - states: external_exports.record(external_exports.string(), StateNodeSchema).describe("State Nodes"), - /** Global Listeners */ - on: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), TransitionSchema, external_exports.array(TransitionSchema)])).optional() -}); -external_exports.object({ - /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ - key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), - /** Default value when translation is not available */ - defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), - /** Interpolation parameters for dynamic translations */ - params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") -}); -var I18nLabelSchema = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); -var AriaPropsSchema = external_exports.object({ - /** Accessible label for screen readers */ - ariaLabel: I18nLabelSchema.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), - /** ID of element that describes this component */ - ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), - /** WAI-ARIA role override */ - role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') -}).describe("ARIA accessibility attributes"); -external_exports.object({ - /** Translation key for the plural form */ - key: external_exports.string().describe("Translation key"), - /** Form for zero quantity */ - zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), - /** Form for singular (1) */ - one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), - /** Form for dual (2) — used in Arabic, Welsh, etc. */ - two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), - /** Form for few (2-4 in Slavic languages) */ - few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), - /** Form for many (5+ in Slavic languages) */ - many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), - /** Default/fallback form */ - other: external_exports.string().describe('Default plural form (e.g., "{count} items")') -}).describe("ICU plural rules for a translation key"); -var NumberFormatSchema = external_exports.object({ - style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), - currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), - unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), - minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), - maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), - useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") -}).describe("Number formatting rules"); -var DateFormatSchema = external_exports.object({ - dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), - timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), - timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), - hour12: external_exports.boolean().optional().describe("Use 12-hour format") -}).describe("Date/time formatting rules"); -external_exports.object({ - /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ - code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), - /** Ordered fallback chain for missing translations */ - fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), - /** Text direction */ - direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), - /** Default number formatting */ - numberFormat: NumberFormatSchema.optional().describe("Default number formatting rules"), - /** Default date formatting */ - dateFormat: DateFormatSchema.optional().describe("Default date/time formatting rules") -}).describe("Locale configuration"); -var ActionParamSchema = external_exports.object({ - name: external_exports.string(), - label: I18nLabelSchema, - type: FieldType, - required: external_exports.boolean().default(false), - options: external_exports.array(external_exports.object({ label: I18nLabelSchema, value: external_exports.string() })).optional() -}); -var ActionType = external_exports.enum(["script", "url", "modal", "flow", "api"]); -var TARGET_REQUIRED_TYPES = new Set( - ActionType.options.filter((t) => t !== "script") -); -var ActionSchema = external_exports.object({ - /** Machine name of the action */ - name: SnakeCaseIdentifierSchema.describe("Machine name (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema.describe("Display label"), - /** Target object this action belongs to (optional, snake_case) */ - objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Icon name"), - /** Where does this action appear? */ - locations: external_exports.array(external_exports.enum([ - "list_toolbar", - "list_item", - "record_header", - "record_more", - "record_related", - "global_nav" - ])).optional().describe("Locations where this action is visible"), - /** - * Visual Component Type - * Defaults to 'button' or 'menu_item' based on location, - * but can be overridden. - */ - component: external_exports.enum([ - "action:button", - // Standard Button - "action:icon", - // Icon only - "action:menu", - // Dropdown menu - "action:group" - // Button Group - ]).optional().describe("Visual component override"), - /** What type of interaction? */ - type: ActionType.default("script").describe("Action functionality type"), - /** - * Payload / Target — the canonical binding for the action handler. - * Required for url, flow, modal, and api types. - * Recommended for script type. - */ - target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), - /** - * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. - */ - execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), - /** User Input Requirements */ - params: external_exports.array(ActionParamSchema).optional().describe("Input parameters required from user"), - /** Visual Style */ - variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), - /** UX Behavior */ - confirmText: I18nLabelSchema.optional().describe("Confirmation message before execution"), - successMessage: I18nLabelSchema.optional().describe("Success message to show after execution"), - refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), - /** Access */ - visible: external_exports.string().optional().describe("Formula returning boolean"), - disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), - /** Keyboard Shortcut */ - shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), - /** Bulk Operations */ - bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), - /** Execution */ - timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema.optional().describe("ARIA accessibility attributes") -}).transform((data) => { - if (data.execute && !data.target) { - return { ...data, target: data.execute }; - } - return data; -}).refine((data) => { - if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) { - return false; - } - return true; -}, { - message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", - path: ["target"] -}); -var ApiMethod = external_exports.enum([ - "get", - "list", - // Read - "create", - "update", - "delete", - // Write - "upsert", - // Idempotent Write - "bulk", - // Batch operations - "aggregate", - // Analytics (count, sum) - "history", - // Audit access - "search", - // Search access - "restore", - "purge", - // Trash management - "import", - "export" - // Data portability -]); -var ObjectCapabilities = external_exports.object({ - /** Enable history tracking (Audit Trail) */ - trackHistory: external_exports.boolean().default(false).describe("Enable field history tracking for audit compliance"), - /** Enable global search indexing */ - searchable: external_exports.boolean().default(true).describe("Index records for global search"), - /** Enable REST/GraphQL API access */ - apiEnabled: external_exports.boolean().default(true).describe("Expose object via automatic APIs"), - /** - * API Supported Operations - * Granular control over API exposure. - */ - apiMethods: external_exports.array(ApiMethod).optional().describe("Whitelist of allowed API operations"), - /** Enable standard attachments/files engine */ - files: external_exports.boolean().default(false).describe("Enable file attachments and document management"), - /** Enable social collaboration (Comments, Mentions, Feeds) */ - feeds: external_exports.boolean().default(false).describe("Enable social feed, comments, and mentions (Chatter-like)"), - /** Enable standard Activity suite (Tasks, Calendars, Events) */ - activities: external_exports.boolean().default(false).describe("Enable standard tasks and events tracking"), - /** Enable Recycle Bin / Soft Delete */ - trash: external_exports.boolean().default(true).describe("Enable soft-delete with restore capability"), - /** Enable "Recently Viewed" tracking */ - mru: external_exports.boolean().default(true).describe("Track Most Recently Used (MRU) list for users"), - /** Allow cloning records */ - clone: external_exports.boolean().default(true).describe("Allow record deep cloning") -}); -var IndexSchema = external_exports.object({ - name: external_exports.string().optional().describe("Index name (auto-generated if not provided)"), - fields: external_exports.array(external_exports.string()).describe("Fields included in the index"), - type: external_exports.enum(["btree", "hash", "gin", "gist", "fulltext"]).optional().default("btree").describe("Index algorithm type"), - unique: external_exports.boolean().optional().default(false).describe("Whether the index enforces uniqueness"), - partial: external_exports.string().optional().describe("Partial index condition (SQL WHERE clause for conditional indexes)") -}); -var SearchConfigSchema2 = external_exports.object({ - fields: external_exports.array(external_exports.string()).describe("Fields to index for full-text search weighting"), - displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display in search result cards"), - filters: external_exports.array(external_exports.string()).optional().describe("Default filters for search results") -}); -var TenancyConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable multi-tenancy for this object"), - strategy: external_exports.enum(["shared", "isolated", "hybrid"]).describe("Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)"), - tenantField: external_exports.string().default("tenant_id").describe("Field name for tenant identifier"), - crossTenantAccess: external_exports.boolean().default(false).describe("Allow cross-tenant data access (with explicit permission)") -}); -var SoftDeleteConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable soft delete (trash/recycle bin)"), - field: external_exports.string().default("deleted_at").describe("Field name for soft delete timestamp"), - cascadeDelete: external_exports.boolean().default(false).describe("Cascade soft delete to related records") -}); -var VersioningConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable record versioning"), - strategy: external_exports.enum(["snapshot", "delta", "event-sourcing"]).describe("Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)"), - retentionDays: external_exports.number().min(1).optional().describe("Number of days to retain old versions (undefined = infinite)"), - versionField: external_exports.string().default("version").describe("Field name for version number/timestamp") -}); -var PartitioningConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable table partitioning"), - strategy: external_exports.enum(["range", "hash", "list"]).describe("Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)"), - key: external_exports.string().describe("Field name to partition by"), - interval: external_exports.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")') -}).refine((data) => { - if (data.strategy === "range" && !data.interval) { - return false; - } - return true; -}, { - message: 'interval is required when strategy is "range"' -}); -var CDCConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable Change Data Capture"), - events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).describe("Event types to capture"), - destination: external_exports.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")') -}); -var ObjectSchemaBase = external_exports.object({ - /** - * Identity & Metadata - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine unique key (snake_case). Immutable."), - label: external_exports.string().optional().describe('Human readable singular label (e.g. "Account")'), - pluralLabel: external_exports.string().optional().describe('Human readable plural label (e.g. "Accounts")'), - description: external_exports.string().optional().describe("Developer documentation / description"), - icon: external_exports.string().optional().describe("Icon name (Lucide/Material) for UI representation"), - /** - * Namespace & Domain Classification - * - * Groups objects into logical domains for routing, permissions, and discovery. - * System objects use `'sys'`; business packages use their own namespace. - * - * When set, `tableName` is auto-derived as `{namespace}_{name}` by - * `ObjectSchema.create()` unless an explicit `tableName` is provided. - * - * Namespace must be a single lowercase word (no underscores or hyphens) - * to ensure clean auto-derivation of `{namespace}_{name}` table names. - * - * @example namespace: 'sys' → tableName defaults to 'sys_user' - * @example namespace: 'crm' → tableName defaults to 'crm_account' - */ - namespace: external_exports.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace \u2014 single lowercase word (e.g. "sys", "crm"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'), - /** - * Taxonomy & Organization - */ - tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'), - active: external_exports.boolean().optional().default(true).describe("Is the object active and usable"), - isSystem: external_exports.boolean().optional().default(false).describe("Is system object (protected from deletion)"), - abstract: external_exports.boolean().optional().default(false).describe("Is abstract base object (cannot be instantiated)"), - /** - * Storage & Virtualization - */ - datasource: external_exports.string().optional().default("default").describe('Target Datasource ID. "default" is the primary DB.'), - tableName: external_exports.string().optional().describe("Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set."), - /** - * Data Model - */ - fields: external_exports.record(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/, { - message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")' - }), FieldSchema).describe("Field definitions map. Keys must be snake_case identifiers."), - indexes: external_exports.array(IndexSchema).optional().describe("Database performance indexes"), - /** - * Advanced Data Management - */ - // Multi-tenancy configuration - tenancy: TenancyConfigSchema.optional().describe("Multi-tenancy configuration for SaaS applications"), - // Soft delete configuration - softDelete: SoftDeleteConfigSchema.optional().describe("Soft delete (trash/recycle bin) configuration"), - // Versioning configuration - versioning: VersioningConfigSchema.optional().describe("Record versioning and history tracking configuration"), - // Partitioning strategy - partitioning: PartitioningConfigSchema.optional().describe("Table partitioning configuration for performance"), - // Change Data Capture - cdc: CDCConfigSchema.optional().describe("Change Data Capture (CDC) configuration for real-time data streaming"), - /** - * Logic & Validation (Co-located) - * Best Practice: Define rules close to data. - */ - validations: external_exports.array(ValidationRuleSchema).optional().describe("Object-level validation rules"), - /** - * State Machine(s) - * Named record of state machines, where each key is a unique machine identifier. - * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status). - * - * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} } - */ - stateMachines: external_exports.record(external_exports.string(), StateMachineSchema).optional().describe("Named state machines for parallel lifecycles (e.g., status, payment, approval)"), - /** - * Display & UI Hints (Data-Layer) - */ - displayNameField: external_exports.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'), - recordName: external_exports.object({ - type: external_exports.enum(["text", "autonumber"]).describe("Record name type: text (user-entered) or autonumber (system-generated)"), - displayFormat: external_exports.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'), - startNumber: external_exports.number().int().min(0).optional().describe("Starting number for autonumber (default: 1)") - }).optional().describe("Record name generation configuration (Salesforce pattern)"), - titleFormat: external_exports.string().optional().describe('Title expression (e.g. "{name} - {code}"). Overrides displayNameField.'), - compactLayout: external_exports.array(external_exports.string()).optional().describe("Primary fields for hover/cards/lookups"), - /** - * Search Engine Config - */ - search: SearchConfigSchema2.optional().describe("Search engine configuration"), - /** - * System Capabilities - */ - enable: ObjectCapabilities.optional().describe("Enabled system features modules"), - /** Record Types */ - recordTypes: external_exports.array(external_exports.string()).optional().describe("Record type names for this object"), - /** Sharing Model */ - sharingModel: external_exports.enum(["private", "read", "read_write", "full"]).optional().describe("Default sharing model"), - /** Key Prefix */ - keyPrefix: external_exports.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'), - /** - * Object Actions - * - * Actions associated with this object. Populated automatically by `defineStack()` - * when top-level actions specify `objectName` matching this object. - * Can also be defined directly on the object. - * - * Aligns with Salesforce/ServiceNow patterns where actions are part of the - * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`) - * include the action list without requiring downstream merge. - */ - actions: external_exports.array(ActionSchema).optional().describe("Actions associated with this object (auto-populated from top-level actions via objectName)") -}); -function snakeCaseToLabel(name) { - return name.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); -} -var ObjectSchema = Object.assign(ObjectSchemaBase, { - /** - * Type-safe factory for creating business object definitions. - * - * Enhancements over raw schema: - * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case). - * - **Validation**: Runs Zod `.parse()` to validate the config at creation time. - * - * @example - * ```ts - * const Task = ObjectSchema.create({ - * name: 'project_task', - * // label auto-generated as 'Project Task' - * fields: { - * subject: { type: 'text', label: 'Subject', required: true }, - * }, - * }); - * ``` - */ - create: (config4) => { - const withDefaults = { - ...config4, - label: config4.label ?? snakeCaseToLabel(config4.name), - // Auto-derive tableName as {namespace}_{name} when namespace is set - tableName: config4.tableName ?? (config4.namespace ? `${config4.namespace}_${config4.name}` : void 0) - }; - return ObjectSchemaBase.parse(withDefaults); - } -}); -external_exports.enum(["own", "extend"]); -external_exports.object({ - /** The target object name (FQN) to extend */ - extend: external_exports.string().describe("Target object name (FQN) to extend"), - /** Fields to merge into the target object (additive) */ - fields: external_exports.record(external_exports.string(), FieldSchema).optional().describe("Fields to add/override"), - /** Override label */ - label: external_exports.string().optional().describe("Override label for the extended object"), - /** Override plural label */ - pluralLabel: external_exports.string().optional().describe("Override plural label for the extended object"), - /** Override description */ - description: external_exports.string().optional().describe("Override description for the extended object"), - /** Additional validation rules to add */ - validations: external_exports.array(ValidationRuleSchema).optional().describe("Additional validation rules to merge into the target object"), - /** Additional indexes to add */ - indexes: external_exports.array(IndexSchema).optional().describe("Additional indexes to merge into the target object"), - /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ - priority: external_exports.number().int().min(0).max(999).default(200).describe("Merge priority (higher = applied later)") -}); -var AddFieldOperation = external_exports.object({ - type: external_exports.literal("add_field"), - objectName: external_exports.string().describe("Target object name"), - fieldName: external_exports.string().describe("Name of the field to add"), - field: FieldSchema.describe("Full field definition to add") -}).describe("Add a new field to an existing object"); -var ModifyFieldOperation = external_exports.object({ - type: external_exports.literal("modify_field"), - objectName: external_exports.string().describe("Target object name"), - fieldName: external_exports.string().describe("Name of the field to modify"), - changes: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Partial field definition updates") -}).describe("Modify properties of an existing field"); -var RemoveFieldOperation = external_exports.object({ - type: external_exports.literal("remove_field"), - objectName: external_exports.string().describe("Target object name"), - fieldName: external_exports.string().describe("Name of the field to remove") -}).describe("Remove a field from an existing object"); -var CreateObjectOperation = external_exports.object({ - type: external_exports.literal("create_object"), - object: ObjectSchema.describe("Full object definition to create") -}).describe("Create a new object"); -var RenameObjectOperation = external_exports.object({ - type: external_exports.literal("rename_object"), - oldName: external_exports.string().describe("Current object name"), - newName: external_exports.string().describe("New object name") -}).describe("Rename an existing object"); -var DeleteObjectOperation = external_exports.object({ - type: external_exports.literal("delete_object"), - objectName: external_exports.string().describe("Name of the object to delete") -}).describe("Delete an existing object"); -var ExecuteSqlOperation = external_exports.object({ - type: external_exports.literal("execute_sql"), - sql: external_exports.string().describe("Raw SQL statement to execute"), - description: external_exports.string().optional().describe("Human-readable description of the SQL") -}).describe("Execute a raw SQL statement"); -var MigrationOperationSchema = external_exports.discriminatedUnion("type", [ - AddFieldOperation, - ModifyFieldOperation, - RemoveFieldOperation, - CreateObjectOperation, - RenameObjectOperation, - DeleteObjectOperation, - ExecuteSqlOperation -]); -var MigrationDependencySchema = external_exports.object({ - migrationId: external_exports.string().describe("ID of the migration this depends on"), - package: external_exports.string().optional().describe("Package that owns the dependency migration") -}).describe("Dependency reference to another migration that must run first"); -var ChangeSetSchema = external_exports.object({ - id: external_exports.string().uuid().describe("Unique identifier for this change set"), - name: external_exports.string().describe("Human readable name for the migration"), - description: external_exports.string().optional().describe("Detailed description of what this migration does"), - author: external_exports.string().optional().describe("Author who created this migration"), - createdAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp when the migration was created"), - // Dependencies ensure migrations run in order - dependencies: external_exports.array(MigrationDependencySchema).optional().describe("Migrations that must run before this one"), - // The actual atomic operations - operations: external_exports.array(MigrationOperationSchema).describe("Ordered list of atomic migration operations"), - // Rollback operations (AI should generate these too) - rollback: external_exports.array(MigrationOperationSchema).optional().describe("Operations to reverse this migration") -}).describe("A versioned set of atomic schema migration operations"); -var AuthProviderConfigSchema = external_exports.object({ - id: external_exports.string().describe("Provider ID (github, google)"), - clientId: external_exports.string().describe("OAuth Client ID"), - clientSecret: external_exports.string().describe("OAuth Client Secret"), - scope: external_exports.array(external_exports.string()).optional().describe("Requested permissions") -}); -var AuthPluginConfigSchema = external_exports.object({ - organization: external_exports.boolean().default(false).describe("Enable Organization/Teams support"), - twoFactor: external_exports.boolean().default(false).describe("Enable 2FA"), - passkeys: external_exports.boolean().default(false).describe("Enable Passkey support"), - magicLink: external_exports.boolean().default(false).describe("Enable Magic Link login") -}); -var MutualTLSConfigSchema = external_exports.object({ - /** Enable mutual TLS authentication */ - enabled: external_exports.boolean().default(false).describe("Enable mutual TLS authentication"), - /** Require client certificates for all connections */ - clientCertRequired: external_exports.boolean().default(false).describe("Require client certificates for all connections"), - /** PEM-encoded CA certificates or file paths for trust validation */ - trustedCAs: external_exports.array(external_exports.string()).describe("PEM-encoded CA certificates or file paths"), - /** Certificate Revocation List URL */ - crlUrl: external_exports.string().optional().describe("Certificate Revocation List (CRL) URL"), - /** Online Certificate Status Protocol URL */ - ocspUrl: external_exports.string().optional().describe("Online Certificate Status Protocol (OCSP) URL"), - /** Certificate validation strictness level */ - certificateValidation: external_exports.enum(["strict", "relaxed", "none"]).describe("Certificate validation strictness level"), - /** Allowed Common Names on client certificates */ - allowedCNs: external_exports.array(external_exports.string()).optional().describe("Allowed Common Names (CN) on client certificates"), - /** Allowed Organizational Units on client certificates */ - allowedOUs: external_exports.array(external_exports.string()).optional().describe("Allowed Organizational Units (OU) on client certificates"), - /** Certificate pinning configuration */ - pinning: external_exports.object({ - /** Enable certificate pinning */ - enabled: external_exports.boolean().describe("Enable certificate pinning"), - /** Array of pinned certificate hashes */ - pins: external_exports.array(external_exports.string()).describe("Pinned certificate hashes") - }).optional().describe("Certificate pinning configuration") -}); -var SocialProviderConfigSchema = external_exports.record( - external_exports.string(), - external_exports.object({ - clientId: external_exports.string().describe("OAuth Client ID"), - clientSecret: external_exports.string().describe("OAuth Client Secret"), - enabled: external_exports.boolean().optional().default(true).describe("Enable this provider"), - scope: external_exports.array(external_exports.string()).optional().describe("Additional OAuth scopes") - }).catchall(external_exports.unknown()) -).optional().describe( - "Social/OAuth provider map forwarded to better-auth socialProviders. Keys are provider ids (google, github, apple, \u2026)." -); -var EmailAndPasswordConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable email/password auth"), - disableSignUp: external_exports.boolean().optional().describe("Disable new user registration via email/password"), - requireEmailVerification: external_exports.boolean().optional().describe( - "Require email verification before creating a session" - ), - minPasswordLength: external_exports.number().optional().describe("Minimum password length (default 8)"), - maxPasswordLength: external_exports.number().optional().describe("Maximum password length (default 128)"), - resetPasswordTokenExpiresIn: external_exports.number().optional().describe( - "Reset-password token TTL in seconds (default 3600)" - ), - autoSignIn: external_exports.boolean().optional().describe("Auto sign-in after sign-up (default true)"), - revokeSessionsOnPasswordReset: external_exports.boolean().optional().describe( - "Revoke all other sessions on password reset" - ) -}).optional().describe("Email and password authentication options forwarded to better-auth"); -var EmailVerificationConfigSchema = external_exports.object({ - sendOnSignUp: external_exports.boolean().optional().describe( - "Automatically send verification email after sign-up" - ), - sendOnSignIn: external_exports.boolean().optional().describe( - "Send verification email on sign-in when not yet verified" - ), - autoSignInAfterVerification: external_exports.boolean().optional().describe( - "Auto sign-in the user after email verification" - ), - expiresIn: external_exports.number().optional().describe( - "Verification token TTL in seconds (default 3600)" - ) -}).optional().describe("Email verification options forwarded to better-auth"); -var AdvancedAuthConfigSchema = external_exports.object({ - crossSubDomainCookies: external_exports.object({ - enabled: external_exports.boolean().describe("Enable cross-subdomain cookies"), - additionalCookies: external_exports.array(external_exports.string()).optional().describe("Extra cookies shared across subdomains"), - domain: external_exports.string().optional().describe( - "Cookie domain override \u2014 defaults to root domain derived from baseUrl" - ) - }).optional().describe( - "Share auth cookies across subdomains (critical for *.example.com multi-tenant)" - ), - useSecureCookies: external_exports.boolean().optional().describe("Force Secure flag on cookies"), - disableCSRFCheck: external_exports.boolean().optional().describe( - "\u26A0 Disable CSRF check \u2014 security risk, use with caution" - ), - cookiePrefix: external_exports.string().optional().describe("Prefix for auth cookie names") -}).optional().describe("Advanced / low-level Better-Auth options"); -var AuthConfigSchema = external_exports.object({ - secret: external_exports.string().optional().describe("Encryption secret"), - baseUrl: external_exports.string().optional().describe("Base URL for auth routes"), - databaseUrl: external_exports.string().optional().describe("Database connection string"), - providers: external_exports.array(AuthProviderConfigSchema).optional(), - plugins: AuthPluginConfigSchema.optional(), - session: external_exports.object({ - expiresIn: external_exports.number().default(60 * 60 * 24 * 7).describe("Session duration in seconds"), - updateAge: external_exports.number().default(60 * 60 * 24).describe("Session update frequency") - }).optional(), - trustedOrigins: external_exports.array(external_exports.string()).optional().describe( - 'Trusted origins for CSRF protection. Supports wildcards (e.g. "https://*.example.com"). The baseUrl origin is always trusted implicitly.' - ), - socialProviders: SocialProviderConfigSchema, - emailAndPassword: EmailAndPasswordConfigSchema, - emailVerification: EmailVerificationConfigSchema, - advanced: AdvancedAuthConfigSchema, - mutualTls: MutualTLSConfigSchema.optional().describe("Mutual TLS (mTLS) configuration") -}).catchall(external_exports.unknown()); -var GDPRConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable GDPR compliance controls"), - dataSubjectRights: external_exports.object({ - rightToAccess: external_exports.boolean().default(true).describe("Allow data subjects to access their data"), - rightToRectification: external_exports.boolean().default(true).describe("Allow data subjects to correct their data"), - rightToErasure: external_exports.boolean().default(true).describe("Allow data subjects to request deletion"), - rightToRestriction: external_exports.boolean().default(true).describe("Allow data subjects to restrict processing"), - rightToPortability: external_exports.boolean().default(true).describe("Allow data subjects to export their data"), - rightToObjection: external_exports.boolean().default(true).describe("Allow data subjects to object to processing") - }).describe("Data subject rights configuration per GDPR Articles 15-21"), - legalBasis: external_exports.enum([ - "consent", - "contract", - "legal-obligation", - "vital-interests", - "public-task", - "legitimate-interests" - ]).describe("Legal basis for data processing under GDPR Article 6"), - consentTracking: external_exports.boolean().default(true).describe("Track and record user consent"), - dataRetentionDays: external_exports.number().optional().describe("Maximum data retention period in days"), - dataProcessingAgreement: external_exports.string().optional().describe("URL or reference to the data processing agreement") -}).describe("GDPR (General Data Protection Regulation) compliance configuration"); -var HIPAAConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable HIPAA compliance controls"), - phi: external_exports.object({ - encryption: external_exports.boolean().default(true).describe("Encrypt Protected Health Information at rest"), - accessControl: external_exports.boolean().default(true).describe("Enforce role-based access to PHI"), - auditTrail: external_exports.boolean().default(true).describe("Log all PHI access events"), - backupAndRecovery: external_exports.boolean().default(true).describe("Enable PHI backup and disaster recovery") - }).describe("Protected Health Information safeguards"), - businessAssociateAgreement: external_exports.boolean().default(false).describe("BAA is in place with third-party processors") -}).describe("HIPAA (Health Insurance Portability and Accountability Act) compliance configuration"); -var PCIDSSConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable PCI-DSS compliance controls"), - level: external_exports.enum(["1", "2", "3", "4"]).describe("PCI-DSS compliance level (1 = highest)"), - cardDataFields: external_exports.array(external_exports.string()).describe("Field names containing cardholder data"), - tokenization: external_exports.boolean().default(true).describe("Replace card data with secure tokens"), - encryptionInTransit: external_exports.boolean().default(true).describe("Encrypt cardholder data during transmission"), - encryptionAtRest: external_exports.boolean().default(true).describe("Encrypt stored cardholder data") -}).describe("PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration"); -var AuditLogConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable audit logging"), - retentionDays: external_exports.number().default(365).describe("Number of days to retain audit logs"), - immutable: external_exports.boolean().default(true).describe("Prevent modification or deletion of audit logs"), - signLogs: external_exports.boolean().default(false).describe("Cryptographically sign log entries for tamper detection"), - events: external_exports.array(external_exports.enum([ - "create", - "read", - "update", - "delete", - "export", - "permission-change", - "login", - "logout", - "failed-login" - ])).describe("Event types to capture in the audit log") -}).describe("Audit log configuration for compliance and security monitoring"); -var AuditFindingSeveritySchema = external_exports.enum([ - "critical", - // Immediate remediation required - "major", - // Significant non-conformity - "minor", - // Minor non-conformity - "observation" - // Improvement opportunity -]); -var AuditFindingStatusSchema = external_exports.enum([ - "open", - // Finding identified, not yet addressed - "in_remediation", - // Remediation in progress - "remediated", - // Remediation completed, pending verification - "verified", - // Remediation verified and accepted - "accepted_risk", - // Risk accepted by management - "closed" - // Finding closed -]); -var AuditFindingSchema = external_exports.object({ - /** - * Unique finding identifier - */ - id: external_exports.string().describe("Unique finding identifier"), - /** - * Short descriptive title - */ - title: external_exports.string().describe("Finding title"), - /** - * Detailed description of the finding - */ - description: external_exports.string().describe("Finding description"), - /** - * Finding severity - */ - severity: AuditFindingSeveritySchema.describe("Finding severity"), - /** - * Current status - */ - status: AuditFindingStatusSchema.describe("Finding status"), - /** - * ISO 27001 control reference (e.g., "A.5.35", "A.8.15") - */ - controlReference: external_exports.string().optional().describe("ISO 27001 control reference"), - /** - * Compliance framework - */ - framework: ComplianceFrameworkSchema.optional().describe("Related compliance framework"), - /** - * Timestamp when finding was identified (Unix milliseconds) - */ - identifiedAt: external_exports.number().describe("Identification timestamp"), - /** - * User or entity who identified the finding - */ - identifiedBy: external_exports.string().describe("Identifier (auditor name or system)"), - /** - * Planned remediation actions - */ - remediationPlan: external_exports.string().optional().describe("Remediation plan"), - /** - * Remediation deadline (Unix milliseconds) - */ - remediationDeadline: external_exports.number().optional().describe("Remediation deadline timestamp"), - /** - * Timestamp when remediation was verified (Unix milliseconds) - */ - verifiedAt: external_exports.number().optional().describe("Verification timestamp"), - /** - * Verifier name or role - */ - verifiedBy: external_exports.string().optional().describe("Verifier name or role"), - /** - * Notes or comments - */ - notes: external_exports.string().optional().describe("Additional notes") -}).describe("Audit finding with remediation tracking per ISO 27001:2022 A.5.35"); -var AuditScheduleSchema = external_exports.object({ - /** - * Unique audit schedule identifier - */ - id: external_exports.string().describe("Unique audit schedule identifier"), - /** - * Audit title or name - */ - title: external_exports.string().describe("Audit title"), - /** - * Scope of areas to audit - */ - scope: external_exports.array(external_exports.string()).describe("Audit scope areas"), - /** - * Target compliance framework - */ - framework: ComplianceFrameworkSchema.describe("Target compliance framework"), - /** - * Scheduled audit date (Unix milliseconds) - */ - scheduledAt: external_exports.number().describe("Scheduled audit timestamp"), - /** - * Actual completion date (Unix milliseconds) - */ - completedAt: external_exports.number().optional().describe("Completion timestamp"), - /** - * Assessor name, team, or external firm - */ - assessor: external_exports.string().describe("Assessor or audit team"), - /** - * Whether this is an external (independent) audit - */ - isExternal: external_exports.boolean().default(false).describe("Whether this is an external audit"), - /** - * Recurrence interval in months (0 = one-time) - */ - recurrenceMonths: external_exports.number().default(0).describe("Recurrence interval in months (0 = one-time)"), - /** - * Findings from this audit - */ - findings: external_exports.array(AuditFindingSchema).optional().describe("Audit findings") -}).describe("Audit schedule for independent security reviews per ISO 27001:2022 A.5.35"); -var ComplianceConfigSchema = external_exports.object({ - gdpr: GDPRConfigSchema.optional().describe("GDPR compliance settings"), - hipaa: HIPAAConfigSchema.optional().describe("HIPAA compliance settings"), - pciDss: PCIDSSConfigSchema.optional().describe("PCI-DSS compliance settings"), - auditLog: AuditLogConfigSchema.describe("Audit log configuration"), - auditSchedules: external_exports.array(AuditScheduleSchema).optional().describe("Scheduled compliance audits (A.5.35)") -}).describe("Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance"); -var IncidentSeveritySchema = external_exports.enum([ - "critical", - // Immediate threat to business operations or data integrity - "high", - // Significant impact requiring urgent response - "medium", - // Moderate impact with controlled response timeline - "low" - // Minor impact with standard response procedures -]); -var IncidentCategorySchema = external_exports.enum([ - "data_breach", - // Unauthorized access or disclosure of data - "malware", - // Malicious software detection - "unauthorized_access", - // Unauthorized system or data access - "denial_of_service", - // Service availability attack - "social_engineering", - // Phishing, pretexting, or manipulation - "insider_threat", - // Threat originating from internal actors - "physical_security", - // Physical security breach - "configuration_error", - // Security misconfiguration - "vulnerability_exploit", - // Exploitation of known vulnerability - "policy_violation", - // Violation of security policies - "other" - // Other security incidents -]); -var IncidentStatusSchema = external_exports.enum([ - "reported", - // Initial report received - "triaged", - // Severity and category assessed - "investigating", - // Active investigation in progress - "containing", - // Containment measures being applied - "eradicating", - // Root cause being removed - "recovering", - // Systems being restored to normal - "resolved", - // Incident resolved - "closed" - // Post-incident review complete -]); -var IncidentResponsePhaseSchema = external_exports.object({ - /** - * Phase name identifier - */ - phase: external_exports.enum([ - "identification", - "containment", - "eradication", - "recovery", - "lessons_learned" - ]).describe("Response phase name"), - /** - * Phase description and objectives - */ - description: external_exports.string().describe("Phase description and objectives"), - /** - * Responsible team or role for this phase - */ - assignedTo: external_exports.string().describe("Responsible team or role"), - /** - * Target completion time in hours from incident start - */ - targetHours: external_exports.number().min(0).describe("Target completion time in hours"), - /** - * Actual completion timestamp (Unix milliseconds) - */ - completedAt: external_exports.number().optional().describe("Actual completion timestamp"), - /** - * Notes and findings during this phase - */ - notes: external_exports.string().optional().describe("Phase notes and findings") -}).describe("Incident response phase with timing and assignment"); -var IncidentNotificationRuleSchema = external_exports.object({ - /** - * Minimum severity level that triggers this notification - */ - severity: IncidentSeveritySchema.describe("Minimum severity to trigger notification"), - /** - * Notification channels to use - */ - channels: external_exports.array(external_exports.enum([ - "email", - "sms", - "slack", - "pagerduty", - "webhook" - ])).describe("Notification channels"), - /** - * Roles or teams to notify - */ - recipients: external_exports.array(external_exports.string()).describe("Roles or teams to notify"), - /** - * Maximum time in minutes to send notification after incident detection - */ - withinMinutes: external_exports.number().min(1).describe("Notification deadline in minutes from detection"), - /** - * Whether to notify external regulators (for data breaches) - */ - notifyRegulators: external_exports.boolean().default(false).describe("Whether to notify regulatory authorities"), - /** - * Regulatory notification deadline in hours (e.g., GDPR 72h) - */ - regulatorDeadlineHours: external_exports.number().optional().describe("Regulatory notification deadline in hours") -}).describe("Incident notification rule per severity level"); -var IncidentNotificationMatrixSchema = external_exports.object({ - /** - * Notification rules ordered by severity - */ - rules: external_exports.array(IncidentNotificationRuleSchema).describe("Notification rules by severity level"), - /** - * Default escalation timeout in minutes before auto-escalation - */ - escalationTimeoutMinutes: external_exports.number().default(30).describe("Auto-escalation timeout in minutes"), - /** - * Escalation chain: ordered list of roles to escalate to - */ - escalationChain: external_exports.array(external_exports.string()).default([]).describe("Ordered escalation chain of roles") -}).describe("Incident notification matrix with escalation policies"); -var IncidentSchema = external_exports.object({ - /** - * Unique incident identifier - */ - id: external_exports.string().describe("Unique incident identifier"), - /** - * Short descriptive title of the incident - */ - title: external_exports.string().describe("Incident title"), - /** - * Detailed description of the security event - */ - description: external_exports.string().describe("Detailed incident description"), - /** - * Severity classification - */ - severity: IncidentSeveritySchema.describe("Incident severity level"), - /** - * Incident category / type - */ - category: IncidentCategorySchema.describe("Incident category"), - /** - * Current status in the incident lifecycle - */ - status: IncidentStatusSchema.describe("Current incident status"), - /** - * User or system that reported the incident - */ - reportedBy: external_exports.string().describe("Reporter user ID or system name"), - /** - * Timestamp when the incident was reported (Unix milliseconds) - */ - reportedAt: external_exports.number().describe("Report timestamp"), - /** - * Timestamp when the incident was detected (may differ from reported) - */ - detectedAt: external_exports.number().optional().describe("Detection timestamp"), - /** - * Timestamp when the incident was resolved - */ - resolvedAt: external_exports.number().optional().describe("Resolution timestamp"), - /** - * Systems affected by the incident - */ - affectedSystems: external_exports.array(external_exports.string()).describe("Affected systems"), - /** - * Data classifications affected (for data breach assessment) - */ - affectedDataClassifications: external_exports.array(DataClassificationSchema).optional().describe("Affected data classifications"), - /** - * Structured response phases tracking - */ - responsePhases: external_exports.array(IncidentResponsePhaseSchema).optional().describe("Incident response phases"), - /** - * Root cause analysis (completed post-incident) - */ - rootCause: external_exports.string().optional().describe("Root cause analysis"), - /** - * Corrective actions taken or planned - */ - correctiveActions: external_exports.array(external_exports.string()).optional().describe("Corrective actions taken or planned"), - /** - * Lessons learned from the incident (A.5.28) - */ - lessonsLearned: external_exports.string().optional().describe("Lessons learned from the incident"), - /** - * Related change request IDs (if changes resulted from incident) - */ - relatedChangeRequestIds: external_exports.array(external_exports.string()).optional().describe("Related change request IDs"), - /** - * Custom metadata for extensibility - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs") -}).describe("Security incident record per ISO 27001:2022 A.5.24\u2013A.5.28"); -var IncidentResponsePolicySchema = external_exports.object({ - /** - * Whether incident response is enabled - */ - enabled: external_exports.boolean().default(true).describe("Enable incident response management"), - /** - * Notification matrix configuration - */ - notificationMatrix: IncidentNotificationMatrixSchema.describe("Notification and escalation matrix"), - /** - * Default response team or role - */ - defaultResponseTeam: external_exports.string().describe("Default incident response team or role"), - /** - * Maximum time in hours to begin initial triage - */ - triageDeadlineHours: external_exports.number().default(1).describe("Maximum hours to begin triage after detection"), - /** - * Whether to require post-incident review for all incidents - */ - requirePostIncidentReview: external_exports.boolean().default(true).describe("Require post-incident review for all incidents"), - /** - * Minimum severity level that requires regulatory notification - */ - regulatoryNotificationThreshold: IncidentSeveritySchema.default("high").describe("Minimum severity requiring regulatory notification"), - /** - * Retention period for incident records in days - */ - retentionDays: external_exports.number().default(2555).describe("Incident record retention period in days (default ~7 years)") -}).describe("Organization-level incident response policy per ISO 27001:2022"); -var SupplierRiskLevelSchema = external_exports.enum([ - "critical", - // Direct access to sensitive data or core infrastructure - "high", - // Significant data processing or service dependency - "medium", - // Limited data access with moderate dependency - "low" - // Minimal data access and low service dependency -]); -var SupplierAssessmentStatusSchema = external_exports.enum([ - "pending", - // Assessment not yet started - "in_progress", - // Assessment currently underway - "completed", - // Assessment completed - "expired", - // Assessment past its validity period - "failed" - // Supplier did not meet security requirements -]); -var SupplierSecurityRequirementSchema = external_exports.object({ - /** - * Requirement identifier - */ - id: external_exports.string().describe("Requirement identifier"), - /** - * Requirement description - */ - description: external_exports.string().describe("Requirement description"), - /** - * ISO 27001 control reference (e.g., "A.5.19") - */ - controlReference: external_exports.string().optional().describe("ISO 27001 control reference"), - /** - * Whether this requirement is mandatory - */ - mandatory: external_exports.boolean().default(true).describe("Whether this requirement is mandatory"), - /** - * Compliance status - */ - compliant: external_exports.boolean().optional().describe("Whether the supplier meets this requirement"), - /** - * Evidence or notes for compliance assessment - */ - evidence: external_exports.string().optional().describe("Compliance evidence or assessment notes") -}).describe("Individual supplier security requirement"); -var SupplierSecurityAssessmentSchema = external_exports.object({ - /** - * Unique supplier identifier - */ - supplierId: external_exports.string().describe("Unique supplier identifier"), - /** - * Supplier name - */ - supplierName: external_exports.string().describe("Supplier display name"), - /** - * Risk classification - */ - riskLevel: SupplierRiskLevelSchema.describe("Supplier risk classification"), - /** - * Assessment status - */ - status: SupplierAssessmentStatusSchema.describe("Assessment status"), - /** - * User or team who performed the assessment - */ - assessedBy: external_exports.string().describe("Assessor user ID or team"), - /** - * Assessment completion timestamp (Unix milliseconds) - */ - assessedAt: external_exports.number().describe("Assessment timestamp"), - /** - * Assessment validity expiry (Unix milliseconds) - */ - validUntil: external_exports.number().describe("Assessment validity expiry timestamp"), - /** - * Security requirements assessed - */ - requirements: external_exports.array(SupplierSecurityRequirementSchema).describe("Security requirements and their compliance status"), - /** - * Overall compliance result - */ - overallCompliant: external_exports.boolean().describe("Whether supplier meets all mandatory requirements"), - /** - * Data classifications shared with this supplier - */ - dataClassificationsShared: external_exports.array(DataClassificationSchema).optional().describe("Data classifications shared with supplier"), - /** - * Services provided by the supplier - */ - servicesProvided: external_exports.array(external_exports.string()).optional().describe("Services provided by this supplier"), - /** - * Certifications held by the supplier - */ - certifications: external_exports.array(external_exports.string()).optional().describe("Supplier certifications (e.g., ISO 27001, SOC 2)"), - /** - * Remediation items for non-compliant requirements - */ - remediationItems: external_exports.array(external_exports.object({ - requirementId: external_exports.string().describe("Non-compliant requirement ID"), - action: external_exports.string().describe("Required remediation action"), - deadline: external_exports.number().describe("Remediation deadline timestamp"), - status: external_exports.enum(["pending", "in_progress", "completed"]).default("pending").describe("Remediation status") - })).optional().describe("Remediation items for non-compliant requirements"), - /** - * Custom metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs") -}).describe("Supplier security assessment record per ISO 27001:2022 A.5.19\u2013A.5.21"); -var SupplierSecurityPolicySchema = external_exports.object({ - /** - * Whether supplier security management is enabled - */ - enabled: external_exports.boolean().default(true).describe("Enable supplier security management"), - /** - * Reassessment interval in days - */ - reassessmentIntervalDays: external_exports.number().default(365).describe("Supplier reassessment interval in days"), - /** - * Whether to require supplier security assessment before onboarding - */ - requirePreOnboardingAssessment: external_exports.boolean().default(true).describe("Require security assessment before supplier onboarding"), - /** - * Minimum risk level that requires formal assessment - */ - formalAssessmentThreshold: SupplierRiskLevelSchema.default("medium").describe("Minimum risk level requiring formal assessment"), - /** - * Whether to monitor supplier security changes (A.5.22) - */ - monitorChanges: external_exports.boolean().default(true).describe("Monitor supplier security posture changes"), - /** - * Required certifications for critical suppliers - */ - requiredCertifications: external_exports.array(external_exports.string()).default([]).describe("Required certifications for critical-risk suppliers") -}).describe("Organization-level supplier security management policy per ISO 27001:2022"); -var TrainingCategorySchema = external_exports.enum([ - "security_awareness", - // General security awareness - "data_protection", - // Data handling and privacy - "incident_response", - // Incident reporting and response - "access_control", - // Access management best practices - "phishing_awareness", - // Phishing and social engineering - "compliance", - // Regulatory compliance (GDPR, HIPAA, etc.) - "secure_development", - // Secure coding and development practices - "physical_security", - // Physical security awareness - "business_continuity", - // Business continuity and disaster recovery - "other" - // Other training categories -]); -var TrainingCompletionStatusSchema = external_exports.enum([ - "not_started", - // Training not yet begun - "in_progress", - // Training currently underway - "completed", - // Training completed successfully - "failed", - // Training assessment not passed - "expired" - // Training certification has expired -]); -var TrainingCourseSchema = external_exports.object({ - /** - * Unique course identifier - */ - id: external_exports.string().describe("Unique course identifier"), - /** - * Course title - */ - title: external_exports.string().describe("Course title"), - /** - * Course description and objectives - */ - description: external_exports.string().describe("Course description and learning objectives"), - /** - * Training category - */ - category: TrainingCategorySchema.describe("Training category"), - /** - * Estimated duration in minutes - */ - durationMinutes: external_exports.number().min(1).describe("Estimated course duration in minutes"), - /** - * Whether this training is mandatory - */ - mandatory: external_exports.boolean().default(false).describe("Whether training is mandatory"), - /** - * Target roles or groups for this training - */ - targetRoles: external_exports.array(external_exports.string()).describe("Target roles or groups"), - /** - * Validity period in days before recertification is needed - */ - validityDays: external_exports.number().optional().describe("Certification validity period in days"), - /** - * Minimum passing score (percentage) for assessment - */ - passingScore: external_exports.number().min(0).max(100).optional().describe("Minimum passing score percentage"), - /** - * Course version for tracking content updates - */ - version: external_exports.string().optional().describe("Course content version") -}).describe("Security training course definition"); -var TrainingRecordSchema = external_exports.object({ - /** - * Reference to the course ID - */ - courseId: external_exports.string().describe("Training course identifier"), - /** - * User who completed (or is assigned) the training - */ - userId: external_exports.string().describe("User identifier"), - /** - * Completion status - */ - status: TrainingCompletionStatusSchema.describe("Training completion status"), - /** - * Training assignment date (Unix milliseconds) - */ - assignedAt: external_exports.number().describe("Assignment timestamp"), - /** - * Training completion date (Unix milliseconds) - */ - completedAt: external_exports.number().optional().describe("Completion timestamp"), - /** - * Assessment score (percentage) - */ - score: external_exports.number().min(0).max(100).optional().describe("Assessment score percentage"), - /** - * Certification expiry date (Unix milliseconds) - */ - expiresAt: external_exports.number().optional().describe("Certification expiry timestamp"), - /** - * Notes or comments from instructor or system - */ - notes: external_exports.string().optional().describe("Training notes or comments") -}).describe("Individual training completion record"); -var TrainingPlanSchema = external_exports.object({ - /** - * Whether training management is enabled - */ - enabled: external_exports.boolean().default(true).describe("Enable training management"), - /** - * Training courses in the plan - */ - courses: external_exports.array(TrainingCourseSchema).describe("Training courses"), - /** - * Default recertification interval in days - */ - recertificationIntervalDays: external_exports.number().default(365).describe("Default recertification interval in days"), - /** - * Whether to track training completion for compliance reporting - */ - trackCompletion: external_exports.boolean().default(true).describe("Track training completion for compliance"), - /** - * Grace period in days after expiry before non-compliance escalation - */ - gracePeriodDays: external_exports.number().default(30).describe("Grace period in days after certification expiry"), - /** - * Whether to send reminders for upcoming training deadlines - */ - sendReminders: external_exports.boolean().default(true).describe("Send reminders for upcoming training deadlines"), - /** - * Days before deadline to send first reminder - */ - reminderDaysBefore: external_exports.number().default(14).describe("Days before deadline to send first reminder") -}).describe("Organizational training plan per ISO 27001:2022 A.6.3"); -var CronScheduleSchema = external_exports.object({ - type: external_exports.literal("cron"), - expression: external_exports.string().describe('Cron expression (e.g., "0 0 * * *" for daily at midnight)'), - timezone: external_exports.string().optional().default("UTC").describe('Timezone for cron execution (e.g., "America/New_York")') -}); -var IntervalScheduleSchema = external_exports.object({ - type: external_exports.literal("interval"), - intervalMs: external_exports.number().int().positive().describe("Interval in milliseconds") -}); -var OnceScheduleSchema = external_exports.object({ - type: external_exports.literal("once"), - at: external_exports.string().datetime().describe("ISO 8601 datetime when to execute") -}); -var ScheduleSchema = external_exports.discriminatedUnion("type", [ - CronScheduleSchema, - IntervalScheduleSchema, - OnceScheduleSchema -]); -var RetryPolicySchema = external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum number of retry attempts"), - backoffMs: external_exports.number().int().positive().default(1e3).describe("Initial backoff delay in milliseconds"), - backoffMultiplier: external_exports.number().positive().default(2).describe("Multiplier for exponential backoff") -}); -var JobSchema = external_exports.object({ - id: external_exports.string().describe("Unique job identifier"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Job name (snake_case)"), - schedule: ScheduleSchema.describe("Job schedule configuration"), - handler: external_exports.string().describe('Handler path (e.g. "path/to/file:functionName") or script ID'), - retryPolicy: RetryPolicySchema.optional().describe("Retry policy configuration"), - timeout: external_exports.number().int().positive().optional().describe("Timeout in milliseconds"), - enabled: external_exports.boolean().default(true).describe("Whether the job is enabled") -}); -var JobExecutionStatus = external_exports.enum([ - "running", - "success", - "failed", - "timeout" -]); -var JobExecutionSchema = external_exports.object({ - jobId: external_exports.string().describe("Job identifier"), - startedAt: external_exports.string().datetime().describe("ISO 8601 datetime when execution started"), - completedAt: external_exports.string().datetime().optional().describe("ISO 8601 datetime when execution completed"), - status: JobExecutionStatus.describe("Execution status"), - error: external_exports.string().optional().describe("Error message if failed"), - duration: external_exports.number().int().optional().describe("Execution duration in milliseconds") -}); -var TaskPriority = external_exports.enum([ - "critical", - // 0 - Must execute immediately - "high", - // 1 - Execute soon - "normal", - // 2 - Default priority - "low", - // 3 - Execute when resources available - "background" - // 4 - Execute during low-traffic periods -]); -var TaskStatus = external_exports.enum([ - "pending", - // Waiting to be processed - "queued", - // In queue, ready for worker - "processing", - // Currently being executed - "completed", - // Successfully completed - "failed", - // Failed (may retry) - "cancelled", - // Manually cancelled - "timeout", - // Exceeded execution timeout - "dead" - // Moved to dead letter queue -]); -var TaskRetryPolicySchema = external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retry attempts"), - backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy between retries"), - initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay in milliseconds"), - maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Maximum retry delay in milliseconds"), - backoffMultiplier: external_exports.number().positive().default(2).describe("Multiplier for exponential backoff") -}); -var TaskSchema = external_exports.object({ - /** - * Unique task identifier - */ - id: external_exports.string().describe("Unique task identifier"), - /** - * Task type (handler identifier) - */ - type: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Task type (snake_case)"), - /** - * Task payload data - */ - payload: external_exports.unknown().describe("Task payload data"), - /** - * Queue name - */ - queue: external_exports.string().default("default").describe("Queue name"), - /** - * Task priority - */ - priority: TaskPriority.default("normal").describe("Task priority level"), - /** - * Retry policy - */ - retryPolicy: TaskRetryPolicySchema.optional().describe("Retry policy configuration"), - /** - * Execution timeout in milliseconds - */ - timeoutMs: external_exports.number().int().positive().optional().describe("Task timeout in milliseconds"), - /** - * Scheduled execution time - */ - scheduledAt: external_exports.string().datetime().optional().describe("ISO 8601 datetime to execute task"), - /** - * Maximum execution attempts - */ - attempts: external_exports.number().int().min(0).default(0).describe("Number of execution attempts"), - /** - * Task status - */ - status: TaskStatus.default("pending").describe("Current task status"), - /** - * Task metadata - */ - metadata: external_exports.object({ - createdAt: external_exports.string().datetime().optional().describe("When task was created"), - updatedAt: external_exports.string().datetime().optional().describe("Last update time"), - createdBy: external_exports.string().optional().describe("User who created task"), - tags: external_exports.array(external_exports.string()).optional().describe("Task tags for filtering") - }).optional().describe("Task metadata") -}); -var TaskExecutionResultSchema = external_exports.object({ - /** - * Task identifier - */ - taskId: external_exports.string().describe("Task identifier"), - /** - * Execution status - */ - status: TaskStatus.describe("Execution status"), - /** - * Execution result data - */ - result: external_exports.unknown().optional().describe("Execution result data"), - /** - * Error information - */ - error: external_exports.object({ - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Error stack trace"), - code: external_exports.string().optional().describe("Error code") - }).optional().describe("Error details if failed"), - /** - * Execution duration - */ - durationMs: external_exports.number().int().optional().describe("Execution duration in milliseconds"), - /** - * Execution timestamps - */ - startedAt: external_exports.string().datetime().describe("When execution started"), - completedAt: external_exports.string().datetime().optional().describe("When execution completed"), - /** - * Retry information - */ - attempt: external_exports.number().int().min(1).describe("Attempt number (1-indexed)"), - willRetry: external_exports.boolean().describe("Whether task will be retried") -}); -var QueueConfigSchema = external_exports.object({ - /** - * Queue name - */ - name: external_exports.string().describe("Queue name (snake_case)"), - /** - * Maximum concurrent workers - */ - concurrency: external_exports.number().int().min(1).default(5).describe("Max concurrent task executions"), - /** - * Rate limiting - */ - rateLimit: external_exports.object({ - max: external_exports.number().int().positive().describe("Maximum tasks per duration"), - duration: external_exports.number().int().positive().describe("Duration in milliseconds") - }).optional().describe("Rate limit configuration"), - /** - * Default retry policy - */ - defaultRetryPolicy: TaskRetryPolicySchema.optional().describe("Default retry policy for tasks"), - /** - * Dead letter queue - */ - deadLetterQueue: external_exports.string().optional().describe("Dead letter queue name"), - /** - * Queue priority - */ - priority: external_exports.number().int().min(0).default(0).describe("Queue priority (lower = higher priority)"), - /** - * Auto-scaling configuration - */ - autoScale: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable auto-scaling"), - minWorkers: external_exports.number().int().min(1).default(1).describe("Minimum workers"), - maxWorkers: external_exports.number().int().min(1).default(10).describe("Maximum workers"), - scaleUpThreshold: external_exports.number().int().positive().default(100).describe("Queue size to scale up"), - scaleDownThreshold: external_exports.number().int().min(0).default(10).describe("Queue size to scale down") - }).optional().describe("Auto-scaling configuration") -}); -var BatchTaskSchema = external_exports.object({ - /** - * Batch job identifier - */ - id: external_exports.string().describe("Unique batch job identifier"), - /** - * Task type for processing each item - */ - type: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Task type (snake_case)"), - /** - * Items to process - */ - items: external_exports.array(external_exports.unknown()).describe("Array of items to process"), - /** - * Batch size (items per task) - */ - batchSize: external_exports.number().int().min(1).default(100).describe("Number of items per batch"), - /** - * Queue name - */ - queue: external_exports.string().default("batch").describe("Queue for batch tasks"), - /** - * Priority - */ - priority: TaskPriority.default("normal").describe("Batch task priority"), - /** - * Parallel processing - */ - parallel: external_exports.boolean().default(true).describe("Process batches in parallel"), - /** - * Stop on error - */ - stopOnError: external_exports.boolean().default(false).describe("Stop batch if any item fails"), - /** - * Progress callback - * - * Called after each batch completes to report progress. - * Invoked asynchronously and should not throw errors. - * If the callback throws, the error is logged but batch processing continues. - * - * @param progress - Object containing processed count, total count, and failed count - */ - onProgress: external_exports.function().input(external_exports.tuple([external_exports.object({ - processed: external_exports.number(), - total: external_exports.number(), - failed: external_exports.number() - })])).output(external_exports.void()).optional().describe("Progress callback function (called after each batch)") -}); -var BatchProgressSchema = external_exports.object({ - /** - * Batch job identifier - */ - batchId: external_exports.string().describe("Batch job identifier"), - /** - * Total items - */ - total: external_exports.number().int().min(0).describe("Total number of items"), - /** - * Processed items - */ - processed: external_exports.number().int().min(0).default(0).describe("Items processed"), - /** - * Successful items - */ - succeeded: external_exports.number().int().min(0).default(0).describe("Items succeeded"), - /** - * Failed items - */ - failed: external_exports.number().int().min(0).default(0).describe("Items failed"), - /** - * Progress percentage - */ - percentage: external_exports.number().min(0).max(100).describe("Progress percentage"), - /** - * Status - */ - status: external_exports.enum(["pending", "running", "completed", "failed", "cancelled"]).describe("Batch status"), - /** - * Timestamps - */ - startedAt: external_exports.string().datetime().optional().describe("When batch started"), - completedAt: external_exports.string().datetime().optional().describe("When batch completed") -}); -var WorkerConfigSchema = external_exports.object({ - /** - * Worker name - */ - name: external_exports.string().describe("Worker name"), - /** - * Queues to process - */ - queues: external_exports.array(external_exports.string()).min(1).describe("Queue names to process"), - /** - * Queue configurations - */ - queueConfigs: external_exports.array(QueueConfigSchema).optional().describe("Queue configurations"), - /** - * Polling interval - */ - pollIntervalMs: external_exports.number().int().positive().default(1e3).describe("Queue polling interval in milliseconds"), - /** - * Visibility timeout - */ - visibilityTimeoutMs: external_exports.number().int().positive().default(3e4).describe("How long a task is invisible after being claimed"), - /** - * Task timeout - */ - defaultTimeoutMs: external_exports.number().int().positive().default(3e5).describe("Default task timeout in milliseconds"), - /** - * Graceful shutdown timeout - */ - shutdownTimeoutMs: external_exports.number().int().positive().default(3e4).describe("Graceful shutdown timeout in milliseconds"), - /** - * Task handlers - */ - handlers: external_exports.record(external_exports.string(), external_exports.function()).optional().describe("Task type handlers") -}); -var WorkerStatsSchema = external_exports.object({ - /** - * Worker name - */ - workerName: external_exports.string().describe("Worker name"), - /** - * Total tasks processed - */ - totalProcessed: external_exports.number().int().min(0).describe("Total tasks processed"), - /** - * Successful tasks - */ - succeeded: external_exports.number().int().min(0).describe("Successful tasks"), - /** - * Failed tasks - */ - failed: external_exports.number().int().min(0).describe("Failed tasks"), - /** - * Active tasks - */ - active: external_exports.number().int().min(0).describe("Currently active tasks"), - /** - * Average execution time - */ - avgExecutionMs: external_exports.number().min(0).optional().describe("Average execution time in milliseconds"), - /** - * Uptime - */ - uptimeMs: external_exports.number().int().min(0).describe("Worker uptime in milliseconds"), - /** - * Queue stats - */ - queues: external_exports.record(external_exports.string(), external_exports.object({ - pending: external_exports.number().int().min(0).describe("Pending tasks"), - active: external_exports.number().int().min(0).describe("Active tasks"), - completed: external_exports.number().int().min(0).describe("Completed tasks"), - failed: external_exports.number().int().min(0).describe("Failed tasks") - })).optional().describe("Per-queue statistics") -}); -var Task = Object.assign(TaskSchema, { - create: (task) => task -}); -var QueueConfig = Object.assign(QueueConfigSchema, { - create: (config4) => config4 -}); -var WorkerConfig = Object.assign(WorkerConfigSchema, { - create: (config4) => config4 -}); -var BatchTask = Object.assign(BatchTaskSchema, { - create: (batch) => batch -}); -var EmailTemplateSchema = external_exports.object({ - /** - * Unique identifier for the email template - */ - id: external_exports.string().describe("Template identifier"), - /** - * Email subject line (supports variable interpolation) - */ - subject: external_exports.string().describe("Email subject"), - /** - * Email body content - */ - body: external_exports.string().describe("Email body content"), - /** - * Content type of the email body - * @default 'html' - */ - bodyType: external_exports.enum(["text", "html", "markdown"]).optional().default("html").describe("Body content type"), - /** - * List of template variables for dynamic content - */ - variables: external_exports.array(external_exports.string()).optional().describe("Template variables"), - /** - * File attachments to include with the email - */ - attachments: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Attachment filename"), - url: external_exports.string().url().describe("Attachment URL") - })).optional().describe("Email attachments") -}); -var SMSTemplateSchema = external_exports.object({ - /** - * Unique identifier for the SMS template - */ - id: external_exports.string().describe("Template identifier"), - /** - * SMS message content (supports variable interpolation) - */ - message: external_exports.string().describe("SMS message content"), - /** - * Maximum character length for the SMS - * @default 160 - */ - maxLength: external_exports.number().optional().default(160).describe("Maximum message length"), - /** - * List of template variables for dynamic content - */ - variables: external_exports.array(external_exports.string()).optional().describe("Template variables") -}); -var PushNotificationSchema = external_exports.object({ - /** - * Notification title - */ - title: external_exports.string().describe("Notification title"), - /** - * Notification body text - */ - body: external_exports.string().describe("Notification body"), - /** - * Icon URL to display with notification - */ - icon: external_exports.string().url().optional().describe("Notification icon URL"), - /** - * Badge count to display on app icon - */ - badge: external_exports.number().optional().describe("Badge count"), - /** - * Custom data payload - */ - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom data"), - /** - * Action buttons for the notification - */ - actions: external_exports.array(external_exports.object({ - action: external_exports.string().describe("Action identifier"), - title: external_exports.string().describe("Action button title") - })).optional().describe("Notification actions") -}); -var InAppNotificationSchema = external_exports.object({ - /** - * Notification title - */ - title: external_exports.string().describe("Notification title"), - /** - * Notification message content - */ - message: external_exports.string().describe("Notification message"), - /** - * Notification severity type - */ - type: external_exports.enum(["info", "success", "warning", "error"]).describe("Notification type"), - /** - * Optional URL to navigate to when clicked - */ - actionUrl: external_exports.string().optional().describe("Action URL"), - /** - * Whether the notification can be dismissed by the user - * @default true - */ - dismissible: external_exports.boolean().optional().default(true).describe("User dismissible"), - /** - * Timestamp when notification expires (Unix milliseconds) - */ - expiresAt: external_exports.number().optional().describe("Expiration timestamp") -}); -var NotificationChannelSchema = external_exports.enum([ - "email", - "sms", - "push", - "in-app", - "slack", - "teams", - "webhook" -]); -var NotificationConfigSchema = external_exports.object({ - /** - * Unique identifier for this notification configuration - */ - id: external_exports.string().describe("Notification ID"), - /** - * Human-readable name for this notification - */ - name: external_exports.string().describe("Notification name"), - /** - * Delivery channel for the notification - */ - channel: NotificationChannelSchema.describe("Notification channel"), - /** - * Notification template based on channel type - */ - template: external_exports.union([ - EmailTemplateSchema, - SMSTemplateSchema, - PushNotificationSchema, - InAppNotificationSchema - ]).describe("Notification template"), - /** - * Recipient configuration - */ - recipients: external_exports.object({ - /** - * Primary recipients - */ - to: external_exports.array(external_exports.string()).describe("Primary recipients"), - /** - * CC recipients (email only) - */ - cc: external_exports.array(external_exports.string()).optional().describe("CC recipients"), - /** - * BCC recipients (email only) - */ - bcc: external_exports.array(external_exports.string()).optional().describe("BCC recipients") - }).describe("Recipients"), - /** - * Scheduling configuration - */ - schedule: external_exports.object({ - /** - * Scheduling type - */ - type: external_exports.enum(["immediate", "delayed", "scheduled"]).describe("Schedule type"), - /** - * Delay in milliseconds (for delayed type) - */ - delay: external_exports.number().optional().describe("Delay in milliseconds"), - /** - * Scheduled send time (Unix timestamp in milliseconds) - */ - scheduledAt: external_exports.number().optional().describe("Scheduled timestamp") - }).optional().describe("Scheduling"), - /** - * Retry policy for failed deliveries - */ - retryPolicy: external_exports.object({ - /** - * Enable automatic retries - * @default true - */ - enabled: external_exports.boolean().optional().default(true).describe("Enable retries"), - /** - * Maximum number of retry attempts - * @default 3 - */ - maxRetries: external_exports.number().optional().default(3).describe("Max retry attempts"), - /** - * Backoff strategy for retries - */ - backoffStrategy: external_exports.enum(["exponential", "linear", "fixed"]).describe("Backoff strategy") - }).optional().describe("Retry policy"), - /** - * Delivery tracking configuration - */ - tracking: external_exports.object({ - /** - * Track when emails are opened - * @default false - */ - trackOpens: external_exports.boolean().optional().default(false).describe("Track opens"), - /** - * Track when links are clicked - * @default false - */ - trackClicks: external_exports.boolean().optional().default(false).describe("Track clicks"), - /** - * Track delivery status - * @default true - */ - trackDelivery: external_exports.boolean().optional().default(true).describe("Track delivery") - }).optional().describe("Tracking configuration") -}); -var LocaleSchema = external_exports.string().describe("BCP-47 Language Tag (e.g. en-US, zh-CN)"); -var FieldTranslationSchema = external_exports.object({ - label: external_exports.string().optional().describe("Translated field label"), - help: external_exports.string().optional().describe("Translated help text"), - placeholder: external_exports.string().optional().describe("Translated placeholder text for form inputs"), - options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Option value to translated label map") -}).describe("Translation data for a single field"); -var ObjectTranslationDataSchema = external_exports.object({ - /** Translated singular label for the object */ - label: external_exports.string().describe("Translated singular label"), - /** Translated plural label for the object */ - pluralLabel: external_exports.string().optional().describe("Translated plural label"), - /** Field-level translations keyed by field name (snake_case) */ - fields: external_exports.record(external_exports.string(), FieldTranslationSchema).optional().describe("Field-level translations") -}).describe("Translation data for a single object"); -var TranslationDataSchema = external_exports.object({ - /** Object translations */ - objects: external_exports.record(external_exports.string(), ObjectTranslationDataSchema).optional().describe("Object translations keyed by object name"), - /** App/Menu translations */ - apps: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().describe("Translated app label"), - description: external_exports.string().optional().describe("Translated app description") - })).optional().describe("App translations keyed by app name"), - /** UI Messages */ - messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID"), - /** Validation Error Messages */ - validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%"})') -}).describe("Translation data for objects, apps, and UI messages"); -var TranslationBundleSchema = external_exports.record(LocaleSchema, TranslationDataSchema).describe("Map of locale codes to translation data"); -var TranslationFileOrganizationSchema = external_exports.enum([ - "bundled", - "per_locale", - "per_namespace" -]).describe("Translation file organization strategy"); -var MessageFormatSchema = external_exports.enum([ - "icu", - "simple" -]).describe("Message interpolation format: ICU MessageFormat or simple {variable} replacement"); -var TranslationConfigSchema = external_exports.object({ - /** Default locale for the application */ - defaultLocale: LocaleSchema.describe('Default locale (e.g., "en")'), - /** Supported BCP-47 locale codes */ - supportedLocales: external_exports.array(LocaleSchema).describe("Supported BCP-47 locale codes"), - /** Fallback locale when translation is not found */ - fallbackLocale: LocaleSchema.optional().describe("Fallback locale code"), - /** How translation files are organized on disk */ - fileOrganization: TranslationFileOrganizationSchema.default("per_locale").describe("File organization strategy"), - /** - * Message interpolation format. - * When set to `'icu'`, messages and validationMessages are expected to use - * ICU MessageFormat syntax (plurals, select, number/date skeletons). - * @default 'simple' - */ - messageFormat: MessageFormatSchema.default("simple").describe("Message interpolation format (ICU MessageFormat or simple)"), - /** Load translations on demand instead of eagerly */ - lazyLoad: external_exports.boolean().default(false).describe("Load translations on demand"), - /** Cache loaded translations in memory */ - cache: external_exports.boolean().default(true).describe("Cache loaded translations") -}).describe("Internationalization configuration"); -var OptionTranslationMapSchema = external_exports.record(external_exports.string(), external_exports.string()).describe("Option value to translated label map"); -var ObjectTranslationNodeSchema = external_exports.object({ - /** Translated singular label */ - label: external_exports.string().describe("Translated singular label"), - /** Translated plural label */ - pluralLabel: external_exports.string().optional().describe("Translated plural label"), - /** Translated object description */ - description: external_exports.string().optional().describe("Translated object description"), - /** Translated help text shown in tooltips or guidance panels */ - helpText: external_exports.string().optional().describe("Translated help text for the object"), - /** Field-level translations keyed by field name (snake_case) */ - fields: external_exports.record(external_exports.string(), FieldTranslationSchema).optional().describe("Field translations keyed by field name"), - /** - * Global picklist / select option overrides scoped to this object. - * Keyed by field name → { optionValue: translatedLabel }. - */ - _options: external_exports.record(external_exports.string(), OptionTranslationMapSchema).optional().describe("Object-scoped picklist option translations keyed by field name"), - /** View translations keyed by view name */ - _views: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated view label"), - description: external_exports.string().optional().describe("Translated view description") - })).optional().describe("View translations keyed by view name"), - /** Section (form section / tab) translations keyed by section name */ - _sections: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated section label") - })).optional().describe("Section translations keyed by section name"), - /** Action translations keyed by action name */ - _actions: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated action label"), - confirmMessage: external_exports.string().optional().describe("Translated confirmation message") - })).optional().describe("Action translations keyed by action name"), - /** Notification message translations keyed by notification name */ - _notifications: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated notification title"), - body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") - })).optional().describe("Notification translations keyed by notification name"), - /** Error message translations keyed by error code */ - _errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Error message translations keyed by error code") -}).describe("Object-first aggregated translation node"); -var AppTranslationBundleSchema = external_exports.object({ - /** - * Bundle-level metadata. - * Provides locale-aware rendering hints such as text direction (bidi) - * and the canonical locale code this bundle represents. - */ - _meta: external_exports.object({ - /** BCP-47 locale code this bundle represents */ - locale: external_exports.string().optional().describe("BCP-47 locale code for this bundle"), - /** Text direction for the locale */ - direction: external_exports.enum(["ltr", "rtl"]).optional().describe("Text direction: left-to-right or right-to-left") - }).optional().describe("Bundle-level metadata (locale, bidi direction)"), - /** - * Namespace for plugin/extension isolation. - * When multiple plugins contribute translations, each should use a unique - * namespace to avoid key collisions (e.g. "crm", "helpdesk", "plugin-xyz"). - */ - namespace: external_exports.string().optional().describe("Namespace for plugin isolation to avoid translation key collisions"), - /** Object-first translations keyed by object name (snake_case) */ - o: external_exports.record(external_exports.string(), ObjectTranslationNodeSchema).optional().describe("Object-first translations keyed by object name"), - /** Global picklist options not bound to any specific object */ - _globalOptions: external_exports.record(external_exports.string(), OptionTranslationMapSchema).optional().describe("Global picklist option translations keyed by option set name"), - /** App-level translations */ - app: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().describe("Translated app label"), - description: external_exports.string().optional().describe("Translated app description") - })).optional().describe("App translations keyed by app name"), - /** Navigation menu translations */ - nav: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Navigation item translations keyed by nav item name"), - /** Dashboard translations keyed by dashboard name */ - dashboard: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated dashboard label"), - description: external_exports.string().optional().describe("Translated dashboard description") - })).optional().describe("Dashboard translations keyed by dashboard name"), - /** Report translations keyed by report name */ - reports: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated report label"), - description: external_exports.string().optional().describe("Translated report description") - })).optional().describe("Report translations keyed by report name"), - /** Page translations keyed by page name */ - pages: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated page title"), - description: external_exports.string().optional().describe("Translated page description") - })).optional().describe("Page translations keyed by page name"), - /** UI message translations (supports ICU MessageFormat when enabled) */ - messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID (supports ICU MessageFormat)"), - /** Validation error message translations (supports ICU MessageFormat when enabled) */ - validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Validation error message translations keyed by rule name (supports ICU MessageFormat)"), - /** Global notification translations not bound to a specific object */ - notifications: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated notification title"), - body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") - })).optional().describe("Global notification translations keyed by notification name"), - /** Global error message translations not bound to a specific object */ - errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Global error message translations keyed by error code") -}).describe("Object-first application translation bundle for a single locale"); -var TranslationDiffStatusSchema = external_exports.enum([ - "missing", - "redundant", - "stale" -]).describe("Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)"); -var TranslationDiffItemSchema = external_exports.object({ - /** Dot-path translation key (e.g. "o.account.fields.website.label") */ - key: external_exports.string().describe("Dot-path translation key"), - /** Diff status */ - status: TranslationDiffStatusSchema.describe("Diff status of this translation key"), - /** Object name if the key belongs to an object translation node */ - objectName: external_exports.string().optional().describe("Associated object name (snake_case)"), - /** Locale code */ - locale: external_exports.string().describe("BCP-47 locale code"), - /** - * Hash of the source metadata value at the time the translation was made. - * Used by CLI/Workbench to detect stale translations without a full diff. - */ - sourceHash: external_exports.string().optional().describe("Hash of source metadata for precise stale detection"), - /** - * AI-suggested translation text for missing or stale entries. - * Populated by AI translation hooks or TMS integrations. - */ - aiSuggested: external_exports.string().optional().describe("AI-suggested translation for this key"), - /** Confidence score (0-1) for the AI suggestion */ - aiConfidence: external_exports.number().min(0).max(1).optional().describe("AI suggestion confidence score (0\u20131)") -}).describe("A single translation diff item"); -var CoverageBreakdownEntrySchema = external_exports.object({ - /** Group category (e.g. "fields", "views", "actions", "messages") */ - group: external_exports.string().describe("Translation group category"), - /** Total translatable keys in this group */ - totalKeys: external_exports.number().int().nonnegative().describe("Total keys in this group"), - /** Number of translated keys in this group */ - translatedKeys: external_exports.number().int().nonnegative().describe("Translated keys in this group"), - /** Coverage percentage for this group */ - coveragePercent: external_exports.number().min(0).max(100).describe("Coverage percentage for this group") -}).describe("Coverage breakdown for a single translation group"); -var TranslationCoverageResultSchema = external_exports.object({ - /** BCP-47 locale code */ - locale: external_exports.string().describe("BCP-47 locale code"), - /** Optional object name scope */ - objectName: external_exports.string().optional().describe("Object name scope (omit for full bundle)"), - /** Total translatable keys derived from metadata */ - totalKeys: external_exports.number().int().nonnegative().describe("Total translatable keys from metadata"), - /** Number of keys that have a translation */ - translatedKeys: external_exports.number().int().nonnegative().describe("Number of translated keys"), - /** Number of missing translations */ - missingKeys: external_exports.number().int().nonnegative().describe("Number of missing translations"), - /** Number of redundant (orphaned) translations */ - redundantKeys: external_exports.number().int().nonnegative().describe("Number of redundant translations"), - /** Number of stale translations */ - staleKeys: external_exports.number().int().nonnegative().describe("Number of stale translations"), - /** Coverage percentage (0-100) */ - coveragePercent: external_exports.number().min(0).max(100).describe("Translation coverage percentage"), - /** Individual diff items */ - items: external_exports.array(TranslationDiffItemSchema).describe("Detailed diff items"), - /** - * Per-group coverage breakdown for translation project management. - * Each entry represents a logical group (e.g. "fields", "views", "actions", - * "messages") with its own coverage statistics. - */ - breakdown: external_exports.array(CoverageBreakdownEntrySchema).optional().describe("Per-group coverage breakdown") -}).describe("Aggregated translation coverage result"); -var OTOperationType = external_exports.enum([ - "insert", - // Insert characters at position - "delete", - // Delete characters at position - "retain" - // Keep characters (used for composing operations) -]); -var OTComponentSchema = external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("insert"), - text: external_exports.string().describe("Text to insert"), - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Text formatting attributes (e.g., bold, italic)") - }), - external_exports.object({ - type: external_exports.literal("delete"), - count: external_exports.number().int().positive().describe("Number of characters to delete") - }), - external_exports.object({ - type: external_exports.literal("retain"), - count: external_exports.number().int().positive().describe("Number of characters to retain"), - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Attribute changes to apply") - }) -]); -var OTOperationSchema = external_exports.object({ - operationId: external_exports.string().uuid().describe("Unique operation identifier"), - documentId: external_exports.string().describe("Document identifier"), - userId: external_exports.string().describe("User who created the operation"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - components: external_exports.array(OTComponentSchema).describe("Operation components"), - baseVersion: external_exports.number().int().nonnegative().describe("Document version this operation is based on"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when operation was created"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional operation metadata") -}); -var OTTransformResultSchema = external_exports.object({ - operation: OTOperationSchema.describe("Transformed operation"), - transformed: external_exports.boolean().describe("Whether transformation was applied"), - conflicts: external_exports.array(external_exports.string()).optional().describe("Conflict descriptions if any") -}); -var CRDTType = external_exports.enum([ - "lww-register", - // Last-Write-Wins Register - "g-counter", - // Grow-only Counter - "pn-counter", - // Positive-Negative Counter - "g-set", - // Grow-only Set - "or-set", - // Observed-Remove Set - "lww-map", - // Last-Write-Wins Map - "text", - // CRDT-based Text (e.g., Yjs, Automerge) - "tree", - // CRDT-based Tree structure - "json" - // CRDT-based JSON (e.g., Automerge) -]); -var VectorClockSchema = external_exports.object({ - clock: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Map of replica ID to logical timestamp") -}); -var LWWRegisterSchema = external_exports.object({ - type: external_exports.literal("lww-register"), - value: external_exports.unknown().describe("Current register value"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of last write"), - replicaId: external_exports.string().describe("ID of replica that performed last write"), - vectorClock: VectorClockSchema.optional().describe("Optional vector clock for causality tracking") -}); -var CounterOperationSchema = external_exports.object({ - replicaId: external_exports.string().describe("Replica identifier"), - delta: external_exports.number().int().describe("Change amount (positive for increment, negative for decrement)"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of operation") -}); -var GCounterSchema = external_exports.object({ - type: external_exports.literal("g-counter"), - counts: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Map of replica ID to count") -}); -var PNCounterSchema = external_exports.object({ - type: external_exports.literal("pn-counter"), - positive: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Positive increments per replica"), - negative: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Negative increments per replica") -}); -var ORSetElementSchema = external_exports.object({ - value: external_exports.unknown().describe("Element value"), - timestamp: external_exports.string().datetime().describe("Addition timestamp"), - replicaId: external_exports.string().describe("Replica that added the element"), - uid: external_exports.string().uuid().describe("Unique identifier for this addition"), - removed: external_exports.boolean().optional().default(false).describe("Whether element has been removed") -}); -var ORSetSchema = external_exports.object({ - type: external_exports.literal("or-set"), - elements: external_exports.array(ORSetElementSchema).describe("Set elements with metadata") -}); -var TextCRDTOperationSchema = external_exports.object({ - operationId: external_exports.string().uuid().describe("Unique operation identifier"), - replicaId: external_exports.string().describe("Replica identifier"), - position: external_exports.number().int().nonnegative().describe("Position in document"), - insert: external_exports.string().optional().describe("Text to insert"), - delete: external_exports.number().int().positive().optional().describe("Number of characters to delete"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of operation"), - lamportTimestamp: external_exports.number().int().nonnegative().describe("Lamport timestamp for ordering") -}); -var TextCRDTStateSchema = external_exports.object({ - type: external_exports.literal("text"), - documentId: external_exports.string().describe("Document identifier"), - content: external_exports.string().describe("Current text content"), - operations: external_exports.array(TextCRDTOperationSchema).describe("History of operations"), - lamportClock: external_exports.number().int().nonnegative().describe("Current Lamport clock value"), - vectorClock: VectorClockSchema.describe("Vector clock for causality") -}); -var CRDTStateSchema = external_exports.discriminatedUnion("type", [ - LWWRegisterSchema, - GCounterSchema, - PNCounterSchema, - ORSetSchema, - TextCRDTStateSchema -]); -var CRDTMergeResultSchema = external_exports.object({ - state: CRDTStateSchema.describe("Merged CRDT state"), - conflicts: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Conflict type"), - description: external_exports.string().describe("Conflict description"), - resolved: external_exports.boolean().describe("Whether conflict was automatically resolved") - })).optional().describe("Conflicts encountered during merge") -}); -var CursorColorPreset = external_exports.enum([ - "blue", - "green", - "red", - "yellow", - "purple", - "orange", - "pink", - "teal", - "indigo", - "cyan" -]); -var CursorStyleSchema = external_exports.object({ - color: external_exports.union([CursorColorPreset, external_exports.string()]).describe("Cursor color (preset or custom hex)"), - opacity: external_exports.number().min(0).max(1).optional().default(1).describe("Cursor opacity (0-1)"), - label: external_exports.string().optional().describe("Label to display with cursor (usually username)"), - showLabel: external_exports.boolean().optional().default(true).describe("Whether to show label"), - pulseOnUpdate: external_exports.boolean().optional().default(true).describe("Whether to pulse when cursor moves") -}); -var CursorSelectionSchema = external_exports.object({ - anchor: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Anchor line number"), - column: external_exports.number().int().nonnegative().describe("Anchor column number") - }).describe("Selection anchor (start point)"), - focus: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Focus line number"), - column: external_exports.number().int().nonnegative().describe("Focus column number") - }).describe("Selection focus (end point)"), - direction: external_exports.enum(["forward", "backward"]).optional().describe("Selection direction") -}); -var CollaborativeCursorSchema = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - documentId: external_exports.string().describe("Document identifier"), - userName: external_exports.string().describe("Display name of user"), - position: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Cursor line number (0-indexed)"), - column: external_exports.number().int().nonnegative().describe("Cursor column number (0-indexed)") - }).describe("Current cursor position"), - selection: CursorSelectionSchema.optional().describe("Current text selection"), - style: CursorStyleSchema.describe("Visual style for this cursor"), - isTyping: external_exports.boolean().optional().default(false).describe("Whether user is currently typing"), - lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last cursor update"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional cursor metadata") -}); -var CursorUpdateSchema = external_exports.object({ - position: external_exports.object({ - line: external_exports.number().int().nonnegative(), - column: external_exports.number().int().nonnegative() - }).optional().describe("Updated cursor position"), - selection: CursorSelectionSchema.optional().describe("Updated selection"), - isTyping: external_exports.boolean().optional().describe("Updated typing state"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") -}); -var UserActivityStatus = external_exports.enum([ - "active", - // User is actively editing - "idle", - // User is idle but connected - "viewing", - // User is viewing but not editing - "disconnected" - // User is disconnected -]); -var AwarenessUserStateSchema = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - userName: external_exports.string().describe("Display name"), - userAvatar: external_exports.string().optional().describe("User avatar URL"), - status: UserActivityStatus.describe("Current activity status"), - currentDocument: external_exports.string().optional().describe("Document ID user is currently editing"), - currentView: external_exports.string().optional().describe("Current view/page user is on"), - lastActivity: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), - joinedAt: external_exports.string().datetime().describe("ISO 8601 datetime when user joined session"), - permissions: external_exports.array(external_exports.string()).optional().describe("User permissions in this session"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional user state metadata") -}); -var AwarenessSessionSchema = external_exports.object({ - sessionId: external_exports.string().uuid().describe("Session identifier"), - documentId: external_exports.string().optional().describe("Document ID this session is for"), - users: external_exports.array(AwarenessUserStateSchema).describe("Active users in session"), - startedAt: external_exports.string().datetime().describe("ISO 8601 datetime when session started"), - lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last update"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Session metadata") -}); -var AwarenessUpdateSchema = external_exports.object({ - status: UserActivityStatus.optional().describe("Updated status"), - currentDocument: external_exports.string().optional().describe("Updated current document"), - currentView: external_exports.string().optional().describe("Updated current view"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") -}); -var AwarenessEventSchema = external_exports.object({ - eventId: external_exports.string().uuid().describe("Event identifier"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - eventType: external_exports.enum([ - "user.joined", - "user.left", - "user.updated", - "session.created", - "session.ended" - ]).describe("Type of awareness event"), - userId: external_exports.string().optional().describe("User involved in event"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of event"), - payload: external_exports.unknown().describe("Event payload") -}); -var CollaborationMode = external_exports.enum([ - "ot", - // Operational Transformation - "crdt", - // CRDT-based - "lock", - // Pessimistic locking (turn-based) - "hybrid" - // Hybrid approach -]); -var CollaborationSessionConfigSchema = external_exports.object({ - mode: CollaborationMode.describe("Collaboration mode to use"), - enableCursorSharing: external_exports.boolean().optional().default(true).describe("Enable cursor sharing"), - enablePresence: external_exports.boolean().optional().default(true).describe("Enable presence tracking"), - enableAwareness: external_exports.boolean().optional().default(true).describe("Enable awareness state"), - maxUsers: external_exports.number().int().positive().optional().describe("Maximum concurrent users"), - idleTimeout: external_exports.number().int().positive().optional().default(3e5).describe("Idle timeout in milliseconds"), - conflictResolution: external_exports.enum(["ot", "crdt", "manual"]).optional().default("ot").describe("Conflict resolution strategy"), - persistence: external_exports.boolean().optional().default(true).describe("Enable operation persistence"), - snapshot: external_exports.object({ - enabled: external_exports.boolean().describe("Enable periodic snapshots"), - interval: external_exports.number().int().positive().describe("Snapshot interval in milliseconds") - }).optional().describe("Snapshot configuration") -}); -var CollaborationSessionSchema = external_exports.object({ - sessionId: external_exports.string().uuid().describe("Session identifier"), - documentId: external_exports.string().describe("Document identifier"), - config: CollaborationSessionConfigSchema.describe("Session configuration"), - users: external_exports.array(AwarenessUserStateSchema).describe("Active users"), - cursors: external_exports.array(CollaborativeCursorSchema).describe("Active cursors"), - version: external_exports.number().int().nonnegative().describe("Current document version"), - operations: external_exports.array(external_exports.union([OTOperationSchema, TextCRDTOperationSchema])).optional().describe("Recent operations"), - createdAt: external_exports.string().datetime().describe("ISO 8601 datetime when session was created"), - lastActivity: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), - status: external_exports.enum(["active", "idle", "ended"]).describe("Session status") -}); -var MetadataScopeSchema = external_exports.enum([ - "system", - // Defined in Code (Files). Read-only at runtime. Upgraded via deployment. - "platform", - // Defined in DB (Global). admin-configured. Overrides system. - "user" - // Defined in DB (Personal). User-configured. Overrides platform/system. -]); -var MetadataStateSchema = external_exports.enum([ - "draft", - // Work in progress, not active - "active", - // Live and running - "archived", - // Soft deleted - "deprecated" - // Running but flagged for removal -]); -var MetadataRecordSchema = external_exports.object({ - /** Primary Key (UUID) */ - id: external_exports.string(), - /** - * Machine Name - * The unique identifier used in code references (e.g. "account_list_view"). - */ - name: external_exports.string(), - /** - * Metadata Type - * e.g. "object", "view", "permission_set", "flow" - */ - type: external_exports.string(), - /** - * Namespace / Module - * Groups metadata into packages (e.g. "crm", "finance", "core"). - */ - namespace: external_exports.string().default("default"), - /** - * Package Ownership Reference - * Links this metadata record to the package that delivered it. - * When set, the record is "managed" by the package and should not be - * directly edited — customizations go through the overlay system. - * Null/undefined means the record was created independently (not from a package). - */ - packageId: external_exports.string().optional().describe("Package ID that owns/delivered this metadata"), - /** - * Managed By Indicator - * Determines who controls this metadata record's lifecycle. - * - "package": Delivered and upgraded by a plugin package (read-only base) - * - "platform": Created by platform admin via UI - * - "user": Created by end user - */ - managedBy: external_exports.enum(["package", "platform", "user"]).optional().describe("Who manages this metadata record lifecycle"), - /** - * Ownership differentiation - */ - scope: MetadataScopeSchema.default("platform"), - /** - * The Payload - * Stores the actual configuration JSON. - * This field holds the value of `ViewSchema`, `ObjectSchema`, etc. - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()), - /** - * Extension / Merge Strategy - * If this record overrides a system record, how should it be applied? - */ - extends: external_exports.string().optional().describe("Name of the parent metadata to extend/override"), - strategy: external_exports.enum(["merge", "replace"]).default("merge"), - /** Owner (for user-scope items) */ - owner: external_exports.string().optional(), - /** State */ - state: MetadataStateSchema.default("active"), - /** Tenant ID for multi-tenant isolation */ - tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant isolation"), - /** Version number for optimistic concurrency */ - version: external_exports.number().default(1).describe("Record version for optimistic concurrency control"), - /** Checksum for change detection */ - checksum: external_exports.string().optional().describe("Content checksum for change detection"), - /** Source origin marker */ - source: external_exports.enum(["filesystem", "database", "api", "migration"]).optional().describe("Origin of this metadata record"), - /** Classification tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Classification tags for filtering and grouping"), - /** Package Publishing */ - publishedDefinition: external_exports.unknown().optional().describe("Snapshot of the last published definition"), - publishedAt: external_exports.string().datetime().optional().describe("When this metadata was last published"), - publishedBy: external_exports.string().optional().describe("Who published this version"), - /** Audit */ - createdBy: external_exports.string().optional(), - createdAt: external_exports.string().datetime().optional().describe("Creation timestamp"), - updatedBy: external_exports.string().optional(), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp") -}); -var PackagePublishResultSchema = external_exports.object({ - success: external_exports.boolean().describe("Whether the publish succeeded"), - packageId: external_exports.string().describe("The package ID that was published"), - version: external_exports.number().int().describe("New version number after publish"), - publishedAt: external_exports.string().datetime().describe("Publish timestamp"), - itemsPublished: external_exports.number().int().describe("Total metadata items published"), - validationErrors: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type that failed validation"), - name: external_exports.string().describe("Item name that failed validation"), - message: external_exports.string().describe("Validation error message") - })).optional().describe("Validation errors if publish failed") -}); -var MetadataFormatSchema = external_exports.enum([ - "json", - "yaml", - "yml", - "ts", - "js", - "typescript", - "javascript" - // Aliases -]); -var MetadataStatsSchema = external_exports.object({ - path: external_exports.string().optional(), - size: external_exports.number().optional(), - mtime: external_exports.string().datetime().optional(), - hash: external_exports.string().optional(), - etag: external_exports.string().optional(), - // Required by local cache - modifiedAt: external_exports.string().datetime().optional(), - // Alias for mtime - format: MetadataFormatSchema.optional() - // Required for serialization -}); -var MetadataLoaderContractSchema = external_exports.object({ - name: external_exports.string(), - protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Loader protocol identifier"), - description: external_exports.string().optional(), - supportedFormats: external_exports.array(external_exports.string()).optional(), - supportsWatch: external_exports.boolean().optional(), - supportsWrite: external_exports.boolean().optional(), - supportsCache: external_exports.boolean().optional(), - capabilities: external_exports.object({ - read: external_exports.boolean().default(true), - write: external_exports.boolean().default(false), - watch: external_exports.boolean().default(false), - list: external_exports.boolean().default(true) - }) -}); -var MetadataLoadOptionsSchema = external_exports.object({ - scope: MetadataScopeSchema.optional(), - namespace: external_exports.string().optional(), - raw: external_exports.boolean().optional().describe("Return raw file content instead of parsed JSON"), - cache: external_exports.boolean().optional(), - useCache: external_exports.boolean().optional(), - // Alias for cache - validate: external_exports.boolean().optional(), - ifNoneMatch: external_exports.string().optional(), - // For caching - recursive: external_exports.boolean().optional(), - limit: external_exports.number().optional(), - patterns: external_exports.array(external_exports.string()).optional(), - loader: external_exports.string().optional().describe("Specific loader to use (e.g. filesystem, database)") -}); -var MetadataLoadResultSchema = external_exports.object({ - data: external_exports.unknown(), - stats: MetadataStatsSchema.optional(), - format: MetadataFormatSchema.optional(), - source: external_exports.string().optional(), - // File path or URL - fromCache: external_exports.boolean().optional(), - etag: external_exports.string().optional(), - notModified: external_exports.boolean().optional(), - loadTime: external_exports.number().optional() -}); -var MetadataSaveOptionsSchema = external_exports.object({ - format: MetadataFormatSchema.optional(), - create: external_exports.boolean().default(true), - overwrite: external_exports.boolean().default(true), - path: external_exports.string().optional(), - prettify: external_exports.boolean().optional(), - indent: external_exports.number().optional(), - sortKeys: external_exports.boolean().optional(), - backup: external_exports.boolean().optional(), - atomic: external_exports.boolean().optional(), - loader: external_exports.string().optional().describe("Specific loader to use (e.g. filesystem, database)") -}); -var MetadataSaveResultSchema = external_exports.object({ - success: external_exports.boolean(), - path: external_exports.string().optional(), - stats: MetadataStatsSchema.optional(), - etag: external_exports.string().optional(), - size: external_exports.number().optional(), - saveTime: external_exports.number().optional(), - backupPath: external_exports.string().optional() -}); -var MetadataWatchEventSchema = external_exports.object({ - type: external_exports.enum(["add", "change", "unlink", "added", "changed", "deleted"]), - path: external_exports.string(), - name: external_exports.string().optional(), - stats: MetadataStatsSchema.optional(), - metadataType: external_exports.string().optional(), - data: external_exports.unknown().optional(), - timestamp: external_exports.string().datetime().optional() -}); -var MetadataCollectionInfoSchema = external_exports.object({ - type: external_exports.string(), - count: external_exports.number(), - namespaces: external_exports.array(external_exports.string()) -}); -var MetadataExportOptionsSchema = external_exports.object({ - types: external_exports.array(external_exports.string()).optional(), - namespaces: external_exports.array(external_exports.string()).optional(), - output: external_exports.string().describe("Output directory or file"), - format: MetadataFormatSchema.default("json") -}); -var MetadataImportOptionsSchema = external_exports.object({ - source: external_exports.string().describe("Input directory or file"), - strategy: external_exports.enum(["merge", "replace", "skip"]).default("merge"), - validate: external_exports.boolean().default(true) -}); -var MetadataFallbackStrategySchema = external_exports.enum([ - "filesystem", - // Fall back to filesystem-based loading - "memory", - // Fall back to in-memory storage - "none" - // No fallback — fail immediately -]); -var MetadataSourceSchema = external_exports.enum([ - "filesystem", - // Loaded from local files - "database", - // Loaded from database via datasource - "api", - // Loaded from remote API - "migration" - // Created during a migration process -]); -var MetadataManagerConfigSchema = external_exports.object({ - /** - * Datasource Name Reference - * References a DatasourceSchema.name (e.g. 'default'). - * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. - * When provided, metadata is persisted to a database table. - */ - datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), - /** - * Metadata Table Name - * The database table used for metadata storage when datasource is configured. - */ - tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), - /** - * Fallback Strategy - * Determines behavior when the primary datasource is unavailable. - */ - fallback: MetadataFallbackStrategySchema.default("none").describe("Fallback strategy when datasource is unavailable"), - /** - * Root directory for metadata (for filesystem loaders) - */ - rootDir: external_exports.string().optional().describe("Root directory for filesystem-based metadata"), - /** - * Enabled serialization formats - */ - formats: external_exports.array(MetadataFormatSchema).optional().describe("Enabled metadata formats"), - /** - * Enable file watching - */ - watch: external_exports.boolean().optional().describe("Enable file watching for filesystem loaders"), - /** - * Cache configuration - */ - cache: external_exports.boolean().optional().describe("Enable metadata caching"), - /** - * Watch options - */ - watchOptions: external_exports.object({ - ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), - persistent: external_exports.boolean().default(true).describe("Keep process running") - }).optional().describe("File watcher options") -}); -var MetadataHistoryRecordSchema = external_exports.object({ - /** Primary Key (UUID) */ - id: external_exports.string(), - /** Reference to the parent metadata record ID */ - metadataId: external_exports.string().describe("Foreign key to sys_metadata.id"), - /** - * Machine Name - * Denormalized from parent for easier querying. - */ - name: external_exports.string(), - /** - * Metadata Type - * Denormalized from parent for easier querying. - */ - type: external_exports.string(), - /** - * Version Number - * Snapshot of the metadata version at this point in history. - */ - version: external_exports.number().describe("Version number at this snapshot"), - /** - * Operation Type - * Indicates what kind of change triggered this history record. - */ - operationType: external_exports.enum(["create", "update", "publish", "revert", "delete"]).describe("Type of operation that created this history entry"), - /** - * Historical Metadata Snapshot - * Full JSON payload of the metadata definition at this version. - * May be stored as a raw JSON string in the history table, or as a parsed object - * in higher-level APIs. When `includeMetadata` is false, this field is null. - */ - metadata: external_exports.union([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown())]).nullable().optional().describe("Snapshot of metadata definition at this version (raw JSON string or parsed object)"), - /** - * Content Checksum - * SHA-256 checksum of the normalized metadata JSON for change detection. - */ - checksum: external_exports.string().describe("SHA-256 checksum of metadata content"), - /** - * Previous Checksum - * Checksum of the previous version for diff optimization. - */ - previousChecksum: external_exports.string().optional().describe("Checksum of the previous version"), - /** - * Change Note - * Human-readable description of what changed in this version. - */ - changeNote: external_exports.string().optional().describe("Description of changes made in this version"), - /** Tenant ID for multi-tenant isolation */ - tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant isolation"), - /** Audit: who made this change */ - recordedBy: external_exports.string().optional().describe("User who made this change"), - /** Audit: when was this version recorded */ - recordedAt: external_exports.string().datetime().describe("Timestamp when this version was recorded") -}); -var MetadataHistoryQueryOptionsSchema = external_exports.object({ - /** Limit number of history records returned */ - limit: external_exports.number().int().positive().optional().describe("Maximum number of history records to return"), - /** Offset for pagination */ - offset: external_exports.number().int().nonnegative().optional().describe("Number of records to skip"), - /** Only return versions after this timestamp */ - since: external_exports.string().datetime().optional().describe("Only return history after this timestamp"), - /** Only return versions before this timestamp */ - until: external_exports.string().datetime().optional().describe("Only return history before this timestamp"), - /** Filter by operation type */ - operationType: external_exports.enum(["create", "update", "publish", "revert", "delete"]).optional().describe("Filter by operation type"), - /** Include full metadata payload in results (default: true) */ - includeMetadata: external_exports.boolean().optional().default(true).describe("Include full metadata payload") -}); -var MetadataHistoryQueryResultSchema = external_exports.object({ - /** Array of history records */ - records: external_exports.array(MetadataHistoryRecordSchema), - /** Total number of history records (for pagination) */ - total: external_exports.number().int().nonnegative(), - /** Whether there are more records available */ - hasMore: external_exports.boolean() -}); -var MetadataDiffResultSchema = external_exports.object({ - /** Metadata type */ - type: external_exports.string(), - /** Metadata name */ - name: external_exports.string(), - /** Version 1 (older) */ - version1: external_exports.number(), - /** Version 2 (newer) */ - version2: external_exports.number(), - /** Checksum of version 1 */ - checksum1: external_exports.string(), - /** Checksum of version 2 */ - checksum2: external_exports.string(), - /** Whether the versions are identical */ - identical: external_exports.boolean(), - /** JSON patch operations to transform v1 into v2 */ - patch: external_exports.array(external_exports.unknown()).optional().describe("JSON patch operations"), - /** Human-readable diff summary */ - summary: external_exports.string().optional().describe("Human-readable summary of changes") -}); -var MetadataHistoryRetentionPolicySchema = external_exports.object({ - /** Maximum number of versions to keep per metadata item */ - maxVersions: external_exports.number().int().positive().optional().describe("Maximum number of versions to retain"), - /** Maximum age of history records in days */ - maxAgeDays: external_exports.number().int().positive().optional().describe("Maximum age of history records in days"), - /** Whether to enable automatic cleanup */ - autoCleanup: external_exports.boolean().default(false).describe("Enable automatic cleanup of old history"), - /** Cleanup interval in hours */ - cleanupIntervalHours: external_exports.number().int().positive().default(24).describe("How often to run cleanup (in hours)") -}); -var CoreServiceName = external_exports.enum([ - // Core Data & Metadata - "metadata", - // Object/Field Definitions - "data", - // CRUD & Query Engine - "auth", - // Authentication & Identity - // Infrastructure - "file-storage", - // Storage Driver (Local/S3) - "search", - // Search Engine (Elastic/Meili) - "cache", - // Cache Driver (Redis/Memory) - "queue", - // Job Queue (BullMQ/Redis) - // Advanced Capabilities - "automation", - // Flow & Script Engine - "graphql", - // GraphQL API Engine - "analytics", - // BI & Semantic Layer - "realtime", - // WebSocket & PubSub - "job", - // Background Job Manager - "notification", - // Email/Push/SMS - "ai", - // AI Engine (NLQ, Chat, Suggest, Insights) - "i18n", - // Internationalization Service - "ui", - // UI Metadata Service (View CRUD) - "workflow" - // Workflow State Machine Engine -]); -var ServiceCriticalitySchema = external_exports.enum([ - "required", - // System fails to start if missing (Exit Code 1) - "core", - // System warns if missing, functionality degraded (Warn) - "optional" - // System ignores if missing, feature disabled (Info) -]); -var ServiceRequirementDef = { - // Required: The kernel cannot function without these - data: "required", - // Core: Highly recommended, defaults to in-memory / no-op if missing - metadata: "core", - auth: "core", - // Core: Highly recommended, defaults to in-memory / no-op if missing - cache: "core", - queue: "core", - job: "core", - i18n: "core", - // Optional: Add-on capabilities - "file-storage": "optional", - search: "optional", - automation: "optional", - graphql: "optional", - analytics: "optional", - realtime: "optional", - notification: "optional", - ai: "optional", - ui: "optional", - workflow: "optional" -}; -var ServiceStatusSchema = external_exports.object({ - name: CoreServiceName, - enabled: external_exports.boolean(), - status: external_exports.enum(["running", "stopped", "degraded", "initializing"]), - version: external_exports.string().optional(), - provider: external_exports.string().optional().describe('Implementation provider (e.g. "s3" for storage)'), - features: external_exports.array(external_exports.string()).optional().describe("List of supported sub-features") -}); -var KernelServiceMapSchema = external_exports.record( - CoreServiceName, - external_exports.unknown().describe("Service Instance implementing the protocol interface") -); -var ServiceConfigSchema = external_exports.object({ - id: external_exports.string(), - name: CoreServiceName, - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var TenantIsolationLevel = external_exports.enum([ - "shared_schema", - // Shared DB, shared schema, row-level isolation (most economical) - "isolated_schema", - // Shared DB, separate schema per tenant (balanced) - "isolated_db" - // Separate database per tenant (maximum isolation) -]); -var DatabaseProviderSchema = external_exports.enum([ - "turso", - // Turso/libSQL (DB-per-Tenant, edge-native) - "postgres", - // PostgreSQL (traditional, self-hosted or managed) - "memory" - // In-memory (testing/development only) -]).describe("Database provider for tenant data"); -var TenantConnectionConfigSchema = external_exports.object({ - /** Database connection URL */ - url: external_exports.string().min(1).describe("Database connection URL"), - /** Authentication token (JWT for Turso, password for Postgres) */ - authToken: external_exports.string().optional().describe("Database auth token (encrypted at rest)"), - /** Turso database group name */ - group: external_exports.string().optional().describe("Turso database group name") -}).describe("Tenant database connection configuration"); -var TenantQuotaSchema = external_exports.object({ - /** - * Maximum number of users allowed for this tenant - */ - maxUsers: external_exports.number().int().positive().optional().describe("Maximum number of users"), - /** - * Maximum storage space in bytes - */ - maxStorage: external_exports.number().int().positive().optional().describe("Maximum storage in bytes"), - /** - * API rate limit (requests per minute) - */ - apiRateLimit: external_exports.number().int().positive().optional().describe("API requests per minute"), - /** - * Maximum number of custom objects the tenant can create - */ - maxObjects: external_exports.number().int().positive().optional().describe("Maximum number of custom objects"), - /** - * Maximum records per object/table - */ - maxRecordsPerObject: external_exports.number().int().positive().optional().describe("Maximum records per object"), - /** - * Maximum deployments allowed per day - */ - maxDeploymentsPerDay: external_exports.number().int().positive().optional().describe("Maximum deployments per day"), - /** - * Maximum storage in bytes - */ - maxStorageBytes: external_exports.number().int().positive().optional().describe("Maximum storage in bytes") -}); -var TenantUsageSchema = external_exports.object({ - /** Current number of custom objects */ - currentObjectCount: external_exports.number().int().min(0).default(0).describe("Current number of custom objects"), - /** Current total record count across all objects */ - currentRecordCount: external_exports.number().int().min(0).default(0).describe("Total records across all objects"), - /** Current storage usage in bytes */ - currentStorageBytes: external_exports.number().int().min(0).default(0).describe("Current storage usage in bytes"), - /** Deployments executed today */ - deploymentsToday: external_exports.number().int().min(0).default(0).describe("Deployments executed today"), - /** Current number of active users */ - currentUsers: external_exports.number().int().min(0).default(0).describe("Current number of active users"), - /** API requests in the current minute */ - apiRequestsThisMinute: external_exports.number().int().min(0).default(0).describe("API requests in the current minute"), - /** Last updated timestamp (ISO 8601) */ - lastUpdatedAt: external_exports.string().datetime().optional().describe("Last usage update time") -}).describe("Current tenant resource usage"); -var QuotaEnforcementResultSchema = external_exports.object({ - /** Whether the operation is allowed */ - allowed: external_exports.boolean().describe("Whether the operation is within quota"), - /** Quota that would be exceeded (if not allowed) */ - exceededQuota: external_exports.string().optional().describe("Name of the exceeded quota"), - /** Current usage value */ - currentUsage: external_exports.number().optional().describe("Current usage value"), - /** Quota limit value */ - limit: external_exports.number().optional().describe("Quota limit"), - /** Human-readable message */ - message: external_exports.string().optional().describe("Human-readable quota message") -}).describe("Quota enforcement check result"); -var TenantSchema = external_exports.object({ - /** - * Unique tenant identifier - */ - id: external_exports.string().describe("Unique tenant identifier"), - /** - * Tenant display name - */ - name: external_exports.string().describe("Tenant display name"), - /** - * Data isolation level - */ - isolationLevel: TenantIsolationLevel, - /** - * Database provider for this tenant - */ - databaseProvider: DatabaseProviderSchema.optional().describe("Database provider"), - /** - * Database connection configuration (encrypted at rest) - */ - connectionConfig: TenantConnectionConfigSchema.optional().describe("Database connection config"), - /** - * Current provisioning status - */ - provisioningStatus: external_exports.enum([ - "provisioning", - "active", - "suspended", - "failed", - "destroying" - ]).optional().describe("Current provisioning lifecycle status"), - /** - * Tenant subscription plan - */ - plan: external_exports.enum(["free", "pro", "enterprise"]).optional().describe("Subscription plan"), - /** - * Custom configuration values - */ - customizations: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom configuration values"), - /** - * Resource quotas - */ - quotas: TenantQuotaSchema.optional() -}); -var RowLevelIsolationStrategySchema = external_exports.object({ - strategy: external_exports.literal("shared_schema").describe("Row-level isolation strategy"), - /** - * Database configuration for row-level isolation - */ - database: external_exports.object({ - /** - * Whether to enable Row-Level Security (RLS) - */ - enableRLS: external_exports.boolean().default(true).describe("Enable PostgreSQL Row-Level Security"), - /** - * Tenant context setting method - */ - contextMethod: external_exports.enum([ - "session_variable", - // SET app.current_tenant = 'tenant_123' - "search_path", - // SET search_path = tenant_123, public - "application_name" - // SET application_name = 'tenant_123' - ]).default("session_variable").describe("How to set tenant context"), - /** - * Session variable name for tenant context - */ - contextVariable: external_exports.string().default("app.current_tenant").describe("Session variable name"), - /** - * Whether to validate tenant_id at application level - */ - applicationValidation: external_exports.boolean().default(true).describe("Application-level tenant validation") - }).optional().describe("Database configuration"), - /** - * Performance optimization settings - */ - performance: external_exports.object({ - /** - * Whether to use partial indexes for tenant_id - */ - usePartialIndexes: external_exports.boolean().default(true).describe("Use partial indexes per tenant"), - /** - * Whether to use table partitioning - */ - usePartitioning: external_exports.boolean().default(false).describe("Use table partitioning by tenant_id"), - /** - * Connection pool size per tenant - */ - poolSizePerTenant: external_exports.number().int().positive().optional().describe("Connection pool size per tenant") - }).optional().describe("Performance settings") -}); -var SchemaLevelIsolationStrategySchema = external_exports.object({ - strategy: external_exports.literal("isolated_schema").describe("Schema-level isolation strategy"), - /** - * Schema configuration - */ - schema: external_exports.object({ - /** - * Schema naming pattern - * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) - * The tenant_id will be sanitized before substitution to prevent SQL injection - */ - namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Schema naming pattern"), - /** - * Whether to include public schema in search_path - */ - includePublicSchema: external_exports.boolean().default(true).describe("Include public schema"), - /** - * Default schema for shared resources - */ - sharedSchema: external_exports.string().default("public").describe("Schema for shared resources"), - /** - * Whether to automatically create schema on tenant creation - */ - autoCreateSchema: external_exports.boolean().default(true).describe("Auto-create schema") - }).optional().describe("Schema configuration"), - /** - * Migration configuration - */ - migrations: external_exports.object({ - /** - * Migration strategy - */ - strategy: external_exports.enum([ - "parallel", - // Run migrations on all schemas in parallel - "sequential", - // Run migrations one schema at a time - "on_demand" - // Run migrations when tenant accesses system - ]).default("parallel").describe("Migration strategy"), - /** - * Maximum concurrent migrations - */ - maxConcurrent: external_exports.number().int().positive().default(10).describe("Max concurrent migrations"), - /** - * Whether to rollback on first failure - */ - rollbackOnError: external_exports.boolean().default(true).describe("Rollback on error") - }).optional().describe("Migration configuration"), - /** - * Performance optimization settings - */ - performance: external_exports.object({ - /** - * Whether to use connection pooling per schema - */ - poolPerSchema: external_exports.boolean().default(false).describe("Separate pool per schema"), - /** - * Schema cache TTL in seconds - */ - schemaCacheTTL: external_exports.number().int().positive().default(3600).describe("Schema cache TTL") - }).optional().describe("Performance settings") -}); -var DatabaseLevelIsolationStrategySchema = external_exports.object({ - strategy: external_exports.literal("isolated_db").describe("Database-level isolation strategy"), - /** - * Database configuration - */ - database: external_exports.object({ - /** - * Database naming pattern - * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) - * The tenant_id will be sanitized before substitution to prevent SQL injection - */ - namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Database naming pattern"), - /** - * Database server/cluster assignment strategy - */ - serverStrategy: external_exports.enum([ - "shared", - // All tenant databases on same server - "sharded", - // Tenant databases distributed across servers - "dedicated" - // Each tenant gets dedicated server (enterprise) - ]).default("shared").describe("Server assignment strategy"), - /** - * Whether to use separate credentials per tenant - */ - separateCredentials: external_exports.boolean().default(true).describe("Separate credentials per tenant"), - /** - * Whether to automatically create database on tenant creation - */ - autoCreateDatabase: external_exports.boolean().default(true).describe("Auto-create database") - }).optional().describe("Database configuration"), - /** - * Connection pooling configuration - */ - connectionPool: external_exports.object({ - /** - * Pool size per tenant database - */ - poolSize: external_exports.number().int().positive().default(10).describe("Connection pool size"), - /** - * Maximum number of tenant pools to keep active - */ - maxActivePools: external_exports.number().int().positive().default(100).describe("Max active pools"), - /** - * Idle pool timeout in seconds - */ - idleTimeout: external_exports.number().int().positive().default(300).describe("Idle pool timeout"), - /** - * Whether to use connection pooler (PgBouncer, etc.) - */ - usePooler: external_exports.boolean().default(true).describe("Use connection pooler") - }).optional().describe("Connection pool configuration"), - /** - * Backup and restore configuration - */ - backup: external_exports.object({ - /** - * Backup strategy per tenant - */ - strategy: external_exports.enum([ - "individual", - // Separate backup per tenant - "consolidated", - // Combined backup with all tenants - "on_demand" - // Backup only when requested - ]).default("individual").describe("Backup strategy"), - /** - * Backup frequency in hours - */ - frequencyHours: external_exports.number().int().positive().default(24).describe("Backup frequency"), - /** - * Retention period in days - */ - retentionDays: external_exports.number().int().positive().default(30).describe("Backup retention days") - }).optional().describe("Backup configuration"), - /** - * Encryption configuration - */ - encryption: external_exports.object({ - /** - * Whether to use per-tenant encryption keys - */ - perTenantKeys: external_exports.boolean().default(false).describe("Per-tenant encryption keys"), - /** - * Encryption algorithm - */ - algorithm: external_exports.string().default("AES-256-GCM").describe("Encryption algorithm"), - /** - * Key management service - */ - keyManagement: external_exports.enum(["aws_kms", "azure_key_vault", "gcp_kms", "hashicorp_vault", "custom"]).optional().describe("Key management service") - }).optional().describe("Encryption configuration") -}); -var TenantIsolationConfigSchema = external_exports.discriminatedUnion("strategy", [ - RowLevelIsolationStrategySchema, - SchemaLevelIsolationStrategySchema, - DatabaseLevelIsolationStrategySchema -]); -var TenantSecurityPolicySchema = external_exports.object({ - /** - * Encryption requirements - */ - encryption: external_exports.object({ - /** - * Require encryption at rest - */ - atRest: external_exports.boolean().default(true).describe("Require encryption at rest"), - /** - * Require encryption in transit - */ - inTransit: external_exports.boolean().default(true).describe("Require encryption in transit"), - /** - * Require field-level encryption for sensitive data - */ - fieldLevel: external_exports.boolean().default(false).describe("Require field-level encryption") - }).optional().describe("Encryption requirements"), - /** - * Access control requirements - */ - accessControl: external_exports.object({ - /** - * Require multi-factor authentication - */ - requireMFA: external_exports.boolean().default(false).describe("Require MFA"), - /** - * Require SSO/SAML authentication - */ - requireSSO: external_exports.boolean().default(false).describe("Require SSO"), - /** - * IP whitelist - */ - ipWhitelist: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses"), - /** - * Session timeout in seconds - */ - sessionTimeout: external_exports.number().int().positive().default(3600).describe("Session timeout") - }).optional().describe("Access control requirements"), - /** - * Audit and compliance requirements - */ - compliance: external_exports.object({ - /** - * Compliance standards to enforce - */ - standards: external_exports.array(external_exports.enum([ - "sox", - "hipaa", - "gdpr", - "pci_dss", - "iso_27001", - "fedramp" - ])).optional().describe("Compliance standards"), - /** - * Require audit logging for all operations - */ - requireAuditLog: external_exports.boolean().default(true).describe("Require audit logging"), - /** - * Audit log retention period in days - */ - auditRetentionDays: external_exports.number().int().positive().default(365).describe("Audit retention days"), - /** - * Data residency requirements - */ - dataResidency: external_exports.object({ - /** - * Required geographic region - */ - region: external_exports.string().optional().describe("Required region (e.g., US, EU, APAC)"), - /** - * Prohibited regions - */ - excludeRegions: external_exports.array(external_exports.string()).optional().describe("Prohibited regions") - }).optional().describe("Data residency requirements") - }).optional().describe("Compliance requirements") -}); -var LicenseMetricType = external_exports.enum([ - "boolean", - // Feature Flag (Enabled/Disabled) - "counter", - // Usage Count (e.g. API Calls, Records Created) - Accumulates - "gauge" - // Current Level (e.g. Storage Used, Users Active) - Point in time -]).describe("License metric type"); -var FeatureSchema = external_exports.object({ - code: external_exports.string().regex(/^[a-z_][a-z0-9_.]*$/).describe("Feature code (e.g. core.api_access)"), - label: external_exports.string(), - description: external_exports.string().optional(), - type: LicenseMetricType.default("boolean"), - /** For counters/gauges */ - unit: external_exports.enum(["count", "bytes", "seconds", "percent"]).optional(), - /** Dependencies (e.g. 'audit_log' requires 'enterprise_tier') */ - requires: external_exports.array(external_exports.string()).optional() -}); -var PlanSchema = external_exports.object({ - code: external_exports.string().describe("Plan code (e.g. pro_v1)"), - label: external_exports.string(), - active: external_exports.boolean().default(true), - /** Feature Entitlements */ - features: external_exports.array(external_exports.string()).describe("List of enabled boolean features"), - /** Limit Quotas */ - limits: external_exports.record(external_exports.string(), external_exports.number()).describe("Map of metric codes to limit values (e.g. { storage_gb: 10 })"), - /** Pricing (Optional Metadata) */ - currency: external_exports.string().default("USD").optional(), - priceMonthly: external_exports.number().optional(), - priceYearly: external_exports.number().optional() -}); -var LicenseSchema = external_exports.object({ - /** Identity */ - spaceId: external_exports.string().describe("Target Space ID"), - planCode: external_exports.string(), - /** Validity */ - issuedAt: external_exports.string().datetime(), - expiresAt: external_exports.string().datetime().optional(), - // Null = Perpetual - /** Status */ - status: external_exports.enum(["active", "expired", "suspended", "trial"]), - /** Overrides (Specific to this space, exceeding the plan) */ - customFeatures: external_exports.array(external_exports.string()).optional(), - customLimits: external_exports.record(external_exports.string(), external_exports.number()).optional(), - /** Authorized Add-ons */ - plugins: external_exports.array(external_exports.string()).optional().describe("List of enabled plugin package IDs"), - /** Signature */ - signature: external_exports.string().optional().describe("Cryptographic signature of the license") -}); -var RegistrySyncPolicySchema = external_exports.enum([ - "manual", - // Manual synchronization only - "auto", - // Automatic synchronization - "proxy" - // Proxy requests to upstream without caching -]).describe("Registry synchronization strategy"); -var RegistryUpstreamSchema = external_exports.object({ - /** - * Upstream registry URL - */ - url: external_exports.string().url().describe("Upstream registry endpoint"), - /** - * Synchronization policy - */ - syncPolicy: RegistrySyncPolicySchema.default("auto"), - /** - * Sync interval in seconds (for auto sync) - */ - syncInterval: external_exports.number().int().min(60).optional().describe("Auto-sync interval in seconds"), - /** - * Authentication credentials - */ - auth: external_exports.object({ - type: external_exports.enum(["none", "basic", "bearer", "api-key", "oauth2"]).default("none"), - username: external_exports.string().optional(), - password: external_exports.string().optional(), - token: external_exports.string().optional(), - apiKey: external_exports.string().optional() - }).optional(), - /** - * TLS/SSL configuration - */ - tls: external_exports.object({ - enabled: external_exports.boolean().default(true), - verifyCertificate: external_exports.boolean().default(true), - certificate: external_exports.string().optional(), - privateKey: external_exports.string().optional() - }).optional(), - /** - * Timeout settings - */ - timeout: external_exports.number().int().min(1e3).default(3e4).describe("Request timeout in milliseconds"), - /** - * Retry configuration - */ - retry: external_exports.object({ - maxAttempts: external_exports.number().int().min(0).default(3), - backoff: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential") - }).optional() -}); -var RegistryConfigSchema = external_exports.object({ - /** - * Registry type - */ - type: external_exports.enum([ - "public", - // Public marketplace (e.g., plugins.objectstack.com) - "private", - // Private enterprise registry - "hybrid" - // Hybrid with upstream federation - ]).describe("Registry deployment type"), - /** - * Upstream registries (for hybrid/private registries) - */ - upstream: external_exports.array(RegistryUpstreamSchema).optional().describe("Upstream registries to sync from or proxy to"), - /** - * Scopes managed by this registry - */ - scope: external_exports.array(external_exports.string()).optional().describe("npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)"), - /** - * Default scope for new plugins - */ - defaultScope: external_exports.string().optional().describe("Default scope prefix for new plugins"), - /** - * Registry storage configuration - */ - storage: external_exports.object({ - /** - * Storage backend type - */ - backend: external_exports.enum(["local", "s3", "gcs", "azure-blob", "oss"]).default("local"), - /** - * Storage path or bucket name - */ - path: external_exports.string().optional(), - /** - * Credentials - */ - credentials: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional(), - /** - * Registry visibility - */ - visibility: external_exports.enum(["public", "private", "internal"]).default("private").describe("Who can access this registry"), - /** - * Access control - */ - accessControl: external_exports.object({ - /** - * Require authentication for read - */ - requireAuthForRead: external_exports.boolean().default(false), - /** - * Require authentication for write - */ - requireAuthForWrite: external_exports.boolean().default(true), - /** - * Allowed users/teams - */ - allowedPrincipals: external_exports.array(external_exports.string()).optional() - }).optional(), - /** - * Caching configuration - */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(true), - ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), - maxSize: external_exports.number().int().optional().describe("Maximum cache size in bytes") - }).optional(), - /** - * Mirroring configuration (for high availability) - */ - mirrors: external_exports.array(external_exports.object({ - url: external_exports.string().url(), - priority: external_exports.number().int().min(1).default(1) - })).optional().describe("Mirror registries for redundancy") -}); -var TenantProvisioningStatusEnum = external_exports.enum([ - "provisioning", - // Database creation in progress - "active", - // Fully provisioned and operational - "suspended", - // Temporarily disabled (billing, policy) - "failed", - // Provisioning failed (requires retry or manual intervention) - "destroying" - // Deletion in progress -]).describe("Tenant provisioning lifecycle status"); -var TenantPlanSchema = external_exports.enum([ - "free", - // Free tier with limited quotas - "pro", - // Professional tier with higher quotas - "enterprise" - // Enterprise tier with custom quotas and SLAs -]).describe("Tenant subscription plan"); -var TenantRegionSchema = external_exports.enum([ - "us-east", - // US East (Virginia) - "us-west", - // US West (Oregon) - "eu-west", - // EU West (Ireland) - "eu-central", - // EU Central (Frankfurt) - "ap-southeast", - // Asia Pacific (Singapore) - "ap-northeast" - // Asia Pacific (Tokyo) -]).describe("Available deployment region"); -var ProvisioningStepSchema = external_exports.object({ - /** Step identifier */ - name: external_exports.string().min(1).describe("Step name (e.g., create_database, sync_schema)"), - /** Step execution status */ - status: external_exports.enum(["pending", "running", "completed", "failed", "skipped"]).describe("Step status"), - /** When the step started (ISO 8601) */ - startedAt: external_exports.string().datetime().optional().describe("Step start time"), - /** When the step completed (ISO 8601) */ - completedAt: external_exports.string().datetime().optional().describe("Step completion time"), - /** Duration in milliseconds */ - durationMs: external_exports.number().int().min(0).optional().describe("Step duration in ms"), - /** Error message if the step failed */ - error: external_exports.string().optional().describe("Error message on failure") -}).describe("Individual provisioning step status"); -var TenantProvisioningRequestSchema = external_exports.object({ - /** Organization ID that owns this tenant */ - orgId: external_exports.string().min(1).describe("Organization ID"), - /** Requested subscription plan */ - plan: TenantPlanSchema.default("free"), - /** Preferred deployment region */ - region: TenantRegionSchema.default("us-east"), - /** Optional tenant display name */ - displayName: external_exports.string().optional().describe("Tenant display name"), - /** Optional initial admin user email */ - adminEmail: external_exports.string().email().optional().describe("Initial admin user email"), - /** Optional metadata to attach to the tenant */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata") -}).describe("Tenant provisioning request"); -var TenantProvisioningResultSchema = external_exports.object({ - /** Unique tenant identifier */ - tenantId: external_exports.string().min(1).describe("Provisioned tenant ID"), - /** Database connection URL (libsql:// or https://) */ - connectionUrl: external_exports.string().min(1).describe("Database connection URL"), - /** Current provisioning status */ - status: TenantProvisioningStatusEnum, - /** Deployment region */ - region: TenantRegionSchema, - /** Active subscription plan */ - plan: TenantPlanSchema, - /** Provisioning pipeline steps with status */ - steps: external_exports.array(ProvisioningStepSchema).default([]).describe("Pipeline step statuses"), - /** Total provisioning duration in milliseconds */ - totalDurationMs: external_exports.number().int().min(0).optional().describe("Total provisioning duration"), - /** Provisioned timestamp (ISO 8601) */ - provisionedAt: external_exports.string().datetime().optional().describe("Provisioning completion time"), - /** Error message if provisioning failed */ - error: external_exports.string().optional().describe("Error message on failure") -}).describe("Tenant provisioning result"); -var DeployStatusEnum = external_exports.enum([ - "validating", - // Zod schema validation in progress - "diffing", - // Comparing desired state vs current state - "migrating", - // Executing DDL statements - "registering", - // Updating metadata registry - "ready", - // Deployment complete and live - "failed", - // Deployment failed at some stage - "rolling_back" - // Rollback in progress -]).describe("Deployment lifecycle status"); -var SchemaChangeSchema = external_exports.object({ - /** Type of entity being changed */ - entityType: external_exports.enum(["object", "field", "index", "view", "flow", "permission"]).describe("Entity type"), - /** Name of the entity */ - entityName: external_exports.string().min(1).describe("Entity name"), - /** Parent entity name (e.g., object name for a field change) */ - parentEntity: external_exports.string().optional().describe("Parent entity name"), - /** Type of change */ - changeType: external_exports.enum(["added", "modified", "removed"]).describe("Change type"), - /** Previous value (for modified/removed) */ - oldValue: external_exports.unknown().optional().describe("Previous value"), - /** New value (for added/modified) */ - newValue: external_exports.unknown().optional().describe("New value") -}).describe("Individual schema change"); -var DeployDiffSchema = external_exports.object({ - /** List of all schema changes */ - changes: external_exports.array(SchemaChangeSchema).default([]).describe("List of schema changes"), - /** Summary counts */ - summary: external_exports.object({ - added: external_exports.number().int().min(0).default(0).describe("Number of added entities"), - modified: external_exports.number().int().min(0).default(0).describe("Number of modified entities"), - removed: external_exports.number().int().min(0).default(0).describe("Number of removed entities") - }).describe("Change summary counts"), - /** Whether the diff contains breaking changes (e.g., column removal) */ - hasBreakingChanges: external_exports.boolean().default(false).describe("Whether diff contains breaking changes") -}).describe("Schema diff between current and desired state"); -var MigrationStatementSchema = external_exports.object({ - /** SQL DDL statement to execute */ - sql: external_exports.string().min(1).describe("SQL DDL statement"), - /** Whether this statement is reversible */ - reversible: external_exports.boolean().default(true).describe("Whether the statement can be reversed"), - /** Reverse SQL statement (for rollback) */ - rollbackSql: external_exports.string().optional().describe("Reverse SQL for rollback"), - /** Execution order (lower = earlier) */ - order: external_exports.number().int().min(0).describe("Execution order") -}).describe("Single DDL migration statement"); -var MigrationPlanSchema = external_exports.object({ - /** Ordered list of migration statements */ - statements: external_exports.array(MigrationStatementSchema).default([]).describe("Ordered DDL statements"), - /** SQL dialect the statements are written for */ - dialect: external_exports.string().min(1).describe("Target SQL dialect"), - /** Whether the entire plan is reversible */ - reversible: external_exports.boolean().default(true).describe("Whether the plan can be fully rolled back"), - /** Estimated execution time in milliseconds */ - estimatedDurationMs: external_exports.number().int().min(0).optional().describe("Estimated execution time") -}).describe("Ordered migration plan"); -var DeployValidationIssueSchema = external_exports.object({ - /** Severity of the issue */ - severity: external_exports.enum(["error", "warning", "info"]).describe("Issue severity"), - /** Entity path where the issue was found */ - path: external_exports.string().describe("Entity path (e.g., objects.project_task.fields.name)"), - /** Human-readable issue description */ - message: external_exports.string().describe("Issue description"), - /** Zod error code if applicable */ - code: external_exports.string().optional().describe("Validation error code") -}).describe("Validation issue"); -var DeployValidationResultSchema = external_exports.object({ - /** Whether the bundle passed validation */ - valid: external_exports.boolean().describe("Whether the bundle is valid"), - /** List of validation issues */ - issues: external_exports.array(DeployValidationIssueSchema).default([]).describe("Validation issues"), - /** Number of errors */ - errorCount: external_exports.number().int().min(0).default(0).describe("Number of errors"), - /** Number of warnings */ - warningCount: external_exports.number().int().min(0).default(0).describe("Number of warnings") -}).describe("Bundle validation result"); -var DeployManifestSchema = external_exports.object({ - /** Deployment version (semver) */ - version: external_exports.string().min(1).describe("Deployment version"), - /** SHA256 checksum of the bundle contents */ - checksum: external_exports.string().optional().describe("SHA256 checksum"), - /** Object definitions included in this deployment */ - objects: external_exports.array(external_exports.string()).default([]).describe("Object names included"), - /** View definitions included */ - views: external_exports.array(external_exports.string()).default([]).describe("View names included"), - /** Flow definitions included */ - flows: external_exports.array(external_exports.string()).default([]).describe("Flow names included"), - /** Permission definitions included */ - permissions: external_exports.array(external_exports.string()).default([]).describe("Permission names included"), - /** Timestamp of bundle creation (ISO 8601) */ - createdAt: external_exports.string().datetime().optional().describe("Bundle creation time") -}).describe("Deployment manifest"); -var DeployBundleSchema = external_exports.object({ - /** Bundle manifest with version and contents list */ - manifest: DeployManifestSchema, - /** Object definitions (JSON-serialized ObjectStack objects) */ - objects: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Object definitions"), - /** View definitions */ - views: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("View definitions"), - /** Flow definitions */ - flows: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Flow definitions"), - /** Permission definitions */ - permissions: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Permission definitions"), - /** Seed data records to populate after schema migration */ - seedData: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Seed data records") -}).describe("Deploy bundle containing all metadata for deployment"); -var AppManifestSchema = external_exports.object({ - /** Unique app identifier (snake_case) */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("App identifier (snake_case)"), - /** Display label for the app */ - label: external_exports.string().min(1).describe("App display label"), - /** App version (semver) */ - version: external_exports.string().min(1).describe("App version (semver)"), - /** App description */ - description: external_exports.string().optional().describe("App description"), - /** Minimum kernel version required */ - minKernelVersion: external_exports.string().optional().describe("Minimum required kernel version"), - /** Object definitions provided by this app */ - objects: external_exports.array(external_exports.string()).default([]).describe("Object names provided"), - /** View definitions provided */ - views: external_exports.array(external_exports.string()).default([]).describe("View names provided"), - /** Flow definitions provided */ - flows: external_exports.array(external_exports.string()).default([]).describe("Flow names provided"), - /** Whether seed data is included */ - hasSeedData: external_exports.boolean().default(false).describe("Whether app includes seed data"), - /** Seed data records to populate on install */ - seedData: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Seed data records"), - /** App dependencies (other apps that must be installed first) */ - dependencies: external_exports.array(external_exports.string()).default([]).describe("Required app dependencies") -}).describe("App manifest for marketplace installation"); -var AppCompatibilityCheckSchema = external_exports.object({ - /** Whether the app is compatible with the current environment */ - compatible: external_exports.boolean().describe("Whether the app is compatible"), - /** Compatibility issues found */ - issues: external_exports.array(external_exports.object({ - /** Issue severity */ - severity: external_exports.enum(["error", "warning"]).describe("Issue severity"), - /** Issue description */ - message: external_exports.string().describe("Issue description"), - /** Issue category */ - category: external_exports.enum([ - "kernel_version", - // Kernel version mismatch - "object_conflict", - // Object name already exists - "dependency_missing", - // Required dependency not installed - "quota_exceeded" - // Tenant quota would be exceeded - ]).describe("Issue category") - })).default([]).describe("Compatibility issues") -}).describe("App compatibility check result"); -var AppInstallRequestSchema = external_exports.object({ - /** Target tenant ID */ - tenantId: external_exports.string().min(1).describe("Target tenant ID"), - /** App identifier to install */ - appId: external_exports.string().min(1).describe("App identifier"), - /** Optional configuration overrides */ - configOverrides: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Configuration overrides"), - /** Whether to skip seed data */ - skipSeedData: external_exports.boolean().default(false).describe("Skip seed data population") -}).describe("App install request"); -var AppInstallResultSchema = external_exports.object({ - /** Whether the installation succeeded */ - success: external_exports.boolean().describe("Whether installation succeeded"), - /** App identifier that was installed */ - appId: external_exports.string().describe("Installed app identifier"), - /** App version installed */ - version: external_exports.string().describe("Installed app version"), - /** Objects created or updated */ - installedObjects: external_exports.array(external_exports.string()).default([]).describe("Objects created/updated"), - /** Tables created in the database */ - createdTables: external_exports.array(external_exports.string()).default([]).describe("Database tables created"), - /** Number of seed records inserted */ - seededRecords: external_exports.number().int().min(0).default(0).describe("Seed records inserted"), - /** Installation duration in milliseconds */ - durationMs: external_exports.number().int().min(0).optional().describe("Installation duration"), - /** Error message if installation failed */ - error: external_exports.string().optional().describe("Error message on failure") -}).describe("App install result"); -var SystemObjectName = { - /** Authentication: user identity */ - USER: "sys_user", - /** Authentication: active session */ - SESSION: "sys_session", - /** Authentication: OAuth / credential account */ - ACCOUNT: "sys_account", - /** Authentication: email / phone verification */ - VERIFICATION: "sys_verification", - /** Authentication: organization (multi-org support) */ - ORGANIZATION: "sys_organization", - /** Authentication: organization member */ - MEMBER: "sys_member", - /** Authentication: organization invitation */ - INVITATION: "sys_invitation", - /** Authentication: team within an organization */ - TEAM: "sys_team", - /** Authentication: team membership */ - TEAM_MEMBER: "sys_team_member", - /** Authentication: API key for programmatic access */ - API_KEY: "sys_api_key", - /** Authentication: two-factor authentication credentials */ - TWO_FACTOR: "sys_two_factor", - /** Authentication: user preferences (theme, locale, etc.) */ - USER_PREFERENCE: "sys_user_preference", - /** Security: role definition for RBAC */ - ROLE: "sys_role", - /** Security: permission set grouping */ - PERMISSION_SET: "sys_permission_set", - /** Audit: system audit log */ - AUDIT_LOG: "sys_audit_log", - /** System metadata storage */ - METADATA: "sys_metadata", - /** Realtime: user presence state */ - PRESENCE: "sys_presence" -}; - -// ../../packages/core/dist/index.js -init_zod(); - -// ../../packages/spec/dist/api/index.mjs -init_zod(); -var FieldReferenceSchema = external_exports.object({ - $field: external_exports.string().describe("Field Reference/Column Name") -}); -external_exports.object({ - /** Equal to (default) - SQL: = | MongoDB: $eq */ - $eq: external_exports.any().optional(), - /** Not equal to - SQL: <> or != | MongoDB: $ne */ - $ne: external_exports.any().optional() -}); -external_exports.object({ - /** Greater than - SQL: > | MongoDB: $gt */ - $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), - /** Greater than or equal to - SQL: >= | MongoDB: $gte */ - $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), - /** Less than - SQL: < | MongoDB: $lt */ - $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), - /** Less than or equal to - SQL: <= | MongoDB: $lte */ - $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional() -}); -external_exports.object({ - /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */ - $in: external_exports.array(external_exports.any()).optional(), - /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */ - $nin: external_exports.array(external_exports.any()).optional() -}); -external_exports.object({ - /** Between (inclusive) - takes [min, max] array */ - $between: external_exports.tuple([ - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]), - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]) - ]).optional() -}); -external_exports.object({ - /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */ - $contains: external_exports.string().optional(), - /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */ - $notContains: external_exports.string().optional(), - /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */ - $startsWith: external_exports.string().optional(), - /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */ - $endsWith: external_exports.string().optional() -}); -external_exports.object({ - /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */ - $null: external_exports.boolean().optional(), - /** Field exists check (primarily for NoSQL) - MongoDB: $exists */ - $exists: external_exports.boolean().optional() -}); -var FieldOperatorsSchema = external_exports.object({ - // Equality - $eq: external_exports.any().optional(), - $ne: external_exports.any().optional(), - // Comparison (numeric/date) - $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), - $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), - $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), - $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]).optional(), - // Set & Range - $in: external_exports.array(external_exports.any()).optional(), - $nin: external_exports.array(external_exports.any()).optional(), - $between: external_exports.tuple([ - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]), - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema]) - ]).optional(), - // String-specific - $contains: external_exports.string().optional(), - $notContains: external_exports.string().optional(), - $startsWith: external_exports.string().optional(), - $endsWith: external_exports.string().optional(), - // Special - $null: external_exports.boolean().optional(), - $exists: external_exports.boolean().optional() -}); -var FilterConditionSchema = external_exports.lazy( - () => external_exports.record(external_exports.string(), external_exports.unknown()).and( - external_exports.object({ - $and: external_exports.array(FilterConditionSchema).optional(), - $or: external_exports.array(FilterConditionSchema).optional(), - $not: FilterConditionSchema.optional() - }) - ) -); -external_exports.object({ - where: FilterConditionSchema.optional() -}); -var NormalizedFilterSchema = external_exports.lazy( - () => external_exports.object({ - $and: external_exports.array( - external_exports.union([ - // Field condition: { field: { $op: value } } - external_exports.record(external_exports.string(), FieldOperatorsSchema), - // Nested logical group - NormalizedFilterSchema - ]) - ).optional(), - $or: external_exports.array( - external_exports.union([ - external_exports.record(external_exports.string(), FieldOperatorsSchema), - NormalizedFilterSchema - ]) - ).optional(), - $not: external_exports.union([ - external_exports.record(external_exports.string(), FieldOperatorsSchema), - NormalizedFilterSchema - ]).optional() - }) -); -var SortNodeSchema = external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]).default("asc") -}); -var AggregationFunction = external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "array_agg", - "string_agg" -]); -var AggregationNodeSchema = external_exports.object({ - function: AggregationFunction.describe("Aggregation function"), - field: external_exports.string().optional().describe("Field to aggregate (optional for COUNT(*))"), - alias: external_exports.string().describe("Result column alias"), - distinct: external_exports.boolean().optional().describe("Apply DISTINCT before aggregation"), - filter: FilterConditionSchema.optional().describe("Filter/Condition to apply to the aggregation (FILTER WHERE clause)") -}); -var JoinType = external_exports.enum(["inner", "left", "right", "full"]); -var JoinStrategy = external_exports.enum(["auto", "database", "hash", "loop"]); -var JoinNodeSchema = external_exports.lazy( - () => external_exports.object({ - type: JoinType.describe("Join type"), - strategy: JoinStrategy.optional().describe("Execution strategy hint"), - object: external_exports.string().describe("Object/table to join"), - alias: external_exports.string().optional().describe("Table alias"), - on: FilterConditionSchema.describe("Join condition"), - subquery: external_exports.lazy(() => QuerySchema).optional().describe("Subquery instead of object") - }) -); -var WindowFunction = external_exports.enum([ - "row_number", - "rank", - "dense_rank", - "percent_rank", - "lag", - "lead", - "first_value", - "last_value", - "sum", - "avg", - "count", - "min", - "max" -]); -var WindowSpecSchema = external_exports.object({ - partitionBy: external_exports.array(external_exports.string()).optional().describe("PARTITION BY fields"), - orderBy: external_exports.array(SortNodeSchema).optional().describe("ORDER BY specification"), - frame: external_exports.object({ - type: external_exports.enum(["rows", "range"]).optional(), - start: external_exports.string().optional().describe('Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")'), - end: external_exports.string().optional().describe('Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")') - }).optional().describe("Window frame specification") -}); -var WindowFunctionNodeSchema = external_exports.object({ - function: WindowFunction.describe("Window function name"), - field: external_exports.string().optional().describe("Field to operate on (for aggregate window functions)"), - alias: external_exports.string().describe("Result column alias"), - over: WindowSpecSchema.describe("Window specification (OVER clause)") -}); -var FieldNodeSchema = external_exports.lazy( - () => external_exports.union([ - external_exports.string(), - // Primitive field: "name" - external_exports.object({ - field: external_exports.string(), - // Relationship field: "owner" - fields: external_exports.array(FieldNodeSchema).optional(), - // Nested select: ["name", "email"] - alias: external_exports.string().optional() - }) - ]) -); -var FullTextSearchSchema = external_exports.object({ - query: external_exports.string().describe("Search query text"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to search in (if not specified, searches all text fields)"), - fuzzy: external_exports.boolean().optional().default(false).describe("Enable fuzzy matching (tolerates typos)"), - operator: external_exports.enum(["and", "or"]).optional().default("or").describe("Logical operator between terms"), - boost: external_exports.record(external_exports.string(), external_exports.number()).optional().describe("Field-specific relevance boosting (field name -> boost factor)"), - minScore: external_exports.number().optional().describe("Minimum relevance score threshold"), - language: external_exports.string().optional().describe('Language for text analysis (e.g., "en", "zh", "es")'), - highlight: external_exports.boolean().optional().default(false).describe("Enable search result highlighting") -}); -var BaseQuerySchema = external_exports.object({ - /** Target Entity */ - object: external_exports.string().describe("Object name (e.g. account)"), - /** Select Clause */ - fields: external_exports.array(FieldNodeSchema).optional().describe("Fields to retrieve"), - /** Where Clause (Filtering) */ - where: FilterConditionSchema.optional().describe("Filtering criteria (WHERE)"), - /** Full-Text Search */ - search: FullTextSearchSchema.optional().describe("Full-text search configuration ($search parameter)"), - /** Order By Clause (Sorting) */ - orderBy: external_exports.array(SortNodeSchema).optional().describe("Sorting instructions (ORDER BY)"), - /** Pagination */ - limit: external_exports.number().optional().describe("Max records to return (LIMIT)"), - offset: external_exports.number().optional().describe("Records to skip (OFFSET)"), - top: external_exports.number().optional().describe("Alias for limit (OData compatibility)"), - cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Cursor for keyset pagination"), - /** Joins */ - joins: external_exports.array(JoinNodeSchema).optional().describe("Explicit Table Joins"), - /** Aggregations */ - aggregations: external_exports.array(AggregationNodeSchema).optional().describe("Aggregation functions"), - /** Group By Clause */ - groupBy: external_exports.array(external_exports.string()).optional().describe("GROUP BY fields"), - /** Having Clause */ - having: FilterConditionSchema.optional().describe("HAVING clause for aggregation filtering"), - /** Window Functions */ - windowFunctions: external_exports.array(WindowFunctionNodeSchema).optional().describe("Window functions with OVER clause"), - /** Subquery flag */ - distinct: external_exports.boolean().optional().describe("SELECT DISTINCT flag") -}); -var QuerySchema = BaseQuerySchema.extend({ - expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema)).optional().describe( - "Recursive relation loading map. Keys are lookup/master_detail field names; values are nested QueryAST objects that control select, filter, sort, and further expansion on the related object. The engine resolves expand via batch $in queries (driver-agnostic) with a default max depth of 3." - ) -}); -var ApiErrorSchema = external_exports.object({ - code: external_exports.string().describe("Error code (e.g. validation_error)"), - message: external_exports.string().describe("Readable error message"), - category: external_exports.string().optional().describe("Error category (e.g. validation, authorization)"), - details: external_exports.unknown().optional().describe("Additional error context (e.g. field validation errors)"), - requestId: external_exports.string().optional().describe("Request ID for tracking") -}); -var BaseResponseSchema = external_exports.object({ - success: external_exports.boolean().describe("Operation success status"), - error: ApiErrorSchema.optional().describe("Error details if success is false"), - meta: external_exports.object({ - timestamp: external_exports.string(), - duration: external_exports.number().optional(), - requestId: external_exports.string().optional(), - traceId: external_exports.string().optional() - }).optional().describe("Response metadata") -}); -var RecordDataSchema = external_exports.record(external_exports.string(), external_exports.unknown()).describe("Key-value map of record data"); -var CreateRequestSchema = external_exports.object({ - data: RecordDataSchema.describe("Record data to insert") -}); -var UpdateRequestSchema = external_exports.object({ - data: RecordDataSchema.describe("Partial record data to update") -}); -var BulkRequestSchema = external_exports.object({ - records: external_exports.array(RecordDataSchema).describe("Array of records to process"), - allOrNone: external_exports.boolean().default(true).describe("If true, rollback entire transaction on any failure") -}); -var ExportRequestSchema = external_exports.intersection( - QuerySchema, - external_exports.object({ - format: external_exports.enum(["csv", "json", "xlsx"]).default("csv") - }) -); -var SingleRecordResponseSchema = BaseResponseSchema.extend({ - data: RecordDataSchema.describe("The requested or modified record") -}); -var ListRecordResponseSchema = BaseResponseSchema.extend({ - data: external_exports.array(RecordDataSchema).describe("Array of matching records"), - pagination: external_exports.object({ - total: external_exports.number().optional().describe("Total matching records count"), - limit: external_exports.number().optional().describe("Page size"), - offset: external_exports.number().optional().describe("Page offset"), - cursor: external_exports.string().optional().describe("Cursor for next page"), - nextCursor: external_exports.string().optional().describe("Next cursor for pagination"), - hasMore: external_exports.boolean().describe("Are there more pages?") - }).describe("Pagination info") -}); -var IdRequestSchema = external_exports.object({ - id: external_exports.string().describe("Record ID") -}); -var ModificationResultSchema = external_exports.object({ - id: external_exports.string().optional().describe("Record ID if processed"), - success: external_exports.boolean(), - errors: external_exports.array(ApiErrorSchema).optional(), - index: external_exports.number().optional().describe("Index in original request"), - data: external_exports.unknown().optional().describe("Result data (e.g. created record)") -}); -var BulkResponseSchema = BaseResponseSchema.extend({ - data: external_exports.array(ModificationResultSchema).describe("Results for each item in the batch") -}); -var DeleteResponseSchema = BaseResponseSchema.extend({ - id: external_exports.string().describe("ID of the deleted record") -}); -var StandardApiContracts = { - create: { - input: CreateRequestSchema, - output: SingleRecordResponseSchema - }, - delete: { - input: IdRequestSchema, - output: DeleteResponseSchema - }, - get: { - input: IdRequestSchema, - output: SingleRecordResponseSchema - }, - update: { - input: UpdateRequestSchema, - output: SingleRecordResponseSchema - }, - list: { - input: QuerySchema, - output: ListRecordResponseSchema - }, - bulkCreate: { - input: BulkRequestSchema, - output: BulkResponseSchema - }, - bulkUpdate: { - input: BulkRequestSchema, - output: BulkResponseSchema - }, - bulkUpsert: { - input: BulkRequestSchema, - output: BulkResponseSchema - }, - bulkDelete: { - input: external_exports.object({ ids: external_exports.array(external_exports.string()) }), - output: BulkResponseSchema - } -}; -var DataLoaderConfigSchema = external_exports.object({ - maxBatchSize: external_exports.number().int().default(100).describe("Maximum number of keys per batch load"), - batchScheduleFn: external_exports.enum(["microtask", "timeout", "manual"]).default("microtask").describe("Scheduling strategy for collecting batch keys"), - cacheEnabled: external_exports.boolean().default(true).describe("Enable per-request result caching"), - cacheKeyFn: external_exports.string().optional().describe("Name or identifier of the cache key function"), - cacheTtl: external_exports.number().min(0).optional().describe("Cache time-to-live in seconds (0 = no expiration)"), - coalesceRequests: external_exports.boolean().default(true).describe("Deduplicate identical requests within a batch window"), - maxConcurrency: external_exports.number().int().optional().describe("Maximum parallel batch requests") -}); -var BatchLoadingStrategySchema = external_exports.object({ - strategy: external_exports.enum(["dataloader", "windowed", "prefetch"]).describe("Batch loading strategy type"), - windowMs: external_exports.number().optional().describe("Collection window duration in milliseconds (for windowed strategy)"), - prefetchDepth: external_exports.number().int().optional().describe("Depth of relation prefetching (for prefetch strategy)"), - associationLoading: external_exports.enum(["lazy", "eager", "batch"]).default("batch").describe("How to load related associations") -}); -var QueryOptimizationConfigSchema = external_exports.object({ - preventNPlusOne: external_exports.boolean().describe("Enable N+1 query detection and prevention"), - dataLoader: DataLoaderConfigSchema.optional().describe("DataLoader batch loading configuration"), - batchStrategy: BatchLoadingStrategySchema.optional().describe("Batch loading strategy configuration"), - maxQueryDepth: external_exports.number().int().describe("Maximum depth for nested relation queries"), - queryComplexityLimit: external_exports.number().optional().describe("Maximum allowed query complexity score"), - enableQueryPlan: external_exports.boolean().default(false).describe("Log query execution plans for debugging") -}); -var HttpMethod2 = external_exports.enum([ - "GET", - "POST", - "PUT", - "DELETE", - "PATCH", - "HEAD", - "OPTIONS" -]); -var HttpMethodSchema2 = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); -var HttpRequestSchema = external_exports.object({ - url: external_exports.string().describe("API endpoint URL"), - method: HttpMethodSchema2.optional().default("GET").describe("HTTP method"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), - body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") -}); -var CorsConfigSchema2 = external_exports.object({ - /** - * Enable CORS - */ - enabled: external_exports.boolean().default(true).describe("Enable CORS"), - /** - * Allowed origins (* for all) - */ - origins: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.string()) - ]).default("*").describe("Allowed origins (* for all)"), - /** - * Allowed HTTP methods - */ - methods: external_exports.array(HttpMethod2).optional().describe("Allowed HTTP methods"), - /** - * Allow credentials (cookies, authorization headers) - */ - credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), - /** - * Preflight cache duration in seconds - */ - maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") -}); -var RateLimitConfigSchema2 = external_exports.object({ - /** - * Enable rate limiting - */ - enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), - /** - * Time window in milliseconds - */ - windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), - /** - * Max requests per window - */ - maxRequests: external_exports.number().int().default(100).describe("Max requests per window") -}); -var StaticMountSchema2 = external_exports.object({ - /** - * URL path to serve from - */ - path: external_exports.string().describe("URL path to serve from"), - /** - * Physical directory to serve - */ - directory: external_exports.string().describe("Physical directory to serve"), - /** - * Cache-Control header value - */ - cacheControl: external_exports.string().optional().describe("Cache-Control header value") -}); -var ApiMappingSchema = external_exports.object({ - source: external_exports.string().describe("Source field/path"), - target: external_exports.string().describe("Target field/path"), - transform: external_exports.string().optional().describe("Transformation function name") -}); -var ApiEndpointSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique endpoint ID"), - path: external_exports.string().regex(/^\//).describe("URL Path (e.g. /api/v1/customers)"), - method: HttpMethod2.describe("HTTP Method"), - /** Documentation */ - summary: external_exports.string().optional(), - description: external_exports.string().optional(), - /** Execution Logic */ - type: external_exports.enum(["flow", "script", "object_operation", "proxy"]).describe("Implementation type"), - target: external_exports.string().describe("Target Flow ID, Script Name, or Proxy URL"), - /** Logic Config */ - objectParams: external_exports.object({ - object: external_exports.string().optional(), - operation: external_exports.enum(["find", "get", "create", "update", "delete"]).optional() - }).optional().describe("For object_operation type"), - /** Data Transformation */ - inputMapping: external_exports.array(ApiMappingSchema).optional().describe("Map Request Body to Internal Params"), - outputMapping: external_exports.array(ApiMappingSchema).optional().describe("Map Internal Result to Response Body"), - /** Policies */ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - rateLimit: RateLimitConfigSchema2.optional().describe("Rate limiting policy"), - cacheTtl: external_exports.number().optional().describe("Response cache TTL in seconds") -}); -var ApiEndpoint = Object.assign(ApiEndpointSchema, { - create: (config4) => config4 -}); -var ServiceStatus = external_exports.enum([ - "available", - "registered", - "unavailable", - "degraded", - "stub" -]).describe( - "available = fully operational, registered = route declared but handler unverified, unavailable = not installed, degraded = partial, stub = placeholder that returns 501" -); -var ServiceInfoSchema = external_exports.object({ - /** Whether the service is enabled and available */ - enabled: external_exports.boolean(), - /** Current operational status */ - status: ServiceStatus, - /** - * Whether the HTTP handler for this service is confirmed to be mounted. - * - * Semantics: - * - `undefined` (omitted) = handler readiness is unknown / not yet verified. - * - `true` = handler is registered in the adapter / dispatcher (safe to call). - * - `false` = route is declared but no handler exists or only a stub is present - * — requests are expected to receive 501 Not Implemented. - * - * Clients SHOULD check this flag before displaying or invoking a service endpoint and may - * distinguish between "unknown" (omitted) and "known missing" (`false`). - */ - handlerReady: external_exports.boolean().optional().describe( - "Whether the HTTP handler is confirmed to be mounted. Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501)." - ), - /** Route path (only present if enabled) */ - route: external_exports.string().optional().describe("e.g. /api/v1/analytics"), - /** Implementation provider name */ - provider: external_exports.string().optional().describe('e.g. "objectql", "plugin-redis", "driver-memory"'), - /** Service version */ - version: external_exports.string().optional().describe('Semantic version of the service implementation (e.g. "3.0.6")'), - /** Human-readable reason if unavailable */ - message: external_exports.string().optional().describe('e.g. "Install plugin-workflow to enable"'), - /** Rate limit configuration for this service */ - rateLimit: external_exports.object({ - requestsPerMinute: external_exports.number().int().optional().describe("Maximum requests per minute"), - requestsPerHour: external_exports.number().int().optional().describe("Maximum requests per hour"), - burstLimit: external_exports.number().int().optional().describe("Maximum burst request count"), - retryAfterMs: external_exports.number().int().optional().describe("Suggested retry-after delay in milliseconds when rate-limited") - }).optional().describe("Rate limit and quota info for this service") -}); -var ApiRoutesSchema = external_exports.object({ - /** Base URL for Object CRUD (Data Protocol) */ - data: external_exports.string().describe("e.g. /api/v1/data"), - /** Base URL for Schema Definitions (Metadata Protocol) */ - metadata: external_exports.string().describe("e.g. /api/v1/meta"), - /** Base URL for API Discovery endpoint */ - discovery: external_exports.string().optional().describe("e.g. /api/v1/discovery"), - /** Base URL for UI Configurations (Views, Menus) */ - ui: external_exports.string().optional().describe("e.g. /api/v1/ui"), - /** Base URL for Authentication (plugin-provided) */ - auth: external_exports.string().optional().describe("e.g. /api/v1/auth"), - /** Base URL for Automation (Flows/Scripts) */ - automation: external_exports.string().optional().describe("e.g. /api/v1/automation"), - /** Base URL for File/Storage operations */ - storage: external_exports.string().optional().describe("e.g. /api/v1/storage"), - /** Base URL for Analytics/BI operations */ - analytics: external_exports.string().optional().describe("e.g. /api/v1/analytics"), - /** GraphQL Endpoint (if enabled) */ - graphql: external_exports.string().optional().describe("e.g. /graphql"), - /** Base URL for Package Management */ - packages: external_exports.string().optional().describe("e.g. /api/v1/packages"), - /** Base URL for Workflow Engine */ - workflow: external_exports.string().optional().describe("e.g. /api/v1/workflow"), - /** Base URL for Realtime (WebSocket/SSE) */ - realtime: external_exports.string().optional().describe("e.g. /api/v1/realtime"), - /** Base URL for Notification Service */ - notifications: external_exports.string().optional().describe("e.g. /api/v1/notifications"), - /** Base URL for AI Engine (NLQ, Chat, Suggest) */ - ai: external_exports.string().optional().describe("e.g. /api/v1/ai"), - /** Base URL for Internationalization */ - i18n: external_exports.string().optional().describe("e.g. /api/v1/i18n"), - /** Base URL for Feed / Chatter API */ - feed: external_exports.string().optional().describe("e.g. /api/v1/feed") -}); -var DiscoverySchema = external_exports.object({ - /** System Identity */ - name: external_exports.string(), - version: external_exports.string(), - environment: external_exports.enum(["production", "sandbox", "development"]), - /** Dynamic Routing — convenience shortcut for client routing */ - routes: ApiRoutesSchema, - /** Localization Info (helping frontend init i18n) */ - locale: external_exports.object({ - default: external_exports.string(), - supported: external_exports.array(external_exports.string()), - timezone: external_exports.string() - }), - /** - * Per-service status map. - * This is the **single source of truth** for service availability. - * Clients use this to determine which features are available, - * show/hide UI elements, and display appropriate messages. - */ - services: external_exports.record(external_exports.string(), ServiceInfoSchema).describe( - "Per-service availability map keyed by CoreServiceName" - ), - /** - * Hierarchical capability descriptors. - * Declares platform features so clients can adapt UI without probing individual services. - * Each key is a capability domain (e.g., "comments", "automation", "search"), - * and its value describes what sub-features are available. - */ - capabilities: external_exports.record(external_exports.string(), external_exports.object({ - enabled: external_exports.boolean().describe("Whether this capability is available"), - features: external_exports.record(external_exports.string(), external_exports.boolean()).optional().describe("Sub-feature flags within this capability"), - description: external_exports.string().optional().describe("Human-readable capability description") - })).optional().describe("Hierarchical capability descriptors for frontend intelligent adaptation"), - /** - * Schema discovery URLs for cross-ecosystem interoperability. - */ - schemaDiscovery: external_exports.object({ - openapi: external_exports.string().optional().describe('URL to OpenAPI (Swagger) specification (e.g., "/api/v1/openapi.json")'), - graphql: external_exports.string().optional().describe('URL to GraphQL schema endpoint (e.g., "/graphql")'), - jsonSchema: external_exports.string().optional().describe("URL to JSON Schema definitions") - }).optional().describe("Schema discovery endpoints for API toolchain integration"), - /** - * Custom metadata key-value pairs for extensibility - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") -}); -var WellKnownCapabilitiesSchema = external_exports.object({ - /** Whether the backend supports Feed / Chatter API */ - feed: external_exports.boolean().describe("Whether the backend supports Feed / Chatter API"), - /** Whether the backend supports comments (a subset of Feed) */ - comments: external_exports.boolean().describe("Whether the backend supports comments (a subset of Feed)"), - /** Whether the backend supports Automation CRUD (flows, triggers) */ - automation: external_exports.boolean().describe("Whether the backend supports Automation CRUD (flows, triggers)"), - /** Whether the backend supports cron scheduling */ - cron: external_exports.boolean().describe("Whether the backend supports cron scheduling"), - /** Whether the backend supports full-text search */ - search: external_exports.boolean().describe("Whether the backend supports full-text search"), - /** Whether the backend supports async export */ - export: external_exports.boolean().describe("Whether the backend supports async export"), - /** Whether the backend supports chunked (multipart) uploads */ - chunkedUpload: external_exports.boolean().describe("Whether the backend supports chunked (multipart) uploads") -}).describe("Well-known capability flags for frontend intelligent adaptation"); -var RouteHealthEntrySchema = external_exports.object({ - /** Route path (e.g. /api/v1/analytics) */ - route: external_exports.string().describe("Route path pattern"), - /** HTTP method */ - method: HttpMethod2.describe("HTTP method (GET, POST, etc.)"), - /** Target service name */ - service: external_exports.string().describe("Target service name"), - /** Whether the route is declared in discovery */ - declared: external_exports.boolean().describe("Whether the route is declared in discovery/metadata"), - /** Whether the handler is actually registered in the adapter/dispatcher */ - handlerRegistered: external_exports.boolean().describe("Whether the HTTP handler is registered"), - /** - * Health check result: - * - `pass` – Handler exists and responds (2xx/4xx — i.e., not 404/501/503) - * - `fail` – Handler returned 501 or 503 - * - `missing` – No handler registered (404) - * - `skip` – Health check was not performed - */ - healthStatus: external_exports.enum(["pass", "fail", "missing", "skip"]).describe( - "pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked" - ), - /** Optional diagnostic message */ - message: external_exports.string().optional().describe("Diagnostic message") -}); -var RouteHealthReportSchema = external_exports.object({ - /** ISO 8601 timestamp of when the report was generated */ - timestamp: external_exports.string().describe("ISO 8601 timestamp of report generation"), - /** Adapter name that generated the report (e.g. "hono", "express", "nextjs") */ - adapter: external_exports.string().describe("Adapter or runtime that produced this report"), - /** Total routes declared in discovery / dispatcher table */ - totalDeclared: external_exports.number().int().describe("Total routes declared in discovery"), - /** Routes with a confirmed handler registration */ - totalRegistered: external_exports.number().int().describe("Routes with confirmed handler"), - /** Routes missing a handler */ - totalMissing: external_exports.number().int().describe("Routes missing a handler"), - /** Per-route health entries */ - routes: external_exports.array(RouteHealthEntrySchema).describe("Per-route health entries") -}); -var MetadataEventType = external_exports.enum([ - "metadata.object.created", - "metadata.object.updated", - "metadata.object.deleted", - "metadata.field.created", - "metadata.field.updated", - "metadata.field.deleted", - "metadata.view.created", - "metadata.view.updated", - "metadata.view.deleted", - "metadata.app.created", - "metadata.app.updated", - "metadata.app.deleted", - "metadata.agent.created", - "metadata.agent.updated", - "metadata.agent.deleted", - "metadata.tool.created", - "metadata.tool.updated", - "metadata.tool.deleted", - "metadata.flow.created", - "metadata.flow.updated", - "metadata.flow.deleted", - "metadata.action.created", - "metadata.action.updated", - "metadata.action.deleted", - "metadata.workflow.created", - "metadata.workflow.updated", - "metadata.workflow.deleted", - "metadata.dashboard.created", - "metadata.dashboard.updated", - "metadata.dashboard.deleted", - "metadata.report.created", - "metadata.report.updated", - "metadata.report.deleted", - "metadata.role.created", - "metadata.role.updated", - "metadata.role.deleted", - "metadata.permission.created", - "metadata.permission.updated", - "metadata.permission.deleted" -]); -var DataEventType = external_exports.enum([ - "data.record.created", - "data.record.updated", - "data.record.deleted", - "data.field.changed" -]); -var MetadataEventSchema = external_exports.object({ - /** Unique event identifier */ - id: external_exports.string().uuid().describe("Unique event identifier"), - /** Event type (metadata.{type}.{action}) */ - type: MetadataEventType.describe("Event type"), - /** Metadata type (object, view, agent, tool, etc.) */ - metadataType: external_exports.string().describe("Metadata type (object, view, agent, etc.)"), - /** Metadata item name */ - name: external_exports.string().describe("Metadata item name"), - /** Package ID (if applicable) */ - packageId: external_exports.string().optional().describe("Package ID"), - /** Full definition (only for create/update events) */ - definition: external_exports.unknown().optional().describe("Full definition (create/update only)"), - /** User who triggered the event */ - userId: external_exports.string().optional().describe("User who triggered the event"), - /** Event timestamp (ISO 8601) */ - timestamp: external_exports.string().datetime().describe("Event timestamp") -}); -var DataEventSchema = external_exports.object({ - /** Unique event identifier */ - id: external_exports.string().uuid().describe("Unique event identifier"), - /** Event type (data.record.{action}) */ - type: DataEventType.describe("Event type"), - /** Object name */ - object: external_exports.string().describe("Object name"), - /** Record ID */ - recordId: external_exports.string().describe("Record ID"), - /** Changed fields (update events only) */ - changes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Changed fields"), - /** Record before update (update events only) */ - before: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Before state"), - /** Record after update (create/update events) */ - after: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("After state"), - /** User who triggered the event */ - userId: external_exports.string().optional().describe("User who triggered the event"), - /** Event timestamp (ISO 8601) */ - timestamp: external_exports.string().datetime().describe("Event timestamp") -}); -var PresenceStatus = external_exports.enum([ - "online", - // User is actively connected - "away", - // User is idle/inactive - "busy", - // User is busy (do not disturb) - "offline" - // User is disconnected -]); -var RealtimeRecordAction = external_exports.enum([ - "created", - "updated", - "deleted" -]); -var BasePresenceSchema = external_exports.object({ - /** User identifier */ - userId: external_exports.string().describe("User identifier"), - /** Current presence status */ - status: PresenceStatus.describe("Current presence status"), - /** Last activity timestamp */ - lastSeen: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), - /** Custom metadata */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom presence data (e.g., current page, custom status)") -}); -var TransportProtocol = external_exports.enum([ - "websocket", - // Full-duplex, low latency communication - "sse", - // Server-Sent Events, unidirectional push - "polling" - // Short polling, best compatibility -]); -var RealtimeEventType = external_exports.enum([ - "record.created", - "record.updated", - "record.deleted", - "field.changed" -]); -var SubscriptionEventSchema = external_exports.object({ - type: RealtimeEventType.describe("Type of event to subscribe to"), - object: external_exports.string().optional().describe("Object name to subscribe to"), - filters: external_exports.unknown().optional().describe("Filter conditions") -}); -var SubscriptionSchema = external_exports.object({ - id: external_exports.string().uuid().describe("Unique subscription identifier"), - events: external_exports.array(SubscriptionEventSchema).describe("Array of events to subscribe to"), - transport: TransportProtocol.describe("Transport protocol to use"), - channel: external_exports.string().optional().describe("Optional channel name for grouping subscriptions") -}); -var RealtimePresenceSchema = BasePresenceSchema; -var RealtimeEventSchema = external_exports.object({ - id: external_exports.string().uuid().describe("Unique event identifier"), - type: external_exports.string().describe("Event type (e.g., record.created, record.updated)"), - object: external_exports.string().optional().describe("Object name the event relates to"), - action: RealtimeRecordAction.optional().describe("Action performed"), - payload: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Event payload data"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when event occurred"), - userId: external_exports.string().optional().describe("User who triggered the event"), - sessionId: external_exports.string().optional().describe("Session identifier") -}); -var RealtimeConfigSchema = external_exports.object({ - /** Enable realtime sync */ - enabled: external_exports.boolean().default(true).describe("Enable realtime synchronization"), - /** Transport protocol */ - transport: TransportProtocol.default("websocket").describe("Transport protocol"), - /** Default subscriptions */ - subscriptions: external_exports.array(SubscriptionSchema).optional().describe("Default subscriptions") -}).passthrough(); -var SystemIdentifierSchema2 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' -}).describe("System identifier (lowercase with underscores or dots)"); -var SnakeCaseIdentifierSchema2 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { - message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' -}).describe("Snake case identifier (lowercase with underscores only)"); -var EventNameSchema = external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' -}).describe("Event name (lowercase with dot notation for namespacing)"); -var WebSocketMessageType = external_exports.enum([ - "subscribe", - // Client subscribes to events - "unsubscribe", - // Client unsubscribes from events - "event", - // Server sends event to client - "ping", - // Keepalive ping - "pong", - // Keepalive pong response - "ack", - // Acknowledgment of message receipt - "error", - // Error message - "presence", - // Presence update (user status) - "cursor", - // Cursor position update (collaborative editing) - "edit" - // Document edit operation (collaborative editing) -]); -var FilterOperator = external_exports.enum([ - "eq", - // Equal - "ne", - // Not equal - "gt", - // Greater than - "gte", - // Greater than or equal - "lt", - // Less than - "lte", - // Less than or equal - "in", - // In array - "nin", - // Not in array - "contains", - // String contains - "startsWith", - // String starts with - "endsWith", - // String ends with - "exists", - // Field exists - "regex" - // Regex match -]); -var EventFilterCondition = external_exports.object({ - field: external_exports.string().describe('Field path to filter on (supports dot notation, e.g., "user.email")'), - operator: FilterOperator.describe("Comparison operator"), - value: external_exports.unknown().optional().describe('Value to compare against (not needed for "exists" operator)') -}); -var EventFilterSchema = external_exports.object({ - conditions: external_exports.array(EventFilterCondition).optional().describe("Array of filter conditions"), - and: external_exports.lazy(() => external_exports.array(EventFilterSchema)).optional().describe("AND logical combination of filters"), - or: external_exports.lazy(() => external_exports.array(EventFilterSchema)).optional().describe("OR logical combination of filters"), - not: external_exports.lazy(() => EventFilterSchema).optional().describe("NOT logical negation of filter") -}); -var EventPatternSchema = external_exports.string().min(1).regex(/^[a-z*][a-z0-9_.*]*$/, { - message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., "record.*", "*.created", "user.login")' -}).describe('Event pattern (supports wildcards like "record.*" or "*.created")'); -var EventSubscriptionSchema = external_exports.object({ - subscriptionId: external_exports.string().uuid().describe("Unique subscription identifier"), - events: external_exports.array(EventPatternSchema).describe('Event patterns to subscribe to (supports wildcards, e.g., "record.*", "user.created")'), - objects: external_exports.array(external_exports.string()).optional().describe('Object names to filter events by (e.g., ["account", "contact"])'), - filters: EventFilterSchema.optional().describe("Advanced filter conditions for event payloads"), - channels: external_exports.array(external_exports.string()).optional().describe("Channel names for scoped subscriptions") -}); -var UnsubscribeRequestSchema = external_exports.object({ - subscriptionId: external_exports.string().uuid().describe("Subscription ID to unsubscribe from") -}); -var WebSocketPresenceStatus = PresenceStatus; -var PresenceStateSchema = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - sessionId: external_exports.string().uuid().describe("Unique session identifier"), - status: WebSocketPresenceStatus.describe("Current presence status"), - lastSeen: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), - currentLocation: external_exports.string().optional().describe("Current page/route user is viewing"), - device: external_exports.enum(["desktop", "mobile", "tablet", "other"]).optional().describe("Device type"), - customStatus: external_exports.string().optional().describe("Custom user status message"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom presence data") -}); -var PresenceUpdateSchema = external_exports.object({ - status: WebSocketPresenceStatus.optional().describe("Updated presence status"), - currentLocation: external_exports.string().optional().describe("Updated current location"), - customStatus: external_exports.string().optional().describe("Updated custom status message"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") -}); -var CursorPositionSchema = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - documentId: external_exports.string().describe("Document identifier being edited"), - position: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Line number (0-indexed)"), - column: external_exports.number().int().nonnegative().describe("Column number (0-indexed)") - }).optional().describe("Cursor position in document"), - selection: external_exports.object({ - start: external_exports.object({ - line: external_exports.number().int().nonnegative(), - column: external_exports.number().int().nonnegative() - }), - end: external_exports.object({ - line: external_exports.number().int().nonnegative(), - column: external_exports.number().int().nonnegative() - }) - }).optional().describe("Selection range (if text is selected)"), - color: external_exports.string().optional().describe("Cursor color for visual representation"), - userName: external_exports.string().optional().describe("Display name of user"), - lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last cursor update") -}); -var EditOperationType = external_exports.enum([ - "insert", - // Insert text at position - "delete", - // Delete text from range - "replace" - // Replace text in range -]); -var EditOperationSchema = external_exports.object({ - operationId: external_exports.string().uuid().describe("Unique operation identifier"), - documentId: external_exports.string().describe("Document identifier"), - userId: external_exports.string().describe("User who performed the edit"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - type: EditOperationType.describe("Type of edit operation"), - position: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Line number (0-indexed)"), - column: external_exports.number().int().nonnegative().describe("Column number (0-indexed)") - }).describe("Starting position of the operation"), - endPosition: external_exports.object({ - line: external_exports.number().int().nonnegative(), - column: external_exports.number().int().nonnegative() - }).optional().describe("Ending position (for delete/replace operations)"), - content: external_exports.string().optional().describe("Content to insert/replace"), - version: external_exports.number().int().nonnegative().describe("Document version before this operation"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when operation was created"), - baseOperationId: external_exports.string().uuid().optional().describe("Previous operation ID this builds upon (for OT)") -}); -var DocumentStateSchema = external_exports.object({ - documentId: external_exports.string().describe("Document identifier"), - version: external_exports.number().int().nonnegative().describe("Current document version"), - content: external_exports.string().describe("Current document content"), - lastModified: external_exports.string().datetime().describe("ISO 8601 datetime of last modification"), - activeSessions: external_exports.array(external_exports.string().uuid()).describe("Active editing session IDs"), - checksum: external_exports.string().optional().describe("Content checksum for integrity verification") -}); -var BaseWebSocketMessage = external_exports.object({ - messageId: external_exports.string().uuid().describe("Unique message identifier"), - type: WebSocketMessageType.describe("Message type"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when message was sent") -}); -var SubscribeMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("subscribe"), - subscription: EventSubscriptionSchema.describe("Subscription configuration") -}); -var UnsubscribeMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("unsubscribe"), - request: UnsubscribeRequestSchema.describe("Unsubscribe request") -}); -var EventMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("event"), - subscriptionId: external_exports.string().uuid().describe("Subscription ID this event belongs to"), - eventName: EventNameSchema.describe("Event name"), - object: external_exports.string().optional().describe("Object name the event relates to"), - payload: external_exports.unknown().describe("Event payload data"), - userId: external_exports.string().optional().describe("User who triggered the event") -}); -var PresenceMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("presence"), - presence: PresenceStateSchema.describe("Presence state") -}); -var CursorMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("cursor"), - cursor: CursorPositionSchema.describe("Cursor position") -}); -var EditMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("edit"), - operation: EditOperationSchema.describe("Edit operation") -}); -var AckMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("ack"), - ackMessageId: external_exports.string().uuid().describe("ID of the message being acknowledged"), - success: external_exports.boolean().describe("Whether the operation was successful"), - error: external_exports.string().optional().describe("Error message if operation failed") -}); -var ErrorMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("error"), - code: external_exports.string().describe("Error code"), - message: external_exports.string().describe("Error message"), - details: external_exports.unknown().optional().describe("Additional error details") -}); -var PingMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("ping") -}); -var PongMessageSchema = BaseWebSocketMessage.extend({ - type: external_exports.literal("pong"), - pingMessageId: external_exports.string().uuid().optional().describe("ID of ping message being responded to") -}); -var WebSocketMessageSchema = external_exports.discriminatedUnion("type", [ - SubscribeMessageSchema, - UnsubscribeMessageSchema, - EventMessageSchema, - PresenceMessageSchema, - CursorMessageSchema, - EditMessageSchema, - AckMessageSchema, - ErrorMessageSchema, - PingMessageSchema, - PongMessageSchema -]); -var WebSocketConfigSchema = external_exports.object({ - url: external_exports.string().url().describe("WebSocket server URL"), - protocols: external_exports.array(external_exports.string()).optional().describe("WebSocket sub-protocols"), - reconnect: external_exports.boolean().optional().default(true).describe("Enable automatic reconnection"), - reconnectInterval: external_exports.number().int().positive().optional().default(1e3).describe("Reconnection interval in milliseconds"), - maxReconnectAttempts: external_exports.number().int().positive().optional().default(5).describe("Maximum reconnection attempts"), - pingInterval: external_exports.number().int().positive().optional().default(3e4).describe("Ping interval in milliseconds"), - timeout: external_exports.number().int().positive().optional().default(5e3).describe("Message timeout in milliseconds"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for WebSocket handshake") -}); -var WebSocketEventSchema = external_exports.object({ - type: external_exports.enum([ - "subscribe", - // Client subscribes to channel - "unsubscribe", - // Client unsubscribes from channel - "data-change", - // Data modification event - "presence-update", - // User presence change - "cursor-update", - // Cursor position change (collaborative editing) - "error" - // Error message - ]).describe("Event type"), - channel: external_exports.string().describe('Channel identifier (e.g., "record.account.123", "user.456")'), - payload: external_exports.unknown().describe("Event payload data"), - timestamp: external_exports.number().describe("Unix timestamp in milliseconds") -}); -var SimplePresenceStateSchema = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - userName: external_exports.string().describe("User display name"), - status: external_exports.enum(["online", "away", "offline"]).describe("User presence status"), - lastSeen: external_exports.number().describe("Unix timestamp of last activity in milliseconds"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional presence metadata (e.g., current page, custom status)") -}); -var SimpleCursorPositionSchema = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - recordId: external_exports.string().describe("Record identifier being edited"), - fieldName: external_exports.string().describe("Field name being edited"), - position: external_exports.number().describe("Cursor position (character offset from start)"), - selection: external_exports.object({ - start: external_exports.number().describe("Selection start position"), - end: external_exports.number().describe("Selection end position") - }).optional().describe("Text selection range (if text is selected)") -}); -var WebSocketServerConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable WebSocket server"), - path: external_exports.string().default("/ws").describe("WebSocket endpoint path"), - heartbeatInterval: external_exports.number().default(3e4).describe("Heartbeat interval in milliseconds"), - reconnectAttempts: external_exports.number().default(5).describe("Maximum reconnection attempts for clients"), - presence: external_exports.boolean().default(false).describe("Enable presence tracking"), - cursorSharing: external_exports.boolean().default(false).describe("Enable collaborative cursor sharing") -}); -var RouteCategory = external_exports.enum([ - "system", - // Health, Metrics, Info (No Auth usually) - "api", - // Business Logic API (Auth required) - "auth", - // Login/Callback endpoints - "static", - // Asset serving - "webhook", - // External callbacks - "plugin" - // Plugin extensions -]); -var RouteDefinitionSchema = external_exports.object({ - /** - * HTTP Method - */ - method: HttpMethod2, - /** - * URL Path Pattern (supports parameters like /user/:id) - */ - path: external_exports.string().describe("URL Path pattern"), - /** - * Route Type/Category - */ - category: RouteCategory.default("api"), - /** - * Handler Identifier - * References an internal function or plugin action ID. - */ - handler: external_exports.string().describe("Unique handler identifier"), - /** - * Route specific metadata - */ - summary: external_exports.string().optional().describe("OpenAPI summary"), - description: external_exports.string().optional().describe("OpenAPI description"), - /** - * Security constraints - */ - public: external_exports.boolean().default(false).describe("Is publicly accessible"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - /** - * Performance hints - */ - timeout: external_exports.number().int().optional().describe("Execution timeout in ms"), - rateLimit: external_exports.string().optional().describe("Rate limit policy name") -}); -var RouterConfigSchema = external_exports.object({ - /** - * URL Prefix for all kernel routes - */ - basePath: external_exports.string().default("/api").describe("Global API prefix"), - /** - * Standard Protocol Mounts (Relative to basePath) - */ - mounts: external_exports.object({ - data: external_exports.string().default("/data").describe("Data Protocol (CRUD)"), - metadata: external_exports.string().default("/meta").describe("Metadata Protocol (Schemas)"), - auth: external_exports.string().default("/auth").describe("Auth Protocol"), - automation: external_exports.string().default("/automation").describe("Automation Protocol"), - storage: external_exports.string().default("/storage").describe("Storage Protocol"), - analytics: external_exports.string().default("/analytics").describe("Analytics Protocol"), - graphql: external_exports.string().default("/graphql").describe("GraphQL Endpoint"), - ui: external_exports.string().default("/ui").describe("UI Metadata Protocol (Views, Layouts)"), - workflow: external_exports.string().default("/workflow").describe("Workflow Engine Protocol"), - realtime: external_exports.string().default("/realtime").describe("Realtime/WebSocket Protocol"), - notifications: external_exports.string().default("/notifications").describe("Notification Protocol"), - ai: external_exports.string().default("/ai").describe("AI Engine Protocol (NLQ, Chat, Suggest)"), - i18n: external_exports.string().default("/i18n").describe("Internationalization Protocol"), - packages: external_exports.string().default("/packages").describe("Package Management Protocol") - }).default({ - data: "/data", - metadata: "/meta", - auth: "/auth", - automation: "/automation", - storage: "/storage", - analytics: "/analytics", - graphql: "/graphql", - ui: "/ui", - workflow: "/workflow", - realtime: "/realtime", - notifications: "/notifications", - ai: "/ai", - i18n: "/i18n", - packages: "/packages" - }), - // Defaults match standardized spec - /** - * Cross-Origin Resource Sharing - */ - cors: CorsConfigSchema2.optional(), - /** - * Static asset mounts - */ - staticMounts: external_exports.array(StaticMountSchema2).optional() -}); -var ODataQuerySchema = external_exports.object({ - /** - * $select - Select specific fields to return - * - * Comma-separated list of field names to include in the response. - * Reduces payload size and improves performance. - * - * @example "name,email,phone" - * @example "id,customer/name" - With navigation path - */ - $select: external_exports.union([ - external_exports.string(), - // "name,email" - external_exports.array(external_exports.string()) - // ["name", "email"] - ]).optional().describe("Fields to select"), - /** - * $filter - Filter results with conditions - * - * OData filter expression using comparison operators, logical operators, - * and functions. - * - * Comparison: eq, ne, lt, le, gt, ge - * Logical: and, or, not - * Functions: contains, startswith, endswith, length, indexof, substring, etc. - * - * @example "age gt 18" - * @example "country eq 'US' and revenue gt 100000" - * @example "contains(name, 'Smith')" - * @example "startswith(email, 'admin') and isActive eq true" - */ - $filter: external_exports.string().optional().describe("Filter expression (OData filter syntax)"), - /** - * $orderby - Sort results - * - * Comma-separated list of fields with optional asc/desc. - * Default is ascending. - * - * @example "name" - * @example "revenue desc" - * @example "country asc, revenue desc" - */ - $orderby: external_exports.union([ - external_exports.string(), - // "name desc" - external_exports.array(external_exports.string()) - // ["name desc", "email asc"] - ]).optional().describe("Sort order"), - /** - * $top - Limit number of results - * - * Maximum number of results to return. - * Equivalent to SQL LIMIT or FETCH FIRST. - * - * @example 10 - * @example 100 - */ - $top: external_exports.number().int().min(0).optional().describe("Max results to return"), - /** - * $skip - Skip results for pagination - * - * Number of results to skip before returning results. - * Equivalent to SQL OFFSET. - * - * @example 20 - * @example 100 - */ - $skip: external_exports.number().int().min(0).optional().describe("Results to skip"), - /** - * $expand - Include related entities (lookup/master_detail fields) - * - * Comma-separated list of navigation properties (relationship field names) to expand. - * Loads related data in the same request by resolving lookup and master_detail fields. - * The engine replaces foreign key IDs with full related objects via batch $in queries. - * Supports nested expand via OData parenthetical syntax. - * - * Behavior: - * - Only fields with `type: 'lookup'` or `type: 'master_detail'` and a valid `reference` are expanded. - * - Fields without a schema or reference definition are silently skipped (ID returned as-is). - * - Maximum expand depth defaults to 3 (configurable via QueryAdapterConfig). - * - * @example "orders" - * @example "customer,products" - * @example "orders($select=id,total)" - With nested query options - */ - $expand: external_exports.union([ - external_exports.string(), - // "orders" - external_exports.array(external_exports.string()) - // ["orders", "customer"] - ]).optional().describe("Navigation properties to expand (lookup/master_detail fields)"), - /** - * $count - Include total count - * - * When true, includes totalResults count in response. - * Useful for pagination UI. - * - * @example true - */ - $count: external_exports.boolean().optional().describe("Include total count"), - /** - * $search - Full-text search - * - * Free-text search expression. - * Search implementation is service-specific. - * - * @example "John Smith" - * @example "urgent AND support" - */ - $search: external_exports.string().optional().describe("Search expression"), - /** - * $format - Response format - * - * Preferred response format. - * - * @example "json" - * @example "xml" - */ - $format: external_exports.enum(["json", "xml", "atom"]).optional().describe("Response format"), - /** - * $apply - Data aggregation - * - * Aggregation transformations (groupby, aggregate, etc.) - * Part of OData aggregation extension. - * - * @example "groupby((country),aggregate(revenue with sum as totalRevenue))" - */ - $apply: external_exports.string().optional().describe("Aggregation expression") -}); -var ODataFilterOperatorSchema = external_exports.enum([ - // Comparison Operators - "eq", - // Equal to - "ne", - // Not equal to - "lt", - // Less than - "le", - // Less than or equal to - "gt", - // Greater than - "ge", - // Greater than or equal to - // Logical Operators - "and", - // Logical AND - "or", - // Logical OR - "not", - // Logical NOT - // Grouping - "(", - // Left parenthesis - ")", - // Right parenthesis - // Other - "in", - // Value in list - "has" - // Has flag (for enum flags) -]); -var ODataFilterFunctionSchema = external_exports.enum([ - // String Functions - "contains", - // contains(field, 'value') - "startswith", - // startswith(field, 'value') - "endswith", - // endswith(field, 'value') - "length", - // length(field) - "indexof", - // indexof(field, 'substring') - "substring", - // substring(field, start, length) - "tolower", - // tolower(field) - "toupper", - // toupper(field) - "trim", - // trim(field) - "concat", - // concat(field1, field2) - // Date/Time Functions - "year", - // year(dateField) - "month", - // month(dateField) - "day", - // day(dateField) - "hour", - // hour(datetimeField) - "minute", - // minute(datetimeField) - "second", - // second(datetimeField) - "date", - // date(datetimeField) - "time", - // time(datetimeField) - "now", - // now() - "maxdatetime", - // maxdatetime() - "mindatetime", - // mindatetime() - // Math Functions - "round", - // round(numField) - "floor", - // floor(numField) - "ceiling", - // ceiling(numField) - // Type Functions - "cast", - // cast(field, 'Edm.String') - "isof", - // isof(field, 'Type') - // Collection Functions - "any", - // collection/any(d:d/prop eq value) - "all" - // collection/all(d:d/prop eq value) -]); -var ODataResponseSchema = external_exports.object({ - /** - * OData context URL - * Describes the payload structure - */ - "@odata.context": external_exports.string().url().optional().describe("Metadata context URL"), - /** - * Total count (when $count=true) - */ - "@odata.count": external_exports.number().int().optional().describe("Total results count"), - /** - * Next link for pagination - */ - "@odata.nextLink": external_exports.string().url().optional().describe("Next page URL"), - /** - * Result array - */ - value: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Results array") -}); -var ODataErrorSchema = external_exports.object({ - error: external_exports.object({ - /** - * Error code - */ - code: external_exports.string().describe("Error code"), - /** - * Error message - */ - message: external_exports.string().describe("Error message"), - /** - * Target of the error (field name, etc.) - */ - target: external_exports.string().optional().describe("Error target"), - /** - * Additional error details - */ - details: external_exports.array(external_exports.object({ - code: external_exports.string(), - message: external_exports.string(), - target: external_exports.string().optional() - })).optional().describe("Error details"), - /** - * Inner error for debugging - */ - innererror: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Inner error details") - }) -}); -var ODataMetadataSchema = external_exports.object({ - /** - * Service namespace - */ - namespace: external_exports.string().describe("Service namespace"), - /** - * Entity types to expose - */ - entityTypes: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Entity type name"), - key: external_exports.array(external_exports.string()).describe("Key fields"), - properties: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string().describe("OData type (Edm.String, Edm.Int32, etc.)"), - nullable: external_exports.boolean().default(true) - })), - navigationProperties: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string(), - partner: external_exports.string().optional() - })).optional() - })).describe("Entity types"), - /** - * Entity sets - */ - entitySets: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Entity set name"), - entityType: external_exports.string().describe("Entity type") - })).describe("Entity sets") -}); -var ODataConfigSchema = external_exports.object({ - /** Enable OData endpoint */ - enabled: external_exports.boolean().default(true).describe("Enable OData API"), - /** OData endpoint path */ - path: external_exports.string().default("/odata").describe("OData endpoint path"), - /** Metadata configuration */ - metadata: ODataMetadataSchema.optional().describe("OData metadata configuration") -}).passthrough(); -var GraphQLScalarType = external_exports.enum([ - // Built-in GraphQL Scalars - "ID", - "String", - "Int", - "Float", - "Boolean", - // Extended Scalars (common custom types) - "DateTime", - "Date", - "Time", - "JSON", - "JSONObject", - "Upload", - "URL", - "Email", - "PhoneNumber", - "Currency", - "Decimal", - "BigInt", - "Long", - "UUID", - "Base64", - "Void" -]); -var GraphQLTypeConfigSchema = external_exports.object({ - /** Type name in GraphQL schema */ - name: external_exports.string().describe("GraphQL type name (PascalCase recommended)"), - /** Source Object name */ - object: external_exports.string().describe("Source ObjectQL object name"), - /** Description for GraphQL schema documentation */ - description: external_exports.string().optional().describe("Type description"), - /** Fields to include/exclude */ - fields: external_exports.object({ - /** Include only these fields (allow list) */ - include: external_exports.array(external_exports.string()).optional().describe("Fields to include"), - /** Exclude these fields (deny list) */ - exclude: external_exports.array(external_exports.string()).optional().describe("Fields to exclude (e.g., sensitive fields)"), - /** Custom field mappings */ - mappings: external_exports.record(external_exports.string(), external_exports.object({ - graphqlName: external_exports.string().optional().describe("Custom GraphQL field name"), - graphqlType: external_exports.string().optional().describe("Override GraphQL type"), - description: external_exports.string().optional().describe("Field description"), - deprecationReason: external_exports.string().optional().describe("Why field is deprecated"), - nullable: external_exports.boolean().optional().describe("Override nullable") - })).optional().describe("Field-level customizations") - }).optional().describe("Field configuration"), - /** Interfaces this type implements */ - interfaces: external_exports.array(external_exports.string()).optional().describe("GraphQL interface names"), - /** Whether this is an interface definition */ - isInterface: external_exports.boolean().optional().default(false).describe("Define as GraphQL interface"), - /** Custom directives */ - directives: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Directive name"), - args: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Directive arguments") - })).optional().describe("GraphQL directives") -}); -var GraphQLQueryConfigSchema = external_exports.object({ - /** Query name */ - name: external_exports.string().describe("Query field name (camelCase recommended)"), - /** Source Object */ - object: external_exports.string().describe("Source ObjectQL object name"), - /** Query type: single record or list */ - type: external_exports.enum(["get", "list", "search"]).describe("Query type"), - /** Description */ - description: external_exports.string().optional().describe("Query description"), - /** Input arguments */ - args: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.string().describe('GraphQL type (e.g., "ID!", "String", "Int")'), - description: external_exports.string().optional().describe("Argument description"), - defaultValue: external_exports.unknown().optional().describe("Default value") - })).optional().describe("Query arguments"), - /** Filtering configuration */ - filtering: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Allow filtering"), - fields: external_exports.array(external_exports.string()).optional().describe("Filterable fields"), - operators: external_exports.array(external_exports.enum([ - "eq", - "ne", - "gt", - "gte", - "lt", - "lte", - "in", - "notIn", - "contains", - "startsWith", - "endsWith", - "isNull", - "isNotNull" - ])).optional().describe("Allowed filter operators") - }).optional().describe("Filtering capabilities"), - /** Sorting configuration */ - sorting: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Allow sorting"), - fields: external_exports.array(external_exports.string()).optional().describe("Sortable fields"), - defaultSort: external_exports.object({ - field: external_exports.string(), - direction: external_exports.enum(["ASC", "DESC"]) - }).optional().describe("Default sort order") - }).optional().describe("Sorting capabilities"), - /** Pagination configuration */ - pagination: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable pagination"), - type: external_exports.enum(["offset", "cursor", "relay"]).default("offset").describe("Pagination style"), - defaultLimit: external_exports.number().int().min(1).default(20).describe("Default page size"), - maxLimit: external_exports.number().int().min(1).default(100).describe("Maximum page size"), - cursors: external_exports.object({ - field: external_exports.string().default("id").describe("Field to use for cursor pagination") - }).optional() - }).optional().describe("Pagination configuration"), - /** Field selection */ - fields: external_exports.object({ - /** Always include these fields */ - required: external_exports.array(external_exports.string()).optional().describe("Required fields (always returned)"), - /** Allow selecting these fields */ - selectable: external_exports.array(external_exports.string()).optional().describe("Selectable fields") - }).optional().describe("Field selection configuration"), - /** Authorization */ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - /** Caching */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable caching"), - ttl: external_exports.number().int().min(0).optional().describe("Cache TTL in seconds"), - key: external_exports.string().optional().describe("Cache key template") - }).optional().describe("Query caching") -}); -var GraphQLMutationConfigSchema = external_exports.object({ - /** Mutation name */ - name: external_exports.string().describe("Mutation field name (camelCase recommended)"), - /** Source Object */ - object: external_exports.string().describe("Source ObjectQL object name"), - /** Mutation type */ - type: external_exports.enum(["create", "update", "delete", "upsert", "custom"]).describe("Mutation type"), - /** Description */ - description: external_exports.string().optional().describe("Mutation description"), - /** Input type configuration */ - input: external_exports.object({ - /** Input type name */ - typeName: external_exports.string().optional().describe("Custom input type name"), - /** Fields to include in input */ - fields: external_exports.object({ - include: external_exports.array(external_exports.string()).optional().describe("Fields to include"), - exclude: external_exports.array(external_exports.string()).optional().describe("Fields to exclude"), - required: external_exports.array(external_exports.string()).optional().describe("Required input fields") - }).optional().describe("Input field configuration"), - /** Validation */ - validation: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable input validation"), - rules: external_exports.array(external_exports.string()).optional().describe("Custom validation rules") - }).optional().describe("Input validation") - }).optional().describe("Input configuration"), - /** Return type configuration */ - output: external_exports.object({ - /** Type of output */ - type: external_exports.enum(["object", "payload", "boolean", "custom"]).default("object").describe("Output type"), - /** Include success/error envelope */ - includeEnvelope: external_exports.boolean().optional().default(false).describe("Wrap in success/error payload"), - /** Custom output type */ - customType: external_exports.string().optional().describe("Custom output type name") - }).optional().describe("Output configuration"), - /** Transaction handling */ - transaction: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Use database transaction"), - isolationLevel: external_exports.enum(["read_uncommitted", "read_committed", "repeatable_read", "serializable"]).optional().describe("Transaction isolation level") - }).optional().describe("Transaction configuration"), - /** Authorization */ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - /** Hooks */ - hooks: external_exports.object({ - before: external_exports.array(external_exports.string()).optional().describe("Pre-mutation hooks"), - after: external_exports.array(external_exports.string()).optional().describe("Post-mutation hooks") - }).optional().describe("Lifecycle hooks") -}); -var GraphQLSubscriptionConfigSchema = external_exports.object({ - /** Subscription name */ - name: external_exports.string().describe("Subscription field name (camelCase recommended)"), - /** Source Object */ - object: external_exports.string().describe("Source ObjectQL object name"), - /** Subscription trigger events */ - events: external_exports.array(external_exports.enum(["created", "updated", "deleted", "custom"])).describe("Events to subscribe to"), - /** Description */ - description: external_exports.string().optional().describe("Subscription description"), - /** Filtering */ - filter: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Allow filtering subscriptions"), - fields: external_exports.array(external_exports.string()).optional().describe("Filterable fields") - }).optional().describe("Subscription filtering"), - /** Payload configuration */ - payload: external_exports.object({ - /** Include the modified entity */ - includeEntity: external_exports.boolean().default(true).describe("Include entity in payload"), - /** Include previous values (for updates) */ - includePreviousValues: external_exports.boolean().optional().default(false).describe("Include previous field values"), - /** Include mutation metadata */ - includeMeta: external_exports.boolean().optional().default(true).describe("Include metadata (timestamp, user, etc.)") - }).optional().describe("Payload configuration"), - /** Authorization */ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - /** Rate limiting for subscriptions */ - rateLimit: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable rate limiting"), - maxSubscriptionsPerUser: external_exports.number().int().min(1).default(10).describe("Max concurrent subscriptions per user"), - throttleMs: external_exports.number().int().min(0).optional().describe("Throttle interval in milliseconds") - }).optional().describe("Subscription rate limiting") -}); -var GraphQLResolverConfigSchema = external_exports.object({ - /** Field path (e.g., "Query.users", "Mutation.createUser") */ - path: external_exports.string().describe("Resolver path (Type.field)"), - /** Resolver implementation type */ - type: external_exports.enum(["datasource", "computed", "script", "proxy"]).describe("Resolver implementation type"), - /** Implementation details */ - implementation: external_exports.object({ - /** For datasource type */ - datasource: external_exports.string().optional().describe("Datasource ID"), - query: external_exports.string().optional().describe("Query/SQL to execute"), - /** For computed type */ - expression: external_exports.string().optional().describe("Computation expression"), - dependencies: external_exports.array(external_exports.string()).optional().describe("Dependent fields"), - /** For script type */ - script: external_exports.string().optional().describe("Script ID or inline code"), - /** For proxy type */ - url: external_exports.string().optional().describe("Proxy URL"), - method: external_exports.enum(["GET", "POST", "PUT", "DELETE"]).optional().describe("HTTP method") - }).optional().describe("Implementation configuration"), - /** Caching */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable resolver caching"), - ttl: external_exports.number().int().min(0).optional().describe("Cache TTL in seconds"), - keyArgs: external_exports.array(external_exports.string()).optional().describe("Arguments to include in cache key") - }).optional().describe("Resolver caching") -}); -var GraphQLDataLoaderConfigSchema = external_exports.object({ - /** Loader name */ - name: external_exports.string().describe("DataLoader name"), - /** Source Object or datasource */ - source: external_exports.string().describe("Source object or datasource"), - /** Batch function configuration */ - batchFunction: external_exports.object({ - /** Type of batch operation */ - type: external_exports.enum(["findByIds", "query", "script", "custom"]).describe("Batch function type"), - /** For findByIds */ - keyField: external_exports.string().optional().describe('Field to batch on (e.g., "id")'), - /** For query */ - query: external_exports.string().optional().describe("Query template"), - /** For script */ - script: external_exports.string().optional().describe("Script ID"), - /** Maximum batch size */ - maxBatchSize: external_exports.number().int().min(1).optional().default(100).describe("Maximum batch size") - }).describe("Batch function configuration"), - /** Caching */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable per-request caching"), - /** Cache key function */ - keyFn: external_exports.string().optional().describe("Custom cache key function") - }).optional().describe("DataLoader caching"), - /** Options */ - options: external_exports.object({ - /** Batch multiple requests in single tick */ - batch: external_exports.boolean().default(true).describe("Enable batching"), - /** Cache loaded values */ - cache: external_exports.boolean().default(true).describe("Enable caching"), - /** Maximum cache size */ - maxCacheSize: external_exports.number().int().min(0).optional().describe("Max cache entries") - }).optional().describe("DataLoader options") -}); -var GraphQLDirectiveLocation = external_exports.enum([ - // Executable Directive Locations - "QUERY", - "MUTATION", - "SUBSCRIPTION", - "FIELD", - "FRAGMENT_DEFINITION", - "FRAGMENT_SPREAD", - "INLINE_FRAGMENT", - "VARIABLE_DEFINITION", - // Type System Directive Locations - "SCHEMA", - "SCALAR", - "OBJECT", - "FIELD_DEFINITION", - "ARGUMENT_DEFINITION", - "INTERFACE", - "UNION", - "ENUM", - "ENUM_VALUE", - "INPUT_OBJECT", - "INPUT_FIELD_DEFINITION" -]); -var GraphQLDirectiveConfigSchema = external_exports.object({ - /** Directive name */ - name: external_exports.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe("Directive name (camelCase)"), - /** Description */ - description: external_exports.string().optional().describe("Directive description"), - /** Where directive can be used */ - locations: external_exports.array(GraphQLDirectiveLocation).describe("Directive locations"), - /** Arguments */ - args: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.string().describe("Argument type"), - description: external_exports.string().optional().describe("Argument description"), - defaultValue: external_exports.unknown().optional().describe("Default value") - })).optional().describe("Directive arguments"), - /** Is repeatable */ - repeatable: external_exports.boolean().optional().default(false).describe("Can be applied multiple times"), - /** Implementation */ - implementation: external_exports.object({ - /** Directive behavior type */ - type: external_exports.enum(["auth", "validation", "transform", "cache", "deprecation", "custom"]).describe("Directive type"), - /** Handler function */ - handler: external_exports.string().optional().describe("Handler function name or script") - }).optional().describe("Directive implementation") -}); -var GraphQLQueryDepthLimitSchema = external_exports.object({ - /** Enable depth limiting */ - enabled: external_exports.boolean().default(true).describe("Enable query depth limiting"), - /** Maximum allowed depth */ - maxDepth: external_exports.number().int().min(1).default(10).describe("Maximum query depth"), - /** Fields to ignore in depth calculation */ - ignoreFields: external_exports.array(external_exports.string()).optional().describe("Fields excluded from depth calculation"), - /** Callback on depth exceeded */ - onDepthExceeded: external_exports.enum(["reject", "log", "warn"]).default("reject").describe("Action when depth exceeded"), - /** Custom error message */ - errorMessage: external_exports.string().optional().describe("Custom error message for depth violations") -}); -var GraphQLQueryComplexitySchema = external_exports.object({ - /** Enable complexity limiting */ - enabled: external_exports.boolean().default(true).describe("Enable query complexity limiting"), - /** Maximum allowed complexity score */ - maxComplexity: external_exports.number().int().min(1).default(1e3).describe("Maximum query complexity"), - /** Default field complexity */ - defaultFieldComplexity: external_exports.number().int().min(0).default(1).describe("Default complexity per field"), - /** Field-specific complexity scores */ - fieldComplexity: external_exports.record(external_exports.string(), external_exports.union([ - external_exports.number().int().min(0), - external_exports.object({ - /** Base complexity */ - base: external_exports.number().int().min(0).describe("Base complexity"), - /** Multiplier based on arguments */ - multiplier: external_exports.string().optional().describe('Argument multiplier (e.g., "limit")'), - /** Custom complexity calculation */ - calculator: external_exports.string().optional().describe("Custom calculator function") - }) - ])).optional().describe("Per-field complexity configuration"), - /** List multiplier */ - listMultiplier: external_exports.number().min(0).default(10).describe("Multiplier for list fields"), - /** Callback on complexity exceeded */ - onComplexityExceeded: external_exports.enum(["reject", "log", "warn"]).default("reject").describe("Action when complexity exceeded"), - /** Custom error message */ - errorMessage: external_exports.string().optional().describe("Custom error message for complexity violations") -}); -var GraphQLRateLimitSchema = external_exports.object({ - /** Enable rate limiting */ - enabled: external_exports.boolean().default(true).describe("Enable rate limiting"), - /** Rate limit strategy */ - strategy: external_exports.enum(["token_bucket", "fixed_window", "sliding_window", "cost_based"]).default("token_bucket").describe("Rate limiting strategy"), - /** Global rate limits */ - global: external_exports.object({ - /** Requests per time window */ - maxRequests: external_exports.number().int().min(1).default(1e3).describe("Maximum requests per window"), - /** Time window in milliseconds */ - windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds") - }).optional().describe("Global rate limits"), - /** Per-user rate limits */ - perUser: external_exports.object({ - /** Requests per time window */ - maxRequests: external_exports.number().int().min(1).default(100).describe("Maximum requests per user per window"), - /** Time window in milliseconds */ - windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds") - }).optional().describe("Per-user rate limits"), - /** Cost-based rate limiting */ - costBased: external_exports.object({ - /** Enable cost-based limiting */ - enabled: external_exports.boolean().default(false).describe("Enable cost-based rate limiting"), - /** Maximum cost per time window */ - maxCost: external_exports.number().int().min(1).default(1e4).describe("Maximum cost per window"), - /** Time window in milliseconds */ - windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds"), - /** Use complexity as cost */ - useComplexityAsCost: external_exports.boolean().default(true).describe("Use query complexity as cost") - }).optional().describe("Cost-based rate limiting"), - /** Operation-specific limits */ - operations: external_exports.record(external_exports.string(), external_exports.object({ - maxRequests: external_exports.number().int().min(1).describe("Max requests for this operation"), - windowMs: external_exports.number().int().min(1e3).describe("Time window") - })).optional().describe("Per-operation rate limits"), - /** Callback on limit exceeded */ - onLimitExceeded: external_exports.enum(["reject", "queue", "log"]).default("reject").describe("Action when rate limit exceeded"), - /** Custom error message */ - errorMessage: external_exports.string().optional().describe("Custom error message for rate limit violations"), - /** Headers to include in response */ - includeHeaders: external_exports.boolean().default(true).describe("Include rate limit headers in response") -}); -var GraphQLPersistedQuerySchema = external_exports.object({ - /** Enable persisted queries */ - enabled: external_exports.boolean().default(false).describe("Enable persisted queries"), - /** Enforcement mode */ - mode: external_exports.enum(["optional", "required"]).default("optional").describe("Persisted query mode (optional: allow both, required: only persisted)"), - /** Query store configuration */ - store: external_exports.object({ - /** Store type */ - type: external_exports.enum(["memory", "redis", "database", "file"]).default("memory").describe("Query store type"), - /** Store connection string */ - connection: external_exports.string().optional().describe("Store connection string or path"), - /** TTL for cached queries */ - ttl: external_exports.number().int().min(0).optional().describe("TTL in seconds for stored queries") - }).optional().describe("Query store configuration"), - /** Automatic Persisted Queries (APQ) */ - apq: external_exports.object({ - /** Enable APQ */ - enabled: external_exports.boolean().default(true).describe("Enable Automatic Persisted Queries"), - /** Hash algorithm */ - hashAlgorithm: external_exports.enum(["sha256", "sha1", "md5"]).default("sha256").describe("Hash algorithm for query IDs"), - /** Cache control */ - cache: external_exports.object({ - /** Cache TTL */ - ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), - /** Max cache size */ - maxSize: external_exports.number().int().min(1).optional().describe("Maximum number of cached queries") - }).optional().describe("APQ cache configuration") - }).optional().describe("Automatic Persisted Queries configuration"), - /** Query allow list */ - allowlist: external_exports.object({ - /** Enable allow list mode */ - enabled: external_exports.boolean().default(false).describe("Enable query allow list (reject queries not in list)"), - /** Allowed query IDs */ - queries: external_exports.array(external_exports.object({ - id: external_exports.string().describe("Query ID or hash"), - operation: external_exports.string().optional().describe("Operation name"), - query: external_exports.string().optional().describe("Query string") - })).optional().describe("Allowed queries"), - /** External allow list source */ - source: external_exports.string().optional().describe("External allow list source (file path or URL)") - }).optional().describe("Query allow list configuration"), - /** Security */ - security: external_exports.object({ - /** Maximum query size */ - maxQuerySize: external_exports.number().int().min(1).optional().describe("Maximum query string size in bytes"), - /** Reject introspection in production */ - rejectIntrospection: external_exports.boolean().default(false).describe("Reject introspection queries") - }).optional().describe("Security configuration") -}); -var FederationEntityKeySchema = external_exports.object({ - /** Fields composing the key (e.g., "id" or "sku packageId") */ - fields: external_exports.string().describe("Selection set of fields composing the entity key"), - /** Whether this key can be used for resolution across subgraphs */ - resolvable: external_exports.boolean().optional().default(true).describe("Whether entities can be resolved from this subgraph") -}); -var FederationExternalFieldSchema = external_exports.object({ - /** Field name */ - field: external_exports.string().describe("Field name marked as external"), - /** The subgraph that owns this field */ - ownerSubgraph: external_exports.string().optional().describe("Subgraph that owns this field") -}); -var FederationRequiresSchema = external_exports.object({ - /** The field that has this requirement */ - field: external_exports.string().describe("Field with the requirement"), - /** Selection set of external fields required for resolution */ - fields: external_exports.string().describe('Selection set of required fields (e.g., "price weight")') -}); -var FederationProvidesSchema = external_exports.object({ - /** The field that provides additional data */ - field: external_exports.string().describe("Field that provides additional entity fields"), - /** Selection set of fields provided during resolution */ - fields: external_exports.string().describe('Selection set of provided fields (e.g., "name price")') -}); -var FederationEntitySchema = external_exports.object({ - /** Type/Object name */ - typeName: external_exports.string().describe("GraphQL type name for this entity"), - /** Entity keys (`@key` directive) */ - keys: external_exports.array(FederationEntityKeySchema).min(1).describe("Entity key definitions"), - /** External fields (`@external`) */ - externalFields: external_exports.array(FederationExternalFieldSchema).optional().describe("Fields owned by other subgraphs"), - /** Requires directives (`@requires`) */ - requires: external_exports.array(FederationRequiresSchema).optional().describe("Required external fields for computed fields"), - /** Provides directives (`@provides`) */ - provides: external_exports.array(FederationProvidesSchema).optional().describe("Fields provided during resolution"), - /** Whether this subgraph owns this entity */ - owner: external_exports.boolean().optional().default(false).describe("Whether this subgraph is the owner of this entity") -}); -var SubgraphConfigSchema = external_exports.object({ - /** Subgraph name */ - name: external_exports.string().describe("Unique subgraph identifier"), - /** Subgraph URL */ - url: external_exports.string().describe("Subgraph endpoint URL"), - /** Schema source */ - schemaSource: external_exports.enum(["introspection", "file", "registry"]).default("introspection").describe("How to obtain the subgraph schema"), - /** Schema file path (when schemaSource is "file") */ - schemaPath: external_exports.string().optional().describe("Path to schema file (SDL format)"), - /** Federated entities defined by this subgraph */ - entities: external_exports.array(FederationEntitySchema).optional().describe("Entity definitions for this subgraph"), - /** Health check endpoint */ - healthCheck: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable health checking"), - path: external_exports.string().default("/health").describe("Health check endpoint path"), - intervalMs: external_exports.number().int().min(1e3).default(3e4).describe("Health check interval in milliseconds") - }).optional().describe("Subgraph health check configuration"), - /** Request headers to forward */ - forwardHeaders: external_exports.array(external_exports.string()).optional().describe("HTTP headers to forward to this subgraph") -}); -var FederationGatewaySchema = external_exports.object({ - /** Enable federation mode */ - enabled: external_exports.boolean().default(false).describe("Enable GraphQL Federation gateway mode"), - /** Federation specification version */ - version: external_exports.enum(["v1", "v2"]).default("v2").describe("Federation specification version"), - /** Registered subgraphs */ - subgraphs: external_exports.array(SubgraphConfigSchema).describe("Subgraph configurations"), - /** Service discovery */ - serviceDiscovery: external_exports.object({ - /** Discovery mode */ - type: external_exports.enum(["static", "dns", "consul", "kubernetes"]).default("static").describe("Service discovery method"), - /** Poll interval for dynamic discovery */ - pollIntervalMs: external_exports.number().int().min(1e3).optional().describe("Discovery poll interval in milliseconds"), - /** Kubernetes namespace (when type is "kubernetes") */ - namespace: external_exports.string().optional().describe("Kubernetes namespace for subgraph discovery") - }).optional().describe("Service discovery configuration"), - /** Query planning */ - queryPlanning: external_exports.object({ - /** Execution strategy */ - strategy: external_exports.enum(["parallel", "sequential", "adaptive"]).default("parallel").describe("Query execution strategy across subgraphs"), - /** Maximum query depth across subgraphs */ - maxDepth: external_exports.number().int().min(1).optional().describe("Max query depth in federated execution"), - /** Dry-run mode for debugging query plans */ - dryRun: external_exports.boolean().optional().default(false).describe("Log query plans without executing") - }).optional().describe("Query planning configuration"), - /** Schema composition settings */ - composition: external_exports.object({ - /** How schema conflicts are resolved */ - conflictResolution: external_exports.enum(["error", "first_wins", "last_wins"]).default("error").describe("Strategy for resolving schema conflicts"), - /** Whether to validate composed schema */ - validate: external_exports.boolean().default(true).describe("Validate composed supergraph schema") - }).optional().describe("Schema composition configuration"), - /** Gateway-level error handling */ - errorHandling: external_exports.object({ - /** Whether to include subgraph names in errors */ - includeSubgraphName: external_exports.boolean().default(false).describe("Include subgraph name in error responses"), - /** Partial error behavior */ - partialErrors: external_exports.enum(["propagate", "nullify", "reject"]).default("propagate").describe("Behavior when a subgraph returns partial errors") - }).optional().describe("Error handling configuration") -}); -var GraphQLConfigSchema = external_exports.object({ - /** Enable GraphQL API */ - enabled: external_exports.boolean().default(true).describe("Enable GraphQL API"), - /** GraphQL endpoint path */ - path: external_exports.string().default("/graphql").describe("GraphQL endpoint path"), - /** GraphQL Playground */ - playground: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable GraphQL Playground"), - path: external_exports.string().default("/playground").describe("Playground path") - }).optional().describe("GraphQL Playground configuration"), - /** Schema generation */ - schema: external_exports.object({ - /** Auto-generate types from Objects */ - autoGenerateTypes: external_exports.boolean().default(true).describe("Auto-generate types from Objects"), - /** Type configurations */ - types: external_exports.array(GraphQLTypeConfigSchema).optional().describe("Type configurations"), - /** Query configurations */ - queries: external_exports.array(GraphQLQueryConfigSchema).optional().describe("Query configurations"), - /** Mutation configurations */ - mutations: external_exports.array(GraphQLMutationConfigSchema).optional().describe("Mutation configurations"), - /** Subscription configurations */ - subscriptions: external_exports.array(GraphQLSubscriptionConfigSchema).optional().describe("Subscription configurations"), - /** Custom resolvers */ - resolvers: external_exports.array(GraphQLResolverConfigSchema).optional().describe("Custom resolver configurations"), - /** Custom directives */ - directives: external_exports.array(GraphQLDirectiveConfigSchema).optional().describe("Custom directive configurations") - }).optional().describe("Schema generation configuration"), - /** DataLoader configurations */ - dataLoaders: external_exports.array(GraphQLDataLoaderConfigSchema).optional().describe("DataLoader configurations"), - /** Security configuration */ - security: external_exports.object({ - /** Query depth limiting */ - depthLimit: GraphQLQueryDepthLimitSchema.optional().describe("Query depth limiting"), - /** Query complexity */ - complexity: GraphQLQueryComplexitySchema.optional().describe("Query complexity calculation"), - /** Rate limiting */ - rateLimit: GraphQLRateLimitSchema.optional().describe("Rate limiting"), - /** Persisted queries */ - persistedQueries: GraphQLPersistedQuerySchema.optional().describe("Persisted queries") - }).optional().describe("Security configuration"), - /** Federation configuration */ - federation: FederationGatewaySchema.optional().describe("GraphQL Federation gateway configuration") -}); -var GraphQLConfig = Object.assign(GraphQLConfigSchema, { - create: (config4) => config4 -}); -var BatchOperationType = external_exports.enum([ - "create", - // Batch insert - "update", - // Batch update - "upsert", - // Batch upsert (insert or update based on external ID) - "delete" - // Batch delete -]); -var BatchRecordSchema = external_exports.object({ - id: external_exports.string().optional().describe("Record ID (required for update/delete)"), - data: RecordDataSchema.optional().describe("Record data (required for create/update/upsert)"), - externalId: external_exports.string().optional().describe("External ID for upsert matching") -}); -var BatchOptionsSchema = external_exports.object({ - atomic: external_exports.boolean().optional().default(true).describe("If true, rollback entire batch on any failure (transaction mode)"), - returnRecords: external_exports.boolean().optional().default(false).describe("If true, return full record data in response"), - continueOnError: external_exports.boolean().optional().default(false).describe("If true (and atomic=false), continue processing remaining records after errors"), - validateOnly: external_exports.boolean().optional().default(false).describe("If true, validate records without persisting changes (dry-run mode)") -}); -var BatchUpdateRequestSchema = external_exports.object({ - operation: BatchOperationType.describe("Type of batch operation"), - records: external_exports.array(BatchRecordSchema).min(1).max(200).describe("Array of records to process (max 200 per batch)"), - options: BatchOptionsSchema.optional().describe("Batch operation options") -}); -var UpdateManyRequestSchema = external_exports.object({ - records: external_exports.array(BatchRecordSchema).min(1).max(200).describe("Array of records to update (max 200 per batch)"), - options: BatchOptionsSchema.optional().describe("Update options") -}); -var BatchOperationResultSchema = external_exports.object({ - id: external_exports.string().optional().describe("Record ID if operation succeeded"), - success: external_exports.boolean().describe("Whether this record was processed successfully"), - errors: external_exports.array(ApiErrorSchema).optional().describe("Array of errors if operation failed"), - data: RecordDataSchema.optional().describe("Full record data (if returnRecords=true)"), - index: external_exports.number().optional().describe("Index of the record in the request array") -}); -var BatchUpdateResponseSchema = BaseResponseSchema.extend({ - operation: BatchOperationType.optional().describe("Operation type that was performed"), - total: external_exports.number().describe("Total number of records in the batch"), - succeeded: external_exports.number().describe("Number of records that succeeded"), - failed: external_exports.number().describe("Number of records that failed"), - results: external_exports.array(BatchOperationResultSchema).describe("Detailed results for each record") -}); -var DeleteManyRequestSchema = external_exports.object({ - ids: external_exports.array(external_exports.string()).min(1).max(200).describe("Array of record IDs to delete (max 200)"), - options: BatchOptionsSchema.optional().describe("Delete options") -}); -var BatchConfigSchema = external_exports.object({ - /** Enable batch operations */ - enabled: external_exports.boolean().default(true).describe("Enable batch operations"), - /** Maximum records per batch */ - maxRecordsPerBatch: external_exports.number().int().min(1).max(1e3).default(200).describe("Maximum records per batch"), - /** Default options */ - defaultOptions: BatchOptionsSchema.optional().describe("Default batch options") -}).passthrough(); -var CacheDirective = external_exports.enum([ - "public", - // Cacheable by any cache - "private", - // Cacheable only by user-agent - "no-cache", - // Must revalidate with server - "no-store", - // Never cache - "must-revalidate", - // Must revalidate stale responses - "max-age" - // Maximum cache age in seconds -]); -var CacheControlSchema = external_exports.object({ - directives: external_exports.array(CacheDirective).describe("Cache control directives"), - maxAge: external_exports.number().optional().describe("Maximum cache age in seconds"), - staleWhileRevalidate: external_exports.number().optional().describe("Allow serving stale content while revalidating (seconds)"), - staleIfError: external_exports.number().optional().describe("Allow serving stale content on error (seconds)") -}); -var ETagSchema = external_exports.object({ - value: external_exports.string().describe("ETag value (hash or version identifier)"), - weak: external_exports.boolean().optional().default(false).describe("Whether this is a weak ETag") -}); -var MetadataCacheRequestSchema = external_exports.object({ - ifNoneMatch: external_exports.string().optional().describe("ETag value for conditional request (If-None-Match header)"), - ifModifiedSince: external_exports.string().datetime().optional().describe("Timestamp for conditional request (If-Modified-Since header)"), - cacheControl: CacheControlSchema.optional().describe("Client cache control preferences") -}); -var MetadataCacheResponseSchema = external_exports.object({ - data: external_exports.unknown().optional().describe("Metadata payload (omitted for 304 Not Modified)"), - etag: ETagSchema.optional().describe("ETag for this resource version"), - lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), - cacheControl: CacheControlSchema.optional().describe("Cache control directives"), - notModified: external_exports.boolean().optional().default(false).describe("True if resource has not been modified (304 response)"), - version: external_exports.string().optional().describe("Metadata version identifier") -}); -var CacheInvalidationTarget = external_exports.enum([ - "all", - // Invalidate all cached metadata - "object", - // Invalidate specific object metadata - "field", - // Invalidate specific field metadata - "permission", - // Invalidate permission metadata - "layout", - // Invalidate layout metadata - "custom" - // Custom invalidation pattern -]); -var CacheInvalidationRequestSchema = external_exports.object({ - target: CacheInvalidationTarget.describe("What to invalidate"), - identifiers: external_exports.array(external_exports.string()).optional().describe("Specific resources to invalidate (e.g., object names)"), - cascade: external_exports.boolean().optional().default(false).describe("If true, invalidate dependent resources"), - pattern: external_exports.string().optional().describe("Pattern for custom invalidation (supports wildcards)") -}); -var CacheInvalidationResponseSchema = external_exports.object({ - success: external_exports.boolean().describe("Whether invalidation succeeded"), - invalidated: external_exports.number().describe("Number of cache entries invalidated"), - targets: external_exports.array(external_exports.string()).optional().describe("List of invalidated resources") -}); -var ErrorCategory = external_exports.enum([ - "validation", - // Input validation errors (400) - "authentication", - // Authentication failures (401) - "authorization", - // Permission denied errors (403) - "not_found", - // Resource not found (404) - "conflict", - // Resource conflict (409) - "rate_limit", - // Rate limiting (429) - "server", - // Internal server errors (500) - "external", - // External service errors (502/503) - "maintenance" - // Planned maintenance (503) -]); -var StandardErrorCode = external_exports.enum([ - // Validation Errors (400) - "validation_error", - // Generic validation failure - "invalid_field", - // Invalid field value - "missing_required_field", - // Required field missing - "invalid_format", - // Field format invalid (e.g., email, date) - "value_too_long", - // Field value exceeds max length - "value_too_short", - // Field value below min length - "value_out_of_range", - // Numeric value out of range - "invalid_reference", - // Invalid foreign key reference - "duplicate_value", - // Unique constraint violation - "invalid_query", - // Malformed query syntax - "invalid_filter", - // Invalid filter expression - "invalid_sort", - // Invalid sort specification - "max_records_exceeded", - // Query would return too many records - // Authentication Errors (401) - "unauthenticated", - // No valid authentication provided - "invalid_credentials", - // Wrong username/password - "expired_token", - // Authentication token expired - "invalid_token", - // Authentication token invalid - "session_expired", - // User session expired - "mfa_required", - // Multi-factor authentication required - "email_not_verified", - // Email verification required - // Authorization Errors (403) - "permission_denied", - // User lacks required permission - "insufficient_privileges", - // Operation requires higher privileges - "field_not_accessible", - // Field-level security restriction - "record_not_accessible", - // Sharing rule restriction - "license_required", - // Feature requires license - "ip_restricted", - // IP address not allowed - "time_restricted", - // Access outside allowed time window - // Not Found Errors (404) - "resource_not_found", - // Generic resource not found - "object_not_found", - // Object/table not found - "record_not_found", - // Record with given ID not found - "field_not_found", - // Field not found in object - "endpoint_not_found", - // API endpoint not found - // Conflict Errors (409) - "resource_conflict", - // Generic resource conflict - "concurrent_modification", - // Record modified by another user - "delete_restricted", - // Cannot delete due to dependencies - "duplicate_record", - // Record already exists - "lock_conflict", - // Record is locked by another process - // Rate Limiting (429) - "rate_limit_exceeded", - // Too many requests - "quota_exceeded", - // API quota exceeded - "concurrent_limit_exceeded", - // Too many concurrent requests - // Server Errors (500) - "internal_error", - // Generic internal server error - "database_error", - // Database operation failed - "timeout", - // Operation timed out - "service_unavailable", - // Service temporarily unavailable - "not_implemented", - // Feature not yet implemented - // External Service Errors (502/503) - "external_service_error", - // External API call failed - "integration_error", - // Integration service error - "webhook_delivery_failed", - // Webhook delivery failed - // Batch Operation Errors - "batch_partial_failure", - // Batch operation partially succeeded - "batch_complete_failure", - // Batch operation completely failed - "transaction_failed" - // Transaction rolled back -]); -var RetryStrategy = external_exports.enum([ - "no_retry", - // Do not retry (permanent failure) - "retry_immediate", - // Retry immediately - "retry_backoff", - // Retry with exponential backoff - "retry_after" - // Retry after specified delay -]); -var FieldErrorSchema = external_exports.object({ - field: external_exports.string().describe("Field path (supports dot notation)"), - code: StandardErrorCode.describe("Error code for this field"), - message: external_exports.string().describe("Human-readable error message"), - value: external_exports.unknown().optional().describe("The invalid value that was provided"), - constraint: external_exports.unknown().optional().describe("The constraint that was violated (e.g., max length)") -}); -var EnhancedApiErrorSchema = external_exports.object({ - code: StandardErrorCode.describe("Machine-readable error code"), - message: external_exports.string().describe("Human-readable error message"), - category: ErrorCategory.optional().describe("Error category"), - httpStatus: external_exports.number().optional().describe("HTTP status code"), - retryable: external_exports.boolean().default(false).describe("Whether the request can be retried"), - retryStrategy: RetryStrategy.optional().describe("Recommended retry strategy"), - retryAfter: external_exports.number().optional().describe("Seconds to wait before retrying"), - details: external_exports.unknown().optional().describe("Additional error context"), - fieldErrors: external_exports.array(FieldErrorSchema).optional().describe("Field-specific validation errors"), - timestamp: external_exports.string().datetime().optional().describe("When the error occurred"), - requestId: external_exports.string().optional().describe("Request ID for tracking"), - traceId: external_exports.string().optional().describe("Distributed trace ID"), - documentation: external_exports.string().url().optional().describe("URL to error documentation"), - helpText: external_exports.string().optional().describe("Suggested actions to resolve the error") -}); -var ErrorResponseSchema = external_exports.object({ - success: external_exports.literal(false).describe("Always false for error responses"), - error: EnhancedApiErrorSchema.describe("Error details"), - meta: external_exports.object({ - timestamp: external_exports.string().datetime().optional(), - requestId: external_exports.string().optional(), - traceId: external_exports.string().optional() - }).optional().describe("Response metadata") -}); -external_exports.object({ - /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ - key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), - /** Default value when translation is not available */ - defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), - /** Interpolation parameters for dynamic translations */ - params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") -}); -var I18nLabelSchema2 = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); -var AriaPropsSchema2 = external_exports.object({ - /** Accessible label for screen readers */ - ariaLabel: I18nLabelSchema2.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), - /** ID of element that describes this component */ - ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), - /** WAI-ARIA role override */ - role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') -}).describe("ARIA accessibility attributes"); -external_exports.object({ - /** Translation key for the plural form */ - key: external_exports.string().describe("Translation key"), - /** Form for zero quantity */ - zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), - /** Form for singular (1) */ - one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), - /** Form for dual (2) — used in Arabic, Welsh, etc. */ - two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), - /** Form for few (2-4 in Slavic languages) */ - few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), - /** Form for many (5+ in Slavic languages) */ - many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), - /** Default/fallback form */ - other: external_exports.string().describe('Default plural form (e.g., "{count} items")') -}).describe("ICU plural rules for a translation key"); -var NumberFormatSchema2 = external_exports.object({ - style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), - currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), - unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), - minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), - maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), - useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") -}).describe("Number formatting rules"); -var DateFormatSchema2 = external_exports.object({ - dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), - timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), - timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), - hour12: external_exports.boolean().optional().describe("Use 12-hour format") -}).describe("Date/time formatting rules"); -external_exports.object({ - /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ - code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), - /** Ordered fallback chain for missing translations */ - fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), - /** Text direction */ - direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), - /** Default number formatting */ - numberFormat: NumberFormatSchema2.optional().describe("Default number formatting rules"), - /** Default date formatting */ - dateFormat: DateFormatSchema2.optional().describe("Default date/time formatting rules") -}).describe("Locale configuration"); -var SharingConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable public sharing"), - publicLink: external_exports.string().optional().describe("Generated public share URL"), - password: external_exports.string().optional().describe("Password required to access shared link"), - allowedDomains: external_exports.array(external_exports.string()).optional().describe('Restrict access to specific email domains (e.g. ["example.com"])'), - expiresAt: external_exports.string().optional().describe("Expiration date/time in ISO 8601 format"), - allowAnonymous: external_exports.boolean().optional().default(false).describe("Allow access without authentication") -}); -var EmbedConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable iframe embedding"), - allowedOrigins: external_exports.array(external_exports.string()).optional().describe('Allowed iframe parent origins (e.g. ["https://example.com"])'), - width: external_exports.string().optional().default("100%").describe("Embed width (CSS value)"), - height: external_exports.string().optional().default("600px").describe("Embed height (CSS value)"), - showHeader: external_exports.boolean().optional().default(true).describe("Show interface header in embed"), - showNavigation: external_exports.boolean().optional().default(false).describe("Show navigation in embed"), - responsive: external_exports.boolean().optional().default(true).describe("Enable responsive resizing") -}); -var BreakpointName = external_exports.enum(["xs", "sm", "md", "lg", "xl", "2xl"]); -var BreakpointColumnMapSchema = external_exports.object({ - xs: external_exports.number().min(1).max(12).optional(), - sm: external_exports.number().min(1).max(12).optional(), - md: external_exports.number().min(1).max(12).optional(), - lg: external_exports.number().min(1).max(12).optional(), - xl: external_exports.number().min(1).max(12).optional(), - "2xl": external_exports.number().min(1).max(12).optional() -}).describe("Grid columns per breakpoint (1-12)"); -var BreakpointOrderMapSchema = external_exports.object({ - xs: external_exports.number().optional(), - sm: external_exports.number().optional(), - md: external_exports.number().optional(), - lg: external_exports.number().optional(), - xl: external_exports.number().optional(), - "2xl": external_exports.number().optional() -}).describe("Display order per breakpoint"); -var ResponsiveConfigSchema = external_exports.object({ - /** Minimum breakpoint for visibility */ - breakpoint: BreakpointName.optional().describe("Minimum breakpoint for visibility"), - /** Hide on specific breakpoints */ - hiddenOn: external_exports.array(BreakpointName).optional().describe("Hide on these breakpoints"), - /** Grid columns per breakpoint (1-12 column grid) */ - columns: BreakpointColumnMapSchema.optional().describe("Grid columns per breakpoint"), - /** Display order per breakpoint */ - order: BreakpointOrderMapSchema.optional().describe("Display order per breakpoint") -}).describe("Responsive layout configuration"); -var PerformanceConfigSchema = external_exports.object({ - /** Enable lazy loading for this component */ - lazyLoad: external_exports.boolean().optional().describe("Enable lazy loading (defer rendering until visible)"), - /** Virtual scrolling configuration for large datasets */ - virtualScroll: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable virtual scrolling"), - itemHeight: external_exports.number().optional().describe("Fixed item height in pixels (for estimation)"), - overscan: external_exports.number().optional().describe("Number of extra items to render outside viewport") - }).optional().describe("Virtual scrolling configuration"), - /** Client-side caching strategy */ - cacheStrategy: external_exports.enum([ - "none", - "cache-first", - "network-first", - "stale-while-revalidate" - ]).optional().describe("Client-side data caching strategy"), - /** Enable data prefetching */ - prefetch: external_exports.boolean().optional().describe("Prefetch data before component is visible"), - /** Maximum number of items to render before pagination */ - pageSize: external_exports.number().optional().describe("Number of items per page for pagination"), - /** Debounce interval for user interactions (ms) */ - debounceMs: external_exports.number().optional().describe("Debounce interval for user interactions in milliseconds") -}).describe("Performance optimization configuration"); -var ViewDataSchema = external_exports.discriminatedUnion("provider", [ - external_exports.object({ - provider: external_exports.literal("object"), - object: external_exports.string().describe("Target object name") - }), - external_exports.object({ - provider: external_exports.literal("api"), - read: HttpRequestSchema.optional().describe("Configuration for fetching data"), - write: HttpRequestSchema.optional().describe("Configuration for submitting data (for forms/editable tables)") - }), - external_exports.object({ - provider: external_exports.literal("value"), - items: external_exports.array(external_exports.unknown()).describe("Static data array") - }) -]); -var ViewFilterRuleSchema = external_exports.object({ - /** Field name to filter on */ - field: external_exports.string().describe("Field name to filter on"), - /** Filter operator */ - operator: external_exports.string().describe("Filter operator (e.g. equals, not_equals, contains, this_quarter)"), - /** Filter value (optional for unary operators like is_null, this_quarter) */ - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Filter value") -}).describe("View filter rule"); -var ColumnSummarySchema = external_exports.enum([ - "none", - "count", - "count_empty", - "count_filled", - "count_unique", - "percent_empty", - "percent_filled", - "sum", - "avg", - "min", - "max" -]).describe("Aggregation function for column footer summary"); -var ListColumnSchema = external_exports.object({ - field: external_exports.string().describe("Field name (snake_case)"), - label: I18nLabelSchema2.optional().describe("Display label override"), - width: external_exports.number().positive().optional().describe("Column width in pixels"), - align: external_exports.enum(["left", "center", "right"]).optional().describe("Text alignment"), - hidden: external_exports.boolean().optional().describe("Hide column by default"), - sortable: external_exports.boolean().optional().describe("Allow sorting by this column"), - resizable: external_exports.boolean().optional().describe("Allow resizing this column"), - wrap: external_exports.boolean().optional().describe("Allow text wrapping"), - type: external_exports.string().optional().describe('Renderer type override (e.g., "currency", "date")'), - /** Pinning (Airtable-style frozen columns) */ - pinned: external_exports.enum(["left", "right"]).optional().describe("Pin/freeze column to left or right side"), - /** Column Footer Summary (Airtable-style aggregation) */ - summary: ColumnSummarySchema.optional().describe("Footer aggregation function for this column"), - /** Interaction */ - link: external_exports.boolean().optional().describe("Functions as the primary navigation link (triggers View navigation)"), - action: external_exports.string().optional().describe("Registered Action ID to execute when clicked") -}); -var SelectionConfigSchema = external_exports.object({ - type: external_exports.enum(["none", "single", "multiple"]).default("none").describe("Selection mode") -}); -var PaginationConfigSchema = external_exports.object({ - pageSize: external_exports.number().int().positive().default(25).describe("Number of records per page"), - pageSizeOptions: external_exports.array(external_exports.number().int().positive()).optional().describe("Available page size options") -}); -var RowHeightSchema = external_exports.enum([ - "compact", - // Minimal padding, single line - "short", - // Reduced padding - "medium", - // Default padding - "tall", - // Extra padding, multi-line preview - "extra_tall" - // Maximum padding, rich content preview -]).describe("Row height / density setting for list view"); -var GroupingFieldSchema = external_exports.object({ - field: external_exports.string().describe("Field name to group by"), - order: external_exports.enum(["asc", "desc"]).default("asc").describe("Group sort order"), - collapsed: external_exports.boolean().default(false).describe("Collapse groups by default") -}); -var GroupingConfigSchema = external_exports.object({ - fields: external_exports.array(GroupingFieldSchema).min(1).describe("Fields to group by (supports up to 3 levels)") -}).describe("Record grouping configuration"); -var GalleryConfigSchema = external_exports.object({ - coverField: external_exports.string().optional().describe("Attachment/image field to display as card cover"), - coverFit: external_exports.enum(["cover", "contain"]).default("cover").describe("Image fit mode for card cover"), - cardSize: external_exports.enum(["small", "medium", "large"]).default("medium").describe("Card size in gallery view"), - titleField: external_exports.string().optional().describe("Field to display as card title"), - visibleFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on card body") -}).describe("Gallery/card view configuration"); -var TimelineConfigSchema = external_exports.object({ - startDateField: external_exports.string().describe("Field for timeline item start date"), - endDateField: external_exports.string().optional().describe("Field for timeline item end date"), - titleField: external_exports.string().describe("Field to display as timeline item title"), - groupByField: external_exports.string().optional().describe("Field to group timeline rows"), - colorField: external_exports.string().optional().describe("Field to determine item color"), - scale: external_exports.enum(["hour", "day", "week", "month", "quarter", "year"]).default("week").describe("Default timeline scale") -}).describe("Timeline view configuration"); -var ViewSharingSchema = external_exports.object({ - type: external_exports.enum(["personal", "collaborative"]).default("collaborative").describe("View ownership type"), - lockedBy: external_exports.string().optional().describe("User who locked the view configuration") -}).describe("View sharing and access configuration"); -var RowColorConfigSchema = external_exports.object({ - field: external_exports.string().describe("Field to derive color from (typically a select/status field)"), - colors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Map of field value to color (hex/token)") -}).describe("Row color configuration based on field values"); -var VisualizationTypeSchema = external_exports.enum([ - "grid", - "kanban", - "gallery", - "calendar", - "timeline", - "gantt", - "map" -]).describe("Visualization type that users can switch to"); -var UserActionsConfigSchema = external_exports.object({ - sort: external_exports.boolean().default(true).describe("Allow users to sort records"), - search: external_exports.boolean().default(true).describe("Allow users to search records"), - filter: external_exports.boolean().default(true).describe("Allow users to filter records"), - rowHeight: external_exports.boolean().default(true).describe("Allow users to toggle row height/density"), - addRecordForm: external_exports.boolean().default(false).describe("Add records through a form instead of inline"), - buttons: external_exports.array(external_exports.string()).optional().describe("Custom action button IDs to show in the toolbar") -}).describe("User action toggles for the view toolbar"); -var AppearanceConfigSchema = external_exports.object({ - showDescription: external_exports.boolean().default(true).describe("Show the view description text"), - allowedVisualizations: external_exports.array(VisualizationTypeSchema).optional().describe('Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])') -}).describe("Appearance and visualization configuration"); -var ViewTabSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema2.describe("Tab identifier (snake_case)"), - label: I18nLabelSchema2.optional().describe("Display label"), - icon: external_exports.string().optional().describe("Tab icon name"), - view: external_exports.string().optional().describe("Referenced list view name from listViews"), - filter: external_exports.array(ViewFilterRuleSchema).optional().describe("Tab-specific filter criteria"), - order: external_exports.number().int().min(0).optional().describe("Tab display order"), - pinned: external_exports.boolean().default(false).describe("Pin tab (cannot be removed by users)"), - isDefault: external_exports.boolean().default(false).describe("Set as the default active tab"), - visible: external_exports.boolean().default(true).describe("Tab visibility") -}).describe("Tab configuration for multi-tab view interface"); -var AddRecordConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Show the add record entry point"), - position: external_exports.enum(["top", "bottom", "both"]).default("bottom").describe("Position of the add record button"), - mode: external_exports.enum(["inline", "form", "modal"]).default("inline").describe("How to add a new record"), - formView: external_exports.string().optional().describe('Named form view to use when mode is "form" or "modal"') -}).describe("Add record entry point configuration"); -var KanbanConfigSchema = external_exports.object({ - groupByField: external_exports.string().describe("Field to group columns by (usually status/select)"), - summarizeField: external_exports.string().optional().describe("Field to sum at top of column (e.g. amount)"), - columns: external_exports.array(external_exports.string()).describe("Fields to show on cards") -}); -var CalendarConfigSchema = external_exports.object({ - startDateField: external_exports.string(), - endDateField: external_exports.string().optional(), - titleField: external_exports.string(), - colorField: external_exports.string().optional() -}); -var GanttConfigSchema = external_exports.object({ - startDateField: external_exports.string(), - endDateField: external_exports.string(), - titleField: external_exports.string(), - progressField: external_exports.string().optional(), - dependenciesField: external_exports.string().optional() -}); -var NavigationModeSchema = external_exports.enum([ - "page", - // Navigate to a new route (default) - "drawer", - // Open details in a side drawer/panel - "modal", - // Open details in a modal dialog - "split", - // Show details side-by-side with the list (master-detail) - "popover", - // Show details in a popover (lightweight) - "new_window", - // Open in new browser tab/window - "none" - // No navigation (read-only list) -]); -var NavigationConfigSchema = external_exports.object({ - mode: NavigationModeSchema.default("page"), - /** Target View Config */ - view: external_exports.string().optional().describe('Name of the form view to use for details (e.g. "summary_view", "edit_form")'), - /** Interaction Triggers */ - preventNavigation: external_exports.boolean().default(false).describe("Disable standard navigation entirely"), - openNewTab: external_exports.boolean().default(false).describe("Force open in new tab (applies to page mode)"), - /** Dimensions (for modal/drawer) */ - width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Width of the drawer/modal (e.g. "600px", "50%")') -}); -var ListViewSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema2.optional().describe("Internal view name (lowercase snake_case)"), - label: I18nLabelSchema2.optional(), - // Display label override (supports i18n) - type: external_exports.enum([ - "grid", - // Standard Data Table - "kanban", - // Board / Columns - "gallery", - // Card Deck / Masonry - "calendar", - // Monthly/Weekly/Daily - "timeline", - // Chronological Stream (Feed) - "gantt", - // Project Timeline - "map" - // Geospatial - ]).default("grid"), - /** Data Source Configuration */ - data: ViewDataSchema.optional().describe('Data source configuration (defaults to "object" provider)'), - /** Shared Query Config */ - columns: external_exports.union([ - external_exports.array(external_exports.string()), - // Legacy: simple field names - external_exports.array(ListColumnSchema) - // Enhanced: detailed column config - ]).describe("Fields to display as columns"), - filter: external_exports.array(ViewFilterRuleSchema).optional().describe("Filter criteria (JSON Rules)"), - sort: external_exports.union([ - external_exports.string(), - //Legacy "field desc" - external_exports.array(external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]) - })) - ]).optional(), - /** Search & Filter */ - searchableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for search"), - filterableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for end-user filtering in the top bar"), - /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */ - quickFilters: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name to filter by"), - label: external_exports.string().optional().describe("Display label for the chip"), - operator: external_exports.enum(["equals", "not_equals", "contains", "in", "is_null", "is_not_null"]).default("equals").describe("Filter operator"), - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Preset filter value") - })).optional().describe("One-click filter chips for quick record filtering"), - /** Grid Features */ - resizable: external_exports.boolean().optional().describe("Enable column resizing"), - striped: external_exports.boolean().optional().describe("Striped row styling"), - bordered: external_exports.boolean().optional().describe("Show borders"), - /** Selection */ - selection: SelectionConfigSchema.optional().describe("Row selection configuration"), - /** Navigation / Interaction */ - navigation: NavigationConfigSchema.optional().describe("Configuration for item click navigation (page, drawer, modal, etc.)"), - /** Pagination */ - pagination: PaginationConfigSchema.optional().describe("Pagination configuration"), - /** Type Specific Config */ - kanban: KanbanConfigSchema.optional(), - calendar: CalendarConfigSchema.optional(), - gantt: GanttConfigSchema.optional(), - gallery: GalleryConfigSchema.optional(), - timeline: TimelineConfigSchema.optional(), - /** View Metadata (Airtable-style view management) */ - description: I18nLabelSchema2.optional().describe("View description for documentation/tooltips"), - sharing: ViewSharingSchema.optional().describe("View sharing and access configuration"), - /** Row Height / Density (Airtable-style) */ - rowHeight: RowHeightSchema.optional().describe("Row height / density setting"), - /** Record Grouping (Airtable-style) */ - grouping: GroupingConfigSchema.optional().describe("Group records by one or more fields"), - /** Row Color (Airtable-style) */ - rowColor: RowColorConfigSchema.optional().describe("Color rows based on field value"), - /** Field Visibility & Ordering per View (Airtable-style) */ - hiddenFields: external_exports.array(external_exports.string()).optional().describe("Fields to hide in this specific view"), - fieldOrder: external_exports.array(external_exports.string()).optional().describe("Explicit field display order for this view"), - /** Row & Bulk Actions */ - rowActions: external_exports.array(external_exports.string()).optional().describe("Actions available for individual row items"), - bulkActions: external_exports.array(external_exports.string()).optional().describe("Actions available when multiple rows are selected"), - /** Performance */ - virtualScroll: external_exports.boolean().optional().describe("Enable virtual scrolling for large datasets"), - /** Conditional Formatting */ - conditionalFormatting: external_exports.array(external_exports.object({ - condition: external_exports.string().describe("Condition expression to evaluate"), - style: external_exports.record(external_exports.string(), external_exports.string()).describe("CSS styles to apply when condition is true") - })).optional().describe("Conditional formatting rules for list rows"), - /** Inline Edit */ - inlineEdit: external_exports.boolean().optional().describe("Allow inline editing of records directly in the list view"), - /** Export */ - exportOptions: external_exports.array(external_exports.enum(["csv", "xlsx", "pdf", "json"])).optional().describe("Available export format options"), - /** User Actions (Airtable Interface parity) */ - userActions: UserActionsConfigSchema.optional().describe("User action toggles for the view toolbar"), - /** Appearance (Airtable Interface parity) */ - appearance: AppearanceConfigSchema.optional().describe("Appearance and visualization configuration"), - /** Tabs (Airtable Interface parity) */ - tabs: external_exports.array(ViewTabSchema).optional().describe("Tab definitions for multi-tab view interface"), - /** Add Record (Airtable Interface parity) */ - addRecord: AddRecordConfigSchema.optional().describe("Add record entry point configuration"), - /** Record Count Display (Airtable Interface parity) */ - showRecordCount: external_exports.boolean().optional().describe("Show record count at the bottom of the list"), - /** Advanced: Allow Printing (Airtable Interface parity) */ - allowPrinting: external_exports.boolean().optional().describe("Allow users to print the view"), - /** Empty State */ - emptyState: external_exports.object({ - title: I18nLabelSchema2.optional(), - message: I18nLabelSchema2.optional(), - icon: external_exports.string().optional() - }).optional().describe("Empty state configuration when no records found"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema2.optional().describe("ARIA accessibility attributes for the list view"), - /** Responsive layout overrides per breakpoint */ - responsive: ResponsiveConfigSchema.optional().describe("Responsive layout configuration"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema.optional().describe("Performance optimization settings") -}); -var FormFieldSchema = external_exports.object({ - field: external_exports.string().describe("Field name (snake_case)"), - label: I18nLabelSchema2.optional().describe("Display label override"), - placeholder: I18nLabelSchema2.optional().describe("Placeholder text"), - helpText: I18nLabelSchema2.optional().describe("Help/hint text"), - readonly: external_exports.boolean().optional().describe("Read-only override"), - required: external_exports.boolean().optional().describe("Required override"), - hidden: external_exports.boolean().optional().describe("Hidden override"), - colSpan: external_exports.number().int().min(1).max(4).optional().describe("Column span in grid layout (1-4)"), - widget: external_exports.string().optional().describe("Custom widget/component name"), - dependsOn: external_exports.string().optional().describe("Parent field name for cascading"), - visibleOn: external_exports.string().optional().describe("Visibility condition expression") -}); -var FormSectionSchema = external_exports.object({ - label: I18nLabelSchema2.optional(), - collapsible: external_exports.boolean().default(false), - collapsed: external_exports.boolean().default(false), - columns: external_exports.enum(["1", "2", "3", "4"]).default("2").transform((val) => parseInt(val)), - fields: external_exports.array(external_exports.union([ - external_exports.string(), - // Legacy: simple field name - FormFieldSchema - // Enhanced: detailed field config - ])) -}); -var FormViewSchema = external_exports.object({ - type: external_exports.enum([ - "simple", - // Single column or sections - "tabbed", - // Tabs - "wizard", - // Step by step - "split", - // Master-Detail split - "drawer", - // Side panel - "modal" - // Dialog - ]).default("simple"), - /** Data Source Configuration */ - data: ViewDataSchema.optional().describe('Data source configuration (defaults to "object" provider)'), - sections: external_exports.array(FormSectionSchema).optional(), - // For simple layout - groups: external_exports.array(FormSectionSchema).optional(), - // Legacy support -> alias to sections - /** Default Sort for Related Lists (e.g., sort child records by date) */ - defaultSort: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - order: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction") - })).optional().describe("Default sort order for related list views within this form"), - /** Public form sharing configuration */ - sharing: SharingConfigSchema.optional().describe("Public sharing configuration for this form"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema2.optional().describe("ARIA accessibility attributes for the form view") -}); -var ViewSchema = external_exports.object({ - list: ListViewSchema.optional(), - // Default list view - form: FormViewSchema.optional(), - // Default form view - listViews: external_exports.record(external_exports.string(), ListViewSchema).optional().describe("Additional named list views"), - formViews: external_exports.record(external_exports.string(), FormViewSchema).optional().describe("Additional named form views") -}); -var RLSOperation = external_exports.enum(["select", "insert", "update", "delete", "all"]); -var RowLevelSecurityPolicySchema = external_exports.object({ - /** - * Unique identifier for this policy. - * Must be unique within the object. - * Use snake_case following ObjectStack naming conventions. - * - * @example "tenant_isolation", "owner_access", "manager_team_view" - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Policy unique identifier (snake_case)"), - /** - * Human-readable label for the policy. - * Used in admin UI and logs. - * - * @example "Multi-Tenant Data Isolation", "Owner-Based Access" - */ - label: external_exports.string().optional().describe("Human-readable policy label"), - /** - * Description explaining what this policy does and why. - * Helps with governance and compliance. - * - * @example "Ensures users can only access records from their own tenant organization" - */ - description: external_exports.string().optional().describe("Policy description and business justification"), - /** - * Target object (table) this policy applies to. - * Must reference a valid ObjectStack object name. - * - * @example "account", "opportunity", "contact", "custom_object" - */ - object: external_exports.string().describe("Target object name"), - /** - * Database operation(s) this policy applies to. - * - * - **select**: Controls read access (SELECT queries) - * - **insert**: Controls insert access (INSERT statements) - * - **update**: Controls update access (UPDATE statements) - * - **delete**: Controls delete access (DELETE statements) - * - **all**: Applies to all operations - * - * @example "select" - Most common, controls what users can view - * @example "all" - Apply same rule to all operations - */ - operation: RLSOperation.describe("Database operation this policy applies to"), - /** - * USING clause - Filter condition for SELECT/UPDATE/DELETE. - * - * This is a SQL-like expression evaluated for each row. - * Only rows where this expression returns TRUE are accessible. - * - * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed). - * For SELECT/UPDATE/DELETE operations, USING is required. - * - * **Security Note**: RLS conditions are executed at the database level with - * parameterized queries. The implementation must use prepared statements - * to prevent SQL injection. Never concatenate user input directly into - * RLS conditions. - * - * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations - * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain - * semantic equivalence. - * - * Available context variables: - * - `current_user.id` - Current user's ID - * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext) - * - `current_user.role` - Current user's role - * - `current_user.department` - Current user's department - * - `current_user.*` - Any custom user field - * - `NOW()` - Current timestamp - * - `CURRENT_DATE` - Current date - * - `CURRENT_TIME` - Current time - * - * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`), - * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`). - * Implementations must handle this mapping. - * - * Supported operators: - * - Comparison: =, !=, <, >, <=, >=, <> (not equal) - * - Logical: AND, OR, NOT - * - NULL checks: IS NULL, IS NOT NULL - * - Set operations: IN, NOT IN - * - String: LIKE, NOT LIKE, ILIKE (case-insensitive) - * - Pattern matching: ~ (regex), !~ (not regex) - * - Subqueries: (SELECT ...) - * - Array operations: ANY, ALL - * - * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE) - * - * @example "tenant_id = current_user.tenant_id" - * @example "owner_id = current_user.id OR created_by = current_user.id" - * @example "department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)" - * @example "status = 'active' AND expiry_date > NOW()" - */ - using: external_exports.string().optional().describe("Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies."), - /** - * CHECK clause - Validation for INSERT/UPDATE operations. - * - * Similar to USING but applies to new/modified rows. - * Prevents users from creating/updating rows they wouldn't be able to see. - * - * **Default Behavior**: If not specified, implementations should use the - * USING clause as the CHECK clause. This ensures data integrity by preventing - * users from creating records they cannot view. - * - * Use cases: - * - Prevent cross-tenant data creation - * - Enforce mandatory field values - * - Validate data integrity rules - * - Restrict certain operations (e.g., only allow creating "draft" status) - * - * @example "tenant_id = current_user.tenant_id" - * @example "status IN ('draft', 'pending')" - Only allow certain statuses - * @example "created_by = current_user.id" - Must be the creator - */ - check: external_exports.string().optional().describe("Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)"), - /** - * Restrict this policy to specific roles. - * If specified, only users with these roles will have this policy applied. - * If omitted, policy applies to all users (except those with bypassRLS permission). - * - * Role names must match defined roles in the system. - * - * @example ["sales_rep", "account_manager"] - * @example ["employee"] - Apply to all employees - * @example ["guest"] - Special restrictions for guests - */ - roles: external_exports.array(external_exports.string()).optional().describe("Roles this policy applies to (omit for all roles)"), - /** - * Whether this policy is currently active. - * Disabled policies are not evaluated. - * Useful for temporary policy changes without deletion. - * - * @default true - */ - enabled: external_exports.boolean().default(true).describe("Whether this policy is active"), - /** - * Policy priority for conflict resolution. - * Higher numbers = higher priority. - * When multiple policies apply, the most permissive wins (OR logic). - * Priority is only used for ordering evaluation (performance). - * - * @default 0 - */ - priority: external_exports.number().int().default(0).describe("Policy evaluation priority (higher = evaluated first)"), - /** - * Tags for policy categorization and reporting. - * Useful for governance, compliance, and auditing. - * - * @example ["compliance", "gdpr", "pci"] - * @example ["multi-tenant", "security"] - */ - tags: external_exports.array(external_exports.string()).optional().describe("Policy categorization tags") -}).superRefine((data, ctx) => { - if (!data.using && !data.check) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: 'At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".' - }); - } -}); -external_exports.object({ - /** ISO 8601 timestamp of the evaluation */ - timestamp: external_exports.string().describe("ISO 8601 timestamp of the evaluation"), - /** ID of the user whose access was evaluated */ - userId: external_exports.string().describe("User ID whose access was evaluated"), - /** Database operation being performed */ - operation: external_exports.enum(["select", "insert", "update", "delete"]).describe("Database operation being performed"), - /** Target object (table) name */ - object: external_exports.string().describe("Target object name"), - /** Name of the RLS policy evaluated */ - policyName: external_exports.string().describe("Name of the RLS policy evaluated"), - /** Whether access was granted */ - granted: external_exports.boolean().describe("Whether access was granted"), - /** Time taken to evaluate the policy in milliseconds */ - evaluationDurationMs: external_exports.number().describe("Policy evaluation duration in milliseconds"), - /** Which USING/CHECK clause matched */ - matchedCondition: external_exports.string().optional().describe("Which USING/CHECK clause matched"), - /** Number of rows affected by the operation */ - rowCount: external_exports.number().optional().describe("Number of rows affected"), - /** Additional metadata for the audit event */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional audit event metadata") -}); -var RLSAuditConfigSchema = external_exports.object({ - /** Enable RLS audit logging */ - enabled: external_exports.boolean().describe("Enable RLS audit logging"), - /** Which evaluations to log */ - logLevel: external_exports.enum(["all", "denied_only", "granted_only", "none"]).describe("Which evaluations to log"), - /** Where to send audit logs */ - destination: external_exports.enum(["system_log", "audit_trail", "external"]).describe("Audit log destination"), - /** Sampling rate for high-traffic environments (0-1) */ - sampleRate: external_exports.number().min(0).max(1).describe("Sampling rate (0-1) for high-traffic environments"), - /** Number of days to retain audit logs */ - retentionDays: external_exports.number().int().default(90).describe("Audit log retention period in days"), - /** Whether to include row data in audit logs (security-sensitive) */ - includeRowData: external_exports.boolean().default(false).describe("Include row data in audit logs (security-sensitive)"), - /** Alert when access is denied */ - alertOnDenied: external_exports.boolean().default(true).describe("Send alerts when access is denied") -}); -external_exports.object({ - /** - * Global RLS enable/disable flag. - * When false, all RLS policies are ignored (use with caution!). - * - * @default true - */ - enabled: external_exports.boolean().default(true).describe("Enable RLS enforcement globally"), - /** - * Default behavior when no policies match. - * - * - **deny**: Deny access (secure default) - * - **allow**: Allow access (permissive mode, not recommended) - * - * @default "deny" - */ - defaultPolicy: external_exports.enum(["deny", "allow"]).default("deny").describe("Default action when no policies match"), - /** - * Whether to allow superusers to bypass RLS. - * Superusers include system administrators and service accounts. - * - * @default true - */ - allowSuperuserBypass: external_exports.boolean().default(true).describe("Allow superusers to bypass RLS"), - /** - * List of roles that can bypass RLS. - * Users with these roles see all records regardless of policies. - * - * @example ["system_admin", "data_auditor"] - */ - bypassRoles: external_exports.array(external_exports.string()).optional().describe("Roles that bypass RLS (see all data)"), - /** - * Whether to log RLS policy evaluations. - * Useful for debugging and auditing. - * Can impact performance if enabled globally. - * - * @default false - */ - logEvaluations: external_exports.boolean().default(false).describe("Log RLS policy evaluations for debugging"), - /** - * Cache RLS policy evaluation results. - * Can improve performance for frequently accessed records. - * Cache is invalidated when policies change or user context changes. - * - * @default true - */ - cacheResults: external_exports.boolean().default(true).describe("Cache RLS evaluation results"), - /** - * Cache TTL in seconds. - * How long to cache RLS evaluation results. - * - * @default 300 (5 minutes) - */ - cacheTtlSeconds: external_exports.number().int().positive().default(300).describe("Cache TTL in seconds"), - /** - * Performance optimization: Pre-fetch user context. - * Load user context once per request instead of per-query. - * - * @default true - */ - prefetchUserContext: external_exports.boolean().default(true).describe("Pre-fetch user context for performance"), - /** - * Audit logging configuration for RLS evaluations. - */ - audit: RLSAuditConfigSchema.optional().describe("RLS audit logging configuration") -}); -external_exports.object({ - /** - * User ID - */ - id: external_exports.string().describe("User ID"), - /** - * User email - */ - email: external_exports.string().email().optional().describe("User email"), - /** - * Tenant/Organization ID - */ - tenantId: external_exports.string().optional().describe("Tenant/Organization ID"), - /** - * User role(s) - */ - role: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.string()) - ]).optional().describe("User role(s)"), - /** - * User department - */ - department: external_exports.string().optional().describe("User department"), - /** - * Additional custom attributes - * Can include any custom user fields for RLS evaluation - */ - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom user attributes") -}); -external_exports.object({ - /** - * Policy name that was evaluated - */ - policyName: external_exports.string().describe("Policy name"), - /** - * Whether access was granted - */ - granted: external_exports.boolean().describe("Whether access was granted"), - /** - * Evaluation duration in milliseconds - */ - durationMs: external_exports.number().optional().describe("Evaluation duration in milliseconds"), - /** - * Error message if evaluation failed - */ - error: external_exports.string().optional().describe("Error message if evaluation failed"), - /** - * Evaluated USING clause result - */ - usingResult: external_exports.boolean().optional().describe("USING clause evaluation result"), - /** - * Evaluated CHECK clause result (for INSERT/UPDATE) - */ - checkResult: external_exports.boolean().optional().describe("CHECK clause evaluation result") -}); -var ObjectPermissionSchema = external_exports.object({ - /** C: Create */ - allowCreate: external_exports.boolean().default(false).describe("Create permission"), - /** R: Read (Owned records or Shared records) */ - allowRead: external_exports.boolean().default(false).describe("Read permission"), - /** U: Edit (Owned records or Shared records) */ - allowEdit: external_exports.boolean().default(false).describe("Edit permission"), - /** D: Delete (Owned records or Shared records) */ - allowDelete: external_exports.boolean().default(false).describe("Delete permission"), - /** Lifecycle Operations */ - allowTransfer: external_exports.boolean().default(false).describe("Change record ownership"), - allowRestore: external_exports.boolean().default(false).describe("Restore from trash (Undelete)"), - allowPurge: external_exports.boolean().default(false).describe("Permanently delete (Hard Delete/GDPR)"), - /** - * View All Records: Super-user read access. - * Bypasses Sharing Rules and Ownership checks. - * Equivalent to Microsoft Dataverse "Organization" level read access. - */ - viewAllRecords: external_exports.boolean().default(false).describe("View All Data (Bypass Sharing)"), - /** - * Modify All Records: Super-user write access. - * Bypasses Sharing Rules and Ownership checks. - * Equivalent to Microsoft Dataverse "Organization" level write access. - */ - modifyAllRecords: external_exports.boolean().default(false).describe("Modify All Data (Bypass Sharing)") -}); -var FieldPermissionSchema = external_exports.object({ - /** Can see this field */ - readable: external_exports.boolean().default(true).describe("Field read access"), - /** Can edit this field */ - editable: external_exports.boolean().default(false).describe("Field edit access") -}); -external_exports.object({ - /** Unique permission set name */ - name: SnakeCaseIdentifierSchema2.describe("Permission set unique name (lowercase snake_case)"), - /** Display label */ - label: external_exports.string().optional().describe("Display label"), - /** Is this a Profile? (Base set for a user) */ - isProfile: external_exports.boolean().default(false).describe("Whether this is a user profile"), - /** Object Permissions Map: -> permissions */ - objects: external_exports.record(external_exports.string(), ObjectPermissionSchema).describe("Entity permissions"), - /** Field Permissions Map: . -> permissions */ - fields: external_exports.record(external_exports.string(), FieldPermissionSchema).optional().describe("Field level security"), - /** System permissions (e.g., "manage_users") */ - systemPermissions: external_exports.array(external_exports.string()).optional().describe("System level capabilities"), - /** - * Tab/App Visibility Permissions (Salesforce Pattern) - * Controls which app tabs are visible, hidden, or set as default for this permission set. - * - * @example - * ```typescript - * tabPermissions: { - * 'app_crm': 'visible', - * 'app_admin': 'hidden', - * 'app_sales': 'default_on' - * } - * ``` - */ - tabPermissions: external_exports.record(external_exports.string(), external_exports.enum(["visible", "hidden", "default_on", "default_off"])).optional().describe("App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)"), - /** - * Row-Level Security Rules - * - * Row-level security policies that filter records based on user context. - * These rules are applied in addition to object-level permissions. - * - * Uses the canonical RLS protocol from rls.zod.ts for comprehensive - * row-level security features including PostgreSQL-style USING and CHECK clauses. - * - * @see {@link RowLevelSecurityPolicySchema} for full RLS specification - * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation - * - * @example Multi-tenant isolation - * ```typescript - * rls: [{ - * name: 'tenant_filter', - * object: 'account', - * operation: 'select', - * using: 'tenant_id = current_user.tenant_id' - * }] - * ``` - */ - rowLevelSecurity: external_exports.array(RowLevelSecurityPolicySchema).optional().describe("Row-level security policies (see rls.zod.ts for full spec)"), - /** - * Context-Based Access Control Variables - * - * Custom context variables that can be referenced in RLS rules. - * These variables are evaluated at runtime based on the user's session. - * - * Common context variables: - * - `current_user.id` - Current user ID - * - `current_user.tenant_id` - User's tenant/organization ID - * - `current_user.department` - User's department - * - `current_user.role` - User's role - * - `current_user.region` - User's geographic region - * - * @example Custom context - * ```typescript - * contextVariables: { - * allowed_regions: ['US', 'EU'], - * access_level: 2, - * custom_attribute: 'value' - * } - * ``` - */ - contextVariables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Context variables for RLS evaluation") -}); -var WorkflowTriggerType = external_exports.enum([ - "on_create", - // When record is created - "on_update", - // When record is updated - "on_create_or_update", - // Both - "on_delete", - // When record is deleted - "schedule" - // Time-based (cron) -]); -var FieldUpdateActionSchema = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("field_update"), - field: external_exports.string().describe("Field to update"), - value: external_exports.unknown().describe("Value or Formula to set") -}); -var EmailAlertActionSchema = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("email_alert"), - template: external_exports.string().describe("Email template ID/DevName"), - recipients: external_exports.array(external_exports.string()).describe("List of recipient emails or user IDs") -}); -var ConnectorActionRefSchema = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("connector_action"), - connectorId: external_exports.string().describe("Target Connector ID (e.g. slack, twilio)"), - actionId: external_exports.string().describe("Target Action ID (e.g. send_message)"), - input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Input parameters matching the action schema") -}); -var HttpCallActionSchema = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("http_call"), - url: external_exports.string().describe("Target URL"), - method: external_exports.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).default("POST").describe("HTTP Method"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP Headers"), - body: external_exports.string().optional().describe("Request body (JSON or text)") -}); -var TaskCreationActionSchema = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("task_creation"), - taskObject: external_exports.string().describe('Task object name (e.g., "task", "project_task")'), - subject: external_exports.string().describe("Task subject/title"), - description: external_exports.string().optional().describe("Task description"), - assignedTo: external_exports.string().optional().describe("User ID or field reference for assignee"), - dueDate: external_exports.string().optional().describe("Due date (ISO string or formula)"), - priority: external_exports.string().optional().describe("Task priority"), - relatedTo: external_exports.string().optional().describe("Related record ID or field reference"), - additionalFields: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom fields") -}); -var PushNotificationActionSchema = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("push_notification"), - title: external_exports.string().describe("Notification title"), - body: external_exports.string().describe("Notification body text"), - recipients: external_exports.array(external_exports.string()).describe("User IDs or device tokens"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data payload"), - badge: external_exports.number().optional().describe("Badge count (iOS)"), - sound: external_exports.string().optional().describe("Notification sound"), - clickAction: external_exports.string().optional().describe("Action/URL when notification is clicked") -}); -var CustomScriptActionSchema = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("custom_script"), - language: external_exports.enum(["javascript", "typescript", "python"]).default("javascript").describe("Script language"), - code: external_exports.string().describe("Script code to execute"), - timeout: external_exports.number().default(3e4).describe("Execution timeout in milliseconds"), - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context variables") -}); -var WorkflowActionSchema = external_exports.discriminatedUnion("type", [ - FieldUpdateActionSchema, - EmailAlertActionSchema, - HttpCallActionSchema, - ConnectorActionRefSchema, - TaskCreationActionSchema, - PushNotificationActionSchema, - CustomScriptActionSchema -]); -var TimeTriggerSchema = external_exports.object({ - id: external_exports.string().optional().describe("Unique identifier"), - /** Timing Logic */ - timeLength: external_exports.number().int().describe("Duration amount (e.g. 1, 30)"), - timeUnit: external_exports.enum(["minutes", "hours", "days"]).describe("Unit of time"), - /** Reference Point */ - offsetDirection: external_exports.enum(["before", "after"]).describe("Before or After the reference date"), - offsetFrom: external_exports.enum(["trigger_date", "date_field"]).describe("Basis for calculation"), - dateField: external_exports.string().optional().describe("Date field to calculate from (required if offsetFrom is date_field)"), - /** Actions */ - actions: external_exports.array(WorkflowActionSchema).describe("Actions to execute at the scheduled time") -}); -var WorkflowRuleSchema = external_exports.object({ - /** Machine name */ - name: SnakeCaseIdentifierSchema2.describe("Unique workflow name (lowercase snake_case)"), - /** Target Object */ - objectName: external_exports.string().describe("Target Object"), - /** When to evaluate the rule */ - triggerType: WorkflowTriggerType.describe("When to evaluate"), - /** - * Condition to start the workflow. - * If empty, runs on every trigger event. - */ - criteria: external_exports.string().optional().describe("Formula condition. If TRUE, actions execute."), - /** Actions to execute immediately */ - actions: external_exports.array(WorkflowActionSchema).optional().describe("Immediate actions"), - /** - * Time-Dependent Actions - * Actions scheduled to run in the future. - */ - timeTriggers: external_exports.array(TimeTriggerSchema).optional().describe("Scheduled actions relative to trigger or date field"), - /** Active status */ - active: external_exports.boolean().default(true).describe("Whether this workflow is active"), - /** Execution Order */ - executionOrder: external_exports.number().int().min(0).default(100).describe("Deterministic execution order when multiple workflows match (lower runs first)"), - /** Recursion Control */ - reevaluateOnChange: external_exports.boolean().default(false).describe("Re-evaluate rule if field updates change the record validity") -}); -var LocaleSchema2 = external_exports.string().describe("BCP-47 Language Tag (e.g. en-US, zh-CN)"); -var FieldTranslationSchema2 = external_exports.object({ - label: external_exports.string().optional().describe("Translated field label"), - help: external_exports.string().optional().describe("Translated help text"), - placeholder: external_exports.string().optional().describe("Translated placeholder text for form inputs"), - options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Option value to translated label map") -}).describe("Translation data for a single field"); -var ObjectTranslationDataSchema2 = external_exports.object({ - /** Translated singular label for the object */ - label: external_exports.string().describe("Translated singular label"), - /** Translated plural label for the object */ - pluralLabel: external_exports.string().optional().describe("Translated plural label"), - /** Field-level translations keyed by field name (snake_case) */ - fields: external_exports.record(external_exports.string(), FieldTranslationSchema2).optional().describe("Field-level translations") -}).describe("Translation data for a single object"); -var TranslationDataSchema2 = external_exports.object({ - /** Object translations */ - objects: external_exports.record(external_exports.string(), ObjectTranslationDataSchema2).optional().describe("Object translations keyed by object name"), - /** App/Menu translations */ - apps: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().describe("Translated app label"), - description: external_exports.string().optional().describe("Translated app description") - })).optional().describe("App translations keyed by app name"), - /** UI Messages */ - messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID"), - /** Validation Error Messages */ - validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%"})') -}).describe("Translation data for objects, apps, and UI messages"); -external_exports.record(LocaleSchema2, TranslationDataSchema2).describe("Map of locale codes to translation data"); -var TranslationFileOrganizationSchema2 = external_exports.enum([ - "bundled", - "per_locale", - "per_namespace" -]).describe("Translation file organization strategy"); -var MessageFormatSchema2 = external_exports.enum([ - "icu", - "simple" -]).describe("Message interpolation format: ICU MessageFormat or simple {variable} replacement"); -external_exports.object({ - /** Default locale for the application */ - defaultLocale: LocaleSchema2.describe('Default locale (e.g., "en")'), - /** Supported BCP-47 locale codes */ - supportedLocales: external_exports.array(LocaleSchema2).describe("Supported BCP-47 locale codes"), - /** Fallback locale when translation is not found */ - fallbackLocale: LocaleSchema2.optional().describe("Fallback locale code"), - /** How translation files are organized on disk */ - fileOrganization: TranslationFileOrganizationSchema2.default("per_locale").describe("File organization strategy"), - /** - * Message interpolation format. - * When set to `'icu'`, messages and validationMessages are expected to use - * ICU MessageFormat syntax (plurals, select, number/date skeletons). - * @default 'simple' - */ - messageFormat: MessageFormatSchema2.default("simple").describe("Message interpolation format (ICU MessageFormat or simple)"), - /** Load translations on demand instead of eagerly */ - lazyLoad: external_exports.boolean().default(false).describe("Load translations on demand"), - /** Cache loaded translations in memory */ - cache: external_exports.boolean().default(true).describe("Cache loaded translations") -}).describe("Internationalization configuration"); -var OptionTranslationMapSchema2 = external_exports.record(external_exports.string(), external_exports.string()).describe("Option value to translated label map"); -var ObjectTranslationNodeSchema2 = external_exports.object({ - /** Translated singular label */ - label: external_exports.string().describe("Translated singular label"), - /** Translated plural label */ - pluralLabel: external_exports.string().optional().describe("Translated plural label"), - /** Translated object description */ - description: external_exports.string().optional().describe("Translated object description"), - /** Translated help text shown in tooltips or guidance panels */ - helpText: external_exports.string().optional().describe("Translated help text for the object"), - /** Field-level translations keyed by field name (snake_case) */ - fields: external_exports.record(external_exports.string(), FieldTranslationSchema2).optional().describe("Field translations keyed by field name"), - /** - * Global picklist / select option overrides scoped to this object. - * Keyed by field name → { optionValue: translatedLabel }. - */ - _options: external_exports.record(external_exports.string(), OptionTranslationMapSchema2).optional().describe("Object-scoped picklist option translations keyed by field name"), - /** View translations keyed by view name */ - _views: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated view label"), - description: external_exports.string().optional().describe("Translated view description") - })).optional().describe("View translations keyed by view name"), - /** Section (form section / tab) translations keyed by section name */ - _sections: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated section label") - })).optional().describe("Section translations keyed by section name"), - /** Action translations keyed by action name */ - _actions: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated action label"), - confirmMessage: external_exports.string().optional().describe("Translated confirmation message") - })).optional().describe("Action translations keyed by action name"), - /** Notification message translations keyed by notification name */ - _notifications: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated notification title"), - body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") - })).optional().describe("Notification translations keyed by notification name"), - /** Error message translations keyed by error code */ - _errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Error message translations keyed by error code") -}).describe("Object-first aggregated translation node"); -external_exports.object({ - /** - * Bundle-level metadata. - * Provides locale-aware rendering hints such as text direction (bidi) - * and the canonical locale code this bundle represents. - */ - _meta: external_exports.object({ - /** BCP-47 locale code this bundle represents */ - locale: external_exports.string().optional().describe("BCP-47 locale code for this bundle"), - /** Text direction for the locale */ - direction: external_exports.enum(["ltr", "rtl"]).optional().describe("Text direction: left-to-right or right-to-left") - }).optional().describe("Bundle-level metadata (locale, bidi direction)"), - /** - * Namespace for plugin/extension isolation. - * When multiple plugins contribute translations, each should use a unique - * namespace to avoid key collisions (e.g. "crm", "helpdesk", "plugin-xyz"). - */ - namespace: external_exports.string().optional().describe("Namespace for plugin isolation to avoid translation key collisions"), - /** Object-first translations keyed by object name (snake_case) */ - o: external_exports.record(external_exports.string(), ObjectTranslationNodeSchema2).optional().describe("Object-first translations keyed by object name"), - /** Global picklist options not bound to any specific object */ - _globalOptions: external_exports.record(external_exports.string(), OptionTranslationMapSchema2).optional().describe("Global picklist option translations keyed by option set name"), - /** App-level translations */ - app: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().describe("Translated app label"), - description: external_exports.string().optional().describe("Translated app description") - })).optional().describe("App translations keyed by app name"), - /** Navigation menu translations */ - nav: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Navigation item translations keyed by nav item name"), - /** Dashboard translations keyed by dashboard name */ - dashboard: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated dashboard label"), - description: external_exports.string().optional().describe("Translated dashboard description") - })).optional().describe("Dashboard translations keyed by dashboard name"), - /** Report translations keyed by report name */ - reports: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated report label"), - description: external_exports.string().optional().describe("Translated report description") - })).optional().describe("Report translations keyed by report name"), - /** Page translations keyed by page name */ - pages: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated page title"), - description: external_exports.string().optional().describe("Translated page description") - })).optional().describe("Page translations keyed by page name"), - /** UI message translations (supports ICU MessageFormat when enabled) */ - messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID (supports ICU MessageFormat)"), - /** Validation error message translations (supports ICU MessageFormat when enabled) */ - validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Validation error message translations keyed by rule name (supports ICU MessageFormat)"), - /** Global notification translations not bound to a specific object */ - notifications: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated notification title"), - body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") - })).optional().describe("Global notification translations keyed by notification name"), - /** Global error message translations not bound to a specific object */ - errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Global error message translations keyed by error code") -}).describe("Object-first application translation bundle for a single locale"); -var TranslationDiffStatusSchema2 = external_exports.enum([ - "missing", - "redundant", - "stale" -]).describe("Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)"); -var TranslationDiffItemSchema2 = external_exports.object({ - /** Dot-path translation key (e.g. "o.account.fields.website.label") */ - key: external_exports.string().describe("Dot-path translation key"), - /** Diff status */ - status: TranslationDiffStatusSchema2.describe("Diff status of this translation key"), - /** Object name if the key belongs to an object translation node */ - objectName: external_exports.string().optional().describe("Associated object name (snake_case)"), - /** Locale code */ - locale: external_exports.string().describe("BCP-47 locale code"), - /** - * Hash of the source metadata value at the time the translation was made. - * Used by CLI/Workbench to detect stale translations without a full diff. - */ - sourceHash: external_exports.string().optional().describe("Hash of source metadata for precise stale detection"), - /** - * AI-suggested translation text for missing or stale entries. - * Populated by AI translation hooks or TMS integrations. - */ - aiSuggested: external_exports.string().optional().describe("AI-suggested translation for this key"), - /** Confidence score (0-1) for the AI suggestion */ - aiConfidence: external_exports.number().min(0).max(1).optional().describe("AI suggestion confidence score (0\u20131)") -}).describe("A single translation diff item"); -var CoverageBreakdownEntrySchema2 = external_exports.object({ - /** Group category (e.g. "fields", "views", "actions", "messages") */ - group: external_exports.string().describe("Translation group category"), - /** Total translatable keys in this group */ - totalKeys: external_exports.number().int().nonnegative().describe("Total keys in this group"), - /** Number of translated keys in this group */ - translatedKeys: external_exports.number().int().nonnegative().describe("Translated keys in this group"), - /** Coverage percentage for this group */ - coveragePercent: external_exports.number().min(0).max(100).describe("Coverage percentage for this group") -}).describe("Coverage breakdown for a single translation group"); -external_exports.object({ - /** BCP-47 locale code */ - locale: external_exports.string().describe("BCP-47 locale code"), - /** Optional object name scope */ - objectName: external_exports.string().optional().describe("Object name scope (omit for full bundle)"), - /** Total translatable keys derived from metadata */ - totalKeys: external_exports.number().int().nonnegative().describe("Total translatable keys from metadata"), - /** Number of keys that have a translation */ - translatedKeys: external_exports.number().int().nonnegative().describe("Number of translated keys"), - /** Number of missing translations */ - missingKeys: external_exports.number().int().nonnegative().describe("Number of missing translations"), - /** Number of redundant (orphaned) translations */ - redundantKeys: external_exports.number().int().nonnegative().describe("Number of redundant translations"), - /** Number of stale translations */ - staleKeys: external_exports.number().int().nonnegative().describe("Number of stale translations"), - /** Coverage percentage (0-100) */ - coveragePercent: external_exports.number().min(0).max(100).describe("Translation coverage percentage"), - /** Individual diff items */ - items: external_exports.array(TranslationDiffItemSchema2).describe("Detailed diff items"), - /** - * Per-group coverage breakdown for translation project management. - * Each entry represents a logical group (e.g. "fields", "views", "actions", - * "messages") with its own coverage statistics. - */ - breakdown: external_exports.array(CoverageBreakdownEntrySchema2).optional().describe("Per-group coverage breakdown") -}).describe("Aggregated translation coverage result"); -var CapabilityConformanceLevelSchema = external_exports.enum([ - "full", - // Complete implementation of all protocol features - "partial", - // Subset implementation with specific features listed - "experimental", - // Unstable/preview implementation - "deprecated" - // Still supported but scheduled for removal -]).describe("Level of protocol conformance"); -var ProtocolVersionSchema = external_exports.object({ - major: external_exports.number().int().min(0), - minor: external_exports.number().int().min(0), - patch: external_exports.number().int().min(0) -}).describe("Semantic version of the protocol"); -var ProtocolReferenceSchema = external_exports.object({ - /** - * Protocol identifier using reverse domain notation. - * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major} - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+protocol\.[a-z][a-z0-9._]*\.v\d+$/).describe("Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)"), - /** - * Human-readable protocol name - */ - label: external_exports.string(), - /** - * Protocol version - */ - version: ProtocolVersionSchema, - /** - * Detailed protocol specification URL or file reference - */ - specification: external_exports.string().optional().describe("URL or path to protocol specification"), - /** - * Brief description of what this protocol defines - */ - description: external_exports.string().optional() -}); -var ProtocolFeatureSchema = external_exports.object({ - name: external_exports.string().describe("Feature identifier within the protocol"), - enabled: external_exports.boolean().default(true), - description: external_exports.string().optional(), - sinceVersion: external_exports.string().optional().describe("Version when this feature was added"), - deprecatedSince: external_exports.string().optional().describe("Version when deprecated") -}); -var PluginCapabilitySchema = external_exports.object({ - /** - * The protocol being implemented - */ - protocol: ProtocolReferenceSchema, - /** - * Conformance level - */ - conformance: CapabilityConformanceLevelSchema.default("full"), - /** - * Specific features implemented (required if conformance is 'partial') - */ - implementedFeatures: external_exports.array(external_exports.string()).optional().describe("List of implemented feature names"), - /** - * Optional feature flags indicating advanced capabilities - */ - features: external_exports.array(ProtocolFeatureSchema).optional(), - /** - * Custom metadata for vendor-specific information - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Testing/Certification status - */ - certified: external_exports.boolean().default(false).describe("Has passed official conformance tests"), - certificationDate: external_exports.string().datetime().optional() -}); -var PluginInterfaceSchema = external_exports.object({ - /** - * Unique interface identifier - * Format: {plugin-id}.interface.{name} - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+interface\.[a-z][a-z0-9._]+$/).describe("Unique interface identifier"), - /** - * Interface name - */ - name: external_exports.string(), - /** - * Description of what this interface provides - */ - description: external_exports.string().optional(), - /** - * Interface version - */ - version: ProtocolVersionSchema, - /** - * Methods exposed by this interface - */ - methods: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Method name"), - description: external_exports.string().optional(), - parameters: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string().describe("Type notation (e.g., string, number, User)"), - required: external_exports.boolean().default(true), - description: external_exports.string().optional() - })).optional(), - returnType: external_exports.string().optional().describe("Return value type"), - async: external_exports.boolean().default(false).describe("Whether method returns a Promise") - })), - /** - * Events emitted by this interface - */ - events: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Event name"), - description: external_exports.string().optional(), - payload: external_exports.string().optional().describe("Event payload type") - })).optional(), - /** - * Stability level - */ - stability: external_exports.enum(["stable", "beta", "alpha", "experimental"]).default("stable") -}); -var PluginDependencySchema = external_exports.object({ - /** - * Plugin ID using reverse domain notation - */ - pluginId: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Required plugin identifier"), - /** - * Version constraint (supports semver ranges) - * Examples: "1.0.0", "^1.2.3", ">=2.0.0 <3.0.0" - */ - version: external_exports.string().describe("Semantic version constraint"), - /** - * Whether this dependency is optional - */ - optional: external_exports.boolean().default(false), - /** - * Reason for the dependency - */ - reason: external_exports.string().optional(), - /** - * Minimum required capabilities from the dependency - */ - requiredCapabilities: external_exports.array(external_exports.string()).optional().describe("Protocol IDs the dependency must support") -}); -var ExtensionPointSchema = external_exports.object({ - /** - * Extension point identifier - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+extension\.[a-z][a-z0-9._]+$/).describe("Unique extension point identifier"), - /** - * Extension point name - */ - name: external_exports.string(), - /** - * Description - */ - description: external_exports.string().optional(), - /** - * Type of extension point - */ - type: external_exports.enum([ - "action", - // Plugins can register executable actions - "hook", - // Plugins can listen to lifecycle events - "widget", - // Plugins can contribute UI widgets - "provider", - // Plugins can provide data/services - "transformer", - // Plugins can transform data - "validator", - // Plugins can validate data - "decorator" - // Plugins can enhance/wrap functionality - ]), - /** - * Expected interface contract for extensions - */ - contract: external_exports.object({ - input: external_exports.string().optional().describe("Input type/schema"), - output: external_exports.string().optional().describe("Output type/schema"), - signature: external_exports.string().optional().describe("Function signature if applicable") - }).optional(), - /** - * Cardinality - */ - cardinality: external_exports.enum(["single", "multiple"]).default("multiple").describe("Whether multiple extensions can register to this point") -}); -var PluginCapabilityManifestSchema = external_exports.object({ - /** - * Protocols this plugin implements - */ - implements: external_exports.array(PluginCapabilitySchema).optional().describe("List of protocols this plugin conforms to"), - /** - * Interfaces this plugin exposes to other plugins - */ - provides: external_exports.array(PluginInterfaceSchema).optional().describe("Services/APIs this plugin offers to others"), - /** - * Dependencies on other plugins - */ - requires: external_exports.array(PluginDependencySchema).optional().describe("Required plugins and their capabilities"), - /** - * Extension points this plugin defines - */ - extensionPoints: external_exports.array(ExtensionPointSchema).optional().describe("Points where other plugins can extend this plugin"), - /** - * Extensions this plugin contributes to other plugins - */ - extensions: external_exports.array(external_exports.object({ - targetPluginId: external_exports.string().describe("Plugin ID being extended"), - extensionPointId: external_exports.string().describe("Extension point identifier"), - implementation: external_exports.string().describe("Path to implementation module"), - priority: external_exports.number().int().default(100).describe("Registration priority (lower = higher priority)") - })).optional().describe("Extensions contributed to other plugins") -}); -var PluginLoadingStrategySchema = external_exports.enum([ - "eager", - // Load immediately during bootstrap (critical plugins) - "lazy", - // Load on first use (feature plugins) - "parallel", - // Load in parallel with other plugins - "deferred", - // Load after initial bootstrap complete - "on-demand" - // Load only when explicitly requested -]).describe("Plugin loading strategy"); -var PluginPreloadConfigSchema = external_exports.object({ - /** - * Enable preloading for this plugin - */ - enabled: external_exports.boolean().default(false), - /** - * Preload priority (lower = higher priority) - */ - priority: external_exports.number().int().min(0).default(100), - /** - * Resources to preload - */ - resources: external_exports.array(external_exports.enum([ - "metadata", - // Plugin manifest and metadata - "dependencies", - // Plugin dependencies - "assets", - // Static assets (icons, translations) - "code", - // JavaScript code chunks - "services" - // Service definitions - ])).optional(), - /** - * Conditions for preloading - */ - conditions: external_exports.object({ - /** - * Preload only on specific routes - */ - routes: external_exports.array(external_exports.string()).optional(), - /** - * Preload only for specific user roles - */ - roles: external_exports.array(external_exports.string()).optional(), - /** - * Preload based on device type - */ - deviceType: external_exports.array(external_exports.enum(["desktop", "mobile", "tablet"])).optional(), - /** - * Network connection quality threshold - */ - minNetworkSpeed: external_exports.enum(["slow-2g", "2g", "3g", "4g"]).optional() - }).optional() -}).describe("Plugin preloading configuration"); -var PluginCodeSplittingSchema = external_exports.object({ - /** - * Enable code splitting for this plugin - */ - enabled: external_exports.boolean().default(true), - /** - * Split strategy - */ - strategy: external_exports.enum([ - "route", - // Split by UI routes - "feature", - // Split by feature modules - "size", - // Split by bundle size threshold - "custom" - // Custom split points defined by plugin - ]).default("feature"), - /** - * Chunk naming strategy - */ - chunkNaming: external_exports.enum(["hashed", "named", "sequential"]).default("hashed"), - /** - * Maximum chunk size in KB - */ - maxChunkSize: external_exports.number().int().min(10).optional().describe("Max chunk size in KB"), - /** - * Shared dependencies optimization - */ - sharedDependencies: external_exports.object({ - enabled: external_exports.boolean().default(true), - /** - * Minimum times a module must be shared before extraction - */ - minChunks: external_exports.number().int().min(1).default(2) - }).optional() -}).describe("Plugin code splitting configuration"); -var PluginDynamicImportSchema = external_exports.object({ - /** - * Enable dynamic imports - */ - enabled: external_exports.boolean().default(true), - /** - * Import mode - */ - mode: external_exports.enum([ - "async", - // Asynchronous import (recommended) - "sync", - // Synchronous import (blocking) - "eager", - // Eager evaluation - "lazy" - // Lazy evaluation - ]).default("async"), - /** - * Prefetch strategy - */ - prefetch: external_exports.boolean().default(false).describe("Prefetch module in idle time"), - /** - * Preload strategy - */ - preload: external_exports.boolean().default(false).describe("Preload module in parallel with parent"), - /** - * Webpack magic comments support - */ - webpackChunkName: external_exports.string().optional().describe("Custom chunk name for webpack"), - /** - * Import timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4).describe("Dynamic import timeout (ms)"), - /** - * Retry configuration on import failure - */ - retry: external_exports.object({ - enabled: external_exports.boolean().default(true), - maxAttempts: external_exports.number().int().min(1).max(10).default(3), - backoffMs: external_exports.number().int().min(0).default(1e3).describe("Exponential backoff base delay") - }).optional() -}).describe("Plugin dynamic import configuration"); -var PluginInitializationSchema = external_exports.object({ - /** - * Initialization mode - */ - mode: external_exports.enum([ - "sync", - // Synchronous initialization - "async", - // Asynchronous initialization - "parallel", - // Parallel with other plugins - "sequential" - // Must complete before next plugin - ]).default("async"), - /** - * Initialization timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4), - /** - * Startup priority (lower = higher priority, earlier initialization) - */ - priority: external_exports.number().int().min(0).default(100), - /** - * Whether to continue bootstrap if this plugin fails - */ - critical: external_exports.boolean().default(false).describe("If true, kernel bootstrap fails if plugin fails"), - /** - * Retry configuration on initialization failure - */ - retry: external_exports.object({ - enabled: external_exports.boolean().default(false), - maxAttempts: external_exports.number().int().min(1).max(5).default(3), - backoffMs: external_exports.number().int().min(0).default(1e3) - }).optional(), - /** - * Health check interval for monitoring - */ - healthCheckInterval: external_exports.number().int().min(0).optional().describe("Health check interval in ms (0 = disabled)") -}).describe("Plugin initialization configuration"); -var PluginDependencyResolutionSchema = external_exports.object({ - /** - * Dependency resolution strategy - */ - strategy: external_exports.enum([ - "strict", - // Exact version match required - "compatible", - // Semver compatible versions (^) - "latest", - // Always use latest compatible - "pinned" - // Lock to specific version - ]).default("compatible"), - /** - * Peer dependency handling - */ - peerDependencies: external_exports.object({ - /** - * Whether to resolve peer dependencies - */ - resolve: external_exports.boolean().default(true), - /** - * Action on missing peer dependency - */ - onMissing: external_exports.enum(["error", "warn", "ignore"]).default("warn"), - /** - * Action on peer version mismatch - */ - onMismatch: external_exports.enum(["error", "warn", "ignore"]).default("warn") - }).optional(), - /** - * Optional dependency handling - */ - optionalDependencies: external_exports.object({ - /** - * Whether to attempt loading optional dependencies - */ - load: external_exports.boolean().default(true), - /** - * Action on optional dependency load failure - */ - onFailure: external_exports.enum(["warn", "ignore"]).default("warn") - }).optional(), - /** - * Conflict resolution - */ - conflictResolution: external_exports.enum([ - "fail", - // Fail on any version conflict - "latest", - // Use latest version - "oldest", - // Use oldest version - "manual" - // Require manual resolution - ]).default("latest"), - /** - * Circular dependency handling - */ - circularDependencies: external_exports.enum([ - "error", - // Throw error on circular dependency - "warn", - // Warn but continue - "allow" - // Allow circular dependencies - ]).default("warn") -}).describe("Plugin dependency resolution configuration"); -var PluginHotReloadSchema = external_exports.object({ - /** - * Enable hot reload - */ - enabled: external_exports.boolean().default(false), - /** - * Target environment for hot reload behavior - */ - environment: external_exports.enum([ - "development", - // Fast reload with relaxed safety (file watchers, no health validation) - "staging", - // Production-like reload with validation but relaxed rollback - "production" - // Full safety: health validation, rollback, connection draining - ]).default("development").describe("Target environment controlling safety level"), - /** - * Hot reload strategy - */ - strategy: external_exports.enum([ - "full", - // Full plugin reload (destroy and reinitialize) - "partial", - // Partial reload (update changed modules only) - "state-preserve" - // Preserve plugin state during reload - ]).default("full"), - /** - * Files to watch for changes - */ - watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to watch"), - /** - * Files to ignore - */ - ignorePatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to ignore"), - /** - * Debounce delay in milliseconds - */ - debounceMs: external_exports.number().int().min(0).default(300), - /** - * Whether to preserve state during reload - */ - preserveState: external_exports.boolean().default(false), - /** - * State serialization - */ - stateSerialization: external_exports.object({ - enabled: external_exports.boolean().default(false), - /** - * Path to state serialization handler - */ - handler: external_exports.string().optional() - }).optional(), - /** - * Hooks for hot reload lifecycle - */ - hooks: external_exports.object({ - beforeReload: external_exports.string().optional().describe("Function to call before reload"), - afterReload: external_exports.string().optional().describe("Function to call after reload"), - onError: external_exports.string().optional().describe("Function to call on reload error") - }).optional(), - /** - * Production safety configuration - * Applied when environment is 'staging' or 'production' - */ - productionSafety: external_exports.object({ - /** - * Validate plugin health before completing reload - */ - healthValidation: external_exports.boolean().default(true).describe("Run health checks after reload before accepting traffic"), - /** - * Automatically rollback to previous version on reload failure - */ - rollbackOnFailure: external_exports.boolean().default(true).describe("Auto-rollback if reloaded plugin fails health check"), - /** - * Maximum time to wait for health validation after reload (ms) - */ - healthTimeout: external_exports.number().int().min(1e3).default(3e4).describe("Health check timeout after reload in ms"), - /** - * Drain active connections before reload - */ - drainConnections: external_exports.boolean().default(true).describe("Gracefully drain active requests before reloading"), - /** - * Maximum time to wait for connection draining (ms) - */ - drainTimeout: external_exports.number().int().min(0).default(15e3).describe("Max wait time for connection draining in ms"), - /** - * Maximum number of concurrent plugin reloads - */ - maxConcurrentReloads: external_exports.number().int().min(1).default(1).describe("Limit concurrent reloads to prevent system instability"), - /** - * Minimum interval between reloads of the same plugin (ms) - */ - minReloadInterval: external_exports.number().int().min(1e3).default(5e3).describe("Cooldown period between reloads of the same plugin") - }).optional() -}).describe("Plugin hot reload configuration"); -var PluginCachingSchema = external_exports.object({ - /** - * Enable caching - */ - enabled: external_exports.boolean().default(true), - /** - * Cache storage type - */ - storage: external_exports.enum([ - "memory", - // In-memory cache (fastest, not persistent) - "disk", - // Disk cache (persistent) - "indexeddb", - // Browser IndexedDB (persistent, browser only) - "hybrid" - // Memory + Disk hybrid - ]).default("memory"), - /** - * Cache key strategy - */ - keyStrategy: external_exports.enum([ - "version", - // Cache by plugin version - "hash", - // Cache by content hash - "timestamp" - // Cache by last modified timestamp - ]).default("version"), - /** - * Cache TTL in seconds - */ - ttl: external_exports.number().int().min(0).optional().describe("Time to live in seconds (0 = infinite)"), - /** - * Maximum cache size in MB - */ - maxSize: external_exports.number().int().min(1).optional().describe("Max cache size in MB"), - /** - * Cache invalidation triggers - */ - invalidateOn: external_exports.array(external_exports.enum([ - "version-change", - "dependency-change", - "manual", - "error" - ])).optional(), - /** - * Compression - */ - compression: external_exports.object({ - enabled: external_exports.boolean().default(false), - algorithm: external_exports.enum(["gzip", "brotli", "deflate"]).default("gzip") - }).optional() -}).describe("Plugin caching configuration"); -var PluginSandboxingSchema = external_exports.object({ - /** - * Enable sandboxing - */ - enabled: external_exports.boolean().default(false), - /** - * Isolation scope - which plugins are subject to sandboxing - */ - scope: external_exports.enum([ - "automation-only", - // Sandbox automation/scripting plugins only (current behavior) - "untrusted-only", - // Sandbox plugins below a trust threshold - "all-plugins" - // Sandbox all plugins (maximum isolation) - ]).default("automation-only").describe("Which plugins are subject to isolation"), - /** - * Sandbox isolation level - */ - isolationLevel: external_exports.enum([ - "none", - // No isolation - "process", - // Separate process (Node.js worker threads) - "vm", - // VM context isolation - "iframe", - // iframe isolation (browser) - "web-worker" - // Web Worker (browser) - ]).default("none"), - /** - * Allowed capabilities - */ - allowedCapabilities: external_exports.array(external_exports.string()).optional().describe("List of allowed capability IDs"), - /** - * Resource quotas - */ - resourceQuotas: external_exports.object({ - /** - * Maximum memory usage in MB - */ - maxMemoryMB: external_exports.number().int().min(1).optional(), - /** - * Maximum CPU time in milliseconds - */ - maxCpuTimeMs: external_exports.number().int().min(100).optional(), - /** - * Maximum number of file descriptors - */ - maxFileDescriptors: external_exports.number().int().min(1).optional(), - /** - * Maximum network bandwidth in KB/s - */ - maxNetworkKBps: external_exports.number().int().min(1).optional() - }).optional(), - /** - * Permissions - */ - permissions: external_exports.object({ - /** - * Allowed API access - */ - allowedAPIs: external_exports.array(external_exports.string()).optional(), - /** - * Allowed file system paths - */ - allowedPaths: external_exports.array(external_exports.string()).optional(), - /** - * Allowed network endpoints - */ - allowedEndpoints: external_exports.array(external_exports.string()).optional(), - /** - * Allowed environment variables - */ - allowedEnvVars: external_exports.array(external_exports.string()).optional() - }).optional(), - /** - * Inter-Plugin Communication (IPC) configuration - * Enables isolated plugins to communicate with the kernel and other plugins - */ - ipc: external_exports.object({ - /** - * Enable IPC for sandboxed plugins - */ - enabled: external_exports.boolean().default(true).describe("Allow sandboxed plugins to communicate via IPC"), - /** - * IPC transport mechanism - */ - transport: external_exports.enum([ - "message-port", - // MessagePort (worker threads / Web Workers) - "unix-socket", - // Unix domain sockets (process isolation) - "tcp", - // TCP sockets (container isolation) - "memory" - // Shared memory channel (in-process VM) - ]).default("message-port").describe("IPC transport for cross-boundary communication"), - /** - * Maximum message size in bytes - */ - maxMessageSize: external_exports.number().int().min(1024).default(1048576).describe("Maximum IPC message size in bytes (default 1MB)"), - /** - * Message timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4).describe("IPC message response timeout in ms"), - /** - * Allowed service calls through IPC - */ - allowedServices: external_exports.array(external_exports.string()).optional().describe("Service names the sandboxed plugin may invoke via IPC") - }).optional() -}).describe("Plugin sandboxing configuration"); -var PluginPerformanceMonitoringSchema = external_exports.object({ - /** - * Enable performance monitoring - */ - enabled: external_exports.boolean().default(false), - /** - * Metrics to collect - */ - metrics: external_exports.array(external_exports.enum([ - "load-time", - "init-time", - "memory-usage", - "cpu-usage", - "api-calls", - "error-rate", - "cache-hit-rate" - ])).optional(), - /** - * Sampling rate (0-1, where 1 = 100%) - */ - samplingRate: external_exports.number().min(0).max(1).default(1), - /** - * Reporting interval in seconds - */ - reportingInterval: external_exports.number().int().min(1).default(60), - /** - * Performance budget thresholds - */ - budgets: external_exports.object({ - /** - * Maximum load time in milliseconds - */ - maxLoadTimeMs: external_exports.number().int().min(0).optional(), - /** - * Maximum init time in milliseconds - */ - maxInitTimeMs: external_exports.number().int().min(0).optional(), - /** - * Maximum memory usage in MB - */ - maxMemoryMB: external_exports.number().int().min(0).optional() - }).optional(), - /** - * Action on budget violation - */ - onBudgetViolation: external_exports.enum(["warn", "error", "ignore"]).default("warn") -}).describe("Plugin performance monitoring configuration"); -var PluginLoadingConfigSchema = external_exports.object({ - /** - * Loading strategy - */ - strategy: PluginLoadingStrategySchema.default("lazy"), - /** - * Preloading configuration - */ - preload: PluginPreloadConfigSchema.optional(), - /** - * Code splitting configuration - */ - codeSplitting: PluginCodeSplittingSchema.optional(), - /** - * Dynamic import configuration - */ - dynamicImport: PluginDynamicImportSchema.optional(), - /** - * Initialization configuration - */ - initialization: PluginInitializationSchema.optional(), - /** - * Dependency resolution configuration - */ - dependencyResolution: PluginDependencyResolutionSchema.optional(), - /** - * Hot reload configuration (development and production) - */ - hotReload: PluginHotReloadSchema.optional(), - /** - * Caching configuration - */ - caching: PluginCachingSchema.optional(), - /** - * Sandboxing configuration - */ - sandboxing: PluginSandboxingSchema.optional(), - /** - * Performance monitoring - */ - monitoring: PluginPerformanceMonitoringSchema.optional() -}).describe("Complete plugin loading configuration"); -external_exports.object({ - /** - * Event type - */ - type: external_exports.enum([ - "load-started", - "load-completed", - "load-failed", - "init-started", - "init-completed", - "init-failed", - "preload-started", - "preload-completed", - "cache-hit", - "cache-miss", - "hot-reload", - "dynamic-load", - // Plugin loaded at runtime - "dynamic-unload", - // Plugin unloaded at runtime - "dynamic-discover" - // Plugin discovered via registry - ]), - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Timestamp - */ - timestamp: external_exports.number().int().min(0), - /** - * Duration in milliseconds - */ - durationMs: external_exports.number().int().min(0).optional(), - /** - * Additional metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Error if event represents a failure - */ - error: external_exports.object({ - message: external_exports.string(), - code: external_exports.string().optional(), - stack: external_exports.string().optional() - }).optional() -}).describe("Plugin loading lifecycle event"); -external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Current state - */ - state: external_exports.enum([ - "pending", - // Not yet loaded - "loading", - // Currently loading - "loaded", - // Code loaded, not initialized - "initializing", - // Currently initializing - "ready", - // Fully initialized and ready - "failed", - // Failed to load or initialize - "reloading", - // Hot reloading in progress - "unloading", - // Being unloaded at runtime - "unloaded" - // Successfully unloaded (dynamic loading) - ]), - /** - * Load progress (0-100) - */ - progress: external_exports.number().min(0).max(100).default(0), - /** - * Loading start time - */ - startedAt: external_exports.number().int().min(0).optional(), - /** - * Loading completion time - */ - completedAt: external_exports.number().int().min(0).optional(), - /** - * Last error - */ - lastError: external_exports.string().optional(), - /** - * Retry count - */ - retryCount: external_exports.number().int().min(0).default(0) -}).describe("Plugin loading state"); -external_exports.object({ - ql: external_exports.object({ - object: external_exports.function().describe("Get object handle for method chaining"), - query: external_exports.function().describe("Execute a query") - }).passthrough().describe("ObjectQL Engine Interface"), - os: external_exports.object({ - getCurrentUser: external_exports.function().describe("Get the current authenticated user"), - getConfig: external_exports.function().describe("Get platform configuration") - }).passthrough().describe("ObjectStack Kernel Interface"), - logger: external_exports.object({ - debug: external_exports.function().describe("Log debug message"), - info: external_exports.function().describe("Log info message"), - warn: external_exports.function().describe("Log warning message"), - error: external_exports.function().describe("Log error message") - }).passthrough().describe("Logger Interface"), - storage: external_exports.object({ - get: external_exports.function().describe("Get a value from storage"), - set: external_exports.function().describe("Set a value in storage"), - delete: external_exports.function().describe("Delete a value from storage") - }).passthrough().describe("Storage Interface"), - i18n: external_exports.object({ - t: external_exports.function().describe("Translate a key"), - getLocale: external_exports.function().describe("Get current locale") - }).passthrough().describe("Internationalization Interface"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()), - events: external_exports.record(external_exports.string(), external_exports.unknown()), - app: external_exports.object({ - router: external_exports.object({ - get: external_exports.function().describe("Register GET route handler"), - post: external_exports.function().describe("Register POST route handler"), - use: external_exports.function().describe("Register middleware") - }).passthrough() - }).passthrough().describe("App Framework Interface"), - drivers: external_exports.object({ - register: external_exports.function().describe("Register a driver") - }).passthrough().describe("Driver Registry") -}); -external_exports.object({ - /** Version before upgrade */ - previousVersion: external_exports.string().describe("Version before upgrade"), - /** Version after upgrade */ - newVersion: external_exports.string().describe("Version after upgrade"), - /** Whether this is a major version bump */ - isMajorUpgrade: external_exports.boolean().describe("Whether this is a major version bump"), - /** Metadata snapshot before upgrade (for migration logic) */ - previousMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Metadata snapshot before upgrade") -}).describe("Version migration context for onUpgrade hook"); -var PluginLifecycleSchema = external_exports.object({ - onInstall: external_exports.function().optional().describe("Called when plugin is installed"), - onEnable: external_exports.function().optional().describe("Called when plugin is enabled"), - onDisable: external_exports.function().optional().describe("Called when plugin is disabled"), - onUninstall: external_exports.function().optional().describe("Called when plugin is uninstalled"), - onUpgrade: external_exports.function().optional().describe("Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade") -}); -var CORE_PLUGIN_TYPES = [ - "ui", - // Frontend: Serves static assets/SPA (e.g. Console, Studio) - "driver", - // Connectivity: Database or Storage adapters (e.g. SQL, S3) - "server", - // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL) - "app", - // Business: Vertical Solution Bundle (Metadata + Logic) - "theme", - // Appearance: UI Overrides & CSS Variables - "agent", - // AI: Autonomous Agent & Tool Definitions - "objectql" - // Core: ObjectQL Engine Data Provider -]; -PluginLifecycleSchema.extend({ - id: external_exports.string().min(1).optional().describe("Unique Plugin ID (e.g. com.example.crm)"), - type: external_exports.enum([ - "standard", - // Default: General purpose backend logic (Service, Hook, etc.) - ...CORE_PLUGIN_TYPES - ]).default("standard").optional().describe("Plugin Type categorization for runtime behavior"), - staticPath: external_exports.string().optional().describe('Absolute path to static assets (Required for type="ui-plugin")'), - slug: external_exports.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type="ui-plugin")'), - default: external_exports.boolean().optional().describe('Serve at root path (Only one "ui-plugin" can be default)'), - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic Version"), - description: external_exports.string().optional(), - author: external_exports.string().optional(), - homepage: external_exports.string().url().optional() -}); -var DatasetMode = external_exports.enum([ - "insert", - // Try to insert, fail on duplicate - "update", - // Only update found records, ignore new - "upsert", - // Create new or Update existing (Standard) - "replace", - // Delete ALL records in object then insert (Dangerous - use for cache tables) - "ignore" - // Try to insert, silently skip duplicates -]); -var DatasetSchema = external_exports.object({ - /** - * Target Object - * The machine name of the object to populate. - */ - object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target Object Name"), - /** - * Idempotency Key (The "Upsert" Key) - * The field used to check if a record already exists. - * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'. - * Standard: 'id' is rarely used for portable seed data — prefer natural keys. - */ - externalId: external_exports.string().default("name").describe("Field match for uniqueness check"), - /** - * Import Strategy - */ - mode: DatasetMode.default("upsert").describe("Conflict resolution strategy"), - /** - * Environment Scope - * - 'all': Always load - * - 'dev': Only for development/demo - * - 'test': Only for CI/CD tests - */ - env: external_exports.array(external_exports.enum(["prod", "dev", "test"])).default(["prod", "dev", "test"]).describe("Applicable environments"), - /** - * The Payload - * Array of raw JSON objects matching the Object Schema. - */ - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Data records") -}); -var ManifestSchema = external_exports.object({ - /** - * Unique package identifier using reverse domain notation. - * Must be unique across the entire ecosystem. - * - * @example "com.steedos.crm" - * @example "org.apache.superset" - */ - id: external_exports.string().describe("Unique package identifier (reverse domain style)"), - /** - * Short namespace identifier for metadata scoping. - * Used as a prefix for objects and other metadata to prevent naming collisions - * across packages from different vendors. - * - * Rules: - * - 2-20 characters, lowercase letters, digits, and underscores only. - * - Must be unique within a running instance. - * - Platform-reserved namespaces (no prefix applied): "base", "system". - * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator). - * - * @example "crm" → objects become crm__account, crm__deal - * @example "todo" → objects become todo__task - * @example "base" → objects keep short name (platform reserved) - */ - namespace: external_exports.string().regex(/^[a-z][a-z0-9_]{1,19}$/, "Namespace must be 2-20 chars, lowercase alphanumeric + underscore").optional().describe('Short namespace identifier for metadata scoping (e.g. "crm", "todo")'), - /** - * Package version following semantic versioning (major.minor.patch). - * - * @example "1.0.0" - * @example "2.1.0-beta.1" - */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Package version (semantic versioning)"), - /** - * Type of the package in the ObjectStack ecosystem. - * - plugin: General-purpose functionality extension (Runtime: standard) - * - app: Business application package - * - driver: Connectivity adapter - * - server: Protocol gateway (Hono, GraphQL) - * - ui: Frontend package (Static/SPA) - * - theme: UI Theme - * - agent: AI Agent - * - module: Reusable code library/shared module - * - objectql: Core engine - * - adapter: Host adapter (Express, Fastify) - */ - type: external_exports.enum([ - "plugin", - ...CORE_PLUGIN_TYPES, - "module", - "gateway", - // Deprecated: use 'server' - "adapter" - ]).describe("Type of package"), - /** - * Human-readable name of the package. - * Displayed in the UI for users. - * - * @example "Project Management" - */ - name: external_exports.string().describe("Human-readable package name"), - /** - * Brief description of the package functionality. - * Displayed in the marketplace and plugin manager. - */ - description: external_exports.string().optional().describe("Package description"), - /** - * Array of permission strings that the package requires. - * These form the "Scope" requested by the package at installation. - * - * @example ["system.user.read", "system.data.write"] - */ - permissions: external_exports.array(external_exports.string()).optional().describe("Array of required permission strings"), - /** - * Glob patterns specifying ObjectQL schemas files. - * Matches `*.object.yml` or `*.object.ts` files to load business objects. - * - * @example ["./src/objects/*.object.yml"] - */ - objects: external_exports.array(external_exports.string()).optional().describe("Glob patterns for ObjectQL schemas files"), - /** - * Defines system level DataSources. - * Matches `*.datasource.yml` files. - * - * @example ["./src/datasources/*.datasource.mongo.yml"] - */ - datasources: external_exports.array(external_exports.string()).optional().describe("Glob patterns for Datasource definitions"), - /** - * Package Dependencies. - * Map of package IDs to version requirements. - * - * @example { "@steedos/plugin-auth": "^2.0.0" } - */ - dependencies: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Package dependencies"), - /** - * Plugin Configuration Schema. - * Defines the settings this plugin exposes to the user via UI/ENV. - * Uses a simplified JSON Schema format. - * - * @example - * { - * "title": "Stripe Config", - * "properties": { - * "apiKey": { "type": "string", "secret": true }, - * "currency": { "type": "string", "default": "USD" } - * } - * } - */ - configuration: external_exports.object({ - title: external_exports.string().optional(), - properties: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["string", "number", "boolean", "array", "object"]).describe("Data type of the setting"), - default: external_exports.unknown().optional().describe("Default value"), - description: external_exports.string().optional().describe("Tooltip description"), - required: external_exports.boolean().optional().describe("Is this setting required?"), - secret: external_exports.boolean().optional().describe("If true, value is encrypted/masked (e.g. API Keys)"), - enum: external_exports.array(external_exports.string()).optional().describe("Allowed values for select inputs") - })).describe("Map of configuration keys to their definitions") - }).optional().describe("Plugin configuration settings"), - /** - * Contribution Points (VS Code Style). - * formalized way to extend the platform capabilities. - */ - contributes: external_exports.object({ - /** - * Register new Metadata Kinds (CRDs). - * Enables the system to parse and validate new file types. - * Example: Registering a BI plugin to handle *.report.ts - */ - kinds: external_exports.array(external_exports.object({ - id: external_exports.string().describe('The generic identifier of the kind (e.g., "sys.bi.report")'), - globs: external_exports.array(external_exports.string()).describe('File patterns to watch (e.g., ["**/*.report.ts"])'), - description: external_exports.string().optional().describe("Description of what this kind represents") - })).optional().describe("New Metadata Types to recognize"), - /** - * Register System Hooks. - * Declares that this plugin listens to specific system events. - */ - events: external_exports.array(external_exports.string()).optional().describe("Events this plugin listens to"), - /** - * Register UI Menus. - */ - menus: external_exports.record(external_exports.string(), external_exports.array(external_exports.object({ - id: external_exports.string(), - label: external_exports.string(), - command: external_exports.string().optional() - }))).optional().describe("UI Menu contributions"), - /** - * Register Custom Themes. - */ - themes: external_exports.array(external_exports.object({ - id: external_exports.string(), - label: external_exports.string(), - path: external_exports.string() - })).optional().describe("Theme contributions"), - /** - * Register Translations. - * Path to translation files (e.g. "locales/en.json"). - */ - translations: external_exports.array(external_exports.object({ - locale: external_exports.string(), - path: external_exports.string() - })).optional().describe("Translation resources"), - /** - * Register Server Actions. - * Invocable functions exposed to Flows or API. - */ - actions: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Unique action name"), - label: external_exports.string().optional(), - description: external_exports.string().optional(), - input: external_exports.unknown().optional().describe("Input validation schema"), - output: external_exports.unknown().optional().describe("Output schema") - })).optional().describe("Exposed server actions"), - /** - * Register Storage Drivers. - * Enables connecting to new types of datasources. - */ - drivers: external_exports.array(external_exports.object({ - id: external_exports.string().describe('Driver unique identifier (e.g. "postgres", "mongo")'), - label: external_exports.string().describe("Human readable name"), - description: external_exports.string().optional() - })).optional().describe("Driver contributions"), - /** - * Register Custom Field Types. - * Extends the data model with new widget types. - */ - fieldTypes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Unique field type name (e.g. "vector")'), - label: external_exports.string().describe("Display label"), - description: external_exports.string().optional() - })).optional().describe("Field Type contributions"), - /** - * Register Custom Query Operators/Functions. - * Extends ObjectQL with new functions (e.g. distance()). - */ - functions: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Function name (e.g. "distance")'), - description: external_exports.string().optional(), - args: external_exports.array(external_exports.string()).optional().describe("Argument types"), - returnType: external_exports.string().optional() - })).optional().describe("Query Function contributions"), - /** - * Register API Route Namespaces. - * Declares the API endpoints this plugin provides to the HttpDispatcher. - * The kernel routes matching prefixes to this plugin's handler. - * - * @example - * routes: [ - * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] } - * ] - */ - routes: external_exports.array(external_exports.object({ - /** URL path prefix (e.g. "/api/v1/ai") */ - prefix: external_exports.string().regex(/^\//).describe("API path prefix"), - /** Service name this plugin provides */ - service: external_exports.string().describe("Service name this plugin provides"), - /** Protocol method names implemented */ - methods: external_exports.array(external_exports.string()).optional().describe('Protocol method names implemented (e.g. ["aiNlq", "aiChat"])') - })).optional().describe("API route contributions to HttpDispatcher"), - /** - * Register CLI Commands. - * Allows plugins to extend the ObjectStack CLI with custom commands. - * Each command entry declares metadata; the actual Commander.js command - * is resolved at runtime by importing the plugin's module. - * - * The plugin package must export a `commands` array of Commander.js `Command` instances - * from its main entry point or from the path specified in `module`. - * - * @example - * ```yaml - * commands: - * - name: marketplace - * description: "Manage marketplace apps" - * module: "./cli" # optional, defaults to package main - * - name: deploy - * description: "Deploy to cloud" - * ``` - */ - commands: external_exports.array(external_exports.object({ - /** CLI command name (e.g., "marketplace", "deploy"). Must be a valid CLI identifier. */ - name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), - /** Brief description shown in `os --help` */ - description: external_exports.string().optional().describe("Command description for help text"), - /** - * Optional module path (relative to package root) that exports the Commander.js commands. - * If omitted, the CLI will import from the package's main entry point. - * The module must export a `commands` array of Commander.js `Command` instances, - * or a single `Command` instance as default export. - */ - module: external_exports.string().optional().describe("Module path exporting Commander.js commands") - })).optional().describe("CLI command contributions") - }).optional().describe("Platform contributions"), - /** - * Initial data seeding configuration. - * Defines default records to be inserted when the package is installed. - * - * Uses the standard DatasetSchema which supports idempotent upsert via - * `externalId`, environment scoping via `env`, and multiple conflict - * resolution modes. - * - * @deprecated Prefer using the top-level `data` field on the Stack Definition - * (defineStack({ data: [...] })) for better visibility and metadata registration. - * This field is retained for backward compatibility with manifest-only packages. - */ - data: external_exports.array(DatasetSchema).optional().describe("Initial seed data (prefer top-level data field)"), - /** - * Plugin Capability Manifest. - * Declares protocols implemented, interfaces provided, dependencies, and extension points. - * This enables plugin interoperability and automatic discovery. - */ - capabilities: PluginCapabilityManifestSchema.optional().describe("Plugin capability declarations for interoperability"), - /** - * Extension points contributed by this package. - * Allows packages to extend UI components, add functionality, etc. - */ - extensions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Extension points and contributions"), - /** - * Plugin Loading Configuration. - * Configures how the plugin is loaded, initialized, and managed at runtime. - * Includes strategies for lazy loading, code splitting, caching, and hot reload. - */ - loading: PluginLoadingConfigSchema.optional().describe("Plugin loading and runtime behavior configuration"), - /** - * Platform Compatibility Requirements. - * Specifies the minimum ObjectStack platform version required to run this package. - * Used at install time to prevent incompatible packages from being installed. - * - * @example - * ```yaml - * engine: - * objectstack: ">=3.0.0" - * ``` - */ - engine: external_exports.object({ - /** ObjectStack platform version requirement (SemVer range) */ - objectstack: external_exports.string().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe('ObjectStack platform version requirement (SemVer range, e.g. ">=3.0.0")') - }).optional().describe("Platform compatibility requirements") -}); -var DependencyStatusEnum = external_exports.enum([ - "satisfied", - // Already installed and version compatible - "needs_install", - // Not installed, needs to be installed - "needs_upgrade", - // Installed but version incompatible, needs upgrade - "conflict" - // Conflicts with another package's dependency -]).describe("Resolution status for a dependency"); -var ResolvedDependencySchema = external_exports.object({ - /** Package identifier of the dependency */ - packageId: external_exports.string().describe("Dependency package identifier"), - /** SemVer range required by the parent package */ - requiredRange: external_exports.string().describe('SemVer range required (e.g. "^2.0.0")'), - /** Actual version resolved (if available) */ - resolvedVersion: external_exports.string().optional().describe("Actual version resolved from registry"), - /** Currently installed version (if any) */ - installedVersion: external_exports.string().optional().describe("Currently installed version"), - /** Resolution status */ - status: DependencyStatusEnum.describe("Resolution status"), - /** Conflict details (when status is "conflict") */ - conflictReason: external_exports.string().optional().describe("Explanation of the conflict") -}).describe("Resolution result for a single dependency"); -var RequiredActionSchema = external_exports.object({ - /** Type of action required */ - type: external_exports.enum(["install", "upgrade", "confirm_conflict"]).describe("Type of action required"), - /** Target package identifier */ - packageId: external_exports.string().describe("Target package identifier"), - /** Human-readable description of the action */ - description: external_exports.string().describe("Human-readable action description") -}).describe("Action required before installation can proceed"); -var DependencyResolutionResultSchema = external_exports.object({ - /** All dependencies and their resolution results */ - dependencies: external_exports.array(ResolvedDependencySchema).describe("Resolution result for each dependency"), - /** Whether installation can proceed without conflicts */ - canProceed: external_exports.boolean().describe("Whether installation can proceed"), - /** Actions that require user confirmation or system execution */ - requiredActions: external_exports.array(RequiredActionSchema).describe("Actions required before proceeding"), - /** Topologically sorted package IDs for installation order */ - installOrder: external_exports.array(external_exports.string()).describe("Topologically sorted package IDs for installation"), - /** Detected circular dependency chains */ - circularDependencies: external_exports.array(external_exports.array(external_exports.string())).optional().describe('Circular dependency chains detected (e.g. [["A", "B", "A"]])') -}).describe("Complete dependency resolution result"); -var PackageStatusEnum = external_exports.enum([ - "installed", - // Successfully installed and enabled - "disabled", - // Installed but disabled (metadata not active) - "installing", - // Installation in progress - "upgrading", - // Upgrade in progress - "uninstalling", - // Removal in progress - "error" - // Installation or runtime error -]).describe("Package installation status"); -var InstalledPackageSchema = external_exports.object({ - /** - * The full package manifest (source of truth for package definition). - */ - manifest: ManifestSchema.describe("Full package manifest"), - /** - * Current lifecycle status. - */ - status: PackageStatusEnum.default("installed").describe("Package state: installed, disabled, installing, upgrading, uninstalling, or error"), - /** - * Whether the package is currently enabled (active). - * When disabled, the package's metadata is not loaded into the registry. - */ - enabled: external_exports.boolean().default(true).describe("Whether the package is currently enabled"), - /** - * ISO 8601 timestamp of when the package was installed. - */ - installedAt: external_exports.string().datetime().optional().describe("Installation timestamp"), - /** - * ISO 8601 timestamp of last update. - */ - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - /** - * The currently installed version string. - * Mirrors manifest.version for quick access without parsing the full manifest. - */ - installedVersion: external_exports.string().optional().describe("Currently installed version for quick access"), - /** - * The previously installed version (before last upgrade). - * Useful for rollback and upgrade tracking. - */ - previousVersion: external_exports.string().optional().describe("Version before the last upgrade"), - /** - * ISO 8601 timestamp of when the package was last enabled/disabled. - */ - statusChangedAt: external_exports.string().datetime().optional().describe("Status change timestamp"), - /** - * Error message if status is 'error'. - */ - errorMessage: external_exports.string().optional().describe("Error message when status is error"), - /** - * Configuration values set by the user for this package. - * Keys correspond to the package's `configuration.properties`. - */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided configuration settings"), - /** - * Upgrade history for this package. - * Records each version migration with status and optional log. - */ - upgradeHistory: external_exports.array(external_exports.object({ - /** Previous version before upgrade */ - fromVersion: external_exports.string().describe("Version before upgrade"), - /** New version after upgrade */ - toVersion: external_exports.string().describe("Version after upgrade"), - /** Timestamp of the upgrade */ - upgradedAt: external_exports.string().datetime().describe("Upgrade timestamp"), - /** Outcome of the upgrade */ - status: external_exports.enum(["success", "failed", "rolled_back"]).describe("Upgrade outcome"), - /** Migration log entries */ - migrationLog: external_exports.array(external_exports.string()).optional().describe("Migration step logs") - })).optional().describe("Version upgrade history"), - /** - * Namespaces registered by this package. - * Tracks which namespace prefixes are occupied by this package. - */ - registeredNamespaces: external_exports.array(external_exports.string()).optional().describe("Namespace prefixes registered by this package") -}).describe("Installed package with runtime lifecycle state"); -external_exports.object({ - /** Namespace prefix */ - namespace: external_exports.string().describe("Namespace prefix"), - /** Package that owns this namespace */ - packageId: external_exports.string().describe("Owning package ID"), - /** Registration timestamp */ - registeredAt: external_exports.string().datetime().describe("Registration timestamp"), - /** Namespace status */ - status: external_exports.enum(["active", "disabled", "reserved"]).describe("Namespace status") -}).describe("Namespace ownership entry in the registry"); -external_exports.object({ - /** Error type discriminator */ - type: external_exports.literal("namespace_conflict").describe("Error type"), - /** Namespace that was requested */ - requestedNamespace: external_exports.string().describe("Requested namespace"), - /** ID of the package that already owns the namespace */ - conflictingPackageId: external_exports.string().describe("Conflicting package ID"), - /** Name of the conflicting package */ - conflictingPackageName: external_exports.string().describe("Conflicting package display name"), - /** Suggested alternative namespace */ - suggestion: external_exports.string().optional().describe("Suggested alternative namespace") -}).describe("Namespace collision error during installation"); -var ListPackagesRequestSchema = external_exports.object({ - /** Filter by status */ - status: PackageStatusEnum.optional().describe("Filter by package status"), - /** Filter by package type */ - type: ManifestSchema.shape.type.optional().describe("Filter by package type"), - /** Filter by enabled state */ - enabled: external_exports.boolean().optional().describe("Filter by enabled state") -}).describe("List packages request"); -var ListPackagesResponseSchema = external_exports.object({ - packages: external_exports.array(InstalledPackageSchema).describe("List of installed packages"), - total: external_exports.number().describe("Total package count") -}).describe("List packages response"); -var GetPackageRequestSchema = external_exports.object({ - /** Package ID (reverse domain identifier from manifest) */ - id: external_exports.string().describe("Package identifier") -}).describe("Get package request"); -var GetPackageResponseSchema = external_exports.object({ - package: InstalledPackageSchema.describe("Package details") -}).describe("Get package response"); -var InstallPackageRequestSchema = external_exports.object({ - /** The package manifest to install */ - manifest: ManifestSchema.describe("Package manifest to install"), - /** Optional: user-provided settings at install time */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), - /** Whether to enable immediately after install (default: true) */ - enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), - /** - * Current platform version for compatibility checking. - * When provided, the system compares this against the package's - * `engine.objectstack` requirement to verify compatibility. - */ - platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification") -}).describe("Install package request"); -var InstallPackageResponseSchema = external_exports.object({ - package: InstalledPackageSchema.describe("Installed package details"), - message: external_exports.string().optional().describe("Installation status message"), - /** Dependency resolution result (when dependencies were analyzed) */ - dependencyResolution: DependencyResolutionResultSchema.optional().describe("Dependency resolution result from install analysis") -}).describe("Install package response"); -var UninstallPackageRequestSchema = external_exports.object({ - /** Package ID to uninstall */ - id: external_exports.string().describe("Package ID to uninstall") -}).describe("Uninstall package request"); -var UninstallPackageResponseSchema = external_exports.object({ - id: external_exports.string().describe("Uninstalled package ID"), - success: external_exports.boolean().describe("Whether uninstall succeeded"), - message: external_exports.string().optional().describe("Uninstall status message") -}).describe("Uninstall package response"); -var EnablePackageRequestSchema = external_exports.object({ - /** Package ID to enable */ - id: external_exports.string().describe("Package ID to enable") -}).describe("Enable package request"); -var EnablePackageResponseSchema = external_exports.object({ - package: InstalledPackageSchema.describe("Enabled package details"), - message: external_exports.string().optional().describe("Enable status message") -}).describe("Enable package response"); -var DisablePackageRequestSchema = external_exports.object({ - /** Package ID to disable */ - id: external_exports.string().describe("Package ID to disable") -}).describe("Disable package request"); -var DisablePackageResponseSchema = external_exports.object({ - package: InstalledPackageSchema.describe("Disabled package details"), - message: external_exports.string().optional().describe("Disable status message") -}).describe("Disable package response"); -var AutomationTriggerRequestSchema = external_exports.object({ - trigger: external_exports.string(), - payload: external_exports.record(external_exports.string(), external_exports.unknown()) -}); -var AutomationTriggerResponseSchema = external_exports.object({ - success: external_exports.boolean(), - jobId: external_exports.string().optional(), - result: external_exports.unknown().optional() -}); -var GetDiscoveryRequestSchema = external_exports.object({}); -var GetDiscoveryResponseSchema = DiscoverySchema.partial().required({ version: true }).extend({ - /** @deprecated Use `name` instead. Kept for backward compatibility. */ - apiName: external_exports.string().optional().describe("API name (deprecated \u2014 use name)") -}); -var GetMetaTypesRequestSchema = external_exports.object({}); -var GetMetaTypesResponseSchema = external_exports.object({ - types: external_exports.array(external_exports.string()).describe('Available metadata type names (e.g., "object", "plugin", "view")') -}); -var GetMetaItemsRequestSchema = external_exports.object({ - type: external_exports.string().describe('Metadata type name (e.g., "object", "plugin")'), - packageId: external_exports.string().optional().describe("Optional package ID to filter items by") -}); -var GetMetaItemsResponseSchema = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - items: external_exports.array(external_exports.unknown()).describe("Array of metadata items") -}); -var GetMetaItemRequestSchema = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - name: external_exports.string().describe("Item name (snake_case identifier)"), - packageId: external_exports.string().optional().describe("Optional package ID to filter items by") -}); -var GetMetaItemResponseSchema = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - name: external_exports.string().describe("Item name"), - item: external_exports.unknown().describe("Metadata item definition") -}); -var SaveMetaItemRequestSchema = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - name: external_exports.string().describe("Item name"), - item: external_exports.unknown().describe("Metadata item definition") -}); -var SaveMetaItemResponseSchema = external_exports.object({ - success: external_exports.boolean(), - message: external_exports.string().optional() -}); -var GetMetaItemCachedRequestSchema = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - name: external_exports.string().describe("Item name"), - cacheRequest: MetadataCacheRequestSchema.optional().describe("Cache validation parameters") -}); -var GetUiViewRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - type: external_exports.enum(["list", "form"]).describe("View type") -}); -var FindDataRequestSchema = external_exports.object({ - object: external_exports.string().describe('The unique machine name of the object to query (e.g. "account").'), - query: QuerySchema.optional().describe("Structured query definition (filter, sort, select, pagination).") -}); -var FindDataResponseSchema = external_exports.object({ - object: external_exports.string().describe("The object name for the returned records."), - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("The list of matching records."), - total: external_exports.number().optional().describe("Total number of records matching the filter (if requested)."), - nextCursor: external_exports.string().optional().describe("Cursor for the next page of results (cursor-based pagination)."), - hasMore: external_exports.boolean().optional().describe("True if there are more records available (pagination).") -}); -var HttpFindQueryParamsSchema = external_exports.object({ - /** @canonical Singular form — the standard going forward. JSON string of filter expression or AST. */ - filter: external_exports.string().optional().describe("JSON-encoded filter expression (canonical, singular)."), - /** @deprecated Use `filter` (singular). Accepted for backward compatibility. */ - filters: external_exports.string().optional().describe("JSON-encoded filter expression (deprecated plural alias)."), - select: external_exports.string().optional().describe("Comma-separated list of fields to retrieve."), - sort: external_exports.string().optional().describe('Sort expression (e.g. "name asc,created_at desc" or "-created_at").'), - orderBy: external_exports.string().optional().describe("Alias for sort (OData compatibility)."), - top: external_exports.coerce.number().optional().describe("Max records to return (limit)."), - skip: external_exports.coerce.number().optional().describe("Records to skip (offset)."), - expand: external_exports.string().optional().describe( - "Comma-separated list of lookup/master_detail field names to expand. Resolved to populate array and passed to the engine for batch $in expansion." - ), - search: external_exports.string().optional().describe("Full-text search query."), - distinct: external_exports.coerce.boolean().optional().describe("SELECT DISTINCT flag."), - count: external_exports.coerce.boolean().optional().describe("Include total count in response.") -}); -var GetDataRequestSchema = external_exports.object({ - object: external_exports.string().describe("The object name."), - id: external_exports.string().describe("The unique record identifier (primary key)."), - select: external_exports.array(external_exports.string()).optional().describe("Fields to include in the response (allowlisted query param)."), - expand: external_exports.array(external_exports.string()).optional().describe( - "Lookup/master_detail field names to expand. The engine resolves these via batch $in queries, replacing foreign key IDs with full objects." - ) -}); -var GetDataResponseSchema = external_exports.object({ - object: external_exports.string().describe("The object name."), - id: external_exports.string().describe("The record ID."), - record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The complete record data.") -}); -var CreateDataRequestSchema = external_exports.object({ - object: external_exports.string().describe("The object name."), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The dictionary of field values to insert.") -}); -var CreateDataResponseSchema = external_exports.object({ - object: external_exports.string().describe("The object name."), - id: external_exports.string().describe("The ID of the newly created record."), - record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The created record, including server-generated fields (created_at, owner).") -}); -var UpdateDataRequestSchema = external_exports.object({ - object: external_exports.string().describe("The object name."), - id: external_exports.string().describe("The ID of the record to update."), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The fields to update (partial update).") -}); -var UpdateDataResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - id: external_exports.string().describe("Updated record ID"), - record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Updated record") -}); -var DeleteDataRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - id: external_exports.string().describe("Record ID to delete") -}); -var DeleteDataResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - id: external_exports.string().describe("Deleted record ID"), - success: external_exports.boolean().describe("Whether deletion succeeded") -}); -var BatchDataRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - request: BatchUpdateRequestSchema.describe("Batch operation request") -}); -var CreateManyDataRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Array of records to create") -}); -var CreateManyDataResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Created records"), - count: external_exports.number().describe("Number of records created") -}); -var UpdateManyDataRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - records: external_exports.array(external_exports.object({ - id: external_exports.string().describe("Record ID"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Fields to update") - })).describe("Array of updates"), - options: BatchOptionsSchema.optional().describe("Update options") -}); -var DeleteManyDataRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - ids: external_exports.array(external_exports.string()).describe("Array of record IDs to delete"), - options: BatchOptionsSchema.optional().describe("Delete options") -}); -var ListViewsRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - type: external_exports.enum(["list", "form"]).optional().describe("Filter by view type") -}); -var ListViewsResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - views: external_exports.array(ViewSchema).describe("Array of view definitions") -}); -var GetViewRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - viewId: external_exports.string().describe("View identifier") -}); -var GetViewResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - view: ViewSchema.describe("View definition") -}); -var CreateViewRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - data: ViewSchema.describe("View definition to create") -}); -var CreateViewResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - viewId: external_exports.string().describe("Created view identifier"), - view: ViewSchema.describe("Created view definition") -}); -var UpdateViewRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - viewId: external_exports.string().describe("View identifier"), - data: ViewSchema.partial().describe("Partial view data to update") -}); -var UpdateViewResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - viewId: external_exports.string().describe("Updated view identifier"), - view: ViewSchema.describe("Updated view definition") -}); -var DeleteViewRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - viewId: external_exports.string().describe("View identifier to delete") -}); -var DeleteViewResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - viewId: external_exports.string().describe("Deleted view identifier"), - success: external_exports.boolean().describe("Whether deletion succeeded") -}); -var CheckPermissionRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name to check permissions for"), - action: external_exports.enum(["create", "read", "edit", "delete", "transfer", "restore", "purge"]).describe("Action to check"), - recordId: external_exports.string().optional().describe("Specific record ID (for record-level checks)"), - field: external_exports.string().optional().describe("Specific field name (for field-level checks)") -}); -var CheckPermissionResponseSchema = external_exports.object({ - allowed: external_exports.boolean().describe("Whether the action is permitted"), - reason: external_exports.string().optional().describe("Reason if denied") -}); -var GetObjectPermissionsRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name to get permissions for") -}); -var GetObjectPermissionsResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - permissions: ObjectPermissionSchema.describe("Object-level permissions"), - fieldPermissions: external_exports.record(external_exports.string(), FieldPermissionSchema).optional().describe("Field-level permissions keyed by field name") -}); -var GetEffectivePermissionsRequestSchema = external_exports.object({}); -var GetEffectivePermissionsResponseSchema = external_exports.object({ - objects: external_exports.record(external_exports.string(), ObjectPermissionSchema).describe("Effective object permissions keyed by object name"), - systemPermissions: external_exports.array(external_exports.string()).describe("Effective system-level permissions") -}); -var GetWorkflowConfigRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name to get workflow config for") -}); -var GetWorkflowConfigResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - workflows: external_exports.array(WorkflowRuleSchema).describe("Active workflow rules for this object") -}); -var WorkflowStateSchema = external_exports.object({ - currentState: external_exports.string().describe("Current workflow state name"), - availableTransitions: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Transition name"), - targetState: external_exports.string().describe("Target state after transition"), - label: external_exports.string().optional().describe("Display label"), - requiresApproval: external_exports.boolean().default(false).describe("Whether transition requires approval") - })).describe("Available transitions from current state"), - history: external_exports.array(external_exports.object({ - fromState: external_exports.string().describe("Previous state"), - toState: external_exports.string().describe("New state"), - action: external_exports.string().describe("Action that triggered the transition"), - userId: external_exports.string().describe("User who performed the action"), - timestamp: external_exports.string().datetime().describe("When the transition occurred"), - comment: external_exports.string().optional().describe("Optional comment") - })).optional().describe("State transition history") -}); -var GetWorkflowStateRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID to get workflow state for") -}); -var GetWorkflowStateResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - state: WorkflowStateSchema.describe("Current workflow state and available transitions") -}); -var WorkflowTransitionRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - transition: external_exports.string().describe("Transition name to execute"), - comment: external_exports.string().optional().describe("Optional comment for the transition"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data for the transition") -}); -var WorkflowTransitionResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - success: external_exports.boolean().describe("Whether the transition succeeded"), - state: WorkflowStateSchema.describe("New workflow state after transition") -}); -var WorkflowApproveRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - comment: external_exports.string().optional().describe("Approval comment"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data") -}); -var WorkflowApproveResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - success: external_exports.boolean().describe("Whether the approval succeeded"), - state: WorkflowStateSchema.describe("New workflow state after approval") -}); -var WorkflowRejectRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - reason: external_exports.string().describe("Rejection reason"), - comment: external_exports.string().optional().describe("Additional comment") -}); -var WorkflowRejectResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - success: external_exports.boolean().describe("Whether the rejection succeeded"), - state: WorkflowStateSchema.describe("New workflow state after rejection") -}); -var RealtimeConnectRequestSchema = external_exports.object({ - transport: TransportProtocol.optional().describe("Preferred transport protocol"), - channels: external_exports.array(external_exports.string()).optional().describe("Channels to subscribe to on connect"), - token: external_exports.string().optional().describe("Authentication token") -}); -var RealtimeConnectResponseSchema = external_exports.object({ - connectionId: external_exports.string().describe("Unique connection identifier"), - transport: TransportProtocol.describe("Negotiated transport protocol"), - url: external_exports.string().optional().describe("WebSocket/SSE endpoint URL") -}); -var RealtimeDisconnectRequestSchema = external_exports.object({ - connectionId: external_exports.string().optional().describe("Connection ID to disconnect") -}); -var RealtimeDisconnectResponseSchema = external_exports.object({ - success: external_exports.boolean().describe("Whether disconnection succeeded") -}); -var RealtimeSubscribeRequestSchema = external_exports.object({ - channel: external_exports.string().describe("Channel name to subscribe to"), - events: external_exports.array(external_exports.string()).optional().describe("Specific event types to listen for"), - filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event filter criteria") -}); -var RealtimeSubscribeResponseSchema = external_exports.object({ - subscriptionId: external_exports.string().describe("Unique subscription identifier"), - channel: external_exports.string().describe("Subscribed channel name") -}); -var RealtimeUnsubscribeRequestSchema = external_exports.object({ - subscriptionId: external_exports.string().describe("Subscription ID to cancel") -}); -var RealtimeUnsubscribeResponseSchema = external_exports.object({ - success: external_exports.boolean().describe("Whether unsubscription succeeded") -}); -var SetPresenceRequestSchema = external_exports.object({ - channel: external_exports.string().describe("Channel to set presence in"), - state: RealtimePresenceSchema.describe("Presence state to set") -}); -var SetPresenceResponseSchema = external_exports.object({ - success: external_exports.boolean().describe("Whether presence was set") -}); -var GetPresenceRequestSchema = external_exports.object({ - channel: external_exports.string().describe("Channel to get presence for") -}); -var GetPresenceResponseSchema = external_exports.object({ - channel: external_exports.string().describe("Channel name"), - members: external_exports.array(RealtimePresenceSchema).describe("Active members and their presence state") -}); -var RegisterDeviceRequestSchema = external_exports.object({ - token: external_exports.string().describe("Device push notification token"), - platform: external_exports.enum(["ios", "android", "web"]).describe("Device platform"), - deviceId: external_exports.string().optional().describe("Unique device identifier"), - name: external_exports.string().optional().describe("Device friendly name") -}); -var RegisterDeviceResponseSchema = external_exports.object({ - deviceId: external_exports.string().describe("Registered device ID"), - success: external_exports.boolean().describe("Whether registration succeeded") -}); -var UnregisterDeviceRequestSchema = external_exports.object({ - deviceId: external_exports.string().describe("Device ID to unregister") -}); -var UnregisterDeviceResponseSchema = external_exports.object({ - success: external_exports.boolean().describe("Whether unregistration succeeded") -}); -var NotificationPreferencesSchema = external_exports.object({ - email: external_exports.boolean().default(true).describe("Receive email notifications"), - push: external_exports.boolean().default(true).describe("Receive push notifications"), - inApp: external_exports.boolean().default(true).describe("Receive in-app notifications"), - digest: external_exports.enum(["none", "daily", "weekly"]).default("none").describe("Email digest frequency"), - channels: external_exports.record(external_exports.string(), external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Whether this channel is enabled"), - email: external_exports.boolean().optional().describe("Override email setting"), - push: external_exports.boolean().optional().describe("Override push setting") - })).optional().describe("Per-channel notification preferences") -}); -var GetNotificationPreferencesRequestSchema = external_exports.object({}); -var GetNotificationPreferencesResponseSchema = external_exports.object({ - preferences: NotificationPreferencesSchema.describe("Current notification preferences") -}); -var UpdateNotificationPreferencesRequestSchema = external_exports.object({ - preferences: NotificationPreferencesSchema.partial().describe("Preferences to update") -}); -var UpdateNotificationPreferencesResponseSchema = external_exports.object({ - preferences: NotificationPreferencesSchema.describe("Updated notification preferences") -}); -var NotificationSchema = external_exports.object({ - id: external_exports.string().describe("Notification ID"), - type: external_exports.string().describe("Notification type"), - title: external_exports.string().describe("Notification title"), - body: external_exports.string().describe("Notification body text"), - read: external_exports.boolean().default(false).describe("Whether notification has been read"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional notification data"), - actionUrl: external_exports.string().optional().describe("URL to navigate to when clicked"), - createdAt: external_exports.string().datetime().describe("When notification was created") -}); -var ListNotificationsRequestSchema = external_exports.object({ - read: external_exports.boolean().optional().describe("Filter by read status"), - type: external_exports.string().optional().describe("Filter by notification type"), - limit: external_exports.number().default(20).describe("Maximum number of notifications to return"), - cursor: external_exports.string().optional().describe("Pagination cursor") -}); -var ListNotificationsResponseSchema = external_exports.object({ - notifications: external_exports.array(NotificationSchema).describe("List of notifications"), - unreadCount: external_exports.number().describe("Total number of unread notifications"), - cursor: external_exports.string().optional().describe("Next page cursor") -}); -var MarkNotificationsReadRequestSchema = external_exports.object({ - ids: external_exports.array(external_exports.string()).describe("Notification IDs to mark as read") -}); -var MarkNotificationsReadResponseSchema = external_exports.object({ - success: external_exports.boolean().describe("Whether the operation succeeded"), - readCount: external_exports.number().describe("Number of notifications marked as read") -}); -var MarkAllNotificationsReadRequestSchema = external_exports.object({}); -var MarkAllNotificationsReadResponseSchema = external_exports.object({ - success: external_exports.boolean().describe("Whether the operation succeeded"), - readCount: external_exports.number().describe("Number of notifications marked as read") -}); -var AiNlqRequestSchema = external_exports.object({ - query: external_exports.string().describe("Natural language query string"), - object: external_exports.string().optional().describe("Target object context"), - conversationId: external_exports.string().optional().describe("Conversation ID for multi-turn queries") -}); -var AiNlqResponseSchema = external_exports.object({ - query: external_exports.unknown().describe("Generated structured query (AST)"), - explanation: external_exports.string().optional().describe("Human-readable explanation of the query"), - confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), - suggestions: external_exports.array(external_exports.string()).optional().describe("Suggested follow-up queries") -}); -var AiSuggestRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name for context"), - field: external_exports.string().optional().describe("Field to suggest values for"), - recordId: external_exports.string().optional().describe("Record ID for context"), - partial: external_exports.string().optional().describe("Partial input for completion") -}); -var AiSuggestResponseSchema = external_exports.object({ - suggestions: external_exports.array(external_exports.object({ - value: external_exports.unknown().describe("Suggested value"), - label: external_exports.string().describe("Display label"), - confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), - reason: external_exports.string().optional().describe("Reason for this suggestion") - })).describe("Suggested values") -}); -var AiInsightsRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name to analyze"), - recordId: external_exports.string().optional().describe("Specific record to analyze"), - type: external_exports.enum(["summary", "trends", "anomalies", "recommendations"]).optional().describe("Type of insight") -}); -var AiInsightsResponseSchema = external_exports.object({ - insights: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Insight type"), - title: external_exports.string().describe("Insight title"), - description: external_exports.string().describe("Detailed description"), - confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Supporting data") - })).describe("Generated insights") -}); -var GetLocalesRequestSchema = external_exports.object({}); -var GetLocalesResponseSchema = external_exports.object({ - locales: external_exports.array(external_exports.object({ - code: external_exports.string().describe("BCP-47 locale code (e.g., en-US, zh-CN)"), - label: external_exports.string().describe("Display name of the locale"), - isDefault: external_exports.boolean().default(false).describe("Whether this is the default locale") - })).describe("Available locales") -}); -var GetTranslationsRequestSchema = external_exports.object({ - locale: external_exports.string().describe("BCP-47 locale code"), - namespace: external_exports.string().optional().describe("Translation namespace (e.g., objects, apps, messages)"), - keys: external_exports.array(external_exports.string()).optional().describe("Specific translation keys to fetch") -}); -var GetTranslationsResponseSchema = external_exports.object({ - locale: external_exports.string().describe("Locale code"), - translations: TranslationDataSchema2.describe("Translation data") -}); -var GetFieldLabelsRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - locale: external_exports.string().describe("BCP-47 locale code") -}); -var GetFieldLabelsResponseSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - locale: external_exports.string().describe("Locale code"), - labels: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().describe("Translated field label"), - help: external_exports.string().optional().describe("Translated help text"), - options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Translated option labels") - })).describe("Field labels keyed by field name") -}); -var ObjectStackProtocolSchema = external_exports.object({ - // Discovery & Metadata - getDiscovery: external_exports.function().describe("Get API discovery information"), - getMetaTypes: external_exports.function().describe("Get available metadata types"), - getMetaItems: external_exports.function().describe("Get all items of a metadata type"), - getMetaItem: external_exports.function().describe("Get a specific metadata item"), - saveMetaItem: external_exports.function().describe("Save metadata item"), - getMetaItemCached: external_exports.function().describe("Get a metadata item with cache validation"), - getUiView: external_exports.function().describe("Get UI view definition"), - // Analytics Operations - analyticsQuery: external_exports.function().describe("Execute analytics query"), - getAnalyticsMeta: external_exports.function().describe("Get analytics metadata (cubes)"), - // Automation Operations - triggerAutomation: external_exports.function().describe("Trigger an automation flow or script"), - // Package Management Operations - listPackages: external_exports.function().describe("List installed packages with optional filters"), - getPackage: external_exports.function().describe("Get a specific installed package by ID"), - installPackage: external_exports.function().describe("Install a new package from manifest"), - uninstallPackage: external_exports.function().describe("Uninstall a package by ID"), - enablePackage: external_exports.function().describe("Enable a disabled package"), - disablePackage: external_exports.function().describe("Disable an installed package"), - // Data Operations - findData: external_exports.function().describe("Find data records"), - getData: external_exports.function().describe("Get single data record"), - createData: external_exports.function().describe("Create a data record"), - updateData: external_exports.function().describe("Update a data record"), - deleteData: external_exports.function().describe("Delete a data record"), - // Batch Operations - batchData: external_exports.function().describe("Perform batch operations"), - createManyData: external_exports.function().describe("Create multiple records"), - updateManyData: external_exports.function().describe("Update multiple records"), - deleteManyData: external_exports.function().describe("Delete multiple records"), - // View Management Operations - listViews: external_exports.function().describe("List views for an object"), - getView: external_exports.function().describe("Get a specific view"), - createView: external_exports.function().describe("Create a new view"), - updateView: external_exports.function().describe("Update an existing view"), - deleteView: external_exports.function().describe("Delete a view"), - // Permission Operations - checkPermission: external_exports.function().describe("Check if an action is permitted"), - getObjectPermissions: external_exports.function().describe("Get permissions for an object"), - getEffectivePermissions: external_exports.function().describe("Get effective permissions for current user"), - // Workflow Operations - getWorkflowConfig: external_exports.function().describe("Get workflow configuration for an object"), - getWorkflowState: external_exports.function().describe("Get workflow state for a record"), - workflowTransition: external_exports.function().describe("Execute a workflow state transition"), - workflowApprove: external_exports.function().describe("Approve a workflow step"), - workflowReject: external_exports.function().describe("Reject a workflow step"), - // Realtime Operations - realtimeConnect: external_exports.function().describe("Establish realtime connection"), - realtimeDisconnect: external_exports.function().describe("Close realtime connection"), - realtimeSubscribe: external_exports.function().describe("Subscribe to a realtime channel"), - realtimeUnsubscribe: external_exports.function().describe("Unsubscribe from a realtime channel"), - setPresence: external_exports.function().describe("Set user presence state"), - getPresence: external_exports.function().describe("Get channel presence information"), - // Notification Operations - registerDevice: external_exports.function().describe("Register a device for push notifications"), - unregisterDevice: external_exports.function().describe("Unregister a device"), - getNotificationPreferences: external_exports.function().describe("Get notification preferences"), - updateNotificationPreferences: external_exports.function().describe("Update notification preferences"), - listNotifications: external_exports.function().describe("List notifications"), - markNotificationsRead: external_exports.function().describe("Mark specific notifications as read"), - markAllNotificationsRead: external_exports.function().describe("Mark all notifications as read"), - // AI Operations - aiNlq: external_exports.function().describe("Natural language query"), - aiChat: external_exports.function().describe("AI chat interaction"), - aiSuggest: external_exports.function().describe("Get AI-powered suggestions"), - aiInsights: external_exports.function().describe("Get AI-generated insights"), - // i18n Operations - getLocales: external_exports.function().describe("Get available locales"), - getTranslations: external_exports.function().describe("Get translations for a locale"), - getFieldLabels: external_exports.function().describe("Get translated field labels for an object"), - // Feed Operations - listFeed: external_exports.function().describe("List feed items for a record"), - createFeedItem: external_exports.function().describe("Create a new feed item"), - updateFeedItem: external_exports.function().describe("Update an existing feed item"), - deleteFeedItem: external_exports.function().describe("Delete a feed item"), - addReaction: external_exports.function().describe("Add an emoji reaction to a feed item"), - removeReaction: external_exports.function().describe("Remove an emoji reaction from a feed item"), - pinFeedItem: external_exports.function().describe("Pin a feed item"), - unpinFeedItem: external_exports.function().describe("Unpin a feed item"), - starFeedItem: external_exports.function().describe("Star a feed item"), - unstarFeedItem: external_exports.function().describe("Unstar a feed item"), - searchFeed: external_exports.function().describe("Search feed items"), - getChangelog: external_exports.function().describe("Get field-level changelog for a record"), - feedSubscribe: external_exports.function().describe("Subscribe to record notifications"), - feedUnsubscribe: external_exports.function().describe("Unsubscribe from record notifications") -}); -var RestApiConfigSchema = external_exports.object({ - /** - * API version identifier - */ - version: external_exports.string().regex(/^[a-zA-Z0-9_\-\.]+$/).default("v1").describe("API version (e.g., v1, v2, 2024-01)"), - /** - * Base path for all API routes - */ - basePath: external_exports.string().default("/api").describe("Base URL path for API"), - /** - * Full API path (combines basePath and version) - */ - apiPath: external_exports.string().optional().describe("Full API path (defaults to {basePath}/{version})"), - /** - * Enable automatic CRUD endpoints - */ - enableCrud: external_exports.boolean().default(true).describe("Enable automatic CRUD endpoint generation"), - /** - * Enable metadata endpoints - */ - enableMetadata: external_exports.boolean().default(true).describe("Enable metadata API endpoints"), - /** - * Enable UI API endpoints - */ - enableUi: external_exports.boolean().default(true).describe("Enable UI API endpoints (Views, Menus, Layouts)"), - /** - * Enable batch operation endpoints - */ - enableBatch: external_exports.boolean().default(true).describe("Enable batch operation endpoints"), - /** - * Enable discovery endpoint - */ - enableDiscovery: external_exports.boolean().default(true).describe("Enable API discovery endpoint"), - /** - * API documentation configuration - */ - documentation: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable API documentation"), - title: external_exports.string().default("ObjectStack API").describe("API documentation title"), - description: external_exports.string().optional().describe("API description"), - version: external_exports.string().optional().describe("Documentation version"), - termsOfService: external_exports.string().optional().describe("Terms of service URL"), - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().optional(), - email: external_exports.string().optional() - }).optional(), - license: external_exports.object({ - name: external_exports.string(), - url: external_exports.string().optional() - }).optional() - }).optional().describe("OpenAPI/Swagger documentation config"), - /** - * Response format configuration - */ - responseFormat: external_exports.object({ - envelope: external_exports.boolean().default(true).describe("Wrap responses in standard envelope"), - includeMetadata: external_exports.boolean().default(true).describe("Include response metadata (timestamp, requestId)"), - includePagination: external_exports.boolean().default(true).describe("Include pagination info in list responses") - }).optional().describe("Response format options") -}); -var CrudOperation = external_exports.enum([ - "create", - // POST /api/v1/data/{object} - "read", - // GET /api/v1/data/{object}/:id - "update", - // PATCH /api/v1/data/{object}/:id - "delete", - // DELETE /api/v1/data/{object}/:id - "list" - // GET /api/v1/data/{object} -]); -var CrudEndpointPatternSchema = external_exports.object({ - /** - * HTTP method - */ - method: HttpMethod2.describe("HTTP method"), - /** - * URL path pattern (relative to API base) - */ - path: external_exports.string().describe("URL path pattern"), - /** - * Operation summary for documentation - */ - summary: external_exports.string().optional().describe("Operation summary"), - /** - * Operation description - */ - description: external_exports.string().optional().describe("Operation description") -}); -var CrudEndpointsConfigSchema = external_exports.object({ - /** - * Enable/disable specific CRUD operations - */ - operations: external_exports.object({ - create: external_exports.boolean().default(true).describe("Enable create operation"), - read: external_exports.boolean().default(true).describe("Enable read operation"), - update: external_exports.boolean().default(true).describe("Enable update operation"), - delete: external_exports.boolean().default(true).describe("Enable delete operation"), - list: external_exports.boolean().default(true).describe("Enable list operation") - }).optional().describe("Enable/disable operations"), - /** - * Custom endpoint patterns (override defaults) - */ - patterns: external_exports.record(CrudOperation, CrudEndpointPatternSchema.optional()).optional().describe("Custom URL patterns for operations"), - /** - * Path prefix for data operations - */ - dataPrefix: external_exports.string().default("/data").describe("URL prefix for data endpoints"), - /** - * Object name parameter style - */ - objectParamStyle: external_exports.enum(["path", "query"]).default("path").describe("How object name is passed (path param or query param)") -}); -var MetadataEndpointsConfigSchema = external_exports.object({ - /** - * Path prefix for metadata operations - */ - prefix: external_exports.string().default("/meta").describe("URL prefix for metadata endpoints"), - /** - * Enable HTTP caching for metadata - */ - enableCache: external_exports.boolean().default(true).describe("Enable HTTP cache headers (ETag, Last-Modified)"), - /** - * Cache TTL in seconds - */ - cacheTtl: external_exports.number().int().default(3600).describe("Cache TTL in seconds"), - /** - * Enable specific metadata endpoints - */ - endpoints: external_exports.object({ - types: external_exports.boolean().default(true).describe("GET /meta - List all metadata types"), - items: external_exports.boolean().default(true).describe("GET /meta/:type - List items of type"), - item: external_exports.boolean().default(true).describe("GET /meta/:type/:name - Get specific item"), - schema: external_exports.boolean().default(true).describe("GET /meta/:type/:name/schema - Get JSON schema") - }).optional().describe("Enable/disable specific endpoints") -}); -var BatchEndpointsConfigSchema = external_exports.object({ - /** - * Maximum batch size - */ - maxBatchSize: external_exports.number().int().min(1).max(1e3).default(200).describe("Maximum records per batch operation"), - /** - * Enable generic batch endpoint - */ - enableBatchEndpoint: external_exports.boolean().default(true).describe("Enable POST /data/:object/batch endpoint"), - /** - * Enable specific batch operations - */ - operations: external_exports.object({ - createMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/createMany"), - updateMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/updateMany"), - deleteMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/deleteMany"), - upsertMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/upsertMany") - }).optional().describe("Enable/disable specific batch operations"), - /** - * Transaction mode default - */ - defaultAtomic: external_exports.boolean().default(true).describe("Default atomic/transaction mode for batch operations") -}); -var RouteGenerationConfigSchema = external_exports.object({ - /** - * Objects to include (if empty, include all) - */ - includeObjects: external_exports.array(external_exports.string()).optional().describe("Specific objects to generate routes for (empty = all)"), - /** - * Objects to exclude - */ - excludeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to exclude from route generation"), - /** - * Object name transformations - */ - nameTransform: external_exports.enum(["none", "plural", "kebab-case", "camelCase"]).default("none").describe("Transform object names in URLs"), - /** - * Custom route overrides per object - */ - overrides: external_exports.record(external_exports.string(), external_exports.object({ - enabled: external_exports.boolean().optional().describe("Enable/disable routes for this object"), - basePath: external_exports.string().optional().describe("Custom base path"), - operations: external_exports.record(CrudOperation, external_exports.boolean()).optional().describe("Enable/disable specific operations") - })).optional().describe("Per-object route customization") -}); -var WebhookEventSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Webhook event identifier (snake_case)"), - description: external_exports.string().describe("Human-readable event description"), - method: HttpMethod2.default("POST").describe("HTTP method for webhook delivery"), - payloadSchema: external_exports.string().describe("JSON Schema $ref for the webhook payload"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers to include in webhook delivery"), - security: external_exports.array( - external_exports.enum(["hmac_sha256", "basic", "bearer", "api_key"]) - ).describe("Supported authentication methods for webhook verification") -}); -var WebhookConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable webhook support"), - events: external_exports.array(WebhookEventSchema).describe("Registered webhook events"), - deliveryConfig: external_exports.object({ - maxRetries: external_exports.number().int().default(3).describe("Maximum delivery retry attempts"), - retryIntervalMs: external_exports.number().int().default(5e3).describe("Milliseconds between retry attempts"), - timeoutMs: external_exports.number().int().default(3e4).describe("Delivery request timeout in milliseconds"), - signatureHeader: external_exports.string().default("X-Signature-256").describe("Header name for webhook signature") - }).describe("Webhook delivery configuration"), - registrationEndpoint: external_exports.string().default("/webhooks").describe("URL path for webhook registration") -}); -var CallbackSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Callback identifier (snake_case)"), - expression: external_exports.string().describe("Runtime expression (e.g., {$request.body#/callbackUrl})"), - method: HttpMethod2.describe("HTTP method for callback request"), - url: external_exports.string().describe("Callback URL template with runtime expressions") -}); -var OpenApi31ExtensionsSchema = external_exports.object({ - webhooks: external_exports.record(external_exports.string(), WebhookEventSchema).optional().describe("OpenAPI 3.1 webhooks (top-level webhook definitions)"), - callbacks: external_exports.record(external_exports.string(), external_exports.array(CallbackSchema)).optional().describe("OpenAPI 3.1 callbacks (async response definitions)"), - jsonSchemaDialect: external_exports.string().default("https://json-schema.org/draft/2020-12/schema").describe("JSON Schema dialect for schema definitions"), - pathItemReferences: external_exports.boolean().default(false).describe("Allow $ref in path items (OpenAPI 3.1 feature)") -}); -var RestServerConfigSchema = external_exports.object({ - /** - * API configuration - */ - api: RestApiConfigSchema.optional().describe("REST API configuration"), - /** - * CRUD endpoints configuration - */ - crud: CrudEndpointsConfigSchema.optional().describe("CRUD endpoints configuration"), - /** - * Metadata endpoints configuration - */ - metadata: MetadataEndpointsConfigSchema.optional().describe("Metadata endpoints configuration"), - /** - * Batch endpoints configuration - */ - batch: BatchEndpointsConfigSchema.optional().describe("Batch endpoints configuration"), - /** - * Route generation configuration - */ - routes: RouteGenerationConfigSchema.optional().describe("Route generation configuration"), - /** - * OpenAPI 3.1 extensions (webhooks, callbacks) - */ - openApi31: OpenApi31ExtensionsSchema.optional().describe("OpenAPI 3.1 extensions configuration") -}); -var GeneratedEndpointSchema = external_exports.object({ - /** - * Endpoint identifier - */ - id: external_exports.string().describe("Unique endpoint identifier"), - /** - * HTTP method - */ - method: HttpMethod2.describe("HTTP method"), - /** - * Full URL path - */ - path: external_exports.string().describe("Full URL path"), - /** - * Object this endpoint operates on - */ - object: external_exports.string().describe("Object name (snake_case)"), - /** - * Operation type - */ - operation: external_exports.union([CrudOperation, external_exports.string()]).describe("Operation type"), - /** - * Handler reference - */ - handler: external_exports.string().describe("Handler function identifier"), - /** - * Endpoint metadata - */ - metadata: external_exports.object({ - summary: external_exports.string().optional(), - description: external_exports.string().optional(), - tags: external_exports.array(external_exports.string()).optional(), - deprecated: external_exports.boolean().optional() - }).optional() -}); -var EndpointRegistrySchema = external_exports.object({ - /** - * Generated endpoints - */ - endpoints: external_exports.array(GeneratedEndpointSchema).describe("All generated endpoints"), - /** - * Total endpoint count - */ - total: external_exports.number().int().describe("Total number of endpoints"), - /** - * Endpoints by object - */ - byObject: external_exports.record(external_exports.string(), external_exports.array(GeneratedEndpointSchema)).optional().describe("Endpoints grouped by object"), - /** - * Endpoints by operation - */ - byOperation: external_exports.record(external_exports.string(), external_exports.array(GeneratedEndpointSchema)).optional().describe("Endpoints grouped by operation") -}); -var RestApiConfig = Object.assign(RestApiConfigSchema, { - create: (config4) => config4 -}); -var RestServerConfig = Object.assign(RestServerConfigSchema, { - create: (config4) => config4 -}); -var ApiProtocolType = external_exports.enum([ - "rest", - // RESTful API (CRUD operations) - "graphql", - // GraphQL API (flexible queries) - "odata", - // OData v4 API (enterprise integration) - "websocket", - // WebSocket API (real-time) - "file", - // File/Storage API (uploads/downloads) - "auth", - // Authentication/Authorization API - "metadata", - // Metadata/Schema API - "plugin", - // Plugin-registered custom API - "webhook", - // Webhook endpoints - "rpc" - // JSON-RPC or similar -]); -var HttpStatusCode = external_exports.union([ - external_exports.number().int().min(100).max(599), - external_exports.enum(["2xx", "3xx", "4xx", "5xx"]) - // Pattern matching -]); -var ObjectQLReferenceSchema = external_exports.object({ - /** Referenced object name (snake_case) */ - objectId: SnakeCaseIdentifierSchema2.describe("Object name to reference"), - /** Include only specific fields (optional) */ - includeFields: external_exports.array(external_exports.string()).optional().describe("Include only these fields in the schema"), - /** Exclude specific fields (optional) */ - excludeFields: external_exports.array(external_exports.string()).optional().describe("Exclude these fields from the schema"), - /** Include related objects via lookup fields */ - includeRelated: external_exports.array(external_exports.string()).optional().describe("Include related objects via lookup fields") -}); -var SchemaDefinition = external_exports.union([ - external_exports.unknown().describe("Static JSON Schema definition"), - external_exports.object({ - $ref: ObjectQLReferenceSchema.describe("Dynamic reference to ObjectQL object") - }).describe("Dynamic ObjectQL reference") -]); -var ApiParameterSchema = external_exports.object({ - /** Parameter name */ - name: external_exports.string().describe("Parameter name"), - /** Parameter location */ - in: external_exports.enum(["path", "query", "header", "body", "cookie"]).describe("Parameter location"), - /** Parameter description */ - description: external_exports.string().optional().describe("Parameter description"), - /** Required flag */ - required: external_exports.boolean().default(false).describe("Whether parameter is required"), - /** Parameter type/schema - supports static or dynamic (ObjectQL) schemas */ - schema: external_exports.union([ - external_exports.object({ - type: external_exports.enum(["string", "number", "integer", "boolean", "array", "object"]).describe("Parameter type"), - format: external_exports.string().optional().describe("Format (e.g., date-time, email, uuid)"), - enum: external_exports.array(external_exports.unknown()).optional().describe("Allowed values"), - default: external_exports.unknown().optional().describe("Default value"), - items: external_exports.unknown().optional().describe("Array item schema"), - properties: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Object properties") - }).describe("Static JSON Schema"), - external_exports.object({ - $ref: ObjectQLReferenceSchema - }).describe("Dynamic ObjectQL reference") - ]).describe("Parameter schema definition"), - /** Example value */ - example: external_exports.unknown().optional().describe("Example value") -}); -var ApiResponseSchema = external_exports.object({ - /** HTTP status code */ - statusCode: HttpStatusCode.describe("HTTP status code"), - /** Response description */ - description: external_exports.string().describe("Response description"), - /** Response content type */ - contentType: external_exports.string().default("application/json").describe("Response content type"), - /** Response schema - supports static or dynamic (ObjectQL) schemas */ - schema: external_exports.union([ - external_exports.unknown().describe("Static JSON Schema"), - external_exports.object({ - $ref: ObjectQLReferenceSchema - }).describe("Dynamic ObjectQL reference") - ]).optional().describe("Response body schema"), - /** Response headers */ - headers: external_exports.record(external_exports.string(), external_exports.object({ - description: external_exports.string().optional(), - schema: external_exports.unknown() - })).optional().describe("Response headers"), - /** Example response */ - example: external_exports.unknown().optional().describe("Example response") -}); -var ApiEndpointRegistrationSchema = external_exports.object({ - /** Unique endpoint identifier */ - id: external_exports.string().describe("Unique endpoint identifier"), - /** HTTP method (for HTTP-based APIs) */ - method: HttpMethod2.optional().describe("HTTP method"), - /** URL path pattern */ - path: external_exports.string().describe("URL path pattern"), - /** Short summary */ - summary: external_exports.string().optional().describe("Short endpoint summary"), - /** Detailed description */ - description: external_exports.string().optional().describe("Detailed endpoint description"), - /** Operation ID (OpenAPI) */ - operationId: external_exports.string().optional().describe("Unique operation identifier"), - /** Tags for grouping */ - tags: external_exports.array(external_exports.string()).optional().default([]).describe("Tags for categorization"), - /** Parameters */ - parameters: external_exports.array(ApiParameterSchema).optional().default([]).describe("Endpoint parameters"), - /** Request body schema */ - requestBody: external_exports.object({ - description: external_exports.string().optional(), - required: external_exports.boolean().default(false), - contentType: external_exports.string().default("application/json"), - schema: external_exports.unknown().optional(), - example: external_exports.unknown().optional() - }).optional().describe("Request body specification"), - /** Response definitions */ - responses: external_exports.array(ApiResponseSchema).optional().default([]).describe("Possible responses"), - /** Rate Limiting */ - rateLimit: RateLimitConfigSchema2.optional().describe("Endpoint specific rate limiting"), - /** Security Requirements */ - security: external_exports.array(external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))).optional().describe('Security requirements (e.g. [{"bearerAuth": []}])'), - /** - * Required Permissions (RBAC Integration) - * - * Array of permission names required to access this endpoint. - * The gateway layer automatically validates these permissions before - * allowing the request to proceed, eliminating the need for permission - * checks in individual API handlers. - * - * **Format:** `.` or system permission name - * - * **Object Permissions:** - * - `customer.read` - Read customer records - * - `customer.create` - Create customer records - * - `customer.edit` - Update customer records - * - `customer.delete` - Delete customer records - * - `customer.viewAll` - View all customer records (bypass sharing) - * - `customer.modifyAll` - Modify all customer records (bypass sharing) - * - * **System Permissions:** - * - `manage_users` - User management - * - `view_setup` - Access to system setup - * - `customize_application` - Modify metadata - * - `api_enabled` - API access - * - * @example Object-level permissions - * ```json - * { - * "requiredPermissions": ["customer.read"] - * } - * ``` - * - * @example Multiple permissions (ALL required) - * ```json - * { - * "requiredPermissions": ["customer.read", "account.read"] - * } - * ``` - * - * @example System permission - * ```json - * { - * "requiredPermissions": ["manage_users"] - * } - * ``` - * - * @see {@link file://../../permission/permission.zod.ts} for permission definitions - */ - requiredPermissions: external_exports.array(external_exports.string()).optional().default([]).describe('Required RBAC permissions (e.g., "customer.read", "manage_users")'), - /** - * Route Priority - * - * Priority level for route conflict resolution. Higher priority routes - * are registered first and take precedence when multiple routes match - * the same path pattern. - * - * **Default:** 100 (medium priority) - * **Range:** 0-1000 (higher = more important) - * - * **Use Cases:** - * - Core system APIs: 900-1000 - * - Plugin APIs: 100-500 - * - Custom/override APIs: 500-900 - * - Fallback routes: 0-100 - * - * @example High priority core endpoint - * ```json - * { - * "path": "/api/v1/data/:object/:id", - * "priority": 950 - * } - * ``` - * - * @example Medium priority plugin endpoint - * ```json - * { - * "path": "/api/v1/custom/action", - * "priority": 300 - * } - * ``` - */ - priority: external_exports.number().int().min(0).max(1e3).optional().default(100).describe("Route priority for conflict resolution (0-1000, higher = more important)"), - /** - * Protocol-Specific Configuration - * - * Allows plugins and custom APIs to define protocol-specific metadata - * that can be used for specialized handling or documentation generation. - * - * **Examples:** - * - gRPC: Service and method names - * - tRPC: Procedure type (query/mutation) - * - WebSocket: Event names and handlers - * - Custom protocols: Any metadata needed - * - * @example gRPC configuration - * ```json - * { - * "protocolConfig": { - * "subProtocol": "grpc", - * "serviceName": "CustomerService", - * "methodName": "GetCustomer", - * "streaming": false - * } - * } - * ``` - * - * @example tRPC configuration - * ```json - * { - * "protocolConfig": { - * "subProtocol": "trpc", - * "procedureType": "query", - * "router": "customer" - * } - * } - * ``` - * - * @example WebSocket configuration - * ```json - * { - * "protocolConfig": { - * "subProtocol": "websocket", - * "eventName": "customer.updated", - * "direction": "server-to-client" - * } - * } - * ``` - */ - protocolConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)"), - /** Deprecation flag */ - deprecated: external_exports.boolean().default(false).describe("Whether endpoint is deprecated"), - /** External documentation */ - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional().describe("External documentation link") -}); -var ApiMetadataSchema = external_exports.object({ - /** API owner/team */ - owner: external_exports.string().optional().describe("Owner team or person"), - /** API status */ - status: external_exports.enum(["active", "deprecated", "experimental", "beta"]).default("active").describe("API lifecycle status"), - /** Categorization tags */ - tags: external_exports.array(external_exports.string()).optional().default([]).describe("Classification tags"), - /** Plugin source (if plugin-registered) */ - pluginSource: external_exports.string().optional().describe("Source plugin name"), - /** Custom metadata */ - custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata fields") -}); -var ApiRegistryEntrySchema = external_exports.object({ - /** Unique API identifier */ - id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique API identifier (snake_case)"), - /** Human-readable name */ - name: external_exports.string().describe("API display name"), - /** API protocol type */ - type: ApiProtocolType.describe("API protocol type"), - /** API version */ - version: external_exports.string().describe("API version (e.g., v1, 2024-01)"), - /** Base URL path */ - basePath: external_exports.string().describe("Base URL path for this API"), - /** API description */ - description: external_exports.string().optional().describe("API description"), - /** Endpoints in this API */ - endpoints: external_exports.array(ApiEndpointRegistrationSchema).describe("Registered endpoints"), - /** OpenAPI/GraphQL/OData specific configuration */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Protocol-specific configuration"), - /** API metadata */ - metadata: ApiMetadataSchema.optional().describe("Additional metadata"), - /** Terms of service URL */ - termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), - /** Contact information */ - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().url().optional(), - email: external_exports.string().email().optional() - }).optional().describe("Contact information"), - /** License information */ - license: external_exports.object({ - name: external_exports.string(), - url: external_exports.string().url().optional() - }).optional().describe("License information") -}); -var ConflictResolutionStrategy = external_exports.enum([ - "error", - // Throw error on conflict (safest, default) - "priority", - // Use priority field to resolve (highest priority wins) - "first-wins", - // First registered endpoint wins - "last-wins" - // Last registered endpoint wins (override mode) -]); -var ApiRegistrySchema = external_exports.object({ - /** Registry version */ - version: external_exports.string().describe("Registry version"), - /** - * Conflict Resolution Strategy - * - * Defines how to handle route conflicts when multiple endpoints - * register the same or overlapping URL patterns. - * - * **Strategies:** - * - `error`: Throw error on conflict (safest, prevents silent overwrites) - * - `priority`: Use endpoint priority field (highest priority wins) - * - `first-wins`: First registered endpoint wins (stable, predictable) - * - `last-wins`: Last registered endpoint wins (allows overrides) - * - * **Default:** `error` - * - * **Best Practices:** - * - Use `error` in production to catch configuration issues - * - Use `priority` when mixing core and plugin APIs - * - Use `last-wins` for development/testing overrides - * - * @example Prevent accidental conflicts - * ```json - * { - * "conflictResolution": "error" - * } - * ``` - * - * @example Allow plugin overrides with priority - * ```json - * { - * "conflictResolution": "priority" - * } - * ``` - */ - conflictResolution: ConflictResolutionStrategy.optional().default("error").describe("Strategy for handling route conflicts"), - /** Registered APIs */ - apis: external_exports.array(ApiRegistryEntrySchema).describe("All registered APIs"), - /** Total API count */ - totalApis: external_exports.number().int().describe("Total number of registered APIs"), - /** Total endpoint count across all APIs */ - totalEndpoints: external_exports.number().int().describe("Total number of endpoints"), - /** APIs grouped by type */ - byType: external_exports.record(ApiProtocolType, external_exports.array(ApiRegistryEntrySchema)).optional().describe("APIs grouped by protocol type"), - /** APIs grouped by status */ - byStatus: external_exports.record(external_exports.string(), external_exports.array(ApiRegistryEntrySchema)).optional().describe("APIs grouped by status"), - /** Last updated timestamp */ - updatedAt: external_exports.string().datetime().optional().describe("Last registry update time") -}); -var ApiDiscoveryQuerySchema = external_exports.object({ - /** Filter by API type */ - type: ApiProtocolType.optional().describe("Filter by API protocol type"), - /** Filter by tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags (ANY match)"), - /** Filter by status */ - status: external_exports.enum(["active", "deprecated", "experimental", "beta"]).optional().describe("Filter by lifecycle status"), - /** Filter by plugin source */ - pluginSource: external_exports.string().optional().describe("Filter by plugin name"), - /** Search in name/description */ - search: external_exports.string().optional().describe("Full-text search in name/description"), - /** Filter by version */ - version: external_exports.string().optional().describe("Filter by specific version") -}); -var ApiDiscoveryResponseSchema = external_exports.object({ - /** Matching APIs */ - apis: external_exports.array(ApiRegistryEntrySchema).describe("Matching API entries"), - /** Total matches */ - total: external_exports.number().int().describe("Total matching APIs"), - /** Applied filters */ - filters: ApiDiscoveryQuerySchema.optional().describe("Applied query filters") -}); -var ApiEndpointRegistration = Object.assign(ApiEndpointRegistrationSchema, { - create: (config4) => config4 -}); -var ApiRegistryEntry = Object.assign(ApiRegistryEntrySchema, { - create: (config4) => config4 -}); -var ApiRegistry = Object.assign(ApiRegistrySchema, { - create: (config4) => config4 -}); -var OpenApiServerSchema = external_exports.object({ - /** Server URL */ - url: external_exports.string().url().describe("Server base URL"), - /** Server description */ - description: external_exports.string().optional().describe("Server description"), - /** Server variables */ - variables: external_exports.record(external_exports.string(), external_exports.object({ - default: external_exports.string(), - description: external_exports.string().optional(), - enum: external_exports.array(external_exports.string()).optional() - })).optional().describe("URL template variables") -}); -var OpenApiSecuritySchemeSchema = external_exports.object({ - /** Security scheme type */ - type: external_exports.enum(["apiKey", "http", "oauth2", "openIdConnect"]).describe("Security type"), - /** Scheme name */ - scheme: external_exports.string().optional().describe("HTTP auth scheme (bearer, basic, etc.)"), - /** Bearer format */ - bearerFormat: external_exports.string().optional().describe("Bearer token format (e.g., JWT)"), - /** API key name */ - name: external_exports.string().optional().describe("API key parameter name"), - /** API key location */ - in: external_exports.enum(["header", "query", "cookie"]).optional().describe("API key location"), - /** OAuth flows */ - flows: external_exports.object({ - implicit: external_exports.unknown().optional(), - password: external_exports.unknown().optional(), - clientCredentials: external_exports.unknown().optional(), - authorizationCode: external_exports.unknown().optional() - }).optional().describe("OAuth2 flows"), - /** OpenID Connect URL */ - openIdConnectUrl: external_exports.string().url().optional().describe("OpenID Connect discovery URL"), - /** Description */ - description: external_exports.string().optional().describe("Security scheme description") -}); -var OpenApiSpecSchema = external_exports.object({ - /** OpenAPI version */ - openapi: external_exports.string().default("3.0.0").describe("OpenAPI specification version"), - /** API information */ - info: external_exports.object({ - title: external_exports.string().describe("API title"), - version: external_exports.string().describe("API version"), - description: external_exports.string().optional().describe("API description"), - termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().url().optional(), - email: external_exports.string().email().optional() - }).optional(), - license: external_exports.object({ - name: external_exports.string(), - url: external_exports.string().url().optional() - }).optional() - }).describe("API metadata"), - /** Servers */ - servers: external_exports.array(OpenApiServerSchema).optional().default([]).describe("API servers"), - /** API paths */ - paths: external_exports.record(external_exports.string(), external_exports.unknown()).describe("API paths and operations"), - /** Reusable components */ - components: external_exports.object({ - schemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - responses: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - examples: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - requestBodies: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - headers: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - securitySchemes: external_exports.record(external_exports.string(), OpenApiSecuritySchemeSchema).optional(), - links: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - callbacks: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional().describe("Reusable components"), - /** Security requirements */ - security: external_exports.array(external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))).optional().describe("Global security requirements"), - /** Tags */ - tags: external_exports.array(external_exports.object({ - name: external_exports.string(), - description: external_exports.string().optional(), - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional() - })).optional().describe("Tag definitions"), - /** External documentation */ - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional().describe("External documentation") -}); -var ApiTestingUiType = external_exports.enum([ - "swagger-ui", - // Swagger UI - "redoc", - // Redoc - "rapidoc", - // RapiDoc - "stoplight", - // Stoplight Elements - "scalar", - // Scalar API Reference - "graphql-playground", - // GraphQL Playground - "graphiql", - // GraphiQL - "postman", - // Postman-like interface - "custom" - // Custom implementation -]); -var ApiTestingUiConfigSchema = external_exports.object({ - /** UI type */ - type: ApiTestingUiType.describe("Testing UI implementation"), - /** UI path */ - path: external_exports.string().default("/api-docs").describe("URL path for documentation UI"), - /** UI theme */ - theme: external_exports.enum(["light", "dark", "auto"]).default("light").describe("UI color theme"), - /** Enable try-it-out feature */ - enableTryItOut: external_exports.boolean().default(true).describe("Enable interactive API testing"), - /** Enable filtering */ - enableFilter: external_exports.boolean().default(true).describe("Enable endpoint filtering"), - /** Enable CORS for testing */ - enableCors: external_exports.boolean().default(true).describe("Enable CORS for browser testing"), - /** Default expand depth for models */ - defaultModelsExpandDepth: external_exports.number().int().min(-1).default(1).describe("Default expand depth for schemas (-1 = fully expand)"), - /** Display request duration */ - displayRequestDuration: external_exports.boolean().default(true).describe("Show request duration"), - /** Syntax highlighting */ - syntaxHighlighting: external_exports.boolean().default(true).describe("Enable syntax highlighting"), - /** Custom CSS URL */ - customCssUrl: external_exports.string().url().optional().describe("Custom CSS stylesheet URL"), - /** Custom JavaScript URL */ - customJsUrl: external_exports.string().url().optional().describe("Custom JavaScript URL"), - /** Layout options */ - layout: external_exports.object({ - showExtensions: external_exports.boolean().default(false).describe("Show vendor extensions"), - showCommonExtensions: external_exports.boolean().default(false).describe("Show common extensions"), - deepLinking: external_exports.boolean().default(true).describe("Enable deep linking"), - displayOperationId: external_exports.boolean().default(false).describe("Display operation IDs"), - defaultModelRendering: external_exports.enum(["example", "model"]).default("example").describe("Default model rendering mode"), - defaultModelsExpandDepth: external_exports.number().int().default(1).describe("Models expand depth"), - defaultModelExpandDepth: external_exports.number().int().default(1).describe("Single model expand depth"), - docExpansion: external_exports.enum(["list", "full", "none"]).default("list").describe("Documentation expansion mode") - }).optional().describe("Layout configuration") -}); -var ApiTestRequestSchema = external_exports.object({ - /** Request name */ - name: external_exports.string().describe("Test request name"), - /** Request description */ - description: external_exports.string().optional().describe("Request description"), - /** HTTP method */ - method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]).describe("HTTP method"), - /** Request URL */ - url: external_exports.string().describe("Request URL (can include variables)"), - /** Request headers */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().default({}).describe("Request headers"), - /** Query parameters */ - queryParams: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().default({}).describe("Query parameters"), - /** Request body */ - body: external_exports.unknown().optional().describe("Request body"), - /** Environment variables */ - variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().default({}).describe("Template variables"), - /** Expected response */ - expectedResponse: external_exports.object({ - statusCode: external_exports.number().int(), - body: external_exports.unknown().optional() - }).optional().describe("Expected response for validation") -}); -var ApiTestCollectionSchema = external_exports.object({ - /** Collection name */ - name: external_exports.string().describe("Collection name"), - /** Collection description */ - description: external_exports.string().optional().describe("Collection description"), - /** Collection variables */ - variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().default({}).describe("Shared variables"), - /** Test requests */ - requests: external_exports.array(ApiTestRequestSchema).describe("Test requests in this collection"), - /** Folders/grouping */ - folders: external_exports.array(external_exports.object({ - name: external_exports.string(), - description: external_exports.string().optional(), - requests: external_exports.array(ApiTestRequestSchema) - })).optional().describe("Request folders for organization") -}); -var ApiChangelogEntrySchema = external_exports.object({ - /** Version */ - version: external_exports.string().describe("API version"), - /** Release date */ - date: external_exports.string().date().describe("Release date"), - /** Changes */ - changes: external_exports.object({ - added: external_exports.array(external_exports.string()).optional().default([]).describe("New features"), - changed: external_exports.array(external_exports.string()).optional().default([]).describe("Changes"), - deprecated: external_exports.array(external_exports.string()).optional().default([]).describe("Deprecations"), - removed: external_exports.array(external_exports.string()).optional().default([]).describe("Removed features"), - fixed: external_exports.array(external_exports.string()).optional().default([]).describe("Bug fixes"), - security: external_exports.array(external_exports.string()).optional().default([]).describe("Security fixes") - }).describe("Version changes"), - /** Migration guide */ - migrationGuide: external_exports.string().optional().describe("Migration guide URL or text") -}); -var CodeGenerationTemplateSchema = external_exports.object({ - /** Language/framework */ - language: external_exports.string().describe("Target language/framework (e.g., typescript, python, curl)"), - /** Template name */ - name: external_exports.string().describe("Template name"), - /** Template content */ - template: external_exports.string().describe("Code template with placeholders"), - /** Template variables */ - variables: external_exports.array(external_exports.string()).optional().describe("Required template variables") -}); -var ApiDocumentationConfigSchema = external_exports.object({ - /** Enable documentation */ - enabled: external_exports.boolean().default(true).describe("Enable API documentation"), - /** Documentation title */ - title: external_exports.string().default("API Documentation").describe("Documentation title"), - /** API version */ - version: external_exports.string().describe("API version"), - /** API description */ - description: external_exports.string().optional().describe("API description"), - /** Server configurations */ - servers: external_exports.array(OpenApiServerSchema).optional().default([]).describe("API server URLs"), - /** UI configuration */ - ui: ApiTestingUiConfigSchema.optional().describe("Testing UI configuration"), - /** Generate OpenAPI spec */ - generateOpenApi: external_exports.boolean().default(true).describe("Generate OpenAPI 3.0 specification"), - /** Generate test collections */ - generateTestCollections: external_exports.boolean().default(true).describe("Generate API test collections"), - /** Test collections */ - testCollections: external_exports.array(ApiTestCollectionSchema).optional().default([]).describe("Predefined test collections"), - /** API changelog */ - changelog: external_exports.array(ApiChangelogEntrySchema).optional().default([]).describe("API version changelog"), - /** Code generation templates */ - codeTemplates: external_exports.array(CodeGenerationTemplateSchema).optional().default([]).describe("Code generation templates"), - /** Terms of service */ - termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), - /** Contact information */ - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().url().optional(), - email: external_exports.string().email().optional() - }).optional().describe("Contact information"), - /** License */ - license: external_exports.object({ - name: external_exports.string(), - url: external_exports.string().url().optional() - }).optional().describe("API license"), - /** External documentation */ - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional().describe("External documentation link"), - /** Security schemes */ - securitySchemes: external_exports.record(external_exports.string(), OpenApiSecuritySchemeSchema).optional().describe("Security scheme definitions"), - /** Global tags */ - tags: external_exports.array(external_exports.object({ - name: external_exports.string(), - description: external_exports.string().optional(), - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional() - })).optional().describe("Global tag definitions") -}); -var GeneratedApiDocumentationSchema = external_exports.object({ - /** OpenAPI specification */ - openApiSpec: OpenApiSpecSchema.optional().describe("Generated OpenAPI specification"), - /** Test collections */ - testCollections: external_exports.array(ApiTestCollectionSchema).optional().describe("Generated test collections"), - /** Markdown documentation */ - markdown: external_exports.string().optional().describe("Generated markdown documentation"), - /** HTML documentation */ - html: external_exports.string().optional().describe("Generated HTML documentation"), - /** Generation timestamp */ - generatedAt: external_exports.string().datetime().describe("Generation timestamp"), - /** Source APIs */ - sourceApis: external_exports.array(external_exports.string()).describe("Source API IDs used for generation") -}); -var ApiDocumentationConfig = Object.assign(ApiDocumentationConfigSchema, { - create: (config4) => config4 -}); -var ApiTestCollection = Object.assign(ApiTestCollectionSchema, { - create: (config4) => config4 -}); -var OpenApiSpec = Object.assign(OpenApiSpecSchema, { - create: (config4) => config4 -}); -var AggregationMetricType = external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "number", - // Custom SQL expression returning a number - "string", - // Custom SQL expression returning a string - "boolean" - // Custom SQL expression returning a boolean -]); -var DimensionType = external_exports.enum([ - "string", - "number", - "boolean", - "time", - "geo" -]); -var TimeUpdateInterval = external_exports.enum([ - "second", - "minute", - "hour", - "day", - "week", - "month", - "quarter", - "year" -]); -var MetricSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique metric ID"), - label: external_exports.string().describe("Human readable label"), - description: external_exports.string().optional(), - type: AggregationMetricType, - /** Source Calculation */ - sql: external_exports.string().describe("SQL expression or field reference"), - /** Filtering for this specific metric (e.g. "Revenue from Premium Users") */ - filters: external_exports.array(external_exports.object({ - sql: external_exports.string() - })).optional(), - /** Format for display (e.g. "currency", "percent") */ - format: external_exports.string().optional() -}); -var DimensionSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique dimension ID"), - label: external_exports.string().describe("Human readable label"), - description: external_exports.string().optional(), - type: DimensionType, - /** Source Column */ - sql: external_exports.string().describe("SQL expression or column reference"), - /** For Time Dimensions: Supported Granularities */ - granularities: external_exports.array(TimeUpdateInterval).optional() -}); -var CubeJoinSchema = external_exports.object({ - name: external_exports.string().describe("Target cube name"), - relationship: external_exports.enum(["one_to_one", "one_to_many", "many_to_one"]).default("many_to_one"), - sql: external_exports.string().describe("Join condition (ON clause)") -}); -var CubeSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Cube name (snake_case)"), - title: external_exports.string().optional(), - description: external_exports.string().optional(), - /** Physical Data Source */ - sql: external_exports.string().describe("Base SQL statement or Table Name"), - /** Semantic Definitions */ - measures: external_exports.record(external_exports.string(), MetricSchema).describe("Quantitative metrics"), - dimensions: external_exports.record(external_exports.string(), DimensionSchema).describe("Qualitative attributes"), - /** Relationships */ - joins: external_exports.record(external_exports.string(), CubeJoinSchema).optional(), - /** Pre-aggregations / Caching */ - refreshKey: external_exports.object({ - every: external_exports.string().optional(), - // e.g. "1 hour" - sql: external_exports.string().optional() - // SQL to check for data changes - }).optional(), - /** Access Control */ - public: external_exports.boolean().default(false) -}); -var AnalyticsQuerySchema = external_exports.object({ - cube: external_exports.string().optional().describe("Target cube name (optional when provided externally, e.g. in API request wrapper)"), - measures: external_exports.array(external_exports.string()).describe("List of metrics to calculate"), - dimensions: external_exports.array(external_exports.string()).optional().describe("List of dimensions to group by"), - filters: external_exports.array(external_exports.object({ - member: external_exports.string().describe("Dimension or Measure"), - operator: external_exports.enum(["equals", "notEquals", "contains", "notContains", "gt", "gte", "lt", "lte", "set", "notSet", "inDateRange"]), - values: external_exports.array(external_exports.string()).optional() - })).optional(), - timeDimensions: external_exports.array(external_exports.object({ - dimension: external_exports.string(), - granularity: TimeUpdateInterval.optional(), - dateRange: external_exports.union([ - external_exports.string(), - // "Last 7 days" - external_exports.array(external_exports.string()) - // ["2023-01-01", "2023-01-31"] - ]).optional() - })).optional(), - order: external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])).optional(), - limit: external_exports.number().optional(), - offset: external_exports.number().optional(), - timezone: external_exports.string().optional().default("UTC") -}); -var AnalyticsEndpoint = external_exports.enum([ - "/api/v1/analytics/query", - // Execute analysis - "/api/v1/analytics/meta", - // Discover cubes/metrics - "/api/v1/analytics/sql" - // Dry-run SQL generation -]); -var AnalyticsQueryRequestSchema = external_exports.object({ - query: AnalyticsQuerySchema.describe("The analytic query definition"), - cube: external_exports.string().describe("Target cube name"), - format: external_exports.enum(["json", "csv", "xlsx"]).default("json").describe("Response format") -}); -var AnalyticsResultResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - rows: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Result rows"), - fields: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string() - })).describe("Column metadata"), - sql: external_exports.string().optional().describe("Executed SQL (if debug enabled)") - }) -}); -var GetAnalyticsMetaRequestSchema = external_exports.object({ - cube: external_exports.string().optional().describe("Optional cube name to filter") -}); -var AnalyticsMetadataResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - cubes: external_exports.array(CubeSchema).describe("Available cubes") - }) -}); -var AnalyticsSqlResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - sql: external_exports.string(), - params: external_exports.array(external_exports.unknown()) - }) -}); -var VersioningStrategy = external_exports.enum([ - "urlPath", - "header", - "queryParam", - "dateBased" -]); -var VersionStatus = external_exports.enum([ - "preview", - "current", - "supported", - "deprecated", - "retired" -]); -var VersionDefinitionSchema = external_exports.object({ - /** Version identifier (e.g., "v1", "v2beta1", "2025-01-01") */ - version: external_exports.string().describe('Version identifier (e.g., "v1", "v2beta1", "2025-01-01")'), - /** Current lifecycle status */ - status: VersionStatus.describe("Lifecycle status of this version"), - /** Date this version was released (ISO 8601 date) */ - releasedAt: external_exports.string().describe('Release date (ISO 8601, e.g., "2025-01-15")'), - /** Date this version was deprecated (ISO 8601 date) */ - deprecatedAt: external_exports.string().optional().describe("Deprecation date (ISO 8601). Only set for deprecated/retired versions"), - /** Date this version will be retired (ISO 8601 date) */ - sunsetAt: external_exports.string().optional().describe("Sunset date (ISO 8601). After this date, the version returns 410 Gone"), - /** URL to migration guide for moving to a newer version */ - migrationGuide: external_exports.string().url().optional().describe("URL to migration guide for upgrading from this version"), - /** Human-readable description of this version */ - description: external_exports.string().optional().describe("Human-readable description or release notes summary"), - /** Breaking changes introduced in or since this version */ - breakingChanges: external_exports.array(external_exports.string()).optional().describe("List of breaking changes (for preview/new versions)") -}); -var VersioningConfigSchema2 = external_exports.object({ - /** Versioning strategy */ - strategy: VersioningStrategy.default("urlPath").describe("How the API version is specified by clients"), - /** Current (recommended) API version */ - current: external_exports.string().describe("The current/recommended API version identifier"), - /** Default version when none specified by client */ - default: external_exports.string().describe("Fallback version when client does not specify one"), - /** All available API versions */ - versions: external_exports.array(VersionDefinitionSchema).min(1).describe("All available API versions with lifecycle metadata"), - /** Header name for header-based versioning */ - headerName: external_exports.string().default("ObjectStack-Version").describe("HTTP header name for version negotiation (header/dateBased strategies)"), - /** Query parameter name for queryParam strategy */ - queryParamName: external_exports.string().default("version").describe("Query parameter name for version specification (queryParam strategy)"), - /** URL prefix pattern for urlPath strategy */ - urlPrefix: external_exports.string().default("/api").describe("URL prefix before version segment (urlPath strategy)"), - /** Deprecation behavior */ - deprecation: external_exports.object({ - /** Include Deprecation header in responses for deprecated versions */ - warnHeader: external_exports.boolean().default(true).describe("Include Deprecation header (RFC 8594) in responses"), - /** Include Sunset header with retirement date */ - sunsetHeader: external_exports.boolean().default(true).describe("Include Sunset header (RFC 8594) with retirement date"), - /** Include Link header pointing to migration guide */ - linkHeader: external_exports.boolean().default(true).describe("Include Link header pointing to migration guide URL"), - /** Whether to reject requests to retired versions */ - rejectRetired: external_exports.boolean().default(true).describe("Return 410 Gone for retired API versions"), - /** Custom deprecation warning message */ - warningMessage: external_exports.string().optional().describe("Custom warning message for deprecated version responses") - }).optional().describe("Deprecation lifecycle behavior"), - /** Whether to include version info in discovery response */ - includeInDiscovery: external_exports.boolean().default(true).describe("Include version information in the API discovery endpoint") -}); -var VersionNegotiationResponseSchema = external_exports.object({ - /** The current/recommended version */ - current: external_exports.string().describe("Current recommended API version"), - /** The version the client requested (if any) */ - requested: external_exports.string().optional().describe("Version requested by the client"), - /** The version actually being used for this request */ - resolved: external_exports.string().describe("Resolved API version for this request"), - /** All supported (non-retired) version identifiers */ - supported: external_exports.array(external_exports.string()).describe("All supported version identifiers"), - /** Deprecated version identifiers (still functional but will be removed) */ - deprecated: external_exports.array(external_exports.string()).optional().describe("Deprecated version identifiers"), - /** Full version definitions (optional, for detailed clients) */ - versions: external_exports.array(VersionDefinitionSchema).optional().describe("Full version definitions with lifecycle metadata") -}); -var AuthProvider = external_exports.enum([ - "local", - "google", - "github", - "microsoft", - "ldap", - "saml" -]); -var SessionUserSchema = external_exports.object({ - id: external_exports.string().describe("User ID"), - email: external_exports.string().email().describe("Email address"), - emailVerified: external_exports.boolean().default(false).describe("Is email verified?"), - name: external_exports.string().describe("Display name"), - image: external_exports.string().optional().describe("Avatar URL"), - username: external_exports.string().optional().describe("Username (optional)"), - roles: external_exports.array(external_exports.string()).optional().default([]).describe("Assigned role IDs"), - tenantId: external_exports.string().optional().describe("Current tenant ID"), - language: external_exports.string().default("en").describe("Preferred language"), - timezone: external_exports.string().optional().describe("Preferred timezone"), - createdAt: external_exports.string().datetime().optional(), - updatedAt: external_exports.string().datetime().optional() -}); -var SessionSchema = external_exports.object({ - id: external_exports.string(), - expiresAt: external_exports.string().datetime(), - token: external_exports.string().optional(), - ipAddress: external_exports.string().optional(), - userAgent: external_exports.string().optional(), - userId: external_exports.string() -}); -var LoginType = external_exports.enum(["email", "username", "phone", "magic-link", "social"]); -var LoginRequestSchema = external_exports.object({ - type: LoginType.default("email").describe("Login method"), - email: external_exports.string().email().optional().describe("Required for email/magic-link"), - username: external_exports.string().optional().describe("Required for username login"), - password: external_exports.string().optional().describe("Required for password login"), - provider: external_exports.string().optional().describe("Required for social (google, github)"), - redirectTo: external_exports.string().optional().describe("Redirect URL after successful login") -}); -var RegisterRequestSchema = external_exports.object({ - email: external_exports.string().email(), - password: external_exports.string(), - name: external_exports.string(), - image: external_exports.string().optional() -}); -var RefreshTokenRequestSchema = external_exports.object({ - refreshToken: external_exports.string().describe("Refresh token") -}); -var SessionResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - session: SessionSchema.describe("Active Session Info"), - user: SessionUserSchema.describe("Current User Details"), - token: external_exports.string().optional().describe("Bearer token if not using cookies") - }) -}); -var UserProfileResponseSchema = BaseResponseSchema.extend({ - data: SessionUserSchema -}); -var AuthEndpointPaths = { - // Email/Password Authentication - signInEmail: "/sign-in/email", - signUpEmail: "/sign-up/email", - signOut: "/sign-out", - // Session Management - getSession: "/get-session", - // Password Management - forgetPassword: "/forget-password", - resetPassword: "/reset-password", - // Email Verification - sendVerificationEmail: "/send-verification-email", - verifyEmail: "/verify-email", - // OAuth (dynamic based on provider) - // authorize: '/authorize/:provider' - // callback: '/callback/:provider' - // 2FA (when enabled) - twoFactorEnable: "/two-factor/enable", - twoFactorVerify: "/two-factor/verify", - // Passkeys (when enabled) - passkeyRegister: "/passkey/register", - passkeyAuthenticate: "/passkey/authenticate", - // Magic Links (when enabled) - magicLinkSend: "/magic-link/send", - magicLinkVerify: "/magic-link/verify" -}; -var AuthEndpointSchema = external_exports.object({ - /** Sign in with email and password */ - signInEmail: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths.signInEmail), - description: external_exports.literal("Sign in with email and password") - }), - /** Register new user with email and password */ - signUpEmail: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths.signUpEmail), - description: external_exports.literal("Register new user with email and password") - }), - /** Sign out current user */ - signOut: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths.signOut), - description: external_exports.literal("Sign out current user") - }), - /** Get current user session */ - getSession: external_exports.object({ - method: external_exports.literal("GET"), - path: external_exports.literal(AuthEndpointPaths.getSession), - description: external_exports.literal("Get current user session") - }), - /** Request password reset email */ - forgetPassword: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths.forgetPassword), - description: external_exports.literal("Request password reset email") - }), - /** Reset password with token */ - resetPassword: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths.resetPassword), - description: external_exports.literal("Reset password with token") - }), - /** Send email verification */ - sendVerificationEmail: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths.sendVerificationEmail), - description: external_exports.literal("Send email verification link") - }), - /** Verify email with token */ - verifyEmail: external_exports.object({ - method: external_exports.literal("GET"), - path: external_exports.literal(AuthEndpointPaths.verifyEmail), - description: external_exports.literal("Verify email with token") - }) -}); -var AuthEndpointAliases = { - login: AuthEndpointPaths.signInEmail, - register: AuthEndpointPaths.signUpEmail, - logout: AuthEndpointPaths.signOut, - me: AuthEndpointPaths.getSession -}; -var EndpointMapping = { - "/login": AuthEndpointPaths.signInEmail, - "/register": AuthEndpointPaths.signUpEmail, - "/logout": AuthEndpointPaths.signOut, - "/me": AuthEndpointPaths.getSession, - "/refresh": AuthEndpointPaths.getSession - // Session refresh handled by better-auth automatically -}; -var StorageScopeSchema2 = external_exports.enum([ - "global", - // Global application-wide storage - "tenant", - // Tenant-scoped storage (multi-tenant apps) - "user", - // User-scoped storage - "session", - // Session-scoped storage (ephemeral) - "temp", - // Ephemeral, cleared on restart - "cache", - // Ephemeral, survives restarts, cleared on LRU/Expiration - "data", - // Persistent, backed up - "logs", - // Append-only, rotated - "config", - // Read-heavy, versioned - "public" - // Publicly accessible static assets -]).describe("Storage scope classification"); -var FileMetadataSchema2 = external_exports.object({ - path: external_exports.string().describe("File path"), - name: external_exports.string().describe("File name"), - size: external_exports.number().int().describe("File size in bytes"), - mimeType: external_exports.string().describe("MIME type"), - lastModified: external_exports.string().datetime().describe("Last modified timestamp"), - created: external_exports.string().datetime().describe("Creation timestamp"), - etag: external_exports.string().optional().describe("Entity tag") -}); -var StorageProviderSchema2 = external_exports.enum([ - "s3", - // Amazon S3 - "azure_blob", - // Azure Blob Storage - "gcs", - // Google Cloud Storage - "minio", - // MinIO (self-hosted S3-compatible) - "r2", - // Cloudflare R2 - "spaces", - // DigitalOcean Spaces - "wasabi", - // Wasabi Hot Cloud Storage - "backblaze", - // Backblaze B2 - "local" - // Local filesystem (development only) -]).describe("Storage provider type"); -var StorageAclSchema2 = external_exports.enum([ - "private", - // Owner has full control, no one else has access - "public_read", - // Owner has full control, everyone can read - "public_read_write", - // Owner has full control, everyone can read/write (not recommended) - "authenticated_read", - // Owner has full control, authenticated users can read - "bucket_owner_read", - // Object owner has full control, bucket owner can read - "bucket_owner_full_control" - // Both object and bucket owner have full control -]).describe("Storage access control level"); -var StorageClassSchema2 = external_exports.enum([ - "standard", - // Standard/hot storage for frequently accessed data - "intelligent", - // Intelligent tiering (auto-moves between hot/cool) - "infrequent_access", - // Infrequent access/cool storage - "glacier", - // Archive/cold storage (slower retrieval) - "deep_archive" - // Deep archive (cheapest, slowest retrieval) -]).describe("Storage class/tier for cost optimization"); -var LifecycleActionSchema2 = external_exports.enum([ - "transition", - // Move to different storage class - "delete", - // Delete the object - "abort" - // Abort incomplete multipart uploads -]).describe("Lifecycle policy action type"); -external_exports.object({ - contentType: external_exports.string().describe("MIME type (e.g., image/jpeg, application/pdf)"), - contentLength: external_exports.number().min(0).describe("File size in bytes"), - contentEncoding: external_exports.string().optional().describe("Content encoding (e.g., gzip)"), - contentDisposition: external_exports.string().optional().describe("Content disposition header"), - contentLanguage: external_exports.string().optional().describe("Content language"), - cacheControl: external_exports.string().optional().describe("Cache control directives"), - etag: external_exports.string().optional().describe("Entity tag for versioning/caching"), - lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), - versionId: external_exports.string().optional().describe("Object version identifier"), - storageClass: StorageClassSchema2.optional().describe("Storage class/tier"), - encryption: external_exports.object({ - algorithm: external_exports.string().describe("Encryption algorithm (e.g., AES256, aws:kms)"), - keyId: external_exports.string().optional().describe("KMS key ID if using managed encryption") - }).optional().describe("Server-side encryption configuration"), - custom: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom user-defined metadata") -}); -external_exports.object({ - operation: external_exports.enum(["get", "put", "delete", "head"]).describe("Allowed operation"), - expiresIn: external_exports.number().min(1).max(604800).describe("Expiration time in seconds (max 7 days)"), - contentType: external_exports.string().optional().describe("Required content type for PUT operations"), - maxSize: external_exports.number().min(0).optional().describe("Maximum file size in bytes for PUT operations"), - responseContentType: external_exports.string().optional().describe("Override content-type for GET operations"), - responseContentDisposition: external_exports.string().optional().describe("Override content-disposition for GET operations") -}); -var MultipartUploadConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable multipart uploads"), - partSize: external_exports.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe("Part size in bytes (min 5MB, max 5GB)"), - maxParts: external_exports.number().min(1).max(1e4).default(1e4).describe("Maximum number of parts (max 10,000)"), - threshold: external_exports.number().min(0).default(100 * 1024 * 1024).describe("File size threshold to trigger multipart upload (bytes)"), - maxConcurrent: external_exports.number().min(1).max(100).default(4).describe("Maximum concurrent part uploads"), - abortIncompleteAfterDays: external_exports.number().min(1).optional().describe("Auto-abort incomplete uploads after N days") -}); -var AccessControlConfigSchema2 = external_exports.object({ - acl: StorageAclSchema2.default("private").describe("Default access control level"), - allowedOrigins: external_exports.array(external_exports.string()).optional().describe("CORS allowed origins"), - allowedMethods: external_exports.array(external_exports.enum(["GET", "PUT", "POST", "DELETE", "HEAD"])).optional().describe("CORS allowed HTTP methods"), - allowedHeaders: external_exports.array(external_exports.string()).optional().describe("CORS allowed headers"), - exposeHeaders: external_exports.array(external_exports.string()).optional().describe("CORS exposed headers"), - maxAge: external_exports.number().min(0).optional().describe("CORS preflight cache duration in seconds"), - corsEnabled: external_exports.boolean().default(false).describe("Enable CORS configuration"), - publicAccess: external_exports.object({ - allowPublicRead: external_exports.boolean().default(false).describe("Allow public read access"), - allowPublicWrite: external_exports.boolean().default(false).describe("Allow public write access"), - allowPublicList: external_exports.boolean().default(false).describe("Allow public bucket listing") - }).optional().describe("Public access control"), - allowedIps: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses/CIDR blocks"), - blockedIps: external_exports.array(external_exports.string()).optional().describe("Blocked IP addresses/CIDR blocks") -}); -var LifecyclePolicyRuleSchema2 = external_exports.object({ - id: SystemIdentifierSchema2.describe("Rule identifier"), - enabled: external_exports.boolean().default(true).describe("Enable this rule"), - action: LifecycleActionSchema2.describe("Action to perform"), - prefix: external_exports.string().optional().describe('Object key prefix filter (e.g., "uploads/")'), - tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Object tag filters"), - daysAfterCreation: external_exports.number().min(0).optional().describe("Days after object creation"), - daysAfterModification: external_exports.number().min(0).optional().describe("Days after last modification"), - targetStorageClass: StorageClassSchema2.optional().describe("Target storage class for transition action") -}).refine((data) => { - if (data.action === "transition" && !data.targetStorageClass) { - return false; - } - return true; -}, { - message: 'targetStorageClass is required when action is "transition"' -}); -var LifecyclePolicyConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable lifecycle policies"), - rules: external_exports.array(LifecyclePolicyRuleSchema2).default([]).describe("Lifecycle rules") -}); -var BucketConfigSchema2 = external_exports.object({ - name: SystemIdentifierSchema2.describe("Bucket identifier in ObjectStack (snake_case)"), - label: external_exports.string().describe("Display label"), - bucketName: external_exports.string().describe("Actual bucket/container name in storage provider"), - region: external_exports.string().optional().describe("Storage region (e.g., us-east-1, westus)"), - provider: StorageProviderSchema2.describe("Storage provider"), - endpoint: external_exports.string().optional().describe("Custom endpoint URL (for S3-compatible providers)"), - pathStyle: external_exports.boolean().default(false).describe("Use path-style URLs (for S3-compatible providers)"), - versioning: external_exports.boolean().default(false).describe("Enable object versioning"), - encryption: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable server-side encryption"), - algorithm: external_exports.enum(["AES256", "aws:kms", "azure:kms", "gcp:kms"]).default("AES256").describe("Encryption algorithm"), - kmsKeyId: external_exports.string().optional().describe("KMS key ID for managed encryption") - }).optional().describe("Server-side encryption configuration"), - accessControl: AccessControlConfigSchema2.optional().describe("Access control configuration"), - lifecyclePolicy: LifecyclePolicyConfigSchema2.optional().describe("Lifecycle policy configuration"), - multipartConfig: MultipartUploadConfigSchema2.optional().describe("Multipart upload configuration"), - tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Bucket tags for organization"), - description: external_exports.string().optional().describe("Bucket description"), - enabled: external_exports.boolean().default(true).describe("Enable this bucket") -}); -var StorageConnectionSchema2 = external_exports.object({ - // AWS S3 / MinIO - accessKeyId: external_exports.string().optional().describe("AWS access key ID or MinIO access key"), - secretAccessKey: external_exports.string().optional().describe("AWS secret access key or MinIO secret key"), - sessionToken: external_exports.string().optional().describe("AWS session token for temporary credentials"), - // Azure Blob Storage - accountName: external_exports.string().optional().describe("Azure storage account name"), - accountKey: external_exports.string().optional().describe("Azure storage account key"), - sasToken: external_exports.string().optional().describe("Azure SAS token"), - // Google Cloud Storage - projectId: external_exports.string().optional().describe("GCP project ID"), - credentials: external_exports.string().optional().describe("GCP service account credentials JSON"), - // Common - endpoint: external_exports.string().optional().describe("Custom endpoint URL"), - region: external_exports.string().optional().describe("Default region"), - useSSL: external_exports.boolean().default(true).describe("Use SSL/TLS for connections"), - timeout: external_exports.number().min(0).optional().describe("Connection timeout in milliseconds") -}); -var ObjectStorageConfigSchema2 = external_exports.object({ - name: SystemIdentifierSchema2.describe("Storage configuration identifier"), - label: external_exports.string().describe("Display label"), - provider: StorageProviderSchema2.describe("Primary storage provider"), - /** - * Storage scope - * Defines the lifecycle and access pattern for this storage - */ - scope: StorageScopeSchema2.optional().default("global").describe("Storage scope"), - connection: StorageConnectionSchema2.describe("Connection credentials"), - buckets: external_exports.array(BucketConfigSchema2).default([]).describe("Configured buckets"), - defaultBucket: external_exports.string().optional().describe("Default bucket name for operations"), - /** - * Base path or location - * For local/scoped storage configurations - */ - location: external_exports.string().optional().describe("Root path (local) or base location"), - /** - * Storage quota in bytes - */ - quota: external_exports.number().int().positive().optional().describe("Max size in bytes"), - /** - * Provider-specific options - */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration options"), - enabled: external_exports.boolean().default(true).describe("Enable this storage configuration"), - description: external_exports.string().optional().describe("Configuration description") -}); -ObjectStorageConfigSchema2.parse({ - name: "aws_s3_storage", - label: "AWS S3 Production Storage", - provider: "s3", - connection: { - accessKeyId: "${AWS_ACCESS_KEY_ID}", - secretAccessKey: "${AWS_SECRET_ACCESS_KEY}", - region: "us-east-1" - }, - buckets: [ - { - name: "user_uploads", - label: "User Uploads", - bucketName: "my-app-user-uploads", - region: "us-east-1", - provider: "s3", - versioning: true, - encryption: { - enabled: true, - algorithm: "aws:kms", - kmsKeyId: "${AWS_KMS_KEY_ID}" - }, - accessControl: { - acl: "private", - corsEnabled: true, - allowedOrigins: ["https://app.example.com"], - allowedMethods: ["GET", "PUT", "POST"] - }, - lifecyclePolicy: { - enabled: true, - rules: [ - { - id: "archive_old_uploads", - enabled: true, - action: "transition", - daysAfterCreation: 90, - targetStorageClass: "glacier" - } - ] - }, - multipartConfig: { - enabled: true, - partSize: 10 * 1024 * 1024, - threshold: 100 * 1024 * 1024, - maxConcurrent: 4 - } - } - ], - defaultBucket: "user_uploads", - enabled: true -}); -ObjectStorageConfigSchema2.parse({ - name: "minio_local", - label: "MinIO Local Storage", - provider: "minio", - connection: { - accessKeyId: "minioadmin", - secretAccessKey: "minioadmin", - endpoint: "http://localhost:9000", - useSSL: false - }, - buckets: [ - { - name: "development_files", - label: "Development Files", - bucketName: "dev-files", - provider: "minio", - endpoint: "http://localhost:9000", - pathStyle: true, - accessControl: { - acl: "private" - } - } - ], - defaultBucket: "development_files", - enabled: true -}); -ObjectStorageConfigSchema2.parse({ - name: "azure_blob_storage", - label: "Azure Blob Storage", - provider: "azure_blob", - connection: { - accountName: "mystorageaccount", - accountKey: "${AZURE_STORAGE_KEY}", - endpoint: "https://mystorageaccount.blob.core.windows.net" - }, - buckets: [ - { - name: "media_files", - label: "Media Files", - bucketName: "media", - provider: "azure_blob", - region: "eastus", - accessControl: { - acl: "public_read", - publicAccess: { - allowPublicRead: true, - allowPublicWrite: false, - allowPublicList: false - } - } - } - ], - defaultBucket: "media_files", - enabled: true -}); -ObjectStorageConfigSchema2.parse({ - name: "gcs_storage", - label: "Google Cloud Storage", - provider: "gcs", - connection: { - projectId: "my-gcp-project", - credentials: "${GCP_SERVICE_ACCOUNT_JSON}" - }, - buckets: [ - { - name: "backup_storage", - label: "Backup Storage", - bucketName: "my-app-backups", - region: "us-central1", - provider: "gcs", - lifecyclePolicy: { - enabled: true, - rules: [ - { - id: "delete_old_backups", - enabled: true, - action: "delete", - daysAfterCreation: 30 - } - ] - } - } - ], - defaultBucket: "backup_storage", - enabled: true -}); -var GetPresignedUrlRequestSchema = external_exports.object({ - filename: external_exports.string().describe("Original filename"), - mimeType: external_exports.string().describe("File MIME type"), - size: external_exports.number().describe("File size in bytes"), - scope: external_exports.string().default("user").describe("Target storage scope (e.g. user, private, public)"), - bucket: external_exports.string().optional().describe("Specific bucket override (admin only)") -}); -var CompleteUploadRequestSchema = external_exports.object({ - fileId: external_exports.string().describe("File ID returned from presigned request"), - eTag: external_exports.string().optional().describe("S3 ETag verification") -}); -var PresignedUrlResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - uploadUrl: external_exports.string().describe("PUT/POST URL for direct upload"), - downloadUrl: external_exports.string().optional().describe("Public/Private preview URL"), - fileId: external_exports.string().describe("Temporary File ID"), - method: external_exports.enum(["PUT", "POST"]).describe("HTTP Method to use"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Required headers for upload"), - expiresIn: external_exports.number().describe("URL expiry in seconds") - }) -}); -var FileUploadResponseSchema = BaseResponseSchema.extend({ - data: FileMetadataSchema2.describe("Uploaded file metadata") -}); -var FileTypeValidationSchema = external_exports.object({ - mode: external_exports.enum(["whitelist", "blacklist"]).describe("whitelist = only allow listed types, blacklist = block listed types"), - mimeTypes: external_exports.array(external_exports.string()).min(1).describe('List of MIME types to allow or block (e.g., "image/jpeg", "application/pdf")'), - extensions: external_exports.array(external_exports.string()).optional().describe('List of file extensions to allow or block (e.g., ".jpg", ".pdf")'), - maxFileSize: external_exports.number().int().min(1).optional().describe("Maximum file size in bytes"), - minFileSize: external_exports.number().int().min(0).optional().describe("Minimum file size in bytes (e.g., reject empty files)") -}); -var InitiateChunkedUploadRequestSchema = external_exports.object({ - filename: external_exports.string().describe("Original filename"), - mimeType: external_exports.string().describe("File MIME type"), - totalSize: external_exports.number().int().min(1).describe("Total file size in bytes"), - chunkSize: external_exports.number().int().min(5242880).default(5242880).describe("Size of each chunk in bytes (minimum 5MB per S3 spec)"), - scope: external_exports.string().default("user").describe("Target storage scope"), - bucket: external_exports.string().optional().describe("Specific bucket override (admin only)"), - metadata: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom metadata key-value pairs") -}); -var InitiateChunkedUploadResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - uploadId: external_exports.string().describe("Multipart upload session ID"), - resumeToken: external_exports.string().describe("Opaque token for resuming interrupted uploads"), - fileId: external_exports.string().describe("Assigned file ID"), - totalChunks: external_exports.number().int().min(1).describe("Expected number of chunks"), - chunkSize: external_exports.number().int().describe("Chunk size in bytes"), - expiresAt: external_exports.string().datetime().describe("Upload session expiration timestamp") - }) -}); -var UploadChunkRequestSchema = external_exports.object({ - uploadId: external_exports.string().describe("Multipart upload session ID"), - chunkIndex: external_exports.number().int().min(0).describe("Zero-based chunk index"), - resumeToken: external_exports.string().describe("Resume token from initiate response") -}); -var UploadChunkResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - chunkIndex: external_exports.number().int().describe("Chunk index that was uploaded"), - eTag: external_exports.string().describe("Chunk ETag for multipart completion"), - bytesReceived: external_exports.number().int().describe("Bytes received for this chunk") - }) -}); -var CompleteChunkedUploadRequestSchema = external_exports.object({ - uploadId: external_exports.string().describe("Multipart upload session ID"), - parts: external_exports.array(external_exports.object({ - chunkIndex: external_exports.number().int().describe("Chunk index"), - eTag: external_exports.string().describe("ETag returned from chunk upload") - })).min(1).describe("Ordered list of uploaded parts for assembly") -}); -var CompleteChunkedUploadResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - fileId: external_exports.string().describe("Final file ID"), - key: external_exports.string().describe("Storage key/path of the assembled file"), - size: external_exports.number().int().describe("Total file size in bytes"), - mimeType: external_exports.string().describe("File MIME type"), - eTag: external_exports.string().optional().describe("Final ETag of the assembled file"), - url: external_exports.string().optional().describe("Download URL for the assembled file") - }) -}); -var UploadProgressSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - uploadId: external_exports.string().describe("Multipart upload session ID"), - fileId: external_exports.string().describe("Assigned file ID"), - filename: external_exports.string().describe("Original filename"), - totalSize: external_exports.number().int().describe("Total file size in bytes"), - uploadedSize: external_exports.number().int().describe("Bytes uploaded so far"), - totalChunks: external_exports.number().int().describe("Total expected chunks"), - uploadedChunks: external_exports.number().int().describe("Number of chunks uploaded"), - percentComplete: external_exports.number().min(0).max(100).describe("Upload progress percentage"), - status: external_exports.enum(["in_progress", "completing", "completed", "failed", "expired"]).describe("Current upload session status"), - startedAt: external_exports.string().datetime().describe("Upload session start timestamp"), - expiresAt: external_exports.string().datetime().describe("Session expiration timestamp") - }) -}); -var EncryptionAlgorithmSchema2 = external_exports.enum([ - "aes-256-gcm", - "aes-256-cbc", - "chacha20-poly1305" -]).describe("Supported encryption algorithm"); -var KeyManagementProviderSchema2 = external_exports.enum([ - "local", - "aws-kms", - "azure-key-vault", - "gcp-kms", - "hashicorp-vault" -]).describe("Key management service provider"); -var KeyRotationPolicySchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), - frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), - retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), - autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") -}).describe("Policy for automatic encryption key rotation"); -var EncryptionConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), - algorithm: EncryptionAlgorithmSchema2.default("aes-256-gcm").describe("Encryption algorithm"), - keyManagement: external_exports.object({ - provider: KeyManagementProviderSchema2.describe("Key management service provider"), - keyId: external_exports.string().optional().describe("Key identifier in the provider"), - rotationPolicy: KeyRotationPolicySchema2.optional().describe("Key rotation policy") - }).describe("Key management configuration"), - scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), - deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), - searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") -}).describe("Field-level encryption configuration"); -external_exports.object({ - fieldName: external_exports.string().describe("Name of the field to encrypt"), - encryptionConfig: EncryptionConfigSchema2.describe("Encryption settings for this field"), - indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") -}).describe("Per-field encryption assignment"); -var MaskingStrategySchema2 = external_exports.enum([ - "redact", - // Complete redaction: **** - "partial", - // Partial masking: 138****5678 - "hash", - // Hash value: sha256(value) - "tokenize", - // Tokenization: token-12345 - "randomize", - // Randomize: generate random value - "nullify", - // Null value: null - "substitute" - // Substitute with dummy data -]).describe("Data masking strategy for PII protection"); -var MaskingRuleSchema2 = external_exports.object({ - field: external_exports.string().describe("Field name to apply masking to"), - strategy: MaskingStrategySchema2.describe("Masking strategy to use"), - pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), - preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), - preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), - roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), - exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") -}).describe("Masking rule for a single field"); -external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable data masking"), - rules: external_exports.array(MaskingRuleSchema2).describe("List of field-level masking rules"), - auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") -}).describe("Top-level data masking configuration for PII protection"); -var FieldType2 = external_exports.enum([ - // Core Text - "text", - "textarea", - "email", - "url", - "phone", - "password", - // Rich Content - "markdown", - "html", - "richtext", - // Numbers - "number", - "currency", - "percent", - // Date & Time - "date", - "datetime", - "time", - // Logic - "boolean", - "toggle", - // Toggle is a distinct UI from checkbox - // Selection - "select", - // Single select dropdown - "multiselect", - // Multi select (often tags) - "radio", - // Radio group - "checkboxes", - // Checkbox group - // Relational - "lookup", - "master_detail", - // Dynamic reference - "tree", - // Hierarchical reference - // Media - "image", - "file", - "avatar", - "video", - "audio", - // Calculated / System - "formula", - "summary", - "autonumber", - // Enhanced Types - "location", - // GPS coordinates - "address", - // Structured address - "code", - // Code editor (JSON/SQL/JS) - "json", - // Structured JSON data - "color", - // Color picker - "rating", - // Star rating - "slider", - // Numeric slider - "signature", - // Digital signature - "qrcode", - // QR code / Barcode - "progress", - // Progress bar - "tags", - // Simple tag list - // AI/ML Types - "vector" - // Vector embeddings for AI/ML (semantic search, RAG) -]); -var SelectOptionSchema2 = external_exports.object({ - label: external_exports.string().describe("Display label (human-readable, any case allowed)"), - value: SystemIdentifierSchema2.describe("Stored value (lowercase machine identifier)"), - color: external_exports.string().optional().describe("Color code for badges/charts"), - default: external_exports.boolean().optional().describe("Is default option") -}); -external_exports.object({ - latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), - longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), - altitude: external_exports.number().optional().describe("Altitude in meters"), - accuracy: external_exports.number().optional().describe("Accuracy in meters") -}); -var CurrencyConfigSchema2 = external_exports.object({ - precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), - currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), - defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") -}); -external_exports.object({ - value: external_exports.number().describe("Monetary amount"), - currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") -}); -external_exports.object({ - street: external_exports.string().optional().describe("Street address"), - city: external_exports.string().optional().describe("City name"), - state: external_exports.string().optional().describe("State/Province"), - postalCode: external_exports.string().optional().describe("Postal/ZIP code"), - country: external_exports.string().optional().describe("Country name or code"), - countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), - formatted: external_exports.string().optional().describe("Formatted address string") -}); -var VectorConfigSchema2 = external_exports.object({ - dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), - distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), - normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), - indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), - indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") -}); -var FileAttachmentConfigSchema2 = external_exports.object({ - /** File Size Limits */ - minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), - maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), - /** File Type Restrictions */ - allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), - blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), - allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), - blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), - /** Virus Scanning */ - virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), - virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), - virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), - quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), - /** Storage Configuration */ - storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), - storageBucket: external_exports.string().optional().describe("Target bucket name"), - storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), - /** Image-Specific Validation */ - imageValidation: external_exports.object({ - minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), - maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), - minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), - maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), - aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), - generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), - thumbnailSizes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), - width: external_exports.number().min(1).describe("Thumbnail width in pixels"), - height: external_exports.number().min(1).describe("Thumbnail height in pixels"), - crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") - })).optional().describe("Thumbnail size configurations"), - preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), - autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") - }).optional().describe("Image-specific validation rules"), - /** Upload Behavior */ - allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), - allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), - allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), - requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), - /** Metadata Extraction */ - extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), - extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), - /** Versioning */ - versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), - maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), - /** Access Control */ - publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), - presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") -}).refine((data) => { - if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { - return false; - } - return true; -}, { - message: "minSize must be less than or equal to maxSize" -}).refine((data) => { - if (data.virusScanProvider !== void 0 && data.virusScan !== true) { - return false; - } - return true; -}, { - message: "virusScanProvider requires virusScan to be enabled" -}); -var DataQualityRulesSchema2 = external_exports.object({ - /** Enforce uniqueness constraint */ - uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), - /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ - completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), - /** Accuracy validation against authoritative source */ - accuracy: external_exports.object({ - source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), - threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") - }).optional().describe("Accuracy validation configuration") -}); -var ComputedFieldCacheSchema2 = external_exports.object({ - /** Enable caching for this computed field */ - enabled: external_exports.boolean().describe("Enable caching for computed field results"), - /** Time-to-live in seconds */ - ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), - /** Array of field paths that trigger cache invalidation when changed */ - invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') -}); -var FieldSchema2 = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), - label: external_exports.string().optional().describe("Human readable label"), - type: FieldType2.describe("Field Data Type"), - description: external_exports.string().optional().describe("Tooltip/Help text"), - format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), - /** Storage Layer Mapping */ - columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), - /** Database Constraints */ - required: external_exports.boolean().default(false).describe("Is required"), - searchable: external_exports.boolean().default(false).describe("Is searchable"), - multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), - unique: external_exports.boolean().default(false).describe("Is unique constraint"), - defaultValue: external_exports.unknown().optional().describe("Default value"), - /** Text/String Constraints */ - maxLength: external_exports.number().optional().describe("Max character length"), - minLength: external_exports.number().optional().describe("Min character length"), - /** Number Constraints */ - precision: external_exports.number().optional().describe("Total digits"), - scale: external_exports.number().optional().describe("Decimal places"), - min: external_exports.number().optional().describe("Minimum value"), - max: external_exports.number().optional().describe("Maximum value"), - /** Selection Options */ - options: external_exports.array(SelectOptionSchema2).optional().describe("Static options for select/multiselect"), - /** - * Relationship Config - * - * Used by `lookup` and `master_detail` field types to define cross-object references. - * The `reference` property is **required** for these types — it identifies the target - * object whose records this field links to. The engine uses `reference` during $expand - * post-processing to resolve foreign key IDs into full related objects via batch queries. - * - * For `master_detail` fields, the parent record controls the lifecycle of child records - * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. - */ - reference: external_exports.string().optional().describe( - "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." - ), - referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), - writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), - deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), - /** Calculation */ - expression: external_exports.string().optional().describe("Formula expression"), - summaryOperations: external_exports.object({ - object: external_exports.string().describe("Source child object name for roll-up"), - field: external_exports.string().describe("Field on child object to aggregate"), - function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") - }).optional().describe("Roll-up summary definition"), - /** Enhanced Field Type Configurations */ - // Code field config - language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), - theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), - lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), - // Rating field config - maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), - allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), - // Location field config - displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), - allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), - // Address field config - addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), - // Color field config - colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), - allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), - presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), - // Slider field config - step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), - showValue: external_exports.boolean().optional().describe("Display current value on slider"), - marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), - // QR Code / Barcode field config - // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' - // Runtime validation should enforce this constraint - barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), - qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), - displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), - allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), - // Currency field config - currencyConfig: CurrencyConfigSchema2.optional().describe("Configuration for currency field type"), - // Vector field config - vectorConfig: VectorConfigSchema2.optional().describe("Configuration for vector field type (AI/ML embeddings)"), - // File attachment field config - fileAttachmentConfig: FileAttachmentConfigSchema2.optional().describe("Configuration for file and attachment field types"), - /** Enhanced Security & Compliance */ - // Encryption configuration - encryptionConfig: EncryptionConfigSchema2.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), - // Data masking rules - maskingRule: MaskingRuleSchema2.optional().describe("Data masking rules for PII protection"), - // Audit trail - auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), - /** Field Dependencies & Relationships */ - // Field dependencies - dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), - /** Computed Field Optimization */ - // Computed field caching - cached: ComputedFieldCacheSchema2.optional().describe("Caching configuration for computed/formula fields"), - /** Data Quality & Governance */ - // Data quality rules - dataQuality: DataQualityRulesSchema2.optional().describe("Data quality validation and monitoring rules"), - /** Layout & Grouping */ - group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), - /** Conditional Requirements */ - conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), - /** Security & Visibility */ - hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), - readonly: external_exports.boolean().default(false).describe("Read-only in UI"), - sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), - inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), - trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), - caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), - autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), - /** Indexing */ - index: external_exports.boolean().default(false).describe("Create standard database index"), - externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") -}); -var BaseValidationSchema2 = external_exports.object({ - // Identification - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label for the rule listing"), - description: external_exports.string().optional().describe("Administrative notes explaining the business reason"), - // Execution Control - active: external_exports.boolean().default(true), - events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).default(["insert", "update"]).describe("Validation contexts"), - priority: external_exports.number().int().min(0).max(9999).default(100).describe("Execution priority (lower runs first, default: 100)"), - // Classification - tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g., "compliance", "billing")'), - // Feedback - severity: external_exports.enum(["error", "warning", "info"]).default("error"), - message: external_exports.string().describe("Error message to display to the user") -}); -var ScriptValidationSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("script"), - condition: external_exports.string().describe("Formula expression. If TRUE, validation fails. (e.g. amount < 0)") -}); -var UniquenessValidationSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("unique"), - fields: external_exports.array(external_exports.string()).describe("Fields that must be combined unique"), - scope: external_exports.string().optional().describe("Formula condition for scope (e.g. active = true)"), - caseSensitive: external_exports.boolean().default(true) -}); -var StateMachineValidationSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("state_machine"), - field: external_exports.string().describe("State field (e.g. status)"), - transitions: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).describe("Map of { OldState: [AllowedNewStates] }") -}); -var FormatValidationSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("format"), - field: external_exports.string(), - regex: external_exports.string().optional(), - format: external_exports.enum(["email", "url", "phone", "json"]).optional() -}); -var CrossFieldValidationSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("cross_field"), - condition: external_exports.string().describe('Formula expression comparing fields (e.g. "end_date > start_date")'), - fields: external_exports.array(external_exports.string()).describe("Fields involved in the validation") -}); -var JSONValidationSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("json_schema"), - field: external_exports.string().describe("JSON field to validate"), - schema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema object definition") -}); -var AsyncValidationSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("async"), - field: external_exports.string().describe("Field to validate"), - validatorUrl: external_exports.string().optional().describe("External API endpoint for validation"), - method: external_exports.enum(["GET", "POST"]).default("GET").describe("HTTP method for external call"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for the request"), - validatorFunction: external_exports.string().optional().describe("Reference to custom validator function"), - timeout: external_exports.number().optional().default(5e3).describe("Timeout in milliseconds"), - debounce: external_exports.number().optional().describe("Debounce delay in milliseconds"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional parameters to pass to validator") -}); -var CustomValidatorSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("custom"), - handler: external_exports.string().describe("Name of the custom validation function registered in the system"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the custom handler") -}); -var ValidationRuleSchema2 = external_exports.lazy( - () => external_exports.discriminatedUnion("type", [ - ScriptValidationSchema2, - UniquenessValidationSchema2, - StateMachineValidationSchema2, - FormatValidationSchema2, - CrossFieldValidationSchema2, - JSONValidationSchema2, - AsyncValidationSchema2, - CustomValidatorSchema2, - ConditionalValidationSchema2 - ]) -); -var ConditionalValidationSchema2 = BaseValidationSchema2.extend({ - type: external_exports.literal("conditional"), - when: external_exports.string().describe(`Condition formula (e.g. "type = 'enterprise'")`), - then: ValidationRuleSchema2.describe("Validation rule to apply when condition is true"), - otherwise: ValidationRuleSchema2.optional().describe("Validation rule to apply when condition is false") -}); -var ActionRefSchema2 = external_exports.union([ - external_exports.string().describe("Action Name"), - external_exports.object({ - type: external_exports.string(), - // e.g., 'xstate.assign', 'log', 'email' - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }) -]); -var GuardRefSchema2 = external_exports.union([ - external_exports.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'), - external_exports.object({ - type: external_exports.string(), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }) -]); -var TransitionSchema2 = external_exports.object({ - target: external_exports.string().optional().describe("Target State ID"), - cond: GuardRefSchema2.optional().describe("Condition (Guard) required to take this path"), - actions: external_exports.array(ActionRefSchema2).optional().describe("Actions to execute during transition"), - description: external_exports.string().optional().describe("Human readable description of this rule") -}); -external_exports.object({ - type: external_exports.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'), - // Payload validation schema could go here if we want deep validation - schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Expected event payload structure") -}); -var StateNodeSchema2 = external_exports.lazy(() => external_exports.object({ - /** Type of state */ - type: external_exports.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"), - /** Entry/Exit Actions */ - entry: external_exports.array(ActionRefSchema2).optional().describe("Actions to run when entering this state"), - exit: external_exports.array(ActionRefSchema2).optional().describe("Actions to run when leaving this state"), - /** Transitions (Events) */ - on: external_exports.record(external_exports.string(), external_exports.union([ - external_exports.string(), - // Shorthand target - TransitionSchema2, - external_exports.array(TransitionSchema2) - ])).optional().describe("Map of Event Type -> Transition Definition"), - /** Always Transitions (Eventless) */ - always: external_exports.array(TransitionSchema2).optional(), - /** Nesting (Hierarchical States) */ - initial: external_exports.string().optional().describe("Initial child state (if compound)"), - states: external_exports.record(external_exports.string(), StateNodeSchema2).optional(), - /** Metadata for UI/AI */ - meta: external_exports.object({ - label: external_exports.string().optional(), - description: external_exports.string().optional(), - color: external_exports.string().optional(), - // For UI diagrams - // Instructions for AI Agent when in this state - aiInstructions: external_exports.string().optional().describe("Specific instructions for AI when in this state") - }).optional() -})); -var StateMachineSchema2 = external_exports.object({ - id: SnakeCaseIdentifierSchema2.describe("Unique Machine ID"), - description: external_exports.string().optional(), - /** Context (Memory) Schema */ - contextSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Zod Schema for the machine context/memory"), - /** Initial State */ - initial: external_exports.string().describe("Initial State ID"), - /** State Definitions */ - states: external_exports.record(external_exports.string(), StateNodeSchema2).describe("State Nodes"), - /** Global Listeners */ - on: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), TransitionSchema2, external_exports.array(TransitionSchema2)])).optional() -}); -var ActionParamSchema2 = external_exports.object({ - name: external_exports.string(), - label: I18nLabelSchema2, - type: FieldType2, - required: external_exports.boolean().default(false), - options: external_exports.array(external_exports.object({ label: I18nLabelSchema2, value: external_exports.string() })).optional() -}); -var ActionType2 = external_exports.enum(["script", "url", "modal", "flow", "api"]); -var TARGET_REQUIRED_TYPES2 = new Set( - ActionType2.options.filter((t) => t !== "script") -); -var ActionSchema2 = external_exports.object({ - /** Machine name of the action */ - name: SnakeCaseIdentifierSchema2.describe("Machine name (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema2.describe("Display label"), - /** Target object this action belongs to (optional, snake_case) */ - objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Icon name"), - /** Where does this action appear? */ - locations: external_exports.array(external_exports.enum([ - "list_toolbar", - "list_item", - "record_header", - "record_more", - "record_related", - "global_nav" - ])).optional().describe("Locations where this action is visible"), - /** - * Visual Component Type - * Defaults to 'button' or 'menu_item' based on location, - * but can be overridden. - */ - component: external_exports.enum([ - "action:button", - // Standard Button - "action:icon", - // Icon only - "action:menu", - // Dropdown menu - "action:group" - // Button Group - ]).optional().describe("Visual component override"), - /** What type of interaction? */ - type: ActionType2.default("script").describe("Action functionality type"), - /** - * Payload / Target — the canonical binding for the action handler. - * Required for url, flow, modal, and api types. - * Recommended for script type. - */ - target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), - /** - * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. - */ - execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), - /** User Input Requirements */ - params: external_exports.array(ActionParamSchema2).optional().describe("Input parameters required from user"), - /** Visual Style */ - variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), - /** UX Behavior */ - confirmText: I18nLabelSchema2.optional().describe("Confirmation message before execution"), - successMessage: I18nLabelSchema2.optional().describe("Success message to show after execution"), - refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), - /** Access */ - visible: external_exports.string().optional().describe("Formula returning boolean"), - disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), - /** Keyboard Shortcut */ - shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), - /** Bulk Operations */ - bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), - /** Execution */ - timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema2.optional().describe("ARIA accessibility attributes") -}).transform((data) => { - if (data.execute && !data.target) { - return { ...data, target: data.execute }; - } - return data; -}).refine((data) => { - if (TARGET_REQUIRED_TYPES2.has(data.type) && !data.target) { - return false; - } - return true; -}, { - message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", - path: ["target"] -}); -var ApiMethod2 = external_exports.enum([ - "get", - "list", - // Read - "create", - "update", - "delete", - // Write - "upsert", - // Idempotent Write - "bulk", - // Batch operations - "aggregate", - // Analytics (count, sum) - "history", - // Audit access - "search", - // Search access - "restore", - "purge", - // Trash management - "import", - "export" - // Data portability -]); -var ObjectCapabilities2 = external_exports.object({ - /** Enable history tracking (Audit Trail) */ - trackHistory: external_exports.boolean().default(false).describe("Enable field history tracking for audit compliance"), - /** Enable global search indexing */ - searchable: external_exports.boolean().default(true).describe("Index records for global search"), - /** Enable REST/GraphQL API access */ - apiEnabled: external_exports.boolean().default(true).describe("Expose object via automatic APIs"), - /** - * API Supported Operations - * Granular control over API exposure. - */ - apiMethods: external_exports.array(ApiMethod2).optional().describe("Whitelist of allowed API operations"), - /** Enable standard attachments/files engine */ - files: external_exports.boolean().default(false).describe("Enable file attachments and document management"), - /** Enable social collaboration (Comments, Mentions, Feeds) */ - feeds: external_exports.boolean().default(false).describe("Enable social feed, comments, and mentions (Chatter-like)"), - /** Enable standard Activity suite (Tasks, Calendars, Events) */ - activities: external_exports.boolean().default(false).describe("Enable standard tasks and events tracking"), - /** Enable Recycle Bin / Soft Delete */ - trash: external_exports.boolean().default(true).describe("Enable soft-delete with restore capability"), - /** Enable "Recently Viewed" tracking */ - mru: external_exports.boolean().default(true).describe("Track Most Recently Used (MRU) list for users"), - /** Allow cloning records */ - clone: external_exports.boolean().default(true).describe("Allow record deep cloning") -}); -var IndexSchema2 = external_exports.object({ - name: external_exports.string().optional().describe("Index name (auto-generated if not provided)"), - fields: external_exports.array(external_exports.string()).describe("Fields included in the index"), - type: external_exports.enum(["btree", "hash", "gin", "gist", "fulltext"]).optional().default("btree").describe("Index algorithm type"), - unique: external_exports.boolean().optional().default(false).describe("Whether the index enforces uniqueness"), - partial: external_exports.string().optional().describe("Partial index condition (SQL WHERE clause for conditional indexes)") -}); -var SearchConfigSchema3 = external_exports.object({ - fields: external_exports.array(external_exports.string()).describe("Fields to index for full-text search weighting"), - displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display in search result cards"), - filters: external_exports.array(external_exports.string()).optional().describe("Default filters for search results") -}); -var TenancyConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable multi-tenancy for this object"), - strategy: external_exports.enum(["shared", "isolated", "hybrid"]).describe("Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)"), - tenantField: external_exports.string().default("tenant_id").describe("Field name for tenant identifier"), - crossTenantAccess: external_exports.boolean().default(false).describe("Allow cross-tenant data access (with explicit permission)") -}); -var SoftDeleteConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable soft delete (trash/recycle bin)"), - field: external_exports.string().default("deleted_at").describe("Field name for soft delete timestamp"), - cascadeDelete: external_exports.boolean().default(false).describe("Cascade soft delete to related records") -}); -var VersioningConfigSchema22 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable record versioning"), - strategy: external_exports.enum(["snapshot", "delta", "event-sourcing"]).describe("Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)"), - retentionDays: external_exports.number().min(1).optional().describe("Number of days to retain old versions (undefined = infinite)"), - versionField: external_exports.string().default("version").describe("Field name for version number/timestamp") -}); -var PartitioningConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable table partitioning"), - strategy: external_exports.enum(["range", "hash", "list"]).describe("Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)"), - key: external_exports.string().describe("Field name to partition by"), - interval: external_exports.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")') -}).refine((data) => { - if (data.strategy === "range" && !data.interval) { - return false; - } - return true; -}, { - message: 'interval is required when strategy is "range"' -}); -var CDCConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable Change Data Capture"), - events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).describe("Event types to capture"), - destination: external_exports.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")') -}); -var ObjectSchemaBase2 = external_exports.object({ - /** - * Identity & Metadata - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine unique key (snake_case). Immutable."), - label: external_exports.string().optional().describe('Human readable singular label (e.g. "Account")'), - pluralLabel: external_exports.string().optional().describe('Human readable plural label (e.g. "Accounts")'), - description: external_exports.string().optional().describe("Developer documentation / description"), - icon: external_exports.string().optional().describe("Icon name (Lucide/Material) for UI representation"), - /** - * Namespace & Domain Classification - * - * Groups objects into logical domains for routing, permissions, and discovery. - * System objects use `'sys'`; business packages use their own namespace. - * - * When set, `tableName` is auto-derived as `{namespace}_{name}` by - * `ObjectSchema.create()` unless an explicit `tableName` is provided. - * - * Namespace must be a single lowercase word (no underscores or hyphens) - * to ensure clean auto-derivation of `{namespace}_{name}` table names. - * - * @example namespace: 'sys' → tableName defaults to 'sys_user' - * @example namespace: 'crm' → tableName defaults to 'crm_account' - */ - namespace: external_exports.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace \u2014 single lowercase word (e.g. "sys", "crm"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'), - /** - * Taxonomy & Organization - */ - tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'), - active: external_exports.boolean().optional().default(true).describe("Is the object active and usable"), - isSystem: external_exports.boolean().optional().default(false).describe("Is system object (protected from deletion)"), - abstract: external_exports.boolean().optional().default(false).describe("Is abstract base object (cannot be instantiated)"), - /** - * Storage & Virtualization - */ - datasource: external_exports.string().optional().default("default").describe('Target Datasource ID. "default" is the primary DB.'), - tableName: external_exports.string().optional().describe("Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set."), - /** - * Data Model - */ - fields: external_exports.record(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/, { - message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")' - }), FieldSchema2).describe("Field definitions map. Keys must be snake_case identifiers."), - indexes: external_exports.array(IndexSchema2).optional().describe("Database performance indexes"), - /** - * Advanced Data Management - */ - // Multi-tenancy configuration - tenancy: TenancyConfigSchema2.optional().describe("Multi-tenancy configuration for SaaS applications"), - // Soft delete configuration - softDelete: SoftDeleteConfigSchema2.optional().describe("Soft delete (trash/recycle bin) configuration"), - // Versioning configuration - versioning: VersioningConfigSchema22.optional().describe("Record versioning and history tracking configuration"), - // Partitioning strategy - partitioning: PartitioningConfigSchema2.optional().describe("Table partitioning configuration for performance"), - // Change Data Capture - cdc: CDCConfigSchema2.optional().describe("Change Data Capture (CDC) configuration for real-time data streaming"), - /** - * Logic & Validation (Co-located) - * Best Practice: Define rules close to data. - */ - validations: external_exports.array(ValidationRuleSchema2).optional().describe("Object-level validation rules"), - /** - * State Machine(s) - * Named record of state machines, where each key is a unique machine identifier. - * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status). - * - * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} } - */ - stateMachines: external_exports.record(external_exports.string(), StateMachineSchema2).optional().describe("Named state machines for parallel lifecycles (e.g., status, payment, approval)"), - /** - * Display & UI Hints (Data-Layer) - */ - displayNameField: external_exports.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'), - recordName: external_exports.object({ - type: external_exports.enum(["text", "autonumber"]).describe("Record name type: text (user-entered) or autonumber (system-generated)"), - displayFormat: external_exports.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'), - startNumber: external_exports.number().int().min(0).optional().describe("Starting number for autonumber (default: 1)") - }).optional().describe("Record name generation configuration (Salesforce pattern)"), - titleFormat: external_exports.string().optional().describe('Title expression (e.g. "{name} - {code}"). Overrides displayNameField.'), - compactLayout: external_exports.array(external_exports.string()).optional().describe("Primary fields for hover/cards/lookups"), - /** - * Search Engine Config - */ - search: SearchConfigSchema3.optional().describe("Search engine configuration"), - /** - * System Capabilities - */ - enable: ObjectCapabilities2.optional().describe("Enabled system features modules"), - /** Record Types */ - recordTypes: external_exports.array(external_exports.string()).optional().describe("Record type names for this object"), - /** Sharing Model */ - sharingModel: external_exports.enum(["private", "read", "read_write", "full"]).optional().describe("Default sharing model"), - /** Key Prefix */ - keyPrefix: external_exports.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'), - /** - * Object Actions - * - * Actions associated with this object. Populated automatically by `defineStack()` - * when top-level actions specify `objectName` matching this object. - * Can also be defined directly on the object. - * - * Aligns with Salesforce/ServiceNow patterns where actions are part of the - * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`) - * include the action list without requiring downstream merge. - */ - actions: external_exports.array(ActionSchema2).optional().describe("Actions associated with this object (auto-populated from top-level actions via objectName)") -}); -function snakeCaseToLabel2(name) { - return name.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); -} -var ObjectSchema2 = Object.assign(ObjectSchemaBase2, { - /** - * Type-safe factory for creating business object definitions. - * - * Enhancements over raw schema: - * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case). - * - **Validation**: Runs Zod `.parse()` to validate the config at creation time. - * - * @example - * ```ts - * const Task = ObjectSchema.create({ - * name: 'project_task', - * // label auto-generated as 'Project Task' - * fields: { - * subject: { type: 'text', label: 'Subject', required: true }, - * }, - * }); - * ``` - */ - create: (config4) => { - const withDefaults = { - ...config4, - label: config4.label ?? snakeCaseToLabel2(config4.name), - // Auto-derive tableName as {namespace}_{name} when namespace is set - tableName: config4.tableName ?? (config4.namespace ? `${config4.namespace}_${config4.name}` : void 0) - }; - return ObjectSchemaBase2.parse(withDefaults); - } -}); -external_exports.enum(["own", "extend"]); -external_exports.object({ - /** The target object name (FQN) to extend */ - extend: external_exports.string().describe("Target object name (FQN) to extend"), - /** Fields to merge into the target object (additive) */ - fields: external_exports.record(external_exports.string(), FieldSchema2).optional().describe("Fields to add/override"), - /** Override label */ - label: external_exports.string().optional().describe("Override label for the extended object"), - /** Override plural label */ - pluralLabel: external_exports.string().optional().describe("Override plural label for the extended object"), - /** Override description */ - description: external_exports.string().optional().describe("Override description for the extended object"), - /** Additional validation rules to add */ - validations: external_exports.array(ValidationRuleSchema2).optional().describe("Additional validation rules to merge into the target object"), - /** Additional indexes to add */ - indexes: external_exports.array(IndexSchema2).optional().describe("Additional indexes to merge into the target object"), - /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ - priority: external_exports.number().int().min(0).max(999).default(200).describe("Merge priority (higher = applied later)") -}); -var BaseNavItemSchema = external_exports.object({ - /** Unique identifier for the item */ - id: SnakeCaseIdentifierSchema2.describe("Unique identifier for this navigation item (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema2.describe("Display proper label"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Icon name"), - /** Sort order within the same level (lower numbers appear first) */ - order: external_exports.number().optional().describe("Sort order within the same level (lower = first)"), - /** Badge text or count displayed on the navigation item (e.g. "3", "New") */ - badge: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("Badge text or count displayed on the item"), - /** - * Visibility condition. - * Formula expression returning boolean. - * e.g. "user.is_admin || user.department == 'sales'" - */ - visible: external_exports.string().optional().describe("Visibility formula condition"), - /** Permissions required to see/access this navigation item */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this item") -}); -var ObjectNavItemSchema = BaseNavItemSchema.extend({ - type: external_exports.literal("object"), - objectName: external_exports.string().describe("Target object name"), - viewName: external_exports.string().optional().describe('Default list view to open. Defaults to "all"') -}); -var DashboardNavItemSchema = BaseNavItemSchema.extend({ - type: external_exports.literal("dashboard"), - dashboardName: external_exports.string().describe("Target dashboard name") -}); -var PageNavItemSchema = BaseNavItemSchema.extend({ - type: external_exports.literal("page"), - pageName: external_exports.string().describe("Target custom page component name"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the page context") -}); -var UrlNavItemSchema = BaseNavItemSchema.extend({ - type: external_exports.literal("url"), - url: external_exports.string().describe("Target external URL"), - target: external_exports.enum(["_self", "_blank"]).default("_self").describe("Link target window") -}); -var ReportNavItemSchema = BaseNavItemSchema.extend({ - type: external_exports.literal("report"), - reportName: external_exports.string().describe("Target report name") -}); -var ActionNavItemSchema = BaseNavItemSchema.extend({ - type: external_exports.literal("action"), - actionDef: external_exports.object({ - actionName: external_exports.string().describe("Action machine name to execute"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the action") - }).describe("Action definition to execute when clicked") -}); -var GroupNavItemSchema = BaseNavItemSchema.extend({ - type: external_exports.literal("group"), - expanded: external_exports.boolean().default(false).describe("Default expansion state in sidebar") - // children property is added in the recursive definition below -}); -var NavigationItemSchema = external_exports.lazy( - () => external_exports.union([ - ObjectNavItemSchema.extend({ - children: external_exports.array(NavigationItemSchema).optional().describe("Child navigation items (e.g. specific views)") - }), - DashboardNavItemSchema, - PageNavItemSchema, - UrlNavItemSchema, - ReportNavItemSchema, - ActionNavItemSchema, - GroupNavItemSchema.extend({ - children: external_exports.array(NavigationItemSchema).describe("Child navigation items") - }) - ]) -); -var AppBrandingSchema = external_exports.object({ - primaryColor: external_exports.string().optional().describe("Primary theme color hex code"), - logo: external_exports.string().optional().describe("Custom logo URL for this app"), - favicon: external_exports.string().optional().describe("Custom favicon URL for this app") -}); -var NavigationAreaSchema = external_exports.object({ - /** Unique area identifier */ - id: SnakeCaseIdentifierSchema2.describe("Unique area identifier (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema2.describe("Area display label"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Area icon name"), - /** Sort order among areas (lower = first) */ - order: external_exports.number().optional().describe("Sort order among areas (lower = first)"), - /** Area description */ - description: I18nLabelSchema2.optional().describe("Area description"), - /** - * Visibility condition. - * Formula expression returning boolean. - */ - visible: external_exports.string().optional().describe("Visibility formula condition for this area"), - /** Permissions required to access this area */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this area"), - /** Navigation items within this area */ - navigation: external_exports.array(NavigationItemSchema).describe("Navigation items within this area") -}); -var AppSchema = external_exports.object({ - /** Machine name (id) */ - name: SnakeCaseIdentifierSchema2.describe("App unique machine name (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema2.describe("App display label"), - /** App version */ - version: external_exports.string().optional().describe("App version"), - /** Description */ - description: I18nLabelSchema2.optional().describe("App description"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("App icon used in the App Launcher"), - /** Branding/Theming Configuration */ - branding: AppBrandingSchema.optional().describe("App-specific branding"), - /** Application status */ - active: external_exports.boolean().optional().default(true).describe("Whether the app is enabled"), - /** Is this the default app for new users? */ - isDefault: external_exports.boolean().optional().default(false).describe("Is default app"), - /** - * Full Navigation Tree — supports unlimited nesting depth. - * Pages are referenced by name via `type: 'page'` items. - * Groups can contain other groups for arbitrary sidebar depth. - * - * For simple apps, use `navigation` directly. - * For enterprise apps with multiple business domains, use `areas` instead. - */ - navigation: external_exports.array(NavigationItemSchema).optional().describe("Full navigation tree for the app sidebar"), - /** - * Navigation Areas — partitions navigation by business domain. - * Each area defines an independent navigation tree (e.g. Sales, Service, Settings). - * When areas are defined, they take precedence over the top-level `navigation` array. - * - * @example - * ```ts - * areas: [ - * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] }, - * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] }, - * ] - * ``` - */ - areas: external_exports.array(NavigationAreaSchema).optional().describe("Navigation areas for partitioning navigation by business domain"), - /** - * App-level Home Page Override - * ID of the navigation item to act as the landing page. - * If not set, usually defaults to the first navigation item. - */ - homePageId: external_exports.string().optional().describe("ID of the navigation item to serve as landing page"), - /** - * Access Control - * List of permissions required to access this app. - * Modern replacement for role/profile based assignment. - * Example: ["app.access.crm"] - */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this app"), - /** - * Package Components (For config file convenience) - * In a real monorepo these might be auto-discovered, but here we allow explicit registration. - */ - objects: external_exports.array(external_exports.unknown()).optional().describe("Objects belonging to this app"), - apis: external_exports.array(external_exports.unknown()).optional().describe("Custom APIs belonging to this app"), - /** Sharing configuration for public access */ - sharing: SharingConfigSchema.optional().describe("Public sharing configuration"), - /** Embed configuration for iframe embedding */ - embed: EmbedConfigSchema.optional().describe("Iframe embedding configuration"), - /** Mobile navigation mode */ - mobileNavigation: external_exports.object({ - mode: external_exports.enum(["drawer", "bottom_nav", "hamburger"]).default("drawer").describe("Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu"), - bottomNavItems: external_exports.array(external_exports.string()).optional().describe("Navigation item IDs to show in bottom nav (max 5)") - }).optional().describe("Mobile-specific navigation configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema2.optional().describe("ARIA accessibility attributes for the application") -}); -var MetadataFormatSchema2 = external_exports.enum(["json", "yaml", "typescript", "javascript"]); -var MetadataStatsSchema2 = external_exports.object({ - /** - * Size of the metadata file in bytes - */ - size: external_exports.number().int().min(0).describe("File size in bytes"), - /** - * Last modification timestamp - */ - modifiedAt: external_exports.string().datetime().describe("Last modified date"), - /** - * ETag for cache validation - * Used for conditional requests (If-None-Match header) - */ - etag: external_exports.string().describe("Entity tag for cache validation"), - /** - * Serialization format - */ - format: MetadataFormatSchema2.describe("Serialization format"), - /** - * Full file path (if applicable) - */ - path: external_exports.string().optional().describe("File system path"), - /** - * Additional metadata provider-specific properties - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific metadata") -}); -external_exports.object({ - /** - * Glob patterns to match files - * Example: ["**\/*.object.ts", "**\/*.object.json"] - */ - patterns: external_exports.array(external_exports.string()).optional().describe("File glob patterns"), - /** - * If-None-Match header for conditional loading - * Only load if ETag doesn't match - */ - ifNoneMatch: external_exports.string().optional().describe("ETag for conditional request"), - /** - * If-Modified-Since header for conditional loading - */ - ifModifiedSince: external_exports.string().datetime().optional().describe("Only load if modified after this date"), - /** - * Whether to validate against Zod schema - */ - validate: external_exports.boolean().default(true).describe("Validate against schema"), - /** - * Whether to use cache if available - */ - useCache: external_exports.boolean().default(true).describe("Enable caching"), - /** - * Filter function (serialized as string) - * Example: "(item) => item.name.startsWith('sys_')" - */ - filter: external_exports.string().optional().describe("Filter predicate as string"), - /** - * Maximum number of items to load - */ - limit: external_exports.number().int().min(1).optional().describe("Maximum items to load"), - /** - * Recursively search subdirectories - */ - recursive: external_exports.boolean().default(true).describe("Search subdirectories") -}); -external_exports.object({ - /** - * Serialization format - */ - format: MetadataFormatSchema2.default("typescript").describe("Output format"), - /** - * Prettify output (formatted with indentation) - */ - prettify: external_exports.boolean().default(true).describe("Format with indentation"), - /** - * Indentation size (spaces) - */ - indent: external_exports.number().int().min(0).max(8).default(2).describe("Indentation spaces"), - /** - * Sort object keys alphabetically - */ - sortKeys: external_exports.boolean().default(false).describe("Sort object keys"), - /** - * Include default values in output - */ - includeDefaults: external_exports.boolean().default(false).describe("Include default values"), - /** - * Create backup before overwriting - */ - backup: external_exports.boolean().default(false).describe("Create backup file"), - /** - * Overwrite if exists - */ - overwrite: external_exports.boolean().default(true).describe("Overwrite existing file"), - /** - * Atomic write (write to temp file, then rename) - */ - atomic: external_exports.boolean().default(true).describe("Use atomic write operation"), - /** - * Custom file path (overrides default location) - */ - path: external_exports.string().optional().describe("Custom output path") -}); -external_exports.object({ - /** - * Output file path - */ - output: external_exports.string().describe("Output file path"), - /** - * Export format - */ - format: MetadataFormatSchema2.default("json").describe("Export format"), - /** - * Filter predicate as string - */ - filter: external_exports.string().optional().describe("Filter items to export"), - /** - * Include statistics in export - */ - includeStats: external_exports.boolean().default(false).describe("Include metadata statistics"), - /** - * Compress output - */ - compress: external_exports.boolean().default(false).describe("Compress output (gzip)"), - /** - * Pretty print output - */ - prettify: external_exports.boolean().default(true).describe("Pretty print output") -}); -external_exports.object({ - /** - * Conflict resolution strategy - */ - conflictResolution: external_exports.enum(["skip", "overwrite", "merge", "fail"]).default("merge").describe("How to handle existing items"), - /** - * Validate items against schema - */ - validate: external_exports.boolean().default(true).describe("Validate before import"), - /** - * Dry run (don't actually save) - */ - dryRun: external_exports.boolean().default(false).describe("Simulate import without saving"), - /** - * Continue on errors - */ - continueOnError: external_exports.boolean().default(false).describe("Continue if validation fails"), - /** - * Transform function (as string) - * Example: "(item) => ({ ...item, imported: true })" - */ - transform: external_exports.string().optional().describe("Transform items before import") -}); -external_exports.object({ - /** - * Loaded data - */ - data: external_exports.unknown().nullable().describe("Loaded metadata"), - /** - * Whether data came from cache (304 Not Modified) - */ - fromCache: external_exports.boolean().default(false).describe("Loaded from cache"), - /** - * Not modified (conditional request matched) - */ - notModified: external_exports.boolean().default(false).describe("Not modified since last request"), - /** - * ETag of loaded data - */ - etag: external_exports.string().optional().describe("Entity tag"), - /** - * Statistics about loaded data - */ - stats: MetadataStatsSchema2.optional().describe("Metadata statistics"), - /** - * Load time in milliseconds - */ - loadTime: external_exports.number().min(0).optional().describe("Load duration in ms") -}); -external_exports.object({ - /** - * Whether save was successful - */ - success: external_exports.boolean().describe("Save successful"), - /** - * Path where file was saved - */ - path: external_exports.string().describe("Output path"), - /** - * Generated ETag - */ - etag: external_exports.string().optional().describe("Generated entity tag"), - /** - * File size in bytes - */ - size: external_exports.number().int().min(0).optional().describe("File size"), - /** - * Save time in milliseconds - */ - saveTime: external_exports.number().min(0).optional().describe("Save duration in ms"), - /** - * Backup path (if created) - */ - backupPath: external_exports.string().optional().describe("Backup file path") -}); -external_exports.object({ - /** - * Event type - */ - type: external_exports.enum(["added", "changed", "deleted"]).describe("Event type"), - /** - * Metadata type (e.g., 'object', 'view', 'app') - */ - metadataType: external_exports.string().describe("Type of metadata"), - /** - * Item name/identifier - */ - name: external_exports.string().describe("Item identifier"), - /** - * Full file path - */ - path: external_exports.string().describe("File path"), - /** - * Loaded item data (for added/changed events) - */ - data: external_exports.unknown().optional().describe("Item data"), - /** - * Timestamp - */ - timestamp: external_exports.string().datetime().describe("Event timestamp") -}); -external_exports.object({ - /** - * Collection type (e.g., 'object', 'view', 'app') - */ - type: external_exports.string().describe("Collection type"), - /** - * Total items in collection - */ - count: external_exports.number().int().min(0).describe("Number of items"), - /** - * Formats found in collection - */ - formats: external_exports.array(MetadataFormatSchema2).describe("Formats in collection"), - /** - * Total size in bytes - */ - totalSize: external_exports.number().int().min(0).optional().describe("Total size in bytes"), - /** - * Last modified timestamp - */ - lastModified: external_exports.string().datetime().optional().describe("Last modification date"), - /** - * Collection location (path or URL) - */ - location: external_exports.string().optional().describe("Collection location") -}); -external_exports.object({ - /** - * Loader name/identifier - */ - name: external_exports.string().describe("Loader identifier"), - /** - * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:') - */ - protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Protocol identifier"), - /** - * Detailed capabilities - */ - capabilities: external_exports.object({ - read: external_exports.boolean().default(true), - write: external_exports.boolean().default(false), - watch: external_exports.boolean().default(false), - list: external_exports.boolean().default(true) - }).describe("Loader capabilities"), - /** - * Supported formats - */ - supportedFormats: external_exports.array(MetadataFormatSchema2).describe("Supported formats"), - /** - * Whether loader supports watching for changes - */ - supportsWatch: external_exports.boolean().default(false).describe("Supports file watching"), - /** - * Whether loader supports saving - */ - supportsWrite: external_exports.boolean().default(true).describe("Supports write operations"), - /** - * Whether loader supports caching - */ - supportsCache: external_exports.boolean().default(true).describe("Supports caching") -}); -var MetadataFallbackStrategySchema2 = external_exports.enum([ - "filesystem", - // Fall back to filesystem-based loading - "memory", - // Fall back to in-memory storage - "none" - // No fallback — fail immediately -]); -var MetadataManagerConfigSchema2 = external_exports.object({ - /** - * Datasource Name Reference - * References a DatasourceSchema.name (e.g. 'default'). - * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. - */ - datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), - /** - * Metadata Table Name - * The database table used for metadata storage when datasource is configured. - */ - tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), - /** - * Fallback Strategy - * Determines behavior when the primary datasource is unavailable. - */ - fallback: MetadataFallbackStrategySchema2.default("none").describe("Fallback strategy when datasource is unavailable"), - /** - * Root directory for metadata (for filesystem loaders) - */ - rootDir: external_exports.string().optional().describe("Root directory path"), - /** - * Enabled serialization formats - */ - formats: external_exports.array(MetadataFormatSchema2).default(["typescript", "json", "yaml"]).describe("Enabled formats"), - /** - * Cache configuration - */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable caching"), - ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), - maxSize: external_exports.number().int().min(0).optional().describe("Max cache size in bytes") - }).optional().describe("Cache settings"), - /** - * Watch for file changes - */ - watch: external_exports.boolean().default(false).describe("Enable file watching"), - /** - * Watch options - */ - watchOptions: external_exports.object({ - ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), - persistent: external_exports.boolean().default(true).describe("Keep process running"), - ignoreInitial: external_exports.boolean().default(true).describe("Ignore initial add events") - }).optional().describe("File watcher options"), - /** - * Validation settings - */ - validation: external_exports.object({ - strict: external_exports.boolean().default(true).describe("Strict validation"), - throwOnError: external_exports.boolean().default(true).describe("Throw on validation error") - }).optional().describe("Validation settings"), - /** - * Loader-specific options - */ - loaderOptions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Loader-specific configuration") -}); -external_exports.enum([ - "package", - // Delivered by a plugin package (system layer, read-only) - "admin", - // Created/modified by platform admin via UI - "user", - // Created/modified by end user via UI - "migration", - // Created during data migration - "api" - // Created via API -]); -var FieldChangeSchema = external_exports.object({ - /** JSON path to the changed field (e.g. "fields.status.label") */ - path: external_exports.string().describe("JSON path to the changed field"), - /** Original value from the package (for diff/rollback) */ - originalValue: external_exports.unknown().optional().describe("Original value from the package"), - /** Current customized value */ - currentValue: external_exports.unknown().describe("Current customized value"), - /** Who made this change */ - changedBy: external_exports.string().optional().describe("User or admin who made this change"), - /** When this change was made */ - changedAt: external_exports.string().datetime().optional().describe("Timestamp of the change") -}); -var MetadataOverlaySchema = external_exports.object({ - /** Primary key */ - id: external_exports.string().describe("Overlay record ID (UUID)"), - /** The metadata type being customized (e.g. "object", "view", "flow") */ - baseType: external_exports.string().describe("Metadata type being customized"), - /** The metadata name being customized (e.g. "crm__account") */ - baseName: external_exports.string().describe("Metadata name being customized"), - /** Package that owns the base metadata (null for platform-created metadata) */ - packageId: external_exports.string().optional().describe("Package ID that delivered the base metadata"), - /** Package version when the customization was made (for upgrade diffing) */ - packageVersion: external_exports.string().optional().describe("Package version when overlay was created"), - /** Customization scope */ - scope: external_exports.enum(["platform", "user"]).default("platform").describe("Customization scope (platform=admin, user=personal)"), - /** Tenant ID for multi-tenant isolation */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** Owner user ID (for user-scope overlays) */ - owner: external_exports.string().optional().describe("Owner user ID for user-scope overlays"), - /** - * The overlay payload. - * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396). - * - To modify a field: include the field with its new value - * - To delete a field: set its value to null - * - Omitted fields remain unchanged from base - */ - patch: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Merge Patch payload (changed fields only)"), - /** - * Detailed change tracking for each modified field. - * Enables field-level conflict detection during upgrades. - */ - changes: external_exports.array(FieldChangeSchema).optional().describe("Field-level change tracking for conflict detection"), - /** Whether this overlay is currently active */ - active: external_exports.boolean().default(true).describe("Whether this overlay is active"), - /** Audit timestamps */ - createdAt: external_exports.string().datetime().optional(), - createdBy: external_exports.string().optional(), - updatedAt: external_exports.string().datetime().optional(), - updatedBy: external_exports.string().optional() -}); -var MergeConflictSchema = external_exports.object({ - /** JSON path to the conflicting field */ - path: external_exports.string().describe("JSON path to the conflicting field"), - /** Value in the old package version */ - baseValue: external_exports.unknown().describe("Value in the old package version"), - /** Value in the new package version */ - incomingValue: external_exports.unknown().describe("Value in the new package version"), - /** Customer's customized value */ - customValue: external_exports.unknown().describe("Customer customized value"), - /** Suggested resolution strategy */ - suggestedResolution: external_exports.enum([ - "keep-custom", - // Keep customer's customization - "accept-incoming", - // Accept package update - "manual" - // Requires manual resolution - ]).describe("Suggested resolution strategy"), - /** Reason for the suggested resolution */ - reason: external_exports.string().optional().describe("Explanation for the suggested resolution") -}); -var MergeStrategyConfigSchema = external_exports.object({ - /** Default strategy when no field-level rule matches */ - defaultStrategy: external_exports.enum([ - "keep-custom", - // Preserve all customer customizations (safe) - "accept-incoming", - // Accept all package updates (overwrite) - "three-way-merge" - // Intelligent 3-way merge with conflict detection - ]).default("three-way-merge").describe("Default merge strategy"), - /** - * Field paths that should always accept incoming package updates. - * Use for fields that the package vendor considers "owned" and should not be customized. - * @example ["fields.*.type", "triggers.*"] - */ - alwaysAcceptIncoming: external_exports.array(external_exports.string()).optional().describe("Field paths that always accept package updates"), - /** - * Field paths where customer customizations always win. - * Use for UI-facing fields like labels, descriptions, help text. - * @example ["fields.*.label", "fields.*.helpText", "description"] - */ - alwaysKeepCustom: external_exports.array(external_exports.string()).optional().describe("Field paths where customer customizations always win"), - /** Whether to automatically resolve non-conflicting changes */ - autoResolveNonConflicting: external_exports.boolean().default(true).describe("Auto-resolve changes that do not conflict") -}); -external_exports.object({ - /** Whether the merge completed successfully (no unresolved conflicts) */ - success: external_exports.boolean().describe("Whether merge completed without unresolved conflicts"), - /** The merged metadata payload */ - mergedMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Merged metadata result"), - /** Updated overlay with remaining customizations */ - updatedOverlay: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated overlay after merge"), - /** List of conflicts that require manual resolution */ - conflicts: external_exports.array(MergeConflictSchema).optional().describe("Unresolved merge conflicts"), - /** Summary of automatically resolved changes */ - autoResolved: external_exports.array(external_exports.object({ - path: external_exports.string(), - resolution: external_exports.string(), - description: external_exports.string().optional() - })).optional().describe("Summary of auto-resolved changes"), - /** Statistics */ - stats: external_exports.object({ - totalFields: external_exports.number().int().min(0).describe("Total fields evaluated"), - unchanged: external_exports.number().int().min(0).describe("Fields with no changes"), - autoResolved: external_exports.number().int().min(0).describe("Fields auto-resolved"), - conflicts: external_exports.number().int().min(0).describe("Fields with conflicts") - }).optional() -}); -var CustomizationPolicySchema = external_exports.object({ - /** Metadata type this policy applies to */ - metadataType: external_exports.string().describe('Metadata type (e.g. "object", "view")'), - /** Whether customization is allowed at all for this type */ - allowCustomization: external_exports.boolean().default(true), - /** - * Field paths that are locked (cannot be customized). - * @example ["name", "type", "fields.*.type"] - */ - lockedFields: external_exports.array(external_exports.string()).optional().describe("Field paths that cannot be customized"), - /** - * Field paths that are customizable. - * If specified, only these fields can be customized (whitelist mode). - * @example ["label", "description", "fields.*.label", "fields.*.helpText"] - */ - customizableFields: external_exports.array(external_exports.string()).optional().describe("Field paths that can be customized (whitelist)"), - /** - * Whether users can add new fields to package objects. - * When true, admins can extend package objects with custom fields. - */ - allowAddFields: external_exports.boolean().default(true).describe("Whether admins can add new fields to package objects"), - /** - * Whether users can delete package-delivered fields. - * Typically false — fields can only be hidden, not deleted. - */ - allowDeleteFields: external_exports.boolean().default(false).describe("Whether admins can delete package-delivered fields") -}); -var MetadataTypeSchema = external_exports.enum([ - // Data Protocol - "object", - // Business entity definition (ObjectSchema) - "field", - // Standalone field definition (FieldSchema) - "trigger", - // Data-layer event triggers (TriggerSchema) - "validation", - // Validation rules (ValidationSchema) - "hook", - // Data hooks (HookSchema) - // UI Protocol - "view", - // List/form views (ViewSchema) - "page", - // Standalone pages (PageSchema) - "dashboard", - // Dashboard layouts (DashboardSchema) - "app", - // Application shell (AppSchema) - "action", - // UI/Server actions (ActionSchema) - "report", - // Report definitions (ReportSchema) - // Automation Protocol - "flow", - // Visual logic flows (FlowSchema) - "workflow", - // State machines (WorkflowSchema) - "approval", - // Approval processes (ApprovalSchema) - // System Protocol - "datasource", - // Data connections (DatasourceSchema) - "translation", - // i18n resources (TranslationSchema) - "router", - // API routes - "function", - // Serverless functions - "service", - // Service definitions - // Security Protocol - "permission", - // Permission sets (PermissionSetSchema) - "profile", - // User profiles (ProfileSchema) - "role", - // Security roles - // AI Protocol - "agent", - // AI agent definitions (AgentSchema) - "tool", - // AI tool definitions (ToolSchema) - "skill" - // AI skill definitions (SkillSchema) -]); -var MetadataTypeRegistryEntrySchema = external_exports.object({ - /** Metadata type identifier (e.g., 'object', 'view') */ - type: MetadataTypeSchema.describe("Metadata type identifier"), - /** Human-readable label */ - label: external_exports.string().describe("Display label for the metadata type"), - /** Brief description */ - description: external_exports.string().optional().describe("Description of the metadata type"), - /** - * File glob patterns for this type. - * Used to discover metadata files on disk. - * @example ["**\/*.object.ts", "**\/*.object.yml"] - */ - filePatterns: external_exports.array(external_exports.string()).describe("Glob patterns to discover files of this type"), - /** - * Whether this type supports the customization overlay system. - * When true, platform/user overlays can be applied on top of package-delivered metadata. - */ - supportsOverlay: external_exports.boolean().default(true).describe("Whether overlay customization is supported"), - /** - * Whether metadata of this type can be created at runtime via API. - * Some types (e.g., 'object') may be restricted to deployment-only. - */ - allowRuntimeCreate: external_exports.boolean().default(true).describe("Allow runtime creation via API"), - /** - * Whether this type supports versioning. - * When true, changes are tracked with version history. - */ - supportsVersioning: external_exports.boolean().default(false).describe("Whether version history is tracked"), - /** - * Priority order for loading (lower = earlier). - * Objects load before views, views before dashboards. - */ - loadOrder: external_exports.number().int().min(0).default(100).describe("Loading priority (lower = earlier)"), - /** The domain this type belongs to */ - domain: external_exports.enum(["data", "ui", "automation", "system", "security", "ai"]).describe("Protocol domain") -}); -var MetadataQuerySchema = external_exports.object({ - /** Filter by metadata type(s) */ - types: external_exports.array(MetadataTypeSchema).optional().describe("Filter by metadata types"), - /** Filter by namespace(s) */ - namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), - /** Filter by package ID */ - packageId: external_exports.string().optional().describe("Filter by owning package"), - /** Full-text search across name, label, description */ - search: external_exports.string().optional().describe("Full-text search query"), - /** Filter by scope */ - scope: external_exports.enum(["system", "platform", "user"]).optional().describe("Filter by scope"), - /** Filter by state */ - state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional().describe("Filter by lifecycle state"), - /** Filter by tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), - /** Sort field */ - sortBy: external_exports.enum(["name", "type", "updatedAt", "createdAt"]).default("name").describe("Sort field"), - /** Sort direction */ - sortOrder: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction"), - /** Pagination: page number (1-based) */ - page: external_exports.number().int().min(1).default(1).describe("Page number"), - /** Pagination: items per page */ - pageSize: external_exports.number().int().min(1).max(500).default(50).describe("Items per page") -}); -var MetadataQueryResultSchema = external_exports.object({ - /** Matched items */ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - namespace: external_exports.string().optional().describe("Namespace"), - label: external_exports.string().optional().describe("Display label"), - scope: external_exports.enum(["system", "platform", "user"]).optional(), - state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional(), - packageId: external_exports.string().optional(), - updatedAt: external_exports.string().datetime().optional() - })).describe("Matched metadata items"), - /** Total count (for pagination) */ - total: external_exports.number().int().min(0).describe("Total matching items"), - /** Current page */ - page: external_exports.number().int().min(1).describe("Current page"), - /** Page size */ - pageSize: external_exports.number().int().min(1).describe("Page size") -}); -external_exports.object({ - /** Event type */ - event: external_exports.enum([ - "metadata.registered", - "metadata.updated", - "metadata.unregistered", - "metadata.validated", - "metadata.deployed", - "metadata.overlay.applied", - "metadata.overlay.removed", - "metadata.imported", - "metadata.exported" - ]).describe("Event type"), - /** Metadata type */ - metadataType: MetadataTypeSchema.describe("Metadata type"), - /** Item name */ - name: external_exports.string().describe("Metadata item name"), - /** Namespace */ - namespace: external_exports.string().optional().describe("Namespace"), - /** Package ID (if package-managed) */ - packageId: external_exports.string().optional().describe("Owning package ID"), - /** Timestamp */ - timestamp: external_exports.string().datetime().describe("Event timestamp"), - /** Actor who caused the event */ - actor: external_exports.string().optional().describe("User or system that triggered the event"), - /** Additional event-specific payload */ - payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific payload") -}); -var MetadataValidationResultSchema = external_exports.object({ - /** Whether validation passed */ - valid: external_exports.boolean().describe("Whether the metadata is valid"), - /** Validation errors */ - errors: external_exports.array(external_exports.object({ - path: external_exports.string().describe("JSON path to the invalid field"), - message: external_exports.string().describe("Error description"), - code: external_exports.string().optional().describe("Error code") - })).optional().describe("Validation errors"), - /** Validation warnings (non-blocking) */ - warnings: external_exports.array(external_exports.object({ - path: external_exports.string().describe("JSON path to the field"), - message: external_exports.string().describe("Warning description") - })).optional().describe("Validation warnings") -}); -var MetadataPluginConfigSchema = external_exports.object({ - /** - * Storage configuration. - * References MetadataManagerConfigSchema for the underlying storage backend. - */ - storage: MetadataManagerConfigSchema2.describe("Storage backend configuration"), - /** - * Default customization policies per metadata type. - * Controls what parts of metadata can be customized by admins/users. - */ - customizationPolicies: external_exports.array(CustomizationPolicySchema).optional().describe("Default customization policies per type"), - /** - * Merge strategy for package upgrades. - */ - mergeStrategy: MergeStrategyConfigSchema.optional().describe("Merge strategy for package upgrades"), - /** - * Additional metadata type registrations. - * Used by plugins to register custom metadata types beyond the built-in set. - */ - additionalTypes: external_exports.array(MetadataTypeRegistryEntrySchema.omit({ type: true }).extend({ - type: external_exports.string().describe("Custom metadata type identifier") - })).optional().describe("Additional custom metadata types"), - /** - * Enable metadata change events. - * When true, the plugin emits events on every metadata change. - */ - enableEvents: external_exports.boolean().default(true).describe("Emit metadata change events"), - /** - * Enable metadata validation on write operations. - * When true, all metadata is validated against its type schema before saving. - */ - validateOnWrite: external_exports.boolean().default(true).describe("Validate metadata on write"), - /** - * Enable metadata versioning. - * When true, changes to metadata are tracked with version history. - */ - enableVersioning: external_exports.boolean().default(false).describe("Track metadata version history"), - /** - * Maximum number of metadata items to keep in memory cache. - */ - cacheMaxItems: external_exports.number().int().min(0).default(1e4).describe("Max items in memory cache") -}); -external_exports.object({ - /** Plugin identifier */ - id: external_exports.literal("com.objectstack.metadata").describe("Metadata plugin ID"), - /** Plugin name */ - name: external_exports.literal("ObjectStack Metadata Service").describe("Plugin name"), - /** Plugin version */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Plugin version"), - /** Plugin type */ - type: external_exports.literal("standard").describe("Plugin type"), - /** Plugin description */ - description: external_exports.string().default("Core metadata management service for ObjectStack platform").describe("Plugin description"), - /** - * Capabilities this plugin provides. - * The kernel uses this to route metadata requests to this plugin. - */ - capabilities: external_exports.object({ - /** Supports CRUD operations on metadata */ - crud: external_exports.boolean().default(true).describe("Supports metadata CRUD"), - /** Supports metadata query/search */ - query: external_exports.boolean().default(true).describe("Supports metadata query"), - /** Supports the overlay/customization system */ - overlay: external_exports.boolean().default(true).describe("Supports customization overlays"), - /** Supports file watching for hot reload */ - watch: external_exports.boolean().default(false).describe("Supports file watching"), - /** Supports bulk import/export */ - importExport: external_exports.boolean().default(true).describe("Supports import/export"), - /** Supports metadata validation */ - validation: external_exports.boolean().default(true).describe("Supports schema validation"), - /** Supports metadata versioning */ - versioning: external_exports.boolean().default(false).describe("Supports version history"), - /** Supports metadata events */ - events: external_exports.boolean().default(true).describe("Emits metadata events") - }).describe("Plugin capabilities"), - /** Plugin configuration */ - config: MetadataPluginConfigSchema.optional().describe("Plugin configuration") -}); -external_exports.object({ - /** Items to register */ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), - namespace: external_exports.string().optional().describe("Namespace") - })).min(1).describe("Items to register"), - /** Continue on individual item failure */ - continueOnError: external_exports.boolean().default(false).describe("Continue if individual item fails"), - /** Validate items before registering */ - validate: external_exports.boolean().default(true).describe("Validate before register") -}); -var MetadataBulkResultSchema = external_exports.object({ - /** Total items processed */ - total: external_exports.number().int().min(0).describe("Total items processed"), - /** Successfully processed items */ - succeeded: external_exports.number().int().min(0).describe("Successfully processed"), - /** Failed items */ - failed: external_exports.number().int().min(0).describe("Failed items"), - /** Per-item error details */ - errors: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - error: external_exports.string().describe("Error message") - })).optional().describe("Per-item errors") -}); -var MetadataDependencySchema = external_exports.object({ - /** Source metadata type */ - sourceType: external_exports.string().describe("Dependent metadata type"), - /** Source metadata name */ - sourceName: external_exports.string().describe("Dependent metadata name"), - /** Target metadata type */ - targetType: external_exports.string().describe("Referenced metadata type"), - /** Target metadata name */ - targetName: external_exports.string().describe("Referenced metadata name"), - /** Dependency kind */ - kind: external_exports.enum(["reference", "extends", "includes", "triggers"]).describe("How the dependency is formed") -}); -var ObjectDefinitionResponseSchema = BaseResponseSchema.extend({ - data: ObjectSchema2.describe("Full Object Schema") -}); -var AppDefinitionResponseSchema = BaseResponseSchema.extend({ - data: AppSchema.describe("Full App Configuration") -}); -var ConceptListResponseSchema = BaseResponseSchema.extend({ - data: external_exports.array(external_exports.object({ - name: external_exports.string(), - label: external_exports.string(), - icon: external_exports.string().optional(), - description: external_exports.string().optional() - })).describe("List of available concepts (Objects, Apps, Flows)") -}); -var MetadataRegisterRequestSchema = external_exports.object({ - type: MetadataTypeSchema.describe("Metadata type"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Item name (snake_case)"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), - namespace: external_exports.string().optional().describe("Optional namespace") -}); -var MetadataItemResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - definition: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata definition payload") - }).describe("Metadata item") -}); -var MetadataListResponseSchema = BaseResponseSchema.extend({ - data: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Array of metadata definitions") -}); -var MetadataNamesResponseSchema = BaseResponseSchema.extend({ - data: external_exports.array(external_exports.string()).describe("Array of metadata item names") -}); -var MetadataExistsResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - exists: external_exports.boolean().describe("Whether the item exists") - }) -}); -var MetadataDeleteResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Deleted item name") - }) -}); -var MetadataQueryRequestSchema = MetadataQuerySchema.describe( - "Metadata query with filtering, sorting, and pagination" -); -var MetadataQueryResponseSchema = BaseResponseSchema.extend({ - data: MetadataQueryResultSchema.describe("Paginated query result") -}); -var MetadataBulkRegisterRequestSchema2 = external_exports.object({ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload") - })).min(1).describe("Items to register"), - continueOnError: external_exports.boolean().default(false).describe("Continue on individual failure"), - validate: external_exports.boolean().default(true).describe("Validate before registering") -}); -var MetadataBulkUnregisterRequestSchema = external_exports.object({ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name") - })).min(1).describe("Items to unregister") -}); -var MetadataBulkResponseSchema = BaseResponseSchema.extend({ - data: MetadataBulkResultSchema.describe("Bulk operation result") -}); -var MetadataOverlayResponseSchema = BaseResponseSchema.extend({ - data: MetadataOverlaySchema.optional().describe("Overlay definition, undefined if none") -}); -var MetadataOverlaySaveRequestSchema = MetadataOverlaySchema.describe( - "Overlay to save" -); -var MetadataEffectiveResponseSchema = BaseResponseSchema.extend({ - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Effective metadata with all overlays applied") -}); -var MetadataExportRequestSchema = external_exports.object({ - types: external_exports.array(external_exports.string()).optional().describe("Filter by metadata types"), - namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), - format: external_exports.enum(["json", "yaml"]).default("json").describe("Export format") -}); -var MetadataExportResponseSchema = BaseResponseSchema.extend({ - data: external_exports.unknown().describe("Exported metadata bundle") -}); -var MetadataImportRequestSchema = external_exports.object({ - data: external_exports.unknown().describe("Metadata bundle to import"), - conflictResolution: external_exports.enum(["skip", "overwrite", "merge"]).default("skip").describe("Conflict resolution strategy"), - validate: external_exports.boolean().default(true).describe("Validate before import"), - dryRun: external_exports.boolean().default(false).describe("Dry run (no save)") -}); -var MetadataImportResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - total: external_exports.number().int().min(0), - imported: external_exports.number().int().min(0), - skipped: external_exports.number().int().min(0), - failed: external_exports.number().int().min(0), - errors: external_exports.array(external_exports.object({ - type: external_exports.string(), - name: external_exports.string(), - error: external_exports.string() - })).optional() - }).describe("Import result") -}); -var MetadataValidateRequestSchema = external_exports.object({ - type: external_exports.string().describe("Metadata type to validate against"), - data: external_exports.unknown().describe("Metadata payload to validate") -}); -var MetadataValidateResponseSchema = BaseResponseSchema.extend({ - data: MetadataValidationResultSchema.describe("Validation result") -}); -var MetadataTypesResponseSchema = BaseResponseSchema.extend({ - data: external_exports.array(external_exports.string()).describe("Registered metadata type identifiers") -}); -var MetadataTypeInfoResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - type: external_exports.string().describe("Metadata type identifier"), - label: external_exports.string().describe("Display label"), - description: external_exports.string().optional().describe("Description"), - filePatterns: external_exports.array(external_exports.string()).describe("File glob patterns"), - supportsOverlay: external_exports.boolean().describe("Overlay support"), - domain: external_exports.string().describe("Protocol domain") - }).optional().describe("Type info") -}); -var MetadataDependenciesResponseSchema = BaseResponseSchema.extend({ - data: external_exports.array(MetadataDependencySchema).describe("Items this item depends on") -}); -var MetadataDependentsResponseSchema = BaseResponseSchema.extend({ - data: external_exports.array(MetadataDependencySchema).describe("Items that depend on this item") -}); -var CoreServiceName2 = external_exports.enum([ - // Core Data & Metadata - "metadata", - // Object/Field Definitions - "data", - // CRUD & Query Engine - "auth", - // Authentication & Identity - // Infrastructure - "file-storage", - // Storage Driver (Local/S3) - "search", - // Search Engine (Elastic/Meili) - "cache", - // Cache Driver (Redis/Memory) - "queue", - // Job Queue (BullMQ/Redis) - // Advanced Capabilities - "automation", - // Flow & Script Engine - "graphql", - // GraphQL API Engine - "analytics", - // BI & Semantic Layer - "realtime", - // WebSocket & PubSub - "job", - // Background Job Manager - "notification", - // Email/Push/SMS - "ai", - // AI Engine (NLQ, Chat, Suggest, Insights) - "i18n", - // Internationalization Service - "ui", - // UI Metadata Service (View CRUD) - "workflow" - // Workflow State Machine Engine -]); -var ServiceCriticalitySchema2 = external_exports.enum([ - "required", - // System fails to start if missing (Exit Code 1) - "core", - // System warns if missing, functionality degraded (Warn) - "optional" - // System ignores if missing, feature disabled (Info) -]); -external_exports.object({ - name: CoreServiceName2, - enabled: external_exports.boolean(), - status: external_exports.enum(["running", "stopped", "degraded", "initializing"]), - version: external_exports.string().optional(), - provider: external_exports.string().optional().describe('Implementation provider (e.g. "s3" for storage)'), - features: external_exports.array(external_exports.string()).optional().describe("List of supported sub-features") -}); -external_exports.record( - CoreServiceName2, - external_exports.unknown().describe("Service Instance implementing the protocol interface") -); -external_exports.object({ - id: external_exports.string(), - name: CoreServiceName2, - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var DispatcherRouteSchema = external_exports.object({ - /** - * URL path prefix for routing. - * Incoming requests matching this prefix are routed to the target service. - * Must start with '/'. - */ - prefix: external_exports.string().regex(/^\//).describe("URL path prefix for routing (e.g. /api/v1/data)"), - /** - * Target core service name. - * The service that handles requests matching this prefix. - */ - service: CoreServiceName2.describe("Target core service name"), - /** - * Whether requests to this route require authentication. - * Discovery endpoint is typically public; most others require auth. - * @default true - */ - authRequired: external_exports.boolean().default(true).describe("Whether authentication is required"), - /** - * Service criticality level. - * Determines behavior when the service is unavailable: - * - required: return 500 Internal Server Error - * - core: return 503 with degraded notice - * - optional: return 503 Service Unavailable - * @default 'optional' - */ - criticality: ServiceCriticalitySchema2.default("optional").describe("Service criticality level for unavailability handling"), - /** - * Required permissions for accessing this route namespace. - * Applied as a baseline before individual endpoint permission checks. - */ - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions for this route namespace") -}); -var DispatcherConfigSchema = external_exports.object({ - /** - * Registered route mappings. - * Routes are matched by longest-prefix-first strategy. - */ - routes: external_exports.array(DispatcherRouteSchema).describe("Route-to-service mappings"), - /** - * Behavior when no route matches the request. - * - 404: Return 404 Not Found (default) - * - proxy: Forward to a configured proxy target - * - custom: Delegate to a custom handler - * @default '404' - */ - fallback: external_exports.enum(["404", "proxy", "custom"]).default("404").describe("Behavior when no route matches"), - /** - * Proxy target URL for fallback: 'proxy' mode. - */ - proxyTarget: external_exports.string().url().optional().describe('Proxy target URL when fallback is "proxy"') -}); -var DispatcherErrorCode = external_exports.enum(["404", "405", "501", "503"]).describe( - "404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable" -); -var DispatcherErrorResponseSchema = external_exports.object({ - /** Always `false` for error responses */ - success: external_exports.literal(false), - error: external_exports.object({ - /** HTTP status code */ - code: external_exports.number().int().describe("HTTP status code (404, 405, 501, 503, \u2026)"), - /** Human-readable error message */ - message: external_exports.string().describe("Human-readable error message"), - /** - * Machine-readable error type for programmatic branching. - */ - type: external_exports.enum([ - "ROUTE_NOT_FOUND", - "METHOD_NOT_ALLOWED", - "NOT_IMPLEMENTED", - "SERVICE_UNAVAILABLE" - ]).optional().describe("Machine-readable error type"), - /** Route that was requested */ - route: external_exports.string().optional().describe("Requested route path"), - /** Service that the route maps to (if known) */ - service: external_exports.string().optional().describe("Target service name, if resolvable"), - /** Guidance for the developer */ - hint: external_exports.string().optional().describe('Actionable hint for the developer (e.g., "Install plugin-workflow")') - }) -}); -var HttpServerConfigSchema2 = external_exports.object({ - /** - * Server port number - */ - port: external_exports.number().int().min(1).max(65535).default(3e3).describe("Port number to listen on"), - /** - * Server host address - */ - host: external_exports.string().default("0.0.0.0").describe("Host address to bind to"), - /** - * CORS configuration - */ - cors: CorsConfigSchema2.optional().describe("CORS configuration"), - /** - * Request handling options - */ - requestTimeout: external_exports.number().int().default(3e4).describe("Request timeout in milliseconds"), - bodyLimit: external_exports.string().default("10mb").describe("Maximum request body size"), - /** - * Compression settings - */ - compression: external_exports.boolean().default(true).describe("Enable response compression"), - /** - * Security headers - */ - security: external_exports.object({ - helmet: external_exports.boolean().default(true).describe("Enable security headers via helmet"), - rateLimit: RateLimitConfigSchema2.optional().describe("Global rate limiting configuration") - }).optional().describe("Security configuration"), - /** - * Static file serving - */ - static: external_exports.array(StaticMountSchema2).optional().describe("Static file serving configuration"), - /** - * Trust proxy settings - */ - trustProxy: external_exports.boolean().default(false).describe("Trust X-Forwarded-* headers") -}); -external_exports.object({ - /** - * HTTP method - */ - method: HttpMethod2.describe("HTTP method"), - /** - * URL path pattern (supports parameters like /api/users/:id) - */ - path: external_exports.string().describe("URL path pattern"), - /** - * Handler function name or identifier - */ - handler: external_exports.string().describe("Handler identifier or name"), - /** - * Route metadata - */ - metadata: external_exports.object({ - summary: external_exports.string().optional().describe("Route summary for documentation"), - description: external_exports.string().optional().describe("Route description"), - tags: external_exports.array(external_exports.string()).optional().describe("Tags for grouping"), - operationId: external_exports.string().optional().describe("Unique operation identifier") - }).optional(), - /** - * Security requirements - */ - security: external_exports.object({ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - rateLimit: external_exports.string().optional().describe("Rate limit policy override") - }).optional() -}); -var MiddlewareType2 = external_exports.enum([ - "authentication", - // Authentication middleware - "authorization", - // Authorization/permission checks - "logging", - // Request/response logging - "validation", - // Input validation - "transformation", - // Request/response transformation - "error", - // Error handling - "custom" - // Custom middleware -]); -var MiddlewareConfigSchema2 = external_exports.object({ - /** - * Middleware identifier - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Middleware name (snake_case)"), - /** - * Middleware type - */ - type: MiddlewareType2.describe("Middleware type"), - /** - * Enable/disable middleware - */ - enabled: external_exports.boolean().default(true).describe("Whether middleware is enabled"), - /** - * Execution order (lower numbers execute first) - */ - order: external_exports.number().int().default(100).describe("Execution order priority"), - /** - * Middleware-specific configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Middleware configuration object"), - /** - * Path patterns to apply middleware to - */ - paths: external_exports.object({ - include: external_exports.array(external_exports.string()).optional().describe("Include path patterns (glob)"), - exclude: external_exports.array(external_exports.string()).optional().describe("Exclude path patterns (glob)") - }).optional().describe("Path filtering") -}); -var ServerEventType2 = external_exports.enum([ - "starting", - // Server is starting - "started", - // Server has started and is listening - "stopping", - // Server is stopping - "stopped", - // Server has stopped - "request", - // Request received - "response", - // Response sent - "error" - // Error occurred -]); -external_exports.object({ - /** - * Event type - */ - type: ServerEventType2.describe("Event type"), - /** - * Timestamp - */ - timestamp: external_exports.string().datetime().describe("Event timestamp (ISO 8601)"), - /** - * Event payload - */ - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific data") -}); -external_exports.object({ - /** - * Supported HTTP versions - */ - httpVersions: external_exports.array(external_exports.enum(["1.0", "1.1", "2.0", "3.0"])).default(["1.1"]).describe("Supported HTTP versions"), - /** - * WebSocket support - */ - websocket: external_exports.boolean().default(false).describe("WebSocket support"), - /** - * Server-Sent Events support - */ - sse: external_exports.boolean().default(false).describe("Server-Sent Events support"), - /** - * HTTP/2 Server Push - */ - serverPush: external_exports.boolean().default(false).describe("HTTP/2 Server Push support"), - /** - * Streaming support - */ - streaming: external_exports.boolean().default(true).describe("Response streaming support"), - /** - * Middleware support - */ - middleware: external_exports.boolean().default(true).describe("Middleware chain support"), - /** - * Route parameterization - */ - routeParams: external_exports.boolean().default(true).describe("URL parameter support (/users/:id)"), - /** - * Built-in compression - */ - compression: external_exports.boolean().default(true).describe("Built-in compression support") -}); -external_exports.object({ - /** - * Server state - */ - state: external_exports.enum(["stopped", "starting", "running", "stopping", "error"]).describe("Current server state"), - /** - * Uptime in milliseconds - */ - uptime: external_exports.number().int().optional().describe("Server uptime in milliseconds"), - /** - * Server information - */ - server: external_exports.object({ - port: external_exports.number().int().describe("Listening port"), - host: external_exports.string().describe("Bound host"), - url: external_exports.string().optional().describe("Full server URL") - }).optional(), - /** - * Connection metrics - */ - connections: external_exports.object({ - active: external_exports.number().int().describe("Active connections"), - total: external_exports.number().int().describe("Total connections handled") - }).optional(), - /** - * Request metrics - */ - requests: external_exports.object({ - total: external_exports.number().int().describe("Total requests processed"), - success: external_exports.number().int().describe("Successful requests"), - errors: external_exports.number().int().describe("Failed requests") - }).optional() -}); -Object.assign(HttpServerConfigSchema2, { - create: (config4) => config4 -}); -Object.assign(MiddlewareConfigSchema2, { - create: (config4) => config4 -}); -var RestApiRouteCategory = external_exports.enum([ - "discovery", - // API discovery and capabilities - "metadata", - // Metadata operations (objects, fields, views) - "data", - // Data CRUD operations - "batch", - // Batch/bulk operations - "permission", - // Permission/authorization checks - "analytics", - // Analytics and reporting - "automation", - // Automation triggers and flows - "workflow", - // Workflow state management - "ui", - // UI metadata (views, layouts) - "realtime", - // Realtime/WebSocket - "notification", - // Notification management - "ai", - // AI operations (NLQ, chat) - "i18n" - // Internationalization -]); -var HandlerStatusSchema = external_exports.enum(["implemented", "stub", "planned"]); -var RestApiEndpointSchema = external_exports.object({ - /** - * HTTP method - */ - method: HttpMethod2.describe("HTTP method for this endpoint"), - /** - * URL path pattern (supports parameters like :id) - */ - path: external_exports.string().describe("URL path pattern (e.g., /api/v1/data/:object/:id)"), - /** - * Handler reference (protocol method name) - */ - handler: external_exports.string().describe("Protocol method name or handler identifier"), - /** - * Route category - */ - category: RestApiRouteCategory.describe("Route category"), - /** - * Whether endpoint is publicly accessible (no auth required) - */ - public: external_exports.boolean().default(false).describe("Is publicly accessible without authentication"), - /** - * Required permissions - */ - permissions: external_exports.array(external_exports.string()).optional().describe('Required permissions (e.g., ["data.read", "object.account.read"])'), - /** - * OpenAPI documentation metadata - */ - summary: external_exports.string().optional().describe("Short description for OpenAPI"), - description: external_exports.string().optional().describe("Detailed description for OpenAPI"), - tags: external_exports.array(external_exports.string()).optional().describe("OpenAPI tags for grouping"), - /** - * Request/Response schema references - */ - requestSchema: external_exports.string().optional().describe("Request schema name (for validation)"), - responseSchema: external_exports.string().optional().describe("Response schema name (for documentation)"), - /** - * Performance and reliability settings - */ - timeout: external_exports.number().int().optional().describe("Request timeout in milliseconds"), - rateLimit: external_exports.string().optional().describe("Rate limit policy name"), - cacheable: external_exports.boolean().default(false).describe("Whether response can be cached"), - cacheTtl: external_exports.number().int().optional().describe("Cache TTL in seconds"), - /** - * Handler implementation status. - * Tracks whether this endpoint has a real handler or is only declared. - * - * - `implemented` – A real handler is coded and registered. - * - `stub` – A placeholder handler exists that returns 501 Not Implemented. - * - `planned` – Declared in the protocol spec but not yet implemented. - * @default 'implemented' - */ - handlerStatus: HandlerStatusSchema.optional().describe("Handler implementation status: implemented (default if omitted), stub, or planned") -}); -var RestApiRouteRegistrationSchema = external_exports.object({ - /** - * URL prefix for this route group (e.g., /api/v1/data) - */ - prefix: external_exports.string().regex(/^\//).describe("URL path prefix for this route group"), - /** - * Service name that handles these routes - */ - service: external_exports.string().describe("Core service name (metadata, data, auth, etc.)"), - /** - * Route category - */ - category: RestApiRouteCategory.describe("Primary category for this route group"), - /** - * Protocol methods implemented - */ - methods: external_exports.array(external_exports.string()).optional().describe("Protocol method names implemented"), - /** - * Detailed endpoint definitions - */ - endpoints: external_exports.array(RestApiEndpointSchema).optional().describe("Endpoint definitions"), - /** - * Middleware applied to all routes in this group - */ - middleware: external_exports.array(MiddlewareConfigSchema2).optional().describe("Middleware stack for this route group"), - /** - * Whether authentication is required for all routes - */ - authRequired: external_exports.boolean().default(true).describe("Whether authentication is required by default"), - /** - * OpenAPI documentation - */ - documentation: external_exports.object({ - title: external_exports.string().optional().describe("Route group title"), - description: external_exports.string().optional().describe("Route group description"), - tags: external_exports.array(external_exports.string()).optional().describe("OpenAPI tags") - }).optional().describe("Documentation metadata for this route group") -}); -var ValidationMode = external_exports.enum([ - "strict", - // Reject requests with validation errors (400 Bad Request) - "permissive", - // Log validation errors but allow request to proceed - "strip" - // Remove invalid fields and continue with valid data -]); -var RequestValidationConfigSchema = external_exports.object({ - /** - * Enable request validation - */ - enabled: external_exports.boolean().default(true).describe("Enable automatic request validation"), - /** - * Validation mode - */ - mode: ValidationMode.default("strict").describe("How to handle validation errors"), - /** - * Validate request body - */ - validateBody: external_exports.boolean().default(true).describe("Validate request body against schema"), - /** - * Validate query parameters - */ - validateQuery: external_exports.boolean().default(true).describe("Validate query string parameters"), - /** - * Validate URL parameters - */ - validateParams: external_exports.boolean().default(true).describe("Validate URL path parameters"), - /** - * Validate request headers - */ - validateHeaders: external_exports.boolean().default(false).describe("Validate request headers"), - /** - * Include detailed field errors in response - */ - includeFieldErrors: external_exports.boolean().default(true).describe("Include field-level error details in response"), - /** - * Custom error message prefix - */ - errorPrefix: external_exports.string().optional().describe("Custom prefix for validation error messages"), - /** - * Schema registry reference - */ - schemaRegistry: external_exports.string().optional().describe("Schema registry name to use for validation") -}); -var ResponseEnvelopeConfigSchema = external_exports.object({ - /** - * Enable response envelope wrapping - */ - enabled: external_exports.boolean().default(true).describe("Enable automatic response envelope wrapping"), - /** - * Include metadata object - */ - includeMetadata: external_exports.boolean().default(true).describe("Include meta object in responses"), - /** - * Include timestamp in metadata - */ - includeTimestamp: external_exports.boolean().default(true).describe("Include timestamp in response metadata"), - /** - * Include request ID in metadata - */ - includeRequestId: external_exports.boolean().default(true).describe("Include requestId in response metadata"), - /** - * Include request duration in metadata - */ - includeDuration: external_exports.boolean().default(false).describe("Include request duration in ms"), - /** - * Include trace ID for distributed tracing - */ - includeTraceId: external_exports.boolean().default(false).describe("Include distributed traceId"), - /** - * Custom metadata fields - */ - customMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata fields to include"), - /** - * Whether to wrap already-wrapped responses - */ - skipIfWrapped: external_exports.boolean().default(true).describe("Skip wrapping if response already has success field") -}); -var ErrorHandlingConfigSchema = external_exports.object({ - /** - * Enable standardized error handling - */ - enabled: external_exports.boolean().default(true).describe("Enable standardized error handling"), - /** - * Include stack traces in error responses (dev only) - */ - includeStackTrace: external_exports.boolean().default(false).describe("Include stack traces in error responses"), - /** - * Log errors to logger - */ - logErrors: external_exports.boolean().default(true).describe("Log errors to system logger"), - /** - * Expose internal error details - */ - exposeInternalErrors: external_exports.boolean().default(false).describe("Expose internal error details in responses"), - /** - * Include request ID in errors - */ - includeRequestId: external_exports.boolean().default(true).describe("Include requestId in error responses"), - /** - * Include timestamp in errors - */ - includeTimestamp: external_exports.boolean().default(true).describe("Include timestamp in error responses"), - /** - * Include error documentation URLs - */ - includeDocumentation: external_exports.boolean().default(true).describe("Include documentation URLs for errors"), - /** - * Documentation base URL - */ - documentationBaseUrl: external_exports.string().url().optional().describe("Base URL for error documentation"), - /** - * Custom error messages by code - */ - customErrorMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom error messages by error code"), - /** - * Sensitive fields to redact from error details - */ - redactFields: external_exports.array(external_exports.string()).optional().describe("Field names to redact from error details") -}); -var OpenApiGenerationConfigSchema = external_exports.object({ - /** - * Enable OpenAPI generation - */ - enabled: external_exports.boolean().default(true).describe("Enable automatic OpenAPI documentation generation"), - /** - * OpenAPI specification version - */ - version: external_exports.enum(["3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.1.0"]).default("3.0.3").describe("OpenAPI specification version"), - /** - * API title - */ - title: external_exports.string().default("ObjectStack API").describe("API title"), - /** - * API description - */ - description: external_exports.string().optional().describe("API description"), - /** - * API version - */ - apiVersion: external_exports.string().default("1.0.0").describe("API version"), - /** - * Output path for OpenAPI spec - */ - outputPath: external_exports.string().default("/api/docs/openapi.json").describe("URL path to serve OpenAPI JSON"), - /** - * UI path for Swagger/Redoc - */ - uiPath: external_exports.string().default("/api/docs").describe("URL path to serve documentation UI"), - /** - * UI framework to use - */ - uiFramework: external_exports.enum(["swagger-ui", "redoc", "rapidoc", "elements"]).default("swagger-ui").describe("Documentation UI framework"), - /** - * Include internal/admin endpoints - */ - includeInternal: external_exports.boolean().default(false).describe("Include internal endpoints in documentation"), - /** - * Generate JSON schemas from Zod - */ - generateSchemas: external_exports.boolean().default(true).describe("Auto-generate schemas from Zod definitions"), - /** - * Include examples in documentation - */ - includeExamples: external_exports.boolean().default(true).describe("Include request/response examples"), - /** - * Server URLs - */ - servers: external_exports.array(external_exports.object({ - url: external_exports.string().describe("Server URL"), - description: external_exports.string().optional().describe("Server description") - })).optional().describe("Server URLs for API"), - /** - * Contact information - */ - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().url().optional(), - email: external_exports.string().email().optional() - }).optional().describe("API contact information"), - /** - * License information - */ - license: external_exports.object({ - name: external_exports.string().describe("License name"), - url: external_exports.string().url().optional().describe("License URL") - }).optional().describe("API license information"), - /** - * Security schemes - */ - securitySchemes: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["apiKey", "http", "oauth2", "openIdConnect"]), - scheme: external_exports.string().optional(), - bearerFormat: external_exports.string().optional() - })).optional().describe("Security scheme definitions") -}); -var RestApiPluginConfigSchema = external_exports.object({ - /** - * Enable REST API plugin - */ - enabled: external_exports.boolean().default(true).describe("Enable REST API plugin"), - /** - * API base path - */ - basePath: external_exports.string().default("/api").describe("Base path for all API routes"), - /** - * API version - */ - version: external_exports.string().default("v1").describe("API version identifier"), - /** - * Route registrations - */ - routes: external_exports.array(RestApiRouteRegistrationSchema).describe("Route registrations"), - /** - * Request validation configuration - */ - validation: RequestValidationConfigSchema.optional().describe("Request validation configuration"), - /** - * Response envelope configuration - */ - responseEnvelope: ResponseEnvelopeConfigSchema.optional().describe("Response envelope configuration"), - /** - * Error handling configuration - */ - errorHandling: ErrorHandlingConfigSchema.optional().describe("Error handling configuration"), - /** - * OpenAPI documentation configuration - */ - openApi: OpenApiGenerationConfigSchema.optional().describe("OpenAPI documentation configuration"), - /** - * Global middleware applied to all routes - */ - globalMiddleware: external_exports.array(MiddlewareConfigSchema2).optional().describe("Global middleware stack"), - /** - * CORS configuration - */ - cors: external_exports.object({ - enabled: external_exports.boolean().default(true), - origins: external_exports.array(external_exports.string()).optional(), - methods: external_exports.array(HttpMethod2).optional(), - credentials: external_exports.boolean().default(true) - }).optional().describe("CORS configuration"), - /** - * Performance settings - */ - performance: external_exports.object({ - enableCompression: external_exports.boolean().default(true).describe("Enable response compression"), - enableETag: external_exports.boolean().default(true).describe("Enable ETag generation"), - enableCaching: external_exports.boolean().default(true).describe("Enable HTTP caching"), - defaultCacheTtl: external_exports.number().int().default(300).describe("Default cache TTL in seconds") - }).optional().describe("Performance optimization settings") -}); -var RestApiPluginConfig = Object.assign(RestApiPluginConfigSchema, { - create: (config4) => config4 -}); -var RestApiRouteRegistration = Object.assign(RestApiRouteRegistrationSchema, { - create: (registration) => registration -}); -var RouteCoverageEntrySchema = external_exports.object({ - /** Full URL path of the endpoint */ - path: external_exports.string().describe("Full URL path (e.g. /api/v1/analytics/query)"), - /** HTTP method */ - method: HttpMethod2.describe("HTTP method (GET, POST, etc.)"), - /** Route category */ - category: RestApiRouteCategory.describe("Route category"), - /** Handler implementation status */ - handlerStatus: HandlerStatusSchema.describe("Handler status"), - /** Target service */ - service: external_exports.string().describe("Target service name"), - /** Whether the handler was successfully called during health check */ - healthCheckPassed: external_exports.boolean().optional().describe("Whether the health check probe succeeded") -}); -var RouteCoverageReportSchema = external_exports.object({ - /** ISO 8601 timestamp of report generation */ - timestamp: external_exports.string().describe("ISO 8601 timestamp"), - /** Adapter that generated the report */ - adapter: external_exports.string().describe('Adapter name (e.g. "hono", "express", "nextjs")'), - /** Summary counters */ - summary: external_exports.object({ - total: external_exports.number().int().describe("Total declared endpoints"), - implemented: external_exports.number().int().describe("Endpoints with real handlers"), - stub: external_exports.number().int().describe("Endpoints with stub handlers (501)"), - planned: external_exports.number().int().describe("Endpoints not yet implemented") - }), - /** Per-endpoint entries */ - entries: external_exports.array(RouteCoverageEntrySchema).describe("Per-endpoint coverage entries") -}); -var QueryAdapterTargetSchema = external_exports.enum([ - "rest", - // REST API (?filter[field][op]=value) - "graphql", - // GraphQL (where: \{ field: \{ op: value \}\}) - "odata" - // OData ($filter=field op value) -]); -var OperatorMappingSchema = external_exports.object({ - /** Unified DSL operator (e.g., 'eq', 'gt', 'contains') */ - operator: external_exports.string().describe("Unified DSL operator"), - /** REST query parameter format (e.g., 'filter[{field}][{op}]') */ - rest: external_exports.string().optional().describe("REST query parameter template"), - /** GraphQL where clause format (e.g., '{field}: { {op}: $value }') */ - graphql: external_exports.string().optional().describe("GraphQL where clause template"), - /** OData $filter expression format (e.g., '{field} {op} {value}') */ - odata: external_exports.string().optional().describe("OData $filter expression template") -}); -var RestQueryAdapterSchema = external_exports.object({ - /** Filter parameter style */ - filterStyle: external_exports.enum([ - "bracket", - // ?filter[field][op]=value (JSON API style) - "dot", - // ?filter.field.op=value - "flat", - // ?field=value (simple equality) - "rsql" - // ?filter=field==value;field=gt=10 (RSQL / FIQL) - ]).default("bracket").describe("REST filter parameter encoding style"), - /** Pagination parameter names */ - pagination: external_exports.object({ - /** Page size parameter name */ - limitParam: external_exports.string().default("limit").describe("Page size parameter name"), - /** Offset parameter name */ - offsetParam: external_exports.string().default("offset").describe("Offset parameter name"), - /** Cursor parameter name (for cursor-based pagination) */ - cursorParam: external_exports.string().default("cursor").describe("Cursor parameter name"), - /** Page number parameter name (for page-based pagination) */ - pageParam: external_exports.string().default("page").describe("Page number parameter name") - }).optional().describe("Pagination parameter name mappings"), - /** Sort parameter name and format */ - sorting: external_exports.object({ - /** Sort parameter name */ - param: external_exports.string().default("sort").describe("Sort parameter name"), - /** Sort format */ - format: external_exports.enum([ - "comma", - // ?sort=field1,-field2 - "array", - // ?sort[]=field1&sort[]=-field2 - "pipe" - // ?sort=field1|asc,field2|desc - ]).default("comma").describe("Sort parameter encoding format") - }).optional().describe("Sort parameter mapping"), - /** Field selection parameter name */ - fieldsParam: external_exports.string().default("fields").describe("Field selection parameter name") -}); -var GraphQLQueryAdapterSchema = external_exports.object({ - /** Filter argument name in GraphQL queries */ - filterArgName: external_exports.string().default("where").describe("GraphQL filter argument name"), - /** Filter nesting style */ - filterStyle: external_exports.enum([ - "nested", - // where: { field: { op: value } } (Prisma style) - "flat", - // where: { field_op: value } (Hasura style) - "array" - // where: [{ field, op, value }] (Array of conditions) - ]).default("nested").describe("GraphQL filter nesting style"), - /** Pagination argument names */ - pagination: external_exports.object({ - limitArg: external_exports.string().default("limit").describe("Page size argument name"), - offsetArg: external_exports.string().default("offset").describe("Offset argument name"), - firstArg: external_exports.string().default("first").describe('Relay "first" argument name'), - afterArg: external_exports.string().default("after").describe('Relay "after" cursor argument name') - }).optional().describe("Pagination argument name mappings"), - /** Sort argument configuration */ - sorting: external_exports.object({ - argName: external_exports.string().default("orderBy").describe("Sort argument name"), - format: external_exports.enum([ - "enum", - // orderBy: { field: ASC } - "array" - // orderBy: [{ field: "name", direction: "ASC" }] - ]).default("enum").describe("Sort argument format") - }).optional().describe("Sort argument mapping") -}); -var ODataQueryAdapterSchema = external_exports.object({ - /** OData version */ - version: external_exports.enum(["v2", "v4"]).default("v4").describe("OData version"), - /** System query option prefixes */ - usePrefix: external_exports.boolean().default(true).describe("Use $ prefix for system query options ($filter vs filter)"), - /** String function support */ - stringFunctions: external_exports.array(external_exports.enum([ - "contains", - "startswith", - "endswith", - "tolower", - "toupper", - "trim", - "concat", - "substring", - "length" - ])).optional().describe("Supported OData string functions"), - /** Expand (nested resource) configuration */ - expand: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable $expand support"), - maxDepth: external_exports.number().int().min(1).default(3).describe("Maximum expand depth") - }).optional().describe("$expand configuration") -}); -var QueryAdapterConfigSchema = external_exports.object({ - /** Default operator mappings */ - operatorMappings: external_exports.array(OperatorMappingSchema).optional().describe("Custom operator mappings"), - /** REST adapter configuration */ - rest: RestQueryAdapterSchema.optional().describe("REST query adapter configuration"), - /** GraphQL adapter configuration */ - graphql: GraphQLQueryAdapterSchema.optional().describe("GraphQL query adapter configuration"), - /** OData adapter configuration */ - odata: ODataQueryAdapterSchema.optional().describe("OData query adapter configuration") -}); -var FeedItemType = external_exports.enum([ - "comment", - "field_change", - "task", - "event", - "email", - "call", - "note", - "file", - "record_create", - "record_delete", - "approval", - "sharing", - "system" -]); -var MentionSchema = external_exports.object({ - type: external_exports.enum(["user", "team", "record"]).describe("Mention target type"), - id: external_exports.string().describe("Target ID"), - name: external_exports.string().describe("Display name for rendering"), - offset: external_exports.number().int().min(0).describe("Character offset in body text"), - length: external_exports.number().int().min(1).describe("Length of mention token in body text") -}); -var FieldChangeEntrySchema = external_exports.object({ - field: external_exports.string().describe("Field machine name"), - fieldLabel: external_exports.string().optional().describe("Field display label"), - oldValue: external_exports.unknown().optional().describe("Previous value"), - newValue: external_exports.unknown().optional().describe("New value"), - oldDisplayValue: external_exports.string().optional().describe("Human-readable old value"), - newDisplayValue: external_exports.string().optional().describe("Human-readable new value") -}); -var ReactionSchema = external_exports.object({ - emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")'), - userIds: external_exports.array(external_exports.string()).describe("Users who reacted"), - count: external_exports.number().int().min(1).describe("Total reaction count") -}); -var FeedActorSchema = external_exports.object({ - type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), - id: external_exports.string().describe("Actor ID"), - name: external_exports.string().optional().describe("Actor display name"), - avatarUrl: external_exports.string().url().optional().describe("Actor avatar URL"), - source: external_exports.string().optional().describe('Source application (e.g., "Omni", "API", "Studio")') -}); -var FeedVisibility = external_exports.enum(["public", "internal", "private"]); -var FeedItemSchema = external_exports.object({ - /** Unique identifier */ - id: external_exports.string().describe("Feed item ID"), - /** Feed item type */ - type: FeedItemType.describe("Activity type"), - /** Target record reference */ - object: external_exports.string().describe('Object name (e.g., "account")'), - recordId: external_exports.string().describe("Record ID this feed item belongs to"), - /** Actor (who performed the action) */ - actor: FeedActorSchema.describe("Who performed this action"), - /** Content (for comments/notes) */ - body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), - /** @Mentions */ - mentions: external_exports.array(MentionSchema).optional().describe("Mentioned users/teams/records"), - /** Field changes (for field_change type) */ - changes: external_exports.array(FieldChangeEntrySchema).optional().describe("Field-level changes"), - /** Reactions */ - reactions: external_exports.array(ReactionSchema).optional().describe("Emoji reactions on this item"), - /** Reply threading */ - parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), - replyCount: external_exports.number().int().min(0).default(0).describe("Number of replies"), - /** Pin / Star */ - pinned: external_exports.boolean().default(false).describe("Whether the feed item is pinned to the top of the timeline"), - pinnedAt: external_exports.string().datetime().optional().describe("Timestamp when the item was pinned"), - pinnedBy: external_exports.string().optional().describe("User ID who pinned the item"), - starred: external_exports.boolean().default(false).describe("Whether the feed item is starred/bookmarked by the current user"), - starredAt: external_exports.string().datetime().optional().describe("Timestamp when the item was starred"), - /** Visibility */ - visibility: FeedVisibility.default("public").describe("Visibility: public (all users), internal (team only), private (author + mentioned)"), - /** Timestamps */ - createdAt: external_exports.string().datetime().describe("Creation timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - editedAt: external_exports.string().datetime().optional().describe("When comment was last edited"), - isEdited: external_exports.boolean().default(false).describe("Whether comment has been edited") -}); -external_exports.enum([ - "all", - "comments_only", - "changes_only", - "tasks_only" -]); -var SubscriptionEventType = external_exports.enum([ - "comment", - "mention", - "field_change", - "task", - "approval", - "all" -]); -var NotificationChannel = external_exports.enum([ - "in_app", - "email", - "push", - "slack" -]); -var RecordSubscriptionSchema = external_exports.object({ - /** Target */ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - /** Subscriber */ - userId: external_exports.string().describe("Subscribing user ID"), - /** Events to subscribe to */ - events: external_exports.array(SubscriptionEventType).default(["all"]).describe("Event types to receive notifications for"), - /** Notification channels */ - channels: external_exports.array(NotificationChannel).default(["in_app"]).describe("Notification delivery channels"), - /** Active */ - active: external_exports.boolean().default(true).describe("Whether the subscription is active"), - /** Timestamps */ - createdAt: external_exports.string().datetime().describe("Subscription creation timestamp") -}); -var FeedPathParamsSchema = external_exports.object({ - object: external_exports.string().describe('Object name (e.g., "account")'), - recordId: external_exports.string().describe("Record ID") -}); -var FeedItemPathParamsSchema = FeedPathParamsSchema.extend({ - feedId: external_exports.string().describe("Feed item ID") -}); -var FeedListFilterType = external_exports.enum([ - "all", - "comments_only", - "changes_only", - "tasks_only" -]); -var GetFeedRequestSchema = FeedPathParamsSchema.extend({ - type: FeedListFilterType.default("all").describe("Filter by feed item category"), - limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of items to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination (opaque string from previous response)") -}); -var GetFeedResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - items: external_exports.array(FeedItemSchema).describe("Feed items in reverse chronological order"), - total: external_exports.number().int().optional().describe("Total feed items matching filter"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more items are available") - }) -}); -var CreateFeedItemRequestSchema = FeedPathParamsSchema.extend({ - type: FeedItemType.describe("Type of feed item to create"), - body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), - mentions: external_exports.array(MentionSchema).optional().describe("Mentioned users, teams, or records"), - parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), - visibility: FeedVisibility.default("public").describe("Visibility: public, internal, or private") -}); -var CreateFeedItemResponseSchema = BaseResponseSchema.extend({ - data: FeedItemSchema.describe("The created feed item") -}); -var UpdateFeedItemRequestSchema = FeedItemPathParamsSchema.extend({ - body: external_exports.string().optional().describe("Updated rich text body"), - mentions: external_exports.array(MentionSchema).optional().describe("Updated mentions"), - visibility: FeedVisibility.optional().describe("Updated visibility") -}); -var UpdateFeedItemResponseSchema = BaseResponseSchema.extend({ - data: FeedItemSchema.describe("The updated feed item") -}); -var DeleteFeedItemResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the deleted feed item") - }) -}); -var AddReactionRequestSchema = FeedItemPathParamsSchema.extend({ - emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")') -}); -var AddReactionResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - reactions: external_exports.array(ReactionSchema).describe("Updated reaction list for the feed item") - }) -}); -var RemoveReactionRequestSchema = FeedItemPathParamsSchema.extend({ - emoji: external_exports.string().describe("Emoji character or shortcode to remove") -}); -var RemoveReactionResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - reactions: external_exports.array(ReactionSchema).describe("Updated reaction list for the feed item") - }) -}); -var PinFeedItemResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the pinned feed item"), - pinned: external_exports.boolean().describe("Whether the item is now pinned"), - pinnedAt: external_exports.string().datetime().describe("Timestamp when pinned") - }) -}); -var UnpinFeedItemResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the unpinned feed item"), - pinned: external_exports.boolean().describe("Whether the item is now pinned (should be false)") - }) -}); -var StarFeedItemResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the starred feed item"), - starred: external_exports.boolean().describe("Whether the item is now starred"), - starredAt: external_exports.string().datetime().describe("Timestamp when starred") - }) -}); -var UnstarFeedItemResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the unstarred feed item"), - starred: external_exports.boolean().describe("Whether the item is now starred (should be false)") - }) -}); -var SearchFeedRequestSchema = FeedPathParamsSchema.extend({ - query: external_exports.string().min(1).describe("Full-text search query against feed body content"), - type: FeedListFilterType.optional().describe("Filter by feed item category"), - actorId: external_exports.string().optional().describe("Filter by actor user ID"), - dateFrom: external_exports.string().datetime().optional().describe("Filter feed items created after this timestamp"), - dateTo: external_exports.string().datetime().optional().describe("Filter feed items created before this timestamp"), - hasAttachments: external_exports.boolean().optional().describe("Filter for items with file attachments"), - pinnedOnly: external_exports.boolean().optional().describe("Return only pinned items"), - starredOnly: external_exports.boolean().optional().describe("Return only starred items"), - limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of items to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination") -}); -var SearchFeedResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - items: external_exports.array(FeedItemSchema).describe("Matching feed items sorted by relevance"), - total: external_exports.number().int().optional().describe("Total matching items"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more items are available") - }) -}); -var GetChangelogRequestSchema = FeedPathParamsSchema.extend({ - field: external_exports.string().optional().describe("Filter changelog to a specific field name"), - actorId: external_exports.string().optional().describe("Filter changelog by actor user ID"), - dateFrom: external_exports.string().datetime().optional().describe("Filter changes after this timestamp"), - dateTo: external_exports.string().datetime().optional().describe("Filter changes before this timestamp"), - limit: external_exports.number().int().min(1).max(200).default(50).describe("Maximum number of changelog entries to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination") -}); -var ChangelogEntrySchema = external_exports.object({ - id: external_exports.string().describe("Changelog entry ID"), - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - actor: external_exports.object({ - type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), - id: external_exports.string().describe("Actor ID"), - name: external_exports.string().optional().describe("Actor display name") - }).describe("Who made the change"), - changes: external_exports.array(FieldChangeEntrySchema).min(1).describe("Field-level changes"), - timestamp: external_exports.string().datetime().describe("When the change occurred"), - source: external_exports.string().optional().describe('Change source (e.g., "API", "UI", "automation")') -}); -var GetChangelogResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - entries: external_exports.array(ChangelogEntrySchema).describe("Changelog entries in reverse chronological order"), - total: external_exports.number().int().optional().describe("Total changelog entries matching filter"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more entries are available") - }) -}); -var SubscribeRequestSchema = FeedPathParamsSchema.extend({ - events: external_exports.array(SubscriptionEventType).default(["all"]).describe("Event types to subscribe to"), - channels: external_exports.array(NotificationChannel).default(["in_app"]).describe("Notification delivery channels") -}); -var SubscribeResponseSchema = BaseResponseSchema.extend({ - data: RecordSubscriptionSchema.describe("The created or updated subscription") -}); -var UnsubscribeResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - unsubscribed: external_exports.boolean().describe("Whether the user was unsubscribed") - }) -}); -var FeedApiErrorCode = external_exports.enum([ - "feed_item_not_found", - "feed_permission_denied", - "feed_item_not_editable", - "feed_invalid_parent", - "reaction_already_exists", - "reaction_not_found", - "subscription_already_exists", - "subscription_not_found", - "invalid_feed_type", - "feed_already_pinned", - "feed_not_pinned", - "feed_already_starred", - "feed_not_starred", - "feed_search_query_too_short" -]); -var ExportFormat = external_exports.enum([ - "csv", - "json", - "jsonl", - "xlsx", - "parquet" -]); -var ExportJobStatus = external_exports.enum([ - "pending", - "processing", - "completed", - "failed", - "cancelled", - "expired" -]); -var CreateExportJobRequestSchema = external_exports.object({ - object: external_exports.string().describe("Object name to export"), - format: ExportFormat.default("csv").describe("Export file format"), - fields: external_exports.array(external_exports.string()).optional().describe("Specific fields to include (omit for all fields)"), - filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria for records to export"), - sort: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - direction: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction") - })).optional().describe("Sort order for exported records"), - limit: external_exports.number().int().min(1).optional().describe("Maximum number of records to export"), - includeHeaders: external_exports.boolean().default(true).describe("Include header row (CSV/XLSX)"), - encoding: external_exports.string().default("utf-8").describe("Character encoding for the export file"), - templateId: external_exports.string().optional().describe("Export template ID for predefined field mappings") -}); -var CreateExportJobResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - jobId: external_exports.string().describe("Export job ID"), - status: ExportJobStatus.describe("Initial job status"), - estimatedRecords: external_exports.number().int().optional().describe("Estimated total records"), - createdAt: external_exports.string().datetime().describe("Job creation timestamp") - }) -}); -var ExportJobProgressSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - jobId: external_exports.string().describe("Export job ID"), - status: ExportJobStatus.describe("Current job status"), - format: ExportFormat.describe("Export format"), - totalRecords: external_exports.number().int().optional().describe("Total records to export"), - processedRecords: external_exports.number().int().describe("Records processed so far"), - percentComplete: external_exports.number().min(0).max(100).describe("Export progress percentage"), - fileSize: external_exports.number().int().optional().describe("Current file size in bytes"), - downloadUrl: external_exports.string().optional().describe('Presigned download URL (available when status is "completed")'), - downloadExpiresAt: external_exports.string().datetime().optional().describe("Download URL expiration timestamp"), - error: external_exports.object({ - code: external_exports.string().describe("Error code"), - message: external_exports.string().describe("Error message") - }).optional().describe("Error details if job failed"), - startedAt: external_exports.string().datetime().optional().describe("Processing start timestamp"), - completedAt: external_exports.string().datetime().optional().describe("Completion timestamp") - }) -}); -var ImportValidationMode = external_exports.enum([ - "strict", - // Reject entire import on any validation error - "lenient", - // Skip invalid records, import valid ones - "dry_run" - // Validate all records without persisting -]); -var DeduplicationStrategy = external_exports.enum([ - "skip", - // Skip duplicates (keep existing) - "update", - // Update existing with import data - "create_new", - // Create new record even if duplicate - "fail" - // Fail the import if duplicates found -]); -var ImportValidationConfigSchema = external_exports.object({ - mode: ImportValidationMode.default("strict").describe("Validation mode for the import"), - deduplication: external_exports.object({ - strategy: DeduplicationStrategy.default("skip").describe("How to handle duplicate records"), - matchFields: external_exports.array(external_exports.string()).min(1).describe('Fields used to identify duplicates (e.g., "email", "external_id")') - }).optional().describe("Deduplication configuration"), - maxErrors: external_exports.number().int().min(1).default(100).describe("Maximum validation errors before aborting"), - trimWhitespace: external_exports.boolean().default(true).describe("Trim leading/trailing whitespace from string fields"), - dateFormat: external_exports.string().optional().describe('Expected date format in import data (e.g., "YYYY-MM-DD")'), - nullValues: external_exports.array(external_exports.string()).optional().describe('Strings to treat as null (e.g., ["", "N/A", "null"])') -}); -var ImportValidationResultSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - totalRecords: external_exports.number().int().describe("Total records in import file"), - validRecords: external_exports.number().int().describe("Records that passed validation"), - invalidRecords: external_exports.number().int().describe("Records that failed validation"), - duplicateRecords: external_exports.number().int().describe("Duplicate records detected"), - errors: external_exports.array(external_exports.object({ - row: external_exports.number().int().describe("Row number in the import file"), - field: external_exports.string().optional().describe("Field that failed validation"), - code: external_exports.string().describe("Validation error code"), - message: external_exports.string().describe("Validation error message") - })).describe("List of validation errors"), - preview: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Preview of first N valid records (for dry_run mode)") - }) -}); -var FieldMappingEntrySchema = external_exports.object({ - sourceField: external_exports.string().describe("Field name in the source data (import) or object (export)"), - targetField: external_exports.string().describe("Field name in the target object (import) or file column (export)"), - targetLabel: external_exports.string().optional().describe("Display label for the target column (export)"), - transform: external_exports.enum(["none", "uppercase", "lowercase", "trim", "date_format", "lookup"]).default("none").describe("Transformation to apply during mapping"), - defaultValue: external_exports.unknown().optional().describe("Default value if source field is null/empty"), - required: external_exports.boolean().default(false).describe("Whether this field is required (import validation)") -}); -var ExportImportTemplateSchema = external_exports.object({ - id: external_exports.string().optional().describe("Template ID (generated on save)"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Template machine name (snake_case)"), - label: external_exports.string().describe("Human-readable template label"), - description: external_exports.string().optional().describe("Template description"), - object: external_exports.string().describe("Target object name"), - direction: external_exports.enum(["import", "export", "bidirectional"]).describe("Template direction"), - format: ExportFormat.optional().describe("Default file format for this template"), - mappings: external_exports.array(FieldMappingEntrySchema).min(1).describe("Field mapping entries"), - createdAt: external_exports.string().datetime().optional().describe("Template creation timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - createdBy: external_exports.string().optional().describe("User who created the template") -}); -var ScheduledExportSchema = external_exports.object({ - id: external_exports.string().optional().describe("Scheduled export ID"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Schedule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label"), - object: external_exports.string().describe("Object name to export"), - format: ExportFormat.default("csv").describe("Export file format"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to include"), - filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record filter criteria"), - templateId: external_exports.string().optional().describe("Export template ID for field mappings"), - schedule: external_exports.object({ - cronExpression: external_exports.string().describe("Cron expression for schedule"), - timezone: external_exports.string().default("UTC").describe("IANA timezone") - }).describe("Schedule timing configuration"), - delivery: external_exports.object({ - method: external_exports.enum(["email", "storage", "webhook"]).describe("How to deliver the export file"), - recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients (for email delivery)"), - storagePath: external_exports.string().optional().describe("Storage path (for storage delivery)"), - webhookUrl: external_exports.string().optional().describe("Webhook URL (for webhook delivery)") - }).describe("Export delivery configuration"), - enabled: external_exports.boolean().default(true).describe("Whether the scheduled export is active"), - lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp"), - nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution"), - createdAt: external_exports.string().datetime().optional().describe("Creation timestamp"), - createdBy: external_exports.string().optional().describe("User who created the schedule") -}); -var GetExportJobDownloadRequestSchema = external_exports.object({ - jobId: external_exports.string().describe("Export job ID") -}); -var GetExportJobDownloadResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - jobId: external_exports.string().describe("Export job ID"), - downloadUrl: external_exports.string().describe("Presigned download URL"), - fileName: external_exports.string().describe("Suggested file name"), - fileSize: external_exports.number().int().describe("File size in bytes"), - format: ExportFormat.describe("Export file format"), - expiresAt: external_exports.string().datetime().describe("Download URL expiration timestamp"), - checksum: external_exports.string().optional().describe("File checksum (SHA-256)") - }) -}); -var ListExportJobsRequestSchema = external_exports.object({ - object: external_exports.string().optional().describe("Filter by object name"), - status: ExportJobStatus.optional().describe("Filter by job status"), - limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of jobs to return"), - cursor: external_exports.string().optional().describe("Pagination cursor from a previous response") -}); -var ExportJobSummarySchema = external_exports.object({ - jobId: external_exports.string().describe("Export job ID"), - object: external_exports.string().describe("Object name that was exported"), - status: ExportJobStatus.describe("Current job status"), - format: ExportFormat.describe("Export file format"), - totalRecords: external_exports.number().int().optional().describe("Total records exported"), - fileSize: external_exports.number().int().optional().describe("File size in bytes"), - createdAt: external_exports.string().datetime().describe("Job creation timestamp"), - completedAt: external_exports.string().datetime().optional().describe("Completion timestamp"), - createdBy: external_exports.string().optional().describe("User who initiated the export") -}); -var ListExportJobsResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - jobs: external_exports.array(ExportJobSummarySchema).describe("List of export jobs"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more jobs are available") - }) -}); -var ScheduleExportRequestSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Schedule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label"), - object: external_exports.string().describe("Object name to export"), - format: ExportFormat.default("csv").describe("Export file format"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to include"), - filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record filter criteria"), - templateId: external_exports.string().optional().describe("Export template ID for field mappings"), - schedule: external_exports.object({ - cronExpression: external_exports.string().describe("Cron expression for schedule"), - timezone: external_exports.string().default("UTC").describe("IANA timezone") - }).describe("Schedule timing configuration"), - delivery: external_exports.object({ - method: external_exports.enum(["email", "storage", "webhook"]).describe("How to deliver the export file"), - recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients (for email delivery)"), - storagePath: external_exports.string().optional().describe("Storage path (for storage delivery)"), - webhookUrl: external_exports.string().optional().describe("Webhook URL (for webhook delivery)") - }).describe("Export delivery configuration") -}); -var ScheduleExportResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - id: external_exports.string().describe("Scheduled export ID"), - name: external_exports.string().describe("Schedule name"), - enabled: external_exports.boolean().describe("Whether the schedule is active"), - nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution"), - createdAt: external_exports.string().datetime().describe("Creation timestamp") - }) -}); -var ExportApiContracts = { - createExportJob: { - method: "POST", - path: "/api/v1/data/:object/export", - input: CreateExportJobRequestSchema, - output: CreateExportJobResponseSchema - }, - getExportJobProgress: { - method: "GET", - path: "/api/v1/data/export/:jobId", - input: external_exports.object({ jobId: external_exports.string() }), - output: ExportJobProgressSchema - }, - getExportJobDownload: { - method: "GET", - path: "/api/v1/data/export/:jobId/download", - input: GetExportJobDownloadRequestSchema, - output: GetExportJobDownloadResponseSchema - }, - listExportJobs: { - method: "GET", - path: "/api/v1/data/export", - input: ListExportJobsRequestSchema, - output: ListExportJobsResponseSchema - }, - scheduleExport: { - method: "POST", - path: "/api/v1/data/export/schedules", - input: ScheduleExportRequestSchema, - output: ScheduleExportResponseSchema - }, - cancelExportJob: { - method: "POST", - path: "/api/v1/data/export/:jobId/cancel", - input: external_exports.object({ jobId: external_exports.string() }), - output: BaseResponseSchema - } -}; -var FlowNodeAction = external_exports.enum([ - "start", - // Trigger - "end", - // Return/Stop - "decision", - // If/Else logic - "assignment", - // Set Variable - "loop", - // For Each - "create_record", - // CRUD: Create - "update_record", - // CRUD: Update - "delete_record", - // CRUD: Delete - "get_record", - // CRUD: Get/Query - "http_request", - // Webhook/API Call - "script", - // Custom Script (JS/TS) - "screen", - // Screen / User-Input Element - "wait", - // Delay/Sleep - "subflow", - // Call another flow - "connector_action", - // Zapier-style integration action - "parallel_gateway", - // BPMN Parallel Gateway — AND-split (all outgoing branches execute concurrently) - "join_gateway", - // BPMN Join Gateway — AND-join (waits for all incoming branches to complete) - "boundary_event" - // BPMN Boundary Event — attached to a host node for timer/error/signal interrupts -]); -var FlowVariableSchema = external_exports.object({ - name: external_exports.string().describe("Variable name"), - type: external_exports.string().describe("Data type (text, number, boolean, object, list)"), - isInput: external_exports.boolean().default(false).describe("Is input parameter"), - isOutput: external_exports.boolean().default(false).describe("Is output parameter") -}); -var FlowNodeSchema = external_exports.object({ - id: external_exports.string().describe("Node unique ID"), - type: FlowNodeAction.describe("Action type"), - label: external_exports.string().describe("Node label"), - /** Node Configuration Options (Specific to type) */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Node configuration"), - /** - * Connector Action Configuration - * Used when type is 'connector_action' - */ - connectorConfig: external_exports.object({ - connectorId: external_exports.string(), - actionId: external_exports.string(), - input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Mapped inputs for the action") - }).optional(), - /** UI Position (for the canvas) */ - position: external_exports.object({ x: external_exports.number(), y: external_exports.number() }).optional(), - /** Node-level execution timeout */ - timeoutMs: external_exports.number().int().min(0).optional().describe("Maximum execution time for this node in milliseconds"), - /** Node input schema declaration for Studio form generation and runtime validation */ - inputSchema: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["string", "number", "boolean", "object", "array"]).describe("Parameter type"), - required: external_exports.boolean().default(false).describe("Whether the parameter is required"), - description: external_exports.string().optional().describe("Parameter description") - })).optional().describe("Input parameter schema for this node"), - /** Node output schema declaration */ - outputSchema: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["string", "number", "boolean", "object", "array"]).describe("Output type"), - description: external_exports.string().optional().describe("Output description") - })).optional().describe("Output schema declaration for this node"), - /** - * Wait Event Configuration (for 'wait' nodes) - * Defines what external event or condition should resume the paused execution. - * Industry alignment: BPMN Intermediate Catch Events, Temporal Signals. - */ - waitEventConfig: external_exports.object({ - /** Type of event to wait for */ - eventType: external_exports.enum(["timer", "signal", "webhook", "manual", "condition"]).describe("What kind of event resumes the execution"), - /** Duration to wait (ISO 8601 duration or milliseconds) — for timer events */ - timerDuration: external_exports.string().optional().describe('ISO 8601 duration (e.g., "PT1H") or wait time for timer events'), - /** Signal name to listen for — for signal/webhook events */ - signalName: external_exports.string().optional().describe("Named signal or webhook event to wait for"), - /** Timeout before auto-failing or continuing — optional guard */ - timeoutMs: external_exports.number().int().min(0).optional().describe("Maximum wait time before timeout (ms)"), - /** Action to take on timeout */ - onTimeout: external_exports.enum(["fail", "continue"]).default("fail").describe("Behavior when the wait times out") - }).optional().describe("Configuration for wait node event resumption"), - /** - * Boundary Event Configuration (for 'boundary_event' nodes) - * Attaches an event handler to a host activity node (BPMN Boundary Event pattern). - * Industry alignment: BPMN Boundary Error/Timer/Signal Events. - */ - boundaryConfig: external_exports.object({ - /** ID of the host node this boundary event is attached to */ - attachedToNodeId: external_exports.string().describe("Host node ID this boundary event monitors"), - /** Type of boundary event */ - eventType: external_exports.enum(["error", "timer", "signal", "cancel"]).describe("Boundary event trigger type"), - /** Whether the boundary event interrupts the host activity */ - interrupting: external_exports.boolean().default(true).describe("If true, the host activity is cancelled when this event fires"), - /** Error code filter — only for error boundary events */ - errorCode: external_exports.string().optional().describe("Specific error code to catch (empty = catch all errors)"), - /** Timer duration — only for timer boundary events */ - timerDuration: external_exports.string().optional().describe("ISO 8601 duration for timer boundary events"), - /** Signal name — only for signal boundary events */ - signalName: external_exports.string().optional().describe("Named signal to catch") - }).optional().describe("Configuration for boundary events attached to host nodes") -}); -var FlowEdgeSchema = external_exports.object({ - id: external_exports.string().describe("Edge unique ID"), - source: external_exports.string().describe("Source Node ID"), - target: external_exports.string().describe("Target Node ID"), - /** Condition for this path (only for decision/branch nodes) */ - condition: external_exports.string().optional().describe("Expression returning boolean used for branching"), - type: external_exports.enum(["default", "fault", "conditional"]).default("default").describe("Connection type: default (normal flow), fault (error path), or conditional (expression-guarded)"), - label: external_exports.string().optional().describe("Label on the connector"), - /** - * Default Sequence Flow marker (BPMN Default Flow semantics). - * When true, this edge is taken when no sibling conditional edges match. - * Only meaningful on outgoing edges of decision/gateway nodes. - */ - isDefault: external_exports.boolean().default(false).describe("Marks this edge as the default path when no other conditions match") -}); -var FlowSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name"), - label: external_exports.string().describe("Flow label"), - description: external_exports.string().optional(), - /** Metadata & Versioning */ - version: external_exports.number().int().default(1).describe("Version number"), - status: external_exports.enum(["draft", "active", "obsolete", "invalid"]).default("draft").describe("Deployment status"), - template: external_exports.boolean().default(false).describe("Is logic template (Subflow)"), - /** Trigger Type */ - type: external_exports.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).describe("Flow type"), - /** Configuration Variables */ - variables: external_exports.array(FlowVariableSchema).optional().describe("Flow variables"), - /** Graph Definition */ - nodes: external_exports.array(FlowNodeSchema).describe("Flow nodes"), - edges: external_exports.array(FlowEdgeSchema).describe("Flow connections"), - /** Execution Config */ - active: external_exports.boolean().default(false).describe("Is active (Deprecated: use status)"), - runAs: external_exports.enum(["system", "user"]).default("user").describe("Execution context"), - /** Error Handling Strategy */ - errorHandling: external_exports.object({ - strategy: external_exports.enum(["fail", "retry", "continue"]).default("fail").describe("How to handle node execution errors"), - maxRetries: external_exports.number().int().min(0).max(10).default(0).describe("Number of retry attempts (only for retry strategy)"), - retryDelayMs: external_exports.number().int().min(0).default(1e3).describe("Delay between retries in milliseconds"), - backoffMultiplier: external_exports.number().min(1).default(1).describe("Multiplier for exponential backoff between retries"), - maxRetryDelayMs: external_exports.number().int().min(0).default(3e4).describe("Maximum delay between retries in milliseconds"), - jitter: external_exports.boolean().default(false).describe("Add random jitter to retry delay to avoid thundering herd"), - fallbackNodeId: external_exports.string().optional().describe("Node ID to jump to on unrecoverable error") - }).optional().describe("Flow-level error handling configuration") -}); -external_exports.object({ - flowName: external_exports.string().describe("Flow machine name"), - version: external_exports.number().int().min(1).describe("Version number"), - definition: FlowSchema.describe("Complete flow definition snapshot"), - createdAt: external_exports.string().datetime().describe("When this version was created"), - createdBy: external_exports.string().optional().describe("User who created this version"), - changeNote: external_exports.string().optional().describe("Description of what changed in this version") -}); -var ExecutionStatus = external_exports.enum([ - "pending", - // Queued, not yet started - "running", - // Currently executing - "paused", - // Paused at a wait/checkpoint node - "completed", - // Successfully finished - "failed", - // Terminated with error - "cancelled", - // Manually cancelled - "timed_out", - // Exceeded max execution time - "retrying" - // Failed and retrying -]); -var ExecutionStepLogSchema = external_exports.object({ - nodeId: external_exports.string().describe("Node ID that was executed"), - nodeType: external_exports.string().describe('Node action type (e.g., "decision", "http_request")'), - nodeLabel: external_exports.string().optional().describe("Human-readable node label"), - status: external_exports.enum(["success", "failure", "skipped"]).describe("Step execution result"), - startedAt: external_exports.string().datetime().describe("When the step started"), - completedAt: external_exports.string().datetime().optional().describe("When the step completed"), - durationMs: external_exports.number().int().min(0).optional().describe("Step execution duration in milliseconds"), - input: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Input data passed to the node"), - output: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Output data produced by the node"), - error: external_exports.object({ - code: external_exports.string().describe("Error code"), - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Stack trace") - }).optional().describe("Error details if step failed"), - retryAttempt: external_exports.number().int().min(0).optional().describe("Retry attempt number (0 = first try)") -}); -var ExecutionLogSchema = external_exports.object({ - /** Unique execution ID */ - id: external_exports.string().describe("Execution instance ID"), - /** Flow reference */ - flowName: external_exports.string().describe("Machine name of the executed flow"), - flowVersion: external_exports.number().int().optional().describe("Version of the flow that was executed"), - /** Execution status */ - status: ExecutionStatus.describe("Current execution status"), - /** Trigger context */ - trigger: external_exports.object({ - type: external_exports.string().describe('Trigger type (e.g., "record_change", "schedule", "api", "manual")'), - recordId: external_exports.string().optional().describe("Triggering record ID"), - object: external_exports.string().optional().describe("Triggering object name"), - userId: external_exports.string().optional().describe("User who triggered the execution"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional trigger context") - }).describe("What triggered this execution"), - /** Step-by-step execution history */ - steps: external_exports.array(ExecutionStepLogSchema).describe("Ordered list of executed steps"), - /** Execution variables snapshot */ - variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Final state of flow variables"), - /** Timing */ - startedAt: external_exports.string().datetime().describe("Execution start timestamp"), - completedAt: external_exports.string().datetime().optional().describe("Execution completion timestamp"), - durationMs: external_exports.number().int().min(0).optional().describe("Total execution duration in milliseconds"), - /** Context */ - runAs: external_exports.enum(["system", "user"]).optional().describe("Execution context identity"), - tenantId: external_exports.string().optional().describe("Tenant ID for multi-tenant isolation") -}); -var ExecutionErrorSeverity = external_exports.enum([ - "warning", - // Non-fatal issue (e.g., deprecated node type) - "error", - // Node-level failure (may be retried) - "critical" - // Flow-level failure (execution terminated) -]); -external_exports.object({ - id: external_exports.string().describe("Error record ID"), - executionId: external_exports.string().describe("Parent execution ID"), - nodeId: external_exports.string().optional().describe("Node where the error occurred"), - severity: ExecutionErrorSeverity.describe("Error severity level"), - code: external_exports.string().describe("Machine-readable error code"), - message: external_exports.string().describe("Human-readable error message"), - stack: external_exports.string().optional().describe("Stack trace for debugging"), - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional diagnostic context (input data, config snapshot)"), - timestamp: external_exports.string().datetime().describe("When the error occurred"), - retryable: external_exports.boolean().default(false).describe("Whether this error can be retried"), - resolvedAt: external_exports.string().datetime().optional().describe("When the error was resolved (e.g., after successful retry)") -}); -external_exports.object({ - /** Unique checkpoint ID */ - id: external_exports.string().describe("Checkpoint ID"), - /** Execution reference */ - executionId: external_exports.string().describe("Parent execution ID"), - flowName: external_exports.string().describe("Flow machine name"), - /** State snapshot */ - currentNodeId: external_exports.string().describe("Node ID where execution is paused"), - variables: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Flow variable state at checkpoint"), - completedNodeIds: external_exports.array(external_exports.string()).describe("List of node IDs already executed"), - /** Timing */ - createdAt: external_exports.string().datetime().describe("Checkpoint creation timestamp"), - expiresAt: external_exports.string().datetime().optional().describe("Checkpoint expiration (auto-cleanup)"), - /** Reason */ - reason: external_exports.enum(["wait", "screen_input", "approval", "error", "manual_pause", "parallel_join", "boundary_event"]).describe("Why the execution was checkpointed") -}); -external_exports.object({ - /** Maximum concurrent executions of this flow */ - maxConcurrent: external_exports.number().int().min(1).default(1).describe("Maximum number of concurrent executions allowed"), - /** What to do when max concurrency is reached */ - onConflict: external_exports.enum(["queue", "reject", "cancel_existing"]).default("queue").describe("queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance"), - /** Lock scope for concurrency */ - lockScope: external_exports.enum(["global", "per_record", "per_user"]).default("global").describe("Scope of the concurrency lock"), - /** Queue timeout (only when onConflict is "queue") */ - queueTimeoutMs: external_exports.number().int().min(0).optional().describe("Maximum time to wait in queue before timing out (ms)") -}); -external_exports.object({ - /** Unique schedule ID */ - id: external_exports.string().describe("Schedule instance ID"), - /** Flow reference */ - flowName: external_exports.string().describe("Flow machine name"), - /** Schedule configuration */ - cronExpression: external_exports.string().describe('Cron expression (e.g., "0 9 * * MON-FRI")'), - timezone: external_exports.string().default("UTC").describe("IANA timezone for cron evaluation"), - /** Runtime state */ - status: external_exports.enum(["active", "paused", "disabled", "expired"]).default("active").describe("Current schedule status"), - nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution timestamp"), - lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp"), - lastExecutionId: external_exports.string().optional().describe("Execution ID of the last run"), - lastRunStatus: ExecutionStatus.optional().describe("Status of the last run"), - /** Execution tracking */ - totalRuns: external_exports.number().int().min(0).default(0).describe("Total number of executions"), - consecutiveFailures: external_exports.number().int().min(0).default(0).describe("Consecutive failed executions"), - /** Bounds */ - startDate: external_exports.string().datetime().optional().describe("Schedule effective start date"), - endDate: external_exports.string().datetime().optional().describe("Schedule expiration date"), - maxRuns: external_exports.number().int().min(1).optional().describe("Maximum total executions before auto-disable"), - /** Metadata */ - createdAt: external_exports.string().datetime().describe("Schedule creation timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - createdBy: external_exports.string().optional().describe("User who created the schedule") -}); -var AutomationFlowPathParamsSchema = external_exports.object({ - name: external_exports.string().describe("Flow machine name (snake_case)") -}); -var AutomationRunPathParamsSchema = AutomationFlowPathParamsSchema.extend({ - runId: external_exports.string().describe("Execution run ID") -}); -var ListFlowsRequestSchema = external_exports.object({ - status: external_exports.enum(["draft", "active", "obsolete", "invalid"]).optional().describe("Filter by flow status"), - type: external_exports.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).optional().describe("Filter by flow type"), - limit: external_exports.number().int().min(1).max(100).default(50).describe("Maximum number of flows to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination") -}); -var FlowSummarySchema = external_exports.object({ - name: external_exports.string().describe("Flow machine name"), - label: external_exports.string().describe("Flow display label"), - type: external_exports.string().describe("Flow type"), - status: external_exports.string().describe("Flow deployment status"), - version: external_exports.number().int().describe("Flow version number"), - enabled: external_exports.boolean().describe("Whether the flow is enabled for execution"), - nodeCount: external_exports.number().int().optional().describe("Number of nodes in the flow"), - lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp") -}); -var ListFlowsResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - flows: external_exports.array(FlowSummarySchema).describe("Flow summaries"), - total: external_exports.number().int().optional().describe("Total matching flows"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more flows are available") - }) -}); -var GetFlowResponseSchema = BaseResponseSchema.extend({ - data: FlowSchema.describe("Full flow definition") -}); -var CreateFlowResponseSchema = BaseResponseSchema.extend({ - data: FlowSchema.describe("The created flow definition") -}); -var UpdateFlowRequestSchema = AutomationFlowPathParamsSchema.extend({ - definition: FlowSchema.partial().describe("Partial flow definition to update") -}); -var UpdateFlowResponseSchema = BaseResponseSchema.extend({ - data: FlowSchema.describe("The updated flow definition") -}); -var DeleteFlowResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - name: external_exports.string().describe("Name of the deleted flow"), - deleted: external_exports.boolean().describe("Whether the flow was deleted") - }) -}); -var TriggerFlowRequestSchema = AutomationFlowPathParamsSchema.extend({ - record: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record that triggered the automation"), - object: external_exports.string().optional().describe("Object name the record belongs to"), - event: external_exports.string().optional().describe("Trigger event type"), - userId: external_exports.string().optional().describe("User who triggered the automation"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional contextual data") -}); -var TriggerFlowResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - success: external_exports.boolean().describe("Whether the automation completed successfully"), - output: external_exports.unknown().optional().describe("Output data from the automation"), - error: external_exports.string().optional().describe("Error message if execution failed"), - durationMs: external_exports.number().optional().describe("Execution duration in milliseconds") - }) -}); -var ToggleFlowRequestSchema = AutomationFlowPathParamsSchema.extend({ - enabled: external_exports.boolean().describe("Whether to enable (true) or disable (false) the flow") -}); -var ToggleFlowResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - name: external_exports.string().describe("Flow name"), - enabled: external_exports.boolean().describe("New enabled state") - }) -}); -var ListRunsRequestSchema = AutomationFlowPathParamsSchema.extend({ - status: external_exports.enum(["pending", "running", "paused", "completed", "failed", "cancelled", "timed_out", "retrying"]).optional().describe("Filter by execution status"), - limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of runs to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination") -}); -var ListRunsResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - runs: external_exports.array(ExecutionLogSchema).describe("Execution run logs"), - total: external_exports.number().int().optional().describe("Total matching runs"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more runs are available") - }) -}); -var GetRunResponseSchema = BaseResponseSchema.extend({ - data: ExecutionLogSchema.describe("Full execution log with step details") -}); -var AutomationApiErrorCode = external_exports.enum([ - "flow_not_found", - "flow_already_exists", - "flow_validation_failed", - "flow_disabled", - "execution_not_found", - "execution_failed", - "execution_timeout", - "node_executor_not_found", - "concurrent_execution_limit" -]); -var MetadataChangeTypeSchema = external_exports.enum([ - "added", - // New metadata item added in new version - "modified", - // Existing metadata item modified - "removed", - // Metadata item removed in new version - "renamed" - // Metadata item renamed -]).describe("Type of metadata change between package versions"); -var MetadataDiffItemSchema = external_exports.object({ - /** Metadata type (e.g. "object", "view", "flow") */ - type: external_exports.string().describe("Metadata type"), - /** Metadata name */ - name: external_exports.string().describe("Metadata name"), - /** Type of change */ - changeType: MetadataChangeTypeSchema.describe("Category of metadata modification (added, modified, removed, or renamed)"), - /** Whether this change has potential conflicts with customizations */ - hasConflict: external_exports.boolean().default(false).describe("Whether this change may conflict with customizations"), - /** Human-readable summary of the change */ - summary: external_exports.string().optional().describe("Human-readable change summary"), - /** Previous name (for renames) */ - previousName: external_exports.string().optional().describe("Previous name if renamed") -}).describe("Single metadata change between package versions"); -var UpgradeImpactLevelSchema = external_exports.enum([ - "none", - // No impact, seamless upgrade - "low", - // Minor changes, no user action needed - "medium", - // Some changes that may affect workflows - "high", - // Significant changes, user review recommended - "critical" - // Breaking changes, manual intervention required -]).describe("Severity of upgrade impact"); -var UpgradePlanSchema = external_exports.object({ - /** Package being upgraded */ - packageId: external_exports.string().describe("Package identifier"), - /** Current installed version */ - fromVersion: external_exports.string().describe("Currently installed version"), - /** Target version to upgrade to */ - toVersion: external_exports.string().describe("Target upgrade version"), - /** Overall impact level */ - impactLevel: UpgradeImpactLevelSchema.describe("Severity assessment from none (seamless) to critical (breaking changes)"), - /** List of all metadata changes between versions */ - changes: external_exports.array(MetadataDiffItemSchema).describe("All metadata changes"), - /** Number of customer customizations that may be affected */ - affectedCustomizations: external_exports.number().int().min(0).default(0).describe("Count of customizations that may be affected"), - /** Whether any migration scripts need to run */ - requiresMigration: external_exports.boolean().default(false).describe("Whether data migration scripts are needed"), - /** Migration script paths (relative to package root) */ - migrationScripts: external_exports.array(external_exports.string()).optional().describe("Paths to migration scripts"), - /** Dependencies that also need upgrading */ - dependencyUpgrades: external_exports.array(external_exports.object({ - packageId: external_exports.string(), - fromVersion: external_exports.string(), - toVersion: external_exports.string() - })).optional().describe("Dependent packages that also need upgrading"), - /** Estimated upgrade duration in seconds */ - estimatedDuration: external_exports.number().int().min(0).optional().describe("Estimated upgrade duration in seconds"), - /** Human-readable summary */ - summary: external_exports.string().optional().describe("Human-readable upgrade summary") -}).describe("Upgrade analysis plan generated before execution"); -external_exports.object({ - /** Snapshot ID (UUID) */ - id: external_exports.string().describe("Snapshot identifier"), - /** Package being upgraded */ - packageId: external_exports.string().describe("Package identifier"), - /** Version being upgraded from */ - fromVersion: external_exports.string().describe("Version before upgrade"), - /** Version being upgraded to */ - toVersion: external_exports.string().describe("Target upgrade version"), - /** Tenant ID */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** Complete manifest of the old package version */ - previousManifest: ManifestSchema.describe("Complete manifest of the previous package version"), - /** - * Snapshot of all metadata records owned by this package. - * Stored as array of { type, name, metadata } tuples. - */ - metadataSnapshot: external_exports.array(external_exports.object({ - type: external_exports.string(), - name: external_exports.string(), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()) - })).describe("Snapshot of all package metadata"), - /** - * Snapshot of all customer customizations (overlays) for this package's metadata. - */ - customizationSnapshot: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Snapshot of customer customizations"), - /** When the snapshot was created */ - createdAt: external_exports.string().datetime().describe("Snapshot creation timestamp"), - /** Expiry time for snapshot cleanup */ - expiresAt: external_exports.string().datetime().optional().describe("Snapshot expiry timestamp") -}).describe("Pre-upgrade state snapshot for rollback capability"); -external_exports.object({ - /** Package ID to upgrade */ - packageId: external_exports.string().describe("Package ID to upgrade"), - /** Target version (if omitted, upgrades to latest) */ - targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), - /** New manifest for the target version */ - manifest: ManifestSchema.optional().describe("New manifest (if installing from local)"), - /** Whether to create a pre-upgrade snapshot */ - createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), - /** Merge strategy for handling customizations */ - mergeStrategy: external_exports.enum([ - "keep-custom", - "accept-incoming", - "three-way-merge" - ]).default("three-way-merge").describe("How to handle customer customizations"), - /** Whether to run in dry-run mode (preview only, no changes) */ - dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), - /** Whether to skip pre-upgrade validation */ - skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") -}).describe("Upgrade package request"); -var UpgradePhaseSchema = external_exports.enum([ - "pending", - // Upgrade requested but not started - "analyzing", - // Generating upgrade plan - "snapshot", - // Creating pre-upgrade snapshot - "executing", - // Applying metadata changes - "migrating", - // Running migration scripts - "validating", - // Post-upgrade validation - "completed", - // Upgrade completed successfully - "failed", - // Upgrade failed - "rolling-back", - // Rollback in progress - "rolled-back" - // Rollback completed -]).describe("Current phase of the upgrade process"); -external_exports.object({ - /** Whether the upgrade was successful */ - success: external_exports.boolean().describe("Whether the upgrade succeeded"), - /** Current upgrade phase */ - phase: UpgradePhaseSchema.describe("Current upgrade phase"), - /** The upgrade plan that was executed */ - plan: UpgradePlanSchema.optional().describe("Upgrade plan"), - /** Snapshot ID for rollback */ - snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), - /** Merge conflicts that need manual resolution (if any) */ - conflicts: external_exports.array(external_exports.object({ - path: external_exports.string(), - baseValue: external_exports.unknown(), - incomingValue: external_exports.unknown(), - customValue: external_exports.unknown() - })).optional().describe("Unresolved merge conflicts"), - /** Error message (if failed) */ - errorMessage: external_exports.string().optional().describe("Error message if upgrade failed"), - /** Human-readable summary */ - message: external_exports.string().optional().describe("Human-readable status message") -}).describe("Upgrade package response"); -external_exports.object({ - /** Package ID to rollback */ - packageId: external_exports.string().describe("Package ID to rollback"), - /** Snapshot ID to restore from */ - snapshotId: external_exports.string().describe("Snapshot ID to restore from"), - /** Whether to also rollback customizations */ - rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") -}).describe("Rollback package request"); -external_exports.object({ - /** Whether the rollback was successful */ - success: external_exports.boolean().describe("Whether the rollback succeeded"), - /** Restored version */ - restoredVersion: external_exports.string().optional().describe("Version restored to"), - /** Message */ - message: external_exports.string().optional().describe("Rollback status message") -}).describe("Rollback package response"); -var MetadataCategoryEnum = external_exports.enum([ - "objects", - "views", - "pages", - "flows", - "dashboards", - "permissions", - "agents", - "reports", - "actions", - "translations", - "themes", - "datasets", - "apis", - "triggers", - "workflows" -]).describe("Metadata category within the artifact"); -var ArtifactFileEntrySchema = external_exports.object({ - /** Relative path within the artifact (e.g. "metadata/objects/account.object.json") */ - path: external_exports.string().describe("Relative file path within the artifact"), - /** File size in bytes */ - size: external_exports.number().int().nonnegative().describe("File size in bytes"), - /** Metadata category (if under metadata/) */ - category: MetadataCategoryEnum.optional().describe("Metadata category this file belongs to") -}).describe("A single file entry within the artifact"); -var ArtifactChecksumSchema = external_exports.object({ - /** Hash algorithm used (default: SHA256) */ - algorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm used for checksums"), - /** Map of relative file paths to their hash values */ - files: external_exports.record(external_exports.string(), external_exports.string().regex(/^[a-f0-9]+$/)).describe("File path to hash value mapping") -}).describe("Checksum manifest for artifact integrity verification"); -var ArtifactSignatureSchema = external_exports.object({ - /** Signature algorithm */ - algorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).default("RSA-SHA256").describe("Signing algorithm used"), - /** Public key reference (URL or fingerprint) for verification */ - publicKeyRef: external_exports.string().describe("Public key reference (URL or fingerprint) for signature verification"), - /** Base64-encoded signature value */ - signature: external_exports.string().describe("Base64-encoded digital signature"), - /** Timestamp of when the artifact was signed */ - signedAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp of when the artifact was signed"), - /** Signer identity (publisher ID or email) */ - signedBy: external_exports.string().optional().describe("Identity of the signer (publisher ID or email)") -}).describe("Digital signature for artifact authenticity verification"); -var PackageArtifactSchema = external_exports.object({ - /** Artifact format version (for forward compatibility) */ - formatVersion: external_exports.string().regex(/^\d+\.\d+$/).default("1.0").describe('Artifact format version (e.g. "1.0")'), - /** Package ID from the manifest */ - packageId: external_exports.string().describe("Package identifier from manifest"), - /** Package version from the manifest */ - version: external_exports.string().describe("Package version from manifest"), - /** Artifact format */ - format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format of the artifact"), - /** Total artifact size in bytes */ - size: external_exports.number().int().positive().optional().describe("Total artifact file size in bytes"), - /** Build timestamp */ - builtAt: external_exports.string().datetime().describe("ISO 8601 timestamp of when the artifact was built"), - /** Build tool and version that produced this artifact */ - builtWith: external_exports.string().optional().describe('Build tool identifier (e.g. "os-cli@3.2.0")'), - /** File listing within the artifact */ - files: external_exports.array(ArtifactFileEntrySchema).optional().describe("List of files contained in the artifact"), - /** Metadata categories present in the artifact */ - metadataCategories: external_exports.array(MetadataCategoryEnum).optional().describe("Metadata categories included in this artifact"), - /** Integrity checksums for all files */ - checksums: ArtifactChecksumSchema.optional().describe("SHA256 checksums for artifact integrity verification"), - /** Digital signature for authenticity */ - signature: ArtifactSignatureSchema.optional().describe("Digital signature for artifact authenticity verification") -}).describe("Package artifact structure and metadata"); -var PublisherVerificationSchema = external_exports.enum([ - "unverified", - // Not yet verified - "pending", - // Verification in progress - "verified", - // Identity verified by platform - "trusted", - // Trusted publisher (track record of quality) - "partner" - // Official platform partner -]).describe("Publisher verification status"); -external_exports.object({ - /** Publisher unique identifier */ - id: external_exports.string().describe("Publisher ID"), - /** Display name */ - name: external_exports.string().describe("Publisher display name"), - /** Publisher type */ - type: external_exports.enum(["individual", "organization"]).describe("Publisher type"), - /** Verification status */ - verification: PublisherVerificationSchema.default("unverified").describe("Publisher verification status"), - /** Contact email */ - email: external_exports.string().email().optional().describe("Contact email"), - /** Website URL */ - website: external_exports.string().url().optional().describe("Publisher website"), - /** Organization logo URL */ - logoUrl: external_exports.string().url().optional().describe("Publisher logo URL"), - /** Short description/bio */ - description: external_exports.string().optional().describe("Publisher description"), - /** Registration date */ - registeredAt: external_exports.string().datetime().optional().describe("Publisher registration timestamp") -}).describe("Developer or organization that publishes packages"); -var ArtifactReferenceSchema = external_exports.object({ - /** Artifact download URL */ - url: external_exports.string().url().describe("Artifact download URL"), - /** SHA256 integrity checksum */ - sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).describe("SHA256 checksum"), - /** File size in bytes */ - size: external_exports.number().int().positive().describe("Artifact size in bytes"), - /** Artifact format */ - format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Artifact format"), - /** Upload timestamp */ - uploadedAt: external_exports.string().datetime().describe("Upload timestamp") -}).describe("Reference to a downloadable package artifact"); -external_exports.object({ - /** Pre-signed or direct download URL */ - downloadUrl: external_exports.string().url().describe("Artifact download URL (may be pre-signed)"), - /** SHA256 checksum for download verification */ - sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).describe("SHA256 checksum for verification"), - /** File size in bytes */ - size: external_exports.number().int().positive().describe("Artifact size in bytes"), - /** Artifact format */ - format: external_exports.enum(["tgz", "zip"]).describe("Artifact format"), - /** URL expiration time (for pre-signed URLs) */ - expiresAt: external_exports.string().datetime().optional().describe("URL expiration timestamp for pre-signed URLs") -}).describe("Artifact download response with integrity metadata"); -var MarketplaceCategorySchema = external_exports.enum([ - "crm", - // Customer Relationship Management - "erp", - // Enterprise Resource Planning - "hr", - // Human Resources - "finance", - // Finance & Accounting - "project", - // Project Management - "collaboration", - // Collaboration & Communication - "analytics", - // Analytics & Reporting - "integration", - // Integrations & Connectors - "automation", - // Automation & Workflows - "ai", - // AI & Machine Learning - "security", - // Security & Compliance - "developer-tools", - // Developer Tools - "ui-theme", - // UI Themes & Appearance - "storage", - // Storage & Drivers - "other" - // Other / Uncategorized -]).describe("Marketplace package category"); -var ListingStatusSchema = external_exports.enum([ - "draft", - // Not yet submitted - "submitted", - // Submitted for review - "in-review", - // Under review - "approved", - // Approved, ready to publish - "published", - // Live on marketplace - "rejected", - // Review rejected - "suspended", - // Suspended by platform (policy violation) - "deprecated", - // Deprecated by publisher - "unlisted" - // Available by direct link only -]).describe("Marketplace listing status"); -var PricingModelSchema = external_exports.enum([ - "free", - // Free to install - "freemium", - // Free with paid premium features - "paid", - // Requires purchase - "subscription", - // Recurring subscription - "usage-based", - // Pay per usage - "contact-sales" - // Enterprise pricing, contact for quote -]).describe("Package pricing model"); -var MarketplaceListingSchema = external_exports.object({ - /** Listing ID (matches package ID) */ - id: external_exports.string().describe("Listing ID (matches package manifest ID)"), - /** Package ID (reverse domain notation) */ - packageId: external_exports.string().describe("Package identifier"), - /** Publisher information */ - publisherId: external_exports.string().describe("Publisher ID"), - /** Current listing status */ - status: ListingStatusSchema.default("draft").describe("Publication state: draft, published, under-review, suspended, deprecated, or unlisted"), - /** Display name */ - name: external_exports.string().describe("Display name"), - /** Tagline (short description for cards/search results) */ - tagline: external_exports.string().max(120).optional().describe("Short tagline (max 120 chars)"), - /** Full description (supports Markdown) */ - description: external_exports.string().optional().describe("Full description (Markdown)"), - /** Category */ - category: MarketplaceCategorySchema.describe("Package category"), - /** Additional tags for search discovery */ - tags: external_exports.array(external_exports.string()).optional().describe("Search tags"), - /** Icon/logo URL */ - iconUrl: external_exports.string().url().optional().describe("Package icon URL"), - /** Screenshot URLs */ - screenshots: external_exports.array(external_exports.object({ - url: external_exports.string().url(), - caption: external_exports.string().optional() - })).optional().describe("Screenshots"), - /** Documentation URL */ - documentationUrl: external_exports.string().url().optional().describe("Documentation URL"), - /** Support URL */ - supportUrl: external_exports.string().url().optional().describe("Support URL"), - /** Source repository URL (if open source) */ - repositoryUrl: external_exports.string().url().optional().describe("Source repository URL"), - /** Pricing model */ - pricing: PricingModelSchema.default("free").describe("Pricing model"), - /** Price in cents (if paid) */ - priceInCents: external_exports.number().int().min(0).optional().describe("Price in cents (e.g. 999 = $9.99)"), - /** Latest published version */ - latestVersion: external_exports.string().describe("Latest published version"), - /** Minimum platform version required */ - minPlatformVersion: external_exports.string().optional().describe("Minimum ObjectStack platform version"), - /** Available versions for installation */ - versions: external_exports.array(external_exports.object({ - version: external_exports.string().describe("Version string"), - releaseDate: external_exports.string().datetime().describe("Release date"), - releaseNotes: external_exports.string().optional().describe("Release notes"), - minPlatformVersion: external_exports.string().optional().describe("Minimum platform version"), - deprecated: external_exports.boolean().default(false).describe("Whether this version is deprecated"), - /** Artifact reference for this version */ - artifact: ArtifactReferenceSchema.optional().describe("Downloadable artifact for this version") - })).optional().describe("Published versions"), - /** Aggregate statistics */ - stats: external_exports.object({ - totalInstalls: external_exports.number().int().min(0).default(0).describe("Total installs"), - activeInstalls: external_exports.number().int().min(0).default(0).describe("Active installs"), - averageRating: external_exports.number().min(0).max(5).optional().describe("Average user rating (0-5)"), - totalRatings: external_exports.number().int().min(0).default(0).describe("Total ratings count"), - totalReviews: external_exports.number().int().min(0).default(0).describe("Total reviews count") - }).optional().describe("Aggregate marketplace statistics"), - /** First published date */ - publishedAt: external_exports.string().datetime().optional().describe("First published timestamp"), - /** Last updated date */ - updatedAt: external_exports.string().datetime().optional().describe("Last updated timestamp") -}).describe("Public-facing package listing on the marketplace"); -external_exports.object({ - /** Submission ID */ - id: external_exports.string().describe("Submission ID"), - /** Package ID */ - packageId: external_exports.string().describe("Package identifier"), - /** Version being submitted */ - version: external_exports.string().describe("Version being submitted"), - /** Publisher ID */ - publisherId: external_exports.string().describe("Publisher submitting"), - /** Submission status */ - status: external_exports.enum([ - "pending", - // Awaiting review - "scanning", - // Automated scan in progress - "in-review", - // Under manual review - "changes-requested", - // Reviewer requests changes - "approved", - // Approved for publishing - "rejected" - // Rejected - ]).default("pending").describe("Review status"), - /** - * Package artifact URL or reference. - * Points to the built package bundle for review. - */ - artifactUrl: external_exports.string().describe("Package artifact URL for review"), - /** Release notes for this version */ - releaseNotes: external_exports.string().optional().describe("Release notes for this version"), - /** Whether this is the first submission (new listing) vs version update */ - isNewListing: external_exports.boolean().default(false).describe("Whether this is a new listing submission"), - /** Automated scan results */ - scanResults: external_exports.object({ - /** Whether automated scan passed */ - passed: external_exports.boolean(), - /** Security scan score (0-100) */ - securityScore: external_exports.number().min(0).max(100).optional(), - /** Compatibility check passed */ - compatibilityCheck: external_exports.boolean().optional(), - /** Issues found during scan */ - issues: external_exports.array(external_exports.object({ - severity: external_exports.enum(["critical", "high", "medium", "low", "info"]), - message: external_exports.string(), - file: external_exports.string().optional(), - line: external_exports.number().optional() - })).optional() - }).optional().describe("Automated scan results"), - /** Reviewer notes (from platform reviewer) */ - reviewerNotes: external_exports.string().optional().describe("Notes from the platform reviewer"), - /** Submitted timestamp */ - submittedAt: external_exports.string().datetime().optional().describe("Submission timestamp"), - /** Review completed timestamp */ - reviewedAt: external_exports.string().datetime().optional().describe("Review completion timestamp") -}).describe("Developer submission of a package version for review"); -external_exports.object({ - /** Search query string */ - query: external_exports.string().optional().describe("Full-text search query"), - /** Filter by category */ - category: MarketplaceCategorySchema.optional().describe("Filter by category"), - /** Filter by tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), - /** Filter by pricing model */ - pricing: PricingModelSchema.optional().describe("Filter by pricing model"), - /** Filter by publisher verification level */ - publisherVerification: PublisherVerificationSchema.optional().describe("Filter by publisher verification level"), - /** Sort by */ - sortBy: external_exports.enum([ - "relevance", - // Best match (default for search) - "popularity", - // Most installs - "rating", - // Highest rated - "newest", - // Most recently published - "updated", - // Most recently updated - "name" - // Alphabetical - ]).default("relevance").describe("Sort field"), - /** Sort direction */ - sortDirection: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction"), - /** Pagination: page number */ - page: external_exports.number().int().min(1).default(1).describe("Page number"), - /** Pagination: items per page */ - pageSize: external_exports.number().int().min(1).max(100).default(20).describe("Items per page"), - /** Filter by minimum platform version compatibility */ - platformVersion: external_exports.string().optional().describe("Filter by platform version compatibility") -}).describe("Marketplace search request"); -external_exports.object({ - /** Search results */ - items: external_exports.array(MarketplaceListingSchema).describe("Search result listings"), - /** Total count (for pagination) */ - total: external_exports.number().int().min(0).describe("Total matching results"), - /** Current page */ - page: external_exports.number().int().min(1).describe("Current page number"), - /** Items per page */ - pageSize: external_exports.number().int().min(1).describe("Items per page"), - /** Facets for filtering */ - facets: external_exports.object({ - categories: external_exports.array(external_exports.object({ - category: MarketplaceCategorySchema, - count: external_exports.number().int().min(0) - })).optional(), - pricing: external_exports.array(external_exports.object({ - model: PricingModelSchema, - count: external_exports.number().int().min(0) - })).optional() - }).optional().describe("Aggregation facets for refining search") -}).describe("Marketplace search response"); -external_exports.object({ - /** Listing ID to install */ - listingId: external_exports.string().describe("Marketplace listing ID"), - /** Specific version to install (defaults to latest) */ - version: external_exports.string().optional().describe("Version to install"), - /** License key (for paid packages) */ - licenseKey: external_exports.string().optional().describe("License key for paid packages"), - /** User-provided settings at install time */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), - /** Whether to enable immediately after install */ - enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), - /** Artifact reference (resolved from listing version, or provided directly) */ - artifactRef: ArtifactReferenceSchema.optional().describe("Artifact reference for direct installation"), - /** Tenant ID */ - tenantId: external_exports.string().optional().describe("Tenant identifier") -}).describe("Install from marketplace request"); -external_exports.object({ - /** Whether installation was successful */ - success: external_exports.boolean().describe("Whether installation succeeded"), - /** Installed package ID */ - packageId: external_exports.string().optional().describe("Installed package identifier"), - /** Installed version */ - version: external_exports.string().optional().describe("Installed version"), - /** Human-readable message */ - message: external_exports.string().optional().describe("Installation status message") -}).describe("Install from marketplace response"); -var PackagePathParamsSchema = external_exports.object({ - packageId: external_exports.string().describe("Package identifier") -}); -var ListInstalledPackagesRequestSchema = external_exports.object({ - /** Filter by package status */ - status: external_exports.enum(["installed", "disabled", "installing", "upgrading", "uninstalling", "error"]).optional().describe("Filter by package status"), - /** Filter by enabled state */ - enabled: external_exports.boolean().optional().describe("Filter by enabled state"), - /** Maximum number of packages to return */ - limit: external_exports.number().int().min(1).max(100).default(50).describe("Maximum number of packages to return"), - /** Cursor for pagination */ - cursor: external_exports.string().optional().describe("Cursor for pagination") -}).describe("List installed packages request"); -var ListInstalledPackagesResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - packages: external_exports.array(InstalledPackageSchema).describe("Installed packages"), - total: external_exports.number().int().optional().describe("Total matching packages"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more packages are available") - }) -}).describe("List installed packages response"); -var GetInstalledPackageResponseSchema = BaseResponseSchema.extend({ - data: InstalledPackageSchema.describe("Installed package details") -}).describe("Get installed package response"); -var PackageInstallRequestSchema = external_exports.object({ - /** Package manifest to install */ - manifest: ManifestSchema.describe("Package manifest to install"), - /** User-provided settings at install time */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), - /** Whether to enable immediately after install */ - enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), - /** Current platform version for compatibility verification */ - platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification"), - /** Artifact reference for the package (if installing from marketplace) */ - artifactRef: ArtifactReferenceSchema.optional().describe("Artifact reference for marketplace installation") -}).describe("Install package request"); -var PackageInstallResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - package: InstalledPackageSchema.describe("Installed package details"), - dependencyResolution: DependencyResolutionResultSchema.optional().describe("Dependency resolution result"), - namespaceConflicts: external_exports.array(external_exports.object({ - type: external_exports.literal("namespace_conflict").describe("Error type"), - requestedNamespace: external_exports.string().describe("Requested namespace"), - conflictingPackageId: external_exports.string().describe("Conflicting package ID"), - conflictingPackageName: external_exports.string().describe("Conflicting package name"), - suggestion: external_exports.string().optional().describe("Suggested alternative") - })).optional().describe("Namespace conflicts detected"), - message: external_exports.string().optional().describe("Installation status message") - }) -}).describe("Install package response"); -var PackageUpgradeRequestSchema = external_exports.object({ - /** Package ID to upgrade */ - packageId: external_exports.string().describe("Package ID to upgrade"), - /** Target version (defaults to latest) */ - targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), - /** New manifest for the target version */ - manifest: ManifestSchema.optional().describe("New manifest for the target version"), - /** Whether to create a pre-upgrade snapshot */ - createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), - /** Merge strategy for handling customizations */ - mergeStrategy: external_exports.enum(["keep-custom", "accept-incoming", "three-way-merge"]).default("three-way-merge").describe("How to handle customer customizations"), - /** Preview upgrade without making changes */ - dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), - /** Skip pre-upgrade compatibility checks */ - skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") -}).describe("Upgrade package request"); -var PackageUpgradeResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - success: external_exports.boolean().describe("Whether the upgrade succeeded"), - phase: external_exports.string().describe("Current upgrade phase"), - plan: UpgradePlanSchema.optional().describe("Upgrade plan that was executed"), - snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), - conflicts: external_exports.array(external_exports.object({ - path: external_exports.string().describe("Conflict path"), - baseValue: external_exports.unknown().describe("Base value"), - incomingValue: external_exports.unknown().describe("Incoming value"), - customValue: external_exports.unknown().describe("Custom value") - })).optional().describe("Unresolved merge conflicts"), - errorMessage: external_exports.string().optional().describe("Error message if failed"), - message: external_exports.string().optional().describe("Human-readable status message") - }) -}).describe("Upgrade package response"); -var ResolveDependenciesRequestSchema = external_exports.object({ - /** Package manifest whose dependencies to resolve */ - manifest: ManifestSchema.describe("Package manifest to resolve dependencies for"), - /** Current platform version for compatibility checking */ - platformVersion: external_exports.string().optional().describe("Current platform version for compatibility filtering") -}).describe("Resolve dependencies request"); -var ResolveDependenciesResponseSchema = BaseResponseSchema.extend({ - data: DependencyResolutionResultSchema.describe("Dependency resolution result with topological sort") -}).describe("Resolve dependencies response"); -var UploadArtifactRequestSchema = external_exports.object({ - /** Artifact metadata */ - artifact: PackageArtifactSchema.describe("Package artifact metadata"), - /** SHA256 checksum of the uploaded file (for verification) */ - sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).optional().describe("SHA256 checksum of the uploaded file"), - /** Publisher authentication token */ - token: external_exports.string().optional().describe("Publisher authentication token"), - /** Release notes for this version */ - releaseNotes: external_exports.string().optional().describe("Release notes for this version") -}).describe("Upload artifact request"); -var UploadArtifactResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - /** Whether the upload succeeded */ - success: external_exports.boolean().describe("Whether the upload succeeded"), - /** Artifact reference for the uploaded package */ - artifactRef: ArtifactReferenceSchema.optional().describe("Artifact reference in the registry"), - /** Submission ID for review tracking */ - submissionId: external_exports.string().optional().describe("Marketplace submission ID for review tracking"), - /** Message */ - message: external_exports.string().optional().describe("Upload status message") - }) -}).describe("Upload artifact response"); -var PackageRollbackRequestSchema = PackagePathParamsSchema.extend({ - /** Snapshot ID to restore from */ - snapshotId: external_exports.string().describe("Snapshot ID to restore from"), - /** Whether to also rollback customizations */ - rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") -}).describe("Rollback package request"); -var PackageRollbackResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - success: external_exports.boolean().describe("Whether the rollback succeeded"), - restoredVersion: external_exports.string().optional().describe("Restored version"), - message: external_exports.string().optional().describe("Rollback status message") - }) -}).describe("Rollback package response"); -var UninstallPackageApiResponseSchema = BaseResponseSchema.extend({ - data: external_exports.object({ - packageId: external_exports.string().describe("Uninstalled package ID"), - success: external_exports.boolean().describe("Whether uninstall succeeded"), - message: external_exports.string().optional().describe("Uninstall status message") - }) -}).describe("Uninstall package response"); -var PackageApiErrorCode = external_exports.enum([ - "package_not_found", - "package_already_installed", - "version_not_found", - "dependency_conflict", - "namespace_conflict", - "platform_incompatible", - "artifact_invalid", - "checksum_mismatch", - "signature_invalid", - "upgrade_failed", - "rollback_failed", - "snapshot_not_found", - "upload_failed" -]); - -// ../../packages/core/dist/index.js -import nodePath from "path"; -var __defProp2 = Object.defineProperty; -var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); -}; -var isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null; -function getEnv(key, defaultValue) { - if (typeof process !== "undefined" && process.env) { - return process.env[key] || defaultValue; - } - try { - if (typeof globalThis !== "undefined" && globalThis.process?.env) { - return globalThis.process.env[key] || defaultValue; - } - } catch (e) { - } - return defaultValue; -} -function safeExit(code = 0) { - if (isNode) { - process.exit(code); - } -} -function getMemoryUsage() { - if (isNode) { - return process.memoryUsage(); - } - return { heapUsed: 0, heapTotal: 0 }; -} -var ObjectLogger = class _ObjectLogger { - // CommonJS require function for Node.js - constructor(config4 = {}) { - this.isNode = isNode; - this.config = { - name: config4.name, - level: config4.level ?? "info", - format: config4.format ?? (this.isNode ? "json" : "pretty"), - redact: config4.redact ?? ["password", "token", "secret", "key"], - sourceLocation: config4.sourceLocation ?? false, - file: config4.file, - rotation: config4.rotation ?? { - maxSize: "10m", - maxFiles: 5 - } - }; - if (this.isNode) { - this.initPinoLogger(); - } - } - /** - * Initialize Pino logger for Node.js - */ - async initPinoLogger() { - if (!this.isNode) return; - try { - const { createRequire } = await import("module"); - this.require = createRequire(import.meta.url); - const pino = this.require("pino"); - const pinoOptions = { - level: this.config.level, - redact: { - paths: this.config.redact, - censor: "***REDACTED***" - } - }; - if (this.config.name) { - pinoOptions.name = this.config.name; - } - const targets = []; - if (this.config.format === "pretty") { - let hasPretty = false; - try { - this.require.resolve("pino-pretty"); - hasPretty = true; - } catch (e) { - } - if (hasPretty) { - targets.push({ - target: "pino-pretty", - options: { - colorize: true, - translateTime: "SYS:standard", - ignore: "pid,hostname" - }, - level: this.config.level - }); - } else { - console.warn("[Logger] pino-pretty not found. Install it for pretty logging: pnpm add -D pino-pretty"); - targets.push({ - target: "pino/file", - options: { destination: 1 }, - level: this.config.level - }); - } - } else if (this.config.format === "json") { - targets.push({ - target: "pino/file", - options: { destination: 1 }, - // stdout - level: this.config.level - }); - } else { - targets.push({ - target: "pino/file", - options: { destination: 1 }, - level: this.config.level - }); - } - if (this.config.file) { - targets.push({ - target: "pino/file", - options: { - destination: this.config.file, - mkdir: true - }, - level: this.config.level - }); - } - if (targets.length > 0) { - pinoOptions.transport = targets.length === 1 ? targets[0] : { targets }; - } - this.pinoInstance = pino(pinoOptions); - this.pinoLogger = this.pinoInstance; - } catch (error49) { - console.warn("[Logger] Pino not available, falling back to console:", error49); - this.pinoLogger = null; - } - } - /** - * Redact sensitive keys from context object (for browser) - */ - redactSensitive(obj) { - if (!obj || typeof obj !== "object") return obj; - const redacted = Array.isArray(obj) ? [...obj] : { ...obj }; - for (const key in redacted) { - const lowerKey = key.toLowerCase(); - const shouldRedact = this.config.redact.some( - (pattern) => lowerKey.includes(pattern.toLowerCase()) - ); - if (shouldRedact) { - redacted[key] = "***REDACTED***"; - } else if (typeof redacted[key] === "object" && redacted[key] !== null) { - redacted[key] = this.redactSensitive(redacted[key]); - } - } - return redacted; - } - /** - * Format log entry for browser - */ - formatBrowserLog(level, message2, context) { - if (this.config.format === "json") { - return JSON.stringify({ - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - level, - message: message2, - ...context - }); - } - if (this.config.format === "text") { - const parts = [(/* @__PURE__ */ new Date()).toISOString(), level.toUpperCase(), message2]; - if (context && Object.keys(context).length > 0) { - parts.push(JSON.stringify(context)); - } - return parts.join(" | "); - } - const levelColors2 = { - debug: "\x1B[36m", - // Cyan - info: "\x1B[32m", - // Green - warn: "\x1B[33m", - // Yellow - error: "\x1B[31m", - // Red - fatal: "\x1B[35m", - // Magenta - silent: "" - }; - const reset = "\x1B[0m"; - const color = levelColors2[level] || ""; - let output = `${color}[${level.toUpperCase()}]${reset} ${message2}`; - if (context && Object.keys(context).length > 0) { - output += ` ${JSON.stringify(context, null, 2)}`; - } - return output; - } - /** - * Log using browser console - */ - logBrowser(level, message2, context, error49) { - const redactedContext = context ? this.redactSensitive(context) : void 0; - const mergedContext = error49 ? { ...redactedContext, error: { message: error49.message, stack: error49.stack } } : redactedContext; - const formatted = this.formatBrowserLog(level, message2, mergedContext); - const consoleMethod = level === "debug" ? "debug" : level === "info" ? "log" : level === "warn" ? "warn" : level === "error" || level === "fatal" ? "error" : "log"; - console[consoleMethod](formatted); - } - /** - * Public logging methods - */ - debug(message2, meta3) { - if (this.isNode && this.pinoLogger) { - this.pinoLogger.debug(meta3 || {}, message2); - } else { - this.logBrowser("debug", message2, meta3); - } - } - info(message2, meta3) { - if (this.isNode && this.pinoLogger) { - this.pinoLogger.info(meta3 || {}, message2); - } else { - this.logBrowser("info", message2, meta3); - } - } - warn(message2, meta3) { - if (this.isNode && this.pinoLogger) { - this.pinoLogger.warn(meta3 || {}, message2); - } else { - this.logBrowser("warn", message2, meta3); - } - } - error(message2, errorOrMeta, meta3) { - let error49; - let context = {}; - if (errorOrMeta instanceof Error) { - error49 = errorOrMeta; - context = meta3 || {}; - } else { - context = errorOrMeta || {}; - } - if (this.isNode && this.pinoLogger) { - const errorContext = error49 ? { err: error49, ...context } : context; - this.pinoLogger.error(errorContext, message2); - } else { - this.logBrowser("error", message2, context, error49); - } - } - fatal(message2, errorOrMeta, meta3) { - let error49; - let context = {}; - if (errorOrMeta instanceof Error) { - error49 = errorOrMeta; - context = meta3 || {}; - } else { - context = errorOrMeta || {}; - } - if (this.isNode && this.pinoLogger) { - const errorContext = error49 ? { err: error49, ...context } : context; - this.pinoLogger.fatal(errorContext, message2); - } else { - this.logBrowser("fatal", message2, context, error49); - } - } - /** - * Create a child logger with additional context - * Note: Child loggers share the parent's Pino instance - */ - child(context) { - const childLogger = new _ObjectLogger(this.config); - if (this.isNode && this.pinoInstance) { - childLogger.pinoLogger = this.pinoInstance.child(context); - childLogger.pinoInstance = this.pinoInstance; - } - return childLogger; - } - /** - * Set trace context for distributed tracing - */ - withTrace(traceId, spanId) { - return this.child({ traceId, spanId }); - } - /** - * Cleanup resources - */ - async destroy() { - if (this.pinoLogger && this.pinoLogger.flush) { - await new Promise((resolve2) => { - this.pinoLogger.flush(() => resolve2()); - }); - } - } - /** - * Compatibility method for console.log usage - */ - log(message2, ...args) { - this.info(message2, args.length > 0 ? { args } : void 0); - } -}; -function createLogger(config4) { - return new ObjectLogger(config4); -} -var PluginConfigValidator = class { - constructor(logger2) { - this.logger = logger2; - } - /** - * Validate plugin configuration against its Zod schema - * - * @param plugin - Plugin metadata with configSchema - * @param config - User-provided configuration - * @returns Validated and typed configuration - * @throws Error with detailed validation errors - */ - validatePluginConfig(plugin, config4) { - if (!plugin.configSchema) { - this.logger.debug(`Plugin ${plugin.name} has no config schema - skipping validation`); - return config4; - } - try { - const validatedConfig = plugin.configSchema.parse(config4); - this.logger.debug(`\u2705 Plugin config validated: ${plugin.name}`, { - plugin: plugin.name, - configKeys: Object.keys(config4 || {}).length - }); - return validatedConfig; - } catch (error49) { - if (error49 instanceof external_exports.ZodError) { - const formattedErrors = this.formatZodErrors(error49); - const errorMessage = [ - `Plugin ${plugin.name} configuration validation failed:`, - ...formattedErrors.map((e) => ` - ${e.path}: ${e.message}`) - ].join("\n"); - this.logger.error(errorMessage, void 0, { - plugin: plugin.name, - errors: formattedErrors - }); - throw new Error(errorMessage); - } - throw error49; - } - } - /** - * Validate partial configuration (for incremental updates) - * - * @param plugin - Plugin metadata - * @param partialConfig - Partial configuration to validate - * @returns Validated partial configuration - */ - validatePartialConfig(plugin, partialConfig) { - if (!plugin.configSchema) { - return partialConfig; - } - try { - const partialSchema = plugin.configSchema.partial(); - const validatedConfig = partialSchema.parse(partialConfig); - this.logger.debug(`\u2705 Partial config validated: ${plugin.name}`); - return validatedConfig; - } catch (error49) { - if (error49 instanceof external_exports.ZodError) { - const formattedErrors = this.formatZodErrors(error49); - const errorMessage = [ - `Plugin ${plugin.name} partial configuration validation failed:`, - ...formattedErrors.map((e) => ` - ${e.path}: ${e.message}`) - ].join("\n"); - throw new Error(errorMessage); - } - throw error49; - } - } - /** - * Get default configuration from schema - * - * @param plugin - Plugin metadata - * @returns Default configuration object - */ - getDefaultConfig(plugin) { - if (!plugin.configSchema) { - return void 0; - } - try { - const defaults = plugin.configSchema.parse({}); - this.logger.debug(`Default config extracted: ${plugin.name}`); - return defaults; - } catch (error49) { - this.logger.debug(`No default config available: ${plugin.name}`); - return void 0; - } - } - /** - * Check if configuration is valid without throwing - * - * @param plugin - Plugin metadata - * @param config - Configuration to check - * @returns True if valid, false otherwise - */ - isConfigValid(plugin, config4) { - if (!plugin.configSchema) { - return true; - } - const result = plugin.configSchema.safeParse(config4); - return result.success; - } - /** - * Get configuration errors without throwing - * - * @param plugin - Plugin metadata - * @param config - Configuration to check - * @returns Array of validation errors, or empty array if valid - */ - getConfigErrors(plugin, config4) { - if (!plugin.configSchema) { - return []; - } - const result = plugin.configSchema.safeParse(config4); - if (result.success) { - return []; - } - return this.formatZodErrors(result.error); - } - // Private methods - formatZodErrors(error49) { - return error49.issues.map((e) => ({ - path: e.path.join(".") || "root", - message: e.message - })); - } -}; -var PluginLoader = class { - constructor(logger2) { - this.loadedPlugins = /* @__PURE__ */ new Map(); - this.serviceFactories = /* @__PURE__ */ new Map(); - this.serviceInstances = /* @__PURE__ */ new Map(); - this.scopedServices = /* @__PURE__ */ new Map(); - this.creating = /* @__PURE__ */ new Set(); - this.logger = logger2; - this.configValidator = new PluginConfigValidator(logger2); - } - /** - * Set the plugin context for service factories - */ - setContext(context) { - this.context = context; - } - /** - * Get a synchronous service instance if it exists (Sync Helper) - */ - getServiceInstance(name) { - return this.serviceInstances.get(name); - } - /** - * Load a plugin asynchronously with validation - */ - async loadPlugin(plugin) { - const startTime = Date.now(); - try { - this.logger.info(`Loading plugin: ${plugin.name}`); - const metadata = this.toPluginMetadata(plugin); - this.validatePluginStructure(metadata); - const versionCheck = this.checkVersionCompatibility(metadata); - if (!versionCheck.compatible) { - throw new Error(`Version incompatible: ${versionCheck.message}`); - } - if (metadata.configSchema) { - this.validatePluginConfig(metadata); - } - if (metadata.signature) { - await this.verifyPluginSignature(metadata); - } - this.loadedPlugins.set(metadata.name, metadata); - const loadTime = Date.now() - startTime; - this.logger.info(`Plugin loaded: ${plugin.name} (${loadTime}ms)`); - return { - success: true, - plugin: metadata, - loadTime - }; - } catch (error49) { - this.logger.error(`Failed to load plugin: ${plugin.name}`, error49); - return { - success: false, - error: error49, - loadTime: Date.now() - startTime - }; - } - } - /** - * Register a service with factory function - */ - registerServiceFactory(registration) { - if (this.serviceFactories.has(registration.name)) { - throw new Error(`Service factory '${registration.name}' already registered`); - } - this.serviceFactories.set(registration.name, registration); - this.logger.debug(`Service factory registered: ${registration.name} (${registration.lifecycle})`); - } - /** - * Get or create a service instance based on lifecycle type - */ - async getService(name, scopeId) { - const registration = this.serviceFactories.get(name); - if (!registration) { - const instance = this.serviceInstances.get(name); - if (!instance) { - throw new Error(`Service '${name}' not found`); - } - return instance; - } - switch (registration.lifecycle) { - case "singleton": - return await this.getSingletonService(registration); - case "transient": - return await this.createTransientService(registration); - case "scoped": - if (!scopeId) { - throw new Error(`Scope ID required for scoped service '${name}'`); - } - return await this.getScopedService(registration, scopeId); - default: - throw new Error(`Unknown service lifecycle: ${registration.lifecycle}`); - } - } - /** - * Register a static service instance (legacy support) - */ - registerService(name, service) { - if (this.serviceInstances.has(name)) { - throw new Error(`Service '${name}' already registered`); - } - this.serviceInstances.set(name, service); - } - /** - * Replace an existing service instance. - * Used by optimization plugins to swap kernel internals. - * @throws Error if service does not exist - */ - replaceService(name, service) { - if (!this.hasService(name)) { - throw new Error(`Service '${name}' not found`); - } - this.serviceInstances.set(name, service); - } - /** - * Check if a service is registered (either as instance or factory) - */ - hasService(name) { - return this.serviceInstances.has(name) || this.serviceFactories.has(name); - } - /** - * Detect circular dependencies in service factories - * Note: This only detects cycles in service dependencies, not plugin dependencies. - * Plugin dependency cycles are detected in the kernel's resolveDependencies method. - */ - detectCircularDependencies() { - const cycles = []; - const visited = /* @__PURE__ */ new Set(); - const visiting = /* @__PURE__ */ new Set(); - const visit = (serviceName, path3 = []) => { - if (visiting.has(serviceName)) { - const cycle = [...path3, serviceName].join(" -> "); - cycles.push(cycle); - return; - } - if (visited.has(serviceName)) { - return; - } - visiting.add(serviceName); - const registration = this.serviceFactories.get(serviceName); - if (registration?.dependencies) { - for (const dep of registration.dependencies) { - visit(dep, [...path3, serviceName]); - } - } - visiting.delete(serviceName); - visited.add(serviceName); - }; - for (const serviceName of this.serviceFactories.keys()) { - visit(serviceName); - } - return cycles; - } - /** - * Check plugin health - */ - async checkPluginHealth(pluginName) { - const plugin = this.loadedPlugins.get(pluginName); - if (!plugin) { - return { - healthy: false, - message: "Plugin not found", - lastCheck: /* @__PURE__ */ new Date() - }; - } - if (!plugin.healthCheck) { - return { - healthy: true, - message: "No health check defined", - lastCheck: /* @__PURE__ */ new Date() - }; - } - try { - const status = await plugin.healthCheck(); - return { - ...status, - lastCheck: /* @__PURE__ */ new Date() - }; - } catch (error49) { - return { - healthy: false, - message: `Health check failed: ${error49.message}`, - lastCheck: /* @__PURE__ */ new Date() - }; - } - } - /** - * Clear scoped services for a scope - */ - clearScope(scopeId) { - this.scopedServices.delete(scopeId); - this.logger.debug(`Cleared scope: ${scopeId}`); - } - /** - * Get all loaded plugins - */ - getLoadedPlugins() { - return new Map(this.loadedPlugins); - } - // Private helper methods - toPluginMetadata(plugin) { - const metadata = plugin; - if (!metadata.version) { - metadata.version = "0.0.0"; - } - return metadata; - } - validatePluginStructure(plugin) { - if (!plugin.name) { - throw new Error("Plugin name is required"); - } - if (!plugin.init) { - throw new Error("Plugin init function is required"); - } - if (!this.isValidSemanticVersion(plugin.version)) { - throw new Error(`Invalid semantic version: ${plugin.version}`); - } - } - checkVersionCompatibility(plugin) { - const version3 = plugin.version; - if (!this.isValidSemanticVersion(version3)) { - return { - compatible: false, - pluginVersion: version3, - message: "Invalid semantic version format" - }; - } - return { - compatible: true, - pluginVersion: version3 - }; - } - isValidSemanticVersion(version3) { - const semverRegex = /^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/; - return semverRegex.test(version3); - } - validatePluginConfig(plugin, config4) { - if (!plugin.configSchema) { - return; - } - if (config4 === void 0) { - this.logger.debug(`Plugin ${plugin.name} has configuration schema (config validation postponed)`); - return; - } - this.configValidator.validatePluginConfig(plugin, config4); - } - async verifyPluginSignature(plugin) { - if (!plugin.signature) { - return; - } - this.logger.debug(`Plugin ${plugin.name} has signature (use PluginSignatureVerifier for verification)`); - } - async getSingletonService(registration) { - let instance = this.serviceInstances.get(registration.name); - if (!instance) { - instance = await this.createServiceInstance(registration); - this.serviceInstances.set(registration.name, instance); - this.logger.debug(`Singleton service created: ${registration.name}`); - } - return instance; - } - async createTransientService(registration) { - const instance = await this.createServiceInstance(registration); - this.logger.debug(`Transient service created: ${registration.name}`); - return instance; - } - async getScopedService(registration, scopeId) { - if (!this.scopedServices.has(scopeId)) { - this.scopedServices.set(scopeId, /* @__PURE__ */ new Map()); - } - const scope = this.scopedServices.get(scopeId); - let instance = scope.get(registration.name); - if (!instance) { - instance = await this.createServiceInstance(registration); - scope.set(registration.name, instance); - this.logger.debug(`Scoped service created: ${registration.name} (scope: ${scopeId})`); - } - return instance; - } - async createServiceInstance(registration) { - if (!this.context) { - throw new Error(`[PluginLoader] Context not set - cannot create service '${registration.name}'`); - } - if (this.creating.has(registration.name)) { - throw new Error(`Circular dependency detected: ${Array.from(this.creating).join(" -> ")} -> ${registration.name}`); - } - this.creating.add(registration.name); - try { - return await registration.factory(this.context); - } finally { - this.creating.delete(registration.name); - } - } -}; -function createMemoryCache() { - const store = /* @__PURE__ */ new Map(); - let hits = 0; - let misses = 0; - return { - _fallback: true, - _serviceName: "cache", - async get(key) { - const entry = store.get(key); - if (!entry || entry.expires && Date.now() > entry.expires) { - store.delete(key); - misses++; - return void 0; - } - hits++; - return entry.value; - }, - async set(key, value, ttl) { - store.set(key, { value, expires: ttl ? Date.now() + ttl * 1e3 : void 0 }); - }, - async delete(key) { - return store.delete(key); - }, - async has(key) { - return store.has(key); - }, - async clear() { - store.clear(); - }, - async stats() { - return { hits, misses, keyCount: store.size }; - } - }; -} -function createMemoryQueue() { - const handlers = /* @__PURE__ */ new Map(); - let msgId = 0; - return { - _fallback: true, - _serviceName: "queue", - async publish(queue, data) { - const id = `fallback-msg-${++msgId}`; - const fns = handlers.get(queue) ?? []; - for (const fn of fns) fn({ id, data, attempts: 1, timestamp: Date.now() }); - return id; - }, - async subscribe(queue, handler) { - handlers.set(queue, [...handlers.get(queue) ?? [], handler]); - }, - async unsubscribe(queue) { - handlers.delete(queue); - }, - async getQueueSize() { - return 0; - }, - async purge(queue) { - handlers.delete(queue); - } - }; -} -function createMemoryJob() { - const jobs = /* @__PURE__ */ new Map(); - return { - _fallback: true, - _serviceName: "job", - async schedule(name, schedule, handler) { - jobs.set(name, { schedule, handler }); - }, - async cancel(name) { - jobs.delete(name); - }, - async trigger(name, data) { - const job = jobs.get(name); - if (job?.handler) await job.handler({ jobId: name, data }); - }, - async getExecutions() { - return []; - }, - async listJobs() { - return [...jobs.keys()]; - } - }; -} -function resolveLocale(requestedLocale, availableLocales) { - if (availableLocales.length === 0) return void 0; - if (availableLocales.includes(requestedLocale)) return requestedLocale; - const lower = requestedLocale.toLowerCase(); - const caseMatch = availableLocales.find((l) => l.toLowerCase() === lower); - if (caseMatch) return caseMatch; - const baseLang = requestedLocale.split("-")[0].toLowerCase(); - const baseMatch = availableLocales.find((l) => l.toLowerCase() === baseLang); - if (baseMatch) return baseMatch; - const variantMatch = availableLocales.find((l) => l.split("-")[0].toLowerCase() === baseLang); - if (variantMatch) return variantMatch; - return void 0; -} -function createMemoryI18n() { - const translations = /* @__PURE__ */ new Map(); - let defaultLocale = "en"; - function resolveKey(data, key) { - const parts = key.split("."); - let current = data; - for (const part of parts) { - if (current == null || typeof current !== "object") return void 0; - current = current[part]; - } - return typeof current === "string" ? current : void 0; - } - function resolveTranslations(locale) { - if (translations.has(locale)) return translations.get(locale); - const resolved = resolveLocale(locale, [...translations.keys()]); - if (resolved) return translations.get(resolved); - return void 0; - } - return { - _fallback: true, - _serviceName: "i18n", - t(key, locale, params) { - const data = resolveTranslations(locale) ?? translations.get(defaultLocale); - const value = data ? resolveKey(data, key) : void 0; - if (value == null) return key; - if (!params) return value; - return value.replace(/\{\{(\w+)\}\}/g, (_, name) => String(params[name] ?? `{{${name}}}`)); - }, - getTranslations(locale) { - return resolveTranslations(locale) ?? {}; - }, - loadTranslations(locale, data) { - const existing = translations.get(locale) ?? {}; - translations.set(locale, { ...existing, ...data }); - }, - getLocales() { - return [...translations.keys()]; - }, - getDefaultLocale() { - return defaultLocale; - }, - setDefaultLocale(locale) { - defaultLocale = locale; - } - }; -} -function createMemoryMetadata() { - const store = /* @__PURE__ */ new Map(); - function getTypeMap(type) { - let map3 = store.get(type); - if (!map3) { - map3 = /* @__PURE__ */ new Map(); - store.set(type, map3); - } - return map3; - } - return { - _fallback: true, - _serviceName: "metadata", - async register(type, name, data) { - getTypeMap(type).set(name, data); - }, - async get(type, name) { - return getTypeMap(type).get(name); - }, - async list(type) { - return Array.from(getTypeMap(type).values()); - }, - async unregister(type, name) { - getTypeMap(type).delete(name); - }, - async exists(type, name) { - return getTypeMap(type).has(name); - }, - async listNames(type) { - return Array.from(getTypeMap(type).keys()); - }, - async getObject(name) { - return getTypeMap("object").get(name); - }, - async listObjects() { - return Array.from(getTypeMap("object").values()); - } - }; -} -var CORE_FALLBACK_FACTORIES = { - metadata: createMemoryMetadata, - cache: createMemoryCache, - queue: createMemoryQueue, - job: createMemoryJob, - i18n: createMemoryI18n -}; -var ObjectKernel = class { - constructor(config4 = {}) { - this.plugins = /* @__PURE__ */ new Map(); - this.services = /* @__PURE__ */ new Map(); - this.hooks = /* @__PURE__ */ new Map(); - this.state = "idle"; - this.startedPlugins = /* @__PURE__ */ new Set(); - this.pluginStartTimes = /* @__PURE__ */ new Map(); - this.shutdownHandlers = []; - this.config = { - defaultStartupTimeout: 3e4, - // 30 seconds - gracefulShutdown: true, - shutdownTimeout: 6e4, - // 60 seconds - rollbackOnFailure: true, - ...config4 - }; - this.logger = createLogger(config4.logger); - this.pluginLoader = new PluginLoader(this.logger); - this.context = { - registerService: (name, service) => { - this.registerService(name, service); - }, - getService: (name) => { - const service = this.services.get(name); - if (service) { - return service; - } - const loaderService = this.pluginLoader.getServiceInstance(name); - if (loaderService) { - this.services.set(name, loaderService); - return loaderService; - } - try { - const service2 = this.pluginLoader.getService(name); - if (service2 instanceof Promise) { - service2.catch(() => { - }); - throw new Error(`Service '${name}' is async - use await`); - } - return service2; - } catch (error49) { - if (error49.message?.includes("is async")) { - throw error49; - } - const isNotFoundError = error49.message === `Service '${name}' not found`; - if (!isNotFoundError) { - throw error49; - } - throw new Error(`[Kernel] Service '${name}' not found`); - } - }, - replaceService: (name, implementation) => { - const hasService = this.services.has(name) || this.pluginLoader.hasService(name); - if (!hasService) { - throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`); - } - this.services.set(name, implementation); - this.pluginLoader.replaceService(name, implementation); - this.logger.info(`Service '${name}' replaced`, { service: name }); - }, - hook: (name, handler) => { - if (!this.hooks.has(name)) { - this.hooks.set(name, []); - } - this.hooks.get(name).push(handler); - }, - trigger: async (name, ...args) => { - const handlers = this.hooks.get(name) || []; - for (const handler of handlers) { - await handler(...args); - } - }, - getServices: () => { - return new Map(this.services); - }, - logger: this.logger, - getKernel: () => this - // Type compatibility - }; - this.pluginLoader.setContext(this.context); - if (this.config.gracefulShutdown) { - this.registerShutdownSignals(); - } - } - /** - * Register a plugin with enhanced validation - */ - async use(plugin) { - if (this.state !== "idle") { - throw new Error("[Kernel] Cannot register plugins after bootstrap has started"); - } - const result = await this.pluginLoader.loadPlugin(plugin); - if (!result.success || !result.plugin) { - throw new Error(`Failed to load plugin: ${plugin.name} - ${result.error?.message}`); - } - const pluginMeta = result.plugin; - this.plugins.set(pluginMeta.name, pluginMeta); - this.logger.info(`Plugin registered: ${pluginMeta.name}@${pluginMeta.version}`, { - plugin: pluginMeta.name, - version: pluginMeta.version - }); - return this; - } - /** - * Register a service instance directly - */ - registerService(name, service) { - if (this.services.has(name)) { - throw new Error(`[Kernel] Service '${name}' already registered`); - } - this.services.set(name, service); - this.pluginLoader.registerService(name, service); - this.logger.info(`Service '${name}' registered`, { service: name }); - return this; - } - /** - * Register a service factory with lifecycle management - */ - registerServiceFactory(name, factory, lifecycle = "singleton", dependencies) { - this.pluginLoader.registerServiceFactory({ - name, - factory, - lifecycle, - dependencies - }); - return this; - } - /** - * Pre-inject in-memory fallbacks for 'core' services that were not registered - * by plugins during Phase 1. Called before Phase 2 so that all core services - * (e.g. 'metadata', 'cache', 'queue') are resolvable via ctx.getService() - * when plugin start() methods execute. - */ - preInjectCoreFallbacks() { - if (this.config.skipSystemValidation) return; - for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) { - if (criticality !== "core") continue; - const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName); - if (!hasService) { - const factory = CORE_FALLBACK_FACTORIES[serviceName]; - if (factory) { - const fallback = factory(); - this.registerService(serviceName, fallback); - this.logger.debug(`[Kernel] Pre-injected in-memory fallback for '${serviceName}' before Phase 2`); - } - } - } - } - /** - * Validate Critical System Requirements - */ - validateSystemRequirements() { - if (this.config.skipSystemValidation) { - this.logger.debug("System requirement validation skipped"); - return; - } - this.logger.debug("Validating system service requirements..."); - const missingServices = []; - const missingCoreServices = []; - for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) { - const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName); - if (!hasService) { - if (criticality === "required") { - this.logger.error(`CRITICAL: Required service missing: ${serviceName}`); - missingServices.push(serviceName); - } else if (criticality === "core") { - const factory = CORE_FALLBACK_FACTORIES[serviceName]; - if (factory) { - const fallback = factory(); - this.registerService(serviceName, fallback); - this.logger.warn(`Service '${serviceName}' not provided \u2014 using in-memory fallback`); - } else { - this.logger.warn(`CORE: Core service missing, functionality may be degraded: ${serviceName}`); - missingCoreServices.push(serviceName); - } - } else { - this.logger.info(`Info: Optional service not present: ${serviceName}`); - } - } - } - if (missingServices.length > 0) { - const errorMsg = `System failed to start. Missing critical services: ${missingServices.join(", ")}`; - this.logger.error(errorMsg); - throw new Error(errorMsg); - } - if (missingCoreServices.length > 0) { - this.logger.warn(`System started with degraded capabilities. Missing core services: ${missingCoreServices.join(", ")}`); - } - this.logger.info("System requirement check passed"); - } - /** - * Bootstrap the kernel with enhanced features - */ - async bootstrap() { - if (this.state !== "idle") { - throw new Error("[Kernel] Kernel already bootstrapped"); - } - this.state = "initializing"; - this.logger.info("Bootstrap started"); - try { - const cycles = this.pluginLoader.detectCircularDependencies(); - if (cycles.length > 0) { - this.logger.warn("Circular service dependencies detected:", { cycles }); - } - const orderedPlugins = this.resolveDependencies(); - this.logger.info("Phase 1: Init plugins"); - for (const plugin of orderedPlugins) { - await this.initPluginWithTimeout(plugin); - } - this.preInjectCoreFallbacks(); - this.logger.info("Phase 2: Start plugins"); - this.state = "running"; - for (const plugin of orderedPlugins) { - const result = await this.startPluginWithTimeout(plugin); - if (!result.success) { - this.logger.error(`Plugin startup failed: ${plugin.name}`, result.error); - if (this.config.rollbackOnFailure) { - this.logger.warn("Rolling back started plugins..."); - await this.rollbackStartedPlugins(); - throw new Error(`Plugin ${plugin.name} failed to start - rollback complete`); - } - } - } - this.validateSystemRequirements(); - this.logger.debug("Triggering kernel:ready hook"); - await this.context.trigger("kernel:ready"); - this.logger.info("\u2705 Bootstrap complete"); - } catch (error49) { - this.state = "stopped"; - throw error49; - } - } - /** - * Graceful shutdown with timeout - */ - async shutdown() { - if (this.state === "stopped" || this.state === "stopping") { - this.logger.warn("Kernel already stopped or stopping"); - return; - } - if (this.state !== "running") { - throw new Error("[Kernel] Kernel not running"); - } - this.state = "stopping"; - this.logger.info("Graceful shutdown started"); - try { - const shutdownPromise = this.performShutdown(); - const timeoutPromise = new Promise((_, reject) => { - setTimeout(() => { - reject(new Error("Shutdown timeout exceeded")); - }, this.config.shutdownTimeout); - }); - await Promise.race([shutdownPromise, timeoutPromise]); - this.state = "stopped"; - this.logger.info("\u2705 Graceful shutdown complete"); - } catch (error49) { - this.logger.error("Shutdown error - forcing stop", error49); - this.state = "stopped"; - throw error49; - } finally { - await this.logger.destroy(); - } - } - /** - * Check health of a specific plugin - */ - async checkPluginHealth(pluginName) { - return await this.pluginLoader.checkPluginHealth(pluginName); - } - /** - * Check health of all plugins - */ - async checkAllPluginsHealth() { - const results = /* @__PURE__ */ new Map(); - for (const pluginName of this.plugins.keys()) { - const health = await this.checkPluginHealth(pluginName); - results.set(pluginName, health); - } - return results; - } - /** - * Get plugin startup metrics - */ - getPluginMetrics() { - return new Map(this.pluginStartTimes); - } - /** - * Get a service (sync helper) - */ - getService(name) { - return this.context.getService(name); - } - /** - * Get a service asynchronously (supports factories) - */ - async getServiceAsync(name, scopeId) { - return await this.pluginLoader.getService(name, scopeId); - } - /** - * Check if kernel is running - */ - isRunning() { - return this.state === "running"; - } - /** - * Get kernel state - */ - getState() { - return this.state; - } - // Private methods - async initPluginWithTimeout(plugin) { - const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout; - this.logger.debug(`Init: ${plugin.name}`, { plugin: plugin.name }); - const initPromise = plugin.init(this.context); - const timeoutPromise = new Promise((_, reject) => { - setTimeout(() => { - reject(new Error(`Plugin ${plugin.name} init timeout after ${timeout}ms`)); - }, timeout); - }); - await Promise.race([initPromise, timeoutPromise]); - } - async startPluginWithTimeout(plugin) { - if (!plugin.start) { - return { success: true, pluginName: plugin.name }; - } - const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout; - const startTime = Date.now(); - this.logger.debug(`Start: ${plugin.name}`, { plugin: plugin.name }); - try { - const startPromise = plugin.start(this.context); - const timeoutPromise = new Promise((_, reject) => { - setTimeout(() => { - reject(new Error(`Plugin ${plugin.name} start timeout after ${timeout}ms`)); - }, timeout); - }); - await Promise.race([startPromise, timeoutPromise]); - const duration3 = Date.now() - startTime; - this.startedPlugins.add(plugin.name); - this.pluginStartTimes.set(plugin.name, duration3); - this.logger.debug(`Plugin started: ${plugin.name} (${duration3}ms)`); - return { - success: true, - pluginName: plugin.name, - startTime: duration3 - }; - } catch (error49) { - const duration3 = Date.now() - startTime; - const isTimeout = error49.message.includes("timeout"); - return { - success: false, - pluginName: plugin.name, - error: error49, - startTime: duration3, - timedOut: isTimeout - }; - } - } - async rollbackStartedPlugins() { - const pluginsToRollback = Array.from(this.startedPlugins).reverse(); - for (const pluginName of pluginsToRollback) { - const plugin = this.plugins.get(pluginName); - if (plugin?.destroy) { - try { - this.logger.debug(`Rollback: ${pluginName}`); - await plugin.destroy(); - } catch (error49) { - this.logger.error(`Rollback failed for ${pluginName}`, error49); - } - } - } - this.startedPlugins.clear(); - } - async performShutdown() { - await this.context.trigger("kernel:shutdown"); - const orderedPlugins = Array.from(this.plugins.values()).reverse(); - for (const plugin of orderedPlugins) { - if (plugin.destroy) { - this.logger.debug(`Destroy: ${plugin.name}`, { plugin: plugin.name }); - try { - await plugin.destroy(); - } catch (error49) { - this.logger.error(`Error destroying plugin ${plugin.name}`, error49); - } - } - } - for (const handler of this.shutdownHandlers) { - try { - await handler(); - } catch (error49) { - this.logger.error("Shutdown handler error", error49); - } - } - } - resolveDependencies() { - const resolved = []; - const visited = /* @__PURE__ */ new Set(); - const visiting = /* @__PURE__ */ new Set(); - const visit = (pluginName) => { - if (visited.has(pluginName)) return; - if (visiting.has(pluginName)) { - throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`); - } - const plugin = this.plugins.get(pluginName); - if (!plugin) { - throw new Error(`[Kernel] Plugin '${pluginName}' not found`); - } - visiting.add(pluginName); - const deps = plugin.dependencies || []; - for (const dep of deps) { - if (!this.plugins.has(dep)) { - throw new Error(`[Kernel] Dependency '${dep}' not found for plugin '${pluginName}'`); - } - visit(dep); - } - visiting.delete(pluginName); - visited.add(pluginName); - resolved.push(plugin); - }; - for (const pluginName of this.plugins.keys()) { - visit(pluginName); - } - return resolved; - } - registerShutdownSignals() { - const signals = ["SIGINT", "SIGTERM", "SIGQUIT"]; - let shutdownInProgress = false; - const handleShutdown = async (signal) => { - if (shutdownInProgress) { - this.logger.warn(`Shutdown already in progress, ignoring ${signal}`); - return; - } - shutdownInProgress = true; - this.logger.info(`Received ${signal} - initiating graceful shutdown`); - try { - await this.shutdown(); - safeExit(0); - } catch (error49) { - this.logger.error("Shutdown failed", error49); - safeExit(1); - } - }; - if (isNode) { - for (const signal of signals) { - process.on(signal, () => handleShutdown(signal)); - } - } - } - /** - * Register a custom shutdown handler - */ - onShutdown(handler) { - this.shutdownHandlers.push(handler); - } -}; -var qa_exports = {}; -__export2(qa_exports, { - HttpTestAdapter: () => HttpTestAdapter, - TestRunner: () => TestRunner -}); -var TestRunner = class { - constructor(adapter) { - this.adapter = adapter; - } - async runSuite(suite) { - const results = []; - for (const scenario of suite.scenarios) { - results.push(await this.runScenario(scenario)); - } - return results; - } - async runScenario(scenario) { - const startTime = Date.now(); - const context = {}; - if (scenario.setup) { - for (const step of scenario.setup) { - try { - await this.runStep(step, context); - } catch (e) { - return { - scenarioId: scenario.id, - passed: false, - steps: [], - error: `Setup failed: ${e instanceof Error ? e.message : String(e)}`, - duration: Date.now() - startTime - }; - } - } - } - const stepResults = []; - let scenarioPassed = true; - let scenarioError = void 0; - for (const step of scenario.steps) { - const stepStartTime = Date.now(); - try { - const output = await this.runStep(step, context); - stepResults.push({ - stepName: step.name, - passed: true, - output, - duration: Date.now() - stepStartTime - }); - } catch (e) { - scenarioPassed = false; - scenarioError = e; - stepResults.push({ - stepName: step.name, - passed: false, - error: e, - duration: Date.now() - stepStartTime - }); - break; - } - } - if (scenario.teardown) { - for (const step of scenario.teardown) { - try { - await this.runStep(step, context); - } catch (e) { - if (scenarioPassed) { - scenarioPassed = false; - scenarioError = `Teardown failed: ${e instanceof Error ? e.message : String(e)}`; - } - } - } - } - return { - scenarioId: scenario.id, - passed: scenarioPassed, - steps: stepResults, - error: scenarioError, - duration: Date.now() - startTime - }; - } - async runStep(step, context) { - const resolvedAction = this.resolveVariables(step.action, context); - const result = await this.adapter.execute(resolvedAction, context); - if (step.capture) { - for (const [varName, path3] of Object.entries(step.capture)) { - context[varName] = this.getValueByPath(result, path3); - } - } - if (step.assertions) { - for (const assertion of step.assertions) { - this.assert(result, assertion, context); - } - } - return result; - } - resolveVariables(action, context) { - const actionStr = JSON.stringify(action); - const resolved = actionStr.replace(/\{\{([^}]+)\}\}/g, (_match, varPath) => { - const value = this.getValueByPath(context, varPath.trim()); - if (value === void 0) return _match; - return typeof value === "string" ? value : JSON.stringify(value); - }); - try { - return JSON.parse(resolved); - } catch { - return action; - } - } - getValueByPath(obj, path3) { - if (!path3) return obj; - const parts = path3.split("."); - let current = obj; - for (const part of parts) { - if (current === null || current === void 0) return void 0; - current = current[part]; - } - return current; - } - assert(result, assertion, _context2) { - const actual = this.getValueByPath(result, assertion.field); - const expected = assertion.expectedValue; - switch (assertion.operator) { - case "equals": - if (actual !== expected) throw new Error(`Assertion failed: ${assertion.field} expected ${expected}, got ${actual}`); - break; - case "not_equals": - if (actual === expected) throw new Error(`Assertion failed: ${assertion.field} expected not ${expected}, got ${actual}`); - break; - case "contains": - if (Array.isArray(actual)) { - if (!actual.includes(expected)) throw new Error(`Assertion failed: ${assertion.field} array does not contain ${expected}`); - } else if (typeof actual === "string") { - if (!actual.includes(String(expected))) throw new Error(`Assertion failed: ${assertion.field} string does not contain ${expected}`); - } - break; - case "not_null": - if (actual === null || actual === void 0) throw new Error(`Assertion failed: ${assertion.field} is null`); - break; - case "is_null": - if (actual !== null && actual !== void 0) throw new Error(`Assertion failed: ${assertion.field} is not null`); - break; - // ... Add other operators - default: - throw new Error(`Unknown assertion operator: ${assertion.operator}`); - } - } -}; -var HttpTestAdapter = class { - constructor(baseUrl, authToken) { - this.baseUrl = baseUrl; - this.authToken = authToken; - } - async execute(action, _context2) { - const headers = { - "Content-Type": "application/json" - }; - if (this.authToken) { - headers["Authorization"] = `Bearer ${this.authToken}`; - } - if (action.user) { - headers["X-Run-As"] = action.user; - } - switch (action.type) { - case "create_record": - return this.createRecord(action.target, action.payload || {}, headers); - case "update_record": - return this.updateRecord(action.target, action.payload || {}, headers); - case "delete_record": - return this.deleteRecord(action.target, action.payload || {}, headers); - case "read_record": - return this.readRecord(action.target, action.payload || {}, headers); - case "query_records": - return this.queryRecords(action.target, action.payload || {}, headers); - case "api_call": - return this.rawApiCall(action.target, action.payload || {}, headers); - case "wait": - const ms = Number(action.payload?.duration || 1e3); - return new Promise((resolve2) => setTimeout(() => resolve2({ waited: ms }), ms)); - default: - throw new Error(`Unsupported action type in HttpAdapter: ${action.type}`); - } - } - async createRecord(objectName, data, headers) { - const response = await fetch(`${this.baseUrl}/api/data/${objectName}`, { - method: "POST", - headers, - body: JSON.stringify(data) - }); - return this.handleResponse(response); - } - async updateRecord(objectName, data, headers) { - const id = data.id; - if (!id) throw new Error("Update record requires id in payload"); - const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, { - method: "PUT", - headers, - body: JSON.stringify(data) - }); - return this.handleResponse(response); - } - async deleteRecord(objectName, data, headers) { - const id = data.id; - if (!id) throw new Error("Delete record requires id in payload"); - const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, { - method: "DELETE", - headers - }); - return this.handleResponse(response); - } - async readRecord(objectName, data, headers) { - const id = data.id; - if (!id) throw new Error("Read record requires id in payload"); - const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, { - method: "GET", - headers - }); - return this.handleResponse(response); - } - async queryRecords(objectName, data, headers) { - const response = await fetch(`${this.baseUrl}/api/data/${objectName}/query`, { - method: "POST", - headers, - body: JSON.stringify(data) - }); - return this.handleResponse(response); - } - async rawApiCall(endpoint, data, headers) { - const method = data.method || "GET"; - const body = data.body ? JSON.stringify(data.body) : void 0; - const url2 = endpoint.startsWith("http") ? endpoint : `${this.baseUrl}${endpoint}`; - const response = await fetch(url2, { - method, - headers, - body - }); - return this.handleResponse(response); - } - async handleResponse(response) { - if (!response.ok) { - const text = await response.text(); - throw new Error(`HTTP Error ${response.status}: ${text}`); - } - const contentType = response.headers.get("content-type"); - if (contentType && contentType.includes("application/json")) { - return response.json(); - } - return response.text(); - } -}; -var _PluginSandboxRuntime = class _PluginSandboxRuntime2 { - constructor(logger2) { - this.sandboxes = /* @__PURE__ */ new Map(); - this.monitoringIntervals = /* @__PURE__ */ new Map(); - this.memoryBaselines = /* @__PURE__ */ new Map(); - this.cpuBaselines = /* @__PURE__ */ new Map(); - this.logger = logger2.child({ component: "SandboxRuntime" }); - } - /** - * Create a sandbox for a plugin - */ - createSandbox(pluginId, config4) { - if (this.sandboxes.has(pluginId)) { - throw new Error(`Sandbox already exists for plugin: ${pluginId}`); - } - const context = { - pluginId, - config: config4, - startTime: /* @__PURE__ */ new Date(), - resourceUsage: { - memory: { current: 0, peak: 0, limit: config4.memory?.maxHeap }, - cpu: { current: 0, average: 0, limit: config4.cpu?.maxCpuPercent }, - connections: { current: 0, limit: config4.network?.maxConnections } - } - }; - this.sandboxes.set(pluginId, context); - const baselineMemory = getMemoryUsage(); - this.memoryBaselines.set(pluginId, baselineMemory.heapUsed); - this.cpuBaselines.set(pluginId, process.cpuUsage()); - this.startResourceMonitoring(pluginId); - this.logger.info("Sandbox created", { - pluginId, - level: config4.level, - memoryLimit: config4.memory?.maxHeap, - cpuLimit: config4.cpu?.maxCpuPercent - }); - return context; - } - /** - * Destroy a sandbox - */ - destroySandbox(pluginId) { - const context = this.sandboxes.get(pluginId); - if (!context) { - return; - } - this.stopResourceMonitoring(pluginId); - this.memoryBaselines.delete(pluginId); - this.cpuBaselines.delete(pluginId); - this.sandboxes.delete(pluginId); - this.logger.info("Sandbox destroyed", { pluginId }); - } - /** - * Check if resource access is allowed - */ - checkResourceAccess(pluginId, resourceType, resourcePath) { - const context = this.sandboxes.get(pluginId); - if (!context) { - return { allowed: false, reason: "Sandbox not found" }; - } - const { config: config4 } = context; - switch (resourceType) { - case "file": - return this.checkFileAccess(config4, resourcePath); - case "network": - return this.checkNetworkAccess(config4, resourcePath); - case "process": - return this.checkProcessAccess(config4); - case "env": - return this.checkEnvAccess(config4, resourcePath); - default: - return { allowed: false, reason: "Unknown resource type" }; - } - } - /** - * Check file system access - * Uses path.resolve() and path.normalize() to prevent directory traversal. - */ - checkFileAccess(config4, filePath) { - if (config4.level === "none") { - return { allowed: true }; - } - if (!config4.filesystem) { - return { allowed: false, reason: "File system access not configured" }; - } - if (!filePath) { - return { allowed: config4.filesystem.mode !== "none" }; - } - const allowedPaths = config4.filesystem.allowedPaths || []; - const resolvedPath = nodePath.normalize(nodePath.resolve(filePath)); - const isAllowed = allowedPaths.some((allowed2) => { - const resolvedAllowed = nodePath.normalize(nodePath.resolve(allowed2)); - return resolvedPath.startsWith(resolvedAllowed); - }); - if (allowedPaths.length > 0 && !isAllowed) { - return { - allowed: false, - reason: `Path not in allowed list: ${filePath}` - }; - } - const deniedPaths = config4.filesystem.deniedPaths || []; - const isDenied = deniedPaths.some((denied) => { - const resolvedDenied = nodePath.normalize(nodePath.resolve(denied)); - return resolvedPath.startsWith(resolvedDenied); - }); - if (isDenied) { - return { - allowed: false, - reason: `Path is explicitly denied: ${filePath}` - }; - } - return { allowed: true }; - } - /** - * Check network access - * Uses URL parsing to properly validate hostnames. - */ - checkNetworkAccess(config4, url2) { - if (config4.level === "none") { - return { allowed: true }; - } - if (!config4.network) { - return { allowed: false, reason: "Network access not configured" }; - } - if (config4.network.mode === "none") { - return { allowed: false, reason: "Network access disabled" }; - } - if (!url2) { - return { allowed: config4.network.mode !== "none" }; - } - let parsedHostname; - try { - parsedHostname = new URL(url2).hostname; - } catch { - return { allowed: false, reason: `Invalid URL: ${url2}` }; - } - const allowedHosts = config4.network.allowedHosts || []; - if (allowedHosts.length > 0) { - const isAllowed = allowedHosts.some((host) => { - return parsedHostname === host; - }); - if (!isAllowed) { - return { - allowed: false, - reason: `Host not in allowed list: ${url2}` - }; - } - } - const deniedHosts = config4.network.deniedHosts || []; - const isDenied = deniedHosts.some((host) => { - return parsedHostname === host; - }); - if (isDenied) { - return { - allowed: false, - reason: `Host is blocked: ${url2}` - }; - } - return { allowed: true }; - } - /** - * Check process spawning access - */ - checkProcessAccess(config4) { - if (config4.level === "none") { - return { allowed: true }; - } - if (!config4.process) { - return { allowed: false, reason: "Process access not configured" }; - } - if (!config4.process.allowSpawn) { - return { allowed: false, reason: "Process spawning not allowed" }; - } - return { allowed: true }; - } - /** - * Check environment variable access - */ - checkEnvAccess(config4, varName) { - if (config4.level === "none") { - return { allowed: true }; - } - if (!config4.process) { - return { allowed: false, reason: "Environment access not configured" }; - } - if (!varName) { - return { allowed: true }; - } - return { allowed: true }; - } - /** - * Check resource limits - */ - checkResourceLimits(pluginId) { - const context = this.sandboxes.get(pluginId); - if (!context) { - return { withinLimits: true, violations: [] }; - } - const violations = []; - const { resourceUsage, config: config4 } = context; - if (config4.memory?.maxHeap && resourceUsage.memory.current > config4.memory.maxHeap) { - violations.push(`Memory limit exceeded: ${resourceUsage.memory.current} > ${config4.memory.maxHeap}`); - } - if (config4.runtime?.resourceLimits?.maxCpu && resourceUsage.cpu.current > config4.runtime.resourceLimits.maxCpu) { - violations.push(`CPU limit exceeded: ${resourceUsage.cpu.current}% > ${config4.runtime.resourceLimits.maxCpu}%`); - } - if (config4.network?.maxConnections && resourceUsage.connections.current > config4.network.maxConnections) { - violations.push(`Connection limit exceeded: ${resourceUsage.connections.current} > ${config4.network.maxConnections}`); - } - return { - withinLimits: violations.length === 0, - violations - }; - } - /** - * Get resource usage for a plugin - */ - getResourceUsage(pluginId) { - const context = this.sandboxes.get(pluginId); - return context?.resourceUsage; - } - /** - * Start monitoring resource usage - */ - startResourceMonitoring(pluginId) { - const interval = setInterval(() => { - this.updateResourceUsage(pluginId); - }, _PluginSandboxRuntime2.MONITORING_INTERVAL_MS); - this.monitoringIntervals.set(pluginId, interval); - } - /** - * Stop monitoring resource usage - */ - stopResourceMonitoring(pluginId) { - const interval = this.monitoringIntervals.get(pluginId); - if (interval) { - clearInterval(interval); - this.monitoringIntervals.delete(pluginId); - } - } - /** - * Update resource usage statistics - * - * Tracks per-plugin memory and CPU usage using delta from baseline - * captured at sandbox creation time. This is an approximation since - * true per-plugin isolation isn't possible in a single Node.js process. - */ - updateResourceUsage(pluginId) { - const context = this.sandboxes.get(pluginId); - if (!context) { - return; - } - const memoryUsage = getMemoryUsage(); - const memoryBaseline = this.memoryBaselines.get(pluginId) ?? 0; - const memoryDelta = Math.max(0, memoryUsage.heapUsed - memoryBaseline); - context.resourceUsage.memory.current = memoryDelta; - context.resourceUsage.memory.peak = Math.max( - context.resourceUsage.memory.peak, - memoryDelta - ); - const cpuBaseline = this.cpuBaselines.get(pluginId) ?? { user: 0, system: 0 }; - const cpuCurrent = process.cpuUsage(); - const cpuDeltaUser = cpuCurrent.user - cpuBaseline.user; - const cpuDeltaSystem = cpuCurrent.system - cpuBaseline.system; - const totalCpuMicros = cpuDeltaUser + cpuDeltaSystem; - const intervalMicros = _PluginSandboxRuntime2.MONITORING_INTERVAL_MS * 1e3; - context.resourceUsage.cpu.current = totalCpuMicros / intervalMicros * 100; - this.cpuBaselines.set(pluginId, cpuCurrent); - const { withinLimits, violations } = this.checkResourceLimits(pluginId); - if (!withinLimits) { - this.logger.warn("Resource limit violations detected", { - pluginId, - violations - }); - } - } - /** - * Get all active sandboxes - */ - getAllSandboxes() { - return new Map(this.sandboxes); - } - /** - * Shutdown sandbox runtime - */ - shutdown() { - for (const pluginId of this.monitoringIntervals.keys()) { - this.stopResourceMonitoring(pluginId); - } - this.sandboxes.clear(); - this.memoryBaselines.clear(); - this.cpuBaselines.clear(); - this.logger.info("Sandbox runtime shutdown complete"); - } -}; -_PluginSandboxRuntime.MONITORING_INTERVAL_MS = 5e3; - -// ../../packages/runtime/dist/index.js -init_data(); - -// ../../packages/spec/dist/shared/index.mjs -init_zod(); -var SystemIdentifierSchema4 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' -}).describe("System identifier (lowercase with underscores or dots)"); -var SnakeCaseIdentifierSchema4 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { - message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' -}).describe("Snake case identifier (lowercase with underscores only)"); -var EventNameSchema2 = external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' -}).describe("Event name (lowercase with dot notation for namespacing)"); -var TransformTypeSchema2 = external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("constant"), - value: external_exports.unknown().describe("Constant value to use") - }).describe("Set a constant value"), - external_exports.object({ - type: external_exports.literal("cast"), - targetType: external_exports.enum(["string", "number", "boolean", "date"]).describe("Target data type") - }).describe("Cast to a specific data type"), - external_exports.object({ - type: external_exports.literal("lookup"), - table: external_exports.string().describe("Lookup table name"), - keyField: external_exports.string().describe("Field to match on"), - valueField: external_exports.string().describe("Field to retrieve") - }).describe("Lookup value from another table"), - external_exports.object({ - type: external_exports.literal("javascript"), - expression: external_exports.string().describe('JavaScript expression (e.g., "value.toUpperCase()")') - }).describe("Custom JavaScript transformation"), - external_exports.object({ - type: external_exports.literal("map"), - mappings: external_exports.record(external_exports.string(), external_exports.unknown()).describe('Value mappings (e.g., {"Active": "active"})') - }).describe("Map values using a dictionary") -]); -var FieldMappingSchema3 = external_exports.object({ - /** - * Source field name - */ - source: external_exports.string().describe("Source field name"), - /** - * Target field name (should be snake_case for ObjectStack) - */ - target: external_exports.string().describe("Target field name"), - /** - * Transformation to apply - */ - transform: TransformTypeSchema2.optional().describe("Transformation to apply"), - /** - * Default value if source is null/undefined - */ - defaultValue: external_exports.unknown().optional().describe("Default if source is null/undefined") -}); -var HttpMethod3 = external_exports.enum([ - "GET", - "POST", - "PUT", - "DELETE", - "PATCH", - "HEAD", - "OPTIONS" -]); -var HttpMethodSchema3 = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); -var HttpRequestSchema2 = external_exports.object({ - url: external_exports.string().describe("API endpoint URL"), - method: HttpMethodSchema3.optional().default("GET").describe("HTTP method"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), - body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") -}); -var CorsConfigSchema3 = external_exports.object({ - /** - * Enable CORS - */ - enabled: external_exports.boolean().default(true).describe("Enable CORS"), - /** - * Allowed origins (* for all) - */ - origins: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.string()) - ]).default("*").describe("Allowed origins (* for all)"), - /** - * Allowed HTTP methods - */ - methods: external_exports.array(HttpMethod3).optional().describe("Allowed HTTP methods"), - /** - * Allow credentials (cookies, authorization headers) - */ - credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), - /** - * Preflight cache duration in seconds - */ - maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") -}); -var RateLimitConfigSchema3 = external_exports.object({ - /** - * Enable rate limiting - */ - enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), - /** - * Time window in milliseconds - */ - windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), - /** - * Max requests per window - */ - maxRequests: external_exports.number().int().default(100).describe("Max requests per window") -}); -var StaticMountSchema3 = external_exports.object({ - /** - * URL path to serve from - */ - path: external_exports.string().describe("URL path to serve from"), - /** - * Physical directory to serve - */ - directory: external_exports.string().describe("Physical directory to serve"), - /** - * Cache-Control header value - */ - cacheControl: external_exports.string().optional().describe("Cache-Control header value") -}); -var AggregationFunctionEnum = external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "percentile", - "median", - "stddev", - "variance" -]).describe("Standard aggregation functions"); -var SortDirectionEnum2 = external_exports.enum(["asc", "desc"]).describe("Sort order direction"); -var SortItemSchema = external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - order: SortDirectionEnum2.describe("Sort direction") -}).describe("Sort field and direction pair"); -var MutationEventEnum = external_exports.enum([ - "insert", - "update", - "delete", - "upsert" -]).describe("Data mutation event types"); -var IsolationLevelEnum2 = external_exports.enum([ - "read_uncommitted", - "read_committed", - "repeatable_read", - "serializable", - "snapshot" -]).describe("Transaction isolation levels (snake_case standard)"); -var CacheStrategyEnum = external_exports.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy"); -var MetadataFormatSchema3 = external_exports.enum(["yaml", "json", "typescript", "javascript"]).describe("Metadata file format"); -var BaseMetadataRecordSchema = external_exports.object({ - id: external_exports.string().describe("Unique metadata record identifier"), - type: external_exports.string().describe('Metadata type (e.g. "object", "view", "flow")'), - name: SnakeCaseIdentifierSchema4.describe("Machine name (snake_case)"), - format: MetadataFormatSchema3.optional().describe("Source file format") -}).describe("Base metadata record fields shared across kernel and system"); -var ObjectNameSchema = SnakeCaseIdentifierSchema4.brand().describe("Branded object name (snake_case, no dots)"); -var FieldNameSchema = SnakeCaseIdentifierSchema4.brand().describe("Branded field name (snake_case, no dots)"); -var ViewNameSchema = SystemIdentifierSchema4.brand().describe("Branded view name (system identifier)"); -var AppNameSchema = SystemIdentifierSchema4.brand().describe("Branded app name (system identifier)"); -var FlowNameSchema = SystemIdentifierSchema4.brand().describe("Branded flow name (system identifier)"); -var RoleNameSchema = SystemIdentifierSchema4.brand().describe("Branded role name (system identifier)"); -var EncryptionAlgorithmSchema4 = external_exports.enum([ - "aes-256-gcm", - "aes-256-cbc", - "chacha20-poly1305" -]).describe("Supported encryption algorithm"); -var KeyManagementProviderSchema4 = external_exports.enum([ - "local", - "aws-kms", - "azure-key-vault", - "gcp-kms", - "hashicorp-vault" -]).describe("Key management service provider"); -var KeyRotationPolicySchema4 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), - frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), - retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), - autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") -}).describe("Policy for automatic encryption key rotation"); -var EncryptionConfigSchema4 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), - algorithm: EncryptionAlgorithmSchema4.default("aes-256-gcm").describe("Encryption algorithm"), - keyManagement: external_exports.object({ - provider: KeyManagementProviderSchema4.describe("Key management service provider"), - keyId: external_exports.string().optional().describe("Key identifier in the provider"), - rotationPolicy: KeyRotationPolicySchema4.optional().describe("Key rotation policy") - }).describe("Key management configuration"), - scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), - deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), - searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") -}).describe("Field-level encryption configuration"); -external_exports.object({ - fieldName: external_exports.string().describe("Name of the field to encrypt"), - encryptionConfig: EncryptionConfigSchema4.describe("Encryption settings for this field"), - indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") -}).describe("Per-field encryption assignment"); -var MaskingStrategySchema4 = external_exports.enum([ - "redact", - // Complete redaction: **** - "partial", - // Partial masking: 138****5678 - "hash", - // Hash value: sha256(value) - "tokenize", - // Tokenization: token-12345 - "randomize", - // Randomize: generate random value - "nullify", - // Null value: null - "substitute" - // Substitute with dummy data -]).describe("Data masking strategy for PII protection"); -var MaskingRuleSchema4 = external_exports.object({ - field: external_exports.string().describe("Field name to apply masking to"), - strategy: MaskingStrategySchema4.describe("Masking strategy to use"), - pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), - preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), - preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), - roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), - exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") -}).describe("Masking rule for a single field"); -external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable data masking"), - rules: external_exports.array(MaskingRuleSchema4).describe("List of field-level masking rules"), - auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") -}).describe("Top-level data masking configuration for PII protection"); -var FieldType4 = external_exports.enum([ - // Core Text - "text", - "textarea", - "email", - "url", - "phone", - "password", - // Rich Content - "markdown", - "html", - "richtext", - // Numbers - "number", - "currency", - "percent", - // Date & Time - "date", - "datetime", - "time", - // Logic - "boolean", - "toggle", - // Toggle is a distinct UI from checkbox - // Selection - "select", - // Single select dropdown - "multiselect", - // Multi select (often tags) - "radio", - // Radio group - "checkboxes", - // Checkbox group - // Relational - "lookup", - "master_detail", - // Dynamic reference - "tree", - // Hierarchical reference - // Media - "image", - "file", - "avatar", - "video", - "audio", - // Calculated / System - "formula", - "summary", - "autonumber", - // Enhanced Types - "location", - // GPS coordinates - "address", - // Structured address - "code", - // Code editor (JSON/SQL/JS) - "json", - // Structured JSON data - "color", - // Color picker - "rating", - // Star rating - "slider", - // Numeric slider - "signature", - // Digital signature - "qrcode", - // QR code / Barcode - "progress", - // Progress bar - "tags", - // Simple tag list - // AI/ML Types - "vector" - // Vector embeddings for AI/ML (semantic search, RAG) -]); -var SelectOptionSchema4 = external_exports.object({ - label: external_exports.string().describe("Display label (human-readable, any case allowed)"), - value: SystemIdentifierSchema4.describe("Stored value (lowercase machine identifier)"), - color: external_exports.string().optional().describe("Color code for badges/charts"), - default: external_exports.boolean().optional().describe("Is default option") -}); -external_exports.object({ - latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), - longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), - altitude: external_exports.number().optional().describe("Altitude in meters"), - accuracy: external_exports.number().optional().describe("Accuracy in meters") -}); -var CurrencyConfigSchema4 = external_exports.object({ - precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), - currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), - defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") -}); -external_exports.object({ - value: external_exports.number().describe("Monetary amount"), - currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") -}); -external_exports.object({ - street: external_exports.string().optional().describe("Street address"), - city: external_exports.string().optional().describe("City name"), - state: external_exports.string().optional().describe("State/Province"), - postalCode: external_exports.string().optional().describe("Postal/ZIP code"), - country: external_exports.string().optional().describe("Country name or code"), - countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), - formatted: external_exports.string().optional().describe("Formatted address string") -}); -var VectorConfigSchema4 = external_exports.object({ - dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), - distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), - normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), - indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), - indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") -}); -var FileAttachmentConfigSchema4 = external_exports.object({ - /** File Size Limits */ - minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), - maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), - /** File Type Restrictions */ - allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), - blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), - allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), - blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), - /** Virus Scanning */ - virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), - virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), - virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), - quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), - /** Storage Configuration */ - storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), - storageBucket: external_exports.string().optional().describe("Target bucket name"), - storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), - /** Image-Specific Validation */ - imageValidation: external_exports.object({ - minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), - maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), - minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), - maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), - aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), - generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), - thumbnailSizes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), - width: external_exports.number().min(1).describe("Thumbnail width in pixels"), - height: external_exports.number().min(1).describe("Thumbnail height in pixels"), - crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") - })).optional().describe("Thumbnail size configurations"), - preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), - autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") - }).optional().describe("Image-specific validation rules"), - /** Upload Behavior */ - allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), - allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), - allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), - requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), - /** Metadata Extraction */ - extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), - extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), - /** Versioning */ - versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), - maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), - /** Access Control */ - publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), - presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") -}).refine((data) => { - if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { - return false; - } - return true; -}, { - message: "minSize must be less than or equal to maxSize" -}).refine((data) => { - if (data.virusScanProvider !== void 0 && data.virusScan !== true) { - return false; - } - return true; -}, { - message: "virusScanProvider requires virusScan to be enabled" -}); -var DataQualityRulesSchema4 = external_exports.object({ - /** Enforce uniqueness constraint */ - uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), - /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ - completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), - /** Accuracy validation against authoritative source */ - accuracy: external_exports.object({ - source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), - threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") - }).optional().describe("Accuracy validation configuration") -}); -var ComputedFieldCacheSchema4 = external_exports.object({ - /** Enable caching for this computed field */ - enabled: external_exports.boolean().describe("Enable caching for computed field results"), - /** Time-to-live in seconds */ - ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), - /** Array of field paths that trigger cache invalidation when changed */ - invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') -}); -external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), - label: external_exports.string().optional().describe("Human readable label"), - type: FieldType4.describe("Field Data Type"), - description: external_exports.string().optional().describe("Tooltip/Help text"), - format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), - /** Storage Layer Mapping */ - columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), - /** Database Constraints */ - required: external_exports.boolean().default(false).describe("Is required"), - searchable: external_exports.boolean().default(false).describe("Is searchable"), - multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), - unique: external_exports.boolean().default(false).describe("Is unique constraint"), - defaultValue: external_exports.unknown().optional().describe("Default value"), - /** Text/String Constraints */ - maxLength: external_exports.number().optional().describe("Max character length"), - minLength: external_exports.number().optional().describe("Min character length"), - /** Number Constraints */ - precision: external_exports.number().optional().describe("Total digits"), - scale: external_exports.number().optional().describe("Decimal places"), - min: external_exports.number().optional().describe("Minimum value"), - max: external_exports.number().optional().describe("Maximum value"), - /** Selection Options */ - options: external_exports.array(SelectOptionSchema4).optional().describe("Static options for select/multiselect"), - /** - * Relationship Config - * - * Used by `lookup` and `master_detail` field types to define cross-object references. - * The `reference` property is **required** for these types — it identifies the target - * object whose records this field links to. The engine uses `reference` during $expand - * post-processing to resolve foreign key IDs into full related objects via batch queries. - * - * For `master_detail` fields, the parent record controls the lifecycle of child records - * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. - */ - reference: external_exports.string().optional().describe( - "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." - ), - referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), - writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), - deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), - /** Calculation */ - expression: external_exports.string().optional().describe("Formula expression"), - summaryOperations: external_exports.object({ - object: external_exports.string().describe("Source child object name for roll-up"), - field: external_exports.string().describe("Field on child object to aggregate"), - function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") - }).optional().describe("Roll-up summary definition"), - /** Enhanced Field Type Configurations */ - // Code field config - language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), - theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), - lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), - // Rating field config - maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), - allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), - // Location field config - displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), - allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), - // Address field config - addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), - // Color field config - colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), - allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), - presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), - // Slider field config - step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), - showValue: external_exports.boolean().optional().describe("Display current value on slider"), - marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), - // QR Code / Barcode field config - // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' - // Runtime validation should enforce this constraint - barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), - qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), - displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), - allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), - // Currency field config - currencyConfig: CurrencyConfigSchema4.optional().describe("Configuration for currency field type"), - // Vector field config - vectorConfig: VectorConfigSchema4.optional().describe("Configuration for vector field type (AI/ML embeddings)"), - // File attachment field config - fileAttachmentConfig: FileAttachmentConfigSchema4.optional().describe("Configuration for file and attachment field types"), - /** Enhanced Security & Compliance */ - // Encryption configuration - encryptionConfig: EncryptionConfigSchema4.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), - // Data masking rules - maskingRule: MaskingRuleSchema4.optional().describe("Data masking rules for PII protection"), - // Audit trail - auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), - /** Field Dependencies & Relationships */ - // Field dependencies - dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), - /** Computed Field Optimization */ - // Computed field caching - cached: ComputedFieldCacheSchema4.optional().describe("Caching configuration for computed/formula fields"), - /** Data Quality & Governance */ - // Data quality rules - dataQuality: DataQualityRulesSchema4.optional().describe("Data quality validation and monitoring rules"), - /** Layout & Grouping */ - group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), - /** Conditional Requirements */ - conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), - /** Security & Visibility */ - hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), - readonly: external_exports.boolean().default(false).describe("Read-only in UI"), - sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), - inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), - trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), - caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), - autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), - /** Indexing */ - index: external_exports.boolean().default(false).describe("Create standard database index"), - externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") -}); -var PLURAL_TO_SINGULAR = { - objects: "object", - apps: "app", - pages: "page", - dashboards: "dashboard", - reports: "report", - actions: "action", - themes: "theme", - workflows: "workflow", - approvals: "approval", - flows: "flow", - roles: "role", - permissions: "permission", - profiles: "profile", - sharingRules: "sharingRule", - policies: "policy", - apis: "api", - webhooks: "webhook", - agents: "agent", - ragPipelines: "ragPipeline", - hooks: "hook", - mappings: "mapping", - analyticsCubes: "analyticsCube", - connectors: "connector", - datasources: "datasource", - views: "view" -}; -var SINGULAR_TO_PLURAL = Object.fromEntries( - Object.entries(PLURAL_TO_SINGULAR).map(([plural, singular]) => [singular, plural]) -); -function pluralToSingular(key) { - return PLURAL_TO_SINGULAR[key] ?? key; -} - -// ../../packages/runtime/dist/index.js -var DriverPlugin = class { - constructor(driver, driverName) { - this.type = "driver"; - this.version = "1.0.0"; - this.init = async (ctx) => { - const serviceName = `driver.${this.driver.name || "unknown"}`; - ctx.registerService(serviceName, this.driver); - ctx.logger.info("Driver service registered", { - serviceName, - driverName: this.driver.name, - driverVersion: this.driver.version - }); - }; - this.start = async (ctx) => { - if (this.name.startsWith("com.objectstack.driver.")) { - } - try { - const metadata = ctx.getService("metadata"); - if (metadata && metadata.addDatasource) { - const datasources = metadata.getDatasources ? metadata.getDatasources() : []; - const hasDefault = datasources.some((ds) => ds.name === "default"); - if (!hasDefault) { - ctx.logger.info(`[DriverPlugin] No 'default' datasource found. Auto-configuring '${this.driver.name}' as default.`); - await metadata.addDatasource({ - name: "default", - driver: this.driver.name - // The driver's internal name (e.g. com.objectstack.driver.memory) - }); - } - } - } catch (e) { - ctx.logger.debug("[DriverPlugin] Failed to auto-configure default datasource (Metadata service missing?)", { error: e }); - } - ctx.logger.debug("Driver plugin started", { driverName: this.driver.name || "unknown" }); - }; - this.driver = driver; - this.name = `com.objectstack.driver.${driverName || driver.name || "unknown"}`; - } -}; -var DEFAULT_EXTERNAL_ID_FIELD = "name"; -var SeedLoaderService = class { - constructor(engine, metadata, logger2) { - this.engine = engine; - this.metadata = metadata; - this.logger = logger2; - } - // ========================================================================== - // Public API - // ========================================================================== - async load(request) { - const startTime = Date.now(); - const config4 = request.config; - const allErrors = []; - const allResults = []; - const datasets = this.filterByEnv(request.datasets, config4.env); - if (datasets.length === 0) { - return this.buildEmptyResult(config4, Date.now() - startTime); - } - const objectNames = datasets.map((d) => d.object); - const graph = await this.buildDependencyGraph(objectNames); - this.logger.info("[SeedLoader] Dependency graph built", { - objects: objectNames.length, - insertOrder: graph.insertOrder, - circularDeps: graph.circularDependencies.length - }); - const orderedDatasets = this.orderDatasets(datasets, graph.insertOrder); - const refMap = this.buildReferenceMap(graph); - const insertedRecords = /* @__PURE__ */ new Map(); - const deferredUpdates = []; - for (const dataset of orderedDatasets) { - const result = await this.loadDataset( - dataset, - config4, - refMap, - insertedRecords, - deferredUpdates, - allErrors - ); - allResults.push(result); - if (config4.haltOnError && result.errored > 0) { - this.logger.warn("[SeedLoader] Halting on first error", { object: dataset.object }); - break; - } - } - if (config4.multiPass && deferredUpdates.length > 0 && !config4.dryRun) { - this.logger.info("[SeedLoader] Pass 2: resolving deferred references", { - count: deferredUpdates.length - }); - await this.resolveDeferredUpdates(deferredUpdates, insertedRecords, allResults, allErrors); - } - const durationMs = Date.now() - startTime; - return this.buildResult(config4, graph, allResults, allErrors, durationMs); - } - async buildDependencyGraph(objectNames) { - const nodes = []; - const objectSet = new Set(objectNames); - for (const objectName of objectNames) { - const objDef = await this.metadata.getObject(objectName); - const dependsOn = []; - const references = []; - if (objDef && objDef.fields) { - const fields = objDef.fields; - for (const [fieldName, fieldDef] of Object.entries(fields)) { - if ((fieldDef.type === "lookup" || fieldDef.type === "master_detail") && fieldDef.reference) { - const targetObject = fieldDef.reference; - if (objectSet.has(targetObject) && !dependsOn.includes(targetObject)) { - dependsOn.push(targetObject); - } - references.push({ - field: fieldName, - targetObject, - targetField: DEFAULT_EXTERNAL_ID_FIELD, - fieldType: fieldDef.type - }); - } - } - } - nodes.push({ object: objectName, dependsOn, references }); - } - const { insertOrder, circularDependencies } = this.topologicalSort(nodes); - return { nodes, insertOrder, circularDependencies }; - } - async validate(datasets, config4) { - const parsedConfig = SeedLoaderConfigSchema.parse({ ...config4, dryRun: true }); - return this.load({ datasets, config: parsedConfig }); - } - // ========================================================================== - // Internal: Dataset Loading - // ========================================================================== - async loadDataset(dataset, config4, refMap, insertedRecords, deferredUpdates, allErrors) { - const objectName = dataset.object; - const mode = dataset.mode || config4.defaultMode; - const externalId = dataset.externalId || "name"; - let inserted = 0; - let updated = 0; - let skipped = 0; - let errored = 0; - let referencesResolved = 0; - let referencesDeferred = 0; - const errors = []; - if (!insertedRecords.has(objectName)) { - insertedRecords.set(objectName, /* @__PURE__ */ new Map()); - } - let existingRecords; - if ((mode === "upsert" || mode === "update" || mode === "ignore") && !config4.dryRun) { - existingRecords = await this.loadExistingRecords(objectName, externalId); - } - const objectRefs = refMap.get(objectName) || []; - for (let i = 0; i < dataset.records.length; i++) { - const record2 = { ...dataset.records[i] }; - for (const ref of objectRefs) { - const fieldValue = record2[ref.field]; - if (fieldValue === void 0 || fieldValue === null) continue; - if (typeof fieldValue !== "string" || this.looksLikeInternalId(fieldValue)) continue; - const targetMap = insertedRecords.get(ref.targetObject); - const resolvedId = targetMap?.get(String(fieldValue)); - if (resolvedId) { - record2[ref.field] = resolvedId; - referencesResolved++; - } else if (!config4.dryRun) { - const dbId = await this.resolveFromDatabase(ref.targetObject, ref.targetField, fieldValue); - if (dbId) { - record2[ref.field] = dbId; - referencesResolved++; - } else if (config4.multiPass) { - record2[ref.field] = null; - deferredUpdates.push({ - objectName, - recordExternalId: String(record2[externalId] ?? ""), - field: ref.field, - targetObject: ref.targetObject, - targetField: ref.targetField, - attemptedValue: fieldValue, - recordIndex: i - }); - referencesDeferred++; - } else { - const error49 = { - sourceObject: objectName, - field: ref.field, - targetObject: ref.targetObject, - targetField: ref.targetField, - attemptedValue: fieldValue, - recordIndex: i, - message: `Cannot resolve reference: ${objectName}.${ref.field} = '${fieldValue}' \u2192 ${ref.targetObject}.${ref.targetField} not found` - }; - errors.push(error49); - allErrors.push(error49); - } - } else { - const targetMap2 = insertedRecords.get(ref.targetObject); - if (!targetMap2?.has(String(fieldValue))) { - const error49 = { - sourceObject: objectName, - field: ref.field, - targetObject: ref.targetObject, - targetField: ref.targetField, - attemptedValue: fieldValue, - recordIndex: i, - message: `[dry-run] Reference may not resolve: ${objectName}.${ref.field} = '${fieldValue}' \u2192 ${ref.targetObject}.${ref.targetField}` - }; - errors.push(error49); - allErrors.push(error49); - } - } - } - if (!config4.dryRun) { - try { - const result = await this.writeRecord( - objectName, - record2, - mode, - externalId, - existingRecords - ); - if (result.action === "inserted") inserted++; - else if (result.action === "updated") updated++; - else if (result.action === "skipped") skipped++; - const externalIdValue = String(record2[externalId] ?? ""); - const internalId = result.id; - if (externalIdValue && internalId) { - insertedRecords.get(objectName).set(externalIdValue, String(internalId)); - } - } catch (err) { - errored++; - this.logger.warn(`[SeedLoader] Failed to write ${objectName} record`, { - error: err.message, - recordIndex: i - }); - } - } else { - const externalIdValue = String(record2[externalId] ?? ""); - if (externalIdValue) { - insertedRecords.get(objectName).set(externalIdValue, `dry-run-id-${i}`); - } - inserted++; - } - } - return { - object: objectName, - mode, - inserted, - updated, - skipped, - errored, - total: dataset.records.length, - referencesResolved, - referencesDeferred, - errors - }; - } - // ========================================================================== - // Internal: Reference Resolution - // ========================================================================== - async resolveFromDatabase(targetObject, targetField, value) { - try { - const records = await this.engine.find(targetObject, { - where: { [targetField]: value }, - fields: ["id"], - limit: 1 - }); - if (records && records.length > 0) { - return String(records[0].id || records[0]._id); - } - } catch { - } - return null; - } - async resolveDeferredUpdates(deferredUpdates, insertedRecords, allResults, allErrors) { - for (const deferred of deferredUpdates) { - const targetMap = insertedRecords.get(deferred.targetObject); - let resolvedId = targetMap?.get(String(deferred.attemptedValue)); - if (!resolvedId) { - resolvedId = await this.resolveFromDatabase( - deferred.targetObject, - deferred.targetField, - deferred.attemptedValue - ) ?? void 0; - } - if (resolvedId) { - const objectRecordMap = insertedRecords.get(deferred.objectName); - const recordId = objectRecordMap?.get(deferred.recordExternalId); - if (recordId) { - try { - await this.engine.update(deferred.objectName, { - id: recordId, - [deferred.field]: resolvedId - }); - const resultEntry = allResults.find((r) => r.object === deferred.objectName); - if (resultEntry) { - resultEntry.referencesResolved++; - resultEntry.referencesDeferred--; - } - } catch (err) { - this.logger.warn("[SeedLoader] Failed to resolve deferred reference", { - object: deferred.objectName, - field: deferred.field, - error: err.message - }); - } - } - } else { - const error49 = { - sourceObject: deferred.objectName, - field: deferred.field, - targetObject: deferred.targetObject, - targetField: deferred.targetField, - attemptedValue: deferred.attemptedValue, - recordIndex: deferred.recordIndex, - message: `Deferred reference unresolved after pass 2: ${deferred.objectName}.${deferred.field} = '${deferred.attemptedValue}' \u2192 ${deferred.targetObject}.${deferred.targetField} not found` - }; - const resultEntry = allResults.find((r) => r.object === deferred.objectName); - if (resultEntry) { - resultEntry.errors.push(error49); - } - allErrors.push(error49); - } - } - } - // ========================================================================== - // Internal: Write Operations - // ========================================================================== - async writeRecord(objectName, record2, mode, externalId, existingRecords) { - const externalIdValue = record2[externalId]; - const existing = existingRecords?.get(String(externalIdValue ?? "")); - switch (mode) { - case "insert": { - const result = await this.engine.insert(objectName, record2); - return { action: "inserted", id: this.extractId(result) }; - } - case "update": { - if (!existing) { - return { action: "skipped" }; - } - const id = this.extractId(existing); - await this.engine.update(objectName, { ...record2, id }); - return { action: "updated", id }; - } - case "upsert": { - if (existing) { - const id = this.extractId(existing); - await this.engine.update(objectName, { ...record2, id }); - return { action: "updated", id }; - } else { - const result = await this.engine.insert(objectName, record2); - return { action: "inserted", id: this.extractId(result) }; - } - } - case "ignore": { - if (existing) { - return { action: "skipped", id: this.extractId(existing) }; - } - const result = await this.engine.insert(objectName, record2); - return { action: "inserted", id: this.extractId(result) }; - } - case "replace": { - const result = await this.engine.insert(objectName, record2); - return { action: "inserted", id: this.extractId(result) }; - } - default: { - const result = await this.engine.insert(objectName, record2); - return { action: "inserted", id: this.extractId(result) }; - } - } - } - // ========================================================================== - // Internal: Dependency Graph - // ========================================================================== - /** - * Kahn's algorithm for topological sort with cycle detection. - */ - topologicalSort(nodes) { - const inDegree = /* @__PURE__ */ new Map(); - const adjacency = /* @__PURE__ */ new Map(); - const objectSet = new Set(nodes.map((n) => n.object)); - for (const node of nodes) { - inDegree.set(node.object, 0); - adjacency.set(node.object, []); - } - for (const node of nodes) { - for (const dep of node.dependsOn) { - if (objectSet.has(dep) && dep !== node.object) { - adjacency.get(dep).push(node.object); - inDegree.set(node.object, (inDegree.get(node.object) || 0) + 1); - } - } - } - const queue = []; - for (const [obj, degree] of inDegree) { - if (degree === 0) queue.push(obj); - } - const insertOrder = []; - while (queue.length > 0) { - const current = queue.shift(); - insertOrder.push(current); - for (const neighbor of adjacency.get(current) || []) { - const newDegree = (inDegree.get(neighbor) || 0) - 1; - inDegree.set(neighbor, newDegree); - if (newDegree === 0) { - queue.push(neighbor); - } - } - } - const circularDependencies = []; - const remaining = nodes.filter((n) => !insertOrder.includes(n.object)); - if (remaining.length > 0) { - const cycles = this.findCycles(remaining); - circularDependencies.push(...cycles); - for (const node of remaining) { - if (!insertOrder.includes(node.object)) { - insertOrder.push(node.object); - } - } - } - return { insertOrder, circularDependencies }; - } - findCycles(nodes) { - const cycles = []; - const nodeMap = new Map(nodes.map((n) => [n.object, n])); - const visited = /* @__PURE__ */ new Set(); - const inStack = /* @__PURE__ */ new Set(); - const dfs = (current, path3) => { - if (inStack.has(current)) { - const cycleStart = path3.indexOf(current); - if (cycleStart !== -1) { - cycles.push([...path3.slice(cycleStart), current]); - } - return; - } - if (visited.has(current)) return; - visited.add(current); - inStack.add(current); - path3.push(current); - const node = nodeMap.get(current); - if (node) { - for (const dep of node.dependsOn) { - if (nodeMap.has(dep)) { - dfs(dep, [...path3]); - } - } - } - inStack.delete(current); - }; - for (const node of nodes) { - if (!visited.has(node.object)) { - dfs(node.object, []); - } - } - return cycles; - } - // ========================================================================== - // Internal: Helpers - // ========================================================================== - filterByEnv(datasets, env2) { - if (!env2) return datasets; - return datasets.filter((d) => d.env.includes(env2)); - } - orderDatasets(datasets, insertOrder) { - const orderMap = new Map(insertOrder.map((name, i) => [name, i])); - return [...datasets].sort((a, b) => { - const orderA = orderMap.get(a.object) ?? Number.MAX_SAFE_INTEGER; - const orderB = orderMap.get(b.object) ?? Number.MAX_SAFE_INTEGER; - return orderA - orderB; - }); - } - buildReferenceMap(graph) { - const map3 = /* @__PURE__ */ new Map(); - for (const node of graph.nodes) { - if (node.references.length > 0) { - map3.set(node.object, node.references); - } - } - return map3; - } - async loadExistingRecords(objectName, externalId) { - const map3 = /* @__PURE__ */ new Map(); - try { - const records = await this.engine.find(objectName, { - fields: ["id", externalId] - }); - for (const record2 of records || []) { - const key = String(record2[externalId] ?? ""); - if (key) { - map3.set(key, record2); - } - } - } catch { - } - return map3; - } - looksLikeInternalId(value) { - if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) { - return true; - } - if (/^[0-9a-f]{24}$/i.test(value)) { - return true; - } - return false; - } - extractId(record2) { - if (!record2) return void 0; - return String(record2.id || record2._id || ""); - } - buildEmptyResult(config4, durationMs) { - return { - success: true, - dryRun: config4.dryRun, - dependencyGraph: { nodes: [], insertOrder: [], circularDependencies: [] }, - results: [], - errors: [], - summary: { - objectsProcessed: 0, - totalRecords: 0, - totalInserted: 0, - totalUpdated: 0, - totalSkipped: 0, - totalErrored: 0, - totalReferencesResolved: 0, - totalReferencesDeferred: 0, - circularDependencyCount: 0, - durationMs - } - }; - } - buildResult(config4, graph, results, errors, durationMs) { - const summary = { - objectsProcessed: results.length, - totalRecords: results.reduce((sum, r) => sum + r.total, 0), - totalInserted: results.reduce((sum, r) => sum + r.inserted, 0), - totalUpdated: results.reduce((sum, r) => sum + r.updated, 0), - totalSkipped: results.reduce((sum, r) => sum + r.skipped, 0), - totalErrored: results.reduce((sum, r) => sum + r.errored, 0), - totalReferencesResolved: results.reduce((sum, r) => sum + r.referencesResolved, 0), - totalReferencesDeferred: results.reduce((sum, r) => sum + r.referencesDeferred, 0), - circularDependencyCount: graph.circularDependencies.length, - durationMs - }; - const hasErrors = errors.length > 0 || summary.totalErrored > 0; - return { - success: !hasErrors, - dryRun: config4.dryRun, - dependencyGraph: graph, - results, - errors, - summary - }; - } -}; -var AppPlugin = class { - constructor(bundle) { - this.type = "app"; - this.init = async (ctx) => { - const sys2 = this.bundle.manifest || this.bundle; - const appId2 = sys2.id || sys2.name; - ctx.logger.info("Registering App Service", { - appId: appId2, - pluginName: this.name, - version: this.version - }); - const servicePayload = this.bundle.manifest ? { ...this.bundle.manifest, ...this.bundle } : this.bundle; - ctx.getService("manifest").register(servicePayload); - }; - this.start = async (ctx) => { - const sys2 = this.bundle.manifest || this.bundle; - const appId2 = sys2.id || sys2.name; - let ql; - try { - ql = ctx.getService("objectql"); - } catch { - } - if (!ql) { - ctx.logger.warn("ObjectQL engine service not found", { - appName: this.name, - appId: appId2 - }); - return; - } - ctx.logger.debug("Retrieved ObjectQL engine service", { appId: appId2 }); - const runtime = this.bundle.default || this.bundle; - if (runtime && typeof runtime.onEnable === "function") { - ctx.logger.info("Executing runtime.onEnable", { - appName: this.name, - appId: appId2 - }); - const hostContext = { - ...ctx, - ql, - logger: ctx.logger, - drivers: { - register: (driver) => { - ctx.logger.debug("Registering driver via app runtime", { - driverName: driver.name, - appId: appId2 - }); - ql.registerDriver(driver); - } - } - }; - await runtime.onEnable(hostContext); - ctx.logger.debug("Runtime.onEnable completed", { appId: appId2 }); - } else { - ctx.logger.debug("No runtime.onEnable function found", { appId: appId2 }); - } - this.loadTranslations(ctx, appId2); - const seedDatasets = []; - if (Array.isArray(this.bundle.data)) { - seedDatasets.push(...this.bundle.data); - } - const manifest = this.bundle.manifest || this.bundle; - if (manifest && Array.isArray(manifest.data)) { - seedDatasets.push(...manifest.data); - } - const namespace = (this.bundle.manifest || this.bundle)?.namespace; - const RESERVED_NS = /* @__PURE__ */ new Set(["base", "system"]); - const toFQN = (name) => { - if (name.includes("__") || !namespace || RESERVED_NS.has(namespace)) return name; - return `${namespace}__${name}`; - }; - if (seedDatasets.length > 0) { - ctx.logger.info(`[AppPlugin] Found ${seedDatasets.length} seed datasets for ${appId2}`); - const normalizedDatasets = seedDatasets.filter((d) => d.object && Array.isArray(d.records)).map((d) => ({ - ...d, - object: toFQN(d.object) - })); - try { - const metadata = ctx.getService("metadata"); - if (metadata) { - const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger); - const { SeedLoaderRequestSchema: SeedLoaderRequestSchema3 } = await Promise.resolve().then(() => (init_data(), data_exports)); - const request = SeedLoaderRequestSchema3.parse({ - datasets: normalizedDatasets, - config: { defaultMode: "upsert", multiPass: true } - }); - const result = await seedLoader.load(request); - ctx.logger.info("[Seeder] Seed loading complete", { - inserted: result.summary.totalInserted, - updated: result.summary.totalUpdated, - errors: result.errors.length - }); - } else { - ctx.logger.debug("[Seeder] No metadata service; using basic insert fallback"); - for (const dataset of normalizedDatasets) { - ctx.logger.info(`[Seeder] Seeding ${dataset.records.length} records for ${dataset.object}`); - for (const record2 of dataset.records) { - try { - await ql.insert(dataset.object, record2); - } catch (err) { - ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: err.message }); - } - } - } - ctx.logger.info("[Seeder] Data seeding complete."); - } - } catch (err) { - ctx.logger.warn("[Seeder] SeedLoaderService failed, falling back to basic insert", { error: err.message }); - for (const dataset of normalizedDatasets) { - for (const record2 of dataset.records) { - try { - await ql.insert(dataset.object, record2); - } catch (insertErr) { - ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: insertErr.message }); - } - } - } - ctx.logger.info("[Seeder] Data seeding complete (fallback)."); - } - } - }; - this.bundle = bundle; - const sys = bundle.manifest || bundle; - const appId = sys.id || sys.name || "unnamed-app"; - this.name = `plugin.app.${appId}`; - this.version = sys.version; - } - /** - * Auto-load i18n translation bundles from the app config into the - * kernel's i18n service. Handles both `translations` (array of - * TranslationBundle) and `i18n` config (default locale, etc.). - * - * Gracefully skips when the i18n service is not registered — - * this keeps AppPlugin resilient across server/dev/mock environments. - */ - loadTranslations(ctx, appId) { - let i18nService; - try { - i18nService = ctx.getService("i18n"); - } catch { - } - const bundles = []; - if (Array.isArray(this.bundle.translations)) { - bundles.push(...this.bundle.translations); - } - const manifest = this.bundle.manifest || this.bundle; - if (manifest && Array.isArray(manifest.translations) && manifest.translations !== this.bundle.translations) { - bundles.push(...manifest.translations); - } - if (!i18nService) { - if (bundles.length > 0) { - ctx.logger.warn( - `[i18n] App "${appId}" has ${bundles.length} translation bundle(s) but no i18n service is registered. Translations will not be served via REST API. Register I18nServicePlugin from @objectstack/service-i18n, or use DevPlugin which auto-detects translations and registers the i18n service automatically.` - ); - } else { - ctx.logger.debug("[i18n] No i18n service registered; skipping translation loading", { appId }); - } - return; - } - const i18nConfig = this.bundle.i18n || (this.bundle.manifest || this.bundle)?.i18n; - if (i18nConfig?.defaultLocale && typeof i18nService.setDefaultLocale === "function") { - i18nService.setDefaultLocale(i18nConfig.defaultLocale); - ctx.logger.debug("[i18n] Set default locale", { appId, locale: i18nConfig.defaultLocale }); - } - if (bundles.length === 0) { - return; - } - let loadedLocales = 0; - for (const bundle of bundles) { - for (const [locale, data] of Object.entries(bundle)) { - if (data && typeof data === "object") { - try { - i18nService.loadTranslations(locale, data); - loadedLocales++; - } catch (err) { - ctx.logger.warn("[i18n] Failed to load translations", { appId, locale, error: err.message }); - } - } - } - } - const svcAny = i18nService; - if (svcAny._fallback || svcAny._dev) { - ctx.logger.info( - `[i18n] Loaded ${loadedLocales} locale(s) into in-memory i18n fallback for "${appId}". For production, consider registering I18nServicePlugin from @objectstack/service-i18n.` - ); - } else { - ctx.logger.info("[i18n] Loaded translation bundles", { appId, bundles: bundles.length, locales: loadedLocales }); - } - } -}; -function randomUUID() { - if (globalThis.crypto && typeof globalThis.crypto.randomUUID === "function") { - return globalThis.crypto.randomUUID(); - } - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = Math.random() * 16 | 0; - const v = c === "x" ? r : r & 3 | 8; - return v.toString(16); - }); -} -var HttpDispatcher = class { - // Casting to any to access dynamic props like broker, services, graphql - constructor(kernel) { - this.kernel = kernel; - } - success(data, meta3) { - return { - status: 200, - body: { success: true, data, meta: meta3 } - }; - } - error(message2, code = 500, details) { - return { - status: code, - body: { success: false, error: { message: message2, code, details } } - }; - } - /** - * 404 Route Not Found — no route is registered for this path. - */ - routeNotFound(route) { - return { - status: 404, - body: { - success: false, - error: { - code: 404, - message: `Route Not Found: ${route}`, - type: "ROUTE_NOT_FOUND", - route, - hint: "No route is registered for this path. Check the API discovery endpoint for available routes." - } - } - }; - } - ensureBroker() { - if (!this.kernel.broker) { - throw { statusCode: 500, message: "Kernel Broker not available" }; - } - return this.kernel.broker; - } - /** - * Generates the discovery JSON response for the API root. - * - * Uses the same async `resolveService()` fallback chain that request - * handlers use, so the reported service status is always consistent - * with the actual runtime availability. - */ - async getDiscoveryInfo(prefix) { - const [ - authSvc, - graphqlSvc, - searchSvc, - realtimeSvc, - filesSvc, - analyticsSvc, - workflowSvc, - aiSvc, - notificationSvc, - i18nSvc, - uiSvc, - automationSvc, - cacheSvc, - queueSvc, - jobSvc - ] = await Promise.all([ - this.resolveService(CoreServiceName.enum.auth), - this.resolveService(CoreServiceName.enum.graphql), - this.resolveService(CoreServiceName.enum.search), - this.resolveService(CoreServiceName.enum.realtime), - this.resolveService(CoreServiceName.enum["file-storage"]), - this.resolveService(CoreServiceName.enum.analytics), - this.resolveService(CoreServiceName.enum.workflow), - this.resolveService(CoreServiceName.enum.ai), - this.resolveService(CoreServiceName.enum.notification), - this.resolveService(CoreServiceName.enum.i18n), - this.resolveService(CoreServiceName.enum.ui), - this.resolveService(CoreServiceName.enum.automation), - this.resolveService(CoreServiceName.enum.cache), - this.resolveService(CoreServiceName.enum.queue), - this.resolveService(CoreServiceName.enum.job) - ]); - const hasAuth = !!authSvc; - const hasGraphQL = !!(graphqlSvc || this.kernel.graphql); - const hasSearch = !!searchSvc; - const hasWebSockets = !!realtimeSvc; - const hasFiles = !!filesSvc; - const hasAnalytics = !!analyticsSvc; - const hasWorkflow = !!workflowSvc; - const hasAi = !!aiSvc; - const hasNotification = !!notificationSvc; - const hasI18n = !!i18nSvc; - const hasUi = !!uiSvc; - const hasAutomation = !!automationSvc; - const hasCache = !!cacheSvc; - const hasQueue = !!queueSvc; - const hasJob = !!jobSvc; - const routes = { - data: `${prefix}/data`, - metadata: `${prefix}/meta`, - packages: `${prefix}/packages`, - auth: hasAuth ? `${prefix}/auth` : void 0, - ui: hasUi ? `${prefix}/ui` : void 0, - graphql: hasGraphQL ? `${prefix}/graphql` : void 0, - storage: hasFiles ? `${prefix}/storage` : void 0, - analytics: hasAnalytics ? `${prefix}/analytics` : void 0, - automation: hasAutomation ? `${prefix}/automation` : void 0, - workflow: hasWorkflow ? `${prefix}/workflow` : void 0, - realtime: hasWebSockets ? `${prefix}/realtime` : void 0, - notifications: hasNotification ? `${prefix}/notifications` : void 0, - ai: hasAi ? `${prefix}/ai` : void 0, - i18n: hasI18n ? `${prefix}/i18n` : void 0 - }; - const svcAvailable = (route, provider) => ({ - enabled: true, - status: "available", - handlerReady: true, - route, - provider - }); - const svcUnavailable = (name) => ({ - enabled: false, - status: "unavailable", - handlerReady: false, - message: `Install a ${name} plugin to enable` - }); - let locale = { default: "en", supported: ["en"], timezone: "UTC" }; - if (hasI18n && i18nSvc) { - const defaultLocale = typeof i18nSvc.getDefaultLocale === "function" ? i18nSvc.getDefaultLocale() : "en"; - const locales = typeof i18nSvc.getLocales === "function" ? i18nSvc.getLocales() : []; - locale = { - default: defaultLocale, - supported: locales.length > 0 ? locales : [defaultLocale], - timezone: "UTC" - }; - } - return { - name: "ObjectOS", - version: "1.0.0", - environment: getEnv("NODE_ENV", "development"), - routes, - endpoints: routes, - // Alias for backward compatibility with some clients - features: { - graphql: hasGraphQL, - search: hasSearch, - websockets: hasWebSockets, - files: hasFiles, - analytics: hasAnalytics, - ai: hasAi, - workflow: hasWorkflow, - notifications: hasNotification, - i18n: hasI18n - }, - services: { - // Kernel-provided (always available via protocol implementation) - metadata: { enabled: true, status: "degraded", handlerReady: true, route: routes.metadata, provider: "kernel", message: "In-memory registry; DB persistence pending" }, - data: svcAvailable(routes.data, "kernel"), - // Plugin-provided — only available when a plugin registers the service - auth: hasAuth ? svcAvailable(routes.auth) : svcUnavailable("auth"), - automation: hasAutomation ? svcAvailable(routes.automation) : svcUnavailable("automation"), - analytics: hasAnalytics ? svcAvailable(routes.analytics) : svcUnavailable("analytics"), - cache: hasCache ? svcAvailable() : svcUnavailable("cache"), - queue: hasQueue ? svcAvailable() : svcUnavailable("queue"), - job: hasJob ? svcAvailable() : svcUnavailable("job"), - ui: hasUi ? svcAvailable(routes.ui) : svcUnavailable("ui"), - workflow: hasWorkflow ? svcAvailable(routes.workflow) : svcUnavailable("workflow"), - realtime: hasWebSockets ? svcAvailable(routes.realtime) : svcUnavailable("realtime"), - notification: hasNotification ? svcAvailable(routes.notifications) : svcUnavailable("notification"), - ai: hasAi ? svcAvailable(routes.ai) : svcUnavailable("ai"), - i18n: hasI18n ? svcAvailable(routes.i18n) : svcUnavailable("i18n"), - graphql: hasGraphQL ? svcAvailable(routes.graphql) : svcUnavailable("graphql"), - "file-storage": hasFiles ? svcAvailable(routes.storage) : svcUnavailable("file-storage"), - search: hasSearch ? svcAvailable() : svcUnavailable("search") - }, - locale - }; - } - /** - * Handles GraphQL requests - */ - async handleGraphQL(body, context) { - if (!body || !body.query) { - throw { statusCode: 400, message: "Missing query in request body" }; - } - if (typeof this.kernel.graphql !== "function") { - throw { statusCode: 501, message: "GraphQL service not available" }; - } - return this.kernel.graphql(body.query, body.variables, { - request: context.request - }); - } - /** - * Handles Auth requests - * path: sub-path after /auth/ - */ - async handleAuth(path3, method, body, context) { - const authService = await this.getService(CoreServiceName.enum.auth); - if (authService && typeof authService.handler === "function") { - const response = await authService.handler(context.request, context.response); - return { handled: true, result: response }; - } - const normalizedPath = path3.replace(/^\/+/, ""); - if (normalizedPath === "login" && method.toUpperCase() === "POST") { - try { - const broker = this.ensureBroker(); - const data = await broker.call("auth.login", body, { request: context.request }); - return { handled: true, response: { status: 200, body: data } }; - } catch (error49) { - const statusCode = error49?.statusCode ?? error49?.status; - if (statusCode !== 500 || !error49?.message?.includes("Broker not available")) { - throw error49; - } - } - } - return this.mockAuthFallback(normalizedPath, method, body); - } - /** - * Provides mock auth responses for core better-auth endpoints when - * AuthPlugin is not loaded (e.g. MSW/browser-only environments). - * This ensures registration/sign-in flows do not 404 in mock mode. - */ - mockAuthFallback(path3, method, body) { - const m = method.toUpperCase(); - const MOCK_SESSION_EXPIRY_MS = 864e5; - if ((path3 === "sign-up/email" || path3 === "register") && m === "POST") { - const id = `mock_${randomUUID()}`; - return { - handled: true, - response: { - status: 200, - body: { - user: { id, name: body?.name || "Mock User", email: body?.email || "mock@test.local", emailVerified: false, createdAt: (/* @__PURE__ */ new Date()).toISOString(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, - session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() } - } - } - }; - } - if ((path3 === "sign-in/email" || path3 === "login") && m === "POST") { - const id = `mock_${randomUUID()}`; - return { - handled: true, - response: { - status: 200, - body: { - user: { id, name: "Mock User", email: body?.email || "mock@test.local", emailVerified: true, createdAt: (/* @__PURE__ */ new Date()).toISOString(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, - session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() } - } - } - }; - } - if (path3 === "get-session" && m === "GET") { - return { - handled: true, - response: { status: 200, body: { session: null, user: null } } - }; - } - if (path3 === "sign-out" && m === "POST") { - return { - handled: true, - response: { status: 200, body: { success: true } } - }; - } - return { handled: false }; - } - /** - * Handles Metadata requests - * Standard: /metadata/:type/:name - * Fallback for backward compat: /metadata (all objects), /metadata/:objectName (get object) - */ - async handleMetadata(path3, context, method, body, query) { - const broker = this.kernel.broker ?? null; - const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); - if (parts[0] === "types") { - console.log("[HttpDispatcher] Attempting to resolve MetadataService..."); - console.log("[HttpDispatcher] Available kernel methods:", { - hasGetServiceAsync: typeof this.kernel.getServiceAsync === "function", - hasGetService: typeof this.kernel.getService === "function", - hasContext: !!this.kernel.context, - hasContextGetService: typeof this.kernel.context?.getService === "function" - }); - let metadataService = null; - if (typeof this.kernel.getServiceAsync === "function") { - try { - metadataService = await this.kernel.getServiceAsync("metadata"); - console.log('[HttpDispatcher] kernel.getServiceAsync("metadata") returned:', !!metadataService); - } catch (e) { - console.log('[HttpDispatcher] kernel.getServiceAsync("metadata") failed:', e.message); - } - } - if (!metadataService && typeof this.kernel.getService === "function") { - try { - metadataService = await this.kernel.getService("metadata"); - console.log('[HttpDispatcher] kernel.getService("metadata") returned:', !!metadataService); - } catch (e) { - console.log('[HttpDispatcher] kernel.getService("metadata") failed:', e.message); - } - } - if (!metadataService && this.kernel.context?.getService) { - try { - metadataService = await this.kernel.context.getService("metadata"); - console.log('[HttpDispatcher] kernel.context.getService("metadata") returned:', !!metadataService); - } catch (e) { - console.log('[HttpDispatcher] kernel.context.getService("metadata") failed:', e.message); - } - } - console.log("[HttpDispatcher] Final metadataService:", !!metadataService, "has getRegisteredTypes:", typeof metadataService?.getRegisteredTypes); - if (metadataService && typeof metadataService.getRegisteredTypes === "function") { - try { - const types = await metadataService.getRegisteredTypes(); - console.log("[HttpDispatcher] MetadataService.getRegisteredTypes() returned:", types); - return { handled: true, response: this.success({ types }) }; - } catch (e) { - console.warn("[HttpDispatcher] MetadataService.getRegisteredTypes() failed:", e.message, e.stack); - } - } else { - console.log("[HttpDispatcher] MetadataService not available or missing getRegisteredTypes, falling back to protocol service"); - } - const protocol = await this.resolveService("protocol"); - if (protocol && typeof protocol.getMetaTypes === "function") { - const result = await protocol.getMetaTypes({}); - console.log("[HttpDispatcher] Protocol service returned types:", result); - return { handled: true, response: this.success(result) }; - } - if (broker) { - try { - const data = await broker.call("metadata.types", {}, { request: context.request }); - console.log("[HttpDispatcher] Broker returned types:", data); - return { handled: true, response: this.success(data) }; - } catch (e) { - console.log("[HttpDispatcher] Broker call failed:", e); - } - } - console.warn("[HttpDispatcher] Falling back to hardcoded defaults for metadata types"); - return { handled: true, response: this.success({ types: ["object", "app", "plugin"] }) }; - } - if (parts.length === 3 && parts[2] === "published" && (!method || method === "GET")) { - const [type, name] = parts; - const metadataService = await this.getService(CoreServiceName.enum.metadata); - if (metadataService && typeof metadataService.getPublished === "function") { - const data = await metadataService.getPublished(type, name); - if (data === void 0) return { handled: true, response: this.error("Not found", 404) }; - return { handled: true, response: this.success(data) }; - } - if (broker) { - try { - const data = await broker.call("metadata.getPublished", { type, name }, { request: context.request }); - return { handled: true, response: this.success(data) }; - } catch (e) { - return { handled: true, response: this.error(e.message, 404) }; - } - } - return { handled: true, response: this.error("Not found", 404) }; - } - if (parts.length === 2) { - const [type, name] = parts; - const packageId = query?.package || void 0; - if (method === "PUT" && body) { - const protocol = await this.resolveService("protocol"); - if (protocol && typeof protocol.saveMetaItem === "function") { - try { - const result = await protocol.saveMetaItem({ type, name, item: body }); - return { handled: true, response: this.success(result) }; - } catch (e) { - return { handled: true, response: this.error(e.message, 400) }; - } - } - if (broker) { - try { - const data = await broker.call("metadata.saveItem", { type, name, item: body }, { request: context.request }); - return { handled: true, response: this.success(data) }; - } catch (e) { - return { handled: true, response: this.error(e.message || "Save not supported", 501) }; - } - } - return { handled: true, response: this.error("Save not supported", 501) }; - } - try { - if (type === "objects" || type === "object") { - if (broker) { - const data = await broker.call("metadata.getObject", { objectName: name }, { request: context.request }); - return { handled: true, response: this.success(data) }; - } - const qlService = await this.getObjectQLService(); - if (qlService?.registry) { - const data = qlService.registry.getObject(name); - if (data) return { handled: true, response: this.success(data) }; - } - return { handled: true, response: this.error("Not found", 404) }; - } - const singularType = pluralToSingular(type); - const protocol = await this.resolveService("protocol"); - if (protocol && typeof protocol.getMetaItem === "function") { - try { - const data = await protocol.getMetaItem({ type: singularType, name, packageId }); - return { handled: true, response: this.success(data) }; - } catch (e) { - } - } - if (broker) { - const method2 = `metadata.get${this.capitalize(singularType)}`; - const data = await broker.call(method2, { name }, { request: context.request }); - return { handled: true, response: this.success(data) }; - } - return { handled: true, response: this.error("Not found", 404) }; - } catch (e) { - return { handled: true, response: this.error(e.message, 404) }; - } - } - if (parts.length === 1) { - const typeOrName = parts[0]; - const packageId = query?.package || void 0; - const protocol = await this.resolveService("protocol"); - if (protocol && typeof protocol.getMetaItems === "function") { - try { - const data = await protocol.getMetaItems({ type: typeOrName, packageId }); - if (data && (data.items !== void 0 || Array.isArray(data))) { - return { handled: true, response: this.success(data) }; - } - } catch { - } - } - const metadataService = await this.getService(CoreServiceName.enum.metadata); - if (metadataService && typeof metadataService.list === "function") { - try { - const items = await metadataService.list(typeOrName); - if (items && items.length > 0) { - return { handled: true, response: this.success({ type: typeOrName, items }) }; - } - } catch (e) { - const sanitizedType = String(typeOrName).replace(/[\r\n\t]/g, ""); - console.debug(`[HttpDispatcher] MetadataService.list() failed for type:`, sanitizedType, "error:", e.message); - } - } - if (broker) { - try { - if (typeOrName === "objects") { - const data2 = await broker.call("metadata.objects", { packageId }, { request: context.request }); - return { handled: true, response: this.success(data2) }; - } - const data = await broker.call(`metadata.${typeOrName}`, { packageId }, { request: context.request }); - if (data !== null && data !== void 0) { - return { handled: true, response: this.success(data) }; - } - } catch { - } - try { - const data = await broker.call("metadata.getObject", { objectName: typeOrName }, { request: context.request }); - return { handled: true, response: this.success(data) }; - } catch (e) { - return { handled: true, response: this.error(e.message, 404) }; - } - } - const qlService = await this.getObjectQLService(); - if (qlService?.registry) { - if (typeOrName === "objects") { - const objs = qlService.registry.getAllObjects(packageId); - return { handled: true, response: this.success({ type: "object", items: objs }) }; - } - const items = qlService.registry.listItems?.(typeOrName, packageId); - if (items && items.length > 0) { - return { handled: true, response: this.success({ type: typeOrName, items }) }; - } - const obj = qlService.registry.getObject(typeOrName); - if (obj) return { handled: true, response: this.success(obj) }; - } - return { handled: true, response: this.error("Not found", 404) }; - } - if (parts.length === 0) { - const protocol = await this.resolveService("protocol"); - if (protocol && typeof protocol.getMetaTypes === "function") { - const result = await protocol.getMetaTypes({}); - return { handled: true, response: this.success(result) }; - } - if (broker) { - try { - const data = await broker.call("metadata.types", {}, { request: context.request }); - return { handled: true, response: this.success(data) }; - } catch { - } - } - return { handled: true, response: this.success({ types: ["object", "app", "plugin"] }) }; - } - return { handled: false }; - } - /** - * Handles Data requests - * path: sub-path after /data/ (e.g. "contacts", "contacts/123", "contacts/query") - */ - async handleData(path3, method, body, query, context) { - const broker = this.ensureBroker(); - const parts = path3.replace(/^\/+/, "").split("/"); - const objectName = parts[0]; - if (!objectName) { - return { handled: true, response: this.error("Object name required", 400) }; - } - const m = method.toUpperCase(); - if (parts.length > 1) { - const action = parts[1]; - if (action === "query" && m === "POST") { - const result = await broker.call("data.query", { object: objectName, ...body }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (action === "batch" && m === "POST") { - const result = await broker.call("data.batch", { object: objectName, ...body }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (parts.length === 2 && m === "GET") { - const id = parts[1]; - const { select, expand: expand2 } = query || {}; - const allowedParams = {}; - if (select != null) allowedParams.select = select; - if (expand2 != null) allowedParams.expand = expand2; - const result = await broker.call("data.get", { object: objectName, id, ...allowedParams }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (parts.length === 2 && m === "PATCH") { - const id = parts[1]; - const result = await broker.call("data.update", { object: objectName, id, data: body }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (parts.length === 2 && m === "DELETE") { - const id = parts[1]; - const result = await broker.call("data.delete", { object: objectName, id }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - } else { - if (m === "GET") { - const normalized = { ...query }; - if (normalized.filter != null || normalized.filters != null) { - normalized.where = normalized.where ?? normalized.filter ?? normalized.filters; - delete normalized.filter; - delete normalized.filters; - } - if (normalized.select != null && normalized.fields == null) { - normalized.fields = normalized.select; - delete normalized.select; - } - if (normalized.sort != null && normalized.orderBy == null) { - normalized.orderBy = normalized.sort; - delete normalized.sort; - } - if (normalized.top != null && normalized.limit == null) { - normalized.limit = normalized.top; - delete normalized.top; - } - if (normalized.skip != null && normalized.offset == null) { - normalized.offset = normalized.skip; - delete normalized.skip; - } - const result = await broker.call("data.query", { object: objectName, query: normalized }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (m === "POST") { - const result = await broker.call("data.create", { object: objectName, data: body }, { request: context.request }); - const res = this.success(result); - res.status = 201; - return { handled: true, response: res }; - } - } - return { handled: false }; - } - /** - * Handles Analytics requests - * path: sub-path after /analytics/ - */ - async handleAnalytics(path3, method, body, _context2) { - const analyticsService = await this.getService(CoreServiceName.enum.analytics); - if (!analyticsService) return { handled: false }; - const m = method.toUpperCase(); - const subPath = path3.replace(/^\/+/, ""); - if (subPath === "query" && m === "POST") { - const result = await analyticsService.query(body); - return { handled: true, response: this.success(result) }; - } - if (subPath === "meta" && m === "GET") { - const result = await analyticsService.getMeta(); - return { handled: true, response: this.success(result) }; - } - if (subPath === "sql" && m === "POST") { - const result = await analyticsService.generateSql(body); - return { handled: true, response: this.success(result) }; - } - return { handled: false }; - } - /** - * Handles i18n requests - * path: sub-path after /i18n/ - * - * Routes: - * GET /locales → getLocales - * GET /translations/:locale → getTranslations (locale from path) - * GET /translations?locale=xx → getTranslations (locale from query) - * GET /labels/:object/:locale → getFieldLabels (both from path) - * GET /labels/:object?locale=xx → getFieldLabels (locale from query) - */ - async handleI18n(path3, method, query, _context2) { - const i18nService = await this.getService(CoreServiceName.enum.i18n); - if (!i18nService) return { handled: true, response: this.error("i18n service not available", 501) }; - const m = method.toUpperCase(); - const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); - if (m !== "GET") return { handled: false }; - if (parts[0] === "locales" && parts.length === 1) { - const locales = i18nService.getLocales(); - return { handled: true, response: this.success({ locales }) }; - } - if (parts[0] === "translations") { - const locale = parts[1] ? decodeURIComponent(parts[1]) : query?.locale; - if (!locale) return { handled: true, response: this.error("Missing locale parameter", 400) }; - let translations = i18nService.getTranslations(locale); - if (Object.keys(translations).length === 0) { - const availableLocales = typeof i18nService.getLocales === "function" ? i18nService.getLocales() : []; - const resolved = resolveLocale(locale, availableLocales); - if (resolved && resolved !== locale) { - translations = i18nService.getTranslations(resolved); - return { handled: true, response: this.success({ locale: resolved, requestedLocale: locale, translations }) }; - } - } - return { handled: true, response: this.success({ locale, translations }) }; - } - if (parts[0] === "labels" && parts.length >= 2) { - const objectName = decodeURIComponent(parts[1]); - let locale = parts[2] ? decodeURIComponent(parts[2]) : query?.locale; - if (!locale) return { handled: true, response: this.error("Missing locale parameter", 400) }; - const availableLocales = typeof i18nService.getLocales === "function" ? i18nService.getLocales() : []; - const resolved = resolveLocale(locale, availableLocales); - if (resolved) locale = resolved; - if (typeof i18nService.getFieldLabels === "function") { - const labels2 = i18nService.getFieldLabels(objectName, locale); - return { handled: true, response: this.success({ object: objectName, locale, labels: labels2 }) }; - } - const translations = i18nService.getTranslations(locale); - const prefix = `o.${objectName}.fields.`; - const labels = {}; - for (const [key, value] of Object.entries(translations)) { - if (key.startsWith(prefix)) { - labels[key.substring(prefix.length)] = value; - } - } - return { handled: true, response: this.success({ object: objectName, locale, labels }) }; - } - return { handled: false }; - } - /** - * Handles Package Management requests - * - * REST Endpoints: - * - GET /packages → list all installed packages - * - GET /packages/:id → get a specific package - * - POST /packages → install a new package - * - DELETE /packages/:id → uninstall a package - * - PATCH /packages/:id/enable → enable a package - * - PATCH /packages/:id/disable → disable a package - * - POST /packages/:id/publish → publish a package (metadata snapshot) - * - POST /packages/:id/revert → revert a package to last published state - * - * Uses ObjectQL SchemaRegistry directly (via the 'objectql' service) - * with broker fallback for backward compatibility. - */ - async handlePackages(path3, method, body, query, context) { - const m = method.toUpperCase(); - const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); - const qlService = await this.getObjectQLService(); - const registry2 = qlService?.registry; - if (!registry2) { - if (this.kernel.broker) { - return this.handlePackagesViaBroker(parts, m, body, query, context); - } - return { handled: true, response: this.error("Package service not available", 503) }; - } - try { - if (parts.length === 0 && m === "GET") { - let packages = registry2.getAllPackages(); - if (query?.status) { - packages = packages.filter((p) => p.status === query.status); - } - if (query?.type) { - packages = packages.filter((p) => p.manifest?.type === query.type); - } - return { handled: true, response: this.success({ packages, total: packages.length }) }; - } - if (parts.length === 0 && m === "POST") { - const pkg = registry2.installPackage(body.manifest || body, body.settings); - const res = this.success(pkg); - res.status = 201; - return { handled: true, response: res }; - } - if (parts.length === 2 && parts[1] === "enable" && m === "PATCH") { - const id = decodeURIComponent(parts[0]); - const pkg = registry2.enablePackage(id); - if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) }; - return { handled: true, response: this.success(pkg) }; - } - if (parts.length === 2 && parts[1] === "disable" && m === "PATCH") { - const id = decodeURIComponent(parts[0]); - const pkg = registry2.disablePackage(id); - if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) }; - return { handled: true, response: this.success(pkg) }; - } - if (parts.length === 2 && parts[1] === "publish" && m === "POST") { - const id = decodeURIComponent(parts[0]); - const metadataService = await this.getService(CoreServiceName.enum.metadata); - if (metadataService && typeof metadataService.publishPackage === "function") { - const result = await metadataService.publishPackage(id, body || {}); - return { handled: true, response: this.success(result) }; - } - if (this.kernel.broker) { - const result = await this.kernel.broker.call("metadata.publishPackage", { packageId: id, ...body }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - return { handled: true, response: this.error("Metadata service not available", 503) }; - } - if (parts.length === 2 && parts[1] === "revert" && m === "POST") { - const id = decodeURIComponent(parts[0]); - const metadataService = await this.getService(CoreServiceName.enum.metadata); - if (metadataService && typeof metadataService.revertPackage === "function") { - await metadataService.revertPackage(id); - return { handled: true, response: this.success({ success: true }) }; - } - if (this.kernel.broker) { - await this.kernel.broker.call("metadata.revertPackage", { packageId: id }, { request: context.request }); - return { handled: true, response: this.success({ success: true }) }; - } - return { handled: true, response: this.error("Metadata service not available", 503) }; - } - if (parts.length === 1 && m === "GET") { - const id = decodeURIComponent(parts[0]); - const pkg = registry2.getPackage(id); - if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) }; - return { handled: true, response: this.success(pkg) }; - } - if (parts.length === 1 && m === "DELETE") { - const id = decodeURIComponent(parts[0]); - const success2 = registry2.uninstallPackage(id); - if (!success2) return { handled: true, response: this.error(`Package '${id}' not found`, 404) }; - return { handled: true, response: this.success({ success: true }) }; - } - } catch (e) { - return { handled: true, response: this.error(e.message, e.statusCode || 500) }; - } - return { handled: false }; - } - /** - * Fallback: handle packages via broker (for backward compatibility) - */ - async handlePackagesViaBroker(parts, m, body, query, context) { - const broker = this.kernel.broker; - try { - if (parts.length === 0 && m === "GET") { - const result = await broker.call("package.list", query || {}, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (parts.length === 0 && m === "POST") { - const result = await broker.call("package.install", body, { request: context.request }); - const res = this.success(result); - res.status = 201; - return { handled: true, response: res }; - } - if (parts.length === 2 && parts[1] === "enable" && m === "PATCH") { - const id = decodeURIComponent(parts[0]); - const result = await broker.call("package.enable", { id }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (parts.length === 2 && parts[1] === "disable" && m === "PATCH") { - const id = decodeURIComponent(parts[0]); - const result = await broker.call("package.disable", { id }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (parts.length === 1 && m === "GET") { - const id = decodeURIComponent(parts[0]); - const result = await broker.call("package.get", { id }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (parts.length === 1 && m === "DELETE") { - const id = decodeURIComponent(parts[0]); - const result = await broker.call("package.uninstall", { id }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - } catch (e) { - return { handled: true, response: this.error(e.message, e.statusCode || 500) }; - } - return { handled: false }; - } - /** - * Handles Storage requests - * path: sub-path after /storage/ - */ - async handleStorage(path3, method, file2, context) { - const storageService = await this.getService(CoreServiceName.enum["file-storage"]) || this.kernel.services?.["file-storage"]; - if (!storageService) { - return { handled: true, response: this.error("File storage not configured", 501) }; - } - const m = method.toUpperCase(); - const parts = path3.replace(/^\/+/, "").split("/"); - if (parts[0] === "upload" && m === "POST") { - if (!file2) { - return { handled: true, response: this.error("No file provided", 400) }; - } - const result = await storageService.upload(file2, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (parts[0] === "file" && parts[1] && m === "GET") { - const id = parts[1]; - const result = await storageService.download(id, { request: context.request }); - if (result.url && result.redirect) { - return { handled: true, result: { type: "redirect", url: result.url } }; - } - if (result.stream) { - return { - handled: true, - result: { - type: "stream", - stream: result.stream, - headers: { - "Content-Type": result.mimeType || "application/octet-stream", - "Content-Length": result.size - } - } - }; - } - return { handled: true, response: this.success(result) }; - } - return { handled: false }; - } - /** - * Handles UI requests - * path: sub-path after /ui/ - */ - async handleUi(path3, query, _context2) { - const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); - if (parts[0] === "view" && parts[1]) { - const objectName = parts[1]; - const type = parts[2] || query?.type || "list"; - const protocol = await this.resolveService("protocol"); - if (protocol && typeof protocol.getUiView === "function") { - try { - const result = await protocol.getUiView({ object: objectName, type }); - return { handled: true, response: this.success(result) }; - } catch (e) { - return { handled: true, response: this.error(e.message, 500) }; - } - } else { - return { handled: true, response: this.error("Protocol service not available", 503) }; - } - } - return { handled: false }; - } - /** - * Handles Automation requests - * path: sub-path after /automation/ - * - * Routes: - * GET / → listFlows - * GET /:name → getFlow - * POST / → createFlow (registerFlow) - * PUT /:name → updateFlow - * DELETE /:name → deleteFlow (unregisterFlow) - * POST /:name/trigger → execute (legacy: trigger/:name also supported) - * POST /:name/toggle → toggleFlow - * GET /:name/runs → listRuns - * GET /:name/runs/:runId → getRun - */ - async handleAutomation(path3, method, body, context, query) { - const automationService = await this.getService(CoreServiceName.enum.automation); - if (!automationService) return { handled: false }; - const m = method.toUpperCase(); - const parts = path3.replace(/^\/+/, "").split("/").filter(Boolean); - if (parts[0] === "trigger" && parts[1] && m === "POST") { - const triggerName = parts[1]; - if (typeof automationService.trigger === "function") { - const result = await automationService.trigger(triggerName, body, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (typeof automationService.execute === "function") { - const result = await automationService.execute(triggerName, body); - return { handled: true, response: this.success(result) }; - } - } - if (parts.length === 0 && m === "GET") { - if (typeof automationService.listFlows === "function") { - const names = await automationService.listFlows(); - return { handled: true, response: this.success({ flows: names, total: names.length, hasMore: false }) }; - } - } - if (parts.length === 0 && m === "POST") { - if (typeof automationService.registerFlow === "function") { - automationService.registerFlow(body?.name, body); - return { handled: true, response: this.success(body) }; - } - } - if (parts.length >= 1) { - const name = parts[0]; - if (parts[1] === "trigger" && m === "POST") { - if (typeof automationService.execute === "function") { - const result = await automationService.execute(name, body); - return { handled: true, response: this.success(result) }; - } - } - if (parts[1] === "toggle" && m === "POST") { - if (typeof automationService.toggleFlow === "function") { - await automationService.toggleFlow(name, body?.enabled ?? true); - return { handled: true, response: this.success({ name, enabled: body?.enabled ?? true }) }; - } - } - if (parts[1] === "runs" && parts[2] && m === "GET") { - if (typeof automationService.getRun === "function") { - const run = await automationService.getRun(parts[2]); - if (!run) return { handled: true, response: this.error("Execution not found", 404) }; - return { handled: true, response: this.success(run) }; - } - } - if (parts[1] === "runs" && !parts[2] && m === "GET") { - if (typeof automationService.listRuns === "function") { - const options = query ? { limit: query.limit ? Number(query.limit) : void 0, cursor: query.cursor } : void 0; - const runs = await automationService.listRuns(name, options); - return { handled: true, response: this.success({ runs, hasMore: false }) }; - } - } - if (parts.length === 1 && m === "GET") { - if (typeof automationService.getFlow === "function") { - const flow = await automationService.getFlow(name); - if (!flow) return { handled: true, response: this.error("Flow not found", 404) }; - return { handled: true, response: this.success(flow) }; - } - } - if (parts.length === 1 && m === "PUT") { - if (typeof automationService.registerFlow === "function") { - automationService.registerFlow(name, body?.definition ?? body); - return { handled: true, response: this.success(body?.definition ?? body) }; - } - } - if (parts.length === 1 && m === "DELETE") { - if (typeof automationService.unregisterFlow === "function") { - automationService.unregisterFlow(name); - return { handled: true, response: this.success({ name, deleted: true }) }; - } - } - } - return { handled: false }; - } - getServicesMap() { - if (this.kernel.services instanceof Map) { - return Object.fromEntries(this.kernel.services); - } - return this.kernel.services || {}; - } - async getService(name) { - return this.resolveService(name); - } - /** - * Resolve any service by name, supporting async factories. - * Fallback chain: getServiceAsync → getService (sync) → context.getService → services map. - * Only returns when a non-null service is found; otherwise falls through to the next step. - */ - async resolveService(name) { - if (typeof this.kernel.getServiceAsync === "function") { - try { - const svc = await this.kernel.getServiceAsync(name); - if (svc != null) return svc; - } catch { - } - } - if (typeof this.kernel.getService === "function") { - try { - const svc = await this.kernel.getService(name); - if (svc != null) return svc; - } catch { - } - } - if (this.kernel?.context?.getService) { - try { - const svc = await this.kernel.context.getService(name); - if (svc != null) return svc; - } catch { - } - } - const services = this.getServicesMap(); - return services[name]; - } - /** - * Get the ObjectQL service which provides access to SchemaRegistry. - * Tries multiple access patterns since kernel structure varies. - */ - async getObjectQLService() { - try { - const svc = await this.resolveService("objectql"); - if (svc?.registry) return svc; - } catch { - } - return null; - } - capitalize(s) { - return s.charAt(0).toUpperCase() + s.slice(1); - } - /** - * Handle AI service routes (/ai/chat, /ai/models, /ai/conversations, etc.) - * Resolves the AI service and its built-in route handlers, then dispatches. - */ - async handleAI(subPath, method, body, query, _context2) { - let aiService; - try { - aiService = await this.resolveService("ai"); - } catch { - } - if (!aiService) { - return { - handled: true, - response: { - status: 404, - body: { success: false, error: { message: "AI service is not configured", code: 404 } } - } - }; - } - const fullPath = `/api/v1${subPath}`; - const matchRoute = (pattern, path3) => { - const patternParts = pattern.split("/"); - const pathParts = path3.split("/"); - if (patternParts.length !== pathParts.length) return null; - const params = {}; - for (let i = 0; i < patternParts.length; i++) { - if (patternParts[i].startsWith(":")) { - params[patternParts[i].substring(1)] = pathParts[i]; - } else if (patternParts[i] !== pathParts[i]) { - return null; - } - } - return params; - }; - const routes = this.kernel.__aiRoutes; - if (!routes) { - return { - handled: true, - response: { - status: 503, - body: { success: false, error: { message: "AI service routes not yet initialized", code: 503 } } - } - }; - } - for (const route of routes) { - if (route.method !== method) continue; - const params = matchRoute(route.path, fullPath); - if (params === null) continue; - const result = await route.handler({ body, params, query }); - if (result.stream && result.events) { - return { - handled: true, - result: { - type: "stream", - contentType: result.vercelDataStream ? "text/plain; charset=utf-8" : "text/event-stream", - events: result.events, - vercelDataStream: result.vercelDataStream, - headers: { - "Content-Type": result.vercelDataStream ? "text/plain; charset=utf-8" : "text/event-stream", - "Cache-Control": "no-cache", - "Connection": "keep-alive" - } - } - }; - } - return { - handled: true, - response: { - status: result.status, - body: result.body - } - }; - } - return { - handled: true, - response: this.routeNotFound(subPath) - }; - } - /** - * Main Dispatcher Entry Point - * Routes the request to the appropriate handler based on path and precedence - */ - async dispatch(method, path3, body, query, context, prefix) { - const cleanPath = path3.replace(/\/$/, ""); - if ((cleanPath === "/discovery" || cleanPath === "") && method === "GET") { - const info2 = await this.getDiscoveryInfo(prefix ?? ""); - return { - handled: true, - response: this.success(info2) - }; - } - if (cleanPath === "/health" && method === "GET") { - return { - handled: true, - response: this.success({ - status: "ok", - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - version: "1.0.0", - uptime: typeof process !== "undefined" ? process.uptime() : void 0 - }) - }; - } - if (cleanPath.startsWith("/auth")) { - return this.handleAuth(cleanPath.substring(5), method, body, context); - } - if (cleanPath.startsWith("/meta")) { - return this.handleMetadata(cleanPath.substring(5), context, method, body, query); - } - if (cleanPath.startsWith("/data")) { - return this.handleData(cleanPath.substring(5), method, body, query, context); - } - if (cleanPath.startsWith("/graphql")) { - if (method === "POST") return this.handleGraphQL(body, context); - } - if (cleanPath.startsWith("/storage")) { - return this.handleStorage(cleanPath.substring(8), method, body, context); - } - if (cleanPath.startsWith("/ui")) { - return this.handleUi(cleanPath.substring(3), query, context); - } - if (cleanPath.startsWith("/automation")) { - return this.handleAutomation(cleanPath.substring(11), method, body, context, query); - } - if (cleanPath.startsWith("/analytics")) { - return this.handleAnalytics(cleanPath.substring(10), method, body, context); - } - if (cleanPath.startsWith("/packages")) { - return this.handlePackages(cleanPath.substring(9), method, body, query, context); - } - if (cleanPath.startsWith("/i18n")) { - return this.handleI18n(cleanPath.substring(5), method, query, context); - } - if (cleanPath.startsWith("/ai")) { - return this.handleAI(cleanPath, method, body, query, context); - } - if (cleanPath === "/openapi.json" && method === "GET") { - const broker = this.ensureBroker(); - try { - const result2 = await broker.call("metadata.generateOpenApi", {}, { request: context.request }); - return { handled: true, response: this.success(result2) }; - } catch (e) { - } - } - const result = await this.handleApiEndpoint(cleanPath, method, body, query, context); - if (result.handled) return result; - return { - handled: true, - response: this.routeNotFound(cleanPath) - }; - } - /** - * Handles Custom API Endpoints defined in metadata - */ - async handleApiEndpoint(path3, method, body, query, context) { - const broker = this.ensureBroker(); - try { - const endpoint = await broker.call("metadata.matchEndpoint", { path: path3, method }); - if (endpoint) { - if (endpoint.type === "flow") { - const result = await broker.call("automation.runFlow", { - flowId: endpoint.target, - inputs: { ...query, ...body, _request: context.request } - }); - return { handled: true, response: this.success(result) }; - } - if (endpoint.type === "script") { - const result = await broker.call("automation.runScript", { - scriptName: endpoint.target, - context: { ...query, ...body, request: context.request } - }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (endpoint.type === "object_operation") { - if (endpoint.objectParams) { - const { object: object2, operation } = endpoint.objectParams; - if (operation === "find") { - const result = await broker.call("data.query", { object: object2, query }, { request: context.request }); - return { handled: true, response: this.success(result.records, { total: result.total }) }; - } - if (operation === "get" && query.id) { - const result = await broker.call("data.get", { object: object2, id: query.id }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - if (operation === "create") { - const result = await broker.call("data.create", { object: object2, data: body }, { request: context.request }); - return { handled: true, response: this.success(result) }; - } - } - } - if (endpoint.type === "proxy") { - return { - handled: true, - response: { - status: 200, - body: { proxy: true, target: endpoint.target, note: "Proxy execution requires http-client service" } - } - }; - } - } - } catch (e) { - } - return { handled: false }; - } -}; - -// ../../packages/objectql/dist/index.mjs -init_data(); - -// ../../packages/spec/dist/kernel/index.mjs -init_zod(); -var CLICommandContributionSchema = external_exports.object({ - /** - * CLI command name. Must be a valid identifier: lowercase alphanumeric with hyphens. - * This becomes a top-level subcommand of the `os` CLI. - * - * @example "marketplace" - * @example "deploy" - * @example "cloud-sync" - */ - name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), - /** Brief description shown in `os --help` output. */ - description: external_exports.string().optional().describe("Command description for help text"), - /** - * Module path that exports the oclif Command class(es). - * Relative to the plugin package root. With oclif, this is typically - * auto-discovered from the `commands` directory, but can be specified - * for documentation or manifest purposes. - * - * @example "./dist/commands/marketplace.js" - * @example "./dist/commands" - */ - module: external_exports.string().optional().describe("Module path exporting oclif Command classes") -}); -var OclifPluginConfigSchema = external_exports.object({ - /** Command discovery configuration */ - commands: external_exports.object({ - /** Discovery strategy — typically "pattern" for file-based discovery */ - strategy: external_exports.enum(["pattern", "explicit", "single"]).optional().describe("Command discovery strategy"), - /** Directory path containing compiled command files */ - target: external_exports.string().optional().describe("Target directory for command files"), - /** Glob pattern for matching command files */ - glob: external_exports.string().optional().describe("Glob pattern for command file matching") - }).optional().describe("Command discovery configuration"), - /** Topic separator character (default: space) */ - topicSeparator: external_exports.string().optional().describe("Character separating topic and command names") -}).describe("oclif plugin configuration section"); -var MetadataCategoryEnum2 = external_exports.enum([ - "objects", - "views", - "pages", - "flows", - "dashboards", - "permissions", - "agents", - "reports", - "actions", - "translations", - "themes", - "datasets", - "apis", - "triggers", - "workflows" -]).describe("Metadata category within the artifact"); -var ArtifactFileEntrySchema2 = external_exports.object({ - /** Relative path within the artifact (e.g. "metadata/objects/account.object.json") */ - path: external_exports.string().describe("Relative file path within the artifact"), - /** File size in bytes */ - size: external_exports.number().int().nonnegative().describe("File size in bytes"), - /** Metadata category (if under metadata/) */ - category: MetadataCategoryEnum2.optional().describe("Metadata category this file belongs to") -}).describe("A single file entry within the artifact"); -var ArtifactChecksumSchema2 = external_exports.object({ - /** Hash algorithm used (default: SHA256) */ - algorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm used for checksums"), - /** Map of relative file paths to their hash values */ - files: external_exports.record(external_exports.string(), external_exports.string().regex(/^[a-f0-9]+$/)).describe("File path to hash value mapping") -}).describe("Checksum manifest for artifact integrity verification"); -var ArtifactSignatureSchema2 = external_exports.object({ - /** Signature algorithm */ - algorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).default("RSA-SHA256").describe("Signing algorithm used"), - /** Public key reference (URL or fingerprint) for verification */ - publicKeyRef: external_exports.string().describe("Public key reference (URL or fingerprint) for signature verification"), - /** Base64-encoded signature value */ - signature: external_exports.string().describe("Base64-encoded digital signature"), - /** Timestamp of when the artifact was signed */ - signedAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp of when the artifact was signed"), - /** Signer identity (publisher ID or email) */ - signedBy: external_exports.string().optional().describe("Identity of the signer (publisher ID or email)") -}).describe("Digital signature for artifact authenticity verification"); -var PackageArtifactSchema2 = external_exports.object({ - /** Artifact format version (for forward compatibility) */ - formatVersion: external_exports.string().regex(/^\d+\.\d+$/).default("1.0").describe('Artifact format version (e.g. "1.0")'), - /** Package ID from the manifest */ - packageId: external_exports.string().describe("Package identifier from manifest"), - /** Package version from the manifest */ - version: external_exports.string().describe("Package version from manifest"), - /** Artifact format */ - format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format of the artifact"), - /** Total artifact size in bytes */ - size: external_exports.number().int().positive().optional().describe("Total artifact file size in bytes"), - /** Build timestamp */ - builtAt: external_exports.string().datetime().describe("ISO 8601 timestamp of when the artifact was built"), - /** Build tool and version that produced this artifact */ - builtWith: external_exports.string().optional().describe('Build tool identifier (e.g. "os-cli@3.2.0")'), - /** File listing within the artifact */ - files: external_exports.array(ArtifactFileEntrySchema2).optional().describe("List of files contained in the artifact"), - /** Metadata categories present in the artifact */ - metadataCategories: external_exports.array(MetadataCategoryEnum2).optional().describe("Metadata categories included in this artifact"), - /** Integrity checksums for all files */ - checksums: ArtifactChecksumSchema2.optional().describe("SHA256 checksums for artifact integrity verification"), - /** Digital signature for authenticity */ - signature: ArtifactSignatureSchema2.optional().describe("Digital signature for artifact authenticity verification") -}).describe("Package artifact structure and metadata"); -var PluginBuildOptionsSchema = external_exports.object({ - /** Project root directory (defaults to cwd) */ - directory: external_exports.string().optional().describe("Project root directory (defaults to current working directory)"), - /** Output directory for the built artifact */ - outDir: external_exports.string().optional().describe("Output directory for the built artifact (defaults to ./dist)"), - /** Archive format */ - format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format for the artifact"), - /** Whether to sign the artifact */ - sign: external_exports.boolean().default(false).describe("Whether to digitally sign the artifact"), - /** Path to the private key for signing */ - privateKeyPath: external_exports.string().optional().describe("Path to RSA/ECDSA private key file for signing"), - /** Signing algorithm */ - signAlgorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).optional().describe("Signing algorithm to use"), - /** Checksum algorithm */ - checksumAlgorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm for file checksums"), - /** Whether to include seed data */ - includeData: external_exports.boolean().default(true).describe("Whether to include seed data in the artifact"), - /** Whether to include locale/translation files */ - includeLocales: external_exports.boolean().default(true).describe("Whether to include locale/translation files") -}).describe("Options for the os plugin build command"); -var PluginBuildResultSchema = external_exports.object({ - /** Whether the build succeeded */ - success: external_exports.boolean().describe("Whether the build succeeded"), - /** Path to the generated artifact file */ - artifactPath: external_exports.string().optional().describe("Absolute path to the generated artifact file"), - /** Artifact metadata (validated against PackageArtifactSchema) */ - artifact: PackageArtifactSchema2.optional().describe("Artifact metadata"), - /** Total file count in the artifact */ - fileCount: external_exports.number().int().min(0).optional().describe("Total number of files in the artifact"), - /** Total artifact size in bytes */ - size: external_exports.number().int().min(0).optional().describe("Total artifact size in bytes"), - /** Build duration in milliseconds */ - durationMs: external_exports.number().optional().describe("Build duration in milliseconds"), - /** Error message if build failed */ - errorMessage: external_exports.string().optional().describe("Error message if build failed"), - /** Warnings emitted during build */ - warnings: external_exports.array(external_exports.string()).optional().describe("Warnings emitted during build") -}).describe("Result of the os plugin build command"); -var ValidationSeverityEnum = external_exports.enum([ - "error", - // Must fix — artifact is invalid - "warning", - // Should fix — may cause issues - "info" - // Informational — suggestion -]).describe("Validation issue severity"); -var ValidationFindingSchema = external_exports.object({ - /** Finding severity */ - severity: ValidationSeverityEnum.describe("Issue severity level"), - /** Rule or check that produced this finding */ - rule: external_exports.string().describe("Validation rule identifier"), - /** Human-readable message */ - message: external_exports.string().describe("Human-readable finding description"), - /** File path within the artifact (if applicable) */ - path: external_exports.string().optional().describe("Relative file path within the artifact") -}).describe("A single validation finding"); -var PluginValidateOptionsSchema = external_exports.object({ - /** Path to the .tgz artifact file to validate */ - artifactPath: external_exports.string().describe("Path to the artifact file to validate"), - /** Whether to verify the digital signature */ - verifySignature: external_exports.boolean().default(true).describe("Whether to verify the digital signature"), - /** Path to the public key for signature verification */ - publicKeyPath: external_exports.string().optional().describe("Path to the public key for signature verification"), - /** Whether to verify SHA256 checksums of all files */ - verifyChecksums: external_exports.boolean().default(true).describe("Whether to verify checksums of all files"), - /** Whether to validate metadata schema compliance */ - validateMetadata: external_exports.boolean().default(true).describe("Whether to validate metadata against schemas"), - /** Target platform version for compatibility check */ - platformVersion: external_exports.string().optional().describe("Platform version for compatibility verification") -}).describe("Options for the os plugin validate command"); -var PluginValidateResultSchema = external_exports.object({ - /** Whether the artifact is valid (no error-level findings) */ - valid: external_exports.boolean().describe("Whether the artifact passed validation"), - /** Artifact metadata extracted from the archive */ - artifact: PackageArtifactSchema2.optional().describe("Extracted artifact metadata"), - /** Checksum verification result */ - checksumVerification: external_exports.object({ - /** Whether all checksums match */ - passed: external_exports.boolean().describe("Whether all checksums match"), - /** Checksum details */ - checksums: ArtifactChecksumSchema2.optional().describe("Verified checksums"), - /** Files with mismatched checksums */ - mismatches: external_exports.array(external_exports.string()).optional().describe("Files with checksum mismatches") - }).optional().describe("Checksum verification result"), - /** Signature verification result */ - signatureVerification: external_exports.object({ - /** Whether the signature is valid */ - passed: external_exports.boolean().describe("Whether the signature is valid"), - /** Signature details */ - signature: ArtifactSignatureSchema2.optional().describe("Signature details"), - /** Reason for failure */ - failureReason: external_exports.string().optional().describe("Signature verification failure reason") - }).optional().describe("Signature verification result"), - /** Platform compatibility result */ - platformCompatibility: external_exports.object({ - /** Whether the artifact is compatible with the target platform */ - compatible: external_exports.boolean().describe("Whether artifact is compatible"), - /** Required platform version range */ - requiredRange: external_exports.string().optional().describe("Required platform version range"), - /** Target platform version checked against */ - targetVersion: external_exports.string().optional().describe("Target platform version") - }).optional().describe("Platform compatibility check result"), - /** All validation findings */ - findings: external_exports.array(ValidationFindingSchema).describe("All validation findings"), - /** Counts by severity */ - summary: external_exports.object({ - errors: external_exports.number().int().min(0).describe("Error count"), - warnings: external_exports.number().int().min(0).describe("Warning count"), - infos: external_exports.number().int().min(0).describe("Info count") - }).optional().describe("Finding counts by severity") -}).describe("Result of the os plugin validate command"); -var PluginPublishOptionsSchema = external_exports.object({ - /** Path to the .tgz artifact file to publish */ - artifactPath: external_exports.string().describe("Path to the artifact file to publish"), - /** Marketplace API base URL */ - registryUrl: external_exports.string().url().optional().describe("Marketplace API base URL"), - /** Authentication token for the marketplace API */ - token: external_exports.string().optional().describe("Authentication token for marketplace API"), - /** Release notes for this version */ - releaseNotes: external_exports.string().optional().describe("Release notes for this version"), - /** Whether this is a pre-release */ - preRelease: external_exports.boolean().default(false).describe("Whether this is a pre-release version"), - /** Whether to skip validation before publishing */ - skipValidation: external_exports.boolean().default(false).describe("Whether to skip local validation before publish"), - /** Access level for the published package */ - access: external_exports.enum(["public", "restricted"]).default("public").describe("Package access level on the marketplace"), - /** Tags for categorization */ - tags: external_exports.array(external_exports.string()).optional().describe("Tags for marketplace categorization") -}).describe("Options for the os plugin publish command"); -var PluginPublishResultSchema = external_exports.object({ - /** Whether the publish succeeded */ - success: external_exports.boolean().describe("Whether the publish succeeded"), - /** Package ID that was published */ - packageId: external_exports.string().optional().describe("Published package identifier"), - /** Version that was published */ - version: external_exports.string().optional().describe("Published version string"), - /** Artifact reference in the marketplace */ - artifactUrl: external_exports.string().url().optional().describe("URL of the published artifact in the marketplace"), - /** SHA256 checksum of the uploaded artifact */ - sha256: external_exports.string().optional().describe("SHA256 checksum of the uploaded artifact"), - /** Submission ID for tracking the review process */ - submissionId: external_exports.string().optional().describe("Marketplace submission ID for review tracking"), - /** Error message if publish failed */ - errorMessage: external_exports.string().optional().describe("Error message if publish failed"), - /** Human-readable status message */ - message: external_exports.string().optional().describe("Human-readable status message") -}).describe("Result of the os plugin publish command"); -var TenantIsolationLevel2 = external_exports.enum([ - "shared_schema", - // Shared DB, shared schema, row-level isolation (most economical) - "isolated_schema", - // Shared DB, separate schema per tenant (balanced) - "isolated_db" - // Separate database per tenant (maximum isolation) -]); -var DatabaseProviderSchema2 = external_exports.enum([ - "turso", - // Turso/libSQL (DB-per-Tenant, edge-native) - "postgres", - // PostgreSQL (traditional, self-hosted or managed) - "memory" - // In-memory (testing/development only) -]).describe("Database provider for tenant data"); -var TenantConnectionConfigSchema2 = external_exports.object({ - /** Database connection URL */ - url: external_exports.string().min(1).describe("Database connection URL"), - /** Authentication token (JWT for Turso, password for Postgres) */ - authToken: external_exports.string().optional().describe("Database auth token (encrypted at rest)"), - /** Turso database group name */ - group: external_exports.string().optional().describe("Turso database group name") -}).describe("Tenant database connection configuration"); -var TenantQuotaSchema2 = external_exports.object({ - /** - * Maximum number of users allowed for this tenant - */ - maxUsers: external_exports.number().int().positive().optional().describe("Maximum number of users"), - /** - * Maximum storage space in bytes - */ - maxStorage: external_exports.number().int().positive().optional().describe("Maximum storage in bytes"), - /** - * API rate limit (requests per minute) - */ - apiRateLimit: external_exports.number().int().positive().optional().describe("API requests per minute"), - /** - * Maximum number of custom objects the tenant can create - */ - maxObjects: external_exports.number().int().positive().optional().describe("Maximum number of custom objects"), - /** - * Maximum records per object/table - */ - maxRecordsPerObject: external_exports.number().int().positive().optional().describe("Maximum records per object"), - /** - * Maximum deployments allowed per day - */ - maxDeploymentsPerDay: external_exports.number().int().positive().optional().describe("Maximum deployments per day"), - /** - * Maximum storage in bytes - */ - maxStorageBytes: external_exports.number().int().positive().optional().describe("Maximum storage in bytes") -}); -external_exports.object({ - /** Current number of custom objects */ - currentObjectCount: external_exports.number().int().min(0).default(0).describe("Current number of custom objects"), - /** Current total record count across all objects */ - currentRecordCount: external_exports.number().int().min(0).default(0).describe("Total records across all objects"), - /** Current storage usage in bytes */ - currentStorageBytes: external_exports.number().int().min(0).default(0).describe("Current storage usage in bytes"), - /** Deployments executed today */ - deploymentsToday: external_exports.number().int().min(0).default(0).describe("Deployments executed today"), - /** Current number of active users */ - currentUsers: external_exports.number().int().min(0).default(0).describe("Current number of active users"), - /** API requests in the current minute */ - apiRequestsThisMinute: external_exports.number().int().min(0).default(0).describe("API requests in the current minute"), - /** Last updated timestamp (ISO 8601) */ - lastUpdatedAt: external_exports.string().datetime().optional().describe("Last usage update time") -}).describe("Current tenant resource usage"); -external_exports.object({ - /** Whether the operation is allowed */ - allowed: external_exports.boolean().describe("Whether the operation is within quota"), - /** Quota that would be exceeded (if not allowed) */ - exceededQuota: external_exports.string().optional().describe("Name of the exceeded quota"), - /** Current usage value */ - currentUsage: external_exports.number().optional().describe("Current usage value"), - /** Quota limit value */ - limit: external_exports.number().optional().describe("Quota limit"), - /** Human-readable message */ - message: external_exports.string().optional().describe("Human-readable quota message") -}).describe("Quota enforcement check result"); -external_exports.object({ - /** - * Unique tenant identifier - */ - id: external_exports.string().describe("Unique tenant identifier"), - /** - * Tenant display name - */ - name: external_exports.string().describe("Tenant display name"), - /** - * Data isolation level - */ - isolationLevel: TenantIsolationLevel2, - /** - * Database provider for this tenant - */ - databaseProvider: DatabaseProviderSchema2.optional().describe("Database provider"), - /** - * Database connection configuration (encrypted at rest) - */ - connectionConfig: TenantConnectionConfigSchema2.optional().describe("Database connection config"), - /** - * Current provisioning status - */ - provisioningStatus: external_exports.enum([ - "provisioning", - "active", - "suspended", - "failed", - "destroying" - ]).optional().describe("Current provisioning lifecycle status"), - /** - * Tenant subscription plan - */ - plan: external_exports.enum(["free", "pro", "enterprise"]).optional().describe("Subscription plan"), - /** - * Custom configuration values - */ - customizations: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom configuration values"), - /** - * Resource quotas - */ - quotas: TenantQuotaSchema2.optional() -}); -var RowLevelIsolationStrategySchema2 = external_exports.object({ - strategy: external_exports.literal("shared_schema").describe("Row-level isolation strategy"), - /** - * Database configuration for row-level isolation - */ - database: external_exports.object({ - /** - * Whether to enable Row-Level Security (RLS) - */ - enableRLS: external_exports.boolean().default(true).describe("Enable PostgreSQL Row-Level Security"), - /** - * Tenant context setting method - */ - contextMethod: external_exports.enum([ - "session_variable", - // SET app.current_tenant = 'tenant_123' - "search_path", - // SET search_path = tenant_123, public - "application_name" - // SET application_name = 'tenant_123' - ]).default("session_variable").describe("How to set tenant context"), - /** - * Session variable name for tenant context - */ - contextVariable: external_exports.string().default("app.current_tenant").describe("Session variable name"), - /** - * Whether to validate tenant_id at application level - */ - applicationValidation: external_exports.boolean().default(true).describe("Application-level tenant validation") - }).optional().describe("Database configuration"), - /** - * Performance optimization settings - */ - performance: external_exports.object({ - /** - * Whether to use partial indexes for tenant_id - */ - usePartialIndexes: external_exports.boolean().default(true).describe("Use partial indexes per tenant"), - /** - * Whether to use table partitioning - */ - usePartitioning: external_exports.boolean().default(false).describe("Use table partitioning by tenant_id"), - /** - * Connection pool size per tenant - */ - poolSizePerTenant: external_exports.number().int().positive().optional().describe("Connection pool size per tenant") - }).optional().describe("Performance settings") -}); -var SchemaLevelIsolationStrategySchema2 = external_exports.object({ - strategy: external_exports.literal("isolated_schema").describe("Schema-level isolation strategy"), - /** - * Schema configuration - */ - schema: external_exports.object({ - /** - * Schema naming pattern - * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) - * The tenant_id will be sanitized before substitution to prevent SQL injection - */ - namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Schema naming pattern"), - /** - * Whether to include public schema in search_path - */ - includePublicSchema: external_exports.boolean().default(true).describe("Include public schema"), - /** - * Default schema for shared resources - */ - sharedSchema: external_exports.string().default("public").describe("Schema for shared resources"), - /** - * Whether to automatically create schema on tenant creation - */ - autoCreateSchema: external_exports.boolean().default(true).describe("Auto-create schema") - }).optional().describe("Schema configuration"), - /** - * Migration configuration - */ - migrations: external_exports.object({ - /** - * Migration strategy - */ - strategy: external_exports.enum([ - "parallel", - // Run migrations on all schemas in parallel - "sequential", - // Run migrations one schema at a time - "on_demand" - // Run migrations when tenant accesses system - ]).default("parallel").describe("Migration strategy"), - /** - * Maximum concurrent migrations - */ - maxConcurrent: external_exports.number().int().positive().default(10).describe("Max concurrent migrations"), - /** - * Whether to rollback on first failure - */ - rollbackOnError: external_exports.boolean().default(true).describe("Rollback on error") - }).optional().describe("Migration configuration"), - /** - * Performance optimization settings - */ - performance: external_exports.object({ - /** - * Whether to use connection pooling per schema - */ - poolPerSchema: external_exports.boolean().default(false).describe("Separate pool per schema"), - /** - * Schema cache TTL in seconds - */ - schemaCacheTTL: external_exports.number().int().positive().default(3600).describe("Schema cache TTL") - }).optional().describe("Performance settings") -}); -var DatabaseLevelIsolationStrategySchema2 = external_exports.object({ - strategy: external_exports.literal("isolated_db").describe("Database-level isolation strategy"), - /** - * Database configuration - */ - database: external_exports.object({ - /** - * Database naming pattern - * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) - * The tenant_id will be sanitized before substitution to prevent SQL injection - */ - namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Database naming pattern"), - /** - * Database server/cluster assignment strategy - */ - serverStrategy: external_exports.enum([ - "shared", - // All tenant databases on same server - "sharded", - // Tenant databases distributed across servers - "dedicated" - // Each tenant gets dedicated server (enterprise) - ]).default("shared").describe("Server assignment strategy"), - /** - * Whether to use separate credentials per tenant - */ - separateCredentials: external_exports.boolean().default(true).describe("Separate credentials per tenant"), - /** - * Whether to automatically create database on tenant creation - */ - autoCreateDatabase: external_exports.boolean().default(true).describe("Auto-create database") - }).optional().describe("Database configuration"), - /** - * Connection pooling configuration - */ - connectionPool: external_exports.object({ - /** - * Pool size per tenant database - */ - poolSize: external_exports.number().int().positive().default(10).describe("Connection pool size"), - /** - * Maximum number of tenant pools to keep active - */ - maxActivePools: external_exports.number().int().positive().default(100).describe("Max active pools"), - /** - * Idle pool timeout in seconds - */ - idleTimeout: external_exports.number().int().positive().default(300).describe("Idle pool timeout"), - /** - * Whether to use connection pooler (PgBouncer, etc.) - */ - usePooler: external_exports.boolean().default(true).describe("Use connection pooler") - }).optional().describe("Connection pool configuration"), - /** - * Backup and restore configuration - */ - backup: external_exports.object({ - /** - * Backup strategy per tenant - */ - strategy: external_exports.enum([ - "individual", - // Separate backup per tenant - "consolidated", - // Combined backup with all tenants - "on_demand" - // Backup only when requested - ]).default("individual").describe("Backup strategy"), - /** - * Backup frequency in hours - */ - frequencyHours: external_exports.number().int().positive().default(24).describe("Backup frequency"), - /** - * Retention period in days - */ - retentionDays: external_exports.number().int().positive().default(30).describe("Backup retention days") - }).optional().describe("Backup configuration"), - /** - * Encryption configuration - */ - encryption: external_exports.object({ - /** - * Whether to use per-tenant encryption keys - */ - perTenantKeys: external_exports.boolean().default(false).describe("Per-tenant encryption keys"), - /** - * Encryption algorithm - */ - algorithm: external_exports.string().default("AES-256-GCM").describe("Encryption algorithm"), - /** - * Key management service - */ - keyManagement: external_exports.enum(["aws_kms", "azure_key_vault", "gcp_kms", "hashicorp_vault", "custom"]).optional().describe("Key management service") - }).optional().describe("Encryption configuration") -}); -external_exports.discriminatedUnion("strategy", [ - RowLevelIsolationStrategySchema2, - SchemaLevelIsolationStrategySchema2, - DatabaseLevelIsolationStrategySchema2 -]); -external_exports.object({ - /** - * Encryption requirements - */ - encryption: external_exports.object({ - /** - * Require encryption at rest - */ - atRest: external_exports.boolean().default(true).describe("Require encryption at rest"), - /** - * Require encryption in transit - */ - inTransit: external_exports.boolean().default(true).describe("Require encryption in transit"), - /** - * Require field-level encryption for sensitive data - */ - fieldLevel: external_exports.boolean().default(false).describe("Require field-level encryption") - }).optional().describe("Encryption requirements"), - /** - * Access control requirements - */ - accessControl: external_exports.object({ - /** - * Require multi-factor authentication - */ - requireMFA: external_exports.boolean().default(false).describe("Require MFA"), - /** - * Require SSO/SAML authentication - */ - requireSSO: external_exports.boolean().default(false).describe("Require SSO"), - /** - * IP whitelist - */ - ipWhitelist: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses"), - /** - * Session timeout in seconds - */ - sessionTimeout: external_exports.number().int().positive().default(3600).describe("Session timeout") - }).optional().describe("Access control requirements"), - /** - * Audit and compliance requirements - */ - compliance: external_exports.object({ - /** - * Compliance standards to enforce - */ - standards: external_exports.array(external_exports.enum([ - "sox", - "hipaa", - "gdpr", - "pci_dss", - "iso_27001", - "fedramp" - ])).optional().describe("Compliance standards"), - /** - * Require audit logging for all operations - */ - requireAuditLog: external_exports.boolean().default(true).describe("Require audit logging"), - /** - * Audit log retention period in days - */ - auditRetentionDays: external_exports.number().int().positive().default(365).describe("Audit retention days"), - /** - * Data residency requirements - */ - dataResidency: external_exports.object({ - /** - * Required geographic region - */ - region: external_exports.string().optional().describe("Required region (e.g., US, EU, APAC)"), - /** - * Prohibited regions - */ - excludeRegions: external_exports.array(external_exports.string()).optional().describe("Prohibited regions") - }).optional().describe("Data residency requirements") - }).optional().describe("Compliance requirements") -}); -var RuntimeMode = external_exports.enum([ - "development", - // Hot-reload, verbose logging - "production", - // Optimized, strict security - "test", - // Mocked interfaces - "provisioning", - // Setup/Migration mode - "preview" - // Demo/preview mode — bypass auth, simulate admin identity -]).describe("Kernel operating mode"); -var PreviewModeConfigSchema = external_exports.object({ - /** - * Automatically log in as a simulated user on startup. - * When enabled, the frontend skips login/registration screens entirely. - */ - autoLogin: external_exports.boolean().default(true).describe("Auto-login as simulated user, skipping login/registration pages"), - /** - * Role of the simulated user. - * Determines the permission level of the auto-created preview session. - */ - simulatedRole: external_exports.enum(["admin", "user", "viewer"]).default("admin").describe("Permission role for the simulated preview user"), - /** - * Display name for the simulated user shown in the UI. - */ - simulatedUserName: external_exports.string().default("Preview User").describe("Display name for the simulated preview user"), - /** - * Whether the preview session is read-only. - * When true, all write operations (create, update, delete) are blocked. - */ - readOnly: external_exports.boolean().default(false).describe("Restrict the preview session to read-only operations"), - /** - * Session duration in seconds. After expiry the preview session ends. - * 0 means no expiration. - */ - expiresInSeconds: external_exports.number().int().min(0).default(0).describe("Preview session duration in seconds (0 = no expiration)"), - /** - * Optional banner message shown in the UI to indicate preview mode. - * Useful for marketplace demos so visitors know they are in a sandbox. - */ - bannerMessage: external_exports.string().optional().describe("Banner message displayed in the UI during preview mode") -}); -var KernelContextSchema = external_exports.object({ - /** - * Instance Identity - */ - instanceId: external_exports.string().uuid().describe("Unique UUID for this running kernel process"), - /** - * Environment Metadata - */ - mode: RuntimeMode.default("production"), - version: external_exports.string().describe("Kernel version"), - appName: external_exports.string().optional().describe("Host application name"), - /** - * Paths - */ - cwd: external_exports.string().describe("Current working directory"), - workspaceRoot: external_exports.string().optional().describe("Workspace root if different from cwd"), - /** - * Telemetry - */ - startTime: external_exports.number().int().describe("Boot timestamp (ms)"), - /** - * Feature Flags (Global) - */ - features: external_exports.record(external_exports.string(), external_exports.boolean()).default({}).describe("Global feature toggles"), - /** - * Preview Mode Configuration. - * Only relevant when `mode` is `'preview'`. Configures auto-login, - * simulated identity, read-only restrictions, and UI banner. - */ - previewMode: PreviewModeConfigSchema.optional().describe('Preview/demo mode configuration (used when mode is "preview")') -}); -var TenantRuntimeContextSchema = KernelContextSchema.extend({ - /** Unique tenant identifier resolved from the current session */ - tenantId: external_exports.string().min(1).describe("Resolved tenant identifier"), - /** Tenant subscription plan */ - tenantPlan: external_exports.enum(["free", "pro", "enterprise"]).describe("Tenant subscription plan"), - /** Tenant deployment region */ - tenantRegion: external_exports.string().optional().describe("Tenant deployment region"), - /** Tenant database connection URL */ - tenantDbUrl: external_exports.string().min(1).describe("Tenant database connection URL"), - /** Optional tenant quotas for the current plan */ - tenantQuotas: TenantQuotaSchema2.optional().describe("Tenant resource quotas") -}).describe("Tenant-aware kernel runtime context"); -var DependencyStatusEnum2 = external_exports.enum([ - "satisfied", - // Already installed and version compatible - "needs_install", - // Not installed, needs to be installed - "needs_upgrade", - // Installed but version incompatible, needs upgrade - "conflict" - // Conflicts with another package's dependency -]).describe("Resolution status for a dependency"); -var ResolvedDependencySchema2 = external_exports.object({ - /** Package identifier of the dependency */ - packageId: external_exports.string().describe("Dependency package identifier"), - /** SemVer range required by the parent package */ - requiredRange: external_exports.string().describe('SemVer range required (e.g. "^2.0.0")'), - /** Actual version resolved (if available) */ - resolvedVersion: external_exports.string().optional().describe("Actual version resolved from registry"), - /** Currently installed version (if any) */ - installedVersion: external_exports.string().optional().describe("Currently installed version"), - /** Resolution status */ - status: DependencyStatusEnum2.describe("Resolution status"), - /** Conflict details (when status is "conflict") */ - conflictReason: external_exports.string().optional().describe("Explanation of the conflict") -}).describe("Resolution result for a single dependency"); -var RequiredActionSchema2 = external_exports.object({ - /** Type of action required */ - type: external_exports.enum(["install", "upgrade", "confirm_conflict"]).describe("Type of action required"), - /** Target package identifier */ - packageId: external_exports.string().describe("Target package identifier"), - /** Human-readable description of the action */ - description: external_exports.string().describe("Human-readable action description") -}).describe("Action required before installation can proceed"); -var DependencyResolutionResultSchema2 = external_exports.object({ - /** All dependencies and their resolution results */ - dependencies: external_exports.array(ResolvedDependencySchema2).describe("Resolution result for each dependency"), - /** Whether installation can proceed without conflicts */ - canProceed: external_exports.boolean().describe("Whether installation can proceed"), - /** Actions that require user confirmation or system execution */ - requiredActions: external_exports.array(RequiredActionSchema2).describe("Actions required before proceeding"), - /** Topologically sorted package IDs for installation order */ - installOrder: external_exports.array(external_exports.string()).describe("Topologically sorted package IDs for installation"), - /** Detected circular dependency chains */ - circularDependencies: external_exports.array(external_exports.array(external_exports.string())).optional().describe('Circular dependency chains detected (e.g. [["A", "B", "A"]])') -}).describe("Complete dependency resolution result"); -var DevServiceOverrideSchema = external_exports.object({ - /** Service identifier (e.g. 'auth', 'eventBus', 'fileStorage') */ - service: external_exports.string().min(1).describe("Target service identifier"), - /** Whether this service is enabled in dev mode */ - enabled: external_exports.boolean().default(true).describe("Enable or disable this service"), - /** - * Implementation strategy for the service in dev mode. - * - mock: Use a mock/stub that records calls (for assertions) - * - memory: Use a real but in-memory implementation (e.g. SQLite, Map) - * - stub: Use a static/no-op implementation - * - passthrough: Use the real production implementation (for integration testing) - */ - strategy: external_exports.enum(["mock", "memory", "stub", "passthrough"]).default("memory").describe("Implementation strategy for development"), - /** Optional per-service configuration (strategy-specific) */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Strategy-specific configuration for this service override") -}); -var DevFixtureConfigSchema = external_exports.object({ - /** Whether to load fixtures on startup */ - enabled: external_exports.boolean().default(true).describe("Load fixture data on startup"), - /** - * Glob patterns pointing to fixture files - * (e.g. `["./fixtures/*.json", "./test/data/*.yml"]`) - */ - paths: external_exports.array(external_exports.string()).optional().describe("Glob patterns for fixture files"), - /** Whether to reset data before loading fixtures */ - resetBeforeLoad: external_exports.boolean().default(true).describe("Clear existing data before loading fixtures"), - /** - * Environment tag filter – only load fixtures tagged for these environments. - * When omitted, all fixtures are loaded. - */ - envFilter: external_exports.array(external_exports.string()).optional().describe("Only load fixtures matching these environment tags") -}); -var DevToolsConfigSchema = external_exports.object({ - /** Enable hot-module replacement / live reload */ - hotReload: external_exports.boolean().default(true).describe("Enable HMR / live-reload"), - /** Enable request inspector UI for debugging HTTP traffic */ - requestInspector: external_exports.boolean().default(false).describe("Enable request inspector"), - /** Enable an in-browser database explorer */ - dbExplorer: external_exports.boolean().default(false).describe("Enable database explorer UI"), - /** Enable verbose logging across all services */ - verboseLogging: external_exports.boolean().default(true).describe("Enable verbose logging"), - /** Enable OpenAPI / Swagger documentation endpoint */ - apiDocs: external_exports.boolean().default(true).describe("Serve OpenAPI docs at /_dev/docs"), - /** Enable a mail catcher for outbound email (like MailHog) */ - mailCatcher: external_exports.boolean().default(false).describe("Capture outbound emails in dev") -}); -var DevPluginPreset = external_exports.enum([ - "minimal", - "standard", - "full" -]).describe("Predefined dev configuration profile"); -var DevPluginConfigSchema = external_exports.object({ - /** - * Configuration preset. - * When provided, services and tools are pre-configured for the selected - * profile. Individual `services` and `tools` settings override the preset. - * @default 'standard' - */ - preset: DevPluginPreset.default("standard").describe("Base configuration preset"), - /** - * Per-service overrides. - * Keys are service names; values configure the dev strategy. - * Only services explicitly listed here override the preset defaults. - */ - services: external_exports.record( - external_exports.string().min(1), - DevServiceOverrideSchema.omit({ service: true }) - ).optional().describe("Per-service dev overrides keyed by service name"), - /** Fixture / seed data configuration */ - fixtures: DevFixtureConfigSchema.optional().describe("Fixture data loading configuration"), - /** Developer tooling configuration */ - tools: DevToolsConfigSchema.optional().describe("Developer tooling settings"), - /** - * Port for the dev-tools UI dashboard. - * Serves a lightweight web dashboard for inspecting services, events, - * and request logs during development. - * @default 4400 - */ - port: external_exports.number().int().min(1).max(65535).default(4400).describe("Port for the dev-tools dashboard"), - /** - * Auto-open the dev-tools dashboard in the default browser on startup. - */ - open: external_exports.boolean().default(false).describe("Auto-open dev dashboard in browser"), - /** - * Seed a default admin user for development. - * When enabled, the dev plugin creates a pre-authenticated admin user - * so that developers can bypass login flows. - */ - seedAdminUser: external_exports.boolean().default(true).describe("Create a default admin user for development"), - /** - * Simulated latency (ms) to add to service calls. - * Helps developers build UIs that handle loading states correctly. - * Set to 0 to disable. - */ - simulatedLatency: external_exports.number().int().min(0).default(0).describe("Artificial latency (ms) added to service calls") -}); -external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' -}).describe("System identifier (lowercase with underscores or dots)"); -var SnakeCaseIdentifierSchema5 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { - message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' -}).describe("Snake case identifier (lowercase with underscores only)"); -var EventNameSchema3 = external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' -}).describe("Event name (lowercase with dot notation for namespacing)"); -var EventPriority = external_exports.enum([ - "critical", - // 0 - Process immediately, block if necessary - "high", - // 1 - Process soon, minimal delay - "normal", - // 2 - Default priority - "low", - // 3 - Process when resources available - "background" - // 4 - Process during idle time -]); -var EventMetadataSchema = external_exports.object({ - source: external_exports.string().describe("Event source (e.g., plugin name, system component)"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when event was created"), - userId: external_exports.string().optional().describe("User who triggered the event"), - tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant systems"), - correlationId: external_exports.string().optional().describe("Correlation ID for event tracing"), - causationId: external_exports.string().optional().describe("ID of the event that caused this event"), - priority: EventPriority.optional().default("normal").describe("Event priority") -}); -var EventTypeDefinitionSchema = external_exports.object({ - name: EventNameSchema3.describe("Event type name (lowercase with dots)"), - version: external_exports.string().default("1.0.0").describe("Event schema version"), - schema: external_exports.unknown().optional().describe("JSON Schema for event payload validation"), - description: external_exports.string().optional().describe("Event type description"), - deprecated: external_exports.boolean().optional().default(false).describe("Whether this event type is deprecated"), - tags: external_exports.array(external_exports.string()).optional().describe("Event type tags") -}); -var EventSchema = external_exports.object({ - /** - * Event identifier (for tracking and deduplication) - */ - id: external_exports.string().optional().describe("Unique event identifier"), - /** - * Event name - */ - name: EventNameSchema3.describe("Event name (lowercase with dots, e.g., user.created, order.paid)"), - /** - * Event payload - */ - payload: external_exports.unknown().describe("Event payload schema"), - /** - * Event metadata - */ - metadata: EventMetadataSchema.describe("Event metadata") -}); -var EventHandlerSchema = external_exports.object({ - /** - * Handler identifier - */ - id: external_exports.string().optional().describe("Unique handler identifier"), - /** - * Event name pattern - */ - eventName: external_exports.string().describe("Name of event to handle (supports wildcards like user.*)"), - /** - * Handler function - */ - handler: external_exports.unknown().describe("Handler function"), - /** - * Execution priority - */ - priority: external_exports.number().int().default(0).describe("Execution priority (lower numbers execute first)"), - /** - * Async execution - */ - async: external_exports.boolean().default(true).describe("Execute in background (true) or block (false)"), - /** - * Retry configuration - */ - retry: external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retry attempts"), - backoffMs: external_exports.number().int().positive().default(1e3).describe("Initial backoff delay"), - backoffMultiplier: external_exports.number().positive().default(2).describe("Backoff multiplier") - }).optional().describe("Retry policy for failed handlers"), - /** - * Timeout - */ - timeoutMs: external_exports.number().int().positive().optional().describe("Handler timeout in milliseconds"), - /** - * Filter function - */ - filter: external_exports.unknown().optional().describe("Optional filter to determine if handler should execute") -}); -var EventRouteSchema = external_exports.object({ - from: external_exports.string().describe("Source event pattern (supports wildcards, e.g., user.* or *.created)"), - to: external_exports.array(external_exports.string()).describe("Target event names to route to"), - transform: external_exports.unknown().optional().describe("Optional function to transform payload") -}); -var EventPersistenceSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable event persistence"), - retention: external_exports.number().int().positive().describe("Days to retain persisted events"), - filter: external_exports.unknown().optional().describe("Optional filter function to select which events to persist"), - storage: external_exports.enum(["database", "file", "s3", "custom"]).default("database").describe("Storage backend for persisted events") -}); -var EventQueueConfigSchema = external_exports.object({ - /** - * Queue name - */ - name: external_exports.string().default("events").describe("Event queue name"), - /** - * Concurrency - */ - concurrency: external_exports.number().int().min(1).default(10).describe("Max concurrent event handlers"), - /** - * Retry policy - */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Max retries for failed events"), - backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy"), - initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay"), - maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Maximum retry delay") - }).optional().describe("Default retry policy for events"), - /** - * Dead letter queue - */ - deadLetterQueue: external_exports.string().optional().describe("Dead letter queue name for failed events"), - /** - * Enable priority processing - */ - priorityEnabled: external_exports.boolean().default(true).describe("Process events based on priority") -}); -var EventReplayConfigSchema = external_exports.object({ - /** - * Start timestamp - */ - fromTimestamp: external_exports.string().datetime().describe("Start timestamp for replay (ISO 8601)"), - /** - * End timestamp - */ - toTimestamp: external_exports.string().datetime().optional().describe("End timestamp for replay (ISO 8601)"), - /** - * Event types to replay - */ - eventTypes: external_exports.array(external_exports.string()).optional().describe("Event types to replay (empty = all)"), - /** - * Event filters - */ - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional filters for event selection"), - /** - * Replay speed multiplier - */ - speed: external_exports.number().positive().default(1).describe("Replay speed multiplier (1 = real-time)"), - /** - * Target handlers - */ - targetHandlers: external_exports.array(external_exports.string()).optional().describe("Handler IDs to execute (empty = all)") -}); -var EventSourcingConfigSchema = external_exports.object({ - /** - * Enable event sourcing - */ - enabled: external_exports.boolean().default(false).describe("Enable event sourcing"), - /** - * Snapshot interval - */ - snapshotInterval: external_exports.number().int().positive().default(100).describe("Create snapshot every N events"), - /** - * Snapshot retention - */ - snapshotRetention: external_exports.number().int().positive().default(10).describe("Number of snapshots to retain"), - /** - * Event retention - */ - retention: external_exports.number().int().positive().default(365).describe("Days to retain events"), - /** - * Aggregate types - */ - aggregateTypes: external_exports.array(external_exports.string()).optional().describe("Aggregate types to enable event sourcing for"), - /** - * Storage configuration - */ - storage: external_exports.object({ - type: external_exports.enum(["database", "file", "s3", "eventstore"]).default("database").describe("Storage backend"), - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage-specific options") - }).optional().describe("Event store configuration") -}); -var DeadLetterQueueEntrySchema = external_exports.object({ - /** - * Entry identifier - */ - id: external_exports.string().describe("Unique entry identifier"), - /** - * Original event - */ - event: EventSchema.describe("Original event"), - /** - * Failure reason - */ - error: external_exports.object({ - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Error stack trace"), - code: external_exports.string().optional().describe("Error code") - }).describe("Failure details"), - /** - * Retry count - */ - retries: external_exports.number().int().min(0).describe("Number of retry attempts"), - /** - * Timestamps - */ - firstFailedAt: external_exports.string().datetime().describe("When event first failed"), - lastFailedAt: external_exports.string().datetime().describe("When event last failed"), - /** - * Handler that failed - */ - failedHandler: external_exports.string().optional().describe("Handler ID that failed") -}); -var EventLogEntrySchema = external_exports.object({ - /** - * Log entry ID - */ - id: external_exports.string().describe("Unique log entry identifier"), - /** - * Event - */ - event: EventSchema.describe("The event"), - /** - * Status - */ - status: external_exports.enum(["pending", "processing", "completed", "failed"]).describe("Processing status"), - /** - * Handlers executed - */ - handlersExecuted: external_exports.array(external_exports.object({ - handlerId: external_exports.string().describe("Handler identifier"), - status: external_exports.enum(["success", "failed", "timeout"]).describe("Handler execution status"), - durationMs: external_exports.number().int().optional().describe("Execution duration"), - error: external_exports.string().optional().describe("Error message if failed") - })).optional().describe("Handlers that processed this event"), - /** - * Timestamps - */ - receivedAt: external_exports.string().datetime().describe("When event was received"), - processedAt: external_exports.string().datetime().optional().describe("When event was processed"), - /** - * Total duration - */ - totalDurationMs: external_exports.number().int().optional().describe("Total processing time") -}); -var EventWebhookConfigSchema = external_exports.object({ - /** - * Webhook identifier - */ - id: external_exports.string().optional().describe("Unique webhook identifier"), - /** - * Event pattern to match - */ - eventPattern: external_exports.string().describe("Event name pattern (supports wildcards)"), - /** - * Target URL - */ - url: external_exports.string().url().describe("Webhook endpoint URL"), - /** - * HTTP method - */ - method: external_exports.enum(["GET", "POST", "PUT", "PATCH"]).default("POST").describe("HTTP method"), - /** - * Headers - */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP headers"), - /** - * Authentication - */ - authentication: external_exports.object({ - type: external_exports.enum(["none", "bearer", "basic", "api-key"]).describe("Auth type"), - credentials: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Auth credentials") - }).optional().describe("Authentication configuration"), - /** - * Retry policy - */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Max retry attempts"), - backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential"), - initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay"), - maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Max retry delay") - }).optional().describe("Retry policy"), - /** - * Timeout - */ - timeoutMs: external_exports.number().int().positive().default(3e4).describe("Request timeout in milliseconds"), - /** - * Event transformation - */ - transform: external_exports.unknown().optional().describe("Transform event before sending"), - /** - * Enabled - */ - enabled: external_exports.boolean().default(true).describe("Whether webhook is enabled") -}); -var EventMessageQueueConfigSchema = external_exports.object({ - /** - * Provider - */ - provider: external_exports.enum(["kafka", "rabbitmq", "aws-sqs", "redis-pubsub", "google-pubsub", "azure-service-bus"]).describe("Message queue provider"), - /** - * Topic/Queue name - */ - topic: external_exports.string().describe("Topic or queue name"), - /** - * Event pattern - */ - eventPattern: external_exports.string().default("*").describe("Event name pattern to publish (supports wildcards)"), - /** - * Partition key - */ - partitionKey: external_exports.string().optional().describe('JSON path for partition key (e.g., "metadata.tenantId")'), - /** - * Message format - */ - format: external_exports.enum(["json", "avro", "protobuf"]).default("json").describe("Message serialization format"), - /** - * Include metadata - */ - includeMetadata: external_exports.boolean().default(true).describe("Include event metadata in message"), - /** - * Compression - */ - compression: external_exports.enum(["none", "gzip", "snappy", "lz4"]).default("none").describe("Message compression"), - /** - * Batch size - */ - batchSize: external_exports.number().int().min(1).default(1).describe("Batch size for publishing"), - /** - * Flush interval - */ - flushIntervalMs: external_exports.number().int().positive().default(1e3).describe("Flush interval for batching") -}); -var RealTimeNotificationConfigSchema = external_exports.object({ - /** - * Enable real-time notifications - */ - enabled: external_exports.boolean().default(true).describe("Enable real-time notifications"), - /** - * Protocol - */ - protocol: external_exports.enum(["websocket", "sse", "long-polling"]).default("websocket").describe("Real-time protocol"), - /** - * Event pattern - */ - eventPattern: external_exports.string().default("*").describe("Event pattern to broadcast"), - /** - * User-specific filtering - */ - userFilter: external_exports.boolean().default(true).describe("Filter events by user"), - /** - * Tenant-specific filtering - */ - tenantFilter: external_exports.boolean().default(true).describe("Filter events by tenant"), - /** - * Channels - */ - channels: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Channel name"), - eventPattern: external_exports.string().describe("Event pattern for channel"), - filter: external_exports.unknown().optional().describe("Additional filter function") - })).optional().describe("Named channels for event broadcasting"), - /** - * Rate limiting - */ - rateLimit: external_exports.object({ - maxEventsPerSecond: external_exports.number().int().positive().describe("Max events per second per client"), - windowMs: external_exports.number().int().positive().default(1e3).describe("Rate limit window") - }).optional().describe("Rate limiting configuration") -}); -var EventBusConfigSchema = external_exports.object({ - /** - * Event persistence - */ - persistence: EventPersistenceSchema.optional().describe("Event persistence configuration"), - /** - * Event queue - */ - queue: EventQueueConfigSchema.optional().describe("Event queue configuration"), - /** - * Event sourcing - */ - eventSourcing: EventSourcingConfigSchema.optional().describe("Event sourcing configuration"), - /** - * Event replay - */ - replay: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable event replay capability") - }).optional().describe("Event replay configuration"), - /** - * Webhooks - */ - webhooks: external_exports.array(EventWebhookConfigSchema).optional().describe("Webhook configurations"), - /** - * Message queue integration - */ - messageQueue: EventMessageQueueConfigSchema.optional().describe("Message queue integration"), - /** - * Real-time notifications - */ - realtime: RealTimeNotificationConfigSchema.optional().describe("Real-time notification configuration"), - /** - * Event type definitions - */ - eventTypes: external_exports.array(EventTypeDefinitionSchema).optional().describe("Event type definitions"), - /** - * Global handlers - */ - handlers: external_exports.array(EventHandlerSchema).optional().describe("Global event handlers") -}); -var FeatureStrategy = external_exports.enum([ - "boolean", - // Simple On/Off - "percentage", - // Gradual rollout (0-100%) - "user_list", - // Specific users - "group", - // Specific groups/roles - "custom" - // Custom constraint/script -]); -var FeatureFlagSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema5.describe("Feature key (snake_case)"), - label: external_exports.string().optional().describe("Display label"), - description: external_exports.string().optional(), - /** Default state */ - enabled: external_exports.boolean().default(false).describe("Is globally enabled"), - /** Rollout Strategy */ - strategy: FeatureStrategy.default("boolean"), - /** Strategy Configuration */ - conditions: external_exports.object({ - percentage: external_exports.number().min(0).max(100).optional(), - users: external_exports.array(external_exports.string()).optional(), - groups: external_exports.array(external_exports.string()).optional(), - expression: external_exports.string().optional().describe("Custom formula expression") - }).optional(), - /** Integration */ - environment: external_exports.enum(["dev", "staging", "prod", "all"]).default("all").describe("Environment validity"), - /** Expiration */ - expiresAt: external_exports.string().datetime().optional().describe("Feature flag expiration date") -}); -var FeatureFlag = Object.assign(FeatureFlagSchema, { - create: (config4) => config4 -}); -var CapabilityConformanceLevelSchema2 = external_exports.enum([ - "full", - // Complete implementation of all protocol features - "partial", - // Subset implementation with specific features listed - "experimental", - // Unstable/preview implementation - "deprecated" - // Still supported but scheduled for removal -]).describe("Level of protocol conformance"); -var ProtocolVersionSchema2 = external_exports.object({ - major: external_exports.number().int().min(0), - minor: external_exports.number().int().min(0), - patch: external_exports.number().int().min(0) -}).describe("Semantic version of the protocol"); -var ProtocolReferenceSchema2 = external_exports.object({ - /** - * Protocol identifier using reverse domain notation. - * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major} - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+protocol\.[a-z][a-z0-9._]*\.v\d+$/).describe("Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)"), - /** - * Human-readable protocol name - */ - label: external_exports.string(), - /** - * Protocol version - */ - version: ProtocolVersionSchema2, - /** - * Detailed protocol specification URL or file reference - */ - specification: external_exports.string().optional().describe("URL or path to protocol specification"), - /** - * Brief description of what this protocol defines - */ - description: external_exports.string().optional() -}); -var ProtocolFeatureSchema2 = external_exports.object({ - name: external_exports.string().describe("Feature identifier within the protocol"), - enabled: external_exports.boolean().default(true), - description: external_exports.string().optional(), - sinceVersion: external_exports.string().optional().describe("Version when this feature was added"), - deprecatedSince: external_exports.string().optional().describe("Version when deprecated") -}); -var PluginCapabilitySchema2 = external_exports.object({ - /** - * The protocol being implemented - */ - protocol: ProtocolReferenceSchema2, - /** - * Conformance level - */ - conformance: CapabilityConformanceLevelSchema2.default("full"), - /** - * Specific features implemented (required if conformance is 'partial') - */ - implementedFeatures: external_exports.array(external_exports.string()).optional().describe("List of implemented feature names"), - /** - * Optional feature flags indicating advanced capabilities - */ - features: external_exports.array(ProtocolFeatureSchema2).optional(), - /** - * Custom metadata for vendor-specific information - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Testing/Certification status - */ - certified: external_exports.boolean().default(false).describe("Has passed official conformance tests"), - certificationDate: external_exports.string().datetime().optional() -}); -var PluginInterfaceSchema2 = external_exports.object({ - /** - * Unique interface identifier - * Format: {plugin-id}.interface.{name} - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+interface\.[a-z][a-z0-9._]+$/).describe("Unique interface identifier"), - /** - * Interface name - */ - name: external_exports.string(), - /** - * Description of what this interface provides - */ - description: external_exports.string().optional(), - /** - * Interface version - */ - version: ProtocolVersionSchema2, - /** - * Methods exposed by this interface - */ - methods: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Method name"), - description: external_exports.string().optional(), - parameters: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string().describe("Type notation (e.g., string, number, User)"), - required: external_exports.boolean().default(true), - description: external_exports.string().optional() - })).optional(), - returnType: external_exports.string().optional().describe("Return value type"), - async: external_exports.boolean().default(false).describe("Whether method returns a Promise") - })), - /** - * Events emitted by this interface - */ - events: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Event name"), - description: external_exports.string().optional(), - payload: external_exports.string().optional().describe("Event payload type") - })).optional(), - /** - * Stability level - */ - stability: external_exports.enum(["stable", "beta", "alpha", "experimental"]).default("stable") -}); -var PluginDependencySchema2 = external_exports.object({ - /** - * Plugin ID using reverse domain notation - */ - pluginId: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Required plugin identifier"), - /** - * Version constraint (supports semver ranges) - * Examples: "1.0.0", "^1.2.3", ">=2.0.0 <3.0.0" - */ - version: external_exports.string().describe("Semantic version constraint"), - /** - * Whether this dependency is optional - */ - optional: external_exports.boolean().default(false), - /** - * Reason for the dependency - */ - reason: external_exports.string().optional(), - /** - * Minimum required capabilities from the dependency - */ - requiredCapabilities: external_exports.array(external_exports.string()).optional().describe("Protocol IDs the dependency must support") -}); -var ExtensionPointSchema2 = external_exports.object({ - /** - * Extension point identifier - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+extension\.[a-z][a-z0-9._]+$/).describe("Unique extension point identifier"), - /** - * Extension point name - */ - name: external_exports.string(), - /** - * Description - */ - description: external_exports.string().optional(), - /** - * Type of extension point - */ - type: external_exports.enum([ - "action", - // Plugins can register executable actions - "hook", - // Plugins can listen to lifecycle events - "widget", - // Plugins can contribute UI widgets - "provider", - // Plugins can provide data/services - "transformer", - // Plugins can transform data - "validator", - // Plugins can validate data - "decorator" - // Plugins can enhance/wrap functionality - ]), - /** - * Expected interface contract for extensions - */ - contract: external_exports.object({ - input: external_exports.string().optional().describe("Input type/schema"), - output: external_exports.string().optional().describe("Output type/schema"), - signature: external_exports.string().optional().describe("Function signature if applicable") - }).optional(), - /** - * Cardinality - */ - cardinality: external_exports.enum(["single", "multiple"]).default("multiple").describe("Whether multiple extensions can register to this point") -}); -var PluginCapabilityManifestSchema2 = external_exports.object({ - /** - * Protocols this plugin implements - */ - implements: external_exports.array(PluginCapabilitySchema2).optional().describe("List of protocols this plugin conforms to"), - /** - * Interfaces this plugin exposes to other plugins - */ - provides: external_exports.array(PluginInterfaceSchema2).optional().describe("Services/APIs this plugin offers to others"), - /** - * Dependencies on other plugins - */ - requires: external_exports.array(PluginDependencySchema2).optional().describe("Required plugins and their capabilities"), - /** - * Extension points this plugin defines - */ - extensionPoints: external_exports.array(ExtensionPointSchema2).optional().describe("Points where other plugins can extend this plugin"), - /** - * Extensions this plugin contributes to other plugins - */ - extensions: external_exports.array(external_exports.object({ - targetPluginId: external_exports.string().describe("Plugin ID being extended"), - extensionPointId: external_exports.string().describe("Extension point identifier"), - implementation: external_exports.string().describe("Path to implementation module"), - priority: external_exports.number().int().default(100).describe("Registration priority (lower = higher priority)") - })).optional().describe("Extensions contributed to other plugins") -}); -var PluginLoadingStrategySchema2 = external_exports.enum([ - "eager", - // Load immediately during bootstrap (critical plugins) - "lazy", - // Load on first use (feature plugins) - "parallel", - // Load in parallel with other plugins - "deferred", - // Load after initial bootstrap complete - "on-demand" - // Load only when explicitly requested -]).describe("Plugin loading strategy"); -var PluginPreloadConfigSchema2 = external_exports.object({ - /** - * Enable preloading for this plugin - */ - enabled: external_exports.boolean().default(false), - /** - * Preload priority (lower = higher priority) - */ - priority: external_exports.number().int().min(0).default(100), - /** - * Resources to preload - */ - resources: external_exports.array(external_exports.enum([ - "metadata", - // Plugin manifest and metadata - "dependencies", - // Plugin dependencies - "assets", - // Static assets (icons, translations) - "code", - // JavaScript code chunks - "services" - // Service definitions - ])).optional(), - /** - * Conditions for preloading - */ - conditions: external_exports.object({ - /** - * Preload only on specific routes - */ - routes: external_exports.array(external_exports.string()).optional(), - /** - * Preload only for specific user roles - */ - roles: external_exports.array(external_exports.string()).optional(), - /** - * Preload based on device type - */ - deviceType: external_exports.array(external_exports.enum(["desktop", "mobile", "tablet"])).optional(), - /** - * Network connection quality threshold - */ - minNetworkSpeed: external_exports.enum(["slow-2g", "2g", "3g", "4g"]).optional() - }).optional() -}).describe("Plugin preloading configuration"); -var PluginCodeSplittingSchema2 = external_exports.object({ - /** - * Enable code splitting for this plugin - */ - enabled: external_exports.boolean().default(true), - /** - * Split strategy - */ - strategy: external_exports.enum([ - "route", - // Split by UI routes - "feature", - // Split by feature modules - "size", - // Split by bundle size threshold - "custom" - // Custom split points defined by plugin - ]).default("feature"), - /** - * Chunk naming strategy - */ - chunkNaming: external_exports.enum(["hashed", "named", "sequential"]).default("hashed"), - /** - * Maximum chunk size in KB - */ - maxChunkSize: external_exports.number().int().min(10).optional().describe("Max chunk size in KB"), - /** - * Shared dependencies optimization - */ - sharedDependencies: external_exports.object({ - enabled: external_exports.boolean().default(true), - /** - * Minimum times a module must be shared before extraction - */ - minChunks: external_exports.number().int().min(1).default(2) - }).optional() -}).describe("Plugin code splitting configuration"); -var PluginDynamicImportSchema2 = external_exports.object({ - /** - * Enable dynamic imports - */ - enabled: external_exports.boolean().default(true), - /** - * Import mode - */ - mode: external_exports.enum([ - "async", - // Asynchronous import (recommended) - "sync", - // Synchronous import (blocking) - "eager", - // Eager evaluation - "lazy" - // Lazy evaluation - ]).default("async"), - /** - * Prefetch strategy - */ - prefetch: external_exports.boolean().default(false).describe("Prefetch module in idle time"), - /** - * Preload strategy - */ - preload: external_exports.boolean().default(false).describe("Preload module in parallel with parent"), - /** - * Webpack magic comments support - */ - webpackChunkName: external_exports.string().optional().describe("Custom chunk name for webpack"), - /** - * Import timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4).describe("Dynamic import timeout (ms)"), - /** - * Retry configuration on import failure - */ - retry: external_exports.object({ - enabled: external_exports.boolean().default(true), - maxAttempts: external_exports.number().int().min(1).max(10).default(3), - backoffMs: external_exports.number().int().min(0).default(1e3).describe("Exponential backoff base delay") - }).optional() -}).describe("Plugin dynamic import configuration"); -var PluginInitializationSchema2 = external_exports.object({ - /** - * Initialization mode - */ - mode: external_exports.enum([ - "sync", - // Synchronous initialization - "async", - // Asynchronous initialization - "parallel", - // Parallel with other plugins - "sequential" - // Must complete before next plugin - ]).default("async"), - /** - * Initialization timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4), - /** - * Startup priority (lower = higher priority, earlier initialization) - */ - priority: external_exports.number().int().min(0).default(100), - /** - * Whether to continue bootstrap if this plugin fails - */ - critical: external_exports.boolean().default(false).describe("If true, kernel bootstrap fails if plugin fails"), - /** - * Retry configuration on initialization failure - */ - retry: external_exports.object({ - enabled: external_exports.boolean().default(false), - maxAttempts: external_exports.number().int().min(1).max(5).default(3), - backoffMs: external_exports.number().int().min(0).default(1e3) - }).optional(), - /** - * Health check interval for monitoring - */ - healthCheckInterval: external_exports.number().int().min(0).optional().describe("Health check interval in ms (0 = disabled)") -}).describe("Plugin initialization configuration"); -var PluginDependencyResolutionSchema2 = external_exports.object({ - /** - * Dependency resolution strategy - */ - strategy: external_exports.enum([ - "strict", - // Exact version match required - "compatible", - // Semver compatible versions (^) - "latest", - // Always use latest compatible - "pinned" - // Lock to specific version - ]).default("compatible"), - /** - * Peer dependency handling - */ - peerDependencies: external_exports.object({ - /** - * Whether to resolve peer dependencies - */ - resolve: external_exports.boolean().default(true), - /** - * Action on missing peer dependency - */ - onMissing: external_exports.enum(["error", "warn", "ignore"]).default("warn"), - /** - * Action on peer version mismatch - */ - onMismatch: external_exports.enum(["error", "warn", "ignore"]).default("warn") - }).optional(), - /** - * Optional dependency handling - */ - optionalDependencies: external_exports.object({ - /** - * Whether to attempt loading optional dependencies - */ - load: external_exports.boolean().default(true), - /** - * Action on optional dependency load failure - */ - onFailure: external_exports.enum(["warn", "ignore"]).default("warn") - }).optional(), - /** - * Conflict resolution - */ - conflictResolution: external_exports.enum([ - "fail", - // Fail on any version conflict - "latest", - // Use latest version - "oldest", - // Use oldest version - "manual" - // Require manual resolution - ]).default("latest"), - /** - * Circular dependency handling - */ - circularDependencies: external_exports.enum([ - "error", - // Throw error on circular dependency - "warn", - // Warn but continue - "allow" - // Allow circular dependencies - ]).default("warn") -}).describe("Plugin dependency resolution configuration"); -var PluginHotReloadSchema2 = external_exports.object({ - /** - * Enable hot reload - */ - enabled: external_exports.boolean().default(false), - /** - * Target environment for hot reload behavior - */ - environment: external_exports.enum([ - "development", - // Fast reload with relaxed safety (file watchers, no health validation) - "staging", - // Production-like reload with validation but relaxed rollback - "production" - // Full safety: health validation, rollback, connection draining - ]).default("development").describe("Target environment controlling safety level"), - /** - * Hot reload strategy - */ - strategy: external_exports.enum([ - "full", - // Full plugin reload (destroy and reinitialize) - "partial", - // Partial reload (update changed modules only) - "state-preserve" - // Preserve plugin state during reload - ]).default("full"), - /** - * Files to watch for changes - */ - watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to watch"), - /** - * Files to ignore - */ - ignorePatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to ignore"), - /** - * Debounce delay in milliseconds - */ - debounceMs: external_exports.number().int().min(0).default(300), - /** - * Whether to preserve state during reload - */ - preserveState: external_exports.boolean().default(false), - /** - * State serialization - */ - stateSerialization: external_exports.object({ - enabled: external_exports.boolean().default(false), - /** - * Path to state serialization handler - */ - handler: external_exports.string().optional() - }).optional(), - /** - * Hooks for hot reload lifecycle - */ - hooks: external_exports.object({ - beforeReload: external_exports.string().optional().describe("Function to call before reload"), - afterReload: external_exports.string().optional().describe("Function to call after reload"), - onError: external_exports.string().optional().describe("Function to call on reload error") - }).optional(), - /** - * Production safety configuration - * Applied when environment is 'staging' or 'production' - */ - productionSafety: external_exports.object({ - /** - * Validate plugin health before completing reload - */ - healthValidation: external_exports.boolean().default(true).describe("Run health checks after reload before accepting traffic"), - /** - * Automatically rollback to previous version on reload failure - */ - rollbackOnFailure: external_exports.boolean().default(true).describe("Auto-rollback if reloaded plugin fails health check"), - /** - * Maximum time to wait for health validation after reload (ms) - */ - healthTimeout: external_exports.number().int().min(1e3).default(3e4).describe("Health check timeout after reload in ms"), - /** - * Drain active connections before reload - */ - drainConnections: external_exports.boolean().default(true).describe("Gracefully drain active requests before reloading"), - /** - * Maximum time to wait for connection draining (ms) - */ - drainTimeout: external_exports.number().int().min(0).default(15e3).describe("Max wait time for connection draining in ms"), - /** - * Maximum number of concurrent plugin reloads - */ - maxConcurrentReloads: external_exports.number().int().min(1).default(1).describe("Limit concurrent reloads to prevent system instability"), - /** - * Minimum interval between reloads of the same plugin (ms) - */ - minReloadInterval: external_exports.number().int().min(1e3).default(5e3).describe("Cooldown period between reloads of the same plugin") - }).optional() -}).describe("Plugin hot reload configuration"); -var PluginCachingSchema2 = external_exports.object({ - /** - * Enable caching - */ - enabled: external_exports.boolean().default(true), - /** - * Cache storage type - */ - storage: external_exports.enum([ - "memory", - // In-memory cache (fastest, not persistent) - "disk", - // Disk cache (persistent) - "indexeddb", - // Browser IndexedDB (persistent, browser only) - "hybrid" - // Memory + Disk hybrid - ]).default("memory"), - /** - * Cache key strategy - */ - keyStrategy: external_exports.enum([ - "version", - // Cache by plugin version - "hash", - // Cache by content hash - "timestamp" - // Cache by last modified timestamp - ]).default("version"), - /** - * Cache TTL in seconds - */ - ttl: external_exports.number().int().min(0).optional().describe("Time to live in seconds (0 = infinite)"), - /** - * Maximum cache size in MB - */ - maxSize: external_exports.number().int().min(1).optional().describe("Max cache size in MB"), - /** - * Cache invalidation triggers - */ - invalidateOn: external_exports.array(external_exports.enum([ - "version-change", - "dependency-change", - "manual", - "error" - ])).optional(), - /** - * Compression - */ - compression: external_exports.object({ - enabled: external_exports.boolean().default(false), - algorithm: external_exports.enum(["gzip", "brotli", "deflate"]).default("gzip") - }).optional() -}).describe("Plugin caching configuration"); -var PluginSandboxingSchema2 = external_exports.object({ - /** - * Enable sandboxing - */ - enabled: external_exports.boolean().default(false), - /** - * Isolation scope - which plugins are subject to sandboxing - */ - scope: external_exports.enum([ - "automation-only", - // Sandbox automation/scripting plugins only (current behavior) - "untrusted-only", - // Sandbox plugins below a trust threshold - "all-plugins" - // Sandbox all plugins (maximum isolation) - ]).default("automation-only").describe("Which plugins are subject to isolation"), - /** - * Sandbox isolation level - */ - isolationLevel: external_exports.enum([ - "none", - // No isolation - "process", - // Separate process (Node.js worker threads) - "vm", - // VM context isolation - "iframe", - // iframe isolation (browser) - "web-worker" - // Web Worker (browser) - ]).default("none"), - /** - * Allowed capabilities - */ - allowedCapabilities: external_exports.array(external_exports.string()).optional().describe("List of allowed capability IDs"), - /** - * Resource quotas - */ - resourceQuotas: external_exports.object({ - /** - * Maximum memory usage in MB - */ - maxMemoryMB: external_exports.number().int().min(1).optional(), - /** - * Maximum CPU time in milliseconds - */ - maxCpuTimeMs: external_exports.number().int().min(100).optional(), - /** - * Maximum number of file descriptors - */ - maxFileDescriptors: external_exports.number().int().min(1).optional(), - /** - * Maximum network bandwidth in KB/s - */ - maxNetworkKBps: external_exports.number().int().min(1).optional() - }).optional(), - /** - * Permissions - */ - permissions: external_exports.object({ - /** - * Allowed API access - */ - allowedAPIs: external_exports.array(external_exports.string()).optional(), - /** - * Allowed file system paths - */ - allowedPaths: external_exports.array(external_exports.string()).optional(), - /** - * Allowed network endpoints - */ - allowedEndpoints: external_exports.array(external_exports.string()).optional(), - /** - * Allowed environment variables - */ - allowedEnvVars: external_exports.array(external_exports.string()).optional() - }).optional(), - /** - * Inter-Plugin Communication (IPC) configuration - * Enables isolated plugins to communicate with the kernel and other plugins - */ - ipc: external_exports.object({ - /** - * Enable IPC for sandboxed plugins - */ - enabled: external_exports.boolean().default(true).describe("Allow sandboxed plugins to communicate via IPC"), - /** - * IPC transport mechanism - */ - transport: external_exports.enum([ - "message-port", - // MessagePort (worker threads / Web Workers) - "unix-socket", - // Unix domain sockets (process isolation) - "tcp", - // TCP sockets (container isolation) - "memory" - // Shared memory channel (in-process VM) - ]).default("message-port").describe("IPC transport for cross-boundary communication"), - /** - * Maximum message size in bytes - */ - maxMessageSize: external_exports.number().int().min(1024).default(1048576).describe("Maximum IPC message size in bytes (default 1MB)"), - /** - * Message timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4).describe("IPC message response timeout in ms"), - /** - * Allowed service calls through IPC - */ - allowedServices: external_exports.array(external_exports.string()).optional().describe("Service names the sandboxed plugin may invoke via IPC") - }).optional() -}).describe("Plugin sandboxing configuration"); -var PluginPerformanceMonitoringSchema2 = external_exports.object({ - /** - * Enable performance monitoring - */ - enabled: external_exports.boolean().default(false), - /** - * Metrics to collect - */ - metrics: external_exports.array(external_exports.enum([ - "load-time", - "init-time", - "memory-usage", - "cpu-usage", - "api-calls", - "error-rate", - "cache-hit-rate" - ])).optional(), - /** - * Sampling rate (0-1, where 1 = 100%) - */ - samplingRate: external_exports.number().min(0).max(1).default(1), - /** - * Reporting interval in seconds - */ - reportingInterval: external_exports.number().int().min(1).default(60), - /** - * Performance budget thresholds - */ - budgets: external_exports.object({ - /** - * Maximum load time in milliseconds - */ - maxLoadTimeMs: external_exports.number().int().min(0).optional(), - /** - * Maximum init time in milliseconds - */ - maxInitTimeMs: external_exports.number().int().min(0).optional(), - /** - * Maximum memory usage in MB - */ - maxMemoryMB: external_exports.number().int().min(0).optional() - }).optional(), - /** - * Action on budget violation - */ - onBudgetViolation: external_exports.enum(["warn", "error", "ignore"]).default("warn") -}).describe("Plugin performance monitoring configuration"); -var PluginLoadingConfigSchema2 = external_exports.object({ - /** - * Loading strategy - */ - strategy: PluginLoadingStrategySchema2.default("lazy"), - /** - * Preloading configuration - */ - preload: PluginPreloadConfigSchema2.optional(), - /** - * Code splitting configuration - */ - codeSplitting: PluginCodeSplittingSchema2.optional(), - /** - * Dynamic import configuration - */ - dynamicImport: PluginDynamicImportSchema2.optional(), - /** - * Initialization configuration - */ - initialization: PluginInitializationSchema2.optional(), - /** - * Dependency resolution configuration - */ - dependencyResolution: PluginDependencyResolutionSchema2.optional(), - /** - * Hot reload configuration (development and production) - */ - hotReload: PluginHotReloadSchema2.optional(), - /** - * Caching configuration - */ - caching: PluginCachingSchema2.optional(), - /** - * Sandboxing configuration - */ - sandboxing: PluginSandboxingSchema2.optional(), - /** - * Performance monitoring - */ - monitoring: PluginPerformanceMonitoringSchema2.optional() -}).describe("Complete plugin loading configuration"); -var PluginLoadingEventSchema = external_exports.object({ - /** - * Event type - */ - type: external_exports.enum([ - "load-started", - "load-completed", - "load-failed", - "init-started", - "init-completed", - "init-failed", - "preload-started", - "preload-completed", - "cache-hit", - "cache-miss", - "hot-reload", - "dynamic-load", - // Plugin loaded at runtime - "dynamic-unload", - // Plugin unloaded at runtime - "dynamic-discover" - // Plugin discovered via registry - ]), - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Timestamp - */ - timestamp: external_exports.number().int().min(0), - /** - * Duration in milliseconds - */ - durationMs: external_exports.number().int().min(0).optional(), - /** - * Additional metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Error if event represents a failure - */ - error: external_exports.object({ - message: external_exports.string(), - code: external_exports.string().optional(), - stack: external_exports.string().optional() - }).optional() -}).describe("Plugin loading lifecycle event"); -var PluginLoadingStateSchema = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Current state - */ - state: external_exports.enum([ - "pending", - // Not yet loaded - "loading", - // Currently loading - "loaded", - // Code loaded, not initialized - "initializing", - // Currently initializing - "ready", - // Fully initialized and ready - "failed", - // Failed to load or initialize - "reloading", - // Hot reloading in progress - "unloading", - // Being unloaded at runtime - "unloaded" - // Successfully unloaded (dynamic loading) - ]), - /** - * Load progress (0-100) - */ - progress: external_exports.number().min(0).max(100).default(0), - /** - * Loading start time - */ - startedAt: external_exports.number().int().min(0).optional(), - /** - * Loading completion time - */ - completedAt: external_exports.number().int().min(0).optional(), - /** - * Last error - */ - lastError: external_exports.string().optional(), - /** - * Retry count - */ - retryCount: external_exports.number().int().min(0).default(0) -}).describe("Plugin loading state"); -var PluginContextSchema = external_exports.object({ - ql: external_exports.object({ - object: external_exports.function().describe("Get object handle for method chaining"), - query: external_exports.function().describe("Execute a query") - }).passthrough().describe("ObjectQL Engine Interface"), - os: external_exports.object({ - getCurrentUser: external_exports.function().describe("Get the current authenticated user"), - getConfig: external_exports.function().describe("Get platform configuration") - }).passthrough().describe("ObjectStack Kernel Interface"), - logger: external_exports.object({ - debug: external_exports.function().describe("Log debug message"), - info: external_exports.function().describe("Log info message"), - warn: external_exports.function().describe("Log warning message"), - error: external_exports.function().describe("Log error message") - }).passthrough().describe("Logger Interface"), - storage: external_exports.object({ - get: external_exports.function().describe("Get a value from storage"), - set: external_exports.function().describe("Set a value in storage"), - delete: external_exports.function().describe("Delete a value from storage") - }).passthrough().describe("Storage Interface"), - i18n: external_exports.object({ - t: external_exports.function().describe("Translate a key"), - getLocale: external_exports.function().describe("Get current locale") - }).passthrough().describe("Internationalization Interface"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()), - events: external_exports.record(external_exports.string(), external_exports.unknown()), - app: external_exports.object({ - router: external_exports.object({ - get: external_exports.function().describe("Register GET route handler"), - post: external_exports.function().describe("Register POST route handler"), - use: external_exports.function().describe("Register middleware") - }).passthrough() - }).passthrough().describe("App Framework Interface"), - drivers: external_exports.object({ - register: external_exports.function().describe("Register a driver") - }).passthrough().describe("Driver Registry") -}); -var UpgradeContextSchema = external_exports.object({ - /** Version before upgrade */ - previousVersion: external_exports.string().describe("Version before upgrade"), - /** Version after upgrade */ - newVersion: external_exports.string().describe("Version after upgrade"), - /** Whether this is a major version bump */ - isMajorUpgrade: external_exports.boolean().describe("Whether this is a major version bump"), - /** Metadata snapshot before upgrade (for migration logic) */ - previousMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Metadata snapshot before upgrade") -}).describe("Version migration context for onUpgrade hook"); -var PluginLifecycleSchema2 = external_exports.object({ - onInstall: external_exports.function().optional().describe("Called when plugin is installed"), - onEnable: external_exports.function().optional().describe("Called when plugin is enabled"), - onDisable: external_exports.function().optional().describe("Called when plugin is disabled"), - onUninstall: external_exports.function().optional().describe("Called when plugin is uninstalled"), - onUpgrade: external_exports.function().optional().describe("Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade") -}); -var CORE_PLUGIN_TYPES2 = [ - "ui", - // Frontend: Serves static assets/SPA (e.g. Console, Studio) - "driver", - // Connectivity: Database or Storage adapters (e.g. SQL, S3) - "server", - // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL) - "app", - // Business: Vertical Solution Bundle (Metadata + Logic) - "theme", - // Appearance: UI Overrides & CSS Variables - "agent", - // AI: Autonomous Agent & Tool Definitions - "objectql" - // Core: ObjectQL Engine Data Provider -]; -var PluginSchema = PluginLifecycleSchema2.extend({ - id: external_exports.string().min(1).optional().describe("Unique Plugin ID (e.g. com.example.crm)"), - type: external_exports.enum([ - "standard", - // Default: General purpose backend logic (Service, Hook, etc.) - ...CORE_PLUGIN_TYPES2 - ]).default("standard").optional().describe("Plugin Type categorization for runtime behavior"), - staticPath: external_exports.string().optional().describe('Absolute path to static assets (Required for type="ui-plugin")'), - slug: external_exports.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type="ui-plugin")'), - default: external_exports.boolean().optional().describe('Serve at root path (Only one "ui-plugin" can be default)'), - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic Version"), - description: external_exports.string().optional(), - author: external_exports.string().optional(), - homepage: external_exports.string().url().optional() -}); -var DatasetMode3 = external_exports.enum([ - "insert", - // Try to insert, fail on duplicate - "update", - // Only update found records, ignore new - "upsert", - // Create new or Update existing (Standard) - "replace", - // Delete ALL records in object then insert (Dangerous - use for cache tables) - "ignore" - // Try to insert, silently skip duplicates -]); -var DatasetSchema3 = external_exports.object({ - /** - * Target Object - * The machine name of the object to populate. - */ - object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target Object Name"), - /** - * Idempotency Key (The "Upsert" Key) - * The field used to check if a record already exists. - * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'. - * Standard: 'id' is rarely used for portable seed data — prefer natural keys. - */ - externalId: external_exports.string().default("name").describe("Field match for uniqueness check"), - /** - * Import Strategy - */ - mode: DatasetMode3.default("upsert").describe("Conflict resolution strategy"), - /** - * Environment Scope - * - 'all': Always load - * - 'dev': Only for development/demo - * - 'test': Only for CI/CD tests - */ - env: external_exports.array(external_exports.enum(["prod", "dev", "test"])).default(["prod", "dev", "test"]).describe("Applicable environments"), - /** - * The Payload - * Array of raw JSON objects matching the Object Schema. - */ - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Data records") -}); -var ManifestSchema2 = external_exports.object({ - /** - * Unique package identifier using reverse domain notation. - * Must be unique across the entire ecosystem. - * - * @example "com.steedos.crm" - * @example "org.apache.superset" - */ - id: external_exports.string().describe("Unique package identifier (reverse domain style)"), - /** - * Short namespace identifier for metadata scoping. - * Used as a prefix for objects and other metadata to prevent naming collisions - * across packages from different vendors. - * - * Rules: - * - 2-20 characters, lowercase letters, digits, and underscores only. - * - Must be unique within a running instance. - * - Platform-reserved namespaces (no prefix applied): "base", "system". - * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator). - * - * @example "crm" → objects become crm__account, crm__deal - * @example "todo" → objects become todo__task - * @example "base" → objects keep short name (platform reserved) - */ - namespace: external_exports.string().regex(/^[a-z][a-z0-9_]{1,19}$/, "Namespace must be 2-20 chars, lowercase alphanumeric + underscore").optional().describe('Short namespace identifier for metadata scoping (e.g. "crm", "todo")'), - /** - * Package version following semantic versioning (major.minor.patch). - * - * @example "1.0.0" - * @example "2.1.0-beta.1" - */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Package version (semantic versioning)"), - /** - * Type of the package in the ObjectStack ecosystem. - * - plugin: General-purpose functionality extension (Runtime: standard) - * - app: Business application package - * - driver: Connectivity adapter - * - server: Protocol gateway (Hono, GraphQL) - * - ui: Frontend package (Static/SPA) - * - theme: UI Theme - * - agent: AI Agent - * - module: Reusable code library/shared module - * - objectql: Core engine - * - adapter: Host adapter (Express, Fastify) - */ - type: external_exports.enum([ - "plugin", - ...CORE_PLUGIN_TYPES2, - "module", - "gateway", - // Deprecated: use 'server' - "adapter" - ]).describe("Type of package"), - /** - * Human-readable name of the package. - * Displayed in the UI for users. - * - * @example "Project Management" - */ - name: external_exports.string().describe("Human-readable package name"), - /** - * Brief description of the package functionality. - * Displayed in the marketplace and plugin manager. - */ - description: external_exports.string().optional().describe("Package description"), - /** - * Array of permission strings that the package requires. - * These form the "Scope" requested by the package at installation. - * - * @example ["system.user.read", "system.data.write"] - */ - permissions: external_exports.array(external_exports.string()).optional().describe("Array of required permission strings"), - /** - * Glob patterns specifying ObjectQL schemas files. - * Matches `*.object.yml` or `*.object.ts` files to load business objects. - * - * @example ["./src/objects/*.object.yml"] - */ - objects: external_exports.array(external_exports.string()).optional().describe("Glob patterns for ObjectQL schemas files"), - /** - * Defines system level DataSources. - * Matches `*.datasource.yml` files. - * - * @example ["./src/datasources/*.datasource.mongo.yml"] - */ - datasources: external_exports.array(external_exports.string()).optional().describe("Glob patterns for Datasource definitions"), - /** - * Package Dependencies. - * Map of package IDs to version requirements. - * - * @example { "@steedos/plugin-auth": "^2.0.0" } - */ - dependencies: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Package dependencies"), - /** - * Plugin Configuration Schema. - * Defines the settings this plugin exposes to the user via UI/ENV. - * Uses a simplified JSON Schema format. - * - * @example - * { - * "title": "Stripe Config", - * "properties": { - * "apiKey": { "type": "string", "secret": true }, - * "currency": { "type": "string", "default": "USD" } - * } - * } - */ - configuration: external_exports.object({ - title: external_exports.string().optional(), - properties: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["string", "number", "boolean", "array", "object"]).describe("Data type of the setting"), - default: external_exports.unknown().optional().describe("Default value"), - description: external_exports.string().optional().describe("Tooltip description"), - required: external_exports.boolean().optional().describe("Is this setting required?"), - secret: external_exports.boolean().optional().describe("If true, value is encrypted/masked (e.g. API Keys)"), - enum: external_exports.array(external_exports.string()).optional().describe("Allowed values for select inputs") - })).describe("Map of configuration keys to their definitions") - }).optional().describe("Plugin configuration settings"), - /** - * Contribution Points (VS Code Style). - * formalized way to extend the platform capabilities. - */ - contributes: external_exports.object({ - /** - * Register new Metadata Kinds (CRDs). - * Enables the system to parse and validate new file types. - * Example: Registering a BI plugin to handle *.report.ts - */ - kinds: external_exports.array(external_exports.object({ - id: external_exports.string().describe('The generic identifier of the kind (e.g., "sys.bi.report")'), - globs: external_exports.array(external_exports.string()).describe('File patterns to watch (e.g., ["**/*.report.ts"])'), - description: external_exports.string().optional().describe("Description of what this kind represents") - })).optional().describe("New Metadata Types to recognize"), - /** - * Register System Hooks. - * Declares that this plugin listens to specific system events. - */ - events: external_exports.array(external_exports.string()).optional().describe("Events this plugin listens to"), - /** - * Register UI Menus. - */ - menus: external_exports.record(external_exports.string(), external_exports.array(external_exports.object({ - id: external_exports.string(), - label: external_exports.string(), - command: external_exports.string().optional() - }))).optional().describe("UI Menu contributions"), - /** - * Register Custom Themes. - */ - themes: external_exports.array(external_exports.object({ - id: external_exports.string(), - label: external_exports.string(), - path: external_exports.string() - })).optional().describe("Theme contributions"), - /** - * Register Translations. - * Path to translation files (e.g. "locales/en.json"). - */ - translations: external_exports.array(external_exports.object({ - locale: external_exports.string(), - path: external_exports.string() - })).optional().describe("Translation resources"), - /** - * Register Server Actions. - * Invocable functions exposed to Flows or API. - */ - actions: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Unique action name"), - label: external_exports.string().optional(), - description: external_exports.string().optional(), - input: external_exports.unknown().optional().describe("Input validation schema"), - output: external_exports.unknown().optional().describe("Output schema") - })).optional().describe("Exposed server actions"), - /** - * Register Storage Drivers. - * Enables connecting to new types of datasources. - */ - drivers: external_exports.array(external_exports.object({ - id: external_exports.string().describe('Driver unique identifier (e.g. "postgres", "mongo")'), - label: external_exports.string().describe("Human readable name"), - description: external_exports.string().optional() - })).optional().describe("Driver contributions"), - /** - * Register Custom Field Types. - * Extends the data model with new widget types. - */ - fieldTypes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Unique field type name (e.g. "vector")'), - label: external_exports.string().describe("Display label"), - description: external_exports.string().optional() - })).optional().describe("Field Type contributions"), - /** - * Register Custom Query Operators/Functions. - * Extends ObjectQL with new functions (e.g. distance()). - */ - functions: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Function name (e.g. "distance")'), - description: external_exports.string().optional(), - args: external_exports.array(external_exports.string()).optional().describe("Argument types"), - returnType: external_exports.string().optional() - })).optional().describe("Query Function contributions"), - /** - * Register API Route Namespaces. - * Declares the API endpoints this plugin provides to the HttpDispatcher. - * The kernel routes matching prefixes to this plugin's handler. - * - * @example - * routes: [ - * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] } - * ] - */ - routes: external_exports.array(external_exports.object({ - /** URL path prefix (e.g. "/api/v1/ai") */ - prefix: external_exports.string().regex(/^\//).describe("API path prefix"), - /** Service name this plugin provides */ - service: external_exports.string().describe("Service name this plugin provides"), - /** Protocol method names implemented */ - methods: external_exports.array(external_exports.string()).optional().describe('Protocol method names implemented (e.g. ["aiNlq", "aiChat"])') - })).optional().describe("API route contributions to HttpDispatcher"), - /** - * Register CLI Commands. - * Allows plugins to extend the ObjectStack CLI with custom commands. - * Each command entry declares metadata; the actual Commander.js command - * is resolved at runtime by importing the plugin's module. - * - * The plugin package must export a `commands` array of Commander.js `Command` instances - * from its main entry point or from the path specified in `module`. - * - * @example - * ```yaml - * commands: - * - name: marketplace - * description: "Manage marketplace apps" - * module: "./cli" # optional, defaults to package main - * - name: deploy - * description: "Deploy to cloud" - * ``` - */ - commands: external_exports.array(external_exports.object({ - /** CLI command name (e.g., "marketplace", "deploy"). Must be a valid CLI identifier. */ - name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), - /** Brief description shown in `os --help` */ - description: external_exports.string().optional().describe("Command description for help text"), - /** - * Optional module path (relative to package root) that exports the Commander.js commands. - * If omitted, the CLI will import from the package's main entry point. - * The module must export a `commands` array of Commander.js `Command` instances, - * or a single `Command` instance as default export. - */ - module: external_exports.string().optional().describe("Module path exporting Commander.js commands") - })).optional().describe("CLI command contributions") - }).optional().describe("Platform contributions"), - /** - * Initial data seeding configuration. - * Defines default records to be inserted when the package is installed. - * - * Uses the standard DatasetSchema which supports idempotent upsert via - * `externalId`, environment scoping via `env`, and multiple conflict - * resolution modes. - * - * @deprecated Prefer using the top-level `data` field on the Stack Definition - * (defineStack({ data: [...] })) for better visibility and metadata registration. - * This field is retained for backward compatibility with manifest-only packages. - */ - data: external_exports.array(DatasetSchema3).optional().describe("Initial seed data (prefer top-level data field)"), - /** - * Plugin Capability Manifest. - * Declares protocols implemented, interfaces provided, dependencies, and extension points. - * This enables plugin interoperability and automatic discovery. - */ - capabilities: PluginCapabilityManifestSchema2.optional().describe("Plugin capability declarations for interoperability"), - /** - * Extension points contributed by this package. - * Allows packages to extend UI components, add functionality, etc. - */ - extensions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Extension points and contributions"), - /** - * Plugin Loading Configuration. - * Configures how the plugin is loaded, initialized, and managed at runtime. - * Includes strategies for lazy loading, code splitting, caching, and hot reload. - */ - loading: PluginLoadingConfigSchema2.optional().describe("Plugin loading and runtime behavior configuration"), - /** - * Platform Compatibility Requirements. - * Specifies the minimum ObjectStack platform version required to run this package. - * Used at install time to prevent incompatible packages from being installed. - * - * @example - * ```yaml - * engine: - * objectstack: ">=3.0.0" - * ``` - */ - engine: external_exports.object({ - /** ObjectStack platform version requirement (SemVer range) */ - objectstack: external_exports.string().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe('ObjectStack platform version requirement (SemVer range, e.g. ">=3.0.0")') - }).optional().describe("Platform compatibility requirements") -}); -var CustomizationOriginSchema = external_exports.enum([ - "package", - // Delivered by a plugin package (system layer, read-only) - "admin", - // Created/modified by platform admin via UI - "user", - // Created/modified by end user via UI - "migration", - // Created during data migration - "api" - // Created via API -]); -var FieldChangeSchema2 = external_exports.object({ - /** JSON path to the changed field (e.g. "fields.status.label") */ - path: external_exports.string().describe("JSON path to the changed field"), - /** Original value from the package (for diff/rollback) */ - originalValue: external_exports.unknown().optional().describe("Original value from the package"), - /** Current customized value */ - currentValue: external_exports.unknown().describe("Current customized value"), - /** Who made this change */ - changedBy: external_exports.string().optional().describe("User or admin who made this change"), - /** When this change was made */ - changedAt: external_exports.string().datetime().optional().describe("Timestamp of the change") -}); -var MetadataOverlaySchema2 = external_exports.object({ - /** Primary key */ - id: external_exports.string().describe("Overlay record ID (UUID)"), - /** The metadata type being customized (e.g. "object", "view", "flow") */ - baseType: external_exports.string().describe("Metadata type being customized"), - /** The metadata name being customized (e.g. "crm__account") */ - baseName: external_exports.string().describe("Metadata name being customized"), - /** Package that owns the base metadata (null for platform-created metadata) */ - packageId: external_exports.string().optional().describe("Package ID that delivered the base metadata"), - /** Package version when the customization was made (for upgrade diffing) */ - packageVersion: external_exports.string().optional().describe("Package version when overlay was created"), - /** Customization scope */ - scope: external_exports.enum(["platform", "user"]).default("platform").describe("Customization scope (platform=admin, user=personal)"), - /** Tenant ID for multi-tenant isolation */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** Owner user ID (for user-scope overlays) */ - owner: external_exports.string().optional().describe("Owner user ID for user-scope overlays"), - /** - * The overlay payload. - * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396). - * - To modify a field: include the field with its new value - * - To delete a field: set its value to null - * - Omitted fields remain unchanged from base - */ - patch: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Merge Patch payload (changed fields only)"), - /** - * Detailed change tracking for each modified field. - * Enables field-level conflict detection during upgrades. - */ - changes: external_exports.array(FieldChangeSchema2).optional().describe("Field-level change tracking for conflict detection"), - /** Whether this overlay is currently active */ - active: external_exports.boolean().default(true).describe("Whether this overlay is active"), - /** Audit timestamps */ - createdAt: external_exports.string().datetime().optional(), - createdBy: external_exports.string().optional(), - updatedAt: external_exports.string().datetime().optional(), - updatedBy: external_exports.string().optional() -}); -var MergeConflictSchema2 = external_exports.object({ - /** JSON path to the conflicting field */ - path: external_exports.string().describe("JSON path to the conflicting field"), - /** Value in the old package version */ - baseValue: external_exports.unknown().describe("Value in the old package version"), - /** Value in the new package version */ - incomingValue: external_exports.unknown().describe("Value in the new package version"), - /** Customer's customized value */ - customValue: external_exports.unknown().describe("Customer customized value"), - /** Suggested resolution strategy */ - suggestedResolution: external_exports.enum([ - "keep-custom", - // Keep customer's customization - "accept-incoming", - // Accept package update - "manual" - // Requires manual resolution - ]).describe("Suggested resolution strategy"), - /** Reason for the suggested resolution */ - reason: external_exports.string().optional().describe("Explanation for the suggested resolution") -}); -var MergeStrategyConfigSchema2 = external_exports.object({ - /** Default strategy when no field-level rule matches */ - defaultStrategy: external_exports.enum([ - "keep-custom", - // Preserve all customer customizations (safe) - "accept-incoming", - // Accept all package updates (overwrite) - "three-way-merge" - // Intelligent 3-way merge with conflict detection - ]).default("three-way-merge").describe("Default merge strategy"), - /** - * Field paths that should always accept incoming package updates. - * Use for fields that the package vendor considers "owned" and should not be customized. - * @example ["fields.*.type", "triggers.*"] - */ - alwaysAcceptIncoming: external_exports.array(external_exports.string()).optional().describe("Field paths that always accept package updates"), - /** - * Field paths where customer customizations always win. - * Use for UI-facing fields like labels, descriptions, help text. - * @example ["fields.*.label", "fields.*.helpText", "description"] - */ - alwaysKeepCustom: external_exports.array(external_exports.string()).optional().describe("Field paths where customer customizations always win"), - /** Whether to automatically resolve non-conflicting changes */ - autoResolveNonConflicting: external_exports.boolean().default(true).describe("Auto-resolve changes that do not conflict") -}); -var MergeResultSchema = external_exports.object({ - /** Whether the merge completed successfully (no unresolved conflicts) */ - success: external_exports.boolean().describe("Whether merge completed without unresolved conflicts"), - /** The merged metadata payload */ - mergedMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Merged metadata result"), - /** Updated overlay with remaining customizations */ - updatedOverlay: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated overlay after merge"), - /** List of conflicts that require manual resolution */ - conflicts: external_exports.array(MergeConflictSchema2).optional().describe("Unresolved merge conflicts"), - /** Summary of automatically resolved changes */ - autoResolved: external_exports.array(external_exports.object({ - path: external_exports.string(), - resolution: external_exports.string(), - description: external_exports.string().optional() - })).optional().describe("Summary of auto-resolved changes"), - /** Statistics */ - stats: external_exports.object({ - totalFields: external_exports.number().int().min(0).describe("Total fields evaluated"), - unchanged: external_exports.number().int().min(0).describe("Fields with no changes"), - autoResolved: external_exports.number().int().min(0).describe("Fields auto-resolved"), - conflicts: external_exports.number().int().min(0).describe("Fields with conflicts") - }).optional() -}); -var CustomizationPolicySchema2 = external_exports.object({ - /** Metadata type this policy applies to */ - metadataType: external_exports.string().describe('Metadata type (e.g. "object", "view")'), - /** Whether customization is allowed at all for this type */ - allowCustomization: external_exports.boolean().default(true), - /** - * Field paths that are locked (cannot be customized). - * @example ["name", "type", "fields.*.type"] - */ - lockedFields: external_exports.array(external_exports.string()).optional().describe("Field paths that cannot be customized"), - /** - * Field paths that are customizable. - * If specified, only these fields can be customized (whitelist mode). - * @example ["label", "description", "fields.*.label", "fields.*.helpText"] - */ - customizableFields: external_exports.array(external_exports.string()).optional().describe("Field paths that can be customized (whitelist)"), - /** - * Whether users can add new fields to package objects. - * When true, admins can extend package objects with custom fields. - */ - allowAddFields: external_exports.boolean().default(true).describe("Whether admins can add new fields to package objects"), - /** - * Whether users can delete package-delivered fields. - * Typically false — fields can only be hidden, not deleted. - */ - allowDeleteFields: external_exports.boolean().default(false).describe("Whether admins can delete package-delivered fields") -}); -var MetadataFormatSchema4 = external_exports.enum(["json", "yaml", "typescript", "javascript"]); -var MetadataStatsSchema3 = external_exports.object({ - /** - * Size of the metadata file in bytes - */ - size: external_exports.number().int().min(0).describe("File size in bytes"), - /** - * Last modification timestamp - */ - modifiedAt: external_exports.string().datetime().describe("Last modified date"), - /** - * ETag for cache validation - * Used for conditional requests (If-None-Match header) - */ - etag: external_exports.string().describe("Entity tag for cache validation"), - /** - * Serialization format - */ - format: MetadataFormatSchema4.describe("Serialization format"), - /** - * Full file path (if applicable) - */ - path: external_exports.string().optional().describe("File system path"), - /** - * Additional metadata provider-specific properties - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific metadata") -}); -var MetadataLoadOptionsSchema2 = external_exports.object({ - /** - * Glob patterns to match files - * Example: ["**\/*.object.ts", "**\/*.object.json"] - */ - patterns: external_exports.array(external_exports.string()).optional().describe("File glob patterns"), - /** - * If-None-Match header for conditional loading - * Only load if ETag doesn't match - */ - ifNoneMatch: external_exports.string().optional().describe("ETag for conditional request"), - /** - * If-Modified-Since header for conditional loading - */ - ifModifiedSince: external_exports.string().datetime().optional().describe("Only load if modified after this date"), - /** - * Whether to validate against Zod schema - */ - validate: external_exports.boolean().default(true).describe("Validate against schema"), - /** - * Whether to use cache if available - */ - useCache: external_exports.boolean().default(true).describe("Enable caching"), - /** - * Filter function (serialized as string) - * Example: "(item) => item.name.startsWith('sys_')" - */ - filter: external_exports.string().optional().describe("Filter predicate as string"), - /** - * Maximum number of items to load - */ - limit: external_exports.number().int().min(1).optional().describe("Maximum items to load"), - /** - * Recursively search subdirectories - */ - recursive: external_exports.boolean().default(true).describe("Search subdirectories") -}); -var MetadataSaveOptionsSchema2 = external_exports.object({ - /** - * Serialization format - */ - format: MetadataFormatSchema4.default("typescript").describe("Output format"), - /** - * Prettify output (formatted with indentation) - */ - prettify: external_exports.boolean().default(true).describe("Format with indentation"), - /** - * Indentation size (spaces) - */ - indent: external_exports.number().int().min(0).max(8).default(2).describe("Indentation spaces"), - /** - * Sort object keys alphabetically - */ - sortKeys: external_exports.boolean().default(false).describe("Sort object keys"), - /** - * Include default values in output - */ - includeDefaults: external_exports.boolean().default(false).describe("Include default values"), - /** - * Create backup before overwriting - */ - backup: external_exports.boolean().default(false).describe("Create backup file"), - /** - * Overwrite if exists - */ - overwrite: external_exports.boolean().default(true).describe("Overwrite existing file"), - /** - * Atomic write (write to temp file, then rename) - */ - atomic: external_exports.boolean().default(true).describe("Use atomic write operation"), - /** - * Custom file path (overrides default location) - */ - path: external_exports.string().optional().describe("Custom output path") -}); -var MetadataExportOptionsSchema2 = external_exports.object({ - /** - * Output file path - */ - output: external_exports.string().describe("Output file path"), - /** - * Export format - */ - format: MetadataFormatSchema4.default("json").describe("Export format"), - /** - * Filter predicate as string - */ - filter: external_exports.string().optional().describe("Filter items to export"), - /** - * Include statistics in export - */ - includeStats: external_exports.boolean().default(false).describe("Include metadata statistics"), - /** - * Compress output - */ - compress: external_exports.boolean().default(false).describe("Compress output (gzip)"), - /** - * Pretty print output - */ - prettify: external_exports.boolean().default(true).describe("Pretty print output") -}); -var MetadataImportOptionsSchema2 = external_exports.object({ - /** - * Conflict resolution strategy - */ - conflictResolution: external_exports.enum(["skip", "overwrite", "merge", "fail"]).default("merge").describe("How to handle existing items"), - /** - * Validate items against schema - */ - validate: external_exports.boolean().default(true).describe("Validate before import"), - /** - * Dry run (don't actually save) - */ - dryRun: external_exports.boolean().default(false).describe("Simulate import without saving"), - /** - * Continue on errors - */ - continueOnError: external_exports.boolean().default(false).describe("Continue if validation fails"), - /** - * Transform function (as string) - * Example: "(item) => ({ ...item, imported: true })" - */ - transform: external_exports.string().optional().describe("Transform items before import") -}); -var MetadataLoadResultSchema2 = external_exports.object({ - /** - * Loaded data - */ - data: external_exports.unknown().nullable().describe("Loaded metadata"), - /** - * Whether data came from cache (304 Not Modified) - */ - fromCache: external_exports.boolean().default(false).describe("Loaded from cache"), - /** - * Not modified (conditional request matched) - */ - notModified: external_exports.boolean().default(false).describe("Not modified since last request"), - /** - * ETag of loaded data - */ - etag: external_exports.string().optional().describe("Entity tag"), - /** - * Statistics about loaded data - */ - stats: MetadataStatsSchema3.optional().describe("Metadata statistics"), - /** - * Load time in milliseconds - */ - loadTime: external_exports.number().min(0).optional().describe("Load duration in ms") -}); -var MetadataSaveResultSchema2 = external_exports.object({ - /** - * Whether save was successful - */ - success: external_exports.boolean().describe("Save successful"), - /** - * Path where file was saved - */ - path: external_exports.string().describe("Output path"), - /** - * Generated ETag - */ - etag: external_exports.string().optional().describe("Generated entity tag"), - /** - * File size in bytes - */ - size: external_exports.number().int().min(0).optional().describe("File size"), - /** - * Save time in milliseconds - */ - saveTime: external_exports.number().min(0).optional().describe("Save duration in ms"), - /** - * Backup path (if created) - */ - backupPath: external_exports.string().optional().describe("Backup file path") -}); -var MetadataWatchEventSchema2 = external_exports.object({ - /** - * Event type - */ - type: external_exports.enum(["added", "changed", "deleted"]).describe("Event type"), - /** - * Metadata type (e.g., 'object', 'view', 'app') - */ - metadataType: external_exports.string().describe("Type of metadata"), - /** - * Item name/identifier - */ - name: external_exports.string().describe("Item identifier"), - /** - * Full file path - */ - path: external_exports.string().describe("File path"), - /** - * Loaded item data (for added/changed events) - */ - data: external_exports.unknown().optional().describe("Item data"), - /** - * Timestamp - */ - timestamp: external_exports.string().datetime().describe("Event timestamp") -}); -var MetadataCollectionInfoSchema2 = external_exports.object({ - /** - * Collection type (e.g., 'object', 'view', 'app') - */ - type: external_exports.string().describe("Collection type"), - /** - * Total items in collection - */ - count: external_exports.number().int().min(0).describe("Number of items"), - /** - * Formats found in collection - */ - formats: external_exports.array(MetadataFormatSchema4).describe("Formats in collection"), - /** - * Total size in bytes - */ - totalSize: external_exports.number().int().min(0).optional().describe("Total size in bytes"), - /** - * Last modified timestamp - */ - lastModified: external_exports.string().datetime().optional().describe("Last modification date"), - /** - * Collection location (path or URL) - */ - location: external_exports.string().optional().describe("Collection location") -}); -var MetadataLoaderContractSchema2 = external_exports.object({ - /** - * Loader name/identifier - */ - name: external_exports.string().describe("Loader identifier"), - /** - * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:') - */ - protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Protocol identifier"), - /** - * Detailed capabilities - */ - capabilities: external_exports.object({ - read: external_exports.boolean().default(true), - write: external_exports.boolean().default(false), - watch: external_exports.boolean().default(false), - list: external_exports.boolean().default(true) - }).describe("Loader capabilities"), - /** - * Supported formats - */ - supportedFormats: external_exports.array(MetadataFormatSchema4).describe("Supported formats"), - /** - * Whether loader supports watching for changes - */ - supportsWatch: external_exports.boolean().default(false).describe("Supports file watching"), - /** - * Whether loader supports saving - */ - supportsWrite: external_exports.boolean().default(true).describe("Supports write operations"), - /** - * Whether loader supports caching - */ - supportsCache: external_exports.boolean().default(true).describe("Supports caching") -}); -var MetadataFallbackStrategySchema3 = external_exports.enum([ - "filesystem", - // Fall back to filesystem-based loading - "memory", - // Fall back to in-memory storage - "none" - // No fallback — fail immediately -]); -var MetadataManagerConfigSchema3 = external_exports.object({ - /** - * Datasource Name Reference - * References a DatasourceSchema.name (e.g. 'default'). - * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. - */ - datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), - /** - * Metadata Table Name - * The database table used for metadata storage when datasource is configured. - */ - tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), - /** - * Fallback Strategy - * Determines behavior when the primary datasource is unavailable. - */ - fallback: MetadataFallbackStrategySchema3.default("none").describe("Fallback strategy when datasource is unavailable"), - /** - * Root directory for metadata (for filesystem loaders) - */ - rootDir: external_exports.string().optional().describe("Root directory path"), - /** - * Enabled serialization formats - */ - formats: external_exports.array(MetadataFormatSchema4).default(["typescript", "json", "yaml"]).describe("Enabled formats"), - /** - * Cache configuration - */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable caching"), - ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), - maxSize: external_exports.number().int().min(0).optional().describe("Max cache size in bytes") - }).optional().describe("Cache settings"), - /** - * Watch for file changes - */ - watch: external_exports.boolean().default(false).describe("Enable file watching"), - /** - * Watch options - */ - watchOptions: external_exports.object({ - ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), - persistent: external_exports.boolean().default(true).describe("Keep process running"), - ignoreInitial: external_exports.boolean().default(true).describe("Ignore initial add events") - }).optional().describe("File watcher options"), - /** - * Validation settings - */ - validation: external_exports.object({ - strict: external_exports.boolean().default(true).describe("Strict validation"), - throwOnError: external_exports.boolean().default(true).describe("Throw on validation error") - }).optional().describe("Validation settings"), - /** - * Loader-specific options - */ - loaderOptions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Loader-specific configuration") -}); -var MetadataTypeSchema2 = external_exports.enum([ - // Data Protocol - "object", - // Business entity definition (ObjectSchema) - "field", - // Standalone field definition (FieldSchema) - "trigger", - // Data-layer event triggers (TriggerSchema) - "validation", - // Validation rules (ValidationSchema) - "hook", - // Data hooks (HookSchema) - // UI Protocol - "view", - // List/form views (ViewSchema) - "page", - // Standalone pages (PageSchema) - "dashboard", - // Dashboard layouts (DashboardSchema) - "app", - // Application shell (AppSchema) - "action", - // UI/Server actions (ActionSchema) - "report", - // Report definitions (ReportSchema) - // Automation Protocol - "flow", - // Visual logic flows (FlowSchema) - "workflow", - // State machines (WorkflowSchema) - "approval", - // Approval processes (ApprovalSchema) - // System Protocol - "datasource", - // Data connections (DatasourceSchema) - "translation", - // i18n resources (TranslationSchema) - "router", - // API routes - "function", - // Serverless functions - "service", - // Service definitions - // Security Protocol - "permission", - // Permission sets (PermissionSetSchema) - "profile", - // User profiles (ProfileSchema) - "role", - // Security roles - // AI Protocol - "agent", - // AI agent definitions (AgentSchema) - "tool", - // AI tool definitions (ToolSchema) - "skill" - // AI skill definitions (SkillSchema) -]); -var MetadataTypeRegistryEntrySchema2 = external_exports.object({ - /** Metadata type identifier (e.g., 'object', 'view') */ - type: MetadataTypeSchema2.describe("Metadata type identifier"), - /** Human-readable label */ - label: external_exports.string().describe("Display label for the metadata type"), - /** Brief description */ - description: external_exports.string().optional().describe("Description of the metadata type"), - /** - * File glob patterns for this type. - * Used to discover metadata files on disk. - * @example ["**\/*.object.ts", "**\/*.object.yml"] - */ - filePatterns: external_exports.array(external_exports.string()).describe("Glob patterns to discover files of this type"), - /** - * Whether this type supports the customization overlay system. - * When true, platform/user overlays can be applied on top of package-delivered metadata. - */ - supportsOverlay: external_exports.boolean().default(true).describe("Whether overlay customization is supported"), - /** - * Whether metadata of this type can be created at runtime via API. - * Some types (e.g., 'object') may be restricted to deployment-only. - */ - allowRuntimeCreate: external_exports.boolean().default(true).describe("Allow runtime creation via API"), - /** - * Whether this type supports versioning. - * When true, changes are tracked with version history. - */ - supportsVersioning: external_exports.boolean().default(false).describe("Whether version history is tracked"), - /** - * Priority order for loading (lower = earlier). - * Objects load before views, views before dashboards. - */ - loadOrder: external_exports.number().int().min(0).default(100).describe("Loading priority (lower = earlier)"), - /** The domain this type belongs to */ - domain: external_exports.enum(["data", "ui", "automation", "system", "security", "ai"]).describe("Protocol domain") -}); -var MetadataQuerySchema2 = external_exports.object({ - /** Filter by metadata type(s) */ - types: external_exports.array(MetadataTypeSchema2).optional().describe("Filter by metadata types"), - /** Filter by namespace(s) */ - namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), - /** Filter by package ID */ - packageId: external_exports.string().optional().describe("Filter by owning package"), - /** Full-text search across name, label, description */ - search: external_exports.string().optional().describe("Full-text search query"), - /** Filter by scope */ - scope: external_exports.enum(["system", "platform", "user"]).optional().describe("Filter by scope"), - /** Filter by state */ - state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional().describe("Filter by lifecycle state"), - /** Filter by tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), - /** Sort field */ - sortBy: external_exports.enum(["name", "type", "updatedAt", "createdAt"]).default("name").describe("Sort field"), - /** Sort direction */ - sortOrder: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction"), - /** Pagination: page number (1-based) */ - page: external_exports.number().int().min(1).default(1).describe("Page number"), - /** Pagination: items per page */ - pageSize: external_exports.number().int().min(1).max(500).default(50).describe("Items per page") -}); -var MetadataQueryResultSchema2 = external_exports.object({ - /** Matched items */ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - namespace: external_exports.string().optional().describe("Namespace"), - label: external_exports.string().optional().describe("Display label"), - scope: external_exports.enum(["system", "platform", "user"]).optional(), - state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional(), - packageId: external_exports.string().optional(), - updatedAt: external_exports.string().datetime().optional() - })).describe("Matched metadata items"), - /** Total count (for pagination) */ - total: external_exports.number().int().min(0).describe("Total matching items"), - /** Current page */ - page: external_exports.number().int().min(1).describe("Current page"), - /** Page size */ - pageSize: external_exports.number().int().min(1).describe("Page size") -}); -var MetadataEventSchema2 = external_exports.object({ - /** Event type */ - event: external_exports.enum([ - "metadata.registered", - "metadata.updated", - "metadata.unregistered", - "metadata.validated", - "metadata.deployed", - "metadata.overlay.applied", - "metadata.overlay.removed", - "metadata.imported", - "metadata.exported" - ]).describe("Event type"), - /** Metadata type */ - metadataType: MetadataTypeSchema2.describe("Metadata type"), - /** Item name */ - name: external_exports.string().describe("Metadata item name"), - /** Namespace */ - namespace: external_exports.string().optional().describe("Namespace"), - /** Package ID (if package-managed) */ - packageId: external_exports.string().optional().describe("Owning package ID"), - /** Timestamp */ - timestamp: external_exports.string().datetime().describe("Event timestamp"), - /** Actor who caused the event */ - actor: external_exports.string().optional().describe("User or system that triggered the event"), - /** Additional event-specific payload */ - payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific payload") -}); -var MetadataValidationResultSchema2 = external_exports.object({ - /** Whether validation passed */ - valid: external_exports.boolean().describe("Whether the metadata is valid"), - /** Validation errors */ - errors: external_exports.array(external_exports.object({ - path: external_exports.string().describe("JSON path to the invalid field"), - message: external_exports.string().describe("Error description"), - code: external_exports.string().optional().describe("Error code") - })).optional().describe("Validation errors"), - /** Validation warnings (non-blocking) */ - warnings: external_exports.array(external_exports.object({ - path: external_exports.string().describe("JSON path to the field"), - message: external_exports.string().describe("Warning description") - })).optional().describe("Validation warnings") -}); -var MetadataPluginConfigSchema2 = external_exports.object({ - /** - * Storage configuration. - * References MetadataManagerConfigSchema for the underlying storage backend. - */ - storage: MetadataManagerConfigSchema3.describe("Storage backend configuration"), - /** - * Default customization policies per metadata type. - * Controls what parts of metadata can be customized by admins/users. - */ - customizationPolicies: external_exports.array(CustomizationPolicySchema2).optional().describe("Default customization policies per type"), - /** - * Merge strategy for package upgrades. - */ - mergeStrategy: MergeStrategyConfigSchema2.optional().describe("Merge strategy for package upgrades"), - /** - * Additional metadata type registrations. - * Used by plugins to register custom metadata types beyond the built-in set. - */ - additionalTypes: external_exports.array(MetadataTypeRegistryEntrySchema2.omit({ type: true }).extend({ - type: external_exports.string().describe("Custom metadata type identifier") - })).optional().describe("Additional custom metadata types"), - /** - * Enable metadata change events. - * When true, the plugin emits events on every metadata change. - */ - enableEvents: external_exports.boolean().default(true).describe("Emit metadata change events"), - /** - * Enable metadata validation on write operations. - * When true, all metadata is validated against its type schema before saving. - */ - validateOnWrite: external_exports.boolean().default(true).describe("Validate metadata on write"), - /** - * Enable metadata versioning. - * When true, changes to metadata are tracked with version history. - */ - enableVersioning: external_exports.boolean().default(false).describe("Track metadata version history"), - /** - * Maximum number of metadata items to keep in memory cache. - */ - cacheMaxItems: external_exports.number().int().min(0).default(1e4).describe("Max items in memory cache") -}); -var MetadataPluginManifestSchema = external_exports.object({ - /** Plugin identifier */ - id: external_exports.literal("com.objectstack.metadata").describe("Metadata plugin ID"), - /** Plugin name */ - name: external_exports.literal("ObjectStack Metadata Service").describe("Plugin name"), - /** Plugin version */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Plugin version"), - /** Plugin type */ - type: external_exports.literal("standard").describe("Plugin type"), - /** Plugin description */ - description: external_exports.string().default("Core metadata management service for ObjectStack platform").describe("Plugin description"), - /** - * Capabilities this plugin provides. - * The kernel uses this to route metadata requests to this plugin. - */ - capabilities: external_exports.object({ - /** Supports CRUD operations on metadata */ - crud: external_exports.boolean().default(true).describe("Supports metadata CRUD"), - /** Supports metadata query/search */ - query: external_exports.boolean().default(true).describe("Supports metadata query"), - /** Supports the overlay/customization system */ - overlay: external_exports.boolean().default(true).describe("Supports customization overlays"), - /** Supports file watching for hot reload */ - watch: external_exports.boolean().default(false).describe("Supports file watching"), - /** Supports bulk import/export */ - importExport: external_exports.boolean().default(true).describe("Supports import/export"), - /** Supports metadata validation */ - validation: external_exports.boolean().default(true).describe("Supports schema validation"), - /** Supports metadata versioning */ - versioning: external_exports.boolean().default(false).describe("Supports version history"), - /** Supports metadata events */ - events: external_exports.boolean().default(true).describe("Emits metadata events") - }).describe("Plugin capabilities"), - /** Plugin configuration */ - config: MetadataPluginConfigSchema2.optional().describe("Plugin configuration") -}); -var MetadataBulkRegisterRequestSchema = external_exports.object({ - /** Items to register */ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), - namespace: external_exports.string().optional().describe("Namespace") - })).min(1).describe("Items to register"), - /** Continue on individual item failure */ - continueOnError: external_exports.boolean().default(false).describe("Continue if individual item fails"), - /** Validate items before registering */ - validate: external_exports.boolean().default(true).describe("Validate before register") -}); -var MetadataBulkResultSchema2 = external_exports.object({ - /** Total items processed */ - total: external_exports.number().int().min(0).describe("Total items processed"), - /** Successfully processed items */ - succeeded: external_exports.number().int().min(0).describe("Successfully processed"), - /** Failed items */ - failed: external_exports.number().int().min(0).describe("Failed items"), - /** Per-item error details */ - errors: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - error: external_exports.string().describe("Error message") - })).optional().describe("Per-item errors") -}); -var MetadataDependencySchema2 = external_exports.object({ - /** Source metadata type */ - sourceType: external_exports.string().describe("Dependent metadata type"), - /** Source metadata name */ - sourceName: external_exports.string().describe("Dependent metadata name"), - /** Target metadata type */ - targetType: external_exports.string().describe("Referenced metadata type"), - /** Target metadata name */ - targetName: external_exports.string().describe("Referenced metadata name"), - /** Dependency kind */ - kind: external_exports.enum(["reference", "extends", "includes", "triggers"]).describe("How the dependency is formed") -}); -var PackageStatusEnum2 = external_exports.enum([ - "installed", - // Successfully installed and enabled - "disabled", - // Installed but disabled (metadata not active) - "installing", - // Installation in progress - "upgrading", - // Upgrade in progress - "uninstalling", - // Removal in progress - "error" - // Installation or runtime error -]).describe("Package installation status"); -var InstalledPackageSchema2 = external_exports.object({ - /** - * The full package manifest (source of truth for package definition). - */ - manifest: ManifestSchema2.describe("Full package manifest"), - /** - * Current lifecycle status. - */ - status: PackageStatusEnum2.default("installed").describe("Package state: installed, disabled, installing, upgrading, uninstalling, or error"), - /** - * Whether the package is currently enabled (active). - * When disabled, the package's metadata is not loaded into the registry. - */ - enabled: external_exports.boolean().default(true).describe("Whether the package is currently enabled"), - /** - * ISO 8601 timestamp of when the package was installed. - */ - installedAt: external_exports.string().datetime().optional().describe("Installation timestamp"), - /** - * ISO 8601 timestamp of last update. - */ - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - /** - * The currently installed version string. - * Mirrors manifest.version for quick access without parsing the full manifest. - */ - installedVersion: external_exports.string().optional().describe("Currently installed version for quick access"), - /** - * The previously installed version (before last upgrade). - * Useful for rollback and upgrade tracking. - */ - previousVersion: external_exports.string().optional().describe("Version before the last upgrade"), - /** - * ISO 8601 timestamp of when the package was last enabled/disabled. - */ - statusChangedAt: external_exports.string().datetime().optional().describe("Status change timestamp"), - /** - * Error message if status is 'error'. - */ - errorMessage: external_exports.string().optional().describe("Error message when status is error"), - /** - * Configuration values set by the user for this package. - * Keys correspond to the package's `configuration.properties`. - */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided configuration settings"), - /** - * Upgrade history for this package. - * Records each version migration with status and optional log. - */ - upgradeHistory: external_exports.array(external_exports.object({ - /** Previous version before upgrade */ - fromVersion: external_exports.string().describe("Version before upgrade"), - /** New version after upgrade */ - toVersion: external_exports.string().describe("Version after upgrade"), - /** Timestamp of the upgrade */ - upgradedAt: external_exports.string().datetime().describe("Upgrade timestamp"), - /** Outcome of the upgrade */ - status: external_exports.enum(["success", "failed", "rolled_back"]).describe("Upgrade outcome"), - /** Migration log entries */ - migrationLog: external_exports.array(external_exports.string()).optional().describe("Migration step logs") - })).optional().describe("Version upgrade history"), - /** - * Namespaces registered by this package. - * Tracks which namespace prefixes are occupied by this package. - */ - registeredNamespaces: external_exports.array(external_exports.string()).optional().describe("Namespace prefixes registered by this package") -}).describe("Installed package with runtime lifecycle state"); -var NamespaceRegistryEntrySchema = external_exports.object({ - /** Namespace prefix */ - namespace: external_exports.string().describe("Namespace prefix"), - /** Package that owns this namespace */ - packageId: external_exports.string().describe("Owning package ID"), - /** Registration timestamp */ - registeredAt: external_exports.string().datetime().describe("Registration timestamp"), - /** Namespace status */ - status: external_exports.enum(["active", "disabled", "reserved"]).describe("Namespace status") -}).describe("Namespace ownership entry in the registry"); -var NamespaceConflictErrorSchema = external_exports.object({ - /** Error type discriminator */ - type: external_exports.literal("namespace_conflict").describe("Error type"), - /** Namespace that was requested */ - requestedNamespace: external_exports.string().describe("Requested namespace"), - /** ID of the package that already owns the namespace */ - conflictingPackageId: external_exports.string().describe("Conflicting package ID"), - /** Name of the conflicting package */ - conflictingPackageName: external_exports.string().describe("Conflicting package display name"), - /** Suggested alternative namespace */ - suggestion: external_exports.string().optional().describe("Suggested alternative namespace") -}).describe("Namespace collision error during installation"); -var ListPackagesRequestSchema2 = external_exports.object({ - /** Filter by status */ - status: PackageStatusEnum2.optional().describe("Filter by package status"), - /** Filter by package type */ - type: ManifestSchema2.shape.type.optional().describe("Filter by package type"), - /** Filter by enabled state */ - enabled: external_exports.boolean().optional().describe("Filter by enabled state") -}).describe("List packages request"); -var ListPackagesResponseSchema2 = external_exports.object({ - packages: external_exports.array(InstalledPackageSchema2).describe("List of installed packages"), - total: external_exports.number().describe("Total package count") -}).describe("List packages response"); -var GetPackageRequestSchema2 = external_exports.object({ - /** Package ID (reverse domain identifier from manifest) */ - id: external_exports.string().describe("Package identifier") -}).describe("Get package request"); -var GetPackageResponseSchema2 = external_exports.object({ - package: InstalledPackageSchema2.describe("Package details") -}).describe("Get package response"); -var InstallPackageRequestSchema2 = external_exports.object({ - /** The package manifest to install */ - manifest: ManifestSchema2.describe("Package manifest to install"), - /** Optional: user-provided settings at install time */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), - /** Whether to enable immediately after install (default: true) */ - enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), - /** - * Current platform version for compatibility checking. - * When provided, the system compares this against the package's - * `engine.objectstack` requirement to verify compatibility. - */ - platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification") -}).describe("Install package request"); -var InstallPackageResponseSchema2 = external_exports.object({ - package: InstalledPackageSchema2.describe("Installed package details"), - message: external_exports.string().optional().describe("Installation status message"), - /** Dependency resolution result (when dependencies were analyzed) */ - dependencyResolution: DependencyResolutionResultSchema2.optional().describe("Dependency resolution result from install analysis") -}).describe("Install package response"); -var UninstallPackageRequestSchema2 = external_exports.object({ - /** Package ID to uninstall */ - id: external_exports.string().describe("Package ID to uninstall") -}).describe("Uninstall package request"); -var UninstallPackageResponseSchema2 = external_exports.object({ - id: external_exports.string().describe("Uninstalled package ID"), - success: external_exports.boolean().describe("Whether uninstall succeeded"), - message: external_exports.string().optional().describe("Uninstall status message") -}).describe("Uninstall package response"); -var EnablePackageRequestSchema2 = external_exports.object({ - /** Package ID to enable */ - id: external_exports.string().describe("Package ID to enable") -}).describe("Enable package request"); -var EnablePackageResponseSchema2 = external_exports.object({ - package: InstalledPackageSchema2.describe("Enabled package details"), - message: external_exports.string().optional().describe("Enable status message") -}).describe("Enable package response"); -var DisablePackageRequestSchema2 = external_exports.object({ - /** Package ID to disable */ - id: external_exports.string().describe("Package ID to disable") -}).describe("Disable package request"); -var DisablePackageResponseSchema2 = external_exports.object({ - package: InstalledPackageSchema2.describe("Disabled package details"), - message: external_exports.string().optional().describe("Disable status message") -}).describe("Disable package response"); -var MetadataChangeTypeSchema2 = external_exports.enum([ - "added", - // New metadata item added in new version - "modified", - // Existing metadata item modified - "removed", - // Metadata item removed in new version - "renamed" - // Metadata item renamed -]).describe("Type of metadata change between package versions"); -var MetadataDiffItemSchema2 = external_exports.object({ - /** Metadata type (e.g. "object", "view", "flow") */ - type: external_exports.string().describe("Metadata type"), - /** Metadata name */ - name: external_exports.string().describe("Metadata name"), - /** Type of change */ - changeType: MetadataChangeTypeSchema2.describe("Category of metadata modification (added, modified, removed, or renamed)"), - /** Whether this change has potential conflicts with customizations */ - hasConflict: external_exports.boolean().default(false).describe("Whether this change may conflict with customizations"), - /** Human-readable summary of the change */ - summary: external_exports.string().optional().describe("Human-readable change summary"), - /** Previous name (for renames) */ - previousName: external_exports.string().optional().describe("Previous name if renamed") -}).describe("Single metadata change between package versions"); -var UpgradeImpactLevelSchema2 = external_exports.enum([ - "none", - // No impact, seamless upgrade - "low", - // Minor changes, no user action needed - "medium", - // Some changes that may affect workflows - "high", - // Significant changes, user review recommended - "critical" - // Breaking changes, manual intervention required -]).describe("Severity of upgrade impact"); -var UpgradePlanSchema2 = external_exports.object({ - /** Package being upgraded */ - packageId: external_exports.string().describe("Package identifier"), - /** Current installed version */ - fromVersion: external_exports.string().describe("Currently installed version"), - /** Target version to upgrade to */ - toVersion: external_exports.string().describe("Target upgrade version"), - /** Overall impact level */ - impactLevel: UpgradeImpactLevelSchema2.describe("Severity assessment from none (seamless) to critical (breaking changes)"), - /** List of all metadata changes between versions */ - changes: external_exports.array(MetadataDiffItemSchema2).describe("All metadata changes"), - /** Number of customer customizations that may be affected */ - affectedCustomizations: external_exports.number().int().min(0).default(0).describe("Count of customizations that may be affected"), - /** Whether any migration scripts need to run */ - requiresMigration: external_exports.boolean().default(false).describe("Whether data migration scripts are needed"), - /** Migration script paths (relative to package root) */ - migrationScripts: external_exports.array(external_exports.string()).optional().describe("Paths to migration scripts"), - /** Dependencies that also need upgrading */ - dependencyUpgrades: external_exports.array(external_exports.object({ - packageId: external_exports.string(), - fromVersion: external_exports.string(), - toVersion: external_exports.string() - })).optional().describe("Dependent packages that also need upgrading"), - /** Estimated upgrade duration in seconds */ - estimatedDuration: external_exports.number().int().min(0).optional().describe("Estimated upgrade duration in seconds"), - /** Human-readable summary */ - summary: external_exports.string().optional().describe("Human-readable upgrade summary") -}).describe("Upgrade analysis plan generated before execution"); -var UpgradeSnapshotSchema = external_exports.object({ - /** Snapshot ID (UUID) */ - id: external_exports.string().describe("Snapshot identifier"), - /** Package being upgraded */ - packageId: external_exports.string().describe("Package identifier"), - /** Version being upgraded from */ - fromVersion: external_exports.string().describe("Version before upgrade"), - /** Version being upgraded to */ - toVersion: external_exports.string().describe("Target upgrade version"), - /** Tenant ID */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** Complete manifest of the old package version */ - previousManifest: ManifestSchema2.describe("Complete manifest of the previous package version"), - /** - * Snapshot of all metadata records owned by this package. - * Stored as array of { type, name, metadata } tuples. - */ - metadataSnapshot: external_exports.array(external_exports.object({ - type: external_exports.string(), - name: external_exports.string(), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()) - })).describe("Snapshot of all package metadata"), - /** - * Snapshot of all customer customizations (overlays) for this package's metadata. - */ - customizationSnapshot: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Snapshot of customer customizations"), - /** When the snapshot was created */ - createdAt: external_exports.string().datetime().describe("Snapshot creation timestamp"), - /** Expiry time for snapshot cleanup */ - expiresAt: external_exports.string().datetime().optional().describe("Snapshot expiry timestamp") -}).describe("Pre-upgrade state snapshot for rollback capability"); -var UpgradePackageRequestSchema = external_exports.object({ - /** Package ID to upgrade */ - packageId: external_exports.string().describe("Package ID to upgrade"), - /** Target version (if omitted, upgrades to latest) */ - targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), - /** New manifest for the target version */ - manifest: ManifestSchema2.optional().describe("New manifest (if installing from local)"), - /** Whether to create a pre-upgrade snapshot */ - createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), - /** Merge strategy for handling customizations */ - mergeStrategy: external_exports.enum([ - "keep-custom", - "accept-incoming", - "three-way-merge" - ]).default("three-way-merge").describe("How to handle customer customizations"), - /** Whether to run in dry-run mode (preview only, no changes) */ - dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), - /** Whether to skip pre-upgrade validation */ - skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") -}).describe("Upgrade package request"); -var UpgradePhaseSchema2 = external_exports.enum([ - "pending", - // Upgrade requested but not started - "analyzing", - // Generating upgrade plan - "snapshot", - // Creating pre-upgrade snapshot - "executing", - // Applying metadata changes - "migrating", - // Running migration scripts - "validating", - // Post-upgrade validation - "completed", - // Upgrade completed successfully - "failed", - // Upgrade failed - "rolling-back", - // Rollback in progress - "rolled-back" - // Rollback completed -]).describe("Current phase of the upgrade process"); -var UpgradePackageResponseSchema = external_exports.object({ - /** Whether the upgrade was successful */ - success: external_exports.boolean().describe("Whether the upgrade succeeded"), - /** Current upgrade phase */ - phase: UpgradePhaseSchema2.describe("Current upgrade phase"), - /** The upgrade plan that was executed */ - plan: UpgradePlanSchema2.optional().describe("Upgrade plan"), - /** Snapshot ID for rollback */ - snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), - /** Merge conflicts that need manual resolution (if any) */ - conflicts: external_exports.array(external_exports.object({ - path: external_exports.string(), - baseValue: external_exports.unknown(), - incomingValue: external_exports.unknown(), - customValue: external_exports.unknown() - })).optional().describe("Unresolved merge conflicts"), - /** Error message (if failed) */ - errorMessage: external_exports.string().optional().describe("Error message if upgrade failed"), - /** Human-readable summary */ - message: external_exports.string().optional().describe("Human-readable status message") -}).describe("Upgrade package response"); -var RollbackPackageRequestSchema = external_exports.object({ - /** Package ID to rollback */ - packageId: external_exports.string().describe("Package ID to rollback"), - /** Snapshot ID to restore from */ - snapshotId: external_exports.string().describe("Snapshot ID to restore from"), - /** Whether to also rollback customizations */ - rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") -}).describe("Rollback package request"); -var RollbackPackageResponseSchema = external_exports.object({ - /** Whether the rollback was successful */ - success: external_exports.boolean().describe("Whether the rollback succeeded"), - /** Restored version */ - restoredVersion: external_exports.string().optional().describe("Version restored to"), - /** Message */ - message: external_exports.string().optional().describe("Rollback status message") -}).describe("Rollback package response"); -var PluginHealthStatusSchema = external_exports.enum([ - "healthy", - // Plugin is operating normally - "degraded", - // Plugin is operational but with reduced functionality - "unhealthy", - // Plugin has critical issues but still running - "failed", - // Plugin has failed and is not operational - "recovering", - // Plugin is in recovery process - "unknown" - // Health status cannot be determined -]).describe("Current health status of the plugin"); -var PluginHealthCheckSchema = external_exports.object({ - /** - * Health check interval in milliseconds - */ - interval: external_exports.number().int().min(1e3).default(3e4).describe("How often to perform health checks (default: 30s)"), - /** - * Timeout for health check in milliseconds - */ - timeout: external_exports.number().int().min(100).default(5e3).describe("Maximum time to wait for health check response"), - /** - * Number of consecutive failures before marking as unhealthy - */ - failureThreshold: external_exports.number().int().min(1).default(3).describe("Consecutive failures needed to mark unhealthy"), - /** - * Number of consecutive successes to recover from unhealthy state - */ - successThreshold: external_exports.number().int().min(1).default(1).describe("Consecutive successes needed to mark healthy"), - /** - * Custom health check function name or endpoint - */ - checkMethod: external_exports.string().optional().describe("Method name to call for health check"), - /** - * Enable automatic restart on failure - */ - autoRestart: external_exports.boolean().default(false).describe("Automatically restart plugin on health check failure"), - /** - * Maximum number of restart attempts - */ - maxRestartAttempts: external_exports.number().int().min(0).default(3).describe("Maximum restart attempts before giving up"), - /** - * Backoff strategy for restarts - */ - restartBackoff: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy for restart delays") -}); -var PluginHealthReportSchema = external_exports.object({ - /** - * Overall health status - */ - status: PluginHealthStatusSchema, - /** - * Timestamp of the health check - */ - timestamp: external_exports.string().datetime(), - /** - * Human-readable message about health status - */ - message: external_exports.string().optional(), - /** - * Detailed metrics - */ - metrics: external_exports.object({ - uptime: external_exports.number().describe("Plugin uptime in milliseconds"), - memoryUsage: external_exports.number().optional().describe("Memory usage in bytes"), - cpuUsage: external_exports.number().optional().describe("CPU usage percentage"), - activeConnections: external_exports.number().optional().describe("Number of active connections"), - errorRate: external_exports.number().optional().describe("Error rate (errors per minute)"), - responseTime: external_exports.number().optional().describe("Average response time in ms") - }).partial().optional(), - /** - * List of checks performed - */ - checks: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Check name"), - status: external_exports.enum(["passed", "failed", "warning"]), - message: external_exports.string().optional(), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - })).optional(), - /** - * Dependencies health - */ - dependencies: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - status: PluginHealthStatusSchema, - message: external_exports.string().optional() - })).optional() -}); -var DistributedStateConfigSchema = external_exports.object({ - /** - * Distributed cache provider - */ - provider: external_exports.enum(["redis", "etcd", "custom"]).describe("Distributed state backend provider"), - /** - * Connection URL or endpoints - */ - endpoints: external_exports.array(external_exports.string()).optional().describe("Backend connection endpoints"), - /** - * Key prefix for namespacing - */ - keyPrefix: external_exports.string().optional().describe('Prefix for all keys (e.g., "plugin:my-plugin:")'), - /** - * Time to live in seconds - */ - ttl: external_exports.number().int().min(0).optional().describe("State expiration time in seconds"), - /** - * Authentication configuration - */ - auth: external_exports.object({ - username: external_exports.string().optional(), - password: external_exports.string().optional(), - token: external_exports.string().optional(), - certificate: external_exports.string().optional() - }).optional(), - /** - * Replication settings - */ - replication: external_exports.object({ - enabled: external_exports.boolean().default(true), - minReplicas: external_exports.number().int().min(1).default(1) - }).optional(), - /** - * Custom provider configuration - */ - customConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration") -}); -var HotReloadConfigSchema = external_exports.object({ - /** - * Enable hot reload capability - */ - enabled: external_exports.boolean().default(false), - /** - * Watch file patterns for auto-reload - */ - watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns to watch for changes"), - /** - * Debounce delay before reloading (milliseconds) - */ - debounceDelay: external_exports.number().int().min(0).default(1e3).describe("Wait time after change detection before reload"), - /** - * Preserve plugin state during reload - */ - preserveState: external_exports.boolean().default(true).describe("Keep plugin state across reloads"), - /** - * State serialization strategy - */ - stateStrategy: external_exports.enum(["memory", "disk", "distributed", "none"]).default("memory").describe("How to preserve state during reload"), - /** - * Distributed state configuration (required when stateStrategy is "distributed") - */ - distributedConfig: DistributedStateConfigSchema.optional().describe("Configuration for distributed state management"), - /** - * Graceful shutdown timeout - */ - shutdownTimeout: external_exports.number().int().min(0).default(3e4).describe("Maximum time to wait for graceful shutdown"), - /** - * Pre-reload hooks - */ - beforeReload: external_exports.array(external_exports.string()).optional().describe("Hook names to call before reload"), - /** - * Post-reload hooks - */ - afterReload: external_exports.array(external_exports.string()).optional().describe("Hook names to call after reload") -}); -var GracefulDegradationSchema = external_exports.object({ - /** - * Enable graceful degradation - */ - enabled: external_exports.boolean().default(true), - /** - * Fallback mode when dependencies fail - */ - fallbackMode: external_exports.enum([ - "minimal", - // Provide minimal functionality - "cached", - // Use cached data - "readonly", - // Allow read-only operations - "offline", - // Offline mode with local data - "disabled" - // Disable plugin functionality - ]).default("minimal"), - /** - * Critical dependencies that must be available - */ - criticalDependencies: external_exports.array(external_exports.string()).optional().describe("Plugin IDs that are required for operation"), - /** - * Optional dependencies that can fail - */ - optionalDependencies: external_exports.array(external_exports.string()).optional().describe("Plugin IDs that are nice to have but not required"), - /** - * Feature flags for degraded mode - */ - degradedFeatures: external_exports.array(external_exports.object({ - feature: external_exports.string().describe("Feature name"), - enabled: external_exports.boolean().describe("Whether feature is available in degraded mode"), - reason: external_exports.string().optional() - })).optional(), - /** - * Automatic recovery attempts - */ - autoRecovery: external_exports.object({ - enabled: external_exports.boolean().default(true), - retryInterval: external_exports.number().int().min(1e3).default(6e4).describe("Interval between recovery attempts (ms)"), - maxAttempts: external_exports.number().int().min(0).default(5).describe("Maximum recovery attempts before giving up") - }).optional() -}); -var PluginUpdateStrategySchema = external_exports.object({ - /** - * Update mode - */ - mode: external_exports.enum([ - "manual", - // Manual updates only - "automatic", - // Automatic updates - "scheduled", - // Scheduled update windows - "rolling" - // Rolling updates with zero downtime - ]).default("manual"), - /** - * Version constraints for automatic updates - */ - autoUpdateConstraints: external_exports.object({ - major: external_exports.boolean().default(false).describe("Allow major version updates"), - minor: external_exports.boolean().default(true).describe("Allow minor version updates"), - patch: external_exports.boolean().default(true).describe("Allow patch version updates") - }).optional(), - /** - * Update schedule (for scheduled mode) - */ - schedule: external_exports.object({ - /** - * Cron expression for update window - */ - cron: external_exports.string().optional(), - /** - * Timezone for schedule - */ - timezone: external_exports.string().default("UTC"), - /** - * Maintenance window duration in minutes - */ - maintenanceWindow: external_exports.number().int().min(1).default(60) - }).optional(), - /** - * Rollback configuration - */ - rollback: external_exports.object({ - enabled: external_exports.boolean().default(true), - /** - * Automatic rollback on failure - */ - automatic: external_exports.boolean().default(true), - /** - * Keep N previous versions for rollback - */ - keepVersions: external_exports.number().int().min(1).default(3), - /** - * Rollback timeout in milliseconds - */ - timeout: external_exports.number().int().min(1e3).default(3e4) - }).optional(), - /** - * Pre-update validation - */ - validation: external_exports.object({ - /** - * Run compatibility checks before update - */ - checkCompatibility: external_exports.boolean().default(true), - /** - * Run tests before applying update - */ - runTests: external_exports.boolean().default(false), - /** - * Test suite to run - */ - testSuite: external_exports.string().optional() - }).optional() -}); -var PluginStateSnapshotSchema = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Version at time of snapshot - */ - version: external_exports.string(), - /** - * Snapshot timestamp - */ - timestamp: external_exports.string().datetime(), - /** - * Serialized state data - */ - state: external_exports.record(external_exports.string(), external_exports.unknown()), - /** - * State metadata - */ - metadata: external_exports.object({ - checksum: external_exports.string().optional().describe("State checksum for verification"), - compressed: external_exports.boolean().default(false), - encryption: external_exports.string().optional().describe("Encryption algorithm if encrypted") - }).optional() -}); -var AdvancedPluginLifecycleConfigSchema = external_exports.object({ - /** - * Health monitoring configuration - */ - health: PluginHealthCheckSchema.optional(), - /** - * Hot reload configuration - */ - hotReload: HotReloadConfigSchema.optional(), - /** - * Graceful degradation configuration - */ - degradation: GracefulDegradationSchema.optional(), - /** - * Update strategy - */ - updates: PluginUpdateStrategySchema.optional(), - /** - * Resource limits - */ - resources: external_exports.object({ - maxMemory: external_exports.number().int().optional().describe("Maximum memory in bytes"), - maxCpu: external_exports.number().min(0).max(100).optional().describe("Maximum CPU percentage"), - maxConnections: external_exports.number().int().optional().describe("Maximum concurrent connections"), - timeout: external_exports.number().int().optional().describe("Operation timeout in milliseconds") - }).optional(), - /** - * Monitoring and observability - */ - observability: external_exports.object({ - enableMetrics: external_exports.boolean().default(true), - enableTracing: external_exports.boolean().default(true), - enableProfiling: external_exports.boolean().default(false), - metricsInterval: external_exports.number().int().min(1e3).default(6e4).describe("Metrics collection interval in ms") - }).optional() -}); -var EventPhaseSchema = external_exports.enum(["init", "start", "destroy"]).describe("Plugin lifecycle phase"); -var PluginEventBaseSchema = external_exports.object({ - /** - * Plugin name - */ - pluginName: external_exports.string().describe("Name of the plugin"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds when event occurred") -}); -var PluginRegisteredEventSchema = PluginEventBaseSchema.extend({ - /** - * Plugin version (optional) - */ - version: external_exports.string().optional().describe("Plugin version") -}); -var PluginLifecyclePhaseEventSchema = PluginEventBaseSchema.extend({ - /** - * Duration of the phase (milliseconds) - */ - duration: external_exports.number().min(0).optional().describe("Duration of the lifecycle phase in milliseconds"), - /** - * Lifecycle phase - */ - phase: EventPhaseSchema.optional().describe("Lifecycle phase") -}); -var PluginErrorEventSchema = PluginEventBaseSchema.extend({ - /** - * Error object - */ - error: external_exports.object({ - name: external_exports.string().describe("Error class name"), - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Stack trace"), - code: external_exports.string().optional().describe("Error code") - }).describe("Serializable error representation"), - /** - * Lifecycle phase where error occurred - */ - phase: EventPhaseSchema.describe("Lifecycle phase where error occurred"), - /** - * Error message (for serialization) - */ - errorMessage: external_exports.string().optional().describe("Error message"), - /** - * Error stack trace (for debugging) - */ - errorStack: external_exports.string().optional().describe("Error stack trace") -}); -var ServiceRegisteredEventSchema = external_exports.object({ - /** - * Service name - */ - serviceName: external_exports.string().describe("Name of the registered service"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), - /** - * Service type (optional) - */ - serviceType: external_exports.string().optional().describe("Type or interface name of the service") -}); -var ServiceUnregisteredEventSchema = external_exports.object({ - /** - * Service name - */ - serviceName: external_exports.string().describe("Name of the unregistered service"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds") -}); -var HookRegisteredEventSchema = external_exports.object({ - /** - * Hook name - */ - hookName: external_exports.string().describe("Name of the hook"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), - /** - * Number of handlers registered for this hook - */ - handlerCount: external_exports.number().int().min(0).describe("Number of handlers registered for this hook") -}); -var HookTriggeredEventSchema = external_exports.object({ - /** - * Hook name - */ - hookName: external_exports.string().describe("Name of the hook"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), - /** - * Arguments passed to the hook - */ - args: external_exports.array(external_exports.unknown()).describe("Arguments passed to the hook handlers"), - /** - * Number of handlers that will handle this event - */ - handlerCount: external_exports.number().int().min(0).optional().describe("Number of handlers that will handle this event") -}); -var KernelEventBaseSchema = external_exports.object({ - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds") -}); -var KernelReadyEventSchema = KernelEventBaseSchema.extend({ - /** - * Total initialization duration (milliseconds) - */ - duration: external_exports.number().min(0).optional().describe("Total initialization duration in milliseconds"), - /** - * Number of plugins initialized - */ - pluginCount: external_exports.number().int().min(0).optional().describe("Number of plugins initialized") -}); -var KernelShutdownEventSchema = KernelEventBaseSchema.extend({ - /** - * Shutdown reason (optional) - */ - reason: external_exports.string().optional().describe("Reason for kernel shutdown") -}); -var PluginLifecycleEventType = external_exports.enum([ - "kernel:ready", - "kernel:shutdown", - "kernel:before-init", - "kernel:after-init", - "plugin:registered", - "plugin:before-init", - "plugin:init", - "plugin:after-init", - "plugin:before-start", - "plugin:started", - "plugin:after-start", - "plugin:before-destroy", - "plugin:destroyed", - "plugin:after-destroy", - "plugin:error", - "service:registered", - "service:unregistered", - "hook:registered", - "hook:triggered" -]).describe("Plugin lifecycle event type"); -var DynamicPluginOperationSchema = external_exports.enum([ - "load", - // Load and initialize a plugin at runtime - "unload", - // Gracefully unload a running plugin - "reload", - // Unload then load (e.g., version upgrade) - "enable", - // Enable a loaded but disabled plugin - "disable" - // Disable a running plugin without unloading -]).describe("Runtime plugin operation type"); -var PluginSourceSchema = external_exports.object({ - /** - * Source type - */ - type: external_exports.enum([ - "npm", - // npm registry package - "local", - // Local filesystem path - "url", - // Remote URL (tarball or module) - "registry", - // ObjectStack plugin registry - "git" - // Git repository - ]).describe("Plugin source type"), - /** - * Source location (package name, path, URL, or git repo) - */ - location: external_exports.string().describe("Package name, file path, URL, or git repository"), - /** - * Version constraint (semver range) - */ - version: external_exports.string().optional().describe('Semver version range (e.g., "^1.0.0")'), - /** - * Integrity hash for verification - */ - integrity: external_exports.string().optional().describe('Subresource Integrity hash (e.g., "sha384-...")') -}).describe("Plugin source location for dynamic resolution"); -var ActivationEventSchema = external_exports.object({ - /** - * Event type - */ - type: external_exports.enum([ - "onCommand", - // Activate when a specific command is executed - "onRoute", - // Activate when a URL route is matched - "onObject", - // Activate when a specific object type is accessed - "onEvent", - // Activate when a system event fires - "onService", - // Activate when a service is requested - "onSchedule", - // Activate on a cron schedule - "onStartup" - // Activate immediately on kernel startup - ]).describe("Trigger type for lazy activation"), - /** - * Pattern to match (command name, route glob, object name, event pattern, etc.) - */ - pattern: external_exports.string().describe("Match pattern for the activation trigger") -}).describe("Lazy activation trigger for a dynamic plugin"); -var DynamicLoadRequestSchema = external_exports.object({ - /** - * Plugin identifier to load - */ - pluginId: external_exports.string().describe("Unique plugin identifier"), - /** - * Plugin source - */ - source: PluginSourceSchema, - /** - * Activation events (if omitted, plugin activates immediately) - */ - activationEvents: external_exports.array(ActivationEventSchema).optional().describe("Lazy activation triggers; if omitted plugin starts immediately"), - /** - * Configuration overrides for the plugin - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Runtime configuration overrides"), - /** - * Loading priority (lower = higher priority) - */ - priority: external_exports.number().int().min(0).default(100).describe("Loading priority (lower is higher)"), - /** - * Whether to enable sandboxing for this dynamically loaded plugin - */ - sandbox: external_exports.boolean().default(false).describe("Run in an isolated sandbox"), - /** - * Timeout for the load operation in milliseconds - */ - timeout: external_exports.number().int().min(1e3).default(6e4).describe("Maximum time to complete loading in ms") -}).describe("Request to dynamically load a plugin at runtime"); -var DynamicUnloadRequestSchema = external_exports.object({ - /** - * Plugin identifier to unload - */ - pluginId: external_exports.string().describe("Plugin to unload"), - /** - * Unload strategy - */ - strategy: external_exports.enum([ - "graceful", - // Wait for in-flight requests, then unload - "forceful", - // Unload immediately, cancel pending work - "drain" - // Stop accepting new work, finish existing, then unload - ]).default("graceful").describe("How to handle in-flight work during unload"), - /** - * Timeout for the unload operation in milliseconds - */ - timeout: external_exports.number().int().min(1e3).default(3e4).describe("Maximum time to complete unloading in ms"), - /** - * Whether to remove cached artifacts - */ - cleanupCache: external_exports.boolean().default(false).describe("Remove cached code and assets after unload"), - /** - * Action for dependents: plugins that depend on this one - */ - dependentAction: external_exports.enum([ - "cascade", - // Also unload dependent plugins - "warn", - // Warn about dependents but proceed - "block" - // Block unload if dependents exist - ]).default("block").describe("How to handle plugins that depend on this one") -}).describe("Request to dynamically unload a plugin at runtime"); -var DynamicPluginResultSchema = external_exports.object({ - /** - * Whether the operation succeeded - */ - success: external_exports.boolean(), - /** - * The operation that was performed - */ - operation: DynamicPluginOperationSchema, - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Operation duration in milliseconds - */ - durationMs: external_exports.number().int().min(0).optional(), - /** - * Resulting plugin version (for load/reload) - */ - version: external_exports.string().optional(), - /** - * Error details if operation failed - */ - error: external_exports.object({ - code: external_exports.string().describe("Machine-readable error code"), - message: external_exports.string().describe("Human-readable error message"), - details: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional(), - /** - * Warnings (e.g., dependents affected) - */ - warnings: external_exports.array(external_exports.string()).optional() -}).describe("Result of a dynamic plugin operation"); -var PluginDiscoverySourceSchema = external_exports.object({ - /** - * Discovery source type - */ - type: external_exports.enum([ - "registry", - // ObjectStack plugin registry API - "npm", - // npm registry search - "directory", - // Local filesystem directory scan - "url" - // Remote manifest URL - ]).describe("Discovery source type"), - /** - * Source endpoint or path - */ - endpoint: external_exports.string().describe("Registry URL, directory path, or manifest URL"), - /** - * Polling interval in milliseconds (0 = manual only) - */ - pollInterval: external_exports.number().int().min(0).default(0).describe("How often to re-scan for new plugins (0 = manual)"), - /** - * Filter criteria for discovered plugins - */ - filter: external_exports.object({ - /** - * Only discover plugins matching these tags - */ - tags: external_exports.array(external_exports.string()).optional(), - /** - * Only discover plugins from these vendors - */ - vendors: external_exports.array(external_exports.string()).optional(), - /** - * Minimum trust level - */ - minTrustLevel: external_exports.enum(["verified", "trusted", "community", "untrusted"]).optional() - }).optional() -}).describe("Source for runtime plugin discovery"); -var PluginDiscoveryConfigSchema = external_exports.object({ - /** - * Enable runtime plugin discovery - */ - enabled: external_exports.boolean().default(false), - /** - * Discovery sources - */ - sources: external_exports.array(PluginDiscoverySourceSchema).default([]), - /** - * Auto-load discovered plugins matching criteria - */ - autoLoad: external_exports.boolean().default(false).describe("Automatically load newly discovered plugins"), - /** - * Require approval before loading discovered plugins - */ - requireApproval: external_exports.boolean().default(true).describe("Require admin approval before loading discovered plugins") -}).describe("Runtime plugin discovery configuration"); -var DynamicLoadingConfigSchema = external_exports.object({ - /** - * Enable dynamic loading/unloading at runtime - */ - enabled: external_exports.boolean().default(false).describe("Enable runtime load/unload of plugins"), - /** - * Maximum number of dynamically loaded plugins - */ - maxDynamicPlugins: external_exports.number().int().min(1).default(50).describe("Upper limit on runtime-loaded plugins"), - /** - * Plugin discovery configuration - */ - discovery: PluginDiscoveryConfigSchema.optional(), - /** - * Default sandbox policy for dynamically loaded plugins - */ - defaultSandbox: external_exports.boolean().default(true).describe("Sandbox dynamically loaded plugins by default"), - /** - * Allowed plugin sources (empty = all allowed) - */ - allowedSources: external_exports.array(external_exports.enum(["npm", "local", "url", "registry", "git"])).optional().describe("Restrict which source types are permitted"), - /** - * Require integrity verification for remote plugins - */ - requireIntegrity: external_exports.boolean().default(true).describe("Require integrity hash verification for remote sources"), - /** - * Global timeout for dynamic operations in milliseconds - */ - operationTimeout: external_exports.number().int().min(1e3).default(6e4).describe("Default timeout for load/unload operations in ms") -}).describe("Dynamic plugin loading subsystem configuration"); -var PermissionScopeSchema = external_exports.enum([ - "global", - // Applies to entire system - "tenant", - // Applies to specific tenant - "user", - // Applies to specific user - "resource", - // Applies to specific resource - "plugin" - // Applies within plugin boundaries -]).describe("Scope of permission application"); -var PermissionActionSchema = external_exports.enum([ - "create", - // Create new resources - "read", - // Read existing resources - "update", - // Update existing resources - "delete", - // Delete resources - "execute", - // Execute operations/functions - "manage", - // Full management rights - "configure", - // Configuration changes - "share", - // Share with others - "export", - // Export data - "import", - // Import data - "admin" - // Administrative access -]).describe("Type of action being permitted"); -var ResourceTypeSchema = external_exports.enum([ - "data.object", - // ObjectQL objects - "data.record", - // Individual records - "data.field", - // Specific fields - "ui.view", - // UI views - "ui.dashboard", - // Dashboards - "ui.report", - // Reports - "system.config", - // System configuration - "system.plugin", - // Other plugins - "system.api", - // API endpoints - "system.service", - // System services - "storage.file", - // File storage - "storage.database", - // Database access - "network.http", - // HTTP requests - "network.websocket", - // WebSocket connections - "process.spawn", - // Process spawning - "process.env" - // Environment variables -]).describe("Type of resource being accessed"); -var PermissionSchema = external_exports.object({ - /** - * Permission identifier - */ - id: external_exports.string().describe("Unique permission identifier"), - /** - * Resource type - */ - resource: ResourceTypeSchema, - /** - * Allowed actions - */ - actions: external_exports.array(PermissionActionSchema), - /** - * Permission scope - */ - scope: PermissionScopeSchema.default("plugin"), - /** - * Resource filter - */ - filter: external_exports.object({ - /** - * Specific resource IDs - */ - resourceIds: external_exports.array(external_exports.string()).optional(), - /** - * Filter condition - */ - condition: external_exports.string().optional().describe("Filter expression (e.g., owner = currentUser)"), - /** - * Field-level access - */ - fields: external_exports.array(external_exports.string()).optional().describe("Allowed fields for data resources") - }).optional(), - /** - * Human-readable description - */ - description: external_exports.string(), - /** - * Whether this permission is required or optional - */ - required: external_exports.boolean().default(true), - /** - * Justification for permission - */ - justification: external_exports.string().optional().describe("Why this permission is needed") -}); -var PermissionSetSchema = external_exports.object({ - /** - * All permissions required by plugin - */ - permissions: external_exports.array(PermissionSchema), - /** - * Permission groups for easier management - */ - groups: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Group name"), - description: external_exports.string(), - permissions: external_exports.array(external_exports.string()).describe("Permission IDs in this group") - })).optional(), - /** - * Default grant strategy - */ - defaultGrant: external_exports.enum([ - "prompt", - // Always prompt user - "allow", - // Allow by default - "deny", - // Deny by default - "inherit" - // Inherit from parent - ]).default("prompt") -}); -var RuntimeConfigSchema = external_exports.object({ - /** - * Runtime engine type - */ - engine: external_exports.enum([ - "v8-isolate", - // V8 isolate-based isolation (lightweight, fast) - "wasm", - // WebAssembly-based isolation (secure, portable) - "container", - // Container-based isolation (Docker, podman) - "process" - // Process-based isolation (traditional) - ]).default("v8-isolate").describe("Execution environment engine"), - /** - * Engine-specific configuration - */ - engineConfig: external_exports.object({ - /** - * WASM-specific settings (when engine is "wasm") - */ - wasm: external_exports.object({ - /** - * Maximum memory pages (64KB per page) - */ - maxMemoryPages: external_exports.number().int().min(1).max(65536).optional().describe("Maximum WASM memory pages (64KB each)"), - /** - * Instruction execution limit - */ - instructionLimit: external_exports.number().int().min(1).optional().describe("Maximum instructions before timeout"), - /** - * Enable SIMD instructions - */ - enableSimd: external_exports.boolean().default(false).describe("Enable WebAssembly SIMD support"), - /** - * Enable threads - */ - enableThreads: external_exports.boolean().default(false).describe("Enable WebAssembly threads"), - /** - * Enable bulk memory operations - */ - enableBulkMemory: external_exports.boolean().default(true).describe("Enable bulk memory operations") - }).optional(), - /** - * Container-specific settings (when engine is "container") - */ - container: external_exports.object({ - /** - * Container image - */ - image: external_exports.string().optional().describe("Container image to use"), - /** - * Container runtime - */ - runtime: external_exports.enum(["docker", "podman", "containerd"]).default("docker"), - /** - * Resource limits - */ - resources: external_exports.object({ - cpuLimit: external_exports.string().optional().describe('CPU limit (e.g., "0.5", "2")'), - memoryLimit: external_exports.string().optional().describe('Memory limit (e.g., "512m", "1g")') - }).optional(), - /** - * Network mode - */ - networkMode: external_exports.enum(["none", "bridge", "host"]).default("bridge") - }).optional(), - /** - * V8 Isolate-specific settings (when engine is "v8-isolate") - */ - v8Isolate: external_exports.object({ - /** - * Heap size limit in MB - */ - heapSizeMb: external_exports.number().int().min(1).optional(), - /** - * Enable snapshot - */ - enableSnapshot: external_exports.boolean().default(true) - }).optional() - }).optional(), - /** - * General resource limits (applies to all engines) - */ - resourceLimits: external_exports.object({ - /** - * Maximum memory in bytes - */ - maxMemory: external_exports.number().int().optional().describe("Maximum memory allocation"), - /** - * Maximum CPU percentage - */ - maxCpu: external_exports.number().min(0).max(100).optional().describe("Maximum CPU usage percentage"), - /** - * Execution timeout in milliseconds - */ - timeout: external_exports.number().int().min(0).optional().describe("Maximum execution time") - }).optional() -}); -var SandboxConfigSchema = external_exports.object({ - /** - * Enable sandboxing - */ - enabled: external_exports.boolean().default(true), - /** - * Sandboxing level - */ - level: external_exports.enum([ - "none", - // No sandboxing - "minimal", - // Basic isolation - "standard", - // Standard sandboxing - "strict", - // Strict isolation - "paranoid" - // Maximum isolation - ]).default("standard"), - /** - * Runtime environment configuration - */ - runtime: RuntimeConfigSchema.optional().describe("Execution environment and isolation settings"), - /** - * File system access - */ - filesystem: external_exports.object({ - mode: external_exports.enum(["none", "readonly", "restricted", "full"]).default("restricted"), - allowedPaths: external_exports.array(external_exports.string()).optional().describe("Whitelisted paths"), - deniedPaths: external_exports.array(external_exports.string()).optional().describe("Blacklisted paths"), - maxFileSize: external_exports.number().int().optional().describe("Maximum file size in bytes") - }).optional(), - /** - * Network access - */ - network: external_exports.object({ - mode: external_exports.enum(["none", "local", "restricted", "full"]).default("restricted"), - allowedHosts: external_exports.array(external_exports.string()).optional().describe("Whitelisted hosts"), - deniedHosts: external_exports.array(external_exports.string()).optional().describe("Blacklisted hosts"), - allowedPorts: external_exports.array(external_exports.number()).optional().describe("Allowed port numbers"), - maxConnections: external_exports.number().int().optional() - }).optional(), - /** - * Process execution - */ - process: external_exports.object({ - allowSpawn: external_exports.boolean().default(false).describe("Allow spawning child processes"), - allowedCommands: external_exports.array(external_exports.string()).optional().describe("Whitelisted commands"), - timeout: external_exports.number().int().optional().describe("Process timeout in ms") - }).optional(), - /** - * Memory limits - */ - memory: external_exports.object({ - maxHeap: external_exports.number().int().optional().describe("Maximum heap size in bytes"), - maxStack: external_exports.number().int().optional().describe("Maximum stack size in bytes") - }).optional(), - /** - * CPU limits - */ - cpu: external_exports.object({ - maxCpuPercent: external_exports.number().min(0).max(100).optional(), - maxThreads: external_exports.number().int().optional() - }).optional(), - /** - * Environment variables - */ - environment: external_exports.object({ - mode: external_exports.enum(["none", "readonly", "restricted", "full"]).default("readonly"), - allowedVars: external_exports.array(external_exports.string()).optional(), - deniedVars: external_exports.array(external_exports.string()).optional() - }).optional() -}); -var KernelSecurityVulnerabilitySchema = external_exports.object({ - /** - * CVE identifier - */ - cve: external_exports.string().optional(), - /** - * Vulnerability identifier - */ - id: external_exports.string(), - /** - * Severity level - */ - severity: external_exports.enum(["critical", "high", "medium", "low", "info"]), - /** - * Category (e.g., SAST, DAST, Dependency) - */ - category: external_exports.string().optional(), - /** - * Title - */ - title: external_exports.string(), - /** - * Location of the vulnerability - */ - location: external_exports.string().optional(), - /** - * Remediation steps - */ - remediation: external_exports.string().optional(), - /** - * Description - */ - description: external_exports.string(), - /** - * Affected versions - */ - affectedVersions: external_exports.array(external_exports.string()), - /** - * Fixed in versions - */ - fixedIn: external_exports.array(external_exports.string()).optional(), - /** - * CVSS score - */ - cvssScore: external_exports.number().min(0).max(10).optional(), - /** - * Exploit availability - */ - exploitAvailable: external_exports.boolean().default(false), - /** - * Patch available - */ - patchAvailable: external_exports.boolean().default(false), - /** - * Workaround - */ - workaround: external_exports.string().optional(), - /** - * References - */ - references: external_exports.array(external_exports.string()).optional(), - /** - * Discovered date - */ - discoveredDate: external_exports.string().datetime().optional(), - /** - * Published date - */ - publishedDate: external_exports.string().datetime().optional() -}); -var KernelSecurityScanResultSchema = external_exports.object({ - /** - * Scan timestamp - */ - timestamp: external_exports.string().datetime(), - /** - * Scanner information - */ - scanner: external_exports.object({ - name: external_exports.string(), - version: external_exports.string() - }), - /** - * Overall status - */ - status: external_exports.enum(["passed", "failed", "warning"]), - /** - * Vulnerabilities found - */ - vulnerabilities: external_exports.array(KernelSecurityVulnerabilitySchema).optional(), - /** - * Code quality issues - */ - codeIssues: external_exports.array(external_exports.object({ - severity: external_exports.enum(["error", "warning", "info"]), - type: external_exports.string().describe("Issue type (e.g., sql-injection, xss)"), - file: external_exports.string(), - line: external_exports.number().int().optional(), - message: external_exports.string(), - suggestion: external_exports.string().optional() - })).optional(), - /** - * Dependency vulnerabilities - */ - dependencyVulnerabilities: external_exports.array(external_exports.object({ - package: external_exports.string(), - version: external_exports.string(), - vulnerability: KernelSecurityVulnerabilitySchema - })).optional(), - /** - * License compliance - */ - licenseCompliance: external_exports.object({ - status: external_exports.enum(["compliant", "non-compliant", "unknown"]), - issues: external_exports.array(external_exports.object({ - package: external_exports.string(), - license: external_exports.string(), - reason: external_exports.string() - })).optional() - }).optional(), - /** - * Summary statistics - */ - summary: external_exports.object({ - totalVulnerabilities: external_exports.number().int(), - criticalCount: external_exports.number().int(), - highCount: external_exports.number().int(), - mediumCount: external_exports.number().int(), - lowCount: external_exports.number().int(), - infoCount: external_exports.number().int() - }) -}); -var KernelSecurityPolicySchema = external_exports.object({ - /** - * Content Security Policy - */ - csp: external_exports.object({ - directives: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional(), - reportOnly: external_exports.boolean().default(false) - }).optional(), - /** - * CORS policy - */ - cors: external_exports.object({ - allowedOrigins: external_exports.array(external_exports.string()), - allowedMethods: external_exports.array(external_exports.string()), - allowedHeaders: external_exports.array(external_exports.string()), - allowCredentials: external_exports.boolean().default(false), - maxAge: external_exports.number().int().optional() - }).optional(), - /** - * Rate limiting - */ - rateLimit: external_exports.object({ - enabled: external_exports.boolean().default(true), - maxRequests: external_exports.number().int(), - windowMs: external_exports.number().int().describe("Time window in milliseconds"), - strategy: external_exports.enum(["fixed", "sliding", "token-bucket"]).default("sliding") - }).optional(), - /** - * Authentication requirements - */ - authentication: external_exports.object({ - required: external_exports.boolean().default(true), - methods: external_exports.array(external_exports.enum(["jwt", "oauth2", "api-key", "session", "certificate"])), - tokenExpiration: external_exports.number().int().optional().describe("Token expiration in seconds") - }).optional(), - /** - * Encryption requirements - */ - encryption: external_exports.object({ - dataAtRest: external_exports.boolean().default(false).describe("Encrypt data at rest"), - dataInTransit: external_exports.boolean().default(true).describe("Enforce HTTPS/TLS"), - algorithm: external_exports.string().optional().describe("Encryption algorithm"), - minKeyLength: external_exports.number().int().optional().describe("Minimum key length in bits") - }).optional(), - /** - * Audit logging - */ - auditLog: external_exports.object({ - enabled: external_exports.boolean().default(true), - events: external_exports.array(external_exports.string()).optional().describe("Events to log"), - retention: external_exports.number().int().optional().describe("Log retention in days") - }).optional() -}); -var PluginTrustLevelSchema = external_exports.enum([ - "verified", - // Official/verified plugin - "trusted", - // Trusted third-party - "community", - // Community plugin - "untrusted", - // Unverified plugin - "blocked" - // Blocked/malicious -]).describe("Trust level of the plugin"); -var PluginSecurityManifestSchema = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Trust level - */ - trustLevel: PluginTrustLevelSchema, - /** - * Required permissions - */ - permissions: PermissionSetSchema, - /** - * Sandbox configuration - */ - sandbox: SandboxConfigSchema, - /** - * Security policy - */ - policy: KernelSecurityPolicySchema.optional(), - /** - * Security scan results - */ - scanResults: external_exports.array(KernelSecurityScanResultSchema).optional(), - /** - * Known vulnerabilities - */ - vulnerabilities: external_exports.array(KernelSecurityVulnerabilitySchema).optional(), - /** - * Code signing - */ - codeSigning: external_exports.object({ - signed: external_exports.boolean(), - signature: external_exports.string().optional(), - certificate: external_exports.string().optional(), - algorithm: external_exports.string().optional(), - timestamp: external_exports.string().datetime().optional() - }).optional(), - /** - * Security certifications - */ - certifications: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Certification name (e.g., SOC 2, ISO 27001)"), - issuer: external_exports.string(), - issuedDate: external_exports.string().datetime(), - expiryDate: external_exports.string().datetime().optional(), - certificateUrl: external_exports.string().url().optional() - })).optional(), - /** - * Security contact - */ - securityContact: external_exports.object({ - email: external_exports.string().email().optional(), - url: external_exports.string().url().optional(), - pgpKey: external_exports.string().optional() - }).optional(), - /** - * Vulnerability disclosure policy - */ - vulnerabilityDisclosure: external_exports.object({ - policyUrl: external_exports.string().url().optional(), - responseTime: external_exports.number().int().optional().describe("Expected response time in hours"), - bugBounty: external_exports.boolean().default(false) - }).optional() -}); -var SNAKE_CASE_REGEX = /^[a-z][a-z0-9_]*$/; -var OpsFilePathSchema = external_exports.string().describe("Validates a file path against OPS naming conventions").superRefine((path3, ctx) => { - if (!path3.startsWith("src/")) { - return; - } - const parts = path3.split("/"); - if (parts.length > 2) { - const domainDir = parts[1]; - if (!SNAKE_CASE_REGEX.test(domainDir)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Domain directory '${domainDir}' must be lowercase snake_case` - }); - } - } - const filename = parts[parts.length - 1]; - if (filename === "index.ts" || filename === "main.ts") return; - if (!SNAKE_CASE_REGEX.test(filename.split(".")[0])) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Filename '${filename}' base name must be lowercase snake_case` - }); - } -}); -var OpsDomainModuleSchema = external_exports.object({ - name: external_exports.string().regex(SNAKE_CASE_REGEX).describe("Module name (snake_case)"), - files: external_exports.array(external_exports.string()).describe("List of files in this module"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") -}).describe("Scanned domain module representing a plugin folder").superRefine((module, ctx) => { - if (!module.files.includes("index.ts")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Module '${module.name}' is missing an 'index.ts' entry point.` - }); - } -}); -var OpsPluginStructureSchema = external_exports.object({ - root: external_exports.string().describe("Root directory path of the plugin project"), - files: external_exports.array(external_exports.string()).describe("List of all file paths relative to root"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") -}).describe("Full plugin project layout validated against OPS conventions").superRefine((project, ctx) => { - if (!project.files.includes("objectstack.config.ts")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "Missing 'objectstack.config.ts' configuration file." - }); - } - project.files.filter((f) => f.startsWith("src/")).forEach((file2) => { - const result = OpsFilePathSchema.safeParse(file2); - if (!result.success) { - result.error.issues.forEach((issue2) => { - ctx.addIssue({ ...issue2, path: [file2] }); - }); - } - }); -}); -var ValidationErrorSchema = external_exports.object({ - /** - * Field that failed validation - */ - field: external_exports.string().describe("Field name that failed validation"), - /** - * Human-readable error message - */ - message: external_exports.string().describe("Human-readable error message"), - /** - * Machine-readable error code (optional) - */ - code: external_exports.string().optional().describe("Machine-readable error code") -}); -var ValidationWarningSchema = external_exports.object({ - /** - * Field with warning - */ - field: external_exports.string().describe("Field name with warning"), - /** - * Human-readable warning message - */ - message: external_exports.string().describe("Human-readable warning message"), - /** - * Machine-readable warning code (optional) - */ - code: external_exports.string().optional().describe("Machine-readable warning code") -}); -var ValidationResultSchema = external_exports.object({ - /** - * Whether validation passed - */ - valid: external_exports.boolean().describe("Whether the plugin passed validation"), - /** - * Validation errors (if any) - */ - errors: external_exports.array(ValidationErrorSchema).optional().describe("Validation errors"), - /** - * Validation warnings (non-fatal issues) - */ - warnings: external_exports.array(ValidationWarningSchema).optional().describe("Validation warnings") -}); -var PluginMetadataSchema = external_exports.object({ - /** - * Unique plugin identifier (snake_case) - */ - name: external_exports.string().min(1).describe("Unique plugin identifier"), - /** - * Plugin version (semver) - */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic version (e.g., 1.0.0)"), - /** - * Plugin dependencies (array of plugin names) - */ - dependencies: external_exports.array(external_exports.string()).optional().describe("Array of plugin names this plugin depends on"), - /** - * Plugin signature for cryptographic verification (optional) - */ - signature: external_exports.string().optional().describe("Cryptographic signature for plugin verification") - /** - * Additional plugin metadata - */ -}).passthrough().describe("Plugin metadata for validation"); -var SemanticVersionSchema = external_exports.object({ - major: external_exports.number().int().min(0).describe("Major version (breaking changes)"), - minor: external_exports.number().int().min(0).describe("Minor version (backward compatible features)"), - patch: external_exports.number().int().min(0).describe("Patch version (backward compatible fixes)"), - preRelease: external_exports.string().optional().describe("Pre-release identifier (alpha, beta, rc.1)"), - build: external_exports.string().optional().describe("Build metadata") -}).describe("Semantic version number"); -var VersionConstraintSchema = external_exports.union([ - external_exports.string().regex(/^[\d.]+$/).describe("Exact version: `1.2.3`"), - external_exports.string().regex(/^\^[\d.]+$/).describe("Compatible with: `^1.2.3` (`>=1.2.3 <2.0.0`)"), - external_exports.string().regex(/^~[\d.]+$/).describe("Approximately: `~1.2.3` (`>=1.2.3 <1.3.0`)"), - external_exports.string().regex(/^>=[\d.]+$/).describe("Greater than or equal: `>=1.2.3`"), - external_exports.string().regex(/^>[\d.]+$/).describe("Greater than: `>1.2.3`"), - external_exports.string().regex(/^<=[\d.]+$/).describe("Less than or equal: `<=1.2.3`"), - external_exports.string().regex(/^<[\d.]+$/).describe("Less than: `<1.2.3`"), - external_exports.string().regex(/^[\d.]+ - [\d.]+$/).describe("Range: `1.2.3 - 2.3.4`"), - external_exports.literal("*").describe("Any version"), - external_exports.literal("latest").describe("Latest stable version") -]); -var CompatibilityLevelSchema = external_exports.enum([ - "fully-compatible", - // 100% compatible, drop-in replacement - "backward-compatible", - // Backward compatible, new features added - "deprecated-compatible", - // Compatible but uses deprecated features - "breaking-changes", - // Breaking changes, migration required - "incompatible" - // Completely incompatible -]).describe("Compatibility level between versions"); -var BreakingChangeSchema = external_exports.object({ - /** - * Version where the change was introduced - */ - introducedIn: external_exports.string().describe("Version that introduced this breaking change"), - /** - * Type of breaking change - */ - type: external_exports.enum([ - "api-removed", - // API removed - "api-renamed", - // API renamed - "api-signature-changed", - // Function signature changed - "behavior-changed", - // Behavior changed - "dependency-changed", - // Dependency requirement changed - "configuration-changed", - // Configuration schema changed - "protocol-changed" - // Protocol implementation changed - ]), - /** - * What was changed - */ - description: external_exports.string(), - /** - * Migration guide - */ - migrationGuide: external_exports.string().optional().describe("How to migrate from old to new"), - /** - * Deprecated in version - */ - deprecatedIn: external_exports.string().optional().describe("Version where old API was deprecated"), - /** - * Will be removed in version - */ - removedIn: external_exports.string().optional().describe("Version where old API will be removed"), - /** - * Automated migration available - */ - automatedMigration: external_exports.boolean().default(false).describe("Whether automated migration tool is available"), - /** - * Impact severity - */ - severity: external_exports.enum(["critical", "major", "minor"]).describe("Impact severity") -}); -var DeprecationNoticeSchema = external_exports.object({ - /** - * Feature or API being deprecated - */ - feature: external_exports.string().describe("Deprecated feature identifier"), - /** - * Version when deprecated - */ - deprecatedIn: external_exports.string(), - /** - * Planned removal version - */ - removeIn: external_exports.string().optional(), - /** - * Reason for deprecation - */ - reason: external_exports.string(), - /** - * Recommended alternative - */ - alternative: external_exports.string().optional().describe("What to use instead"), - /** - * Migration path - */ - migrationPath: external_exports.string().optional().describe("How to migrate to alternative") -}); -var CompatibilityMatrixEntrySchema = external_exports.object({ - /** - * Source version - */ - from: external_exports.string().describe("Version being upgraded from"), - /** - * Target version - */ - to: external_exports.string().describe("Version being upgraded to"), - /** - * Compatibility level - */ - compatibility: CompatibilityLevelSchema, - /** - * Breaking changes list - */ - breakingChanges: external_exports.array(BreakingChangeSchema).optional(), - /** - * Migration required - */ - migrationRequired: external_exports.boolean().default(false), - /** - * Migration complexity - */ - migrationComplexity: external_exports.enum(["trivial", "simple", "moderate", "complex", "major"]).optional(), - /** - * Estimated migration time in hours - */ - estimatedMigrationTime: external_exports.number().optional(), - /** - * Migration script available - */ - migrationScript: external_exports.string().optional().describe("Path to migration script"), - /** - * Test coverage for migration - */ - testCoverage: external_exports.number().min(0).max(100).optional().describe("Percentage of migration covered by tests") -}); -var PluginCompatibilityMatrixSchema = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Current version - */ - currentVersion: external_exports.string(), - /** - * Compatibility entries - */ - compatibilityMatrix: external_exports.array(CompatibilityMatrixEntrySchema), - /** - * Supported versions - */ - supportedVersions: external_exports.array(external_exports.object({ - version: external_exports.string(), - supported: external_exports.boolean(), - endOfLife: external_exports.string().datetime().optional().describe("End of support date"), - securitySupport: external_exports.boolean().default(false).describe("Still receives security updates") - })), - /** - * Minimum compatible version - */ - minimumCompatibleVersion: external_exports.string().optional().describe("Oldest version that can be directly upgraded") -}); -var DependencyConflictSchema = external_exports.object({ - /** - * Type of conflict - */ - type: external_exports.enum([ - "version-mismatch", - // Different versions required - "missing-dependency", - // Required dependency not found - "circular-dependency", - // Circular dependency detected - "incompatible-versions", - // Incompatible versions required by different plugins - "conflicting-interfaces" - // Plugins implement conflicting interfaces - ]), - /** - * Plugins involved in conflict - */ - plugins: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - version: external_exports.string(), - requirement: external_exports.string().optional().describe("What this plugin requires") - })), - /** - * Conflict description - */ - description: external_exports.string(), - /** - * Possible resolutions - */ - resolutions: external_exports.array(external_exports.object({ - strategy: external_exports.enum([ - "upgrade", - // Upgrade one or more plugins - "downgrade", - // Downgrade one or more plugins - "replace", - // Replace with alternative plugin - "disable", - // Disable conflicting plugin - "manual" - // Manual intervention required - ]), - description: external_exports.string(), - automaticResolution: external_exports.boolean().default(false), - riskLevel: external_exports.enum(["low", "medium", "high"]) - })).optional(), - /** - * Severity of conflict - */ - severity: external_exports.enum(["critical", "error", "warning", "info"]) -}); -var PluginDependencyResolutionResultSchema = external_exports.object({ - /** - * Resolution successful - */ - success: external_exports.boolean(), - /** - * Resolved plugin versions - */ - resolved: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - version: external_exports.string(), - resolvedVersion: external_exports.string() - })).optional(), - /** - * Conflicts found - */ - conflicts: external_exports.array(DependencyConflictSchema).optional(), - /** - * Warnings - */ - warnings: external_exports.array(external_exports.string()).optional(), - /** - * Installation order (topologically sorted) - */ - installationOrder: external_exports.array(external_exports.string()).optional().describe("Plugin IDs in order they should be installed"), - /** - * Dependency graph - */ - dependencyGraph: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional().describe("Map of plugin ID to its dependencies") -}); -var MultiVersionSupportSchema = external_exports.object({ - /** - * Enable multi-version support - */ - enabled: external_exports.boolean().default(false), - /** - * Maximum concurrent versions - */ - maxConcurrentVersions: external_exports.number().int().min(1).default(2).describe("How many versions can run at the same time"), - /** - * Version selection strategy - */ - selectionStrategy: external_exports.enum([ - "latest", - // Always use latest version - "stable", - // Use latest stable version - "compatible", - // Use version compatible with dependencies - "pinned", - // Use pinned version - "canary", - // Use canary/preview version - "custom" - // Custom selection logic - ]).default("latest"), - /** - * Version routing rules - */ - routing: external_exports.array(external_exports.object({ - condition: external_exports.string().describe("Routing condition (e.g., tenant, user, feature flag)"), - version: external_exports.string().describe("Version to use when condition matches"), - priority: external_exports.number().int().default(100).describe("Rule priority") - })).optional(), - /** - * Gradual rollout configuration - */ - rollout: external_exports.object({ - enabled: external_exports.boolean().default(false), - strategy: external_exports.enum(["percentage", "blue-green", "canary"]), - percentage: external_exports.number().min(0).max(100).optional().describe("Percentage of traffic to new version"), - duration: external_exports.number().int().optional().describe("Rollout duration in milliseconds") - }).optional() -}); -var PluginVersionMetadataSchema = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Version number - */ - version: SemanticVersionSchema, - /** - * Version string (computed) - */ - versionString: external_exports.string().describe("Full version string (e.g., 1.2.3-beta.1+build.123)"), - /** - * Release date - */ - releaseDate: external_exports.string().datetime(), - /** - * Release notes - */ - releaseNotes: external_exports.string().optional(), - /** - * Breaking changes - */ - breakingChanges: external_exports.array(BreakingChangeSchema).optional(), - /** - * Deprecations - */ - deprecations: external_exports.array(DeprecationNoticeSchema).optional(), - /** - * Compatibility matrix - */ - compatibilityMatrix: external_exports.array(CompatibilityMatrixEntrySchema).optional(), - /** - * Security vulnerabilities fixed - */ - securityFixes: external_exports.array(external_exports.object({ - cve: external_exports.string().optional().describe("CVE identifier"), - severity: external_exports.enum(["critical", "high", "medium", "low"]), - description: external_exports.string(), - fixedIn: external_exports.string().describe("Version where vulnerability was fixed") - })).optional(), - /** - * Download statistics - */ - statistics: external_exports.object({ - downloads: external_exports.number().int().min(0).optional(), - installations: external_exports.number().int().min(0).optional(), - ratings: external_exports.number().min(0).max(5).optional() - }).optional(), - /** - * Support status - */ - support: external_exports.object({ - status: external_exports.enum(["active", "maintenance", "deprecated", "eol"]), - endOfLife: external_exports.string().datetime().optional(), - securitySupport: external_exports.boolean().default(true) - }) -}); -var ServiceScopeType = external_exports.enum([ - "singleton", - // Single instance shared across the application - "transient", - // New instance created each time - "scoped" - // Instance per scope (request, session, transaction, etc.) -]).describe("Service scope type"); -var ServiceMetadataSchema = external_exports.object({ - /** - * Service name (unique identifier) - */ - name: external_exports.string().min(1).describe("Unique service name identifier"), - /** - * Service scope type - */ - scope: ServiceScopeType.optional().default("singleton").describe("Service scope type"), - /** - * Service type or interface name (optional) - */ - type: external_exports.string().optional().describe("Service type or interface name"), - /** - * Registration timestamp (Unix milliseconds) - */ - registeredAt: external_exports.number().int().optional().describe("Unix timestamp in milliseconds when service was registered"), - /** - * Additional metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional service-specific metadata") -}); -var ServiceRegistryConfigSchema = external_exports.object({ - /** - * Strict mode: throw errors on invalid operations - * @default true - */ - strictMode: external_exports.boolean().optional().default(true).describe("Throw errors on invalid operations (duplicate registration, service not found, etc.)"), - /** - * Allow overwriting existing services - * @default false - */ - allowOverwrite: external_exports.boolean().optional().default(false).describe("Allow overwriting existing service registrations"), - /** - * Enable logging for service operations - * @default false - */ - enableLogging: external_exports.boolean().optional().default(false).describe("Enable logging for service registration and retrieval"), - /** - * Custom scope types (beyond singleton, transient, scoped) - * @default ['singleton', 'transient', 'scoped'] - */ - scopeTypes: external_exports.array(external_exports.string()).optional().describe("Supported scope types"), - /** - * Maximum number of services (prevent memory leaks) - */ - maxServices: external_exports.number().int().min(1).optional().describe("Maximum number of services that can be registered") -}); -var ServiceFactoryRegistrationSchema = external_exports.object({ - /** - * Service name (unique identifier) - */ - name: external_exports.string().min(1).describe("Unique service name identifier"), - /** - * Service scope type - */ - scope: ServiceScopeType.optional().default("singleton").describe("Service scope type"), - /** - * Factory type (sync or async) - */ - factoryType: external_exports.enum(["sync", "async"]).optional().default("sync").describe("Whether factory is synchronous or asynchronous"), - /** - * Whether this is a singleton (cache factory result) - */ - singleton: external_exports.boolean().optional().default(true).describe("Whether to cache the factory result (singleton pattern)") -}); -var ScopeConfigSchema = external_exports.object({ - /** - * Type of scope (request, session, transaction, etc.) - */ - scopeType: external_exports.string().describe("Type of scope"), - /** - * Scope identifier (optional, auto-generated if not provided) - */ - scopeId: external_exports.string().optional().describe("Unique scope identifier"), - /** - * Scope metadata (context information) - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Scope-specific context metadata") -}); -var ScopeInfoSchema = external_exports.object({ - /** - * Scope identifier - */ - scopeId: external_exports.string().describe("Unique scope identifier"), - /** - * Type of scope - */ - scopeType: external_exports.string().describe("Type of scope"), - /** - * Creation timestamp (Unix milliseconds) - */ - createdAt: external_exports.number().int().describe("Unix timestamp in milliseconds when scope was created"), - /** - * Number of services in this scope - */ - serviceCount: external_exports.number().int().min(0).optional().describe("Number of services registered in this scope"), - /** - * Scope metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Scope-specific context metadata") -}); -var StartupOptionsSchema = external_exports.object({ - /** - * Maximum time (ms) to wait for each plugin to start - * @default 30000 (30 seconds) - */ - timeout: external_exports.number().int().min(0).optional().default(3e4).describe("Maximum time in milliseconds to wait for each plugin to start"), - /** - * Whether to rollback (destroy) already-started plugins on failure - * @default true - */ - rollbackOnFailure: external_exports.boolean().optional().default(true).describe("Whether to rollback already-started plugins if any plugin fails"), - /** - * Whether to run health checks after startup - * @default false - */ - healthCheck: external_exports.boolean().optional().default(false).describe("Whether to run health checks after plugin startup"), - /** - * Whether to run plugins in parallel (if dependencies allow) - * @default false (sequential startup) - */ - parallel: external_exports.boolean().optional().default(false).describe("Whether to start plugins in parallel when dependencies allow"), - /** - * Custom context to pass to plugin lifecycle methods - */ - context: external_exports.unknown().optional().describe("Custom context object to pass to plugin lifecycle methods") -}); -var HealthStatusSchema = external_exports.object({ - /** - * Whether the plugin is healthy - */ - healthy: external_exports.boolean().describe("Whether the plugin is healthy"), - /** - * Health check timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds when health check was performed"), - /** - * Optional health details (plugin-specific) - */ - details: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Optional plugin-specific health details"), - /** - * Optional error message if unhealthy - */ - message: external_exports.string().optional().describe("Error message if plugin is unhealthy") -}); -var PluginStartupResultSchema = external_exports.object({ - /** - * Plugin that was started - */ - plugin: external_exports.object({ - name: external_exports.string(), - version: external_exports.string().optional() - }).passthrough().describe("Plugin metadata"), - /** - * Whether startup was successful - */ - success: external_exports.boolean().describe("Whether the plugin started successfully"), - /** - * Time taken to start (milliseconds) - */ - duration: external_exports.number().min(0).describe("Time taken to start the plugin in milliseconds"), - /** - * Error if startup failed - */ - error: external_exports.object({ - name: external_exports.string().describe("Error class name"), - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Stack trace"), - code: external_exports.string().optional().describe("Error code") - }).optional().describe("Serializable error representation if startup failed"), - /** - * Health status after startup (if healthCheck enabled) - */ - health: HealthStatusSchema.optional().describe("Health status after startup if health check was enabled") -}); -var StartupOrchestrationResultSchema = external_exports.object({ - /** - * Individual plugin startup results - */ - results: external_exports.array(PluginStartupResultSchema).describe("Startup results for each plugin"), - /** - * Total time taken for all plugins (milliseconds) - */ - totalDuration: external_exports.number().min(0).describe("Total time taken for all plugins in milliseconds"), - /** - * Whether all plugins started successfully - */ - allSuccessful: external_exports.boolean().describe("Whether all plugins started successfully"), - /** - * Plugins that were rolled back (if rollbackOnFailure was enabled) - */ - rolledBack: external_exports.array(external_exports.string()).optional().describe("Names of plugins that were rolled back") -}); -var PluginVendorSchema = external_exports.object({ - /** - * Vendor identifier (reverse domain notation) - * Example: "com.acme", "org.apache", "com.objectstack" - */ - id: external_exports.string().regex(/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)+$/).describe("Vendor identifier (reverse domain)"), - /** - * Vendor display name - */ - name: external_exports.string(), - /** - * Vendor website - */ - website: external_exports.string().url().optional(), - /** - * Contact email - */ - email: external_exports.string().email().optional(), - /** - * Verification status - */ - verified: external_exports.boolean().default(false).describe("Whether vendor is verified by ObjectStack"), - /** - * Trust level - */ - trustLevel: external_exports.enum(["official", "verified", "community", "unverified"]).default("unverified") -}); -var PluginQualityMetricsSchema = external_exports.object({ - /** - * Test coverage percentage - */ - testCoverage: external_exports.number().min(0).max(100).optional(), - /** - * Documentation score (0-100) - */ - documentationScore: external_exports.number().min(0).max(100).optional(), - /** - * Code quality score (0-100) - */ - codeQuality: external_exports.number().min(0).max(100).optional(), - /** - * Security scan status - */ - securityScan: external_exports.object({ - lastScanDate: external_exports.string().datetime().optional(), - vulnerabilities: external_exports.object({ - critical: external_exports.number().int().min(0).default(0), - high: external_exports.number().int().min(0).default(0), - medium: external_exports.number().int().min(0).default(0), - low: external_exports.number().int().min(0).default(0) - }).optional(), - passed: external_exports.boolean().default(false) - }).optional(), - /** - * Conformance test results - */ - conformanceTests: external_exports.array(external_exports.object({ - protocolId: external_exports.string().describe("Protocol being tested"), - passed: external_exports.boolean(), - totalTests: external_exports.number().int().min(0), - passedTests: external_exports.number().int().min(0), - lastRunDate: external_exports.string().datetime().optional() - })).optional() -}); -var PluginStatisticsSchema = external_exports.object({ - /** - * Total downloads - */ - downloads: external_exports.number().int().min(0).default(0), - /** - * Downloads in the last 30 days - */ - downloadsLastMonth: external_exports.number().int().min(0).default(0), - /** - * Number of active installations - */ - activeInstallations: external_exports.number().int().min(0).default(0), - /** - * User ratings - */ - ratings: external_exports.object({ - average: external_exports.number().min(0).max(5).default(0), - count: external_exports.number().int().min(0).default(0), - distribution: external_exports.object({ - "5": external_exports.number().int().min(0).default(0), - "4": external_exports.number().int().min(0).default(0), - "3": external_exports.number().int().min(0).default(0), - "2": external_exports.number().int().min(0).default(0), - "1": external_exports.number().int().min(0).default(0) - }).optional() - }).optional(), - /** - * GitHub stars (if open source) - */ - stars: external_exports.number().int().min(0).optional(), - /** - * Number of dependent plugins - */ - dependents: external_exports.number().int().min(0).default(0) -}); -var PluginRegistryEntrySchema = external_exports.object({ - /** - * Plugin identifier (must match manifest.id) - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Plugin identifier (reverse domain notation)"), - /** - * Current version - */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/), - /** - * Plugin display name - */ - name: external_exports.string(), - /** - * Short description - */ - description: external_exports.string().optional(), - /** - * Detailed documentation/README - */ - readme: external_exports.string().optional(), - /** - * Plugin type/category - */ - category: external_exports.enum([ - "data", - // Data management, storage, databases - "integration", - // External service integrations - "ui", - // UI components and themes - "analytics", - // Analytics and reporting - "security", - // Security, auth, compliance - "automation", - // Workflows and automation - "ai", - // AI/ML capabilities - "utility", - // General utilities - "driver", - // Database/storage drivers - "gateway", - // API gateways - "adapter" - // Runtime adapters - ]).optional(), - /** - * Tags for categorization - */ - tags: external_exports.array(external_exports.string()).optional(), - /** - * Vendor information - */ - vendor: PluginVendorSchema, - /** - * Capability manifest (what the plugin implements/provides) - */ - capabilities: PluginCapabilityManifestSchema2.optional(), - /** - * Compatibility information - */ - compatibility: external_exports.object({ - /** - * Minimum ObjectStack version required - */ - minObjectStackVersion: external_exports.string().optional(), - /** - * Maximum ObjectStack version supported - */ - maxObjectStackVersion: external_exports.string().optional(), - /** - * Node.js version requirement - */ - nodeVersion: external_exports.string().optional(), - /** - * Supported platforms - */ - platforms: external_exports.array(external_exports.enum(["linux", "darwin", "win32", "browser"])).optional() - }).optional(), - /** - * Links and resources - */ - links: external_exports.object({ - homepage: external_exports.string().url().optional(), - repository: external_exports.string().url().optional(), - documentation: external_exports.string().url().optional(), - bugs: external_exports.string().url().optional(), - changelog: external_exports.string().url().optional() - }).optional(), - /** - * Media assets - */ - media: external_exports.object({ - icon: external_exports.string().url().optional(), - logo: external_exports.string().url().optional(), - screenshots: external_exports.array(external_exports.string().url()).optional(), - video: external_exports.string().url().optional() - }).optional(), - /** - * Quality metrics - */ - quality: PluginQualityMetricsSchema.optional(), - /** - * Usage statistics - */ - statistics: PluginStatisticsSchema.optional(), - /** - * License information - */ - license: external_exports.string().optional().describe("SPDX license identifier"), - /** - * Pricing (if commercial) - */ - pricing: external_exports.object({ - model: external_exports.enum(["free", "freemium", "paid", "enterprise"]), - price: external_exports.number().min(0).optional(), - currency: external_exports.string().default("USD").optional(), - billingPeriod: external_exports.enum(["one-time", "monthly", "yearly"]).optional() - }).optional(), - /** - * Publication dates - */ - publishedAt: external_exports.string().datetime().optional(), - updatedAt: external_exports.string().datetime().optional(), - /** - * Deprecation status - */ - deprecated: external_exports.boolean().default(false), - deprecationMessage: external_exports.string().optional(), - replacedBy: external_exports.string().optional().describe("Plugin ID that replaces this one"), - /** - * Feature flags - */ - flags: external_exports.object({ - experimental: external_exports.boolean().default(false), - beta: external_exports.boolean().default(false), - featured: external_exports.boolean().default(false), - verified: external_exports.boolean().default(false) - }).optional() -}); -var PluginSearchFiltersSchema = external_exports.object({ - /** - * Search query - */ - query: external_exports.string().optional(), - /** - * Filter by category - */ - category: external_exports.array(external_exports.string()).optional(), - /** - * Filter by tags - */ - tags: external_exports.array(external_exports.string()).optional(), - /** - * Filter by vendor trust level - */ - trustLevel: external_exports.array(external_exports.enum(["official", "verified", "community", "unverified"])).optional(), - /** - * Filter by protocols implemented - */ - implementsProtocols: external_exports.array(external_exports.string()).optional(), - /** - * Filter by pricing model - */ - pricingModel: external_exports.array(external_exports.enum(["free", "freemium", "paid", "enterprise"])).optional(), - /** - * Minimum rating - */ - minRating: external_exports.number().min(0).max(5).optional(), - /** - * Sort options - */ - sortBy: external_exports.enum([ - "relevance", - "downloads", - "rating", - "updated", - "name" - ]).optional(), - /** - * Sort order - */ - sortOrder: external_exports.enum(["asc", "desc"]).default("desc").optional(), - /** - * Pagination - */ - page: external_exports.number().int().min(1).default(1).optional(), - limit: external_exports.number().int().min(1).max(100).default(20).optional() -}); -var PluginInstallConfigSchema = external_exports.object({ - /** - * Plugin identifier to install - */ - pluginId: external_exports.string(), - /** - * Version to install (supports semver ranges) - */ - version: external_exports.string().optional().describe("Defaults to latest"), - /** - * Plugin-specific configuration values - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Whether to auto-update - */ - autoUpdate: external_exports.boolean().default(false).optional(), - /** - * Installation options - */ - options: external_exports.object({ - /** - * Skip dependency installation - */ - skipDependencies: external_exports.boolean().default(false).optional(), - /** - * Force reinstall - */ - force: external_exports.boolean().default(false).optional(), - /** - * Installation target - */ - target: external_exports.enum(["system", "space", "user"]).default("space").optional() - }).optional() -}); -var VulnerabilitySeverity = external_exports.enum([ - "critical", - "high", - "medium", - "low", - "info" -]).describe("Severity level of a security vulnerability"); -var SecurityVulnerabilitySchema = external_exports.object({ - /** - * CVE identifier (if applicable) - */ - cve: external_exports.string().regex(/^CVE-\d{4}-\d+$/).optional().describe("CVE identifier"), - /** - * Vulnerability identifier (GHSA, SNYK, etc.) - */ - id: external_exports.string().describe("Vulnerability ID"), - /** - * Title - */ - title: external_exports.string().describe("Short title summarizing the vulnerability"), - /** - * Description - */ - description: external_exports.string().describe("Detailed description of the vulnerability"), - /** - * Severity - */ - severity: VulnerabilitySeverity.describe("Severity level of this vulnerability"), - /** - * CVSS score (0-10) - */ - cvss: external_exports.number().min(0).max(10).optional().describe("CVSS score ranging from 0 to 10"), - /** - * Affected package - */ - package: external_exports.object({ - name: external_exports.string().describe("Name of the affected package"), - version: external_exports.string().describe("Version of the affected package"), - ecosystem: external_exports.string().optional().describe("Package ecosystem (e.g., npm, pip, maven)") - }).describe("Affected package information"), - /** - * Vulnerable version range - */ - vulnerableVersions: external_exports.string().describe("Semver range of vulnerable versions"), - /** - * Patched versions - */ - patchedVersions: external_exports.string().optional().describe("Semver range of patched versions"), - /** - * References - */ - references: external_exports.array(external_exports.object({ - type: external_exports.enum(["advisory", "article", "report", "web"]).describe("Type of reference source"), - url: external_exports.string().url().describe("URL of the reference") - })).default([]).describe("External references related to the vulnerability"), - /** - * CWE (Common Weakness Enumeration) - */ - cwe: external_exports.array(external_exports.string()).default([]).describe("CWE identifiers associated with this vulnerability"), - /** - * Published date - */ - publishedAt: external_exports.string().datetime().optional().describe("ISO 8601 date when the vulnerability was published"), - /** - * Mitigation advice - */ - mitigation: external_exports.string().optional().describe("Recommended steps to mitigate the vulnerability") -}).describe("A known security vulnerability in a package dependency"); -var SecurityScanResultSchema = external_exports.object({ - /** - * Scan identifier - */ - scanId: external_exports.string().uuid().describe("Unique identifier for this security scan"), - /** - * Plugin being scanned - */ - plugin: external_exports.object({ - id: external_exports.string().describe("Plugin identifier"), - version: external_exports.string().describe("Plugin version that was scanned") - }).describe("Plugin that was scanned"), - /** - * Scan timestamp - */ - scannedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the scan was performed"), - /** - * Scanner information - */ - scanner: external_exports.object({ - name: external_exports.string().describe("Scanner name (e.g., snyk, osv, trivy)"), - version: external_exports.string().describe("Version of the scanner tool") - }).describe("Information about the scanner tool used"), - /** - * Scan status - */ - status: external_exports.enum(["passed", "failed", "warning"]).describe("Overall result status of the security scan"), - /** - * Vulnerabilities found - */ - vulnerabilities: external_exports.array(SecurityVulnerabilitySchema).describe("List of vulnerabilities discovered during the scan"), - /** - * Vulnerability summary - */ - summary: external_exports.object({ - critical: external_exports.number().int().min(0).default(0).describe("Count of critical severity vulnerabilities"), - high: external_exports.number().int().min(0).default(0).describe("Count of high severity vulnerabilities"), - medium: external_exports.number().int().min(0).default(0).describe("Count of medium severity vulnerabilities"), - low: external_exports.number().int().min(0).default(0).describe("Count of low severity vulnerabilities"), - info: external_exports.number().int().min(0).default(0).describe("Count of informational severity vulnerabilities"), - total: external_exports.number().int().min(0).default(0).describe("Total count of all vulnerabilities") - }).describe("Summary counts of vulnerabilities by severity"), - /** - * License compliance issues - */ - licenseIssues: external_exports.array(external_exports.object({ - package: external_exports.string().describe("Name of the package with a license issue"), - license: external_exports.string().describe("License identifier of the package"), - reason: external_exports.string().describe("Reason the license is flagged"), - severity: external_exports.enum(["error", "warning", "info"]).describe("Severity of the license compliance issue") - })).default([]).describe("License compliance issues found during the scan"), - /** - * Code quality issues - */ - codeQuality: external_exports.object({ - score: external_exports.number().min(0).max(100).optional().describe("Overall code quality score from 0 to 100"), - issues: external_exports.array(external_exports.object({ - type: external_exports.enum(["security", "quality", "style"]).describe("Category of the code quality issue"), - severity: external_exports.enum(["error", "warning", "info"]).describe("Severity of the code quality issue"), - message: external_exports.string().describe("Description of the code quality issue"), - file: external_exports.string().optional().describe("File path where the issue was found"), - line: external_exports.number().int().optional().describe("Line number where the issue was found") - })).default([]).describe("List of individual code quality issues") - }).optional().describe("Code quality analysis results"), - /** - * Next scan scheduled - */ - nextScanAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp for the next scheduled scan") -}).describe("Result of a security scan performed on a plugin"); -var SecurityPolicySchema = external_exports.object({ - /** - * Policy identifier - */ - id: external_exports.string().describe("Unique identifier for the security policy"), - /** - * Policy name - */ - name: external_exports.string().describe("Human-readable name of the security policy"), - /** - * Automatic scanning - */ - autoScan: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Whether automatic scanning is enabled"), - frequency: external_exports.enum(["on-publish", "daily", "weekly", "monthly"]).default("daily").describe("How often automatic scans are performed") - }).describe("Automatic security scanning configuration"), - /** - * Vulnerability thresholds - */ - thresholds: external_exports.object({ - /** - * Block plugin if critical vulnerabilities exceed this - */ - maxCritical: external_exports.number().int().min(0).default(0).describe("Maximum allowed critical vulnerabilities before blocking"), - /** - * Block plugin if high vulnerabilities exceed this - */ - maxHigh: external_exports.number().int().min(0).default(0).describe("Maximum allowed high vulnerabilities before blocking"), - /** - * Warn if medium vulnerabilities exceed this - */ - maxMedium: external_exports.number().int().min(0).default(5).describe("Maximum allowed medium vulnerabilities before warning") - }).describe("Vulnerability count thresholds for policy enforcement"), - /** - * Allowed licenses - */ - allowedLicenses: external_exports.array(external_exports.string()).default([ - "MIT", - "Apache-2.0", - "BSD-3-Clause", - "BSD-2-Clause", - "ISC" - ]).describe("List of SPDX license identifiers that are permitted"), - /** - * Prohibited licenses - */ - prohibitedLicenses: external_exports.array(external_exports.string()).default([ - "GPL-3.0", - "AGPL-3.0" - ]).describe("List of SPDX license identifiers that are prohibited"), - /** - * Code signing requirements - */ - codeSigning: external_exports.object({ - required: external_exports.boolean().default(false).describe("Whether code signing is required for plugins"), - allowedSigners: external_exports.array(external_exports.string()).default([]).describe("List of trusted signer identities") - }).optional().describe("Code signing requirements for plugin artifacts"), - /** - * Sandbox restrictions - */ - sandbox: external_exports.object({ - /** - * Restrict network access - */ - networkAccess: external_exports.enum(["none", "localhost", "allowlist", "all"]).default("all").describe("Level of network access granted to the plugin"), - /** - * Allowed network destinations (if allowlist) - */ - allowedDestinations: external_exports.array(external_exports.string()).default([]).describe("Permitted network destinations when using allowlist mode"), - /** - * File system access - */ - filesystemAccess: external_exports.enum(["none", "read-only", "temp-only", "full"]).default("full").describe("Level of file system access granted to the plugin"), - /** - * Maximum memory (MB) - */ - maxMemoryMB: external_exports.number().int().positive().optional().describe("Maximum memory allocation in megabytes"), - /** - * Maximum CPU time (seconds) - */ - maxCPUSeconds: external_exports.number().int().positive().optional().describe("Maximum CPU time allowed in seconds") - }).optional().describe("Sandbox restrictions for plugin execution") -}).describe("Security policy governing plugin scanning and enforcement"); -var PackageDependencySchema = external_exports.object({ - /** - * Package name/ID - */ - name: external_exports.string().describe("Package name or identifier"), - /** - * Version constraint (semver range) - */ - versionConstraint: external_exports.string().describe("Semver range (e.g., `^1.0.0`, `>=2.0.0 <3.0.0`)"), - /** - * Dependency type - */ - type: external_exports.enum(["required", "optional", "peer", "dev"]).default("required").describe("Category of the dependency relationship"), - /** - * Resolved version (filled during resolution) - */ - resolvedVersion: external_exports.string().optional().describe("Concrete version resolved during dependency resolution") -}).describe("A package dependency with its version constraint"); -var DependencyGraphNodeSchema = external_exports.object({ - /** - * Package identifier - */ - id: external_exports.string().describe("Unique identifier of the package"), - /** - * Package version - */ - version: external_exports.string().describe("Resolved version of the package"), - /** - * Dependencies of this package - */ - dependencies: external_exports.array(PackageDependencySchema).default([]).describe("Dependencies required by this package"), - /** - * Depth in dependency tree - */ - depth: external_exports.number().int().min(0).describe("Depth level in the dependency tree (0 = root)"), - /** - * Whether this is a direct dependency - */ - isDirect: external_exports.boolean().describe("Whether this is a direct (top-level) dependency"), - /** - * Package metadata - */ - metadata: external_exports.object({ - name: external_exports.string().describe("Display name of the package"), - description: external_exports.string().optional().describe("Short description of the package"), - license: external_exports.string().optional().describe("SPDX license identifier of the package"), - homepage: external_exports.string().url().optional().describe("Homepage URL of the package") - }).optional().describe("Additional metadata about the package") -}).describe("A node in the dependency graph representing a resolved package"); -var DependencyGraphSchema = external_exports.object({ - /** - * Root package - */ - root: external_exports.object({ - id: external_exports.string().describe("Identifier of the root package"), - version: external_exports.string().describe("Version of the root package") - }).describe("Root package of the dependency graph"), - /** - * All nodes in the graph - */ - nodes: external_exports.array(DependencyGraphNodeSchema).describe("All resolved package nodes in the dependency graph"), - /** - * Edges (dependency relationships) - */ - edges: external_exports.array(external_exports.object({ - from: external_exports.string().describe("Package ID"), - to: external_exports.string().describe("Package ID"), - constraint: external_exports.string().describe("Version constraint") - })).describe("Directed edges representing dependency relationships"), - /** - * Resolution statistics - */ - stats: external_exports.object({ - totalDependencies: external_exports.number().int().min(0).describe("Total number of resolved dependencies"), - directDependencies: external_exports.number().int().min(0).describe("Number of direct (top-level) dependencies"), - maxDepth: external_exports.number().int().min(0).describe("Maximum depth of the dependency tree") - }).describe("Summary statistics for the dependency graph") -}).describe("Complete dependency graph for a package and its transitive dependencies"); -var PackageDependencyConflictSchema = external_exports.object({ - /** - * Package with conflict - */ - package: external_exports.string().describe("Name of the package with conflicting version requirements"), - /** - * Conflicting versions - */ - conflicts: external_exports.array(external_exports.object({ - version: external_exports.string().describe("Conflicting version of the package"), - requestedBy: external_exports.array(external_exports.string()).describe("Packages that require this version"), - constraint: external_exports.string().describe("Semver constraint that produced this version requirement") - })).describe("List of conflicting version requirements"), - /** - * Suggested resolution - */ - resolution: external_exports.object({ - strategy: external_exports.enum(["pick-highest", "pick-lowest", "manual"]).describe("Strategy used to resolve the conflict"), - version: external_exports.string().optional().describe("Resolved version selected by the strategy"), - reason: external_exports.string().optional().describe("Explanation of why this resolution was chosen") - }).optional().describe("Suggested resolution for the conflict"), - /** - * Severity - */ - severity: external_exports.enum(["error", "warning", "info"]).describe("Severity level of the dependency conflict") -}).describe("A detected conflict between dependency version requirements"); -var PackageDependencyResolutionResultSchema = external_exports.object({ - /** - * Resolution status - */ - status: external_exports.enum(["success", "conflict", "error"]).describe("Overall status of the dependency resolution"), - /** - * Resolved dependency graph - */ - graph: DependencyGraphSchema.optional().describe("Resolved dependency graph if resolution succeeded"), - /** - * Conflicts detected - */ - conflicts: external_exports.array(PackageDependencyConflictSchema).default([]).describe("List of dependency conflicts detected during resolution"), - /** - * Errors encountered - */ - errors: external_exports.array(external_exports.object({ - package: external_exports.string().describe("Name of the package that caused the error"), - error: external_exports.string().describe("Error message describing what went wrong") - })).default([]).describe("Errors encountered during dependency resolution"), - /** - * Installation order (topological sort) - */ - installOrder: external_exports.array(external_exports.string()).default([]).describe("Topologically sorted list of package IDs for installation"), - /** - * Resolution time (ms) - */ - resolvedIn: external_exports.number().int().min(0).optional().describe("Time taken to resolve dependencies in milliseconds") -}).describe("Result of a dependency resolution process"); -var SBOMEntrySchema = external_exports.object({ - /** - * Component name - */ - name: external_exports.string().describe("Name of the software component"), - /** - * Component version - */ - version: external_exports.string().describe("Version of the software component"), - /** - * Package URL (purl) - */ - purl: external_exports.string().optional().describe("Package URL identifier"), - /** - * License - */ - license: external_exports.string().optional().describe("SPDX license identifier of the component"), - /** - * Hashes - */ - hashes: external_exports.object({ - sha256: external_exports.string().optional().describe("SHA-256 hash of the component artifact"), - sha512: external_exports.string().optional().describe("SHA-512 hash of the component artifact") - }).optional().describe("Cryptographic hashes for integrity verification"), - /** - * Supplier - */ - supplier: external_exports.object({ - name: external_exports.string().describe("Name of the component supplier"), - url: external_exports.string().url().optional().describe("URL of the component supplier") - }).optional().describe("Supplier information for the component"), - /** - * External references - */ - externalRefs: external_exports.array(external_exports.object({ - type: external_exports.enum(["website", "repository", "documentation", "issue-tracker"]).describe("Type of external reference"), - url: external_exports.string().url().describe("URL of the external reference") - })).default([]).describe("External references related to the component") -}).describe("A single entry in a Software Bill of Materials"); -var SBOMSchema = external_exports.object({ - /** - * SBOM format - */ - format: external_exports.enum(["spdx", "cyclonedx"]).default("cyclonedx").describe("SBOM standard format used"), - /** - * SBOM version - */ - version: external_exports.string().describe("Version of the SBOM specification"), - /** - * Plugin metadata - */ - plugin: external_exports.object({ - id: external_exports.string().describe("Plugin identifier"), - version: external_exports.string().describe("Plugin version"), - name: external_exports.string().describe("Human-readable plugin name") - }).describe("Metadata about the plugin this SBOM describes"), - /** - * Components (dependencies) - */ - components: external_exports.array(SBOMEntrySchema).describe("List of software components included in the plugin"), - /** - * Generation timestamp - */ - generatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the SBOM was generated"), - /** - * Generator tool - */ - generator: external_exports.object({ - name: external_exports.string().describe("Name of the SBOM generator tool"), - version: external_exports.string().describe("Version of the SBOM generator tool") - }).optional().describe("Tool used to generate this SBOM") -}).describe("Software Bill of Materials for a plugin"); -var PluginProvenanceSchema = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string().describe("Unique identifier of the plugin"), - /** - * Plugin version - */ - version: external_exports.string().describe("Version of the plugin artifact"), - /** - * Build information - */ - build: external_exports.object({ - /** - * Build timestamp - */ - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the build was produced"), - /** - * Build environment - */ - environment: external_exports.object({ - os: external_exports.string().describe("Operating system used for the build"), - arch: external_exports.string().describe("CPU architecture used for the build"), - nodeVersion: external_exports.string().describe("Node.js version used for the build") - }).optional().describe("Environment details where the build was executed"), - /** - * Source repository - */ - source: external_exports.object({ - repository: external_exports.string().url().describe("URL of the source repository"), - commit: external_exports.string().regex(/^[a-f0-9]{40}$/).describe("Full SHA-1 commit hash of the source"), - branch: external_exports.string().optional().describe("Branch name the build was produced from"), - tag: external_exports.string().optional().describe("Git tag associated with the build") - }).optional().describe("Source repository information for the build"), - /** - * Builder identity - */ - builder: external_exports.object({ - name: external_exports.string().describe("Name of the person or system that produced the build"), - email: external_exports.string().email().optional().describe("Email address of the builder") - }).optional().describe("Identity of the builder who produced the artifact") - }).describe("Build provenance information"), - /** - * Artifact hashes - */ - artifacts: external_exports.array(external_exports.object({ - filename: external_exports.string().describe("Name of the artifact file"), - sha256: external_exports.string().describe("SHA-256 hash of the artifact"), - size: external_exports.number().int().positive().describe("Size of the artifact in bytes") - })).describe("List of build artifacts with integrity hashes"), - /** - * Signatures - */ - signatures: external_exports.array(external_exports.object({ - algorithm: external_exports.enum(["rsa", "ecdsa", "ed25519"]).describe("Cryptographic algorithm used for signing"), - publicKey: external_exports.string().describe("Public key used to verify the signature"), - signature: external_exports.string().describe("Digital signature value"), - signedBy: external_exports.string().describe("Identity of the signer"), - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the signature was created") - })).default([]).describe("Cryptographic signatures for the plugin artifact"), - /** - * Attestations - */ - attestations: external_exports.array(external_exports.object({ - type: external_exports.enum(["code-review", "security-scan", "test-results", "ci-build"]).describe("Type of attestation"), - status: external_exports.enum(["passed", "failed"]).describe("Result status of the attestation"), - url: external_exports.string().url().optional().describe("URL with details about the attestation"), - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the attestation was issued") - })).default([]).describe("Verification attestations for the plugin") -}).describe("Verifiable provenance and chain of custody for a plugin artifact"); -var PluginTrustScoreSchema = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string().describe("Unique identifier of the plugin"), - /** - * Overall trust score (0-100) - */ - score: external_exports.number().min(0).max(100).describe("Overall trust score from 0 to 100"), - /** - * Score components - */ - components: external_exports.object({ - /** - * Vendor reputation (0-100) - */ - vendorReputation: external_exports.number().min(0).max(100).describe("Vendor reputation score from 0 to 100"), - /** - * Security scan results (0-100) - */ - securityScore: external_exports.number().min(0).max(100).describe("Security scan results score from 0 to 100"), - /** - * Code quality (0-100) - */ - codeQuality: external_exports.number().min(0).max(100).describe("Code quality score from 0 to 100"), - /** - * Community engagement (0-100) - */ - communityScore: external_exports.number().min(0).max(100).describe("Community engagement score from 0 to 100"), - /** - * Update frequency (0-100) - */ - maintenanceScore: external_exports.number().min(0).max(100).describe("Maintenance and update frequency score from 0 to 100") - }).describe("Individual score components contributing to the overall trust score"), - /** - * Trust level - */ - level: external_exports.enum(["verified", "trusted", "neutral", "untrusted", "blocked"]).describe("Computed trust level based on the overall score"), - /** - * Verification badges - */ - badges: external_exports.array(external_exports.enum([ - "official", - // Official ObjectStack plugin - "verified-vendor", - // Verified vendor - "security-scanned", - // Passed security scan - "code-signed", - // Digitally signed - "open-source", - // Open source - "popular" - // High downloads - ])).default([]).describe("Verification badges earned by the plugin"), - /** - * Last updated - */ - updatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the trust score was last updated") -}).describe("Trust score and verification status for a plugin"); -var ExecutionContextSchema2 = external_exports.object({ - /** Current user ID (resolved from session) */ - userId: external_exports.string().optional(), - /** Current organization/tenant ID (resolved from session.activeOrganizationId) */ - tenantId: external_exports.string().optional(), - /** User role names (resolved from Member + Role) */ - roles: external_exports.array(external_exports.string()).default([]), - /** Aggregated permission names (resolved from PermissionSet) */ - permissions: external_exports.array(external_exports.string()).default([]), - /** Whether this is a system-level operation (bypasses permission checks) */ - isSystem: external_exports.boolean().default(false), - /** Raw access token (for external API call pass-through) */ - accessToken: external_exports.string().optional(), - /** Database transaction handle */ - transaction: external_exports.unknown().optional(), - /** Request trace ID (for distributed tracing) */ - traceId: external_exports.string().optional() -}); - -// ../../packages/spec/dist/ui/index.mjs -init_zod(); -var I18nObjectSchema = external_exports.object({ - /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ - key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), - /** Default value when translation is not available */ - defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), - /** Interpolation parameters for dynamic translations */ - params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") -}); -var I18nLabelSchema4 = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); -var AriaPropsSchema4 = external_exports.object({ - /** Accessible label for screen readers */ - ariaLabel: I18nLabelSchema4.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), - /** ID of element that describes this component */ - ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), - /** WAI-ARIA role override */ - role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') -}).describe("ARIA accessibility attributes"); -var PluralRuleSchema = external_exports.object({ - /** Translation key for the plural form */ - key: external_exports.string().describe("Translation key"), - /** Form for zero quantity */ - zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), - /** Form for singular (1) */ - one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), - /** Form for dual (2) — used in Arabic, Welsh, etc. */ - two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), - /** Form for few (2-4 in Slavic languages) */ - few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), - /** Form for many (5+ in Slavic languages) */ - many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), - /** Default/fallback form */ - other: external_exports.string().describe('Default plural form (e.g., "{count} items")') -}).describe("ICU plural rules for a translation key"); -var NumberFormatSchema4 = external_exports.object({ - style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), - currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), - unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), - minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), - maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), - useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") -}).describe("Number formatting rules"); -var DateFormatSchema4 = external_exports.object({ - dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), - timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), - timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), - hour12: external_exports.boolean().optional().describe("Use 12-hour format") -}).describe("Date/time formatting rules"); -var LocaleConfigSchema = external_exports.object({ - /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ - code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), - /** Ordered fallback chain for missing translations */ - fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), - /** Text direction */ - direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), - /** Default number formatting */ - numberFormat: NumberFormatSchema4.optional().describe("Default number formatting rules"), - /** Default date formatting */ - dateFormat: DateFormatSchema4.optional().describe("Default date/time formatting rules") -}).describe("Locale configuration"); -var ChartTypeSchema = external_exports.enum([ - // Comparison - "bar", - "horizontal-bar", - "column", - "grouped-bar", - "stacked-bar", - "bi-polar-bar", - // Trend - "line", - "area", - "stacked-area", - "step-line", - "spline", - // Distribution - "pie", - "donut", - "funnel", - "pyramid", - // Relationship - "scatter", - "bubble", - // Composition - "treemap", - "sunburst", - "sankey", - "word-cloud", - // Performance - "gauge", - "solid-gauge", - "metric", - "kpi", - "bullet", - // Geo - "choropleth", - "bubble-map", - "gl-map", - // Advanced - "heatmap", - "radar", - "waterfall", - "box-plot", - "violin", - "candlestick", - "stock", - // Tabular - "table", - "pivot" -]); -var ChartAxisSchema = external_exports.object({ - /** Data field to map to this axis */ - field: external_exports.string().describe("Data field key"), - /** Axis title */ - title: I18nLabelSchema4.optional().describe("Axis display title"), - /** Value formatting (d3-format or similar) */ - format: external_exports.string().optional().describe('Value format string (e.g., "$0,0.00")'), - /** Axis scale settings */ - min: external_exports.number().optional().describe("Minimum value"), - max: external_exports.number().optional().describe("Maximum value"), - stepSize: external_exports.number().optional().describe("Step size for ticks"), - /** Appearance */ - showGridLines: external_exports.boolean().default(true), - position: external_exports.enum(["left", "right", "top", "bottom"]).optional().describe("Axis position"), - /** Logarithmic scale */ - logarithmic: external_exports.boolean().default(false) -}); -var ChartSeriesSchema = external_exports.object({ - /** Field name for values */ - name: external_exports.string().describe("Field name or series identifier"), - /** Display label */ - label: I18nLabelSchema4.optional().describe("Series display label"), - /** Series type override (combo charts) */ - type: ChartTypeSchema.optional().describe("Override chart type for this series"), - /** Specific color */ - color: external_exports.string().optional().describe("Series color (hex/rgb/token)"), - /** Stacking group */ - stack: external_exports.string().optional().describe("Stack identifier to group series"), - /** Axis binding */ - yAxis: external_exports.enum(["left", "right"]).default("left").describe("Bind to specific Y-Axis") -}); -var ChartAnnotationSchema = external_exports.object({ - type: external_exports.enum(["line", "region"]).default("line"), - axis: external_exports.enum(["x", "y"]).default("y"), - value: external_exports.union([external_exports.number(), external_exports.string()]).describe("Start value"), - endValue: external_exports.union([external_exports.number(), external_exports.string()]).optional().describe("End value for regions"), - color: external_exports.string().optional(), - label: I18nLabelSchema4.optional(), - style: external_exports.enum(["solid", "dashed", "dotted"]).default("dashed") -}); -var ChartInteractionSchema = external_exports.object({ - tooltips: external_exports.boolean().default(true), - zoom: external_exports.boolean().default(false), - brush: external_exports.boolean().default(false), - clickAction: external_exports.string().optional().describe("Action ID to trigger on click") -}); -var ChartConfigSchema = external_exports.object({ - /** Chart Type */ - type: ChartTypeSchema, - /** Titles */ - title: I18nLabelSchema4.optional().describe("Chart title"), - subtitle: I18nLabelSchema4.optional().describe("Chart subtitle"), - description: I18nLabelSchema4.optional().describe("Accessibility description"), - /** Axes Mapping */ - xAxis: ChartAxisSchema.optional().describe("X-Axis configuration"), - yAxis: external_exports.array(ChartAxisSchema).optional().describe("Y-Axis configuration (support dual axis)"), - /** Series Configuration */ - series: external_exports.array(ChartSeriesSchema).optional().describe("Defined series configuration"), - /** Appearance */ - colors: external_exports.array(external_exports.string()).optional().describe("Color palette"), - height: external_exports.number().optional().describe("Fixed height in pixels"), - /** Components */ - showLegend: external_exports.boolean().default(true).describe("Display legend"), - showDataLabels: external_exports.boolean().default(false).describe("Display data labels"), - /** Annotations & Reference Lines */ - annotations: external_exports.array(ChartAnnotationSchema).optional(), - /** Interactions */ - interaction: ChartInteractionSchema.optional(), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var BreakpointName2 = external_exports.enum(["xs", "sm", "md", "lg", "xl", "2xl"]); -var BreakpointColumnMapSchema2 = external_exports.object({ - xs: external_exports.number().min(1).max(12).optional(), - sm: external_exports.number().min(1).max(12).optional(), - md: external_exports.number().min(1).max(12).optional(), - lg: external_exports.number().min(1).max(12).optional(), - xl: external_exports.number().min(1).max(12).optional(), - "2xl": external_exports.number().min(1).max(12).optional() -}).describe("Grid columns per breakpoint (1-12)"); -var BreakpointOrderMapSchema2 = external_exports.object({ - xs: external_exports.number().optional(), - sm: external_exports.number().optional(), - md: external_exports.number().optional(), - lg: external_exports.number().optional(), - xl: external_exports.number().optional(), - "2xl": external_exports.number().optional() -}).describe("Display order per breakpoint"); -var ResponsiveConfigSchema2 = external_exports.object({ - /** Minimum breakpoint for visibility */ - breakpoint: BreakpointName2.optional().describe("Minimum breakpoint for visibility"), - /** Hide on specific breakpoints */ - hiddenOn: external_exports.array(BreakpointName2).optional().describe("Hide on these breakpoints"), - /** Grid columns per breakpoint (1-12 column grid) */ - columns: BreakpointColumnMapSchema2.optional().describe("Grid columns per breakpoint"), - /** Display order per breakpoint */ - order: BreakpointOrderMapSchema2.optional().describe("Display order per breakpoint") -}).describe("Responsive layout configuration"); -var PerformanceConfigSchema2 = external_exports.object({ - /** Enable lazy loading for this component */ - lazyLoad: external_exports.boolean().optional().describe("Enable lazy loading (defer rendering until visible)"), - /** Virtual scrolling configuration for large datasets */ - virtualScroll: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable virtual scrolling"), - itemHeight: external_exports.number().optional().describe("Fixed item height in pixels (for estimation)"), - overscan: external_exports.number().optional().describe("Number of extra items to render outside viewport") - }).optional().describe("Virtual scrolling configuration"), - /** Client-side caching strategy */ - cacheStrategy: external_exports.enum([ - "none", - "cache-first", - "network-first", - "stale-while-revalidate" - ]).optional().describe("Client-side data caching strategy"), - /** Enable data prefetching */ - prefetch: external_exports.boolean().optional().describe("Prefetch data before component is visible"), - /** Maximum number of items to render before pagination */ - pageSize: external_exports.number().optional().describe("Number of items per page for pagination"), - /** Debounce interval for user interactions (ms) */ - debounceMs: external_exports.number().optional().describe("Debounce interval for user interactions in milliseconds") -}).describe("Performance optimization configuration"); -var SystemIdentifierSchema5 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' -}).describe("System identifier (lowercase with underscores or dots)"); -var SnakeCaseIdentifierSchema6 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { - message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' -}).describe("Snake case identifier (lowercase with underscores only)"); -external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' -}).describe("Event name (lowercase with dot notation for namespacing)"); -var SharingConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable public sharing"), - publicLink: external_exports.string().optional().describe("Generated public share URL"), - password: external_exports.string().optional().describe("Password required to access shared link"), - allowedDomains: external_exports.array(external_exports.string()).optional().describe('Restrict access to specific email domains (e.g. ["example.com"])'), - expiresAt: external_exports.string().optional().describe("Expiration date/time in ISO 8601 format"), - allowAnonymous: external_exports.boolean().optional().default(false).describe("Allow access without authentication") -}); -var EmbedConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable iframe embedding"), - allowedOrigins: external_exports.array(external_exports.string()).optional().describe('Allowed iframe parent origins (e.g. ["https://example.com"])'), - width: external_exports.string().optional().default("100%").describe("Embed width (CSS value)"), - height: external_exports.string().optional().default("600px").describe("Embed height (CSS value)"), - showHeader: external_exports.boolean().optional().default(true).describe("Show interface header in embed"), - showNavigation: external_exports.boolean().optional().default(false).describe("Show navigation in embed"), - responsive: external_exports.boolean().optional().default(true).describe("Enable responsive resizing") -}); -var BaseNavItemSchema2 = external_exports.object({ - /** Unique identifier for the item */ - id: SnakeCaseIdentifierSchema6.describe("Unique identifier for this navigation item (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema4.describe("Display proper label"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Icon name"), - /** Sort order within the same level (lower numbers appear first) */ - order: external_exports.number().optional().describe("Sort order within the same level (lower = first)"), - /** Badge text or count displayed on the navigation item (e.g. "3", "New") */ - badge: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("Badge text or count displayed on the item"), - /** - * Visibility condition. - * Formula expression returning boolean. - * e.g. "user.is_admin || user.department == 'sales'" - */ - visible: external_exports.string().optional().describe("Visibility formula condition"), - /** Permissions required to see/access this navigation item */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this item") -}); -var ObjectNavItemSchema2 = BaseNavItemSchema2.extend({ - type: external_exports.literal("object"), - objectName: external_exports.string().describe("Target object name"), - viewName: external_exports.string().optional().describe('Default list view to open. Defaults to "all"') -}); -var DashboardNavItemSchema2 = BaseNavItemSchema2.extend({ - type: external_exports.literal("dashboard"), - dashboardName: external_exports.string().describe("Target dashboard name") -}); -var PageNavItemSchema2 = BaseNavItemSchema2.extend({ - type: external_exports.literal("page"), - pageName: external_exports.string().describe("Target custom page component name"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the page context") -}); -var UrlNavItemSchema2 = BaseNavItemSchema2.extend({ - type: external_exports.literal("url"), - url: external_exports.string().describe("Target external URL"), - target: external_exports.enum(["_self", "_blank"]).default("_self").describe("Link target window") -}); -var ReportNavItemSchema2 = BaseNavItemSchema2.extend({ - type: external_exports.literal("report"), - reportName: external_exports.string().describe("Target report name") -}); -var ActionNavItemSchema2 = BaseNavItemSchema2.extend({ - type: external_exports.literal("action"), - actionDef: external_exports.object({ - actionName: external_exports.string().describe("Action machine name to execute"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the action") - }).describe("Action definition to execute when clicked") -}); -var GroupNavItemSchema2 = BaseNavItemSchema2.extend({ - type: external_exports.literal("group"), - expanded: external_exports.boolean().default(false).describe("Default expansion state in sidebar") - // children property is added in the recursive definition below -}); -var NavigationItemSchema2 = external_exports.lazy( - () => external_exports.union([ - ObjectNavItemSchema2.extend({ - children: external_exports.array(NavigationItemSchema2).optional().describe("Child navigation items (e.g. specific views)") - }), - DashboardNavItemSchema2, - PageNavItemSchema2, - UrlNavItemSchema2, - ReportNavItemSchema2, - ActionNavItemSchema2, - GroupNavItemSchema2.extend({ - children: external_exports.array(NavigationItemSchema2).describe("Child navigation items") - }) - ]) -); -var AppBrandingSchema2 = external_exports.object({ - primaryColor: external_exports.string().optional().describe("Primary theme color hex code"), - logo: external_exports.string().optional().describe("Custom logo URL for this app"), - favicon: external_exports.string().optional().describe("Custom favicon URL for this app") -}); -var NavigationAreaSchema2 = external_exports.object({ - /** Unique area identifier */ - id: SnakeCaseIdentifierSchema6.describe("Unique area identifier (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema4.describe("Area display label"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Area icon name"), - /** Sort order among areas (lower = first) */ - order: external_exports.number().optional().describe("Sort order among areas (lower = first)"), - /** Area description */ - description: I18nLabelSchema4.optional().describe("Area description"), - /** - * Visibility condition. - * Formula expression returning boolean. - */ - visible: external_exports.string().optional().describe("Visibility formula condition for this area"), - /** Permissions required to access this area */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this area"), - /** Navigation items within this area */ - navigation: external_exports.array(NavigationItemSchema2).describe("Navigation items within this area") -}); -var AppSchema2 = external_exports.object({ - /** Machine name (id) */ - name: SnakeCaseIdentifierSchema6.describe("App unique machine name (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema4.describe("App display label"), - /** App version */ - version: external_exports.string().optional().describe("App version"), - /** Description */ - description: I18nLabelSchema4.optional().describe("App description"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("App icon used in the App Launcher"), - /** Branding/Theming Configuration */ - branding: AppBrandingSchema2.optional().describe("App-specific branding"), - /** Application status */ - active: external_exports.boolean().optional().default(true).describe("Whether the app is enabled"), - /** Is this the default app for new users? */ - isDefault: external_exports.boolean().optional().default(false).describe("Is default app"), - /** - * Full Navigation Tree — supports unlimited nesting depth. - * Pages are referenced by name via `type: 'page'` items. - * Groups can contain other groups for arbitrary sidebar depth. - * - * For simple apps, use `navigation` directly. - * For enterprise apps with multiple business domains, use `areas` instead. - */ - navigation: external_exports.array(NavigationItemSchema2).optional().describe("Full navigation tree for the app sidebar"), - /** - * Navigation Areas — partitions navigation by business domain. - * Each area defines an independent navigation tree (e.g. Sales, Service, Settings). - * When areas are defined, they take precedence over the top-level `navigation` array. - * - * @example - * ```ts - * areas: [ - * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] }, - * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] }, - * ] - * ``` - */ - areas: external_exports.array(NavigationAreaSchema2).optional().describe("Navigation areas for partitioning navigation by business domain"), - /** - * App-level Home Page Override - * ID of the navigation item to act as the landing page. - * If not set, usually defaults to the first navigation item. - */ - homePageId: external_exports.string().optional().describe("ID of the navigation item to serve as landing page"), - /** - * Access Control - * List of permissions required to access this app. - * Modern replacement for role/profile based assignment. - * Example: ["app.access.crm"] - */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this app"), - /** - * Package Components (For config file convenience) - * In a real monorepo these might be auto-discovered, but here we allow explicit registration. - */ - objects: external_exports.array(external_exports.unknown()).optional().describe("Objects belonging to this app"), - apis: external_exports.array(external_exports.unknown()).optional().describe("Custom APIs belonging to this app"), - /** Sharing configuration for public access */ - sharing: SharingConfigSchema2.optional().describe("Public sharing configuration"), - /** Embed configuration for iframe embedding */ - embed: EmbedConfigSchema2.optional().describe("Iframe embedding configuration"), - /** Mobile navigation mode */ - mobileNavigation: external_exports.object({ - mode: external_exports.enum(["drawer", "bottom_nav", "hamburger"]).default("drawer").describe("Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu"), - bottomNavItems: external_exports.array(external_exports.string()).optional().describe("Navigation item IDs to show in bottom nav (max 5)") - }).optional().describe("Mobile-specific navigation configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes for the application") -}); -var App = { - create: (config4) => AppSchema2.parse(config4) -}; -function defineApp(config4) { - return AppSchema2.parse(config4); -} -var HttpMethod4 = external_exports.enum([ - "GET", - "POST", - "PUT", - "DELETE", - "PATCH", - "HEAD", - "OPTIONS" -]); -var HttpMethodSchema4 = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); -var HttpRequestSchema3 = external_exports.object({ - url: external_exports.string().describe("API endpoint URL"), - method: HttpMethodSchema4.optional().default("GET").describe("HTTP method"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), - body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") -}); -external_exports.object({ - /** - * Enable CORS - */ - enabled: external_exports.boolean().default(true).describe("Enable CORS"), - /** - * Allowed origins (* for all) - */ - origins: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.string()) - ]).default("*").describe("Allowed origins (* for all)"), - /** - * Allowed HTTP methods - */ - methods: external_exports.array(HttpMethod4).optional().describe("Allowed HTTP methods"), - /** - * Allow credentials (cookies, authorization headers) - */ - credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), - /** - * Preflight cache duration in seconds - */ - maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") -}); -external_exports.object({ - /** - * Enable rate limiting - */ - enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), - /** - * Time window in milliseconds - */ - windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), - /** - * Max requests per window - */ - maxRequests: external_exports.number().int().default(100).describe("Max requests per window") -}); -external_exports.object({ - /** - * URL path to serve from - */ - path: external_exports.string().describe("URL path to serve from"), - /** - * Physical directory to serve - */ - directory: external_exports.string().describe("Physical directory to serve"), - /** - * Cache-Control header value - */ - cacheControl: external_exports.string().optional().describe("Cache-Control header value") -}); -var ViewDataSchema2 = external_exports.discriminatedUnion("provider", [ - external_exports.object({ - provider: external_exports.literal("object"), - object: external_exports.string().describe("Target object name") - }), - external_exports.object({ - provider: external_exports.literal("api"), - read: HttpRequestSchema3.optional().describe("Configuration for fetching data"), - write: HttpRequestSchema3.optional().describe("Configuration for submitting data (for forms/editable tables)") - }), - external_exports.object({ - provider: external_exports.literal("value"), - items: external_exports.array(external_exports.unknown()).describe("Static data array") - }) -]); -var ViewFilterRuleSchema2 = external_exports.object({ - /** Field name to filter on */ - field: external_exports.string().describe("Field name to filter on"), - /** Filter operator */ - operator: external_exports.string().describe("Filter operator (e.g. equals, not_equals, contains, this_quarter)"), - /** Filter value (optional for unary operators like is_null, this_quarter) */ - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Filter value") -}).describe("View filter rule"); -var ColumnSummarySchema2 = external_exports.enum([ - "none", - "count", - "count_empty", - "count_filled", - "count_unique", - "percent_empty", - "percent_filled", - "sum", - "avg", - "min", - "max" -]).describe("Aggregation function for column footer summary"); -var ListColumnSchema2 = external_exports.object({ - field: external_exports.string().describe("Field name (snake_case)"), - label: I18nLabelSchema4.optional().describe("Display label override"), - width: external_exports.number().positive().optional().describe("Column width in pixels"), - align: external_exports.enum(["left", "center", "right"]).optional().describe("Text alignment"), - hidden: external_exports.boolean().optional().describe("Hide column by default"), - sortable: external_exports.boolean().optional().describe("Allow sorting by this column"), - resizable: external_exports.boolean().optional().describe("Allow resizing this column"), - wrap: external_exports.boolean().optional().describe("Allow text wrapping"), - type: external_exports.string().optional().describe('Renderer type override (e.g., "currency", "date")'), - /** Pinning (Airtable-style frozen columns) */ - pinned: external_exports.enum(["left", "right"]).optional().describe("Pin/freeze column to left or right side"), - /** Column Footer Summary (Airtable-style aggregation) */ - summary: ColumnSummarySchema2.optional().describe("Footer aggregation function for this column"), - /** Interaction */ - link: external_exports.boolean().optional().describe("Functions as the primary navigation link (triggers View navigation)"), - action: external_exports.string().optional().describe("Registered Action ID to execute when clicked") -}); -var SelectionConfigSchema2 = external_exports.object({ - type: external_exports.enum(["none", "single", "multiple"]).default("none").describe("Selection mode") -}); -var PaginationConfigSchema2 = external_exports.object({ - pageSize: external_exports.number().int().positive().default(25).describe("Number of records per page"), - pageSizeOptions: external_exports.array(external_exports.number().int().positive()).optional().describe("Available page size options") -}); -var RowHeightSchema2 = external_exports.enum([ - "compact", - // Minimal padding, single line - "short", - // Reduced padding - "medium", - // Default padding - "tall", - // Extra padding, multi-line preview - "extra_tall" - // Maximum padding, rich content preview -]).describe("Row height / density setting for list view"); -var GroupingFieldSchema2 = external_exports.object({ - field: external_exports.string().describe("Field name to group by"), - order: external_exports.enum(["asc", "desc"]).default("asc").describe("Group sort order"), - collapsed: external_exports.boolean().default(false).describe("Collapse groups by default") -}); -var GroupingConfigSchema2 = external_exports.object({ - fields: external_exports.array(GroupingFieldSchema2).min(1).describe("Fields to group by (supports up to 3 levels)") -}).describe("Record grouping configuration"); -var GalleryConfigSchema2 = external_exports.object({ - coverField: external_exports.string().optional().describe("Attachment/image field to display as card cover"), - coverFit: external_exports.enum(["cover", "contain"]).default("cover").describe("Image fit mode for card cover"), - cardSize: external_exports.enum(["small", "medium", "large"]).default("medium").describe("Card size in gallery view"), - titleField: external_exports.string().optional().describe("Field to display as card title"), - visibleFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on card body") -}).describe("Gallery/card view configuration"); -var TimelineConfigSchema2 = external_exports.object({ - startDateField: external_exports.string().describe("Field for timeline item start date"), - endDateField: external_exports.string().optional().describe("Field for timeline item end date"), - titleField: external_exports.string().describe("Field to display as timeline item title"), - groupByField: external_exports.string().optional().describe("Field to group timeline rows"), - colorField: external_exports.string().optional().describe("Field to determine item color"), - scale: external_exports.enum(["hour", "day", "week", "month", "quarter", "year"]).default("week").describe("Default timeline scale") -}).describe("Timeline view configuration"); -var ViewSharingSchema2 = external_exports.object({ - type: external_exports.enum(["personal", "collaborative"]).default("collaborative").describe("View ownership type"), - lockedBy: external_exports.string().optional().describe("User who locked the view configuration") -}).describe("View sharing and access configuration"); -var RowColorConfigSchema2 = external_exports.object({ - field: external_exports.string().describe("Field to derive color from (typically a select/status field)"), - colors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Map of field value to color (hex/token)") -}).describe("Row color configuration based on field values"); -var VisualizationTypeSchema2 = external_exports.enum([ - "grid", - "kanban", - "gallery", - "calendar", - "timeline", - "gantt", - "map" -]).describe("Visualization type that users can switch to"); -var UserActionsConfigSchema2 = external_exports.object({ - sort: external_exports.boolean().default(true).describe("Allow users to sort records"), - search: external_exports.boolean().default(true).describe("Allow users to search records"), - filter: external_exports.boolean().default(true).describe("Allow users to filter records"), - rowHeight: external_exports.boolean().default(true).describe("Allow users to toggle row height/density"), - addRecordForm: external_exports.boolean().default(false).describe("Add records through a form instead of inline"), - buttons: external_exports.array(external_exports.string()).optional().describe("Custom action button IDs to show in the toolbar") -}).describe("User action toggles for the view toolbar"); -var AppearanceConfigSchema2 = external_exports.object({ - showDescription: external_exports.boolean().default(true).describe("Show the view description text"), - allowedVisualizations: external_exports.array(VisualizationTypeSchema2).optional().describe('Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])') -}).describe("Appearance and visualization configuration"); -var ViewTabSchema2 = external_exports.object({ - name: SnakeCaseIdentifierSchema6.describe("Tab identifier (snake_case)"), - label: I18nLabelSchema4.optional().describe("Display label"), - icon: external_exports.string().optional().describe("Tab icon name"), - view: external_exports.string().optional().describe("Referenced list view name from listViews"), - filter: external_exports.array(ViewFilterRuleSchema2).optional().describe("Tab-specific filter criteria"), - order: external_exports.number().int().min(0).optional().describe("Tab display order"), - pinned: external_exports.boolean().default(false).describe("Pin tab (cannot be removed by users)"), - isDefault: external_exports.boolean().default(false).describe("Set as the default active tab"), - visible: external_exports.boolean().default(true).describe("Tab visibility") -}).describe("Tab configuration for multi-tab view interface"); -var AddRecordConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Show the add record entry point"), - position: external_exports.enum(["top", "bottom", "both"]).default("bottom").describe("Position of the add record button"), - mode: external_exports.enum(["inline", "form", "modal"]).default("inline").describe("How to add a new record"), - formView: external_exports.string().optional().describe('Named form view to use when mode is "form" or "modal"') -}).describe("Add record entry point configuration"); -var KanbanConfigSchema2 = external_exports.object({ - groupByField: external_exports.string().describe("Field to group columns by (usually status/select)"), - summarizeField: external_exports.string().optional().describe("Field to sum at top of column (e.g. amount)"), - columns: external_exports.array(external_exports.string()).describe("Fields to show on cards") -}); -var CalendarConfigSchema2 = external_exports.object({ - startDateField: external_exports.string(), - endDateField: external_exports.string().optional(), - titleField: external_exports.string(), - colorField: external_exports.string().optional() -}); -var GanttConfigSchema2 = external_exports.object({ - startDateField: external_exports.string(), - endDateField: external_exports.string(), - titleField: external_exports.string(), - progressField: external_exports.string().optional(), - dependenciesField: external_exports.string().optional() -}); -var NavigationModeSchema2 = external_exports.enum([ - "page", - // Navigate to a new route (default) - "drawer", - // Open details in a side drawer/panel - "modal", - // Open details in a modal dialog - "split", - // Show details side-by-side with the list (master-detail) - "popover", - // Show details in a popover (lightweight) - "new_window", - // Open in new browser tab/window - "none" - // No navigation (read-only list) -]); -var NavigationConfigSchema2 = external_exports.object({ - mode: NavigationModeSchema2.default("page"), - /** Target View Config */ - view: external_exports.string().optional().describe('Name of the form view to use for details (e.g. "summary_view", "edit_form")'), - /** Interaction Triggers */ - preventNavigation: external_exports.boolean().default(false).describe("Disable standard navigation entirely"), - openNewTab: external_exports.boolean().default(false).describe("Force open in new tab (applies to page mode)"), - /** Dimensions (for modal/drawer) */ - width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Width of the drawer/modal (e.g. "600px", "50%")') -}); -var ListViewSchema2 = external_exports.object({ - name: SnakeCaseIdentifierSchema6.optional().describe("Internal view name (lowercase snake_case)"), - label: I18nLabelSchema4.optional(), - // Display label override (supports i18n) - type: external_exports.enum([ - "grid", - // Standard Data Table - "kanban", - // Board / Columns - "gallery", - // Card Deck / Masonry - "calendar", - // Monthly/Weekly/Daily - "timeline", - // Chronological Stream (Feed) - "gantt", - // Project Timeline - "map" - // Geospatial - ]).default("grid"), - /** Data Source Configuration */ - data: ViewDataSchema2.optional().describe('Data source configuration (defaults to "object" provider)'), - /** Shared Query Config */ - columns: external_exports.union([ - external_exports.array(external_exports.string()), - // Legacy: simple field names - external_exports.array(ListColumnSchema2) - // Enhanced: detailed column config - ]).describe("Fields to display as columns"), - filter: external_exports.array(ViewFilterRuleSchema2).optional().describe("Filter criteria (JSON Rules)"), - sort: external_exports.union([ - external_exports.string(), - //Legacy "field desc" - external_exports.array(external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]) - })) - ]).optional(), - /** Search & Filter */ - searchableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for search"), - filterableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for end-user filtering in the top bar"), - /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */ - quickFilters: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name to filter by"), - label: external_exports.string().optional().describe("Display label for the chip"), - operator: external_exports.enum(["equals", "not_equals", "contains", "in", "is_null", "is_not_null"]).default("equals").describe("Filter operator"), - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Preset filter value") - })).optional().describe("One-click filter chips for quick record filtering"), - /** Grid Features */ - resizable: external_exports.boolean().optional().describe("Enable column resizing"), - striped: external_exports.boolean().optional().describe("Striped row styling"), - bordered: external_exports.boolean().optional().describe("Show borders"), - /** Selection */ - selection: SelectionConfigSchema2.optional().describe("Row selection configuration"), - /** Navigation / Interaction */ - navigation: NavigationConfigSchema2.optional().describe("Configuration for item click navigation (page, drawer, modal, etc.)"), - /** Pagination */ - pagination: PaginationConfigSchema2.optional().describe("Pagination configuration"), - /** Type Specific Config */ - kanban: KanbanConfigSchema2.optional(), - calendar: CalendarConfigSchema2.optional(), - gantt: GanttConfigSchema2.optional(), - gallery: GalleryConfigSchema2.optional(), - timeline: TimelineConfigSchema2.optional(), - /** View Metadata (Airtable-style view management) */ - description: I18nLabelSchema4.optional().describe("View description for documentation/tooltips"), - sharing: ViewSharingSchema2.optional().describe("View sharing and access configuration"), - /** Row Height / Density (Airtable-style) */ - rowHeight: RowHeightSchema2.optional().describe("Row height / density setting"), - /** Record Grouping (Airtable-style) */ - grouping: GroupingConfigSchema2.optional().describe("Group records by one or more fields"), - /** Row Color (Airtable-style) */ - rowColor: RowColorConfigSchema2.optional().describe("Color rows based on field value"), - /** Field Visibility & Ordering per View (Airtable-style) */ - hiddenFields: external_exports.array(external_exports.string()).optional().describe("Fields to hide in this specific view"), - fieldOrder: external_exports.array(external_exports.string()).optional().describe("Explicit field display order for this view"), - /** Row & Bulk Actions */ - rowActions: external_exports.array(external_exports.string()).optional().describe("Actions available for individual row items"), - bulkActions: external_exports.array(external_exports.string()).optional().describe("Actions available when multiple rows are selected"), - /** Performance */ - virtualScroll: external_exports.boolean().optional().describe("Enable virtual scrolling for large datasets"), - /** Conditional Formatting */ - conditionalFormatting: external_exports.array(external_exports.object({ - condition: external_exports.string().describe("Condition expression to evaluate"), - style: external_exports.record(external_exports.string(), external_exports.string()).describe("CSS styles to apply when condition is true") - })).optional().describe("Conditional formatting rules for list rows"), - /** Inline Edit */ - inlineEdit: external_exports.boolean().optional().describe("Allow inline editing of records directly in the list view"), - /** Export */ - exportOptions: external_exports.array(external_exports.enum(["csv", "xlsx", "pdf", "json"])).optional().describe("Available export format options"), - /** User Actions (Airtable Interface parity) */ - userActions: UserActionsConfigSchema2.optional().describe("User action toggles for the view toolbar"), - /** Appearance (Airtable Interface parity) */ - appearance: AppearanceConfigSchema2.optional().describe("Appearance and visualization configuration"), - /** Tabs (Airtable Interface parity) */ - tabs: external_exports.array(ViewTabSchema2).optional().describe("Tab definitions for multi-tab view interface"), - /** Add Record (Airtable Interface parity) */ - addRecord: AddRecordConfigSchema2.optional().describe("Add record entry point configuration"), - /** Record Count Display (Airtable Interface parity) */ - showRecordCount: external_exports.boolean().optional().describe("Show record count at the bottom of the list"), - /** Advanced: Allow Printing (Airtable Interface parity) */ - allowPrinting: external_exports.boolean().optional().describe("Allow users to print the view"), - /** Empty State */ - emptyState: external_exports.object({ - title: I18nLabelSchema4.optional(), - message: I18nLabelSchema4.optional(), - icon: external_exports.string().optional() - }).optional().describe("Empty state configuration when no records found"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes for the list view"), - /** Responsive layout overrides per breakpoint */ - responsive: ResponsiveConfigSchema2.optional().describe("Responsive layout configuration"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema2.optional().describe("Performance optimization settings") -}); -var FormFieldSchema2 = external_exports.object({ - field: external_exports.string().describe("Field name (snake_case)"), - label: I18nLabelSchema4.optional().describe("Display label override"), - placeholder: I18nLabelSchema4.optional().describe("Placeholder text"), - helpText: I18nLabelSchema4.optional().describe("Help/hint text"), - readonly: external_exports.boolean().optional().describe("Read-only override"), - required: external_exports.boolean().optional().describe("Required override"), - hidden: external_exports.boolean().optional().describe("Hidden override"), - colSpan: external_exports.number().int().min(1).max(4).optional().describe("Column span in grid layout (1-4)"), - widget: external_exports.string().optional().describe("Custom widget/component name"), - dependsOn: external_exports.string().optional().describe("Parent field name for cascading"), - visibleOn: external_exports.string().optional().describe("Visibility condition expression") -}); -var FormSectionSchema2 = external_exports.object({ - label: I18nLabelSchema4.optional(), - collapsible: external_exports.boolean().default(false), - collapsed: external_exports.boolean().default(false), - columns: external_exports.enum(["1", "2", "3", "4"]).default("2").transform((val) => parseInt(val)), - fields: external_exports.array(external_exports.union([ - external_exports.string(), - // Legacy: simple field name - FormFieldSchema2 - // Enhanced: detailed field config - ])) -}); -var FormViewSchema2 = external_exports.object({ - type: external_exports.enum([ - "simple", - // Single column or sections - "tabbed", - // Tabs - "wizard", - // Step by step - "split", - // Master-Detail split - "drawer", - // Side panel - "modal" - // Dialog - ]).default("simple"), - /** Data Source Configuration */ - data: ViewDataSchema2.optional().describe('Data source configuration (defaults to "object" provider)'), - sections: external_exports.array(FormSectionSchema2).optional(), - // For simple layout - groups: external_exports.array(FormSectionSchema2).optional(), - // Legacy support -> alias to sections - /** Default Sort for Related Lists (e.g., sort child records by date) */ - defaultSort: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - order: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction") - })).optional().describe("Default sort order for related list views within this form"), - /** Public form sharing configuration */ - sharing: SharingConfigSchema2.optional().describe("Public sharing configuration for this form"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes for the form view") -}); -var ViewSchema2 = external_exports.object({ - list: ListViewSchema2.optional(), - // Default list view - form: FormViewSchema2.optional(), - // Default form view - listViews: external_exports.record(external_exports.string(), ListViewSchema2).optional().describe("Additional named list views"), - formViews: external_exports.record(external_exports.string(), FormViewSchema2).optional().describe("Additional named form views") -}); -var FieldReferenceSchema3 = external_exports.object({ - $field: external_exports.string().describe("Field Reference/Column Name") -}); -external_exports.object({ - /** Equal to (default) - SQL: = | MongoDB: $eq */ - $eq: external_exports.any().optional(), - /** Not equal to - SQL: <> or != | MongoDB: $ne */ - $ne: external_exports.any().optional() -}); -external_exports.object({ - /** Greater than - SQL: > | MongoDB: $gt */ - $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), - /** Greater than or equal to - SQL: >= | MongoDB: $gte */ - $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), - /** Less than - SQL: < | MongoDB: $lt */ - $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), - /** Less than or equal to - SQL: <= | MongoDB: $lte */ - $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional() -}); -external_exports.object({ - /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */ - $in: external_exports.array(external_exports.any()).optional(), - /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */ - $nin: external_exports.array(external_exports.any()).optional() -}); -external_exports.object({ - /** Between (inclusive) - takes [min, max] array */ - $between: external_exports.tuple([ - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]), - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]) - ]).optional() -}); -external_exports.object({ - /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */ - $contains: external_exports.string().optional(), - /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */ - $notContains: external_exports.string().optional(), - /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */ - $startsWith: external_exports.string().optional(), - /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */ - $endsWith: external_exports.string().optional() -}); -external_exports.object({ - /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */ - $null: external_exports.boolean().optional(), - /** Field exists check (primarily for NoSQL) - MongoDB: $exists */ - $exists: external_exports.boolean().optional() -}); -var FieldOperatorsSchema3 = external_exports.object({ - // Equality - $eq: external_exports.any().optional(), - $ne: external_exports.any().optional(), - // Comparison (numeric/date) - $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), - $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), - $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), - $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]).optional(), - // Set & Range - $in: external_exports.array(external_exports.any()).optional(), - $nin: external_exports.array(external_exports.any()).optional(), - $between: external_exports.tuple([ - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]), - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema3]) - ]).optional(), - // String-specific - $contains: external_exports.string().optional(), - $notContains: external_exports.string().optional(), - $startsWith: external_exports.string().optional(), - $endsWith: external_exports.string().optional(), - // Special - $null: external_exports.boolean().optional(), - $exists: external_exports.boolean().optional() -}); -var FilterConditionSchema3 = external_exports.lazy( - () => external_exports.record(external_exports.string(), external_exports.unknown()).and( - external_exports.object({ - $and: external_exports.array(FilterConditionSchema3).optional(), - $or: external_exports.array(FilterConditionSchema3).optional(), - $not: FilterConditionSchema3.optional() - }) - ) -); -external_exports.object({ - where: FilterConditionSchema3.optional() -}); -var NormalizedFilterSchema3 = external_exports.lazy( - () => external_exports.object({ - $and: external_exports.array( - external_exports.union([ - // Field condition: { field: { $op: value } } - external_exports.record(external_exports.string(), FieldOperatorsSchema3), - // Nested logical group - NormalizedFilterSchema3 - ]) - ).optional(), - $or: external_exports.array( - external_exports.union([ - external_exports.record(external_exports.string(), FieldOperatorsSchema3), - NormalizedFilterSchema3 - ]) - ).optional(), - $not: external_exports.union([ - external_exports.record(external_exports.string(), FieldOperatorsSchema3), - NormalizedFilterSchema3 - ]).optional() - }) -); -var WidgetColorVariantSchema = external_exports.enum([ - "default", - "blue", - "teal", - "orange", - "purple", - "success", - "warning", - "danger" -]).describe("Widget color variant"); -var WidgetActionTypeSchema = external_exports.enum([ - "script", - "url", - "modal", - "flow", - "api" -]).describe("Widget action type"); -var DashboardHeaderActionSchema = external_exports.object({ - /** Action label */ - label: I18nLabelSchema4.describe("Action button label"), - /** Action URL or target */ - actionUrl: external_exports.string().describe("URL or target for the action"), - /** Action type */ - actionType: WidgetActionTypeSchema.optional().describe("Type of action"), - /** Icon identifier */ - icon: external_exports.string().optional().describe("Icon identifier for the action button") -}).describe("Dashboard header action"); -var DashboardHeaderSchema = external_exports.object({ - /** Whether to show the dashboard title in the header */ - showTitle: external_exports.boolean().default(true).describe("Show dashboard title in header"), - /** Whether to show the dashboard description in the header */ - showDescription: external_exports.boolean().default(true).describe("Show dashboard description in header"), - /** Action buttons displayed in the header */ - actions: external_exports.array(DashboardHeaderActionSchema).optional().describe("Header action buttons") -}).describe("Dashboard header configuration"); -var WidgetMeasureSchema = external_exports.object({ - /** Value field to aggregate */ - valueField: external_exports.string().describe("Field to aggregate"), - /** Aggregate function */ - aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).default("count").describe("Aggregate function"), - /** Display label for the measure */ - label: I18nLabelSchema4.optional().describe("Measure display label"), - /** Number format string (e.g., "$0,0.00", "0.0%") */ - format: external_exports.string().optional().describe("Number format string") -}).describe("Widget measure definition"); -var DashboardWidgetSchema = external_exports.object({ - /** Unique widget identifier (snake_case, used for targetWidgets references) */ - id: SnakeCaseIdentifierSchema6.describe("Unique widget identifier (snake_case)"), - /** Widget Title */ - title: I18nLabelSchema4.optional().describe("Widget title"), - /** Widget Description (displayed below the title) */ - description: I18nLabelSchema4.optional().describe("Widget description text below the header"), - /** Visualization Type */ - type: ChartTypeSchema.default("metric").describe("Visualization type"), - /** Chart Configuration */ - chartConfig: ChartConfigSchema.optional().describe("Chart visualization configuration"), - /** Color variant for the widget (e.g., KPI card accent color) */ - colorVariant: WidgetColorVariantSchema.optional().describe("Widget color variant for theming"), - /** Action URL for the widget header action button */ - actionUrl: external_exports.string().optional().describe("URL or target for the widget action button"), - /** Action type for the widget header action button */ - actionType: WidgetActionTypeSchema.optional().describe("Type of action for the widget action button"), - /** Icon for the widget header action button */ - actionIcon: external_exports.string().optional().describe("Icon identifier for the widget action button"), - /** Data Source Object */ - object: external_exports.string().optional().describe("Data source object name"), - /** Data Filter (MongoDB-style FilterCondition) */ - filter: FilterConditionSchema3.optional().describe("Data filter criteria"), - /** Category Field (X-Axis / Group By) */ - categoryField: external_exports.string().optional().describe("Field for grouping (X-Axis)"), - /** Value Field (Y-Axis) */ - valueField: external_exports.string().optional().describe("Field for values (Y-Axis)"), - /** Aggregate operation */ - aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).optional().default("count").describe("Aggregate function"), - /** Multi-measure definitions for pivot/matrix widgets */ - measures: external_exports.array(WidgetMeasureSchema).optional().describe("Multiple measures for pivot/matrix analysis"), - /** - * Layout Position (React-Grid-Layout style) - * x: column (0-11) - * y: row - * w: width (1-12) - * h: height - */ - layout: external_exports.object({ - x: external_exports.number(), - y: external_exports.number(), - w: external_exports.number(), - h: external_exports.number() - }).describe("Grid layout position"), - /** Widget specific options (colors, legend, etc.) */ - options: external_exports.unknown().optional().describe("Widget specific configuration"), - /** Responsive layout overrides per breakpoint */ - responsive: ResponsiveConfigSchema2.optional().describe("Responsive layout configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var GlobalFilterOptionsFromSchema = external_exports.object({ - /** Source object name to fetch options from */ - object: external_exports.string().describe("Source object name"), - /** Field to use as option value */ - valueField: external_exports.string().describe("Field to use as option value"), - /** Field to use as option label */ - labelField: external_exports.string().describe("Field to use as option label"), - /** Optional filter to apply when fetching options */ - filter: FilterConditionSchema3.optional().describe("Filter to apply to source object") -}).describe("Dynamic filter options from object"); -var GlobalFilterSchema = external_exports.object({ - /** Field name to filter on */ - field: external_exports.string().describe("Field name to filter on"), - /** Display label for the filter */ - label: I18nLabelSchema4.optional().describe("Display label for the filter"), - /** Filter input type */ - type: external_exports.enum(["text", "select", "date", "number", "lookup"]).optional().describe("Filter input type"), - /** Static options for select/lookup filters */ - options: external_exports.array(external_exports.object({ - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).describe("Option value"), - label: I18nLabelSchema4 - })).optional().describe("Static filter options"), - /** Dynamic data binding for filter options */ - optionsFrom: GlobalFilterOptionsFromSchema.optional().describe("Dynamic filter options from object"), - /** Default filter value */ - defaultValue: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Default filter value"), - /** Filter application scope */ - scope: external_exports.enum(["dashboard", "widget"]).default("dashboard").describe("Filter application scope"), - /** Widget IDs to apply this filter to (when scope is widget) */ - targetWidgets: external_exports.array(external_exports.string()).optional().describe("Widget IDs to apply this filter to") -}); -var DashboardSchema = external_exports.object({ - /** Machine name */ - name: SnakeCaseIdentifierSchema6.describe("Dashboard unique name"), - /** Display label */ - label: I18nLabelSchema4.describe("Dashboard label"), - /** Description */ - description: I18nLabelSchema4.optional().describe("Dashboard description"), - /** Structured header configuration */ - header: DashboardHeaderSchema.optional().describe("Dashboard header configuration"), - /** Collection of widgets */ - widgets: external_exports.array(DashboardWidgetSchema).describe("Widgets to display"), - /** Auto-refresh */ - refreshInterval: external_exports.number().optional().describe("Auto-refresh interval in seconds"), - /** Dashboard Date Range (Global time filter) */ - dateRange: external_exports.object({ - field: external_exports.string().optional().describe("Default date field name for time-based filtering"), - defaultRange: external_exports.enum(["today", "yesterday", "this_week", "last_week", "this_month", "last_month", "this_quarter", "last_quarter", "this_year", "last_year", "last_7_days", "last_30_days", "last_90_days", "custom"]).default("this_month").describe("Default date range preset"), - allowCustomRange: external_exports.boolean().default(true).describe("Allow users to pick a custom date range") - }).optional().describe("Global dashboard date range filter configuration"), - /** Global Filters */ - globalFilters: external_exports.array(GlobalFilterSchema).optional().describe("Global filters that apply to all widgets in the dashboard"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema2.optional().describe("Performance optimization settings") -}); -var ReportType = external_exports.enum([ - "tabular", - // Simple list - "summary", - // Grouped by row - "matrix", - // Grouped by row and column - "joined" - // Joined multiple blocks -]); -var ReportColumnSchema = external_exports.object({ - field: external_exports.string().describe("Field name"), - label: I18nLabelSchema4.optional().describe("Override label"), - aggregate: external_exports.enum(["sum", "avg", "max", "min", "count", "unique"]).optional().describe("Aggregation function"), - /** Responsive visibility/priority per breakpoint */ - responsive: ResponsiveConfigSchema2.optional().describe("Responsive visibility for this column") -}); -var ReportGroupingSchema = external_exports.object({ - field: external_exports.string().describe("Field to group by"), - sortOrder: external_exports.enum(["asc", "desc"]).default("asc"), - dateGranularity: external_exports.enum(["day", "week", "month", "quarter", "year"]).optional().describe("For date fields") -}); -var ReportChartSchema = ChartConfigSchema.extend({ - /** Report-specific chart configuration */ - xAxis: external_exports.string().describe("Grouping field for X-Axis"), - yAxis: external_exports.string().describe("Summary field for Y-Axis"), - groupBy: external_exports.string().optional().describe("Additional grouping field") -}); -var ReportSchema = external_exports.object({ - /** Identity */ - name: SnakeCaseIdentifierSchema6.describe("Report unique name"), - label: I18nLabelSchema4.describe("Report label"), - description: I18nLabelSchema4.optional(), - /** Data Source */ - objectName: external_exports.string().describe("Primary object"), - /** Report Configuration */ - type: ReportType.default("tabular").describe("Report format type"), - columns: external_exports.array(ReportColumnSchema).describe("Columns to display"), - /** Grouping (for Summary/Matrix) */ - groupingsDown: external_exports.array(ReportGroupingSchema).optional().describe("Row groupings"), - groupingsAcross: external_exports.array(ReportGroupingSchema).optional().describe("Column groupings (Matrix only)"), - /** Filtering (MongoDB-style FilterCondition) */ - filter: FilterConditionSchema3.optional().describe("Filter criteria"), - /** Visualization */ - chart: ReportChartSchema.optional().describe("Embedded chart configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema2.optional().describe("Performance optimization settings") -}); -var EncryptionAlgorithmSchema5 = external_exports.enum([ - "aes-256-gcm", - "aes-256-cbc", - "chacha20-poly1305" -]).describe("Supported encryption algorithm"); -var KeyManagementProviderSchema5 = external_exports.enum([ - "local", - "aws-kms", - "azure-key-vault", - "gcp-kms", - "hashicorp-vault" -]).describe("Key management service provider"); -var KeyRotationPolicySchema5 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), - frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), - retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), - autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") -}).describe("Policy for automatic encryption key rotation"); -var EncryptionConfigSchema5 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), - algorithm: EncryptionAlgorithmSchema5.default("aes-256-gcm").describe("Encryption algorithm"), - keyManagement: external_exports.object({ - provider: KeyManagementProviderSchema5.describe("Key management service provider"), - keyId: external_exports.string().optional().describe("Key identifier in the provider"), - rotationPolicy: KeyRotationPolicySchema5.optional().describe("Key rotation policy") - }).describe("Key management configuration"), - scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), - deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), - searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") -}).describe("Field-level encryption configuration"); -external_exports.object({ - fieldName: external_exports.string().describe("Name of the field to encrypt"), - encryptionConfig: EncryptionConfigSchema5.describe("Encryption settings for this field"), - indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") -}).describe("Per-field encryption assignment"); -var MaskingStrategySchema5 = external_exports.enum([ - "redact", - // Complete redaction: **** - "partial", - // Partial masking: 138****5678 - "hash", - // Hash value: sha256(value) - "tokenize", - // Tokenization: token-12345 - "randomize", - // Randomize: generate random value - "nullify", - // Null value: null - "substitute" - // Substitute with dummy data -]).describe("Data masking strategy for PII protection"); -var MaskingRuleSchema5 = external_exports.object({ - field: external_exports.string().describe("Field name to apply masking to"), - strategy: MaskingStrategySchema5.describe("Masking strategy to use"), - pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), - preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), - preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), - roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), - exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") -}).describe("Masking rule for a single field"); -external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable data masking"), - rules: external_exports.array(MaskingRuleSchema5).describe("List of field-level masking rules"), - auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") -}).describe("Top-level data masking configuration for PII protection"); -var FieldType5 = external_exports.enum([ - // Core Text - "text", - "textarea", - "email", - "url", - "phone", - "password", - // Rich Content - "markdown", - "html", - "richtext", - // Numbers - "number", - "currency", - "percent", - // Date & Time - "date", - "datetime", - "time", - // Logic - "boolean", - "toggle", - // Toggle is a distinct UI from checkbox - // Selection - "select", - // Single select dropdown - "multiselect", - // Multi select (often tags) - "radio", - // Radio group - "checkboxes", - // Checkbox group - // Relational - "lookup", - "master_detail", - // Dynamic reference - "tree", - // Hierarchical reference - // Media - "image", - "file", - "avatar", - "video", - "audio", - // Calculated / System - "formula", - "summary", - "autonumber", - // Enhanced Types - "location", - // GPS coordinates - "address", - // Structured address - "code", - // Code editor (JSON/SQL/JS) - "json", - // Structured JSON data - "color", - // Color picker - "rating", - // Star rating - "slider", - // Numeric slider - "signature", - // Digital signature - "qrcode", - // QR code / Barcode - "progress", - // Progress bar - "tags", - // Simple tag list - // AI/ML Types - "vector" - // Vector embeddings for AI/ML (semantic search, RAG) -]); -var SelectOptionSchema5 = external_exports.object({ - label: external_exports.string().describe("Display label (human-readable, any case allowed)"), - value: SystemIdentifierSchema5.describe("Stored value (lowercase machine identifier)"), - color: external_exports.string().optional().describe("Color code for badges/charts"), - default: external_exports.boolean().optional().describe("Is default option") -}); -external_exports.object({ - latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), - longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), - altitude: external_exports.number().optional().describe("Altitude in meters"), - accuracy: external_exports.number().optional().describe("Accuracy in meters") -}); -var CurrencyConfigSchema5 = external_exports.object({ - precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), - currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), - defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") -}); -external_exports.object({ - value: external_exports.number().describe("Monetary amount"), - currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") -}); -external_exports.object({ - street: external_exports.string().optional().describe("Street address"), - city: external_exports.string().optional().describe("City name"), - state: external_exports.string().optional().describe("State/Province"), - postalCode: external_exports.string().optional().describe("Postal/ZIP code"), - country: external_exports.string().optional().describe("Country name or code"), - countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), - formatted: external_exports.string().optional().describe("Formatted address string") -}); -var VectorConfigSchema5 = external_exports.object({ - dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), - distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), - normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), - indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), - indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") -}); -var FileAttachmentConfigSchema5 = external_exports.object({ - /** File Size Limits */ - minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), - maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), - /** File Type Restrictions */ - allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), - blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), - allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), - blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), - /** Virus Scanning */ - virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), - virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), - virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), - quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), - /** Storage Configuration */ - storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), - storageBucket: external_exports.string().optional().describe("Target bucket name"), - storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), - /** Image-Specific Validation */ - imageValidation: external_exports.object({ - minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), - maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), - minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), - maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), - aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), - generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), - thumbnailSizes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), - width: external_exports.number().min(1).describe("Thumbnail width in pixels"), - height: external_exports.number().min(1).describe("Thumbnail height in pixels"), - crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") - })).optional().describe("Thumbnail size configurations"), - preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), - autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") - }).optional().describe("Image-specific validation rules"), - /** Upload Behavior */ - allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), - allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), - allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), - requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), - /** Metadata Extraction */ - extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), - extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), - /** Versioning */ - versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), - maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), - /** Access Control */ - publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), - presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") -}).refine((data) => { - if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { - return false; - } - return true; -}, { - message: "minSize must be less than or equal to maxSize" -}).refine((data) => { - if (data.virusScanProvider !== void 0 && data.virusScan !== true) { - return false; - } - return true; -}, { - message: "virusScanProvider requires virusScan to be enabled" -}); -var DataQualityRulesSchema5 = external_exports.object({ - /** Enforce uniqueness constraint */ - uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), - /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ - completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), - /** Accuracy validation against authoritative source */ - accuracy: external_exports.object({ - source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), - threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") - }).optional().describe("Accuracy validation configuration") -}); -var ComputedFieldCacheSchema5 = external_exports.object({ - /** Enable caching for this computed field */ - enabled: external_exports.boolean().describe("Enable caching for computed field results"), - /** Time-to-live in seconds */ - ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), - /** Array of field paths that trigger cache invalidation when changed */ - invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') -}); -var FieldSchema4 = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), - label: external_exports.string().optional().describe("Human readable label"), - type: FieldType5.describe("Field Data Type"), - description: external_exports.string().optional().describe("Tooltip/Help text"), - format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), - /** Storage Layer Mapping */ - columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), - /** Database Constraints */ - required: external_exports.boolean().default(false).describe("Is required"), - searchable: external_exports.boolean().default(false).describe("Is searchable"), - multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), - unique: external_exports.boolean().default(false).describe("Is unique constraint"), - defaultValue: external_exports.unknown().optional().describe("Default value"), - /** Text/String Constraints */ - maxLength: external_exports.number().optional().describe("Max character length"), - minLength: external_exports.number().optional().describe("Min character length"), - /** Number Constraints */ - precision: external_exports.number().optional().describe("Total digits"), - scale: external_exports.number().optional().describe("Decimal places"), - min: external_exports.number().optional().describe("Minimum value"), - max: external_exports.number().optional().describe("Maximum value"), - /** Selection Options */ - options: external_exports.array(SelectOptionSchema5).optional().describe("Static options for select/multiselect"), - /** - * Relationship Config - * - * Used by `lookup` and `master_detail` field types to define cross-object references. - * The `reference` property is **required** for these types — it identifies the target - * object whose records this field links to. The engine uses `reference` during $expand - * post-processing to resolve foreign key IDs into full related objects via batch queries. - * - * For `master_detail` fields, the parent record controls the lifecycle of child records - * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. - */ - reference: external_exports.string().optional().describe( - "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." - ), - referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), - writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), - deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), - /** Calculation */ - expression: external_exports.string().optional().describe("Formula expression"), - summaryOperations: external_exports.object({ - object: external_exports.string().describe("Source child object name for roll-up"), - field: external_exports.string().describe("Field on child object to aggregate"), - function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") - }).optional().describe("Roll-up summary definition"), - /** Enhanced Field Type Configurations */ - // Code field config - language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), - theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), - lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), - // Rating field config - maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), - allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), - // Location field config - displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), - allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), - // Address field config - addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), - // Color field config - colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), - allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), - presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), - // Slider field config - step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), - showValue: external_exports.boolean().optional().describe("Display current value on slider"), - marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), - // QR Code / Barcode field config - // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' - // Runtime validation should enforce this constraint - barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), - qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), - displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), - allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), - // Currency field config - currencyConfig: CurrencyConfigSchema5.optional().describe("Configuration for currency field type"), - // Vector field config - vectorConfig: VectorConfigSchema5.optional().describe("Configuration for vector field type (AI/ML embeddings)"), - // File attachment field config - fileAttachmentConfig: FileAttachmentConfigSchema5.optional().describe("Configuration for file and attachment field types"), - /** Enhanced Security & Compliance */ - // Encryption configuration - encryptionConfig: EncryptionConfigSchema5.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), - // Data masking rules - maskingRule: MaskingRuleSchema5.optional().describe("Data masking rules for PII protection"), - // Audit trail - auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), - /** Field Dependencies & Relationships */ - // Field dependencies - dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), - /** Computed Field Optimization */ - // Computed field caching - cached: ComputedFieldCacheSchema5.optional().describe("Caching configuration for computed/formula fields"), - /** Data Quality & Governance */ - // Data quality rules - dataQuality: DataQualityRulesSchema5.optional().describe("Data quality validation and monitoring rules"), - /** Layout & Grouping */ - group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), - /** Conditional Requirements */ - conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), - /** Security & Visibility */ - hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), - readonly: external_exports.boolean().default(false).describe("Read-only in UI"), - sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), - inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), - trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), - caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), - autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), - /** Indexing */ - index: external_exports.boolean().default(false).describe("Create standard database index"), - externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") -}); -var ActionParamSchema4 = external_exports.object({ - name: external_exports.string(), - label: I18nLabelSchema4, - type: FieldType5, - required: external_exports.boolean().default(false), - options: external_exports.array(external_exports.object({ label: I18nLabelSchema4, value: external_exports.string() })).optional() -}); -var ActionType4 = external_exports.enum(["script", "url", "modal", "flow", "api"]); -var TARGET_REQUIRED_TYPES4 = new Set( - ActionType4.options.filter((t) => t !== "script") -); -var ActionSchema4 = external_exports.object({ - /** Machine name of the action */ - name: SnakeCaseIdentifierSchema6.describe("Machine name (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema4.describe("Display label"), - /** Target object this action belongs to (optional, snake_case) */ - objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Icon name"), - /** Where does this action appear? */ - locations: external_exports.array(external_exports.enum([ - "list_toolbar", - "list_item", - "record_header", - "record_more", - "record_related", - "global_nav" - ])).optional().describe("Locations where this action is visible"), - /** - * Visual Component Type - * Defaults to 'button' or 'menu_item' based on location, - * but can be overridden. - */ - component: external_exports.enum([ - "action:button", - // Standard Button - "action:icon", - // Icon only - "action:menu", - // Dropdown menu - "action:group" - // Button Group - ]).optional().describe("Visual component override"), - /** What type of interaction? */ - type: ActionType4.default("script").describe("Action functionality type"), - /** - * Payload / Target — the canonical binding for the action handler. - * Required for url, flow, modal, and api types. - * Recommended for script type. - */ - target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), - /** - * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. - */ - execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), - /** User Input Requirements */ - params: external_exports.array(ActionParamSchema4).optional().describe("Input parameters required from user"), - /** Visual Style */ - variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), - /** UX Behavior */ - confirmText: I18nLabelSchema4.optional().describe("Confirmation message before execution"), - successMessage: I18nLabelSchema4.optional().describe("Success message to show after execution"), - refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), - /** Access */ - visible: external_exports.string().optional().describe("Formula returning boolean"), - disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), - /** Keyboard Shortcut */ - shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), - /** Bulk Operations */ - bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), - /** Execution */ - timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}).transform((data) => { - if (data.execute && !data.target) { - return { ...data, target: data.execute }; - } - return data; -}).refine((data) => { - if (TARGET_REQUIRED_TYPES4.has(data.type) && !data.target) { - return false; - } - return true; -}, { - message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", - path: ["target"] -}); -external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "percentile", - "median", - "stddev", - "variance" -]).describe("Standard aggregation functions"); -var SortDirectionEnum3 = external_exports.enum(["asc", "desc"]).describe("Sort order direction"); -var SortItemSchema2 = external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - order: SortDirectionEnum3.describe("Sort direction") -}).describe("Sort field and direction pair"); -external_exports.enum([ - "insert", - "update", - "delete", - "upsert" -]).describe("Data mutation event types"); -external_exports.enum([ - "read_uncommitted", - "read_committed", - "repeatable_read", - "serializable", - "snapshot" -]).describe("Transaction isolation levels (snake_case standard)"); -external_exports.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy"); -var PageRegionSchema = external_exports.object({ - name: external_exports.string().describe('Region name (e.g. "sidebar", "main", "header")'), - width: external_exports.enum(["small", "medium", "large", "full"]).optional(), - components: external_exports.array(external_exports.lazy(() => PageComponentSchema)).describe("Components in this region") -}); -var PageComponentType = external_exports.enum([ - // Structure - "page:header", - "page:footer", - "page:sidebar", - "page:tabs", - "page:accordion", - "page:card", - "page:section", - // Record Context - "record:details", - "record:highlights", - "record:related_list", - "record:activity", - "record:chatter", - "record:path", - // Navigation - "app:launcher", - "nav:menu", - "nav:breadcrumb", - // Utility - "global:search", - "global:notifications", - "user:profile", - // AI - "ai:chat_window", - "ai:suggestion", - // Content Elements (Airtable Interface parity) - "element:text", - "element:number", - "element:image", - "element:divider", - // Interactive Elements (Phase B — Element Library) - "element:button", - "element:filter", - "element:form", - "element:record_picker" -]); -var ElementDataSourceSchema = external_exports.object({ - object: external_exports.string().describe("Object to query"), - view: external_exports.string().optional().describe("Named view to apply"), - filter: FilterConditionSchema3.optional().describe("Additional filter criteria"), - sort: external_exports.array(SortItemSchema2).optional().describe("Sort order"), - limit: external_exports.number().int().positive().optional().describe("Max records to display") -}); -var PageComponentSchema = external_exports.object({ - /** Definition */ - type: external_exports.union([ - PageComponentType, - external_exports.string() - ]).describe("Component Type (Standard enum or custom string)"), - id: external_exports.string().optional().describe("Unique instance ID"), - /** Configuration */ - label: I18nLabelSchema4.optional(), - properties: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Component props passed to the widget. See component.zod.ts for schemas."), - /** - * Event Handlers - * Map event names to Action expressions. - * "onClick": "set_variable('userId', $event.id)" - * "onRowSelect": "navigate_to('page_detail', { id: $event.id })" - */ - events: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Event handlers map"), - /** Appearance */ - style: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Inline styles or utility classes"), - className: external_exports.string().optional().describe("CSS class names"), - /** Visibility Rule */ - visibility: external_exports.string().optional().describe("Visibility filter/formula"), - /** Per-element data binding, overrides page-level object context */ - dataSource: ElementDataSourceSchema.optional().describe("Per-element data binding for multi-object pages"), - /** Responsive layout overrides per breakpoint */ - responsive: ResponsiveConfigSchema2.optional().describe("Responsive layout configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var PageVariableSchema = external_exports.object({ - name: external_exports.string().describe("Variable name"), - type: external_exports.enum(["string", "number", "boolean", "object", "array", "record_id"]).default("string"), - defaultValue: external_exports.unknown().optional(), - /** Source element binding (e.g. element:record_picker writes to this variable) */ - source: external_exports.string().optional().describe("Component ID that writes to this variable") -}); -var BlankPageLayoutItemSchema = external_exports.object({ - componentId: external_exports.string().describe("Reference to a PageComponent.id in the page"), - x: external_exports.number().int().min(0).describe("Grid column position (0-based)"), - y: external_exports.number().int().min(0).describe("Grid row position (0-based)"), - width: external_exports.number().int().min(1).describe("Width in grid columns"), - height: external_exports.number().int().min(1).describe("Height in grid rows") -}); -var BlankPageLayoutSchema = external_exports.object({ - columns: external_exports.number().int().min(1).default(12).describe("Number of grid columns"), - rowHeight: external_exports.number().int().min(1).default(40).describe("Height of each grid row in pixels"), - gap: external_exports.number().int().min(0).default(8).describe("Gap between grid items in pixels"), - items: external_exports.array(BlankPageLayoutItemSchema).describe("Positioned components on the canvas") -}); -var PageTypeSchema = external_exports.enum([ - // Platform page types (Salesforce FlexiPage style) - "record", - // Component-based record layout page with regions - "home", - // Platform-level home/landing page - "app", - // App-level page with navigation context - "utility", - // Floating utility panel (e.g. notes, phone dialer) - // Interface page types (Airtable Interface parity) - "dashboard", - // KPI summary with charts/metrics - "grid", - // Spreadsheet-like data table - "list", - // Record list with quick actions - "gallery", - // Card-based visual browsing - "kanban", - // Status-based board - "calendar", - // Date-based scheduling - "timeline", - // Gantt-like project timeline - "form", - // Data entry form - "record_detail", - // Auto-generated single record field display - "record_review", - // Sequential record review/approval - "overview", - // Interface-level navigation/landing hub - "blank" - // Free-form canvas for custom composition -]).describe("Page type \u2014 platform or interface page types"); -var RecordReviewConfigSchema = external_exports.object({ - object: external_exports.string().describe("Target object for review"), - filter: FilterConditionSchema3.optional().describe("Filter criteria for review queue"), - sort: external_exports.array(SortItemSchema2).optional().describe("Sort order for review queue"), - displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on the review page"), - actions: external_exports.array(external_exports.object({ - label: external_exports.string().describe("Action button label"), - type: external_exports.enum(["approve", "reject", "skip", "custom"]).describe("Action type"), - field: external_exports.string().optional().describe("Field to update on action"), - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Value to set on action"), - nextRecord: external_exports.boolean().optional().default(true).describe("Auto-advance to next record after action") - })).describe("Review actions"), - navigation: external_exports.enum(["sequential", "random", "filtered"]).optional().default("sequential").describe("Record navigation mode"), - showProgress: external_exports.boolean().optional().default(true).describe("Show review progress indicator") -}); -var InterfacePageConfigSchema = external_exports.object({ - /** Data binding */ - source: external_exports.string().optional().describe("Source object name for the page"), - levels: external_exports.number().int().min(1).optional().describe("Number of hierarchy levels to display"), - filterBy: external_exports.array(ViewFilterRuleSchema2).optional().describe("Page-level filter criteria"), - /** Appearance */ - appearance: AppearanceConfigSchema2.optional().describe("Appearance and visualization configuration"), - /** User filters */ - userFilters: external_exports.object({ - elements: external_exports.array(external_exports.enum(["grid", "gallery", "kanban"])).optional().describe("Visualization element types available in user filter bar"), - tabs: external_exports.array(ViewTabSchema2).optional().describe("User-configurable tabs") - }).optional().describe("User filter configuration"), - /** User actions */ - userActions: UserActionsConfigSchema2.optional().describe("User action toggles"), - /** Add record */ - addRecord: AddRecordConfigSchema2.optional().describe("Add record entry point configuration"), - /** Record count */ - showRecordCount: external_exports.boolean().optional().describe("Show record count at page bottom"), - /** Advanced */ - allowPrinting: external_exports.boolean().optional().describe("Allow users to print the page") -}).describe("Interface-level page configuration (Airtable parity)"); -var PageSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema6.describe("Page unique name (lowercase snake_case)"), - label: I18nLabelSchema4, - description: I18nLabelSchema4.optional(), - /** Icon (used in interface navigation) */ - icon: external_exports.string().optional().describe("Page icon name"), - /** Page Type */ - type: PageTypeSchema.default("record").describe("Page type"), - /** Page State Definitions */ - variables: external_exports.array(PageVariableSchema).optional().describe("Local page state variables"), - /** Context */ - object: external_exports.string().optional().describe("Bound object (for Record pages)"), - /** Record Review Configuration (only for record_review pages) */ - recordReview: RecordReviewConfigSchema.optional().describe('Record review configuration (required when type is "record_review")'), - /** Blank Page Layout (only for blank pages) */ - blankLayout: BlankPageLayoutSchema.optional().describe('Free-form grid layout for blank pages (used when type is "blank")'), - /** Layout Template */ - template: external_exports.string().default("default").describe('Layout template name (e.g. "header-sidebar-main")'), - /** Regions & Content */ - regions: external_exports.array(PageRegionSchema).describe("Defined regions with components"), - /** Activation */ - isDefault: external_exports.boolean().default(false), - assignedProfiles: external_exports.array(external_exports.string()).optional(), - /** Interface Page Configuration (Airtable Interface parity) */ - interfaceConfig: InterfacePageConfigSchema.optional().describe("Interface-level page configuration (for Airtable-style interface pages)"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}).superRefine((data, ctx) => { - if (data.type === "record_review" && !data.recordReview) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - path: ["recordReview"], - message: 'recordReview is required when type is "record_review"' - }); - } - if (data.type === "blank" && !data.blankLayout) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - path: ["blankLayout"], - message: 'blankLayout is required when type is "blank"' - }); - } -}); -var WidgetLifecycleSchema = external_exports.object({ - /** - * Called when widget is mounted/rendered for the first time - * Use for initialization, setting up event listeners, loading data, etc. - * - * @example "initializeDatePicker(); loadOptions();" - */ - onMount: external_exports.string().optional().describe("Initialization code when widget mounts"), - /** - * Called when widget props change - * Receives previous props for comparison - * - * @example "if (prevProps.value !== props.value) { updateDisplay() }" - */ - onUpdate: external_exports.string().optional().describe("Code to run when props change"), - /** - * Called when widget is about to be removed from DOM - * Use for cleanup, removing event listeners, canceling timers, etc. - * - * @example "destroyDatePicker(); cancelPendingRequests();" - */ - onUnmount: external_exports.string().optional().describe("Cleanup code when widget unmounts"), - /** - * Custom validation logic for this widget - * Should return error message string if invalid, null/undefined if valid - * - * @example "return value && value.length >= 10 ? null : 'Minimum 10 characters'" - */ - onValidate: external_exports.string().optional().describe("Custom validation logic"), - /** - * Called when widget receives focus - * - * @example "highlightField(); logFocusEvent();" - */ - onFocus: external_exports.string().optional().describe("Code to run on focus"), - /** - * Called when widget loses focus - * - * @example "validateField(); saveFieldState();" - */ - onBlur: external_exports.string().optional().describe("Code to run on blur"), - /** - * Called on any error in the widget - * - * @example "logError(error); showErrorNotification();" - */ - onError: external_exports.string().optional().describe("Error handling code") -}); -var WidgetEventSchema = external_exports.object({ - /** - * Event name - * Should be lowercase, dash-separated for consistency - * - * @example "value-change", "item-selected", "search-complete" - */ - name: external_exports.string().describe("Event name"), - /** - * Event label for documentation - */ - label: I18nLabelSchema4.optional().describe("Human-readable event label"), - /** - * Event description - */ - description: I18nLabelSchema4.optional().describe("Event description and usage"), - /** - * Whether event bubbles up through the DOM hierarchy - * - * @default false - */ - bubbles: external_exports.boolean().default(false).describe("Whether event bubbles"), - /** - * Whether event can be cancelled - * - * @default false - */ - cancelable: external_exports.boolean().default(false).describe("Whether event is cancelable"), - /** - * Event payload schema - * Defines the data structure sent with the event - * - * @example { userId: 'string', timestamp: 'number' } - */ - payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event payload schema") -}); -var WidgetPropertySchema = external_exports.object({ - /** - * Property name - * Should be camelCase following ObjectStack conventions - */ - name: external_exports.string().describe("Property name (camelCase)"), - /** - * Property label for UI - */ - label: I18nLabelSchema4.optional().describe("Human-readable label"), - /** - * Property data type - * - * @example "string", "number", "boolean", "array", "object", "function" - */ - type: external_exports.enum(["string", "number", "boolean", "array", "object", "function", "any"]).describe("TypeScript type"), - /** - * Whether property is required - * - * @default false - */ - required: external_exports.boolean().default(false).describe("Whether property is required"), - /** - * Default value for the property - */ - default: external_exports.unknown().optional().describe("Default value"), - /** - * Property description - */ - description: I18nLabelSchema4.optional().describe("Property description"), - /** - * Property validation schema - * Can include min/max, regex, enum values, etc. - */ - validation: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation rules"), - /** - * Property category for grouping in UI - */ - category: external_exports.string().optional().describe("Property category") -}); -var WidgetSourceSchema = external_exports.discriminatedUnion("type", [ - // NPM Registry (standard) - external_exports.object({ - type: external_exports.literal("npm"), - packageName: external_exports.string().describe("NPM package name"), - version: external_exports.string().default("latest"), - exportName: external_exports.string().optional().describe("Named export (default: default)") - }), - // Module Federation (Remote) - external_exports.object({ - type: external_exports.literal("remote"), - url: external_exports.string().url().describe("Remote entry URL (.js)"), - moduleName: external_exports.string().describe("Exposed module name"), - scope: external_exports.string().describe("Remote scope name") - }), - // Inline Code (Simple scripts) - external_exports.object({ - type: external_exports.literal("inline"), - code: external_exports.string().describe("JavaScript code body") - }) -]); -var WidgetManifestSchema = external_exports.object({ - /** - * Widget identifier (snake_case) - */ - name: SnakeCaseIdentifierSchema6.describe("Widget identifier (snake_case)"), - /** - * Human-readable widget name - */ - label: I18nLabelSchema4.describe("Widget display name"), - /** - * Widget description - */ - description: I18nLabelSchema4.optional().describe("Widget description"), - /** - * Widget version (semver) - */ - version: external_exports.string().optional().describe("Widget version (semver)"), - /** - * Widget author/organization - */ - author: external_exports.string().optional().describe("Widget author"), - /** - * Icon name or URL - */ - icon: external_exports.string().optional().describe("Widget icon"), - /** - * Field types this widget supports - * - * @example ["text", "email", "url"] - */ - fieldTypes: external_exports.array(external_exports.string()).optional().describe("Supported field types"), - /** - * Widget category for organization - */ - category: external_exports.enum(["input", "display", "picker", "editor", "custom"]).default("custom").describe("Widget category"), - /** - * Widget lifecycle hooks - */ - lifecycle: WidgetLifecycleSchema.optional().describe("Lifecycle hooks"), - /** - * Custom events this widget emits - */ - events: external_exports.array(WidgetEventSchema).optional().describe("Custom events"), - /** - * Widget configuration properties - */ - properties: external_exports.array(WidgetPropertySchema).optional().describe("Configuration properties"), - /** - * Widget implementation - * Defines how to load the widget code - */ - implementation: WidgetSourceSchema.optional().describe("Widget implementation source"), - /** - * Widget dependencies - * External libraries or scripts needed - */ - dependencies: external_exports.array(external_exports.object({ - name: external_exports.string(), - version: external_exports.string().optional(), - url: external_exports.string().url().optional() - })).optional().describe("Widget dependencies"), - /** - * Widget screenshots for showcase - */ - screenshots: external_exports.array(external_exports.string().url()).optional().describe("Screenshot URLs"), - /** - * Widget documentation URL - */ - documentation: external_exports.string().url().optional().describe("Documentation URL"), - /** - * License information - */ - license: external_exports.string().optional().describe("License (SPDX identifier)"), - /** - * Tags for discovery - */ - tags: external_exports.array(external_exports.string()).optional().describe("Tags for categorization"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema2.optional().describe("Performance optimization settings") -}); -var FieldWidgetPropsSchema = external_exports.object({ - /** - * Current field value. - * Type depends on the field type (string, number, boolean, array, object, etc.) - */ - value: external_exports.unknown().describe("Current field value"), - /** - * Callback function to update the field value. - * Should be called when user interaction changes the value. - * - * @param newValue - The new value to set - */ - onChange: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.void()).describe("Callback to update field value"), - /** - * Whether the field is in read-only mode. - * When true, the widget should display the value but not allow editing. - */ - readonly: external_exports.boolean().default(false).describe("Read-only mode flag"), - /** - * Whether the field is required. - * Widget should indicate required state visually and validate accordingly. - */ - required: external_exports.boolean().default(false).describe("Required field flag"), - /** - * Validation error message to display. - * When present, widget should display the error in its UI. - */ - error: external_exports.string().optional().describe("Validation error message"), - /** - * Complete field definition from the schema. - * Contains metadata like type, constraints, options, etc. - */ - field: FieldSchema4.describe("Field schema definition"), - /** - * The complete record/document being edited. - * Useful for conditional logic and cross-field dependencies. - */ - record: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Complete record data"), - /** - * Custom options passed to the widget. - * Can contain widget-specific configuration like themes, behaviors, etc. - */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom widget options") -}); -var FeedItemType3 = external_exports.enum([ - "comment", - "field_change", - "task", - "event", - "email", - "call", - "note", - "file", - "record_create", - "record_delete", - "approval", - "sharing", - "system" -]); -var MentionSchema3 = external_exports.object({ - type: external_exports.enum(["user", "team", "record"]).describe("Mention target type"), - id: external_exports.string().describe("Target ID"), - name: external_exports.string().describe("Display name for rendering"), - offset: external_exports.number().int().min(0).describe("Character offset in body text"), - length: external_exports.number().int().min(1).describe("Length of mention token in body text") -}); -var FieldChangeEntrySchema3 = external_exports.object({ - field: external_exports.string().describe("Field machine name"), - fieldLabel: external_exports.string().optional().describe("Field display label"), - oldValue: external_exports.unknown().optional().describe("Previous value"), - newValue: external_exports.unknown().optional().describe("New value"), - oldDisplayValue: external_exports.string().optional().describe("Human-readable old value"), - newDisplayValue: external_exports.string().optional().describe("Human-readable new value") -}); -var ReactionSchema3 = external_exports.object({ - emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")'), - userIds: external_exports.array(external_exports.string()).describe("Users who reacted"), - count: external_exports.number().int().min(1).describe("Total reaction count") -}); -var FeedActorSchema3 = external_exports.object({ - type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), - id: external_exports.string().describe("Actor ID"), - name: external_exports.string().optional().describe("Actor display name"), - avatarUrl: external_exports.string().url().optional().describe("Actor avatar URL"), - source: external_exports.string().optional().describe('Source application (e.g., "Omni", "API", "Studio")') -}); -var FeedVisibility3 = external_exports.enum(["public", "internal", "private"]); -external_exports.object({ - /** Unique identifier */ - id: external_exports.string().describe("Feed item ID"), - /** Feed item type */ - type: FeedItemType3.describe("Activity type"), - /** Target record reference */ - object: external_exports.string().describe('Object name (e.g., "account")'), - recordId: external_exports.string().describe("Record ID this feed item belongs to"), - /** Actor (who performed the action) */ - actor: FeedActorSchema3.describe("Who performed this action"), - /** Content (for comments/notes) */ - body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), - /** @Mentions */ - mentions: external_exports.array(MentionSchema3).optional().describe("Mentioned users/teams/records"), - /** Field changes (for field_change type) */ - changes: external_exports.array(FieldChangeEntrySchema3).optional().describe("Field-level changes"), - /** Reactions */ - reactions: external_exports.array(ReactionSchema3).optional().describe("Emoji reactions on this item"), - /** Reply threading */ - parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), - replyCount: external_exports.number().int().min(0).default(0).describe("Number of replies"), - /** Pin / Star */ - pinned: external_exports.boolean().default(false).describe("Whether the feed item is pinned to the top of the timeline"), - pinnedAt: external_exports.string().datetime().optional().describe("Timestamp when the item was pinned"), - pinnedBy: external_exports.string().optional().describe("User ID who pinned the item"), - starred: external_exports.boolean().default(false).describe("Whether the feed item is starred/bookmarked by the current user"), - starredAt: external_exports.string().datetime().optional().describe("Timestamp when the item was starred"), - /** Visibility */ - visibility: FeedVisibility3.default("public").describe("Visibility: public (all users), internal (team only), private (author + mentioned)"), - /** Timestamps */ - createdAt: external_exports.string().datetime().describe("Creation timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - editedAt: external_exports.string().datetime().optional().describe("When comment was last edited"), - isEdited: external_exports.boolean().default(false).describe("Whether comment has been edited") -}); -var FeedFilterMode2 = external_exports.enum([ - "all", - "comments_only", - "changes_only", - "tasks_only" -]); -var EmptyProps = external_exports.object({}); -var PageHeaderProps = external_exports.object({ - title: I18nLabelSchema4.describe("Page title"), - subtitle: I18nLabelSchema4.optional().describe("Page subtitle"), - icon: external_exports.string().optional().describe("Icon name"), - breadcrumb: external_exports.boolean().default(true).describe("Show breadcrumb"), - actions: external_exports.array(external_exports.string()).optional().describe("Action IDs to show in header"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var PageTabsProps = external_exports.object({ - type: external_exports.enum(["line", "card", "pill"]).default("line"), - position: external_exports.enum(["top", "left"]).default("top"), - items: external_exports.array(external_exports.object({ - label: I18nLabelSchema4, - icon: external_exports.string().optional(), - children: external_exports.array(external_exports.unknown()).describe("Child components") - })), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var PageCardProps = external_exports.object({ - title: I18nLabelSchema4.optional(), - bordered: external_exports.boolean().default(true), - actions: external_exports.array(external_exports.string()).optional(), - /** Slot for nested content in the Card body */ - body: external_exports.array(external_exports.unknown()).optional().describe("Card content components (slot)"), - /** Slot for footer content */ - footer: external_exports.array(external_exports.unknown()).optional().describe("Card footer components (slot)"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var RecordDetailsProps = external_exports.object({ - columns: external_exports.enum(["1", "2", "3", "4"]).default("2").describe("Number of columns for field layout (1-4)"), - layout: external_exports.enum(["auto", "custom"]).default("auto").describe("Layout mode: auto uses object compactLayout, custom uses explicit sections"), - sections: external_exports.array(external_exports.string()).optional().describe('Section IDs to show (required when layout is "custom")'), - fields: external_exports.array(external_exports.string()).optional().describe("Explicit field list to display (optional, overrides compactLayout)"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var RecordRelatedListProps = external_exports.object({ - objectName: external_exports.string().describe('Related object name (e.g., "task", "opportunity")'), - relationshipField: external_exports.string().describe('Field on related object that points to this record (e.g., "account_id")'), - columns: external_exports.array(external_exports.string()).describe("Fields to display in the related list"), - sort: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]) - })) - ]).optional().describe("Sort order for related records"), - limit: external_exports.number().int().positive().default(5).describe("Number of records to display initially"), - filter: external_exports.array(ViewFilterRuleSchema2).optional().describe("Additional filter criteria for related records"), - title: I18nLabelSchema4.optional().describe("Custom title for the related list"), - showViewAll: external_exports.boolean().default(true).describe('Show "View All" link to see all related records'), - actions: external_exports.array(external_exports.string()).optional().describe("Action IDs available for related records"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var RecordHighlightsProps = external_exports.object({ - fields: external_exports.array(external_exports.string()).min(1).max(7).describe("Key fields to highlight (1-7 fields max, typically displayed as prominent cards)"), - layout: external_exports.enum(["horizontal", "vertical"]).default("horizontal").describe("Layout orientation for highlight fields"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var RecordActivityProps = external_exports.object({ - /** Activity types to display (unified enum including comment, field_change, etc.) */ - types: external_exports.array(FeedItemType3).optional().describe("Feed item types to show (default: all)"), - /** Default filter mode (Airtable-style dropdown) */ - filterMode: FeedFilterMode2.default("all").describe("Default activity filter"), - /** Allow user to switch filter modes */ - showFilterToggle: external_exports.boolean().default(true).describe("Show filter dropdown in panel header"), - /** Pagination */ - limit: external_exports.number().int().positive().default(20).describe("Number of items to load per page"), - /** Show completed activities */ - showCompleted: external_exports.boolean().default(false).describe("Include completed activities"), - /** Merge field_change + comment in a unified timeline */ - unifiedTimeline: external_exports.boolean().default(true).describe("Mix field changes and comments in one timeline (Airtable style)"), - /** Show the comment input box at the bottom */ - showCommentInput: external_exports.boolean().default(true).describe('Show "Leave a comment" input at the bottom'), - /** Enable @mentions in comments */ - enableMentions: external_exports.boolean().default(true).describe("Enable @mentions in comments"), - /** Enable emoji reactions */ - enableReactions: external_exports.boolean().default(false).describe("Enable emoji reactions on feed items"), - /** Enable threaded replies */ - enableThreading: external_exports.boolean().default(false).describe("Enable threaded replies on comments"), - /** Show notification subscription toggle (bell icon) */ - showSubscriptionToggle: external_exports.boolean().default(true).describe("Show bell icon for record-level notification subscription"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var RecordChatterProps = external_exports.object({ - /** Panel position */ - position: external_exports.enum(["sidebar", "inline", "drawer"]).default("sidebar").describe("Where to render the chatter panel"), - /** Panel width (for sidebar/drawer) */ - width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Panel width (e.g., "350px", "30%")'), - /** Collapsible */ - collapsible: external_exports.boolean().default(true).describe("Whether the panel can be collapsed"), - /** Default collapsed state */ - defaultCollapsed: external_exports.boolean().default(false).describe("Whether the panel starts collapsed"), - /** Feed configuration (delegates to RecordActivityProps) */ - feed: RecordActivityProps.optional().describe("Embedded activity feed configuration"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var RecordPathProps = external_exports.object({ - statusField: external_exports.string().describe("Field name representing the current status/stage"), - stages: external_exports.array(external_exports.object({ - value: external_exports.string(), - label: I18nLabelSchema4 - })).optional().describe("Explicit stage definitions (if not using field metadata)"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var PageAccordionProps = external_exports.object({ - items: external_exports.array(external_exports.object({ - label: I18nLabelSchema4, - icon: external_exports.string().optional(), - collapsed: external_exports.boolean().default(false), - children: external_exports.array(external_exports.unknown()).describe("Child components") - })), - allowMultiple: external_exports.boolean().default(false).describe("Allow multiple panels to be expanded simultaneously"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var AIChatWindowProps = external_exports.object({ - mode: external_exports.enum(["float", "sidebar", "inline"]).default("float").describe("Display mode for the chat window"), - agentId: external_exports.string().optional().describe("Specific AI agent to use"), - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Contextual data to pass to the AI"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var ElementTextPropsSchema = external_exports.object({ - content: external_exports.string().describe("Text or Markdown content"), - variant: external_exports.enum(["heading", "subheading", "body", "caption"]).optional().default("body").describe("Text style variant"), - align: external_exports.enum(["left", "center", "right"]).optional().default("left").describe("Text alignment"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var ElementNumberPropsSchema = external_exports.object({ - object: external_exports.string().describe("Source object"), - field: external_exports.string().optional().describe("Field to aggregate"), - aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).describe("Aggregation function"), - filter: FilterConditionSchema3.optional().describe("Filter criteria"), - format: external_exports.enum(["number", "currency", "percent"]).optional().describe("Number display format"), - prefix: external_exports.string().optional().describe('Prefix text (e.g. "$")'), - suffix: external_exports.string().optional().describe('Suffix text (e.g. "%")'), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var ElementImagePropsSchema = external_exports.object({ - src: external_exports.string().describe("Image URL or attachment field"), - alt: external_exports.string().optional().describe("Alt text for accessibility"), - fit: external_exports.enum(["cover", "contain", "fill"]).optional().default("cover").describe("Image object-fit mode"), - height: external_exports.number().optional().describe("Fixed height in pixels"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var ElementButtonPropsSchema = external_exports.object({ - label: I18nLabelSchema4.describe("Button display label"), - variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().default("primary").describe("Button visual variant"), - size: external_exports.enum(["small", "medium", "large"]).optional().default("medium").describe("Button size"), - icon: external_exports.string().optional().describe("Icon name (Lucide icon)"), - iconPosition: external_exports.enum(["left", "right"]).optional().default("left").describe("Icon position relative to label"), - disabled: external_exports.boolean().optional().default(false).describe("Disable the button"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var ElementFilterPropsSchema = external_exports.object({ - object: external_exports.string().describe("Object to filter"), - fields: external_exports.array(external_exports.string()).describe("Filterable field names"), - targetVariable: external_exports.string().optional().describe("Page variable to store filter state"), - layout: external_exports.enum(["inline", "dropdown", "sidebar"]).optional().default("inline").describe("Filter display layout"), - showSearch: external_exports.boolean().optional().default(true).describe("Show search input"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var ElementFormPropsSchema = external_exports.object({ - object: external_exports.string().describe("Object for the form"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to display (defaults to all editable fields)"), - mode: external_exports.enum(["create", "edit"]).optional().default("create").describe("Form mode"), - submitLabel: I18nLabelSchema4.optional().describe("Submit button label"), - onSubmit: external_exports.string().optional().describe("Action expression on form submit"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var ElementRecordPickerPropsSchema = external_exports.object({ - object: external_exports.string().describe("Object to pick records from"), - displayField: external_exports.string().describe("Field to display as the record label"), - searchFields: external_exports.array(external_exports.string()).optional().describe("Fields to search against"), - filter: FilterConditionSchema3.optional().describe("Filter criteria for available records"), - multiple: external_exports.boolean().optional().default(false).describe("Allow multiple record selection"), - targetVariable: external_exports.string().optional().describe("Page variable to bind selected record ID(s)"), - placeholder: I18nLabelSchema4.optional().describe("Placeholder text"), - /** ARIA accessibility */ - aria: AriaPropsSchema4.optional().describe("ARIA accessibility attributes") -}); -var ComponentPropsMap = { - // Structure - "page:header": PageHeaderProps, - "page:tabs": PageTabsProps, - "page:card": PageCardProps, - "page:footer": EmptyProps, - "page:sidebar": EmptyProps, - "page:accordion": PageAccordionProps, - "page:section": EmptyProps, - // Record - "record:details": RecordDetailsProps, - "record:related_list": RecordRelatedListProps, - "record:highlights": RecordHighlightsProps, - "record:activity": RecordActivityProps, - "record:chatter": RecordChatterProps, - "record:path": RecordPathProps, - // Navigation - "app:launcher": EmptyProps, - "nav:menu": EmptyProps, - "nav:breadcrumb": EmptyProps, - // Utility - "global:search": EmptyProps, - "global:notifications": EmptyProps, - "user:profile": EmptyProps, - // AI - "ai:chat_window": AIChatWindowProps, - "ai:suggestion": external_exports.object({ context: external_exports.string().optional() }), - // Content Elements - "element:text": ElementTextPropsSchema, - "element:number": ElementNumberPropsSchema, - "element:image": ElementImagePropsSchema, - "element:divider": EmptyProps, - // Interactive Elements - "element:button": ElementButtonPropsSchema, - "element:filter": ElementFilterPropsSchema, - "element:form": ElementFormPropsSchema, - "element:record_picker": ElementRecordPickerPropsSchema -}; -var TouchTargetConfigSchema = external_exports.object({ - minWidth: external_exports.number().default(44).describe("Minimum touch target width in pixels (WCAG 2.5.5: 44px)"), - minHeight: external_exports.number().default(44).describe("Minimum touch target height in pixels (WCAG 2.5.5: 44px)"), - padding: external_exports.number().optional().describe("Additional padding around touch target in pixels"), - hitSlop: external_exports.object({ - top: external_exports.number().optional().describe("Extra hit area above the element"), - right: external_exports.number().optional().describe("Extra hit area to the right of the element"), - bottom: external_exports.number().optional().describe("Extra hit area below the element"), - left: external_exports.number().optional().describe("Extra hit area to the left of the element") - }).optional().describe("Invisible hit area extension beyond the visible bounds") -}).describe("Touch target sizing configuration (WCAG accessible)"); -var GestureTypeSchema = external_exports.enum([ - "swipe", - "pinch", - "long_press", - "double_tap", - "drag", - "rotate", - "pan" -]).describe("Touch gesture type"); -var SwipeDirectionSchema = external_exports.enum(["up", "down", "left", "right"]); -var SwipeGestureConfigSchema = external_exports.object({ - direction: external_exports.array(SwipeDirectionSchema).describe("Allowed swipe directions"), - threshold: external_exports.number().optional().describe("Minimum distance in pixels to recognize swipe"), - velocity: external_exports.number().optional().describe("Minimum velocity (px/ms) to trigger swipe") -}).describe("Swipe gesture recognition settings"); -var PinchGestureConfigSchema = external_exports.object({ - minScale: external_exports.number().optional().describe("Minimum scale factor (e.g., 0.5 for 50%)"), - maxScale: external_exports.number().optional().describe("Maximum scale factor (e.g., 3.0 for 300%)") -}).describe("Pinch/zoom gesture recognition settings"); -var LongPressGestureConfigSchema = external_exports.object({ - duration: external_exports.number().default(500).describe("Hold duration in milliseconds to trigger long press"), - moveTolerance: external_exports.number().optional().describe("Max movement in pixels allowed during press") -}).describe("Long press gesture recognition settings"); -var GestureConfigSchema = external_exports.object({ - type: GestureTypeSchema.describe("Gesture type to configure"), - label: I18nLabelSchema4.optional().describe("Descriptive label for the gesture action"), - enabled: external_exports.boolean().default(true).describe("Whether this gesture is active"), - swipe: SwipeGestureConfigSchema.optional().describe("Swipe gesture settings (when type is swipe)"), - pinch: PinchGestureConfigSchema.optional().describe("Pinch gesture settings (when type is pinch)"), - longPress: LongPressGestureConfigSchema.optional().describe("Long press settings (when type is long_press)") -}).describe("Per-gesture configuration"); -var TouchInteractionSchema = external_exports.object({ - gestures: external_exports.array(GestureConfigSchema).optional().describe("Configured gesture recognizers"), - touchTarget: TouchTargetConfigSchema.optional().describe("Touch target sizing and hit area"), - hapticFeedback: external_exports.boolean().optional().describe("Enable haptic feedback on touch interactions") -}).merge(AriaPropsSchema4.partial()).describe("Touch and gesture interaction configuration"); -var FocusTrapConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable focus trapping within this container"), - initialFocus: external_exports.string().optional().describe("CSS selector for the element to focus on activation"), - returnFocus: external_exports.boolean().default(true).describe("Return focus to trigger element on deactivation"), - escapeDeactivates: external_exports.boolean().default(true).describe("Allow Escape key to deactivate the focus trap") -}).describe("Focus trap configuration for modal-like containers"); -var KeyboardShortcutSchema = external_exports.object({ - key: external_exports.string().describe('Key combination (e.g., "Ctrl+S", "Alt+N", "Escape")'), - action: external_exports.string().describe("Action identifier to invoke when shortcut is triggered"), - description: I18nLabelSchema4.optional().describe("Human-readable description of what the shortcut does"), - scope: external_exports.enum(["global", "view", "form", "modal", "list"]).default("global").describe("Scope in which this shortcut is active") -}).describe("Keyboard shortcut binding"); -var FocusManagementSchema = external_exports.object({ - tabOrder: external_exports.enum(["auto", "manual"]).default("auto").describe("Tab order strategy: auto (DOM order) or manual (explicit tabIndex)"), - skipLinks: external_exports.boolean().default(false).describe("Provide skip-to-content navigation links"), - focusVisible: external_exports.boolean().default(true).describe("Show visible focus indicators for keyboard users"), - focusTrap: FocusTrapConfigSchema.optional().describe("Focus trap settings"), - arrowNavigation: external_exports.boolean().default(false).describe("Enable arrow key navigation between focusable items") -}).describe("Focus and tab navigation management"); -var KeyboardNavigationConfigSchema = external_exports.object({ - shortcuts: external_exports.array(KeyboardShortcutSchema).optional().describe("Registered keyboard shortcuts"), - focusManagement: FocusManagementSchema.optional().describe("Focus and tab order management"), - rovingTabindex: external_exports.boolean().default(false).describe("Enable roving tabindex pattern for composite widgets") -}).merge(AriaPropsSchema4.partial()).describe("Keyboard navigation and shortcut configuration"); -var ColorPaletteSchema = external_exports.object({ - primary: external_exports.string().describe("Primary brand color (hex, rgb, or hsl)"), - secondary: external_exports.string().optional().describe("Secondary brand color"), - accent: external_exports.string().optional().describe("Accent color for highlights"), - success: external_exports.string().optional().describe("Success state color (default: green)"), - warning: external_exports.string().optional().describe("Warning state color (default: yellow)"), - error: external_exports.string().optional().describe("Error state color (default: red)"), - info: external_exports.string().optional().describe("Info state color (default: blue)"), - // Neutral colors - background: external_exports.string().optional().describe("Background color"), - surface: external_exports.string().optional().describe("Surface/card background color"), - text: external_exports.string().optional().describe("Primary text color"), - textSecondary: external_exports.string().optional().describe("Secondary text color"), - border: external_exports.string().optional().describe("Border color"), - disabled: external_exports.string().optional().describe("Disabled state color"), - // Color variants (shades) - primaryLight: external_exports.string().optional().describe("Lighter shade of primary"), - primaryDark: external_exports.string().optional().describe("Darker shade of primary"), - secondaryLight: external_exports.string().optional().describe("Lighter shade of secondary"), - secondaryDark: external_exports.string().optional().describe("Darker shade of secondary") -}); -var TypographySchema = external_exports.object({ - fontFamily: external_exports.object({ - base: external_exports.string().optional().describe("Base font family (default: system fonts)"), - heading: external_exports.string().optional().describe("Heading font family"), - mono: external_exports.string().optional().describe("Monospace font family for code") - }).optional(), - fontSize: external_exports.object({ - xs: external_exports.string().optional().describe("Extra small font size (e.g., 0.75rem)"), - sm: external_exports.string().optional().describe("Small font size (e.g., 0.875rem)"), - base: external_exports.string().optional().describe("Base font size (e.g., 1rem)"), - lg: external_exports.string().optional().describe("Large font size (e.g., 1.125rem)"), - xl: external_exports.string().optional().describe("Extra large font size (e.g., 1.25rem)"), - "2xl": external_exports.string().optional().describe("2X large font size (e.g., 1.5rem)"), - "3xl": external_exports.string().optional().describe("3X large font size (e.g., 1.875rem)"), - "4xl": external_exports.string().optional().describe("4X large font size (e.g., 2.25rem)") - }).optional(), - fontWeight: external_exports.object({ - light: external_exports.number().optional().describe("Light weight (default: 300)"), - normal: external_exports.number().optional().describe("Normal weight (default: 400)"), - medium: external_exports.number().optional().describe("Medium weight (default: 500)"), - semibold: external_exports.number().optional().describe("Semibold weight (default: 600)"), - bold: external_exports.number().optional().describe("Bold weight (default: 700)") - }).optional(), - lineHeight: external_exports.object({ - tight: external_exports.string().optional().describe("Tight line height (e.g., 1.25)"), - normal: external_exports.string().optional().describe("Normal line height (e.g., 1.5)"), - relaxed: external_exports.string().optional().describe("Relaxed line height (e.g., 1.75)"), - loose: external_exports.string().optional().describe("Loose line height (e.g., 2)") - }).optional(), - letterSpacing: external_exports.object({ - tighter: external_exports.string().optional().describe("Tighter letter spacing (e.g., -0.05em)"), - tight: external_exports.string().optional().describe("Tight letter spacing (e.g., -0.025em)"), - normal: external_exports.string().optional().describe("Normal letter spacing (e.g., 0)"), - wide: external_exports.string().optional().describe("Wide letter spacing (e.g., 0.025em)"), - wider: external_exports.string().optional().describe("Wider letter spacing (e.g., 0.05em)") - }).optional() -}); -var SpacingSchema = external_exports.object({ - "0": external_exports.string().optional().describe("0 spacing (0)"), - "1": external_exports.string().optional().describe("Spacing unit 1 (e.g., 0.25rem)"), - "2": external_exports.string().optional().describe("Spacing unit 2 (e.g., 0.5rem)"), - "3": external_exports.string().optional().describe("Spacing unit 3 (e.g., 0.75rem)"), - "4": external_exports.string().optional().describe("Spacing unit 4 (e.g., 1rem)"), - "5": external_exports.string().optional().describe("Spacing unit 5 (e.g., 1.25rem)"), - "6": external_exports.string().optional().describe("Spacing unit 6 (e.g., 1.5rem)"), - "8": external_exports.string().optional().describe("Spacing unit 8 (e.g., 2rem)"), - "10": external_exports.string().optional().describe("Spacing unit 10 (e.g., 2.5rem)"), - "12": external_exports.string().optional().describe("Spacing unit 12 (e.g., 3rem)"), - "16": external_exports.string().optional().describe("Spacing unit 16 (e.g., 4rem)"), - "20": external_exports.string().optional().describe("Spacing unit 20 (e.g., 5rem)"), - "24": external_exports.string().optional().describe("Spacing unit 24 (e.g., 6rem)") -}); -var BorderRadiusSchema = external_exports.object({ - none: external_exports.string().optional().describe("No border radius (0)"), - sm: external_exports.string().optional().describe("Small border radius (e.g., 0.125rem)"), - base: external_exports.string().optional().describe("Base border radius (e.g., 0.25rem)"), - md: external_exports.string().optional().describe("Medium border radius (e.g., 0.375rem)"), - lg: external_exports.string().optional().describe("Large border radius (e.g., 0.5rem)"), - xl: external_exports.string().optional().describe("Extra large border radius (e.g., 0.75rem)"), - "2xl": external_exports.string().optional().describe("2X large border radius (e.g., 1rem)"), - full: external_exports.string().optional().describe("Full border radius (50%)") -}); -var ShadowSchema = external_exports.object({ - none: external_exports.string().optional().describe("No shadow"), - sm: external_exports.string().optional().describe("Small shadow"), - base: external_exports.string().optional().describe("Base shadow"), - md: external_exports.string().optional().describe("Medium shadow"), - lg: external_exports.string().optional().describe("Large shadow"), - xl: external_exports.string().optional().describe("Extra large shadow"), - "2xl": external_exports.string().optional().describe("2X large shadow"), - inner: external_exports.string().optional().describe("Inner shadow (inset)") -}); -var BreakpointsSchema = external_exports.object({ - xs: external_exports.string().optional().describe("Extra small breakpoint (e.g., 480px)"), - sm: external_exports.string().optional().describe("Small breakpoint (e.g., 640px)"), - md: external_exports.string().optional().describe("Medium breakpoint (e.g., 768px)"), - lg: external_exports.string().optional().describe("Large breakpoint (e.g., 1024px)"), - xl: external_exports.string().optional().describe("Extra large breakpoint (e.g., 1280px)"), - "2xl": external_exports.string().optional().describe("2X large breakpoint (e.g., 1536px)") -}); -var AnimationSchema = external_exports.object({ - duration: external_exports.object({ - fast: external_exports.string().optional().describe("Fast animation (e.g., 150ms)"), - base: external_exports.string().optional().describe("Base animation (e.g., 300ms)"), - slow: external_exports.string().optional().describe("Slow animation (e.g., 500ms)") - }).optional(), - timing: external_exports.object({ - linear: external_exports.string().optional().describe("Linear timing function"), - ease: external_exports.string().optional().describe("Ease timing function"), - ease_in: external_exports.string().optional().describe("Ease-in timing function"), - ease_out: external_exports.string().optional().describe("Ease-out timing function"), - ease_in_out: external_exports.string().optional().describe("Ease-in-out timing function") - }).optional() -}); -var ZIndexSchema = external_exports.object({ - base: external_exports.number().optional().describe("Base z-index (e.g., 0)"), - dropdown: external_exports.number().optional().describe("Dropdown z-index (e.g., 1000)"), - sticky: external_exports.number().optional().describe("Sticky z-index (e.g., 1020)"), - fixed: external_exports.number().optional().describe("Fixed z-index (e.g., 1030)"), - modalBackdrop: external_exports.number().optional().describe("Modal backdrop z-index (e.g., 1040)"), - modal: external_exports.number().optional().describe("Modal z-index (e.g., 1050)"), - popover: external_exports.number().optional().describe("Popover z-index (e.g., 1060)"), - tooltip: external_exports.number().optional().describe("Tooltip z-index (e.g., 1070)") -}); -var ThemeModeSchema = external_exports.enum(["light", "dark", "auto"]); -var DensityModeSchema = external_exports.enum(["compact", "regular", "spacious"]); -var WcagContrastLevelSchema = external_exports.enum(["AA", "AAA"]); -var ThemeSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema6.describe("Unique theme identifier (snake_case)"), - label: external_exports.string().describe("Human-readable theme name"), - description: external_exports.string().optional().describe("Theme description"), - /** Theme mode */ - mode: ThemeModeSchema.default("light").describe("Theme mode (light, dark, or auto)"), - /** Color system */ - colors: ColorPaletteSchema.describe("Color palette configuration"), - /** Typography */ - typography: TypographySchema.optional().describe("Typography settings"), - /** Spacing */ - spacing: SpacingSchema.optional().describe("Spacing scale"), - /** Border radius */ - borderRadius: BorderRadiusSchema.optional().describe("Border radius scale"), - /** Shadows */ - shadows: ShadowSchema.optional().describe("Box shadow effects"), - /** Breakpoints */ - breakpoints: BreakpointsSchema.optional().describe("Responsive breakpoints"), - /** Animation */ - animation: AnimationSchema.optional().describe("Animation settings"), - /** Z-Index */ - zIndex: ZIndexSchema.optional().describe("Z-index scale for layering"), - /** Custom CSS variables */ - customVars: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom CSS variables (key-value pairs)"), - /** Logo */ - logo: external_exports.object({ - light: external_exports.string().optional().describe("Logo URL for light mode"), - dark: external_exports.string().optional().describe("Logo URL for dark mode"), - favicon: external_exports.string().optional().describe("Favicon URL") - }).optional().describe("Logo assets"), - /** Extends another theme */ - extends: external_exports.string().optional().describe("Base theme to extend from"), - /** Display density mode */ - density: DensityModeSchema.optional().describe("Display density: compact, regular, or spacious"), - /** WCAG contrast level requirement */ - wcagContrast: WcagContrastLevelSchema.optional().describe("WCAG color contrast level (AA or AAA)"), - /** Right-to-left language support */ - rtl: external_exports.boolean().optional().describe("Enable right-to-left layout direction"), - /** Touch target accessibility configuration */ - touchTarget: TouchTargetConfigSchema.optional().describe("Touch target sizing defaults"), - /** Keyboard navigation and focus management */ - keyboardNavigation: FocusManagementSchema.optional().describe("Keyboard focus management settings") -}); -var OfflineStrategySchema = external_exports.enum([ - "cache_first", - "network_first", - "stale_while_revalidate", - "network_only", - "cache_only" -]).describe("Data fetching strategy for offline/online transitions"); -var ConflictResolutionSchema = external_exports.enum([ - "client_wins", - "server_wins", - "manual", - "last_write_wins" -]).describe("How to resolve conflicts when syncing offline changes"); -var SyncConfigSchema = external_exports.object({ - strategy: OfflineStrategySchema.default("network_first").describe("Sync fetch strategy"), - conflictResolution: ConflictResolutionSchema.default("last_write_wins").describe("Conflict resolution policy"), - retryInterval: external_exports.number().optional().describe("Retry interval in milliseconds between sync attempts"), - maxRetries: external_exports.number().optional().describe("Maximum number of sync retry attempts"), - batchSize: external_exports.number().optional().describe("Number of mutations to sync per batch") -}).describe("Offline-to-online synchronization configuration"); -var PersistStorageSchema = external_exports.enum([ - "indexeddb", - "localstorage", - "sqlite" -]).describe("Client-side storage backend for offline cache"); -var EvictionPolicySchema = external_exports.enum([ - "lru", - "lfu", - "fifo" -]).describe("Cache eviction policy"); -var OfflineCacheConfigSchema = external_exports.object({ - maxSize: external_exports.number().optional().describe("Maximum cache size in bytes"), - ttl: external_exports.number().optional().describe("Time-to-live for cached entries in milliseconds"), - persistStorage: PersistStorageSchema.default("indexeddb").describe("Storage backend"), - evictionPolicy: EvictionPolicySchema.default("lru").describe("Cache eviction policy when full") -}).describe("Client-side offline cache configuration"); -var OfflineConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable offline support"), - strategy: OfflineStrategySchema.default("network_first").describe("Default offline fetch strategy"), - cache: OfflineCacheConfigSchema.optional().describe("Cache settings for offline data"), - sync: SyncConfigSchema.optional().describe("Sync settings for offline mutations"), - offlineIndicator: external_exports.boolean().default(true).describe("Show a visual indicator when offline"), - offlineMessage: I18nLabelSchema4.optional().describe("Customizable offline status message shown to users"), - queueMaxSize: external_exports.number().optional().describe("Maximum number of queued offline mutations") -}).describe("Offline support configuration"); -var TransitionPresetSchema = external_exports.enum([ - "fade", - "slide_up", - "slide_down", - "slide_left", - "slide_right", - "scale", - "rotate", - "flip", - "none" -]).describe("Transition preset type"); -var EasingFunctionSchema = external_exports.enum([ - "linear", - "ease", - "ease_in", - "ease_out", - "ease_in_out", - "spring" -]).describe("Animation easing function"); -var TransitionConfigSchema = external_exports.object({ - preset: TransitionPresetSchema.optional().describe("Transition preset to apply"), - duration: external_exports.number().optional().describe("Transition duration in milliseconds"), - easing: EasingFunctionSchema.optional().describe("Easing function for the transition"), - delay: external_exports.number().optional().describe("Delay before transition starts in milliseconds"), - customKeyframes: external_exports.string().optional().describe("CSS @keyframes name for custom animations"), - themeToken: external_exports.string().optional().describe('Reference to a theme animation token (e.g. "animation.duration.fast")') -}).describe("Animation transition configuration"); -var AnimationTriggerSchema = external_exports.enum([ - "on_mount", - "on_unmount", - "on_hover", - "on_focus", - "on_click", - "on_scroll", - "on_visible" -]).describe("Event that triggers the animation"); -var ComponentAnimationSchema = external_exports.object({ - label: I18nLabelSchema4.optional().describe("Descriptive label for this animation configuration"), - enter: TransitionConfigSchema.optional().describe("Enter/mount animation"), - exit: TransitionConfigSchema.optional().describe("Exit/unmount animation"), - hover: TransitionConfigSchema.optional().describe("Hover state animation"), - trigger: AnimationTriggerSchema.optional().describe("When to trigger the animation"), - reducedMotion: external_exports.enum(["respect", "disable", "alternative"]).default("respect").describe("Accessibility: how to handle prefers-reduced-motion") -}).merge(AriaPropsSchema4.partial()).describe("Component-level animation configuration"); -var PageTransitionSchema = external_exports.object({ - type: TransitionPresetSchema.default("fade").describe("Page transition type"), - duration: external_exports.number().default(300).describe("Transition duration in milliseconds"), - easing: EasingFunctionSchema.default("ease_in_out").describe("Easing function for the transition"), - crossFade: external_exports.boolean().default(false).describe("Whether to cross-fade between pages") -}).describe("Page-level transition configuration"); -var MotionConfigSchema = external_exports.object({ - label: I18nLabelSchema4.optional().describe("Descriptive label for the motion configuration"), - defaultTransition: TransitionConfigSchema.optional().describe("Default transition applied to all animations"), - pageTransitions: PageTransitionSchema.optional().describe("Page navigation transition settings"), - componentAnimations: external_exports.record(external_exports.string(), ComponentAnimationSchema).optional().describe("Component name to animation configuration mapping"), - reducedMotion: external_exports.boolean().default(false).describe("When true, respect prefers-reduced-motion and suppress animations globally"), - enabled: external_exports.boolean().default(true).describe("Enable or disable all animations globally") -}).describe("Top-level motion and animation design configuration"); -var NotificationTypeSchema = external_exports.enum([ - "toast", - "snackbar", - "banner", - "alert", - "inline" -]).describe("Notification presentation style"); -var NotificationSeveritySchema = external_exports.enum([ - "info", - "success", - "warning", - "error" -]).describe("Notification severity level"); -var NotificationPositionSchema = external_exports.enum([ - "top_left", - "top_center", - "top_right", - "bottom_left", - "bottom_center", - "bottom_right" -]).describe("Screen position for notification placement"); -var NotificationActionSchema = external_exports.object({ - label: I18nLabelSchema4.describe("Action button label"), - action: external_exports.string().describe("Action identifier to execute"), - variant: external_exports.enum(["primary", "secondary", "link"]).default("primary").describe("Button variant style") -}).describe("Notification action button"); -var NotificationSchema2 = external_exports.object({ - type: NotificationTypeSchema.default("toast").describe("Notification presentation style"), - severity: NotificationSeveritySchema.default("info").describe("Notification severity level"), - title: I18nLabelSchema4.optional().describe("Notification title"), - message: I18nLabelSchema4.describe("Notification message body"), - icon: external_exports.string().optional().describe("Icon name override"), - duration: external_exports.number().optional().describe("Auto-dismiss duration in ms, omit for persistent"), - dismissible: external_exports.boolean().default(true).describe("Allow user to dismiss the notification"), - actions: external_exports.array(NotificationActionSchema).optional().describe("Action buttons"), - position: NotificationPositionSchema.optional().describe("Override default position") -}).merge(AriaPropsSchema4.partial()).describe("Notification instance definition"); -var NotificationConfigSchema2 = external_exports.object({ - defaultPosition: NotificationPositionSchema.default("top_right").describe("Default screen position for notifications"), - defaultDuration: external_exports.number().default(5e3).describe("Default auto-dismiss duration in ms"), - maxVisible: external_exports.number().default(5).describe("Maximum number of notifications visible at once"), - stackDirection: external_exports.enum(["up", "down"]).default("down").describe("Stack direction for multiple notifications"), - pauseOnHover: external_exports.boolean().default(true).describe("Pause auto-dismiss timer on hover") -}).describe("Global notification system configuration"); -var DragHandleSchema = external_exports.enum([ - "element", - "handle", - "grip_icon" -]).describe("Drag initiation method"); -var DropEffectSchema = external_exports.enum([ - "move", - "copy", - "link", - "none" -]).describe("Drop operation effect"); -var DragConstraintSchema = external_exports.object({ - axis: external_exports.enum(["x", "y", "both"]).default("both").describe("Constrain drag axis"), - bounds: external_exports.enum(["parent", "viewport", "none"]).default("none").describe("Constrain within bounds"), - grid: external_exports.tuple([external_exports.number(), external_exports.number()]).optional().describe("Snap to grid [x, y] in pixels") -}).describe("Drag movement constraints"); -var DropZoneSchema = external_exports.object({ - label: I18nLabelSchema4.optional().describe("Accessible label for the drop zone"), - accept: external_exports.array(external_exports.string()).describe("Accepted drag item types"), - maxItems: external_exports.number().optional().describe("Maximum items allowed in drop zone"), - highlightOnDragOver: external_exports.boolean().default(true).describe("Highlight drop zone when dragging over"), - dropEffect: DropEffectSchema.default("move").describe("Visual effect on drop") -}).merge(AriaPropsSchema4.partial()).describe("Drop zone configuration"); -var DragItemSchema = external_exports.object({ - type: external_exports.string().describe("Drag item type identifier for matching with drop zones"), - label: I18nLabelSchema4.optional().describe("Accessible label describing the draggable item"), - handle: DragHandleSchema.default("element").describe("How to initiate drag"), - constraint: DragConstraintSchema.optional().describe("Drag movement constraints"), - preview: external_exports.enum(["element", "custom", "none"]).default("element").describe("Drag preview type"), - disabled: external_exports.boolean().default(false).describe("Disable dragging") -}).merge(AriaPropsSchema4.partial()).describe("Draggable item configuration"); -var DndConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable drag and drop"), - dragItem: DragItemSchema.optional().describe("Configuration for draggable item"), - dropZone: DropZoneSchema.optional().describe("Configuration for drop target"), - sortable: external_exports.boolean().default(false).describe("Enable sortable list behavior"), - autoScroll: external_exports.boolean().default(true).describe("Auto-scroll during drag near edges"), - touchDelay: external_exports.number().default(200).describe("Delay in ms before drag starts on touch devices") -}).describe("Drag and drop interaction configuration"); - -// ../../packages/objectql/dist/index.mjs -init_data(); -var RESERVED_NAMESPACES = /* @__PURE__ */ new Set(["base", "system"]); -var DEFAULT_OWNER_PRIORITY = 100; -var DEFAULT_EXTENDER_PRIORITY = 200; -function computeFQN(namespace, shortName) { - if (!namespace || RESERVED_NAMESPACES.has(namespace)) { - return shortName; - } - return `${namespace}__${shortName}`; -} -function parseFQN(fqn) { - const idx = fqn.indexOf("__"); - if (idx === -1) { - return { namespace: void 0, shortName: fqn }; - } - return { - namespace: fqn.slice(0, idx), - shortName: fqn.slice(idx + 2) - }; -} -function mergeObjectDefinitions(base, extension) { - const merged = { ...base }; - if (extension.fields) { - merged.fields = { ...base.fields, ...extension.fields }; - } - if (extension.validations) { - merged.validations = [...base.validations || [], ...extension.validations]; - } - if (extension.indexes) { - merged.indexes = [...base.indexes || [], ...extension.indexes]; - } - if (extension.label !== void 0) merged.label = extension.label; - if (extension.pluralLabel !== void 0) merged.pluralLabel = extension.pluralLabel; - if (extension.description !== void 0) merged.description = extension.description; - return merged; -} -var SchemaRegistry = class { - static get logLevel() { - return this._logLevel; - } - static set logLevel(level) { - this._logLevel = level; - } - static log(msg) { - if (this._logLevel === "silent" || this._logLevel === "error" || this._logLevel === "warn") return; - console.log(msg); - } - // ========================================== - // Namespace Management - // ========================================== - /** - * Register a namespace for a package. - * Multiple packages can share the same namespace (e.g. 'sys'). - */ - static registerNamespace(namespace, packageId) { - if (!namespace) return; - let owners = this.namespaceRegistry.get(namespace); - if (!owners) { - owners = /* @__PURE__ */ new Set(); - this.namespaceRegistry.set(namespace, owners); - } - owners.add(packageId); - this.log(`[Registry] Registered namespace: ${namespace} \u2192 ${packageId}`); - } - /** - * Unregister a namespace when a package is uninstalled. - */ - static unregisterNamespace(namespace, packageId) { - const owners = this.namespaceRegistry.get(namespace); - if (owners) { - owners.delete(packageId); - if (owners.size === 0) { - this.namespaceRegistry.delete(namespace); - } - this.log(`[Registry] Unregistered namespace: ${namespace} \u2190 ${packageId}`); - } - } - /** - * Get the packages that use a namespace. - */ - static getNamespaceOwner(namespace) { - const owners = this.namespaceRegistry.get(namespace); - if (!owners || owners.size === 0) return void 0; - return owners.values().next().value; - } - /** - * Get all packages that share a namespace. - */ - static getNamespaceOwners(namespace) { - const owners = this.namespaceRegistry.get(namespace); - return owners ? Array.from(owners) : []; - } - // ========================================== - // Object Registration (Ownership Model) - // ========================================== - /** - * Register an object with ownership semantics. - * - * @param schema - The object definition - * @param packageId - The owning package ID - * @param namespace - The package namespace (for FQN computation) - * @param ownership - 'own' (single owner) or 'extend' (additive merge) - * @param priority - Merge priority (lower applied first, higher wins on conflict) - * - * @throws Error if trying to 'own' an object that already has an owner - */ - static registerObject(schema3, packageId, namespace, ownership = "own", priority = ownership === "own" ? DEFAULT_OWNER_PRIORITY : DEFAULT_EXTENDER_PRIORITY) { - const shortName = schema3.name; - const fqn = computeFQN(namespace, shortName); - if (namespace) { - this.registerNamespace(namespace, packageId); - } - let contributors = this.objectContributors.get(fqn); - if (!contributors) { - contributors = []; - this.objectContributors.set(fqn, contributors); - } - if (ownership === "own") { - const existingOwner = contributors.find((c) => c.ownership === "own"); - if (existingOwner && existingOwner.packageId !== packageId) { - throw new Error( - `Object "${fqn}" is already owned by package "${existingOwner.packageId}". Package "${packageId}" cannot claim ownership. Use 'extend' to add fields.` - ); - } - const idx = contributors.findIndex((c) => c.packageId === packageId && c.ownership === "own"); - if (idx !== -1) { - contributors.splice(idx, 1); - console.warn(`[Registry] Re-registering owned object: ${fqn} from ${packageId}`); - } - } else { - const idx = contributors.findIndex((c) => c.packageId === packageId && c.ownership === "extend"); - if (idx !== -1) { - contributors.splice(idx, 1); - } - } - const contributor = { - packageId, - namespace: namespace || "", - ownership, - priority, - definition: { ...schema3, name: fqn } - // Store with FQN as name - }; - contributors.push(contributor); - contributors.sort((a, b) => a.priority - b.priority); - this.mergedObjectCache.delete(fqn); - this.log(`[Registry] Registered object: ${fqn} (${ownership}, priority=${priority}) from ${packageId}`); - return fqn; - } - /** - * Resolve an object by FQN, merging all contributions. - * Returns the merged object or undefined if not found. - */ - static resolveObject(fqn) { - const cached2 = this.mergedObjectCache.get(fqn); - if (cached2) return cached2; - const contributors = this.objectContributors.get(fqn); - if (!contributors || contributors.length === 0) { - return void 0; - } - const ownerContrib = contributors.find((c) => c.ownership === "own"); - if (!ownerContrib) { - console.warn(`[Registry] Object "${fqn}" has extenders but no owner. Skipping.`); - return void 0; - } - let merged = { ...ownerContrib.definition }; - for (const contrib of contributors) { - if (contrib.ownership === "extend") { - merged = mergeObjectDefinitions(merged, contrib.definition); - } - } - this.mergedObjectCache.set(fqn, merged); - return merged; - } - /** - * Get object by name (FQN, short name, or physical table name). - * - * Resolution order: - * 1. Exact FQN match (e.g., 'crm__account') - * 2. Short name fallback (e.g., 'account' → 'crm__account') - * 3. Physical table name match (e.g., 'sys_user' → 'sys__user') - * ObjectSchema.create() auto-derives tableName as {namespace}_{name}, - * which uses a single underscore — different from the FQN double underscore. - */ - static getObject(name) { - const direct = this.resolveObject(name); - if (direct) return direct; - for (const fqn of this.objectContributors.keys()) { - const { shortName } = parseFQN(fqn); - if (shortName === name) { - return this.resolveObject(fqn); - } - } - for (const fqn of this.objectContributors.keys()) { - const resolved = this.resolveObject(fqn); - if (resolved?.tableName === name) { - return resolved; - } - } - return void 0; - } - /** - * Get all registered objects (merged). - * - * @param packageId - Optional filter: only objects contributed by this package - */ - static getAllObjects(packageId) { - const results = []; - for (const fqn of this.objectContributors.keys()) { - if (packageId) { - const contributors = this.objectContributors.get(fqn); - const hasContribution = contributors?.some((c) => c.packageId === packageId); - if (!hasContribution) continue; - } - const merged = this.resolveObject(fqn); - if (merged) { - merged._packageId = this.getObjectOwner(fqn)?.packageId; - results.push(merged); - } - } - return results; - } - /** - * Get all contributors for an object. - */ - static getObjectContributors(fqn) { - return this.objectContributors.get(fqn) || []; - } - /** - * Get the owner contributor for an object. - */ - static getObjectOwner(fqn) { - const contributors = this.objectContributors.get(fqn); - return contributors?.find((c) => c.ownership === "own"); - } - /** - * Unregister all objects contributed by a package. - * - * @throws Error if trying to uninstall an owner that has extenders - */ - static unregisterObjectsByPackage(packageId, force = false) { - for (const [fqn, contributors] of this.objectContributors.entries()) { - const packageContribs = contributors.filter((c) => c.packageId === packageId); - for (const contrib of packageContribs) { - if (contrib.ownership === "own" && !force) { - const otherExtenders = contributors.filter( - (c) => c.packageId !== packageId && c.ownership === "extend" - ); - if (otherExtenders.length > 0) { - throw new Error( - `Cannot uninstall package "${packageId}": object "${fqn}" is extended by ${otherExtenders.map((c) => c.packageId).join(", ")}. Uninstall extenders first.` - ); - } - } - const idx = contributors.indexOf(contrib); - if (idx !== -1) { - contributors.splice(idx, 1); - this.log(`[Registry] Removed ${contrib.ownership} contribution to ${fqn} from ${packageId}`); - } - } - if (contributors.length === 0) { - this.objectContributors.delete(fqn); - } - this.mergedObjectCache.delete(fqn); - } - } - // ========================================== - // Generic Metadata (Non-Object Types) - // ========================================== - /** - * Universal Register Method for non-object metadata. - */ - static registerItem(type, item, keyField = "name", packageId) { - if (!this.metadata.has(type)) { - this.metadata.set(type, /* @__PURE__ */ new Map()); - } - const collection = this.metadata.get(type); - const baseName = String(item[keyField]); - if (packageId) { - item._packageId = packageId; - } - try { - this.validate(type, item); - } catch (e) { - console.error(`[Registry] Validation failed for ${type} ${baseName}: ${e.message}`); - } - const storageKey = packageId ? `${packageId}:${baseName}` : baseName; - if (collection.has(storageKey)) { - console.warn(`[Registry] Overwriting ${type}: ${storageKey}`); - } - collection.set(storageKey, item); - this.log(`[Registry] Registered ${type}: ${storageKey}`); - } - /** - * Validate Metadata against Spec Zod Schemas - */ - static validate(type, item) { - if (type === "object") { - return ObjectSchema3.parse(item); - } - if (type === "app") { - return AppSchema2.parse(item); - } - if (type === "package") { - return InstalledPackageSchema2.parse(item); - } - if (type === "plugin") { - return ManifestSchema2.parse(item); - } - return true; - } - /** - * Universal Unregister Method - */ - static unregisterItem(type, name) { - const collection = this.metadata.get(type); - if (!collection) { - console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`); - return; - } - if (collection.has(name)) { - collection.delete(name); - this.log(`[Registry] Unregistered ${type}: ${name}`); - return; - } - for (const key of collection.keys()) { - if (key.endsWith(`:${name}`)) { - collection.delete(key); - this.log(`[Registry] Unregistered ${type}: ${key}`); - return; - } - } - console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`); - } - /** - * Universal Get Method - */ - static getItem(type, name) { - if (type === "object" || type === "objects") { - return this.getObject(name); - } - const collection = this.metadata.get(type); - if (!collection) return void 0; - const direct = collection.get(name); - if (direct) return direct; - for (const [key, item] of collection) { - if (key.endsWith(`:${name}`)) return item; - } - return void 0; - } - /** - * Universal List Method - */ - static listItems(type, packageId) { - if (type === "object" || type === "objects") { - return this.getAllObjects(packageId); - } - const items = Array.from(this.metadata.get(type)?.values() || []); - if (packageId) { - return items.filter((item) => item._packageId === packageId); - } - return items; - } - /** - * Get all registered metadata types (Kinds) - */ - static getRegisteredTypes() { - const types = Array.from(this.metadata.keys()); - if (!types.includes("object") && this.objectContributors.size > 0) { - types.push("object"); - } - return types; - } - // ========================================== - // Package Management - // ========================================== - static installPackage(manifest, settings) { - const now2 = (/* @__PURE__ */ new Date()).toISOString(); - const pkg = { - manifest, - status: "installed", - enabled: true, - installedAt: now2, - updatedAt: now2, - settings - }; - if (manifest.namespace) { - this.registerNamespace(manifest.namespace, manifest.id); - } - if (!this.metadata.has("package")) { - this.metadata.set("package", /* @__PURE__ */ new Map()); - } - const collection = this.metadata.get("package"); - if (collection.has(manifest.id)) { - console.warn(`[Registry] Overwriting package: ${manifest.id}`); - } - collection.set(manifest.id, pkg); - this.log(`[Registry] Installed package: ${manifest.id} (${manifest.name})`); - return pkg; - } - static uninstallPackage(id) { - const pkg = this.getPackage(id); - if (!pkg) { - console.warn(`[Registry] Package not found for uninstall: ${id}`); - return false; - } - if (pkg.manifest.namespace) { - this.unregisterNamespace(pkg.manifest.namespace, id); - } - this.unregisterObjectsByPackage(id); - const collection = this.metadata.get("package"); - if (collection) { - collection.delete(id); - this.log(`[Registry] Uninstalled package: ${id}`); - return true; - } - return false; - } - static getPackage(id) { - return this.metadata.get("package")?.get(id); - } - static getAllPackages() { - return this.listItems("package"); - } - static enablePackage(id) { - const pkg = this.getPackage(id); - if (pkg) { - pkg.enabled = true; - pkg.status = "installed"; - pkg.statusChangedAt = (/* @__PURE__ */ new Date()).toISOString(); - pkg.updatedAt = (/* @__PURE__ */ new Date()).toISOString(); - this.log(`[Registry] Enabled package: ${id}`); - } - return pkg; - } - static disablePackage(id) { - const pkg = this.getPackage(id); - if (pkg) { - pkg.enabled = false; - pkg.status = "disabled"; - pkg.statusChangedAt = (/* @__PURE__ */ new Date()).toISOString(); - pkg.updatedAt = (/* @__PURE__ */ new Date()).toISOString(); - this.log(`[Registry] Disabled package: ${id}`); - } - return pkg; - } - // ========================================== - // App Helpers - // ========================================== - static registerApp(app, packageId) { - this.registerItem("app", app, "name", packageId); - } - static getApp(name) { - return this.getItem("app", name); - } - static getAllApps() { - return this.listItems("app"); - } - // ========================================== - // Plugin Helpers - // ========================================== - static registerPlugin(manifest) { - this.registerItem("plugin", manifest, "id"); - } - static getAllPlugins() { - return this.listItems("plugin"); - } - // ========================================== - // Kind Helpers - // ========================================== - static registerKind(kind) { - this.registerItem("kind", kind, "id"); - } - static getAllKinds() { - return this.listItems("kind"); - } - // ========================================== - // Reset (for testing) - // ========================================== - /** - * Clear all registry state. Use only for testing. - */ - static reset() { - this.objectContributors.clear(); - this.mergedObjectCache.clear(); - this.namespaceRegistry.clear(); - this.metadata.clear(); - this.log("[Registry] Reset complete"); - } -}; -SchemaRegistry._logLevel = "info"; -SchemaRegistry.objectContributors = /* @__PURE__ */ new Map(); -SchemaRegistry.mergedObjectCache = /* @__PURE__ */ new Map(); -SchemaRegistry.namespaceRegistry = /* @__PURE__ */ new Map(); -SchemaRegistry.metadata = /* @__PURE__ */ new Map(); -function simpleHash(str) { - let hash2 = 0; - for (let i = 0; i < str.length; i++) { - const char = str.charCodeAt(i); - hash2 = (hash2 << 5) - hash2 + char; - hash2 = hash2 & hash2; - } - return Math.abs(hash2).toString(16); -} -var SERVICE_CONFIG = { - auth: { route: "/api/v1/auth", plugin: "plugin-auth" }, - automation: { route: "/api/v1/automation", plugin: "plugin-automation" }, - cache: { route: "/api/v1/cache", plugin: "plugin-redis" }, - queue: { route: "/api/v1/queue", plugin: "plugin-bullmq" }, - job: { route: "/api/v1/jobs", plugin: "job-scheduler" }, - ui: { route: "/api/v1/ui", plugin: "ui-plugin" }, - workflow: { route: "/api/v1/workflow", plugin: "plugin-workflow" }, - realtime: { route: "/api/v1/realtime", plugin: "plugin-realtime" }, - notification: { route: "/api/v1/notifications", plugin: "plugin-notifications" }, - ai: { route: "/api/v1/ai", plugin: "plugin-ai" }, - i18n: { route: "/api/v1/i18n", plugin: "service-i18n" }, - graphql: { route: "/graphql", plugin: "plugin-graphql" }, - // GraphQL uses /graphql by convention (not versioned REST) - "file-storage": { route: "/api/v1/storage", plugin: "plugin-storage" }, - search: { route: "/api/v1/search", plugin: "plugin-search" } -}; -var ObjectStackProtocolImplementation = class { - constructor(engine, getServicesRegistry, getFeedService) { - this.engine = engine; - this.getServicesRegistry = getServicesRegistry; - this.getFeedService = getFeedService; - } - requireFeedService() { - const svc = this.getFeedService?.(); - if (!svc) { - throw new Error("Feed service not available. Install and register service-feed to enable feed operations."); - } - return svc; - } - async getDiscovery() { - const registeredServices = this.getServicesRegistry ? this.getServicesRegistry() : /* @__PURE__ */ new Map(); - const services = { - // --- Kernel-provided (objectql is an example kernel implementation) --- - metadata: { enabled: true, status: "available", route: "/api/v1/meta", provider: "objectql" }, - data: { enabled: true, status: "available", route: "/api/v1/data", provider: "objectql" }, - analytics: { enabled: true, status: "available", route: "/api/v1/analytics", provider: "objectql" } - }; - for (const [serviceName, config4] of Object.entries(SERVICE_CONFIG)) { - if (registeredServices.has(serviceName)) { - services[serviceName] = { - enabled: true, - status: "available", - route: config4.route, - provider: config4.plugin - }; - } else { - services[serviceName] = { - enabled: false, - status: "unavailable", - message: `Install ${config4.plugin} to enable` - }; - } - } - const serviceToRouteKey = { - auth: "auth", - automation: "automation", - ui: "ui", - workflow: "workflow", - realtime: "realtime", - notification: "notifications", - ai: "ai", - i18n: "i18n", - graphql: "graphql", - "file-storage": "storage" - }; - const optionalRoutes = { - analytics: "/api/v1/analytics" - }; - for (const [serviceName, config4] of Object.entries(SERVICE_CONFIG)) { - if (registeredServices.has(serviceName)) { - const routeKey = serviceToRouteKey[serviceName]; - if (routeKey) { - optionalRoutes[routeKey] = config4.route; - } - } - } - if (registeredServices.has("feed")) { - services["feed"] = { - enabled: true, - status: "available", - route: "/api/v1/data", - provider: "service-feed" - }; - } else { - services["feed"] = { - enabled: false, - status: "unavailable", - message: "Install service-feed to enable" - }; - } - const routes = { - data: "/api/v1/data", - metadata: "/api/v1/meta", - ...optionalRoutes - }; - const wellKnown = { - feed: registeredServices.has("feed"), - comments: registeredServices.has("feed"), - automation: registeredServices.has("automation"), - cron: registeredServices.has("job"), - search: registeredServices.has("search"), - export: registeredServices.has("automation") || registeredServices.has("queue"), - chunkedUpload: registeredServices.has("file-storage") - }; - const capabilities = {}; - for (const [key, enabled] of Object.entries(wellKnown)) { - capabilities[key] = { enabled }; - } - return { - version: "1.0", - apiName: "ObjectStack API", - routes, - services, - capabilities - }; - } - async getMetaTypes() { - const schemaTypes = SchemaRegistry.getRegisteredTypes(); - let runtimeTypes = []; - try { - const services = this.getServicesRegistry?.(); - const metadataService = services?.get("metadata"); - if (metadataService && typeof metadataService.getRegisteredTypes === "function") { - runtimeTypes = await metadataService.getRegisteredTypes(); - } - } catch { - } - const allTypes = Array.from(/* @__PURE__ */ new Set([...schemaTypes, ...runtimeTypes])); - return { types: allTypes }; - } - async getMetaItems(request) { - const { packageId } = request; - let items = SchemaRegistry.listItems(request.type, packageId); - if (items.length === 0) { - const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; - if (alt) items = SchemaRegistry.listItems(alt, packageId); - } - if (items.length === 0) { - try { - const whereClause = { type: request.type, state: "active" }; - if (packageId) whereClause._packageId = packageId; - const allRecords = await this.engine.find("sys_metadata", { - where: whereClause - }); - if (allRecords && allRecords.length > 0) { - items = allRecords.map((record2) => { - const data = typeof record2.metadata === "string" ? JSON.parse(record2.metadata) : record2.metadata; - SchemaRegistry.registerItem(request.type, data, "name"); - return data; - }); - } else { - const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; - if (alt) { - const altRecords = await this.engine.find("sys_metadata", { - where: { type: alt, state: "active" } - }); - if (altRecords && altRecords.length > 0) { - items = altRecords.map((record2) => { - const data = typeof record2.metadata === "string" ? JSON.parse(record2.metadata) : record2.metadata; - SchemaRegistry.registerItem(request.type, data, "name"); - return data; - }); - } - } - } - } catch { - } - } - try { - const services = this.getServicesRegistry?.(); - const metadataService = services?.get("metadata"); - if (metadataService && typeof metadataService.list === "function") { - const runtimeItems = await metadataService.list(request.type); - if (runtimeItems && runtimeItems.length > 0) { - const itemMap = /* @__PURE__ */ new Map(); - for (const item of items) { - const entry = item; - if (entry && typeof entry === "object" && "name" in entry) { - itemMap.set(entry.name, entry); - } - } - for (const item of runtimeItems) { - const entry = item; - if (entry && typeof entry === "object" && "name" in entry) { - itemMap.set(entry.name, entry); - } - } - items = Array.from(itemMap.values()); - } - } - } catch { - } - return { - type: request.type, - items - }; - } - async getMetaItem(request) { - let item = SchemaRegistry.getItem(request.type, request.name); - if (item === void 0) { - const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; - if (alt) item = SchemaRegistry.getItem(alt, request.name); - } - if (item === void 0) { - try { - const record2 = await this.engine.findOne("sys_metadata", { - where: { type: request.type, name: request.name, state: "active" } - }); - if (record2) { - item = typeof record2.metadata === "string" ? JSON.parse(record2.metadata) : record2.metadata; - SchemaRegistry.registerItem(request.type, item, "name"); - } else { - const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; - if (alt) { - const altRecord = await this.engine.findOne("sys_metadata", { - where: { type: alt, name: request.name, state: "active" } - }); - if (altRecord) { - item = typeof altRecord.metadata === "string" ? JSON.parse(altRecord.metadata) : altRecord.metadata; - SchemaRegistry.registerItem(request.type, item, "name"); - } - } - } - } catch { - } - } - if (item === void 0) { - try { - const services = this.getServicesRegistry?.(); - const metadataService = services?.get("metadata"); - if (metadataService && typeof metadataService.get === "function") { - item = await metadataService.get(request.type, request.name); - } - } catch { - } - } - return { - type: request.type, - name: request.name, - item - }; - } - async getUiView(request) { - const schema3 = SchemaRegistry.getObject(request.object); - if (!schema3) throw new Error(`Object ${request.object} not found`); - const fields = schema3.fields || {}; - const fieldKeys = Object.keys(fields); - if (request.type === "list") { - const priorityFields = ["name", "title", "label", "subject", "email", "status", "type", "category", "created_at"]; - let columns = fieldKeys.filter((k) => priorityFields.includes(k)); - if (columns.length < 5) { - const remaining = fieldKeys.filter((k) => !columns.includes(k) && k !== "id" && !fields[k].hidden); - columns = [...columns, ...remaining.slice(0, 5 - columns.length)]; - } - return { - list: { - type: "grid", - object: request.object, - label: schema3.label || schema3.name, - columns: columns.map((f) => ({ - field: f, - label: fields[f]?.label || f, - sortable: true - })), - sort: fields["created_at"] ? [{ field: "created_at", order: "desc" }] : void 0, - searchableFields: columns.slice(0, 3) - // Make first few textual columns searchable - } - }; - } else { - const formFields = fieldKeys.filter((k) => k !== "id" && k !== "created_at" && k !== "updated_at" && !fields[k].hidden).map((f) => ({ - field: f, - label: fields[f]?.label, - required: fields[f]?.required, - readonly: fields[f]?.readonly, - type: fields[f]?.type, - // Default to 2 columns for most, 1 for textareas - colSpan: fields[f]?.type === "textarea" || fields[f]?.type === "html" ? 2 : 1 - })); - return { - form: { - type: "simple", - object: request.object, - label: `Edit ${schema3.label || schema3.name}`, - sections: [ - { - label: "General Information", - columns: 2, - collapsible: false, - collapsed: false, - fields: formFields - } - ] - } - }; - } - } - async findData(request) { - const options = { ...request.query }; - if (options.top != null) { - options.limit = Number(options.top); - delete options.top; - } - if (options.skip != null) { - options.offset = Number(options.skip); - delete options.skip; - } - if (options.limit != null) options.limit = Number(options.limit); - if (options.offset != null) options.offset = Number(options.offset); - if (typeof options.select === "string") { - options.fields = options.select.split(",").map((s) => s.trim()).filter(Boolean); - } else if (Array.isArray(options.select)) { - options.fields = options.select; - } - if (options.select !== void 0) delete options.select; - const sortValue = options.orderBy ?? options.sort; - if (typeof sortValue === "string") { - const parsed = sortValue.split(",").map((part) => { - const trimmed = part.trim(); - if (trimmed.startsWith("-")) { - return { field: trimmed.slice(1), order: "desc" }; - } - const [field, order] = trimmed.split(/\s+/); - return { field, order: order?.toLowerCase() === "desc" ? "desc" : "asc" }; - }).filter((s) => s.field); - options.orderBy = parsed; - } else if (Array.isArray(sortValue)) { - options.orderBy = sortValue; - } - delete options.sort; - const filterValue = options.filter ?? options.filters ?? options.$filter ?? options.where; - delete options.filter; - delete options.filters; - delete options.$filter; - if (filterValue !== void 0) { - let parsedFilter = filterValue; - if (typeof parsedFilter === "string") { - try { - parsedFilter = JSON.parse(parsedFilter); - } catch { - } - } - if (isFilterAST(parsedFilter)) { - parsedFilter = parseFilterAST(parsedFilter); - } - options.where = parsedFilter; - } - const populateValue = options.populate; - const expandValue = options.$expand ?? options.expand; - const expandNames = []; - if (typeof populateValue === "string") { - expandNames.push(...populateValue.split(",").map((s) => s.trim()).filter(Boolean)); - } else if (Array.isArray(populateValue)) { - expandNames.push(...populateValue); - } - if (!expandNames.length && expandValue) { - if (typeof expandValue === "string") { - expandNames.push(...expandValue.split(",").map((s) => s.trim()).filter(Boolean)); - } else if (Array.isArray(expandValue)) { - expandNames.push(...expandValue); - } - } - delete options.populate; - delete options.$expand; - if (typeof options.expand !== "object" || options.expand === null) { - delete options.expand; - } - if (expandNames.length > 0 && !options.expand) { - options.expand = {}; - for (const rel of expandNames) { - options.expand[rel] = { object: rel }; - } - } - for (const key of ["distinct", "count"]) { - if (options[key] === "true") options[key] = true; - else if (options[key] === "false") options[key] = false; - } - const knownParams = /* @__PURE__ */ new Set([ - "top", - "limit", - "offset", - "orderBy", - "fields", - "where", - "expand", - "distinct", - "count", - "aggregations", - "groupBy", - "search", - "context", - "cursor" - ]); - if (!options.where) { - const implicitFilters = {}; - for (const key of Object.keys(options)) { - if (!knownParams.has(key)) { - implicitFilters[key] = options[key]; - delete options[key]; - } - } - if (Object.keys(implicitFilters).length > 0) { - options.where = implicitFilters; - } - } - const records = await this.engine.find(request.object, options); - return { - object: request.object, - records, - total: records.length, - hasMore: false - }; - } - async getData(request) { - const queryOptions = { - where: { id: request.id } - }; - if (request.select) { - queryOptions.fields = typeof request.select === "string" ? request.select.split(",").map((s) => s.trim()).filter(Boolean) : request.select; - } - if (request.expand) { - const expandNames = typeof request.expand === "string" ? request.expand.split(",").map((s) => s.trim()).filter(Boolean) : request.expand; - queryOptions.expand = {}; - for (const rel of expandNames) { - queryOptions.expand[rel] = { object: rel }; - } - } - const result = await this.engine.findOne(request.object, queryOptions); - if (result) { - return { - object: request.object, - id: request.id, - record: result - }; - } - throw new Error(`Record ${request.id} not found in ${request.object}`); - } - async createData(request) { - const result = await this.engine.insert(request.object, request.data); - return { - object: request.object, - id: result.id, - record: result - }; - } - async updateData(request) { - const result = await this.engine.update(request.object, request.data, { where: { id: request.id } }); - return { - object: request.object, - id: request.id, - record: result - }; - } - async deleteData(request) { - await this.engine.delete(request.object, { where: { id: request.id } }); - return { - object: request.object, - id: request.id, - success: true - }; - } - // ========================================== - // Metadata Caching - // ========================================== - async getMetaItemCached(request) { - try { - let item = SchemaRegistry.getItem(request.type, request.name); - if (!item) { - const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type]; - if (alt) item = SchemaRegistry.getItem(alt, request.name); - } - if (!item) { - try { - const services = this.getServicesRegistry?.(); - const metadataService = services?.get("metadata"); - if (metadataService && typeof metadataService.get === "function") { - item = await metadataService.get(request.type, request.name); - } - } catch { - } - } - if (!item) { - throw new Error(`Metadata item ${request.type}/${request.name} not found`); - } - const content = JSON.stringify(item); - const hash2 = simpleHash(content); - const etag = { value: hash2, weak: false }; - if (request.cacheRequest?.ifNoneMatch) { - const clientEtag = request.cacheRequest.ifNoneMatch.replace(/^"(.*)"$/, "$1").replace(/^W\/"(.*)"$/, "$1"); - if (clientEtag === hash2) { - return { - notModified: true, - etag - }; - } - } - return { - data: item, - etag, - lastModified: (/* @__PURE__ */ new Date()).toISOString(), - cacheControl: { - directives: ["public", "max-age"], - maxAge: 3600 - // 1 hour - }, - notModified: false - }; - } catch (error49) { - throw error49; - } - } - // ========================================== - // Batch Operations - // ========================================== - async batchData(request) { - const { object: object2, request: batchReq } = request; - const { operation, records, options } = batchReq; - const results = []; - let succeeded = 0; - let failed = 0; - for (const record2 of records) { - try { - switch (operation) { - case "create": { - const created = await this.engine.insert(object2, record2.data || record2); - results.push({ id: created.id, success: true, record: created }); - succeeded++; - break; - } - case "update": { - if (!record2.id) throw new Error("Record id is required for update"); - const updated = await this.engine.update(object2, record2.data || {}, { where: { id: record2.id } }); - results.push({ id: record2.id, success: true, record: updated }); - succeeded++; - break; - } - case "upsert": { - if (record2.id) { - try { - const existing = await this.engine.findOne(object2, { where: { id: record2.id } }); - if (existing) { - const updated = await this.engine.update(object2, record2.data || {}, { where: { id: record2.id } }); - results.push({ id: record2.id, success: true, record: updated }); - } else { - const created = await this.engine.insert(object2, { id: record2.id, ...record2.data || {} }); - results.push({ id: created.id, success: true, record: created }); - } - } catch { - const created = await this.engine.insert(object2, { id: record2.id, ...record2.data || {} }); - results.push({ id: created.id, success: true, record: created }); - } - } else { - const created = await this.engine.insert(object2, record2.data || record2); - results.push({ id: created.id, success: true, record: created }); - } - succeeded++; - break; - } - case "delete": { - if (!record2.id) throw new Error("Record id is required for delete"); - await this.engine.delete(object2, { where: { id: record2.id } }); - results.push({ id: record2.id, success: true }); - succeeded++; - break; - } - default: - results.push({ id: record2.id, success: false, error: `Unknown operation: ${operation}` }); - failed++; - } - } catch (err) { - results.push({ id: record2.id, success: false, error: err.message }); - failed++; - if (options?.atomic) { - break; - } - if (!options?.continueOnError) { - break; - } - } - } - return { - success: failed === 0, - operation, - total: records.length, - succeeded, - failed, - results: options?.returnRecords !== false ? results : results.map((r) => ({ id: r.id, success: r.success, error: r.error })) - }; - } - async createManyData(request) { - const records = await this.engine.insert(request.object, request.records); - return { - object: request.object, - records, - count: records.length - }; - } - async updateManyData(request) { - const { object: object2, records, options } = request; - const results = []; - let succeeded = 0; - let failed = 0; - for (const record2 of records) { - try { - const updated = await this.engine.update(object2, record2.data, { where: { id: record2.id } }); - results.push({ id: record2.id, success: true, record: updated }); - succeeded++; - } catch (err) { - results.push({ id: record2.id, success: false, error: err.message }); - failed++; - if (!options?.continueOnError) { - break; - } - } - } - return { - success: failed === 0, - operation: "update", - total: records.length, - succeeded, - failed, - results - }; - } - async analyticsQuery(request) { - const { query, cube } = request; - const object2 = cube; - const groupBy2 = query.dimensions || []; - const aggregations = []; - if (query.measures) { - for (const measure of query.measures) { - if (measure === "count" || measure === "count_all") { - aggregations.push({ field: "*", method: "count", alias: "count" }); - } else if (measure.includes(".")) { - const [field, method] = measure.split("."); - aggregations.push({ field, method, alias: `${field}_${method}` }); - } else { - aggregations.push({ field: measure, method: "sum", alias: measure }); - } - } - } - let filter = void 0; - if (query.filters && query.filters.length > 0) { - const conditions = query.filters.map((f) => { - const op = this.mapAnalyticsOperator(f.operator); - if (f.values && f.values.length === 1) { - return { [f.member]: { [op]: f.values[0] } }; - } else if (f.values && f.values.length > 1) { - return { [f.member]: { $in: f.values } }; - } - return { [f.member]: { [op]: true } }; - }); - filter = conditions.length === 1 ? conditions[0] : { $and: conditions }; - } - const rows = await this.engine.aggregate(object2, { - where: filter, - groupBy: groupBy2.length > 0 ? groupBy2 : void 0, - aggregations: aggregations.length > 0 ? aggregations.map((a) => ({ function: a.method, field: a.field, alias: a.alias })) : [{ function: "count", alias: "count" }] - }); - const fields = [ - ...groupBy2.map((d) => ({ name: d, type: "string" })), - ...aggregations.map((a) => ({ name: a.alias, type: "number" })) - ]; - return { - success: true, - data: { - rows, - fields - } - }; - } - async getAnalyticsMeta(request) { - const objects = SchemaRegistry.listItems("object"); - const cubeFilter = request?.cube; - const cubes = []; - for (const obj of objects) { - const schema3 = obj; - if (cubeFilter && schema3.name !== cubeFilter) continue; - const measures = {}; - const dimensions = {}; - const fields = schema3.fields || {}; - measures["count"] = { - name: "count", - label: "Count", - type: "count", - sql: "*" - }; - for (const [fieldName, fieldDef] of Object.entries(fields)) { - const fd = fieldDef; - const fieldType = fd.type || "text"; - if (["number", "currency", "percent"].includes(fieldType)) { - measures[`${fieldName}_sum`] = { - name: `${fieldName}_sum`, - label: `${fd.label || fieldName} (Sum)`, - type: "sum", - sql: fieldName - }; - measures[`${fieldName}_avg`] = { - name: `${fieldName}_avg`, - label: `${fd.label || fieldName} (Avg)`, - type: "avg", - sql: fieldName - }; - dimensions[fieldName] = { - name: fieldName, - label: fd.label || fieldName, - type: "number", - sql: fieldName - }; - } else if (["date", "datetime"].includes(fieldType)) { - dimensions[fieldName] = { - name: fieldName, - label: fd.label || fieldName, - type: "time", - sql: fieldName, - granularities: ["day", "week", "month", "quarter", "year"] - }; - } else if (["boolean"].includes(fieldType)) { - dimensions[fieldName] = { - name: fieldName, - label: fd.label || fieldName, - type: "boolean", - sql: fieldName - }; - } else { - dimensions[fieldName] = { - name: fieldName, - label: fd.label || fieldName, - type: "string", - sql: fieldName - }; - } - } - cubes.push({ - name: schema3.name, - title: schema3.label || schema3.name, - description: schema3.description, - sql: schema3.name, - measures, - dimensions, - public: true - }); - } - return { - success: true, - data: { cubes } - }; - } - mapAnalyticsOperator(op) { - const map3 = { - equals: "$eq", - notEquals: "$ne", - contains: "$contains", - notContains: "$notContains", - gt: "$gt", - gte: "$gte", - lt: "$lt", - lte: "$lte", - set: "$ne", - notSet: "$eq" - }; - return map3[op] || "$eq"; - } - async triggerAutomation(_request2) { - throw new Error('triggerAutomation requires plugin-automation service. Install and register a plugin that provides the "automation" service.'); - } - async deleteManyData(request) { - return this.engine.delete(request.object, { - where: { id: { $in: request.ids } }, - ...request.options - }); - } - async saveMetaItem(request) { - if (!request.item) { - throw new Error("Item data is required"); - } - SchemaRegistry.registerItem(request.type, request.item, "name"); - try { - const now2 = (/* @__PURE__ */ new Date()).toISOString(); - const existing = await this.engine.findOne("sys_metadata", { - where: { type: request.type, name: request.name } - }); - if (existing) { - await this.engine.update("sys_metadata", { - metadata: JSON.stringify(request.item), - updated_at: now2, - version: (existing.version || 0) + 1 - }, { - where: { id: existing.id } - }); - } else { - const id = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `meta_${Date.now()}_${Math.random().toString(36).slice(2)}`; - await this.engine.insert("sys_metadata", { - id, - name: request.name, - type: request.type, - scope: "platform", - metadata: JSON.stringify(request.item), - state: "active", - version: 1, - created_at: now2, - updated_at: now2 - }); - } - return { - success: true, - message: "Saved to database and registry" - }; - } catch (dbError) { - console.warn(`[Protocol] DB persistence failed for ${request.type}/${request.name}: ${dbError.message}`); - return { - success: true, - message: "Saved to memory registry (DB persistence unavailable)", - warning: dbError.message - }; - } - } - /** - * Hydrate SchemaRegistry from the database on startup. - * Loads all active metadata records and registers them in the in-memory registry. - * Safe to call repeatedly — idempotent (latest DB record wins). - */ - async loadMetaFromDb() { - let loaded = 0; - let errors = 0; - try { - const records = await this.engine.find("sys_metadata", { - where: { state: "active" } - }); - for (const record2 of records) { - try { - const data = typeof record2.metadata === "string" ? JSON.parse(record2.metadata) : record2.metadata; - const normalizedType = PLURAL_TO_SINGULAR[record2.type] ?? record2.type; - if (normalizedType === "object") { - SchemaRegistry.registerObject(data, record2.packageId || "sys_metadata"); - } else { - SchemaRegistry.registerItem(normalizedType, data, "name"); - } - loaded++; - } catch (e) { - errors++; - console.warn(`[Protocol] Failed to hydrate ${record2.type}/${record2.name}: ${e instanceof Error ? e.message : String(e)}`); - } - } - } catch (e) { - console.warn(`[Protocol] DB hydration skipped: ${e.message}`); - } - return { loaded, errors }; - } - // ========================================== - // Feed Operations - // ========================================== - async listFeed(request) { - const svc = this.requireFeedService(); - const result = await svc.listFeed({ - object: request.object, - recordId: request.recordId, - filter: request.type, - limit: request.limit, - cursor: request.cursor - }); - return { success: true, data: result }; - } - async createFeedItem(request) { - const svc = this.requireFeedService(); - const item = await svc.createFeedItem({ - object: request.object, - recordId: request.recordId, - type: request.type, - actor: { type: "user", id: "current_user" }, - body: request.body, - mentions: request.mentions, - parentId: request.parentId, - visibility: request.visibility - }); - return { success: true, data: item }; - } - async updateFeedItem(request) { - const svc = this.requireFeedService(); - const item = await svc.updateFeedItem(request.feedId, { - body: request.body, - mentions: request.mentions, - visibility: request.visibility - }); - return { success: true, data: item }; - } - async deleteFeedItem(request) { - const svc = this.requireFeedService(); - await svc.deleteFeedItem(request.feedId); - return { success: true, data: { feedId: request.feedId } }; - } - async addReaction(request) { - const svc = this.requireFeedService(); - const reactions = await svc.addReaction(request.feedId, request.emoji, "current_user"); - return { success: true, data: { reactions } }; - } - async removeReaction(request) { - const svc = this.requireFeedService(); - const reactions = await svc.removeReaction(request.feedId, request.emoji, "current_user"); - return { success: true, data: { reactions } }; - } - async pinFeedItem(request) { - const svc = this.requireFeedService(); - const item = await svc.getFeedItem(request.feedId); - if (!item) throw new Error(`Feed item ${request.feedId} not found`); - await svc.updateFeedItem(request.feedId, { visibility: item.visibility }); - return { success: true, data: { feedId: request.feedId, pinned: true, pinnedAt: (/* @__PURE__ */ new Date()).toISOString() } }; - } - async unpinFeedItem(request) { - const svc = this.requireFeedService(); - const item = await svc.getFeedItem(request.feedId); - if (!item) throw new Error(`Feed item ${request.feedId} not found`); - await svc.updateFeedItem(request.feedId, { visibility: item.visibility }); - return { success: true, data: { feedId: request.feedId, pinned: false } }; - } - async starFeedItem(request) { - const svc = this.requireFeedService(); - const item = await svc.getFeedItem(request.feedId); - if (!item) throw new Error(`Feed item ${request.feedId} not found`); - await svc.updateFeedItem(request.feedId, { visibility: item.visibility }); - return { success: true, data: { feedId: request.feedId, starred: true, starredAt: (/* @__PURE__ */ new Date()).toISOString() } }; - } - async unstarFeedItem(request) { - const svc = this.requireFeedService(); - const item = await svc.getFeedItem(request.feedId); - if (!item) throw new Error(`Feed item ${request.feedId} not found`); - await svc.updateFeedItem(request.feedId, { visibility: item.visibility }); - return { success: true, data: { feedId: request.feedId, starred: false } }; - } - async searchFeed(request) { - const svc = this.requireFeedService(); - const result = await svc.listFeed({ - object: request.object, - recordId: request.recordId, - filter: request.type, - limit: request.limit, - cursor: request.cursor - }); - const queryLower = (request.query || "").toLowerCase(); - const filtered = result.items.filter( - (item) => item.body?.toLowerCase().includes(queryLower) - ); - return { success: true, data: { items: filtered, total: filtered.length, hasMore: false } }; - } - async getChangelog(request) { - const svc = this.requireFeedService(); - const result = await svc.listFeed({ - object: request.object, - recordId: request.recordId, - filter: "changes_only", - limit: request.limit, - cursor: request.cursor - }); - const entries = result.items.map((item) => ({ - id: item.id, - object: item.object, - recordId: item.recordId, - actor: item.actor, - changes: item.changes || [], - timestamp: item.createdAt, - source: item.source - })); - return { success: true, data: { entries, total: result.total, nextCursor: result.nextCursor, hasMore: result.hasMore } }; - } - async feedSubscribe(request) { - const svc = this.requireFeedService(); - const subscription = await svc.subscribe({ - object: request.object, - recordId: request.recordId, - userId: "current_user", - events: request.events, - channels: request.channels - }); - return { success: true, data: subscription }; - } - async feedUnsubscribe(request) { - const svc = this.requireFeedService(); - const unsubscribed = await svc.unsubscribe(request.object, request.recordId, "current_user"); - return { success: true, data: { object: request.object, recordId: request.recordId, unsubscribed } }; - } -}; -var _ObjectQL = class _ObjectQL2 { - constructor(hostContext = {}) { - this.drivers = /* @__PURE__ */ new Map(); - this.defaultDriver = null; - this.hooks = /* @__PURE__ */ new Map([ - ["beforeFind", []], - ["afterFind", []], - ["beforeInsert", []], - ["afterInsert", []], - ["beforeUpdate", []], - ["afterUpdate", []], - ["beforeDelete", []], - ["afterDelete", []] - ]); - this.middlewares = []; - this.actions = /* @__PURE__ */ new Map(); - this.hostContext = {}; - this.hostContext = hostContext; - this.logger = hostContext.logger || createLogger({ level: "info", format: "pretty" }); - this.logger.info("ObjectQL Engine Instance Created"); - } - /** - * Service Status Report - * Used by Kernel to verify health and capabilities. - */ - getStatus() { - return { - name: CoreServiceName.enum.data, - status: "running", - version: "0.9.0", - features: ["crud", "query", "aggregate", "transactions", "metadata"] - }; - } - /** - * Expose the SchemaRegistry for plugins to register metadata - */ - get registry() { - return SchemaRegistry; - } - /** - * Load and Register a Plugin - */ - async use(manifestPart, runtimePart) { - this.logger.debug("Loading plugin", { - hasManifest: !!manifestPart, - hasRuntime: !!runtimePart - }); - if (manifestPart) { - this.registerApp(manifestPart); - } - if (runtimePart) { - const pluginDef = runtimePart.default || runtimePart; - if (pluginDef.onEnable) { - this.logger.debug("Executing plugin runtime onEnable"); - const context = { - ql: this, - logger: this.logger, - // Expose the driver registry helper explicitly if needed - drivers: { - register: (driver) => this.registerDriver(driver) - }, - ...this.hostContext - }; - await pluginDef.onEnable(context); - this.logger.debug("Plugin runtime onEnable completed"); - } - } - } - /** - * Register a hook - * @param event The event name (e.g. 'beforeFind', 'afterInsert') - * @param handler The handler function - * @param options Optional: target object(s) and priority - */ - registerHook(event, handler, options) { - if (!this.hooks.has(event)) { - this.hooks.set(event, []); - } - const entries = this.hooks.get(event); - entries.push({ - handler, - object: options?.object, - priority: options?.priority ?? 100, - packageId: options?.packageId - }); - entries.sort((a, b) => a.priority - b.priority); - this.logger.debug("Registered hook", { event, object: options?.object, priority: options?.priority ?? 100, totalHandlers: entries.length }); - } - async triggerHooks(event, context) { - const entries = this.hooks.get(event) || []; - if (entries.length === 0) { - this.logger.debug("No hooks registered for event", { event }); - return; - } - this.logger.debug("Triggering hooks", { event, count: entries.length }); - for (const entry of entries) { - if (entry.object) { - const targets = Array.isArray(entry.object) ? entry.object : [entry.object]; - if (!targets.includes("*") && !targets.includes(context.object)) { - continue; - } - } - await entry.handler(context); - } - } - // ======================================== - // Action System - // ======================================== - /** - * Register a named action on an object. - * Actions are custom business logic callable via `repo.execute(actionName, params)`. - * - * @param objectName Target object - * @param actionName Unique action name within the object - * @param handler Handler function - * @param packageName Optional package owner (for cleanup) - */ - registerAction(objectName, actionName, handler, packageName) { - const key = `${objectName}:${actionName}`; - this.actions.set(key, { handler, package: packageName }); - this.logger.debug("Registered action", { objectName, actionName, package: packageName }); - } - /** - * Execute a named action on an object. - */ - async executeAction(objectName, actionName, ctx) { - const entry = this.actions.get(`${objectName}:${actionName}`); - if (!entry) { - throw new Error(`Action '${actionName}' on object '${objectName}' not found`); - } - return entry.handler(ctx); - } - /** - * Remove all actions registered by a specific package. - */ - removeActionsByPackage(packageName) { - for (const [key, entry] of this.actions.entries()) { - if (entry.package === packageName) { - this.actions.delete(key); - } - } - } - /** - * Register a middleware function - * Middlewares execute in onion model around every data operation. - * @param fn The middleware function - * @param options Optional: target object filter - */ - registerMiddleware(fn, options) { - this.middlewares.push({ fn, object: options?.object }); - this.logger.debug("Registered middleware", { object: options?.object, total: this.middlewares.length }); - } - /** - * Execute an operation through the middleware chain - */ - async executeWithMiddleware(ctx, executor) { - const applicable = this.middlewares.filter( - (m) => !m.object || m.object === "*" || m.object === ctx.object - ); - let index = 0; - const next = async () => { - if (index < applicable.length) { - const mw = applicable[index++]; - await mw.fn(ctx, next); - } else { - ctx.result = await executor(); - } - }; - await next(); - return ctx.result; - } - /** - * Build a HookContext.session from ExecutionContext - */ - buildSession(execCtx) { - if (!execCtx) return void 0; - return { - userId: execCtx.userId, - tenantId: execCtx.tenantId, - roles: execCtx.roles, - accessToken: execCtx.accessToken - }; - } - /** - * Register contribution (Manifest) - * - * Installs the manifest as a Package (the unit of installation), - * then decomposes it into individual metadata items (objects, apps, actions, etc.) - * and registers each into the SchemaRegistry. - * - * Key: Package ≠ App. The manifest is the package. The apps[] array inside - * the manifest contains UI navigation definitions (AppSchema). - */ - registerApp(manifest) { - const id = manifest.id || manifest.name; - const namespace = manifest.namespace; - this.logger.debug("Registering package manifest", { id, namespace }); - SchemaRegistry.installPackage(manifest); - this.logger.debug("Installed Package", { id: manifest.id, name: manifest.name, namespace }); - if (manifest.objects) { - if (Array.isArray(manifest.objects)) { - this.logger.debug("Registering objects from manifest (Array)", { id, objectCount: manifest.objects.length }); - for (const objDef of manifest.objects) { - const fqn = SchemaRegistry.registerObject(objDef, id, namespace, "own"); - this.logger.debug("Registered Object", { fqn, from: id }); - } - } else { - this.logger.debug("Registering objects from manifest (Map)", { id, objectCount: Object.keys(manifest.objects).length }); - for (const [name, objDef] of Object.entries(manifest.objects)) { - objDef.name = name; - const fqn = SchemaRegistry.registerObject(objDef, id, namespace, "own"); - this.logger.debug("Registered Object", { fqn, from: id }); - } - } - } - if (Array.isArray(manifest.objectExtensions) && manifest.objectExtensions.length > 0) { - this.logger.debug("Registering object extensions", { id, count: manifest.objectExtensions.length }); - for (const ext of manifest.objectExtensions) { - const targetFqn = ext.extend; - const priority = ext.priority ?? 200; - const extDef = { - name: targetFqn, - // Use the target FQN as name - fields: ext.fields, - label: ext.label, - pluralLabel: ext.pluralLabel, - description: ext.description, - validations: ext.validations, - indexes: ext.indexes - }; - SchemaRegistry.registerObject(extDef, id, void 0, "extend", priority); - this.logger.debug("Registered Object Extension", { target: targetFqn, priority, from: id }); - } - } - if (Array.isArray(manifest.apps) && manifest.apps.length > 0) { - this.logger.debug("Registering apps from manifest", { id, count: manifest.apps.length }); - for (const app of manifest.apps) { - const appName = app.name || app.id; - if (appName) { - SchemaRegistry.registerApp(app, id); - this.logger.debug("Registered App", { app: appName, from: id }); - } - } - } - if (manifest.name && manifest.navigation && !manifest.apps?.length) { - SchemaRegistry.registerApp(manifest, id); - this.logger.debug("Registered manifest-as-app", { app: manifest.name, from: id }); - } - const metadataArrayKeys = [ - // UI Protocol - "actions", - "views", - "pages", - "dashboards", - "reports", - "themes", - // Automation Protocol - "flows", - "workflows", - "approvals", - "webhooks", - // Security Protocol - "roles", - "permissions", - "profiles", - "sharingRules", - "policies", - // AI Protocol - "agents", - "ragPipelines", - // API Protocol - "apis", - // Data Extensions - "hooks", - "mappings", - "analyticsCubes", - // Integration Protocol - "connectors" - ]; - for (const key of metadataArrayKeys) { - const items = manifest[key]; - if (Array.isArray(items) && items.length > 0) { - this.logger.debug(`Registering ${key} from manifest`, { id, count: items.length }); - for (const item of items) { - const itemName = item.name || item.id; - if (itemName) { - SchemaRegistry.registerItem(pluralToSingular(key), item, "name", id); - } - } - } - } - const seedData = manifest.data; - if (Array.isArray(seedData) && seedData.length > 0) { - this.logger.debug("Registering seed data datasets", { id, count: seedData.length }); - for (const dataset of seedData) { - if (dataset.object) { - SchemaRegistry.registerItem("data", dataset, "object", id); - } - } - } - if (manifest.contributes?.kinds) { - this.logger.debug("Registering kinds from manifest", { id, kindCount: manifest.contributes.kinds.length }); - for (const kind of manifest.contributes.kinds) { - SchemaRegistry.registerKind(kind); - this.logger.debug("Registered Kind", { kind: kind.name || kind.type, from: id }); - } - } - if (Array.isArray(manifest.plugins) && manifest.plugins.length > 0) { - this.logger.debug("Processing nested plugins", { id, count: manifest.plugins.length }); - for (const plugin of manifest.plugins) { - if (plugin && typeof plugin === "object") { - const pluginName = plugin.name || plugin.id || "unnamed-plugin"; - this.logger.debug("Registering nested plugin", { pluginName, parentId: id }); - this.registerPlugin(plugin, id, namespace); - } - } - } - } - /** - * Register a nested plugin's metadata (objects, actions, views, etc.) - * - * Unlike registerApp(), this does NOT call SchemaRegistry.installPackage() - * because plugins are not formal manifests — they are lightweight config - * bundles with objects, actions, triggers, and navigation. - * - * @param plugin - The plugin config object - * @param parentId - The parent package ID (for ownership tracking) - * @param parentNamespace - The parent package's namespace (for FQN resolution) - */ - registerPlugin(plugin, parentId, parentNamespace) { - const pluginName = plugin.name || plugin.id || "unnamed"; - const pluginNamespace = plugin.namespace || parentNamespace; - const ownerId = parentId; - if (plugin.objects) { - try { - if (Array.isArray(plugin.objects)) { - this.logger.debug("Registering plugin objects (Array)", { pluginName, count: plugin.objects.length }); - for (const objDef of plugin.objects) { - const fqn = SchemaRegistry.registerObject(objDef, ownerId, pluginNamespace, "own"); - this.logger.debug("Registered Object", { fqn, from: pluginName }); - } - } else { - const entries = Object.entries(plugin.objects); - this.logger.debug("Registering plugin objects (Map)", { pluginName, count: entries.length }); - for (const [name, objDef] of entries) { - objDef.name = name; - const fqn = SchemaRegistry.registerObject(objDef, ownerId, pluginNamespace, "own"); - this.logger.debug("Registered Object", { fqn, from: pluginName }); - } - } - } catch (err) { - this.logger.warn("Failed to register plugin objects", { pluginName, error: err.message }); - } - } - if (plugin.name && plugin.navigation) { - try { - SchemaRegistry.registerApp(plugin, ownerId); - this.logger.debug("Registered plugin-as-app", { app: plugin.name, from: pluginName }); - } catch (err) { - this.logger.warn("Failed to register plugin as app", { pluginName, error: err.message }); - } - } - const metadataArrayKeys = [ - "actions", - "views", - "pages", - "dashboards", - "reports", - "themes", - "flows", - "workflows", - "approvals", - "webhooks", - "roles", - "permissions", - "profiles", - "sharingRules", - "policies", - "agents", - "ragPipelines", - "apis", - "hooks", - "mappings", - "analyticsCubes", - "connectors" - ]; - for (const key of metadataArrayKeys) { - const items = plugin[key]; - if (Array.isArray(items) && items.length > 0) { - for (const item of items) { - const itemName = item.name || item.id; - if (itemName) { - SchemaRegistry.registerItem(pluralToSingular(key), item, "name", ownerId); - } - } - } - } - } - /** - * Register a new storage driver - */ - registerDriver(driver, isDefault = false) { - if (this.drivers.has(driver.name)) { - this.logger.warn("Driver already registered, skipping", { driverName: driver.name }); - return; - } - this.drivers.set(driver.name, driver); - this.logger.info("Registered driver", { - driverName: driver.name, - version: driver.version - }); - if (isDefault || this.drivers.size === 1) { - this.defaultDriver = driver.name; - this.logger.info("Set default driver", { driverName: driver.name }); - } - } - /** - * Set the realtime service for publishing data change events. - * Should be called after kernel resolves the realtime service. - * - * @param service - An IRealtimeService instance for event publishing - */ - setRealtimeService(service) { - this.realtimeService = service; - this.logger.info("RealtimeService configured for data events"); - } - /** - * Helper to get object definition - */ - getSchema(objectName) { - return SchemaRegistry.getObject(objectName); - } - /** - * Resolve an object name to its Fully Qualified Name (FQN). - * - * Short names like 'task' are resolved to FQN like 'todo__task' - * via SchemaRegistry lookup. If no match is found, the name is - * returned as-is (for ad-hoc / unregistered objects). - * - * This ensures that all driver operations use a consistent key - * regardless of whether the caller uses the short name or FQN. - */ - resolveObjectName(name) { - const schema3 = SchemaRegistry.getObject(name); - if (schema3) { - return schema3.tableName || schema3.name; - } - return name; - } - /** - * Helper to get the target driver - */ - getDriver(objectName) { - const object2 = SchemaRegistry.getObject(objectName); - if (object2) { - const datasourceName = object2.datasource || "default"; - if (datasourceName === "default") { - if (this.defaultDriver && this.drivers.has(this.defaultDriver)) { - return this.drivers.get(this.defaultDriver); - } - } else { - if (this.drivers.has(datasourceName)) { - return this.drivers.get(datasourceName); - } - throw new Error(`[ObjectQL] Datasource '${datasourceName}' configured for object '${objectName}' is not registered.`); - } - } - if (this.defaultDriver) { - return this.drivers.get(this.defaultDriver); - } - throw new Error(`[ObjectQL] No driver available for object '${objectName}'`); - } - /** - * Initialize the engine and all registered drivers - */ - async init() { - this.logger.info("Initializing ObjectQL engine", { - driverCount: this.drivers.size, - drivers: Array.from(this.drivers.keys()) - }); - const failedDrivers = []; - for (const [name, driver] of this.drivers) { - try { - await driver.connect(); - this.logger.info("Driver connected successfully", { driverName: name }); - } catch (e) { - failedDrivers.push(name); - this.logger.error("Failed to connect driver", e, { driverName: name }); - } - } - if (failedDrivers.length > 0) { - this.logger.warn( - `${failedDrivers.length} of ${this.drivers.size} driver(s) failed initial connect. Operations may recover via lazy reconnection or fail at query time.`, - { failedDrivers } - ); - } - this.logger.info("ObjectQL engine initialization complete"); - } - async destroy() { - this.logger.info("Destroying ObjectQL engine", { driverCount: this.drivers.size }); - for (const [name, driver] of this.drivers.entries()) { - try { - await driver.disconnect(); - } catch (e) { - this.logger.error("Error disconnecting driver", e, { driverName: name }); - } - } - this.logger.info("ObjectQL engine destroyed"); - } - /** - * Post-process expand: resolve lookup/master_detail fields by batch-loading related records. - * - * This is a driver-agnostic implementation that uses secondary queries ($in batches) - * to load related records, then injects them into the result set. - * - * @param objectName - The source object name - * @param records - The records returned by the driver - * @param expand - The expand map from QueryAST (field name → nested QueryAST) - * @param depth - Current recursion depth (0-based) - * @returns Records with expanded lookup fields (IDs replaced by full objects) - */ - async expandRelatedRecords(objectName, records, expand2, depth = 0) { - if (!records || records.length === 0) return records; - if (depth >= _ObjectQL2.MAX_EXPAND_DEPTH) return records; - const objectSchema = SchemaRegistry.getObject(objectName); - if (!objectSchema || !objectSchema.fields) return records; - for (const [fieldName, nestedAST] of Object.entries(expand2)) { - const fieldDef = objectSchema.fields[fieldName]; - if (!fieldDef || !fieldDef.reference) continue; - if (fieldDef.type !== "lookup" && fieldDef.type !== "master_detail") continue; - const referenceObject = fieldDef.reference; - const allIds = []; - for (const record2 of records) { - const val = record2[fieldName]; - if (val == null) continue; - if (Array.isArray(val)) { - allIds.push(...val.filter((id) => id != null)); - } else if (typeof val === "object") { - continue; - } else { - allIds.push(val); - } - } - const uniqueIds = [...new Set(allIds)]; - if (uniqueIds.length === 0) continue; - try { - const relatedQuery = { - object: referenceObject, - where: { id: { $in: uniqueIds } }, - ...nestedAST.fields ? { fields: nestedAST.fields } : {}, - ...nestedAST.orderBy ? { orderBy: nestedAST.orderBy } : {} - }; - const driver = this.getDriver(referenceObject); - const relatedRecords = await driver.find(referenceObject, relatedQuery) ?? []; - const recordMap = /* @__PURE__ */ new Map(); - for (const rec of relatedRecords) { - const id = rec.id; - if (id != null) recordMap.set(String(id), rec); - } - if (nestedAST.expand && Object.keys(nestedAST.expand).length > 0) { - const expandedRelated = await this.expandRelatedRecords( - referenceObject, - relatedRecords, - nestedAST.expand, - depth + 1 - ); - recordMap.clear(); - for (const rec of expandedRelated) { - const id = rec.id; - if (id != null) recordMap.set(String(id), rec); - } - } - for (const record2 of records) { - const val = record2[fieldName]; - if (val == null) continue; - if (Array.isArray(val)) { - record2[fieldName] = val.map((id) => recordMap.get(String(id)) ?? id); - } else if (typeof val !== "object") { - record2[fieldName] = recordMap.get(String(val)) ?? val; - } - } - } catch (e) { - this.logger.warn("Failed to expand relationship field; retaining foreign key IDs", { - object: objectName, - field: fieldName, - reference: referenceObject, - error: e.message - }); - } - } - return records; - } - // ============================================ - // Data Access Methods (IDataEngine Interface) - // ============================================ - async find(object2, query) { - object2 = this.resolveObjectName(object2); - this.logger.debug("Find operation starting", { object: object2, query }); - const driver = this.getDriver(object2); - const ast = { object: object2, ...query }; - delete ast.context; - if (ast.top != null && ast.limit == null) { - ast.limit = ast.top; - } - delete ast.top; - const opCtx = { - object: object2, - operation: "find", - ast, - options: query, - context: query?.context - }; - await this.executeWithMiddleware(opCtx, async () => { - const hookContext = { - object: object2, - event: "beforeFind", - input: { ast: opCtx.ast, options: opCtx.options }, - session: this.buildSession(opCtx.context), - transaction: opCtx.context?.transaction, - ql: this - }; - await this.triggerHooks("beforeFind", hookContext); - try { - let result = await driver.find(object2, hookContext.input.ast, hookContext.input.options); - if (ast.expand && Object.keys(ast.expand).length > 0 && Array.isArray(result)) { - result = await this.expandRelatedRecords(object2, result, ast.expand, 0); - } - hookContext.event = "afterFind"; - hookContext.result = result; - await this.triggerHooks("afterFind", hookContext); - return hookContext.result; - } catch (e) { - this.logger.error("Find operation failed", e, { object: object2 }); - throw e; - } - }); - return opCtx.result; - } - async findOne(objectName, query) { - objectName = this.resolveObjectName(objectName); - this.logger.debug("FindOne operation", { objectName }); - const driver = this.getDriver(objectName); - const ast = { object: objectName, ...query, limit: 1 }; - delete ast.context; - delete ast.top; - const opCtx = { - object: objectName, - operation: "findOne", - ast, - options: query, - context: query?.context - }; - await this.executeWithMiddleware(opCtx, async () => { - let result = await driver.findOne(objectName, opCtx.ast); - if (ast.expand && Object.keys(ast.expand).length > 0 && result != null) { - const expanded = await this.expandRelatedRecords(objectName, [result], ast.expand, 0); - result = expanded[0]; - } - return result; - }); - return opCtx.result; - } - async insert(object2, data, options) { - object2 = this.resolveObjectName(object2); - this.logger.debug("Insert operation starting", { object: object2, isBatch: Array.isArray(data) }); - const driver = this.getDriver(object2); - const opCtx = { - object: object2, - operation: "insert", - data, - options, - context: options?.context - }; - await this.executeWithMiddleware(opCtx, async () => { - const hookContext = { - object: object2, - event: "beforeInsert", - input: { data: opCtx.data, options: opCtx.options }, - session: this.buildSession(opCtx.context), - transaction: opCtx.context?.transaction, - ql: this - }; - await this.triggerHooks("beforeInsert", hookContext); - try { - let result; - if (Array.isArray(hookContext.input.data)) { - if (driver.bulkCreate) { - result = await driver.bulkCreate(object2, hookContext.input.data, hookContext.input.options); - } else { - result = await Promise.all(hookContext.input.data.map((item) => driver.create(object2, item, hookContext.input.options))); - } - } else { - result = await driver.create(object2, hookContext.input.data, hookContext.input.options); - } - hookContext.event = "afterInsert"; - hookContext.result = result; - await this.triggerHooks("afterInsert", hookContext); - if (this.realtimeService) { - try { - if (Array.isArray(result)) { - for (const record2 of result) { - const event = { - type: "data.record.created", - object: object2, - payload: { - recordId: record2.id, - after: record2 - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }; - await this.realtimeService.publish(event); - } - this.logger.debug(`Published ${result.length} data.record.created events`, { object: object2 }); - } else { - const event = { - type: "data.record.created", - object: object2, - payload: { - recordId: result.id, - after: result - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }; - await this.realtimeService.publish(event); - this.logger.debug("Published data.record.created event", { object: object2, recordId: result.id }); - } - } catch (error49) { - this.logger.warn("Failed to publish data event", { object: object2, error: error49 }); - } - } - return hookContext.result; - } catch (e) { - this.logger.error("Insert operation failed", e, { object: object2 }); - throw e; - } - }); - return opCtx.result; - } - async update(object2, data, options) { - object2 = this.resolveObjectName(object2); - this.logger.debug("Update operation starting", { object: object2 }); - const driver = this.getDriver(object2); - let id = data.id; - if (!id && options?.where && typeof options.where === "object" && "id" in options.where) { - id = options.where.id; - } - const opCtx = { - object: object2, - operation: "update", - data, - options, - context: options?.context - }; - await this.executeWithMiddleware(opCtx, async () => { - const hookContext = { - object: object2, - event: "beforeUpdate", - input: { id, data: opCtx.data, options: opCtx.options }, - session: this.buildSession(opCtx.context), - transaction: opCtx.context?.transaction, - ql: this - }; - await this.triggerHooks("beforeUpdate", hookContext); - try { - let result; - if (hookContext.input.id) { - result = await driver.update(object2, hookContext.input.id, hookContext.input.data, hookContext.input.options); - } else if (options?.multi && driver.updateMany) { - const ast = { object: object2, where: options.where }; - result = await driver.updateMany(object2, ast, hookContext.input.data, hookContext.input.options); - } else { - throw new Error("Update requires an ID or options.multi=true"); - } - hookContext.event = "afterUpdate"; - hookContext.result = result; - await this.triggerHooks("afterUpdate", hookContext); - if (this.realtimeService) { - try { - const resultId = typeof result === "object" && result && "id" in result ? result.id : void 0; - const recordId = String(hookContext.input.id || resultId || ""); - const event = { - type: "data.record.updated", - object: object2, - payload: { - recordId, - changes: hookContext.input.data, - after: result - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }; - await this.realtimeService.publish(event); - this.logger.debug("Published data.record.updated event", { object: object2, recordId }); - } catch (error49) { - this.logger.warn("Failed to publish data event", { object: object2, error: error49 }); - } - } - return hookContext.result; - } catch (e) { - this.logger.error("Update operation failed", e, { object: object2 }); - throw e; - } - }); - return opCtx.result; - } - async delete(object2, options) { - object2 = this.resolveObjectName(object2); - this.logger.debug("Delete operation starting", { object: object2 }); - const driver = this.getDriver(object2); - let id = void 0; - if (options?.where && typeof options.where === "object" && "id" in options.where) { - id = options.where.id; - } - const opCtx = { - object: object2, - operation: "delete", - options, - context: options?.context - }; - await this.executeWithMiddleware(opCtx, async () => { - const hookContext = { - object: object2, - event: "beforeDelete", - input: { id, options: opCtx.options }, - session: this.buildSession(opCtx.context), - transaction: opCtx.context?.transaction, - ql: this - }; - await this.triggerHooks("beforeDelete", hookContext); - try { - let result; - if (hookContext.input.id) { - result = await driver.delete(object2, hookContext.input.id, hookContext.input.options); - } else if (options?.multi && driver.deleteMany) { - const ast = { object: object2, where: options.where }; - result = await driver.deleteMany(object2, ast, hookContext.input.options); - } else { - throw new Error("Delete requires an ID or options.multi=true"); - } - hookContext.event = "afterDelete"; - hookContext.result = result; - await this.triggerHooks("afterDelete", hookContext); - if (this.realtimeService) { - try { - const resultId = typeof result === "object" && result && "id" in result ? result.id : void 0; - const recordId = String(hookContext.input.id || resultId || ""); - const event = { - type: "data.record.deleted", - object: object2, - payload: { - recordId - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }; - await this.realtimeService.publish(event); - this.logger.debug("Published data.record.deleted event", { object: object2, recordId }); - } catch (error49) { - this.logger.warn("Failed to publish data event", { object: object2, error: error49 }); - } - } - return hookContext.result; - } catch (e) { - this.logger.error("Delete operation failed", e, { object: object2 }); - throw e; - } - }); - return opCtx.result; - } - async count(object2, query) { - object2 = this.resolveObjectName(object2); - const driver = this.getDriver(object2); - const opCtx = { - object: object2, - operation: "count", - options: query, - context: query?.context - }; - await this.executeWithMiddleware(opCtx, async () => { - if (driver.count) { - const ast = { object: object2, where: query?.where }; - return driver.count(object2, ast); - } - const res = await this.find(object2, { where: query?.where, fields: ["id"] }); - return res.length; - }); - return opCtx.result; - } - async aggregate(object2, query) { - object2 = this.resolveObjectName(object2); - const driver = this.getDriver(object2); - this.logger.debug(`Aggregate on ${object2} using ${driver.name}`, query); - const opCtx = { - object: object2, - operation: "aggregate", - options: query, - context: query?.context - }; - await this.executeWithMiddleware(opCtx, async () => { - const ast = { - object: object2, - where: query.where, - groupBy: query.groupBy, - aggregations: query.aggregations - }; - return driver.find(object2, ast); - }); - return opCtx.result; - } - async execute(command, options) { - if (options?.object) { - const driver = this.getDriver(options.object); - if (driver.execute) { - return driver.execute(command, void 0, options); - } - } - throw new Error("Execute requires options.object to select driver"); - } - // ============================================ - // Compatibility / Convenience API - // ============================================ - // These methods provide a higher-level API matching the @objectql/core - // ObjectQL interface, enabling painless migration from the legacy layer. - /** - * Register a single object definition. - * - * Proxies to SchemaRegistry.registerObject() with sensible defaults. - * Fields without a `name` property are auto-assigned from their key. - */ - registerObject(schema3, packageId = "__runtime__", namespace) { - if (schema3.fields) { - for (const [key, field] of Object.entries(schema3.fields)) { - if (field && typeof field === "object" && !("name" in field)) { - field.name = key; - } - } - } - return SchemaRegistry.registerObject(schema3, packageId, namespace); - } - /** - * Unregister a single object by name. - */ - unregisterObject(name, packageId) { - if (packageId) { - SchemaRegistry.unregisterObjectsByPackage(packageId); - } else { - SchemaRegistry.unregisterItem("object", name); - } - } - /** - * Get an object definition by name. - * Alias for getSchema() — matches @objectql/core API. - */ - getObject(name) { - return this.getSchema(name); - } - /** - * Get all registered object configs as a name→config map. - * Matches @objectql/core getConfigs() API. - */ - getConfigs() { - const result = {}; - const objects = SchemaRegistry.getAllObjects(); - for (const obj of objects) { - if (obj.name) { - result[obj.name] = obj; - } - } - return result; - } - /** - * Get a registered driver by datasource name. - * - * Unlike the private getDriver() (which resolves by object name), - * this method directly looks up a driver by its registered name. - */ - getDriverByName(name) { - return this.drivers.get(name); - } - /** - * Get the driver responsible for the given object. - * - * Resolves datasource binding from the object's schema definition, - * falling back to the default driver. This is a public version of - * the internal getDriver() used by CRUD operations. - * - * @param objectName - FQN or short name of the registered object. - * @returns The resolved DriverInterface, or undefined if no driver is available. - */ - getDriverForObject(objectName) { - try { - return this.getDriver(objectName); - } catch { - return void 0; - } - } - /** - * Get a registered driver by datasource name. - * Alias matching @objectql/core datasource() API. - * - * @throws Error if the datasource is not found - */ - datasource(name) { - const driver = this.drivers.get(name); - if (!driver) { - throw new Error(`[ObjectQL] Datasource '${name}' not found`); - } - return driver; - } - /** - * Register a hook handler. - * Convenience alias for registerHook() matching @objectql/core on() API. - * - * Usage: - * ql.on('beforeInsert', 'user', async (ctx) => { ... }); - */ - on(event, objectName, handler, packageId) { - this.registerHook(event, handler, { object: objectName, packageId }); - } - /** - * Remove all hooks, actions, and objects contributed by a package. - */ - removePackage(packageId) { - for (const [key, handlers] of this.hooks.entries()) { - const filtered = handlers.filter((h) => h.packageId !== packageId); - if (filtered.length !== handlers.length) { - this.hooks.set(key, filtered); - } - } - this.removeActionsByPackage(packageId); - SchemaRegistry.unregisterObjectsByPackage(packageId, true); - } - /** - * Gracefully shut down the engine, disconnecting all drivers. - * Alias for destroy() — matches @objectql/core close() API. - */ - async close() { - return this.destroy(); - } - /** - * Create a scoped execution context bound to this engine. - * - * Usage: - * const ctx = engine.createContext({ userId: '...', tenantId: '...' }); - * const users = ctx.object('user'); - * await users.find({ filter: { status: 'active' } }); - */ - createContext(ctx) { - return new ScopedContext( - ExecutionContextSchema2.parse(ctx), - this - ); - } - /** - * Static factory: create a fully configured ObjectQL instance. - * - * Matches @objectql/core's `new ObjectQL(config)` pattern but also - * registers drivers and objects, then calls init(). - * - * Usage: - * const ql = await ObjectQL.create({ - * datasources: { default: myDriver }, - * objects: { user: { name: 'user', fields: { ... } } } - * }); - */ - static async create(config4) { - const ql = new _ObjectQL2(); - if (config4.datasources) { - for (const [name, driver] of Object.entries(config4.datasources)) { - if (!driver.name) { - driver.name = name; - } - ql.registerDriver(driver, name === "default"); - } - } - if (config4.objects) { - for (const [_key, schema3] of Object.entries(config4.objects)) { - ql.registerObject(schema3); - } - } - if (config4.hooks) { - for (const hook of config4.hooks) { - ql.on(hook.event, hook.object, hook.handler); - } - } - await ql.init(); - return ql; - } -}; -_ObjectQL.MAX_EXPAND_DEPTH = 3; -var ObjectQL = _ObjectQL; -var ObjectRepository = class { - constructor(objectName, context, engine) { - this.objectName = objectName; - this.context = context; - this.engine = engine; - } - async find(query = {}) { - return this.engine.find(this.objectName, { - ...query, - context: this.context - }); - } - async findOne(query = {}) { - return this.engine.findOne(this.objectName, { - ...query, - context: this.context - }); - } - async insert(data) { - return this.engine.insert(this.objectName, data, { - context: this.context - }); - } - /** Alias for insert() — matches @objectql/core convention */ - async create(data) { - return this.insert(data); - } - async update(data, options = {}) { - return this.engine.update(this.objectName, data, { - ...options, - context: this.context - }); - } - /** Update a single record by ID */ - async updateById(id, data) { - return this.engine.update(this.objectName, { ...data, id }, { - where: { id }, - context: this.context - }); - } - async delete(options = {}) { - return this.engine.delete(this.objectName, { - ...options, - context: this.context - }); - } - /** Delete a single record by ID */ - async deleteById(id) { - return this.engine.delete(this.objectName, { - where: { id }, - context: this.context - }); - } - async count(query = {}) { - return this.engine.count(this.objectName, { - ...query, - context: this.context - }); - } - /** Aggregate query */ - async aggregate(query = {}) { - return this.engine.aggregate(this.objectName, { - ...query, - context: this.context - }); - } - /** Execute a named action registered on this object */ - async execute(actionName, params) { - if (this.engine.executeAction) { - return this.engine.executeAction(this.objectName, actionName, { - ...params, - userId: this.context.userId, - tenantId: this.context.tenantId, - roles: this.context.roles - }); - } - throw new Error(`Actions not supported by engine`); - } -}; -var ScopedContext = class _ScopedContext { - constructor(executionContext, engine) { - this.executionContext = executionContext; - this.engine = engine; - } - /** Get a repository scoped to this context */ - object(name) { - return new ObjectRepository(name, this.executionContext, this.engine); - } - /** Create an elevated (system) context */ - sudo() { - return new _ScopedContext( - { ...this.executionContext, isSystem: true }, - this.engine - ); - } - /** - * Execute a callback within a database transaction. - * - * The callback receives a new ScopedContext whose operations - * share the same transaction handle. If the callback throws, - * the transaction is rolled back; otherwise it is committed. - * - * Falls back to non-transactional execution if the driver - * does not support transactions. - */ - async transaction(callback) { - const engine = this.engine; - const driver = engine.defaultDriver ? engine.drivers?.get(engine.defaultDriver) : void 0; - if (!driver?.beginTransaction) { - return callback(this); - } - const trx = await driver.beginTransaction(); - const trxCtx = new _ScopedContext( - { ...this.executionContext, transaction: trx }, - this.engine - ); - try { - const result = await callback(trxCtx); - if (driver.commit) await driver.commit(trx); - else if (driver.commitTransaction) await driver.commitTransaction(trx); - return result; - } catch (error49) { - if (driver.rollback) await driver.rollback(trx); - else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx); - throw error49; - } - } - get userId() { - return this.executionContext.userId; - } - get tenantId() { - return this.executionContext.tenantId; - } - /** Alias for tenantId — matches ObjectQLContext.spaceId convention */ - get spaceId() { - return this.executionContext.tenantId; - } - get roles() { - return this.executionContext.roles; - } - get isSystem() { - return this.executionContext.isSystem; - } - /** Internal: expose the transaction handle for driver-level access */ - get transactionHandle() { - return this.executionContext.transaction; - } -}; -function hasLoadMetaFromDb(service) { - return typeof service === "object" && service !== null && typeof service["loadMetaFromDb"] === "function"; -} -var ObjectQLPlugin = class { - constructor(ql, hostContext) { - this.name = "com.objectstack.engine.objectql"; - this.type = "objectql"; - this.version = "1.0.0"; - this.init = async (ctx) => { - if (!this.ql) { - const hostCtx = { ...this.hostContext, logger: ctx.logger }; - this.ql = new ObjectQL(hostCtx); - } - ctx.registerService("objectql", this.ql); - ctx.registerService("data", this.ql); - const ql2 = this.ql; - ctx.registerService("manifest", { - register: (manifest) => { - ql2.registerApp(manifest); - ctx.logger.debug("Manifest registered via manifest service", { - id: manifest.id || manifest.name - }); - } - }); - ctx.logger.info("ObjectQL engine registered", { - services: ["objectql", "data", "manifest"] - }); - const protocolShim = new ObjectStackProtocolImplementation( - this.ql, - () => ctx.getServices ? ctx.getServices() : /* @__PURE__ */ new Map() - ); - ctx.registerService("protocol", protocolShim); - ctx.logger.info("Protocol service registered"); - }; - this.start = async (ctx) => { - ctx.logger.info("ObjectQL engine starting..."); - try { - const metadataService = ctx.getService("metadata"); - if (metadataService && typeof metadataService.loadMany === "function" && this.ql) { - await this.loadMetadataFromService(metadataService, ctx); - } - } catch (e) { - ctx.logger.debug("No external metadata service to sync from"); - } - if (ctx.getServices && this.ql) { - const services = ctx.getServices(); - for (const [name, service] of services.entries()) { - if (name.startsWith("driver.")) { - this.ql.registerDriver(service); - ctx.logger.debug("Discovered and registered driver service", { serviceName: name }); - } - if (name.startsWith("app.")) { - ctx.logger.warn( - `[DEPRECATED] Service "${name}" uses legacy app.* convention. Migrate to ctx.getService('manifest').register(data).` - ); - this.ql.registerApp(service); - ctx.logger.debug("Discovered and registered app service (legacy)", { serviceName: name }); - } - } - try { - const realtimeService = ctx.getService("realtime"); - if (realtimeService && typeof realtimeService === "object" && "publish" in realtimeService) { - ctx.logger.info("[ObjectQLPlugin] Bridging realtime service to ObjectQL for event publishing"); - this.ql.setRealtimeService(realtimeService); - } - } catch (e) { - ctx.logger.debug("[ObjectQLPlugin] No realtime service found \u2014 data events will not be published", { - error: e.message - }); - } - } - await this.ql?.init(); - await this.restoreMetadataFromDb(ctx); - await this.syncRegisteredSchemas(ctx); - await this.bridgeObjectsToMetadataService(ctx); - this.registerAuditHooks(ctx); - this.registerTenantMiddleware(ctx); - ctx.logger.info("ObjectQL engine started", { - driversRegistered: this.ql?.["drivers"]?.size || 0, - objectsRegistered: this.ql?.registry?.getAllObjects?.()?.length || 0 - }); - }; - if (ql) { - this.ql = ql; - } else { - this.hostContext = hostContext; - } - } - /** - * Register built-in audit hooks for auto-stamping created_by/updated_by - * and fetching previousData for update/delete operations. - */ - registerAuditHooks(ctx) { - if (!this.ql) return; - this.ql.registerHook("beforeInsert", async (hookCtx) => { - if (hookCtx.session?.userId && hookCtx.input?.data) { - const data = hookCtx.input.data; - if (typeof data === "object" && data !== null) { - data.created_by = data.created_by ?? hookCtx.session.userId; - data.updated_by = hookCtx.session.userId; - data.created_at = data.created_at ?? (/* @__PURE__ */ new Date()).toISOString(); - data.updated_at = (/* @__PURE__ */ new Date()).toISOString(); - if (hookCtx.session.tenantId) { - data.tenant_id = data.tenant_id ?? hookCtx.session.tenantId; - } - } - } - }, { object: "*", priority: 10 }); - this.ql.registerHook("beforeUpdate", async (hookCtx) => { - if (hookCtx.session?.userId && hookCtx.input?.data) { - const data = hookCtx.input.data; - if (typeof data === "object" && data !== null) { - data.updated_by = hookCtx.session.userId; - data.updated_at = (/* @__PURE__ */ new Date()).toISOString(); - } - } - }, { object: "*", priority: 10 }); - this.ql.registerHook("beforeUpdate", async (hookCtx) => { - if (hookCtx.input?.id && !hookCtx.previous) { - try { - const existing = await this.ql.findOne(hookCtx.object, { - where: { id: hookCtx.input.id } - }); - if (existing) { - hookCtx.previous = existing; - } - } catch (_e) { - } - } - }, { object: "*", priority: 5 }); - this.ql.registerHook("beforeDelete", async (hookCtx) => { - if (hookCtx.input?.id && !hookCtx.previous) { - try { - const existing = await this.ql.findOne(hookCtx.object, { - where: { id: hookCtx.input.id } - }); - if (existing) { - hookCtx.previous = existing; - } - } catch (_e) { - } - } - }, { object: "*", priority: 5 }); - ctx.logger.debug("Audit hooks registered (created_by/updated_by, previousData)"); - } - /** - * Register tenant isolation middleware that auto-injects tenant_id filter - * for multi-tenant operations. - */ - registerTenantMiddleware(ctx) { - if (!this.ql) return; - this.ql.registerMiddleware(async (opCtx, next) => { - if (!opCtx.context?.tenantId || opCtx.context?.isSystem) { - return next(); - } - if (["find", "findOne", "count", "aggregate"].includes(opCtx.operation)) { - if (opCtx.ast) { - const tenantFilter = { tenant_id: opCtx.context.tenantId }; - if (opCtx.ast.where) { - opCtx.ast.where = { $and: [opCtx.ast.where, tenantFilter] }; - } else { - opCtx.ast.where = tenantFilter; - } - } - } - await next(); - }); - ctx.logger.debug("Tenant isolation middleware registered"); - } - /** - * Synchronize all registered object schemas to the database. - * - * Groups objects by their responsible driver, then: - * - If the driver advertises `supports.batchSchemaSync` and implements - * `syncSchemasBatch()`, submits all schemas in a single call (reducing - * network round-trips for remote drivers like Turso). - * - Otherwise falls back to sequential `syncSchema()` per object. - * - * This is idempotent — drivers must tolerate repeated calls without - * duplicating tables or erroring out. - * - * Drivers that do not implement `syncSchema` are silently skipped. - */ - async syncRegisteredSchemas(ctx) { - if (!this.ql) return; - const allObjects = this.ql.registry?.getAllObjects?.() ?? []; - if (allObjects.length === 0) return; - let synced = 0; - let skipped = 0; - const driverGroups = /* @__PURE__ */ new Map(); - for (const obj of allObjects) { - const driver = this.ql.getDriverForObject(obj.name); - if (!driver) { - ctx.logger.debug("No driver available for object, skipping schema sync", { - object: obj.name - }); - skipped++; - continue; - } - if (typeof driver.syncSchema !== "function") { - ctx.logger.debug("Driver does not support syncSchema, skipping", { - object: obj.name, - driver: driver.name - }); - skipped++; - continue; - } - const tableName = obj.tableName || obj.name; - let group = driverGroups.get(driver); - if (!group) { - group = []; - driverGroups.set(driver, group); - } - group.push({ obj, tableName }); - } - for (const [driver, entries] of driverGroups) { - if (driver.supports?.batchSchemaSync && typeof driver.syncSchemasBatch === "function") { - const batchPayload = entries.map((e) => ({ - object: e.tableName, - schema: e.obj - })); - try { - await driver.syncSchemasBatch(batchPayload); - synced += entries.length; - ctx.logger.debug("Batch schema sync succeeded", { - driver: driver.name, - count: entries.length - }); - } catch (e) { - ctx.logger.warn("Batch schema sync failed, falling back to sequential", { - driver: driver.name, - error: e instanceof Error ? e.message : String(e) - }); - for (const { obj, tableName } of entries) { - try { - await driver.syncSchema(tableName, obj); - synced++; - } catch (seqErr) { - ctx.logger.warn("Failed to sync schema for object", { - object: obj.name, - tableName, - driver: driver.name, - error: seqErr instanceof Error ? seqErr.message : String(seqErr) - }); - } - } - } - } else { - for (const { obj, tableName } of entries) { - try { - await driver.syncSchema(tableName, obj); - synced++; - } catch (e) { - ctx.logger.warn("Failed to sync schema for object", { - object: obj.name, - tableName, - driver: driver.name, - error: e instanceof Error ? e.message : String(e) - }); - } - } - } - } - if (synced > 0 || skipped > 0) { - ctx.logger.info("Schema sync complete", { synced, skipped, total: allObjects.length }); - } - } - /** - * Restore persisted metadata from the database (sys_metadata) on startup. - * - * Calls `protocol.loadMetaFromDb()` to bulk-load all active metadata - * records (objects, views, apps, etc.) into the in-memory SchemaRegistry. - * This closes the persistence loop so that user-created schemas survive - * kernel cold starts and redeployments. - * - * Gracefully degrades when: - * - The protocol service is unavailable (e.g., in-memory-only mode). - * - `loadMetaFromDb` is not implemented by the protocol shim. - * - The underlying driver/table does not exist yet (first-run scenario). - */ - async restoreMetadataFromDb(ctx) { - let protocol; - try { - const service = ctx.getService("protocol"); - if (!service || !hasLoadMetaFromDb(service)) { - ctx.logger.debug("Protocol service does not support loadMetaFromDb, skipping DB restore"); - return; - } - protocol = service; - } catch (e) { - ctx.logger.debug("Protocol service unavailable, skipping DB restore", { - error: e instanceof Error ? e.message : String(e) - }); - return; - } - try { - const { loaded, errors } = await protocol.loadMetaFromDb(); - if (loaded > 0 || errors > 0) { - ctx.logger.info("Metadata restored from database to SchemaRegistry", { loaded, errors }); - } else { - ctx.logger.debug("No persisted metadata found in database"); - } - } catch (e) { - ctx.logger.debug("DB metadata restore failed (non-fatal)", { - error: e instanceof Error ? e.message : String(e) - }); - } - } - /** - * Bridge all SchemaRegistry objects to the metadata service. - * - * This ensures objects registered by plugins and loaded from sys_metadata - * are visible to AI tools and other consumers that query IMetadataService. - * - * Runs after both restoreMetadataFromDb() and syncRegisteredSchemas() to - * catch all objects in the SchemaRegistry regardless of their source. - */ - async bridgeObjectsToMetadataService(ctx) { - try { - const metadataService = ctx.getService("metadata"); - if (!metadataService || typeof metadataService.register !== "function") { - ctx.logger.debug("Metadata service unavailable for bridging, skipping"); - return; - } - if (!this.ql?.registry) { - ctx.logger.debug("SchemaRegistry unavailable for bridging, skipping"); - return; - } - const objects = this.ql.registry.getAllObjects(); - let bridged = 0; - for (const obj of objects) { - try { - const existing = await metadataService.getObject(obj.name); - if (!existing) { - await metadataService.register("object", obj.name, obj); - bridged++; - } - } catch (e) { - ctx.logger.debug("Failed to bridge object to metadata service", { - object: obj.name, - error: e instanceof Error ? e.message : String(e) - }); - } - } - if (bridged > 0) { - ctx.logger.info("Bridged objects from SchemaRegistry to metadata service", { - count: bridged, - total: objects.length - }); - } else { - ctx.logger.debug("No objects needed bridging (all already in metadata service)"); - } - } catch (e) { - ctx.logger.debug("Failed to bridge objects to metadata service", { - error: e instanceof Error ? e.message : String(e) - }); - } - } - /** - * Load metadata from external metadata service into ObjectQL registry - * This enables ObjectQL to use file-based or remote metadata - */ - async loadMetadataFromService(metadataService, ctx) { - ctx.logger.info("Syncing metadata from external service into ObjectQL registry..."); - const metadataTypes = ["object", "view", "app", "flow", "workflow", "function"]; - let totalLoaded = 0; - for (const type of metadataTypes) { - try { - if (typeof metadataService.loadMany === "function") { - const items = await metadataService.loadMany(type); - if (items && items.length > 0) { - items.forEach((item) => { - const keyField = item.id ? "id" : "name"; - if (type === "object" && this.ql) { - return; - } - if (this.ql?.registry?.registerItem) { - this.ql.registry.registerItem(type, item, keyField); - } - }); - totalLoaded += items.length; - ctx.logger.info(`Synced ${items.length} ${type}(s) from metadata service`); - } - } - } catch (e) { - ctx.logger.debug(`No ${type} metadata found or error loading`, { - error: e.message - }); - } - } - if (totalLoaded > 0) { - ctx.logger.info(`Metadata sync complete: ${totalLoaded} items loaded into ObjectQL registry`); - } - } -}; - -// ../../packages/plugins/driver-memory/dist/index.mjs -import * as fs from "fs"; -import * as path from "path"; -var import_mingo = __toESM(require_cjs(), 1); -var __defProp3 = Object.defineProperty; -var __getOwnPropNames2 = Object.getOwnPropertyNames; -var __esm2 = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res; -}; -var __export3 = (target, all) => { - for (var name in all) - __defProp3(target, name, { get: all[name], enumerable: true }); -}; -var local_storage_adapter_exports = {}; -__export3(local_storage_adapter_exports, { - LocalStoragePersistenceAdapter: () => LocalStoragePersistenceAdapter -}); -var _LocalStoragePersistenceAdapter; -var LocalStoragePersistenceAdapter; -var init_local_storage_adapter = __esm2({ - "src/persistence/local-storage-adapter.ts"() { - "use strict"; - _LocalStoragePersistenceAdapter = class _LocalStoragePersistenceAdapter2 { - // 4.5MB warning threshold - constructor(options) { - this.storageKey = options?.key || "objectstack:memory-db"; - } - /** - * Load persisted data from localStorage. - * Returns null if no data exists. - */ - async load() { - try { - const raw2 = localStorage.getItem(this.storageKey); - if (!raw2) return null; - return JSON.parse(raw2); - } catch { - return null; - } - } - /** - * Save data to localStorage. - * Warns if data size approaches the ~5MB localStorage limit. - */ - async save(db) { - const json2 = JSON.stringify(db); - if (json2.length > _LocalStoragePersistenceAdapter2.SIZE_WARNING_BYTES) { - console.warn( - `[ObjectStack] localStorage persistence data size (${(json2.length / 1024 / 1024).toFixed(2)}MB) is approaching the ~5MB limit. Consider using a different persistence strategy.` - ); - } - try { - localStorage.setItem(this.storageKey, json2); - } catch (e) { - console.error("[ObjectStack] Failed to persist data to localStorage:", e?.message || e); - } - } - /** - * Flush is a no-op for localStorage (writes are synchronous). - */ - async flush() { - } - }; - _LocalStoragePersistenceAdapter.SIZE_WARNING_BYTES = 4.5 * 1024 * 1024; - LocalStoragePersistenceAdapter = _LocalStoragePersistenceAdapter; - } -}); -var file_adapter_exports = {}; -__export3(file_adapter_exports, { - FileSystemPersistenceAdapter: () => FileSystemPersistenceAdapter -}); -var FileSystemPersistenceAdapter; -var init_file_adapter = __esm2({ - "src/persistence/file-adapter.ts"() { - "use strict"; - FileSystemPersistenceAdapter = class { - constructor(options) { - this.dirty = false; - this.timer = null; - this.currentDb = null; - this.filePath = options?.path || path.join(".objectstack", "data", "memory-driver.json"); - this.autoSaveInterval = options?.autoSaveInterval ?? 2e3; - } - /** - * Load persisted data from disk. - * Returns null if no file exists. - */ - async load() { - try { - if (!fs.existsSync(this.filePath)) { - return null; - } - const raw2 = fs.readFileSync(this.filePath, "utf-8"); - const data = JSON.parse(raw2); - return data; - } catch { - return null; - } - } - /** - * Save data to disk using atomic write (temp file + rename). - */ - async save(db) { - this.currentDb = db; - this.dirty = true; - } - /** - * Flush pending writes to disk immediately. - */ - async flush() { - if (!this.dirty || !this.currentDb) return; - await this.writeToDisk(this.currentDb); - this.dirty = false; - } - /** - * Start the auto-save timer. - */ - startAutoSave() { - if (this.timer) return; - this.timer = setInterval(async () => { - if (this.dirty && this.currentDb) { - await this.writeToDisk(this.currentDb); - this.dirty = false; - } - }, this.autoSaveInterval); - if (this.timer) { - this.timer.unref(); - } - } - /** - * Stop the auto-save timer and flush pending writes. - */ - async stopAutoSave() { - if (this.timer) { - clearInterval(this.timer); - this.timer = null; - } - await this.flush(); - } - /** - * Atomic write: write to temp file, then rename. - */ - async writeToDisk(db) { - const dir = path.dirname(this.filePath); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); - } - const tmpPath = this.filePath + ".tmp"; - const json2 = JSON.stringify(db, null, 2); - fs.writeFileSync(tmpPath, json2, "utf-8"); - fs.renameSync(tmpPath, this.filePath); - } - }; - } -}); -function getValueByPath(obj, path22) { - if (!path22.includes(".")) return obj[path22]; - return path22.split(".").reduce((o, i) => o ? o[i] : void 0, obj); -} -var _InMemoryDriver = class _InMemoryDriver2 { - constructor(config4) { - this.name = "com.objectstack.driver.memory"; - this.type = "driver"; - this.version = "1.0.0"; - this.idCounters = /* @__PURE__ */ new Map(); - this.transactions = /* @__PURE__ */ new Map(); - this.persistenceAdapter = null; - this.supports = { - // Basic CRUD Operations - create: true, - read: true, - update: true, - delete: true, - // Bulk Operations - bulkCreate: true, - bulkUpdate: true, - bulkDelete: true, - // Transaction & Connection Management - transactions: true, - // Snapshot-based transactions - savepoints: false, - // Query Operations - queryFilters: true, - // Implemented via memory-matcher - queryAggregations: true, - // Implemented - querySorting: true, - // Implemented via JS sort - queryPagination: true, - // Implemented - queryWindowFunctions: false, - // @planned: Window functions (ROW_NUMBER, RANK, etc.) - querySubqueries: false, - // @planned: Subquery execution - queryCTE: false, - joins: false, - // @planned: In-memory join operations - // Advanced Features - fullTextSearch: false, - // @planned: Text tokenization + matching - jsonQuery: false, - geospatialQuery: false, - streaming: true, - // Implemented via findStream() - jsonFields: true, - // Native JS object support - arrayFields: true, - // Native JS array support - vectorSearch: false, - // @planned: Cosine similarity search - // Schema Management - schemaSync: true, - // Implemented via syncSchema() - batchSchemaSync: false, - migrations: false, - indexes: false, - // Performance & Optimization - connectionPooling: false, - preparedStatements: false, - queryCache: false - }; - this.db = {}; - this.config = config4 || {}; - this.logger = config4?.logger || createLogger({ level: "info", format: "pretty" }); - this.logger.debug("InMemory driver instance created"); - } - // Duck-typed RuntimePlugin hook - install(ctx) { - this.logger.debug("Installing InMemory driver via plugin hook"); - if (ctx.engine && ctx.engine.ql && typeof ctx.engine.ql.registerDriver === "function") { - ctx.engine.ql.registerDriver(this); - this.logger.info("InMemory driver registered with ObjectQL engine"); - } else { - this.logger.warn("Could not register driver - ObjectQL engine not found in context"); - } - } - // =================================== - // Lifecycle - // =================================== - async connect() { - await this.initPersistence(); - if (this.persistenceAdapter) { - const persisted = await this.persistenceAdapter.load(); - if (persisted) { - for (const [objectName, records] of Object.entries(persisted)) { - this.db[objectName] = records; - for (const record2 of records) { - if (record2.id && typeof record2.id === "string") { - const parts = record2.id.split("-"); - const lastPart = parts[parts.length - 1]; - const counter = parseInt(lastPart, 10); - if (!isNaN(counter)) { - const current = this.idCounters.get(objectName) || 0; - if (counter > current) { - this.idCounters.set(objectName, counter); - } - } - } - } - } - this.logger.info("InMemory Database restored from persistence", { - tables: Object.keys(persisted).length - }); - } - } - if (this.config.initialData) { - for (const [objectName, records] of Object.entries(this.config.initialData)) { - const table = this.getTable(objectName); - for (const record2 of records) { - const id = record2.id || this.generateId(objectName); - table.push({ ...record2, id }); - } - } - this.logger.info("InMemory Database Connected with initial data", { - tables: Object.keys(this.config.initialData).length - }); - } else { - this.logger.info("InMemory Database Connected (Virtual)"); - } - if (this.persistenceAdapter?.startAutoSave) { - this.persistenceAdapter.startAutoSave(); - } - } - async disconnect() { - if (this.persistenceAdapter) { - if (this.persistenceAdapter.stopAutoSave) { - await this.persistenceAdapter.stopAutoSave(); - } - await this.persistenceAdapter.flush(); - } - const tableCount = Object.keys(this.db).length; - const recordCount = Object.values(this.db).reduce((sum, table) => sum + table.length, 0); - this.db = {}; - this.logger.info("InMemory Database Disconnected & Cleared", { - tableCount, - recordCount - }); - } - async checkHealth() { - this.logger.debug("Health check performed", { - tableCount: Object.keys(this.db).length, - status: "healthy" - }); - return true; - } - // =================================== - // Execution - // =================================== - async execute(command, params) { - this.logger.warn("Raw execution not supported in InMemory driver", { command }); - return null; - } - // =================================== - // CRUD - // =================================== - async find(object2, query, options) { - this.logger.debug("Find operation", { object: object2, query }); - const table = this.getTable(object2); - let results = [...table]; - if (query.where) { - const mongoQuery = this.convertToMongoQuery(query.where); - if (mongoQuery && Object.keys(mongoQuery).length > 0) { - const mingoQuery = new import_mingo.Query(mongoQuery); - results = mingoQuery.find(results).all(); - } - } - if (query.groupBy || query.aggregations && query.aggregations.length > 0) { - results = this.performAggregation(results, query); - } - if (query.orderBy) { - const sortFields = Array.isArray(query.orderBy) ? query.orderBy : [query.orderBy]; - results = this.applySort(results, sortFields); - } - if (query.offset) { - results = results.slice(query.offset); - } - if (query.limit) { - results = results.slice(0, query.limit); - } - if (query.fields && Array.isArray(query.fields) && query.fields.length > 0) { - results = results.map((record2) => this.projectFields(record2, query.fields)); - } - this.logger.debug("Find completed", { object: object2, resultCount: results.length }); - return results; - } - async *findStream(object2, query, options) { - this.logger.debug("FindStream operation", { object: object2 }); - const results = await this.find(object2, query, options); - for (const record2 of results) { - yield record2; - } - } - async findOne(object2, query, options) { - this.logger.debug("FindOne operation", { object: object2, query }); - const results = await this.find(object2, { ...query, limit: 1 }, options); - const result = results[0] || null; - this.logger.debug("FindOne completed", { object: object2, found: !!result }); - return result; - } - async create(object2, data, options) { - this.logger.debug("Create operation", { object: object2, hasData: !!data }); - const table = this.getTable(object2); - const newRecord = { - id: data.id || this.generateId(object2), - ...data, - created_at: data.created_at || (/* @__PURE__ */ new Date()).toISOString(), - updated_at: data.updated_at || (/* @__PURE__ */ new Date()).toISOString() - }; - table.push(newRecord); - this.markDirty(); - this.logger.debug("Record created", { object: object2, id: newRecord.id, tableSize: table.length }); - return { ...newRecord }; - } - async update(object2, id, data, options) { - this.logger.debug("Update operation", { object: object2, id }); - const table = this.getTable(object2); - const index = table.findIndex((r) => r.id == id); - if (index === -1) { - if (this.config.strictMode) { - this.logger.warn("Record not found for update", { object: object2, id }); - throw new Error(`Record with ID ${id} not found in ${object2}`); - } - return null; - } - const updatedRecord = { - ...table[index], - ...data, - id: table[index].id, - // Preserve original ID - created_at: table[index].created_at, - // Preserve created_at - updated_at: (/* @__PURE__ */ new Date()).toISOString() - }; - table[index] = updatedRecord; - this.markDirty(); - this.logger.debug("Record updated", { object: object2, id }); - return { ...updatedRecord }; - } - async upsert(object2, data, conflictKeys, options) { - this.logger.debug("Upsert operation", { object: object2, conflictKeys }); - const table = this.getTable(object2); - let existingRecord = null; - if (data.id) { - existingRecord = table.find((r) => r.id === data.id); - } else if (conflictKeys && conflictKeys.length > 0) { - existingRecord = table.find((r) => conflictKeys.every((key) => r[key] === data[key])); - } - if (existingRecord) { - this.logger.debug("Record exists, updating", { object: object2, id: existingRecord.id }); - return this.update(object2, existingRecord.id, data, options); - } else { - this.logger.debug("Record does not exist, creating", { object: object2 }); - return this.create(object2, data, options); - } - } - async delete(object2, id, options) { - this.logger.debug("Delete operation", { object: object2, id }); - const table = this.getTable(object2); - const index = table.findIndex((r) => r.id == id); - if (index === -1) { - if (this.config.strictMode) { - throw new Error(`Record with ID ${id} not found in ${object2}`); - } - this.logger.warn("Record not found for deletion", { object: object2, id }); - return false; - } - table.splice(index, 1); - this.markDirty(); - this.logger.debug("Record deleted", { object: object2, id, tableSize: table.length }); - return true; - } - async count(object2, query, options) { - let records = this.getTable(object2); - if (query?.where) { - const mongoQuery = this.convertToMongoQuery(query.where); - if (mongoQuery && Object.keys(mongoQuery).length > 0) { - const mingoQuery = new import_mingo.Query(mongoQuery); - records = mingoQuery.find(records).all(); - } - } - const count = records.length; - this.logger.debug("Count operation", { object: object2, count }); - return count; - } - // =================================== - // Bulk Operations - // =================================== - async bulkCreate(object2, dataArray, options) { - this.logger.debug("BulkCreate operation", { object: object2, count: dataArray.length }); - const results = await Promise.all(dataArray.map((data) => this.create(object2, data, options))); - this.logger.debug("BulkCreate completed", { object: object2, count: results.length }); - return results; - } - async updateMany(object2, query, data, options) { - this.logger.debug("UpdateMany operation", { object: object2, query }); - const table = this.getTable(object2); - let targetRecords = table; - if (query && query.where) { - const mongoQuery = this.convertToMongoQuery(query.where); - if (mongoQuery && Object.keys(mongoQuery).length > 0) { - const mingoQuery = new import_mingo.Query(mongoQuery); - targetRecords = mingoQuery.find(targetRecords).all(); - } - } - const count = targetRecords.length; - for (const record2 of targetRecords) { - const index = table.findIndex((r) => r.id === record2.id); - if (index !== -1) { - const updated = { - ...table[index], - ...data, - updated_at: (/* @__PURE__ */ new Date()).toISOString() - }; - table[index] = updated; - } - } - if (count > 0) this.markDirty(); - this.logger.debug("UpdateMany completed", { object: object2, count }); - return count; - } - async deleteMany(object2, query, options) { - this.logger.debug("DeleteMany operation", { object: object2, query }); - const table = this.getTable(object2); - const initialLength = table.length; - if (query && query.where) { - const mongoQuery = this.convertToMongoQuery(query.where); - if (mongoQuery && Object.keys(mongoQuery).length > 0) { - const mingoQuery = new import_mingo.Query(mongoQuery); - const matched = mingoQuery.find(table).all(); - const matchedIds = new Set(matched.map((r) => r.id)); - this.db[object2] = table.filter((r) => !matchedIds.has(r.id)); - } else { - this.db[object2] = []; - } - } else { - this.db[object2] = []; - } - const count = initialLength - this.db[object2].length; - if (count > 0) this.markDirty(); - this.logger.debug("DeleteMany completed", { object: object2, count }); - return count; - } - // Compatibility aliases - async bulkUpdate(object2, updates, options) { - this.logger.debug("BulkUpdate operation", { object: object2, count: updates.length }); - const results = await Promise.all(updates.map((u) => this.update(object2, u.id, u.data, options))); - this.logger.debug("BulkUpdate completed", { object: object2, count: results.length }); - return results; - } - async bulkDelete(object2, ids, options) { - this.logger.debug("BulkDelete operation", { object: object2, count: ids.length }); - await Promise.all(ids.map((id) => this.delete(object2, id, options))); - this.logger.debug("BulkDelete completed", { object: object2, count: ids.length }); - } - // =================================== - // Transaction Management - // =================================== - async beginTransaction() { - const txId = `tx_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`; - const snapshot = {}; - for (const [table, records] of Object.entries(this.db)) { - snapshot[table] = records.map((r) => ({ ...r })); - } - const transaction = { id: txId, snapshot }; - this.transactions.set(txId, transaction); - this.logger.debug("Transaction started", { txId }); - return { id: txId }; - } - async commit(txHandle) { - const txId = txHandle?.id; - if (!txId || !this.transactions.has(txId)) { - this.logger.warn("Commit called with unknown transaction"); - return; - } - this.transactions.delete(txId); - this.logger.debug("Transaction committed", { txId }); - } - async rollback(txHandle) { - const txId = txHandle?.id; - if (!txId || !this.transactions.has(txId)) { - this.logger.warn("Rollback called with unknown transaction"); - return; - } - const tx = this.transactions.get(txId); - this.db = tx.snapshot; - this.transactions.delete(txId); - this.markDirty(); - this.logger.debug("Transaction rolled back", { txId }); - } - // =================================== - // Utility Methods - // =================================== - /** - * Remove all data from the store. - */ - async clear() { - this.db = {}; - this.idCounters.clear(); - this.markDirty(); - this.logger.debug("All data cleared"); - } - /** - * Get total number of records across all tables. - */ - getSize() { - return Object.values(this.db).reduce((sum, table) => sum + table.length, 0); - } - /** - * Get distinct values for a field, optionally filtered. - */ - async distinct(object2, field, query) { - let records = this.getTable(object2); - if (query?.where) { - const mongoQuery = this.convertToMongoQuery(query.where); - if (mongoQuery && Object.keys(mongoQuery).length > 0) { - const mingoQuery = new import_mingo.Query(mongoQuery); - records = mingoQuery.find(records).all(); - } - } - const values = /* @__PURE__ */ new Set(); - for (const record2 of records) { - const value = getValueByPath(record2, field); - if (value !== void 0 && value !== null) { - values.add(value); - } - } - return Array.from(values); - } - /** - * Execute a MongoDB-style aggregation pipeline using Mingo. - * - * Supports all standard MongoDB pipeline stages: - * - $match, $group, $sort, $project, $unwind, $limit, $skip - * - $addFields, $replaceRoot, $lookup (limited), $count - * - Accumulator operators: $sum, $avg, $min, $max, $first, $last, $push, $addToSet - * - * @example - * // Group by status and count - * const results = await driver.aggregate('orders', [ - * { $match: { status: 'completed' } }, - * { $group: { _id: '$customer', totalAmount: { $sum: '$amount' } } } - * ]); - * - * @example - * // Calculate average with filter - * const results = await driver.aggregate('products', [ - * { $match: { category: 'electronics' } }, - * { $group: { _id: null, avgPrice: { $avg: '$price' } } } - * ]); - */ - async aggregate(object2, pipeline, options) { - this.logger.debug("Aggregate operation", { object: object2, stageCount: pipeline.length }); - const records = this.getTable(object2).map((r) => ({ ...r })); - const aggregator = new import_mingo.Aggregator(pipeline); - const results = aggregator.run(records); - this.logger.debug("Aggregate completed", { object: object2, resultCount: results.length }); - return results; - } - // =================================== - // Query Conversion (ObjectQL → MongoDB) - // =================================== - /** - * Convert ObjectQL filter format to MongoDB query format for Mingo. - * - * Supports: - * 1. AST Comparison Node: { type: 'comparison', field, operator, value } - * 2. AST Logical Node: { type: 'logical', operator: 'and'|'or', conditions: [...] } - * 3. Legacy Array Format: [['field', 'op', value], 'and', ['field2', 'op', value2]] - * 4. MongoDB Format: { field: value } or { field: { $eq: value } } (passthrough) - */ - convertToMongoQuery(filters) { - if (!filters) return {}; - if (!Array.isArray(filters) && typeof filters === "object") { - if (filters.type === "comparison") { - return this.convertConditionToMongo(filters.field, filters.operator, filters.value) || {}; - } - if (filters.type === "logical") { - const conditions = filters.conditions?.map((c) => this.convertToMongoQuery(c)) || []; - if (conditions.length === 0) return {}; - if (conditions.length === 1) return conditions[0]; - const op = filters.operator === "or" ? "$or" : "$and"; - return { [op]: conditions }; - } - return this.normalizeFilterCondition(filters); - } - if (!Array.isArray(filters) || filters.length === 0) return {}; - const logicGroups = [ - { logic: "and", conditions: [] } - ]; - let currentLogic = "and"; - for (const item of filters) { - if (typeof item === "string") { - const newLogic = item.toLowerCase(); - if (newLogic !== currentLogic) { - currentLogic = newLogic; - logicGroups.push({ logic: currentLogic, conditions: [] }); - } - } else if (Array.isArray(item)) { - const [field, operator, value] = item; - const cond = this.convertConditionToMongo(field, operator, value); - if (cond) logicGroups[logicGroups.length - 1].conditions.push(cond); - } - } - const allConditions = []; - for (const group of logicGroups) { - if (group.conditions.length === 0) continue; - if (group.conditions.length === 1) { - allConditions.push(group.conditions[0]); - } else { - const op = group.logic === "or" ? "$or" : "$and"; - allConditions.push({ [op]: group.conditions }); - } - } - if (allConditions.length === 0) return {}; - if (allConditions.length === 1) return allConditions[0]; - return { $and: allConditions }; - } - /** - * Convert a single ObjectQL condition to MongoDB operator format. - */ - convertConditionToMongo(field, operator, value) { - switch (operator) { - case "=": - case "==": - return { [field]: value }; - case "!=": - case "<>": - return { [field]: { $ne: value } }; - case ">": - return { [field]: { $gt: value } }; - case ">=": - return { [field]: { $gte: value } }; - case "<": - return { [field]: { $lt: value } }; - case "<=": - return { [field]: { $lte: value } }; - case "in": - return { [field]: { $in: value } }; - case "nin": - case "not in": - return { [field]: { $nin: value } }; - case "contains": - case "like": - return { [field]: { $regex: new RegExp(this.escapeRegex(value), "i") } }; - case "notcontains": - case "not_contains": - return { [field]: { $not: { $regex: new RegExp(this.escapeRegex(value), "i") } } }; - case "startswith": - case "starts_with": - return { [field]: { $regex: new RegExp(`^${this.escapeRegex(value)}`, "i") } }; - case "endswith": - case "ends_with": - return { [field]: { $regex: new RegExp(`${this.escapeRegex(value)}$`, "i") } }; - case "between": - if (Array.isArray(value) && value.length === 2) { - return { [field]: { $gte: value[0], $lte: value[1] } }; - } - return null; - default: - return null; - } - } - /** - * Normalize a FilterCondition object by converting non-standard $-prefixed - * operators ($contains, $notContains, $startsWith, $endsWith, $between, $null) - * to Mingo-compatible equivalents ($regex, $gte/$lte, null checks). - */ - normalizeFilterCondition(filter) { - const result = {}; - const extraAndConditions = []; - for (const key of Object.keys(filter)) { - const value = filter[key]; - if (key === "$and" || key === "$or") { - result[key] = Array.isArray(value) ? value.map((child) => this.normalizeFilterCondition(child)) : value; - continue; - } - if (key === "$not") { - result[key] = value && typeof value === "object" ? this.normalizeFilterCondition(value) : value; - continue; - } - if (key.startsWith("$")) { - result[key] = value; - continue; - } - if (value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp)) { - const normalized = this.normalizeFieldOperators(value); - if (normalized._multiRegex) { - const regexConditions = normalized._multiRegex; - delete normalized._multiRegex; - for (const rc of regexConditions) { - extraAndConditions.push({ [key]: { ...normalized, ...rc } }); - } - } else { - result[key] = normalized; - } - } else { - result[key] = value; - } - } - if (extraAndConditions.length > 0) { - const existing = result.$and; - const andArray = Array.isArray(existing) ? existing : []; - if (Object.keys(result).filter((k) => k !== "$and").length > 0) { - const rest = { ...result }; - delete rest.$and; - andArray.push(rest); - } - andArray.push(...extraAndConditions); - return { $and: andArray }; - } - return result; - } - /** - * Convert non-standard field operators to Mingo-compatible format. - * When multiple regex-producing operators appear on the same field - * (e.g. $startsWith + $endsWith), they are combined via $and. - */ - normalizeFieldOperators(ops) { - const result = {}; - const regexConditions = []; - for (const op of Object.keys(ops)) { - const val = ops[op]; - switch (op) { - case "$contains": - regexConditions.push({ $regex: new RegExp(this.escapeRegex(val), "i") }); - break; - case "$notContains": - result.$not = { $regex: new RegExp(this.escapeRegex(val), "i") }; - break; - case "$startsWith": - regexConditions.push({ $regex: new RegExp(`^${this.escapeRegex(val)}`, "i") }); - break; - case "$endsWith": - regexConditions.push({ $regex: new RegExp(`${this.escapeRegex(val)}$`, "i") }); - break; - case "$between": - if (Array.isArray(val) && val.length === 2) { - result.$gte = val[0]; - result.$lte = val[1]; - } - break; - case "$null": - if (val === true) { - result.$eq = null; - } else { - result.$ne = null; - } - break; - default: - result[op] = val; - break; - } - } - if (regexConditions.length === 1) { - Object.assign(result, regexConditions[0]); - } else if (regexConditions.length > 1) { - result._multiRegex = regexConditions; - } - return result; - } - /** - * Escape special regex characters for safe literal matching. - */ - escapeRegex(str) { - return String(str).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - } - // =================================== - // Aggregation Logic - // =================================== - performAggregation(records, query) { - const { groupBy: groupBy2, aggregations } = query; - const groups = /* @__PURE__ */ new Map(); - if (groupBy2 && groupBy2.length > 0) { - for (const record2 of records) { - const keyParts = groupBy2.map((field) => { - const val = getValueByPath(record2, field); - return val === void 0 || val === null ? "null" : String(val); - }); - const key = JSON.stringify(keyParts); - if (!groups.has(key)) { - groups.set(key, []); - } - groups.get(key).push(record2); - } - } else { - groups.set("all", records); - } - const resultRows = []; - for (const [_key, groupRecords] of groups.entries()) { - const row = {}; - if (groupBy2 && groupBy2.length > 0) { - if (groupRecords.length > 0) { - const firstRecord = groupRecords[0]; - for (const field of groupBy2) { - this.setValueByPath(row, field, getValueByPath(firstRecord, field)); - } - } - } - if (aggregations) { - for (const agg of aggregations) { - const value = this.computeAggregate(groupRecords, agg); - row[agg.alias] = value; - } - } - resultRows.push(row); - } - return resultRows; - } - computeAggregate(records, agg) { - const { function: func, field } = agg; - const values = field ? records.map((r) => getValueByPath(r, field)) : []; - switch (func) { - case "count": - if (!field || field === "*") return records.length; - return values.filter((v) => v !== null && v !== void 0).length; - case "sum": - case "avg": { - const nums = values.filter((v) => typeof v === "number"); - const sum = nums.reduce((a, b) => a + b, 0); - if (func === "sum") return sum; - return nums.length > 0 ? sum / nums.length : null; - } - case "min": { - const valid = values.filter((v) => v !== null && v !== void 0); - if (valid.length === 0) return null; - return valid.reduce((min, v) => v < min ? v : min, valid[0]); - } - case "max": { - const valid = values.filter((v) => v !== null && v !== void 0); - if (valid.length === 0) return null; - return valid.reduce((max, v) => v > max ? v : max, valid[0]); - } - default: - return null; - } - } - setValueByPath(obj, path22, value) { - const parts = path22.split("."); - let current = obj; - for (let i = 0; i < parts.length - 1; i++) { - const part = parts[i]; - if (!current[part]) current[part] = {}; - current = current[part]; - } - current[parts[parts.length - 1]] = value; - } - // =================================== - // Schema Management - // =================================== - async syncSchema(object2, schema3, options) { - if (!this.db[object2]) { - this.db[object2] = []; - this.logger.info("Created in-memory table", { object: object2 }); - } - } - async dropTable(object2, options) { - if (this.db[object2]) { - const recordCount = this.db[object2].length; - delete this.db[object2]; - this.logger.info("Dropped in-memory table", { object: object2, recordCount }); - } - } - // =================================== - // Helpers - // =================================== - /** - * Apply manual sorting (Mingo sort has CJS build issues). - */ - applySort(records, sortFields) { - const sorted = [...records]; - for (let i = sortFields.length - 1; i >= 0; i--) { - const sortItem = sortFields[i]; - let field; - let direction; - if (typeof sortItem === "object" && !Array.isArray(sortItem)) { - field = sortItem.field; - direction = sortItem.order || sortItem.direction || "asc"; - } else if (Array.isArray(sortItem)) { - [field, direction] = sortItem; - } else { - continue; - } - sorted.sort((a, b) => { - const aVal = getValueByPath(a, field); - const bVal = getValueByPath(b, field); - if (aVal == null && bVal == null) return 0; - if (aVal == null) return 1; - if (bVal == null) return -1; - if (aVal < bVal) return direction === "desc" ? 1 : -1; - if (aVal > bVal) return direction === "desc" ? -1 : 1; - return 0; - }); - } - return sorted; - } - /** - * Project specific fields from a record. - */ - projectFields(record2, fields) { - const result = {}; - for (const field of fields) { - const value = getValueByPath(record2, field); - if (value !== void 0) { - result[field] = value; - } - } - if (!fields.includes("id") && record2.id !== void 0) { - result.id = record2.id; - } - return result; - } - getTable(name) { - if (!this.db[name]) { - this.db[name] = []; - } - return this.db[name]; - } - generateId(objectName) { - const key = objectName || "_global"; - const counter = (this.idCounters.get(key) || 0) + 1; - this.idCounters.set(key, counter); - const timestamp = Date.now(); - return `${key}-${timestamp}-${counter}`; - } - // =================================== - // Persistence - // =================================== - /** - * Mark the database as dirty, triggering persistence save. - */ - markDirty() { - if (this.persistenceAdapter) { - this.persistenceAdapter.save(this.db); - } - } - /** - * Flush pending persistence writes to ensure data is safely stored. - */ - async flush() { - if (this.persistenceAdapter) { - await this.persistenceAdapter.flush(); - } - } - /** - * Detect whether the current runtime is a browser environment. - */ - isBrowserEnvironment() { - return typeof globalThis.localStorage !== "undefined"; - } - /** - * Detect whether the current runtime is a serverless/edge environment. - * - * Checks well-known environment variables set by serverless platforms: - * - `VERCEL` / `VERCEL_ENV` — Vercel Functions / Edge - * - `AWS_LAMBDA_FUNCTION_NAME` — AWS Lambda - * - `NETLIFY` — Netlify Functions - * - `FUNCTIONS_WORKER_RUNTIME` — Azure Functions - * - `K_SERVICE` — Google Cloud Run / Cloud Functions - * - `FUNCTION_TARGET` — Google Cloud Functions (Node.js) - * - `DENO_DEPLOYMENT_ID` — Deno Deploy - * - * Returns `false` when `process` or `process.env` is unavailable - * (e.g. browser or edge runtimes without a Node.js process object). - */ - isServerlessEnvironment() { - if (typeof globalThis.process === "undefined" || !globalThis.process.env) { - return false; - } - const env2 = globalThis.process.env; - return !!(env2.VERCEL || env2.VERCEL_ENV || env2.AWS_LAMBDA_FUNCTION_NAME || env2.NETLIFY || env2.FUNCTIONS_WORKER_RUNTIME || env2.K_SERVICE || env2.FUNCTION_TARGET || env2.DENO_DEPLOYMENT_ID); - } - /** - * Initialize the persistence adapter based on configuration. - * Defaults to 'auto' when persistence is not specified. - * Use `persistence: false` to explicitly disable persistence. - * - * In serverless environments (Vercel, AWS Lambda, etc.), auto mode disables - * file-system persistence and emits a warning. Use `persistence: false` or - * supply a custom adapter for serverless-safe operation. - */ - async initPersistence() { - const persistence = this.config.persistence === void 0 ? "auto" : this.config.persistence; - if (persistence === false) return; - if (typeof persistence === "string") { - if (persistence === "auto") { - if (this.isBrowserEnvironment()) { - const { LocalStoragePersistenceAdapter: LocalStoragePersistenceAdapter2 } = await Promise.resolve().then(() => (init_local_storage_adapter(), local_storage_adapter_exports)); - this.persistenceAdapter = new LocalStoragePersistenceAdapter2(); - this.logger.debug("Auto-detected browser environment, using localStorage persistence"); - } else if (this.isServerlessEnvironment()) { - this.logger.warn(_InMemoryDriver2.SERVERLESS_PERSISTENCE_WARNING); - } else { - const { FileSystemPersistenceAdapter: FileSystemPersistenceAdapter2 } = await Promise.resolve().then(() => (init_file_adapter(), file_adapter_exports)); - this.persistenceAdapter = new FileSystemPersistenceAdapter2(); - this.logger.debug("Auto-detected Node.js environment, using file persistence"); - } - } else if (persistence === "file") { - const { FileSystemPersistenceAdapter: FileSystemPersistenceAdapter2 } = await Promise.resolve().then(() => (init_file_adapter(), file_adapter_exports)); - this.persistenceAdapter = new FileSystemPersistenceAdapter2(); - } else if (persistence === "local") { - const { LocalStoragePersistenceAdapter: LocalStoragePersistenceAdapter2 } = await Promise.resolve().then(() => (init_local_storage_adapter(), local_storage_adapter_exports)); - this.persistenceAdapter = new LocalStoragePersistenceAdapter2(); - } else { - throw new Error(`Unknown persistence type: "${persistence}". Use 'file', 'local', or 'auto'.`); - } - } else if ("adapter" in persistence && persistence.adapter) { - this.persistenceAdapter = persistence.adapter; - } else if ("type" in persistence) { - if (persistence.type === "auto") { - if (this.isBrowserEnvironment()) { - const { LocalStoragePersistenceAdapter: LocalStoragePersistenceAdapter2 } = await Promise.resolve().then(() => (init_local_storage_adapter(), local_storage_adapter_exports)); - this.persistenceAdapter = new LocalStoragePersistenceAdapter2({ - key: persistence.key - }); - this.logger.debug("Auto-detected browser environment, using localStorage persistence"); - } else if (this.isServerlessEnvironment()) { - this.logger.warn(_InMemoryDriver2.SERVERLESS_PERSISTENCE_WARNING); - } else { - const { FileSystemPersistenceAdapter: FileSystemPersistenceAdapter2 } = await Promise.resolve().then(() => (init_file_adapter(), file_adapter_exports)); - this.persistenceAdapter = new FileSystemPersistenceAdapter2({ - path: persistence.path, - autoSaveInterval: persistence.autoSaveInterval - }); - this.logger.debug("Auto-detected Node.js environment, using file persistence"); - } - } else if (persistence.type === "file") { - const { FileSystemPersistenceAdapter: FileSystemPersistenceAdapter2 } = await Promise.resolve().then(() => (init_file_adapter(), file_adapter_exports)); - this.persistenceAdapter = new FileSystemPersistenceAdapter2({ - path: persistence.path, - autoSaveInterval: persistence.autoSaveInterval - }); - } else if (persistence.type === "local") { - const { LocalStoragePersistenceAdapter: LocalStoragePersistenceAdapter2 } = await Promise.resolve().then(() => (init_local_storage_adapter(), local_storage_adapter_exports)); - this.persistenceAdapter = new LocalStoragePersistenceAdapter2({ - key: persistence.key - }); - } - } - if (this.persistenceAdapter) { - this.logger.debug("Persistence adapter initialized"); - } - } -}; -_InMemoryDriver.SERVERLESS_PERSISTENCE_WARNING = "Serverless environment detected \u2014 file-system persistence is disabled in auto mode. Data will NOT be persisted across function invocations. Set persistence: false to silence this warning, or provide a custom adapter (e.g. Upstash Redis, Vercel KV) via persistence: { adapter: yourAdapter }."; -var InMemoryDriver = _InMemoryDriver; -init_file_adapter(); -init_local_storage_adapter(); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/compose.js -var compose = (middleware, onError, onNotFound) => { - return (context, next) => { - let index = -1; - return dispatch(0); - async function dispatch(i) { - if (i <= index) { - throw new Error("next() called multiple times"); - } - index = i; - let res; - let isError = false; - let handler; - if (middleware[i]) { - handler = middleware[i][0][0]; - context.req.routeIndex = i; - } else { - handler = i === middleware.length && next || void 0; - } - if (handler) { - try { - res = await handler(context, () => dispatch(i + 1)); - } catch (err) { - if (err instanceof Error && onError) { - context.error = err; - res = await onError(err, context); - isError = true; - } else { - throw err; - } - } - } else { - if (context.finalized === false && onNotFound) { - res = await onNotFound(context); - } - } - if (res && (context.finalized === false || isError)) { - context.res = res; - } - return context; - } - }; -}; - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/request/constants.js -var GET_MATCH_RESULT = /* @__PURE__ */ Symbol(); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/body.js -var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => { - const { all = false, dot = false } = options; - const headers = request instanceof HonoRequest ? request.raw.headers : request.headers; - const contentType = headers.get("Content-Type"); - if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) { - return parseFormData(request, { all, dot }); - } - return {}; -}; -async function parseFormData(request, options) { - const formData = await request.formData(); - if (formData) { - return convertFormDataToBodyData(formData, options); - } - return {}; -} -function convertFormDataToBodyData(formData, options) { - const form = /* @__PURE__ */ Object.create(null); - formData.forEach((value, key) => { - const shouldParseAllValues = options.all || key.endsWith("[]"); - if (!shouldParseAllValues) { - form[key] = value; - } else { - handleParsingAllValues(form, key, value); - } - }); - if (options.dot) { - Object.entries(form).forEach(([key, value]) => { - const shouldParseDotValues = key.includes("."); - if (shouldParseDotValues) { - handleParsingNestedValues(form, key, value); - delete form[key]; - } - }); - } - return form; -} -var handleParsingAllValues = (form, key, value) => { - if (form[key] !== void 0) { - if (Array.isArray(form[key])) { - ; - form[key].push(value); - } else { - form[key] = [form[key], value]; - } - } else { - if (!key.endsWith("[]")) { - form[key] = value; - } else { - form[key] = [value]; - } - } -}; -var handleParsingNestedValues = (form, key, value) => { - if (/(?:^|\.)__proto__\./.test(key)) { - return; - } - let nestedForm = form; - const keys = key.split("."); - keys.forEach((key2, index) => { - if (index === keys.length - 1) { - nestedForm[key2] = value; - } else { - if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) { - nestedForm[key2] = /* @__PURE__ */ Object.create(null); - } - nestedForm = nestedForm[key2]; - } - }); -}; - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/url.js -var splitPath = (path3) => { - const paths2 = path3.split("/"); - if (paths2[0] === "") { - paths2.shift(); - } - return paths2; -}; -var splitRoutingPath = (routePath) => { - const { groups, path: path3 } = extractGroupsFromPath(routePath); - const paths2 = splitPath(path3); - return replaceGroupMarks(paths2, groups); -}; -var extractGroupsFromPath = (path3) => { - const groups = []; - path3 = path3.replace(/\{[^}]+\}/g, (match2, index) => { - const mark = `@${index}`; - groups.push([mark, match2]); - return mark; - }); - return { groups, path: path3 }; -}; -var replaceGroupMarks = (paths2, groups) => { - for (let i = groups.length - 1; i >= 0; i--) { - const [mark] = groups[i]; - for (let j = paths2.length - 1; j >= 0; j--) { - if (paths2[j].includes(mark)) { - paths2[j] = paths2[j].replace(mark, groups[i][1]); - break; - } - } - } - return paths2; -}; -var patternCache = {}; -var getPattern = (label, next) => { - if (label === "*") { - return "*"; - } - const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); - if (match2) { - const cacheKey2 = `${label}#${next}`; - if (!patternCache[cacheKey2]) { - if (match2[2]) { - patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)]; - } else { - patternCache[cacheKey2] = [label, match2[1], true]; - } - } - return patternCache[cacheKey2]; - } - return null; -}; -var tryDecode = (str, decoder2) => { - try { - return decoder2(str); - } catch { - return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => { - try { - return decoder2(match2); - } catch { - return match2; - } - }); - } -}; -var tryDecodeURI = (str) => tryDecode(str, decodeURI); -var getPath = (request) => { - const url2 = request.url; - const start = url2.indexOf("/", url2.indexOf(":") + 4); - let i = start; - for (; i < url2.length; i++) { - const charCode = url2.charCodeAt(i); - if (charCode === 37) { - const queryIndex = url2.indexOf("?", i); - const hashIndex = url2.indexOf("#", i); - const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex); - const path3 = url2.slice(start, end); - return tryDecodeURI(path3.includes("%25") ? path3.replace(/%25/g, "%2525") : path3); - } else if (charCode === 63 || charCode === 35) { - break; - } - } - return url2.slice(start, i); -}; -var getPathNoStrict = (request) => { - const result = getPath(request); - return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result; -}; -var mergePath = (base, sub, ...rest) => { - if (rest.length) { - sub = mergePath(sub, ...rest); - } - return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`; -}; -var checkOptionalParameter = (path3) => { - if (path3.charCodeAt(path3.length - 1) !== 63 || !path3.includes(":")) { - return null; - } - const segments = path3.split("/"); - const results = []; - let basePath = ""; - segments.forEach((segment) => { - if (segment !== "" && !/\:/.test(segment)) { - basePath += "/" + segment; - } else if (/\:/.test(segment)) { - if (/\?/.test(segment)) { - if (results.length === 0 && basePath === "") { - results.push("/"); - } else { - results.push(basePath); - } - const optionalSegment = segment.replace("?", ""); - basePath += "/" + optionalSegment; - results.push(basePath); - } else { - basePath += "/" + segment; - } - } - }); - return results.filter((v, i, a) => a.indexOf(v) === i); -}; -var _decodeURI = (value) => { - if (!/[%+]/.test(value)) { - return value; - } - if (value.indexOf("+") !== -1) { - value = value.replace(/\+/g, " "); - } - return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value; -}; -var _getQueryParam = (url2, key, multiple) => { - let encoded; - if (!multiple && key && !/[%+]/.test(key)) { - let keyIndex2 = url2.indexOf("?", 8); - if (keyIndex2 === -1) { - return void 0; - } - if (!url2.startsWith(key, keyIndex2 + 1)) { - keyIndex2 = url2.indexOf(`&${key}`, keyIndex2 + 1); - } - while (keyIndex2 !== -1) { - const trailingKeyCode = url2.charCodeAt(keyIndex2 + key.length + 1); - if (trailingKeyCode === 61) { - const valueIndex = keyIndex2 + key.length + 2; - const endIndex = url2.indexOf("&", valueIndex); - return _decodeURI(url2.slice(valueIndex, endIndex === -1 ? void 0 : endIndex)); - } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { - return ""; - } - keyIndex2 = url2.indexOf(`&${key}`, keyIndex2 + 1); - } - encoded = /[%+]/.test(url2); - if (!encoded) { - return void 0; - } - } - const results = {}; - encoded ?? (encoded = /[%+]/.test(url2)); - let keyIndex = url2.indexOf("?", 8); - while (keyIndex !== -1) { - const nextKeyIndex = url2.indexOf("&", keyIndex + 1); - let valueIndex = url2.indexOf("=", keyIndex); - if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { - valueIndex = -1; - } - let name = url2.slice( - keyIndex + 1, - valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex - ); - if (encoded) { - name = _decodeURI(name); - } - keyIndex = nextKeyIndex; - if (name === "") { - continue; - } - let value; - if (valueIndex === -1) { - value = ""; - } else { - value = url2.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex); - if (encoded) { - value = _decodeURI(value); - } - } - if (multiple) { - if (!(results[name] && Array.isArray(results[name]))) { - results[name] = []; - } - ; - results[name].push(value); - } else { - results[name] ?? (results[name] = value); - } - } - return key ? results[key] : results; -}; -var getQueryParam = _getQueryParam; -var getQueryParams = (url2, key) => { - return _getQueryParam(url2, key, true); -}; -var decodeURIComponent_ = decodeURIComponent; - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/request.js -var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_); -var _validatedData, _matchResult, _HonoRequest_instances, getDecodedParam_fn, getAllDecodedParams_fn, getParamValue_fn, _cachedBody, _a2; -var HonoRequest = (_a2 = class { - constructor(request, path3 = "/", matchResult = [[]]) { - __privateAdd(this, _HonoRequest_instances); - /** - * `.raw` can get the raw Request object. - * - * @see {@link https://hono.dev/docs/api/request#raw} - * - * @example - * ```ts - * // For Cloudflare Workers - * app.post('/', async (c) => { - * const metadata = c.req.raw.cf?.hostMetadata? - * ... - * }) - * ``` - */ - __publicField(this, "raw"); - __privateAdd(this, _validatedData); - // Short name of validatedData - __privateAdd(this, _matchResult); - __publicField(this, "routeIndex", 0); - /** - * `.path` can get the pathname of the request. - * - * @see {@link https://hono.dev/docs/api/request#path} - * - * @example - * ```ts - * app.get('/about/me', (c) => { - * const pathname = c.req.path // `/about/me` - * }) - * ``` - */ - __publicField(this, "path"); - __publicField(this, "bodyCache", {}); - __privateAdd(this, _cachedBody, (key) => { - const { bodyCache, raw: raw2 } = this; - const cachedBody = bodyCache[key]; - if (cachedBody) { - return cachedBody; - } - const anyCachedKey = Object.keys(bodyCache)[0]; - if (anyCachedKey) { - return bodyCache[anyCachedKey].then((body) => { - if (anyCachedKey === "json") { - body = JSON.stringify(body); - } - return new Response(body)[key](); - }); - } - return bodyCache[key] = raw2[key](); - }); - this.raw = request; - this.path = path3; - __privateSet(this, _matchResult, matchResult); - __privateSet(this, _validatedData, {}); - } - param(key) { - return key ? __privateMethod(this, _HonoRequest_instances, getDecodedParam_fn).call(this, key) : __privateMethod(this, _HonoRequest_instances, getAllDecodedParams_fn).call(this); - } - query(key) { - return getQueryParam(this.url, key); - } - queries(key) { - return getQueryParams(this.url, key); - } - header(name) { - if (name) { - return this.raw.headers.get(name) ?? void 0; - } - const headerData = {}; - this.raw.headers.forEach((value, key) => { - headerData[key] = value; - }); - return headerData; - } - async parseBody(options) { - return parseBody(this, options); - } - /** - * `.json()` can parse Request body of type `application/json` - * - * @see {@link https://hono.dev/docs/api/request#json} - * - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.json() - * }) - * ``` - */ - json() { - return __privateGet(this, _cachedBody).call(this, "text").then((text) => JSON.parse(text)); - } - /** - * `.text()` can parse Request body of type `text/plain` - * - * @see {@link https://hono.dev/docs/api/request#text} - * - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.text() - * }) - * ``` - */ - text() { - return __privateGet(this, _cachedBody).call(this, "text"); - } - /** - * `.arrayBuffer()` parse Request body as an `ArrayBuffer` - * - * @see {@link https://hono.dev/docs/api/request#arraybuffer} - * - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.arrayBuffer() - * }) - * ``` - */ - arrayBuffer() { - return __privateGet(this, _cachedBody).call(this, "arrayBuffer"); - } - /** - * Parses the request body as a `Blob`. - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.blob(); - * }); - * ``` - * @see https://hono.dev/docs/api/request#blob - */ - blob() { - return __privateGet(this, _cachedBody).call(this, "blob"); - } - /** - * Parses the request body as `FormData`. - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.formData(); - * }); - * ``` - * @see https://hono.dev/docs/api/request#formdata - */ - formData() { - return __privateGet(this, _cachedBody).call(this, "formData"); - } - /** - * Adds validated data to the request. - * - * @param target - The target of the validation. - * @param data - The validated data to add. - */ - addValidatedData(target, data) { - __privateGet(this, _validatedData)[target] = data; - } - valid(target) { - return __privateGet(this, _validatedData)[target]; - } - /** - * `.url()` can get the request url strings. - * - * @see {@link https://hono.dev/docs/api/request#url} - * - * @example - * ```ts - * app.get('/about/me', (c) => { - * const url = c.req.url // `http://localhost:8787/about/me` - * ... - * }) - * ``` - */ - get url() { - return this.raw.url; - } - /** - * `.method()` can get the method name of the request. - * - * @see {@link https://hono.dev/docs/api/request#method} - * - * @example - * ```ts - * app.get('/about/me', (c) => { - * const method = c.req.method // `GET` - * }) - * ``` - */ - get method() { - return this.raw.method; - } - get [GET_MATCH_RESULT]() { - return __privateGet(this, _matchResult); - } - /** - * `.matchedRoutes()` can return a matched route in the handler - * - * @deprecated - * - * Use matchedRoutes helper defined in "hono/route" instead. - * - * @see {@link https://hono.dev/docs/api/request#matchedroutes} - * - * @example - * ```ts - * app.use('*', async function logger(c, next) { - * await next() - * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { - * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') - * console.log( - * method, - * ' ', - * path, - * ' '.repeat(Math.max(10 - path.length, 0)), - * name, - * i === c.req.routeIndex ? '<- respond from here' : '' - * ) - * }) - * }) - * ``` - */ - get matchedRoutes() { - return __privateGet(this, _matchResult)[0].map(([[, route]]) => route); - } - /** - * `routePath()` can retrieve the path registered within the handler - * - * @deprecated - * - * Use routePath helper defined in "hono/route" instead. - * - * @see {@link https://hono.dev/docs/api/request#routepath} - * - * @example - * ```ts - * app.get('/posts/:id', (c) => { - * return c.json({ path: c.req.routePath }) - * }) - * ``` - */ - get routePath() { - return __privateGet(this, _matchResult)[0].map(([[, route]]) => route)[this.routeIndex].path; - } -}, _validatedData = new WeakMap(), _matchResult = new WeakMap(), _HonoRequest_instances = new WeakSet(), getDecodedParam_fn = function(key) { - const paramKey = __privateGet(this, _matchResult)[0][this.routeIndex][1][key]; - const param = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, paramKey); - return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param; -}, getAllDecodedParams_fn = function() { - const decoded = {}; - const keys = Object.keys(__privateGet(this, _matchResult)[0][this.routeIndex][1]); - for (const key of keys) { - const value = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, __privateGet(this, _matchResult)[0][this.routeIndex][1][key]); - if (value !== void 0) { - decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value; - } - } - return decoded; -}, getParamValue_fn = function(paramKey) { - return __privateGet(this, _matchResult)[1] ? __privateGet(this, _matchResult)[1][paramKey] : paramKey; -}, _cachedBody = new WeakMap(), _a2); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/html.js -var HtmlEscapedCallbackPhase = { - Stringify: 1, - BeforeStream: 2, - Stream: 3 -}; -var raw = (value, callbacks) => { - const escapedString = new String(value); - escapedString.isEscaped = true; - escapedString.callbacks = callbacks; - return escapedString; -}; -var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => { - if (typeof str === "object" && !(str instanceof String)) { - if (!(str instanceof Promise)) { - str = str.toString(); - } - if (str instanceof Promise) { - str = await str; - } - } - const callbacks = str.callbacks; - if (!callbacks?.length) { - return Promise.resolve(str); - } - if (buffer) { - buffer[0] += str; - } else { - buffer = [str]; - } - const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then( - (res) => Promise.all( - res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer)) - ).then(() => buffer[0]) - ); - if (preserveCallbacks) { - return raw(await resStr, callbacks); - } else { - return resStr; - } -}; - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/context.js -var TEXT_PLAIN = "text/plain; charset=UTF-8"; -var setDefaultContentType = (contentType, headers) => { - return { - "Content-Type": contentType, - ...headers - }; -}; -var createResponseInstance = (body, init2) => new Response(body, init2); -var _rawRequest, _req, _var, _status, _executionCtx, _res, _layout, _renderer, _notFoundHandler, _preparedHeaders, _matchResult2, _path, _Context_instances, newResponse_fn, _a3; -var Context2 = (_a3 = class { - /** - * Creates an instance of the Context class. - * - * @param req - The Request object. - * @param options - Optional configuration options for the context. - */ - constructor(req, options) { - __privateAdd(this, _Context_instances); - __privateAdd(this, _rawRequest); - __privateAdd(this, _req); - /** - * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers. - * - * @see {@link https://hono.dev/docs/api/context#env} - * - * @example - * ```ts - * // Environment object for Cloudflare Workers - * app.get('*', async c => { - * const counter = c.env.COUNTER - * }) - * ``` - */ - __publicField(this, "env", {}); - __privateAdd(this, _var); - __publicField(this, "finalized", false); - /** - * `.error` can get the error object from the middleware if the Handler throws an error. - * - * @see {@link https://hono.dev/docs/api/context#error} - * - * @example - * ```ts - * app.use('*', async (c, next) => { - * await next() - * if (c.error) { - * // do something... - * } - * }) - * ``` - */ - __publicField(this, "error"); - __privateAdd(this, _status); - __privateAdd(this, _executionCtx); - __privateAdd(this, _res); - __privateAdd(this, _layout); - __privateAdd(this, _renderer); - __privateAdd(this, _notFoundHandler); - __privateAdd(this, _preparedHeaders); - __privateAdd(this, _matchResult2); - __privateAdd(this, _path); - /** - * `.render()` can create a response within a layout. - * - * @see {@link https://hono.dev/docs/api/context#render-setrenderer} - * - * @example - * ```ts - * app.get('/', (c) => { - * return c.render('Hello!') - * }) - * ``` - */ - __publicField(this, "render", (...args) => { - __privateGet(this, _renderer) ?? __privateSet(this, _renderer, (content) => this.html(content)); - return __privateGet(this, _renderer).call(this, ...args); - }); - /** - * Sets the layout for the response. - * - * @param layout - The layout to set. - * @returns The layout function. - */ - __publicField(this, "setLayout", (layout) => __privateSet(this, _layout, layout)); - /** - * Gets the current layout for the response. - * - * @returns The current layout function. - */ - __publicField(this, "getLayout", () => __privateGet(this, _layout)); - /** - * `.setRenderer()` can set the layout in the custom middleware. - * - * @see {@link https://hono.dev/docs/api/context#render-setrenderer} - * - * @example - * ```tsx - * app.use('*', async (c, next) => { - * c.setRenderer((content) => { - * return c.html( - * - * - *

{content}

- * - * - * ) - * }) - * await next() - * }) - * ``` - */ - __publicField(this, "setRenderer", (renderer) => { - __privateSet(this, _renderer, renderer); - }); - /** - * `.header()` can set headers. - * - * @see {@link https://hono.dev/docs/api/context#header} - * - * @example - * ```ts - * app.get('/welcome', (c) => { - * // Set headers - * c.header('X-Message', 'Hello!') - * c.header('Content-Type', 'text/plain') - * - * return c.body('Thank you for coming') - * }) - * ``` - */ - __publicField(this, "header", (name, value, options) => { - if (this.finalized) { - __privateSet(this, _res, createResponseInstance(__privateGet(this, _res).body, __privateGet(this, _res))); - } - const headers = __privateGet(this, _res) ? __privateGet(this, _res).headers : __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, new Headers()); - if (value === void 0) { - headers.delete(name); - } else if (options?.append) { - headers.append(name, value); - } else { - headers.set(name, value); - } - }); - __publicField(this, "status", (status) => { - __privateSet(this, _status, status); - }); - /** - * `.set()` can set the value specified by the key. - * - * @see {@link https://hono.dev/docs/api/context#set-get} - * - * @example - * ```ts - * app.use('*', async (c, next) => { - * c.set('message', 'Hono is hot!!') - * await next() - * }) - * ``` - */ - __publicField(this, "set", (key, value) => { - __privateGet(this, _var) ?? __privateSet(this, _var, /* @__PURE__ */ new Map()); - __privateGet(this, _var).set(key, value); - }); - /** - * `.get()` can use the value specified by the key. - * - * @see {@link https://hono.dev/docs/api/context#set-get} - * - * @example - * ```ts - * app.get('/', (c) => { - * const message = c.get('message') - * return c.text(`The message is "${message}"`) - * }) - * ``` - */ - __publicField(this, "get", (key) => { - return __privateGet(this, _var) ? __privateGet(this, _var).get(key) : void 0; - }); - __publicField(this, "newResponse", (...args) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, ...args)); - /** - * `.body()` can return the HTTP response. - * You can set headers with `.header()` and set HTTP status code with `.status`. - * This can also be set in `.text()`, `.json()` and so on. - * - * @see {@link https://hono.dev/docs/api/context#body} - * - * @example - * ```ts - * app.get('/welcome', (c) => { - * // Set headers - * c.header('X-Message', 'Hello!') - * c.header('Content-Type', 'text/plain') - * // Set HTTP status code - * c.status(201) - * - * // Return the response body - * return c.body('Thank you for coming') - * }) - * ``` - */ - __publicField(this, "body", (data, arg, headers) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg, headers)); - /** - * `.text()` can render text as `Content-Type:text/plain`. - * - * @see {@link https://hono.dev/docs/api/context#text} - * - * @example - * ```ts - * app.get('/say', (c) => { - * return c.text('Hello!') - * }) - * ``` - */ - __publicField(this, "text", (text, arg, headers) => { - return !__privateGet(this, _preparedHeaders) && !__privateGet(this, _status) && !arg && !headers && !this.finalized ? new Response(text) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg, setDefaultContentType(TEXT_PLAIN, headers)); - }); - /** - * `.json()` can render JSON as `Content-Type:application/json`. - * - * @see {@link https://hono.dev/docs/api/context#json} - * - * @example - * ```ts - * app.get('/api', (c) => { - * return c.json({ message: 'Hello!' }) - * }) - * ``` - */ - __publicField(this, "json", (object2, arg, headers) => { - return __privateMethod(this, _Context_instances, newResponse_fn).call(this, JSON.stringify(object2), arg, setDefaultContentType("application/json", headers)); - }); - __publicField(this, "html", (html2, arg, headers) => { - const res = (html22) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, html22, arg, setDefaultContentType("text/html; charset=UTF-8", headers)); - return typeof html2 === "object" ? resolveCallback(html2, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html2); - }); - /** - * `.redirect()` can Redirect, default status code is 302. - * - * @see {@link https://hono.dev/docs/api/context#redirect} - * - * @example - * ```ts - * app.get('/redirect', (c) => { - * return c.redirect('/') - * }) - * app.get('/redirect-permanently', (c) => { - * return c.redirect('/', 301) - * }) - * ``` - */ - __publicField(this, "redirect", (location, status) => { - const locationString = String(location); - this.header( - "Location", - // Multibyes should be encoded - // eslint-disable-next-line no-control-regex - !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString) - ); - return this.newResponse(null, status ?? 302); - }); - /** - * `.notFound()` can return the Not Found Response. - * - * @see {@link https://hono.dev/docs/api/context#notfound} - * - * @example - * ```ts - * app.get('/notfound', (c) => { - * return c.notFound() - * }) - * ``` - */ - __publicField(this, "notFound", () => { - __privateGet(this, _notFoundHandler) ?? __privateSet(this, _notFoundHandler, () => createResponseInstance()); - return __privateGet(this, _notFoundHandler).call(this, this); - }); - __privateSet(this, _rawRequest, req); - if (options) { - __privateSet(this, _executionCtx, options.executionCtx); - this.env = options.env; - __privateSet(this, _notFoundHandler, options.notFoundHandler); - __privateSet(this, _path, options.path); - __privateSet(this, _matchResult2, options.matchResult); - } - } - /** - * `.req` is the instance of {@link HonoRequest}. - */ - get req() { - __privateGet(this, _req) ?? __privateSet(this, _req, new HonoRequest(__privateGet(this, _rawRequest), __privateGet(this, _path), __privateGet(this, _matchResult2))); - return __privateGet(this, _req); - } - /** - * @see {@link https://hono.dev/docs/api/context#event} - * The FetchEvent associated with the current request. - * - * @throws Will throw an error if the context does not have a FetchEvent. - */ - get event() { - if (__privateGet(this, _executionCtx) && "respondWith" in __privateGet(this, _executionCtx)) { - return __privateGet(this, _executionCtx); - } else { - throw Error("This context has no FetchEvent"); - } - } - /** - * @see {@link https://hono.dev/docs/api/context#executionctx} - * The ExecutionContext associated with the current request. - * - * @throws Will throw an error if the context does not have an ExecutionContext. - */ - get executionCtx() { - if (__privateGet(this, _executionCtx)) { - return __privateGet(this, _executionCtx); - } else { - throw Error("This context has no ExecutionContext"); - } - } - /** - * @see {@link https://hono.dev/docs/api/context#res} - * The Response object for the current request. - */ - get res() { - return __privateGet(this, _res) || __privateSet(this, _res, createResponseInstance(null, { - headers: __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, new Headers()) - })); - } - /** - * Sets the Response object for the current request. - * - * @param _res - The Response object to set. - */ - set res(_res2) { - if (__privateGet(this, _res) && _res2) { - _res2 = createResponseInstance(_res2.body, _res2); - for (const [k, v] of __privateGet(this, _res).headers.entries()) { - if (k === "content-type") { - continue; - } - if (k === "set-cookie") { - const cookies = __privateGet(this, _res).headers.getSetCookie(); - _res2.headers.delete("set-cookie"); - for (const cookie of cookies) { - _res2.headers.append("set-cookie", cookie); - } - } else { - _res2.headers.set(k, v); - } - } - } - __privateSet(this, _res, _res2); - this.finalized = true; - } - /** - * `.var` can access the value of a variable. - * - * @see {@link https://hono.dev/docs/api/context#var} - * - * @example - * ```ts - * const result = c.var.client.oneMethod() - * ``` - */ - // c.var.propName is a read-only - get var() { - if (!__privateGet(this, _var)) { - return {}; - } - return Object.fromEntries(__privateGet(this, _var)); - } -}, _rawRequest = new WeakMap(), _req = new WeakMap(), _var = new WeakMap(), _status = new WeakMap(), _executionCtx = new WeakMap(), _res = new WeakMap(), _layout = new WeakMap(), _renderer = new WeakMap(), _notFoundHandler = new WeakMap(), _preparedHeaders = new WeakMap(), _matchResult2 = new WeakMap(), _path = new WeakMap(), _Context_instances = new WeakSet(), newResponse_fn = function(data, arg, headers) { - const responseHeaders = __privateGet(this, _res) ? new Headers(__privateGet(this, _res).headers) : __privateGet(this, _preparedHeaders) ?? new Headers(); - if (typeof arg === "object" && "headers" in arg) { - const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers); - for (const [key, value] of argHeaders) { - if (key.toLowerCase() === "set-cookie") { - responseHeaders.append(key, value); - } else { - responseHeaders.set(key, value); - } - } - } - if (headers) { - for (const [k, v] of Object.entries(headers)) { - if (typeof v === "string") { - responseHeaders.set(k, v); - } else { - responseHeaders.delete(k); - for (const v2 of v) { - responseHeaders.append(k, v2); - } - } - } - } - const status = typeof arg === "number" ? arg : arg?.status ?? __privateGet(this, _status); - return createResponseInstance(data, { status, headers: responseHeaders }); -}, _a3); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router.js -var METHOD_NAME_ALL = "ALL"; -var METHOD_NAME_ALL_LOWERCASE = "all"; -var METHODS = ["get", "post", "put", "delete", "options", "patch"]; -var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built."; -var UnsupportedPathError = class extends Error { -}; - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/constants.js -var COMPOSED_HANDLER = "__COMPOSED_HANDLER"; - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/hono-base.js -var notFoundHandler = (c) => { - return c.text("404 Not Found", 404); -}; -var errorHandler = (err, c) => { - if ("getResponse" in err) { - const res = err.getResponse(); - return c.newResponse(res.body, res); - } - console.error(err); - return c.text("Internal Server Error", 500); -}; -var _path2, __Hono_instances, clone_fn, _notFoundHandler2, addRoute_fn, handleError_fn, dispatch_fn, _a4; -var Hono = (_a4 = class { - constructor(options = {}) { - __privateAdd(this, __Hono_instances); - __publicField(this, "get"); - __publicField(this, "post"); - __publicField(this, "put"); - __publicField(this, "delete"); - __publicField(this, "options"); - __publicField(this, "patch"); - __publicField(this, "all"); - __publicField(this, "on"); - __publicField(this, "use"); - /* - This class is like an abstract class and does not have a router. - To use it, inherit the class and implement router in the constructor. - */ - __publicField(this, "router"); - __publicField(this, "getPath"); - // Cannot use `#` because it requires visibility at JavaScript runtime. - __publicField(this, "_basePath", "/"); - __privateAdd(this, _path2, "/"); - __publicField(this, "routes", []); - __privateAdd(this, _notFoundHandler2, notFoundHandler); - // Cannot use `#` because it requires visibility at JavaScript runtime. - __publicField(this, "errorHandler", errorHandler); - /** - * `.onError()` handles an error and returns a customized Response. - * - * @see {@link https://hono.dev/docs/api/hono#error-handling} - * - * @param {ErrorHandler} handler - request Handler for error - * @returns {Hono} changed Hono instance - * - * @example - * ```ts - * app.onError((err, c) => { - * console.error(`${err}`) - * return c.text('Custom Error Message', 500) - * }) - * ``` - */ - __publicField(this, "onError", (handler) => { - this.errorHandler = handler; - return this; - }); - /** - * `.notFound()` allows you to customize a Not Found Response. - * - * @see {@link https://hono.dev/docs/api/hono#not-found} - * - * @param {NotFoundHandler} handler - request handler for not-found - * @returns {Hono} changed Hono instance - * - * @example - * ```ts - * app.notFound((c) => { - * return c.text('Custom 404 Message', 404) - * }) - * ``` - */ - __publicField(this, "notFound", (handler) => { - __privateSet(this, _notFoundHandler2, handler); - return this; - }); - /** - * `.fetch()` will be entry point of your app. - * - * @see {@link https://hono.dev/docs/api/hono#fetch} - * - * @param {Request} request - request Object of request - * @param {Env} Env - env Object - * @param {ExecutionContext} - context of execution - * @returns {Response | Promise} response of request - * - */ - __publicField(this, "fetch", (request, ...rest) => { - return __privateMethod(this, __Hono_instances, dispatch_fn).call(this, request, rest[1], rest[0], request.method); - }); - /** - * `.request()` is a useful method for testing. - * You can pass a URL or pathname to send a GET request. - * app will return a Response object. - * ```ts - * test('GET /hello is ok', async () => { - * const res = await app.request('/hello') - * expect(res.status).toBe(200) - * }) - * ``` - * @see https://hono.dev/docs/api/hono#request - */ - __publicField(this, "request", (input, requestInit, Env, executionCtx) => { - if (input instanceof Request) { - return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx); - } - input = input.toString(); - return this.fetch( - new Request( - /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, - requestInit - ), - Env, - executionCtx - ); - }); - /** - * `.fire()` automatically adds a global fetch event listener. - * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers. - * @deprecated - * Use `fire` from `hono/service-worker` instead. - * ```ts - * import { Hono } from 'hono' - * import { fire } from 'hono/service-worker' - * - * const app = new Hono() - * // ... - * fire(app) - * ``` - * @see https://hono.dev/docs/api/hono#fire - * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API - * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ - */ - __publicField(this, "fire", () => { - addEventListener("fetch", (event) => { - event.respondWith(__privateMethod(this, __Hono_instances, dispatch_fn).call(this, event.request, event, void 0, event.request.method)); - }); - }); - const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]; - allMethods.forEach((method) => { - this[method] = (args1, ...args) => { - if (typeof args1 === "string") { - __privateSet(this, _path2, args1); - } else { - __privateMethod(this, __Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), args1); - } - args.forEach((handler) => { - __privateMethod(this, __Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), handler); - }); - return this; - }; - }); - this.on = (method, path3, ...handlers) => { - for (const p of [path3].flat()) { - __privateSet(this, _path2, p); - for (const m of [method].flat()) { - handlers.map((handler) => { - __privateMethod(this, __Hono_instances, addRoute_fn).call(this, m.toUpperCase(), __privateGet(this, _path2), handler); - }); - } - } - return this; - }; - this.use = (arg1, ...handlers) => { - if (typeof arg1 === "string") { - __privateSet(this, _path2, arg1); - } else { - __privateSet(this, _path2, "*"); - handlers.unshift(arg1); - } - handlers.forEach((handler) => { - __privateMethod(this, __Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, __privateGet(this, _path2), handler); - }); - return this; - }; - const { strict, ...optionsWithoutStrict } = options; - Object.assign(this, optionsWithoutStrict); - this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict; - } - /** - * `.route()` allows grouping other Hono instance in routes. - * - * @see {@link https://hono.dev/docs/api/routing#grouping} - * - * @param {string} path - base Path - * @param {Hono} app - other Hono instance - * @returns {Hono} routed Hono instance - * - * @example - * ```ts - * const app = new Hono() - * const app2 = new Hono() - * - * app2.get("/user", (c) => c.text("user")) - * app.route("/api", app2) // GET /api/user - * ``` - */ - route(path3, app) { - const subApp = this.basePath(path3); - app.routes.map((r) => { - var _a30; - let handler; - if (app.errorHandler === errorHandler) { - handler = r.handler; - } else { - handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res; - handler[COMPOSED_HANDLER] = r.handler; - } - __privateMethod(_a30 = subApp, __Hono_instances, addRoute_fn).call(_a30, r.method, r.path, handler); - }); - return this; - } - /** - * `.basePath()` allows base paths to be specified. - * - * @see {@link https://hono.dev/docs/api/routing#base-path} - * - * @param {string} path - base Path - * @returns {Hono} changed Hono instance - * - * @example - * ```ts - * const api = new Hono().basePath('/api') - * ``` - */ - basePath(path3) { - const subApp = __privateMethod(this, __Hono_instances, clone_fn).call(this); - subApp._basePath = mergePath(this._basePath, path3); - return subApp; - } - /** - * `.mount()` allows you to mount applications built with other frameworks into your Hono application. - * - * @see {@link https://hono.dev/docs/api/hono#mount} - * - * @param {string} path - base Path - * @param {Function} applicationHandler - other Request Handler - * @param {MountOptions} [options] - options of `.mount()` - * @returns {Hono} mounted Hono instance - * - * @example - * ```ts - * import { Router as IttyRouter } from 'itty-router' - * import { Hono } from 'hono' - * // Create itty-router application - * const ittyRouter = IttyRouter() - * // GET /itty-router/hello - * ittyRouter.get('/hello', () => new Response('Hello from itty-router')) - * - * const app = new Hono() - * app.mount('/itty-router', ittyRouter.handle) - * ``` - * - * @example - * ```ts - * const app = new Hono() - * // Send the request to another application without modification. - * app.mount('/app', anotherApp, { - * replaceRequest: (req) => req, - * }) - * ``` - */ - mount(path3, applicationHandler, options) { - let replaceRequest; - let optionHandler; - if (options) { - if (typeof options === "function") { - optionHandler = options; - } else { - optionHandler = options.optionHandler; - if (options.replaceRequest === false) { - replaceRequest = (request) => request; - } else { - replaceRequest = options.replaceRequest; - } - } - } - const getOptions = optionHandler ? (c) => { - const options2 = optionHandler(c); - return Array.isArray(options2) ? options2 : [options2]; - } : (c) => { - let executionContext = void 0; - try { - executionContext = c.executionCtx; - } catch { - } - return [c.env, executionContext]; - }; - replaceRequest || (replaceRequest = (() => { - const mergedPath = mergePath(this._basePath, path3); - const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; - return (request) => { - const url2 = new URL(request.url); - url2.pathname = url2.pathname.slice(pathPrefixLength) || "/"; - return new Request(url2, request); - }; - })()); - const handler = async (c, next) => { - const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c)); - if (res) { - return res; - } - await next(); - }; - __privateMethod(this, __Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, mergePath(path3, "*"), handler); - return this; - } -}, _path2 = new WeakMap(), __Hono_instances = new WeakSet(), clone_fn = function() { - const clone2 = new _a4({ - router: this.router, - getPath: this.getPath - }); - clone2.errorHandler = this.errorHandler; - __privateSet(clone2, _notFoundHandler2, __privateGet(this, _notFoundHandler2)); - clone2.routes = this.routes; - return clone2; -}, _notFoundHandler2 = new WeakMap(), addRoute_fn = function(method, path3, handler) { - method = method.toUpperCase(); - path3 = mergePath(this._basePath, path3); - const r = { basePath: this._basePath, path: path3, method, handler }; - this.router.add(method, path3, [handler, r]); - this.routes.push(r); -}, handleError_fn = function(err, c) { - if (err instanceof Error) { - return this.errorHandler(err, c); - } - throw err; -}, dispatch_fn = function(request, executionCtx, env2, method) { - if (method === "HEAD") { - return (async () => new Response(null, await __privateMethod(this, __Hono_instances, dispatch_fn).call(this, request, executionCtx, env2, "GET")))(); - } - const path3 = this.getPath(request, { env: env2 }); - const matchResult = this.router.match(method, path3); - const c = new Context2(request, { - path: path3, - matchResult, - env: env2, - executionCtx, - notFoundHandler: __privateGet(this, _notFoundHandler2) - }); - if (matchResult[0].length === 1) { - let res; - try { - res = matchResult[0][0][0][0](c, async () => { - c.res = await __privateGet(this, _notFoundHandler2).call(this, c); - }); - } catch (err) { - return __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c); - } - return res instanceof Promise ? res.then( - (resolved) => resolved || (c.finalized ? c.res : __privateGet(this, _notFoundHandler2).call(this, c)) - ).catch((err) => __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c)) : res ?? __privateGet(this, _notFoundHandler2).call(this, c); - } - const composed = compose(matchResult[0], this.errorHandler, __privateGet(this, _notFoundHandler2)); - return (async () => { - try { - const context = await composed(c); - if (!context.finalized) { - throw new Error( - "Context is not finalized. Did you forget to return a Response object or `await next()`?" - ); - } - return context.res; - } catch (err) { - return __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c); - } - })(); -}, _a4); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/matcher.js -var emptyParam = []; -function match(method, path3) { - const matchers = this.buildAllMatchers(); - const match2 = (method2, path22) => { - const matcher = matchers[method2] || matchers[METHOD_NAME_ALL]; - const staticMatch = matcher[2][path22]; - if (staticMatch) { - return staticMatch; - } - const match3 = path22.match(matcher[0]); - if (!match3) { - return [[], emptyParam]; - } - const index = match3.indexOf("", 1); - return [matcher[1][index], match3]; - }; - this.match = match2; - return match2(method, path3); -} - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/node.js -var LABEL_REG_EXP_STR = "[^/]+"; -var ONLY_WILDCARD_REG_EXP_STR = ".*"; -var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)"; -var PATH_ERROR = /* @__PURE__ */ Symbol(); -var regExpMetaChars = new Set(".\\+*[^]$()"); -function compareKey(a, b) { - if (a.length === 1) { - return b.length === 1 ? a < b ? -1 : 1 : -1; - } - if (b.length === 1) { - return 1; - } - if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { - return 1; - } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) { - return -1; - } - if (a === LABEL_REG_EXP_STR) { - return 1; - } else if (b === LABEL_REG_EXP_STR) { - return -1; - } - return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length; -} -var _index, _varIndex, _children, _a5; -var Node = (_a5 = class { - constructor() { - __privateAdd(this, _index); - __privateAdd(this, _varIndex); - __privateAdd(this, _children, /* @__PURE__ */ Object.create(null)); - } - insert(tokens, index, paramMap, context, pathErrorCheckOnly) { - if (tokens.length === 0) { - if (__privateGet(this, _index) !== void 0) { - throw PATH_ERROR; - } - if (pathErrorCheckOnly) { - return; - } - __privateSet(this, _index, index); - return; - } - const [token, ...restTokens] = tokens; - const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); - let node; - if (pattern) { - const name = pattern[1]; - let regexpStr = pattern[2] || LABEL_REG_EXP_STR; - if (name && pattern[2]) { - if (regexpStr === ".*") { - throw PATH_ERROR; - } - regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"); - if (/\((?!\?:)/.test(regexpStr)) { - throw PATH_ERROR; - } - } - node = __privateGet(this, _children)[regexpStr]; - if (!node) { - if (Object.keys(__privateGet(this, _children)).some( - (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR - )) { - throw PATH_ERROR; - } - if (pathErrorCheckOnly) { - return; - } - node = __privateGet(this, _children)[regexpStr] = new _a5(); - if (name !== "") { - __privateSet(node, _varIndex, context.varIndex++); - } - } - if (!pathErrorCheckOnly && name !== "") { - paramMap.push([name, __privateGet(node, _varIndex)]); - } - } else { - node = __privateGet(this, _children)[token]; - if (!node) { - if (Object.keys(__privateGet(this, _children)).some( - (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR - )) { - throw PATH_ERROR; - } - if (pathErrorCheckOnly) { - return; - } - node = __privateGet(this, _children)[token] = new _a5(); - } - } - node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly); - } - buildRegExpStr() { - const childKeys = Object.keys(__privateGet(this, _children)).sort(compareKey); - const strList = childKeys.map((k) => { - const c = __privateGet(this, _children)[k]; - return (typeof __privateGet(c, _varIndex) === "number" ? `(${k})@${__privateGet(c, _varIndex)}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr(); - }); - if (typeof __privateGet(this, _index) === "number") { - strList.unshift(`#${__privateGet(this, _index)}`); - } - if (strList.length === 0) { - return ""; - } - if (strList.length === 1) { - return strList[0]; - } - return "(?:" + strList.join("|") + ")"; - } -}, _index = new WeakMap(), _varIndex = new WeakMap(), _children = new WeakMap(), _a5); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/trie.js -var _context, _root, _a6; -var Trie = (_a6 = class { - constructor() { - __privateAdd(this, _context, { varIndex: 0 }); - __privateAdd(this, _root, new Node()); - } - insert(path3, index, pathErrorCheckOnly) { - const paramAssoc = []; - const groups = []; - for (let i = 0; ; ) { - let replaced = false; - path3 = path3.replace(/\{[^}]+\}/g, (m) => { - const mark = `@\\${i}`; - groups[i] = [mark, m]; - i++; - replaced = true; - return mark; - }); - if (!replaced) { - break; - } - } - const tokens = path3.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []; - for (let i = groups.length - 1; i >= 0; i--) { - const [mark] = groups[i]; - for (let j = tokens.length - 1; j >= 0; j--) { - if (tokens[j].indexOf(mark) !== -1) { - tokens[j] = tokens[j].replace(mark, groups[i][1]); - break; - } - } - } - __privateGet(this, _root).insert(tokens, index, paramAssoc, __privateGet(this, _context), pathErrorCheckOnly); - return paramAssoc; - } - buildRegExp() { - let regexp = __privateGet(this, _root).buildRegExpStr(); - if (regexp === "") { - return [/^$/, [], []]; - } - let captureIndex = 0; - const indexReplacementMap = []; - const paramReplacementMap = []; - regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => { - if (handlerIndex !== void 0) { - indexReplacementMap[++captureIndex] = Number(handlerIndex); - return "$()"; - } - if (paramIndex !== void 0) { - paramReplacementMap[Number(paramIndex)] = ++captureIndex; - return ""; - } - return ""; - }); - return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]; - } -}, _context = new WeakMap(), _root = new WeakMap(), _a6); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/router.js -var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; -var wildcardRegExpCache = /* @__PURE__ */ Object.create(null); -function buildWildcardRegExp(path3) { - return wildcardRegExpCache[path3] ?? (wildcardRegExpCache[path3] = new RegExp( - path3 === "*" ? "" : `^${path3.replace( - /\/\*$|([.\\+*[^\]$()])/g, - (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)" - )}$` - )); -} -function clearWildcardRegExpCache() { - wildcardRegExpCache = /* @__PURE__ */ Object.create(null); -} -function buildMatcherFromPreprocessedRoutes(routes) { - const trie = new Trie(); - const handlerData = []; - if (routes.length === 0) { - return nullMatcher; - } - const routesWithStaticPathFlag = routes.map( - (route) => [!/\*|\/:/.test(route[0]), ...route] - ).sort( - ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length - ); - const staticMap = /* @__PURE__ */ Object.create(null); - for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) { - const [pathErrorCheckOnly, path3, handlers] = routesWithStaticPathFlag[i]; - if (pathErrorCheckOnly) { - staticMap[path3] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam]; - } else { - j++; - } - let paramAssoc; - try { - paramAssoc = trie.insert(path3, j, pathErrorCheckOnly); - } catch (e) { - throw e === PATH_ERROR ? new UnsupportedPathError(path3) : e; - } - if (pathErrorCheckOnly) { - continue; - } - handlerData[j] = handlers.map(([h, paramCount]) => { - const paramIndexMap = /* @__PURE__ */ Object.create(null); - paramCount -= 1; - for (; paramCount >= 0; paramCount--) { - const [key, value] = paramAssoc[paramCount]; - paramIndexMap[key] = value; - } - return [h, paramIndexMap]; - }); - } - const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp(); - for (let i = 0, len = handlerData.length; i < len; i++) { - for (let j = 0, len2 = handlerData[i].length; j < len2; j++) { - const map3 = handlerData[i][j]?.[1]; - if (!map3) { - continue; - } - const keys = Object.keys(map3); - for (let k = 0, len3 = keys.length; k < len3; k++) { - map3[keys[k]] = paramReplacementMap[map3[keys[k]]]; - } - } - } - const handlerMap = []; - for (const i in indexReplacementMap) { - handlerMap[i] = handlerData[indexReplacementMap[i]]; - } - return [regexp, handlerMap, staticMap]; -} -function findMiddleware(middleware, path3) { - if (!middleware) { - return void 0; - } - for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) { - if (buildWildcardRegExp(k).test(path3)) { - return [...middleware[k]]; - } - } - return void 0; -} -var _middleware, _routes, _RegExpRouter_instances, buildMatcher_fn, _a7; -var RegExpRouter = (_a7 = class { - constructor() { - __privateAdd(this, _RegExpRouter_instances); - __publicField(this, "name", "RegExpRouter"); - __privateAdd(this, _middleware); - __privateAdd(this, _routes); - __publicField(this, "match", match); - __privateSet(this, _middleware, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }); - __privateSet(this, _routes, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }); - } - add(method, path3, handler) { - var _a30; - const middleware = __privateGet(this, _middleware); - const routes = __privateGet(this, _routes); - if (!middleware || !routes) { - throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); - } - if (!middleware[method]) { - ; - [middleware, routes].forEach((handlerMap) => { - handlerMap[method] = /* @__PURE__ */ Object.create(null); - Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => { - handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]; - }); - }); - } - if (path3 === "/*") { - path3 = "*"; - } - const paramCount = (path3.match(/\/:/g) || []).length; - if (/\*$/.test(path3)) { - const re2 = buildWildcardRegExp(path3); - if (method === METHOD_NAME_ALL) { - Object.keys(middleware).forEach((m) => { - var _a31; - (_a31 = middleware[m])[path3] || (_a31[path3] = findMiddleware(middleware[m], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || []); - }); - } else { - (_a30 = middleware[method])[path3] || (_a30[path3] = findMiddleware(middleware[method], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || []); - } - Object.keys(middleware).forEach((m) => { - if (method === METHOD_NAME_ALL || method === m) { - Object.keys(middleware[m]).forEach((p) => { - re2.test(p) && middleware[m][p].push([handler, paramCount]); - }); - } - }); - Object.keys(routes).forEach((m) => { - if (method === METHOD_NAME_ALL || method === m) { - Object.keys(routes[m]).forEach( - (p) => re2.test(p) && routes[m][p].push([handler, paramCount]) - ); - } - }); - return; - } - const paths2 = checkOptionalParameter(path3) || [path3]; - for (let i = 0, len = paths2.length; i < len; i++) { - const path22 = paths2[i]; - Object.keys(routes).forEach((m) => { - var _a31; - if (method === METHOD_NAME_ALL || method === m) { - (_a31 = routes[m])[path22] || (_a31[path22] = [ - ...findMiddleware(middleware[m], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || [] - ]); - routes[m][path22].push([handler, paramCount - len + i + 1]); - } - }); - } - } - buildAllMatchers() { - const matchers = /* @__PURE__ */ Object.create(null); - Object.keys(__privateGet(this, _routes)).concat(Object.keys(__privateGet(this, _middleware))).forEach((method) => { - matchers[method] || (matchers[method] = __privateMethod(this, _RegExpRouter_instances, buildMatcher_fn).call(this, method)); - }); - __privateSet(this, _middleware, __privateSet(this, _routes, void 0)); - clearWildcardRegExpCache(); - return matchers; - } -}, _middleware = new WeakMap(), _routes = new WeakMap(), _RegExpRouter_instances = new WeakSet(), buildMatcher_fn = function(method) { - const routes = []; - let hasOwnRoute = method === METHOD_NAME_ALL; - [__privateGet(this, _middleware), __privateGet(this, _routes)].forEach((r) => { - const ownRoute = r[method] ? Object.keys(r[method]).map((path3) => [path3, r[method][path3]]) : []; - if (ownRoute.length !== 0) { - hasOwnRoute || (hasOwnRoute = true); - routes.push(...ownRoute); - } else if (method !== METHOD_NAME_ALL) { - routes.push( - ...Object.keys(r[METHOD_NAME_ALL]).map((path3) => [path3, r[METHOD_NAME_ALL][path3]]) - ); - } - }); - if (!hasOwnRoute) { - return null; - } else { - return buildMatcherFromPreprocessedRoutes(routes); - } -}, _a7); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/smart-router/router.js -var _routers, _routes2, _a8; -var SmartRouter = (_a8 = class { - constructor(init2) { - __publicField(this, "name", "SmartRouter"); - __privateAdd(this, _routers, []); - __privateAdd(this, _routes2, []); - __privateSet(this, _routers, init2.routers); - } - add(method, path3, handler) { - if (!__privateGet(this, _routes2)) { - throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); - } - __privateGet(this, _routes2).push([method, path3, handler]); - } - match(method, path3) { - if (!__privateGet(this, _routes2)) { - throw new Error("Fatal error"); - } - const routers = __privateGet(this, _routers); - const routes = __privateGet(this, _routes2); - const len = routers.length; - let i = 0; - let res; - for (; i < len; i++) { - const router2 = routers[i]; - try { - for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) { - router2.add(...routes[i2]); - } - res = router2.match(method, path3); - } catch (e) { - if (e instanceof UnsupportedPathError) { - continue; - } - throw e; - } - this.match = router2.match.bind(router2); - __privateSet(this, _routers, [router2]); - __privateSet(this, _routes2, void 0); - break; - } - if (i === len) { - throw new Error("Fatal error"); - } - this.name = `SmartRouter + ${this.activeRouter.name}`; - return res; - } - get activeRouter() { - if (__privateGet(this, _routes2) || __privateGet(this, _routers).length !== 1) { - throw new Error("No active router has been determined yet."); - } - return __privateGet(this, _routers)[0]; - } -}, _routers = new WeakMap(), _routes2 = new WeakMap(), _a8); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/trie-router/node.js -var emptyParams = /* @__PURE__ */ Object.create(null); -var hasChildren = (children) => { - for (const _ in children) { - return true; - } - return false; -}; -var _methods, _children2, _patterns, _order, _params, __Node_instances, pushHandlerSets_fn, _a9; -var Node2 = (_a9 = class { - constructor(method, handler, children) { - __privateAdd(this, __Node_instances); - __privateAdd(this, _methods); - __privateAdd(this, _children2); - __privateAdd(this, _patterns); - __privateAdd(this, _order, 0); - __privateAdd(this, _params, emptyParams); - __privateSet(this, _children2, children || /* @__PURE__ */ Object.create(null)); - __privateSet(this, _methods, []); - if (method && handler) { - const m = /* @__PURE__ */ Object.create(null); - m[method] = { handler, possibleKeys: [], score: 0 }; - __privateSet(this, _methods, [m]); - } - __privateSet(this, _patterns, []); - } - insert(method, path3, handler) { - __privateSet(this, _order, ++__privateWrapper(this, _order)._); - let curNode = this; - const parts = splitRoutingPath(path3); - const possibleKeys = []; - for (let i = 0, len = parts.length; i < len; i++) { - const p = parts[i]; - const nextP = parts[i + 1]; - const pattern = getPattern(p, nextP); - const key = Array.isArray(pattern) ? pattern[0] : p; - if (key in __privateGet(curNode, _children2)) { - curNode = __privateGet(curNode, _children2)[key]; - if (pattern) { - possibleKeys.push(pattern[1]); - } - continue; - } - __privateGet(curNode, _children2)[key] = new _a9(); - if (pattern) { - __privateGet(curNode, _patterns).push(pattern); - possibleKeys.push(pattern[1]); - } - curNode = __privateGet(curNode, _children2)[key]; - } - __privateGet(curNode, _methods).push({ - [method]: { - handler, - possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i), - score: __privateGet(this, _order) - } - }); - return curNode; - } - search(method, path3) { - const handlerSets = []; - __privateSet(this, _params, emptyParams); - const curNode = this; - let curNodes = [curNode]; - const parts = splitPath(path3); - const curNodesQueue = []; - const len = parts.length; - let partOffsets = null; - for (let i = 0; i < len; i++) { - const part = parts[i]; - const isLast = i === len - 1; - const tempNodes = []; - for (let j = 0, len2 = curNodes.length; j < len2; j++) { - const node = curNodes[j]; - const nextNode = __privateGet(node, _children2)[part]; - if (nextNode) { - __privateSet(nextNode, _params, __privateGet(node, _params)); - if (isLast) { - if (__privateGet(nextNode, _children2)["*"]) { - __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, __privateGet(nextNode, _children2)["*"], method, __privateGet(node, _params)); - } - __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, nextNode, method, __privateGet(node, _params)); - } else { - tempNodes.push(nextNode); - } - } - for (let k = 0, len3 = __privateGet(node, _patterns).length; k < len3; k++) { - const pattern = __privateGet(node, _patterns)[k]; - const params = __privateGet(node, _params) === emptyParams ? {} : { ...__privateGet(node, _params) }; - if (pattern === "*") { - const astNode = __privateGet(node, _children2)["*"]; - if (astNode) { - __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, astNode, method, __privateGet(node, _params)); - __privateSet(astNode, _params, params); - tempNodes.push(astNode); - } - continue; - } - const [key, name, matcher] = pattern; - if (!part && !(matcher instanceof RegExp)) { - continue; - } - const child = __privateGet(node, _children2)[key]; - if (matcher instanceof RegExp) { - if (partOffsets === null) { - partOffsets = new Array(len); - let offset = path3[0] === "/" ? 1 : 0; - for (let p = 0; p < len; p++) { - partOffsets[p] = offset; - offset += parts[p].length + 1; - } - } - const restPathString = path3.substring(partOffsets[i]); - const m = matcher.exec(restPathString); - if (m) { - params[name] = m[0]; - __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, child, method, __privateGet(node, _params), params); - if (hasChildren(__privateGet(child, _children2))) { - __privateSet(child, _params, params); - const componentCount = m[0].match(/\//)?.length ?? 0; - const targetCurNodes = curNodesQueue[componentCount] || (curNodesQueue[componentCount] = []); - targetCurNodes.push(child); - } - continue; - } - } - if (matcher === true || matcher.test(part)) { - params[name] = part; - if (isLast) { - __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, child, method, params, __privateGet(node, _params)); - if (__privateGet(child, _children2)["*"]) { - __privateMethod(this, __Node_instances, pushHandlerSets_fn).call(this, handlerSets, __privateGet(child, _children2)["*"], method, params, __privateGet(node, _params)); - } - } else { - __privateSet(child, _params, params); - tempNodes.push(child); - } - } - } - } - const shifted = curNodesQueue.shift(); - curNodes = shifted ? tempNodes.concat(shifted) : tempNodes; - } - if (handlerSets.length > 1) { - handlerSets.sort((a, b) => { - return a.score - b.score; - }); - } - return [handlerSets.map(({ handler, params }) => [handler, params])]; - } -}, _methods = new WeakMap(), _children2 = new WeakMap(), _patterns = new WeakMap(), _order = new WeakMap(), _params = new WeakMap(), __Node_instances = new WeakSet(), pushHandlerSets_fn = function(handlerSets, node, method, nodeParams, params) { - for (let i = 0, len = __privateGet(node, _methods).length; i < len; i++) { - const m = __privateGet(node, _methods)[i]; - const handlerSet = m[method] || m[METHOD_NAME_ALL]; - const processedSet = {}; - if (handlerSet !== void 0) { - handlerSet.params = /* @__PURE__ */ Object.create(null); - handlerSets.push(handlerSet); - if (nodeParams !== emptyParams || params && params !== emptyParams) { - for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) { - const key = handlerSet.possibleKeys[i2]; - const processed = processedSet[handlerSet.score]; - handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key]; - processedSet[handlerSet.score] = true; - } - } - } - } -}, _a9); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/trie-router/router.js -var _node, _a10; -var TrieRouter = (_a10 = class { - constructor() { - __publicField(this, "name", "TrieRouter"); - __privateAdd(this, _node); - __privateSet(this, _node, new Node2()); - } - add(method, path3, handler) { - const results = checkOptionalParameter(path3); - if (results) { - for (let i = 0, len = results.length; i < len; i++) { - __privateGet(this, _node).insert(method, results[i], handler); - } - return; - } - __privateGet(this, _node).insert(method, path3, handler); - } - match(method, path3) { - return __privateGet(this, _node).search(method, path3); - } -}, _node = new WeakMap(), _a10); - -// ../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/hono.js -var Hono2 = class extends Hono { - /** - * Creates an instance of the Hono class. - * - * @param options - Optional configuration options for the Hono instance. - */ - constructor(options = {}) { - super(options); - this.router = options.router ?? new SmartRouter({ - routers: [new RegExpRouter(), new TrieRouter()] - }); - } -}; - -// ../../packages/adapters/hono/dist/index.mjs -function createHonoApp(options) { - const app = new Hono2(); - const prefix = options.prefix || "/api"; - const dispatcher = new HttpDispatcher(options.kernel); - const errorJson = (c, message2, code = 500) => { - return c.json({ success: false, error: { message: message2, code } }, code); - }; - const toResponse2 = (c, result) => { - if (result.handled) { - if (result.response) { - if (result.response.headers) { - Object.entries(result.response.headers).forEach(([k, v]) => c.header(k, v)); - } - return c.json(result.response.body, result.response.status); - } - if (result.result) { - const res = result.result; - if (res.type === "redirect" && res.url) { - return c.redirect(res.url); - } - if (res.type === "stream" && res.events) { - const headers = { - "Content-Type": res.contentType || "text/event-stream", - "Cache-Control": "no-cache", - "Connection": "keep-alive", - ...res.headers || {} - }; - const stream = new ReadableStream({ - async start(controller) { - try { - const encoder3 = new TextEncoder(); - for await (const event of res.events) { - const chunk = res.vercelDataStream ? typeof event === "string" ? event : JSON.stringify(event) + "\n" : `data: ${JSON.stringify(event)} - -`; - controller.enqueue(encoder3.encode(chunk)); - } - } catch (err) { - } finally { - controller.close(); - } - } - }); - return new Response(stream, { status: 200, headers }); - } - if (res.type === "stream" && res.stream) { - if (res.headers) { - Object.entries(res.headers).forEach(([k, v]) => c.header(k, v)); - } - return new Response(res.stream, { status: 200 }); - } - return c.json(res, 200); - } - } - return errorJson(c, "Not Found", 404); - }; - app.get(prefix, async (c) => { - return c.json({ data: await dispatcher.getDiscoveryInfo(prefix) }); - }); - app.get(`${prefix}/discovery`, async (c) => { - return c.json({ data: await dispatcher.getDiscoveryInfo(prefix) }); - }); - app.get("/.well-known/objectstack", (c) => { - return c.redirect(prefix); - }); - app.all(`${prefix}/auth/*`, async (c) => { - try { - const path3 = c.req.path.substring(`${prefix}/auth/`.length); - const method = c.req.method; - let authService = null; - try { - if (typeof options.kernel.getServiceAsync === "function") { - authService = await options.kernel.getServiceAsync("auth"); - } else if (typeof options.kernel.getService === "function") { - authService = options.kernel.getService("auth"); - } - } catch { - authService = null; - } - if (authService && typeof authService.handleRequest === "function") { - const response = await authService.handleRequest(c.req.raw); - return new Response(response.body, { - status: response.status, - headers: response.headers - }); - } - const body = method === "GET" || method === "HEAD" ? {} : await c.req.json().catch(() => ({})); - const result = await dispatcher.handleAuth(path3, method, body, { request: c.req.raw }); - return toResponse2(c, result); - } catch (err) { - return errorJson(c, err.message || "Internal Server Error", err.statusCode || 500); - } - }); - app.post(`${prefix}/graphql`, async (c) => { - try { - const body = await c.req.json(); - const result = await dispatcher.handleGraphQL(body, { request: c.req.raw }); - return c.json(result); - } catch (err) { - return errorJson(c, err.message || "Internal Server Error", err.statusCode || 500); - } - }); - app.all(`${prefix}/storage/*`, async (c) => { - try { - const subPath = c.req.path.substring(`${prefix}/storage`.length); - const method = c.req.method; - let file2 = void 0; - if (method === "POST" && subPath === "/upload") { - const formData = await c.req.formData(); - file2 = formData.get("file"); - } - const result = await dispatcher.handleStorage(subPath, method, file2, { request: c.req.raw }); - return toResponse2(c, result); - } catch (err) { - return errorJson(c, err.message || "Internal Server Error", err.statusCode || 500); - } - }); - app.all(`${prefix}/*`, async (c) => { - try { - const subPath = c.req.path.substring(prefix.length); - const method = c.req.method; - let body = void 0; - if (method === "POST" || method === "PUT" || method === "PATCH") { - body = await c.req.json().catch(() => ({})); - } - const queryParams = {}; - const url2 = new URL(c.req.url); - url2.searchParams.forEach((val, key) => { - queryParams[key] = val; - }); - const result = await dispatcher.dispatch(method, subPath, body, queryParams, { request: c.req.raw }, prefix); - return toResponse2(c, result); - } catch (err) { - return errorJson(c, err.message || "Internal Server Error", err.statusCode || 500); - } - }); - return app; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/wildcard.mjs -function escapeRegExpChar(char) { - if (char === "-" || char === "^" || char === "$" || char === "+" || char === "." || char === "(" || char === ")" || char === "|" || char === "[" || char === "]" || char === "{" || char === "}" || char === "*" || char === "?" || char === "\\") return `\\${char}`; - else return char; -} -function escapeRegExpString(str) { - let result = ""; - for (let i = 0; i < str.length; i++) result += escapeRegExpChar(str[i]); - return result; -} -function transform2(pattern, separator = true) { - if (Array.isArray(pattern)) return `(?:${pattern.map((p) => `^${transform2(p, separator)}$`).join("|")})`; - let separatorSplitter = ""; - let separatorMatcher = ""; - let wildcard = "."; - if (separator === true) { - separatorSplitter = "/"; - separatorMatcher = "[/\\\\]"; - wildcard = "[^/\\\\]"; - } else if (separator) { - separatorSplitter = separator; - separatorMatcher = escapeRegExpString(separatorSplitter); - if (separatorMatcher.length > 1) { - separatorMatcher = `(?:${separatorMatcher})`; - wildcard = `((?!${separatorMatcher}).)`; - } else wildcard = `[^${separatorMatcher}]`; - } - const requiredSeparator = separator ? `${separatorMatcher}+?` : ""; - const optionalSeparator = separator ? `${separatorMatcher}*?` : ""; - const segments = separator ? pattern.split(separatorSplitter) : [pattern]; - let result = ""; - for (let s = 0; s < segments.length; s++) { - const segment = segments[s]; - const nextSegment = segments[s + 1]; - let currentSeparator = ""; - if (!segment && s > 0) continue; - if (separator) if (s === segments.length - 1) currentSeparator = optionalSeparator; - else if (nextSegment !== "**") currentSeparator = requiredSeparator; - else currentSeparator = ""; - if (separator && segment === "**") { - if (currentSeparator) { - result += s === 0 ? "" : currentSeparator; - result += `(?:${wildcard}*?${currentSeparator})*?`; - } - continue; - } - for (let c = 0; c < segment.length; c++) { - const char = segment[c]; - if (char === "\\") { - if (c < segment.length - 1) { - result += escapeRegExpChar(segment[c + 1]); - c++; - } - } else if (char === "?") result += wildcard; - else if (char === "*") result += `${wildcard}*?`; - else result += escapeRegExpChar(char); - } - result += currentSeparator; - } - return result; -} -function isMatch(regexp, sample) { - if (typeof sample !== "string") throw new TypeError(`Sample must be a string, but ${typeof sample} given`); - return regexp.test(sample); -} -function wildcardMatch(pattern, options) { - if (typeof pattern !== "string" && !Array.isArray(pattern)) throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`); - if (typeof options === "string" || typeof options === "boolean") options = { separator: options }; - if (arguments.length === 2 && !(typeof options === "undefined" || typeof options === "object" && options !== null && !Array.isArray(options))) throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof options} given`); - options = options || {}; - if (options.separator === "\\") throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead"); - const regexpPattern = transform2(pattern, options.separator); - const regexp = new RegExp(`^${regexpPattern}$`, options.flags); - const fn = isMatch.bind(null, regexp); - fn.options = options; - fn.pattern = pattern; - fn.regexp = regexp; - return fn; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/url.mjs -init_env(); -init_error2(); -function checkHasPath(url2) { - try { - return (new URL(url2).pathname.replace(/\/+$/, "") || "/") !== "/"; - } catch { - throw new BetterAuthError(`Invalid base URL: ${url2}. Please provide a valid base URL.`); - } -} -function assertHasProtocol(url2) { - try { - const parsedUrl = new URL(url2); - if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") throw new BetterAuthError(`Invalid base URL: ${url2}. URL must include 'http://' or 'https://'`); - } catch (error49) { - if (error49 instanceof BetterAuthError) throw error49; - throw new BetterAuthError(`Invalid base URL: ${url2}. Please provide a valid base URL.`, { cause: error49 }); - } -} -function withPath(url2, path3 = "/api/auth") { - assertHasProtocol(url2); - if (checkHasPath(url2)) return url2; - const trimmedUrl = url2.replace(/\/+$/, ""); - if (!path3 || path3 === "/") return trimmedUrl; - path3 = path3.startsWith("/") ? path3 : `/${path3}`; - return `${trimmedUrl}${path3}`; -} -function validateProxyHeader(header, type) { - if (!header || header.trim() === "") return false; - if (type === "proto") return header === "http" || header === "https"; - if (type === "host") { - if ([ - /\.\./, - /\0/, - /[\s]/, - /^[.]/, - /[<>'"]/, - /javascript:/i, - /file:/i, - /data:/i - ].some((pattern) => pattern.test(header))) return false; - return /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(header) || /^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header); - } - return false; -} -function getBaseURL(url2, path3, request, loadEnv, trustedProxyHeaders) { - if (url2) return withPath(url2, path3); - if (loadEnv !== false) { - const fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== "/" ? env.BASE_URL : void 0); - if (fromEnv) return withPath(fromEnv, path3); - } - const fromRequest = request?.headers.get("x-forwarded-host"); - const fromRequestProto = request?.headers.get("x-forwarded-proto"); - if (fromRequest && fromRequestProto && trustedProxyHeaders) { - if (validateProxyHeader(fromRequestProto, "proto") && validateProxyHeader(fromRequest, "host")) try { - return withPath(`${fromRequestProto}://${fromRequest}`, path3); - } catch (_error) { - } - } - if (request) { - const url3 = getOrigin(request.url); - if (!url3) throw new BetterAuthError("Could not get origin from request. Please provide a valid base URL."); - return withPath(url3, path3); - } - if (typeof window !== "undefined" && window.location) return withPath(window.location.origin, path3); -} -function getOrigin(url2) { - try { - const parsedUrl = new URL(url2); - return parsedUrl.origin === "null" ? null : parsedUrl.origin; - } catch { - return null; - } -} -function getProtocol(url2) { - try { - return new URL(url2).protocol; - } catch { - return null; - } -} -function getHost(url2) { - try { - return new URL(url2).host; - } catch { - return null; - } -} -function isDynamicBaseURLConfig(config4) { - return typeof config4 === "object" && config4 !== null && "allowedHosts" in config4 && Array.isArray(config4.allowedHosts); -} -function getHostFromRequest(request) { - const forwardedHost = request.headers.get("x-forwarded-host"); - if (forwardedHost && validateProxyHeader(forwardedHost, "host")) return forwardedHost; - const host = request.headers.get("host"); - if (host && validateProxyHeader(host, "host")) return host; - try { - return new URL(request.url).host; - } catch { - return null; - } -} -function getProtocolFromRequest(request, configProtocol) { - if (configProtocol === "http" || configProtocol === "https") return configProtocol; - const forwardedProto = request.headers.get("x-forwarded-proto"); - if (forwardedProto && validateProxyHeader(forwardedProto, "proto")) return forwardedProto; - try { - const url2 = new URL(request.url); - if (url2.protocol === "http:" || url2.protocol === "https:") return url2.protocol.slice(0, -1); - } catch { - } - return "https"; -} -var matchesHostPattern = (host, pattern) => { - if (!host || !pattern) return false; - const normalizedHost = host.replace(/^https?:\/\//, "").split("/")[0].toLowerCase(); - const normalizedPattern = pattern.replace(/^https?:\/\//, "").split("/")[0].toLowerCase(); - if (normalizedPattern.includes("*") || normalizedPattern.includes("?")) return wildcardMatch(normalizedPattern)(normalizedHost); - return normalizedHost.toLowerCase() === normalizedPattern.toLowerCase(); -}; -function resolveDynamicBaseURL(config4, request, basePath) { - const host = getHostFromRequest(request); - if (!host) { - if (config4.fallback) return withPath(config4.fallback, basePath); - throw new BetterAuthError("Could not determine host from request headers. Please provide a fallback URL in your baseURL config."); - } - if (config4.allowedHosts.some((pattern) => matchesHostPattern(host, pattern))) return withPath(`${getProtocolFromRequest(request, config4.protocol)}://${host}`, basePath); - if (config4.fallback) return withPath(config4.fallback, basePath); - throw new BetterAuthError(`Host "${host}" is not in the allowed hosts list. Allowed hosts: ${config4.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`); -} -function resolveBaseURL(config4, basePath, request, loadEnv, trustedProxyHeaders) { - if (isDynamicBaseURLConfig(config4)) { - if (request) return resolveDynamicBaseURL(config4, request, basePath); - if (config4.fallback) return withPath(config4.fallback, basePath); - return getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders); - } - if (typeof config4 === "string") return getBaseURL(config4, basePath, request, loadEnv, trustedProxyHeaders); - return getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/random.mjs -init_random(); -var generateRandomString = createRandomStringGenerator("a-z", "0-9", "A-Z", "-_"); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/buffer.mjs -function constantTimeEqual(a, b) { - if (typeof a === "string") a = new TextEncoder().encode(a); - if (typeof b === "string") b = new TextEncoder().encode(b); - const aBuffer = new Uint8Array(a); - const bBuffer = new Uint8Array(b); - let c = aBuffer.length ^ bBuffer.length; - const length = Math.max(aBuffer.length, bBuffer.length); - for (let i = 0; i < length; i++) c |= (i < aBuffer.length ? aBuffer[i] : 0) ^ (i < bBuffer.length ? bBuffer[i] : 0); - return c === 0; -} - -// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js -function isBytes(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; -} -function anumber(n, title = "") { - if (typeof n !== "number") { - const prefix = title && `"${title}" `; - throw new TypeError(`${prefix}expected number, got ${typeof n}`); - } - if (!Number.isSafeInteger(n) || n < 0) { - const prefix = title && `"${title}" `; - throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); - } -} -function abytes(value, length, title = "") { - const bytes = isBytes(value); - const len = value?.length; - const needsLen = length !== void 0; - if (!bytes || needsLen && len !== length) { - const prefix = title && `"${title}" `; - const ofLen = needsLen ? ` of length ${length}` : ""; - const got = bytes ? `length=${len}` : `type=${typeof value}`; - const message2 = prefix + "expected Uint8Array" + ofLen + ", got " + got; - if (!bytes) - throw new TypeError(message2); - throw new RangeError(message2); - } - return value; -} -function ahash(h) { - if (typeof h !== "function" || typeof h.create !== "function") - throw new TypeError("Hash must wrapped by utils.createHasher"); - anumber(h.outputLen); - anumber(h.blockLen); - if (h.outputLen < 1) - throw new Error('"outputLen" must be >= 1'); - if (h.blockLen < 1) - throw new Error('"blockLen" must be >= 1'); -} -function aexists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function aoutput(out, instance) { - abytes(out, void 0, "digestInto() output"); - const min = instance.outputLen; - if (out.length < min) { - throw new RangeError('"digestInto() output" expected to be of length >=' + min); - } -} -function clean(...arrays) { - for (let i = 0; i < arrays.length; i++) { - arrays[i].fill(0); - } -} -function createView(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -} -function rotr(word, shift) { - return word << 32 - shift | word >>> shift; -} -function createHasher(hashCons, info2 = {}) { - const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); - const tmp = hashCons(void 0); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.canXOF = tmp.canXOF; - hashC.create = (opts) => hashCons(opts); - Object.assign(hashC, info2); - return Object.freeze(hashC); -} -var oidNist = (suffix) => ({ - // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. - // Larger suffix values would need base-128 OID encoding and a different length byte. - oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) -}); - -// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js -var _HMAC = class { - constructor(hash2, key) { - __publicField(this, "oHash"); - __publicField(this, "iHash"); - __publicField(this, "blockLen"); - __publicField(this, "outputLen"); - __publicField(this, "canXOF", false); - __publicField(this, "finished", false); - __publicField(this, "destroyed", false); - ahash(hash2); - abytes(key, void 0, "key"); - this.iHash = hash2.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54; - this.iHash.update(pad); - this.oHash = hash2.create(); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54 ^ 92; - this.oHash.update(pad); - clean(pad); - } - update(buf) { - aexists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const buf = out.subarray(0, this.outputLen); - this.iHash.digestInto(buf); - this.oHash.update(buf); - this.oHash.digestInto(buf); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - clone() { - return this._cloneInto(); - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } -}; -var hmac = /* @__PURE__ */ (() => { - const hmac_ = (hash2, key, message2) => new _HMAC(hash2, key).update(message2).digest(); - hmac_.create = (hash2, key) => new _HMAC(hash2, key); - return hmac_; -})(); - -// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hkdf.js -function extract(hash2, ikm, salt) { - ahash(hash2); - if (salt === void 0) - salt = new Uint8Array(hash2.outputLen); - return hmac(hash2, salt, ikm); -} -var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); -var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); -function expand(hash2, prk, info2, length = 32) { - ahash(hash2); - anumber(length, "length"); - abytes(prk, void 0, "prk"); - const olen = hash2.outputLen; - if (prk.length < olen) - throw new Error('"prk" must be at least HashLen octets'); - if (length > 255 * olen) - throw new Error("Length must be <= 255*HashLen"); - const blocks = Math.ceil(length / olen); - if (info2 === void 0) - info2 = EMPTY_BUFFER; - else - abytes(info2, void 0, "info"); - const okm = new Uint8Array(blocks * olen); - const HMAC = hmac.create(hash2, prk); - const HMACTmp = HMAC._cloneInto(); - const T = new Uint8Array(HMAC.outputLen); - for (let counter = 0; counter < blocks; counter++) { - HKDF_COUNTER[0] = counter + 1; - HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info2).update(HKDF_COUNTER).digestInto(T); - okm.set(T, olen * counter); - HMAC._cloneInto(HMACTmp); - } - HMAC.destroy(); - HMACTmp.destroy(); - clean(T, HKDF_COUNTER); - return okm.slice(0, length); -} -var hkdf = (hash2, ikm, salt, info2, length) => expand(hash2, extract(hash2, ikm, salt), info2, length); - -// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js -function Chi(a, b, c) { - return a & b ^ ~a & c; -} -function Maj(a, b, c) { - return a & b ^ a & c ^ b & c; -} -var HashMD = class { - constructor(blockLen, outputLen, padOffset, isLE2) { - __publicField(this, "blockLen"); - __publicField(this, "outputLen"); - __publicField(this, "canXOF", false); - __publicField(this, "padOffset"); - __publicField(this, "isLE"); - // For partial updates less than block size - __publicField(this, "buffer"); - __publicField(this, "view"); - __publicField(this, "finished", false); - __publicField(this, "length", 0); - __publicField(this, "pos", 0); - __publicField(this, "destroyed", false); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE2; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - aexists(this); - abytes(data); - const { view, buffer, blockLen } = this; - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE: isLE2 } = this; - let { pos } = this; - buffer[pos++] = 128; - clean(this.buffer.subarray(pos)); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen must be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE2); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.destroyed = destroyed; - to.finished = finished; - to.length = length; - to.pos = pos; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - clone() { - return this._cloneInto(); - } -}; -var SHA256_IV = /* @__PURE__ */ Uint32Array.from([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); - -// ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js -var SHA256_K = /* @__PURE__ */ Uint32Array.from([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]); -var SHA256_W = /* @__PURE__ */ new Uint32Array(64); -var SHA2_32B = class extends HashMD { - constructor(outputLen) { - super(64, outputLen, 8, false); - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - // prettier-ignore - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - clean(SHA256_W); - } - destroy() { - this.destroyed = true; - this.set(0, 0, 0, 0, 0, 0, 0, 0); - clean(this.buffer); - } -}; -var _SHA256 = class extends SHA2_32B { - constructor() { - super(32); - // We cannot use array here since array allows indexing by variable - // which means optimizer/compiler cannot use registers. - __publicField(this, "A", SHA256_IV[0] | 0); - __publicField(this, "B", SHA256_IV[1] | 0); - __publicField(this, "C", SHA256_IV[2] | 0); - __publicField(this, "D", SHA256_IV[3] | 0); - __publicField(this, "E", SHA256_IV[4] | 0); - __publicField(this, "F", SHA256_IV[5] | 0); - __publicField(this, "G", SHA256_IV[6] | 0); - __publicField(this, "H", SHA256_IV[7] | 0); - } -}; -var sha256 = /* @__PURE__ */ createHasher( - () => new _SHA256(), - /* @__PURE__ */ oidNist(1) -); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js -var base64url_exports = {}; -__export(base64url_exports, { - decode: () => decode3, - encode: () => encode4 -}); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js -var encoder = new TextEncoder(); -var decoder = new TextDecoder(); -var MAX_INT32 = 2 ** 32; -function concat(...buffers) { - const size = buffers.reduce((acc, { length }) => acc + length, 0); - const buf = new Uint8Array(size); - let i = 0; - for (const buffer of buffers) { - buf.set(buffer, i); - i += buffer.length; - } - return buf; -} -function writeUInt32BE(buf, value, offset) { - if (value < 0 || value >= MAX_INT32) { - throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); - } - buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); -} -function uint64be(value) { - const high = Math.floor(value / MAX_INT32); - const low = value % MAX_INT32; - const buf = new Uint8Array(8); - writeUInt32BE(buf, high, 0); - writeUInt32BE(buf, low, 4); - return buf; -} -function uint32be(value) { - const buf = new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -function encode3(string4) { - const bytes = new Uint8Array(string4.length); - for (let i = 0; i < string4.length; i++) { - const code = string4.charCodeAt(i); - if (code > 127) { - throw new TypeError("non-ASCII string encountered in encode()"); - } - bytes[i] = code; - } - return bytes; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js -function encodeBase64(input) { - if (Uint8Array.prototype.toBase64) { - return input.toBase64(); - } - const CHUNK_SIZE2 = 32768; - const arr = []; - for (let i = 0; i < input.length; i += CHUNK_SIZE2) { - arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE2))); - } - return btoa(arr.join("")); -} -function decodeBase64(encoded) { - if (Uint8Array.fromBase64) { - return Uint8Array.fromBase64(encoded); - } - const binary2 = atob(encoded); - const bytes = new Uint8Array(binary2.length); - for (let i = 0; i < binary2.length; i++) { - bytes[i] = binary2.charCodeAt(i); - } - return bytes; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js -function decode3(input) { - if (Uint8Array.fromBase64) { - return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { - alphabet: "base64url" - }); - } - let encoded = input; - if (encoded instanceof Uint8Array) { - encoded = decoder.decode(encoded); - } - encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); - try { - return decodeBase64(encoded); - } catch { - throw new TypeError("The input to be decoded is not correctly encoded."); - } -} -function encode4(input) { - let unencoded = input; - if (typeof unencoded === "string") { - unencoded = encoder.encode(unencoded); - } - if (Uint8Array.prototype.toBase64) { - return unencoded.toBase64({ alphabet: "base64url", omitPadding: true }); - } - return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js -var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); -var isAlgorithm = (algorithm2, name) => algorithm2.name === name; -function getHashLength(hash2) { - return parseInt(hash2.name.slice(4), 10); -} -function checkHashLength(algorithm2, expected) { - const actual = getHashLength(algorithm2.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); -} -function getNamedCurve(alg2) { - switch (alg2) { - case "ES256": - return "P-256"; - case "ES384": - return "P-384"; - case "ES512": - return "P-521"; - default: - throw new Error("unreachable"); - } -} -function checkUsage(key, usage) { - if (usage && !key.usages.includes(usage)) { - throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); - } -} -function checkSigCryptoKey(key, alg2, usage) { - switch (alg2) { - case "HS256": - case "HS384": - case "HS512": { - if (!isAlgorithm(key.algorithm, "HMAC")) - throw unusable("HMAC"); - checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); - break; - } - case "RS256": - case "RS384": - case "RS512": { - if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) - throw unusable("RSASSA-PKCS1-v1_5"); - checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); - break; - } - case "PS256": - case "PS384": - case "PS512": { - if (!isAlgorithm(key.algorithm, "RSA-PSS")) - throw unusable("RSA-PSS"); - checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); - break; - } - case "Ed25519": - case "EdDSA": { - if (!isAlgorithm(key.algorithm, "Ed25519")) - throw unusable("Ed25519"); - break; - } - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": { - if (!isAlgorithm(key.algorithm, alg2)) - throw unusable(alg2); - break; - } - case "ES256": - case "ES384": - case "ES512": { - if (!isAlgorithm(key.algorithm, "ECDSA")) - throw unusable("ECDSA"); - const expected = getNamedCurve(alg2); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, "algorithm.namedCurve"); - break; - } - default: - throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -function checkEncCryptoKey(key, alg2, usage) { - switch (alg2) { - case "A128GCM": - case "A192GCM": - case "A256GCM": { - if (!isAlgorithm(key.algorithm, "AES-GCM")) - throw unusable("AES-GCM"); - const expected = parseInt(alg2.slice(1, 4), 10); - const actual = key.algorithm.length; - if (actual !== expected) - throw unusable(expected, "algorithm.length"); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - if (!isAlgorithm(key.algorithm, "AES-KW")) - throw unusable("AES-KW"); - const expected = parseInt(alg2.slice(1, 4), 10); - const actual = key.algorithm.length; - if (actual !== expected) - throw unusable(expected, "algorithm.length"); - break; - } - case "ECDH": { - switch (key.algorithm.name) { - case "ECDH": - case "X25519": - break; - default: - throw unusable("ECDH or X25519"); - } - break; - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": - if (!isAlgorithm(key.algorithm, "PBKDF2")) - throw unusable("PBKDF2"); - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - if (!isAlgorithm(key.algorithm, "RSA-OAEP")) - throw unusable("RSA-OAEP"); - checkHashLength(key.algorithm, parseInt(alg2.slice(9), 10) || 1); - break; - } - default: - throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js -function message(msg, actual, ...types) { - types = types.filter(Boolean); - if (types.length > 2) { - const last = types.pop(); - msg += `one of type ${types.join(", ")}, or ${last}.`; - } else if (types.length === 2) { - msg += `one of type ${types[0]} or ${types[1]}.`; - } else { - msg += `of type ${types[0]}.`; - } - if (actual == null) { - msg += ` Received ${actual}`; - } else if (typeof actual === "function" && actual.name) { - msg += ` Received function ${actual.name}`; - } else if (typeof actual === "object" && actual != null) { - if (actual.constructor?.name) { - msg += ` Received an instance of ${actual.constructor.name}`; - } - } - return msg; -} -var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types); -var withAlg = (alg2, actual, ...types) => message(`Key for the ${alg2} algorithm must be `, actual, ...types); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js -var JOSEError = class extends Error { - constructor(message2, options) { - super(message2, options); - __publicField(this, "code", "ERR_JOSE_GENERIC"); - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } -}; -__publicField(JOSEError, "code", "ERR_JOSE_GENERIC"); -var JWTClaimValidationFailed = class extends JOSEError { - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }); - __publicField(this, "code", "ERR_JWT_CLAIM_VALIDATION_FAILED"); - __publicField(this, "claim"); - __publicField(this, "reason"); - __publicField(this, "payload"); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -}; -__publicField(JWTClaimValidationFailed, "code", "ERR_JWT_CLAIM_VALIDATION_FAILED"); -var JWTExpired = class extends JOSEError { - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }); - __publicField(this, "code", "ERR_JWT_EXPIRED"); - __publicField(this, "claim"); - __publicField(this, "reason"); - __publicField(this, "payload"); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -}; -__publicField(JWTExpired, "code", "ERR_JWT_EXPIRED"); -var JOSEAlgNotAllowed = class extends JOSEError { - constructor() { - super(...arguments); - __publicField(this, "code", "ERR_JOSE_ALG_NOT_ALLOWED"); - } -}; -__publicField(JOSEAlgNotAllowed, "code", "ERR_JOSE_ALG_NOT_ALLOWED"); -var JOSENotSupported = class extends JOSEError { - constructor() { - super(...arguments); - __publicField(this, "code", "ERR_JOSE_NOT_SUPPORTED"); - } -}; -__publicField(JOSENotSupported, "code", "ERR_JOSE_NOT_SUPPORTED"); -var JWEDecryptionFailed = class extends JOSEError { - constructor(message2 = "decryption operation failed", options) { - super(message2, options); - __publicField(this, "code", "ERR_JWE_DECRYPTION_FAILED"); - } -}; -__publicField(JWEDecryptionFailed, "code", "ERR_JWE_DECRYPTION_FAILED"); -var JWEInvalid = class extends JOSEError { - constructor() { - super(...arguments); - __publicField(this, "code", "ERR_JWE_INVALID"); - } -}; -__publicField(JWEInvalid, "code", "ERR_JWE_INVALID"); -var JWSInvalid = class extends JOSEError { - constructor() { - super(...arguments); - __publicField(this, "code", "ERR_JWS_INVALID"); - } -}; -__publicField(JWSInvalid, "code", "ERR_JWS_INVALID"); -var JWTInvalid = class extends JOSEError { - constructor() { - super(...arguments); - __publicField(this, "code", "ERR_JWT_INVALID"); - } -}; -__publicField(JWTInvalid, "code", "ERR_JWT_INVALID"); -var JWKInvalid = class extends JOSEError { - constructor() { - super(...arguments); - __publicField(this, "code", "ERR_JWK_INVALID"); - } -}; -__publicField(JWKInvalid, "code", "ERR_JWK_INVALID"); -var JWKSInvalid = class extends JOSEError { - constructor() { - super(...arguments); - __publicField(this, "code", "ERR_JWKS_INVALID"); - } -}; -__publicField(JWKSInvalid, "code", "ERR_JWKS_INVALID"); -var JWKSNoMatchingKey = class extends JOSEError { - constructor(message2 = "no applicable key found in the JSON Web Key Set", options) { - super(message2, options); - __publicField(this, "code", "ERR_JWKS_NO_MATCHING_KEY"); - } -}; -__publicField(JWKSNoMatchingKey, "code", "ERR_JWKS_NO_MATCHING_KEY"); -var _a11, _b; -var JWKSMultipleMatchingKeys = class extends (_b = JOSEError, _a11 = Symbol.asyncIterator, _b) { - constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) { - super(message2, options); - __publicField(this, _a11); - __publicField(this, "code", "ERR_JWKS_MULTIPLE_MATCHING_KEYS"); - } -}; -__publicField(JWKSMultipleMatchingKeys, "code", "ERR_JWKS_MULTIPLE_MATCHING_KEYS"); -var JWKSTimeout = class extends JOSEError { - constructor(message2 = "request timed out", options) { - super(message2, options); - __publicField(this, "code", "ERR_JWKS_TIMEOUT"); - } -}; -__publicField(JWKSTimeout, "code", "ERR_JWKS_TIMEOUT"); -var JWSSignatureVerificationFailed = class extends JOSEError { - constructor(message2 = "signature verification failed", options) { - super(message2, options); - __publicField(this, "code", "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"); - } -}; -__publicField(JWSSignatureVerificationFailed, "code", "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js -function assertCryptoKey(key) { - if (!isCryptoKey(key)) { - throw new Error("CryptoKey instance expected"); - } -} -var isCryptoKey = (key) => { - if (key?.[Symbol.toStringTag] === "CryptoKey") - return true; - try { - return key instanceof CryptoKey; - } catch { - return false; - } -}; -var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; -var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js -function cekLength(alg2) { - switch (alg2) { - case "A128GCM": - return 128; - case "A192GCM": - return 192; - case "A256GCM": - case "A128CBC-HS256": - return 256; - case "A192CBC-HS384": - return 384; - case "A256CBC-HS512": - return 512; - default: - throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg2}`); - } -} -var generateCek = (alg2) => crypto.getRandomValues(new Uint8Array(cekLength(alg2) >> 3)); -function checkCekLength(cek, expected) { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } -} -function ivBitLength(alg2) { - switch (alg2) { - case "A128GCM": - case "A128GCMKW": - case "A192GCM": - case "A192GCMKW": - case "A256GCM": - case "A256GCMKW": - return 96; - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - return 128; - default: - throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg2}`); - } -} -var generateIv = (alg2) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg2) >> 3)); -function checkIvLength(enc2, iv) { - if (iv.length << 3 !== ivBitLength(enc2)) { - throw new JWEInvalid("Invalid Initialization Vector length"); - } -} -async function cbcKeySetup(enc2, cek, usage) { - if (!(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "Uint8Array")); - } - const keySize = parseInt(enc2.slice(1, 4), 10); - const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]); - const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { - hash: `SHA-${keySize << 1}`, - name: "HMAC" - }, false, ["sign"]); - return { encKey, macKey, keySize }; -} -async function cbcHmacTag(macKey, macData, keySize) { - return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); -} -async function cbcEncrypt(enc2, plaintext, cek, iv, aad) { - const { encKey, macKey, keySize } = await cbcKeySetup(enc2, cek, "encrypt"); - const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ - iv, - name: "AES-CBC" - }, encKey, plaintext)); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const tag2 = await cbcHmacTag(macKey, macData, keySize); - return { ciphertext, tag: tag2, iv }; -} -async function timingSafeEqual(a, b) { - if (!(a instanceof Uint8Array)) { - throw new TypeError("First argument must be a buffer"); - } - if (!(b instanceof Uint8Array)) { - throw new TypeError("Second argument must be a buffer"); - } - const algorithm2 = { name: "HMAC", hash: "SHA-256" }; - const key = await crypto.subtle.generateKey(algorithm2, false, ["sign"]); - const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm2, key, a)); - const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm2, key, b)); - let out = 0; - let i = -1; - while (++i < 32) { - out |= aHmac[i] ^ bHmac[i]; - } - return out === 0; -} -async function cbcDecrypt(enc2, cek, ciphertext, iv, tag2, aad) { - const { encKey, macKey, keySize } = await cbcKeySetup(enc2, cek, "decrypt"); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const expectedTag = await cbcHmacTag(macKey, macData, keySize); - let macCheckPassed; - try { - macCheckPassed = await timingSafeEqual(tag2, expectedTag); - } catch { - } - if (!macCheckPassed) { - throw new JWEDecryptionFailed(); - } - let plaintext; - try { - plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); - } catch { - } - if (!plaintext) { - throw new JWEDecryptionFailed(); - } - return plaintext; -} -async function gcmEncrypt(enc2, plaintext, cek, iv, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); - } else { - checkEncCryptoKey(cek, enc2, "encrypt"); - encKey = cek; - } - const encrypted = new Uint8Array(await crypto.subtle.encrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, plaintext)); - const tag2 = encrypted.slice(-16); - const ciphertext = encrypted.slice(0, -16); - return { ciphertext, tag: tag2, iv }; -} -async function gcmDecrypt(enc2, cek, ciphertext, iv, tag2, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); - } else { - checkEncCryptoKey(cek, enc2, "decrypt"); - encKey = cek; - } - try { - return new Uint8Array(await crypto.subtle.decrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, concat(ciphertext, tag2))); - } catch { - throw new JWEDecryptionFailed(); - } -} -var unsupportedEnc = "Unsupported JWE Content Encryption Algorithm"; -async function encrypt(enc2, plaintext, cek, iv, aad) { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); - } - if (iv) { - checkIvLength(enc2, iv); - } else { - iv = generateIv(enc2); - } - switch (enc2) { - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc2.slice(-3), 10)); - } - return cbcEncrypt(enc2, plaintext, cek, iv, aad); - case "A128GCM": - case "A192GCM": - case "A256GCM": - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc2.slice(1, 4), 10)); - } - return gcmEncrypt(enc2, plaintext, cek, iv, aad); - default: - throw new JOSENotSupported(unsupportedEnc); - } -} -async function decrypt(enc2, cek, ciphertext, iv, tag2, aad) { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); - } - if (!iv) { - throw new JWEInvalid("JWE Initialization Vector missing"); - } - if (!tag2) { - throw new JWEInvalid("JWE Authentication Tag missing"); - } - checkIvLength(enc2, iv); - switch (enc2) { - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - if (cek instanceof Uint8Array) - checkCekLength(cek, parseInt(enc2.slice(-3), 10)); - return cbcDecrypt(enc2, cek, ciphertext, iv, tag2, aad); - case "A128GCM": - case "A192GCM": - case "A256GCM": - if (cek instanceof Uint8Array) - checkCekLength(cek, parseInt(enc2.slice(1, 4), 10)); - return gcmDecrypt(enc2, cek, ciphertext, iv, tag2, aad); - default: - throw new JOSENotSupported(unsupportedEnc); - } -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js -var unprotected = Symbol(); -function assertNotSet(value, name) { - if (value) { - throw new TypeError(`${name} can only be called once`); - } -} -function decodeBase64url(value, label, ErrorClass) { - try { - return decode3(value); - } catch { - throw new ErrorClass(`Failed to base64url decode the ${label}`); - } -} -async function digest(algorithm2, data) { - const subtleDigest = `SHA-${algorithm2.slice(-3)}`; - return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js -var isObjectLike2 = (value) => typeof value === "object" && value !== null; -function isObject3(input) { - if (!isObjectLike2(input) || Object.prototype.toString.call(input) !== "[object Object]") { - return false; - } - if (Object.getPrototypeOf(input) === null) { - return true; - } - let proto = input; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(input) === proto; -} -function isDisjoint(...headers) { - const sources = headers.filter(Boolean); - if (sources.length === 0 || sources.length === 1) { - return true; - } - let acc; - for (const header of sources) { - const parameters = Object.keys(header); - if (!acc || acc.size === 0) { - acc = new Set(parameters); - continue; - } - for (const parameter of parameters) { - if (acc.has(parameter)) { - return false; - } - acc.add(parameter); - } - } - return true; -} -var isJWK = (key) => isObject3(key) && typeof key.kty === "string"; -var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); -var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; -var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js -function checkKeySize(key, alg2) { - if (key.algorithm.length !== parseInt(alg2.slice(1, 4), 10)) { - throw new TypeError(`Invalid key size for alg: ${alg2}`); - } -} -function getCryptoKey(key, alg2, usage) { - if (key instanceof Uint8Array) { - return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]); - } - checkEncCryptoKey(key, alg2, usage); - return key; -} -async function wrap(alg2, key, cek) { - const cryptoKey = await getCryptoKey(key, alg2, "wrapKey"); - checkKeySize(cryptoKey, alg2); - const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); - return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); -} -async function unwrap(alg2, key, encryptedKey) { - const cryptoKey = await getCryptoKey(key, alg2, "unwrapKey"); - checkKeySize(cryptoKey, alg2); - const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); - return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek)); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js -function lengthAndInput(input) { - return concat(uint32be(input.length), input); -} -async function concatKdf(Z, L, OtherInfo) { - const dkLen = L >> 3; - const hashLen = 32; - const reps = Math.ceil(dkLen / hashLen); - const dk = new Uint8Array(reps * hashLen); - for (let i = 1; i <= reps; i++) { - const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length); - hashInput.set(uint32be(i), 0); - hashInput.set(Z, 4); - hashInput.set(OtherInfo, 4 + Z.length); - const hashResult = await digest("sha256", hashInput); - dk.set(hashResult, (i - 1) * hashLen); - } - return dk.slice(0, dkLen); -} -async function deriveKey(publicKey, privateKey, algorithm2, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) { - checkEncCryptoKey(publicKey, "ECDH"); - checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); - const algorithmID = lengthAndInput(encode3(algorithm2)); - const partyUInfo = lengthAndInput(apu); - const partyVInfo = lengthAndInput(apv); - const suppPubInfo = uint32be(keyLength); - const suppPrivInfo = new Uint8Array(); - const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); - const Z = new Uint8Array(await crypto.subtle.deriveBits({ - name: publicKey.algorithm.name, - public: publicKey - }, privateKey, getEcdhBitLength(publicKey))); - return concatKdf(Z, keyLength, otherInfo); -} -function getEcdhBitLength(publicKey) { - if (publicKey.algorithm.name === "X25519") { - return 256; - } - return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3; -} -function allowed(key) { - switch (key.algorithm.namedCurve) { - case "P-256": - case "P-384": - case "P-521": - return true; - default: - return key.algorithm.name === "X25519"; - } -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js -function getCryptoKey2(key, alg2) { - if (key instanceof Uint8Array) { - return crypto.subtle.importKey("raw", key, "PBKDF2", false, [ - "deriveBits" - ]); - } - checkEncCryptoKey(key, alg2, "deriveBits"); - return key; -} -var concatSalt = (alg2, p2sInput) => concat(encode3(alg2), Uint8Array.of(0), p2sInput); -async function deriveKey2(p2s, alg2, p2c, key) { - if (!(p2s instanceof Uint8Array) || p2s.length < 8) { - throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); - } - const salt = concatSalt(alg2, p2s); - const keylen = parseInt(alg2.slice(13, 16), 10); - const subtleAlg = { - hash: `SHA-${alg2.slice(8, 11)}`, - iterations: p2c, - name: "PBKDF2", - salt - }; - const cryptoKey = await getCryptoKey2(key, alg2); - return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); -} -async function wrap2(alg2, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) { - const derived = await deriveKey2(p2s, alg2, p2c, key); - const encryptedKey = await wrap(alg2.slice(-6), derived, cek); - return { encryptedKey, p2c, p2s: encode4(p2s) }; -} -async function unwrap2(alg2, key, encryptedKey, p2c, p2s) { - const derived = await deriveKey2(p2s, alg2, p2c, key); - return unwrap(alg2.slice(-6), derived, encryptedKey); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js -function checkKeyLength(alg2, key) { - if (alg2.startsWith("RS") || alg2.startsWith("PS")) { - const { modulusLength } = key.algorithm; - if (typeof modulusLength !== "number" || modulusLength < 2048) { - throw new TypeError(`${alg2} requires key modulusLength to be 2048 bits or larger`); - } - } -} -function subtleAlgorithm(alg2, algorithm2) { - const hash2 = `SHA-${alg2.slice(-3)}`; - switch (alg2) { - case "HS256": - case "HS384": - case "HS512": - return { hash: hash2, name: "HMAC" }; - case "PS256": - case "PS384": - case "PS512": - return { hash: hash2, name: "RSA-PSS", saltLength: parseInt(alg2.slice(-3), 10) >> 3 }; - case "RS256": - case "RS384": - case "RS512": - return { hash: hash2, name: "RSASSA-PKCS1-v1_5" }; - case "ES256": - case "ES384": - case "ES512": - return { hash: hash2, name: "ECDSA", namedCurve: algorithm2.namedCurve }; - case "Ed25519": - case "EdDSA": - return { name: "Ed25519" }; - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - return { name: alg2 }; - default: - throw new JOSENotSupported(`alg ${alg2} is not supported either by JOSE or your javascript runtime`); - } -} -async function getSigKey(alg2, key, usage) { - if (key instanceof Uint8Array) { - if (!alg2.startsWith("HS")) { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg2.slice(-3)}`, name: "HMAC" }, false, [usage]); - } - checkSigCryptoKey(key, alg2, usage); - return key; -} -async function sign(alg2, key, data) { - const cryptoKey = await getSigKey(alg2, key, "sign"); - checkKeyLength(alg2, cryptoKey); - const signature = await crypto.subtle.sign(subtleAlgorithm(alg2, cryptoKey.algorithm), cryptoKey, data); - return new Uint8Array(signature); -} -async function verify(alg2, key, signature, data) { - const cryptoKey = await getSigKey(alg2, key, "verify"); - checkKeyLength(alg2, cryptoKey); - const algorithm2 = subtleAlgorithm(alg2, cryptoKey.algorithm); - try { - return await crypto.subtle.verify(algorithm2, cryptoKey, signature, data); - } catch { - return false; - } -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js -var subtleAlgorithm2 = (alg2) => { - switch (alg2) { - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - return "RSA-OAEP"; - default: - throw new JOSENotSupported(`alg ${alg2} is not supported either by JOSE or your javascript runtime`); - } -}; -async function encrypt2(alg2, key, cek) { - checkEncCryptoKey(key, alg2, "encrypt"); - checkKeyLength(alg2, key); - return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm2(alg2), key, cek)); -} -async function decrypt2(alg2, key, encryptedKey) { - checkEncCryptoKey(key, alg2, "decrypt"); - checkKeyLength(alg2, key); - return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm2(alg2), key, encryptedKey)); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js -var unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value'; -function subtleMapping(jwk) { - let algorithm2; - let keyUsages; - switch (jwk.kty) { - case "AKP": { - switch (jwk.alg) { - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - algorithm2 = { name: jwk.alg }; - keyUsages = jwk.priv ? ["sign"] : ["verify"]; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "RSA": { - switch (jwk.alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm2 = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm2 = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm2 = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` - }; - keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "EC": { - switch (jwk.alg) { - case "ES256": - case "ES384": - case "ES512": - algorithm2 = { - name: "ECDSA", - namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg] - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm2 = { name: "ECDH", namedCurve: jwk.crv }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "OKP": { - switch (jwk.alg) { - case "Ed25519": - case "EdDSA": - algorithm2 = { name: "Ed25519" }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm2 = { name: jwk.crv }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); - } - return { algorithm: algorithm2, keyUsages }; -} -async function jwkToKey(jwk) { - if (!jwk.alg) { - throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); - } - const { algorithm: algorithm2, keyUsages } = subtleMapping(jwk); - const keyData = { ...jwk }; - if (keyData.kty !== "AKP") { - delete keyData.alg; - } - delete keyData.use; - return crypto.subtle.importKey("jwk", keyData, algorithm2, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js -var unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; -var cache; -var handleJWK = async (key, jwk, alg2, freeze2 = false) => { - cache || (cache = /* @__PURE__ */ new WeakMap()); - let cached2 = cache.get(key); - if (cached2?.[alg2]) { - return cached2[alg2]; - } - const cryptoKey = await jwkToKey({ ...jwk, alg: alg2 }); - if (freeze2) - Object.freeze(key); - if (!cached2) { - cache.set(key, { [alg2]: cryptoKey }); - } else { - cached2[alg2] = cryptoKey; - } - return cryptoKey; -}; -var handleKeyObject = (keyObject, alg2) => { - cache || (cache = /* @__PURE__ */ new WeakMap()); - let cached2 = cache.get(keyObject); - if (cached2?.[alg2]) { - return cached2[alg2]; - } - const isPublic = keyObject.type === "public"; - const extractable = isPublic ? true : false; - let cryptoKey; - if (keyObject.asymmetricKeyType === "x25519") { - switch (alg2) { - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - break; - default: - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); - } - if (keyObject.asymmetricKeyType === "ed25519") { - if (alg2 !== "EdDSA" && alg2 !== "Ed25519") { - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ - isPublic ? "verify" : "sign" - ]); - } - switch (keyObject.asymmetricKeyType) { - case "ml-dsa-44": - case "ml-dsa-65": - case "ml-dsa-87": { - if (alg2 !== keyObject.asymmetricKeyType.toUpperCase()) { - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ - isPublic ? "verify" : "sign" - ]); - } - } - if (keyObject.asymmetricKeyType === "rsa") { - let hash2; - switch (alg2) { - case "RSA-OAEP": - hash2 = "SHA-1"; - break; - case "RS256": - case "PS256": - case "RSA-OAEP-256": - hash2 = "SHA-256"; - break; - case "RS384": - case "PS384": - case "RSA-OAEP-384": - hash2 = "SHA-384"; - break; - case "RS512": - case "PS512": - case "RSA-OAEP-512": - hash2 = "SHA-512"; - break; - default: - throw new TypeError(unusableForAlg); - } - if (alg2.startsWith("RSA-OAEP")) { - return keyObject.toCryptoKey({ - name: "RSA-OAEP", - hash: hash2 - }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); - } - cryptoKey = keyObject.toCryptoKey({ - name: alg2.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", - hash: hash2 - }, extractable, [isPublic ? "verify" : "sign"]); - } - if (keyObject.asymmetricKeyType === "ec") { - const nist = /* @__PURE__ */ new Map([ - ["prime256v1", "P-256"], - ["secp384r1", "P-384"], - ["secp521r1", "P-521"] - ]); - const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve); - if (!namedCurve) { - throw new TypeError(unusableForAlg); - } - const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }; - if (expectedCurve[alg2] && namedCurve === expectedCurve[alg2]) { - cryptoKey = keyObject.toCryptoKey({ - name: "ECDSA", - namedCurve - }, extractable, [isPublic ? "verify" : "sign"]); - } - if (alg2.startsWith("ECDH-ES")) { - cryptoKey = keyObject.toCryptoKey({ - name: "ECDH", - namedCurve - }, extractable, isPublic ? [] : ["deriveBits"]); - } - } - if (!cryptoKey) { - throw new TypeError(unusableForAlg); - } - if (!cached2) { - cache.set(keyObject, { [alg2]: cryptoKey }); - } else { - cached2[alg2] = cryptoKey; - } - return cryptoKey; -}; -async function normalizeKey(key, alg2) { - if (key instanceof Uint8Array) { - return key; - } - if (isCryptoKey(key)) { - return key; - } - if (isKeyObject(key)) { - if (key.type === "secret") { - return key.export(); - } - if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") { - try { - return handleKeyObject(key, alg2); - } catch (err) { - if (err instanceof TypeError) { - throw err; - } - } - } - let jwk = key.export({ format: "jwk" }); - return handleJWK(key, jwk, alg2); - } - if (isJWK(key)) { - if (key.k) { - return decode3(key.k); - } - return handleJWK(key, key, alg2, true); - } - throw new Error("unreachable"); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js -async function importJWK(jwk, alg2, options) { - if (!isObject3(jwk)) { - throw new TypeError("JWK must be an object"); - } - let ext; - alg2 ?? (alg2 = jwk.alg); - ext ?? (ext = options?.extractable ?? jwk.ext); - switch (jwk.kty) { - case "oct": - if (typeof jwk.k !== "string" || !jwk.k) { - throw new TypeError('missing "k" (Key Value) Parameter value'); - } - return decode3(jwk.k); - case "RSA": - if ("oth" in jwk && jwk.oth !== void 0) { - throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); - } - return jwkToKey({ ...jwk, alg: alg2, ext }); - case "AKP": { - if (typeof jwk.alg !== "string" || !jwk.alg) { - throw new TypeError('missing "alg" (Algorithm) Parameter value'); - } - if (alg2 !== void 0 && alg2 !== jwk.alg) { - throw new TypeError("JWK alg and alg option value mismatch"); - } - return jwkToKey({ ...jwk, ext }); - } - case "EC": - case "OKP": - return jwkToKey({ ...jwk, alg: alg2, ext }); - default: - throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); - } -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js -async function keyToJWK(key) { - if (isKeyObject(key)) { - if (key.type === "secret") { - key = key.export(); - } else { - return key.export({ format: "jwk" }); - } - } - if (key instanceof Uint8Array) { - return { - kty: "oct", - k: encode4(key) - }; - } - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array")); - } - if (!key.extractable) { - throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); - } - const { ext, key_ops, alg: alg2, use: use2, ...jwk } = await crypto.subtle.exportKey("jwk", key); - if (jwk.kty === "AKP") { - ; - jwk.alg = alg2; - } - return jwk; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js -async function exportJWK(key) { - return keyToJWK(key); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js -async function wrap3(alg2, key, cek, iv) { - const jweAlgorithm = alg2.slice(0, 7); - const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array()); - return { - encryptedKey: wrapped.ciphertext, - iv: encode4(wrapped.iv), - tag: encode4(wrapped.tag) - }; -} -async function unwrap3(alg2, key, encryptedKey, iv, tag2) { - const jweAlgorithm = alg2.slice(0, 7); - return decrypt(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array()); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js -var unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value'; -function assertEncryptedKey(encryptedKey) { - if (encryptedKey === void 0) - throw new JWEInvalid("JWE Encrypted Key missing"); -} -async function decryptKeyManagement(alg2, key, encryptedKey, joseHeader, options) { - switch (alg2) { - case "dir": { - if (encryptedKey !== void 0) - throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); - return key; - } - case "ECDH-ES": - if (encryptedKey !== void 0) - throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - if (!isObject3(joseHeader.epk)) - throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - assertCryptoKey(key); - if (!allowed(key)) - throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); - const epk = await importJWK(joseHeader.epk, alg2); - assertCryptoKey(epk); - let partyUInfo; - let partyVInfo; - if (joseHeader.apu !== void 0) { - if (typeof joseHeader.apu !== "string") - throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); - partyUInfo = decodeBase64url(joseHeader.apu, "apu", JWEInvalid); - } - if (joseHeader.apv !== void 0) { - if (typeof joseHeader.apv !== "string") - throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); - partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid); - } - const sharedSecret = await deriveKey(epk, key, alg2 === "ECDH-ES" ? joseHeader.enc : alg2, alg2 === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg2.slice(-5, -2), 10), partyUInfo, partyVInfo); - if (alg2 === "ECDH-ES") - return sharedSecret; - assertEncryptedKey(encryptedKey); - return unwrap(alg2.slice(-6), sharedSecret, encryptedKey); - } - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - assertEncryptedKey(encryptedKey); - assertCryptoKey(key); - return decrypt2(alg2, key, encryptedKey); - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": { - assertEncryptedKey(encryptedKey); - if (typeof joseHeader.p2c !== "number") - throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); - const p2cLimit = options?.maxPBES2Count || 1e4; - if (joseHeader.p2c > p2cLimit) - throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); - if (typeof joseHeader.p2s !== "string") - throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); - let p2s; - p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid); - return unwrap2(alg2, key, encryptedKey, joseHeader.p2c, p2s); - } - case "A128KW": - case "A192KW": - case "A256KW": { - assertEncryptedKey(encryptedKey); - return unwrap(alg2, key, encryptedKey); - } - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": { - assertEncryptedKey(encryptedKey); - if (typeof joseHeader.iv !== "string") - throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); - if (typeof joseHeader.tag !== "string") - throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); - let iv; - iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid); - let tag2; - tag2 = decodeBase64url(joseHeader.tag, "tag", JWEInvalid); - return unwrap3(alg2, key, encryptedKey, iv, tag2); - } - default: { - throw new JOSENotSupported(unsupportedAlgHeader); - } - } -} -async function encryptKeyManagement(alg2, enc2, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - switch (alg2) { - case "dir": { - cek = key; - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - assertCryptoKey(key); - if (!allowed(key)) { - throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); - } - const { apu, apv } = providedParameters; - let ephemeralKey; - if (providedParameters.epk) { - ephemeralKey = await normalizeKey(providedParameters.epk, alg2); - } else { - ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey; - } - const { x, y, crv, kty } = await exportJWK(ephemeralKey); - const sharedSecret = await deriveKey(key, ephemeralKey, alg2 === "ECDH-ES" ? enc2 : alg2, alg2 === "ECDH-ES" ? cekLength(enc2) : parseInt(alg2.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x, crv, kty } }; - if (kty === "EC") - parameters.epk.y = y; - if (apu) - parameters.apu = encode4(apu); - if (apv) - parameters.apv = encode4(apv); - if (alg2 === "ECDH-ES") { - cek = sharedSecret; - break; - } - cek = providedCek || generateCek(enc2); - const kwAlg = alg2.slice(-6); - encryptedKey = await wrap(kwAlg, sharedSecret, cek); - break; - } - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - cek = providedCek || generateCek(enc2); - assertCryptoKey(key); - encryptedKey = await encrypt2(alg2, key, cek); - break; - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": { - cek = providedCek || generateCek(enc2); - const { p2c, p2s } = providedParameters; - ({ encryptedKey, ...parameters } = await wrap2(alg2, key, cek, p2c, p2s)); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - cek = providedCek || generateCek(enc2); - encryptedKey = await wrap(alg2, key, cek); - break; - } - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": { - cek = providedCek || generateCek(enc2); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await wrap3(alg2, key, cek, iv)); - break; - } - default: { - throw new JOSENotSupported(unsupportedAlgHeader); - } - } - return { cek, encryptedKey, parameters }; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) { - throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); - } - if (!protectedHeader || protectedHeader.crit === void 0) { - return /* @__PURE__ */ new Set(); - } - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { - throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); - } - let recognized; - if (recognizedOption !== void 0) { - recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); - } else { - recognized = recognizedDefault; - } - for (const parameter of protectedHeader.crit) { - if (!recognized.has(parameter)) { - throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); - } - if (joseHeader[parameter] === void 0) { - throw new Err(`Extension Header Parameter "${parameter}" is missing`); - } - if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { - throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); - } - } - return new Set(protectedHeader.crit); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js -function validateAlgorithms(option, algorithms) { - if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) { - throw new TypeError(`"${option}" option must be an array of strings`); - } - if (!algorithms) { - return void 0; - } - return new Set(algorithms); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js -var tag = (key) => key?.[Symbol.toStringTag]; -var jwkMatchesOp = (alg2, key, usage) => { - if (key.use !== void 0) { - let expected; - switch (usage) { - case "sign": - case "verify": - expected = "sig"; - break; - case "encrypt": - case "decrypt": - expected = "enc"; - break; - } - if (key.use !== expected) { - throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); - } - } - if (key.alg !== void 0 && key.alg !== alg2) { - throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg2}" when present`); - } - if (Array.isArray(key.key_ops)) { - let expectedKeyOp; - switch (true) { - case (usage === "sign" || usage === "verify"): - case alg2 === "dir": - case alg2.includes("CBC-HS"): - expectedKeyOp = usage; - break; - case alg2.startsWith("PBES2"): - expectedKeyOp = "deriveBits"; - break; - case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg2): - if (!alg2.includes("GCM") && alg2.endsWith("KW")) { - expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; - } else { - expectedKeyOp = usage; - } - break; - case (usage === "encrypt" && alg2.startsWith("RSA")): - expectedKeyOp = "wrapKey"; - break; - case usage === "decrypt": - expectedKeyOp = alg2.startsWith("RSA") ? "unwrapKey" : "deriveBits"; - break; - } - if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) { - throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); - } - } - return true; -}; -var symmetricTypeCheck = (alg2, key, usage) => { - if (key instanceof Uint8Array) - return; - if (isJWK(key)) { - if (isSecretJWK(key) && jwkMatchesOp(alg2, key, usage)) - return; - throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); - } - if (!isKeyLike(key)) { - throw new TypeError(withAlg(alg2, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); - } - if (key.type !== "secret") { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); - } -}; -var asymmetricTypeCheck = (alg2, key, usage) => { - if (isJWK(key)) { - switch (usage) { - case "decrypt": - case "sign": - if (isPrivateJWK(key) && jwkMatchesOp(alg2, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation must be a private JWK`); - case "encrypt": - case "verify": - if (isPublicJWK(key) && jwkMatchesOp(alg2, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation must be a public JWK`); - } - } - if (!isKeyLike(key)) { - throw new TypeError(withAlg(alg2, key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - if (key.type === "secret") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (key.type === "public") { - switch (usage) { - case "sign": - throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - case "decrypt": - throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - } - if (key.type === "private") { - switch (usage) { - case "verify": - throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - case "encrypt": - throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } - } -}; -function checkKeyType(alg2, key, usage) { - switch (alg2.substring(0, 2)) { - case "A1": - case "A2": - case "di": - case "HS": - case "PB": - symmetricTypeCheck(alg2, key, usage); - break; - default: - asymmetricTypeCheck(alg2, key, usage); - } -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js -function supported(name) { - if (typeof globalThis[name] === "undefined") { - throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`); - } -} -async function compress(input) { - supported("CompressionStream"); - const cs = new CompressionStream("deflate-raw"); - const writer = cs.writable.getWriter(); - writer.write(input).catch(() => { - }); - writer.close().catch(() => { - }); - const chunks = []; - const reader = cs.readable.getReader(); - for (; ; ) { - const { value, done } = await reader.read(); - if (done) - break; - chunks.push(value); - } - return concat(...chunks); -} -async function decompress(input, maxLength) { - supported("DecompressionStream"); - const ds = new DecompressionStream("deflate-raw"); - const writer = ds.writable.getWriter(); - writer.write(input).catch(() => { - }); - writer.close().catch(() => { - }); - const chunks = []; - let length = 0; - const reader = ds.readable.getReader(); - for (; ; ) { - const { value, done } = await reader.read(); - if (done) - break; - chunks.push(value); - length += value.byteLength; - if (maxLength !== Infinity && length > maxLength) { - throw new JWEInvalid("Decompressed plaintext exceeded the configured limit"); - } - } - return concat(...chunks); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js -async function flattenedDecrypt(jwe, key, options) { - if (!isObject3(jwe)) { - throw new JWEInvalid("Flattened JWE must be an object"); - } - if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { - throw new JWEInvalid("JOSE Header missing"); - } - if (jwe.iv !== void 0 && typeof jwe.iv !== "string") { - throw new JWEInvalid("JWE Initialization Vector incorrect type"); - } - if (typeof jwe.ciphertext !== "string") { - throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); - } - if (jwe.tag !== void 0 && typeof jwe.tag !== "string") { - throw new JWEInvalid("JWE Authentication Tag incorrect type"); - } - if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { - throw new JWEInvalid("JWE Protected Header incorrect type"); - } - if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { - throw new JWEInvalid("JWE Encrypted Key incorrect type"); - } - if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { - throw new JWEInvalid("JWE AAD incorrect type"); - } - if (jwe.header !== void 0 && !isObject3(jwe.header)) { - throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); - } - if (jwe.unprotected !== void 0 && !isObject3(jwe.unprotected)) { - throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); - } - let parsedProt; - if (jwe.protected) { - try { - const protectedHeader2 = decode3(jwe.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader2)); - } catch { - throw new JWEInvalid("JWE Protected Header is invalid"); - } - } - if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { - throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...parsedProt, - ...jwe.header, - ...jwe.unprotected - }; - validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader); - if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { - throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); - } - if (joseHeader.zip !== void 0 && !parsedProt?.zip) { - throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); - } - const { alg: alg2, enc: enc2 } = joseHeader; - if (typeof alg2 !== "string" || !alg2) { - throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); - } - if (typeof enc2 !== "string" || !enc2) { - throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); - } - const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms); - const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); - if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg2) || !keyManagementAlgorithms && alg2.startsWith("PBES2")) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc2)) { - throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); - } - let encryptedKey; - if (jwe.encrypted_key !== void 0) { - encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid); - } - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jwe); - resolvedKey = true; - } - checkKeyType(alg2 === "dir" ? enc2 : alg2, key, "decrypt"); - const k = await normalizeKey(key, alg2); - let cek; - try { - cek = await decryptKeyManagement(alg2, k, encryptedKey, joseHeader, options); - } catch (err) { - if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { - throw err; - } - cek = generateCek(enc2); - } - let iv; - let tag2; - if (jwe.iv !== void 0) { - iv = decodeBase64url(jwe.iv, "iv", JWEInvalid); - } - if (jwe.tag !== void 0) { - tag2 = decodeBase64url(jwe.tag, "tag", JWEInvalid); - } - const protectedHeader = jwe.protected !== void 0 ? encode3(jwe.protected) : new Uint8Array(); - let additionalData; - if (jwe.aad !== void 0) { - additionalData = concat(protectedHeader, encode3("."), encode3(jwe.aad)); - } else { - additionalData = protectedHeader; - } - const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid); - const plaintext = await decrypt(enc2, cek, ciphertext, iv, tag2, additionalData); - const result = { plaintext }; - if (joseHeader.zip === "DEF") { - const maxDecompressedLength = options?.maxDecompressedLength ?? 25e4; - if (maxDecompressedLength === 0) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) { - throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity"); - } - result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => { - if (cause instanceof JWEInvalid) - throw cause; - throw new JWEInvalid("Failed to decompress plaintext", { cause }); - }); - } - if (jwe.protected !== void 0) { - result.protectedHeader = parsedProt; - } - if (jwe.aad !== void 0) { - result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid); - } - if (jwe.unprotected !== void 0) { - result.sharedUnprotectedHeader = jwe.unprotected; - } - if (jwe.header !== void 0) { - result.unprotectedHeader = jwe.header; - } - if (resolvedKey) { - return { ...result, key: k }; - } - return result; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js -async function compactDecrypt(jwe, key, options) { - if (jwe instanceof Uint8Array) { - jwe = decoder.decode(jwe); - } - if (typeof jwe !== "string") { - throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); - } - const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split("."); - if (length !== 5) { - throw new JWEInvalid("Invalid Compact JWE"); - } - const decrypted = await flattenedDecrypt({ - ciphertext, - iv: iv || void 0, - protected: protectedHeader, - tag: tag2 || void 0, - encrypted_key: encryptedKey || void 0 - }, key, options); - const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: decrypted.key }; - } - return result; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js -var _plaintext, _protectedHeader, _sharedUnprotectedHeader, _unprotectedHeader, _aad, _cek, _iv, _keyManagementParameters; -var FlattenedEncrypt = class { - constructor(plaintext) { - __privateAdd(this, _plaintext); - __privateAdd(this, _protectedHeader); - __privateAdd(this, _sharedUnprotectedHeader); - __privateAdd(this, _unprotectedHeader); - __privateAdd(this, _aad); - __privateAdd(this, _cek); - __privateAdd(this, _iv); - __privateAdd(this, _keyManagementParameters); - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError("plaintext must be an instance of Uint8Array"); - } - __privateSet(this, _plaintext, plaintext); - } - setKeyManagementParameters(parameters) { - assertNotSet(__privateGet(this, _keyManagementParameters), "setKeyManagementParameters"); - __privateSet(this, _keyManagementParameters, parameters); - return this; - } - setProtectedHeader(protectedHeader) { - assertNotSet(__privateGet(this, _protectedHeader), "setProtectedHeader"); - __privateSet(this, _protectedHeader, protectedHeader); - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - assertNotSet(__privateGet(this, _sharedUnprotectedHeader), "setSharedUnprotectedHeader"); - __privateSet(this, _sharedUnprotectedHeader, sharedUnprotectedHeader); - return this; - } - setUnprotectedHeader(unprotectedHeader) { - assertNotSet(__privateGet(this, _unprotectedHeader), "setUnprotectedHeader"); - __privateSet(this, _unprotectedHeader, unprotectedHeader); - return this; - } - setAdditionalAuthenticatedData(aad) { - __privateSet(this, _aad, aad); - return this; - } - setContentEncryptionKey(cek) { - assertNotSet(__privateGet(this, _cek), "setContentEncryptionKey"); - __privateSet(this, _cek, cek); - return this; - } - setInitializationVector(iv) { - assertNotSet(__privateGet(this, _iv), "setInitializationVector"); - __privateSet(this, _iv, iv); - return this; - } - async encrypt(key, options) { - if (!__privateGet(this, _protectedHeader) && !__privateGet(this, _unprotectedHeader) && !__privateGet(this, _sharedUnprotectedHeader)) { - throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); - } - if (!isDisjoint(__privateGet(this, _protectedHeader), __privateGet(this, _unprotectedHeader), __privateGet(this, _sharedUnprotectedHeader))) { - throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); - } - const joseHeader = { - ...__privateGet(this, _protectedHeader), - ...__privateGet(this, _unprotectedHeader), - ...__privateGet(this, _sharedUnprotectedHeader) - }; - validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, __privateGet(this, _protectedHeader), joseHeader); - if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { - throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); - } - if (joseHeader.zip !== void 0 && !__privateGet(this, _protectedHeader)?.zip) { - throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); - } - const { alg: alg2, enc: enc2 } = joseHeader; - if (typeof alg2 !== "string" || !alg2) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc2 !== "string" || !enc2) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (__privateGet(this, _cek) && (alg2 === "dir" || alg2 === "ECDH-ES")) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg2}`); - } - checkKeyType(alg2 === "dir" ? enc2 : alg2, key, "encrypt"); - let cek; - { - let parameters; - const k = await normalizeKey(key, alg2); - ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg2, enc2, k, __privateGet(this, _cek), __privateGet(this, _keyManagementParameters))); - if (parameters) { - if (options && unprotected in options) { - if (!__privateGet(this, _unprotectedHeader)) { - this.setUnprotectedHeader(parameters); - } else { - __privateSet(this, _unprotectedHeader, { ...__privateGet(this, _unprotectedHeader), ...parameters }); - } - } else if (!__privateGet(this, _protectedHeader)) { - this.setProtectedHeader(parameters); - } else { - __privateSet(this, _protectedHeader, { ...__privateGet(this, _protectedHeader), ...parameters }); - } - } - } - let additionalData; - let protectedHeaderS; - let protectedHeaderB; - let aadMember; - if (__privateGet(this, _protectedHeader)) { - protectedHeaderS = encode4(JSON.stringify(__privateGet(this, _protectedHeader))); - protectedHeaderB = encode3(protectedHeaderS); - } else { - protectedHeaderS = ""; - protectedHeaderB = new Uint8Array(); - } - if (__privateGet(this, _aad)) { - aadMember = encode4(__privateGet(this, _aad)); - const aadMemberBytes = encode3(aadMember); - additionalData = concat(protectedHeaderB, encode3("."), aadMemberBytes); - } else { - additionalData = protectedHeaderB; - } - let plaintext = __privateGet(this, _plaintext); - if (joseHeader.zip === "DEF") { - plaintext = await compress(plaintext).catch((cause) => { - throw new JWEInvalid("Failed to compress plaintext", { cause }); - }); - } - const { ciphertext, tag: tag2, iv } = await encrypt(enc2, plaintext, cek, __privateGet(this, _iv), additionalData); - const jwe = { - ciphertext: encode4(ciphertext) - }; - if (iv) { - jwe.iv = encode4(iv); - } - if (tag2) { - jwe.tag = encode4(tag2); - } - if (encryptedKey) { - jwe.encrypted_key = encode4(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (__privateGet(this, _protectedHeader)) { - jwe.protected = protectedHeaderS; - } - if (__privateGet(this, _sharedUnprotectedHeader)) { - jwe.unprotected = __privateGet(this, _sharedUnprotectedHeader); - } - if (__privateGet(this, _unprotectedHeader)) { - jwe.header = __privateGet(this, _unprotectedHeader); - } - return jwe; - } -}; -_plaintext = new WeakMap(); -_protectedHeader = new WeakMap(); -_sharedUnprotectedHeader = new WeakMap(); -_unprotectedHeader = new WeakMap(); -_aad = new WeakMap(); -_cek = new WeakMap(); -_iv = new WeakMap(); -_keyManagementParameters = new WeakMap(); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js -async function flattenedVerify(jws, key, options) { - if (!isObject3(jws)) { - throw new JWSInvalid("Flattened JWS must be an object"); - } - if (jws.protected === void 0 && jws.header === void 0) { - throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== void 0 && typeof jws.protected !== "string") { - throw new JWSInvalid("JWS Protected Header incorrect type"); - } - if (jws.payload === void 0) { - throw new JWSInvalid("JWS Payload missing"); - } - if (typeof jws.signature !== "string") { - throw new JWSInvalid("JWS Signature missing or incorrect type"); - } - if (jws.header !== void 0 && !isObject3(jws.header)) { - throw new JWSInvalid("JWS Unprotected Header incorrect type"); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = decode3(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } catch { - throw new JWSInvalid("JWS Protected Header is invalid"); - } - } - if (!isDisjoint(parsedProt, jws.header)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...parsedProt, - ...jws.header - }; - const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = parsedProt.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg: alg2 } = joseHeader; - if (typeof alg2 !== "string" || !alg2) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && validateAlgorithms("algorithms", options.algorithms); - if (algorithms && !algorithms.has(alg2)) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== "string") { - throw new JWSInvalid("JWS Payload must be a string"); - } - } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { - throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); - } - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jws); - resolvedKey = true; - } - checkKeyType(alg2, key, "verify"); - const data = concat(jws.protected !== void 0 ? encode3(jws.protected) : new Uint8Array(), encode3("."), typeof jws.payload === "string" ? b64 ? encode3(jws.payload) : encoder.encode(jws.payload) : jws.payload); - const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); - const k = await normalizeKey(key, alg2); - const verified = await verify(alg2, k, signature, data); - if (!verified) { - throw new JWSSignatureVerificationFailed(); - } - let payload; - if (b64) { - payload = decodeBase64url(jws.payload, "payload", JWSInvalid); - } else if (typeof jws.payload === "string") { - payload = encoder.encode(jws.payload); - } else { - payload = jws.payload; - } - const result = { payload }; - if (jws.protected !== void 0) { - result.protectedHeader = parsedProt; - } - if (jws.header !== void 0) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key: k }; - } - return result; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js -async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = decoder.decode(jws); - } - if (typeof jws !== "string") { - throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); - if (length !== 3) { - throw new JWSInvalid("Invalid Compact JWS"); - } - const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js -var epoch = (date5) => Math.floor(date5.getTime() / 1e3); -var minute = 60; -var hour = minute * 60; -var day = hour * 24; -var week = day * 7; -var year = day * 365.25; -var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; -function secs(str) { - const matched = REGEX.exec(str); - if (!matched || matched[4] && matched[1]) { - throw new TypeError("Invalid time period format"); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case "sec": - case "secs": - case "second": - case "seconds": - case "s": - numericDate = Math.round(value); - break; - case "minute": - case "minutes": - case "min": - case "mins": - case "m": - numericDate = Math.round(value * minute); - break; - case "hour": - case "hours": - case "hr": - case "hrs": - case "h": - numericDate = Math.round(value * hour); - break; - case "day": - case "days": - case "d": - numericDate = Math.round(value * day); - break; - case "week": - case "weeks": - case "w": - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === "-" || matched[4] === "ago") { - return -numericDate; - } - return numericDate; -} -function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); - } - return input; -} -var normalizeTyp = (value) => { - if (value.includes("/")) { - return value.toLowerCase(); - } - return `application/${value.toLowerCase()}`; -}; -var checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === "string") { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; -}; -function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { - let payload; - try { - payload = JSON.parse(decoder.decode(encodedPayload)); - } catch { - } - if (!isObject3(payload)) { - throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); - } - const { typ } = options; - if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed"); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== void 0) - presenceCheck.push("iat"); - if (audience !== void 0) - presenceCheck.push("aud"); - if (subject !== void 0) - presenceCheck.push("sub"); - if (issuer !== void 0) - presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); - } - } - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { - throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed"); - } - if (subject && payload.sub !== subject) { - throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed"); - } - if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { - throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed"); - } - let tolerance; - switch (typeof options.clockTolerance) { - case "string": - tolerance = secs(options.clockTolerance); - break; - case "number": - tolerance = options.clockTolerance; - break; - case "undefined": - tolerance = 0; - break; - default: - throw new TypeError("Invalid clockTolerance option type"); - } - const { currentDate } = options; - const now2 = epoch(currentDate || /* @__PURE__ */ new Date()); - if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") { - throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid"); - } - if (payload.nbf !== void 0) { - if (typeof payload.nbf !== "number") { - throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid"); - } - if (payload.nbf > now2 + tolerance) { - throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed"); - } - } - if (payload.exp !== void 0) { - if (typeof payload.exp !== "number") { - throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid"); - } - if (payload.exp <= now2 - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed"); - } - } - if (maxTokenAge) { - const age = now2 - payload.iat; - const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); - if (age - tolerance > max) { - throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed"); - } - if (age < 0 - tolerance) { - throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed"); - } - } - return payload; -} -var _payload; -var JWTClaimsBuilder = class { - constructor(payload) { - __privateAdd(this, _payload); - if (!isObject3(payload)) { - throw new TypeError("JWT Claims Set MUST be an object"); - } - __privateSet(this, _payload, structuredClone(payload)); - } - data() { - return encoder.encode(JSON.stringify(__privateGet(this, _payload))); - } - get iss() { - return __privateGet(this, _payload).iss; - } - set iss(value) { - __privateGet(this, _payload).iss = value; - } - get sub() { - return __privateGet(this, _payload).sub; - } - set sub(value) { - __privateGet(this, _payload).sub = value; - } - get aud() { - return __privateGet(this, _payload).aud; - } - set aud(value) { - __privateGet(this, _payload).aud = value; - } - set jti(value) { - __privateGet(this, _payload).jti = value; - } - set nbf(value) { - if (typeof value === "number") { - __privateGet(this, _payload).nbf = validateInput("setNotBefore", value); - } else if (value instanceof Date) { - __privateGet(this, _payload).nbf = validateInput("setNotBefore", epoch(value)); - } else { - __privateGet(this, _payload).nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - } - set exp(value) { - if (typeof value === "number") { - __privateGet(this, _payload).exp = validateInput("setExpirationTime", value); - } else if (value instanceof Date) { - __privateGet(this, _payload).exp = validateInput("setExpirationTime", epoch(value)); - } else { - __privateGet(this, _payload).exp = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - } - set iat(value) { - if (value === void 0) { - __privateGet(this, _payload).iat = epoch(/* @__PURE__ */ new Date()); - } else if (value instanceof Date) { - __privateGet(this, _payload).iat = validateInput("setIssuedAt", epoch(value)); - } else if (typeof value === "string") { - __privateGet(this, _payload).iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); - } else { - __privateGet(this, _payload).iat = validateInput("setIssuedAt", value); - } - } -}; -_payload = new WeakMap(); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js -async function jwtVerify(jwt2, key, options) { - const verified = await compactVerify(jwt2, key, options); - if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options); - const result = { payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js -async function jwtDecrypt(jwt2, key, options) { - const decrypted = await compactDecrypt(jwt2, key, options); - const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) { - throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch"); - } - if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) { - throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch"); - } - if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { - throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch"); - } - const result = { payload, protectedHeader }; - if (typeof key === "function") { - return { ...result, key: decrypted.key }; - } - return result; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js -var _flattened; -var CompactEncrypt = class { - constructor(plaintext) { - __privateAdd(this, _flattened); - __privateSet(this, _flattened, new FlattenedEncrypt(plaintext)); - } - setContentEncryptionKey(cek) { - __privateGet(this, _flattened).setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - __privateGet(this, _flattened).setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - __privateGet(this, _flattened).setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - __privateGet(this, _flattened).setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await __privateGet(this, _flattened).encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); - } -}; -_flattened = new WeakMap(); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js -var _payload2, _protectedHeader2, _unprotectedHeader2; -var FlattenedSign = class { - constructor(payload) { - __privateAdd(this, _payload2); - __privateAdd(this, _protectedHeader2); - __privateAdd(this, _unprotectedHeader2); - if (!(payload instanceof Uint8Array)) { - throw new TypeError("payload must be an instance of Uint8Array"); - } - __privateSet(this, _payload2, payload); - } - setProtectedHeader(protectedHeader) { - assertNotSet(__privateGet(this, _protectedHeader2), "setProtectedHeader"); - __privateSet(this, _protectedHeader2, protectedHeader); - return this; - } - setUnprotectedHeader(unprotectedHeader) { - assertNotSet(__privateGet(this, _unprotectedHeader2), "setUnprotectedHeader"); - __privateSet(this, _unprotectedHeader2, unprotectedHeader); - return this; - } - async sign(key, options) { - if (!__privateGet(this, _protectedHeader2) && !__privateGet(this, _unprotectedHeader2)) { - throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); - } - if (!isDisjoint(__privateGet(this, _protectedHeader2), __privateGet(this, _unprotectedHeader2))) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...__privateGet(this, _protectedHeader2), - ...__privateGet(this, _unprotectedHeader2) - }; - const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, __privateGet(this, _protectedHeader2), joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = __privateGet(this, _protectedHeader2).b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg: alg2 } = joseHeader; - if (typeof alg2 !== "string" || !alg2) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - checkKeyType(alg2, key, "sign"); - let payloadS; - let payloadB; - if (b64) { - payloadS = encode4(__privateGet(this, _payload2)); - payloadB = encode3(payloadS); - } else { - payloadB = __privateGet(this, _payload2); - payloadS = ""; - } - let protectedHeaderString; - let protectedHeaderBytes; - if (__privateGet(this, _protectedHeader2)) { - protectedHeaderString = encode4(JSON.stringify(__privateGet(this, _protectedHeader2))); - protectedHeaderBytes = encode3(protectedHeaderString); - } else { - protectedHeaderString = ""; - protectedHeaderBytes = new Uint8Array(); - } - const data = concat(protectedHeaderBytes, encode3("."), payloadB); - const k = await normalizeKey(key, alg2); - const signature = await sign(alg2, k, data); - const jws = { - signature: encode4(signature), - payload: payloadS - }; - if (__privateGet(this, _unprotectedHeader2)) { - jws.header = __privateGet(this, _unprotectedHeader2); - } - if (__privateGet(this, _protectedHeader2)) { - jws.protected = protectedHeaderString; - } - return jws; - } -}; -_payload2 = new WeakMap(); -_protectedHeader2 = new WeakMap(); -_unprotectedHeader2 = new WeakMap(); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js -var _flattened2; -var CompactSign = class { - constructor(payload) { - __privateAdd(this, _flattened2); - __privateSet(this, _flattened2, new FlattenedSign(payload)); - } - setProtectedHeader(protectedHeader) { - __privateGet(this, _flattened2).setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await __privateGet(this, _flattened2).sign(key, options); - if (jws.payload === void 0) { - throw new TypeError("use the flattened module for creating JWS with b64: false"); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } -}; -_flattened2 = new WeakMap(); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js -var _protectedHeader3, _jwt2; -var SignJWT = class { - constructor(payload = {}) { - __privateAdd(this, _protectedHeader3); - __privateAdd(this, _jwt2); - __privateSet(this, _jwt2, new JWTClaimsBuilder(payload)); - } - setIssuer(issuer) { - __privateGet(this, _jwt2).iss = issuer; - return this; - } - setSubject(subject) { - __privateGet(this, _jwt2).sub = subject; - return this; - } - setAudience(audience) { - __privateGet(this, _jwt2).aud = audience; - return this; - } - setJti(jwtId) { - __privateGet(this, _jwt2).jti = jwtId; - return this; - } - setNotBefore(input) { - __privateGet(this, _jwt2).nbf = input; - return this; - } - setExpirationTime(input) { - __privateGet(this, _jwt2).exp = input; - return this; - } - setIssuedAt(input) { - __privateGet(this, _jwt2).iat = input; - return this; - } - setProtectedHeader(protectedHeader) { - __privateSet(this, _protectedHeader3, protectedHeader); - return this; - } - async sign(key, options) { - const sig = new CompactSign(__privateGet(this, _jwt2).data()); - sig.setProtectedHeader(__privateGet(this, _protectedHeader3)); - if (Array.isArray(__privateGet(this, _protectedHeader3)?.crit) && __privateGet(this, _protectedHeader3).crit.includes("b64") && __privateGet(this, _protectedHeader3).b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - return sig.sign(key, options); - } -}; -_protectedHeader3 = new WeakMap(); -_jwt2 = new WeakMap(); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js -var _cek2, _iv2, _keyManagementParameters2, _protectedHeader4, _replicateIssuerAsHeader, _replicateSubjectAsHeader, _replicateAudienceAsHeader, _jwt3; -var EncryptJWT = class { - constructor(payload = {}) { - __privateAdd(this, _cek2); - __privateAdd(this, _iv2); - __privateAdd(this, _keyManagementParameters2); - __privateAdd(this, _protectedHeader4); - __privateAdd(this, _replicateIssuerAsHeader); - __privateAdd(this, _replicateSubjectAsHeader); - __privateAdd(this, _replicateAudienceAsHeader); - __privateAdd(this, _jwt3); - __privateSet(this, _jwt3, new JWTClaimsBuilder(payload)); - } - setIssuer(issuer) { - __privateGet(this, _jwt3).iss = issuer; - return this; - } - setSubject(subject) { - __privateGet(this, _jwt3).sub = subject; - return this; - } - setAudience(audience) { - __privateGet(this, _jwt3).aud = audience; - return this; - } - setJti(jwtId) { - __privateGet(this, _jwt3).jti = jwtId; - return this; - } - setNotBefore(input) { - __privateGet(this, _jwt3).nbf = input; - return this; - } - setExpirationTime(input) { - __privateGet(this, _jwt3).exp = input; - return this; - } - setIssuedAt(input) { - __privateGet(this, _jwt3).iat = input; - return this; - } - setProtectedHeader(protectedHeader) { - assertNotSet(__privateGet(this, _protectedHeader4), "setProtectedHeader"); - __privateSet(this, _protectedHeader4, protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - assertNotSet(__privateGet(this, _keyManagementParameters2), "setKeyManagementParameters"); - __privateSet(this, _keyManagementParameters2, parameters); - return this; - } - setContentEncryptionKey(cek) { - assertNotSet(__privateGet(this, _cek2), "setContentEncryptionKey"); - __privateSet(this, _cek2, cek); - return this; - } - setInitializationVector(iv) { - assertNotSet(__privateGet(this, _iv2), "setInitializationVector"); - __privateSet(this, _iv2, iv); - return this; - } - replicateIssuerAsHeader() { - __privateSet(this, _replicateIssuerAsHeader, true); - return this; - } - replicateSubjectAsHeader() { - __privateSet(this, _replicateSubjectAsHeader, true); - return this; - } - replicateAudienceAsHeader() { - __privateSet(this, _replicateAudienceAsHeader, true); - return this; - } - async encrypt(key, options) { - const enc2 = new CompactEncrypt(__privateGet(this, _jwt3).data()); - if (__privateGet(this, _protectedHeader4) && (__privateGet(this, _replicateIssuerAsHeader) || __privateGet(this, _replicateSubjectAsHeader) || __privateGet(this, _replicateAudienceAsHeader))) { - __privateSet(this, _protectedHeader4, { - ...__privateGet(this, _protectedHeader4), - iss: __privateGet(this, _replicateIssuerAsHeader) ? __privateGet(this, _jwt3).iss : void 0, - sub: __privateGet(this, _replicateSubjectAsHeader) ? __privateGet(this, _jwt3).sub : void 0, - aud: __privateGet(this, _replicateAudienceAsHeader) ? __privateGet(this, _jwt3).aud : void 0 - }); - } - enc2.setProtectedHeader(__privateGet(this, _protectedHeader4)); - if (__privateGet(this, _iv2)) { - enc2.setInitializationVector(__privateGet(this, _iv2)); - } - if (__privateGet(this, _cek2)) { - enc2.setContentEncryptionKey(__privateGet(this, _cek2)); - } - if (__privateGet(this, _keyManagementParameters2)) { - enc2.setKeyManagementParameters(__privateGet(this, _keyManagementParameters2)); - } - return enc2.encrypt(key, options); - } -}; -_cek2 = new WeakMap(); -_iv2 = new WeakMap(); -_keyManagementParameters2 = new WeakMap(); -_protectedHeader4 = new WeakMap(); -_replicateIssuerAsHeader = new WeakMap(); -_replicateSubjectAsHeader = new WeakMap(); -_replicateAudienceAsHeader = new WeakMap(); -_jwt3 = new WeakMap(); - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js -var check2 = (value, description) => { - if (typeof value !== "string" || !value) { - throw new JWKInvalid(`${description} missing or invalid`); - } -}; -async function calculateJwkThumbprint(key, digestAlgorithm) { - let jwk; - if (isJWK(key)) { - jwk = key; - } else if (isKeyLike(key)) { - jwk = await exportJWK(key); - } else { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - digestAlgorithm ?? (digestAlgorithm = "sha256"); - if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case "AKP": - check2(jwk.alg, '"alg" (Algorithm) Parameter'); - check2(jwk.pub, '"pub" (Public key) Parameter'); - components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub }; - break; - case "EC": - check2(jwk.crv, '"crv" (Curve) Parameter'); - check2(jwk.x, '"x" (X Coordinate) Parameter'); - check2(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case "OKP": - check2(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check2(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case "RSA": - check2(jwk.e, '"e" (Exponent) Parameter'); - check2(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case "oct": - check2(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); - } - const data = encode3(JSON.stringify(components)); - return encode4(await digest(digestAlgorithm, data)); -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js -function getKtyFromAlg(alg2) { - switch (typeof alg2 === "string" && alg2.slice(0, 2)) { - case "RS": - case "PS": - return "RSA"; - case "ES": - return "EC"; - case "Ed": - return "OKP"; - case "ML": - return "AKP"; - default: - throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } -} -function isJWKSLike(jwks) { - return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); -} -function isJWKLike(key) { - return isObject3(key); -} -var _jwks, _cached; -var LocalJWKSet = class { - constructor(jwks) { - __privateAdd(this, _jwks); - __privateAdd(this, _cached, /* @__PURE__ */ new WeakMap()); - if (!isJWKSLike(jwks)) { - throw new JWKSInvalid("JSON Web Key Set malformed"); - } - __privateSet(this, _jwks, structuredClone(jwks)); - } - jwks() { - return __privateGet(this, _jwks); - } - async getKey(protectedHeader, token) { - const { alg: alg2, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg2); - const candidates = __privateGet(this, _jwks).keys.filter((jwk2) => { - let candidate = kty === jwk2.kty; - if (candidate && typeof kid === "string") { - candidate = kid === jwk2.kid; - } - if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) { - candidate = alg2 === jwk2.alg; - } - if (candidate && typeof jwk2.use === "string") { - candidate = jwk2.use === "sig"; - } - if (candidate && Array.isArray(jwk2.key_ops)) { - candidate = jwk2.key_ops.includes("verify"); - } - if (candidate) { - switch (alg2) { - case "ES256": - candidate = jwk2.crv === "P-256"; - break; - case "ES384": - candidate = jwk2.crv === "P-384"; - break; - case "ES512": - candidate = jwk2.crv === "P-521"; - break; - case "Ed25519": - case "EdDSA": - candidate = jwk2.crv === "Ed25519"; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new JWKSNoMatchingKey(); - } - if (length !== 1) { - const error49 = new JWKSMultipleMatchingKeys(); - const _cached2 = __privateGet(this, _cached); - error49[Symbol.asyncIterator] = async function* () { - for (const jwk2 of candidates) { - try { - yield await importWithAlgCache(_cached2, jwk2, alg2); - } catch { - } - } - }; - throw error49; - } - return importWithAlgCache(__privateGet(this, _cached), jwk, alg2); - } -}; -_jwks = new WeakMap(); -_cached = new WeakMap(); -async function importWithAlgCache(cache3, jwk, alg2) { - const cached2 = cache3.get(jwk) || cache3.set(jwk, {}).get(jwk); - if (cached2[alg2] === void 0) { - const key = await importJWK({ ...jwk, ext: true }, alg2); - if (key instanceof Uint8Array || key.type !== "public") { - throw new JWKSInvalid("JSON Web Key Set members must be public keys"); - } - cached2[alg2] = key; - } - return cached2[alg2]; -} -function createLocalJWKSet(jwks) { - const set2 = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => structuredClone(set2.jwks()), - enumerable: false, - configurable: false, - writable: false - } - }); - return localJWKSet; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js -function isCloudflareWorkers() { - return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; -} -var USER_AGENT; -if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { - const NAME = "jose"; - const VERSION2 = "v6.2.2"; - USER_AGENT = `${NAME}/${VERSION2}`; -} -var customFetch = Symbol(); -async function fetchJwks(url2, headers, signal, fetchImpl = fetch) { - const response = await fetchImpl(url2, { - method: "GET", - signal, - redirect: "manual", - headers - }).catch((err) => { - if (err.name === "TimeoutError") { - throw new JWKSTimeout(); - } - throw err; - }); - if (response.status !== 200) { - throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); - } - try { - return await response.json(); - } catch { - throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); - } -} -var jwksCache = Symbol(); -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== "object" || input === null) { - return false; - } - if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!("jwks" in input) || !isObject3(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject3)) { - return false; - } - return true; -} -var _url2, _timeoutDuration, _cooldownDuration, _cacheMaxAge, _jwksTimestamp, _pendingFetch, _headers, _customFetch, _local, _cache; -var RemoteJWKSet = class { - constructor(url2, options) { - __privateAdd(this, _url2); - __privateAdd(this, _timeoutDuration); - __privateAdd(this, _cooldownDuration); - __privateAdd(this, _cacheMaxAge); - __privateAdd(this, _jwksTimestamp); - __privateAdd(this, _pendingFetch); - __privateAdd(this, _headers); - __privateAdd(this, _customFetch); - __privateAdd(this, _local); - __privateAdd(this, _cache); - if (!(url2 instanceof URL)) { - throw new TypeError("url must be an instance of URL"); - } - __privateSet(this, _url2, new URL(url2.href)); - __privateSet(this, _timeoutDuration, typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3); - __privateSet(this, _cooldownDuration, typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4); - __privateSet(this, _cacheMaxAge, typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5); - __privateSet(this, _headers, new Headers(options?.headers)); - if (USER_AGENT && !__privateGet(this, _headers).has("User-Agent")) { - __privateGet(this, _headers).set("User-Agent", USER_AGENT); - } - if (!__privateGet(this, _headers).has("accept")) { - __privateGet(this, _headers).set("accept", "application/json"); - __privateGet(this, _headers).append("accept", "application/jwk-set+json"); - } - __privateSet(this, _customFetch, options?.[customFetch]); - if (options?.[jwksCache] !== void 0) { - __privateSet(this, _cache, options?.[jwksCache]); - if (isFreshJwksCache(options?.[jwksCache], __privateGet(this, _cacheMaxAge))) { - __privateSet(this, _jwksTimestamp, __privateGet(this, _cache).uat); - __privateSet(this, _local, createLocalJWKSet(__privateGet(this, _cache).jwks)); - } - } - } - pendingFetch() { - return !!__privateGet(this, _pendingFetch); - } - coolingDown() { - return typeof __privateGet(this, _jwksTimestamp) === "number" ? Date.now() < __privateGet(this, _jwksTimestamp) + __privateGet(this, _cooldownDuration) : false; - } - fresh() { - return typeof __privateGet(this, _jwksTimestamp) === "number" ? Date.now() < __privateGet(this, _jwksTimestamp) + __privateGet(this, _cacheMaxAge) : false; - } - jwks() { - return __privateGet(this, _local)?.jwks(); - } - async getKey(protectedHeader, token) { - if (!__privateGet(this, _local) || !this.fresh()) { - await this.reload(); - } - try { - return await __privateGet(this, _local).call(this, protectedHeader, token); - } catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return __privateGet(this, _local).call(this, protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (__privateGet(this, _pendingFetch) && isCloudflareWorkers()) { - __privateSet(this, _pendingFetch, void 0); - } - __privateGet(this, _pendingFetch) || __privateSet(this, _pendingFetch, fetchJwks(__privateGet(this, _url2).href, __privateGet(this, _headers), AbortSignal.timeout(__privateGet(this, _timeoutDuration)), __privateGet(this, _customFetch)).then((json2) => { - __privateSet(this, _local, createLocalJWKSet(json2)); - if (__privateGet(this, _cache)) { - __privateGet(this, _cache).uat = Date.now(); - __privateGet(this, _cache).jwks = json2; - } - __privateSet(this, _jwksTimestamp, Date.now()); - __privateSet(this, _pendingFetch, void 0); - }).catch((err) => { - __privateSet(this, _pendingFetch, void 0); - throw err; - })); - await __privateGet(this, _pendingFetch); - } -}; -_url2 = new WeakMap(); -_timeoutDuration = new WeakMap(); -_cooldownDuration = new WeakMap(); -_cacheMaxAge = new WeakMap(); -_jwksTimestamp = new WeakMap(); -_pendingFetch = new WeakMap(); -_headers = new WeakMap(); -_customFetch = new WeakMap(); -_local = new WeakMap(); -_cache = new WeakMap(); -function createRemoteJWKSet(url2, options) { - const set2 = new RemoteJWKSet(url2, options); - const remoteJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set2.coolingDown(), - enumerable: true, - configurable: false - }, - fresh: { - get: () => set2.fresh(), - enumerable: true, - configurable: false - }, - reload: { - value: () => set2.reload(), - enumerable: true, - configurable: false, - writable: false - }, - reloading: { - get: () => set2.pendingFetch(), - enumerable: true, - configurable: false - }, - jwks: { - value: () => set2.jwks(), - enumerable: true, - configurable: false, - writable: false - } - }); - return remoteJWKSet; -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js -function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === "string") { - const parts = token.split("."); - if (parts.length === 3 || parts.length === 5) { - ; - [protectedB64u] = parts; - } - } else if (typeof token === "object" && token) { - if ("protected" in token) { - protectedB64u = token.protected; - } else { - throw new TypeError("Token does not contain a Protected Header"); - } - } - try { - if (typeof protectedB64u !== "string" || !protectedB64u) { - throw new Error(); - } - const result = JSON.parse(decoder.decode(decode3(protectedB64u))); - if (!isObject3(result)) { - throw new Error(); - } - return result; - } catch { - throw new TypeError("Invalid Token or Protected Header formatting"); - } -} - -// ../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js -function decodeJwt(jwt2) { - if (typeof jwt2 !== "string") - throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); - const { 1: payload, length } = jwt2.split("."); - if (length === 5) - throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); - if (length !== 3) - throw new JWTInvalid("Invalid JWT"); - if (!payload) - throw new JWTInvalid("JWTs must contain a payload"); - let decoded; - try { - decoded = decode3(payload); - } catch { - throw new JWTInvalid("Failed to base64url decode the payload"); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } catch { - throw new JWTInvalid("Failed to parse the decoded payload as JSON"); - } - if (!isObject3(result)) - throw new JWTInvalid("Invalid JWT Claims Set"); - return result; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/jwt.mjs -async function signJWT(payload, secret, expiresIn = 3600) { - return await new SignJWT(payload).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret)); -} -async function verifyJWT(token, secret) { - try { - return (await jwtVerify(token, new TextEncoder().encode(secret))).payload; - } catch { - return null; - } -} -var info = new Uint8Array([ - 66, - 101, - 116, - 116, - 101, - 114, - 65, - 117, - 116, - 104, - 46, - 106, - 115, - 32, - 71, - 101, - 110, - 101, - 114, - 97, - 116, - 101, - 100, - 32, - 69, - 110, - 99, - 114, - 121, - 112, - 116, - 105, - 111, - 110, - 32, - 75, - 101, - 121 -]); -var now = () => Date.now() / 1e3 | 0; -var alg = "dir"; -var enc = "A256CBC-HS512"; -function deriveEncryptionSecret(secret, salt) { - return hkdf(sha256, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64); -} -function getCurrentSecret(secret) { - if (typeof secret === "string") return secret; - const value = secret.keys.get(secret.currentVersion); - if (!value) throw new Error(`Secret version ${secret.currentVersion} not found in keys`); - return value; -} -function getAllSecrets(secret) { - if (typeof secret === "string") return [{ - version: 0, - value: secret - }]; - const result = []; - for (const [version3, value] of secret.keys) result.push({ - version: version3, - value - }); - if (secret.legacySecret && !result.some((s) => s.value === secret.legacySecret)) result.push({ - version: -1, - value: secret.legacySecret - }); - return result; -} -async function symmetricEncodeJWT(payload, secret, salt, expiresIn = 3600) { - const encryptionSecret = deriveEncryptionSecret(getCurrentSecret(secret), salt); - const thumbprint = await calculateJwkThumbprint({ - kty: "oct", - k: base64url_exports.encode(encryptionSecret) - }, "sha256"); - return await new EncryptJWT(payload).setProtectedHeader({ - alg, - enc, - kid: thumbprint - }).setIssuedAt().setExpirationTime(now() + expiresIn).setJti(crypto.randomUUID()).encrypt(encryptionSecret); -} -var jwtDecryptOpts = { - clockTolerance: 15, - keyManagementAlgorithms: [alg], - contentEncryptionAlgorithms: [enc, "A256GCM"] -}; -async function symmetricDecodeJWT(token, secret, salt) { - if (!token) return null; - let hasKid = false; - try { - hasKid = decodeProtectedHeader(token).kid !== void 0; - } catch { - return null; - } - try { - const secrets = getAllSecrets(secret); - const { payload } = await jwtDecrypt(token, async (protectedHeader) => { - const kid = protectedHeader.kid; - if (kid !== void 0) { - for (const s of secrets) { - const encryptionSecret = deriveEncryptionSecret(s.value, salt); - if (kid === await calculateJwkThumbprint({ - kty: "oct", - k: base64url_exports.encode(encryptionSecret) - }, "sha256")) return encryptionSecret; - } - throw new Error("no matching decryption secret"); - } - if (secrets.length === 1) return deriveEncryptionSecret(secrets[0].value, salt); - return deriveEncryptionSecret(secrets[0].value, salt); - }, jwtDecryptOpts); - return payload; - } catch { - if (hasKid) return null; - const secrets = getAllSecrets(secret); - if (secrets.length <= 1) return null; - for (let i = 1; i < secrets.length; i++) try { - const s = secrets[i]; - const { payload } = await jwtDecrypt(token, deriveEncryptionSecret(s.value, salt), jwtDecryptOpts); - return payload; - } catch { - continue; - } - return null; - } -} - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/password.node.mjs -import { randomBytes, scrypt } from "node:crypto"; -var config2 = { - N: 16384, - r: 16, - p: 1, - dkLen: 64 -}; -function generateKey(password, salt) { - return new Promise((resolve2, reject) => { - scrypt( - password.normalize("NFKC"), - salt, - config2.dkLen, - { - N: config2.N, - r: config2.r, - p: config2.p, - maxmem: 128 * config2.N * config2.r * 2 - }, - (err, key) => { - if (err) - reject(err); - else - resolve2(key); - } - ); - }); -} -async function hashPassword(password) { - const salt = randomBytes(16).toString("hex"); - const key = await generateKey(password, salt); - return `${salt}:${key.toString("hex")}`; -} -async function verifyPassword(hash2, password) { - const [salt, key] = hash2.split(":"); - if (!salt || !key) { - throw new Error("Invalid password hash"); - } - const targetKey = await generateKey(password, salt); - return targetKey.toString("hex") === key; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/password.mjs -var hashPassword$1 = hashPassword; -var verifyPassword$1 = async ({ hash: hash2, password }) => { - return verifyPassword(hash2, password); -}; - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/base64.mjs -function getAlphabet(urlSafe) { - return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -} -function base64Encode(data, alphabet, padding) { - let result = ""; - let buffer = 0; - let shift = 0; - for (const byte of data) { - buffer = buffer << 8 | byte; - shift += 8; - while (shift >= 6) { - shift -= 6; - result += alphabet[buffer >> shift & 63]; - } - } - if (shift > 0) { - result += alphabet[buffer << 6 - shift & 63]; - } - if (padding) { - const padCount = (4 - result.length % 4) % 4; - result += "=".repeat(padCount); - } - return result; -} -function base64Decode(data, alphabet) { - const decodeMap = /* @__PURE__ */ new Map(); - for (let i = 0; i < alphabet.length; i++) { - decodeMap.set(alphabet[i], i); - } - const result = []; - let buffer = 0; - let bitsCollected = 0; - for (const char of data) { - if (char === "=") - break; - const value = decodeMap.get(char); - if (value === void 0) { - throw new Error(`Invalid Base64 character: ${char}`); - } - buffer = buffer << 6 | value; - bitsCollected += 6; - if (bitsCollected >= 8) { - bitsCollected -= 8; - result.push(buffer >> bitsCollected & 255); - } - } - return Uint8Array.from(result); -} -var base643 = { - encode(data, options = {}) { - const alphabet = getAlphabet(false); - const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data); - return base64Encode(buffer, alphabet, options.padding ?? true); - }, - decode(data) { - if (typeof data !== "string") { - data = new TextDecoder().decode(data); - } - const urlSafe = data.includes("-") || data.includes("_"); - const alphabet = getAlphabet(urlSafe); - return base64Decode(data, alphabet); - } -}; -var base64Url = { - encode(data, options = {}) { - const alphabet = getAlphabet(true); - const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data); - return base64Encode(buffer, alphabet, options.padding ?? true); - }, - decode(data) { - const urlSafe = data.includes("-") || data.includes("_"); - const alphabet = getAlphabet(urlSafe); - return base64Decode(data, alphabet); - } -}; - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/index.mjs -function getWebcryptoSubtle() { - const cr = typeof globalThis !== "undefined" && globalThis.crypto; - if (cr && typeof cr.subtle === "object" && cr.subtle != null) - return cr.subtle; - throw new Error("crypto.subtle must be defined"); -} - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hash.mjs -function createHash(algorithm2, encoding) { - return { - digest: async (input) => { - const encoder3 = new TextEncoder(); - const data = typeof input === "string" ? encoder3.encode(input) : input; - const hashBuffer = await getWebcryptoSubtle().digest(algorithm2, data); - if (encoding === "hex") { - const hashArray = Array.from(new Uint8Array(hashBuffer)); - const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); - return hashHex; - } - if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { - if (encoding.includes("url")) { - return base64Url.encode(hashBuffer, { - padding: encoding !== "base64urlnopad" - }); - } - const hashBase64 = base643.encode(hashBuffer); - return hashBase64; - } - return hashBuffer; - } - }; -} - -// ../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/utils.js -function isBytes2(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; -} -function abool(b) { - if (typeof b !== "boolean") - throw new TypeError(`boolean expected, not ${b}`); -} -function anumber2(n) { - if (typeof n !== "number") - throw new TypeError("number expected, got " + typeof n); - if (!Number.isSafeInteger(n) || n < 0) - throw new RangeError("positive integer expected, got " + n); -} -function abytes2(value, length, title = "") { - const bytes = isBytes2(value); - const len = value?.length; - const needsLen = length !== void 0; - if (!bytes || needsLen && len !== length) { - const prefix = title && `"${title}" `; - const ofLen = needsLen ? ` of length ${length}` : ""; - const got = bytes ? `length=${len}` : `type=${typeof value}`; - const message2 = prefix + "expected Uint8Array" + ofLen + ", got " + got; - if (!bytes) - throw new TypeError(message2); - throw new RangeError(message2); - } - return value; -} -function aexists2(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function aoutput2(out, instance, onlyAligned = false) { - abytes2(out, void 0, "output"); - const min = instance.outputLen; - if (out.length < min) { - throw new RangeError("digestInto() expects output buffer of length at least " + min); - } - if (onlyAligned && !isAligned32(out)) - throw new Error("invalid output, must be aligned"); -} -function u32(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -} -function clean2(...arrays) { - for (let i = 0; i < arrays.length; i++) { - arrays[i].fill(0); - } -} -function createView2(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -} -var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); -var byteSwap = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; -var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0; -var byteSwap32 = (arr) => { - for (let i = 0; i < arr.length; i++) - arr[i] = byteSwap(arr[i]); - return arr; -}; -var swap32IfBE = isLE ? (u) => u : byteSwap32; -var hasHexBuiltin = /* @__PURE__ */ (() => ( - // @ts-ignore - typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" -))(); -var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); -function bytesToHex(bytes) { - abytes2(bytes); - if (hasHexBuiltin) - return bytes.toHex(); - let hex4 = ""; - for (let i = 0; i < bytes.length; i++) { - hex4 += hexes[bytes[i]]; - } - return hex4; -} -var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; -function asciiToBase16(ch) { - if (ch >= asciis._0 && ch <= asciis._9) - return ch - asciis._0; - if (ch >= asciis.A && ch <= asciis.F) - return ch - (asciis.A - 10); - if (ch >= asciis.a && ch <= asciis.f) - return ch - (asciis.a - 10); - return; -} -function hexToBytes(hex4) { - if (typeof hex4 !== "string") - throw new TypeError("hex string expected, got " + typeof hex4); - if (hasHexBuiltin) { - try { - return Uint8Array.fromHex(hex4); - } catch (error49) { - if (error49 instanceof SyntaxError) - throw new RangeError(error49.message); - throw error49; - } - } - const hl = hex4.length; - const al = hl / 2; - if (hl % 2) - throw new RangeError("hex string expected, got unpadded hex of length " + hl); - const array2 = new Uint8Array(al); - for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { - const n1 = asciiToBase16(hex4.charCodeAt(hi)); - const n2 = asciiToBase16(hex4.charCodeAt(hi + 1)); - if (n1 === void 0 || n2 === void 0) { - const char = hex4[hi] + hex4[hi + 1]; - throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi); - } - array2[ai] = n1 * 16 + n2; - } - return array2; -} -function utf8ToBytes(str) { - if (typeof str !== "string") - throw new TypeError("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); -} -function overlapBytes(a, b) { - if (!a.byteLength || !b.byteLength) - return false; - return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy - a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end - b.byteOffset < a.byteOffset + a.byteLength; -} -function concatBytes(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a = arrays[i]; - abytes2(a); - sum += a.length; - } - const res = new Uint8Array(sum); - for (let i = 0, pad = 0; i < arrays.length; i++) { - const a = arrays[i]; - res.set(a, pad); - pad += a.length; - } - return res; -} -function checkOpts(defaults, opts) { - if (opts == null || typeof opts !== "object") - throw new Error("options must be defined"); - const merged = Object.assign(defaults, opts); - return merged; -} -function equalBytes(a, b) { - if (a.length !== b.length) - return false; - let diff = 0; - for (let i = 0; i < a.length; i++) - diff |= a[i] ^ b[i]; - return diff === 0; -} -function wrapMacConstructor(keyLen, macCons, fromMsg) { - const mac3 = macCons; - const getArgs = fromMsg || (() => []); - const macC = (msg, key) => mac3(key, ...getArgs(msg)).update(msg).digest(); - const tmp = mac3(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0))); - macC.outputLen = tmp.outputLen; - macC.blockLen = tmp.blockLen; - macC.create = (key, ...args) => mac3(key, ...args); - return macC; -} -var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => { - function wrappedCipher(key, ...args) { - abytes2(key, void 0, "key"); - if (params.nonceLength !== void 0) { - const nonce = args[0]; - abytes2(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce"); - } - const tagl = params.tagLength; - if (tagl && args[1] !== void 0) - abytes2(args[1], void 0, "AAD"); - const cipher = constructor(key, ...args); - const checkOutput = (fnLength, output) => { - if (output !== void 0) { - if (fnLength !== 2) - throw new Error("cipher output not supported"); - abytes2(output, void 0, "output"); - } - }; - let called = false; - const wrCipher = { - encrypt(data, output) { - if (called) - throw new Error("cannot encrypt() twice with same key + nonce"); - called = true; - abytes2(data); - checkOutput(cipher.encrypt.length, output); - return cipher.encrypt(data, output); - }, - decrypt(data, output) { - abytes2(data); - if (tagl && data.length < tagl) - throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl); - checkOutput(cipher.decrypt.length, output); - return cipher.decrypt(data, output); - } - }; - return wrCipher; - } - Object.assign(wrappedCipher, params); - return wrappedCipher; -}; -function getOutput(expectedLength, out, onlyAligned = true) { - if (out === void 0) - return new Uint8Array(expectedLength); - abytes2(out, void 0, "output"); - if (out.length !== expectedLength) - throw new Error('"output" expected Uint8Array of length ' + expectedLength + ", got: " + out.length); - if (onlyAligned && !isAligned32(out)) - throw new Error("invalid output, must be aligned"); - return out; -} -function u64Lengths(dataLength, aadLength, isLE2) { - anumber2(dataLength); - anumber2(aadLength); - abool(isLE2); - const num = new Uint8Array(16); - const view = createView2(num); - view.setBigUint64(0, BigInt(aadLength), isLE2); - view.setBigUint64(8, BigInt(dataLength), isLE2); - return num; -} -function isAligned32(bytes) { - return bytes.byteOffset % 4 === 0; -} -function copyBytes(bytes) { - return Uint8Array.from(abytes2(bytes)); -} -function randomBytes2(bytesLength = 32) { - anumber2(bytesLength); - const cr = typeof globalThis === "object" ? globalThis.crypto : null; - if (typeof cr?.getRandomValues !== "function") - throw new Error("crypto.getRandomValues must be defined"); - return cr.getRandomValues(new Uint8Array(bytesLength)); -} -function managedNonce(fn, randomBytes_ = randomBytes2) { - const { nonceLength } = fn; - anumber2(nonceLength); - const addNonce = (nonce, ciphertext, plaintext) => { - const out = concatBytes(nonce, ciphertext); - if (!overlapBytes(plaintext, ciphertext)) - ciphertext.fill(0); - return out; - }; - const res = (key, ...args) => ({ - encrypt(plaintext) { - abytes2(plaintext); - const nonce = randomBytes_(nonceLength); - const encrypted = fn(key, nonce, ...args).encrypt(plaintext); - if (encrypted instanceof Promise) - return encrypted.then((ct) => addNonce(nonce, ct, plaintext)); - return addNonce(nonce, encrypted, plaintext); - }, - decrypt(ciphertext) { - abytes2(ciphertext); - const nonce = ciphertext.subarray(0, nonceLength); - const decrypted = ciphertext.subarray(nonceLength); - return fn(key, nonce, ...args).decrypt(decrypted); - } - }); - if ("blockSize" in fn) - res.blockSize = fn.blockSize; - if ("tagLength" in fn) - res.tagLength = fn.tagLength; - return res; -} - -// ../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_arx.js -var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0)); -var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))(); -var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))(); -function rotl(a, b) { - return a << b | a >>> 32 - b; -} -var BLOCK_LEN = 64; -var BLOCK_LEN32 = 16; -var MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)(); -var U32_EMPTY = /* @__PURE__ */ Uint32Array.of(); -function runCipher(core, sigma, key, nonce, data, output, counter, rounds) { - const len = data.length; - const block = new Uint8Array(BLOCK_LEN); - const b32 = u32(block); - const isAligned = isLE && isAligned32(data) && isAligned32(output); - const d32 = isAligned ? u32(data) : U32_EMPTY; - const o32 = isAligned ? u32(output) : U32_EMPTY; - if (!isLE) { - for (let pos = 0; pos < len; counter++) { - core(sigma, key, nonce, b32, counter, rounds); - swap32IfBE(b32); - if (counter >= MAX_COUNTER) - throw new Error("arx: counter overflow"); - const take = Math.min(BLOCK_LEN, len - pos); - for (let j = 0, posj; j < take; j++) { - posj = pos + j; - output[posj] = data[posj] ^ block[j]; - } - pos += take; - } - return; - } - for (let pos = 0; pos < len; counter++) { - core(sigma, key, nonce, b32, counter, rounds); - if (counter >= MAX_COUNTER) - throw new Error("arx: counter overflow"); - const take = Math.min(BLOCK_LEN, len - pos); - if (isAligned && take === BLOCK_LEN) { - const pos32 = pos / 4; - if (pos % 4 !== 0) - throw new Error("arx: invalid block position"); - for (let j = 0, posj; j < BLOCK_LEN32; j++) { - posj = pos32 + j; - o32[posj] = d32[posj] ^ b32[j]; - } - pos += BLOCK_LEN; - continue; - } - for (let j = 0, posj; j < take; j++) { - posj = pos + j; - output[posj] = data[posj] ^ block[j]; - } - pos += take; - } -} -function createCipher(core, opts) { - const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); - if (typeof core !== "function") - throw new Error("core must be a function"); - anumber2(counterLength); - anumber2(rounds); - abool(counterRight); - abool(allowShortKeys); - return (key, nonce, data, output, counter = 0) => { - abytes2(key, void 0, "key"); - abytes2(nonce, void 0, "nonce"); - abytes2(data, void 0, "data"); - const len = data.length; - output = getOutput(len, output, false); - anumber2(counter); - if (counter < 0 || counter >= MAX_COUNTER) - throw new Error("arx: counter overflow"); - const toClean = []; - let l = key.length; - let k; - let sigma; - if (l === 32) { - toClean.push(k = copyBytes(key)); - sigma = sigma32_32; - } else if (l === 16 && allowShortKeys) { - k = new Uint8Array(32); - k.set(key); - k.set(key, 16); - sigma = sigma16_32; - toClean.push(k); - } else { - abytes2(key, 32, "arx key"); - throw new Error("invalid key size"); - } - if (!isLE || !isAligned32(nonce)) - toClean.push(nonce = copyBytes(nonce)); - let k32 = u32(k); - if (extendNonceFn) { - if (nonce.length !== 24) - throw new Error(`arx: extended nonce must be 24 bytes`); - const n16 = nonce.subarray(0, 16); - if (isLE) - extendNonceFn(sigma, k32, u32(n16), k32); - else { - const sigmaRaw = swap32IfBE(Uint32Array.from(sigma)); - extendNonceFn(sigmaRaw, k32, u32(n16), k32); - clean2(sigmaRaw); - swap32IfBE(k32); - } - nonce = nonce.subarray(16); - } else if (!isLE) - swap32IfBE(k32); - const nonceNcLen = 16 - counterLength; - if (nonceNcLen !== nonce.length) - throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); - if (nonceNcLen !== 12) { - const nc = new Uint8Array(12); - nc.set(nonce, counterRight ? 0 : 12 - nonce.length); - nonce = nc; - toClean.push(nonce); - } - const n32 = swap32IfBE(u32(nonce)); - try { - runCipher(core, sigma, k32, n32, data, output, counter, rounds); - return output; - } finally { - clean2(...toClean); - } - }; -} - -// ../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_poly1305.js -function u8to16(a, i) { - return a[i++] & 255 | (a[i++] & 255) << 8; -} -var Poly1305 = class { - // Can be speed-up using BigUint64Array, at the cost of complexity - constructor(key) { - __publicField(this, "blockLen", 16); - __publicField(this, "outputLen", 16); - __publicField(this, "buffer", new Uint8Array(16)); - __publicField(this, "r", new Uint16Array(10)); - // Allocating 1 array with .subarray() here is slower than 3 - __publicField(this, "h", new Uint16Array(10)); - __publicField(this, "pad", new Uint16Array(8)); - __publicField(this, "pos", 0); - __publicField(this, "finished", false); - __publicField(this, "destroyed", false); - key = copyBytes(abytes2(key, 32, "key")); - const t0 = u8to16(key, 0); - const t1 = u8to16(key, 2); - const t2 = u8to16(key, 4); - const t3 = u8to16(key, 6); - const t4 = u8to16(key, 8); - const t5 = u8to16(key, 10); - const t6 = u8to16(key, 12); - const t7 = u8to16(key, 14); - this.r[0] = t0 & 8191; - this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; - this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; - this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; - this.r[4] = (t3 >>> 4 | t4 << 12) & 255; - this.r[5] = t4 >>> 1 & 8190; - this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; - this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; - this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; - this.r[9] = t7 >>> 5 & 127; - for (let i = 0; i < 8; i++) - this.pad[i] = u8to16(key, 16 + 2 * i); - } - process(data, offset, isLast = false) { - const hibit = isLast ? 0 : 1 << 11; - const { h, r } = this; - const r0 = r[0]; - const r1 = r[1]; - const r2 = r[2]; - const r3 = r[3]; - const r4 = r[4]; - const r5 = r[5]; - const r6 = r[6]; - const r7 = r[7]; - const r8 = r[8]; - const r9 = r[9]; - const t0 = u8to16(data, offset + 0); - const t1 = u8to16(data, offset + 2); - const t2 = u8to16(data, offset + 4); - const t3 = u8to16(data, offset + 6); - const t4 = u8to16(data, offset + 8); - const t5 = u8to16(data, offset + 10); - const t6 = u8to16(data, offset + 12); - const t7 = u8to16(data, offset + 14); - let h0 = h[0] + (t0 & 8191); - let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191); - let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191); - let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191); - let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191); - let h5 = h[5] + (t4 >>> 1 & 8191); - let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191); - let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191); - let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191); - let h9 = h[9] + (t7 >>> 5 | hibit); - let c = 0; - let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); - c = d0 >>> 13; - d0 &= 8191; - d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); - c += d0 >>> 13; - d0 &= 8191; - let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); - c = d1 >>> 13; - d1 &= 8191; - d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); - c += d1 >>> 13; - d1 &= 8191; - let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); - c = d2 >>> 13; - d2 &= 8191; - d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); - c += d2 >>> 13; - d2 &= 8191; - let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); - c = d3 >>> 13; - d3 &= 8191; - d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); - c += d3 >>> 13; - d3 &= 8191; - let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; - c = d4 >>> 13; - d4 &= 8191; - d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); - c += d4 >>> 13; - d4 &= 8191; - let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; - c = d5 >>> 13; - d5 &= 8191; - d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); - c += d5 >>> 13; - d5 &= 8191; - let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; - c = d6 >>> 13; - d6 &= 8191; - d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); - c += d6 >>> 13; - d6 &= 8191; - let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; - c = d7 >>> 13; - d7 &= 8191; - d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); - c += d7 >>> 13; - d7 &= 8191; - let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; - c = d8 >>> 13; - d8 &= 8191; - d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); - c += d8 >>> 13; - d8 &= 8191; - let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; - c = d9 >>> 13; - d9 &= 8191; - d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; - c += d9 >>> 13; - d9 &= 8191; - c = (c << 2) + c | 0; - c = c + d0 | 0; - d0 = c & 8191; - c = c >>> 13; - d1 += c; - h[0] = d0; - h[1] = d1; - h[2] = d2; - h[3] = d3; - h[4] = d4; - h[5] = d5; - h[6] = d6; - h[7] = d7; - h[8] = d8; - h[9] = d9; - } - finalize() { - const { h, pad } = this; - const g = new Uint16Array(10); - let c = h[1] >>> 13; - h[1] &= 8191; - for (let i = 2; i < 10; i++) { - h[i] += c; - c = h[i] >>> 13; - h[i] &= 8191; - } - h[0] += c * 5; - c = h[0] >>> 13; - h[0] &= 8191; - h[1] += c; - c = h[1] >>> 13; - h[1] &= 8191; - h[2] += c; - g[0] = h[0] + 5; - c = g[0] >>> 13; - g[0] &= 8191; - for (let i = 1; i < 10; i++) { - g[i] = h[i] + c; - c = g[i] >>> 13; - g[i] &= 8191; - } - g[9] -= 1 << 13; - let mask = (c ^ 1) - 1; - for (let i = 0; i < 10; i++) - g[i] &= mask; - mask = ~mask; - for (let i = 0; i < 10; i++) - h[i] = h[i] & mask | g[i]; - h[0] = (h[0] | h[1] << 13) & 65535; - h[1] = (h[1] >>> 3 | h[2] << 10) & 65535; - h[2] = (h[2] >>> 6 | h[3] << 7) & 65535; - h[3] = (h[3] >>> 9 | h[4] << 4) & 65535; - h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535; - h[5] = (h[6] >>> 2 | h[7] << 11) & 65535; - h[6] = (h[7] >>> 5 | h[8] << 8) & 65535; - h[7] = (h[8] >>> 8 | h[9] << 5) & 65535; - let f = h[0] + pad[0]; - h[0] = f & 65535; - for (let i = 1; i < 8; i++) { - f = (h[i] + pad[i] | 0) + (f >>> 16) | 0; - h[i] = f & 65535; - } - clean2(g); - } - update(data) { - aexists2(this); - abytes2(data); - data = copyBytes(data); - const { buffer, blockLen } = this; - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - for (; blockLen <= len - pos; pos += blockLen) - this.process(data, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(buffer, 0, false); - this.pos = 0; - } - } - return this; - } - destroy() { - this.destroyed = true; - clean2(this.h, this.r, this.buffer, this.pad); - } - digestInto(out) { - aexists2(this); - aoutput2(out, this); - this.finished = true; - const { buffer, h } = this; - let { pos } = this; - if (pos) { - buffer[pos++] = 1; - for (; pos < 16; pos++) - buffer[pos] = 0; - this.process(buffer, 0, true); - } - this.finalize(); - let opos = 0; - for (let i = 0; i < 8; i++) { - out[opos++] = h[i] >>> 0; - out[opos++] = h[i] >>> 8; - } - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } -}; -var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key)); - -// ../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/chacha.js -function chachaCore(s, k, n, out, cnt, rounds = 20) { - let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; - let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; - for (let r = 0; r < rounds; r += 2) { - x00 = x00 + x04 | 0; - x12 = rotl(x12 ^ x00, 16); - x08 = x08 + x12 | 0; - x04 = rotl(x04 ^ x08, 12); - x00 = x00 + x04 | 0; - x12 = rotl(x12 ^ x00, 8); - x08 = x08 + x12 | 0; - x04 = rotl(x04 ^ x08, 7); - x01 = x01 + x05 | 0; - x13 = rotl(x13 ^ x01, 16); - x09 = x09 + x13 | 0; - x05 = rotl(x05 ^ x09, 12); - x01 = x01 + x05 | 0; - x13 = rotl(x13 ^ x01, 8); - x09 = x09 + x13 | 0; - x05 = rotl(x05 ^ x09, 7); - x02 = x02 + x06 | 0; - x14 = rotl(x14 ^ x02, 16); - x10 = x10 + x14 | 0; - x06 = rotl(x06 ^ x10, 12); - x02 = x02 + x06 | 0; - x14 = rotl(x14 ^ x02, 8); - x10 = x10 + x14 | 0; - x06 = rotl(x06 ^ x10, 7); - x03 = x03 + x07 | 0; - x15 = rotl(x15 ^ x03, 16); - x11 = x11 + x15 | 0; - x07 = rotl(x07 ^ x11, 12); - x03 = x03 + x07 | 0; - x15 = rotl(x15 ^ x03, 8); - x11 = x11 + x15 | 0; - x07 = rotl(x07 ^ x11, 7); - x00 = x00 + x05 | 0; - x15 = rotl(x15 ^ x00, 16); - x10 = x10 + x15 | 0; - x05 = rotl(x05 ^ x10, 12); - x00 = x00 + x05 | 0; - x15 = rotl(x15 ^ x00, 8); - x10 = x10 + x15 | 0; - x05 = rotl(x05 ^ x10, 7); - x01 = x01 + x06 | 0; - x12 = rotl(x12 ^ x01, 16); - x11 = x11 + x12 | 0; - x06 = rotl(x06 ^ x11, 12); - x01 = x01 + x06 | 0; - x12 = rotl(x12 ^ x01, 8); - x11 = x11 + x12 | 0; - x06 = rotl(x06 ^ x11, 7); - x02 = x02 + x07 | 0; - x13 = rotl(x13 ^ x02, 16); - x08 = x08 + x13 | 0; - x07 = rotl(x07 ^ x08, 12); - x02 = x02 + x07 | 0; - x13 = rotl(x13 ^ x02, 8); - x08 = x08 + x13 | 0; - x07 = rotl(x07 ^ x08, 7); - x03 = x03 + x04 | 0; - x14 = rotl(x14 ^ x03, 16); - x09 = x09 + x14 | 0; - x04 = rotl(x04 ^ x09, 12); - x03 = x03 + x04 | 0; - x14 = rotl(x14 ^ x03, 8); - x09 = x09 + x14 | 0; - x04 = rotl(x04 ^ x09, 7); - } - let oi = 0; - out[oi++] = y00 + x00 | 0; - out[oi++] = y01 + x01 | 0; - out[oi++] = y02 + x02 | 0; - out[oi++] = y03 + x03 | 0; - out[oi++] = y04 + x04 | 0; - out[oi++] = y05 + x05 | 0; - out[oi++] = y06 + x06 | 0; - out[oi++] = y07 + x07 | 0; - out[oi++] = y08 + x08 | 0; - out[oi++] = y09 + x09 | 0; - out[oi++] = y10 + x10 | 0; - out[oi++] = y11 + x11 | 0; - out[oi++] = y12 + x12 | 0; - out[oi++] = y13 + x13 | 0; - out[oi++] = y14 + x14 | 0; - out[oi++] = y15 + x15 | 0; -} -function hchacha(s, k, i, out) { - let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]), x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]), x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]), x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]); - for (let r = 0; r < 20; r += 2) { - x00 = x00 + x04 | 0; - x12 = rotl(x12 ^ x00, 16); - x08 = x08 + x12 | 0; - x04 = rotl(x04 ^ x08, 12); - x00 = x00 + x04 | 0; - x12 = rotl(x12 ^ x00, 8); - x08 = x08 + x12 | 0; - x04 = rotl(x04 ^ x08, 7); - x01 = x01 + x05 | 0; - x13 = rotl(x13 ^ x01, 16); - x09 = x09 + x13 | 0; - x05 = rotl(x05 ^ x09, 12); - x01 = x01 + x05 | 0; - x13 = rotl(x13 ^ x01, 8); - x09 = x09 + x13 | 0; - x05 = rotl(x05 ^ x09, 7); - x02 = x02 + x06 | 0; - x14 = rotl(x14 ^ x02, 16); - x10 = x10 + x14 | 0; - x06 = rotl(x06 ^ x10, 12); - x02 = x02 + x06 | 0; - x14 = rotl(x14 ^ x02, 8); - x10 = x10 + x14 | 0; - x06 = rotl(x06 ^ x10, 7); - x03 = x03 + x07 | 0; - x15 = rotl(x15 ^ x03, 16); - x11 = x11 + x15 | 0; - x07 = rotl(x07 ^ x11, 12); - x03 = x03 + x07 | 0; - x15 = rotl(x15 ^ x03, 8); - x11 = x11 + x15 | 0; - x07 = rotl(x07 ^ x11, 7); - x00 = x00 + x05 | 0; - x15 = rotl(x15 ^ x00, 16); - x10 = x10 + x15 | 0; - x05 = rotl(x05 ^ x10, 12); - x00 = x00 + x05 | 0; - x15 = rotl(x15 ^ x00, 8); - x10 = x10 + x15 | 0; - x05 = rotl(x05 ^ x10, 7); - x01 = x01 + x06 | 0; - x12 = rotl(x12 ^ x01, 16); - x11 = x11 + x12 | 0; - x06 = rotl(x06 ^ x11, 12); - x01 = x01 + x06 | 0; - x12 = rotl(x12 ^ x01, 8); - x11 = x11 + x12 | 0; - x06 = rotl(x06 ^ x11, 7); - x02 = x02 + x07 | 0; - x13 = rotl(x13 ^ x02, 16); - x08 = x08 + x13 | 0; - x07 = rotl(x07 ^ x08, 12); - x02 = x02 + x07 | 0; - x13 = rotl(x13 ^ x02, 8); - x08 = x08 + x13 | 0; - x07 = rotl(x07 ^ x08, 7); - x03 = x03 + x04 | 0; - x14 = rotl(x14 ^ x03, 16); - x09 = x09 + x14 | 0; - x04 = rotl(x04 ^ x09, 12); - x03 = x03 + x04 | 0; - x14 = rotl(x14 ^ x03, 8); - x09 = x09 + x14 | 0; - x04 = rotl(x04 ^ x09, 7); - } - let oi = 0; - out[oi++] = x00; - out[oi++] = x01; - out[oi++] = x02; - out[oi++] = x03; - out[oi++] = x12; - out[oi++] = x13; - out[oi++] = x14; - out[oi++] = x15; - swap32IfBE(out); -} -var xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { - counterRight: false, - counterLength: 8, - extendNonceFn: hchacha, - allowShortKeys: false -}); -var ZEROS16 = /* @__PURE__ */ new Uint8Array(16); -var updatePadded = (h, msg) => { - h.update(msg); - const leftover = msg.length % 16; - if (leftover) - h.update(ZEROS16.subarray(leftover)); -}; -var ZEROS32 = /* @__PURE__ */ new Uint8Array(32); -function computeTag(fn, key, nonce, ciphertext, AAD) { - if (AAD !== void 0) - abytes2(AAD, void 0, "AAD"); - const authKey = fn(key, nonce, ZEROS32); - const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true); - const h = poly1305.create(authKey); - if (AAD) - updatePadded(h, AAD); - updatePadded(h, ciphertext); - h.update(lengths); - const res = h.digest(); - clean2(authKey, lengths); - return res; -} -var _poly1305_aead = (xorStream) => (key, nonce, AAD) => { - const tagLength = 16; - return { - encrypt(plaintext, output) { - const plength = plaintext.length; - output = getOutput(plength + tagLength, output, false); - output.set(plaintext); - const oPlain = output.subarray(0, -tagLength); - xorStream(key, nonce, oPlain, oPlain, 1); - const tag2 = computeTag(xorStream, key, nonce, oPlain, AAD); - output.set(tag2, plength); - clean2(tag2); - return output; - }, - decrypt(ciphertext, output) { - output = getOutput(ciphertext.length - tagLength, output, false); - const data = ciphertext.subarray(0, -tagLength); - const passedTag = ciphertext.subarray(-tagLength); - const tag2 = computeTag(xorStream, key, nonce, data, AAD); - if (!equalBytes(passedTag, tag2)) { - clean2(tag2); - throw new Error("invalid tag"); - } - output.set(ciphertext.subarray(0, -tagLength)); - xorStream(key, nonce, output, output, 1); - clean2(tag2); - return output; - } - }; -}; -var xchacha20poly1305 = /* @__PURE__ */ wrapCipher( - { blockSize: 64, nonceLength: 24, tagLength: 16 }, - /* @__PURE__ */ _poly1305_aead(xchacha20) -); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/index.mjs -var ENVELOPE_PREFIX = "$ba$"; -function parseEnvelope(data) { - if (!data.startsWith(ENVELOPE_PREFIX)) return null; - const firstSep = 4; - const secondSep = data.indexOf("$", firstSep); - if (secondSep === -1) return null; - const version3 = parseInt(data.slice(firstSep, secondSep), 10); - if (!Number.isInteger(version3) || version3 < 0) return null; - return { - version: version3, - ciphertext: data.slice(secondSep + 1) - }; -} -function formatEnvelope(version3, ciphertext) { - return `${ENVELOPE_PREFIX}${version3}$${ciphertext}`; -} -async function rawEncrypt(secret, data) { - const keyAsBytes = await createHash("SHA-256").digest(secret); - const dataAsBytes = utf8ToBytes(data); - return bytesToHex(managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)).encrypt(dataAsBytes)); -} -async function rawDecrypt(secret, hex4) { - const keyAsBytes = await createHash("SHA-256").digest(secret); - const dataAsBytes = hexToBytes(hex4); - const chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)); - return new TextDecoder().decode(chacha.decrypt(dataAsBytes)); -} -var symmetricEncrypt = async ({ key, data }) => { - if (typeof key === "string") return rawEncrypt(key, data); - const secret = key.keys.get(key.currentVersion); - if (!secret) throw new Error(`Secret version ${key.currentVersion} not found in keys`); - const ciphertext = await rawEncrypt(secret, data); - return formatEnvelope(key.currentVersion, ciphertext); -}; -var symmetricDecrypt = async ({ key, data }) => { - if (typeof key === "string") return rawDecrypt(key, data); - const envelope = parseEnvelope(data); - if (envelope) { - const secret = key.keys.get(envelope.version); - if (!secret) throw new Error(`Secret version ${envelope.version} not found in keys (key may have been retired)`); - return rawDecrypt(secret, envelope.ciphertext); - } - if (key.legacySecret) return rawDecrypt(key.legacySecret, data); - throw new Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility."); -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/date.mjs -var getDate = (span, unit = "ms") => { - return new Date(Date.now() + (unit === "sec" ? span * 1e3 : span)); -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/index.mjs -init_get_tables(); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/schema.mjs -init_error2(); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/db.mjs -function filterOutputFields(data, additionalFields) { - if (!data || !additionalFields) return data; - const returnFiltered = Object.entries(additionalFields).filter(([, { returned }]) => returned === false).map(([key]) => key); - return Object.entries(structuredClone(data)).filter(([key]) => !returnFiltered.includes(key)).reduce((acc, [key, value]) => ({ - ...acc, - [key]: value - }), {}); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/schema.mjs -var cache2 = /* @__PURE__ */ new WeakMap(); -function getFields(options, modelName, mode) { - const cacheKey2 = `${modelName}:${mode}`; - if (!cache2.has(options)) cache2.set(options, /* @__PURE__ */ new Map()); - const tableCache = cache2.get(options); - if (tableCache.has(cacheKey2)) return tableCache.get(cacheKey2); - const coreSchema = mode === "output" ? getAuthTables(options)[modelName]?.fields ?? {} : {}; - const additionalFields = modelName === "user" || modelName === "session" || modelName === "account" ? options[modelName]?.additionalFields : void 0; - let schema3 = { - ...coreSchema, - ...additionalFields ?? {} - }; - for (const plugin of options.plugins || []) if (plugin.schema && plugin.schema[modelName]) schema3 = { - ...schema3, - ...plugin.schema[modelName].fields - }; - tableCache.set(cacheKey2, schema3); - return schema3; -} -function parseUserOutput(options, user) { - return filterOutputFields(user, getFields(options, "user", "output")); -} -function parseSessionOutput(options, session) { - return filterOutputFields(session, getFields(options, "session", "output")); -} -function parseAccountOutput(options, account) { - const { accessToken: _accessToken, refreshToken: _refreshToken, idToken: _idToken, accessTokenExpiresAt: _accessTokenExpiresAt, refreshTokenExpiresAt: _refreshTokenExpiresAt, password: _password, ...rest } = filterOutputFields(account, getFields(options, "account", "output")); - return rest; -} -function parseInputData(data, schema3) { - const action = schema3.action || "create"; - const fields = schema3.fields; - const parsedData = /* @__PURE__ */ Object.create(null); - for (const key in fields) { - if (key in data) { - if (fields[key].input === false) { - if (fields[key].defaultValue !== void 0) { - if (action !== "update") { - parsedData[key] = fields[key].defaultValue; - continue; - } - } - if (data[key]) throw APIError2.from("BAD_REQUEST", { - ...BASE_ERROR_CODES.FIELD_NOT_ALLOWED, - message: `${key} is not allowed to be set` - }); - continue; - } - if (fields[key].validator?.input && data[key] !== void 0) { - const result = fields[key].validator.input["~standard"].validate(data[key]); - if (result instanceof Promise) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED); - if ("issues" in result && result.issues) throw APIError2.from("BAD_REQUEST", { - ...BASE_ERROR_CODES.VALIDATION_ERROR, - message: result.issues[0]?.message || "Validation Error" - }); - parsedData[key] = result.value; - continue; - } - if (fields[key].transform?.input && data[key] !== void 0) { - parsedData[key] = fields[key].transform?.input(data[key]); - continue; - } - parsedData[key] = data[key]; - continue; - } - if (fields[key].defaultValue !== void 0 && action === "create") { - if (typeof fields[key].defaultValue === "function") { - parsedData[key] = fields[key].defaultValue(); - continue; - } - parsedData[key] = fields[key].defaultValue; - continue; - } - if (fields[key].required && action === "create") throw APIError2.from("BAD_REQUEST", { - ...BASE_ERROR_CODES.MISSING_FIELD, - message: `${key} is required` - }); - } - return parsedData; -} -function parseUserInput(options, user = {}, action) { - return parseInputData(user, { - fields: getFields(options, "user", "input"), - action - }); -} -function parseSessionInput(options, session, action) { - return parseInputData(session, { - fields: getFields(options, "session", "input"), - action - }); -} -function getSessionDefaultFields(options) { - const fields = getFields(options, "session", "input"); - const defaults = {}; - for (const key in fields) if (fields[key].defaultValue !== void 0) defaults[key] = typeof fields[key].defaultValue === "function" ? fields[key].defaultValue() : fields[key].defaultValue; - return defaults; -} -function mergeSchema(schema3, newSchema) { - if (!newSchema) return schema3; - for (const table in newSchema) { - const newModelName = newSchema[table]?.modelName; - if (newModelName) schema3[table].modelName = newModelName; - for (const field in schema3[table].fields) { - const newField = newSchema[table]?.fields?.[field]; - if (!newField) continue; - schema3[table].fields[field].fieldName = newField; - } - } - return schema3; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-promise.mjs -function isPromise(obj) { - return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/session-store.mjs -init_json(); -init_zod(); -var ALLOWED_COOKIE_SIZE = 4096; -var ESTIMATED_EMPTY_COOKIE_SIZE = 200; -var CHUNK_SIZE = ALLOWED_COOKIE_SIZE - ESTIMATED_EMPTY_COOKIE_SIZE; -function parseCookiesFromContext(ctx) { - const cookieHeader = ctx.headers?.get("cookie"); - if (!cookieHeader) return {}; - const cookies = {}; - const pairs = cookieHeader.split("; "); - for (const pair of pairs) { - const [name, ...valueParts] = pair.split("="); - if (name && valueParts.length > 0) cookies[name] = valueParts.join("="); - } - return cookies; -} -function getChunkIndex(cookieName) { - const parts = cookieName.split("."); - const lastPart = parts[parts.length - 1]; - const index = parseInt(lastPart || "0", 10); - return isNaN(index) ? 0 : index; -} -function readExistingChunks(cookieName, ctx) { - const chunks = {}; - const cookies = parseCookiesFromContext(ctx); - for (const [name, value] of Object.entries(cookies)) if (name.startsWith(cookieName)) chunks[name] = value; - return chunks; -} -function joinChunks(chunks) { - return Object.keys(chunks).sort((a, b) => { - return getChunkIndex(a) - getChunkIndex(b); - }).map((key) => chunks[key]).join(""); -} -function chunkCookie(storeName, cookie, chunks, logger2) { - const chunkCount = Math.ceil(cookie.value.length / CHUNK_SIZE); - if (chunkCount === 1) { - chunks[cookie.name] = cookie.value; - return [cookie]; - } - const cookies = []; - for (let i = 0; i < chunkCount; i++) { - const name = `${cookie.name}.${i}`; - const start = i * CHUNK_SIZE; - const value = cookie.value.substring(start, start + CHUNK_SIZE); - cookies.push({ - ...cookie, - name, - value - }); - chunks[name] = value; - } - logger2.debug(`CHUNKING_${storeName.toUpperCase()}_COOKIE`, { - message: `${storeName} cookie exceeds allowed ${ALLOWED_COOKIE_SIZE} bytes.`, - emptyCookieSize: ESTIMATED_EMPTY_COOKIE_SIZE, - valueSize: cookie.value.length, - chunkCount, - chunks: cookies.map((c) => c.value.length + ESTIMATED_EMPTY_COOKIE_SIZE) - }); - return cookies; -} -function getCleanCookies(chunks, cookieOptions) { - const cleanedChunks = {}; - for (const name in chunks) cleanedChunks[name] = { - name, - value: "", - attributes: { - ...cookieOptions, - maxAge: 0 - } - }; - return cleanedChunks; -} -var storeFactory = (storeName) => (cookieName, cookieOptions, ctx) => { - const chunks = readExistingChunks(cookieName, ctx); - const logger2 = ctx.context.logger; - return { - getValue() { - return joinChunks(chunks); - }, - hasChunks() { - return Object.keys(chunks).length > 0; - }, - chunk(value, options) { - const cleanedChunks = getCleanCookies(chunks, cookieOptions); - for (const name in chunks) delete chunks[name]; - const cookies = cleanedChunks; - const chunked = chunkCookie(storeName, { - name: cookieName, - value, - attributes: { - ...cookieOptions, - ...options - } - }, chunks, logger2); - for (const chunk of chunked) cookies[chunk.name] = chunk; - return Object.values(cookies); - }, - clean() { - const cleanedChunks = getCleanCookies(chunks, cookieOptions); - for (const name in chunks) delete chunks[name]; - return Object.values(cleanedChunks); - }, - setCookies(cookies) { - for (const cookie of cookies) ctx.setCookie(cookie.name, cookie.value, cookie.attributes); - } - }; -}; -var createSessionStore = storeFactory("Session"); -var createAccountStore = storeFactory("Account"); -function getChunkedCookie(ctx, cookieName) { - const value = ctx.getCookie(cookieName); - if (value) return value; - const chunks = []; - const cookieHeader = ctx.headers?.get("cookie"); - if (!cookieHeader) return null; - const cookies = {}; - const pairs = cookieHeader.split("; "); - for (const pair of pairs) { - const [name, ...valueParts] = pair.split("="); - if (name && valueParts.length > 0) cookies[name] = valueParts.join("="); - } - for (const [name, val] of Object.entries(cookies)) if (name.startsWith(cookieName + ".")) { - const indexStr = name.split(".").at(-1); - const index = parseInt(indexStr || "0", 10); - if (!isNaN(index)) chunks.push({ - index, - value: val - }); - } - if (chunks.length > 0) { - chunks.sort((a, b) => a.index - b.index); - return chunks.map((c) => c.value).join(""); - } - return null; -} -async function setAccountCookie(c, accountData) { - const accountDataCookie = c.context.authCookies.accountData; - const options = { - maxAge: 300, - ...accountDataCookie.attributes - }; - const data = await symmetricEncodeJWT(accountData, c.context.secretConfig, "better-auth-account", options.maxAge); - if (data.length > ALLOWED_COOKIE_SIZE) { - const accountStore = createAccountStore(accountDataCookie.name, options, c); - const cookies = accountStore.chunk(data, options); - accountStore.setCookies(cookies); - } else { - const accountStore = createAccountStore(accountDataCookie.name, options, c); - if (accountStore.hasChunks()) { - const cleanCookies = accountStore.clean(); - accountStore.setCookies(cleanCookies); - } - c.setCookie(accountDataCookie.name, data, options); - } -} -async function getAccountCookie(c) { - const accountCookie = getChunkedCookie(c, c.context.authCookies.accountData.name); - if (accountCookie) { - const accountData = safeJSONParse(await symmetricDecodeJWT(accountCookie, c.context.secretConfig, "better-auth-account")); - if (accountData) return accountData; - } - return null; -} -var getSessionQuerySchema = optional(object({ - disableCookieCache: coerce_exports.boolean().meta({ description: "Disable cookie cache and fetch session from database" }).optional(), - disableRefresh: coerce_exports.boolean().meta({ description: "Disable session refresh. Useful for checking session status, without updating the session" }).optional() -})); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/time.mjs -var SEC = 1e3; -var MIN = SEC * 60; -var HOUR = MIN * 60; -var DAY = HOUR * 24; -var WEEK = DAY * 7; -var MONTH = DAY * 30; -var YEAR = DAY * 365.25; -var REGEX2 = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i; -function parse3(value) { - const match2 = REGEX2.exec(value); - if (!match2 || match2[4] && match2[1]) throw new TypeError(`Invalid time string format: "${value}". Use formats like "7d", "30m", "1 hour", etc.`); - const n = parseFloat(match2[2]); - const unit = match2[3].toLowerCase(); - let result; - switch (unit) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - result = n * YEAR; - break; - case "months": - case "month": - case "mo": - result = n * MONTH; - break; - case "weeks": - case "week": - case "w": - result = n * WEEK; - break; - case "days": - case "day": - case "d": - result = n * DAY; - break; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - result = n * HOUR; - break; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - result = n * MIN; - break; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - result = n * SEC; - break; - default: - throw new TypeError(`Unknown time unit: "${unit}"`); - } - if (match2[1] === "-" || match2[4] === "ago") return -result; - return result; -} -function sec(value) { - return Math.round(parse3(value) / 1e3); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/cookie-utils.mjs -var SECURE_COOKIE_PREFIX = "__Secure-"; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/index.mjs -init_env(); -init_error2(); - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/binary.mjs -var decoders = /* @__PURE__ */ new Map(); -var encoder2 = new TextEncoder(); -var binary = { - decode: (data, encoding = "utf-8") => { - if (!decoders.has(encoding)) { - decoders.set(encoding, new TextDecoder(encoding)); - } - const decoder2 = decoders.get(encoding); - return decoder2.decode(data); - }, - encode: encoder2.encode -}; - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hex.mjs -var hexadecimal = "0123456789abcdef"; -var hex3 = { - encode: (data) => { - if (typeof data === "string") { - data = new TextEncoder().encode(data); - } - if (data.byteLength === 0) { - return ""; - } - const buffer = new Uint8Array(data); - let result = ""; - for (const byte of buffer) { - result += byte.toString(16).padStart(2, "0"); - } - return result; - }, - decode: (data) => { - if (!data) { - return ""; - } - if (typeof data === "string") { - if (data.length % 2 !== 0) { - throw new Error("Invalid hexadecimal string"); - } - if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) { - throw new Error("Invalid hexadecimal string"); - } - const result = new Uint8Array(data.length / 2); - for (let i = 0; i < data.length; i += 2) { - result[i / 2] = parseInt(data.slice(i, i + 2), 16); - } - return new TextDecoder().decode(result); - } - return new TextDecoder().decode(data); - } -}; - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hmac.mjs -var createHMAC = (algorithm2 = "SHA-256", encoding = "none") => { - const hmac2 = { - importKey: async (key, keyUsage) => { - return getWebcryptoSubtle().importKey( - "raw", - typeof key === "string" ? new TextEncoder().encode(key) : key, - { name: "HMAC", hash: { name: algorithm2 } }, - false, - [keyUsage] - ); - }, - sign: async (hmacKey, data) => { - if (typeof hmacKey === "string") { - hmacKey = await hmac2.importKey(hmacKey, "sign"); - } - const signature = await getWebcryptoSubtle().sign( - "HMAC", - hmacKey, - typeof data === "string" ? new TextEncoder().encode(data) : data - ); - if (encoding === "hex") { - return hex3.encode(signature); - } - if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { - return base64Url.encode(signature, { - padding: encoding !== "base64urlnopad" - }); - } - return signature; - }, - verify: async (hmacKey, data, signature) => { - if (typeof hmacKey === "string") { - hmacKey = await hmac2.importKey(hmacKey, "verify"); - } - if (encoding === "hex") { - signature = hex3.decode(signature); - } - if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { - signature = await base643.decode(signature); - } - return getWebcryptoSubtle().verify( - "HMAC", - hmacKey, - typeof signature === "string" ? new TextEncoder().encode(signature) : signature, - typeof data === "string" ? new TextEncoder().encode(data) : data - ); - } - }; - return hmac2; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/index.mjs -function createCookieGetter(options) { - const baseURLString = typeof options.baseURL === "string" ? options.baseURL : void 0; - const dynamicProtocol = typeof options.baseURL === "object" && options.baseURL !== null ? options.baseURL.protocol : void 0; - const secureCookiePrefix = (options.advanced?.useSecureCookies !== void 0 ? options.advanced?.useSecureCookies : dynamicProtocol === "https" ? true : dynamicProtocol === "http" ? false : baseURLString ? baseURLString.startsWith("https://") : isProduction) ? SECURE_COOKIE_PREFIX : ""; - const crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled; - const domain2 = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (baseURLString ? new URL(baseURLString).hostname : void 0) : void 0; - if (crossSubdomainEnabled && !domain2 && !isDynamicBaseURLConfig(options.baseURL)) throw new BetterAuthError("baseURL is required when crossSubdomainCookies are enabled."); - function createCookie(cookieName, overrideAttributes = {}) { - const prefix = options.advanced?.cookiePrefix || "better-auth"; - const name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`; - const attributes = options.advanced?.cookies?.[cookieName]?.attributes ?? {}; - return { - name: `${secureCookiePrefix}${name}`, - attributes: { - secure: !!secureCookiePrefix, - sameSite: "lax", - path: "/", - httpOnly: true, - ...crossSubdomainEnabled ? { domain: domain2 } : {}, - ...options.advanced?.defaultCookieAttributes, - ...overrideAttributes, - ...attributes - } - }; - } - return createCookie; -} -function getCookies(options) { - const createCookie = createCookieGetter(options); - const sessionToken = createCookie("session_token", { maxAge: options.session?.expiresIn || sec("7d") }); - const sessionData = createCookie("session_data", { maxAge: options.session?.cookieCache?.maxAge || 300 }); - const accountData = createCookie("account_data", { maxAge: options.session?.cookieCache?.maxAge || 300 }); - const dontRememberToken = createCookie("dont_remember"); - return { - sessionToken: { - name: sessionToken.name, - attributes: sessionToken.attributes - }, - sessionData: { - name: sessionData.name, - attributes: sessionData.attributes - }, - dontRememberToken: { - name: dontRememberToken.name, - attributes: dontRememberToken.attributes - }, - accountData: { - name: accountData.name, - attributes: accountData.attributes - } - }; -} -async function setCookieCache(ctx, session, dontRememberMe) { - if (!ctx.context.options.session?.cookieCache?.enabled) return; - const filteredSession = filterOutputFields(session.session, ctx.context.options.session?.additionalFields); - const filteredUser = parseUserOutput(ctx.context.options, session.user); - const versionConfig = ctx.context.options.session?.cookieCache?.version; - let version3 = "1"; - if (versionConfig) { - if (typeof versionConfig === "string") version3 = versionConfig; - else if (typeof versionConfig === "function") { - const result = versionConfig(session.session, session.user); - version3 = isPromise(result) ? await result : result; - } - } - const sessionData = { - session: filteredSession, - user: filteredUser, - updatedAt: Date.now(), - version: version3 - }; - const options = { - ...ctx.context.authCookies.sessionData.attributes, - maxAge: dontRememberMe ? void 0 : ctx.context.authCookies.sessionData.attributes.maxAge - }; - const expiresAtDate = getDate(options.maxAge || 60, "sec").getTime(); - const strategy = ctx.context.options.session?.cookieCache?.strategy || "compact"; - let data; - if (strategy === "jwe") data = await symmetricEncodeJWT(sessionData, ctx.context.secretConfig, "better-auth-session", options.maxAge || 300); - else if (strategy === "jwt") data = await signJWT(sessionData, ctx.context.secret, options.maxAge || 300); - else data = base64Url.encode(JSON.stringify({ - session: sessionData, - expiresAt: expiresAtDate, - signature: await createHMAC("SHA-256", "base64urlnopad").sign(ctx.context.secret, JSON.stringify({ - ...sessionData, - expiresAt: expiresAtDate - })) - }), { padding: false }); - if (data.length > 4093) { - const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx); - const cookies = sessionStore.chunk(data, options); - sessionStore.setCookies(cookies); - } else { - const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx); - if (sessionStore.hasChunks()) { - const cleanCookies = sessionStore.clean(); - sessionStore.setCookies(cleanCookies); - } - ctx.setCookie(ctx.context.authCookies.sessionData.name, data, options); - } - if (ctx.context.options.account?.storeAccountCookie) { - const accountData = await getAccountCookie(ctx); - if (accountData) await setAccountCookie(ctx, accountData); - } -} -async function setSessionCookie(ctx, session, dontRememberMe, overrides) { - const dontRememberMeCookie = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); - dontRememberMe = dontRememberMe !== void 0 ? dontRememberMe : !!dontRememberMeCookie; - const options = ctx.context.authCookies.sessionToken.attributes; - const maxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn; - await ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, { - ...options, - maxAge, - ...overrides - }); - if (dontRememberMe) await ctx.setSignedCookie(ctx.context.authCookies.dontRememberToken.name, "true", ctx.context.secret, ctx.context.authCookies.dontRememberToken.attributes); - await setCookieCache(ctx, session, dontRememberMe); - ctx.context.setNewSession(session); -} -function expireCookie(ctx, cookie) { - ctx.setCookie(cookie.name, "", { - ...cookie.attributes, - maxAge: 0 - }); -} -function deleteSessionCookie(ctx, skipDontRememberMe) { - expireCookie(ctx, ctx.context.authCookies.sessionToken); - expireCookie(ctx, ctx.context.authCookies.sessionData); - if (ctx.context.options.account?.storeAccountCookie) { - expireCookie(ctx, ctx.context.authCookies.accountData); - const accountStore = createAccountStore(ctx.context.authCookies.accountData.name, ctx.context.authCookies.accountData.attributes, ctx); - const cleanCookies2 = accountStore.clean(); - accountStore.setCookies(cleanCookies2); - } - if (ctx.context.oauthConfig.storeStateStrategy === "cookie") expireCookie(ctx, ctx.context.createAuthCookie("oauth_state")); - const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, ctx.context.authCookies.sessionData.attributes, ctx); - const cleanCookies = sessionStore.clean(); - sessionStore.setCookies(cleanCookies); - if (!skipDontRememberMe) expireCookie(ctx, ctx.context.authCookies.dontRememberToken); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/state.mjs -init_error2(); -init_zod(); -var stateDataSchema = looseObject({ - callbackURL: string2(), - codeVerifier: string2(), - errorURL: string2().optional(), - newUserURL: string2().optional(), - expiresAt: number2(), - oauthState: string2().optional(), - link: object({ - email: string2(), - userId: coerce_exports.string() - }).optional(), - requestSignUp: boolean2().optional() -}); -var StateError = class extends BetterAuthError { - constructor(message2, options) { - super(message2, options); - __publicField(this, "code"); - __publicField(this, "details"); - this.code = options.code; - this.details = options.details; - } -}; -async function generateGenericState(c, stateData, settings) { - const state = generateRandomString(32); - if (c.context.oauthConfig.storeStateStrategy === "cookie") { - const payload = { - ...stateData, - oauthState: state - }; - const encryptedData = await symmetricEncrypt({ - key: c.context.secretConfig, - data: JSON.stringify(payload) - }); - const stateCookie2 = c.context.createAuthCookie(settings?.cookieName ?? "oauth_state", { maxAge: 600 }); - c.setCookie(stateCookie2.name, encryptedData, stateCookie2.attributes); - return { - state, - codeVerifier: stateData.codeVerifier - }; - } - const stateCookie = c.context.createAuthCookie(settings?.cookieName ?? "state", { maxAge: 300 }); - await c.setSignedCookie(stateCookie.name, state, c.context.secret, stateCookie.attributes); - const expiresAt = /* @__PURE__ */ new Date(); - expiresAt.setMinutes(expiresAt.getMinutes() + 10); - if (!await c.context.internalAdapter.createVerificationValue({ - value: JSON.stringify({ - ...stateData, - oauthState: state - }), - identifier: state, - expiresAt - })) throw new StateError("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database", { code: "state_generation_error" }); - return { - state, - codeVerifier: stateData.codeVerifier - }; -} -async function parseGenericState(c, state, settings) { - const storeStateStrategy = c.context.oauthConfig.storeStateStrategy; - let parsedData; - if (storeStateStrategy === "cookie") { - const stateCookie = c.context.createAuthCookie(settings?.cookieName ?? "oauth_state"); - const encryptedData = c.getCookie(stateCookie.name); - if (!encryptedData) throw new StateError("State mismatch: auth state cookie not found", { - code: "state_mismatch", - details: { state } - }); - try { - const decryptedData = await symmetricDecrypt({ - key: c.context.secretConfig, - data: encryptedData - }); - parsedData = stateDataSchema.parse(JSON.parse(decryptedData)); - } catch (error49) { - throw new StateError("State invalid: Failed to decrypt or parse auth state", { - code: "state_invalid", - details: { state }, - cause: error49 - }); - } - if (!parsedData.oauthState || parsedData.oauthState !== state) throw new StateError("State mismatch: OAuth state parameter does not match stored state", { - code: "state_security_mismatch", - details: { state } - }); - expireCookie(c, stateCookie); - } else { - const data = await c.context.internalAdapter.findVerificationValue(state); - if (!data) throw new StateError("State mismatch: verification not found", { - code: "state_mismatch", - details: { state } - }); - parsedData = stateDataSchema.parse(JSON.parse(data.value)); - if (parsedData.oauthState !== void 0 && parsedData.oauthState !== state) throw new StateError("State mismatch: OAuth state parameter does not match stored state", { - code: "state_security_mismatch", - details: { state } - }); - const stateCookie = c.context.createAuthCookie(settings?.cookieName ?? "state"); - const stateCookieValue = await c.getSignedCookie(stateCookie.name, c.context.secret); - if (!(settings?.skipStateCookieCheck ?? c.context.oauthConfig.skipStateCookieCheck) && (!stateCookieValue || stateCookieValue !== state)) throw new StateError("State mismatch: State not persisted correctly", { - code: "state_security_mismatch", - details: { state } - }); - expireCookie(c, stateCookie); - await c.context.internalAdapter.deleteVerificationByIdentifier(state); - } - if (parsedData.expiresAt < Date.now()) throw new StateError("Invalid state: request expired", { - code: "state_mismatch", - details: { expiresAt: parsedData.expiresAt } - }); - return parsedData; -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/global.mjs -var symbol2 = Symbol.for("better-auth:global"); -var bind = null; -var __context = {}; -var __betterAuthVersion = "1.6.2"; -function __getBetterAuthGlobal() { - if (!globalThis[symbol2]) { - globalThis[symbol2] = { - version: __betterAuthVersion, - epoch: 1, - context: __context - }; - bind = globalThis[symbol2]; - } - bind = globalThis[symbol2]; - if (bind.version !== __betterAuthVersion) { - bind.version = __betterAuthVersion; - bind.epoch++; - } - return globalThis[symbol2]; -} -function getBetterAuthVersion() { - return __getBetterAuthGlobal().version; -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/async_hooks/index.mjs -var AsyncLocalStoragePromise = import( - /* @vite-ignore */ - /* webpackIgnore: true */ - "node:async_hooks" -).then((mod) => mod.AsyncLocalStorage).catch((err) => { - if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage; - if (typeof window !== "undefined") return null; - console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."); - console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"); - console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"); - throw err; -}); -async function getAsyncLocalStorage() { - const mod = await AsyncLocalStoragePromise; - if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code"); - else return mod; -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/endpoint-context.mjs -var ensureAsyncStorage = async () => { - const betterAuthGlobal = __getBetterAuthGlobal(); - if (!betterAuthGlobal.context.endpointContextAsyncStorage) { - const AsyncLocalStorage = await getAsyncLocalStorage(); - betterAuthGlobal.context.endpointContextAsyncStorage = new AsyncLocalStorage(); - } - return betterAuthGlobal.context.endpointContextAsyncStorage; -}; -async function getCurrentAuthContext() { - const context = (await ensureAsyncStorage()).getStore(); - if (!context) throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback."); - return context; -} -async function runWithEndpointContext(context, fn) { - return (await ensureAsyncStorage()).run(context, fn); -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/request-state.mjs -var ensureAsyncStorage2 = async () => { - const betterAuthGlobal = __getBetterAuthGlobal(); - if (!betterAuthGlobal.context.requestStateAsyncStorage) { - const AsyncLocalStorage = await getAsyncLocalStorage(); - betterAuthGlobal.context.requestStateAsyncStorage = new AsyncLocalStorage(); - } - return betterAuthGlobal.context.requestStateAsyncStorage; -}; -async function hasRequestState() { - return (await ensureAsyncStorage2()).getStore() !== void 0; -} -async function getCurrentRequestState() { - const store = (await ensureAsyncStorage2()).getStore(); - if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback."); - return store; -} -async function runWithRequestState(store, fn) { - return (await ensureAsyncStorage2()).run(store, fn); -} -function defineRequestState(initFn) { - const ref = Object.freeze({}); - return { - get ref() { - return ref; - }, - async get() { - const store = await getCurrentRequestState(); - if (!store.has(ref)) { - const initialValue = await initFn(); - store.set(ref, initialValue); - return initialValue; - } - return store.get(ref); - }, - async set(value) { - (await getCurrentRequestState()).set(ref, value); - } - }; -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/transaction.mjs -var ensureAsyncStorage3 = async () => { - const betterAuthGlobal = __getBetterAuthGlobal(); - if (!betterAuthGlobal.context.adapterAsyncStorage) { - const AsyncLocalStorage = await getAsyncLocalStorage(); - betterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage(); - } - return betterAuthGlobal.context.adapterAsyncStorage; -}; -var getCurrentAdapter = async (fallback) => { - return ensureAsyncStorage3().then((als) => { - return als.getStore()?.adapter || fallback; - }).catch(() => { - return fallback; - }); -}; -var runWithAdapter = async (adapter, fn) => { - let called = false; - return ensureAsyncStorage3().then(async (als) => { - called = true; - const pendingHooks = []; - let result; - let error49; - let hasError = false; - try { - result = await als.run({ - adapter, - pendingHooks - }, fn); - } catch (err) { - error49 = err; - hasError = true; - } - for (const hook of pendingHooks) await hook(); - if (hasError) throw error49; - return result; - }).catch((err) => { - if (!called) return fn(); - throw err; - }); -}; -var runWithTransaction = async (adapter, fn) => { - let called = true; - return ensureAsyncStorage3().then(async (als) => { - called = true; - const pendingHooks = []; - let result; - let error49; - let hasError = false; - try { - result = await adapter.transaction(async (trx) => { - return als.run({ - adapter: trx, - pendingHooks - }, fn); - }); - } catch (e) { - hasError = true; - error49 = e; - } - for (const hook of pendingHooks) await hook(); - if (hasError) throw error49; - return result; - }).catch((err) => { - if (!called) return fn(); - throw err; - }); -}; -var queueAfterTransactionHook = async (hook) => { - return ensureAsyncStorage3().then((als) => { - const store = als.getStore(); - if (store) store.pendingHooks.push(hook); - else return hook(); - }).catch(() => { - return hook(); - }); -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/state/oauth.mjs -var { get: getOAuthState, set: setOAuthState } = defineRequestState(() => null); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/state.mjs -init_error2(); -async function generateState(c, link, additionalData) { - const callbackURL = c.body?.callbackURL || c.context.options.baseURL; - if (!callbackURL) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.CALLBACK_URL_REQUIRED); - const codeVerifier = generateRandomString(128); - const stateData = { - ...additionalData ? additionalData : {}, - callbackURL, - codeVerifier, - errorURL: c.body?.errorCallbackURL, - newUserURL: c.body?.newUserCallbackURL, - link, - expiresAt: Date.now() + 600 * 1e3, - requestSignUp: c.body?.requestSignUp - }; - await setOAuthState(stateData); - try { - return generateGenericState(c, stateData); - } catch (error49) { - c.context.logger.error("Failed to create verification", error49); - throw new APIError2("INTERNAL_SERVER_ERROR", { - message: "Unable to create verification", - cause: error49 - }); - } -} -async function parseState(c) { - const state = c.query.state || c.body.state; - const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`; - let parsedData; - try { - parsedData = await parseGenericState(c, state); - } catch (error49) { - c.context.logger.error("Failed to parse state", error49); - if (error49 instanceof StateError && error49.code === "state_security_mismatch") throw c.redirect(`${errorURL}?error=state_mismatch`); - throw c.redirect(`${errorURL}?error=please_restart_the_process`); - } - if (!parsedData.errorURL) parsedData.errorURL = errorURL; - if (parsedData) await setOAuthState(parsedData); - return parsedData; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/hide-metadata.mjs -var HIDE_METADATA = { scope: "server" }; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-api-error.mjs -init_error2(); - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/index.mjs -init_error(); - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/to-response.mjs -init_error(); - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/utils.mjs -init_error(); -var jsonContentTypeRegex = /^application\/([a-z0-9.+-]*\+)?json/i; -async function getBody(request, allowedMediaTypes) { - const contentType = request.headers.get("content-type") || ""; - const normalizedContentType = contentType.toLowerCase(); - if (!request.body) return; - if (allowedMediaTypes && allowedMediaTypes.length > 0) { - if (!allowedMediaTypes.some((allowed2) => { - const normalizedContentTypeBase = normalizedContentType.split(";")[0].trim(); - const normalizedAllowed = allowed2.toLowerCase().trim(); - return normalizedContentTypeBase === normalizedAllowed || normalizedContentTypeBase.includes(normalizedAllowed); - })) { - if (!normalizedContentType) throw new APIError(415, { - message: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(", ")}`, - code: "UNSUPPORTED_MEDIA_TYPE" - }); - throw new APIError(415, { - message: `Content-Type "${contentType}" is not allowed. Allowed types: ${allowedMediaTypes.join(", ")}`, - code: "UNSUPPORTED_MEDIA_TYPE" - }); - } - } - if (jsonContentTypeRegex.test(normalizedContentType)) return await request.json(); - if (normalizedContentType.includes("application/x-www-form-urlencoded")) { - const formData = await request.formData(); - const result = {}; - formData.forEach((value, key) => { - result[key] = value.toString(); - }); - return result; - } - if (normalizedContentType.includes("multipart/form-data")) { - const formData = await request.formData(); - const result = {}; - formData.forEach((value, key) => { - result[key] = value; - }); - return result; - } - if (normalizedContentType.includes("text/plain")) return await request.text(); - if (normalizedContentType.includes("application/octet-stream")) return await request.arrayBuffer(); - if (normalizedContentType.includes("application/pdf") || normalizedContentType.includes("image/") || normalizedContentType.includes("video/")) return await request.blob(); - if (normalizedContentType.includes("application/stream") || request.body instanceof ReadableStream) return request.body; - return await request.text(); -} -function isAPIError(error49) { - return error49 instanceof APIError || error49?.name === "APIError"; -} -function tryDecode2(str) { - try { - return str.includes("%") ? decodeURIComponent(str) : str; - } catch { - return str; - } -} -async function tryCatch(promise2) { - try { - return { - data: await promise2, - error: null - }; - } catch (error49) { - return { - data: null, - error: error49 - }; - } -} -function isRequest(obj) { - return obj instanceof Request || Object.prototype.toString.call(obj) === "[object Request]"; -} - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/to-response.mjs -function isJSONSerializable(value) { - if (value === void 0) return false; - const t = typeof value; - if (t === "string" || t === "number" || t === "boolean" || t === null) return true; - if (t !== "object") return false; - if (Array.isArray(value)) return true; - if (value.buffer) return false; - return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; -} -function safeStringify(obj, replacer, space) { - let id = 0; - const seen = /* @__PURE__ */ new WeakMap(); - const safeReplacer = (key, value) => { - if (typeof value === "bigint") return value.toString(); - if (typeof value === "object" && value !== null) { - if (seen.has(value)) return `[Circular ref-${seen.get(value)}]`; - seen.set(value, id++); - } - if (replacer) return replacer(key, value); - return value; - }; - return JSON.stringify(obj, safeReplacer, space); -} -function isJSONResponse(value) { - if (!value || typeof value !== "object") return false; - return "_flag" in value && value._flag === "json"; -} -var REQUEST_ONLY_HEADERS = /* @__PURE__ */ new Set([ - "host", - "user-agent", - "referer", - "from", - "expect", - "authorization", - "proxy-authorization", - "cookie", - "origin", - "accept-charset", - "accept-encoding", - "accept-language", - "if-match", - "if-none-match", - "if-modified-since", - "if-unmodified-since", - "if-range", - "range", - "max-forwards", - "connection", - "keep-alive", - "transfer-encoding", - "te", - "upgrade", - "trailer", - "proxy-connection", - "content-length" -]); -function stripRequestOnlyHeaders(headers) { - for (const name of REQUEST_ONLY_HEADERS) headers.delete(name); -} -function toResponse(data, init2) { - if (data instanceof Response) { - if (init2?.headers) { - const safeHeaders = new Headers(init2.headers); - stripRequestOnlyHeaders(safeHeaders); - safeHeaders.forEach((value, key) => { - data.headers.set(key, value); - }); - } - return data; - } - if (isJSONResponse(data)) { - const body2 = data.body; - const routerResponse = data.routerResponse; - if (routerResponse instanceof Response) return routerResponse; - const headers2 = new Headers(); - if (routerResponse?.headers) { - const headers3 = new Headers(routerResponse.headers); - for (const [key, value] of headers3.entries()) headers3.set(key, value); - } - if (data.headers) for (const [key, value] of new Headers(data.headers).entries()) headers2.set(key, value); - if (init2?.headers) { - const safeHeaders = new Headers(init2.headers); - stripRequestOnlyHeaders(safeHeaders); - for (const [key, value] of safeHeaders.entries()) headers2.set(key, value); - } - headers2.set("Content-Type", "application/json"); - return new Response(JSON.stringify(body2), { - ...routerResponse, - headers: headers2, - status: data.status ?? init2?.status ?? routerResponse?.status, - statusText: init2?.statusText ?? routerResponse?.statusText - }); - } - if (isAPIError(data)) return toResponse(data.body, { - status: init2?.status ?? data.statusCode, - statusText: data.status.toString(), - headers: init2?.headers || data.headers - }); - let body = data; - const headers = new Headers(init2?.headers); - stripRequestOnlyHeaders(headers); - if (!data) { - if (data === null) body = JSON.stringify(null); - headers.set("content-type", "application/json"); - } else if (typeof data === "string") { - body = data; - headers.set("Content-Type", "text/plain"); - } else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { - body = data; - headers.set("Content-Type", "application/octet-stream"); - } else if (data instanceof Blob) { - body = data; - headers.set("Content-Type", data.type || "application/octet-stream"); - } else if (data instanceof FormData) body = data; - else if (data instanceof URLSearchParams) { - body = data; - headers.set("Content-Type", "application/x-www-form-urlencoded"); - } else if (data instanceof ReadableStream) { - body = data; - headers.set("Content-Type", "application/octet-stream"); - } else if (isJSONSerializable(data)) { - body = safeStringify(data); - headers.set("Content-Type", "application/json"); - } - return new Response(body, { - ...init2, - headers - }); -} - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/crypto.mjs -var algorithm = { - name: "HMAC", - hash: "SHA-256" -}; -var getCryptoKey3 = async (secret) => { - const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret; - return await getWebcryptoSubtle().importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]); -}; -var verifySignature = async (base64Signature, value, secret) => { - try { - const signatureBinStr = atob(base64Signature); - const signature = new Uint8Array(signatureBinStr.length); - for (let i = 0, len = signatureBinStr.length; i < len; i++) signature[i] = signatureBinStr.charCodeAt(i); - return await getWebcryptoSubtle().verify(algorithm, secret, signature, new TextEncoder().encode(value)); - } catch (e) { - return false; - } -}; -var makeSignature = async (value, secret) => { - const key = await getCryptoKey3(secret); - const signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value)); - return btoa(String.fromCharCode(...new Uint8Array(signature))); -}; -var signCookieValue = async (value, secret) => { - const signature = await makeSignature(value, secret); - value = `${value}.${signature}`; - value = encodeURIComponent(value); - return value; -}; - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/cookies.mjs -var getCookieKey = (key, prefix) => { - let finalKey = key; - if (prefix) if (prefix === "secure") finalKey = "__Secure-" + key; - else if (prefix === "host") finalKey = "__Host-" + key; - else return; - return finalKey; -}; -function parseCookies(str) { - if (typeof str !== "string") throw new TypeError("argument str must be a string"); - const cookies = /* @__PURE__ */ new Map(); - let index = 0; - while (index < str.length) { - const eqIdx = str.indexOf("=", index); - if (eqIdx === -1) break; - let endIdx = str.indexOf(";", index); - if (endIdx === -1) endIdx = str.length; - else if (endIdx < eqIdx) { - index = str.lastIndexOf(";", eqIdx - 1) + 1; - continue; - } - const key = str.slice(index, eqIdx).trim(); - if (!cookies.has(key)) { - let val = str.slice(eqIdx + 1, endIdx).trim(); - if (val.codePointAt(0) === 34) val = val.slice(1, -1); - cookies.set(key, tryDecode2(val)); - } - index = endIdx + 1; - } - return cookies; -} -var _serialize = (key, value, opt = {}) => { - let cookie; - if (opt?.prefix === "secure") cookie = `${`__Secure-${key}`}=${value}`; - else if (opt?.prefix === "host") cookie = `${`__Host-${key}`}=${value}`; - else cookie = `${key}=${value}`; - if (key.startsWith("__Secure-") && !opt.secure) opt.secure = true; - if (key.startsWith("__Host-")) { - if (!opt.secure) opt.secure = true; - if (opt.path !== "/") opt.path = "/"; - if (opt.domain) opt.domain = void 0; - } - if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) { - if (opt.maxAge > 3456e4) throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration."); - cookie += `; Max-Age=${Math.floor(opt.maxAge)}`; - } - if (opt.domain && opt.prefix !== "host") cookie += `; Domain=${opt.domain}`; - if (opt.path) cookie += `; Path=${opt.path}`; - if (opt.expires) { - if (opt.expires.getTime() - Date.now() > 3456e7) throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future."); - cookie += `; Expires=${opt.expires.toUTCString()}`; - } - if (opt.httpOnly) cookie += "; HttpOnly"; - if (opt.secure) cookie += "; Secure"; - if (opt.sameSite) cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`; - if (opt.partitioned) { - if (!opt.secure) opt.secure = true; - cookie += "; Partitioned"; - } - return cookie; -}; -var serializeCookie = (key, value, opt) => { - value = encodeURIComponent(value); - return _serialize(key, value, opt); -}; -var serializeSignedCookie = async (key, value, secret, opt) => { - value = await signCookieValue(value, secret); - return _serialize(key, value, opt); -}; - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/context.mjs -init_error(); - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/validator.mjs -async function runValidation(options, context = {}) { - let request = { - body: context.body, - query: context.query - }; - if (options.body) { - const result = await options.body["~standard"].validate(context.body); - if (result.issues) return { - data: null, - error: fromError(result.issues, "body") - }; - request.body = result.value; - } - if (options.query) { - const result = await options.query["~standard"].validate(context.query); - if (result.issues) return { - data: null, - error: fromError(result.issues, "query") - }; - request.query = result.value; - } - if (options.requireHeaders && !context.headers) return { - data: null, - error: { - message: "Headers is required", - issues: [] - } - }; - if (options.requireRequest && !context.request) return { - data: null, - error: { - message: "Request is required", - issues: [] - } - }; - return { - data: request, - error: null - }; -} -function fromError(error49, validating) { - return { - message: error49.map((e) => { - return `[${e.path?.length ? `${validating}.` + e.path.map((x) => typeof x === "object" ? x.key : x).join(".") : validating}] ${e.message}`; - }).join("; "), - issues: error49 - }; -} - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/context.mjs -var createInternalContext = async (context, { options, path: path3 }) => { - const headers = new Headers(); - let responseStatus = void 0; - const { data, error: error49 } = await runValidation(options, context); - if (error49) throw new ValidationError(error49.message, error49.issues); - const requestHeaders = "headers" in context ? context.headers instanceof Headers ? context.headers : new Headers(context.headers) : "request" in context && isRequest(context.request) ? context.request.headers : null; - const requestCookies = requestHeaders?.get("cookie"); - const parsedCookies = requestCookies ? parseCookies(requestCookies) : void 0; - const internalContext = { - ...context, - body: data.body, - query: data.query, - path: context.path || path3 || "virtual:", - context: "context" in context && context.context ? context.context : {}, - returned: void 0, - headers: context?.headers, - request: context?.request, - params: "params" in context ? context.params : void 0, - method: context.method ?? (Array.isArray(options.method) ? options.method[0] : options.method === "*" ? "GET" : options.method), - setHeader: (key, value) => { - headers.set(key, value); - }, - getHeader: (key) => { - if (!requestHeaders) return null; - return requestHeaders.get(key); - }, - getCookie: (key, prefix) => { - const finalKey = getCookieKey(key, prefix); - if (!finalKey) return null; - return parsedCookies?.get(finalKey) || null; - }, - getSignedCookie: async (key, secret, prefix) => { - const finalKey = getCookieKey(key, prefix); - if (!finalKey) return null; - const value = parsedCookies?.get(finalKey); - if (!value) return null; - const signatureStartPos = value.lastIndexOf("."); - if (signatureStartPos < 1) return null; - const signedValue = value.substring(0, signatureStartPos); - const signature = value.substring(signatureStartPos + 1); - if (signature.length !== 44 || !signature.endsWith("=")) return null; - return await verifySignature(signature, signedValue, await getCryptoKey3(secret)) ? signedValue : false; - }, - setCookie: (key, value, options2) => { - const cookie = serializeCookie(key, value, options2); - headers.append("set-cookie", cookie); - return cookie; - }, - setSignedCookie: async (key, value, secret, options2) => { - const cookie = await serializeSignedCookie(key, value, secret, options2); - headers.append("set-cookie", cookie); - return cookie; - }, - redirect: (url2) => { - headers.set("location", url2); - return new APIError("FOUND", void 0, headers); - }, - error: (status, body, headers2) => { - return new APIError(status, body, headers2); - }, - setStatus: (status) => { - responseStatus = status; - }, - json: (json2, routerResponse) => { - if (!context.asResponse) return json2; - return { - body: routerResponse?.body || json2, - routerResponse, - _flag: "json" - }; - }, - responseHeaders: headers, - get responseStatus() { - return responseStatus; - } - }; - for (const middleware of options.use || []) { - const response = await middleware({ - ...internalContext, - returnHeaders: true, - asResponse: false - }); - if (response.response) Object.assign(internalContext.context, response.response); - if (response.headers) response.headers.forEach((value, key) => { - internalContext.responseHeaders.set(key, value); - }); - } - return internalContext; -}; - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/endpoint.mjs -init_error(); -function createEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { - const path3 = typeof pathOrOptions === "string" ? pathOrOptions : void 0; - const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; - const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; - if ((options.method === "GET" || options.method === "HEAD") && options.body) throw new BetterCallError("Body is not allowed with GET or HEAD methods"); - if (path3 && /\/{2,}/.test(path3)) throw new BetterCallError("Path cannot contain consecutive slashes"); - const internalHandler = async (...inputCtx) => { - const context = inputCtx[0] || {}; - const { data: internalContext, error: validationError } = await tryCatch(createInternalContext(context, { - options, - path: path3 - })); - if (validationError) { - if (!(validationError instanceof ValidationError)) throw validationError; - if (options.onValidationError) await options.onValidationError({ - message: validationError.message, - issues: validationError.issues - }); - throw new APIError(400, { - message: validationError.message, - code: "VALIDATION_ERROR" - }); - } - const response = await handler(internalContext).catch(async (e) => { - if (isAPIError(e)) { - const onAPIError = options.onAPIError; - if (onAPIError) await onAPIError(e); - if (context.asResponse) return e; - } - throw e; - }); - const headers = internalContext.responseHeaders; - const status = internalContext.responseStatus; - return context.asResponse ? toResponse(response, { - headers, - status - }) : context.returnHeaders ? context.returnStatus ? { - headers, - response, - status - } : { - headers, - response - } : context.returnStatus ? { - response, - status - } : response; - }; - internalHandler.options = options; - internalHandler.path = path3; - return internalHandler; -} -createEndpoint.create = (opts) => { - return (path3, options, handler) => { - return createEndpoint(path3, { - ...options, - use: [...options?.use || [], ...opts?.use || []] - }, handler); - }; -}; - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/middleware.mjs -init_error(); -function createMiddleware(optionsOrHandler, handler) { - const internalHandler = async (inputCtx) => { - const context = inputCtx; - const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler; - const internalContext = await createInternalContext(context, { - options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler, - path: "/" - }); - if (!_handler) throw new Error("handler must be defined"); - try { - const response = await _handler(internalContext); - const headers = internalContext.responseHeaders; - return context.returnHeaders ? { - headers, - response - } : response; - } catch (e) { - if (isAPIError(e)) Object.defineProperty(e, kAPIErrorHeaderSymbol, { - enumerable: false, - configurable: true, - get() { - return internalContext.responseHeaders; - } - }); - throw e; - } - }; - internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler; - return internalHandler; -} -createMiddleware.create = (opts) => { - function fn(optionsOrHandler, handler) { - if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler); - if (!handler) throw new Error("Middleware handler is required"); - return createMiddleware({ - ...optionsOrHandler, - method: "*", - use: [...opts?.use || [], ...optionsOrHandler.use || []] - }, handler); - } - return fn; -}; - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/openapi.mjs -init_zod(); -var paths = {}; -function getTypeFromZodType(zodType) { - switch (zodType.constructor.name) { - case "ZodString": - return "string"; - case "ZodNumber": - return "number"; - case "ZodBoolean": - return "boolean"; - case "ZodObject": - return "object"; - case "ZodArray": - return "array"; - default: - return "string"; - } -} -function getParameters(options) { - const parameters = []; - if (options.metadata?.openapi?.parameters) { - parameters.push(...options.metadata.openapi.parameters); - return parameters; - } - if (options.query instanceof ZodObject) Object.entries(options.query.shape).forEach(([key, value]) => { - if (value instanceof ZodObject) parameters.push({ - name: key, - in: "query", - schema: { - type: getTypeFromZodType(value), - ..."minLength" in value && value.minLength ? { minLength: value.minLength } : {}, - description: value.description - } - }); - }); - return parameters; -} -function getRequestBody(options) { - if (options.metadata?.openapi?.requestBody) return options.metadata.openapi.requestBody; - if (!options.body) return void 0; - if (options.body instanceof ZodObject || options.body instanceof ZodOptional) { - const shape = options.body.shape; - if (!shape) return void 0; - const properties = {}; - const required2 = []; - Object.entries(shape).forEach(([key, value]) => { - if (value instanceof ZodObject) { - properties[key] = { - type: getTypeFromZodType(value), - description: value.description - }; - if (!(value instanceof ZodOptional)) required2.push(key); - } - }); - return { - required: options.body instanceof ZodOptional ? false : options.body ? true : false, - content: { "application/json": { schema: { - type: "object", - properties, - required: required2 - } } } - }; - } -} -function getResponse(responses) { - return { - "400": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } }, - required: ["message"] - } } }, - description: "Bad Request. Usually due to missing parameters, or invalid parameters." - }, - "401": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } }, - required: ["message"] - } } }, - description: "Unauthorized. Due to missing or invalid authentication." - }, - "403": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Forbidden. You do not have permission to access this resource or to perform this action." - }, - "404": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Not Found. The requested resource was not found." - }, - "429": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Too Many Requests. You have exceeded the rate limit. Try again later." - }, - "500": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Internal Server Error. This is a problem with the server that you cannot fix." - }, - ...responses - }; -} -async function generator(endpoints, config4) { - const components = { schemas: {} }; - Object.entries(endpoints).forEach(([_, value]) => { - const options = value.options; - if (!value.path || options.metadata?.SERVER_ONLY) return; - if (options.method === "GET") paths[value.path] = { get: { - tags: ["Default", ...options.metadata?.openapi?.tags || []], - description: options.metadata?.openapi?.description, - operationId: options.metadata?.openapi?.operationId, - security: [{ bearerAuth: [] }], - parameters: getParameters(options), - responses: getResponse(options.metadata?.openapi?.responses) - } }; - if (options.method === "POST") { - const body = getRequestBody(options); - paths[value.path] = { post: { - tags: ["Default", ...options.metadata?.openapi?.tags || []], - description: options.metadata?.openapi?.description, - operationId: options.metadata?.openapi?.operationId, - security: [{ bearerAuth: [] }], - parameters: getParameters(options), - ...body ? { requestBody: body } : { requestBody: { content: { "application/json": { schema: { - type: "object", - properties: {} - } } } } }, - responses: getResponse(options.metadata?.openapi?.responses) - } }; - } - }); - return { - openapi: "3.1.1", - info: { - title: "Better Auth", - description: "API Reference for your Better Auth Instance", - version: "1.1.0" - }, - components, - security: [{ apiKeyCookie: [] }], - servers: [{ url: config4?.url }], - tags: [{ - name: "Default", - description: "Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin." - }], - paths - }; -} -var getHTML = (apiReference, config4) => ` - - - Scalar API Reference - - - - - - - - -`; - -// ../../node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs -var NullProtoObj = /* @__PURE__ */ (() => { - const e = function() { - }; - return e.prototype = /* @__PURE__ */ Object.create(null), Object.freeze(e.prototype), e; -})(); -function createRouter() { - return { - root: { key: "" }, - static: new NullProtoObj() - }; -} -function splitPath2(path3) { - const [_, ...s] = path3.split("/"); - return s[s.length - 1] === "" ? s.slice(0, -1) : s; -} -function getMatchParams(segments, paramsMap) { - const params = new NullProtoObj(); - for (const [index, name] of paramsMap) { - const segment = index < 0 ? segments.slice(-(index + 1)).join("/") : segments[index]; - if (typeof name === "string") params[name] = segment; - else { - const match2 = segment.match(name); - if (match2) for (const key in match2.groups) params[key] = match2.groups[key]; - } - } - return params; -} -function addRoute(ctx, method = "", path3, data) { - var _a30; - method = method.toUpperCase(); - if (path3.charCodeAt(0) !== 47) path3 = `/${path3}`; - path3 = path3.replace(/\\:/g, "%3A"); - const segments = splitPath2(path3); - let node = ctx.root; - let _unnamedParamIndex = 0; - const paramsMap = []; - const paramsRegexp = []; - for (let i = 0; i < segments.length; i++) { - let segment = segments[i]; - if (segment.startsWith("**")) { - if (!node.wildcard) node.wildcard = { key: "**" }; - node = node.wildcard; - paramsMap.push([ - -(i + 1), - segment.split(":")[1] || "_", - segment.length === 2 - ]); - break; - } - if (segment === "*" || segment.includes(":")) { - if (!node.param) node.param = { key: "*" }; - node = node.param; - if (segment === "*") paramsMap.push([ - i, - `_${_unnamedParamIndex++}`, - true - ]); - else if (segment.includes(":", 1)) { - const regexp = getParamRegexp(segment); - paramsRegexp[i] = regexp; - node.hasRegexParam = true; - paramsMap.push([ - i, - regexp, - false - ]); - } else paramsMap.push([ - i, - segment.slice(1), - false - ]); - continue; - } - if (segment === "\\*") segment = segments[i] = "*"; - else if (segment === "\\*\\*") segment = segments[i] = "**"; - const child = node.static?.[segment]; - if (child) node = child; - else { - const staticNode = { key: segment }; - if (!node.static) node.static = new NullProtoObj(); - node.static[segment] = staticNode; - node = staticNode; - } - } - const hasParams = paramsMap.length > 0; - if (!node.methods) node.methods = new NullProtoObj(); - (_a30 = node.methods)[method] ?? (_a30[method] = []); - node.methods[method].push({ - data: data || null, - paramsRegexp, - paramsMap: hasParams ? paramsMap : void 0 - }); - if (!hasParams) ctx.static["/" + segments.join("/")] = node; -} -function getParamRegexp(segment) { - const regex = segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\."); - return /* @__PURE__ */ new RegExp(`^${regex}$`); -} -function findRoute(ctx, method = "", path3, opts) { - if (path3.charCodeAt(path3.length - 1) === 47) path3 = path3.slice(0, -1); - const staticNode = ctx.static[path3]; - if (staticNode && staticNode.methods) { - const staticMatch = staticNode.methods[method] || staticNode.methods[""]; - if (staticMatch !== void 0) return staticMatch[0]; - } - const segments = splitPath2(path3); - const match2 = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0]; - if (match2 === void 0) return; - if (opts?.params === false) return match2; - return { - data: match2.data, - params: match2.paramsMap ? getMatchParams(segments, match2.paramsMap) : void 0 - }; -} -function _lookupTree(ctx, node, method, segments, index) { - if (index === segments.length) { - if (node.methods) { - const match2 = node.methods[method] || node.methods[""]; - if (match2) return match2; - } - if (node.param && node.param.methods) { - const match2 = node.param.methods[method] || node.param.methods[""]; - if (match2) { - const pMap = match2[0].paramsMap; - if (pMap?.[pMap?.length - 1]?.[2]) return match2; - } - } - if (node.wildcard && node.wildcard.methods) { - const match2 = node.wildcard.methods[method] || node.wildcard.methods[""]; - if (match2) { - const pMap = match2[0].paramsMap; - if (pMap?.[pMap?.length - 1]?.[2]) return match2; - } - } - return; - } - const segment = segments[index]; - if (node.static) { - const staticChild = node.static[segment]; - if (staticChild) { - const match2 = _lookupTree(ctx, staticChild, method, segments, index + 1); - if (match2) return match2; - } - } - if (node.param) { - const match2 = _lookupTree(ctx, node.param, method, segments, index + 1); - if (match2) { - if (node.param.hasRegexParam) { - const exactMatch = match2.find((m) => m.paramsRegexp[index]?.test(segment)) || match2.find((m) => !m.paramsRegexp[index]); - return exactMatch ? [exactMatch] : void 0; - } - return match2; - } - } - if (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[""]; -} -function findAllRoutes(ctx, method = "", path3, opts) { - if (path3.charCodeAt(path3.length - 1) === 47) path3 = path3.slice(0, -1); - const segments = splitPath2(path3); - const matches = _findAll(ctx, ctx.root, method, segments, 0); - if (opts?.params === false) return matches; - return matches.map((m) => { - return { - data: m.data, - params: m.paramsMap ? getMatchParams(segments, m.paramsMap) : void 0 - }; - }); -} -function _findAll(ctx, node, method, segments, index, matches = []) { - const segment = segments[index]; - if (node.wildcard && node.wildcard.methods) { - const match2 = node.wildcard.methods[method] || node.wildcard.methods[""]; - if (match2) matches.push(...match2); - } - if (node.param) { - _findAll(ctx, node.param, method, segments, index + 1, matches); - if (index === segments.length && node.param.methods) { - const match2 = node.param.methods[method] || node.param.methods[""]; - if (match2) { - const pMap = match2[0].paramsMap; - if (pMap?.[pMap?.length - 1]?.[2]) matches.push(...match2); - } - } - } - const staticChild = node.static?.[segment]; - if (staticChild) _findAll(ctx, staticChild, method, segments, index + 1, matches); - if (index === segments.length && node.methods) { - const match2 = node.methods[method] || node.methods[""]; - if (match2) matches.push(...match2); - } - return matches; -} - -// ../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/router.mjs -var createRouter$1 = (endpoints, config4) => { - if (!config4?.openapi?.disabled) { - const openapi = { - path: "/api/reference", - ...config4?.openapi - }; - endpoints["openapi"] = createEndpoint(openapi.path, { method: "GET" }, async (c) => { - const schema3 = await generator(endpoints); - return new Response(getHTML(schema3, openapi.scalar), { headers: { "Content-Type": "text/html" } }); - }); - } - const router2 = createRouter(); - const middlewareRouter = createRouter(); - for (const endpoint of Object.values(endpoints)) { - if (!endpoint.options || !endpoint.path) continue; - if (endpoint.options?.metadata?.SERVER_ONLY) continue; - const methods2 = Array.isArray(endpoint.options?.method) ? endpoint.options.method : [endpoint.options?.method]; - for (const method of methods2) addRoute(router2, method, endpoint.path, endpoint); - } - if (config4?.routerMiddleware?.length) for (const { path: path3, middleware } of config4.routerMiddleware) addRoute(middlewareRouter, "*", path3, middleware); - const processRequest = async (request) => { - const url2 = new URL(request.url); - const pathname = url2.pathname; - const path3 = config4?.basePath && config4.basePath !== "/" ? pathname.split(config4.basePath).reduce((acc, curr, index) => { - if (index !== 0) if (index > 1) acc.push(`${config4.basePath}${curr}`); - else acc.push(curr); - return acc; - }, []).join("") : url2.pathname; - if (!path3?.length) return new Response(null, { - status: 404, - statusText: "Not Found" - }); - if (/\/{2,}/.test(path3)) return new Response(null, { - status: 404, - statusText: "Not Found" - }); - const route = findRoute(router2, request.method, path3); - if (path3.endsWith("/") !== route?.data?.path?.endsWith("/") && !config4?.skipTrailingSlashes) return new Response(null, { - status: 404, - statusText: "Not Found" - }); - if (!route?.data) return new Response(null, { - status: 404, - statusText: "Not Found" - }); - const query = {}; - url2.searchParams.forEach((value, key) => { - if (key in query) if (Array.isArray(query[key])) query[key].push(value); - else query[key] = [query[key], value]; - else query[key] = value; - }); - const handler = route.data; - try { - const allowedMediaTypes = handler.options.metadata?.allowedMediaTypes || config4?.allowedMediaTypes; - const context = { - path: path3, - method: request.method, - headers: request.headers, - params: route.params ? JSON.parse(JSON.stringify(route.params)) : {}, - request, - body: handler.options.disableBody ? void 0 : await getBody(handler.options.cloneRequest ? request.clone() : request, allowedMediaTypes), - query, - _flag: "router", - asResponse: true, - context: config4?.routerContext - }; - const middlewareRoutes = findAllRoutes(middlewareRouter, "*", path3); - if (middlewareRoutes?.length) for (const { data: middleware, params } of middlewareRoutes) { - const res = await middleware({ - ...context, - params, - asResponse: false - }); - if (res instanceof Response) return res; - } - return await handler(context); - } catch (error49) { - if (config4?.onError) try { - const errorResponse = await config4.onError(error49, request); - if (errorResponse instanceof Response) return toResponse(errorResponse); - } catch (error50) { - if (isAPIError(error50)) return toResponse(error50); - throw error50; - } - if (config4?.throwError) throw error49; - if (isAPIError(error49)) return toResponse(error49); - console.error(`# SERVER_ERROR: `, error49); - return new Response(null, { - status: 500, - statusText: "Internal Server Error" - }); - } - }; - return { - handler: async (request) => { - const onReq = await config4?.onRequest?.(request); - if (onReq instanceof Response) return onReq; - const req = isRequest(onReq) ? onReq : request; - const res = await processRequest(req); - const onRes = await config4?.onResponse?.(res, req); - if (onRes instanceof Response) return onRes; - return res; - }, - endpoints - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-api-error.mjs -function isAPIError2(error49) { - return error49 instanceof APIError || error49 instanceof APIError2 || error49?.name === "APIError"; -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/api/index.mjs -var optionsMiddleware = createMiddleware(async () => { - return {}; -}); -var createAuthMiddleware = createMiddleware.create({ use: [optionsMiddleware, createMiddleware(async () => { - return {}; -})] }); -var use = [optionsMiddleware]; -function createAuthEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { - const path3 = typeof pathOrOptions === "string" ? pathOrOptions : void 0; - const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; - const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; - if (path3) return createEndpoint(path3, { - ...options, - use: [...options?.use || [], ...use] - }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx))); - return createEndpoint({ - ...options, - use: [...options?.use || [], ...use] - }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx))); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/trusted-origins.mjs -var matchesOriginPattern = (url2, pattern, settings) => { - if (url2.startsWith("/")) { - if (settings?.allowRelativePaths) return url2.startsWith("/") && /^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(url2); - return false; - } - if (pattern.includes("*") || pattern.includes("?")) { - if (pattern.includes("://")) return wildcardMatch(pattern)(getOrigin(url2) || url2); - const host = getHost(url2); - if (!host) return false; - return wildcardMatch(pattern)(host); - } - const protocol = getProtocol(url2); - return protocol === "http:" || protocol === "https:" || !protocol ? pattern === getOrigin(url2) : url2.startsWith(pattern); -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/middlewares/origin-check.mjs -init_error2(); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/url.mjs -function normalizePathname(requestUrl, basePath) { - let pathname; - try { - pathname = new URL(requestUrl).pathname.replace(/\/+$/, "") || "/"; - } catch { - return "/"; - } - if (basePath === "/" || basePath === "") return pathname; - if (pathname === basePath) return "/"; - if (pathname.startsWith(basePath + "/")) return pathname.slice(basePath.length).replace(/\/+$/, "") || "/"; - return pathname; -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/deprecate.mjs -function deprecate(fn, message2, logger2) { - let warned = false; - return function(...args) { - if (!warned) { - (logger2?.warn ?? console.warn)(`[Deprecation] ${message2}`); - warned = true; - } - return fn.apply(this, args); - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/middlewares/origin-check.mjs -function shouldSkipCSRFForBackwardCompat(ctx) { - return ctx.context.skipOriginCheck === true && ctx.context.options.advanced?.disableCSRFCheck === void 0; -} -function shouldSkipOriginCheck(ctx) { - const skipOriginCheck = ctx.context.skipOriginCheck; - if (skipOriginCheck === true) return true; - if (Array.isArray(skipOriginCheck) && ctx.request) try { - const basePath = new URL(ctx.context.baseURL).pathname; - const currentPath = normalizePathname(ctx.request.url, basePath); - return skipOriginCheck.some((skipPath) => currentPath.startsWith(skipPath)); - } catch { - } - return false; -} -var logBackwardCompatWarning = deprecate(function logBackwardCompatWarning2() { -}, "disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."); -var originCheckMiddleware = createAuthMiddleware(async (ctx) => { - if (ctx.request?.method === "GET" || ctx.request?.method === "OPTIONS" || ctx.request?.method === "HEAD" || !ctx.request) return; - await validateOrigin(ctx); - if (shouldSkipOriginCheck(ctx)) return; - const { body, query } = ctx; - const callbackURL = body?.callbackURL || query?.callbackURL; - const redirectURL = body?.redirectTo; - const errorCallbackURL = body?.errorCallbackURL; - const newUserCallbackURL = body?.newUserCallbackURL; - const validateURL = (url2, label) => { - if (!url2) return; - if (!ctx.context.isTrustedOrigin(url2, { allowRelativePaths: label !== "origin" })) { - ctx.context.logger.error(`Invalid ${label}: ${url2}`); - ctx.context.logger.info(`If it's a valid URL, please add ${url2} to trustedOrigins in your auth config -`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`); - if (label === "origin") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ORIGIN); - if (label === "callbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_CALLBACK_URL); - if (label === "redirectURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_REDIRECT_URL); - if (label === "errorCallbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL); - if (label === "newUserCallbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL); - throw APIError2.fromStatus("FORBIDDEN", { message: `Invalid ${label}` }); - } - }; - callbackURL && validateURL(callbackURL, "callbackURL"); - redirectURL && validateURL(redirectURL, "redirectURL"); - errorCallbackURL && validateURL(errorCallbackURL, "errorCallbackURL"); - newUserCallbackURL && validateURL(newUserCallbackURL, "newUserCallbackURL"); -}); -var originCheck = (getValue) => createAuthMiddleware(async (ctx) => { - if (!ctx.request) return; - if (shouldSkipOriginCheck(ctx)) return; - const callbackURL = getValue(ctx); - const validateURL = (url2, label) => { - if (!url2) return; - if (!ctx.context.isTrustedOrigin(url2, { allowRelativePaths: label !== "origin" })) { - ctx.context.logger.error(`Invalid ${label}: ${url2}`); - ctx.context.logger.info(`If it's a valid URL, please add ${url2} to trustedOrigins in your auth config -`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`); - if (label === "origin") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ORIGIN); - if (label === "callbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_CALLBACK_URL); - if (label === "redirectURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_REDIRECT_URL); - if (label === "errorCallbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL); - if (label === "newUserCallbackURL") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL); - throw APIError2.fromStatus("FORBIDDEN", { message: `Invalid ${label}` }); - } - }; - const callbacks = Array.isArray(callbackURL) ? callbackURL : [callbackURL]; - for (const url2 of callbacks) validateURL(url2, "callbackURL"); -}); -async function validateOrigin(ctx, forceValidate = false) { - const headers = ctx.request?.headers; - if (!headers || !ctx.request) return; - const originHeader = headers.get("origin") || headers.get("referer") || ""; - const useCookies = headers.has("cookie"); - if (ctx.context.skipCSRFCheck) return; - if (shouldSkipCSRFForBackwardCompat(ctx)) { - ctx.context.options.advanced?.disableOriginCheck === true && logBackwardCompatWarning(); - return; - } - if (shouldSkipOriginCheck(ctx)) return; - if (!(forceValidate || useCookies)) return; - if (!originHeader || originHeader === "null") throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN); - const trustedOrigins = Array.isArray(ctx.context.options.trustedOrigins) ? ctx.context.trustedOrigins : [...ctx.context.trustedOrigins, ...(await ctx.context.options.trustedOrigins?.(ctx.request))?.filter((v) => Boolean(v)) || []]; - if (!trustedOrigins.some((origin) => matchesOriginPattern(originHeader, origin))) { - ctx.context.logger.error(`Invalid origin: ${originHeader}`); - ctx.context.logger.info(`If it's a valid URL, please add ${originHeader} to trustedOrigins in your auth config -`, `Current list of trustedOrigins: ${trustedOrigins}`); - throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.INVALID_ORIGIN); - } -} -var formCsrfMiddleware = createAuthMiddleware(async (ctx) => { - if (!ctx.request) return; - await validateFormCsrf(ctx); -}); -async function validateFormCsrf(ctx) { - const req = ctx.request; - if (!req) return; - if (ctx.context.skipCSRFCheck) return; - if (shouldSkipCSRFForBackwardCompat(ctx)) return; - const headers = req.headers; - if (headers.has("cookie")) return await validateOrigin(ctx); - const site = headers.get("Sec-Fetch-Site"); - const mode = headers.get("Sec-Fetch-Mode"); - const dest = headers.get("Sec-Fetch-Dest"); - if (Boolean(site && site.trim() || mode && mode.trim() || dest && dest.trim())) { - if (site === "cross-site" && mode === "navigate") { - ctx.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)", { - secFetchSite: site, - secFetchMode: mode, - secFetchDest: dest - }); - throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED); - } - return await validateOrigin(ctx, true); - } -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/get-request-ip.mjs -init_env(); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/ip.mjs -init_zod(); -function isValidIP(ip) { - return ipv42().safeParse(ip).success || ipv62().safeParse(ip).success; -} -function isIPv6(ip) { - return ipv62().safeParse(ip).success; -} -function extractIPv4FromMapped(ipv63) { - const lower = ipv63.toLowerCase(); - if (lower.startsWith("::ffff:")) { - const ipv4Part = lower.substring(7); - if (ipv42().safeParse(ipv4Part).success) return ipv4Part; - } - const parts = ipv63.split(":"); - if (parts.length === 7 && parts[5]?.toLowerCase() === "ffff") { - const ipv4Part = parts[6]; - if (ipv4Part && ipv42().safeParse(ipv4Part).success) return ipv4Part; - } - if (lower.includes("::ffff:") || lower.includes(":ffff:")) { - const groups = expandIPv6(ipv63); - if (groups.length === 8 && groups[0] === "0000" && groups[1] === "0000" && groups[2] === "0000" && groups[3] === "0000" && groups[4] === "0000" && groups[5] === "ffff" && groups[6] && groups[7]) return `${Number.parseInt(groups[6].substring(0, 2), 16)}.${Number.parseInt(groups[6].substring(2, 4), 16)}.${Number.parseInt(groups[7].substring(0, 2), 16)}.${Number.parseInt(groups[7].substring(2, 4), 16)}`; - } - return null; -} -function expandIPv6(ipv63) { - if (ipv63.includes("::")) { - const sides = ipv63.split("::"); - const left = sides[0] ? sides[0].split(":") : []; - const right = sides[1] ? sides[1].split(":") : []; - const missingGroups = 8 - left.length - right.length; - const zeros = Array(missingGroups).fill("0000"); - const paddedLeft = left.map((g) => g.padStart(4, "0")); - const paddedRight = right.map((g) => g.padStart(4, "0")); - return [ - ...paddedLeft, - ...zeros, - ...paddedRight - ]; - } - return ipv63.split(":").map((g) => g.padStart(4, "0")); -} -function normalizeIPv6(ipv63, subnetPrefix) { - const groups = expandIPv6(ipv63); - if (subnetPrefix && subnetPrefix < 128) { - let bitsRemaining = subnetPrefix; - return groups.map((group) => { - if (bitsRemaining <= 0) return "0000"; - if (bitsRemaining >= 16) { - bitsRemaining -= 16; - return group; - } - const masked = Number.parseInt(group, 16) & (65535 << 16 - bitsRemaining & 65535); - bitsRemaining = 0; - return masked.toString(16).padStart(4, "0"); - }).join(":").toLowerCase(); - } - return groups.join(":").toLowerCase(); -} -function normalizeIP(ip, options = {}) { - if (ipv42().safeParse(ip).success) return ip.toLowerCase(); - if (!isIPv6(ip)) return ip.toLowerCase(); - const ipv43 = extractIPv4FromMapped(ip); - if (ipv43) return ipv43.toLowerCase(); - return normalizeIPv6(ip, options.ipv6Subnet || 64); -} -function createRateLimitKey(ip, path3) { - return `${ip}|${path3}`; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/get-request-ip.mjs -var LOCALHOST_IP = "127.0.0.1"; -function getIp(req, options) { - if (options.advanced?.ipAddress?.disableIpTracking) return null; - const headers = "headers" in req ? req.headers : req; - const ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || ["x-forwarded-for"]; - for (const key of ipHeaders) { - const value = "get" in headers ? headers.get(key) : headers[key]; - if (typeof value === "string") { - const ip = value.split(",")[0].trim(); - if (isValidIP(ip)) return normalizeIP(ip, { ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet }); - } - } - if (isTest() || isDevelopment()) return LOCALHOST_IP; - return null; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/rate-limiter/index.mjs -init_json(); -var memory = /* @__PURE__ */ new Map(); -function shouldRateLimit(max, window2, rateLimitData) { - const now2 = Date.now(); - const windowInMs = window2 * 1e3; - return now2 - rateLimitData.lastRequest < windowInMs && rateLimitData.count >= max; -} -function rateLimitResponse(retryAfter) { - return new Response(JSON.stringify({ message: "Too many requests. Please try again later." }), { - status: 429, - statusText: "Too Many Requests", - headers: { "X-Retry-After": retryAfter.toString() } - }); -} -function getRetryAfter(lastRequest, window2) { - const now2 = Date.now(); - const windowInMs = window2 * 1e3; - return Math.ceil((lastRequest + windowInMs - now2) / 1e3); -} -function createDatabaseStorageWrapper(ctx) { - const model = "rateLimit"; - const db = ctx.adapter; - return { - get: async (key) => { - const data = (await db.findMany({ - model, - where: [{ - field: "key", - value: key - }] - }))[0]; - if (typeof data?.lastRequest === "bigint") data.lastRequest = Number(data.lastRequest); - return data; - }, - set: async (key, value, _update) => { - try { - if (_update) await db.updateMany({ - model, - where: [{ - field: "key", - value: key - }], - update: { - count: value.count, - lastRequest: value.lastRequest - } - }); - else await db.create({ - model, - data: { - key, - count: value.count, - lastRequest: value.lastRequest - } - }); - } catch (e) { - ctx.logger.error("Error setting rate limit", e); - } - } - }; -} -function getRateLimitStorage(ctx, rateLimitSettings) { - if (ctx.options.rateLimit?.customStorage) return ctx.options.rateLimit.customStorage; - const storage = ctx.rateLimit.storage; - if (storage === "secondary-storage") return { - get: async (key) => { - const data = await ctx.options.secondaryStorage?.get(key); - return data ? safeJSONParse(data) : null; - }, - set: async (key, value, _update) => { - const ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10; - await ctx.options.secondaryStorage?.set?.(key, JSON.stringify(value), ttl); - } - }; - else if (storage === "memory") return { - async get(key) { - const entry = memory.get(key); - if (!entry) return null; - if (Date.now() >= entry.expiresAt) { - memory.delete(key); - return null; - } - return entry.data; - }, - async set(key, value, _update) { - const ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10; - const expiresAt = Date.now() + ttl * 1e3; - memory.set(key, { - data: value, - expiresAt - }); - } - }; - return createDatabaseStorageWrapper(ctx); -} -var ipWarningLogged = false; -async function resolveRateLimitConfig(req, ctx) { - const basePath = new URL(ctx.baseURL).pathname; - const path3 = normalizePathname(req.url, basePath); - let currentWindow = ctx.rateLimit.window; - let currentMax = ctx.rateLimit.max; - const ip = getIp(req, ctx.options); - if (!ip) { - if (!ipWarningLogged) { - ctx.logger.warn("Rate limiting skipped: could not determine client IP address. Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed."); - ipWarningLogged = true; - } - return null; - } - const key = createRateLimitKey(ip, path3); - const specialRule = getDefaultSpecialRules().find((rule) => rule.pathMatcher(path3)); - if (specialRule) { - currentWindow = specialRule.window; - currentMax = specialRule.max; - } - for (const plugin of ctx.options.plugins || []) if (plugin.rateLimit) { - const matchedRule = plugin.rateLimit.find((rule) => rule.pathMatcher(path3)); - if (matchedRule) { - currentWindow = matchedRule.window; - currentMax = matchedRule.max; - break; - } - } - if (ctx.rateLimit.customRules) { - const _path3 = Object.keys(ctx.rateLimit.customRules).find((p) => { - if (p.includes("*")) return wildcardMatch(p)(path3); - return p === path3; - }); - if (_path3) { - const customRule = ctx.rateLimit.customRules[_path3]; - const resolved = typeof customRule === "function" ? await customRule(req, { - window: currentWindow, - max: currentMax - }) : customRule; - if (resolved) { - currentWindow = resolved.window; - currentMax = resolved.max; - } - if (resolved === false) return null; - } - } - return { - key, - currentWindow, - currentMax - }; -} -async function onRequestRateLimit(req, ctx) { - if (!ctx.rateLimit.enabled) return; - const config4 = await resolveRateLimitConfig(req, ctx); - if (!config4) return; - const { key, currentWindow, currentMax } = config4; - const data = await getRateLimitStorage(ctx, { window: currentWindow }).get(key); - if (data && shouldRateLimit(currentMax, currentWindow, data)) return rateLimitResponse(getRetryAfter(data.lastRequest, currentWindow)); -} -async function onResponseRateLimit(req, ctx) { - if (!ctx.rateLimit.enabled) return; - const config4 = await resolveRateLimitConfig(req, ctx); - if (!config4) return; - const { key, currentWindow } = config4; - const storage = getRateLimitStorage(ctx, { window: currentWindow }); - const data = await storage.get(key); - const now2 = Date.now(); - if (!data) await storage.set(key, { - key, - count: 1, - lastRequest: now2 - }); - else if (now2 - data.lastRequest > currentWindow * 1e3) await storage.set(key, { - ...data, - count: 1, - lastRequest: now2 - }, true); - else await storage.set(key, { - ...data, - count: data.count + 1, - lastRequest: now2 - }, true); -} -function getDefaultSpecialRules() { - return [{ - pathMatcher(path3) { - return path3.startsWith("/sign-in") || path3.startsWith("/sign-up") || path3.startsWith("/change-password") || path3.startsWith("/change-email"); - }, - window: 10, - max: 3 - }, { - pathMatcher(path3) { - return path3 === "/request-password-reset" || path3 === "/send-verification-email" || path3.startsWith("/forget-password") || path3 === "/email-otp/send-verification-otp" || path3 === "/email-otp/request-password-reset"; - }, - window: 60, - max: 3 - }]; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/state/should-session-refresh.mjs -var { get: getShouldSkipSessionRefresh, set: setShouldSkipSessionRefresh } = defineRequestState(() => false); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/session.mjs -init_error2(); -init_json(); -init_zod(); -var getSession = () => createAuthEndpoint("/get-session", { - method: ["GET", "POST"], - operationId: "getSession", - query: getSessionQuerySchema, - requireHeaders: true, - metadata: { openapi: { - operationId: "getSession", - description: "Get the current session", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - nullable: true, - properties: { - session: { $ref: "#/components/schemas/Session" }, - user: { $ref: "#/components/schemas/User" } - }, - required: ["session", "user"] - } } } - } } - } } -}, async (ctx) => { - const deferSessionRefresh = ctx.context.options.session?.deferSessionRefresh; - const isPostRequest = ctx.method === "POST"; - if (isPostRequest && !deferSessionRefresh) throw APIError2.from("METHOD_NOT_ALLOWED", BASE_ERROR_CODES.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED); - try { - const sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret); - if (!sessionCookieToken) return null; - const sessionDataCookie = getChunkedCookie(ctx, ctx.context.authCookies.sessionData.name); - let sessionDataPayload = null; - if (sessionDataCookie) { - const strategy = ctx.context.options.session?.cookieCache?.strategy || "compact"; - if (strategy === "jwe") { - const payload = await symmetricDecodeJWT(sessionDataCookie, ctx.context.secretConfig, "better-auth-session"); - if (payload && payload.session && payload.user) sessionDataPayload = { - session: { - session: payload.session, - user: payload.user, - updatedAt: payload.updatedAt, - version: payload.version - }, - expiresAt: payload.exp ? payload.exp * 1e3 : Date.now() - }; - else { - expireCookie(ctx, ctx.context.authCookies.sessionData); - return ctx.json(null); - } - } else if (strategy === "jwt") { - const payload = await verifyJWT(sessionDataCookie, ctx.context.secret); - if (payload && payload.session && payload.user) sessionDataPayload = { - session: { - session: payload.session, - user: payload.user, - updatedAt: payload.updatedAt, - version: payload.version - }, - expiresAt: payload.exp ? payload.exp * 1e3 : Date.now() - }; - else { - expireCookie(ctx, ctx.context.authCookies.sessionData); - return ctx.json(null); - } - } else { - const parsed = safeJSONParse(binary.decode(base64Url.decode(sessionDataCookie))); - if (parsed) if (await createHMAC("SHA-256", "base64urlnopad").verify(ctx.context.secret, JSON.stringify({ - ...parsed.session, - expiresAt: parsed.expiresAt - }), parsed.signature)) sessionDataPayload = parsed; - else { - expireCookie(ctx, ctx.context.authCookies.sessionData); - return ctx.json(null); - } - } - } - const dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); - if (sessionDataPayload?.session && ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache) { - const session2 = sessionDataPayload.session; - const versionConfig = ctx.context.options.session?.cookieCache?.version; - let expectedVersion = "1"; - if (versionConfig) { - if (typeof versionConfig === "string") expectedVersion = versionConfig; - else if (typeof versionConfig === "function") { - const result = versionConfig(session2.session, session2.user); - expectedVersion = result instanceof Promise ? await result : result; - } - } - if ((session2.version || "1") !== expectedVersion) expireCookie(ctx, ctx.context.authCookies.sessionData); - else { - const cachedSessionExpiresAt = new Date(session2.session.expiresAt); - if (sessionDataPayload.expiresAt < Date.now() || cachedSessionExpiresAt < /* @__PURE__ */ new Date()) expireCookie(ctx, ctx.context.authCookies.sessionData); - else { - const cookieRefreshCache = ctx.context.sessionConfig.cookieRefreshCache; - if (cookieRefreshCache === false) { - ctx.context.session = session2; - const parsedSession3 = parseSessionOutput(ctx.context.options, { - ...session2.session, - expiresAt: new Date(session2.session.expiresAt), - createdAt: new Date(session2.session.createdAt), - updatedAt: new Date(session2.session.updatedAt) - }); - const parsedUser3 = parseUserOutput(ctx.context.options, { - ...session2.user, - createdAt: new Date(session2.user.createdAt), - updatedAt: new Date(session2.user.updatedAt) - }); - return ctx.json({ - session: parsedSession3, - user: parsedUser3 - }); - } - const timeUntilExpiry = sessionDataPayload.expiresAt - Date.now(); - const updateAge2 = cookieRefreshCache.updateAge * 1e3; - const shouldSkipSessionRefresh2 = await getShouldSkipSessionRefresh(); - if (timeUntilExpiry < updateAge2 && !shouldSkipSessionRefresh2) { - const newExpiresAt = getDate(ctx.context.options.session?.cookieCache?.maxAge || 300, "sec"); - const refreshedSession = { - session: { - ...session2.session, - expiresAt: newExpiresAt - }, - user: session2.user, - updatedAt: Date.now() - }; - await setCookieCache(ctx, refreshedSession, false); - const sessionTokenOptions = ctx.context.authCookies.sessionToken.attributes; - const sessionTokenMaxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn; - await ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session2.session.token, ctx.context.secret, { - ...sessionTokenOptions, - maxAge: sessionTokenMaxAge - }); - const parsedRefreshedSession = parseSessionOutput(ctx.context.options, { - ...refreshedSession.session, - expiresAt: new Date(refreshedSession.session.expiresAt), - createdAt: new Date(refreshedSession.session.createdAt), - updatedAt: new Date(refreshedSession.session.updatedAt) - }); - const parsedRefreshedUser = parseUserOutput(ctx.context.options, { - ...refreshedSession.user, - createdAt: new Date(refreshedSession.user.createdAt), - updatedAt: new Date(refreshedSession.user.updatedAt) - }); - ctx.context.session = { - session: parsedRefreshedSession, - user: parsedRefreshedUser - }; - return ctx.json({ - session: parsedRefreshedSession, - user: parsedRefreshedUser - }); - } - const parsedSession2 = parseSessionOutput(ctx.context.options, { - ...session2.session, - expiresAt: new Date(session2.session.expiresAt), - createdAt: new Date(session2.session.createdAt), - updatedAt: new Date(session2.session.updatedAt) - }); - const parsedUser2 = parseUserOutput(ctx.context.options, { - ...session2.user, - createdAt: new Date(session2.user.createdAt), - updatedAt: new Date(session2.user.updatedAt) - }); - ctx.context.session = { - session: parsedSession2, - user: parsedUser2 - }; - return ctx.json({ - session: parsedSession2, - user: parsedUser2 - }); - } - } - } - const session = await ctx.context.internalAdapter.findSession(sessionCookieToken); - ctx.context.session = session; - if (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) { - deleteSessionCookie(ctx); - if (session) { - if (!deferSessionRefresh || isPostRequest) await ctx.context.internalAdapter.deleteSession(session.session.token); - } - return ctx.json(null); - } - if (dontRememberMe || ctx.query?.disableRefresh) { - const parsedSession2 = parseSessionOutput(ctx.context.options, session.session); - const parsedUser2 = parseUserOutput(ctx.context.options, session.user); - return ctx.json({ - session: parsedSession2, - user: parsedUser2 - }); - } - const expiresIn = ctx.context.sessionConfig.expiresIn; - const updateAge = ctx.context.sessionConfig.updateAge; - const shouldBeUpdated = session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3 <= Date.now(); - const disableRefresh = ctx.query?.disableRefresh || ctx.context.options.session?.disableSessionRefresh; - const shouldSkipSessionRefresh = await getShouldSkipSessionRefresh(); - const needsRefresh = shouldBeUpdated && !disableRefresh && !shouldSkipSessionRefresh; - if (deferSessionRefresh && !isPostRequest) { - await setCookieCache(ctx, session, !!dontRememberMe); - const parsedSession2 = parseSessionOutput(ctx.context.options, session.session); - const parsedUser2 = parseUserOutput(ctx.context.options, session.user); - return ctx.json({ - session: parsedSession2, - user: parsedUser2, - needsRefresh - }); - } - if (needsRefresh) { - const updatedSession = await ctx.context.internalAdapter.updateSession(session.session.token, { - expiresAt: getDate(ctx.context.sessionConfig.expiresIn, "sec"), - updatedAt: /* @__PURE__ */ new Date() - }); - if (!updatedSession) { - deleteSessionCookie(ctx); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_GET_SESSION); - } - const maxAge = (updatedSession.expiresAt.valueOf() - Date.now()) / 1e3; - await setSessionCookie(ctx, { - session: updatedSession, - user: session.user - }, false, { maxAge }); - const parsedUpdatedSession = parseSessionOutput(ctx.context.options, updatedSession); - const parsedUser2 = parseUserOutput(ctx.context.options, session.user); - return ctx.json({ - session: parsedUpdatedSession, - user: parsedUser2 - }); - } - await setCookieCache(ctx, session, !!dontRememberMe); - const parsedSession = parseSessionOutput(ctx.context.options, session.session); - const parsedUser = parseUserOutput(ctx.context.options, session.user); - return ctx.json({ - session: parsedSession, - user: parsedUser - }); - } catch (error49) { - if (isAPIError2(error49)) throw error49; - ctx.context.logger.error("INTERNAL_SERVER_ERROR", error49); - throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_GET_SESSION); - } -}); -var getSessionFromCtx = async (ctx, config4) => { - if (ctx.context.session) return ctx.context.session; - const session = await getSession()({ - ...ctx, - method: "GET", - asResponse: false, - headers: ctx.headers, - returnHeaders: false, - returnStatus: false, - query: { - ...config4, - ...ctx.query - } - }).catch((e) => { - return null; - }); - ctx.context.session = session; - return session; -}; -var sessionMiddleware = createAuthMiddleware(async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session?.session) throw APIError2.from("UNAUTHORIZED", { - message: "Unauthorized", - code: "UNAUTHORIZED" - }); - return { session }; -}); -var sensitiveSessionMiddleware = createAuthMiddleware(async (ctx) => { - const session = await getSessionFromCtx(ctx, { disableCookieCache: true }); - if (!session?.session) throw APIError2.from("UNAUTHORIZED", { - message: "Unauthorized", - code: "UNAUTHORIZED" - }); - return { session }; -}); -var requestOnlySessionMiddleware = createAuthMiddleware(async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session?.session && (ctx.request || ctx.headers)) throw APIError2.from("UNAUTHORIZED", { - message: "Unauthorized", - code: "UNAUTHORIZED" - }); - return { session }; -}); -var freshSessionMiddleware = createAuthMiddleware(async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session?.session) throw APIError2.from("UNAUTHORIZED", { - message: "Unauthorized", - code: "UNAUTHORIZED" - }); - if (ctx.context.sessionConfig.freshAge !== 0) { - const createdAt = new Date(session.session.createdAt).getTime(); - const freshAge = ctx.context.sessionConfig.freshAge * 1e3; - if (Date.now() - createdAt >= freshAge) throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.SESSION_NOT_FRESH); - } - return { session }; -}); -var listSessions = () => createAuthEndpoint("/list-sessions", { - method: "GET", - operationId: "listUserSessions", - use: [sessionMiddleware], - requireHeaders: true, - metadata: { openapi: { - operationId: "listUserSessions", - description: "List all active sessions for the user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "array", - items: { $ref: "#/components/schemas/Session" } - } } } - } } - } } -}, async (ctx) => { - try { - const activeSessions = (await ctx.context.internalAdapter.listSessions(ctx.context.session.user.id, { onlyActiveSessions: true })).filter((session) => { - return session.expiresAt > /* @__PURE__ */ new Date(); - }); - return ctx.json(activeSessions.map((session) => parseSessionOutput(ctx.context.options, session))); - } catch (e) { - ctx.context.logger.error(e); - throw ctx.error("INTERNAL_SERVER_ERROR"); - } -}); -var revokeSession = createAuthEndpoint("/revoke-session", { - method: "POST", - body: object({ token: string2().meta({ description: "The token to revoke" }) }), - use: [sensitiveSessionMiddleware], - requireHeaders: true, - metadata: { openapi: { - description: "Revoke a single session", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { token: { - type: "string", - description: "The token to revoke" - } }, - required: ["token"] - } } } }, - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { - type: "boolean", - description: "Indicates if the session was revoked successfully" - } }, - required: ["status"] - } } } - } } - } } -}, async (ctx) => { - const token = ctx.body.token; - if ((await ctx.context.internalAdapter.findSession(token))?.session.userId === ctx.context.session.user.id) try { - await ctx.context.internalAdapter.deleteSession(token); - } catch (error49) { - ctx.context.logger.error(error49 && typeof error49 === "object" && "name" in error49 ? error49.name : "", error49); - throw APIError2.from("INTERNAL_SERVER_ERROR", { - message: "Internal Server Error", - code: "INTERNAL_SERVER_ERROR" - }); - } - return ctx.json({ status: true }); -}); -var revokeSessions = createAuthEndpoint("/revoke-sessions", { - method: "POST", - use: [sensitiveSessionMiddleware], - requireHeaders: true, - metadata: { openapi: { - description: "Revoke all sessions for the user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { - type: "boolean", - description: "Indicates if all sessions were revoked successfully" - } }, - required: ["status"] - } } } - } } - } } -}, async (ctx) => { - try { - await ctx.context.internalAdapter.deleteSessions(ctx.context.session.user.id); - } catch (error49) { - ctx.context.logger.error(error49 && typeof error49 === "object" && "name" in error49 ? error49.name : "", error49); - throw APIError2.from("INTERNAL_SERVER_ERROR", { - message: "Internal Server Error", - code: "INTERNAL_SERVER_ERROR" - }); - } - return ctx.json({ status: true }); -}); -var revokeOtherSessions = createAuthEndpoint("/revoke-other-sessions", { - method: "POST", - requireHeaders: true, - use: [sensitiveSessionMiddleware], - metadata: { openapi: { - description: "Revoke all other sessions for the user except the current one", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { - type: "boolean", - description: "Indicates if all other sessions were revoked successfully" - } }, - required: ["status"] - } } } - } } - } } -}, async (ctx) => { - const session = ctx.context.session; - if (!session.user) throw APIError2.from("UNAUTHORIZED", { - message: "Unauthorized", - code: "UNAUTHORIZED" - }); - const otherSessions = (await ctx.context.internalAdapter.listSessions(session.user.id)).filter((session2) => { - return session2.expiresAt > /* @__PURE__ */ new Date(); - }).filter((session2) => session2.token !== ctx.context.session.session.token); - await Promise.all(otherSessions.map((session2) => ctx.context.internalAdapter.deleteSession(session2.token))); - return ctx.json({ status: true }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/verification-token-storage.mjs -var defaultKeyHasher = async (identifier) => { - const hash2 = await createHash("SHA-256").digest(new TextEncoder().encode(identifier)); - return base64Url.encode(new Uint8Array(hash2), { padding: false }); -}; -async function processIdentifier(identifier, option) { - if (!option || option === "plain") return identifier; - if (option === "hashed") return defaultKeyHasher(identifier); - if (typeof option === "object" && "hash" in option) return option.hash(identifier); - return identifier; -} -function getStorageOption(identifier, config4) { - if (!config4) return; - if (typeof config4 === "object" && "default" in config4) { - if (config4.overrides) { - for (const [prefix, option] of Object.entries(config4.overrides)) if (identifier.startsWith(prefix)) return option; - } - return config4.default; - } - return config4; -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/index.mjs -init_attributes(); -init_tracer(); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/with-hooks.mjs -function getWithHooks(adapter, ctx) { - const hooksEntries = ctx.hooks; - async function createWithHooks(data, model, customCreateFn) { - const context = await getCurrentAuthContext().catch(() => null); - let actualData = data; - for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.create?.before; - if (toRun) { - const result = await withSpan(`db create.before ${model}`, { - [ATTR_HOOK_TYPE]: "create.before", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(actualData, context)); - if (result === false) return null; - if (typeof result === "object" && "data" in result) actualData = { - ...actualData, - ...result.data - }; - } - } - let created = null; - if (!customCreateFn || customCreateFn.executeMainFn) created = await (await getCurrentAdapter(adapter)).create({ - model, - data: actualData, - forceAllowId: true - }); - if (customCreateFn?.fn) created = await customCreateFn.fn(created ?? actualData); - for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.create?.after; - if (toRun) await queueAfterTransactionHook(async () => { - await withSpan(`db create.after ${model}`, { - [ATTR_HOOK_TYPE]: "create.after", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(created, context)); - }); - } - return created; - } - async function updateWithHooks(data, where, model, customUpdateFn) { - const context = await getCurrentAuthContext().catch(() => null); - let actualData = data; - for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.update?.before; - if (toRun) { - const result = await withSpan(`db update.before ${model}`, { - [ATTR_HOOK_TYPE]: "update.before", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(data, context)); - if (result === false) return null; - if (typeof result === "object" && "data" in result) actualData = { - ...actualData, - ...result.data - }; - } - } - const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null; - const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).update({ - model, - update: actualData, - where - }) : customUpdated; - for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.update?.after; - if (toRun) await queueAfterTransactionHook(async () => { - await withSpan(`db update.after ${model}`, { - [ATTR_HOOK_TYPE]: "update.after", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(updated, context)); - }); - } - return updated; - } - async function updateManyWithHooks(data, where, model, customUpdateFn) { - const context = await getCurrentAuthContext().catch(() => null); - let actualData = data; - for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.update?.before; - if (toRun) { - const result = await withSpan(`db updateMany.before ${model}`, { - [ATTR_HOOK_TYPE]: "updateMany.before", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(data, context)); - if (result === false) return null; - if (typeof result === "object" && "data" in result) actualData = { - ...actualData, - ...result.data - }; - } - } - const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null; - const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).updateMany({ - model, - update: actualData, - where - }) : customUpdated; - for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.update?.after; - if (toRun) await queueAfterTransactionHook(async () => { - await withSpan(`db updateMany.after ${model}`, { - [ATTR_HOOK_TYPE]: "updateMany.after", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(updated, context)); - }); - } - return updated; - } - async function deleteWithHooks(where, model, customDeleteFn) { - const context = await getCurrentAuthContext().catch(() => null); - let entityToDelete = null; - try { - entityToDelete = (await (await getCurrentAdapter(adapter)).findMany({ - model, - where, - limit: 1 - }))[0] || null; - } catch { - } - if (entityToDelete) for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.delete?.before; - if (toRun) { - if (await withSpan(`db delete.before ${model}`, { - [ATTR_HOOK_TYPE]: "delete.before", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(entityToDelete, context)) === false) return null; - } - } - const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null; - const deleted = (!customDeleteFn || customDeleteFn.executeMainFn) && entityToDelete ? await (await getCurrentAdapter(adapter)).delete({ - model, - where - }) : customDeleted; - if (entityToDelete) for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.delete?.after; - if (toRun) await queueAfterTransactionHook(async () => { - await withSpan(`db delete.after ${model}`, { - [ATTR_HOOK_TYPE]: "delete.after", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(entityToDelete, context)); - }); - } - return deleted; - } - async function deleteManyWithHooks(where, model, customDeleteFn) { - const context = await getCurrentAuthContext().catch(() => null); - let entitiesToDelete = []; - try { - entitiesToDelete = await (await getCurrentAdapter(adapter)).findMany({ - model, - where - }); - } catch { - } - for (const entity of entitiesToDelete) for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.delete?.before; - if (toRun) { - if (await withSpan(`db delete.before ${model}`, { - [ATTR_HOOK_TYPE]: "delete.before", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(entity, context)) === false) return null; - } - } - const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null; - const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await (await getCurrentAdapter(adapter)).deleteMany({ - model, - where - }) : customDeleted; - for (const entity of entitiesToDelete) for (const { source, hooks } of hooksEntries) { - const toRun = hooks[model]?.delete?.after; - if (toRun) await queueAfterTransactionHook(async () => { - await withSpan(`db delete.after ${model}`, { - [ATTR_HOOK_TYPE]: "delete.after", - [ATTR_DB_COLLECTION_NAME]: model, - [ATTR_CONTEXT]: source - }, () => toRun(entity, context)); - }); - } - return deleted; - } - return { - createWithHooks, - updateWithHooks, - updateManyWithHooks, - deleteWithHooks, - deleteManyWithHooks - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/internal-adapter.mjs -init_id2(); -init_json(); -function getTTLSeconds(expiresAt, now2 = Date.now()) { - const expiresMs = typeof expiresAt === "number" ? expiresAt : expiresAt.getTime(); - return Math.max(Math.floor((expiresMs - now2) / 1e3), 0); -} -var createInternalAdapter = (adapter, ctx) => { - const logger2 = ctx.logger; - const options = ctx.options; - const secondaryStorage = options.secondaryStorage; - const sessionExpiration = options.session?.expiresIn || 3600 * 24 * 7; - const { createWithHooks, updateWithHooks, updateManyWithHooks, deleteWithHooks, deleteManyWithHooks } = getWithHooks(adapter, ctx); - async function refreshUserSessions(user) { - if (!secondaryStorage) return; - const listRaw = await secondaryStorage.get(`active-sessions-${user.id}`); - if (!listRaw) return; - const now2 = Date.now(); - const validSessions = (safeJSONParse(listRaw) || []).filter((s) => s.expiresAt > now2); - await Promise.all(validSessions.map(async ({ token }) => { - const cached2 = await secondaryStorage.get(token); - if (!cached2) return; - const parsed = safeJSONParse(cached2); - if (!parsed) return; - const sessionTTL = getTTLSeconds(parsed.session.expiresAt, now2); - await secondaryStorage.set(token, JSON.stringify({ - session: parsed.session, - user - }), Math.floor(sessionTTL)); - })); - } - return { - createOAuthUser: async (user, account) => { - return runWithTransaction(adapter, async () => { - const createdUser = await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...user - }, "user", void 0); - return { - user: createdUser, - account: await createWithHooks({ - ...account, - userId: createdUser.id, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }, "account", void 0) - }; - }); - }, - createUser: async (user) => { - return await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...user, - email: user.email?.toLowerCase() - }, "user", void 0); - }, - createAccount: async (account) => { - return await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...account - }, "account", void 0); - }, - listSessions: async (userId, options2) => { - if (secondaryStorage) { - const currentList = await secondaryStorage.get(`active-sessions-${userId}`); - if (!currentList) return []; - const list = safeJSONParse(currentList) || []; - const now2 = Date.now(); - const seenTokens = /* @__PURE__ */ new Set(); - const sessions = []; - for (const { token, expiresAt } of list) { - if (expiresAt <= now2 || seenTokens.has(token)) continue; - seenTokens.add(token); - const data = await secondaryStorage.get(token); - if (!data) continue; - try { - const parsed = typeof data === "string" ? JSON.parse(data) : data; - if (!parsed?.session) continue; - sessions.push(parseSessionOutput(ctx.options, { - ...parsed.session, - expiresAt: new Date(parsed.session.expiresAt) - })); - } catch { - continue; - } - } - return sessions; - } - return await (await getCurrentAdapter(adapter)).findMany({ - model: "session", - where: [{ - field: "userId", - value: userId - }, ...options2?.onlyActiveSessions ? [{ - field: "expiresAt", - value: /* @__PURE__ */ new Date(), - operator: "gt" - }] : []] - }); - }, - listUsers: async (limit, offset, sortBy, where) => { - return await (await getCurrentAdapter(adapter)).findMany({ - model: "user", - limit, - offset, - sortBy, - where - }); - }, - countTotalUsers: async (where) => { - const total = await (await getCurrentAdapter(adapter)).count({ - model: "user", - where - }); - if (typeof total === "string") return parseInt(total); - return total; - }, - deleteUser: async (userId) => { - if (!secondaryStorage || options.session?.storeSessionInDatabase) await deleteManyWithHooks([{ - field: "userId", - value: userId - }], "session", void 0); - await deleteManyWithHooks([{ - field: "userId", - value: userId - }], "account", void 0); - await deleteWithHooks([{ - field: "id", - value: userId - }], "user", void 0); - }, - createSession: async (userId, dontRememberMe, override, overrideAll) => { - const headers = await (async () => { - const ctx2 = await getCurrentAuthContext().catch(() => null); - return ctx2?.headers || ctx2?.request?.headers; - })(); - const storeInDb = options.session?.storeSessionInDatabase; - const { id: _, ...rest } = override || {}; - let sessionId; - if (secondaryStorage && !storeInDb) { - const generatedId = ctx.generateId({ model: "session" }); - sessionId = generatedId !== false ? generatedId : generateId(); - } - const defaultAdditionalFields = getSessionDefaultFields(options); - const data = { - ...sessionId ? { id: sessionId } : {}, - ipAddress: headers ? getIp(headers, options) || "" : "", - userAgent: headers?.get("user-agent") || "", - ...rest, - expiresAt: dontRememberMe ? getDate(3600 * 24, "sec") : getDate(sessionExpiration, "sec"), - userId, - token: generateId(32), - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...defaultAdditionalFields, - ...overrideAll ? rest : {} - }; - return await createWithHooks(data, "session", secondaryStorage ? { - fn: async (sessionData) => { - const currentList = await secondaryStorage.get(`active-sessions-${userId}`); - let list = []; - const now2 = Date.now(); - if (currentList) { - list = safeJSONParse(currentList) || []; - list = list.filter((session) => session.expiresAt > now2 && session.token !== data.token); - } - const sorted = [...list, { - token: data.token, - expiresAt: data.expiresAt.getTime() - }].sort((a, b) => a.expiresAt - b.expiresAt); - const furthestSessionTTL = getTTLSeconds(sorted.at(-1)?.expiresAt ?? data.expiresAt.getTime(), now2); - if (furthestSessionTTL > 0) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(sorted), furthestSessionTTL); - const user = await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - field: "id", - value: userId - }] - }); - const sessionTTL = getTTLSeconds(data.expiresAt, now2); - if (sessionTTL > 0) await secondaryStorage.set(data.token, JSON.stringify({ - session: sessionData, - user - }), sessionTTL); - return sessionData; - }, - executeMainFn: storeInDb - } : void 0); - }, - findSession: async (token) => { - if (secondaryStorage) { - const sessionStringified = await secondaryStorage.get(token); - if (!sessionStringified && (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase)) return null; - if (sessionStringified) { - const s = safeJSONParse(sessionStringified); - if (!s) return null; - return { - session: parseSessionOutput(ctx.options, { - ...s.session, - expiresAt: new Date(s.session.expiresAt), - createdAt: new Date(s.session.createdAt), - updatedAt: new Date(s.session.updatedAt) - }), - user: parseUserOutput(ctx.options, { - ...s.user, - createdAt: new Date(s.user.createdAt), - updatedAt: new Date(s.user.updatedAt) - }) - }; - } - } - const result = await (await getCurrentAdapter(adapter)).findOne({ - model: "session", - where: [{ - value: token, - field: "token" - }], - join: { user: true } - }); - if (!result) return null; - const { user, ...session } = result; - if (!user) return null; - return { - session: parseSessionOutput(ctx.options, session), - user: parseUserOutput(ctx.options, user) - }; - }, - findSessions: async (sessionTokens, options2) => { - if (secondaryStorage) { - const sessions2 = []; - for (const sessionToken of sessionTokens) { - const sessionStringified = await secondaryStorage.get(sessionToken); - if (sessionStringified) try { - const s = typeof sessionStringified === "string" ? JSON.parse(sessionStringified) : sessionStringified; - if (!s) return []; - const expiresAt = new Date(s.session.expiresAt); - if (options2?.onlyActiveSessions && expiresAt <= /* @__PURE__ */ new Date()) continue; - const session = { - session: { - ...s.session, - expiresAt: new Date(s.session.expiresAt) - }, - user: { - ...s.user, - createdAt: new Date(s.user.createdAt), - updatedAt: new Date(s.user.updatedAt) - } - }; - sessions2.push(session); - } catch { - continue; - } - } - return sessions2; - } - const sessions = await (await getCurrentAdapter(adapter)).findMany({ - model: "session", - where: [{ - field: "token", - value: sessionTokens, - operator: "in" - }, ...options2?.onlyActiveSessions ? [{ - field: "expiresAt", - value: /* @__PURE__ */ new Date(), - operator: "gt" - }] : []], - join: { user: true } - }); - if (!sessions.length) return []; - if (sessions.some((session) => !session.user)) return []; - return sessions.map((_session) => { - const { user, ...session } = _session; - return { - session, - user - }; - }); - }, - updateSession: async (sessionToken, session) => { - return await updateWithHooks(session, [{ - field: "token", - value: sessionToken - }], "session", secondaryStorage ? { - async fn(data) { - const currentSession = await secondaryStorage.get(sessionToken); - if (!currentSession) return null; - const parsedSession = safeJSONParse(currentSession); - if (!parsedSession) return null; - const mergedSession = { - ...parsedSession.session, - ...data, - expiresAt: new Date(data.expiresAt ?? parsedSession.session.expiresAt), - createdAt: new Date(parsedSession.session.createdAt), - updatedAt: new Date(data.updatedAt ?? parsedSession.session.updatedAt) - }; - const updatedSession = parseSessionOutput(ctx.options, mergedSession); - const now2 = Date.now(); - const expiresMs = new Date(updatedSession.expiresAt).getTime(); - const sessionTTL = getTTLSeconds(expiresMs, now2); - if (sessionTTL > 0) { - await secondaryStorage.set(sessionToken, JSON.stringify({ - session: updatedSession, - user: parsedSession.user - }), sessionTTL); - const listKey = `active-sessions-${updatedSession.userId}`; - const listRaw = await secondaryStorage.get(listKey); - const sorted = (listRaw ? safeJSONParse(listRaw) || [] : []).filter((s) => s.token !== sessionToken && s.expiresAt > now2).concat([{ - token: sessionToken, - expiresAt: expiresMs - }]).sort((a, b) => a.expiresAt - b.expiresAt); - const furthestSessionExp = sorted.at(-1)?.expiresAt; - if (furthestSessionExp && furthestSessionExp > now2) await secondaryStorage.set(listKey, JSON.stringify(sorted), getTTLSeconds(furthestSessionExp, now2)); - else await secondaryStorage.delete(listKey); - } - return updatedSession; - }, - executeMainFn: options.session?.storeSessionInDatabase - } : void 0); - }, - deleteSession: async (token) => { - if (secondaryStorage) { - const data = await secondaryStorage.get(token); - if (data) { - const { session } = safeJSONParse(data) ?? {}; - if (!session) { - logger2.error("Session not found in secondary storage"); - return; - } - const userId = session.userId; - const currentList = await secondaryStorage.get(`active-sessions-${userId}`); - if (currentList) { - const list = safeJSONParse(currentList) || []; - const now2 = Date.now(); - const filtered = list.filter((session2) => session2.expiresAt > now2 && session2.token !== token); - const furthestSessionExp = filtered.sort((a, b) => a.expiresAt - b.expiresAt).at(-1)?.expiresAt; - if (filtered.length > 0 && furthestSessionExp && furthestSessionExp > Date.now()) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(filtered), getTTLSeconds(furthestSessionExp, now2)); - else await secondaryStorage.delete(`active-sessions-${userId}`); - } else logger2.error("Active sessions list not found in secondary storage"); - } - await secondaryStorage.delete(token); - if (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return; - } - await deleteWithHooks([{ - field: "token", - value: token - }], "session", void 0); - }, - deleteAccounts: async (userId) => { - await deleteManyWithHooks([{ - field: "userId", - value: userId - }], "account", void 0); - }, - deleteAccount: async (accountId) => { - await deleteWithHooks([{ - field: "id", - value: accountId - }], "account", void 0); - }, - deleteSessions: async (userIdOrSessionTokens) => { - if (secondaryStorage) { - if (typeof userIdOrSessionTokens === "string") { - const activeSession = await secondaryStorage.get(`active-sessions-${userIdOrSessionTokens}`); - const sessions = activeSession ? safeJSONParse(activeSession) : []; - if (!sessions) return; - for (const session of sessions) await secondaryStorage.delete(session.token); - await secondaryStorage.delete(`active-sessions-${userIdOrSessionTokens}`); - } else for (const sessionToken of userIdOrSessionTokens) if (await secondaryStorage.get(sessionToken)) await secondaryStorage.delete(sessionToken); - if (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return; - } - await deleteManyWithHooks([{ - field: Array.isArray(userIdOrSessionTokens) ? "token" : "userId", - value: userIdOrSessionTokens, - operator: Array.isArray(userIdOrSessionTokens) ? "in" : void 0 - }], "session", void 0); - }, - findOAuthUser: async (email3, accountId, providerId) => { - const account = await (await getCurrentAdapter(adapter)).findOne({ - model: "account", - where: [{ - value: accountId, - field: "accountId" - }, { - value: providerId, - field: "providerId" - }], - join: { user: true } - }); - if (account) if (account.user) return { - user: account.user, - linkedAccount: account, - accounts: [account] - }; - else { - const user = await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - value: email3.toLowerCase(), - field: "email" - }] - }); - if (user) return { - user, - linkedAccount: account, - accounts: [account] - }; - return null; - } - else { - const user = await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - value: email3.toLowerCase(), - field: "email" - }] - }); - if (user) return { - user, - linkedAccount: null, - accounts: await (await getCurrentAdapter(adapter)).findMany({ - model: "account", - where: [{ - value: user.id, - field: "userId" - }] - }) || [] - }; - else return null; - } - }, - findUserByEmail: async (email3, options2) => { - const result = await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - value: email3.toLowerCase(), - field: "email" - }], - join: { ...options2?.includeAccounts ? { account: true } : {} } - }); - if (!result) return null; - const { account: accounts2, ...user } = result; - return { - user, - accounts: accounts2 ?? [] - }; - }, - findUserById: async (userId) => { - if (!userId) return null; - return await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - field: "id", - value: userId - }] - }); - }, - linkAccount: async (account) => { - return await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...account - }, "account", void 0); - }, - updateUser: async (userId, data) => { - const user = await updateWithHooks(data, [{ - field: "id", - value: userId - }], "user", void 0); - await refreshUserSessions(user); - return user; - }, - updateUserByEmail: async (email3, data) => { - const user = await updateWithHooks(data, [{ - field: "email", - value: email3.toLowerCase() - }], "user", void 0); - await refreshUserSessions(user); - return user; - }, - updatePassword: async (userId, password) => { - await updateManyWithHooks({ password }, [{ - field: "userId", - value: userId - }, { - field: "providerId", - value: "credential" - }], "account", void 0); - }, - findAccounts: async (userId) => { - return await (await getCurrentAdapter(adapter)).findMany({ - model: "account", - where: [{ - field: "userId", - value: userId - }] - }); - }, - findAccount: async (accountId) => { - return await (await getCurrentAdapter(adapter)).findOne({ - model: "account", - where: [{ - field: "accountId", - value: accountId - }] - }); - }, - findAccountByProviderId: async (accountId, providerId) => { - return await (await getCurrentAdapter(adapter)).findOne({ - model: "account", - where: [{ - field: "accountId", - value: accountId - }, { - field: "providerId", - value: providerId - }] - }); - }, - findAccountByUserId: async (userId) => { - return await (await getCurrentAdapter(adapter)).findMany({ - model: "account", - where: [{ - field: "userId", - value: userId - }] - }); - }, - updateAccount: async (id, data) => { - return await updateWithHooks(data, [{ - field: "id", - value: id - }], "account", void 0); - }, - createVerificationValue: async (data) => { - const storageOption = getStorageOption(data.identifier, options.verification?.storeIdentifier); - const storedIdentifier = await processIdentifier(data.identifier, storageOption); - return await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...data, - identifier: storedIdentifier - }, "verification", secondaryStorage ? { - async fn(verificationData) { - const ttl = getTTLSeconds(verificationData.expiresAt); - if (ttl > 0) await secondaryStorage.set(`verification:${storedIdentifier}`, JSON.stringify(verificationData), ttl); - return verificationData; - }, - executeMainFn: options.verification?.storeInDatabase - } : void 0); - }, - findVerificationValue: async (identifier) => { - const storageOption = getStorageOption(identifier, options.verification?.storeIdentifier); - const storedIdentifier = await processIdentifier(identifier, storageOption); - if (secondaryStorage) { - const cached2 = await secondaryStorage.get(`verification:${storedIdentifier}`); - if (cached2) { - const parsed = safeJSONParse(cached2); - if (parsed) return parsed; - } - if (storageOption && storageOption !== "plain") { - const plainCached = await secondaryStorage.get(`verification:${identifier}`); - if (plainCached) { - const parsed = safeJSONParse(plainCached); - if (parsed) return parsed; - } - } - if (!options.verification?.storeInDatabase) return null; - } - const currentAdapter = await getCurrentAdapter(adapter); - async function findByIdentifier(id) { - return currentAdapter.findMany({ - model: "verification", - where: [{ - field: "identifier", - value: id - }], - sortBy: { - field: "createdAt", - direction: "desc" - }, - limit: 1 - }); - } - let verification = await findByIdentifier(storedIdentifier); - if (!verification.length && storageOption && storageOption !== "plain") verification = await findByIdentifier(identifier); - if (!options.verification?.disableCleanup) await deleteManyWithHooks([{ - field: "expiresAt", - value: /* @__PURE__ */ new Date(), - operator: "lt" - }], "verification", void 0); - return verification[0] || null; - }, - deleteVerificationByIdentifier: async (identifier) => { - const storedIdentifier = await processIdentifier(identifier, getStorageOption(identifier, options.verification?.storeIdentifier)); - if (secondaryStorage) await secondaryStorage.delete(`verification:${storedIdentifier}`); - if (!secondaryStorage || options.verification?.storeInDatabase) await deleteWithHooks([{ - field: "identifier", - value: storedIdentifier - }], "verification", void 0); - }, - updateVerificationByIdentifier: async (identifier, data) => { - const storedIdentifier = await processIdentifier(identifier, getStorageOption(identifier, options.verification?.storeIdentifier)); - if (secondaryStorage) { - const cached2 = await secondaryStorage.get(`verification:${storedIdentifier}`); - if (cached2) { - const parsed = safeJSONParse(cached2); - if (parsed) { - const updated = { - ...parsed, - ...data - }; - const expiresAt = updated.expiresAt ?? parsed.expiresAt; - const ttl = getTTLSeconds(expiresAt instanceof Date ? expiresAt : new Date(expiresAt)); - if (ttl > 0) await secondaryStorage.set(`verification:${storedIdentifier}`, JSON.stringify(updated), ttl); - if (!options.verification?.storeInDatabase) return updated; - } - } - } - if (!secondaryStorage || options.verification?.storeInDatabase) return await updateWithHooks(data, [{ - field: "identifier", - value: storedIdentifier - }], "verification", void 0); - return data; - } - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/helpers.mjs -init_env(); - -// ../../node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs -function isPlainObject2(value) { - if (value === null || typeof value !== "object") { - return false; - } - const prototype = Object.getPrototypeOf(value); - if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) { - return false; - } - if (Symbol.iterator in value) { - return false; - } - if (Symbol.toStringTag in value) { - return Object.prototype.toString.call(value) === "[object Module]"; - } - return true; -} -function _defu(baseObject, defaults, namespace = ".", merger) { - if (!isPlainObject2(defaults)) { - return _defu(baseObject, {}, namespace, merger); - } - const object2 = { ...defaults }; - for (const key of Object.keys(baseObject)) { - if (key === "__proto__" || key === "constructor") { - continue; - } - const value = baseObject[key]; - if (value === null || value === void 0) { - continue; - } - if (merger && merger(object2, key, value, namespace)) { - continue; - } - if (Array.isArray(value) && Array.isArray(object2[key])) { - object2[key] = [...value, ...object2[key]]; - } else if (isPlainObject2(value) && isPlainObject2(object2[key])) { - object2[key] = _defu( - value, - object2[key], - (namespace ? `${namespace}.` : "") + key.toString(), - merger - ); - } else { - object2[key] = value; - } - } - return object2; -} -function createDefu(merger) { - return (...arguments_) => ( - // eslint-disable-next-line unicorn/no-array-reduce - arguments_.reduce((p, c) => _defu(p, c, "", merger), {}) - ); -} -var defu = createDefu(); -var defuFn = createDefu((object2, key, currentValue) => { - if (object2[key] !== void 0 && typeof currentValue === "function") { - object2[key] = currentValue(object2[key]); - return true; - } -}); -var defuArrayFn = createDefu((object2, key, currentValue) => { - if (Array.isArray(object2[key]) && typeof currentValue === "function") { - object2[key] = currentValue(object2[key]); - return true; - } -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/helpers.mjs -async function runPluginInit(context) { - let options = context.options; - const plugins = options.plugins || []; - const pluginTrustedOrigins = []; - const dbHooks = []; - for (const plugin of plugins) if (plugin.init) { - const initPromise = plugin.init(context); - let result; - if (isPromise(initPromise)) result = await initPromise; - else result = initPromise; - if (typeof result === "object") { - if (result.options) { - const { databaseHooks, trustedOrigins, ...restOpts } = result.options; - if (databaseHooks) dbHooks.push({ - source: `plugin:${plugin.id}`, - hooks: databaseHooks - }); - if (trustedOrigins) pluginTrustedOrigins.push(trustedOrigins); - options = defu(options, restOpts); - } - if (result.context) Object.assign(context, result.context); - } - } - if (pluginTrustedOrigins.length > 0) { - const allSources = [...options.trustedOrigins ? [options.trustedOrigins] : [], ...pluginTrustedOrigins]; - const staticOrigins = allSources.filter(Array.isArray).flat(); - const dynamicOrigins = allSources.filter((s) => typeof s === "function"); - if (dynamicOrigins.length > 0) options.trustedOrigins = async (request) => { - const resolved = await Promise.all(dynamicOrigins.map((fn) => fn(request))); - return [...staticOrigins, ...resolved.flat()].filter((v) => typeof v === "string" && v !== ""); - }; - else options.trustedOrigins = staticOrigins; - } - if (options.databaseHooks) dbHooks.push({ - source: "user", - hooks: options.databaseHooks - }); - context.internalAdapter = createInternalAdapter(context.adapter, { - options, - logger: context.logger, - hooks: dbHooks, - generateId: context.generateId - }); - context.options = options; -} -function getInternalPlugins(options) { - const plugins = []; - if (options.advanced?.crossSubDomainCookies?.enabled) { - } - return plugins; -} -async function getTrustedOrigins(options, request) { - const trustedOrigins = []; - if (isDynamicBaseURLConfig(options.baseURL)) { - const allowedHosts = options.baseURL.allowedHosts; - for (const host of allowedHosts) if (!host.includes("://")) { - trustedOrigins.push(`https://${host}`); - if (host.includes("localhost") || host.includes("127.0.0.1")) trustedOrigins.push(`http://${host}`); - } else trustedOrigins.push(host); - if (options.baseURL.fallback) try { - trustedOrigins.push(new URL(options.baseURL.fallback).origin); - } catch { - } - } else { - const baseURL = getBaseURL(typeof options.baseURL === "string" ? options.baseURL : void 0, options.basePath, request); - if (baseURL) trustedOrigins.push(new URL(baseURL).origin); - } - if (options.trustedOrigins) { - if (Array.isArray(options.trustedOrigins)) trustedOrigins.push(...options.trustedOrigins); - if (typeof options.trustedOrigins === "function") { - const validOrigins = await options.trustedOrigins(request); - trustedOrigins.push(...validOrigins); - } - } - const envTrustedOrigins = env.BETTER_AUTH_TRUSTED_ORIGINS; - if (envTrustedOrigins) trustedOrigins.push(...envTrustedOrigins.split(",")); - return trustedOrigins.filter((v) => Boolean(v)); -} -async function getAwaitableValue(arr, item) { - if (!arr) return void 0; - for (const val of arr) { - const value = typeof val === "function" ? await val() : val; - if (value[item.field ?? "id"] === item.value) return value; - } -} -async function getTrustedProviders(options, request) { - const trustedProviders = options.account?.accountLinking?.trustedProviders; - if (!trustedProviders) return []; - if (Array.isArray(trustedProviders)) return trustedProviders.filter((v) => Boolean(v)); - return (await trustedProviders(request) ?? []).filter((v) => Boolean(v)); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/utils.mjs -function isLikelyEncrypted(token) { - if (token.startsWith("$ba$")) return true; - return token.length % 2 === 0 && /^[0-9a-f]+$/i.test(token); -} -function decryptOAuthToken(token, ctx) { - if (!token) return token; - if (ctx.options.account?.encryptOAuthTokens) { - if (!isLikelyEncrypted(token)) return token; - return symmetricDecrypt({ - key: ctx.secretConfig, - data: token - }); - } - return token; -} -function setTokenUtil(token, ctx) { - if (ctx.options.account?.encryptOAuthTokens && token) return symmetricEncrypt({ - key: ctx.secretConfig, - data: token - }); - return token; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/account.mjs -init_error2(); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/apple.mjs -init_error2(); - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/utils.mjs -function getOAuth2Tokens(data) { - const getDate2 = (seconds) => { - const now2 = /* @__PURE__ */ new Date(); - return new Date(now2.getTime() + seconds * 1e3); - }; - return { - tokenType: data.token_type, - accessToken: data.access_token, - refreshToken: data.refresh_token, - accessTokenExpiresAt: data.expires_in ? getDate2(data.expires_in) : void 0, - refreshTokenExpiresAt: data.refresh_token_expires_in ? getDate2(data.refresh_token_expires_in) : void 0, - scopes: data?.scope ? typeof data.scope === "string" ? data.scope.split(" ") : data.scope : [], - idToken: data.id_token, - raw: data - }; -} -async function generateCodeChallenge(codeVerifier) { - const data = new TextEncoder().encode(codeVerifier); - const hash2 = await crypto.subtle.digest("SHA-256", data); - return base64Url.encode(new Uint8Array(hash2), { padding: false }); -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/create-authorization-url.mjs -async function createAuthorizationURL({ id, options, authorizationEndpoint: authorizationEndpoint2, state, codeVerifier, scopes, claims, redirectURI, duration: duration3, prompt, accessType, responseType, display, loginHint, hd, responseMode, additionalParams, scopeJoiner }) { - options = typeof options === "function" ? await options() : options; - const url2 = new URL(options.authorizationEndpoint || authorizationEndpoint2); - url2.searchParams.set("response_type", responseType || "code"); - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - url2.searchParams.set("client_id", primaryClientId); - url2.searchParams.set("state", state); - if (scopes) url2.searchParams.set("scope", scopes.join(scopeJoiner || " ")); - url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); - duration3 && url2.searchParams.set("duration", duration3); - display && url2.searchParams.set("display", display); - loginHint && url2.searchParams.set("login_hint", loginHint); - prompt && url2.searchParams.set("prompt", prompt); - hd && url2.searchParams.set("hd", hd); - accessType && url2.searchParams.set("access_type", accessType); - responseMode && url2.searchParams.set("response_mode", responseMode); - if (codeVerifier) { - const codeChallenge = await generateCodeChallenge(codeVerifier); - url2.searchParams.set("code_challenge_method", "S256"); - url2.searchParams.set("code_challenge", codeChallenge); - } - if (claims) { - const claimsObj = claims.reduce((acc, claim) => { - acc[claim] = null; - return acc; - }, {}); - url2.searchParams.set("claims", JSON.stringify({ id_token: { - email: null, - email_verified: null, - ...claimsObj - } })); - } - if (additionalParams) Object.entries(additionalParams).forEach(([key, value]) => { - url2.searchParams.set(key, value); - }); - return url2; -} - -// ../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/dist/index.js -var __defProp4 = Object.defineProperty; -var __defProps = Object.defineProperties; -var __getOwnPropDescs = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols = Object.getOwnPropertySymbols; -var __hasOwnProp2 = Object.prototype.hasOwnProperty; -var __propIsEnum = Object.prototype.propertyIsEnumerable; -var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp2.call(b, prop)) - __defNormalProp2(a, prop, b[prop]); - if (__getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(b)) { - if (__propIsEnum.call(b, prop)) - __defNormalProp2(a, prop, b[prop]); - } - return a; -}; -var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); -var BetterFetchError = class extends Error { - constructor(status, statusText, error49) { - super(statusText || status.toString(), { - cause: error49 - }); - this.status = status; - this.statusText = statusText; - this.error = error49; - Error.captureStackTrace(this, this.constructor); - } -}; -var initializePlugins = async (url2, options) => { - var _a30, _b2, _c, _d, _e, _f; - let opts = options || {}; - const hooks = { - onRequest: [options == null ? void 0 : options.onRequest], - onResponse: [options == null ? void 0 : options.onResponse], - onSuccess: [options == null ? void 0 : options.onSuccess], - onError: [options == null ? void 0 : options.onError], - onRetry: [options == null ? void 0 : options.onRetry] - }; - if (!options || !(options == null ? void 0 : options.plugins)) { - return { - url: url2, - options: opts, - hooks - }; - } - for (const plugin of (options == null ? void 0 : options.plugins) || []) { - if (plugin.init) { - const pluginRes = await ((_a30 = plugin.init) == null ? void 0 : _a30.call(plugin, url2.toString(), options)); - opts = pluginRes.options || opts; - url2 = pluginRes.url; - } - hooks.onRequest.push((_b2 = plugin.hooks) == null ? void 0 : _b2.onRequest); - hooks.onResponse.push((_c = plugin.hooks) == null ? void 0 : _c.onResponse); - hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess); - hooks.onError.push((_e = plugin.hooks) == null ? void 0 : _e.onError); - hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry); - } - return { - url: url2, - options: opts, - hooks - }; -}; -var LinearRetryStrategy = class { - constructor(options) { - this.options = options; - } - shouldAttemptRetry(attempt, response) { - if (this.options.shouldRetry) { - return Promise.resolve( - attempt < this.options.attempts && this.options.shouldRetry(response) - ); - } - return Promise.resolve(attempt < this.options.attempts); - } - getDelay() { - return this.options.delay; - } -}; -var ExponentialRetryStrategy = class { - constructor(options) { - this.options = options; - } - shouldAttemptRetry(attempt, response) { - if (this.options.shouldRetry) { - return Promise.resolve( - attempt < this.options.attempts && this.options.shouldRetry(response) - ); - } - return Promise.resolve(attempt < this.options.attempts); - } - getDelay(attempt) { - const delay = Math.min( - this.options.maxDelay, - this.options.baseDelay * 2 ** attempt - ); - return delay; - } -}; -function createRetryStrategy(options) { - if (typeof options === "number") { - return new LinearRetryStrategy({ - type: "linear", - attempts: options, - delay: 1e3 - }); - } - switch (options.type) { - case "linear": - return new LinearRetryStrategy(options); - case "exponential": - return new ExponentialRetryStrategy(options); - default: - throw new Error("Invalid retry strategy"); - } -} -var getAuthHeader = async (options) => { - const headers = {}; - const getValue = async (value) => typeof value === "function" ? await value() : value; - if (options == null ? void 0 : options.auth) { - if (options.auth.type === "Bearer") { - const token = await getValue(options.auth.token); - if (!token) { - return headers; - } - headers["authorization"] = `Bearer ${token}`; - } else if (options.auth.type === "Basic") { - const [username, password] = await Promise.all([ - getValue(options.auth.username), - getValue(options.auth.password) - ]); - if (!username || !password) { - return headers; - } - headers["authorization"] = `Basic ${btoa(`${username}:${password}`)}`; - } else if (options.auth.type === "Custom") { - const [prefix, value] = await Promise.all([ - getValue(options.auth.prefix), - getValue(options.auth.value) - ]); - if (!value) { - return headers; - } - headers["authorization"] = `${prefix != null ? prefix : ""} ${value}`; - } - } - return headers; -}; -var JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i; -function detectResponseType(request) { - const _contentType = request.headers.get("content-type"); - const textTypes = /* @__PURE__ */ new Set([ - "image/svg", - "application/xml", - "application/xhtml", - "application/html" - ]); - if (!_contentType) { - return "json"; - } - const contentType = _contentType.split(";").shift() || ""; - if (JSON_RE.test(contentType)) { - return "json"; - } - if (textTypes.has(contentType) || contentType.startsWith("text/")) { - return "text"; - } - return "blob"; -} -function isJSONParsable(value) { - try { - JSON.parse(value); - return true; - } catch (error49) { - return false; - } -} -function isJSONSerializable2(value) { - if (value === void 0) { - return false; - } - const t = typeof value; - if (t === "string" || t === "number" || t === "boolean" || t === null) { - return true; - } - if (t !== "object") { - return false; - } - if (Array.isArray(value)) { - return true; - } - if (value.buffer) { - return false; - } - return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; -} -function jsonParse(text) { - try { - return JSON.parse(text); - } catch (error49) { - return text; - } -} -function isFunction2(value) { - return typeof value === "function"; -} -function getFetch(options) { - if (options == null ? void 0 : options.customFetchImpl) { - return options.customFetchImpl; - } - if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch)) { - return globalThis.fetch; - } - if (typeof window !== "undefined" && isFunction2(window.fetch)) { - return window.fetch; - } - throw new Error("No fetch implementation found"); -} -async function getHeaders(opts) { - const headers = new Headers(opts == null ? void 0 : opts.headers); - const authHeader = await getAuthHeader(opts); - for (const [key, value] of Object.entries(authHeader || {})) { - headers.set(key, value); - } - if (!headers.has("content-type")) { - const t = detectContentType(opts == null ? void 0 : opts.body); - if (t) { - headers.set("content-type", t); - } - } - return headers; -} -function detectContentType(body) { - if (isJSONSerializable2(body)) { - return "application/json"; - } - return null; -} -function getBody2(options) { - if (!(options == null ? void 0 : options.body)) { - return null; - } - const headers = new Headers(options == null ? void 0 : options.headers); - if (isJSONSerializable2(options.body) && !headers.has("content-type")) { - for (const [key, value] of Object.entries(options == null ? void 0 : options.body)) { - if (value instanceof Date) { - options.body[key] = value.toISOString(); - } - } - return JSON.stringify(options.body); - } - if (headers.has("content-type") && headers.get("content-type") === "application/x-www-form-urlencoded") { - if (isJSONSerializable2(options.body)) { - return new URLSearchParams(options.body).toString(); - } - return options.body; - } - return options.body; -} -function getMethod(url2, options) { - var _a30; - if (options == null ? void 0 : options.method) { - return options.method.toUpperCase(); - } - if (url2.startsWith("@")) { - const pMethod = (_a30 = url2.split("@")[1]) == null ? void 0 : _a30.split("/")[0]; - if (!methods.includes(pMethod)) { - return (options == null ? void 0 : options.body) ? "POST" : "GET"; - } - return pMethod.toUpperCase(); - } - return (options == null ? void 0 : options.body) ? "POST" : "GET"; -} -function getTimeout(options, controller) { - let abortTimeout; - if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) { - abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout); - } - return { - abortTimeout, - clearTimeout: () => { - if (abortTimeout) { - clearTimeout(abortTimeout); - } - } - }; -} -var ValidationError2 = class _ValidationError extends Error { - constructor(issues, message2) { - super(message2 || JSON.stringify(issues, null, 2)); - this.issues = issues; - Object.setPrototypeOf(this, _ValidationError.prototype); - } -}; -async function parseStandardSchema(schema3, input) { - const result = await schema3["~standard"].validate(input); - if (result.issues) { - throw new ValidationError2(result.issues); - } - return result.value; -} -var methods = ["get", "post", "put", "patch", "delete"]; -function getURL2(url2, option) { - const { baseURL, params, query } = option || { - query: {}, - params: {}, - baseURL: "" - }; - let basePath = url2.startsWith("http") ? url2.split("/").slice(0, 3).join("/") : baseURL || ""; - if (url2.startsWith("@")) { - const m = url2.toString().split("@")[1].split("/")[0]; - if (methods.includes(m)) { - url2 = url2.replace(`@${m}/`, "/"); - } - } - if (!basePath.endsWith("/")) basePath += "/"; - let [path3, urlQuery] = url2.replace(basePath, "").split("?"); - const queryParams = new URLSearchParams(urlQuery); - for (const [key, value] of Object.entries(query || {})) { - if (value == null) continue; - let serializedValue; - if (typeof value === "string") { - serializedValue = value; - } else if (Array.isArray(value)) { - for (const val of value) { - queryParams.append(key, val); - } - continue; - } else { - serializedValue = JSON.stringify(value); - } - queryParams.set(key, serializedValue); - } - if (params) { - if (Array.isArray(params)) { - const paramPaths = path3.split("/").filter((p) => p.startsWith(":")); - for (const [index, key] of paramPaths.entries()) { - const value = params[index]; - path3 = path3.replace(key, value); - } - } else { - for (const [key, value] of Object.entries(params)) { - path3 = path3.replace(`:${key}`, String(value)); - } - } - } - path3 = path3.split("/").map(encodeURIComponent).join("/"); - if (path3.startsWith("/")) path3 = path3.slice(1); - let queryParamString = queryParams.toString(); - queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\+/g, "%20") : ""; - if (!basePath.startsWith("http")) { - return `${basePath}${path3}${queryParamString}`; - } - const _url3 = new URL(`${path3}${queryParamString}`, basePath); - return _url3; -} -var betterFetch = async (url2, options) => { - var _a30, _b2, _c, _d, _e, _f, _g, _h; - const { - hooks, - url: __url, - options: opts - } = await initializePlugins(url2, options); - const fetch2 = getFetch(opts); - const controller = new AbortController(); - const signal = (_a30 = opts.signal) != null ? _a30 : controller.signal; - const _url3 = getURL2(__url, opts); - const body = getBody2(opts); - const headers = await getHeaders(opts); - const method = getMethod(__url, opts); - let context = __spreadProps(__spreadValues({}, opts), { - url: _url3, - headers, - body, - method, - signal - }); - for (const onRequest of hooks.onRequest) { - if (onRequest) { - const res = await onRequest(context); - if (typeof res === "object" && res !== null) { - context = res; - } - } - } - if ("pipeTo" in context && typeof context.pipeTo === "function" || typeof ((_b2 = options == null ? void 0 : options.body) == null ? void 0 : _b2.pipe) === "function") { - if (!("duplex" in context)) { - context.duplex = "half"; - } - } - const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller); - let response = await fetch2(context.url, context); - clearTimeout2(); - const responseContext = { - response, - request: context - }; - for (const onResponse of hooks.onResponse) { - if (onResponse) { - const r = await onResponse(__spreadProps(__spreadValues({}, responseContext), { - response: ((_c = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c.cloneResponse) ? response.clone() : response - })); - if (r instanceof Response) { - response = r; - } else if (typeof r === "object" && r !== null) { - response = r.response; - } - } - } - if (response.ok) { - const hasBody = context.method !== "HEAD"; - if (!hasBody) { - return { - data: "", - error: null - }; - } - const responseType = detectResponseType(response); - const successContext = { - data: null, - response, - request: context - }; - if (responseType === "json" || responseType === "text") { - const text = await response.text(); - const parser2 = (_d = context.jsonParser) != null ? _d : jsonParse; - successContext.data = await parser2(text); - } else { - successContext.data = await response[responseType](); - } - if (context == null ? void 0 : context.output) { - if (context.output && !context.disableValidation) { - successContext.data = await parseStandardSchema( - context.output, - successContext.data - ); - } - } - for (const onSuccess of hooks.onSuccess) { - if (onSuccess) { - await onSuccess(__spreadProps(__spreadValues({}, successContext), { - response: ((_e = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e.cloneResponse) ? response.clone() : response - })); - } - } - if (options == null ? void 0 : options.throw) { - return successContext.data; - } - return { - data: successContext.data, - error: null - }; - } - const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse; - const responseText = await response.text(); - const isJSONResponse2 = isJSONParsable(responseText); - const errorObject = isJSONResponse2 ? await parser(responseText) : null; - const errorContext = { - response, - responseText, - request: context, - error: __spreadProps(__spreadValues({}, errorObject), { - status: response.status, - statusText: response.statusText - }) - }; - for (const onError of hooks.onError) { - if (onError) { - await onError(__spreadProps(__spreadValues({}, errorContext), { - response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response - })); - } - } - if (options == null ? void 0 : options.retry) { - const retryStrategy = createRetryStrategy(options.retry); - const _retryAttempt = (_h = options.retryAttempt) != null ? _h : 0; - if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) { - for (const onRetry of hooks.onRetry) { - if (onRetry) { - await onRetry(responseContext); - } - } - const delay = retryStrategy.getDelay(_retryAttempt); - await new Promise((resolve2) => setTimeout(resolve2, delay)); - return await betterFetch(url2, __spreadProps(__spreadValues({}, options), { - retryAttempt: _retryAttempt + 1 - })); - } - } - if (options == null ? void 0 : options.throw) { - throw new BetterFetchError( - response.status, - response.statusText, - isJSONResponse2 ? errorObject : responseText - ); - } - return { - data: null, - error: __spreadProps(__spreadValues({}, errorObject), { - status: response.status, - statusText: response.statusText - }) - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/refresh-access-token.mjs -function createRefreshAccessTokenRequest({ refreshToken: refreshToken2, options, authentication, extraParams, resource }) { - const body = new URLSearchParams(); - const headers = { - "content-type": "application/x-www-form-urlencoded", - accept: "application/json" - }; - body.set("grant_type", "refresh_token"); - body.set("refresh_token", refreshToken2); - if (authentication === "basic") { - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - if (primaryClientId) headers["authorization"] = "Basic " + base643.encode(`${primaryClientId}:${options.clientSecret ?? ""}`); - else headers["authorization"] = "Basic " + base643.encode(`:${options.clientSecret ?? ""}`); - } else { - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - body.set("client_id", primaryClientId); - if (options.clientSecret) body.set("client_secret", options.clientSecret); - } - if (resource) if (typeof resource === "string") body.append("resource", resource); - else for (const _resource of resource) body.append("resource", _resource); - if (extraParams) for (const [key, value] of Object.entries(extraParams)) body.set(key, value); - return { - body, - headers - }; -} -async function refreshAccessToken({ refreshToken: refreshToken2, options, tokenEndpoint: tokenEndpoint2, authentication, extraParams }) { - const { body, headers } = await createRefreshAccessTokenRequest({ - refreshToken: refreshToken2, - options, - authentication, - extraParams - }); - const { data, error: error49 } = await betterFetch(tokenEndpoint2, { - method: "POST", - body, - headers - }); - if (error49) throw error49; - const tokens = { - accessToken: data.access_token, - refreshToken: data.refresh_token, - tokenType: data.token_type, - scopes: data.scope?.split(" "), - idToken: data.id_token - }; - if (data.expires_in) { - const now2 = /* @__PURE__ */ new Date(); - tokens.accessTokenExpiresAt = new Date(now2.getTime() + data.expires_in * 1e3); - } - if (data.refresh_token_expires_in) { - const now2 = /* @__PURE__ */ new Date(); - tokens.refreshTokenExpiresAt = new Date(now2.getTime() + data.refresh_token_expires_in * 1e3); - } - return tokens; -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/validate-authorization-code.mjs -async function authorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) { - options = typeof options === "function" ? await options() : options; - return createAuthorizationCodeRequest({ - code, - codeVerifier, - redirectURI, - options, - authentication, - deviceId, - headers, - additionalParams, - resource - }); -} -function createAuthorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) { - const body = new URLSearchParams(); - const requestHeaders = { - "content-type": "application/x-www-form-urlencoded", - accept: "application/json", - ...headers - }; - body.set("grant_type", "authorization_code"); - body.set("code", code); - codeVerifier && body.set("code_verifier", codeVerifier); - options.clientKey && body.set("client_key", options.clientKey); - deviceId && body.set("device_id", deviceId); - body.set("redirect_uri", options.redirectURI || redirectURI); - if (resource) if (typeof resource === "string") body.append("resource", resource); - else for (const _resource of resource) body.append("resource", _resource); - if (authentication === "basic") { - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - requestHeaders["authorization"] = `Basic ${base643.encode(`${primaryClientId}:${options.clientSecret ?? ""}`)}`; - } else { - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - body.set("client_id", primaryClientId); - if (options.clientSecret) body.set("client_secret", options.clientSecret); - } - for (const [key, value] of Object.entries(additionalParams)) if (!body.has(key)) body.append(key, value); - return { - body, - headers: requestHeaders - }; -} -async function validateAuthorizationCode({ code, codeVerifier, redirectURI, options, tokenEndpoint: tokenEndpoint2, authentication, deviceId, headers, additionalParams = {}, resource }) { - const { body, headers: requestHeaders } = await authorizationCodeRequest({ - code, - codeVerifier, - redirectURI, - options, - authentication, - deviceId, - headers, - additionalParams, - resource - }); - const { data, error: error49 } = await betterFetch(tokenEndpoint2, { - method: "POST", - body, - headers: requestHeaders - }); - if (error49) throw error49; - return getOAuth2Tokens(data); -} - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/apple.mjs -var apple = (options) => { - const tokenEndpoint2 = "https://appleid.apple.com/auth/token"; - return { - id: "apple", - name: "Apple", - async createAuthorizationURL({ state, scopes, redirectURI }) { - const _scope = options.disableDefaultScope ? [] : ["email", "name"]; - if (options.scope) _scope.push(...options.scope); - if (scopes) _scope.push(...scopes); - return await createAuthorizationURL({ - id: "apple", - options, - authorizationEndpoint: "https://appleid.apple.com/auth/authorize", - scopes: _scope, - state, - redirectURI, - responseMode: "form_post", - responseType: "code id_token" - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - try { - const { kid, alg: jwtAlg } = decodeProtectedHeader(token); - if (!kid || !jwtAlg) return false; - const { payload: jwtClaims } = await jwtVerify(token, await getApplePublicKey(kid), { - algorithms: [jwtAlg], - issuer: "https://appleid.apple.com", - audience: options.audience && options.audience.length ? options.audience : options.appBundleIdentifier ? options.appBundleIdentifier : options.clientId, - maxTokenAge: "1h" - }); - ["email_verified", "is_private_email"].forEach((field) => { - if (jwtClaims[field] !== void 0) jwtClaims[field] = Boolean(jwtClaims[field]); - }); - if (nonce && jwtClaims.nonce !== nonce) return false; - return !!jwtClaims; - } catch { - return false; - } - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.idToken) return null; - const profile = decodeJwt(token.idToken); - if (!profile) return null; - let name; - if (token.user?.name) name = `${token.user.name.firstName || ""} ${token.user.name.lastName || ""}`.trim(); - else name = profile.name || ""; - const emailVerified = typeof profile.email_verified === "boolean" ? profile.email_verified : profile.email_verified === "true"; - const enrichedProfile = { - ...profile, - name - }; - const userMap = await options.mapProfileToUser?.(enrichedProfile); - return { - user: { - id: profile.sub, - name: enrichedProfile.name, - emailVerified, - email: profile.email, - ...userMap - }, - data: enrichedProfile - }; - }, - options - }; -}; -var getApplePublicKey = async (kid) => { - const { data } = await betterFetch(`https://appleid.apple.com/auth/keys`); - if (!data?.keys) throw new APIError2("BAD_REQUEST", { message: "Keys not found" }); - const jwk = data.keys.find((key) => key.kid === kid); - if (!jwk) throw new Error(`JWK with kid ${kid} not found`); - return await importJWK(jwk, jwk.alg); -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/atlassian.mjs -init_logger(); -init_error2(); -var atlassian = (options) => { - const tokenEndpoint2 = "https://auth.atlassian.com/oauth/token"; - return { - id: "atlassian", - name: "Atlassian", - async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - if (!options.clientId || !options.clientSecret) { - logger.error("Client Id and Secret are required for Atlassian"); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Atlassian"); - const _scopes = options.disableDefaultScope ? [] : ["read:jira-user", "offline_access"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "atlassian", - options, - authorizationEndpoint: "https://auth.atlassian.com/authorize", - scopes: _scopes, - state, - codeVerifier, - redirectURI, - additionalParams: { audience: "api.atlassian.com" }, - prompt: options.prompt - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.accessToken) return null; - try { - const { data: profile } = await betterFetch("https://api.atlassian.com/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (!profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.account_id, - name: profile.name, - email: profile.email, - image: profile.picture, - emailVerified: false, - ...userMap - }, - data: profile - }; - } catch (error49) { - logger.error("Failed to fetch user info from Figma:", error49); - return null; - } - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/cognito.mjs -init_logger(); -init_error2(); -var cognito = (options) => { - if (!options.domain || !options.region || !options.userPoolId) { - logger.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."); - throw new BetterAuthError("DOMAIN_AND_REGION_REQUIRED"); - } - const cleanDomain = options.domain.replace(/^https?:\/\//, ""); - const authorizationEndpoint2 = `https://${cleanDomain}/oauth2/authorize`; - const tokenEndpoint2 = `https://${cleanDomain}/oauth2/token`; - const userInfoEndpoint = `https://${cleanDomain}/oauth2/userinfo`; - return { - id: "cognito", - name: "Cognito", - async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - if (!options.clientId) { - logger.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (options.requireClientSecret && !options.clientSecret) { - logger.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."); - throw new BetterAuthError("CLIENT_SECRET_REQUIRED"); - } - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - const url2 = await createAuthorizationURL({ - id: "cognito", - options: { ...options }, - authorizationEndpoint: authorizationEndpoint2, - scopes: _scopes, - state, - codeVerifier, - redirectURI, - prompt: options.prompt - }); - const scopeValue = url2.searchParams.get("scope"); - if (scopeValue) { - url2.searchParams.delete("scope"); - const encodedScope = encodeURIComponent(scopeValue); - const urlString = url2.toString(); - const separator = urlString.includes("?") ? "&" : "?"; - return new URL(`${urlString}${separator}scope=${encodedScope}`); - } - return url2; - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - try { - const { kid, alg: jwtAlg } = decodeProtectedHeader(token); - if (!kid || !jwtAlg) return false; - const publicKey = await getCognitoPublicKey(kid, options.region, options.userPoolId); - const expectedIssuer = `https://cognito-idp.${options.region}.amazonaws.com/${options.userPoolId}`; - const { payload: jwtClaims } = await jwtVerify(token, publicKey, { - algorithms: [jwtAlg], - issuer: expectedIssuer, - audience: options.clientId, - maxTokenAge: "1h" - }); - if (nonce && jwtClaims.nonce !== nonce) return false; - return true; - } catch (error49) { - logger.error("Failed to verify ID token:", error49); - return false; - } - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (token.idToken) try { - const profile = decodeJwt(token.idToken); - if (!profile) return null; - const name = profile.name || profile.given_name || profile.username || ""; - const enrichedProfile = { - ...profile, - name - }; - const userMap = await options.mapProfileToUser?.(enrichedProfile); - return { - user: { - id: profile.sub, - name: enrichedProfile.name, - email: profile.email, - image: profile.picture, - emailVerified: profile.email_verified, - ...userMap - }, - data: enrichedProfile - }; - } catch (error49) { - logger.error("Failed to decode ID token:", error49); - } - if (token.accessToken) try { - const { data: userInfo } = await betterFetch(userInfoEndpoint, { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (userInfo) { - const userMap = await options.mapProfileToUser?.(userInfo); - return { - user: { - id: userInfo.sub, - name: userInfo.name || userInfo.given_name || userInfo.username || "", - email: userInfo.email, - image: userInfo.picture, - emailVerified: userInfo.email_verified, - ...userMap - }, - data: userInfo - }; - } - } catch (error49) { - logger.error("Failed to fetch user info from Cognito:", error49); - } - return null; - }, - options - }; -}; -var getCognitoPublicKey = async (kid, region, userPoolId) => { - const COGNITO_JWKS_URI = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`; - try { - const { data } = await betterFetch(COGNITO_JWKS_URI); - if (!data?.keys) throw new APIError2("BAD_REQUEST", { message: "Keys not found" }); - const jwk = data.keys.find((key) => key.kid === kid); - if (!jwk) throw new Error(`JWK with kid ${kid} not found`); - return await importJWK(jwk, jwk.alg); - } catch (error49) { - logger.error("Failed to fetch Cognito public key:", error49); - throw error49; - } -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/discord.mjs -var discord = (options) => { - const tokenEndpoint2 = "https://discord.com/api/oauth2/token"; - return { - id: "discord", - name: "Discord", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["identify", "email"]; - if (scopes) _scopes.push(...scopes); - if (options.scope) _scopes.push(...options.scope); - const permissionsParam = _scopes.includes("bot") && options.permissions !== void 0 ? `&permissions=${options.permissions}` : ""; - return new URL(`https://discord.com/api/oauth2/authorize?scope=${_scopes.join("+")}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state}&prompt=${options.prompt || "none"}${permissionsParam}`); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://discord.com/api/users/@me", { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error49) return null; - if (profile.avatar === null) profile.image_url = `https://cdn.discordapp.com/embed/avatars/${profile.discriminator === "0" ? Number(BigInt(profile.id) >> BigInt(22)) % 6 : parseInt(profile.discriminator) % 5}.png`; - else { - const format = profile.avatar.startsWith("a_") ? "gif" : "png"; - profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`; - } - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.global_name || profile.username || "", - email: profile.email, - emailVerified: profile.verified, - image: profile.image_url, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/dropbox.mjs -var dropbox = (options) => { - const tokenEndpoint2 = "https://api.dropboxapi.com/oauth2/token"; - return { - id: "dropbox", - name: "Dropbox", - createAuthorizationURL: async ({ state, scopes, codeVerifier, redirectURI }) => { - const _scopes = options.disableDefaultScope ? [] : ["account_info.read"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - const additionalParams = {}; - if (options.accessType) additionalParams.token_access_type = options.accessType; - return await createAuthorizationURL({ - id: "dropbox", - options, - authorizationEndpoint: "https://www.dropbox.com/oauth2/authorize", - scopes: _scopes, - state, - redirectURI, - codeVerifier, - additionalParams - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return await validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.dropboxapi.com/2/users/get_current_account", { - method: "POST", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.account_id, - name: profile.name?.display_name, - email: profile.email, - emailVerified: profile.email_verified || false, - image: profile.profile_photo_url, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/facebook.mjs -var facebook = (options) => { - return { - id: "facebook", - name: "Facebook", - async createAuthorizationURL({ state, scopes, redirectURI, loginHint }) { - const _scopes = options.disableDefaultScope ? [] : ["email", "public_profile"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "facebook", - options, - authorizationEndpoint: "https://www.facebook.com/v24.0/dialog/oauth", - scopes: _scopes, - state, - redirectURI, - loginHint, - additionalParams: options.configId ? { config_id: options.configId } : {} - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://graph.facebook.com/v24.0/oauth/access_token" - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - if (token.split(".").length === 3) try { - const { payload: jwtClaims } = await jwtVerify(token, createRemoteJWKSet(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")), { - algorithms: ["RS256"], - audience: options.clientId, - issuer: "https://www.facebook.com" - }); - if (nonce && jwtClaims.nonce !== nonce) return false; - return !!jwtClaims; - } catch { - return false; - } - return true; - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://graph.facebook.com/v24.0/oauth/access_token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (token.idToken && token.idToken.split(".").length === 3) { - const profile2 = decodeJwt(token.idToken); - const user = { - id: profile2.sub, - name: profile2.name, - email: profile2.email, - picture: { data: { - url: profile2.picture, - height: 100, - width: 100, - is_silhouette: false - } } - }; - const userMap2 = await options.mapProfileToUser?.({ - ...user, - email_verified: false - }); - return { - user: { - ...user, - emailVerified: false, - ...userMap2 - }, - data: profile2 - }; - } - const { data: profile, error: error49 } = await betterFetch("https://graph.facebook.com/me?fields=" + [ - "id", - "name", - "email", - "picture", - ...options?.fields || [] - ].join(","), { auth: { - type: "Bearer", - token: token.accessToken - } }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.name, - email: profile.email, - image: profile.picture.data.url, - emailVerified: profile.email_verified, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/figma.mjs -init_logger(); -init_error2(); -var figma = (options) => { - const tokenEndpoint2 = "https://api.figma.com/v1/oauth/token"; - return { - id: "figma", - name: "Figma", - async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - if (!options.clientId || !options.clientSecret) { - logger.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Figma"); - const _scopes = options.disableDefaultScope ? [] : ["current_user:read"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "figma", - options, - authorizationEndpoint: "https://www.figma.com/oauth", - scopes: _scopes, - state, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2, - authentication: "basic" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2, - authentication: "basic" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - try { - const { data: profile } = await betterFetch("https://api.figma.com/v1/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (!profile) { - logger.error("Failed to fetch user from Figma"); - return null; - } - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.handle, - email: profile.email, - image: profile.img_url, - emailVerified: false, - ...userMap - }, - data: profile - }; - } catch (error49) { - logger.error("Failed to fetch user info from Figma:", error49); - return null; - } - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/github.mjs -init_logger(); -var github = (options) => { - const tokenEndpoint2 = "https://github.com/login/oauth/access_token"; - return { - id: "github", - name: "GitHub", - createAuthorizationURL({ state, scopes, loginHint, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["read:user", "user:email"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "github", - options, - authorizationEndpoint: "https://github.com/login/oauth/authorize", - scopes: _scopes, - state, - codeVerifier, - redirectURI, - loginHint, - prompt: options.prompt - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - const { body, headers: requestHeaders } = createAuthorizationCodeRequest({ - code, - codeVerifier, - redirectURI, - options - }); - const { data, error: error49 } = await betterFetch(tokenEndpoint2, { - method: "POST", - body, - headers: requestHeaders - }); - if (error49) { - logger.error("GitHub OAuth token exchange failed:", error49); - return null; - } - if ("error" in data) { - logger.error("GitHub OAuth token exchange failed:", data); - return null; - } - return getOAuth2Tokens(data); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.github.com/user", { headers: { - "User-Agent": "better-auth", - authorization: `Bearer ${token.accessToken}` - } }); - if (error49) return null; - const { data: emails } = await betterFetch("https://api.github.com/user/emails", { headers: { - Authorization: `Bearer ${token.accessToken}`, - "User-Agent": "better-auth" - } }); - if (!profile.email && emails) profile.email = (emails.find((e) => e.primary) ?? emails[0])?.email; - const emailVerified = emails?.find((e) => e.email === profile.email)?.verified ?? false; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.name || profile.login || "", - email: profile.email, - image: profile.avatar_url, - emailVerified, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/gitlab.mjs -var cleanDoubleSlashes = (input = "") => { - return input.split("://").map((str) => str.replace(/\/{2,}/g, "/")).join("://"); -}; -var issuerToEndpoints = (issuer) => { - const baseUrl = issuer || "https://gitlab.com"; - return { - authorizationEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/authorize`), - tokenEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/token`), - userinfoEndpoint: cleanDoubleSlashes(`${baseUrl}/api/v4/user`) - }; -}; -var gitlab = (options) => { - const { authorizationEndpoint: authorizationEndpoint2, tokenEndpoint: tokenEndpoint2, userinfoEndpoint: userinfoEndpoint2 } = issuerToEndpoints(options.issuer); - const issuerId = "gitlab"; - return { - id: issuerId, - name: "Gitlab", - createAuthorizationURL: async ({ state, scopes, codeVerifier, loginHint, redirectURI }) => { - const _scopes = options.disableDefaultScope ? [] : ["read_user"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: issuerId, - options, - authorizationEndpoint: authorizationEndpoint2, - scopes: _scopes, - state, - redirectURI, - codeVerifier, - loginHint - }); - }, - validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - codeVerifier, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch(userinfoEndpoint2, { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error49 || profile.state !== "active" || profile.locked) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.name ?? profile.username ?? "", - email: profile.email, - image: profile.avatar_url, - emailVerified: profile.email_verified ?? false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/google.mjs -init_logger(); -init_error2(); -var google = (options) => { - return { - id: "google", - name: "Google", - async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, loginHint, display }) { - if (!options.clientId || !options.clientSecret) { - logger.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Google"); - const _scopes = options.disableDefaultScope ? [] : [ - "email", - "profile", - "openid" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "google", - options, - authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth", - scopes: _scopes, - state, - codeVerifier, - redirectURI, - prompt: options.prompt, - accessType: options.accessType, - display: display || options.display, - loginHint, - hd: options.hd, - additionalParams: { include_granted_scopes: "true" } - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://oauth2.googleapis.com/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://oauth2.googleapis.com/token" - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - try { - const { kid, alg: jwtAlg } = decodeProtectedHeader(token); - if (!kid || !jwtAlg) return false; - const { payload: jwtClaims } = await jwtVerify(token, await getGooglePublicKey(kid), { - algorithms: [jwtAlg], - issuer: ["https://accounts.google.com", "accounts.google.com"], - audience: options.clientId, - maxTokenAge: "1h" - }); - if (nonce && jwtClaims.nonce !== nonce) return false; - return true; - } catch { - return false; - } - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.idToken) return null; - const user = decodeJwt(token.idToken); - const userMap = await options.mapProfileToUser?.(user); - return { - user: { - id: user.sub, - name: user.name, - email: user.email, - image: user.picture, - emailVerified: user.email_verified, - ...userMap - }, - data: user - }; - }, - options - }; -}; -var getGooglePublicKey = async (kid) => { - const { data } = await betterFetch("https://www.googleapis.com/oauth2/v3/certs"); - if (!data?.keys) throw new APIError2("BAD_REQUEST", { message: "Keys not found" }); - const jwk = data.keys.find((key) => key.kid === kid); - if (!jwk) throw new Error(`JWK with kid ${kid} not found`); - return await importJWK(jwk, jwk.alg); -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/huggingface.mjs -var huggingface = (options) => { - const tokenEndpoint2 = "https://huggingface.co/oauth/token"; - return { - id: "huggingface", - name: "Hugging Face", - createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "huggingface", - options, - authorizationEndpoint: "https://huggingface.co/oauth/authorize", - scopes: _scopes, - state, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://huggingface.co/oauth/userinfo", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.name || profile.preferred_username || "", - email: profile.email, - image: profile.picture, - emailVerified: profile.email_verified ?? false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/kakao.mjs -var kakao = (options) => { - const tokenEndpoint2 = "https://kauth.kakao.com/oauth/token"; - return { - id: "kakao", - name: "Kakao", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "account_email", - "profile_image", - "profile_nickname" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "kakao", - options, - authorizationEndpoint: "https://kauth.kakao.com/oauth/authorize", - scopes: _scopes, - state, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://kapi.kakao.com/v2/user/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (error49 || !profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - const account = profile.kakao_account || {}; - const kakaoProfile = account.profile || {}; - return { - user: { - id: String(profile.id), - name: kakaoProfile.nickname || account.name || "", - email: account.email, - image: kakaoProfile.profile_image_url || kakaoProfile.thumbnail_image_url, - emailVerified: !!account.is_email_valid && !!account.is_email_verified, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/kick.mjs -var kick = (options) => { - return { - id: "kick", - name: "Kick", - createAuthorizationURL({ state, scopes, redirectURI, codeVerifier }) { - const _scopes = options.disableDefaultScope ? [] : ["user:read"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "kick", - redirectURI, - options, - authorizationEndpoint: "https://id.kick.com/oauth/authorize", - scopes: _scopes, - codeVerifier, - state - }); - }, - async validateAuthorizationCode({ code, redirectURI, codeVerifier }) { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://id.kick.com/oauth/token", - codeVerifier - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://id.kick.com/oauth/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data, error: error49 } = await betterFetch("https://api.kick.com/public/v1/users", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error49) return null; - const profile = data.data[0]; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.user_id, - name: profile.name, - email: profile.email, - image: profile.profile_picture, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/line.mjs -var line = (options) => { - const authorizationEndpoint2 = "https://access.line.me/oauth2/v2.1/authorize"; - const tokenEndpoint2 = "https://api.line.me/oauth2/v2.1/token"; - const userInfoEndpoint = "https://api.line.me/oauth2/v2.1/userinfo"; - const verifyIdTokenEndpoint = "https://api.line.me/oauth2/v2.1/verify"; - return { - id: "line", - name: "LINE", - async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, loginHint }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "line", - options, - authorizationEndpoint: authorizationEndpoint2, - scopes: _scopes, - state, - codeVerifier, - redirectURI, - loginHint - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - const body = new URLSearchParams(); - body.set("id_token", token); - body.set("client_id", options.clientId); - if (nonce) body.set("nonce", nonce); - const { data, error: error49 } = await betterFetch(verifyIdTokenEndpoint, { - method: "POST", - headers: { "content-type": "application/x-www-form-urlencoded" }, - body - }); - if (error49 || !data) return false; - if (data.aud !== options.clientId) return false; - if (data.nonce && data.nonce !== nonce) return false; - return true; - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - let profile = null; - if (token.idToken) try { - profile = decodeJwt(token.idToken); - } catch { - } - if (!profile) { - const { data } = await betterFetch(userInfoEndpoint, { headers: { authorization: `Bearer ${token.accessToken}` } }); - profile = data || null; - } - if (!profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - const id = profile.sub || profile.userId; - const name = profile.name || profile.displayName || ""; - const image = profile.picture || profile.pictureUrl || void 0; - return { - user: { - id, - name, - email: profile.email, - image, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/linear.mjs -var linear = (options) => { - const tokenEndpoint2 = "https://api.linear.app/oauth/token"; - return { - id: "linear", - name: "Linear", - createAuthorizationURL({ state, scopes, loginHint, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["read"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "linear", - options, - authorizationEndpoint: "https://linear.app/oauth/authorize", - scopes: _scopes, - state, - redirectURI, - loginHint - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.linear.app/graphql", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token.accessToken}` - }, - body: JSON.stringify({ query: ` - query { - viewer { - id - name - email - avatarUrl - active - createdAt - updatedAt - } - } - ` }) - }); - if (error49 || !profile?.data?.viewer) return null; - const userData = profile.data.viewer; - const userMap = await options.mapProfileToUser?.(userData); - return { - user: { - id: profile.data.viewer.id, - name: profile.data.viewer.name, - email: profile.data.viewer.email, - image: profile.data.viewer.avatarUrl, - emailVerified: false, - ...userMap - }, - data: userData - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/linkedin.mjs -var linkedin = (options) => { - const authorizationEndpoint2 = "https://www.linkedin.com/oauth/v2/authorization"; - const tokenEndpoint2 = "https://www.linkedin.com/oauth/v2/accessToken"; - return { - id: "linkedin", - name: "Linkedin", - createAuthorizationURL: async ({ state, scopes, redirectURI, loginHint }) => { - const _scopes = options.disableDefaultScope ? [] : [ - "profile", - "email", - "openid" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "linkedin", - options, - authorizationEndpoint: authorizationEndpoint2, - scopes: _scopes, - state, - loginHint, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return await validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.linkedin.com/v2/userinfo", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.name, - email: profile.email, - emailVerified: profile.email_verified || false, - image: profile.picture, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/microsoft-entra-id.mjs -init_logger(); -init_error2(); -var microsoft = (options) => { - const tenant = options.tenantId || "common"; - const authority = options.authority || "https://login.microsoftonline.com"; - const authorizationEndpoint2 = `${authority}/${tenant}/oauth2/v2.0/authorize`; - const tokenEndpoint2 = `${authority}/${tenant}/oauth2/v2.0/token`; - return { - id: "microsoft", - name: "Microsoft EntraID", - createAuthorizationURL(data) { - const scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email", - "User.Read", - "offline_access" - ]; - if (options.scope) scopes.push(...options.scope); - if (data.scopes) scopes.push(...data.scopes); - return createAuthorizationURL({ - id: "microsoft", - options, - authorizationEndpoint: authorizationEndpoint2, - state: data.state, - codeVerifier: data.codeVerifier, - scopes, - redirectURI: data.redirectURI, - prompt: options.prompt, - loginHint: data.loginHint - }); - }, - validateAuthorizationCode({ code, codeVerifier, redirectURI }) { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - try { - const { kid, alg: jwtAlg } = decodeProtectedHeader(token); - if (!kid || !jwtAlg) return false; - const publicKey = await getMicrosoftPublicKey(kid, tenant, authority); - const verifyOptions = { - algorithms: [jwtAlg], - audience: options.clientId, - maxTokenAge: "1h" - }; - if (tenant !== "common" && tenant !== "organizations" && tenant !== "consumers") verifyOptions.issuer = `${authority}/${tenant}/v2.0`; - const { payload: jwtClaims } = await jwtVerify(token, publicKey, verifyOptions); - if (nonce && jwtClaims.nonce !== nonce) return false; - return true; - } catch (error49) { - logger.error("Failed to verify ID token:", error49); - return false; - } - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.idToken) return null; - const user = decodeJwt(token.idToken); - const profilePhotoSize = options.profilePhotoSize || 48; - await betterFetch(`https://graph.microsoft.com/v1.0/me/photos/${profilePhotoSize}x${profilePhotoSize}/$value`, { - headers: { Authorization: `Bearer ${token.accessToken}` }, - async onResponse(context) { - if (options.disableProfilePhoto || !context.response.ok) return; - try { - const pictureBuffer = await context.response.clone().arrayBuffer(); - user.picture = `data:image/jpeg;base64, ${base643.encode(pictureBuffer)}`; - } catch (e) { - logger.error(e && typeof e === "object" && "name" in e ? e.name : "", e); - } - } - }); - const userMap = await options.mapProfileToUser?.(user); - const emailVerified = user.email_verified !== void 0 ? user.email_verified : user.email && (user.verified_primary_email?.includes(user.email) || user.verified_secondary_email?.includes(user.email)) ? true : false; - return { - user: { - id: user.sub, - name: user.name, - email: user.email, - image: user.picture, - emailVerified, - ...userMap - }, - data: user - }; - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - const scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email", - "User.Read", - "offline_access" - ]; - if (options.scope) scopes.push(...options.scope); - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - extraParams: { scope: scopes.join(" ") }, - tokenEndpoint: tokenEndpoint2 - }); - }, - options - }; -}; -var getMicrosoftPublicKey = async (kid, tenant, authority) => { - const { data } = await betterFetch(`${authority}/${tenant}/discovery/v2.0/keys`); - if (!data?.keys) throw new APIError2("BAD_REQUEST", { message: "Keys not found" }); - const jwk = data.keys.find((key) => key.kid === kid); - if (!jwk) throw new Error(`JWK with kid ${kid} not found`); - return await importJWK(jwk, jwk.alg); -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/naver.mjs -var naver = (options) => { - const tokenEndpoint2 = "https://nid.naver.com/oauth2.0/token"; - return { - id: "naver", - name: "Naver", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["profile", "email"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "naver", - options, - authorizationEndpoint: "https://nid.naver.com/oauth2.0/authorize", - scopes: _scopes, - state, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://openapi.naver.com/v1/nid/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (error49 || !profile || profile.resultcode !== "00") return null; - const userMap = await options.mapProfileToUser?.(profile); - const res = profile.response || {}; - return { - user: { - id: res.id, - name: res.name || res.nickname || "", - email: res.email, - image: res.profile_image, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/notion.mjs -var notion = (options) => { - const tokenEndpoint2 = "https://api.notion.com/v1/oauth/token"; - return { - id: "notion", - name: "Notion", - createAuthorizationURL({ state, scopes, loginHint, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : []; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "notion", - options, - authorizationEndpoint: "https://api.notion.com/v1/oauth/authorize", - scopes: _scopes, - state, - redirectURI, - loginHint, - additionalParams: { owner: "user" } - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2, - authentication: "basic" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.notion.com/v1/users/me", { headers: { - Authorization: `Bearer ${token.accessToken}`, - "Notion-Version": "2022-06-28" - } }); - if (error49 || !profile) return null; - const userProfile = profile.bot?.owner?.user; - if (!userProfile) return null; - const userMap = await options.mapProfileToUser?.(userProfile); - return { - user: { - id: userProfile.id, - name: userProfile.name || "", - email: userProfile.person?.email || null, - image: userProfile.avatar_url, - emailVerified: false, - ...userMap - }, - data: userProfile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/paybin.mjs -init_logger(); -init_error2(); -var paybin = (options) => { - const issuer = options.issuer || "https://idp.paybin.io"; - const authorizationEndpoint2 = `${issuer}/oauth2/authorize`; - const tokenEndpoint2 = `${issuer}/oauth2/token`; - return { - id: "paybin", - name: "Paybin", - async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, loginHint }) { - if (!options.clientId || !options.clientSecret) { - logger.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Paybin"); - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "email", - "profile" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "paybin", - options, - authorizationEndpoint: authorizationEndpoint2, - scopes: _scopes, - state, - codeVerifier, - redirectURI, - prompt: options.prompt, - loginHint - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.idToken) return null; - const user = decodeJwt(token.idToken); - const userMap = await options.mapProfileToUser?.(user); - return { - user: { - id: user.sub, - name: user.name || user.preferred_username || "", - email: user.email, - image: user.picture, - emailVerified: user.email_verified || false, - ...userMap - }, - data: user - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/paypal.mjs -init_logger(); -init_error2(); -var paypal = (options) => { - const isSandbox = (options.environment || "sandbox") === "sandbox"; - const authorizationEndpoint2 = isSandbox ? "https://www.sandbox.paypal.com/signin/authorize" : "https://www.paypal.com/signin/authorize"; - const tokenEndpoint2 = isSandbox ? "https://api-m.sandbox.paypal.com/v1/oauth2/token" : "https://api-m.paypal.com/v1/oauth2/token"; - const userInfoEndpoint = isSandbox ? "https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo" : "https://api-m.paypal.com/v1/identity/oauth2/userinfo"; - return { - id: "paypal", - name: "PayPal", - async createAuthorizationURL({ state, codeVerifier, redirectURI }) { - if (!options.clientId || !options.clientSecret) { - logger.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - return await createAuthorizationURL({ - id: "paypal", - options, - authorizationEndpoint: authorizationEndpoint2, - scopes: [], - state, - codeVerifier, - redirectURI, - prompt: options.prompt - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - const credentials = base643.encode(`${options.clientId}:${options.clientSecret}`); - try { - const response = await betterFetch(tokenEndpoint2, { - method: "POST", - headers: { - Authorization: `Basic ${credentials}`, - Accept: "application/json", - "Accept-Language": "en_US", - "Content-Type": "application/x-www-form-urlencoded" - }, - body: new URLSearchParams({ - grant_type: "authorization_code", - code, - redirect_uri: redirectURI - }).toString() - }); - if (!response.data) throw new BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN"); - const data = response.data; - return { - accessToken: data.access_token, - refreshToken: data.refresh_token, - accessTokenExpiresAt: data.expires_in ? new Date(Date.now() + data.expires_in * 1e3) : void 0, - idToken: data.id_token - }; - } catch (error49) { - logger.error("PayPal token exchange failed:", error49); - throw new BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN"); - } - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - const credentials = base643.encode(`${options.clientId}:${options.clientSecret}`); - try { - const response = await betterFetch(tokenEndpoint2, { - method: "POST", - headers: { - Authorization: `Basic ${credentials}`, - Accept: "application/json", - "Accept-Language": "en_US", - "Content-Type": "application/x-www-form-urlencoded" - }, - body: new URLSearchParams({ - grant_type: "refresh_token", - refresh_token: refreshToken2 - }).toString() - }); - if (!response.data) throw new BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN"); - const data = response.data; - return { - accessToken: data.access_token, - refreshToken: data.refresh_token, - accessTokenExpiresAt: data.expires_in ? new Date(Date.now() + data.expires_in * 1e3) : void 0 - }; - } catch (error49) { - logger.error("PayPal token refresh failed:", error49); - throw new BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN"); - } - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - try { - return !!decodeJwt(token).sub; - } catch (error49) { - logger.error("Failed to verify PayPal ID token:", error49); - return false; - } - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.accessToken) { - logger.error("Access token is required to fetch PayPal user info"); - return null; - } - try { - const response = await betterFetch(`${userInfoEndpoint}?schema=paypalv1.1`, { headers: { - Authorization: `Bearer ${token.accessToken}`, - Accept: "application/json" - } }); - if (!response.data) { - logger.error("Failed to fetch user info from PayPal"); - return null; - } - const userInfo = response.data; - const userMap = await options.mapProfileToUser?.(userInfo); - return { - user: { - id: userInfo.user_id, - name: userInfo.name, - email: userInfo.email, - image: userInfo.picture, - emailVerified: userInfo.email_verified, - ...userMap - }, - data: userInfo - }; - } catch (error49) { - logger.error("Failed to fetch user info from PayPal:", error49); - return null; - } - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/polar.mjs -var polar = (options) => { - const tokenEndpoint2 = "https://api.polar.sh/v1/oauth2/token"; - return { - id: "polar", - name: "Polar", - createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "polar", - options, - authorizationEndpoint: "https://polar.sh/oauth2/authorize", - scopes: _scopes, - state, - codeVerifier, - redirectURI, - prompt: options.prompt - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.polar.sh/v1/oauth2/userinfo", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.public_name || profile.username || "", - email: profile.email, - image: profile.avatar_url, - emailVerified: profile.email_verified ?? false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/railway.mjs -var authorizationEndpoint = "https://backboard.railway.com/oauth/auth"; -var tokenEndpoint = "https://backboard.railway.com/oauth/token"; -var userinfoEndpoint = "https://backboard.railway.com/oauth/me"; -var railway = (options) => { - return { - id: "railway", - name: "Railway", - createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "email", - "profile" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "railway", - options, - authorizationEndpoint, - scopes: _scopes, - state, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint, - authentication: "basic" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint, - authentication: "basic" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch(userinfoEndpoint, { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error49 || !profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.name, - email: profile.email, - image: profile.picture, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/reddit.mjs -var reddit = (options) => { - return { - id: "reddit", - name: "Reddit", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["identity"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "reddit", - options, - authorizationEndpoint: "https://www.reddit.com/api/v1/authorize", - scopes: _scopes, - state, - redirectURI, - duration: options.duration - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - const body = new URLSearchParams({ - grant_type: "authorization_code", - code, - redirect_uri: options.redirectURI || redirectURI - }); - const { data, error: error49 } = await betterFetch("https://www.reddit.com/api/v1/access_token", { - method: "POST", - headers: { - "content-type": "application/x-www-form-urlencoded", - accept: "text/plain", - "user-agent": "better-auth", - Authorization: `Basic ${base643.encode(`${options.clientId}:${options.clientSecret}`)}` - }, - body: body.toString() - }); - if (error49) throw error49; - return getOAuth2Tokens(data); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - authentication: "basic", - tokenEndpoint: "https://www.reddit.com/api/v1/access_token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://oauth.reddit.com/api/v1/me", { headers: { - Authorization: `Bearer ${token.accessToken}`, - "User-Agent": "better-auth" - } }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.name, - email: profile.oauth_client_id, - emailVerified: profile.has_verified_email, - image: profile.icon_img?.split("?")[0], - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/roblox.mjs -var roblox = (options) => { - const tokenEndpoint2 = "https://apis.roblox.com/oauth/v1/token"; - return { - id: "roblox", - name: "Roblox", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["openid", "profile"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${_scopes.join("+")}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state}&prompt=${options.prompt || "select_account consent"}`); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI: options.redirectURI || redirectURI, - options, - tokenEndpoint: tokenEndpoint2, - authentication: "post" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://apis.roblox.com/oauth/v1/userinfo", { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.nickname || profile.preferred_username || "", - image: profile.picture, - email: profile.preferred_username || null, - emailVerified: false, - ...userMap - }, - data: { ...profile } - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/salesforce.mjs -init_logger(); -init_error2(); -var salesforce = (options) => { - const isSandbox = (options.environment ?? "production") === "sandbox"; - const authorizationEndpoint2 = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/authorize` : isSandbox ? "https://test.salesforce.com/services/oauth2/authorize" : "https://login.salesforce.com/services/oauth2/authorize"; - const tokenEndpoint2 = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/token` : isSandbox ? "https://test.salesforce.com/services/oauth2/token" : "https://login.salesforce.com/services/oauth2/token"; - const userInfoEndpoint = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/userinfo` : isSandbox ? "https://test.salesforce.com/services/oauth2/userinfo" : "https://login.salesforce.com/services/oauth2/userinfo"; - return { - id: "salesforce", - name: "Salesforce", - async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - if (!options.clientId || !options.clientSecret) { - logger.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Salesforce"); - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "email", - "profile" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "salesforce", - options, - authorizationEndpoint: authorizationEndpoint2, - scopes: _scopes, - state, - codeVerifier, - redirectURI: options.redirectURI || redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI: options.redirectURI || redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - try { - const { data: user } = await betterFetch(userInfoEndpoint, { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (!user) { - logger.error("Failed to fetch user info from Salesforce"); - return null; - } - const userMap = await options.mapProfileToUser?.(user); - return { - user: { - id: user.user_id, - name: user.name, - email: user.email, - image: user.photos?.picture || user.photos?.thumbnail, - emailVerified: user.email_verified ?? false, - ...userMap - }, - data: user - }; - } catch (error49) { - logger.error("Failed to fetch user info from Salesforce:", error49); - return null; - } - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/slack.mjs -var slack = (options) => { - const tokenEndpoint2 = "https://slack.com/api/openid.connect.token"; - return { - id: "slack", - name: "Slack", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (scopes) _scopes.push(...scopes); - if (options.scope) _scopes.push(...options.scope); - const url2 = new URL("https://slack.com/openid/connect/authorize"); - url2.searchParams.set("scope", _scopes.join(" ")); - url2.searchParams.set("response_type", "code"); - url2.searchParams.set("client_id", options.clientId); - url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); - url2.searchParams.set("state", state); - return url2; - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://slack.com/api/openid.connect.userInfo", { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile["https://slack.com/user_id"], - name: profile.name || "", - email: profile.email, - emailVerified: profile.email_verified, - image: profile.picture || profile["https://slack.com/user_image_512"], - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/spotify.mjs -var spotify = (options) => { - const tokenEndpoint2 = "https://accounts.spotify.com/api/token"; - return { - id: "spotify", - name: "Spotify", - createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["user-read-email"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "spotify", - options, - authorizationEndpoint: "https://accounts.spotify.com/authorize", - scopes: _scopes, - state, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.spotify.com/v1/me", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.display_name, - email: profile.email, - image: profile.images[0]?.url, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/tiktok.mjs -var tiktok = (options) => { - const tokenEndpoint2 = "https://open.tiktokapis.com/v2/oauth/token/"; - return { - id: "tiktok", - name: "TikTok", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["user.info.profile"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${_scopes.join(",")}&response_type=code&client_key=${options.clientKey}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state}`); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI: options.redirectURI || redirectURI, - options: { - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { clientSecret: options.clientSecret }, - tokenEndpoint: tokenEndpoint2, - authentication: "post", - extraParams: { client_key: options.clientKey } - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch(`https://open.tiktokapis.com/v2/user/info/?fields=${[ - "open_id", - "avatar_large_url", - "display_name", - "username" - ].join(",")}`, { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error49) return null; - return { - user: { - email: profile.data.user.email || profile.data.user.username, - id: profile.data.user.open_id, - name: profile.data.user.display_name || profile.data.user.username || "", - image: profile.data.user.avatar_large_url, - emailVerified: false - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/twitch.mjs -init_logger(); -var twitch = (options) => { - const tokenEndpoint2 = "https://id.twitch.tv/oauth2/token"; - return { - id: "twitch", - name: "Twitch", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["user:read:email", "openid"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "twitch", - redirectURI, - options, - authorizationEndpoint: "https://id.twitch.tv/oauth2/authorize", - scopes: _scopes, - state, - claims: options.claims || [ - "email", - "email_verified", - "preferred_username", - "picture" - ] - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const idToken = token.idToken; - if (!idToken) { - logger.error("No idToken found in token"); - return null; - } - const profile = decodeJwt(idToken); - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.preferred_username, - email: profile.email, - image: profile.picture, - emailVerified: profile.email_verified, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/twitter.mjs -var twitter = (options) => { - const tokenEndpoint2 = "https://api.x.com/2/oauth2/token"; - return { - id: "twitter", - name: "Twitter", - createAuthorizationURL(data) { - const _scopes = options.disableDefaultScope ? [] : [ - "users.read", - "tweet.read", - "offline.access", - "users.email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (data.scopes) _scopes.push(...data.scopes); - return createAuthorizationURL({ - id: "twitter", - options, - authorizationEndpoint: "https://x.com/i/oauth2/authorize", - scopes: _scopes, - state: data.state, - codeVerifier: data.codeVerifier, - redirectURI: data.redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - authentication: "basic", - redirectURI, - options, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - authentication: "basic", - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: profileError } = await betterFetch("https://api.x.com/2/users/me?user.fields=profile_image_url", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (profileError) return null; - const { data: emailData, error: emailError } = await betterFetch("https://api.x.com/2/users/me?user.fields=confirmed_email", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - let emailVerified = false; - if (!emailError && emailData?.data?.confirmed_email) { - profile.data.email = emailData.data.confirmed_email; - emailVerified = true; - } - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.data.id, - name: profile.data.name, - email: profile.data.email || profile.data.username || null, - image: profile.data.profile_image_url, - emailVerified, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/vercel.mjs -init_error2(); -var vercel = (options) => { - return { - id: "vercel", - name: "Vercel", - createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Vercel"); - let _scopes = void 0; - if (options.scope !== void 0 || scopes !== void 0) { - _scopes = []; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - } - return createAuthorizationURL({ - id: "vercel", - options, - authorizationEndpoint: "https://vercel.com/oauth/authorize", - scopes: _scopes, - state, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://api.vercel.com/login/oauth/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.vercel.com/login/oauth/userinfo", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (error49 || !profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.name ?? profile.preferred_username ?? "", - email: profile.email, - image: profile.picture, - emailVerified: profile.email_verified ?? false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/vk.mjs -var vk = (options) => { - const tokenEndpoint2 = "https://id.vk.com/oauth2/auth"; - return { - id: "vk", - name: "VK", - async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["email", "phone"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "vk", - options, - authorizationEndpoint: "https://id.vk.com/authorize", - scopes: _scopes, - state, - redirectURI, - codeVerifier - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI, deviceId }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI: options.redirectURI || redirectURI, - options, - deviceId, - tokenEndpoint: tokenEndpoint2 - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: tokenEndpoint2 - }); - }, - async getUserInfo(data) { - if (options.getUserInfo) return options.getUserInfo(data); - if (!data.accessToken) return null; - const formBody = new URLSearchParams({ - access_token: data.accessToken, - client_id: options.clientId - }).toString(); - const { data: profile, error: error49 } = await betterFetch("https://id.vk.com/oauth2/user_info", { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: formBody - }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - if (!profile.user.email && !userMap?.email) return null; - return { - user: { - id: profile.user.user_id, - first_name: profile.user.first_name, - last_name: profile.user.last_name, - email: profile.user.email, - image: profile.user.avatar, - emailVerified: false, - birthday: profile.user.birthday, - sex: profile.user.sex, - name: `${profile.user.first_name} ${profile.user.last_name}`, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/wechat.mjs -var wechat = (options) => { - return { - id: "wechat", - name: "WeChat", - createAuthorizationURL({ state, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["snsapi_login"]; - options.scope && _scopes.push(...options.scope); - scopes && _scopes.push(...scopes); - const url2 = new URL("https://open.weixin.qq.com/connect/qrconnect"); - url2.searchParams.set("scope", _scopes.join(",")); - url2.searchParams.set("response_type", "code"); - url2.searchParams.set("appid", options.clientId); - url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); - url2.searchParams.set("state", state); - url2.searchParams.set("lang", options.lang || "cn"); - url2.hash = "wechat_redirect"; - return url2; - }, - validateAuthorizationCode: async ({ code }) => { - const { data: tokenData, error: error49 } = await betterFetch("https://api.weixin.qq.com/sns/oauth2/access_token?" + new URLSearchParams({ - appid: options.clientId, - secret: options.clientSecret, - code, - grant_type: "authorization_code" - }).toString(), { method: "GET" }); - if (error49 || !tokenData || tokenData.errcode) throw new Error(`Failed to validate authorization code: ${tokenData?.errmsg || error49?.message || "Unknown error"}`); - return { - tokenType: "Bearer", - accessToken: tokenData.access_token, - refreshToken: tokenData.refresh_token, - accessTokenExpiresAt: new Date(Date.now() + tokenData.expires_in * 1e3), - scopes: tokenData.scope.split(","), - openid: tokenData.openid, - unionid: tokenData.unionid - }; - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - const { data: tokenData, error: error49 } = await betterFetch("https://api.weixin.qq.com/sns/oauth2/refresh_token?" + new URLSearchParams({ - appid: options.clientId, - grant_type: "refresh_token", - refresh_token: refreshToken2 - }).toString(), { method: "GET" }); - if (error49 || !tokenData || tokenData.errcode) throw new Error(`Failed to refresh access token: ${tokenData?.errmsg || error49?.message || "Unknown error"}`); - return { - tokenType: "Bearer", - accessToken: tokenData.access_token, - refreshToken: tokenData.refresh_token, - accessTokenExpiresAt: new Date(Date.now() + tokenData.expires_in * 1e3), - scopes: tokenData.scope.split(",") - }; - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const openid = token.openid; - if (!openid) return null; - const { data: profile, error: error49 } = await betterFetch("https://api.weixin.qq.com/sns/userinfo?" + new URLSearchParams({ - access_token: token.accessToken || "", - openid, - lang: "zh_CN" - }).toString(), { method: "GET" }); - if (error49 || !profile || profile.errcode) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.unionid || profile.openid || openid, - name: profile.nickname, - email: profile.email || null, - image: profile.headimgurl, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/zoom.mjs -var zoom = (userOptions) => { - const options = { - pkce: true, - ...userOptions - }; - return { - id: "zoom", - name: "Zoom", - createAuthorizationURL: async ({ state, redirectURI, codeVerifier }) => { - const params = new URLSearchParams({ - response_type: "code", - redirect_uri: options.redirectURI ? options.redirectURI : redirectURI, - client_id: options.clientId, - state - }); - if (options.pkce) { - const codeChallenge = await generateCodeChallenge(codeVerifier); - params.set("code_challenge_method", "S256"); - params.set("code_challenge", codeChallenge); - } - const url2 = new URL("https://zoom.us/oauth/authorize"); - url2.search = params.toString(); - return url2; - }, - validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => { - return validateAuthorizationCode({ - code, - redirectURI: options.redirectURI || redirectURI, - codeVerifier, - options, - tokenEndpoint: "https://zoom.us/oauth/token", - authentication: "post" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://zoom.us/oauth/token" - }), - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error49 } = await betterFetch("https://api.zoom.us/v2/users/me", { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error49) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.display_name, - image: profile.pic_url, - email: profile.email, - emailVerified: Boolean(profile.verified), - ...userMap - }, - data: { ...profile } - }; - } - }; -}; - -// ../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/index.mjs -init_zod(); -var socialProviders = { - apple, - atlassian, - cognito, - discord, - facebook, - figma, - github, - microsoft, - google, - huggingface, - slack, - spotify, - twitch, - twitter, - dropbox, - kick, - linear, - linkedin, - gitlab, - tiktok, - reddit, - roblox, - salesforce, - vk, - zoom, - notion, - kakao, - naver, - line, - paybin, - paypal, - polar, - railway, - vercel, - wechat -}; -var socialProviderList = Object.keys(socialProviders); -var SocialProviderListEnum = _enum2(socialProviderList).or(string2()); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/account.mjs -init_zod(); -var listUserAccounts = createAuthEndpoint("/list-accounts", { - method: "GET", - use: [sessionMiddleware], - metadata: { openapi: { - operationId: "listUserAccounts", - description: "List all accounts linked to the user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "array", - items: { - type: "object", - properties: { - id: { type: "string" }, - providerId: { type: "string" }, - createdAt: { - type: "string", - format: "date-time" - }, - updatedAt: { - type: "string", - format: "date-time" - }, - accountId: { type: "string" }, - userId: { type: "string" }, - scopes: { - type: "array", - items: { type: "string" } - } - }, - required: [ - "id", - "providerId", - "createdAt", - "updatedAt", - "accountId", - "userId", - "scopes" - ] - } - } } } - } } - } } -}, async (c) => { - const session = c.context.session; - const accounts2 = await c.context.internalAdapter.findAccounts(session.user.id); - return c.json(accounts2.map((a) => { - const { scope, ...parsed } = parseAccountOutput(c.context.options, a); - return { - ...parsed, - scopes: scope?.split(",") || [] - }; - })); -}); -var linkSocialAccount = createAuthEndpoint("/link-social", { - method: "POST", - requireHeaders: true, - body: object({ - callbackURL: string2().meta({ description: "The URL to redirect to after the user has signed in" }).optional(), - provider: SocialProviderListEnum, - idToken: object({ - token: string2(), - nonce: string2().optional(), - accessToken: string2().optional(), - refreshToken: string2().optional(), - scopes: array(string2()).optional() - }).optional(), - requestSignUp: boolean2().optional(), - scopes: array(string2()).meta({ description: "Additional scopes to request from the provider" }).optional(), - errorCallbackURL: string2().meta({ description: "The URL to redirect to if there is an error during the link process" }).optional(), - disableRedirect: boolean2().meta({ description: "Disable automatic redirection to the provider. Useful for handling the redirection yourself" }).optional(), - additionalData: record(string2(), any()).optional() - }), - use: [sessionMiddleware], - metadata: { openapi: { - description: "Link a social account to the user", - operationId: "linkSocialAccount", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - url: { - type: "string", - description: "The authorization URL to redirect the user to" - }, - redirect: { - type: "boolean", - description: "Indicates if the user should be redirected to the authorization URL" - }, - status: { type: "boolean" } - }, - required: ["redirect"] - } } } - } } - } } -}, async (c) => { - const session = c.context.session; - const provider = await getAwaitableValue(c.context.socialProviders, { value: c.body.provider }); - if (!provider) { - c.context.logger.error("Provider not found. Make sure to add the provider in your auth config", { provider: c.body.provider }); - throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.PROVIDER_NOT_FOUND); - } - if (c.body.idToken) { - if (!provider.verifyIdToken) { - c.context.logger.error("Provider does not support id token verification", { provider: c.body.provider }); - throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED); - } - const { token, nonce } = c.body.idToken; - if (!await provider.verifyIdToken(token, nonce)) { - c.context.logger.error("Invalid id token", { provider: c.body.provider }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_TOKEN); - } - const linkingUserInfo = await provider.getUserInfo({ - idToken: token, - accessToken: c.body.idToken.accessToken, - refreshToken: c.body.idToken.refreshToken - }); - if (!linkingUserInfo || !linkingUserInfo?.user) { - c.context.logger.error("Failed to get user info", { provider: c.body.provider }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO); - } - const linkingUserId = String(linkingUserInfo.user.id); - if (!linkingUserInfo.user.email) { - c.context.logger.error("User email not found", { provider: c.body.provider }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND); - } - if ((await c.context.internalAdapter.findAccounts(session.user.id)).find((a) => a.providerId === provider.id && a.accountId === linkingUserId)) return c.json({ - url: "", - status: true, - redirect: false - }); - if (!c.context.trustedProviders.includes(provider.id) && !linkingUserInfo.user.emailVerified || c.context.options.account?.accountLinking?.enabled === false) throw APIError2.from("UNAUTHORIZED", { - message: "Account not linked - linking not allowed", - code: "LINKING_NOT_ALLOWED" - }); - if (linkingUserInfo.user.email?.toLowerCase() !== session.user.email.toLowerCase() && c.context.options.account?.accountLinking?.allowDifferentEmails !== true) throw APIError2.from("UNAUTHORIZED", { - message: "Account not linked - different emails not allowed", - code: "LINKING_DIFFERENT_EMAILS_NOT_ALLOWED" - }); - try { - await c.context.internalAdapter.createAccount({ - userId: session.user.id, - providerId: provider.id, - accountId: linkingUserId, - accessToken: c.body.idToken.accessToken, - idToken: token, - refreshToken: c.body.idToken.refreshToken, - scope: c.body.idToken.scopes?.join(",") - }); - } catch (_e) { - throw APIError2.from("EXPECTATION_FAILED", { - message: "Account not linked - unable to create account", - code: "LINKING_FAILED" - }); - } - if (c.context.options.account?.accountLinking?.updateUserInfoOnLink === true) try { - await c.context.internalAdapter.updateUser(session.user.id, { - name: linkingUserInfo.user?.name, - image: linkingUserInfo.user?.image - }); - } catch (e) { - console.warn("Could not update user - " + e.toString()); - } - return c.json({ - url: "", - status: true, - redirect: false - }); - } - const state = await generateState(c, { - userId: session.user.id, - email: session.user.email - }, c.body.additionalData); - const url2 = await provider.createAuthorizationURL({ - state: state.state, - codeVerifier: state.codeVerifier, - redirectURI: `${c.context.baseURL}/callback/${provider.id}`, - scopes: c.body.scopes - }); - if (!c.body.disableRedirect) c.setHeader("Location", url2.toString()); - return c.json({ - url: url2.toString(), - redirect: !c.body.disableRedirect - }); -}); -var unlinkAccount = createAuthEndpoint("/unlink-account", { - method: "POST", - body: object({ - providerId: string2(), - accountId: string2().optional() - }), - use: [freshSessionMiddleware], - metadata: { openapi: { - description: "Unlink an account", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } } -}, async (ctx) => { - const { providerId, accountId } = ctx.body; - const accounts2 = await ctx.context.internalAdapter.findAccounts(ctx.context.session.user.id); - if (accounts2.length === 1 && !ctx.context.options.account?.accountLinking?.allowUnlinkingAll) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT); - const accountExist = accounts2.find((account) => accountId ? account.accountId === accountId && account.providerId === providerId : account.providerId === providerId); - if (!accountExist) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND); - await ctx.context.internalAdapter.deleteAccount(accountExist.id); - return ctx.json({ status: true }); -}); -var getAccessToken = createAuthEndpoint("/get-access-token", { - method: "POST", - body: object({ - providerId: string2().meta({ description: "The provider ID for the OAuth provider" }), - accountId: string2().meta({ description: "The account ID associated with the refresh token" }).optional(), - userId: string2().meta({ description: "The user ID associated with the account" }).optional() - }), - metadata: { openapi: { - description: "Get a valid access token, doing a refresh if needed", - responses: { - 200: { - description: "A Valid access token", - content: { "application/json": { schema: { - type: "object", - properties: { - tokenType: { type: "string" }, - idToken: { type: "string" }, - accessToken: { type: "string" }, - accessTokenExpiresAt: { - type: "string", - format: "date-time" - } - } - } } } - }, - 400: { description: "Invalid refresh token or provider configuration" } - } - } } -}, async (ctx) => { - const { providerId, accountId, userId } = ctx.body || {}; - const req = ctx.request; - const session = await getSessionFromCtx(ctx); - if (req && !session) throw ctx.error("UNAUTHORIZED"); - const resolvedUserId = session?.user?.id || userId; - if (!resolvedUserId) throw ctx.error("UNAUTHORIZED"); - const provider = await getAwaitableValue(ctx.context.socialProviders, { value: providerId }); - if (!provider) throw APIError2.from("BAD_REQUEST", { - message: `Provider ${providerId} is not supported.`, - code: "PROVIDER_NOT_SUPPORTED" - }); - const accountData = await getAccountCookie(ctx); - let account = void 0; - if (accountData && accountData.userId === resolvedUserId && providerId === accountData.providerId && (!accountId || accountData.accountId === accountId)) account = accountData; - else account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.accountId === accountId && acc.providerId === providerId : acc.providerId === providerId); - if (!account) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND); - try { - let newTokens = null; - const accessTokenExpired = account.accessTokenExpiresAt && new Date(account.accessTokenExpiresAt).getTime() - Date.now() < 5e3; - if (account.refreshToken && accessTokenExpired && provider.refreshAccessToken) { - const refreshToken2 = await decryptOAuthToken(account.refreshToken, ctx.context); - newTokens = await provider.refreshAccessToken(refreshToken2); - const updatedData = { - accessToken: await setTokenUtil(newTokens?.accessToken, ctx.context), - accessTokenExpiresAt: newTokens?.accessTokenExpiresAt, - refreshToken: newTokens?.refreshToken ? await setTokenUtil(newTokens.refreshToken, ctx.context) : account.refreshToken, - refreshTokenExpiresAt: newTokens?.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt, - idToken: newTokens?.idToken || account.idToken - }; - let updatedAccount = null; - if (account.id) updatedAccount = await ctx.context.internalAdapter.updateAccount(account.id, updatedData); - if (ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, { - ...account, - ...updatedAccount ?? updatedData - }); - } - const accessTokenExpiresAt = (() => { - if (newTokens?.accessTokenExpiresAt) { - if (typeof newTokens.accessTokenExpiresAt === "string") return new Date(newTokens.accessTokenExpiresAt); - return newTokens.accessTokenExpiresAt; - } - if (account.accessTokenExpiresAt) { - if (typeof account.accessTokenExpiresAt === "string") return new Date(account.accessTokenExpiresAt); - return account.accessTokenExpiresAt; - } - })(); - const tokens = { - accessToken: newTokens?.accessToken ?? await decryptOAuthToken(account.accessToken ?? "", ctx.context), - accessTokenExpiresAt, - scopes: account.scope?.split(",") ?? [], - idToken: newTokens?.idToken ?? account.idToken ?? void 0 - }; - return ctx.json(tokens); - } catch (_error) { - throw APIError2.from("BAD_REQUEST", { - message: "Failed to get a valid access token", - code: "FAILED_TO_GET_ACCESS_TOKEN" - }); - } -}); -var refreshToken = createAuthEndpoint("/refresh-token", { - method: "POST", - body: object({ - providerId: string2().meta({ description: "The provider ID for the OAuth provider" }), - accountId: string2().meta({ description: "The account ID associated with the refresh token" }).optional(), - userId: string2().meta({ description: "The user ID associated with the account" }).optional() - }), - metadata: { openapi: { - description: "Refresh the access token using a refresh token", - responses: { - 200: { - description: "Access token refreshed successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - tokenType: { type: "string" }, - idToken: { type: "string" }, - accessToken: { type: "string" }, - refreshToken: { type: "string" }, - accessTokenExpiresAt: { - type: "string", - format: "date-time" - }, - refreshTokenExpiresAt: { - type: "string", - format: "date-time" - } - } - } } } - }, - 400: { description: "Invalid refresh token or provider configuration" } - } - } } -}, async (ctx) => { - const { providerId, accountId, userId } = ctx.body; - const req = ctx.request; - const session = await getSessionFromCtx(ctx); - if (req && !session) throw ctx.error("UNAUTHORIZED"); - const resolvedUserId = session?.user?.id || userId; - if (!resolvedUserId) throw APIError2.from("BAD_REQUEST", { - message: `Either userId or session is required`, - code: "USER_ID_OR_SESSION_REQUIRED" - }); - const provider = await getAwaitableValue(ctx.context.socialProviders, { value: providerId }); - if (!provider) throw APIError2.from("BAD_REQUEST", { - message: `Provider ${providerId} is not supported.`, - code: "PROVIDER_NOT_SUPPORTED" - }); - if (!provider.refreshAccessToken) throw APIError2.from("BAD_REQUEST", { - message: `Provider ${providerId} does not support token refreshing.`, - code: "TOKEN_REFRESH_NOT_SUPPORTED" - }); - let account = void 0; - const accountData = await getAccountCookie(ctx); - if (accountData && accountData.userId === resolvedUserId && (!providerId || providerId === accountData?.providerId)) account = accountData; - else account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.accountId === accountId && acc.providerId === providerId : acc.providerId === providerId); - if (!account) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND); - let refreshToken2 = void 0; - if (accountData && providerId === accountData.providerId) refreshToken2 = accountData.refreshToken ?? void 0; - else refreshToken2 = account.refreshToken ?? void 0; - if (!refreshToken2) throw APIError2.from("BAD_REQUEST", { - message: "Refresh token not found", - code: "REFRESH_TOKEN_NOT_FOUND" - }); - try { - const decryptedRefreshToken = await decryptOAuthToken(refreshToken2, ctx.context); - const tokens = await provider.refreshAccessToken(decryptedRefreshToken); - const resolvedRefreshToken = tokens.refreshToken ? await setTokenUtil(tokens.refreshToken, ctx.context) : refreshToken2; - const resolvedRefreshTokenExpiresAt = tokens.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt; - if (account.id) { - const updateData = { - ...account || {}, - accessToken: await setTokenUtil(tokens.accessToken, ctx.context), - refreshToken: resolvedRefreshToken, - accessTokenExpiresAt: tokens.accessTokenExpiresAt, - refreshTokenExpiresAt: resolvedRefreshTokenExpiresAt, - scope: tokens.scopes?.join(",") || account.scope, - idToken: tokens.idToken || account.idToken - }; - await ctx.context.internalAdapter.updateAccount(account.id, updateData); - } - if (accountData && providerId === accountData.providerId && ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, { - ...accountData, - accessToken: await setTokenUtil(tokens.accessToken, ctx.context), - refreshToken: resolvedRefreshToken, - accessTokenExpiresAt: tokens.accessTokenExpiresAt, - refreshTokenExpiresAt: resolvedRefreshTokenExpiresAt, - scope: tokens.scopes?.join(",") || accountData.scope, - idToken: tokens.idToken || accountData.idToken - }); - return ctx.json({ - accessToken: tokens.accessToken, - refreshToken: tokens.refreshToken ?? decryptedRefreshToken, - accessTokenExpiresAt: tokens.accessTokenExpiresAt, - refreshTokenExpiresAt: resolvedRefreshTokenExpiresAt, - scope: tokens.scopes?.join(",") || account.scope, - idToken: tokens.idToken || account.idToken, - providerId: account.providerId, - accountId: account.accountId - }); - } catch (_error) { - throw APIError2.from("BAD_REQUEST", { - message: "Failed to refresh access token", - code: "FAILED_TO_REFRESH_ACCESS_TOKEN" - }); - } -}); -var accountInfoQuerySchema = optional(object({ accountId: string2().meta({ description: "The provider given account id for which to get the account info" }).optional() })); -var accountInfo = createAuthEndpoint("/account-info", { - method: "GET", - use: [sessionMiddleware], - metadata: { openapi: { - description: "Get the account info provided by the provider", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - user: { - type: "object", - properties: { - id: { type: "string" }, - name: { type: "string" }, - email: { type: "string" }, - image: { type: "string" }, - emailVerified: { type: "boolean" } - }, - required: ["id", "emailVerified"] - }, - data: { - type: "object", - properties: {}, - additionalProperties: true - } - }, - required: ["user", "data"], - additionalProperties: false - } } } - } } - } }, - query: accountInfoQuerySchema -}, async (ctx) => { - const providedAccountId = ctx.query?.accountId; - let account = void 0; - if (!providedAccountId) { - if (ctx.context.options.account?.storeAccountCookie) { - const accountData = await getAccountCookie(ctx); - if (accountData) account = accountData; - } - } else { - const accountData = await ctx.context.internalAdapter.findAccount(providedAccountId); - if (accountData) account = accountData; - } - if (!account || account.userId !== ctx.context.session.user.id) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND); - const provider = await getAwaitableValue(ctx.context.socialProviders, { value: account.providerId }); - if (!provider) throw APIError2.from("INTERNAL_SERVER_ERROR", { - message: `Provider account provider is ${account.providerId} but it is not configured`, - code: "PROVIDER_NOT_CONFIGURED" - }); - const tokens = await getAccessToken({ - ...ctx, - method: "POST", - body: { - accountId: account.accountId, - providerId: account.providerId - }, - returnHeaders: false, - returnStatus: false - }); - if (!tokens.accessToken) throw APIError2.from("BAD_REQUEST", { - message: "Access token not found", - code: "ACCESS_TOKEN_NOT_FOUND" - }); - const info2 = await provider.getUserInfo({ - ...tokens, - accessToken: tokens.accessToken - }); - return ctx.json(info2); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/email-verification.mjs -init_error2(); -init_zod(); -async function createEmailVerificationToken(secret, email3, updateTo, expiresIn = 3600, extraPayload) { - return await signJWT({ - email: email3.toLowerCase(), - updateTo, - ...extraPayload - }, secret, expiresIn); -} -async function sendVerificationEmailFn(ctx, user) { - if (!ctx.context.options.emailVerification?.sendVerificationEmail) { - ctx.context.logger.error("Verification email isn't enabled."); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED); - } - const token = await createEmailVerificationToken(ctx.context.secret, user.email, void 0, ctx.context.options.emailVerification?.expiresIn); - const callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent("/"); - const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user, - url: url2, - token - }, ctx.request)); -} -var sendVerificationEmail = createAuthEndpoint("/send-verification-email", { - method: "POST", - operationId: "sendVerificationEmail", - body: object({ - email: email2().meta({ description: "The email to send the verification email to" }), - callbackURL: string2().meta({ description: "The URL to use for email verification callback" }).optional() - }), - metadata: { openapi: { - operationId: "sendVerificationEmail", - description: "Send a verification email to the user", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - email: { - type: "string", - description: "The email to send the verification email to", - example: "user@example.com" - }, - callbackURL: { - type: "string", - description: "The URL to use for email verification callback", - example: "https://example.com/callback", - nullable: true - } - }, - required: ["email"] - } } } }, - responses: { - "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { - type: "boolean", - description: "Indicates if the email was sent successfully", - example: true - } } - } } } - }, - "400": { - description: "Bad Request", - content: { "application/json": { schema: { - type: "object", - properties: { message: { - type: "string", - description: "Error message", - example: "Verification email isn't enabled" - } } - } } } - } - } - } } -}, async (ctx) => { - if (!ctx.context.options.emailVerification?.sendVerificationEmail) { - ctx.context.logger.error("Verification email isn't enabled."); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED); - } - const { email: email3 } = ctx.body; - const session = await getSessionFromCtx(ctx); - if (!session) { - const user = await ctx.context.internalAdapter.findUserByEmail(email3); - if (!user || user.user.emailVerified) { - await createEmailVerificationToken(ctx.context.secret, email3, void 0, ctx.context.options.emailVerification?.expiresIn); - return ctx.json({ status: true }); - } - await sendVerificationEmailFn(ctx, user.user); - return ctx.json({ status: true }); - } - if (session?.user.email !== email3) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.EMAIL_MISMATCH); - if (session?.user.emailVerified) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.EMAIL_ALREADY_VERIFIED); - await sendVerificationEmailFn(ctx, session.user); - return ctx.json({ status: true }); -}); -var verifyEmail = createAuthEndpoint("/verify-email", { - method: "GET", - operationId: "verifyEmail", - query: object({ - token: string2().meta({ description: "The token to verify the email" }), - callbackURL: string2().meta({ description: "The URL to redirect to after email verification" }).optional() - }), - use: [originCheck((ctx) => ctx.query.callbackURL)], - metadata: { openapi: { - description: "Verify the email of the user", - parameters: [{ - name: "token", - in: "query", - description: "The token to verify the email", - required: true, - schema: { type: "string" } - }, { - name: "callbackURL", - in: "query", - description: "The URL to redirect to after email verification", - required: false, - schema: { type: "string" } - }], - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - user: { - type: "object", - $ref: "#/components/schemas/User" - }, - status: { - type: "boolean", - description: "Indicates if the email was verified successfully" - } - }, - required: ["user", "status"] - } } } - } } - } } -}, async (ctx) => { - function redirectOnError(error49) { - if (ctx.query.callbackURL) { - if (ctx.query.callbackURL.includes("?")) throw ctx.redirect(`${ctx.query.callbackURL}&error=${error49.code}`); - throw ctx.redirect(`${ctx.query.callbackURL}?error=${error49.code}`); - } - throw APIError2.from("UNAUTHORIZED", error49); - } - const { token } = ctx.query; - let jwt2; - try { - jwt2 = await jwtVerify(token, new TextEncoder().encode(ctx.context.secret), { algorithms: ["HS256"] }); - } catch (e) { - if (e instanceof JWTExpired) return redirectOnError(BASE_ERROR_CODES.TOKEN_EXPIRED); - return redirectOnError(BASE_ERROR_CODES.INVALID_TOKEN); - } - const parsed = object({ - email: email2(), - updateTo: string2().optional(), - requestType: string2().optional() - }).parse(jwt2.payload); - const user = await ctx.context.internalAdapter.findUserByEmail(parsed.email); - if (!user) return redirectOnError(BASE_ERROR_CODES.USER_NOT_FOUND); - if (parsed.updateTo) { - const session = await getSessionFromCtx(ctx); - if (session && session.user.email !== parsed.email) return redirectOnError(BASE_ERROR_CODES.INVALID_USER); - switch (parsed.requestType) { - case "change-email-confirmation": { - const newToken = await createEmailVerificationToken(ctx.context.secret, parsed.email, parsed.updateTo, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-verification" }); - const updateCallbackURL = ctx.query.callbackURL ? encodeURIComponent(ctx.query.callbackURL) : encodeURIComponent("/"); - const url2 = `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${updateCallbackURL}`; - if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: { - ...user.user, - email: parsed.updateTo - }, - url: url2, - token: newToken - }, ctx.request)); - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ status: true }); - } - case "change-email-verification": { - let activeSession = session; - if (!activeSession) { - const newSession = await ctx.context.internalAdapter.createSession(user.user.id); - if (!newSession) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); - activeSession = { - session: newSession, - user: user.user - }; - } - const updatedUser2 = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { - email: parsed.updateTo, - emailVerified: true - }); - if (ctx.context.options.emailVerification?.afterEmailVerification) await ctx.context.options.emailVerification.afterEmailVerification(updatedUser2, ctx.request); - await setSessionCookie(ctx, { - session: activeSession.session, - user: { - ...activeSession.user, - email: parsed.updateTo, - emailVerified: true - } - }); - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ - status: true, - user: parseUserOutput(ctx.context.options, updatedUser2) - }); - } - default: { - let activeSession = session; - if (!activeSession) { - const newSession = await ctx.context.internalAdapter.createSession(user.user.id); - if (!newSession) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); - activeSession = { - session: newSession, - user: user.user - }; - } - const updatedUser2 = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { - email: parsed.updateTo, - emailVerified: false - }); - const newToken = await createEmailVerificationToken(ctx.context.secret, parsed.updateTo); - const updateCallbackURL = ctx.query.callbackURL ? encodeURIComponent(ctx.query.callbackURL) : encodeURIComponent("/"); - if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: updatedUser2, - url: `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${updateCallbackURL}`, - token: newToken - }, ctx.request)); - await setSessionCookie(ctx, { - session: activeSession.session, - user: { - ...activeSession.user, - email: parsed.updateTo, - emailVerified: false - } - }); - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ - status: true, - user: parseUserOutput(ctx.context.options, updatedUser2) - }); - } - } - } - if (user.user.emailVerified) { - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ - status: true, - user: null - }); - } - if (ctx.context.options.emailVerification?.beforeEmailVerification) await ctx.context.options.emailVerification.beforeEmailVerification(user.user, ctx.request); - const updatedUser = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { emailVerified: true }); - if (ctx.context.options.emailVerification?.afterEmailVerification) await ctx.context.options.emailVerification.afterEmailVerification(updatedUser, ctx.request); - if (ctx.context.options.emailVerification?.autoSignInAfterVerification) { - const currentSession = await getSessionFromCtx(ctx); - if (!currentSession || currentSession.user.email !== parsed.email) { - const session = await ctx.context.internalAdapter.createSession(user.user.id); - if (!session) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); - await setSessionCookie(ctx, { - session, - user: { - ...user.user, - emailVerified: true - } - }); - } else await setSessionCookie(ctx, { - session: currentSession.session, - user: { - ...currentSession.user, - emailVerified: true - } - }); - } - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ - status: true, - user: null - }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/link-account.mjs -init_env(); -async function handleOAuthUserInfo(c, opts) { - const { userInfo, account, callbackURL, disableSignUp, overrideUserInfo } = opts; - const dbUser = await c.context.internalAdapter.findOAuthUser(userInfo.email.toLowerCase(), account.accountId, account.providerId).catch((e) => { - logger.error("Better auth was unable to query your database.\nError: ", e); - const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`; - throw c.redirect(`${errorURL}?error=internal_server_error`); - }); - let user = dbUser?.user; - const isRegister = !user; - if (dbUser) { - const linkedAccount = dbUser.linkedAccount ?? dbUser.accounts.find((acc) => acc.providerId === account.providerId && acc.accountId === account.accountId); - if (!linkedAccount) { - const accountLinking = c.context.options.account?.accountLinking; - if (!(opts.isTrustedProvider || c.context.trustedProviders.includes(account.providerId)) && !userInfo.emailVerified || accountLinking?.enabled === false || accountLinking?.disableImplicitLinking === true) { - if (isDevelopment()) logger.warn(`User already exist but account isn't linked to ${account.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`); - return { - error: "account not linked", - data: null - }; - } - try { - await c.context.internalAdapter.linkAccount({ - providerId: account.providerId, - accountId: userInfo.id.toString(), - userId: dbUser.user.id, - accessToken: await setTokenUtil(account.accessToken, c.context), - refreshToken: await setTokenUtil(account.refreshToken, c.context), - idToken: account.idToken, - accessTokenExpiresAt: account.accessTokenExpiresAt, - refreshTokenExpiresAt: account.refreshTokenExpiresAt, - scope: account.scope - }); - } catch (e) { - logger.error("Unable to link account", e); - return { - error: "unable to link account", - data: null - }; - } - if (userInfo.emailVerified && !dbUser.user.emailVerified && userInfo.email.toLowerCase() === dbUser.user.email) await c.context.internalAdapter.updateUser(dbUser.user.id, { emailVerified: true }); - } else { - const freshTokens = c.context.options.account?.updateAccountOnSignIn !== false ? Object.fromEntries(Object.entries({ - idToken: account.idToken, - accessToken: await setTokenUtil(account.accessToken, c.context), - refreshToken: await setTokenUtil(account.refreshToken, c.context), - accessTokenExpiresAt: account.accessTokenExpiresAt, - refreshTokenExpiresAt: account.refreshTokenExpiresAt, - scope: account.scope - }).filter(([_, value]) => value !== void 0)) : {}; - if (c.context.options.account?.storeAccountCookie) await setAccountCookie(c, { - ...linkedAccount, - ...freshTokens - }); - if (Object.keys(freshTokens).length > 0) await c.context.internalAdapter.updateAccount(linkedAccount.id, freshTokens); - if (userInfo.emailVerified && !dbUser.user.emailVerified && userInfo.email.toLowerCase() === dbUser.user.email) await c.context.internalAdapter.updateUser(dbUser.user.id, { emailVerified: true }); - } - if (overrideUserInfo) { - const { id: _, ...restUserInfo } = userInfo; - user = await c.context.internalAdapter.updateUser(dbUser.user.id, { - ...restUserInfo, - email: userInfo.email.toLowerCase(), - emailVerified: userInfo.email.toLowerCase() === dbUser.user.email ? dbUser.user.emailVerified || userInfo.emailVerified : userInfo.emailVerified - }); - } - } else { - if (disableSignUp) return { - error: "signup disabled", - data: null, - isRegister: false - }; - try { - const { id: _, ...restUserInfo } = userInfo; - const accountData = { - accessToken: await setTokenUtil(account.accessToken, c.context), - refreshToken: await setTokenUtil(account.refreshToken, c.context), - idToken: account.idToken, - accessTokenExpiresAt: account.accessTokenExpiresAt, - refreshTokenExpiresAt: account.refreshTokenExpiresAt, - scope: account.scope, - providerId: account.providerId, - accountId: userInfo.id.toString() - }; - const { user: createdUser, account: createdAccount } = await c.context.internalAdapter.createOAuthUser({ - ...restUserInfo, - email: userInfo.email.toLowerCase() - }, accountData); - user = createdUser; - if (c.context.options.account?.storeAccountCookie) await setAccountCookie(c, createdAccount); - if (!userInfo.emailVerified && user && c.context.options.emailVerification?.sendOnSignUp && c.context.options.emailVerification?.sendVerificationEmail) { - const token = await createEmailVerificationToken(c.context.secret, user.email, void 0, c.context.options.emailVerification?.expiresIn); - const url2 = `${c.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; - await c.context.runInBackgroundOrAwait(c.context.options.emailVerification.sendVerificationEmail({ - user, - url: url2, - token - }, c.request)); - } - } catch (e) { - logger.error(e); - if (isAPIError2(e)) return { - error: e.message, - data: null, - isRegister: false - }; - return { - error: "unable to create user", - data: null, - isRegister: false - }; - } - } - if (!user) return { - error: "unable to create user", - data: null, - isRegister: false - }; - const session = await c.context.internalAdapter.createSession(user.id); - if (!session) return { - error: "unable to create session", - data: null, - isRegister: false - }; - return { - data: { - session, - user - }, - error: null, - isRegister - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/callback.mjs -init_json(); -init_zod(); -var schema = object({ - code: string2().optional(), - error: string2().optional(), - device_id: string2().optional(), - error_description: string2().optional(), - state: string2().optional(), - user: string2().optional() -}); -var callbackOAuth = createAuthEndpoint("/callback/:id", { - method: ["GET", "POST"], - operationId: "handleOAuthCallback", - body: schema.optional(), - query: schema.optional(), - metadata: { - ...HIDE_METADATA, - allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"] - } -}, async (c) => { - let queryOrBody; - const defaultErrorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`; - if (c.method === "POST") { - const postData = c.body ? schema.parse(c.body) : {}; - const queryData = c.query ? schema.parse(c.query) : {}; - const mergedData = schema.parse({ - ...postData, - ...queryData - }); - const params = new URLSearchParams(); - for (const [key, value] of Object.entries(mergedData)) if (value !== void 0 && value !== null) params.set(key, String(value)); - const redirectURL = `${c.context.baseURL}/callback/${c.params.id}?${params.toString()}`; - throw c.redirect(redirectURL); - } - try { - if (c.method === "GET") queryOrBody = schema.parse(c.query); - else if (c.method === "POST") queryOrBody = schema.parse(c.body); - else throw new Error("Unsupported method"); - } catch (e) { - c.context.logger.error("INVALID_CALLBACK_REQUEST", e); - throw c.redirect(`${defaultErrorURL}?error=invalid_callback_request`); - } - const { code, error: error49, state, error_description, device_id, user: userData } = queryOrBody; - if (!state) { - c.context.logger.error("State not found", error49); - const url2 = `${defaultErrorURL}${defaultErrorURL.includes("?") ? "&" : "?"}state=state_not_found`; - throw c.redirect(url2); - } - const { codeVerifier, callbackURL, link, errorURL, newUserURL, requestSignUp } = await parseState(c); - function redirectOnError(error50, description) { - const baseURL = errorURL ?? defaultErrorURL; - const params = new URLSearchParams({ error: error50 }); - if (description) params.set("error_description", description); - const url2 = `${baseURL}${baseURL.includes("?") ? "&" : "?"}${params.toString()}`; - throw c.redirect(url2); - } - if (error49) redirectOnError(error49, error_description); - if (!code) { - c.context.logger.error("Code not found"); - throw redirectOnError("no_code"); - } - const provider = await getAwaitableValue(c.context.socialProviders, { value: c.params.id }); - if (!provider) { - c.context.logger.error("Oauth provider with id", c.params.id, "not found"); - throw redirectOnError("oauth_provider_not_found"); - } - let tokens; - try { - tokens = await provider.validateAuthorizationCode({ - code, - codeVerifier, - deviceId: device_id, - redirectURI: `${c.context.baseURL}/callback/${provider.id}` - }); - } catch (e) { - c.context.logger.error("", e); - throw redirectOnError("invalid_code"); - } - if (!tokens) throw redirectOnError("invalid_code"); - const parsedUserData = userData ? safeJSONParse(userData) : null; - const userInfo = await provider.getUserInfo({ - ...tokens, - user: parsedUserData ?? void 0 - }).then((res) => res?.user); - if (!userInfo) { - c.context.logger.error("Unable to get user info"); - return redirectOnError("unable_to_get_user_info"); - } - if (!callbackURL) { - c.context.logger.error("No callback URL found"); - throw redirectOnError("no_callback_url"); - } - if (link) { - if (!c.context.trustedProviders.includes(provider.id) && !userInfo.emailVerified || c.context.options.account?.accountLinking?.enabled === false) { - c.context.logger.error("Unable to link account - untrusted provider"); - return redirectOnError("unable_to_link_account"); - } - if (userInfo.email?.toLowerCase() !== link.email.toLowerCase() && c.context.options.account?.accountLinking?.allowDifferentEmails !== true) return redirectOnError("email_doesn't_match"); - const existingAccount = await c.context.internalAdapter.findAccountByProviderId(String(userInfo.id), provider.id); - if (existingAccount) { - if (existingAccount.userId.toString() !== link.userId.toString()) return redirectOnError("account_already_linked_to_different_user"); - const updateData = Object.fromEntries(Object.entries({ - accessToken: await setTokenUtil(tokens.accessToken, c.context), - refreshToken: await setTokenUtil(tokens.refreshToken, c.context), - idToken: tokens.idToken, - accessTokenExpiresAt: tokens.accessTokenExpiresAt, - refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, - scope: tokens.scopes?.join(",") - }).filter(([_, value]) => value !== void 0)); - await c.context.internalAdapter.updateAccount(existingAccount.id, updateData); - } else if (!await c.context.internalAdapter.createAccount({ - userId: link.userId, - providerId: provider.id, - accountId: String(userInfo.id), - ...tokens, - accessToken: await setTokenUtil(tokens.accessToken, c.context), - refreshToken: await setTokenUtil(tokens.refreshToken, c.context), - scope: tokens.scopes?.join(",") - })) return redirectOnError("unable_to_link_account"); - let toRedirectTo2; - try { - toRedirectTo2 = callbackURL.toString(); - } catch { - toRedirectTo2 = callbackURL; - } - throw c.redirect(toRedirectTo2); - } - if (!userInfo.email) { - c.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."); - return redirectOnError("email_not_found"); - } - const accountData = { - providerId: provider.id, - accountId: String(userInfo.id), - ...tokens, - scope: tokens.scopes?.join(",") - }; - const result = await handleOAuthUserInfo(c, { - userInfo: { - ...userInfo, - id: String(userInfo.id), - email: userInfo.email, - name: userInfo.name || "" - }, - account: accountData, - callbackURL, - disableSignUp: provider.disableImplicitSignUp && !requestSignUp || provider.options?.disableSignUp, - overrideUserInfo: provider.options?.overrideUserInfoOnSignIn - }); - if (result.error) { - c.context.logger.error(result.error.split(" ").join("_")); - return redirectOnError(result.error.split(" ").join("_")); - } - const { session, user } = result.data; - await setSessionCookie(c, { - session, - user - }); - let toRedirectTo; - try { - toRedirectTo = (result.isRegister ? newUserURL || callbackURL : callbackURL).toString(); - } catch { - toRedirectTo = result.isRegister ? newUserURL || callbackURL : callbackURL; - } - throw c.redirect(toRedirectTo); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/error.mjs -init_env(); -function sanitize(input) { - return input.replace(//g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g, "&"); -} -var html = (options, code = "Unknown", description = null) => { - const custom2 = options.onAPIError?.customizeDefaultErrorPage; - return ` - - - - - Error - - - -
-${custom2?.disableBackgroundGrid ? "" : ` -
-
-`} - -
- ${custom2?.disableCornerDecorations ? "" : ` - -
-
- -
-
`} - -
-
-
-

- ERROR -

-
-
-
- -

- Something went wrong -

- -
- - CODE: - - - ${sanitize(code)} - -
- -

- ${!description ? `We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find more information about the error here.` : description} -

-
- - -
-
- -`; -}; -var error48 = createAuthEndpoint("/error", { - method: "GET", - metadata: { - ...HIDE_METADATA, - openapi: { - description: "Displays an error page", - responses: { "200": { - description: "Success", - content: { "text/html": { schema: { - type: "string", - description: "The HTML content of the error page" - } } } - } } - } - } -}, async (c) => { - const url2 = new URL(c.request?.url || ""); - const unsanitizedCode = url2.searchParams.get("error") || "UNKNOWN"; - const unsanitizedDescription = url2.searchParams.get("error_description") || null; - const safeCode = /^[\'A-Za-z0-9_-]+$/.test(unsanitizedCode || "") ? unsanitizedCode : "UNKNOWN"; - const safeDescription = unsanitizedDescription ? sanitize(unsanitizedDescription) : null; - const queryParams = new URLSearchParams(); - queryParams.set("error", safeCode); - if (unsanitizedDescription) queryParams.set("error_description", unsanitizedDescription); - const options = c.context.options; - const errorURL = options.onAPIError?.errorURL; - if (errorURL) return new Response(null, { - status: 302, - headers: { Location: `${errorURL}${errorURL.includes("?") ? "&" : "?"}${queryParams.toString()}` } - }); - if (isProduction && !options.onAPIError?.customizeDefaultErrorPage) return new Response(null, { - status: 302, - headers: { Location: `/?${queryParams.toString()}` } - }); - return new Response(html(c.context.options, safeCode, safeDescription), { headers: { "Content-Type": "text/html" } }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/ok.mjs -var ok = createAuthEndpoint("/ok", { - method: "GET", - metadata: { - ...HIDE_METADATA, - openapi: { - description: "Check if the API is working", - responses: { "200": { - description: "API is working", - content: { "application/json": { schema: { - type: "object", - properties: { ok: { - type: "boolean", - description: "Indicates if the API is working" - } }, - required: ["ok"] - } } } - } } - } - } -}, async (ctx) => { - return ctx.json({ ok: true }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/password.mjs -init_error2(); -async function validatePassword(ctx, data) { - const credentialAccount = (await ctx.context.internalAdapter.findAccounts(data.userId))?.find((account) => account.providerId === "credential"); - const currentPassword = credentialAccount?.password; - if (!credentialAccount || !currentPassword) return false; - return await ctx.context.password.verify({ - hash: currentPassword, - password: data.password - }); -} -async function checkPassword(userId, c) { - const credentialAccount = (await c.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === "credential"); - const currentPassword = credentialAccount?.password; - const password = c.body.password; - if (!credentialAccount || !currentPassword || !password) { - if (password) await c.context.password.hash(password); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - } - if (!await c.context.password.verify({ - hash: currentPassword, - password - })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - return true; -} -async function shouldRequirePassword(ctx, userId, allowPasswordless) { - if (!allowPasswordless) return true; - const credentialAccount = (await ctx.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === "credential" && account.password); - return Boolean(credentialAccount); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/password.mjs -init_error2(); -init_id2(); -init_zod(); -function redirectError(ctx, callbackURL, query) { - const url2 = callbackURL ? new URL(callbackURL, ctx.baseURL) : new URL(`${ctx.baseURL}/error`); - if (query) Object.entries(query).forEach(([k, v]) => url2.searchParams.set(k, v)); - return url2.href; -} -function redirectCallback(ctx, callbackURL, query) { - const url2 = new URL(callbackURL, ctx.baseURL); - if (query) Object.entries(query).forEach(([k, v]) => url2.searchParams.set(k, v)); - return url2.href; -} -var requestPasswordReset = createAuthEndpoint("/request-password-reset", { - method: "POST", - body: object({ - email: email2().meta({ description: "The email address of the user to send a password reset email to" }), - redirectTo: string2().meta({ description: "The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN" }).optional() - }), - metadata: { openapi: { - operationId: "requestPasswordReset", - description: "Send a password reset email to the user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - status: { type: "boolean" }, - message: { type: "string" } - } - } } } - } } - } }, - use: [originCheck((ctx) => ctx.body.redirectTo)] -}, async (ctx) => { - if (!ctx.context.options.emailAndPassword?.sendResetPassword) { - ctx.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"); - throw APIError2.from("BAD_REQUEST", { - message: "Reset password isn't enabled", - code: "RESET_PASSWORD_DISABLED" - }); - } - const { email: email3, redirectTo } = ctx.body; - const user = await ctx.context.internalAdapter.findUserByEmail(email3, { includeAccounts: true }); - if (!user) { - generateId(24); - await ctx.context.internalAdapter.findVerificationValue("dummy-verification-token"); - ctx.context.logger.error("Reset Password: User not found", { email: email3 }); - return ctx.json({ - status: true, - message: "If this email exists in our system, check your email for the reset link" - }); - } - const expiresAt = getDate(ctx.context.options.emailAndPassword.resetPasswordTokenExpiresIn || 3600 * 1, "sec"); - const verificationToken = generateId(24); - await ctx.context.internalAdapter.createVerificationValue({ - value: user.user.id, - identifier: `reset-password:${verificationToken}`, - expiresAt - }); - const callbackURL = redirectTo ? encodeURIComponent(redirectTo) : ""; - const url2 = `${ctx.context.baseURL}/reset-password/${verificationToken}?callbackURL=${callbackURL}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.sendResetPassword({ - user: user.user, - url: url2, - token: verificationToken - }, ctx.request)); - return ctx.json({ - status: true, - message: "If this email exists in our system, check your email for the reset link" - }); -}); -var requestPasswordResetCallback = createAuthEndpoint("/reset-password/:token", { - method: "GET", - operationId: "forgetPasswordCallback", - query: object({ callbackURL: string2().meta({ description: "The URL to redirect the user to reset their password" }) }), - use: [originCheck((ctx) => ctx.query.callbackURL)], - metadata: { openapi: { - operationId: "resetPasswordCallback", - description: "Redirects the user to the callback URL with the token", - parameters: [{ - name: "token", - in: "path", - required: true, - description: "The token to reset the password", - schema: { type: "string" } - }, { - name: "callbackURL", - in: "query", - required: true, - description: "The URL to redirect the user to reset their password", - schema: { type: "string" } - }], - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { token: { type: "string" } } - } } } - } } - } } -}, async (ctx) => { - const { token } = ctx.params; - const { callbackURL } = ctx.query; - if (!token || !callbackURL) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: "INVALID_TOKEN" })); - const verification = await ctx.context.internalAdapter.findVerificationValue(`reset-password:${token}`); - if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: "INVALID_TOKEN" })); - throw ctx.redirect(redirectCallback(ctx.context, callbackURL, { token })); -}); -var resetPassword = createAuthEndpoint("/reset-password", { - method: "POST", - operationId: "resetPassword", - query: object({ token: string2().optional() }).optional(), - body: object({ - newPassword: string2().meta({ description: "The new password to set" }), - token: string2().meta({ description: "The token to reset the password" }).optional() - }), - metadata: { openapi: { - operationId: "resetPassword", - description: "Reset the password for a user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } } -}, async (ctx) => { - const token = ctx.body.token || ctx.query?.token; - if (!token) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_TOKEN); - const { newPassword } = ctx.body; - const minLength = ctx.context.password?.config.minPasswordLength; - const maxLength = ctx.context.password?.config.maxPasswordLength; - if (newPassword.length < minLength) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_SHORT); - if (newPassword.length > maxLength) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_LONG); - const id = `reset-password:${token}`; - const verification = await ctx.context.internalAdapter.findVerificationValue(id); - if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_TOKEN); - const userId = verification.value; - const hashedPassword = await ctx.context.password.hash(newPassword); - if (!(await ctx.context.internalAdapter.findAccounts(userId)).find((ac) => ac.providerId === "credential")) await ctx.context.internalAdapter.createAccount({ - userId, - providerId: "credential", - password: hashedPassword, - accountId: userId - }); - else await ctx.context.internalAdapter.updatePassword(userId, hashedPassword); - await ctx.context.internalAdapter.deleteVerificationByIdentifier(id); - if (ctx.context.options.emailAndPassword?.onPasswordReset) { - const user = await ctx.context.internalAdapter.findUserById(userId); - if (user) await ctx.context.options.emailAndPassword.onPasswordReset({ user }, ctx.request); - } - if (ctx.context.options.emailAndPassword?.revokeSessionsOnPasswordReset) await ctx.context.internalAdapter.deleteSessions(userId); - return ctx.json({ status: true }); -}); -var verifyPassword2 = createAuthEndpoint("/verify-password", { - method: "POST", - body: object({ password: string2().meta({ description: "The password to verify" }) }), - metadata: { - scope: "server", - openapi: { - operationId: "verifyPassword", - description: "Verify the current user's password", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } - }, - use: [sensitiveSessionMiddleware] -}, async (ctx) => { - const { password } = ctx.body; - const session = ctx.context.session; - if (!await validatePassword(ctx, { - password, - userId: session.user.id - })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - return ctx.json({ status: true }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-in.mjs -init_error2(); -init_zod(); -var socialSignInBodySchema = object({ - callbackURL: string2().meta({ description: "Callback URL to redirect to after the user has signed in" }).optional(), - newUserCallbackURL: string2().optional(), - errorCallbackURL: string2().meta({ description: "Callback URL to redirect to if an error happens" }).optional(), - provider: SocialProviderListEnum, - disableRedirect: boolean2().meta({ description: "Disable automatic redirection to the provider. Useful for handling the redirection yourself" }).optional(), - idToken: optional(object({ - token: string2().meta({ description: "ID token from the provider" }), - nonce: string2().meta({ description: "Nonce used to generate the token" }).optional(), - accessToken: string2().meta({ description: "Access token from the provider" }).optional(), - refreshToken: string2().meta({ description: "Refresh token from the provider" }).optional(), - expiresAt: number2().meta({ description: "Expiry date of the token" }).optional(), - user: object({ - name: object({ - firstName: string2().optional(), - lastName: string2().optional() - }).optional(), - email: string2().optional() - }).meta({ description: "The user object from the provider. Only available for some providers like Apple." }).optional() - })), - scopes: array(string2()).meta({ description: "Array of scopes to request from the provider. This will override the default scopes passed." }).optional(), - requestSignUp: boolean2().meta({ description: "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider" }).optional(), - loginHint: string2().meta({ description: "The login hint to use for the authorization code request" }).optional(), - additionalData: record(string2(), any()).optional().meta({ description: "Additional data to be passed through the OAuth flow" }) -}); -var signInSocial = () => createAuthEndpoint("/sign-in/social", { - method: "POST", - operationId: "socialSignIn", - body: socialSignInBodySchema, - metadata: { - $Infer: { - body: {}, - returned: {} - }, - openapi: { - description: "Sign in with a social provider", - operationId: "socialSignIn", - responses: { "200": { - description: "Success - Returns either session details or redirect URL", - content: { "application/json": { schema: { - type: "object", - description: "Session response when idToken is provided", - properties: { - token: { type: "string" }, - user: { - type: "object", - $ref: "#/components/schemas/User" - }, - url: { type: "string" }, - redirect: { - type: "boolean", - enum: [false] - } - }, - required: [ - "redirect", - "token", - "user" - ] - } } } - } } - } - } -}, async (c) => { - const provider = await getAwaitableValue(c.context.socialProviders, { value: c.body.provider }); - if (!provider) { - c.context.logger.error("Provider not found. Make sure to add the provider in your auth config", { provider: c.body.provider }); - throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.PROVIDER_NOT_FOUND); - } - if (c.body.idToken) { - if (!provider.verifyIdToken) { - c.context.logger.error("Provider does not support id token verification", { provider: c.body.provider }); - throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED); - } - const { token, nonce } = c.body.idToken; - if (!await provider.verifyIdToken(token, nonce)) { - c.context.logger.error("Invalid id token", { provider: c.body.provider }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_TOKEN); - } - const userInfo = await provider.getUserInfo({ - idToken: token, - accessToken: c.body.idToken.accessToken, - refreshToken: c.body.idToken.refreshToken, - user: c.body.idToken.user - }); - if (!userInfo || !userInfo?.user) { - c.context.logger.error("Failed to get user info", { provider: c.body.provider }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO); - } - if (!userInfo.user.email) { - c.context.logger.error("User email not found", { provider: c.body.provider }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND); - } - const data = await handleOAuthUserInfo(c, { - userInfo: { - ...userInfo.user, - email: userInfo.user.email, - id: String(userInfo.user.id), - name: userInfo.user.name || "", - image: userInfo.user.image, - emailVerified: userInfo.user.emailVerified || false - }, - account: { - providerId: provider.id, - accountId: String(userInfo.user.id), - accessToken: c.body.idToken.accessToken - }, - callbackURL: c.body.callbackURL, - disableSignUp: provider.disableImplicitSignUp && !c.body.requestSignUp || provider.disableSignUp - }); - if (data.error) throw APIError2.from("UNAUTHORIZED", { - message: data.error, - code: "OAUTH_LINK_ERROR" - }); - await setSessionCookie(c, data.data); - return c.json({ - redirect: false, - token: data.data.session.token, - url: void 0, - user: parseUserOutput(c.context.options, data.data.user) - }); - } - const { codeVerifier, state } = await generateState(c, void 0, c.body.additionalData); - const url2 = await provider.createAuthorizationURL({ - state, - codeVerifier, - redirectURI: `${c.context.baseURL}/callback/${provider.id}`, - scopes: c.body.scopes, - loginHint: c.body.loginHint - }); - if (!c.body.disableRedirect) c.setHeader("Location", url2.toString()); - return c.json({ - url: url2.toString(), - redirect: !c.body.disableRedirect - }); -}); -var signInEmail = () => createAuthEndpoint("/sign-in/email", { - method: "POST", - operationId: "signInEmail", - use: [formCsrfMiddleware], - body: object({ - email: string2().meta({ description: "Email of the user" }), - password: string2().meta({ description: "Password of the user" }), - callbackURL: string2().meta({ description: "Callback URL to use as a redirect for email verification" }).optional(), - rememberMe: boolean2().meta({ description: "If this is false, the session will not be remembered. Default is `true`." }).default(true).optional() - }), - metadata: { - allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"], - $Infer: { - body: {}, - returned: {} - }, - openapi: { - operationId: "signInEmail", - description: "Sign in with email and password", - responses: { "200": { - description: "Success - Returns either session details or redirect URL", - content: { "application/json": { schema: { - type: "object", - description: "Session response when idToken is provided", - properties: { - redirect: { - type: "boolean", - enum: [false] - }, - token: { - type: "string", - description: "Session token" - }, - url: { - type: "string", - nullable: true - }, - user: { - type: "object", - $ref: "#/components/schemas/User" - } - }, - required: [ - "redirect", - "token", - "user" - ] - } } } - } } - } - } -}, async (ctx) => { - if (!ctx.context.options?.emailAndPassword?.enabled) { - ctx.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"); - throw APIError2.from("BAD_REQUEST", { - code: "EMAIL_PASSWORD_DISABLED", - message: "Email and password is not enabled" - }); - } - const { email: email3, password } = ctx.body; - if (!email2().safeParse(email3).success) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_EMAIL); - const user = await ctx.context.internalAdapter.findUserByEmail(email3, { includeAccounts: true }); - if (!user) { - await ctx.context.password.hash(password); - ctx.context.logger.error("User not found", { email: email3 }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); - } - const credentialAccount = user.accounts.find((a) => a.providerId === "credential"); - if (!credentialAccount) { - await ctx.context.password.hash(password); - ctx.context.logger.error("Credential account not found", { email: email3 }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); - } - const currentPassword = credentialAccount?.password; - if (!currentPassword) { - await ctx.context.password.hash(password); - ctx.context.logger.error("Password not found", { email: email3 }); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); - } - if (!await ctx.context.password.verify({ - hash: currentPassword, - password - })) { - ctx.context.logger.error("Invalid password"); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); - } - if (ctx.context.options?.emailAndPassword?.requireEmailVerification && !user.user.emailVerified) { - if (!ctx.context.options?.emailVerification?.sendVerificationEmail) throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.EMAIL_NOT_VERIFIED); - if (ctx.context.options?.emailVerification?.sendOnSignIn) { - const token = await createEmailVerificationToken(ctx.context.secret, user.user.email, void 0, ctx.context.options.emailVerification?.expiresIn); - const callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent("/"); - const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: user.user, - url: url2, - token - }, ctx.request)); - } - throw APIError2.from("FORBIDDEN", BASE_ERROR_CODES.EMAIL_NOT_VERIFIED); - } - const session = await ctx.context.internalAdapter.createSession(user.user.id, ctx.body.rememberMe === false); - if (!session) { - ctx.context.logger.error("Failed to create session"); - throw APIError2.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); - } - await setSessionCookie(ctx, { - session, - user: user.user - }, ctx.body.rememberMe === false); - if (ctx.body.callbackURL) ctx.setHeader("Location", ctx.body.callbackURL); - return ctx.json({ - redirect: !!ctx.body.callbackURL, - token: session.token, - url: ctx.body.callbackURL, - user: parseUserOutput(ctx.context.options, user.user) - }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-out.mjs -var signOut = createAuthEndpoint("/sign-out", { - method: "POST", - operationId: "signOut", - requireHeaders: true, - metadata: { openapi: { - operationId: "signOut", - description: "Sign out the current user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { success: { type: "boolean" } } - } } } - } } - } } -}, async (ctx) => { - const sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret); - if (sessionCookieToken) try { - await ctx.context.internalAdapter.deleteSession(sessionCookieToken); - } catch (e) { - ctx.context.logger.error("Failed to delete session from database", e); - } - deleteSessionCookie(ctx); - return ctx.json({ success: true }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-up.mjs -init_env(); -init_error2(); -init_id2(); -init_zod(); -var signUpEmailBodySchema = object({ - name: string2(), - email: email2(), - password: string2().nonempty(), - image: string2().optional(), - callbackURL: string2().optional(), - rememberMe: boolean2().optional() -}).and(record(string2(), any())); -var signUpEmail = () => createAuthEndpoint("/sign-up/email", { - method: "POST", - operationId: "signUpWithEmailAndPassword", - use: [formCsrfMiddleware], - body: signUpEmailBodySchema, - metadata: { - allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"], - $Infer: { - body: {}, - returned: {} - }, - openapi: { - operationId: "signUpWithEmailAndPassword", - description: "Sign up a user using email and password", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the user" - }, - email: { - type: "string", - description: "The email of the user" - }, - password: { - type: "string", - description: "The password of the user" - }, - image: { - type: "string", - description: "The profile image URL of the user" - }, - callbackURL: { - type: "string", - description: "The URL to use for email verification callback" - }, - rememberMe: { - type: "boolean", - description: "If this is false, the session will not be remembered. Default is `true`." - } - }, - required: [ - "name", - "email", - "password" - ] - } } } }, - responses: { - "200": { - description: "Successfully created user", - content: { "application/json": { schema: { - type: "object", - properties: { - token: { - type: "string", - nullable: true, - description: "Authentication token for the session" - }, - user: { - type: "object", - properties: { - id: { - type: "string", - description: "The unique identifier of the user" - }, - email: { - type: "string", - format: "email", - description: "The email address of the user" - }, - name: { - type: "string", - description: "The name of the user" - }, - image: { - type: "string", - format: "uri", - nullable: true, - description: "The profile image URL of the user" - }, - emailVerified: { - type: "boolean", - description: "Whether the email has been verified" - }, - createdAt: { - type: "string", - format: "date-time", - description: "When the user was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "When the user was last updated" - } - }, - required: [ - "id", - "email", - "name", - "emailVerified", - "createdAt", - "updatedAt" - ] - } - }, - required: ["user"] - } } } - }, - "422": { - description: "Unprocessable Entity. User already exists or failed to create user.", - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } } - } - } - } - } -}, async (ctx) => { - return runWithTransaction(ctx.context.adapter, async () => { - if (!ctx.context.options.emailAndPassword?.enabled || ctx.context.options.emailAndPassword?.disableSignUp) throw APIError2.from("BAD_REQUEST", { - message: "Email and password sign up is not enabled", - code: "EMAIL_PASSWORD_SIGN_UP_DISABLED" - }); - const body = ctx.body; - const { name, email: email3, password, image, callbackURL: _callbackURL, rememberMe, ...rest } = body; - if (!email2().safeParse(email3).success) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_EMAIL); - if (!password || typeof password !== "string") throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - const minPasswordLength = ctx.context.password.config.minPasswordLength; - if (password.length < minPasswordLength) { - ctx.context.logger.error("Password is too short"); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_SHORT); - } - const maxPasswordLength = ctx.context.password.config.maxPasswordLength; - if (password.length > maxPasswordLength) { - ctx.context.logger.error("Password is too long"); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_LONG); - } - const shouldReturnGenericDuplicateResponse = ctx.context.options.emailAndPassword.requireEmailVerification; - const shouldSkipAutoSignIn = ctx.context.options.emailAndPassword.autoSignIn === false || shouldReturnGenericDuplicateResponse; - const additionalUserFields = parseUserInput(ctx.context.options, rest, "create"); - const normalizedEmail = email3.toLowerCase(); - const dbUser = await ctx.context.internalAdapter.findUserByEmail(normalizedEmail); - if (dbUser?.user) { - ctx.context.logger.info(`Sign-up attempt for existing email: ${email3}`); - if (shouldReturnGenericDuplicateResponse) { - await ctx.context.password.hash(password); - if (ctx.context.options.emailAndPassword?.onExistingUserSignUp) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.onExistingUserSignUp({ user: dbUser.user }, ctx.request)); - const now2 = /* @__PURE__ */ new Date(); - const generatedId = ctx.context.generateId({ model: "user" }) || generateId(); - const coreFields = { - name, - email: normalizedEmail, - emailVerified: false, - image: image || null, - createdAt: now2, - updatedAt: now2 - }; - const customSyntheticUser = ctx.context.options.emailAndPassword?.customSyntheticUser; - let syntheticUser; - if (customSyntheticUser) { - const additionalFieldKeys = Object.keys(ctx.context.options.user?.additionalFields ?? {}); - const additionalFields = {}; - for (const key of additionalFieldKeys) if (key in additionalUserFields) additionalFields[key] = additionalUserFields[key]; - syntheticUser = customSyntheticUser({ - coreFields, - additionalFields, - id: generatedId - }); - } else syntheticUser = { - ...coreFields, - ...additionalUserFields, - id: generatedId - }; - return ctx.json({ - token: null, - user: parseUserOutput(ctx.context.options, syntheticUser) - }); - } - throw APIError2.from("UNPROCESSABLE_ENTITY", BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL); - } - const hash2 = await ctx.context.password.hash(password); - let createdUser; - try { - createdUser = await ctx.context.internalAdapter.createUser({ - email: normalizedEmail, - name, - image, - ...additionalUserFields, - emailVerified: false - }); - if (!createdUser) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.FAILED_TO_CREATE_USER); - } catch (e) { - if (isDevelopment()) ctx.context.logger.error("Failed to create user", e); - if (isAPIError2(e)) throw e; - ctx.context.logger?.error("Failed to create user", e); - throw APIError2.from("UNPROCESSABLE_ENTITY", BASE_ERROR_CODES.FAILED_TO_CREATE_USER); - } - if (!createdUser) throw APIError2.from("UNPROCESSABLE_ENTITY", BASE_ERROR_CODES.FAILED_TO_CREATE_USER); - await ctx.context.internalAdapter.linkAccount({ - userId: createdUser.id, - providerId: "credential", - accountId: createdUser.id, - password: hash2 - }); - if (ctx.context.options.emailVerification?.sendOnSignUp ?? ctx.context.options.emailAndPassword.requireEmailVerification) { - const token = await createEmailVerificationToken(ctx.context.secret, createdUser.email, void 0, ctx.context.options.emailVerification?.expiresIn); - const callbackURL = body.callbackURL ? encodeURIComponent(body.callbackURL) : encodeURIComponent("/"); - const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; - if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: createdUser, - url: url2, - token - }, ctx.request)); - } - if (shouldSkipAutoSignIn) return ctx.json({ - token: null, - user: parseUserOutput(ctx.context.options, createdUser) - }); - const session = await ctx.context.internalAdapter.createSession(createdUser.id, rememberMe === false); - if (!session) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); - await setSessionCookie(ctx, { - session, - user: createdUser - }, rememberMe === false); - return ctx.json({ - token: session.token, - user: parseUserOutput(ctx.context.options, createdUser) - }); - }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/update-session.mjs -init_error2(); -init_zod(); -var updateSessionBodySchema = record(string2().meta({ description: "Field name must be a string" }), any()); -var updateSession = () => createAuthEndpoint("/update-session", { - method: "POST", - operationId: "updateSession", - body: updateSessionBodySchema, - use: [sessionMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - operationId: "updateSession", - description: "Update the current session", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { session: { - type: "object", - $ref: "#/components/schemas/Session" - } } - } } } - } } - } - } -}, async (ctx) => { - const body = ctx.body; - if (typeof body !== "object" || Array.isArray(body)) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT); - const session = ctx.context.session; - const additionalFields = parseSessionInput(ctx.context.options, body, "update"); - if (Object.keys(additionalFields).length === 0) throw APIError2.fromStatus("BAD_REQUEST", { message: "No fields to update" }); - const newSession = await ctx.context.internalAdapter.updateSession(session.session.token, { - ...additionalFields, - updatedAt: /* @__PURE__ */ new Date() - }) ?? { - ...session.session, - ...additionalFields, - updatedAt: /* @__PURE__ */ new Date() - }; - await setSessionCookie(ctx, { - session: newSession, - user: session.user - }); - return ctx.json({ session: parseSessionOutput(ctx.context.options, newSession) }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/update-user.mjs -init_error2(); -init_zod(); -var updateUserBodySchema = record(string2().meta({ description: "Field name must be a string" }), any()); -var updateUser = () => createAuthEndpoint("/update-user", { - method: "POST", - operationId: "updateUser", - body: updateUserBodySchema, - use: [sessionMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - operationId: "updateUser", - description: "Update the current user", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the user" - }, - image: { - type: "string", - description: "The image of the user", - nullable: true - } - } - } } } }, - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { user: { - type: "object", - $ref: "#/components/schemas/User" - } } - } } } - } } - } - } -}, async (ctx) => { - const body = ctx.body; - if (typeof body !== "object" || Array.isArray(body)) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT); - if (body.email) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED); - const { name, image, ...rest } = body; - const session = ctx.context.session; - const additionalFields = parseUserInput(ctx.context.options, rest, "update"); - if (image === void 0 && name === void 0 && Object.keys(additionalFields).length === 0) throw APIError2.fromStatus("BAD_REQUEST", { message: "No fields to update" }); - const updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { - name, - image, - ...additionalFields - }) ?? { - ...session.user, - ...name !== void 0 && { name }, - ...image !== void 0 && { image }, - ...additionalFields - }; - await setSessionCookie(ctx, { - session: session.session, - user: updatedUser - }); - return ctx.json({ status: true }); -}); -var changePassword = createAuthEndpoint("/change-password", { - method: "POST", - operationId: "changePassword", - body: object({ - newPassword: string2().meta({ description: "The new password to set" }), - currentPassword: string2().meta({ description: "The current password is required" }), - revokeOtherSessions: boolean2().meta({ description: "Must be a boolean value" }).optional() - }), - use: [sensitiveSessionMiddleware], - metadata: { openapi: { - operationId: "changePassword", - description: "Change the password of the user", - responses: { "200": { - description: "Password successfully changed", - content: { "application/json": { schema: { - type: "object", - properties: { - token: { - type: "string", - nullable: true, - description: "New session token if other sessions were revoked" - }, - user: { - type: "object", - properties: { - id: { - type: "string", - description: "The unique identifier of the user" - }, - email: { - type: "string", - format: "email", - description: "The email address of the user" - }, - name: { - type: "string", - description: "The name of the user" - }, - image: { - type: "string", - format: "uri", - nullable: true, - description: "The profile image URL of the user" - }, - emailVerified: { - type: "boolean", - description: "Whether the email has been verified" - }, - createdAt: { - type: "string", - format: "date-time", - description: "When the user was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "When the user was last updated" - } - }, - required: [ - "id", - "email", - "name", - "emailVerified", - "createdAt", - "updatedAt" - ] - } - }, - required: ["user"] - } } } - } } - } } -}, async (ctx) => { - const { newPassword, currentPassword, revokeOtherSessions: revokeOtherSessions2 } = ctx.body; - const session = ctx.context.session; - const minPasswordLength = ctx.context.password.config.minPasswordLength; - if (newPassword.length < minPasswordLength) { - ctx.context.logger.error("Password is too short"); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_SHORT); - } - const maxPasswordLength = ctx.context.password.config.maxPasswordLength; - if (newPassword.length > maxPasswordLength) { - ctx.context.logger.error("Password is too long"); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_LONG); - } - const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account2) => account2.providerId === "credential" && account2.password); - if (!account || !account.password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND); - const passwordHash = await ctx.context.password.hash(newPassword); - if (!await ctx.context.password.verify({ - hash: account.password, - password: currentPassword - })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - await ctx.context.internalAdapter.updateAccount(account.id, { password: passwordHash }); - let token = null; - if (revokeOtherSessions2) { - await ctx.context.internalAdapter.deleteSessions(session.user.id); - const newSession = await ctx.context.internalAdapter.createSession(session.user.id); - if (!newSession) throw APIError2.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_GET_SESSION); - await setSessionCookie(ctx, { - session: newSession, - user: session.user - }); - token = newSession.token; - } - return ctx.json({ - token, - user: parseUserOutput(ctx.context.options, session.user) - }); -}); -var setPassword = createAuthEndpoint({ - method: "POST", - body: object({ newPassword: string2().meta({ description: "The new password to set is required" }) }), - use: [sensitiveSessionMiddleware] -}, async (ctx) => { - const { newPassword } = ctx.body; - const session = ctx.context.session; - const minPasswordLength = ctx.context.password.config.minPasswordLength; - if (newPassword.length < minPasswordLength) { - ctx.context.logger.error("Password is too short"); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_SHORT); - } - const maxPasswordLength = ctx.context.password.config.maxPasswordLength; - if (newPassword.length > maxPasswordLength) { - ctx.context.logger.error("Password is too long"); - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_TOO_LONG); - } - const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account2) => account2.providerId === "credential" && account2.password); - const passwordHash = await ctx.context.password.hash(newPassword); - if (!account) { - await ctx.context.internalAdapter.linkAccount({ - userId: session.user.id, - providerId: "credential", - accountId: session.user.id, - password: passwordHash - }); - return ctx.json({ status: true }); - } - throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.PASSWORD_ALREADY_SET); -}); -var deleteUser = createAuthEndpoint("/delete-user", { - method: "POST", - use: [sensitiveSessionMiddleware], - body: object({ - callbackURL: string2().meta({ description: "The callback URL to redirect to after the user is deleted" }).optional(), - password: string2().meta({ description: "The password of the user is required to delete the user" }).optional(), - token: string2().meta({ description: "The token to delete the user is required" }).optional() - }), - metadata: { openapi: { - operationId: "deleteUser", - description: "Delete the user", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - callbackURL: { - type: "string", - description: "The callback URL to redirect to after the user is deleted" - }, - password: { - type: "string", - description: "The user's password. Required if session is not fresh" - }, - token: { - type: "string", - description: "The deletion verification token" - } - } - } } } }, - responses: { "200": { - description: "User deletion processed successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - success: { - type: "boolean", - description: "Indicates if the operation was successful" - }, - message: { - type: "string", - enum: ["User deleted", "Verification email sent"], - description: "Status message of the deletion process" - } - }, - required: ["success", "message"] - } } } - } } - } } -}, async (ctx) => { - if (!ctx.context.options.user?.deleteUser?.enabled) { - ctx.context.logger.error("Delete user is disabled. Enable it in the options"); - throw APIError2.fromStatus("NOT_FOUND"); - } - const session = ctx.context.session; - if (ctx.body.password) { - const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account2) => account2.providerId === "credential" && account2.password); - if (!account || !account.password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND); - if (!await ctx.context.password.verify({ - hash: account.password, - password: ctx.body.password - })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - } - if (ctx.body.token) { - await deleteUserCallback({ - ...ctx, - query: { token: ctx.body.token } - }); - return ctx.json({ - success: true, - message: "User deleted" - }); - } - if (ctx.context.options.user.deleteUser?.sendDeleteAccountVerification) { - const token = generateRandomString(32, "0-9", "a-z"); - await ctx.context.internalAdapter.createVerificationValue({ - value: session.user.id, - identifier: `delete-account-${token}`, - expiresAt: new Date(Date.now() + (ctx.context.options.user.deleteUser?.deleteTokenExpiresIn || 3600 * 24) * 1e3) - }); - const url2 = `${ctx.context.baseURL}/delete-user/callback?token=${token}&callbackURL=${encodeURIComponent(ctx.body.callbackURL || "/")}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.user.deleteUser.sendDeleteAccountVerification({ - user: session.user, - url: url2, - token - }, ctx.request)); - return ctx.json({ - success: true, - message: "Verification email sent" - }); - } - if (!ctx.body.password && ctx.context.sessionConfig.freshAge !== 0) { - const createdAt = new Date(session.session.createdAt).getTime(); - const freshAge = ctx.context.sessionConfig.freshAge * 1e3; - if (Date.now() - createdAt >= freshAge) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.SESSION_EXPIRED); - } - const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete; - if (beforeDelete) await beforeDelete(session.user, ctx.request); - await ctx.context.internalAdapter.deleteUser(session.user.id); - await ctx.context.internalAdapter.deleteSessions(session.user.id); - deleteSessionCookie(ctx); - const afterDelete = ctx.context.options.user.deleteUser?.afterDelete; - if (afterDelete) await afterDelete(session.user, ctx.request); - return ctx.json({ - success: true, - message: "User deleted" - }); -}); -var deleteUserCallback = createAuthEndpoint("/delete-user/callback", { - method: "GET", - query: object({ - token: string2().meta({ description: "The token to verify the deletion request" }), - callbackURL: string2().meta({ description: "The URL to redirect to after deletion" }).optional() - }), - use: [originCheck((ctx) => ctx.query.callbackURL)], - metadata: { openapi: { - description: "Callback to complete user deletion with verification token", - responses: { "200": { - description: "User successfully deleted", - content: { "application/json": { schema: { - type: "object", - properties: { - success: { - type: "boolean", - description: "Indicates if the deletion was successful" - }, - message: { - type: "string", - enum: ["User deleted"], - description: "Confirmation message" - } - }, - required: ["success", "message"] - } } } - } } - } } -}, async (ctx) => { - if (!ctx.context.options.user?.deleteUser?.enabled) { - ctx.context.logger.error("Delete user is disabled. Enable it in the options"); - throw APIError2.from("NOT_FOUND", { - message: "Not found", - code: "NOT_FOUND" - }); - } - const session = await getSessionFromCtx(ctx); - if (!session) throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO); - const token = await ctx.context.internalAdapter.findVerificationValue(`delete-account-${ctx.query.token}`); - if (!token || token.expiresAt < /* @__PURE__ */ new Date()) throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.INVALID_TOKEN); - if (token.value !== session.user.id) throw APIError2.from("NOT_FOUND", BASE_ERROR_CODES.INVALID_TOKEN); - const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete; - if (beforeDelete) await beforeDelete(session.user, ctx.request); - await ctx.context.internalAdapter.deleteUser(session.user.id); - await ctx.context.internalAdapter.deleteSessions(session.user.id); - await ctx.context.internalAdapter.deleteAccounts(session.user.id); - await ctx.context.internalAdapter.deleteVerificationByIdentifier(`delete-account-${ctx.query.token}`); - deleteSessionCookie(ctx); - const afterDelete = ctx.context.options.user.deleteUser?.afterDelete; - if (afterDelete) await afterDelete(session.user, ctx.request); - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL || "/"); - return ctx.json({ - success: true, - message: "User deleted" - }); -}); -var changeEmail = createAuthEndpoint("/change-email", { - method: "POST", - body: object({ - newEmail: email2().meta({ description: "The new email address to set must be a valid email address" }), - callbackURL: string2().meta({ description: "The URL to redirect to after email verification" }).optional() - }), - use: [sensitiveSessionMiddleware], - metadata: { openapi: { - operationId: "changeEmail", - responses: { "200": { - description: "Email change request processed successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - user: { - type: "object", - $ref: "#/components/schemas/User" - }, - status: { - type: "boolean", - description: "Indicates if the request was successful" - }, - message: { - type: "string", - enum: ["Email updated", "Verification email sent"], - description: "Status message of the email change process", - nullable: true - } - }, - required: ["status"] - } } } - } } - } } -}, async (ctx) => { - if (!ctx.context.options.user?.changeEmail?.enabled) { - ctx.context.logger.error("Change email is disabled."); - throw APIError2.fromStatus("BAD_REQUEST", { message: "Change email is disabled" }); - } - const newEmail = ctx.body.newEmail.toLowerCase(); - if (newEmail === ctx.context.session.user.email) { - ctx.context.logger.error("Email is the same"); - throw APIError2.fromStatus("BAD_REQUEST", { message: "Email is the same" }); - } - const canUpdateWithoutVerification = ctx.context.session.user.emailVerified !== true && ctx.context.options.user.changeEmail.updateEmailWithoutVerification; - const canSendConfirmation = ctx.context.session.user.emailVerified && ctx.context.options.user.changeEmail.sendChangeEmailConfirmation; - const canSendVerification = ctx.context.options.emailVerification?.sendVerificationEmail; - if (!canUpdateWithoutVerification && !canSendConfirmation && !canSendVerification) { - ctx.context.logger.error("Verification email isn't enabled."); - throw APIError2.fromStatus("BAD_REQUEST", { message: "Verification email isn't enabled" }); - } - if (await ctx.context.internalAdapter.findUserByEmail(newEmail)) { - await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn); - ctx.context.logger.info("Change email attempt for existing email"); - return ctx.json({ status: true }); - } - if (canUpdateWithoutVerification) { - await ctx.context.internalAdapter.updateUserByEmail(ctx.context.session.user.email, { email: newEmail }); - await setSessionCookie(ctx, { - session: ctx.context.session.session, - user: { - ...ctx.context.session.user, - email: newEmail - } - }); - if (canSendVerification) { - const token2 = await createEmailVerificationToken(ctx.context.secret, newEmail, void 0, ctx.context.options.emailVerification?.expiresIn); - const url3 = `${ctx.context.baseURL}/verify-email?token=${token2}&callbackURL=${ctx.body.callbackURL || "/"}`; - await ctx.context.runInBackgroundOrAwait(canSendVerification({ - user: { - ...ctx.context.session.user, - email: newEmail - }, - url: url3, - token: token2 - }, ctx.request)); - } - return ctx.json({ status: true }); - } - if (canSendConfirmation) { - const token2 = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-confirmation" }); - const url3 = `${ctx.context.baseURL}/verify-email?token=${token2}&callbackURL=${ctx.body.callbackURL || "/"}`; - await ctx.context.runInBackgroundOrAwait(canSendConfirmation({ - user: ctx.context.session.user, - newEmail, - url: url3, - token: token2 - }, ctx.request)); - return ctx.json({ status: true }); - } - if (!canSendVerification) { - ctx.context.logger.error("Verification email isn't enabled."); - throw APIError2.fromStatus("BAD_REQUEST", { message: "Verification email isn't enabled" }); - } - const token = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-verification" }); - const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || "/"}`; - await ctx.context.runInBackgroundOrAwait(canSendVerification({ - user: { - ...ctx.context.session.user, - email: newEmail - }, - url: url2, - token - }, ctx.request)); - return ctx.json({ status: true }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/to-auth-endpoints.mjs -init_env(); -init_error2(); -var defuReplaceArrays = createDefu((obj, key, value) => { - if (Array.isArray(obj[key]) && Array.isArray(value)) { - obj[key] = value; - return true; - } -}); -var hooksSourceWeakMap = /* @__PURE__ */ new WeakMap(); -function getOperationId(endpoint, key) { - if (!endpoint?.options) return key; - const opts = endpoint.options; - return opts.operationId ?? opts.metadata?.openapi?.operationId ?? key; -} -function toAuthEndpoints(endpoints, ctx) { - const api = {}; - for (const [key, endpoint] of Object.entries(endpoints)) { - api[key] = async (context) => { - const operationId = getOperationId(endpoint, key); - const endpointMethod = endpoint?.options?.method; - const defaultMethod = Array.isArray(endpointMethod) ? endpointMethod[0] : endpointMethod; - const run = async () => { - const authContext = await ctx; - const methodName = context?.method ?? context?.request?.method ?? defaultMethod ?? "?"; - const route = endpoint.path ?? "/:virtual"; - let internalContext = { - ...context, - context: { - ...authContext, - returned: void 0, - responseHeaders: void 0, - session: null - }, - path: endpoint.path, - headers: context?.headers ? new Headers(context?.headers) : void 0 - }; - const hasRequest = context?.request instanceof Request; - const shouldReturnResponse = context?.asResponse ?? hasRequest; - return withSpan(`${methodName} ${route}`, { - [ATTR_HTTP_ROUTE]: route, - [ATTR_OPERATION_ID]: operationId - }, async () => runWithEndpointContext(internalContext, async () => { - const { beforeHooks, afterHooks } = getHooks(authContext); - const before = await runBeforeHooks(internalContext, beforeHooks, endpoint, operationId); - if ("context" in before && before.context && typeof before.context === "object") { - const { headers, ...rest } = before.context; - if (headers) headers.forEach((value, key2) => { - internalContext.headers.set(key2, value); - }); - internalContext = defuReplaceArrays(rest, internalContext); - } else if (before) return shouldReturnResponse ? toResponse(before, { headers: context?.headers }) : context?.returnHeaders ? { - headers: context?.headers, - response: before - } : before; - internalContext.asResponse = false; - internalContext.returnHeaders = true; - internalContext.returnStatus = true; - const result = await runWithEndpointContext(internalContext, () => withSpan(`handler ${route}`, { - [ATTR_HTTP_ROUTE]: route, - [ATTR_OPERATION_ID]: operationId - }, () => endpoint(internalContext))).catch((e) => { - if (isAPIError2(e)) - return { - response: e, - status: e.statusCode, - headers: e.headers ? new Headers(e.headers) : null - }; - throw e; - }); - if (result && result instanceof Response) return result; - internalContext.context.returned = result.response; - internalContext.context.responseHeaders = result.headers; - const after = await runAfterHooks(internalContext, afterHooks, endpoint, operationId); - if (after.response) result.response = after.response; - if (isAPIError2(result.response) && shouldPublishLog(authContext.logger.level, "debug")) result.response.stack = result.response.errorStack; - if (isAPIError2(result.response) && !shouldReturnResponse) throw result.response; - return shouldReturnResponse ? toResponse(result.response, { - headers: result.headers, - status: result.status - }) : context?.returnHeaders ? context?.returnStatus ? { - headers: result.headers, - response: result.response, - status: result.status - } : { - headers: result.headers, - response: result.response - } : context?.returnStatus ? { - response: result.response, - status: result.status - } : result.response; - })); - }; - if (await hasRequestState()) return run(); - else return runWithRequestState(/* @__PURE__ */ new WeakMap(), run); - }; - api[key].path = endpoint.path; - api[key].options = endpoint.options; - } - return api; -} -async function runBeforeHooks(context, hooks, endpoint, operationId) { - let modifiedContext = {}; - for (const hook of hooks) { - let matched = false; - try { - matched = hook.matcher(context); - } catch (error49) { - const hookSource = hooksSourceWeakMap.get(hook.handler) ?? "unknown"; - context.context.logger.error(`An error occurred during ${hookSource} hook matcher execution:`, error49); - throw new APIError2("INTERNAL_SERVER_ERROR", { message: `An error occurred during hook matcher execution. Check the logs for more details.` }); - } - if (matched) { - const hookSource = hooksSourceWeakMap.get(hook.handler) ?? "unknown"; - const route = endpoint.path ?? "/:virtual"; - const result = await withSpan(`hook before ${route} ${hookSource}`, { - [ATTR_HOOK_TYPE]: "before", - [ATTR_HTTP_ROUTE]: route, - [ATTR_CONTEXT]: hookSource, - [ATTR_OPERATION_ID]: operationId - }, () => hook.handler({ - ...context, - returnHeaders: false - })).catch((e) => { - if (isAPIError2(e) && shouldPublishLog(context.context.logger.level, "debug")) e.stack = e.errorStack; - throw e; - }); - if (result && typeof result === "object") { - if ("context" in result && typeof result.context === "object") { - const { headers, ...rest } = result.context; - if (headers instanceof Headers) if (modifiedContext.headers) headers.forEach((value, key) => { - modifiedContext.headers?.set(key, value); - }); - else modifiedContext.headers = headers; - modifiedContext = defuReplaceArrays(rest, modifiedContext); - continue; - } - return result; - } - } - } - return { context: modifiedContext }; -} -async function runAfterHooks(context, hooks, endpoint, operationId) { - for (const hook of hooks) if (hook.matcher(context)) { - const hookSource = hooksSourceWeakMap.get(hook.handler) ?? "unknown"; - const route = endpoint.path ?? "/:virtual"; - const result = await withSpan(`hook after ${route} ${hookSource}`, { - [ATTR_HOOK_TYPE]: "after", - [ATTR_HTTP_ROUTE]: route, - [ATTR_CONTEXT]: hookSource, - [ATTR_OPERATION_ID]: operationId - }, () => hook.handler(context)).catch((e) => { - if (isAPIError2(e)) { - const headers = e[kAPIErrorHeaderSymbol]; - if (shouldPublishLog(context.context.logger.level, "debug")) e.stack = e.errorStack; - return { - response: e, - headers: headers ? headers : e.headers ? new Headers(e.headers) : null - }; - } - throw e; - }); - if (result.headers) result.headers.forEach((value, key) => { - if (!context.context.responseHeaders) context.context.responseHeaders = new Headers({ [key]: value }); - else if (key.toLowerCase() === "set-cookie") context.context.responseHeaders.append(key, value); - else context.context.responseHeaders.set(key, value); - }); - if (result.response) context.context.returned = result.response; - } - return { - response: context.context.returned, - headers: context.context.responseHeaders - }; -} -function getHooks(authContext) { - const plugins = authContext.options.plugins || []; - const beforeHooks = []; - const afterHooks = []; - const beforeHookHandler = authContext.options.hooks?.before; - if (beforeHookHandler) { - hooksSourceWeakMap.set(beforeHookHandler, "user"); - beforeHooks.push({ - matcher: () => true, - handler: beforeHookHandler - }); - } - const afterHookHandler = authContext.options.hooks?.after; - if (afterHookHandler) { - hooksSourceWeakMap.set(afterHookHandler, "user"); - afterHooks.push({ - matcher: () => true, - handler: afterHookHandler - }); - } - const pluginBeforeHooks = plugins.flatMap((plugin) => (plugin.hooks?.before ?? []).map((h) => { - hooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`); - return h; - })); - const pluginAfterHooks = plugins.flatMap((plugin) => (plugin.hooks?.after ?? []).map((h) => { - hooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`); - return h; - })); - if (pluginBeforeHooks.length) beforeHooks.push(...pluginBeforeHooks); - if (pluginAfterHooks.length) afterHooks.push(...pluginAfterHooks); - return { - beforeHooks, - afterHooks - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/index.mjs -init_env(); -init_error2(); -function checkEndpointConflicts(options, logger2) { - const endpointRegistry = /* @__PURE__ */ new Map(); - options.plugins?.forEach((plugin) => { - if (plugin.endpoints) { - for (const [key, endpoint] of Object.entries(plugin.endpoints)) if (endpoint && "path" in endpoint && typeof endpoint.path === "string") { - const path3 = endpoint.path; - let methods2 = []; - if (endpoint.options && "method" in endpoint.options) { - if (Array.isArray(endpoint.options.method)) methods2 = endpoint.options.method; - else if (typeof endpoint.options.method === "string") methods2 = [endpoint.options.method]; - } - if (methods2.length === 0) methods2 = ["*"]; - if (!endpointRegistry.has(path3)) endpointRegistry.set(path3, []); - endpointRegistry.get(path3).push({ - pluginId: plugin.id, - endpointKey: key, - methods: methods2 - }); - } - } - }); - const conflicts = []; - for (const [path3, entries] of endpointRegistry.entries()) if (entries.length > 1) { - const methodMap = /* @__PURE__ */ new Map(); - let hasConflict = false; - for (const entry of entries) for (const method of entry.methods) { - if (!methodMap.has(method)) methodMap.set(method, []); - methodMap.get(method).push(entry.pluginId); - if (methodMap.get(method).length > 1) hasConflict = true; - if (method === "*" && entries.length > 1) hasConflict = true; - else if (method !== "*" && methodMap.has("*")) hasConflict = true; - } - if (hasConflict) { - const uniquePlugins = [...new Set(entries.map((e) => e.pluginId))]; - const conflictingMethods = []; - for (const [method, plugins] of methodMap.entries()) if (plugins.length > 1 || method === "*" && entries.length > 1 || method !== "*" && methodMap.has("*")) conflictingMethods.push(method); - conflicts.push({ - path: path3, - plugins: uniquePlugins, - conflictingMethods - }); - } - } - if (conflicts.length > 0) { - const conflictMessages = conflicts.map((conflict) => ` - "${conflict.path}" [${conflict.conflictingMethods.join(", ")}] used by plugins: ${conflict.plugins.join(", ")}`).join("\n"); - logger2.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods: -${conflictMessages} - -To resolve this, you can: - 1. Use only one of the conflicting plugins - 2. Configure the plugins to use different paths (if supported) - 3. Ensure plugins use different HTTP methods for the same path -`); - } -} -function getEndpoints(ctx, options) { - const pluginEndpoints = options.plugins?.reduce((acc, plugin) => { - return { - ...acc, - ...plugin.endpoints - }; - }, {}) ?? {}; - const middlewares = options.plugins?.map((plugin) => plugin.middlewares?.map((m) => { - const middleware = async (context) => { - const authContext = await ctx; - return withSpan(`middleware ${m.path} ${plugin.id}`, { - [ATTR_HOOK_TYPE]: "middleware", - [ATTR_HTTP_ROUTE]: m.path, - [ATTR_CONTEXT]: `plugin:${plugin.id}` - }, () => m.middleware({ - ...context, - context: { - ...authContext, - ...context.context - } - })); - }; - middleware.options = m.middleware.options; - return { - path: m.path, - middleware - }; - })).filter((plugin) => plugin !== void 0).flat() || []; - return { - api: toAuthEndpoints({ - signInSocial: signInSocial(), - callbackOAuth, - getSession: getSession(), - signOut, - signUpEmail: signUpEmail(), - signInEmail: signInEmail(), - resetPassword, - verifyPassword: verifyPassword2, - verifyEmail, - sendVerificationEmail, - changeEmail, - changePassword, - setPassword, - updateSession: updateSession(), - updateUser: updateUser(), - deleteUser, - requestPasswordReset, - requestPasswordResetCallback, - listSessions: listSessions(), - revokeSession, - revokeSessions, - revokeOtherSessions, - linkSocialAccount, - listUserAccounts, - deleteUserCallback, - unlinkAccount, - refreshToken, - getAccessToken, - accountInfo, - ...pluginEndpoints, - ok, - error: error48 - }, ctx), - middlewares - }; -} -var router = (ctx, options) => { - const { api, middlewares } = getEndpoints(ctx, options); - const basePath = new URL(ctx.baseURL).pathname; - return createRouter$1(api, { - routerContext: ctx, - openapi: { disabled: true }, - basePath, - routerMiddleware: [{ - path: "/**", - middleware: originCheckMiddleware - }, ...middlewares], - allowedMediaTypes: ["application/json"], - skipTrailingSlashes: options.advanced?.skipTrailingSlashes ?? false, - async onRequest(req) { - const disabledPaths = ctx.options.disabledPaths || []; - const normalizedPath = normalizePathname(req.url, basePath); - if (disabledPaths.includes(normalizedPath)) return new Response("Not Found", { status: 404 }); - let currentRequest = req; - for (const plugin of ctx.options.plugins || []) if (plugin.onRequest) { - const response = await withSpan(`onRequest ${plugin.id}`, { - [ATTR_HOOK_TYPE]: "onRequest", - [ATTR_CONTEXT]: `plugin:${plugin.id}` - }, () => plugin.onRequest(currentRequest, ctx)); - if (response && "response" in response) return response.response; - if (response && "request" in response) currentRequest = response.request; - } - const rateLimitResponse2 = await onRequestRateLimit(currentRequest, ctx); - if (rateLimitResponse2) return rateLimitResponse2; - return currentRequest; - }, - async onResponse(res, req) { - await onResponseRateLimit(req, ctx); - for (const plugin of ctx.options.plugins || []) if (plugin.onResponse) { - const response = await withSpan(`onResponse ${plugin.id}`, { - [ATTR_HOOK_TYPE]: "onResponse", - [ATTR_CONTEXT]: `plugin:${plugin.id}`, - [ATTR_HTTP_RESPONSE_STATUS_CODE]: res.status - }, () => plugin.onResponse(res, ctx)); - if (response) return response.response; - } - return res; - }, - onError(e) { - if (isAPIError2(e) && e.status === "FOUND") return; - if (options.onAPIError?.throw) throw e; - if (options.onAPIError?.onError) { - options.onAPIError.onError(e, ctx); - return; - } - const optLogLevel = options.logger?.level; - const log = optLogLevel === "error" || optLogLevel === "warn" || optLogLevel === "debug" ? logger : void 0; - if (options.logger?.disabled !== true) { - if (e && typeof e === "object" && "message" in e && typeof e.message === "string") { - if (e.message.includes("no column") || e.message.includes("column") || e.message.includes("relation") || e.message.includes("table") || e.message.includes("does not exist")) { - ctx.logger?.error(e.message); - return; - } - } - if (isAPIError2(e)) { - if (e.status === "INTERNAL_SERVER_ERROR") ctx.logger.error(e.status, e); - log?.error(e.message); - } else ctx.logger?.error(e && typeof e === "object" && "name" in e ? e.name : "", e); - } - } - }); -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/adapter-base.mjs -init_env(); -async function getBaseAdapter(options, handleDirectDatabase) { - let adapter; - if (!options.database) { - const tables = getAuthTables(options); - const memoryDB = Object.keys(tables).reduce((acc, key) => { - acc[key] = []; - return acc; - }, {}); - const { memoryAdapter: memoryAdapter2 } = await Promise.resolve().then(() => (init_dist(), dist_exports)); - adapter = memoryAdapter2(memoryDB)(options); - } else if (typeof options.database === "function") adapter = options.database(options); - else adapter = await handleDirectDatabase(options); - if (!adapter.transaction) { - logger.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."); - adapter.transaction = async (cb) => { - return cb(adapter); - }; - } - return adapter; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/adapter-kysely.mjs -init_error2(); -async function getAdapter(options) { - return getBaseAdapter(options, async (opts) => { - const { createKyselyAdapter: createKyselyAdapter2 } = await Promise.resolve().then(() => (init_kysely_adapter(), kysely_adapter_exports)); - const { kysely, databaseType, transaction } = await createKyselyAdapter2(opts); - if (!kysely) throw new BetterAuthError("Failed to initialize database adapter"); - const { kyselyAdapter: kyselyAdapter2 } = await Promise.resolve().then(() => (init_kysely_adapter(), kysely_adapter_exports)); - return kyselyAdapter2(kysely, { - type: databaseType || "sqlite", - debugLogs: opts.database && "debugLogs" in opts.database ? opts.database.debugLogs : false, - transaction - })(opts); - }); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/get-schema.mjs -function getSchema(config4) { - const tables = getAuthTables(config4); - const schema3 = {}; - for (const key in tables) { - const table = tables[key]; - const fields = table.fields; - const actualFields = {}; - Object.entries(fields).forEach(([key2, field]) => { - actualFields[field.fieldName || key2] = field; - if (field.references) { - const refTable = tables[field.references.model]; - if (refTable) actualFields[field.fieldName || key2].references = { - ...field.references, - model: refTable.modelName, - field: field.references.field - }; - } - }); - if (schema3[table.modelName]) { - schema3[table.modelName].fields = { - ...schema3[table.modelName].fields, - ...actualFields - }; - continue; - } - schema3[table.modelName] = { - fields: actualFields, - order: table.order || Infinity - }; - } - return schema3; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/get-migration.mjs -init_env(); -init_dist2(); -init_adapter(); -init_esm3(); -var map2 = { - postgres: { - string: [ - "character varying", - "varchar", - "text", - "uuid" - ], - number: [ - "int4", - "integer", - "bigint", - "smallint", - "numeric", - "real", - "double precision" - ], - boolean: ["bool", "boolean"], - date: [ - "timestamptz", - "timestamp", - "date" - ], - json: ["json", "jsonb"] - }, - mysql: { - string: [ - "varchar", - "text", - "uuid" - ], - number: [ - "integer", - "int", - "bigint", - "smallint", - "decimal", - "float", - "double" - ], - boolean: ["boolean", "tinyint"], - date: [ - "timestamp", - "datetime", - "date" - ], - json: ["json"] - }, - sqlite: { - string: ["TEXT"], - number: ["INTEGER", "REAL"], - boolean: ["INTEGER", "BOOLEAN"], - date: ["DATE", "INTEGER"], - json: ["TEXT"] - }, - mssql: { - string: [ - "varchar", - "nvarchar", - "uniqueidentifier" - ], - number: [ - "int", - "bigint", - "smallint", - "decimal", - "float", - "double" - ], - boolean: ["bit", "smallint"], - date: [ - "datetime2", - "date", - "datetime" - ], - json: ["varchar", "nvarchar"] - } -}; -function matchType(columnDataType, fieldType, dbType) { - function normalize2(type) { - return type.toLowerCase().split("(")[0].trim(); - } - if (fieldType === "string[]" || fieldType === "number[]") return columnDataType.toLowerCase().includes("json"); - const types = map2[dbType]; - return (Array.isArray(fieldType) ? types["string"].map((t) => t.toLowerCase()) : types[fieldType].map((t) => t.toLowerCase())).includes(normalize2(columnDataType)); -} -async function getPostgresSchema(db) { - try { - const result = await sql`SHOW search_path`.execute(db); - const searchPath = result.rows[0]?.search_path ?? result.rows[0]?.searchPath; - if (searchPath) return searchPath.split(",").map((s) => s.trim()).map((s) => s.replace(/^["']|["']$/g, "")).filter((s) => !s.startsWith("$") && !s.startsWith("\\$"))[0] || "public"; - } catch { - } - return "public"; -} -async function getMigrations(config4) { - const betterAuthSchema = getSchema(config4); - const logger2 = createLogger2(config4.logger); - let { kysely: db, databaseType: dbType } = await createKyselyAdapter(config4); - if (!dbType) { - logger2.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."); - dbType = "sqlite"; - } - if (!db) { - logger2.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."); - process.exit(1); - } - let currentSchema = "public"; - if (dbType === "postgres") { - currentSchema = await getPostgresSchema(db); - logger2.debug(`PostgreSQL migration: Using schema '${currentSchema}' (from search_path)`); - try { - const schemaCheck = await sql` - SELECT schema_name - FROM information_schema.schemata - WHERE schema_name = ${currentSchema} - `.execute(db); - if (!(schemaCheck.rows[0]?.schema_name ?? schemaCheck.rows[0]?.schemaName)) logger2.warn(`Schema '${currentSchema}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`); - } catch (error49) { - logger2.debug(`Could not verify schema existence: ${error49 instanceof Error ? error49.message : String(error49)}`); - } - } - const allTableMetadata = await db.introspection.getTables(); - let tableMetadata = allTableMetadata; - if (dbType === "postgres") try { - const tablesInSchema = await sql` - SELECT table_name - FROM information_schema.tables - WHERE table_schema = ${currentSchema} - AND table_type = 'BASE TABLE' - `.execute(db); - const tableNamesInSchema = new Set(tablesInSchema.rows.map((row) => row.table_name ?? row.tableName)); - tableMetadata = allTableMetadata.filter((table) => table.schema === currentSchema && tableNamesInSchema.has(table.name)); - logger2.debug(`Found ${tableMetadata.length} table(s) in schema '${currentSchema}': ${tableMetadata.map((t) => t.name).join(", ") || "(none)"}`); - } catch (error49) { - logger2.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${error49 instanceof Error ? error49.message : String(error49)}`); - } - const toBeCreated = []; - const toBeAdded = []; - for (const [key, value] of Object.entries(betterAuthSchema)) { - const table = tableMetadata.find((t) => t.name === key); - if (!table) { - const tIndex = toBeCreated.findIndex((t) => t.table === key); - const tableData = { - table: key, - fields: value.fields, - order: value.order || Infinity - }; - const insertIndex = toBeCreated.findIndex((t) => (t.order || Infinity) > tableData.order); - if (insertIndex === -1) if (tIndex === -1) toBeCreated.push(tableData); - else toBeCreated[tIndex].fields = { - ...toBeCreated[tIndex].fields, - ...value.fields - }; - else toBeCreated.splice(insertIndex, 0, tableData); - continue; - } - const toBeAddedFields = {}; - for (const [fieldName, field] of Object.entries(value.fields)) { - const column = table.columns.find((c) => c.name === fieldName); - if (!column) { - toBeAddedFields[fieldName] = field; - continue; - } - if (matchType(column.dataType, field.type, dbType)) continue; - else logger2.warn(`Field ${fieldName} in table ${key} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`); - } - if (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({ - table: key, - fields: toBeAddedFields, - order: value.order || Infinity - }); - } - const migrations = []; - const useUUIDs = config4.advanced?.database?.generateId === "uuid"; - const useNumberId = config4.advanced?.database?.generateId === "serial"; - function getType(field, fieldName) { - const type = field.type; - const provider = dbType || "sqlite"; - const typeMap = { - string: { - sqlite: "text", - postgres: "text", - mysql: field.unique ? "varchar(255)" : field.references ? "varchar(36)" : field.sortable ? "varchar(255)" : field.index ? "varchar(255)" : "text", - mssql: field.unique || field.sortable ? "varchar(255)" : field.references ? "varchar(36)" : "varchar(8000)" - }, - boolean: { - sqlite: "integer", - postgres: "boolean", - mysql: "boolean", - mssql: "smallint" - }, - number: { - sqlite: field.bigint ? "bigint" : "integer", - postgres: field.bigint ? "bigint" : "integer", - mysql: field.bigint ? "bigint" : "integer", - mssql: field.bigint ? "bigint" : "integer" - }, - date: { - sqlite: "date", - postgres: "timestamptz", - mysql: "timestamp(3)", - mssql: sql`datetime2(3)` - }, - json: { - sqlite: "text", - postgres: "jsonb", - mysql: "json", - mssql: "varchar(8000)" - }, - id: { - postgres: useNumberId ? sql`integer GENERATED BY DEFAULT AS IDENTITY` : useUUIDs ? "uuid" : "text", - mysql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", - mssql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", - sqlite: useNumberId ? "integer" : "text" - }, - foreignKeyId: { - postgres: useNumberId ? "integer" : useUUIDs ? "uuid" : "text", - mysql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", - mssql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", - sqlite: useNumberId ? "integer" : "text" - }, - "string[]": { - sqlite: "text", - postgres: "jsonb", - mysql: "json", - mssql: "varchar(8000)" - }, - "number[]": { - sqlite: "text", - postgres: "jsonb", - mysql: "json", - mssql: "varchar(8000)" - } - }; - if (fieldName === "id" || field.references?.field === "id") { - if (fieldName === "id") return typeMap.id[provider]; - return typeMap.foreignKeyId[provider]; - } - if (Array.isArray(type)) return "text"; - if (!(type in typeMap)) throw new Error(`Unsupported field type '${String(type)}' for field '${fieldName}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`); - return typeMap[type][provider]; - } - const getModelName = initGetModelName({ - schema: getAuthTables(config4), - usePlural: false - }); - const getFieldName = initGetFieldName({ - schema: getAuthTables(config4), - usePlural: false - }); - function getReferencePath(model, field) { - try { - return `${getModelName(model)}.${getFieldName({ - model, - field - })}`; - } catch { - return `${model}.${field}`; - } - } - if (toBeAdded.length) for (const table of toBeAdded) for (const [fieldName, field] of Object.entries(table.fields)) { - const type = getType(field, fieldName); - const builder = db.schema.alterTable(table.table); - if (field.index) { - const indexName = `${table.table}_${fieldName}_${field.unique ? "uidx" : "idx"}`; - const indexBuilder = db.schema.createIndex(indexName).on(table.table).columns([fieldName]); - migrations.push(field.unique ? indexBuilder.unique() : indexBuilder); - } - const built = builder.addColumn(fieldName, type, (col) => { - col = field.required !== false ? col.notNull() : col; - if (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || "cascade"); - if (field.unique) col = col.unique(); - if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`); - else col = col.defaultTo(sql`CURRENT_TIMESTAMP`); - return col; - }); - migrations.push(built); - } - const toBeIndexed = []; - if (toBeCreated.length) for (const table of toBeCreated) { - const idType = getType({ type: useNumberId ? "number" : "string" }, "id"); - let dbT = db.schema.createTable(table.table).addColumn("id", idType, (col) => { - if (useNumberId) { - if (dbType === "postgres") return col.primaryKey().notNull(); - else if (dbType === "sqlite") return col.primaryKey().notNull(); - else if (dbType === "mssql") return col.identity().primaryKey().notNull(); - return col.autoIncrement().primaryKey().notNull(); - } - if (useUUIDs) { - if (dbType === "postgres") return col.primaryKey().defaultTo(sql`pg_catalog.gen_random_uuid()`).notNull(); - return col.primaryKey().notNull(); - } - return col.primaryKey().notNull(); - }); - for (const [fieldName, field] of Object.entries(table.fields)) { - const type = getType(field, fieldName); - dbT = dbT.addColumn(fieldName, type, (col) => { - col = field.required !== false ? col.notNull() : col; - if (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || "cascade"); - if (field.unique) col = col.unique(); - if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`); - else col = col.defaultTo(sql`CURRENT_TIMESTAMP`); - return col; - }); - if (field.index) { - const builder = db.schema.createIndex(`${table.table}_${fieldName}_${field.unique ? "uidx" : "idx"}`).on(table.table).columns([fieldName]); - toBeIndexed.push(field.unique ? builder.unique() : builder); - } - } - migrations.push(dbT); - } - if (toBeIndexed.length) for (const index of toBeIndexed) migrations.push(index); - async function runMigrations() { - for (const migration of migrations) await migration.execute(); - } - async function compileMigrations() { - return migrations.map((m) => m.compile().sql).join(";\n\n") + ";"; - } - return { - toBeCreated, - toBeAdded, - runMigrations, - compileMigrations - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/constants.mjs -var DEFAULT_SECRET = "better-auth-secret-12345678901234567890"; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/secret-utils.mjs -init_error2(); -function estimateEntropy(str) { - const unique2 = new Set(str).size; - if (unique2 === 0) return 0; - return Math.log2(Math.pow(unique2, str.length)); -} -function parseSecretsEnv(envValue) { - if (!envValue) return null; - return envValue.split(",").map((entry) => { - entry = entry.trim(); - const colonIdx = entry.indexOf(":"); - if (colonIdx === -1) throw new BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry: "${entry}". Expected format: ":"`); - const version3 = parseInt(entry.slice(0, colonIdx), 10); - if (!Number.isInteger(version3) || version3 < 0) throw new BetterAuthError(`Invalid version in BETTER_AUTH_SECRETS: "${entry.slice(0, colonIdx)}". Version must be a non-negative integer.`); - const value = entry.slice(colonIdx + 1).trim(); - if (!value) throw new BetterAuthError(`Empty secret value for version ${version3} in BETTER_AUTH_SECRETS.`); - return { - version: version3, - value - }; - }); -} -function validateSecretsArray(secrets, logger2) { - if (secrets.length === 0) throw new BetterAuthError("`secrets` array must contain at least one entry."); - const seen = /* @__PURE__ */ new Set(); - for (const s of secrets) { - const version3 = parseInt(String(s.version), 10); - if (!Number.isInteger(version3) || version3 < 0 || String(version3) !== String(s.version).trim()) throw new BetterAuthError(`Invalid version ${s.version} in \`secrets\`. Version must be a non-negative integer.`); - if (!s.value) throw new BetterAuthError(`Empty secret value for version ${version3} in \`secrets\`.`); - if (seen.has(version3)) throw new BetterAuthError(`Duplicate version ${version3} in \`secrets\`. Each version must be unique.`); - seen.add(version3); - } - const current = secrets[0]; - if (current.value.length < 32) logger2.warn(`[better-auth] Warning: the current secret (version ${current.version}) should be at least 32 characters long for adequate security.`); - if (estimateEntropy(current.value) < 120) logger2.warn("[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production."); -} -function buildSecretConfig(secrets, legacySecret) { - const keys = /* @__PURE__ */ new Map(); - for (const s of secrets) keys.set(parseInt(String(s.version), 10), s.value); - return { - keys, - currentVersion: parseInt(String(secrets[0].version), 10), - legacySecret: legacySecret && legacySecret !== "better-auth-secret-12345678901234567890" ? legacySecret : void 0 - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/create-context.mjs -init_env(); -init_error2(); -init_id2(); - -// ../../node_modules/.pnpm/@better-auth+telemetry@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-f_04cb191a006c1c341def4e42b17bd9b5/node_modules/@better-auth/telemetry/dist/node.mjs -init_env(); -import fs2 from "node:fs"; -import fsPromises from "node:fs/promises"; -import os from "node:os"; -import path2 from "node:path"; -init_random(); -async function getTelemetryAuthConfig(options, context) { - return { - database: context?.database, - adapter: context?.adapter, - emailVerification: { - sendVerificationEmail: !!options.emailVerification?.sendVerificationEmail, - sendOnSignUp: !!options.emailVerification?.sendOnSignUp, - sendOnSignIn: !!options.emailVerification?.sendOnSignIn, - autoSignInAfterVerification: !!options.emailVerification?.autoSignInAfterVerification, - expiresIn: options.emailVerification?.expiresIn, - beforeEmailVerification: !!options.emailVerification?.beforeEmailVerification, - afterEmailVerification: !!options.emailVerification?.afterEmailVerification - }, - emailAndPassword: { - enabled: !!options.emailAndPassword?.enabled, - disableSignUp: !!options.emailAndPassword?.disableSignUp, - requireEmailVerification: !!options.emailAndPassword?.requireEmailVerification, - maxPasswordLength: options.emailAndPassword?.maxPasswordLength, - minPasswordLength: options.emailAndPassword?.minPasswordLength, - sendResetPassword: !!options.emailAndPassword?.sendResetPassword, - resetPasswordTokenExpiresIn: options.emailAndPassword?.resetPasswordTokenExpiresIn, - onPasswordReset: !!options.emailAndPassword?.onPasswordReset, - password: { - hash: !!options.emailAndPassword?.password?.hash, - verify: !!options.emailAndPassword?.password?.verify - }, - autoSignIn: !!options.emailAndPassword?.autoSignIn, - revokeSessionsOnPasswordReset: !!options.emailAndPassword?.revokeSessionsOnPasswordReset - }, - socialProviders: await Promise.all(Object.keys(options.socialProviders || {}).map(async (key) => { - const p = options.socialProviders?.[key]; - if (!p) return {}; - const provider = typeof p === "function" ? await p() : p; - return { - id: key, - mapProfileToUser: !!provider.mapProfileToUser, - disableDefaultScope: !!provider.disableDefaultScope, - disableIdTokenSignIn: !!provider.disableIdTokenSignIn, - disableImplicitSignUp: provider.disableImplicitSignUp, - disableSignUp: provider.disableSignUp, - getUserInfo: !!provider.getUserInfo, - overrideUserInfoOnSignIn: !!provider.overrideUserInfoOnSignIn, - prompt: provider.prompt, - verifyIdToken: !!provider.verifyIdToken, - scope: provider.scope, - refreshAccessToken: !!provider.refreshAccessToken - }; - })), - plugins: options.plugins?.map((p) => p.id.toString()), - user: { - modelName: options.user?.modelName, - fields: options.user?.fields, - additionalFields: options.user?.additionalFields, - changeEmail: { - enabled: options.user?.changeEmail?.enabled, - sendChangeEmailConfirmation: !!options.user?.changeEmail?.sendChangeEmailConfirmation - } - }, - verification: { - modelName: options.verification?.modelName, - disableCleanup: options.verification?.disableCleanup, - fields: options.verification?.fields - }, - session: { - modelName: options.session?.modelName, - additionalFields: options.session?.additionalFields, - cookieCache: { - enabled: options.session?.cookieCache?.enabled, - maxAge: options.session?.cookieCache?.maxAge, - strategy: options.session?.cookieCache?.strategy - }, - disableSessionRefresh: options.session?.disableSessionRefresh, - expiresIn: options.session?.expiresIn, - fields: options.session?.fields, - freshAge: options.session?.freshAge, - preserveSessionInDatabase: options.session?.preserveSessionInDatabase, - storeSessionInDatabase: options.session?.storeSessionInDatabase, - updateAge: options.session?.updateAge - }, - account: { - modelName: options.account?.modelName, - fields: options.account?.fields, - encryptOAuthTokens: options.account?.encryptOAuthTokens, - updateAccountOnSignIn: options.account?.updateAccountOnSignIn, - accountLinking: { - enabled: options.account?.accountLinking?.enabled, - trustedProviders: options.account?.accountLinking?.trustedProviders, - updateUserInfoOnLink: options.account?.accountLinking?.updateUserInfoOnLink, - allowUnlinkingAll: options.account?.accountLinking?.allowUnlinkingAll - } - }, - hooks: { - after: !!options.hooks?.after, - before: !!options.hooks?.before - }, - secondaryStorage: !!options.secondaryStorage, - advanced: { - cookiePrefix: !!options.advanced?.cookiePrefix, - cookies: !!options.advanced?.cookies, - crossSubDomainCookies: { - domain: !!options.advanced?.crossSubDomainCookies?.domain, - enabled: options.advanced?.crossSubDomainCookies?.enabled, - additionalCookies: options.advanced?.crossSubDomainCookies?.additionalCookies - }, - database: { - generateId: options.advanced?.database?.generateId, - defaultFindManyLimit: options.advanced?.database?.defaultFindManyLimit - }, - useSecureCookies: options.advanced?.useSecureCookies, - ipAddress: { - disableIpTracking: options.advanced?.ipAddress?.disableIpTracking, - ipAddressHeaders: options.advanced?.ipAddress?.ipAddressHeaders - }, - disableCSRFCheck: options.advanced?.disableCSRFCheck, - cookieAttributes: { - expires: options.advanced?.defaultCookieAttributes?.expires, - secure: options.advanced?.defaultCookieAttributes?.secure, - sameSite: options.advanced?.defaultCookieAttributes?.sameSite, - domain: !!options.advanced?.defaultCookieAttributes?.domain, - path: options.advanced?.defaultCookieAttributes?.path, - httpOnly: options.advanced?.defaultCookieAttributes?.httpOnly - } - }, - trustedOrigins: options.trustedOrigins?.length, - rateLimit: { - storage: options.rateLimit?.storage, - modelName: options.rateLimit?.modelName, - window: options.rateLimit?.window, - customStorage: !!options.rateLimit?.customStorage, - enabled: options.rateLimit?.enabled, - max: options.rateLimit?.max - }, - onAPIError: { - errorURL: options.onAPIError?.errorURL, - onError: !!options.onAPIError?.onError, - throw: options.onAPIError?.throw - }, - logger: { - disabled: options.logger?.disabled, - level: options.logger?.level, - log: !!options.logger?.log - }, - databaseHooks: { - user: { - create: { - after: !!options.databaseHooks?.user?.create?.after, - before: !!options.databaseHooks?.user?.create?.before - }, - update: { - after: !!options.databaseHooks?.user?.update?.after, - before: !!options.databaseHooks?.user?.update?.before - } - }, - session: { - create: { - after: !!options.databaseHooks?.session?.create?.after, - before: !!options.databaseHooks?.session?.create?.before - }, - update: { - after: !!options.databaseHooks?.session?.update?.after, - before: !!options.databaseHooks?.session?.update?.before - } - }, - account: { - create: { - after: !!options.databaseHooks?.account?.create?.after, - before: !!options.databaseHooks?.account?.create?.before - }, - update: { - after: !!options.databaseHooks?.account?.update?.after, - before: !!options.databaseHooks?.account?.update?.before - } - }, - verification: { - create: { - after: !!options.databaseHooks?.verification?.create?.after, - before: !!options.databaseHooks?.verification?.create?.before - }, - update: { - after: !!options.databaseHooks?.verification?.update?.after, - before: !!options.databaseHooks?.verification?.update?.before - } - } - } - }; -} -function detectPackageManager() { - const userAgent = env.npm_config_user_agent; - if (!userAgent) return; - const pmSpec = userAgent.split(" ")[0]; - const separatorPos = pmSpec.lastIndexOf("/"); - const name = pmSpec.substring(0, separatorPos); - return { - name: name === "npminstall" ? "cnpm" : name, - version: pmSpec.substring(separatorPos + 1) - }; -} -function isCI() { - return env.CI !== "false" && ("BUILD_ID" in env || "BUILD_NUMBER" in env || "CI" in env || "CI_APP_ID" in env || "CI_BUILD_ID" in env || "CI_BUILD_NUMBER" in env || "CI_NAME" in env || "CONTINUOUS_INTEGRATION" in env || "RUN_ID" in env); -} -function detectRuntime() { - if (typeof Deno !== "undefined") return { - name: "deno", - version: Deno?.version?.deno ?? null - }; - if (typeof Bun !== "undefined") return { - name: "bun", - version: Bun?.version ?? null - }; - if (typeof process !== "undefined" && process?.versions?.node) return { - name: "node", - version: process.versions.node ?? null - }; - return { - name: "edge", - version: null - }; -} -function detectEnvironment() { - return getEnvVar("NODE_ENV") === "production" ? "production" : isCI() ? "ci" : isTest() ? "test" : "development"; -} -async function hashToBase64(data) { - const buffer = await createHash("SHA-256").digest(data); - return base643.encode(buffer); -} -var generateId2 = (size) => { - return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32); -}; -var packageJSONCache; -async function readRootPackageJson() { - if (packageJSONCache) return packageJSONCache; - try { - const cwd = process.cwd(); - if (!cwd) return void 0; - const raw2 = await fsPromises.readFile(path2.join(cwd, "package.json"), "utf-8"); - packageJSONCache = JSON.parse(raw2); - return packageJSONCache; - } catch { - } -} -async function getPackageVersion(pkg) { - if (packageJSONCache) return packageJSONCache.dependencies?.[pkg] || packageJSONCache.devDependencies?.[pkg] || packageJSONCache.peerDependencies?.[pkg]; - try { - const cwd = process.cwd(); - if (!cwd) throw new Error("no-cwd"); - const pkgJsonPath = path2.join(cwd, "node_modules", pkg, "package.json"); - const raw2 = await fsPromises.readFile(pkgJsonPath, "utf-8"); - return JSON.parse(raw2).version || await getVersionFromLocalPackageJson(pkg) || void 0; - } catch { - } - return getVersionFromLocalPackageJson(pkg); -} -async function getVersionFromLocalPackageJson(pkg) { - const json2 = await readRootPackageJson(); - if (!json2) return void 0; - return { - ...json2.dependencies, - ...json2.devDependencies, - ...json2.peerDependencies - }[pkg]; -} -async function getNameFromLocalPackageJson() { - return (await readRootPackageJson())?.name; -} -async function detectSystemInfo() { - try { - const cpus = os.cpus(); - return { - deploymentVendor: getVendor(), - systemPlatform: os.platform(), - systemRelease: os.release(), - systemArchitecture: os.arch(), - cpuCount: cpus.length, - cpuModel: cpus.length ? cpus[0].model : null, - cpuSpeed: cpus.length ? cpus[0].speed : null, - memory: os.totalmem(), - isWSL: await isWsl(), - isDocker: await isDocker(), - isTTY: process.stdout ? process.stdout.isTTY : null - }; - } catch { - return { - systemPlatform: null, - systemRelease: null, - systemArchitecture: null, - cpuCount: null, - cpuModel: null, - cpuSpeed: null, - memory: null, - isWSL: null, - isDocker: null, - isTTY: null - }; - } -} -function getVendor() { - const env2 = process.env; - const hasAny = (...keys) => keys.some((k) => Boolean(env2[k])); - if (hasAny("CF_PAGES", "CF_PAGES_URL", "CF_ACCOUNT_ID") || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") return "cloudflare"; - if (hasAny("VERCEL", "VERCEL_URL", "VERCEL_ENV")) return "vercel"; - if (hasAny("NETLIFY", "NETLIFY_URL")) return "netlify"; - if (hasAny("RENDER", "RENDER_URL", "RENDER_INTERNAL_HOSTNAME", "RENDER_SERVICE_ID")) return "render"; - if (hasAny("AWS_LAMBDA_FUNCTION_NAME", "AWS_EXECUTION_ENV", "LAMBDA_TASK_ROOT")) return "aws"; - if (hasAny("GOOGLE_CLOUD_FUNCTION_NAME", "GOOGLE_CLOUD_PROJECT", "GCP_PROJECT", "K_SERVICE")) return "gcp"; - if (hasAny("AZURE_FUNCTION_NAME", "FUNCTIONS_WORKER_RUNTIME", "WEBSITE_INSTANCE_ID", "WEBSITE_SITE_NAME")) return "azure"; - if (hasAny("DENO_DEPLOYMENT_ID", "DENO_REGION")) return "deno-deploy"; - if (hasAny("FLY_APP_NAME", "FLY_REGION", "FLY_ALLOC_ID")) return "fly-io"; - if (hasAny("RAILWAY_STATIC_URL", "RAILWAY_ENVIRONMENT_NAME")) return "railway"; - if (hasAny("DYNO", "HEROKU_APP_NAME")) return "heroku"; - if (hasAny("DO_DEPLOYMENT_ID", "DO_APP_NAME", "DIGITALOCEAN")) return "digitalocean"; - if (hasAny("KOYEB", "KOYEB_DEPLOYMENT_ID", "KOYEB_APP_NAME")) return "koyeb"; - return null; -} -var isDockerCached; -async function hasDockerEnv() { - try { - fs2.statSync("/.dockerenv"); - return true; - } catch { - return false; - } -} -async function hasDockerCGroup() { - try { - return fs2.readFileSync("/proc/self/cgroup", "utf8").includes("docker"); - } catch { - return false; - } -} -async function isDocker() { - if (isDockerCached === void 0) isDockerCached = await hasDockerEnv() || await hasDockerCGroup(); - return isDockerCached; -} -var isInsideContainerCached; -var hasContainerEnv = async () => { - try { - fs2.statSync("/run/.containerenv"); - return true; - } catch { - return false; - } -}; -async function isInsideContainer() { - if (isInsideContainerCached === void 0) isInsideContainerCached = await hasContainerEnv() || await isDocker(); - return isInsideContainerCached; -} -async function isWsl() { - try { - if (process.platform !== "linux") return false; - if (os.release().toLowerCase().includes("microsoft")) { - if (await isInsideContainer()) return false; - return true; - } - return fs2.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !await isInsideContainer() : false; - } catch { - return false; - } -} -var projectIdCached = null; -async function getProjectId(baseUrl) { - if (projectIdCached) return projectIdCached; - const projectName = await getNameFromLocalPackageJson(); - if (projectName) { - projectIdCached = await hashToBase64(baseUrl ? baseUrl + projectName : projectName); - return projectIdCached; - } - if (baseUrl) { - projectIdCached = await hashToBase64(baseUrl); - return projectIdCached; - } - projectIdCached = generateId2(32); - return projectIdCached; -} -async function detectDatabaseNode() { - for (const [pkg, name] of Object.entries({ - pg: "postgresql", - mysql: "mysql", - mariadb: "mariadb", - sqlite3: "sqlite", - "better-sqlite3": "sqlite", - "@prisma/client": "prisma", - mongoose: "mongodb", - mongodb: "mongodb", - "drizzle-orm": "drizzle" - })) { - const version3 = await getPackageVersion(pkg); - if (version3) return { - name, - version: version3 - }; - } -} -async function detectFrameworkNode() { - for (const [pkg, name] of Object.entries({ - next: "next", - nuxt: "nuxt", - "react-router": "react-router", - astro: "astro", - "@sveltejs/kit": "sveltekit", - "solid-start": "solid-start", - "tanstack-start": "tanstack-start", - hono: "hono", - express: "express", - elysia: "elysia", - expo: "expo" - })) { - const version3 = await getPackageVersion(pkg); - if (version3) return { - name, - version: version3 - }; - } -} -var noop2 = async function noop3() { -}; -async function createTelemetry(options, context) { - const debugEnabled = options.telemetry?.debug || getBooleanEnvVar("BETTER_AUTH_TELEMETRY_DEBUG", false); - const telemetryEndpoint = ENV.BETTER_AUTH_TELEMETRY_ENDPOINT; - if (!telemetryEndpoint && !context?.customTrack) return { publish: noop2 }; - const track = async (event) => { - if (context?.customTrack) await context.customTrack(event).catch(logger.error); - else if (telemetryEndpoint) if (debugEnabled) logger.info("telemetry event", JSON.stringify(event, null, 2)); - else await betterFetch(telemetryEndpoint, { - method: "POST", - body: event - }).catch(logger.error); - }; - const isEnabled = async () => { - const telemetryEnabled = options.telemetry?.enabled !== void 0 ? options.telemetry.enabled : false; - return (getBooleanEnvVar("BETTER_AUTH_TELEMETRY", false) || telemetryEnabled) && (context?.skipTestCheck || !isTest()); - }; - const enabled = await isEnabled(); - let anonymousId; - if (enabled) { - anonymousId = await getProjectId(typeof options.baseURL === "string" ? options.baseURL : void 0); - track({ - type: "init", - payload: { - config: await getTelemetryAuthConfig(options, context), - runtime: detectRuntime(), - database: await detectDatabaseNode(), - framework: await detectFrameworkNode(), - environment: detectEnvironment(), - systemInfo: await detectSystemInfo(), - packageManager: detectPackageManager() - }, - anonymousId - }); - } - return { publish: async (event) => { - if (!enabled) return; - if (!anonymousId) anonymousId = await getProjectId(typeof options.baseURL === "string" ? options.baseURL : void 0); - await track({ - type: event.type, - payload: event.payload, - anonymousId - }); - } }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/create-context.mjs -function estimateEntropy2(str) { - const unique2 = new Set(str).size; - if (unique2 === 0) return 0; - return Math.log2(Math.pow(unique2, str.length)); -} -function validateSecret(secret, logger2) { - const isDefaultSecret = secret === DEFAULT_SECRET; - if (isTest()) return; - if (isDefaultSecret && isProduction) throw new BetterAuthError("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config."); - if (!secret) throw new BetterAuthError("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret })."); - if (secret.length < 32) logger2.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with \`npx auth secret\` or \`openssl rand -base64 32\`.`); - if (estimateEntropy2(secret) < 120) logger2.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production."); -} -async function createAuthContext(adapter, options, getDatabaseType) { - if (!options.database) options = defu(options, { - session: { cookieCache: { - enabled: true, - strategy: "jwe", - refreshCache: true, - maxAge: options.session?.expiresIn || 3600 * 24 * 7 - } }, - account: { - storeStateStrategy: "cookie", - storeAccountCookie: true - } - }); - const plugins = options.plugins || []; - const internalPlugins = getInternalPlugins(options); - const logger2 = createLogger2(options.logger); - const isDynamicConfig = isDynamicBaseURLConfig(options.baseURL); - if (isDynamicBaseURLConfig(options.baseURL)) { - const { allowedHosts } = options.baseURL; - if (!allowedHosts || allowedHosts.length === 0) throw new BetterAuthError('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).'); - } - const baseURL = isDynamicConfig ? void 0 : getBaseURL(typeof options.baseURL === "string" ? options.baseURL : void 0, options.basePath); - if (!baseURL && !isDynamicConfig) logger2.warn(`[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_URL environment variable. Without this, callbacks and redirects may not work correctly.`); - if (adapter.id === "memory" && options.advanced?.database?.generateId === false) logger2.error(`[better-auth] Misconfiguration detected. -You are using the memory DB with generateId: false. -This will cause no id to be generated for any model. -Most of the features of Better Auth will not work correctly.`); - const secretsArray = options.secrets ?? parseSecretsEnv(env.BETTER_AUTH_SECRETS); - const legacySecret = options.secret || env.BETTER_AUTH_SECRET || env.AUTH_SECRET || ""; - let secret; - let secretConfig; - if (secretsArray) { - validateSecretsArray(secretsArray, logger2); - secret = secretsArray[0].value; - secretConfig = buildSecretConfig(secretsArray, legacySecret); - } else { - secret = legacySecret || "better-auth-secret-12345678901234567890"; - validateSecret(secret, logger2); - secretConfig = secret; - } - options = { - ...options, - secret, - baseURL: isDynamicConfig ? options.baseURL : baseURL ? new URL(baseURL).origin : "", - basePath: options.basePath || "/api/auth", - plugins: plugins.concat(internalPlugins) - }; - checkEndpointConflicts(options, logger2); - const cookies = getCookies(options); - const tables = getAuthTables(options); - const providers = (await Promise.all(Object.entries(options.socialProviders || {}).map(async ([key, originalConfig]) => { - const config4 = typeof originalConfig === "function" ? await originalConfig() : originalConfig; - if (config4 == null) return null; - if (config4.enabled === false) return null; - if (!config4.clientId) logger2.warn(`Social provider ${key} is missing clientId or clientSecret`); - const provider = socialProviders[key](config4); - provider.disableImplicitSignUp = config4.disableImplicitSignUp; - return provider; - }))).filter((x) => x !== null); - const generateIdFunc = ({ model, size }) => { - if (typeof options.advanced?.generateId === "function") return options.advanced.generateId({ - model, - size - }); - const dbGenerateId = options?.advanced?.database?.generateId; - if (typeof dbGenerateId === "function") return dbGenerateId({ - model, - size - }); - if (dbGenerateId === "uuid") return crypto.randomUUID(); - if (dbGenerateId === "serial" || dbGenerateId === false) return false; - return generateId(size); - }; - const { publish } = await createTelemetry(options, { - adapter: adapter.id, - database: typeof options.database === "function" ? "adapter" : getDatabaseType(options.database) - }); - const pluginIds = new Set(options.plugins.map((p) => p.id)); - const getPluginFn = (id) => options.plugins.find((p) => p.id === id) ?? null; - const hasPluginFn = (id) => pluginIds.has(id); - const trustedOrigins = await getTrustedOrigins(options); - const trustedProviders = await getTrustedProviders(options); - const ctx = { - appName: options.appName || "Better Auth", - baseURL: baseURL || "", - version: getBetterAuthVersion(), - socialProviders: providers, - options, - oauthConfig: { - storeStateStrategy: options.account?.storeStateStrategy || (options.database ? "database" : "cookie"), - skipStateCookieCheck: !!options.account?.skipStateCookieCheck - }, - tables, - trustedOrigins, - trustedProviders, - isTrustedOrigin(url2, settings) { - return this.trustedOrigins.some((origin) => matchesOriginPattern(url2, origin, settings)); - }, - sessionConfig: { - updateAge: options.session?.updateAge !== void 0 ? options.session.updateAge : 1440 * 60, - expiresIn: options.session?.expiresIn || 3600 * 24 * 7, - freshAge: options.session?.freshAge === void 0 ? 3600 * 24 : options.session.freshAge, - cookieRefreshCache: (() => { - const refreshCache = options.session?.cookieCache?.refreshCache; - const maxAge = options.session?.cookieCache?.maxAge || 300; - if ((!!options.database || !!options.secondaryStorage) && refreshCache) { - logger2.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` \u2014 remove it from your config to silence this warning."); - return false; - } - if (refreshCache === false || refreshCache === void 0) return false; - if (refreshCache === true) return { - enabled: true, - updateAge: Math.floor(maxAge * 0.2) - }; - return { - enabled: true, - updateAge: refreshCache.updateAge !== void 0 ? refreshCache.updateAge : Math.floor(maxAge * 0.2) - }; - })() - }, - secret, - secretConfig, - rateLimit: { - ...options.rateLimit, - enabled: options.rateLimit?.enabled ?? isProduction, - window: options.rateLimit?.window || 10, - max: options.rateLimit?.max || 100, - storage: options.rateLimit?.storage || (options.secondaryStorage ? "secondary-storage" : "memory") - }, - authCookies: cookies, - logger: logger2, - generateId: generateIdFunc, - session: null, - secondaryStorage: options.secondaryStorage, - password: { - hash: options.emailAndPassword?.password?.hash || hashPassword$1, - verify: options.emailAndPassword?.password?.verify || verifyPassword$1, - config: { - minPasswordLength: options.emailAndPassword?.minPasswordLength || 8, - maxPasswordLength: options.emailAndPassword?.maxPasswordLength || 128 - }, - checkPassword - }, - setNewSession(session) { - this.newSession = session; - }, - newSession: null, - adapter, - internalAdapter: createInternalAdapter(adapter, { - options, - logger: logger2, - hooks: options.databaseHooks ? [{ - source: "user", - hooks: options.databaseHooks - }] : [], - generateId: generateIdFunc - }), - createAuthCookie: createCookieGetter(options), - async runMigrations() { - throw new BetterAuthError("runMigrations will be set by the specific init implementation"); - }, - publishTelemetry: publish, - skipCSRFCheck: !!options.advanced?.disableCSRFCheck, - skipOriginCheck: options.advanced?.disableOriginCheck !== void 0 ? options.advanced.disableOriginCheck : isTest() ? true : false, - runInBackground: options.advanced?.backgroundTasks?.handler ?? ((p) => { - p.catch(() => { - }); - }), - async runInBackgroundOrAwait(promise2) { - try { - if (options.advanced?.backgroundTasks?.handler) { - if (promise2 instanceof Promise) options.advanced.backgroundTasks.handler(promise2.catch((e) => { - logger2.error("Failed to run background task:", e); - })); - } else await promise2; - } catch (e) { - logger2.error("Failed to run background task:", e); - } - }, - getPlugin: getPluginFn, - hasPlugin: hasPluginFn - }; - const initOrPromise = runPluginInit(ctx); - if (isPromise(initOrPromise)) await initOrPromise; - return ctx; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/init.mjs -init_error2(); -init_dist2(); -var init = async (options) => { - const adapter = await getAdapter(options); - const getDatabaseType = (database) => getKyselyDatabaseType(database) || "unknown"; - const ctx = await createAuthContext(adapter, options, getDatabaseType); - ctx.runMigrations = async function() { - if (!options.database || "updateMany" in options.database) throw new BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance."); - const { runMigrations } = await getMigrations(options); - await runMigrations(); - }; - return ctx; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/base.mjs -init_error2(); -var createBetterAuth = (options, initFn) => { - const authContext = initFn(options); - const { api } = getEndpoints(authContext, options); - return { - handler: async (request) => { - const ctx = await authContext; - const basePath = ctx.options.basePath || "/api/auth"; - let handlerCtx; - if (isDynamicBaseURLConfig(options.baseURL)) { - handlerCtx = Object.create(Object.getPrototypeOf(ctx), Object.getOwnPropertyDescriptors(ctx)); - const baseURL = resolveBaseURL(options.baseURL, basePath, request); - if (baseURL) { - handlerCtx.baseURL = baseURL; - handlerCtx.options = { - ...ctx.options, - baseURL: getOrigin(baseURL) || void 0 - }; - } else throw new BetterAuthError("Could not resolve base URL from request. Check your allowedHosts config."); - const trustedOriginOptions = { - ...handlerCtx.options, - baseURL: options.baseURL - }; - handlerCtx.trustedOrigins = await getTrustedOrigins(trustedOriginOptions, request); - if (options.advanced?.crossSubDomainCookies?.enabled) { - handlerCtx.authCookies = getCookies(handlerCtx.options); - handlerCtx.createAuthCookie = createCookieGetter(handlerCtx.options); - } - } else { - handlerCtx = ctx; - if (!ctx.options.baseURL) { - const baseURL = getBaseURL(void 0, basePath, request, void 0, ctx.options.advanced?.trustedProxyHeaders); - if (baseURL) { - ctx.baseURL = baseURL; - ctx.options.baseURL = getOrigin(ctx.baseURL) || void 0; - } else throw new BetterAuthError("Could not get base URL from request. Please provide a valid base URL."); - } - handlerCtx.trustedOrigins = await getTrustedOrigins(ctx.options, request); - } - handlerCtx.trustedProviders = await getTrustedProviders(handlerCtx.options, request); - const { handler } = router(handlerCtx, options); - return runWithAdapter(handlerCtx.adapter, () => handler(request)); - }, - api, - options, - $context: authContext, - $ERROR_CODES: { - ...options.plugins?.reduce((acc, plugin) => { - if (plugin.$ERROR_CODES) return { - ...acc, - ...plugin.$ERROR_CODES - }; - return acc; - }, {}), - ...BASE_ERROR_CODES - } - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/full.mjs -var betterAuth = (options) => { - return createBetterAuth(options, init); -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/index.mjs -init_env(); -init_error2(); -init_error_codes(); -init_id2(); -init_json(); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/client/parser.mjs -var PROTO_POLLUTION_PATTERNS = { - proto: /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/, - constructor: /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/, - protoShort: /"__proto__"\s*:/, - constructorShort: /"constructor"\s*:/ -}; -var JSON_SIGNATURE = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; -var SPECIAL_VALUES = { - true: true, - false: false, - null: null, - undefined: void 0, - nan: NaN, - infinity: Number.POSITIVE_INFINITY, - "-infinity": Number.NEGATIVE_INFINITY -}; -var ISO_DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/; -function isValidDate(date5) { - return date5 instanceof Date && !isNaN(date5.getTime()); -} -function parseISODate(value) { - const match2 = ISO_DATE_REGEX.exec(value); - if (!match2) return null; - const [, year2, month, day2, hour2, minute2, second, ms, offsetSign, offsetHour, offsetMinute] = match2; - const date5 = new Date(Date.UTC(parseInt(year2, 10), parseInt(month, 10) - 1, parseInt(day2, 10), parseInt(hour2, 10), parseInt(minute2, 10), parseInt(second, 10), ms ? parseInt(ms.padEnd(3, "0"), 10) : 0)); - if (offsetSign) { - const offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === "+" ? -1 : 1); - date5.setUTCMinutes(date5.getUTCMinutes() + offset); - } - return isValidDate(date5) ? date5 : null; -} -function betterJSONParse(value, options = {}) { - const { strict = false, warnings = false, reviver, parseDates = true } = options; - if (typeof value !== "string") return value; - const trimmed = value.trim(); - if (trimmed.length > 0 && trimmed[0] === '"' && trimmed.endsWith('"') && !trimmed.slice(1, -1).includes('"')) return trimmed.slice(1, -1); - const lowerValue = trimmed.toLowerCase(); - if (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) return SPECIAL_VALUES[lowerValue]; - if (!JSON_SIGNATURE.test(trimmed)) { - if (strict) throw new SyntaxError("[better-json] Invalid JSON"); - return value; - } - if (Object.entries(PROTO_POLLUTION_PATTERNS).some(([key, pattern]) => { - const matches = pattern.test(trimmed); - if (matches && warnings) console.warn(`[better-json] Detected potential prototype pollution attempt using ${key} pattern`); - return matches; - }) && strict) throw new Error("[better-json] Potential prototype pollution attempt detected"); - try { - const secureReviver = (key, value2) => { - if (key === "__proto__" || key === "constructor" && value2 && typeof value2 === "object" && "prototype" in value2) { - if (warnings) console.warn(`[better-json] Dropping "${key}" key to prevent prototype pollution`); - return; - } - if (parseDates && typeof value2 === "string") { - const date5 = parseISODate(value2); - if (date5) return date5; - } - return reviver ? reviver(key, value2) : value2; - }; - return JSON.parse(trimmed, secureReviver); - } catch (error49) { - if (strict) throw error49; - return value; - } -} -function parseJSON(value, options = { strict: true }) { - return betterJSONParse(value, options); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/adapter.mjs -init_error2(); -var getOrgAdapter = (context, options) => { - const baseAdapter = context.adapter; - const orgAdditionalFields = options?.schema?.organization?.additionalFields; - const memberAdditionalFields = options?.schema?.member?.additionalFields; - const invitationAdditionalFields = options?.schema?.invitation?.additionalFields; - const teamAdditionalFields = options?.schema?.team?.additionalFields; - return { - findOrganizationBySlug: async (slug) => { - return filterOutputFields(await (await getCurrentAdapter(baseAdapter)).findOne({ - model: "organization", - where: [{ - field: "slug", - value: slug - }] - }), orgAdditionalFields); - }, - createOrganization: async (data) => { - const organization2 = await (await getCurrentAdapter(baseAdapter)).create({ - model: "organization", - data: { - ...data.organization, - metadata: data.organization.metadata ? JSON.stringify(data.organization.metadata) : void 0 - }, - forceAllowId: true - }); - return filterOutputFields({ - ...organization2, - metadata: organization2.metadata && typeof organization2.metadata === "string" ? JSON.parse(organization2.metadata) : void 0 - }, orgAdditionalFields); - }, - findMemberByEmail: async (data) => { - const adapter = await getCurrentAdapter(baseAdapter); - const user = await adapter.findOne({ - model: "user", - where: [{ - field: "email", - value: data.email.toLowerCase() - }] - }); - if (!user) return null; - const member = await adapter.findOne({ - model: "member", - where: [{ - field: "organizationId", - value: data.organizationId - }, { - field: "userId", - value: user.id - }] - }); - if (!member) return null; - return { - ...member, - user: { - id: user.id, - name: user.name, - email: user.email, - image: user.image - } - }; - }, - listMembers: async (data) => { - const adapter = await getCurrentAdapter(baseAdapter); - const members = await Promise.all([adapter.findMany({ - model: "member", - where: [{ - field: "organizationId", - value: data.organizationId - }, ...data.filter?.field ? [{ - field: data.filter?.field, - value: data.filter?.value, - ...data.filter.operator ? { operator: data.filter.operator } : {} - }] : []], - limit: data.limit || (typeof options?.membershipLimit === "number" ? options.membershipLimit : 100) || 100, - offset: data.offset || 0, - sortBy: data.sortBy ? { - field: data.sortBy, - direction: data.sortOrder || "asc" - } : void 0 - }), adapter.count({ - model: "member", - where: [{ - field: "organizationId", - value: data.organizationId - }, ...data.filter?.field ? [{ - field: data.filter?.field, - value: data.filter?.value, - ...data.filter.operator ? { operator: data.filter.operator } : {} - }] : []] - })]); - const users = await adapter.findMany({ - model: "user", - where: [{ - field: "id", - value: members[0].map((member) => member.userId), - operator: "in" - }] - }); - return { - members: members[0].map((member) => { - const user = users.find((user2) => user2.id === member.userId); - if (!user) throw new BetterAuthError("Unexpected error: User not found for member"); - return { - ...member, - user: { - id: user.id, - name: user.name, - email: user.email, - image: user.image - } - }; - }), - total: members[1] - }; - }, - findMemberByOrgId: async (data) => { - const result = await (await getCurrentAdapter(baseAdapter)).findOne({ - model: "member", - where: [{ - field: "userId", - value: data.userId - }, { - field: "organizationId", - value: data.organizationId - }], - join: { user: true } - }); - if (!result || !result.user) return null; - const { user, ...member } = result; - return { - ...member, - user: { - id: user.id, - name: user.name, - email: user.email, - image: user.image - } - }; - }, - findMemberById: async (memberId) => { - const result = await (await getCurrentAdapter(baseAdapter)).findOne({ - model: "member", - where: [{ - field: "id", - value: memberId - }], - join: { user: true } - }); - if (!result) return null; - const { user, ...member } = result; - return { - ...member, - user: { - id: user.id, - name: user.name, - email: user.email, - image: user.image - } - }; - }, - createMember: async (data) => { - return await (await getCurrentAdapter(baseAdapter)).create({ - model: "member", - data: { - ...data, - createdAt: /* @__PURE__ */ new Date() - } - }); - }, - updateMember: async (memberId, role2) => { - return await (await getCurrentAdapter(baseAdapter)).update({ - model: "member", - where: [{ - field: "id", - value: memberId - }], - update: { role: role2 } - }); - }, - deleteMember: async ({ memberId, organizationId, userId: _userId }) => { - const adapter = await getCurrentAdapter(baseAdapter); - let userId; - if (!_userId) { - const member2 = await adapter.findOne({ - model: "member", - where: [{ - field: "id", - value: memberId - }] - }); - if (!member2) throw new BetterAuthError("Member not found"); - userId = member2.userId; - } else userId = _userId; - const member = await adapter.delete({ - model: "member", - where: [{ - field: "id", - value: memberId - }] - }); - if (options?.teams?.enabled) { - const teams = await adapter.findMany({ - model: "team", - where: [{ - field: "organizationId", - value: organizationId - }] - }); - await Promise.all(teams.map((team) => adapter.deleteMany({ - model: "teamMember", - where: [{ - field: "teamId", - value: team.id - }, { - field: "userId", - value: userId - }] - }))); - } - return member; - }, - updateOrganization: async (organizationId, data) => { - const organization2 = await (await getCurrentAdapter(baseAdapter)).update({ - model: "organization", - where: [{ - field: "id", - value: organizationId - }], - update: { - ...data, - metadata: typeof data.metadata === "object" ? JSON.stringify(data.metadata) : data.metadata - } - }); - if (!organization2) return null; - return filterOutputFields({ - ...organization2, - metadata: organization2.metadata ? parseJSON(organization2.metadata) : void 0 - }, orgAdditionalFields); - }, - deleteOrganization: async (organizationId) => { - const adapter = await getCurrentAdapter(baseAdapter); - await adapter.deleteMany({ - model: "member", - where: [{ - field: "organizationId", - value: organizationId - }] - }); - await adapter.deleteMany({ - model: "invitation", - where: [{ - field: "organizationId", - value: organizationId - }] - }); - await adapter.delete({ - model: "organization", - where: [{ - field: "id", - value: organizationId - }] - }); - return organizationId; - }, - setActiveOrganization: async (sessionToken, organizationId, ctx) => { - return await context.internalAdapter.updateSession(sessionToken, { activeOrganizationId: organizationId }); - }, - findOrganizationById: async (organizationId) => { - return filterOutputFields(await (await getCurrentAdapter(baseAdapter)).findOne({ - model: "organization", - where: [{ - field: "id", - value: organizationId - }] - }), orgAdditionalFields); - }, - checkMembership: async ({ userId, organizationId }) => { - return await (await getCurrentAdapter(baseAdapter)).findOne({ - model: "member", - where: [{ - field: "userId", - value: userId - }, { - field: "organizationId", - value: organizationId - }] - }); - }, - findFullOrganization: async ({ organizationId, isSlug, includeTeams, membersLimit }) => { - const adapter = await getCurrentAdapter(baseAdapter); - const result = await adapter.findOne({ - model: "organization", - where: [{ - field: isSlug ? "slug" : "id", - value: organizationId - }], - join: { - invitation: true, - member: membersLimit ? { limit: membersLimit } : true, - ...includeTeams ? { team: true } : {} - } - }); - if (!result) return null; - const { invitation: invitations, member: members, team: teams, ...org } = result; - const userIds = members.map((member) => member.userId); - const users = userIds.length > 0 ? await adapter.findMany({ - model: "user", - where: [{ - field: "id", - value: userIds, - operator: "in" - }], - limit: (typeof options?.membershipLimit === "number" ? options.membershipLimit : 100) || 100 - }) : []; - const userMap = new Map(users.map((user) => [user.id, user])); - const membersWithUsers = members.map((member) => { - const user = userMap.get(member.userId); - if (!user) throw new BetterAuthError("Unexpected error: User not found for member"); - return { - ...filterOutputFields(member, memberAdditionalFields), - user: { - id: user.id, - name: user.name, - email: user.email, - image: user.image - } - }; - }); - const filteredOrg = filterOutputFields(org, orgAdditionalFields); - const filteredInvitations = invitations.map((inv) => filterOutputFields(inv, invitationAdditionalFields)); - const filteredTeams = teams?.map((team) => filterOutputFields(team, teamAdditionalFields)); - return { - ...filteredOrg, - invitations: filteredInvitations, - members: membersWithUsers, - teams: filteredTeams - }; - }, - listOrganizations: async (userId) => { - const result = await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "member", - where: [{ - field: "userId", - value: userId - }], - join: { organization: true } - }); - if (!result || result.length === 0) return []; - return result.map((member) => filterOutputFields(member.organization, orgAdditionalFields)); - }, - createTeam: async (data) => { - return await (await getCurrentAdapter(baseAdapter)).create({ - model: "team", - data - }); - }, - findTeamById: async ({ teamId, organizationId, includeTeamMembers }) => { - const result = await (await getCurrentAdapter(baseAdapter)).findOne({ - model: "team", - where: [{ - field: "id", - value: teamId - }, ...organizationId ? [{ - field: "organizationId", - value: organizationId - }] : []], - join: { ...includeTeamMembers ? { teamMember: true } : {} } - }); - if (!result) return null; - const { teamMember, ...team } = result; - return { - ...team, - ...includeTeamMembers ? { members: teamMember } : {} - }; - }, - updateTeam: async (teamId, data) => { - const adapter = await getCurrentAdapter(baseAdapter); - if ("id" in data) data.id = void 0; - return await adapter.update({ - model: "team", - where: [{ - field: "id", - value: teamId - }], - update: { ...data } - }); - }, - deleteTeam: async (teamId) => { - const adapter = await getCurrentAdapter(baseAdapter); - await adapter.deleteMany({ - model: "teamMember", - where: [{ - field: "teamId", - value: teamId - }] - }); - return await adapter.delete({ - model: "team", - where: [{ - field: "id", - value: teamId - }] - }); - }, - listTeams: async (organizationId) => { - return await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "team", - where: [{ - field: "organizationId", - value: organizationId - }] - }); - }, - createTeamInvitation: async ({ email: email3, role: role2, teamId, organizationId, inviterId, expiresIn = 1e3 * 60 * 60 * 48 }) => { - const adapter = await getCurrentAdapter(baseAdapter); - const expiresAt = getDate(expiresIn); - return await adapter.create({ - model: "invitation", - data: { - email: email3, - role: role2, - organizationId, - teamId, - inviterId, - status: "pending", - expiresAt - } - }); - }, - setActiveTeam: async (sessionToken, teamId, ctx) => { - return await context.internalAdapter.updateSession(sessionToken, { activeTeamId: teamId }); - }, - listTeamMembers: async (data) => { - return await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "teamMember", - where: [{ - field: "teamId", - value: data.teamId - }] - }); - }, - countTeamMembers: async (data) => { - return await (await getCurrentAdapter(baseAdapter)).count({ - model: "teamMember", - where: [{ - field: "teamId", - value: data.teamId - }] - }); - }, - countMembers: async (data) => { - return await (await getCurrentAdapter(baseAdapter)).count({ - model: "member", - where: [{ - field: "organizationId", - value: data.organizationId - }] - }); - }, - listTeamsByUser: async (data) => { - return (await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "teamMember", - where: [{ - field: "userId", - value: data.userId - }], - join: { team: true } - })).map((result) => result.team); - }, - findTeamMember: async (data) => { - return await (await getCurrentAdapter(baseAdapter)).findOne({ - model: "teamMember", - where: [{ - field: "teamId", - value: data.teamId - }, { - field: "userId", - value: data.userId - }] - }); - }, - findOrCreateTeamMember: async (data) => { - const adapter = await getCurrentAdapter(baseAdapter); - const member = await adapter.findOne({ - model: "teamMember", - where: [{ - field: "teamId", - value: data.teamId - }, { - field: "userId", - value: data.userId - }] - }); - if (member) return member; - return await adapter.create({ - model: "teamMember", - data: { - teamId: data.teamId, - userId: data.userId, - createdAt: /* @__PURE__ */ new Date() - } - }); - }, - removeTeamMember: async (data) => { - await (await getCurrentAdapter(baseAdapter)).deleteMany({ - model: "teamMember", - where: [{ - field: "teamId", - value: data.teamId - }, { - field: "userId", - value: data.userId - }] - }); - }, - findInvitationsByTeamId: async (teamId) => { - return await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "invitation", - where: [{ - field: "teamId", - value: teamId - }] - }); - }, - listUserInvitations: async (email3) => { - return (await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "invitation", - where: [{ - field: "email", - value: email3.toLowerCase() - }], - join: { organization: true } - })).filter(Boolean).map(({ organization: organization2, ...inv }) => ({ - ...inv, - organizationName: organization2?.name - })); - }, - createInvitation: async ({ invitation, user }) => { - const adapter = await getCurrentAdapter(baseAdapter); - const expiresAt = getDate(options?.invitationExpiresIn || 3600 * 48, "sec"); - return await adapter.create({ - model: "invitation", - data: { - status: "pending", - expiresAt, - createdAt: /* @__PURE__ */ new Date(), - inviterId: user.id, - ...invitation, - teamId: invitation.teamIds.length > 0 ? invitation.teamIds.join(",") : null - } - }); - }, - findInvitationById: async (id) => { - return await (await getCurrentAdapter(baseAdapter)).findOne({ - model: "invitation", - where: [{ - field: "id", - value: id - }] - }); - }, - findPendingInvitation: async (data) => { - return (await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "invitation", - where: [ - { - field: "email", - value: data.email.toLowerCase() - }, - { - field: "organizationId", - value: data.organizationId - }, - { - field: "status", - value: "pending" - } - ] - })).filter((invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date()); - }, - findPendingInvitations: async (data) => { - return (await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "invitation", - where: [{ - field: "organizationId", - value: data.organizationId - }, { - field: "status", - value: "pending" - }] - })).filter((invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date()); - }, - listInvitations: async (data) => { - return await (await getCurrentAdapter(baseAdapter)).findMany({ - model: "invitation", - where: [{ - field: "organizationId", - value: data.organizationId - }] - }); - }, - updateInvitation: async (data) => { - return await (await getCurrentAdapter(baseAdapter)).update({ - model: "invitation", - where: [{ - field: "id", - value: data.invitationId - }], - update: { status: data.status } - }); - } - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/access/access.mjs -init_error2(); -function role(statements) { - return { - authorize(request, connector = "AND") { - let success2 = false; - for (const [requestedResource, requestedActions] of Object.entries(request)) { - const allowedActions = statements[requestedResource]; - if (!allowedActions) return { - success: false, - error: `You are not allowed to access resource: ${requestedResource}` - }; - if (Array.isArray(requestedActions)) success2 = requestedActions.every((requestedAction) => allowedActions.includes(requestedAction)); - else if (typeof requestedActions === "object") { - const actions = requestedActions; - if (actions.connector === "OR") success2 = actions.actions.some((requestedAction) => allowedActions.includes(requestedAction)); - else success2 = actions.actions.every((requestedAction) => allowedActions.includes(requestedAction)); - } else throw new BetterAuthError("Invalid access control request"); - if (success2 && connector === "OR") return { success: success2 }; - if (!success2 && connector === "AND") return { - success: false, - error: `unauthorized to access resource "${requestedResource}"` - }; - } - if (success2) return { success: success2 }; - return { - success: false, - error: "Not authorized" - }; - }, - statements - }; -} -function createAccessControl(s) { - return { - newRole(statements) { - return role(statements); - }, - statements: s - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/access/statement.mjs -var defaultStatements = { - organization: ["update", "delete"], - member: [ - "create", - "update", - "delete" - ], - invitation: ["create", "cancel"], - team: [ - "create", - "update", - "delete" - ], - ac: [ - "create", - "read", - "update", - "delete" - ] -}; -var defaultAc = createAccessControl(defaultStatements); -var adminAc = defaultAc.newRole({ - organization: ["update"], - invitation: ["create", "cancel"], - member: [ - "create", - "update", - "delete" - ], - team: [ - "create", - "update", - "delete" - ], - ac: [ - "create", - "read", - "update", - "delete" - ] -}); -var ownerAc = defaultAc.newRole({ - organization: ["update", "delete"], - member: [ - "create", - "update", - "delete" - ], - invitation: ["create", "cancel"], - team: [ - "create", - "update", - "delete" - ], - ac: [ - "create", - "read", - "update", - "delete" - ] -}); -var memberAc = defaultAc.newRole({ - organization: [], - member: [], - invitation: [], - team: [], - ac: ["read"] -}); -var defaultRoles = { - admin: adminAc, - owner: ownerAc, - member: memberAc -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/permission.mjs -var hasPermissionFn = (input, acRoles) => { - if (!input.permissions) return false; - const roles = input.role.split(","); - const creatorRole = input.options.creatorRole || "owner"; - const isCreator = roles.includes(creatorRole); - const allowCreatorsAllPermissions = input.allowCreatorAllPermissions || false; - if (isCreator && allowCreatorsAllPermissions) return true; - for (const role2 of roles) if (acRoles[role2]?.authorize(input.permissions)?.success) return true; - return false; -}; -var cacheAllRoles = /* @__PURE__ */ new Map(); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/has-permission.mjs -init_zod(); -var hasPermission = async (input, ctx) => { - let acRoles = { ...input.options.roles || defaultRoles }; - if (ctx && input.organizationId && input.options.dynamicAccessControl?.enabled && input.options.ac && !input.useMemoryCache) { - const roles = await ctx.context.adapter.findMany({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: input.organizationId - }] - }); - for (const { role: role2, permission: permissionsString } of roles) { - const result = record(string2(), array(string2())).safeParse(JSON.parse(permissionsString)); - if (!result.success) { - ctx.context.logger.error("[hasPermission] Invalid permissions for role " + role2, { permissions: JSON.parse(permissionsString) }); - throw new APIError2("INTERNAL_SERVER_ERROR", { message: "Invalid permissions for role " + role2 }); - } - const merged = { ...acRoles[role2]?.statements }; - for (const [key, actions] of Object.entries(result.data)) merged[key] = [.../* @__PURE__ */ new Set([...merged[key] ?? [], ...actions])]; - acRoles[role2] = input.options.ac.newRole(merged); - } - } - if (input.useMemoryCache) acRoles = cacheAllRoles.get(input.organizationId) || acRoles; - cacheAllRoles.set(input.organizationId, acRoles); - return hasPermissionFn(input, acRoles); -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/package.mjs -var version2 = "1.6.2"; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/version.mjs -var PACKAGE_VERSION = version2; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/error-codes.mjs -init_error_codes(); -var ORGANIZATION_ERROR_CODES = defineErrorCodes({ - YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION: "You are not allowed to create a new organization", - YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS: "You have reached the maximum number of organizations", - ORGANIZATION_ALREADY_EXISTS: "Organization already exists", - ORGANIZATION_SLUG_ALREADY_TAKEN: "Organization slug already taken", - ORGANIZATION_NOT_FOUND: "Organization not found", - USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION: "User is not a member of the organization", - YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION: "You are not allowed to update this organization", - YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION: "You are not allowed to delete this organization", - NO_ACTIVE_ORGANIZATION: "No active organization", - USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION: "User is already a member of this organization", - MEMBER_NOT_FOUND: "Member not found", - ROLE_NOT_FOUND: "Role not found", - YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM: "You are not allowed to create a new team", - TEAM_ALREADY_EXISTS: "Team already exists", - TEAM_NOT_FOUND: "Team not found", - YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER: "You cannot leave the organization as the only owner", - YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER: "You cannot leave the organization without an owner", - YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER: "You are not allowed to delete this member", - YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION: "You are not allowed to invite users to this organization", - USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION: "User is already invited to this organization", - INVITATION_NOT_FOUND: "Invitation not found", - YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION: "You are not the recipient of the invitation", - EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION: "Email verification required before accepting or rejecting invitation", - YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION: "You are not allowed to cancel this invitation", - INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION: "Inviter is no longer a member of the organization", - YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE: "You are not allowed to invite a user with this role", - FAILED_TO_RETRIEVE_INVITATION: "Failed to retrieve invitation", - YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS: "You have reached the maximum number of teams", - UNABLE_TO_REMOVE_LAST_TEAM: "Unable to remove last team", - YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER: "You are not allowed to update this member", - ORGANIZATION_MEMBERSHIP_LIMIT_REACHED: "Organization membership limit reached", - YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION: "You are not allowed to create teams in this organization", - YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION: "You are not allowed to delete teams in this organization", - YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM: "You are not allowed to update this team", - YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM: "You are not allowed to delete this team", - INVITATION_LIMIT_REACHED: "Invitation limit reached", - TEAM_MEMBER_LIMIT_REACHED: "Team member limit reached", - USER_IS_NOT_A_MEMBER_OF_THE_TEAM: "User is not a member of the team", - YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM: "You are not allowed to list the members of this team", - YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM: "You do not have an active team", - YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER: "You are not allowed to create a new member", - YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER: "You are not allowed to remove a team member", - YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION: "You are not allowed to access this organization as an owner", - YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION: "You are not a member of this organization", - MISSING_AC_INSTANCE: "Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information", - YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE: "You must be in an organization to create a role", - YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE: "You are not allowed to create a role", - YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE: "You are not allowed to update a role", - YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE: "You are not allowed to delete a role", - YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE: "You are not allowed to read a role", - YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE: "You are not allowed to list a role", - YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE: "You are not allowed to get a role", - TOO_MANY_ROLES: "This organization has too many roles", - INVALID_RESOURCE: "The provided permission includes an invalid resource", - ROLE_NAME_IS_ALREADY_TAKEN: "That role name is already taken", - CANNOT_DELETE_A_PRE_DEFINED_ROLE: "Cannot delete a pre-defined role", - ROLE_IS_ASSIGNED_TO_MEMBERS: "Cannot delete a role that is assigned to members. Please reassign the members to a different role first" -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/shim.mjs -var shimContext = (originalObject, newContext) => { - const shimmedObj = {}; - for (const [key, value] of Object.entries(originalObject)) { - shimmedObj[key] = (ctx) => { - return value({ - ...ctx, - context: { - ...newContext, - ...ctx.context - } - }); - }; - shimmedObj[key].path = value.path; - shimmedObj[key].method = value.method; - shimmedObj[key].options = value.options; - shimmedObj[key].headers = value.headers; - } - return shimmedObj; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/call.mjs -var orgMiddleware = createAuthMiddleware(async () => { - return {}; -}); -var orgSessionMiddleware = createAuthMiddleware({ use: [sessionMiddleware] }, async (ctx) => { - return { session: ctx.context.session }; -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/to-zod.mjs -init_zod(); -function toZodSchema({ fields, isClientSide }) { - const zodFields = Object.keys(fields).reduce((acc, key) => { - const field = fields[key]; - if (!field) return acc; - if (isClientSide && field.input === false) return acc; - let schema3; - if (field.type === "json") schema3 = json ? json() : any(); - else if (field.type === "string[]" || field.type === "number[]") schema3 = array(field.type === "string[]" ? string2() : number2()); - else if (Array.isArray(field.type)) schema3 = any(); - else schema3 = zod_exports[field.type](); - if (field?.required === false) schema3 = schema3.optional(); - if (!isClientSide && field?.returned === false) return acc; - return { - ...acc, - [key]: schema3 - }; - }, {}); - return object(zodFields); -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-access-control.mjs -init_error2(); -init_zod(); -var normalizeRoleName = (role2) => role2.toLowerCase(); -var DEFAULT_MAXIMUM_ROLES_PER_ORGANIZATION = Number.POSITIVE_INFINITY; -var getAdditionalFields = (options, shouldBePartial = false) => { - const additionalFields = options?.schema?.organizationRole?.additionalFields || {}; - if (shouldBePartial) for (const key in additionalFields) additionalFields[key].required = false; - return { - additionalFieldsSchema: toZodSchema({ - fields: additionalFields, - isClientSide: true - }), - $AdditionalFields: {}, - $ReturnAdditionalFields: {} - }; -}; -var baseCreateOrgRoleSchema = object({ - organizationId: string2().optional().meta({ description: "The id of the organization to create the role in. If not provided, the user's active organization will be used." }), - role: string2().meta({ description: "The name of the role to create" }), - permission: record(string2(), array(string2())).meta({ description: "The permission to assign to the role" }) -}); -var createOrgRole = (options) => { - const { additionalFieldsSchema, $AdditionalFields, $ReturnAdditionalFields } = getAdditionalFields(options, false); - return createAuthEndpoint("/organization/create-role", { - method: "POST", - body: baseCreateOrgRoleSchema.safeExtend({ additionalFields: object({ ...additionalFieldsSchema.shape }).optional() }), - metadata: { $Infer: { body: {} } }, - requireHeaders: true, - use: [orgSessionMiddleware] - }, async (ctx) => { - const { session, user } = ctx.context.session; - let roleName = ctx.body.role; - const permission = ctx.body.permission; - const additionalFields = ctx.body.additionalFields; - const ac = options.ac; - if (!ac) { - ctx.context.logger.error(`[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.`, ` -Please refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`); - throw APIError2.from("NOT_IMPLEMENTED", ORGANIZATION_ERROR_CODES.MISSING_AC_INSTANCE); - } - const organizationId = ctx.body.organizationId ?? session.activeOrganizationId; - if (!organizationId) { - ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to create a role. Either set an active org id, or pass an organizationId in the request body.`); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE); - } - roleName = normalizeRoleName(roleName); - await checkIfRoleNameIsTakenByPreDefinedRole({ - role: roleName, - organizationId, - options, - ctx - }); - const member = await ctx.context.adapter.findOne({ - model: "member", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, { - field: "userId", - value: user.id, - operator: "eq", - connector: "AND" - }] - }); - if (!member) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to create a role.`, { - userId: user.id, - organizationId - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); - } - if (!await hasPermission({ - options, - organizationId, - permissions: { ac: ["create"] }, - role: member.role - }, ctx)) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to create a role. If this is unexpected, please make sure the role associated to that member has the "ac" resource with the "create" permission.`, { - userId: user.id, - organizationId, - role: member.role - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE); - } - const maximumRolesPerOrganization = typeof options.dynamicAccessControl?.maximumRolesPerOrganization === "function" ? await options.dynamicAccessControl.maximumRolesPerOrganization(organizationId) : options.dynamicAccessControl?.maximumRolesPerOrganization ?? DEFAULT_MAXIMUM_ROLES_PER_ORGANIZATION; - const rolesInDB = await ctx.context.adapter.count({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }] - }); - if (rolesInDB >= maximumRolesPerOrganization) { - ctx.context.logger.error(`[Dynamic Access Control] Failed to create a new role, the organization has too many roles. Maximum allowed roles is ${maximumRolesPerOrganization}.`, { - organizationId, - maximumRolesPerOrganization, - rolesInDB - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TOO_MANY_ROLES); - } - await checkForInvalidResources({ - ac, - ctx, - permission - }); - await checkIfMemberHasPermission({ - ctx, - member, - options, - organizationId, - permissionRequired: permission, - user, - action: "create" - }); - await checkIfRoleNameIsTakenByRoleInDB({ - ctx, - organizationId, - role: roleName - }); - const newRole = ac.newRole(permission); - const data = { - ...await ctx.context.adapter.create({ - model: "organizationRole", - data: { - createdAt: /* @__PURE__ */ new Date(), - organizationId, - permission: JSON.stringify(permission), - role: roleName, - ...additionalFields - } - }), - permission - }; - return ctx.json({ - success: true, - roleData: data, - statements: newRole.statements - }); - }); -}; -var deleteOrgRoleBodySchema = object({ organizationId: string2().optional().meta({ description: "The id of the organization to create the role in. If not provided, the user's active organization will be used." }) }).and(union([object({ roleName: string2().nonempty().meta({ description: "The name of the role to delete" }) }), object({ roleId: string2().nonempty().meta({ description: "The id of the role to delete" }) })])); -var deleteOrgRole = (options) => { - return createAuthEndpoint("/organization/delete-role", { - method: "POST", - body: deleteOrgRoleBodySchema, - requireHeaders: true, - use: [orgSessionMiddleware], - metadata: { $Infer: { body: {} } } - }, async (ctx) => { - const { session, user } = ctx.context.session; - const organizationId = ctx.body.organizationId ?? session.activeOrganizationId; - if (!organizationId) { - ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to delete a role. Either set an active org id, or pass an organizationId in the request body.`); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - } - const member = await ctx.context.adapter.findOne({ - model: "member", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, { - field: "userId", - value: user.id, - operator: "eq", - connector: "AND" - }] - }); - if (!member) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to delete a role.`, { - userId: user.id, - organizationId - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); - } - if (!await hasPermission({ - options, - organizationId, - permissions: { ac: ["delete"] }, - role: member.role - }, ctx)) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to delete a role. If this is unexpected, please make sure the role associated to that member has the "ac" resource with the "delete" permission.`, { - userId: user.id, - organizationId, - role: member.role - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE); - } - if (ctx.body.roleName) { - const roleName = ctx.body.roleName; - const defaultRoles3 = options.roles ? Object.keys(options.roles) : [ - "owner", - "admin", - "member" - ]; - if (defaultRoles3.includes(roleName)) { - ctx.context.logger.error(`[Dynamic Access Control] Cannot delete a pre-defined role.`, { - roleName, - organizationId, - defaultRoles: defaultRoles3 - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.CANNOT_DELETE_A_PRE_DEFINED_ROLE); - } - } - let condition; - if (ctx.body.roleName) condition = { - field: "role", - value: ctx.body.roleName, - operator: "eq", - connector: "AND" - }; - else if (ctx.body.roleId) condition = { - field: "id", - value: ctx.body.roleId, - operator: "eq", - connector: "AND" - }; - else { - ctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request body.`); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); - } - const existingRoleInDB = await ctx.context.adapter.findOne({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, condition] - }); - if (!existingRoleInDB) { - ctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, { - ..."roleName" in ctx.body ? { roleName: ctx.body.roleName } : { roleId: ctx.body.roleId }, - organizationId - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); - } - existingRoleInDB.permission = JSON.parse(existingRoleInDB.permission); - const roleToDelete = existingRoleInDB.role; - if ((await ctx.context.adapter.findMany({ - model: "member", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, { - field: "role", - value: roleToDelete, - operator: "contains" - }] - })).find((member2) => { - return member2.role.split(",").map((r) => r.trim()).includes(roleToDelete); - })) { - ctx.context.logger.error(`[Dynamic Access Control] Cannot delete a role that is assigned to members.`, { - role: existingRoleInDB.role, - organizationId - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_IS_ASSIGNED_TO_MEMBERS); - } - await ctx.context.adapter.delete({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, condition] - }); - return ctx.json({ success: true }); - }); -}; -var listOrgRolesQuerySchema = object({ organizationId: string2().optional().meta({ description: "The id of the organization to list roles for. If not provided, the user's active organization will be used." }) }).optional(); -var listOrgRoles = (options) => { - const { $ReturnAdditionalFields } = getAdditionalFields(options, false); - return createAuthEndpoint("/organization/list-roles", { - method: "GET", - requireHeaders: true, - use: [orgSessionMiddleware], - query: listOrgRolesQuerySchema - }, async (ctx) => { - const { session, user } = ctx.context.session; - const organizationId = ctx.query?.organizationId ?? session.activeOrganizationId; - if (!organizationId) { - ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to list roles. Either set an active org id, or pass an organizationId in the request query.`); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - } - const member = await ctx.context.adapter.findOne({ - model: "member", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, { - field: "userId", - value: user.id, - operator: "eq", - connector: "AND" - }] - }); - if (!member) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to list roles.`, { - userId: user.id, - organizationId - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); - } - if (!await hasPermission({ - options, - organizationId, - permissions: { ac: ["read"] }, - role: member.role - }, ctx)) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to list roles.`, { - userId: user.id, - organizationId, - role: member.role - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE); - } - let roles = await ctx.context.adapter.findMany({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }] - }); - roles = roles.map((x) => ({ - ...x, - permission: JSON.parse(x.permission) - })); - return ctx.json(roles); - }); -}; -var getOrgRoleQuerySchema = object({ organizationId: string2().optional().meta({ description: "The id of the organization to read a role for. If not provided, the user's active organization will be used." }) }).and(union([object({ roleName: string2().nonempty().meta({ description: "The name of the role to read" }) }), object({ roleId: string2().nonempty().meta({ description: "The id of the role to read" }) })])).optional(); -var getOrgRole = (options) => { - const { $ReturnAdditionalFields } = getAdditionalFields(options, false); - return createAuthEndpoint("/organization/get-role", { - method: "GET", - requireHeaders: true, - use: [orgSessionMiddleware], - query: getOrgRoleQuerySchema, - metadata: { $Infer: { query: {} } } - }, async (ctx) => { - const { session, user } = ctx.context.session; - const organizationId = ctx.query?.organizationId ?? session.activeOrganizationId; - if (!organizationId) { - ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to read a role. Either set an active org id, or pass an organizationId in the request query.`); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - } - const member = await ctx.context.adapter.findOne({ - model: "member", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, { - field: "userId", - value: user.id, - operator: "eq", - connector: "AND" - }] - }); - if (!member) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to read a role.`, { - userId: user.id, - organizationId - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); - } - if (!await hasPermission({ - options, - organizationId, - permissions: { ac: ["read"] }, - role: member.role - }, ctx)) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to read a role.`, { - userId: user.id, - organizationId, - role: member.role - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE); - } - let condition; - if (ctx.query.roleName) condition = { - field: "role", - value: ctx.query.roleName, - operator: "eq", - connector: "AND" - }; - else if (ctx.query.roleId) condition = { - field: "id", - value: ctx.query.roleId, - operator: "eq", - connector: "AND" - }; - else { - ctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request query.`); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); - } - const role2 = await ctx.context.adapter.findOne({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, condition] - }); - if (!role2) { - ctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, { - ..."roleName" in ctx.query ? { roleName: ctx.query.roleName } : { roleId: ctx.query.roleId }, - organizationId - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); - } - role2.permission = JSON.parse(role2.permission); - return ctx.json(role2); - }); -}; -var roleNameOrIdSchema = union([object({ roleName: string2().nonempty().meta({ description: "The name of the role to update" }) }), object({ roleId: string2().nonempty().meta({ description: "The id of the role to update" }) })]); -var updateOrgRole = (options) => { - const { additionalFieldsSchema, $AdditionalFields, $ReturnAdditionalFields } = getAdditionalFields(options, true); - return createAuthEndpoint("/organization/update-role", { - method: "POST", - body: object({ - organizationId: string2().optional().meta({ description: "The id of the organization to update the role in. If not provided, the user's active organization will be used." }), - data: object({ - permission: record(string2(), array(string2())).optional().meta({ description: "The permission to update the role with" }), - roleName: string2().optional().meta({ description: "The name of the role to update" }), - ...additionalFieldsSchema.shape - }) - }).and(roleNameOrIdSchema), - metadata: { $Infer: { body: {} } }, - requireHeaders: true, - use: [orgSessionMiddleware] - }, async (ctx) => { - const { session, user } = ctx.context.session; - const ac = options.ac; - if (!ac) { - ctx.context.logger.error(`[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.`, ` -Please refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`); - throw APIError2.from("NOT_IMPLEMENTED", ORGANIZATION_ERROR_CODES.MISSING_AC_INSTANCE); - } - const organizationId = ctx.body.organizationId ?? session.activeOrganizationId; - if (!organizationId) { - ctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to update a role. Either set an active org id, or pass an organizationId in the request body.`); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - } - const member = await ctx.context.adapter.findOne({ - model: "member", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, { - field: "userId", - value: user.id, - operator: "eq", - connector: "AND" - }] - }); - if (!member) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to update a role.`, { - userId: user.id, - organizationId - }); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); - } - if (!await hasPermission({ - options, - organizationId, - role: member.role, - permissions: { ac: ["update"] } - }, ctx)) { - ctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to update a role.`); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE); - } - let condition; - if (ctx.body.roleName) condition = { - field: "role", - value: ctx.body.roleName, - operator: "eq", - connector: "AND" - }; - else if (ctx.body.roleId) condition = { - field: "id", - value: ctx.body.roleId, - operator: "eq", - connector: "AND" - }; - else { - ctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request body.`); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); - } - const role2 = await ctx.context.adapter.findOne({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, condition] - }); - if (!role2) { - ctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, { - ..."roleName" in ctx.body ? { roleName: ctx.body.roleName } : { roleId: ctx.body.roleId }, - organizationId - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND); - } - role2.permission = role2.permission ? JSON.parse(role2.permission) : void 0; - const { permission: _, roleName: __, ...additionalFields } = ctx.body.data; - const updateData = { ...additionalFields }; - if (ctx.body.data.permission) { - const newPermission = ctx.body.data.permission; - await checkForInvalidResources({ - ac, - ctx, - permission: newPermission - }); - await checkIfMemberHasPermission({ - ctx, - member, - options, - organizationId, - permissionRequired: newPermission, - user, - action: "update" - }); - updateData.permission = newPermission; - } - if (ctx.body.data.roleName) { - let newRoleName = ctx.body.data.roleName; - newRoleName = normalizeRoleName(newRoleName); - await checkIfRoleNameIsTakenByPreDefinedRole({ - role: newRoleName, - organizationId, - options, - ctx - }); - await checkIfRoleNameIsTakenByRoleInDB({ - role: newRoleName, - organizationId, - ctx - }); - updateData.role = newRoleName; - } - const update = { - ...updateData, - ...updateData.permission ? { permission: JSON.stringify(updateData.permission) } : {} - }; - await ctx.context.adapter.update({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, condition], - update - }); - return ctx.json({ - success: true, - roleData: { - ...role2, - ...update, - permission: updateData.permission || role2.permission || null - } - }); - }); -}; -async function checkForInvalidResources({ ac, ctx, permission }) { - const validResources = Object.keys(ac.statements); - const providedResources = Object.keys(permission); - if (providedResources.some((r) => !validResources.includes(r))) { - ctx.context.logger.error(`[Dynamic Access Control] The provided permission includes an invalid resource.`, { - providedResources, - validResources - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVALID_RESOURCE); - } -} -async function checkIfMemberHasPermission({ ctx, permissionRequired: permission, options, organizationId, member, user, action }) { - const hasNecessaryPermissions = []; - const permissionEntries = Object.entries(permission); - for await (const [resource, permissions] of permissionEntries) for await (const perm of permissions) hasNecessaryPermissions.push({ - resource: { [resource]: [perm] }, - hasPermission: await hasPermission({ - options, - organizationId, - permissions: { [resource]: [perm] }, - useMemoryCache: true, - role: member.role - }, ctx) - }); - const missingPermissions = hasNecessaryPermissions.filter((x) => x.hasPermission === false).map((x) => { - const key = Object.keys(x.resource)[0]; - return `${key}:${x.resource[key][0]}`; - }); - if (missingPermissions.length > 0) { - ctx.context.logger.error(`[Dynamic Access Control] The user is missing permissions necessary to ${action} a role with those set of permissions. -`, { - userId: user.id, - organizationId, - role: member.role, - missingPermissions - }); - let error49; - if (action === "create") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE; - else if (action === "update") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE; - else if (action === "delete") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE; - else if (action === "read") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE; - else if (action === "list") error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE; - else error49 = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE; - throw APIError2.fromStatus("FORBIDDEN", { - message: error49.message, - code: error49.code, - missingPermissions - }); - } -} -async function checkIfRoleNameIsTakenByPreDefinedRole({ options, organizationId, role: role2, ctx }) { - const defaultRoles3 = options.roles ? Object.keys(options.roles) : [ - "owner", - "admin", - "member" - ]; - if (defaultRoles3.includes(role2)) { - ctx.context.logger.error(`[Dynamic Access Control] The role name "${role2}" is already taken by a pre-defined role.`, { - role: role2, - organizationId, - defaultRoles: defaultRoles3 - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NAME_IS_ALREADY_TAKEN); - } -} -async function checkIfRoleNameIsTakenByRoleInDB({ organizationId, role: role2, ctx }) { - if (await ctx.context.adapter.findOne({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId, - operator: "eq", - connector: "AND" - }, { - field: "role", - value: role2, - operator: "eq", - connector: "AND" - }] - })) { - ctx.context.logger.error(`[Dynamic Access Control] The role name "${role2}" is already taken by a role in the database.`, { - role: role2, - organizationId - }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ROLE_NAME_IS_ALREADY_TAKEN); - } -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-invites.mjs -init_error2(); -init_zod(); -var baseInvitationSchema = object({ - email: string2().meta({ description: "The email address of the user to invite" }), - role: union([string2().meta({ description: "The role to assign to the user" }), array(string2().meta({ description: "The roles to assign to the user" }))]).meta({ description: 'The role(s) to assign to the user. It can be `admin`, `member`, owner. Eg: "member"' }), - organizationId: string2().meta({ description: "The organization ID to invite the user to" }).optional(), - resend: boolean2().meta({ description: "Resend the invitation email, if the user is already invited. Eg: true" }).optional(), - teamId: union([string2().meta({ description: "The team ID to invite the user to" }).optional(), array(string2()).meta({ description: "The team IDs to invite the user to" }).optional()]) -}); -var createInvitation = (option) => { - const additionalFieldsSchema = toZodSchema({ - fields: option?.schema?.invitation?.additionalFields || {}, - isClientSide: true - }); - return createAuthEndpoint("/organization/invite-member", { - method: "POST", - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware], - body: object({ - ...baseInvitationSchema.shape, - ...additionalFieldsSchema.shape - }), - metadata: { - $Infer: { body: {} }, - openapi: { - operationId: "createOrganizationInvitation", - description: "Create an invitation to an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - id: { type: "string" }, - email: { type: "string" }, - role: { type: "string" }, - organizationId: { type: "string" }, - inviterId: { type: "string" }, - status: { type: "string" }, - expiresAt: { type: "string" }, - createdAt: { type: "string" } - }, - required: [ - "id", - "email", - "role", - "organizationId", - "inviterId", - "status", - "expiresAt", - "createdAt" - ] - } } } - } } - } - } - }, async (ctx) => { - const session = ctx.context.session; - const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const email3 = ctx.body.email.toLowerCase(); - if (!email2().safeParse(email3).success) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_EMAIL); - const adapter = getOrgAdapter(ctx.context, option); - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - if (!await hasPermission({ - role: member.role, - options: ctx.context.orgOptions, - permissions: { invitation: ["create"] }, - organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION); - const creatorRole = ctx.context.orgOptions.creatorRole || "owner"; - const roles = parseRoles(ctx.body.role); - const rolesArray = roles.split(",").map((r) => r.trim()).filter(Boolean); - const defaults = Object.keys(defaultRoles); - const customRoles = Object.keys(ctx.context.orgOptions.roles || {}); - const validStaticRoles = /* @__PURE__ */ new Set([...defaults, ...customRoles]); - const unknownRoles = rolesArray.filter((role2) => !validStaticRoles.has(role2)); - if (unknownRoles.length > 0) if (ctx.context.orgOptions.dynamicAccessControl?.enabled) { - const foundRoleNames = (await ctx.context.adapter.findMany({ - model: "organizationRole", - where: [{ - field: "organizationId", - value: organizationId - }, { - field: "role", - value: unknownRoles, - operator: "in" - }] - })).map((r) => r.role); - const stillInvalid = unknownRoles.filter((r) => !foundRoleNames.includes(r)); - if (stillInvalid.length > 0) throw new APIError2("BAD_REQUEST", { message: `${ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND}: ${stillInvalid.join(", ")}` }); - } else throw new APIError2("BAD_REQUEST", { message: `${ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND}: ${unknownRoles.join(", ")}` }); - if (!member.role.split(",").map((r) => r.trim()).includes(creatorRole) && roles.split(",").includes(creatorRole)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE); - if (await adapter.findMemberByEmail({ - email: email3, - organizationId - })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION); - const alreadyInvited = await adapter.findPendingInvitation({ - email: email3, - organizationId - }); - if (alreadyInvited.length && !ctx.body.resend) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION); - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - if (alreadyInvited.length && ctx.body.resend) { - const existingInvitation = alreadyInvited[0]; - const newExpiresAt = getDate(ctx.context.orgOptions.invitationExpiresIn || 3600 * 48, "sec"); - await ctx.context.adapter.update({ - model: "invitation", - where: [{ - field: "id", - value: existingInvitation.id - }], - update: { expiresAt: newExpiresAt } - }); - const updatedInvitation = { - ...existingInvitation, - expiresAt: newExpiresAt - }; - if (ctx.context.orgOptions.sendInvitationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.orgOptions.sendInvitationEmail({ - id: updatedInvitation.id, - role: updatedInvitation.role, - email: updatedInvitation.email.toLowerCase(), - organization: organization2, - inviter: { - ...member, - user: session.user - }, - invitation: updatedInvitation - }, ctx.request)); - return ctx.json(updatedInvitation); - } - if (alreadyInvited.length && ctx.context.orgOptions.cancelPendingInvitationsOnReInvite) await adapter.updateInvitation({ - invitationId: alreadyInvited[0].id, - status: "canceled" - }); - const invitationLimit = typeof ctx.context.orgOptions.invitationLimit === "function" ? await ctx.context.orgOptions.invitationLimit({ - user: session.user, - organization: organization2, - member - }, ctx.context) : ctx.context.orgOptions.invitationLimit ?? 100; - if ((await adapter.findPendingInvitations({ organizationId })).length >= invitationLimit) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.INVITATION_LIMIT_REACHED); - if (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== "undefined" && "teamId" in ctx.body && ctx.body.teamId) { - const teamIds2 = typeof ctx.body.teamId === "string" ? [ctx.body.teamId] : ctx.body.teamId; - for (const teamId of teamIds2) { - const team = await adapter.findTeamById({ - teamId, - organizationId, - includeTeamMembers: true - }); - if (!team) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); - const maximumMembersPerTeam = typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === "function" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({ - teamId, - session, - organizationId - }) : ctx.context.orgOptions.teams.maximumMembersPerTeam; - if (team.members.length >= maximumMembersPerTeam) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED); - } - } - const teamIds = "teamId" in ctx.body ? typeof ctx.body.teamId === "string" ? [ctx.body.teamId] : ctx.body.teamId ?? [] : []; - const { email: _, role: __, organizationId: ___, resend: ____, ...additionalFields } = ctx.body; - let invitationData = { - role: roles, - email: email3, - organizationId, - teamIds, - ...additionalFields ? additionalFields : {} - }; - if (option?.organizationHooks?.beforeCreateInvitation) { - const response = await option?.organizationHooks.beforeCreateInvitation({ - invitation: { - ...invitationData, - inviterId: session.user.id, - teamId: teamIds.length > 0 ? teamIds[0] : void 0 - }, - inviter: session.user, - organization: organization2 - }); - if (response && typeof response === "object" && "data" in response) invitationData = { - ...invitationData, - ...response.data - }; - } - const invitation = await adapter.createInvitation({ - invitation: invitationData, - user: session.user - }); - if (ctx.context.orgOptions.sendInvitationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.orgOptions.sendInvitationEmail({ - id: invitation.id, - role: invitation.role, - email: invitation.email.toLowerCase(), - organization: organization2, - inviter: { - ...member, - user: session.user - }, - invitation - }, ctx.request)); - if (option?.organizationHooks?.afterCreateInvitation) await option?.organizationHooks.afterCreateInvitation({ - invitation, - inviter: session.user, - organization: organization2 - }); - return ctx.json(invitation); - }); -}; -var acceptInvitationBodySchema = object({ invitationId: string2().meta({ description: "The ID of the invitation to accept" }) }); -var acceptInvitation = (options) => createAuthEndpoint("/organization/accept-invitation", { - method: "POST", - body: acceptInvitationBodySchema, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware], - metadata: { openapi: { - description: "Accept an invitation to an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - invitation: { type: "object" }, - member: { type: "object" } - } - } } } - } } - } } -}, async (ctx) => { - const session = ctx.context.session; - const adapter = getOrgAdapter(ctx.context, options); - const invitation = await adapter.findInvitationById(ctx.body.invitationId); - if (!invitation || invitation.expiresAt < /* @__PURE__ */ new Date() || invitation.status !== "pending") throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND); - if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION); - if (ctx.context.orgOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION); - const membershipLimit = ctx.context.orgOptions?.membershipLimit || 100; - const membersCount = await adapter.countMembers({ organizationId: invitation.organizationId }); - const organization2 = await adapter.findOrganizationById(invitation.organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - if (membersCount >= (typeof membershipLimit === "number" ? membershipLimit : await membershipLimit(session.user, organization2))) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED); - if (options?.organizationHooks?.beforeAcceptInvitation) await options?.organizationHooks.beforeAcceptInvitation({ - invitation, - user: session.user, - organization: organization2 - }); - const acceptedI = await adapter.updateInvitation({ - invitationId: ctx.body.invitationId, - status: "accepted" - }); - if (!acceptedI) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.FAILED_TO_RETRIEVE_INVITATION); - if (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && "teamId" in acceptedI && acceptedI.teamId) { - const teamIds = acceptedI.teamId.split(","); - const onlyOne = teamIds.length === 1; - for (const teamId of teamIds) { - await adapter.findOrCreateTeamMember({ - teamId, - userId: session.user.id - }); - if (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== "undefined") { - if (await adapter.countTeamMembers({ teamId }) >= (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === "function" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({ - teamId, - session, - organizationId: invitation.organizationId - }) : ctx.context.orgOptions.teams.maximumMembersPerTeam)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED); - } - } - if (onlyOne) { - const teamId = teamIds[0]; - await setSessionCookie(ctx, { - session: await adapter.setActiveTeam(session.session.token, teamId, ctx), - user: session.user - }); - } - } - const member = await adapter.createMember({ - organizationId: invitation.organizationId, - userId: session.user.id, - role: invitation.role, - createdAt: /* @__PURE__ */ new Date() - }); - await adapter.setActiveOrganization(session.session.token, invitation.organizationId, ctx); - if (options?.organizationHooks?.afterAcceptInvitation) await options?.organizationHooks.afterAcceptInvitation({ - invitation: acceptedI, - member, - user: session.user, - organization: organization2 - }); - return ctx.json({ - invitation: acceptedI, - member - }); -}); -var rejectInvitationBodySchema = object({ invitationId: string2().meta({ description: "The ID of the invitation to reject" }) }); -var rejectInvitation = (options) => createAuthEndpoint("/organization/reject-invitation", { - method: "POST", - body: rejectInvitationBodySchema, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware], - metadata: { openapi: { - description: "Reject an invitation to an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - invitation: { type: "object" }, - member: { - type: "object", - nullable: true - } - } - } } } - } } - } } -}, async (ctx) => { - const session = ctx.context.session; - const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); - const invitation = await adapter.findInvitationById(ctx.body.invitationId); - if (!invitation || invitation.status !== "pending") throw APIError2.from("BAD_REQUEST", { - message: "Invitation not found!", - code: "INVITATION_NOT_FOUND" - }); - if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION); - if (ctx.context.orgOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION); - const organization2 = await adapter.findOrganizationById(invitation.organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - if (options?.organizationHooks?.beforeRejectInvitation) await options?.organizationHooks.beforeRejectInvitation({ - invitation, - user: session.user, - organization: organization2 - }); - const rejectedI = await adapter.updateInvitation({ - invitationId: ctx.body.invitationId, - status: "rejected" - }); - if (options?.organizationHooks?.afterRejectInvitation) await options?.organizationHooks.afterRejectInvitation({ - invitation: rejectedI || invitation, - user: session.user, - organization: organization2 - }); - return ctx.json({ - invitation: rejectedI, - member: null - }); -}); -var cancelInvitationBodySchema = object({ invitationId: string2().meta({ description: "The ID of the invitation to cancel" }) }); -var cancelInvitation = (options) => createAuthEndpoint("/organization/cancel-invitation", { - method: "POST", - body: cancelInvitationBodySchema, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware], - openapi: { - operationId: "cancelOrganizationInvitation", - description: "Cancel an invitation to an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { invitation: { type: "object" } } - } } } - } } - } -}, async (ctx) => { - const session = ctx.context.session; - const adapter = getOrgAdapter(ctx.context, options); - const invitation = await adapter.findInvitationById(ctx.body.invitationId); - if (!invitation) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND); - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId: invitation.organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - if (!await hasPermission({ - role: member.role, - options: ctx.context.orgOptions, - permissions: { invitation: ["cancel"] }, - organizationId: invitation.organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION); - const organization2 = await adapter.findOrganizationById(invitation.organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - if (options?.organizationHooks?.beforeCancelInvitation) await options?.organizationHooks.beforeCancelInvitation({ - invitation, - cancelledBy: session.user, - organization: organization2 - }); - const canceledI = await adapter.updateInvitation({ - invitationId: ctx.body.invitationId, - status: "canceled" - }); - if (options?.organizationHooks?.afterCancelInvitation) await options?.organizationHooks.afterCancelInvitation({ - invitation: canceledI || invitation, - cancelledBy: session.user, - organization: organization2 - }); - return ctx.json(canceledI); -}); -var getInvitationQuerySchema = object({ id: string2().meta({ description: "The ID of the invitation to get" }) }); -var getInvitation = (options) => createAuthEndpoint("/organization/get-invitation", { - method: "GET", - use: [orgMiddleware], - requireHeaders: true, - query: getInvitationQuerySchema, - metadata: { openapi: { - description: "Get an invitation by ID", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - id: { type: "string" }, - email: { type: "string" }, - role: { type: "string" }, - organizationId: { type: "string" }, - inviterId: { type: "string" }, - status: { type: "string" }, - expiresAt: { type: "string" }, - organizationName: { type: "string" }, - organizationSlug: { type: "string" }, - inviterEmail: { type: "string" } - }, - required: [ - "id", - "email", - "role", - "organizationId", - "inviterId", - "status", - "expiresAt", - "organizationName", - "organizationSlug", - "inviterEmail" - ] - } } } - } } - } } -}, async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session) throw APIError2.fromStatus("UNAUTHORIZED", { message: "Not authenticated" }); - const adapter = getOrgAdapter(ctx.context, options); - const invitation = await adapter.findInvitationById(ctx.query.id); - if (!invitation || invitation.status !== "pending" || invitation.expiresAt < /* @__PURE__ */ new Date()) throw APIError2.fromStatus("BAD_REQUEST", { message: "Invitation not found!" }); - if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION); - const organization2 = await adapter.findOrganizationById(invitation.organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const member = await adapter.findMemberByOrgId({ - userId: invitation.inviterId, - organizationId: invitation.organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION); - return ctx.json({ - ...invitation, - organizationName: organization2.name, - organizationSlug: organization2.slug, - inviterEmail: member.user.email - }); -}); -var listInvitationQuerySchema = object({ organizationId: string2().meta({ description: "The ID of the organization to list invitations for" }).optional() }).optional(); -var listInvitations = (options) => createAuthEndpoint("/organization/list-invitations", { - method: "GET", - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware], - query: listInvitationQuerySchema -}, async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session) throw APIError2.fromStatus("UNAUTHORIZED", { message: "Not authenticated" }); - const orgId = ctx.query?.organizationId || session.session.activeOrganizationId; - if (!orgId) throw APIError2.fromStatus("BAD_REQUEST", { message: "Organization ID is required" }); - const adapter = getOrgAdapter(ctx.context, options); - if (!await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId: orgId - })) throw APIError2.fromStatus("FORBIDDEN", { message: "You are not a member of this organization" }); - const invitations = await adapter.listInvitations({ organizationId: orgId }); - return ctx.json(invitations); -}); -var listUserInvitations = (options) => createAuthEndpoint("/organization/list-user-invitations", { - method: "GET", - use: [orgMiddleware], - query: object({ email: string2().meta({ description: "The email of the user to list invitations for. This only works for server side API calls." }).optional() }).optional(), - metadata: { openapi: { - description: "List all invitations a user has received", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "array", - items: { - type: "object", - properties: { - id: { type: "string" }, - email: { type: "string" }, - role: { type: "string" }, - organizationId: { type: "string" }, - organizationName: { type: "string" }, - inviterId: { - type: "string", - description: "The ID of the user who created the invitation" - }, - teamId: { - type: "string", - description: "The ID of the team associated with the invitation", - nullable: true - }, - status: { type: "string" }, - expiresAt: { type: "string" }, - createdAt: { type: "string" } - }, - required: [ - "id", - "email", - "role", - "organizationId", - "organizationName", - "inviterId", - "status", - "expiresAt", - "createdAt" - ] - } - } } } - } } - } } -}, async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (ctx.request && ctx.query?.email) throw APIError2.fromStatus("BAD_REQUEST", { message: "User email cannot be passed for client side API calls." }); - const userEmail = session?.user.email || ctx.query?.email; - if (!userEmail) throw APIError2.fromStatus("BAD_REQUEST", { message: "Missing session headers, or email query parameter." }); - const pendingInvitations = (await getOrgAdapter(ctx.context, options).listUserInvitations(userEmail)).filter((inv) => inv.status === "pending"); - return ctx.json(pendingInvitations); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-members.mjs -init_error2(); -init_adapter(); -init_zod(); -var baseMemberSchema = object({ - userId: coerce_exports.string().meta({ description: 'The user Id which represents the user to be added as a member. If `null` is provided, then it\'s expected to provide session headers. Eg: "user-id"' }), - role: union([string2(), array(string2())]).meta({ description: 'The role(s) to assign to the new member. Eg: ["admin", "sale"]' }), - organizationId: string2().meta({ description: `An optional organization ID to pass. If not provided, will default to the user's active organization. Eg: "org-id"` }).optional(), - teamId: string2().meta({ description: 'An optional team ID to add the member to. Eg: "team-id"' }).optional() -}); -var addMember = (option) => { - const additionalFieldsSchema = toZodSchema({ - fields: option?.schema?.member?.additionalFields || {}, - isClientSide: true - }); - return createAuthEndpoint({ - method: "POST", - body: object({ - ...baseMemberSchema.shape, - ...additionalFieldsSchema.shape - }), - use: [orgMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - operationId: "addOrganizationMember", - description: "Add a member to an organization" - } - } - }, async (ctx) => { - const session = ctx.body.userId ? await getSessionFromCtx(ctx).catch((e) => null) : null; - const orgId = ctx.body.organizationId || session?.session.activeOrganizationId; - if (!orgId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const teamId = "teamId" in ctx.body ? ctx.body.teamId : void 0; - if (teamId && !ctx.context.orgOptions.teams?.enabled) { - ctx.context.logger.error("Teams are not enabled"); - throw APIError2.fromStatus("BAD_REQUEST", { message: "Teams are not enabled" }); - } - const adapter = getOrgAdapter(ctx.context, option); - const user = await ctx.context.internalAdapter.findUserById(ctx.body.userId); - if (!user) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.USER_NOT_FOUND); - if (await adapter.findMemberByEmail({ - email: user.email, - organizationId: orgId - })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION); - if (teamId) { - const team = await adapter.findTeamById({ - teamId, - organizationId: orgId - }); - if (!team || team.organizationId !== orgId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); - } - const membershipLimit = ctx.context.orgOptions?.membershipLimit || 100; - const count = await adapter.countMembers({ organizationId: orgId }); - const organization2 = await adapter.findOrganizationById(orgId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - if (count >= (typeof membershipLimit === "number" ? membershipLimit : await membershipLimit(user, organization2))) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED); - const { role: _, userId: __, organizationId: ___, ...additionalFields } = ctx.body; - let memberData = { - organizationId: orgId, - userId: user.id, - role: parseRoles(ctx.body.role), - createdAt: /* @__PURE__ */ new Date(), - ...additionalFields ? additionalFields : {} - }; - if (option?.organizationHooks?.beforeAddMember) { - const response = await option?.organizationHooks.beforeAddMember({ - member: { - userId: user.id, - organizationId: orgId, - role: parseRoles(ctx.body.role), - ...additionalFields - }, - user, - organization: organization2 - }); - if (response && typeof response === "object" && "data" in response) memberData = { - ...memberData, - ...response.data - }; - } - const createdMember = await adapter.createMember(memberData); - if (teamId) await adapter.findOrCreateTeamMember({ - userId: user.id, - teamId - }); - if (option?.organizationHooks?.afterAddMember) await option?.organizationHooks.afterAddMember({ - member: createdMember, - user, - organization: organization2 - }); - return ctx.json(createdMember); - }); -}; -var removeMemberBodySchema = object({ - memberIdOrEmail: string2().meta({ description: "The ID or email of the member to remove" }), - organizationId: string2().meta({ description: 'The ID of the organization to remove the member from. If not provided, the active organization will be used. Eg: "org-id"' }).optional() -}); -var removeMember = (options) => createAuthEndpoint("/organization/remove-member", { - method: "POST", - body: removeMemberBodySchema, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware], - metadata: { openapi: { - description: "Remove a member from an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { member: { - type: "object", - properties: { - id: { type: "string" }, - userId: { type: "string" }, - organizationId: { type: "string" }, - role: { type: "string" } - }, - required: [ - "id", - "userId", - "organizationId", - "role" - ] - } }, - required: ["member"] - } } } - } } - } } -}, async (ctx) => { - const session = ctx.context.session; - const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const adapter = getOrgAdapter(ctx.context, options); - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - let toBeRemovedMember = null; - if (ctx.body.memberIdOrEmail.includes("@")) toBeRemovedMember = await adapter.findMemberByEmail({ - email: ctx.body.memberIdOrEmail, - organizationId - }); - else { - const result = await adapter.findMemberById(ctx.body.memberIdOrEmail); - if (!result) toBeRemovedMember = null; - else { - const { user: _user, ...member2 } = result; - toBeRemovedMember = member2; - } - } - if (!toBeRemovedMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - const roles = toBeRemovedMember.role.split(","); - const creatorRole = ctx.context.orgOptions?.creatorRole || "owner"; - if (roles.includes(creatorRole)) { - if (!member.role.split(",").map((r) => r.trim()).includes(creatorRole)) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER); - const { members } = await adapter.listMembers({ organizationId }); - if (members.filter((member2) => { - return member2.role.split(",").includes(creatorRole); - }).length <= 1) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER); - } - if (!await hasPermission({ - role: member.role, - options: ctx.context.orgOptions, - permissions: { member: ["delete"] }, - organizationId - }, ctx)) throw APIError2.from("UNAUTHORIZED", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER); - if (toBeRemovedMember?.organizationId !== organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const userBeingRemoved = await ctx.context.internalAdapter.findUserById(toBeRemovedMember.userId); - if (!userBeingRemoved) throw APIError2.fromStatus("BAD_REQUEST", { message: "User not found" }); - if (options?.organizationHooks?.beforeRemoveMember) await options?.organizationHooks.beforeRemoveMember({ - member: toBeRemovedMember, - user: userBeingRemoved, - organization: organization2 - }); - await adapter.deleteMember({ - memberId: toBeRemovedMember.id, - organizationId, - userId: toBeRemovedMember.userId - }); - if (session.user.id === toBeRemovedMember.userId && session.session.activeOrganizationId === toBeRemovedMember.organizationId) await adapter.setActiveOrganization(session.session.token, null, ctx); - if (options?.organizationHooks?.afterRemoveMember) await options?.organizationHooks.afterRemoveMember({ - member: toBeRemovedMember, - user: userBeingRemoved, - organization: organization2 - }); - return ctx.json({ member: toBeRemovedMember }); -}); -var updateMemberRoleBodySchema = object({ - role: union([string2(), array(string2())]).meta({ description: 'The new role to be applied. This can be a string or array of strings representing the roles. Eg: ["admin", "sale"]' }), - memberId: string2().meta({ description: 'The member id to apply the role update to. Eg: "member-id"' }), - organizationId: string2().meta({ description: 'An optional organization ID which the member is a part of to apply the role update. If not provided, you must provide session headers to get the active organization. Eg: "organization-id"' }).optional() -}); -var updateMemberRole = (option) => createAuthEndpoint("/organization/update-member-role", { - method: "POST", - body: updateMemberRoleBodySchema, - use: [orgMiddleware, orgSessionMiddleware], - requireHeaders: true, - metadata: { - $Infer: { body: {} }, - openapi: { - operationId: "updateOrganizationMemberRole", - description: "Update the role of a member in an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { member: { - type: "object", - properties: { - id: { type: "string" }, - userId: { type: "string" }, - organizationId: { type: "string" }, - role: { type: "string" } - }, - required: [ - "id", - "userId", - "organizationId", - "role" - ] - } }, - required: ["member"] - } } } - } } - } - } -}, async (ctx) => { - const session = ctx.context.session; - if (!ctx.body.role) throw APIError2.fromStatus("BAD_REQUEST"); - const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); - const roleToSet = Array.isArray(ctx.body.role) ? ctx.body.role : ctx.body.role ? [ctx.body.role] : []; - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - const toBeUpdatedMember = member.id !== ctx.body.memberId ? await adapter.findMemberById(ctx.body.memberId) : member; - if (!toBeUpdatedMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - if (!(toBeUpdatedMember.organizationId === organizationId)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER); - const creatorRole = ctx.context.orgOptions?.creatorRole || "owner"; - const updatingMemberRoles = member.role.split(","); - const isUpdatingCreator = toBeUpdatedMember.role.split(",").includes(creatorRole); - const updaterIsCreator = updatingMemberRoles.includes(creatorRole); - const isSettingCreatorRole = roleToSet.includes(creatorRole); - const memberIsUpdatingThemselves = member.id === toBeUpdatedMember.id; - if (isUpdatingCreator && !updaterIsCreator || isSettingCreatorRole && !updaterIsCreator) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER); - if (updaterIsCreator && memberIsUpdatingThemselves) { - if ((await ctx.context.adapter.findMany({ - model: "member", - where: [{ - field: "organizationId", - value: organizationId - }] - })).filter((member2) => { - return member2.role.split(",").includes(creatorRole); - }).length <= 1 && !isSettingCreatorRole) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER); - } - if (!await hasPermission({ - role: member.role, - options: ctx.context.orgOptions, - permissions: { member: ["update"] }, - allowCreatorAllPermissions: true, - organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER); - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const userBeingUpdated = await ctx.context.internalAdapter.findUserById(toBeUpdatedMember.userId); - if (!userBeingUpdated) throw APIError2.fromStatus("BAD_REQUEST", { message: "User not found" }); - const previousRole = toBeUpdatedMember.role; - const newRole = parseRoles(ctx.body.role); - if (option?.organizationHooks?.beforeUpdateMemberRole) { - const response = await option?.organizationHooks.beforeUpdateMemberRole({ - member: toBeUpdatedMember, - newRole, - user: userBeingUpdated, - organization: organization2 - }); - if (response && typeof response === "object" && "data" in response) { - const updatedMember2 = await adapter.updateMember(ctx.body.memberId, response.data.role || newRole); - if (!updatedMember2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - if (option?.organizationHooks?.afterUpdateMemberRole) await option?.organizationHooks.afterUpdateMemberRole({ - member: updatedMember2, - previousRole, - user: userBeingUpdated, - organization: organization2 - }); - return ctx.json(updatedMember2); - } - } - const updatedMember = await adapter.updateMember(ctx.body.memberId, newRole); - if (!updatedMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - if (option?.organizationHooks?.afterUpdateMemberRole) await option?.organizationHooks.afterUpdateMemberRole({ - member: updatedMember, - previousRole, - user: userBeingUpdated, - organization: organization2 - }); - return ctx.json(updatedMember); -}); -var getActiveMember = (options) => createAuthEndpoint("/organization/get-active-member", { - method: "GET", - use: [orgMiddleware, orgSessionMiddleware], - requireHeaders: true, - metadata: { openapi: { - description: "Get the member details of the active organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - id: { type: "string" }, - userId: { type: "string" }, - organizationId: { type: "string" }, - role: { type: "string" } - }, - required: [ - "id", - "userId", - "organizationId", - "role" - ] - } } } - } } - } } -}, async (ctx) => { - const session = ctx.context.session; - const organizationId = session.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const member = await getOrgAdapter(ctx.context, options).findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - return ctx.json(member); -}); -var leaveOrganizationBodySchema = object({ organizationId: string2().meta({ description: 'The organization Id for the member to leave. Eg: "organization-id"' }) }); -var leaveOrganization = (options) => createAuthEndpoint("/organization/leave", { - method: "POST", - body: leaveOrganizationBodySchema, - requireHeaders: true, - use: [sessionMiddleware, orgMiddleware] -}, async (ctx) => { - const session = ctx.context.session; - const adapter = getOrgAdapter(ctx.context, options); - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId: ctx.body.organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND); - const creatorRole = ctx.context.orgOptions?.creatorRole || "owner"; - if (member.role.split(",").includes(creatorRole)) { - if ((await ctx.context.adapter.findMany({ - model: "member", - where: [{ - field: "organizationId", - value: ctx.body.organizationId - }] - })).filter((member2) => member2.role.split(",").includes(creatorRole)).length <= 1) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER); - } - await adapter.deleteMember({ - memberId: member.id, - organizationId: ctx.body.organizationId, - userId: session.user.id - }); - if (session.session.activeOrganizationId === ctx.body.organizationId) await adapter.setActiveOrganization(session.session.token, null, ctx); - return ctx.json(member); -}); -var listMembers = (options) => createAuthEndpoint("/organization/list-members", { - method: "GET", - query: object({ - limit: string2().meta({ description: "The number of users to return" }).or(number2()).optional(), - offset: string2().meta({ description: "The offset to start from" }).or(number2()).optional(), - sortBy: string2().meta({ description: "The field to sort by" }).optional(), - sortDirection: _enum2(["asc", "desc"]).meta({ description: "The direction to sort by" }).optional(), - filterField: string2().meta({ description: "The field to filter by" }).optional(), - filterValue: string2().meta({ description: "The value to filter by" }).or(number2()).or(boolean2()).or(array(string2())).or(array(number2())).optional(), - filterOperator: _enum2(whereOperators).meta({ description: "The operator to use for the filter" }).optional(), - organizationId: string2().meta({ description: `The organization ID to list members for. If not provided, will default to the user's active organization. Eg: "organization-id"` }).optional(), - organizationSlug: string2().meta({ description: `The organization slug to list members for. If not provided, will default to the user's active organization. Eg: "organization-slug"` }).optional() - }).optional(), - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware] -}, async (ctx) => { - const session = ctx.context.session; - let organizationId = ctx.query?.organizationId || session.session.activeOrganizationId; - const adapter = getOrgAdapter(ctx.context, options); - if (ctx.query?.organizationSlug) { - const organization2 = await adapter.findOrganizationBySlug(ctx.query?.organizationSlug); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - organizationId = organization2.id; - } - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - if (!await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - })) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); - const { members, total } = await adapter.listMembers({ - organizationId, - limit: ctx.query?.limit ? Number(ctx.query.limit) : void 0, - offset: ctx.query?.offset ? Number(ctx.query.offset) : void 0, - sortBy: ctx.query?.sortBy, - sortOrder: ctx.query?.sortDirection, - filter: ctx.query?.filterField ? { - field: ctx.query?.filterField, - operator: ctx.query.filterOperator, - value: ctx.query.filterValue - } : void 0 - }); - return ctx.json({ - members, - total - }); -}); -var getActiveMemberRoleQuerySchema = object({ - userId: string2().meta({ description: "The user ID to get the role for. If not provided, will default to the current user's" }).optional(), - organizationId: string2().meta({ description: `The organization ID to list members for. If not provided, will default to the user's active organization. Eg: "organization-id"` }).optional(), - organizationSlug: string2().meta({ description: `The organization slug to list members for. If not provided, will default to the user's active organization. Eg: "organization-slug"` }).optional() -}).optional(); -var getActiveMemberRole = (options) => createAuthEndpoint("/organization/get-active-member-role", { - method: "GET", - query: getActiveMemberRoleQuerySchema, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware] -}, async (ctx) => { - const session = ctx.context.session; - let organizationId = ctx.query?.organizationId || session.session.activeOrganizationId; - const adapter = getOrgAdapter(ctx.context, options); - if (ctx.query?.organizationSlug) { - const organization2 = await adapter.findOrganizationBySlug(ctx.query?.organizationSlug); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - organizationId = organization2.id; - } - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const isMember = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!isMember) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); - if (!ctx.query?.userId) return ctx.json({ role: isMember.role }); - const userIdToGetRole = ctx.query?.userId; - const member = await adapter.findMemberByOrgId({ - userId: userIdToGetRole, - organizationId - }); - if (!member) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION); - return ctx.json({ role: member?.role }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-org.mjs -init_error2(); -init_zod(); -var baseOrganizationSchema = object({ - name: string2().min(1).meta({ description: "The name of the organization" }), - slug: string2().min(1).meta({ description: "The slug of the organization" }), - userId: coerce_exports.string().meta({ description: 'The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server. server-only. Eg: "user-id"' }).optional(), - logo: string2().meta({ description: "The logo of the organization" }).optional(), - metadata: record(string2(), any()).meta({ description: "The metadata of the organization" }).optional(), - keepCurrentActiveOrganization: boolean2().meta({ description: "Whether to keep the current active organization active after creating a new one. Eg: true" }).optional() -}); -var createOrganization = (options) => { - const additionalFieldsSchema = toZodSchema({ - fields: options?.schema?.organization?.additionalFields || {}, - isClientSide: true - }); - return createAuthEndpoint("/organization/create", { - method: "POST", - body: object({ - ...baseOrganizationSchema.shape, - ...additionalFieldsSchema.shape - }), - use: [orgMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - description: "Create an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - description: "The organization that was created", - $ref: "#/components/schemas/Organization" - } } } - } } - } - } - }, async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session && (ctx.request || ctx.headers)) throw APIError2.fromStatus("UNAUTHORIZED"); - let user = session?.user || null; - if (!user) { - if (!ctx.body.userId) throw APIError2.fromStatus("UNAUTHORIZED"); - user = await ctx.context.internalAdapter.findUserById(ctx.body.userId); - } - if (!user) throw APIError2.fromStatus("UNAUTHORIZED"); - const options2 = ctx.context.orgOptions; - const canCreateOrg = typeof options2?.allowUserToCreateOrganization === "function" ? await options2.allowUserToCreateOrganization(user) : options2?.allowUserToCreateOrganization === void 0 ? true : options2.allowUserToCreateOrganization; - const isSystemAction = !session && ctx.body.userId; - if (!canCreateOrg && !isSystemAction) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION); - const adapter = getOrgAdapter(ctx.context, options2); - const userOrganizations = await adapter.listOrganizations(user.id); - if (typeof options2.organizationLimit === "number" ? userOrganizations.length >= options2.organizationLimit : typeof options2.organizationLimit === "function" ? await options2.organizationLimit(user) : false) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS); - if (await adapter.findOrganizationBySlug(ctx.body.slug)) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_ALREADY_EXISTS); - let { keepCurrentActiveOrganization: _, userId: __, ...orgData } = ctx.body; - if (options2?.organizationHooks?.beforeCreateOrganization) { - const response = await options2?.organizationHooks.beforeCreateOrganization({ - organization: orgData, - user - }); - if (response && typeof response === "object" && "data" in response) orgData = { - ...ctx.body, - ...response.data - }; - } - const organization2 = await adapter.createOrganization({ organization: { - ...orgData, - createdAt: /* @__PURE__ */ new Date() - } }); - let member; - let teamMember = null; - let data = { - userId: user.id, - organizationId: organization2.id, - role: ctx.context.orgOptions.creatorRole || "owner" - }; - if (options2?.organizationHooks?.beforeAddMember) { - const response = await options2?.organizationHooks.beforeAddMember({ - member: { - userId: user.id, - organizationId: organization2.id, - role: ctx.context.orgOptions.creatorRole || "owner" - }, - user, - organization: organization2 - }); - if (response && typeof response === "object" && "data" in response) data = { - ...data, - ...response.data - }; - } - member = await adapter.createMember(data); - if (options2?.organizationHooks?.afterAddMember) await options2?.organizationHooks.afterAddMember({ - member, - user, - organization: organization2 - }); - if (options2?.teams?.enabled && options2.teams.defaultTeam?.enabled !== false) { - let teamData = { - organizationId: organization2.id, - name: `${organization2.name}`, - createdAt: /* @__PURE__ */ new Date() - }; - if (options2?.organizationHooks?.beforeCreateTeam) { - const response = await options2?.organizationHooks.beforeCreateTeam({ - team: { - organizationId: organization2.id, - name: `${organization2.name}` - }, - user, - organization: organization2 - }); - if (response && typeof response === "object" && "data" in response) teamData = { - ...teamData, - ...response.data - }; - } - const defaultTeam = await options2.teams.defaultTeam?.customCreateDefaultTeam?.(organization2, ctx) || await adapter.createTeam(teamData); - teamMember = await adapter.findOrCreateTeamMember({ - teamId: defaultTeam.id, - userId: user.id - }); - if (options2?.organizationHooks?.afterCreateTeam) await options2?.organizationHooks.afterCreateTeam({ - team: defaultTeam, - user, - organization: organization2 - }); - } - if (options2?.organizationHooks?.afterCreateOrganization) await options2?.organizationHooks.afterCreateOrganization({ - organization: organization2, - user, - member - }); - if (ctx.context.session && !ctx.body.keepCurrentActiveOrganization) await adapter.setActiveOrganization(ctx.context.session.session.token, organization2.id, ctx); - if (teamMember && ctx.context.session && !ctx.body.keepCurrentActiveOrganization) await adapter.setActiveTeam(ctx.context.session.session.token, teamMember.teamId, ctx); - return ctx.json({ - ...organization2, - metadata: organization2.metadata && typeof organization2.metadata === "string" ? JSON.parse(organization2.metadata) : organization2.metadata, - members: [member] - }); - }); -}; -var checkOrganizationSlugBodySchema = object({ slug: string2().meta({ description: 'The organization slug to check. Eg: "my-org"' }) }); -var checkOrganizationSlug = (options) => createAuthEndpoint("/organization/check-slug", { - method: "POST", - body: checkOrganizationSlugBodySchema, - use: [requestOnlySessionMiddleware, orgMiddleware] -}, async (ctx) => { - if (!await getOrgAdapter(ctx.context, options).findOrganizationBySlug(ctx.body.slug)) return ctx.json({ status: true }); - throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_SLUG_ALREADY_TAKEN); -}); -var baseUpdateOrganizationSchema = object({ - name: string2().min(1).meta({ description: "The name of the organization" }).optional(), - slug: string2().min(1).meta({ description: "The slug of the organization" }).optional(), - logo: string2().meta({ description: "The logo of the organization" }).optional(), - metadata: record(string2(), any()).meta({ description: "The metadata of the organization" }).optional() -}); -var updateOrganization = (options) => { - const additionalFieldsSchema = toZodSchema({ - fields: options?.schema?.organization?.additionalFields || {}, - isClientSide: true - }); - return createAuthEndpoint("/organization/update", { - method: "POST", - body: object({ - data: object({ - ...additionalFieldsSchema.shape, - ...baseUpdateOrganizationSchema.shape - }).partial(), - organizationId: string2().meta({ description: 'The organization ID. Eg: "org-id"' }).optional() - }), - requireHeaders: true, - use: [orgMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - description: "Update an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - description: "The updated organization", - $ref: "#/components/schemas/Organization" - } } } - } } - } - } - }, async (ctx) => { - const session = await ctx.context.getSession(ctx); - if (!session) throw APIError2.fromStatus("UNAUTHORIZED", { message: "User not found" }); - const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const adapter = getOrgAdapter(ctx.context, options); - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - if (!await hasPermission({ - permissions: { organization: ["update"] }, - role: member.role, - options: ctx.context.orgOptions, - organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION); - if (typeof ctx.body.data.slug === "string") { - const existingOrganization = await adapter.findOrganizationBySlug(ctx.body.data.slug); - if (existingOrganization && existingOrganization.id !== organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_SLUG_ALREADY_TAKEN); - } - if (options?.organizationHooks?.beforeUpdateOrganization) { - const response = await options.organizationHooks.beforeUpdateOrganization({ - organization: ctx.body.data, - user: session.user, - member - }); - if (response && typeof response === "object" && "data" in response) ctx.body.data = { - ...ctx.body.data, - ...response.data - }; - } - const updatedOrg = await adapter.updateOrganization(organizationId, ctx.body.data); - if (options?.organizationHooks?.afterUpdateOrganization) await options.organizationHooks.afterUpdateOrganization({ - organization: updatedOrg, - user: session.user, - member - }); - return ctx.json(updatedOrg); - }); -}; -var deleteOrganizationBodySchema = object({ organizationId: string2().meta({ description: "The organization id to delete" }) }); -var deleteOrganization = (options) => { - return createAuthEndpoint("/organization/delete", { - method: "POST", - body: deleteOrganizationBodySchema, - requireHeaders: true, - use: [orgMiddleware], - metadata: { openapi: { - description: "Delete an organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "string", - description: "The organization id that was deleted" - } } } - } } - } } - }, async (ctx) => { - if (ctx.context.orgOptions.disableOrganizationDeletion) throw APIError2.from("NOT_FOUND", { - message: "Organization deletion is disabled", - code: "ORGANIZATION_DELETION_DISABLED" - }); - const session = await ctx.context.getSession(ctx); - if (!session) throw APIError2.fromStatus("UNAUTHORIZED"); - const organizationId = ctx.body.organizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const adapter = getOrgAdapter(ctx.context, options); - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - if (!await hasPermission({ - role: member.role, - permissions: { organization: ["delete"] }, - organizationId, - options: ctx.context.orgOptions - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION); - if (organizationId === session.session.activeOrganizationId) - await adapter.setActiveOrganization(session.session.token, null, ctx); - const org = await adapter.findOrganizationById(organizationId); - if (!org) throw APIError2.fromStatus("BAD_REQUEST"); - if (options?.organizationHooks?.beforeDeleteOrganization) await options.organizationHooks.beforeDeleteOrganization({ - organization: org, - user: session.user - }); - await adapter.deleteOrganization(organizationId); - if (options?.organizationHooks?.afterDeleteOrganization) await options.organizationHooks.afterDeleteOrganization({ - organization: org, - user: session.user - }); - return ctx.json(org); - }); -}; -var getFullOrganizationQuerySchema = optional(object({ - organizationId: string2().meta({ description: "The organization id to get" }).optional(), - organizationSlug: string2().meta({ description: "The organization slug to get" }).optional(), - membersLimit: number2().or(string2().transform((val) => parseInt(val))).meta({ description: "The limit of members to get. By default, it uses the membershipLimit option." }).optional() -})); -var getFullOrganization = (options) => createAuthEndpoint("/organization/get-full-organization", { - method: "GET", - query: getFullOrganizationQuerySchema, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware], - metadata: { openapi: { - operationId: "getOrganization", - description: "Get the full organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - description: "The organization", - $ref: "#/components/schemas/Organization" - } } } - } } - } } -}, async (ctx) => { - const session = ctx.context.session; - const organizationId = ctx.query?.organizationSlug || ctx.query?.organizationId || session.session.activeOrganizationId; - if (!organizationId) return ctx.json(null, { status: 200 }); - const adapter = getOrgAdapter(ctx.context, options); - const organization2 = await adapter.findFullOrganization({ - organizationId, - isSlug: !!ctx.query?.organizationSlug, - includeTeams: ctx.context.orgOptions.teams?.enabled, - membersLimit: ctx.query?.membersLimit - }); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - if (!await adapter.checkMembership({ - userId: session.user.id, - organizationId: organization2.id - })) { - await adapter.setActiveOrganization(session.session.token, null, ctx); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - } - return ctx.json(organization2); -}); -var setActiveOrganizationBodySchema = object({ - organizationId: string2().meta({ description: 'The organization id to set as active. It can be null to unset the active organization. Eg: "org-id"' }).nullable().optional(), - organizationSlug: string2().meta({ description: 'The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided. Eg: "org-slug"' }).optional() -}); -var setActiveOrganization = (options) => { - return createAuthEndpoint("/organization/set-active", { - method: "POST", - body: setActiveOrganizationBodySchema, - use: [orgSessionMiddleware, orgMiddleware], - requireHeaders: true, - metadata: { openapi: { - operationId: "setActiveOrganization", - description: "Set the active organization", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - description: "The organization", - $ref: "#/components/schemas/Organization" - } } } - } } - } } - }, async (ctx) => { - const adapter = getOrgAdapter(ctx.context, options); - const session = ctx.context.session; - let organizationId = ctx.body.organizationId; - const organizationSlug = ctx.body.organizationSlug; - if (organizationId === null) { - if (!session.session.activeOrganizationId) return ctx.json(null); - await setSessionCookie(ctx, { - session: await adapter.setActiveOrganization(session.session.token, null, ctx), - user: session.user - }); - return ctx.json(null); - } - if (!organizationId && !organizationSlug) { - const sessionOrgId = session.session.activeOrganizationId; - if (!sessionOrgId) return ctx.json(null); - organizationId = sessionOrgId; - } - if (organizationSlug && !organizationId) { - const organization3 = await adapter.findOrganizationBySlug(organizationSlug); - if (!organization3) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - organizationId = organization3.id; - } - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - if (!await adapter.checkMembership({ - userId: session.user.id, - organizationId - })) { - await adapter.setActiveOrganization(session.session.token, null, ctx); - throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - } - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - await setSessionCookie(ctx, { - session: await adapter.setActiveOrganization(session.session.token, organization2.id, ctx), - user: session.user - }); - return ctx.json(organization2); - }); -}; -var listOrganizations = (options) => createAuthEndpoint("/organization/list", { - method: "GET", - use: [orgMiddleware, orgSessionMiddleware], - requireHeaders: true, - metadata: { openapi: { - description: "List all organizations", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "array", - items: { $ref: "#/components/schemas/Organization" } - } } } - } } - } } -}, async (ctx) => { - const organizations = await getOrgAdapter(ctx.context, options).listOrganizations(ctx.context.session.user.id); - return ctx.json(organizations); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/schema.mjs -init_id2(); -init_zod(); -var roleSchema = string2(); -var invitationStatus = _enum2([ - "pending", - "accepted", - "rejected", - "canceled" -]).default("pending"); -object({ - id: string2().default(generateId), - name: string2(), - slug: string2(), - logo: string2().nullish().optional(), - metadata: record(string2(), unknown()).or(string2().transform((v) => JSON.parse(v))).optional(), - createdAt: date3() -}); -object({ - id: string2().default(generateId), - organizationId: string2(), - userId: coerce_exports.string(), - role: roleSchema, - createdAt: date3().default(() => /* @__PURE__ */ new Date()) -}); -object({ - id: string2().default(generateId), - organizationId: string2(), - email: string2(), - role: roleSchema, - status: invitationStatus, - teamId: string2().nullish(), - inviterId: string2(), - expiresAt: date3(), - createdAt: date3().default(() => /* @__PURE__ */ new Date()) -}); -var teamSchema = object({ - id: string2().default(generateId), - name: string2().min(1), - organizationId: string2(), - createdAt: date3(), - updatedAt: date3().optional() -}); -object({ - id: string2().default(generateId), - teamId: string2(), - userId: string2(), - createdAt: date3().default(() => /* @__PURE__ */ new Date()) -}); -object({ - id: string2().default(generateId), - organizationId: string2(), - role: string2(), - permission: record(string2(), array(string2())), - createdAt: date3().default(() => /* @__PURE__ */ new Date()), - updatedAt: date3().optional() -}); -var defaultRoles2 = [ - "admin", - "member", - "owner" -]; -union([_enum2(defaultRoles2), array(_enum2(defaultRoles2))]); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-team.mjs -init_error2(); -init_zod(); -var teamBaseSchema = object({ - name: string2().meta({ description: 'The name of the team. Eg: "my-team"' }), - organizationId: string2().meta({ description: 'The organization ID which the team will be created in. Defaults to the active organization. Eg: "organization-id"' }).optional() -}); -var createTeam = (options) => { - const additionalFieldsSchema = toZodSchema({ - fields: options?.schema?.team?.additionalFields ?? {}, - isClientSide: true - }); - return createAuthEndpoint("/organization/create-team", { - method: "POST", - body: object({ - ...teamBaseSchema.shape, - ...additionalFieldsSchema.shape - }), - use: [orgMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - description: "Create a new team within an organization", - responses: { "200": { - description: "Team created successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - id: { - type: "string", - description: "Unique identifier of the created team" - }, - name: { - type: "string", - description: "Name of the team" - }, - organizationId: { - type: "string", - description: "ID of the organization the team belongs to" - }, - createdAt: { - type: "string", - format: "date-time", - description: "Timestamp when the team was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "Timestamp when the team was last updated" - } - }, - required: [ - "id", - "name", - "organizationId", - "createdAt", - "updatedAt" - ] - } } } - } } - } - } - }, async (ctx) => { - const session = await getSessionFromCtx(ctx); - const organizationId = ctx.body.organizationId || session?.session.activeOrganizationId; - if (!session && (ctx.request || ctx.headers)) throw APIError2.fromStatus("UNAUTHORIZED"); - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const adapter = getOrgAdapter(ctx.context, options); - if (session) { - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION); - if (!await hasPermission({ - role: member.role, - options: ctx.context.orgOptions, - permissions: { team: ["create"] }, - organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION); - } - const existingTeams = await adapter.listTeams(organizationId); - const maximum = typeof ctx.context.orgOptions.teams?.maximumTeams === "function" ? await ctx.context.orgOptions.teams?.maximumTeams({ - organizationId, - session - }, ctx) : ctx.context.orgOptions.teams?.maximumTeams; - if (maximum ? existingTeams.length >= maximum : false) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS); - const { name, organizationId: _, ...additionalFields } = ctx.body; - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - let teamData = { - name, - organizationId, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...additionalFields - }; - if (options?.organizationHooks?.beforeCreateTeam) { - const response = await options?.organizationHooks.beforeCreateTeam({ - team: { - name, - organizationId, - ...additionalFields - }, - user: session?.user, - organization: organization2 - }); - if (response && typeof response === "object" && "data" in response) teamData = { - ...teamData, - ...response.data - }; - } - const createdTeam = await adapter.createTeam(teamData); - if (options?.organizationHooks?.afterCreateTeam) await options?.organizationHooks.afterCreateTeam({ - team: createdTeam, - user: session?.user, - organization: organization2 - }); - return ctx.json(createdTeam); - }); -}; -var removeTeamBodySchema = object({ - teamId: string2().meta({ description: `The team ID of the team to remove. Eg: "team-id"` }), - organizationId: string2().meta({ description: `The organization ID which the team falls under. If not provided, it will default to the user's active organization. Eg: "organization-id"` }).optional() -}); -var removeTeam = (options) => createAuthEndpoint("/organization/remove-team", { - method: "POST", - body: removeTeamBodySchema, - use: [orgMiddleware], - metadata: { openapi: { - description: "Remove a team from an organization", - responses: { "200": { - description: "Team removed successfully", - content: { "application/json": { schema: { - type: "object", - properties: { message: { - type: "string", - description: "Confirmation message indicating successful removal", - enum: ["Team removed successfully."] - } }, - required: ["message"] - } } } - } } - } } -}, async (ctx) => { - const session = await getSessionFromCtx(ctx); - const organizationId = ctx.body.organizationId || session?.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - if (!session && (ctx.request || ctx.headers)) throw APIError2.fromStatus("UNAUTHORIZED"); - const adapter = getOrgAdapter(ctx.context, options); - if (session) { - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member || session.session?.activeTeamId === ctx.body.teamId) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM); - if (!await hasPermission({ - role: member.role, - options: ctx.context.orgOptions, - permissions: { team: ["delete"] }, - organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION); - } - const team = await adapter.findTeamById({ - teamId: ctx.body.teamId, - organizationId - }); - if (!team || team.organizationId !== organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); - if (!ctx.context.orgOptions.teams?.allowRemovingAllTeams) { - if ((await adapter.listTeams(organizationId)).length <= 1) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.UNABLE_TO_REMOVE_LAST_TEAM); - } - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - if (options?.organizationHooks?.beforeDeleteTeam) await options?.organizationHooks.beforeDeleteTeam({ - team, - user: session?.user, - organization: organization2 - }); - await adapter.deleteTeam(team.id); - if (options?.organizationHooks?.afterDeleteTeam) await options?.organizationHooks.afterDeleteTeam({ - team, - user: session?.user, - organization: organization2 - }); - return ctx.json({ message: "Team removed successfully." }); -}); -var updateTeam = (options) => { - const additionalFieldsSchema = toZodSchema({ - fields: options?.schema?.team?.additionalFields ?? {}, - isClientSide: true - }); - return createAuthEndpoint("/organization/update-team", { - method: "POST", - body: object({ - teamId: string2().meta({ description: `The ID of the team to be updated. Eg: "team-id"` }), - data: object({ - ...teamSchema.shape, - ...additionalFieldsSchema.shape - }).partial() - }), - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - description: "Update an existing team in an organization", - responses: { "200": { - description: "Team updated successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - id: { - type: "string", - description: "Unique identifier of the updated team" - }, - name: { - type: "string", - description: "Updated name of the team" - }, - organizationId: { - type: "string", - description: "ID of the organization the team belongs to" - }, - createdAt: { - type: "string", - format: "date-time", - description: "Timestamp when the team was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "Timestamp when the team was last updated" - } - }, - required: [ - "id", - "name", - "organizationId", - "createdAt", - "updatedAt" - ] - } } } - } } - } - } - }, async (ctx) => { - const session = ctx.context.session; - const organizationId = ctx.body.data.organizationId || session.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const adapter = getOrgAdapter(ctx.context, options); - const member = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!member) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM); - if (!await hasPermission({ - role: member.role, - options: ctx.context.orgOptions, - permissions: { team: ["update"] }, - organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM); - const team = await adapter.findTeamById({ - teamId: ctx.body.teamId, - organizationId - }); - if (!team || team.organizationId !== organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); - const { name, organizationId: __, ...additionalFields } = ctx.body.data; - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const updates = { - name, - ...additionalFields - }; - if (options?.organizationHooks?.beforeUpdateTeam) { - const response = await options?.organizationHooks.beforeUpdateTeam({ - team, - updates, - user: session.user, - organization: organization2 - }); - if (response && typeof response === "object" && "data" in response) { - const modifiedUpdates = response.data; - const updatedTeam2 = await adapter.updateTeam(team.id, modifiedUpdates); - if (options?.organizationHooks?.afterUpdateTeam) await options?.organizationHooks.afterUpdateTeam({ - team: updatedTeam2, - user: session.user, - organization: organization2 - }); - return ctx.json(updatedTeam2); - } - } - const updatedTeam = await adapter.updateTeam(team.id, updates); - if (options?.organizationHooks?.afterUpdateTeam) await options?.organizationHooks.afterUpdateTeam({ - team: updatedTeam, - user: session.user, - organization: organization2 - }); - return ctx.json(updatedTeam); - }); -}; -var listOrganizationTeamsQuerySchema = optional(object({ organizationId: string2().meta({ description: `The organization ID which the teams are under to list. Defaults to the users active organization. Eg: "organization-id"` }).optional() })); -var listOrganizationTeams = (options) => createAuthEndpoint("/organization/list-teams", { - method: "GET", - query: listOrganizationTeamsQuerySchema, - metadata: { openapi: { - description: "List all teams in an organization", - responses: { "200": { - description: "Teams retrieved successfully", - content: { "application/json": { schema: { - type: "array", - items: { - type: "object", - properties: { - id: { - type: "string", - description: "Unique identifier of the team" - }, - name: { - type: "string", - description: "Name of the team" - }, - organizationId: { - type: "string", - description: "ID of the organization the team belongs to" - }, - createdAt: { - type: "string", - format: "date-time", - description: "Timestamp when the team was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "Timestamp when the team was last updated" - } - }, - required: [ - "id", - "name", - "organizationId", - "createdAt", - "updatedAt" - ] - }, - description: "Array of team objects within the organization" - } } } - } } - } }, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware] -}, async (ctx) => { - const session = ctx.context.session; - const organizationId = ctx.query?.organizationId || session?.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const adapter = getOrgAdapter(ctx.context, options); - if (!await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId: organizationId || "" - })) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION); - const teams = await adapter.listTeams(organizationId); - return ctx.json(teams); -}); -var setActiveTeamBodySchema = object({ teamId: string2().meta({ description: "The team id to set as active. It can be null to unset the active team" }).nullable().optional() }); -var setActiveTeam = (options) => createAuthEndpoint("/organization/set-active-team", { - method: "POST", - body: setActiveTeamBodySchema, - requireHeaders: true, - use: [orgSessionMiddleware, orgMiddleware], - metadata: { openapi: { - description: "Set the active team", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - description: "The team", - $ref: "#/components/schemas/Team" - } } } - } } - } } -}, async (ctx) => { - const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); - const session = ctx.context.session; - if (ctx.body.teamId === null) { - if (!session.session.activeTeamId) return ctx.json(null); - await setSessionCookie(ctx, { - session: await adapter.setActiveTeam(session.session.token, null, ctx), - user: session.user - }); - return ctx.json(null); - } - let teamId; - if (!ctx.body.teamId) { - const sessionTeamId = session.session.activeTeamId; - if (!sessionTeamId) return ctx.json(null); - else teamId = sessionTeamId; - } else teamId = ctx.body.teamId; - const team = await adapter.findTeamById({ teamId }); - if (!team) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); - if (!await adapter.findTeamMember({ - teamId, - userId: session.user.id - })) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM); - await setSessionCookie(ctx, { - session: await adapter.setActiveTeam(session.session.token, team.id, ctx), - user: session.user - }); - return ctx.json(team); -}); -var listUserTeams = (options) => createAuthEndpoint("/organization/list-user-teams", { - method: "GET", - metadata: { openapi: { - description: "List all teams that the current user is a part of.", - responses: { "200": { - description: "Teams retrieved successfully", - content: { "application/json": { schema: { - type: "array", - items: { - type: "object", - description: "The team", - $ref: "#/components/schemas/Team" - }, - description: "Array of team objects within the organization" - } } } - } } - } }, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware] -}, async (ctx) => { - const session = ctx.context.session; - const teams = await getOrgAdapter(ctx.context, ctx.context.orgOptions).listTeamsByUser({ userId: session.user.id }); - return ctx.json(teams); -}); -var listTeamMembersQuerySchema = optional(object({ teamId: string2().optional().meta({ description: "The team whose members we should return. If this is not provided the members of the current active team get returned." }) })); -var listTeamMembers = (options) => createAuthEndpoint("/organization/list-team-members", { - method: "GET", - query: listTeamMembersQuerySchema, - metadata: { openapi: { - description: "List the members of the given team.", - responses: { "200": { - description: "Teams retrieved successfully", - content: { "application/json": { schema: { - type: "array", - items: { - type: "object", - description: "The team member", - properties: { - id: { - type: "string", - description: "Unique identifier of the team member" - }, - userId: { - type: "string", - description: "The user ID of the team member" - }, - teamId: { - type: "string", - description: "The team ID of the team the team member is in" - }, - createdAt: { - type: "string", - format: "date-time", - description: "Timestamp when the team member was created" - } - }, - required: [ - "id", - "userId", - "teamId", - "createdAt" - ] - }, - description: "Array of team member objects within the team" - } } } - } } - } }, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware] -}, async (ctx) => { - const session = ctx.context.session; - const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); - const teamId = ctx.query?.teamId || session?.session.activeTeamId; - if (!teamId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM); - if (!await adapter.findTeamMember({ - userId: session.user.id, - teamId - })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM); - const members = await adapter.listTeamMembers({ teamId }); - return ctx.json(members); -}); -var addTeamMemberBodySchema = object({ - teamId: string2().meta({ description: "The team the user should be a member of." }), - userId: coerce_exports.string().meta({ description: "The user Id which represents the user to be added as a member." }), - organizationId: string2().meta({ description: "The organization ID which the team falls under. If not provided, it will default to the user's active organization." }).optional() -}); -var addTeamMember = (options) => createAuthEndpoint("/organization/add-team-member", { - method: "POST", - body: addTeamMemberBodySchema, - metadata: { openapi: { - description: "The newly created member", - responses: { "200": { - description: "Team member created successfully", - content: { "application/json": { schema: { - type: "object", - description: "The team member", - properties: { - id: { - type: "string", - description: "Unique identifier of the team member" - }, - userId: { - type: "string", - description: "The user ID of the team member" - }, - teamId: { - type: "string", - description: "The team ID of the team the team member is in" - }, - createdAt: { - type: "string", - format: "date-time", - description: "Timestamp when the team member was created" - } - }, - required: [ - "id", - "userId", - "teamId", - "createdAt" - ] - } } } - } } - } }, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware] -}, async (ctx) => { - const session = ctx.context.session; - const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); - const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const currentMember = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!currentMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - if (!await hasPermission({ - role: currentMember.role, - options: ctx.context.orgOptions, - permissions: { member: ["update"] }, - organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER); - if (!await adapter.findMemberByOrgId({ - userId: ctx.body.userId, - organizationId - })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - const team = await adapter.findTeamById({ - teamId: ctx.body.teamId, - organizationId - }); - if (!team) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const userBeingAdded = await ctx.context.internalAdapter.findUserById(ctx.body.userId); - if (!userBeingAdded) throw APIError2.fromStatus("BAD_REQUEST", { message: "User not found" }); - if (options?.organizationHooks?.beforeAddTeamMember) { - const response = await options?.organizationHooks.beforeAddTeamMember({ - teamMember: { - teamId: ctx.body.teamId, - userId: ctx.body.userId - }, - team, - user: userBeingAdded, - organization: organization2 - }); - if (response && typeof response === "object" && "data" in response) { - } - } - const teamMember = await adapter.findOrCreateTeamMember({ - teamId: ctx.body.teamId, - userId: ctx.body.userId - }); - if (options?.organizationHooks?.afterAddTeamMember) await options?.organizationHooks.afterAddTeamMember({ - teamMember, - team, - user: userBeingAdded, - organization: organization2 - }); - return ctx.json(teamMember); -}); -var removeTeamMemberBodySchema = object({ - teamId: string2().meta({ description: "The team the user should be removed from." }), - userId: coerce_exports.string().meta({ description: "The user which should be removed from the team." }), - organizationId: string2().meta({ description: "The organization ID which the team falls under. If not provided, it will default to the user's active organization." }).optional() -}); -var removeTeamMember = (options) => createAuthEndpoint("/organization/remove-team-member", { - method: "POST", - body: removeTeamMemberBodySchema, - metadata: { openapi: { - description: "Remove a member from a team", - responses: { "200": { - description: "Team member removed successfully", - content: { "application/json": { schema: { - type: "object", - properties: { message: { - type: "string", - description: "Confirmation message indicating successful removal", - enum: ["Team member removed successfully."] - } }, - required: ["message"] - } } } - } } - } }, - requireHeaders: true, - use: [orgMiddleware, orgSessionMiddleware] -}, async (ctx) => { - const session = ctx.context.session; - const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions); - const organizationId = ctx.body.organizationId || session.session.activeOrganizationId; - if (!organizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const currentMember = await adapter.findMemberByOrgId({ - userId: session.user.id, - organizationId - }); - if (!currentMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - if (!await hasPermission({ - role: currentMember.role, - options: ctx.context.orgOptions, - permissions: { member: ["delete"] }, - organizationId - }, ctx)) throw APIError2.from("FORBIDDEN", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER); - if (!await adapter.findMemberByOrgId({ - userId: ctx.body.userId, - organizationId - })) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - const team = await adapter.findTeamById({ - teamId: ctx.body.teamId, - organizationId - }); - if (!team) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND); - const organization2 = await adapter.findOrganizationById(organizationId); - if (!organization2) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND); - const userBeingRemoved = await ctx.context.internalAdapter.findUserById(ctx.body.userId); - if (!userBeingRemoved) throw APIError2.fromStatus("BAD_REQUEST", { message: "User not found" }); - const teamMember = await adapter.findTeamMember({ - teamId: ctx.body.teamId, - userId: ctx.body.userId - }); - if (!teamMember) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM); - if (options?.organizationHooks?.beforeRemoveTeamMember) await options?.organizationHooks.beforeRemoveTeamMember({ - teamMember, - team, - user: userBeingRemoved, - organization: organization2 - }); - await adapter.removeTeamMember({ - teamId: ctx.body.teamId, - userId: ctx.body.userId - }); - if (options?.organizationHooks?.afterRemoveTeamMember) await options?.organizationHooks.afterRemoveTeamMember({ - teamMember, - team, - user: userBeingRemoved, - organization: organization2 - }); - return ctx.json({ message: "Team member removed successfully." }); -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/organization.mjs -init_error2(); -init_zod(); -function parseRoles(roles) { - return Array.isArray(roles) ? roles.join(",") : roles; -} -var createHasPermissionBodySchema = object({ organizationId: string2().optional() }).and(union([object({ - permission: record(string2(), array(string2())), - permissions: _undefined3() -}), object({ - permission: _undefined3(), - permissions: record(string2(), array(string2())) -})])); -var createHasPermission = (options) => { - return createAuthEndpoint("/organization/has-permission", { - method: "POST", - requireHeaders: true, - body: createHasPermissionBodySchema, - use: [orgSessionMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - description: "Check if the user has permission", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - permission: { - type: "object", - description: "The permission to check", - deprecated: true - }, - permissions: { - type: "object", - description: "The permission to check" - } - }, - required: ["permissions"] - } } } }, - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - error: { type: "string" }, - success: { type: "boolean" } - }, - required: ["success"] - } } } - } } - } - } - }, async (ctx) => { - const activeOrganizationId = ctx.body.organizationId || ctx.context.session.session.activeOrganizationId; - if (!activeOrganizationId) throw APIError2.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION); - const member = await getOrgAdapter(ctx.context, options).findMemberByOrgId({ - userId: ctx.context.session.user.id, - organizationId: activeOrganizationId - }); - if (!member) throw APIError2.from("UNAUTHORIZED", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION); - const result = await hasPermission({ - role: member.role, - options, - permissions: ctx.body.permissions, - organizationId: activeOrganizationId - }, ctx); - return ctx.json({ - error: null, - success: result - }); - }); -}; -function organization(options) { - const opts = options || {}; - let endpoints = { - createOrganization: createOrganization(opts), - updateOrganization: updateOrganization(opts), - deleteOrganization: deleteOrganization(opts), - setActiveOrganization: setActiveOrganization(opts), - getFullOrganization: getFullOrganization(opts), - listOrganizations: listOrganizations(opts), - createInvitation: createInvitation(opts), - cancelInvitation: cancelInvitation(opts), - acceptInvitation: acceptInvitation(opts), - getInvitation: getInvitation(opts), - rejectInvitation: rejectInvitation(opts), - listInvitations: listInvitations(opts), - getActiveMember: getActiveMember(opts), - checkOrganizationSlug: checkOrganizationSlug(opts), - addMember: addMember(opts), - removeMember: removeMember(opts), - updateMemberRole: updateMemberRole(opts), - leaveOrganization: leaveOrganization(opts), - listUserInvitations: listUserInvitations(opts), - listMembers: listMembers(opts), - getActiveMemberRole: getActiveMemberRole(opts) - }; - const teamSupport = opts.teams?.enabled; - const teamEndpoints = { - createTeam: createTeam(opts), - listOrganizationTeams: listOrganizationTeams(opts), - removeTeam: removeTeam(opts), - updateTeam: updateTeam(opts), - setActiveTeam: setActiveTeam(opts), - listUserTeams: listUserTeams(opts), - listTeamMembers: listTeamMembers(opts), - addTeamMember: addTeamMember(opts), - removeTeamMember: removeTeamMember(opts) - }; - if (teamSupport) endpoints = { - ...endpoints, - ...teamEndpoints - }; - const dynamicAccessControlEndpoints = { - createOrgRole: createOrgRole(opts), - deleteOrgRole: deleteOrgRole(opts), - listOrgRoles: listOrgRoles(opts), - getOrgRole: getOrgRole(opts), - updateOrgRole: updateOrgRole(opts) - }; - if (opts.dynamicAccessControl?.enabled) endpoints = { - ...endpoints, - ...dynamicAccessControlEndpoints - }; - const roles = { - ...defaultRoles, - ...opts.roles - }; - const teamSchema2 = teamSupport ? { - team: { - modelName: opts.schema?.team?.modelName, - fields: { - name: { - type: "string", - required: true, - fieldName: opts.schema?.team?.fields?.name - }, - organizationId: { - type: "string", - required: true, - references: { - model: "organization", - field: "id" - }, - fieldName: opts.schema?.team?.fields?.organizationId, - index: true - }, - createdAt: { - type: "date", - required: true, - fieldName: opts.schema?.team?.fields?.createdAt - }, - updatedAt: { - type: "date", - required: false, - fieldName: opts.schema?.team?.fields?.updatedAt, - onUpdate: () => /* @__PURE__ */ new Date() - }, - ...opts.schema?.team?.additionalFields || {} - } - }, - teamMember: { - modelName: opts.schema?.teamMember?.modelName, - fields: { - teamId: { - type: "string", - required: true, - references: { - model: "team", - field: "id" - }, - fieldName: opts.schema?.teamMember?.fields?.teamId, - index: true - }, - userId: { - type: "string", - required: true, - references: { - model: "user", - field: "id" - }, - fieldName: opts.schema?.teamMember?.fields?.userId, - index: true - }, - createdAt: { - type: "date", - required: false, - fieldName: opts.schema?.teamMember?.fields?.createdAt - } - } - } - } : {}; - const organizationRoleSchema = opts.dynamicAccessControl?.enabled ? { organizationRole: { - fields: { - organizationId: { - type: "string", - required: true, - references: { - model: "organization", - field: "id" - }, - fieldName: opts.schema?.organizationRole?.fields?.organizationId, - index: true - }, - role: { - type: "string", - required: true, - fieldName: opts.schema?.organizationRole?.fields?.role, - index: true - }, - permission: { - type: "string", - required: true, - fieldName: opts.schema?.organizationRole?.fields?.permission - }, - createdAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - fieldName: opts.schema?.organizationRole?.fields?.createdAt - }, - updatedAt: { - type: "date", - required: false, - fieldName: opts.schema?.organizationRole?.fields?.updatedAt, - onUpdate: () => /* @__PURE__ */ new Date() - }, - ...opts.schema?.organizationRole?.additionalFields || {} - }, - modelName: opts.schema?.organizationRole?.modelName - } } : {}; - const schema3 = { - organization: { - modelName: opts.schema?.organization?.modelName, - fields: { - name: { - type: "string", - required: true, - sortable: true, - fieldName: opts.schema?.organization?.fields?.name - }, - slug: { - type: "string", - required: true, - unique: true, - sortable: true, - fieldName: opts.schema?.organization?.fields?.slug, - index: true - }, - logo: { - type: "string", - required: false, - fieldName: opts.schema?.organization?.fields?.logo - }, - createdAt: { - type: "date", - required: true, - fieldName: opts.schema?.organization?.fields?.createdAt - }, - metadata: { - type: "string", - required: false, - fieldName: opts.schema?.organization?.fields?.metadata - }, - ...opts.schema?.organization?.additionalFields || {} - } - }, - ...organizationRoleSchema, - ...teamSchema2, - member: { - modelName: opts.schema?.member?.modelName, - fields: { - organizationId: { - type: "string", - required: true, - references: { - model: "organization", - field: "id" - }, - fieldName: opts.schema?.member?.fields?.organizationId, - index: true - }, - userId: { - type: "string", - required: true, - fieldName: opts.schema?.member?.fields?.userId, - references: { - model: "user", - field: "id" - }, - index: true - }, - role: { - type: "string", - required: true, - sortable: true, - defaultValue: "member", - fieldName: opts.schema?.member?.fields?.role - }, - createdAt: { - type: "date", - required: true, - fieldName: opts.schema?.member?.fields?.createdAt - }, - ...opts.schema?.member?.additionalFields || {} - } - }, - invitation: { - modelName: opts.schema?.invitation?.modelName, - fields: { - organizationId: { - type: "string", - required: true, - references: { - model: "organization", - field: "id" - }, - fieldName: opts.schema?.invitation?.fields?.organizationId, - index: true - }, - email: { - type: "string", - required: true, - sortable: true, - fieldName: opts.schema?.invitation?.fields?.email, - index: true - }, - role: { - type: "string", - required: false, - sortable: true, - fieldName: opts.schema?.invitation?.fields?.role - }, - ...teamSupport ? { teamId: { - type: "string", - required: false, - sortable: true, - fieldName: opts.schema?.invitation?.fields?.teamId - } } : {}, - status: { - type: "string", - required: true, - sortable: true, - defaultValue: "pending", - fieldName: opts.schema?.invitation?.fields?.status - }, - expiresAt: { - type: "date", - required: true, - fieldName: opts.schema?.invitation?.fields?.expiresAt - }, - createdAt: { - type: "date", - required: true, - fieldName: opts.schema?.invitation?.fields?.createdAt, - defaultValue: () => /* @__PURE__ */ new Date() - }, - inviterId: { - type: "string", - references: { - model: "user", - field: "id" - }, - fieldName: opts.schema?.invitation?.fields?.inviterId, - required: true - }, - ...opts.schema?.invitation?.additionalFields || {} - } - } - }; - return { - id: "organization", - version: PACKAGE_VERSION, - endpoints: { - ...shimContext(endpoints, { - orgOptions: opts, - roles, - getSession: async (context) => { - return await getSessionFromCtx(context); - } - }), - hasPermission: createHasPermission(opts) - }, - schema: { - ...schema3, - session: { fields: { - activeOrganizationId: { - type: "string", - required: false, - fieldName: opts.schema?.session?.fields?.activeOrganizationId - }, - ...teamSupport ? { activeTeamId: { - type: "string", - required: false, - fieldName: opts.schema?.session?.fields?.activeTeamId - } } : {} - } } - }, - $Infer: { - Organization: {}, - Invitation: {}, - Member: {}, - Team: teamSupport ? {} : {}, - TeamMember: teamSupport ? {} : {}, - ActiveOrganization: {} - }, - $ERROR_CODES: ORGANIZATION_ERROR_CODES, - options: opts - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/error-code.mjs -init_error_codes(); -var TWO_FACTOR_ERROR_CODES = defineErrorCodes({ - OTP_NOT_ENABLED: "OTP not enabled", - OTP_HAS_EXPIRED: "OTP has expired", - TOTP_NOT_ENABLED: "TOTP not enabled", - TWO_FACTOR_NOT_ENABLED: "Two factor isn't enabled", - BACKUP_CODES_NOT_ENABLED: "Backup codes aren't enabled", - INVALID_BACKUP_CODE: "Invalid backup code", - INVALID_CODE: "Invalid code", - TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: "Too many attempts. Please request a new code.", - INVALID_TWO_FACTOR_COOKIE: "Invalid two factor cookie" -}); - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/constant.mjs -var TWO_FACTOR_COOKIE_NAME = "two_factor"; -var TRUST_DEVICE_COOKIE_NAME = "trust_device"; -var TRUST_DEVICE_COOKIE_MAX_AGE = 720 * 60 * 60; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/verify-two-factor.mjs -init_error2(); -async function verifyTwoFactor(ctx) { - const invalid = (errorKey) => { - throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES[errorKey]); - }; - const session = await getSessionFromCtx(ctx); - if (!session) { - const twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME); - const signedTwoFactorCookie = await ctx.getSignedCookie(twoFactorCookie.name, ctx.context.secret); - if (!signedTwoFactorCookie) throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE); - const verificationToken = await ctx.context.internalAdapter.findVerificationValue(signedTwoFactorCookie); - if (!verificationToken) throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE); - const user = await ctx.context.internalAdapter.findUserById(verificationToken.value); - if (!user) throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE); - const dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); - return { - valid: async (ctx2) => { - const session2 = await ctx2.context.internalAdapter.createSession(verificationToken.value, !!dontRememberMe); - if (!session2) throw APIError2.from("INTERNAL_SERVER_ERROR", { - message: "failed to create session", - code: "FAILED_TO_CREATE_SESSION" - }); - await ctx2.context.internalAdapter.deleteVerificationByIdentifier(signedTwoFactorCookie); - await setSessionCookie(ctx2, { - session: session2, - user - }); - expireCookie(ctx2, twoFactorCookie); - if (ctx2.body.trustDevice) { - const maxAge = ctx2.context.getPlugin("two-factor").options?.trustDeviceMaxAge ?? 2592e3; - const trustDeviceCookie = ctx2.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge }); - const trustIdentifier = `trust-device-${generateRandomString(32)}`; - const token = await createHMAC("SHA-256", "base64urlnopad").sign(ctx2.context.secret, `${user.id}!${trustIdentifier}`); - await ctx2.context.internalAdapter.createVerificationValue({ - value: user.id, - identifier: trustIdentifier, - expiresAt: new Date(Date.now() + maxAge * 1e3) - }); - await ctx2.setSignedCookie(trustDeviceCookie.name, `${token}!${trustIdentifier}`, ctx2.context.secret, trustDeviceCookie.attributes); - expireCookie(ctx2, ctx2.context.authCookies.dontRememberToken); - } - return ctx2.json({ - token: session2.token, - user: parseUserOutput(ctx2.context.options, user) - }); - }, - invalid, - session: { - session: null, - user - }, - key: signedTwoFactorCookie - }; - } - return { - valid: async (ctx2) => { - return ctx2.json({ - token: session.session.token, - user: parseUserOutput(ctx2.context.options, session.user) - }); - }, - invalid, - session, - key: `${session.user.id}!${session.session.id}` - }; -} - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/backup-codes/index.mjs -init_error2(); -init_json(); -init_zod(); -function generateBackupCodesFn(options) { - return Array.from({ length: options?.amount ?? 10 }).fill(null).map(() => generateRandomString(options?.length ?? 10, "a-z", "0-9", "A-Z")).map((code) => `${code.slice(0, 5)}-${code.slice(5)}`); -} -async function generateBackupCodes(secret, options) { - const backupCodes = options?.customBackupCodesGenerate ? options.customBackupCodesGenerate() : generateBackupCodesFn(options); - if (options?.storeBackupCodes === "encrypted") return { - backupCodes, - encryptedBackupCodes: await symmetricEncrypt({ - data: JSON.stringify(backupCodes), - key: secret - }) - }; - if (typeof options?.storeBackupCodes === "object" && "encrypt" in options?.storeBackupCodes) return { - backupCodes, - encryptedBackupCodes: await options?.storeBackupCodes.encrypt(JSON.stringify(backupCodes)) - }; - return { - backupCodes, - encryptedBackupCodes: JSON.stringify(backupCodes) - }; -} -async function verifyBackupCode(data, key, options) { - const codes = await getBackupCodes(data.backupCodes, key, options); - if (!codes) return { - status: false, - updated: null - }; - return { - status: codes.includes(data.code), - updated: codes.filter((code) => code !== data.code) - }; -} -async function getBackupCodes(backupCodes, key, options) { - if (options?.storeBackupCodes === "encrypted") return safeJSONParse(await symmetricDecrypt({ - key, - data: backupCodes - })); - if (typeof options?.storeBackupCodes === "object" && "decrypt" in options?.storeBackupCodes) return safeJSONParse(await options?.storeBackupCodes.decrypt(backupCodes)); - return safeJSONParse(backupCodes); -} -var verifyBackupCodeBodySchema = object({ - code: string2().meta({ description: `A backup code to verify. Eg: "123456"` }), - disableSession: boolean2().meta({ description: "If true, the session cookie will not be set." }).optional(), - trustDevice: boolean2().meta({ description: "If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true" }).optional() -}); -var viewBackupCodesBodySchema = object({ userId: coerce_exports.string().meta({ description: `The user ID to view all backup codes. Eg: "user-id"` }) }); -var backupCode2fa = (opts) => { - const twoFactorTable = "twoFactor"; - const passwordSchema = string2().meta({ description: "The users password." }); - const generateBackupCodesBodySchema = opts.allowPasswordless ? object({ password: passwordSchema.optional() }) : object({ password: passwordSchema }); - return { - id: "backup_code", - version: PACKAGE_VERSION, - endpoints: { - verifyBackupCode: createAuthEndpoint("/two-factor/verify-backup-code", { - method: "POST", - body: verifyBackupCodeBodySchema, - metadata: { openapi: { - description: "Verify a backup code for two-factor authentication", - responses: { "200": { - description: "Backup code verified successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - user: { - type: "object", - properties: { - id: { - type: "string", - description: "Unique identifier of the user" - }, - email: { - type: "string", - format: "email", - nullable: true, - description: "User's email address" - }, - emailVerified: { - type: "boolean", - nullable: true, - description: "Whether the email is verified" - }, - name: { - type: "string", - nullable: true, - description: "User's name" - }, - image: { - type: "string", - format: "uri", - nullable: true, - description: "User's profile image URL" - }, - twoFactorEnabled: { - type: "boolean", - description: "Whether two-factor authentication is enabled for the user" - }, - createdAt: { - type: "string", - format: "date-time", - description: "Timestamp when the user was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "Timestamp when the user was last updated" - } - }, - required: [ - "id", - "twoFactorEnabled", - "createdAt", - "updatedAt" - ], - description: "The authenticated user object with two-factor details" - }, - session: { - type: "object", - properties: { - token: { - type: "string", - description: "Session token" - }, - userId: { - type: "string", - description: "ID of the user associated with the session" - }, - createdAt: { - type: "string", - format: "date-time", - description: "Timestamp when the session was created" - }, - expiresAt: { - type: "string", - format: "date-time", - description: "Timestamp when the session expires" - } - }, - required: [ - "token", - "userId", - "createdAt", - "expiresAt" - ], - description: "The current session object, included unless disableSession is true" - } - }, - required: ["user", "session"] - } } } - } } - } } - }, async (ctx) => { - const { session, valid } = await verifyTwoFactor(ctx); - const user = session.user; - const twoFactor2 = await ctx.context.adapter.findOne({ - model: twoFactorTable, - where: [{ - field: "userId", - value: user.id - }] - }); - if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED); - const validate = await verifyBackupCode({ - backupCodes: twoFactor2.backupCodes, - code: ctx.body.code - }, ctx.context.secretConfig, opts); - if (!validate.status) throw APIError2.from("UNAUTHORIZED", TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE); - const updatedBackupCodes = await symmetricEncrypt({ - key: ctx.context.secretConfig, - data: JSON.stringify(validate.updated) - }); - if (!await ctx.context.adapter.update({ - model: twoFactorTable, - update: { backupCodes: updatedBackupCodes }, - where: [{ - field: "id", - value: twoFactor2.id - }, { - field: "backupCodes", - value: twoFactor2.backupCodes - }] - })) throw APIError2.fromStatus("CONFLICT", { message: "Failed to verify backup code. Please try again." }); - if (!ctx.body.disableSession) return valid(ctx); - return ctx.json({ - token: session.session?.token, - user: parseUserOutput(ctx.context.options, session.user) - }); - }), - generateBackupCodes: createAuthEndpoint("/two-factor/generate-backup-codes", { - method: "POST", - body: generateBackupCodesBodySchema, - use: [sessionMiddleware], - metadata: { openapi: { - description: "Generate new backup codes for two-factor authentication", - responses: { "200": { - description: "Backup codes generated successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - status: { - type: "boolean", - description: "Indicates if the backup codes were generated successfully", - enum: [true] - }, - backupCodes: { - type: "array", - items: { type: "string" }, - description: "Array of generated backup codes in plain text" - } - }, - required: ["status", "backupCodes"] - } } } - } } - } } - }, async (ctx) => { - const user = ctx.context.session.user; - if (!user.twoFactorEnabled) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED); - if (await shouldRequirePassword(ctx, user.id, opts.allowPasswordless)) { - if (!ctx.body.password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - await ctx.context.password.checkPassword(user.id, ctx); - } - const twoFactor2 = await ctx.context.adapter.findOne({ - model: twoFactorTable, - where: [{ - field: "userId", - value: user.id - }] - }); - if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED); - const backupCodes = await generateBackupCodes(ctx.context.secretConfig, opts); - await ctx.context.adapter.update({ - model: twoFactorTable, - update: { backupCodes: backupCodes.encryptedBackupCodes }, - where: [{ - field: "id", - value: twoFactor2.id - }] - }); - return ctx.json({ - status: true, - backupCodes: backupCodes.backupCodes - }); - }), - viewBackupCodes: createAuthEndpoint({ - method: "POST", - body: viewBackupCodesBodySchema - }, async (ctx) => { - const twoFactor2 = await ctx.context.adapter.findOne({ - model: twoFactorTable, - where: [{ - field: "userId", - value: ctx.body.userId - }] - }); - if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED); - const decryptedBackupCodes = await getBackupCodes(twoFactor2.backupCodes, ctx.context.secretConfig, opts); - if (!decryptedBackupCodes) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE); - return ctx.json({ - status: true, - backupCodes: decryptedBackupCodes - }); - }) - } - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/utils.mjs -var defaultKeyHasher2 = async (token) => { - const hash2 = await createHash("SHA-256").digest(new TextEncoder().encode(token)); - return base64Url.encode(new Uint8Array(hash2), { padding: false }); -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/otp/index.mjs -init_error2(); -init_zod(); -var verifyOTPBodySchema = object({ - code: string2().meta({ description: 'The otp code to verify. Eg: "012345"' }), - trustDevice: boolean2().optional().meta({ description: "If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true" }) -}); -var send2FaOTPBodySchema = object({ trustDevice: boolean2().optional().meta({ description: "If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true" }) }).optional(); -var otp2fa = (options) => { - const opts = { - storeOTP: "plain", - digits: 6, - ...options, - period: (options?.period || 3) * 60 * 1e3 - }; - async function storeOTP(ctx, otp) { - if (opts.storeOTP === "hashed") return await defaultKeyHasher2(otp); - if (typeof opts.storeOTP === "object" && "hash" in opts.storeOTP) return await opts.storeOTP.hash(otp); - if (typeof opts.storeOTP === "object" && "encrypt" in opts.storeOTP) return await opts.storeOTP.encrypt(otp); - if (opts.storeOTP === "encrypted") return await symmetricEncrypt({ - key: ctx.context.secretConfig, - data: otp - }); - return otp; - } - async function decryptOrHashForComparison(ctx, storedOtp, userInput) { - if (opts.storeOTP === "hashed") return [storedOtp, await defaultKeyHasher2(userInput)]; - if (opts.storeOTP === "encrypted") return [await symmetricDecrypt({ - key: ctx.context.secretConfig, - data: storedOtp - }), userInput]; - if (typeof opts.storeOTP === "object" && "encrypt" in opts.storeOTP) return [await opts.storeOTP.decrypt(storedOtp), userInput]; - if (typeof opts.storeOTP === "object" && "hash" in opts.storeOTP) return [storedOtp, await opts.storeOTP.hash(userInput)]; - return [storedOtp, userInput]; - } - return { - id: "otp", - version: PACKAGE_VERSION, - endpoints: { - sendTwoFactorOTP: createAuthEndpoint("/two-factor/send-otp", { - method: "POST", - body: send2FaOTPBodySchema, - metadata: { openapi: { - summary: "Send two factor OTP", - description: "Send two factor OTP to the user", - responses: { 200: { - description: "Successful response", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } } - }, async (ctx) => { - if (!options || !options.sendOTP) { - ctx.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."); - throw APIError2.from("BAD_REQUEST", { - message: "otp isn't configured", - code: "OTP_NOT_CONFIGURED" - }); - } - const { session, key } = await verifyTwoFactor(ctx); - const code = generateRandomString(opts.digits, "0-9"); - const hashedCode = await storeOTP(ctx, code); - await ctx.context.internalAdapter.createVerificationValue({ - value: `${hashedCode}:0`, - identifier: `2fa-otp-${key}`, - expiresAt: new Date(Date.now() + opts.period) - }); - const sendOTPResult = options.sendOTP({ - user: session.user, - otp: code - }, ctx); - if (sendOTPResult instanceof Promise) await ctx.context.runInBackgroundOrAwait(sendOTPResult.catch((e) => { - ctx.context.logger.error("Failed to send two-factor OTP", e); - })); - return ctx.json({ status: true }); - }), - verifyTwoFactorOTP: createAuthEndpoint("/two-factor/verify-otp", { - method: "POST", - body: verifyOTPBodySchema, - metadata: { openapi: { - summary: "Verify two factor OTP", - description: "Verify two factor OTP", - responses: { "200": { - description: "Two-factor OTP verified successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - token: { - type: "string", - description: "Session token for the authenticated session" - }, - user: { - type: "object", - properties: { - id: { - type: "string", - description: "Unique identifier of the user" - }, - email: { - type: "string", - format: "email", - nullable: true, - description: "User's email address" - }, - emailVerified: { - type: "boolean", - nullable: true, - description: "Whether the email is verified" - }, - name: { - type: "string", - nullable: true, - description: "User's name" - }, - image: { - type: "string", - format: "uri", - nullable: true, - description: "User's profile image URL" - }, - createdAt: { - type: "string", - format: "date-time", - description: "Timestamp when the user was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "Timestamp when the user was last updated" - } - }, - required: [ - "id", - "createdAt", - "updatedAt" - ], - description: "The authenticated user object" - } - }, - required: ["token", "user"] - } } } - } } - } } - }, async (ctx) => { - const { session, key, valid, invalid } = await verifyTwoFactor(ctx); - const toCheckOtp = await ctx.context.internalAdapter.findVerificationValue(`2fa-otp-${key}`); - const [otp, counter] = toCheckOtp?.value?.split(":") ?? []; - if (!toCheckOtp || toCheckOtp.expiresAt < /* @__PURE__ */ new Date()) { - if (toCheckOtp) await ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`); - throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.OTP_HAS_EXPIRED); - } - const allowedAttempts = options?.allowedAttempts || 5; - if (parseInt(counter) >= allowedAttempts) { - await ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`); - throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE); - } - const [storedValue, inputValue] = await decryptOrHashForComparison(ctx, otp, ctx.body.code); - if (constantTimeEqual(new TextEncoder().encode(storedValue), new TextEncoder().encode(inputValue))) { - if (!session.user.twoFactorEnabled) { - if (!session.session) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION); - const updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { twoFactorEnabled: true }); - const newSession = await ctx.context.internalAdapter.createSession(session.user.id, false, session.session); - await setSessionCookie(ctx, { - session: newSession, - user: updatedUser - }); - await ctx.context.internalAdapter.deleteSession(session.session.token); - return ctx.json({ - token: newSession.token, - user: parseUserOutput(ctx.context.options, updatedUser) - }); - } - return valid(ctx); - } else { - await ctx.context.internalAdapter.updateVerificationByIdentifier(`2fa-otp-${key}`, { value: `${otp}:${(parseInt(counter, 10) || 0) + 1}` }); - return invalid("INVALID_CODE"); - } - }) - } - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/schema.mjs -var schema2 = { - user: { fields: { twoFactorEnabled: { - type: "boolean", - required: false, - defaultValue: false, - input: false - } } }, - twoFactor: { fields: { - secret: { - type: "string", - required: true, - returned: false, - index: true - }, - backupCodes: { - type: "string", - required: true, - returned: false - }, - userId: { - type: "string", - required: true, - returned: false, - references: { - model: "user", - field: "id" - }, - index: true - }, - verified: { - type: "boolean", - required: false, - defaultValue: true, - input: false - } - } } -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/totp/index.mjs -init_error2(); -init_zod(); - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/base32.mjs -function getAlphabet2(hex4) { - return hex4 ? "0123456789ABCDEFGHIJKLMNOPQRSTUV" : "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; -} -function createDecodeMap(alphabet) { - const decodeMap = /* @__PURE__ */ new Map(); - for (let i = 0; i < alphabet.length; i++) { - decodeMap.set(alphabet[i], i); - } - return decodeMap; -} -function base32Encode(data, alphabet, padding) { - let result = ""; - let buffer = 0; - let shift = 0; - for (const byte of data) { - buffer = buffer << 8 | byte; - shift += 8; - while (shift >= 5) { - shift -= 5; - result += alphabet[buffer >> shift & 31]; - } - } - if (shift > 0) { - result += alphabet[buffer << 5 - shift & 31]; - } - if (padding) { - const padCount = (8 - result.length % 8) % 8; - result += "=".repeat(padCount); - } - return result; -} -function base32Decode(data, alphabet) { - const decodeMap = createDecodeMap(alphabet); - const result = []; - let buffer = 0; - let bitsCollected = 0; - for (const char of data) { - if (char === "=") - break; - const value = decodeMap.get(char); - if (value === void 0) { - throw new Error(`Invalid Base32 character: ${char}`); - } - buffer = buffer << 5 | value; - bitsCollected += 5; - while (bitsCollected >= 8) { - bitsCollected -= 8; - result.push(buffer >> bitsCollected & 255); - } - } - return Uint8Array.from(result); -} -var base32 = { - /** - * Encodes data into a Base32 string. - * @param data - The data to encode (ArrayBuffer, TypedArray, or string). - * @param options - Encoding options. - * @returns The Base32 encoded string. - */ - encode(data, options = {}) { - const alphabet = getAlphabet2(false); - const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data); - return base32Encode(buffer, alphabet, options.padding ?? true); - }, - /** - * Decodes a Base32 string into a Uint8Array. - * @param data - The Base32 encoded string or ArrayBuffer/TypedArray. - * @returns The decoded Uint8Array. - */ - decode(data) { - if (typeof data !== "string") { - data = new TextDecoder().decode(data); - } - const alphabet = getAlphabet2(false); - return base32Decode(data, alphabet); - } -}; - -// ../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/otp.mjs -var defaultPeriod = 30; -var defaultDigits = 6; -async function generateHOTP(secret, { - counter, - digits, - hash: hash2 = "SHA-1" -}) { - const _digits = digits ?? defaultDigits; - if (_digits < 1 || _digits > 8) { - throw new TypeError("Digits must be between 1 and 8"); - } - const buffer = new ArrayBuffer(8); - new DataView(buffer).setBigUint64(0, BigInt(counter), false); - const bytes = new Uint8Array(buffer); - const hmacResult = new Uint8Array(await createHMAC(hash2).sign(secret, bytes)); - const offset = hmacResult[hmacResult.length - 1] & 15; - const truncated = (hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255; - const otp = truncated % 10 ** _digits; - return otp.toString().padStart(_digits, "0"); -} -async function generateTOTP(secret, options) { - const digits = options?.digits ?? defaultDigits; - const period = options?.period ?? defaultPeriod; - const milliseconds = period * 1e3; - const counter = Math.floor(Date.now() / milliseconds); - return await generateHOTP(secret, { counter, digits, hash: options?.hash }); -} -async function verifyTOTP(otp, { - window: window2 = 1, - digits = defaultDigits, - secret, - period = defaultPeriod -}) { - const milliseconds = period * 1e3; - const counter = Math.floor(Date.now() / milliseconds); - for (let i = -window2; i <= window2; i++) { - const generatedOTP = await generateHOTP(secret, { - counter: counter + i, - digits - }); - if (otp === generatedOTP) { - return true; - } - } - return false; -} -function generateQRCode({ - issuer, - account, - secret, - digits = defaultDigits, - period = defaultPeriod -}) { - const encodedIssuer = encodeURIComponent(issuer); - const encodedAccountName = encodeURIComponent(account); - const baseURI = `otpauth://totp/${encodedIssuer}:${encodedAccountName}`; - const params = new URLSearchParams({ - secret: base32.encode(secret, { - padding: false - }), - issuer - }); - if (digits !== void 0) { - params.set("digits", digits.toString()); - } - if (period !== void 0) { - params.set("period", period.toString()); - } - return `${baseURI}?${params.toString()}`; -} -var createOTP = (secret, opts) => { - const digits = opts?.digits ?? defaultDigits; - const period = opts?.period ?? defaultPeriod; - return { - hotp: (counter) => generateHOTP(secret, { counter, digits }), - totp: () => generateTOTP(secret, { digits, period }), - verify: (otp, options) => verifyTOTP(otp, { secret, digits, period, ...options }), - url: (issuer, account) => generateQRCode({ issuer, account, secret, digits, period }) - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/totp/index.mjs -var generateTOTPBodySchema = object({ secret: string2().meta({ description: "The secret to generate the TOTP code" }) }); -var verifyTOTPBodySchema = object({ - code: string2().meta({ description: 'The otp code to verify. Eg: "012345"' }), - trustDevice: boolean2().meta({ description: "If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true" }).optional() -}); -var totp2fa = (options) => { - const opts = { - ...options, - digits: options?.digits || 6, - period: options?.period || 30 - }; - const passwordSchema = string2().meta({ description: "User password" }); - const getTOTPURIBodySchema = options?.allowPasswordless ? object({ password: passwordSchema.optional() }) : object({ password: passwordSchema }); - const twoFactorTable = "twoFactor"; - return { - id: "totp", - version: PACKAGE_VERSION, - endpoints: { - generateTOTP: createAuthEndpoint({ - method: "POST", - body: generateTOTPBodySchema, - metadata: { openapi: { - summary: "Generate TOTP code", - description: "Use this endpoint to generate a TOTP code", - responses: { 200: { - description: "Successful response", - content: { "application/json": { schema: { - type: "object", - properties: { code: { type: "string" } } - } } } - } } - } } - }, async (ctx) => { - if (options?.disable) { - ctx.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"); - throw APIError2.from("BAD_REQUEST", { - message: "totp isn't configured", - code: "TOTP_NOT_CONFIGURED" - }); - } - return { code: await createOTP(ctx.body.secret, { - period: opts.period, - digits: opts.digits - }).totp() }; - }), - getTOTPURI: createAuthEndpoint("/two-factor/get-totp-uri", { - method: "POST", - use: [sessionMiddleware], - body: getTOTPURIBodySchema, - metadata: { openapi: { - summary: "Get TOTP URI", - description: "Use this endpoint to get the TOTP URI", - responses: { 200: { - description: "Successful response", - content: { "application/json": { schema: { - type: "object", - properties: { totpURI: { type: "string" } } - } } } - } } - } } - }, async (ctx) => { - if (options?.disable) { - ctx.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"); - throw APIError2.from("BAD_REQUEST", { - message: "totp isn't configured", - code: "TOTP_NOT_CONFIGURED" - }); - } - const user = ctx.context.session.user; - const twoFactor2 = await ctx.context.adapter.findOne({ - model: twoFactorTable, - where: [{ - field: "userId", - value: user.id - }] - }); - if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED); - const secret = await symmetricDecrypt({ - key: ctx.context.secretConfig, - data: twoFactor2.secret - }); - if (await shouldRequirePassword(ctx, user.id, options?.allowPasswordless)) { - if (!ctx.body.password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - await ctx.context.password.checkPassword(user.id, ctx); - } - return { totpURI: createOTP(secret, { - digits: opts.digits, - period: opts.period - }).url(options?.issuer || ctx.context.appName, user.email) }; - }), - verifyTOTP: createAuthEndpoint("/two-factor/verify-totp", { - method: "POST", - body: verifyTOTPBodySchema, - metadata: { openapi: { - summary: "Verify two factor TOTP", - description: "Verify two factor TOTP", - responses: { 200: { - description: "Successful response", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } } - }, async (ctx) => { - if (options?.disable) { - ctx.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"); - throw APIError2.from("BAD_REQUEST", { - message: "totp isn't configured", - code: "TOTP_NOT_CONFIGURED" - }); - } - const { session, valid, invalid } = await verifyTwoFactor(ctx); - const user = session.user; - const isSignIn = !session.session; - const twoFactor2 = await ctx.context.adapter.findOne({ - model: twoFactorTable, - where: [{ - field: "userId", - value: user.id - }] - }); - if (!twoFactor2) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED); - if (isSignIn && twoFactor2.verified === false) throw APIError2.from("BAD_REQUEST", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED); - if (!await createOTP(await symmetricDecrypt({ - key: ctx.context.secretConfig, - data: twoFactor2.secret - }), { - period: opts.period, - digits: opts.digits - }).verify(ctx.body.code)) return invalid("INVALID_CODE"); - if (twoFactor2.verified !== true) { - if (!user.twoFactorEnabled) { - const activeSession = session.session; - const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: true }); - await setSessionCookie(ctx, { - session: await ctx.context.internalAdapter.createSession(user.id, false, activeSession), - user: updatedUser - }); - await ctx.context.internalAdapter.deleteSession(activeSession.token); - } - await ctx.context.adapter.update({ - model: twoFactorTable, - update: { verified: true }, - where: [{ - field: "id", - value: twoFactor2.id - }] - }); - } - return valid(ctx); - }) - } - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/index.mjs -init_error2(); -init_zod(); -var twoFactor = (options) => { - const opts = { twoFactorTable: "twoFactor" }; - const trustDeviceMaxAge = options?.trustDeviceMaxAge ?? 2592e3; - const allowPasswordless = options?.allowPasswordless; - const backupCodeOptions = { - storeBackupCodes: "encrypted", - ...options?.backupCodeOptions - }; - const totp = totp2fa({ - ...options?.totpOptions, - allowPasswordless: options?.totpOptions?.allowPasswordless ?? allowPasswordless - }); - const backupCode = backupCode2fa({ - ...backupCodeOptions, - allowPasswordless: options?.backupCodeOptions?.allowPasswordless ?? allowPasswordless - }); - const otp = otp2fa(options?.otpOptions); - const passwordSchema = string2().meta({ description: "User password" }); - const enableTwoFactorBodySchema = allowPasswordless ? object({ - password: passwordSchema.optional(), - issuer: string2().meta({ description: "Custom issuer for the TOTP URI" }).optional() - }) : object({ - password: passwordSchema, - issuer: string2().meta({ description: "Custom issuer for the TOTP URI" }).optional() - }); - const disableTwoFactorBodySchema = allowPasswordless ? object({ password: passwordSchema.optional() }) : object({ password: passwordSchema }); - return { - id: "two-factor", - version: PACKAGE_VERSION, - endpoints: { - ...totp.endpoints, - ...otp.endpoints, - ...backupCode.endpoints, - enableTwoFactor: createAuthEndpoint("/two-factor/enable", { - method: "POST", - body: enableTwoFactorBodySchema, - use: [sessionMiddleware], - metadata: { openapi: { - summary: "Enable two factor authentication", - description: "Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.", - responses: { 200: { - description: "Successful response", - content: { "application/json": { schema: { - type: "object", - properties: { - totpURI: { - type: "string", - description: "TOTP URI" - }, - backupCodes: { - type: "array", - items: { type: "string" }, - description: "Backup codes" - } - } - } } } - } } - } } - }, async (ctx) => { - const user = ctx.context.session.user; - const { password, issuer } = ctx.body; - if (await shouldRequirePassword(ctx, user.id, allowPasswordless)) { - if (!password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - if (!await validatePassword(ctx, { - password, - userId: user.id - })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - } - const secret = generateRandomString(32); - const encryptedSecret = await symmetricEncrypt({ - key: ctx.context.secretConfig, - data: secret - }); - const backupCodes = await generateBackupCodes(ctx.context.secretConfig, backupCodeOptions); - if (options?.skipVerificationOnEnable) { - const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: true }); - await setSessionCookie(ctx, { - session: await ctx.context.internalAdapter.createSession(updatedUser.id, false, ctx.context.session.session), - user: updatedUser - }); - await ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token); - } - const existingTwoFactor = await ctx.context.adapter.findOne({ - model: opts.twoFactorTable, - where: [{ - field: "userId", - value: user.id - }] - }); - await ctx.context.adapter.deleteMany({ - model: opts.twoFactorTable, - where: [{ - field: "userId", - value: user.id - }] - }); - await ctx.context.adapter.create({ - model: opts.twoFactorTable, - data: { - secret: encryptedSecret, - backupCodes: backupCodes.encryptedBackupCodes, - userId: user.id, - verified: existingTwoFactor != null && existingTwoFactor.verified !== false || !!options?.skipVerificationOnEnable - } - }); - const totpURI = createOTP(secret, { - digits: options?.totpOptions?.digits || 6, - period: options?.totpOptions?.period - }).url(issuer || options?.issuer || ctx.context.appName, user.email); - return ctx.json({ - totpURI, - backupCodes: backupCodes.backupCodes - }); - }), - disableTwoFactor: createAuthEndpoint("/two-factor/disable", { - method: "POST", - body: disableTwoFactorBodySchema, - use: [sessionMiddleware], - metadata: { openapi: { - summary: "Disable two factor authentication", - description: "Use this endpoint to disable two factor authentication.", - responses: { 200: { - description: "Successful response", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } } - }, async (ctx) => { - const user = ctx.context.session.user; - const { password } = ctx.body; - if (await shouldRequirePassword(ctx, user.id, allowPasswordless)) { - if (!password) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - if (!await validatePassword(ctx, { - password, - userId: user.id - })) throw APIError2.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_PASSWORD); - } - const updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: false }); - await ctx.context.adapter.delete({ - model: opts.twoFactorTable, - where: [{ - field: "userId", - value: updatedUser.id - }] - }); - await setSessionCookie(ctx, { - session: await ctx.context.internalAdapter.createSession(updatedUser.id, false, ctx.context.session.session), - user: updatedUser - }); - await ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token); - const disableTrustCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge }); - const disableTrustValue = await ctx.getSignedCookie(disableTrustCookie.name, ctx.context.secret); - if (disableTrustValue) { - const [, trustId] = disableTrustValue.split("!"); - if (trustId) await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustId); - expireCookie(ctx, disableTrustCookie); - } - return ctx.json({ status: true }); - }) - }, - options, - hooks: { after: [{ - matcher(context) { - return context.path === "/sign-in/email" || context.path === "/sign-in/username" || context.path === "/sign-in/phone-number"; - }, - handler: createAuthMiddleware(async (ctx) => { - const data = ctx.context.newSession; - if (!data) return; - if (!data?.user.twoFactorEnabled) return; - const trustDeviceCookieAttrs = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge }); - const trustDeviceCookie = await ctx.getSignedCookie(trustDeviceCookieAttrs.name, ctx.context.secret); - if (trustDeviceCookie) { - const [token, trustIdentifier] = trustDeviceCookie.split("!"); - if (token && trustIdentifier) { - if (token === await createHMAC("SHA-256", "base64urlnopad").sign(ctx.context.secret, `${data.user.id}!${trustIdentifier}`)) { - const verificationRecord = await ctx.context.internalAdapter.findVerificationValue(trustIdentifier); - if (verificationRecord && verificationRecord.value === data.user.id && verificationRecord.expiresAt > /* @__PURE__ */ new Date()) { - await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustIdentifier); - const newTrustIdentifier = `trust-device-${generateRandomString(32)}`; - const newToken = await createHMAC("SHA-256", "base64urlnopad").sign(ctx.context.secret, `${data.user.id}!${newTrustIdentifier}`); - await ctx.context.internalAdapter.createVerificationValue({ - value: data.user.id, - identifier: newTrustIdentifier, - expiresAt: new Date(Date.now() + trustDeviceMaxAge * 1e3) - }); - const newTrustDeviceCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge }); - await ctx.setSignedCookie(newTrustDeviceCookie.name, `${newToken}!${newTrustIdentifier}`, ctx.context.secret, trustDeviceCookieAttrs.attributes); - return; - } - } - } - expireCookie(ctx, trustDeviceCookieAttrs); - } - deleteSessionCookie(ctx, true); - await ctx.context.internalAdapter.deleteSession(data.session.token); - const maxAge = options?.twoFactorCookieMaxAge ?? 600; - const twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME, { maxAge }); - const identifier = `2fa-${generateRandomString(20)}`; - await ctx.context.internalAdapter.createVerificationValue({ - value: data.user.id, - identifier, - expiresAt: new Date(Date.now() + maxAge * 1e3) - }); - await ctx.setSignedCookie(twoFactorCookie.name, identifier, ctx.context.secret, twoFactorCookie.attributes); - const twoFactorMethods = []; - if (!options?.totpOptions?.disable) { - const userTotpSecret = await ctx.context.adapter.findOne({ - model: opts.twoFactorTable, - where: [{ - field: "userId", - value: data.user.id - }] - }); - if (userTotpSecret && userTotpSecret.verified !== false) twoFactorMethods.push("totp"); - } - if (options?.otpOptions?.sendOTP) twoFactorMethods.push("otp"); - return ctx.json({ - twoFactorRedirect: true, - twoFactorMethods - }); - }) - }] }, - schema: mergeSchema(schema2, { - ...options?.schema, - twoFactor: { - ...options?.schema?.twoFactor, - ...options?.twoFactorTable ? { modelName: options.twoFactorTable } : {} - } - }), - rateLimit: [{ - pathMatcher(path3) { - return path3.startsWith("/two-factor/"); - }, - window: 10, - max: 3 - }], - $ERROR_CODES: TWO_FACTOR_ERROR_CODES - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/magic-link/utils.mjs -var defaultKeyHasher3 = async (otp) => { - const hash2 = await createHash("SHA-256").digest(new TextEncoder().encode(otp)); - return base64Url.encode(new Uint8Array(hash2), { padding: false }); -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/magic-link/index.mjs -init_zod(); -var signInMagicLinkBodySchema = object({ - email: email2().meta({ description: "Email address to send the magic link" }), - name: string2().meta({ description: 'User display name. Only used if the user is registering for the first time. Eg: "my-name"' }).optional(), - callbackURL: string2().meta({ description: "URL to redirect after magic link verification" }).optional(), - newUserCallbackURL: string2().meta({ description: "URL to redirect after new user signup. Only used if the user is registering for the first time." }).optional(), - errorCallbackURL: string2().meta({ description: "URL to redirect after error." }).optional(), - metadata: record(string2(), any()).meta({ description: "Additional metadata to pass to sendMagicLink." }).optional() -}); -var magicLinkVerifyQuerySchema = object({ - token: string2().meta({ description: "Verification token" }), - callbackURL: string2().meta({ description: 'URL to redirect after magic link verification, if not provided the user will be redirected to the root URL. Eg: "/dashboard"' }).optional(), - errorCallbackURL: string2().meta({ description: "URL to redirect after error." }).optional(), - newUserCallbackURL: string2().meta({ description: "URL to redirect after new user signup. Only used if the user is registering for the first time." }).optional() -}); -var magicLink = (options) => { - const opts = { - storeToken: "plain", - allowedAttempts: 1, - ...options - }; - async function storeToken(ctx, token) { - if (opts.storeToken === "hashed") return await defaultKeyHasher3(token); - if (typeof opts.storeToken === "object" && "type" in opts.storeToken && opts.storeToken.type === "custom-hasher") return await opts.storeToken.hash(token); - return token; - } - return { - id: "magic-link", - version: PACKAGE_VERSION, - endpoints: { - signInMagicLink: createAuthEndpoint("/sign-in/magic-link", { - method: "POST", - requireHeaders: true, - body: signInMagicLinkBodySchema, - metadata: { openapi: { - operationId: "signInWithMagicLink", - description: "Sign in with magic link", - responses: { 200: { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } } - }, async (ctx) => { - const { email: email3, metadata } = ctx.body; - const verificationToken = opts?.generateToken ? await opts.generateToken(email3) : generateRandomString(32, "a-z", "A-Z"); - const storedToken = await storeToken(ctx, verificationToken); - await ctx.context.internalAdapter.createVerificationValue({ - identifier: storedToken, - value: JSON.stringify({ - email: email3, - name: ctx.body.name, - attempt: 0 - }), - expiresAt: new Date(Date.now() + (opts.expiresIn || 300) * 1e3) - }); - const realBaseURL = new URL(ctx.context.baseURL); - const pathname = realBaseURL.pathname === "/" ? "" : realBaseURL.pathname; - const basePath = pathname ? "" : ctx.context.options.basePath || ""; - const url2 = new URL(`${pathname}${basePath}/magic-link/verify`, realBaseURL.origin); - url2.searchParams.set("token", verificationToken); - url2.searchParams.set("callbackURL", ctx.body.callbackURL || "/"); - if (ctx.body.newUserCallbackURL) url2.searchParams.set("newUserCallbackURL", ctx.body.newUserCallbackURL); - if (ctx.body.errorCallbackURL) url2.searchParams.set("errorCallbackURL", ctx.body.errorCallbackURL); - await options.sendMagicLink({ - email: email3, - url: url2.toString(), - token: verificationToken, - metadata - }, ctx); - return ctx.json({ status: true }); - }), - magicLinkVerify: createAuthEndpoint("/magic-link/verify", { - method: "GET", - query: magicLinkVerifyQuerySchema, - use: [ - originCheck((ctx) => { - return ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : "/"; - }), - originCheck((ctx) => { - return ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : "/"; - }), - originCheck((ctx) => { - return ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : "/"; - }) - ], - requireHeaders: true, - metadata: { openapi: { - operationId: "verifyMagicLink", - description: "Verify magic link", - responses: { 200: { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - session: { $ref: "#/components/schemas/Session" }, - user: { $ref: "#/components/schemas/User" } - } - } } } - } } - } } - }, async (ctx) => { - const token = ctx.query.token; - const callbackURL = new URL(ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : "/", ctx.context.baseURL).toString(); - const errorCallbackURL = new URL(ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : callbackURL, ctx.context.baseURL); - function redirectWithError(error49) { - errorCallbackURL.searchParams.set("error", error49); - throw ctx.redirect(errorCallbackURL.toString()); - } - const newUserCallbackURL = new URL(ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : callbackURL, ctx.context.baseURL).toString(); - const storedToken = await storeToken(ctx, token); - const tokenValue = await ctx.context.internalAdapter.findVerificationValue(storedToken); - if (!tokenValue) redirectWithError("INVALID_TOKEN"); - if (tokenValue.expiresAt < /* @__PURE__ */ new Date()) { - await ctx.context.internalAdapter.deleteVerificationByIdentifier(storedToken); - redirectWithError("EXPIRED_TOKEN"); - } - const { email: email3, name, attempt = 0 } = JSON.parse(tokenValue.value); - if (attempt >= opts.allowedAttempts) { - await ctx.context.internalAdapter.deleteVerificationByIdentifier(storedToken); - redirectWithError("ATTEMPTS_EXCEEDED"); - } - await ctx.context.internalAdapter.updateVerificationByIdentifier(storedToken, { value: JSON.stringify({ - email: email3, - name, - attempt: attempt + 1 - }) }); - let isNewUser = false; - let user = await ctx.context.internalAdapter.findUserByEmail(email3).then((res) => res?.user); - if (!user) if (!opts.disableSignUp) { - const newUser = await ctx.context.internalAdapter.createUser({ - email: email3, - emailVerified: true, - name: name || "" - }); - isNewUser = true; - user = newUser; - if (!user) redirectWithError("failed_to_create_user"); - } else redirectWithError("new_user_signup_disabled"); - if (!user.emailVerified) user = await ctx.context.internalAdapter.updateUser(user.id, { emailVerified: true }); - const session = await ctx.context.internalAdapter.createSession(user.id); - if (!session) redirectWithError("failed_to_create_session"); - await setSessionCookie(ctx, { - session, - user - }); - if (!ctx.query.callbackURL) return ctx.json({ - token: session.token, - user: parseUserOutput(ctx.context.options, user), - session: parseSessionOutput(ctx.context.options, session) - }); - if (isNewUser) throw ctx.redirect(newUserCallbackURL); - throw ctx.redirect(callbackURL); - }) - }, - rateLimit: [{ - pathMatcher(path3) { - return path3.startsWith("/sign-in/magic-link") || path3.startsWith("/magic-link/verify"); - }, - window: opts.rateLimit?.window || 60, - max: opts.rateLimit?.max || 5 - }], - options - }; -}; - -// ../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/index.mjs -init_adapter(); -init_adapter(); - -// ../../packages/plugins/plugin-auth/dist/index.mjs -init_data(); -init_data(); -init_data(); -init_data(); -init_data(); -init_data(); -init_data(); -init_data(); -init_data(); -init_data(); -init_data(); -init_data(); -var AUTH_MODEL_TO_PROTOCOL = { - user: SystemObjectName.USER, - session: SystemObjectName.SESSION, - account: SystemObjectName.ACCOUNT, - verification: SystemObjectName.VERIFICATION -}; -function convertWhere(where) { - const filter = {}; - for (const condition of where) { - const fieldName = condition.field; - if (condition.operator === "eq") { - filter[fieldName] = condition.value; - } else if (condition.operator === "ne") { - filter[fieldName] = { $ne: condition.value }; - } else if (condition.operator === "in") { - filter[fieldName] = { $in: condition.value }; - } else if (condition.operator === "gt") { - filter[fieldName] = { $gt: condition.value }; - } else if (condition.operator === "gte") { - filter[fieldName] = { $gte: condition.value }; - } else if (condition.operator === "lt") { - filter[fieldName] = { $lt: condition.value }; - } else if (condition.operator === "lte") { - filter[fieldName] = { $lte: condition.value }; - } else if (condition.operator === "contains") { - filter[fieldName] = { $regex: condition.value }; - } - } - return filter; -} -function createObjectQLAdapterFactory(dataEngine) { - return createAdapterFactory({ - config: { - adapterId: "objectql", - // ObjectQL natively supports these types — no extra conversion needed - supportsBooleans: true, - supportsDates: true, - supportsJSON: true - }, - adapter: () => ({ - create: async ({ model, data, select: _select }) => { - const result = await dataEngine.insert(model, data); - return result; - }, - findOne: async ({ model, where, select, join: _join }) => { - const filter = convertWhere(where); - const result = await dataEngine.findOne(model, { where: filter, fields: select }); - return result ? result : null; - }, - findMany: async ({ model, where, limit, offset, sortBy, join: _join }) => { - const filter = where ? convertWhere(where) : {}; - const orderBy = sortBy ? [{ field: sortBy.field, order: sortBy.direction }] : void 0; - const results = await dataEngine.find(model, { - where: filter, - limit: limit || 100, - offset, - orderBy - }); - return results; - }, - count: async ({ model, where }) => { - const filter = where ? convertWhere(where) : {}; - return await dataEngine.count(model, { where: filter }); - }, - update: async ({ model, where, update }) => { - const filter = convertWhere(where); - const record2 = await dataEngine.findOne(model, { where: filter }); - if (!record2) return null; - const result = await dataEngine.update(model, { ...update, id: record2.id }); - return result ? result : null; - }, - updateMany: async ({ model, where, update }) => { - const filter = convertWhere(where); - const records = await dataEngine.find(model, { where: filter }); - for (const record2 of records) { - await dataEngine.update(model, { ...update, id: record2.id }); - } - return records.length; - }, - delete: async ({ model, where }) => { - const filter = convertWhere(where); - const record2 = await dataEngine.findOne(model, { where: filter }); - if (!record2) return; - await dataEngine.delete(model, { where: { id: record2.id } }); - }, - deleteMany: async ({ model, where }) => { - const filter = convertWhere(where); - const records = await dataEngine.find(model, { where: filter }); - for (const record2 of records) { - await dataEngine.delete(model, { where: { id: record2.id } }); - } - return records.length; - } - }) - }); -} -var AUTH_USER_CONFIG = { - modelName: SystemObjectName.USER, - // 'sys_user' - fields: { - emailVerified: "email_verified", - createdAt: "created_at", - updatedAt: "updated_at" - } -}; -var AUTH_SESSION_CONFIG = { - modelName: SystemObjectName.SESSION, - // 'sys_session' - fields: { - userId: "user_id", - expiresAt: "expires_at", - createdAt: "created_at", - updatedAt: "updated_at", - ipAddress: "ip_address", - userAgent: "user_agent" - } -}; -var AUTH_ACCOUNT_CONFIG = { - modelName: SystemObjectName.ACCOUNT, - // 'sys_account' - fields: { - userId: "user_id", - providerId: "provider_id", - accountId: "account_id", - accessToken: "access_token", - refreshToken: "refresh_token", - idToken: "id_token", - accessTokenExpiresAt: "access_token_expires_at", - refreshTokenExpiresAt: "refresh_token_expires_at", - createdAt: "created_at", - updatedAt: "updated_at" - } -}; -var AUTH_VERIFICATION_CONFIG = { - modelName: SystemObjectName.VERIFICATION, - // 'sys_verification' - fields: { - expiresAt: "expires_at", - createdAt: "created_at", - updatedAt: "updated_at" - } -}; -var AUTH_ORGANIZATION_SCHEMA = { - modelName: SystemObjectName.ORGANIZATION, - // 'sys_organization' - fields: { - createdAt: "created_at", - updatedAt: "updated_at" - } -}; -var AUTH_MEMBER_SCHEMA = { - modelName: SystemObjectName.MEMBER, - // 'sys_member' - fields: { - organizationId: "organization_id", - userId: "user_id", - createdAt: "created_at" - } -}; -var AUTH_INVITATION_SCHEMA = { - modelName: SystemObjectName.INVITATION, - // 'sys_invitation' - fields: { - organizationId: "organization_id", - inviterId: "inviter_id", - expiresAt: "expires_at", - createdAt: "created_at", - teamId: "team_id" - } -}; -var AUTH_ORG_SESSION_FIELDS = { - activeOrganizationId: "active_organization_id", - activeTeamId: "active_team_id" -}; -var AUTH_TEAM_SCHEMA = { - modelName: SystemObjectName.TEAM, - // 'sys_team' - fields: { - organizationId: "organization_id", - createdAt: "created_at", - updatedAt: "updated_at" - } -}; -var AUTH_TEAM_MEMBER_SCHEMA = { - modelName: SystemObjectName.TEAM_MEMBER, - // 'sys_team_member' - fields: { - teamId: "team_id", - userId: "user_id", - createdAt: "created_at" - } -}; -var AUTH_TWO_FACTOR_SCHEMA = { - modelName: SystemObjectName.TWO_FACTOR, - // 'sys_two_factor' - fields: { - backupCodes: "backup_codes", - userId: "user_id" - } -}; -var AUTH_TWO_FACTOR_USER_FIELDS = { - twoFactorEnabled: "two_factor_enabled" -}; -function buildTwoFactorPluginSchema() { - return { - twoFactor: AUTH_TWO_FACTOR_SCHEMA, - user: { - fields: AUTH_TWO_FACTOR_USER_FIELDS - } - }; -} -function buildOrganizationPluginSchema() { - return { - organization: AUTH_ORGANIZATION_SCHEMA, - member: AUTH_MEMBER_SCHEMA, - invitation: AUTH_INVITATION_SCHEMA, - team: AUTH_TEAM_SCHEMA, - teamMember: AUTH_TEAM_MEMBER_SCHEMA, - session: { - fields: AUTH_ORG_SESSION_FIELDS - } - }; -} -var AuthManager = class { - constructor(config4) { - this.auth = null; - this.config = config4; - if (config4.authInstance) { - this.auth = config4.authInstance; - } - } - /** - * Get or create the better-auth instance (lazy initialization) - */ - getOrCreateAuth() { - if (!this.auth) { - this.auth = this.createAuthInstance(); - } - return this.auth; - } - /** - * Create a better-auth instance from configuration - */ - createAuthInstance() { - const betterAuthConfig = { - // Base configuration - secret: this.config.secret || this.generateSecret(), - baseURL: this.config.baseUrl || "http://localhost:3000", - basePath: this.config.basePath || "/api/v1/auth", - // Database adapter configuration - database: this.createDatabaseConfig(), - // Model/field mapping: camelCase (better-auth) → snake_case (ObjectStack) - // These declarations tell better-auth the actual table/column names used - // by ObjectStack's protocol layer, enabling automatic transformation via - // createAdapterFactory. - user: { - ...AUTH_USER_CONFIG - }, - account: { - ...AUTH_ACCOUNT_CONFIG - }, - verification: { - ...AUTH_VERIFICATION_CONFIG - }, - // Social / OAuth providers - ...this.config.socialProviders ? { socialProviders: this.config.socialProviders } : {}, - // Email and password configuration - emailAndPassword: { - enabled: this.config.emailAndPassword?.enabled ?? true, - ...this.config.emailAndPassword?.disableSignUp != null ? { disableSignUp: this.config.emailAndPassword.disableSignUp } : {}, - ...this.config.emailAndPassword?.requireEmailVerification != null ? { requireEmailVerification: this.config.emailAndPassword.requireEmailVerification } : {}, - ...this.config.emailAndPassword?.minPasswordLength != null ? { minPasswordLength: this.config.emailAndPassword.minPasswordLength } : {}, - ...this.config.emailAndPassword?.maxPasswordLength != null ? { maxPasswordLength: this.config.emailAndPassword.maxPasswordLength } : {}, - ...this.config.emailAndPassword?.resetPasswordTokenExpiresIn != null ? { resetPasswordTokenExpiresIn: this.config.emailAndPassword.resetPasswordTokenExpiresIn } : {}, - ...this.config.emailAndPassword?.autoSignIn != null ? { autoSignIn: this.config.emailAndPassword.autoSignIn } : {}, - ...this.config.emailAndPassword?.revokeSessionsOnPasswordReset != null ? { revokeSessionsOnPasswordReset: this.config.emailAndPassword.revokeSessionsOnPasswordReset } : {} - }, - // Email verification - ...this.config.emailVerification ? { - emailVerification: { - ...this.config.emailVerification.sendOnSignUp != null ? { sendOnSignUp: this.config.emailVerification.sendOnSignUp } : {}, - ...this.config.emailVerification.sendOnSignIn != null ? { sendOnSignIn: this.config.emailVerification.sendOnSignIn } : {}, - ...this.config.emailVerification.autoSignInAfterVerification != null ? { autoSignInAfterVerification: this.config.emailVerification.autoSignInAfterVerification } : {}, - ...this.config.emailVerification.expiresIn != null ? { expiresIn: this.config.emailVerification.expiresIn } : {} - } - } : {}, - // Session configuration - session: { - ...AUTH_SESSION_CONFIG, - expiresIn: this.config.session?.expiresIn || 60 * 60 * 24 * 7, - // 7 days default - updateAge: this.config.session?.updateAge || 60 * 60 * 24 - // 1 day default - }, - // better-auth plugins — registered based on AuthPluginConfig flags - plugins: this.buildPluginList(), - // Trusted origins for CSRF protection (supports wildcards like "https://*.example.com") - ...this.config.trustedOrigins?.length ? { trustedOrigins: this.config.trustedOrigins } : {}, - // Advanced options (cross-subdomain cookies, secure cookies, CSRF, etc.) - ...this.config.advanced ? { - advanced: { - ...this.config.advanced.crossSubDomainCookies ? { crossSubDomainCookies: this.config.advanced.crossSubDomainCookies } : {}, - ...this.config.advanced.useSecureCookies != null ? { useSecureCookies: this.config.advanced.useSecureCookies } : {}, - ...this.config.advanced.disableCSRFCheck != null ? { disableCSRFCheck: this.config.advanced.disableCSRFCheck } : {}, - ...this.config.advanced.cookiePrefix != null ? { cookiePrefix: this.config.advanced.cookiePrefix } : {} - } - } : {} - }; - return betterAuth(betterAuthConfig); - } - /** - * Build the list of better-auth plugins based on AuthPluginConfig flags. - * - * Each plugin that introduces its own database tables is configured with - * a `schema` option containing the appropriate snake_case field mappings, - * so that `createAdapterFactory` transforms them automatically. - */ - buildPluginList() { - const pluginConfig = this.config.plugins; - const plugins = []; - if (pluginConfig?.organization) { - plugins.push(organization({ - schema: buildOrganizationPluginSchema() - })); - } - if (pluginConfig?.twoFactor) { - plugins.push(twoFactor({ - schema: buildTwoFactorPluginSchema() - })); - } - if (pluginConfig?.magicLink) { - plugins.push(magicLink({ - sendMagicLink: async ({ email: email3, url: url2 }) => { - console.warn( - `[AuthManager] Magic-link requested for ${email3} but no sendMagicLink handler configured. URL: ${url2}` - ); - } - })); - } - return plugins; - } - /** - * Create database configuration using ObjectQL adapter - * - * better-auth resolves the `database` option as follows: - * - `undefined` → in-memory adapter - * - `typeof fn === "function"` → treated as `DBAdapterInstance`, called with `(options)` - * - otherwise → forwarded to Kysely adapter factory (pool/dialect) - * - * A raw `CustomAdapter` object would fall into the third branch and fail - * silently. We therefore wrap the ObjectQL adapter in a factory function - * so it is correctly recognised as a `DBAdapterInstance`. - */ - createDatabaseConfig() { - if (this.config.dataEngine) { - return createObjectQLAdapterFactory(this.config.dataEngine); - } - console.warn( - "\u26A0\uFE0F WARNING: No dataEngine provided to AuthManager! Using in-memory storage. This is NOT suitable for production. Please provide a dataEngine instance (e.g., ObjectQL) in AuthManagerOptions." - ); - return void 0; - } - /** - * Generate a secure secret if not provided - */ - generateSecret() { - const envSecret = process.env.AUTH_SECRET; - if (!envSecret) { - const fallbackSecret = "dev-secret-" + Date.now(); - console.warn( - "\u26A0\uFE0F WARNING: No AUTH_SECRET environment variable set! Using a temporary development secret. This is NOT secure for production use. Please set AUTH_SECRET in your environment variables." - ); - return fallbackSecret; - } - return envSecret; - } - /** - * Update the base URL at runtime. - * - * This **must** be called before the first request triggers lazy - * initialisation of the better-auth instance — typically from a - * `kernel:ready` hook where the actual server port is known. - * - * If the auth instance has already been created this is a no-op and - * a warning is emitted. - */ - setRuntimeBaseUrl(url2) { - if (this.auth) { - console.warn( - "[AuthManager] setRuntimeBaseUrl() called after the auth instance was already created \u2014 ignoring. Ensure this method is called before the first request." - ); - return; - } - this.config = { ...this.config, baseUrl: url2 }; - } - /** - * Get the underlying better-auth instance - * Useful for advanced use cases - */ - getAuthInstance() { - return this.getOrCreateAuth(); - } - /** - * Handle an authentication request - * Forwards the request directly to better-auth's universal handler - * - * better-auth catches internal errors (database / adapter / ORM) and - * returns a 500 Response instead of throwing. We therefore inspect the - * response status and log server errors so they are not silently swallowed. - * - * @param request - Web standard Request object - * @returns Web standard Response object - */ - async handleRequest(request) { - const auth = this.getOrCreateAuth(); - const response = await auth.handler(request); - if (response.status >= 500) { - try { - const body = await response.clone().text(); - console.error("[AuthManager] better-auth returned error:", response.status, body); - } catch { - console.error("[AuthManager] better-auth returned error:", response.status, "(unable to read body)"); - } - } - return response; - } - /** - * Get the better-auth API for programmatic access - * Use this for server-side operations (e.g., creating users, checking sessions) - */ - get api() { - return this.getOrCreateAuth().api; - } -}; -var SysUser = ObjectSchema3.create({ - namespace: "sys", - name: "user", - label: "User", - pluralLabel: "Users", - icon: "user", - isSystem: true, - description: "User accounts for authentication", - titleFormat: "{name} ({email})", - compactLayout: ["name", "email", "email_verified"], - fields: { - id: Field.text({ - label: "User ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - email: Field.email({ - label: "Email", - required: true, - searchable: true - }), - email_verified: Field.boolean({ - label: "Email Verified", - defaultValue: false - }), - name: Field.text({ - label: "Name", - required: true, - searchable: true, - maxLength: 255 - }), - image: Field.url({ - label: "Profile Image", - required: false - }) - }, - indexes: [ - { fields: ["email"], unique: true }, - { fields: ["created_at"], unique: false } - ], - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete"], - trash: true, - mru: true - }, - validations: [ - { - name: "email_unique", - type: "unique", - severity: "error", - message: "Email must be unique", - fields: ["email"], - caseSensitive: false - } - ] -}); -var SysSession = ObjectSchema3.create({ - namespace: "sys", - name: "session", - label: "Session", - pluralLabel: "Sessions", - icon: "key", - isSystem: true, - description: "Active user sessions", - titleFormat: "Session {token}", - compactLayout: ["user_id", "expires_at", "ip_address"], - fields: { - id: Field.text({ - label: "Session ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - user_id: Field.text({ - label: "User ID", - required: true - }), - expires_at: Field.datetime({ - label: "Expires At", - required: true - }), - token: Field.text({ - label: "Session Token", - required: true - }), - ip_address: Field.text({ - label: "IP Address", - required: false, - maxLength: 45 - // Support IPv6 - }), - user_agent: Field.textarea({ - label: "User Agent", - required: false - }) - }, - indexes: [ - { fields: ["token"], unique: true }, - { fields: ["user_id"], unique: false }, - { fields: ["expires_at"], unique: false } - ], - enable: { - trackHistory: false, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "list", "create", "delete"], - trash: false, - mru: false - } -}); -var SysAccount = ObjectSchema3.create({ - namespace: "sys", - name: "account", - label: "Account", - pluralLabel: "Accounts", - icon: "link", - isSystem: true, - description: "OAuth and authentication provider accounts", - titleFormat: "{provider_id} - {account_id}", - compactLayout: ["provider_id", "user_id", "account_id"], - fields: { - id: Field.text({ - label: "Account ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - provider_id: Field.text({ - label: "Provider ID", - required: true, - description: "OAuth provider identifier (google, github, etc.)" - }), - account_id: Field.text({ - label: "Provider Account ID", - required: true, - description: "User's ID in the provider's system" - }), - user_id: Field.text({ - label: "User ID", - required: true, - description: "Link to user table" - }), - access_token: Field.textarea({ - label: "Access Token", - required: false - }), - refresh_token: Field.textarea({ - label: "Refresh Token", - required: false - }), - id_token: Field.textarea({ - label: "ID Token", - required: false - }), - access_token_expires_at: Field.datetime({ - label: "Access Token Expires At", - required: false - }), - refresh_token_expires_at: Field.datetime({ - label: "Refresh Token Expires At", - required: false - }), - scope: Field.text({ - label: "OAuth Scope", - required: false - }), - password: Field.text({ - label: "Password Hash", - required: false, - description: "Hashed password for email/password provider" - }) - }, - indexes: [ - { fields: ["user_id"], unique: false }, - { fields: ["provider_id", "account_id"], unique: true } - ], - enable: { - trackHistory: false, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete"], - trash: true, - mru: false - } -}); -var SysVerification = ObjectSchema3.create({ - namespace: "sys", - name: "verification", - label: "Verification", - pluralLabel: "Verifications", - icon: "shield-check", - isSystem: true, - description: "Email and phone verification tokens", - titleFormat: "Verification for {identifier}", - compactLayout: ["identifier", "expires_at", "created_at"], - fields: { - id: Field.text({ - label: "Verification ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - value: Field.text({ - label: "Verification Token", - required: true, - description: "Token or code for verification" - }), - expires_at: Field.datetime({ - label: "Expires At", - required: true - }), - identifier: Field.text({ - label: "Identifier", - required: true, - description: "Email address or phone number" - }) - }, - indexes: [ - { fields: ["value"], unique: true }, - { fields: ["identifier"], unique: false }, - { fields: ["expires_at"], unique: false } - ], - enable: { - trackHistory: false, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "create", "delete"], - trash: false, - mru: false - } -}); -var SysOrganization = ObjectSchema3.create({ - namespace: "sys", - name: "organization", - label: "Organization", - pluralLabel: "Organizations", - icon: "building-2", - isSystem: true, - description: "Organizations for multi-tenant grouping", - titleFormat: "{name}", - compactLayout: ["name", "slug", "created_at"], - fields: { - id: Field.text({ - label: "Organization ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - name: Field.text({ - label: "Name", - required: true, - searchable: true, - maxLength: 255 - }), - slug: Field.text({ - label: "Slug", - required: false, - maxLength: 255, - description: "URL-friendly identifier" - }), - logo: Field.url({ - label: "Logo", - required: false - }), - metadata: Field.textarea({ - label: "Metadata", - required: false, - description: "JSON-serialized organization metadata" - }) - }, - indexes: [ - { fields: ["slug"], unique: true }, - { fields: ["name"] } - ], - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete"], - trash: true, - mru: true - } -}); -var SysMember = ObjectSchema3.create({ - namespace: "sys", - name: "member", - label: "Member", - pluralLabel: "Members", - icon: "user-check", - isSystem: true, - description: "Organization membership records", - titleFormat: "{user_id} in {organization_id}", - compactLayout: ["user_id", "organization_id", "role"], - fields: { - id: Field.text({ - label: "Member ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - organization_id: Field.text({ - label: "Organization ID", - required: true - }), - user_id: Field.text({ - label: "User ID", - required: true - }), - role: Field.text({ - label: "Role", - required: false, - description: "Member role within the organization (e.g. admin, member)", - maxLength: 100 - }) - }, - indexes: [ - { fields: ["organization_id", "user_id"], unique: true }, - { fields: ["user_id"] } - ], - enable: { - trackHistory: true, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete"], - trash: false, - mru: false - } -}); -var SysInvitation = ObjectSchema3.create({ - namespace: "sys", - name: "invitation", - label: "Invitation", - pluralLabel: "Invitations", - icon: "mail", - isSystem: true, - description: "Organization invitations for user onboarding", - titleFormat: "Invitation to {organization_id}", - compactLayout: ["email", "organization_id", "status"], - fields: { - id: Field.text({ - label: "Invitation ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - organization_id: Field.text({ - label: "Organization ID", - required: true - }), - email: Field.email({ - label: "Email", - required: true, - description: "Email address of the invited user" - }), - role: Field.text({ - label: "Role", - required: false, - maxLength: 100, - description: "Role to assign upon acceptance" - }), - status: Field.select(["pending", "accepted", "rejected", "expired", "canceled"], { - label: "Status", - required: true, - defaultValue: "pending" - }), - inviter_id: Field.text({ - label: "Inviter ID", - required: true, - description: "User ID of the person who sent the invitation" - }), - expires_at: Field.datetime({ - label: "Expires At", - required: true - }), - team_id: Field.text({ - label: "Team ID", - required: false, - description: "Optional team to assign upon acceptance" - }) - }, - indexes: [ - { fields: ["organization_id"] }, - { fields: ["email"] }, - { fields: ["expires_at"] } - ], - enable: { - trackHistory: true, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete"], - trash: false, - mru: false - } -}); -var SysTeam = ObjectSchema3.create({ - namespace: "sys", - name: "team", - label: "Team", - pluralLabel: "Teams", - icon: "users", - isSystem: true, - description: "Teams within organizations for fine-grained grouping", - titleFormat: "{name}", - compactLayout: ["name", "organization_id", "created_at"], - fields: { - id: Field.text({ - label: "Team ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - name: Field.text({ - label: "Name", - required: true, - searchable: true, - maxLength: 255 - }), - organization_id: Field.text({ - label: "Organization ID", - required: true - }) - }, - indexes: [ - { fields: ["organization_id"] }, - { fields: ["name", "organization_id"], unique: true } - ], - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete"], - trash: true, - mru: false - } -}); -var SysTeamMember = ObjectSchema3.create({ - namespace: "sys", - name: "team_member", - label: "Team Member", - pluralLabel: "Team Members", - icon: "user-plus", - isSystem: true, - description: "Team membership records linking users to teams", - titleFormat: "{user_id} in {team_id}", - compactLayout: ["user_id", "team_id", "created_at"], - fields: { - id: Field.text({ - label: "Team Member ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - team_id: Field.text({ - label: "Team ID", - required: true - }), - user_id: Field.text({ - label: "User ID", - required: true - }) - }, - indexes: [ - { fields: ["team_id", "user_id"], unique: true }, - { fields: ["user_id"] } - ], - enable: { - trackHistory: true, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "list", "create", "delete"], - trash: false, - mru: false - } -}); -var SysApiKey = ObjectSchema3.create({ - namespace: "sys", - name: "api_key", - label: "API Key", - pluralLabel: "API Keys", - icon: "key-round", - isSystem: true, - description: "API keys for programmatic access", - titleFormat: "{name}", - compactLayout: ["name", "user_id", "expires_at"], - fields: { - id: Field.text({ - label: "API Key ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - name: Field.text({ - label: "Name", - required: true, - maxLength: 255, - description: "Human-readable label for the API key" - }), - key: Field.text({ - label: "Key", - required: true, - description: "Hashed API key value" - }), - prefix: Field.text({ - label: "Prefix", - required: false, - maxLength: 16, - description: 'Visible prefix for identifying the key (e.g., "osk_")' - }), - user_id: Field.text({ - label: "User ID", - required: true, - description: "Owner user of this API key" - }), - scopes: Field.textarea({ - label: "Scopes", - required: false, - description: "JSON array of permission scopes" - }), - expires_at: Field.datetime({ - label: "Expires At", - required: false - }), - last_used_at: Field.datetime({ - label: "Last Used At", - required: false - }), - revoked: Field.boolean({ - label: "Revoked", - defaultValue: false - }) - }, - indexes: [ - { fields: ["key"], unique: true }, - { fields: ["user_id"] }, - { fields: ["prefix"] } - ], - enable: { - trackHistory: true, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete"], - trash: false, - mru: false - } -}); -var SysTwoFactor = ObjectSchema3.create({ - namespace: "sys", - name: "two_factor", - label: "Two Factor", - pluralLabel: "Two Factor Credentials", - icon: "smartphone", - isSystem: true, - description: "Two-factor authentication credentials", - titleFormat: "Two-factor for {user_id}", - compactLayout: ["user_id", "created_at"], - fields: { - id: Field.text({ - label: "Two Factor ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - user_id: Field.text({ - label: "User ID", - required: true - }), - secret: Field.text({ - label: "Secret", - required: true, - description: "TOTP secret key" - }), - backup_codes: Field.textarea({ - label: "Backup Codes", - required: false, - description: "JSON-serialized backup recovery codes" - }) - }, - indexes: [ - { fields: ["user_id"], unique: true } - ], - enable: { - trackHistory: false, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "create", "update", "delete"], - trash: false, - mru: false - } -}); -var SysUserPreference = ObjectSchema3.create({ - namespace: "sys", - name: "user_preference", - label: "User Preference", - pluralLabel: "User Preferences", - icon: "settings", - isSystem: true, - description: "Per-user key-value preferences (theme, locale, etc.)", - titleFormat: "{key}", - compactLayout: ["user_id", "key"], - fields: { - id: Field.text({ - label: "Preference ID", - required: true, - readonly: true - }), - created_at: Field.datetime({ - label: "Created At", - defaultValue: "NOW()", - readonly: true - }), - updated_at: Field.datetime({ - label: "Updated At", - defaultValue: "NOW()", - readonly: true - }), - user_id: Field.text({ - label: "User ID", - required: true, - maxLength: 255, - description: "Owner user of this preference" - }), - key: Field.text({ - label: "Key", - required: true, - maxLength: 255, - description: "Preference key (e.g., theme, locale, plugin.ai.auto_save)" - }), - value: Field.json({ - label: "Value", - description: "Preference value (any JSON-serializable type)" - }) - }, - indexes: [ - { fields: ["user_id", "key"], unique: true }, - { fields: ["user_id"], unique: false } - ], - enable: { - trackHistory: false, - searchable: false, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete"], - trash: false, - mru: false - } -}); -var AuthPlugin = class { - constructor(options = {}) { - this.name = "com.objectstack.auth"; - this.type = "standard"; - this.version = "1.0.0"; - this.dependencies = ["com.objectstack.engine.objectql"]; - this.authManager = null; - this.options = { - registerRoutes: true, - basePath: "/api/v1/auth", - ...options - }; - } - async init(ctx) { - ctx.logger.info("Initializing Auth Plugin..."); - if (!this.options.secret) { - throw new Error("AuthPlugin: secret is required"); - } - const dataEngine = ctx.getService("data"); - if (!dataEngine) { - ctx.logger.warn("No data engine service found - auth will use in-memory storage"); - } - this.authManager = new AuthManager({ - ...this.options, - dataEngine - }); - ctx.registerService("auth", this.authManager); - ctx.getService("manifest").register({ - id: "com.objectstack.system", - name: "System", - version: "1.0.0", - type: "plugin", - namespace: "sys", - objects: [ - SysUser, - SysSession, - SysAccount, - SysVerification, - SysOrganization, - SysMember, - SysInvitation, - SysTeam, - SysTeamMember, - SysApiKey, - SysTwoFactor, - SysUserPreference - ] - }); - try { - const setupNav = ctx.getService("setupNav"); - if (setupNav) { - setupNav.contribute({ - areaId: "area_administration", - items: [ - { id: "nav_users", type: "object", label: "Users", objectName: "user", icon: "users", order: 10 }, - { id: "nav_organizations", type: "object", label: "Organizations", objectName: "organization", icon: "building-2", order: 20 }, - { id: "nav_teams", type: "object", label: "Teams", objectName: "team", icon: "users-round", order: 30 }, - { id: "nav_api_keys", type: "object", label: "API Keys", objectName: "api_key", icon: "key", order: 40 }, - { id: "nav_sessions", type: "object", label: "Sessions", objectName: "session", icon: "monitor", order: 50 } - ] - }); - ctx.logger.info("Auth navigation items contributed to Setup App"); - } - } catch { - } - ctx.logger.info("Auth Plugin initialized successfully"); - } - async start(ctx) { - ctx.logger.info("Starting Auth Plugin..."); - if (!this.authManager) { - throw new Error("Auth manager not initialized"); - } - if (this.options.registerRoutes) { - ctx.hook("kernel:ready", async () => { - let httpServer = null; - try { - httpServer = ctx.getService("http-server"); - } catch { - } - if (httpServer) { - const serverWithPort = httpServer; - if (this.authManager && typeof serverWithPort.getPort === "function") { - const actualPort = serverWithPort.getPort(); - if (actualPort) { - const configuredUrl = this.options.baseUrl || "http://localhost:3000"; - const configuredOrigin = new URL(configuredUrl).origin; - const actualUrl = `http://localhost:${actualPort}`; - if (configuredOrigin !== actualUrl) { - this.authManager.setRuntimeBaseUrl(actualUrl); - ctx.logger.info( - `Auth baseUrl auto-updated to ${actualUrl} (configured: ${configuredUrl})` - ); - } - } - } - this.registerAuthRoutes(httpServer, ctx); - ctx.logger.info(`Auth routes registered at ${this.options.basePath}`); - } else { - ctx.logger.warn( - "No HTTP server available \u2014 auth routes not registered. Auth service is still available for MSW/mock environments via HttpDispatcher." - ); - } - }); - } - try { - const ql = ctx.getService("objectql"); - if (ql && typeof ql.registerMiddleware === "function") { - ql.registerMiddleware(async (opCtx, next) => { - if (opCtx.context?.userId || opCtx.context?.isSystem) { - return next(); - } - await next(); - }); - ctx.logger.info("Auth middleware registered on ObjectQL engine"); - } - } catch (_e) { - ctx.logger.debug("ObjectQL engine not available, skipping auth middleware registration"); - } - ctx.logger.info("Auth Plugin started successfully"); - } - async destroy() { - this.authManager = null; - } - /** - * Register authentication routes with HTTP server - * - * Uses better-auth's universal handler for all authentication requests. - * This forwards all requests under basePath to better-auth, which handles: - * - Email/password authentication - * - OAuth providers (Google, GitHub, etc.) - * - Session management - * - Password reset - * - Email verification - * - 2FA, passkeys, magic links (if enabled) - */ - registerAuthRoutes(httpServer, ctx) { - if (!this.authManager) return; - const basePath = this.options.basePath || "/api/v1/auth"; - if (!("getRawApp" in httpServer) || typeof httpServer.getRawApp !== "function") { - ctx.logger.error("HTTP server does not support getRawApp() - wildcard routing requires Hono server"); - throw new Error( - "AuthPlugin requires HonoServerPlugin for wildcard routing support. Please ensure HonoServerPlugin is loaded before AuthPlugin." - ); - } - const rawApp = httpServer.getRawApp(); - rawApp.all(`${basePath}/*`, async (c) => { - try { - const response = await this.authManager.handleRequest(c.req.raw); - if (response.status >= 500) { - try { - const body = await response.clone().text(); - ctx.logger.error("[AuthPlugin] better-auth returned server error", new Error(`HTTP ${response.status}: ${body}`)); - } catch { - ctx.logger.error("[AuthPlugin] better-auth returned server error", new Error(`HTTP ${response.status}: (unable to read body)`)); - } - } - return response; - } catch (error49) { - const err = error49 instanceof Error ? error49 : new Error(String(error49)); - ctx.logger.error("Auth request error:", err); - return new Response( - JSON.stringify({ - success: false, - error: err.message - }), - { - status: 500, - headers: { "Content-Type": "application/json" } - } - ); - } - }); - ctx.logger.info(`Auth routes registered: All requests under ${basePath}/* forwarded to better-auth`); - } -}; - -// ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.12/node_modules/@hono/node-server/dist/index.mjs -import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2"; -import { Http2ServerRequest } from "http2"; -import { Readable } from "stream"; -import crypto2 from "crypto"; -var RequestError = class extends Error { - constructor(message2, options) { - super(message2, options); - this.name = "RequestError"; - } -}; -var toRequestError = (e) => { - if (e instanceof RequestError) { - return e; - } - return new RequestError(e.message, { cause: e }); -}; -var GlobalRequest = global.Request; -var Request2 = class extends GlobalRequest { - constructor(input, options) { - if (typeof input === "object" && getRequestCache in input) { - input = input[getRequestCache](); - } - if (typeof options?.body?.getReader !== "undefined") { - ; - options.duplex ?? (options.duplex = "half"); - } - super(input, options); - } -}; -var newHeadersFromIncoming = (incoming) => { - const headerRecord = []; - const rawHeaders = incoming.rawHeaders; - for (let i = 0; i < rawHeaders.length; i += 2) { - const { [i]: key, [i + 1]: value } = rawHeaders; - if (key.charCodeAt(0) !== /*:*/ - 58) { - headerRecord.push([key, value]); - } - } - return new Headers(headerRecord); -}; -var wrapBodyStream = Symbol("wrapBodyStream"); -var newRequestFromIncoming = (method, url2, headers, incoming, abortController) => { - const init2 = { - method, - headers, - signal: abortController.signal - }; - if (method === "TRACE") { - init2.method = "GET"; - const req = new Request2(url2, init2); - Object.defineProperty(req, "method", { - get() { - return "TRACE"; - } - }); - return req; - } - if (!(method === "GET" || method === "HEAD")) { - if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { - init2.body = new ReadableStream({ - start(controller) { - controller.enqueue(incoming.rawBody); - controller.close(); - } - }); - } else if (incoming[wrapBodyStream]) { - let reader; - init2.body = new ReadableStream({ - async pull(controller) { - try { - reader || (reader = Readable.toWeb(incoming).getReader()); - const { done, value } = await reader.read(); - if (done) { - controller.close(); - } else { - controller.enqueue(value); - } - } catch (error49) { - controller.error(error49); - } - } - }); - } else { - init2.body = Readable.toWeb(incoming); - } - } - return new Request2(url2, init2); -}; -var getRequestCache = Symbol("getRequestCache"); -var requestCache = Symbol("requestCache"); -var incomingKey = Symbol("incomingKey"); -var urlKey = Symbol("urlKey"); -var headersKey = Symbol("headersKey"); -var abortControllerKey = Symbol("abortControllerKey"); -var getAbortController = Symbol("getAbortController"); -var requestPrototype = { - get method() { - return this[incomingKey].method || "GET"; - }, - get url() { - return this[urlKey]; - }, - get headers() { - return this[headersKey] || (this[headersKey] = newHeadersFromIncoming(this[incomingKey])); - }, - [getAbortController]() { - this[getRequestCache](); - return this[abortControllerKey]; - }, - [getRequestCache]() { - this[abortControllerKey] || (this[abortControllerKey] = new AbortController()); - return this[requestCache] || (this[requestCache] = newRequestFromIncoming( - this.method, - this[urlKey], - this.headers, - this[incomingKey], - this[abortControllerKey] - )); - } -}; -[ - "body", - "bodyUsed", - "cache", - "credentials", - "destination", - "integrity", - "mode", - "redirect", - "referrer", - "referrerPolicy", - "signal", - "keepalive" -].forEach((k) => { - Object.defineProperty(requestPrototype, k, { - get() { - return this[getRequestCache]()[k]; - } - }); -}); -["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { - Object.defineProperty(requestPrototype, k, { - value: function() { - return this[getRequestCache]()[k](); - } - }); -}); -Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { - value: function(depth, options, inspectFn) { - const props = { - method: this.method, - url: this.url, - headers: this.headers, - nativeRequest: this[requestCache] - }; - return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`; - } -}); -Object.setPrototypeOf(requestPrototype, Request2.prototype); -var newRequest = (incoming, defaultHostname) => { - const req = Object.create(requestPrototype); - req[incomingKey] = incoming; - const incomingUrl = incoming.url || ""; - if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. - (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { - if (incoming instanceof Http2ServerRequest) { - throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); - } - try { - const url22 = new URL(incomingUrl); - req[urlKey] = url22.href; - } catch (e) { - throw new RequestError("Invalid absolute URL", { cause: e }); - } - return req; - } - const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; - if (!host) { - throw new RequestError("Missing host header"); - } - let scheme; - if (incoming instanceof Http2ServerRequest) { - scheme = incoming.scheme; - if (!(scheme === "http" || scheme === "https")) { - throw new RequestError("Unsupported scheme"); - } - } else { - scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; - } - const url2 = new URL(`${scheme}://${host}${incomingUrl}`); - if (url2.hostname.length !== host.length && url2.hostname !== host.replace(/:\d+$/, "")) { - throw new RequestError("Invalid host header"); - } - req[urlKey] = url2.href; - return req; -}; -var responseCache = Symbol("responseCache"); -var getResponseCache = Symbol("getResponseCache"); -var cacheKey = Symbol("cache"); -var GlobalResponse = global.Response; -var _body, _init, _a29; -var Response2 = (_a29 = class { - constructor(body, init2) { - __privateAdd(this, _body); - __privateAdd(this, _init); - let headers; - __privateSet(this, _body, body); - if (init2 instanceof _a29) { - const cachedGlobalResponse = init2[responseCache]; - if (cachedGlobalResponse) { - __privateSet(this, _init, cachedGlobalResponse); - this[getResponseCache](); - return; - } else { - __privateSet(this, _init, __privateGet(init2, _init)); - headers = new Headers(__privateGet(init2, _init).headers); - } - } else { - __privateSet(this, _init, init2); - } - if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { - ; - this[cacheKey] = [init2?.status || 200, body, headers || init2?.headers]; - } - } - [getResponseCache]() { - delete this[cacheKey]; - return this[responseCache] || (this[responseCache] = new GlobalResponse(__privateGet(this, _body), __privateGet(this, _init))); - } - get headers() { - const cache3 = this[cacheKey]; - if (cache3) { - if (!(cache3[2] instanceof Headers)) { - cache3[2] = new Headers( - cache3[2] || { "content-type": "text/plain; charset=UTF-8" } - ); - } - return cache3[2]; - } - return this[getResponseCache]().headers; - } - get status() { - return this[cacheKey]?.[0] ?? this[getResponseCache]().status; - } - get ok() { - const status = this.status; - return status >= 200 && status < 300; - } -}, _body = new WeakMap(), _init = new WeakMap(), _a29); -["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { - Object.defineProperty(Response2.prototype, k, { - get() { - return this[getResponseCache]()[k]; - } - }); -}); -["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { - Object.defineProperty(Response2.prototype, k, { - value: function() { - return this[getResponseCache]()[k](); - } - }); -}); -Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), { - value: function(depth, options, inspectFn) { - const props = { - status: this.status, - headers: this.headers, - ok: this.ok, - nativeResponse: this[responseCache] - }; - return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`; - } -}); -Object.setPrototypeOf(Response2, GlobalResponse); -Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); -async function readWithoutBlocking(readPromise) { - return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); -} -function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { - const cancel = (error49) => { - reader.cancel(error49).catch(() => { - }); - }; - writable.on("close", cancel); - writable.on("error", cancel); - (currentReadPromise ?? reader.read()).then(flow, handleStreamError); - return reader.closed.finally(() => { - writable.off("close", cancel); - writable.off("error", cancel); - }); - function handleStreamError(error49) { - if (error49) { - writable.destroy(error49); - } - } - function onDrain() { - reader.read().then(flow, handleStreamError); - } - function flow({ done, value }) { - try { - if (done) { - writable.end(); - } else if (!writable.write(value)) { - writable.once("drain", onDrain); - } else { - return reader.read().then(flow, handleStreamError); - } - } catch (e) { - handleStreamError(e); - } - } -} -function writeFromReadableStream(stream, writable) { - if (stream.locked) { - throw new TypeError("ReadableStream is locked."); - } else if (writable.destroyed) { - return; - } - return writeFromReadableStreamDefaultReader(stream.getReader(), writable); -} -var buildOutgoingHttpHeaders = (headers) => { - const res = {}; - if (!(headers instanceof Headers)) { - headers = new Headers(headers ?? void 0); - } - const cookies = []; - for (const [k, v] of headers) { - if (k === "set-cookie") { - cookies.push(v); - } else { - res[k] = v; - } - } - if (cookies.length > 0) { - res["set-cookie"] = cookies; - } - res["content-type"] ?? (res["content-type"] = "text/plain; charset=UTF-8"); - return res; -}; -var X_ALREADY_SENT = "x-hono-already-sent"; -if (typeof global.crypto === "undefined") { - global.crypto = crypto2; -} -var outgoingEnded = Symbol("outgoingEnded"); -var incomingDraining = Symbol("incomingDraining"); -var DRAIN_TIMEOUT_MS = 500; -var MAX_DRAIN_BYTES = 64 * 1024 * 1024; -var drainIncoming = (incoming) => { - const incomingWithDrainState = incoming; - if (incoming.destroyed || incomingWithDrainState[incomingDraining]) { - return; - } - incomingWithDrainState[incomingDraining] = true; - if (incoming instanceof Http2ServerRequest2) { - try { - ; - incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR); - } catch { - } - return; - } - let bytesRead = 0; - const cleanup = () => { - clearTimeout(timer); - incoming.off("data", onData); - incoming.off("end", cleanup); - incoming.off("error", cleanup); - }; - const forceClose = () => { - cleanup(); - const socket = incoming.socket; - if (socket && !socket.destroyed) { - socket.destroySoon(); - } - }; - const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS); - timer.unref?.(); - const onData = (chunk) => { - bytesRead += chunk.length; - if (bytesRead > MAX_DRAIN_BYTES) { - forceClose(); - } - }; - incoming.on("data", onData); - incoming.on("end", cleanup); - incoming.on("error", cleanup); - incoming.resume(); -}; -var handleRequestError = () => new Response(null, { - status: 400 -}); -var handleFetchError = (e) => new Response(null, { - status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 -}); -var handleResponseError = (e, outgoing) => { - const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); - if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { - console.info("The user aborted a request."); - } else { - console.error(e); - if (!outgoing.headersSent) { - outgoing.writeHead(500, { "Content-Type": "text/plain" }); - } - outgoing.end(`Error: ${err.message}`); - outgoing.destroy(err); - } -}; -var flushHeaders = (outgoing) => { - if ("flushHeaders" in outgoing && outgoing.writable) { - outgoing.flushHeaders(); - } -}; -var responseViaCache = async (res, outgoing) => { - let [status, body, header] = res[cacheKey]; - let hasContentLength = false; - if (!header) { - header = { "content-type": "text/plain; charset=UTF-8" }; - } else if (header instanceof Headers) { - hasContentLength = header.has("content-length"); - header = buildOutgoingHttpHeaders(header); - } else if (Array.isArray(header)) { - const headerObj = new Headers(header); - hasContentLength = headerObj.has("content-length"); - header = buildOutgoingHttpHeaders(headerObj); - } else { - for (const key in header) { - if (key.length === 14 && key.toLowerCase() === "content-length") { - hasContentLength = true; - break; - } - } - } - if (!hasContentLength) { - if (typeof body === "string") { - header["Content-Length"] = Buffer.byteLength(body); - } else if (body instanceof Uint8Array) { - header["Content-Length"] = body.byteLength; - } else if (body instanceof Blob) { - header["Content-Length"] = body.size; - } - } - outgoing.writeHead(status, header); - if (typeof body === "string" || body instanceof Uint8Array) { - outgoing.end(body); - } else if (body instanceof Blob) { - outgoing.end(new Uint8Array(await body.arrayBuffer())); - } else { - flushHeaders(outgoing); - await writeFromReadableStream(body, outgoing)?.catch( - (e) => handleResponseError(e, outgoing) - ); - } - ; - outgoing[outgoingEnded]?.(); -}; -var isPromise2 = (res) => typeof res.then === "function"; -var responseViaResponseObject = async (res, outgoing, options = {}) => { - if (isPromise2(res)) { - if (options.errorHandler) { - try { - res = await res; - } catch (err) { - const errRes = await options.errorHandler(err); - if (!errRes) { - return; - } - res = errRes; - } - } else { - res = await res.catch(handleFetchError); - } - } - if (cacheKey in res) { - return responseViaCache(res, outgoing); - } - const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); - if (res.body) { - const reader = res.body.getReader(); - const values = []; - let done = false; - let currentReadPromise = void 0; - if (resHeaderRecord["transfer-encoding"] !== "chunked") { - let maxReadCount = 2; - for (let i = 0; i < maxReadCount; i++) { - currentReadPromise || (currentReadPromise = reader.read()); - const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { - console.error(e); - done = true; - }); - if (!chunk) { - if (i === 1) { - await new Promise((resolve2) => setTimeout(resolve2)); - maxReadCount = 3; - continue; - } - break; - } - currentReadPromise = void 0; - if (chunk.value) { - values.push(chunk.value); - } - if (chunk.done) { - done = true; - break; - } - } - if (done && !("content-length" in resHeaderRecord)) { - resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); - } - } - outgoing.writeHead(res.status, resHeaderRecord); - values.forEach((value) => { - ; - outgoing.write(value); - }); - if (done) { - outgoing.end(); - } else { - if (values.length === 0) { - flushHeaders(outgoing); - } - await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); - } - } else if (resHeaderRecord[X_ALREADY_SENT]) { - } else { - outgoing.writeHead(res.status, resHeaderRecord); - outgoing.end(); - } - ; - outgoing[outgoingEnded]?.(); -}; -var getRequestListener = (fetchCallback, options = {}) => { - const autoCleanupIncoming = options.autoCleanupIncoming ?? true; - if (options.overrideGlobalObjects !== false && global.Request !== Request2) { - Object.defineProperty(global, "Request", { - value: Request2 - }); - Object.defineProperty(global, "Response", { - value: Response2 - }); - } - return async (incoming, outgoing) => { - let res, req; - try { - req = newRequest(incoming, options.hostname); - let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; - if (!incomingEnded) { - ; - incoming[wrapBodyStream] = true; - incoming.on("end", () => { - incomingEnded = true; - }); - if (incoming instanceof Http2ServerRequest2) { - ; - outgoing[outgoingEnded] = () => { - if (!incomingEnded) { - setTimeout(() => { - if (!incomingEnded) { - setTimeout(() => { - drainIncoming(incoming); - }); - } - }); - } - }; - } - outgoing.on("finish", () => { - if (!incomingEnded) { - drainIncoming(incoming); - } - }); - } - outgoing.on("close", () => { - const abortController = req[abortControllerKey]; - if (abortController) { - if (incoming.errored) { - req[abortControllerKey].abort(incoming.errored.toString()); - } else if (!outgoing.writableFinished) { - req[abortControllerKey].abort("Client connection prematurely closed."); - } - } - if (!incomingEnded) { - setTimeout(() => { - if (!incomingEnded) { - setTimeout(() => { - drainIncoming(incoming); - }); - } - }); - } - }); - res = fetchCallback(req, { incoming, outgoing }); - if (cacheKey in res) { - return responseViaCache(res, outgoing); - } - } catch (e) { - if (!res) { - if (options.errorHandler) { - res = await options.errorHandler(req ? e : toRequestError(e)); - if (!res) { - return; - } - } else if (!req) { - res = handleRequestError(); - } else { - res = handleFetchError(e); - } - } else { - return handleResponseError(e, outgoing); - } - } - try { - return await responseViaResponseObject(res, outgoing, options); - } catch (e) { - return handleResponseError(e, outgoing); - } - }; -}; - -// ../../packages/spec/dist/index.mjs -init_zod(); -var __defProp5 = Object.defineProperty; -var __export4 = (target, all) => { - for (var name in all) - __defProp5(target, name, { get: all[name], enumerable: true }); -}; -var shared_exports = {}; -__export4(shared_exports, { - AggregationFunctionEnum: () => AggregationFunctionEnum2, - AppNameSchema: () => AppNameSchema2, - BaseMetadataRecordSchema: () => BaseMetadataRecordSchema2, - CacheStrategyEnum: () => CacheStrategyEnum2, - CorsConfigSchema: () => CorsConfigSchema4, - EventNameSchema: () => EventNameSchema4, - FieldMappingSchema: () => FieldMappingSchema4, - FieldNameSchema: () => FieldNameSchema2, - FlowNameSchema: () => FlowNameSchema2, - HttpMethod: () => HttpMethod5, - HttpMethodSchema: () => HttpMethodSchema5, - HttpRequestSchema: () => HttpRequestSchema4, - IsolationLevelEnum: () => IsolationLevelEnum3, - MAP_SUPPORTED_FIELDS: () => MAP_SUPPORTED_FIELDS, - METADATA_ALIASES: () => METADATA_ALIASES, - MetadataFormatSchema: () => MetadataFormatSchema5, - MutationEventEnum: () => MutationEventEnum2, - ObjectNameSchema: () => ObjectNameSchema2, - PLURAL_TO_SINGULAR: () => PLURAL_TO_SINGULAR2, - RateLimitConfigSchema: () => RateLimitConfigSchema4, - RoleNameSchema: () => RoleNameSchema2, - SINGULAR_TO_PLURAL: () => SINGULAR_TO_PLURAL2, - SnakeCaseIdentifierSchema: () => SnakeCaseIdentifierSchema7, - SortDirectionEnum: () => SortDirectionEnum4, - SortItemSchema: () => SortItemSchema3, - StaticMountSchema: () => StaticMountSchema4, - SystemIdentifierSchema: () => SystemIdentifierSchema6, - TransformTypeSchema: () => TransformTypeSchema3, - ViewNameSchema: () => ViewNameSchema2, - findClosestMatches: () => findClosestMatches, - formatSuggestion: () => formatSuggestion, - formatZodError: () => formatZodError, - formatZodIssue: () => formatZodIssue, - levenshteinDistance: () => levenshteinDistance, - normalizeMetadataCollection: () => normalizeMetadataCollection, - normalizePluginMetadata: () => normalizePluginMetadata, - normalizeStackInput: () => normalizeStackInput, - objectStackErrorMap: () => objectStackErrorMap, - pluralToSingular: () => pluralToSingular2, - safeParsePretty: () => safeParsePretty, - singularToPlural: () => singularToPlural, - suggestFieldType: () => suggestFieldType -}); -var SystemIdentifierSchema6 = external_exports.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")' -}).describe("System identifier (lowercase with underscores or dots)"); -var SnakeCaseIdentifierSchema7 = external_exports.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, { - message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")' -}).describe("Snake case identifier (lowercase with underscores only)"); -var EventNameSchema4 = external_exports.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, { - message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")' -}).describe("Event name (lowercase with dot notation for namespacing)"); -var TransformTypeSchema3 = external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("constant"), - value: external_exports.unknown().describe("Constant value to use") - }).describe("Set a constant value"), - external_exports.object({ - type: external_exports.literal("cast"), - targetType: external_exports.enum(["string", "number", "boolean", "date"]).describe("Target data type") - }).describe("Cast to a specific data type"), - external_exports.object({ - type: external_exports.literal("lookup"), - table: external_exports.string().describe("Lookup table name"), - keyField: external_exports.string().describe("Field to match on"), - valueField: external_exports.string().describe("Field to retrieve") - }).describe("Lookup value from another table"), - external_exports.object({ - type: external_exports.literal("javascript"), - expression: external_exports.string().describe('JavaScript expression (e.g., "value.toUpperCase()")') - }).describe("Custom JavaScript transformation"), - external_exports.object({ - type: external_exports.literal("map"), - mappings: external_exports.record(external_exports.string(), external_exports.unknown()).describe('Value mappings (e.g., {"Active": "active"})') - }).describe("Map values using a dictionary") -]); -var FieldMappingSchema4 = external_exports.object({ - /** - * Source field name - */ - source: external_exports.string().describe("Source field name"), - /** - * Target field name (should be snake_case for ObjectStack) - */ - target: external_exports.string().describe("Target field name"), - /** - * Transformation to apply - */ - transform: TransformTypeSchema3.optional().describe("Transformation to apply"), - /** - * Default value if source is null/undefined - */ - defaultValue: external_exports.unknown().optional().describe("Default if source is null/undefined") -}); -var HttpMethod5 = external_exports.enum([ - "GET", - "POST", - "PUT", - "DELETE", - "PATCH", - "HEAD", - "OPTIONS" -]); -var HttpMethodSchema5 = external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]); -var HttpRequestSchema4 = external_exports.object({ - url: external_exports.string().describe("API endpoint URL"), - method: HttpMethodSchema5.optional().default("GET").describe("HTTP method"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters"), - body: external_exports.unknown().optional().describe("Request body for POST/PUT/PATCH") -}); -var CorsConfigSchema4 = external_exports.object({ - /** - * Enable CORS - */ - enabled: external_exports.boolean().default(true).describe("Enable CORS"), - /** - * Allowed origins (* for all) - */ - origins: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.string()) - ]).default("*").describe("Allowed origins (* for all)"), - /** - * Allowed HTTP methods - */ - methods: external_exports.array(HttpMethod5).optional().describe("Allowed HTTP methods"), - /** - * Allow credentials (cookies, authorization headers) - */ - credentials: external_exports.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"), - /** - * Preflight cache duration in seconds - */ - maxAge: external_exports.number().int().optional().describe("Preflight cache duration in seconds") -}); -var RateLimitConfigSchema4 = external_exports.object({ - /** - * Enable rate limiting - */ - enabled: external_exports.boolean().default(false).describe("Enable rate limiting"), - /** - * Time window in milliseconds - */ - windowMs: external_exports.number().int().default(6e4).describe("Time window in milliseconds"), - /** - * Max requests per window - */ - maxRequests: external_exports.number().int().default(100).describe("Max requests per window") -}); -var StaticMountSchema4 = external_exports.object({ - /** - * URL path to serve from - */ - path: external_exports.string().describe("URL path to serve from"), - /** - * Physical directory to serve - */ - directory: external_exports.string().describe("Physical directory to serve"), - /** - * Cache-Control header value - */ - cacheControl: external_exports.string().optional().describe("Cache-Control header value") -}); -var AggregationFunctionEnum2 = external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "percentile", - "median", - "stddev", - "variance" -]).describe("Standard aggregation functions"); -var SortDirectionEnum4 = external_exports.enum(["asc", "desc"]).describe("Sort order direction"); -var SortItemSchema3 = external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - order: SortDirectionEnum4.describe("Sort direction") -}).describe("Sort field and direction pair"); -var MutationEventEnum2 = external_exports.enum([ - "insert", - "update", - "delete", - "upsert" -]).describe("Data mutation event types"); -var IsolationLevelEnum3 = external_exports.enum([ - "read_uncommitted", - "read_committed", - "repeatable_read", - "serializable", - "snapshot" -]).describe("Transaction isolation levels (snake_case standard)"); -var CacheStrategyEnum2 = external_exports.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy"); -var MetadataFormatSchema5 = external_exports.enum(["yaml", "json", "typescript", "javascript"]).describe("Metadata file format"); -var BaseMetadataRecordSchema2 = external_exports.object({ - id: external_exports.string().describe("Unique metadata record identifier"), - type: external_exports.string().describe('Metadata type (e.g. "object", "view", "flow")'), - name: SnakeCaseIdentifierSchema7.describe("Machine name (snake_case)"), - format: MetadataFormatSchema5.optional().describe("Source file format") -}).describe("Base metadata record fields shared across kernel and system"); -var ObjectNameSchema2 = SnakeCaseIdentifierSchema7.brand().describe("Branded object name (snake_case, no dots)"); -var FieldNameSchema2 = SnakeCaseIdentifierSchema7.brand().describe("Branded field name (snake_case, no dots)"); -var ViewNameSchema2 = SystemIdentifierSchema6.brand().describe("Branded view name (system identifier)"); -var AppNameSchema2 = SystemIdentifierSchema6.brand().describe("Branded app name (system identifier)"); -var FlowNameSchema2 = SystemIdentifierSchema6.brand().describe("Branded flow name (system identifier)"); -var RoleNameSchema2 = SystemIdentifierSchema6.brand().describe("Branded role name (system identifier)"); -var EncryptionAlgorithmSchema6 = external_exports.enum([ - "aes-256-gcm", - "aes-256-cbc", - "chacha20-poly1305" -]).describe("Supported encryption algorithm"); -var KeyManagementProviderSchema6 = external_exports.enum([ - "local", - "aws-kms", - "azure-key-vault", - "gcp-kms", - "hashicorp-vault" -]).describe("Key management service provider"); -var KeyRotationPolicySchema6 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable automatic key rotation"), - frequencyDays: external_exports.number().min(1).default(90).describe("Rotation frequency in days"), - retainOldVersions: external_exports.number().default(3).describe("Number of old key versions to retain"), - autoRotate: external_exports.boolean().default(true).describe("Automatically rotate without manual approval") -}).describe("Policy for automatic encryption key rotation"); -var EncryptionConfigSchema6 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable field-level encryption"), - algorithm: EncryptionAlgorithmSchema6.default("aes-256-gcm").describe("Encryption algorithm"), - keyManagement: external_exports.object({ - provider: KeyManagementProviderSchema6.describe("Key management service provider"), - keyId: external_exports.string().optional().describe("Key identifier in the provider"), - rotationPolicy: KeyRotationPolicySchema6.optional().describe("Key rotation policy") - }).describe("Key management configuration"), - scope: external_exports.enum(["field", "record", "table", "database"]).describe("Encryption scope level"), - deterministicEncryption: external_exports.boolean().default(false).describe("Allows equality queries on encrypted data"), - searchableEncryption: external_exports.boolean().default(false).describe("Allows search on encrypted data") -}).describe("Field-level encryption configuration"); -var FieldEncryptionSchema2 = external_exports.object({ - fieldName: external_exports.string().describe("Name of the field to encrypt"), - encryptionConfig: EncryptionConfigSchema6.describe("Encryption settings for this field"), - indexable: external_exports.boolean().default(false).describe("Allow indexing on encrypted field") -}).describe("Per-field encryption assignment"); -var MaskingStrategySchema6 = external_exports.enum([ - "redact", - // Complete redaction: **** - "partial", - // Partial masking: 138****5678 - "hash", - // Hash value: sha256(value) - "tokenize", - // Tokenization: token-12345 - "randomize", - // Randomize: generate random value - "nullify", - // Null value: null - "substitute" - // Substitute with dummy data -]).describe("Data masking strategy for PII protection"); -var MaskingRuleSchema6 = external_exports.object({ - field: external_exports.string().describe("Field name to apply masking to"), - strategy: MaskingStrategySchema6.describe("Masking strategy to use"), - pattern: external_exports.string().optional().describe("Regex pattern for partial masking"), - preserveFormat: external_exports.boolean().default(true).describe("Keep the original data format after masking"), - preserveLength: external_exports.boolean().default(true).describe("Keep the original data length after masking"), - roles: external_exports.array(external_exports.string()).optional().describe("Roles that see masked data"), - exemptRoles: external_exports.array(external_exports.string()).optional().describe("Roles that see unmasked data") -}).describe("Masking rule for a single field"); -var MaskingConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable data masking"), - rules: external_exports.array(MaskingRuleSchema6).describe("List of field-level masking rules"), - auditUnmasking: external_exports.boolean().default(true).describe("Log when masked data is accessed unmasked") -}).describe("Top-level data masking configuration for PII protection"); -var FieldType6 = external_exports.enum([ - // Core Text - "text", - "textarea", - "email", - "url", - "phone", - "password", - // Rich Content - "markdown", - "html", - "richtext", - // Numbers - "number", - "currency", - "percent", - // Date & Time - "date", - "datetime", - "time", - // Logic - "boolean", - "toggle", - // Toggle is a distinct UI from checkbox - // Selection - "select", - // Single select dropdown - "multiselect", - // Multi select (often tags) - "radio", - // Radio group - "checkboxes", - // Checkbox group - // Relational - "lookup", - "master_detail", - // Dynamic reference - "tree", - // Hierarchical reference - // Media - "image", - "file", - "avatar", - "video", - "audio", - // Calculated / System - "formula", - "summary", - "autonumber", - // Enhanced Types - "location", - // GPS coordinates - "address", - // Structured address - "code", - // Code editor (JSON/SQL/JS) - "json", - // Structured JSON data - "color", - // Color picker - "rating", - // Star rating - "slider", - // Numeric slider - "signature", - // Digital signature - "qrcode", - // QR code / Barcode - "progress", - // Progress bar - "tags", - // Simple tag list - // AI/ML Types - "vector" - // Vector embeddings for AI/ML (semantic search, RAG) -]); -var SelectOptionSchema6 = external_exports.object({ - label: external_exports.string().describe("Display label (human-readable, any case allowed)"), - value: SystemIdentifierSchema6.describe("Stored value (lowercase machine identifier)"), - color: external_exports.string().optional().describe("Color code for badges/charts"), - default: external_exports.boolean().optional().describe("Is default option") -}); -var LocationCoordinatesSchema2 = external_exports.object({ - latitude: external_exports.number().min(-90).max(90).describe("Latitude coordinate"), - longitude: external_exports.number().min(-180).max(180).describe("Longitude coordinate"), - altitude: external_exports.number().optional().describe("Altitude in meters"), - accuracy: external_exports.number().optional().describe("Accuracy in meters") -}); -var CurrencyConfigSchema6 = external_exports.object({ - precision: external_exports.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"), - currencyMode: external_exports.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"), - defaultCurrency: external_exports.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)") -}); -var CurrencyValueSchema2 = external_exports.object({ - value: external_exports.number().describe("Monetary amount"), - currency: external_exports.string().length(3).describe("Currency code (ISO 4217)") -}); -var AddressSchema2 = external_exports.object({ - street: external_exports.string().optional().describe("Street address"), - city: external_exports.string().optional().describe("City name"), - state: external_exports.string().optional().describe("State/Province"), - postalCode: external_exports.string().optional().describe("Postal/ZIP code"), - country: external_exports.string().optional().describe("Country name or code"), - countryCode: external_exports.string().optional().describe("ISO country code (e.g., US, GB)"), - formatted: external_exports.string().optional().describe("Formatted address string") -}); -var VectorConfigSchema6 = external_exports.object({ - dimensions: external_exports.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"), - distanceMetric: external_exports.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"), - normalized: external_exports.boolean().default(false).describe("Whether vectors are normalized (unit length)"), - indexed: external_exports.boolean().default(true).describe("Whether to create a vector index for fast similarity search"), - indexType: external_exports.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)") -}); -var FileAttachmentConfigSchema6 = external_exports.object({ - /** File Size Limits */ - minSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), - maxSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"), - /** File Type Restrictions */ - allowedTypes: external_exports.array(external_exports.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'), - blockedTypes: external_exports.array(external_exports.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'), - allowedMimeTypes: external_exports.array(external_exports.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'), - blockedMimeTypes: external_exports.array(external_exports.string()).optional().describe("Blocked MIME types"), - /** Virus Scanning */ - virusScan: external_exports.boolean().default(false).describe("Enable virus scanning for uploaded files"), - virusScanProvider: external_exports.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"), - virusScanOnUpload: external_exports.boolean().default(true).describe("Scan files immediately on upload"), - quarantineOnThreat: external_exports.boolean().default(true).describe("Quarantine files if threat detected"), - /** Storage Configuration */ - storageProvider: external_exports.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"), - storageBucket: external_exports.string().optional().describe("Target bucket name"), - storagePrefix: external_exports.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'), - /** Image-Specific Validation */ - imageValidation: external_exports.object({ - minWidth: external_exports.number().min(1).optional().describe("Minimum image width in pixels"), - maxWidth: external_exports.number().min(1).optional().describe("Maximum image width in pixels"), - minHeight: external_exports.number().min(1).optional().describe("Minimum image height in pixels"), - maxHeight: external_exports.number().min(1).optional().describe("Maximum image height in pixels"), - aspectRatio: external_exports.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'), - generateThumbnails: external_exports.boolean().default(false).describe("Auto-generate thumbnails"), - thumbnailSizes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'), - width: external_exports.number().min(1).describe("Thumbnail width in pixels"), - height: external_exports.number().min(1).describe("Thumbnail height in pixels"), - crop: external_exports.boolean().default(false).describe("Crop to exact dimensions") - })).optional().describe("Thumbnail size configurations"), - preserveMetadata: external_exports.boolean().default(false).describe("Preserve EXIF metadata"), - autoRotate: external_exports.boolean().default(true).describe("Auto-rotate based on EXIF orientation") - }).optional().describe("Image-specific validation rules"), - /** Upload Behavior */ - allowMultiple: external_exports.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"), - allowReplace: external_exports.boolean().default(true).describe("Allow replacing existing files"), - allowDelete: external_exports.boolean().default(true).describe("Allow deleting uploaded files"), - requireUpload: external_exports.boolean().default(false).describe("Require at least one file when field is required"), - /** Metadata Extraction */ - extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"), - extractText: external_exports.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"), - /** Versioning */ - versioningEnabled: external_exports.boolean().default(false).describe("Keep previous versions of replaced files"), - maxVersions: external_exports.number().min(1).optional().describe("Maximum number of versions to retain"), - /** Access Control */ - publicRead: external_exports.boolean().default(false).describe("Allow public read access to uploaded files"), - presignedUrlExpiry: external_exports.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)") -}).refine((data) => { - if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) { - return false; - } - return true; -}, { - message: "minSize must be less than or equal to maxSize" -}).refine((data) => { - if (data.virusScanProvider !== void 0 && data.virusScan !== true) { - return false; - } - return true; -}, { - message: "virusScanProvider requires virusScan to be enabled" -}); -var DataQualityRulesSchema6 = external_exports.object({ - /** Enforce uniqueness constraint */ - uniqueness: external_exports.boolean().default(false).describe("Enforce unique values across all records"), - /** Completeness ratio (0-1) indicating minimum percentage of non-null values */ - completeness: external_exports.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"), - /** Accuracy validation against authoritative source */ - accuracy: external_exports.object({ - source: external_exports.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'), - threshold: external_exports.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)") - }).optional().describe("Accuracy validation configuration") -}); -var ComputedFieldCacheSchema6 = external_exports.object({ - /** Enable caching for this computed field */ - enabled: external_exports.boolean().describe("Enable caching for computed field results"), - /** Time-to-live in seconds */ - ttl: external_exports.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"), - /** Array of field paths that trigger cache invalidation when changed */ - invalidateOn: external_exports.array(external_exports.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])') -}); -var FieldSchema5 = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(), - label: external_exports.string().optional().describe("Human readable label"), - type: FieldType6.describe("Field Data Type"), - description: external_exports.string().optional().describe("Tooltip/Help text"), - format: external_exports.string().optional().describe("Format string (e.g. email, phone)"), - /** Storage Layer Mapping */ - columnName: external_exports.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."), - /** Database Constraints */ - required: external_exports.boolean().default(false).describe("Is required"), - searchable: external_exports.boolean().default(false).describe("Is searchable"), - multiple: external_exports.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."), - unique: external_exports.boolean().default(false).describe("Is unique constraint"), - defaultValue: external_exports.unknown().optional().describe("Default value"), - /** Text/String Constraints */ - maxLength: external_exports.number().optional().describe("Max character length"), - minLength: external_exports.number().optional().describe("Min character length"), - /** Number Constraints */ - precision: external_exports.number().optional().describe("Total digits"), - scale: external_exports.number().optional().describe("Decimal places"), - min: external_exports.number().optional().describe("Minimum value"), - max: external_exports.number().optional().describe("Maximum value"), - /** Selection Options */ - options: external_exports.array(SelectOptionSchema6).optional().describe("Static options for select/multiselect"), - /** - * Relationship Config - * - * Used by `lookup` and `master_detail` field types to define cross-object references. - * The `reference` property is **required** for these types — it identifies the target - * object whose records this field links to. The engine uses `reference` during $expand - * post-processing to resolve foreign key IDs into full related objects via batch queries. - * - * For `master_detail` fields, the parent record controls the lifecycle of child records - * (e.g., cascade delete). For `lookup` fields, the reference is a soft link. - */ - reference: external_exports.string().optional().describe( - "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects." - ), - referenceFilters: external_exports.array(external_exports.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'), - writeRequiresMasterRead: external_exports.boolean().optional().describe("If true, user needs read access to master record to edit this field"), - deleteBehavior: external_exports.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"), - /** Calculation */ - expression: external_exports.string().optional().describe("Formula expression"), - summaryOperations: external_exports.object({ - object: external_exports.string().describe("Source child object name for roll-up"), - field: external_exports.string().describe("Field on child object to aggregate"), - function: external_exports.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply") - }).optional().describe("Roll-up summary definition"), - /** Enhanced Field Type Configurations */ - // Code field config - language: external_exports.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"), - theme: external_exports.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"), - lineNumbers: external_exports.boolean().optional().describe("Show line numbers in code editor"), - // Rating field config - maxRating: external_exports.number().optional().describe("Maximum rating value (default: 5)"), - allowHalf: external_exports.boolean().optional().describe("Allow half-star ratings"), - // Location field config - displayMap: external_exports.boolean().optional().describe("Display map widget for location field"), - allowGeocoding: external_exports.boolean().optional().describe("Allow address-to-coordinate conversion"), - // Address field config - addressFormat: external_exports.enum(["us", "uk", "international"]).optional().describe("Address format template"), - // Color field config - colorFormat: external_exports.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"), - allowAlpha: external_exports.boolean().optional().describe("Allow transparency/alpha channel"), - presetColors: external_exports.array(external_exports.string()).optional().describe("Preset color options"), - // Slider field config - step: external_exports.number().optional().describe("Step increment for slider (default: 1)"), - showValue: external_exports.boolean().optional().describe("Display current value on slider"), - marks: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'), - // QR Code / Barcode field config - // Note: qrErrorCorrection is only applicable when barcodeFormat='qr' - // Runtime validation should enforce this constraint - barcodeFormat: external_exports.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"), - qrErrorCorrection: external_exports.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'), - displayValue: external_exports.boolean().optional().describe("Display human-readable value below barcode/QR code"), - allowScanning: external_exports.boolean().optional().describe("Enable camera scanning for barcode/QR code input"), - // Currency field config - currencyConfig: CurrencyConfigSchema6.optional().describe("Configuration for currency field type"), - // Vector field config - vectorConfig: VectorConfigSchema6.optional().describe("Configuration for vector field type (AI/ML embeddings)"), - // File attachment field config - fileAttachmentConfig: FileAttachmentConfigSchema6.optional().describe("Configuration for file and attachment field types"), - /** Enhanced Security & Compliance */ - // Encryption configuration - encryptionConfig: EncryptionConfigSchema6.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"), - // Data masking rules - maskingRule: MaskingRuleSchema6.optional().describe("Data masking rules for PII protection"), - // Audit trail - auditTrail: external_exports.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"), - /** Field Dependencies & Relationships */ - // Field dependencies - dependencies: external_exports.array(external_exports.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"), - /** Computed Field Optimization */ - // Computed field caching - cached: ComputedFieldCacheSchema6.optional().describe("Caching configuration for computed/formula fields"), - /** Data Quality & Governance */ - // Data quality rules - dataQuality: DataQualityRulesSchema6.optional().describe("Data quality validation and monitoring rules"), - /** Layout & Grouping */ - group: external_exports.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'), - /** Conditional Requirements */ - conditionalRequired: external_exports.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`), - /** Security & Visibility */ - hidden: external_exports.boolean().default(false).describe("Hidden from default UI"), - readonly: external_exports.boolean().default(false).describe("Read-only in UI"), - sortable: external_exports.boolean().optional().default(true).describe("Whether field is sortable in list views"), - inlineHelpText: external_exports.string().optional().describe("Help text displayed below the field in forms"), - trackFeedHistory: external_exports.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"), - caseSensitive: external_exports.boolean().optional().describe("Whether text comparisons are case-sensitive"), - autonumberFormat: external_exports.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'), - /** Indexing */ - index: external_exports.boolean().default(false).describe("Create standard database index"), - externalId: external_exports.boolean().default(false).describe("Is external ID for upsert operations") -}); -var Field2 = { - text: (config4 = {}) => ({ type: "text", ...config4 }), - textarea: (config4 = {}) => ({ type: "textarea", ...config4 }), - number: (config4 = {}) => ({ type: "number", ...config4 }), - boolean: (config4 = {}) => ({ type: "boolean", ...config4 }), - date: (config4 = {}) => ({ type: "date", ...config4 }), - datetime: (config4 = {}) => ({ type: "datetime", ...config4 }), - currency: (config4 = {}) => ({ type: "currency", ...config4 }), - percent: (config4 = {}) => ({ type: "percent", ...config4 }), - url: (config4 = {}) => ({ type: "url", ...config4 }), - email: (config4 = {}) => ({ type: "email", ...config4 }), - phone: (config4 = {}) => ({ type: "phone", ...config4 }), - image: (config4 = {}) => ({ type: "image", ...config4 }), - file: (config4 = {}) => ({ type: "file", ...config4 }), - avatar: (config4 = {}) => ({ type: "avatar", ...config4 }), - formula: (config4 = {}) => ({ type: "formula", ...config4 }), - summary: (config4 = {}) => ({ type: "summary", ...config4 }), - autonumber: (config4 = {}) => ({ type: "autonumber", ...config4 }), - markdown: (config4 = {}) => ({ type: "markdown", ...config4 }), - html: (config4 = {}) => ({ type: "html", ...config4 }), - password: (config4 = {}) => ({ type: "password", ...config4 }), - /** - * Select field helper with backward-compatible API - * - * Automatically converts option values to lowercase to enforce naming conventions. - * - * @example Old API (array first) - auto-converts to lowercase - * Field.select(['High', 'Low'], { label: 'Priority' }) - * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }] - * - * @example New API (config object) - enforces lowercase - * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' }) - * - * @example Multi-word values - converts to snake_case - * Field.select(['In Progress', 'Closed Won'], { label: 'Status' }) - * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }] - */ - select: (optionsOrConfig, config4) => { - const toSnakeCase = (str) => { - return str.toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, ""); - }; - let options; - let finalConfig; - if (Array.isArray(optionsOrConfig)) { - options = optionsOrConfig.map( - (o) => typeof o === "string" ? { label: o, value: toSnakeCase(o) } : { ...o, value: o.value.toLowerCase() } - // Ensure value is lowercase - ); - finalConfig = config4 || {}; - } else { - options = (optionsOrConfig.options || []).map( - (o) => typeof o === "string" ? { label: o, value: toSnakeCase(o) } : { ...o, value: o.value.toLowerCase() } - // Ensure value is lowercase - ); - const { options: _, ...restConfig } = optionsOrConfig; - finalConfig = restConfig; - } - return { type: "select", options, ...finalConfig }; - }, - lookup: (reference, config4 = {}) => ({ - type: "lookup", - reference, - ...config4 - }), - masterDetail: (reference, config4 = {}) => ({ - type: "master_detail", - reference, - ...config4 - }), - // Enhanced Field Type Helpers - location: (config4 = {}) => ({ - type: "location", - ...config4 - }), - address: (config4 = {}) => ({ - type: "address", - ...config4 - }), - richtext: (config4 = {}) => ({ - type: "richtext", - ...config4 - }), - code: (language, config4 = {}) => ({ - type: "code", - language, - ...config4 - }), - color: (config4 = {}) => ({ - type: "color", - ...config4 - }), - rating: (maxRating = 5, config4 = {}) => ({ - type: "rating", - maxRating, - ...config4 - }), - signature: (config4 = {}) => ({ - type: "signature", - ...config4 - }), - slider: (config4 = {}) => ({ - type: "slider", - ...config4 - }), - qrcode: (config4 = {}) => ({ - type: "qrcode", - ...config4 - }), - json: (config4 = {}) => ({ - type: "json", - ...config4 - }), - vector: (dimensions, config4 = {}) => ({ - type: "vector", - vectorConfig: { - dimensions, - distanceMetric: "cosine", - normalized: false, - indexed: true, - ...config4.vectorConfig - }, - ...config4 - }) -}; -function levenshteinDistance(a, b) { - const la = a.length; - const lb = b.length; - if (la === 0) return lb; - if (lb === 0) return la; - let prev = new Array(lb + 1); - let curr = new Array(lb + 1); - for (let j = 0; j <= lb; j++) { - prev[j] = j; - } - for (let i = 1; i <= la; i++) { - curr[0] = i; - for (let j = 1; j <= lb; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - curr[j] = Math.min( - prev[j] + 1, - // deletion - curr[j - 1] + 1, - // insertion - prev[j - 1] + cost - // substitution - ); - } - [prev, curr] = [curr, prev]; - } - return prev[lb]; -} -function findClosestMatches(input, candidates, maxDistance = 3, maxResults = 3) { - const normalized = input.toLowerCase().replace(/[-\s]/g, "_"); - const scored = candidates.map((candidate) => ({ - value: candidate, - distance: levenshteinDistance(normalized, candidate) - })).filter((s) => s.distance <= maxDistance && s.distance > 0).sort((a, b) => a.distance - b.distance); - return scored.slice(0, maxResults).map((s) => s.value); -} -var FIELD_TYPE_ALIASES = { - // Common alternative names - string: "text", - str: "text", - varchar: "text", - char: "text", - int: "number", - integer: "number", - float: "number", - double: "number", - decimal: "number", - numeric: "number", - bool: "boolean", - checkbox: "boolean", - check: "boolean", - date_time: "datetime", - timestamp: "datetime", - // Common typos - text_area: "textarea", - textarea_: "textarea", - textfield: "text", - dropdown: "select", - picklist: "select", - enum: "select", - multi_select: "multiselect", - multiselect_: "multiselect", - reference: "lookup", - ref: "lookup", - foreign_key: "lookup", - fk: "lookup", - relation: "lookup", - master: "master_detail", - richtext_: "richtext", - rich_text: "richtext", - upload: "file", - attachment: "file", - photo: "image", - picture: "image", - img: "image", - percent_: "percent", - percentage: "percent", - money: "currency", - price: "currency", - auto_number: "autonumber", - auto_increment: "autonumber", - sequence: "autonumber", - markdown_: "markdown", - md: "markdown", - barcode: "qrcode", - tag: "tags", - star: "rating", - stars: "rating", - geo: "location", - gps: "location", - coordinates: "location", - embed: "vector", - embedding: "vector", - embeddings: "vector" -}; -function suggestFieldType(input) { - const normalized = input.toLowerCase().replace(/[-\s]/g, "_"); - const alias = FIELD_TYPE_ALIASES[normalized]; - if (alias) { - return [alias]; - } - return findClosestMatches(normalized, FieldType6.options); -} -function formatSuggestion(suggestions) { - if (suggestions.length === 0) return ""; - if (suggestions.length === 1) return `Did you mean '${suggestions[0]}'?`; - return `Did you mean one of: ${suggestions.map((s) => `'${s}'`).join(", ")}?`; -} -var objectStackErrorMap = (issue2) => { - if (issue2.code === "invalid_value") { - const values = issue2.values; - const input = issue2.input; - const received = String(input ?? ""); - const options = values.map(String); - const fieldTypeOptions = FieldType6.options; - const isFieldTypeEnum = options.length > 10 && fieldTypeOptions.every((ft) => options.includes(ft)); - if (isFieldTypeEnum) { - const suggestions2 = suggestFieldType(received); - const suggestion2 = formatSuggestion(suggestions2); - const base2 = `Invalid field type '${received}'.`; - return { - message: suggestion2 ? `${base2} ${suggestion2}` : `${base2} Valid types: ${options.slice(0, 10).join(", ")}...` - }; - } - const suggestions = findClosestMatches(received, options); - const suggestion = formatSuggestion(suggestions); - const base = `Invalid value '${received}'.`; - return { - message: suggestion ? `${base} ${suggestion}` : `${base} Expected one of: ${options.join(", ")}.` - }; - } - if (issue2.code === "too_small") { - const origin = issue2.origin; - const minimum = issue2.minimum; - if (origin === "string") { - return { - message: `Must be at least ${minimum} character${minimum === 1 ? "" : "s"} long.` - }; - } - } - if (issue2.code === "too_big") { - const origin = issue2.origin; - const maximum = issue2.maximum; - if (origin === "string") { - return { - message: `Must be at most ${maximum} character${maximum === 1 ? "" : "s"} long.` - }; - } - } - if (issue2.code === "invalid_format") { - const format = issue2.format; - const input = issue2.input; - if (format === "regex" && input) { - const pathArr = issue2.path; - const pathStr = pathArr?.join(".") ?? ""; - if (pathStr.endsWith("name") || pathStr === "name") { - return { - message: `Invalid identifier '${input}'. Must be lowercase snake_case (e.g., 'my_object', 'task_name'). No uppercase, spaces, or hyphens allowed.` - }; - } - } - } - if (issue2.code === "invalid_type") { - const expected = issue2.expected; - const input = issue2.input; - if (input === void 0) { - const pathArr = issue2.path; - const field = pathArr?.[pathArr.length - 1] ?? ""; - return { - message: `Required property '${field}' is missing.` - }; - } - const receivedType = input === null ? "null" : typeof input; - return { - message: `Expected ${expected} but received ${receivedType}.` - }; - } - if (issue2.code === "unrecognized_keys") { - const keys = issue2.keys; - const keyStr = keys.join(", "); - return { - message: `Unrecognized key${keys.length > 1 ? "s" : ""}: ${keyStr}. Check for typos in property names.` - }; - } - return null; -}; -function formatZodIssue(issue2) { - const path3 = issue2.path.length > 0 ? issue2.path.join(".") : "(root)"; - return ` \u2717 ${path3}: ${issue2.message}`; -} -function formatZodError(error49, label) { - const count = error49.issues.length; - const header = label ? `${label} (${count} issue${count === 1 ? "" : "s"}):` : `Validation failed (${count} issue${count === 1 ? "" : "s"}):`; - const lines = error49.issues.map(formatZodIssue); - return `${header} - -${lines.join("\n")}`; -} -function safeParsePretty(schema3, data, label) { - const result = schema3.safeParse(data, { error: objectStackErrorMap }); - if (result.success) { - return { success: true, data: result.data }; - } - return { - success: false, - error: result.error, - formatted: formatZodError(result.error, label) - }; -} -var MAP_SUPPORTED_FIELDS = [ - "objects", - "apps", - "pages", - "dashboards", - "reports", - "actions", - "themes", - "workflows", - "approvals", - "flows", - "roles", - "permissions", - "sharingRules", - "policies", - "apis", - "webhooks", - "agents", - "ragPipelines", - "hooks", - "mappings", - "analyticsCubes", - "connectors", - "datasources" -]; -var PLURAL_TO_SINGULAR2 = { - objects: "object", - apps: "app", - pages: "page", - dashboards: "dashboard", - reports: "report", - actions: "action", - themes: "theme", - workflows: "workflow", - approvals: "approval", - flows: "flow", - roles: "role", - permissions: "permission", - profiles: "profile", - sharingRules: "sharingRule", - policies: "policy", - apis: "api", - webhooks: "webhook", - agents: "agent", - ragPipelines: "ragPipeline", - hooks: "hook", - mappings: "mapping", - analyticsCubes: "analyticsCube", - connectors: "connector", - datasources: "datasource", - views: "view" -}; -var SINGULAR_TO_PLURAL2 = Object.fromEntries( - Object.entries(PLURAL_TO_SINGULAR2).map(([plural, singular]) => [singular, plural]) -); -function pluralToSingular2(key) { - return PLURAL_TO_SINGULAR2[key] ?? key; -} -function singularToPlural(key) { - return SINGULAR_TO_PLURAL2[key] ?? key; -} -function normalizeMetadataCollection(value, keyField = "name") { - if (value == null || Array.isArray(value)) return value; - if (typeof value === "object") { - return Object.entries(value).map(([key, item]) => { - if (item && typeof item === "object" && !Array.isArray(item)) { - const obj = item; - if (!(keyField in obj) || obj[keyField] === void 0) { - return { ...obj, [keyField]: key }; - } - return obj; - } - return item; - }); - } - return value; -} -function normalizeStackInput(input) { - const result = { ...input }; - for (const field of MAP_SUPPORTED_FIELDS) { - if (field in result) { - result[field] = normalizeMetadataCollection(result[field]); - } - } - return result; -} -var METADATA_ALIASES = { - triggers: "hooks" -}; -function normalizePluginMetadata(metadata) { - const result = { ...metadata }; - for (const [alias, canonical] of Object.entries(METADATA_ALIASES)) { - if (alias in result) { - const aliasValue = normalizeMetadataCollection(result[alias]); - const canonicalValue = normalizeMetadataCollection(result[canonical]); - if (Array.isArray(aliasValue)) { - result[canonical] = Array.isArray(canonicalValue) ? [...canonicalValue, ...aliasValue] : aliasValue; - } - delete result[alias]; - } - } - for (const field of MAP_SUPPORTED_FIELDS) { - if (field in result) { - result[field] = normalizeMetadataCollection(result[field]); - } - } - if (Array.isArray(result.plugins)) { - result.plugins = result.plugins.map((p) => { - if (p && typeof p === "object" && !Array.isArray(p)) { - return normalizePluginMetadata(p); - } - return p; - }); - } - return result; -} -var data_exports2 = {}; -__export4(data_exports2, { - ALL_OPERATORS: () => ALL_OPERATORS2, - AddressSchema: () => AddressSchema2, - AggregationFunction: () => AggregationFunction3, - AggregationMetricType: () => AggregationMetricType3, - AggregationNodeSchema: () => AggregationNodeSchema3, - AggregationPipelineSchema: () => AggregationPipelineSchema2, - AggregationStageSchema: () => AggregationStageSchema2, - AnalyticsQuerySchema: () => AnalyticsQuerySchema3, - ApiMethod: () => ApiMethod4, - AsyncValidationSchema: () => AsyncValidationSchema4, - BaseEngineOptionsSchema: () => BaseEngineOptionsSchema2, - CDCConfigSchema: () => CDCConfigSchema4, - ComparisonOperatorSchema: () => ComparisonOperatorSchema2, - ComputedFieldCacheSchema: () => ComputedFieldCacheSchema6, - ConditionalValidationSchema: () => ConditionalValidationSchema4, - ConsistencyLevelSchema: () => ConsistencyLevelSchema2, - CrossFieldValidationSchema: () => CrossFieldValidationSchema4, - CubeJoinSchema: () => CubeJoinSchema3, - CubeSchema: () => CubeSchema3, - CurrencyConfigSchema: () => CurrencyConfigSchema6, - CurrencyValueSchema: () => CurrencyValueSchema2, - CustomValidatorSchema: () => CustomValidatorSchema4, - DataEngineAggregateOptionsSchema: () => DataEngineAggregateOptionsSchema2, - DataEngineAggregateRequestSchema: () => DataEngineAggregateRequestSchema2, - DataEngineBatchRequestSchema: () => DataEngineBatchRequestSchema2, - DataEngineContractSchema: () => DataEngineContractSchema2, - DataEngineCountOptionsSchema: () => DataEngineCountOptionsSchema2, - DataEngineCountRequestSchema: () => DataEngineCountRequestSchema2, - DataEngineDeleteOptionsSchema: () => DataEngineDeleteOptionsSchema2, - DataEngineDeleteRequestSchema: () => DataEngineDeleteRequestSchema2, - DataEngineExecuteRequestSchema: () => DataEngineExecuteRequestSchema2, - DataEngineFilterSchema: () => DataEngineFilterSchema2, - DataEngineFindOneRequestSchema: () => DataEngineFindOneRequestSchema2, - DataEngineFindRequestSchema: () => DataEngineFindRequestSchema2, - DataEngineInsertOptionsSchema: () => DataEngineInsertOptionsSchema2, - DataEngineInsertRequestSchema: () => DataEngineInsertRequestSchema2, - DataEngineQueryOptionsSchema: () => DataEngineQueryOptionsSchema2, - DataEngineRequestSchema: () => DataEngineRequestSchema2, - DataEngineSortSchema: () => DataEngineSortSchema2, - DataEngineUpdateOptionsSchema: () => DataEngineUpdateOptionsSchema2, - DataEngineUpdateRequestSchema: () => DataEngineUpdateRequestSchema2, - DataEngineVectorFindRequestSchema: () => DataEngineVectorFindRequestSchema2, - DataQualityRulesSchema: () => DataQualityRulesSchema6, - DataTypeMappingSchema: () => DataTypeMappingSchema2, - DatasetLoadResultSchema: () => DatasetLoadResultSchema2, - DatasetMode: () => DatasetMode4, - DatasetSchema: () => DatasetSchema4, - DatasourceCapabilities: () => DatasourceCapabilities2, - DatasourceSchema: () => DatasourceSchema2, - DimensionSchema: () => DimensionSchema3, - DimensionType: () => DimensionType3, - DocumentSchema: () => DocumentSchema2, - DocumentSchemaValidationSchema: () => DocumentSchemaValidationSchema2, - DocumentTemplateSchema: () => DocumentTemplateSchema2, - DocumentVersionSchema: () => DocumentVersionSchema2, - DriverCapabilitiesSchema: () => DriverCapabilitiesSchema2, - DriverConfigSchema: () => DriverConfigSchema2, - DriverDefinitionSchema: () => DriverDefinitionSchema2, - DriverInterfaceSchema: () => DriverInterfaceSchema2, - DriverOptionsSchema: () => DriverOptionsSchema2, - DriverType: () => DriverType2, - ESignatureConfigSchema: () => ESignatureConfigSchema2, - EngineAggregateOptionsSchema: () => EngineAggregateOptionsSchema2, - EngineCountOptionsSchema: () => EngineCountOptionsSchema2, - EngineDeleteOptionsSchema: () => EngineDeleteOptionsSchema2, - EngineQueryOptionsSchema: () => EngineQueryOptionsSchema2, - EngineUpdateOptionsSchema: () => EngineUpdateOptionsSchema2, - EqualityOperatorSchema: () => EqualityOperatorSchema2, - ExternalDataSourceSchema: () => ExternalDataSourceSchema2, - ExternalFieldMappingSchema: () => ExternalFieldMappingSchema2, - ExternalLookupSchema: () => ExternalLookupSchema2, - FILTER_OPERATORS: () => FILTER_OPERATORS2, - FeedActorSchema: () => FeedActorSchema4, - FeedFilterMode: () => FeedFilterMode3, - FeedItemSchema: () => FeedItemSchema3, - FeedItemType: () => FeedItemType4, - FeedVisibility: () => FeedVisibility4, - Field: () => Field2, - FieldChangeEntrySchema: () => FieldChangeEntrySchema4, - FieldMappingSchema: () => FieldMappingSchema22, - FieldNodeSchema: () => FieldNodeSchema3, - FieldOperatorsSchema: () => FieldOperatorsSchema4, - FieldReferenceSchema: () => FieldReferenceSchema4, - FieldSchema: () => FieldSchema5, - FieldType: () => FieldType6, - FileAttachmentConfigSchema: () => FileAttachmentConfigSchema6, - FilterConditionSchema: () => FilterConditionSchema4, - FormatValidationSchema: () => FormatValidationSchema4, - FullTextSearchSchema: () => FullTextSearchSchema3, - HookContextSchema: () => HookContextSchema2, - HookEvent: () => HookEvent2, - HookSchema: () => HookSchema2, - IndexSchema: () => IndexSchema4, - JSONValidationSchema: () => JSONValidationSchema4, - JoinNodeSchema: () => JoinNodeSchema3, - JoinStrategy: () => JoinStrategy3, - JoinType: () => JoinType3, - LOGICAL_OPERATORS: () => LOGICAL_OPERATORS2, - LocationCoordinatesSchema: () => LocationCoordinatesSchema2, - MappingSchema: () => MappingSchema2, - MentionSchema: () => MentionSchema4, - MetricSchema: () => MetricSchema3, - NoSQLDataTypeMappingSchema: () => NoSQLDataTypeMappingSchema2, - NoSQLDatabaseTypeSchema: () => NoSQLDatabaseTypeSchema2, - NoSQLDriverConfigSchema: () => NoSQLDriverConfigSchema2, - NoSQLIndexSchema: () => NoSQLIndexSchema2, - NoSQLIndexTypeSchema: () => NoSQLIndexTypeSchema2, - NoSQLOperationTypeSchema: () => NoSQLOperationTypeSchema2, - NoSQLQueryOptionsSchema: () => NoSQLQueryOptionsSchema2, - NoSQLTransactionOptionsSchema: () => NoSQLTransactionOptionsSchema2, - NormalizedFilterSchema: () => NormalizedFilterSchema4, - NotificationChannel: () => NotificationChannel3, - ObjectCapabilities: () => ObjectCapabilities4, - ObjectDependencyGraphSchema: () => ObjectDependencyGraphSchema2, - ObjectDependencyNodeSchema: () => ObjectDependencyNodeSchema2, - ObjectExtensionSchema: () => ObjectExtensionSchema2, - ObjectOwnershipEnum: () => ObjectOwnershipEnum2, - ObjectSchema: () => ObjectSchema4, - PartitioningConfigSchema: () => PartitioningConfigSchema4, - PoolConfigSchema: () => PoolConfigSchema2, - QueryFilterSchema: () => QueryFilterSchema2, - QuerySchema: () => QuerySchema3, - RangeOperatorSchema: () => RangeOperatorSchema2, - ReactionSchema: () => ReactionSchema4, - RecordSubscriptionSchema: () => RecordSubscriptionSchema3, - ReferenceResolutionErrorSchema: () => ReferenceResolutionErrorSchema2, - ReferenceResolutionSchema: () => ReferenceResolutionSchema2, - ReplicationConfigSchema: () => ReplicationConfigSchema2, - SQLDialectSchema: () => SQLDialectSchema2, - SQLDriverConfigSchema: () => SQLDriverConfigSchema2, - SQLiteAlterTableLimitations: () => SQLiteAlterTableLimitations2, - SQLiteDataTypeMappingDefaults: () => SQLiteDataTypeMappingDefaults2, - SSLConfigSchema: () => SSLConfigSchema2, - ScriptValidationSchema: () => ScriptValidationSchema4, - SearchConfigSchema: () => SearchConfigSchema5, - SeedLoaderConfigSchema: () => SeedLoaderConfigSchema2, - SeedLoaderRequestSchema: () => SeedLoaderRequestSchema2, - SeedLoaderResultSchema: () => SeedLoaderResultSchema2, - SelectOptionSchema: () => SelectOptionSchema6, - SetOperatorSchema: () => SetOperatorSchema2, - ShardingConfigSchema: () => ShardingConfigSchema2, - SoftDeleteConfigSchema: () => SoftDeleteConfigSchema4, - SortNodeSchema: () => SortNodeSchema3, - SpecialOperatorSchema: () => SpecialOperatorSchema2, - StateMachineValidationSchema: () => StateMachineValidationSchema4, - StringOperatorSchema: () => StringOperatorSchema2, - SubscriptionEventType: () => SubscriptionEventType3, - TenancyConfigSchema: () => TenancyConfigSchema4, - TenantDatabaseLifecycleSchema: () => TenantDatabaseLifecycleSchema2, - TenantResolverStrategySchema: () => TenantResolverStrategySchema2, - TimeUpdateInterval: () => TimeUpdateInterval3, - TransformType: () => TransformType2, - TursoGroupSchema: () => TursoGroupSchema2, - TursoMultiTenantConfigSchema: () => TursoMultiTenantConfigSchema2, - UniquenessValidationSchema: () => UniquenessValidationSchema4, - VALID_AST_OPERATORS: () => VALID_AST_OPERATORS2, - ValidationRuleSchema: () => ValidationRuleSchema4, - VectorConfigSchema: () => VectorConfigSchema6, - VersioningConfigSchema: () => VersioningConfigSchema4, - WindowFunction: () => WindowFunction3, - WindowFunctionNodeSchema: () => WindowFunctionNodeSchema3, - WindowSpecSchema: () => WindowSpecSchema3, - isFilterAST: () => isFilterAST2, - parseFilterAST: () => parseFilterAST2 -}); -var FieldReferenceSchema4 = external_exports.object({ - $field: external_exports.string().describe("Field Reference/Column Name") -}); -var EqualityOperatorSchema2 = external_exports.object({ - /** Equal to (default) - SQL: = | MongoDB: $eq */ - $eq: external_exports.any().optional(), - /** Not equal to - SQL: <> or != | MongoDB: $ne */ - $ne: external_exports.any().optional() -}); -var ComparisonOperatorSchema2 = external_exports.object({ - /** Greater than - SQL: > | MongoDB: $gt */ - $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), - /** Greater than or equal to - SQL: >= | MongoDB: $gte */ - $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), - /** Less than - SQL: < | MongoDB: $lt */ - $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), - /** Less than or equal to - SQL: <= | MongoDB: $lte */ - $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional() -}); -var SetOperatorSchema2 = external_exports.object({ - /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */ - $in: external_exports.array(external_exports.any()).optional(), - /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */ - $nin: external_exports.array(external_exports.any()).optional() -}); -var RangeOperatorSchema2 = external_exports.object({ - /** Between (inclusive) - takes [min, max] array */ - $between: external_exports.tuple([ - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]), - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]) - ]).optional() -}); -var StringOperatorSchema2 = external_exports.object({ - /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */ - $contains: external_exports.string().optional(), - /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */ - $notContains: external_exports.string().optional(), - /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */ - $startsWith: external_exports.string().optional(), - /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */ - $endsWith: external_exports.string().optional() -}); -var SpecialOperatorSchema2 = external_exports.object({ - /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */ - $null: external_exports.boolean().optional(), - /** Field exists check (primarily for NoSQL) - MongoDB: $exists */ - $exists: external_exports.boolean().optional() -}); -var FieldOperatorsSchema4 = external_exports.object({ - // Equality - $eq: external_exports.any().optional(), - $ne: external_exports.any().optional(), - // Comparison (numeric/date) - $gt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), - $gte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), - $lt: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), - $lte: external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]).optional(), - // Set & Range - $in: external_exports.array(external_exports.any()).optional(), - $nin: external_exports.array(external_exports.any()).optional(), - $between: external_exports.tuple([ - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]), - external_exports.union([external_exports.number(), external_exports.date(), FieldReferenceSchema4]) - ]).optional(), - // String-specific - $contains: external_exports.string().optional(), - $notContains: external_exports.string().optional(), - $startsWith: external_exports.string().optional(), - $endsWith: external_exports.string().optional(), - // Special - $null: external_exports.boolean().optional(), - $exists: external_exports.boolean().optional() -}); -var FilterConditionSchema4 = external_exports.lazy( - () => external_exports.record(external_exports.string(), external_exports.unknown()).and( - external_exports.object({ - $and: external_exports.array(FilterConditionSchema4).optional(), - $or: external_exports.array(FilterConditionSchema4).optional(), - $not: FilterConditionSchema4.optional() - }) - ) -); -var QueryFilterSchema2 = external_exports.object({ - where: FilterConditionSchema4.optional() -}); -var NormalizedFilterSchema4 = external_exports.lazy( - () => external_exports.object({ - $and: external_exports.array( - external_exports.union([ - // Field condition: { field: { $op: value } } - external_exports.record(external_exports.string(), FieldOperatorsSchema4), - // Nested logical group - NormalizedFilterSchema4 - ]) - ).optional(), - $or: external_exports.array( - external_exports.union([ - external_exports.record(external_exports.string(), FieldOperatorsSchema4), - NormalizedFilterSchema4 - ]) - ).optional(), - $not: external_exports.union([ - external_exports.record(external_exports.string(), FieldOperatorsSchema4), - NormalizedFilterSchema4 - ]).optional() - }) -); -var VALID_AST_OPERATORS2 = /* @__PURE__ */ new Set([ - "=", - "==", - "!=", - "<>", - ">", - ">=", - "<", - "<=", - "in", - "nin", - "not_in", - "contains", - "notcontains", - "not_contains", - "like", - "startswith", - "starts_with", - "endswith", - "ends_with", - "between", - "is_null", - "is_not_null" -]); -function isFilterAST2(filter) { - if (!Array.isArray(filter) || filter.length === 0) return false; - const first = filter[0]; - if (typeof first === "string") { - const lower = first.toLowerCase(); - if (lower === "and" || lower === "or") { - return filter.length >= 2 && filter.slice(1).every((child) => isFilterAST2(child)); - } - if (filter.length >= 2 && typeof filter[1] === "string") { - return VALID_AST_OPERATORS2.has(filter[1].toLowerCase()); - } - } - if (filter.every((item) => isFilterAST2(item))) { - return filter.length > 0; - } - return false; -} -var AST_OPERATOR_MAP2 = { - "=": "$eq", - "==": "$eq", - "!=": "$ne", - "<>": "$ne", - ">": "$gt", - ">=": "$gte", - "<": "$lt", - "<=": "$lte", - "in": "$in", - "nin": "$nin", - "not_in": "$nin", - "contains": "$contains", - "notcontains": "$notContains", - "not_contains": "$notContains", - "like": "$contains", - "startswith": "$startsWith", - "starts_with": "$startsWith", - "endswith": "$endsWith", - "ends_with": "$endsWith", - "between": "$between", - "is_null": "$null", - "is_not_null": "$null" -}; -function convertComparison2(node) { - const [field, operator, value] = node; - const op = operator.toLowerCase(); - if (op === "=" || op === "==") { - return { [field]: value }; - } - if (op === "is_null") { - return { [field]: { $null: true } }; - } - if (op === "is_not_null") { - return { [field]: { $null: false } }; - } - const mapped = AST_OPERATOR_MAP2[op]; - if (mapped) { - return { [field]: { [mapped]: value } }; - } - return { [field]: { [`$${op}`]: value } }; -} -function parseFilterAST2(filter) { - if (filter == null) return void 0; - if (!Array.isArray(filter)) return filter; - if (filter.length === 0) return void 0; - const first = filter[0]; - if (typeof first === "string" && (first.toLowerCase() === "and" || first.toLowerCase() === "or")) { - const logicOp = `$${first.toLowerCase()}`; - const children = filter.slice(1).map((child) => parseFilterAST2(child)).filter(Boolean); - if (children.length === 0) return void 0; - if (children.length === 1) return children[0]; - return { [logicOp]: children }; - } - if (filter.length >= 2 && typeof first === "string") { - return convertComparison2(filter); - } - if (filter.every((item) => Array.isArray(item))) { - const children = filter.map((child) => parseFilterAST2(child)).filter(Boolean); - if (children.length === 0) return void 0; - if (children.length === 1) return children[0]; - return { $and: children }; - } - return void 0; -} -var FILTER_OPERATORS2 = [ - // Equality - "$eq", - "$ne", - // Comparison - "$gt", - "$gte", - "$lt", - "$lte", - // Set & Range - "$in", - "$nin", - "$between", - // String - "$contains", - "$notContains", - "$startsWith", - "$endsWith", - // Special - "$null", - "$exists" -]; -var LOGICAL_OPERATORS2 = ["$and", "$or", "$not"]; -var ALL_OPERATORS2 = [...FILTER_OPERATORS2, ...LOGICAL_OPERATORS2]; -var SortNodeSchema3 = external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]).default("asc") -}); -var AggregationFunction3 = external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "array_agg", - "string_agg" -]); -var AggregationNodeSchema3 = external_exports.object({ - function: AggregationFunction3.describe("Aggregation function"), - field: external_exports.string().optional().describe("Field to aggregate (optional for COUNT(*))"), - alias: external_exports.string().describe("Result column alias"), - distinct: external_exports.boolean().optional().describe("Apply DISTINCT before aggregation"), - filter: FilterConditionSchema4.optional().describe("Filter/Condition to apply to the aggregation (FILTER WHERE clause)") -}); -var JoinType3 = external_exports.enum(["inner", "left", "right", "full"]); -var JoinStrategy3 = external_exports.enum(["auto", "database", "hash", "loop"]); -var JoinNodeSchema3 = external_exports.lazy( - () => external_exports.object({ - type: JoinType3.describe("Join type"), - strategy: JoinStrategy3.optional().describe("Execution strategy hint"), - object: external_exports.string().describe("Object/table to join"), - alias: external_exports.string().optional().describe("Table alias"), - on: FilterConditionSchema4.describe("Join condition"), - subquery: external_exports.lazy(() => QuerySchema3).optional().describe("Subquery instead of object") - }) -); -var WindowFunction3 = external_exports.enum([ - "row_number", - "rank", - "dense_rank", - "percent_rank", - "lag", - "lead", - "first_value", - "last_value", - "sum", - "avg", - "count", - "min", - "max" -]); -var WindowSpecSchema3 = external_exports.object({ - partitionBy: external_exports.array(external_exports.string()).optional().describe("PARTITION BY fields"), - orderBy: external_exports.array(SortNodeSchema3).optional().describe("ORDER BY specification"), - frame: external_exports.object({ - type: external_exports.enum(["rows", "range"]).optional(), - start: external_exports.string().optional().describe('Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")'), - end: external_exports.string().optional().describe('Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")') - }).optional().describe("Window frame specification") -}); -var WindowFunctionNodeSchema3 = external_exports.object({ - function: WindowFunction3.describe("Window function name"), - field: external_exports.string().optional().describe("Field to operate on (for aggregate window functions)"), - alias: external_exports.string().describe("Result column alias"), - over: WindowSpecSchema3.describe("Window specification (OVER clause)") -}); -var FieldNodeSchema3 = external_exports.lazy( - () => external_exports.union([ - external_exports.string(), - // Primitive field: "name" - external_exports.object({ - field: external_exports.string(), - // Relationship field: "owner" - fields: external_exports.array(FieldNodeSchema3).optional(), - // Nested select: ["name", "email"] - alias: external_exports.string().optional() - }) - ]) -); -var FullTextSearchSchema3 = external_exports.object({ - query: external_exports.string().describe("Search query text"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to search in (if not specified, searches all text fields)"), - fuzzy: external_exports.boolean().optional().default(false).describe("Enable fuzzy matching (tolerates typos)"), - operator: external_exports.enum(["and", "or"]).optional().default("or").describe("Logical operator between terms"), - boost: external_exports.record(external_exports.string(), external_exports.number()).optional().describe("Field-specific relevance boosting (field name -> boost factor)"), - minScore: external_exports.number().optional().describe("Minimum relevance score threshold"), - language: external_exports.string().optional().describe('Language for text analysis (e.g., "en", "zh", "es")'), - highlight: external_exports.boolean().optional().default(false).describe("Enable search result highlighting") -}); -var BaseQuerySchema3 = external_exports.object({ - /** Target Entity */ - object: external_exports.string().describe("Object name (e.g. account)"), - /** Select Clause */ - fields: external_exports.array(FieldNodeSchema3).optional().describe("Fields to retrieve"), - /** Where Clause (Filtering) */ - where: FilterConditionSchema4.optional().describe("Filtering criteria (WHERE)"), - /** Full-Text Search */ - search: FullTextSearchSchema3.optional().describe("Full-text search configuration ($search parameter)"), - /** Order By Clause (Sorting) */ - orderBy: external_exports.array(SortNodeSchema3).optional().describe("Sorting instructions (ORDER BY)"), - /** Pagination */ - limit: external_exports.number().optional().describe("Max records to return (LIMIT)"), - offset: external_exports.number().optional().describe("Records to skip (OFFSET)"), - top: external_exports.number().optional().describe("Alias for limit (OData compatibility)"), - cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Cursor for keyset pagination"), - /** Joins */ - joins: external_exports.array(JoinNodeSchema3).optional().describe("Explicit Table Joins"), - /** Aggregations */ - aggregations: external_exports.array(AggregationNodeSchema3).optional().describe("Aggregation functions"), - /** Group By Clause */ - groupBy: external_exports.array(external_exports.string()).optional().describe("GROUP BY fields"), - /** Having Clause */ - having: FilterConditionSchema4.optional().describe("HAVING clause for aggregation filtering"), - /** Window Functions */ - windowFunctions: external_exports.array(WindowFunctionNodeSchema3).optional().describe("Window functions with OVER clause"), - /** Subquery flag */ - distinct: external_exports.boolean().optional().describe("SELECT DISTINCT flag") -}); -var QuerySchema3 = BaseQuerySchema3.extend({ - expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema3)).optional().describe( - "Recursive relation loading map. Keys are lookup/master_detail field names; values are nested QueryAST objects that control select, filter, sort, and further expansion on the related object. The engine resolves expand via batch $in queries (driver-agnostic) with a default max depth of 3." - ) -}); -var BaseValidationSchema4 = external_exports.object({ - // Identification - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label for the rule listing"), - description: external_exports.string().optional().describe("Administrative notes explaining the business reason"), - // Execution Control - active: external_exports.boolean().default(true), - events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).default(["insert", "update"]).describe("Validation contexts"), - priority: external_exports.number().int().min(0).max(9999).default(100).describe("Execution priority (lower runs first, default: 100)"), - // Classification - tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g., "compliance", "billing")'), - // Feedback - severity: external_exports.enum(["error", "warning", "info"]).default("error"), - message: external_exports.string().describe("Error message to display to the user") -}); -var ScriptValidationSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("script"), - condition: external_exports.string().describe("Formula expression. If TRUE, validation fails. (e.g. amount < 0)") -}); -var UniquenessValidationSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("unique"), - fields: external_exports.array(external_exports.string()).describe("Fields that must be combined unique"), - scope: external_exports.string().optional().describe("Formula condition for scope (e.g. active = true)"), - caseSensitive: external_exports.boolean().default(true) -}); -var StateMachineValidationSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("state_machine"), - field: external_exports.string().describe("State field (e.g. status)"), - transitions: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).describe("Map of { OldState: [AllowedNewStates] }") -}); -var FormatValidationSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("format"), - field: external_exports.string(), - regex: external_exports.string().optional(), - format: external_exports.enum(["email", "url", "phone", "json"]).optional() -}); -var CrossFieldValidationSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("cross_field"), - condition: external_exports.string().describe('Formula expression comparing fields (e.g. "end_date > start_date")'), - fields: external_exports.array(external_exports.string()).describe("Fields involved in the validation") -}); -var JSONValidationSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("json_schema"), - field: external_exports.string().describe("JSON field to validate"), - schema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema object definition") -}); -var AsyncValidationSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("async"), - field: external_exports.string().describe("Field to validate"), - validatorUrl: external_exports.string().optional().describe("External API endpoint for validation"), - method: external_exports.enum(["GET", "POST"]).default("GET").describe("HTTP method for external call"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for the request"), - validatorFunction: external_exports.string().optional().describe("Reference to custom validator function"), - timeout: external_exports.number().optional().default(5e3).describe("Timeout in milliseconds"), - debounce: external_exports.number().optional().describe("Debounce delay in milliseconds"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional parameters to pass to validator") -}); -var CustomValidatorSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("custom"), - handler: external_exports.string().describe("Name of the custom validation function registered in the system"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the custom handler") -}); -var ValidationRuleSchema4 = external_exports.lazy( - () => external_exports.discriminatedUnion("type", [ - ScriptValidationSchema4, - UniquenessValidationSchema4, - StateMachineValidationSchema4, - FormatValidationSchema4, - CrossFieldValidationSchema4, - JSONValidationSchema4, - AsyncValidationSchema4, - CustomValidatorSchema4, - ConditionalValidationSchema4 - ]) -); -var ConditionalValidationSchema4 = BaseValidationSchema4.extend({ - type: external_exports.literal("conditional"), - when: external_exports.string().describe(`Condition formula (e.g. "type = 'enterprise'")`), - then: ValidationRuleSchema4.describe("Validation rule to apply when condition is true"), - otherwise: ValidationRuleSchema4.optional().describe("Validation rule to apply when condition is false") -}); -var ActionRefSchema4 = external_exports.union([ - external_exports.string().describe("Action Name"), - external_exports.object({ - type: external_exports.string(), - // e.g., 'xstate.assign', 'log', 'email' - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }) -]); -var GuardRefSchema4 = external_exports.union([ - external_exports.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'), - external_exports.object({ - type: external_exports.string(), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }) -]); -var TransitionSchema4 = external_exports.object({ - target: external_exports.string().optional().describe("Target State ID"), - cond: GuardRefSchema4.optional().describe("Condition (Guard) required to take this path"), - actions: external_exports.array(ActionRefSchema4).optional().describe("Actions to execute during transition"), - description: external_exports.string().optional().describe("Human readable description of this rule") -}); -var EventSchema2 = external_exports.object({ - type: external_exports.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'), - // Payload validation schema could go here if we want deep validation - schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Expected event payload structure") -}); -var StateNodeSchema4 = external_exports.lazy(() => external_exports.object({ - /** Type of state */ - type: external_exports.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"), - /** Entry/Exit Actions */ - entry: external_exports.array(ActionRefSchema4).optional().describe("Actions to run when entering this state"), - exit: external_exports.array(ActionRefSchema4).optional().describe("Actions to run when leaving this state"), - /** Transitions (Events) */ - on: external_exports.record(external_exports.string(), external_exports.union([ - external_exports.string(), - // Shorthand target - TransitionSchema4, - external_exports.array(TransitionSchema4) - ])).optional().describe("Map of Event Type -> Transition Definition"), - /** Always Transitions (Eventless) */ - always: external_exports.array(TransitionSchema4).optional(), - /** Nesting (Hierarchical States) */ - initial: external_exports.string().optional().describe("Initial child state (if compound)"), - states: external_exports.record(external_exports.string(), StateNodeSchema4).optional(), - /** Metadata for UI/AI */ - meta: external_exports.object({ - label: external_exports.string().optional(), - description: external_exports.string().optional(), - color: external_exports.string().optional(), - // For UI diagrams - // Instructions for AI Agent when in this state - aiInstructions: external_exports.string().optional().describe("Specific instructions for AI when in this state") - }).optional() -})); -var StateMachineSchema4 = external_exports.object({ - id: SnakeCaseIdentifierSchema7.describe("Unique Machine ID"), - description: external_exports.string().optional(), - /** Context (Memory) Schema */ - contextSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Zod Schema for the machine context/memory"), - /** Initial State */ - initial: external_exports.string().describe("Initial State ID"), - /** State Definitions */ - states: external_exports.record(external_exports.string(), StateNodeSchema4).describe("State Nodes"), - /** Global Listeners */ - on: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), TransitionSchema4, external_exports.array(TransitionSchema4)])).optional() -}); -var I18nObjectSchema2 = external_exports.object({ - /** Translation key (e.g., "views.task_list.label", "apps.crm.description") */ - key: external_exports.string().describe('Translation key (e.g., "views.task_list.label")'), - /** Default value when translation is not available */ - defaultValue: external_exports.string().optional().describe("Fallback value when translation key is not found"), - /** Interpolation parameters for dynamic translations */ - params: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Interpolation parameters (e.g., { count: 5 })") -}); -var I18nLabelSchema5 = external_exports.string().describe("Display label (plain string; i18n keys are auto-generated by the framework)"); -var AriaPropsSchema5 = external_exports.object({ - /** Accessible label for screen readers */ - ariaLabel: I18nLabelSchema5.optional().describe("Accessible label for screen readers (WAI-ARIA aria-label)"), - /** ID of element that describes this component */ - ariaDescribedBy: external_exports.string().optional().describe("ID of element providing additional description (WAI-ARIA aria-describedby)"), - /** WAI-ARIA role override */ - role: external_exports.string().optional().describe('WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")') -}).describe("ARIA accessibility attributes"); -var PluralRuleSchema2 = external_exports.object({ - /** Translation key for the plural form */ - key: external_exports.string().describe("Translation key"), - /** Form for zero quantity */ - zero: external_exports.string().optional().describe('Zero form (e.g., "No items")'), - /** Form for singular (1) */ - one: external_exports.string().optional().describe('Singular form (e.g., "{count} item")'), - /** Form for dual (2) — used in Arabic, Welsh, etc. */ - two: external_exports.string().optional().describe('Dual form (e.g., "{count} items" for exactly 2)'), - /** Form for few (2-4 in Slavic languages) */ - few: external_exports.string().optional().describe("Few form (e.g., for 2-4 in some languages)"), - /** Form for many (5+ in Slavic languages) */ - many: external_exports.string().optional().describe("Many form (e.g., for 5+ in some languages)"), - /** Default/fallback form */ - other: external_exports.string().describe('Default plural form (e.g., "{count} items")') -}).describe("ICU plural rules for a translation key"); -var NumberFormatSchema5 = external_exports.object({ - style: external_exports.enum(["decimal", "currency", "percent", "unit"]).default("decimal").describe("Number formatting style"), - currency: external_exports.string().optional().describe('ISO 4217 currency code (e.g., "USD", "EUR")'), - unit: external_exports.string().optional().describe('Unit for unit formatting (e.g., "kilometer", "liter")'), - minimumFractionDigits: external_exports.number().optional().describe("Minimum number of fraction digits"), - maximumFractionDigits: external_exports.number().optional().describe("Maximum number of fraction digits"), - useGrouping: external_exports.boolean().optional().describe("Whether to use grouping separators (e.g., 1,000)") -}).describe("Number formatting rules"); -var DateFormatSchema5 = external_exports.object({ - dateStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Date display style"), - timeStyle: external_exports.enum(["full", "long", "medium", "short"]).optional().describe("Time display style"), - timeZone: external_exports.string().optional().describe('IANA time zone (e.g., "America/New_York")'), - hour12: external_exports.boolean().optional().describe("Use 12-hour format") -}).describe("Date/time formatting rules"); -var LocaleConfigSchema2 = external_exports.object({ - /** BCP 47 language code (e.g., "en-US", "zh-CN", "ar-SA") */ - code: external_exports.string().describe('BCP 47 language code (e.g., "en-US", "zh-CN")'), - /** Ordered fallback chain for missing translations */ - fallbackChain: external_exports.array(external_exports.string()).optional().describe('Fallback language codes in priority order (e.g., ["zh-TW", "en"])'), - /** Text direction */ - direction: external_exports.enum(["ltr", "rtl"]).default("ltr").describe("Text direction: left-to-right or right-to-left"), - /** Default number formatting */ - numberFormat: NumberFormatSchema5.optional().describe("Default number formatting rules"), - /** Default date formatting */ - dateFormat: DateFormatSchema5.optional().describe("Default date/time formatting rules") -}).describe("Locale configuration"); -var ActionParamSchema5 = external_exports.object({ - name: external_exports.string(), - label: I18nLabelSchema5, - type: FieldType6, - required: external_exports.boolean().default(false), - options: external_exports.array(external_exports.object({ label: I18nLabelSchema5, value: external_exports.string() })).optional() -}); -var ActionType5 = external_exports.enum(["script", "url", "modal", "flow", "api"]); -var TARGET_REQUIRED_TYPES5 = new Set( - ActionType5.options.filter((t) => t !== "script") -); -var ActionSchema5 = external_exports.object({ - /** Machine name of the action */ - name: SnakeCaseIdentifierSchema7.describe("Machine name (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema5.describe("Display label"), - /** Target object this action belongs to (optional, snake_case) */ - objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack()."), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Icon name"), - /** Where does this action appear? */ - locations: external_exports.array(external_exports.enum([ - "list_toolbar", - "list_item", - "record_header", - "record_more", - "record_related", - "global_nav" - ])).optional().describe("Locations where this action is visible"), - /** - * Visual Component Type - * Defaults to 'button' or 'menu_item' based on location, - * but can be overridden. - */ - component: external_exports.enum([ - "action:button", - // Standard Button - "action:icon", - // Icon only - "action:menu", - // Dropdown menu - "action:group" - // Button Group - ]).optional().describe("Visual component override"), - /** What type of interaction? */ - type: ActionType5.default("script").describe("Action functionality type"), - /** - * Payload / Target — the canonical binding for the action handler. - * Required for url, flow, modal, and api types. - * Recommended for script type. - */ - target: external_exports.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint"), - /** - * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing. - */ - execute: external_exports.string().optional().describe("@deprecated \u2014 Use target instead. Auto-migrated to target during parsing."), - /** User Input Requirements */ - params: external_exports.array(ActionParamSchema5).optional().describe("Input parameters required from user"), - /** Visual Style */ - variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().describe("Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)"), - /** UX Behavior */ - confirmText: I18nLabelSchema5.optional().describe("Confirmation message before execution"), - successMessage: I18nLabelSchema5.optional().describe("Success message to show after execution"), - refreshAfter: external_exports.boolean().default(false).describe("Refresh view after execution"), - /** Access */ - visible: external_exports.string().optional().describe("Formula returning boolean"), - disabled: external_exports.union([external_exports.boolean(), external_exports.string()]).optional().describe("Whether the action is disabled, or a condition expression string"), - /** Keyboard Shortcut */ - shortcut: external_exports.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'), - /** Bulk Operations */ - bulkEnabled: external_exports.boolean().optional().describe("Whether this action can be applied to multiple selected records"), - /** Execution */ - timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds for the action"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}).transform((data) => { - if (data.execute && !data.target) { - return { ...data, target: data.execute }; - } - return data; -}).refine((data) => { - if (TARGET_REQUIRED_TYPES5.has(data.type) && !data.target) { - return false; - } - return true; -}, { - message: "Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.", - path: ["target"] -}); -var Action = { - create: (config4) => ActionSchema5.parse(config4) -}; -var ApiMethod4 = external_exports.enum([ - "get", - "list", - // Read - "create", - "update", - "delete", - // Write - "upsert", - // Idempotent Write - "bulk", - // Batch operations - "aggregate", - // Analytics (count, sum) - "history", - // Audit access - "search", - // Search access - "restore", - "purge", - // Trash management - "import", - "export" - // Data portability -]); -var ObjectCapabilities4 = external_exports.object({ - /** Enable history tracking (Audit Trail) */ - trackHistory: external_exports.boolean().default(false).describe("Enable field history tracking for audit compliance"), - /** Enable global search indexing */ - searchable: external_exports.boolean().default(true).describe("Index records for global search"), - /** Enable REST/GraphQL API access */ - apiEnabled: external_exports.boolean().default(true).describe("Expose object via automatic APIs"), - /** - * API Supported Operations - * Granular control over API exposure. - */ - apiMethods: external_exports.array(ApiMethod4).optional().describe("Whitelist of allowed API operations"), - /** Enable standard attachments/files engine */ - files: external_exports.boolean().default(false).describe("Enable file attachments and document management"), - /** Enable social collaboration (Comments, Mentions, Feeds) */ - feeds: external_exports.boolean().default(false).describe("Enable social feed, comments, and mentions (Chatter-like)"), - /** Enable standard Activity suite (Tasks, Calendars, Events) */ - activities: external_exports.boolean().default(false).describe("Enable standard tasks and events tracking"), - /** Enable Recycle Bin / Soft Delete */ - trash: external_exports.boolean().default(true).describe("Enable soft-delete with restore capability"), - /** Enable "Recently Viewed" tracking */ - mru: external_exports.boolean().default(true).describe("Track Most Recently Used (MRU) list for users"), - /** Allow cloning records */ - clone: external_exports.boolean().default(true).describe("Allow record deep cloning") -}); -var IndexSchema4 = external_exports.object({ - name: external_exports.string().optional().describe("Index name (auto-generated if not provided)"), - fields: external_exports.array(external_exports.string()).describe("Fields included in the index"), - type: external_exports.enum(["btree", "hash", "gin", "gist", "fulltext"]).optional().default("btree").describe("Index algorithm type"), - unique: external_exports.boolean().optional().default(false).describe("Whether the index enforces uniqueness"), - partial: external_exports.string().optional().describe("Partial index condition (SQL WHERE clause for conditional indexes)") -}); -var SearchConfigSchema5 = external_exports.object({ - fields: external_exports.array(external_exports.string()).describe("Fields to index for full-text search weighting"), - displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display in search result cards"), - filters: external_exports.array(external_exports.string()).optional().describe("Default filters for search results") -}); -var TenancyConfigSchema4 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable multi-tenancy for this object"), - strategy: external_exports.enum(["shared", "isolated", "hybrid"]).describe("Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)"), - tenantField: external_exports.string().default("tenant_id").describe("Field name for tenant identifier"), - crossTenantAccess: external_exports.boolean().default(false).describe("Allow cross-tenant data access (with explicit permission)") -}); -var SoftDeleteConfigSchema4 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable soft delete (trash/recycle bin)"), - field: external_exports.string().default("deleted_at").describe("Field name for soft delete timestamp"), - cascadeDelete: external_exports.boolean().default(false).describe("Cascade soft delete to related records") -}); -var VersioningConfigSchema4 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable record versioning"), - strategy: external_exports.enum(["snapshot", "delta", "event-sourcing"]).describe("Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)"), - retentionDays: external_exports.number().min(1).optional().describe("Number of days to retain old versions (undefined = infinite)"), - versionField: external_exports.string().default("version").describe("Field name for version number/timestamp") -}); -var PartitioningConfigSchema4 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable table partitioning"), - strategy: external_exports.enum(["range", "hash", "list"]).describe("Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)"), - key: external_exports.string().describe("Field name to partition by"), - interval: external_exports.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")') -}).refine((data) => { - if (data.strategy === "range" && !data.interval) { - return false; - } - return true; -}, { - message: 'interval is required when strategy is "range"' -}); -var CDCConfigSchema4 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable Change Data Capture"), - events: external_exports.array(external_exports.enum(["insert", "update", "delete"])).describe("Event types to capture"), - destination: external_exports.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")') -}); -var ObjectSchemaBase4 = external_exports.object({ - /** - * Identity & Metadata - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine unique key (snake_case). Immutable."), - label: external_exports.string().optional().describe('Human readable singular label (e.g. "Account")'), - pluralLabel: external_exports.string().optional().describe('Human readable plural label (e.g. "Accounts")'), - description: external_exports.string().optional().describe("Developer documentation / description"), - icon: external_exports.string().optional().describe("Icon name (Lucide/Material) for UI representation"), - /** - * Namespace & Domain Classification - * - * Groups objects into logical domains for routing, permissions, and discovery. - * System objects use `'sys'`; business packages use their own namespace. - * - * When set, `tableName` is auto-derived as `{namespace}_{name}` by - * `ObjectSchema.create()` unless an explicit `tableName` is provided. - * - * Namespace must be a single lowercase word (no underscores or hyphens) - * to ensure clean auto-derivation of `{namespace}_{name}` table names. - * - * @example namespace: 'sys' → tableName defaults to 'sys_user' - * @example namespace: 'crm' → tableName defaults to 'crm_account' - */ - namespace: external_exports.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace \u2014 single lowercase word (e.g. "sys", "crm"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'), - /** - * Taxonomy & Organization - */ - tags: external_exports.array(external_exports.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'), - active: external_exports.boolean().optional().default(true).describe("Is the object active and usable"), - isSystem: external_exports.boolean().optional().default(false).describe("Is system object (protected from deletion)"), - abstract: external_exports.boolean().optional().default(false).describe("Is abstract base object (cannot be instantiated)"), - /** - * Storage & Virtualization - */ - datasource: external_exports.string().optional().default("default").describe('Target Datasource ID. "default" is the primary DB.'), - tableName: external_exports.string().optional().describe("Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set."), - /** - * Data Model - */ - fields: external_exports.record(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/, { - message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")' - }), FieldSchema5).describe("Field definitions map. Keys must be snake_case identifiers."), - indexes: external_exports.array(IndexSchema4).optional().describe("Database performance indexes"), - /** - * Advanced Data Management - */ - // Multi-tenancy configuration - tenancy: TenancyConfigSchema4.optional().describe("Multi-tenancy configuration for SaaS applications"), - // Soft delete configuration - softDelete: SoftDeleteConfigSchema4.optional().describe("Soft delete (trash/recycle bin) configuration"), - // Versioning configuration - versioning: VersioningConfigSchema4.optional().describe("Record versioning and history tracking configuration"), - // Partitioning strategy - partitioning: PartitioningConfigSchema4.optional().describe("Table partitioning configuration for performance"), - // Change Data Capture - cdc: CDCConfigSchema4.optional().describe("Change Data Capture (CDC) configuration for real-time data streaming"), - /** - * Logic & Validation (Co-located) - * Best Practice: Define rules close to data. - */ - validations: external_exports.array(ValidationRuleSchema4).optional().describe("Object-level validation rules"), - /** - * State Machine(s) - * Named record of state machines, where each key is a unique machine identifier. - * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status). - * - * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} } - */ - stateMachines: external_exports.record(external_exports.string(), StateMachineSchema4).optional().describe("Named state machines for parallel lifecycles (e.g., status, payment, approval)"), - /** - * Display & UI Hints (Data-Layer) - */ - displayNameField: external_exports.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'), - recordName: external_exports.object({ - type: external_exports.enum(["text", "autonumber"]).describe("Record name type: text (user-entered) or autonumber (system-generated)"), - displayFormat: external_exports.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'), - startNumber: external_exports.number().int().min(0).optional().describe("Starting number for autonumber (default: 1)") - }).optional().describe("Record name generation configuration (Salesforce pattern)"), - titleFormat: external_exports.string().optional().describe('Title expression (e.g. "{name} - {code}"). Overrides displayNameField.'), - compactLayout: external_exports.array(external_exports.string()).optional().describe("Primary fields for hover/cards/lookups"), - /** - * Search Engine Config - */ - search: SearchConfigSchema5.optional().describe("Search engine configuration"), - /** - * System Capabilities - */ - enable: ObjectCapabilities4.optional().describe("Enabled system features modules"), - /** Record Types */ - recordTypes: external_exports.array(external_exports.string()).optional().describe("Record type names for this object"), - /** Sharing Model */ - sharingModel: external_exports.enum(["private", "read", "read_write", "full"]).optional().describe("Default sharing model"), - /** Key Prefix */ - keyPrefix: external_exports.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'), - /** - * Object Actions - * - * Actions associated with this object. Populated automatically by `defineStack()` - * when top-level actions specify `objectName` matching this object. - * Can also be defined directly on the object. - * - * Aligns with Salesforce/ServiceNow patterns where actions are part of the - * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`) - * include the action list without requiring downstream merge. - */ - actions: external_exports.array(ActionSchema5).optional().describe("Actions associated with this object (auto-populated from top-level actions via objectName)") -}); -function snakeCaseToLabel4(name) { - return name.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); -} -var ObjectSchema4 = Object.assign(ObjectSchemaBase4, { - /** - * Type-safe factory for creating business object definitions. - * - * Enhancements over raw schema: - * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case). - * - **Validation**: Runs Zod `.parse()` to validate the config at creation time. - * - * @example - * ```ts - * const Task = ObjectSchema.create({ - * name: 'project_task', - * // label auto-generated as 'Project Task' - * fields: { - * subject: { type: 'text', label: 'Subject', required: true }, - * }, - * }); - * ``` - */ - create: (config4) => { - const withDefaults = { - ...config4, - label: config4.label ?? snakeCaseToLabel4(config4.name), - // Auto-derive tableName as {namespace}_{name} when namespace is set - tableName: config4.tableName ?? (config4.namespace ? `${config4.namespace}_${config4.name}` : void 0) - }; - return ObjectSchemaBase4.parse(withDefaults); - } -}); -var ObjectOwnershipEnum2 = external_exports.enum(["own", "extend"]); -var ObjectExtensionSchema2 = external_exports.object({ - /** The target object name (FQN) to extend */ - extend: external_exports.string().describe("Target object name (FQN) to extend"), - /** Fields to merge into the target object (additive) */ - fields: external_exports.record(external_exports.string(), FieldSchema5).optional().describe("Fields to add/override"), - /** Override label */ - label: external_exports.string().optional().describe("Override label for the extended object"), - /** Override plural label */ - pluralLabel: external_exports.string().optional().describe("Override plural label for the extended object"), - /** Override description */ - description: external_exports.string().optional().describe("Override description for the extended object"), - /** Additional validation rules to add */ - validations: external_exports.array(ValidationRuleSchema4).optional().describe("Additional validation rules to merge into the target object"), - /** Additional indexes to add */ - indexes: external_exports.array(IndexSchema4).optional().describe("Additional indexes to merge into the target object"), - /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ - priority: external_exports.number().int().min(0).max(999).default(200).describe("Merge priority (higher = applied later)") -}); -var HookEvent2 = external_exports.enum([ - // Read Operations - "beforeFind", - "afterFind", - "beforeFindOne", - "afterFindOne", - "beforeCount", - "afterCount", - "beforeAggregate", - "afterAggregate", - // Write Operations - "beforeInsert", - "afterInsert", - "beforeUpdate", - "afterUpdate", - "beforeDelete", - "afterDelete", - // Bulk Operations (Query-based) - "beforeUpdateMany", - "afterUpdateMany", - "beforeDeleteMany", - "afterDeleteMany" -]); -var HookSchema2 = external_exports.object({ - /** - * Unique identifier for the hook - * Required for debugging and overriding. - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Hook unique name (snake_case)"), - /** - * Human readable label - */ - label: external_exports.string().optional().describe("Description of what this hook does"), - /** - * Target Object(s) - * can be: - * - Single object: "account" - * - List of objects: ["account", "contact"] - * - Wildcard: "*" (All objects) - */ - object: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Target object(s)"), - /** - * Events to subscribe to - * Combinations of timing (before/after) and action (find/insert/update/delete/etc) - */ - events: external_exports.array(HookEvent2).describe("Lifecycle events"), - /** - * Handler Logic - * Reference to a registered function in the plugin system OR a direct function (runtime only). - */ - handler: external_exports.union([external_exports.string(), external_exports.function()]).optional().describe("Handler function name (string) or inline function reference"), - /** - * Execution Order - * Lower numbers run first. - * - System Hooks: 0-99 - * - App Hooks: 100-999 - * - User Hooks: 1000+ - */ - priority: external_exports.number().default(100).describe("Execution priority"), - /** - * Async / Background Execution - * If true, the hook runs in the background and does not block the transaction. - * Only applicable for 'after*' events. - * Default: false (Blocking) - */ - async: external_exports.boolean().default(false).describe("Run specifically as fire-and-forget"), - /** - * Declarative Condition - * Formula expression evaluated before the handler runs. - * If provided and evaluates to FALSE, the hook is skipped entirely. - * Useful for filtering by record data without writing handler code. - * - * @example "status = 'active' AND amount > 1000" - */ - condition: external_exports.string().optional().describe(`Formula expression; hook runs only when TRUE (e.g., "status = 'closed' AND amount > 1000")`), - /** - * Human-readable description - */ - description: external_exports.string().optional().describe("Human-readable description of what this hook does"), - /** - * Retry Policy - */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().default(3).describe("Maximum retry attempts on failure"), - backoffMs: external_exports.number().default(1e3).describe("Backoff delay between retries in milliseconds") - }).optional().describe("Retry policy for failed hook executions"), - /** - * Execution Timeout - */ - timeout: external_exports.number().optional().describe("Maximum execution time in milliseconds before the hook is aborted"), - /** - * Error Policy - * What to do if the hook throws an exception? - * - abort: Rollback transaction (if blocking) - * - log: Log error and continue - */ - onError: external_exports.enum(["abort", "log"]).default("abort").describe("Error handling strategy") -}); -var HookContextSchema2 = external_exports.object({ - /** Tracing ID */ - id: external_exports.string().optional().describe("Unique execution ID for tracing"), - /** Target Object Name */ - object: external_exports.string(), - /** Current Lifecycle Event */ - event: HookEvent2, - /** - * Input Parameters (Mutable) - * Modify this to change the behavior of the operation. - * - * - find: { query: QueryAST, options: DriverOptions } - * - insert: { doc: Record, options: DriverOptions } - * - update: { id: ID, doc: Record, options: DriverOptions } - * - delete: { id: ID, options: DriverOptions } - * - updateMany: { query: QueryAST, doc: Record, options: DriverOptions } - * - deleteMany: { query: QueryAST, options: DriverOptions } - */ - input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Mutable input parameters"), - /** - * Operation Result (Mutable) - * Available in 'after*' events. Modify this to transform the output. - */ - result: external_exports.unknown().optional().describe("Operation result (After hooks only)"), - /** - * Data Snapshot - * The state of the record BEFORE the operation (for update/delete). - */ - previous: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record state before operation"), - /** - * Execution Session - * Contains authentication and tenancy information. - */ - session: external_exports.object({ - userId: external_exports.string().optional(), - tenantId: external_exports.string().optional(), - roles: external_exports.array(external_exports.string()).optional(), - accessToken: external_exports.string().optional() - }).optional().describe("Current session context"), - /** - * Transaction Handle - * If the operation is part of a transaction, use this handle for side-effects. - */ - transaction: external_exports.unknown().optional().describe("Database transaction handle"), - /** - * Engine Access - * Reference to the ObjectQL engine for performing side effects. - */ - ql: external_exports.unknown().describe("ObjectQL Engine Reference"), - /** - * Cross-Object API - * Provides a scoped data access interface for performing CRUD operations - * on other objects within hooks. Bound to the current execution context - * (userId, tenantId, transaction). - * - * Usage in hooks: - * const users = ctx.api.object('user'); - * const admin = await users.findOne({ filter: { role: 'admin' } }); - */ - api: external_exports.unknown().optional().describe("Cross-object data access (ScopedContext)"), - /** - * Current User Info - * Convenience shortcut for session.userId + additional user metadata. - * Populated by the engine when available. - */ - user: external_exports.object({ - id: external_exports.string().optional(), - name: external_exports.string().optional(), - email: external_exports.string().optional() - }).optional().describe("Current user info shortcut") -}); -var TransformType2 = external_exports.enum([ - "none", - // Direct copy - "constant", - // Use a hardcoded value - "lookup", - // Resolve FK (Name -> ID) - "split", - // "John Doe" -> ["John", "Doe"] - "join", - // ["John", "Doe"] -> "John Doe" - "javascript", - // Custom script (Review security!) - "map" - // Value mapping (e.g. "Active" -> "active") -]); -var FieldMappingSchema22 = external_exports.object({ - /** Source Column */ - source: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Source column header(s)"), - /** Target Field */ - target: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Target object field(s)"), - /** Transformation */ - transform: TransformType2.default("none"), - /** Configuration for transform */ - params: external_exports.object({ - // Constant - value: external_exports.unknown().optional(), - // Lookup - object: external_exports.string().optional(), - // Lookup Object - fromField: external_exports.string().optional(), - // Match on (e.g. "name") - toField: external_exports.string().optional(), - // Value to take (e.g. "id") - autoCreate: external_exports.boolean().optional(), - // Create if missing - // Map - valueMap: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - // { "Open": "draft" } - // Split/Join - separator: external_exports.string().optional() - }).optional() -}); -var MappingSchema2 = external_exports.object({ - /** Identity */ - name: SnakeCaseIdentifierSchema7.describe("Mapping unique name (lowercase snake_case)"), - label: external_exports.string().optional(), - /** Scope */ - sourceFormat: external_exports.enum(["csv", "json", "xml", "sql"]).default("csv"), - targetObject: external_exports.string().describe("Target Object Name"), - /** Column Mappings */ - fieldMapping: external_exports.array(FieldMappingSchema22), - /** Upsert Logic */ - mode: external_exports.enum(["insert", "update", "upsert"]).default("insert"), - upsertKey: external_exports.array(external_exports.string()).optional().describe("Fields to match for upsert (e.g. email)"), - /** Extract Logic (For Export) */ - extractQuery: QuerySchema3.optional().describe("Query to run for export only"), - /** Error Handling */ - errorPolicy: external_exports.enum(["skip", "abort", "retry"]).default("skip"), - batchSize: external_exports.number().default(1e3) -}); -var ExecutionContextSchema3 = external_exports.object({ - /** Current user ID (resolved from session) */ - userId: external_exports.string().optional(), - /** Current organization/tenant ID (resolved from session.activeOrganizationId) */ - tenantId: external_exports.string().optional(), - /** User role names (resolved from Member + Role) */ - roles: external_exports.array(external_exports.string()).default([]), - /** Aggregated permission names (resolved from PermissionSet) */ - permissions: external_exports.array(external_exports.string()).default([]), - /** Whether this is a system-level operation (bypasses permission checks) */ - isSystem: external_exports.boolean().default(false), - /** Raw access token (for external API call pass-through) */ - accessToken: external_exports.string().optional(), - /** Database transaction handle */ - transaction: external_exports.unknown().optional(), - /** Request trace ID (for distributed tracing) */ - traceId: external_exports.string().optional() -}); -var DataEngineFilterSchema2 = external_exports.union([ - external_exports.record(external_exports.string(), external_exports.unknown()), - FilterConditionSchema4 -]).describe("Data Engine query filter conditions"); -var DataEngineSortSchema2 = external_exports.union([ - external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])), - external_exports.record(external_exports.string(), external_exports.union([external_exports.literal(1), external_exports.literal(-1)])), - external_exports.array(SortNodeSchema3) -]).describe("Sort order definition"); -var BaseEngineOptionsSchema2 = external_exports.object({ - /** Execution context (identity, tenant, transaction) */ - context: ExecutionContextSchema3.optional() -}); -var EngineQueryOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** Filter conditions (WHERE) — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), - /** Fields to retrieve (SELECT) — standard QueryAST `fields` */ - fields: external_exports.array(FieldNodeSchema3).optional(), - /** Sorting instructions (ORDER BY) — standard QueryAST `orderBy` */ - orderBy: external_exports.array(SortNodeSchema3).optional(), - /** Max records to return (LIMIT) */ - limit: external_exports.number().optional(), - /** Records to skip (OFFSET) — standard QueryAST `offset` */ - offset: external_exports.number().optional(), - /** Alias for limit (OData compatibility) */ - top: external_exports.number().optional(), - /** Cursor for keyset pagination */ - cursor: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** Full-text search configuration */ - search: FullTextSearchSchema3.optional(), - /** - * Recursive relation loading map (expand). - * - * Keys are lookup/master_detail field names; values are nested QueryAST - * objects that control select, filter, sort, and further expansion on - * the related object. The engine resolves expand via batch $in queries - * (driver-agnostic) with a default max depth of 3. - */ - expand: external_exports.lazy(() => external_exports.record(external_exports.string(), QuerySchema3)).optional(), - /** SELECT DISTINCT flag */ - distinct: external_exports.boolean().optional() -}).describe("QueryAST-aligned query options for IDataEngine.find() operations"); -var DataEngineQueryOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** @deprecated Use `where` (EngineQueryOptionsSchema) */ - filter: DataEngineFilterSchema2.optional(), - /** @deprecated Use `fields` (EngineQueryOptionsSchema) */ - select: external_exports.array(external_exports.string()).optional(), - /** @deprecated Use `orderBy` (EngineQueryOptionsSchema) */ - sort: DataEngineSortSchema2.optional(), - limit: external_exports.number().int().min(1).optional(), - /** @deprecated Use `offset` (EngineQueryOptionsSchema) */ - skip: external_exports.number().int().min(0).optional(), - top: external_exports.number().int().min(1).optional(), - /** @deprecated Use `expand` (EngineQueryOptionsSchema) */ - populate: external_exports.array(external_exports.string()).optional() -}).describe("Query options for IDataEngine.find() operations"); -var DataEngineInsertOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** - * Return the inserted record(s)? - * Some drivers support RETURNING clause for efficiency. - * Default: true - */ - returning: external_exports.boolean().default(true).optional() -}).describe("Options for DataEngine.insert operations"); -var EngineUpdateOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** Filter conditions to identify records to update — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), - /** Perform an upsert? If true, insert if not found. */ - upsert: external_exports.boolean().default(false).optional(), - /** Update multiple records? If false, only the first match is updated. Default: false */ - multi: external_exports.boolean().default(false).optional(), - /** Return the updated record(s)? Default: false (returns update count/status) */ - returning: external_exports.boolean().default(false).optional() -}).describe("QueryAST-aligned options for DataEngine.update operations"); -var DataEngineUpdateOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** @deprecated Use `where` (EngineUpdateOptionsSchema) */ - filter: DataEngineFilterSchema2.optional(), - upsert: external_exports.boolean().default(false).optional(), - multi: external_exports.boolean().default(false).optional(), - returning: external_exports.boolean().default(false).optional() -}).describe("Options for DataEngine.update operations"); -var EngineDeleteOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** Filter conditions to identify records to delete — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), - /** Delete multiple records? If false, only the first match is deleted. Default: false */ - multi: external_exports.boolean().default(false).optional() -}).describe("QueryAST-aligned options for DataEngine.delete operations"); -var DataEngineDeleteOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** @deprecated Use `where` (EngineDeleteOptionsSchema) */ - filter: DataEngineFilterSchema2.optional(), - multi: external_exports.boolean().default(false).optional() -}).describe("Options for DataEngine.delete operations"); -var EngineAggregateOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** Filter conditions (WHERE) — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), - /** Group By fields */ - groupBy: external_exports.array(external_exports.string()).optional(), - /** - * Aggregation definitions — uses standard AggregationNodeSchema (`function` key). - * e.g. [{ function: 'sum', field: 'amount', alias: 'total' }] - */ - aggregations: external_exports.array(AggregationNodeSchema3).optional() -}).describe("QueryAST-aligned options for DataEngine.aggregate operations"); -var DataEngineAggregateOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** @deprecated Use `where` (EngineAggregateOptionsSchema) */ - filter: DataEngineFilterSchema2.optional(), - groupBy: external_exports.array(external_exports.string()).optional(), - /** - * @deprecated Use `EngineAggregateOptionsSchema` with standard AggregationNodeSchema (`function` key). - */ - aggregations: external_exports.array(external_exports.object({ - field: external_exports.string(), - method: external_exports.enum(["count", "sum", "avg", "min", "max", "count_distinct"]), - alias: external_exports.string().optional() - })).optional() -}).describe("Options for DataEngine.aggregate operations"); -var EngineCountOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** Filter conditions — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional() -}).describe("QueryAST-aligned options for DataEngine.count operations"); -var DataEngineCountOptionsSchema2 = BaseEngineOptionsSchema2.extend({ - /** @deprecated Use `where` (EngineCountOptionsSchema) */ - filter: DataEngineFilterSchema2.optional() -}).describe("Options for DataEngine.count operations"); -var DataEngineContractSchema2 = external_exports.object({ - find: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineQueryOptionsSchema2.optional()])).output(external_exports.promise(external_exports.array(external_exports.unknown()))), - findOne: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineQueryOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())), - insert: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown()))]), DataEngineInsertOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())), - update: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), EngineUpdateOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())), - delete: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineDeleteOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())), - count: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineCountOptionsSchema2.optional()])).output(external_exports.promise(external_exports.number())), - aggregate: external_exports.function().input(external_exports.tuple([external_exports.string(), EngineAggregateOptionsSchema2])).output(external_exports.promise(external_exports.array(external_exports.unknown()))) -}).describe("Standard Data Engine Contract"); -var RpcLegacyFilterMixin2 = { - /** @deprecated Use `where` */ - filter: DataEngineFilterSchema2.optional() -}; -var RpcQueryOptionsSchema2 = EngineQueryOptionsSchema2.extend({ - ...RpcLegacyFilterMixin2, - /** @deprecated Use `fields` */ - select: external_exports.array(external_exports.string()).optional(), - /** @deprecated Use `orderBy` */ - sort: DataEngineSortSchema2.optional(), - /** @deprecated Use `offset` */ - skip: external_exports.number().int().min(0).optional(), - /** @deprecated Use `expand` */ - populate: external_exports.array(external_exports.string()).optional() -}); -var DataEngineFindRequestSchema2 = external_exports.object({ - method: external_exports.literal("find"), - object: external_exports.string(), - query: RpcQueryOptionsSchema2.optional() -}); -var DataEngineFindOneRequestSchema2 = external_exports.object({ - method: external_exports.literal("findOne"), - object: external_exports.string(), - query: RpcQueryOptionsSchema2.optional() -}); -var DataEngineInsertRequestSchema2 = external_exports.object({ - method: external_exports.literal("insert"), - object: external_exports.string(), - data: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown()))]), - options: DataEngineInsertOptionsSchema2.optional() -}); -var DataEngineUpdateRequestSchema2 = external_exports.object({ - method: external_exports.literal("update"), - object: external_exports.string(), - data: external_exports.record(external_exports.string(), external_exports.unknown()), - id: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("ID for single update, or use where in options"), - options: EngineUpdateOptionsSchema2.extend(RpcLegacyFilterMixin2).optional() -}); -var DataEngineDeleteRequestSchema2 = external_exports.object({ - method: external_exports.literal("delete"), - object: external_exports.string(), - id: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("ID for single delete, or use where in options"), - options: EngineDeleteOptionsSchema2.extend(RpcLegacyFilterMixin2).optional() -}); -var DataEngineCountRequestSchema2 = external_exports.object({ - method: external_exports.literal("count"), - object: external_exports.string(), - query: EngineCountOptionsSchema2.extend(RpcLegacyFilterMixin2).optional() -}); -var DataEngineAggregateRequestSchema2 = external_exports.object({ - method: external_exports.literal("aggregate"), - object: external_exports.string(), - query: EngineAggregateOptionsSchema2.extend(RpcLegacyFilterMixin2) -}); -var DataEngineExecuteRequestSchema2 = external_exports.object({ - method: external_exports.literal("execute"), - /** The abstract command (string SQL, or JSON object) */ - command: external_exports.unknown(), - /** Optional options */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var DataEngineVectorFindRequestSchema2 = external_exports.object({ - method: external_exports.literal("vectorFind"), - object: external_exports.string(), - /** The vector embedding to search for */ - vector: external_exports.array(external_exports.number()), - /** Optional pre-filter (Metadata filtering) — standard QueryAST `where` */ - where: external_exports.union([external_exports.record(external_exports.string(), external_exports.unknown()), FilterConditionSchema4]).optional(), - /** Fields to retrieve — standard QueryAST `fields` */ - fields: external_exports.array(external_exports.string()).optional(), - /** Number of results */ - limit: external_exports.number().int().default(5).optional(), - /** Minimum similarity score (0-1) or distance threshold */ - threshold: external_exports.number().optional() -}); -var DataEngineBatchRequestSchema2 = external_exports.object({ - method: external_exports.literal("batch"), - requests: external_exports.array(external_exports.discriminatedUnion("method", [ - DataEngineFindRequestSchema2, - DataEngineFindOneRequestSchema2, - DataEngineInsertRequestSchema2, - DataEngineUpdateRequestSchema2, - DataEngineDeleteRequestSchema2, - DataEngineCountRequestSchema2, - DataEngineAggregateRequestSchema2, - DataEngineExecuteRequestSchema2, - DataEngineVectorFindRequestSchema2 - ])), - /** - * Transaction Mode - * - true: All or nothing (Atomic) - * - false: Best effort, continue on error - */ - transaction: external_exports.boolean().default(true).optional() -}); -var DataEngineRequestSchema2 = external_exports.discriminatedUnion("method", [ - DataEngineFindRequestSchema2, - DataEngineFindOneRequestSchema2, - DataEngineInsertRequestSchema2, - DataEngineUpdateRequestSchema2, - DataEngineDeleteRequestSchema2, - DataEngineCountRequestSchema2, - DataEngineAggregateRequestSchema2, - DataEngineBatchRequestSchema2, - DataEngineExecuteRequestSchema2, - DataEngineVectorFindRequestSchema2 -]).describe("Virtual ObjectQL Request Protocol"); -var DriverOptionsSchema2 = external_exports.object({ - /** - * Transaction handle/identifier. - * If provided, the operation must run within this transaction. - */ - transaction: external_exports.unknown().optional().describe("Transaction handle"), - /** - * Operation timeout in milliseconds. - */ - timeout: external_exports.number().optional().describe("Timeout in ms"), - /** - * Whether to bypass cache and force a fresh read. - */ - skipCache: external_exports.boolean().optional().describe("Bypass cache"), - /** - * Distributed Tracing Context. - * Used for passing OpenTelemetry span context or request IDs for observability. - */ - traceContext: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("OpenTelemetry context or request ID"), - /** - * Tenant Identifier. - * For multi-tenant databases (row-level security or schema-per-tenant). - */ - tenantId: external_exports.string().optional().describe("Tenant Isolation identifier") -}); -var DriverCapabilitiesSchema2 = external_exports.object({ - // ============================================================================ - // Basic CRUD Operations - // ============================================================================ - /** - * Whether the driver supports create operations. - */ - create: external_exports.boolean().default(true).describe("Supports CREATE operations"), - /** - * Whether the driver supports read operations. - */ - read: external_exports.boolean().default(true).describe("Supports READ operations"), - /** - * Whether the driver supports update operations. - */ - update: external_exports.boolean().default(true).describe("Supports UPDATE operations"), - /** - * Whether the driver supports delete operations. - */ - delete: external_exports.boolean().default(true).describe("Supports DELETE operations"), - // ============================================================================ - // Bulk Operations - // ============================================================================ - /** - * Whether the driver supports bulk create operations. - */ - bulkCreate: external_exports.boolean().default(false).describe("Supports bulk CREATE operations"), - /** - * Whether the driver supports bulk update operations. - */ - bulkUpdate: external_exports.boolean().default(false).describe("Supports bulk UPDATE operations"), - /** - * Whether the driver supports bulk delete operations. - */ - bulkDelete: external_exports.boolean().default(false).describe("Supports bulk DELETE operations"), - // ============================================================================ - // Transaction & Connection Management - // ============================================================================ - /** - * Whether the driver supports database transactions. - * If true, beginTransaction, commit, and rollback must be implemented. - */ - transactions: external_exports.boolean().default(false).describe("Supports ACID transactions"), - /** - * Whether the driver supports savepoints within transactions. - */ - savepoints: external_exports.boolean().default(false).describe("Supports transaction savepoints"), - /** - * Supported transaction isolation levels. - */ - isolationLevels: external_exports.array(IsolationLevelEnum3).optional().describe("Supported isolation levels"), - // ============================================================================ - // Query Operations - // ============================================================================ - /** - * Whether the driver supports WHERE clause filters. - * If false, ObjectQL will fetch all records and filter in memory. - * - * Example: Memory driver might not support complex filter conditions. - */ - queryFilters: external_exports.boolean().default(true).describe("Supports WHERE clause filtering"), - /** - * Whether the driver supports aggregation functions (COUNT, SUM, AVG, etc.). - * If false, ObjectQL will compute aggregations in memory. - */ - queryAggregations: external_exports.boolean().default(false).describe("Supports GROUP BY and aggregation functions"), - /** - * Whether the driver supports ORDER BY sorting. - * If false, ObjectQL will sort results in memory. - */ - querySorting: external_exports.boolean().default(true).describe("Supports ORDER BY sorting"), - /** - * Whether the driver supports LIMIT/OFFSET pagination. - * If false, ObjectQL will fetch all records and paginate in memory. - */ - queryPagination: external_exports.boolean().default(true).describe("Supports LIMIT/OFFSET pagination"), - /** - * Whether the driver supports window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.). - * If false, ObjectQL will compute window functions in memory. - */ - queryWindowFunctions: external_exports.boolean().default(false).describe("Supports window functions with OVER clause"), - /** - * Whether the driver supports subqueries (nested SELECT statements). - * If false, ObjectQL will execute queries separately and combine results. - */ - querySubqueries: external_exports.boolean().default(false).describe("Supports subqueries"), - /** - * Whether the driver supports Common Table Expressions (WITH clause). - */ - queryCTE: external_exports.boolean().default(false).describe("Supports Common Table Expressions (WITH clause)"), - /** - * Whether the driver supports SQL-style joins. - * If false, ObjectQL will fetch related data separately and join in memory. - */ - joins: external_exports.boolean().default(false).describe("Supports SQL joins"), - // ============================================================================ - // Advanced Features - // ============================================================================ - /** - * Whether the driver supports full-text search. - * If true, text search queries can be pushed to the database. - */ - fullTextSearch: external_exports.boolean().default(false).describe("Supports full-text search"), - /** - * Whether the driver supports JSON querying capabilities. - */ - jsonQuery: external_exports.boolean().default(false).describe("Supports JSON field querying"), - /** - * Whether the driver supports geospatial queries. - */ - geospatialQuery: external_exports.boolean().default(false).describe("Supports geospatial queries"), - /** - * Whether the driver supports streaming large result sets. - */ - streaming: external_exports.boolean().default(false).describe("Supports result streaming (cursors/iterators)"), - /** - * Whether the driver supports JSON field types. - * If false, JSON data will be serialized as strings. - */ - jsonFields: external_exports.boolean().default(false).describe("Supports JSON field types"), - /** - * Whether the driver supports array field types. - * If false, arrays will be stored as JSON strings or in separate tables. - */ - arrayFields: external_exports.boolean().default(false).describe("Supports array field types"), - /** - * Whether the driver supports vector embeddings and similarity search. - * Required for RAG (Retrieval-Augmented Generation) and AI features. - */ - vectorSearch: external_exports.boolean().default(false).describe("Supports vector embeddings and similarity search"), - // ============================================================================ - // Schema Management - // ============================================================================ - /** - * Whether the driver supports automatic schema synchronization. - */ - schemaSync: external_exports.boolean().default(false).describe("Supports automatic schema synchronization"), - /** - * Whether the driver supports batching multiple schema sync operations - * into a single (or fewer) round-trips for the DDL phase. When true, - * the engine may call `syncSchemasBatch()` instead of calling - * `syncSchema()` per object, reducing network round-trips for remote drivers. - */ - batchSchemaSync: external_exports.boolean().default(false).describe("Supports batched schema sync to reduce schema DDL round-trips"), - /** - * Whether the driver supports database migrations. - */ - migrations: external_exports.boolean().default(false).describe("Supports database migrations"), - /** - * Whether the driver supports index management. - */ - indexes: external_exports.boolean().default(false).describe("Supports index creation and management"), - // ============================================================================ - // Performance & Optimization - // ============================================================================ - /** - * Whether the driver supports connection pooling. - */ - connectionPooling: external_exports.boolean().default(false).describe("Supports connection pooling"), - /** - * Whether the driver supports prepared statements. - */ - preparedStatements: external_exports.boolean().default(false).describe("Supports prepared statements (SQL injection prevention)"), - /** - * Whether the driver supports query result caching. - */ - queryCache: external_exports.boolean().default(false).describe("Supports query result caching") -}); -var DriverInterfaceSchema2 = external_exports.object({ - /** - * Driver name (e.g., 'postgresql', 'mongodb', 'rest_api'). - */ - name: external_exports.string().describe("Driver unique name"), - /** - * Driver version. - */ - version: external_exports.string().describe("Driver version"), - /** - * Capabilities descriptor. - */ - supports: DriverCapabilitiesSchema2, - // ============================================================================ - // Lifecycle Management - // ============================================================================ - /** - * Initialize connection pool or authenticate. - */ - connect: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.void())).describe("Establish connection"), - /** - * Close connections and cleanup resources. - */ - disconnect: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.void())).describe("Close connection"), - /** - * Check connection health. - * @returns true if healthy, false otherwise. - */ - checkHealth: external_exports.function().input(external_exports.tuple([])).output(external_exports.promise(external_exports.boolean())).describe("Health check"), - /** - * Get Connection Pool Statistics. - * Useful for monitoring database load. - */ - getPoolStats: external_exports.function().input(external_exports.tuple([])).output(external_exports.object({ - total: external_exports.number(), - idle: external_exports.number(), - active: external_exports.number(), - waiting: external_exports.number() - }).optional()).optional().describe("Get connection pool statistics"), - // ============================================================================ - // Raw Execution (Escape Hatch) - // ============================================================================ - /** - * Execute a raw command/query native to the driver. - * Useful for complex reports, stored procedures, or DDL not covered by standard sync. - * - * @param command - The raw command (e.g., SQL string, shell command, or remote API payload). - * @param parameters - Optional array of bound parameters for safe execution (prevention of injection). - * @param options - Driver options (transaction context, timeout). - * @returns Promise resolving to the raw result from the driver. - * - * @example - * // SQL Driver - * await driver.execute('SELECT * FROM complex_view WHERE id = ?', [123]); - * - * // Mongo Driver - * await driver.execute({ aggregate: 'orders', pipeline: [...] }); - */ - execute: external_exports.function().input(external_exports.tuple([external_exports.unknown(), external_exports.array(external_exports.unknown()).optional(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())).describe("Execute raw command"), - // ============================================================================ - // CRUD Operations - // ============================================================================ - /** - * Find multiple records matching the structured query. - * Parsing the QueryAST is the responsibility of the driver implementation. - * - * @param object - The name of the object/table to query (e.g. 'account'). - * @param query - The structured QueryAST (filters, sorts, joins, pagination). - * @param options - Driver options. - * @returns Array of records. - * - * @example - * await driver.find('account', { - * filters: [['status', '=', 'active'], 'and', ['amount', '>', 500]], - * sort: [{ field: 'created_at', order: 'desc' }], - * top: 10 - * }); - * @returns Array of records. - * MUST return `id` as string. MUST NOT return implementation details like `_id`. - */ - find: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))).describe("Find records"), - /** - * Stream records matching the structured query. - * Optimized for large datasets to avoid memory overflow. - * - * @param object - The name of the object. - * @param query - The structured QueryAST. - * @param options - Driver options. - * @returns AsyncIterable/ReadableStream of records. - */ - findStream: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.unknown()).describe("Stream records (AsyncIterable)"), - /** - * Find a single record by query. - * Similar to find(), but returns only the first match or null. - * - * @param object - The name of the object. - * @param query - QueryAST. - * @param options - Driver options. - * @returns The record or null. - * MUST return `id` as string. MUST NOT return implementation details like `_id`. - */ - findOne: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()).nullable())).describe("Find one record"), - /** - * Create a new record. - * - * @param object - The object name. - * @param data - Key-value map of field data. - * @param options - Driver options. - * @returns The created record, including server-generated fields (id, created_at, etc.). - * MUST return `id` as string. MUST NOT return implementation details like `_id`. - */ - create: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Create record"), - /** - * Update an existing record by ID. - * - * @param object - The object name. - * @param id - The unique identifier of the record. - * @param data - The fields to update. - * @param options - Driver options. - * @returns The updated record. - * MUST return `id` as string. MUST NOT return implementation details like `_id`. - */ - update: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.string().or(external_exports.number()), external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Update record"), - /** - * Upsert (Update or Insert) a record. - * - * @param object - The object name. - * @param data - The data to upsert. - * @param conflictKeys - Fields to check for conflict (uniqueness). - * @param options - Driver options. - * @returns The created or updated record. - */ - upsert: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown()), external_exports.array(external_exports.string()).optional(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.record(external_exports.string(), external_exports.unknown()))).describe("Upsert record"), - /** - * Delete a record by ID. - * - * @param object - The object name. - * @param id - The unique identifier of the record. - * @param options - Driver options. - * @returns True if deleted, false if not found. - */ - delete: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.string().or(external_exports.number()), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.boolean())).describe("Delete record"), - /** - * Count records matching a query. - * - * @param object - The object name. - * @param query - Optional filtering criteria. - * @param options - Driver options. - * @returns Total count. - */ - count: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3.optional(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.number())).describe("Count records"), - // ============================================================================ - // Bulk Operations - // ============================================================================ - /** - * Create multiple records in a single batch. - * Optimized for performance. - * - * @param object - The object name. - * @param dataArray - Array of record data. - * @returns Array of created records. - */ - bulkCreate: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))), - /** - * Update multiple records in a single batch. - * - * @param object - The object name. - * @param updates - Array of objects containing {id, data}. - * @returns Array of updated records. - */ - bulkUpdate: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.object({ id: external_exports.string().or(external_exports.number()), data: external_exports.record(external_exports.string(), external_exports.unknown()) })), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())))), - /** - * Delete multiple records in a single batch. - * - * @param object - The object name. - * @param ids - Array of record IDs. - */ - bulkDelete: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.array(external_exports.string().or(external_exports.number())), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.void())), - /** - * Update multiple records matching a query. - * Direct database push-down. DOES NOT trigger per-record hooks. - * - * @param object - The object name. - * @param query - The filtering criteria. - * @param data - The data to update. - * @returns Count of modified records. - */ - updateMany: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, external_exports.record(external_exports.string(), external_exports.unknown()), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.number())).optional(), - /** - * Delete multiple records matching a query. - * Direct database push-down. DOES NOT trigger per-record hooks. - * - * @param object - The object name. - * @param query - The filtering criteria. - * @returns Count of deleted records. - */ - deleteMany: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.number())).optional(), - // ============================================================================ - // Transaction Management - // ============================================================================ - /** - * Begin a new database transaction. - * @param options - Isolation level and other settings. - * @returns A transaction handle to be passed to subsequent operations via `options.transaction`. - */ - beginTransaction: external_exports.function().input(external_exports.tuple([external_exports.object({ - isolationLevel: IsolationLevelEnum3.optional() - }).optional()])).output(external_exports.promise(external_exports.unknown())).describe("Start transaction"), - /** - * Commit the transaction. - * @param transaction - The transaction handle. - */ - commit: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.promise(external_exports.void())).describe("Commit transaction"), - /** - * Rollback the transaction. - * @param transaction - The transaction handle. - */ - rollback: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.promise(external_exports.void())).describe("Rollback transaction"), - // ============================================================================ - // Schema Management - // ============================================================================ - /** - * Synchronize the database schema with the Object definition. - * This is an idempotent operation: it should create tables if missing, - * add columns if missing, and update indexes. - * - * @param object - The object name. - * @param schema - The full Object Schema (fields, indexes, etc). - * @param options - Driver options. - */ - syncSchema: external_exports.function().input(external_exports.tuple([external_exports.string(), external_exports.unknown(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.void())).describe("Sync object schema to DB"), - /** - * Batch-synchronize multiple object schemas with fewer round-trips. - * - * Drivers that advertise `supports.batchSchemaSync = true` MUST implement - * this method. The engine will call it once with every - * `{ object, schema }` pair instead of calling `syncSchema()` N times. - * - * @param schemas - Array of `{ object: string; schema: unknown }` pairs. - * @param options - Driver options. - */ - syncSchemasBatch: external_exports.function().input(external_exports.tuple([ - external_exports.array(external_exports.object({ object: external_exports.string(), schema: external_exports.unknown() })), - DriverOptionsSchema2.optional() - ])).output(external_exports.promise(external_exports.void())).optional().describe("Batch sync multiple schemas in one round-trip"), - /** - * Drop the underlying table or collection for an object. - * WARNING: Destructive operation. - * - * @param object - The object name. - */ - dropTable: external_exports.function().input(external_exports.tuple([external_exports.string(), DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.void())), - /** - * Analyze query performance. - * Returns execution plan without executing the query (where possible). - * - * @param object - The object name. - * @param query - The query to explain. - * @returns The execution plan details. - */ - explain: external_exports.function().input(external_exports.tuple([external_exports.string(), QuerySchema3, DriverOptionsSchema2.optional()])).output(external_exports.promise(external_exports.unknown())).optional() -}); -var PoolConfigSchema2 = external_exports.object({ - min: external_exports.number().min(0).default(2).describe("Minimum number of connections in pool"), - max: external_exports.number().min(1).default(10).describe("Maximum number of connections in pool"), - idleTimeoutMillis: external_exports.number().min(0).default(3e4).describe("Time in ms before idle connection is closed"), - connectionTimeoutMillis: external_exports.number().min(0).default(5e3).describe("Time in ms to wait for available connection") -}); -var DriverConfigSchema2 = external_exports.object({ - name: external_exports.string().describe("Driver instance name"), - type: external_exports.enum(["sql", "nosql", "cache", "search", "graph", "timeseries"]).describe("Driver type category"), - capabilities: DriverCapabilitiesSchema2.describe("Driver capability flags"), - connectionString: external_exports.string().optional().describe("Database connection string (driver-specific format)"), - poolConfig: PoolConfigSchema2.optional().describe("Connection pool configuration") -}); -var SQLDialectSchema2 = external_exports.enum([ - "postgresql", - "mysql", - "sqlite", - "mssql", - "oracle", - "mariadb" -]); -var DataTypeMappingSchema2 = external_exports.object({ - text: external_exports.string().describe("SQL type for text fields (e.g., VARCHAR, TEXT)"), - number: external_exports.string().describe("SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)"), - boolean: external_exports.string().describe("SQL type for boolean fields (e.g., BOOLEAN, BIT)"), - date: external_exports.string().describe("SQL type for date fields (e.g., DATE)"), - datetime: external_exports.string().describe("SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)"), - json: external_exports.string().optional().describe("SQL type for JSON fields (e.g., JSON, JSONB)"), - uuid: external_exports.string().optional().describe("SQL type for UUID fields (e.g., UUID, CHAR(36))"), - binary: external_exports.string().optional().describe("SQL type for binary fields (e.g., BLOB, BYTEA)") -}); -var SSLConfigSchema2 = external_exports.object({ - rejectUnauthorized: external_exports.boolean().default(true).describe("Reject connections with invalid certificates"), - ca: external_exports.string().optional().describe("CA certificate file path or content"), - cert: external_exports.string().optional().describe("Client certificate file path or content"), - key: external_exports.string().optional().describe("Client private key file path or content") -}).refine((data) => { - const hasCert = data.cert !== void 0; - const hasKey = data.key !== void 0; - return hasCert === hasKey; -}, { - message: "Client certificate (cert) and private key (key) must be provided together" -}); -var SQLDriverConfigSchema2 = DriverConfigSchema2.extend({ - type: external_exports.literal("sql").describe('Driver type must be "sql"'), - dialect: SQLDialectSchema2.describe("SQL database dialect"), - dataTypeMapping: DataTypeMappingSchema2.describe("SQL data type mapping configuration"), - ssl: external_exports.boolean().default(false).describe("Enable SSL/TLS connection"), - sslConfig: SSLConfigSchema2.optional().describe("SSL/TLS configuration (required when ssl is true)") -}).refine((data) => { - if (data.ssl && !data.sslConfig) { - return false; - } - return true; -}, { - message: "sslConfig is required when ssl is true" -}); -var SQLiteDataTypeMappingDefaults2 = { - text: "TEXT", - number: "REAL", - boolean: "INTEGER", - date: "TEXT", - datetime: "TEXT", - json: "TEXT", - uuid: "TEXT", - binary: "BLOB" -}; -var SQLiteAlterTableLimitations2 = { - /** SQLite supports ADD COLUMN */ - supportsAddColumn: true, - /** SQLite supports RENAME COLUMN (3.25.0+) */ - supportsRenameColumn: true, - /** SQLite supports DROP COLUMN (3.35.0+) */ - supportsDropColumn: true, - /** SQLite does NOT support MODIFY/ALTER COLUMN type */ - supportsModifyColumn: false, - /** SQLite does NOT support adding constraints to existing columns */ - supportsAddConstraint: false, - /** - * When an unsupported alteration is needed, the migration planner - * must use the 12-step table rebuild strategy: - * 1. CREATE new table with desired schema - * 2. Copy data from old table - * 3. DROP old table - * 4. RENAME new table to old name - */ - rebuildStrategy: "create_copy_drop_rename" -}; -var NoSQLDatabaseTypeSchema2 = external_exports.enum([ - "mongodb", - "couchdb", - "dynamodb", - "cassandra", - "redis", - "elasticsearch", - "neo4j", - "orientdb" -]); -var NoSQLOperationTypeSchema2 = external_exports.enum([ - "find", - // Query documents/records - "findOne", - // Get single document - "insert", - // Insert document - "update", - // Update document - "delete", - // Delete document - "aggregate", - // Aggregation pipeline - "mapReduce", - // MapReduce operation - "count", - // Count documents - "distinct", - // Get distinct values - "createIndex", - // Create index - "dropIndex" - // Drop index -]); -var ConsistencyLevelSchema2 = external_exports.enum([ - "all", - "quorum", - "one", - "local_quorum", - "each_quorum", - "eventual" -]); -var NoSQLIndexTypeSchema2 = external_exports.enum([ - "single", - // Single field index - "compound", - // Multiple fields index - "unique", - // Unique constraint - "text", - // Full-text search index - "geospatial", - // Geospatial index (2d, 2dsphere) - "hashed", - // Hashed index for sharding - "ttl", - // Time-to-live index (auto-deletion) - "sparse" - // Sparse index (only indexed documents with field) -]); -var ShardingConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable sharding"), - shardKey: external_exports.string().optional().describe("Field to use as shard key"), - shardingStrategy: external_exports.enum(["hash", "range", "zone"]).optional().describe("Sharding strategy"), - numShards: external_exports.number().int().positive().optional().describe("Number of shards") -}); -var ReplicationConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable replication"), - replicaSetName: external_exports.string().optional().describe("Replica set name"), - replicas: external_exports.number().int().positive().optional().describe("Number of replicas"), - readPreference: external_exports.enum(["primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"]).optional().describe("Read preference for replica set"), - writeConcern: external_exports.enum(["majority", "acknowledged", "unacknowledged"]).optional().describe("Write concern level") -}); -var DocumentSchemaValidationSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable schema validation"), - validationLevel: external_exports.enum(["strict", "moderate", "off"]).optional().describe("Validation strictness"), - validationAction: external_exports.enum(["error", "warn"]).optional().describe("Action on validation failure"), - jsonSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON Schema for validation") -}); -var NoSQLDataTypeMappingSchema2 = external_exports.object({ - text: external_exports.string().describe("NoSQL type for text fields"), - number: external_exports.string().describe("NoSQL type for number fields"), - boolean: external_exports.string().describe("NoSQL type for boolean fields"), - date: external_exports.string().describe("NoSQL type for date fields"), - datetime: external_exports.string().describe("NoSQL type for datetime fields"), - json: external_exports.string().optional().describe("NoSQL type for JSON/object fields"), - uuid: external_exports.string().optional().describe("NoSQL type for UUID fields"), - binary: external_exports.string().optional().describe("NoSQL type for binary fields"), - array: external_exports.string().optional().describe("NoSQL type for array fields"), - objectId: external_exports.string().optional().describe("NoSQL type for ObjectID fields (MongoDB)"), - geopoint: external_exports.string().optional().describe("NoSQL type for geospatial point fields") -}); -var NoSQLDriverConfigSchema2 = DriverConfigSchema2.extend({ - type: external_exports.literal("nosql").describe('Driver type must be "nosql"'), - databaseType: NoSQLDatabaseTypeSchema2.describe("Specific NoSQL database type"), - dataTypeMapping: NoSQLDataTypeMappingSchema2.describe("NoSQL data type mapping configuration"), - /** - * Consistency level for reads/writes - */ - consistency: ConsistencyLevelSchema2.optional().describe("Consistency level for operations"), - /** - * Replication configuration - */ - replication: ReplicationConfigSchema2.optional().describe("Replication configuration"), - /** - * Sharding configuration - */ - sharding: ShardingConfigSchema2.optional().describe("Sharding configuration"), - /** - * Schema validation rules (for document databases) - */ - schemaValidation: DocumentSchemaValidationSchema2.optional().describe("Document schema validation"), - /** - * AWS Region (for DynamoDB, DocumentDB, etc.) - */ - region: external_exports.string().optional().describe("AWS region (for managed NoSQL services)"), - /** - * AWS Access Key ID (for DynamoDB, DocumentDB, etc.) - */ - accessKeyId: external_exports.string().optional().describe("AWS access key ID"), - /** - * AWS Secret Access Key (for DynamoDB, DocumentDB, etc.) - */ - secretAccessKey: external_exports.string().optional().describe("AWS secret access key"), - /** - * Time-to-live (TTL) field name - * Automatically delete documents after a specified time - */ - ttlField: external_exports.string().optional().describe("Field name for TTL (auto-deletion)"), - /** - * Maximum document size in bytes - */ - maxDocumentSize: external_exports.number().int().positive().optional().describe("Maximum document size in bytes"), - /** - * Collection/Table name prefix - * Useful for multi-tenancy or environment isolation - */ - collectionPrefix: external_exports.string().optional().describe("Prefix for collection/table names") -}); -var NoSQLQueryOptionsSchema2 = external_exports.object({ - /** - * Consistency level for this query - */ - consistency: ConsistencyLevelSchema2.optional().describe("Consistency level override"), - /** - * Read from secondary replicas - */ - readFromSecondary: external_exports.boolean().optional().describe("Allow reading from secondary replicas"), - /** - * Projection (fields to include/exclude) - */ - projection: external_exports.record(external_exports.string(), external_exports.union([external_exports.literal(0), external_exports.literal(1)])).optional().describe("Field projection"), - /** - * Query timeout in milliseconds - */ - timeout: external_exports.number().int().positive().optional().describe("Query timeout (ms)"), - /** - * Use cursor for large result sets - */ - useCursor: external_exports.boolean().optional().describe("Use cursor instead of loading all results"), - /** - * Batch size for cursor iteration - */ - batchSize: external_exports.number().int().positive().optional().describe("Cursor batch size"), - /** - * Enable query profiling - */ - profile: external_exports.boolean().optional().describe("Enable query profiling"), - /** - * Use hinted index - */ - hint: external_exports.string().optional().describe("Index hint for query optimization") -}); -var AggregationStageSchema2 = external_exports.object({ - /** - * Stage operator (e.g., $match, $group, $sort, $project) - */ - operator: external_exports.string().describe("Aggregation operator (e.g., $match, $group, $sort)"), - /** - * Stage parameters/options - */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Stage-specific options") -}); -var AggregationPipelineSchema2 = external_exports.object({ - /** - * Collection/Table to aggregate - */ - collection: external_exports.string().describe("Collection/table name"), - /** - * Pipeline stages - */ - stages: external_exports.array(AggregationStageSchema2).describe("Aggregation pipeline stages"), - /** - * Additional options - */ - options: NoSQLQueryOptionsSchema2.optional().describe("Query options") -}); -var NoSQLIndexSchema2 = external_exports.object({ - /** - * Index name - */ - name: external_exports.string().describe("Index name"), - /** - * Index type - */ - type: NoSQLIndexTypeSchema2.describe("Index type"), - /** - * Fields to index - * For compound indexes, order matters - */ - fields: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name"), - order: external_exports.enum(["asc", "desc", "text", "2dsphere"]).optional().describe("Index order or type") - })).describe("Fields to index"), - /** - * Unique constraint - */ - unique: external_exports.boolean().default(false).describe("Enforce uniqueness"), - /** - * Sparse index (only index documents with the field) - */ - sparse: external_exports.boolean().default(false).describe("Sparse index"), - /** - * TTL in seconds (for TTL indexes) - */ - expireAfterSeconds: external_exports.number().int().positive().optional().describe("TTL in seconds"), - /** - * Partial index filter - */ - partialFilterExpression: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Partial index filter"), - /** - * Background index creation - */ - background: external_exports.boolean().default(false).describe("Create index in background") -}); -var NoSQLTransactionOptionsSchema2 = external_exports.object({ - /** - * Read concern level - */ - readConcern: external_exports.enum(["local", "majority", "linearizable", "snapshot"]).optional().describe("Read concern level"), - /** - * Write concern level - */ - writeConcern: external_exports.enum(["majority", "acknowledged", "unacknowledged"]).optional().describe("Write concern level"), - /** - * Read preference - */ - readPreference: external_exports.enum(["primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"]).optional().describe("Read preference"), - /** - * Transaction timeout in milliseconds - */ - maxCommitTimeMS: external_exports.number().int().positive().optional().describe("Transaction commit timeout (ms)") -}); -var DatasetMode4 = external_exports.enum([ - "insert", - // Try to insert, fail on duplicate - "update", - // Only update found records, ignore new - "upsert", - // Create new or Update existing (Standard) - "replace", - // Delete ALL records in object then insert (Dangerous - use for cache tables) - "ignore" - // Try to insert, silently skip duplicates -]); -var DatasetSchema4 = external_exports.object({ - /** - * Target Object - * The machine name of the object to populate. - */ - object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target Object Name"), - /** - * Idempotency Key (The "Upsert" Key) - * The field used to check if a record already exists. - * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'. - * Standard: 'id' is rarely used for portable seed data — prefer natural keys. - */ - externalId: external_exports.string().default("name").describe("Field match for uniqueness check"), - /** - * Import Strategy - */ - mode: DatasetMode4.default("upsert").describe("Conflict resolution strategy"), - /** - * Environment Scope - * - 'all': Always load - * - 'dev': Only for development/demo - * - 'test': Only for CI/CD tests - */ - env: external_exports.array(external_exports.enum(["prod", "dev", "test"])).default(["prod", "dev", "test"]).describe("Applicable environments"), - /** - * The Payload - * Array of raw JSON objects matching the Object Schema. - */ - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Data records") -}); -var ReferenceResolutionSchema2 = external_exports.object({ - /** The field name on the source object (e.g., 'account_id') */ - field: external_exports.string().describe("Source field name containing the reference value"), - /** The target object being referenced (e.g., 'account') */ - targetObject: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Target object name (snake_case)"), - /** - * The field on the target object used to match the reference value. - * Defaults to the target object's externalId (usually 'name'). - */ - targetField: external_exports.string().default("name").describe("Field on target object used for matching"), - /** The field type that triggered this resolution (lookup or master_detail) */ - fieldType: external_exports.enum(["lookup", "master_detail"]).describe("Relationship field type") -}).describe("Describes how a field reference is resolved during seed loading"); -var ObjectDependencyNodeSchema2 = external_exports.object({ - /** Object machine name */ - object: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Object name (snake_case)"), - /** - * Objects that this object depends on (via lookup/master_detail fields). - * These must be loaded before this object. - */ - dependsOn: external_exports.array(external_exports.string()).describe("Objects this object depends on"), - /** - * Field-level reference details for each dependency. - * Maps field name → reference resolution info. - */ - references: external_exports.array(ReferenceResolutionSchema2).describe("Field-level reference details") -}).describe("Object node in the seed data dependency graph"); -var ObjectDependencyGraphSchema2 = external_exports.object({ - /** All object nodes in the graph */ - nodes: external_exports.array(ObjectDependencyNodeSchema2).describe("All objects in the dependency graph"), - /** - * Topologically sorted object names for insertion order. - * Parent objects appear before child objects. - */ - insertOrder: external_exports.array(external_exports.string()).describe("Topologically sorted insert order"), - /** - * Circular dependency chains detected in the graph. - * Each chain is an array of object names forming a cycle. - * When present, the loader must use a multi-pass strategy. - * - * @example [['project', 'task', 'project']] - */ - circularDependencies: external_exports.array(external_exports.array(external_exports.string())).default([]).describe('Circular dependency chains (e.g., [["a", "b", "a"]])') -}).describe("Complete object dependency graph for seed data loading"); -var ReferenceResolutionErrorSchema2 = external_exports.object({ - /** The source object containing the broken reference */ - sourceObject: external_exports.string().describe("Object with the broken reference"), - /** The field containing the unresolved value */ - field: external_exports.string().describe("Field name with unresolved reference"), - /** The target object that was searched */ - targetObject: external_exports.string().describe("Target object searched for the reference"), - /** The externalId field used for matching on the target object */ - targetField: external_exports.string().describe("ExternalId field used for matching"), - /** The value that could not be resolved */ - attemptedValue: external_exports.unknown().describe("Value that failed to resolve"), - /** The index of the record in the dataset's records array */ - recordIndex: external_exports.number().int().min(0).describe("Index of the record in the dataset"), - /** Human-readable error message */ - message: external_exports.string().describe("Human-readable error description") -}).describe("Actionable error for a failed reference resolution"); -var SeedLoaderConfigSchema2 = external_exports.object({ - /** - * Dry-run mode: validate all references without writing data. - * Surfaces broken references before any mutations occur. - * @default false - */ - dryRun: external_exports.boolean().default(false).describe("Validate references without writing data"), - /** - * Whether to halt on the first reference resolution error. - * When false, collects all errors and continues loading. - * @default false - */ - haltOnError: external_exports.boolean().default(false).describe("Stop on first reference resolution error"), - /** - * Enable multi-pass loading for circular dependencies. - * Pass 1: Insert records with null for circular references. - * Pass 2: Update records to fill deferred references. - * @default true - */ - multiPass: external_exports.boolean().default(true).describe("Enable multi-pass loading for circular dependencies"), - /** - * Default dataset mode when not specified per-dataset. - * @default 'upsert' - */ - defaultMode: DatasetMode4.default("upsert").describe("Default conflict resolution strategy"), - /** - * Maximum number of records to process in a single batch. - * Controls memory usage for large datasets. - * @default 1000 - */ - batchSize: external_exports.number().int().min(1).default(1e3).describe("Maximum records per batch insert/upsert"), - /** - * Whether to wrap the entire load operation in a transaction. - * When true, all-or-nothing semantics apply. - * @default false - */ - transaction: external_exports.boolean().default(false).describe("Wrap entire load in a transaction (all-or-nothing)"), - /** - * Environment filter. Only datasets matching this environment are loaded. - * When not specified, all datasets are loaded regardless of env scope. - */ - env: external_exports.enum(["prod", "dev", "test"]).optional().describe("Only load datasets matching this environment") -}).describe("Seed data loader configuration"); -var DatasetLoadResultSchema2 = external_exports.object({ - /** Target object name */ - object: external_exports.string().describe("Object that was loaded"), - /** Import mode used */ - mode: DatasetMode4.describe("Import mode used"), - /** Number of records successfully inserted */ - inserted: external_exports.number().int().min(0).describe("Records inserted"), - /** Number of records successfully updated (upsert matched existing) */ - updated: external_exports.number().int().min(0).describe("Records updated"), - /** Number of records skipped (mode: ignore, or already exists) */ - skipped: external_exports.number().int().min(0).describe("Records skipped"), - /** Number of records with errors */ - errored: external_exports.number().int().min(0).describe("Records with errors"), - /** Total records in the dataset */ - total: external_exports.number().int().min(0).describe("Total records in dataset"), - /** Number of references resolved via externalId */ - referencesResolved: external_exports.number().int().min(0).describe("References resolved via externalId"), - /** Number of references deferred to pass 2 (circular dependencies) */ - referencesDeferred: external_exports.number().int().min(0).describe("References deferred to second pass"), - /** Reference resolution errors for this object */ - errors: external_exports.array(ReferenceResolutionErrorSchema2).default([]).describe("Reference resolution errors") -}).describe("Result of loading a single dataset"); -var SeedLoaderResultSchema2 = external_exports.object({ - /** Whether the overall load operation succeeded */ - success: external_exports.boolean().describe("Overall success status"), - /** Was this a dry-run (validation only, no writes)? */ - dryRun: external_exports.boolean().describe("Whether this was a dry-run"), - /** The dependency graph used for ordering */ - dependencyGraph: ObjectDependencyGraphSchema2.describe("Object dependency graph"), - /** Per-object load results, in the order they were processed */ - results: external_exports.array(DatasetLoadResultSchema2).describe("Per-object load results"), - /** All reference resolution errors across all objects */ - errors: external_exports.array(ReferenceResolutionErrorSchema2).describe("All reference resolution errors"), - /** Summary statistics */ - summary: external_exports.object({ - /** Total objects processed */ - objectsProcessed: external_exports.number().int().min(0).describe("Total objects processed"), - /** Total records across all objects */ - totalRecords: external_exports.number().int().min(0).describe("Total records across all objects"), - /** Total records inserted */ - totalInserted: external_exports.number().int().min(0).describe("Total records inserted"), - /** Total records updated */ - totalUpdated: external_exports.number().int().min(0).describe("Total records updated"), - /** Total records skipped */ - totalSkipped: external_exports.number().int().min(0).describe("Total records skipped"), - /** Total records with errors */ - totalErrored: external_exports.number().int().min(0).describe("Total records with errors"), - /** Total references resolved via externalId */ - totalReferencesResolved: external_exports.number().int().min(0).describe("Total references resolved"), - /** Total references deferred to second pass */ - totalReferencesDeferred: external_exports.number().int().min(0).describe("Total references deferred"), - /** Number of circular dependency chains detected */ - circularDependencyCount: external_exports.number().int().min(0).describe("Circular dependency chains detected"), - /** Duration of the load operation in milliseconds */ - durationMs: external_exports.number().min(0).describe("Load duration in milliseconds") - }).describe("Summary statistics") -}).describe("Complete seed loader result"); -var SeedLoaderRequestSchema2 = external_exports.object({ - /** Datasets to load */ - datasets: external_exports.array(DatasetSchema4).min(1).describe("Datasets to load"), - /** Loader configuration */ - config: external_exports.preprocess((val) => val ?? {}, SeedLoaderConfigSchema2).describe("Loader configuration") -}).describe("Seed loader request with datasets and configuration"); -var DocumentVersionSchema2 = external_exports.object({ - /** - * Sequential version number (increments with each new version) - */ - versionNumber: external_exports.number().describe("Version number"), - /** - * Timestamp when this version was created (Unix milliseconds) - */ - createdAt: external_exports.number().describe("Creation timestamp"), - /** - * User ID who created this version - */ - createdBy: external_exports.string().describe("Creator user ID"), - /** - * File size in bytes - */ - size: external_exports.number().describe("File size in bytes"), - /** - * Checksum/hash of the file content (for integrity verification) - */ - checksum: external_exports.string().describe("File checksum"), - /** - * URL to download this specific version - */ - downloadUrl: external_exports.string().url().describe("Download URL"), - /** - * Whether this is the latest version - * @default false - */ - isLatest: external_exports.boolean().optional().default(false).describe("Is latest version") -}); -var DocumentTemplateSchema2 = external_exports.object({ - /** - * Unique identifier for the template - */ - id: external_exports.string().describe("Template ID"), - /** - * Human-readable name of the template - */ - name: external_exports.string().describe("Template name"), - /** - * Optional description of the template's purpose - */ - description: external_exports.string().optional().describe("Template description"), - /** - * URL to the template file - */ - fileUrl: external_exports.string().url().describe("Template file URL"), - /** - * MIME type of the template file - */ - fileType: external_exports.string().describe("File MIME type"), - /** - * List of dynamic placeholders in the template - */ - placeholders: external_exports.array(external_exports.object({ - /** - * Placeholder identifier (used in template) - */ - key: external_exports.string().describe("Placeholder key"), - /** - * Human-readable label for the placeholder - */ - label: external_exports.string().describe("Placeholder label"), - /** - * Data type of the placeholder value - */ - type: external_exports.enum(["text", "number", "date", "image"]).describe("Placeholder type"), - /** - * Whether this placeholder must be filled - * @default false - */ - required: external_exports.boolean().optional().default(false).describe("Is required") - })).describe("Template placeholders") -}); -var ESignatureConfigSchema2 = external_exports.object({ - /** - * E-signature service provider - */ - provider: external_exports.enum(["docusign", "adobe-sign", "hellosign", "custom"]).describe("E-signature provider"), - /** - * Whether e-signature is enabled for this document - * @default false - */ - enabled: external_exports.boolean().optional().default(false).describe("E-signature enabled"), - /** - * List of signers in signing order - */ - signers: external_exports.array(external_exports.object({ - /** - * Signer's email address - */ - email: external_exports.string().email().describe("Signer email"), - /** - * Signer's full name - */ - name: external_exports.string().describe("Signer name"), - /** - * Signer's role in the document - */ - role: external_exports.string().describe("Signer role"), - /** - * Signing order (lower numbers sign first) - */ - order: external_exports.number().describe("Signing order") - })).describe("Document signers"), - /** - * Days until signature request expires - * @default 30 - */ - expirationDays: external_exports.number().optional().default(30).describe("Expiration days"), - /** - * Days between reminder emails - * @default 7 - */ - reminderDays: external_exports.number().optional().default(7).describe("Reminder interval days") -}); -var DocumentSchema2 = external_exports.object({ - /** - * Unique document identifier - */ - id: external_exports.string().describe("Document ID"), - /** - * Document name - */ - name: external_exports.string().describe("Document name"), - /** - * Optional document description - */ - description: external_exports.string().optional().describe("Document description"), - /** - * MIME type of the document - */ - fileType: external_exports.string().describe("File MIME type"), - /** - * File size in bytes - */ - fileSize: external_exports.number().describe("File size in bytes"), - /** - * Document category for organization - */ - category: external_exports.string().optional().describe("Document category"), - /** - * Tags for searchability and organization - */ - tags: external_exports.array(external_exports.string()).optional().describe("Document tags"), - /** - * Version control configuration - */ - versioning: external_exports.object({ - /** - * Whether versioning is enabled - */ - enabled: external_exports.boolean().describe("Versioning enabled"), - /** - * List of all document versions - */ - versions: external_exports.array(DocumentVersionSchema2).describe("Version history"), - /** - * Current major version number - */ - majorVersion: external_exports.number().describe("Major version"), - /** - * Current minor version number - */ - minorVersion: external_exports.number().describe("Minor version") - }).optional().describe("Version control"), - /** - * Template configuration (if document is generated from template) - */ - template: DocumentTemplateSchema2.optional().describe("Document template"), - /** - * E-signature configuration - */ - eSignature: ESignatureConfigSchema2.optional().describe("E-signature config"), - /** - * Access control settings - */ - access: external_exports.object({ - /** - * Whether document is publicly accessible - * @default false - */ - isPublic: external_exports.boolean().optional().default(false).describe("Public access"), - /** - * List of user/team IDs with access - */ - sharedWith: external_exports.array(external_exports.string()).optional().describe("Shared with"), - /** - * Timestamp when access expires (Unix milliseconds) - */ - expiresAt: external_exports.number().optional().describe("Access expiration") - }).optional().describe("Access control"), - /** - * Custom metadata fields - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") -}); -var ExternalDataSourceSchema2 = external_exports.object({ - /** - * Unique identifier for the external data source - */ - id: external_exports.string().describe("Data source ID"), - /** - * Human-readable name of the data source - */ - name: external_exports.string().describe("Data source name"), - /** - * Protocol type for connecting to the data source - */ - type: external_exports.enum(["odata", "rest-api", "graphql", "custom"]).describe("Protocol type"), - /** - * Base URL endpoint for the external system - */ - endpoint: external_exports.string().url().describe("API endpoint URL"), - /** - * Authentication configuration - */ - authentication: external_exports.object({ - /** - * Authentication method - */ - type: external_exports.enum(["oauth2", "api-key", "basic", "none"]).describe("Auth type"), - /** - * Authentication-specific configuration - * Structure varies based on auth type - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Auth configuration") - }).describe("Authentication") -}); -var ExternalFieldMappingSchema2 = FieldMappingSchema4.extend({ - /** - * Field data type - */ - type: external_exports.string().optional().describe("Field type"), - /** - * Whether the field is read-only - * @default true - */ - readonly: external_exports.boolean().optional().default(true).describe("Read-only field") -}); -var ExternalLookupSchema2 = external_exports.object({ - /** - * Name of the field that uses external lookup - */ - fieldName: external_exports.string().describe("Field name"), - /** - * External data source configuration - */ - dataSource: ExternalDataSourceSchema2.describe("External data source"), - /** - * Query configuration for fetching external data - */ - query: external_exports.object({ - /** - * API endpoint path (relative to base endpoint) - */ - endpoint: external_exports.string().describe("Query endpoint path"), - /** - * HTTP method for the query - * @default 'GET' - */ - method: external_exports.enum(["GET", "POST"]).optional().default("GET").describe("HTTP method"), - /** - * Query parameters or request body - */ - parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Query parameters") - }).describe("Query configuration"), - /** - * Mapping between external and local fields - */ - fieldMappings: external_exports.array(ExternalFieldMappingSchema2).describe("Field mappings"), - /** - * Cache configuration for external data - */ - caching: external_exports.object({ - /** - * Whether caching is enabled - * @default true - */ - enabled: external_exports.boolean().optional().default(true).describe("Cache enabled"), - /** - * Time-to-live in seconds - * @default 300 - */ - ttl: external_exports.number().optional().default(300).describe("Cache TTL (seconds)"), - /** - * Cache eviction strategy - * @default 'ttl' - */ - strategy: external_exports.enum(["lru", "lfu", "ttl"]).optional().default("ttl").describe("Cache strategy") - }).optional().describe("Caching configuration"), - /** - * Fallback behavior when external system is unavailable - */ - fallback: external_exports.object({ - /** - * Whether fallback is enabled - * @default true - */ - enabled: external_exports.boolean().optional().default(true).describe("Fallback enabled"), - /** - * Default value to use when external system fails - */ - defaultValue: external_exports.unknown().optional().describe("Default fallback value"), - /** - * Whether to show error message to user - * @default true - */ - showError: external_exports.boolean().optional().default(true).describe("Show error to user") - }).optional().describe("Fallback configuration"), - /** - * Rate limiting to prevent overwhelming external system - */ - rateLimit: external_exports.object({ - /** - * Maximum requests per second - */ - requestsPerSecond: external_exports.number().describe("Requests per second limit"), - /** - * Burst size for handling spikes - */ - burstSize: external_exports.number().optional().describe("Burst size") - }).optional().describe("Rate limiting"), - /** - * Retry configuration with exponential backoff - * - * @example - * ```json - * { - * "maxRetries": 3, - * "initialDelayMs": 1000, - * "maxDelayMs": 30000, - * "backoffMultiplier": 2, - * "retryableStatusCodes": [429, 500, 502, 503, 504] - * } - * ``` - */ - retry: external_exports.object({ - /** Maximum number of retry attempts */ - maxRetries: external_exports.number().min(0).default(3).describe("Maximum retry attempts"), - /** Initial delay before first retry (ms) */ - initialDelayMs: external_exports.number().default(1e3).describe("Initial retry delay in milliseconds"), - /** Maximum delay between retries (ms) */ - maxDelayMs: external_exports.number().default(3e4).describe("Maximum retry delay in milliseconds"), - /** Backoff multiplier for exponential backoff */ - backoffMultiplier: external_exports.number().default(2).describe("Exponential backoff multiplier"), - /** HTTP status codes that trigger a retry */ - retryableStatusCodes: external_exports.array(external_exports.number()).default([429, 500, 502, 503, 504]).describe("HTTP status codes that are retryable") - }).optional().describe("Retry configuration with exponential backoff"), - /** - * Request/response transformation pipeline - * - * Allows transforming request parameters and response data - * before they are processed by the external lookup system. - */ - transform: external_exports.object({ - /** Transform request parameters before sending */ - request: external_exports.object({ - /** Header transformations (key-value additions) */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Additional request headers"), - /** Query parameter transformations */ - queryParams: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Additional query parameters") - }).optional().describe("Request transformation"), - /** Transform response data after receiving */ - response: external_exports.object({ - /** JSONPath expression to extract data from response */ - dataPath: external_exports.string().optional().describe('JSONPath to extract data (e.g., "$.data.results")'), - /** JSONPath expression to extract total count for pagination */ - totalPath: external_exports.string().optional().describe('JSONPath to extract total count (e.g., "$.meta.total")') - }).optional().describe("Response transformation") - }).optional().describe("Request/response transformation pipeline"), - /** Pagination support for external data sources */ - pagination: external_exports.object({ - /** Pagination type */ - type: external_exports.enum(["offset", "cursor", "page"]).default("offset").describe("Pagination type"), - /** Page size */ - pageSize: external_exports.number().default(100).describe("Items per page"), - /** Maximum pages to fetch */ - maxPages: external_exports.number().optional().describe("Maximum number of pages to fetch") - }).optional().describe("Pagination configuration for external data") -}); -var DriverType2 = external_exports.string().describe("Underlying driver identifier"); -var DriverDefinitionSchema2 = external_exports.object({ - id: external_exports.string().describe('Unique driver identifier (e.g. "postgres")'), - label: external_exports.string().describe('Display label (e.g. "PostgreSQL")'), - description: external_exports.string().optional(), - icon: external_exports.string().optional(), - /** - * Configuration Schema (JSON Schema) - * Describes the structure of the `config` object needed for this driver. - * Used by the UI to generate the connection form. - */ - configSchema: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema for connection configuration"), - /** - * Default Capabilities - * What this driver supports out-of-the-box. - */ - capabilities: external_exports.lazy(() => DatasourceCapabilities2).optional() -}); -var DatasourceCapabilities2 = external_exports.object({ - // ============================================================================ - // Transaction & Connection Management - // ============================================================================ - /** Can handle ACID transactions? */ - transactions: external_exports.boolean().default(false), - // ============================================================================ - // Query Operations - // ============================================================================ - /** Can execute WHERE clause filters natively? */ - queryFilters: external_exports.boolean().default(false), - /** Can perform aggregation (group by, sum, avg)? */ - queryAggregations: external_exports.boolean().default(false), - /** Can perform ORDER BY sorting? */ - querySorting: external_exports.boolean().default(false), - /** Can perform LIMIT/OFFSET pagination? */ - queryPagination: external_exports.boolean().default(false), - /** Can perform window functions? */ - queryWindowFunctions: external_exports.boolean().default(false), - /** Can perform subqueries? */ - querySubqueries: external_exports.boolean().default(false), - /** Can execute SQL-like joins natively? */ - joins: external_exports.boolean().default(false), - // ============================================================================ - // Advanced Features - // ============================================================================ - /** Can perform full-text search? */ - fullTextSearch: external_exports.boolean().default(false), - /** Is read-only? */ - readOnly: external_exports.boolean().default(false), - /** Is scheme-less (needs schema inference)? */ - dynamicSchema: external_exports.boolean().default(false) -}); -var DatasourceSchema2 = external_exports.object({ - /** Machine Name */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique datasource identifier"), - /** Human Label */ - label: external_exports.string().optional().describe("Display label"), - /** Driver */ - driver: DriverType2.describe("Underlying driver type"), - /** - * Connection Configuration - * Specific to the driver (e.g., host, port, user, password, bucket, etc.) - * Stored securely (passwords usually interpolated from ENV). - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Driver specific configuration"), - /** - * Connection Pool Configuration - * Standard connection pooling settings. - */ - pool: external_exports.object({ - min: external_exports.number().default(0).describe("Minimum connections"), - max: external_exports.number().default(10).describe("Maximum connections"), - idleTimeoutMillis: external_exports.number().default(3e4).describe("Idle timeout"), - connectionTimeoutMillis: external_exports.number().default(3e3).describe("Connection establishment timeout") - }).optional().describe("Connection pool settings"), - /** - * Read Replicas - * Optional list of duplicate configurations for read-only operations. - * Useful for scaling read throughput. - */ - readReplicas: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Read-only replica configurations"), - /** - * Capability Overrides - * Manually override what the driver claims to support. - */ - capabilities: DatasourceCapabilities2.optional().describe("Capability overrides"), - /** Health Check */ - healthCheck: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable health check endpoint"), - intervalMs: external_exports.number().default(3e4).describe("Health check interval in milliseconds"), - timeoutMs: external_exports.number().default(5e3).describe("Health check timeout in milliseconds") - }).optional().describe("Datasource health check configuration"), - /** SSL/TLS Configuration */ - ssl: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable SSL/TLS for database connection"), - rejectUnauthorized: external_exports.boolean().default(true).describe("Reject connections with invalid/self-signed certificates"), - ca: external_exports.string().optional().describe("CA certificate (PEM format or path to file)"), - cert: external_exports.string().optional().describe("Client certificate (PEM format or path to file)"), - key: external_exports.string().optional().describe("Client private key (PEM format or path to file)") - }).optional().describe("SSL/TLS configuration for secure database connections"), - /** Retry Policy */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().default(3).describe("Maximum number of retry attempts"), - baseDelayMs: external_exports.number().default(1e3).describe("Base delay between retries in milliseconds"), - maxDelayMs: external_exports.number().default(3e4).describe("Maximum delay between retries in milliseconds"), - backoffMultiplier: external_exports.number().default(2).describe("Exponential backoff multiplier") - }).optional().describe("Connection retry policy for transient failures"), - /** Description */ - description: external_exports.string().optional().describe("Internal description"), - /** Is enabled? */ - active: external_exports.boolean().default(true).describe("Is datasource enabled") -}); -var AggregationMetricType3 = external_exports.enum([ - "count", - "sum", - "avg", - "min", - "max", - "count_distinct", - "number", - // Custom SQL expression returning a number - "string", - // Custom SQL expression returning a string - "boolean" - // Custom SQL expression returning a boolean -]); -var DimensionType3 = external_exports.enum([ - "string", - "number", - "boolean", - "time", - "geo" -]); -var TimeUpdateInterval3 = external_exports.enum([ - "second", - "minute", - "hour", - "day", - "week", - "month", - "quarter", - "year" -]); -var MetricSchema3 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique metric ID"), - label: external_exports.string().describe("Human readable label"), - description: external_exports.string().optional(), - type: AggregationMetricType3, - /** Source Calculation */ - sql: external_exports.string().describe("SQL expression or field reference"), - /** Filtering for this specific metric (e.g. "Revenue from Premium Users") */ - filters: external_exports.array(external_exports.object({ - sql: external_exports.string() - })).optional(), - /** Format for display (e.g. "currency", "percent") */ - format: external_exports.string().optional() -}); -var DimensionSchema3 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique dimension ID"), - label: external_exports.string().describe("Human readable label"), - description: external_exports.string().optional(), - type: DimensionType3, - /** Source Column */ - sql: external_exports.string().describe("SQL expression or column reference"), - /** For Time Dimensions: Supported Granularities */ - granularities: external_exports.array(TimeUpdateInterval3).optional() -}); -var CubeJoinSchema3 = external_exports.object({ - name: external_exports.string().describe("Target cube name"), - relationship: external_exports.enum(["one_to_one", "one_to_many", "many_to_one"]).default("many_to_one"), - sql: external_exports.string().describe("Join condition (ON clause)") -}); -var CubeSchema3 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Cube name (snake_case)"), - title: external_exports.string().optional(), - description: external_exports.string().optional(), - /** Physical Data Source */ - sql: external_exports.string().describe("Base SQL statement or Table Name"), - /** Semantic Definitions */ - measures: external_exports.record(external_exports.string(), MetricSchema3).describe("Quantitative metrics"), - dimensions: external_exports.record(external_exports.string(), DimensionSchema3).describe("Qualitative attributes"), - /** Relationships */ - joins: external_exports.record(external_exports.string(), CubeJoinSchema3).optional(), - /** Pre-aggregations / Caching */ - refreshKey: external_exports.object({ - every: external_exports.string().optional(), - // e.g. "1 hour" - sql: external_exports.string().optional() - // SQL to check for data changes - }).optional(), - /** Access Control */ - public: external_exports.boolean().default(false) -}); -var AnalyticsQuerySchema3 = external_exports.object({ - cube: external_exports.string().optional().describe("Target cube name (optional when provided externally, e.g. in API request wrapper)"), - measures: external_exports.array(external_exports.string()).describe("List of metrics to calculate"), - dimensions: external_exports.array(external_exports.string()).optional().describe("List of dimensions to group by"), - filters: external_exports.array(external_exports.object({ - member: external_exports.string().describe("Dimension or Measure"), - operator: external_exports.enum(["equals", "notEquals", "contains", "notContains", "gt", "gte", "lt", "lte", "set", "notSet", "inDateRange"]), - values: external_exports.array(external_exports.string()).optional() - })).optional(), - timeDimensions: external_exports.array(external_exports.object({ - dimension: external_exports.string(), - granularity: TimeUpdateInterval3.optional(), - dateRange: external_exports.union([ - external_exports.string(), - // "Last 7 days" - external_exports.array(external_exports.string()) - // ["2023-01-01", "2023-01-31"] - ]).optional() - })).optional(), - order: external_exports.record(external_exports.string(), external_exports.enum(["asc", "desc"])).optional(), - limit: external_exports.number().optional(), - offset: external_exports.number().optional(), - timezone: external_exports.string().optional().default("UTC") -}); -var FeedItemType4 = external_exports.enum([ - "comment", - "field_change", - "task", - "event", - "email", - "call", - "note", - "file", - "record_create", - "record_delete", - "approval", - "sharing", - "system" -]); -var MentionSchema4 = external_exports.object({ - type: external_exports.enum(["user", "team", "record"]).describe("Mention target type"), - id: external_exports.string().describe("Target ID"), - name: external_exports.string().describe("Display name for rendering"), - offset: external_exports.number().int().min(0).describe("Character offset in body text"), - length: external_exports.number().int().min(1).describe("Length of mention token in body text") -}); -var FieldChangeEntrySchema4 = external_exports.object({ - field: external_exports.string().describe("Field machine name"), - fieldLabel: external_exports.string().optional().describe("Field display label"), - oldValue: external_exports.unknown().optional().describe("Previous value"), - newValue: external_exports.unknown().optional().describe("New value"), - oldDisplayValue: external_exports.string().optional().describe("Human-readable old value"), - newDisplayValue: external_exports.string().optional().describe("Human-readable new value") -}); -var ReactionSchema4 = external_exports.object({ - emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")'), - userIds: external_exports.array(external_exports.string()).describe("Users who reacted"), - count: external_exports.number().int().min(1).describe("Total reaction count") -}); -var FeedActorSchema4 = external_exports.object({ - type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), - id: external_exports.string().describe("Actor ID"), - name: external_exports.string().optional().describe("Actor display name"), - avatarUrl: external_exports.string().url().optional().describe("Actor avatar URL"), - source: external_exports.string().optional().describe('Source application (e.g., "Omni", "API", "Studio")') -}); -var FeedVisibility4 = external_exports.enum(["public", "internal", "private"]); -var FeedItemSchema3 = external_exports.object({ - /** Unique identifier */ - id: external_exports.string().describe("Feed item ID"), - /** Feed item type */ - type: FeedItemType4.describe("Activity type"), - /** Target record reference */ - object: external_exports.string().describe('Object name (e.g., "account")'), - recordId: external_exports.string().describe("Record ID this feed item belongs to"), - /** Actor (who performed the action) */ - actor: FeedActorSchema4.describe("Who performed this action"), - /** Content (for comments/notes) */ - body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), - /** @Mentions */ - mentions: external_exports.array(MentionSchema4).optional().describe("Mentioned users/teams/records"), - /** Field changes (for field_change type) */ - changes: external_exports.array(FieldChangeEntrySchema4).optional().describe("Field-level changes"), - /** Reactions */ - reactions: external_exports.array(ReactionSchema4).optional().describe("Emoji reactions on this item"), - /** Reply threading */ - parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), - replyCount: external_exports.number().int().min(0).default(0).describe("Number of replies"), - /** Pin / Star */ - pinned: external_exports.boolean().default(false).describe("Whether the feed item is pinned to the top of the timeline"), - pinnedAt: external_exports.string().datetime().optional().describe("Timestamp when the item was pinned"), - pinnedBy: external_exports.string().optional().describe("User ID who pinned the item"), - starred: external_exports.boolean().default(false).describe("Whether the feed item is starred/bookmarked by the current user"), - starredAt: external_exports.string().datetime().optional().describe("Timestamp when the item was starred"), - /** Visibility */ - visibility: FeedVisibility4.default("public").describe("Visibility: public (all users), internal (team only), private (author + mentioned)"), - /** Timestamps */ - createdAt: external_exports.string().datetime().describe("Creation timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - editedAt: external_exports.string().datetime().optional().describe("When comment was last edited"), - isEdited: external_exports.boolean().default(false).describe("Whether comment has been edited") -}); -var FeedFilterMode3 = external_exports.enum([ - "all", - "comments_only", - "changes_only", - "tasks_only" -]); -var SubscriptionEventType3 = external_exports.enum([ - "comment", - "mention", - "field_change", - "task", - "approval", - "all" -]); -var NotificationChannel3 = external_exports.enum([ - "in_app", - "email", - "push", - "slack" -]); -var RecordSubscriptionSchema3 = external_exports.object({ - /** Target */ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - /** Subscriber */ - userId: external_exports.string().describe("Subscribing user ID"), - /** Events to subscribe to */ - events: external_exports.array(SubscriptionEventType3).default(["all"]).describe("Event types to receive notifications for"), - /** Notification channels */ - channels: external_exports.array(NotificationChannel3).default(["in_app"]).describe("Notification delivery channels"), - /** Active */ - active: external_exports.boolean().default(true).describe("Whether the subscription is active"), - /** Timestamps */ - createdAt: external_exports.string().datetime().describe("Subscription creation timestamp") -}); -var TenantResolverStrategySchema2 = external_exports.enum([ - "header", - // Resolve from X-Tenant-ID request header - "subdomain", - // Resolve from subdomain (e.g., acme.app.com → acme) - "path", - // Resolve from URL path segment (e.g., /api/acme/...) - "token", - // Resolve from JWT claim (e.g., tenant_id in access token) - "lookup" - // Resolve from control-plane database lookup -]).describe("Strategy for resolving tenant identity from request context"); -var TursoGroupSchema2 = external_exports.object({ - /** - * Group name identifier. - * Used to reference the group when creating new tenant databases. - */ - name: external_exports.string().min(1).describe("Turso database group name"), - /** - * Primary location for the group (Turso region code). - * Example: 'iad' (US East), 'lhr' (London), 'nrt' (Tokyo) - */ - primaryLocation: external_exports.string().min(2).describe("Primary Turso region code (e.g., iad, lhr, nrt)"), - /** - * Additional replica locations for read performance. - * Databases in this group will have read replicas in these regions. - */ - replicaLocations: external_exports.array(external_exports.string().min(2)).default([]).describe("Additional replica region codes"), - /** - * Schema database name within the group. - * When using multi-db schemas, this is the "parent" database - * whose schema is shared by all child (tenant) databases. - */ - schemaDatabase: external_exports.string().optional().describe("Schema database name for multi-db schemas") -}).describe("Turso database group configuration"); -var TenantDatabaseLifecycleSchema2 = external_exports.object({ - /** - * Hook executed when a new tenant is created. - * Defines how the tenant database is provisioned. - */ - onTenantCreate: external_exports.object({ - /** Whether to automatically create a Turso database */ - autoCreate: external_exports.boolean().default(true).describe("Auto-create database on tenant registration"), - /** Database group to create the database in */ - group: external_exports.string().optional().describe("Turso group for the new database"), - /** Whether to apply schema from the group schema database */ - applyGroupSchema: external_exports.boolean().default(true).describe("Apply shared schema from group"), - /** Seed data to populate on creation */ - seedData: external_exports.boolean().default(false).describe("Populate seed data on creation") - }).describe("Tenant creation hook"), - /** - * Hook executed when a tenant is deleted/destroyed. - */ - onTenantDelete: external_exports.object({ - /** Whether to destroy the database immediately or schedule for deletion */ - immediate: external_exports.boolean().default(false).describe("Destroy database immediately"), - /** Grace period in hours before permanent deletion (soft-delete) */ - gracePeriodHours: external_exports.number().int().min(0).default(72).describe("Grace period before permanent deletion"), - /** Whether to create a final backup before deletion */ - createBackup: external_exports.boolean().default(true).describe("Create backup before deletion") - }).describe("Tenant deletion hook"), - /** - * Hook executed when a tenant is suspended (e.g., unpaid, policy violation). - */ - onTenantSuspend: external_exports.object({ - /** Whether to revoke auth tokens on suspension */ - revokeTokens: external_exports.boolean().default(true).describe("Revoke auth tokens on suspension"), - /** Whether to set database to read-only mode */ - readOnly: external_exports.boolean().default(true).describe("Set database to read-only on suspension") - }).describe("Tenant suspension hook") -}).describe("Tenant database lifecycle hooks"); -var TursoMultiTenantConfigSchema2 = external_exports.object({ - /** - * Turso organization slug. - * Used for Platform API calls and URL construction. - */ - organizationSlug: external_exports.string().min(1).describe("Turso organization slug"), - /** - * URL template for constructing tenant database URLs. - * Use `{tenant_id}` as placeholder for the tenant identifier. - * - * Example: 'libsql://{tenant_id}-myorg.turso.io' - */ - urlTemplate: external_exports.string().min(1).describe("URL template with {tenant_id} placeholder"), - /** - * Group-level auth token for Turso Platform API operations. - * Used for database creation, deletion, and management. - * This token has full access to all databases in the group. - */ - groupAuthToken: external_exports.string().min(1).describe("Group-level auth token for platform operations"), - /** - * Strategy for resolving tenant identity from the request context. - */ - tenantResolverStrategy: TenantResolverStrategySchema2.default("token"), - /** - * Turso database group configuration. - */ - group: TursoGroupSchema2.optional().describe("Database group configuration"), - /** - * Lifecycle hooks for tenant database management. - */ - lifecycle: TenantDatabaseLifecycleSchema2.optional().describe("Lifecycle hooks"), - /** - * Maximum number of cached tenant database connections. - * Connections are evicted using LRU strategy when the limit is reached. - */ - maxCachedConnections: external_exports.number().int().min(1).default(100).describe("Max cached tenant connections (LRU)"), - /** - * Connection cache TTL in seconds. - * Cached connections are refreshed after this period. - */ - connectionCacheTTL: external_exports.number().int().min(0).default(300).describe("Connection cache TTL in seconds") -}).describe("Turso multi-tenant router configuration"); -var security_exports = {}; -__export4(security_exports, { - AuditPolicySchema: () => AuditPolicySchema, - CriteriaSharingRuleSchema: () => CriteriaSharingRuleSchema, - FieldPermissionSchema: () => FieldPermissionSchema2, - NetworkPolicySchema: () => NetworkPolicySchema, - OWDModel: () => OWDModel, - ObjectPermissionSchema: () => ObjectPermissionSchema2, - OwnerSharingRuleSchema: () => OwnerSharingRuleSchema, - PasswordPolicySchema: () => PasswordPolicySchema, - PermissionSetSchema: () => PermissionSetSchema2, - PolicySchema: () => PolicySchema, - RLS: () => RLS, - RLSAuditConfigSchema: () => RLSAuditConfigSchema2, - RLSAuditEventSchema: () => RLSAuditEventSchema, - RLSConfigSchema: () => RLSConfigSchema, - RLSEvaluationResultSchema: () => RLSEvaluationResultSchema, - RLSOperation: () => RLSOperation2, - RLSUserContextSchema: () => RLSUserContextSchema, - RowLevelSecurityPolicySchema: () => RowLevelSecurityPolicySchema2, - SessionPolicySchema: () => SessionPolicySchema, - ShareRecipientType: () => ShareRecipientType, - SharingLevel: () => SharingLevel, - SharingRuleSchema: () => SharingRuleSchema, - SharingRuleType: () => SharingRuleType, - TerritoryModelSchema: () => TerritoryModelSchema, - TerritorySchema: () => TerritorySchema, - TerritoryType: () => TerritoryType -}); -var RLSOperation2 = external_exports.enum(["select", "insert", "update", "delete", "all"]); -var RowLevelSecurityPolicySchema2 = external_exports.object({ - /** - * Unique identifier for this policy. - * Must be unique within the object. - * Use snake_case following ObjectStack naming conventions. - * - * @example "tenant_isolation", "owner_access", "manager_team_view" - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Policy unique identifier (snake_case)"), - /** - * Human-readable label for the policy. - * Used in admin UI and logs. - * - * @example "Multi-Tenant Data Isolation", "Owner-Based Access" - */ - label: external_exports.string().optional().describe("Human-readable policy label"), - /** - * Description explaining what this policy does and why. - * Helps with governance and compliance. - * - * @example "Ensures users can only access records from their own tenant organization" - */ - description: external_exports.string().optional().describe("Policy description and business justification"), - /** - * Target object (table) this policy applies to. - * Must reference a valid ObjectStack object name. - * - * @example "account", "opportunity", "contact", "custom_object" - */ - object: external_exports.string().describe("Target object name"), - /** - * Database operation(s) this policy applies to. - * - * - **select**: Controls read access (SELECT queries) - * - **insert**: Controls insert access (INSERT statements) - * - **update**: Controls update access (UPDATE statements) - * - **delete**: Controls delete access (DELETE statements) - * - **all**: Applies to all operations - * - * @example "select" - Most common, controls what users can view - * @example "all" - Apply same rule to all operations - */ - operation: RLSOperation2.describe("Database operation this policy applies to"), - /** - * USING clause - Filter condition for SELECT/UPDATE/DELETE. - * - * This is a SQL-like expression evaluated for each row. - * Only rows where this expression returns TRUE are accessible. - * - * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed). - * For SELECT/UPDATE/DELETE operations, USING is required. - * - * **Security Note**: RLS conditions are executed at the database level with - * parameterized queries. The implementation must use prepared statements - * to prevent SQL injection. Never concatenate user input directly into - * RLS conditions. - * - * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations - * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain - * semantic equivalence. - * - * Available context variables: - * - `current_user.id` - Current user's ID - * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext) - * - `current_user.role` - Current user's role - * - `current_user.department` - Current user's department - * - `current_user.*` - Any custom user field - * - `NOW()` - Current timestamp - * - `CURRENT_DATE` - Current date - * - `CURRENT_TIME` - Current time - * - * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`), - * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`). - * Implementations must handle this mapping. - * - * Supported operators: - * - Comparison: =, !=, <, >, <=, >=, <> (not equal) - * - Logical: AND, OR, NOT - * - NULL checks: IS NULL, IS NOT NULL - * - Set operations: IN, NOT IN - * - String: LIKE, NOT LIKE, ILIKE (case-insensitive) - * - Pattern matching: ~ (regex), !~ (not regex) - * - Subqueries: (SELECT ...) - * - Array operations: ANY, ALL - * - * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE) - * - * @example "tenant_id = current_user.tenant_id" - * @example "owner_id = current_user.id OR created_by = current_user.id" - * @example "department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)" - * @example "status = 'active' AND expiry_date > NOW()" - */ - using: external_exports.string().optional().describe("Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies."), - /** - * CHECK clause - Validation for INSERT/UPDATE operations. - * - * Similar to USING but applies to new/modified rows. - * Prevents users from creating/updating rows they wouldn't be able to see. - * - * **Default Behavior**: If not specified, implementations should use the - * USING clause as the CHECK clause. This ensures data integrity by preventing - * users from creating records they cannot view. - * - * Use cases: - * - Prevent cross-tenant data creation - * - Enforce mandatory field values - * - Validate data integrity rules - * - Restrict certain operations (e.g., only allow creating "draft" status) - * - * @example "tenant_id = current_user.tenant_id" - * @example "status IN ('draft', 'pending')" - Only allow certain statuses - * @example "created_by = current_user.id" - Must be the creator - */ - check: external_exports.string().optional().describe("Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)"), - /** - * Restrict this policy to specific roles. - * If specified, only users with these roles will have this policy applied. - * If omitted, policy applies to all users (except those with bypassRLS permission). - * - * Role names must match defined roles in the system. - * - * @example ["sales_rep", "account_manager"] - * @example ["employee"] - Apply to all employees - * @example ["guest"] - Special restrictions for guests - */ - roles: external_exports.array(external_exports.string()).optional().describe("Roles this policy applies to (omit for all roles)"), - /** - * Whether this policy is currently active. - * Disabled policies are not evaluated. - * Useful for temporary policy changes without deletion. - * - * @default true - */ - enabled: external_exports.boolean().default(true).describe("Whether this policy is active"), - /** - * Policy priority for conflict resolution. - * Higher numbers = higher priority. - * When multiple policies apply, the most permissive wins (OR logic). - * Priority is only used for ordering evaluation (performance). - * - * @default 0 - */ - priority: external_exports.number().int().default(0).describe("Policy evaluation priority (higher = evaluated first)"), - /** - * Tags for policy categorization and reporting. - * Useful for governance, compliance, and auditing. - * - * @example ["compliance", "gdpr", "pci"] - * @example ["multi-tenant", "security"] - */ - tags: external_exports.array(external_exports.string()).optional().describe("Policy categorization tags") -}).superRefine((data, ctx) => { - if (!data.using && !data.check) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: 'At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".' - }); - } -}); -var RLSAuditEventSchema = external_exports.object({ - /** ISO 8601 timestamp of the evaluation */ - timestamp: external_exports.string().describe("ISO 8601 timestamp of the evaluation"), - /** ID of the user whose access was evaluated */ - userId: external_exports.string().describe("User ID whose access was evaluated"), - /** Database operation being performed */ - operation: external_exports.enum(["select", "insert", "update", "delete"]).describe("Database operation being performed"), - /** Target object (table) name */ - object: external_exports.string().describe("Target object name"), - /** Name of the RLS policy evaluated */ - policyName: external_exports.string().describe("Name of the RLS policy evaluated"), - /** Whether access was granted */ - granted: external_exports.boolean().describe("Whether access was granted"), - /** Time taken to evaluate the policy in milliseconds */ - evaluationDurationMs: external_exports.number().describe("Policy evaluation duration in milliseconds"), - /** Which USING/CHECK clause matched */ - matchedCondition: external_exports.string().optional().describe("Which USING/CHECK clause matched"), - /** Number of rows affected by the operation */ - rowCount: external_exports.number().optional().describe("Number of rows affected"), - /** Additional metadata for the audit event */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional audit event metadata") -}); -var RLSAuditConfigSchema2 = external_exports.object({ - /** Enable RLS audit logging */ - enabled: external_exports.boolean().describe("Enable RLS audit logging"), - /** Which evaluations to log */ - logLevel: external_exports.enum(["all", "denied_only", "granted_only", "none"]).describe("Which evaluations to log"), - /** Where to send audit logs */ - destination: external_exports.enum(["system_log", "audit_trail", "external"]).describe("Audit log destination"), - /** Sampling rate for high-traffic environments (0-1) */ - sampleRate: external_exports.number().min(0).max(1).describe("Sampling rate (0-1) for high-traffic environments"), - /** Number of days to retain audit logs */ - retentionDays: external_exports.number().int().default(90).describe("Audit log retention period in days"), - /** Whether to include row data in audit logs (security-sensitive) */ - includeRowData: external_exports.boolean().default(false).describe("Include row data in audit logs (security-sensitive)"), - /** Alert when access is denied */ - alertOnDenied: external_exports.boolean().default(true).describe("Send alerts when access is denied") -}); -var RLSConfigSchema = external_exports.object({ - /** - * Global RLS enable/disable flag. - * When false, all RLS policies are ignored (use with caution!). - * - * @default true - */ - enabled: external_exports.boolean().default(true).describe("Enable RLS enforcement globally"), - /** - * Default behavior when no policies match. - * - * - **deny**: Deny access (secure default) - * - **allow**: Allow access (permissive mode, not recommended) - * - * @default "deny" - */ - defaultPolicy: external_exports.enum(["deny", "allow"]).default("deny").describe("Default action when no policies match"), - /** - * Whether to allow superusers to bypass RLS. - * Superusers include system administrators and service accounts. - * - * @default true - */ - allowSuperuserBypass: external_exports.boolean().default(true).describe("Allow superusers to bypass RLS"), - /** - * List of roles that can bypass RLS. - * Users with these roles see all records regardless of policies. - * - * @example ["system_admin", "data_auditor"] - */ - bypassRoles: external_exports.array(external_exports.string()).optional().describe("Roles that bypass RLS (see all data)"), - /** - * Whether to log RLS policy evaluations. - * Useful for debugging and auditing. - * Can impact performance if enabled globally. - * - * @default false - */ - logEvaluations: external_exports.boolean().default(false).describe("Log RLS policy evaluations for debugging"), - /** - * Cache RLS policy evaluation results. - * Can improve performance for frequently accessed records. - * Cache is invalidated when policies change or user context changes. - * - * @default true - */ - cacheResults: external_exports.boolean().default(true).describe("Cache RLS evaluation results"), - /** - * Cache TTL in seconds. - * How long to cache RLS evaluation results. - * - * @default 300 (5 minutes) - */ - cacheTtlSeconds: external_exports.number().int().positive().default(300).describe("Cache TTL in seconds"), - /** - * Performance optimization: Pre-fetch user context. - * Load user context once per request instead of per-query. - * - * @default true - */ - prefetchUserContext: external_exports.boolean().default(true).describe("Pre-fetch user context for performance"), - /** - * Audit logging configuration for RLS evaluations. - */ - audit: RLSAuditConfigSchema2.optional().describe("RLS audit logging configuration") -}); -var RLSUserContextSchema = external_exports.object({ - /** - * User ID - */ - id: external_exports.string().describe("User ID"), - /** - * User email - */ - email: external_exports.string().email().optional().describe("User email"), - /** - * Tenant/Organization ID - */ - tenantId: external_exports.string().optional().describe("Tenant/Organization ID"), - /** - * User role(s) - */ - role: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.string()) - ]).optional().describe("User role(s)"), - /** - * User department - */ - department: external_exports.string().optional().describe("User department"), - /** - * Additional custom attributes - * Can include any custom user fields for RLS evaluation - */ - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom user attributes") -}); -var RLSEvaluationResultSchema = external_exports.object({ - /** - * Policy name that was evaluated - */ - policyName: external_exports.string().describe("Policy name"), - /** - * Whether access was granted - */ - granted: external_exports.boolean().describe("Whether access was granted"), - /** - * Evaluation duration in milliseconds - */ - durationMs: external_exports.number().optional().describe("Evaluation duration in milliseconds"), - /** - * Error message if evaluation failed - */ - error: external_exports.string().optional().describe("Error message if evaluation failed"), - /** - * Evaluated USING clause result - */ - usingResult: external_exports.boolean().optional().describe("USING clause evaluation result"), - /** - * Evaluated CHECK clause result (for INSERT/UPDATE) - */ - checkResult: external_exports.boolean().optional().describe("CHECK clause evaluation result") -}); -var RLS = { - /** - * Create a simple owner-based policy - */ - ownerPolicy: (object2, ownerField = "owner_id") => ({ - name: `${object2}_owner_access`, - label: `Owner Access for ${object2}`, - object: object2, - operation: "all", - using: `${ownerField} = current_user.id`, - enabled: true, - priority: 0 - }), - /** - * Create a tenant isolation policy - */ - tenantPolicy: (object2, tenantField = "tenant_id") => ({ - name: `${object2}_tenant_isolation`, - label: `Tenant Isolation for ${object2}`, - object: object2, - operation: "all", - using: `${tenantField} = current_user.tenant_id`, - check: `${tenantField} = current_user.tenant_id`, - enabled: true, - priority: 0 - }), - /** - * Create a role-based policy - */ - rolePolicy: (object2, roles, condition) => ({ - name: `${object2}_${roles.join("_")}_access`, - label: `${roles.join(", ")} Access for ${object2}`, - object: object2, - operation: "select", - using: condition, - roles, - enabled: true, - priority: 0 - }), - /** - * Create a permissive policy (allow all for specific roles) - */ - allowAllPolicy: (object2, roles) => ({ - name: `${object2}_${roles.join("_")}_full_access`, - label: `Full Access for ${roles.join(", ")}`, - object: object2, - operation: "all", - using: "1 = 1", - // Always true - roles, - enabled: true, - priority: 0 - }) -}; -var ObjectPermissionSchema2 = external_exports.object({ - /** C: Create */ - allowCreate: external_exports.boolean().default(false).describe("Create permission"), - /** R: Read (Owned records or Shared records) */ - allowRead: external_exports.boolean().default(false).describe("Read permission"), - /** U: Edit (Owned records or Shared records) */ - allowEdit: external_exports.boolean().default(false).describe("Edit permission"), - /** D: Delete (Owned records or Shared records) */ - allowDelete: external_exports.boolean().default(false).describe("Delete permission"), - /** Lifecycle Operations */ - allowTransfer: external_exports.boolean().default(false).describe("Change record ownership"), - allowRestore: external_exports.boolean().default(false).describe("Restore from trash (Undelete)"), - allowPurge: external_exports.boolean().default(false).describe("Permanently delete (Hard Delete/GDPR)"), - /** - * View All Records: Super-user read access. - * Bypasses Sharing Rules and Ownership checks. - * Equivalent to Microsoft Dataverse "Organization" level read access. - */ - viewAllRecords: external_exports.boolean().default(false).describe("View All Data (Bypass Sharing)"), - /** - * Modify All Records: Super-user write access. - * Bypasses Sharing Rules and Ownership checks. - * Equivalent to Microsoft Dataverse "Organization" level write access. - */ - modifyAllRecords: external_exports.boolean().default(false).describe("Modify All Data (Bypass Sharing)") -}); -var FieldPermissionSchema2 = external_exports.object({ - /** Can see this field */ - readable: external_exports.boolean().default(true).describe("Field read access"), - /** Can edit this field */ - editable: external_exports.boolean().default(false).describe("Field edit access") -}); -var PermissionSetSchema2 = external_exports.object({ - /** Unique permission set name */ - name: SnakeCaseIdentifierSchema7.describe("Permission set unique name (lowercase snake_case)"), - /** Display label */ - label: external_exports.string().optional().describe("Display label"), - /** Is this a Profile? (Base set for a user) */ - isProfile: external_exports.boolean().default(false).describe("Whether this is a user profile"), - /** Object Permissions Map: -> permissions */ - objects: external_exports.record(external_exports.string(), ObjectPermissionSchema2).describe("Entity permissions"), - /** Field Permissions Map: . -> permissions */ - fields: external_exports.record(external_exports.string(), FieldPermissionSchema2).optional().describe("Field level security"), - /** System permissions (e.g., "manage_users") */ - systemPermissions: external_exports.array(external_exports.string()).optional().describe("System level capabilities"), - /** - * Tab/App Visibility Permissions (Salesforce Pattern) - * Controls which app tabs are visible, hidden, or set as default for this permission set. - * - * @example - * ```typescript - * tabPermissions: { - * 'app_crm': 'visible', - * 'app_admin': 'hidden', - * 'app_sales': 'default_on' - * } - * ``` - */ - tabPermissions: external_exports.record(external_exports.string(), external_exports.enum(["visible", "hidden", "default_on", "default_off"])).optional().describe("App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)"), - /** - * Row-Level Security Rules - * - * Row-level security policies that filter records based on user context. - * These rules are applied in addition to object-level permissions. - * - * Uses the canonical RLS protocol from rls.zod.ts for comprehensive - * row-level security features including PostgreSQL-style USING and CHECK clauses. - * - * @see {@link RowLevelSecurityPolicySchema} for full RLS specification - * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation - * - * @example Multi-tenant isolation - * ```typescript - * rls: [{ - * name: 'tenant_filter', - * object: 'account', - * operation: 'select', - * using: 'tenant_id = current_user.tenant_id' - * }] - * ``` - */ - rowLevelSecurity: external_exports.array(RowLevelSecurityPolicySchema2).optional().describe("Row-level security policies (see rls.zod.ts for full spec)"), - /** - * Context-Based Access Control Variables - * - * Custom context variables that can be referenced in RLS rules. - * These variables are evaluated at runtime based on the user's session. - * - * Common context variables: - * - `current_user.id` - Current user ID - * - `current_user.tenant_id` - User's tenant/organization ID - * - `current_user.department` - User's department - * - `current_user.role` - User's role - * - `current_user.region` - User's geographic region - * - * @example Custom context - * ```typescript - * contextVariables: { - * allowed_regions: ['US', 'EU'], - * access_level: 2, - * custom_attribute: 'value' - * } - * ``` - */ - contextVariables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Context variables for RLS evaluation") -}); -var OWDModel = external_exports.enum([ - "private", - // Only owner can see - "public_read", - // Everyone can see, owner can edit - "public_read_write", - // Everyone can see and edit - "controlled_by_parent" - // Access derived from parent record (Master-Detail) -]); -var SharingRuleType = external_exports.enum([ - "owner", - // Based on record ownership (Role Hierarchy) - "criteria" - // Based on field values (e.g. Status = 'Open') -]); -var SharingLevel = external_exports.enum([ - "read", - // Read Only - "edit", - // Read / Write - "full" - // Full Access (Transfer, Share, Delete) -]); -var ShareRecipientType = external_exports.enum([ - "user", - "group", - "role", - "role_and_subordinates", - "guest" - // for public sharing -]); -var BaseSharingRuleSchema = external_exports.object({ - // Identification - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label"), - description: external_exports.string().optional().describe("Administrative notes"), - // Scope - object: external_exports.string().describe("Target Object Name"), - active: external_exports.boolean().default(true), - // Access - accessLevel: SharingLevel.default("read"), - // Recipient (Whom to share with) - sharedWith: external_exports.object({ - type: ShareRecipientType, - value: external_exports.string().describe("ID or Code of the User/Group/Role") - }).describe("The recipient of the shared access") -}); -var CriteriaSharingRuleSchema = BaseSharingRuleSchema.extend({ - type: external_exports.literal("criteria"), - condition: external_exports.string().describe(`Formula condition (e.g. "department = 'Sales'")`) -}); -var OwnerSharingRuleSchema = BaseSharingRuleSchema.extend({ - type: external_exports.literal("owner"), - ownedBy: external_exports.object({ - type: ShareRecipientType, - value: external_exports.string() - }).describe("Source group/role whose records are being shared") -}); -var SharingRuleSchema = external_exports.discriminatedUnion("type", [ - CriteriaSharingRuleSchema, - OwnerSharingRuleSchema -]); -var TerritoryType = external_exports.enum([ - "geography", - // Region/Country/City - "industry", - // Vertical - "named_account", - // Key Accounts - "product_line" - // Product Specialty -]); -var TerritoryModelSchema = external_exports.object({ - name: external_exports.string().describe("Model Name (e.g. FY24 Planning)"), - state: external_exports.enum(["planning", "active", "archived"]).default("planning"), - startDate: external_exports.string().optional(), - endDate: external_exports.string().optional() -}); -var TerritorySchema = external_exports.object({ - /** Identity */ - name: SnakeCaseIdentifierSchema7.describe("Territory unique name (lowercase snake_case)"), - label: external_exports.string().describe('Territory Label (e.g. "West Coast")'), - /** Structure */ - modelId: external_exports.string().describe("Belongs to which Territory Model"), - parent: external_exports.string().optional().describe("Parent Territory"), - type: TerritoryType.default("geography"), - /** - * Assignment Rules (The "Magic") - * How do accounts automatically fall into this territory? - * e.g. "BillingCountry = 'US' AND BillingState = 'CA'" - */ - assignmentRule: external_exports.string().optional().describe("Criteria based assignment rule"), - /** - * User Assignment - * Users assigned to work this territory. - */ - assignedUsers: external_exports.array(external_exports.string()).optional(), - /** Access Level */ - accountAccess: external_exports.enum(["read", "edit"]).default("read"), - opportunityAccess: external_exports.enum(["read", "edit"]).default("read"), - caseAccess: external_exports.enum(["read", "edit"]).default("read") -}); -var PasswordPolicySchema = external_exports.object({ - minLength: external_exports.number().default(8), - requireUppercase: external_exports.boolean().default(true), - requireLowercase: external_exports.boolean().default(true), - requireNumbers: external_exports.boolean().default(true), - requireSymbols: external_exports.boolean().default(false), - expirationDays: external_exports.number().optional().describe("Force password change every X days"), - historyCount: external_exports.number().default(3).describe("Prevent reusing last X passwords") -}); -var NetworkPolicySchema = external_exports.object({ - trustedRanges: external_exports.array(external_exports.string()).describe("CIDR ranges allowed to access (e.g. 10.0.0.0/8)"), - blockUnknown: external_exports.boolean().default(false).describe("Block all IPs not in trusted ranges"), - vpnRequired: external_exports.boolean().default(false) -}); -var SessionPolicySchema = external_exports.object({ - idleTimeout: external_exports.number().default(30).describe("Minutes before idle session logout"), - absoluteTimeout: external_exports.number().default(480).describe("Max session duration (minutes)"), - forceMfa: external_exports.boolean().default(false).describe("Require 2FA for all users") -}); -var AuditPolicySchema = external_exports.object({ - logRetentionDays: external_exports.number().default(180), - sensitiveFields: external_exports.array(external_exports.string()).describe("Fields to redact in logs (e.g. password, ssn)"), - captureRead: external_exports.boolean().default(false).describe("Log read access (High volume!)") -}); -var PolicySchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Policy Name"), - password: PasswordPolicySchema.optional(), - network: NetworkPolicySchema.optional(), - session: SessionPolicySchema.optional(), - audit: AuditPolicySchema.optional(), - /** Assignment */ - isDefault: external_exports.boolean().default(false).describe("Apply to all users by default"), - assignedProfiles: external_exports.array(external_exports.string()).optional().describe("Apply to specific profiles") -}); -var ui_exports = {}; -__export4(ui_exports, { - AIChatWindowProps: () => AIChatWindowProps2, - Action: () => Action, - ActionNavItemSchema: () => ActionNavItemSchema3, - ActionParamSchema: () => ActionParamSchema5, - ActionSchema: () => ActionSchema5, - ActionType: () => ActionType5, - AddRecordConfigSchema: () => AddRecordConfigSchema3, - AnimationSchema: () => AnimationSchema2, - AnimationTriggerSchema: () => AnimationTriggerSchema2, - App: () => App2, - AppBrandingSchema: () => AppBrandingSchema3, - AppSchema: () => AppSchema3, - AppearanceConfigSchema: () => AppearanceConfigSchema3, - AriaPropsSchema: () => AriaPropsSchema5, - BlankPageLayoutItemSchema: () => BlankPageLayoutItemSchema2, - BlankPageLayoutSchema: () => BlankPageLayoutSchema2, - BorderRadiusSchema: () => BorderRadiusSchema2, - BreakpointColumnMapSchema: () => BreakpointColumnMapSchema3, - BreakpointName: () => BreakpointName3, - BreakpointOrderMapSchema: () => BreakpointOrderMapSchema3, - BreakpointsSchema: () => BreakpointsSchema2, - CalendarConfigSchema: () => CalendarConfigSchema3, - ChartAnnotationSchema: () => ChartAnnotationSchema2, - ChartAxisSchema: () => ChartAxisSchema2, - ChartConfigSchema: () => ChartConfigSchema2, - ChartInteractionSchema: () => ChartInteractionSchema2, - ChartSeriesSchema: () => ChartSeriesSchema2, - ChartTypeSchema: () => ChartTypeSchema2, - ColorPaletteSchema: () => ColorPaletteSchema2, - ColumnSummarySchema: () => ColumnSummarySchema3, - ComponentAnimationSchema: () => ComponentAnimationSchema2, - ComponentPropsMap: () => ComponentPropsMap2, - ConflictResolutionSchema: () => ConflictResolutionSchema2, - Dashboard: () => Dashboard, - DashboardHeaderActionSchema: () => DashboardHeaderActionSchema2, - DashboardHeaderSchema: () => DashboardHeaderSchema2, - DashboardNavItemSchema: () => DashboardNavItemSchema3, - DashboardSchema: () => DashboardSchema2, - DashboardWidgetSchema: () => DashboardWidgetSchema2, - DateFormatSchema: () => DateFormatSchema5, - DensityMode: () => DensityMode, - DensityModeSchema: () => DensityModeSchema2, - DndConfigSchema: () => DndConfigSchema2, - DragConstraintSchema: () => DragConstraintSchema2, - DragHandleSchema: () => DragHandleSchema2, - DragItemSchema: () => DragItemSchema2, - DropEffectSchema: () => DropEffectSchema2, - DropZoneSchema: () => DropZoneSchema2, - EasingFunctionSchema: () => EasingFunctionSchema2, - ElementButtonPropsSchema: () => ElementButtonPropsSchema2, - ElementDataSourceSchema: () => ElementDataSourceSchema2, - ElementFilterPropsSchema: () => ElementFilterPropsSchema2, - ElementFormPropsSchema: () => ElementFormPropsSchema2, - ElementImagePropsSchema: () => ElementImagePropsSchema2, - ElementNumberPropsSchema: () => ElementNumberPropsSchema2, - ElementRecordPickerPropsSchema: () => ElementRecordPickerPropsSchema2, - ElementTextPropsSchema: () => ElementTextPropsSchema2, - EmbedConfigSchema: () => EmbedConfigSchema3, - EvictionPolicySchema: () => EvictionPolicySchema2, - FieldWidgetPropsSchema: () => FieldWidgetPropsSchema2, - FocusManagementSchema: () => FocusManagementSchema2, - FocusTrapConfigSchema: () => FocusTrapConfigSchema2, - FormFieldSchema: () => FormFieldSchema3, - FormSectionSchema: () => FormSectionSchema3, - FormViewSchema: () => FormViewSchema3, - GalleryConfigSchema: () => GalleryConfigSchema3, - GanttConfigSchema: () => GanttConfigSchema3, - GestureConfigSchema: () => GestureConfigSchema2, - GestureTypeSchema: () => GestureTypeSchema2, - GlobalFilterOptionsFromSchema: () => GlobalFilterOptionsFromSchema2, - GlobalFilterSchema: () => GlobalFilterSchema2, - GroupNavItemSchema: () => GroupNavItemSchema3, - GroupingConfigSchema: () => GroupingConfigSchema3, - GroupingFieldSchema: () => GroupingFieldSchema3, - HttpMethodSchema: () => HttpMethodSchema5, - HttpRequestSchema: () => HttpRequestSchema4, - I18nLabelSchema: () => I18nLabelSchema5, - I18nObjectSchema: () => I18nObjectSchema2, - InterfacePageConfigSchema: () => InterfacePageConfigSchema2, - KanbanConfigSchema: () => KanbanConfigSchema3, - KeyboardNavigationConfigSchema: () => KeyboardNavigationConfigSchema2, - KeyboardShortcutSchema: () => KeyboardShortcutSchema2, - ListColumnSchema: () => ListColumnSchema3, - ListViewSchema: () => ListViewSchema3, - LocaleConfigSchema: () => LocaleConfigSchema2, - LongPressGestureConfigSchema: () => LongPressGestureConfigSchema2, - MotionConfigSchema: () => MotionConfigSchema2, - NavigationAreaSchema: () => NavigationAreaSchema3, - NavigationConfigSchema: () => NavigationConfigSchema3, - NavigationItemSchema: () => NavigationItemSchema3, - NavigationModeSchema: () => NavigationModeSchema3, - NotificationActionSchema: () => NotificationActionSchema2, - NotificationConfigSchema: () => NotificationConfigSchema3, - NotificationPositionSchema: () => NotificationPositionSchema2, - NotificationSchema: () => NotificationSchema3, - NotificationSeveritySchema: () => NotificationSeveritySchema2, - NotificationTypeSchema: () => NotificationTypeSchema2, - NumberFormatSchema: () => NumberFormatSchema5, - ObjectNavItemSchema: () => ObjectNavItemSchema3, - OfflineCacheConfigSchema: () => OfflineCacheConfigSchema2, - OfflineConfigSchema: () => OfflineConfigSchema2, - OfflineStrategySchema: () => OfflineStrategySchema2, - PageAccordionProps: () => PageAccordionProps2, - PageCardProps: () => PageCardProps2, - PageComponentSchema: () => PageComponentSchema2, - PageComponentType: () => PageComponentType2, - PageHeaderProps: () => PageHeaderProps2, - PageNavItemSchema: () => PageNavItemSchema3, - PageRegionSchema: () => PageRegionSchema2, - PageSchema: () => PageSchema2, - PageTabsProps: () => PageTabsProps2, - PageTransitionSchema: () => PageTransitionSchema2, - PageTypeSchema: () => PageTypeSchema2, - PageVariableSchema: () => PageVariableSchema2, - PaginationConfigSchema: () => PaginationConfigSchema3, - PerformanceConfigSchema: () => PerformanceConfigSchema3, - PersistStorageSchema: () => PersistStorageSchema2, - PinchGestureConfigSchema: () => PinchGestureConfigSchema2, - PluralRuleSchema: () => PluralRuleSchema2, - RecordActivityProps: () => RecordActivityProps2, - RecordChatterProps: () => RecordChatterProps2, - RecordDetailsProps: () => RecordDetailsProps2, - RecordHighlightsProps: () => RecordHighlightsProps2, - RecordPathProps: () => RecordPathProps2, - RecordRelatedListProps: () => RecordRelatedListProps2, - RecordReviewConfigSchema: () => RecordReviewConfigSchema2, - Report: () => Report, - ReportChartSchema: () => ReportChartSchema2, - ReportColumnSchema: () => ReportColumnSchema2, - ReportGroupingSchema: () => ReportGroupingSchema2, - ReportNavItemSchema: () => ReportNavItemSchema3, - ReportSchema: () => ReportSchema2, - ReportType: () => ReportType2, - ResponsiveConfigSchema: () => ResponsiveConfigSchema3, - RowColorConfigSchema: () => RowColorConfigSchema3, - RowHeightSchema: () => RowHeightSchema3, - SelectionConfigSchema: () => SelectionConfigSchema3, - ShadowSchema: () => ShadowSchema2, - SharingConfigSchema: () => SharingConfigSchema3, - SpacingSchema: () => SpacingSchema2, - SwipeDirectionSchema: () => SwipeDirectionSchema2, - SwipeGestureConfigSchema: () => SwipeGestureConfigSchema2, - SyncConfigSchema: () => SyncConfigSchema2, - ThemeMode: () => ThemeMode, - ThemeModeSchema: () => ThemeModeSchema2, - ThemeSchema: () => ThemeSchema2, - TimelineConfigSchema: () => TimelineConfigSchema3, - TouchInteractionSchema: () => TouchInteractionSchema2, - TouchTargetConfigSchema: () => TouchTargetConfigSchema2, - TransitionConfigSchema: () => TransitionConfigSchema2, - TransitionPresetSchema: () => TransitionPresetSchema2, - TypographySchema: () => TypographySchema2, - UrlNavItemSchema: () => UrlNavItemSchema3, - UserActionsConfigSchema: () => UserActionsConfigSchema3, - ViewDataSchema: () => ViewDataSchema3, - ViewFilterRuleSchema: () => ViewFilterRuleSchema3, - ViewSchema: () => ViewSchema3, - ViewSharingSchema: () => ViewSharingSchema3, - ViewTabSchema: () => ViewTabSchema3, - VisualizationTypeSchema: () => VisualizationTypeSchema3, - WcagContrastLevel: () => WcagContrastLevel, - WcagContrastLevelSchema: () => WcagContrastLevelSchema2, - WidgetActionTypeSchema: () => WidgetActionTypeSchema2, - WidgetColorVariantSchema: () => WidgetColorVariantSchema2, - WidgetEventSchema: () => WidgetEventSchema2, - WidgetLifecycleSchema: () => WidgetLifecycleSchema2, - WidgetManifestSchema: () => WidgetManifestSchema2, - WidgetMeasureSchema: () => WidgetMeasureSchema2, - WidgetPropertySchema: () => WidgetPropertySchema2, - WidgetSourceSchema: () => WidgetSourceSchema2, - ZIndexSchema: () => ZIndexSchema2, - defineApp: () => defineApp2, - defineView: () => defineView -}); -var ChartTypeSchema2 = external_exports.enum([ - // Comparison - "bar", - "horizontal-bar", - "column", - "grouped-bar", - "stacked-bar", - "bi-polar-bar", - // Trend - "line", - "area", - "stacked-area", - "step-line", - "spline", - // Distribution - "pie", - "donut", - "funnel", - "pyramid", - // Relationship - "scatter", - "bubble", - // Composition - "treemap", - "sunburst", - "sankey", - "word-cloud", - // Performance - "gauge", - "solid-gauge", - "metric", - "kpi", - "bullet", - // Geo - "choropleth", - "bubble-map", - "gl-map", - // Advanced - "heatmap", - "radar", - "waterfall", - "box-plot", - "violin", - "candlestick", - "stock", - // Tabular - "table", - "pivot" -]); -var ChartAxisSchema2 = external_exports.object({ - /** Data field to map to this axis */ - field: external_exports.string().describe("Data field key"), - /** Axis title */ - title: I18nLabelSchema5.optional().describe("Axis display title"), - /** Value formatting (d3-format or similar) */ - format: external_exports.string().optional().describe('Value format string (e.g., "$0,0.00")'), - /** Axis scale settings */ - min: external_exports.number().optional().describe("Minimum value"), - max: external_exports.number().optional().describe("Maximum value"), - stepSize: external_exports.number().optional().describe("Step size for ticks"), - /** Appearance */ - showGridLines: external_exports.boolean().default(true), - position: external_exports.enum(["left", "right", "top", "bottom"]).optional().describe("Axis position"), - /** Logarithmic scale */ - logarithmic: external_exports.boolean().default(false) -}); -var ChartSeriesSchema2 = external_exports.object({ - /** Field name for values */ - name: external_exports.string().describe("Field name or series identifier"), - /** Display label */ - label: I18nLabelSchema5.optional().describe("Series display label"), - /** Series type override (combo charts) */ - type: ChartTypeSchema2.optional().describe("Override chart type for this series"), - /** Specific color */ - color: external_exports.string().optional().describe("Series color (hex/rgb/token)"), - /** Stacking group */ - stack: external_exports.string().optional().describe("Stack identifier to group series"), - /** Axis binding */ - yAxis: external_exports.enum(["left", "right"]).default("left").describe("Bind to specific Y-Axis") -}); -var ChartAnnotationSchema2 = external_exports.object({ - type: external_exports.enum(["line", "region"]).default("line"), - axis: external_exports.enum(["x", "y"]).default("y"), - value: external_exports.union([external_exports.number(), external_exports.string()]).describe("Start value"), - endValue: external_exports.union([external_exports.number(), external_exports.string()]).optional().describe("End value for regions"), - color: external_exports.string().optional(), - label: I18nLabelSchema5.optional(), - style: external_exports.enum(["solid", "dashed", "dotted"]).default("dashed") -}); -var ChartInteractionSchema2 = external_exports.object({ - tooltips: external_exports.boolean().default(true), - zoom: external_exports.boolean().default(false), - brush: external_exports.boolean().default(false), - clickAction: external_exports.string().optional().describe("Action ID to trigger on click") -}); -var ChartConfigSchema2 = external_exports.object({ - /** Chart Type */ - type: ChartTypeSchema2, - /** Titles */ - title: I18nLabelSchema5.optional().describe("Chart title"), - subtitle: I18nLabelSchema5.optional().describe("Chart subtitle"), - description: I18nLabelSchema5.optional().describe("Accessibility description"), - /** Axes Mapping */ - xAxis: ChartAxisSchema2.optional().describe("X-Axis configuration"), - yAxis: external_exports.array(ChartAxisSchema2).optional().describe("Y-Axis configuration (support dual axis)"), - /** Series Configuration */ - series: external_exports.array(ChartSeriesSchema2).optional().describe("Defined series configuration"), - /** Appearance */ - colors: external_exports.array(external_exports.string()).optional().describe("Color palette"), - height: external_exports.number().optional().describe("Fixed height in pixels"), - /** Components */ - showLegend: external_exports.boolean().default(true).describe("Display legend"), - showDataLabels: external_exports.boolean().default(false).describe("Display data labels"), - /** Annotations & Reference Lines */ - annotations: external_exports.array(ChartAnnotationSchema2).optional(), - /** Interactions */ - interaction: ChartInteractionSchema2.optional(), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var BreakpointName3 = external_exports.enum(["xs", "sm", "md", "lg", "xl", "2xl"]); -var BreakpointColumnMapSchema3 = external_exports.object({ - xs: external_exports.number().min(1).max(12).optional(), - sm: external_exports.number().min(1).max(12).optional(), - md: external_exports.number().min(1).max(12).optional(), - lg: external_exports.number().min(1).max(12).optional(), - xl: external_exports.number().min(1).max(12).optional(), - "2xl": external_exports.number().min(1).max(12).optional() -}).describe("Grid columns per breakpoint (1-12)"); -var BreakpointOrderMapSchema3 = external_exports.object({ - xs: external_exports.number().optional(), - sm: external_exports.number().optional(), - md: external_exports.number().optional(), - lg: external_exports.number().optional(), - xl: external_exports.number().optional(), - "2xl": external_exports.number().optional() -}).describe("Display order per breakpoint"); -var ResponsiveConfigSchema3 = external_exports.object({ - /** Minimum breakpoint for visibility */ - breakpoint: BreakpointName3.optional().describe("Minimum breakpoint for visibility"), - /** Hide on specific breakpoints */ - hiddenOn: external_exports.array(BreakpointName3).optional().describe("Hide on these breakpoints"), - /** Grid columns per breakpoint (1-12 column grid) */ - columns: BreakpointColumnMapSchema3.optional().describe("Grid columns per breakpoint"), - /** Display order per breakpoint */ - order: BreakpointOrderMapSchema3.optional().describe("Display order per breakpoint") -}).describe("Responsive layout configuration"); -var PerformanceConfigSchema3 = external_exports.object({ - /** Enable lazy loading for this component */ - lazyLoad: external_exports.boolean().optional().describe("Enable lazy loading (defer rendering until visible)"), - /** Virtual scrolling configuration for large datasets */ - virtualScroll: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable virtual scrolling"), - itemHeight: external_exports.number().optional().describe("Fixed item height in pixels (for estimation)"), - overscan: external_exports.number().optional().describe("Number of extra items to render outside viewport") - }).optional().describe("Virtual scrolling configuration"), - /** Client-side caching strategy */ - cacheStrategy: external_exports.enum([ - "none", - "cache-first", - "network-first", - "stale-while-revalidate" - ]).optional().describe("Client-side data caching strategy"), - /** Enable data prefetching */ - prefetch: external_exports.boolean().optional().describe("Prefetch data before component is visible"), - /** Maximum number of items to render before pagination */ - pageSize: external_exports.number().optional().describe("Number of items per page for pagination"), - /** Debounce interval for user interactions (ms) */ - debounceMs: external_exports.number().optional().describe("Debounce interval for user interactions in milliseconds") -}).describe("Performance optimization configuration"); -var SharingConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable public sharing"), - publicLink: external_exports.string().optional().describe("Generated public share URL"), - password: external_exports.string().optional().describe("Password required to access shared link"), - allowedDomains: external_exports.array(external_exports.string()).optional().describe('Restrict access to specific email domains (e.g. ["example.com"])'), - expiresAt: external_exports.string().optional().describe("Expiration date/time in ISO 8601 format"), - allowAnonymous: external_exports.boolean().optional().default(false).describe("Allow access without authentication") -}); -var EmbedConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable iframe embedding"), - allowedOrigins: external_exports.array(external_exports.string()).optional().describe('Allowed iframe parent origins (e.g. ["https://example.com"])'), - width: external_exports.string().optional().default("100%").describe("Embed width (CSS value)"), - height: external_exports.string().optional().default("600px").describe("Embed height (CSS value)"), - showHeader: external_exports.boolean().optional().default(true).describe("Show interface header in embed"), - showNavigation: external_exports.boolean().optional().default(false).describe("Show navigation in embed"), - responsive: external_exports.boolean().optional().default(true).describe("Enable responsive resizing") -}); -var BaseNavItemSchema3 = external_exports.object({ - /** Unique identifier for the item */ - id: SnakeCaseIdentifierSchema7.describe("Unique identifier for this navigation item (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema5.describe("Display proper label"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Icon name"), - /** Sort order within the same level (lower numbers appear first) */ - order: external_exports.number().optional().describe("Sort order within the same level (lower = first)"), - /** Badge text or count displayed on the navigation item (e.g. "3", "New") */ - badge: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe("Badge text or count displayed on the item"), - /** - * Visibility condition. - * Formula expression returning boolean. - * e.g. "user.is_admin || user.department == 'sales'" - */ - visible: external_exports.string().optional().describe("Visibility formula condition"), - /** Permissions required to see/access this navigation item */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this item") -}); -var ObjectNavItemSchema3 = BaseNavItemSchema3.extend({ - type: external_exports.literal("object"), - objectName: external_exports.string().describe("Target object name"), - viewName: external_exports.string().optional().describe('Default list view to open. Defaults to "all"') -}); -var DashboardNavItemSchema3 = BaseNavItemSchema3.extend({ - type: external_exports.literal("dashboard"), - dashboardName: external_exports.string().describe("Target dashboard name") -}); -var PageNavItemSchema3 = BaseNavItemSchema3.extend({ - type: external_exports.literal("page"), - pageName: external_exports.string().describe("Target custom page component name"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the page context") -}); -var UrlNavItemSchema3 = BaseNavItemSchema3.extend({ - type: external_exports.literal("url"), - url: external_exports.string().describe("Target external URL"), - target: external_exports.enum(["_self", "_blank"]).default("_self").describe("Link target window") -}); -var ReportNavItemSchema3 = BaseNavItemSchema3.extend({ - type: external_exports.literal("report"), - reportName: external_exports.string().describe("Target report name") -}); -var ActionNavItemSchema3 = BaseNavItemSchema3.extend({ - type: external_exports.literal("action"), - actionDef: external_exports.object({ - actionName: external_exports.string().describe("Action machine name to execute"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Parameters passed to the action") - }).describe("Action definition to execute when clicked") -}); -var GroupNavItemSchema3 = BaseNavItemSchema3.extend({ - type: external_exports.literal("group"), - expanded: external_exports.boolean().default(false).describe("Default expansion state in sidebar") - // children property is added in the recursive definition below -}); -var NavigationItemSchema3 = external_exports.lazy( - () => external_exports.union([ - ObjectNavItemSchema3.extend({ - children: external_exports.array(NavigationItemSchema3).optional().describe("Child navigation items (e.g. specific views)") - }), - DashboardNavItemSchema3, - PageNavItemSchema3, - UrlNavItemSchema3, - ReportNavItemSchema3, - ActionNavItemSchema3, - GroupNavItemSchema3.extend({ - children: external_exports.array(NavigationItemSchema3).describe("Child navigation items") - }) - ]) -); -var AppBrandingSchema3 = external_exports.object({ - primaryColor: external_exports.string().optional().describe("Primary theme color hex code"), - logo: external_exports.string().optional().describe("Custom logo URL for this app"), - favicon: external_exports.string().optional().describe("Custom favicon URL for this app") -}); -var NavigationAreaSchema3 = external_exports.object({ - /** Unique area identifier */ - id: SnakeCaseIdentifierSchema7.describe("Unique area identifier (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema5.describe("Area display label"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("Area icon name"), - /** Sort order among areas (lower = first) */ - order: external_exports.number().optional().describe("Sort order among areas (lower = first)"), - /** Area description */ - description: I18nLabelSchema5.optional().describe("Area description"), - /** - * Visibility condition. - * Formula expression returning boolean. - */ - visible: external_exports.string().optional().describe("Visibility formula condition for this area"), - /** Permissions required to access this area */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this area"), - /** Navigation items within this area */ - navigation: external_exports.array(NavigationItemSchema3).describe("Navigation items within this area") -}); -var AppSchema3 = external_exports.object({ - /** Machine name (id) */ - name: SnakeCaseIdentifierSchema7.describe("App unique machine name (lowercase snake_case)"), - /** Display label */ - label: I18nLabelSchema5.describe("App display label"), - /** App version */ - version: external_exports.string().optional().describe("App version"), - /** Description */ - description: I18nLabelSchema5.optional().describe("App description"), - /** Icon name (Lucide) */ - icon: external_exports.string().optional().describe("App icon used in the App Launcher"), - /** Branding/Theming Configuration */ - branding: AppBrandingSchema3.optional().describe("App-specific branding"), - /** Application status */ - active: external_exports.boolean().optional().default(true).describe("Whether the app is enabled"), - /** Is this the default app for new users? */ - isDefault: external_exports.boolean().optional().default(false).describe("Is default app"), - /** - * Full Navigation Tree — supports unlimited nesting depth. - * Pages are referenced by name via `type: 'page'` items. - * Groups can contain other groups for arbitrary sidebar depth. - * - * For simple apps, use `navigation` directly. - * For enterprise apps with multiple business domains, use `areas` instead. - */ - navigation: external_exports.array(NavigationItemSchema3).optional().describe("Full navigation tree for the app sidebar"), - /** - * Navigation Areas — partitions navigation by business domain. - * Each area defines an independent navigation tree (e.g. Sales, Service, Settings). - * When areas are defined, they take precedence over the top-level `navigation` array. - * - * @example - * ```ts - * areas: [ - * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] }, - * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] }, - * ] - * ``` - */ - areas: external_exports.array(NavigationAreaSchema3).optional().describe("Navigation areas for partitioning navigation by business domain"), - /** - * App-level Home Page Override - * ID of the navigation item to act as the landing page. - * If not set, usually defaults to the first navigation item. - */ - homePageId: external_exports.string().optional().describe("ID of the navigation item to serve as landing page"), - /** - * Access Control - * List of permissions required to access this app. - * Modern replacement for role/profile based assignment. - * Example: ["app.access.crm"] - */ - requiredPermissions: external_exports.array(external_exports.string()).optional().describe("Permissions required to access this app"), - /** - * Package Components (For config file convenience) - * In a real monorepo these might be auto-discovered, but here we allow explicit registration. - */ - objects: external_exports.array(external_exports.unknown()).optional().describe("Objects belonging to this app"), - apis: external_exports.array(external_exports.unknown()).optional().describe("Custom APIs belonging to this app"), - /** Sharing configuration for public access */ - sharing: SharingConfigSchema3.optional().describe("Public sharing configuration"), - /** Embed configuration for iframe embedding */ - embed: EmbedConfigSchema3.optional().describe("Iframe embedding configuration"), - /** Mobile navigation mode */ - mobileNavigation: external_exports.object({ - mode: external_exports.enum(["drawer", "bottom_nav", "hamburger"]).default("drawer").describe("Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu"), - bottomNavItems: external_exports.array(external_exports.string()).optional().describe("Navigation item IDs to show in bottom nav (max 5)") - }).optional().describe("Mobile-specific navigation configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes for the application") -}); -var App2 = { - create: (config4) => AppSchema3.parse(config4) -}; -function defineApp2(config4) { - return AppSchema3.parse(config4); -} -var ViewDataSchema3 = external_exports.discriminatedUnion("provider", [ - external_exports.object({ - provider: external_exports.literal("object"), - object: external_exports.string().describe("Target object name") - }), - external_exports.object({ - provider: external_exports.literal("api"), - read: HttpRequestSchema4.optional().describe("Configuration for fetching data"), - write: HttpRequestSchema4.optional().describe("Configuration for submitting data (for forms/editable tables)") - }), - external_exports.object({ - provider: external_exports.literal("value"), - items: external_exports.array(external_exports.unknown()).describe("Static data array") - }) -]); -var ViewFilterRuleSchema3 = external_exports.object({ - /** Field name to filter on */ - field: external_exports.string().describe("Field name to filter on"), - /** Filter operator */ - operator: external_exports.string().describe("Filter operator (e.g. equals, not_equals, contains, this_quarter)"), - /** Filter value (optional for unary operators like is_null, this_quarter) */ - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Filter value") -}).describe("View filter rule"); -var ColumnSummarySchema3 = external_exports.enum([ - "none", - "count", - "count_empty", - "count_filled", - "count_unique", - "percent_empty", - "percent_filled", - "sum", - "avg", - "min", - "max" -]).describe("Aggregation function for column footer summary"); -var ListColumnSchema3 = external_exports.object({ - field: external_exports.string().describe("Field name (snake_case)"), - label: I18nLabelSchema5.optional().describe("Display label override"), - width: external_exports.number().positive().optional().describe("Column width in pixels"), - align: external_exports.enum(["left", "center", "right"]).optional().describe("Text alignment"), - hidden: external_exports.boolean().optional().describe("Hide column by default"), - sortable: external_exports.boolean().optional().describe("Allow sorting by this column"), - resizable: external_exports.boolean().optional().describe("Allow resizing this column"), - wrap: external_exports.boolean().optional().describe("Allow text wrapping"), - type: external_exports.string().optional().describe('Renderer type override (e.g., "currency", "date")'), - /** Pinning (Airtable-style frozen columns) */ - pinned: external_exports.enum(["left", "right"]).optional().describe("Pin/freeze column to left or right side"), - /** Column Footer Summary (Airtable-style aggregation) */ - summary: ColumnSummarySchema3.optional().describe("Footer aggregation function for this column"), - /** Interaction */ - link: external_exports.boolean().optional().describe("Functions as the primary navigation link (triggers View navigation)"), - action: external_exports.string().optional().describe("Registered Action ID to execute when clicked") -}); -var SelectionConfigSchema3 = external_exports.object({ - type: external_exports.enum(["none", "single", "multiple"]).default("none").describe("Selection mode") -}); -var PaginationConfigSchema3 = external_exports.object({ - pageSize: external_exports.number().int().positive().default(25).describe("Number of records per page"), - pageSizeOptions: external_exports.array(external_exports.number().int().positive()).optional().describe("Available page size options") -}); -var RowHeightSchema3 = external_exports.enum([ - "compact", - // Minimal padding, single line - "short", - // Reduced padding - "medium", - // Default padding - "tall", - // Extra padding, multi-line preview - "extra_tall" - // Maximum padding, rich content preview -]).describe("Row height / density setting for list view"); -var GroupingFieldSchema3 = external_exports.object({ - field: external_exports.string().describe("Field name to group by"), - order: external_exports.enum(["asc", "desc"]).default("asc").describe("Group sort order"), - collapsed: external_exports.boolean().default(false).describe("Collapse groups by default") -}); -var GroupingConfigSchema3 = external_exports.object({ - fields: external_exports.array(GroupingFieldSchema3).min(1).describe("Fields to group by (supports up to 3 levels)") -}).describe("Record grouping configuration"); -var GalleryConfigSchema3 = external_exports.object({ - coverField: external_exports.string().optional().describe("Attachment/image field to display as card cover"), - coverFit: external_exports.enum(["cover", "contain"]).default("cover").describe("Image fit mode for card cover"), - cardSize: external_exports.enum(["small", "medium", "large"]).default("medium").describe("Card size in gallery view"), - titleField: external_exports.string().optional().describe("Field to display as card title"), - visibleFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on card body") -}).describe("Gallery/card view configuration"); -var TimelineConfigSchema3 = external_exports.object({ - startDateField: external_exports.string().describe("Field for timeline item start date"), - endDateField: external_exports.string().optional().describe("Field for timeline item end date"), - titleField: external_exports.string().describe("Field to display as timeline item title"), - groupByField: external_exports.string().optional().describe("Field to group timeline rows"), - colorField: external_exports.string().optional().describe("Field to determine item color"), - scale: external_exports.enum(["hour", "day", "week", "month", "quarter", "year"]).default("week").describe("Default timeline scale") -}).describe("Timeline view configuration"); -var ViewSharingSchema3 = external_exports.object({ - type: external_exports.enum(["personal", "collaborative"]).default("collaborative").describe("View ownership type"), - lockedBy: external_exports.string().optional().describe("User who locked the view configuration") -}).describe("View sharing and access configuration"); -var RowColorConfigSchema3 = external_exports.object({ - field: external_exports.string().describe("Field to derive color from (typically a select/status field)"), - colors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Map of field value to color (hex/token)") -}).describe("Row color configuration based on field values"); -var VisualizationTypeSchema3 = external_exports.enum([ - "grid", - "kanban", - "gallery", - "calendar", - "timeline", - "gantt", - "map" -]).describe("Visualization type that users can switch to"); -var UserActionsConfigSchema3 = external_exports.object({ - sort: external_exports.boolean().default(true).describe("Allow users to sort records"), - search: external_exports.boolean().default(true).describe("Allow users to search records"), - filter: external_exports.boolean().default(true).describe("Allow users to filter records"), - rowHeight: external_exports.boolean().default(true).describe("Allow users to toggle row height/density"), - addRecordForm: external_exports.boolean().default(false).describe("Add records through a form instead of inline"), - buttons: external_exports.array(external_exports.string()).optional().describe("Custom action button IDs to show in the toolbar") -}).describe("User action toggles for the view toolbar"); -var AppearanceConfigSchema3 = external_exports.object({ - showDescription: external_exports.boolean().default(true).describe("Show the view description text"), - allowedVisualizations: external_exports.array(VisualizationTypeSchema3).optional().describe('Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])') -}).describe("Appearance and visualization configuration"); -var ViewTabSchema3 = external_exports.object({ - name: SnakeCaseIdentifierSchema7.describe("Tab identifier (snake_case)"), - label: I18nLabelSchema5.optional().describe("Display label"), - icon: external_exports.string().optional().describe("Tab icon name"), - view: external_exports.string().optional().describe("Referenced list view name from listViews"), - filter: external_exports.array(ViewFilterRuleSchema3).optional().describe("Tab-specific filter criteria"), - order: external_exports.number().int().min(0).optional().describe("Tab display order"), - pinned: external_exports.boolean().default(false).describe("Pin tab (cannot be removed by users)"), - isDefault: external_exports.boolean().default(false).describe("Set as the default active tab"), - visible: external_exports.boolean().default(true).describe("Tab visibility") -}).describe("Tab configuration for multi-tab view interface"); -var AddRecordConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Show the add record entry point"), - position: external_exports.enum(["top", "bottom", "both"]).default("bottom").describe("Position of the add record button"), - mode: external_exports.enum(["inline", "form", "modal"]).default("inline").describe("How to add a new record"), - formView: external_exports.string().optional().describe('Named form view to use when mode is "form" or "modal"') -}).describe("Add record entry point configuration"); -var KanbanConfigSchema3 = external_exports.object({ - groupByField: external_exports.string().describe("Field to group columns by (usually status/select)"), - summarizeField: external_exports.string().optional().describe("Field to sum at top of column (e.g. amount)"), - columns: external_exports.array(external_exports.string()).describe("Fields to show on cards") -}); -var CalendarConfigSchema3 = external_exports.object({ - startDateField: external_exports.string(), - endDateField: external_exports.string().optional(), - titleField: external_exports.string(), - colorField: external_exports.string().optional() -}); -var GanttConfigSchema3 = external_exports.object({ - startDateField: external_exports.string(), - endDateField: external_exports.string(), - titleField: external_exports.string(), - progressField: external_exports.string().optional(), - dependenciesField: external_exports.string().optional() -}); -var NavigationModeSchema3 = external_exports.enum([ - "page", - // Navigate to a new route (default) - "drawer", - // Open details in a side drawer/panel - "modal", - // Open details in a modal dialog - "split", - // Show details side-by-side with the list (master-detail) - "popover", - // Show details in a popover (lightweight) - "new_window", - // Open in new browser tab/window - "none" - // No navigation (read-only list) -]); -var NavigationConfigSchema3 = external_exports.object({ - mode: NavigationModeSchema3.default("page"), - /** Target View Config */ - view: external_exports.string().optional().describe('Name of the form view to use for details (e.g. "summary_view", "edit_form")'), - /** Interaction Triggers */ - preventNavigation: external_exports.boolean().default(false).describe("Disable standard navigation entirely"), - openNewTab: external_exports.boolean().default(false).describe("Force open in new tab (applies to page mode)"), - /** Dimensions (for modal/drawer) */ - width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Width of the drawer/modal (e.g. "600px", "50%")') -}); -var ListViewSchema3 = external_exports.object({ - name: SnakeCaseIdentifierSchema7.optional().describe("Internal view name (lowercase snake_case)"), - label: I18nLabelSchema5.optional(), - // Display label override (supports i18n) - type: external_exports.enum([ - "grid", - // Standard Data Table - "kanban", - // Board / Columns - "gallery", - // Card Deck / Masonry - "calendar", - // Monthly/Weekly/Daily - "timeline", - // Chronological Stream (Feed) - "gantt", - // Project Timeline - "map" - // Geospatial - ]).default("grid"), - /** Data Source Configuration */ - data: ViewDataSchema3.optional().describe('Data source configuration (defaults to "object" provider)'), - /** Shared Query Config */ - columns: external_exports.union([ - external_exports.array(external_exports.string()), - // Legacy: simple field names - external_exports.array(ListColumnSchema3) - // Enhanced: detailed column config - ]).describe("Fields to display as columns"), - filter: external_exports.array(ViewFilterRuleSchema3).optional().describe("Filter criteria (JSON Rules)"), - sort: external_exports.union([ - external_exports.string(), - //Legacy "field desc" - external_exports.array(external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]) - })) - ]).optional(), - /** Search & Filter */ - searchableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for search"), - filterableFields: external_exports.array(external_exports.string()).optional().describe("Fields enabled for end-user filtering in the top bar"), - /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */ - quickFilters: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name to filter by"), - label: external_exports.string().optional().describe("Display label for the chip"), - operator: external_exports.enum(["equals", "not_equals", "contains", "in", "is_null", "is_not_null"]).default("equals").describe("Filter operator"), - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).optional().describe("Preset filter value") - })).optional().describe("One-click filter chips for quick record filtering"), - /** Grid Features */ - resizable: external_exports.boolean().optional().describe("Enable column resizing"), - striped: external_exports.boolean().optional().describe("Striped row styling"), - bordered: external_exports.boolean().optional().describe("Show borders"), - /** Selection */ - selection: SelectionConfigSchema3.optional().describe("Row selection configuration"), - /** Navigation / Interaction */ - navigation: NavigationConfigSchema3.optional().describe("Configuration for item click navigation (page, drawer, modal, etc.)"), - /** Pagination */ - pagination: PaginationConfigSchema3.optional().describe("Pagination configuration"), - /** Type Specific Config */ - kanban: KanbanConfigSchema3.optional(), - calendar: CalendarConfigSchema3.optional(), - gantt: GanttConfigSchema3.optional(), - gallery: GalleryConfigSchema3.optional(), - timeline: TimelineConfigSchema3.optional(), - /** View Metadata (Airtable-style view management) */ - description: I18nLabelSchema5.optional().describe("View description for documentation/tooltips"), - sharing: ViewSharingSchema3.optional().describe("View sharing and access configuration"), - /** Row Height / Density (Airtable-style) */ - rowHeight: RowHeightSchema3.optional().describe("Row height / density setting"), - /** Record Grouping (Airtable-style) */ - grouping: GroupingConfigSchema3.optional().describe("Group records by one or more fields"), - /** Row Color (Airtable-style) */ - rowColor: RowColorConfigSchema3.optional().describe("Color rows based on field value"), - /** Field Visibility & Ordering per View (Airtable-style) */ - hiddenFields: external_exports.array(external_exports.string()).optional().describe("Fields to hide in this specific view"), - fieldOrder: external_exports.array(external_exports.string()).optional().describe("Explicit field display order for this view"), - /** Row & Bulk Actions */ - rowActions: external_exports.array(external_exports.string()).optional().describe("Actions available for individual row items"), - bulkActions: external_exports.array(external_exports.string()).optional().describe("Actions available when multiple rows are selected"), - /** Performance */ - virtualScroll: external_exports.boolean().optional().describe("Enable virtual scrolling for large datasets"), - /** Conditional Formatting */ - conditionalFormatting: external_exports.array(external_exports.object({ - condition: external_exports.string().describe("Condition expression to evaluate"), - style: external_exports.record(external_exports.string(), external_exports.string()).describe("CSS styles to apply when condition is true") - })).optional().describe("Conditional formatting rules for list rows"), - /** Inline Edit */ - inlineEdit: external_exports.boolean().optional().describe("Allow inline editing of records directly in the list view"), - /** Export */ - exportOptions: external_exports.array(external_exports.enum(["csv", "xlsx", "pdf", "json"])).optional().describe("Available export format options"), - /** User Actions (Airtable Interface parity) */ - userActions: UserActionsConfigSchema3.optional().describe("User action toggles for the view toolbar"), - /** Appearance (Airtable Interface parity) */ - appearance: AppearanceConfigSchema3.optional().describe("Appearance and visualization configuration"), - /** Tabs (Airtable Interface parity) */ - tabs: external_exports.array(ViewTabSchema3).optional().describe("Tab definitions for multi-tab view interface"), - /** Add Record (Airtable Interface parity) */ - addRecord: AddRecordConfigSchema3.optional().describe("Add record entry point configuration"), - /** Record Count Display (Airtable Interface parity) */ - showRecordCount: external_exports.boolean().optional().describe("Show record count at the bottom of the list"), - /** Advanced: Allow Printing (Airtable Interface parity) */ - allowPrinting: external_exports.boolean().optional().describe("Allow users to print the view"), - /** Empty State */ - emptyState: external_exports.object({ - title: I18nLabelSchema5.optional(), - message: I18nLabelSchema5.optional(), - icon: external_exports.string().optional() - }).optional().describe("Empty state configuration when no records found"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes for the list view"), - /** Responsive layout overrides per breakpoint */ - responsive: ResponsiveConfigSchema3.optional().describe("Responsive layout configuration"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema3.optional().describe("Performance optimization settings") -}); -var FormFieldSchema3 = external_exports.object({ - field: external_exports.string().describe("Field name (snake_case)"), - label: I18nLabelSchema5.optional().describe("Display label override"), - placeholder: I18nLabelSchema5.optional().describe("Placeholder text"), - helpText: I18nLabelSchema5.optional().describe("Help/hint text"), - readonly: external_exports.boolean().optional().describe("Read-only override"), - required: external_exports.boolean().optional().describe("Required override"), - hidden: external_exports.boolean().optional().describe("Hidden override"), - colSpan: external_exports.number().int().min(1).max(4).optional().describe("Column span in grid layout (1-4)"), - widget: external_exports.string().optional().describe("Custom widget/component name"), - dependsOn: external_exports.string().optional().describe("Parent field name for cascading"), - visibleOn: external_exports.string().optional().describe("Visibility condition expression") -}); -var FormSectionSchema3 = external_exports.object({ - label: I18nLabelSchema5.optional(), - collapsible: external_exports.boolean().default(false), - collapsed: external_exports.boolean().default(false), - columns: external_exports.enum(["1", "2", "3", "4"]).default("2").transform((val) => parseInt(val)), - fields: external_exports.array(external_exports.union([ - external_exports.string(), - // Legacy: simple field name - FormFieldSchema3 - // Enhanced: detailed field config - ])) -}); -var FormViewSchema3 = external_exports.object({ - type: external_exports.enum([ - "simple", - // Single column or sections - "tabbed", - // Tabs - "wizard", - // Step by step - "split", - // Master-Detail split - "drawer", - // Side panel - "modal" - // Dialog - ]).default("simple"), - /** Data Source Configuration */ - data: ViewDataSchema3.optional().describe('Data source configuration (defaults to "object" provider)'), - sections: external_exports.array(FormSectionSchema3).optional(), - // For simple layout - groups: external_exports.array(FormSectionSchema3).optional(), - // Legacy support -> alias to sections - /** Default Sort for Related Lists (e.g., sort child records by date) */ - defaultSort: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - order: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction") - })).optional().describe("Default sort order for related list views within this form"), - /** Public form sharing configuration */ - sharing: SharingConfigSchema3.optional().describe("Public sharing configuration for this form"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes for the form view") -}); -var ViewSchema3 = external_exports.object({ - list: ListViewSchema3.optional(), - // Default list view - form: FormViewSchema3.optional(), - // Default form view - listViews: external_exports.record(external_exports.string(), ListViewSchema3).optional().describe("Additional named list views"), - formViews: external_exports.record(external_exports.string(), FormViewSchema3).optional().describe("Additional named form views") -}); -function defineView(config4) { - return ViewSchema3.parse(config4); -} -var WidgetColorVariantSchema2 = external_exports.enum([ - "default", - "blue", - "teal", - "orange", - "purple", - "success", - "warning", - "danger" -]).describe("Widget color variant"); -var WidgetActionTypeSchema2 = external_exports.enum([ - "script", - "url", - "modal", - "flow", - "api" -]).describe("Widget action type"); -var DashboardHeaderActionSchema2 = external_exports.object({ - /** Action label */ - label: I18nLabelSchema5.describe("Action button label"), - /** Action URL or target */ - actionUrl: external_exports.string().describe("URL or target for the action"), - /** Action type */ - actionType: WidgetActionTypeSchema2.optional().describe("Type of action"), - /** Icon identifier */ - icon: external_exports.string().optional().describe("Icon identifier for the action button") -}).describe("Dashboard header action"); -var DashboardHeaderSchema2 = external_exports.object({ - /** Whether to show the dashboard title in the header */ - showTitle: external_exports.boolean().default(true).describe("Show dashboard title in header"), - /** Whether to show the dashboard description in the header */ - showDescription: external_exports.boolean().default(true).describe("Show dashboard description in header"), - /** Action buttons displayed in the header */ - actions: external_exports.array(DashboardHeaderActionSchema2).optional().describe("Header action buttons") -}).describe("Dashboard header configuration"); -var WidgetMeasureSchema2 = external_exports.object({ - /** Value field to aggregate */ - valueField: external_exports.string().describe("Field to aggregate"), - /** Aggregate function */ - aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).default("count").describe("Aggregate function"), - /** Display label for the measure */ - label: I18nLabelSchema5.optional().describe("Measure display label"), - /** Number format string (e.g., "$0,0.00", "0.0%") */ - format: external_exports.string().optional().describe("Number format string") -}).describe("Widget measure definition"); -var DashboardWidgetSchema2 = external_exports.object({ - /** Unique widget identifier (snake_case, used for targetWidgets references) */ - id: SnakeCaseIdentifierSchema7.describe("Unique widget identifier (snake_case)"), - /** Widget Title */ - title: I18nLabelSchema5.optional().describe("Widget title"), - /** Widget Description (displayed below the title) */ - description: I18nLabelSchema5.optional().describe("Widget description text below the header"), - /** Visualization Type */ - type: ChartTypeSchema2.default("metric").describe("Visualization type"), - /** Chart Configuration */ - chartConfig: ChartConfigSchema2.optional().describe("Chart visualization configuration"), - /** Color variant for the widget (e.g., KPI card accent color) */ - colorVariant: WidgetColorVariantSchema2.optional().describe("Widget color variant for theming"), - /** Action URL for the widget header action button */ - actionUrl: external_exports.string().optional().describe("URL or target for the widget action button"), - /** Action type for the widget header action button */ - actionType: WidgetActionTypeSchema2.optional().describe("Type of action for the widget action button"), - /** Icon for the widget header action button */ - actionIcon: external_exports.string().optional().describe("Icon identifier for the widget action button"), - /** Data Source Object */ - object: external_exports.string().optional().describe("Data source object name"), - /** Data Filter (MongoDB-style FilterCondition) */ - filter: FilterConditionSchema4.optional().describe("Data filter criteria"), - /** Category Field (X-Axis / Group By) */ - categoryField: external_exports.string().optional().describe("Field for grouping (X-Axis)"), - /** Value Field (Y-Axis) */ - valueField: external_exports.string().optional().describe("Field for values (Y-Axis)"), - /** Aggregate operation */ - aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).optional().default("count").describe("Aggregate function"), - /** Multi-measure definitions for pivot/matrix widgets */ - measures: external_exports.array(WidgetMeasureSchema2).optional().describe("Multiple measures for pivot/matrix analysis"), - /** - * Layout Position (React-Grid-Layout style) - * x: column (0-11) - * y: row - * w: width (1-12) - * h: height - */ - layout: external_exports.object({ - x: external_exports.number(), - y: external_exports.number(), - w: external_exports.number(), - h: external_exports.number() - }).describe("Grid layout position"), - /** Widget specific options (colors, legend, etc.) */ - options: external_exports.unknown().optional().describe("Widget specific configuration"), - /** Responsive layout overrides per breakpoint */ - responsive: ResponsiveConfigSchema3.optional().describe("Responsive layout configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var GlobalFilterOptionsFromSchema2 = external_exports.object({ - /** Source object name to fetch options from */ - object: external_exports.string().describe("Source object name"), - /** Field to use as option value */ - valueField: external_exports.string().describe("Field to use as option value"), - /** Field to use as option label */ - labelField: external_exports.string().describe("Field to use as option label"), - /** Optional filter to apply when fetching options */ - filter: FilterConditionSchema4.optional().describe("Filter to apply to source object") -}).describe("Dynamic filter options from object"); -var GlobalFilterSchema2 = external_exports.object({ - /** Field name to filter on */ - field: external_exports.string().describe("Field name to filter on"), - /** Display label for the filter */ - label: I18nLabelSchema5.optional().describe("Display label for the filter"), - /** Filter input type */ - type: external_exports.enum(["text", "select", "date", "number", "lookup"]).optional().describe("Filter input type"), - /** Static options for select/lookup filters */ - options: external_exports.array(external_exports.object({ - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).describe("Option value"), - label: I18nLabelSchema5 - })).optional().describe("Static filter options"), - /** Dynamic data binding for filter options */ - optionsFrom: GlobalFilterOptionsFromSchema2.optional().describe("Dynamic filter options from object"), - /** Default filter value */ - defaultValue: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Default filter value"), - /** Filter application scope */ - scope: external_exports.enum(["dashboard", "widget"]).default("dashboard").describe("Filter application scope"), - /** Widget IDs to apply this filter to (when scope is widget) */ - targetWidgets: external_exports.array(external_exports.string()).optional().describe("Widget IDs to apply this filter to") -}); -var DashboardSchema2 = external_exports.object({ - /** Machine name */ - name: SnakeCaseIdentifierSchema7.describe("Dashboard unique name"), - /** Display label */ - label: I18nLabelSchema5.describe("Dashboard label"), - /** Description */ - description: I18nLabelSchema5.optional().describe("Dashboard description"), - /** Structured header configuration */ - header: DashboardHeaderSchema2.optional().describe("Dashboard header configuration"), - /** Collection of widgets */ - widgets: external_exports.array(DashboardWidgetSchema2).describe("Widgets to display"), - /** Auto-refresh */ - refreshInterval: external_exports.number().optional().describe("Auto-refresh interval in seconds"), - /** Dashboard Date Range (Global time filter) */ - dateRange: external_exports.object({ - field: external_exports.string().optional().describe("Default date field name for time-based filtering"), - defaultRange: external_exports.enum(["today", "yesterday", "this_week", "last_week", "this_month", "last_month", "this_quarter", "last_quarter", "this_year", "last_year", "last_7_days", "last_30_days", "last_90_days", "custom"]).default("this_month").describe("Default date range preset"), - allowCustomRange: external_exports.boolean().default(true).describe("Allow users to pick a custom date range") - }).optional().describe("Global dashboard date range filter configuration"), - /** Global Filters */ - globalFilters: external_exports.array(GlobalFilterSchema2).optional().describe("Global filters that apply to all widgets in the dashboard"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema3.optional().describe("Performance optimization settings") -}); -var Dashboard = { - create: (config4) => DashboardSchema2.parse(config4) -}; -var ReportType2 = external_exports.enum([ - "tabular", - // Simple list - "summary", - // Grouped by row - "matrix", - // Grouped by row and column - "joined" - // Joined multiple blocks -]); -var ReportColumnSchema2 = external_exports.object({ - field: external_exports.string().describe("Field name"), - label: I18nLabelSchema5.optional().describe("Override label"), - aggregate: external_exports.enum(["sum", "avg", "max", "min", "count", "unique"]).optional().describe("Aggregation function"), - /** Responsive visibility/priority per breakpoint */ - responsive: ResponsiveConfigSchema3.optional().describe("Responsive visibility for this column") -}); -var ReportGroupingSchema2 = external_exports.object({ - field: external_exports.string().describe("Field to group by"), - sortOrder: external_exports.enum(["asc", "desc"]).default("asc"), - dateGranularity: external_exports.enum(["day", "week", "month", "quarter", "year"]).optional().describe("For date fields") -}); -var ReportChartSchema2 = ChartConfigSchema2.extend({ - /** Report-specific chart configuration */ - xAxis: external_exports.string().describe("Grouping field for X-Axis"), - yAxis: external_exports.string().describe("Summary field for Y-Axis"), - groupBy: external_exports.string().optional().describe("Additional grouping field") -}); -var ReportSchema2 = external_exports.object({ - /** Identity */ - name: SnakeCaseIdentifierSchema7.describe("Report unique name"), - label: I18nLabelSchema5.describe("Report label"), - description: I18nLabelSchema5.optional(), - /** Data Source */ - objectName: external_exports.string().describe("Primary object"), - /** Report Configuration */ - type: ReportType2.default("tabular").describe("Report format type"), - columns: external_exports.array(ReportColumnSchema2).describe("Columns to display"), - /** Grouping (for Summary/Matrix) */ - groupingsDown: external_exports.array(ReportGroupingSchema2).optional().describe("Row groupings"), - groupingsAcross: external_exports.array(ReportGroupingSchema2).optional().describe("Column groupings (Matrix only)"), - /** Filtering (MongoDB-style FilterCondition) */ - filter: FilterConditionSchema4.optional().describe("Filter criteria"), - /** Visualization */ - chart: ReportChartSchema2.optional().describe("Embedded chart configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema3.optional().describe("Performance optimization settings") -}); -var Report = { - create: (config4) => ReportSchema2.parse(config4) -}; -var PageRegionSchema2 = external_exports.object({ - name: external_exports.string().describe('Region name (e.g. "sidebar", "main", "header")'), - width: external_exports.enum(["small", "medium", "large", "full"]).optional(), - components: external_exports.array(external_exports.lazy(() => PageComponentSchema2)).describe("Components in this region") -}); -var PageComponentType2 = external_exports.enum([ - // Structure - "page:header", - "page:footer", - "page:sidebar", - "page:tabs", - "page:accordion", - "page:card", - "page:section", - // Record Context - "record:details", - "record:highlights", - "record:related_list", - "record:activity", - "record:chatter", - "record:path", - // Navigation - "app:launcher", - "nav:menu", - "nav:breadcrumb", - // Utility - "global:search", - "global:notifications", - "user:profile", - // AI - "ai:chat_window", - "ai:suggestion", - // Content Elements (Airtable Interface parity) - "element:text", - "element:number", - "element:image", - "element:divider", - // Interactive Elements (Phase B — Element Library) - "element:button", - "element:filter", - "element:form", - "element:record_picker" -]); -var ElementDataSourceSchema2 = external_exports.object({ - object: external_exports.string().describe("Object to query"), - view: external_exports.string().optional().describe("Named view to apply"), - filter: FilterConditionSchema4.optional().describe("Additional filter criteria"), - sort: external_exports.array(SortItemSchema3).optional().describe("Sort order"), - limit: external_exports.number().int().positive().optional().describe("Max records to display") -}); -var PageComponentSchema2 = external_exports.object({ - /** Definition */ - type: external_exports.union([ - PageComponentType2, - external_exports.string() - ]).describe("Component Type (Standard enum or custom string)"), - id: external_exports.string().optional().describe("Unique instance ID"), - /** Configuration */ - label: I18nLabelSchema5.optional(), - properties: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Component props passed to the widget. See component.zod.ts for schemas."), - /** - * Event Handlers - * Map event names to Action expressions. - * "onClick": "set_variable('userId', $event.id)" - * "onRowSelect": "navigate_to('page_detail', { id: $event.id })" - */ - events: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Event handlers map"), - /** Appearance */ - style: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Inline styles or utility classes"), - className: external_exports.string().optional().describe("CSS class names"), - /** Visibility Rule */ - visibility: external_exports.string().optional().describe("Visibility filter/formula"), - /** Per-element data binding, overrides page-level object context */ - dataSource: ElementDataSourceSchema2.optional().describe("Per-element data binding for multi-object pages"), - /** Responsive layout overrides per breakpoint */ - responsive: ResponsiveConfigSchema3.optional().describe("Responsive layout configuration"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var PageVariableSchema2 = external_exports.object({ - name: external_exports.string().describe("Variable name"), - type: external_exports.enum(["string", "number", "boolean", "object", "array", "record_id"]).default("string"), - defaultValue: external_exports.unknown().optional(), - /** Source element binding (e.g. element:record_picker writes to this variable) */ - source: external_exports.string().optional().describe("Component ID that writes to this variable") -}); -var BlankPageLayoutItemSchema2 = external_exports.object({ - componentId: external_exports.string().describe("Reference to a PageComponent.id in the page"), - x: external_exports.number().int().min(0).describe("Grid column position (0-based)"), - y: external_exports.number().int().min(0).describe("Grid row position (0-based)"), - width: external_exports.number().int().min(1).describe("Width in grid columns"), - height: external_exports.number().int().min(1).describe("Height in grid rows") -}); -var BlankPageLayoutSchema2 = external_exports.object({ - columns: external_exports.number().int().min(1).default(12).describe("Number of grid columns"), - rowHeight: external_exports.number().int().min(1).default(40).describe("Height of each grid row in pixels"), - gap: external_exports.number().int().min(0).default(8).describe("Gap between grid items in pixels"), - items: external_exports.array(BlankPageLayoutItemSchema2).describe("Positioned components on the canvas") -}); -var PageTypeSchema2 = external_exports.enum([ - // Platform page types (Salesforce FlexiPage style) - "record", - // Component-based record layout page with regions - "home", - // Platform-level home/landing page - "app", - // App-level page with navigation context - "utility", - // Floating utility panel (e.g. notes, phone dialer) - // Interface page types (Airtable Interface parity) - "dashboard", - // KPI summary with charts/metrics - "grid", - // Spreadsheet-like data table - "list", - // Record list with quick actions - "gallery", - // Card-based visual browsing - "kanban", - // Status-based board - "calendar", - // Date-based scheduling - "timeline", - // Gantt-like project timeline - "form", - // Data entry form - "record_detail", - // Auto-generated single record field display - "record_review", - // Sequential record review/approval - "overview", - // Interface-level navigation/landing hub - "blank" - // Free-form canvas for custom composition -]).describe("Page type \u2014 platform or interface page types"); -var RecordReviewConfigSchema2 = external_exports.object({ - object: external_exports.string().describe("Target object for review"), - filter: FilterConditionSchema4.optional().describe("Filter criteria for review queue"), - sort: external_exports.array(SortItemSchema3).optional().describe("Sort order for review queue"), - displayFields: external_exports.array(external_exports.string()).optional().describe("Fields to display on the review page"), - actions: external_exports.array(external_exports.object({ - label: external_exports.string().describe("Action button label"), - type: external_exports.enum(["approve", "reject", "skip", "custom"]).describe("Action type"), - field: external_exports.string().optional().describe("Field to update on action"), - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Value to set on action"), - nextRecord: external_exports.boolean().optional().default(true).describe("Auto-advance to next record after action") - })).describe("Review actions"), - navigation: external_exports.enum(["sequential", "random", "filtered"]).optional().default("sequential").describe("Record navigation mode"), - showProgress: external_exports.boolean().optional().default(true).describe("Show review progress indicator") -}); -var InterfacePageConfigSchema2 = external_exports.object({ - /** Data binding */ - source: external_exports.string().optional().describe("Source object name for the page"), - levels: external_exports.number().int().min(1).optional().describe("Number of hierarchy levels to display"), - filterBy: external_exports.array(ViewFilterRuleSchema3).optional().describe("Page-level filter criteria"), - /** Appearance */ - appearance: AppearanceConfigSchema3.optional().describe("Appearance and visualization configuration"), - /** User filters */ - userFilters: external_exports.object({ - elements: external_exports.array(external_exports.enum(["grid", "gallery", "kanban"])).optional().describe("Visualization element types available in user filter bar"), - tabs: external_exports.array(ViewTabSchema3).optional().describe("User-configurable tabs") - }).optional().describe("User filter configuration"), - /** User actions */ - userActions: UserActionsConfigSchema3.optional().describe("User action toggles"), - /** Add record */ - addRecord: AddRecordConfigSchema3.optional().describe("Add record entry point configuration"), - /** Record count */ - showRecordCount: external_exports.boolean().optional().describe("Show record count at page bottom"), - /** Advanced */ - allowPrinting: external_exports.boolean().optional().describe("Allow users to print the page") -}).describe("Interface-level page configuration (Airtable parity)"); -var PageSchema2 = external_exports.object({ - name: SnakeCaseIdentifierSchema7.describe("Page unique name (lowercase snake_case)"), - label: I18nLabelSchema5, - description: I18nLabelSchema5.optional(), - /** Icon (used in interface navigation) */ - icon: external_exports.string().optional().describe("Page icon name"), - /** Page Type */ - type: PageTypeSchema2.default("record").describe("Page type"), - /** Page State Definitions */ - variables: external_exports.array(PageVariableSchema2).optional().describe("Local page state variables"), - /** Context */ - object: external_exports.string().optional().describe("Bound object (for Record pages)"), - /** Record Review Configuration (only for record_review pages) */ - recordReview: RecordReviewConfigSchema2.optional().describe('Record review configuration (required when type is "record_review")'), - /** Blank Page Layout (only for blank pages) */ - blankLayout: BlankPageLayoutSchema2.optional().describe('Free-form grid layout for blank pages (used when type is "blank")'), - /** Layout Template */ - template: external_exports.string().default("default").describe('Layout template name (e.g. "header-sidebar-main")'), - /** Regions & Content */ - regions: external_exports.array(PageRegionSchema2).describe("Defined regions with components"), - /** Activation */ - isDefault: external_exports.boolean().default(false), - assignedProfiles: external_exports.array(external_exports.string()).optional(), - /** Interface Page Configuration (Airtable Interface parity) */ - interfaceConfig: InterfacePageConfigSchema2.optional().describe("Interface-level page configuration (for Airtable-style interface pages)"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}).superRefine((data, ctx) => { - if (data.type === "record_review" && !data.recordReview) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - path: ["recordReview"], - message: 'recordReview is required when type is "record_review"' - }); - } - if (data.type === "blank" && !data.blankLayout) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - path: ["blankLayout"], - message: 'blankLayout is required when type is "blank"' - }); - } -}); -var WidgetLifecycleSchema2 = external_exports.object({ - /** - * Called when widget is mounted/rendered for the first time - * Use for initialization, setting up event listeners, loading data, etc. - * - * @example "initializeDatePicker(); loadOptions();" - */ - onMount: external_exports.string().optional().describe("Initialization code when widget mounts"), - /** - * Called when widget props change - * Receives previous props for comparison - * - * @example "if (prevProps.value !== props.value) { updateDisplay() }" - */ - onUpdate: external_exports.string().optional().describe("Code to run when props change"), - /** - * Called when widget is about to be removed from DOM - * Use for cleanup, removing event listeners, canceling timers, etc. - * - * @example "destroyDatePicker(); cancelPendingRequests();" - */ - onUnmount: external_exports.string().optional().describe("Cleanup code when widget unmounts"), - /** - * Custom validation logic for this widget - * Should return error message string if invalid, null/undefined if valid - * - * @example "return value && value.length >= 10 ? null : 'Minimum 10 characters'" - */ - onValidate: external_exports.string().optional().describe("Custom validation logic"), - /** - * Called when widget receives focus - * - * @example "highlightField(); logFocusEvent();" - */ - onFocus: external_exports.string().optional().describe("Code to run on focus"), - /** - * Called when widget loses focus - * - * @example "validateField(); saveFieldState();" - */ - onBlur: external_exports.string().optional().describe("Code to run on blur"), - /** - * Called on any error in the widget - * - * @example "logError(error); showErrorNotification();" - */ - onError: external_exports.string().optional().describe("Error handling code") -}); -var WidgetEventSchema2 = external_exports.object({ - /** - * Event name - * Should be lowercase, dash-separated for consistency - * - * @example "value-change", "item-selected", "search-complete" - */ - name: external_exports.string().describe("Event name"), - /** - * Event label for documentation - */ - label: I18nLabelSchema5.optional().describe("Human-readable event label"), - /** - * Event description - */ - description: I18nLabelSchema5.optional().describe("Event description and usage"), - /** - * Whether event bubbles up through the DOM hierarchy - * - * @default false - */ - bubbles: external_exports.boolean().default(false).describe("Whether event bubbles"), - /** - * Whether event can be cancelled - * - * @default false - */ - cancelable: external_exports.boolean().default(false).describe("Whether event is cancelable"), - /** - * Event payload schema - * Defines the data structure sent with the event - * - * @example { userId: 'string', timestamp: 'number' } - */ - payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event payload schema") -}); -var WidgetPropertySchema2 = external_exports.object({ - /** - * Property name - * Should be camelCase following ObjectStack conventions - */ - name: external_exports.string().describe("Property name (camelCase)"), - /** - * Property label for UI - */ - label: I18nLabelSchema5.optional().describe("Human-readable label"), - /** - * Property data type - * - * @example "string", "number", "boolean", "array", "object", "function" - */ - type: external_exports.enum(["string", "number", "boolean", "array", "object", "function", "any"]).describe("TypeScript type"), - /** - * Whether property is required - * - * @default false - */ - required: external_exports.boolean().default(false).describe("Whether property is required"), - /** - * Default value for the property - */ - default: external_exports.unknown().optional().describe("Default value"), - /** - * Property description - */ - description: I18nLabelSchema5.optional().describe("Property description"), - /** - * Property validation schema - * Can include min/max, regex, enum values, etc. - */ - validation: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation rules"), - /** - * Property category for grouping in UI - */ - category: external_exports.string().optional().describe("Property category") -}); -var WidgetSourceSchema2 = external_exports.discriminatedUnion("type", [ - // NPM Registry (standard) - external_exports.object({ - type: external_exports.literal("npm"), - packageName: external_exports.string().describe("NPM package name"), - version: external_exports.string().default("latest"), - exportName: external_exports.string().optional().describe("Named export (default: default)") - }), - // Module Federation (Remote) - external_exports.object({ - type: external_exports.literal("remote"), - url: external_exports.string().url().describe("Remote entry URL (.js)"), - moduleName: external_exports.string().describe("Exposed module name"), - scope: external_exports.string().describe("Remote scope name") - }), - // Inline Code (Simple scripts) - external_exports.object({ - type: external_exports.literal("inline"), - code: external_exports.string().describe("JavaScript code body") - }) -]); -var WidgetManifestSchema2 = external_exports.object({ - /** - * Widget identifier (snake_case) - */ - name: SnakeCaseIdentifierSchema7.describe("Widget identifier (snake_case)"), - /** - * Human-readable widget name - */ - label: I18nLabelSchema5.describe("Widget display name"), - /** - * Widget description - */ - description: I18nLabelSchema5.optional().describe("Widget description"), - /** - * Widget version (semver) - */ - version: external_exports.string().optional().describe("Widget version (semver)"), - /** - * Widget author/organization - */ - author: external_exports.string().optional().describe("Widget author"), - /** - * Icon name or URL - */ - icon: external_exports.string().optional().describe("Widget icon"), - /** - * Field types this widget supports - * - * @example ["text", "email", "url"] - */ - fieldTypes: external_exports.array(external_exports.string()).optional().describe("Supported field types"), - /** - * Widget category for organization - */ - category: external_exports.enum(["input", "display", "picker", "editor", "custom"]).default("custom").describe("Widget category"), - /** - * Widget lifecycle hooks - */ - lifecycle: WidgetLifecycleSchema2.optional().describe("Lifecycle hooks"), - /** - * Custom events this widget emits - */ - events: external_exports.array(WidgetEventSchema2).optional().describe("Custom events"), - /** - * Widget configuration properties - */ - properties: external_exports.array(WidgetPropertySchema2).optional().describe("Configuration properties"), - /** - * Widget implementation - * Defines how to load the widget code - */ - implementation: WidgetSourceSchema2.optional().describe("Widget implementation source"), - /** - * Widget dependencies - * External libraries or scripts needed - */ - dependencies: external_exports.array(external_exports.object({ - name: external_exports.string(), - version: external_exports.string().optional(), - url: external_exports.string().url().optional() - })).optional().describe("Widget dependencies"), - /** - * Widget screenshots for showcase - */ - screenshots: external_exports.array(external_exports.string().url()).optional().describe("Screenshot URLs"), - /** - * Widget documentation URL - */ - documentation: external_exports.string().url().optional().describe("Documentation URL"), - /** - * License information - */ - license: external_exports.string().optional().describe("License (SPDX identifier)"), - /** - * Tags for discovery - */ - tags: external_exports.array(external_exports.string()).optional().describe("Tags for categorization"), - /** ARIA accessibility attributes */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes"), - /** Performance optimization settings */ - performance: PerformanceConfigSchema3.optional().describe("Performance optimization settings") -}); -var FieldWidgetPropsSchema2 = external_exports.object({ - /** - * Current field value. - * Type depends on the field type (string, number, boolean, array, object, etc.) - */ - value: external_exports.unknown().describe("Current field value"), - /** - * Callback function to update the field value. - * Should be called when user interaction changes the value. - * - * @param newValue - The new value to set - */ - onChange: external_exports.function().input(external_exports.tuple([external_exports.unknown()])).output(external_exports.void()).describe("Callback to update field value"), - /** - * Whether the field is in read-only mode. - * When true, the widget should display the value but not allow editing. - */ - readonly: external_exports.boolean().default(false).describe("Read-only mode flag"), - /** - * Whether the field is required. - * Widget should indicate required state visually and validate accordingly. - */ - required: external_exports.boolean().default(false).describe("Required field flag"), - /** - * Validation error message to display. - * When present, widget should display the error in its UI. - */ - error: external_exports.string().optional().describe("Validation error message"), - /** - * Complete field definition from the schema. - * Contains metadata like type, constraints, options, etc. - */ - field: FieldSchema5.describe("Field schema definition"), - /** - * The complete record/document being edited. - * Useful for conditional logic and cross-field dependencies. - */ - record: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Complete record data"), - /** - * Custom options passed to the widget. - * Can contain widget-specific configuration like themes, behaviors, etc. - */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom widget options") -}); -var EmptyProps2 = external_exports.object({}); -var PageHeaderProps2 = external_exports.object({ - title: I18nLabelSchema5.describe("Page title"), - subtitle: I18nLabelSchema5.optional().describe("Page subtitle"), - icon: external_exports.string().optional().describe("Icon name"), - breadcrumb: external_exports.boolean().default(true).describe("Show breadcrumb"), - actions: external_exports.array(external_exports.string()).optional().describe("Action IDs to show in header"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var PageTabsProps2 = external_exports.object({ - type: external_exports.enum(["line", "card", "pill"]).default("line"), - position: external_exports.enum(["top", "left"]).default("top"), - items: external_exports.array(external_exports.object({ - label: I18nLabelSchema5, - icon: external_exports.string().optional(), - children: external_exports.array(external_exports.unknown()).describe("Child components") - })), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var PageCardProps2 = external_exports.object({ - title: I18nLabelSchema5.optional(), - bordered: external_exports.boolean().default(true), - actions: external_exports.array(external_exports.string()).optional(), - /** Slot for nested content in the Card body */ - body: external_exports.array(external_exports.unknown()).optional().describe("Card content components (slot)"), - /** Slot for footer content */ - footer: external_exports.array(external_exports.unknown()).optional().describe("Card footer components (slot)"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var RecordDetailsProps2 = external_exports.object({ - columns: external_exports.enum(["1", "2", "3", "4"]).default("2").describe("Number of columns for field layout (1-4)"), - layout: external_exports.enum(["auto", "custom"]).default("auto").describe("Layout mode: auto uses object compactLayout, custom uses explicit sections"), - sections: external_exports.array(external_exports.string()).optional().describe('Section IDs to show (required when layout is "custom")'), - fields: external_exports.array(external_exports.string()).optional().describe("Explicit field list to display (optional, overrides compactLayout)"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var RecordRelatedListProps2 = external_exports.object({ - objectName: external_exports.string().describe('Related object name (e.g., "task", "opportunity")'), - relationshipField: external_exports.string().describe('Field on related object that points to this record (e.g., "account_id")'), - columns: external_exports.array(external_exports.string()).describe("Fields to display in the related list"), - sort: external_exports.union([ - external_exports.string(), - external_exports.array(external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]) - })) - ]).optional().describe("Sort order for related records"), - limit: external_exports.number().int().positive().default(5).describe("Number of records to display initially"), - filter: external_exports.array(ViewFilterRuleSchema3).optional().describe("Additional filter criteria for related records"), - title: I18nLabelSchema5.optional().describe("Custom title for the related list"), - showViewAll: external_exports.boolean().default(true).describe('Show "View All" link to see all related records'), - actions: external_exports.array(external_exports.string()).optional().describe("Action IDs available for related records"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var RecordHighlightsProps2 = external_exports.object({ - fields: external_exports.array(external_exports.string()).min(1).max(7).describe("Key fields to highlight (1-7 fields max, typically displayed as prominent cards)"), - layout: external_exports.enum(["horizontal", "vertical"]).default("horizontal").describe("Layout orientation for highlight fields"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var RecordActivityProps2 = external_exports.object({ - /** Activity types to display (unified enum including comment, field_change, etc.) */ - types: external_exports.array(FeedItemType4).optional().describe("Feed item types to show (default: all)"), - /** Default filter mode (Airtable-style dropdown) */ - filterMode: FeedFilterMode3.default("all").describe("Default activity filter"), - /** Allow user to switch filter modes */ - showFilterToggle: external_exports.boolean().default(true).describe("Show filter dropdown in panel header"), - /** Pagination */ - limit: external_exports.number().int().positive().default(20).describe("Number of items to load per page"), - /** Show completed activities */ - showCompleted: external_exports.boolean().default(false).describe("Include completed activities"), - /** Merge field_change + comment in a unified timeline */ - unifiedTimeline: external_exports.boolean().default(true).describe("Mix field changes and comments in one timeline (Airtable style)"), - /** Show the comment input box at the bottom */ - showCommentInput: external_exports.boolean().default(true).describe('Show "Leave a comment" input at the bottom'), - /** Enable @mentions in comments */ - enableMentions: external_exports.boolean().default(true).describe("Enable @mentions in comments"), - /** Enable emoji reactions */ - enableReactions: external_exports.boolean().default(false).describe("Enable emoji reactions on feed items"), - /** Enable threaded replies */ - enableThreading: external_exports.boolean().default(false).describe("Enable threaded replies on comments"), - /** Show notification subscription toggle (bell icon) */ - showSubscriptionToggle: external_exports.boolean().default(true).describe("Show bell icon for record-level notification subscription"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var RecordChatterProps2 = external_exports.object({ - /** Panel position */ - position: external_exports.enum(["sidebar", "inline", "drawer"]).default("sidebar").describe("Where to render the chatter panel"), - /** Panel width (for sidebar/drawer) */ - width: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('Panel width (e.g., "350px", "30%")'), - /** Collapsible */ - collapsible: external_exports.boolean().default(true).describe("Whether the panel can be collapsed"), - /** Default collapsed state */ - defaultCollapsed: external_exports.boolean().default(false).describe("Whether the panel starts collapsed"), - /** Feed configuration (delegates to RecordActivityProps) */ - feed: RecordActivityProps2.optional().describe("Embedded activity feed configuration"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var RecordPathProps2 = external_exports.object({ - statusField: external_exports.string().describe("Field name representing the current status/stage"), - stages: external_exports.array(external_exports.object({ - value: external_exports.string(), - label: I18nLabelSchema5 - })).optional().describe("Explicit stage definitions (if not using field metadata)"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var PageAccordionProps2 = external_exports.object({ - items: external_exports.array(external_exports.object({ - label: I18nLabelSchema5, - icon: external_exports.string().optional(), - collapsed: external_exports.boolean().default(false), - children: external_exports.array(external_exports.unknown()).describe("Child components") - })), - allowMultiple: external_exports.boolean().default(false).describe("Allow multiple panels to be expanded simultaneously"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var AIChatWindowProps2 = external_exports.object({ - mode: external_exports.enum(["float", "sidebar", "inline"]).default("float").describe("Display mode for the chat window"), - agentId: external_exports.string().optional().describe("Specific AI agent to use"), - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Contextual data to pass to the AI"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var ElementTextPropsSchema2 = external_exports.object({ - content: external_exports.string().describe("Text or Markdown content"), - variant: external_exports.enum(["heading", "subheading", "body", "caption"]).optional().default("body").describe("Text style variant"), - align: external_exports.enum(["left", "center", "right"]).optional().default("left").describe("Text alignment"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var ElementNumberPropsSchema2 = external_exports.object({ - object: external_exports.string().describe("Source object"), - field: external_exports.string().optional().describe("Field to aggregate"), - aggregate: external_exports.enum(["count", "sum", "avg", "min", "max"]).describe("Aggregation function"), - filter: FilterConditionSchema4.optional().describe("Filter criteria"), - format: external_exports.enum(["number", "currency", "percent"]).optional().describe("Number display format"), - prefix: external_exports.string().optional().describe('Prefix text (e.g. "$")'), - suffix: external_exports.string().optional().describe('Suffix text (e.g. "%")'), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var ElementImagePropsSchema2 = external_exports.object({ - src: external_exports.string().describe("Image URL or attachment field"), - alt: external_exports.string().optional().describe("Alt text for accessibility"), - fit: external_exports.enum(["cover", "contain", "fill"]).optional().default("cover").describe("Image object-fit mode"), - height: external_exports.number().optional().describe("Fixed height in pixels"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var ElementButtonPropsSchema2 = external_exports.object({ - label: I18nLabelSchema5.describe("Button display label"), - variant: external_exports.enum(["primary", "secondary", "danger", "ghost", "link"]).optional().default("primary").describe("Button visual variant"), - size: external_exports.enum(["small", "medium", "large"]).optional().default("medium").describe("Button size"), - icon: external_exports.string().optional().describe("Icon name (Lucide icon)"), - iconPosition: external_exports.enum(["left", "right"]).optional().default("left").describe("Icon position relative to label"), - disabled: external_exports.boolean().optional().default(false).describe("Disable the button"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var ElementFilterPropsSchema2 = external_exports.object({ - object: external_exports.string().describe("Object to filter"), - fields: external_exports.array(external_exports.string()).describe("Filterable field names"), - targetVariable: external_exports.string().optional().describe("Page variable to store filter state"), - layout: external_exports.enum(["inline", "dropdown", "sidebar"]).optional().default("inline").describe("Filter display layout"), - showSearch: external_exports.boolean().optional().default(true).describe("Show search input"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var ElementFormPropsSchema2 = external_exports.object({ - object: external_exports.string().describe("Object for the form"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to display (defaults to all editable fields)"), - mode: external_exports.enum(["create", "edit"]).optional().default("create").describe("Form mode"), - submitLabel: I18nLabelSchema5.optional().describe("Submit button label"), - onSubmit: external_exports.string().optional().describe("Action expression on form submit"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var ElementRecordPickerPropsSchema2 = external_exports.object({ - object: external_exports.string().describe("Object to pick records from"), - displayField: external_exports.string().describe("Field to display as the record label"), - searchFields: external_exports.array(external_exports.string()).optional().describe("Fields to search against"), - filter: FilterConditionSchema4.optional().describe("Filter criteria for available records"), - multiple: external_exports.boolean().optional().default(false).describe("Allow multiple record selection"), - targetVariable: external_exports.string().optional().describe("Page variable to bind selected record ID(s)"), - placeholder: I18nLabelSchema5.optional().describe("Placeholder text"), - /** ARIA accessibility */ - aria: AriaPropsSchema5.optional().describe("ARIA accessibility attributes") -}); -var ComponentPropsMap2 = { - // Structure - "page:header": PageHeaderProps2, - "page:tabs": PageTabsProps2, - "page:card": PageCardProps2, - "page:footer": EmptyProps2, - "page:sidebar": EmptyProps2, - "page:accordion": PageAccordionProps2, - "page:section": EmptyProps2, - // Record - "record:details": RecordDetailsProps2, - "record:related_list": RecordRelatedListProps2, - "record:highlights": RecordHighlightsProps2, - "record:activity": RecordActivityProps2, - "record:chatter": RecordChatterProps2, - "record:path": RecordPathProps2, - // Navigation - "app:launcher": EmptyProps2, - "nav:menu": EmptyProps2, - "nav:breadcrumb": EmptyProps2, - // Utility - "global:search": EmptyProps2, - "global:notifications": EmptyProps2, - "user:profile": EmptyProps2, - // AI - "ai:chat_window": AIChatWindowProps2, - "ai:suggestion": external_exports.object({ context: external_exports.string().optional() }), - // Content Elements - "element:text": ElementTextPropsSchema2, - "element:number": ElementNumberPropsSchema2, - "element:image": ElementImagePropsSchema2, - "element:divider": EmptyProps2, - // Interactive Elements - "element:button": ElementButtonPropsSchema2, - "element:filter": ElementFilterPropsSchema2, - "element:form": ElementFormPropsSchema2, - "element:record_picker": ElementRecordPickerPropsSchema2 -}; -var TouchTargetConfigSchema2 = external_exports.object({ - minWidth: external_exports.number().default(44).describe("Minimum touch target width in pixels (WCAG 2.5.5: 44px)"), - minHeight: external_exports.number().default(44).describe("Minimum touch target height in pixels (WCAG 2.5.5: 44px)"), - padding: external_exports.number().optional().describe("Additional padding around touch target in pixels"), - hitSlop: external_exports.object({ - top: external_exports.number().optional().describe("Extra hit area above the element"), - right: external_exports.number().optional().describe("Extra hit area to the right of the element"), - bottom: external_exports.number().optional().describe("Extra hit area below the element"), - left: external_exports.number().optional().describe("Extra hit area to the left of the element") - }).optional().describe("Invisible hit area extension beyond the visible bounds") -}).describe("Touch target sizing configuration (WCAG accessible)"); -var GestureTypeSchema2 = external_exports.enum([ - "swipe", - "pinch", - "long_press", - "double_tap", - "drag", - "rotate", - "pan" -]).describe("Touch gesture type"); -var SwipeDirectionSchema2 = external_exports.enum(["up", "down", "left", "right"]); -var SwipeGestureConfigSchema2 = external_exports.object({ - direction: external_exports.array(SwipeDirectionSchema2).describe("Allowed swipe directions"), - threshold: external_exports.number().optional().describe("Minimum distance in pixels to recognize swipe"), - velocity: external_exports.number().optional().describe("Minimum velocity (px/ms) to trigger swipe") -}).describe("Swipe gesture recognition settings"); -var PinchGestureConfigSchema2 = external_exports.object({ - minScale: external_exports.number().optional().describe("Minimum scale factor (e.g., 0.5 for 50%)"), - maxScale: external_exports.number().optional().describe("Maximum scale factor (e.g., 3.0 for 300%)") -}).describe("Pinch/zoom gesture recognition settings"); -var LongPressGestureConfigSchema2 = external_exports.object({ - duration: external_exports.number().default(500).describe("Hold duration in milliseconds to trigger long press"), - moveTolerance: external_exports.number().optional().describe("Max movement in pixels allowed during press") -}).describe("Long press gesture recognition settings"); -var GestureConfigSchema2 = external_exports.object({ - type: GestureTypeSchema2.describe("Gesture type to configure"), - label: I18nLabelSchema5.optional().describe("Descriptive label for the gesture action"), - enabled: external_exports.boolean().default(true).describe("Whether this gesture is active"), - swipe: SwipeGestureConfigSchema2.optional().describe("Swipe gesture settings (when type is swipe)"), - pinch: PinchGestureConfigSchema2.optional().describe("Pinch gesture settings (when type is pinch)"), - longPress: LongPressGestureConfigSchema2.optional().describe("Long press settings (when type is long_press)") -}).describe("Per-gesture configuration"); -var TouchInteractionSchema2 = external_exports.object({ - gestures: external_exports.array(GestureConfigSchema2).optional().describe("Configured gesture recognizers"), - touchTarget: TouchTargetConfigSchema2.optional().describe("Touch target sizing and hit area"), - hapticFeedback: external_exports.boolean().optional().describe("Enable haptic feedback on touch interactions") -}).merge(AriaPropsSchema5.partial()).describe("Touch and gesture interaction configuration"); -var FocusTrapConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable focus trapping within this container"), - initialFocus: external_exports.string().optional().describe("CSS selector for the element to focus on activation"), - returnFocus: external_exports.boolean().default(true).describe("Return focus to trigger element on deactivation"), - escapeDeactivates: external_exports.boolean().default(true).describe("Allow Escape key to deactivate the focus trap") -}).describe("Focus trap configuration for modal-like containers"); -var KeyboardShortcutSchema2 = external_exports.object({ - key: external_exports.string().describe('Key combination (e.g., "Ctrl+S", "Alt+N", "Escape")'), - action: external_exports.string().describe("Action identifier to invoke when shortcut is triggered"), - description: I18nLabelSchema5.optional().describe("Human-readable description of what the shortcut does"), - scope: external_exports.enum(["global", "view", "form", "modal", "list"]).default("global").describe("Scope in which this shortcut is active") -}).describe("Keyboard shortcut binding"); -var FocusManagementSchema2 = external_exports.object({ - tabOrder: external_exports.enum(["auto", "manual"]).default("auto").describe("Tab order strategy: auto (DOM order) or manual (explicit tabIndex)"), - skipLinks: external_exports.boolean().default(false).describe("Provide skip-to-content navigation links"), - focusVisible: external_exports.boolean().default(true).describe("Show visible focus indicators for keyboard users"), - focusTrap: FocusTrapConfigSchema2.optional().describe("Focus trap settings"), - arrowNavigation: external_exports.boolean().default(false).describe("Enable arrow key navigation between focusable items") -}).describe("Focus and tab navigation management"); -var KeyboardNavigationConfigSchema2 = external_exports.object({ - shortcuts: external_exports.array(KeyboardShortcutSchema2).optional().describe("Registered keyboard shortcuts"), - focusManagement: FocusManagementSchema2.optional().describe("Focus and tab order management"), - rovingTabindex: external_exports.boolean().default(false).describe("Enable roving tabindex pattern for composite widgets") -}).merge(AriaPropsSchema5.partial()).describe("Keyboard navigation and shortcut configuration"); -var ColorPaletteSchema2 = external_exports.object({ - primary: external_exports.string().describe("Primary brand color (hex, rgb, or hsl)"), - secondary: external_exports.string().optional().describe("Secondary brand color"), - accent: external_exports.string().optional().describe("Accent color for highlights"), - success: external_exports.string().optional().describe("Success state color (default: green)"), - warning: external_exports.string().optional().describe("Warning state color (default: yellow)"), - error: external_exports.string().optional().describe("Error state color (default: red)"), - info: external_exports.string().optional().describe("Info state color (default: blue)"), - // Neutral colors - background: external_exports.string().optional().describe("Background color"), - surface: external_exports.string().optional().describe("Surface/card background color"), - text: external_exports.string().optional().describe("Primary text color"), - textSecondary: external_exports.string().optional().describe("Secondary text color"), - border: external_exports.string().optional().describe("Border color"), - disabled: external_exports.string().optional().describe("Disabled state color"), - // Color variants (shades) - primaryLight: external_exports.string().optional().describe("Lighter shade of primary"), - primaryDark: external_exports.string().optional().describe("Darker shade of primary"), - secondaryLight: external_exports.string().optional().describe("Lighter shade of secondary"), - secondaryDark: external_exports.string().optional().describe("Darker shade of secondary") -}); -var TypographySchema2 = external_exports.object({ - fontFamily: external_exports.object({ - base: external_exports.string().optional().describe("Base font family (default: system fonts)"), - heading: external_exports.string().optional().describe("Heading font family"), - mono: external_exports.string().optional().describe("Monospace font family for code") - }).optional(), - fontSize: external_exports.object({ - xs: external_exports.string().optional().describe("Extra small font size (e.g., 0.75rem)"), - sm: external_exports.string().optional().describe("Small font size (e.g., 0.875rem)"), - base: external_exports.string().optional().describe("Base font size (e.g., 1rem)"), - lg: external_exports.string().optional().describe("Large font size (e.g., 1.125rem)"), - xl: external_exports.string().optional().describe("Extra large font size (e.g., 1.25rem)"), - "2xl": external_exports.string().optional().describe("2X large font size (e.g., 1.5rem)"), - "3xl": external_exports.string().optional().describe("3X large font size (e.g., 1.875rem)"), - "4xl": external_exports.string().optional().describe("4X large font size (e.g., 2.25rem)") - }).optional(), - fontWeight: external_exports.object({ - light: external_exports.number().optional().describe("Light weight (default: 300)"), - normal: external_exports.number().optional().describe("Normal weight (default: 400)"), - medium: external_exports.number().optional().describe("Medium weight (default: 500)"), - semibold: external_exports.number().optional().describe("Semibold weight (default: 600)"), - bold: external_exports.number().optional().describe("Bold weight (default: 700)") - }).optional(), - lineHeight: external_exports.object({ - tight: external_exports.string().optional().describe("Tight line height (e.g., 1.25)"), - normal: external_exports.string().optional().describe("Normal line height (e.g., 1.5)"), - relaxed: external_exports.string().optional().describe("Relaxed line height (e.g., 1.75)"), - loose: external_exports.string().optional().describe("Loose line height (e.g., 2)") - }).optional(), - letterSpacing: external_exports.object({ - tighter: external_exports.string().optional().describe("Tighter letter spacing (e.g., -0.05em)"), - tight: external_exports.string().optional().describe("Tight letter spacing (e.g., -0.025em)"), - normal: external_exports.string().optional().describe("Normal letter spacing (e.g., 0)"), - wide: external_exports.string().optional().describe("Wide letter spacing (e.g., 0.025em)"), - wider: external_exports.string().optional().describe("Wider letter spacing (e.g., 0.05em)") - }).optional() -}); -var SpacingSchema2 = external_exports.object({ - "0": external_exports.string().optional().describe("0 spacing (0)"), - "1": external_exports.string().optional().describe("Spacing unit 1 (e.g., 0.25rem)"), - "2": external_exports.string().optional().describe("Spacing unit 2 (e.g., 0.5rem)"), - "3": external_exports.string().optional().describe("Spacing unit 3 (e.g., 0.75rem)"), - "4": external_exports.string().optional().describe("Spacing unit 4 (e.g., 1rem)"), - "5": external_exports.string().optional().describe("Spacing unit 5 (e.g., 1.25rem)"), - "6": external_exports.string().optional().describe("Spacing unit 6 (e.g., 1.5rem)"), - "8": external_exports.string().optional().describe("Spacing unit 8 (e.g., 2rem)"), - "10": external_exports.string().optional().describe("Spacing unit 10 (e.g., 2.5rem)"), - "12": external_exports.string().optional().describe("Spacing unit 12 (e.g., 3rem)"), - "16": external_exports.string().optional().describe("Spacing unit 16 (e.g., 4rem)"), - "20": external_exports.string().optional().describe("Spacing unit 20 (e.g., 5rem)"), - "24": external_exports.string().optional().describe("Spacing unit 24 (e.g., 6rem)") -}); -var BorderRadiusSchema2 = external_exports.object({ - none: external_exports.string().optional().describe("No border radius (0)"), - sm: external_exports.string().optional().describe("Small border radius (e.g., 0.125rem)"), - base: external_exports.string().optional().describe("Base border radius (e.g., 0.25rem)"), - md: external_exports.string().optional().describe("Medium border radius (e.g., 0.375rem)"), - lg: external_exports.string().optional().describe("Large border radius (e.g., 0.5rem)"), - xl: external_exports.string().optional().describe("Extra large border radius (e.g., 0.75rem)"), - "2xl": external_exports.string().optional().describe("2X large border radius (e.g., 1rem)"), - full: external_exports.string().optional().describe("Full border radius (50%)") -}); -var ShadowSchema2 = external_exports.object({ - none: external_exports.string().optional().describe("No shadow"), - sm: external_exports.string().optional().describe("Small shadow"), - base: external_exports.string().optional().describe("Base shadow"), - md: external_exports.string().optional().describe("Medium shadow"), - lg: external_exports.string().optional().describe("Large shadow"), - xl: external_exports.string().optional().describe("Extra large shadow"), - "2xl": external_exports.string().optional().describe("2X large shadow"), - inner: external_exports.string().optional().describe("Inner shadow (inset)") -}); -var BreakpointsSchema2 = external_exports.object({ - xs: external_exports.string().optional().describe("Extra small breakpoint (e.g., 480px)"), - sm: external_exports.string().optional().describe("Small breakpoint (e.g., 640px)"), - md: external_exports.string().optional().describe("Medium breakpoint (e.g., 768px)"), - lg: external_exports.string().optional().describe("Large breakpoint (e.g., 1024px)"), - xl: external_exports.string().optional().describe("Extra large breakpoint (e.g., 1280px)"), - "2xl": external_exports.string().optional().describe("2X large breakpoint (e.g., 1536px)") -}); -var AnimationSchema2 = external_exports.object({ - duration: external_exports.object({ - fast: external_exports.string().optional().describe("Fast animation (e.g., 150ms)"), - base: external_exports.string().optional().describe("Base animation (e.g., 300ms)"), - slow: external_exports.string().optional().describe("Slow animation (e.g., 500ms)") - }).optional(), - timing: external_exports.object({ - linear: external_exports.string().optional().describe("Linear timing function"), - ease: external_exports.string().optional().describe("Ease timing function"), - ease_in: external_exports.string().optional().describe("Ease-in timing function"), - ease_out: external_exports.string().optional().describe("Ease-out timing function"), - ease_in_out: external_exports.string().optional().describe("Ease-in-out timing function") - }).optional() -}); -var ZIndexSchema2 = external_exports.object({ - base: external_exports.number().optional().describe("Base z-index (e.g., 0)"), - dropdown: external_exports.number().optional().describe("Dropdown z-index (e.g., 1000)"), - sticky: external_exports.number().optional().describe("Sticky z-index (e.g., 1020)"), - fixed: external_exports.number().optional().describe("Fixed z-index (e.g., 1030)"), - modalBackdrop: external_exports.number().optional().describe("Modal backdrop z-index (e.g., 1040)"), - modal: external_exports.number().optional().describe("Modal z-index (e.g., 1050)"), - popover: external_exports.number().optional().describe("Popover z-index (e.g., 1060)"), - tooltip: external_exports.number().optional().describe("Tooltip z-index (e.g., 1070)") -}); -var ThemeModeSchema2 = external_exports.enum(["light", "dark", "auto"]); -var ThemeMode = ThemeModeSchema2; -var DensityModeSchema2 = external_exports.enum(["compact", "regular", "spacious"]); -var DensityMode = DensityModeSchema2; -var WcagContrastLevelSchema2 = external_exports.enum(["AA", "AAA"]); -var WcagContrastLevel = WcagContrastLevelSchema2; -var ThemeSchema2 = external_exports.object({ - name: SnakeCaseIdentifierSchema7.describe("Unique theme identifier (snake_case)"), - label: external_exports.string().describe("Human-readable theme name"), - description: external_exports.string().optional().describe("Theme description"), - /** Theme mode */ - mode: ThemeModeSchema2.default("light").describe("Theme mode (light, dark, or auto)"), - /** Color system */ - colors: ColorPaletteSchema2.describe("Color palette configuration"), - /** Typography */ - typography: TypographySchema2.optional().describe("Typography settings"), - /** Spacing */ - spacing: SpacingSchema2.optional().describe("Spacing scale"), - /** Border radius */ - borderRadius: BorderRadiusSchema2.optional().describe("Border radius scale"), - /** Shadows */ - shadows: ShadowSchema2.optional().describe("Box shadow effects"), - /** Breakpoints */ - breakpoints: BreakpointsSchema2.optional().describe("Responsive breakpoints"), - /** Animation */ - animation: AnimationSchema2.optional().describe("Animation settings"), - /** Z-Index */ - zIndex: ZIndexSchema2.optional().describe("Z-index scale for layering"), - /** Custom CSS variables */ - customVars: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom CSS variables (key-value pairs)"), - /** Logo */ - logo: external_exports.object({ - light: external_exports.string().optional().describe("Logo URL for light mode"), - dark: external_exports.string().optional().describe("Logo URL for dark mode"), - favicon: external_exports.string().optional().describe("Favicon URL") - }).optional().describe("Logo assets"), - /** Extends another theme */ - extends: external_exports.string().optional().describe("Base theme to extend from"), - /** Display density mode */ - density: DensityModeSchema2.optional().describe("Display density: compact, regular, or spacious"), - /** WCAG contrast level requirement */ - wcagContrast: WcagContrastLevelSchema2.optional().describe("WCAG color contrast level (AA or AAA)"), - /** Right-to-left language support */ - rtl: external_exports.boolean().optional().describe("Enable right-to-left layout direction"), - /** Touch target accessibility configuration */ - touchTarget: TouchTargetConfigSchema2.optional().describe("Touch target sizing defaults"), - /** Keyboard navigation and focus management */ - keyboardNavigation: FocusManagementSchema2.optional().describe("Keyboard focus management settings") -}); -var OfflineStrategySchema2 = external_exports.enum([ - "cache_first", - "network_first", - "stale_while_revalidate", - "network_only", - "cache_only" -]).describe("Data fetching strategy for offline/online transitions"); -var ConflictResolutionSchema2 = external_exports.enum([ - "client_wins", - "server_wins", - "manual", - "last_write_wins" -]).describe("How to resolve conflicts when syncing offline changes"); -var SyncConfigSchema2 = external_exports.object({ - strategy: OfflineStrategySchema2.default("network_first").describe("Sync fetch strategy"), - conflictResolution: ConflictResolutionSchema2.default("last_write_wins").describe("Conflict resolution policy"), - retryInterval: external_exports.number().optional().describe("Retry interval in milliseconds between sync attempts"), - maxRetries: external_exports.number().optional().describe("Maximum number of sync retry attempts"), - batchSize: external_exports.number().optional().describe("Number of mutations to sync per batch") -}).describe("Offline-to-online synchronization configuration"); -var PersistStorageSchema2 = external_exports.enum([ - "indexeddb", - "localstorage", - "sqlite" -]).describe("Client-side storage backend for offline cache"); -var EvictionPolicySchema2 = external_exports.enum([ - "lru", - "lfu", - "fifo" -]).describe("Cache eviction policy"); -var OfflineCacheConfigSchema2 = external_exports.object({ - maxSize: external_exports.number().optional().describe("Maximum cache size in bytes"), - ttl: external_exports.number().optional().describe("Time-to-live for cached entries in milliseconds"), - persistStorage: PersistStorageSchema2.default("indexeddb").describe("Storage backend"), - evictionPolicy: EvictionPolicySchema2.default("lru").describe("Cache eviction policy when full") -}).describe("Client-side offline cache configuration"); -var OfflineConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable offline support"), - strategy: OfflineStrategySchema2.default("network_first").describe("Default offline fetch strategy"), - cache: OfflineCacheConfigSchema2.optional().describe("Cache settings for offline data"), - sync: SyncConfigSchema2.optional().describe("Sync settings for offline mutations"), - offlineIndicator: external_exports.boolean().default(true).describe("Show a visual indicator when offline"), - offlineMessage: I18nLabelSchema5.optional().describe("Customizable offline status message shown to users"), - queueMaxSize: external_exports.number().optional().describe("Maximum number of queued offline mutations") -}).describe("Offline support configuration"); -var TransitionPresetSchema2 = external_exports.enum([ - "fade", - "slide_up", - "slide_down", - "slide_left", - "slide_right", - "scale", - "rotate", - "flip", - "none" -]).describe("Transition preset type"); -var EasingFunctionSchema2 = external_exports.enum([ - "linear", - "ease", - "ease_in", - "ease_out", - "ease_in_out", - "spring" -]).describe("Animation easing function"); -var TransitionConfigSchema2 = external_exports.object({ - preset: TransitionPresetSchema2.optional().describe("Transition preset to apply"), - duration: external_exports.number().optional().describe("Transition duration in milliseconds"), - easing: EasingFunctionSchema2.optional().describe("Easing function for the transition"), - delay: external_exports.number().optional().describe("Delay before transition starts in milliseconds"), - customKeyframes: external_exports.string().optional().describe("CSS @keyframes name for custom animations"), - themeToken: external_exports.string().optional().describe('Reference to a theme animation token (e.g. "animation.duration.fast")') -}).describe("Animation transition configuration"); -var AnimationTriggerSchema2 = external_exports.enum([ - "on_mount", - "on_unmount", - "on_hover", - "on_focus", - "on_click", - "on_scroll", - "on_visible" -]).describe("Event that triggers the animation"); -var ComponentAnimationSchema2 = external_exports.object({ - label: I18nLabelSchema5.optional().describe("Descriptive label for this animation configuration"), - enter: TransitionConfigSchema2.optional().describe("Enter/mount animation"), - exit: TransitionConfigSchema2.optional().describe("Exit/unmount animation"), - hover: TransitionConfigSchema2.optional().describe("Hover state animation"), - trigger: AnimationTriggerSchema2.optional().describe("When to trigger the animation"), - reducedMotion: external_exports.enum(["respect", "disable", "alternative"]).default("respect").describe("Accessibility: how to handle prefers-reduced-motion") -}).merge(AriaPropsSchema5.partial()).describe("Component-level animation configuration"); -var PageTransitionSchema2 = external_exports.object({ - type: TransitionPresetSchema2.default("fade").describe("Page transition type"), - duration: external_exports.number().default(300).describe("Transition duration in milliseconds"), - easing: EasingFunctionSchema2.default("ease_in_out").describe("Easing function for the transition"), - crossFade: external_exports.boolean().default(false).describe("Whether to cross-fade between pages") -}).describe("Page-level transition configuration"); -var MotionConfigSchema2 = external_exports.object({ - label: I18nLabelSchema5.optional().describe("Descriptive label for the motion configuration"), - defaultTransition: TransitionConfigSchema2.optional().describe("Default transition applied to all animations"), - pageTransitions: PageTransitionSchema2.optional().describe("Page navigation transition settings"), - componentAnimations: external_exports.record(external_exports.string(), ComponentAnimationSchema2).optional().describe("Component name to animation configuration mapping"), - reducedMotion: external_exports.boolean().default(false).describe("When true, respect prefers-reduced-motion and suppress animations globally"), - enabled: external_exports.boolean().default(true).describe("Enable or disable all animations globally") -}).describe("Top-level motion and animation design configuration"); -var NotificationTypeSchema2 = external_exports.enum([ - "toast", - "snackbar", - "banner", - "alert", - "inline" -]).describe("Notification presentation style"); -var NotificationSeveritySchema2 = external_exports.enum([ - "info", - "success", - "warning", - "error" -]).describe("Notification severity level"); -var NotificationPositionSchema2 = external_exports.enum([ - "top_left", - "top_center", - "top_right", - "bottom_left", - "bottom_center", - "bottom_right" -]).describe("Screen position for notification placement"); -var NotificationActionSchema2 = external_exports.object({ - label: I18nLabelSchema5.describe("Action button label"), - action: external_exports.string().describe("Action identifier to execute"), - variant: external_exports.enum(["primary", "secondary", "link"]).default("primary").describe("Button variant style") -}).describe("Notification action button"); -var NotificationSchema3 = external_exports.object({ - type: NotificationTypeSchema2.default("toast").describe("Notification presentation style"), - severity: NotificationSeveritySchema2.default("info").describe("Notification severity level"), - title: I18nLabelSchema5.optional().describe("Notification title"), - message: I18nLabelSchema5.describe("Notification message body"), - icon: external_exports.string().optional().describe("Icon name override"), - duration: external_exports.number().optional().describe("Auto-dismiss duration in ms, omit for persistent"), - dismissible: external_exports.boolean().default(true).describe("Allow user to dismiss the notification"), - actions: external_exports.array(NotificationActionSchema2).optional().describe("Action buttons"), - position: NotificationPositionSchema2.optional().describe("Override default position") -}).merge(AriaPropsSchema5.partial()).describe("Notification instance definition"); -var NotificationConfigSchema3 = external_exports.object({ - defaultPosition: NotificationPositionSchema2.default("top_right").describe("Default screen position for notifications"), - defaultDuration: external_exports.number().default(5e3).describe("Default auto-dismiss duration in ms"), - maxVisible: external_exports.number().default(5).describe("Maximum number of notifications visible at once"), - stackDirection: external_exports.enum(["up", "down"]).default("down").describe("Stack direction for multiple notifications"), - pauseOnHover: external_exports.boolean().default(true).describe("Pause auto-dismiss timer on hover") -}).describe("Global notification system configuration"); -var DragHandleSchema2 = external_exports.enum([ - "element", - "handle", - "grip_icon" -]).describe("Drag initiation method"); -var DropEffectSchema2 = external_exports.enum([ - "move", - "copy", - "link", - "none" -]).describe("Drop operation effect"); -var DragConstraintSchema2 = external_exports.object({ - axis: external_exports.enum(["x", "y", "both"]).default("both").describe("Constrain drag axis"), - bounds: external_exports.enum(["parent", "viewport", "none"]).default("none").describe("Constrain within bounds"), - grid: external_exports.tuple([external_exports.number(), external_exports.number()]).optional().describe("Snap to grid [x, y] in pixels") -}).describe("Drag movement constraints"); -var DropZoneSchema2 = external_exports.object({ - label: I18nLabelSchema5.optional().describe("Accessible label for the drop zone"), - accept: external_exports.array(external_exports.string()).describe("Accepted drag item types"), - maxItems: external_exports.number().optional().describe("Maximum items allowed in drop zone"), - highlightOnDragOver: external_exports.boolean().default(true).describe("Highlight drop zone when dragging over"), - dropEffect: DropEffectSchema2.default("move").describe("Visual effect on drop") -}).merge(AriaPropsSchema5.partial()).describe("Drop zone configuration"); -var DragItemSchema2 = external_exports.object({ - type: external_exports.string().describe("Drag item type identifier for matching with drop zones"), - label: I18nLabelSchema5.optional().describe("Accessible label describing the draggable item"), - handle: DragHandleSchema2.default("element").describe("How to initiate drag"), - constraint: DragConstraintSchema2.optional().describe("Drag movement constraints"), - preview: external_exports.enum(["element", "custom", "none"]).default("element").describe("Drag preview type"), - disabled: external_exports.boolean().default(false).describe("Disable dragging") -}).merge(AriaPropsSchema5.partial()).describe("Draggable item configuration"); -var DndConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable drag and drop"), - dragItem: DragItemSchema2.optional().describe("Configuration for draggable item"), - dropZone: DropZoneSchema2.optional().describe("Configuration for drop target"), - sortable: external_exports.boolean().default(false).describe("Enable sortable list behavior"), - autoScroll: external_exports.boolean().default(true).describe("Auto-scroll during drag near edges"), - touchDelay: external_exports.number().default(200).describe("Delay in ms before drag starts on touch devices") -}).describe("Drag and drop interaction configuration"); -var system_exports = {}; -__export4(system_exports, { - AccessControlConfigSchema: () => AccessControlConfigSchema3, - AddFieldOperation: () => AddFieldOperation2, - AdvancedAuthConfigSchema: () => AdvancedAuthConfigSchema2, - AnalyzerConfigSchema: () => AnalyzerConfigSchema2, - AppCompatibilityCheckSchema: () => AppCompatibilityCheckSchema2, - AppInstallRequestSchema: () => AppInstallRequestSchema2, - AppInstallResultSchema: () => AppInstallResultSchema2, - AppManifestSchema: () => AppManifestSchema2, - AppTranslationBundleSchema: () => AppTranslationBundleSchema2, - AuditConfigSchema: () => AuditConfigSchema2, - AuditEventActorSchema: () => AuditEventActorSchema2, - AuditEventChangeSchema: () => AuditEventChangeSchema2, - AuditEventFilterSchema: () => AuditEventFilterSchema2, - AuditEventSchema: () => AuditEventSchema2, - AuditEventSeverity: () => AuditEventSeverity2, - AuditEventTargetSchema: () => AuditEventTargetSchema2, - AuditEventType: () => AuditEventType2, - AuditFindingSchema: () => AuditFindingSchema2, - AuditFindingSeveritySchema: () => AuditFindingSeveritySchema2, - AuditFindingStatusSchema: () => AuditFindingStatusSchema2, - AuditLogConfigSchema: () => AuditLogConfigSchema2, - AuditRetentionPolicySchema: () => AuditRetentionPolicySchema2, - AuditScheduleSchema: () => AuditScheduleSchema2, - AuditStorageConfigSchema: () => AuditStorageConfigSchema2, - AuthConfigSchema: () => AuthConfigSchema2, - AuthPluginConfigSchema: () => AuthPluginConfigSchema2, - AuthProviderConfigSchema: () => AuthProviderConfigSchema2, - AwarenessEventSchema: () => AwarenessEventSchema2, - AwarenessSessionSchema: () => AwarenessSessionSchema2, - AwarenessUpdateSchema: () => AwarenessUpdateSchema2, - AwarenessUserStateSchema: () => AwarenessUserStateSchema2, - BackupConfigSchema: () => BackupConfigSchema2, - BackupRetentionSchema: () => BackupRetentionSchema2, - BackupStrategySchema: () => BackupStrategySchema2, - BatchProgressSchema: () => BatchProgressSchema2, - BatchTask: () => BatchTask2, - BatchTaskSchema: () => BatchTaskSchema2, - BucketConfigSchema: () => BucketConfigSchema3, - CRDTMergeResultSchema: () => CRDTMergeResultSchema2, - CRDTStateSchema: () => CRDTStateSchema2, - CRDTType: () => CRDTType2, - CacheAvalanchePreventionSchema: () => CacheAvalanchePreventionSchema2, - CacheConfigSchema: () => CacheConfigSchema2, - CacheConsistencySchema: () => CacheConsistencySchema2, - CacheInvalidationSchema: () => CacheInvalidationSchema2, - CacheStrategySchema: () => CacheStrategySchema2, - CacheTierSchema: () => CacheTierSchema2, - CacheWarmupSchema: () => CacheWarmupSchema2, - ChangeImpactSchema: () => ChangeImpactSchema2, - ChangePrioritySchema: () => ChangePrioritySchema2, - ChangeRequestSchema: () => ChangeRequestSchema2, - ChangeSetSchema: () => ChangeSetSchema2, - ChangeStatusSchema: () => ChangeStatusSchema2, - ChangeTypeSchema: () => ChangeTypeSchema2, - CollaborationMode: () => CollaborationMode2, - CollaborationSessionConfigSchema: () => CollaborationSessionConfigSchema2, - CollaborationSessionSchema: () => CollaborationSessionSchema2, - CollaborativeCursorSchema: () => CollaborativeCursorSchema2, - ComplianceAuditRequirementSchema: () => ComplianceAuditRequirementSchema2, - ComplianceConfigSchema: () => ComplianceConfigSchema2, - ComplianceEncryptionRequirementSchema: () => ComplianceEncryptionRequirementSchema2, - ComplianceFrameworkSchema: () => ComplianceFrameworkSchema2, - ConsoleDestinationConfigSchema: () => ConsoleDestinationConfigSchema2, - ConsumerConfigSchema: () => ConsumerConfigSchema2, - CoreServiceName: () => CoreServiceName3, - CounterOperationSchema: () => CounterOperationSchema2, - CoverageBreakdownEntrySchema: () => CoverageBreakdownEntrySchema3, - CreateObjectOperation: () => CreateObjectOperation2, - CronScheduleSchema: () => CronScheduleSchema2, - CursorColorPreset: () => CursorColorPreset2, - CursorSelectionSchema: () => CursorSelectionSchema2, - CursorStyleSchema: () => CursorStyleSchema2, - CursorUpdateSchema: () => CursorUpdateSchema2, - DEFAULT_SUSPICIOUS_ACTIVITY_RULES: () => DEFAULT_SUSPICIOUS_ACTIVITY_RULES, - DataClassificationPolicySchema: () => DataClassificationPolicySchema2, - DataClassificationSchema: () => DataClassificationSchema2, - DatabaseLevelIsolationStrategySchema: () => DatabaseLevelIsolationStrategySchema3, - DatabaseProviderSchema: () => DatabaseProviderSchema3, - DeadLetterQueueSchema: () => DeadLetterQueueSchema2, - DeleteObjectOperation: () => DeleteObjectOperation2, - DeployBundleSchema: () => DeployBundleSchema2, - DeployDiffSchema: () => DeployDiffSchema2, - DeployManifestSchema: () => DeployManifestSchema2, - DeployStatusEnum: () => DeployStatusEnum2, - DeployValidationIssueSchema: () => DeployValidationIssueSchema2, - DeployValidationResultSchema: () => DeployValidationResultSchema2, - DisasterRecoveryPlanSchema: () => DisasterRecoveryPlanSchema2, - DistributedCacheConfigSchema: () => DistributedCacheConfigSchema2, - EmailAndPasswordConfigSchema: () => EmailAndPasswordConfigSchema2, - EmailTemplateSchema: () => EmailTemplateSchema2, - EmailVerificationConfigSchema: () => EmailVerificationConfigSchema2, - EncryptionAlgorithmSchema: () => EncryptionAlgorithmSchema6, - EncryptionConfigSchema: () => EncryptionConfigSchema6, - ExecuteSqlOperation: () => ExecuteSqlOperation2, - ExtendedLogLevel: () => ExtendedLogLevel2, - ExternalServiceDestinationConfigSchema: () => ExternalServiceDestinationConfigSchema2, - FacetConfigSchema: () => FacetConfigSchema2, - FailoverConfigSchema: () => FailoverConfigSchema2, - FailoverModeSchema: () => FailoverModeSchema2, - FeatureSchema: () => FeatureSchema2, - FieldEncryptionSchema: () => FieldEncryptionSchema2, - FieldTranslationSchema: () => FieldTranslationSchema3, - FileDestinationConfigSchema: () => FileDestinationConfigSchema2, - FileMetadataSchema: () => FileMetadataSchema3, - GCounterSchema: () => GCounterSchema2, - GDPRConfigSchema: () => GDPRConfigSchema2, - HIPAAConfigSchema: () => HIPAAConfigSchema2, - HistogramBucketConfigSchema: () => HistogramBucketConfigSchema2, - HttpDestinationConfigSchema: () => HttpDestinationConfigSchema2, - HttpServerConfig: () => HttpServerConfig2, - HttpServerConfigSchema: () => HttpServerConfigSchema3, - InAppNotificationSchema: () => InAppNotificationSchema2, - IncidentCategorySchema: () => IncidentCategorySchema2, - IncidentNotificationMatrixSchema: () => IncidentNotificationMatrixSchema2, - IncidentNotificationRuleSchema: () => IncidentNotificationRuleSchema2, - IncidentResponsePhaseSchema: () => IncidentResponsePhaseSchema2, - IncidentResponsePolicySchema: () => IncidentResponsePolicySchema2, - IncidentSchema: () => IncidentSchema2, - IncidentSeveritySchema: () => IncidentSeveritySchema2, - IncidentStatusSchema: () => IncidentStatusSchema2, - IntervalScheduleSchema: () => IntervalScheduleSchema2, - JobExecutionSchema: () => JobExecutionSchema2, - JobExecutionStatus: () => JobExecutionStatus2, - JobSchema: () => JobSchema2, - KernelServiceMapSchema: () => KernelServiceMapSchema2, - KeyManagementProviderSchema: () => KeyManagementProviderSchema6, - KeyRotationPolicySchema: () => KeyRotationPolicySchema6, - LWWRegisterSchema: () => LWWRegisterSchema2, - LicenseMetricType: () => LicenseMetricType2, - LicenseSchema: () => LicenseSchema2, - LifecycleActionSchema: () => LifecycleActionSchema3, - LifecyclePolicyConfigSchema: () => LifecyclePolicyConfigSchema3, - LifecyclePolicyRuleSchema: () => LifecyclePolicyRuleSchema3, - LocaleSchema: () => LocaleSchema3, - LogDestinationSchema: () => LogDestinationSchema2, - LogDestinationType: () => LogDestinationType2, - LogEnrichmentConfigSchema: () => LogEnrichmentConfigSchema2, - LogEntrySchema: () => LogEntrySchema2, - LogFormat: () => LogFormat2, - LogLevel: () => LogLevel2, - LoggerConfigSchema: () => LoggerConfigSchema2, - LoggingConfigSchema: () => LoggingConfigSchema2, - MaskingConfigSchema: () => MaskingConfigSchema2, - MaskingRuleSchema: () => MaskingRuleSchema6, - MaskingStrategySchema: () => MaskingStrategySchema6, - MaskingVisibilityRuleSchema: () => MaskingVisibilityRuleSchema2, - MessageFormatSchema: () => MessageFormatSchema3, - MessageQueueConfigSchema: () => MessageQueueConfigSchema2, - MessageQueueProviderSchema: () => MessageQueueProviderSchema2, - MetadataCollectionInfoSchema: () => MetadataCollectionInfoSchema3, - MetadataDiffResultSchema: () => MetadataDiffResultSchema2, - MetadataExportOptionsSchema: () => MetadataExportOptionsSchema3, - MetadataFallbackStrategySchema: () => MetadataFallbackStrategySchema4, - MetadataFormatSchema: () => MetadataFormatSchema22, - MetadataHistoryQueryOptionsSchema: () => MetadataHistoryQueryOptionsSchema2, - MetadataHistoryQueryResultSchema: () => MetadataHistoryQueryResultSchema2, - MetadataHistoryRecordSchema: () => MetadataHistoryRecordSchema2, - MetadataHistoryRetentionPolicySchema: () => MetadataHistoryRetentionPolicySchema2, - MetadataImportOptionsSchema: () => MetadataImportOptionsSchema3, - MetadataLoadOptionsSchema: () => MetadataLoadOptionsSchema3, - MetadataLoadResultSchema: () => MetadataLoadResultSchema3, - MetadataLoaderContractSchema: () => MetadataLoaderContractSchema3, - MetadataManagerConfigSchema: () => MetadataManagerConfigSchema4, - MetadataRecordSchema: () => MetadataRecordSchema2, - MetadataSaveOptionsSchema: () => MetadataSaveOptionsSchema3, - MetadataSaveResultSchema: () => MetadataSaveResultSchema3, - MetadataScopeSchema: () => MetadataScopeSchema2, - MetadataSourceSchema: () => MetadataSourceSchema2, - MetadataStateSchema: () => MetadataStateSchema2, - MetadataStatsSchema: () => MetadataStatsSchema4, - MetadataWatchEventSchema: () => MetadataWatchEventSchema3, - MetricAggregationConfigSchema: () => MetricAggregationConfigSchema2, - MetricAggregationType: () => MetricAggregationType2, - MetricDataPointSchema: () => MetricDataPointSchema2, - MetricDefinitionSchema: () => MetricDefinitionSchema2, - MetricExportConfigSchema: () => MetricExportConfigSchema2, - MetricLabelsSchema: () => MetricLabelsSchema2, - MetricType: () => MetricType2, - MetricUnit: () => MetricUnit2, - MetricsConfigSchema: () => MetricsConfigSchema2, - MiddlewareConfig: () => MiddlewareConfig2, - MiddlewareConfigSchema: () => MiddlewareConfigSchema3, - MiddlewareType: () => MiddlewareType3, - MigrationDependencySchema: () => MigrationDependencySchema2, - MigrationOperationSchema: () => MigrationOperationSchema2, - MigrationPlanSchema: () => MigrationPlanSchema2, - MigrationStatementSchema: () => MigrationStatementSchema2, - ModifyFieldOperation: () => ModifyFieldOperation2, - MultipartUploadConfigSchema: () => MultipartUploadConfigSchema3, - MutualTLSConfigSchema: () => MutualTLSConfigSchema2, - NotificationChannelSchema: () => NotificationChannelSchema2, - NotificationConfigSchema: () => NotificationConfigSchema22, - ORSetElementSchema: () => ORSetElementSchema2, - ORSetSchema: () => ORSetSchema2, - OTComponentSchema: () => OTComponentSchema2, - OTOperationSchema: () => OTOperationSchema2, - OTOperationType: () => OTOperationType2, - OTTransformResultSchema: () => OTTransformResultSchema2, - ObjectMetadataSchema: () => ObjectMetadataSchema2, - ObjectStorageConfigSchema: () => ObjectStorageConfigSchema3, - ObjectTranslationDataSchema: () => ObjectTranslationDataSchema3, - ObjectTranslationNodeSchema: () => ObjectTranslationNodeSchema3, - OnceScheduleSchema: () => OnceScheduleSchema2, - OpenTelemetryCompatibilitySchema: () => OpenTelemetryCompatibilitySchema2, - OtelExporterType: () => OtelExporterType2, - PCIDSSConfigSchema: () => PCIDSSConfigSchema2, - PKG_CONVENTIONS: () => PKG_CONVENTIONS, - PNCounterSchema: () => PNCounterSchema2, - PackagePublishResultSchema: () => PackagePublishResultSchema2, - PlanSchema: () => PlanSchema2, - PresignedUrlConfigSchema: () => PresignedUrlConfigSchema2, - ProvisioningStepSchema: () => ProvisioningStepSchema2, - PushNotificationSchema: () => PushNotificationSchema2, - QueueConfig: () => QueueConfig2, - QueueConfigSchema: () => QueueConfigSchema2, - QuotaEnforcementResultSchema: () => QuotaEnforcementResultSchema2, - RPOSchema: () => RPOSchema2, - RTOSchema: () => RTOSchema2, - RegistryConfigSchema: () => RegistryConfigSchema2, - RegistrySyncPolicySchema: () => RegistrySyncPolicySchema2, - RegistryUpstreamSchema: () => RegistryUpstreamSchema2, - RemoveFieldOperation: () => RemoveFieldOperation2, - RenameObjectOperation: () => RenameObjectOperation2, - RetryPolicySchema: () => RetryPolicySchema2, - RollbackPlanSchema: () => RollbackPlanSchema2, - RouteHandlerMetadataSchema: () => RouteHandlerMetadataSchema2, - RowLevelIsolationStrategySchema: () => RowLevelIsolationStrategySchema3, - SMSTemplateSchema: () => SMSTemplateSchema2, - SamplingDecision: () => SamplingDecision2, - SamplingStrategyType: () => SamplingStrategyType2, - ScheduleSchema: () => ScheduleSchema2, - SchemaChangeSchema: () => SchemaChangeSchema2, - SchemaLevelIsolationStrategySchema: () => SchemaLevelIsolationStrategySchema3, - SearchConfigSchema: () => SearchConfigSchema22, - SearchIndexConfigSchema: () => SearchIndexConfigSchema2, - SearchProviderSchema: () => SearchProviderSchema2, - SecurityContextConfigSchema: () => SecurityContextConfigSchema2, - SecurityEventCorrelationSchema: () => SecurityEventCorrelationSchema2, - ServerCapabilitiesSchema: () => ServerCapabilitiesSchema2, - ServerEventSchema: () => ServerEventSchema2, - ServerEventType: () => ServerEventType3, - ServerStatusSchema: () => ServerStatusSchema2, - ServiceConfigSchema: () => ServiceConfigSchema2, - ServiceCriticalitySchema: () => ServiceCriticalitySchema3, - ServiceLevelIndicatorSchema: () => ServiceLevelIndicatorSchema2, - ServiceLevelObjectiveSchema: () => ServiceLevelObjectiveSchema2, - ServiceRequirementDef: () => ServiceRequirementDef2, - ServiceStatusSchema: () => ServiceStatusSchema2, - SocialProviderConfigSchema: () => SocialProviderConfigSchema2, - SpanAttributeValueSchema: () => SpanAttributeValueSchema2, - SpanAttributesSchema: () => SpanAttributesSchema2, - SpanEventSchema: () => SpanEventSchema2, - SpanKind: () => SpanKind2, - SpanLinkSchema: () => SpanLinkSchema2, - SpanSchema: () => SpanSchema2, - SpanStatus: () => SpanStatus2, - StorageAclSchema: () => StorageAclSchema3, - StorageClassSchema: () => StorageClassSchema3, - StorageConnectionSchema: () => StorageConnectionSchema3, - StorageNameMapping: () => StorageNameMapping, - StorageProviderSchema: () => StorageProviderSchema3, - StorageScopeSchema: () => StorageScopeSchema3, - StructuredLogEntrySchema: () => StructuredLogEntrySchema2, - SupplierAssessmentStatusSchema: () => SupplierAssessmentStatusSchema2, - SupplierRiskLevelSchema: () => SupplierRiskLevelSchema2, - SupplierSecurityAssessmentSchema: () => SupplierSecurityAssessmentSchema2, - SupplierSecurityPolicySchema: () => SupplierSecurityPolicySchema2, - SupplierSecurityRequirementSchema: () => SupplierSecurityRequirementSchema2, - SuspiciousActivityRuleSchema: () => SuspiciousActivityRuleSchema2, - SystemFieldName: () => SystemFieldName, - SystemObjectName: () => SystemObjectName2, - TASK_PRIORITY_VALUES: () => TASK_PRIORITY_VALUES, - TRANSLATE_PLACEHOLDER: () => TRANSLATE_PLACEHOLDER, - Task: () => Task2, - TaskExecutionResultSchema: () => TaskExecutionResultSchema2, - TaskPriority: () => TaskPriority2, - TaskRetryPolicySchema: () => TaskRetryPolicySchema2, - TaskSchema: () => TaskSchema2, - TaskStatus: () => TaskStatus2, - TenantConnectionConfigSchema: () => TenantConnectionConfigSchema3, - TenantIsolationConfigSchema: () => TenantIsolationConfigSchema2, - TenantIsolationLevel: () => TenantIsolationLevel3, - TenantPlanSchema: () => TenantPlanSchema2, - TenantProvisioningRequestSchema: () => TenantProvisioningRequestSchema2, - TenantProvisioningResultSchema: () => TenantProvisioningResultSchema2, - TenantProvisioningStatusEnum: () => TenantProvisioningStatusEnum2, - TenantQuotaSchema: () => TenantQuotaSchema3, - TenantRegionSchema: () => TenantRegionSchema2, - TenantSchema: () => TenantSchema2, - TenantSecurityPolicySchema: () => TenantSecurityPolicySchema2, - TenantUsageSchema: () => TenantUsageSchema2, - TextCRDTOperationSchema: () => TextCRDTOperationSchema2, - TextCRDTStateSchema: () => TextCRDTStateSchema2, - TimeSeriesDataPointSchema: () => TimeSeriesDataPointSchema2, - TimeSeriesSchema: () => TimeSeriesSchema2, - TopicConfigSchema: () => TopicConfigSchema2, - TraceContextPropagationSchema: () => TraceContextPropagationSchema2, - TraceContextSchema: () => TraceContextSchema2, - TraceFlagsSchema: () => TraceFlagsSchema2, - TracePropagationFormat: () => TracePropagationFormat2, - TraceSamplingConfigSchema: () => TraceSamplingConfigSchema2, - TraceStateSchema: () => TraceStateSchema2, - TracingConfigSchema: () => TracingConfigSchema2, - TrainingCategorySchema: () => TrainingCategorySchema2, - TrainingCompletionStatusSchema: () => TrainingCompletionStatusSchema2, - TrainingCourseSchema: () => TrainingCourseSchema2, - TrainingPlanSchema: () => TrainingPlanSchema2, - TrainingRecordSchema: () => TrainingRecordSchema2, - TranslationBundleSchema: () => TranslationBundleSchema2, - TranslationConfigSchema: () => TranslationConfigSchema2, - TranslationCoverageResultSchema: () => TranslationCoverageResultSchema2, - TranslationDataSchema: () => TranslationDataSchema3, - TranslationDiffItemSchema: () => TranslationDiffItemSchema3, - TranslationDiffStatusSchema: () => TranslationDiffStatusSchema3, - TranslationFileOrganizationSchema: () => TranslationFileOrganizationSchema3, - UserActivityStatus: () => UserActivityStatus2, - VectorClockSchema: () => VectorClockSchema2, - WorkerConfig: () => WorkerConfig2, - WorkerConfigSchema: () => WorkerConfigSchema2, - WorkerStatsSchema: () => WorkerStatsSchema2, - azureBlobStorageExample: () => azureBlobStorageExample2, - gcsStorageExample: () => gcsStorageExample2, - minioStorageExample: () => minioStorageExample2, - s3StorageExample: () => s3StorageExample2 -}); -var CacheStrategySchema2 = external_exports.enum([ - "lru", - // Least Recently Used - "lfu", - // Least Frequently Used - "fifo", - // First In First Out - "ttl", - // Time To Live only - "adaptive" - // Dynamic strategy selection -]).describe("Cache eviction strategy"); -var CacheTierSchema2 = external_exports.object({ - name: external_exports.string().describe("Unique cache tier name"), - type: external_exports.enum(["memory", "redis", "memcached", "cdn"]).describe("Cache backend type"), - maxSize: external_exports.number().optional().describe("Max size in MB"), - ttl: external_exports.number().default(300).describe("Default TTL in seconds"), - strategy: CacheStrategySchema2.default("lru").describe("Eviction strategy"), - warmup: external_exports.boolean().default(false).describe("Pre-populate cache on startup") -}).describe("Configuration for a single cache tier in the hierarchy"); -var CacheInvalidationSchema2 = external_exports.object({ - trigger: external_exports.enum(["create", "update", "delete", "manual"]).describe("Event that triggers invalidation"), - scope: external_exports.enum(["key", "pattern", "tag", "all"]).describe("Invalidation scope"), - pattern: external_exports.string().optional().describe("Key pattern for pattern-based invalidation"), - tags: external_exports.array(external_exports.string()).optional().describe("Cache tags to invalidate") -}).describe("Rule defining when and how cached entries are invalidated"); -var CacheConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable application-level caching"), - tiers: external_exports.array(CacheTierSchema2).describe("Ordered cache tier hierarchy"), - invalidation: external_exports.array(CacheInvalidationSchema2).describe("Cache invalidation rules"), - prefetch: external_exports.boolean().default(false).describe("Enable cache prefetching"), - compression: external_exports.boolean().default(false).describe("Enable data compression in cache"), - encryption: external_exports.boolean().default(false).describe("Enable encryption for cached data") -}).describe("Top-level application cache configuration"); -var CacheConsistencySchema2 = external_exports.enum([ - "write_through", - "write_behind", - "write_around", - "refresh_ahead" -]).describe("Distributed cache write consistency strategy"); -var CacheAvalanchePreventionSchema2 = external_exports.object({ - /** TTL jitter to stagger cache expiration */ - jitterTtl: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Add random jitter to TTL values"), - maxJitterSeconds: external_exports.number().default(60).describe("Maximum jitter added to TTL in seconds") - }).optional().describe("TTL jitter to prevent simultaneous expiration"), - /** Circuit breaker to protect backend under cache pressure */ - circuitBreaker: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable circuit breaker for backend protection"), - failureThreshold: external_exports.number().default(5).describe("Failures before circuit opens"), - resetTimeout: external_exports.number().default(30).describe("Seconds before half-open state") - }).optional().describe("Circuit breaker for backend protection"), - /** Cache lock to prevent thundering herd on key miss */ - lockout: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable cache locking for key regeneration"), - lockTimeoutMs: external_exports.number().default(5e3).describe("Maximum lock wait time in milliseconds") - }).optional().describe("Lock-based stampede prevention") -}).describe("Cache avalanche/stampede prevention configuration"); -var CacheWarmupSchema2 = external_exports.object({ - /** Enable cache warming */ - enabled: external_exports.boolean().default(false).describe("Enable cache warmup"), - /** Warmup strategy */ - strategy: external_exports.enum(["eager", "lazy", "scheduled"]).default("lazy").describe("Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)"), - /** Cron schedule for scheduled warmup */ - schedule: external_exports.string().optional().describe("Cron expression for scheduled warmup"), - /** Keys/patterns to warm up */ - patterns: external_exports.array(external_exports.string()).optional().describe('Key patterns to warm up (e.g., "user:*", "config:*")'), - /** Maximum concurrent warmup operations */ - concurrency: external_exports.number().default(10).describe("Maximum concurrent warmup operations") -}).describe("Cache warmup strategy"); -var DistributedCacheConfigSchema2 = CacheConfigSchema2.extend({ - /** Distributed write consistency strategy */ - consistency: CacheConsistencySchema2.optional().describe("Distributed cache consistency strategy"), - /** Avalanche/stampede prevention settings */ - avalanchePrevention: CacheAvalanchePreventionSchema2.optional().describe("Cache avalanche and stampede prevention"), - /** Cache warmup configuration */ - warmup: CacheWarmupSchema2.optional().describe("Cache warmup strategy") -}).describe("Distributed cache configuration with consistency and avalanche prevention"); -var BackupStrategySchema2 = external_exports.enum([ - "full", - "incremental", - "differential" -]).describe("Backup strategy type"); -var BackupRetentionSchema2 = external_exports.object({ - /** Number of days to retain backups */ - days: external_exports.number().min(1).describe("Retention period in days"), - /** Minimum number of backup copies to keep regardless of age */ - minCopies: external_exports.number().min(1).default(3).describe("Minimum backup copies to retain"), - /** Maximum number of backup copies */ - maxCopies: external_exports.number().optional().describe("Maximum backup copies to store") -}).describe("Backup retention policy"); -var BackupConfigSchema2 = external_exports.object({ - /** Backup strategy */ - strategy: BackupStrategySchema2.default("incremental").describe("Backup strategy"), - /** Cron schedule for automated backups */ - schedule: external_exports.string().optional().describe('Cron expression for backup schedule (e.g., "0 2 * * *")'), - /** Retention policy */ - retention: BackupRetentionSchema2.describe("Backup retention policy"), - /** Storage destination */ - destination: external_exports.object({ - type: external_exports.enum(["s3", "gcs", "azure_blob", "local"]).describe("Storage backend type"), - bucket: external_exports.string().optional().describe("Cloud storage bucket/container name"), - path: external_exports.string().optional().describe("Storage path prefix"), - region: external_exports.string().optional().describe("Cloud storage region") - }).describe("Backup storage destination"), - /** Encryption settings */ - encryption: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable backup encryption"), - algorithm: external_exports.enum(["AES-256-GCM", "AES-256-CBC", "ChaCha20-Poly1305"]).default("AES-256-GCM").describe("Encryption algorithm"), - keyId: external_exports.string().optional().describe("KMS key ID for encryption") - }).optional().describe("Backup encryption settings"), - /** Compression settings */ - compression: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable backup compression"), - algorithm: external_exports.enum(["gzip", "zstd", "lz4", "snappy"]).default("zstd").describe("Compression algorithm") - }).optional().describe("Backup compression settings"), - /** Verify backup integrity after creation */ - verifyAfterBackup: external_exports.boolean().default(true).describe("Verify backup integrity after creation") -}).describe("Backup configuration"); -var FailoverModeSchema2 = external_exports.enum([ - "active_passive", - "active_active", - "pilot_light", - "warm_standby" -]).describe("Failover mode"); -var FailoverConfigSchema2 = external_exports.object({ - /** Failover mode */ - mode: FailoverModeSchema2.default("active_passive").describe("Failover mode"), - /** Automatic failover enabled */ - autoFailover: external_exports.boolean().default(true).describe("Enable automatic failover"), - /** Health check interval in seconds */ - healthCheckInterval: external_exports.number().default(30).describe("Health check interval in seconds"), - /** Number of consecutive failures before triggering failover */ - failureThreshold: external_exports.number().default(3).describe("Consecutive failures before failover"), - /** Regions/zones for disaster recovery */ - regions: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Region identifier (e.g., "us-east-1", "eu-west-1")'), - role: external_exports.enum(["primary", "secondary", "witness"]).describe("Region role"), - endpoint: external_exports.string().optional().describe("Region endpoint URL"), - priority: external_exports.number().optional().describe("Failover priority (lower = higher priority)") - })).min(2).describe("Multi-region configuration (minimum 2 regions)"), - /** DNS failover configuration */ - dns: external_exports.object({ - ttl: external_exports.number().default(60).describe("DNS TTL in seconds for failover"), - provider: external_exports.enum(["route53", "cloudflare", "azure_dns", "custom"]).optional().describe("DNS provider for automatic failover") - }).optional().describe("DNS failover settings") -}).describe("Failover configuration"); -var RPOSchema2 = external_exports.object({ - /** RPO value */ - value: external_exports.number().min(0).describe("RPO value"), - /** RPO time unit */ - unit: external_exports.enum(["seconds", "minutes", "hours"]).default("minutes").describe("RPO time unit") -}).describe("Recovery Point Objective (maximum acceptable data loss)"); -var RTOSchema2 = external_exports.object({ - /** RTO value */ - value: external_exports.number().min(0).describe("RTO value"), - /** RTO time unit */ - unit: external_exports.enum(["seconds", "minutes", "hours"]).default("minutes").describe("RTO time unit") -}).describe("Recovery Time Objective (maximum acceptable downtime)"); -var DisasterRecoveryPlanSchema2 = external_exports.object({ - /** Enable disaster recovery */ - enabled: external_exports.boolean().default(false).describe("Enable disaster recovery plan"), - /** Recovery Point Objective */ - rpo: RPOSchema2.describe("Recovery Point Objective"), - /** Recovery Time Objective */ - rto: RTOSchema2.describe("Recovery Time Objective"), - /** Backup configuration */ - backup: BackupConfigSchema2.describe("Backup configuration"), - /** Failover configuration */ - failover: FailoverConfigSchema2.optional().describe("Multi-region failover configuration"), - /** Data replication settings */ - replication: external_exports.object({ - /** Replication mode */ - mode: external_exports.enum(["synchronous", "asynchronous", "semi_synchronous"]).default("asynchronous").describe("Data replication mode"), - /** Maximum replication lag allowed (seconds) */ - maxLagSeconds: external_exports.number().optional().describe("Maximum acceptable replication lag in seconds"), - /** Objects/tables to replicate (empty = all) */ - includeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to replicate (empty = all)"), - /** Objects/tables to exclude from replication */ - excludeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to exclude from replication") - }).optional().describe("Data replication settings"), - /** Automated recovery testing */ - testing: external_exports.object({ - /** Enable periodic DR testing */ - enabled: external_exports.boolean().default(false).describe("Enable automated DR testing"), - /** Cron schedule for DR tests */ - schedule: external_exports.string().optional().describe("Cron expression for DR test schedule"), - /** Notification channel for test results */ - notificationChannel: external_exports.string().optional().describe("Notification channel for DR test results") - }).optional().describe("Automated disaster recovery testing"), - /** Runbook URL for manual procedures */ - runbookUrl: external_exports.string().optional().describe("URL to disaster recovery runbook/playbook"), - /** Contact list for DR incidents */ - contacts: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Contact name"), - role: external_exports.string().describe('Contact role (e.g., "DBA", "SRE Lead")'), - email: external_exports.string().optional().describe("Contact email"), - phone: external_exports.string().optional().describe("Contact phone") - })).optional().describe("Emergency contact list for DR incidents") -}).describe("Complete disaster recovery plan configuration"); -var MessageQueueProviderSchema2 = external_exports.enum([ - "kafka", - "rabbitmq", - "aws-sqs", - "redis-pubsub", - "google-pubsub", - "azure-service-bus" -]).describe("Supported message queue backend provider"); -var TopicConfigSchema2 = external_exports.object({ - name: external_exports.string().describe("Topic name identifier"), - partitions: external_exports.number().default(1).describe("Number of partitions for parallel consumption"), - replicationFactor: external_exports.number().default(1).describe("Number of replicas for fault tolerance"), - retentionMs: external_exports.number().optional().describe("Message retention period in milliseconds"), - compressionType: external_exports.enum(["none", "gzip", "snappy", "lz4"]).default("none").describe("Message compression algorithm") -}).describe("Configuration for a message queue topic"); -var ConsumerConfigSchema2 = external_exports.object({ - groupId: external_exports.string().describe("Consumer group identifier"), - autoOffsetReset: external_exports.enum(["earliest", "latest"]).default("latest").describe("Where to start reading when no offset exists"), - enableAutoCommit: external_exports.boolean().default(true).describe("Automatically commit consumed offsets"), - maxPollRecords: external_exports.number().default(500).describe("Maximum records returned per poll") -}).describe("Consumer group configuration for topic consumption"); -var DeadLetterQueueSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable dead letter queue for failed messages"), - maxRetries: external_exports.number().default(3).describe("Maximum delivery attempts before sending to DLQ"), - queueName: external_exports.string().describe("Name of the dead letter queue") -}).describe("Dead letter queue configuration for unprocessable messages"); -var MessageQueueConfigSchema2 = external_exports.object({ - provider: MessageQueueProviderSchema2.describe("Message queue backend provider"), - topics: external_exports.array(TopicConfigSchema2).describe("List of topic configurations"), - consumers: external_exports.array(ConsumerConfigSchema2).optional().describe("Consumer group configurations"), - deadLetterQueue: DeadLetterQueueSchema2.optional().describe("Dead letter queue for failed messages"), - ssl: external_exports.boolean().default(false).describe("Enable SSL/TLS for broker connections"), - sasl: external_exports.object({ - mechanism: external_exports.enum(["plain", "scram-sha-256", "scram-sha-512"]).describe("SASL authentication mechanism"), - username: external_exports.string().describe("SASL username"), - password: external_exports.string().describe("SASL password") - }).optional().describe("SASL authentication configuration") -}).describe("Top-level message queue configuration"); -var StorageScopeSchema3 = external_exports.enum([ - "global", - // Global application-wide storage - "tenant", - // Tenant-scoped storage (multi-tenant apps) - "user", - // User-scoped storage - "session", - // Session-scoped storage (ephemeral) - "temp", - // Ephemeral, cleared on restart - "cache", - // Ephemeral, survives restarts, cleared on LRU/Expiration - "data", - // Persistent, backed up - "logs", - // Append-only, rotated - "config", - // Read-heavy, versioned - "public" - // Publicly accessible static assets -]).describe("Storage scope classification"); -var FileMetadataSchema3 = external_exports.object({ - path: external_exports.string().describe("File path"), - name: external_exports.string().describe("File name"), - size: external_exports.number().int().describe("File size in bytes"), - mimeType: external_exports.string().describe("MIME type"), - lastModified: external_exports.string().datetime().describe("Last modified timestamp"), - created: external_exports.string().datetime().describe("Creation timestamp"), - etag: external_exports.string().optional().describe("Entity tag") -}); -var StorageProviderSchema3 = external_exports.enum([ - "s3", - // Amazon S3 - "azure_blob", - // Azure Blob Storage - "gcs", - // Google Cloud Storage - "minio", - // MinIO (self-hosted S3-compatible) - "r2", - // Cloudflare R2 - "spaces", - // DigitalOcean Spaces - "wasabi", - // Wasabi Hot Cloud Storage - "backblaze", - // Backblaze B2 - "local" - // Local filesystem (development only) -]).describe("Storage provider type"); -var StorageAclSchema3 = external_exports.enum([ - "private", - // Owner has full control, no one else has access - "public_read", - // Owner has full control, everyone can read - "public_read_write", - // Owner has full control, everyone can read/write (not recommended) - "authenticated_read", - // Owner has full control, authenticated users can read - "bucket_owner_read", - // Object owner has full control, bucket owner can read - "bucket_owner_full_control" - // Both object and bucket owner have full control -]).describe("Storage access control level"); -var StorageClassSchema3 = external_exports.enum([ - "standard", - // Standard/hot storage for frequently accessed data - "intelligent", - // Intelligent tiering (auto-moves between hot/cool) - "infrequent_access", - // Infrequent access/cool storage - "glacier", - // Archive/cold storage (slower retrieval) - "deep_archive" - // Deep archive (cheapest, slowest retrieval) -]).describe("Storage class/tier for cost optimization"); -var LifecycleActionSchema3 = external_exports.enum([ - "transition", - // Move to different storage class - "delete", - // Delete the object - "abort" - // Abort incomplete multipart uploads -]).describe("Lifecycle policy action type"); -var ObjectMetadataSchema2 = external_exports.object({ - contentType: external_exports.string().describe("MIME type (e.g., image/jpeg, application/pdf)"), - contentLength: external_exports.number().min(0).describe("File size in bytes"), - contentEncoding: external_exports.string().optional().describe("Content encoding (e.g., gzip)"), - contentDisposition: external_exports.string().optional().describe("Content disposition header"), - contentLanguage: external_exports.string().optional().describe("Content language"), - cacheControl: external_exports.string().optional().describe("Cache control directives"), - etag: external_exports.string().optional().describe("Entity tag for versioning/caching"), - lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), - versionId: external_exports.string().optional().describe("Object version identifier"), - storageClass: StorageClassSchema3.optional().describe("Storage class/tier"), - encryption: external_exports.object({ - algorithm: external_exports.string().describe("Encryption algorithm (e.g., AES256, aws:kms)"), - keyId: external_exports.string().optional().describe("KMS key ID if using managed encryption") - }).optional().describe("Server-side encryption configuration"), - custom: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom user-defined metadata") -}); -var PresignedUrlConfigSchema2 = external_exports.object({ - operation: external_exports.enum(["get", "put", "delete", "head"]).describe("Allowed operation"), - expiresIn: external_exports.number().min(1).max(604800).describe("Expiration time in seconds (max 7 days)"), - contentType: external_exports.string().optional().describe("Required content type for PUT operations"), - maxSize: external_exports.number().min(0).optional().describe("Maximum file size in bytes for PUT operations"), - responseContentType: external_exports.string().optional().describe("Override content-type for GET operations"), - responseContentDisposition: external_exports.string().optional().describe("Override content-disposition for GET operations") -}); -var MultipartUploadConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable multipart uploads"), - partSize: external_exports.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe("Part size in bytes (min 5MB, max 5GB)"), - maxParts: external_exports.number().min(1).max(1e4).default(1e4).describe("Maximum number of parts (max 10,000)"), - threshold: external_exports.number().min(0).default(100 * 1024 * 1024).describe("File size threshold to trigger multipart upload (bytes)"), - maxConcurrent: external_exports.number().min(1).max(100).default(4).describe("Maximum concurrent part uploads"), - abortIncompleteAfterDays: external_exports.number().min(1).optional().describe("Auto-abort incomplete uploads after N days") -}); -var AccessControlConfigSchema3 = external_exports.object({ - acl: StorageAclSchema3.default("private").describe("Default access control level"), - allowedOrigins: external_exports.array(external_exports.string()).optional().describe("CORS allowed origins"), - allowedMethods: external_exports.array(external_exports.enum(["GET", "PUT", "POST", "DELETE", "HEAD"])).optional().describe("CORS allowed HTTP methods"), - allowedHeaders: external_exports.array(external_exports.string()).optional().describe("CORS allowed headers"), - exposeHeaders: external_exports.array(external_exports.string()).optional().describe("CORS exposed headers"), - maxAge: external_exports.number().min(0).optional().describe("CORS preflight cache duration in seconds"), - corsEnabled: external_exports.boolean().default(false).describe("Enable CORS configuration"), - publicAccess: external_exports.object({ - allowPublicRead: external_exports.boolean().default(false).describe("Allow public read access"), - allowPublicWrite: external_exports.boolean().default(false).describe("Allow public write access"), - allowPublicList: external_exports.boolean().default(false).describe("Allow public bucket listing") - }).optional().describe("Public access control"), - allowedIps: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses/CIDR blocks"), - blockedIps: external_exports.array(external_exports.string()).optional().describe("Blocked IP addresses/CIDR blocks") -}); -var LifecyclePolicyRuleSchema3 = external_exports.object({ - id: SystemIdentifierSchema6.describe("Rule identifier"), - enabled: external_exports.boolean().default(true).describe("Enable this rule"), - action: LifecycleActionSchema3.describe("Action to perform"), - prefix: external_exports.string().optional().describe('Object key prefix filter (e.g., "uploads/")'), - tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Object tag filters"), - daysAfterCreation: external_exports.number().min(0).optional().describe("Days after object creation"), - daysAfterModification: external_exports.number().min(0).optional().describe("Days after last modification"), - targetStorageClass: StorageClassSchema3.optional().describe("Target storage class for transition action") -}).refine((data) => { - if (data.action === "transition" && !data.targetStorageClass) { - return false; - } - return true; -}, { - message: 'targetStorageClass is required when action is "transition"' -}); -var LifecyclePolicyConfigSchema3 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable lifecycle policies"), - rules: external_exports.array(LifecyclePolicyRuleSchema3).default([]).describe("Lifecycle rules") -}); -var BucketConfigSchema3 = external_exports.object({ - name: SystemIdentifierSchema6.describe("Bucket identifier in ObjectStack (snake_case)"), - label: external_exports.string().describe("Display label"), - bucketName: external_exports.string().describe("Actual bucket/container name in storage provider"), - region: external_exports.string().optional().describe("Storage region (e.g., us-east-1, westus)"), - provider: StorageProviderSchema3.describe("Storage provider"), - endpoint: external_exports.string().optional().describe("Custom endpoint URL (for S3-compatible providers)"), - pathStyle: external_exports.boolean().default(false).describe("Use path-style URLs (for S3-compatible providers)"), - versioning: external_exports.boolean().default(false).describe("Enable object versioning"), - encryption: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable server-side encryption"), - algorithm: external_exports.enum(["AES256", "aws:kms", "azure:kms", "gcp:kms"]).default("AES256").describe("Encryption algorithm"), - kmsKeyId: external_exports.string().optional().describe("KMS key ID for managed encryption") - }).optional().describe("Server-side encryption configuration"), - accessControl: AccessControlConfigSchema3.optional().describe("Access control configuration"), - lifecyclePolicy: LifecyclePolicyConfigSchema3.optional().describe("Lifecycle policy configuration"), - multipartConfig: MultipartUploadConfigSchema3.optional().describe("Multipart upload configuration"), - tags: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Bucket tags for organization"), - description: external_exports.string().optional().describe("Bucket description"), - enabled: external_exports.boolean().default(true).describe("Enable this bucket") -}); -var StorageConnectionSchema3 = external_exports.object({ - // AWS S3 / MinIO - accessKeyId: external_exports.string().optional().describe("AWS access key ID or MinIO access key"), - secretAccessKey: external_exports.string().optional().describe("AWS secret access key or MinIO secret key"), - sessionToken: external_exports.string().optional().describe("AWS session token for temporary credentials"), - // Azure Blob Storage - accountName: external_exports.string().optional().describe("Azure storage account name"), - accountKey: external_exports.string().optional().describe("Azure storage account key"), - sasToken: external_exports.string().optional().describe("Azure SAS token"), - // Google Cloud Storage - projectId: external_exports.string().optional().describe("GCP project ID"), - credentials: external_exports.string().optional().describe("GCP service account credentials JSON"), - // Common - endpoint: external_exports.string().optional().describe("Custom endpoint URL"), - region: external_exports.string().optional().describe("Default region"), - useSSL: external_exports.boolean().default(true).describe("Use SSL/TLS for connections"), - timeout: external_exports.number().min(0).optional().describe("Connection timeout in milliseconds") -}); -var ObjectStorageConfigSchema3 = external_exports.object({ - name: SystemIdentifierSchema6.describe("Storage configuration identifier"), - label: external_exports.string().describe("Display label"), - provider: StorageProviderSchema3.describe("Primary storage provider"), - /** - * Storage scope - * Defines the lifecycle and access pattern for this storage - */ - scope: StorageScopeSchema3.optional().default("global").describe("Storage scope"), - connection: StorageConnectionSchema3.describe("Connection credentials"), - buckets: external_exports.array(BucketConfigSchema3).default([]).describe("Configured buckets"), - defaultBucket: external_exports.string().optional().describe("Default bucket name for operations"), - /** - * Base path or location - * For local/scoped storage configurations - */ - location: external_exports.string().optional().describe("Root path (local) or base location"), - /** - * Storage quota in bytes - */ - quota: external_exports.number().int().positive().optional().describe("Max size in bytes"), - /** - * Provider-specific options - */ - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration options"), - enabled: external_exports.boolean().default(true).describe("Enable this storage configuration"), - description: external_exports.string().optional().describe("Configuration description") -}); -var s3StorageExample2 = ObjectStorageConfigSchema3.parse({ - name: "aws_s3_storage", - label: "AWS S3 Production Storage", - provider: "s3", - connection: { - accessKeyId: "${AWS_ACCESS_KEY_ID}", - secretAccessKey: "${AWS_SECRET_ACCESS_KEY}", - region: "us-east-1" - }, - buckets: [ - { - name: "user_uploads", - label: "User Uploads", - bucketName: "my-app-user-uploads", - region: "us-east-1", - provider: "s3", - versioning: true, - encryption: { - enabled: true, - algorithm: "aws:kms", - kmsKeyId: "${AWS_KMS_KEY_ID}" - }, - accessControl: { - acl: "private", - corsEnabled: true, - allowedOrigins: ["https://app.example.com"], - allowedMethods: ["GET", "PUT", "POST"] - }, - lifecyclePolicy: { - enabled: true, - rules: [ - { - id: "archive_old_uploads", - enabled: true, - action: "transition", - daysAfterCreation: 90, - targetStorageClass: "glacier" - } - ] - }, - multipartConfig: { - enabled: true, - partSize: 10 * 1024 * 1024, - threshold: 100 * 1024 * 1024, - maxConcurrent: 4 - } - } - ], - defaultBucket: "user_uploads", - enabled: true -}); -var minioStorageExample2 = ObjectStorageConfigSchema3.parse({ - name: "minio_local", - label: "MinIO Local Storage", - provider: "minio", - connection: { - accessKeyId: "minioadmin", - secretAccessKey: "minioadmin", - endpoint: "http://localhost:9000", - useSSL: false - }, - buckets: [ - { - name: "development_files", - label: "Development Files", - bucketName: "dev-files", - provider: "minio", - endpoint: "http://localhost:9000", - pathStyle: true, - accessControl: { - acl: "private" - } - } - ], - defaultBucket: "development_files", - enabled: true -}); -var azureBlobStorageExample2 = ObjectStorageConfigSchema3.parse({ - name: "azure_blob_storage", - label: "Azure Blob Storage", - provider: "azure_blob", - connection: { - accountName: "mystorageaccount", - accountKey: "${AZURE_STORAGE_KEY}", - endpoint: "https://mystorageaccount.blob.core.windows.net" - }, - buckets: [ - { - name: "media_files", - label: "Media Files", - bucketName: "media", - provider: "azure_blob", - region: "eastus", - accessControl: { - acl: "public_read", - publicAccess: { - allowPublicRead: true, - allowPublicWrite: false, - allowPublicList: false - } - } - } - ], - defaultBucket: "media_files", - enabled: true -}); -var gcsStorageExample2 = ObjectStorageConfigSchema3.parse({ - name: "gcs_storage", - label: "Google Cloud Storage", - provider: "gcs", - connection: { - projectId: "my-gcp-project", - credentials: "${GCP_SERVICE_ACCOUNT_JSON}" - }, - buckets: [ - { - name: "backup_storage", - label: "Backup Storage", - bucketName: "my-app-backups", - region: "us-central1", - provider: "gcs", - lifecyclePolicy: { - enabled: true, - rules: [ - { - id: "delete_old_backups", - enabled: true, - action: "delete", - daysAfterCreation: 30 - } - ] - } - } - ], - defaultBucket: "backup_storage", - enabled: true -}); -var SearchProviderSchema2 = external_exports.enum([ - "elasticsearch", - "algolia", - "meilisearch", - "typesense", - "opensearch" -]).describe("Supported full-text search engine provider"); -var AnalyzerConfigSchema2 = external_exports.object({ - type: external_exports.enum(["standard", "simple", "whitespace", "keyword", "pattern", "language"]).describe("Text analyzer type"), - language: external_exports.string().optional().describe("Language for language-specific analysis"), - stopwords: external_exports.array(external_exports.string()).optional().describe("Custom stopwords to filter during analysis"), - customFilters: external_exports.array(external_exports.string()).optional().describe("Additional token filter names to apply") -}).describe("Text analyzer configuration for index tokenization and normalization"); -var SearchIndexConfigSchema2 = external_exports.object({ - indexName: external_exports.string().describe("Name of the search index"), - objectName: external_exports.string().describe("Source ObjectQL object"), - fields: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Field name to index"), - type: external_exports.enum(["text", "keyword", "number", "date", "boolean", "geo"]).describe("Index field data type"), - analyzer: external_exports.string().optional().describe("Named analyzer to use for this field"), - searchable: external_exports.boolean().default(true).describe("Include field in full-text search"), - filterable: external_exports.boolean().default(false).describe("Allow filtering on this field"), - sortable: external_exports.boolean().default(false).describe("Allow sorting by this field"), - boost: external_exports.number().default(1).describe("Relevance boost factor for this field") - })).describe("Fields to include in the search index"), - replicas: external_exports.number().default(1).describe("Number of index replicas for availability"), - shards: external_exports.number().default(1).describe("Number of index shards for distribution") -}).describe("Search index definition mapping an ObjectQL object to a search engine index"); -var FacetConfigSchema2 = external_exports.object({ - field: external_exports.string().describe("Field name to generate facets from"), - maxValues: external_exports.number().default(10).describe("Maximum number of facet values to return"), - sort: external_exports.enum(["count", "alpha"]).default("count").describe("Facet value sort order") -}).describe("Faceted search configuration for a single field"); -var SearchConfigSchema22 = external_exports.object({ - provider: SearchProviderSchema2.describe("Search engine backend provider"), - indexes: external_exports.array(SearchIndexConfigSchema2).describe("Search index definitions"), - analyzers: external_exports.record(external_exports.string(), AnalyzerConfigSchema2).optional().describe("Named text analyzer configurations"), - facets: external_exports.array(FacetConfigSchema2).optional().describe("Faceted search configurations"), - typoTolerance: external_exports.boolean().default(true).describe("Enable typo-tolerant search"), - synonyms: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional().describe("Synonym mappings for search expansion"), - ranking: external_exports.array(external_exports.enum(["typo", "geo", "words", "filters", "proximity", "attribute", "exact", "custom"])).optional().describe("Custom ranking rule order") -}).describe("Top-level full-text search engine configuration"); -var HttpServerConfigSchema3 = external_exports.object({ - /** - * Server port number - */ - port: external_exports.number().int().min(1).max(65535).default(3e3).describe("Port number to listen on"), - /** - * Server host address - */ - host: external_exports.string().default("0.0.0.0").describe("Host address to bind to"), - /** - * CORS configuration - */ - cors: CorsConfigSchema4.optional().describe("CORS configuration"), - /** - * Request handling options - */ - requestTimeout: external_exports.number().int().default(3e4).describe("Request timeout in milliseconds"), - bodyLimit: external_exports.string().default("10mb").describe("Maximum request body size"), - /** - * Compression settings - */ - compression: external_exports.boolean().default(true).describe("Enable response compression"), - /** - * Security headers - */ - security: external_exports.object({ - helmet: external_exports.boolean().default(true).describe("Enable security headers via helmet"), - rateLimit: RateLimitConfigSchema4.optional().describe("Global rate limiting configuration") - }).optional().describe("Security configuration"), - /** - * Static file serving - */ - static: external_exports.array(StaticMountSchema4).optional().describe("Static file serving configuration"), - /** - * Trust proxy settings - */ - trustProxy: external_exports.boolean().default(false).describe("Trust X-Forwarded-* headers") -}); -var RouteHandlerMetadataSchema2 = external_exports.object({ - /** - * HTTP method - */ - method: HttpMethod5.describe("HTTP method"), - /** - * URL path pattern (supports parameters like /api/users/:id) - */ - path: external_exports.string().describe("URL path pattern"), - /** - * Handler function name or identifier - */ - handler: external_exports.string().describe("Handler identifier or name"), - /** - * Route metadata - */ - metadata: external_exports.object({ - summary: external_exports.string().optional().describe("Route summary for documentation"), - description: external_exports.string().optional().describe("Route description"), - tags: external_exports.array(external_exports.string()).optional().describe("Tags for grouping"), - operationId: external_exports.string().optional().describe("Unique operation identifier") - }).optional(), - /** - * Security requirements - */ - security: external_exports.object({ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - rateLimit: external_exports.string().optional().describe("Rate limit policy override") - }).optional() -}); -var MiddlewareType3 = external_exports.enum([ - "authentication", - // Authentication middleware - "authorization", - // Authorization/permission checks - "logging", - // Request/response logging - "validation", - // Input validation - "transformation", - // Request/response transformation - "error", - // Error handling - "custom" - // Custom middleware -]); -var MiddlewareConfigSchema3 = external_exports.object({ - /** - * Middleware identifier - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Middleware name (snake_case)"), - /** - * Middleware type - */ - type: MiddlewareType3.describe("Middleware type"), - /** - * Enable/disable middleware - */ - enabled: external_exports.boolean().default(true).describe("Whether middleware is enabled"), - /** - * Execution order (lower numbers execute first) - */ - order: external_exports.number().int().default(100).describe("Execution order priority"), - /** - * Middleware-specific configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Middleware configuration object"), - /** - * Path patterns to apply middleware to - */ - paths: external_exports.object({ - include: external_exports.array(external_exports.string()).optional().describe("Include path patterns (glob)"), - exclude: external_exports.array(external_exports.string()).optional().describe("Exclude path patterns (glob)") - }).optional().describe("Path filtering") -}); -var ServerEventType3 = external_exports.enum([ - "starting", - // Server is starting - "started", - // Server has started and is listening - "stopping", - // Server is stopping - "stopped", - // Server has stopped - "request", - // Request received - "response", - // Response sent - "error" - // Error occurred -]); -var ServerEventSchema2 = external_exports.object({ - /** - * Event type - */ - type: ServerEventType3.describe("Event type"), - /** - * Timestamp - */ - timestamp: external_exports.string().datetime().describe("Event timestamp (ISO 8601)"), - /** - * Event payload - */ - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific data") -}); -var ServerCapabilitiesSchema2 = external_exports.object({ - /** - * Supported HTTP versions - */ - httpVersions: external_exports.array(external_exports.enum(["1.0", "1.1", "2.0", "3.0"])).default(["1.1"]).describe("Supported HTTP versions"), - /** - * WebSocket support - */ - websocket: external_exports.boolean().default(false).describe("WebSocket support"), - /** - * Server-Sent Events support - */ - sse: external_exports.boolean().default(false).describe("Server-Sent Events support"), - /** - * HTTP/2 Server Push - */ - serverPush: external_exports.boolean().default(false).describe("HTTP/2 Server Push support"), - /** - * Streaming support - */ - streaming: external_exports.boolean().default(true).describe("Response streaming support"), - /** - * Middleware support - */ - middleware: external_exports.boolean().default(true).describe("Middleware chain support"), - /** - * Route parameterization - */ - routeParams: external_exports.boolean().default(true).describe("URL parameter support (/users/:id)"), - /** - * Built-in compression - */ - compression: external_exports.boolean().default(true).describe("Built-in compression support") -}); -var ServerStatusSchema2 = external_exports.object({ - /** - * Server state - */ - state: external_exports.enum(["stopped", "starting", "running", "stopping", "error"]).describe("Current server state"), - /** - * Uptime in milliseconds - */ - uptime: external_exports.number().int().optional().describe("Server uptime in milliseconds"), - /** - * Server information - */ - server: external_exports.object({ - port: external_exports.number().int().describe("Listening port"), - host: external_exports.string().describe("Bound host"), - url: external_exports.string().optional().describe("Full server URL") - }).optional(), - /** - * Connection metrics - */ - connections: external_exports.object({ - active: external_exports.number().int().describe("Active connections"), - total: external_exports.number().int().describe("Total connections handled") - }).optional(), - /** - * Request metrics - */ - requests: external_exports.object({ - total: external_exports.number().int().describe("Total requests processed"), - success: external_exports.number().int().describe("Successful requests"), - errors: external_exports.number().int().describe("Failed requests") - }).optional() -}); -var HttpServerConfig2 = Object.assign(HttpServerConfigSchema3, { - create: (config4) => config4 -}); -var MiddlewareConfig2 = Object.assign(MiddlewareConfigSchema3, { - create: (config4) => config4 -}); -var AuditEventType2 = external_exports.enum([ - // Data Operations (CRUD) - "data.create", - // Record creation - "data.read", - // Record retrieval/viewing - "data.update", - // Record modification - "data.delete", - // Record deletion - "data.export", - // Data export operations - "data.import", - // Data import operations - "data.bulk_update", - // Bulk update operations - "data.bulk_delete", - // Bulk delete operations - // Authentication Events - "auth.login", - // Successful login - "auth.login_failed", - // Failed login attempt - "auth.logout", - // User logout - "auth.session_created", - // New session created - "auth.session_expired", - // Session expiration - "auth.password_reset", - // Password reset initiated - "auth.password_changed", - // Password successfully changed - "auth.email_verified", - // Email verification completed - "auth.mfa_enabled", - // Multi-factor auth enabled - "auth.mfa_disabled", - // Multi-factor auth disabled - "auth.account_locked", - // Account locked (too many failures) - "auth.account_unlocked", - // Account unlocked - // Authorization Events - "authz.permission_granted", - // Permission granted to user - "authz.permission_revoked", - // Permission revoked from user - "authz.role_assigned", - // Role assigned to user - "authz.role_removed", - // Role removed from user - "authz.role_created", - // New role created - "authz.role_updated", - // Role permissions modified - "authz.role_deleted", - // Role deleted - "authz.policy_created", - // Security policy created - "authz.policy_updated", - // Security policy updated - "authz.policy_deleted", - // Security policy deleted - // System Events - "system.config_changed", - // System configuration modified - "system.plugin_installed", - // Plugin installed - "system.plugin_uninstalled", - // Plugin uninstalled - "system.backup_created", - // Backup created - "system.backup_restored", - // Backup restored - "system.integration_added", - // External integration added - "system.integration_removed", - // External integration removed - // Security Events - "security.access_denied", - // Access denied (authorization failure) - "security.suspicious_activity", - // Suspicious activity detected - "security.data_breach", - // Potential data breach detected - "security.api_key_created", - // API key created - "security.api_key_revoked" - // API key revoked -]); -var AuditEventSeverity2 = external_exports.enum([ - "debug", - // Diagnostic information - "info", - // Informational events (normal operations) - "notice", - // Normal but significant events - "warning", - // Warning conditions - "error", - // Error conditions - "critical", - // Critical conditions requiring immediate attention - "alert", - // Action must be taken immediately - "emergency" - // System is unusable -]); -var AuditEventActorSchema2 = external_exports.object({ - /** - * Actor type (user, system, service, api_client, etc.) - */ - type: external_exports.enum(["user", "system", "service", "api_client", "integration"]).describe("Actor type"), - /** - * Unique identifier for the actor - */ - id: external_exports.string().describe("Actor identifier"), - /** - * Display name of the actor - */ - name: external_exports.string().optional().describe("Actor display name"), - /** - * Email address (for user actors) - */ - email: external_exports.string().email().optional().describe("Actor email address"), - /** - * IP address of the actor - */ - ipAddress: external_exports.string().optional().describe("Actor IP address"), - /** - * User agent string (for web/API requests) - */ - userAgent: external_exports.string().optional().describe("User agent string") -}); -var AuditEventTargetSchema2 = external_exports.object({ - /** - * Target type (e.g., 'object', 'record', 'user', 'role', 'config') - */ - type: external_exports.string().describe("Target type"), - /** - * Unique identifier for the target - */ - id: external_exports.string().describe("Target identifier"), - /** - * Display name of the target - */ - name: external_exports.string().optional().describe("Target display name"), - /** - * Additional metadata about the target - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Target metadata") -}); -var AuditEventChangeSchema2 = external_exports.object({ - /** - * Field/property that changed - */ - field: external_exports.string().describe("Changed field name"), - /** - * Value before the change - */ - oldValue: external_exports.unknown().optional().describe("Previous value"), - /** - * Value after the change - */ - newValue: external_exports.unknown().optional().describe("New value") -}); -var AuditEventSchema2 = external_exports.object({ - /** - * Unique identifier for this audit event - */ - id: external_exports.string().describe("Audit event ID"), - /** - * Type of event being audited - */ - eventType: AuditEventType2.describe("Event type"), - /** - * Severity level of the event - */ - severity: AuditEventSeverity2.default("info").describe("Event severity"), - /** - * Timestamp when the event occurred (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("Event timestamp"), - /** - * Who/what performed the action - */ - actor: AuditEventActorSchema2.describe("Event actor"), - /** - * What was acted upon - */ - target: AuditEventTargetSchema2.optional().describe("Event target"), - /** - * Human-readable description of the action - */ - description: external_exports.string().describe("Event description"), - /** - * Detailed changes (for update operations) - */ - changes: external_exports.array(AuditEventChangeSchema2).optional().describe("List of changes"), - /** - * Result of the action (success, failure, partial) - */ - result: external_exports.enum(["success", "failure", "partial"]).default("success").describe("Action result"), - /** - * Error message (if result is failure) - */ - errorMessage: external_exports.string().optional().describe("Error message"), - /** - * Tenant identifier (for multi-tenant systems) - */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** - * Request/trace ID for correlation - */ - requestId: external_exports.string().optional().describe("Request ID for tracing"), - /** - * Additional context and metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata"), - /** - * Geographic location (if available) - */ - location: external_exports.object({ - country: external_exports.string().optional(), - region: external_exports.string().optional(), - city: external_exports.string().optional() - }).optional().describe("Geographic location") -}); -var AuditRetentionPolicySchema2 = external_exports.object({ - /** - * Retention period in days - * Default: 180 days (GDPR 6-month requirement) - */ - retentionDays: external_exports.number().int().min(1).default(180).describe("Retention period in days"), - /** - * Whether to archive logs after retention period - * If true, logs are moved to cold storage; if false, they are deleted - */ - archiveAfterRetention: external_exports.boolean().default(true).describe("Archive logs after retention period"), - /** - * Archive storage configuration - */ - archiveStorage: external_exports.object({ - type: external_exports.enum(["s3", "gcs", "azure_blob", "filesystem"]).describe("Archive storage type"), - endpoint: external_exports.string().optional().describe("Storage endpoint URL"), - bucket: external_exports.string().optional().describe("Storage bucket/container name"), - path: external_exports.string().optional().describe("Storage path prefix"), - credentials: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage credentials") - }).optional().describe("Archive storage configuration"), - /** - * Event types that have different retention periods - * Overrides the default retentionDays for specific event types - */ - customRetention: external_exports.record(external_exports.string(), external_exports.number().int().positive()).optional().describe("Custom retention by event type"), - /** - * Minimum retention period for compliance - * Prevents accidental deletion below compliance requirements - */ - minimumRetentionDays: external_exports.number().int().positive().optional().describe("Minimum retention for compliance") -}); -var SuspiciousActivityRuleSchema2 = external_exports.object({ - /** - * Unique identifier for the rule - */ - id: external_exports.string().describe("Rule identifier"), - /** - * Rule name - */ - name: external_exports.string().describe("Rule name"), - /** - * Rule description - */ - description: external_exports.string().optional().describe("Rule description"), - /** - * Whether the rule is enabled - */ - enabled: external_exports.boolean().default(true).describe("Rule enabled status"), - /** - * Event types to monitor - */ - eventTypes: external_exports.array(AuditEventType2).describe("Event types to monitor"), - /** - * Detection condition - */ - condition: external_exports.object({ - /** - * Number of events that trigger the rule - */ - threshold: external_exports.number().int().positive().describe("Event threshold"), - /** - * Time window in seconds - */ - windowSeconds: external_exports.number().int().positive().describe("Time window in seconds"), - /** - * Grouping criteria (e.g., by actor.id, by ipAddress) - */ - groupBy: external_exports.array(external_exports.string()).optional().describe("Grouping criteria"), - /** - * Additional filters - */ - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional filters") - }).describe("Detection condition"), - /** - * Actions to take when rule is triggered - */ - actions: external_exports.array(external_exports.enum([ - "alert", - // Send alert notification - "lock_account", - // Lock the user account - "block_ip", - // Block the IP address - "require_mfa", - // Require multi-factor authentication - "log_critical", - // Log as critical event - "webhook" - // Call webhook - ])).describe("Actions to take"), - /** - * Severity level for triggered alerts - */ - alertSeverity: AuditEventSeverity2.default("warning").describe("Alert severity"), - /** - * Notification configuration - */ - notifications: external_exports.object({ - /** - * Email addresses to notify - */ - email: external_exports.array(external_exports.string().email()).optional().describe("Email recipients"), - /** - * Slack webhook URL - */ - slack: external_exports.string().url().optional().describe("Slack webhook URL"), - /** - * Custom webhook URL - */ - webhook: external_exports.string().url().optional().describe("Custom webhook URL") - }).optional().describe("Notification configuration") -}); -var AuditStorageConfigSchema2 = external_exports.object({ - /** - * Storage backend type - */ - type: external_exports.enum([ - "database", - // Store in database (PostgreSQL, MySQL, etc.) - "elasticsearch", - // Store in Elasticsearch - "mongodb", - // Store in MongoDB - "clickhouse", - // Store in ClickHouse (for analytics) - "s3", - // Store in S3-compatible storage - "gcs", - // Store in Google Cloud Storage - "azure_blob", - // Store in Azure Blob Storage - "custom" - // Custom storage implementation - ]).describe("Storage backend type"), - /** - * Connection string or configuration - */ - connectionString: external_exports.string().optional().describe("Connection string"), - /** - * Storage configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage-specific configuration"), - /** - * Whether to enable buffering/batching - */ - bufferEnabled: external_exports.boolean().default(true).describe("Enable buffering"), - /** - * Buffer size (number of events before flush) - */ - bufferSize: external_exports.number().int().positive().default(100).describe("Buffer size"), - /** - * Buffer flush interval in seconds - */ - flushIntervalSeconds: external_exports.number().int().positive().default(5).describe("Flush interval in seconds"), - /** - * Whether to compress stored data - */ - compression: external_exports.boolean().default(true).describe("Enable compression") -}); -var AuditEventFilterSchema2 = external_exports.object({ - /** - * Filter by event types - */ - eventTypes: external_exports.array(AuditEventType2).optional().describe("Event types to include"), - /** - * Filter by severity levels - */ - severities: external_exports.array(AuditEventSeverity2).optional().describe("Severity levels to include"), - /** - * Filter by actor ID - */ - actorId: external_exports.string().optional().describe("Actor identifier"), - /** - * Filter by tenant ID - */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** - * Filter by time range - */ - timeRange: external_exports.object({ - from: external_exports.string().datetime().describe("Start time"), - to: external_exports.string().datetime().describe("End time") - }).optional().describe("Time range filter"), - /** - * Filter by result status - */ - result: external_exports.enum(["success", "failure", "partial"]).optional().describe("Result status"), - /** - * Search query (full-text search) - */ - searchQuery: external_exports.string().optional().describe("Search query"), - /** - * Custom filters - */ - customFilters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom filters") -}); -var AuditConfigSchema2 = external_exports.object({ - /** - * Unique identifier for this audit configuration - * Must be in snake_case following ObjectStack conventions - * Maximum length: 64 characters - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), - /** - * Human-readable label - */ - label: external_exports.string().describe("Display label"), - /** - * Whether audit logging is enabled - */ - enabled: external_exports.boolean().default(true).describe("Enable audit logging"), - /** - * Event types to audit - * If not specified, all event types are audited - */ - eventTypes: external_exports.array(AuditEventType2).optional().describe("Event types to audit"), - /** - * Event types to exclude from auditing - */ - excludeEventTypes: external_exports.array(AuditEventType2).optional().describe("Event types to exclude"), - /** - * Minimum severity level to log - * Events below this level are not logged - */ - minimumSeverity: AuditEventSeverity2.default("info").describe("Minimum severity level"), - /** - * Storage configuration - */ - storage: AuditStorageConfigSchema2.describe("Storage configuration"), - /** - * Retention policy - */ - retentionPolicy: AuditRetentionPolicySchema2.optional().describe("Retention policy"), - /** - * Suspicious activity detection rules - */ - suspiciousActivityRules: external_exports.array(SuspiciousActivityRuleSchema2).default([]).describe("Suspicious activity rules"), - /** - * Whether to include sensitive data in audit logs - * If false, sensitive fields are redacted/masked - */ - includeSensitiveData: external_exports.boolean().default(false).describe("Include sensitive data"), - /** - * Fields to redact from audit logs - */ - redactFields: external_exports.array(external_exports.string()).default([ - "password", - "passwordHash", - "token", - "apiKey", - "secret", - "creditCard", - "ssn" - ]).describe("Fields to redact"), - /** - * Whether to log successful read operations - * Can be disabled to reduce log volume - */ - logReads: external_exports.boolean().default(false).describe("Log read operations"), - /** - * Sampling rate for read operations (0.0 to 1.0) - * Only applies if logReads is true - */ - readSamplingRate: external_exports.number().min(0).max(1).default(0.1).describe("Read sampling rate"), - /** - * Whether to log system/internal operations - */ - logSystemEvents: external_exports.boolean().default(true).describe("Log system events"), - /** - * Custom audit event handlers - * Note: Function handlers are for runtime configuration only and will not be serialized to JSON Schema - */ - customHandlers: external_exports.array(external_exports.object({ - eventType: AuditEventType2.describe("Event type to handle"), - handlerId: external_exports.string().describe("Unique identifier for the handler") - })).optional().describe("Custom event handler references"), - /** - * Compliance mode configuration - */ - compliance: external_exports.object({ - /** - * Compliance standards to enforce - */ - standards: external_exports.array(external_exports.enum([ - "sox", - // Sarbanes-Oxley Act - "hipaa", - // Health Insurance Portability and Accountability Act - "gdpr", - // General Data Protection Regulation - "pci_dss", - // Payment Card Industry Data Security Standard - "iso_27001", - // ISO/IEC 27001 - "fedramp" - // Federal Risk and Authorization Management Program - ])).optional().describe("Compliance standards"), - /** - * Whether to enforce immutable audit logs - */ - immutableLogs: external_exports.boolean().default(true).describe("Enforce immutable logs"), - /** - * Whether to require cryptographic signing - */ - requireSigning: external_exports.boolean().default(false).describe("Require log signing"), - /** - * Signing key configuration - */ - signingKey: external_exports.string().optional().describe("Signing key") - }).optional().describe("Compliance configuration") -}); -var DEFAULT_SUSPICIOUS_ACTIVITY_RULES = [ - { - id: "multiple_failed_logins", - name: "Multiple Failed Login Attempts", - description: "Detects multiple failed login attempts from the same user or IP", - enabled: true, - eventTypes: ["auth.login_failed"], - condition: { - threshold: 5, - windowSeconds: 600, - // 10 minutes - groupBy: ["actor.id", "actor.ipAddress"] - }, - actions: ["alert", "lock_account"], - alertSeverity: "warning" - }, - { - id: "bulk_data_export", - name: "Bulk Data Export", - description: "Detects large data export operations", - enabled: true, - eventTypes: ["data.export"], - condition: { - threshold: 3, - windowSeconds: 3600, - // 1 hour - groupBy: ["actor.id"] - }, - actions: ["alert", "log_critical"], - alertSeverity: "warning" - }, - { - id: "suspicious_permission_changes", - name: "Rapid Permission Changes", - description: "Detects rapid permission or role changes", - enabled: true, - eventTypes: ["authz.permission_granted", "authz.role_assigned"], - condition: { - threshold: 10, - windowSeconds: 300, - // 5 minutes - groupBy: ["actor.id"] - }, - actions: ["alert", "log_critical"], - alertSeverity: "critical" - }, - { - id: "after_hours_access", - name: "After Hours Access", - description: "Detects access during non-business hours", - enabled: false, - // Disabled by default, requires time zone configuration - eventTypes: ["auth.login"], - condition: { - threshold: 1, - windowSeconds: 86400 - // 24 hours - }, - actions: ["alert"], - alertSeverity: "notice" - } -]; -var LogLevel2 = external_exports.enum([ - "debug", - "info", - "warn", - "error", - "fatal", - "silent" -]).describe("Log severity level"); -var LogFormat2 = external_exports.enum([ - "json", - // Structured JSON for machine parsing - "text", - // Simple text format - "pretty" - // Colored human-readable output for CLI/console -]).describe("Log output format"); -var LoggerConfigSchema2 = external_exports.object({ - /** - * Logger name - */ - name: external_exports.string().optional().describe("Logger name identifier"), - /** - * Minimum level to log - */ - level: LogLevel2.optional().default("info"), - /** - * Output format - */ - format: LogFormat2.optional().default("json"), - /** - * Redact sensitive keys - */ - redact: external_exports.array(external_exports.string()).optional().default(["password", "token", "secret", "key"]).describe("Keys to redact from log context"), - /** - * Enable source location (file/line) - */ - sourceLocation: external_exports.boolean().optional().default(false).describe("Include file and line number"), - /** - * Log to file (optional) - */ - file: external_exports.string().optional().describe("Path to log file"), - /** - * Log rotation config (if file is set) - */ - rotation: external_exports.object({ - maxSize: external_exports.string().optional().default("10m"), - maxFiles: external_exports.number().optional().default(5) - }).optional() -}); -var LogEntrySchema2 = external_exports.object({ - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), - level: LogLevel2, - message: external_exports.string().describe("Log message"), - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Structured context data"), - error: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Error object if present"), - /** Tracing */ - traceId: external_exports.string().optional().describe("Distributed trace ID"), - spanId: external_exports.string().optional().describe("Span ID"), - /** Source */ - service: external_exports.string().optional().describe("Service name"), - component: external_exports.string().optional().describe("Component name (e.g. plugin id)") -}); -var ExtendedLogLevel2 = external_exports.enum([ - "trace", - // Very detailed debugging information - "debug", - // Debugging information - "info", - // Informational messages - "warn", - // Warning messages - "error", - // Error messages - "fatal" - // Fatal errors causing shutdown -]).describe("Extended log severity level"); -var LogDestinationType2 = external_exports.enum([ - "console", - // Standard output/error - "file", - // File system - "syslog", - // System logger - "elasticsearch", - // Elasticsearch - "cloudwatch", - // AWS CloudWatch - "stackdriver", - // Google Cloud Logging - "azure_monitor", - // Azure Monitor - "datadog", - // Datadog - "splunk", - // Splunk - "loki", - // Grafana Loki - "http", - // HTTP endpoint - "kafka", - // Apache Kafka - "redis", - // Redis streams - "custom" - // Custom implementation -]).describe("Log destination type"); -var ConsoleDestinationConfigSchema2 = external_exports.object({ - /** - * Output stream - */ - stream: external_exports.enum(["stdout", "stderr"]).optional().default("stdout"), - /** - * Enable colored output - */ - colors: external_exports.boolean().optional().default(true), - /** - * Pretty print JSON - */ - prettyPrint: external_exports.boolean().optional().default(false) -}).describe("Console destination configuration"); -var FileDestinationConfigSchema2 = external_exports.object({ - /** - * File path - */ - path: external_exports.string().describe("Log file path"), - /** - * Enable log rotation - */ - rotation: external_exports.object({ - /** - * Maximum file size before rotation (e.g., '10m', '100k', '1g') - */ - maxSize: external_exports.string().optional().default("10m"), - /** - * Maximum number of files to keep - */ - maxFiles: external_exports.number().int().positive().optional().default(5), - /** - * Compress rotated files - */ - compress: external_exports.boolean().optional().default(true), - /** - * Rotation interval (e.g., 'daily', 'weekly') - */ - interval: external_exports.enum(["hourly", "daily", "weekly", "monthly"]).optional() - }).optional(), - /** - * File encoding - */ - encoding: external_exports.string().optional().default("utf8"), - /** - * Append to existing file - */ - append: external_exports.boolean().optional().default(true) -}).describe("File destination configuration"); -var HttpDestinationConfigSchema2 = external_exports.object({ - /** - * HTTP endpoint URL - */ - url: external_exports.string().url().describe("HTTP endpoint URL"), - /** - * HTTP method - */ - method: external_exports.enum(["POST", "PUT"]).optional().default("POST"), - /** - * Headers to include - */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional(), - /** - * Authentication - */ - auth: external_exports.object({ - type: external_exports.enum(["basic", "bearer", "api_key"]).describe("Auth type"), - username: external_exports.string().optional(), - password: external_exports.string().optional(), - token: external_exports.string().optional(), - apiKey: external_exports.string().optional(), - apiKeyHeader: external_exports.string().optional().default("X-API-Key") - }).optional(), - /** - * Batch configuration - */ - batch: external_exports.object({ - /** - * Maximum batch size - */ - maxSize: external_exports.number().int().positive().optional().default(100), - /** - * Flush interval in milliseconds - */ - flushInterval: external_exports.number().int().positive().optional().default(5e3) - }).optional(), - /** - * Retry configuration - */ - retry: external_exports.object({ - /** - * Maximum retry attempts - */ - maxAttempts: external_exports.number().int().positive().optional().default(3), - /** - * Initial retry delay in milliseconds - */ - initialDelay: external_exports.number().int().positive().optional().default(1e3), - /** - * Backoff multiplier - */ - backoffMultiplier: external_exports.number().positive().optional().default(2) - }).optional(), - /** - * Timeout in milliseconds - */ - timeout: external_exports.number().int().positive().optional().default(3e4) -}).describe("HTTP destination configuration"); -var ExternalServiceDestinationConfigSchema2 = external_exports.object({ - /** - * Service-specific endpoint - */ - endpoint: external_exports.string().url().optional(), - /** - * Region (for cloud services) - */ - region: external_exports.string().optional(), - /** - * Credentials - */ - credentials: external_exports.object({ - accessKeyId: external_exports.string().optional(), - secretAccessKey: external_exports.string().optional(), - apiKey: external_exports.string().optional(), - projectId: external_exports.string().optional() - }).optional(), - /** - * Log group/stream/index name - */ - logGroup: external_exports.string().optional(), - logStream: external_exports.string().optional(), - index: external_exports.string().optional(), - /** - * Service-specific configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}).describe("External service destination configuration"); -var LogDestinationSchema2 = external_exports.object({ - /** - * Destination name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Destination name (snake_case)"), - /** - * Destination type - */ - type: LogDestinationType2.describe("Destination type"), - /** - * Minimum log level for this destination - */ - level: ExtendedLogLevel2.optional().default("info"), - /** - * Enabled flag - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Console configuration - */ - console: ConsoleDestinationConfigSchema2.optional(), - /** - * File configuration - */ - file: FileDestinationConfigSchema2.optional(), - /** - * HTTP configuration - */ - http: HttpDestinationConfigSchema2.optional(), - /** - * External service configuration - */ - externalService: ExternalServiceDestinationConfigSchema2.optional(), - /** - * Format for this destination - */ - format: external_exports.enum(["json", "text", "pretty"]).optional().default("json"), - /** - * Filter function reference (runtime only) - */ - filterId: external_exports.string().optional().describe("Filter function identifier") -}).describe("Log destination configuration"); -var LogEnrichmentConfigSchema2 = external_exports.object({ - /** - * Static fields to add to all logs - */ - staticFields: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Static fields added to every log"), - /** - * Dynamic field enrichers (runtime only) - * References to functions that add dynamic context - */ - dynamicEnrichers: external_exports.array(external_exports.string()).optional().describe("Dynamic enricher function IDs"), - /** - * Add hostname - */ - addHostname: external_exports.boolean().optional().default(true), - /** - * Add process ID - */ - addProcessId: external_exports.boolean().optional().default(true), - /** - * Add environment info - */ - addEnvironment: external_exports.boolean().optional().default(true), - /** - * Add timestamp in additional formats - */ - addTimestampFormats: external_exports.object({ - unix: external_exports.boolean().optional().default(false), - iso: external_exports.boolean().optional().default(true) - }).optional(), - /** - * Add caller information (file, line, function) - */ - addCaller: external_exports.boolean().optional().default(false), - /** - * Add correlation IDs - */ - addCorrelationIds: external_exports.boolean().optional().default(true) -}).describe("Log enrichment configuration"); -var StructuredLogEntrySchema2 = external_exports.object({ - /** - * Timestamp (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), - /** - * Log level - */ - level: ExtendedLogLevel2.describe("Log severity level"), - /** - * Log message - */ - message: external_exports.string().describe("Log message"), - /** - * Structured context data - */ - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Structured context"), - /** - * Error information - */ - error: external_exports.object({ - name: external_exports.string().optional(), - message: external_exports.string().optional(), - stack: external_exports.string().optional(), - code: external_exports.string().optional(), - details: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional().describe("Error details"), - /** - * Trace context - */ - trace: external_exports.object({ - traceId: external_exports.string().describe("Trace ID"), - spanId: external_exports.string().describe("Span ID"), - parentSpanId: external_exports.string().optional().describe("Parent span ID"), - traceFlags: external_exports.number().int().optional().describe("Trace flags") - }).optional().describe("Distributed tracing context"), - /** - * Source information - */ - source: external_exports.object({ - service: external_exports.string().optional().describe("Service name"), - component: external_exports.string().optional().describe("Component name"), - file: external_exports.string().optional().describe("Source file"), - line: external_exports.number().int().optional().describe("Line number"), - function: external_exports.string().optional().describe("Function name") - }).optional().describe("Source information"), - /** - * Host information - */ - host: external_exports.object({ - hostname: external_exports.string().optional(), - pid: external_exports.number().int().optional(), - ip: external_exports.string().optional() - }).optional().describe("Host information"), - /** - * Environment - */ - environment: external_exports.string().optional().describe("Environment (e.g., production, staging)"), - /** - * User information - */ - user: external_exports.object({ - id: external_exports.string().optional(), - username: external_exports.string().optional(), - email: external_exports.string().optional() - }).optional().describe("User context"), - /** - * Request information - */ - request: external_exports.object({ - id: external_exports.string().optional(), - method: external_exports.string().optional(), - path: external_exports.string().optional(), - userAgent: external_exports.string().optional(), - ip: external_exports.string().optional() - }).optional().describe("Request context"), - /** - * Custom labels/tags - */ - labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom labels"), - /** - * Additional metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata") -}).describe("Structured log entry"); -var LoggingConfigSchema2 = external_exports.object({ - /** - * Configuration name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Enable logging - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Global minimum log level - */ - level: ExtendedLogLevel2.optional().default("info"), - /** - * Default logger configuration - * Basic logger config for the kernel - */ - default: LoggerConfigSchema2.optional().describe("Default logger configuration"), - /** - * Named logger configurations - * Map of logger name to logger config for different components/modules - */ - loggers: external_exports.record(external_exports.string(), LoggerConfigSchema2).optional().describe("Named logger configurations"), - /** - * Log destinations - */ - destinations: external_exports.array(LogDestinationSchema2).describe("Log destinations"), - /** - * Log enrichment configuration - */ - enrichment: LogEnrichmentConfigSchema2.optional(), - /** - * Fields to redact from logs - */ - redact: external_exports.array(external_exports.string()).optional().default([ - "password", - "passwordHash", - "token", - "apiKey", - "secret", - "creditCard", - "ssn", - "authorization" - ]).describe("Fields to redact"), - /** - * Sampling configuration - */ - sampling: external_exports.object({ - /** - * Enable sampling - */ - enabled: external_exports.boolean().optional().default(false), - /** - * Sample rate (0.0 to 1.0) - */ - rate: external_exports.number().min(0).max(1).optional().default(1), - /** - * Sample rate by level - */ - rateByLevel: external_exports.record(external_exports.string(), external_exports.number().min(0).max(1)).optional() - }).optional(), - /** - * Buffer configuration - */ - buffer: external_exports.object({ - /** - * Enable buffering - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Buffer size - */ - size: external_exports.number().int().positive().optional().default(1e3), - /** - * Flush interval in milliseconds - */ - flushInterval: external_exports.number().int().positive().optional().default(1e3), - /** - * Flush on shutdown - */ - flushOnShutdown: external_exports.boolean().optional().default(true) - }).optional(), - /** - * Performance configuration - */ - performance: external_exports.object({ - /** - * Async logging - */ - async: external_exports.boolean().optional().default(true), - /** - * Worker threads for async logging - */ - workers: external_exports.number().int().positive().optional().default(1) - }).optional() -}).describe("Logging configuration"); -var MetricType2 = external_exports.enum([ - "counter", - // Monotonically increasing value - "gauge", - // Value that can go up and down - "histogram", - // Observations bucketed by configurable ranges - "summary" - // Observations with quantiles -]).describe("Metric type"); -var MetricUnit2 = external_exports.enum([ - // Time units - "nanoseconds", - "microseconds", - "milliseconds", - "seconds", - "minutes", - "hours", - "days", - // Size units - "bytes", - "kilobytes", - "megabytes", - "gigabytes", - "terabytes", - // Rate units - "requests_per_second", - "events_per_second", - "bytes_per_second", - // Percentage - "percent", - "ratio", - // Count - "count", - "operations", - // Custom - "custom" -]).describe("Metric unit"); -var MetricAggregationType2 = external_exports.enum([ - "sum", - // Sum of all values - "avg", - // Average of all values - "min", - // Minimum value - "max", - // Maximum value - "count", - // Count of observations - "p50", - // 50th percentile (median) - "p75", - // 75th percentile - "p90", - // 90th percentile - "p95", - // 95th percentile - "p99", - // 99th percentile - "p999", - // 99.9th percentile - "rate", - // Rate of change - "stddev" - // Standard deviation -]).describe("Metric aggregation type"); -var HistogramBucketConfigSchema2 = external_exports.object({ - /** - * Bucket type - */ - type: external_exports.enum(["linear", "exponential", "explicit"]).describe("Bucket type"), - /** - * Linear bucket configuration - */ - linear: external_exports.object({ - start: external_exports.number().describe("Start value"), - width: external_exports.number().positive().describe("Bucket width"), - count: external_exports.number().int().positive().describe("Number of buckets") - }).optional(), - /** - * Exponential bucket configuration - */ - exponential: external_exports.object({ - start: external_exports.number().positive().describe("Start value"), - factor: external_exports.number().positive().describe("Growth factor"), - count: external_exports.number().int().positive().describe("Number of buckets") - }).optional(), - /** - * Explicit bucket boundaries - */ - explicit: external_exports.object({ - boundaries: external_exports.array(external_exports.number()).describe("Bucket boundaries") - }).optional() -}).describe("Histogram bucket configuration"); -var MetricLabelsSchema2 = external_exports.record(external_exports.string(), external_exports.string()).describe("Metric labels"); -var MetricDefinitionSchema2 = external_exports.object({ - /** - * Metric name (snake_case) - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Metric name (snake_case)"), - /** - * Display label - */ - label: external_exports.string().optional().describe("Display label"), - /** - * Metric type - */ - type: MetricType2.describe("Metric type"), - /** - * Metric unit - */ - unit: MetricUnit2.optional().describe("Metric unit"), - /** - * Description - */ - description: external_exports.string().optional().describe("Metric description"), - /** - * Label names for this metric - */ - labelNames: external_exports.array(external_exports.string()).optional().default([]).describe("Label names"), - /** - * Histogram configuration (for histogram type) - */ - histogram: HistogramBucketConfigSchema2.optional(), - /** - * Summary configuration (for summary type) - */ - summary: external_exports.object({ - /** - * Quantiles to track - */ - quantiles: external_exports.array(external_exports.number().min(0).max(1)).optional().default([0.5, 0.9, 0.99]), - /** - * Max age of observations in seconds - */ - maxAge: external_exports.number().int().positive().optional().default(600), - /** - * Number of age buckets - */ - ageBuckets: external_exports.number().int().positive().optional().default(5) - }).optional(), - /** - * Enabled flag - */ - enabled: external_exports.boolean().optional().default(true) -}).describe("Metric definition"); -var MetricDataPointSchema2 = external_exports.object({ - /** - * Metric name - */ - name: external_exports.string().describe("Metric name"), - /** - * Metric type - */ - type: MetricType2.describe("Metric type"), - /** - * Timestamp (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("Observation timestamp"), - /** - * Value (for counter and gauge) - */ - value: external_exports.number().optional().describe("Metric value"), - /** - * Labels - */ - labels: MetricLabelsSchema2.optional().describe("Metric labels"), - /** - * Histogram data - */ - histogram: external_exports.object({ - count: external_exports.number().int().nonnegative().describe("Total count"), - sum: external_exports.number().describe("Sum of all values"), - buckets: external_exports.array(external_exports.object({ - upperBound: external_exports.number().describe("Upper bound of bucket"), - count: external_exports.number().int().nonnegative().describe("Count in bucket") - })).describe("Histogram buckets") - }).optional(), - /** - * Summary data - */ - summary: external_exports.object({ - count: external_exports.number().int().nonnegative().describe("Total count"), - sum: external_exports.number().describe("Sum of all values"), - quantiles: external_exports.array(external_exports.object({ - quantile: external_exports.number().min(0).max(1).describe("Quantile (0-1)"), - value: external_exports.number().describe("Quantile value") - })).describe("Summary quantiles") - }).optional() -}).describe("Metric data point"); -var TimeSeriesDataPointSchema2 = external_exports.object({ - /** - * Timestamp (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("Timestamp"), - /** - * Value - */ - value: external_exports.number().describe("Value"), - /** - * Labels/tags - */ - labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Labels") -}).describe("Time series data point"); -var TimeSeriesSchema2 = external_exports.object({ - /** - * Series name - */ - name: external_exports.string().describe("Series name"), - /** - * Series labels - */ - labels: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Series labels"), - /** - * Data points - */ - dataPoints: external_exports.array(TimeSeriesDataPointSchema2).describe("Data points"), - /** - * Start time - */ - startTime: external_exports.string().datetime().optional().describe("Start time"), - /** - * End time - */ - endTime: external_exports.string().datetime().optional().describe("End time") -}).describe("Time series"); -var MetricAggregationConfigSchema2 = external_exports.object({ - /** - * Aggregation type - */ - type: MetricAggregationType2.describe("Aggregation type"), - /** - * Time window for aggregation - */ - window: external_exports.object({ - /** - * Window size in seconds - */ - size: external_exports.number().int().positive().describe("Window size in seconds"), - /** - * Sliding window (true) or tumbling window (false) - */ - sliding: external_exports.boolean().optional().default(false), - /** - * Slide interval for sliding windows - */ - slideInterval: external_exports.number().int().positive().optional() - }).optional(), - /** - * Group by labels - */ - groupBy: external_exports.array(external_exports.string()).optional().describe("Group by label names"), - /** - * Filters - */ - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria") -}).describe("Metric aggregation configuration"); -var ServiceLevelIndicatorSchema2 = external_exports.object({ - /** - * SLI name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("SLI name (snake_case)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Description - */ - description: external_exports.string().optional().describe("SLI description"), - /** - * Metric name this SLI is based on - */ - metric: external_exports.string().describe("Base metric name"), - /** - * SLI type - */ - type: external_exports.enum([ - "availability", - // Percentage of successful requests - "latency", - // Response time percentile - "throughput", - // Requests per second - "error_rate", - // Error percentage - "saturation", - // Resource utilization - "custom" - // Custom calculation - ]).describe("SLI type"), - /** - * Success criteria - */ - successCriteria: external_exports.object({ - /** - * Threshold value - */ - threshold: external_exports.number().describe("Threshold value"), - /** - * Comparison operator - */ - operator: external_exports.enum(["lt", "lte", "gt", "gte", "eq"]).describe("Comparison operator"), - /** - * Percentile (for latency SLIs) - */ - percentile: external_exports.number().min(0).max(1).optional().describe("Percentile (0-1)") - }).describe("Success criteria"), - /** - * Measurement window - */ - window: external_exports.object({ - /** - * Window size in seconds - */ - size: external_exports.number().int().positive().describe("Window size in seconds"), - /** - * Rolling window (true) or calendar-aligned (false) - */ - rolling: external_exports.boolean().optional().default(true) - }).describe("Measurement window"), - /** - * Enabled flag - */ - enabled: external_exports.boolean().optional().default(true) -}).describe("Service Level Indicator"); -var ServiceLevelObjectiveSchema2 = external_exports.object({ - /** - * SLO name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("SLO name (snake_case)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Description - */ - description: external_exports.string().optional().describe("SLO description"), - /** - * SLI this SLO is based on - */ - sli: external_exports.string().describe("SLI name"), - /** - * Target percentage (0-100) - */ - target: external_exports.number().min(0).max(100).describe("Target percentage"), - /** - * Time period for SLO - */ - period: external_exports.object({ - /** - * Period type - */ - type: external_exports.enum(["rolling", "calendar"]).describe("Period type"), - /** - * Duration in seconds (for rolling) - */ - duration: external_exports.number().int().positive().optional().describe("Duration in seconds"), - /** - * Calendar period (for calendar) - */ - calendar: external_exports.enum(["daily", "weekly", "monthly", "quarterly", "yearly"]).optional() - }).describe("Time period"), - /** - * Error budget configuration - */ - errorBudget: external_exports.object({ - /** - * Auto-calculated budget (1 - target) - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Alert when budget consumed percentage exceeds threshold - */ - alertThreshold: external_exports.number().min(0).max(100).optional().default(80), - /** - * Burn rate alert windows - */ - burnRateWindows: external_exports.array(external_exports.object({ - /** - * Window size in seconds - */ - window: external_exports.number().int().positive().describe("Window size"), - /** - * Burn rate multiplier threshold - */ - threshold: external_exports.number().positive().describe("Burn rate threshold") - })).optional() - }).optional(), - /** - * Alert configuration - */ - alerts: external_exports.array(external_exports.object({ - /** - * Alert name - */ - name: external_exports.string().describe("Alert name"), - /** - * Severity - */ - severity: external_exports.enum(["info", "warning", "critical"]).describe("Alert severity"), - /** - * Condition - */ - condition: external_exports.object({ - type: external_exports.enum(["slo_breach", "error_budget", "burn_rate"]).describe("Condition type"), - threshold: external_exports.number().optional().describe("Threshold value") - }).describe("Alert condition") - })).optional().default([]), - /** - * Enabled flag - */ - enabled: external_exports.boolean().optional().default(true) -}).describe("Service Level Objective"); -var MetricExportConfigSchema2 = external_exports.object({ - /** - * Export type - */ - type: external_exports.enum([ - "prometheus", - // Prometheus exposition format - "openmetrics", - // OpenMetrics format - "graphite", - // Graphite plaintext protocol - "statsd", - // StatsD protocol - "influxdb", - // InfluxDB line protocol - "datadog", - // Datadog agent - "cloudwatch", - // AWS CloudWatch - "stackdriver", - // Google Cloud Monitoring - "azure_monitor", - // Azure Monitor - "http", - // HTTP push - "custom" - // Custom exporter - ]).describe("Export type"), - /** - * Endpoint configuration - */ - endpoint: external_exports.string().optional().describe("Export endpoint"), - /** - * Export interval in seconds - */ - interval: external_exports.number().int().positive().optional().default(60), - /** - * Batch configuration - */ - batch: external_exports.object({ - enabled: external_exports.boolean().optional().default(true), - size: external_exports.number().int().positive().optional().default(1e3) - }).optional(), - /** - * Authentication - */ - auth: external_exports.object({ - type: external_exports.enum(["none", "basic", "bearer", "api_key"]).describe("Auth type"), - username: external_exports.string().optional(), - password: external_exports.string().optional(), - token: external_exports.string().optional(), - apiKey: external_exports.string().optional() - }).optional(), - /** - * Additional configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional configuration") -}).describe("Metric export configuration"); -var MetricsConfigSchema2 = external_exports.object({ - /** - * Configuration name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Enable metrics collection - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Metric definitions - */ - metrics: external_exports.array(MetricDefinitionSchema2).optional().default([]), - /** - * Default labels applied to all metrics - */ - defaultLabels: MetricLabelsSchema2.optional().default({}), - /** - * Aggregation configurations - */ - aggregations: external_exports.array(MetricAggregationConfigSchema2).optional().default([]), - /** - * Service Level Indicators - */ - slis: external_exports.array(ServiceLevelIndicatorSchema2).optional().default([]), - /** - * Service Level Objectives - */ - slos: external_exports.array(ServiceLevelObjectiveSchema2).optional().default([]), - /** - * Export configurations - */ - exports: external_exports.array(MetricExportConfigSchema2).optional().default([]), - /** - * Collection interval in seconds - */ - collectionInterval: external_exports.number().int().positive().optional().default(15), - /** - * Retention configuration - */ - retention: external_exports.object({ - /** - * Retention period in seconds - */ - period: external_exports.number().int().positive().optional().default(604800), - // 7 days - /** - * Downsampling configuration - */ - downsampling: external_exports.array(external_exports.object({ - /** - * After this duration, downsample to this resolution - */ - afterSeconds: external_exports.number().int().positive().describe("Downsample after seconds"), - /** - * Resolution in seconds - */ - resolution: external_exports.number().int().positive().describe("Downsampled resolution") - })).optional() - }).optional(), - /** - * Cardinality limits - */ - cardinalityLimits: external_exports.object({ - /** - * Maximum unique label combinations per metric - */ - maxLabelCombinations: external_exports.number().int().positive().optional().default(1e4), - /** - * Action when limit exceeded - */ - onLimitExceeded: external_exports.enum(["drop", "sample", "alert"]).optional().default("alert") - }).optional() -}).describe("Metrics configuration"); -var TraceStateSchema2 = external_exports.object({ - /** - * Vendor-specific key-value pairs - */ - entries: external_exports.record(external_exports.string(), external_exports.string()).describe("Trace state entries") -}).describe("Trace state"); -var TraceFlagsSchema2 = external_exports.number().int().min(0).max(255).describe("Trace flags bitmap"); -var TraceContextSchema2 = external_exports.object({ - /** - * Trace ID (128-bit identifier, 32 hex chars) - */ - traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).describe("Trace ID (32 hex chars)"), - /** - * Span ID (64-bit identifier, 16 hex chars) - */ - spanId: external_exports.string().regex(/^[0-9a-f]{16}$/).describe("Span ID (16 hex chars)"), - /** - * Trace flags (8-bit) - */ - traceFlags: TraceFlagsSchema2.optional().default(1), - /** - * Trace state (vendor-specific) - */ - traceState: TraceStateSchema2.optional(), - /** - * Parent span ID - */ - parentSpanId: external_exports.string().regex(/^[0-9a-f]{16}$/).optional().describe("Parent span ID (16 hex chars)"), - /** - * Is sampled - */ - sampled: external_exports.boolean().optional().default(true), - /** - * Remote context (from incoming request) - */ - remote: external_exports.boolean().optional().default(false) -}).describe("Trace context (W3C Trace Context)"); -var SpanKind2 = external_exports.enum([ - "internal", - // Internal operation - "server", - // Server-side request handling - "client", - // Client-side request - "producer", - // Message producer - "consumer" - // Message consumer -]).describe("Span kind"); -var SpanStatus2 = external_exports.enum([ - "unset", - // Default status - "ok", - // Successful operation - "error" - // Error occurred -]).describe("Span status"); -var SpanAttributeValueSchema2 = external_exports.union([ - external_exports.string(), - external_exports.number(), - external_exports.boolean(), - external_exports.array(external_exports.string()), - external_exports.array(external_exports.number()), - external_exports.array(external_exports.boolean()) -]).describe("Span attribute value"); -var SpanAttributesSchema2 = external_exports.record(external_exports.string(), SpanAttributeValueSchema2).describe("Span attributes"); -var SpanEventSchema2 = external_exports.object({ - /** - * Event name - */ - name: external_exports.string().describe("Event name"), - /** - * Event timestamp (ISO 8601) - */ - timestamp: external_exports.string().datetime().describe("Event timestamp"), - /** - * Event attributes - */ - attributes: SpanAttributesSchema2.optional().describe("Event attributes") -}).describe("Span event"); -var SpanLinkSchema2 = external_exports.object({ - /** - * Linked trace context - */ - context: TraceContextSchema2.describe("Linked trace context"), - /** - * Link attributes - */ - attributes: SpanAttributesSchema2.optional().describe("Link attributes") -}).describe("Span link"); -var SpanSchema2 = external_exports.object({ - /** - * Trace context - */ - context: TraceContextSchema2.describe("Trace context"), - /** - * Span name - */ - name: external_exports.string().describe("Span name"), - /** - * Span kind - */ - kind: SpanKind2.optional().default("internal"), - /** - * Start time (ISO 8601) - */ - startTime: external_exports.string().datetime().describe("Span start time"), - /** - * End time (ISO 8601) - */ - endTime: external_exports.string().datetime().optional().describe("Span end time"), - /** - * Duration in milliseconds - */ - duration: external_exports.number().nonnegative().optional().describe("Duration in milliseconds"), - /** - * Span status - */ - status: external_exports.object({ - code: SpanStatus2.describe("Status code"), - message: external_exports.string().optional().describe("Status message") - }).optional(), - /** - * Span attributes - */ - attributes: SpanAttributesSchema2.optional().default({}), - /** - * Span events - */ - events: external_exports.array(SpanEventSchema2).optional().default([]), - /** - * Span links - */ - links: external_exports.array(SpanLinkSchema2).optional().default([]), - /** - * Resource attributes - */ - resource: SpanAttributesSchema2.optional().describe("Resource attributes"), - /** - * Instrumentation library - */ - instrumentationLibrary: external_exports.object({ - name: external_exports.string().describe("Library name"), - version: external_exports.string().optional().describe("Library version") - }).optional() -}).describe("OpenTelemetry span"); -var SamplingDecision2 = external_exports.enum([ - "drop", - // Do not record or export - "record_only", - // Record but do not export - "record_and_sample" - // Record and export -]).describe("Sampling decision"); -var SamplingStrategyType2 = external_exports.enum([ - "always_on", - // Always sample - "always_off", - // Never sample - "trace_id_ratio", - // Sample based on trace ID ratio - "rate_limiting", - // Rate-limited sampling - "parent_based", - // Respect parent span sampling decision - "probability", - // Probability-based sampling - "composite", - // Combine multiple strategies - "custom" - // Custom sampling logic -]).describe("Sampling strategy type"); -var TraceSamplingConfigSchema2 = external_exports.object({ - /** - * Sampling strategy type - */ - type: SamplingStrategyType2.describe("Sampling strategy"), - /** - * Sample ratio (0.0 to 1.0) for trace_id_ratio and probability strategies - */ - ratio: external_exports.number().min(0).max(1).optional().describe("Sample ratio (0-1)"), - /** - * Rate limit (traces per second) for rate_limiting strategy - */ - rateLimit: external_exports.number().positive().optional().describe("Traces per second"), - /** - * Parent-based configuration - */ - parentBased: external_exports.object({ - /** - * Sampler to use when parent is sampled - */ - whenParentSampled: SamplingStrategyType2.optional().default("always_on"), - /** - * Sampler to use when parent is not sampled - */ - whenParentNotSampled: SamplingStrategyType2.optional().default("always_off"), - /** - * Sampler to use when there is no parent (root span) - */ - root: SamplingStrategyType2.optional().default("trace_id_ratio"), - /** - * Root sampler ratio - */ - rootRatio: external_exports.number().min(0).max(1).optional().default(0.1) - }).optional(), - /** - * Composite sampling (multiple strategies) - */ - composite: external_exports.array(external_exports.object({ - strategy: SamplingStrategyType2.describe("Strategy type"), - ratio: external_exports.number().min(0).max(1).optional(), - condition: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Condition for this strategy") - })).optional(), - /** - * Sampling rules - */ - rules: external_exports.array(external_exports.object({ - /** - * Rule name - */ - name: external_exports.string().describe("Rule name"), - /** - * Match condition - */ - match: external_exports.object({ - /** - * Service name pattern - */ - service: external_exports.string().optional(), - /** - * Span name pattern (regex) - */ - spanName: external_exports.string().optional(), - /** - * Attribute filters - */ - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional(), - /** - * Sampling decision for matching spans - */ - decision: SamplingDecision2.describe("Sampling decision"), - /** - * Sample rate for this rule - */ - rate: external_exports.number().min(0).max(1).optional() - })).optional().default([]), - /** - * Custom sampler ID (for custom strategy) - */ - customSamplerId: external_exports.string().optional().describe("Custom sampler identifier") -}).describe("Trace sampling configuration"); -var TracePropagationFormat2 = external_exports.enum([ - "w3c", - // W3C Trace Context - "b3", - // Zipkin B3 (single header) - "b3_multi", - // Zipkin B3 (multi header) - "jaeger", - // Jaeger propagation - "xray", - // AWS X-Ray - "ottrace", - // OpenTracing - "custom" - // Custom format -]).describe("Trace propagation format"); -var TraceContextPropagationSchema2 = external_exports.object({ - /** - * Propagation formats (in priority order) - */ - formats: external_exports.array(TracePropagationFormat2).optional().default(["w3c"]), - /** - * Extract context from incoming requests - */ - extract: external_exports.boolean().optional().default(true), - /** - * Inject context into outgoing requests - */ - inject: external_exports.boolean().optional().default(true), - /** - * Custom header mappings - */ - headers: external_exports.object({ - /** - * Trace ID header name - */ - traceId: external_exports.string().optional(), - /** - * Span ID header name - */ - spanId: external_exports.string().optional(), - /** - * Trace flags header name - */ - traceFlags: external_exports.string().optional(), - /** - * Trace state header name - */ - traceState: external_exports.string().optional() - }).optional(), - /** - * Baggage propagation - */ - baggage: external_exports.object({ - /** - * Enable baggage propagation - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Maximum baggage size in bytes - */ - maxSize: external_exports.number().int().positive().optional().default(8192), - /** - * Allowed baggage keys (whitelist) - */ - allowedKeys: external_exports.array(external_exports.string()).optional() - }).optional() -}).describe("Trace context propagation"); -var OtelExporterType2 = external_exports.enum([ - "otlp_http", - // OTLP over HTTP - "otlp_grpc", - // OTLP over gRPC - "jaeger", - // Jaeger - "zipkin", - // Zipkin - "console", - // Console (for debugging) - "datadog", - // Datadog - "honeycomb", - // Honeycomb - "lightstep", - // Lightstep - "newrelic", - // New Relic - "custom" - // Custom exporter -]).describe("OpenTelemetry exporter type"); -var OpenTelemetryCompatibilitySchema2 = external_exports.object({ - /** - * OpenTelemetry SDK version - */ - sdkVersion: external_exports.string().optional().describe("OTel SDK version"), - /** - * Exporter configuration - */ - exporter: external_exports.object({ - /** - * Exporter type - */ - type: OtelExporterType2.describe("Exporter type"), - /** - * Endpoint URL - */ - endpoint: external_exports.string().url().optional().describe("Exporter endpoint"), - /** - * Protocol version - */ - protocol: external_exports.string().optional().describe("Protocol version"), - /** - * Headers - */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP headers"), - /** - * Timeout in milliseconds - */ - timeout: external_exports.number().int().positive().optional().default(1e4), - /** - * Compression - */ - compression: external_exports.enum(["none", "gzip"]).optional().default("none"), - /** - * Batch configuration - */ - batch: external_exports.object({ - /** - * Maximum batch size - */ - maxBatchSize: external_exports.number().int().positive().optional().default(512), - /** - * Maximum queue size - */ - maxQueueSize: external_exports.number().int().positive().optional().default(2048), - /** - * Export timeout in milliseconds - */ - exportTimeout: external_exports.number().int().positive().optional().default(3e4), - /** - * Scheduled delay in milliseconds - */ - scheduledDelay: external_exports.number().int().positive().optional().default(5e3) - }).optional() - }).describe("Exporter configuration"), - /** - * Resource attributes (service identification) - */ - resource: external_exports.object({ - /** - * Service name - */ - serviceName: external_exports.string().describe("Service name"), - /** - * Service version - */ - serviceVersion: external_exports.string().optional().describe("Service version"), - /** - * Service instance ID - */ - serviceInstanceId: external_exports.string().optional().describe("Service instance ID"), - /** - * Service namespace - */ - serviceNamespace: external_exports.string().optional().describe("Service namespace"), - /** - * Deployment environment - */ - deploymentEnvironment: external_exports.string().optional().describe("Deployment environment"), - /** - * Additional resource attributes - */ - attributes: SpanAttributesSchema2.optional().describe("Additional resource attributes") - }).describe("Resource attributes"), - /** - * Instrumentation configuration - */ - instrumentation: external_exports.object({ - /** - * Auto-instrumentation enabled - */ - autoInstrumentation: external_exports.boolean().optional().default(true), - /** - * Instrumentation libraries to enable - */ - libraries: external_exports.array(external_exports.string()).optional().describe("Enabled libraries"), - /** - * Instrumentation libraries to disable - */ - disabledLibraries: external_exports.array(external_exports.string()).optional().describe("Disabled libraries") - }).optional(), - /** - * Semantic conventions version - */ - semanticConventionsVersion: external_exports.string().optional().describe("Semantic conventions version") -}).describe("OpenTelemetry compatibility configuration"); -var TracingConfigSchema2 = external_exports.object({ - /** - * Configuration name - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe("Configuration name (snake_case, max 64 chars)"), - /** - * Display label - */ - label: external_exports.string().describe("Display label"), - /** - * Enable tracing - */ - enabled: external_exports.boolean().optional().default(true), - /** - * Sampling configuration - */ - sampling: TraceSamplingConfigSchema2.optional().default({ type: "always_on", rules: [] }), - /** - * Context propagation - */ - propagation: TraceContextPropagationSchema2.optional().default({ formats: ["w3c"], extract: true, inject: true }), - /** - * OpenTelemetry configuration - */ - openTelemetry: OpenTelemetryCompatibilitySchema2.optional(), - /** - * Span limits - */ - spanLimits: external_exports.object({ - /** - * Maximum number of attributes per span - */ - maxAttributes: external_exports.number().int().positive().optional().default(128), - /** - * Maximum number of events per span - */ - maxEvents: external_exports.number().int().positive().optional().default(128), - /** - * Maximum number of links per span - */ - maxLinks: external_exports.number().int().positive().optional().default(128), - /** - * Maximum attribute value length - */ - maxAttributeValueLength: external_exports.number().int().positive().optional().default(4096) - }).optional(), - /** - * Trace ID generator - */ - traceIdGenerator: external_exports.enum(["random", "uuid", "custom"]).optional().default("random"), - /** - * Custom trace ID generator ID - */ - customTraceIdGeneratorId: external_exports.string().optional().describe("Custom generator identifier"), - /** - * Performance configuration - */ - performance: external_exports.object({ - /** - * Async span export - */ - asyncExport: external_exports.boolean().optional().default(true), - /** - * Background export interval in milliseconds - */ - exportInterval: external_exports.number().int().positive().optional().default(5e3) - }).optional() -}).describe("Tracing configuration"); -var DataClassificationSchema2 = external_exports.enum([ - "pii", - "phi", - "pci", - "financial", - "confidential", - "internal", - "public" -]).describe("Data classification level"); -var ComplianceFrameworkSchema2 = external_exports.enum([ - "gdpr", - "hipaa", - "sox", - "pci_dss", - "ccpa", - "iso27001" -]).describe("Compliance framework identifier"); -var ComplianceAuditRequirementSchema2 = external_exports.object({ - framework: ComplianceFrameworkSchema2.describe("Compliance framework identifier"), - requiredEvents: external_exports.array(external_exports.string()).describe('Audit event types required by this framework (e.g., "data.delete", "auth.login")'), - retentionDays: external_exports.number().min(1).describe("Minimum audit log retention period required by this framework (in days)"), - alertOnMissing: external_exports.boolean().default(true).describe("Raise alert if a required audit event is not being captured") -}).describe("Compliance framework audit event requirements"); -var ComplianceEncryptionRequirementSchema2 = external_exports.object({ - framework: ComplianceFrameworkSchema2.describe("Compliance framework identifier"), - dataClassifications: external_exports.array(DataClassificationSchema2).describe("Data classifications that must be encrypted under this framework"), - minimumAlgorithm: external_exports.enum(["aes-256-gcm", "aes-256-cbc", "chacha20-poly1305"]).default("aes-256-gcm").describe("Minimum encryption algorithm strength required"), - keyRotationMaxDays: external_exports.number().min(1).default(90).describe("Maximum key rotation interval required (in days)") -}).describe("Compliance framework encryption requirements"); -var MaskingVisibilityRuleSchema2 = external_exports.object({ - dataClassification: DataClassificationSchema2.describe("Data classification this rule applies to"), - defaultMasked: external_exports.boolean().default(true).describe("Whether data is masked by default"), - unmaskRoles: external_exports.array(external_exports.string()).optional().describe("Roles allowed to view unmasked data"), - auditUnmask: external_exports.boolean().default(true).describe("Log an audit event when data is unmasked"), - requireApproval: external_exports.boolean().default(false).describe("Require explicit approval before unmasking"), - approvalRoles: external_exports.array(external_exports.string()).optional().describe("Roles that can approve unmasking requests") -}).describe("Masking visibility and audit rule per data classification"); -var SecurityEventCorrelationSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable cross-subsystem security event correlation"), - correlationId: external_exports.boolean().default(true).describe("Inject a shared correlation ID into audit, encryption, and masking events"), - linkAuthToAudit: external_exports.boolean().default(true).describe("Link authentication events to subsequent data operation audit trails"), - linkEncryptionToAudit: external_exports.boolean().default(true).describe("Log encryption/decryption operations in the audit trail"), - linkMaskingToAudit: external_exports.boolean().default(true).describe("Log masking/unmasking operations in the audit trail") -}).describe("Cross-subsystem security event correlation configuration"); -var DataClassificationPolicySchema2 = external_exports.object({ - classification: DataClassificationSchema2.describe("Data classification level"), - requireEncryption: external_exports.boolean().default(false).describe("Encryption required for this classification"), - requireMasking: external_exports.boolean().default(false).describe("Masking required for this classification"), - requireAudit: external_exports.boolean().default(false).describe("Audit trail required for access to this classification"), - retentionDays: external_exports.number().optional().describe("Data retention limit in days (for compliance)") -}).describe("Security policy for a specific data classification level"); -var SecurityContextConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable unified security context governance"), - complianceAuditRequirements: external_exports.array(ComplianceAuditRequirementSchema2).optional().describe("Compliance-driven audit event requirements"), - complianceEncryptionRequirements: external_exports.array(ComplianceEncryptionRequirementSchema2).optional().describe("Compliance-driven encryption requirements by data classification"), - maskingVisibility: external_exports.array(MaskingVisibilityRuleSchema2).optional().describe("Masking visibility rules per data classification"), - dataClassifications: external_exports.array(DataClassificationPolicySchema2).optional().describe("Data classification policies for unified security enforcement"), - eventCorrelation: SecurityEventCorrelationSchema2.optional().describe("Cross-subsystem security event correlation settings"), - enforceOnWrite: external_exports.boolean().default(true).describe("Enforce encryption and masking requirements on data write operations"), - enforceOnRead: external_exports.boolean().default(true).describe("Enforce masking and audit requirements on data read operations"), - failOpen: external_exports.boolean().default(false).describe("When false (default), deny access if security context cannot be evaluated") -}).describe("Unified security context governance configuration"); -var ChangeTypeSchema2 = external_exports.enum([ - "standard", - // Pre-approved, low-risk changes - "normal", - // Requires standard approval process - "emergency", - // Fast-track approval for critical issues - "major" - // Requires CAB (Change Advisory Board) approval -]); -var ChangePrioritySchema2 = external_exports.enum([ - "critical", - "high", - "medium", - "low" -]); -var ChangeStatusSchema2 = external_exports.enum([ - "draft", - "submitted", - "in-review", - "approved", - "scheduled", - "in-progress", - "completed", - "failed", - "rolled-back", - "cancelled" -]); -var ChangeImpactSchema2 = external_exports.object({ - /** - * Overall impact level of the change - */ - level: external_exports.enum(["low", "medium", "high", "critical"]).describe("Impact level"), - /** - * List of systems affected by this change - */ - affectedSystems: external_exports.array(external_exports.string()).describe("Affected systems"), - /** - * Estimated number of users affected - */ - affectedUsers: external_exports.number().optional().describe("Affected user count"), - /** - * Downtime requirements - */ - downtime: external_exports.object({ - /** - * Whether downtime is required - */ - required: external_exports.boolean().describe("Downtime required"), - /** - * Duration of downtime in minutes - */ - durationMinutes: external_exports.number().optional().describe("Downtime duration") - }).optional().describe("Downtime information") -}); -var RollbackPlanSchema2 = external_exports.object({ - /** - * High-level description of the rollback approach - */ - description: external_exports.string().describe("Rollback description"), - /** - * Sequential steps to execute rollback - */ - steps: external_exports.array(external_exports.object({ - /** - * Step execution order - */ - order: external_exports.number().describe("Step order"), - /** - * Detailed description of this step - */ - description: external_exports.string().describe("Step description"), - /** - * Estimated time to complete this step - */ - estimatedMinutes: external_exports.number().describe("Estimated duration") - })).describe("Rollback steps"), - /** - * Testing procedure to verify successful rollback - */ - testProcedure: external_exports.string().optional().describe("Test procedure") -}); -var ChangeRequestSchema2 = external_exports.object({ - /** - * Unique change request identifier - */ - id: external_exports.string().describe("Change request ID"), - /** - * Short descriptive title of the change - */ - title: external_exports.string().describe("Change title"), - /** - * Detailed description of the change and its purpose - */ - description: external_exports.string().describe("Change description"), - /** - * Change classification type - */ - type: ChangeTypeSchema2.describe("Change type"), - /** - * Priority level for processing - */ - priority: ChangePrioritySchema2.describe("Change priority"), - /** - * Current status in the change lifecycle - */ - status: ChangeStatusSchema2.describe("Change status"), - /** - * User ID of the change requester - */ - requestedBy: external_exports.string().describe("Requester user ID"), - /** - * Timestamp when change was requested (Unix milliseconds) - */ - requestedAt: external_exports.number().describe("Request timestamp"), - /** - * Impact assessment of the change - */ - impact: ChangeImpactSchema2.describe("Impact assessment"), - /** - * Implementation plan and procedures - */ - implementation: external_exports.object({ - /** - * High-level implementation description - */ - description: external_exports.string().describe("Implementation description"), - /** - * Sequential implementation steps - */ - steps: external_exports.array(external_exports.object({ - /** - * Step execution order - */ - order: external_exports.number().describe("Step order"), - /** - * Detailed description of this step - */ - description: external_exports.string().describe("Step description"), - /** - * Estimated time to complete this step - */ - estimatedMinutes: external_exports.number().describe("Estimated duration") - })).describe("Implementation steps"), - /** - * Testing procedures to verify successful implementation - */ - testing: external_exports.string().optional().describe("Testing procedure") - }).describe("Implementation plan"), - /** - * Rollback plan in case of failure - */ - rollbackPlan: RollbackPlanSchema2.describe("Rollback plan"), - /** - * Change schedule and timing - */ - schedule: external_exports.object({ - /** - * Planned start time (Unix milliseconds) - */ - plannedStart: external_exports.number().describe("Planned start time"), - /** - * Planned end time (Unix milliseconds) - */ - plannedEnd: external_exports.number().describe("Planned end time"), - /** - * Actual start time (Unix milliseconds) - */ - actualStart: external_exports.number().optional().describe("Actual start time"), - /** - * Actual end time (Unix milliseconds) - */ - actualEnd: external_exports.number().optional().describe("Actual end time") - }).optional().describe("Schedule"), - /** - * Security impact assessment for the change (A.8.32) - */ - securityImpact: external_exports.object({ - /** - * Whether a security impact assessment has been performed - */ - assessed: external_exports.boolean().describe("Whether security impact has been assessed"), - /** - * Security risk level of this change - */ - riskLevel: external_exports.enum(["none", "low", "medium", "high", "critical"]).optional().describe("Security risk level"), - /** - * Data classifications affected by this change - */ - affectedDataClassifications: external_exports.array(DataClassificationSchema2).optional().describe("Affected data classifications"), - /** - * Whether the change requires security team approval - */ - requiresSecurityApproval: external_exports.boolean().default(false).describe("Whether security team approval is required"), - /** - * Security reviewer user ID - */ - reviewedBy: external_exports.string().optional().describe("Security reviewer user ID"), - /** - * Security review completion timestamp (Unix milliseconds) - */ - reviewedAt: external_exports.number().optional().describe("Security review timestamp"), - /** - * Security review notes or conditions - */ - reviewNotes: external_exports.string().optional().describe("Security review notes or conditions") - }).optional().describe("Security impact assessment per ISO 27001:2022 A.8.32"), - /** - * Approval workflow configuration - */ - approval: external_exports.object({ - /** - * Whether approval is required for this change - */ - required: external_exports.boolean().describe("Approval required"), - /** - * List of approvers and their approval status - */ - approvers: external_exports.array(external_exports.object({ - /** - * Approver user ID - */ - userId: external_exports.string().describe("Approver user ID"), - /** - * Timestamp when approval was granted (Unix milliseconds) - */ - approvedAt: external_exports.number().optional().describe("Approval timestamp"), - /** - * Comments from the approver - */ - comments: external_exports.string().optional().describe("Approver comments") - })).describe("Approvers") - }).optional().describe("Approval workflow"), - /** - * Supporting documentation and files - */ - attachments: external_exports.array(external_exports.object({ - /** - * Attachment file name - */ - name: external_exports.string().describe("Attachment name"), - /** - * URL to download the attachment - */ - url: external_exports.string().url().describe("Attachment URL") - })).optional().describe("Attachments"), - /** - * Custom metadata key-value pairs for extensibility - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") -}); -var AddFieldOperation2 = external_exports.object({ - type: external_exports.literal("add_field"), - objectName: external_exports.string().describe("Target object name"), - fieldName: external_exports.string().describe("Name of the field to add"), - field: FieldSchema5.describe("Full field definition to add") -}).describe("Add a new field to an existing object"); -var ModifyFieldOperation2 = external_exports.object({ - type: external_exports.literal("modify_field"), - objectName: external_exports.string().describe("Target object name"), - fieldName: external_exports.string().describe("Name of the field to modify"), - changes: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Partial field definition updates") -}).describe("Modify properties of an existing field"); -var RemoveFieldOperation2 = external_exports.object({ - type: external_exports.literal("remove_field"), - objectName: external_exports.string().describe("Target object name"), - fieldName: external_exports.string().describe("Name of the field to remove") -}).describe("Remove a field from an existing object"); -var CreateObjectOperation2 = external_exports.object({ - type: external_exports.literal("create_object"), - object: ObjectSchema4.describe("Full object definition to create") -}).describe("Create a new object"); -var RenameObjectOperation2 = external_exports.object({ - type: external_exports.literal("rename_object"), - oldName: external_exports.string().describe("Current object name"), - newName: external_exports.string().describe("New object name") -}).describe("Rename an existing object"); -var DeleteObjectOperation2 = external_exports.object({ - type: external_exports.literal("delete_object"), - objectName: external_exports.string().describe("Name of the object to delete") -}).describe("Delete an existing object"); -var ExecuteSqlOperation2 = external_exports.object({ - type: external_exports.literal("execute_sql"), - sql: external_exports.string().describe("Raw SQL statement to execute"), - description: external_exports.string().optional().describe("Human-readable description of the SQL") -}).describe("Execute a raw SQL statement"); -var MigrationOperationSchema2 = external_exports.discriminatedUnion("type", [ - AddFieldOperation2, - ModifyFieldOperation2, - RemoveFieldOperation2, - CreateObjectOperation2, - RenameObjectOperation2, - DeleteObjectOperation2, - ExecuteSqlOperation2 -]); -var MigrationDependencySchema2 = external_exports.object({ - migrationId: external_exports.string().describe("ID of the migration this depends on"), - package: external_exports.string().optional().describe("Package that owns the dependency migration") -}).describe("Dependency reference to another migration that must run first"); -var ChangeSetSchema2 = external_exports.object({ - id: external_exports.string().uuid().describe("Unique identifier for this change set"), - name: external_exports.string().describe("Human readable name for the migration"), - description: external_exports.string().optional().describe("Detailed description of what this migration does"), - author: external_exports.string().optional().describe("Author who created this migration"), - createdAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp when the migration was created"), - // Dependencies ensure migrations run in order - dependencies: external_exports.array(MigrationDependencySchema2).optional().describe("Migrations that must run before this one"), - // The actual atomic operations - operations: external_exports.array(MigrationOperationSchema2).describe("Ordered list of atomic migration operations"), - // Rollback operations (AI should generate these too) - rollback: external_exports.array(MigrationOperationSchema2).optional().describe("Operations to reverse this migration") -}).describe("A versioned set of atomic schema migration operations"); -var AuthProviderConfigSchema2 = external_exports.object({ - id: external_exports.string().describe("Provider ID (github, google)"), - clientId: external_exports.string().describe("OAuth Client ID"), - clientSecret: external_exports.string().describe("OAuth Client Secret"), - scope: external_exports.array(external_exports.string()).optional().describe("Requested permissions") -}); -var AuthPluginConfigSchema2 = external_exports.object({ - organization: external_exports.boolean().default(false).describe("Enable Organization/Teams support"), - twoFactor: external_exports.boolean().default(false).describe("Enable 2FA"), - passkeys: external_exports.boolean().default(false).describe("Enable Passkey support"), - magicLink: external_exports.boolean().default(false).describe("Enable Magic Link login") -}); -var MutualTLSConfigSchema2 = external_exports.object({ - /** Enable mutual TLS authentication */ - enabled: external_exports.boolean().default(false).describe("Enable mutual TLS authentication"), - /** Require client certificates for all connections */ - clientCertRequired: external_exports.boolean().default(false).describe("Require client certificates for all connections"), - /** PEM-encoded CA certificates or file paths for trust validation */ - trustedCAs: external_exports.array(external_exports.string()).describe("PEM-encoded CA certificates or file paths"), - /** Certificate Revocation List URL */ - crlUrl: external_exports.string().optional().describe("Certificate Revocation List (CRL) URL"), - /** Online Certificate Status Protocol URL */ - ocspUrl: external_exports.string().optional().describe("Online Certificate Status Protocol (OCSP) URL"), - /** Certificate validation strictness level */ - certificateValidation: external_exports.enum(["strict", "relaxed", "none"]).describe("Certificate validation strictness level"), - /** Allowed Common Names on client certificates */ - allowedCNs: external_exports.array(external_exports.string()).optional().describe("Allowed Common Names (CN) on client certificates"), - /** Allowed Organizational Units on client certificates */ - allowedOUs: external_exports.array(external_exports.string()).optional().describe("Allowed Organizational Units (OU) on client certificates"), - /** Certificate pinning configuration */ - pinning: external_exports.object({ - /** Enable certificate pinning */ - enabled: external_exports.boolean().describe("Enable certificate pinning"), - /** Array of pinned certificate hashes */ - pins: external_exports.array(external_exports.string()).describe("Pinned certificate hashes") - }).optional().describe("Certificate pinning configuration") -}); -var SocialProviderConfigSchema2 = external_exports.record( - external_exports.string(), - external_exports.object({ - clientId: external_exports.string().describe("OAuth Client ID"), - clientSecret: external_exports.string().describe("OAuth Client Secret"), - enabled: external_exports.boolean().optional().default(true).describe("Enable this provider"), - scope: external_exports.array(external_exports.string()).optional().describe("Additional OAuth scopes") - }).catchall(external_exports.unknown()) -).optional().describe( - "Social/OAuth provider map forwarded to better-auth socialProviders. Keys are provider ids (google, github, apple, \u2026)." -); -var EmailAndPasswordConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable email/password auth"), - disableSignUp: external_exports.boolean().optional().describe("Disable new user registration via email/password"), - requireEmailVerification: external_exports.boolean().optional().describe( - "Require email verification before creating a session" - ), - minPasswordLength: external_exports.number().optional().describe("Minimum password length (default 8)"), - maxPasswordLength: external_exports.number().optional().describe("Maximum password length (default 128)"), - resetPasswordTokenExpiresIn: external_exports.number().optional().describe( - "Reset-password token TTL in seconds (default 3600)" - ), - autoSignIn: external_exports.boolean().optional().describe("Auto sign-in after sign-up (default true)"), - revokeSessionsOnPasswordReset: external_exports.boolean().optional().describe( - "Revoke all other sessions on password reset" - ) -}).optional().describe("Email and password authentication options forwarded to better-auth"); -var EmailVerificationConfigSchema2 = external_exports.object({ - sendOnSignUp: external_exports.boolean().optional().describe( - "Automatically send verification email after sign-up" - ), - sendOnSignIn: external_exports.boolean().optional().describe( - "Send verification email on sign-in when not yet verified" - ), - autoSignInAfterVerification: external_exports.boolean().optional().describe( - "Auto sign-in the user after email verification" - ), - expiresIn: external_exports.number().optional().describe( - "Verification token TTL in seconds (default 3600)" - ) -}).optional().describe("Email verification options forwarded to better-auth"); -var AdvancedAuthConfigSchema2 = external_exports.object({ - crossSubDomainCookies: external_exports.object({ - enabled: external_exports.boolean().describe("Enable cross-subdomain cookies"), - additionalCookies: external_exports.array(external_exports.string()).optional().describe("Extra cookies shared across subdomains"), - domain: external_exports.string().optional().describe( - "Cookie domain override \u2014 defaults to root domain derived from baseUrl" - ) - }).optional().describe( - "Share auth cookies across subdomains (critical for *.example.com multi-tenant)" - ), - useSecureCookies: external_exports.boolean().optional().describe("Force Secure flag on cookies"), - disableCSRFCheck: external_exports.boolean().optional().describe( - "\u26A0 Disable CSRF check \u2014 security risk, use with caution" - ), - cookiePrefix: external_exports.string().optional().describe("Prefix for auth cookie names") -}).optional().describe("Advanced / low-level Better-Auth options"); -var AuthConfigSchema2 = external_exports.object({ - secret: external_exports.string().optional().describe("Encryption secret"), - baseUrl: external_exports.string().optional().describe("Base URL for auth routes"), - databaseUrl: external_exports.string().optional().describe("Database connection string"), - providers: external_exports.array(AuthProviderConfigSchema2).optional(), - plugins: AuthPluginConfigSchema2.optional(), - session: external_exports.object({ - expiresIn: external_exports.number().default(60 * 60 * 24 * 7).describe("Session duration in seconds"), - updateAge: external_exports.number().default(60 * 60 * 24).describe("Session update frequency") - }).optional(), - trustedOrigins: external_exports.array(external_exports.string()).optional().describe( - 'Trusted origins for CSRF protection. Supports wildcards (e.g. "https://*.example.com"). The baseUrl origin is always trusted implicitly.' - ), - socialProviders: SocialProviderConfigSchema2, - emailAndPassword: EmailAndPasswordConfigSchema2, - emailVerification: EmailVerificationConfigSchema2, - advanced: AdvancedAuthConfigSchema2, - mutualTls: MutualTLSConfigSchema2.optional().describe("Mutual TLS (mTLS) configuration") -}).catchall(external_exports.unknown()); -var GDPRConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable GDPR compliance controls"), - dataSubjectRights: external_exports.object({ - rightToAccess: external_exports.boolean().default(true).describe("Allow data subjects to access their data"), - rightToRectification: external_exports.boolean().default(true).describe("Allow data subjects to correct their data"), - rightToErasure: external_exports.boolean().default(true).describe("Allow data subjects to request deletion"), - rightToRestriction: external_exports.boolean().default(true).describe("Allow data subjects to restrict processing"), - rightToPortability: external_exports.boolean().default(true).describe("Allow data subjects to export their data"), - rightToObjection: external_exports.boolean().default(true).describe("Allow data subjects to object to processing") - }).describe("Data subject rights configuration per GDPR Articles 15-21"), - legalBasis: external_exports.enum([ - "consent", - "contract", - "legal-obligation", - "vital-interests", - "public-task", - "legitimate-interests" - ]).describe("Legal basis for data processing under GDPR Article 6"), - consentTracking: external_exports.boolean().default(true).describe("Track and record user consent"), - dataRetentionDays: external_exports.number().optional().describe("Maximum data retention period in days"), - dataProcessingAgreement: external_exports.string().optional().describe("URL or reference to the data processing agreement") -}).describe("GDPR (General Data Protection Regulation) compliance configuration"); -var HIPAAConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable HIPAA compliance controls"), - phi: external_exports.object({ - encryption: external_exports.boolean().default(true).describe("Encrypt Protected Health Information at rest"), - accessControl: external_exports.boolean().default(true).describe("Enforce role-based access to PHI"), - auditTrail: external_exports.boolean().default(true).describe("Log all PHI access events"), - backupAndRecovery: external_exports.boolean().default(true).describe("Enable PHI backup and disaster recovery") - }).describe("Protected Health Information safeguards"), - businessAssociateAgreement: external_exports.boolean().default(false).describe("BAA is in place with third-party processors") -}).describe("HIPAA (Health Insurance Portability and Accountability Act) compliance configuration"); -var PCIDSSConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().describe("Enable PCI-DSS compliance controls"), - level: external_exports.enum(["1", "2", "3", "4"]).describe("PCI-DSS compliance level (1 = highest)"), - cardDataFields: external_exports.array(external_exports.string()).describe("Field names containing cardholder data"), - tokenization: external_exports.boolean().default(true).describe("Replace card data with secure tokens"), - encryptionInTransit: external_exports.boolean().default(true).describe("Encrypt cardholder data during transmission"), - encryptionAtRest: external_exports.boolean().default(true).describe("Encrypt stored cardholder data") -}).describe("PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration"); -var AuditLogConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable audit logging"), - retentionDays: external_exports.number().default(365).describe("Number of days to retain audit logs"), - immutable: external_exports.boolean().default(true).describe("Prevent modification or deletion of audit logs"), - signLogs: external_exports.boolean().default(false).describe("Cryptographically sign log entries for tamper detection"), - events: external_exports.array(external_exports.enum([ - "create", - "read", - "update", - "delete", - "export", - "permission-change", - "login", - "logout", - "failed-login" - ])).describe("Event types to capture in the audit log") -}).describe("Audit log configuration for compliance and security monitoring"); -var AuditFindingSeveritySchema2 = external_exports.enum([ - "critical", - // Immediate remediation required - "major", - // Significant non-conformity - "minor", - // Minor non-conformity - "observation" - // Improvement opportunity -]); -var AuditFindingStatusSchema2 = external_exports.enum([ - "open", - // Finding identified, not yet addressed - "in_remediation", - // Remediation in progress - "remediated", - // Remediation completed, pending verification - "verified", - // Remediation verified and accepted - "accepted_risk", - // Risk accepted by management - "closed" - // Finding closed -]); -var AuditFindingSchema2 = external_exports.object({ - /** - * Unique finding identifier - */ - id: external_exports.string().describe("Unique finding identifier"), - /** - * Short descriptive title - */ - title: external_exports.string().describe("Finding title"), - /** - * Detailed description of the finding - */ - description: external_exports.string().describe("Finding description"), - /** - * Finding severity - */ - severity: AuditFindingSeveritySchema2.describe("Finding severity"), - /** - * Current status - */ - status: AuditFindingStatusSchema2.describe("Finding status"), - /** - * ISO 27001 control reference (e.g., "A.5.35", "A.8.15") - */ - controlReference: external_exports.string().optional().describe("ISO 27001 control reference"), - /** - * Compliance framework - */ - framework: ComplianceFrameworkSchema2.optional().describe("Related compliance framework"), - /** - * Timestamp when finding was identified (Unix milliseconds) - */ - identifiedAt: external_exports.number().describe("Identification timestamp"), - /** - * User or entity who identified the finding - */ - identifiedBy: external_exports.string().describe("Identifier (auditor name or system)"), - /** - * Planned remediation actions - */ - remediationPlan: external_exports.string().optional().describe("Remediation plan"), - /** - * Remediation deadline (Unix milliseconds) - */ - remediationDeadline: external_exports.number().optional().describe("Remediation deadline timestamp"), - /** - * Timestamp when remediation was verified (Unix milliseconds) - */ - verifiedAt: external_exports.number().optional().describe("Verification timestamp"), - /** - * Verifier name or role - */ - verifiedBy: external_exports.string().optional().describe("Verifier name or role"), - /** - * Notes or comments - */ - notes: external_exports.string().optional().describe("Additional notes") -}).describe("Audit finding with remediation tracking per ISO 27001:2022 A.5.35"); -var AuditScheduleSchema2 = external_exports.object({ - /** - * Unique audit schedule identifier - */ - id: external_exports.string().describe("Unique audit schedule identifier"), - /** - * Audit title or name - */ - title: external_exports.string().describe("Audit title"), - /** - * Scope of areas to audit - */ - scope: external_exports.array(external_exports.string()).describe("Audit scope areas"), - /** - * Target compliance framework - */ - framework: ComplianceFrameworkSchema2.describe("Target compliance framework"), - /** - * Scheduled audit date (Unix milliseconds) - */ - scheduledAt: external_exports.number().describe("Scheduled audit timestamp"), - /** - * Actual completion date (Unix milliseconds) - */ - completedAt: external_exports.number().optional().describe("Completion timestamp"), - /** - * Assessor name, team, or external firm - */ - assessor: external_exports.string().describe("Assessor or audit team"), - /** - * Whether this is an external (independent) audit - */ - isExternal: external_exports.boolean().default(false).describe("Whether this is an external audit"), - /** - * Recurrence interval in months (0 = one-time) - */ - recurrenceMonths: external_exports.number().default(0).describe("Recurrence interval in months (0 = one-time)"), - /** - * Findings from this audit - */ - findings: external_exports.array(AuditFindingSchema2).optional().describe("Audit findings") -}).describe("Audit schedule for independent security reviews per ISO 27001:2022 A.5.35"); -var ComplianceConfigSchema2 = external_exports.object({ - gdpr: GDPRConfigSchema2.optional().describe("GDPR compliance settings"), - hipaa: HIPAAConfigSchema2.optional().describe("HIPAA compliance settings"), - pciDss: PCIDSSConfigSchema2.optional().describe("PCI-DSS compliance settings"), - auditLog: AuditLogConfigSchema2.describe("Audit log configuration"), - auditSchedules: external_exports.array(AuditScheduleSchema2).optional().describe("Scheduled compliance audits (A.5.35)") -}).describe("Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance"); -var IncidentSeveritySchema2 = external_exports.enum([ - "critical", - // Immediate threat to business operations or data integrity - "high", - // Significant impact requiring urgent response - "medium", - // Moderate impact with controlled response timeline - "low" - // Minor impact with standard response procedures -]); -var IncidentCategorySchema2 = external_exports.enum([ - "data_breach", - // Unauthorized access or disclosure of data - "malware", - // Malicious software detection - "unauthorized_access", - // Unauthorized system or data access - "denial_of_service", - // Service availability attack - "social_engineering", - // Phishing, pretexting, or manipulation - "insider_threat", - // Threat originating from internal actors - "physical_security", - // Physical security breach - "configuration_error", - // Security misconfiguration - "vulnerability_exploit", - // Exploitation of known vulnerability - "policy_violation", - // Violation of security policies - "other" - // Other security incidents -]); -var IncidentStatusSchema2 = external_exports.enum([ - "reported", - // Initial report received - "triaged", - // Severity and category assessed - "investigating", - // Active investigation in progress - "containing", - // Containment measures being applied - "eradicating", - // Root cause being removed - "recovering", - // Systems being restored to normal - "resolved", - // Incident resolved - "closed" - // Post-incident review complete -]); -var IncidentResponsePhaseSchema2 = external_exports.object({ - /** - * Phase name identifier - */ - phase: external_exports.enum([ - "identification", - "containment", - "eradication", - "recovery", - "lessons_learned" - ]).describe("Response phase name"), - /** - * Phase description and objectives - */ - description: external_exports.string().describe("Phase description and objectives"), - /** - * Responsible team or role for this phase - */ - assignedTo: external_exports.string().describe("Responsible team or role"), - /** - * Target completion time in hours from incident start - */ - targetHours: external_exports.number().min(0).describe("Target completion time in hours"), - /** - * Actual completion timestamp (Unix milliseconds) - */ - completedAt: external_exports.number().optional().describe("Actual completion timestamp"), - /** - * Notes and findings during this phase - */ - notes: external_exports.string().optional().describe("Phase notes and findings") -}).describe("Incident response phase with timing and assignment"); -var IncidentNotificationRuleSchema2 = external_exports.object({ - /** - * Minimum severity level that triggers this notification - */ - severity: IncidentSeveritySchema2.describe("Minimum severity to trigger notification"), - /** - * Notification channels to use - */ - channels: external_exports.array(external_exports.enum([ - "email", - "sms", - "slack", - "pagerduty", - "webhook" - ])).describe("Notification channels"), - /** - * Roles or teams to notify - */ - recipients: external_exports.array(external_exports.string()).describe("Roles or teams to notify"), - /** - * Maximum time in minutes to send notification after incident detection - */ - withinMinutes: external_exports.number().min(1).describe("Notification deadline in minutes from detection"), - /** - * Whether to notify external regulators (for data breaches) - */ - notifyRegulators: external_exports.boolean().default(false).describe("Whether to notify regulatory authorities"), - /** - * Regulatory notification deadline in hours (e.g., GDPR 72h) - */ - regulatorDeadlineHours: external_exports.number().optional().describe("Regulatory notification deadline in hours") -}).describe("Incident notification rule per severity level"); -var IncidentNotificationMatrixSchema2 = external_exports.object({ - /** - * Notification rules ordered by severity - */ - rules: external_exports.array(IncidentNotificationRuleSchema2).describe("Notification rules by severity level"), - /** - * Default escalation timeout in minutes before auto-escalation - */ - escalationTimeoutMinutes: external_exports.number().default(30).describe("Auto-escalation timeout in minutes"), - /** - * Escalation chain: ordered list of roles to escalate to - */ - escalationChain: external_exports.array(external_exports.string()).default([]).describe("Ordered escalation chain of roles") -}).describe("Incident notification matrix with escalation policies"); -var IncidentSchema2 = external_exports.object({ - /** - * Unique incident identifier - */ - id: external_exports.string().describe("Unique incident identifier"), - /** - * Short descriptive title of the incident - */ - title: external_exports.string().describe("Incident title"), - /** - * Detailed description of the security event - */ - description: external_exports.string().describe("Detailed incident description"), - /** - * Severity classification - */ - severity: IncidentSeveritySchema2.describe("Incident severity level"), - /** - * Incident category / type - */ - category: IncidentCategorySchema2.describe("Incident category"), - /** - * Current status in the incident lifecycle - */ - status: IncidentStatusSchema2.describe("Current incident status"), - /** - * User or system that reported the incident - */ - reportedBy: external_exports.string().describe("Reporter user ID or system name"), - /** - * Timestamp when the incident was reported (Unix milliseconds) - */ - reportedAt: external_exports.number().describe("Report timestamp"), - /** - * Timestamp when the incident was detected (may differ from reported) - */ - detectedAt: external_exports.number().optional().describe("Detection timestamp"), - /** - * Timestamp when the incident was resolved - */ - resolvedAt: external_exports.number().optional().describe("Resolution timestamp"), - /** - * Systems affected by the incident - */ - affectedSystems: external_exports.array(external_exports.string()).describe("Affected systems"), - /** - * Data classifications affected (for data breach assessment) - */ - affectedDataClassifications: external_exports.array(DataClassificationSchema2).optional().describe("Affected data classifications"), - /** - * Structured response phases tracking - */ - responsePhases: external_exports.array(IncidentResponsePhaseSchema2).optional().describe("Incident response phases"), - /** - * Root cause analysis (completed post-incident) - */ - rootCause: external_exports.string().optional().describe("Root cause analysis"), - /** - * Corrective actions taken or planned - */ - correctiveActions: external_exports.array(external_exports.string()).optional().describe("Corrective actions taken or planned"), - /** - * Lessons learned from the incident (A.5.28) - */ - lessonsLearned: external_exports.string().optional().describe("Lessons learned from the incident"), - /** - * Related change request IDs (if changes resulted from incident) - */ - relatedChangeRequestIds: external_exports.array(external_exports.string()).optional().describe("Related change request IDs"), - /** - * Custom metadata for extensibility - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs") -}).describe("Security incident record per ISO 27001:2022 A.5.24\u2013A.5.28"); -var IncidentResponsePolicySchema2 = external_exports.object({ - /** - * Whether incident response is enabled - */ - enabled: external_exports.boolean().default(true).describe("Enable incident response management"), - /** - * Notification matrix configuration - */ - notificationMatrix: IncidentNotificationMatrixSchema2.describe("Notification and escalation matrix"), - /** - * Default response team or role - */ - defaultResponseTeam: external_exports.string().describe("Default incident response team or role"), - /** - * Maximum time in hours to begin initial triage - */ - triageDeadlineHours: external_exports.number().default(1).describe("Maximum hours to begin triage after detection"), - /** - * Whether to require post-incident review for all incidents - */ - requirePostIncidentReview: external_exports.boolean().default(true).describe("Require post-incident review for all incidents"), - /** - * Minimum severity level that requires regulatory notification - */ - regulatoryNotificationThreshold: IncidentSeveritySchema2.default("high").describe("Minimum severity requiring regulatory notification"), - /** - * Retention period for incident records in days - */ - retentionDays: external_exports.number().default(2555).describe("Incident record retention period in days (default ~7 years)") -}).describe("Organization-level incident response policy per ISO 27001:2022"); -var SupplierRiskLevelSchema2 = external_exports.enum([ - "critical", - // Direct access to sensitive data or core infrastructure - "high", - // Significant data processing or service dependency - "medium", - // Limited data access with moderate dependency - "low" - // Minimal data access and low service dependency -]); -var SupplierAssessmentStatusSchema2 = external_exports.enum([ - "pending", - // Assessment not yet started - "in_progress", - // Assessment currently underway - "completed", - // Assessment completed - "expired", - // Assessment past its validity period - "failed" - // Supplier did not meet security requirements -]); -var SupplierSecurityRequirementSchema2 = external_exports.object({ - /** - * Requirement identifier - */ - id: external_exports.string().describe("Requirement identifier"), - /** - * Requirement description - */ - description: external_exports.string().describe("Requirement description"), - /** - * ISO 27001 control reference (e.g., "A.5.19") - */ - controlReference: external_exports.string().optional().describe("ISO 27001 control reference"), - /** - * Whether this requirement is mandatory - */ - mandatory: external_exports.boolean().default(true).describe("Whether this requirement is mandatory"), - /** - * Compliance status - */ - compliant: external_exports.boolean().optional().describe("Whether the supplier meets this requirement"), - /** - * Evidence or notes for compliance assessment - */ - evidence: external_exports.string().optional().describe("Compliance evidence or assessment notes") -}).describe("Individual supplier security requirement"); -var SupplierSecurityAssessmentSchema2 = external_exports.object({ - /** - * Unique supplier identifier - */ - supplierId: external_exports.string().describe("Unique supplier identifier"), - /** - * Supplier name - */ - supplierName: external_exports.string().describe("Supplier display name"), - /** - * Risk classification - */ - riskLevel: SupplierRiskLevelSchema2.describe("Supplier risk classification"), - /** - * Assessment status - */ - status: SupplierAssessmentStatusSchema2.describe("Assessment status"), - /** - * User or team who performed the assessment - */ - assessedBy: external_exports.string().describe("Assessor user ID or team"), - /** - * Assessment completion timestamp (Unix milliseconds) - */ - assessedAt: external_exports.number().describe("Assessment timestamp"), - /** - * Assessment validity expiry (Unix milliseconds) - */ - validUntil: external_exports.number().describe("Assessment validity expiry timestamp"), - /** - * Security requirements assessed - */ - requirements: external_exports.array(SupplierSecurityRequirementSchema2).describe("Security requirements and their compliance status"), - /** - * Overall compliance result - */ - overallCompliant: external_exports.boolean().describe("Whether supplier meets all mandatory requirements"), - /** - * Data classifications shared with this supplier - */ - dataClassificationsShared: external_exports.array(DataClassificationSchema2).optional().describe("Data classifications shared with supplier"), - /** - * Services provided by the supplier - */ - servicesProvided: external_exports.array(external_exports.string()).optional().describe("Services provided by this supplier"), - /** - * Certifications held by the supplier - */ - certifications: external_exports.array(external_exports.string()).optional().describe("Supplier certifications (e.g., ISO 27001, SOC 2)"), - /** - * Remediation items for non-compliant requirements - */ - remediationItems: external_exports.array(external_exports.object({ - requirementId: external_exports.string().describe("Non-compliant requirement ID"), - action: external_exports.string().describe("Required remediation action"), - deadline: external_exports.number().describe("Remediation deadline timestamp"), - status: external_exports.enum(["pending", "in_progress", "completed"]).default("pending").describe("Remediation status") - })).optional().describe("Remediation items for non-compliant requirements"), - /** - * Custom metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs") -}).describe("Supplier security assessment record per ISO 27001:2022 A.5.19\u2013A.5.21"); -var SupplierSecurityPolicySchema2 = external_exports.object({ - /** - * Whether supplier security management is enabled - */ - enabled: external_exports.boolean().default(true).describe("Enable supplier security management"), - /** - * Reassessment interval in days - */ - reassessmentIntervalDays: external_exports.number().default(365).describe("Supplier reassessment interval in days"), - /** - * Whether to require supplier security assessment before onboarding - */ - requirePreOnboardingAssessment: external_exports.boolean().default(true).describe("Require security assessment before supplier onboarding"), - /** - * Minimum risk level that requires formal assessment - */ - formalAssessmentThreshold: SupplierRiskLevelSchema2.default("medium").describe("Minimum risk level requiring formal assessment"), - /** - * Whether to monitor supplier security changes (A.5.22) - */ - monitorChanges: external_exports.boolean().default(true).describe("Monitor supplier security posture changes"), - /** - * Required certifications for critical suppliers - */ - requiredCertifications: external_exports.array(external_exports.string()).default([]).describe("Required certifications for critical-risk suppliers") -}).describe("Organization-level supplier security management policy per ISO 27001:2022"); -var TrainingCategorySchema2 = external_exports.enum([ - "security_awareness", - // General security awareness - "data_protection", - // Data handling and privacy - "incident_response", - // Incident reporting and response - "access_control", - // Access management best practices - "phishing_awareness", - // Phishing and social engineering - "compliance", - // Regulatory compliance (GDPR, HIPAA, etc.) - "secure_development", - // Secure coding and development practices - "physical_security", - // Physical security awareness - "business_continuity", - // Business continuity and disaster recovery - "other" - // Other training categories -]); -var TrainingCompletionStatusSchema2 = external_exports.enum([ - "not_started", - // Training not yet begun - "in_progress", - // Training currently underway - "completed", - // Training completed successfully - "failed", - // Training assessment not passed - "expired" - // Training certification has expired -]); -var TrainingCourseSchema2 = external_exports.object({ - /** - * Unique course identifier - */ - id: external_exports.string().describe("Unique course identifier"), - /** - * Course title - */ - title: external_exports.string().describe("Course title"), - /** - * Course description and objectives - */ - description: external_exports.string().describe("Course description and learning objectives"), - /** - * Training category - */ - category: TrainingCategorySchema2.describe("Training category"), - /** - * Estimated duration in minutes - */ - durationMinutes: external_exports.number().min(1).describe("Estimated course duration in minutes"), - /** - * Whether this training is mandatory - */ - mandatory: external_exports.boolean().default(false).describe("Whether training is mandatory"), - /** - * Target roles or groups for this training - */ - targetRoles: external_exports.array(external_exports.string()).describe("Target roles or groups"), - /** - * Validity period in days before recertification is needed - */ - validityDays: external_exports.number().optional().describe("Certification validity period in days"), - /** - * Minimum passing score (percentage) for assessment - */ - passingScore: external_exports.number().min(0).max(100).optional().describe("Minimum passing score percentage"), - /** - * Course version for tracking content updates - */ - version: external_exports.string().optional().describe("Course content version") -}).describe("Security training course definition"); -var TrainingRecordSchema2 = external_exports.object({ - /** - * Reference to the course ID - */ - courseId: external_exports.string().describe("Training course identifier"), - /** - * User who completed (or is assigned) the training - */ - userId: external_exports.string().describe("User identifier"), - /** - * Completion status - */ - status: TrainingCompletionStatusSchema2.describe("Training completion status"), - /** - * Training assignment date (Unix milliseconds) - */ - assignedAt: external_exports.number().describe("Assignment timestamp"), - /** - * Training completion date (Unix milliseconds) - */ - completedAt: external_exports.number().optional().describe("Completion timestamp"), - /** - * Assessment score (percentage) - */ - score: external_exports.number().min(0).max(100).optional().describe("Assessment score percentage"), - /** - * Certification expiry date (Unix milliseconds) - */ - expiresAt: external_exports.number().optional().describe("Certification expiry timestamp"), - /** - * Notes or comments from instructor or system - */ - notes: external_exports.string().optional().describe("Training notes or comments") -}).describe("Individual training completion record"); -var TrainingPlanSchema2 = external_exports.object({ - /** - * Whether training management is enabled - */ - enabled: external_exports.boolean().default(true).describe("Enable training management"), - /** - * Training courses in the plan - */ - courses: external_exports.array(TrainingCourseSchema2).describe("Training courses"), - /** - * Default recertification interval in days - */ - recertificationIntervalDays: external_exports.number().default(365).describe("Default recertification interval in days"), - /** - * Whether to track training completion for compliance reporting - */ - trackCompletion: external_exports.boolean().default(true).describe("Track training completion for compliance"), - /** - * Grace period in days after expiry before non-compliance escalation - */ - gracePeriodDays: external_exports.number().default(30).describe("Grace period in days after certification expiry"), - /** - * Whether to send reminders for upcoming training deadlines - */ - sendReminders: external_exports.boolean().default(true).describe("Send reminders for upcoming training deadlines"), - /** - * Days before deadline to send first reminder - */ - reminderDaysBefore: external_exports.number().default(14).describe("Days before deadline to send first reminder") -}).describe("Organizational training plan per ISO 27001:2022 A.6.3"); -var CronScheduleSchema2 = external_exports.object({ - type: external_exports.literal("cron"), - expression: external_exports.string().describe('Cron expression (e.g., "0 0 * * *" for daily at midnight)'), - timezone: external_exports.string().optional().default("UTC").describe('Timezone for cron execution (e.g., "America/New_York")') -}); -var IntervalScheduleSchema2 = external_exports.object({ - type: external_exports.literal("interval"), - intervalMs: external_exports.number().int().positive().describe("Interval in milliseconds") -}); -var OnceScheduleSchema2 = external_exports.object({ - type: external_exports.literal("once"), - at: external_exports.string().datetime().describe("ISO 8601 datetime when to execute") -}); -var ScheduleSchema2 = external_exports.discriminatedUnion("type", [ - CronScheduleSchema2, - IntervalScheduleSchema2, - OnceScheduleSchema2 -]); -var RetryPolicySchema2 = external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum number of retry attempts"), - backoffMs: external_exports.number().int().positive().default(1e3).describe("Initial backoff delay in milliseconds"), - backoffMultiplier: external_exports.number().positive().default(2).describe("Multiplier for exponential backoff") -}); -var JobSchema2 = external_exports.object({ - id: external_exports.string().describe("Unique job identifier"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Job name (snake_case)"), - schedule: ScheduleSchema2.describe("Job schedule configuration"), - handler: external_exports.string().describe('Handler path (e.g. "path/to/file:functionName") or script ID'), - retryPolicy: RetryPolicySchema2.optional().describe("Retry policy configuration"), - timeout: external_exports.number().int().positive().optional().describe("Timeout in milliseconds"), - enabled: external_exports.boolean().default(true).describe("Whether the job is enabled") -}); -var JobExecutionStatus2 = external_exports.enum([ - "running", - "success", - "failed", - "timeout" -]); -var JobExecutionSchema2 = external_exports.object({ - jobId: external_exports.string().describe("Job identifier"), - startedAt: external_exports.string().datetime().describe("ISO 8601 datetime when execution started"), - completedAt: external_exports.string().datetime().optional().describe("ISO 8601 datetime when execution completed"), - status: JobExecutionStatus2.describe("Execution status"), - error: external_exports.string().optional().describe("Error message if failed"), - duration: external_exports.number().int().optional().describe("Execution duration in milliseconds") -}); -var TaskPriority2 = external_exports.enum([ - "critical", - // 0 - Must execute immediately - "high", - // 1 - Execute soon - "normal", - // 2 - Default priority - "low", - // 3 - Execute when resources available - "background" - // 4 - Execute during low-traffic periods -]); -var TASK_PRIORITY_VALUES = { - critical: 0, - high: 1, - normal: 2, - low: 3, - background: 4 -}; -var TaskStatus2 = external_exports.enum([ - "pending", - // Waiting to be processed - "queued", - // In queue, ready for worker - "processing", - // Currently being executed - "completed", - // Successfully completed - "failed", - // Failed (may retry) - "cancelled", - // Manually cancelled - "timeout", - // Exceeded execution timeout - "dead" - // Moved to dead letter queue -]); -var TaskRetryPolicySchema2 = external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retry attempts"), - backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy between retries"), - initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay in milliseconds"), - maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Maximum retry delay in milliseconds"), - backoffMultiplier: external_exports.number().positive().default(2).describe("Multiplier for exponential backoff") -}); -var TaskSchema2 = external_exports.object({ - /** - * Unique task identifier - */ - id: external_exports.string().describe("Unique task identifier"), - /** - * Task type (handler identifier) - */ - type: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Task type (snake_case)"), - /** - * Task payload data - */ - payload: external_exports.unknown().describe("Task payload data"), - /** - * Queue name - */ - queue: external_exports.string().default("default").describe("Queue name"), - /** - * Task priority - */ - priority: TaskPriority2.default("normal").describe("Task priority level"), - /** - * Retry policy - */ - retryPolicy: TaskRetryPolicySchema2.optional().describe("Retry policy configuration"), - /** - * Execution timeout in milliseconds - */ - timeoutMs: external_exports.number().int().positive().optional().describe("Task timeout in milliseconds"), - /** - * Scheduled execution time - */ - scheduledAt: external_exports.string().datetime().optional().describe("ISO 8601 datetime to execute task"), - /** - * Maximum execution attempts - */ - attempts: external_exports.number().int().min(0).default(0).describe("Number of execution attempts"), - /** - * Task status - */ - status: TaskStatus2.default("pending").describe("Current task status"), - /** - * Task metadata - */ - metadata: external_exports.object({ - createdAt: external_exports.string().datetime().optional().describe("When task was created"), - updatedAt: external_exports.string().datetime().optional().describe("Last update time"), - createdBy: external_exports.string().optional().describe("User who created task"), - tags: external_exports.array(external_exports.string()).optional().describe("Task tags for filtering") - }).optional().describe("Task metadata") -}); -var TaskExecutionResultSchema2 = external_exports.object({ - /** - * Task identifier - */ - taskId: external_exports.string().describe("Task identifier"), - /** - * Execution status - */ - status: TaskStatus2.describe("Execution status"), - /** - * Execution result data - */ - result: external_exports.unknown().optional().describe("Execution result data"), - /** - * Error information - */ - error: external_exports.object({ - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Error stack trace"), - code: external_exports.string().optional().describe("Error code") - }).optional().describe("Error details if failed"), - /** - * Execution duration - */ - durationMs: external_exports.number().int().optional().describe("Execution duration in milliseconds"), - /** - * Execution timestamps - */ - startedAt: external_exports.string().datetime().describe("When execution started"), - completedAt: external_exports.string().datetime().optional().describe("When execution completed"), - /** - * Retry information - */ - attempt: external_exports.number().int().min(1).describe("Attempt number (1-indexed)"), - willRetry: external_exports.boolean().describe("Whether task will be retried") -}); -var QueueConfigSchema2 = external_exports.object({ - /** - * Queue name - */ - name: external_exports.string().describe("Queue name (snake_case)"), - /** - * Maximum concurrent workers - */ - concurrency: external_exports.number().int().min(1).default(5).describe("Max concurrent task executions"), - /** - * Rate limiting - */ - rateLimit: external_exports.object({ - max: external_exports.number().int().positive().describe("Maximum tasks per duration"), - duration: external_exports.number().int().positive().describe("Duration in milliseconds") - }).optional().describe("Rate limit configuration"), - /** - * Default retry policy - */ - defaultRetryPolicy: TaskRetryPolicySchema2.optional().describe("Default retry policy for tasks"), - /** - * Dead letter queue - */ - deadLetterQueue: external_exports.string().optional().describe("Dead letter queue name"), - /** - * Queue priority - */ - priority: external_exports.number().int().min(0).default(0).describe("Queue priority (lower = higher priority)"), - /** - * Auto-scaling configuration - */ - autoScale: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable auto-scaling"), - minWorkers: external_exports.number().int().min(1).default(1).describe("Minimum workers"), - maxWorkers: external_exports.number().int().min(1).default(10).describe("Maximum workers"), - scaleUpThreshold: external_exports.number().int().positive().default(100).describe("Queue size to scale up"), - scaleDownThreshold: external_exports.number().int().min(0).default(10).describe("Queue size to scale down") - }).optional().describe("Auto-scaling configuration") -}); -var BatchTaskSchema2 = external_exports.object({ - /** - * Batch job identifier - */ - id: external_exports.string().describe("Unique batch job identifier"), - /** - * Task type for processing each item - */ - type: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Task type (snake_case)"), - /** - * Items to process - */ - items: external_exports.array(external_exports.unknown()).describe("Array of items to process"), - /** - * Batch size (items per task) - */ - batchSize: external_exports.number().int().min(1).default(100).describe("Number of items per batch"), - /** - * Queue name - */ - queue: external_exports.string().default("batch").describe("Queue for batch tasks"), - /** - * Priority - */ - priority: TaskPriority2.default("normal").describe("Batch task priority"), - /** - * Parallel processing - */ - parallel: external_exports.boolean().default(true).describe("Process batches in parallel"), - /** - * Stop on error - */ - stopOnError: external_exports.boolean().default(false).describe("Stop batch if any item fails"), - /** - * Progress callback - * - * Called after each batch completes to report progress. - * Invoked asynchronously and should not throw errors. - * If the callback throws, the error is logged but batch processing continues. - * - * @param progress - Object containing processed count, total count, and failed count - */ - onProgress: external_exports.function().input(external_exports.tuple([external_exports.object({ - processed: external_exports.number(), - total: external_exports.number(), - failed: external_exports.number() - })])).output(external_exports.void()).optional().describe("Progress callback function (called after each batch)") -}); -var BatchProgressSchema2 = external_exports.object({ - /** - * Batch job identifier - */ - batchId: external_exports.string().describe("Batch job identifier"), - /** - * Total items - */ - total: external_exports.number().int().min(0).describe("Total number of items"), - /** - * Processed items - */ - processed: external_exports.number().int().min(0).default(0).describe("Items processed"), - /** - * Successful items - */ - succeeded: external_exports.number().int().min(0).default(0).describe("Items succeeded"), - /** - * Failed items - */ - failed: external_exports.number().int().min(0).default(0).describe("Items failed"), - /** - * Progress percentage - */ - percentage: external_exports.number().min(0).max(100).describe("Progress percentage"), - /** - * Status - */ - status: external_exports.enum(["pending", "running", "completed", "failed", "cancelled"]).describe("Batch status"), - /** - * Timestamps - */ - startedAt: external_exports.string().datetime().optional().describe("When batch started"), - completedAt: external_exports.string().datetime().optional().describe("When batch completed") -}); -var WorkerConfigSchema2 = external_exports.object({ - /** - * Worker name - */ - name: external_exports.string().describe("Worker name"), - /** - * Queues to process - */ - queues: external_exports.array(external_exports.string()).min(1).describe("Queue names to process"), - /** - * Queue configurations - */ - queueConfigs: external_exports.array(QueueConfigSchema2).optional().describe("Queue configurations"), - /** - * Polling interval - */ - pollIntervalMs: external_exports.number().int().positive().default(1e3).describe("Queue polling interval in milliseconds"), - /** - * Visibility timeout - */ - visibilityTimeoutMs: external_exports.number().int().positive().default(3e4).describe("How long a task is invisible after being claimed"), - /** - * Task timeout - */ - defaultTimeoutMs: external_exports.number().int().positive().default(3e5).describe("Default task timeout in milliseconds"), - /** - * Graceful shutdown timeout - */ - shutdownTimeoutMs: external_exports.number().int().positive().default(3e4).describe("Graceful shutdown timeout in milliseconds"), - /** - * Task handlers - */ - handlers: external_exports.record(external_exports.string(), external_exports.function()).optional().describe("Task type handlers") -}); -var WorkerStatsSchema2 = external_exports.object({ - /** - * Worker name - */ - workerName: external_exports.string().describe("Worker name"), - /** - * Total tasks processed - */ - totalProcessed: external_exports.number().int().min(0).describe("Total tasks processed"), - /** - * Successful tasks - */ - succeeded: external_exports.number().int().min(0).describe("Successful tasks"), - /** - * Failed tasks - */ - failed: external_exports.number().int().min(0).describe("Failed tasks"), - /** - * Active tasks - */ - active: external_exports.number().int().min(0).describe("Currently active tasks"), - /** - * Average execution time - */ - avgExecutionMs: external_exports.number().min(0).optional().describe("Average execution time in milliseconds"), - /** - * Uptime - */ - uptimeMs: external_exports.number().int().min(0).describe("Worker uptime in milliseconds"), - /** - * Queue stats - */ - queues: external_exports.record(external_exports.string(), external_exports.object({ - pending: external_exports.number().int().min(0).describe("Pending tasks"), - active: external_exports.number().int().min(0).describe("Active tasks"), - completed: external_exports.number().int().min(0).describe("Completed tasks"), - failed: external_exports.number().int().min(0).describe("Failed tasks") - })).optional().describe("Per-queue statistics") -}); -var Task2 = Object.assign(TaskSchema2, { - create: (task) => task -}); -var QueueConfig2 = Object.assign(QueueConfigSchema2, { - create: (config4) => config4 -}); -var WorkerConfig2 = Object.assign(WorkerConfigSchema2, { - create: (config4) => config4 -}); -var BatchTask2 = Object.assign(BatchTaskSchema2, { - create: (batch) => batch -}); -var EmailTemplateSchema2 = external_exports.object({ - /** - * Unique identifier for the email template - */ - id: external_exports.string().describe("Template identifier"), - /** - * Email subject line (supports variable interpolation) - */ - subject: external_exports.string().describe("Email subject"), - /** - * Email body content - */ - body: external_exports.string().describe("Email body content"), - /** - * Content type of the email body - * @default 'html' - */ - bodyType: external_exports.enum(["text", "html", "markdown"]).optional().default("html").describe("Body content type"), - /** - * List of template variables for dynamic content - */ - variables: external_exports.array(external_exports.string()).optional().describe("Template variables"), - /** - * File attachments to include with the email - */ - attachments: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Attachment filename"), - url: external_exports.string().url().describe("Attachment URL") - })).optional().describe("Email attachments") -}); -var SMSTemplateSchema2 = external_exports.object({ - /** - * Unique identifier for the SMS template - */ - id: external_exports.string().describe("Template identifier"), - /** - * SMS message content (supports variable interpolation) - */ - message: external_exports.string().describe("SMS message content"), - /** - * Maximum character length for the SMS - * @default 160 - */ - maxLength: external_exports.number().optional().default(160).describe("Maximum message length"), - /** - * List of template variables for dynamic content - */ - variables: external_exports.array(external_exports.string()).optional().describe("Template variables") -}); -var PushNotificationSchema2 = external_exports.object({ - /** - * Notification title - */ - title: external_exports.string().describe("Notification title"), - /** - * Notification body text - */ - body: external_exports.string().describe("Notification body"), - /** - * Icon URL to display with notification - */ - icon: external_exports.string().url().optional().describe("Notification icon URL"), - /** - * Badge count to display on app icon - */ - badge: external_exports.number().optional().describe("Badge count"), - /** - * Custom data payload - */ - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom data"), - /** - * Action buttons for the notification - */ - actions: external_exports.array(external_exports.object({ - action: external_exports.string().describe("Action identifier"), - title: external_exports.string().describe("Action button title") - })).optional().describe("Notification actions") -}); -var InAppNotificationSchema2 = external_exports.object({ - /** - * Notification title - */ - title: external_exports.string().describe("Notification title"), - /** - * Notification message content - */ - message: external_exports.string().describe("Notification message"), - /** - * Notification severity type - */ - type: external_exports.enum(["info", "success", "warning", "error"]).describe("Notification type"), - /** - * Optional URL to navigate to when clicked - */ - actionUrl: external_exports.string().optional().describe("Action URL"), - /** - * Whether the notification can be dismissed by the user - * @default true - */ - dismissible: external_exports.boolean().optional().default(true).describe("User dismissible"), - /** - * Timestamp when notification expires (Unix milliseconds) - */ - expiresAt: external_exports.number().optional().describe("Expiration timestamp") -}); -var NotificationChannelSchema2 = external_exports.enum([ - "email", - "sms", - "push", - "in-app", - "slack", - "teams", - "webhook" -]); -var NotificationConfigSchema22 = external_exports.object({ - /** - * Unique identifier for this notification configuration - */ - id: external_exports.string().describe("Notification ID"), - /** - * Human-readable name for this notification - */ - name: external_exports.string().describe("Notification name"), - /** - * Delivery channel for the notification - */ - channel: NotificationChannelSchema2.describe("Notification channel"), - /** - * Notification template based on channel type - */ - template: external_exports.union([ - EmailTemplateSchema2, - SMSTemplateSchema2, - PushNotificationSchema2, - InAppNotificationSchema2 - ]).describe("Notification template"), - /** - * Recipient configuration - */ - recipients: external_exports.object({ - /** - * Primary recipients - */ - to: external_exports.array(external_exports.string()).describe("Primary recipients"), - /** - * CC recipients (email only) - */ - cc: external_exports.array(external_exports.string()).optional().describe("CC recipients"), - /** - * BCC recipients (email only) - */ - bcc: external_exports.array(external_exports.string()).optional().describe("BCC recipients") - }).describe("Recipients"), - /** - * Scheduling configuration - */ - schedule: external_exports.object({ - /** - * Scheduling type - */ - type: external_exports.enum(["immediate", "delayed", "scheduled"]).describe("Schedule type"), - /** - * Delay in milliseconds (for delayed type) - */ - delay: external_exports.number().optional().describe("Delay in milliseconds"), - /** - * Scheduled send time (Unix timestamp in milliseconds) - */ - scheduledAt: external_exports.number().optional().describe("Scheduled timestamp") - }).optional().describe("Scheduling"), - /** - * Retry policy for failed deliveries - */ - retryPolicy: external_exports.object({ - /** - * Enable automatic retries - * @default true - */ - enabled: external_exports.boolean().optional().default(true).describe("Enable retries"), - /** - * Maximum number of retry attempts - * @default 3 - */ - maxRetries: external_exports.number().optional().default(3).describe("Max retry attempts"), - /** - * Backoff strategy for retries - */ - backoffStrategy: external_exports.enum(["exponential", "linear", "fixed"]).describe("Backoff strategy") - }).optional().describe("Retry policy"), - /** - * Delivery tracking configuration - */ - tracking: external_exports.object({ - /** - * Track when emails are opened - * @default false - */ - trackOpens: external_exports.boolean().optional().default(false).describe("Track opens"), - /** - * Track when links are clicked - * @default false - */ - trackClicks: external_exports.boolean().optional().default(false).describe("Track clicks"), - /** - * Track delivery status - * @default true - */ - trackDelivery: external_exports.boolean().optional().default(true).describe("Track delivery") - }).optional().describe("Tracking configuration") -}); -var LocaleSchema3 = external_exports.string().describe("BCP-47 Language Tag (e.g. en-US, zh-CN)"); -var FieldTranslationSchema3 = external_exports.object({ - label: external_exports.string().optional().describe("Translated field label"), - help: external_exports.string().optional().describe("Translated help text"), - placeholder: external_exports.string().optional().describe("Translated placeholder text for form inputs"), - options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Option value to translated label map") -}).describe("Translation data for a single field"); -var ObjectTranslationDataSchema3 = external_exports.object({ - /** Translated singular label for the object */ - label: external_exports.string().describe("Translated singular label"), - /** Translated plural label for the object */ - pluralLabel: external_exports.string().optional().describe("Translated plural label"), - /** Field-level translations keyed by field name (snake_case) */ - fields: external_exports.record(external_exports.string(), FieldTranslationSchema3).optional().describe("Field-level translations") -}).describe("Translation data for a single object"); -var TranslationDataSchema3 = external_exports.object({ - /** Object translations */ - objects: external_exports.record(external_exports.string(), ObjectTranslationDataSchema3).optional().describe("Object translations keyed by object name"), - /** App/Menu translations */ - apps: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().describe("Translated app label"), - description: external_exports.string().optional().describe("Translated app description") - })).optional().describe("App translations keyed by app name"), - /** UI Messages */ - messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID"), - /** Validation Error Messages */ - validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%"})') -}).describe("Translation data for objects, apps, and UI messages"); -var TranslationBundleSchema2 = external_exports.record(LocaleSchema3, TranslationDataSchema3).describe("Map of locale codes to translation data"); -var TranslationFileOrganizationSchema3 = external_exports.enum([ - "bundled", - "per_locale", - "per_namespace" -]).describe("Translation file organization strategy"); -var MessageFormatSchema3 = external_exports.enum([ - "icu", - "simple" -]).describe("Message interpolation format: ICU MessageFormat or simple {variable} replacement"); -var TranslationConfigSchema2 = external_exports.object({ - /** Default locale for the application */ - defaultLocale: LocaleSchema3.describe('Default locale (e.g., "en")'), - /** Supported BCP-47 locale codes */ - supportedLocales: external_exports.array(LocaleSchema3).describe("Supported BCP-47 locale codes"), - /** Fallback locale when translation is not found */ - fallbackLocale: LocaleSchema3.optional().describe("Fallback locale code"), - /** How translation files are organized on disk */ - fileOrganization: TranslationFileOrganizationSchema3.default("per_locale").describe("File organization strategy"), - /** - * Message interpolation format. - * When set to `'icu'`, messages and validationMessages are expected to use - * ICU MessageFormat syntax (plurals, select, number/date skeletons). - * @default 'simple' - */ - messageFormat: MessageFormatSchema3.default("simple").describe("Message interpolation format (ICU MessageFormat or simple)"), - /** Load translations on demand instead of eagerly */ - lazyLoad: external_exports.boolean().default(false).describe("Load translations on demand"), - /** Cache loaded translations in memory */ - cache: external_exports.boolean().default(true).describe("Cache loaded translations") -}).describe("Internationalization configuration"); -var OptionTranslationMapSchema3 = external_exports.record(external_exports.string(), external_exports.string()).describe("Option value to translated label map"); -var ObjectTranslationNodeSchema3 = external_exports.object({ - /** Translated singular label */ - label: external_exports.string().describe("Translated singular label"), - /** Translated plural label */ - pluralLabel: external_exports.string().optional().describe("Translated plural label"), - /** Translated object description */ - description: external_exports.string().optional().describe("Translated object description"), - /** Translated help text shown in tooltips or guidance panels */ - helpText: external_exports.string().optional().describe("Translated help text for the object"), - /** Field-level translations keyed by field name (snake_case) */ - fields: external_exports.record(external_exports.string(), FieldTranslationSchema3).optional().describe("Field translations keyed by field name"), - /** - * Global picklist / select option overrides scoped to this object. - * Keyed by field name → { optionValue: translatedLabel }. - */ - _options: external_exports.record(external_exports.string(), OptionTranslationMapSchema3).optional().describe("Object-scoped picklist option translations keyed by field name"), - /** View translations keyed by view name */ - _views: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated view label"), - description: external_exports.string().optional().describe("Translated view description") - })).optional().describe("View translations keyed by view name"), - /** Section (form section / tab) translations keyed by section name */ - _sections: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated section label") - })).optional().describe("Section translations keyed by section name"), - /** Action translations keyed by action name */ - _actions: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated action label"), - confirmMessage: external_exports.string().optional().describe("Translated confirmation message") - })).optional().describe("Action translations keyed by action name"), - /** Notification message translations keyed by notification name */ - _notifications: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated notification title"), - body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") - })).optional().describe("Notification translations keyed by notification name"), - /** Error message translations keyed by error code */ - _errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Error message translations keyed by error code") -}).describe("Object-first aggregated translation node"); -var AppTranslationBundleSchema2 = external_exports.object({ - /** - * Bundle-level metadata. - * Provides locale-aware rendering hints such as text direction (bidi) - * and the canonical locale code this bundle represents. - */ - _meta: external_exports.object({ - /** BCP-47 locale code this bundle represents */ - locale: external_exports.string().optional().describe("BCP-47 locale code for this bundle"), - /** Text direction for the locale */ - direction: external_exports.enum(["ltr", "rtl"]).optional().describe("Text direction: left-to-right or right-to-left") - }).optional().describe("Bundle-level metadata (locale, bidi direction)"), - /** - * Namespace for plugin/extension isolation. - * When multiple plugins contribute translations, each should use a unique - * namespace to avoid key collisions (e.g. "crm", "helpdesk", "plugin-xyz"). - */ - namespace: external_exports.string().optional().describe("Namespace for plugin isolation to avoid translation key collisions"), - /** Object-first translations keyed by object name (snake_case) */ - o: external_exports.record(external_exports.string(), ObjectTranslationNodeSchema3).optional().describe("Object-first translations keyed by object name"), - /** Global picklist options not bound to any specific object */ - _globalOptions: external_exports.record(external_exports.string(), OptionTranslationMapSchema3).optional().describe("Global picklist option translations keyed by option set name"), - /** App-level translations */ - app: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().describe("Translated app label"), - description: external_exports.string().optional().describe("Translated app description") - })).optional().describe("App translations keyed by app name"), - /** Navigation menu translations */ - nav: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Navigation item translations keyed by nav item name"), - /** Dashboard translations keyed by dashboard name */ - dashboard: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated dashboard label"), - description: external_exports.string().optional().describe("Translated dashboard description") - })).optional().describe("Dashboard translations keyed by dashboard name"), - /** Report translations keyed by report name */ - reports: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().optional().describe("Translated report label"), - description: external_exports.string().optional().describe("Translated report description") - })).optional().describe("Report translations keyed by report name"), - /** Page translations keyed by page name */ - pages: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated page title"), - description: external_exports.string().optional().describe("Translated page description") - })).optional().describe("Page translations keyed by page name"), - /** UI message translations (supports ICU MessageFormat when enabled) */ - messages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("UI message translations keyed by message ID (supports ICU MessageFormat)"), - /** Validation error message translations (supports ICU MessageFormat when enabled) */ - validationMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Validation error message translations keyed by rule name (supports ICU MessageFormat)"), - /** Global notification translations not bound to a specific object */ - notifications: external_exports.record(external_exports.string(), external_exports.object({ - title: external_exports.string().optional().describe("Translated notification title"), - body: external_exports.string().optional().describe("Translated notification body (supports ICU MessageFormat when enabled)") - })).optional().describe("Global notification translations keyed by notification name"), - /** Global error message translations not bound to a specific object */ - errors: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Global error message translations keyed by error code") -}).describe("Object-first application translation bundle for a single locale"); -var TranslationDiffStatusSchema3 = external_exports.enum([ - "missing", - "redundant", - "stale" -]).describe("Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)"); -var TranslationDiffItemSchema3 = external_exports.object({ - /** Dot-path translation key (e.g. "o.account.fields.website.label") */ - key: external_exports.string().describe("Dot-path translation key"), - /** Diff status */ - status: TranslationDiffStatusSchema3.describe("Diff status of this translation key"), - /** Object name if the key belongs to an object translation node */ - objectName: external_exports.string().optional().describe("Associated object name (snake_case)"), - /** Locale code */ - locale: external_exports.string().describe("BCP-47 locale code"), - /** - * Hash of the source metadata value at the time the translation was made. - * Used by CLI/Workbench to detect stale translations without a full diff. - */ - sourceHash: external_exports.string().optional().describe("Hash of source metadata for precise stale detection"), - /** - * AI-suggested translation text for missing or stale entries. - * Populated by AI translation hooks or TMS integrations. - */ - aiSuggested: external_exports.string().optional().describe("AI-suggested translation for this key"), - /** Confidence score (0-1) for the AI suggestion */ - aiConfidence: external_exports.number().min(0).max(1).optional().describe("AI suggestion confidence score (0\u20131)") -}).describe("A single translation diff item"); -var CoverageBreakdownEntrySchema3 = external_exports.object({ - /** Group category (e.g. "fields", "views", "actions", "messages") */ - group: external_exports.string().describe("Translation group category"), - /** Total translatable keys in this group */ - totalKeys: external_exports.number().int().nonnegative().describe("Total keys in this group"), - /** Number of translated keys in this group */ - translatedKeys: external_exports.number().int().nonnegative().describe("Translated keys in this group"), - /** Coverage percentage for this group */ - coveragePercent: external_exports.number().min(0).max(100).describe("Coverage percentage for this group") -}).describe("Coverage breakdown for a single translation group"); -var TranslationCoverageResultSchema2 = external_exports.object({ - /** BCP-47 locale code */ - locale: external_exports.string().describe("BCP-47 locale code"), - /** Optional object name scope */ - objectName: external_exports.string().optional().describe("Object name scope (omit for full bundle)"), - /** Total translatable keys derived from metadata */ - totalKeys: external_exports.number().int().nonnegative().describe("Total translatable keys from metadata"), - /** Number of keys that have a translation */ - translatedKeys: external_exports.number().int().nonnegative().describe("Number of translated keys"), - /** Number of missing translations */ - missingKeys: external_exports.number().int().nonnegative().describe("Number of missing translations"), - /** Number of redundant (orphaned) translations */ - redundantKeys: external_exports.number().int().nonnegative().describe("Number of redundant translations"), - /** Number of stale translations */ - staleKeys: external_exports.number().int().nonnegative().describe("Number of stale translations"), - /** Coverage percentage (0-100) */ - coveragePercent: external_exports.number().min(0).max(100).describe("Translation coverage percentage"), - /** Individual diff items */ - items: external_exports.array(TranslationDiffItemSchema3).describe("Detailed diff items"), - /** - * Per-group coverage breakdown for translation project management. - * Each entry represents a logical group (e.g. "fields", "views", "actions", - * "messages") with its own coverage statistics. - */ - breakdown: external_exports.array(CoverageBreakdownEntrySchema3).optional().describe("Per-group coverage breakdown") -}).describe("Aggregated translation coverage result"); -var TRANSLATE_PLACEHOLDER = "__TRANSLATE__"; -var OTOperationType2 = external_exports.enum([ - "insert", - // Insert characters at position - "delete", - // Delete characters at position - "retain" - // Keep characters (used for composing operations) -]); -var OTComponentSchema2 = external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("insert"), - text: external_exports.string().describe("Text to insert"), - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Text formatting attributes (e.g., bold, italic)") - }), - external_exports.object({ - type: external_exports.literal("delete"), - count: external_exports.number().int().positive().describe("Number of characters to delete") - }), - external_exports.object({ - type: external_exports.literal("retain"), - count: external_exports.number().int().positive().describe("Number of characters to retain"), - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Attribute changes to apply") - }) -]); -var OTOperationSchema2 = external_exports.object({ - operationId: external_exports.string().uuid().describe("Unique operation identifier"), - documentId: external_exports.string().describe("Document identifier"), - userId: external_exports.string().describe("User who created the operation"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - components: external_exports.array(OTComponentSchema2).describe("Operation components"), - baseVersion: external_exports.number().int().nonnegative().describe("Document version this operation is based on"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when operation was created"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional operation metadata") -}); -var OTTransformResultSchema2 = external_exports.object({ - operation: OTOperationSchema2.describe("Transformed operation"), - transformed: external_exports.boolean().describe("Whether transformation was applied"), - conflicts: external_exports.array(external_exports.string()).optional().describe("Conflict descriptions if any") -}); -var CRDTType2 = external_exports.enum([ - "lww-register", - // Last-Write-Wins Register - "g-counter", - // Grow-only Counter - "pn-counter", - // Positive-Negative Counter - "g-set", - // Grow-only Set - "or-set", - // Observed-Remove Set - "lww-map", - // Last-Write-Wins Map - "text", - // CRDT-based Text (e.g., Yjs, Automerge) - "tree", - // CRDT-based Tree structure - "json" - // CRDT-based JSON (e.g., Automerge) -]); -var VectorClockSchema2 = external_exports.object({ - clock: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Map of replica ID to logical timestamp") -}); -var LWWRegisterSchema2 = external_exports.object({ - type: external_exports.literal("lww-register"), - value: external_exports.unknown().describe("Current register value"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of last write"), - replicaId: external_exports.string().describe("ID of replica that performed last write"), - vectorClock: VectorClockSchema2.optional().describe("Optional vector clock for causality tracking") -}); -var CounterOperationSchema2 = external_exports.object({ - replicaId: external_exports.string().describe("Replica identifier"), - delta: external_exports.number().int().describe("Change amount (positive for increment, negative for decrement)"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of operation") -}); -var GCounterSchema2 = external_exports.object({ - type: external_exports.literal("g-counter"), - counts: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Map of replica ID to count") -}); -var PNCounterSchema2 = external_exports.object({ - type: external_exports.literal("pn-counter"), - positive: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Positive increments per replica"), - negative: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).describe("Negative increments per replica") -}); -var ORSetElementSchema2 = external_exports.object({ - value: external_exports.unknown().describe("Element value"), - timestamp: external_exports.string().datetime().describe("Addition timestamp"), - replicaId: external_exports.string().describe("Replica that added the element"), - uid: external_exports.string().uuid().describe("Unique identifier for this addition"), - removed: external_exports.boolean().optional().default(false).describe("Whether element has been removed") -}); -var ORSetSchema2 = external_exports.object({ - type: external_exports.literal("or-set"), - elements: external_exports.array(ORSetElementSchema2).describe("Set elements with metadata") -}); -var TextCRDTOperationSchema2 = external_exports.object({ - operationId: external_exports.string().uuid().describe("Unique operation identifier"), - replicaId: external_exports.string().describe("Replica identifier"), - position: external_exports.number().int().nonnegative().describe("Position in document"), - insert: external_exports.string().optional().describe("Text to insert"), - delete: external_exports.number().int().positive().optional().describe("Number of characters to delete"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of operation"), - lamportTimestamp: external_exports.number().int().nonnegative().describe("Lamport timestamp for ordering") -}); -var TextCRDTStateSchema2 = external_exports.object({ - type: external_exports.literal("text"), - documentId: external_exports.string().describe("Document identifier"), - content: external_exports.string().describe("Current text content"), - operations: external_exports.array(TextCRDTOperationSchema2).describe("History of operations"), - lamportClock: external_exports.number().int().nonnegative().describe("Current Lamport clock value"), - vectorClock: VectorClockSchema2.describe("Vector clock for causality") -}); -var CRDTStateSchema2 = external_exports.discriminatedUnion("type", [ - LWWRegisterSchema2, - GCounterSchema2, - PNCounterSchema2, - ORSetSchema2, - TextCRDTStateSchema2 -]); -var CRDTMergeResultSchema2 = external_exports.object({ - state: CRDTStateSchema2.describe("Merged CRDT state"), - conflicts: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Conflict type"), - description: external_exports.string().describe("Conflict description"), - resolved: external_exports.boolean().describe("Whether conflict was automatically resolved") - })).optional().describe("Conflicts encountered during merge") -}); -var CursorColorPreset2 = external_exports.enum([ - "blue", - "green", - "red", - "yellow", - "purple", - "orange", - "pink", - "teal", - "indigo", - "cyan" -]); -var CursorStyleSchema2 = external_exports.object({ - color: external_exports.union([CursorColorPreset2, external_exports.string()]).describe("Cursor color (preset or custom hex)"), - opacity: external_exports.number().min(0).max(1).optional().default(1).describe("Cursor opacity (0-1)"), - label: external_exports.string().optional().describe("Label to display with cursor (usually username)"), - showLabel: external_exports.boolean().optional().default(true).describe("Whether to show label"), - pulseOnUpdate: external_exports.boolean().optional().default(true).describe("Whether to pulse when cursor moves") -}); -var CursorSelectionSchema2 = external_exports.object({ - anchor: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Anchor line number"), - column: external_exports.number().int().nonnegative().describe("Anchor column number") - }).describe("Selection anchor (start point)"), - focus: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Focus line number"), - column: external_exports.number().int().nonnegative().describe("Focus column number") - }).describe("Selection focus (end point)"), - direction: external_exports.enum(["forward", "backward"]).optional().describe("Selection direction") -}); -var CollaborativeCursorSchema2 = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - documentId: external_exports.string().describe("Document identifier"), - userName: external_exports.string().describe("Display name of user"), - position: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Cursor line number (0-indexed)"), - column: external_exports.number().int().nonnegative().describe("Cursor column number (0-indexed)") - }).describe("Current cursor position"), - selection: CursorSelectionSchema2.optional().describe("Current text selection"), - style: CursorStyleSchema2.describe("Visual style for this cursor"), - isTyping: external_exports.boolean().optional().default(false).describe("Whether user is currently typing"), - lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last cursor update"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional cursor metadata") -}); -var CursorUpdateSchema2 = external_exports.object({ - position: external_exports.object({ - line: external_exports.number().int().nonnegative(), - column: external_exports.number().int().nonnegative() - }).optional().describe("Updated cursor position"), - selection: CursorSelectionSchema2.optional().describe("Updated selection"), - isTyping: external_exports.boolean().optional().describe("Updated typing state"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") -}); -var UserActivityStatus2 = external_exports.enum([ - "active", - // User is actively editing - "idle", - // User is idle but connected - "viewing", - // User is viewing but not editing - "disconnected" - // User is disconnected -]); -var AwarenessUserStateSchema2 = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - userName: external_exports.string().describe("Display name"), - userAvatar: external_exports.string().optional().describe("User avatar URL"), - status: UserActivityStatus2.describe("Current activity status"), - currentDocument: external_exports.string().optional().describe("Document ID user is currently editing"), - currentView: external_exports.string().optional().describe("Current view/page user is on"), - lastActivity: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), - joinedAt: external_exports.string().datetime().describe("ISO 8601 datetime when user joined session"), - permissions: external_exports.array(external_exports.string()).optional().describe("User permissions in this session"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional user state metadata") -}); -var AwarenessSessionSchema2 = external_exports.object({ - sessionId: external_exports.string().uuid().describe("Session identifier"), - documentId: external_exports.string().optional().describe("Document ID this session is for"), - users: external_exports.array(AwarenessUserStateSchema2).describe("Active users in session"), - startedAt: external_exports.string().datetime().describe("ISO 8601 datetime when session started"), - lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last update"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Session metadata") -}); -var AwarenessUpdateSchema2 = external_exports.object({ - status: UserActivityStatus2.optional().describe("Updated status"), - currentDocument: external_exports.string().optional().describe("Updated current document"), - currentView: external_exports.string().optional().describe("Updated current view"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") -}); -var AwarenessEventSchema2 = external_exports.object({ - eventId: external_exports.string().uuid().describe("Event identifier"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - eventType: external_exports.enum([ - "user.joined", - "user.left", - "user.updated", - "session.created", - "session.ended" - ]).describe("Type of awareness event"), - userId: external_exports.string().optional().describe("User involved in event"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime of event"), - payload: external_exports.unknown().describe("Event payload") -}); -var CollaborationMode2 = external_exports.enum([ - "ot", - // Operational Transformation - "crdt", - // CRDT-based - "lock", - // Pessimistic locking (turn-based) - "hybrid" - // Hybrid approach -]); -var CollaborationSessionConfigSchema2 = external_exports.object({ - mode: CollaborationMode2.describe("Collaboration mode to use"), - enableCursorSharing: external_exports.boolean().optional().default(true).describe("Enable cursor sharing"), - enablePresence: external_exports.boolean().optional().default(true).describe("Enable presence tracking"), - enableAwareness: external_exports.boolean().optional().default(true).describe("Enable awareness state"), - maxUsers: external_exports.number().int().positive().optional().describe("Maximum concurrent users"), - idleTimeout: external_exports.number().int().positive().optional().default(3e5).describe("Idle timeout in milliseconds"), - conflictResolution: external_exports.enum(["ot", "crdt", "manual"]).optional().default("ot").describe("Conflict resolution strategy"), - persistence: external_exports.boolean().optional().default(true).describe("Enable operation persistence"), - snapshot: external_exports.object({ - enabled: external_exports.boolean().describe("Enable periodic snapshots"), - interval: external_exports.number().int().positive().describe("Snapshot interval in milliseconds") - }).optional().describe("Snapshot configuration") -}); -var CollaborationSessionSchema2 = external_exports.object({ - sessionId: external_exports.string().uuid().describe("Session identifier"), - documentId: external_exports.string().describe("Document identifier"), - config: CollaborationSessionConfigSchema2.describe("Session configuration"), - users: external_exports.array(AwarenessUserStateSchema2).describe("Active users"), - cursors: external_exports.array(CollaborativeCursorSchema2).describe("Active cursors"), - version: external_exports.number().int().nonnegative().describe("Current document version"), - operations: external_exports.array(external_exports.union([OTOperationSchema2, TextCRDTOperationSchema2])).optional().describe("Recent operations"), - createdAt: external_exports.string().datetime().describe("ISO 8601 datetime when session was created"), - lastActivity: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), - status: external_exports.enum(["active", "idle", "ended"]).describe("Session status") -}); -var MetadataScopeSchema2 = external_exports.enum([ - "system", - // Defined in Code (Files). Read-only at runtime. Upgraded via deployment. - "platform", - // Defined in DB (Global). admin-configured. Overrides system. - "user" - // Defined in DB (Personal). User-configured. Overrides platform/system. -]); -var MetadataStateSchema2 = external_exports.enum([ - "draft", - // Work in progress, not active - "active", - // Live and running - "archived", - // Soft deleted - "deprecated" - // Running but flagged for removal -]); -var MetadataRecordSchema2 = external_exports.object({ - /** Primary Key (UUID) */ - id: external_exports.string(), - /** - * Machine Name - * The unique identifier used in code references (e.g. "account_list_view"). - */ - name: external_exports.string(), - /** - * Metadata Type - * e.g. "object", "view", "permission_set", "flow" - */ - type: external_exports.string(), - /** - * Namespace / Module - * Groups metadata into packages (e.g. "crm", "finance", "core"). - */ - namespace: external_exports.string().default("default"), - /** - * Package Ownership Reference - * Links this metadata record to the package that delivered it. - * When set, the record is "managed" by the package and should not be - * directly edited — customizations go through the overlay system. - * Null/undefined means the record was created independently (not from a package). - */ - packageId: external_exports.string().optional().describe("Package ID that owns/delivered this metadata"), - /** - * Managed By Indicator - * Determines who controls this metadata record's lifecycle. - * - "package": Delivered and upgraded by a plugin package (read-only base) - * - "platform": Created by platform admin via UI - * - "user": Created by end user - */ - managedBy: external_exports.enum(["package", "platform", "user"]).optional().describe("Who manages this metadata record lifecycle"), - /** - * Ownership differentiation - */ - scope: MetadataScopeSchema2.default("platform"), - /** - * The Payload - * Stores the actual configuration JSON. - * This field holds the value of `ViewSchema`, `ObjectSchema`, etc. - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()), - /** - * Extension / Merge Strategy - * If this record overrides a system record, how should it be applied? - */ - extends: external_exports.string().optional().describe("Name of the parent metadata to extend/override"), - strategy: external_exports.enum(["merge", "replace"]).default("merge"), - /** Owner (for user-scope items) */ - owner: external_exports.string().optional(), - /** State */ - state: MetadataStateSchema2.default("active"), - /** Tenant ID for multi-tenant isolation */ - tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant isolation"), - /** Version number for optimistic concurrency */ - version: external_exports.number().default(1).describe("Record version for optimistic concurrency control"), - /** Checksum for change detection */ - checksum: external_exports.string().optional().describe("Content checksum for change detection"), - /** Source origin marker */ - source: external_exports.enum(["filesystem", "database", "api", "migration"]).optional().describe("Origin of this metadata record"), - /** Classification tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Classification tags for filtering and grouping"), - /** Package Publishing */ - publishedDefinition: external_exports.unknown().optional().describe("Snapshot of the last published definition"), - publishedAt: external_exports.string().datetime().optional().describe("When this metadata was last published"), - publishedBy: external_exports.string().optional().describe("Who published this version"), - /** Audit */ - createdBy: external_exports.string().optional(), - createdAt: external_exports.string().datetime().optional().describe("Creation timestamp"), - updatedBy: external_exports.string().optional(), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp") -}); -var PackagePublishResultSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Whether the publish succeeded"), - packageId: external_exports.string().describe("The package ID that was published"), - version: external_exports.number().int().describe("New version number after publish"), - publishedAt: external_exports.string().datetime().describe("Publish timestamp"), - itemsPublished: external_exports.number().int().describe("Total metadata items published"), - validationErrors: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type that failed validation"), - name: external_exports.string().describe("Item name that failed validation"), - message: external_exports.string().describe("Validation error message") - })).optional().describe("Validation errors if publish failed") -}); -var MetadataFormatSchema22 = external_exports.enum([ - "json", - "yaml", - "yml", - "ts", - "js", - "typescript", - "javascript" - // Aliases -]); -var MetadataStatsSchema4 = external_exports.object({ - path: external_exports.string().optional(), - size: external_exports.number().optional(), - mtime: external_exports.string().datetime().optional(), - hash: external_exports.string().optional(), - etag: external_exports.string().optional(), - // Required by local cache - modifiedAt: external_exports.string().datetime().optional(), - // Alias for mtime - format: MetadataFormatSchema22.optional() - // Required for serialization -}); -var MetadataLoaderContractSchema3 = external_exports.object({ - name: external_exports.string(), - protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Loader protocol identifier"), - description: external_exports.string().optional(), - supportedFormats: external_exports.array(external_exports.string()).optional(), - supportsWatch: external_exports.boolean().optional(), - supportsWrite: external_exports.boolean().optional(), - supportsCache: external_exports.boolean().optional(), - capabilities: external_exports.object({ - read: external_exports.boolean().default(true), - write: external_exports.boolean().default(false), - watch: external_exports.boolean().default(false), - list: external_exports.boolean().default(true) - }) -}); -var MetadataLoadOptionsSchema3 = external_exports.object({ - scope: MetadataScopeSchema2.optional(), - namespace: external_exports.string().optional(), - raw: external_exports.boolean().optional().describe("Return raw file content instead of parsed JSON"), - cache: external_exports.boolean().optional(), - useCache: external_exports.boolean().optional(), - // Alias for cache - validate: external_exports.boolean().optional(), - ifNoneMatch: external_exports.string().optional(), - // For caching - recursive: external_exports.boolean().optional(), - limit: external_exports.number().optional(), - patterns: external_exports.array(external_exports.string()).optional(), - loader: external_exports.string().optional().describe("Specific loader to use (e.g. filesystem, database)") -}); -var MetadataLoadResultSchema3 = external_exports.object({ - data: external_exports.unknown(), - stats: MetadataStatsSchema4.optional(), - format: MetadataFormatSchema22.optional(), - source: external_exports.string().optional(), - // File path or URL - fromCache: external_exports.boolean().optional(), - etag: external_exports.string().optional(), - notModified: external_exports.boolean().optional(), - loadTime: external_exports.number().optional() -}); -var MetadataSaveOptionsSchema3 = external_exports.object({ - format: MetadataFormatSchema22.optional(), - create: external_exports.boolean().default(true), - overwrite: external_exports.boolean().default(true), - path: external_exports.string().optional(), - prettify: external_exports.boolean().optional(), - indent: external_exports.number().optional(), - sortKeys: external_exports.boolean().optional(), - backup: external_exports.boolean().optional(), - atomic: external_exports.boolean().optional(), - loader: external_exports.string().optional().describe("Specific loader to use (e.g. filesystem, database)") -}); -var MetadataSaveResultSchema3 = external_exports.object({ - success: external_exports.boolean(), - path: external_exports.string().optional(), - stats: MetadataStatsSchema4.optional(), - etag: external_exports.string().optional(), - size: external_exports.number().optional(), - saveTime: external_exports.number().optional(), - backupPath: external_exports.string().optional() -}); -var MetadataWatchEventSchema3 = external_exports.object({ - type: external_exports.enum(["add", "change", "unlink", "added", "changed", "deleted"]), - path: external_exports.string(), - name: external_exports.string().optional(), - stats: MetadataStatsSchema4.optional(), - metadataType: external_exports.string().optional(), - data: external_exports.unknown().optional(), - timestamp: external_exports.string().datetime().optional() -}); -var MetadataCollectionInfoSchema3 = external_exports.object({ - type: external_exports.string(), - count: external_exports.number(), - namespaces: external_exports.array(external_exports.string()) -}); -var MetadataExportOptionsSchema3 = external_exports.object({ - types: external_exports.array(external_exports.string()).optional(), - namespaces: external_exports.array(external_exports.string()).optional(), - output: external_exports.string().describe("Output directory or file"), - format: MetadataFormatSchema22.default("json") -}); -var MetadataImportOptionsSchema3 = external_exports.object({ - source: external_exports.string().describe("Input directory or file"), - strategy: external_exports.enum(["merge", "replace", "skip"]).default("merge"), - validate: external_exports.boolean().default(true) -}); -var MetadataFallbackStrategySchema4 = external_exports.enum([ - "filesystem", - // Fall back to filesystem-based loading - "memory", - // Fall back to in-memory storage - "none" - // No fallback — fail immediately -]); -var MetadataSourceSchema2 = external_exports.enum([ - "filesystem", - // Loaded from local files - "database", - // Loaded from database via datasource - "api", - // Loaded from remote API - "migration" - // Created during a migration process -]); -var MetadataManagerConfigSchema4 = external_exports.object({ - /** - * Datasource Name Reference - * References a DatasourceSchema.name (e.g. 'default'). - * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. - * When provided, metadata is persisted to a database table. - */ - datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), - /** - * Metadata Table Name - * The database table used for metadata storage when datasource is configured. - */ - tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), - /** - * Fallback Strategy - * Determines behavior when the primary datasource is unavailable. - */ - fallback: MetadataFallbackStrategySchema4.default("none").describe("Fallback strategy when datasource is unavailable"), - /** - * Root directory for metadata (for filesystem loaders) - */ - rootDir: external_exports.string().optional().describe("Root directory for filesystem-based metadata"), - /** - * Enabled serialization formats - */ - formats: external_exports.array(MetadataFormatSchema22).optional().describe("Enabled metadata formats"), - /** - * Enable file watching - */ - watch: external_exports.boolean().optional().describe("Enable file watching for filesystem loaders"), - /** - * Cache configuration - */ - cache: external_exports.boolean().optional().describe("Enable metadata caching"), - /** - * Watch options - */ - watchOptions: external_exports.object({ - ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), - persistent: external_exports.boolean().default(true).describe("Keep process running") - }).optional().describe("File watcher options") -}); -var MetadataHistoryRecordSchema2 = external_exports.object({ - /** Primary Key (UUID) */ - id: external_exports.string(), - /** Reference to the parent metadata record ID */ - metadataId: external_exports.string().describe("Foreign key to sys_metadata.id"), - /** - * Machine Name - * Denormalized from parent for easier querying. - */ - name: external_exports.string(), - /** - * Metadata Type - * Denormalized from parent for easier querying. - */ - type: external_exports.string(), - /** - * Version Number - * Snapshot of the metadata version at this point in history. - */ - version: external_exports.number().describe("Version number at this snapshot"), - /** - * Operation Type - * Indicates what kind of change triggered this history record. - */ - operationType: external_exports.enum(["create", "update", "publish", "revert", "delete"]).describe("Type of operation that created this history entry"), - /** - * Historical Metadata Snapshot - * Full JSON payload of the metadata definition at this version. - * May be stored as a raw JSON string in the history table, or as a parsed object - * in higher-level APIs. When `includeMetadata` is false, this field is null. - */ - metadata: external_exports.union([external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown())]).nullable().optional().describe("Snapshot of metadata definition at this version (raw JSON string or parsed object)"), - /** - * Content Checksum - * SHA-256 checksum of the normalized metadata JSON for change detection. - */ - checksum: external_exports.string().describe("SHA-256 checksum of metadata content"), - /** - * Previous Checksum - * Checksum of the previous version for diff optimization. - */ - previousChecksum: external_exports.string().optional().describe("Checksum of the previous version"), - /** - * Change Note - * Human-readable description of what changed in this version. - */ - changeNote: external_exports.string().optional().describe("Description of changes made in this version"), - /** Tenant ID for multi-tenant isolation */ - tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant isolation"), - /** Audit: who made this change */ - recordedBy: external_exports.string().optional().describe("User who made this change"), - /** Audit: when was this version recorded */ - recordedAt: external_exports.string().datetime().describe("Timestamp when this version was recorded") -}); -var MetadataHistoryQueryOptionsSchema2 = external_exports.object({ - /** Limit number of history records returned */ - limit: external_exports.number().int().positive().optional().describe("Maximum number of history records to return"), - /** Offset for pagination */ - offset: external_exports.number().int().nonnegative().optional().describe("Number of records to skip"), - /** Only return versions after this timestamp */ - since: external_exports.string().datetime().optional().describe("Only return history after this timestamp"), - /** Only return versions before this timestamp */ - until: external_exports.string().datetime().optional().describe("Only return history before this timestamp"), - /** Filter by operation type */ - operationType: external_exports.enum(["create", "update", "publish", "revert", "delete"]).optional().describe("Filter by operation type"), - /** Include full metadata payload in results (default: true) */ - includeMetadata: external_exports.boolean().optional().default(true).describe("Include full metadata payload") -}); -var MetadataHistoryQueryResultSchema2 = external_exports.object({ - /** Array of history records */ - records: external_exports.array(MetadataHistoryRecordSchema2), - /** Total number of history records (for pagination) */ - total: external_exports.number().int().nonnegative(), - /** Whether there are more records available */ - hasMore: external_exports.boolean() -}); -var MetadataDiffResultSchema2 = external_exports.object({ - /** Metadata type */ - type: external_exports.string(), - /** Metadata name */ - name: external_exports.string(), - /** Version 1 (older) */ - version1: external_exports.number(), - /** Version 2 (newer) */ - version2: external_exports.number(), - /** Checksum of version 1 */ - checksum1: external_exports.string(), - /** Checksum of version 2 */ - checksum2: external_exports.string(), - /** Whether the versions are identical */ - identical: external_exports.boolean(), - /** JSON patch operations to transform v1 into v2 */ - patch: external_exports.array(external_exports.unknown()).optional().describe("JSON patch operations"), - /** Human-readable diff summary */ - summary: external_exports.string().optional().describe("Human-readable summary of changes") -}); -var MetadataHistoryRetentionPolicySchema2 = external_exports.object({ - /** Maximum number of versions to keep per metadata item */ - maxVersions: external_exports.number().int().positive().optional().describe("Maximum number of versions to retain"), - /** Maximum age of history records in days */ - maxAgeDays: external_exports.number().int().positive().optional().describe("Maximum age of history records in days"), - /** Whether to enable automatic cleanup */ - autoCleanup: external_exports.boolean().default(false).describe("Enable automatic cleanup of old history"), - /** Cleanup interval in hours */ - cleanupIntervalHours: external_exports.number().int().positive().default(24).describe("How often to run cleanup (in hours)") -}); -var CoreServiceName3 = external_exports.enum([ - // Core Data & Metadata - "metadata", - // Object/Field Definitions - "data", - // CRUD & Query Engine - "auth", - // Authentication & Identity - // Infrastructure - "file-storage", - // Storage Driver (Local/S3) - "search", - // Search Engine (Elastic/Meili) - "cache", - // Cache Driver (Redis/Memory) - "queue", - // Job Queue (BullMQ/Redis) - // Advanced Capabilities - "automation", - // Flow & Script Engine - "graphql", - // GraphQL API Engine - "analytics", - // BI & Semantic Layer - "realtime", - // WebSocket & PubSub - "job", - // Background Job Manager - "notification", - // Email/Push/SMS - "ai", - // AI Engine (NLQ, Chat, Suggest, Insights) - "i18n", - // Internationalization Service - "ui", - // UI Metadata Service (View CRUD) - "workflow" - // Workflow State Machine Engine -]); -var ServiceCriticalitySchema3 = external_exports.enum([ - "required", - // System fails to start if missing (Exit Code 1) - "core", - // System warns if missing, functionality degraded (Warn) - "optional" - // System ignores if missing, feature disabled (Info) -]); -var ServiceRequirementDef2 = { - // Required: The kernel cannot function without these - data: "required", - // Core: Highly recommended, defaults to in-memory / no-op if missing - metadata: "core", - auth: "core", - // Core: Highly recommended, defaults to in-memory / no-op if missing - cache: "core", - queue: "core", - job: "core", - i18n: "core", - // Optional: Add-on capabilities - "file-storage": "optional", - search: "optional", - automation: "optional", - graphql: "optional", - analytics: "optional", - realtime: "optional", - notification: "optional", - ai: "optional", - ui: "optional", - workflow: "optional" -}; -var ServiceStatusSchema2 = external_exports.object({ - name: CoreServiceName3, - enabled: external_exports.boolean(), - status: external_exports.enum(["running", "stopped", "degraded", "initializing"]), - version: external_exports.string().optional(), - provider: external_exports.string().optional().describe('Implementation provider (e.g. "s3" for storage)'), - features: external_exports.array(external_exports.string()).optional().describe("List of supported sub-features") -}); -var KernelServiceMapSchema2 = external_exports.record( - CoreServiceName3, - external_exports.unknown().describe("Service Instance implementing the protocol interface") -); -var ServiceConfigSchema2 = external_exports.object({ - id: external_exports.string(), - name: CoreServiceName3, - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var TenantIsolationLevel3 = external_exports.enum([ - "shared_schema", - // Shared DB, shared schema, row-level isolation (most economical) - "isolated_schema", - // Shared DB, separate schema per tenant (balanced) - "isolated_db" - // Separate database per tenant (maximum isolation) -]); -var DatabaseProviderSchema3 = external_exports.enum([ - "turso", - // Turso/libSQL (DB-per-Tenant, edge-native) - "postgres", - // PostgreSQL (traditional, self-hosted or managed) - "memory" - // In-memory (testing/development only) -]).describe("Database provider for tenant data"); -var TenantConnectionConfigSchema3 = external_exports.object({ - /** Database connection URL */ - url: external_exports.string().min(1).describe("Database connection URL"), - /** Authentication token (JWT for Turso, password for Postgres) */ - authToken: external_exports.string().optional().describe("Database auth token (encrypted at rest)"), - /** Turso database group name */ - group: external_exports.string().optional().describe("Turso database group name") -}).describe("Tenant database connection configuration"); -var TenantQuotaSchema3 = external_exports.object({ - /** - * Maximum number of users allowed for this tenant - */ - maxUsers: external_exports.number().int().positive().optional().describe("Maximum number of users"), - /** - * Maximum storage space in bytes - */ - maxStorage: external_exports.number().int().positive().optional().describe("Maximum storage in bytes"), - /** - * API rate limit (requests per minute) - */ - apiRateLimit: external_exports.number().int().positive().optional().describe("API requests per minute"), - /** - * Maximum number of custom objects the tenant can create - */ - maxObjects: external_exports.number().int().positive().optional().describe("Maximum number of custom objects"), - /** - * Maximum records per object/table - */ - maxRecordsPerObject: external_exports.number().int().positive().optional().describe("Maximum records per object"), - /** - * Maximum deployments allowed per day - */ - maxDeploymentsPerDay: external_exports.number().int().positive().optional().describe("Maximum deployments per day"), - /** - * Maximum storage in bytes - */ - maxStorageBytes: external_exports.number().int().positive().optional().describe("Maximum storage in bytes") -}); -var TenantUsageSchema2 = external_exports.object({ - /** Current number of custom objects */ - currentObjectCount: external_exports.number().int().min(0).default(0).describe("Current number of custom objects"), - /** Current total record count across all objects */ - currentRecordCount: external_exports.number().int().min(0).default(0).describe("Total records across all objects"), - /** Current storage usage in bytes */ - currentStorageBytes: external_exports.number().int().min(0).default(0).describe("Current storage usage in bytes"), - /** Deployments executed today */ - deploymentsToday: external_exports.number().int().min(0).default(0).describe("Deployments executed today"), - /** Current number of active users */ - currentUsers: external_exports.number().int().min(0).default(0).describe("Current number of active users"), - /** API requests in the current minute */ - apiRequestsThisMinute: external_exports.number().int().min(0).default(0).describe("API requests in the current minute"), - /** Last updated timestamp (ISO 8601) */ - lastUpdatedAt: external_exports.string().datetime().optional().describe("Last usage update time") -}).describe("Current tenant resource usage"); -var QuotaEnforcementResultSchema2 = external_exports.object({ - /** Whether the operation is allowed */ - allowed: external_exports.boolean().describe("Whether the operation is within quota"), - /** Quota that would be exceeded (if not allowed) */ - exceededQuota: external_exports.string().optional().describe("Name of the exceeded quota"), - /** Current usage value */ - currentUsage: external_exports.number().optional().describe("Current usage value"), - /** Quota limit value */ - limit: external_exports.number().optional().describe("Quota limit"), - /** Human-readable message */ - message: external_exports.string().optional().describe("Human-readable quota message") -}).describe("Quota enforcement check result"); -var TenantSchema2 = external_exports.object({ - /** - * Unique tenant identifier - */ - id: external_exports.string().describe("Unique tenant identifier"), - /** - * Tenant display name - */ - name: external_exports.string().describe("Tenant display name"), - /** - * Data isolation level - */ - isolationLevel: TenantIsolationLevel3, - /** - * Database provider for this tenant - */ - databaseProvider: DatabaseProviderSchema3.optional().describe("Database provider"), - /** - * Database connection configuration (encrypted at rest) - */ - connectionConfig: TenantConnectionConfigSchema3.optional().describe("Database connection config"), - /** - * Current provisioning status - */ - provisioningStatus: external_exports.enum([ - "provisioning", - "active", - "suspended", - "failed", - "destroying" - ]).optional().describe("Current provisioning lifecycle status"), - /** - * Tenant subscription plan - */ - plan: external_exports.enum(["free", "pro", "enterprise"]).optional().describe("Subscription plan"), - /** - * Custom configuration values - */ - customizations: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom configuration values"), - /** - * Resource quotas - */ - quotas: TenantQuotaSchema3.optional() -}); -var RowLevelIsolationStrategySchema3 = external_exports.object({ - strategy: external_exports.literal("shared_schema").describe("Row-level isolation strategy"), - /** - * Database configuration for row-level isolation - */ - database: external_exports.object({ - /** - * Whether to enable Row-Level Security (RLS) - */ - enableRLS: external_exports.boolean().default(true).describe("Enable PostgreSQL Row-Level Security"), - /** - * Tenant context setting method - */ - contextMethod: external_exports.enum([ - "session_variable", - // SET app.current_tenant = 'tenant_123' - "search_path", - // SET search_path = tenant_123, public - "application_name" - // SET application_name = 'tenant_123' - ]).default("session_variable").describe("How to set tenant context"), - /** - * Session variable name for tenant context - */ - contextVariable: external_exports.string().default("app.current_tenant").describe("Session variable name"), - /** - * Whether to validate tenant_id at application level - */ - applicationValidation: external_exports.boolean().default(true).describe("Application-level tenant validation") - }).optional().describe("Database configuration"), - /** - * Performance optimization settings - */ - performance: external_exports.object({ - /** - * Whether to use partial indexes for tenant_id - */ - usePartialIndexes: external_exports.boolean().default(true).describe("Use partial indexes per tenant"), - /** - * Whether to use table partitioning - */ - usePartitioning: external_exports.boolean().default(false).describe("Use table partitioning by tenant_id"), - /** - * Connection pool size per tenant - */ - poolSizePerTenant: external_exports.number().int().positive().optional().describe("Connection pool size per tenant") - }).optional().describe("Performance settings") -}); -var SchemaLevelIsolationStrategySchema3 = external_exports.object({ - strategy: external_exports.literal("isolated_schema").describe("Schema-level isolation strategy"), - /** - * Schema configuration - */ - schema: external_exports.object({ - /** - * Schema naming pattern - * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) - * The tenant_id will be sanitized before substitution to prevent SQL injection - */ - namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Schema naming pattern"), - /** - * Whether to include public schema in search_path - */ - includePublicSchema: external_exports.boolean().default(true).describe("Include public schema"), - /** - * Default schema for shared resources - */ - sharedSchema: external_exports.string().default("public").describe("Schema for shared resources"), - /** - * Whether to automatically create schema on tenant creation - */ - autoCreateSchema: external_exports.boolean().default(true).describe("Auto-create schema") - }).optional().describe("Schema configuration"), - /** - * Migration configuration - */ - migrations: external_exports.object({ - /** - * Migration strategy - */ - strategy: external_exports.enum([ - "parallel", - // Run migrations on all schemas in parallel - "sequential", - // Run migrations one schema at a time - "on_demand" - // Run migrations when tenant accesses system - ]).default("parallel").describe("Migration strategy"), - /** - * Maximum concurrent migrations - */ - maxConcurrent: external_exports.number().int().positive().default(10).describe("Max concurrent migrations"), - /** - * Whether to rollback on first failure - */ - rollbackOnError: external_exports.boolean().default(true).describe("Rollback on error") - }).optional().describe("Migration configuration"), - /** - * Performance optimization settings - */ - performance: external_exports.object({ - /** - * Whether to use connection pooling per schema - */ - poolPerSchema: external_exports.boolean().default(false).describe("Separate pool per schema"), - /** - * Schema cache TTL in seconds - */ - schemaCacheTTL: external_exports.number().int().positive().default(3600).describe("Schema cache TTL") - }).optional().describe("Performance settings") -}); -var DatabaseLevelIsolationStrategySchema3 = external_exports.object({ - strategy: external_exports.literal("isolated_db").describe("Database-level isolation strategy"), - /** - * Database configuration - */ - database: external_exports.object({ - /** - * Database naming pattern - * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores) - * The tenant_id will be sanitized before substitution to prevent SQL injection - */ - namingPattern: external_exports.string().default("tenant_{tenant_id}").describe("Database naming pattern"), - /** - * Database server/cluster assignment strategy - */ - serverStrategy: external_exports.enum([ - "shared", - // All tenant databases on same server - "sharded", - // Tenant databases distributed across servers - "dedicated" - // Each tenant gets dedicated server (enterprise) - ]).default("shared").describe("Server assignment strategy"), - /** - * Whether to use separate credentials per tenant - */ - separateCredentials: external_exports.boolean().default(true).describe("Separate credentials per tenant"), - /** - * Whether to automatically create database on tenant creation - */ - autoCreateDatabase: external_exports.boolean().default(true).describe("Auto-create database") - }).optional().describe("Database configuration"), - /** - * Connection pooling configuration - */ - connectionPool: external_exports.object({ - /** - * Pool size per tenant database - */ - poolSize: external_exports.number().int().positive().default(10).describe("Connection pool size"), - /** - * Maximum number of tenant pools to keep active - */ - maxActivePools: external_exports.number().int().positive().default(100).describe("Max active pools"), - /** - * Idle pool timeout in seconds - */ - idleTimeout: external_exports.number().int().positive().default(300).describe("Idle pool timeout"), - /** - * Whether to use connection pooler (PgBouncer, etc.) - */ - usePooler: external_exports.boolean().default(true).describe("Use connection pooler") - }).optional().describe("Connection pool configuration"), - /** - * Backup and restore configuration - */ - backup: external_exports.object({ - /** - * Backup strategy per tenant - */ - strategy: external_exports.enum([ - "individual", - // Separate backup per tenant - "consolidated", - // Combined backup with all tenants - "on_demand" - // Backup only when requested - ]).default("individual").describe("Backup strategy"), - /** - * Backup frequency in hours - */ - frequencyHours: external_exports.number().int().positive().default(24).describe("Backup frequency"), - /** - * Retention period in days - */ - retentionDays: external_exports.number().int().positive().default(30).describe("Backup retention days") - }).optional().describe("Backup configuration"), - /** - * Encryption configuration - */ - encryption: external_exports.object({ - /** - * Whether to use per-tenant encryption keys - */ - perTenantKeys: external_exports.boolean().default(false).describe("Per-tenant encryption keys"), - /** - * Encryption algorithm - */ - algorithm: external_exports.string().default("AES-256-GCM").describe("Encryption algorithm"), - /** - * Key management service - */ - keyManagement: external_exports.enum(["aws_kms", "azure_key_vault", "gcp_kms", "hashicorp_vault", "custom"]).optional().describe("Key management service") - }).optional().describe("Encryption configuration") -}); -var TenantIsolationConfigSchema2 = external_exports.discriminatedUnion("strategy", [ - RowLevelIsolationStrategySchema3, - SchemaLevelIsolationStrategySchema3, - DatabaseLevelIsolationStrategySchema3 -]); -var TenantSecurityPolicySchema2 = external_exports.object({ - /** - * Encryption requirements - */ - encryption: external_exports.object({ - /** - * Require encryption at rest - */ - atRest: external_exports.boolean().default(true).describe("Require encryption at rest"), - /** - * Require encryption in transit - */ - inTransit: external_exports.boolean().default(true).describe("Require encryption in transit"), - /** - * Require field-level encryption for sensitive data - */ - fieldLevel: external_exports.boolean().default(false).describe("Require field-level encryption") - }).optional().describe("Encryption requirements"), - /** - * Access control requirements - */ - accessControl: external_exports.object({ - /** - * Require multi-factor authentication - */ - requireMFA: external_exports.boolean().default(false).describe("Require MFA"), - /** - * Require SSO/SAML authentication - */ - requireSSO: external_exports.boolean().default(false).describe("Require SSO"), - /** - * IP whitelist - */ - ipWhitelist: external_exports.array(external_exports.string()).optional().describe("Allowed IP addresses"), - /** - * Session timeout in seconds - */ - sessionTimeout: external_exports.number().int().positive().default(3600).describe("Session timeout") - }).optional().describe("Access control requirements"), - /** - * Audit and compliance requirements - */ - compliance: external_exports.object({ - /** - * Compliance standards to enforce - */ - standards: external_exports.array(external_exports.enum([ - "sox", - "hipaa", - "gdpr", - "pci_dss", - "iso_27001", - "fedramp" - ])).optional().describe("Compliance standards"), - /** - * Require audit logging for all operations - */ - requireAuditLog: external_exports.boolean().default(true).describe("Require audit logging"), - /** - * Audit log retention period in days - */ - auditRetentionDays: external_exports.number().int().positive().default(365).describe("Audit retention days"), - /** - * Data residency requirements - */ - dataResidency: external_exports.object({ - /** - * Required geographic region - */ - region: external_exports.string().optional().describe("Required region (e.g., US, EU, APAC)"), - /** - * Prohibited regions - */ - excludeRegions: external_exports.array(external_exports.string()).optional().describe("Prohibited regions") - }).optional().describe("Data residency requirements") - }).optional().describe("Compliance requirements") -}); -var LicenseMetricType2 = external_exports.enum([ - "boolean", - // Feature Flag (Enabled/Disabled) - "counter", - // Usage Count (e.g. API Calls, Records Created) - Accumulates - "gauge" - // Current Level (e.g. Storage Used, Users Active) - Point in time -]).describe("License metric type"); -var FeatureSchema2 = external_exports.object({ - code: external_exports.string().regex(/^[a-z_][a-z0-9_.]*$/).describe("Feature code (e.g. core.api_access)"), - label: external_exports.string(), - description: external_exports.string().optional(), - type: LicenseMetricType2.default("boolean"), - /** For counters/gauges */ - unit: external_exports.enum(["count", "bytes", "seconds", "percent"]).optional(), - /** Dependencies (e.g. 'audit_log' requires 'enterprise_tier') */ - requires: external_exports.array(external_exports.string()).optional() -}); -var PlanSchema2 = external_exports.object({ - code: external_exports.string().describe("Plan code (e.g. pro_v1)"), - label: external_exports.string(), - active: external_exports.boolean().default(true), - /** Feature Entitlements */ - features: external_exports.array(external_exports.string()).describe("List of enabled boolean features"), - /** Limit Quotas */ - limits: external_exports.record(external_exports.string(), external_exports.number()).describe("Map of metric codes to limit values (e.g. { storage_gb: 10 })"), - /** Pricing (Optional Metadata) */ - currency: external_exports.string().default("USD").optional(), - priceMonthly: external_exports.number().optional(), - priceYearly: external_exports.number().optional() -}); -var LicenseSchema2 = external_exports.object({ - /** Identity */ - spaceId: external_exports.string().describe("Target Space ID"), - planCode: external_exports.string(), - /** Validity */ - issuedAt: external_exports.string().datetime(), - expiresAt: external_exports.string().datetime().optional(), - // Null = Perpetual - /** Status */ - status: external_exports.enum(["active", "expired", "suspended", "trial"]), - /** Overrides (Specific to this space, exceeding the plan) */ - customFeatures: external_exports.array(external_exports.string()).optional(), - customLimits: external_exports.record(external_exports.string(), external_exports.number()).optional(), - /** Authorized Add-ons */ - plugins: external_exports.array(external_exports.string()).optional().describe("List of enabled plugin package IDs"), - /** Signature */ - signature: external_exports.string().optional().describe("Cryptographic signature of the license") -}); -var RegistrySyncPolicySchema2 = external_exports.enum([ - "manual", - // Manual synchronization only - "auto", - // Automatic synchronization - "proxy" - // Proxy requests to upstream without caching -]).describe("Registry synchronization strategy"); -var RegistryUpstreamSchema2 = external_exports.object({ - /** - * Upstream registry URL - */ - url: external_exports.string().url().describe("Upstream registry endpoint"), - /** - * Synchronization policy - */ - syncPolicy: RegistrySyncPolicySchema2.default("auto"), - /** - * Sync interval in seconds (for auto sync) - */ - syncInterval: external_exports.number().int().min(60).optional().describe("Auto-sync interval in seconds"), - /** - * Authentication credentials - */ - auth: external_exports.object({ - type: external_exports.enum(["none", "basic", "bearer", "api-key", "oauth2"]).default("none"), - username: external_exports.string().optional(), - password: external_exports.string().optional(), - token: external_exports.string().optional(), - apiKey: external_exports.string().optional() - }).optional(), - /** - * TLS/SSL configuration - */ - tls: external_exports.object({ - enabled: external_exports.boolean().default(true), - verifyCertificate: external_exports.boolean().default(true), - certificate: external_exports.string().optional(), - privateKey: external_exports.string().optional() - }).optional(), - /** - * Timeout settings - */ - timeout: external_exports.number().int().min(1e3).default(3e4).describe("Request timeout in milliseconds"), - /** - * Retry configuration - */ - retry: external_exports.object({ - maxAttempts: external_exports.number().int().min(0).default(3), - backoff: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential") - }).optional() -}); -var RegistryConfigSchema2 = external_exports.object({ - /** - * Registry type - */ - type: external_exports.enum([ - "public", - // Public marketplace (e.g., plugins.objectstack.com) - "private", - // Private enterprise registry - "hybrid" - // Hybrid with upstream federation - ]).describe("Registry deployment type"), - /** - * Upstream registries (for hybrid/private registries) - */ - upstream: external_exports.array(RegistryUpstreamSchema2).optional().describe("Upstream registries to sync from or proxy to"), - /** - * Scopes managed by this registry - */ - scope: external_exports.array(external_exports.string()).optional().describe("npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)"), - /** - * Default scope for new plugins - */ - defaultScope: external_exports.string().optional().describe("Default scope prefix for new plugins"), - /** - * Registry storage configuration - */ - storage: external_exports.object({ - /** - * Storage backend type - */ - backend: external_exports.enum(["local", "s3", "gcs", "azure-blob", "oss"]).default("local"), - /** - * Storage path or bucket name - */ - path: external_exports.string().optional(), - /** - * Credentials - */ - credentials: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional(), - /** - * Registry visibility - */ - visibility: external_exports.enum(["public", "private", "internal"]).default("private").describe("Who can access this registry"), - /** - * Access control - */ - accessControl: external_exports.object({ - /** - * Require authentication for read - */ - requireAuthForRead: external_exports.boolean().default(false), - /** - * Require authentication for write - */ - requireAuthForWrite: external_exports.boolean().default(true), - /** - * Allowed users/teams - */ - allowedPrincipals: external_exports.array(external_exports.string()).optional() - }).optional(), - /** - * Caching configuration - */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(true), - ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), - maxSize: external_exports.number().int().optional().describe("Maximum cache size in bytes") - }).optional(), - /** - * Mirroring configuration (for high availability) - */ - mirrors: external_exports.array(external_exports.object({ - url: external_exports.string().url(), - priority: external_exports.number().int().min(1).default(1) - })).optional().describe("Mirror registries for redundancy") -}); -var TenantProvisioningStatusEnum2 = external_exports.enum([ - "provisioning", - // Database creation in progress - "active", - // Fully provisioned and operational - "suspended", - // Temporarily disabled (billing, policy) - "failed", - // Provisioning failed (requires retry or manual intervention) - "destroying" - // Deletion in progress -]).describe("Tenant provisioning lifecycle status"); -var TenantPlanSchema2 = external_exports.enum([ - "free", - // Free tier with limited quotas - "pro", - // Professional tier with higher quotas - "enterprise" - // Enterprise tier with custom quotas and SLAs -]).describe("Tenant subscription plan"); -var TenantRegionSchema2 = external_exports.enum([ - "us-east", - // US East (Virginia) - "us-west", - // US West (Oregon) - "eu-west", - // EU West (Ireland) - "eu-central", - // EU Central (Frankfurt) - "ap-southeast", - // Asia Pacific (Singapore) - "ap-northeast" - // Asia Pacific (Tokyo) -]).describe("Available deployment region"); -var ProvisioningStepSchema2 = external_exports.object({ - /** Step identifier */ - name: external_exports.string().min(1).describe("Step name (e.g., create_database, sync_schema)"), - /** Step execution status */ - status: external_exports.enum(["pending", "running", "completed", "failed", "skipped"]).describe("Step status"), - /** When the step started (ISO 8601) */ - startedAt: external_exports.string().datetime().optional().describe("Step start time"), - /** When the step completed (ISO 8601) */ - completedAt: external_exports.string().datetime().optional().describe("Step completion time"), - /** Duration in milliseconds */ - durationMs: external_exports.number().int().min(0).optional().describe("Step duration in ms"), - /** Error message if the step failed */ - error: external_exports.string().optional().describe("Error message on failure") -}).describe("Individual provisioning step status"); -var TenantProvisioningRequestSchema2 = external_exports.object({ - /** Organization ID that owns this tenant */ - orgId: external_exports.string().min(1).describe("Organization ID"), - /** Requested subscription plan */ - plan: TenantPlanSchema2.default("free"), - /** Preferred deployment region */ - region: TenantRegionSchema2.default("us-east"), - /** Optional tenant display name */ - displayName: external_exports.string().optional().describe("Tenant display name"), - /** Optional initial admin user email */ - adminEmail: external_exports.string().email().optional().describe("Initial admin user email"), - /** Optional metadata to attach to the tenant */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata") -}).describe("Tenant provisioning request"); -var TenantProvisioningResultSchema2 = external_exports.object({ - /** Unique tenant identifier */ - tenantId: external_exports.string().min(1).describe("Provisioned tenant ID"), - /** Database connection URL (libsql:// or https://) */ - connectionUrl: external_exports.string().min(1).describe("Database connection URL"), - /** Current provisioning status */ - status: TenantProvisioningStatusEnum2, - /** Deployment region */ - region: TenantRegionSchema2, - /** Active subscription plan */ - plan: TenantPlanSchema2, - /** Provisioning pipeline steps with status */ - steps: external_exports.array(ProvisioningStepSchema2).default([]).describe("Pipeline step statuses"), - /** Total provisioning duration in milliseconds */ - totalDurationMs: external_exports.number().int().min(0).optional().describe("Total provisioning duration"), - /** Provisioned timestamp (ISO 8601) */ - provisionedAt: external_exports.string().datetime().optional().describe("Provisioning completion time"), - /** Error message if provisioning failed */ - error: external_exports.string().optional().describe("Error message on failure") -}).describe("Tenant provisioning result"); -var DeployStatusEnum2 = external_exports.enum([ - "validating", - // Zod schema validation in progress - "diffing", - // Comparing desired state vs current state - "migrating", - // Executing DDL statements - "registering", - // Updating metadata registry - "ready", - // Deployment complete and live - "failed", - // Deployment failed at some stage - "rolling_back" - // Rollback in progress -]).describe("Deployment lifecycle status"); -var SchemaChangeSchema2 = external_exports.object({ - /** Type of entity being changed */ - entityType: external_exports.enum(["object", "field", "index", "view", "flow", "permission"]).describe("Entity type"), - /** Name of the entity */ - entityName: external_exports.string().min(1).describe("Entity name"), - /** Parent entity name (e.g., object name for a field change) */ - parentEntity: external_exports.string().optional().describe("Parent entity name"), - /** Type of change */ - changeType: external_exports.enum(["added", "modified", "removed"]).describe("Change type"), - /** Previous value (for modified/removed) */ - oldValue: external_exports.unknown().optional().describe("Previous value"), - /** New value (for added/modified) */ - newValue: external_exports.unknown().optional().describe("New value") -}).describe("Individual schema change"); -var DeployDiffSchema2 = external_exports.object({ - /** List of all schema changes */ - changes: external_exports.array(SchemaChangeSchema2).default([]).describe("List of schema changes"), - /** Summary counts */ - summary: external_exports.object({ - added: external_exports.number().int().min(0).default(0).describe("Number of added entities"), - modified: external_exports.number().int().min(0).default(0).describe("Number of modified entities"), - removed: external_exports.number().int().min(0).default(0).describe("Number of removed entities") - }).describe("Change summary counts"), - /** Whether the diff contains breaking changes (e.g., column removal) */ - hasBreakingChanges: external_exports.boolean().default(false).describe("Whether diff contains breaking changes") -}).describe("Schema diff between current and desired state"); -var MigrationStatementSchema2 = external_exports.object({ - /** SQL DDL statement to execute */ - sql: external_exports.string().min(1).describe("SQL DDL statement"), - /** Whether this statement is reversible */ - reversible: external_exports.boolean().default(true).describe("Whether the statement can be reversed"), - /** Reverse SQL statement (for rollback) */ - rollbackSql: external_exports.string().optional().describe("Reverse SQL for rollback"), - /** Execution order (lower = earlier) */ - order: external_exports.number().int().min(0).describe("Execution order") -}).describe("Single DDL migration statement"); -var MigrationPlanSchema2 = external_exports.object({ - /** Ordered list of migration statements */ - statements: external_exports.array(MigrationStatementSchema2).default([]).describe("Ordered DDL statements"), - /** SQL dialect the statements are written for */ - dialect: external_exports.string().min(1).describe("Target SQL dialect"), - /** Whether the entire plan is reversible */ - reversible: external_exports.boolean().default(true).describe("Whether the plan can be fully rolled back"), - /** Estimated execution time in milliseconds */ - estimatedDurationMs: external_exports.number().int().min(0).optional().describe("Estimated execution time") -}).describe("Ordered migration plan"); -var DeployValidationIssueSchema2 = external_exports.object({ - /** Severity of the issue */ - severity: external_exports.enum(["error", "warning", "info"]).describe("Issue severity"), - /** Entity path where the issue was found */ - path: external_exports.string().describe("Entity path (e.g., objects.project_task.fields.name)"), - /** Human-readable issue description */ - message: external_exports.string().describe("Issue description"), - /** Zod error code if applicable */ - code: external_exports.string().optional().describe("Validation error code") -}).describe("Validation issue"); -var DeployValidationResultSchema2 = external_exports.object({ - /** Whether the bundle passed validation */ - valid: external_exports.boolean().describe("Whether the bundle is valid"), - /** List of validation issues */ - issues: external_exports.array(DeployValidationIssueSchema2).default([]).describe("Validation issues"), - /** Number of errors */ - errorCount: external_exports.number().int().min(0).default(0).describe("Number of errors"), - /** Number of warnings */ - warningCount: external_exports.number().int().min(0).default(0).describe("Number of warnings") -}).describe("Bundle validation result"); -var DeployManifestSchema2 = external_exports.object({ - /** Deployment version (semver) */ - version: external_exports.string().min(1).describe("Deployment version"), - /** SHA256 checksum of the bundle contents */ - checksum: external_exports.string().optional().describe("SHA256 checksum"), - /** Object definitions included in this deployment */ - objects: external_exports.array(external_exports.string()).default([]).describe("Object names included"), - /** View definitions included */ - views: external_exports.array(external_exports.string()).default([]).describe("View names included"), - /** Flow definitions included */ - flows: external_exports.array(external_exports.string()).default([]).describe("Flow names included"), - /** Permission definitions included */ - permissions: external_exports.array(external_exports.string()).default([]).describe("Permission names included"), - /** Timestamp of bundle creation (ISO 8601) */ - createdAt: external_exports.string().datetime().optional().describe("Bundle creation time") -}).describe("Deployment manifest"); -var DeployBundleSchema2 = external_exports.object({ - /** Bundle manifest with version and contents list */ - manifest: DeployManifestSchema2, - /** Object definitions (JSON-serialized ObjectStack objects) */ - objects: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Object definitions"), - /** View definitions */ - views: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("View definitions"), - /** Flow definitions */ - flows: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Flow definitions"), - /** Permission definitions */ - permissions: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Permission definitions"), - /** Seed data records to populate after schema migration */ - seedData: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Seed data records") -}).describe("Deploy bundle containing all metadata for deployment"); -var AppManifestSchema2 = external_exports.object({ - /** Unique app identifier (snake_case) */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("App identifier (snake_case)"), - /** Display label for the app */ - label: external_exports.string().min(1).describe("App display label"), - /** App version (semver) */ - version: external_exports.string().min(1).describe("App version (semver)"), - /** App description */ - description: external_exports.string().optional().describe("App description"), - /** Minimum kernel version required */ - minKernelVersion: external_exports.string().optional().describe("Minimum required kernel version"), - /** Object definitions provided by this app */ - objects: external_exports.array(external_exports.string()).default([]).describe("Object names provided"), - /** View definitions provided */ - views: external_exports.array(external_exports.string()).default([]).describe("View names provided"), - /** Flow definitions provided */ - flows: external_exports.array(external_exports.string()).default([]).describe("Flow names provided"), - /** Whether seed data is included */ - hasSeedData: external_exports.boolean().default(false).describe("Whether app includes seed data"), - /** Seed data records to populate on install */ - seedData: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).default([]).describe("Seed data records"), - /** App dependencies (other apps that must be installed first) */ - dependencies: external_exports.array(external_exports.string()).default([]).describe("Required app dependencies") -}).describe("App manifest for marketplace installation"); -var AppCompatibilityCheckSchema2 = external_exports.object({ - /** Whether the app is compatible with the current environment */ - compatible: external_exports.boolean().describe("Whether the app is compatible"), - /** Compatibility issues found */ - issues: external_exports.array(external_exports.object({ - /** Issue severity */ - severity: external_exports.enum(["error", "warning"]).describe("Issue severity"), - /** Issue description */ - message: external_exports.string().describe("Issue description"), - /** Issue category */ - category: external_exports.enum([ - "kernel_version", - // Kernel version mismatch - "object_conflict", - // Object name already exists - "dependency_missing", - // Required dependency not installed - "quota_exceeded" - // Tenant quota would be exceeded - ]).describe("Issue category") - })).default([]).describe("Compatibility issues") -}).describe("App compatibility check result"); -var AppInstallRequestSchema2 = external_exports.object({ - /** Target tenant ID */ - tenantId: external_exports.string().min(1).describe("Target tenant ID"), - /** App identifier to install */ - appId: external_exports.string().min(1).describe("App identifier"), - /** Optional configuration overrides */ - configOverrides: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Configuration overrides"), - /** Whether to skip seed data */ - skipSeedData: external_exports.boolean().default(false).describe("Skip seed data population") -}).describe("App install request"); -var AppInstallResultSchema2 = external_exports.object({ - /** Whether the installation succeeded */ - success: external_exports.boolean().describe("Whether installation succeeded"), - /** App identifier that was installed */ - appId: external_exports.string().describe("Installed app identifier"), - /** App version installed */ - version: external_exports.string().describe("Installed app version"), - /** Objects created or updated */ - installedObjects: external_exports.array(external_exports.string()).default([]).describe("Objects created/updated"), - /** Tables created in the database */ - createdTables: external_exports.array(external_exports.string()).default([]).describe("Database tables created"), - /** Number of seed records inserted */ - seededRecords: external_exports.number().int().min(0).default(0).describe("Seed records inserted"), - /** Installation duration in milliseconds */ - durationMs: external_exports.number().int().min(0).optional().describe("Installation duration"), - /** Error message if installation failed */ - error: external_exports.string().optional().describe("Error message on failure") -}).describe("App install result"); -var PKG_CONVENTIONS = { - /** - * Standard directories within ObjectStack packages. - * All packages MUST follow these conventions for the runtime to locate resources. - */ - DIRS: { - /** - * Location for schema definitions (Zod schemas, JSON schemas). - * Path: src/schemas - */ - SCHEMA: "src/schemas", - /** - * Location for server-side code and triggers. - * Path: src/server - */ - SERVER: "src/server", - /** - * Location for server-side trigger functions. - * Path: src/triggers - */ - TRIGGERS: "src/triggers", - /** - * Location for client-side code. - * Path: src/client - */ - CLIENT: "src/client", - /** - * Location for client-side page components. - * Path: src/client/pages - */ - PAGES: "src/client/pages", - /** - * Location for static assets (images, fonts, etc.). - * Path: assets - */ - ASSETS: "assets" - }, - /** - * Standard file names within ObjectStack packages. - */ - FILES: { - /** - * Package manifest configuration file. - * File: objectstack.config.ts - */ - MANIFEST: "objectstack.config.ts", - /** - * Main entry point for the package. - * File: src/index.ts - */ - ENTRY: "src/index.ts" - } -}; -var SystemObjectName2 = { - /** Authentication: user identity */ - USER: "sys_user", - /** Authentication: active session */ - SESSION: "sys_session", - /** Authentication: OAuth / credential account */ - ACCOUNT: "sys_account", - /** Authentication: email / phone verification */ - VERIFICATION: "sys_verification", - /** Authentication: organization (multi-org support) */ - ORGANIZATION: "sys_organization", - /** Authentication: organization member */ - MEMBER: "sys_member", - /** Authentication: organization invitation */ - INVITATION: "sys_invitation", - /** Authentication: team within an organization */ - TEAM: "sys_team", - /** Authentication: team membership */ - TEAM_MEMBER: "sys_team_member", - /** Authentication: API key for programmatic access */ - API_KEY: "sys_api_key", - /** Authentication: two-factor authentication credentials */ - TWO_FACTOR: "sys_two_factor", - /** Authentication: user preferences (theme, locale, etc.) */ - USER_PREFERENCE: "sys_user_preference", - /** Security: role definition for RBAC */ - ROLE: "sys_role", - /** Security: permission set grouping */ - PERMISSION_SET: "sys_permission_set", - /** Audit: system audit log */ - AUDIT_LOG: "sys_audit_log", - /** System metadata storage */ - METADATA: "sys_metadata", - /** Realtime: user presence state */ - PRESENCE: "sys_presence" -}; -var SystemFieldName = { - /** Primary key */ - ID: "id", - /** Record creation timestamp */ - CREATED_AT: "created_at", - /** Record last-updated timestamp */ - UPDATED_AT: "updated_at", - /** Record owner (lookup to user) */ - OWNER_ID: "owner_id", - /** Tenant isolation key */ - TENANT_ID: "tenant_id", - /** Foreign key to user on session / account objects */ - USER_ID: "user_id", - /** Soft-delete timestamp */ - DELETED_AT: "deleted_at" -}; -var StorageNameMapping = { - /** - * Resolve the physical table name for an object. - * Priority: explicit `tableName` → auto-derived `{namespace}_{name}` → `name`. - * - * @param object - Object definition (at minimum `{ name: string; namespace?: string; tableName?: string }`) - * @returns The physical table / collection name to use in storage operations. - */ - resolveTableName(object2) { - return object2.tableName ?? (object2.namespace ? `${object2.namespace}_${object2.name}` : object2.name); - }, - /** - * Resolve the physical column name for a field. - * Falls back to `fieldKey` when `columnName` is not set on the field. - * - * @param fieldKey - The protocol-level field key (snake_case identifier). - * @param field - Field definition (at minimum `{ columnName?: string }`). - * @returns The physical column name to use in storage operations. - */ - resolveColumnName(fieldKey, field) { - return field.columnName ?? fieldKey; - }, - /** - * Build a complete field-key → column-name map for an entire object. - * - * @param fields - The fields record from an ObjectSchema. - * @returns A record mapping every protocol field key to its physical column name. - */ - buildColumnMap(fields) { - const map3 = {}; - for (const key of Object.keys(fields)) { - map3[key] = fields[key].columnName ?? key; - } - return map3; - }, - /** - * Build a reverse column-name → field-key map for an entire object. - * Useful for translating storage-layer results back to protocol-level field keys. - * - * @param fields - The fields record from an ObjectSchema. - * @returns A record mapping every physical column name back to its protocol field key. - */ - buildReverseColumnMap(fields) { - const map3 = {}; - for (const key of Object.keys(fields)) { - const col = fields[key].columnName ?? key; - map3[col] = key; - } - return map3; - } -}; -var kernel_exports = {}; -__export4(kernel_exports, { - ActivationEventSchema: () => ActivationEventSchema2, - AdvancedPluginLifecycleConfigSchema: () => AdvancedPluginLifecycleConfigSchema2, - ArtifactChecksumSchema: () => ArtifactChecksumSchema3, - ArtifactFileEntrySchema: () => ArtifactFileEntrySchema3, - ArtifactSignatureSchema: () => ArtifactSignatureSchema3, - BreakingChangeSchema: () => BreakingChangeSchema2, - CLICommandContributionSchema: () => CLICommandContributionSchema2, - CORE_PLUGIN_TYPES: () => CORE_PLUGIN_TYPES3, - CapabilityConformanceLevelSchema: () => CapabilityConformanceLevelSchema3, - CompatibilityLevelSchema: () => CompatibilityLevelSchema2, - CompatibilityMatrixEntrySchema: () => CompatibilityMatrixEntrySchema2, - CustomizationOriginSchema: () => CustomizationOriginSchema2, - CustomizationPolicySchema: () => CustomizationPolicySchema3, - DEFAULT_METADATA_TYPE_REGISTRY: () => DEFAULT_METADATA_TYPE_REGISTRY, - DeadLetterQueueEntrySchema: () => DeadLetterQueueEntrySchema2, - DependencyConflictSchema: () => DependencyConflictSchema2, - DependencyGraphNodeSchema: () => DependencyGraphNodeSchema2, - DependencyGraphSchema: () => DependencyGraphSchema2, - DependencyResolutionResultSchema: () => DependencyResolutionResultSchema3, - DependencyStatusEnum: () => DependencyStatusEnum3, - DeprecationNoticeSchema: () => DeprecationNoticeSchema2, - DevFixtureConfigSchema: () => DevFixtureConfigSchema2, - DevPluginConfigSchema: () => DevPluginConfigSchema2, - DevPluginPreset: () => DevPluginPreset2, - DevServiceOverrideSchema: () => DevServiceOverrideSchema2, - DevToolsConfigSchema: () => DevToolsConfigSchema2, - DisablePackageRequestSchema: () => DisablePackageRequestSchema3, - DisablePackageResponseSchema: () => DisablePackageResponseSchema3, - DistributedStateConfigSchema: () => DistributedStateConfigSchema2, - DynamicLoadRequestSchema: () => DynamicLoadRequestSchema2, - DynamicLoadingConfigSchema: () => DynamicLoadingConfigSchema2, - DynamicPluginOperationSchema: () => DynamicPluginOperationSchema2, - DynamicPluginResultSchema: () => DynamicPluginResultSchema2, - DynamicUnloadRequestSchema: () => DynamicUnloadRequestSchema2, - EVENT_PRIORITY_VALUES: () => EVENT_PRIORITY_VALUES, - EnablePackageRequestSchema: () => EnablePackageRequestSchema3, - EnablePackageResponseSchema: () => EnablePackageResponseSchema3, - EventBusConfigSchema: () => EventBusConfigSchema2, - EventHandlerSchema: () => EventHandlerSchema2, - EventLogEntrySchema: () => EventLogEntrySchema2, - EventMessageQueueConfigSchema: () => EventMessageQueueConfigSchema2, - EventMetadataSchema: () => EventMetadataSchema2, - EventPersistenceSchema: () => EventPersistenceSchema2, - EventPhaseSchema: () => EventPhaseSchema2, - EventPriority: () => EventPriority2, - EventQueueConfigSchema: () => EventQueueConfigSchema2, - EventReplayConfigSchema: () => EventReplayConfigSchema2, - EventRouteSchema: () => EventRouteSchema2, - EventSchema: () => EventSchema22, - EventSourcingConfigSchema: () => EventSourcingConfigSchema2, - EventTypeDefinitionSchema: () => EventTypeDefinitionSchema2, - EventWebhookConfigSchema: () => EventWebhookConfigSchema2, - ExecutionContextSchema: () => ExecutionContextSchema3, - ExtensionPointSchema: () => ExtensionPointSchema3, - FeatureFlag: () => FeatureFlag2, - FeatureFlagSchema: () => FeatureFlagSchema2, - FeatureStrategy: () => FeatureStrategy2, - FieldChangeSchema: () => FieldChangeSchema3, - GetPackageRequestSchema: () => GetPackageRequestSchema3, - GetPackageResponseSchema: () => GetPackageResponseSchema3, - GracefulDegradationSchema: () => GracefulDegradationSchema2, - HealthStatusSchema: () => HealthStatusSchema2, - HookRegisteredEventSchema: () => HookRegisteredEventSchema2, - HookTriggeredEventSchema: () => HookTriggeredEventSchema2, - HotReloadConfigSchema: () => HotReloadConfigSchema2, - InstallPackageRequestSchema: () => InstallPackageRequestSchema3, - InstallPackageResponseSchema: () => InstallPackageResponseSchema3, - InstalledPackageSchema: () => InstalledPackageSchema3, - KernelContextSchema: () => KernelContextSchema2, - KernelEventBaseSchema: () => KernelEventBaseSchema2, - KernelReadyEventSchema: () => KernelReadyEventSchema2, - KernelSecurityPolicySchema: () => KernelSecurityPolicySchema2, - KernelSecurityScanResultSchema: () => KernelSecurityScanResultSchema2, - KernelSecurityVulnerabilitySchema: () => KernelSecurityVulnerabilitySchema2, - KernelShutdownEventSchema: () => KernelShutdownEventSchema2, - ListPackagesRequestSchema: () => ListPackagesRequestSchema3, - ListPackagesResponseSchema: () => ListPackagesResponseSchema3, - ManifestSchema: () => ManifestSchema3, - MergeConflictSchema: () => MergeConflictSchema3, - MergeResultSchema: () => MergeResultSchema2, - MergeStrategyConfigSchema: () => MergeStrategyConfigSchema3, - MetadataBulkRegisterRequestSchema: () => MetadataBulkRegisterRequestSchema3, - MetadataBulkResultSchema: () => MetadataBulkResultSchema3, - MetadataCategoryEnum: () => MetadataCategoryEnum3, - MetadataChangeTypeSchema: () => MetadataChangeTypeSchema3, - MetadataCollectionInfoSchema: () => MetadataCollectionInfoSchema22, - MetadataDependencySchema: () => MetadataDependencySchema3, - MetadataDiffItemSchema: () => MetadataDiffItemSchema3, - MetadataEventSchema: () => MetadataEventSchema3, - MetadataExportOptionsSchema: () => MetadataExportOptionsSchema22, - MetadataFallbackStrategySchema: () => MetadataFallbackStrategySchema22, - MetadataFormatSchema: () => MetadataFormatSchema32, - MetadataImportOptionsSchema: () => MetadataImportOptionsSchema22, - MetadataLoadOptionsSchema: () => MetadataLoadOptionsSchema22, - MetadataLoadResultSchema: () => MetadataLoadResultSchema22, - MetadataLoaderContractSchema: () => MetadataLoaderContractSchema22, - MetadataManagerConfigSchema: () => MetadataManagerConfigSchema22, - MetadataOverlaySchema: () => MetadataOverlaySchema3, - MetadataPluginConfigSchema: () => MetadataPluginConfigSchema3, - MetadataPluginManifestSchema: () => MetadataPluginManifestSchema2, - MetadataQueryResultSchema: () => MetadataQueryResultSchema3, - MetadataQuerySchema: () => MetadataQuerySchema3, - MetadataSaveOptionsSchema: () => MetadataSaveOptionsSchema22, - MetadataSaveResultSchema: () => MetadataSaveResultSchema22, - MetadataStatsSchema: () => MetadataStatsSchema22, - MetadataTypeRegistryEntrySchema: () => MetadataTypeRegistryEntrySchema3, - MetadataTypeSchema: () => MetadataTypeSchema3, - MetadataValidationResultSchema: () => MetadataValidationResultSchema3, - MetadataWatchEventSchema: () => MetadataWatchEventSchema22, - MultiVersionSupportSchema: () => MultiVersionSupportSchema2, - NamespaceConflictErrorSchema: () => NamespaceConflictErrorSchema2, - NamespaceRegistryEntrySchema: () => NamespaceRegistryEntrySchema2, - OclifPluginConfigSchema: () => OclifPluginConfigSchema2, - OpsDomainModuleSchema: () => OpsDomainModuleSchema2, - OpsFilePathSchema: () => OpsFilePathSchema2, - OpsPluginStructureSchema: () => OpsPluginStructureSchema2, - PackageArtifactSchema: () => PackageArtifactSchema3, - PackageDependencyConflictSchema: () => PackageDependencyConflictSchema2, - PackageDependencyResolutionResultSchema: () => PackageDependencyResolutionResultSchema2, - PackageDependencySchema: () => PackageDependencySchema2, - PackageStatusEnum: () => PackageStatusEnum3, - PermissionActionSchema: () => PermissionActionSchema2, - PermissionSchema: () => PermissionSchema2, - PermissionScopeSchema: () => PermissionScopeSchema2, - PermissionSetSchema: () => PermissionSetSchema22, - PluginBuildOptionsSchema: () => PluginBuildOptionsSchema2, - PluginBuildResultSchema: () => PluginBuildResultSchema2, - PluginCachingSchema: () => PluginCachingSchema3, - PluginCapabilityManifestSchema: () => PluginCapabilityManifestSchema3, - PluginCapabilitySchema: () => PluginCapabilitySchema3, - PluginCodeSplittingSchema: () => PluginCodeSplittingSchema3, - PluginCompatibilityMatrixSchema: () => PluginCompatibilityMatrixSchema2, - PluginContextSchema: () => PluginContextSchema2, - PluginDependencyResolutionResultSchema: () => PluginDependencyResolutionResultSchema2, - PluginDependencyResolutionSchema: () => PluginDependencyResolutionSchema3, - PluginDependencySchema: () => PluginDependencySchema3, - PluginDiscoveryConfigSchema: () => PluginDiscoveryConfigSchema2, - PluginDiscoverySourceSchema: () => PluginDiscoverySourceSchema2, - PluginDynamicImportSchema: () => PluginDynamicImportSchema3, - PluginErrorEventSchema: () => PluginErrorEventSchema2, - PluginEventBaseSchema: () => PluginEventBaseSchema2, - PluginHealthCheckSchema: () => PluginHealthCheckSchema2, - PluginHealthReportSchema: () => PluginHealthReportSchema2, - PluginHealthStatusSchema: () => PluginHealthStatusSchema2, - PluginHotReloadSchema: () => PluginHotReloadSchema3, - PluginInitializationSchema: () => PluginInitializationSchema3, - PluginInstallConfigSchema: () => PluginInstallConfigSchema2, - PluginInterfaceSchema: () => PluginInterfaceSchema3, - PluginLifecycleEventType: () => PluginLifecycleEventType2, - PluginLifecyclePhaseEventSchema: () => PluginLifecyclePhaseEventSchema2, - PluginLifecycleSchema: () => PluginLifecycleSchema3, - PluginLoadingConfigSchema: () => PluginLoadingConfigSchema3, - PluginLoadingEventSchema: () => PluginLoadingEventSchema2, - PluginLoadingStateSchema: () => PluginLoadingStateSchema2, - PluginLoadingStrategySchema: () => PluginLoadingStrategySchema3, - PluginMetadataSchema: () => PluginMetadataSchema2, - PluginPerformanceMonitoringSchema: () => PluginPerformanceMonitoringSchema3, - PluginPreloadConfigSchema: () => PluginPreloadConfigSchema3, - PluginProvenanceSchema: () => PluginProvenanceSchema2, - PluginPublishOptionsSchema: () => PluginPublishOptionsSchema2, - PluginPublishResultSchema: () => PluginPublishResultSchema2, - PluginQualityMetricsSchema: () => PluginQualityMetricsSchema2, - PluginRegisteredEventSchema: () => PluginRegisteredEventSchema2, - PluginRegistryEntrySchema: () => PluginRegistryEntrySchema2, - PluginSandboxingSchema: () => PluginSandboxingSchema3, - PluginSchema: () => PluginSchema2, - PluginSearchFiltersSchema: () => PluginSearchFiltersSchema2, - PluginSecurityManifestSchema: () => PluginSecurityManifestSchema2, - PluginSecurityProtocol: () => PluginSecurityProtocol, - PluginSourceSchema: () => PluginSourceSchema2, - PluginStartupResultSchema: () => PluginStartupResultSchema2, - PluginStateSnapshotSchema: () => PluginStateSnapshotSchema2, - PluginStatisticsSchema: () => PluginStatisticsSchema2, - PluginTrustLevelSchema: () => PluginTrustLevelSchema2, - PluginTrustScoreSchema: () => PluginTrustScoreSchema2, - PluginUpdateStrategySchema: () => PluginUpdateStrategySchema2, - PluginValidateOptionsSchema: () => PluginValidateOptionsSchema2, - PluginValidateResultSchema: () => PluginValidateResultSchema2, - PluginVendorSchema: () => PluginVendorSchema2, - PluginVersionMetadataSchema: () => PluginVersionMetadataSchema2, - PreviewModeConfigSchema: () => PreviewModeConfigSchema2, - ProtocolFeatureSchema: () => ProtocolFeatureSchema3, - ProtocolReferenceSchema: () => ProtocolReferenceSchema3, - ProtocolVersionSchema: () => ProtocolVersionSchema3, - RealTimeNotificationConfigSchema: () => RealTimeNotificationConfigSchema2, - RequiredActionSchema: () => RequiredActionSchema3, - ResolvedDependencySchema: () => ResolvedDependencySchema3, - ResourceTypeSchema: () => ResourceTypeSchema2, - RollbackPackageRequestSchema: () => RollbackPackageRequestSchema2, - RollbackPackageResponseSchema: () => RollbackPackageResponseSchema2, - RuntimeConfigSchema: () => RuntimeConfigSchema2, - RuntimeMode: () => RuntimeMode2, - SBOMEntrySchema: () => SBOMEntrySchema2, - SBOMSchema: () => SBOMSchema2, - SandboxConfigSchema: () => SandboxConfigSchema2, - ScopeConfigSchema: () => ScopeConfigSchema2, - ScopeInfoSchema: () => ScopeInfoSchema2, - SecurityPolicySchema: () => SecurityPolicySchema2, - SecurityScanResultSchema: () => SecurityScanResultSchema2, - SecurityVulnerabilitySchema: () => SecurityVulnerabilitySchema2, - SemanticVersionSchema: () => SemanticVersionSchema2, - ServiceFactoryRegistrationSchema: () => ServiceFactoryRegistrationSchema2, - ServiceMetadataSchema: () => ServiceMetadataSchema2, - ServiceRegisteredEventSchema: () => ServiceRegisteredEventSchema2, - ServiceRegistryConfigSchema: () => ServiceRegistryConfigSchema2, - ServiceScopeType: () => ServiceScopeType2, - ServiceUnregisteredEventSchema: () => ServiceUnregisteredEventSchema2, - StartupOptionsSchema: () => StartupOptionsSchema2, - StartupOrchestrationResultSchema: () => StartupOrchestrationResultSchema2, - TenantRuntimeContextSchema: () => TenantRuntimeContextSchema2, - UninstallPackageRequestSchema: () => UninstallPackageRequestSchema3, - UninstallPackageResponseSchema: () => UninstallPackageResponseSchema3, - UpgradeContextSchema: () => UpgradeContextSchema2, - UpgradeImpactLevelSchema: () => UpgradeImpactLevelSchema3, - UpgradePackageRequestSchema: () => UpgradePackageRequestSchema2, - UpgradePackageResponseSchema: () => UpgradePackageResponseSchema2, - UpgradePhaseSchema: () => UpgradePhaseSchema3, - UpgradePlanSchema: () => UpgradePlanSchema3, - UpgradeSnapshotSchema: () => UpgradeSnapshotSchema2, - ValidationErrorSchema: () => ValidationErrorSchema2, - ValidationFindingSchema: () => ValidationFindingSchema2, - ValidationResultSchema: () => ValidationResultSchema2, - ValidationSeverityEnum: () => ValidationSeverityEnum2, - ValidationWarningSchema: () => ValidationWarningSchema2, - VersionConstraintSchema: () => VersionConstraintSchema2, - VulnerabilitySeverity: () => VulnerabilitySeverity2 -}); -var CLICommandContributionSchema2 = external_exports.object({ - /** - * CLI command name. Must be a valid identifier: lowercase alphanumeric with hyphens. - * This becomes a top-level subcommand of the `os` CLI. - * - * @example "marketplace" - * @example "deploy" - * @example "cloud-sync" - */ - name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), - /** Brief description shown in `os --help` output. */ - description: external_exports.string().optional().describe("Command description for help text"), - /** - * Module path that exports the oclif Command class(es). - * Relative to the plugin package root. With oclif, this is typically - * auto-discovered from the `commands` directory, but can be specified - * for documentation or manifest purposes. - * - * @example "./dist/commands/marketplace.js" - * @example "./dist/commands" - */ - module: external_exports.string().optional().describe("Module path exporting oclif Command classes") -}); -var OclifPluginConfigSchema2 = external_exports.object({ - /** Command discovery configuration */ - commands: external_exports.object({ - /** Discovery strategy — typically "pattern" for file-based discovery */ - strategy: external_exports.enum(["pattern", "explicit", "single"]).optional().describe("Command discovery strategy"), - /** Directory path containing compiled command files */ - target: external_exports.string().optional().describe("Target directory for command files"), - /** Glob pattern for matching command files */ - glob: external_exports.string().optional().describe("Glob pattern for command file matching") - }).optional().describe("Command discovery configuration"), - /** Topic separator character (default: space) */ - topicSeparator: external_exports.string().optional().describe("Character separating topic and command names") -}).describe("oclif plugin configuration section"); -var MetadataCategoryEnum3 = external_exports.enum([ - "objects", - "views", - "pages", - "flows", - "dashboards", - "permissions", - "agents", - "reports", - "actions", - "translations", - "themes", - "datasets", - "apis", - "triggers", - "workflows" -]).describe("Metadata category within the artifact"); -var ArtifactFileEntrySchema3 = external_exports.object({ - /** Relative path within the artifact (e.g. "metadata/objects/account.object.json") */ - path: external_exports.string().describe("Relative file path within the artifact"), - /** File size in bytes */ - size: external_exports.number().int().nonnegative().describe("File size in bytes"), - /** Metadata category (if under metadata/) */ - category: MetadataCategoryEnum3.optional().describe("Metadata category this file belongs to") -}).describe("A single file entry within the artifact"); -var ArtifactChecksumSchema3 = external_exports.object({ - /** Hash algorithm used (default: SHA256) */ - algorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm used for checksums"), - /** Map of relative file paths to their hash values */ - files: external_exports.record(external_exports.string(), external_exports.string().regex(/^[a-f0-9]+$/)).describe("File path to hash value mapping") -}).describe("Checksum manifest for artifact integrity verification"); -var ArtifactSignatureSchema3 = external_exports.object({ - /** Signature algorithm */ - algorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).default("RSA-SHA256").describe("Signing algorithm used"), - /** Public key reference (URL or fingerprint) for verification */ - publicKeyRef: external_exports.string().describe("Public key reference (URL or fingerprint) for signature verification"), - /** Base64-encoded signature value */ - signature: external_exports.string().describe("Base64-encoded digital signature"), - /** Timestamp of when the artifact was signed */ - signedAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp of when the artifact was signed"), - /** Signer identity (publisher ID or email) */ - signedBy: external_exports.string().optional().describe("Identity of the signer (publisher ID or email)") -}).describe("Digital signature for artifact authenticity verification"); -var PackageArtifactSchema3 = external_exports.object({ - /** Artifact format version (for forward compatibility) */ - formatVersion: external_exports.string().regex(/^\d+\.\d+$/).default("1.0").describe('Artifact format version (e.g. "1.0")'), - /** Package ID from the manifest */ - packageId: external_exports.string().describe("Package identifier from manifest"), - /** Package version from the manifest */ - version: external_exports.string().describe("Package version from manifest"), - /** Artifact format */ - format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format of the artifact"), - /** Total artifact size in bytes */ - size: external_exports.number().int().positive().optional().describe("Total artifact file size in bytes"), - /** Build timestamp */ - builtAt: external_exports.string().datetime().describe("ISO 8601 timestamp of when the artifact was built"), - /** Build tool and version that produced this artifact */ - builtWith: external_exports.string().optional().describe('Build tool identifier (e.g. "os-cli@3.2.0")'), - /** File listing within the artifact */ - files: external_exports.array(ArtifactFileEntrySchema3).optional().describe("List of files contained in the artifact"), - /** Metadata categories present in the artifact */ - metadataCategories: external_exports.array(MetadataCategoryEnum3).optional().describe("Metadata categories included in this artifact"), - /** Integrity checksums for all files */ - checksums: ArtifactChecksumSchema3.optional().describe("SHA256 checksums for artifact integrity verification"), - /** Digital signature for authenticity */ - signature: ArtifactSignatureSchema3.optional().describe("Digital signature for artifact authenticity verification") -}).describe("Package artifact structure and metadata"); -var PluginBuildOptionsSchema2 = external_exports.object({ - /** Project root directory (defaults to cwd) */ - directory: external_exports.string().optional().describe("Project root directory (defaults to current working directory)"), - /** Output directory for the built artifact */ - outDir: external_exports.string().optional().describe("Output directory for the built artifact (defaults to ./dist)"), - /** Archive format */ - format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Archive format for the artifact"), - /** Whether to sign the artifact */ - sign: external_exports.boolean().default(false).describe("Whether to digitally sign the artifact"), - /** Path to the private key for signing */ - privateKeyPath: external_exports.string().optional().describe("Path to RSA/ECDSA private key file for signing"), - /** Signing algorithm */ - signAlgorithm: external_exports.enum(["RSA-SHA256", "RSA-SHA384", "RSA-SHA512", "ECDSA-SHA256"]).optional().describe("Signing algorithm to use"), - /** Checksum algorithm */ - checksumAlgorithm: external_exports.enum(["sha256", "sha384", "sha512"]).default("sha256").describe("Hash algorithm for file checksums"), - /** Whether to include seed data */ - includeData: external_exports.boolean().default(true).describe("Whether to include seed data in the artifact"), - /** Whether to include locale/translation files */ - includeLocales: external_exports.boolean().default(true).describe("Whether to include locale/translation files") -}).describe("Options for the os plugin build command"); -var PluginBuildResultSchema2 = external_exports.object({ - /** Whether the build succeeded */ - success: external_exports.boolean().describe("Whether the build succeeded"), - /** Path to the generated artifact file */ - artifactPath: external_exports.string().optional().describe("Absolute path to the generated artifact file"), - /** Artifact metadata (validated against PackageArtifactSchema) */ - artifact: PackageArtifactSchema3.optional().describe("Artifact metadata"), - /** Total file count in the artifact */ - fileCount: external_exports.number().int().min(0).optional().describe("Total number of files in the artifact"), - /** Total artifact size in bytes */ - size: external_exports.number().int().min(0).optional().describe("Total artifact size in bytes"), - /** Build duration in milliseconds */ - durationMs: external_exports.number().optional().describe("Build duration in milliseconds"), - /** Error message if build failed */ - errorMessage: external_exports.string().optional().describe("Error message if build failed"), - /** Warnings emitted during build */ - warnings: external_exports.array(external_exports.string()).optional().describe("Warnings emitted during build") -}).describe("Result of the os plugin build command"); -var ValidationSeverityEnum2 = external_exports.enum([ - "error", - // Must fix — artifact is invalid - "warning", - // Should fix — may cause issues - "info" - // Informational — suggestion -]).describe("Validation issue severity"); -var ValidationFindingSchema2 = external_exports.object({ - /** Finding severity */ - severity: ValidationSeverityEnum2.describe("Issue severity level"), - /** Rule or check that produced this finding */ - rule: external_exports.string().describe("Validation rule identifier"), - /** Human-readable message */ - message: external_exports.string().describe("Human-readable finding description"), - /** File path within the artifact (if applicable) */ - path: external_exports.string().optional().describe("Relative file path within the artifact") -}).describe("A single validation finding"); -var PluginValidateOptionsSchema2 = external_exports.object({ - /** Path to the .tgz artifact file to validate */ - artifactPath: external_exports.string().describe("Path to the artifact file to validate"), - /** Whether to verify the digital signature */ - verifySignature: external_exports.boolean().default(true).describe("Whether to verify the digital signature"), - /** Path to the public key for signature verification */ - publicKeyPath: external_exports.string().optional().describe("Path to the public key for signature verification"), - /** Whether to verify SHA256 checksums of all files */ - verifyChecksums: external_exports.boolean().default(true).describe("Whether to verify checksums of all files"), - /** Whether to validate metadata schema compliance */ - validateMetadata: external_exports.boolean().default(true).describe("Whether to validate metadata against schemas"), - /** Target platform version for compatibility check */ - platformVersion: external_exports.string().optional().describe("Platform version for compatibility verification") -}).describe("Options for the os plugin validate command"); -var PluginValidateResultSchema2 = external_exports.object({ - /** Whether the artifact is valid (no error-level findings) */ - valid: external_exports.boolean().describe("Whether the artifact passed validation"), - /** Artifact metadata extracted from the archive */ - artifact: PackageArtifactSchema3.optional().describe("Extracted artifact metadata"), - /** Checksum verification result */ - checksumVerification: external_exports.object({ - /** Whether all checksums match */ - passed: external_exports.boolean().describe("Whether all checksums match"), - /** Checksum details */ - checksums: ArtifactChecksumSchema3.optional().describe("Verified checksums"), - /** Files with mismatched checksums */ - mismatches: external_exports.array(external_exports.string()).optional().describe("Files with checksum mismatches") - }).optional().describe("Checksum verification result"), - /** Signature verification result */ - signatureVerification: external_exports.object({ - /** Whether the signature is valid */ - passed: external_exports.boolean().describe("Whether the signature is valid"), - /** Signature details */ - signature: ArtifactSignatureSchema3.optional().describe("Signature details"), - /** Reason for failure */ - failureReason: external_exports.string().optional().describe("Signature verification failure reason") - }).optional().describe("Signature verification result"), - /** Platform compatibility result */ - platformCompatibility: external_exports.object({ - /** Whether the artifact is compatible with the target platform */ - compatible: external_exports.boolean().describe("Whether artifact is compatible"), - /** Required platform version range */ - requiredRange: external_exports.string().optional().describe("Required platform version range"), - /** Target platform version checked against */ - targetVersion: external_exports.string().optional().describe("Target platform version") - }).optional().describe("Platform compatibility check result"), - /** All validation findings */ - findings: external_exports.array(ValidationFindingSchema2).describe("All validation findings"), - /** Counts by severity */ - summary: external_exports.object({ - errors: external_exports.number().int().min(0).describe("Error count"), - warnings: external_exports.number().int().min(0).describe("Warning count"), - infos: external_exports.number().int().min(0).describe("Info count") - }).optional().describe("Finding counts by severity") -}).describe("Result of the os plugin validate command"); -var PluginPublishOptionsSchema2 = external_exports.object({ - /** Path to the .tgz artifact file to publish */ - artifactPath: external_exports.string().describe("Path to the artifact file to publish"), - /** Marketplace API base URL */ - registryUrl: external_exports.string().url().optional().describe("Marketplace API base URL"), - /** Authentication token for the marketplace API */ - token: external_exports.string().optional().describe("Authentication token for marketplace API"), - /** Release notes for this version */ - releaseNotes: external_exports.string().optional().describe("Release notes for this version"), - /** Whether this is a pre-release */ - preRelease: external_exports.boolean().default(false).describe("Whether this is a pre-release version"), - /** Whether to skip validation before publishing */ - skipValidation: external_exports.boolean().default(false).describe("Whether to skip local validation before publish"), - /** Access level for the published package */ - access: external_exports.enum(["public", "restricted"]).default("public").describe("Package access level on the marketplace"), - /** Tags for categorization */ - tags: external_exports.array(external_exports.string()).optional().describe("Tags for marketplace categorization") -}).describe("Options for the os plugin publish command"); -var PluginPublishResultSchema2 = external_exports.object({ - /** Whether the publish succeeded */ - success: external_exports.boolean().describe("Whether the publish succeeded"), - /** Package ID that was published */ - packageId: external_exports.string().optional().describe("Published package identifier"), - /** Version that was published */ - version: external_exports.string().optional().describe("Published version string"), - /** Artifact reference in the marketplace */ - artifactUrl: external_exports.string().url().optional().describe("URL of the published artifact in the marketplace"), - /** SHA256 checksum of the uploaded artifact */ - sha256: external_exports.string().optional().describe("SHA256 checksum of the uploaded artifact"), - /** Submission ID for tracking the review process */ - submissionId: external_exports.string().optional().describe("Marketplace submission ID for review tracking"), - /** Error message if publish failed */ - errorMessage: external_exports.string().optional().describe("Error message if publish failed"), - /** Human-readable status message */ - message: external_exports.string().optional().describe("Human-readable status message") -}).describe("Result of the os plugin publish command"); -var RuntimeMode2 = external_exports.enum([ - "development", - // Hot-reload, verbose logging - "production", - // Optimized, strict security - "test", - // Mocked interfaces - "provisioning", - // Setup/Migration mode - "preview" - // Demo/preview mode — bypass auth, simulate admin identity -]).describe("Kernel operating mode"); -var PreviewModeConfigSchema2 = external_exports.object({ - /** - * Automatically log in as a simulated user on startup. - * When enabled, the frontend skips login/registration screens entirely. - */ - autoLogin: external_exports.boolean().default(true).describe("Auto-login as simulated user, skipping login/registration pages"), - /** - * Role of the simulated user. - * Determines the permission level of the auto-created preview session. - */ - simulatedRole: external_exports.enum(["admin", "user", "viewer"]).default("admin").describe("Permission role for the simulated preview user"), - /** - * Display name for the simulated user shown in the UI. - */ - simulatedUserName: external_exports.string().default("Preview User").describe("Display name for the simulated preview user"), - /** - * Whether the preview session is read-only. - * When true, all write operations (create, update, delete) are blocked. - */ - readOnly: external_exports.boolean().default(false).describe("Restrict the preview session to read-only operations"), - /** - * Session duration in seconds. After expiry the preview session ends. - * 0 means no expiration. - */ - expiresInSeconds: external_exports.number().int().min(0).default(0).describe("Preview session duration in seconds (0 = no expiration)"), - /** - * Optional banner message shown in the UI to indicate preview mode. - * Useful for marketplace demos so visitors know they are in a sandbox. - */ - bannerMessage: external_exports.string().optional().describe("Banner message displayed in the UI during preview mode") -}); -var KernelContextSchema2 = external_exports.object({ - /** - * Instance Identity - */ - instanceId: external_exports.string().uuid().describe("Unique UUID for this running kernel process"), - /** - * Environment Metadata - */ - mode: RuntimeMode2.default("production"), - version: external_exports.string().describe("Kernel version"), - appName: external_exports.string().optional().describe("Host application name"), - /** - * Paths - */ - cwd: external_exports.string().describe("Current working directory"), - workspaceRoot: external_exports.string().optional().describe("Workspace root if different from cwd"), - /** - * Telemetry - */ - startTime: external_exports.number().int().describe("Boot timestamp (ms)"), - /** - * Feature Flags (Global) - */ - features: external_exports.record(external_exports.string(), external_exports.boolean()).default({}).describe("Global feature toggles"), - /** - * Preview Mode Configuration. - * Only relevant when `mode` is `'preview'`. Configures auto-login, - * simulated identity, read-only restrictions, and UI banner. - */ - previewMode: PreviewModeConfigSchema2.optional().describe('Preview/demo mode configuration (used when mode is "preview")') -}); -var TenantRuntimeContextSchema2 = KernelContextSchema2.extend({ - /** Unique tenant identifier resolved from the current session */ - tenantId: external_exports.string().min(1).describe("Resolved tenant identifier"), - /** Tenant subscription plan */ - tenantPlan: external_exports.enum(["free", "pro", "enterprise"]).describe("Tenant subscription plan"), - /** Tenant deployment region */ - tenantRegion: external_exports.string().optional().describe("Tenant deployment region"), - /** Tenant database connection URL */ - tenantDbUrl: external_exports.string().min(1).describe("Tenant database connection URL"), - /** Optional tenant quotas for the current plan */ - tenantQuotas: TenantQuotaSchema3.optional().describe("Tenant resource quotas") -}).describe("Tenant-aware kernel runtime context"); -var DependencyStatusEnum3 = external_exports.enum([ - "satisfied", - // Already installed and version compatible - "needs_install", - // Not installed, needs to be installed - "needs_upgrade", - // Installed but version incompatible, needs upgrade - "conflict" - // Conflicts with another package's dependency -]).describe("Resolution status for a dependency"); -var ResolvedDependencySchema3 = external_exports.object({ - /** Package identifier of the dependency */ - packageId: external_exports.string().describe("Dependency package identifier"), - /** SemVer range required by the parent package */ - requiredRange: external_exports.string().describe('SemVer range required (e.g. "^2.0.0")'), - /** Actual version resolved (if available) */ - resolvedVersion: external_exports.string().optional().describe("Actual version resolved from registry"), - /** Currently installed version (if any) */ - installedVersion: external_exports.string().optional().describe("Currently installed version"), - /** Resolution status */ - status: DependencyStatusEnum3.describe("Resolution status"), - /** Conflict details (when status is "conflict") */ - conflictReason: external_exports.string().optional().describe("Explanation of the conflict") -}).describe("Resolution result for a single dependency"); -var RequiredActionSchema3 = external_exports.object({ - /** Type of action required */ - type: external_exports.enum(["install", "upgrade", "confirm_conflict"]).describe("Type of action required"), - /** Target package identifier */ - packageId: external_exports.string().describe("Target package identifier"), - /** Human-readable description of the action */ - description: external_exports.string().describe("Human-readable action description") -}).describe("Action required before installation can proceed"); -var DependencyResolutionResultSchema3 = external_exports.object({ - /** All dependencies and their resolution results */ - dependencies: external_exports.array(ResolvedDependencySchema3).describe("Resolution result for each dependency"), - /** Whether installation can proceed without conflicts */ - canProceed: external_exports.boolean().describe("Whether installation can proceed"), - /** Actions that require user confirmation or system execution */ - requiredActions: external_exports.array(RequiredActionSchema3).describe("Actions required before proceeding"), - /** Topologically sorted package IDs for installation order */ - installOrder: external_exports.array(external_exports.string()).describe("Topologically sorted package IDs for installation"), - /** Detected circular dependency chains */ - circularDependencies: external_exports.array(external_exports.array(external_exports.string())).optional().describe('Circular dependency chains detected (e.g. [["A", "B", "A"]])') -}).describe("Complete dependency resolution result"); -var DevServiceOverrideSchema2 = external_exports.object({ - /** Service identifier (e.g. 'auth', 'eventBus', 'fileStorage') */ - service: external_exports.string().min(1).describe("Target service identifier"), - /** Whether this service is enabled in dev mode */ - enabled: external_exports.boolean().default(true).describe("Enable or disable this service"), - /** - * Implementation strategy for the service in dev mode. - * - mock: Use a mock/stub that records calls (for assertions) - * - memory: Use a real but in-memory implementation (e.g. SQLite, Map) - * - stub: Use a static/no-op implementation - * - passthrough: Use the real production implementation (for integration testing) - */ - strategy: external_exports.enum(["mock", "memory", "stub", "passthrough"]).default("memory").describe("Implementation strategy for development"), - /** Optional per-service configuration (strategy-specific) */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Strategy-specific configuration for this service override") -}); -var DevFixtureConfigSchema2 = external_exports.object({ - /** Whether to load fixtures on startup */ - enabled: external_exports.boolean().default(true).describe("Load fixture data on startup"), - /** - * Glob patterns pointing to fixture files - * (e.g. `["./fixtures/*.json", "./test/data/*.yml"]`) - */ - paths: external_exports.array(external_exports.string()).optional().describe("Glob patterns for fixture files"), - /** Whether to reset data before loading fixtures */ - resetBeforeLoad: external_exports.boolean().default(true).describe("Clear existing data before loading fixtures"), - /** - * Environment tag filter – only load fixtures tagged for these environments. - * When omitted, all fixtures are loaded. - */ - envFilter: external_exports.array(external_exports.string()).optional().describe("Only load fixtures matching these environment tags") -}); -var DevToolsConfigSchema2 = external_exports.object({ - /** Enable hot-module replacement / live reload */ - hotReload: external_exports.boolean().default(true).describe("Enable HMR / live-reload"), - /** Enable request inspector UI for debugging HTTP traffic */ - requestInspector: external_exports.boolean().default(false).describe("Enable request inspector"), - /** Enable an in-browser database explorer */ - dbExplorer: external_exports.boolean().default(false).describe("Enable database explorer UI"), - /** Enable verbose logging across all services */ - verboseLogging: external_exports.boolean().default(true).describe("Enable verbose logging"), - /** Enable OpenAPI / Swagger documentation endpoint */ - apiDocs: external_exports.boolean().default(true).describe("Serve OpenAPI docs at /_dev/docs"), - /** Enable a mail catcher for outbound email (like MailHog) */ - mailCatcher: external_exports.boolean().default(false).describe("Capture outbound emails in dev") -}); -var DevPluginPreset2 = external_exports.enum([ - "minimal", - "standard", - "full" -]).describe("Predefined dev configuration profile"); -var DevPluginConfigSchema2 = external_exports.object({ - /** - * Configuration preset. - * When provided, services and tools are pre-configured for the selected - * profile. Individual `services` and `tools` settings override the preset. - * @default 'standard' - */ - preset: DevPluginPreset2.default("standard").describe("Base configuration preset"), - /** - * Per-service overrides. - * Keys are service names; values configure the dev strategy. - * Only services explicitly listed here override the preset defaults. - */ - services: external_exports.record( - external_exports.string().min(1), - DevServiceOverrideSchema2.omit({ service: true }) - ).optional().describe("Per-service dev overrides keyed by service name"), - /** Fixture / seed data configuration */ - fixtures: DevFixtureConfigSchema2.optional().describe("Fixture data loading configuration"), - /** Developer tooling configuration */ - tools: DevToolsConfigSchema2.optional().describe("Developer tooling settings"), - /** - * Port for the dev-tools UI dashboard. - * Serves a lightweight web dashboard for inspecting services, events, - * and request logs during development. - * @default 4400 - */ - port: external_exports.number().int().min(1).max(65535).default(4400).describe("Port for the dev-tools dashboard"), - /** - * Auto-open the dev-tools dashboard in the default browser on startup. - */ - open: external_exports.boolean().default(false).describe("Auto-open dev dashboard in browser"), - /** - * Seed a default admin user for development. - * When enabled, the dev plugin creates a pre-authenticated admin user - * so that developers can bypass login flows. - */ - seedAdminUser: external_exports.boolean().default(true).describe("Create a default admin user for development"), - /** - * Simulated latency (ms) to add to service calls. - * Helps developers build UIs that handle loading states correctly. - * Set to 0 to disable. - */ - simulatedLatency: external_exports.number().int().min(0).default(0).describe("Artificial latency (ms) added to service calls") -}); -var EventPriority2 = external_exports.enum([ - "critical", - // 0 - Process immediately, block if necessary - "high", - // 1 - Process soon, minimal delay - "normal", - // 2 - Default priority - "low", - // 3 - Process when resources available - "background" - // 4 - Process during idle time -]); -var EVENT_PRIORITY_VALUES = { - critical: 0, - high: 1, - normal: 2, - low: 3, - background: 4 -}; -var EventMetadataSchema2 = external_exports.object({ - source: external_exports.string().describe("Event source (e.g., plugin name, system component)"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when event was created"), - userId: external_exports.string().optional().describe("User who triggered the event"), - tenantId: external_exports.string().optional().describe("Tenant identifier for multi-tenant systems"), - correlationId: external_exports.string().optional().describe("Correlation ID for event tracing"), - causationId: external_exports.string().optional().describe("ID of the event that caused this event"), - priority: EventPriority2.optional().default("normal").describe("Event priority") -}); -var EventTypeDefinitionSchema2 = external_exports.object({ - name: EventNameSchema4.describe("Event type name (lowercase with dots)"), - version: external_exports.string().default("1.0.0").describe("Event schema version"), - schema: external_exports.unknown().optional().describe("JSON Schema for event payload validation"), - description: external_exports.string().optional().describe("Event type description"), - deprecated: external_exports.boolean().optional().default(false).describe("Whether this event type is deprecated"), - tags: external_exports.array(external_exports.string()).optional().describe("Event type tags") -}); -var EventSchema22 = external_exports.object({ - /** - * Event identifier (for tracking and deduplication) - */ - id: external_exports.string().optional().describe("Unique event identifier"), - /** - * Event name - */ - name: EventNameSchema4.describe("Event name (lowercase with dots, e.g., user.created, order.paid)"), - /** - * Event payload - */ - payload: external_exports.unknown().describe("Event payload schema"), - /** - * Event metadata - */ - metadata: EventMetadataSchema2.describe("Event metadata") -}); -var EventHandlerSchema2 = external_exports.object({ - /** - * Handler identifier - */ - id: external_exports.string().optional().describe("Unique handler identifier"), - /** - * Event name pattern - */ - eventName: external_exports.string().describe("Name of event to handle (supports wildcards like user.*)"), - /** - * Handler function - */ - handler: external_exports.unknown().describe("Handler function"), - /** - * Execution priority - */ - priority: external_exports.number().int().default(0).describe("Execution priority (lower numbers execute first)"), - /** - * Async execution - */ - async: external_exports.boolean().default(true).describe("Execute in background (true) or block (false)"), - /** - * Retry configuration - */ - retry: external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retry attempts"), - backoffMs: external_exports.number().int().positive().default(1e3).describe("Initial backoff delay"), - backoffMultiplier: external_exports.number().positive().default(2).describe("Backoff multiplier") - }).optional().describe("Retry policy for failed handlers"), - /** - * Timeout - */ - timeoutMs: external_exports.number().int().positive().optional().describe("Handler timeout in milliseconds"), - /** - * Filter function - */ - filter: external_exports.unknown().optional().describe("Optional filter to determine if handler should execute") -}); -var EventRouteSchema2 = external_exports.object({ - from: external_exports.string().describe("Source event pattern (supports wildcards, e.g., user.* or *.created)"), - to: external_exports.array(external_exports.string()).describe("Target event names to route to"), - transform: external_exports.unknown().optional().describe("Optional function to transform payload") -}); -var EventPersistenceSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable event persistence"), - retention: external_exports.number().int().positive().describe("Days to retain persisted events"), - filter: external_exports.unknown().optional().describe("Optional filter function to select which events to persist"), - storage: external_exports.enum(["database", "file", "s3", "custom"]).default("database").describe("Storage backend for persisted events") -}); -var EventQueueConfigSchema2 = external_exports.object({ - /** - * Queue name - */ - name: external_exports.string().default("events").describe("Event queue name"), - /** - * Concurrency - */ - concurrency: external_exports.number().int().min(1).default(10).describe("Max concurrent event handlers"), - /** - * Retry policy - */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Max retries for failed events"), - backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy"), - initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay"), - maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Maximum retry delay") - }).optional().describe("Default retry policy for events"), - /** - * Dead letter queue - */ - deadLetterQueue: external_exports.string().optional().describe("Dead letter queue name for failed events"), - /** - * Enable priority processing - */ - priorityEnabled: external_exports.boolean().default(true).describe("Process events based on priority") -}); -var EventReplayConfigSchema2 = external_exports.object({ - /** - * Start timestamp - */ - fromTimestamp: external_exports.string().datetime().describe("Start timestamp for replay (ISO 8601)"), - /** - * End timestamp - */ - toTimestamp: external_exports.string().datetime().optional().describe("End timestamp for replay (ISO 8601)"), - /** - * Event types to replay - */ - eventTypes: external_exports.array(external_exports.string()).optional().describe("Event types to replay (empty = all)"), - /** - * Event filters - */ - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional filters for event selection"), - /** - * Replay speed multiplier - */ - speed: external_exports.number().positive().default(1).describe("Replay speed multiplier (1 = real-time)"), - /** - * Target handlers - */ - targetHandlers: external_exports.array(external_exports.string()).optional().describe("Handler IDs to execute (empty = all)") -}); -var EventSourcingConfigSchema2 = external_exports.object({ - /** - * Enable event sourcing - */ - enabled: external_exports.boolean().default(false).describe("Enable event sourcing"), - /** - * Snapshot interval - */ - snapshotInterval: external_exports.number().int().positive().default(100).describe("Create snapshot every N events"), - /** - * Snapshot retention - */ - snapshotRetention: external_exports.number().int().positive().default(10).describe("Number of snapshots to retain"), - /** - * Event retention - */ - retention: external_exports.number().int().positive().default(365).describe("Days to retain events"), - /** - * Aggregate types - */ - aggregateTypes: external_exports.array(external_exports.string()).optional().describe("Aggregate types to enable event sourcing for"), - /** - * Storage configuration - */ - storage: external_exports.object({ - type: external_exports.enum(["database", "file", "s3", "eventstore"]).default("database").describe("Storage backend"), - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Storage-specific options") - }).optional().describe("Event store configuration") -}); -var DeadLetterQueueEntrySchema2 = external_exports.object({ - /** - * Entry identifier - */ - id: external_exports.string().describe("Unique entry identifier"), - /** - * Original event - */ - event: EventSchema22.describe("Original event"), - /** - * Failure reason - */ - error: external_exports.object({ - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Error stack trace"), - code: external_exports.string().optional().describe("Error code") - }).describe("Failure details"), - /** - * Retry count - */ - retries: external_exports.number().int().min(0).describe("Number of retry attempts"), - /** - * Timestamps - */ - firstFailedAt: external_exports.string().datetime().describe("When event first failed"), - lastFailedAt: external_exports.string().datetime().describe("When event last failed"), - /** - * Handler that failed - */ - failedHandler: external_exports.string().optional().describe("Handler ID that failed") -}); -var EventLogEntrySchema2 = external_exports.object({ - /** - * Log entry ID - */ - id: external_exports.string().describe("Unique log entry identifier"), - /** - * Event - */ - event: EventSchema22.describe("The event"), - /** - * Status - */ - status: external_exports.enum(["pending", "processing", "completed", "failed"]).describe("Processing status"), - /** - * Handlers executed - */ - handlersExecuted: external_exports.array(external_exports.object({ - handlerId: external_exports.string().describe("Handler identifier"), - status: external_exports.enum(["success", "failed", "timeout"]).describe("Handler execution status"), - durationMs: external_exports.number().int().optional().describe("Execution duration"), - error: external_exports.string().optional().describe("Error message if failed") - })).optional().describe("Handlers that processed this event"), - /** - * Timestamps - */ - receivedAt: external_exports.string().datetime().describe("When event was received"), - processedAt: external_exports.string().datetime().optional().describe("When event was processed"), - /** - * Total duration - */ - totalDurationMs: external_exports.number().int().optional().describe("Total processing time") -}); -var EventWebhookConfigSchema2 = external_exports.object({ - /** - * Webhook identifier - */ - id: external_exports.string().optional().describe("Unique webhook identifier"), - /** - * Event pattern to match - */ - eventPattern: external_exports.string().describe("Event name pattern (supports wildcards)"), - /** - * Target URL - */ - url: external_exports.string().url().describe("Webhook endpoint URL"), - /** - * HTTP method - */ - method: external_exports.enum(["GET", "POST", "PUT", "PATCH"]).default("POST").describe("HTTP method"), - /** - * Headers - */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP headers"), - /** - * Authentication - */ - authentication: external_exports.object({ - type: external_exports.enum(["none", "bearer", "basic", "api-key"]).describe("Auth type"), - credentials: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Auth credentials") - }).optional().describe("Authentication configuration"), - /** - * Retry policy - */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().int().min(0).default(3).describe("Max retry attempts"), - backoffStrategy: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential"), - initialDelayMs: external_exports.number().int().positive().default(1e3).describe("Initial retry delay"), - maxDelayMs: external_exports.number().int().positive().default(6e4).describe("Max retry delay") - }).optional().describe("Retry policy"), - /** - * Timeout - */ - timeoutMs: external_exports.number().int().positive().default(3e4).describe("Request timeout in milliseconds"), - /** - * Event transformation - */ - transform: external_exports.unknown().optional().describe("Transform event before sending"), - /** - * Enabled - */ - enabled: external_exports.boolean().default(true).describe("Whether webhook is enabled") -}); -var EventMessageQueueConfigSchema2 = external_exports.object({ - /** - * Provider - */ - provider: external_exports.enum(["kafka", "rabbitmq", "aws-sqs", "redis-pubsub", "google-pubsub", "azure-service-bus"]).describe("Message queue provider"), - /** - * Topic/Queue name - */ - topic: external_exports.string().describe("Topic or queue name"), - /** - * Event pattern - */ - eventPattern: external_exports.string().default("*").describe("Event name pattern to publish (supports wildcards)"), - /** - * Partition key - */ - partitionKey: external_exports.string().optional().describe('JSON path for partition key (e.g., "metadata.tenantId")'), - /** - * Message format - */ - format: external_exports.enum(["json", "avro", "protobuf"]).default("json").describe("Message serialization format"), - /** - * Include metadata - */ - includeMetadata: external_exports.boolean().default(true).describe("Include event metadata in message"), - /** - * Compression - */ - compression: external_exports.enum(["none", "gzip", "snappy", "lz4"]).default("none").describe("Message compression"), - /** - * Batch size - */ - batchSize: external_exports.number().int().min(1).default(1).describe("Batch size for publishing"), - /** - * Flush interval - */ - flushIntervalMs: external_exports.number().int().positive().default(1e3).describe("Flush interval for batching") -}); -var RealTimeNotificationConfigSchema2 = external_exports.object({ - /** - * Enable real-time notifications - */ - enabled: external_exports.boolean().default(true).describe("Enable real-time notifications"), - /** - * Protocol - */ - protocol: external_exports.enum(["websocket", "sse", "long-polling"]).default("websocket").describe("Real-time protocol"), - /** - * Event pattern - */ - eventPattern: external_exports.string().default("*").describe("Event pattern to broadcast"), - /** - * User-specific filtering - */ - userFilter: external_exports.boolean().default(true).describe("Filter events by user"), - /** - * Tenant-specific filtering - */ - tenantFilter: external_exports.boolean().default(true).describe("Filter events by tenant"), - /** - * Channels - */ - channels: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Channel name"), - eventPattern: external_exports.string().describe("Event pattern for channel"), - filter: external_exports.unknown().optional().describe("Additional filter function") - })).optional().describe("Named channels for event broadcasting"), - /** - * Rate limiting - */ - rateLimit: external_exports.object({ - maxEventsPerSecond: external_exports.number().int().positive().describe("Max events per second per client"), - windowMs: external_exports.number().int().positive().default(1e3).describe("Rate limit window") - }).optional().describe("Rate limiting configuration") -}); -var EventBusConfigSchema2 = external_exports.object({ - /** - * Event persistence - */ - persistence: EventPersistenceSchema2.optional().describe("Event persistence configuration"), - /** - * Event queue - */ - queue: EventQueueConfigSchema2.optional().describe("Event queue configuration"), - /** - * Event sourcing - */ - eventSourcing: EventSourcingConfigSchema2.optional().describe("Event sourcing configuration"), - /** - * Event replay - */ - replay: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable event replay capability") - }).optional().describe("Event replay configuration"), - /** - * Webhooks - */ - webhooks: external_exports.array(EventWebhookConfigSchema2).optional().describe("Webhook configurations"), - /** - * Message queue integration - */ - messageQueue: EventMessageQueueConfigSchema2.optional().describe("Message queue integration"), - /** - * Real-time notifications - */ - realtime: RealTimeNotificationConfigSchema2.optional().describe("Real-time notification configuration"), - /** - * Event type definitions - */ - eventTypes: external_exports.array(EventTypeDefinitionSchema2).optional().describe("Event type definitions"), - /** - * Global handlers - */ - handlers: external_exports.array(EventHandlerSchema2).optional().describe("Global event handlers") -}); -var FeatureStrategy2 = external_exports.enum([ - "boolean", - // Simple On/Off - "percentage", - // Gradual rollout (0-100%) - "user_list", - // Specific users - "group", - // Specific groups/roles - "custom" - // Custom constraint/script -]); -var FeatureFlagSchema2 = external_exports.object({ - name: SnakeCaseIdentifierSchema7.describe("Feature key (snake_case)"), - label: external_exports.string().optional().describe("Display label"), - description: external_exports.string().optional(), - /** Default state */ - enabled: external_exports.boolean().default(false).describe("Is globally enabled"), - /** Rollout Strategy */ - strategy: FeatureStrategy2.default("boolean"), - /** Strategy Configuration */ - conditions: external_exports.object({ - percentage: external_exports.number().min(0).max(100).optional(), - users: external_exports.array(external_exports.string()).optional(), - groups: external_exports.array(external_exports.string()).optional(), - expression: external_exports.string().optional().describe("Custom formula expression") - }).optional(), - /** Integration */ - environment: external_exports.enum(["dev", "staging", "prod", "all"]).default("all").describe("Environment validity"), - /** Expiration */ - expiresAt: external_exports.string().datetime().optional().describe("Feature flag expiration date") -}); -var FeatureFlag2 = Object.assign(FeatureFlagSchema2, { - create: (config4) => config4 -}); -var CapabilityConformanceLevelSchema3 = external_exports.enum([ - "full", - // Complete implementation of all protocol features - "partial", - // Subset implementation with specific features listed - "experimental", - // Unstable/preview implementation - "deprecated" - // Still supported but scheduled for removal -]).describe("Level of protocol conformance"); -var ProtocolVersionSchema3 = external_exports.object({ - major: external_exports.number().int().min(0), - minor: external_exports.number().int().min(0), - patch: external_exports.number().int().min(0) -}).describe("Semantic version of the protocol"); -var ProtocolReferenceSchema3 = external_exports.object({ - /** - * Protocol identifier using reverse domain notation. - * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major} - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+protocol\.[a-z][a-z0-9._]*\.v\d+$/).describe("Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)"), - /** - * Human-readable protocol name - */ - label: external_exports.string(), - /** - * Protocol version - */ - version: ProtocolVersionSchema3, - /** - * Detailed protocol specification URL or file reference - */ - specification: external_exports.string().optional().describe("URL or path to protocol specification"), - /** - * Brief description of what this protocol defines - */ - description: external_exports.string().optional() -}); -var ProtocolFeatureSchema3 = external_exports.object({ - name: external_exports.string().describe("Feature identifier within the protocol"), - enabled: external_exports.boolean().default(true), - description: external_exports.string().optional(), - sinceVersion: external_exports.string().optional().describe("Version when this feature was added"), - deprecatedSince: external_exports.string().optional().describe("Version when deprecated") -}); -var PluginCapabilitySchema3 = external_exports.object({ - /** - * The protocol being implemented - */ - protocol: ProtocolReferenceSchema3, - /** - * Conformance level - */ - conformance: CapabilityConformanceLevelSchema3.default("full"), - /** - * Specific features implemented (required if conformance is 'partial') - */ - implementedFeatures: external_exports.array(external_exports.string()).optional().describe("List of implemented feature names"), - /** - * Optional feature flags indicating advanced capabilities - */ - features: external_exports.array(ProtocolFeatureSchema3).optional(), - /** - * Custom metadata for vendor-specific information - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Testing/Certification status - */ - certified: external_exports.boolean().default(false).describe("Has passed official conformance tests"), - certificationDate: external_exports.string().datetime().optional() -}); -var PluginInterfaceSchema3 = external_exports.object({ - /** - * Unique interface identifier - * Format: {plugin-id}.interface.{name} - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+interface\.[a-z][a-z0-9._]+$/).describe("Unique interface identifier"), - /** - * Interface name - */ - name: external_exports.string(), - /** - * Description of what this interface provides - */ - description: external_exports.string().optional(), - /** - * Interface version - */ - version: ProtocolVersionSchema3, - /** - * Methods exposed by this interface - */ - methods: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Method name"), - description: external_exports.string().optional(), - parameters: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string().describe("Type notation (e.g., string, number, User)"), - required: external_exports.boolean().default(true), - description: external_exports.string().optional() - })).optional(), - returnType: external_exports.string().optional().describe("Return value type"), - async: external_exports.boolean().default(false).describe("Whether method returns a Promise") - })), - /** - * Events emitted by this interface - */ - events: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Event name"), - description: external_exports.string().optional(), - payload: external_exports.string().optional().describe("Event payload type") - })).optional(), - /** - * Stability level - */ - stability: external_exports.enum(["stable", "beta", "alpha", "experimental"]).default("stable") -}); -var PluginDependencySchema3 = external_exports.object({ - /** - * Plugin ID using reverse domain notation - */ - pluginId: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Required plugin identifier"), - /** - * Version constraint (supports semver ranges) - * Examples: "1.0.0", "^1.2.3", ">=2.0.0 <3.0.0" - */ - version: external_exports.string().describe("Semantic version constraint"), - /** - * Whether this dependency is optional - */ - optional: external_exports.boolean().default(false), - /** - * Reason for the dependency - */ - reason: external_exports.string().optional(), - /** - * Minimum required capabilities from the dependency - */ - requiredCapabilities: external_exports.array(external_exports.string()).optional().describe("Protocol IDs the dependency must support") -}); -var ExtensionPointSchema3 = external_exports.object({ - /** - * Extension point identifier - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+extension\.[a-z][a-z0-9._]+$/).describe("Unique extension point identifier"), - /** - * Extension point name - */ - name: external_exports.string(), - /** - * Description - */ - description: external_exports.string().optional(), - /** - * Type of extension point - */ - type: external_exports.enum([ - "action", - // Plugins can register executable actions - "hook", - // Plugins can listen to lifecycle events - "widget", - // Plugins can contribute UI widgets - "provider", - // Plugins can provide data/services - "transformer", - // Plugins can transform data - "validator", - // Plugins can validate data - "decorator" - // Plugins can enhance/wrap functionality - ]), - /** - * Expected interface contract for extensions - */ - contract: external_exports.object({ - input: external_exports.string().optional().describe("Input type/schema"), - output: external_exports.string().optional().describe("Output type/schema"), - signature: external_exports.string().optional().describe("Function signature if applicable") - }).optional(), - /** - * Cardinality - */ - cardinality: external_exports.enum(["single", "multiple"]).default("multiple").describe("Whether multiple extensions can register to this point") -}); -var PluginCapabilityManifestSchema3 = external_exports.object({ - /** - * Protocols this plugin implements - */ - implements: external_exports.array(PluginCapabilitySchema3).optional().describe("List of protocols this plugin conforms to"), - /** - * Interfaces this plugin exposes to other plugins - */ - provides: external_exports.array(PluginInterfaceSchema3).optional().describe("Services/APIs this plugin offers to others"), - /** - * Dependencies on other plugins - */ - requires: external_exports.array(PluginDependencySchema3).optional().describe("Required plugins and their capabilities"), - /** - * Extension points this plugin defines - */ - extensionPoints: external_exports.array(ExtensionPointSchema3).optional().describe("Points where other plugins can extend this plugin"), - /** - * Extensions this plugin contributes to other plugins - */ - extensions: external_exports.array(external_exports.object({ - targetPluginId: external_exports.string().describe("Plugin ID being extended"), - extensionPointId: external_exports.string().describe("Extension point identifier"), - implementation: external_exports.string().describe("Path to implementation module"), - priority: external_exports.number().int().default(100).describe("Registration priority (lower = higher priority)") - })).optional().describe("Extensions contributed to other plugins") -}); -var PluginLoadingStrategySchema3 = external_exports.enum([ - "eager", - // Load immediately during bootstrap (critical plugins) - "lazy", - // Load on first use (feature plugins) - "parallel", - // Load in parallel with other plugins - "deferred", - // Load after initial bootstrap complete - "on-demand" - // Load only when explicitly requested -]).describe("Plugin loading strategy"); -var PluginPreloadConfigSchema3 = external_exports.object({ - /** - * Enable preloading for this plugin - */ - enabled: external_exports.boolean().default(false), - /** - * Preload priority (lower = higher priority) - */ - priority: external_exports.number().int().min(0).default(100), - /** - * Resources to preload - */ - resources: external_exports.array(external_exports.enum([ - "metadata", - // Plugin manifest and metadata - "dependencies", - // Plugin dependencies - "assets", - // Static assets (icons, translations) - "code", - // JavaScript code chunks - "services" - // Service definitions - ])).optional(), - /** - * Conditions for preloading - */ - conditions: external_exports.object({ - /** - * Preload only on specific routes - */ - routes: external_exports.array(external_exports.string()).optional(), - /** - * Preload only for specific user roles - */ - roles: external_exports.array(external_exports.string()).optional(), - /** - * Preload based on device type - */ - deviceType: external_exports.array(external_exports.enum(["desktop", "mobile", "tablet"])).optional(), - /** - * Network connection quality threshold - */ - minNetworkSpeed: external_exports.enum(["slow-2g", "2g", "3g", "4g"]).optional() - }).optional() -}).describe("Plugin preloading configuration"); -var PluginCodeSplittingSchema3 = external_exports.object({ - /** - * Enable code splitting for this plugin - */ - enabled: external_exports.boolean().default(true), - /** - * Split strategy - */ - strategy: external_exports.enum([ - "route", - // Split by UI routes - "feature", - // Split by feature modules - "size", - // Split by bundle size threshold - "custom" - // Custom split points defined by plugin - ]).default("feature"), - /** - * Chunk naming strategy - */ - chunkNaming: external_exports.enum(["hashed", "named", "sequential"]).default("hashed"), - /** - * Maximum chunk size in KB - */ - maxChunkSize: external_exports.number().int().min(10).optional().describe("Max chunk size in KB"), - /** - * Shared dependencies optimization - */ - sharedDependencies: external_exports.object({ - enabled: external_exports.boolean().default(true), - /** - * Minimum times a module must be shared before extraction - */ - minChunks: external_exports.number().int().min(1).default(2) - }).optional() -}).describe("Plugin code splitting configuration"); -var PluginDynamicImportSchema3 = external_exports.object({ - /** - * Enable dynamic imports - */ - enabled: external_exports.boolean().default(true), - /** - * Import mode - */ - mode: external_exports.enum([ - "async", - // Asynchronous import (recommended) - "sync", - // Synchronous import (blocking) - "eager", - // Eager evaluation - "lazy" - // Lazy evaluation - ]).default("async"), - /** - * Prefetch strategy - */ - prefetch: external_exports.boolean().default(false).describe("Prefetch module in idle time"), - /** - * Preload strategy - */ - preload: external_exports.boolean().default(false).describe("Preload module in parallel with parent"), - /** - * Webpack magic comments support - */ - webpackChunkName: external_exports.string().optional().describe("Custom chunk name for webpack"), - /** - * Import timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4).describe("Dynamic import timeout (ms)"), - /** - * Retry configuration on import failure - */ - retry: external_exports.object({ - enabled: external_exports.boolean().default(true), - maxAttempts: external_exports.number().int().min(1).max(10).default(3), - backoffMs: external_exports.number().int().min(0).default(1e3).describe("Exponential backoff base delay") - }).optional() -}).describe("Plugin dynamic import configuration"); -var PluginInitializationSchema3 = external_exports.object({ - /** - * Initialization mode - */ - mode: external_exports.enum([ - "sync", - // Synchronous initialization - "async", - // Asynchronous initialization - "parallel", - // Parallel with other plugins - "sequential" - // Must complete before next plugin - ]).default("async"), - /** - * Initialization timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4), - /** - * Startup priority (lower = higher priority, earlier initialization) - */ - priority: external_exports.number().int().min(0).default(100), - /** - * Whether to continue bootstrap if this plugin fails - */ - critical: external_exports.boolean().default(false).describe("If true, kernel bootstrap fails if plugin fails"), - /** - * Retry configuration on initialization failure - */ - retry: external_exports.object({ - enabled: external_exports.boolean().default(false), - maxAttempts: external_exports.number().int().min(1).max(5).default(3), - backoffMs: external_exports.number().int().min(0).default(1e3) - }).optional(), - /** - * Health check interval for monitoring - */ - healthCheckInterval: external_exports.number().int().min(0).optional().describe("Health check interval in ms (0 = disabled)") -}).describe("Plugin initialization configuration"); -var PluginDependencyResolutionSchema3 = external_exports.object({ - /** - * Dependency resolution strategy - */ - strategy: external_exports.enum([ - "strict", - // Exact version match required - "compatible", - // Semver compatible versions (^) - "latest", - // Always use latest compatible - "pinned" - // Lock to specific version - ]).default("compatible"), - /** - * Peer dependency handling - */ - peerDependencies: external_exports.object({ - /** - * Whether to resolve peer dependencies - */ - resolve: external_exports.boolean().default(true), - /** - * Action on missing peer dependency - */ - onMissing: external_exports.enum(["error", "warn", "ignore"]).default("warn"), - /** - * Action on peer version mismatch - */ - onMismatch: external_exports.enum(["error", "warn", "ignore"]).default("warn") - }).optional(), - /** - * Optional dependency handling - */ - optionalDependencies: external_exports.object({ - /** - * Whether to attempt loading optional dependencies - */ - load: external_exports.boolean().default(true), - /** - * Action on optional dependency load failure - */ - onFailure: external_exports.enum(["warn", "ignore"]).default("warn") - }).optional(), - /** - * Conflict resolution - */ - conflictResolution: external_exports.enum([ - "fail", - // Fail on any version conflict - "latest", - // Use latest version - "oldest", - // Use oldest version - "manual" - // Require manual resolution - ]).default("latest"), - /** - * Circular dependency handling - */ - circularDependencies: external_exports.enum([ - "error", - // Throw error on circular dependency - "warn", - // Warn but continue - "allow" - // Allow circular dependencies - ]).default("warn") -}).describe("Plugin dependency resolution configuration"); -var PluginHotReloadSchema3 = external_exports.object({ - /** - * Enable hot reload - */ - enabled: external_exports.boolean().default(false), - /** - * Target environment for hot reload behavior - */ - environment: external_exports.enum([ - "development", - // Fast reload with relaxed safety (file watchers, no health validation) - "staging", - // Production-like reload with validation but relaxed rollback - "production" - // Full safety: health validation, rollback, connection draining - ]).default("development").describe("Target environment controlling safety level"), - /** - * Hot reload strategy - */ - strategy: external_exports.enum([ - "full", - // Full plugin reload (destroy and reinitialize) - "partial", - // Partial reload (update changed modules only) - "state-preserve" - // Preserve plugin state during reload - ]).default("full"), - /** - * Files to watch for changes - */ - watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to watch"), - /** - * Files to ignore - */ - ignorePatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns for files to ignore"), - /** - * Debounce delay in milliseconds - */ - debounceMs: external_exports.number().int().min(0).default(300), - /** - * Whether to preserve state during reload - */ - preserveState: external_exports.boolean().default(false), - /** - * State serialization - */ - stateSerialization: external_exports.object({ - enabled: external_exports.boolean().default(false), - /** - * Path to state serialization handler - */ - handler: external_exports.string().optional() - }).optional(), - /** - * Hooks for hot reload lifecycle - */ - hooks: external_exports.object({ - beforeReload: external_exports.string().optional().describe("Function to call before reload"), - afterReload: external_exports.string().optional().describe("Function to call after reload"), - onError: external_exports.string().optional().describe("Function to call on reload error") - }).optional(), - /** - * Production safety configuration - * Applied when environment is 'staging' or 'production' - */ - productionSafety: external_exports.object({ - /** - * Validate plugin health before completing reload - */ - healthValidation: external_exports.boolean().default(true).describe("Run health checks after reload before accepting traffic"), - /** - * Automatically rollback to previous version on reload failure - */ - rollbackOnFailure: external_exports.boolean().default(true).describe("Auto-rollback if reloaded plugin fails health check"), - /** - * Maximum time to wait for health validation after reload (ms) - */ - healthTimeout: external_exports.number().int().min(1e3).default(3e4).describe("Health check timeout after reload in ms"), - /** - * Drain active connections before reload - */ - drainConnections: external_exports.boolean().default(true).describe("Gracefully drain active requests before reloading"), - /** - * Maximum time to wait for connection draining (ms) - */ - drainTimeout: external_exports.number().int().min(0).default(15e3).describe("Max wait time for connection draining in ms"), - /** - * Maximum number of concurrent plugin reloads - */ - maxConcurrentReloads: external_exports.number().int().min(1).default(1).describe("Limit concurrent reloads to prevent system instability"), - /** - * Minimum interval between reloads of the same plugin (ms) - */ - minReloadInterval: external_exports.number().int().min(1e3).default(5e3).describe("Cooldown period between reloads of the same plugin") - }).optional() -}).describe("Plugin hot reload configuration"); -var PluginCachingSchema3 = external_exports.object({ - /** - * Enable caching - */ - enabled: external_exports.boolean().default(true), - /** - * Cache storage type - */ - storage: external_exports.enum([ - "memory", - // In-memory cache (fastest, not persistent) - "disk", - // Disk cache (persistent) - "indexeddb", - // Browser IndexedDB (persistent, browser only) - "hybrid" - // Memory + Disk hybrid - ]).default("memory"), - /** - * Cache key strategy - */ - keyStrategy: external_exports.enum([ - "version", - // Cache by plugin version - "hash", - // Cache by content hash - "timestamp" - // Cache by last modified timestamp - ]).default("version"), - /** - * Cache TTL in seconds - */ - ttl: external_exports.number().int().min(0).optional().describe("Time to live in seconds (0 = infinite)"), - /** - * Maximum cache size in MB - */ - maxSize: external_exports.number().int().min(1).optional().describe("Max cache size in MB"), - /** - * Cache invalidation triggers - */ - invalidateOn: external_exports.array(external_exports.enum([ - "version-change", - "dependency-change", - "manual", - "error" - ])).optional(), - /** - * Compression - */ - compression: external_exports.object({ - enabled: external_exports.boolean().default(false), - algorithm: external_exports.enum(["gzip", "brotli", "deflate"]).default("gzip") - }).optional() -}).describe("Plugin caching configuration"); -var PluginSandboxingSchema3 = external_exports.object({ - /** - * Enable sandboxing - */ - enabled: external_exports.boolean().default(false), - /** - * Isolation scope - which plugins are subject to sandboxing - */ - scope: external_exports.enum([ - "automation-only", - // Sandbox automation/scripting plugins only (current behavior) - "untrusted-only", - // Sandbox plugins below a trust threshold - "all-plugins" - // Sandbox all plugins (maximum isolation) - ]).default("automation-only").describe("Which plugins are subject to isolation"), - /** - * Sandbox isolation level - */ - isolationLevel: external_exports.enum([ - "none", - // No isolation - "process", - // Separate process (Node.js worker threads) - "vm", - // VM context isolation - "iframe", - // iframe isolation (browser) - "web-worker" - // Web Worker (browser) - ]).default("none"), - /** - * Allowed capabilities - */ - allowedCapabilities: external_exports.array(external_exports.string()).optional().describe("List of allowed capability IDs"), - /** - * Resource quotas - */ - resourceQuotas: external_exports.object({ - /** - * Maximum memory usage in MB - */ - maxMemoryMB: external_exports.number().int().min(1).optional(), - /** - * Maximum CPU time in milliseconds - */ - maxCpuTimeMs: external_exports.number().int().min(100).optional(), - /** - * Maximum number of file descriptors - */ - maxFileDescriptors: external_exports.number().int().min(1).optional(), - /** - * Maximum network bandwidth in KB/s - */ - maxNetworkKBps: external_exports.number().int().min(1).optional() - }).optional(), - /** - * Permissions - */ - permissions: external_exports.object({ - /** - * Allowed API access - */ - allowedAPIs: external_exports.array(external_exports.string()).optional(), - /** - * Allowed file system paths - */ - allowedPaths: external_exports.array(external_exports.string()).optional(), - /** - * Allowed network endpoints - */ - allowedEndpoints: external_exports.array(external_exports.string()).optional(), - /** - * Allowed environment variables - */ - allowedEnvVars: external_exports.array(external_exports.string()).optional() - }).optional(), - /** - * Inter-Plugin Communication (IPC) configuration - * Enables isolated plugins to communicate with the kernel and other plugins - */ - ipc: external_exports.object({ - /** - * Enable IPC for sandboxed plugins - */ - enabled: external_exports.boolean().default(true).describe("Allow sandboxed plugins to communicate via IPC"), - /** - * IPC transport mechanism - */ - transport: external_exports.enum([ - "message-port", - // MessagePort (worker threads / Web Workers) - "unix-socket", - // Unix domain sockets (process isolation) - "tcp", - // TCP sockets (container isolation) - "memory" - // Shared memory channel (in-process VM) - ]).default("message-port").describe("IPC transport for cross-boundary communication"), - /** - * Maximum message size in bytes - */ - maxMessageSize: external_exports.number().int().min(1024).default(1048576).describe("Maximum IPC message size in bytes (default 1MB)"), - /** - * Message timeout in milliseconds - */ - timeout: external_exports.number().int().min(100).default(3e4).describe("IPC message response timeout in ms"), - /** - * Allowed service calls through IPC - */ - allowedServices: external_exports.array(external_exports.string()).optional().describe("Service names the sandboxed plugin may invoke via IPC") - }).optional() -}).describe("Plugin sandboxing configuration"); -var PluginPerformanceMonitoringSchema3 = external_exports.object({ - /** - * Enable performance monitoring - */ - enabled: external_exports.boolean().default(false), - /** - * Metrics to collect - */ - metrics: external_exports.array(external_exports.enum([ - "load-time", - "init-time", - "memory-usage", - "cpu-usage", - "api-calls", - "error-rate", - "cache-hit-rate" - ])).optional(), - /** - * Sampling rate (0-1, where 1 = 100%) - */ - samplingRate: external_exports.number().min(0).max(1).default(1), - /** - * Reporting interval in seconds - */ - reportingInterval: external_exports.number().int().min(1).default(60), - /** - * Performance budget thresholds - */ - budgets: external_exports.object({ - /** - * Maximum load time in milliseconds - */ - maxLoadTimeMs: external_exports.number().int().min(0).optional(), - /** - * Maximum init time in milliseconds - */ - maxInitTimeMs: external_exports.number().int().min(0).optional(), - /** - * Maximum memory usage in MB - */ - maxMemoryMB: external_exports.number().int().min(0).optional() - }).optional(), - /** - * Action on budget violation - */ - onBudgetViolation: external_exports.enum(["warn", "error", "ignore"]).default("warn") -}).describe("Plugin performance monitoring configuration"); -var PluginLoadingConfigSchema3 = external_exports.object({ - /** - * Loading strategy - */ - strategy: PluginLoadingStrategySchema3.default("lazy"), - /** - * Preloading configuration - */ - preload: PluginPreloadConfigSchema3.optional(), - /** - * Code splitting configuration - */ - codeSplitting: PluginCodeSplittingSchema3.optional(), - /** - * Dynamic import configuration - */ - dynamicImport: PluginDynamicImportSchema3.optional(), - /** - * Initialization configuration - */ - initialization: PluginInitializationSchema3.optional(), - /** - * Dependency resolution configuration - */ - dependencyResolution: PluginDependencyResolutionSchema3.optional(), - /** - * Hot reload configuration (development and production) - */ - hotReload: PluginHotReloadSchema3.optional(), - /** - * Caching configuration - */ - caching: PluginCachingSchema3.optional(), - /** - * Sandboxing configuration - */ - sandboxing: PluginSandboxingSchema3.optional(), - /** - * Performance monitoring - */ - monitoring: PluginPerformanceMonitoringSchema3.optional() -}).describe("Complete plugin loading configuration"); -var PluginLoadingEventSchema2 = external_exports.object({ - /** - * Event type - */ - type: external_exports.enum([ - "load-started", - "load-completed", - "load-failed", - "init-started", - "init-completed", - "init-failed", - "preload-started", - "preload-completed", - "cache-hit", - "cache-miss", - "hot-reload", - "dynamic-load", - // Plugin loaded at runtime - "dynamic-unload", - // Plugin unloaded at runtime - "dynamic-discover" - // Plugin discovered via registry - ]), - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Timestamp - */ - timestamp: external_exports.number().int().min(0), - /** - * Duration in milliseconds - */ - durationMs: external_exports.number().int().min(0).optional(), - /** - * Additional metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Error if event represents a failure - */ - error: external_exports.object({ - message: external_exports.string(), - code: external_exports.string().optional(), - stack: external_exports.string().optional() - }).optional() -}).describe("Plugin loading lifecycle event"); -var PluginLoadingStateSchema2 = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Current state - */ - state: external_exports.enum([ - "pending", - // Not yet loaded - "loading", - // Currently loading - "loaded", - // Code loaded, not initialized - "initializing", - // Currently initializing - "ready", - // Fully initialized and ready - "failed", - // Failed to load or initialize - "reloading", - // Hot reloading in progress - "unloading", - // Being unloaded at runtime - "unloaded" - // Successfully unloaded (dynamic loading) - ]), - /** - * Load progress (0-100) - */ - progress: external_exports.number().min(0).max(100).default(0), - /** - * Loading start time - */ - startedAt: external_exports.number().int().min(0).optional(), - /** - * Loading completion time - */ - completedAt: external_exports.number().int().min(0).optional(), - /** - * Last error - */ - lastError: external_exports.string().optional(), - /** - * Retry count - */ - retryCount: external_exports.number().int().min(0).default(0) -}).describe("Plugin loading state"); -var PluginContextSchema2 = external_exports.object({ - ql: external_exports.object({ - object: external_exports.function().describe("Get object handle for method chaining"), - query: external_exports.function().describe("Execute a query") - }).passthrough().describe("ObjectQL Engine Interface"), - os: external_exports.object({ - getCurrentUser: external_exports.function().describe("Get the current authenticated user"), - getConfig: external_exports.function().describe("Get platform configuration") - }).passthrough().describe("ObjectStack Kernel Interface"), - logger: external_exports.object({ - debug: external_exports.function().describe("Log debug message"), - info: external_exports.function().describe("Log info message"), - warn: external_exports.function().describe("Log warning message"), - error: external_exports.function().describe("Log error message") - }).passthrough().describe("Logger Interface"), - storage: external_exports.object({ - get: external_exports.function().describe("Get a value from storage"), - set: external_exports.function().describe("Set a value in storage"), - delete: external_exports.function().describe("Delete a value from storage") - }).passthrough().describe("Storage Interface"), - i18n: external_exports.object({ - t: external_exports.function().describe("Translate a key"), - getLocale: external_exports.function().describe("Get current locale") - }).passthrough().describe("Internationalization Interface"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()), - events: external_exports.record(external_exports.string(), external_exports.unknown()), - app: external_exports.object({ - router: external_exports.object({ - get: external_exports.function().describe("Register GET route handler"), - post: external_exports.function().describe("Register POST route handler"), - use: external_exports.function().describe("Register middleware") - }).passthrough() - }).passthrough().describe("App Framework Interface"), - drivers: external_exports.object({ - register: external_exports.function().describe("Register a driver") - }).passthrough().describe("Driver Registry") -}); -var UpgradeContextSchema2 = external_exports.object({ - /** Version before upgrade */ - previousVersion: external_exports.string().describe("Version before upgrade"), - /** Version after upgrade */ - newVersion: external_exports.string().describe("Version after upgrade"), - /** Whether this is a major version bump */ - isMajorUpgrade: external_exports.boolean().describe("Whether this is a major version bump"), - /** Metadata snapshot before upgrade (for migration logic) */ - previousMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Metadata snapshot before upgrade") -}).describe("Version migration context for onUpgrade hook"); -var PluginLifecycleSchema3 = external_exports.object({ - onInstall: external_exports.function().optional().describe("Called when plugin is installed"), - onEnable: external_exports.function().optional().describe("Called when plugin is enabled"), - onDisable: external_exports.function().optional().describe("Called when plugin is disabled"), - onUninstall: external_exports.function().optional().describe("Called when plugin is uninstalled"), - onUpgrade: external_exports.function().optional().describe("Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade") -}); -var CORE_PLUGIN_TYPES3 = [ - "ui", - // Frontend: Serves static assets/SPA (e.g. Console, Studio) - "driver", - // Connectivity: Database or Storage adapters (e.g. SQL, S3) - "server", - // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL) - "app", - // Business: Vertical Solution Bundle (Metadata + Logic) - "theme", - // Appearance: UI Overrides & CSS Variables - "agent", - // AI: Autonomous Agent & Tool Definitions - "objectql" - // Core: ObjectQL Engine Data Provider -]; -var PluginSchema2 = PluginLifecycleSchema3.extend({ - id: external_exports.string().min(1).optional().describe("Unique Plugin ID (e.g. com.example.crm)"), - type: external_exports.enum([ - "standard", - // Default: General purpose backend logic (Service, Hook, etc.) - ...CORE_PLUGIN_TYPES3 - ]).default("standard").optional().describe("Plugin Type categorization for runtime behavior"), - staticPath: external_exports.string().optional().describe('Absolute path to static assets (Required for type="ui-plugin")'), - slug: external_exports.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type="ui-plugin")'), - default: external_exports.boolean().optional().describe('Serve at root path (Only one "ui-plugin" can be default)'), - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic Version"), - description: external_exports.string().optional(), - author: external_exports.string().optional(), - homepage: external_exports.string().url().optional() -}); -var ManifestSchema3 = external_exports.object({ - /** - * Unique package identifier using reverse domain notation. - * Must be unique across the entire ecosystem. - * - * @example "com.steedos.crm" - * @example "org.apache.superset" - */ - id: external_exports.string().describe("Unique package identifier (reverse domain style)"), - /** - * Short namespace identifier for metadata scoping. - * Used as a prefix for objects and other metadata to prevent naming collisions - * across packages from different vendors. - * - * Rules: - * - 2-20 characters, lowercase letters, digits, and underscores only. - * - Must be unique within a running instance. - * - Platform-reserved namespaces (no prefix applied): "base", "system". - * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator). - * - * @example "crm" → objects become crm__account, crm__deal - * @example "todo" → objects become todo__task - * @example "base" → objects keep short name (platform reserved) - */ - namespace: external_exports.string().regex(/^[a-z][a-z0-9_]{1,19}$/, "Namespace must be 2-20 chars, lowercase alphanumeric + underscore").optional().describe('Short namespace identifier for metadata scoping (e.g. "crm", "todo")'), - /** - * Package version following semantic versioning (major.minor.patch). - * - * @example "1.0.0" - * @example "2.1.0-beta.1" - */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Package version (semantic versioning)"), - /** - * Type of the package in the ObjectStack ecosystem. - * - plugin: General-purpose functionality extension (Runtime: standard) - * - app: Business application package - * - driver: Connectivity adapter - * - server: Protocol gateway (Hono, GraphQL) - * - ui: Frontend package (Static/SPA) - * - theme: UI Theme - * - agent: AI Agent - * - module: Reusable code library/shared module - * - objectql: Core engine - * - adapter: Host adapter (Express, Fastify) - */ - type: external_exports.enum([ - "plugin", - ...CORE_PLUGIN_TYPES3, - "module", - "gateway", - // Deprecated: use 'server' - "adapter" - ]).describe("Type of package"), - /** - * Human-readable name of the package. - * Displayed in the UI for users. - * - * @example "Project Management" - */ - name: external_exports.string().describe("Human-readable package name"), - /** - * Brief description of the package functionality. - * Displayed in the marketplace and plugin manager. - */ - description: external_exports.string().optional().describe("Package description"), - /** - * Array of permission strings that the package requires. - * These form the "Scope" requested by the package at installation. - * - * @example ["system.user.read", "system.data.write"] - */ - permissions: external_exports.array(external_exports.string()).optional().describe("Array of required permission strings"), - /** - * Glob patterns specifying ObjectQL schemas files. - * Matches `*.object.yml` or `*.object.ts` files to load business objects. - * - * @example ["./src/objects/*.object.yml"] - */ - objects: external_exports.array(external_exports.string()).optional().describe("Glob patterns for ObjectQL schemas files"), - /** - * Defines system level DataSources. - * Matches `*.datasource.yml` files. - * - * @example ["./src/datasources/*.datasource.mongo.yml"] - */ - datasources: external_exports.array(external_exports.string()).optional().describe("Glob patterns for Datasource definitions"), - /** - * Package Dependencies. - * Map of package IDs to version requirements. - * - * @example { "@steedos/plugin-auth": "^2.0.0" } - */ - dependencies: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Package dependencies"), - /** - * Plugin Configuration Schema. - * Defines the settings this plugin exposes to the user via UI/ENV. - * Uses a simplified JSON Schema format. - * - * @example - * { - * "title": "Stripe Config", - * "properties": { - * "apiKey": { "type": "string", "secret": true }, - * "currency": { "type": "string", "default": "USD" } - * } - * } - */ - configuration: external_exports.object({ - title: external_exports.string().optional(), - properties: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["string", "number", "boolean", "array", "object"]).describe("Data type of the setting"), - default: external_exports.unknown().optional().describe("Default value"), - description: external_exports.string().optional().describe("Tooltip description"), - required: external_exports.boolean().optional().describe("Is this setting required?"), - secret: external_exports.boolean().optional().describe("If true, value is encrypted/masked (e.g. API Keys)"), - enum: external_exports.array(external_exports.string()).optional().describe("Allowed values for select inputs") - })).describe("Map of configuration keys to their definitions") - }).optional().describe("Plugin configuration settings"), - /** - * Contribution Points (VS Code Style). - * formalized way to extend the platform capabilities. - */ - contributes: external_exports.object({ - /** - * Register new Metadata Kinds (CRDs). - * Enables the system to parse and validate new file types. - * Example: Registering a BI plugin to handle *.report.ts - */ - kinds: external_exports.array(external_exports.object({ - id: external_exports.string().describe('The generic identifier of the kind (e.g., "sys.bi.report")'), - globs: external_exports.array(external_exports.string()).describe('File patterns to watch (e.g., ["**/*.report.ts"])'), - description: external_exports.string().optional().describe("Description of what this kind represents") - })).optional().describe("New Metadata Types to recognize"), - /** - * Register System Hooks. - * Declares that this plugin listens to specific system events. - */ - events: external_exports.array(external_exports.string()).optional().describe("Events this plugin listens to"), - /** - * Register UI Menus. - */ - menus: external_exports.record(external_exports.string(), external_exports.array(external_exports.object({ - id: external_exports.string(), - label: external_exports.string(), - command: external_exports.string().optional() - }))).optional().describe("UI Menu contributions"), - /** - * Register Custom Themes. - */ - themes: external_exports.array(external_exports.object({ - id: external_exports.string(), - label: external_exports.string(), - path: external_exports.string() - })).optional().describe("Theme contributions"), - /** - * Register Translations. - * Path to translation files (e.g. "locales/en.json"). - */ - translations: external_exports.array(external_exports.object({ - locale: external_exports.string(), - path: external_exports.string() - })).optional().describe("Translation resources"), - /** - * Register Server Actions. - * Invocable functions exposed to Flows or API. - */ - actions: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Unique action name"), - label: external_exports.string().optional(), - description: external_exports.string().optional(), - input: external_exports.unknown().optional().describe("Input validation schema"), - output: external_exports.unknown().optional().describe("Output schema") - })).optional().describe("Exposed server actions"), - /** - * Register Storage Drivers. - * Enables connecting to new types of datasources. - */ - drivers: external_exports.array(external_exports.object({ - id: external_exports.string().describe('Driver unique identifier (e.g. "postgres", "mongo")'), - label: external_exports.string().describe("Human readable name"), - description: external_exports.string().optional() - })).optional().describe("Driver contributions"), - /** - * Register Custom Field Types. - * Extends the data model with new widget types. - */ - fieldTypes: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Unique field type name (e.g. "vector")'), - label: external_exports.string().describe("Display label"), - description: external_exports.string().optional() - })).optional().describe("Field Type contributions"), - /** - * Register Custom Query Operators/Functions. - * Extends ObjectQL with new functions (e.g. distance()). - */ - functions: external_exports.array(external_exports.object({ - name: external_exports.string().describe('Function name (e.g. "distance")'), - description: external_exports.string().optional(), - args: external_exports.array(external_exports.string()).optional().describe("Argument types"), - returnType: external_exports.string().optional() - })).optional().describe("Query Function contributions"), - /** - * Register API Route Namespaces. - * Declares the API endpoints this plugin provides to the HttpDispatcher. - * The kernel routes matching prefixes to this plugin's handler. - * - * @example - * routes: [ - * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] } - * ] - */ - routes: external_exports.array(external_exports.object({ - /** URL path prefix (e.g. "/api/v1/ai") */ - prefix: external_exports.string().regex(/^\//).describe("API path prefix"), - /** Service name this plugin provides */ - service: external_exports.string().describe("Service name this plugin provides"), - /** Protocol method names implemented */ - methods: external_exports.array(external_exports.string()).optional().describe('Protocol method names implemented (e.g. ["aiNlq", "aiChat"])') - })).optional().describe("API route contributions to HttpDispatcher"), - /** - * Register CLI Commands. - * Allows plugins to extend the ObjectStack CLI with custom commands. - * Each command entry declares metadata; the actual Commander.js command - * is resolved at runtime by importing the plugin's module. - * - * The plugin package must export a `commands` array of Commander.js `Command` instances - * from its main entry point or from the path specified in `module`. - * - * @example - * ```yaml - * commands: - * - name: marketplace - * description: "Manage marketplace apps" - * module: "./cli" # optional, defaults to package main - * - name: deploy - * description: "Deploy to cloud" - * ``` - */ - commands: external_exports.array(external_exports.object({ - /** CLI command name (e.g., "marketplace", "deploy"). Must be a valid CLI identifier. */ - name: external_exports.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens").describe("CLI command name"), - /** Brief description shown in `os --help` */ - description: external_exports.string().optional().describe("Command description for help text"), - /** - * Optional module path (relative to package root) that exports the Commander.js commands. - * If omitted, the CLI will import from the package's main entry point. - * The module must export a `commands` array of Commander.js `Command` instances, - * or a single `Command` instance as default export. - */ - module: external_exports.string().optional().describe("Module path exporting Commander.js commands") - })).optional().describe("CLI command contributions") - }).optional().describe("Platform contributions"), - /** - * Initial data seeding configuration. - * Defines default records to be inserted when the package is installed. - * - * Uses the standard DatasetSchema which supports idempotent upsert via - * `externalId`, environment scoping via `env`, and multiple conflict - * resolution modes. - * - * @deprecated Prefer using the top-level `data` field on the Stack Definition - * (defineStack({ data: [...] })) for better visibility and metadata registration. - * This field is retained for backward compatibility with manifest-only packages. - */ - data: external_exports.array(DatasetSchema4).optional().describe("Initial seed data (prefer top-level data field)"), - /** - * Plugin Capability Manifest. - * Declares protocols implemented, interfaces provided, dependencies, and extension points. - * This enables plugin interoperability and automatic discovery. - */ - capabilities: PluginCapabilityManifestSchema3.optional().describe("Plugin capability declarations for interoperability"), - /** - * Extension points contributed by this package. - * Allows packages to extend UI components, add functionality, etc. - */ - extensions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Extension points and contributions"), - /** - * Plugin Loading Configuration. - * Configures how the plugin is loaded, initialized, and managed at runtime. - * Includes strategies for lazy loading, code splitting, caching, and hot reload. - */ - loading: PluginLoadingConfigSchema3.optional().describe("Plugin loading and runtime behavior configuration"), - /** - * Platform Compatibility Requirements. - * Specifies the minimum ObjectStack platform version required to run this package. - * Used at install time to prevent incompatible packages from being installed. - * - * @example - * ```yaml - * engine: - * objectstack: ">=3.0.0" - * ``` - */ - engine: external_exports.object({ - /** ObjectStack platform version requirement (SemVer range) */ - objectstack: external_exports.string().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe('ObjectStack platform version requirement (SemVer range, e.g. ">=3.0.0")') - }).optional().describe("Platform compatibility requirements") -}); -var CustomizationOriginSchema2 = external_exports.enum([ - "package", - // Delivered by a plugin package (system layer, read-only) - "admin", - // Created/modified by platform admin via UI - "user", - // Created/modified by end user via UI - "migration", - // Created during data migration - "api" - // Created via API -]); -var FieldChangeSchema3 = external_exports.object({ - /** JSON path to the changed field (e.g. "fields.status.label") */ - path: external_exports.string().describe("JSON path to the changed field"), - /** Original value from the package (for diff/rollback) */ - originalValue: external_exports.unknown().optional().describe("Original value from the package"), - /** Current customized value */ - currentValue: external_exports.unknown().describe("Current customized value"), - /** Who made this change */ - changedBy: external_exports.string().optional().describe("User or admin who made this change"), - /** When this change was made */ - changedAt: external_exports.string().datetime().optional().describe("Timestamp of the change") -}); -var MetadataOverlaySchema3 = external_exports.object({ - /** Primary key */ - id: external_exports.string().describe("Overlay record ID (UUID)"), - /** The metadata type being customized (e.g. "object", "view", "flow") */ - baseType: external_exports.string().describe("Metadata type being customized"), - /** The metadata name being customized (e.g. "crm__account") */ - baseName: external_exports.string().describe("Metadata name being customized"), - /** Package that owns the base metadata (null for platform-created metadata) */ - packageId: external_exports.string().optional().describe("Package ID that delivered the base metadata"), - /** Package version when the customization was made (for upgrade diffing) */ - packageVersion: external_exports.string().optional().describe("Package version when overlay was created"), - /** Customization scope */ - scope: external_exports.enum(["platform", "user"]).default("platform").describe("Customization scope (platform=admin, user=personal)"), - /** Tenant ID for multi-tenant isolation */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** Owner user ID (for user-scope overlays) */ - owner: external_exports.string().optional().describe("Owner user ID for user-scope overlays"), - /** - * The overlay payload. - * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396). - * - To modify a field: include the field with its new value - * - To delete a field: set its value to null - * - Omitted fields remain unchanged from base - */ - patch: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Merge Patch payload (changed fields only)"), - /** - * Detailed change tracking for each modified field. - * Enables field-level conflict detection during upgrades. - */ - changes: external_exports.array(FieldChangeSchema3).optional().describe("Field-level change tracking for conflict detection"), - /** Whether this overlay is currently active */ - active: external_exports.boolean().default(true).describe("Whether this overlay is active"), - /** Audit timestamps */ - createdAt: external_exports.string().datetime().optional(), - createdBy: external_exports.string().optional(), - updatedAt: external_exports.string().datetime().optional(), - updatedBy: external_exports.string().optional() -}); -var MergeConflictSchema3 = external_exports.object({ - /** JSON path to the conflicting field */ - path: external_exports.string().describe("JSON path to the conflicting field"), - /** Value in the old package version */ - baseValue: external_exports.unknown().describe("Value in the old package version"), - /** Value in the new package version */ - incomingValue: external_exports.unknown().describe("Value in the new package version"), - /** Customer's customized value */ - customValue: external_exports.unknown().describe("Customer customized value"), - /** Suggested resolution strategy */ - suggestedResolution: external_exports.enum([ - "keep-custom", - // Keep customer's customization - "accept-incoming", - // Accept package update - "manual" - // Requires manual resolution - ]).describe("Suggested resolution strategy"), - /** Reason for the suggested resolution */ - reason: external_exports.string().optional().describe("Explanation for the suggested resolution") -}); -var MergeStrategyConfigSchema3 = external_exports.object({ - /** Default strategy when no field-level rule matches */ - defaultStrategy: external_exports.enum([ - "keep-custom", - // Preserve all customer customizations (safe) - "accept-incoming", - // Accept all package updates (overwrite) - "three-way-merge" - // Intelligent 3-way merge with conflict detection - ]).default("three-way-merge").describe("Default merge strategy"), - /** - * Field paths that should always accept incoming package updates. - * Use for fields that the package vendor considers "owned" and should not be customized. - * @example ["fields.*.type", "triggers.*"] - */ - alwaysAcceptIncoming: external_exports.array(external_exports.string()).optional().describe("Field paths that always accept package updates"), - /** - * Field paths where customer customizations always win. - * Use for UI-facing fields like labels, descriptions, help text. - * @example ["fields.*.label", "fields.*.helpText", "description"] - */ - alwaysKeepCustom: external_exports.array(external_exports.string()).optional().describe("Field paths where customer customizations always win"), - /** Whether to automatically resolve non-conflicting changes */ - autoResolveNonConflicting: external_exports.boolean().default(true).describe("Auto-resolve changes that do not conflict") -}); -var MergeResultSchema2 = external_exports.object({ - /** Whether the merge completed successfully (no unresolved conflicts) */ - success: external_exports.boolean().describe("Whether merge completed without unresolved conflicts"), - /** The merged metadata payload */ - mergedMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Merged metadata result"), - /** Updated overlay with remaining customizations */ - updatedOverlay: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated overlay after merge"), - /** List of conflicts that require manual resolution */ - conflicts: external_exports.array(MergeConflictSchema3).optional().describe("Unresolved merge conflicts"), - /** Summary of automatically resolved changes */ - autoResolved: external_exports.array(external_exports.object({ - path: external_exports.string(), - resolution: external_exports.string(), - description: external_exports.string().optional() - })).optional().describe("Summary of auto-resolved changes"), - /** Statistics */ - stats: external_exports.object({ - totalFields: external_exports.number().int().min(0).describe("Total fields evaluated"), - unchanged: external_exports.number().int().min(0).describe("Fields with no changes"), - autoResolved: external_exports.number().int().min(0).describe("Fields auto-resolved"), - conflicts: external_exports.number().int().min(0).describe("Fields with conflicts") - }).optional() -}); -var CustomizationPolicySchema3 = external_exports.object({ - /** Metadata type this policy applies to */ - metadataType: external_exports.string().describe('Metadata type (e.g. "object", "view")'), - /** Whether customization is allowed at all for this type */ - allowCustomization: external_exports.boolean().default(true), - /** - * Field paths that are locked (cannot be customized). - * @example ["name", "type", "fields.*.type"] - */ - lockedFields: external_exports.array(external_exports.string()).optional().describe("Field paths that cannot be customized"), - /** - * Field paths that are customizable. - * If specified, only these fields can be customized (whitelist mode). - * @example ["label", "description", "fields.*.label", "fields.*.helpText"] - */ - customizableFields: external_exports.array(external_exports.string()).optional().describe("Field paths that can be customized (whitelist)"), - /** - * Whether users can add new fields to package objects. - * When true, admins can extend package objects with custom fields. - */ - allowAddFields: external_exports.boolean().default(true).describe("Whether admins can add new fields to package objects"), - /** - * Whether users can delete package-delivered fields. - * Typically false — fields can only be hidden, not deleted. - */ - allowDeleteFields: external_exports.boolean().default(false).describe("Whether admins can delete package-delivered fields") -}); -var MetadataFormatSchema32 = external_exports.enum(["json", "yaml", "typescript", "javascript"]); -var MetadataStatsSchema22 = external_exports.object({ - /** - * Size of the metadata file in bytes - */ - size: external_exports.number().int().min(0).describe("File size in bytes"), - /** - * Last modification timestamp - */ - modifiedAt: external_exports.string().datetime().describe("Last modified date"), - /** - * ETag for cache validation - * Used for conditional requests (If-None-Match header) - */ - etag: external_exports.string().describe("Entity tag for cache validation"), - /** - * Serialization format - */ - format: MetadataFormatSchema32.describe("Serialization format"), - /** - * Full file path (if applicable) - */ - path: external_exports.string().optional().describe("File system path"), - /** - * Additional metadata provider-specific properties - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific metadata") -}); -var MetadataLoadOptionsSchema22 = external_exports.object({ - /** - * Glob patterns to match files - * Example: ["**\/*.object.ts", "**\/*.object.json"] - */ - patterns: external_exports.array(external_exports.string()).optional().describe("File glob patterns"), - /** - * If-None-Match header for conditional loading - * Only load if ETag doesn't match - */ - ifNoneMatch: external_exports.string().optional().describe("ETag for conditional request"), - /** - * If-Modified-Since header for conditional loading - */ - ifModifiedSince: external_exports.string().datetime().optional().describe("Only load if modified after this date"), - /** - * Whether to validate against Zod schema - */ - validate: external_exports.boolean().default(true).describe("Validate against schema"), - /** - * Whether to use cache if available - */ - useCache: external_exports.boolean().default(true).describe("Enable caching"), - /** - * Filter function (serialized as string) - * Example: "(item) => item.name.startsWith('sys_')" - */ - filter: external_exports.string().optional().describe("Filter predicate as string"), - /** - * Maximum number of items to load - */ - limit: external_exports.number().int().min(1).optional().describe("Maximum items to load"), - /** - * Recursively search subdirectories - */ - recursive: external_exports.boolean().default(true).describe("Search subdirectories") -}); -var MetadataSaveOptionsSchema22 = external_exports.object({ - /** - * Serialization format - */ - format: MetadataFormatSchema32.default("typescript").describe("Output format"), - /** - * Prettify output (formatted with indentation) - */ - prettify: external_exports.boolean().default(true).describe("Format with indentation"), - /** - * Indentation size (spaces) - */ - indent: external_exports.number().int().min(0).max(8).default(2).describe("Indentation spaces"), - /** - * Sort object keys alphabetically - */ - sortKeys: external_exports.boolean().default(false).describe("Sort object keys"), - /** - * Include default values in output - */ - includeDefaults: external_exports.boolean().default(false).describe("Include default values"), - /** - * Create backup before overwriting - */ - backup: external_exports.boolean().default(false).describe("Create backup file"), - /** - * Overwrite if exists - */ - overwrite: external_exports.boolean().default(true).describe("Overwrite existing file"), - /** - * Atomic write (write to temp file, then rename) - */ - atomic: external_exports.boolean().default(true).describe("Use atomic write operation"), - /** - * Custom file path (overrides default location) - */ - path: external_exports.string().optional().describe("Custom output path") -}); -var MetadataExportOptionsSchema22 = external_exports.object({ - /** - * Output file path - */ - output: external_exports.string().describe("Output file path"), - /** - * Export format - */ - format: MetadataFormatSchema32.default("json").describe("Export format"), - /** - * Filter predicate as string - */ - filter: external_exports.string().optional().describe("Filter items to export"), - /** - * Include statistics in export - */ - includeStats: external_exports.boolean().default(false).describe("Include metadata statistics"), - /** - * Compress output - */ - compress: external_exports.boolean().default(false).describe("Compress output (gzip)"), - /** - * Pretty print output - */ - prettify: external_exports.boolean().default(true).describe("Pretty print output") -}); -var MetadataImportOptionsSchema22 = external_exports.object({ - /** - * Conflict resolution strategy - */ - conflictResolution: external_exports.enum(["skip", "overwrite", "merge", "fail"]).default("merge").describe("How to handle existing items"), - /** - * Validate items against schema - */ - validate: external_exports.boolean().default(true).describe("Validate before import"), - /** - * Dry run (don't actually save) - */ - dryRun: external_exports.boolean().default(false).describe("Simulate import without saving"), - /** - * Continue on errors - */ - continueOnError: external_exports.boolean().default(false).describe("Continue if validation fails"), - /** - * Transform function (as string) - * Example: "(item) => ({ ...item, imported: true })" - */ - transform: external_exports.string().optional().describe("Transform items before import") -}); -var MetadataLoadResultSchema22 = external_exports.object({ - /** - * Loaded data - */ - data: external_exports.unknown().nullable().describe("Loaded metadata"), - /** - * Whether data came from cache (304 Not Modified) - */ - fromCache: external_exports.boolean().default(false).describe("Loaded from cache"), - /** - * Not modified (conditional request matched) - */ - notModified: external_exports.boolean().default(false).describe("Not modified since last request"), - /** - * ETag of loaded data - */ - etag: external_exports.string().optional().describe("Entity tag"), - /** - * Statistics about loaded data - */ - stats: MetadataStatsSchema22.optional().describe("Metadata statistics"), - /** - * Load time in milliseconds - */ - loadTime: external_exports.number().min(0).optional().describe("Load duration in ms") -}); -var MetadataSaveResultSchema22 = external_exports.object({ - /** - * Whether save was successful - */ - success: external_exports.boolean().describe("Save successful"), - /** - * Path where file was saved - */ - path: external_exports.string().describe("Output path"), - /** - * Generated ETag - */ - etag: external_exports.string().optional().describe("Generated entity tag"), - /** - * File size in bytes - */ - size: external_exports.number().int().min(0).optional().describe("File size"), - /** - * Save time in milliseconds - */ - saveTime: external_exports.number().min(0).optional().describe("Save duration in ms"), - /** - * Backup path (if created) - */ - backupPath: external_exports.string().optional().describe("Backup file path") -}); -var MetadataWatchEventSchema22 = external_exports.object({ - /** - * Event type - */ - type: external_exports.enum(["added", "changed", "deleted"]).describe("Event type"), - /** - * Metadata type (e.g., 'object', 'view', 'app') - */ - metadataType: external_exports.string().describe("Type of metadata"), - /** - * Item name/identifier - */ - name: external_exports.string().describe("Item identifier"), - /** - * Full file path - */ - path: external_exports.string().describe("File path"), - /** - * Loaded item data (for added/changed events) - */ - data: external_exports.unknown().optional().describe("Item data"), - /** - * Timestamp - */ - timestamp: external_exports.string().datetime().describe("Event timestamp") -}); -var MetadataCollectionInfoSchema22 = external_exports.object({ - /** - * Collection type (e.g., 'object', 'view', 'app') - */ - type: external_exports.string().describe("Collection type"), - /** - * Total items in collection - */ - count: external_exports.number().int().min(0).describe("Number of items"), - /** - * Formats found in collection - */ - formats: external_exports.array(MetadataFormatSchema32).describe("Formats in collection"), - /** - * Total size in bytes - */ - totalSize: external_exports.number().int().min(0).optional().describe("Total size in bytes"), - /** - * Last modified timestamp - */ - lastModified: external_exports.string().datetime().optional().describe("Last modification date"), - /** - * Collection location (path or URL) - */ - location: external_exports.string().optional().describe("Collection location") -}); -var MetadataLoaderContractSchema22 = external_exports.object({ - /** - * Loader name/identifier - */ - name: external_exports.string().describe("Loader identifier"), - /** - * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:') - */ - protocol: external_exports.enum(["file:", "http:", "s3:", "datasource:", "memory:"]).describe("Protocol identifier"), - /** - * Detailed capabilities - */ - capabilities: external_exports.object({ - read: external_exports.boolean().default(true), - write: external_exports.boolean().default(false), - watch: external_exports.boolean().default(false), - list: external_exports.boolean().default(true) - }).describe("Loader capabilities"), - /** - * Supported formats - */ - supportedFormats: external_exports.array(MetadataFormatSchema32).describe("Supported formats"), - /** - * Whether loader supports watching for changes - */ - supportsWatch: external_exports.boolean().default(false).describe("Supports file watching"), - /** - * Whether loader supports saving - */ - supportsWrite: external_exports.boolean().default(true).describe("Supports write operations"), - /** - * Whether loader supports caching - */ - supportsCache: external_exports.boolean().default(true).describe("Supports caching") -}); -var MetadataFallbackStrategySchema22 = external_exports.enum([ - "filesystem", - // Fall back to filesystem-based loading - "memory", - // Fall back to in-memory storage - "none" - // No fallback — fail immediately -]); -var MetadataManagerConfigSchema22 = external_exports.object({ - /** - * Datasource Name Reference - * References a DatasourceSchema.name (e.g. 'default'). - * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver. - */ - datasource: external_exports.string().optional().describe("Datasource name reference for database persistence"), - /** - * Metadata Table Name - * The database table used for metadata storage when datasource is configured. - */ - tableName: external_exports.string().default("sys_metadata").describe("Database table name for metadata storage"), - /** - * Fallback Strategy - * Determines behavior when the primary datasource is unavailable. - */ - fallback: MetadataFallbackStrategySchema22.default("none").describe("Fallback strategy when datasource is unavailable"), - /** - * Root directory for metadata (for filesystem loaders) - */ - rootDir: external_exports.string().optional().describe("Root directory path"), - /** - * Enabled serialization formats - */ - formats: external_exports.array(MetadataFormatSchema32).default(["typescript", "json", "yaml"]).describe("Enabled formats"), - /** - * Cache configuration - */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable caching"), - ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), - maxSize: external_exports.number().int().min(0).optional().describe("Max cache size in bytes") - }).optional().describe("Cache settings"), - /** - * Watch for file changes - */ - watch: external_exports.boolean().default(false).describe("Enable file watching"), - /** - * Watch options - */ - watchOptions: external_exports.object({ - ignored: external_exports.array(external_exports.string()).optional().describe("Patterns to ignore"), - persistent: external_exports.boolean().default(true).describe("Keep process running"), - ignoreInitial: external_exports.boolean().default(true).describe("Ignore initial add events") - }).optional().describe("File watcher options"), - /** - * Validation settings - */ - validation: external_exports.object({ - strict: external_exports.boolean().default(true).describe("Strict validation"), - throwOnError: external_exports.boolean().default(true).describe("Throw on validation error") - }).optional().describe("Validation settings"), - /** - * Loader-specific options - */ - loaderOptions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Loader-specific configuration") -}); -var MetadataTypeSchema3 = external_exports.enum([ - // Data Protocol - "object", - // Business entity definition (ObjectSchema) - "field", - // Standalone field definition (FieldSchema) - "trigger", - // Data-layer event triggers (TriggerSchema) - "validation", - // Validation rules (ValidationSchema) - "hook", - // Data hooks (HookSchema) - // UI Protocol - "view", - // List/form views (ViewSchema) - "page", - // Standalone pages (PageSchema) - "dashboard", - // Dashboard layouts (DashboardSchema) - "app", - // Application shell (AppSchema) - "action", - // UI/Server actions (ActionSchema) - "report", - // Report definitions (ReportSchema) - // Automation Protocol - "flow", - // Visual logic flows (FlowSchema) - "workflow", - // State machines (WorkflowSchema) - "approval", - // Approval processes (ApprovalSchema) - // System Protocol - "datasource", - // Data connections (DatasourceSchema) - "translation", - // i18n resources (TranslationSchema) - "router", - // API routes - "function", - // Serverless functions - "service", - // Service definitions - // Security Protocol - "permission", - // Permission sets (PermissionSetSchema) - "profile", - // User profiles (ProfileSchema) - "role", - // Security roles - // AI Protocol - "agent", - // AI agent definitions (AgentSchema) - "tool", - // AI tool definitions (ToolSchema) - "skill" - // AI skill definitions (SkillSchema) -]); -var MetadataTypeRegistryEntrySchema3 = external_exports.object({ - /** Metadata type identifier (e.g., 'object', 'view') */ - type: MetadataTypeSchema3.describe("Metadata type identifier"), - /** Human-readable label */ - label: external_exports.string().describe("Display label for the metadata type"), - /** Brief description */ - description: external_exports.string().optional().describe("Description of the metadata type"), - /** - * File glob patterns for this type. - * Used to discover metadata files on disk. - * @example ["**\/*.object.ts", "**\/*.object.yml"] - */ - filePatterns: external_exports.array(external_exports.string()).describe("Glob patterns to discover files of this type"), - /** - * Whether this type supports the customization overlay system. - * When true, platform/user overlays can be applied on top of package-delivered metadata. - */ - supportsOverlay: external_exports.boolean().default(true).describe("Whether overlay customization is supported"), - /** - * Whether metadata of this type can be created at runtime via API. - * Some types (e.g., 'object') may be restricted to deployment-only. - */ - allowRuntimeCreate: external_exports.boolean().default(true).describe("Allow runtime creation via API"), - /** - * Whether this type supports versioning. - * When true, changes are tracked with version history. - */ - supportsVersioning: external_exports.boolean().default(false).describe("Whether version history is tracked"), - /** - * Priority order for loading (lower = earlier). - * Objects load before views, views before dashboards. - */ - loadOrder: external_exports.number().int().min(0).default(100).describe("Loading priority (lower = earlier)"), - /** The domain this type belongs to */ - domain: external_exports.enum(["data", "ui", "automation", "system", "security", "ai"]).describe("Protocol domain") -}); -var MetadataQuerySchema3 = external_exports.object({ - /** Filter by metadata type(s) */ - types: external_exports.array(MetadataTypeSchema3).optional().describe("Filter by metadata types"), - /** Filter by namespace(s) */ - namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), - /** Filter by package ID */ - packageId: external_exports.string().optional().describe("Filter by owning package"), - /** Full-text search across name, label, description */ - search: external_exports.string().optional().describe("Full-text search query"), - /** Filter by scope */ - scope: external_exports.enum(["system", "platform", "user"]).optional().describe("Filter by scope"), - /** Filter by state */ - state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional().describe("Filter by lifecycle state"), - /** Filter by tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), - /** Sort field */ - sortBy: external_exports.enum(["name", "type", "updatedAt", "createdAt"]).default("name").describe("Sort field"), - /** Sort direction */ - sortOrder: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction"), - /** Pagination: page number (1-based) */ - page: external_exports.number().int().min(1).default(1).describe("Page number"), - /** Pagination: items per page */ - pageSize: external_exports.number().int().min(1).max(500).default(50).describe("Items per page") -}); -var MetadataQueryResultSchema3 = external_exports.object({ - /** Matched items */ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - namespace: external_exports.string().optional().describe("Namespace"), - label: external_exports.string().optional().describe("Display label"), - scope: external_exports.enum(["system", "platform", "user"]).optional(), - state: external_exports.enum(["draft", "active", "archived", "deprecated"]).optional(), - packageId: external_exports.string().optional(), - updatedAt: external_exports.string().datetime().optional() - })).describe("Matched metadata items"), - /** Total count (for pagination) */ - total: external_exports.number().int().min(0).describe("Total matching items"), - /** Current page */ - page: external_exports.number().int().min(1).describe("Current page"), - /** Page size */ - pageSize: external_exports.number().int().min(1).describe("Page size") -}); -var MetadataEventSchema3 = external_exports.object({ - /** Event type */ - event: external_exports.enum([ - "metadata.registered", - "metadata.updated", - "metadata.unregistered", - "metadata.validated", - "metadata.deployed", - "metadata.overlay.applied", - "metadata.overlay.removed", - "metadata.imported", - "metadata.exported" - ]).describe("Event type"), - /** Metadata type */ - metadataType: MetadataTypeSchema3.describe("Metadata type"), - /** Item name */ - name: external_exports.string().describe("Metadata item name"), - /** Namespace */ - namespace: external_exports.string().optional().describe("Namespace"), - /** Package ID (if package-managed) */ - packageId: external_exports.string().optional().describe("Owning package ID"), - /** Timestamp */ - timestamp: external_exports.string().datetime().describe("Event timestamp"), - /** Actor who caused the event */ - actor: external_exports.string().optional().describe("User or system that triggered the event"), - /** Additional event-specific payload */ - payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event-specific payload") -}); -var MetadataValidationResultSchema3 = external_exports.object({ - /** Whether validation passed */ - valid: external_exports.boolean().describe("Whether the metadata is valid"), - /** Validation errors */ - errors: external_exports.array(external_exports.object({ - path: external_exports.string().describe("JSON path to the invalid field"), - message: external_exports.string().describe("Error description"), - code: external_exports.string().optional().describe("Error code") - })).optional().describe("Validation errors"), - /** Validation warnings (non-blocking) */ - warnings: external_exports.array(external_exports.object({ - path: external_exports.string().describe("JSON path to the field"), - message: external_exports.string().describe("Warning description") - })).optional().describe("Validation warnings") -}); -var MetadataPluginConfigSchema3 = external_exports.object({ - /** - * Storage configuration. - * References MetadataManagerConfigSchema for the underlying storage backend. - */ - storage: MetadataManagerConfigSchema22.describe("Storage backend configuration"), - /** - * Default customization policies per metadata type. - * Controls what parts of metadata can be customized by admins/users. - */ - customizationPolicies: external_exports.array(CustomizationPolicySchema3).optional().describe("Default customization policies per type"), - /** - * Merge strategy for package upgrades. - */ - mergeStrategy: MergeStrategyConfigSchema3.optional().describe("Merge strategy for package upgrades"), - /** - * Additional metadata type registrations. - * Used by plugins to register custom metadata types beyond the built-in set. - */ - additionalTypes: external_exports.array(MetadataTypeRegistryEntrySchema3.omit({ type: true }).extend({ - type: external_exports.string().describe("Custom metadata type identifier") - })).optional().describe("Additional custom metadata types"), - /** - * Enable metadata change events. - * When true, the plugin emits events on every metadata change. - */ - enableEvents: external_exports.boolean().default(true).describe("Emit metadata change events"), - /** - * Enable metadata validation on write operations. - * When true, all metadata is validated against its type schema before saving. - */ - validateOnWrite: external_exports.boolean().default(true).describe("Validate metadata on write"), - /** - * Enable metadata versioning. - * When true, changes to metadata are tracked with version history. - */ - enableVersioning: external_exports.boolean().default(false).describe("Track metadata version history"), - /** - * Maximum number of metadata items to keep in memory cache. - */ - cacheMaxItems: external_exports.number().int().min(0).default(1e4).describe("Max items in memory cache") -}); -var MetadataPluginManifestSchema2 = external_exports.object({ - /** Plugin identifier */ - id: external_exports.literal("com.objectstack.metadata").describe("Metadata plugin ID"), - /** Plugin name */ - name: external_exports.literal("ObjectStack Metadata Service").describe("Plugin name"), - /** Plugin version */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).describe("Plugin version"), - /** Plugin type */ - type: external_exports.literal("standard").describe("Plugin type"), - /** Plugin description */ - description: external_exports.string().default("Core metadata management service for ObjectStack platform").describe("Plugin description"), - /** - * Capabilities this plugin provides. - * The kernel uses this to route metadata requests to this plugin. - */ - capabilities: external_exports.object({ - /** Supports CRUD operations on metadata */ - crud: external_exports.boolean().default(true).describe("Supports metadata CRUD"), - /** Supports metadata query/search */ - query: external_exports.boolean().default(true).describe("Supports metadata query"), - /** Supports the overlay/customization system */ - overlay: external_exports.boolean().default(true).describe("Supports customization overlays"), - /** Supports file watching for hot reload */ - watch: external_exports.boolean().default(false).describe("Supports file watching"), - /** Supports bulk import/export */ - importExport: external_exports.boolean().default(true).describe("Supports import/export"), - /** Supports metadata validation */ - validation: external_exports.boolean().default(true).describe("Supports schema validation"), - /** Supports metadata versioning */ - versioning: external_exports.boolean().default(false).describe("Supports version history"), - /** Supports metadata events */ - events: external_exports.boolean().default(true).describe("Emits metadata events") - }).describe("Plugin capabilities"), - /** Plugin configuration */ - config: MetadataPluginConfigSchema3.optional().describe("Plugin configuration") -}); -var DEFAULT_METADATA_TYPE_REGISTRY = [ - // Data Protocol (load first) - { type: "object", label: "Object", filePatterns: ["**/*.object.ts", "**/*.object.yml", "**/*.object.json"], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 10, domain: "data" }, - { type: "field", label: "Field", filePatterns: ["**/*.field.ts", "**/*.field.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 20, domain: "data" }, - { type: "trigger", label: "Trigger", filePatterns: ["**/*.trigger.ts", "**/*.trigger.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: "data" }, - { type: "validation", label: "Validation Rule", filePatterns: ["**/*.validation.ts", "**/*.validation.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: "data" }, - { type: "hook", label: "Hook", filePatterns: ["**/*.hook.ts", "**/*.hook.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: "data" }, - // UI Protocol - { type: "view", label: "View", filePatterns: ["**/*.view.ts", "**/*.view.yml", "**/*.view.json"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: "ui" }, - { type: "page", label: "Page", filePatterns: ["**/*.page.ts", "**/*.page.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: "ui" }, - { type: "dashboard", label: "Dashboard", filePatterns: ["**/*.dashboard.ts", "**/*.dashboard.yml", "**/*.dashboard.json"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: "ui" }, - { type: "app", label: "Application", filePatterns: ["**/*.app.ts", "**/*.app.yml", "**/*.app.json"], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 70, domain: "ui" }, - { type: "action", label: "Action", filePatterns: ["**/*.action.ts", "**/*.action.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: "ui" }, - { type: "report", label: "Report", filePatterns: ["**/*.report.ts", "**/*.report.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: "ui" }, - // Automation Protocol - { type: "flow", label: "Flow", filePatterns: ["**/*.flow.ts", "**/*.flow.yml", "**/*.flow.json"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: "automation" }, - { type: "workflow", label: "Workflow", filePatterns: ["**/*.workflow.ts", "**/*.workflow.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: "automation" }, - { type: "approval", label: "Approval Process", filePatterns: ["**/*.approval.ts", "**/*.approval.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 80, domain: "automation" }, - // System Protocol - { type: "datasource", label: "Datasource", filePatterns: ["**/*.datasource.ts", "**/*.datasource.yml"], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 5, domain: "system" }, - { type: "translation", label: "Translation", filePatterns: ["**/*.translation.ts", "**/*.translation.yml", "**/*.translation.json"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 90, domain: "system" }, - { type: "router", label: "Router", filePatterns: ["**/*.router.ts"], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: "system" }, - { type: "function", label: "Function", filePatterns: ["**/*.function.ts"], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: "system" }, - { type: "service", label: "Service", filePatterns: ["**/*.service.ts"], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: "system" }, - // Security Protocol - { type: "permission", label: "Permission Set", filePatterns: ["**/*.permission.ts", "**/*.permission.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 15, domain: "security" }, - { type: "profile", label: "Profile", filePatterns: ["**/*.profile.ts", "**/*.profile.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: "security" }, - { type: "role", label: "Role", filePatterns: ["**/*.role.ts", "**/*.role.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: "security" }, - // AI Protocol - { type: "agent", label: "AI Agent", filePatterns: ["**/*.agent.ts", "**/*.agent.yml"], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 90, domain: "ai" }, - { type: "tool", label: "AI Tool", filePatterns: ["**/*.tool.ts", "**/*.tool.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 85, domain: "ai" }, - { type: "skill", label: "AI Skill", filePatterns: ["**/*.skill.ts", "**/*.skill.yml"], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 88, domain: "ai" } -]; -var MetadataBulkRegisterRequestSchema3 = external_exports.object({ - /** Items to register */ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), - namespace: external_exports.string().optional().describe("Namespace") - })).min(1).describe("Items to register"), - /** Continue on individual item failure */ - continueOnError: external_exports.boolean().default(false).describe("Continue if individual item fails"), - /** Validate items before registering */ - validate: external_exports.boolean().default(true).describe("Validate before register") -}); -var MetadataBulkResultSchema3 = external_exports.object({ - /** Total items processed */ - total: external_exports.number().int().min(0).describe("Total items processed"), - /** Successfully processed items */ - succeeded: external_exports.number().int().min(0).describe("Successfully processed"), - /** Failed items */ - failed: external_exports.number().int().min(0).describe("Failed items"), - /** Per-item error details */ - errors: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - error: external_exports.string().describe("Error message") - })).optional().describe("Per-item errors") -}); -var MetadataDependencySchema3 = external_exports.object({ - /** Source metadata type */ - sourceType: external_exports.string().describe("Dependent metadata type"), - /** Source metadata name */ - sourceName: external_exports.string().describe("Dependent metadata name"), - /** Target metadata type */ - targetType: external_exports.string().describe("Referenced metadata type"), - /** Target metadata name */ - targetName: external_exports.string().describe("Referenced metadata name"), - /** Dependency kind */ - kind: external_exports.enum(["reference", "extends", "includes", "triggers"]).describe("How the dependency is formed") -}); -var PackageStatusEnum3 = external_exports.enum([ - "installed", - // Successfully installed and enabled - "disabled", - // Installed but disabled (metadata not active) - "installing", - // Installation in progress - "upgrading", - // Upgrade in progress - "uninstalling", - // Removal in progress - "error" - // Installation or runtime error -]).describe("Package installation status"); -var InstalledPackageSchema3 = external_exports.object({ - /** - * The full package manifest (source of truth for package definition). - */ - manifest: ManifestSchema3.describe("Full package manifest"), - /** - * Current lifecycle status. - */ - status: PackageStatusEnum3.default("installed").describe("Package state: installed, disabled, installing, upgrading, uninstalling, or error"), - /** - * Whether the package is currently enabled (active). - * When disabled, the package's metadata is not loaded into the registry. - */ - enabled: external_exports.boolean().default(true).describe("Whether the package is currently enabled"), - /** - * ISO 8601 timestamp of when the package was installed. - */ - installedAt: external_exports.string().datetime().optional().describe("Installation timestamp"), - /** - * ISO 8601 timestamp of last update. - */ - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - /** - * The currently installed version string. - * Mirrors manifest.version for quick access without parsing the full manifest. - */ - installedVersion: external_exports.string().optional().describe("Currently installed version for quick access"), - /** - * The previously installed version (before last upgrade). - * Useful for rollback and upgrade tracking. - */ - previousVersion: external_exports.string().optional().describe("Version before the last upgrade"), - /** - * ISO 8601 timestamp of when the package was last enabled/disabled. - */ - statusChangedAt: external_exports.string().datetime().optional().describe("Status change timestamp"), - /** - * Error message if status is 'error'. - */ - errorMessage: external_exports.string().optional().describe("Error message when status is error"), - /** - * Configuration values set by the user for this package. - * Keys correspond to the package's `configuration.properties`. - */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided configuration settings"), - /** - * Upgrade history for this package. - * Records each version migration with status and optional log. - */ - upgradeHistory: external_exports.array(external_exports.object({ - /** Previous version before upgrade */ - fromVersion: external_exports.string().describe("Version before upgrade"), - /** New version after upgrade */ - toVersion: external_exports.string().describe("Version after upgrade"), - /** Timestamp of the upgrade */ - upgradedAt: external_exports.string().datetime().describe("Upgrade timestamp"), - /** Outcome of the upgrade */ - status: external_exports.enum(["success", "failed", "rolled_back"]).describe("Upgrade outcome"), - /** Migration log entries */ - migrationLog: external_exports.array(external_exports.string()).optional().describe("Migration step logs") - })).optional().describe("Version upgrade history"), - /** - * Namespaces registered by this package. - * Tracks which namespace prefixes are occupied by this package. - */ - registeredNamespaces: external_exports.array(external_exports.string()).optional().describe("Namespace prefixes registered by this package") -}).describe("Installed package with runtime lifecycle state"); -var NamespaceRegistryEntrySchema2 = external_exports.object({ - /** Namespace prefix */ - namespace: external_exports.string().describe("Namespace prefix"), - /** Package that owns this namespace */ - packageId: external_exports.string().describe("Owning package ID"), - /** Registration timestamp */ - registeredAt: external_exports.string().datetime().describe("Registration timestamp"), - /** Namespace status */ - status: external_exports.enum(["active", "disabled", "reserved"]).describe("Namespace status") -}).describe("Namespace ownership entry in the registry"); -var NamespaceConflictErrorSchema2 = external_exports.object({ - /** Error type discriminator */ - type: external_exports.literal("namespace_conflict").describe("Error type"), - /** Namespace that was requested */ - requestedNamespace: external_exports.string().describe("Requested namespace"), - /** ID of the package that already owns the namespace */ - conflictingPackageId: external_exports.string().describe("Conflicting package ID"), - /** Name of the conflicting package */ - conflictingPackageName: external_exports.string().describe("Conflicting package display name"), - /** Suggested alternative namespace */ - suggestion: external_exports.string().optional().describe("Suggested alternative namespace") -}).describe("Namespace collision error during installation"); -var ListPackagesRequestSchema3 = external_exports.object({ - /** Filter by status */ - status: PackageStatusEnum3.optional().describe("Filter by package status"), - /** Filter by package type */ - type: ManifestSchema3.shape.type.optional().describe("Filter by package type"), - /** Filter by enabled state */ - enabled: external_exports.boolean().optional().describe("Filter by enabled state") -}).describe("List packages request"); -var ListPackagesResponseSchema3 = external_exports.object({ - packages: external_exports.array(InstalledPackageSchema3).describe("List of installed packages"), - total: external_exports.number().describe("Total package count") -}).describe("List packages response"); -var GetPackageRequestSchema3 = external_exports.object({ - /** Package ID (reverse domain identifier from manifest) */ - id: external_exports.string().describe("Package identifier") -}).describe("Get package request"); -var GetPackageResponseSchema3 = external_exports.object({ - package: InstalledPackageSchema3.describe("Package details") -}).describe("Get package response"); -var InstallPackageRequestSchema3 = external_exports.object({ - /** The package manifest to install */ - manifest: ManifestSchema3.describe("Package manifest to install"), - /** Optional: user-provided settings at install time */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), - /** Whether to enable immediately after install (default: true) */ - enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), - /** - * Current platform version for compatibility checking. - * When provided, the system compares this against the package's - * `engine.objectstack` requirement to verify compatibility. - */ - platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification") -}).describe("Install package request"); -var InstallPackageResponseSchema3 = external_exports.object({ - package: InstalledPackageSchema3.describe("Installed package details"), - message: external_exports.string().optional().describe("Installation status message"), - /** Dependency resolution result (when dependencies were analyzed) */ - dependencyResolution: DependencyResolutionResultSchema3.optional().describe("Dependency resolution result from install analysis") -}).describe("Install package response"); -var UninstallPackageRequestSchema3 = external_exports.object({ - /** Package ID to uninstall */ - id: external_exports.string().describe("Package ID to uninstall") -}).describe("Uninstall package request"); -var UninstallPackageResponseSchema3 = external_exports.object({ - id: external_exports.string().describe("Uninstalled package ID"), - success: external_exports.boolean().describe("Whether uninstall succeeded"), - message: external_exports.string().optional().describe("Uninstall status message") -}).describe("Uninstall package response"); -var EnablePackageRequestSchema3 = external_exports.object({ - /** Package ID to enable */ - id: external_exports.string().describe("Package ID to enable") -}).describe("Enable package request"); -var EnablePackageResponseSchema3 = external_exports.object({ - package: InstalledPackageSchema3.describe("Enabled package details"), - message: external_exports.string().optional().describe("Enable status message") -}).describe("Enable package response"); -var DisablePackageRequestSchema3 = external_exports.object({ - /** Package ID to disable */ - id: external_exports.string().describe("Package ID to disable") -}).describe("Disable package request"); -var DisablePackageResponseSchema3 = external_exports.object({ - package: InstalledPackageSchema3.describe("Disabled package details"), - message: external_exports.string().optional().describe("Disable status message") -}).describe("Disable package response"); -var MetadataChangeTypeSchema3 = external_exports.enum([ - "added", - // New metadata item added in new version - "modified", - // Existing metadata item modified - "removed", - // Metadata item removed in new version - "renamed" - // Metadata item renamed -]).describe("Type of metadata change between package versions"); -var MetadataDiffItemSchema3 = external_exports.object({ - /** Metadata type (e.g. "object", "view", "flow") */ - type: external_exports.string().describe("Metadata type"), - /** Metadata name */ - name: external_exports.string().describe("Metadata name"), - /** Type of change */ - changeType: MetadataChangeTypeSchema3.describe("Category of metadata modification (added, modified, removed, or renamed)"), - /** Whether this change has potential conflicts with customizations */ - hasConflict: external_exports.boolean().default(false).describe("Whether this change may conflict with customizations"), - /** Human-readable summary of the change */ - summary: external_exports.string().optional().describe("Human-readable change summary"), - /** Previous name (for renames) */ - previousName: external_exports.string().optional().describe("Previous name if renamed") -}).describe("Single metadata change between package versions"); -var UpgradeImpactLevelSchema3 = external_exports.enum([ - "none", - // No impact, seamless upgrade - "low", - // Minor changes, no user action needed - "medium", - // Some changes that may affect workflows - "high", - // Significant changes, user review recommended - "critical" - // Breaking changes, manual intervention required -]).describe("Severity of upgrade impact"); -var UpgradePlanSchema3 = external_exports.object({ - /** Package being upgraded */ - packageId: external_exports.string().describe("Package identifier"), - /** Current installed version */ - fromVersion: external_exports.string().describe("Currently installed version"), - /** Target version to upgrade to */ - toVersion: external_exports.string().describe("Target upgrade version"), - /** Overall impact level */ - impactLevel: UpgradeImpactLevelSchema3.describe("Severity assessment from none (seamless) to critical (breaking changes)"), - /** List of all metadata changes between versions */ - changes: external_exports.array(MetadataDiffItemSchema3).describe("All metadata changes"), - /** Number of customer customizations that may be affected */ - affectedCustomizations: external_exports.number().int().min(0).default(0).describe("Count of customizations that may be affected"), - /** Whether any migration scripts need to run */ - requiresMigration: external_exports.boolean().default(false).describe("Whether data migration scripts are needed"), - /** Migration script paths (relative to package root) */ - migrationScripts: external_exports.array(external_exports.string()).optional().describe("Paths to migration scripts"), - /** Dependencies that also need upgrading */ - dependencyUpgrades: external_exports.array(external_exports.object({ - packageId: external_exports.string(), - fromVersion: external_exports.string(), - toVersion: external_exports.string() - })).optional().describe("Dependent packages that also need upgrading"), - /** Estimated upgrade duration in seconds */ - estimatedDuration: external_exports.number().int().min(0).optional().describe("Estimated upgrade duration in seconds"), - /** Human-readable summary */ - summary: external_exports.string().optional().describe("Human-readable upgrade summary") -}).describe("Upgrade analysis plan generated before execution"); -var UpgradeSnapshotSchema2 = external_exports.object({ - /** Snapshot ID (UUID) */ - id: external_exports.string().describe("Snapshot identifier"), - /** Package being upgraded */ - packageId: external_exports.string().describe("Package identifier"), - /** Version being upgraded from */ - fromVersion: external_exports.string().describe("Version before upgrade"), - /** Version being upgraded to */ - toVersion: external_exports.string().describe("Target upgrade version"), - /** Tenant ID */ - tenantId: external_exports.string().optional().describe("Tenant identifier"), - /** Complete manifest of the old package version */ - previousManifest: ManifestSchema3.describe("Complete manifest of the previous package version"), - /** - * Snapshot of all metadata records owned by this package. - * Stored as array of { type, name, metadata } tuples. - */ - metadataSnapshot: external_exports.array(external_exports.object({ - type: external_exports.string(), - name: external_exports.string(), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()) - })).describe("Snapshot of all package metadata"), - /** - * Snapshot of all customer customizations (overlays) for this package's metadata. - */ - customizationSnapshot: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Snapshot of customer customizations"), - /** When the snapshot was created */ - createdAt: external_exports.string().datetime().describe("Snapshot creation timestamp"), - /** Expiry time for snapshot cleanup */ - expiresAt: external_exports.string().datetime().optional().describe("Snapshot expiry timestamp") -}).describe("Pre-upgrade state snapshot for rollback capability"); -var UpgradePackageRequestSchema2 = external_exports.object({ - /** Package ID to upgrade */ - packageId: external_exports.string().describe("Package ID to upgrade"), - /** Target version (if omitted, upgrades to latest) */ - targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), - /** New manifest for the target version */ - manifest: ManifestSchema3.optional().describe("New manifest (if installing from local)"), - /** Whether to create a pre-upgrade snapshot */ - createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), - /** Merge strategy for handling customizations */ - mergeStrategy: external_exports.enum([ - "keep-custom", - "accept-incoming", - "three-way-merge" - ]).default("three-way-merge").describe("How to handle customer customizations"), - /** Whether to run in dry-run mode (preview only, no changes) */ - dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), - /** Whether to skip pre-upgrade validation */ - skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") -}).describe("Upgrade package request"); -var UpgradePhaseSchema3 = external_exports.enum([ - "pending", - // Upgrade requested but not started - "analyzing", - // Generating upgrade plan - "snapshot", - // Creating pre-upgrade snapshot - "executing", - // Applying metadata changes - "migrating", - // Running migration scripts - "validating", - // Post-upgrade validation - "completed", - // Upgrade completed successfully - "failed", - // Upgrade failed - "rolling-back", - // Rollback in progress - "rolled-back" - // Rollback completed -]).describe("Current phase of the upgrade process"); -var UpgradePackageResponseSchema2 = external_exports.object({ - /** Whether the upgrade was successful */ - success: external_exports.boolean().describe("Whether the upgrade succeeded"), - /** Current upgrade phase */ - phase: UpgradePhaseSchema3.describe("Current upgrade phase"), - /** The upgrade plan that was executed */ - plan: UpgradePlanSchema3.optional().describe("Upgrade plan"), - /** Snapshot ID for rollback */ - snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), - /** Merge conflicts that need manual resolution (if any) */ - conflicts: external_exports.array(external_exports.object({ - path: external_exports.string(), - baseValue: external_exports.unknown(), - incomingValue: external_exports.unknown(), - customValue: external_exports.unknown() - })).optional().describe("Unresolved merge conflicts"), - /** Error message (if failed) */ - errorMessage: external_exports.string().optional().describe("Error message if upgrade failed"), - /** Human-readable summary */ - message: external_exports.string().optional().describe("Human-readable status message") -}).describe("Upgrade package response"); -var RollbackPackageRequestSchema2 = external_exports.object({ - /** Package ID to rollback */ - packageId: external_exports.string().describe("Package ID to rollback"), - /** Snapshot ID to restore from */ - snapshotId: external_exports.string().describe("Snapshot ID to restore from"), - /** Whether to also rollback customizations */ - rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") -}).describe("Rollback package request"); -var RollbackPackageResponseSchema2 = external_exports.object({ - /** Whether the rollback was successful */ - success: external_exports.boolean().describe("Whether the rollback succeeded"), - /** Restored version */ - restoredVersion: external_exports.string().optional().describe("Version restored to"), - /** Message */ - message: external_exports.string().optional().describe("Rollback status message") -}).describe("Rollback package response"); -var PluginHealthStatusSchema2 = external_exports.enum([ - "healthy", - // Plugin is operating normally - "degraded", - // Plugin is operational but with reduced functionality - "unhealthy", - // Plugin has critical issues but still running - "failed", - // Plugin has failed and is not operational - "recovering", - // Plugin is in recovery process - "unknown" - // Health status cannot be determined -]).describe("Current health status of the plugin"); -var PluginHealthCheckSchema2 = external_exports.object({ - /** - * Health check interval in milliseconds - */ - interval: external_exports.number().int().min(1e3).default(3e4).describe("How often to perform health checks (default: 30s)"), - /** - * Timeout for health check in milliseconds - */ - timeout: external_exports.number().int().min(100).default(5e3).describe("Maximum time to wait for health check response"), - /** - * Number of consecutive failures before marking as unhealthy - */ - failureThreshold: external_exports.number().int().min(1).default(3).describe("Consecutive failures needed to mark unhealthy"), - /** - * Number of consecutive successes to recover from unhealthy state - */ - successThreshold: external_exports.number().int().min(1).default(1).describe("Consecutive successes needed to mark healthy"), - /** - * Custom health check function name or endpoint - */ - checkMethod: external_exports.string().optional().describe("Method name to call for health check"), - /** - * Enable automatic restart on failure - */ - autoRestart: external_exports.boolean().default(false).describe("Automatically restart plugin on health check failure"), - /** - * Maximum number of restart attempts - */ - maxRestartAttempts: external_exports.number().int().min(0).default(3).describe("Maximum restart attempts before giving up"), - /** - * Backoff strategy for restarts - */ - restartBackoff: external_exports.enum(["fixed", "linear", "exponential"]).default("exponential").describe("Backoff strategy for restart delays") -}); -var PluginHealthReportSchema2 = external_exports.object({ - /** - * Overall health status - */ - status: PluginHealthStatusSchema2, - /** - * Timestamp of the health check - */ - timestamp: external_exports.string().datetime(), - /** - * Human-readable message about health status - */ - message: external_exports.string().optional(), - /** - * Detailed metrics - */ - metrics: external_exports.object({ - uptime: external_exports.number().describe("Plugin uptime in milliseconds"), - memoryUsage: external_exports.number().optional().describe("Memory usage in bytes"), - cpuUsage: external_exports.number().optional().describe("CPU usage percentage"), - activeConnections: external_exports.number().optional().describe("Number of active connections"), - errorRate: external_exports.number().optional().describe("Error rate (errors per minute)"), - responseTime: external_exports.number().optional().describe("Average response time in ms") - }).partial().optional(), - /** - * List of checks performed - */ - checks: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Check name"), - status: external_exports.enum(["passed", "failed", "warning"]), - message: external_exports.string().optional(), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - })).optional(), - /** - * Dependencies health - */ - dependencies: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - status: PluginHealthStatusSchema2, - message: external_exports.string().optional() - })).optional() -}); -var DistributedStateConfigSchema2 = external_exports.object({ - /** - * Distributed cache provider - */ - provider: external_exports.enum(["redis", "etcd", "custom"]).describe("Distributed state backend provider"), - /** - * Connection URL or endpoints - */ - endpoints: external_exports.array(external_exports.string()).optional().describe("Backend connection endpoints"), - /** - * Key prefix for namespacing - */ - keyPrefix: external_exports.string().optional().describe('Prefix for all keys (e.g., "plugin:my-plugin:")'), - /** - * Time to live in seconds - */ - ttl: external_exports.number().int().min(0).optional().describe("State expiration time in seconds"), - /** - * Authentication configuration - */ - auth: external_exports.object({ - username: external_exports.string().optional(), - password: external_exports.string().optional(), - token: external_exports.string().optional(), - certificate: external_exports.string().optional() - }).optional(), - /** - * Replication settings - */ - replication: external_exports.object({ - enabled: external_exports.boolean().default(true), - minReplicas: external_exports.number().int().min(1).default(1) - }).optional(), - /** - * Custom provider configuration - */ - customConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Provider-specific configuration") -}); -var HotReloadConfigSchema2 = external_exports.object({ - /** - * Enable hot reload capability - */ - enabled: external_exports.boolean().default(false), - /** - * Watch file patterns for auto-reload - */ - watchPatterns: external_exports.array(external_exports.string()).optional().describe("Glob patterns to watch for changes"), - /** - * Debounce delay before reloading (milliseconds) - */ - debounceDelay: external_exports.number().int().min(0).default(1e3).describe("Wait time after change detection before reload"), - /** - * Preserve plugin state during reload - */ - preserveState: external_exports.boolean().default(true).describe("Keep plugin state across reloads"), - /** - * State serialization strategy - */ - stateStrategy: external_exports.enum(["memory", "disk", "distributed", "none"]).default("memory").describe("How to preserve state during reload"), - /** - * Distributed state configuration (required when stateStrategy is "distributed") - */ - distributedConfig: DistributedStateConfigSchema2.optional().describe("Configuration for distributed state management"), - /** - * Graceful shutdown timeout - */ - shutdownTimeout: external_exports.number().int().min(0).default(3e4).describe("Maximum time to wait for graceful shutdown"), - /** - * Pre-reload hooks - */ - beforeReload: external_exports.array(external_exports.string()).optional().describe("Hook names to call before reload"), - /** - * Post-reload hooks - */ - afterReload: external_exports.array(external_exports.string()).optional().describe("Hook names to call after reload") -}); -var GracefulDegradationSchema2 = external_exports.object({ - /** - * Enable graceful degradation - */ - enabled: external_exports.boolean().default(true), - /** - * Fallback mode when dependencies fail - */ - fallbackMode: external_exports.enum([ - "minimal", - // Provide minimal functionality - "cached", - // Use cached data - "readonly", - // Allow read-only operations - "offline", - // Offline mode with local data - "disabled" - // Disable plugin functionality - ]).default("minimal"), - /** - * Critical dependencies that must be available - */ - criticalDependencies: external_exports.array(external_exports.string()).optional().describe("Plugin IDs that are required for operation"), - /** - * Optional dependencies that can fail - */ - optionalDependencies: external_exports.array(external_exports.string()).optional().describe("Plugin IDs that are nice to have but not required"), - /** - * Feature flags for degraded mode - */ - degradedFeatures: external_exports.array(external_exports.object({ - feature: external_exports.string().describe("Feature name"), - enabled: external_exports.boolean().describe("Whether feature is available in degraded mode"), - reason: external_exports.string().optional() - })).optional(), - /** - * Automatic recovery attempts - */ - autoRecovery: external_exports.object({ - enabled: external_exports.boolean().default(true), - retryInterval: external_exports.number().int().min(1e3).default(6e4).describe("Interval between recovery attempts (ms)"), - maxAttempts: external_exports.number().int().min(0).default(5).describe("Maximum recovery attempts before giving up") - }).optional() -}); -var PluginUpdateStrategySchema2 = external_exports.object({ - /** - * Update mode - */ - mode: external_exports.enum([ - "manual", - // Manual updates only - "automatic", - // Automatic updates - "scheduled", - // Scheduled update windows - "rolling" - // Rolling updates with zero downtime - ]).default("manual"), - /** - * Version constraints for automatic updates - */ - autoUpdateConstraints: external_exports.object({ - major: external_exports.boolean().default(false).describe("Allow major version updates"), - minor: external_exports.boolean().default(true).describe("Allow minor version updates"), - patch: external_exports.boolean().default(true).describe("Allow patch version updates") - }).optional(), - /** - * Update schedule (for scheduled mode) - */ - schedule: external_exports.object({ - /** - * Cron expression for update window - */ - cron: external_exports.string().optional(), - /** - * Timezone for schedule - */ - timezone: external_exports.string().default("UTC"), - /** - * Maintenance window duration in minutes - */ - maintenanceWindow: external_exports.number().int().min(1).default(60) - }).optional(), - /** - * Rollback configuration - */ - rollback: external_exports.object({ - enabled: external_exports.boolean().default(true), - /** - * Automatic rollback on failure - */ - automatic: external_exports.boolean().default(true), - /** - * Keep N previous versions for rollback - */ - keepVersions: external_exports.number().int().min(1).default(3), - /** - * Rollback timeout in milliseconds - */ - timeout: external_exports.number().int().min(1e3).default(3e4) - }).optional(), - /** - * Pre-update validation - */ - validation: external_exports.object({ - /** - * Run compatibility checks before update - */ - checkCompatibility: external_exports.boolean().default(true), - /** - * Run tests before applying update - */ - runTests: external_exports.boolean().default(false), - /** - * Test suite to run - */ - testSuite: external_exports.string().optional() - }).optional() -}); -var PluginStateSnapshotSchema2 = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Version at time of snapshot - */ - version: external_exports.string(), - /** - * Snapshot timestamp - */ - timestamp: external_exports.string().datetime(), - /** - * Serialized state data - */ - state: external_exports.record(external_exports.string(), external_exports.unknown()), - /** - * State metadata - */ - metadata: external_exports.object({ - checksum: external_exports.string().optional().describe("State checksum for verification"), - compressed: external_exports.boolean().default(false), - encryption: external_exports.string().optional().describe("Encryption algorithm if encrypted") - }).optional() -}); -var AdvancedPluginLifecycleConfigSchema2 = external_exports.object({ - /** - * Health monitoring configuration - */ - health: PluginHealthCheckSchema2.optional(), - /** - * Hot reload configuration - */ - hotReload: HotReloadConfigSchema2.optional(), - /** - * Graceful degradation configuration - */ - degradation: GracefulDegradationSchema2.optional(), - /** - * Update strategy - */ - updates: PluginUpdateStrategySchema2.optional(), - /** - * Resource limits - */ - resources: external_exports.object({ - maxMemory: external_exports.number().int().optional().describe("Maximum memory in bytes"), - maxCpu: external_exports.number().min(0).max(100).optional().describe("Maximum CPU percentage"), - maxConnections: external_exports.number().int().optional().describe("Maximum concurrent connections"), - timeout: external_exports.number().int().optional().describe("Operation timeout in milliseconds") - }).optional(), - /** - * Monitoring and observability - */ - observability: external_exports.object({ - enableMetrics: external_exports.boolean().default(true), - enableTracing: external_exports.boolean().default(true), - enableProfiling: external_exports.boolean().default(false), - metricsInterval: external_exports.number().int().min(1e3).default(6e4).describe("Metrics collection interval in ms") - }).optional() -}); -var EventPhaseSchema2 = external_exports.enum(["init", "start", "destroy"]).describe("Plugin lifecycle phase"); -var PluginEventBaseSchema2 = external_exports.object({ - /** - * Plugin name - */ - pluginName: external_exports.string().describe("Name of the plugin"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds when event occurred") -}); -var PluginRegisteredEventSchema2 = PluginEventBaseSchema2.extend({ - /** - * Plugin version (optional) - */ - version: external_exports.string().optional().describe("Plugin version") -}); -var PluginLifecyclePhaseEventSchema2 = PluginEventBaseSchema2.extend({ - /** - * Duration of the phase (milliseconds) - */ - duration: external_exports.number().min(0).optional().describe("Duration of the lifecycle phase in milliseconds"), - /** - * Lifecycle phase - */ - phase: EventPhaseSchema2.optional().describe("Lifecycle phase") -}); -var PluginErrorEventSchema2 = PluginEventBaseSchema2.extend({ - /** - * Error object - */ - error: external_exports.object({ - name: external_exports.string().describe("Error class name"), - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Stack trace"), - code: external_exports.string().optional().describe("Error code") - }).describe("Serializable error representation"), - /** - * Lifecycle phase where error occurred - */ - phase: EventPhaseSchema2.describe("Lifecycle phase where error occurred"), - /** - * Error message (for serialization) - */ - errorMessage: external_exports.string().optional().describe("Error message"), - /** - * Error stack trace (for debugging) - */ - errorStack: external_exports.string().optional().describe("Error stack trace") -}); -var ServiceRegisteredEventSchema2 = external_exports.object({ - /** - * Service name - */ - serviceName: external_exports.string().describe("Name of the registered service"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), - /** - * Service type (optional) - */ - serviceType: external_exports.string().optional().describe("Type or interface name of the service") -}); -var ServiceUnregisteredEventSchema2 = external_exports.object({ - /** - * Service name - */ - serviceName: external_exports.string().describe("Name of the unregistered service"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds") -}); -var HookRegisteredEventSchema2 = external_exports.object({ - /** - * Hook name - */ - hookName: external_exports.string().describe("Name of the hook"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), - /** - * Number of handlers registered for this hook - */ - handlerCount: external_exports.number().int().min(0).describe("Number of handlers registered for this hook") -}); -var HookTriggeredEventSchema2 = external_exports.object({ - /** - * Hook name - */ - hookName: external_exports.string().describe("Name of the hook"), - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds"), - /** - * Arguments passed to the hook - */ - args: external_exports.array(external_exports.unknown()).describe("Arguments passed to the hook handlers"), - /** - * Number of handlers that will handle this event - */ - handlerCount: external_exports.number().int().min(0).optional().describe("Number of handlers that will handle this event") -}); -var KernelEventBaseSchema2 = external_exports.object({ - /** - * Event timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds") -}); -var KernelReadyEventSchema2 = KernelEventBaseSchema2.extend({ - /** - * Total initialization duration (milliseconds) - */ - duration: external_exports.number().min(0).optional().describe("Total initialization duration in milliseconds"), - /** - * Number of plugins initialized - */ - pluginCount: external_exports.number().int().min(0).optional().describe("Number of plugins initialized") -}); -var KernelShutdownEventSchema2 = KernelEventBaseSchema2.extend({ - /** - * Shutdown reason (optional) - */ - reason: external_exports.string().optional().describe("Reason for kernel shutdown") -}); -var PluginLifecycleEventType2 = external_exports.enum([ - "kernel:ready", - "kernel:shutdown", - "kernel:before-init", - "kernel:after-init", - "plugin:registered", - "plugin:before-init", - "plugin:init", - "plugin:after-init", - "plugin:before-start", - "plugin:started", - "plugin:after-start", - "plugin:before-destroy", - "plugin:destroyed", - "plugin:after-destroy", - "plugin:error", - "service:registered", - "service:unregistered", - "hook:registered", - "hook:triggered" -]).describe("Plugin lifecycle event type"); -var DynamicPluginOperationSchema2 = external_exports.enum([ - "load", - // Load and initialize a plugin at runtime - "unload", - // Gracefully unload a running plugin - "reload", - // Unload then load (e.g., version upgrade) - "enable", - // Enable a loaded but disabled plugin - "disable" - // Disable a running plugin without unloading -]).describe("Runtime plugin operation type"); -var PluginSourceSchema2 = external_exports.object({ - /** - * Source type - */ - type: external_exports.enum([ - "npm", - // npm registry package - "local", - // Local filesystem path - "url", - // Remote URL (tarball or module) - "registry", - // ObjectStack plugin registry - "git" - // Git repository - ]).describe("Plugin source type"), - /** - * Source location (package name, path, URL, or git repo) - */ - location: external_exports.string().describe("Package name, file path, URL, or git repository"), - /** - * Version constraint (semver range) - */ - version: external_exports.string().optional().describe('Semver version range (e.g., "^1.0.0")'), - /** - * Integrity hash for verification - */ - integrity: external_exports.string().optional().describe('Subresource Integrity hash (e.g., "sha384-...")') -}).describe("Plugin source location for dynamic resolution"); -var ActivationEventSchema2 = external_exports.object({ - /** - * Event type - */ - type: external_exports.enum([ - "onCommand", - // Activate when a specific command is executed - "onRoute", - // Activate when a URL route is matched - "onObject", - // Activate when a specific object type is accessed - "onEvent", - // Activate when a system event fires - "onService", - // Activate when a service is requested - "onSchedule", - // Activate on a cron schedule - "onStartup" - // Activate immediately on kernel startup - ]).describe("Trigger type for lazy activation"), - /** - * Pattern to match (command name, route glob, object name, event pattern, etc.) - */ - pattern: external_exports.string().describe("Match pattern for the activation trigger") -}).describe("Lazy activation trigger for a dynamic plugin"); -var DynamicLoadRequestSchema2 = external_exports.object({ - /** - * Plugin identifier to load - */ - pluginId: external_exports.string().describe("Unique plugin identifier"), - /** - * Plugin source - */ - source: PluginSourceSchema2, - /** - * Activation events (if omitted, plugin activates immediately) - */ - activationEvents: external_exports.array(ActivationEventSchema2).optional().describe("Lazy activation triggers; if omitted plugin starts immediately"), - /** - * Configuration overrides for the plugin - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Runtime configuration overrides"), - /** - * Loading priority (lower = higher priority) - */ - priority: external_exports.number().int().min(0).default(100).describe("Loading priority (lower is higher)"), - /** - * Whether to enable sandboxing for this dynamically loaded plugin - */ - sandbox: external_exports.boolean().default(false).describe("Run in an isolated sandbox"), - /** - * Timeout for the load operation in milliseconds - */ - timeout: external_exports.number().int().min(1e3).default(6e4).describe("Maximum time to complete loading in ms") -}).describe("Request to dynamically load a plugin at runtime"); -var DynamicUnloadRequestSchema2 = external_exports.object({ - /** - * Plugin identifier to unload - */ - pluginId: external_exports.string().describe("Plugin to unload"), - /** - * Unload strategy - */ - strategy: external_exports.enum([ - "graceful", - // Wait for in-flight requests, then unload - "forceful", - // Unload immediately, cancel pending work - "drain" - // Stop accepting new work, finish existing, then unload - ]).default("graceful").describe("How to handle in-flight work during unload"), - /** - * Timeout for the unload operation in milliseconds - */ - timeout: external_exports.number().int().min(1e3).default(3e4).describe("Maximum time to complete unloading in ms"), - /** - * Whether to remove cached artifacts - */ - cleanupCache: external_exports.boolean().default(false).describe("Remove cached code and assets after unload"), - /** - * Action for dependents: plugins that depend on this one - */ - dependentAction: external_exports.enum([ - "cascade", - // Also unload dependent plugins - "warn", - // Warn about dependents but proceed - "block" - // Block unload if dependents exist - ]).default("block").describe("How to handle plugins that depend on this one") -}).describe("Request to dynamically unload a plugin at runtime"); -var DynamicPluginResultSchema2 = external_exports.object({ - /** - * Whether the operation succeeded - */ - success: external_exports.boolean(), - /** - * The operation that was performed - */ - operation: DynamicPluginOperationSchema2, - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Operation duration in milliseconds - */ - durationMs: external_exports.number().int().min(0).optional(), - /** - * Resulting plugin version (for load/reload) - */ - version: external_exports.string().optional(), - /** - * Error details if operation failed - */ - error: external_exports.object({ - code: external_exports.string().describe("Machine-readable error code"), - message: external_exports.string().describe("Human-readable error message"), - details: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional(), - /** - * Warnings (e.g., dependents affected) - */ - warnings: external_exports.array(external_exports.string()).optional() -}).describe("Result of a dynamic plugin operation"); -var PluginDiscoverySourceSchema2 = external_exports.object({ - /** - * Discovery source type - */ - type: external_exports.enum([ - "registry", - // ObjectStack plugin registry API - "npm", - // npm registry search - "directory", - // Local filesystem directory scan - "url" - // Remote manifest URL - ]).describe("Discovery source type"), - /** - * Source endpoint or path - */ - endpoint: external_exports.string().describe("Registry URL, directory path, or manifest URL"), - /** - * Polling interval in milliseconds (0 = manual only) - */ - pollInterval: external_exports.number().int().min(0).default(0).describe("How often to re-scan for new plugins (0 = manual)"), - /** - * Filter criteria for discovered plugins - */ - filter: external_exports.object({ - /** - * Only discover plugins matching these tags - */ - tags: external_exports.array(external_exports.string()).optional(), - /** - * Only discover plugins from these vendors - */ - vendors: external_exports.array(external_exports.string()).optional(), - /** - * Minimum trust level - */ - minTrustLevel: external_exports.enum(["verified", "trusted", "community", "untrusted"]).optional() - }).optional() -}).describe("Source for runtime plugin discovery"); -var PluginDiscoveryConfigSchema2 = external_exports.object({ - /** - * Enable runtime plugin discovery - */ - enabled: external_exports.boolean().default(false), - /** - * Discovery sources - */ - sources: external_exports.array(PluginDiscoverySourceSchema2).default([]), - /** - * Auto-load discovered plugins matching criteria - */ - autoLoad: external_exports.boolean().default(false).describe("Automatically load newly discovered plugins"), - /** - * Require approval before loading discovered plugins - */ - requireApproval: external_exports.boolean().default(true).describe("Require admin approval before loading discovered plugins") -}).describe("Runtime plugin discovery configuration"); -var DynamicLoadingConfigSchema2 = external_exports.object({ - /** - * Enable dynamic loading/unloading at runtime - */ - enabled: external_exports.boolean().default(false).describe("Enable runtime load/unload of plugins"), - /** - * Maximum number of dynamically loaded plugins - */ - maxDynamicPlugins: external_exports.number().int().min(1).default(50).describe("Upper limit on runtime-loaded plugins"), - /** - * Plugin discovery configuration - */ - discovery: PluginDiscoveryConfigSchema2.optional(), - /** - * Default sandbox policy for dynamically loaded plugins - */ - defaultSandbox: external_exports.boolean().default(true).describe("Sandbox dynamically loaded plugins by default"), - /** - * Allowed plugin sources (empty = all allowed) - */ - allowedSources: external_exports.array(external_exports.enum(["npm", "local", "url", "registry", "git"])).optional().describe("Restrict which source types are permitted"), - /** - * Require integrity verification for remote plugins - */ - requireIntegrity: external_exports.boolean().default(true).describe("Require integrity hash verification for remote sources"), - /** - * Global timeout for dynamic operations in milliseconds - */ - operationTimeout: external_exports.number().int().min(1e3).default(6e4).describe("Default timeout for load/unload operations in ms") -}).describe("Dynamic plugin loading subsystem configuration"); -var PermissionScopeSchema2 = external_exports.enum([ - "global", - // Applies to entire system - "tenant", - // Applies to specific tenant - "user", - // Applies to specific user - "resource", - // Applies to specific resource - "plugin" - // Applies within plugin boundaries -]).describe("Scope of permission application"); -var PermissionActionSchema2 = external_exports.enum([ - "create", - // Create new resources - "read", - // Read existing resources - "update", - // Update existing resources - "delete", - // Delete resources - "execute", - // Execute operations/functions - "manage", - // Full management rights - "configure", - // Configuration changes - "share", - // Share with others - "export", - // Export data - "import", - // Import data - "admin" - // Administrative access -]).describe("Type of action being permitted"); -var ResourceTypeSchema2 = external_exports.enum([ - "data.object", - // ObjectQL objects - "data.record", - // Individual records - "data.field", - // Specific fields - "ui.view", - // UI views - "ui.dashboard", - // Dashboards - "ui.report", - // Reports - "system.config", - // System configuration - "system.plugin", - // Other plugins - "system.api", - // API endpoints - "system.service", - // System services - "storage.file", - // File storage - "storage.database", - // Database access - "network.http", - // HTTP requests - "network.websocket", - // WebSocket connections - "process.spawn", - // Process spawning - "process.env" - // Environment variables -]).describe("Type of resource being accessed"); -var PermissionSchema2 = external_exports.object({ - /** - * Permission identifier - */ - id: external_exports.string().describe("Unique permission identifier"), - /** - * Resource type - */ - resource: ResourceTypeSchema2, - /** - * Allowed actions - */ - actions: external_exports.array(PermissionActionSchema2), - /** - * Permission scope - */ - scope: PermissionScopeSchema2.default("plugin"), - /** - * Resource filter - */ - filter: external_exports.object({ - /** - * Specific resource IDs - */ - resourceIds: external_exports.array(external_exports.string()).optional(), - /** - * Filter condition - */ - condition: external_exports.string().optional().describe("Filter expression (e.g., owner = currentUser)"), - /** - * Field-level access - */ - fields: external_exports.array(external_exports.string()).optional().describe("Allowed fields for data resources") - }).optional(), - /** - * Human-readable description - */ - description: external_exports.string(), - /** - * Whether this permission is required or optional - */ - required: external_exports.boolean().default(true), - /** - * Justification for permission - */ - justification: external_exports.string().optional().describe("Why this permission is needed") -}); -var PermissionSetSchema22 = external_exports.object({ - /** - * All permissions required by plugin - */ - permissions: external_exports.array(PermissionSchema2), - /** - * Permission groups for easier management - */ - groups: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Group name"), - description: external_exports.string(), - permissions: external_exports.array(external_exports.string()).describe("Permission IDs in this group") - })).optional(), - /** - * Default grant strategy - */ - defaultGrant: external_exports.enum([ - "prompt", - // Always prompt user - "allow", - // Allow by default - "deny", - // Deny by default - "inherit" - // Inherit from parent - ]).default("prompt") -}); -var RuntimeConfigSchema2 = external_exports.object({ - /** - * Runtime engine type - */ - engine: external_exports.enum([ - "v8-isolate", - // V8 isolate-based isolation (lightweight, fast) - "wasm", - // WebAssembly-based isolation (secure, portable) - "container", - // Container-based isolation (Docker, podman) - "process" - // Process-based isolation (traditional) - ]).default("v8-isolate").describe("Execution environment engine"), - /** - * Engine-specific configuration - */ - engineConfig: external_exports.object({ - /** - * WASM-specific settings (when engine is "wasm") - */ - wasm: external_exports.object({ - /** - * Maximum memory pages (64KB per page) - */ - maxMemoryPages: external_exports.number().int().min(1).max(65536).optional().describe("Maximum WASM memory pages (64KB each)"), - /** - * Instruction execution limit - */ - instructionLimit: external_exports.number().int().min(1).optional().describe("Maximum instructions before timeout"), - /** - * Enable SIMD instructions - */ - enableSimd: external_exports.boolean().default(false).describe("Enable WebAssembly SIMD support"), - /** - * Enable threads - */ - enableThreads: external_exports.boolean().default(false).describe("Enable WebAssembly threads"), - /** - * Enable bulk memory operations - */ - enableBulkMemory: external_exports.boolean().default(true).describe("Enable bulk memory operations") - }).optional(), - /** - * Container-specific settings (when engine is "container") - */ - container: external_exports.object({ - /** - * Container image - */ - image: external_exports.string().optional().describe("Container image to use"), - /** - * Container runtime - */ - runtime: external_exports.enum(["docker", "podman", "containerd"]).default("docker"), - /** - * Resource limits - */ - resources: external_exports.object({ - cpuLimit: external_exports.string().optional().describe('CPU limit (e.g., "0.5", "2")'), - memoryLimit: external_exports.string().optional().describe('Memory limit (e.g., "512m", "1g")') - }).optional(), - /** - * Network mode - */ - networkMode: external_exports.enum(["none", "bridge", "host"]).default("bridge") - }).optional(), - /** - * V8 Isolate-specific settings (when engine is "v8-isolate") - */ - v8Isolate: external_exports.object({ - /** - * Heap size limit in MB - */ - heapSizeMb: external_exports.number().int().min(1).optional(), - /** - * Enable snapshot - */ - enableSnapshot: external_exports.boolean().default(true) - }).optional() - }).optional(), - /** - * General resource limits (applies to all engines) - */ - resourceLimits: external_exports.object({ - /** - * Maximum memory in bytes - */ - maxMemory: external_exports.number().int().optional().describe("Maximum memory allocation"), - /** - * Maximum CPU percentage - */ - maxCpu: external_exports.number().min(0).max(100).optional().describe("Maximum CPU usage percentage"), - /** - * Execution timeout in milliseconds - */ - timeout: external_exports.number().int().min(0).optional().describe("Maximum execution time") - }).optional() -}); -var SandboxConfigSchema2 = external_exports.object({ - /** - * Enable sandboxing - */ - enabled: external_exports.boolean().default(true), - /** - * Sandboxing level - */ - level: external_exports.enum([ - "none", - // No sandboxing - "minimal", - // Basic isolation - "standard", - // Standard sandboxing - "strict", - // Strict isolation - "paranoid" - // Maximum isolation - ]).default("standard"), - /** - * Runtime environment configuration - */ - runtime: RuntimeConfigSchema2.optional().describe("Execution environment and isolation settings"), - /** - * File system access - */ - filesystem: external_exports.object({ - mode: external_exports.enum(["none", "readonly", "restricted", "full"]).default("restricted"), - allowedPaths: external_exports.array(external_exports.string()).optional().describe("Whitelisted paths"), - deniedPaths: external_exports.array(external_exports.string()).optional().describe("Blacklisted paths"), - maxFileSize: external_exports.number().int().optional().describe("Maximum file size in bytes") - }).optional(), - /** - * Network access - */ - network: external_exports.object({ - mode: external_exports.enum(["none", "local", "restricted", "full"]).default("restricted"), - allowedHosts: external_exports.array(external_exports.string()).optional().describe("Whitelisted hosts"), - deniedHosts: external_exports.array(external_exports.string()).optional().describe("Blacklisted hosts"), - allowedPorts: external_exports.array(external_exports.number()).optional().describe("Allowed port numbers"), - maxConnections: external_exports.number().int().optional() - }).optional(), - /** - * Process execution - */ - process: external_exports.object({ - allowSpawn: external_exports.boolean().default(false).describe("Allow spawning child processes"), - allowedCommands: external_exports.array(external_exports.string()).optional().describe("Whitelisted commands"), - timeout: external_exports.number().int().optional().describe("Process timeout in ms") - }).optional(), - /** - * Memory limits - */ - memory: external_exports.object({ - maxHeap: external_exports.number().int().optional().describe("Maximum heap size in bytes"), - maxStack: external_exports.number().int().optional().describe("Maximum stack size in bytes") - }).optional(), - /** - * CPU limits - */ - cpu: external_exports.object({ - maxCpuPercent: external_exports.number().min(0).max(100).optional(), - maxThreads: external_exports.number().int().optional() - }).optional(), - /** - * Environment variables - */ - environment: external_exports.object({ - mode: external_exports.enum(["none", "readonly", "restricted", "full"]).default("readonly"), - allowedVars: external_exports.array(external_exports.string()).optional(), - deniedVars: external_exports.array(external_exports.string()).optional() - }).optional() -}); -var KernelSecurityVulnerabilitySchema2 = external_exports.object({ - /** - * CVE identifier - */ - cve: external_exports.string().optional(), - /** - * Vulnerability identifier - */ - id: external_exports.string(), - /** - * Severity level - */ - severity: external_exports.enum(["critical", "high", "medium", "low", "info"]), - /** - * Category (e.g., SAST, DAST, Dependency) - */ - category: external_exports.string().optional(), - /** - * Title - */ - title: external_exports.string(), - /** - * Location of the vulnerability - */ - location: external_exports.string().optional(), - /** - * Remediation steps - */ - remediation: external_exports.string().optional(), - /** - * Description - */ - description: external_exports.string(), - /** - * Affected versions - */ - affectedVersions: external_exports.array(external_exports.string()), - /** - * Fixed in versions - */ - fixedIn: external_exports.array(external_exports.string()).optional(), - /** - * CVSS score - */ - cvssScore: external_exports.number().min(0).max(10).optional(), - /** - * Exploit availability - */ - exploitAvailable: external_exports.boolean().default(false), - /** - * Patch available - */ - patchAvailable: external_exports.boolean().default(false), - /** - * Workaround - */ - workaround: external_exports.string().optional(), - /** - * References - */ - references: external_exports.array(external_exports.string()).optional(), - /** - * Discovered date - */ - discoveredDate: external_exports.string().datetime().optional(), - /** - * Published date - */ - publishedDate: external_exports.string().datetime().optional() -}); -var KernelSecurityScanResultSchema2 = external_exports.object({ - /** - * Scan timestamp - */ - timestamp: external_exports.string().datetime(), - /** - * Scanner information - */ - scanner: external_exports.object({ - name: external_exports.string(), - version: external_exports.string() - }), - /** - * Overall status - */ - status: external_exports.enum(["passed", "failed", "warning"]), - /** - * Vulnerabilities found - */ - vulnerabilities: external_exports.array(KernelSecurityVulnerabilitySchema2).optional(), - /** - * Code quality issues - */ - codeIssues: external_exports.array(external_exports.object({ - severity: external_exports.enum(["error", "warning", "info"]), - type: external_exports.string().describe("Issue type (e.g., sql-injection, xss)"), - file: external_exports.string(), - line: external_exports.number().int().optional(), - message: external_exports.string(), - suggestion: external_exports.string().optional() - })).optional(), - /** - * Dependency vulnerabilities - */ - dependencyVulnerabilities: external_exports.array(external_exports.object({ - package: external_exports.string(), - version: external_exports.string(), - vulnerability: KernelSecurityVulnerabilitySchema2 - })).optional(), - /** - * License compliance - */ - licenseCompliance: external_exports.object({ - status: external_exports.enum(["compliant", "non-compliant", "unknown"]), - issues: external_exports.array(external_exports.object({ - package: external_exports.string(), - license: external_exports.string(), - reason: external_exports.string() - })).optional() - }).optional(), - /** - * Summary statistics - */ - summary: external_exports.object({ - totalVulnerabilities: external_exports.number().int(), - criticalCount: external_exports.number().int(), - highCount: external_exports.number().int(), - mediumCount: external_exports.number().int(), - lowCount: external_exports.number().int(), - infoCount: external_exports.number().int() - }) -}); -var KernelSecurityPolicySchema2 = external_exports.object({ - /** - * Content Security Policy - */ - csp: external_exports.object({ - directives: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional(), - reportOnly: external_exports.boolean().default(false) - }).optional(), - /** - * CORS policy - */ - cors: external_exports.object({ - allowedOrigins: external_exports.array(external_exports.string()), - allowedMethods: external_exports.array(external_exports.string()), - allowedHeaders: external_exports.array(external_exports.string()), - allowCredentials: external_exports.boolean().default(false), - maxAge: external_exports.number().int().optional() - }).optional(), - /** - * Rate limiting - */ - rateLimit: external_exports.object({ - enabled: external_exports.boolean().default(true), - maxRequests: external_exports.number().int(), - windowMs: external_exports.number().int().describe("Time window in milliseconds"), - strategy: external_exports.enum(["fixed", "sliding", "token-bucket"]).default("sliding") - }).optional(), - /** - * Authentication requirements - */ - authentication: external_exports.object({ - required: external_exports.boolean().default(true), - methods: external_exports.array(external_exports.enum(["jwt", "oauth2", "api-key", "session", "certificate"])), - tokenExpiration: external_exports.number().int().optional().describe("Token expiration in seconds") - }).optional(), - /** - * Encryption requirements - */ - encryption: external_exports.object({ - dataAtRest: external_exports.boolean().default(false).describe("Encrypt data at rest"), - dataInTransit: external_exports.boolean().default(true).describe("Enforce HTTPS/TLS"), - algorithm: external_exports.string().optional().describe("Encryption algorithm"), - minKeyLength: external_exports.number().int().optional().describe("Minimum key length in bits") - }).optional(), - /** - * Audit logging - */ - auditLog: external_exports.object({ - enabled: external_exports.boolean().default(true), - events: external_exports.array(external_exports.string()).optional().describe("Events to log"), - retention: external_exports.number().int().optional().describe("Log retention in days") - }).optional() -}); -var PluginTrustLevelSchema2 = external_exports.enum([ - "verified", - // Official/verified plugin - "trusted", - // Trusted third-party - "community", - // Community plugin - "untrusted", - // Unverified plugin - "blocked" - // Blocked/malicious -]).describe("Trust level of the plugin"); -var PluginSecurityManifestSchema2 = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Trust level - */ - trustLevel: PluginTrustLevelSchema2, - /** - * Required permissions - */ - permissions: PermissionSetSchema22, - /** - * Sandbox configuration - */ - sandbox: SandboxConfigSchema2, - /** - * Security policy - */ - policy: KernelSecurityPolicySchema2.optional(), - /** - * Security scan results - */ - scanResults: external_exports.array(KernelSecurityScanResultSchema2).optional(), - /** - * Known vulnerabilities - */ - vulnerabilities: external_exports.array(KernelSecurityVulnerabilitySchema2).optional(), - /** - * Code signing - */ - codeSigning: external_exports.object({ - signed: external_exports.boolean(), - signature: external_exports.string().optional(), - certificate: external_exports.string().optional(), - algorithm: external_exports.string().optional(), - timestamp: external_exports.string().datetime().optional() - }).optional(), - /** - * Security certifications - */ - certifications: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Certification name (e.g., SOC 2, ISO 27001)"), - issuer: external_exports.string(), - issuedDate: external_exports.string().datetime(), - expiryDate: external_exports.string().datetime().optional(), - certificateUrl: external_exports.string().url().optional() - })).optional(), - /** - * Security contact - */ - securityContact: external_exports.object({ - email: external_exports.string().email().optional(), - url: external_exports.string().url().optional(), - pgpKey: external_exports.string().optional() - }).optional(), - /** - * Vulnerability disclosure policy - */ - vulnerabilityDisclosure: external_exports.object({ - policyUrl: external_exports.string().url().optional(), - responseTime: external_exports.number().int().optional().describe("Expected response time in hours"), - bugBounty: external_exports.boolean().default(false) - }).optional() -}); -var SNAKE_CASE_REGEX2 = /^[a-z][a-z0-9_]*$/; -var OpsFilePathSchema2 = external_exports.string().describe("Validates a file path against OPS naming conventions").superRefine((path3, ctx) => { - if (!path3.startsWith("src/")) { - return; - } - const parts = path3.split("/"); - if (parts.length > 2) { - const domainDir = parts[1]; - if (!SNAKE_CASE_REGEX2.test(domainDir)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Domain directory '${domainDir}' must be lowercase snake_case` - }); - } - } - const filename = parts[parts.length - 1]; - if (filename === "index.ts" || filename === "main.ts") return; - if (!SNAKE_CASE_REGEX2.test(filename.split(".")[0])) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Filename '${filename}' base name must be lowercase snake_case` - }); - } -}); -var OpsDomainModuleSchema2 = external_exports.object({ - name: external_exports.string().regex(SNAKE_CASE_REGEX2).describe("Module name (snake_case)"), - files: external_exports.array(external_exports.string()).describe("List of files in this module"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") -}).describe("Scanned domain module representing a plugin folder").superRefine((module, ctx) => { - if (!module.files.includes("index.ts")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Module '${module.name}' is missing an 'index.ts' entry point.` - }); - } -}); -var OpsPluginStructureSchema2 = external_exports.object({ - root: external_exports.string().describe("Root directory path of the plugin project"), - files: external_exports.array(external_exports.string()).describe("List of all file paths relative to root"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") -}).describe("Full plugin project layout validated against OPS conventions").superRefine((project, ctx) => { - if (!project.files.includes("objectstack.config.ts")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "Missing 'objectstack.config.ts' configuration file." - }); - } - project.files.filter((f) => f.startsWith("src/")).forEach((file2) => { - const result = OpsFilePathSchema2.safeParse(file2); - if (!result.success) { - result.error.issues.forEach((issue2) => { - ctx.addIssue({ ...issue2, path: [file2] }); - }); - } - }); -}); -var ValidationErrorSchema2 = external_exports.object({ - /** - * Field that failed validation - */ - field: external_exports.string().describe("Field name that failed validation"), - /** - * Human-readable error message - */ - message: external_exports.string().describe("Human-readable error message"), - /** - * Machine-readable error code (optional) - */ - code: external_exports.string().optional().describe("Machine-readable error code") -}); -var ValidationWarningSchema2 = external_exports.object({ - /** - * Field with warning - */ - field: external_exports.string().describe("Field name with warning"), - /** - * Human-readable warning message - */ - message: external_exports.string().describe("Human-readable warning message"), - /** - * Machine-readable warning code (optional) - */ - code: external_exports.string().optional().describe("Machine-readable warning code") -}); -var ValidationResultSchema2 = external_exports.object({ - /** - * Whether validation passed - */ - valid: external_exports.boolean().describe("Whether the plugin passed validation"), - /** - * Validation errors (if any) - */ - errors: external_exports.array(ValidationErrorSchema2).optional().describe("Validation errors"), - /** - * Validation warnings (non-fatal issues) - */ - warnings: external_exports.array(ValidationWarningSchema2).optional().describe("Validation warnings") -}); -var PluginMetadataSchema2 = external_exports.object({ - /** - * Unique plugin identifier (snake_case) - */ - name: external_exports.string().min(1).describe("Unique plugin identifier"), - /** - * Plugin version (semver) - */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Semantic version (e.g., 1.0.0)"), - /** - * Plugin dependencies (array of plugin names) - */ - dependencies: external_exports.array(external_exports.string()).optional().describe("Array of plugin names this plugin depends on"), - /** - * Plugin signature for cryptographic verification (optional) - */ - signature: external_exports.string().optional().describe("Cryptographic signature for plugin verification") - /** - * Additional plugin metadata - */ -}).passthrough().describe("Plugin metadata for validation"); -var SemanticVersionSchema2 = external_exports.object({ - major: external_exports.number().int().min(0).describe("Major version (breaking changes)"), - minor: external_exports.number().int().min(0).describe("Minor version (backward compatible features)"), - patch: external_exports.number().int().min(0).describe("Patch version (backward compatible fixes)"), - preRelease: external_exports.string().optional().describe("Pre-release identifier (alpha, beta, rc.1)"), - build: external_exports.string().optional().describe("Build metadata") -}).describe("Semantic version number"); -var VersionConstraintSchema2 = external_exports.union([ - external_exports.string().regex(/^[\d.]+$/).describe("Exact version: `1.2.3`"), - external_exports.string().regex(/^\^[\d.]+$/).describe("Compatible with: `^1.2.3` (`>=1.2.3 <2.0.0`)"), - external_exports.string().regex(/^~[\d.]+$/).describe("Approximately: `~1.2.3` (`>=1.2.3 <1.3.0`)"), - external_exports.string().regex(/^>=[\d.]+$/).describe("Greater than or equal: `>=1.2.3`"), - external_exports.string().regex(/^>[\d.]+$/).describe("Greater than: `>1.2.3`"), - external_exports.string().regex(/^<=[\d.]+$/).describe("Less than or equal: `<=1.2.3`"), - external_exports.string().regex(/^<[\d.]+$/).describe("Less than: `<1.2.3`"), - external_exports.string().regex(/^[\d.]+ - [\d.]+$/).describe("Range: `1.2.3 - 2.3.4`"), - external_exports.literal("*").describe("Any version"), - external_exports.literal("latest").describe("Latest stable version") -]); -var CompatibilityLevelSchema2 = external_exports.enum([ - "fully-compatible", - // 100% compatible, drop-in replacement - "backward-compatible", - // Backward compatible, new features added - "deprecated-compatible", - // Compatible but uses deprecated features - "breaking-changes", - // Breaking changes, migration required - "incompatible" - // Completely incompatible -]).describe("Compatibility level between versions"); -var BreakingChangeSchema2 = external_exports.object({ - /** - * Version where the change was introduced - */ - introducedIn: external_exports.string().describe("Version that introduced this breaking change"), - /** - * Type of breaking change - */ - type: external_exports.enum([ - "api-removed", - // API removed - "api-renamed", - // API renamed - "api-signature-changed", - // Function signature changed - "behavior-changed", - // Behavior changed - "dependency-changed", - // Dependency requirement changed - "configuration-changed", - // Configuration schema changed - "protocol-changed" - // Protocol implementation changed - ]), - /** - * What was changed - */ - description: external_exports.string(), - /** - * Migration guide - */ - migrationGuide: external_exports.string().optional().describe("How to migrate from old to new"), - /** - * Deprecated in version - */ - deprecatedIn: external_exports.string().optional().describe("Version where old API was deprecated"), - /** - * Will be removed in version - */ - removedIn: external_exports.string().optional().describe("Version where old API will be removed"), - /** - * Automated migration available - */ - automatedMigration: external_exports.boolean().default(false).describe("Whether automated migration tool is available"), - /** - * Impact severity - */ - severity: external_exports.enum(["critical", "major", "minor"]).describe("Impact severity") -}); -var DeprecationNoticeSchema2 = external_exports.object({ - /** - * Feature or API being deprecated - */ - feature: external_exports.string().describe("Deprecated feature identifier"), - /** - * Version when deprecated - */ - deprecatedIn: external_exports.string(), - /** - * Planned removal version - */ - removeIn: external_exports.string().optional(), - /** - * Reason for deprecation - */ - reason: external_exports.string(), - /** - * Recommended alternative - */ - alternative: external_exports.string().optional().describe("What to use instead"), - /** - * Migration path - */ - migrationPath: external_exports.string().optional().describe("How to migrate to alternative") -}); -var CompatibilityMatrixEntrySchema2 = external_exports.object({ - /** - * Source version - */ - from: external_exports.string().describe("Version being upgraded from"), - /** - * Target version - */ - to: external_exports.string().describe("Version being upgraded to"), - /** - * Compatibility level - */ - compatibility: CompatibilityLevelSchema2, - /** - * Breaking changes list - */ - breakingChanges: external_exports.array(BreakingChangeSchema2).optional(), - /** - * Migration required - */ - migrationRequired: external_exports.boolean().default(false), - /** - * Migration complexity - */ - migrationComplexity: external_exports.enum(["trivial", "simple", "moderate", "complex", "major"]).optional(), - /** - * Estimated migration time in hours - */ - estimatedMigrationTime: external_exports.number().optional(), - /** - * Migration script available - */ - migrationScript: external_exports.string().optional().describe("Path to migration script"), - /** - * Test coverage for migration - */ - testCoverage: external_exports.number().min(0).max(100).optional().describe("Percentage of migration covered by tests") -}); -var PluginCompatibilityMatrixSchema2 = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Current version - */ - currentVersion: external_exports.string(), - /** - * Compatibility entries - */ - compatibilityMatrix: external_exports.array(CompatibilityMatrixEntrySchema2), - /** - * Supported versions - */ - supportedVersions: external_exports.array(external_exports.object({ - version: external_exports.string(), - supported: external_exports.boolean(), - endOfLife: external_exports.string().datetime().optional().describe("End of support date"), - securitySupport: external_exports.boolean().default(false).describe("Still receives security updates") - })), - /** - * Minimum compatible version - */ - minimumCompatibleVersion: external_exports.string().optional().describe("Oldest version that can be directly upgraded") -}); -var DependencyConflictSchema2 = external_exports.object({ - /** - * Type of conflict - */ - type: external_exports.enum([ - "version-mismatch", - // Different versions required - "missing-dependency", - // Required dependency not found - "circular-dependency", - // Circular dependency detected - "incompatible-versions", - // Incompatible versions required by different plugins - "conflicting-interfaces" - // Plugins implement conflicting interfaces - ]), - /** - * Plugins involved in conflict - */ - plugins: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - version: external_exports.string(), - requirement: external_exports.string().optional().describe("What this plugin requires") - })), - /** - * Conflict description - */ - description: external_exports.string(), - /** - * Possible resolutions - */ - resolutions: external_exports.array(external_exports.object({ - strategy: external_exports.enum([ - "upgrade", - // Upgrade one or more plugins - "downgrade", - // Downgrade one or more plugins - "replace", - // Replace with alternative plugin - "disable", - // Disable conflicting plugin - "manual" - // Manual intervention required - ]), - description: external_exports.string(), - automaticResolution: external_exports.boolean().default(false), - riskLevel: external_exports.enum(["low", "medium", "high"]) - })).optional(), - /** - * Severity of conflict - */ - severity: external_exports.enum(["critical", "error", "warning", "info"]) -}); -var PluginDependencyResolutionResultSchema2 = external_exports.object({ - /** - * Resolution successful - */ - success: external_exports.boolean(), - /** - * Resolved plugin versions - */ - resolved: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - version: external_exports.string(), - resolvedVersion: external_exports.string() - })).optional(), - /** - * Conflicts found - */ - conflicts: external_exports.array(DependencyConflictSchema2).optional(), - /** - * Warnings - */ - warnings: external_exports.array(external_exports.string()).optional(), - /** - * Installation order (topologically sorted) - */ - installationOrder: external_exports.array(external_exports.string()).optional().describe("Plugin IDs in order they should be installed"), - /** - * Dependency graph - */ - dependencyGraph: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional().describe("Map of plugin ID to its dependencies") -}); -var MultiVersionSupportSchema2 = external_exports.object({ - /** - * Enable multi-version support - */ - enabled: external_exports.boolean().default(false), - /** - * Maximum concurrent versions - */ - maxConcurrentVersions: external_exports.number().int().min(1).default(2).describe("How many versions can run at the same time"), - /** - * Version selection strategy - */ - selectionStrategy: external_exports.enum([ - "latest", - // Always use latest version - "stable", - // Use latest stable version - "compatible", - // Use version compatible with dependencies - "pinned", - // Use pinned version - "canary", - // Use canary/preview version - "custom" - // Custom selection logic - ]).default("latest"), - /** - * Version routing rules - */ - routing: external_exports.array(external_exports.object({ - condition: external_exports.string().describe("Routing condition (e.g., tenant, user, feature flag)"), - version: external_exports.string().describe("Version to use when condition matches"), - priority: external_exports.number().int().default(100).describe("Rule priority") - })).optional(), - /** - * Gradual rollout configuration - */ - rollout: external_exports.object({ - enabled: external_exports.boolean().default(false), - strategy: external_exports.enum(["percentage", "blue-green", "canary"]), - percentage: external_exports.number().min(0).max(100).optional().describe("Percentage of traffic to new version"), - duration: external_exports.number().int().optional().describe("Rollout duration in milliseconds") - }).optional() -}); -var PluginVersionMetadataSchema2 = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Version number - */ - version: SemanticVersionSchema2, - /** - * Version string (computed) - */ - versionString: external_exports.string().describe("Full version string (e.g., 1.2.3-beta.1+build.123)"), - /** - * Release date - */ - releaseDate: external_exports.string().datetime(), - /** - * Release notes - */ - releaseNotes: external_exports.string().optional(), - /** - * Breaking changes - */ - breakingChanges: external_exports.array(BreakingChangeSchema2).optional(), - /** - * Deprecations - */ - deprecations: external_exports.array(DeprecationNoticeSchema2).optional(), - /** - * Compatibility matrix - */ - compatibilityMatrix: external_exports.array(CompatibilityMatrixEntrySchema2).optional(), - /** - * Security vulnerabilities fixed - */ - securityFixes: external_exports.array(external_exports.object({ - cve: external_exports.string().optional().describe("CVE identifier"), - severity: external_exports.enum(["critical", "high", "medium", "low"]), - description: external_exports.string(), - fixedIn: external_exports.string().describe("Version where vulnerability was fixed") - })).optional(), - /** - * Download statistics - */ - statistics: external_exports.object({ - downloads: external_exports.number().int().min(0).optional(), - installations: external_exports.number().int().min(0).optional(), - ratings: external_exports.number().min(0).max(5).optional() - }).optional(), - /** - * Support status - */ - support: external_exports.object({ - status: external_exports.enum(["active", "maintenance", "deprecated", "eol"]), - endOfLife: external_exports.string().datetime().optional(), - securitySupport: external_exports.boolean().default(true) - }) -}); -var ServiceScopeType2 = external_exports.enum([ - "singleton", - // Single instance shared across the application - "transient", - // New instance created each time - "scoped" - // Instance per scope (request, session, transaction, etc.) -]).describe("Service scope type"); -var ServiceMetadataSchema2 = external_exports.object({ - /** - * Service name (unique identifier) - */ - name: external_exports.string().min(1).describe("Unique service name identifier"), - /** - * Service scope type - */ - scope: ServiceScopeType2.optional().default("singleton").describe("Service scope type"), - /** - * Service type or interface name (optional) - */ - type: external_exports.string().optional().describe("Service type or interface name"), - /** - * Registration timestamp (Unix milliseconds) - */ - registeredAt: external_exports.number().int().optional().describe("Unix timestamp in milliseconds when service was registered"), - /** - * Additional metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional service-specific metadata") -}); -var ServiceRegistryConfigSchema2 = external_exports.object({ - /** - * Strict mode: throw errors on invalid operations - * @default true - */ - strictMode: external_exports.boolean().optional().default(true).describe("Throw errors on invalid operations (duplicate registration, service not found, etc.)"), - /** - * Allow overwriting existing services - * @default false - */ - allowOverwrite: external_exports.boolean().optional().default(false).describe("Allow overwriting existing service registrations"), - /** - * Enable logging for service operations - * @default false - */ - enableLogging: external_exports.boolean().optional().default(false).describe("Enable logging for service registration and retrieval"), - /** - * Custom scope types (beyond singleton, transient, scoped) - * @default ['singleton', 'transient', 'scoped'] - */ - scopeTypes: external_exports.array(external_exports.string()).optional().describe("Supported scope types"), - /** - * Maximum number of services (prevent memory leaks) - */ - maxServices: external_exports.number().int().min(1).optional().describe("Maximum number of services that can be registered") -}); -var ServiceFactoryRegistrationSchema2 = external_exports.object({ - /** - * Service name (unique identifier) - */ - name: external_exports.string().min(1).describe("Unique service name identifier"), - /** - * Service scope type - */ - scope: ServiceScopeType2.optional().default("singleton").describe("Service scope type"), - /** - * Factory type (sync or async) - */ - factoryType: external_exports.enum(["sync", "async"]).optional().default("sync").describe("Whether factory is synchronous or asynchronous"), - /** - * Whether this is a singleton (cache factory result) - */ - singleton: external_exports.boolean().optional().default(true).describe("Whether to cache the factory result (singleton pattern)") -}); -var ScopeConfigSchema2 = external_exports.object({ - /** - * Type of scope (request, session, transaction, etc.) - */ - scopeType: external_exports.string().describe("Type of scope"), - /** - * Scope identifier (optional, auto-generated if not provided) - */ - scopeId: external_exports.string().optional().describe("Unique scope identifier"), - /** - * Scope metadata (context information) - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Scope-specific context metadata") -}); -var ScopeInfoSchema2 = external_exports.object({ - /** - * Scope identifier - */ - scopeId: external_exports.string().describe("Unique scope identifier"), - /** - * Type of scope - */ - scopeType: external_exports.string().describe("Type of scope"), - /** - * Creation timestamp (Unix milliseconds) - */ - createdAt: external_exports.number().int().describe("Unix timestamp in milliseconds when scope was created"), - /** - * Number of services in this scope - */ - serviceCount: external_exports.number().int().min(0).optional().describe("Number of services registered in this scope"), - /** - * Scope metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Scope-specific context metadata") -}); -var StartupOptionsSchema2 = external_exports.object({ - /** - * Maximum time (ms) to wait for each plugin to start - * @default 30000 (30 seconds) - */ - timeout: external_exports.number().int().min(0).optional().default(3e4).describe("Maximum time in milliseconds to wait for each plugin to start"), - /** - * Whether to rollback (destroy) already-started plugins on failure - * @default true - */ - rollbackOnFailure: external_exports.boolean().optional().default(true).describe("Whether to rollback already-started plugins if any plugin fails"), - /** - * Whether to run health checks after startup - * @default false - */ - healthCheck: external_exports.boolean().optional().default(false).describe("Whether to run health checks after plugin startup"), - /** - * Whether to run plugins in parallel (if dependencies allow) - * @default false (sequential startup) - */ - parallel: external_exports.boolean().optional().default(false).describe("Whether to start plugins in parallel when dependencies allow"), - /** - * Custom context to pass to plugin lifecycle methods - */ - context: external_exports.unknown().optional().describe("Custom context object to pass to plugin lifecycle methods") -}); -var HealthStatusSchema2 = external_exports.object({ - /** - * Whether the plugin is healthy - */ - healthy: external_exports.boolean().describe("Whether the plugin is healthy"), - /** - * Health check timestamp (Unix milliseconds) - */ - timestamp: external_exports.number().int().describe("Unix timestamp in milliseconds when health check was performed"), - /** - * Optional health details (plugin-specific) - */ - details: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Optional plugin-specific health details"), - /** - * Optional error message if unhealthy - */ - message: external_exports.string().optional().describe("Error message if plugin is unhealthy") -}); -var PluginStartupResultSchema2 = external_exports.object({ - /** - * Plugin that was started - */ - plugin: external_exports.object({ - name: external_exports.string(), - version: external_exports.string().optional() - }).passthrough().describe("Plugin metadata"), - /** - * Whether startup was successful - */ - success: external_exports.boolean().describe("Whether the plugin started successfully"), - /** - * Time taken to start (milliseconds) - */ - duration: external_exports.number().min(0).describe("Time taken to start the plugin in milliseconds"), - /** - * Error if startup failed - */ - error: external_exports.object({ - name: external_exports.string().describe("Error class name"), - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Stack trace"), - code: external_exports.string().optional().describe("Error code") - }).optional().describe("Serializable error representation if startup failed"), - /** - * Health status after startup (if healthCheck enabled) - */ - health: HealthStatusSchema2.optional().describe("Health status after startup if health check was enabled") -}); -var StartupOrchestrationResultSchema2 = external_exports.object({ - /** - * Individual plugin startup results - */ - results: external_exports.array(PluginStartupResultSchema2).describe("Startup results for each plugin"), - /** - * Total time taken for all plugins (milliseconds) - */ - totalDuration: external_exports.number().min(0).describe("Total time taken for all plugins in milliseconds"), - /** - * Whether all plugins started successfully - */ - allSuccessful: external_exports.boolean().describe("Whether all plugins started successfully"), - /** - * Plugins that were rolled back (if rollbackOnFailure was enabled) - */ - rolledBack: external_exports.array(external_exports.string()).optional().describe("Names of plugins that were rolled back") -}); -var PluginVendorSchema2 = external_exports.object({ - /** - * Vendor identifier (reverse domain notation) - * Example: "com.acme", "org.apache", "com.objectstack" - */ - id: external_exports.string().regex(/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)+$/).describe("Vendor identifier (reverse domain)"), - /** - * Vendor display name - */ - name: external_exports.string(), - /** - * Vendor website - */ - website: external_exports.string().url().optional(), - /** - * Contact email - */ - email: external_exports.string().email().optional(), - /** - * Verification status - */ - verified: external_exports.boolean().default(false).describe("Whether vendor is verified by ObjectStack"), - /** - * Trust level - */ - trustLevel: external_exports.enum(["official", "verified", "community", "unverified"]).default("unverified") -}); -var PluginQualityMetricsSchema2 = external_exports.object({ - /** - * Test coverage percentage - */ - testCoverage: external_exports.number().min(0).max(100).optional(), - /** - * Documentation score (0-100) - */ - documentationScore: external_exports.number().min(0).max(100).optional(), - /** - * Code quality score (0-100) - */ - codeQuality: external_exports.number().min(0).max(100).optional(), - /** - * Security scan status - */ - securityScan: external_exports.object({ - lastScanDate: external_exports.string().datetime().optional(), - vulnerabilities: external_exports.object({ - critical: external_exports.number().int().min(0).default(0), - high: external_exports.number().int().min(0).default(0), - medium: external_exports.number().int().min(0).default(0), - low: external_exports.number().int().min(0).default(0) - }).optional(), - passed: external_exports.boolean().default(false) - }).optional(), - /** - * Conformance test results - */ - conformanceTests: external_exports.array(external_exports.object({ - protocolId: external_exports.string().describe("Protocol being tested"), - passed: external_exports.boolean(), - totalTests: external_exports.number().int().min(0), - passedTests: external_exports.number().int().min(0), - lastRunDate: external_exports.string().datetime().optional() - })).optional() -}); -var PluginStatisticsSchema2 = external_exports.object({ - /** - * Total downloads - */ - downloads: external_exports.number().int().min(0).default(0), - /** - * Downloads in the last 30 days - */ - downloadsLastMonth: external_exports.number().int().min(0).default(0), - /** - * Number of active installations - */ - activeInstallations: external_exports.number().int().min(0).default(0), - /** - * User ratings - */ - ratings: external_exports.object({ - average: external_exports.number().min(0).max(5).default(0), - count: external_exports.number().int().min(0).default(0), - distribution: external_exports.object({ - "5": external_exports.number().int().min(0).default(0), - "4": external_exports.number().int().min(0).default(0), - "3": external_exports.number().int().min(0).default(0), - "2": external_exports.number().int().min(0).default(0), - "1": external_exports.number().int().min(0).default(0) - }).optional() - }).optional(), - /** - * GitHub stars (if open source) - */ - stars: external_exports.number().int().min(0).optional(), - /** - * Number of dependent plugins - */ - dependents: external_exports.number().int().min(0).default(0) -}); -var PluginRegistryEntrySchema2 = external_exports.object({ - /** - * Plugin identifier (must match manifest.id) - */ - id: external_exports.string().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe("Plugin identifier (reverse domain notation)"), - /** - * Current version - */ - version: external_exports.string().regex(/^\d+\.\d+\.\d+$/), - /** - * Plugin display name - */ - name: external_exports.string(), - /** - * Short description - */ - description: external_exports.string().optional(), - /** - * Detailed documentation/README - */ - readme: external_exports.string().optional(), - /** - * Plugin type/category - */ - category: external_exports.enum([ - "data", - // Data management, storage, databases - "integration", - // External service integrations - "ui", - // UI components and themes - "analytics", - // Analytics and reporting - "security", - // Security, auth, compliance - "automation", - // Workflows and automation - "ai", - // AI/ML capabilities - "utility", - // General utilities - "driver", - // Database/storage drivers - "gateway", - // API gateways - "adapter" - // Runtime adapters - ]).optional(), - /** - * Tags for categorization - */ - tags: external_exports.array(external_exports.string()).optional(), - /** - * Vendor information - */ - vendor: PluginVendorSchema2, - /** - * Capability manifest (what the plugin implements/provides) - */ - capabilities: PluginCapabilityManifestSchema3.optional(), - /** - * Compatibility information - */ - compatibility: external_exports.object({ - /** - * Minimum ObjectStack version required - */ - minObjectStackVersion: external_exports.string().optional(), - /** - * Maximum ObjectStack version supported - */ - maxObjectStackVersion: external_exports.string().optional(), - /** - * Node.js version requirement - */ - nodeVersion: external_exports.string().optional(), - /** - * Supported platforms - */ - platforms: external_exports.array(external_exports.enum(["linux", "darwin", "win32", "browser"])).optional() - }).optional(), - /** - * Links and resources - */ - links: external_exports.object({ - homepage: external_exports.string().url().optional(), - repository: external_exports.string().url().optional(), - documentation: external_exports.string().url().optional(), - bugs: external_exports.string().url().optional(), - changelog: external_exports.string().url().optional() - }).optional(), - /** - * Media assets - */ - media: external_exports.object({ - icon: external_exports.string().url().optional(), - logo: external_exports.string().url().optional(), - screenshots: external_exports.array(external_exports.string().url()).optional(), - video: external_exports.string().url().optional() - }).optional(), - /** - * Quality metrics - */ - quality: PluginQualityMetricsSchema2.optional(), - /** - * Usage statistics - */ - statistics: PluginStatisticsSchema2.optional(), - /** - * License information - */ - license: external_exports.string().optional().describe("SPDX license identifier"), - /** - * Pricing (if commercial) - */ - pricing: external_exports.object({ - model: external_exports.enum(["free", "freemium", "paid", "enterprise"]), - price: external_exports.number().min(0).optional(), - currency: external_exports.string().default("USD").optional(), - billingPeriod: external_exports.enum(["one-time", "monthly", "yearly"]).optional() - }).optional(), - /** - * Publication dates - */ - publishedAt: external_exports.string().datetime().optional(), - updatedAt: external_exports.string().datetime().optional(), - /** - * Deprecation status - */ - deprecated: external_exports.boolean().default(false), - deprecationMessage: external_exports.string().optional(), - replacedBy: external_exports.string().optional().describe("Plugin ID that replaces this one"), - /** - * Feature flags - */ - flags: external_exports.object({ - experimental: external_exports.boolean().default(false), - beta: external_exports.boolean().default(false), - featured: external_exports.boolean().default(false), - verified: external_exports.boolean().default(false) - }).optional() -}); -var PluginSearchFiltersSchema2 = external_exports.object({ - /** - * Search query - */ - query: external_exports.string().optional(), - /** - * Filter by category - */ - category: external_exports.array(external_exports.string()).optional(), - /** - * Filter by tags - */ - tags: external_exports.array(external_exports.string()).optional(), - /** - * Filter by vendor trust level - */ - trustLevel: external_exports.array(external_exports.enum(["official", "verified", "community", "unverified"])).optional(), - /** - * Filter by protocols implemented - */ - implementsProtocols: external_exports.array(external_exports.string()).optional(), - /** - * Filter by pricing model - */ - pricingModel: external_exports.array(external_exports.enum(["free", "freemium", "paid", "enterprise"])).optional(), - /** - * Minimum rating - */ - minRating: external_exports.number().min(0).max(5).optional(), - /** - * Sort options - */ - sortBy: external_exports.enum([ - "relevance", - "downloads", - "rating", - "updated", - "name" - ]).optional(), - /** - * Sort order - */ - sortOrder: external_exports.enum(["asc", "desc"]).default("desc").optional(), - /** - * Pagination - */ - page: external_exports.number().int().min(1).default(1).optional(), - limit: external_exports.number().int().min(1).max(100).default(20).optional() -}); -var PluginInstallConfigSchema2 = external_exports.object({ - /** - * Plugin identifier to install - */ - pluginId: external_exports.string(), - /** - * Version to install (supports semver ranges) - */ - version: external_exports.string().optional().describe("Defaults to latest"), - /** - * Plugin-specific configuration values - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Whether to auto-update - */ - autoUpdate: external_exports.boolean().default(false).optional(), - /** - * Installation options - */ - options: external_exports.object({ - /** - * Skip dependency installation - */ - skipDependencies: external_exports.boolean().default(false).optional(), - /** - * Force reinstall - */ - force: external_exports.boolean().default(false).optional(), - /** - * Installation target - */ - target: external_exports.enum(["system", "space", "user"]).default("space").optional() - }).optional() -}); -var VulnerabilitySeverity2 = external_exports.enum([ - "critical", - "high", - "medium", - "low", - "info" -]).describe("Severity level of a security vulnerability"); -var SecurityVulnerabilitySchema2 = external_exports.object({ - /** - * CVE identifier (if applicable) - */ - cve: external_exports.string().regex(/^CVE-\d{4}-\d+$/).optional().describe("CVE identifier"), - /** - * Vulnerability identifier (GHSA, SNYK, etc.) - */ - id: external_exports.string().describe("Vulnerability ID"), - /** - * Title - */ - title: external_exports.string().describe("Short title summarizing the vulnerability"), - /** - * Description - */ - description: external_exports.string().describe("Detailed description of the vulnerability"), - /** - * Severity - */ - severity: VulnerabilitySeverity2.describe("Severity level of this vulnerability"), - /** - * CVSS score (0-10) - */ - cvss: external_exports.number().min(0).max(10).optional().describe("CVSS score ranging from 0 to 10"), - /** - * Affected package - */ - package: external_exports.object({ - name: external_exports.string().describe("Name of the affected package"), - version: external_exports.string().describe("Version of the affected package"), - ecosystem: external_exports.string().optional().describe("Package ecosystem (e.g., npm, pip, maven)") - }).describe("Affected package information"), - /** - * Vulnerable version range - */ - vulnerableVersions: external_exports.string().describe("Semver range of vulnerable versions"), - /** - * Patched versions - */ - patchedVersions: external_exports.string().optional().describe("Semver range of patched versions"), - /** - * References - */ - references: external_exports.array(external_exports.object({ - type: external_exports.enum(["advisory", "article", "report", "web"]).describe("Type of reference source"), - url: external_exports.string().url().describe("URL of the reference") - })).default([]).describe("External references related to the vulnerability"), - /** - * CWE (Common Weakness Enumeration) - */ - cwe: external_exports.array(external_exports.string()).default([]).describe("CWE identifiers associated with this vulnerability"), - /** - * Published date - */ - publishedAt: external_exports.string().datetime().optional().describe("ISO 8601 date when the vulnerability was published"), - /** - * Mitigation advice - */ - mitigation: external_exports.string().optional().describe("Recommended steps to mitigate the vulnerability") -}).describe("A known security vulnerability in a package dependency"); -var SecurityScanResultSchema2 = external_exports.object({ - /** - * Scan identifier - */ - scanId: external_exports.string().uuid().describe("Unique identifier for this security scan"), - /** - * Plugin being scanned - */ - plugin: external_exports.object({ - id: external_exports.string().describe("Plugin identifier"), - version: external_exports.string().describe("Plugin version that was scanned") - }).describe("Plugin that was scanned"), - /** - * Scan timestamp - */ - scannedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the scan was performed"), - /** - * Scanner information - */ - scanner: external_exports.object({ - name: external_exports.string().describe("Scanner name (e.g., snyk, osv, trivy)"), - version: external_exports.string().describe("Version of the scanner tool") - }).describe("Information about the scanner tool used"), - /** - * Scan status - */ - status: external_exports.enum(["passed", "failed", "warning"]).describe("Overall result status of the security scan"), - /** - * Vulnerabilities found - */ - vulnerabilities: external_exports.array(SecurityVulnerabilitySchema2).describe("List of vulnerabilities discovered during the scan"), - /** - * Vulnerability summary - */ - summary: external_exports.object({ - critical: external_exports.number().int().min(0).default(0).describe("Count of critical severity vulnerabilities"), - high: external_exports.number().int().min(0).default(0).describe("Count of high severity vulnerabilities"), - medium: external_exports.number().int().min(0).default(0).describe("Count of medium severity vulnerabilities"), - low: external_exports.number().int().min(0).default(0).describe("Count of low severity vulnerabilities"), - info: external_exports.number().int().min(0).default(0).describe("Count of informational severity vulnerabilities"), - total: external_exports.number().int().min(0).default(0).describe("Total count of all vulnerabilities") - }).describe("Summary counts of vulnerabilities by severity"), - /** - * License compliance issues - */ - licenseIssues: external_exports.array(external_exports.object({ - package: external_exports.string().describe("Name of the package with a license issue"), - license: external_exports.string().describe("License identifier of the package"), - reason: external_exports.string().describe("Reason the license is flagged"), - severity: external_exports.enum(["error", "warning", "info"]).describe("Severity of the license compliance issue") - })).default([]).describe("License compliance issues found during the scan"), - /** - * Code quality issues - */ - codeQuality: external_exports.object({ - score: external_exports.number().min(0).max(100).optional().describe("Overall code quality score from 0 to 100"), - issues: external_exports.array(external_exports.object({ - type: external_exports.enum(["security", "quality", "style"]).describe("Category of the code quality issue"), - severity: external_exports.enum(["error", "warning", "info"]).describe("Severity of the code quality issue"), - message: external_exports.string().describe("Description of the code quality issue"), - file: external_exports.string().optional().describe("File path where the issue was found"), - line: external_exports.number().int().optional().describe("Line number where the issue was found") - })).default([]).describe("List of individual code quality issues") - }).optional().describe("Code quality analysis results"), - /** - * Next scan scheduled - */ - nextScanAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp for the next scheduled scan") -}).describe("Result of a security scan performed on a plugin"); -var SecurityPolicySchema2 = external_exports.object({ - /** - * Policy identifier - */ - id: external_exports.string().describe("Unique identifier for the security policy"), - /** - * Policy name - */ - name: external_exports.string().describe("Human-readable name of the security policy"), - /** - * Automatic scanning - */ - autoScan: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Whether automatic scanning is enabled"), - frequency: external_exports.enum(["on-publish", "daily", "weekly", "monthly"]).default("daily").describe("How often automatic scans are performed") - }).describe("Automatic security scanning configuration"), - /** - * Vulnerability thresholds - */ - thresholds: external_exports.object({ - /** - * Block plugin if critical vulnerabilities exceed this - */ - maxCritical: external_exports.number().int().min(0).default(0).describe("Maximum allowed critical vulnerabilities before blocking"), - /** - * Block plugin if high vulnerabilities exceed this - */ - maxHigh: external_exports.number().int().min(0).default(0).describe("Maximum allowed high vulnerabilities before blocking"), - /** - * Warn if medium vulnerabilities exceed this - */ - maxMedium: external_exports.number().int().min(0).default(5).describe("Maximum allowed medium vulnerabilities before warning") - }).describe("Vulnerability count thresholds for policy enforcement"), - /** - * Allowed licenses - */ - allowedLicenses: external_exports.array(external_exports.string()).default([ - "MIT", - "Apache-2.0", - "BSD-3-Clause", - "BSD-2-Clause", - "ISC" - ]).describe("List of SPDX license identifiers that are permitted"), - /** - * Prohibited licenses - */ - prohibitedLicenses: external_exports.array(external_exports.string()).default([ - "GPL-3.0", - "AGPL-3.0" - ]).describe("List of SPDX license identifiers that are prohibited"), - /** - * Code signing requirements - */ - codeSigning: external_exports.object({ - required: external_exports.boolean().default(false).describe("Whether code signing is required for plugins"), - allowedSigners: external_exports.array(external_exports.string()).default([]).describe("List of trusted signer identities") - }).optional().describe("Code signing requirements for plugin artifacts"), - /** - * Sandbox restrictions - */ - sandbox: external_exports.object({ - /** - * Restrict network access - */ - networkAccess: external_exports.enum(["none", "localhost", "allowlist", "all"]).default("all").describe("Level of network access granted to the plugin"), - /** - * Allowed network destinations (if allowlist) - */ - allowedDestinations: external_exports.array(external_exports.string()).default([]).describe("Permitted network destinations when using allowlist mode"), - /** - * File system access - */ - filesystemAccess: external_exports.enum(["none", "read-only", "temp-only", "full"]).default("full").describe("Level of file system access granted to the plugin"), - /** - * Maximum memory (MB) - */ - maxMemoryMB: external_exports.number().int().positive().optional().describe("Maximum memory allocation in megabytes"), - /** - * Maximum CPU time (seconds) - */ - maxCPUSeconds: external_exports.number().int().positive().optional().describe("Maximum CPU time allowed in seconds") - }).optional().describe("Sandbox restrictions for plugin execution") -}).describe("Security policy governing plugin scanning and enforcement"); -var PackageDependencySchema2 = external_exports.object({ - /** - * Package name/ID - */ - name: external_exports.string().describe("Package name or identifier"), - /** - * Version constraint (semver range) - */ - versionConstraint: external_exports.string().describe("Semver range (e.g., `^1.0.0`, `>=2.0.0 <3.0.0`)"), - /** - * Dependency type - */ - type: external_exports.enum(["required", "optional", "peer", "dev"]).default("required").describe("Category of the dependency relationship"), - /** - * Resolved version (filled during resolution) - */ - resolvedVersion: external_exports.string().optional().describe("Concrete version resolved during dependency resolution") -}).describe("A package dependency with its version constraint"); -var DependencyGraphNodeSchema2 = external_exports.object({ - /** - * Package identifier - */ - id: external_exports.string().describe("Unique identifier of the package"), - /** - * Package version - */ - version: external_exports.string().describe("Resolved version of the package"), - /** - * Dependencies of this package - */ - dependencies: external_exports.array(PackageDependencySchema2).default([]).describe("Dependencies required by this package"), - /** - * Depth in dependency tree - */ - depth: external_exports.number().int().min(0).describe("Depth level in the dependency tree (0 = root)"), - /** - * Whether this is a direct dependency - */ - isDirect: external_exports.boolean().describe("Whether this is a direct (top-level) dependency"), - /** - * Package metadata - */ - metadata: external_exports.object({ - name: external_exports.string().describe("Display name of the package"), - description: external_exports.string().optional().describe("Short description of the package"), - license: external_exports.string().optional().describe("SPDX license identifier of the package"), - homepage: external_exports.string().url().optional().describe("Homepage URL of the package") - }).optional().describe("Additional metadata about the package") -}).describe("A node in the dependency graph representing a resolved package"); -var DependencyGraphSchema2 = external_exports.object({ - /** - * Root package - */ - root: external_exports.object({ - id: external_exports.string().describe("Identifier of the root package"), - version: external_exports.string().describe("Version of the root package") - }).describe("Root package of the dependency graph"), - /** - * All nodes in the graph - */ - nodes: external_exports.array(DependencyGraphNodeSchema2).describe("All resolved package nodes in the dependency graph"), - /** - * Edges (dependency relationships) - */ - edges: external_exports.array(external_exports.object({ - from: external_exports.string().describe("Package ID"), - to: external_exports.string().describe("Package ID"), - constraint: external_exports.string().describe("Version constraint") - })).describe("Directed edges representing dependency relationships"), - /** - * Resolution statistics - */ - stats: external_exports.object({ - totalDependencies: external_exports.number().int().min(0).describe("Total number of resolved dependencies"), - directDependencies: external_exports.number().int().min(0).describe("Number of direct (top-level) dependencies"), - maxDepth: external_exports.number().int().min(0).describe("Maximum depth of the dependency tree") - }).describe("Summary statistics for the dependency graph") -}).describe("Complete dependency graph for a package and its transitive dependencies"); -var PackageDependencyConflictSchema2 = external_exports.object({ - /** - * Package with conflict - */ - package: external_exports.string().describe("Name of the package with conflicting version requirements"), - /** - * Conflicting versions - */ - conflicts: external_exports.array(external_exports.object({ - version: external_exports.string().describe("Conflicting version of the package"), - requestedBy: external_exports.array(external_exports.string()).describe("Packages that require this version"), - constraint: external_exports.string().describe("Semver constraint that produced this version requirement") - })).describe("List of conflicting version requirements"), - /** - * Suggested resolution - */ - resolution: external_exports.object({ - strategy: external_exports.enum(["pick-highest", "pick-lowest", "manual"]).describe("Strategy used to resolve the conflict"), - version: external_exports.string().optional().describe("Resolved version selected by the strategy"), - reason: external_exports.string().optional().describe("Explanation of why this resolution was chosen") - }).optional().describe("Suggested resolution for the conflict"), - /** - * Severity - */ - severity: external_exports.enum(["error", "warning", "info"]).describe("Severity level of the dependency conflict") -}).describe("A detected conflict between dependency version requirements"); -var PackageDependencyResolutionResultSchema2 = external_exports.object({ - /** - * Resolution status - */ - status: external_exports.enum(["success", "conflict", "error"]).describe("Overall status of the dependency resolution"), - /** - * Resolved dependency graph - */ - graph: DependencyGraphSchema2.optional().describe("Resolved dependency graph if resolution succeeded"), - /** - * Conflicts detected - */ - conflicts: external_exports.array(PackageDependencyConflictSchema2).default([]).describe("List of dependency conflicts detected during resolution"), - /** - * Errors encountered - */ - errors: external_exports.array(external_exports.object({ - package: external_exports.string().describe("Name of the package that caused the error"), - error: external_exports.string().describe("Error message describing what went wrong") - })).default([]).describe("Errors encountered during dependency resolution"), - /** - * Installation order (topological sort) - */ - installOrder: external_exports.array(external_exports.string()).default([]).describe("Topologically sorted list of package IDs for installation"), - /** - * Resolution time (ms) - */ - resolvedIn: external_exports.number().int().min(0).optional().describe("Time taken to resolve dependencies in milliseconds") -}).describe("Result of a dependency resolution process"); -var SBOMEntrySchema2 = external_exports.object({ - /** - * Component name - */ - name: external_exports.string().describe("Name of the software component"), - /** - * Component version - */ - version: external_exports.string().describe("Version of the software component"), - /** - * Package URL (purl) - */ - purl: external_exports.string().optional().describe("Package URL identifier"), - /** - * License - */ - license: external_exports.string().optional().describe("SPDX license identifier of the component"), - /** - * Hashes - */ - hashes: external_exports.object({ - sha256: external_exports.string().optional().describe("SHA-256 hash of the component artifact"), - sha512: external_exports.string().optional().describe("SHA-512 hash of the component artifact") - }).optional().describe("Cryptographic hashes for integrity verification"), - /** - * Supplier - */ - supplier: external_exports.object({ - name: external_exports.string().describe("Name of the component supplier"), - url: external_exports.string().url().optional().describe("URL of the component supplier") - }).optional().describe("Supplier information for the component"), - /** - * External references - */ - externalRefs: external_exports.array(external_exports.object({ - type: external_exports.enum(["website", "repository", "documentation", "issue-tracker"]).describe("Type of external reference"), - url: external_exports.string().url().describe("URL of the external reference") - })).default([]).describe("External references related to the component") -}).describe("A single entry in a Software Bill of Materials"); -var SBOMSchema2 = external_exports.object({ - /** - * SBOM format - */ - format: external_exports.enum(["spdx", "cyclonedx"]).default("cyclonedx").describe("SBOM standard format used"), - /** - * SBOM version - */ - version: external_exports.string().describe("Version of the SBOM specification"), - /** - * Plugin metadata - */ - plugin: external_exports.object({ - id: external_exports.string().describe("Plugin identifier"), - version: external_exports.string().describe("Plugin version"), - name: external_exports.string().describe("Human-readable plugin name") - }).describe("Metadata about the plugin this SBOM describes"), - /** - * Components (dependencies) - */ - components: external_exports.array(SBOMEntrySchema2).describe("List of software components included in the plugin"), - /** - * Generation timestamp - */ - generatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the SBOM was generated"), - /** - * Generator tool - */ - generator: external_exports.object({ - name: external_exports.string().describe("Name of the SBOM generator tool"), - version: external_exports.string().describe("Version of the SBOM generator tool") - }).optional().describe("Tool used to generate this SBOM") -}).describe("Software Bill of Materials for a plugin"); -var PluginProvenanceSchema2 = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string().describe("Unique identifier of the plugin"), - /** - * Plugin version - */ - version: external_exports.string().describe("Version of the plugin artifact"), - /** - * Build information - */ - build: external_exports.object({ - /** - * Build timestamp - */ - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the build was produced"), - /** - * Build environment - */ - environment: external_exports.object({ - os: external_exports.string().describe("Operating system used for the build"), - arch: external_exports.string().describe("CPU architecture used for the build"), - nodeVersion: external_exports.string().describe("Node.js version used for the build") - }).optional().describe("Environment details where the build was executed"), - /** - * Source repository - */ - source: external_exports.object({ - repository: external_exports.string().url().describe("URL of the source repository"), - commit: external_exports.string().regex(/^[a-f0-9]{40}$/).describe("Full SHA-1 commit hash of the source"), - branch: external_exports.string().optional().describe("Branch name the build was produced from"), - tag: external_exports.string().optional().describe("Git tag associated with the build") - }).optional().describe("Source repository information for the build"), - /** - * Builder identity - */ - builder: external_exports.object({ - name: external_exports.string().describe("Name of the person or system that produced the build"), - email: external_exports.string().email().optional().describe("Email address of the builder") - }).optional().describe("Identity of the builder who produced the artifact") - }).describe("Build provenance information"), - /** - * Artifact hashes - */ - artifacts: external_exports.array(external_exports.object({ - filename: external_exports.string().describe("Name of the artifact file"), - sha256: external_exports.string().describe("SHA-256 hash of the artifact"), - size: external_exports.number().int().positive().describe("Size of the artifact in bytes") - })).describe("List of build artifacts with integrity hashes"), - /** - * Signatures - */ - signatures: external_exports.array(external_exports.object({ - algorithm: external_exports.enum(["rsa", "ecdsa", "ed25519"]).describe("Cryptographic algorithm used for signing"), - publicKey: external_exports.string().describe("Public key used to verify the signature"), - signature: external_exports.string().describe("Digital signature value"), - signedBy: external_exports.string().describe("Identity of the signer"), - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the signature was created") - })).default([]).describe("Cryptographic signatures for the plugin artifact"), - /** - * Attestations - */ - attestations: external_exports.array(external_exports.object({ - type: external_exports.enum(["code-review", "security-scan", "test-results", "ci-build"]).describe("Type of attestation"), - status: external_exports.enum(["passed", "failed"]).describe("Result status of the attestation"), - url: external_exports.string().url().optional().describe("URL with details about the attestation"), - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp when the attestation was issued") - })).default([]).describe("Verification attestations for the plugin") -}).describe("Verifiable provenance and chain of custody for a plugin artifact"); -var PluginTrustScoreSchema2 = external_exports.object({ - /** - * Plugin identifier - */ - pluginId: external_exports.string().describe("Unique identifier of the plugin"), - /** - * Overall trust score (0-100) - */ - score: external_exports.number().min(0).max(100).describe("Overall trust score from 0 to 100"), - /** - * Score components - */ - components: external_exports.object({ - /** - * Vendor reputation (0-100) - */ - vendorReputation: external_exports.number().min(0).max(100).describe("Vendor reputation score from 0 to 100"), - /** - * Security scan results (0-100) - */ - securityScore: external_exports.number().min(0).max(100).describe("Security scan results score from 0 to 100"), - /** - * Code quality (0-100) - */ - codeQuality: external_exports.number().min(0).max(100).describe("Code quality score from 0 to 100"), - /** - * Community engagement (0-100) - */ - communityScore: external_exports.number().min(0).max(100).describe("Community engagement score from 0 to 100"), - /** - * Update frequency (0-100) - */ - maintenanceScore: external_exports.number().min(0).max(100).describe("Maintenance and update frequency score from 0 to 100") - }).describe("Individual score components contributing to the overall trust score"), - /** - * Trust level - */ - level: external_exports.enum(["verified", "trusted", "neutral", "untrusted", "blocked"]).describe("Computed trust level based on the overall score"), - /** - * Verification badges - */ - badges: external_exports.array(external_exports.enum([ - "official", - // Official ObjectStack plugin - "verified-vendor", - // Verified vendor - "security-scanned", - // Passed security scan - "code-signed", - // Digitally signed - "open-source", - // Open source - "popular" - // High downloads - ])).default([]).describe("Verification badges earned by the plugin"), - /** - * Last updated - */ - updatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp when the trust score was last updated") -}).describe("Trust score and verification status for a plugin"); -var PluginSecurityProtocol = { - VulnerabilitySeverity: VulnerabilitySeverity2, - SecurityVulnerability: SecurityVulnerabilitySchema2, - SecurityScanResult: SecurityScanResultSchema2, - SecurityPolicy: SecurityPolicySchema2, - PackageDependency: PackageDependencySchema2, - DependencyGraphNode: DependencyGraphNodeSchema2, - DependencyGraph: DependencyGraphSchema2, - DependencyConflict: PackageDependencyConflictSchema2, - DependencyResolutionResult: PackageDependencyResolutionResultSchema2, - SBOMEntry: SBOMEntrySchema2, - SBOM: SBOMSchema2, - PluginProvenance: PluginProvenanceSchema2, - PluginTrustScore: PluginTrustScoreSchema2 -}; -var cloud_exports = {}; -__export4(cloud_exports, { - AnalyticsTimeRangeSchema: () => AnalyticsTimeRangeSchema, - AppDiscoveryRequestSchema: () => AppDiscoveryRequestSchema, - AppDiscoveryResponseSchema: () => AppDiscoveryResponseSchema, - AppSubscriptionSchema: () => AppSubscriptionSchema, - ArtifactDownloadResponseSchema: () => ArtifactDownloadResponseSchema, - ArtifactReferenceSchema: () => ArtifactReferenceSchema2, - CreateListingRequestSchema: () => CreateListingRequestSchema, - CuratedCollectionSchema: () => CuratedCollectionSchema, - FeaturedListingSchema: () => FeaturedListingSchema, - InstalledAppSummarySchema: () => InstalledAppSummarySchema, - ListInstalledAppsRequestSchema: () => ListInstalledAppsRequestSchema, - ListInstalledAppsResponseSchema: () => ListInstalledAppsResponseSchema, - ListReviewsRequestSchema: () => ListReviewsRequestSchema, - ListReviewsResponseSchema: () => ListReviewsResponseSchema, - ListingActionRequestSchema: () => ListingActionRequestSchema, - ListingStatusSchema: () => ListingStatusSchema2, - MarketplaceCategorySchema: () => MarketplaceCategorySchema2, - MarketplaceHealthMetricsSchema: () => MarketplaceHealthMetricsSchema, - MarketplaceInstallRequestSchema: () => MarketplaceInstallRequestSchema, - MarketplaceInstallResponseSchema: () => MarketplaceInstallResponseSchema, - MarketplaceListingSchema: () => MarketplaceListingSchema2, - MarketplaceSearchRequestSchema: () => MarketplaceSearchRequestSchema, - MarketplaceSearchResponseSchema: () => MarketplaceSearchResponseSchema, - PackageSubmissionSchema: () => PackageSubmissionSchema, - PolicyActionSchema: () => PolicyActionSchema, - PolicyViolationTypeSchema: () => PolicyViolationTypeSchema, - PricingModelSchema: () => PricingModelSchema2, - PublisherProfileSchema: () => PublisherProfileSchema, - PublisherSchema: () => PublisherSchema, - PublisherVerificationSchema: () => PublisherVerificationSchema2, - PublishingAnalyticsRequestSchema: () => PublishingAnalyticsRequestSchema, - PublishingAnalyticsResponseSchema: () => PublishingAnalyticsResponseSchema, - RecommendationReasonSchema: () => RecommendationReasonSchema, - RecommendedAppSchema: () => RecommendedAppSchema, - RejectionReasonSchema: () => RejectionReasonSchema, - ReleaseChannelSchema: () => ReleaseChannelSchema, - ReviewCriterionSchema: () => ReviewCriterionSchema, - ReviewDecisionSchema: () => ReviewDecisionSchema, - ReviewModerationStatusSchema: () => ReviewModerationStatusSchema, - SubmissionReviewSchema: () => SubmissionReviewSchema, - SubmitReviewRequestSchema: () => SubmitReviewRequestSchema, - SubscriptionStatusSchema: () => SubscriptionStatusSchema, - TimeSeriesPointSchema: () => TimeSeriesPointSchema, - TrendingListingSchema: () => TrendingListingSchema, - UpdateListingRequestSchema: () => UpdateListingRequestSchema, - UserReviewSchema: () => UserReviewSchema, - VersionReleaseSchema: () => VersionReleaseSchema -}); -var PublisherVerificationSchema2 = external_exports.enum([ - "unverified", - // Not yet verified - "pending", - // Verification in progress - "verified", - // Identity verified by platform - "trusted", - // Trusted publisher (track record of quality) - "partner" - // Official platform partner -]).describe("Publisher verification status"); -var PublisherSchema = external_exports.object({ - /** Publisher unique identifier */ - id: external_exports.string().describe("Publisher ID"), - /** Display name */ - name: external_exports.string().describe("Publisher display name"), - /** Publisher type */ - type: external_exports.enum(["individual", "organization"]).describe("Publisher type"), - /** Verification status */ - verification: PublisherVerificationSchema2.default("unverified").describe("Publisher verification status"), - /** Contact email */ - email: external_exports.string().email().optional().describe("Contact email"), - /** Website URL */ - website: external_exports.string().url().optional().describe("Publisher website"), - /** Organization logo URL */ - logoUrl: external_exports.string().url().optional().describe("Publisher logo URL"), - /** Short description/bio */ - description: external_exports.string().optional().describe("Publisher description"), - /** Registration date */ - registeredAt: external_exports.string().datetime().optional().describe("Publisher registration timestamp") -}).describe("Developer or organization that publishes packages"); -var ArtifactReferenceSchema2 = external_exports.object({ - /** Artifact download URL */ - url: external_exports.string().url().describe("Artifact download URL"), - /** SHA256 integrity checksum */ - sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).describe("SHA256 checksum"), - /** File size in bytes */ - size: external_exports.number().int().positive().describe("Artifact size in bytes"), - /** Artifact format */ - format: external_exports.enum(["tgz", "zip"]).default("tgz").describe("Artifact format"), - /** Upload timestamp */ - uploadedAt: external_exports.string().datetime().describe("Upload timestamp") -}).describe("Reference to a downloadable package artifact"); -var ArtifactDownloadResponseSchema = external_exports.object({ - /** Pre-signed or direct download URL */ - downloadUrl: external_exports.string().url().describe("Artifact download URL (may be pre-signed)"), - /** SHA256 checksum for download verification */ - sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).describe("SHA256 checksum for verification"), - /** File size in bytes */ - size: external_exports.number().int().positive().describe("Artifact size in bytes"), - /** Artifact format */ - format: external_exports.enum(["tgz", "zip"]).describe("Artifact format"), - /** URL expiration time (for pre-signed URLs) */ - expiresAt: external_exports.string().datetime().optional().describe("URL expiration timestamp for pre-signed URLs") -}).describe("Artifact download response with integrity metadata"); -var MarketplaceCategorySchema2 = external_exports.enum([ - "crm", - // Customer Relationship Management - "erp", - // Enterprise Resource Planning - "hr", - // Human Resources - "finance", - // Finance & Accounting - "project", - // Project Management - "collaboration", - // Collaboration & Communication - "analytics", - // Analytics & Reporting - "integration", - // Integrations & Connectors - "automation", - // Automation & Workflows - "ai", - // AI & Machine Learning - "security", - // Security & Compliance - "developer-tools", - // Developer Tools - "ui-theme", - // UI Themes & Appearance - "storage", - // Storage & Drivers - "other" - // Other / Uncategorized -]).describe("Marketplace package category"); -var ListingStatusSchema2 = external_exports.enum([ - "draft", - // Not yet submitted - "submitted", - // Submitted for review - "in-review", - // Under review - "approved", - // Approved, ready to publish - "published", - // Live on marketplace - "rejected", - // Review rejected - "suspended", - // Suspended by platform (policy violation) - "deprecated", - // Deprecated by publisher - "unlisted" - // Available by direct link only -]).describe("Marketplace listing status"); -var PricingModelSchema2 = external_exports.enum([ - "free", - // Free to install - "freemium", - // Free with paid premium features - "paid", - // Requires purchase - "subscription", - // Recurring subscription - "usage-based", - // Pay per usage - "contact-sales" - // Enterprise pricing, contact for quote -]).describe("Package pricing model"); -var MarketplaceListingSchema2 = external_exports.object({ - /** Listing ID (matches package ID) */ - id: external_exports.string().describe("Listing ID (matches package manifest ID)"), - /** Package ID (reverse domain notation) */ - packageId: external_exports.string().describe("Package identifier"), - /** Publisher information */ - publisherId: external_exports.string().describe("Publisher ID"), - /** Current listing status */ - status: ListingStatusSchema2.default("draft").describe("Publication state: draft, published, under-review, suspended, deprecated, or unlisted"), - /** Display name */ - name: external_exports.string().describe("Display name"), - /** Tagline (short description for cards/search results) */ - tagline: external_exports.string().max(120).optional().describe("Short tagline (max 120 chars)"), - /** Full description (supports Markdown) */ - description: external_exports.string().optional().describe("Full description (Markdown)"), - /** Category */ - category: MarketplaceCategorySchema2.describe("Package category"), - /** Additional tags for search discovery */ - tags: external_exports.array(external_exports.string()).optional().describe("Search tags"), - /** Icon/logo URL */ - iconUrl: external_exports.string().url().optional().describe("Package icon URL"), - /** Screenshot URLs */ - screenshots: external_exports.array(external_exports.object({ - url: external_exports.string().url(), - caption: external_exports.string().optional() - })).optional().describe("Screenshots"), - /** Documentation URL */ - documentationUrl: external_exports.string().url().optional().describe("Documentation URL"), - /** Support URL */ - supportUrl: external_exports.string().url().optional().describe("Support URL"), - /** Source repository URL (if open source) */ - repositoryUrl: external_exports.string().url().optional().describe("Source repository URL"), - /** Pricing model */ - pricing: PricingModelSchema2.default("free").describe("Pricing model"), - /** Price in cents (if paid) */ - priceInCents: external_exports.number().int().min(0).optional().describe("Price in cents (e.g. 999 = $9.99)"), - /** Latest published version */ - latestVersion: external_exports.string().describe("Latest published version"), - /** Minimum platform version required */ - minPlatformVersion: external_exports.string().optional().describe("Minimum ObjectStack platform version"), - /** Available versions for installation */ - versions: external_exports.array(external_exports.object({ - version: external_exports.string().describe("Version string"), - releaseDate: external_exports.string().datetime().describe("Release date"), - releaseNotes: external_exports.string().optional().describe("Release notes"), - minPlatformVersion: external_exports.string().optional().describe("Minimum platform version"), - deprecated: external_exports.boolean().default(false).describe("Whether this version is deprecated"), - /** Artifact reference for this version */ - artifact: ArtifactReferenceSchema2.optional().describe("Downloadable artifact for this version") - })).optional().describe("Published versions"), - /** Aggregate statistics */ - stats: external_exports.object({ - totalInstalls: external_exports.number().int().min(0).default(0).describe("Total installs"), - activeInstalls: external_exports.number().int().min(0).default(0).describe("Active installs"), - averageRating: external_exports.number().min(0).max(5).optional().describe("Average user rating (0-5)"), - totalRatings: external_exports.number().int().min(0).default(0).describe("Total ratings count"), - totalReviews: external_exports.number().int().min(0).default(0).describe("Total reviews count") - }).optional().describe("Aggregate marketplace statistics"), - /** First published date */ - publishedAt: external_exports.string().datetime().optional().describe("First published timestamp"), - /** Last updated date */ - updatedAt: external_exports.string().datetime().optional().describe("Last updated timestamp") -}).describe("Public-facing package listing on the marketplace"); -var PackageSubmissionSchema = external_exports.object({ - /** Submission ID */ - id: external_exports.string().describe("Submission ID"), - /** Package ID */ - packageId: external_exports.string().describe("Package identifier"), - /** Version being submitted */ - version: external_exports.string().describe("Version being submitted"), - /** Publisher ID */ - publisherId: external_exports.string().describe("Publisher submitting"), - /** Submission status */ - status: external_exports.enum([ - "pending", - // Awaiting review - "scanning", - // Automated scan in progress - "in-review", - // Under manual review - "changes-requested", - // Reviewer requests changes - "approved", - // Approved for publishing - "rejected" - // Rejected - ]).default("pending").describe("Review status"), - /** - * Package artifact URL or reference. - * Points to the built package bundle for review. - */ - artifactUrl: external_exports.string().describe("Package artifact URL for review"), - /** Release notes for this version */ - releaseNotes: external_exports.string().optional().describe("Release notes for this version"), - /** Whether this is the first submission (new listing) vs version update */ - isNewListing: external_exports.boolean().default(false).describe("Whether this is a new listing submission"), - /** Automated scan results */ - scanResults: external_exports.object({ - /** Whether automated scan passed */ - passed: external_exports.boolean(), - /** Security scan score (0-100) */ - securityScore: external_exports.number().min(0).max(100).optional(), - /** Compatibility check passed */ - compatibilityCheck: external_exports.boolean().optional(), - /** Issues found during scan */ - issues: external_exports.array(external_exports.object({ - severity: external_exports.enum(["critical", "high", "medium", "low", "info"]), - message: external_exports.string(), - file: external_exports.string().optional(), - line: external_exports.number().optional() - })).optional() - }).optional().describe("Automated scan results"), - /** Reviewer notes (from platform reviewer) */ - reviewerNotes: external_exports.string().optional().describe("Notes from the platform reviewer"), - /** Submitted timestamp */ - submittedAt: external_exports.string().datetime().optional().describe("Submission timestamp"), - /** Review completed timestamp */ - reviewedAt: external_exports.string().datetime().optional().describe("Review completion timestamp") -}).describe("Developer submission of a package version for review"); -var MarketplaceSearchRequestSchema = external_exports.object({ - /** Search query string */ - query: external_exports.string().optional().describe("Full-text search query"), - /** Filter by category */ - category: MarketplaceCategorySchema2.optional().describe("Filter by category"), - /** Filter by tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags"), - /** Filter by pricing model */ - pricing: PricingModelSchema2.optional().describe("Filter by pricing model"), - /** Filter by publisher verification level */ - publisherVerification: PublisherVerificationSchema2.optional().describe("Filter by publisher verification level"), - /** Sort by */ - sortBy: external_exports.enum([ - "relevance", - // Best match (default for search) - "popularity", - // Most installs - "rating", - // Highest rated - "newest", - // Most recently published - "updated", - // Most recently updated - "name" - // Alphabetical - ]).default("relevance").describe("Sort field"), - /** Sort direction */ - sortDirection: external_exports.enum(["asc", "desc"]).default("desc").describe("Sort direction"), - /** Pagination: page number */ - page: external_exports.number().int().min(1).default(1).describe("Page number"), - /** Pagination: items per page */ - pageSize: external_exports.number().int().min(1).max(100).default(20).describe("Items per page"), - /** Filter by minimum platform version compatibility */ - platformVersion: external_exports.string().optional().describe("Filter by platform version compatibility") -}).describe("Marketplace search request"); -var MarketplaceSearchResponseSchema = external_exports.object({ - /** Search results */ - items: external_exports.array(MarketplaceListingSchema2).describe("Search result listings"), - /** Total count (for pagination) */ - total: external_exports.number().int().min(0).describe("Total matching results"), - /** Current page */ - page: external_exports.number().int().min(1).describe("Current page number"), - /** Items per page */ - pageSize: external_exports.number().int().min(1).describe("Items per page"), - /** Facets for filtering */ - facets: external_exports.object({ - categories: external_exports.array(external_exports.object({ - category: MarketplaceCategorySchema2, - count: external_exports.number().int().min(0) - })).optional(), - pricing: external_exports.array(external_exports.object({ - model: PricingModelSchema2, - count: external_exports.number().int().min(0) - })).optional() - }).optional().describe("Aggregation facets for refining search") -}).describe("Marketplace search response"); -var MarketplaceInstallRequestSchema = external_exports.object({ - /** Listing ID to install */ - listingId: external_exports.string().describe("Marketplace listing ID"), - /** Specific version to install (defaults to latest) */ - version: external_exports.string().optional().describe("Version to install"), - /** License key (for paid packages) */ - licenseKey: external_exports.string().optional().describe("License key for paid packages"), - /** User-provided settings at install time */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), - /** Whether to enable immediately after install */ - enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), - /** Artifact reference (resolved from listing version, or provided directly) */ - artifactRef: ArtifactReferenceSchema2.optional().describe("Artifact reference for direct installation"), - /** Tenant ID */ - tenantId: external_exports.string().optional().describe("Tenant identifier") -}).describe("Install from marketplace request"); -var MarketplaceInstallResponseSchema = external_exports.object({ - /** Whether installation was successful */ - success: external_exports.boolean().describe("Whether installation succeeded"), - /** Installed package ID */ - packageId: external_exports.string().optional().describe("Installed package identifier"), - /** Installed version */ - version: external_exports.string().optional().describe("Installed version"), - /** Human-readable message */ - message: external_exports.string().optional().describe("Installation status message") -}).describe("Install from marketplace response"); -var PublisherProfileSchema = external_exports.object({ - /** Organization ID (references Identity.Organization.id) */ - organizationId: external_exports.string().describe("Identity Organization ID"), - /** Publisher ID (marketplace-assigned identifier) */ - publisherId: external_exports.string().describe("Marketplace publisher ID"), - /** Verification level (marketplace trust tier) */ - verification: PublisherVerificationSchema2.default("unverified"), - /** Accepted developer program agreement version */ - agreementVersion: external_exports.string().optional().describe("Accepted developer agreement version"), - /** Publisher-specific website (may differ from org) */ - website: external_exports.string().url().optional().describe("Publisher website"), - /** Publisher-specific support email */ - supportEmail: external_exports.string().email().optional().describe("Publisher support email"), - /** Registration timestamp (when org became a publisher) */ - registeredAt: external_exports.string().datetime() -}); -var ReleaseChannelSchema = external_exports.enum([ - "alpha", - // Early development, unstable - "beta", - // Feature-complete, testing phase - "rc", - // Release candidate, final testing - "stable" - // Production-ready, general availability -]); -var VersionReleaseSchema = external_exports.object({ - /** Semver version string */ - version: external_exports.string().describe("Semver version (e.g., 2.1.0-beta.1)"), - /** Release channel */ - channel: ReleaseChannelSchema.default("stable"), - /** Release notes (Markdown) */ - releaseNotes: external_exports.string().optional().describe("Release notes (Markdown)"), - /** Changelog entries (structured) */ - changelog: external_exports.array(external_exports.object({ - type: external_exports.enum(["added", "changed", "fixed", "removed", "deprecated", "security"]), - description: external_exports.string() - })).optional().describe("Structured changelog entries"), - /** Minimum platform version required */ - minPlatformVersion: external_exports.string().optional(), - /** Build artifact URL */ - artifactUrl: external_exports.string().optional().describe("Built package artifact URL"), - /** Artifact checksum (integrity) */ - artifactChecksum: external_exports.string().optional().describe("SHA-256 checksum"), - /** Whether this version is deprecated */ - deprecated: external_exports.boolean().default(false), - /** Deprecation message (if deprecated) */ - deprecationMessage: external_exports.string().optional(), - /** Release timestamp */ - releasedAt: external_exports.string().datetime().optional() -}); -var CreateListingRequestSchema = external_exports.object({ - /** Package ID (reverse domain, e.g., com.acme.crm) */ - packageId: external_exports.string().describe("Package identifier"), - /** Display name */ - name: external_exports.string().describe("App display name"), - /** Short tagline (max 120 chars) */ - tagline: external_exports.string().max(120).optional(), - /** Full description (Markdown) */ - description: external_exports.string().optional(), - /** Category */ - category: external_exports.string().describe("Marketplace category"), - /** Additional tags */ - tags: external_exports.array(external_exports.string()).optional(), - /** Icon URL */ - iconUrl: external_exports.string().url().optional(), - /** Screenshots */ - screenshots: external_exports.array(external_exports.object({ - url: external_exports.string().url(), - caption: external_exports.string().optional() - })).optional(), - /** Documentation URL */ - documentationUrl: external_exports.string().url().optional(), - /** Support URL */ - supportUrl: external_exports.string().url().optional(), - /** Source repository URL */ - repositoryUrl: external_exports.string().url().optional(), - /** Pricing model */ - pricing: external_exports.enum([ - "free", - "freemium", - "paid", - "subscription", - "usage-based", - "contact-sales" - ]).default("free"), - /** Price in cents (if paid) */ - priceInCents: external_exports.number().int().min(0).optional() -}); -var UpdateListingRequestSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string().describe("Listing ID to update"), - /** Updatable fields (all optional, partial update) */ - name: external_exports.string().optional(), - tagline: external_exports.string().max(120).optional(), - description: external_exports.string().optional(), - category: external_exports.string().optional(), - tags: external_exports.array(external_exports.string()).optional(), - iconUrl: external_exports.string().url().optional(), - screenshots: external_exports.array(external_exports.object({ - url: external_exports.string().url(), - caption: external_exports.string().optional() - })).optional(), - documentationUrl: external_exports.string().url().optional(), - supportUrl: external_exports.string().url().optional(), - repositoryUrl: external_exports.string().url().optional(), - pricing: external_exports.enum([ - "free", - "freemium", - "paid", - "subscription", - "usage-based", - "contact-sales" - ]).optional(), - priceInCents: external_exports.number().int().min(0).optional() -}); -var ListingActionRequestSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string().describe("Listing ID"), - /** Action to perform */ - action: external_exports.enum([ - "submit", - // Submit for review - "unlist", - // Remove from public search (keep accessible by direct link) - "deprecate", - // Mark as deprecated - "reactivate" - // Reactivate unlisted/deprecated listing - ]).describe("Action to perform on listing"), - /** Reason for action (e.g., deprecation message) */ - reason: external_exports.string().optional() -}); -var AnalyticsTimeRangeSchema = external_exports.enum([ - "last_7d", - "last_30d", - "last_90d", - "last_365d", - "all_time" -]); -var PublishingAnalyticsRequestSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string().describe("Listing to get analytics for"), - /** Time range */ - timeRange: AnalyticsTimeRangeSchema.default("last_30d"), - /** Metrics to include */ - metrics: external_exports.array(external_exports.enum([ - "installs", - // Install count over time - "uninstalls", - // Uninstall count over time - "active_installs", - // Active install trend - "ratings", - // Rating distribution - "revenue", - // Revenue (for paid apps) - "page_views" - // Listing page views - ])).optional().describe("Metrics to include (default: all)") -}); -var TimeSeriesPointSchema = external_exports.object({ - /** ISO date string (day granularity) */ - date: external_exports.string(), - /** Metric value */ - value: external_exports.number() -}); -var PublishingAnalyticsResponseSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string(), - /** Time range */ - timeRange: AnalyticsTimeRangeSchema, - /** Summary statistics */ - summary: external_exports.object({ - totalInstalls: external_exports.number().int().min(0), - activeInstalls: external_exports.number().int().min(0), - totalUninstalls: external_exports.number().int().min(0), - averageRating: external_exports.number().min(0).max(5).optional(), - totalRatings: external_exports.number().int().min(0), - totalRevenue: external_exports.number().min(0).optional().describe("Revenue in cents"), - pageViews: external_exports.number().int().min(0) - }), - /** Time series data by metric */ - timeSeries: external_exports.record(external_exports.string(), external_exports.array(TimeSeriesPointSchema)).optional().describe("Time series keyed by metric name"), - /** Rating distribution (1-5 stars) */ - ratingDistribution: external_exports.object({ - 1: external_exports.number().int().min(0).default(0), - 2: external_exports.number().int().min(0).default(0), - 3: external_exports.number().int().min(0).default(0), - 4: external_exports.number().int().min(0).default(0), - 5: external_exports.number().int().min(0).default(0) - }).optional() -}); -var ReviewCriterionSchema = external_exports.object({ - /** Criterion identifier */ - id: external_exports.string().describe("Criterion ID"), - /** Category of criterion */ - category: external_exports.enum([ - "security", - // Security best practices - "performance", - // Performance / resource usage - "quality", - // Code quality / best practices - "ux", - // User experience standards - "documentation", - // Documentation completeness - "policy", - // Policy compliance (no malware, GDPR, etc.) - "compatibility" - // Platform compatibility - ]), - /** Description of what to check */ - description: external_exports.string(), - /** Whether this criterion must pass for approval */ - required: external_exports.boolean().default(true), - /** Pass/fail result */ - passed: external_exports.boolean().optional(), - /** Reviewer notes for this criterion */ - notes: external_exports.string().optional() -}); -var ReviewDecisionSchema = external_exports.enum([ - "approved", - // Approved for publishing - "rejected", - // Rejected (with reasons) - "changes-requested" - // Needs changes before re-review -]); -var RejectionReasonSchema = external_exports.enum([ - "security-vulnerability", - // Security issues found - "policy-violation", - // Violates marketplace policy - "quality-below-standard", - // Does not meet quality bar - "misleading-metadata", - // Listing info doesn't match functionality - "incompatible", - // Incompatible with current platform - "duplicate", - // Duplicate of existing listing - "insufficient-documentation", - // Inadequate documentation - "other" - // Other reason (see notes) -]); -var SubmissionReviewSchema = external_exports.object({ - /** Review ID */ - id: external_exports.string().describe("Review ID"), - /** Submission ID being reviewed */ - submissionId: external_exports.string().describe("Submission being reviewed"), - /** Reviewer user ID */ - reviewerId: external_exports.string().describe("Platform reviewer ID"), - /** Review decision */ - decision: ReviewDecisionSchema.optional().describe("Final decision"), - /** Review criteria checklist */ - criteria: external_exports.array(ReviewCriterionSchema).optional().describe("Review checklist results"), - /** Rejection reasons (if rejected) */ - rejectionReasons: external_exports.array(RejectionReasonSchema).optional(), - /** Detailed feedback for the developer */ - feedback: external_exports.string().optional().describe("Detailed review feedback (Markdown)"), - /** Internal notes (not visible to developer) */ - internalNotes: external_exports.string().optional().describe("Internal reviewer notes"), - /** Review started timestamp */ - startedAt: external_exports.string().datetime().optional(), - /** Review completed timestamp */ - completedAt: external_exports.string().datetime().optional() -}); -var FeaturedListingSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string().describe("Featured listing ID"), - /** Featured position/priority (lower = higher priority) */ - priority: external_exports.number().int().min(0).default(0), - /** Featured banner image URL */ - bannerUrl: external_exports.string().url().optional(), - /** Featured reason / editorial note */ - editorialNote: external_exports.string().optional(), - /** Start date for featured period */ - startDate: external_exports.string().datetime(), - /** End date for featured period */ - endDate: external_exports.string().datetime().optional(), - /** Whether currently active */ - active: external_exports.boolean().default(true) -}); -var CuratedCollectionSchema = external_exports.object({ - /** Collection unique identifier */ - id: external_exports.string().describe("Collection ID"), - /** Collection display name */ - name: external_exports.string().describe("Collection name"), - /** Collection description */ - description: external_exports.string().optional(), - /** Cover image URL */ - coverImageUrl: external_exports.string().url().optional(), - /** Listing IDs in this collection (ordered) */ - listingIds: external_exports.array(external_exports.string()).min(1).describe("Ordered listing IDs"), - /** Whether publicly visible */ - published: external_exports.boolean().default(false), - /** Sort order for display among collections */ - sortOrder: external_exports.number().int().min(0).default(0), - /** Created by (admin user ID) */ - createdBy: external_exports.string().optional(), - /** Created at */ - createdAt: external_exports.string().datetime().optional(), - /** Updated at */ - updatedAt: external_exports.string().datetime().optional() -}); -var PolicyViolationTypeSchema = external_exports.enum([ - "malware", - // Malicious software - "data-harvesting", - // Unauthorized data collection - "spam", - // Spammy or misleading content - "copyright", - // Copyright/IP infringement - "inappropriate-content", - // Inappropriate or offensive content - "terms-of-service", - // General ToS violation - "security-risk", - // Unresolved critical security issues - "abandoned" - // Abandoned / no longer maintained -]); -var PolicyActionSchema = external_exports.object({ - /** Action ID */ - id: external_exports.string().describe("Action ID"), - /** Listing ID */ - listingId: external_exports.string().describe("Target listing ID"), - /** Violation type */ - violationType: PolicyViolationTypeSchema, - /** Action taken */ - action: external_exports.enum([ - "warning", - // Warning to publisher - "suspend", - // Temporarily suspend listing - "takedown", - // Permanently remove listing - "restrict" - // Restrict new installs (existing users keep access) - ]), - /** Detailed reason */ - reason: external_exports.string().describe("Explanation of the violation"), - /** Admin user who took the action */ - actionBy: external_exports.string().describe("Admin user ID"), - /** Timestamp */ - actionAt: external_exports.string().datetime(), - /** Resolution notes (if resolved) */ - resolution: external_exports.string().optional(), - /** Whether resolved */ - resolved: external_exports.boolean().default(false) -}); -var MarketplaceHealthMetricsSchema = external_exports.object({ - /** Total number of published listings */ - totalListings: external_exports.number().int().min(0), - /** Listings by status breakdown (partial — only non-zero statuses) */ - listingsByStatus: external_exports.record(external_exports.string(), external_exports.number().int().min(0)).optional(), - /** Listings by category breakdown (partial — only non-zero categories) */ - listingsByCategory: external_exports.record(external_exports.string(), external_exports.number().int().min(0)).optional(), - /** Total registered publishers */ - totalPublishers: external_exports.number().int().min(0), - /** Verified publishers count */ - verifiedPublishers: external_exports.number().int().min(0), - /** Total installs across all listings (all time) */ - totalInstalls: external_exports.number().int().min(0), - /** Average time from submission to review completion (hours) */ - averageReviewTime: external_exports.number().min(0).optional(), - /** Pending review queue size */ - pendingReviews: external_exports.number().int().min(0), - /** Listings by pricing model (partial — only non-zero models) */ - listingsByPricing: external_exports.record(external_exports.string(), external_exports.number().int().min(0)).optional(), - /** Snapshot timestamp */ - snapshotAt: external_exports.string().datetime() -}); -var TrendingListingSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string(), - /** Trending rank (1 = most trending) */ - rank: external_exports.number().int().min(1), - /** Trend score (computed from velocity of installs, ratings, page views) */ - trendScore: external_exports.number().min(0), - /** Install velocity (installs per day over measurement period) */ - installVelocity: external_exports.number().min(0), - /** Measurement period (e.g., "7d", "30d") */ - period: external_exports.string() -}); -var ReviewModerationStatusSchema = external_exports.enum([ - "pending", - // Awaiting moderation - "approved", - // Approved and visible - "flagged", - // Flagged for review - "rejected" - // Rejected (spam, inappropriate) -]); -var UserReviewSchema = external_exports.object({ - /** Review ID */ - id: external_exports.string().describe("Review ID"), - /** Listing ID being reviewed */ - listingId: external_exports.string().describe("Listing being reviewed"), - /** Reviewer user ID */ - userId: external_exports.string().describe("Review author user ID"), - /** Reviewer display name */ - displayName: external_exports.string().optional().describe("Reviewer display name"), - /** Star rating (1-5) */ - rating: external_exports.number().int().min(1).max(5).describe("Star rating (1-5)"), - /** Review title */ - title: external_exports.string().max(200).optional().describe("Review title"), - /** Review body text */ - body: external_exports.string().max(5e3).optional().describe("Review text"), - /** Version the reviewer is using */ - appVersion: external_exports.string().optional().describe("App version being reviewed"), - /** Moderation status */ - moderationStatus: ReviewModerationStatusSchema.default("pending"), - /** Number of "helpful" votes from other users */ - helpfulCount: external_exports.number().int().min(0).default(0), - /** Publisher's response to this review */ - publisherResponse: external_exports.object({ - body: external_exports.string(), - respondedAt: external_exports.string().datetime() - }).optional().describe("Publisher response to review"), - /** Submitted timestamp */ - submittedAt: external_exports.string().datetime(), - /** Updated timestamp */ - updatedAt: external_exports.string().datetime().optional() -}); -var SubmitReviewRequestSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string().describe("Listing to review"), - /** Star rating (1-5) */ - rating: external_exports.number().int().min(1).max(5).describe("Star rating"), - /** Review title */ - title: external_exports.string().max(200).optional(), - /** Review body */ - body: external_exports.string().max(5e3).optional() -}); -var ListReviewsRequestSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string().describe("Listing to get reviews for"), - /** Sort by */ - sortBy: external_exports.enum(["newest", "oldest", "highest", "lowest", "most-helpful"]).default("newest"), - /** Filter by rating */ - rating: external_exports.number().int().min(1).max(5).optional(), - /** Pagination */ - page: external_exports.number().int().min(1).default(1), - pageSize: external_exports.number().int().min(1).max(50).default(10) -}); -var ListReviewsResponseSchema = external_exports.object({ - /** Reviews */ - items: external_exports.array(UserReviewSchema), - /** Total count */ - total: external_exports.number().int().min(0), - /** Pagination */ - page: external_exports.number().int().min(1), - pageSize: external_exports.number().int().min(1), - /** Rating summary */ - ratingSummary: external_exports.object({ - averageRating: external_exports.number().min(0).max(5), - totalRatings: external_exports.number().int().min(0), - distribution: external_exports.object({ - 1: external_exports.number().int().min(0).default(0), - 2: external_exports.number().int().min(0).default(0), - 3: external_exports.number().int().min(0).default(0), - 4: external_exports.number().int().min(0).default(0), - 5: external_exports.number().int().min(0).default(0) - }) - }).optional() -}); -var RecommendationReasonSchema = external_exports.enum([ - "popular-in-category", - // Popular in your industry/category - "similar-users", - // Used by similar organizations - "complements-installed", - // Complements apps you already use - "trending", - // Currently trending - "new-release", - // Recently released / major update - "editor-pick" - // Editorial/curated recommendation -]); -var RecommendedAppSchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string(), - /** App name */ - name: external_exports.string(), - /** Short tagline */ - tagline: external_exports.string().optional(), - /** Icon URL */ - iconUrl: external_exports.string().url().optional(), - /** Category */ - category: MarketplaceCategorySchema2, - /** Pricing */ - pricing: PricingModelSchema2, - /** Average rating */ - averageRating: external_exports.number().min(0).max(5).optional(), - /** Active installs */ - activeInstalls: external_exports.number().int().min(0).optional(), - /** Why this is recommended */ - reason: RecommendationReasonSchema -}); -var AppDiscoveryRequestSchema = external_exports.object({ - /** Tenant ID for personalization */ - tenantId: external_exports.string().optional(), - /** Categories the customer is interested in */ - categories: external_exports.array(MarketplaceCategorySchema2).optional(), - /** Platform version for compatibility filtering */ - platformVersion: external_exports.string().optional(), - /** Max number of items per section */ - limit: external_exports.number().int().min(1).max(50).default(10) -}); -var AppDiscoveryResponseSchema = external_exports.object({ - /** Featured apps (editorial picks) */ - featured: external_exports.array(RecommendedAppSchema).optional(), - /** Personalized recommendations */ - recommended: external_exports.array(RecommendedAppSchema).optional(), - /** Trending apps */ - trending: external_exports.array(RecommendedAppSchema).optional(), - /** Recently added */ - newArrivals: external_exports.array(RecommendedAppSchema).optional(), - /** Curated collections */ - collections: external_exports.array(external_exports.object({ - id: external_exports.string(), - name: external_exports.string(), - description: external_exports.string().optional(), - coverImageUrl: external_exports.string().url().optional(), - apps: external_exports.array(RecommendedAppSchema) - })).optional() -}); -var SubscriptionStatusSchema = external_exports.enum([ - "active", - // Active and paid - "trialing", - // Free trial period - "past-due", - // Payment overdue - "cancelled", - // Cancelled (still active until period ends) - "expired" - // Expired / ended -]); -var AppSubscriptionSchema = external_exports.object({ - /** Subscription ID */ - id: external_exports.string().describe("Subscription ID"), - /** Listing ID */ - listingId: external_exports.string().describe("App listing ID"), - /** Tenant ID */ - tenantId: external_exports.string().describe("Customer tenant ID"), - /** Subscription status */ - status: SubscriptionStatusSchema, - /** License key */ - licenseKey: external_exports.string().optional(), - /** Plan/tier name (if multiple plans) */ - plan: external_exports.string().optional().describe("Subscription plan name"), - /** Billing cycle */ - billingCycle: external_exports.enum(["monthly", "annual"]).optional(), - /** Price per billing cycle (in cents) */ - priceInCents: external_exports.number().int().min(0).optional(), - /** Current period start */ - currentPeriodStart: external_exports.string().datetime().optional(), - /** Current period end */ - currentPeriodEnd: external_exports.string().datetime().optional(), - /** Trial end date (if trialing) */ - trialEndDate: external_exports.string().datetime().optional(), - /** Whether auto-renew is on */ - autoRenew: external_exports.boolean().default(true), - /** Created timestamp */ - createdAt: external_exports.string().datetime() -}); -var InstalledAppSummarySchema = external_exports.object({ - /** Listing ID */ - listingId: external_exports.string(), - /** Package ID */ - packageId: external_exports.string(), - /** Display name */ - name: external_exports.string(), - /** Icon URL */ - iconUrl: external_exports.string().url().optional(), - /** Installed version */ - installedVersion: external_exports.string(), - /** Latest available version */ - latestVersion: external_exports.string().optional(), - /** Whether an update is available */ - updateAvailable: external_exports.boolean().default(false), - /** Whether the app is currently enabled */ - enabled: external_exports.boolean().default(true), - /** Subscription status (for paid apps) */ - subscriptionStatus: SubscriptionStatusSchema.optional(), - /** Installed timestamp */ - installedAt: external_exports.string().datetime() -}); -var ListInstalledAppsRequestSchema = external_exports.object({ - /** Tenant ID */ - tenantId: external_exports.string().optional(), - /** Filter by enabled/disabled */ - enabled: external_exports.boolean().optional(), - /** Filter by update availability */ - updateAvailable: external_exports.boolean().optional(), - /** Sort by */ - sortBy: external_exports.enum(["name", "installed-date", "updated-date"]).default("name"), - /** Pagination */ - page: external_exports.number().int().min(1).default(1), - pageSize: external_exports.number().int().min(1).max(100).default(20) -}); -var ListInstalledAppsResponseSchema = external_exports.object({ - /** Installed apps */ - items: external_exports.array(InstalledAppSummarySchema), - /** Total count */ - total: external_exports.number().int().min(0), - /** Pagination */ - page: external_exports.number().int().min(1), - pageSize: external_exports.number().int().min(1) -}); -var qa_exports2 = {}; -__export4(qa_exports2, { - TestActionSchema: () => TestActionSchema, - TestActionTypeSchema: () => TestActionTypeSchema, - TestAssertionSchema: () => TestAssertionSchema, - TestAssertionTypeSchema: () => TestAssertionTypeSchema, - TestContextSchema: () => TestContextSchema, - TestScenarioSchema: () => TestScenarioSchema, - TestStepSchema: () => TestStepSchema, - TestSuiteSchema: () => TestSuiteSchema -}); -var TestContextSchema = external_exports.record(external_exports.string(), external_exports.unknown()).describe("Initial context or variables for the test"); -var TestActionTypeSchema = external_exports.enum([ - "create_record", - "update_record", - "delete_record", - "read_record", - "query_records", - "api_call", - "run_script", - "wait" - // Testing async processes -]).describe("Type of test action to perform"); -var TestActionSchema = external_exports.object({ - type: TestActionTypeSchema.describe("The action type to execute"), - target: external_exports.string().describe("Target Object, API Endpoint, or Function Name"), - payload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Data to send or use"), - user: external_exports.string().optional().describe("Run as specific user/role for impersonation testing") -}).describe("A single test action to execute against the system"); -var TestAssertionTypeSchema = external_exports.enum([ - "equals", - "not_equals", - "contains", - "not_contains", - "is_null", - "not_null", - "gt", - "gte", - "lt", - "lte", - "error" - // Expecting an error -]).describe("Comparison operator for test assertions"); -var TestAssertionSchema = external_exports.object({ - field: external_exports.string().describe('Field path in the result to check (e.g. "body.data.0.status")'), - operator: TestAssertionTypeSchema.describe("Comparison operator to use"), - expectedValue: external_exports.unknown().describe("Expected value to compare against") -}).describe("A test assertion that validates the result of a test action"); -var TestStepSchema = external_exports.object({ - name: external_exports.string().describe("Step name for identification in test reports"), - description: external_exports.string().optional().describe("Human-readable description of what this step tests"), - action: TestActionSchema.describe("The action to execute in this step"), - assertions: external_exports.array(TestAssertionSchema).optional().describe("Assertions to validate after the action completes"), - // Capture outputs to variables for subsequent steps - capture: external_exports.record(external_exports.string(), external_exports.string()).optional().describe('Map result fields to context variables: { "newId": "body.id" }') -}).describe("A single step in a test scenario, consisting of an action and optional assertions"); -var TestScenarioSchema = external_exports.object({ - id: external_exports.string().describe("Unique scenario identifier"), - name: external_exports.string().describe("Scenario name for test reports"), - description: external_exports.string().optional().describe("Detailed description of the test scenario"), - tags: external_exports.array(external_exports.string()).optional().describe('Tags for filtering and categorization (e.g. "critical", "regression", "crm")'), - setup: external_exports.array(TestStepSchema).optional().describe("Steps to run before main test (preconditions)"), - steps: external_exports.array(TestStepSchema).describe("Main test sequence to execute"), - teardown: external_exports.array(TestStepSchema).optional().describe("Steps to cleanup after test execution"), - // Environment requirements - requires: external_exports.object({ - params: external_exports.array(external_exports.string()).optional().describe("Required environment variables or parameters"), - plugins: external_exports.array(external_exports.string()).optional().describe("Required plugins that must be loaded") - }).optional().describe("Environment requirements for this scenario") -}).describe("A complete test scenario with setup, execution steps, and teardown"); -var TestSuiteSchema = external_exports.object({ - name: external_exports.string().describe("Test suite name"), - scenarios: external_exports.array(TestScenarioSchema).describe("List of test scenarios in this suite") -}).describe("A collection of test scenarios grouped into a test suite"); -var identity_exports = {}; -__export4(identity_exports, { - AUTH_CONSTANTS: () => AUTH_CONSTANTS, - AUTH_ERROR_CODES: () => AUTH_ERROR_CODES, - AccountSchema: () => AccountSchema, - ApiKeySchema: () => ApiKeySchema, - InvitationSchema: () => InvitationSchema, - InvitationStatus: () => InvitationStatus, - MemberSchema: () => MemberSchema, - OrganizationSchema: () => OrganizationSchema, - RoleSchema: () => RoleSchema, - SCIM: () => SCIM, - SCIMAddressSchema: () => SCIMAddressSchema, - SCIMBulkOperationSchema: () => SCIMBulkOperationSchema, - SCIMBulkRequestSchema: () => SCIMBulkRequestSchema, - SCIMBulkResponseOperationSchema: () => SCIMBulkResponseOperationSchema, - SCIMBulkResponseSchema: () => SCIMBulkResponseSchema, - SCIMEmailSchema: () => SCIMEmailSchema, - SCIMEnterpriseUserSchema: () => SCIMEnterpriseUserSchema, - SCIMErrorSchema: () => SCIMErrorSchema, - SCIMGroupReferenceSchema: () => SCIMGroupReferenceSchema, - SCIMGroupSchema: () => SCIMGroupSchema, - SCIMListResponseSchema: () => SCIMListResponseSchema, - SCIMMemberReferenceSchema: () => SCIMMemberReferenceSchema, - SCIMMetaSchema: () => SCIMMetaSchema, - SCIMNameSchema: () => SCIMNameSchema, - SCIMPatchOperationSchema: () => SCIMPatchOperationSchema, - SCIMPatchRequestSchema: () => SCIMPatchRequestSchema, - SCIMPhoneNumberSchema: () => SCIMPhoneNumberSchema, - SCIMUserSchema: () => SCIMUserSchema, - SCIM_SCHEMAS: () => SCIM_SCHEMAS, - SessionSchema: () => SessionSchema2, - UserSchema: () => UserSchema, - VerificationTokenSchema: () => VerificationTokenSchema -}); -var UserSchema = external_exports.object({ - /** - * Unique user identifier - */ - id: external_exports.string().describe("Unique user identifier"), - /** - * User's email address (primary identifier) - */ - email: external_exports.string().email().describe("User email address"), - /** - * Email verification status - */ - emailVerified: external_exports.boolean().default(false).describe("Whether email is verified"), - /** - * User's display name - */ - name: external_exports.string().optional().describe("User display name"), - /** - * User's profile image URL - */ - image: external_exports.string().url().optional().describe("Profile image URL"), - /** - * Account creation timestamp - */ - createdAt: external_exports.string().datetime().describe("Account creation timestamp"), - /** - * Last update timestamp - */ - updatedAt: external_exports.string().datetime().describe("Last update timestamp") -}); -var AccountSchema = external_exports.object({ - /** - * Unique account identifier - */ - id: external_exports.string().describe("Unique account identifier"), - /** - * Associated user ID - */ - userId: external_exports.string().describe("Associated user ID"), - /** - * Account type/provider - */ - type: external_exports.enum([ - "oauth", - "oidc", - "email", - "credentials", - "saml", - "ldap" - ]).describe("Account type"), - /** - * Provider name (e.g., 'google', 'github', 'okta') - */ - provider: external_exports.string().describe("Provider name"), - /** - * Provider account ID - */ - providerAccountId: external_exports.string().describe("Provider account ID"), - /** - * OAuth refresh token - */ - refreshToken: external_exports.string().optional().describe("OAuth refresh token"), - /** - * OAuth access token - */ - accessToken: external_exports.string().optional().describe("OAuth access token"), - /** - * Token expiry timestamp - */ - expiresAt: external_exports.number().optional().describe("Token expiry timestamp (Unix)"), - /** - * OAuth token type - */ - tokenType: external_exports.string().optional().describe("OAuth token type"), - /** - * OAuth scope - */ - scope: external_exports.string().optional().describe("OAuth scope"), - /** - * OAuth ID token - */ - idToken: external_exports.string().optional().describe("OAuth ID token"), - /** - * Session state - */ - sessionState: external_exports.string().optional().describe("Session state"), - /** - * Account creation timestamp - */ - createdAt: external_exports.string().datetime().describe("Account creation timestamp"), - /** - * Last update timestamp - */ - updatedAt: external_exports.string().datetime().describe("Last update timestamp") -}); -var SessionSchema2 = external_exports.object({ - /** - * Unique session identifier - */ - id: external_exports.string().describe("Unique session identifier"), - /** - * Session token - */ - sessionToken: external_exports.string().describe("Session token"), - /** - * Associated user ID - */ - userId: external_exports.string().describe("Associated user ID"), - /** - * Active organization ID for this session - * Used for context switching in multi-tenant applications - */ - activeOrganizationId: external_exports.string().optional().describe("Active organization ID for context switching"), - /** - * Session expiry timestamp - */ - expires: external_exports.string().datetime().describe("Session expiry timestamp"), - /** - * Session creation timestamp - */ - createdAt: external_exports.string().datetime().describe("Session creation timestamp"), - /** - * Last update timestamp - */ - updatedAt: external_exports.string().datetime().describe("Last update timestamp"), - /** - * IP address of the session - */ - ipAddress: external_exports.string().optional().describe("IP address"), - /** - * User agent string - */ - userAgent: external_exports.string().optional().describe("User agent string"), - /** - * Device fingerprint - */ - fingerprint: external_exports.string().optional().describe("Device fingerprint") -}); -var VerificationTokenSchema = external_exports.object({ - /** - * Token identifier (email or phone) - */ - identifier: external_exports.string().describe("Token identifier (email or phone)"), - /** - * Verification token - */ - token: external_exports.string().describe("Verification token"), - /** - * Token expiry timestamp - */ - expires: external_exports.string().datetime().describe("Token expiry timestamp"), - /** - * Token creation timestamp - */ - createdAt: external_exports.string().datetime().describe("Token creation timestamp") -}); -var ApiKeySchema = external_exports.object({ - /** - * Unique API key identifier - */ - id: external_exports.string().describe("API key identifier"), - /** - * Human-readable name for the key - */ - name: external_exports.string().describe("API key display name"), - /** - * Key prefix (visible portion for identification, e.g., "os_pk_ab") - */ - start: external_exports.string().optional().describe("Key prefix for identification"), - /** - * Custom prefix for the key (e.g., "os_pk_") - */ - prefix: external_exports.string().optional().describe("Custom key prefix"), - /** - * User ID of the key owner - */ - userId: external_exports.string().describe("Owner user ID"), - /** - * Organization ID the key is scoped to (optional) - */ - organizationId: external_exports.string().optional().describe("Scoped organization ID"), - /** - * Key expiration timestamp (null = never expires) - */ - expiresAt: external_exports.string().datetime().optional().describe("Expiration timestamp"), - /** - * Creation timestamp - */ - createdAt: external_exports.string().datetime().describe("Creation timestamp"), - /** - * Last update timestamp - */ - updatedAt: external_exports.string().datetime().describe("Last update timestamp"), - /** - * Last used timestamp - */ - lastUsedAt: external_exports.string().datetime().optional().describe("Last used timestamp"), - /** - * Last refetch timestamp (for cached permission checks) - */ - lastRefetchAt: external_exports.string().datetime().optional().describe("Last refetch timestamp"), - /** - * Whether this key is enabled - */ - enabled: external_exports.boolean().default(true).describe("Whether the key is active"), - /** - * Rate limiting: enabled flag - */ - rateLimitEnabled: external_exports.boolean().optional().describe("Whether rate limiting is enabled"), - /** - * Rate limiting: time window in milliseconds - */ - rateLimitTimeWindow: external_exports.number().int().min(0).optional().describe("Rate limit window (ms)"), - /** - * Rate limiting: max requests per window - */ - rateLimitMax: external_exports.number().int().min(0).optional().describe("Max requests per window"), - /** - * Rate limiting: remaining requests in current window - */ - remaining: external_exports.number().int().min(0).optional().describe("Remaining requests"), - /** - * Permissions assigned to this key (granular access control) - */ - permissions: external_exports.record(external_exports.string(), external_exports.boolean()).optional().describe("Granular permission flags"), - /** - * Scopes assigned to this key (high-level access categories) - */ - scopes: external_exports.array(external_exports.string()).optional().describe("High-level access scopes"), - /** - * Custom metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") -}); -var AUTH_CONSTANTS = { - /** - * HTTP header key for authentication tokens - */ - HEADER_KEY: "Authorization", - /** - * Token prefix for Bearer authentication - */ - TOKEN_PREFIX: "Bearer ", - /** - * Cookie prefix for ObjectStack auth cookies - */ - COOKIE_PREFIX: "os_", - /** - * CSRF token header name - */ - CSRF_HEADER: "x-os-csrf-token", - /** - * Default session cookie name - */ - SESSION_COOKIE: "os_session_token", - /** - * Default CSRF cookie name - */ - CSRF_COOKIE: "os_csrf_token", - /** - * Refresh token cookie name - */ - REFRESH_TOKEN_COOKIE: "os_refresh_token" -}; -var AUTH_ERROR_CODES = { - INVALID_CREDENTIALS: "invalid_credentials", - INVALID_TOKEN: "invalid_token", - TOKEN_EXPIRED: "token_expired", - INSUFFICIENT_PERMISSIONS: "insufficient_permissions", - ACCOUNT_LOCKED: "account_locked", - ACCOUNT_NOT_VERIFIED: "account_not_verified", - TOO_MANY_REQUESTS: "too_many_requests", - INVALID_CSRF_TOKEN: "invalid_csrf_token", - SESSION_EXPIRED: "session_expired", - OAUTH_ERROR: "oauth_error", - PROVIDER_ERROR: "provider_error" -}; -var RoleSchema = external_exports.object({ - /** Identity */ - name: SnakeCaseIdentifierSchema7.describe("Unique role name (lowercase snake_case)"), - label: external_exports.string().describe("Display label (e.g. VP of Sales)"), - /** Hierarchy */ - parent: external_exports.string().optional().describe("Parent Role ID (Reports To)"), - /** Description */ - description: external_exports.string().optional() -}); -var OrganizationSchema = external_exports.object({ - /** - * Unique organization identifier - */ - id: external_exports.string().describe("Unique organization identifier"), - /** - * Organization name (display name) - */ - name: external_exports.string().describe("Organization display name"), - /** - * Organization slug (URL-friendly identifier) - * Must be unique across all organizations - */ - slug: external_exports.string().regex(/^[a-z0-9_-]+$/).describe("Unique URL-friendly slug (lowercase alphanumeric, hyphens, underscores)"), - /** - * Organization logo URL - */ - logo: external_exports.string().url().optional().describe("Organization logo URL"), - /** - * Custom metadata for the organization - * Can store additional configuration, settings, or custom fields - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata"), - /** - * Organization creation timestamp - */ - createdAt: external_exports.string().datetime().describe("Organization creation timestamp"), - /** - * Last update timestamp - */ - updatedAt: external_exports.string().datetime().describe("Last update timestamp") -}); -var MemberSchema = external_exports.object({ - /** - * Unique member identifier - */ - id: external_exports.string().describe("Unique member identifier"), - /** - * Organization ID this membership belongs to - */ - organizationId: external_exports.string().describe("Organization ID"), - /** - * User ID of the member - */ - userId: external_exports.string().describe("User ID"), - /** - * Member's role within the organization - * Common roles: 'owner', 'admin', 'member', 'guest' - * Can be customized per application - */ - role: external_exports.string().describe("Member role (e.g., owner, admin, member, guest)"), - /** - * Member creation timestamp - */ - createdAt: external_exports.string().datetime().describe("Member creation timestamp"), - /** - * Last update timestamp - */ - updatedAt: external_exports.string().datetime().describe("Last update timestamp") -}); -var InvitationStatus = external_exports.enum(["pending", "accepted", "rejected", "expired"]); -var InvitationSchema = external_exports.object({ - /** - * Unique invitation identifier - */ - id: external_exports.string().describe("Unique invitation identifier"), - /** - * Organization ID the invitation is for - */ - organizationId: external_exports.string().describe("Organization ID"), - /** - * Email address of the invitee - */ - email: external_exports.string().email().describe("Invitee email address"), - /** - * Role the invitee will receive upon accepting - * Common roles: 'admin', 'member', 'guest' - */ - role: external_exports.string().describe("Role to assign upon acceptance"), - /** - * Invitation status - */ - status: InvitationStatus.default("pending").describe("Invitation status"), - /** - * Invitation expiration timestamp - */ - expiresAt: external_exports.string().datetime().describe("Invitation expiry timestamp"), - /** - * User ID of the person who sent the invitation - */ - inviterId: external_exports.string().describe("User ID of the inviter"), - /** - * Invitation creation timestamp - */ - createdAt: external_exports.string().datetime().describe("Invitation creation timestamp"), - /** - * Last update timestamp - */ - updatedAt: external_exports.string().datetime().describe("Last update timestamp") -}); -var SCIM_SCHEMAS = { - USER: "urn:ietf:params:scim:schemas:core:2.0:User", - GROUP: "urn:ietf:params:scim:schemas:core:2.0:Group", - ENTERPRISE_USER: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User", - RESOURCE_TYPE: "urn:ietf:params:scim:schemas:core:2.0:ResourceType", - SERVICE_PROVIDER_CONFIG: "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig", - SCHEMA: "urn:ietf:params:scim:schemas:core:2.0:Schema", - LIST_RESPONSE: "urn:ietf:params:scim:api:messages:2.0:ListResponse", - PATCH_OP: "urn:ietf:params:scim:api:messages:2.0:PatchOp", - BULK_REQUEST: "urn:ietf:params:scim:api:messages:2.0:BulkRequest", - BULK_RESPONSE: "urn:ietf:params:scim:api:messages:2.0:BulkResponse", - ERROR: "urn:ietf:params:scim:api:messages:2.0:Error" -}; -var SCIMMetaSchema = external_exports.object({ - /** - * Resource type name - * @example "User", "Group" - */ - resourceType: external_exports.string().optional().describe("Resource type"), - /** - * Resource creation timestamp (ISO 8601) - */ - created: external_exports.string().datetime().optional().describe("Creation timestamp"), - /** - * Last modification timestamp (ISO 8601) - */ - lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), - /** - * Resource location URI - * Absolute URL to the resource - */ - location: external_exports.string().url().optional().describe("Resource location URI"), - /** - * Entity tag for optimistic concurrency control - * Used with If-Match header for conditional updates - */ - version: external_exports.string().optional().describe("Entity tag (ETag) for concurrency control") -}); -var SCIMNameSchema = external_exports.object({ - /** - * Full name formatted for display - * @example "Ms. Barbara Jane Jensen III" - */ - formatted: external_exports.string().optional().describe("Formatted full name"), - /** - * Family name (surname) - * @example "Jensen" - */ - familyName: external_exports.string().optional().describe("Family name (last name)"), - /** - * Given name (first name) - * @example "Barbara" - */ - givenName: external_exports.string().optional().describe("Given name (first name)"), - /** - * Middle name - * @example "Jane" - */ - middleName: external_exports.string().optional().describe("Middle name"), - /** - * Honorific prefix - * @example "Ms.", "Dr.", "Prof." - */ - honorificPrefix: external_exports.string().optional().describe("Honorific prefix (Mr., Ms., Dr.)"), - /** - * Honorific suffix - * @example "III", "Jr.", "Sr." - */ - honorificSuffix: external_exports.string().optional().describe("Honorific suffix (Jr., Sr.)") -}); -var SCIMEmailSchema = external_exports.object({ - /** - * Email address value - */ - value: external_exports.string().email().describe("Email address"), - /** - * Email type - * @example "work", "home", "other" - */ - type: external_exports.enum(["work", "home", "other"]).optional().describe("Email type"), - /** - * Display label for the email - */ - display: external_exports.string().optional().describe("Display label"), - /** - * Whether this is the primary email - */ - primary: external_exports.boolean().optional().default(false).describe("Primary email indicator") -}); -var SCIMPhoneNumberSchema = external_exports.object({ - /** - * Phone number value - * Format is not enforced to support international numbers - */ - value: external_exports.string().describe("Phone number"), - /** - * Phone type - */ - type: external_exports.enum(["work", "home", "mobile", "fax", "pager", "other"]).optional().describe("Phone number type"), - /** - * Display label for the phone number - */ - display: external_exports.string().optional().describe("Display label"), - /** - * Whether this is the primary phone - */ - primary: external_exports.boolean().optional().default(false).describe("Primary phone indicator") -}); -var SCIMAddressSchema = external_exports.object({ - /** - * Full mailing address formatted for display - */ - formatted: external_exports.string().optional().describe("Formatted address"), - /** - * Full street address - */ - streetAddress: external_exports.string().optional().describe("Street address"), - /** - * City or locality - */ - locality: external_exports.string().optional().describe("City/Locality"), - /** - * State or region - */ - region: external_exports.string().optional().describe("State/Region"), - /** - * Zip code or postal code - */ - postalCode: external_exports.string().optional().describe("Postal code"), - /** - * Country - */ - country: external_exports.string().optional().describe("Country"), - /** - * Address type - */ - type: external_exports.enum(["work", "home", "other"]).optional().describe("Address type"), - /** - * Whether this is the primary address - */ - primary: external_exports.boolean().optional().default(false).describe("Primary address indicator") -}); -var SCIMGroupReferenceSchema = external_exports.object({ - /** - * Group identifier - */ - value: external_exports.string().describe("Group ID"), - /** - * Direct reference to the group resource - */ - $ref: external_exports.string().url().optional().describe("URI reference to the group"), - /** - * Human-readable group name - */ - display: external_exports.string().optional().describe("Group display name"), - /** - * Type of group - */ - type: external_exports.enum(["direct", "indirect"]).optional().describe("Membership type") -}); -var SCIMEnterpriseUserSchema = external_exports.object({ - /** - * Employee number - */ - employeeNumber: external_exports.string().optional().describe("Employee number"), - /** - * Cost center - */ - costCenter: external_exports.string().optional().describe("Cost center"), - /** - * Organization unit - */ - organization: external_exports.string().optional().describe("Organization"), - /** - * Division - */ - division: external_exports.string().optional().describe("Division"), - /** - * Department - */ - department: external_exports.string().optional().describe("Department"), - /** - * Manager reference - */ - manager: external_exports.object({ - value: external_exports.string().describe("Manager ID"), - $ref: external_exports.string().url().optional().describe("Manager URI"), - displayName: external_exports.string().optional().describe("Manager name") - }).optional().describe("Manager reference") -}); -var SCIMUserSchema = external_exports.object({ - /** - * SCIM schema URIs - * Must include at minimum the core User schema URI - */ - schemas: external_exports.array(external_exports.string()).min(1).refine( - (schemas) => schemas.includes(SCIM_SCHEMAS.USER), - "Must include core User schema URI" - ).default([SCIM_SCHEMAS.USER]).describe("SCIM schema URIs (must include User schema)"), - /** - * Unique identifier - */ - id: external_exports.string().optional().describe("Unique resource identifier"), - /** - * External identifier - * Identifier from the provisioning client - */ - externalId: external_exports.string().optional().describe("External identifier from client system"), - /** - * Unique username - * REQUIRED for user creation - */ - userName: external_exports.string().describe("Unique username (REQUIRED)"), - /** - * Structured name - */ - name: SCIMNameSchema.optional().describe("Structured name components"), - /** - * Display name - */ - displayName: external_exports.string().optional().describe("Display name for UI"), - /** - * Nickname or casual name - */ - nickName: external_exports.string().optional().describe("Nickname"), - /** - * Profile URL - */ - profileUrl: external_exports.string().url().optional().describe("Profile page URL"), - /** - * Job title - */ - title: external_exports.string().optional().describe("Job title"), - /** - * User type (employee, contractor, etc.) - */ - userType: external_exports.string().optional().describe("User type (employee, contractor)"), - /** - * Preferred language (ISO 639-1) - */ - preferredLanguage: external_exports.string().optional().describe("Preferred language (ISO 639-1)"), - /** - * Locale (e.g., en-US) - */ - locale: external_exports.string().optional().describe("Locale (e.g., en-US)"), - /** - * Timezone (e.g., America/Los_Angeles) - */ - timezone: external_exports.string().optional().describe("Timezone"), - /** - * Account active status - */ - active: external_exports.boolean().optional().default(true).describe("Account active status"), - /** - * Password (write-only, never returned) - */ - password: external_exports.string().optional().describe("Password (write-only)"), - /** - * Email addresses (multi-valued) - */ - emails: external_exports.array(SCIMEmailSchema).optional().describe("Email addresses"), - /** - * Phone numbers (multi-valued) - */ - phoneNumbers: external_exports.array(SCIMPhoneNumberSchema).optional().describe("Phone numbers"), - /** - * Instant messaging addresses - */ - ims: external_exports.array(external_exports.object({ - value: external_exports.string(), - type: external_exports.string().optional(), - primary: external_exports.boolean().optional() - })).optional().describe("IM addresses"), - /** - * Photos (profile pictures) - */ - photos: external_exports.array(external_exports.object({ - value: external_exports.string().url(), - type: external_exports.enum(["photo", "thumbnail"]).optional(), - primary: external_exports.boolean().optional() - })).optional().describe("Photo URLs"), - /** - * Physical addresses - */ - addresses: external_exports.array(SCIMAddressSchema).optional().describe("Physical addresses"), - /** - * Group memberships - */ - groups: external_exports.array(SCIMGroupReferenceSchema).optional().describe("Group memberships"), - /** - * User entitlements - */ - entitlements: external_exports.array(external_exports.object({ - value: external_exports.string(), - type: external_exports.string().optional(), - primary: external_exports.boolean().optional() - })).optional().describe("Entitlements"), - /** - * User roles - */ - roles: external_exports.array(external_exports.object({ - value: external_exports.string(), - type: external_exports.string().optional(), - primary: external_exports.boolean().optional() - })).optional().describe("Roles"), - /** - * X509 certificates - */ - x509Certificates: external_exports.array(external_exports.object({ - value: external_exports.string(), - type: external_exports.string().optional(), - primary: external_exports.boolean().optional() - })).optional().describe("X509 certificates"), - /** - * Resource metadata - */ - meta: SCIMMetaSchema.optional().describe("Resource metadata"), - /** - * Enterprise user extension - * Only present when enterprise extension is used - */ - [SCIM_SCHEMAS.ENTERPRISE_USER]: SCIMEnterpriseUserSchema.optional().describe("Enterprise user attributes") -}).superRefine((data, ctx) => { - const hasEnterpriseExtension = data[SCIM_SCHEMAS.ENTERPRISE_USER] != null; - if (!hasEnterpriseExtension) { - return; - } - const schemas = data.schemas || []; - if (!schemas.includes(SCIM_SCHEMAS.ENTERPRISE_USER)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - path: ["schemas"], - message: `schemas must include "${SCIM_SCHEMAS.ENTERPRISE_USER}" when enterprise user extension attributes are present` - }); - } -}); -var SCIMMemberReferenceSchema = external_exports.object({ - /** - * Member identifier - */ - value: external_exports.string().describe("Member ID"), - /** - * Direct reference to the member resource - */ - $ref: external_exports.string().url().optional().describe("URI reference to the member"), - /** - * Member type (User or Group for nested groups) - */ - type: external_exports.enum(["User", "Group"]).optional().describe("Member type"), - /** - * Human-readable member name - */ - display: external_exports.string().optional().describe("Member display name") -}); -var SCIMGroupSchema = external_exports.object({ - /** - * SCIM schema URIs - * Must include at minimum the core Group schema URI - */ - schemas: external_exports.array(external_exports.string()).min(1).refine( - (schemas) => schemas.includes(SCIM_SCHEMAS.GROUP), - "Must include core Group schema URI" - ).default([SCIM_SCHEMAS.GROUP]).describe("SCIM schema URIs (must include Group schema)"), - /** - * Unique identifier - */ - id: external_exports.string().optional().describe("Unique resource identifier"), - /** - * External identifier - */ - externalId: external_exports.string().optional().describe("External identifier from client system"), - /** - * Group display name - * REQUIRED for group creation - */ - displayName: external_exports.string().describe("Group display name (REQUIRED)"), - /** - * Group members - */ - members: external_exports.array(SCIMMemberReferenceSchema).optional().describe("Group members"), - /** - * Resource metadata - */ - meta: SCIMMetaSchema.optional().describe("Resource metadata") -}); -var SCIMListResponseSchema = external_exports.object({ - /** - * SCIM schema URI - */ - schemas: external_exports.array(external_exports.string()).min(1).refine( - (schemas) => schemas.includes(SCIM_SCHEMAS.LIST_RESPONSE), - { message: `schemas must include ${SCIM_SCHEMAS.LIST_RESPONSE}` } - ).default([SCIM_SCHEMAS.LIST_RESPONSE]).describe("SCIM schema URIs"), - /** - * Total number of results matching the query - */ - totalResults: external_exports.number().int().min(0).describe("Total results count"), - /** - * Resources returned in this response - * Use SCIMListResponseOf for type-safe responses - */ - Resources: external_exports.array(external_exports.union([SCIMUserSchema, SCIMGroupSchema, external_exports.record(external_exports.string(), external_exports.unknown())])).describe("Resources array (Users, Groups, or custom resources)"), - /** - * 1-based index of the first result - */ - startIndex: external_exports.number().int().min(1).optional().describe("Start index (1-based)"), - /** - * Number of resources per page - */ - itemsPerPage: external_exports.number().int().min(0).optional().describe("Items per page") -}); -var SCIMErrorSchema = external_exports.object({ - /** - * SCIM schema URI - */ - schemas: external_exports.array(external_exports.string()).min(1).refine( - (schemas) => schemas.includes(SCIM_SCHEMAS.ERROR), - { message: `schemas must include ${SCIM_SCHEMAS.ERROR}` } - ).default([SCIM_SCHEMAS.ERROR]).describe("SCIM schema URIs"), - /** - * HTTP status code - */ - status: external_exports.number().int().min(400).max(599).describe("HTTP status code"), - /** - * SCIM error type - */ - scimType: external_exports.enum([ - "invalidFilter", - "tooMany", - "uniqueness", - "mutability", - "invalidSyntax", - "invalidPath", - "noTarget", - "invalidValue", - "invalidVers", - "sensitive" - ]).optional().describe("SCIM error type"), - /** - * Human-readable error description - */ - detail: external_exports.string().optional().describe("Error detail message") -}); -var SCIMPatchOperationSchema = external_exports.object({ - /** - * Operation type - */ - op: external_exports.enum(["add", "remove", "replace"]).describe("Operation type"), - /** - * Attribute path to modify - */ - path: external_exports.string().optional().describe("Attribute path (optional for add)"), - /** - * Value to set - */ - value: external_exports.unknown().optional().describe("Value to set") -}); -var SCIMPatchRequestSchema = external_exports.object({ - /** - * SCIM schema URI - */ - schemas: external_exports.array(external_exports.string()).min(1).refine( - (schemas) => schemas.includes(SCIM_SCHEMAS.PATCH_OP), - { message: "SCIM PATCH requests must include the PatchOp schema URI" } - ).default([SCIM_SCHEMAS.PATCH_OP]).describe("SCIM schema URIs"), - /** - * Array of patch operations - */ - Operations: external_exports.array(SCIMPatchOperationSchema).min(1).describe("Patch operations") -}); -var SCIM = { - /** - * Create a basic SCIM user - */ - user: (userName, email3, givenName, familyName) => ({ - schemas: [SCIM_SCHEMAS.USER], - userName, - emails: [{ value: email3, type: "work", primary: true }], - name: { - givenName, - familyName - }, - active: true - }), - /** - * Create a SCIM group - */ - group: (displayName, members) => ({ - schemas: [SCIM_SCHEMAS.GROUP], - displayName, - members: members || [] - }), - /** - * Create a list response - */ - listResponse: (resources, totalResults) => ({ - schemas: [SCIM_SCHEMAS.LIST_RESPONSE], - totalResults: totalResults ?? resources.length, - Resources: resources, - startIndex: 1, - itemsPerPage: resources.length - }), - /** - * Create an error response - */ - error: (status, detail, scimType) => ({ - schemas: [SCIM_SCHEMAS.ERROR], - status, - detail, - scimType - }) -}; -var SCIMBulkOperationSchema = external_exports.object({ - /** HTTP method for this operation */ - method: external_exports.enum(["POST", "PUT", "PATCH", "DELETE"]).describe("HTTP method for the bulk operation"), - /** Resource path (e.g. /Users, /Groups/{id}) */ - path: external_exports.string().describe("Resource endpoint path (e.g. /Users, /Groups/{id})"), - /** Client-assigned identifier for cross-referencing operations */ - bulkId: external_exports.string().optional().describe("Client-assigned ID for cross-referencing between operations"), - /** Request body for POST/PUT/PATCH operations */ - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Request body for POST/PUT/PATCH operations"), - /** ETag value for optimistic concurrency control */ - version: external_exports.string().optional().describe("ETag for optimistic concurrency control") -}); -var SCIMBulkRequestSchema = external_exports.object({ - /** SCIM schema URI for bulk request */ - schemas: external_exports.array(external_exports.literal(SCIM_SCHEMAS.BULK_REQUEST)).default([SCIM_SCHEMAS.BULK_REQUEST]).describe("SCIM schema URIs (BulkRequest)"), - /** Array of operations to execute */ - operations: external_exports.array(SCIMBulkOperationSchema).min(1).describe("Bulk operations to execute (minimum 1)"), - /** Stop processing after N errors */ - failOnErrors: external_exports.number().int().optional().describe("Stop processing after this many errors") -}); -var SCIMBulkResponseOperationSchema = external_exports.object({ - /** HTTP method that was executed */ - method: external_exports.enum(["POST", "PUT", "PATCH", "DELETE"]).describe("HTTP method that was executed"), - /** Client-assigned bulk operation ID */ - bulkId: external_exports.string().optional().describe("Client-assigned bulk operation ID"), - /** URL of the created/modified resource */ - location: external_exports.string().optional().describe("URL of the created or modified resource"), - /** HTTP status code as string */ - status: external_exports.string().describe('HTTP status code as string (e.g. "201", "400")'), - /** Response body, typically present for errors */ - response: external_exports.unknown().optional().describe("Response body (typically present for errors)") -}); -var SCIMBulkResponseSchema = external_exports.object({ - /** SCIM schema URI for bulk response */ - schemas: external_exports.array(external_exports.literal(SCIM_SCHEMAS.BULK_RESPONSE)).default([SCIM_SCHEMAS.BULK_RESPONSE]).describe("SCIM schema URIs (BulkResponse)"), - /** Array of operation results */ - operations: external_exports.array(SCIMBulkResponseOperationSchema).describe("Results for each bulk operation") -}); -var ai_exports = {}; -__export4(ai_exports, { - AICodeReviewResultSchema: () => AICodeReviewResultSchema, - AIKnowledgeSchema: () => AIKnowledgeSchema, - AIModelConfigSchema: () => AIModelConfigSchema, - AIOperationCostSchema: () => AIOperationCostSchema, - AIOpsAgentConfigSchema: () => AIOpsAgentConfigSchema, - AIOrchestrationExecutionResultSchema: () => AIOrchestrationExecutionResultSchema, - AIOrchestrationSchema: () => AIOrchestrationSchema, - AIOrchestrationTriggerSchema: () => AIOrchestrationTriggerSchema, - AITaskSchema: () => AITaskSchema, - AITaskTypeSchema: () => AITaskTypeSchema, - AIToolSchema: () => AIToolSchema, - AgentActionResultSchema: () => AgentActionResultSchema, - AgentActionSchema: () => AgentActionSchema, - AgentActionSequenceResultSchema: () => AgentActionSequenceResultSchema, - AgentActionSequenceSchema: () => AgentActionSequenceSchema, - AgentCommunicationProtocolSchema: () => AgentCommunicationProtocolSchema, - AgentGroupMemberSchema: () => AgentGroupMemberSchema, - AgentGroupRoleSchema: () => AgentGroupRoleSchema, - AgentSchema: () => AgentSchema, - AnomalyDetectionConfigSchema: () => AnomalyDetectionConfigSchema, - AutoScalingPolicySchema: () => AutoScalingPolicySchema, - BatchAIOrchestrationExecutionSchema: () => BatchAIOrchestrationExecutionSchema, - BillingPeriodSchema: () => BillingPeriodSchema, - BudgetLimitSchema: () => BudgetLimitSchema, - BudgetStatusSchema: () => BudgetStatusSchema, - BudgetTypeSchema: () => BudgetTypeSchema, - CICDPipelineConfigSchema: () => CICDPipelineConfigSchema, - ChunkingStrategySchema: () => ChunkingStrategySchema, - CodeContentSchema: () => CodeContentSchema, - CodeGenerationConfigSchema: () => CodeGenerationConfigSchema, - CodeGenerationRequestSchema: () => CodeGenerationRequestSchema, - CodeGenerationTargetSchema: () => CodeGenerationTargetSchema, - ComponentActionParamsSchema: () => ComponentActionParamsSchema, - ComponentActionTypeSchema: () => ComponentActionTypeSchema, - ComponentAgentActionSchema: () => ComponentAgentActionSchema, - ConversationAnalyticsSchema: () => ConversationAnalyticsSchema, - ConversationContextSchema: () => ConversationContextSchema, - ConversationMessageSchema: () => ConversationMessageSchema, - ConversationSessionSchema: () => ConversationSessionSchema, - ConversationSummarySchema: () => ConversationSummarySchema, - CostAlertSchema: () => CostAlertSchema, - CostAlertTypeSchema: () => CostAlertTypeSchema, - CostAnalyticsSchema: () => CostAnalyticsSchema, - CostBreakdownDimensionSchema: () => CostBreakdownDimensionSchema, - CostBreakdownEntrySchema: () => CostBreakdownEntrySchema, - CostEntrySchema: () => CostEntrySchema, - CostMetricTypeSchema: () => CostMetricTypeSchema, - CostOptimizationRecommendationSchema: () => CostOptimizationRecommendationSchema, - CostQueryFiltersSchema: () => CostQueryFiltersSchema, - CostReportSchema: () => CostReportSchema, - DataActionParamsSchema: () => DataActionParamsSchema, - DataActionTypeSchema: () => DataActionTypeSchema, - DataAgentActionSchema: () => DataAgentActionSchema, - DeploymentStrategySchema: () => DeploymentStrategySchema, - DevOpsAgentSchema: () => DevOpsAgentSchema, - DevOpsToolSchema: () => DevOpsToolSchema, - DevelopmentConfigSchema: () => DevelopmentConfigSchema, - DocumentChunkSchema: () => DocumentChunkSchema, - DocumentLoaderConfigSchema: () => DocumentLoaderConfigSchema, - DocumentMetadataSchema: () => DocumentMetadataSchema, - EmbeddingModelSchema: () => EmbeddingModelSchema, - EntitySchema: () => EntitySchema, - EvaluationMetricsSchema: () => EvaluationMetricsSchema, - FeedbackLoopSchema: () => FeedbackLoopSchema, - FieldSynonymConfigSchema: () => FieldSynonymConfigSchema, - FileContentSchema: () => FileContentSchema, - FilterExpressionSchema: () => FilterExpressionSchema, - FilterGroupSchema: () => FilterGroupSchema, - FormActionParamsSchema: () => FormActionParamsSchema, - FormActionTypeSchema: () => FormActionTypeSchema, - FormAgentActionSchema: () => FormAgentActionSchema, - FunctionCallSchema: () => FunctionCallSchema, - GeneratedCodeSchema: () => GeneratedCodeSchema, - GitHubIntegrationSchema: () => GitHubIntegrationSchema, - HyperparametersSchema: () => HyperparametersSchema, - ImageContentSchema: () => ImageContentSchema, - IntegrationConfigSchema: () => IntegrationConfigSchema, - IntentActionMappingSchema: () => IntentActionMappingSchema, - IssueSchema: () => IssueSchema, - MCPCapabilitySchema: () => MCPCapabilitySchema, - MCPClientConfigSchema: () => MCPClientConfigSchema, - MCPPromptArgumentSchema: () => MCPPromptArgumentSchema, - MCPPromptMessageSchema: () => MCPPromptMessageSchema, - MCPPromptRequestSchema: () => MCPPromptRequestSchema, - MCPPromptResponseSchema: () => MCPPromptResponseSchema, - MCPPromptSchema: () => MCPPromptSchema, - MCPResourceRequestSchema: () => MCPResourceRequestSchema, - MCPResourceResponseSchema: () => MCPResourceResponseSchema, - MCPResourceSchema: () => MCPResourceSchema, - MCPResourceTemplateSchema: () => MCPResourceTemplateSchema, - MCPResourceTypeSchema: () => MCPResourceTypeSchema, - MCPRootEntrySchema: () => MCPRootEntrySchema, - MCPRootsConfigSchema: () => MCPRootsConfigSchema, - MCPSamplingConfigSchema: () => MCPSamplingConfigSchema, - MCPServerConfigSchema: () => MCPServerConfigSchema, - MCPServerInfoSchema: () => MCPServerInfoSchema, - MCPStreamingConfigSchema: () => MCPStreamingConfigSchema, - MCPToolApprovalSchema: () => MCPToolApprovalSchema, - MCPToolCallRequestSchema: () => MCPToolCallRequestSchema, - MCPToolCallResponseSchema: () => MCPToolCallResponseSchema, - MCPToolParameterSchema: () => MCPToolParameterSchema, - MCPToolSchema: () => MCPToolSchema, - MCPTransportConfigSchema: () => MCPTransportConfigSchema, - MCPTransportTypeSchema: () => MCPTransportTypeSchema, - MessageContentSchema: () => MessageContentSchema, - MessageContentTypeSchema: () => MessageContentTypeSchema, - MessagePruningEventSchema: () => MessagePruningEventSchema, - MessageRoleSchema: () => MessageRoleSchema, - MetadataFilterSchema: () => MetadataFilterSchema, - MetadataSourceSchema: () => MetadataSourceSchema22, - ModelCapabilitySchema: () => ModelCapabilitySchema, - ModelConfigSchema: () => ModelConfigSchema, - ModelDriftSchema: () => ModelDriftSchema, - ModelFeatureSchema: () => ModelFeatureSchema, - ModelLimitsSchema: () => ModelLimitsSchema, - ModelPricingSchema: () => ModelPricingSchema, - ModelProviderSchema: () => ModelProviderSchema, - ModelRegistryEntrySchema: () => ModelRegistryEntrySchema, - ModelRegistrySchema: () => ModelRegistrySchema, - ModelSelectionCriteriaSchema: () => ModelSelectionCriteriaSchema, - MonitoringConfigSchema: () => MonitoringConfigSchema, - MultiAgentGroupSchema: () => MultiAgentGroupSchema, - NLQAnalyticsSchema: () => NLQAnalyticsSchema, - NLQFieldMappingSchema: () => NLQFieldMappingSchema, - NLQModelConfigSchema: () => NLQModelConfigSchema, - NLQParseResultSchema: () => NLQParseResultSchema, - NLQRequestSchema: () => NLQRequestSchema, - NLQResponseSchema: () => NLQResponseSchema, - NLQTrainingExampleSchema: () => NLQTrainingExampleSchema, - NavigationActionParamsSchema: () => NavigationActionParamsSchema, - NavigationActionTypeSchema: () => NavigationActionTypeSchema, - NavigationAgentActionSchema: () => NavigationAgentActionSchema, - PerformanceOptimizationSchema: () => PerformanceOptimizationSchema, - PipelineStageSchema: () => PipelineStageSchema, - PluginCompositionRequestSchema: () => PluginCompositionRequestSchema, - PluginCompositionResultSchema: () => PluginCompositionResultSchema, - PluginRecommendationRequestSchema: () => PluginRecommendationRequestSchema, - PluginRecommendationSchema: () => PluginRecommendationSchema, - PluginScaffoldingTemplateSchema: () => PluginScaffoldingTemplateSchema, - PostProcessingActionSchema: () => PostProcessingActionSchema, - PredictionRequestSchema: () => PredictionRequestSchema, - PredictionResultSchema: () => PredictionResultSchema, - PredictiveModelSchema: () => PredictiveModelSchema, - PredictiveModelTypeSchema: () => PredictiveModelTypeSchema, - PromptTemplateSchema: () => PromptTemplateSchema, - PromptVariableSchema: () => PromptVariableSchema, - QueryContextSchema: () => QueryContextSchema, - QueryIntentSchema: () => QueryIntentSchema, - QueryTemplateSchema: () => QueryTemplateSchema, - RAGPipelineConfigSchema: () => RAGPipelineConfigSchema, - RAGPipelineStatusSchema: () => RAGPipelineStatusSchema, - RAGQueryRequestSchema: () => RAGQueryRequestSchema, - RAGQueryResponseSchema: () => RAGQueryResponseSchema, - RerankingConfigSchema: () => RerankingConfigSchema, - ResolutionSchema: () => ResolutionSchema, - RetrievalStrategySchema: () => RetrievalStrategySchema, - RootCauseAnalysisRequestSchema: () => RootCauseAnalysisRequestSchema, - RootCauseAnalysisResultSchema: () => RootCauseAnalysisResultSchema, - SelfHealingActionSchema: () => SelfHealingActionSchema, - SelfHealingConfigSchema: () => SelfHealingConfigSchema, - SkillSchema: () => SkillSchema, - SkillTriggerConditionSchema: () => SkillTriggerConditionSchema, - StructuredOutputConfigSchema: () => StructuredOutputConfigSchema, - StructuredOutputFormatSchema: () => StructuredOutputFormatSchema, - TestingConfigSchema: () => TestingConfigSchema, - TextContentSchema: () => TextContentSchema, - TimeframeSchema: () => TimeframeSchema, - TokenBudgetConfigSchema: () => TokenBudgetConfigSchema, - TokenBudgetStrategySchema: () => TokenBudgetStrategySchema, - TokenUsageSchema: () => TokenUsageSchema, - TokenUsageStatsSchema: () => TokenUsageStatsSchema, - ToolCallSchema: () => ToolCallSchema, - ToolCategorySchema: () => ToolCategorySchema, - ToolSchema: () => ToolSchema, - TrainingConfigSchema: () => TrainingConfigSchema, - TransformPipelineStepSchema: () => TransformPipelineStepSchema, - TypedAgentActionSchema: () => TypedAgentActionSchema, - UIActionTypeSchema: () => UIActionTypeSchema, - VectorStoreConfigSchema: () => VectorStoreConfigSchema, - VectorStoreProviderSchema: () => VectorStoreProviderSchema, - VercelIntegrationSchema: () => VercelIntegrationSchema, - VersionManagementSchema: () => VersionManagementSchema, - ViewActionParamsSchema: () => ViewActionParamsSchema, - ViewActionTypeSchema: () => ViewActionTypeSchema, - ViewAgentActionSchema: () => ViewAgentActionSchema, - WorkflowActionParamsSchema: () => WorkflowActionParamsSchema, - WorkflowActionTypeSchema: () => WorkflowActionTypeSchema, - WorkflowAgentActionSchema: () => WorkflowAgentActionSchema, - WorkflowFieldConditionSchema: () => WorkflowFieldConditionSchema, - WorkflowScheduleSchema: () => WorkflowScheduleSchema, - defineAgent: () => defineAgent, - defineSkill: () => defineSkill, - defineTool: () => defineTool, - fullStackDevOpsAgentExample: () => fullStackDevOpsAgentExample -}); -var AIModelConfigSchema = external_exports.object({ - provider: external_exports.enum(["openai", "azure_openai", "anthropic", "local"]).default("openai"), - model: external_exports.string().describe("Model name (e.g. gpt-4, claude-3-opus)"), - temperature: external_exports.number().min(0).max(2).default(0.7), - maxTokens: external_exports.number().optional(), - topP: external_exports.number().optional() -}); -var AIToolSchema = external_exports.object({ - type: external_exports.enum(["action", "flow", "query", "vector_search"]), - name: external_exports.string().describe("Reference name (Action Name, Flow Name)"), - description: external_exports.string().optional().describe("Override description for the LLM") -}); -var AIKnowledgeSchema = external_exports.object({ - topics: external_exports.array(external_exports.string()).describe("Topics/Tags to recruit knowledge from"), - indexes: external_exports.array(external_exports.string()).describe("Vector Store Indexes") -}); -var StructuredOutputFormatSchema = external_exports.enum([ - "json_object", - "json_schema", - "regex", - "grammar", - "xml" -]).describe("Output format for structured agent responses"); -var TransformPipelineStepSchema = external_exports.enum([ - "trim", - "parse_json", - "validate", - "coerce_types" -]).describe("Post-processing step for structured output"); -var StructuredOutputConfigSchema = external_exports.object({ - /** Output format type */ - format: StructuredOutputFormatSchema.describe("Expected output format"), - /** JSON Schema definition for output validation */ - schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON Schema definition for output"), - /** Whether to enforce exact schema compliance */ - strict: external_exports.boolean().default(false).describe("Enforce exact schema compliance"), - /** Retry on validation failure */ - retryOnValidationFailure: external_exports.boolean().default(true).describe("Retry generation when output fails validation"), - /** Maximum retry attempts */ - maxRetries: external_exports.number().int().min(0).default(3).describe("Maximum retries on validation failure"), - /** Fallback format if primary format fails */ - fallbackFormat: StructuredOutputFormatSchema.optional().describe("Fallback format if primary format fails"), - /** Post-processing pipeline steps */ - transformPipeline: external_exports.array(TransformPipelineStepSchema).optional().describe("Post-processing steps applied to output") -}).describe("Structured output configuration for agent responses"); -var AgentSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Agent unique identifier"), - label: external_exports.string().describe("Agent display name"), - avatar: external_exports.string().optional(), - role: external_exports.string().describe('The persona/role (e.g. "Senior Support Engineer")'), - /** Cognition */ - instructions: external_exports.string().describe("System Prompt / Prime Directives"), - model: AIModelConfigSchema.optional(), - lifecycle: StateMachineSchema4.optional().describe("State machine defining the agent conversation follow and constraints"), - /** Capabilities — Skill-based (primary) */ - skills: external_exports.array(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/)).optional().describe("Skill names to attach (Agent\u2192Skill\u2192Tool architecture)"), - /** Capabilities — Direct tool references (fallback / legacy) */ - tools: external_exports.array(AIToolSchema).optional().describe("Direct tool references (legacy fallback)"), - /** Knowledge */ - knowledge: AIKnowledgeSchema.optional().describe("RAG access"), - /** Interface */ - active: external_exports.boolean().default(true), - access: external_exports.array(external_exports.string()).optional().describe("Who can chat with this agent"), - /** Permission profiles/roles required to use this agent */ - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions or roles"), - /** Multi-tenancy & Visibility */ - tenantId: external_exports.string().optional().describe("Tenant/Organization ID"), - visibility: external_exports.enum(["global", "organization", "private"]).default("organization"), - /** Autonomous Reasoning */ - planning: external_exports.object({ - /** Planning strategy for autonomous reasoning loops */ - strategy: external_exports.enum(["react", "plan_and_execute", "reflexion", "tree_of_thought"]).default("react").describe("Autonomous reasoning strategy"), - /** Maximum reasoning iterations before stopping */ - maxIterations: external_exports.number().int().min(1).max(100).default(10).describe("Maximum planning loop iterations"), - /** Whether the agent can revise its own plan mid-execution */ - allowReplan: external_exports.boolean().default(true).describe("Allow dynamic re-planning based on intermediate results") - }).optional().describe("Autonomous reasoning and planning configuration"), - /** Memory Management */ - memory: external_exports.object({ - /** Short-term (working) memory configuration */ - shortTerm: external_exports.object({ - /** Maximum number of recent messages to retain */ - maxMessages: external_exports.number().int().min(1).default(50).describe("Max recent messages in working memory"), - /** Maximum token budget for short-term context */ - maxTokens: external_exports.number().int().min(100).optional().describe("Max tokens for short-term context window") - }).optional().describe("Short-term / working memory"), - /** Long-term (persistent) memory configuration */ - longTerm: external_exports.object({ - /** Whether long-term memory is enabled */ - enabled: external_exports.boolean().default(false).describe("Enable long-term memory persistence"), - /** Storage backend for long-term memory */ - store: external_exports.enum(["vector", "database", "redis"]).default("vector").describe("Long-term memory storage backend"), - /** Maximum number of persisted memory entries */ - maxEntries: external_exports.number().int().min(1).optional().describe("Max entries in long-term memory") - }).optional().describe("Long-term / persistent memory"), - /** Reflection interval — how often the agent reflects on past actions */ - reflectionInterval: external_exports.number().int().min(1).optional().describe("Reflect every N interactions to improve behavior") - }).optional().describe("Agent memory management"), - /** Guardrails */ - guardrails: external_exports.object({ - /** Maximum tokens the agent may consume per invocation */ - maxTokensPerInvocation: external_exports.number().int().min(1).optional().describe("Token budget per single invocation"), - /** Maximum wall-clock time per invocation in seconds */ - maxExecutionTimeSec: external_exports.number().int().min(1).optional().describe("Max execution time in seconds"), - /** Topics or actions the agent must avoid */ - blockedTopics: external_exports.array(external_exports.string()).optional().describe("Forbidden topics or action names") - }).optional().describe("Safety guardrails for the agent"), - /** Structured Output */ - structuredOutput: StructuredOutputConfigSchema.optional().describe("Structured output format and validation configuration") -}); -function defineAgent(config4) { - return AgentSchema.parse(config4); -} -var ToolCategorySchema = external_exports.enum([ - "data", - // CRUD / query operations - "action", - // Side-effect actions (send email, create record) - "flow", - // Trigger a visual flow - "integration", - // External API / webhook calls - "vector_search", - // RAG / vector search - "analytics", - // Aggregation & reporting - "utility" - // Formatters, parsers, helpers -]).describe("Tool operational category"); -var ToolSchema = external_exports.object({ - /** Machine name (snake_case, globally unique) */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Tool unique identifier (snake_case)"), - /** Human-readable display name */ - label: external_exports.string().describe("Tool display name"), - /** Detailed description for LLM consumption (the model reads this to decide when to call the tool) */ - description: external_exports.string().describe("Tool description for LLM function calling"), - /** Operational category */ - category: ToolCategorySchema.optional().describe("Tool category for grouping and filtering"), - /** - * JSON Schema describing the tool input parameters. - * Must be a valid JSON Schema object. The AI model generates - * arguments conforming to this schema. - */ - parameters: external_exports.record(external_exports.string(), external_exports.unknown()).describe("JSON Schema for tool parameters"), - /** - * Optional JSON Schema for the tool output. - * Used for structured output validation and downstream tool chaining. - */ - outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON Schema for tool output"), - /** - * Associated object name (when the tool operates on a specific data object). - * @example 'support_case' - */ - objectName: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe("Target object name (snake_case)"), - /** Whether the tool requires human confirmation before execution */ - requiresConfirmation: external_exports.boolean().default(false).describe("Require user confirmation before execution"), - /** Permission profiles/roles required to use this tool */ - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions or roles"), - /** Whether the tool is enabled */ - active: external_exports.boolean().default(true).describe("Whether the tool is enabled"), - /** Whether this is a platform built-in tool (vs. user-defined) */ - builtIn: external_exports.boolean().default(false).describe("Platform built-in tool flag") -}); -function defineTool(config4) { - return ToolSchema.parse(config4); -} -var SkillTriggerConditionSchema = external_exports.object({ - /** Condition field (e.g. 'objectName', 'userRole', 'channel') */ - field: external_exports.string().describe("Context field to evaluate"), - /** Comparison operator */ - operator: external_exports.enum(["eq", "neq", "in", "not_in", "contains"]).describe("Comparison operator"), - /** Expected value(s) */ - value: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe("Expected value or values") -}); -var SkillSchema = external_exports.object({ - /** Machine name (snake_case, globally unique) */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Skill unique identifier (snake_case)"), - /** Human-readable display name */ - label: external_exports.string().describe("Skill display name"), - /** Detailed description of the skill's purpose */ - description: external_exports.string().optional().describe("Skill description"), - /** - * Instructions injected into the system prompt when this skill is active. - * Guides the LLM on how and when to use the skill's tools. - */ - instructions: external_exports.string().optional().describe("LLM instructions when skill is active"), - /** - * References to tool names that belong to this skill. - * Tools must be registered as first-class metadata (type: 'tool'). - */ - tools: external_exports.array(external_exports.string().regex(/^[a-z_][a-z0-9_]*$/)).describe("Tool names belonging to this skill"), - /** - * Natural language phrases that trigger skill activation. - * Used for intent matching and skill routing. - */ - triggerPhrases: external_exports.array(external_exports.string()).optional().describe("Phrases that activate this skill"), - /** - * Programmatic conditions for skill activation. - * Evaluated against the runtime context (object name, user role, etc.). - */ - triggerConditions: external_exports.array(SkillTriggerConditionSchema).optional().describe("Programmatic activation conditions"), - /** Permission profiles/roles required to use this skill */ - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions or roles"), - /** Whether the skill is enabled */ - active: external_exports.boolean().default(true).describe("Whether the skill is enabled") -}); -function defineSkill(config4) { - return SkillSchema.parse(config4); -} -var NavigationActionTypeSchema = external_exports.enum([ - "navigate_to_object_list", - // Navigate to object list view - "navigate_to_object_form", - // Navigate to object form (new/edit) - "navigate_to_record_detail", - // Navigate to specific record detail page - "navigate_to_dashboard", - // Navigate to dashboard - "navigate_to_report", - // Navigate to report view - "navigate_to_app", - // Switch to different app - "navigate_back", - // Go back to previous view - "navigate_home", - // Go to home page - "open_tab", - // Open new tab - "close_tab" - // Close current tab -]); -var ViewActionTypeSchema = external_exports.enum([ - "change_view_mode", - // Switch between list/kanban/calendar/gantt - "apply_filter", - // Apply filter to current view - "clear_filter", - // Clear filters - "apply_sort", - // Apply sorting - "change_grouping", - // Change grouping (for kanban/pivot) - "show_columns", - // Show/hide columns - "expand_record", - // Expand record in list - "collapse_record", - // Collapse record in list - "refresh_view", - // Refresh current view - "export_data" - // Export view data -]); -var FormActionTypeSchema = external_exports.enum([ - "create_record", - // Create new record (submit form) - "update_record", - // Update existing record - "delete_record", - // Delete record - "fill_field", - // Fill a specific form field - "clear_field", - // Clear a form field - "submit_form", - // Submit the form - "cancel_form", - // Cancel form editing - "validate_form", - // Validate form data - "save_draft" - // Save as draft -]); -var DataActionTypeSchema = external_exports.enum([ - "select_record", - // Select record(s) in list - "deselect_record", - // Deselect record(s) - "select_all", - // Select all records - "deselect_all", - // Deselect all records - "bulk_update", - // Bulk update selected records - "bulk_delete", - // Bulk delete selected records - "bulk_export" - // Bulk export selected records -]); -var WorkflowActionTypeSchema = external_exports.enum([ - "trigger_flow", - // Trigger a flow/workflow - "trigger_approval", - // Start approval process - "trigger_webhook", - // Trigger webhook - "run_report", - // Run a report - "send_email", - // Send email - "send_notification", - // Send notification - "schedule_task" - // Schedule a task -]); -var ComponentActionTypeSchema = external_exports.enum([ - "open_modal", - // Open modal dialog - "close_modal", - // Close modal dialog - "open_sidebar", - // Open sidebar panel - "close_sidebar", - // Close sidebar panel - "show_notification", - // Show toast/notification - "hide_notification", - // Hide notification - "open_dropdown", - // Open dropdown menu - "close_dropdown", - // Close dropdown menu - "toggle_section" - // Toggle collapsible section -]); -var UIActionTypeSchema = external_exports.union([ - NavigationActionTypeSchema, - ViewActionTypeSchema, - FormActionTypeSchema, - DataActionTypeSchema, - WorkflowActionTypeSchema, - ComponentActionTypeSchema -]); -var NavigationActionParamsSchema = external_exports.object({ - object: external_exports.string().optional().describe("Object name (for object-specific navigation)"), - recordId: external_exports.string().optional().describe("Record ID (for detail page)"), - viewType: external_exports.enum(["list", "form", "detail", "kanban", "calendar", "gantt"]).optional(), - dashboardId: external_exports.string().optional().describe("Dashboard ID"), - reportId: external_exports.string().optional().describe("Report ID"), - appName: external_exports.string().optional().describe("App name"), - mode: external_exports.enum(["new", "edit", "view"]).optional().describe("Form mode"), - openInNewTab: external_exports.boolean().optional().describe("Open in new tab") -}); -var ViewActionParamsSchema = external_exports.object({ - viewMode: external_exports.enum(["list", "kanban", "calendar", "gantt", "pivot"]).optional(), - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter conditions"), - sort: external_exports.array(external_exports.object({ - field: external_exports.string(), - order: external_exports.enum(["asc", "desc"]) - })).optional(), - groupBy: external_exports.string().optional().describe("Field to group by"), - columns: external_exports.array(external_exports.string()).optional().describe("Columns to show/hide"), - recordId: external_exports.string().optional().describe("Record to expand/collapse"), - exportFormat: external_exports.enum(["csv", "xlsx", "pdf", "json"]).optional() -}); -var FormActionParamsSchema = external_exports.object({ - object: external_exports.string().optional().describe("Object name"), - recordId: external_exports.string().optional().describe("Record ID (for edit/delete)"), - fieldValues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Field name-value pairs"), - fieldName: external_exports.string().optional().describe("Specific field to fill/clear"), - fieldValue: external_exports.unknown().optional().describe("Value to set"), - validateOnly: external_exports.boolean().optional().describe("Validate without saving") -}); -var DataActionParamsSchema = external_exports.object({ - recordIds: external_exports.array(external_exports.string()).optional().describe("Record IDs to select/operate on"), - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter for bulk operations"), - updateData: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Data for bulk update"), - exportFormat: external_exports.enum(["csv", "xlsx", "pdf", "json"]).optional() -}); -var WorkflowActionParamsSchema = external_exports.object({ - flowName: external_exports.string().optional().describe("Flow/workflow name"), - approvalProcessName: external_exports.string().optional().describe("Approval process name"), - webhookUrl: external_exports.string().optional().describe("Webhook URL"), - reportName: external_exports.string().optional().describe("Report name"), - emailTemplate: external_exports.string().optional().describe("Email template"), - recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients"), - subject: external_exports.string().optional().describe("Email subject"), - message: external_exports.string().optional().describe("Notification/email message"), - taskData: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Task creation data"), - scheduleTime: external_exports.string().optional().describe("Schedule time (ISO 8601)"), - contextData: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context data") -}); -var ComponentActionParamsSchema = external_exports.object({ - componentId: external_exports.string().optional().describe("Component ID"), - modalConfig: external_exports.object({ - title: external_exports.string().optional(), - content: external_exports.unknown().optional(), - size: external_exports.enum(["small", "medium", "large", "fullscreen"]).optional() - }).optional(), - notificationConfig: external_exports.object({ - type: external_exports.enum(["info", "success", "warning", "error"]).optional(), - message: external_exports.string(), - duration: external_exports.number().optional().describe("Duration in ms") - }).optional(), - sidebarConfig: external_exports.object({ - position: external_exports.enum(["left", "right"]).optional(), - width: external_exports.string().optional(), - content: external_exports.unknown().optional() - }).optional() -}); -var AgentActionSchema = external_exports.object({ - /** - * Action identifier (generated) - */ - id: external_exports.string().optional().describe("Unique action ID"), - /** - * Action type - */ - type: UIActionTypeSchema.describe("Type of UI action to perform"), - /** - * Action parameters (discriminated union based on type) - */ - params: external_exports.union([ - NavigationActionParamsSchema, - ViewActionParamsSchema, - FormActionParamsSchema, - DataActionParamsSchema, - WorkflowActionParamsSchema, - ComponentActionParamsSchema - ]).describe("Action-specific parameters"), - /** - * Confirmation requirement - */ - requireConfirmation: external_exports.boolean().default(false).describe("Require user confirmation before executing"), - /** - * Confirmation message - */ - confirmationMessage: external_exports.string().optional().describe("Message to show in confirmation dialog"), - /** - * Success message - */ - successMessage: external_exports.string().optional().describe("Message to show on success"), - /** - * Error handling - */ - onError: external_exports.enum(["retry", "skip", "abort"]).default("abort").describe("Error handling strategy"), - /** - * Execution metadata - */ - metadata: external_exports.object({ - intent: external_exports.string().optional().describe("Original user intent/query"), - confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), - agentName: external_exports.string().optional().describe("Agent that generated this action"), - timestamp: external_exports.string().datetime().optional().describe("Generation timestamp (ISO 8601)") - }).optional() -}); -var NavigationAgentActionSchema = AgentActionSchema.extend({ - type: NavigationActionTypeSchema, - params: NavigationActionParamsSchema -}); -var ViewAgentActionSchema = AgentActionSchema.extend({ - type: ViewActionTypeSchema, - params: ViewActionParamsSchema -}); -var FormAgentActionSchema = AgentActionSchema.extend({ - type: FormActionTypeSchema, - params: FormActionParamsSchema -}); -var DataAgentActionSchema = AgentActionSchema.extend({ - type: DataActionTypeSchema, - params: DataActionParamsSchema -}); -var WorkflowAgentActionSchema = AgentActionSchema.extend({ - type: WorkflowActionTypeSchema, - params: WorkflowActionParamsSchema -}); -var ComponentAgentActionSchema = AgentActionSchema.extend({ - type: ComponentActionTypeSchema, - params: ComponentActionParamsSchema -}); -var TypedAgentActionSchema = external_exports.union([ - NavigationAgentActionSchema, - ViewAgentActionSchema, - FormAgentActionSchema, - DataAgentActionSchema, - WorkflowAgentActionSchema, - ComponentAgentActionSchema -]); -var AgentActionSequenceSchema = external_exports.object({ - /** - * Sequence identifier - */ - id: external_exports.string().optional().describe("Unique sequence ID"), - /** - * Actions to execute - */ - actions: external_exports.array(AgentActionSchema).describe("Ordered list of actions"), - /** - * Execution mode - */ - mode: external_exports.enum(["sequential", "parallel"]).default("sequential").describe("Execution mode"), - /** - * Stop on first error - */ - stopOnError: external_exports.boolean().default(true).describe("Stop sequence on first error"), - /** - * Transaction mode (all-or-nothing) - */ - atomic: external_exports.boolean().default(false).describe("Transaction mode (all-or-nothing)"), - startTime: external_exports.string().datetime().optional().describe("Execution start time (ISO 8601)"), - endTime: external_exports.string().datetime().optional().describe("Execution end time (ISO 8601)"), - /** - * Metadata - */ - metadata: external_exports.object({ - intent: external_exports.string().optional().describe("Original user intent"), - confidence: external_exports.number().min(0).max(1).optional().describe("Overall confidence score"), - agentName: external_exports.string().optional().describe("Agent that generated this sequence") - }).optional() -}); -var AgentActionResultSchema = external_exports.object({ - /** - * Action ID - */ - actionId: external_exports.string().describe("ID of the executed action"), - /** - * Execution status - */ - status: external_exports.enum(["success", "error", "cancelled", "pending"]).describe("Execution status"), - /** - * Result data - */ - data: external_exports.unknown().optional().describe("Action result data"), - /** - * Error information - */ - error: external_exports.object({ - code: external_exports.string(), - message: external_exports.string(), - details: external_exports.unknown().optional() - }).optional().describe('Error details if status is "error"'), - /** - * Execution metadata - */ - metadata: external_exports.object({ - startTime: external_exports.string().optional().describe("Execution start time (ISO 8601)"), - endTime: external_exports.string().optional().describe("Execution end time (ISO 8601)"), - duration: external_exports.number().optional().describe("Execution duration in ms") - }).optional() -}); -var AgentActionSequenceResultSchema = external_exports.object({ - /** - * Sequence ID - */ - sequenceId: external_exports.string().describe("ID of the executed sequence"), - /** - * Overall status - */ - status: external_exports.enum(["success", "partial_success", "error", "cancelled"]).describe("Overall execution status"), - /** - * Individual action results - */ - results: external_exports.array(AgentActionResultSchema).describe("Results for each action"), - /** - * Summary - */ - summary: external_exports.object({ - total: external_exports.number().describe("Total number of actions"), - successful: external_exports.number().describe("Number of successful actions"), - failed: external_exports.number().describe("Number of failed actions"), - cancelled: external_exports.number().describe("Number of cancelled actions") - }), - /** - * Execution metadata - */ - metadata: external_exports.object({ - startTime: external_exports.string().optional(), - endTime: external_exports.string().optional(), - totalDuration: external_exports.number().optional().describe("Total execution time in ms") - }).optional() -}); -var IntentActionMappingSchema = external_exports.object({ - /** - * Intent pattern (regex or exact match) - */ - intent: external_exports.string().describe('Intent pattern (e.g., "open_new_record_form")'), - /** - * Intent examples (for training) - */ - examples: external_exports.array(external_exports.string()).optional().describe("Example user queries"), - /** - * Action template - */ - actionTemplate: AgentActionSchema.describe("Action to execute"), - /** - * Parameter extraction rules - */ - paramExtraction: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["entity", "slot", "context"]), - required: external_exports.boolean().default(false), - default: external_exports.unknown().optional() - })).optional().describe("Rules for extracting parameters from user input"), - /** - * Confidence threshold - */ - minConfidence: external_exports.number().min(0).max(1).default(0.7).describe("Minimum confidence to execute") -}); -var CodeGenerationTargetSchema = external_exports.enum([ - "frontend", - // Frontend UI components - "backend", - // Backend services - "api", - // API endpoints - "database", - // Database schemas - "tests", - // Test suites - "documentation", - // Documentation - "infrastructure" - // Infrastructure as code -]).describe("Code generation target"); -var CodeGenerationConfigSchema = external_exports.object({ - /** - * Enable code generation - */ - enabled: external_exports.boolean().optional().default(true).describe("Enable code generation"), - /** - * Generation targets - */ - targets: external_exports.array(CodeGenerationTargetSchema).describe("Code generation targets"), - /** - * Template repository - */ - templateRepo: external_exports.string().optional().describe("Template repository for scaffolding"), - /** - * Code style guide - */ - styleGuide: external_exports.string().optional().describe("Code style guide to follow"), - /** - * Include tests - */ - includeTests: external_exports.boolean().optional().default(true).describe("Generate tests with code"), - /** - * Include documentation - */ - includeDocumentation: external_exports.boolean().optional().default(true).describe("Generate documentation"), - /** - * Validation mode - */ - validationMode: external_exports.enum(["strict", "moderate", "permissive"]).optional().default("strict").describe("Code validation strictness") -}); -var TestingConfigSchema = external_exports.object({ - /** - * Enable automated testing - */ - enabled: external_exports.boolean().optional().default(true).describe("Enable automated testing"), - /** - * Test types to run - */ - testTypes: external_exports.array(external_exports.enum([ - "unit", - "integration", - "e2e", - "performance", - "security", - "accessibility" - ])).optional().default(["unit", "integration"]).describe("Types of tests to run"), - /** - * Minimum coverage threshold - */ - coverageThreshold: external_exports.number().min(0).max(100).optional().default(80).describe("Minimum test coverage percentage"), - /** - * Test framework - */ - framework: external_exports.string().optional().describe("Testing framework (e.g., vitest, jest, playwright)"), - /** - * Run tests before commit - */ - preCommitTests: external_exports.boolean().optional().default(true).describe("Run tests before committing"), - /** - * Auto-fix failing tests - */ - autoFix: external_exports.boolean().optional().default(false).describe("Attempt to auto-fix failing tests") -}); -var PipelineStageSchema = external_exports.object({ - /** - * Stage name - */ - name: external_exports.string().describe("Pipeline stage name"), - /** - * Stage type - */ - type: external_exports.enum([ - "build", - "test", - "lint", - "security_scan", - "deploy", - "smoke_test", - "rollback" - ]).describe("Stage type"), - /** - * Stage order - */ - order: external_exports.number().int().min(0).describe("Execution order"), - /** - * Run in parallel - */ - parallel: external_exports.boolean().optional().default(false).describe("Can run in parallel with other stages"), - /** - * Commands to execute - */ - commands: external_exports.array(external_exports.string()).describe("Commands to execute"), - /** - * Environment variables - */ - env: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Stage-specific environment variables"), - /** - * Timeout in seconds - */ - timeout: external_exports.number().int().min(60).optional().default(600).describe("Stage timeout in seconds"), - /** - * Retry on failure - */ - retryOnFailure: external_exports.boolean().optional().default(false).describe("Retry stage on failure"), - /** - * Max retry attempts - */ - maxRetries: external_exports.number().int().min(0).max(5).optional().default(0).describe("Maximum retry attempts") -}); -var CICDPipelineConfigSchema = external_exports.object({ - /** - * Pipeline name - */ - name: external_exports.string().describe("Pipeline name"), - /** - * Pipeline trigger - */ - trigger: external_exports.enum([ - "push", - "pull_request", - "release", - "schedule", - "manual" - ]).describe("Pipeline trigger"), - /** - * Branch filters - */ - branches: external_exports.array(external_exports.string()).optional().describe("Branches to run pipeline on"), - /** - * Pipeline stages - */ - stages: external_exports.array(PipelineStageSchema).describe("Pipeline stages"), - /** - * Enable notifications - */ - notifications: external_exports.object({ - onSuccess: external_exports.boolean().optional().default(false), - onFailure: external_exports.boolean().optional().default(true), - channels: external_exports.array(external_exports.string()).optional().describe("Notification channels (e.g., slack, email)") - }).optional().describe("Pipeline notifications") -}); -var VersionManagementSchema = external_exports.object({ - /** - * Versioning scheme - */ - scheme: external_exports.enum(["semver", "calver", "custom"]).optional().default("semver").describe("Versioning scheme"), - /** - * Auto-increment strategy - */ - autoIncrement: external_exports.enum(["major", "minor", "patch", "none"]).optional().default("patch").describe("Auto-increment strategy"), - /** - * Version prefix - */ - prefix: external_exports.string().optional().default("v").describe("Version tag prefix"), - /** - * Create changelog - */ - generateChangelog: external_exports.boolean().optional().default(true).describe("Generate changelog automatically"), - /** - * Changelog format - */ - changelogFormat: external_exports.enum(["conventional", "keepachangelog", "custom"]).optional().default("conventional").describe("Changelog format"), - /** - * Tag releases - */ - tagReleases: external_exports.boolean().optional().default(true).describe("Create Git tags for releases") -}); -var DeploymentStrategySchema = external_exports.object({ - /** - * Strategy type - */ - type: external_exports.enum([ - "rolling", - "blue_green", - "canary", - "recreate" - ]).optional().default("rolling").describe("Deployment strategy"), - /** - * Canary percentage (for canary deployments) - */ - canaryPercentage: external_exports.number().min(0).max(100).optional().default(10).describe("Canary deployment percentage"), - /** - * Health check URL - */ - healthCheckUrl: external_exports.string().optional().describe("Health check endpoint"), - /** - * Health check timeout - */ - healthCheckTimeout: external_exports.number().int().min(10).optional().default(60).describe("Health check timeout in seconds"), - /** - * Rollback on failure - */ - autoRollback: external_exports.boolean().optional().default(true).describe("Automatically rollback on failure"), - /** - * Smoke tests - */ - smokeTests: external_exports.array(external_exports.string()).optional().describe("Smoke test commands to run post-deployment") -}); -var MonitoringConfigSchema = external_exports.object({ - /** - * Enable monitoring - */ - enabled: external_exports.boolean().optional().default(true).describe("Enable monitoring"), - /** - * Metrics to track - */ - metrics: external_exports.array(external_exports.enum([ - "performance", - "errors", - "usage", - "availability", - "latency" - ])).optional().default(["performance", "errors", "availability"]).describe("Metrics to monitor"), - /** - * Alert thresholds - */ - alerts: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Alert name"), - metric: external_exports.string().describe("Metric to monitor"), - threshold: external_exports.number().describe("Alert threshold"), - severity: external_exports.enum(["info", "warning", "critical"]).describe("Alert severity") - })).optional().describe("Alert configurations"), - /** - * Monitoring integrations - */ - integrations: external_exports.array(external_exports.string()).optional().describe("Monitoring service integrations") -}); -var DevelopmentConfigSchema = external_exports.object({ - /** - * ObjectStack specification source - */ - specificationSource: external_exports.string().describe("Path to ObjectStack specification"), - /** - * Code generation configuration - */ - codeGeneration: CodeGenerationConfigSchema.describe("Code generation settings"), - /** - * Testing configuration - */ - testing: TestingConfigSchema.optional().describe("Testing configuration"), - /** - * Linting configuration - */ - linting: external_exports.object({ - enabled: external_exports.boolean().optional().default(true), - autoFix: external_exports.boolean().optional().default(true), - rules: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional().describe("Code linting configuration"), - /** - * Formatting configuration - */ - formatting: external_exports.object({ - enabled: external_exports.boolean().optional().default(true), - autoFormat: external_exports.boolean().optional().default(true), - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional().describe("Code formatting configuration") -}); -var GitHubIntegrationSchema = external_exports.object({ - /** - * GitHub connector reference - */ - connector: external_exports.string().describe("GitHub connector name"), - /** - * Repository configuration - */ - repository: external_exports.object({ - owner: external_exports.string().describe("Repository owner"), - name: external_exports.string().describe("Repository name") - }).describe("Repository configuration"), - /** - * Default branch for features - */ - featureBranch: external_exports.string().optional().default("develop").describe("Default feature branch"), - /** - * Pull request configuration - */ - pullRequest: external_exports.object({ - autoCreate: external_exports.boolean().optional().default(true).describe("Automatically create PRs"), - autoMerge: external_exports.boolean().optional().default(false).describe("Automatically merge PRs when checks pass"), - requireReviews: external_exports.boolean().optional().default(true).describe("Require reviews before merge"), - deleteBranchOnMerge: external_exports.boolean().optional().default(true).describe("Delete feature branch after merge") - }).optional().describe("Pull request settings") -}); -var VercelIntegrationSchema = external_exports.object({ - /** - * Vercel connector reference - */ - connector: external_exports.string().describe("Vercel connector name"), - /** - * Project name - */ - project: external_exports.string().describe("Vercel project name"), - /** - * Environment mapping - */ - environments: external_exports.object({ - production: external_exports.string().optional().default("main").describe("Production branch"), - preview: external_exports.array(external_exports.string()).optional().default(["develop", "feature/*"]).describe("Preview branches") - }).optional().describe("Environment mapping"), - /** - * Deployment configuration - */ - deployment: external_exports.object({ - autoDeployProduction: external_exports.boolean().optional().default(false).describe("Auto-deploy to production"), - autoDeployPreview: external_exports.boolean().optional().default(true).describe("Auto-deploy preview environments"), - requireApproval: external_exports.boolean().optional().default(true).describe("Require approval for production deployments") - }).optional().describe("Deployment settings") -}); -var IntegrationConfigSchema = external_exports.object({ - /** - * GitHub integration - */ - github: GitHubIntegrationSchema.describe("GitHub integration configuration"), - /** - * Vercel integration - */ - vercel: VercelIntegrationSchema.describe("Vercel integration configuration"), - /** - * Additional integrations - */ - additional: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional integration configurations") -}); -var DevOpsAgentSchema = AgentSchema.extend({ - /** - * Development configuration - */ - developmentConfig: DevelopmentConfigSchema.describe("Development configuration"), - /** - * CI/CD pipelines - */ - pipelines: external_exports.array(CICDPipelineConfigSchema).optional().describe("CI/CD pipelines"), - /** - * Version management - */ - versionManagement: VersionManagementSchema.optional().describe("Version management configuration"), - /** - * Deployment strategy - */ - deploymentStrategy: DeploymentStrategySchema.optional().describe("Deployment strategy"), - /** - * Monitoring configuration - */ - monitoring: MonitoringConfigSchema.optional().describe("Monitoring configuration"), - /** - * Integration configuration - */ - integrations: IntegrationConfigSchema.describe("Integration configurations"), - /** - * Self-iteration configuration - */ - selfIteration: external_exports.object({ - enabled: external_exports.boolean().optional().default(true).describe("Enable self-iteration"), - iterationFrequency: external_exports.string().optional().describe("Iteration frequency (cron expression)"), - optimizationGoals: external_exports.array(external_exports.enum([ - "performance", - "security", - "code_quality", - "test_coverage", - "documentation" - ])).optional().describe("Optimization goals"), - learningMode: external_exports.enum(["conservative", "balanced", "aggressive"]).optional().default("balanced").describe("Learning mode") - }).optional().describe("Self-iteration configuration") -}); -var DevOpsToolSchema = AIToolSchema.extend({ - type: external_exports.enum([ - "action", - "flow", - "query", - "vector_search", - // DevOps-specific tools - "git_operation", - "code_generation", - "test_execution", - "deployment", - "monitoring" - ]) -}); -var fullStackDevOpsAgentExample = { - name: "devops_automation_agent", - label: "DevOps Automation Agent", - visibility: "organization", - avatar: "/avatars/devops-bot.png", - role: "Senior Full-Stack DevOps Engineer", - instructions: `You are an autonomous DevOps agent specialized in enterprise management software development. - -Your responsibilities: -1. Generate code based on ObjectStack specifications -2. Write comprehensive tests for all generated code -3. Ensure code quality through linting and formatting -4. Manage Git workflow (commits, branches, PRs) -5. Deploy applications to Vercel -6. Monitor deployments and handle rollbacks -7. Continuously optimize and iterate on the codebase - -Guidelines: -- Follow ObjectStack naming conventions (camelCase for props, snake_case for names) -- Write clean, maintainable, well-documented code -- Ensure 80%+ test coverage -- Use conventional commit messages -- Create detailed PR descriptions -- Deploy only after all checks pass -- Monitor production deployments closely -- Learn from failures and optimize continuously - -Always prioritize code quality, security, and maintainability.`, - model: { - provider: "openai", - model: "gpt-4-turbo-preview", - temperature: 0.3, - maxTokens: 8192 - }, - tools: [ - { - type: "action", - name: "generate_from_spec", - description: "Generate code from ObjectStack specification" - }, - { - type: "action", - name: "run_tests", - description: "Execute test suites" - }, - { - type: "action", - name: "commit_and_push", - description: "Commit changes and push to GitHub" - }, - { - type: "action", - name: "create_pull_request", - description: "Create pull request on GitHub" - }, - { - type: "action", - name: "deploy_to_vercel", - description: "Deploy application to Vercel" - }, - { - type: "action", - name: "check_deployment_health", - description: "Check deployment health status" - }, - { - type: "action", - name: "rollback_deployment", - description: "Rollback to previous deployment" - } - ], - knowledge: { - topics: [ - "objectstack_protocol", - "typescript_best_practices", - "testing_strategies", - "ci_cd_patterns", - "deployment_strategies" - ], - indexes: ["devops_knowledge_base"] - }, - developmentConfig: { - specificationSource: "packages/spec", - codeGeneration: { - enabled: true, - targets: ["frontend", "backend", "api", "tests", "documentation"], - styleGuide: "objectstack", - includeTests: true, - includeDocumentation: true, - validationMode: "strict" - }, - testing: { - enabled: true, - testTypes: ["unit", "integration", "e2e"], - coverageThreshold: 80, - framework: "vitest", - preCommitTests: true, - autoFix: false - }, - linting: { - enabled: true, - autoFix: true - }, - formatting: { - enabled: true, - autoFormat: true - } - }, - pipelines: [ - { - name: "CI Pipeline", - trigger: "pull_request", - branches: ["main", "develop"], - stages: [ - { - name: "Install Dependencies", - type: "build", - order: 1, - commands: ["pnpm install"], - timeout: 300, - parallel: false, - retryOnFailure: false, - maxRetries: 0 - }, - { - name: "Lint", - type: "lint", - order: 2, - parallel: true, - commands: ["pnpm run lint"], - timeout: 180, - retryOnFailure: false, - maxRetries: 0 - }, - { - name: "Type Check", - type: "lint", - order: 2, - parallel: true, - commands: ["pnpm run type-check"], - timeout: 180, - retryOnFailure: false, - maxRetries: 0 - }, - { - name: "Test", - type: "test", - order: 3, - commands: ["pnpm run test:ci"], - timeout: 600, - parallel: false, - retryOnFailure: false, - maxRetries: 0 - }, - { - name: "Build", - type: "build", - order: 4, - commands: ["pnpm run build"], - timeout: 600, - parallel: false, - retryOnFailure: false, - maxRetries: 0 - }, - { - name: "Security Scan", - type: "security_scan", - order: 5, - commands: ["pnpm audit", "pnpm run security-scan"], - timeout: 300, - parallel: false, - retryOnFailure: false, - maxRetries: 0 - } - ] - }, - { - name: "CD Pipeline", - trigger: "push", - branches: ["main"], - stages: [ - { - name: "Deploy to Production", - type: "deploy", - order: 1, - commands: ["vercel deploy --prod"], - timeout: 600, - parallel: false, - retryOnFailure: false, - maxRetries: 0 - }, - { - name: "Smoke Tests", - type: "smoke_test", - order: 2, - commands: ["pnpm run test:smoke"], - timeout: 300, - parallel: false, - retryOnFailure: true, - maxRetries: 2 - } - ], - notifications: { - onSuccess: true, - onFailure: true, - channels: ["slack", "email"] - } - } - ], - versionManagement: { - scheme: "semver", - autoIncrement: "patch", - prefix: "v", - generateChangelog: true, - changelogFormat: "conventional", - tagReleases: true - }, - deploymentStrategy: { - type: "rolling", - healthCheckUrl: "/api/health", - healthCheckTimeout: 60, - autoRollback: true, - smokeTests: ["pnpm run test:smoke"], - canaryPercentage: 10 - }, - monitoring: { - enabled: true, - metrics: ["performance", "errors", "availability"], - alerts: [ - { - name: "High Error Rate", - metric: "error_rate", - threshold: 0.05, - severity: "critical" - }, - { - name: "Slow Response Time", - metric: "response_time", - threshold: 1e3, - severity: "warning" - } - ], - integrations: ["vercel", "datadog"] - }, - integrations: { - github: { - connector: "github_production", - repository: { - owner: "objectstack-ai", - name: "app" - }, - featureBranch: "develop", - pullRequest: { - autoCreate: true, - autoMerge: false, - requireReviews: true, - deleteBranchOnMerge: true - } - }, - vercel: { - connector: "vercel_production", - project: "objectstack-app", - environments: { - production: "main", - preview: ["develop", "feature/*"] - }, - deployment: { - autoDeployProduction: false, - autoDeployPreview: true, - requireApproval: true - } - } - }, - selfIteration: { - enabled: true, - iterationFrequency: "0 0 * * 0", - // Weekly on Sunday - optimizationGoals: ["code_quality", "test_coverage", "performance"], - learningMode: "balanced" - }, - active: true -}; -var CodeGenerationRequestSchema = external_exports.object({ - /** - * Natural language description of desired functionality - */ - description: external_exports.string().describe("What the plugin should do"), - /** - * Plugin type to generate - */ - pluginType: external_exports.enum([ - "driver", - // Data driver plugin - "app", - // Application plugin - "widget", - // UI widget - "integration", - // External integration - "automation", - // Automation/workflow - "analytics", - // Analytics plugin - "ai-agent", - // AI agent plugin - "custom" - // Custom plugin type - ]), - /** - * Output format for generated code - */ - outputFormat: external_exports.enum([ - "source-code", - // Generate TypeScript/JavaScript source code - "low-code-schema", - // Generate ObjectStack JSON/YAML schema definitions - "dsl" - // Generate domain-specific language definitions - ]).default("source-code").describe("Format of the generated output"), - /** - * Target programming language (for source-code format) - */ - language: external_exports.enum(["typescript", "javascript", "python"]).default("typescript"), - /** - * Framework preferences - */ - framework: external_exports.object({ - runtime: external_exports.enum(["node", "browser", "edge", "universal"]).optional(), - uiFramework: external_exports.enum(["react", "vue", "svelte", "none"]).optional(), - testing: external_exports.enum(["vitest", "jest", "mocha", "none"]).optional() - }).optional(), - /** - * Required capabilities - */ - capabilities: external_exports.array(external_exports.string()).optional().describe("Protocol IDs to implement"), - /** - * Dependencies - */ - dependencies: external_exports.array(external_exports.string()).optional().describe("Required plugin IDs"), - /** - * Example usage (helps AI understand intent) - */ - examples: external_exports.array(external_exports.object({ - input: external_exports.string(), - expectedOutput: external_exports.string(), - description: external_exports.string().optional() - })).optional(), - /** - * Code style preferences (for source-code format) - */ - style: external_exports.object({ - indentation: external_exports.enum(["tab", "2spaces", "4spaces"]).default("2spaces"), - quotes: external_exports.enum(["single", "double"]).default("single"), - semicolons: external_exports.boolean().default(true), - trailingComma: external_exports.boolean().default(true) - }).optional(), - /** - * Low-code schema preferences (for low-code-schema format) - */ - schemaOptions: external_exports.object({ - /** - * Schema format - */ - format: external_exports.enum(["json", "yaml", "typescript"]).default("typescript").describe("Output schema format"), - /** - * Include example data - */ - includeExamples: external_exports.boolean().default(true), - /** - * Validation strictness - */ - strictValidation: external_exports.boolean().default(true), - /** - * Generate UI definitions - */ - generateUI: external_exports.boolean().default(true).describe("Generate view, dashboard, and page definitions"), - /** - * Generate data models - */ - generateDataModels: external_exports.boolean().default(true).describe("Generate object and field definitions") - }).optional(), - /** - * Additional context - */ - context: external_exports.object({ - /** - * Existing code to extend - */ - existingCode: external_exports.string().optional(), - /** - * Related documentation URLs - */ - documentationUrls: external_exports.array(external_exports.string()).optional(), - /** - * Similar plugins for reference - */ - referencePlugins: external_exports.array(external_exports.string()).optional() - }).optional(), - /** - * Generation options - */ - options: external_exports.object({ - /** - * Include tests - */ - generateTests: external_exports.boolean().default(true), - /** - * Include documentation - */ - generateDocs: external_exports.boolean().default(true), - /** - * Include examples - */ - generateExamples: external_exports.boolean().default(true), - /** - * Code coverage target - */ - targetCoverage: external_exports.number().min(0).max(100).default(80), - /** - * Optimization level - */ - optimizationLevel: external_exports.enum(["none", "basic", "aggressive"]).default("basic") - }).optional() -}); -var GeneratedCodeSchema = external_exports.object({ - /** - * Output format used - */ - outputFormat: external_exports.enum(["source-code", "low-code-schema", "dsl"]), - /** - * Main plugin code (for source-code format) - */ - code: external_exports.string().optional(), - /** - * Language used (for source-code format) - */ - language: external_exports.string().optional(), - /** - * Low-code schema definitions (for low-code-schema format) - */ - schemas: external_exports.array(external_exports.object({ - type: external_exports.enum(["object", "view", "dashboard", "app", "workflow", "api", "page"]), - path: external_exports.string().describe("File path for the schema"), - content: external_exports.string().describe("Schema content (JSON/YAML/TypeScript)"), - description: external_exports.string().optional() - })).optional().describe("Generated low-code schema files"), - /** - * File structure - */ - files: external_exports.array(external_exports.object({ - path: external_exports.string(), - content: external_exports.string(), - description: external_exports.string().optional() - })), - /** - * Generated tests - */ - tests: external_exports.array(external_exports.object({ - path: external_exports.string(), - content: external_exports.string(), - coverage: external_exports.number().min(0).max(100).optional() - })).optional(), - /** - * Documentation - */ - documentation: external_exports.object({ - readme: external_exports.string().optional(), - api: external_exports.string().optional(), - usage: external_exports.string().optional() - }).optional(), - /** - * Package metadata - */ - package: external_exports.object({ - name: external_exports.string(), - version: external_exports.string(), - dependencies: external_exports.record(external_exports.string(), external_exports.string()).optional(), - devDependencies: external_exports.record(external_exports.string(), external_exports.string()).optional() - }).optional(), - /** - * Quality metrics - */ - quality: external_exports.object({ - complexity: external_exports.number().optional().describe("Cyclomatic complexity"), - maintainability: external_exports.number().min(0).max(100).optional(), - testCoverage: external_exports.number().min(0).max(100).optional(), - lintScore: external_exports.number().min(0).max(100).optional() - }).optional(), - /** - * AI confidence score - */ - confidence: external_exports.number().min(0).max(100).describe("AI confidence in generated code"), - /** - * Suggestions for improvement - */ - suggestions: external_exports.array(external_exports.string()).optional(), - /** - * Warnings or caveats - */ - warnings: external_exports.array(external_exports.string()).optional() -}); -var PluginScaffoldingTemplateSchema = external_exports.object({ - /** - * Template identifier - */ - id: external_exports.string(), - /** - * Template name - */ - name: external_exports.string(), - /** - * Description - */ - description: external_exports.string(), - /** - * Plugin type - */ - pluginType: external_exports.string(), - /** - * File structure - */ - structure: external_exports.array(external_exports.object({ - type: external_exports.enum(["file", "directory"]), - path: external_exports.string(), - template: external_exports.string().optional().describe("Template content with variables"), - optional: external_exports.boolean().default(false) - })), - /** - * Variables to be filled - */ - variables: external_exports.array(external_exports.object({ - name: external_exports.string(), - description: external_exports.string(), - type: external_exports.enum(["string", "number", "boolean", "array", "object"]), - required: external_exports.boolean().default(true), - default: external_exports.unknown().optional(), - validation: external_exports.string().optional().describe("Validation regex or rule") - })), - /** - * Post-scaffold scripts - */ - scripts: external_exports.array(external_exports.object({ - name: external_exports.string(), - command: external_exports.string(), - description: external_exports.string().optional(), - optional: external_exports.boolean().default(false) - })).optional() -}); -var AICodeReviewResultSchema = external_exports.object({ - /** - * Overall assessment - */ - assessment: external_exports.enum(["excellent", "good", "acceptable", "needs-improvement", "poor"]), - /** - * Overall score (0-100) - */ - score: external_exports.number().min(0).max(100), - /** - * Issues found - */ - issues: external_exports.array(external_exports.object({ - severity: external_exports.enum(["critical", "error", "warning", "info", "style"]), - category: external_exports.enum([ - "bug", - "security", - "performance", - "maintainability", - "style", - "documentation", - "testing", - "type-safety", - "best-practice" - ]), - file: external_exports.string(), - line: external_exports.number().int().optional(), - column: external_exports.number().int().optional(), - message: external_exports.string(), - suggestion: external_exports.string().optional(), - autoFixable: external_exports.boolean().default(false), - autoFix: external_exports.string().optional().describe("Automated fix code") - })), - /** - * Positive highlights - */ - highlights: external_exports.array(external_exports.object({ - category: external_exports.string(), - description: external_exports.string(), - file: external_exports.string().optional() - })).optional(), - /** - * Quality metrics - */ - metrics: external_exports.object({ - complexity: external_exports.number().optional(), - maintainability: external_exports.number().min(0).max(100).optional(), - testCoverage: external_exports.number().min(0).max(100).optional(), - duplicateCode: external_exports.number().min(0).max(100).optional(), - technicalDebt: external_exports.string().optional().describe("Estimated technical debt") - }).optional(), - /** - * Recommendations - */ - recommendations: external_exports.array(external_exports.object({ - priority: external_exports.enum(["high", "medium", "low"]), - title: external_exports.string(), - description: external_exports.string(), - effort: external_exports.enum(["trivial", "small", "medium", "large"]).optional() - })), - /** - * Security analysis - */ - security: external_exports.object({ - vulnerabilities: external_exports.array(external_exports.object({ - severity: external_exports.enum(["critical", "high", "medium", "low"]), - type: external_exports.string(), - description: external_exports.string(), - remediation: external_exports.string().optional() - })).optional(), - score: external_exports.number().min(0).max(100).optional() - }).optional() -}); -var PluginCompositionRequestSchema = external_exports.object({ - /** - * Desired outcome - */ - goal: external_exports.string().describe("What should the composed plugins achieve"), - /** - * Available plugins - */ - availablePlugins: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - version: external_exports.string(), - capabilities: external_exports.array(external_exports.string()).optional(), - description: external_exports.string().optional() - })), - /** - * Constraints - */ - constraints: external_exports.object({ - /** - * Maximum plugins to use - */ - maxPlugins: external_exports.number().int().min(1).optional(), - /** - * Required plugins - */ - requiredPlugins: external_exports.array(external_exports.string()).optional(), - /** - * Excluded plugins - */ - excludedPlugins: external_exports.array(external_exports.string()).optional(), - /** - * Performance requirements - */ - performance: external_exports.object({ - maxLatency: external_exports.number().optional().describe("Maximum latency in ms"), - maxMemory: external_exports.number().optional().describe("Maximum memory in bytes") - }).optional() - }).optional(), - /** - * Optimization criteria - */ - optimize: external_exports.enum([ - "performance", - "reliability", - "simplicity", - "cost", - "security" - ]).optional() -}); -var PluginCompositionResultSchema = external_exports.object({ - /** - * Selected plugins - */ - plugins: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - version: external_exports.string(), - role: external_exports.string().describe("Role in the composition"), - configuration: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - })), - /** - * Integration code - */ - integration: external_exports.object({ - /** - * Glue code to connect plugins - */ - code: external_exports.string(), - /** - * Configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Initialization order - */ - initOrder: external_exports.array(external_exports.string()) - }), - /** - * Data flow diagram - */ - dataFlow: external_exports.array(external_exports.object({ - from: external_exports.string(), - to: external_exports.string(), - data: external_exports.string().describe("Data type or description") - })), - /** - * Expected performance - */ - performance: external_exports.object({ - estimatedLatency: external_exports.number().optional().describe("Estimated latency in ms"), - estimatedMemory: external_exports.number().optional().describe("Estimated memory in bytes") - }).optional(), - /** - * Confidence score - */ - confidence: external_exports.number().min(0).max(100), - /** - * Alternative compositions - */ - alternatives: external_exports.array(external_exports.object({ - description: external_exports.string(), - plugins: external_exports.array(external_exports.string()), - tradeoffs: external_exports.string() - })).optional(), - /** - * Warnings and considerations - */ - warnings: external_exports.array(external_exports.string()).optional() -}); -var PluginRecommendationRequestSchema = external_exports.object({ - /** - * User context - */ - context: external_exports.object({ - /** - * Current plugins installed - */ - installedPlugins: external_exports.array(external_exports.string()).optional(), - /** - * User's industry - */ - industry: external_exports.string().optional(), - /** - * Use cases - */ - useCases: external_exports.array(external_exports.string()).optional(), - /** - * Team size - */ - teamSize: external_exports.number().int().optional(), - /** - * Budget constraints - */ - budget: external_exports.enum(["free", "low", "medium", "high", "unlimited"]).optional() - }), - /** - * Recommendation criteria - */ - criteria: external_exports.object({ - /** - * Prioritize by - */ - prioritize: external_exports.enum([ - "popularity", - "rating", - "compatibility", - "features", - "cost", - "support" - ]).optional(), - /** - * Only certified plugins - */ - certifiedOnly: external_exports.boolean().default(false), - /** - * Minimum rating - */ - minRating: external_exports.number().min(0).max(5).optional(), - /** - * Maximum results - */ - maxResults: external_exports.number().int().min(1).max(50).default(10) - }).optional() -}); -var PluginRecommendationSchema = external_exports.object({ - /** - * Recommended plugins - */ - recommendations: external_exports.array(external_exports.object({ - pluginId: external_exports.string(), - name: external_exports.string(), - description: external_exports.string(), - score: external_exports.number().min(0).max(100).describe("Relevance score"), - reasons: external_exports.array(external_exports.string()).describe("Why this plugin is recommended"), - benefits: external_exports.array(external_exports.string()), - considerations: external_exports.array(external_exports.string()).optional(), - alternatives: external_exports.array(external_exports.string()).optional(), - estimatedValue: external_exports.string().optional().describe("Expected value/ROI") - })), - /** - * Recommended combinations - */ - combinations: external_exports.array(external_exports.object({ - plugins: external_exports.array(external_exports.string()), - description: external_exports.string(), - synergies: external_exports.array(external_exports.string()).describe("How these plugins work well together"), - totalScore: external_exports.number().min(0).max(100) - })).optional(), - /** - * Learning path - */ - learningPath: external_exports.array(external_exports.object({ - step: external_exports.number().int(), - plugin: external_exports.string(), - reason: external_exports.string(), - resources: external_exports.array(external_exports.string()).optional() - })).optional() -}); -var AnomalyDetectionConfigSchema = external_exports.object({ - /** - * Enable anomaly detection - */ - enabled: external_exports.boolean().default(true), - /** - * Metrics to monitor - */ - metrics: external_exports.array(external_exports.enum([ - "cpu-usage", - "memory-usage", - "response-time", - "error-rate", - "throughput", - "latency", - "connection-count", - "queue-depth" - ])), - /** - * Detection algorithm - */ - algorithm: external_exports.enum([ - "statistical", - // Statistical thresholds - "machine-learning", - // ML-based detection - "heuristic", - // Rule-based heuristics - "hybrid" - // Combination of methods - ]).default("hybrid"), - /** - * Sensitivity level - */ - sensitivity: external_exports.enum(["low", "medium", "high"]).default("medium").describe("How aggressively to detect anomalies"), - /** - * Time window for analysis (seconds) - */ - timeWindow: external_exports.number().int().min(60).default(300).describe("Historical data window for anomaly detection"), - /** - * Confidence threshold (0-100) - */ - confidenceThreshold: external_exports.number().min(0).max(100).default(80).describe("Minimum confidence to flag as anomaly"), - /** - * Alert on detection - */ - alertOnDetection: external_exports.boolean().default(true) -}); -var SelfHealingActionSchema = external_exports.object({ - /** - * Action identifier - */ - id: external_exports.string(), - /** - * Action type - */ - type: external_exports.enum([ - "restart", - // Restart the plugin - "scale", - // Scale resources - "rollback", - // Rollback to previous version - "clear-cache", - // Clear caches - "adjust-config", - // Adjust configuration - "execute-script", - // Run custom script - "notify" - // Notify administrators - ]), - /** - * Trigger condition - */ - trigger: external_exports.object({ - /** - * Health status that triggers this action - */ - healthStatus: external_exports.array(PluginHealthStatusSchema2).optional(), - /** - * Anomaly types that trigger this action - */ - anomalyTypes: external_exports.array(external_exports.string()).optional(), - /** - * Error patterns that trigger this action - */ - errorPatterns: external_exports.array(external_exports.string()).optional(), - /** - * Custom condition expression - */ - customCondition: external_exports.string().optional().describe('Custom trigger condition (e.g., "errorRate > 0.1")') - }), - /** - * Action parameters - */ - parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** - * Maximum number of attempts - */ - maxAttempts: external_exports.number().int().min(1).default(3), - /** - * Cooldown period between attempts (seconds) - */ - cooldown: external_exports.number().int().min(0).default(60), - /** - * Timeout for action execution (seconds) - */ - timeout: external_exports.number().int().min(1).default(300), - /** - * Require manual approval - */ - requireApproval: external_exports.boolean().default(false), - /** - * Priority - */ - priority: external_exports.number().int().min(1).default(5).describe("Action priority (lower number = higher priority)") -}); -var SelfHealingConfigSchema = external_exports.object({ - /** - * Enable self-healing - */ - enabled: external_exports.boolean().default(true), - /** - * Healing strategy - */ - strategy: external_exports.enum([ - "conservative", - // Only safe, proven actions - "moderate", - // Balanced approach - "aggressive" - // Try more recovery options - ]).default("moderate"), - /** - * Recovery actions - */ - actions: external_exports.array(SelfHealingActionSchema), - /** - * Anomaly detection - */ - anomalyDetection: AnomalyDetectionConfigSchema.optional(), - /** - * Maximum concurrent healing operations - */ - maxConcurrentHealing: external_exports.number().int().min(1).default(1).describe("Maximum number of simultaneous healing attempts"), - /** - * Learning mode - */ - learning: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Learn from successful/failed healing attempts"), - feedbackLoop: external_exports.boolean().default(true).describe("Adjust strategy based on outcomes") - }).optional() -}); -var AutoScalingPolicySchema = external_exports.object({ - /** - * Enable auto-scaling - */ - enabled: external_exports.boolean().default(false), - /** - * Scaling metric - */ - metric: external_exports.enum([ - "cpu-usage", - "memory-usage", - "request-rate", - "response-time", - "queue-depth", - "custom" - ]), - /** - * Custom metric query (when metric is "custom") - */ - customMetric: external_exports.string().optional(), - /** - * Target value for the metric - */ - targetValue: external_exports.number().describe("Desired metric value (e.g., 70 for 70% CPU)"), - /** - * Scaling bounds - */ - bounds: external_exports.object({ - /** - * Minimum instances - */ - minInstances: external_exports.number().int().min(1).default(1), - /** - * Maximum instances - */ - maxInstances: external_exports.number().int().min(1).default(10), - /** - * Minimum resources per instance - */ - minResources: external_exports.object({ - cpu: external_exports.string().optional().describe('CPU limit (e.g., "0.5", "1")'), - memory: external_exports.string().optional().describe('Memory limit (e.g., "512Mi", "1Gi")') - }).optional(), - /** - * Maximum resources per instance - */ - maxResources: external_exports.object({ - cpu: external_exports.string().optional(), - memory: external_exports.string().optional() - }).optional() - }), - /** - * Scale up behavior - */ - scaleUp: external_exports.object({ - /** - * Threshold to trigger scale up - */ - threshold: external_exports.number().describe("Metric value that triggers scale up"), - /** - * Stabilization window (seconds) - */ - stabilizationWindow: external_exports.number().int().min(0).default(60).describe("How long metric must exceed threshold"), - /** - * Cooldown period (seconds) - */ - cooldown: external_exports.number().int().min(0).default(300).describe("Minimum time between scale-up operations"), - /** - * Step size - */ - stepSize: external_exports.number().int().min(1).default(1).describe("Number of instances to add") - }), - /** - * Scale down behavior - */ - scaleDown: external_exports.object({ - /** - * Threshold to trigger scale down - */ - threshold: external_exports.number().describe("Metric value that triggers scale down"), - /** - * Stabilization window (seconds) - */ - stabilizationWindow: external_exports.number().int().min(0).default(300).describe("How long metric must be below threshold"), - /** - * Cooldown period (seconds) - */ - cooldown: external_exports.number().int().min(0).default(600).describe("Minimum time between scale-down operations"), - /** - * Step size - */ - stepSize: external_exports.number().int().min(1).default(1).describe("Number of instances to remove") - }), - /** - * Predictive scaling - */ - predictive: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Use ML to predict future load"), - lookAhead: external_exports.number().int().min(60).default(300).describe("How far ahead to predict (seconds)"), - confidence: external_exports.number().min(0).max(100).default(80).describe("Minimum confidence for prediction-based scaling") - }).optional() -}); -var RootCauseAnalysisRequestSchema = external_exports.object({ - /** - * Incident identifier - */ - incidentId: external_exports.string(), - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Symptoms observed - */ - symptoms: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Symptom type"), - description: external_exports.string(), - severity: external_exports.enum(["low", "medium", "high", "critical"]), - timestamp: external_exports.string().datetime() - })), - /** - * Time range for analysis - */ - timeRange: external_exports.object({ - start: external_exports.string().datetime(), - end: external_exports.string().datetime() - }), - /** - * Include log analysis - */ - analyzeLogs: external_exports.boolean().default(true), - /** - * Include metric analysis - */ - analyzeMetrics: external_exports.boolean().default(true), - /** - * Include dependency analysis - */ - analyzeDependencies: external_exports.boolean().default(true), - /** - * Context information - */ - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var RootCauseAnalysisResultSchema = external_exports.object({ - /** - * Analysis identifier - */ - analysisId: external_exports.string(), - /** - * Incident identifier - */ - incidentId: external_exports.string(), - /** - * Identified root causes - */ - rootCauses: external_exports.array(external_exports.object({ - /** - * Cause identifier - */ - id: external_exports.string(), - /** - * Description - */ - description: external_exports.string(), - /** - * Confidence score (0-100) - */ - confidence: external_exports.number().min(0).max(100), - /** - * Category - */ - category: external_exports.enum([ - "code-defect", - "configuration", - "resource-exhaustion", - "dependency-failure", - "network-issue", - "data-corruption", - "security-breach", - "other" - ]), - /** - * Evidence - */ - evidence: external_exports.array(external_exports.object({ - type: external_exports.enum(["log", "metric", "trace", "event"]), - content: external_exports.string(), - timestamp: external_exports.string().datetime().optional() - })), - /** - * Impact assessment - */ - impact: external_exports.enum(["low", "medium", "high", "critical"]), - /** - * Recommended actions - */ - recommendations: external_exports.array(external_exports.string()) - })), - /** - * Contributing factors - */ - contributingFactors: external_exports.array(external_exports.object({ - description: external_exports.string(), - confidence: external_exports.number().min(0).max(100) - })).optional(), - /** - * Timeline of events - */ - timeline: external_exports.array(external_exports.object({ - timestamp: external_exports.string().datetime(), - event: external_exports.string(), - significance: external_exports.enum(["low", "medium", "high"]) - })).optional(), - /** - * Remediation plan - */ - remediation: external_exports.object({ - /** - * Immediate actions - */ - immediate: external_exports.array(external_exports.string()), - /** - * Short-term fixes - */ - shortTerm: external_exports.array(external_exports.string()), - /** - * Long-term improvements - */ - longTerm: external_exports.array(external_exports.string()) - }).optional(), - /** - * Overall confidence in analysis - */ - overallConfidence: external_exports.number().min(0).max(100), - /** - * Analysis timestamp - */ - timestamp: external_exports.string().datetime() -}); -var PerformanceOptimizationSchema = external_exports.object({ - /** - * Optimization identifier - */ - id: external_exports.string(), - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Optimization type - */ - type: external_exports.enum([ - "caching", - "query-optimization", - "resource-allocation", - "code-refactoring", - "architecture-change", - "configuration-tuning" - ]), - /** - * Description - */ - description: external_exports.string(), - /** - * Expected impact - */ - expectedImpact: external_exports.object({ - /** - * Performance improvement percentage - */ - performanceGain: external_exports.number().min(0).max(100).describe("Expected performance improvement (%)"), - /** - * Resource savings - */ - resourceSavings: external_exports.object({ - cpu: external_exports.number().optional().describe("CPU reduction (%)"), - memory: external_exports.number().optional().describe("Memory reduction (%)"), - network: external_exports.number().optional().describe("Network reduction (%)") - }).optional(), - /** - * Cost reduction - */ - costReduction: external_exports.number().optional().describe("Estimated cost reduction (%)") - }), - /** - * Implementation difficulty - */ - difficulty: external_exports.enum(["trivial", "easy", "moderate", "complex", "very-complex"]), - /** - * Implementation steps - */ - steps: external_exports.array(external_exports.string()), - /** - * Risks and considerations - */ - risks: external_exports.array(external_exports.string()).optional(), - /** - * Confidence score - */ - confidence: external_exports.number().min(0).max(100), - /** - * Priority - */ - priority: external_exports.enum(["low", "medium", "high", "critical"]) -}); -var AIOpsAgentConfigSchema = external_exports.object({ - /** - * Agent identifier - */ - agentId: external_exports.string(), - /** - * Plugin identifier - */ - pluginId: external_exports.string(), - /** - * Self-healing configuration - */ - selfHealing: SelfHealingConfigSchema.optional(), - /** - * Auto-scaling policies - */ - autoScaling: external_exports.array(AutoScalingPolicySchema).optional(), - /** - * Continuous monitoring - */ - monitoring: external_exports.object({ - enabled: external_exports.boolean().default(true), - interval: external_exports.number().int().min(1e3).default(6e4).describe("Monitoring interval in milliseconds"), - /** - * Metrics to collect - */ - metrics: external_exports.array(external_exports.string()).optional() - }).optional(), - /** - * Proactive optimization - */ - optimization: external_exports.object({ - enabled: external_exports.boolean().default(true), - /** - * Scan interval (seconds) - */ - scanInterval: external_exports.number().int().min(3600).default(86400).describe("How often to scan for optimization opportunities"), - /** - * Auto-apply optimizations - */ - autoApply: external_exports.boolean().default(false).describe("Automatically apply low-risk optimizations") - }).optional(), - /** - * Incident response - */ - incidentResponse: external_exports.object({ - enabled: external_exports.boolean().default(true), - /** - * Auto-trigger root cause analysis - */ - autoRCA: external_exports.boolean().default(true), - /** - * Notification channels - */ - notifications: external_exports.array(external_exports.object({ - channel: external_exports.enum(["email", "slack", "webhook", "sms"]), - config: external_exports.record(external_exports.string(), external_exports.unknown()) - })).optional() - }).optional() -}); -var ModelProviderSchema = external_exports.enum([ - "openai", - "azure_openai", - "anthropic", - "google", - "cohere", - "huggingface", - "local", - "custom" -]); -var ModelCapabilitySchema = external_exports.object({ - textGeneration: external_exports.boolean().optional().default(true).describe("Supports text generation"), - textEmbedding: external_exports.boolean().optional().default(false).describe("Supports text embedding"), - imageGeneration: external_exports.boolean().optional().default(false).describe("Supports image generation"), - imageUnderstanding: external_exports.boolean().optional().default(false).describe("Supports image understanding"), - functionCalling: external_exports.boolean().optional().default(false).describe("Supports function calling"), - codeGeneration: external_exports.boolean().optional().default(false).describe("Supports code generation"), - reasoning: external_exports.boolean().optional().default(false).describe("Supports advanced reasoning") -}); -var ModelLimitsSchema = external_exports.object({ - maxTokens: external_exports.number().int().positive().describe("Maximum tokens per request"), - contextWindow: external_exports.number().int().positive().describe("Context window size"), - maxOutputTokens: external_exports.number().int().positive().optional().describe("Maximum output tokens"), - rateLimit: external_exports.object({ - requestsPerMinute: external_exports.number().int().positive().optional(), - tokensPerMinute: external_exports.number().int().positive().optional() - }).optional() -}); -var ModelPricingSchema = external_exports.object({ - currency: external_exports.string().optional().default("USD"), - inputCostPer1kTokens: external_exports.number().optional().describe("Cost per 1K input tokens"), - outputCostPer1kTokens: external_exports.number().optional().describe("Cost per 1K output tokens"), - embeddingCostPer1kTokens: external_exports.number().optional().describe("Cost per 1K embedding tokens") -}); -var ModelConfigSchema = external_exports.object({ - /** Identity */ - id: external_exports.string().describe("Unique model identifier"), - name: external_exports.string().describe("Model display name"), - version: external_exports.string().describe('Model version (e.g., "gpt-4-turbo-2024-04-09")'), - provider: ModelProviderSchema, - /** Capabilities */ - capabilities: ModelCapabilitySchema, - limits: ModelLimitsSchema, - /** Pricing */ - pricing: ModelPricingSchema.optional(), - /** Configuration */ - endpoint: external_exports.string().url().optional().describe("Custom API endpoint"), - apiKey: external_exports.string().optional().describe("API key (Warning: Prefer secretRef)"), - secretRef: external_exports.string().optional().describe("Reference to stored secret (e.g. system:openai_api_key)"), - region: external_exports.string().optional().describe('Deployment region (e.g., "us-east-1")'), - /** Metadata */ - description: external_exports.string().optional(), - tags: external_exports.array(external_exports.string()).optional().describe("Tags for categorization"), - deprecated: external_exports.boolean().optional().default(false), - recommendedFor: external_exports.array(external_exports.string()).optional().describe("Use case recommendations") -}); -var PromptVariableSchema = external_exports.object({ - name: external_exports.string().describe('Variable name (e.g., "user_name", "context")'), - type: external_exports.enum(["string", "number", "boolean", "object", "array"]).default("string"), - required: external_exports.boolean().default(false), - defaultValue: external_exports.unknown().optional(), - description: external_exports.string().optional(), - validation: external_exports.object({ - minLength: external_exports.number().optional(), - maxLength: external_exports.number().optional(), - pattern: external_exports.string().optional(), - enum: external_exports.array(external_exports.unknown()).optional() - }).optional() -}); -var PromptTemplateSchema = external_exports.object({ - /** Identity */ - id: external_exports.string().describe("Unique template identifier"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Template name (snake_case)"), - label: external_exports.string().describe("Display name"), - /** Template Content */ - system: external_exports.string().optional().describe("System prompt"), - user: external_exports.string().describe("User prompt template with variables"), - assistant: external_exports.string().optional().describe("Assistant message prefix"), - /** Variables */ - variables: external_exports.array(PromptVariableSchema).optional().describe("Template variables"), - /** Model Configuration */ - modelId: external_exports.string().optional().describe("Recommended model ID"), - temperature: external_exports.number().min(0).max(2).optional(), - maxTokens: external_exports.number().optional(), - topP: external_exports.number().optional(), - frequencyPenalty: external_exports.number().optional(), - presencePenalty: external_exports.number().optional(), - stopSequences: external_exports.array(external_exports.string()).optional(), - /** Metadata */ - version: external_exports.string().optional().default("1.0.0"), - description: external_exports.string().optional(), - category: external_exports.string().optional().describe('Template category (e.g., "code_generation", "support")'), - tags: external_exports.array(external_exports.string()).optional(), - examples: external_exports.array(external_exports.object({ - input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Example variable values"), - output: external_exports.string().describe("Expected output") - })).optional() -}); -var ModelRegistryEntrySchema = external_exports.object({ - model: ModelConfigSchema, - status: external_exports.enum(["active", "deprecated", "experimental", "disabled"]).default("active"), - priority: external_exports.number().int().default(0).describe("Priority for model selection"), - fallbackModels: external_exports.array(external_exports.string()).optional().describe("Fallback model IDs"), - healthCheck: external_exports.object({ - enabled: external_exports.boolean().default(true), - intervalSeconds: external_exports.number().int().default(300), - lastChecked: external_exports.string().optional().describe("ISO timestamp"), - status: external_exports.enum(["healthy", "unhealthy", "unknown"]).default("unknown") - }).optional() -}); -var ModelRegistrySchema = external_exports.object({ - name: external_exports.string().describe("Registry name"), - models: external_exports.record(external_exports.string(), ModelRegistryEntrySchema).describe("Model entries by ID"), - promptTemplates: external_exports.record(external_exports.string(), PromptTemplateSchema).optional().describe("Prompt templates by name"), - defaultModel: external_exports.string().optional().describe("Default model ID"), - enableAutoFallback: external_exports.boolean().default(true).describe("Auto-fallback on errors") -}); -var ModelSelectionCriteriaSchema = external_exports.object({ - capabilities: external_exports.array(external_exports.string()).optional().describe("Required capabilities"), - maxCostPer1kTokens: external_exports.number().optional().describe("Maximum acceptable cost"), - minContextWindow: external_exports.number().optional().describe("Minimum context window size"), - provider: ModelProviderSchema.optional(), - tags: external_exports.array(external_exports.string()).optional(), - excludeDeprecated: external_exports.boolean().default(true) -}); -var MCPTransportTypeSchema = external_exports.enum([ - "stdio", - // Standard input/output (for local processes) - "http", - // HTTP REST API - "websocket", - // WebSocket bidirectional communication - "grpc" - // gRPC for high-performance communication -]); -var MCPTransportConfigSchema = external_exports.object({ - type: MCPTransportTypeSchema, - /** HTTP/WebSocket Configuration */ - url: external_exports.string().url().optional().describe("Server URL (for HTTP/WebSocket/gRPC)"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for requests"), - /** Authentication */ - auth: external_exports.object({ - type: external_exports.enum(["none", "bearer", "api_key", "oauth2", "custom"]).default("none"), - token: external_exports.string().optional().describe("Bearer token or API key"), - secretRef: external_exports.string().optional().describe("Reference to stored secret"), - headerName: external_exports.string().optional().describe("Custom auth header name") - }).optional(), - /** Connection Options */ - timeout: external_exports.number().int().positive().optional().default(3e4).describe("Request timeout in milliseconds"), - retryAttempts: external_exports.number().int().min(0).max(5).optional().default(3), - retryDelay: external_exports.number().int().positive().optional().default(1e3).describe("Delay between retries in milliseconds"), - /** STDIO Configuration */ - command: external_exports.string().optional().describe("Command to execute (for stdio transport)"), - args: external_exports.array(external_exports.string()).optional().describe("Command arguments"), - env: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Environment variables"), - workingDirectory: external_exports.string().optional().describe("Working directory for the process") -}); -var MCPResourceTypeSchema = external_exports.enum([ - "text", - // Plain text or markdown content - "json", - // Structured JSON data - "binary", - // Binary data (files, images, etc.) - "stream" - // Streaming data -]); -var MCPResourceSchema = external_exports.object({ - /** Identity */ - uri: external_exports.string().describe('Unique resource identifier (e.g., "objectstack://objects/account/ABC123")'), - name: external_exports.string().describe("Human-readable resource name"), - description: external_exports.string().optional().describe("Resource description for AI consumption"), - /** Resource Type */ - mimeType: external_exports.string().optional().describe('MIME type (e.g., "application/json", "text/plain")'), - resourceType: MCPResourceTypeSchema.default("json"), - /** Content */ - content: external_exports.unknown().optional().describe("Resource content (for static resources)"), - contentUrl: external_exports.string().url().optional().describe("URL to fetch content dynamically"), - /** Metadata */ - size: external_exports.number().int().nonnegative().optional().describe("Resource size in bytes"), - lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp (ISO 8601)"), - tags: external_exports.array(external_exports.string()).optional().describe("Tags for resource categorization"), - /** Access Control */ - permissions: external_exports.object({ - read: external_exports.boolean().default(true), - write: external_exports.boolean().default(false), - delete: external_exports.boolean().default(false) - }).optional(), - /** Caching */ - cacheable: external_exports.boolean().default(true).describe("Whether this resource can be cached"), - cacheMaxAge: external_exports.number().int().nonnegative().optional().describe("Cache max age in seconds") -}); -var MCPResourceTemplateSchema = external_exports.object({ - uriPattern: external_exports.string().describe('URI pattern with variables (e.g., "objectstack://objects/{objectName}/{recordId}")'), - name: external_exports.string().describe("Template name"), - description: external_exports.string().optional(), - /** Parameters */ - parameters: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Parameter name"), - type: external_exports.enum(["string", "number", "boolean"]).default("string"), - required: external_exports.boolean().default(true), - description: external_exports.string().optional(), - pattern: external_exports.string().optional().describe("Regex validation pattern"), - default: external_exports.unknown().optional() - })).describe("URI parameters"), - /** Generation Logic */ - handler: external_exports.string().optional().describe("Handler function name for dynamic generation"), - mimeType: external_exports.string().optional(), - resourceType: MCPResourceTypeSchema.default("json") -}); -var MCPToolParameterSchema = external_exports.object({ - name: external_exports.string().describe("Parameter name"), - type: external_exports.enum(["string", "number", "boolean", "object", "array"]), - description: external_exports.string().describe("Parameter description for AI consumption"), - required: external_exports.boolean().default(false), - default: external_exports.unknown().optional(), - /** Validation */ - enum: external_exports.array(external_exports.unknown()).optional().describe("Allowed values"), - pattern: external_exports.string().optional().describe("Regex validation pattern (for strings)"), - minimum: external_exports.number().optional().describe("Minimum value (for numbers)"), - maximum: external_exports.number().optional().describe("Maximum value (for numbers)"), - minLength: external_exports.number().int().nonnegative().optional().describe("Minimum length (for strings/arrays)"), - maxLength: external_exports.number().int().nonnegative().optional().describe("Maximum length (for strings/arrays)"), - /** Nested Schema */ - properties: external_exports.record(external_exports.string(), external_exports.lazy(() => MCPToolParameterSchema)).optional().describe("Properties for object types"), - items: external_exports.lazy(() => MCPToolParameterSchema).optional().describe("Item schema for array types") -}); -var MCPToolSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Tool function name (snake_case)"), - description: external_exports.string().describe("Tool description for AI consumption (be detailed and specific)"), - /** Parameters */ - parameters: external_exports.array(MCPToolParameterSchema).describe("Tool parameters"), - /** Return Type */ - returns: external_exports.object({ - type: external_exports.enum(["string", "number", "boolean", "object", "array", "void"]), - description: external_exports.string().optional(), - schema: MCPToolParameterSchema.optional().describe("Return value schema") - }).optional(), - /** Execution Configuration */ - handler: external_exports.string().describe("Handler function or endpoint reference"), - async: external_exports.boolean().default(true).describe("Whether the tool executes asynchronously"), - timeout: external_exports.number().int().positive().optional().describe("Execution timeout in milliseconds"), - /** Side Effects */ - sideEffects: external_exports.enum(["none", "read", "write", "delete"]).default("read").describe("Tool side effects"), - requiresConfirmation: external_exports.boolean().default(false).describe("Require user confirmation before execution"), - confirmationMessage: external_exports.string().optional(), - /** Examples */ - examples: external_exports.array(external_exports.object({ - description: external_exports.string(), - parameters: external_exports.record(external_exports.string(), external_exports.unknown()), - result: external_exports.unknown().optional() - })).optional().describe("Usage examples for AI learning"), - /** Metadata */ - category: external_exports.string().optional().describe('Tool category (e.g., "data", "workflow", "analytics")'), - tags: external_exports.array(external_exports.string()).optional(), - deprecated: external_exports.boolean().default(false), - version: external_exports.string().optional().default("1.0.0") -}); -var MCPPromptArgumentSchema = external_exports.object({ - name: external_exports.string().describe("Argument name"), - description: external_exports.string().optional(), - type: external_exports.enum(["string", "number", "boolean"]).default("string"), - required: external_exports.boolean().default(false), - default: external_exports.unknown().optional() -}); -var MCPPromptMessageSchema = external_exports.object({ - role: external_exports.enum(["system", "user", "assistant"]).describe("Message role"), - content: external_exports.string().describe("Message content (can include {{variable}} placeholders)") -}); -var MCPPromptSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Prompt template name (snake_case)"), - description: external_exports.string().optional().describe("Prompt description"), - /** Template */ - messages: external_exports.array(MCPPromptMessageSchema).describe("Prompt message sequence"), - /** Arguments */ - arguments: external_exports.array(MCPPromptArgumentSchema).optional().describe("Dynamic arguments for the prompt"), - /** Metadata */ - category: external_exports.string().optional(), - tags: external_exports.array(external_exports.string()).optional(), - version: external_exports.string().optional().default("1.0.0") -}); -var MCPStreamingConfigSchema = external_exports.object({ - /** Whether streaming is enabled */ - enabled: external_exports.boolean().describe("Enable streaming for MCP communication"), - /** Size of each streamed chunk in bytes */ - chunkSize: external_exports.number().int().positive().optional().describe("Size of each streamed chunk in bytes"), - /** Heartbeat interval to keep connection alive */ - heartbeatIntervalMs: external_exports.number().int().positive().optional().default(3e4).describe("Heartbeat interval in milliseconds"), - /** Backpressure handling strategy */ - backpressure: external_exports.enum(["drop", "buffer", "block"]).optional().describe("Backpressure handling strategy") -}).describe("Streaming configuration for MCP communication"); -var MCPToolApprovalSchema = external_exports.object({ - /** Whether tool execution requires approval */ - requireApproval: external_exports.boolean().default(false).describe("Require approval before tool execution"), - /** Strategy for handling approvals */ - approvalStrategy: external_exports.enum(["human_in_loop", "auto_approve", "policy_based"]).describe("Approval strategy for tool execution"), - /** Regex patterns matching tool names that require approval */ - dangerousToolPatterns: external_exports.array(external_exports.string()).optional().describe("Regex patterns for tools needing approval"), - /** Timeout in seconds for auto-approval */ - autoApproveTimeout: external_exports.number().int().positive().optional().describe("Auto-approve timeout in seconds") -}).describe("Tool approval configuration for MCP"); -var MCPSamplingConfigSchema = external_exports.object({ - /** Whether sampling is enabled */ - enabled: external_exports.boolean().describe("Enable LLM sampling"), - /** Maximum tokens to generate */ - maxTokens: external_exports.number().int().positive().describe("Maximum tokens to generate"), - /** Sampling temperature */ - temperature: external_exports.number().min(0).max(2).optional().describe("Sampling temperature"), - /** Stop sequences to end generation */ - stopSequences: external_exports.array(external_exports.string()).optional().describe("Stop sequences to end generation"), - /** Preferred model IDs in priority order */ - modelPreferences: external_exports.array(external_exports.string()).optional().describe("Preferred model IDs in priority order"), - /** System prompt for sampling context */ - systemPrompt: external_exports.string().optional().describe("System prompt for sampling context") -}).describe("Sampling configuration for MCP"); -var MCPRootEntrySchema = external_exports.object({ - /** Root URI */ - uri: external_exports.string().describe("Root URI (e.g., file:///path/to/project)"), - /** Human-readable name for the root */ - name: external_exports.string().optional().describe("Human-readable root name"), - /** Whether the root is read-only */ - readOnly: external_exports.boolean().optional().describe("Whether the root is read-only") -}).describe("A single root directory or resource"); -var MCPRootsConfigSchema = external_exports.object({ - /** Root directories/resources */ - roots: external_exports.array(MCPRootEntrySchema).describe("Root directories or resources available to the client"), - /** Watch roots for changes */ - watchForChanges: external_exports.boolean().default(false).describe("Watch root directories for filesystem changes"), - /** Notify server on root changes */ - notifyOnChange: external_exports.boolean().default(true).describe("Notify server when root contents change") -}).describe("Roots configuration for MCP client"); -var MCPCapabilitySchema = external_exports.object({ - resources: external_exports.boolean().default(false).describe("Supports resource listing and retrieval"), - resourceTemplates: external_exports.boolean().default(false).describe("Supports dynamic resource templates"), - tools: external_exports.boolean().default(false).describe("Supports tool/function calling"), - prompts: external_exports.boolean().default(false).describe("Supports prompt templates"), - sampling: external_exports.boolean().default(false).describe("Supports sampling from LLMs"), - logging: external_exports.boolean().default(false).describe("Supports logging and debugging") -}); -var MCPServerInfoSchema = external_exports.object({ - name: external_exports.string().describe("Server name"), - version: external_exports.string().describe("Server version (semver)"), - description: external_exports.string().optional(), - capabilities: MCPCapabilitySchema, - /** Protocol Version */ - protocolVersion: external_exports.string().default("2024-11-05").describe("MCP protocol version"), - /** Metadata */ - vendor: external_exports.string().optional().describe("Server vendor/provider"), - homepage: external_exports.string().url().optional().describe("Server homepage URL"), - documentation: external_exports.string().url().optional().describe("Documentation URL") -}); -var MCPServerConfigSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Server unique identifier (snake_case)"), - label: external_exports.string().describe("Display name"), - description: external_exports.string().optional(), - /** Server Info */ - serverInfo: MCPServerInfoSchema, - /** Transport */ - transport: MCPTransportConfigSchema, - /** Resources */ - resources: external_exports.array(MCPResourceSchema).optional().describe("Static resources"), - resourceTemplates: external_exports.array(MCPResourceTemplateSchema).optional().describe("Dynamic resource templates"), - /** Tools */ - tools: external_exports.array(MCPToolSchema).optional().describe("Available tools"), - /** Prompts */ - prompts: external_exports.array(MCPPromptSchema).optional().describe("Prompt templates"), - /** Lifecycle */ - autoStart: external_exports.boolean().default(false).describe("Auto-start server on system boot"), - restartOnFailure: external_exports.boolean().default(true).describe("Auto-restart on failure"), - healthCheck: external_exports.object({ - enabled: external_exports.boolean().default(true), - interval: external_exports.number().int().positive().default(6e4).describe("Health check interval in milliseconds"), - timeout: external_exports.number().int().positive().default(5e3).describe("Health check timeout in milliseconds"), - endpoint: external_exports.string().optional().describe("Health check endpoint (for HTTP servers)") - }).optional(), - /** Access Control */ - permissions: external_exports.object({ - allowedAgents: external_exports.array(external_exports.string()).optional().describe("Agent names allowed to use this server"), - allowedUsers: external_exports.array(external_exports.string()).optional().describe("User IDs allowed to use this server"), - requireAuth: external_exports.boolean().default(true) - }).optional(), - /** Rate Limiting */ - rateLimit: external_exports.object({ - enabled: external_exports.boolean().default(false), - requestsPerMinute: external_exports.number().int().positive().optional(), - requestsPerHour: external_exports.number().int().positive().optional(), - burstSize: external_exports.number().int().positive().optional() - }).optional(), - /** Metadata */ - tags: external_exports.array(external_exports.string()).optional(), - status: external_exports.enum(["active", "inactive", "maintenance", "deprecated"]).default("active"), - version: external_exports.string().optional().default("1.0.0"), - createdAt: external_exports.string().datetime().optional(), - updatedAt: external_exports.string().datetime().optional(), - /** Streaming */ - streaming: MCPStreamingConfigSchema.optional().describe("Streaming configuration"), - /** Tool Approval */ - toolApproval: MCPToolApprovalSchema.optional().describe("Tool approval configuration"), - /** Sampling */ - sampling: MCPSamplingConfigSchema.optional().describe("LLM sampling configuration") -}); -var MCPResourceRequestSchema = external_exports.object({ - uri: external_exports.string().describe("Resource URI to fetch"), - parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("URI template parameters") -}); -var MCPResourceResponseSchema = external_exports.object({ - resource: MCPResourceSchema, - content: external_exports.unknown().describe("Resource content") -}); -var MCPToolCallRequestSchema = external_exports.object({ - toolName: external_exports.string().describe("Tool to invoke"), - parameters: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Tool parameters"), - /** Execution Options */ - timeout: external_exports.number().int().positive().optional(), - confirmationProvided: external_exports.boolean().optional().describe("User confirmation for tools that require it"), - /** Context */ - context: external_exports.object({ - userId: external_exports.string().optional(), - sessionId: external_exports.string().optional(), - agentName: external_exports.string().optional(), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional() -}); -var MCPToolCallResponseSchema = external_exports.object({ - toolName: external_exports.string(), - status: external_exports.enum(["success", "error", "timeout", "cancelled"]), - /** Result */ - result: external_exports.unknown().optional().describe("Tool execution result"), - /** Error */ - error: external_exports.object({ - code: external_exports.string(), - message: external_exports.string(), - details: external_exports.unknown().optional() - }).optional(), - /** Metrics */ - executionTime: external_exports.number().nonnegative().optional().describe("Execution time in milliseconds"), - timestamp: external_exports.string().datetime().optional() -}); -var MCPPromptRequestSchema = external_exports.object({ - promptName: external_exports.string().describe("Prompt template to use"), - arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Prompt arguments") -}); -var MCPPromptResponseSchema = external_exports.object({ - promptName: external_exports.string(), - messages: external_exports.array(MCPPromptMessageSchema).describe("Rendered prompt messages") -}); -var MCPClientConfigSchema = external_exports.object({ - /** Server Connection */ - servers: external_exports.array(MCPServerConfigSchema).describe("MCP servers to connect to"), - /** Client Settings */ - defaultTimeout: external_exports.number().int().positive().default(3e4).describe("Default timeout for requests"), - enableCaching: external_exports.boolean().default(true).describe("Enable client-side caching"), - cacheMaxAge: external_exports.number().int().nonnegative().default(300).describe("Cache max age in seconds"), - /** Retry Logic */ - retryAttempts: external_exports.number().int().min(0).max(5).default(3), - retryDelay: external_exports.number().int().positive().default(1e3), - /** Logging */ - enableLogging: external_exports.boolean().default(true), - logLevel: external_exports.enum(["debug", "info", "warn", "error"]).default("info"), - /** Roots */ - roots: MCPRootsConfigSchema.optional().describe("Root directories/resources configuration") -}); -var TokenUsageSchema = external_exports.object({ - prompt: external_exports.number().int().nonnegative().describe("Input tokens"), - completion: external_exports.number().int().nonnegative().describe("Output tokens"), - total: external_exports.number().int().nonnegative().describe("Total tokens") -}); -var AIOperationCostSchema = external_exports.object({ - operationId: external_exports.string(), - operationType: external_exports.enum(["conversation", "orchestration", "prediction", "rag", "nlq"]), - agentName: external_exports.string().optional().describe("Agent that performed the operation"), - modelId: external_exports.string(), - tokens: TokenUsageSchema, - cost: external_exports.number().nonnegative().describe("Cost in USD"), - timestamp: external_exports.string().datetime(), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var CostMetricTypeSchema = external_exports.enum([ - "token", - // Cost per token - "request", - // Cost per API request - "character", - // Cost per character (e.g., TTS) - "second", - // Cost per second (e.g., speech) - "image", - // Cost per image - "embedding" - // Cost per embedding -]); -var BillingPeriodSchema = external_exports.enum([ - "hourly", - "daily", - "weekly", - "monthly", - "quarterly", - "yearly", - "custom" -]); -var CostEntrySchema = external_exports.object({ - /** Identity */ - id: external_exports.string().describe("Unique cost entry ID"), - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), - /** Request Details */ - modelId: external_exports.string().describe("AI model used"), - provider: external_exports.string().describe('AI provider (e.g., "openai", "anthropic")'), - operation: external_exports.string().describe('Operation type (e.g., "chat_completion", "embedding")'), - /** Usage Metrics - Standardized */ - tokens: TokenUsageSchema.optional().describe("Standardized token usage"), - requestCount: external_exports.number().int().positive().default(1), - /** Cost Calculation */ - promptCost: external_exports.number().nonnegative().optional().describe("Cost of prompt tokens"), - completionCost: external_exports.number().nonnegative().optional().describe("Cost of completion tokens"), - totalCost: external_exports.number().nonnegative().describe("Total cost in base currency"), - currency: external_exports.string().default("USD"), - /** Context */ - sessionId: external_exports.string().optional().describe("Conversation session ID"), - userId: external_exports.string().optional().describe("User who triggered the request"), - agentId: external_exports.string().optional().describe("AI agent ID"), - object: external_exports.string().optional().describe('Related object (e.g., "case", "project")'), - recordId: external_exports.string().optional().describe("Related record ID"), - /** Metadata */ - tags: external_exports.array(external_exports.string()).optional(), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var BudgetTypeSchema = external_exports.enum([ - "global", - // Organization-wide budget - "user", - // Per-user budget - "agent", - // Per-agent budget - "object", - // Per-object budget (e.g., per case) - "project", - // Per-project budget - "department" - // Per-department budget -]); -var BudgetLimitSchema = external_exports.object({ - /** Limit Configuration */ - type: BudgetTypeSchema, - scope: external_exports.string().optional().describe("Scope identifier (userId, agentId, etc.)"), - /** Limit Amount */ - maxCost: external_exports.number().nonnegative().describe("Maximum cost limit"), - currency: external_exports.string().default("USD"), - /** Period */ - period: BillingPeriodSchema, - customPeriodDays: external_exports.number().int().positive().optional().describe("Custom period in days"), - /** Soft Limits & Warnings */ - softLimit: external_exports.number().nonnegative().optional().describe("Soft limit for warnings"), - warnThresholds: external_exports.array(external_exports.number().min(0).max(1)).optional().describe("Warning thresholds (e.g., [0.5, 0.8, 0.95])"), - /** Enforcement */ - enforced: external_exports.boolean().default(true).describe("Block requests when exceeded"), - gracePeriodSeconds: external_exports.number().int().nonnegative().default(0).describe("Grace period after limit exceeded"), - /** Rollover */ - allowRollover: external_exports.boolean().default(false).describe("Allow unused budget to rollover"), - maxRolloverPercentage: external_exports.number().min(0).max(1).optional().describe("Max rollover as % of limit"), - /** Metadata */ - name: external_exports.string().optional().describe("Budget name"), - description: external_exports.string().optional(), - active: external_exports.boolean().default(true), - tags: external_exports.array(external_exports.string()).optional() -}); -var BudgetStatusSchema = external_exports.object({ - /** Budget Reference */ - budgetId: external_exports.string(), - type: BudgetTypeSchema, - scope: external_exports.string().optional(), - /** Current Period */ - periodStart: external_exports.string().datetime().describe("ISO 8601 timestamp"), - periodEnd: external_exports.string().datetime().describe("ISO 8601 timestamp"), - /** Usage */ - currentCost: external_exports.number().nonnegative().default(0), - maxCost: external_exports.number().nonnegative(), - currency: external_exports.string().default("USD"), - /** Status */ - percentageUsed: external_exports.number().nonnegative().describe("Usage as percentage (can exceed 1.0 if over budget)"), - remainingCost: external_exports.number().describe("Remaining budget (can be negative if exceeded)"), - isExceeded: external_exports.boolean().default(false), - isWarning: external_exports.boolean().default(false), - /** Projections */ - projectedCost: external_exports.number().nonnegative().optional().describe("Projected cost for period"), - projectedOverage: external_exports.number().nonnegative().optional().describe("Projected overage"), - /** Last Update */ - lastUpdated: external_exports.string().datetime().describe("ISO 8601 timestamp") -}); -var CostAlertTypeSchema = external_exports.enum([ - "threshold_warning", - // Warning threshold reached - "threshold_critical", - // Critical threshold reached - "limit_exceeded", - // Budget limit exceeded - "anomaly_detected", - // Unusual spending pattern - "projection_exceeded" - // Projected to exceed budget -]); -var CostAlertSchema = external_exports.object({ - /** Alert Details */ - id: external_exports.string(), - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), - type: CostAlertTypeSchema, - severity: external_exports.enum(["info", "warning", "critical"]), - /** Budget Context */ - budgetId: external_exports.string().optional(), - budgetType: BudgetTypeSchema.optional(), - scope: external_exports.string().optional(), - /** Alert Information */ - message: external_exports.string().describe("Alert message"), - currentCost: external_exports.number().nonnegative(), - maxCost: external_exports.number().nonnegative().optional(), - threshold: external_exports.number().min(0).max(1).optional(), - currency: external_exports.string().default("USD"), - /** Recommendations */ - recommendations: external_exports.array(external_exports.string()).optional(), - /** Status */ - acknowledged: external_exports.boolean().default(false), - acknowledgedBy: external_exports.string().optional(), - acknowledgedAt: external_exports.string().datetime().optional(), - resolved: external_exports.boolean().default(false), - /** Metadata */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var CostBreakdownDimensionSchema = external_exports.enum([ - "model", - "provider", - "user", - "agent", - "object", - "operation", - "date", - "hour", - "tag" -]); -var CostBreakdownEntrySchema = external_exports.object({ - dimension: CostBreakdownDimensionSchema, - value: external_exports.string().describe("Dimension value (e.g., model ID, user ID)"), - /** Metrics */ - totalCost: external_exports.number().nonnegative(), - requestCount: external_exports.number().int().nonnegative(), - totalTokens: external_exports.number().int().nonnegative().optional(), - /** Share */ - percentageOfTotal: external_exports.number().min(0).max(1), - /** Time Range */ - periodStart: external_exports.string().datetime().optional(), - periodEnd: external_exports.string().datetime().optional() -}); -var CostAnalyticsSchema = external_exports.object({ - /** Time Range */ - periodStart: external_exports.string().datetime().describe("ISO 8601 timestamp"), - periodEnd: external_exports.string().datetime().describe("ISO 8601 timestamp"), - /** Summary Metrics */ - totalCost: external_exports.number().nonnegative(), - totalRequests: external_exports.number().int().nonnegative(), - totalTokens: external_exports.number().int().nonnegative().optional(), - currency: external_exports.string().default("USD"), - /** Averages */ - averageCostPerRequest: external_exports.number().nonnegative(), - averageCostPerToken: external_exports.number().nonnegative().optional(), - averageRequestsPerDay: external_exports.number().nonnegative(), - /** Trends */ - costTrend: external_exports.enum(["increasing", "decreasing", "stable"]).optional(), - trendPercentage: external_exports.number().optional().describe("% change vs previous period"), - /** Breakdowns */ - byModel: external_exports.array(CostBreakdownEntrySchema).optional(), - byProvider: external_exports.array(CostBreakdownEntrySchema).optional(), - byUser: external_exports.array(CostBreakdownEntrySchema).optional(), - byAgent: external_exports.array(CostBreakdownEntrySchema).optional(), - byOperation: external_exports.array(CostBreakdownEntrySchema).optional(), - byDate: external_exports.array(CostBreakdownEntrySchema).optional(), - /** Top Consumers */ - topModels: external_exports.array(CostBreakdownEntrySchema).optional(), - topUsers: external_exports.array(CostBreakdownEntrySchema).optional(), - topAgents: external_exports.array(CostBreakdownEntrySchema).optional(), - /** Efficiency Metrics */ - tokensPerDollar: external_exports.number().nonnegative().optional(), - requestsPerDollar: external_exports.number().nonnegative().optional() -}); -var CostOptimizationRecommendationSchema = external_exports.object({ - /** Recommendation Details */ - id: external_exports.string(), - type: external_exports.enum([ - "switch_model", - "reduce_tokens", - "batch_requests", - "cache_results", - "adjust_parameters", - "limit_usage" - ]), - /** Impact */ - title: external_exports.string(), - description: external_exports.string(), - estimatedSavings: external_exports.number().nonnegative().optional(), - savingsPercentage: external_exports.number().min(0).max(1).optional(), - /** Implementation */ - priority: external_exports.enum(["low", "medium", "high"]), - effort: external_exports.enum(["low", "medium", "high"]), - actionable: external_exports.boolean().default(true), - actionSteps: external_exports.array(external_exports.string()).optional(), - /** Context */ - targetModel: external_exports.string().optional(), - alternativeModel: external_exports.string().optional(), - affectedUsers: external_exports.array(external_exports.string()).optional(), - /** Status */ - status: external_exports.enum(["pending", "accepted", "rejected", "implemented"]).default("pending"), - implementedAt: external_exports.string().datetime().optional() -}); -var CostReportSchema = external_exports.object({ - /** Report Metadata */ - id: external_exports.string(), - name: external_exports.string(), - generatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp"), - /** Time Range */ - periodStart: external_exports.string().datetime().describe("ISO 8601 timestamp"), - periodEnd: external_exports.string().datetime().describe("ISO 8601 timestamp"), - period: BillingPeriodSchema, - /** Analytics */ - analytics: CostAnalyticsSchema, - /** Budgets */ - budgets: external_exports.array(BudgetStatusSchema).optional(), - /** Alerts */ - alerts: external_exports.array(CostAlertSchema).optional(), - activeAlertCount: external_exports.number().int().nonnegative().default(0), - /** Recommendations */ - recommendations: external_exports.array(CostOptimizationRecommendationSchema).optional(), - /** Comparisons */ - previousPeriodCost: external_exports.number().nonnegative().optional(), - costChange: external_exports.number().optional().describe("Change vs previous period"), - costChangePercentage: external_exports.number().optional(), - /** Forecasting */ - forecastedCost: external_exports.number().nonnegative().optional(), - forecastedBudgetStatus: external_exports.enum(["under", "at", "over"]).optional(), - /** Export */ - format: external_exports.enum(["summary", "detailed", "executive"]).default("summary"), - currency: external_exports.string().default("USD") -}); -var CostQueryFiltersSchema = external_exports.object({ - /** Time Range */ - startDate: external_exports.string().datetime().optional().describe("ISO 8601 timestamp"), - endDate: external_exports.string().datetime().optional().describe("ISO 8601 timestamp"), - /** Dimensions */ - modelIds: external_exports.array(external_exports.string()).optional(), - providers: external_exports.array(external_exports.string()).optional(), - userIds: external_exports.array(external_exports.string()).optional(), - agentIds: external_exports.array(external_exports.string()).optional(), - operations: external_exports.array(external_exports.string()).optional(), - sessionIds: external_exports.array(external_exports.string()).optional(), - /** Cost Range */ - minCost: external_exports.number().nonnegative().optional(), - maxCost: external_exports.number().nonnegative().optional(), - /** Tags */ - tags: external_exports.array(external_exports.string()).optional(), - /** Aggregation */ - groupBy: external_exports.array(CostBreakdownDimensionSchema).optional(), - /** Sorting */ - orderBy: external_exports.enum(["timestamp", "cost", "tokens"]).optional().default("timestamp"), - orderDirection: external_exports.enum(["asc", "desc"]).optional().default("desc"), - /** Pagination */ - limit: external_exports.number().int().positive().optional(), - offset: external_exports.number().int().nonnegative().optional() -}); -var VectorStoreProviderSchema = external_exports.enum([ - "pinecone", - "weaviate", - "qdrant", - "milvus", - "chroma", - "pgvector", - "redis", - "opensearch", - "elasticsearch", - "custom" -]); -var EmbeddingModelSchema = external_exports.object({ - provider: external_exports.enum(["openai", "cohere", "huggingface", "azure_openai", "local", "custom"]), - model: external_exports.string().describe('Model name (e.g., "text-embedding-3-large")'), - dimensions: external_exports.number().int().positive().describe("Embedding vector dimensions"), - maxTokens: external_exports.number().int().positive().optional().describe("Maximum tokens per embedding"), - batchSize: external_exports.number().int().positive().optional().default(100).describe("Batch size for embedding"), - endpoint: external_exports.string().url().optional().describe("Custom endpoint URL"), - apiKey: external_exports.string().optional().describe("API key"), - secretRef: external_exports.string().optional().describe("Reference to stored secret") -}); -var ChunkingStrategySchema = external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("fixed"), - chunkSize: external_exports.number().int().positive().describe("Fixed chunk size in tokens/chars"), - chunkOverlap: external_exports.number().int().min(0).default(0).describe("Overlap between chunks"), - unit: external_exports.enum(["tokens", "characters"]).default("tokens") - }), - external_exports.object({ - type: external_exports.literal("semantic"), - model: external_exports.string().optional().describe("Model for semantic chunking"), - minChunkSize: external_exports.number().int().positive().default(100), - maxChunkSize: external_exports.number().int().positive().default(1e3) - }), - external_exports.object({ - type: external_exports.literal("recursive"), - separators: external_exports.array(external_exports.string()).default(["\n\n", "\n", " ", ""]), - chunkSize: external_exports.number().int().positive(), - chunkOverlap: external_exports.number().int().min(0).default(0) - }), - external_exports.object({ - type: external_exports.literal("markdown"), - maxChunkSize: external_exports.number().int().positive().default(1e3), - respectHeaders: external_exports.boolean().default(true).describe("Keep headers with content"), - respectCodeBlocks: external_exports.boolean().default(true).describe("Keep code blocks intact") - }) -]); -var DocumentMetadataSchema = external_exports.object({ - source: external_exports.string().describe("Document source (file path, URL, etc.)"), - sourceType: external_exports.enum(["file", "url", "api", "database", "custom"]).optional(), - title: external_exports.string().optional(), - author: external_exports.string().optional().describe("Document author"), - createdAt: external_exports.string().datetime().optional().describe("ISO timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("ISO timestamp"), - tags: external_exports.array(external_exports.string()).optional(), - category: external_exports.string().optional(), - language: external_exports.string().optional().describe("Document language (ISO 639-1 code)"), - custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata fields") -}); -var DocumentChunkSchema = external_exports.object({ - id: external_exports.string().describe("Unique chunk identifier"), - content: external_exports.string().describe("Chunk text content"), - embedding: external_exports.array(external_exports.number()).optional().describe("Embedding vector"), - metadata: DocumentMetadataSchema, - chunkIndex: external_exports.number().int().min(0).describe("Chunk position in document"), - tokens: external_exports.number().int().optional().describe("Token count") -}); -var RetrievalStrategySchema = external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("similarity"), - topK: external_exports.number().int().positive().default(5).describe("Number of results to retrieve"), - scoreThreshold: external_exports.number().min(0).max(1).optional().describe("Minimum similarity score") - }), - external_exports.object({ - type: external_exports.literal("mmr"), - topK: external_exports.number().int().positive().default(5), - fetchK: external_exports.number().int().positive().default(20).describe("Initial fetch size"), - lambda: external_exports.number().min(0).max(1).default(0.5).describe("Diversity vs relevance (0=diverse, 1=relevant)") - }), - external_exports.object({ - type: external_exports.literal("hybrid"), - topK: external_exports.number().int().positive().default(5), - vectorWeight: external_exports.number().min(0).max(1).default(0.7).describe("Weight for vector search"), - keywordWeight: external_exports.number().min(0).max(1).default(0.3).describe("Weight for keyword search") - }), - external_exports.object({ - type: external_exports.literal("parent_document"), - topK: external_exports.number().int().positive().default(5), - retrieveParent: external_exports.boolean().default(true).describe("Retrieve full parent document") - }) -]); -var RerankingConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false), - model: external_exports.string().optional().describe("Reranking model name"), - provider: external_exports.enum(["cohere", "huggingface", "custom"]).optional(), - topK: external_exports.number().int().positive().default(3).describe("Final number of results after reranking") -}); -var VectorStoreConfigSchema = external_exports.object({ - provider: VectorStoreProviderSchema, - indexName: external_exports.string().describe("Index/collection name"), - namespace: external_exports.string().optional().describe("Namespace for multi-tenancy"), - /** Connection */ - host: external_exports.string().optional().describe("Vector store host"), - port: external_exports.number().int().optional().describe("Vector store port"), - secretRef: external_exports.string().optional().describe("Reference to stored secret"), - apiKey: external_exports.string().optional().describe("API key or reference to secret"), - /** Configuration */ - dimensions: external_exports.number().int().positive().describe("Vector dimensions"), - metric: external_exports.enum(["cosine", "euclidean", "dotproduct"]).optional().default("cosine"), - /** Performance */ - batchSize: external_exports.number().int().positive().optional().default(100), - connectionPoolSize: external_exports.number().int().positive().optional().default(10), - timeout: external_exports.number().int().positive().optional().default(3e4).describe("Timeout in milliseconds") -}); -var DocumentLoaderConfigSchema = external_exports.object({ - type: external_exports.enum(["file", "directory", "url", "api", "database", "custom"]), - /** Source */ - source: external_exports.string().describe("Source path, URL, or identifier"), - /** File Types */ - fileTypes: external_exports.array(external_exports.string()).optional().describe('Accepted file extensions (e.g., [".pdf", ".md"])'), - /** Processing */ - recursive: external_exports.boolean().optional().default(false).describe("Process directories recursively"), - maxFileSize: external_exports.number().int().optional().describe("Maximum file size in bytes"), - excludePatterns: external_exports.array(external_exports.string()).optional().describe("Patterns to exclude"), - /** Text Extraction */ - extractImages: external_exports.boolean().optional().default(false).describe("Extract text from images (OCR)"), - extractTables: external_exports.boolean().optional().default(false).describe("Extract and format tables"), - /** Custom Loader */ - loaderConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom loader-specific config") -}); -var FilterExpressionSchema = external_exports.object({ - field: external_exports.string().describe("Metadata field to filter"), - operator: external_exports.enum(["eq", "neq", "gt", "gte", "lt", "lte", "in", "nin", "contains"]).default("eq"), - value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))]).describe("Filter value") -}); -var FilterGroupSchema = external_exports.object({ - logic: external_exports.enum(["and", "or"]).default("and"), - filters: external_exports.array(external_exports.union([FilterExpressionSchema, external_exports.lazy(() => FilterGroupSchema)])) -}); -var MetadataFilterSchema = external_exports.union([ - FilterExpressionSchema, - FilterGroupSchema, - // Legacy support for simple key-value map - external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.array(external_exports.union([external_exports.string(), external_exports.number()]))])) -]); -var RAGPipelineConfigSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Pipeline name (snake_case)"), - label: external_exports.string().describe("Display name"), - description: external_exports.string().optional(), - /** Components */ - embedding: EmbeddingModelSchema, - vectorStore: VectorStoreConfigSchema, - chunking: ChunkingStrategySchema, - retrieval: RetrievalStrategySchema, - reranking: RerankingConfigSchema.optional(), - /** Document Loading */ - loaders: external_exports.array(DocumentLoaderConfigSchema).optional().describe("Document loaders"), - /** Context Management */ - maxContextTokens: external_exports.number().int().positive().default(4e3).describe("Maximum tokens in context"), - contextWindow: external_exports.number().int().positive().optional().describe("LLM context window size"), - /** Metadata Filtering */ - metadataFilters: MetadataFilterSchema.optional().describe("Global filters for retrieval"), - /** Caching */ - enableCache: external_exports.boolean().default(true), - cacheTTL: external_exports.number().int().positive().default(3600).describe("Cache TTL in seconds"), - cacheInvalidationStrategy: external_exports.enum(["time_based", "manual", "on_update"]).default("time_based").optional() -}); -var RAGQueryRequestSchema = external_exports.object({ - query: external_exports.string().describe("User query"), - pipelineName: external_exports.string().describe("Pipeline to use"), - /** Override defaults */ - topK: external_exports.number().int().positive().optional(), - metadataFilters: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - /** Context */ - conversationHistory: external_exports.array(external_exports.object({ - role: external_exports.enum(["user", "assistant", "system"]), - content: external_exports.string() - })).optional(), - /** Options */ - includeMetadata: external_exports.boolean().default(true), - includeSources: external_exports.boolean().default(true) -}); -var RAGQueryResponseSchema = external_exports.object({ - query: external_exports.string(), - results: external_exports.array(external_exports.object({ - content: external_exports.string(), - score: external_exports.number(), - metadata: DocumentMetadataSchema.optional(), - chunkId: external_exports.string().optional() - })), - context: external_exports.string().describe("Assembled context for LLM"), - tokens: TokenUsageSchema.optional().describe("Token usage for this query"), - cost: external_exports.number().nonnegative().optional().describe("Cost for this query in USD"), - retrievalTime: external_exports.number().optional().describe("Retrieval time in milliseconds") -}); -var RAGPipelineStatusSchema = external_exports.object({ - name: external_exports.string(), - status: external_exports.enum(["active", "indexing", "error", "disabled"]), - documentsIndexed: external_exports.number().int().min(0), - lastIndexed: external_exports.string().datetime().optional().describe("ISO timestamp"), - errorMessage: external_exports.string().optional(), - health: external_exports.object({ - vectorStore: external_exports.enum(["healthy", "unhealthy", "unknown"]), - embeddingService: external_exports.enum(["healthy", "unhealthy", "unknown"]) - }).optional() -}); -var QueryIntentSchema = external_exports.enum([ - "select", - // Retrieve data (e.g., "show me all accounts") - "aggregate", - // Aggregation (e.g., "total revenue by region") - "filter", - // Filter data (e.g., "accounts created last month") - "sort", - // Sort data (e.g., "top 10 opportunities by value") - "compare", - // Compare values (e.g., "compare this quarter vs last quarter") - "trend", - // Analyze trends (e.g., "sales trend over time") - "insight", - // Generate insights (e.g., "what's unusual about this data") - "create", - // Create record (e.g., "create a new task") - "update", - // Update record (e.g., "mark this as complete") - "delete" - // Delete record (e.g., "remove this contact") -]); -var EntitySchema = external_exports.object({ - type: external_exports.enum(["object", "field", "value", "operator", "function", "timeframe"]), - text: external_exports.string().describe("Original text from query"), - value: external_exports.unknown().describe("Normalized value"), - confidence: external_exports.number().min(0).max(1).describe("Confidence score"), - span: external_exports.tuple([external_exports.number(), external_exports.number()]).optional().describe("Character span in query") -}); -var TimeframeSchema = external_exports.object({ - type: external_exports.enum(["absolute", "relative"]), - start: external_exports.string().optional().describe("Start date (ISO format)"), - end: external_exports.string().optional().describe("End date (ISO format)"), - relative: external_exports.object({ - unit: external_exports.enum(["hour", "day", "week", "month", "quarter", "year"]), - value: external_exports.number().int(), - direction: external_exports.enum(["past", "future", "current"]).default("past") - }).optional(), - text: external_exports.string().describe("Original timeframe text") -}); -var NLQFieldMappingSchema = external_exports.object({ - naturalLanguage: external_exports.string().describe('NL field name (e.g., "customer name")'), - objectField: external_exports.string().describe('Actual field name (e.g., "account.name")'), - object: external_exports.string().describe("Object name"), - field: external_exports.string().describe("Field name"), - confidence: external_exports.number().min(0).max(1) -}); -var QueryContextSchema = external_exports.object({ - /** User Information */ - userId: external_exports.string().optional(), - userRole: external_exports.string().optional(), - /** Current Context */ - currentObject: external_exports.string().optional().describe("Current object being viewed"), - currentRecordId: external_exports.string().optional().describe("Current record ID"), - /** Conversation History */ - conversationHistory: external_exports.array(external_exports.object({ - query: external_exports.string(), - timestamp: external_exports.string(), - intent: QueryIntentSchema.optional() - })).optional(), - /** Preferences */ - defaultLimit: external_exports.number().int().default(100), - timezone: external_exports.string().default("UTC"), - locale: external_exports.string().default("en-US") -}); -var NLQParseResultSchema = external_exports.object({ - /** Original Query */ - originalQuery: external_exports.string(), - /** Intent Detection */ - intent: QueryIntentSchema, - intentConfidence: external_exports.number().min(0).max(1), - /** Entity Recognition */ - entities: external_exports.array(EntitySchema), - /** Object & Field Resolution */ - targetObject: external_exports.string().optional().describe("Primary object to query"), - fields: external_exports.array(NLQFieldMappingSchema).optional(), - /** Temporal Information */ - timeframe: TimeframeSchema.optional(), - /** Query AST */ - ast: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Generated ObjectQL AST"), - /** Metadata */ - confidence: external_exports.number().min(0).max(1).describe("Overall confidence"), - ambiguities: external_exports.array(external_exports.object({ - type: external_exports.string(), - description: external_exports.string(), - suggestions: external_exports.array(external_exports.string()).optional() - })).optional().describe("Detected ambiguities requiring clarification"), - /** Alternative Interpretations */ - alternatives: external_exports.array(external_exports.object({ - interpretation: external_exports.string(), - confidence: external_exports.number(), - ast: external_exports.unknown() - })).optional() -}); -var NLQRequestSchema = external_exports.object({ - /** Query */ - query: external_exports.string().describe("Natural language query"), - /** Context */ - context: QueryContextSchema.optional(), - /** Options */ - includeAlternatives: external_exports.boolean().default(false).describe("Include alternative interpretations"), - maxAlternatives: external_exports.number().int().default(3), - minConfidence: external_exports.number().min(0).max(1).default(0.5).describe("Minimum confidence threshold"), - /** Execution */ - executeQuery: external_exports.boolean().default(false).describe("Execute query and return results"), - maxResults: external_exports.number().int().optional().describe("Maximum results to return") -}); -var NLQResponseSchema = external_exports.object({ - /** Parse Result */ - parseResult: NLQParseResultSchema, - /** Query Results (if executeQuery = true) */ - results: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Query results"), - totalCount: external_exports.number().int().optional(), - /** Execution Metadata */ - executionTime: external_exports.number().optional().describe("Execution time in milliseconds"), - needsClarification: external_exports.boolean().describe("Whether query needs clarification"), - /** Cost Tracking */ - tokens: TokenUsageSchema.optional().describe("Token usage for this query"), - cost: external_exports.number().nonnegative().optional().describe("Cost for this query in USD"), - /** Suggestions */ - suggestions: external_exports.array(external_exports.string()).optional().describe("Query refinement suggestions") -}); -var NLQTrainingExampleSchema = external_exports.object({ - /** Input */ - query: external_exports.string().describe("Natural language query"), - context: QueryContextSchema.optional(), - /** Expected Output */ - expectedIntent: QueryIntentSchema, - expectedObject: external_exports.string().optional(), - expectedAST: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Expected ObjectQL AST"), - /** Metadata */ - category: external_exports.string().optional().describe("Example category"), - tags: external_exports.array(external_exports.string()).optional(), - notes: external_exports.string().optional() -}); -var NLQModelConfigSchema = external_exports.object({ - /** Model */ - modelId: external_exports.string().describe("Model from registry"), - /** Prompt Engineering */ - systemPrompt: external_exports.string().optional().describe("System prompt override"), - includeSchema: external_exports.boolean().default(true).describe("Include object schema in prompt"), - includeExamples: external_exports.boolean().default(true).describe("Include examples in prompt"), - /** Intent Detection */ - enableIntentDetection: external_exports.boolean().default(true), - intentThreshold: external_exports.number().min(0).max(1).default(0.7), - /** Entity Recognition */ - enableEntityRecognition: external_exports.boolean().default(true), - entityRecognitionModel: external_exports.string().optional(), - /** Field Resolution */ - enableFuzzyMatching: external_exports.boolean().default(true).describe("Fuzzy match field names"), - fuzzyMatchThreshold: external_exports.number().min(0).max(1).default(0.8), - /** Temporal Processing */ - enableTimeframeDetection: external_exports.boolean().default(true), - defaultTimeframe: external_exports.string().optional().describe("Default timeframe if not specified"), - /** Performance */ - enableCaching: external_exports.boolean().default(true), - cacheTTL: external_exports.number().int().default(3600).describe("Cache TTL in seconds") -}); -var NLQAnalyticsSchema = external_exports.object({ - /** Query Metrics */ - totalQueries: external_exports.number().int(), - successfulQueries: external_exports.number().int(), - failedQueries: external_exports.number().int(), - averageConfidence: external_exports.number().min(0).max(1), - /** Intent Distribution */ - intentDistribution: external_exports.record(external_exports.string(), external_exports.number().int()).describe("Count by intent type"), - /** Common Patterns */ - topQueries: external_exports.array(external_exports.object({ - query: external_exports.string(), - count: external_exports.number().int(), - averageConfidence: external_exports.number() - })), - /** Performance */ - averageParseTime: external_exports.number().describe("Average parse time in milliseconds"), - averageExecutionTime: external_exports.number().optional(), - /** Issues */ - lowConfidenceQueries: external_exports.array(external_exports.object({ - query: external_exports.string(), - confidence: external_exports.number(), - timestamp: external_exports.string().datetime() - })), - /** Timeframe */ - startDate: external_exports.string().datetime().describe("ISO timestamp"), - endDate: external_exports.string().datetime().describe("ISO timestamp") -}); -var FieldSynonymConfigSchema = external_exports.object({ - object: external_exports.string().describe("Object name"), - field: external_exports.string().describe("Field name"), - synonyms: external_exports.array(external_exports.string()).describe("Natural language synonyms"), - examples: external_exports.array(external_exports.string()).optional().describe("Example queries using synonyms") -}); -var QueryTemplateSchema = external_exports.object({ - id: external_exports.string(), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Template name (snake_case)"), - label: external_exports.string(), - /** Template */ - pattern: external_exports.string().describe("Query pattern with placeholders"), - variables: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.enum(["object", "field", "value", "timeframe"]), - required: external_exports.boolean().default(false) - })), - /** Generated AST */ - astTemplate: external_exports.record(external_exports.string(), external_exports.unknown()).describe("AST template with variable placeholders"), - /** Metadata */ - category: external_exports.string().optional(), - examples: external_exports.array(external_exports.string()).optional(), - tags: external_exports.array(external_exports.string()).optional() -}); -var AIOrchestrationTriggerSchema = external_exports.enum([ - "record_created", - // When a new record is created - "record_updated", - // When a record is updated - "field_changed", - // When specific field(s) change - "scheduled", - // Time-based trigger (cron) - "manual", - // User-initiated trigger - "webhook", - // External system trigger - "batch" - // Batch processing trigger -]); -var AITaskTypeSchema = external_exports.enum([ - "classify", - // Categorize content into predefined classes - "extract", - // Extract structured data from unstructured content - "summarize", - // Generate concise summaries of text - "generate", - // Generate new content (text, code, etc.) - "predict", - // Make predictions based on historical data - "translate", - // Translate text between languages - "sentiment", - // Analyze sentiment (positive, negative, neutral) - "entity_recognition", - // Identify named entities (people, places, etc.) - "anomaly_detection", - // Detect outliers or unusual patterns - "recommendation" - // Recommend items or actions -]); -var AITaskSchema = external_exports.object({ - /** Task Identity */ - id: external_exports.string().optional().describe("Optional task ID for referencing"), - name: external_exports.string().describe("Human-readable task name"), - type: AITaskTypeSchema, - /** Model Configuration */ - model: external_exports.string().optional().describe("Model ID from registry (uses default if not specified)"), - promptTemplate: external_exports.string().optional().describe("Prompt template ID for this task"), - /** Input Configuration */ - inputFields: external_exports.array(external_exports.string()).describe('Source fields to process (e.g., ["description", "comments"])'), - inputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation schema for inputs"), - inputContext: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context for the AI model"), - /** Output Configuration */ - outputField: external_exports.string().describe("Target field to store the result"), - outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation schema for output"), - outputFormat: external_exports.enum(["text", "json", "number", "boolean", "array"]).optional().default("text"), - /** Classification-specific options */ - classes: external_exports.array(external_exports.string()).optional().describe("Valid classes for classification tasks"), - multiClass: external_exports.boolean().optional().default(false).describe("Allow multiple classes to be selected"), - /** Extraction-specific options */ - extractionSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("JSON schema for structured extraction"), - /** Generation-specific options */ - maxLength: external_exports.number().optional().describe("Maximum length for generated content"), - temperature: external_exports.number().min(0).max(2).optional().describe("Model temperature override"), - /** Error Handling */ - fallbackValue: external_exports.unknown().optional().describe("Fallback value if AI task fails"), - retryAttempts: external_exports.number().int().min(0).max(5).optional().default(1), - /** Conditional Execution */ - condition: external_exports.string().optional().describe("Formula condition - task only runs if TRUE"), - /** Task Metadata */ - description: external_exports.string().optional(), - active: external_exports.boolean().optional().default(true) -}); -var WorkflowFieldConditionSchema = external_exports.object({ - field: external_exports.string().describe("Field name to monitor"), - operator: external_exports.enum(["changed", "changed_to", "changed_from", "is", "is_not"]).optional().default("changed"), - value: external_exports.unknown().optional().describe("Value to compare against (for changed_to/changed_from/is/is_not)") -}); -var WorkflowScheduleSchema = external_exports.object({ - type: external_exports.enum(["cron", "interval", "daily", "weekly", "monthly"]).default("cron"), - cron: external_exports.string().optional().describe('Cron expression (required if type is "cron")'), - interval: external_exports.number().optional().describe('Interval in minutes (required if type is "interval")'), - time: external_exports.string().optional().describe("Time of day for daily schedules (HH:MM format)"), - dayOfWeek: external_exports.number().int().min(0).max(6).optional().describe("Day of week for weekly (0=Sunday)"), - dayOfMonth: external_exports.number().int().min(1).max(31).optional().describe("Day of month for monthly"), - timezone: external_exports.string().optional().default("UTC") -}); -var PostProcessingActionSchema = external_exports.object({ - type: external_exports.enum(["field_update", "send_email", "create_record", "update_related", "trigger_flow", "webhook"]), - name: external_exports.string().describe("Action name"), - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Action-specific configuration"), - condition: external_exports.string().optional().describe("Execute only if condition is TRUE") -}); -var AIOrchestrationSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Orchestration unique identifier (snake_case)"), - label: external_exports.string().describe("Display name"), - description: external_exports.string().optional(), - /** Target Object */ - objectName: external_exports.string().describe("Target object for this orchestration"), - /** Trigger Configuration */ - trigger: AIOrchestrationTriggerSchema, - /** Trigger-specific configuration */ - fieldConditions: external_exports.array(WorkflowFieldConditionSchema).optional().describe("Fields to monitor (for field_changed trigger)"), - schedule: WorkflowScheduleSchema.optional().describe("Schedule configuration (for scheduled trigger)"), - webhookConfig: external_exports.object({ - secret: external_exports.string().optional().describe("Webhook verification secret"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Expected headers") - }).optional().describe("Webhook configuration (for webhook trigger)"), - /** Entry Criteria */ - entryCriteria: external_exports.string().optional().describe("Formula condition - workflow only runs if TRUE"), - /** AI Tasks */ - aiTasks: external_exports.array(AITaskSchema).describe("AI tasks to execute in sequence"), - /** Post-Processing */ - postActions: external_exports.array(PostProcessingActionSchema).optional().describe("Actions after AI tasks complete"), - /** Execution Options */ - executionMode: external_exports.enum(["sequential", "parallel"]).optional().default("sequential").describe("How to execute multiple AI tasks"), - stopOnError: external_exports.boolean().optional().default(false).describe("Stop workflow if any task fails"), - /** Performance & Limits */ - timeout: external_exports.number().optional().describe("Maximum execution time in seconds"), - priority: external_exports.enum(["low", "normal", "high", "critical"]).optional().default("normal"), - /** Monitoring & Logging */ - enableLogging: external_exports.boolean().optional().default(true), - enableMetrics: external_exports.boolean().optional().default(true), - notifyOnFailure: external_exports.array(external_exports.string()).optional().describe("User IDs to notify on failure"), - /** Status */ - active: external_exports.boolean().optional().default(true), - version: external_exports.string().optional().default("1.0.0"), - /** Metadata */ - tags: external_exports.array(external_exports.string()).optional(), - category: external_exports.string().optional().describe('Workflow category (e.g., "support", "sales", "hr")'), - owner: external_exports.string().optional().describe("User ID of workflow owner"), - createdAt: external_exports.string().datetime().optional().describe("ISO timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("ISO timestamp") -}); -var BatchAIOrchestrationExecutionSchema = external_exports.object({ - workflowName: external_exports.string().describe("Orchestration to execute"), - recordIds: external_exports.array(external_exports.string()).describe("Records to process"), - batchSize: external_exports.number().int().min(1).max(1e3).optional().default(10), - parallelism: external_exports.number().int().min(1).max(10).optional().default(3), - priority: external_exports.enum(["low", "normal", "high"]).optional().default("normal") -}); -var AIOrchestrationExecutionResultSchema = external_exports.object({ - workflowName: external_exports.string(), - recordId: external_exports.string(), - status: external_exports.enum(["success", "partial_success", "failed", "skipped"]), - executionTime: external_exports.number().describe("Execution time in milliseconds"), - tasksExecuted: external_exports.number().int().describe("Number of tasks executed"), - tasksSucceeded: external_exports.number().int().describe("Number of tasks succeeded"), - tasksFailed: external_exports.number().int().describe("Number of tasks failed"), - taskResults: external_exports.array(external_exports.object({ - taskId: external_exports.string().optional(), - taskName: external_exports.string(), - status: external_exports.enum(["success", "failed", "skipped"]), - output: external_exports.unknown().optional(), - error: external_exports.string().optional(), - executionTime: external_exports.number().optional().describe("Task execution time in milliseconds"), - modelUsed: external_exports.string().optional(), - tokensUsed: external_exports.number().optional() - })).optional(), - tokens: TokenUsageSchema.optional().describe("Total token usage for this execution"), - cost: external_exports.number().nonnegative().optional().describe("Total cost for this execution in USD"), - error: external_exports.string().optional(), - startedAt: external_exports.string().datetime().describe("ISO timestamp"), - completedAt: external_exports.string().datetime().optional().describe("ISO timestamp") -}); -var AgentCommunicationProtocolSchema = external_exports.enum([ - "message_passing", - // Direct message exchange between agents - "shared_memory", - // Agents read/write to a shared context store - "blackboard" - // Centralized workspace agents contribute to -]); -var AgentGroupRoleSchema = external_exports.enum([ - "coordinator", - // Orchestrates other agents and delegates tasks - "specialist", - // Domain expert performing specific tasks - "critic", - // Reviews and validates other agents' outputs - "executor" - // Carries out actions in the real world (APIs, DB writes) -]); -var AgentGroupMemberSchema = external_exports.object({ - /** Reference to agent name (must match an existing AgentSchema name) */ - agentId: external_exports.string().describe("Agent identifier (reference to AgentSchema.name)"), - /** Role this agent plays in the group */ - role: AgentGroupRoleSchema.describe("Agent role within the group"), - /** Capabilities / skills this agent contributes */ - capabilities: external_exports.array(external_exports.string()).optional().describe("List of capabilities this agent contributes"), - /** Dependencies on other agents in the group */ - dependencies: external_exports.array(external_exports.string()).optional().describe("Agent IDs this agent depends on for input"), - /** Priority order within the group (lower = higher priority) */ - priority: external_exports.number().int().min(0).optional().describe("Execution priority (0 = highest)") -}); -var MultiAgentGroupSchema = external_exports.object({ - /** Group identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Group unique identifier (snake_case)"), - label: external_exports.string().describe("Group display name"), - description: external_exports.string().optional(), - /** Orchestration strategy */ - strategy: external_exports.enum([ - "sequential", - // Agents execute one after another - "parallel", - // Agents execute concurrently - "debate", - // Agents propose, argue, and converge on a solution - "hierarchical", - // Coordinator delegates to specialists - "swarm" - // Agents self-organize dynamically - ]).describe("Multi-agent orchestration strategy"), - /** Agents in this group */ - agents: external_exports.array(AgentGroupMemberSchema).min(2).describe("Agent members (minimum 2)"), - /** Inter-agent communication */ - communication: external_exports.object({ - /** Communication protocol */ - protocol: AgentCommunicationProtocolSchema.describe("Inter-agent communication protocol"), - /** Message queue name (for message_passing) */ - messageQueue: external_exports.string().optional().describe("Message queue identifier for async communication"), - /** Maximum rounds of communication */ - maxRounds: external_exports.number().int().min(1).optional().describe("Maximum communication rounds before forced termination") - }).describe("Communication configuration"), - /** Conflict resolution strategy */ - conflictResolution: external_exports.enum([ - "voting", - // Majority vote decides - "priorityBased", - // Highest-priority agent decides - "consensusBased", - // All agents must agree - "coordinatorDecides" - // Coordinator agent has final say - ]).optional().describe("How conflicts between agents are resolved"), - /** Timeout for the entire group execution in seconds */ - timeout: external_exports.number().int().min(1).optional().describe("Maximum execution time in seconds for the group"), - /** Whether the group is active */ - active: external_exports.boolean().default(true).describe("Whether this agent group is active") -}); -var PredictiveModelTypeSchema = external_exports.enum([ - "classification", - // Binary or multi-class classification - "regression", - // Numerical prediction - "clustering", - // Unsupervised grouping - "forecasting", - // Time-series prediction - "anomaly_detection", - // Outlier detection - "recommendation", - // Item or action recommendation - "ranking" - // Ordering items by relevance -]); -var ModelFeatureSchema = external_exports.object({ - /** Feature Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Feature name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label"), - /** Data Source */ - field: external_exports.string().describe("Source field name"), - object: external_exports.string().optional().describe("Source object (if different from target)"), - /** Feature Type */ - dataType: external_exports.enum(["numeric", "categorical", "text", "datetime", "boolean"]).describe("Feature data type"), - /** Feature Engineering */ - transformation: external_exports.enum([ - "none", - "normalize", - // Normalize to 0-1 range - "standardize", - // Z-score standardization - "one_hot_encode", - // One-hot encoding for categorical - "label_encode", - // Label encoding for categorical - "log_transform", - // Logarithmic transformation - "binning", - // Discretize continuous values - "embedding" - // Text/categorical embedding - ]).optional().default("none"), - /** Configuration */ - required: external_exports.boolean().optional().default(true), - defaultValue: external_exports.unknown().optional(), - /** Metadata */ - description: external_exports.string().optional(), - importance: external_exports.number().optional().describe("Feature importance score (0-1)") -}); -var HyperparametersSchema = external_exports.object({ - /** General Parameters */ - learningRate: external_exports.number().optional().describe("Learning rate for training"), - epochs: external_exports.number().int().optional().describe("Number of training epochs"), - batchSize: external_exports.number().int().optional().describe("Training batch size"), - /** Tree-based Models (Random Forest, XGBoost, etc.) */ - maxDepth: external_exports.number().int().optional().describe("Maximum tree depth"), - numTrees: external_exports.number().int().optional().describe("Number of trees in ensemble"), - minSamplesSplit: external_exports.number().int().optional().describe("Minimum samples to split node"), - minSamplesLeaf: external_exports.number().int().optional().describe("Minimum samples in leaf node"), - /** Neural Networks */ - hiddenLayers: external_exports.array(external_exports.number().int()).optional().describe("Hidden layer sizes"), - activation: external_exports.string().optional().describe("Activation function"), - dropout: external_exports.number().optional().describe("Dropout rate"), - /** Regularization */ - l1Regularization: external_exports.number().optional().describe("L1 regularization strength"), - l2Regularization: external_exports.number().optional().describe("L2 regularization strength"), - /** Clustering */ - numClusters: external_exports.number().int().optional().describe("Number of clusters (k-means, etc.)"), - /** Time Series */ - seasonalPeriod: external_exports.number().int().optional().describe("Seasonal period for time series"), - forecastHorizon: external_exports.number().int().optional().describe("Number of periods to forecast"), - /** Additional custom parameters */ - custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Algorithm-specific parameters") -}); -var TrainingConfigSchema = external_exports.object({ - /** Data Split */ - trainingDataRatio: external_exports.number().min(0).max(1).optional().default(0.8).describe("Proportion of data for training"), - validationDataRatio: external_exports.number().min(0).max(1).optional().default(0.1).describe("Proportion for validation"), - testDataRatio: external_exports.number().min(0).max(1).optional().default(0.1).describe("Proportion for testing"), - /** Data Filtering */ - dataFilter: external_exports.string().optional().describe("Formula to filter training data"), - minRecords: external_exports.number().int().optional().default(100).describe("Minimum records required"), - maxRecords: external_exports.number().int().optional().describe("Maximum records to use"), - /** Training Strategy */ - strategy: external_exports.enum(["full", "incremental", "online", "transfer_learning"]).optional().default("full"), - crossValidation: external_exports.boolean().optional().default(true), - folds: external_exports.number().int().min(2).max(10).optional().default(5).describe("Cross-validation folds"), - /** Early Stopping */ - earlyStoppingEnabled: external_exports.boolean().optional().default(true), - earlyStoppingPatience: external_exports.number().int().optional().default(10).describe("Epochs without improvement before stopping"), - /** Resource Limits */ - maxTrainingTime: external_exports.number().optional().describe("Maximum training time in seconds"), - gpuEnabled: external_exports.boolean().optional().default(false), - /** Reproducibility */ - randomSeed: external_exports.number().int().optional().describe("Random seed for reproducibility") -}).superRefine((data, ctx) => { - if (data.trainingDataRatio && data.validationDataRatio && data.testDataRatio) { - const sum = data.trainingDataRatio + data.validationDataRatio + data.testDataRatio; - if (Math.abs(sum - 1) > 0.01) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Data split ratios must sum to 1. Current sum: ${sum}`, - path: ["trainingDataRatio"] - }); - } - } -}); -var EvaluationMetricsSchema = external_exports.object({ - /** Classification Metrics */ - accuracy: external_exports.number().optional(), - precision: external_exports.number().optional(), - recall: external_exports.number().optional(), - f1Score: external_exports.number().optional(), - auc: external_exports.number().optional().describe("Area Under ROC Curve"), - /** Regression Metrics */ - mse: external_exports.number().optional().describe("Mean Squared Error"), - rmse: external_exports.number().optional().describe("Root Mean Squared Error"), - mae: external_exports.number().optional().describe("Mean Absolute Error"), - r2Score: external_exports.number().optional().describe("R-squared score"), - /** Clustering Metrics */ - silhouetteScore: external_exports.number().optional(), - daviesBouldinIndex: external_exports.number().optional(), - /** Time Series Metrics */ - mape: external_exports.number().optional().describe("Mean Absolute Percentage Error"), - smape: external_exports.number().optional().describe("Symmetric MAPE"), - /** Additional Metrics */ - custom: external_exports.record(external_exports.string(), external_exports.number()).optional() -}); -var PredictiveModelSchema = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Model unique identifier (snake_case)"), - label: external_exports.string().describe("Model display name"), - description: external_exports.string().optional(), - /** Model Type */ - type: PredictiveModelTypeSchema, - algorithm: external_exports.string().optional().describe('Specific algorithm (e.g., "random_forest", "xgboost", "lstm")'), - /** Target Object & Field */ - objectName: external_exports.string().describe("Target object for predictions"), - target: external_exports.string().describe("Target field to predict"), - targetType: external_exports.enum(["numeric", "categorical", "binary"]).optional().describe("Target field type"), - /** Features */ - features: external_exports.array(ModelFeatureSchema).describe("Input features for the model"), - /** Hyperparameters */ - hyperparameters: HyperparametersSchema.optional(), - /** Training Configuration */ - training: TrainingConfigSchema.optional(), - /** Model Performance */ - metrics: EvaluationMetricsSchema.optional().describe("Evaluation metrics from last training"), - /** Deployment */ - deploymentStatus: external_exports.enum(["draft", "training", "trained", "deployed", "deprecated"]).optional().default("draft"), - version: external_exports.string().optional().default("1.0.0"), - /** Prediction Configuration */ - predictionField: external_exports.string().optional().describe("Field to store predictions"), - confidenceField: external_exports.string().optional().describe("Field to store confidence scores"), - updateTrigger: external_exports.enum(["on_create", "on_update", "manual", "scheduled"]).optional().default("on_create"), - /** Retraining */ - autoRetrain: external_exports.boolean().optional().default(false), - retrainSchedule: external_exports.string().optional().describe("Cron expression for auto-retraining"), - retrainThreshold: external_exports.number().optional().describe("Performance threshold to trigger retraining"), - /** Explainability */ - enableExplainability: external_exports.boolean().optional().default(false).describe("Generate feature importance & explanations"), - /** Monitoring */ - enableMonitoring: external_exports.boolean().optional().default(true), - alertOnDrift: external_exports.boolean().optional().default(true).describe("Alert when model drift is detected"), - /** Access Control */ - active: external_exports.boolean().optional().default(true), - owner: external_exports.string().optional().describe("User ID of model owner"), - permissions: external_exports.array(external_exports.string()).optional().describe("User/group IDs with access"), - /** Metadata */ - tags: external_exports.array(external_exports.string()).optional(), - category: external_exports.string().optional().describe('Model category (e.g., "sales", "marketing", "operations")'), - lastTrainedAt: external_exports.string().datetime().optional().describe("ISO timestamp"), - createdAt: external_exports.string().datetime().optional().describe("ISO timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("ISO timestamp") -}); -var PredictionRequestSchema = external_exports.object({ - modelName: external_exports.string().describe("Model to use for prediction"), - recordIds: external_exports.array(external_exports.string()).optional().describe("Specific records to predict (if not provided, uses all)"), - inputData: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Direct input data (alternative to recordIds)"), - returnConfidence: external_exports.boolean().optional().default(true), - returnExplanation: external_exports.boolean().optional().default(false) -}); -var PredictionResultSchema = external_exports.object({ - modelName: external_exports.string(), - modelVersion: external_exports.string(), - recordId: external_exports.string().optional(), - prediction: external_exports.unknown().describe("The predicted value"), - confidence: external_exports.number().optional().describe("Confidence score (0-1)"), - probabilities: external_exports.record(external_exports.string(), external_exports.number()).optional().describe("Class probabilities (for classification)"), - explanation: external_exports.object({ - topFeatures: external_exports.array(external_exports.object({ - feature: external_exports.string(), - importance: external_exports.number(), - value: external_exports.unknown() - })).optional(), - reasoning: external_exports.string().optional() - }).optional(), - tokens: TokenUsageSchema.optional().describe("Token usage for this prediction (if AI-powered)"), - cost: external_exports.number().nonnegative().optional().describe("Cost for this prediction in USD"), - metadata: external_exports.object({ - executionTime: external_exports.number().optional().describe("Execution time in milliseconds"), - timestamp: external_exports.string().datetime().optional().describe("ISO timestamp") - }).optional() -}); -var ModelDriftSchema = external_exports.object({ - modelName: external_exports.string(), - driftType: external_exports.enum(["feature_drift", "prediction_drift", "performance_drift"]), - severity: external_exports.enum(["low", "medium", "high", "critical"]), - detectedAt: external_exports.string().datetime().describe("ISO timestamp"), - metrics: external_exports.object({ - driftScore: external_exports.number().describe("Drift magnitude (0-1)"), - affectedFeatures: external_exports.array(external_exports.string()).optional(), - performanceChange: external_exports.number().optional().describe("Change in performance metric") - }), - recommendation: external_exports.string().optional(), - autoRetrainTriggered: external_exports.boolean().optional().default(false) -}); -var MessageRoleSchema = external_exports.enum([ - "system", - "user", - "assistant", - "function", - "tool" -]); -var MessageContentTypeSchema = external_exports.enum([ - "text", - "image", - "file", - "code", - "structured" -]); -var TextContentSchema = external_exports.object({ - type: external_exports.literal("text"), - text: external_exports.string().describe("Text content"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var ImageContentSchema = external_exports.object({ - type: external_exports.literal("image"), - imageUrl: external_exports.string().url().describe("Image URL"), - detail: external_exports.enum(["low", "high", "auto"]).optional().default("auto"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var FileContentSchema = external_exports.object({ - type: external_exports.literal("file"), - fileUrl: external_exports.string().url().describe("File attachment URL"), - mimeType: external_exports.string().describe("MIME type"), - fileName: external_exports.string().optional(), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var CodeContentSchema = external_exports.object({ - type: external_exports.literal("code"), - text: external_exports.string().describe("Code snippet"), - language: external_exports.string().optional().default("text"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var MessageContentSchema = external_exports.union([ - TextContentSchema, - ImageContentSchema, - FileContentSchema, - CodeContentSchema -]); -var FunctionCallSchema = external_exports.object({ - name: external_exports.string().describe("Function name"), - arguments: external_exports.string().describe("JSON string of function arguments"), - result: external_exports.string().optional().describe("Function execution result") -}); -var ToolCallSchema = external_exports.object({ - id: external_exports.string().describe("Tool call ID"), - type: external_exports.enum(["function"]).default("function"), - function: FunctionCallSchema -}); -var ConversationMessageSchema = external_exports.object({ - /** Identity */ - id: external_exports.string().describe("Unique message ID"), - timestamp: external_exports.string().datetime().describe("ISO 8601 timestamp"), - /** Content */ - role: MessageRoleSchema, - content: external_exports.array(MessageContentSchema).describe("Message content (multimodal array)"), - /** Function/Tool Calls */ - functionCall: FunctionCallSchema.optional().describe("Legacy function call"), - toolCalls: external_exports.array(ToolCallSchema).optional().describe("Tool calls"), - toolCallId: external_exports.string().optional().describe("Tool call ID this message responds to"), - /** Metadata */ - name: external_exports.string().optional().describe("Name of the function/user"), - tokens: TokenUsageSchema.optional().describe("Token usage for this message"), - cost: external_exports.number().nonnegative().optional().describe("Cost for this message in USD"), - /** Context Management */ - pinned: external_exports.boolean().optional().default(false).describe("Prevent removal during pruning"), - importance: external_exports.number().min(0).max(1).optional().describe("Importance score for pruning"), - embedding: external_exports.array(external_exports.number()).optional().describe("Vector embedding for semantic search"), - /** Annotations */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var TokenBudgetStrategySchema = external_exports.enum([ - "fifo", - // First-in-first-out (oldest messages dropped) - "importance", - // Drop by importance score - "semantic", - // Keep semantically relevant messages - "sliding_window", - // Fixed window of recent messages - "summary" - // Summarize old context -]); -var TokenBudgetConfigSchema = external_exports.object({ - /** Budget Limits */ - maxTokens: external_exports.number().int().positive().describe("Maximum total tokens"), - maxPromptTokens: external_exports.number().int().positive().optional().describe("Max tokens for prompt"), - maxCompletionTokens: external_exports.number().int().positive().optional().describe("Max tokens for completion"), - /** Buffer & Reserves */ - reserveTokens: external_exports.number().int().nonnegative().default(500).describe("Reserve tokens for system messages"), - bufferPercentage: external_exports.number().min(0).max(1).default(0.1).describe("Buffer percentage (0.1 = 10%)"), - /** Pruning Strategy */ - strategy: TokenBudgetStrategySchema.default("sliding_window"), - /** Strategy-Specific Options */ - slidingWindowSize: external_exports.number().int().positive().optional().describe("Number of recent messages to keep"), - minImportanceScore: external_exports.number().min(0).max(1).optional().describe("Minimum importance to keep"), - semanticThreshold: external_exports.number().min(0).max(1).optional().describe("Semantic similarity threshold"), - /** Summarization */ - enableSummarization: external_exports.boolean().default(false).describe("Enable context summarization"), - summarizationThreshold: external_exports.number().int().positive().optional().describe("Trigger summarization at N tokens"), - summaryModel: external_exports.string().optional().describe("Model ID for summarization"), - /** Monitoring */ - warnThreshold: external_exports.number().min(0).max(1).default(0.8).describe("Warn at % of budget (0.8 = 80%)") -}); -var TokenUsageStatsSchema = external_exports.object({ - promptTokens: external_exports.number().int().nonnegative().default(0), - completionTokens: external_exports.number().int().nonnegative().default(0), - totalTokens: external_exports.number().int().nonnegative().default(0), - /** Budget Status */ - budgetLimit: external_exports.number().int().positive(), - budgetUsed: external_exports.number().int().nonnegative().default(0), - budgetRemaining: external_exports.number().int().nonnegative(), - budgetPercentage: external_exports.number().min(0).max(1).describe("Usage as percentage of budget"), - /** Message Stats */ - messageCount: external_exports.number().int().nonnegative().default(0), - prunedMessageCount: external_exports.number().int().nonnegative().default(0), - summarizedMessageCount: external_exports.number().int().nonnegative().default(0) -}); -var ConversationContextSchema = external_exports.object({ - /** Identity */ - sessionId: external_exports.string().describe("Conversation session ID"), - userId: external_exports.string().optional().describe("User identifier"), - agentId: external_exports.string().optional().describe("AI agent identifier"), - /** Context Data */ - object: external_exports.string().optional().describe('Related object (e.g., "case", "project")'), - recordId: external_exports.string().optional().describe("Related record ID"), - scope: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context scope"), - /** System Instructions */ - systemMessage: external_exports.string().optional().describe("System prompt/instructions"), - /** Metadata */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var ConversationSessionSchema = external_exports.object({ - /** Identity */ - id: external_exports.string().describe("Unique session ID"), - name: external_exports.string().optional().describe("Session name/title"), - /** Configuration */ - context: ConversationContextSchema, - modelId: external_exports.string().optional().describe("AI model ID"), - tokenBudget: TokenBudgetConfigSchema, - /** Messages */ - messages: external_exports.array(ConversationMessageSchema).default([]), - /** Token Tracking */ - tokens: TokenUsageStatsSchema.optional(), - totalTokens: TokenUsageSchema.optional().describe("Total tokens across all messages"), - totalCost: external_exports.number().nonnegative().optional().describe("Total cost for this session in USD"), - /** Session Status */ - status: external_exports.enum(["active", "paused", "completed", "archived"]).default("active"), - /** Timestamps */ - createdAt: external_exports.string().datetime().describe("ISO 8601 timestamp"), - updatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp"), - expiresAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional() -}); -var ConversationSummarySchema = external_exports.object({ - /** Summary Content */ - summary: external_exports.string().describe("Conversation summary"), - keyPoints: external_exports.array(external_exports.string()).optional().describe("Key discussion points"), - /** Token Savings */ - originalTokens: external_exports.number().int().nonnegative().describe("Original token count"), - summaryTokens: external_exports.number().int().nonnegative().describe("Summary token count"), - tokensSaved: external_exports.number().int().nonnegative().describe("Tokens saved"), - /** Source Messages */ - messageRange: external_exports.object({ - startIndex: external_exports.number().int().nonnegative(), - endIndex: external_exports.number().int().nonnegative() - }).describe("Range of messages summarized"), - /** Metadata */ - generatedAt: external_exports.string().datetime().describe("ISO 8601 timestamp"), - modelId: external_exports.string().optional().describe("Model used for summarization") -}); -var MessagePruningEventSchema = external_exports.object({ - /** Event Details */ - timestamp: external_exports.string().datetime().describe("Event timestamp"), - /** Pruned Messages */ - prunedMessages: external_exports.array(external_exports.object({ - messageId: external_exports.string(), - role: MessageRoleSchema, - tokens: external_exports.number().int().nonnegative(), - importance: external_exports.number().min(0).max(1).optional() - })), - /** Impact */ - tokensFreed: external_exports.number().int().nonnegative(), - messagesRemoved: external_exports.number().int().nonnegative(), - /** Post-Pruning State */ - remainingTokens: external_exports.number().int().nonnegative(), - remainingMessages: external_exports.number().int().nonnegative() -}); -var ConversationAnalyticsSchema = external_exports.object({ - /** Session Info */ - sessionId: external_exports.string(), - /** Message Statistics */ - totalMessages: external_exports.number().int().nonnegative(), - userMessages: external_exports.number().int().nonnegative(), - assistantMessages: external_exports.number().int().nonnegative(), - systemMessages: external_exports.number().int().nonnegative(), - /** Token Statistics */ - totalTokens: external_exports.number().int().nonnegative(), - averageTokensPerMessage: external_exports.number().nonnegative(), - peakTokenUsage: external_exports.number().int().nonnegative(), - /** Efficiency Metrics */ - pruningEvents: external_exports.number().int().nonnegative().default(0), - summarizationEvents: external_exports.number().int().nonnegative().default(0), - tokensSavedByPruning: external_exports.number().int().nonnegative().default(0), - tokensSavedBySummarization: external_exports.number().int().nonnegative().default(0), - /** Duration */ - duration: external_exports.number().nonnegative().optional().describe("Session duration in seconds"), - firstMessageAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp"), - lastMessageAt: external_exports.string().datetime().optional().describe("ISO 8601 timestamp") -}); -var MetadataSourceSchema22 = external_exports.object({ - file: external_exports.string().optional(), - line: external_exports.number().optional(), - column: external_exports.number().optional(), - // Logic references - package: external_exports.string().optional(), - object: external_exports.string().optional(), - field: external_exports.string().optional(), - component: external_exports.string().optional() - // specific UI component or flow node -}); -var IssueSchema = external_exports.object({ - id: external_exports.string(), - severity: external_exports.enum(["critical", "error", "warning", "info"]), - message: external_exports.string(), - stackTrace: external_exports.string().optional(), - timestamp: external_exports.string().datetime(), - userId: external_exports.string().optional(), - // Context snapshot - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - // The suspected metadata culprit - source: MetadataSourceSchema22.optional() -}); -var ResolutionSchema = external_exports.object({ - issueId: external_exports.string(), - reasoning: external_exports.string().describe("Explanation of why this fix is needed"), - confidence: external_exports.number().min(0).max(1), - // Actionable change to fix the issue - fix: external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("metadata_change"), - changeSet: ChangeSetSchema2 - }), - external_exports.object({ - type: external_exports.literal("manual_intervention"), - instructions: external_exports.string() - }) - ]) -}); -var FeedbackLoopSchema = external_exports.object({ - issue: IssueSchema, - analysis: external_exports.string().optional().describe("AI analysis of the root cause"), - resolutions: external_exports.array(ResolutionSchema).optional(), - status: external_exports.enum(["open", "analyzing", "resolved", "ignored"]).default("open") -}); -var api_exports = {}; -__export4(api_exports, { - AckMessageSchema: () => AckMessageSchema2, - AddReactionRequestSchema: () => AddReactionRequestSchema2, - AddReactionResponseSchema: () => AddReactionResponseSchema2, - AiInsightsRequestSchema: () => AiInsightsRequestSchema2, - AiInsightsResponseSchema: () => AiInsightsResponseSchema2, - AiNlqRequestSchema: () => AiNlqRequestSchema2, - AiNlqResponseSchema: () => AiNlqResponseSchema2, - AiSuggestRequestSchema: () => AiSuggestRequestSchema2, - AiSuggestResponseSchema: () => AiSuggestResponseSchema2, - AnalyticsEndpoint: () => AnalyticsEndpoint2, - AnalyticsMetadataResponseSchema: () => AnalyticsMetadataResponseSchema2, - AnalyticsQueryRequestSchema: () => AnalyticsQueryRequestSchema2, - AnalyticsResultResponseSchema: () => AnalyticsResultResponseSchema2, - AnalyticsSqlResponseSchema: () => AnalyticsSqlResponseSchema2, - ApiChangelogEntrySchema: () => ApiChangelogEntrySchema2, - ApiDiscoveryQuerySchema: () => ApiDiscoveryQuerySchema2, - ApiDiscoveryResponseSchema: () => ApiDiscoveryResponseSchema2, - ApiDocumentationConfig: () => ApiDocumentationConfig2, - ApiDocumentationConfigSchema: () => ApiDocumentationConfigSchema2, - ApiEndpoint: () => ApiEndpoint2, - ApiEndpointRegistration: () => ApiEndpointRegistration2, - ApiEndpointRegistrationSchema: () => ApiEndpointRegistrationSchema2, - ApiEndpointSchema: () => ApiEndpointSchema2, - ApiErrorSchema: () => ApiErrorSchema2, - ApiMappingSchema: () => ApiMappingSchema2, - ApiMetadataSchema: () => ApiMetadataSchema2, - ApiParameterSchema: () => ApiParameterSchema2, - ApiProtocolType: () => ApiProtocolType2, - ApiRegistry: () => ApiRegistry2, - ApiRegistryEntry: () => ApiRegistryEntry2, - ApiRegistryEntrySchema: () => ApiRegistryEntrySchema2, - ApiRegistrySchema: () => ApiRegistrySchema2, - ApiResponseSchema: () => ApiResponseSchema2, - ApiRoutesSchema: () => ApiRoutesSchema2, - ApiTestCollection: () => ApiTestCollection2, - ApiTestCollectionSchema: () => ApiTestCollectionSchema2, - ApiTestRequestSchema: () => ApiTestRequestSchema2, - ApiTestingUiConfigSchema: () => ApiTestingUiConfigSchema2, - ApiTestingUiType: () => ApiTestingUiType2, - AppDefinitionResponseSchema: () => AppDefinitionResponseSchema2, - AuthEndpointAliases: () => AuthEndpointAliases2, - AuthEndpointPaths: () => AuthEndpointPaths2, - AuthEndpointSchema: () => AuthEndpointSchema2, - AuthProvider: () => AuthProvider2, - AutomationApiContracts: () => AutomationApiContracts, - AutomationApiErrorCode: () => AutomationApiErrorCode2, - AutomationFlowPathParamsSchema: () => AutomationFlowPathParamsSchema2, - AutomationRunPathParamsSchema: () => AutomationRunPathParamsSchema2, - AutomationTriggerRequestSchema: () => AutomationTriggerRequestSchema2, - AutomationTriggerResponseSchema: () => AutomationTriggerResponseSchema2, - BasePresenceSchema: () => BasePresenceSchema2, - BaseResponseSchema: () => BaseResponseSchema2, - BatchApiContracts: () => BatchApiContracts, - BatchConfigSchema: () => BatchConfigSchema2, - BatchDataRequestSchema: () => BatchDataRequestSchema2, - BatchDataResponseSchema: () => BatchDataResponseSchema, - BatchEndpointsConfigSchema: () => BatchEndpointsConfigSchema2, - BatchLoadingStrategySchema: () => BatchLoadingStrategySchema2, - BatchOperationResultSchema: () => BatchOperationResultSchema2, - BatchOperationType: () => BatchOperationType2, - BatchOptionsSchema: () => BatchOptionsSchema2, - BatchRecordSchema: () => BatchRecordSchema2, - BatchUpdateRequestSchema: () => BatchUpdateRequestSchema2, - BatchUpdateResponseSchema: () => BatchUpdateResponseSchema2, - BulkRequestSchema: () => BulkRequestSchema2, - BulkResponseSchema: () => BulkResponseSchema2, - CacheControlSchema: () => CacheControlSchema2, - CacheDirective: () => CacheDirective2, - CacheInvalidationRequestSchema: () => CacheInvalidationRequestSchema2, - CacheInvalidationResponseSchema: () => CacheInvalidationResponseSchema2, - CacheInvalidationTarget: () => CacheInvalidationTarget2, - CallbackSchema: () => CallbackSchema2, - ChangelogEntrySchema: () => ChangelogEntrySchema2, - CheckPermissionRequestSchema: () => CheckPermissionRequestSchema2, - CheckPermissionResponseSchema: () => CheckPermissionResponseSchema2, - CodeGenerationTemplateSchema: () => CodeGenerationTemplateSchema2, - CompleteChunkedUploadRequestSchema: () => CompleteChunkedUploadRequestSchema2, - CompleteChunkedUploadResponseSchema: () => CompleteChunkedUploadResponseSchema2, - CompleteUploadRequestSchema: () => CompleteUploadRequestSchema2, - ConceptListResponseSchema: () => ConceptListResponseSchema2, - ConflictResolutionStrategy: () => ConflictResolutionStrategy2, - CreateDataRequestSchema: () => CreateDataRequestSchema2, - CreateDataResponseSchema: () => CreateDataResponseSchema2, - CreateExportJobRequestSchema: () => CreateExportJobRequestSchema2, - CreateExportJobResponseSchema: () => CreateExportJobResponseSchema2, - CreateFeedItemRequestSchema: () => CreateFeedItemRequestSchema2, - CreateFeedItemResponseSchema: () => CreateFeedItemResponseSchema2, - CreateFlowRequestSchema: () => CreateFlowRequestSchema, - CreateFlowResponseSchema: () => CreateFlowResponseSchema2, - CreateManyDataRequestSchema: () => CreateManyDataRequestSchema2, - CreateManyDataResponseSchema: () => CreateManyDataResponseSchema2, - CreateRequestSchema: () => CreateRequestSchema2, - CreateViewRequestSchema: () => CreateViewRequestSchema2, - CreateViewResponseSchema: () => CreateViewResponseSchema2, - CrudEndpointPatternSchema: () => CrudEndpointPatternSchema2, - CrudEndpointsConfigSchema: () => CrudEndpointsConfigSchema2, - CrudOperation: () => CrudOperation2, - CursorMessageSchema: () => CursorMessageSchema2, - CursorPositionSchema: () => CursorPositionSchema2, - DEFAULT_AI_ROUTES: () => DEFAULT_AI_ROUTES, - DEFAULT_ANALYTICS_ROUTES: () => DEFAULT_ANALYTICS_ROUTES, - DEFAULT_AUTOMATION_ROUTES: () => DEFAULT_AUTOMATION_ROUTES, - DEFAULT_BATCH_ROUTES: () => DEFAULT_BATCH_ROUTES, - DEFAULT_DATA_CRUD_ROUTES: () => DEFAULT_DATA_CRUD_ROUTES, - DEFAULT_DISCOVERY_ROUTES: () => DEFAULT_DISCOVERY_ROUTES, - DEFAULT_DISPATCHER_ROUTES: () => DEFAULT_DISPATCHER_ROUTES, - DEFAULT_I18N_ROUTES: () => DEFAULT_I18N_ROUTES, - DEFAULT_METADATA_ROUTES: () => DEFAULT_METADATA_ROUTES, - DEFAULT_NOTIFICATION_ROUTES: () => DEFAULT_NOTIFICATION_ROUTES, - DEFAULT_PERMISSION_ROUTES: () => DEFAULT_PERMISSION_ROUTES, - DEFAULT_REALTIME_ROUTES: () => DEFAULT_REALTIME_ROUTES, - DEFAULT_VERSIONING_CONFIG: () => DEFAULT_VERSIONING_CONFIG, - DEFAULT_VIEW_ROUTES: () => DEFAULT_VIEW_ROUTES, - DEFAULT_WORKFLOW_ROUTES: () => DEFAULT_WORKFLOW_ROUTES, - DataEventSchema: () => DataEventSchema2, - DataEventType: () => DataEventType2, - DataLoaderConfigSchema: () => DataLoaderConfigSchema2, - DeduplicationStrategy: () => DeduplicationStrategy2, - DeleteDataRequestSchema: () => DeleteDataRequestSchema2, - DeleteDataResponseSchema: () => DeleteDataResponseSchema2, - DeleteFeedItemRequestSchema: () => DeleteFeedItemRequestSchema, - DeleteFeedItemResponseSchema: () => DeleteFeedItemResponseSchema2, - DeleteFlowRequestSchema: () => DeleteFlowRequestSchema, - DeleteFlowResponseSchema: () => DeleteFlowResponseSchema2, - DeleteManyDataRequestSchema: () => DeleteManyDataRequestSchema2, - DeleteManyDataResponseSchema: () => DeleteManyDataResponseSchema, - DeleteManyRequestSchema: () => DeleteManyRequestSchema2, - DeleteResponseSchema: () => DeleteResponseSchema2, - DeleteViewRequestSchema: () => DeleteViewRequestSchema2, - DeleteViewResponseSchema: () => DeleteViewResponseSchema2, - DisablePackageRequestSchema: () => DisablePackageRequestSchema3, - DisablePackageResponseSchema: () => DisablePackageResponseSchema3, - DiscoverySchema: () => DiscoverySchema2, - DispatcherConfigSchema: () => DispatcherConfigSchema2, - DispatcherErrorCode: () => DispatcherErrorCode2, - DispatcherErrorResponseSchema: () => DispatcherErrorResponseSchema2, - DispatcherRouteSchema: () => DispatcherRouteSchema2, - DocumentStateSchema: () => DocumentStateSchema2, - ETagSchema: () => ETagSchema2, - EditMessageSchema: () => EditMessageSchema2, - EditOperationSchema: () => EditOperationSchema2, - EditOperationType: () => EditOperationType2, - EnablePackageRequestSchema: () => EnablePackageRequestSchema3, - EnablePackageResponseSchema: () => EnablePackageResponseSchema3, - EndpointMapping: () => EndpointMapping2, - EndpointRegistrySchema: () => EndpointRegistrySchema2, - EnhancedApiErrorSchema: () => EnhancedApiErrorSchema2, - ErrorCategory: () => ErrorCategory2, - ErrorHandlingConfigSchema: () => ErrorHandlingConfigSchema2, - ErrorHttpStatusMap: () => ErrorHttpStatusMap, - ErrorMessageSchema: () => ErrorMessageSchema2, - ErrorResponseSchema: () => ErrorResponseSchema2, - EventFilterCondition: () => EventFilterCondition2, - EventFilterSchema: () => EventFilterSchema2, - EventMessageSchema: () => EventMessageSchema2, - EventPatternSchema: () => EventPatternSchema2, - EventSubscriptionSchema: () => EventSubscriptionSchema2, - ExportApiContracts: () => ExportApiContracts2, - ExportFormat: () => ExportFormat2, - ExportImportTemplateSchema: () => ExportImportTemplateSchema2, - ExportJobProgressSchema: () => ExportJobProgressSchema2, - ExportJobStatus: () => ExportJobStatus2, - ExportJobSummarySchema: () => ExportJobSummarySchema2, - ExportRequestSchema: () => ExportRequestSchema2, - FederationEntityKeySchema: () => FederationEntityKeySchema2, - FederationEntitySchema: () => FederationEntitySchema2, - FederationExternalFieldSchema: () => FederationExternalFieldSchema2, - FederationGatewaySchema: () => FederationGatewaySchema2, - FederationProvidesSchema: () => FederationProvidesSchema2, - FederationRequiresSchema: () => FederationRequiresSchema2, - FeedApiContracts: () => FeedApiContracts, - FeedApiErrorCode: () => FeedApiErrorCode2, - FeedItemPathParamsSchema: () => FeedItemPathParamsSchema2, - FeedListFilterType: () => FeedListFilterType2, - FeedPathParamsSchema: () => FeedPathParamsSchema2, - FeedUnsubscribeRequestSchema: () => FeedUnsubscribeRequestSchema, - FieldErrorSchema: () => FieldErrorSchema2, - FieldMappingEntrySchema: () => FieldMappingEntrySchema2, - FileTypeValidationSchema: () => FileTypeValidationSchema2, - FileUploadResponseSchema: () => FileUploadResponseSchema2, - FilterOperator: () => FilterOperator2, - FindDataRequestSchema: () => FindDataRequestSchema2, - FindDataResponseSchema: () => FindDataResponseSchema2, - FlowSummarySchema: () => FlowSummarySchema2, - GeneratedApiDocumentationSchema: () => GeneratedApiDocumentationSchema2, - GeneratedEndpointSchema: () => GeneratedEndpointSchema2, - GetAnalyticsMetaRequestSchema: () => GetAnalyticsMetaRequestSchema2, - GetChangelogRequestSchema: () => GetChangelogRequestSchema2, - GetChangelogResponseSchema: () => GetChangelogResponseSchema2, - GetDataRequestSchema: () => GetDataRequestSchema2, - GetDataResponseSchema: () => GetDataResponseSchema2, - GetDiscoveryRequestSchema: () => GetDiscoveryRequestSchema2, - GetDiscoveryResponseSchema: () => GetDiscoveryResponseSchema2, - GetEffectivePermissionsRequestSchema: () => GetEffectivePermissionsRequestSchema2, - GetEffectivePermissionsResponseSchema: () => GetEffectivePermissionsResponseSchema2, - GetExportJobDownloadRequestSchema: () => GetExportJobDownloadRequestSchema2, - GetExportJobDownloadResponseSchema: () => GetExportJobDownloadResponseSchema2, - GetFeedRequestSchema: () => GetFeedRequestSchema2, - GetFeedResponseSchema: () => GetFeedResponseSchema2, - GetFieldLabelsRequestSchema: () => GetFieldLabelsRequestSchema2, - GetFieldLabelsResponseSchema: () => GetFieldLabelsResponseSchema2, - GetFlowRequestSchema: () => GetFlowRequestSchema, - GetFlowResponseSchema: () => GetFlowResponseSchema2, - GetInstalledPackageRequestSchema: () => GetInstalledPackageRequestSchema, - GetInstalledPackageResponseSchema: () => GetInstalledPackageResponseSchema2, - GetLocalesRequestSchema: () => GetLocalesRequestSchema2, - GetLocalesResponseSchema: () => GetLocalesResponseSchema2, - GetMetaItemCachedRequestSchema: () => GetMetaItemCachedRequestSchema2, - GetMetaItemCachedResponseSchema: () => GetMetaItemCachedResponseSchema, - GetMetaItemRequestSchema: () => GetMetaItemRequestSchema2, - GetMetaItemResponseSchema: () => GetMetaItemResponseSchema2, - GetMetaItemsRequestSchema: () => GetMetaItemsRequestSchema2, - GetMetaItemsResponseSchema: () => GetMetaItemsResponseSchema2, - GetMetaTypesRequestSchema: () => GetMetaTypesRequestSchema2, - GetMetaTypesResponseSchema: () => GetMetaTypesResponseSchema2, - GetNotificationPreferencesRequestSchema: () => GetNotificationPreferencesRequestSchema2, - GetNotificationPreferencesResponseSchema: () => GetNotificationPreferencesResponseSchema2, - GetObjectPermissionsRequestSchema: () => GetObjectPermissionsRequestSchema2, - GetObjectPermissionsResponseSchema: () => GetObjectPermissionsResponseSchema2, - GetPackageRequestSchema: () => GetPackageRequestSchema3, - GetPackageResponseSchema: () => GetPackageResponseSchema3, - GetPresenceRequestSchema: () => GetPresenceRequestSchema2, - GetPresenceResponseSchema: () => GetPresenceResponseSchema2, - GetPresignedUrlRequestSchema: () => GetPresignedUrlRequestSchema2, - GetRunRequestSchema: () => GetRunRequestSchema, - GetRunResponseSchema: () => GetRunResponseSchema2, - GetTranslationsRequestSchema: () => GetTranslationsRequestSchema2, - GetTranslationsResponseSchema: () => GetTranslationsResponseSchema2, - GetUiViewRequestSchema: () => GetUiViewRequestSchema2, - GetUiViewResponseSchema: () => GetUiViewResponseSchema, - GetViewRequestSchema: () => GetViewRequestSchema2, - GetViewResponseSchema: () => GetViewResponseSchema2, - GetWorkflowConfigRequestSchema: () => GetWorkflowConfigRequestSchema2, - GetWorkflowConfigResponseSchema: () => GetWorkflowConfigResponseSchema2, - GetWorkflowStateRequestSchema: () => GetWorkflowStateRequestSchema2, - GetWorkflowStateResponseSchema: () => GetWorkflowStateResponseSchema2, - GraphQLConfig: () => GraphQLConfig2, - GraphQLConfigSchema: () => GraphQLConfigSchema2, - GraphQLDataLoaderConfigSchema: () => GraphQLDataLoaderConfigSchema2, - GraphQLDirectiveConfigSchema: () => GraphQLDirectiveConfigSchema2, - GraphQLDirectiveLocation: () => GraphQLDirectiveLocation2, - GraphQLMutationConfigSchema: () => GraphQLMutationConfigSchema2, - GraphQLPersistedQuerySchema: () => GraphQLPersistedQuerySchema2, - GraphQLQueryAdapterSchema: () => GraphQLQueryAdapterSchema2, - GraphQLQueryComplexitySchema: () => GraphQLQueryComplexitySchema2, - GraphQLQueryConfigSchema: () => GraphQLQueryConfigSchema2, - GraphQLQueryDepthLimitSchema: () => GraphQLQueryDepthLimitSchema2, - GraphQLRateLimitSchema: () => GraphQLRateLimitSchema2, - GraphQLResolverConfigSchema: () => GraphQLResolverConfigSchema2, - GraphQLScalarType: () => GraphQLScalarType2, - GraphQLSubscriptionConfigSchema: () => GraphQLSubscriptionConfigSchema2, - GraphQLTypeConfigSchema: () => GraphQLTypeConfigSchema2, - HandlerStatusSchema: () => HandlerStatusSchema2, - HttpFindQueryParamsSchema: () => HttpFindQueryParamsSchema2, - HttpMethod: () => HttpMethod5, - HttpStatusCode: () => HttpStatusCode2, - IdRequestSchema: () => IdRequestSchema2, - ImportValidationConfigSchema: () => ImportValidationConfigSchema2, - ImportValidationMode: () => ImportValidationMode2, - ImportValidationResultSchema: () => ImportValidationResultSchema2, - InitiateChunkedUploadRequestSchema: () => InitiateChunkedUploadRequestSchema2, - InitiateChunkedUploadResponseSchema: () => InitiateChunkedUploadResponseSchema2, - InstallPackageRequestSchema: () => InstallPackageRequestSchema3, - InstallPackageResponseSchema: () => InstallPackageResponseSchema3, - ListExportJobsRequestSchema: () => ListExportJobsRequestSchema2, - ListExportJobsResponseSchema: () => ListExportJobsResponseSchema2, - ListFlowsRequestSchema: () => ListFlowsRequestSchema2, - ListFlowsResponseSchema: () => ListFlowsResponseSchema2, - ListInstalledPackagesRequestSchema: () => ListInstalledPackagesRequestSchema2, - ListInstalledPackagesResponseSchema: () => ListInstalledPackagesResponseSchema2, - ListNotificationsRequestSchema: () => ListNotificationsRequestSchema2, - ListNotificationsResponseSchema: () => ListNotificationsResponseSchema2, - ListPackagesRequestSchema: () => ListPackagesRequestSchema3, - ListPackagesResponseSchema: () => ListPackagesResponseSchema3, - ListRecordResponseSchema: () => ListRecordResponseSchema2, - ListRunsRequestSchema: () => ListRunsRequestSchema2, - ListRunsResponseSchema: () => ListRunsResponseSchema2, - ListViewsRequestSchema: () => ListViewsRequestSchema2, - ListViewsResponseSchema: () => ListViewsResponseSchema2, - LoginRequestSchema: () => LoginRequestSchema2, - LoginType: () => LoginType2, - MarkAllNotificationsReadRequestSchema: () => MarkAllNotificationsReadRequestSchema2, - MarkAllNotificationsReadResponseSchema: () => MarkAllNotificationsReadResponseSchema2, - MarkNotificationsReadRequestSchema: () => MarkNotificationsReadRequestSchema2, - MarkNotificationsReadResponseSchema: () => MarkNotificationsReadResponseSchema2, - MetadataBulkRegisterRequestSchema: () => MetadataBulkRegisterRequestSchema22, - MetadataBulkResponseSchema: () => MetadataBulkResponseSchema2, - MetadataBulkUnregisterRequestSchema: () => MetadataBulkUnregisterRequestSchema2, - MetadataCacheApi: () => MetadataCacheApi, - MetadataCacheRequestSchema: () => MetadataCacheRequestSchema2, - MetadataCacheResponseSchema: () => MetadataCacheResponseSchema2, - MetadataDeleteResponseSchema: () => MetadataDeleteResponseSchema2, - MetadataDependenciesResponseSchema: () => MetadataDependenciesResponseSchema2, - MetadataDependentsResponseSchema: () => MetadataDependentsResponseSchema2, - MetadataEffectiveResponseSchema: () => MetadataEffectiveResponseSchema2, - MetadataEndpointsConfigSchema: () => MetadataEndpointsConfigSchema2, - MetadataEventSchema: () => MetadataEventSchema22, - MetadataEventType: () => MetadataEventType2, - MetadataExistsResponseSchema: () => MetadataExistsResponseSchema2, - MetadataExportRequestSchema: () => MetadataExportRequestSchema2, - MetadataExportResponseSchema: () => MetadataExportResponseSchema2, - MetadataImportRequestSchema: () => MetadataImportRequestSchema2, - MetadataImportResponseSchema: () => MetadataImportResponseSchema2, - MetadataItemResponseSchema: () => MetadataItemResponseSchema2, - MetadataListResponseSchema: () => MetadataListResponseSchema2, - MetadataNamesResponseSchema: () => MetadataNamesResponseSchema2, - MetadataOverlayResponseSchema: () => MetadataOverlayResponseSchema2, - MetadataOverlaySaveRequestSchema: () => MetadataOverlaySaveRequestSchema2, - MetadataQueryRequestSchema: () => MetadataQueryRequestSchema2, - MetadataQueryResponseSchema: () => MetadataQueryResponseSchema2, - MetadataRegisterRequestSchema: () => MetadataRegisterRequestSchema2, - MetadataTypeInfoResponseSchema: () => MetadataTypeInfoResponseSchema2, - MetadataTypesResponseSchema: () => MetadataTypesResponseSchema2, - MetadataValidateRequestSchema: () => MetadataValidateRequestSchema2, - MetadataValidateResponseSchema: () => MetadataValidateResponseSchema2, - ModificationResultSchema: () => ModificationResultSchema2, - NotificationPreferencesSchema: () => NotificationPreferencesSchema2, - NotificationSchema: () => NotificationSchema22, - OData: () => OData, - ODataConfigSchema: () => ODataConfigSchema2, - ODataErrorSchema: () => ODataErrorSchema2, - ODataFilterFunctionSchema: () => ODataFilterFunctionSchema2, - ODataFilterOperatorSchema: () => ODataFilterOperatorSchema2, - ODataMetadataSchema: () => ODataMetadataSchema2, - ODataQueryAdapterSchema: () => ODataQueryAdapterSchema2, - ODataQuerySchema: () => ODataQuerySchema2, - ODataResponseSchema: () => ODataResponseSchema2, - ObjectDefinitionResponseSchema: () => ObjectDefinitionResponseSchema2, - ObjectQLReferenceSchema: () => ObjectQLReferenceSchema2, - ObjectStackProtocolSchema: () => ObjectStackProtocolSchema2, - OpenApi31ExtensionsSchema: () => OpenApi31ExtensionsSchema2, - OpenApiGenerationConfigSchema: () => OpenApiGenerationConfigSchema2, - OpenApiSecuritySchemeSchema: () => OpenApiSecuritySchemeSchema2, - OpenApiServerSchema: () => OpenApiServerSchema2, - OpenApiSpec: () => OpenApiSpec2, - OpenApiSpecSchema: () => OpenApiSpecSchema2, - OperatorMappingSchema: () => OperatorMappingSchema2, - PackageApiContracts: () => PackageApiContracts, - PackageApiErrorCode: () => PackageApiErrorCode2, - PackageInstallRequestSchema: () => PackageInstallRequestSchema2, - PackageInstallResponseSchema: () => PackageInstallResponseSchema2, - PackagePathParamsSchema: () => PackagePathParamsSchema2, - PackageRollbackRequestSchema: () => PackageRollbackRequestSchema2, - PackageRollbackResponseSchema: () => PackageRollbackResponseSchema2, - PackageUpgradeRequestSchema: () => PackageUpgradeRequestSchema2, - PackageUpgradeResponseSchema: () => PackageUpgradeResponseSchema2, - PinFeedItemRequestSchema: () => PinFeedItemRequestSchema, - PinFeedItemResponseSchema: () => PinFeedItemResponseSchema2, - PingMessageSchema: () => PingMessageSchema2, - PongMessageSchema: () => PongMessageSchema2, - PresenceMessageSchema: () => PresenceMessageSchema2, - PresenceStateSchema: () => PresenceStateSchema2, - PresenceStatus: () => PresenceStatus2, - PresenceUpdateSchema: () => PresenceUpdateSchema2, - PresignedUrlResponseSchema: () => PresignedUrlResponseSchema2, - QueryAdapterConfigSchema: () => QueryAdapterConfigSchema2, - QueryAdapterTargetSchema: () => QueryAdapterTargetSchema2, - QueryOptimizationConfigSchema: () => QueryOptimizationConfigSchema2, - RealtimeConfigSchema: () => RealtimeConfigSchema2, - RealtimeConnectRequestSchema: () => RealtimeConnectRequestSchema2, - RealtimeConnectResponseSchema: () => RealtimeConnectResponseSchema2, - RealtimeDisconnectRequestSchema: () => RealtimeDisconnectRequestSchema2, - RealtimeDisconnectResponseSchema: () => RealtimeDisconnectResponseSchema2, - RealtimeEventSchema: () => RealtimeEventSchema2, - RealtimeEventType: () => RealtimeEventType2, - RealtimePresenceSchema: () => RealtimePresenceSchema2, - RealtimeRecordAction: () => RealtimeRecordAction2, - RealtimeSubscribeRequestSchema: () => RealtimeSubscribeRequestSchema2, - RealtimeSubscribeResponseSchema: () => RealtimeSubscribeResponseSchema2, - RealtimeUnsubscribeRequestSchema: () => RealtimeUnsubscribeRequestSchema2, - RealtimeUnsubscribeResponseSchema: () => RealtimeUnsubscribeResponseSchema2, - RecordDataSchema: () => RecordDataSchema2, - RefreshTokenRequestSchema: () => RefreshTokenRequestSchema2, - RegisterDeviceRequestSchema: () => RegisterDeviceRequestSchema2, - RegisterDeviceResponseSchema: () => RegisterDeviceResponseSchema2, - RegisterRequestSchema: () => RegisterRequestSchema2, - RemoveReactionRequestSchema: () => RemoveReactionRequestSchema2, - RemoveReactionResponseSchema: () => RemoveReactionResponseSchema2, - RequestValidationConfigSchema: () => RequestValidationConfigSchema2, - ResolveDependenciesRequestSchema: () => ResolveDependenciesRequestSchema2, - ResolveDependenciesResponseSchema: () => ResolveDependenciesResponseSchema2, - ResponseEnvelopeConfigSchema: () => ResponseEnvelopeConfigSchema2, - RestApiConfig: () => RestApiConfig2, - RestApiConfigSchema: () => RestApiConfigSchema2, - RestApiEndpointSchema: () => RestApiEndpointSchema2, - RestApiPluginConfig: () => RestApiPluginConfig2, - RestApiPluginConfigSchema: () => RestApiPluginConfigSchema2, - RestApiRouteCategory: () => RestApiRouteCategory2, - RestApiRouteRegistration: () => RestApiRouteRegistration2, - RestApiRouteRegistrationSchema: () => RestApiRouteRegistrationSchema2, - RestQueryAdapterSchema: () => RestQueryAdapterSchema2, - RestServerConfig: () => RestServerConfig2, - RestServerConfigSchema: () => RestServerConfigSchema2, - RetryStrategy: () => RetryStrategy2, - RouteCategory: () => RouteCategory2, - RouteCoverageEntrySchema: () => RouteCoverageEntrySchema2, - RouteCoverageReportSchema: () => RouteCoverageReportSchema2, - RouteDefinitionSchema: () => RouteDefinitionSchema2, - RouteGenerationConfigSchema: () => RouteGenerationConfigSchema2, - RouteHealthEntrySchema: () => RouteHealthEntrySchema2, - RouteHealthReportSchema: () => RouteHealthReportSchema2, - RouterConfigSchema: () => RouterConfigSchema2, - SaveMetaItemRequestSchema: () => SaveMetaItemRequestSchema2, - SaveMetaItemResponseSchema: () => SaveMetaItemResponseSchema2, - ScheduleExportRequestSchema: () => ScheduleExportRequestSchema2, - ScheduleExportResponseSchema: () => ScheduleExportResponseSchema2, - ScheduledExportSchema: () => ScheduledExportSchema2, - SchemaDefinition: () => SchemaDefinition2, - SearchFeedRequestSchema: () => SearchFeedRequestSchema2, - SearchFeedResponseSchema: () => SearchFeedResponseSchema2, - ServiceInfoSchema: () => ServiceInfoSchema2, - ServiceStatus: () => ServiceStatus2, - SessionResponseSchema: () => SessionResponseSchema2, - SessionSchema: () => SessionSchema22, - SessionUserSchema: () => SessionUserSchema2, - SetPresenceRequestSchema: () => SetPresenceRequestSchema2, - SetPresenceResponseSchema: () => SetPresenceResponseSchema2, - SimpleCursorPositionSchema: () => SimpleCursorPositionSchema2, - SimplePresenceStateSchema: () => SimplePresenceStateSchema2, - SingleRecordResponseSchema: () => SingleRecordResponseSchema2, - StandardApiContracts: () => StandardApiContracts2, - StandardErrorCode: () => StandardErrorCode2, - StarFeedItemRequestSchema: () => StarFeedItemRequestSchema, - StarFeedItemResponseSchema: () => StarFeedItemResponseSchema2, - StorageApiContracts: () => StorageApiContracts, - SubgraphConfigSchema: () => SubgraphConfigSchema2, - SubscribeMessageSchema: () => SubscribeMessageSchema2, - SubscribeRequestSchema: () => SubscribeRequestSchema2, - SubscribeResponseSchema: () => SubscribeResponseSchema2, - SubscriptionEventSchema: () => SubscriptionEventSchema2, - SubscriptionSchema: () => SubscriptionSchema2, - ToggleFlowRequestSchema: () => ToggleFlowRequestSchema2, - ToggleFlowResponseSchema: () => ToggleFlowResponseSchema2, - TransportProtocol: () => TransportProtocol2, - TriggerFlowRequestSchema: () => TriggerFlowRequestSchema2, - TriggerFlowResponseSchema: () => TriggerFlowResponseSchema2, - UninstallPackageApiRequestSchema: () => UninstallPackageApiRequestSchema, - UninstallPackageApiResponseSchema: () => UninstallPackageApiResponseSchema2, - UninstallPackageRequestSchema: () => UninstallPackageRequestSchema3, - UninstallPackageResponseSchema: () => UninstallPackageResponseSchema3, - UnpinFeedItemRequestSchema: () => UnpinFeedItemRequestSchema, - UnpinFeedItemResponseSchema: () => UnpinFeedItemResponseSchema2, - UnregisterDeviceRequestSchema: () => UnregisterDeviceRequestSchema2, - UnregisterDeviceResponseSchema: () => UnregisterDeviceResponseSchema2, - UnstarFeedItemRequestSchema: () => UnstarFeedItemRequestSchema, - UnstarFeedItemResponseSchema: () => UnstarFeedItemResponseSchema2, - UnsubscribeMessageSchema: () => UnsubscribeMessageSchema2, - UnsubscribeRequestSchema: () => UnsubscribeRequestSchema2, - UnsubscribeResponseSchema: () => UnsubscribeResponseSchema2, - UpdateDataRequestSchema: () => UpdateDataRequestSchema2, - UpdateDataResponseSchema: () => UpdateDataResponseSchema2, - UpdateFeedItemRequestSchema: () => UpdateFeedItemRequestSchema2, - UpdateFeedItemResponseSchema: () => UpdateFeedItemResponseSchema2, - UpdateFlowRequestSchema: () => UpdateFlowRequestSchema2, - UpdateFlowResponseSchema: () => UpdateFlowResponseSchema2, - UpdateManyDataRequestSchema: () => UpdateManyDataRequestSchema2, - UpdateManyDataResponseSchema: () => UpdateManyDataResponseSchema, - UpdateManyRequestSchema: () => UpdateManyRequestSchema2, - UpdateNotificationPreferencesRequestSchema: () => UpdateNotificationPreferencesRequestSchema2, - UpdateNotificationPreferencesResponseSchema: () => UpdateNotificationPreferencesResponseSchema2, - UpdateRequestSchema: () => UpdateRequestSchema2, - UpdateViewRequestSchema: () => UpdateViewRequestSchema2, - UpdateViewResponseSchema: () => UpdateViewResponseSchema2, - UploadArtifactRequestSchema: () => UploadArtifactRequestSchema2, - UploadArtifactResponseSchema: () => UploadArtifactResponseSchema2, - UploadChunkRequestSchema: () => UploadChunkRequestSchema2, - UploadChunkResponseSchema: () => UploadChunkResponseSchema2, - UploadProgressSchema: () => UploadProgressSchema2, - UserProfileResponseSchema: () => UserProfileResponseSchema2, - ValidationMode: () => ValidationMode2, - VersionDefinitionSchema: () => VersionDefinitionSchema2, - VersionNegotiationResponseSchema: () => VersionNegotiationResponseSchema2, - VersionStatus: () => VersionStatus2, - VersioningConfigSchema: () => VersioningConfigSchema23, - VersioningStrategy: () => VersioningStrategy2, - WebSocketConfigSchema: () => WebSocketConfigSchema2, - WebSocketEventSchema: () => WebSocketEventSchema2, - WebSocketMessageSchema: () => WebSocketMessageSchema2, - WebSocketMessageType: () => WebSocketMessageType2, - WebSocketPresenceStatus: () => WebSocketPresenceStatus2, - WebSocketServerConfigSchema: () => WebSocketServerConfigSchema2, - WebhookConfigSchema: () => WebhookConfigSchema2, - WebhookEventSchema: () => WebhookEventSchema2, - WellKnownCapabilitiesSchema: () => WellKnownCapabilitiesSchema2, - WorkflowApproveRequestSchema: () => WorkflowApproveRequestSchema2, - WorkflowApproveResponseSchema: () => WorkflowApproveResponseSchema2, - WorkflowRejectRequestSchema: () => WorkflowRejectRequestSchema2, - WorkflowRejectResponseSchema: () => WorkflowRejectResponseSchema2, - WorkflowStateSchema: () => WorkflowStateSchema2, - WorkflowTransitionRequestSchema: () => WorkflowTransitionRequestSchema2, - WorkflowTransitionResponseSchema: () => WorkflowTransitionResponseSchema2, - getAuthEndpointUrl: () => getAuthEndpointUrl, - getDefaultRouteRegistrations: () => getDefaultRouteRegistrations, - mapFieldTypeToGraphQL: () => mapFieldTypeToGraphQL -}); -var ApiErrorSchema2 = external_exports.object({ - code: external_exports.string().describe("Error code (e.g. validation_error)"), - message: external_exports.string().describe("Readable error message"), - category: external_exports.string().optional().describe("Error category (e.g. validation, authorization)"), - details: external_exports.unknown().optional().describe("Additional error context (e.g. field validation errors)"), - requestId: external_exports.string().optional().describe("Request ID for tracking") -}); -var BaseResponseSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Operation success status"), - error: ApiErrorSchema2.optional().describe("Error details if success is false"), - meta: external_exports.object({ - timestamp: external_exports.string(), - duration: external_exports.number().optional(), - requestId: external_exports.string().optional(), - traceId: external_exports.string().optional() - }).optional().describe("Response metadata") -}); -var RecordDataSchema2 = external_exports.record(external_exports.string(), external_exports.unknown()).describe("Key-value map of record data"); -var CreateRequestSchema2 = external_exports.object({ - data: RecordDataSchema2.describe("Record data to insert") -}); -var UpdateRequestSchema2 = external_exports.object({ - data: RecordDataSchema2.describe("Partial record data to update") -}); -var BulkRequestSchema2 = external_exports.object({ - records: external_exports.array(RecordDataSchema2).describe("Array of records to process"), - allOrNone: external_exports.boolean().default(true).describe("If true, rollback entire transaction on any failure") -}); -var ExportRequestSchema2 = external_exports.intersection( - QuerySchema3, - external_exports.object({ - format: external_exports.enum(["csv", "json", "xlsx"]).default("csv") - }) -); -var SingleRecordResponseSchema2 = BaseResponseSchema2.extend({ - data: RecordDataSchema2.describe("The requested or modified record") -}); -var ListRecordResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.array(RecordDataSchema2).describe("Array of matching records"), - pagination: external_exports.object({ - total: external_exports.number().optional().describe("Total matching records count"), - limit: external_exports.number().optional().describe("Page size"), - offset: external_exports.number().optional().describe("Page offset"), - cursor: external_exports.string().optional().describe("Cursor for next page"), - nextCursor: external_exports.string().optional().describe("Next cursor for pagination"), - hasMore: external_exports.boolean().describe("Are there more pages?") - }).describe("Pagination info") -}); -var IdRequestSchema2 = external_exports.object({ - id: external_exports.string().describe("Record ID") -}); -var ModificationResultSchema2 = external_exports.object({ - id: external_exports.string().optional().describe("Record ID if processed"), - success: external_exports.boolean(), - errors: external_exports.array(ApiErrorSchema2).optional(), - index: external_exports.number().optional().describe("Index in original request"), - data: external_exports.unknown().optional().describe("Result data (e.g. created record)") -}); -var BulkResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.array(ModificationResultSchema2).describe("Results for each item in the batch") -}); -var DeleteResponseSchema2 = BaseResponseSchema2.extend({ - id: external_exports.string().describe("ID of the deleted record") -}); -var StandardApiContracts2 = { - create: { - input: CreateRequestSchema2, - output: SingleRecordResponseSchema2 - }, - delete: { - input: IdRequestSchema2, - output: DeleteResponseSchema2 - }, - get: { - input: IdRequestSchema2, - output: SingleRecordResponseSchema2 - }, - update: { - input: UpdateRequestSchema2, - output: SingleRecordResponseSchema2 - }, - list: { - input: QuerySchema3, - output: ListRecordResponseSchema2 - }, - bulkCreate: { - input: BulkRequestSchema2, - output: BulkResponseSchema2 - }, - bulkUpdate: { - input: BulkRequestSchema2, - output: BulkResponseSchema2 - }, - bulkUpsert: { - input: BulkRequestSchema2, - output: BulkResponseSchema2 - }, - bulkDelete: { - input: external_exports.object({ ids: external_exports.array(external_exports.string()) }), - output: BulkResponseSchema2 - } -}; -var DataLoaderConfigSchema2 = external_exports.object({ - maxBatchSize: external_exports.number().int().default(100).describe("Maximum number of keys per batch load"), - batchScheduleFn: external_exports.enum(["microtask", "timeout", "manual"]).default("microtask").describe("Scheduling strategy for collecting batch keys"), - cacheEnabled: external_exports.boolean().default(true).describe("Enable per-request result caching"), - cacheKeyFn: external_exports.string().optional().describe("Name or identifier of the cache key function"), - cacheTtl: external_exports.number().min(0).optional().describe("Cache time-to-live in seconds (0 = no expiration)"), - coalesceRequests: external_exports.boolean().default(true).describe("Deduplicate identical requests within a batch window"), - maxConcurrency: external_exports.number().int().optional().describe("Maximum parallel batch requests") -}); -var BatchLoadingStrategySchema2 = external_exports.object({ - strategy: external_exports.enum(["dataloader", "windowed", "prefetch"]).describe("Batch loading strategy type"), - windowMs: external_exports.number().optional().describe("Collection window duration in milliseconds (for windowed strategy)"), - prefetchDepth: external_exports.number().int().optional().describe("Depth of relation prefetching (for prefetch strategy)"), - associationLoading: external_exports.enum(["lazy", "eager", "batch"]).default("batch").describe("How to load related associations") -}); -var QueryOptimizationConfigSchema2 = external_exports.object({ - preventNPlusOne: external_exports.boolean().describe("Enable N+1 query detection and prevention"), - dataLoader: DataLoaderConfigSchema2.optional().describe("DataLoader batch loading configuration"), - batchStrategy: BatchLoadingStrategySchema2.optional().describe("Batch loading strategy configuration"), - maxQueryDepth: external_exports.number().int().describe("Maximum depth for nested relation queries"), - queryComplexityLimit: external_exports.number().optional().describe("Maximum allowed query complexity score"), - enableQueryPlan: external_exports.boolean().default(false).describe("Log query execution plans for debugging") -}); -var ApiMappingSchema2 = external_exports.object({ - source: external_exports.string().describe("Source field/path"), - target: external_exports.string().describe("Target field/path"), - transform: external_exports.string().optional().describe("Transformation function name") -}); -var ApiEndpointSchema2 = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique endpoint ID"), - path: external_exports.string().regex(/^\//).describe("URL Path (e.g. /api/v1/customers)"), - method: HttpMethod5.describe("HTTP Method"), - /** Documentation */ - summary: external_exports.string().optional(), - description: external_exports.string().optional(), - /** Execution Logic */ - type: external_exports.enum(["flow", "script", "object_operation", "proxy"]).describe("Implementation type"), - target: external_exports.string().describe("Target Flow ID, Script Name, or Proxy URL"), - /** Logic Config */ - objectParams: external_exports.object({ - object: external_exports.string().optional(), - operation: external_exports.enum(["find", "get", "create", "update", "delete"]).optional() - }).optional().describe("For object_operation type"), - /** Data Transformation */ - inputMapping: external_exports.array(ApiMappingSchema2).optional().describe("Map Request Body to Internal Params"), - outputMapping: external_exports.array(ApiMappingSchema2).optional().describe("Map Internal Result to Response Body"), - /** Policies */ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - rateLimit: RateLimitConfigSchema4.optional().describe("Rate limiting policy"), - cacheTtl: external_exports.number().optional().describe("Response cache TTL in seconds") -}); -var ApiEndpoint2 = Object.assign(ApiEndpointSchema2, { - create: (config4) => config4 -}); -var ServiceStatus2 = external_exports.enum([ - "available", - "registered", - "unavailable", - "degraded", - "stub" -]).describe( - "available = fully operational, registered = route declared but handler unverified, unavailable = not installed, degraded = partial, stub = placeholder that returns 501" -); -var ServiceInfoSchema2 = external_exports.object({ - /** Whether the service is enabled and available */ - enabled: external_exports.boolean(), - /** Current operational status */ - status: ServiceStatus2, - /** - * Whether the HTTP handler for this service is confirmed to be mounted. - * - * Semantics: - * - `undefined` (omitted) = handler readiness is unknown / not yet verified. - * - `true` = handler is registered in the adapter / dispatcher (safe to call). - * - `false` = route is declared but no handler exists or only a stub is present - * — requests are expected to receive 501 Not Implemented. - * - * Clients SHOULD check this flag before displaying or invoking a service endpoint and may - * distinguish between "unknown" (omitted) and "known missing" (`false`). - */ - handlerReady: external_exports.boolean().optional().describe( - "Whether the HTTP handler is confirmed to be mounted. Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501)." - ), - /** Route path (only present if enabled) */ - route: external_exports.string().optional().describe("e.g. /api/v1/analytics"), - /** Implementation provider name */ - provider: external_exports.string().optional().describe('e.g. "objectql", "plugin-redis", "driver-memory"'), - /** Service version */ - version: external_exports.string().optional().describe('Semantic version of the service implementation (e.g. "3.0.6")'), - /** Human-readable reason if unavailable */ - message: external_exports.string().optional().describe('e.g. "Install plugin-workflow to enable"'), - /** Rate limit configuration for this service */ - rateLimit: external_exports.object({ - requestsPerMinute: external_exports.number().int().optional().describe("Maximum requests per minute"), - requestsPerHour: external_exports.number().int().optional().describe("Maximum requests per hour"), - burstLimit: external_exports.number().int().optional().describe("Maximum burst request count"), - retryAfterMs: external_exports.number().int().optional().describe("Suggested retry-after delay in milliseconds when rate-limited") - }).optional().describe("Rate limit and quota info for this service") -}); -var ApiRoutesSchema2 = external_exports.object({ - /** Base URL for Object CRUD (Data Protocol) */ - data: external_exports.string().describe("e.g. /api/v1/data"), - /** Base URL for Schema Definitions (Metadata Protocol) */ - metadata: external_exports.string().describe("e.g. /api/v1/meta"), - /** Base URL for API Discovery endpoint */ - discovery: external_exports.string().optional().describe("e.g. /api/v1/discovery"), - /** Base URL for UI Configurations (Views, Menus) */ - ui: external_exports.string().optional().describe("e.g. /api/v1/ui"), - /** Base URL for Authentication (plugin-provided) */ - auth: external_exports.string().optional().describe("e.g. /api/v1/auth"), - /** Base URL for Automation (Flows/Scripts) */ - automation: external_exports.string().optional().describe("e.g. /api/v1/automation"), - /** Base URL for File/Storage operations */ - storage: external_exports.string().optional().describe("e.g. /api/v1/storage"), - /** Base URL for Analytics/BI operations */ - analytics: external_exports.string().optional().describe("e.g. /api/v1/analytics"), - /** GraphQL Endpoint (if enabled) */ - graphql: external_exports.string().optional().describe("e.g. /graphql"), - /** Base URL for Package Management */ - packages: external_exports.string().optional().describe("e.g. /api/v1/packages"), - /** Base URL for Workflow Engine */ - workflow: external_exports.string().optional().describe("e.g. /api/v1/workflow"), - /** Base URL for Realtime (WebSocket/SSE) */ - realtime: external_exports.string().optional().describe("e.g. /api/v1/realtime"), - /** Base URL for Notification Service */ - notifications: external_exports.string().optional().describe("e.g. /api/v1/notifications"), - /** Base URL for AI Engine (NLQ, Chat, Suggest) */ - ai: external_exports.string().optional().describe("e.g. /api/v1/ai"), - /** Base URL for Internationalization */ - i18n: external_exports.string().optional().describe("e.g. /api/v1/i18n"), - /** Base URL for Feed / Chatter API */ - feed: external_exports.string().optional().describe("e.g. /api/v1/feed") -}); -var DiscoverySchema2 = external_exports.object({ - /** System Identity */ - name: external_exports.string(), - version: external_exports.string(), - environment: external_exports.enum(["production", "sandbox", "development"]), - /** Dynamic Routing — convenience shortcut for client routing */ - routes: ApiRoutesSchema2, - /** Localization Info (helping frontend init i18n) */ - locale: external_exports.object({ - default: external_exports.string(), - supported: external_exports.array(external_exports.string()), - timezone: external_exports.string() - }), - /** - * Per-service status map. - * This is the **single source of truth** for service availability. - * Clients use this to determine which features are available, - * show/hide UI elements, and display appropriate messages. - */ - services: external_exports.record(external_exports.string(), ServiceInfoSchema2).describe( - "Per-service availability map keyed by CoreServiceName" - ), - /** - * Hierarchical capability descriptors. - * Declares platform features so clients can adapt UI without probing individual services. - * Each key is a capability domain (e.g., "comments", "automation", "search"), - * and its value describes what sub-features are available. - */ - capabilities: external_exports.record(external_exports.string(), external_exports.object({ - enabled: external_exports.boolean().describe("Whether this capability is available"), - features: external_exports.record(external_exports.string(), external_exports.boolean()).optional().describe("Sub-feature flags within this capability"), - description: external_exports.string().optional().describe("Human-readable capability description") - })).optional().describe("Hierarchical capability descriptors for frontend intelligent adaptation"), - /** - * Schema discovery URLs for cross-ecosystem interoperability. - */ - schemaDiscovery: external_exports.object({ - openapi: external_exports.string().optional().describe('URL to OpenAPI (Swagger) specification (e.g., "/api/v1/openapi.json")'), - graphql: external_exports.string().optional().describe('URL to GraphQL schema endpoint (e.g., "/graphql")'), - jsonSchema: external_exports.string().optional().describe("URL to JSON Schema definitions") - }).optional().describe("Schema discovery endpoints for API toolchain integration"), - /** - * Custom metadata key-value pairs for extensibility - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata key-value pairs for extensibility") -}); -var WellKnownCapabilitiesSchema2 = external_exports.object({ - /** Whether the backend supports Feed / Chatter API */ - feed: external_exports.boolean().describe("Whether the backend supports Feed / Chatter API"), - /** Whether the backend supports comments (a subset of Feed) */ - comments: external_exports.boolean().describe("Whether the backend supports comments (a subset of Feed)"), - /** Whether the backend supports Automation CRUD (flows, triggers) */ - automation: external_exports.boolean().describe("Whether the backend supports Automation CRUD (flows, triggers)"), - /** Whether the backend supports cron scheduling */ - cron: external_exports.boolean().describe("Whether the backend supports cron scheduling"), - /** Whether the backend supports full-text search */ - search: external_exports.boolean().describe("Whether the backend supports full-text search"), - /** Whether the backend supports async export */ - export: external_exports.boolean().describe("Whether the backend supports async export"), - /** Whether the backend supports chunked (multipart) uploads */ - chunkedUpload: external_exports.boolean().describe("Whether the backend supports chunked (multipart) uploads") -}).describe("Well-known capability flags for frontend intelligent adaptation"); -var RouteHealthEntrySchema2 = external_exports.object({ - /** Route path (e.g. /api/v1/analytics) */ - route: external_exports.string().describe("Route path pattern"), - /** HTTP method */ - method: HttpMethod5.describe("HTTP method (GET, POST, etc.)"), - /** Target service name */ - service: external_exports.string().describe("Target service name"), - /** Whether the route is declared in discovery */ - declared: external_exports.boolean().describe("Whether the route is declared in discovery/metadata"), - /** Whether the handler is actually registered in the adapter/dispatcher */ - handlerRegistered: external_exports.boolean().describe("Whether the HTTP handler is registered"), - /** - * Health check result: - * - `pass` – Handler exists and responds (2xx/4xx — i.e., not 404/501/503) - * - `fail` – Handler returned 501 or 503 - * - `missing` – No handler registered (404) - * - `skip` – Health check was not performed - */ - healthStatus: external_exports.enum(["pass", "fail", "missing", "skip"]).describe( - "pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked" - ), - /** Optional diagnostic message */ - message: external_exports.string().optional().describe("Diagnostic message") -}); -var RouteHealthReportSchema2 = external_exports.object({ - /** ISO 8601 timestamp of when the report was generated */ - timestamp: external_exports.string().describe("ISO 8601 timestamp of report generation"), - /** Adapter name that generated the report (e.g. "hono", "express", "nextjs") */ - adapter: external_exports.string().describe("Adapter or runtime that produced this report"), - /** Total routes declared in discovery / dispatcher table */ - totalDeclared: external_exports.number().int().describe("Total routes declared in discovery"), - /** Routes with a confirmed handler registration */ - totalRegistered: external_exports.number().int().describe("Routes with confirmed handler"), - /** Routes missing a handler */ - totalMissing: external_exports.number().int().describe("Routes missing a handler"), - /** Per-route health entries */ - routes: external_exports.array(RouteHealthEntrySchema2).describe("Per-route health entries") -}); -var MetadataEventType2 = external_exports.enum([ - "metadata.object.created", - "metadata.object.updated", - "metadata.object.deleted", - "metadata.field.created", - "metadata.field.updated", - "metadata.field.deleted", - "metadata.view.created", - "metadata.view.updated", - "metadata.view.deleted", - "metadata.app.created", - "metadata.app.updated", - "metadata.app.deleted", - "metadata.agent.created", - "metadata.agent.updated", - "metadata.agent.deleted", - "metadata.tool.created", - "metadata.tool.updated", - "metadata.tool.deleted", - "metadata.flow.created", - "metadata.flow.updated", - "metadata.flow.deleted", - "metadata.action.created", - "metadata.action.updated", - "metadata.action.deleted", - "metadata.workflow.created", - "metadata.workflow.updated", - "metadata.workflow.deleted", - "metadata.dashboard.created", - "metadata.dashboard.updated", - "metadata.dashboard.deleted", - "metadata.report.created", - "metadata.report.updated", - "metadata.report.deleted", - "metadata.role.created", - "metadata.role.updated", - "metadata.role.deleted", - "metadata.permission.created", - "metadata.permission.updated", - "metadata.permission.deleted" -]); -var DataEventType2 = external_exports.enum([ - "data.record.created", - "data.record.updated", - "data.record.deleted", - "data.field.changed" -]); -var MetadataEventSchema22 = external_exports.object({ - /** Unique event identifier */ - id: external_exports.string().uuid().describe("Unique event identifier"), - /** Event type (metadata.{type}.{action}) */ - type: MetadataEventType2.describe("Event type"), - /** Metadata type (object, view, agent, tool, etc.) */ - metadataType: external_exports.string().describe("Metadata type (object, view, agent, etc.)"), - /** Metadata item name */ - name: external_exports.string().describe("Metadata item name"), - /** Package ID (if applicable) */ - packageId: external_exports.string().optional().describe("Package ID"), - /** Full definition (only for create/update events) */ - definition: external_exports.unknown().optional().describe("Full definition (create/update only)"), - /** User who triggered the event */ - userId: external_exports.string().optional().describe("User who triggered the event"), - /** Event timestamp (ISO 8601) */ - timestamp: external_exports.string().datetime().describe("Event timestamp") -}); -var DataEventSchema2 = external_exports.object({ - /** Unique event identifier */ - id: external_exports.string().uuid().describe("Unique event identifier"), - /** Event type (data.record.{action}) */ - type: DataEventType2.describe("Event type"), - /** Object name */ - object: external_exports.string().describe("Object name"), - /** Record ID */ - recordId: external_exports.string().describe("Record ID"), - /** Changed fields (update events only) */ - changes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Changed fields"), - /** Record before update (update events only) */ - before: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Before state"), - /** Record after update (create/update events) */ - after: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("After state"), - /** User who triggered the event */ - userId: external_exports.string().optional().describe("User who triggered the event"), - /** Event timestamp (ISO 8601) */ - timestamp: external_exports.string().datetime().describe("Event timestamp") -}); -var PresenceStatus2 = external_exports.enum([ - "online", - // User is actively connected - "away", - // User is idle/inactive - "busy", - // User is busy (do not disturb) - "offline" - // User is disconnected -]); -var RealtimeRecordAction2 = external_exports.enum([ - "created", - "updated", - "deleted" -]); -var BasePresenceSchema2 = external_exports.object({ - /** User identifier */ - userId: external_exports.string().describe("User identifier"), - /** Current presence status */ - status: PresenceStatus2.describe("Current presence status"), - /** Last activity timestamp */ - lastSeen: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), - /** Custom metadata */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom presence data (e.g., current page, custom status)") -}); -var TransportProtocol2 = external_exports.enum([ - "websocket", - // Full-duplex, low latency communication - "sse", - // Server-Sent Events, unidirectional push - "polling" - // Short polling, best compatibility -]); -var RealtimeEventType2 = external_exports.enum([ - "record.created", - "record.updated", - "record.deleted", - "field.changed" -]); -var SubscriptionEventSchema2 = external_exports.object({ - type: RealtimeEventType2.describe("Type of event to subscribe to"), - object: external_exports.string().optional().describe("Object name to subscribe to"), - filters: external_exports.unknown().optional().describe("Filter conditions") -}); -var SubscriptionSchema2 = external_exports.object({ - id: external_exports.string().uuid().describe("Unique subscription identifier"), - events: external_exports.array(SubscriptionEventSchema2).describe("Array of events to subscribe to"), - transport: TransportProtocol2.describe("Transport protocol to use"), - channel: external_exports.string().optional().describe("Optional channel name for grouping subscriptions") -}); -var RealtimePresenceSchema2 = BasePresenceSchema2; -var RealtimeEventSchema2 = external_exports.object({ - id: external_exports.string().uuid().describe("Unique event identifier"), - type: external_exports.string().describe("Event type (e.g., record.created, record.updated)"), - object: external_exports.string().optional().describe("Object name the event relates to"), - action: RealtimeRecordAction2.optional().describe("Action performed"), - payload: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Event payload data"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when event occurred"), - userId: external_exports.string().optional().describe("User who triggered the event"), - sessionId: external_exports.string().optional().describe("Session identifier") -}); -var RealtimeConfigSchema2 = external_exports.object({ - /** Enable realtime sync */ - enabled: external_exports.boolean().default(true).describe("Enable realtime synchronization"), - /** Transport protocol */ - transport: TransportProtocol2.default("websocket").describe("Transport protocol"), - /** Default subscriptions */ - subscriptions: external_exports.array(SubscriptionSchema2).optional().describe("Default subscriptions") -}).passthrough(); -var WebSocketMessageType2 = external_exports.enum([ - "subscribe", - // Client subscribes to events - "unsubscribe", - // Client unsubscribes from events - "event", - // Server sends event to client - "ping", - // Keepalive ping - "pong", - // Keepalive pong response - "ack", - // Acknowledgment of message receipt - "error", - // Error message - "presence", - // Presence update (user status) - "cursor", - // Cursor position update (collaborative editing) - "edit" - // Document edit operation (collaborative editing) -]); -var FilterOperator2 = external_exports.enum([ - "eq", - // Equal - "ne", - // Not equal - "gt", - // Greater than - "gte", - // Greater than or equal - "lt", - // Less than - "lte", - // Less than or equal - "in", - // In array - "nin", - // Not in array - "contains", - // String contains - "startsWith", - // String starts with - "endsWith", - // String ends with - "exists", - // Field exists - "regex" - // Regex match -]); -var EventFilterCondition2 = external_exports.object({ - field: external_exports.string().describe('Field path to filter on (supports dot notation, e.g., "user.email")'), - operator: FilterOperator2.describe("Comparison operator"), - value: external_exports.unknown().optional().describe('Value to compare against (not needed for "exists" operator)') -}); -var EventFilterSchema2 = external_exports.object({ - conditions: external_exports.array(EventFilterCondition2).optional().describe("Array of filter conditions"), - and: external_exports.lazy(() => external_exports.array(EventFilterSchema2)).optional().describe("AND logical combination of filters"), - or: external_exports.lazy(() => external_exports.array(EventFilterSchema2)).optional().describe("OR logical combination of filters"), - not: external_exports.lazy(() => EventFilterSchema2).optional().describe("NOT logical negation of filter") -}); -var EventPatternSchema2 = external_exports.string().min(1).regex(/^[a-z*][a-z0-9_.*]*$/, { - message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., "record.*", "*.created", "user.login")' -}).describe('Event pattern (supports wildcards like "record.*" or "*.created")'); -var EventSubscriptionSchema2 = external_exports.object({ - subscriptionId: external_exports.string().uuid().describe("Unique subscription identifier"), - events: external_exports.array(EventPatternSchema2).describe('Event patterns to subscribe to (supports wildcards, e.g., "record.*", "user.created")'), - objects: external_exports.array(external_exports.string()).optional().describe('Object names to filter events by (e.g., ["account", "contact"])'), - filters: EventFilterSchema2.optional().describe("Advanced filter conditions for event payloads"), - channels: external_exports.array(external_exports.string()).optional().describe("Channel names for scoped subscriptions") -}); -var UnsubscribeRequestSchema2 = external_exports.object({ - subscriptionId: external_exports.string().uuid().describe("Subscription ID to unsubscribe from") -}); -var WebSocketPresenceStatus2 = PresenceStatus2; -var PresenceStateSchema2 = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - sessionId: external_exports.string().uuid().describe("Unique session identifier"), - status: WebSocketPresenceStatus2.describe("Current presence status"), - lastSeen: external_exports.string().datetime().describe("ISO 8601 datetime of last activity"), - currentLocation: external_exports.string().optional().describe("Current page/route user is viewing"), - device: external_exports.enum(["desktop", "mobile", "tablet", "other"]).optional().describe("Device type"), - customStatus: external_exports.string().optional().describe("Custom user status message"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom presence data") -}); -var PresenceUpdateSchema2 = external_exports.object({ - status: WebSocketPresenceStatus2.optional().describe("Updated presence status"), - currentLocation: external_exports.string().optional().describe("Updated current location"), - customStatus: external_exports.string().optional().describe("Updated custom status message"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Updated metadata") -}); -var CursorPositionSchema2 = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - documentId: external_exports.string().describe("Document identifier being edited"), - position: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Line number (0-indexed)"), - column: external_exports.number().int().nonnegative().describe("Column number (0-indexed)") - }).optional().describe("Cursor position in document"), - selection: external_exports.object({ - start: external_exports.object({ - line: external_exports.number().int().nonnegative(), - column: external_exports.number().int().nonnegative() - }), - end: external_exports.object({ - line: external_exports.number().int().nonnegative(), - column: external_exports.number().int().nonnegative() - }) - }).optional().describe("Selection range (if text is selected)"), - color: external_exports.string().optional().describe("Cursor color for visual representation"), - userName: external_exports.string().optional().describe("Display name of user"), - lastUpdate: external_exports.string().datetime().describe("ISO 8601 datetime of last cursor update") -}); -var EditOperationType2 = external_exports.enum([ - "insert", - // Insert text at position - "delete", - // Delete text from range - "replace" - // Replace text in range -]); -var EditOperationSchema2 = external_exports.object({ - operationId: external_exports.string().uuid().describe("Unique operation identifier"), - documentId: external_exports.string().describe("Document identifier"), - userId: external_exports.string().describe("User who performed the edit"), - sessionId: external_exports.string().uuid().describe("Session identifier"), - type: EditOperationType2.describe("Type of edit operation"), - position: external_exports.object({ - line: external_exports.number().int().nonnegative().describe("Line number (0-indexed)"), - column: external_exports.number().int().nonnegative().describe("Column number (0-indexed)") - }).describe("Starting position of the operation"), - endPosition: external_exports.object({ - line: external_exports.number().int().nonnegative(), - column: external_exports.number().int().nonnegative() - }).optional().describe("Ending position (for delete/replace operations)"), - content: external_exports.string().optional().describe("Content to insert/replace"), - version: external_exports.number().int().nonnegative().describe("Document version before this operation"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when operation was created"), - baseOperationId: external_exports.string().uuid().optional().describe("Previous operation ID this builds upon (for OT)") -}); -var DocumentStateSchema2 = external_exports.object({ - documentId: external_exports.string().describe("Document identifier"), - version: external_exports.number().int().nonnegative().describe("Current document version"), - content: external_exports.string().describe("Current document content"), - lastModified: external_exports.string().datetime().describe("ISO 8601 datetime of last modification"), - activeSessions: external_exports.array(external_exports.string().uuid()).describe("Active editing session IDs"), - checksum: external_exports.string().optional().describe("Content checksum for integrity verification") -}); -var BaseWebSocketMessage2 = external_exports.object({ - messageId: external_exports.string().uuid().describe("Unique message identifier"), - type: WebSocketMessageType2.describe("Message type"), - timestamp: external_exports.string().datetime().describe("ISO 8601 datetime when message was sent") -}); -var SubscribeMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("subscribe"), - subscription: EventSubscriptionSchema2.describe("Subscription configuration") -}); -var UnsubscribeMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("unsubscribe"), - request: UnsubscribeRequestSchema2.describe("Unsubscribe request") -}); -var EventMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("event"), - subscriptionId: external_exports.string().uuid().describe("Subscription ID this event belongs to"), - eventName: EventNameSchema4.describe("Event name"), - object: external_exports.string().optional().describe("Object name the event relates to"), - payload: external_exports.unknown().describe("Event payload data"), - userId: external_exports.string().optional().describe("User who triggered the event") -}); -var PresenceMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("presence"), - presence: PresenceStateSchema2.describe("Presence state") -}); -var CursorMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("cursor"), - cursor: CursorPositionSchema2.describe("Cursor position") -}); -var EditMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("edit"), - operation: EditOperationSchema2.describe("Edit operation") -}); -var AckMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("ack"), - ackMessageId: external_exports.string().uuid().describe("ID of the message being acknowledged"), - success: external_exports.boolean().describe("Whether the operation was successful"), - error: external_exports.string().optional().describe("Error message if operation failed") -}); -var ErrorMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("error"), - code: external_exports.string().describe("Error code"), - message: external_exports.string().describe("Error message"), - details: external_exports.unknown().optional().describe("Additional error details") -}); -var PingMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("ping") -}); -var PongMessageSchema2 = BaseWebSocketMessage2.extend({ - type: external_exports.literal("pong"), - pingMessageId: external_exports.string().uuid().optional().describe("ID of ping message being responded to") -}); -var WebSocketMessageSchema2 = external_exports.discriminatedUnion("type", [ - SubscribeMessageSchema2, - UnsubscribeMessageSchema2, - EventMessageSchema2, - PresenceMessageSchema2, - CursorMessageSchema2, - EditMessageSchema2, - AckMessageSchema2, - ErrorMessageSchema2, - PingMessageSchema2, - PongMessageSchema2 -]); -var WebSocketConfigSchema2 = external_exports.object({ - url: external_exports.string().url().describe("WebSocket server URL"), - protocols: external_exports.array(external_exports.string()).optional().describe("WebSocket sub-protocols"), - reconnect: external_exports.boolean().optional().default(true).describe("Enable automatic reconnection"), - reconnectInterval: external_exports.number().int().positive().optional().default(1e3).describe("Reconnection interval in milliseconds"), - maxReconnectAttempts: external_exports.number().int().positive().optional().default(5).describe("Maximum reconnection attempts"), - pingInterval: external_exports.number().int().positive().optional().default(3e4).describe("Ping interval in milliseconds"), - timeout: external_exports.number().int().positive().optional().default(5e3).describe("Message timeout in milliseconds"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers for WebSocket handshake") -}); -var WebSocketEventSchema2 = external_exports.object({ - type: external_exports.enum([ - "subscribe", - // Client subscribes to channel - "unsubscribe", - // Client unsubscribes from channel - "data-change", - // Data modification event - "presence-update", - // User presence change - "cursor-update", - // Cursor position change (collaborative editing) - "error" - // Error message - ]).describe("Event type"), - channel: external_exports.string().describe('Channel identifier (e.g., "record.account.123", "user.456")'), - payload: external_exports.unknown().describe("Event payload data"), - timestamp: external_exports.number().describe("Unix timestamp in milliseconds") -}); -var SimplePresenceStateSchema2 = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - userName: external_exports.string().describe("User display name"), - status: external_exports.enum(["online", "away", "offline"]).describe("User presence status"), - lastSeen: external_exports.number().describe("Unix timestamp of last activity in milliseconds"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional presence metadata (e.g., current page, custom status)") -}); -var SimpleCursorPositionSchema2 = external_exports.object({ - userId: external_exports.string().describe("User identifier"), - recordId: external_exports.string().describe("Record identifier being edited"), - fieldName: external_exports.string().describe("Field name being edited"), - position: external_exports.number().describe("Cursor position (character offset from start)"), - selection: external_exports.object({ - start: external_exports.number().describe("Selection start position"), - end: external_exports.number().describe("Selection end position") - }).optional().describe("Text selection range (if text is selected)") -}); -var WebSocketServerConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable WebSocket server"), - path: external_exports.string().default("/ws").describe("WebSocket endpoint path"), - heartbeatInterval: external_exports.number().default(3e4).describe("Heartbeat interval in milliseconds"), - reconnectAttempts: external_exports.number().default(5).describe("Maximum reconnection attempts for clients"), - presence: external_exports.boolean().default(false).describe("Enable presence tracking"), - cursorSharing: external_exports.boolean().default(false).describe("Enable collaborative cursor sharing") -}); -var RouteCategory2 = external_exports.enum([ - "system", - // Health, Metrics, Info (No Auth usually) - "api", - // Business Logic API (Auth required) - "auth", - // Login/Callback endpoints - "static", - // Asset serving - "webhook", - // External callbacks - "plugin" - // Plugin extensions -]); -var RouteDefinitionSchema2 = external_exports.object({ - /** - * HTTP Method - */ - method: HttpMethod5, - /** - * URL Path Pattern (supports parameters like /user/:id) - */ - path: external_exports.string().describe("URL Path pattern"), - /** - * Route Type/Category - */ - category: RouteCategory2.default("api"), - /** - * Handler Identifier - * References an internal function or plugin action ID. - */ - handler: external_exports.string().describe("Unique handler identifier"), - /** - * Route specific metadata - */ - summary: external_exports.string().optional().describe("OpenAPI summary"), - description: external_exports.string().optional().describe("OpenAPI description"), - /** - * Security constraints - */ - public: external_exports.boolean().default(false).describe("Is publicly accessible"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - /** - * Performance hints - */ - timeout: external_exports.number().int().optional().describe("Execution timeout in ms"), - rateLimit: external_exports.string().optional().describe("Rate limit policy name") -}); -var RouterConfigSchema2 = external_exports.object({ - /** - * URL Prefix for all kernel routes - */ - basePath: external_exports.string().default("/api").describe("Global API prefix"), - /** - * Standard Protocol Mounts (Relative to basePath) - */ - mounts: external_exports.object({ - data: external_exports.string().default("/data").describe("Data Protocol (CRUD)"), - metadata: external_exports.string().default("/meta").describe("Metadata Protocol (Schemas)"), - auth: external_exports.string().default("/auth").describe("Auth Protocol"), - automation: external_exports.string().default("/automation").describe("Automation Protocol"), - storage: external_exports.string().default("/storage").describe("Storage Protocol"), - analytics: external_exports.string().default("/analytics").describe("Analytics Protocol"), - graphql: external_exports.string().default("/graphql").describe("GraphQL Endpoint"), - ui: external_exports.string().default("/ui").describe("UI Metadata Protocol (Views, Layouts)"), - workflow: external_exports.string().default("/workflow").describe("Workflow Engine Protocol"), - realtime: external_exports.string().default("/realtime").describe("Realtime/WebSocket Protocol"), - notifications: external_exports.string().default("/notifications").describe("Notification Protocol"), - ai: external_exports.string().default("/ai").describe("AI Engine Protocol (NLQ, Chat, Suggest)"), - i18n: external_exports.string().default("/i18n").describe("Internationalization Protocol"), - packages: external_exports.string().default("/packages").describe("Package Management Protocol") - }).default({ - data: "/data", - metadata: "/meta", - auth: "/auth", - automation: "/automation", - storage: "/storage", - analytics: "/analytics", - graphql: "/graphql", - ui: "/ui", - workflow: "/workflow", - realtime: "/realtime", - notifications: "/notifications", - ai: "/ai", - i18n: "/i18n", - packages: "/packages" - }), - // Defaults match standardized spec - /** - * Cross-Origin Resource Sharing - */ - cors: CorsConfigSchema4.optional(), - /** - * Static asset mounts - */ - staticMounts: external_exports.array(StaticMountSchema4).optional() -}); -var ODataQuerySchema2 = external_exports.object({ - /** - * $select - Select specific fields to return - * - * Comma-separated list of field names to include in the response. - * Reduces payload size and improves performance. - * - * @example "name,email,phone" - * @example "id,customer/name" - With navigation path - */ - $select: external_exports.union([ - external_exports.string(), - // "name,email" - external_exports.array(external_exports.string()) - // ["name", "email"] - ]).optional().describe("Fields to select"), - /** - * $filter - Filter results with conditions - * - * OData filter expression using comparison operators, logical operators, - * and functions. - * - * Comparison: eq, ne, lt, le, gt, ge - * Logical: and, or, not - * Functions: contains, startswith, endswith, length, indexof, substring, etc. - * - * @example "age gt 18" - * @example "country eq 'US' and revenue gt 100000" - * @example "contains(name, 'Smith')" - * @example "startswith(email, 'admin') and isActive eq true" - */ - $filter: external_exports.string().optional().describe("Filter expression (OData filter syntax)"), - /** - * $orderby - Sort results - * - * Comma-separated list of fields with optional asc/desc. - * Default is ascending. - * - * @example "name" - * @example "revenue desc" - * @example "country asc, revenue desc" - */ - $orderby: external_exports.union([ - external_exports.string(), - // "name desc" - external_exports.array(external_exports.string()) - // ["name desc", "email asc"] - ]).optional().describe("Sort order"), - /** - * $top - Limit number of results - * - * Maximum number of results to return. - * Equivalent to SQL LIMIT or FETCH FIRST. - * - * @example 10 - * @example 100 - */ - $top: external_exports.number().int().min(0).optional().describe("Max results to return"), - /** - * $skip - Skip results for pagination - * - * Number of results to skip before returning results. - * Equivalent to SQL OFFSET. - * - * @example 20 - * @example 100 - */ - $skip: external_exports.number().int().min(0).optional().describe("Results to skip"), - /** - * $expand - Include related entities (lookup/master_detail fields) - * - * Comma-separated list of navigation properties (relationship field names) to expand. - * Loads related data in the same request by resolving lookup and master_detail fields. - * The engine replaces foreign key IDs with full related objects via batch $in queries. - * Supports nested expand via OData parenthetical syntax. - * - * Behavior: - * - Only fields with `type: 'lookup'` or `type: 'master_detail'` and a valid `reference` are expanded. - * - Fields without a schema or reference definition are silently skipped (ID returned as-is). - * - Maximum expand depth defaults to 3 (configurable via QueryAdapterConfig). - * - * @example "orders" - * @example "customer,products" - * @example "orders($select=id,total)" - With nested query options - */ - $expand: external_exports.union([ - external_exports.string(), - // "orders" - external_exports.array(external_exports.string()) - // ["orders", "customer"] - ]).optional().describe("Navigation properties to expand (lookup/master_detail fields)"), - /** - * $count - Include total count - * - * When true, includes totalResults count in response. - * Useful for pagination UI. - * - * @example true - */ - $count: external_exports.boolean().optional().describe("Include total count"), - /** - * $search - Full-text search - * - * Free-text search expression. - * Search implementation is service-specific. - * - * @example "John Smith" - * @example "urgent AND support" - */ - $search: external_exports.string().optional().describe("Search expression"), - /** - * $format - Response format - * - * Preferred response format. - * - * @example "json" - * @example "xml" - */ - $format: external_exports.enum(["json", "xml", "atom"]).optional().describe("Response format"), - /** - * $apply - Data aggregation - * - * Aggregation transformations (groupby, aggregate, etc.) - * Part of OData aggregation extension. - * - * @example "groupby((country),aggregate(revenue with sum as totalRevenue))" - */ - $apply: external_exports.string().optional().describe("Aggregation expression") -}); -var ODataFilterOperatorSchema2 = external_exports.enum([ - // Comparison Operators - "eq", - // Equal to - "ne", - // Not equal to - "lt", - // Less than - "le", - // Less than or equal to - "gt", - // Greater than - "ge", - // Greater than or equal to - // Logical Operators - "and", - // Logical AND - "or", - // Logical OR - "not", - // Logical NOT - // Grouping - "(", - // Left parenthesis - ")", - // Right parenthesis - // Other - "in", - // Value in list - "has" - // Has flag (for enum flags) -]); -var ODataFilterFunctionSchema2 = external_exports.enum([ - // String Functions - "contains", - // contains(field, 'value') - "startswith", - // startswith(field, 'value') - "endswith", - // endswith(field, 'value') - "length", - // length(field) - "indexof", - // indexof(field, 'substring') - "substring", - // substring(field, start, length) - "tolower", - // tolower(field) - "toupper", - // toupper(field) - "trim", - // trim(field) - "concat", - // concat(field1, field2) - // Date/Time Functions - "year", - // year(dateField) - "month", - // month(dateField) - "day", - // day(dateField) - "hour", - // hour(datetimeField) - "minute", - // minute(datetimeField) - "second", - // second(datetimeField) - "date", - // date(datetimeField) - "time", - // time(datetimeField) - "now", - // now() - "maxdatetime", - // maxdatetime() - "mindatetime", - // mindatetime() - // Math Functions - "round", - // round(numField) - "floor", - // floor(numField) - "ceiling", - // ceiling(numField) - // Type Functions - "cast", - // cast(field, 'Edm.String') - "isof", - // isof(field, 'Type') - // Collection Functions - "any", - // collection/any(d:d/prop eq value) - "all" - // collection/all(d:d/prop eq value) -]); -var ODataResponseSchema2 = external_exports.object({ - /** - * OData context URL - * Describes the payload structure - */ - "@odata.context": external_exports.string().url().optional().describe("Metadata context URL"), - /** - * Total count (when $count=true) - */ - "@odata.count": external_exports.number().int().optional().describe("Total results count"), - /** - * Next link for pagination - */ - "@odata.nextLink": external_exports.string().url().optional().describe("Next page URL"), - /** - * Result array - */ - value: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Results array") -}); -var ODataErrorSchema2 = external_exports.object({ - error: external_exports.object({ - /** - * Error code - */ - code: external_exports.string().describe("Error code"), - /** - * Error message - */ - message: external_exports.string().describe("Error message"), - /** - * Target of the error (field name, etc.) - */ - target: external_exports.string().optional().describe("Error target"), - /** - * Additional error details - */ - details: external_exports.array(external_exports.object({ - code: external_exports.string(), - message: external_exports.string(), - target: external_exports.string().optional() - })).optional().describe("Error details"), - /** - * Inner error for debugging - */ - innererror: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Inner error details") - }) -}); -var ODataMetadataSchema2 = external_exports.object({ - /** - * Service namespace - */ - namespace: external_exports.string().describe("Service namespace"), - /** - * Entity types to expose - */ - entityTypes: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Entity type name"), - key: external_exports.array(external_exports.string()).describe("Key fields"), - properties: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string().describe("OData type (Edm.String, Edm.Int32, etc.)"), - nullable: external_exports.boolean().default(true) - })), - navigationProperties: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string(), - partner: external_exports.string().optional() - })).optional() - })).describe("Entity types"), - /** - * Entity sets - */ - entitySets: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Entity set name"), - entityType: external_exports.string().describe("Entity type") - })).describe("Entity sets") -}); -var OData = { - /** - * Build OData query URL - */ - buildUrl: (baseUrl, query) => { - const params = new URLSearchParams(); - if (query.$select) { - params.append("$select", Array.isArray(query.$select) ? query.$select.join(",") : query.$select); - } - if (query.$filter) { - params.append("$filter", query.$filter); - } - if (query.$orderby) { - params.append("$orderby", Array.isArray(query.$orderby) ? query.$orderby.join(",") : query.$orderby); - } - if (query.$top !== void 0) { - params.append("$top", query.$top.toString()); - } - if (query.$skip !== void 0) { - params.append("$skip", query.$skip.toString()); - } - if (query.$expand) { - params.append("$expand", Array.isArray(query.$expand) ? query.$expand.join(",") : query.$expand); - } - if (query.$count !== void 0) { - params.append("$count", query.$count.toString()); - } - if (query.$search) { - params.append("$search", query.$search); - } - if (query.$format) { - params.append("$format", query.$format); - } - if (query.$apply) { - params.append("$apply", query.$apply); - } - const queryString = params.toString(); - return queryString ? `${baseUrl}?${queryString}` : baseUrl; - }, - /** - * Create a simple filter expression - */ - filter: { - eq: (field, value) => `${field} eq ${typeof value === "string" ? `'${value}'` : value}`, - ne: (field, value) => `${field} ne ${typeof value === "string" ? `'${value}'` : value}`, - gt: (field, value) => `${field} gt ${value}`, - lt: (field, value) => `${field} lt ${value}`, - contains: (field, value) => `contains(${field}, '${value}')`, - and: (...expressions) => expressions.join(" and "), - or: (...expressions) => expressions.join(" or ") - } -}; -var ODataConfigSchema2 = external_exports.object({ - /** Enable OData endpoint */ - enabled: external_exports.boolean().default(true).describe("Enable OData API"), - /** OData endpoint path */ - path: external_exports.string().default("/odata").describe("OData endpoint path"), - /** Metadata configuration */ - metadata: ODataMetadataSchema2.optional().describe("OData metadata configuration") -}).passthrough(); -var GraphQLScalarType2 = external_exports.enum([ - // Built-in GraphQL Scalars - "ID", - "String", - "Int", - "Float", - "Boolean", - // Extended Scalars (common custom types) - "DateTime", - "Date", - "Time", - "JSON", - "JSONObject", - "Upload", - "URL", - "Email", - "PhoneNumber", - "Currency", - "Decimal", - "BigInt", - "Long", - "UUID", - "Base64", - "Void" -]); -var GraphQLTypeConfigSchema2 = external_exports.object({ - /** Type name in GraphQL schema */ - name: external_exports.string().describe("GraphQL type name (PascalCase recommended)"), - /** Source Object name */ - object: external_exports.string().describe("Source ObjectQL object name"), - /** Description for GraphQL schema documentation */ - description: external_exports.string().optional().describe("Type description"), - /** Fields to include/exclude */ - fields: external_exports.object({ - /** Include only these fields (allow list) */ - include: external_exports.array(external_exports.string()).optional().describe("Fields to include"), - /** Exclude these fields (deny list) */ - exclude: external_exports.array(external_exports.string()).optional().describe("Fields to exclude (e.g., sensitive fields)"), - /** Custom field mappings */ - mappings: external_exports.record(external_exports.string(), external_exports.object({ - graphqlName: external_exports.string().optional().describe("Custom GraphQL field name"), - graphqlType: external_exports.string().optional().describe("Override GraphQL type"), - description: external_exports.string().optional().describe("Field description"), - deprecationReason: external_exports.string().optional().describe("Why field is deprecated"), - nullable: external_exports.boolean().optional().describe("Override nullable") - })).optional().describe("Field-level customizations") - }).optional().describe("Field configuration"), - /** Interfaces this type implements */ - interfaces: external_exports.array(external_exports.string()).optional().describe("GraphQL interface names"), - /** Whether this is an interface definition */ - isInterface: external_exports.boolean().optional().default(false).describe("Define as GraphQL interface"), - /** Custom directives */ - directives: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Directive name"), - args: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Directive arguments") - })).optional().describe("GraphQL directives") -}); -var GraphQLQueryConfigSchema2 = external_exports.object({ - /** Query name */ - name: external_exports.string().describe("Query field name (camelCase recommended)"), - /** Source Object */ - object: external_exports.string().describe("Source ObjectQL object name"), - /** Query type: single record or list */ - type: external_exports.enum(["get", "list", "search"]).describe("Query type"), - /** Description */ - description: external_exports.string().optional().describe("Query description"), - /** Input arguments */ - args: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.string().describe('GraphQL type (e.g., "ID!", "String", "Int")'), - description: external_exports.string().optional().describe("Argument description"), - defaultValue: external_exports.unknown().optional().describe("Default value") - })).optional().describe("Query arguments"), - /** Filtering configuration */ - filtering: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Allow filtering"), - fields: external_exports.array(external_exports.string()).optional().describe("Filterable fields"), - operators: external_exports.array(external_exports.enum([ - "eq", - "ne", - "gt", - "gte", - "lt", - "lte", - "in", - "notIn", - "contains", - "startsWith", - "endsWith", - "isNull", - "isNotNull" - ])).optional().describe("Allowed filter operators") - }).optional().describe("Filtering capabilities"), - /** Sorting configuration */ - sorting: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Allow sorting"), - fields: external_exports.array(external_exports.string()).optional().describe("Sortable fields"), - defaultSort: external_exports.object({ - field: external_exports.string(), - direction: external_exports.enum(["ASC", "DESC"]) - }).optional().describe("Default sort order") - }).optional().describe("Sorting capabilities"), - /** Pagination configuration */ - pagination: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable pagination"), - type: external_exports.enum(["offset", "cursor", "relay"]).default("offset").describe("Pagination style"), - defaultLimit: external_exports.number().int().min(1).default(20).describe("Default page size"), - maxLimit: external_exports.number().int().min(1).default(100).describe("Maximum page size"), - cursors: external_exports.object({ - field: external_exports.string().default("id").describe("Field to use for cursor pagination") - }).optional() - }).optional().describe("Pagination configuration"), - /** Field selection */ - fields: external_exports.object({ - /** Always include these fields */ - required: external_exports.array(external_exports.string()).optional().describe("Required fields (always returned)"), - /** Allow selecting these fields */ - selectable: external_exports.array(external_exports.string()).optional().describe("Selectable fields") - }).optional().describe("Field selection configuration"), - /** Authorization */ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - /** Caching */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable caching"), - ttl: external_exports.number().int().min(0).optional().describe("Cache TTL in seconds"), - key: external_exports.string().optional().describe("Cache key template") - }).optional().describe("Query caching") -}); -var GraphQLMutationConfigSchema2 = external_exports.object({ - /** Mutation name */ - name: external_exports.string().describe("Mutation field name (camelCase recommended)"), - /** Source Object */ - object: external_exports.string().describe("Source ObjectQL object name"), - /** Mutation type */ - type: external_exports.enum(["create", "update", "delete", "upsert", "custom"]).describe("Mutation type"), - /** Description */ - description: external_exports.string().optional().describe("Mutation description"), - /** Input type configuration */ - input: external_exports.object({ - /** Input type name */ - typeName: external_exports.string().optional().describe("Custom input type name"), - /** Fields to include in input */ - fields: external_exports.object({ - include: external_exports.array(external_exports.string()).optional().describe("Fields to include"), - exclude: external_exports.array(external_exports.string()).optional().describe("Fields to exclude"), - required: external_exports.array(external_exports.string()).optional().describe("Required input fields") - }).optional().describe("Input field configuration"), - /** Validation */ - validation: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable input validation"), - rules: external_exports.array(external_exports.string()).optional().describe("Custom validation rules") - }).optional().describe("Input validation") - }).optional().describe("Input configuration"), - /** Return type configuration */ - output: external_exports.object({ - /** Type of output */ - type: external_exports.enum(["object", "payload", "boolean", "custom"]).default("object").describe("Output type"), - /** Include success/error envelope */ - includeEnvelope: external_exports.boolean().optional().default(false).describe("Wrap in success/error payload"), - /** Custom output type */ - customType: external_exports.string().optional().describe("Custom output type name") - }).optional().describe("Output configuration"), - /** Transaction handling */ - transaction: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Use database transaction"), - isolationLevel: external_exports.enum(["read_uncommitted", "read_committed", "repeatable_read", "serializable"]).optional().describe("Transaction isolation level") - }).optional().describe("Transaction configuration"), - /** Authorization */ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - /** Hooks */ - hooks: external_exports.object({ - before: external_exports.array(external_exports.string()).optional().describe("Pre-mutation hooks"), - after: external_exports.array(external_exports.string()).optional().describe("Post-mutation hooks") - }).optional().describe("Lifecycle hooks") -}); -var GraphQLSubscriptionConfigSchema2 = external_exports.object({ - /** Subscription name */ - name: external_exports.string().describe("Subscription field name (camelCase recommended)"), - /** Source Object */ - object: external_exports.string().describe("Source ObjectQL object name"), - /** Subscription trigger events */ - events: external_exports.array(external_exports.enum(["created", "updated", "deleted", "custom"])).describe("Events to subscribe to"), - /** Description */ - description: external_exports.string().optional().describe("Subscription description"), - /** Filtering */ - filter: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Allow filtering subscriptions"), - fields: external_exports.array(external_exports.string()).optional().describe("Filterable fields") - }).optional().describe("Subscription filtering"), - /** Payload configuration */ - payload: external_exports.object({ - /** Include the modified entity */ - includeEntity: external_exports.boolean().default(true).describe("Include entity in payload"), - /** Include previous values (for updates) */ - includePreviousValues: external_exports.boolean().optional().default(false).describe("Include previous field values"), - /** Include mutation metadata */ - includeMeta: external_exports.boolean().optional().default(true).describe("Include metadata (timestamp, user, etc.)") - }).optional().describe("Payload configuration"), - /** Authorization */ - authRequired: external_exports.boolean().default(true).describe("Require authentication"), - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions"), - /** Rate limiting for subscriptions */ - rateLimit: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable rate limiting"), - maxSubscriptionsPerUser: external_exports.number().int().min(1).default(10).describe("Max concurrent subscriptions per user"), - throttleMs: external_exports.number().int().min(0).optional().describe("Throttle interval in milliseconds") - }).optional().describe("Subscription rate limiting") -}); -var GraphQLResolverConfigSchema2 = external_exports.object({ - /** Field path (e.g., "Query.users", "Mutation.createUser") */ - path: external_exports.string().describe("Resolver path (Type.field)"), - /** Resolver implementation type */ - type: external_exports.enum(["datasource", "computed", "script", "proxy"]).describe("Resolver implementation type"), - /** Implementation details */ - implementation: external_exports.object({ - /** For datasource type */ - datasource: external_exports.string().optional().describe("Datasource ID"), - query: external_exports.string().optional().describe("Query/SQL to execute"), - /** For computed type */ - expression: external_exports.string().optional().describe("Computation expression"), - dependencies: external_exports.array(external_exports.string()).optional().describe("Dependent fields"), - /** For script type */ - script: external_exports.string().optional().describe("Script ID or inline code"), - /** For proxy type */ - url: external_exports.string().optional().describe("Proxy URL"), - method: external_exports.enum(["GET", "POST", "PUT", "DELETE"]).optional().describe("HTTP method") - }).optional().describe("Implementation configuration"), - /** Caching */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable resolver caching"), - ttl: external_exports.number().int().min(0).optional().describe("Cache TTL in seconds"), - keyArgs: external_exports.array(external_exports.string()).optional().describe("Arguments to include in cache key") - }).optional().describe("Resolver caching") -}); -var GraphQLDataLoaderConfigSchema2 = external_exports.object({ - /** Loader name */ - name: external_exports.string().describe("DataLoader name"), - /** Source Object or datasource */ - source: external_exports.string().describe("Source object or datasource"), - /** Batch function configuration */ - batchFunction: external_exports.object({ - /** Type of batch operation */ - type: external_exports.enum(["findByIds", "query", "script", "custom"]).describe("Batch function type"), - /** For findByIds */ - keyField: external_exports.string().optional().describe('Field to batch on (e.g., "id")'), - /** For query */ - query: external_exports.string().optional().describe("Query template"), - /** For script */ - script: external_exports.string().optional().describe("Script ID"), - /** Maximum batch size */ - maxBatchSize: external_exports.number().int().min(1).optional().default(100).describe("Maximum batch size") - }).describe("Batch function configuration"), - /** Caching */ - cache: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable per-request caching"), - /** Cache key function */ - keyFn: external_exports.string().optional().describe("Custom cache key function") - }).optional().describe("DataLoader caching"), - /** Options */ - options: external_exports.object({ - /** Batch multiple requests in single tick */ - batch: external_exports.boolean().default(true).describe("Enable batching"), - /** Cache loaded values */ - cache: external_exports.boolean().default(true).describe("Enable caching"), - /** Maximum cache size */ - maxCacheSize: external_exports.number().int().min(0).optional().describe("Max cache entries") - }).optional().describe("DataLoader options") -}); -var GraphQLDirectiveLocation2 = external_exports.enum([ - // Executable Directive Locations - "QUERY", - "MUTATION", - "SUBSCRIPTION", - "FIELD", - "FRAGMENT_DEFINITION", - "FRAGMENT_SPREAD", - "INLINE_FRAGMENT", - "VARIABLE_DEFINITION", - // Type System Directive Locations - "SCHEMA", - "SCALAR", - "OBJECT", - "FIELD_DEFINITION", - "ARGUMENT_DEFINITION", - "INTERFACE", - "UNION", - "ENUM", - "ENUM_VALUE", - "INPUT_OBJECT", - "INPUT_FIELD_DEFINITION" -]); -var GraphQLDirectiveConfigSchema2 = external_exports.object({ - /** Directive name */ - name: external_exports.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe("Directive name (camelCase)"), - /** Description */ - description: external_exports.string().optional().describe("Directive description"), - /** Where directive can be used */ - locations: external_exports.array(GraphQLDirectiveLocation2).describe("Directive locations"), - /** Arguments */ - args: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.string().describe("Argument type"), - description: external_exports.string().optional().describe("Argument description"), - defaultValue: external_exports.unknown().optional().describe("Default value") - })).optional().describe("Directive arguments"), - /** Is repeatable */ - repeatable: external_exports.boolean().optional().default(false).describe("Can be applied multiple times"), - /** Implementation */ - implementation: external_exports.object({ - /** Directive behavior type */ - type: external_exports.enum(["auth", "validation", "transform", "cache", "deprecation", "custom"]).describe("Directive type"), - /** Handler function */ - handler: external_exports.string().optional().describe("Handler function name or script") - }).optional().describe("Directive implementation") -}); -var GraphQLQueryDepthLimitSchema2 = external_exports.object({ - /** Enable depth limiting */ - enabled: external_exports.boolean().default(true).describe("Enable query depth limiting"), - /** Maximum allowed depth */ - maxDepth: external_exports.number().int().min(1).default(10).describe("Maximum query depth"), - /** Fields to ignore in depth calculation */ - ignoreFields: external_exports.array(external_exports.string()).optional().describe("Fields excluded from depth calculation"), - /** Callback on depth exceeded */ - onDepthExceeded: external_exports.enum(["reject", "log", "warn"]).default("reject").describe("Action when depth exceeded"), - /** Custom error message */ - errorMessage: external_exports.string().optional().describe("Custom error message for depth violations") -}); -var GraphQLQueryComplexitySchema2 = external_exports.object({ - /** Enable complexity limiting */ - enabled: external_exports.boolean().default(true).describe("Enable query complexity limiting"), - /** Maximum allowed complexity score */ - maxComplexity: external_exports.number().int().min(1).default(1e3).describe("Maximum query complexity"), - /** Default field complexity */ - defaultFieldComplexity: external_exports.number().int().min(0).default(1).describe("Default complexity per field"), - /** Field-specific complexity scores */ - fieldComplexity: external_exports.record(external_exports.string(), external_exports.union([ - external_exports.number().int().min(0), - external_exports.object({ - /** Base complexity */ - base: external_exports.number().int().min(0).describe("Base complexity"), - /** Multiplier based on arguments */ - multiplier: external_exports.string().optional().describe('Argument multiplier (e.g., "limit")'), - /** Custom complexity calculation */ - calculator: external_exports.string().optional().describe("Custom calculator function") - }) - ])).optional().describe("Per-field complexity configuration"), - /** List multiplier */ - listMultiplier: external_exports.number().min(0).default(10).describe("Multiplier for list fields"), - /** Callback on complexity exceeded */ - onComplexityExceeded: external_exports.enum(["reject", "log", "warn"]).default("reject").describe("Action when complexity exceeded"), - /** Custom error message */ - errorMessage: external_exports.string().optional().describe("Custom error message for complexity violations") -}); -var GraphQLRateLimitSchema2 = external_exports.object({ - /** Enable rate limiting */ - enabled: external_exports.boolean().default(true).describe("Enable rate limiting"), - /** Rate limit strategy */ - strategy: external_exports.enum(["token_bucket", "fixed_window", "sliding_window", "cost_based"]).default("token_bucket").describe("Rate limiting strategy"), - /** Global rate limits */ - global: external_exports.object({ - /** Requests per time window */ - maxRequests: external_exports.number().int().min(1).default(1e3).describe("Maximum requests per window"), - /** Time window in milliseconds */ - windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds") - }).optional().describe("Global rate limits"), - /** Per-user rate limits */ - perUser: external_exports.object({ - /** Requests per time window */ - maxRequests: external_exports.number().int().min(1).default(100).describe("Maximum requests per user per window"), - /** Time window in milliseconds */ - windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds") - }).optional().describe("Per-user rate limits"), - /** Cost-based rate limiting */ - costBased: external_exports.object({ - /** Enable cost-based limiting */ - enabled: external_exports.boolean().default(false).describe("Enable cost-based rate limiting"), - /** Maximum cost per time window */ - maxCost: external_exports.number().int().min(1).default(1e4).describe("Maximum cost per window"), - /** Time window in milliseconds */ - windowMs: external_exports.number().int().min(1e3).default(6e4).describe("Time window in milliseconds"), - /** Use complexity as cost */ - useComplexityAsCost: external_exports.boolean().default(true).describe("Use query complexity as cost") - }).optional().describe("Cost-based rate limiting"), - /** Operation-specific limits */ - operations: external_exports.record(external_exports.string(), external_exports.object({ - maxRequests: external_exports.number().int().min(1).describe("Max requests for this operation"), - windowMs: external_exports.number().int().min(1e3).describe("Time window") - })).optional().describe("Per-operation rate limits"), - /** Callback on limit exceeded */ - onLimitExceeded: external_exports.enum(["reject", "queue", "log"]).default("reject").describe("Action when rate limit exceeded"), - /** Custom error message */ - errorMessage: external_exports.string().optional().describe("Custom error message for rate limit violations"), - /** Headers to include in response */ - includeHeaders: external_exports.boolean().default(true).describe("Include rate limit headers in response") -}); -var GraphQLPersistedQuerySchema2 = external_exports.object({ - /** Enable persisted queries */ - enabled: external_exports.boolean().default(false).describe("Enable persisted queries"), - /** Enforcement mode */ - mode: external_exports.enum(["optional", "required"]).default("optional").describe("Persisted query mode (optional: allow both, required: only persisted)"), - /** Query store configuration */ - store: external_exports.object({ - /** Store type */ - type: external_exports.enum(["memory", "redis", "database", "file"]).default("memory").describe("Query store type"), - /** Store connection string */ - connection: external_exports.string().optional().describe("Store connection string or path"), - /** TTL for cached queries */ - ttl: external_exports.number().int().min(0).optional().describe("TTL in seconds for stored queries") - }).optional().describe("Query store configuration"), - /** Automatic Persisted Queries (APQ) */ - apq: external_exports.object({ - /** Enable APQ */ - enabled: external_exports.boolean().default(true).describe("Enable Automatic Persisted Queries"), - /** Hash algorithm */ - hashAlgorithm: external_exports.enum(["sha256", "sha1", "md5"]).default("sha256").describe("Hash algorithm for query IDs"), - /** Cache control */ - cache: external_exports.object({ - /** Cache TTL */ - ttl: external_exports.number().int().min(0).default(3600).describe("Cache TTL in seconds"), - /** Max cache size */ - maxSize: external_exports.number().int().min(1).optional().describe("Maximum number of cached queries") - }).optional().describe("APQ cache configuration") - }).optional().describe("Automatic Persisted Queries configuration"), - /** Query allow list */ - allowlist: external_exports.object({ - /** Enable allow list mode */ - enabled: external_exports.boolean().default(false).describe("Enable query allow list (reject queries not in list)"), - /** Allowed query IDs */ - queries: external_exports.array(external_exports.object({ - id: external_exports.string().describe("Query ID or hash"), - operation: external_exports.string().optional().describe("Operation name"), - query: external_exports.string().optional().describe("Query string") - })).optional().describe("Allowed queries"), - /** External allow list source */ - source: external_exports.string().optional().describe("External allow list source (file path or URL)") - }).optional().describe("Query allow list configuration"), - /** Security */ - security: external_exports.object({ - /** Maximum query size */ - maxQuerySize: external_exports.number().int().min(1).optional().describe("Maximum query string size in bytes"), - /** Reject introspection in production */ - rejectIntrospection: external_exports.boolean().default(false).describe("Reject introspection queries") - }).optional().describe("Security configuration") -}); -var FederationEntityKeySchema2 = external_exports.object({ - /** Fields composing the key (e.g., "id" or "sku packageId") */ - fields: external_exports.string().describe("Selection set of fields composing the entity key"), - /** Whether this key can be used for resolution across subgraphs */ - resolvable: external_exports.boolean().optional().default(true).describe("Whether entities can be resolved from this subgraph") -}); -var FederationExternalFieldSchema2 = external_exports.object({ - /** Field name */ - field: external_exports.string().describe("Field name marked as external"), - /** The subgraph that owns this field */ - ownerSubgraph: external_exports.string().optional().describe("Subgraph that owns this field") -}); -var FederationRequiresSchema2 = external_exports.object({ - /** The field that has this requirement */ - field: external_exports.string().describe("Field with the requirement"), - /** Selection set of external fields required for resolution */ - fields: external_exports.string().describe('Selection set of required fields (e.g., "price weight")') -}); -var FederationProvidesSchema2 = external_exports.object({ - /** The field that provides additional data */ - field: external_exports.string().describe("Field that provides additional entity fields"), - /** Selection set of fields provided during resolution */ - fields: external_exports.string().describe('Selection set of provided fields (e.g., "name price")') -}); -var FederationEntitySchema2 = external_exports.object({ - /** Type/Object name */ - typeName: external_exports.string().describe("GraphQL type name for this entity"), - /** Entity keys (`@key` directive) */ - keys: external_exports.array(FederationEntityKeySchema2).min(1).describe("Entity key definitions"), - /** External fields (`@external`) */ - externalFields: external_exports.array(FederationExternalFieldSchema2).optional().describe("Fields owned by other subgraphs"), - /** Requires directives (`@requires`) */ - requires: external_exports.array(FederationRequiresSchema2).optional().describe("Required external fields for computed fields"), - /** Provides directives (`@provides`) */ - provides: external_exports.array(FederationProvidesSchema2).optional().describe("Fields provided during resolution"), - /** Whether this subgraph owns this entity */ - owner: external_exports.boolean().optional().default(false).describe("Whether this subgraph is the owner of this entity") -}); -var SubgraphConfigSchema2 = external_exports.object({ - /** Subgraph name */ - name: external_exports.string().describe("Unique subgraph identifier"), - /** Subgraph URL */ - url: external_exports.string().describe("Subgraph endpoint URL"), - /** Schema source */ - schemaSource: external_exports.enum(["introspection", "file", "registry"]).default("introspection").describe("How to obtain the subgraph schema"), - /** Schema file path (when schemaSource is "file") */ - schemaPath: external_exports.string().optional().describe("Path to schema file (SDL format)"), - /** Federated entities defined by this subgraph */ - entities: external_exports.array(FederationEntitySchema2).optional().describe("Entity definitions for this subgraph"), - /** Health check endpoint */ - healthCheck: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable health checking"), - path: external_exports.string().default("/health").describe("Health check endpoint path"), - intervalMs: external_exports.number().int().min(1e3).default(3e4).describe("Health check interval in milliseconds") - }).optional().describe("Subgraph health check configuration"), - /** Request headers to forward */ - forwardHeaders: external_exports.array(external_exports.string()).optional().describe("HTTP headers to forward to this subgraph") -}); -var FederationGatewaySchema2 = external_exports.object({ - /** Enable federation mode */ - enabled: external_exports.boolean().default(false).describe("Enable GraphQL Federation gateway mode"), - /** Federation specification version */ - version: external_exports.enum(["v1", "v2"]).default("v2").describe("Federation specification version"), - /** Registered subgraphs */ - subgraphs: external_exports.array(SubgraphConfigSchema2).describe("Subgraph configurations"), - /** Service discovery */ - serviceDiscovery: external_exports.object({ - /** Discovery mode */ - type: external_exports.enum(["static", "dns", "consul", "kubernetes"]).default("static").describe("Service discovery method"), - /** Poll interval for dynamic discovery */ - pollIntervalMs: external_exports.number().int().min(1e3).optional().describe("Discovery poll interval in milliseconds"), - /** Kubernetes namespace (when type is "kubernetes") */ - namespace: external_exports.string().optional().describe("Kubernetes namespace for subgraph discovery") - }).optional().describe("Service discovery configuration"), - /** Query planning */ - queryPlanning: external_exports.object({ - /** Execution strategy */ - strategy: external_exports.enum(["parallel", "sequential", "adaptive"]).default("parallel").describe("Query execution strategy across subgraphs"), - /** Maximum query depth across subgraphs */ - maxDepth: external_exports.number().int().min(1).optional().describe("Max query depth in federated execution"), - /** Dry-run mode for debugging query plans */ - dryRun: external_exports.boolean().optional().default(false).describe("Log query plans without executing") - }).optional().describe("Query planning configuration"), - /** Schema composition settings */ - composition: external_exports.object({ - /** How schema conflicts are resolved */ - conflictResolution: external_exports.enum(["error", "first_wins", "last_wins"]).default("error").describe("Strategy for resolving schema conflicts"), - /** Whether to validate composed schema */ - validate: external_exports.boolean().default(true).describe("Validate composed supergraph schema") - }).optional().describe("Schema composition configuration"), - /** Gateway-level error handling */ - errorHandling: external_exports.object({ - /** Whether to include subgraph names in errors */ - includeSubgraphName: external_exports.boolean().default(false).describe("Include subgraph name in error responses"), - /** Partial error behavior */ - partialErrors: external_exports.enum(["propagate", "nullify", "reject"]).default("propagate").describe("Behavior when a subgraph returns partial errors") - }).optional().describe("Error handling configuration") -}); -var GraphQLConfigSchema2 = external_exports.object({ - /** Enable GraphQL API */ - enabled: external_exports.boolean().default(true).describe("Enable GraphQL API"), - /** GraphQL endpoint path */ - path: external_exports.string().default("/graphql").describe("GraphQL endpoint path"), - /** GraphQL Playground */ - playground: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable GraphQL Playground"), - path: external_exports.string().default("/playground").describe("Playground path") - }).optional().describe("GraphQL Playground configuration"), - /** Schema generation */ - schema: external_exports.object({ - /** Auto-generate types from Objects */ - autoGenerateTypes: external_exports.boolean().default(true).describe("Auto-generate types from Objects"), - /** Type configurations */ - types: external_exports.array(GraphQLTypeConfigSchema2).optional().describe("Type configurations"), - /** Query configurations */ - queries: external_exports.array(GraphQLQueryConfigSchema2).optional().describe("Query configurations"), - /** Mutation configurations */ - mutations: external_exports.array(GraphQLMutationConfigSchema2).optional().describe("Mutation configurations"), - /** Subscription configurations */ - subscriptions: external_exports.array(GraphQLSubscriptionConfigSchema2).optional().describe("Subscription configurations"), - /** Custom resolvers */ - resolvers: external_exports.array(GraphQLResolverConfigSchema2).optional().describe("Custom resolver configurations"), - /** Custom directives */ - directives: external_exports.array(GraphQLDirectiveConfigSchema2).optional().describe("Custom directive configurations") - }).optional().describe("Schema generation configuration"), - /** DataLoader configurations */ - dataLoaders: external_exports.array(GraphQLDataLoaderConfigSchema2).optional().describe("DataLoader configurations"), - /** Security configuration */ - security: external_exports.object({ - /** Query depth limiting */ - depthLimit: GraphQLQueryDepthLimitSchema2.optional().describe("Query depth limiting"), - /** Query complexity */ - complexity: GraphQLQueryComplexitySchema2.optional().describe("Query complexity calculation"), - /** Rate limiting */ - rateLimit: GraphQLRateLimitSchema2.optional().describe("Rate limiting"), - /** Persisted queries */ - persistedQueries: GraphQLPersistedQuerySchema2.optional().describe("Persisted queries") - }).optional().describe("Security configuration"), - /** Federation configuration */ - federation: FederationGatewaySchema2.optional().describe("GraphQL Federation gateway configuration") -}); -var GraphQLConfig2 = Object.assign(GraphQLConfigSchema2, { - create: (config4) => config4 -}); -var mapFieldTypeToGraphQL = (fieldType) => { - const mapping = { - // Core Text - "text": "String", - "textarea": "String", - "email": "Email", - "url": "URL", - "phone": "PhoneNumber", - "password": "String", - // Rich Content - "markdown": "String", - "html": "String", - "richtext": "String", - // Numbers - "number": "Float", - "currency": "Currency", - "percent": "Float", - // Date & Time - "date": "Date", - "datetime": "DateTime", - "time": "Time", - // Logic - "boolean": "Boolean", - "toggle": "Boolean", - // Selection - "select": "String", - "multiselect": "[String]", - "radio": "String", - "checkboxes": "[String]", - // Relational - "lookup": "ID", - "master_detail": "ID", - "tree": "ID", - // Media - "image": "URL", - "file": "URL", - "avatar": "URL", - "video": "URL", - "audio": "URL", - // Calculated - "formula": "String", - "summary": "Float", - "autonumber": "String", - // Enhanced Types - "location": "JSONObject", - "address": "JSONObject", - "code": "String", - "json": "JSON", - "color": "String", - "rating": "Float", - "slider": "Float", - "signature": "String", - "qrcode": "String", - "progress": "Float", - "tags": "[String]", - // AI/ML - "vector": "[Float]" - }; - return mapping[fieldType] || "String"; -}; -var BatchOperationType2 = external_exports.enum([ - "create", - // Batch insert - "update", - // Batch update - "upsert", - // Batch upsert (insert or update based on external ID) - "delete" - // Batch delete -]); -var BatchRecordSchema2 = external_exports.object({ - id: external_exports.string().optional().describe("Record ID (required for update/delete)"), - data: RecordDataSchema2.optional().describe("Record data (required for create/update/upsert)"), - externalId: external_exports.string().optional().describe("External ID for upsert matching") -}); -var BatchOptionsSchema2 = external_exports.object({ - atomic: external_exports.boolean().optional().default(true).describe("If true, rollback entire batch on any failure (transaction mode)"), - returnRecords: external_exports.boolean().optional().default(false).describe("If true, return full record data in response"), - continueOnError: external_exports.boolean().optional().default(false).describe("If true (and atomic=false), continue processing remaining records after errors"), - validateOnly: external_exports.boolean().optional().default(false).describe("If true, validate records without persisting changes (dry-run mode)") -}); -var BatchUpdateRequestSchema2 = external_exports.object({ - operation: BatchOperationType2.describe("Type of batch operation"), - records: external_exports.array(BatchRecordSchema2).min(1).max(200).describe("Array of records to process (max 200 per batch)"), - options: BatchOptionsSchema2.optional().describe("Batch operation options") -}); -var UpdateManyRequestSchema2 = external_exports.object({ - records: external_exports.array(BatchRecordSchema2).min(1).max(200).describe("Array of records to update (max 200 per batch)"), - options: BatchOptionsSchema2.optional().describe("Update options") -}); -var BatchOperationResultSchema2 = external_exports.object({ - id: external_exports.string().optional().describe("Record ID if operation succeeded"), - success: external_exports.boolean().describe("Whether this record was processed successfully"), - errors: external_exports.array(ApiErrorSchema2).optional().describe("Array of errors if operation failed"), - data: RecordDataSchema2.optional().describe("Full record data (if returnRecords=true)"), - index: external_exports.number().optional().describe("Index of the record in the request array") -}); -var BatchUpdateResponseSchema2 = BaseResponseSchema2.extend({ - operation: BatchOperationType2.optional().describe("Operation type that was performed"), - total: external_exports.number().describe("Total number of records in the batch"), - succeeded: external_exports.number().describe("Number of records that succeeded"), - failed: external_exports.number().describe("Number of records that failed"), - results: external_exports.array(BatchOperationResultSchema2).describe("Detailed results for each record") -}); -var DeleteManyRequestSchema2 = external_exports.object({ - ids: external_exports.array(external_exports.string()).min(1).max(200).describe("Array of record IDs to delete (max 200)"), - options: BatchOptionsSchema2.optional().describe("Delete options") -}); -var BatchApiContracts = { - batchOperation: { - input: BatchUpdateRequestSchema2, - output: BatchUpdateResponseSchema2 - }, - updateMany: { - input: UpdateManyRequestSchema2, - output: BatchUpdateResponseSchema2 - }, - deleteMany: { - input: DeleteManyRequestSchema2, - output: BatchUpdateResponseSchema2 - } -}; -var BatchConfigSchema2 = external_exports.object({ - /** Enable batch operations */ - enabled: external_exports.boolean().default(true).describe("Enable batch operations"), - /** Maximum records per batch */ - maxRecordsPerBatch: external_exports.number().int().min(1).max(1e3).default(200).describe("Maximum records per batch"), - /** Default options */ - defaultOptions: BatchOptionsSchema2.optional().describe("Default batch options") -}).passthrough(); -var CacheDirective2 = external_exports.enum([ - "public", - // Cacheable by any cache - "private", - // Cacheable only by user-agent - "no-cache", - // Must revalidate with server - "no-store", - // Never cache - "must-revalidate", - // Must revalidate stale responses - "max-age" - // Maximum cache age in seconds -]); -var CacheControlSchema2 = external_exports.object({ - directives: external_exports.array(CacheDirective2).describe("Cache control directives"), - maxAge: external_exports.number().optional().describe("Maximum cache age in seconds"), - staleWhileRevalidate: external_exports.number().optional().describe("Allow serving stale content while revalidating (seconds)"), - staleIfError: external_exports.number().optional().describe("Allow serving stale content on error (seconds)") -}); -var ETagSchema2 = external_exports.object({ - value: external_exports.string().describe("ETag value (hash or version identifier)"), - weak: external_exports.boolean().optional().default(false).describe("Whether this is a weak ETag") -}); -var MetadataCacheRequestSchema2 = external_exports.object({ - ifNoneMatch: external_exports.string().optional().describe("ETag value for conditional request (If-None-Match header)"), - ifModifiedSince: external_exports.string().datetime().optional().describe("Timestamp for conditional request (If-Modified-Since header)"), - cacheControl: CacheControlSchema2.optional().describe("Client cache control preferences") -}); -var MetadataCacheResponseSchema2 = external_exports.object({ - data: external_exports.unknown().optional().describe("Metadata payload (omitted for 304 Not Modified)"), - etag: ETagSchema2.optional().describe("ETag for this resource version"), - lastModified: external_exports.string().datetime().optional().describe("Last modification timestamp"), - cacheControl: CacheControlSchema2.optional().describe("Cache control directives"), - notModified: external_exports.boolean().optional().default(false).describe("True if resource has not been modified (304 response)"), - version: external_exports.string().optional().describe("Metadata version identifier") -}); -var CacheInvalidationTarget2 = external_exports.enum([ - "all", - // Invalidate all cached metadata - "object", - // Invalidate specific object metadata - "field", - // Invalidate specific field metadata - "permission", - // Invalidate permission metadata - "layout", - // Invalidate layout metadata - "custom" - // Custom invalidation pattern -]); -var CacheInvalidationRequestSchema2 = external_exports.object({ - target: CacheInvalidationTarget2.describe("What to invalidate"), - identifiers: external_exports.array(external_exports.string()).optional().describe("Specific resources to invalidate (e.g., object names)"), - cascade: external_exports.boolean().optional().default(false).describe("If true, invalidate dependent resources"), - pattern: external_exports.string().optional().describe("Pattern for custom invalidation (supports wildcards)") -}); -var CacheInvalidationResponseSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Whether invalidation succeeded"), - invalidated: external_exports.number().describe("Number of cache entries invalidated"), - targets: external_exports.array(external_exports.string()).optional().describe("List of invalidated resources") -}); -var MetadataCacheApi = { - getCached: { - input: MetadataCacheRequestSchema2, - output: MetadataCacheResponseSchema2 - }, - invalidate: { - input: CacheInvalidationRequestSchema2, - output: CacheInvalidationResponseSchema2 - } -}; -var ErrorCategory2 = external_exports.enum([ - "validation", - // Input validation errors (400) - "authentication", - // Authentication failures (401) - "authorization", - // Permission denied errors (403) - "not_found", - // Resource not found (404) - "conflict", - // Resource conflict (409) - "rate_limit", - // Rate limiting (429) - "server", - // Internal server errors (500) - "external", - // External service errors (502/503) - "maintenance" - // Planned maintenance (503) -]); -var StandardErrorCode2 = external_exports.enum([ - // Validation Errors (400) - "validation_error", - // Generic validation failure - "invalid_field", - // Invalid field value - "missing_required_field", - // Required field missing - "invalid_format", - // Field format invalid (e.g., email, date) - "value_too_long", - // Field value exceeds max length - "value_too_short", - // Field value below min length - "value_out_of_range", - // Numeric value out of range - "invalid_reference", - // Invalid foreign key reference - "duplicate_value", - // Unique constraint violation - "invalid_query", - // Malformed query syntax - "invalid_filter", - // Invalid filter expression - "invalid_sort", - // Invalid sort specification - "max_records_exceeded", - // Query would return too many records - // Authentication Errors (401) - "unauthenticated", - // No valid authentication provided - "invalid_credentials", - // Wrong username/password - "expired_token", - // Authentication token expired - "invalid_token", - // Authentication token invalid - "session_expired", - // User session expired - "mfa_required", - // Multi-factor authentication required - "email_not_verified", - // Email verification required - // Authorization Errors (403) - "permission_denied", - // User lacks required permission - "insufficient_privileges", - // Operation requires higher privileges - "field_not_accessible", - // Field-level security restriction - "record_not_accessible", - // Sharing rule restriction - "license_required", - // Feature requires license - "ip_restricted", - // IP address not allowed - "time_restricted", - // Access outside allowed time window - // Not Found Errors (404) - "resource_not_found", - // Generic resource not found - "object_not_found", - // Object/table not found - "record_not_found", - // Record with given ID not found - "field_not_found", - // Field not found in object - "endpoint_not_found", - // API endpoint not found - // Conflict Errors (409) - "resource_conflict", - // Generic resource conflict - "concurrent_modification", - // Record modified by another user - "delete_restricted", - // Cannot delete due to dependencies - "duplicate_record", - // Record already exists - "lock_conflict", - // Record is locked by another process - // Rate Limiting (429) - "rate_limit_exceeded", - // Too many requests - "quota_exceeded", - // API quota exceeded - "concurrent_limit_exceeded", - // Too many concurrent requests - // Server Errors (500) - "internal_error", - // Generic internal server error - "database_error", - // Database operation failed - "timeout", - // Operation timed out - "service_unavailable", - // Service temporarily unavailable - "not_implemented", - // Feature not yet implemented - // External Service Errors (502/503) - "external_service_error", - // External API call failed - "integration_error", - // Integration service error - "webhook_delivery_failed", - // Webhook delivery failed - // Batch Operation Errors - "batch_partial_failure", - // Batch operation partially succeeded - "batch_complete_failure", - // Batch operation completely failed - "transaction_failed" - // Transaction rolled back -]); -var ErrorHttpStatusMap = { - validation: 400, - authentication: 401, - authorization: 403, - not_found: 404, - conflict: 409, - rate_limit: 429, - server: 500, - external: 502, - maintenance: 503 -}; -var RetryStrategy2 = external_exports.enum([ - "no_retry", - // Do not retry (permanent failure) - "retry_immediate", - // Retry immediately - "retry_backoff", - // Retry with exponential backoff - "retry_after" - // Retry after specified delay -]); -var FieldErrorSchema2 = external_exports.object({ - field: external_exports.string().describe("Field path (supports dot notation)"), - code: StandardErrorCode2.describe("Error code for this field"), - message: external_exports.string().describe("Human-readable error message"), - value: external_exports.unknown().optional().describe("The invalid value that was provided"), - constraint: external_exports.unknown().optional().describe("The constraint that was violated (e.g., max length)") -}); -var EnhancedApiErrorSchema2 = external_exports.object({ - code: StandardErrorCode2.describe("Machine-readable error code"), - message: external_exports.string().describe("Human-readable error message"), - category: ErrorCategory2.optional().describe("Error category"), - httpStatus: external_exports.number().optional().describe("HTTP status code"), - retryable: external_exports.boolean().default(false).describe("Whether the request can be retried"), - retryStrategy: RetryStrategy2.optional().describe("Recommended retry strategy"), - retryAfter: external_exports.number().optional().describe("Seconds to wait before retrying"), - details: external_exports.unknown().optional().describe("Additional error context"), - fieldErrors: external_exports.array(FieldErrorSchema2).optional().describe("Field-specific validation errors"), - timestamp: external_exports.string().datetime().optional().describe("When the error occurred"), - requestId: external_exports.string().optional().describe("Request ID for tracking"), - traceId: external_exports.string().optional().describe("Distributed trace ID"), - documentation: external_exports.string().url().optional().describe("URL to error documentation"), - helpText: external_exports.string().optional().describe("Suggested actions to resolve the error") -}); -var ErrorResponseSchema2 = external_exports.object({ - success: external_exports.literal(false).describe("Always false for error responses"), - error: EnhancedApiErrorSchema2.describe("Error details"), - meta: external_exports.object({ - timestamp: external_exports.string().datetime().optional(), - requestId: external_exports.string().optional(), - traceId: external_exports.string().optional() - }).optional().describe("Response metadata") -}); -var WorkflowTriggerType2 = external_exports.enum([ - "on_create", - // When record is created - "on_update", - // When record is updated - "on_create_or_update", - // Both - "on_delete", - // When record is deleted - "schedule" - // Time-based (cron) -]); -var FieldUpdateActionSchema2 = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("field_update"), - field: external_exports.string().describe("Field to update"), - value: external_exports.unknown().describe("Value or Formula to set") -}); -var EmailAlertActionSchema2 = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("email_alert"), - template: external_exports.string().describe("Email template ID/DevName"), - recipients: external_exports.array(external_exports.string()).describe("List of recipient emails or user IDs") -}); -var ConnectorActionRefSchema2 = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("connector_action"), - connectorId: external_exports.string().describe("Target Connector ID (e.g. slack, twilio)"), - actionId: external_exports.string().describe("Target Action ID (e.g. send_message)"), - input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Input parameters matching the action schema") -}); -var HttpCallActionSchema2 = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("http_call"), - url: external_exports.string().describe("Target URL"), - method: external_exports.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).default("POST").describe("HTTP Method"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("HTTP Headers"), - body: external_exports.string().optional().describe("Request body (JSON or text)") -}); -var TaskCreationActionSchema2 = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("task_creation"), - taskObject: external_exports.string().describe('Task object name (e.g., "task", "project_task")'), - subject: external_exports.string().describe("Task subject/title"), - description: external_exports.string().optional().describe("Task description"), - assignedTo: external_exports.string().optional().describe("User ID or field reference for assignee"), - dueDate: external_exports.string().optional().describe("Due date (ISO string or formula)"), - priority: external_exports.string().optional().describe("Task priority"), - relatedTo: external_exports.string().optional().describe("Related record ID or field reference"), - additionalFields: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional custom fields") -}); -var PushNotificationActionSchema2 = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("push_notification"), - title: external_exports.string().describe("Notification title"), - body: external_exports.string().describe("Notification body text"), - recipients: external_exports.array(external_exports.string()).describe("User IDs or device tokens"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data payload"), - badge: external_exports.number().optional().describe("Badge count (iOS)"), - sound: external_exports.string().optional().describe("Notification sound"), - clickAction: external_exports.string().optional().describe("Action/URL when notification is clicked") -}); -var CustomScriptActionSchema2 = external_exports.object({ - name: external_exports.string().describe("Action name"), - type: external_exports.literal("custom_script"), - language: external_exports.enum(["javascript", "typescript", "python"]).default("javascript").describe("Script language"), - code: external_exports.string().describe("Script code to execute"), - timeout: external_exports.number().default(3e4).describe("Execution timeout in milliseconds"), - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional context variables") -}); -var WorkflowActionSchema2 = external_exports.discriminatedUnion("type", [ - FieldUpdateActionSchema2, - EmailAlertActionSchema2, - HttpCallActionSchema2, - ConnectorActionRefSchema2, - TaskCreationActionSchema2, - PushNotificationActionSchema2, - CustomScriptActionSchema2 -]); -var TimeTriggerSchema2 = external_exports.object({ - id: external_exports.string().optional().describe("Unique identifier"), - /** Timing Logic */ - timeLength: external_exports.number().int().describe("Duration amount (e.g. 1, 30)"), - timeUnit: external_exports.enum(["minutes", "hours", "days"]).describe("Unit of time"), - /** Reference Point */ - offsetDirection: external_exports.enum(["before", "after"]).describe("Before or After the reference date"), - offsetFrom: external_exports.enum(["trigger_date", "date_field"]).describe("Basis for calculation"), - dateField: external_exports.string().optional().describe("Date field to calculate from (required if offsetFrom is date_field)"), - /** Actions */ - actions: external_exports.array(WorkflowActionSchema2).describe("Actions to execute at the scheduled time") -}); -var WorkflowRuleSchema2 = external_exports.object({ - /** Machine name */ - name: SnakeCaseIdentifierSchema7.describe("Unique workflow name (lowercase snake_case)"), - /** Target Object */ - objectName: external_exports.string().describe("Target Object"), - /** When to evaluate the rule */ - triggerType: WorkflowTriggerType2.describe("When to evaluate"), - /** - * Condition to start the workflow. - * If empty, runs on every trigger event. - */ - criteria: external_exports.string().optional().describe("Formula condition. If TRUE, actions execute."), - /** Actions to execute immediately */ - actions: external_exports.array(WorkflowActionSchema2).optional().describe("Immediate actions"), - /** - * Time-Dependent Actions - * Actions scheduled to run in the future. - */ - timeTriggers: external_exports.array(TimeTriggerSchema2).optional().describe("Scheduled actions relative to trigger or date field"), - /** Active status */ - active: external_exports.boolean().default(true).describe("Whether this workflow is active"), - /** Execution Order */ - executionOrder: external_exports.number().int().min(0).default(100).describe("Deterministic execution order when multiple workflows match (lower runs first)"), - /** Recursion Control */ - reevaluateOnChange: external_exports.boolean().default(false).describe("Re-evaluate rule if field updates change the record validity") -}); -var AutomationTriggerRequestSchema2 = external_exports.object({ - trigger: external_exports.string(), - payload: external_exports.record(external_exports.string(), external_exports.unknown()) -}); -var AutomationTriggerResponseSchema2 = external_exports.object({ - success: external_exports.boolean(), - jobId: external_exports.string().optional(), - result: external_exports.unknown().optional() -}); -var GetDiscoveryRequestSchema2 = external_exports.object({}); -var GetDiscoveryResponseSchema2 = DiscoverySchema2.partial().required({ version: true }).extend({ - /** @deprecated Use `name` instead. Kept for backward compatibility. */ - apiName: external_exports.string().optional().describe("API name (deprecated \u2014 use name)") -}); -var GetMetaTypesRequestSchema2 = external_exports.object({}); -var GetMetaTypesResponseSchema2 = external_exports.object({ - types: external_exports.array(external_exports.string()).describe('Available metadata type names (e.g., "object", "plugin", "view")') -}); -var GetMetaItemsRequestSchema2 = external_exports.object({ - type: external_exports.string().describe('Metadata type name (e.g., "object", "plugin")'), - packageId: external_exports.string().optional().describe("Optional package ID to filter items by") -}); -var GetMetaItemsResponseSchema2 = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - items: external_exports.array(external_exports.unknown()).describe("Array of metadata items") -}); -var GetMetaItemRequestSchema2 = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - name: external_exports.string().describe("Item name (snake_case identifier)"), - packageId: external_exports.string().optional().describe("Optional package ID to filter items by") -}); -var GetMetaItemResponseSchema2 = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - name: external_exports.string().describe("Item name"), - item: external_exports.unknown().describe("Metadata item definition") -}); -var SaveMetaItemRequestSchema2 = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - name: external_exports.string().describe("Item name"), - item: external_exports.unknown().describe("Metadata item definition") -}); -var SaveMetaItemResponseSchema2 = external_exports.object({ - success: external_exports.boolean(), - message: external_exports.string().optional() -}); -var GetMetaItemCachedRequestSchema2 = external_exports.object({ - type: external_exports.string().describe("Metadata type name"), - name: external_exports.string().describe("Item name"), - cacheRequest: MetadataCacheRequestSchema2.optional().describe("Cache validation parameters") -}); -var GetMetaItemCachedResponseSchema = MetadataCacheResponseSchema2; -var GetUiViewRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - type: external_exports.enum(["list", "form"]).describe("View type") -}); -var GetUiViewResponseSchema = ViewSchema3; -var FindDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe('The unique machine name of the object to query (e.g. "account").'), - query: QuerySchema3.optional().describe("Structured query definition (filter, sort, select, pagination).") -}); -var FindDataResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("The object name for the returned records."), - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("The list of matching records."), - total: external_exports.number().optional().describe("Total number of records matching the filter (if requested)."), - nextCursor: external_exports.string().optional().describe("Cursor for the next page of results (cursor-based pagination)."), - hasMore: external_exports.boolean().optional().describe("True if there are more records available (pagination).") -}); -var HttpFindQueryParamsSchema2 = external_exports.object({ - /** @canonical Singular form — the standard going forward. JSON string of filter expression or AST. */ - filter: external_exports.string().optional().describe("JSON-encoded filter expression (canonical, singular)."), - /** @deprecated Use `filter` (singular). Accepted for backward compatibility. */ - filters: external_exports.string().optional().describe("JSON-encoded filter expression (deprecated plural alias)."), - select: external_exports.string().optional().describe("Comma-separated list of fields to retrieve."), - sort: external_exports.string().optional().describe('Sort expression (e.g. "name asc,created_at desc" or "-created_at").'), - orderBy: external_exports.string().optional().describe("Alias for sort (OData compatibility)."), - top: external_exports.coerce.number().optional().describe("Max records to return (limit)."), - skip: external_exports.coerce.number().optional().describe("Records to skip (offset)."), - expand: external_exports.string().optional().describe( - "Comma-separated list of lookup/master_detail field names to expand. Resolved to populate array and passed to the engine for batch $in expansion." - ), - search: external_exports.string().optional().describe("Full-text search query."), - distinct: external_exports.coerce.boolean().optional().describe("SELECT DISTINCT flag."), - count: external_exports.coerce.boolean().optional().describe("Include total count in response.") -}); -var GetDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("The object name."), - id: external_exports.string().describe("The unique record identifier (primary key)."), - select: external_exports.array(external_exports.string()).optional().describe("Fields to include in the response (allowlisted query param)."), - expand: external_exports.array(external_exports.string()).optional().describe( - "Lookup/master_detail field names to expand. The engine resolves these via batch $in queries, replacing foreign key IDs with full objects." - ) -}); -var GetDataResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("The object name."), - id: external_exports.string().describe("The record ID."), - record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The complete record data.") -}); -var CreateDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("The object name."), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The dictionary of field values to insert.") -}); -var CreateDataResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("The object name."), - id: external_exports.string().describe("The ID of the newly created record."), - record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The created record, including server-generated fields (created_at, owner).") -}); -var UpdateDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("The object name."), - id: external_exports.string().describe("The ID of the record to update."), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("The fields to update (partial update).") -}); -var UpdateDataResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - id: external_exports.string().describe("Updated record ID"), - record: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Updated record") -}); -var DeleteDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - id: external_exports.string().describe("Record ID to delete") -}); -var DeleteDataResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - id: external_exports.string().describe("Deleted record ID"), - success: external_exports.boolean().describe("Whether deletion succeeded") -}); -var BatchDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - request: BatchUpdateRequestSchema2.describe("Batch operation request") -}); -var BatchDataResponseSchema = BatchUpdateResponseSchema2; -var CreateManyDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Array of records to create") -}); -var CreateManyDataResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - records: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Created records"), - count: external_exports.number().describe("Number of records created") -}); -var UpdateManyDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - records: external_exports.array(external_exports.object({ - id: external_exports.string().describe("Record ID"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Fields to update") - })).describe("Array of updates"), - options: BatchOptionsSchema2.optional().describe("Update options") -}); -var UpdateManyDataResponseSchema = BatchUpdateResponseSchema2; -var DeleteManyDataRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - ids: external_exports.array(external_exports.string()).describe("Array of record IDs to delete"), - options: BatchOptionsSchema2.optional().describe("Delete options") -}); -var DeleteManyDataResponseSchema = BatchUpdateResponseSchema2; -var ListViewsRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - type: external_exports.enum(["list", "form"]).optional().describe("Filter by view type") -}); -var ListViewsResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - views: external_exports.array(ViewSchema3).describe("Array of view definitions") -}); -var GetViewRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - viewId: external_exports.string().describe("View identifier") -}); -var GetViewResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - view: ViewSchema3.describe("View definition") -}); -var CreateViewRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - data: ViewSchema3.describe("View definition to create") -}); -var CreateViewResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - viewId: external_exports.string().describe("Created view identifier"), - view: ViewSchema3.describe("Created view definition") -}); -var UpdateViewRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - viewId: external_exports.string().describe("View identifier"), - data: ViewSchema3.partial().describe("Partial view data to update") -}); -var UpdateViewResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - viewId: external_exports.string().describe("Updated view identifier"), - view: ViewSchema3.describe("Updated view definition") -}); -var DeleteViewRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name (snake_case)"), - viewId: external_exports.string().describe("View identifier to delete") -}); -var DeleteViewResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - viewId: external_exports.string().describe("Deleted view identifier"), - success: external_exports.boolean().describe("Whether deletion succeeded") -}); -var CheckPermissionRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name to check permissions for"), - action: external_exports.enum(["create", "read", "edit", "delete", "transfer", "restore", "purge"]).describe("Action to check"), - recordId: external_exports.string().optional().describe("Specific record ID (for record-level checks)"), - field: external_exports.string().optional().describe("Specific field name (for field-level checks)") -}); -var CheckPermissionResponseSchema2 = external_exports.object({ - allowed: external_exports.boolean().describe("Whether the action is permitted"), - reason: external_exports.string().optional().describe("Reason if denied") -}); -var GetObjectPermissionsRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name to get permissions for") -}); -var GetObjectPermissionsResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - permissions: ObjectPermissionSchema2.describe("Object-level permissions"), - fieldPermissions: external_exports.record(external_exports.string(), FieldPermissionSchema2).optional().describe("Field-level permissions keyed by field name") -}); -var GetEffectivePermissionsRequestSchema2 = external_exports.object({}); -var GetEffectivePermissionsResponseSchema2 = external_exports.object({ - objects: external_exports.record(external_exports.string(), ObjectPermissionSchema2).describe("Effective object permissions keyed by object name"), - systemPermissions: external_exports.array(external_exports.string()).describe("Effective system-level permissions") -}); -var GetWorkflowConfigRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name to get workflow config for") -}); -var GetWorkflowConfigResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - workflows: external_exports.array(WorkflowRuleSchema2).describe("Active workflow rules for this object") -}); -var WorkflowStateSchema2 = external_exports.object({ - currentState: external_exports.string().describe("Current workflow state name"), - availableTransitions: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Transition name"), - targetState: external_exports.string().describe("Target state after transition"), - label: external_exports.string().optional().describe("Display label"), - requiresApproval: external_exports.boolean().default(false).describe("Whether transition requires approval") - })).describe("Available transitions from current state"), - history: external_exports.array(external_exports.object({ - fromState: external_exports.string().describe("Previous state"), - toState: external_exports.string().describe("New state"), - action: external_exports.string().describe("Action that triggered the transition"), - userId: external_exports.string().describe("User who performed the action"), - timestamp: external_exports.string().datetime().describe("When the transition occurred"), - comment: external_exports.string().optional().describe("Optional comment") - })).optional().describe("State transition history") -}); -var GetWorkflowStateRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID to get workflow state for") -}); -var GetWorkflowStateResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - state: WorkflowStateSchema2.describe("Current workflow state and available transitions") -}); -var WorkflowTransitionRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - transition: external_exports.string().describe("Transition name to execute"), - comment: external_exports.string().optional().describe("Optional comment for the transition"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data for the transition") -}); -var WorkflowTransitionResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - success: external_exports.boolean().describe("Whether the transition succeeded"), - state: WorkflowStateSchema2.describe("New workflow state after transition") -}); -var WorkflowApproveRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - comment: external_exports.string().optional().describe("Approval comment"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional data") -}); -var WorkflowApproveResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - success: external_exports.boolean().describe("Whether the approval succeeded"), - state: WorkflowStateSchema2.describe("New workflow state after approval") -}); -var WorkflowRejectRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - reason: external_exports.string().describe("Rejection reason"), - comment: external_exports.string().optional().describe("Additional comment") -}); -var WorkflowRejectResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - success: external_exports.boolean().describe("Whether the rejection succeeded"), - state: WorkflowStateSchema2.describe("New workflow state after rejection") -}); -var RealtimeConnectRequestSchema2 = external_exports.object({ - transport: TransportProtocol2.optional().describe("Preferred transport protocol"), - channels: external_exports.array(external_exports.string()).optional().describe("Channels to subscribe to on connect"), - token: external_exports.string().optional().describe("Authentication token") -}); -var RealtimeConnectResponseSchema2 = external_exports.object({ - connectionId: external_exports.string().describe("Unique connection identifier"), - transport: TransportProtocol2.describe("Negotiated transport protocol"), - url: external_exports.string().optional().describe("WebSocket/SSE endpoint URL") -}); -var RealtimeDisconnectRequestSchema2 = external_exports.object({ - connectionId: external_exports.string().optional().describe("Connection ID to disconnect") -}); -var RealtimeDisconnectResponseSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Whether disconnection succeeded") -}); -var RealtimeSubscribeRequestSchema2 = external_exports.object({ - channel: external_exports.string().describe("Channel name to subscribe to"), - events: external_exports.array(external_exports.string()).optional().describe("Specific event types to listen for"), - filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event filter criteria") -}); -var RealtimeSubscribeResponseSchema2 = external_exports.object({ - subscriptionId: external_exports.string().describe("Unique subscription identifier"), - channel: external_exports.string().describe("Subscribed channel name") -}); -var RealtimeUnsubscribeRequestSchema2 = external_exports.object({ - subscriptionId: external_exports.string().describe("Subscription ID to cancel") -}); -var RealtimeUnsubscribeResponseSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Whether unsubscription succeeded") -}); -var SetPresenceRequestSchema2 = external_exports.object({ - channel: external_exports.string().describe("Channel to set presence in"), - state: RealtimePresenceSchema2.describe("Presence state to set") -}); -var SetPresenceResponseSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Whether presence was set") -}); -var GetPresenceRequestSchema2 = external_exports.object({ - channel: external_exports.string().describe("Channel to get presence for") -}); -var GetPresenceResponseSchema2 = external_exports.object({ - channel: external_exports.string().describe("Channel name"), - members: external_exports.array(RealtimePresenceSchema2).describe("Active members and their presence state") -}); -var RegisterDeviceRequestSchema2 = external_exports.object({ - token: external_exports.string().describe("Device push notification token"), - platform: external_exports.enum(["ios", "android", "web"]).describe("Device platform"), - deviceId: external_exports.string().optional().describe("Unique device identifier"), - name: external_exports.string().optional().describe("Device friendly name") -}); -var RegisterDeviceResponseSchema2 = external_exports.object({ - deviceId: external_exports.string().describe("Registered device ID"), - success: external_exports.boolean().describe("Whether registration succeeded") -}); -var UnregisterDeviceRequestSchema2 = external_exports.object({ - deviceId: external_exports.string().describe("Device ID to unregister") -}); -var UnregisterDeviceResponseSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Whether unregistration succeeded") -}); -var NotificationPreferencesSchema2 = external_exports.object({ - email: external_exports.boolean().default(true).describe("Receive email notifications"), - push: external_exports.boolean().default(true).describe("Receive push notifications"), - inApp: external_exports.boolean().default(true).describe("Receive in-app notifications"), - digest: external_exports.enum(["none", "daily", "weekly"]).default("none").describe("Email digest frequency"), - channels: external_exports.record(external_exports.string(), external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Whether this channel is enabled"), - email: external_exports.boolean().optional().describe("Override email setting"), - push: external_exports.boolean().optional().describe("Override push setting") - })).optional().describe("Per-channel notification preferences") -}); -var GetNotificationPreferencesRequestSchema2 = external_exports.object({}); -var GetNotificationPreferencesResponseSchema2 = external_exports.object({ - preferences: NotificationPreferencesSchema2.describe("Current notification preferences") -}); -var UpdateNotificationPreferencesRequestSchema2 = external_exports.object({ - preferences: NotificationPreferencesSchema2.partial().describe("Preferences to update") -}); -var UpdateNotificationPreferencesResponseSchema2 = external_exports.object({ - preferences: NotificationPreferencesSchema2.describe("Updated notification preferences") -}); -var NotificationSchema22 = external_exports.object({ - id: external_exports.string().describe("Notification ID"), - type: external_exports.string().describe("Notification type"), - title: external_exports.string().describe("Notification title"), - body: external_exports.string().describe("Notification body text"), - read: external_exports.boolean().default(false).describe("Whether notification has been read"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional notification data"), - actionUrl: external_exports.string().optional().describe("URL to navigate to when clicked"), - createdAt: external_exports.string().datetime().describe("When notification was created") -}); -var ListNotificationsRequestSchema2 = external_exports.object({ - read: external_exports.boolean().optional().describe("Filter by read status"), - type: external_exports.string().optional().describe("Filter by notification type"), - limit: external_exports.number().default(20).describe("Maximum number of notifications to return"), - cursor: external_exports.string().optional().describe("Pagination cursor") -}); -var ListNotificationsResponseSchema2 = external_exports.object({ - notifications: external_exports.array(NotificationSchema22).describe("List of notifications"), - unreadCount: external_exports.number().describe("Total number of unread notifications"), - cursor: external_exports.string().optional().describe("Next page cursor") -}); -var MarkNotificationsReadRequestSchema2 = external_exports.object({ - ids: external_exports.array(external_exports.string()).describe("Notification IDs to mark as read") -}); -var MarkNotificationsReadResponseSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Whether the operation succeeded"), - readCount: external_exports.number().describe("Number of notifications marked as read") -}); -var MarkAllNotificationsReadRequestSchema2 = external_exports.object({}); -var MarkAllNotificationsReadResponseSchema2 = external_exports.object({ - success: external_exports.boolean().describe("Whether the operation succeeded"), - readCount: external_exports.number().describe("Number of notifications marked as read") -}); -var AiNlqRequestSchema2 = external_exports.object({ - query: external_exports.string().describe("Natural language query string"), - object: external_exports.string().optional().describe("Target object context"), - conversationId: external_exports.string().optional().describe("Conversation ID for multi-turn queries") -}); -var AiNlqResponseSchema2 = external_exports.object({ - query: external_exports.unknown().describe("Generated structured query (AST)"), - explanation: external_exports.string().optional().describe("Human-readable explanation of the query"), - confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), - suggestions: external_exports.array(external_exports.string()).optional().describe("Suggested follow-up queries") -}); -var AiSuggestRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name for context"), - field: external_exports.string().optional().describe("Field to suggest values for"), - recordId: external_exports.string().optional().describe("Record ID for context"), - partial: external_exports.string().optional().describe("Partial input for completion") -}); -var AiSuggestResponseSchema2 = external_exports.object({ - suggestions: external_exports.array(external_exports.object({ - value: external_exports.unknown().describe("Suggested value"), - label: external_exports.string().describe("Display label"), - confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), - reason: external_exports.string().optional().describe("Reason for this suggestion") - })).describe("Suggested values") -}); -var AiInsightsRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name to analyze"), - recordId: external_exports.string().optional().describe("Specific record to analyze"), - type: external_exports.enum(["summary", "trends", "anomalies", "recommendations"]).optional().describe("Type of insight") -}); -var AiInsightsResponseSchema2 = external_exports.object({ - insights: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Insight type"), - title: external_exports.string().describe("Insight title"), - description: external_exports.string().describe("Detailed description"), - confidence: external_exports.number().min(0).max(1).optional().describe("Confidence score (0-1)"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Supporting data") - })).describe("Generated insights") -}); -var GetLocalesRequestSchema2 = external_exports.object({}); -var GetLocalesResponseSchema2 = external_exports.object({ - locales: external_exports.array(external_exports.object({ - code: external_exports.string().describe("BCP-47 locale code (e.g., en-US, zh-CN)"), - label: external_exports.string().describe("Display name of the locale"), - isDefault: external_exports.boolean().default(false).describe("Whether this is the default locale") - })).describe("Available locales") -}); -var GetTranslationsRequestSchema2 = external_exports.object({ - locale: external_exports.string().describe("BCP-47 locale code"), - namespace: external_exports.string().optional().describe("Translation namespace (e.g., objects, apps, messages)"), - keys: external_exports.array(external_exports.string()).optional().describe("Specific translation keys to fetch") -}); -var GetTranslationsResponseSchema2 = external_exports.object({ - locale: external_exports.string().describe("Locale code"), - translations: TranslationDataSchema3.describe("Translation data") -}); -var GetFieldLabelsRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - locale: external_exports.string().describe("BCP-47 locale code") -}); -var GetFieldLabelsResponseSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name"), - locale: external_exports.string().describe("Locale code"), - labels: external_exports.record(external_exports.string(), external_exports.object({ - label: external_exports.string().describe("Translated field label"), - help: external_exports.string().optional().describe("Translated help text"), - options: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Translated option labels") - })).describe("Field labels keyed by field name") -}); -var ObjectStackProtocolSchema2 = external_exports.object({ - // Discovery & Metadata - getDiscovery: external_exports.function().describe("Get API discovery information"), - getMetaTypes: external_exports.function().describe("Get available metadata types"), - getMetaItems: external_exports.function().describe("Get all items of a metadata type"), - getMetaItem: external_exports.function().describe("Get a specific metadata item"), - saveMetaItem: external_exports.function().describe("Save metadata item"), - getMetaItemCached: external_exports.function().describe("Get a metadata item with cache validation"), - getUiView: external_exports.function().describe("Get UI view definition"), - // Analytics Operations - analyticsQuery: external_exports.function().describe("Execute analytics query"), - getAnalyticsMeta: external_exports.function().describe("Get analytics metadata (cubes)"), - // Automation Operations - triggerAutomation: external_exports.function().describe("Trigger an automation flow or script"), - // Package Management Operations - listPackages: external_exports.function().describe("List installed packages with optional filters"), - getPackage: external_exports.function().describe("Get a specific installed package by ID"), - installPackage: external_exports.function().describe("Install a new package from manifest"), - uninstallPackage: external_exports.function().describe("Uninstall a package by ID"), - enablePackage: external_exports.function().describe("Enable a disabled package"), - disablePackage: external_exports.function().describe("Disable an installed package"), - // Data Operations - findData: external_exports.function().describe("Find data records"), - getData: external_exports.function().describe("Get single data record"), - createData: external_exports.function().describe("Create a data record"), - updateData: external_exports.function().describe("Update a data record"), - deleteData: external_exports.function().describe("Delete a data record"), - // Batch Operations - batchData: external_exports.function().describe("Perform batch operations"), - createManyData: external_exports.function().describe("Create multiple records"), - updateManyData: external_exports.function().describe("Update multiple records"), - deleteManyData: external_exports.function().describe("Delete multiple records"), - // View Management Operations - listViews: external_exports.function().describe("List views for an object"), - getView: external_exports.function().describe("Get a specific view"), - createView: external_exports.function().describe("Create a new view"), - updateView: external_exports.function().describe("Update an existing view"), - deleteView: external_exports.function().describe("Delete a view"), - // Permission Operations - checkPermission: external_exports.function().describe("Check if an action is permitted"), - getObjectPermissions: external_exports.function().describe("Get permissions for an object"), - getEffectivePermissions: external_exports.function().describe("Get effective permissions for current user"), - // Workflow Operations - getWorkflowConfig: external_exports.function().describe("Get workflow configuration for an object"), - getWorkflowState: external_exports.function().describe("Get workflow state for a record"), - workflowTransition: external_exports.function().describe("Execute a workflow state transition"), - workflowApprove: external_exports.function().describe("Approve a workflow step"), - workflowReject: external_exports.function().describe("Reject a workflow step"), - // Realtime Operations - realtimeConnect: external_exports.function().describe("Establish realtime connection"), - realtimeDisconnect: external_exports.function().describe("Close realtime connection"), - realtimeSubscribe: external_exports.function().describe("Subscribe to a realtime channel"), - realtimeUnsubscribe: external_exports.function().describe("Unsubscribe from a realtime channel"), - setPresence: external_exports.function().describe("Set user presence state"), - getPresence: external_exports.function().describe("Get channel presence information"), - // Notification Operations - registerDevice: external_exports.function().describe("Register a device for push notifications"), - unregisterDevice: external_exports.function().describe("Unregister a device"), - getNotificationPreferences: external_exports.function().describe("Get notification preferences"), - updateNotificationPreferences: external_exports.function().describe("Update notification preferences"), - listNotifications: external_exports.function().describe("List notifications"), - markNotificationsRead: external_exports.function().describe("Mark specific notifications as read"), - markAllNotificationsRead: external_exports.function().describe("Mark all notifications as read"), - // AI Operations - aiNlq: external_exports.function().describe("Natural language query"), - aiChat: external_exports.function().describe("AI chat interaction"), - aiSuggest: external_exports.function().describe("Get AI-powered suggestions"), - aiInsights: external_exports.function().describe("Get AI-generated insights"), - // i18n Operations - getLocales: external_exports.function().describe("Get available locales"), - getTranslations: external_exports.function().describe("Get translations for a locale"), - getFieldLabels: external_exports.function().describe("Get translated field labels for an object"), - // Feed Operations - listFeed: external_exports.function().describe("List feed items for a record"), - createFeedItem: external_exports.function().describe("Create a new feed item"), - updateFeedItem: external_exports.function().describe("Update an existing feed item"), - deleteFeedItem: external_exports.function().describe("Delete a feed item"), - addReaction: external_exports.function().describe("Add an emoji reaction to a feed item"), - removeReaction: external_exports.function().describe("Remove an emoji reaction from a feed item"), - pinFeedItem: external_exports.function().describe("Pin a feed item"), - unpinFeedItem: external_exports.function().describe("Unpin a feed item"), - starFeedItem: external_exports.function().describe("Star a feed item"), - unstarFeedItem: external_exports.function().describe("Unstar a feed item"), - searchFeed: external_exports.function().describe("Search feed items"), - getChangelog: external_exports.function().describe("Get field-level changelog for a record"), - feedSubscribe: external_exports.function().describe("Subscribe to record notifications"), - feedUnsubscribe: external_exports.function().describe("Unsubscribe from record notifications") -}); -var RestApiConfigSchema2 = external_exports.object({ - /** - * API version identifier - */ - version: external_exports.string().regex(/^[a-zA-Z0-9_\-\.]+$/).default("v1").describe("API version (e.g., v1, v2, 2024-01)"), - /** - * Base path for all API routes - */ - basePath: external_exports.string().default("/api").describe("Base URL path for API"), - /** - * Full API path (combines basePath and version) - */ - apiPath: external_exports.string().optional().describe("Full API path (defaults to {basePath}/{version})"), - /** - * Enable automatic CRUD endpoints - */ - enableCrud: external_exports.boolean().default(true).describe("Enable automatic CRUD endpoint generation"), - /** - * Enable metadata endpoints - */ - enableMetadata: external_exports.boolean().default(true).describe("Enable metadata API endpoints"), - /** - * Enable UI API endpoints - */ - enableUi: external_exports.boolean().default(true).describe("Enable UI API endpoints (Views, Menus, Layouts)"), - /** - * Enable batch operation endpoints - */ - enableBatch: external_exports.boolean().default(true).describe("Enable batch operation endpoints"), - /** - * Enable discovery endpoint - */ - enableDiscovery: external_exports.boolean().default(true).describe("Enable API discovery endpoint"), - /** - * API documentation configuration - */ - documentation: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable API documentation"), - title: external_exports.string().default("ObjectStack API").describe("API documentation title"), - description: external_exports.string().optional().describe("API description"), - version: external_exports.string().optional().describe("Documentation version"), - termsOfService: external_exports.string().optional().describe("Terms of service URL"), - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().optional(), - email: external_exports.string().optional() - }).optional(), - license: external_exports.object({ - name: external_exports.string(), - url: external_exports.string().optional() - }).optional() - }).optional().describe("OpenAPI/Swagger documentation config"), - /** - * Response format configuration - */ - responseFormat: external_exports.object({ - envelope: external_exports.boolean().default(true).describe("Wrap responses in standard envelope"), - includeMetadata: external_exports.boolean().default(true).describe("Include response metadata (timestamp, requestId)"), - includePagination: external_exports.boolean().default(true).describe("Include pagination info in list responses") - }).optional().describe("Response format options") -}); -var CrudOperation2 = external_exports.enum([ - "create", - // POST /api/v1/data/{object} - "read", - // GET /api/v1/data/{object}/:id - "update", - // PATCH /api/v1/data/{object}/:id - "delete", - // DELETE /api/v1/data/{object}/:id - "list" - // GET /api/v1/data/{object} -]); -var CrudEndpointPatternSchema2 = external_exports.object({ - /** - * HTTP method - */ - method: HttpMethod5.describe("HTTP method"), - /** - * URL path pattern (relative to API base) - */ - path: external_exports.string().describe("URL path pattern"), - /** - * Operation summary for documentation - */ - summary: external_exports.string().optional().describe("Operation summary"), - /** - * Operation description - */ - description: external_exports.string().optional().describe("Operation description") -}); -var CrudEndpointsConfigSchema2 = external_exports.object({ - /** - * Enable/disable specific CRUD operations - */ - operations: external_exports.object({ - create: external_exports.boolean().default(true).describe("Enable create operation"), - read: external_exports.boolean().default(true).describe("Enable read operation"), - update: external_exports.boolean().default(true).describe("Enable update operation"), - delete: external_exports.boolean().default(true).describe("Enable delete operation"), - list: external_exports.boolean().default(true).describe("Enable list operation") - }).optional().describe("Enable/disable operations"), - /** - * Custom endpoint patterns (override defaults) - */ - patterns: external_exports.record(CrudOperation2, CrudEndpointPatternSchema2.optional()).optional().describe("Custom URL patterns for operations"), - /** - * Path prefix for data operations - */ - dataPrefix: external_exports.string().default("/data").describe("URL prefix for data endpoints"), - /** - * Object name parameter style - */ - objectParamStyle: external_exports.enum(["path", "query"]).default("path").describe("How object name is passed (path param or query param)") -}); -var MetadataEndpointsConfigSchema2 = external_exports.object({ - /** - * Path prefix for metadata operations - */ - prefix: external_exports.string().default("/meta").describe("URL prefix for metadata endpoints"), - /** - * Enable HTTP caching for metadata - */ - enableCache: external_exports.boolean().default(true).describe("Enable HTTP cache headers (ETag, Last-Modified)"), - /** - * Cache TTL in seconds - */ - cacheTtl: external_exports.number().int().default(3600).describe("Cache TTL in seconds"), - /** - * Enable specific metadata endpoints - */ - endpoints: external_exports.object({ - types: external_exports.boolean().default(true).describe("GET /meta - List all metadata types"), - items: external_exports.boolean().default(true).describe("GET /meta/:type - List items of type"), - item: external_exports.boolean().default(true).describe("GET /meta/:type/:name - Get specific item"), - schema: external_exports.boolean().default(true).describe("GET /meta/:type/:name/schema - Get JSON schema") - }).optional().describe("Enable/disable specific endpoints") -}); -var BatchEndpointsConfigSchema2 = external_exports.object({ - /** - * Maximum batch size - */ - maxBatchSize: external_exports.number().int().min(1).max(1e3).default(200).describe("Maximum records per batch operation"), - /** - * Enable generic batch endpoint - */ - enableBatchEndpoint: external_exports.boolean().default(true).describe("Enable POST /data/:object/batch endpoint"), - /** - * Enable specific batch operations - */ - operations: external_exports.object({ - createMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/createMany"), - updateMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/updateMany"), - deleteMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/deleteMany"), - upsertMany: external_exports.boolean().default(true).describe("Enable POST /data/:object/upsertMany") - }).optional().describe("Enable/disable specific batch operations"), - /** - * Transaction mode default - */ - defaultAtomic: external_exports.boolean().default(true).describe("Default atomic/transaction mode for batch operations") -}); -var RouteGenerationConfigSchema2 = external_exports.object({ - /** - * Objects to include (if empty, include all) - */ - includeObjects: external_exports.array(external_exports.string()).optional().describe("Specific objects to generate routes for (empty = all)"), - /** - * Objects to exclude - */ - excludeObjects: external_exports.array(external_exports.string()).optional().describe("Objects to exclude from route generation"), - /** - * Object name transformations - */ - nameTransform: external_exports.enum(["none", "plural", "kebab-case", "camelCase"]).default("none").describe("Transform object names in URLs"), - /** - * Custom route overrides per object - */ - overrides: external_exports.record(external_exports.string(), external_exports.object({ - enabled: external_exports.boolean().optional().describe("Enable/disable routes for this object"), - basePath: external_exports.string().optional().describe("Custom base path"), - operations: external_exports.record(CrudOperation2, external_exports.boolean()).optional().describe("Enable/disable specific operations") - })).optional().describe("Per-object route customization") -}); -var WebhookEventSchema2 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Webhook event identifier (snake_case)"), - description: external_exports.string().describe("Human-readable event description"), - method: HttpMethod5.default("POST").describe("HTTP method for webhook delivery"), - payloadSchema: external_exports.string().describe("JSON Schema $ref for the webhook payload"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers to include in webhook delivery"), - security: external_exports.array( - external_exports.enum(["hmac_sha256", "basic", "bearer", "api_key"]) - ).describe("Supported authentication methods for webhook verification") -}); -var WebhookConfigSchema2 = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable webhook support"), - events: external_exports.array(WebhookEventSchema2).describe("Registered webhook events"), - deliveryConfig: external_exports.object({ - maxRetries: external_exports.number().int().default(3).describe("Maximum delivery retry attempts"), - retryIntervalMs: external_exports.number().int().default(5e3).describe("Milliseconds between retry attempts"), - timeoutMs: external_exports.number().int().default(3e4).describe("Delivery request timeout in milliseconds"), - signatureHeader: external_exports.string().default("X-Signature-256").describe("Header name for webhook signature") - }).describe("Webhook delivery configuration"), - registrationEndpoint: external_exports.string().default("/webhooks").describe("URL path for webhook registration") -}); -var CallbackSchema2 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Callback identifier (snake_case)"), - expression: external_exports.string().describe("Runtime expression (e.g., {$request.body#/callbackUrl})"), - method: HttpMethod5.describe("HTTP method for callback request"), - url: external_exports.string().describe("Callback URL template with runtime expressions") -}); -var OpenApi31ExtensionsSchema2 = external_exports.object({ - webhooks: external_exports.record(external_exports.string(), WebhookEventSchema2).optional().describe("OpenAPI 3.1 webhooks (top-level webhook definitions)"), - callbacks: external_exports.record(external_exports.string(), external_exports.array(CallbackSchema2)).optional().describe("OpenAPI 3.1 callbacks (async response definitions)"), - jsonSchemaDialect: external_exports.string().default("https://json-schema.org/draft/2020-12/schema").describe("JSON Schema dialect for schema definitions"), - pathItemReferences: external_exports.boolean().default(false).describe("Allow $ref in path items (OpenAPI 3.1 feature)") -}); -var RestServerConfigSchema2 = external_exports.object({ - /** - * API configuration - */ - api: RestApiConfigSchema2.optional().describe("REST API configuration"), - /** - * CRUD endpoints configuration - */ - crud: CrudEndpointsConfigSchema2.optional().describe("CRUD endpoints configuration"), - /** - * Metadata endpoints configuration - */ - metadata: MetadataEndpointsConfigSchema2.optional().describe("Metadata endpoints configuration"), - /** - * Batch endpoints configuration - */ - batch: BatchEndpointsConfigSchema2.optional().describe("Batch endpoints configuration"), - /** - * Route generation configuration - */ - routes: RouteGenerationConfigSchema2.optional().describe("Route generation configuration"), - /** - * OpenAPI 3.1 extensions (webhooks, callbacks) - */ - openApi31: OpenApi31ExtensionsSchema2.optional().describe("OpenAPI 3.1 extensions configuration") -}); -var GeneratedEndpointSchema2 = external_exports.object({ - /** - * Endpoint identifier - */ - id: external_exports.string().describe("Unique endpoint identifier"), - /** - * HTTP method - */ - method: HttpMethod5.describe("HTTP method"), - /** - * Full URL path - */ - path: external_exports.string().describe("Full URL path"), - /** - * Object this endpoint operates on - */ - object: external_exports.string().describe("Object name (snake_case)"), - /** - * Operation type - */ - operation: external_exports.union([CrudOperation2, external_exports.string()]).describe("Operation type"), - /** - * Handler reference - */ - handler: external_exports.string().describe("Handler function identifier"), - /** - * Endpoint metadata - */ - metadata: external_exports.object({ - summary: external_exports.string().optional(), - description: external_exports.string().optional(), - tags: external_exports.array(external_exports.string()).optional(), - deprecated: external_exports.boolean().optional() - }).optional() -}); -var EndpointRegistrySchema2 = external_exports.object({ - /** - * Generated endpoints - */ - endpoints: external_exports.array(GeneratedEndpointSchema2).describe("All generated endpoints"), - /** - * Total endpoint count - */ - total: external_exports.number().int().describe("Total number of endpoints"), - /** - * Endpoints by object - */ - byObject: external_exports.record(external_exports.string(), external_exports.array(GeneratedEndpointSchema2)).optional().describe("Endpoints grouped by object"), - /** - * Endpoints by operation - */ - byOperation: external_exports.record(external_exports.string(), external_exports.array(GeneratedEndpointSchema2)).optional().describe("Endpoints grouped by operation") -}); -var RestApiConfig2 = Object.assign(RestApiConfigSchema2, { - create: (config4) => config4 -}); -var RestServerConfig2 = Object.assign(RestServerConfigSchema2, { - create: (config4) => config4 -}); -var ApiProtocolType2 = external_exports.enum([ - "rest", - // RESTful API (CRUD operations) - "graphql", - // GraphQL API (flexible queries) - "odata", - // OData v4 API (enterprise integration) - "websocket", - // WebSocket API (real-time) - "file", - // File/Storage API (uploads/downloads) - "auth", - // Authentication/Authorization API - "metadata", - // Metadata/Schema API - "plugin", - // Plugin-registered custom API - "webhook", - // Webhook endpoints - "rpc" - // JSON-RPC or similar -]); -var HttpStatusCode2 = external_exports.union([ - external_exports.number().int().min(100).max(599), - external_exports.enum(["2xx", "3xx", "4xx", "5xx"]) - // Pattern matching -]); -var ObjectQLReferenceSchema2 = external_exports.object({ - /** Referenced object name (snake_case) */ - objectId: SnakeCaseIdentifierSchema7.describe("Object name to reference"), - /** Include only specific fields (optional) */ - includeFields: external_exports.array(external_exports.string()).optional().describe("Include only these fields in the schema"), - /** Exclude specific fields (optional) */ - excludeFields: external_exports.array(external_exports.string()).optional().describe("Exclude these fields from the schema"), - /** Include related objects via lookup fields */ - includeRelated: external_exports.array(external_exports.string()).optional().describe("Include related objects via lookup fields") -}); -var SchemaDefinition2 = external_exports.union([ - external_exports.unknown().describe("Static JSON Schema definition"), - external_exports.object({ - $ref: ObjectQLReferenceSchema2.describe("Dynamic reference to ObjectQL object") - }).describe("Dynamic ObjectQL reference") -]); -var ApiParameterSchema2 = external_exports.object({ - /** Parameter name */ - name: external_exports.string().describe("Parameter name"), - /** Parameter location */ - in: external_exports.enum(["path", "query", "header", "body", "cookie"]).describe("Parameter location"), - /** Parameter description */ - description: external_exports.string().optional().describe("Parameter description"), - /** Required flag */ - required: external_exports.boolean().default(false).describe("Whether parameter is required"), - /** Parameter type/schema - supports static or dynamic (ObjectQL) schemas */ - schema: external_exports.union([ - external_exports.object({ - type: external_exports.enum(["string", "number", "integer", "boolean", "array", "object"]).describe("Parameter type"), - format: external_exports.string().optional().describe("Format (e.g., date-time, email, uuid)"), - enum: external_exports.array(external_exports.unknown()).optional().describe("Allowed values"), - default: external_exports.unknown().optional().describe("Default value"), - items: external_exports.unknown().optional().describe("Array item schema"), - properties: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Object properties") - }).describe("Static JSON Schema"), - external_exports.object({ - $ref: ObjectQLReferenceSchema2 - }).describe("Dynamic ObjectQL reference") - ]).describe("Parameter schema definition"), - /** Example value */ - example: external_exports.unknown().optional().describe("Example value") -}); -var ApiResponseSchema2 = external_exports.object({ - /** HTTP status code */ - statusCode: HttpStatusCode2.describe("HTTP status code"), - /** Response description */ - description: external_exports.string().describe("Response description"), - /** Response content type */ - contentType: external_exports.string().default("application/json").describe("Response content type"), - /** Response schema - supports static or dynamic (ObjectQL) schemas */ - schema: external_exports.union([ - external_exports.unknown().describe("Static JSON Schema"), - external_exports.object({ - $ref: ObjectQLReferenceSchema2 - }).describe("Dynamic ObjectQL reference") - ]).optional().describe("Response body schema"), - /** Response headers */ - headers: external_exports.record(external_exports.string(), external_exports.object({ - description: external_exports.string().optional(), - schema: external_exports.unknown() - })).optional().describe("Response headers"), - /** Example response */ - example: external_exports.unknown().optional().describe("Example response") -}); -var ApiEndpointRegistrationSchema2 = external_exports.object({ - /** Unique endpoint identifier */ - id: external_exports.string().describe("Unique endpoint identifier"), - /** HTTP method (for HTTP-based APIs) */ - method: HttpMethod5.optional().describe("HTTP method"), - /** URL path pattern */ - path: external_exports.string().describe("URL path pattern"), - /** Short summary */ - summary: external_exports.string().optional().describe("Short endpoint summary"), - /** Detailed description */ - description: external_exports.string().optional().describe("Detailed endpoint description"), - /** Operation ID (OpenAPI) */ - operationId: external_exports.string().optional().describe("Unique operation identifier"), - /** Tags for grouping */ - tags: external_exports.array(external_exports.string()).optional().default([]).describe("Tags for categorization"), - /** Parameters */ - parameters: external_exports.array(ApiParameterSchema2).optional().default([]).describe("Endpoint parameters"), - /** Request body schema */ - requestBody: external_exports.object({ - description: external_exports.string().optional(), - required: external_exports.boolean().default(false), - contentType: external_exports.string().default("application/json"), - schema: external_exports.unknown().optional(), - example: external_exports.unknown().optional() - }).optional().describe("Request body specification"), - /** Response definitions */ - responses: external_exports.array(ApiResponseSchema2).optional().default([]).describe("Possible responses"), - /** Rate Limiting */ - rateLimit: RateLimitConfigSchema4.optional().describe("Endpoint specific rate limiting"), - /** Security Requirements */ - security: external_exports.array(external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))).optional().describe('Security requirements (e.g. [{"bearerAuth": []}])'), - /** - * Required Permissions (RBAC Integration) - * - * Array of permission names required to access this endpoint. - * The gateway layer automatically validates these permissions before - * allowing the request to proceed, eliminating the need for permission - * checks in individual API handlers. - * - * **Format:** `.` or system permission name - * - * **Object Permissions:** - * - `customer.read` - Read customer records - * - `customer.create` - Create customer records - * - `customer.edit` - Update customer records - * - `customer.delete` - Delete customer records - * - `customer.viewAll` - View all customer records (bypass sharing) - * - `customer.modifyAll` - Modify all customer records (bypass sharing) - * - * **System Permissions:** - * - `manage_users` - User management - * - `view_setup` - Access to system setup - * - `customize_application` - Modify metadata - * - `api_enabled` - API access - * - * @example Object-level permissions - * ```json - * { - * "requiredPermissions": ["customer.read"] - * } - * ``` - * - * @example Multiple permissions (ALL required) - * ```json - * { - * "requiredPermissions": ["customer.read", "account.read"] - * } - * ``` - * - * @example System permission - * ```json - * { - * "requiredPermissions": ["manage_users"] - * } - * ``` - * - * @see {@link file://../../permission/permission.zod.ts} for permission definitions - */ - requiredPermissions: external_exports.array(external_exports.string()).optional().default([]).describe('Required RBAC permissions (e.g., "customer.read", "manage_users")'), - /** - * Route Priority - * - * Priority level for route conflict resolution. Higher priority routes - * are registered first and take precedence when multiple routes match - * the same path pattern. - * - * **Default:** 100 (medium priority) - * **Range:** 0-1000 (higher = more important) - * - * **Use Cases:** - * - Core system APIs: 900-1000 - * - Plugin APIs: 100-500 - * - Custom/override APIs: 500-900 - * - Fallback routes: 0-100 - * - * @example High priority core endpoint - * ```json - * { - * "path": "/api/v1/data/:object/:id", - * "priority": 950 - * } - * ``` - * - * @example Medium priority plugin endpoint - * ```json - * { - * "path": "/api/v1/custom/action", - * "priority": 300 - * } - * ``` - */ - priority: external_exports.number().int().min(0).max(1e3).optional().default(100).describe("Route priority for conflict resolution (0-1000, higher = more important)"), - /** - * Protocol-Specific Configuration - * - * Allows plugins and custom APIs to define protocol-specific metadata - * that can be used for specialized handling or documentation generation. - * - * **Examples:** - * - gRPC: Service and method names - * - tRPC: Procedure type (query/mutation) - * - WebSocket: Event names and handlers - * - Custom protocols: Any metadata needed - * - * @example gRPC configuration - * ```json - * { - * "protocolConfig": { - * "subProtocol": "grpc", - * "serviceName": "CustomerService", - * "methodName": "GetCustomer", - * "streaming": false - * } - * } - * ``` - * - * @example tRPC configuration - * ```json - * { - * "protocolConfig": { - * "subProtocol": "trpc", - * "procedureType": "query", - * "router": "customer" - * } - * } - * ``` - * - * @example WebSocket configuration - * ```json - * { - * "protocolConfig": { - * "subProtocol": "websocket", - * "eventName": "customer.updated", - * "direction": "server-to-client" - * } - * } - * ``` - */ - protocolConfig: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)"), - /** Deprecation flag */ - deprecated: external_exports.boolean().default(false).describe("Whether endpoint is deprecated"), - /** External documentation */ - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional().describe("External documentation link") -}); -var ApiMetadataSchema2 = external_exports.object({ - /** API owner/team */ - owner: external_exports.string().optional().describe("Owner team or person"), - /** API status */ - status: external_exports.enum(["active", "deprecated", "experimental", "beta"]).default("active").describe("API lifecycle status"), - /** Categorization tags */ - tags: external_exports.array(external_exports.string()).optional().default([]).describe("Classification tags"), - /** Plugin source (if plugin-registered) */ - pluginSource: external_exports.string().optional().describe("Source plugin name"), - /** Custom metadata */ - custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata fields") -}); -var ApiRegistryEntrySchema2 = external_exports.object({ - /** Unique API identifier */ - id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique API identifier (snake_case)"), - /** Human-readable name */ - name: external_exports.string().describe("API display name"), - /** API protocol type */ - type: ApiProtocolType2.describe("API protocol type"), - /** API version */ - version: external_exports.string().describe("API version (e.g., v1, 2024-01)"), - /** Base URL path */ - basePath: external_exports.string().describe("Base URL path for this API"), - /** API description */ - description: external_exports.string().optional().describe("API description"), - /** Endpoints in this API */ - endpoints: external_exports.array(ApiEndpointRegistrationSchema2).describe("Registered endpoints"), - /** OpenAPI/GraphQL/OData specific configuration */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Protocol-specific configuration"), - /** API metadata */ - metadata: ApiMetadataSchema2.optional().describe("Additional metadata"), - /** Terms of service URL */ - termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), - /** Contact information */ - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().url().optional(), - email: external_exports.string().email().optional() - }).optional().describe("Contact information"), - /** License information */ - license: external_exports.object({ - name: external_exports.string(), - url: external_exports.string().url().optional() - }).optional().describe("License information") -}); -var ConflictResolutionStrategy2 = external_exports.enum([ - "error", - // Throw error on conflict (safest, default) - "priority", - // Use priority field to resolve (highest priority wins) - "first-wins", - // First registered endpoint wins - "last-wins" - // Last registered endpoint wins (override mode) -]); -var ApiRegistrySchema2 = external_exports.object({ - /** Registry version */ - version: external_exports.string().describe("Registry version"), - /** - * Conflict Resolution Strategy - * - * Defines how to handle route conflicts when multiple endpoints - * register the same or overlapping URL patterns. - * - * **Strategies:** - * - `error`: Throw error on conflict (safest, prevents silent overwrites) - * - `priority`: Use endpoint priority field (highest priority wins) - * - `first-wins`: First registered endpoint wins (stable, predictable) - * - `last-wins`: Last registered endpoint wins (allows overrides) - * - * **Default:** `error` - * - * **Best Practices:** - * - Use `error` in production to catch configuration issues - * - Use `priority` when mixing core and plugin APIs - * - Use `last-wins` for development/testing overrides - * - * @example Prevent accidental conflicts - * ```json - * { - * "conflictResolution": "error" - * } - * ``` - * - * @example Allow plugin overrides with priority - * ```json - * { - * "conflictResolution": "priority" - * } - * ``` - */ - conflictResolution: ConflictResolutionStrategy2.optional().default("error").describe("Strategy for handling route conflicts"), - /** Registered APIs */ - apis: external_exports.array(ApiRegistryEntrySchema2).describe("All registered APIs"), - /** Total API count */ - totalApis: external_exports.number().int().describe("Total number of registered APIs"), - /** Total endpoint count across all APIs */ - totalEndpoints: external_exports.number().int().describe("Total number of endpoints"), - /** APIs grouped by type */ - byType: external_exports.record(ApiProtocolType2, external_exports.array(ApiRegistryEntrySchema2)).optional().describe("APIs grouped by protocol type"), - /** APIs grouped by status */ - byStatus: external_exports.record(external_exports.string(), external_exports.array(ApiRegistryEntrySchema2)).optional().describe("APIs grouped by status"), - /** Last updated timestamp */ - updatedAt: external_exports.string().datetime().optional().describe("Last registry update time") -}); -var ApiDiscoveryQuerySchema2 = external_exports.object({ - /** Filter by API type */ - type: ApiProtocolType2.optional().describe("Filter by API protocol type"), - /** Filter by tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Filter by tags (ANY match)"), - /** Filter by status */ - status: external_exports.enum(["active", "deprecated", "experimental", "beta"]).optional().describe("Filter by lifecycle status"), - /** Filter by plugin source */ - pluginSource: external_exports.string().optional().describe("Filter by plugin name"), - /** Search in name/description */ - search: external_exports.string().optional().describe("Full-text search in name/description"), - /** Filter by version */ - version: external_exports.string().optional().describe("Filter by specific version") -}); -var ApiDiscoveryResponseSchema2 = external_exports.object({ - /** Matching APIs */ - apis: external_exports.array(ApiRegistryEntrySchema2).describe("Matching API entries"), - /** Total matches */ - total: external_exports.number().int().describe("Total matching APIs"), - /** Applied filters */ - filters: ApiDiscoveryQuerySchema2.optional().describe("Applied query filters") -}); -var ApiEndpointRegistration2 = Object.assign(ApiEndpointRegistrationSchema2, { - create: (config4) => config4 -}); -var ApiRegistryEntry2 = Object.assign(ApiRegistryEntrySchema2, { - create: (config4) => config4 -}); -var ApiRegistry2 = Object.assign(ApiRegistrySchema2, { - create: (config4) => config4 -}); -var OpenApiServerSchema2 = external_exports.object({ - /** Server URL */ - url: external_exports.string().url().describe("Server base URL"), - /** Server description */ - description: external_exports.string().optional().describe("Server description"), - /** Server variables */ - variables: external_exports.record(external_exports.string(), external_exports.object({ - default: external_exports.string(), - description: external_exports.string().optional(), - enum: external_exports.array(external_exports.string()).optional() - })).optional().describe("URL template variables") -}); -var OpenApiSecuritySchemeSchema2 = external_exports.object({ - /** Security scheme type */ - type: external_exports.enum(["apiKey", "http", "oauth2", "openIdConnect"]).describe("Security type"), - /** Scheme name */ - scheme: external_exports.string().optional().describe("HTTP auth scheme (bearer, basic, etc.)"), - /** Bearer format */ - bearerFormat: external_exports.string().optional().describe("Bearer token format (e.g., JWT)"), - /** API key name */ - name: external_exports.string().optional().describe("API key parameter name"), - /** API key location */ - in: external_exports.enum(["header", "query", "cookie"]).optional().describe("API key location"), - /** OAuth flows */ - flows: external_exports.object({ - implicit: external_exports.unknown().optional(), - password: external_exports.unknown().optional(), - clientCredentials: external_exports.unknown().optional(), - authorizationCode: external_exports.unknown().optional() - }).optional().describe("OAuth2 flows"), - /** OpenID Connect URL */ - openIdConnectUrl: external_exports.string().url().optional().describe("OpenID Connect discovery URL"), - /** Description */ - description: external_exports.string().optional().describe("Security scheme description") -}); -var OpenApiSpecSchema2 = external_exports.object({ - /** OpenAPI version */ - openapi: external_exports.string().default("3.0.0").describe("OpenAPI specification version"), - /** API information */ - info: external_exports.object({ - title: external_exports.string().describe("API title"), - version: external_exports.string().describe("API version"), - description: external_exports.string().optional().describe("API description"), - termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().url().optional(), - email: external_exports.string().email().optional() - }).optional(), - license: external_exports.object({ - name: external_exports.string(), - url: external_exports.string().url().optional() - }).optional() - }).describe("API metadata"), - /** Servers */ - servers: external_exports.array(OpenApiServerSchema2).optional().default([]).describe("API servers"), - /** API paths */ - paths: external_exports.record(external_exports.string(), external_exports.unknown()).describe("API paths and operations"), - /** Reusable components */ - components: external_exports.object({ - schemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - responses: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - examples: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - requestBodies: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - headers: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - securitySchemes: external_exports.record(external_exports.string(), OpenApiSecuritySchemeSchema2).optional(), - links: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), - callbacks: external_exports.record(external_exports.string(), external_exports.unknown()).optional() - }).optional().describe("Reusable components"), - /** Security requirements */ - security: external_exports.array(external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))).optional().describe("Global security requirements"), - /** Tags */ - tags: external_exports.array(external_exports.object({ - name: external_exports.string(), - description: external_exports.string().optional(), - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional() - })).optional().describe("Tag definitions"), - /** External documentation */ - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional().describe("External documentation") -}); -var ApiTestingUiType2 = external_exports.enum([ - "swagger-ui", - // Swagger UI - "redoc", - // Redoc - "rapidoc", - // RapiDoc - "stoplight", - // Stoplight Elements - "scalar", - // Scalar API Reference - "graphql-playground", - // GraphQL Playground - "graphiql", - // GraphiQL - "postman", - // Postman-like interface - "custom" - // Custom implementation -]); -var ApiTestingUiConfigSchema2 = external_exports.object({ - /** UI type */ - type: ApiTestingUiType2.describe("Testing UI implementation"), - /** UI path */ - path: external_exports.string().default("/api-docs").describe("URL path for documentation UI"), - /** UI theme */ - theme: external_exports.enum(["light", "dark", "auto"]).default("light").describe("UI color theme"), - /** Enable try-it-out feature */ - enableTryItOut: external_exports.boolean().default(true).describe("Enable interactive API testing"), - /** Enable filtering */ - enableFilter: external_exports.boolean().default(true).describe("Enable endpoint filtering"), - /** Enable CORS for testing */ - enableCors: external_exports.boolean().default(true).describe("Enable CORS for browser testing"), - /** Default expand depth for models */ - defaultModelsExpandDepth: external_exports.number().int().min(-1).default(1).describe("Default expand depth for schemas (-1 = fully expand)"), - /** Display request duration */ - displayRequestDuration: external_exports.boolean().default(true).describe("Show request duration"), - /** Syntax highlighting */ - syntaxHighlighting: external_exports.boolean().default(true).describe("Enable syntax highlighting"), - /** Custom CSS URL */ - customCssUrl: external_exports.string().url().optional().describe("Custom CSS stylesheet URL"), - /** Custom JavaScript URL */ - customJsUrl: external_exports.string().url().optional().describe("Custom JavaScript URL"), - /** Layout options */ - layout: external_exports.object({ - showExtensions: external_exports.boolean().default(false).describe("Show vendor extensions"), - showCommonExtensions: external_exports.boolean().default(false).describe("Show common extensions"), - deepLinking: external_exports.boolean().default(true).describe("Enable deep linking"), - displayOperationId: external_exports.boolean().default(false).describe("Display operation IDs"), - defaultModelRendering: external_exports.enum(["example", "model"]).default("example").describe("Default model rendering mode"), - defaultModelsExpandDepth: external_exports.number().int().default(1).describe("Models expand depth"), - defaultModelExpandDepth: external_exports.number().int().default(1).describe("Single model expand depth"), - docExpansion: external_exports.enum(["list", "full", "none"]).default("list").describe("Documentation expansion mode") - }).optional().describe("Layout configuration") -}); -var ApiTestRequestSchema2 = external_exports.object({ - /** Request name */ - name: external_exports.string().describe("Test request name"), - /** Request description */ - description: external_exports.string().optional().describe("Request description"), - /** HTTP method */ - method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]).describe("HTTP method"), - /** Request URL */ - url: external_exports.string().describe("Request URL (can include variables)"), - /** Request headers */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().default({}).describe("Request headers"), - /** Query parameters */ - queryParams: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().default({}).describe("Query parameters"), - /** Request body */ - body: external_exports.unknown().optional().describe("Request body"), - /** Environment variables */ - variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().default({}).describe("Template variables"), - /** Expected response */ - expectedResponse: external_exports.object({ - statusCode: external_exports.number().int(), - body: external_exports.unknown().optional() - }).optional().describe("Expected response for validation") -}); -var ApiTestCollectionSchema2 = external_exports.object({ - /** Collection name */ - name: external_exports.string().describe("Collection name"), - /** Collection description */ - description: external_exports.string().optional().describe("Collection description"), - /** Collection variables */ - variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().default({}).describe("Shared variables"), - /** Test requests */ - requests: external_exports.array(ApiTestRequestSchema2).describe("Test requests in this collection"), - /** Folders/grouping */ - folders: external_exports.array(external_exports.object({ - name: external_exports.string(), - description: external_exports.string().optional(), - requests: external_exports.array(ApiTestRequestSchema2) - })).optional().describe("Request folders for organization") -}); -var ApiChangelogEntrySchema2 = external_exports.object({ - /** Version */ - version: external_exports.string().describe("API version"), - /** Release date */ - date: external_exports.string().date().describe("Release date"), - /** Changes */ - changes: external_exports.object({ - added: external_exports.array(external_exports.string()).optional().default([]).describe("New features"), - changed: external_exports.array(external_exports.string()).optional().default([]).describe("Changes"), - deprecated: external_exports.array(external_exports.string()).optional().default([]).describe("Deprecations"), - removed: external_exports.array(external_exports.string()).optional().default([]).describe("Removed features"), - fixed: external_exports.array(external_exports.string()).optional().default([]).describe("Bug fixes"), - security: external_exports.array(external_exports.string()).optional().default([]).describe("Security fixes") - }).describe("Version changes"), - /** Migration guide */ - migrationGuide: external_exports.string().optional().describe("Migration guide URL or text") -}); -var CodeGenerationTemplateSchema2 = external_exports.object({ - /** Language/framework */ - language: external_exports.string().describe("Target language/framework (e.g., typescript, python, curl)"), - /** Template name */ - name: external_exports.string().describe("Template name"), - /** Template content */ - template: external_exports.string().describe("Code template with placeholders"), - /** Template variables */ - variables: external_exports.array(external_exports.string()).optional().describe("Required template variables") -}); -var ApiDocumentationConfigSchema2 = external_exports.object({ - /** Enable documentation */ - enabled: external_exports.boolean().default(true).describe("Enable API documentation"), - /** Documentation title */ - title: external_exports.string().default("API Documentation").describe("Documentation title"), - /** API version */ - version: external_exports.string().describe("API version"), - /** API description */ - description: external_exports.string().optional().describe("API description"), - /** Server configurations */ - servers: external_exports.array(OpenApiServerSchema2).optional().default([]).describe("API server URLs"), - /** UI configuration */ - ui: ApiTestingUiConfigSchema2.optional().describe("Testing UI configuration"), - /** Generate OpenAPI spec */ - generateOpenApi: external_exports.boolean().default(true).describe("Generate OpenAPI 3.0 specification"), - /** Generate test collections */ - generateTestCollections: external_exports.boolean().default(true).describe("Generate API test collections"), - /** Test collections */ - testCollections: external_exports.array(ApiTestCollectionSchema2).optional().default([]).describe("Predefined test collections"), - /** API changelog */ - changelog: external_exports.array(ApiChangelogEntrySchema2).optional().default([]).describe("API version changelog"), - /** Code generation templates */ - codeTemplates: external_exports.array(CodeGenerationTemplateSchema2).optional().default([]).describe("Code generation templates"), - /** Terms of service */ - termsOfService: external_exports.string().url().optional().describe("Terms of service URL"), - /** Contact information */ - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().url().optional(), - email: external_exports.string().email().optional() - }).optional().describe("Contact information"), - /** License */ - license: external_exports.object({ - name: external_exports.string(), - url: external_exports.string().url().optional() - }).optional().describe("API license"), - /** External documentation */ - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional().describe("External documentation link"), - /** Security schemes */ - securitySchemes: external_exports.record(external_exports.string(), OpenApiSecuritySchemeSchema2).optional().describe("Security scheme definitions"), - /** Global tags */ - tags: external_exports.array(external_exports.object({ - name: external_exports.string(), - description: external_exports.string().optional(), - externalDocs: external_exports.object({ - description: external_exports.string().optional(), - url: external_exports.string().url() - }).optional() - })).optional().describe("Global tag definitions") -}); -var GeneratedApiDocumentationSchema2 = external_exports.object({ - /** OpenAPI specification */ - openApiSpec: OpenApiSpecSchema2.optional().describe("Generated OpenAPI specification"), - /** Test collections */ - testCollections: external_exports.array(ApiTestCollectionSchema2).optional().describe("Generated test collections"), - /** Markdown documentation */ - markdown: external_exports.string().optional().describe("Generated markdown documentation"), - /** HTML documentation */ - html: external_exports.string().optional().describe("Generated HTML documentation"), - /** Generation timestamp */ - generatedAt: external_exports.string().datetime().describe("Generation timestamp"), - /** Source APIs */ - sourceApis: external_exports.array(external_exports.string()).describe("Source API IDs used for generation") -}); -var ApiDocumentationConfig2 = Object.assign(ApiDocumentationConfigSchema2, { - create: (config4) => config4 -}); -var ApiTestCollection2 = Object.assign(ApiTestCollectionSchema2, { - create: (config4) => config4 -}); -var OpenApiSpec2 = Object.assign(OpenApiSpecSchema2, { - create: (config4) => config4 -}); -var AnalyticsEndpoint2 = external_exports.enum([ - "/api/v1/analytics/query", - // Execute analysis - "/api/v1/analytics/meta", - // Discover cubes/metrics - "/api/v1/analytics/sql" - // Dry-run SQL generation -]); -var AnalyticsQueryRequestSchema2 = external_exports.object({ - query: AnalyticsQuerySchema3.describe("The analytic query definition"), - cube: external_exports.string().describe("Target cube name"), - format: external_exports.enum(["json", "csv", "xlsx"]).default("json").describe("Response format") -}); -var AnalyticsResultResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - rows: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Result rows"), - fields: external_exports.array(external_exports.object({ - name: external_exports.string(), - type: external_exports.string() - })).describe("Column metadata"), - sql: external_exports.string().optional().describe("Executed SQL (if debug enabled)") - }) -}); -var GetAnalyticsMetaRequestSchema2 = external_exports.object({ - cube: external_exports.string().optional().describe("Optional cube name to filter") -}); -var AnalyticsMetadataResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - cubes: external_exports.array(CubeSchema3).describe("Available cubes") - }) -}); -var AnalyticsSqlResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - sql: external_exports.string(), - params: external_exports.array(external_exports.unknown()) - }) -}); -var VersioningStrategy2 = external_exports.enum([ - "urlPath", - "header", - "queryParam", - "dateBased" -]); -var VersionStatus2 = external_exports.enum([ - "preview", - "current", - "supported", - "deprecated", - "retired" -]); -var VersionDefinitionSchema2 = external_exports.object({ - /** Version identifier (e.g., "v1", "v2beta1", "2025-01-01") */ - version: external_exports.string().describe('Version identifier (e.g., "v1", "v2beta1", "2025-01-01")'), - /** Current lifecycle status */ - status: VersionStatus2.describe("Lifecycle status of this version"), - /** Date this version was released (ISO 8601 date) */ - releasedAt: external_exports.string().describe('Release date (ISO 8601, e.g., "2025-01-15")'), - /** Date this version was deprecated (ISO 8601 date) */ - deprecatedAt: external_exports.string().optional().describe("Deprecation date (ISO 8601). Only set for deprecated/retired versions"), - /** Date this version will be retired (ISO 8601 date) */ - sunsetAt: external_exports.string().optional().describe("Sunset date (ISO 8601). After this date, the version returns 410 Gone"), - /** URL to migration guide for moving to a newer version */ - migrationGuide: external_exports.string().url().optional().describe("URL to migration guide for upgrading from this version"), - /** Human-readable description of this version */ - description: external_exports.string().optional().describe("Human-readable description or release notes summary"), - /** Breaking changes introduced in or since this version */ - breakingChanges: external_exports.array(external_exports.string()).optional().describe("List of breaking changes (for preview/new versions)") -}); -var VersioningConfigSchema23 = external_exports.object({ - /** Versioning strategy */ - strategy: VersioningStrategy2.default("urlPath").describe("How the API version is specified by clients"), - /** Current (recommended) API version */ - current: external_exports.string().describe("The current/recommended API version identifier"), - /** Default version when none specified by client */ - default: external_exports.string().describe("Fallback version when client does not specify one"), - /** All available API versions */ - versions: external_exports.array(VersionDefinitionSchema2).min(1).describe("All available API versions with lifecycle metadata"), - /** Header name for header-based versioning */ - headerName: external_exports.string().default("ObjectStack-Version").describe("HTTP header name for version negotiation (header/dateBased strategies)"), - /** Query parameter name for queryParam strategy */ - queryParamName: external_exports.string().default("version").describe("Query parameter name for version specification (queryParam strategy)"), - /** URL prefix pattern for urlPath strategy */ - urlPrefix: external_exports.string().default("/api").describe("URL prefix before version segment (urlPath strategy)"), - /** Deprecation behavior */ - deprecation: external_exports.object({ - /** Include Deprecation header in responses for deprecated versions */ - warnHeader: external_exports.boolean().default(true).describe("Include Deprecation header (RFC 8594) in responses"), - /** Include Sunset header with retirement date */ - sunsetHeader: external_exports.boolean().default(true).describe("Include Sunset header (RFC 8594) with retirement date"), - /** Include Link header pointing to migration guide */ - linkHeader: external_exports.boolean().default(true).describe("Include Link header pointing to migration guide URL"), - /** Whether to reject requests to retired versions */ - rejectRetired: external_exports.boolean().default(true).describe("Return 410 Gone for retired API versions"), - /** Custom deprecation warning message */ - warningMessage: external_exports.string().optional().describe("Custom warning message for deprecated version responses") - }).optional().describe("Deprecation lifecycle behavior"), - /** Whether to include version info in discovery response */ - includeInDiscovery: external_exports.boolean().default(true).describe("Include version information in the API discovery endpoint") -}); -var VersionNegotiationResponseSchema2 = external_exports.object({ - /** The current/recommended version */ - current: external_exports.string().describe("Current recommended API version"), - /** The version the client requested (if any) */ - requested: external_exports.string().optional().describe("Version requested by the client"), - /** The version actually being used for this request */ - resolved: external_exports.string().describe("Resolved API version for this request"), - /** All supported (non-retired) version identifiers */ - supported: external_exports.array(external_exports.string()).describe("All supported version identifiers"), - /** Deprecated version identifiers (still functional but will be removed) */ - deprecated: external_exports.array(external_exports.string()).optional().describe("Deprecated version identifiers"), - /** Full version definitions (optional, for detailed clients) */ - versions: external_exports.array(VersionDefinitionSchema2).optional().describe("Full version definitions with lifecycle metadata") -}); -var DEFAULT_VERSIONING_CONFIG = { - strategy: "urlPath", - current: "v1", - default: "v1", - versions: [ - { - version: "v1", - status: "current", - releasedAt: "2025-01-15", - description: "ObjectStack API v1 \u2014 Initial stable release" - } - ], - deprecation: { - warnHeader: true, - sunsetHeader: true, - linkHeader: true, - rejectRetired: true - }, - includeInDiscovery: true -}; -var AuthProvider2 = external_exports.enum([ - "local", - "google", - "github", - "microsoft", - "ldap", - "saml" -]); -var SessionUserSchema2 = external_exports.object({ - id: external_exports.string().describe("User ID"), - email: external_exports.string().email().describe("Email address"), - emailVerified: external_exports.boolean().default(false).describe("Is email verified?"), - name: external_exports.string().describe("Display name"), - image: external_exports.string().optional().describe("Avatar URL"), - username: external_exports.string().optional().describe("Username (optional)"), - roles: external_exports.array(external_exports.string()).optional().default([]).describe("Assigned role IDs"), - tenantId: external_exports.string().optional().describe("Current tenant ID"), - language: external_exports.string().default("en").describe("Preferred language"), - timezone: external_exports.string().optional().describe("Preferred timezone"), - createdAt: external_exports.string().datetime().optional(), - updatedAt: external_exports.string().datetime().optional() -}); -var SessionSchema22 = external_exports.object({ - id: external_exports.string(), - expiresAt: external_exports.string().datetime(), - token: external_exports.string().optional(), - ipAddress: external_exports.string().optional(), - userAgent: external_exports.string().optional(), - userId: external_exports.string() -}); -var LoginType2 = external_exports.enum(["email", "username", "phone", "magic-link", "social"]); -var LoginRequestSchema2 = external_exports.object({ - type: LoginType2.default("email").describe("Login method"), - email: external_exports.string().email().optional().describe("Required for email/magic-link"), - username: external_exports.string().optional().describe("Required for username login"), - password: external_exports.string().optional().describe("Required for password login"), - provider: external_exports.string().optional().describe("Required for social (google, github)"), - redirectTo: external_exports.string().optional().describe("Redirect URL after successful login") -}); -var RegisterRequestSchema2 = external_exports.object({ - email: external_exports.string().email(), - password: external_exports.string(), - name: external_exports.string(), - image: external_exports.string().optional() -}); -var RefreshTokenRequestSchema2 = external_exports.object({ - refreshToken: external_exports.string().describe("Refresh token") -}); -var SessionResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - session: SessionSchema22.describe("Active Session Info"), - user: SessionUserSchema2.describe("Current User Details"), - token: external_exports.string().optional().describe("Bearer token if not using cookies") - }) -}); -var UserProfileResponseSchema2 = BaseResponseSchema2.extend({ - data: SessionUserSchema2 -}); -var AuthEndpointPaths2 = { - // Email/Password Authentication - signInEmail: "/sign-in/email", - signUpEmail: "/sign-up/email", - signOut: "/sign-out", - // Session Management - getSession: "/get-session", - // Password Management - forgetPassword: "/forget-password", - resetPassword: "/reset-password", - // Email Verification - sendVerificationEmail: "/send-verification-email", - verifyEmail: "/verify-email", - // OAuth (dynamic based on provider) - // authorize: '/authorize/:provider' - // callback: '/callback/:provider' - // 2FA (when enabled) - twoFactorEnable: "/two-factor/enable", - twoFactorVerify: "/two-factor/verify", - // Passkeys (when enabled) - passkeyRegister: "/passkey/register", - passkeyAuthenticate: "/passkey/authenticate", - // Magic Links (when enabled) - magicLinkSend: "/magic-link/send", - magicLinkVerify: "/magic-link/verify" -}; -var AuthEndpointSchema2 = external_exports.object({ - /** Sign in with email and password */ - signInEmail: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths2.signInEmail), - description: external_exports.literal("Sign in with email and password") - }), - /** Register new user with email and password */ - signUpEmail: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths2.signUpEmail), - description: external_exports.literal("Register new user with email and password") - }), - /** Sign out current user */ - signOut: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths2.signOut), - description: external_exports.literal("Sign out current user") - }), - /** Get current user session */ - getSession: external_exports.object({ - method: external_exports.literal("GET"), - path: external_exports.literal(AuthEndpointPaths2.getSession), - description: external_exports.literal("Get current user session") - }), - /** Request password reset email */ - forgetPassword: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths2.forgetPassword), - description: external_exports.literal("Request password reset email") - }), - /** Reset password with token */ - resetPassword: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths2.resetPassword), - description: external_exports.literal("Reset password with token") - }), - /** Send email verification */ - sendVerificationEmail: external_exports.object({ - method: external_exports.literal("POST"), - path: external_exports.literal(AuthEndpointPaths2.sendVerificationEmail), - description: external_exports.literal("Send email verification link") - }), - /** Verify email with token */ - verifyEmail: external_exports.object({ - method: external_exports.literal("GET"), - path: external_exports.literal(AuthEndpointPaths2.verifyEmail), - description: external_exports.literal("Verify email with token") - }) -}); -var AuthEndpointAliases2 = { - login: AuthEndpointPaths2.signInEmail, - register: AuthEndpointPaths2.signUpEmail, - logout: AuthEndpointPaths2.signOut, - me: AuthEndpointPaths2.getSession -}; -function getAuthEndpointUrl(basePath, endpoint) { - const cleanBase = basePath.replace(/\/$/, ""); - return `${cleanBase}${AuthEndpointPaths2[endpoint]}`; -} -var EndpointMapping2 = { - "/login": AuthEndpointPaths2.signInEmail, - "/register": AuthEndpointPaths2.signUpEmail, - "/logout": AuthEndpointPaths2.signOut, - "/me": AuthEndpointPaths2.getSession, - "/refresh": AuthEndpointPaths2.getSession - // Session refresh handled by better-auth automatically -}; -var GetPresignedUrlRequestSchema2 = external_exports.object({ - filename: external_exports.string().describe("Original filename"), - mimeType: external_exports.string().describe("File MIME type"), - size: external_exports.number().describe("File size in bytes"), - scope: external_exports.string().default("user").describe("Target storage scope (e.g. user, private, public)"), - bucket: external_exports.string().optional().describe("Specific bucket override (admin only)") -}); -var CompleteUploadRequestSchema2 = external_exports.object({ - fileId: external_exports.string().describe("File ID returned from presigned request"), - eTag: external_exports.string().optional().describe("S3 ETag verification") -}); -var PresignedUrlResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - uploadUrl: external_exports.string().describe("PUT/POST URL for direct upload"), - downloadUrl: external_exports.string().optional().describe("Public/Private preview URL"), - fileId: external_exports.string().describe("Temporary File ID"), - method: external_exports.enum(["PUT", "POST"]).describe("HTTP Method to use"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Required headers for upload"), - expiresIn: external_exports.number().describe("URL expiry in seconds") - }) -}); -var FileUploadResponseSchema2 = BaseResponseSchema2.extend({ - data: FileMetadataSchema3.describe("Uploaded file metadata") -}); -var FileTypeValidationSchema2 = external_exports.object({ - mode: external_exports.enum(["whitelist", "blacklist"]).describe("whitelist = only allow listed types, blacklist = block listed types"), - mimeTypes: external_exports.array(external_exports.string()).min(1).describe('List of MIME types to allow or block (e.g., "image/jpeg", "application/pdf")'), - extensions: external_exports.array(external_exports.string()).optional().describe('List of file extensions to allow or block (e.g., ".jpg", ".pdf")'), - maxFileSize: external_exports.number().int().min(1).optional().describe("Maximum file size in bytes"), - minFileSize: external_exports.number().int().min(0).optional().describe("Minimum file size in bytes (e.g., reject empty files)") -}); -var InitiateChunkedUploadRequestSchema2 = external_exports.object({ - filename: external_exports.string().describe("Original filename"), - mimeType: external_exports.string().describe("File MIME type"), - totalSize: external_exports.number().int().min(1).describe("Total file size in bytes"), - chunkSize: external_exports.number().int().min(5242880).default(5242880).describe("Size of each chunk in bytes (minimum 5MB per S3 spec)"), - scope: external_exports.string().default("user").describe("Target storage scope"), - bucket: external_exports.string().optional().describe("Specific bucket override (admin only)"), - metadata: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom metadata key-value pairs") -}); -var InitiateChunkedUploadResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - uploadId: external_exports.string().describe("Multipart upload session ID"), - resumeToken: external_exports.string().describe("Opaque token for resuming interrupted uploads"), - fileId: external_exports.string().describe("Assigned file ID"), - totalChunks: external_exports.number().int().min(1).describe("Expected number of chunks"), - chunkSize: external_exports.number().int().describe("Chunk size in bytes"), - expiresAt: external_exports.string().datetime().describe("Upload session expiration timestamp") - }) -}); -var UploadChunkRequestSchema2 = external_exports.object({ - uploadId: external_exports.string().describe("Multipart upload session ID"), - chunkIndex: external_exports.number().int().min(0).describe("Zero-based chunk index"), - resumeToken: external_exports.string().describe("Resume token from initiate response") -}); -var UploadChunkResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - chunkIndex: external_exports.number().int().describe("Chunk index that was uploaded"), - eTag: external_exports.string().describe("Chunk ETag for multipart completion"), - bytesReceived: external_exports.number().int().describe("Bytes received for this chunk") - }) -}); -var CompleteChunkedUploadRequestSchema2 = external_exports.object({ - uploadId: external_exports.string().describe("Multipart upload session ID"), - parts: external_exports.array(external_exports.object({ - chunkIndex: external_exports.number().int().describe("Chunk index"), - eTag: external_exports.string().describe("ETag returned from chunk upload") - })).min(1).describe("Ordered list of uploaded parts for assembly") -}); -var CompleteChunkedUploadResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - fileId: external_exports.string().describe("Final file ID"), - key: external_exports.string().describe("Storage key/path of the assembled file"), - size: external_exports.number().int().describe("Total file size in bytes"), - mimeType: external_exports.string().describe("File MIME type"), - eTag: external_exports.string().optional().describe("Final ETag of the assembled file"), - url: external_exports.string().optional().describe("Download URL for the assembled file") - }) -}); -var UploadProgressSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - uploadId: external_exports.string().describe("Multipart upload session ID"), - fileId: external_exports.string().describe("Assigned file ID"), - filename: external_exports.string().describe("Original filename"), - totalSize: external_exports.number().int().describe("Total file size in bytes"), - uploadedSize: external_exports.number().int().describe("Bytes uploaded so far"), - totalChunks: external_exports.number().int().describe("Total expected chunks"), - uploadedChunks: external_exports.number().int().describe("Number of chunks uploaded"), - percentComplete: external_exports.number().min(0).max(100).describe("Upload progress percentage"), - status: external_exports.enum(["in_progress", "completing", "completed", "failed", "expired"]).describe("Current upload session status"), - startedAt: external_exports.string().datetime().describe("Upload session start timestamp"), - expiresAt: external_exports.string().datetime().describe("Session expiration timestamp") - }) -}); -var StorageApiContracts = { - getPresignedUrl: { - method: "POST", - path: "/api/v1/storage/upload/presigned", - input: GetPresignedUrlRequestSchema2, - output: PresignedUrlResponseSchema2 - }, - completeUpload: { - method: "POST", - path: "/api/v1/storage/upload/complete", - input: CompleteUploadRequestSchema2, - output: FileUploadResponseSchema2 - }, - initiateChunkedUpload: { - method: "POST", - path: "/api/v1/storage/upload/chunked", - input: InitiateChunkedUploadRequestSchema2, - output: InitiateChunkedUploadResponseSchema2 - }, - uploadChunk: { - method: "PUT", - path: "/api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex", - input: UploadChunkRequestSchema2, - output: UploadChunkResponseSchema2 - }, - completeChunkedUpload: { - method: "POST", - path: "/api/v1/storage/upload/chunked/:uploadId/complete", - input: CompleteChunkedUploadRequestSchema2, - output: CompleteChunkedUploadResponseSchema2 - }, - getUploadProgress: { - method: "GET", - path: "/api/v1/storage/upload/chunked/:uploadId/progress", - output: UploadProgressSchema2 - } -}; -var ObjectDefinitionResponseSchema2 = BaseResponseSchema2.extend({ - data: ObjectSchema4.describe("Full Object Schema") -}); -var AppDefinitionResponseSchema2 = BaseResponseSchema2.extend({ - data: AppSchema3.describe("Full App Configuration") -}); -var ConceptListResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.array(external_exports.object({ - name: external_exports.string(), - label: external_exports.string(), - icon: external_exports.string().optional(), - description: external_exports.string().optional() - })).describe("List of available concepts (Objects, Apps, Flows)") -}); -var MetadataRegisterRequestSchema2 = external_exports.object({ - type: MetadataTypeSchema3.describe("Metadata type"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Item name (snake_case)"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload"), - namespace: external_exports.string().optional().describe("Optional namespace") -}); -var MetadataItemResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - definition: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata definition payload") - }).describe("Metadata item") -}); -var MetadataListResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).describe("Array of metadata definitions") -}); -var MetadataNamesResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.array(external_exports.string()).describe("Array of metadata item names") -}); -var MetadataExistsResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - exists: external_exports.boolean().describe("Whether the item exists") - }) -}); -var MetadataDeleteResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Deleted item name") - }) -}); -var MetadataQueryRequestSchema2 = MetadataQuerySchema3.describe( - "Metadata query with filtering, sorting, and pagination" -); -var MetadataQueryResponseSchema2 = BaseResponseSchema2.extend({ - data: MetadataQueryResultSchema3.describe("Paginated query result") -}); -var MetadataBulkRegisterRequestSchema22 = external_exports.object({ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name"), - data: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Metadata payload") - })).min(1).describe("Items to register"), - continueOnError: external_exports.boolean().default(false).describe("Continue on individual failure"), - validate: external_exports.boolean().default(true).describe("Validate before registering") -}); -var MetadataBulkUnregisterRequestSchema2 = external_exports.object({ - items: external_exports.array(external_exports.object({ - type: external_exports.string().describe("Metadata type"), - name: external_exports.string().describe("Item name") - })).min(1).describe("Items to unregister") -}); -var MetadataBulkResponseSchema2 = BaseResponseSchema2.extend({ - data: MetadataBulkResultSchema3.describe("Bulk operation result") -}); -var MetadataOverlayResponseSchema2 = BaseResponseSchema2.extend({ - data: MetadataOverlaySchema3.optional().describe("Overlay definition, undefined if none") -}); -var MetadataOverlaySaveRequestSchema2 = MetadataOverlaySchema3.describe( - "Overlay to save" -); -var MetadataEffectiveResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Effective metadata with all overlays applied") -}); -var MetadataExportRequestSchema2 = external_exports.object({ - types: external_exports.array(external_exports.string()).optional().describe("Filter by metadata types"), - namespaces: external_exports.array(external_exports.string()).optional().describe("Filter by namespaces"), - format: external_exports.enum(["json", "yaml"]).default("json").describe("Export format") -}); -var MetadataExportResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.unknown().describe("Exported metadata bundle") -}); -var MetadataImportRequestSchema2 = external_exports.object({ - data: external_exports.unknown().describe("Metadata bundle to import"), - conflictResolution: external_exports.enum(["skip", "overwrite", "merge"]).default("skip").describe("Conflict resolution strategy"), - validate: external_exports.boolean().default(true).describe("Validate before import"), - dryRun: external_exports.boolean().default(false).describe("Dry run (no save)") -}); -var MetadataImportResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - total: external_exports.number().int().min(0), - imported: external_exports.number().int().min(0), - skipped: external_exports.number().int().min(0), - failed: external_exports.number().int().min(0), - errors: external_exports.array(external_exports.object({ - type: external_exports.string(), - name: external_exports.string(), - error: external_exports.string() - })).optional() - }).describe("Import result") -}); -var MetadataValidateRequestSchema2 = external_exports.object({ - type: external_exports.string().describe("Metadata type to validate against"), - data: external_exports.unknown().describe("Metadata payload to validate") -}); -var MetadataValidateResponseSchema2 = BaseResponseSchema2.extend({ - data: MetadataValidationResultSchema3.describe("Validation result") -}); -var MetadataTypesResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.array(external_exports.string()).describe("Registered metadata type identifiers") -}); -var MetadataTypeInfoResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - type: external_exports.string().describe("Metadata type identifier"), - label: external_exports.string().describe("Display label"), - description: external_exports.string().optional().describe("Description"), - filePatterns: external_exports.array(external_exports.string()).describe("File glob patterns"), - supportsOverlay: external_exports.boolean().describe("Overlay support"), - domain: external_exports.string().describe("Protocol domain") - }).optional().describe("Type info") -}); -var MetadataDependenciesResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.array(MetadataDependencySchema3).describe("Items this item depends on") -}); -var MetadataDependentsResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.array(MetadataDependencySchema3).describe("Items that depend on this item") -}); -var DispatcherRouteSchema2 = external_exports.object({ - /** - * URL path prefix for routing. - * Incoming requests matching this prefix are routed to the target service. - * Must start with '/'. - */ - prefix: external_exports.string().regex(/^\//).describe("URL path prefix for routing (e.g. /api/v1/data)"), - /** - * Target core service name. - * The service that handles requests matching this prefix. - */ - service: CoreServiceName3.describe("Target core service name"), - /** - * Whether requests to this route require authentication. - * Discovery endpoint is typically public; most others require auth. - * @default true - */ - authRequired: external_exports.boolean().default(true).describe("Whether authentication is required"), - /** - * Service criticality level. - * Determines behavior when the service is unavailable: - * - required: return 500 Internal Server Error - * - core: return 503 with degraded notice - * - optional: return 503 Service Unavailable - * @default 'optional' - */ - criticality: ServiceCriticalitySchema3.default("optional").describe("Service criticality level for unavailability handling"), - /** - * Required permissions for accessing this route namespace. - * Applied as a baseline before individual endpoint permission checks. - */ - permissions: external_exports.array(external_exports.string()).optional().describe("Required permissions for this route namespace") -}); -var DispatcherConfigSchema2 = external_exports.object({ - /** - * Registered route mappings. - * Routes are matched by longest-prefix-first strategy. - */ - routes: external_exports.array(DispatcherRouteSchema2).describe("Route-to-service mappings"), - /** - * Behavior when no route matches the request. - * - 404: Return 404 Not Found (default) - * - proxy: Forward to a configured proxy target - * - custom: Delegate to a custom handler - * @default '404' - */ - fallback: external_exports.enum(["404", "proxy", "custom"]).default("404").describe("Behavior when no route matches"), - /** - * Proxy target URL for fallback: 'proxy' mode. - */ - proxyTarget: external_exports.string().url().optional().describe('Proxy target URL when fallback is "proxy"') -}); -var DEFAULT_DISPATCHER_ROUTES = [ - // Discovery (public) - { prefix: "/api/v1/discovery", service: "metadata", authRequired: false, criticality: "required" }, - // Health (public) - { prefix: "/api/v1/health", service: "metadata", authRequired: false, criticality: "required" }, - // Required Services - { prefix: "/api/v1/meta", service: "metadata", criticality: "required" }, - { prefix: "/api/v1/data", service: "data", criticality: "required" }, - { prefix: "/api/v1/auth", service: "auth", criticality: "required" }, - // Optional Services (plugin-provided) - { prefix: "/api/v1/packages", service: "metadata" }, - { prefix: "/api/v1/ui", service: "ui" }, - // @deprecated — use /api/v1/meta/view and /api/v1/meta/dashboard instead - { prefix: "/api/v1/workflow", service: "workflow" }, - { prefix: "/api/v1/analytics", service: "analytics" }, - { prefix: "/api/v1/automation", service: "automation" }, - { prefix: "/api/v1/storage", service: "file-storage" }, - { prefix: "/api/v1/feed", service: "data" }, - { prefix: "/api/v1/i18n", service: "i18n" }, - { prefix: "/api/v1/notifications", service: "notification" }, - { prefix: "/api/v1/realtime", service: "realtime" }, - { prefix: "/api/v1/ai", service: "ai" } -]; -var DispatcherErrorCode2 = external_exports.enum(["404", "405", "501", "503"]).describe( - "404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable" -); -var DispatcherErrorResponseSchema2 = external_exports.object({ - /** Always `false` for error responses */ - success: external_exports.literal(false), - error: external_exports.object({ - /** HTTP status code */ - code: external_exports.number().int().describe("HTTP status code (404, 405, 501, 503, \u2026)"), - /** Human-readable error message */ - message: external_exports.string().describe("Human-readable error message"), - /** - * Machine-readable error type for programmatic branching. - */ - type: external_exports.enum([ - "ROUTE_NOT_FOUND", - "METHOD_NOT_ALLOWED", - "NOT_IMPLEMENTED", - "SERVICE_UNAVAILABLE" - ]).optional().describe("Machine-readable error type"), - /** Route that was requested */ - route: external_exports.string().optional().describe("Requested route path"), - /** Service that the route maps to (if known) */ - service: external_exports.string().optional().describe("Target service name, if resolvable"), - /** Guidance for the developer */ - hint: external_exports.string().optional().describe('Actionable hint for the developer (e.g., "Install plugin-workflow")') - }) -}); -var RestApiRouteCategory2 = external_exports.enum([ - "discovery", - // API discovery and capabilities - "metadata", - // Metadata operations (objects, fields, views) - "data", - // Data CRUD operations - "batch", - // Batch/bulk operations - "permission", - // Permission/authorization checks - "analytics", - // Analytics and reporting - "automation", - // Automation triggers and flows - "workflow", - // Workflow state management - "ui", - // UI metadata (views, layouts) - "realtime", - // Realtime/WebSocket - "notification", - // Notification management - "ai", - // AI operations (NLQ, chat) - "i18n" - // Internationalization -]); -var HandlerStatusSchema2 = external_exports.enum(["implemented", "stub", "planned"]); -var RestApiEndpointSchema2 = external_exports.object({ - /** - * HTTP method - */ - method: HttpMethod5.describe("HTTP method for this endpoint"), - /** - * URL path pattern (supports parameters like :id) - */ - path: external_exports.string().describe("URL path pattern (e.g., /api/v1/data/:object/:id)"), - /** - * Handler reference (protocol method name) - */ - handler: external_exports.string().describe("Protocol method name or handler identifier"), - /** - * Route category - */ - category: RestApiRouteCategory2.describe("Route category"), - /** - * Whether endpoint is publicly accessible (no auth required) - */ - public: external_exports.boolean().default(false).describe("Is publicly accessible without authentication"), - /** - * Required permissions - */ - permissions: external_exports.array(external_exports.string()).optional().describe('Required permissions (e.g., ["data.read", "object.account.read"])'), - /** - * OpenAPI documentation metadata - */ - summary: external_exports.string().optional().describe("Short description for OpenAPI"), - description: external_exports.string().optional().describe("Detailed description for OpenAPI"), - tags: external_exports.array(external_exports.string()).optional().describe("OpenAPI tags for grouping"), - /** - * Request/Response schema references - */ - requestSchema: external_exports.string().optional().describe("Request schema name (for validation)"), - responseSchema: external_exports.string().optional().describe("Response schema name (for documentation)"), - /** - * Performance and reliability settings - */ - timeout: external_exports.number().int().optional().describe("Request timeout in milliseconds"), - rateLimit: external_exports.string().optional().describe("Rate limit policy name"), - cacheable: external_exports.boolean().default(false).describe("Whether response can be cached"), - cacheTtl: external_exports.number().int().optional().describe("Cache TTL in seconds"), - /** - * Handler implementation status. - * Tracks whether this endpoint has a real handler or is only declared. - * - * - `implemented` – A real handler is coded and registered. - * - `stub` – A placeholder handler exists that returns 501 Not Implemented. - * - `planned` – Declared in the protocol spec but not yet implemented. - * @default 'implemented' - */ - handlerStatus: HandlerStatusSchema2.optional().describe("Handler implementation status: implemented (default if omitted), stub, or planned") -}); -var RestApiRouteRegistrationSchema2 = external_exports.object({ - /** - * URL prefix for this route group (e.g., /api/v1/data) - */ - prefix: external_exports.string().regex(/^\//).describe("URL path prefix for this route group"), - /** - * Service name that handles these routes - */ - service: external_exports.string().describe("Core service name (metadata, data, auth, etc.)"), - /** - * Route category - */ - category: RestApiRouteCategory2.describe("Primary category for this route group"), - /** - * Protocol methods implemented - */ - methods: external_exports.array(external_exports.string()).optional().describe("Protocol method names implemented"), - /** - * Detailed endpoint definitions - */ - endpoints: external_exports.array(RestApiEndpointSchema2).optional().describe("Endpoint definitions"), - /** - * Middleware applied to all routes in this group - */ - middleware: external_exports.array(MiddlewareConfigSchema3).optional().describe("Middleware stack for this route group"), - /** - * Whether authentication is required for all routes - */ - authRequired: external_exports.boolean().default(true).describe("Whether authentication is required by default"), - /** - * OpenAPI documentation - */ - documentation: external_exports.object({ - title: external_exports.string().optional().describe("Route group title"), - description: external_exports.string().optional().describe("Route group description"), - tags: external_exports.array(external_exports.string()).optional().describe("OpenAPI tags") - }).optional().describe("Documentation metadata for this route group") -}); -var ValidationMode2 = external_exports.enum([ - "strict", - // Reject requests with validation errors (400 Bad Request) - "permissive", - // Log validation errors but allow request to proceed - "strip" - // Remove invalid fields and continue with valid data -]); -var RequestValidationConfigSchema2 = external_exports.object({ - /** - * Enable request validation - */ - enabled: external_exports.boolean().default(true).describe("Enable automatic request validation"), - /** - * Validation mode - */ - mode: ValidationMode2.default("strict").describe("How to handle validation errors"), - /** - * Validate request body - */ - validateBody: external_exports.boolean().default(true).describe("Validate request body against schema"), - /** - * Validate query parameters - */ - validateQuery: external_exports.boolean().default(true).describe("Validate query string parameters"), - /** - * Validate URL parameters - */ - validateParams: external_exports.boolean().default(true).describe("Validate URL path parameters"), - /** - * Validate request headers - */ - validateHeaders: external_exports.boolean().default(false).describe("Validate request headers"), - /** - * Include detailed field errors in response - */ - includeFieldErrors: external_exports.boolean().default(true).describe("Include field-level error details in response"), - /** - * Custom error message prefix - */ - errorPrefix: external_exports.string().optional().describe("Custom prefix for validation error messages"), - /** - * Schema registry reference - */ - schemaRegistry: external_exports.string().optional().describe("Schema registry name to use for validation") -}); -var ResponseEnvelopeConfigSchema2 = external_exports.object({ - /** - * Enable response envelope wrapping - */ - enabled: external_exports.boolean().default(true).describe("Enable automatic response envelope wrapping"), - /** - * Include metadata object - */ - includeMetadata: external_exports.boolean().default(true).describe("Include meta object in responses"), - /** - * Include timestamp in metadata - */ - includeTimestamp: external_exports.boolean().default(true).describe("Include timestamp in response metadata"), - /** - * Include request ID in metadata - */ - includeRequestId: external_exports.boolean().default(true).describe("Include requestId in response metadata"), - /** - * Include request duration in metadata - */ - includeDuration: external_exports.boolean().default(false).describe("Include request duration in ms"), - /** - * Include trace ID for distributed tracing - */ - includeTraceId: external_exports.boolean().default(false).describe("Include distributed traceId"), - /** - * Custom metadata fields - */ - customMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional metadata fields to include"), - /** - * Whether to wrap already-wrapped responses - */ - skipIfWrapped: external_exports.boolean().default(true).describe("Skip wrapping if response already has success field") -}); -var ErrorHandlingConfigSchema2 = external_exports.object({ - /** - * Enable standardized error handling - */ - enabled: external_exports.boolean().default(true).describe("Enable standardized error handling"), - /** - * Include stack traces in error responses (dev only) - */ - includeStackTrace: external_exports.boolean().default(false).describe("Include stack traces in error responses"), - /** - * Log errors to logger - */ - logErrors: external_exports.boolean().default(true).describe("Log errors to system logger"), - /** - * Expose internal error details - */ - exposeInternalErrors: external_exports.boolean().default(false).describe("Expose internal error details in responses"), - /** - * Include request ID in errors - */ - includeRequestId: external_exports.boolean().default(true).describe("Include requestId in error responses"), - /** - * Include timestamp in errors - */ - includeTimestamp: external_exports.boolean().default(true).describe("Include timestamp in error responses"), - /** - * Include error documentation URLs - */ - includeDocumentation: external_exports.boolean().default(true).describe("Include documentation URLs for errors"), - /** - * Documentation base URL - */ - documentationBaseUrl: external_exports.string().url().optional().describe("Base URL for error documentation"), - /** - * Custom error messages by code - */ - customErrorMessages: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom error messages by error code"), - /** - * Sensitive fields to redact from error details - */ - redactFields: external_exports.array(external_exports.string()).optional().describe("Field names to redact from error details") -}); -var OpenApiGenerationConfigSchema2 = external_exports.object({ - /** - * Enable OpenAPI generation - */ - enabled: external_exports.boolean().default(true).describe("Enable automatic OpenAPI documentation generation"), - /** - * OpenAPI specification version - */ - version: external_exports.enum(["3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.1.0"]).default("3.0.3").describe("OpenAPI specification version"), - /** - * API title - */ - title: external_exports.string().default("ObjectStack API").describe("API title"), - /** - * API description - */ - description: external_exports.string().optional().describe("API description"), - /** - * API version - */ - apiVersion: external_exports.string().default("1.0.0").describe("API version"), - /** - * Output path for OpenAPI spec - */ - outputPath: external_exports.string().default("/api/docs/openapi.json").describe("URL path to serve OpenAPI JSON"), - /** - * UI path for Swagger/Redoc - */ - uiPath: external_exports.string().default("/api/docs").describe("URL path to serve documentation UI"), - /** - * UI framework to use - */ - uiFramework: external_exports.enum(["swagger-ui", "redoc", "rapidoc", "elements"]).default("swagger-ui").describe("Documentation UI framework"), - /** - * Include internal/admin endpoints - */ - includeInternal: external_exports.boolean().default(false).describe("Include internal endpoints in documentation"), - /** - * Generate JSON schemas from Zod - */ - generateSchemas: external_exports.boolean().default(true).describe("Auto-generate schemas from Zod definitions"), - /** - * Include examples in documentation - */ - includeExamples: external_exports.boolean().default(true).describe("Include request/response examples"), - /** - * Server URLs - */ - servers: external_exports.array(external_exports.object({ - url: external_exports.string().describe("Server URL"), - description: external_exports.string().optional().describe("Server description") - })).optional().describe("Server URLs for API"), - /** - * Contact information - */ - contact: external_exports.object({ - name: external_exports.string().optional(), - url: external_exports.string().url().optional(), - email: external_exports.string().email().optional() - }).optional().describe("API contact information"), - /** - * License information - */ - license: external_exports.object({ - name: external_exports.string().describe("License name"), - url: external_exports.string().url().optional().describe("License URL") - }).optional().describe("API license information"), - /** - * Security schemes - */ - securitySchemes: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["apiKey", "http", "oauth2", "openIdConnect"]), - scheme: external_exports.string().optional(), - bearerFormat: external_exports.string().optional() - })).optional().describe("Security scheme definitions") -}); -var RestApiPluginConfigSchema2 = external_exports.object({ - /** - * Enable REST API plugin - */ - enabled: external_exports.boolean().default(true).describe("Enable REST API plugin"), - /** - * API base path - */ - basePath: external_exports.string().default("/api").describe("Base path for all API routes"), - /** - * API version - */ - version: external_exports.string().default("v1").describe("API version identifier"), - /** - * Route registrations - */ - routes: external_exports.array(RestApiRouteRegistrationSchema2).describe("Route registrations"), - /** - * Request validation configuration - */ - validation: RequestValidationConfigSchema2.optional().describe("Request validation configuration"), - /** - * Response envelope configuration - */ - responseEnvelope: ResponseEnvelopeConfigSchema2.optional().describe("Response envelope configuration"), - /** - * Error handling configuration - */ - errorHandling: ErrorHandlingConfigSchema2.optional().describe("Error handling configuration"), - /** - * OpenAPI documentation configuration - */ - openApi: OpenApiGenerationConfigSchema2.optional().describe("OpenAPI documentation configuration"), - /** - * Global middleware applied to all routes - */ - globalMiddleware: external_exports.array(MiddlewareConfigSchema3).optional().describe("Global middleware stack"), - /** - * CORS configuration - */ - cors: external_exports.object({ - enabled: external_exports.boolean().default(true), - origins: external_exports.array(external_exports.string()).optional(), - methods: external_exports.array(HttpMethod5).optional(), - credentials: external_exports.boolean().default(true) - }).optional().describe("CORS configuration"), - /** - * Performance settings - */ - performance: external_exports.object({ - enableCompression: external_exports.boolean().default(true).describe("Enable response compression"), - enableETag: external_exports.boolean().default(true).describe("Enable ETag generation"), - enableCaching: external_exports.boolean().default(true).describe("Enable HTTP caching"), - defaultCacheTtl: external_exports.number().int().default(300).describe("Default cache TTL in seconds") - }).optional().describe("Performance optimization settings") -}); -var DEFAULT_DISCOVERY_ROUTES = { - prefix: "/api/v1/discovery", - service: "metadata", - category: "discovery", - methods: ["getDiscovery"], - authRequired: false, - endpoints: [{ - method: "GET", - path: "", - handler: "getDiscovery", - category: "discovery", - public: true, - summary: "Get API discovery information", - description: "Returns API version, capabilities, and available routes", - tags: ["Discovery"], - responseSchema: "GetDiscoveryResponseSchema", - cacheable: true, - cacheTtl: 3600 - // Cache for 1 hour as discovery info rarely changes - }], - middleware: [ - { name: "response_envelope", type: "transformation", enabled: true, order: 100 } - ] -}; -var DEFAULT_METADATA_ROUTES = { - prefix: "/api/v1/meta", - service: "metadata", - category: "metadata", - methods: ["getMetaTypes", "getMetaItems", "getMetaItem", "saveMetaItem"], - authRequired: true, - endpoints: [ - { - method: "GET", - path: "", - handler: "getMetaTypes", - category: "metadata", - public: false, - summary: "List all metadata types", - description: "Returns available metadata types (object, field, view, etc.)", - tags: ["Metadata"], - responseSchema: "GetMetaTypesResponseSchema", - cacheable: true, - cacheTtl: 3600 - }, - { - method: "GET", - path: "/:type", - handler: "getMetaItems", - category: "metadata", - public: false, - summary: "List metadata items of a type", - description: "Returns all items of the specified metadata type", - tags: ["Metadata"], - responseSchema: "GetMetaItemsResponseSchema", - cacheable: true, - cacheTtl: 3600 - }, - { - method: "GET", - path: "/:type/:name", - handler: "getMetaItem", - category: "metadata", - public: false, - summary: "Get specific metadata item", - description: "Returns a specific metadata item by type and name", - tags: ["Metadata"], - requestSchema: "GetMetaItemRequestSchema", - responseSchema: "GetMetaItemResponseSchema", - cacheable: true, - cacheTtl: 3600 - }, - { - method: "PUT", - path: "/:type/:name", - handler: "saveMetaItem", - category: "metadata", - public: false, - summary: "Create or update metadata item", - description: "Creates or updates a metadata item", - tags: ["Metadata"], - requestSchema: "SaveMetaItemRequestSchema", - responseSchema: "SaveMetaItemResponseSchema", - permissions: ["metadata.write"], - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 } - ] -}; -var DEFAULT_DATA_CRUD_ROUTES = { - prefix: "/api/v1/data", - service: "data", - category: "data", - methods: ["findData", "getData", "createData", "updateData", "deleteData"], - authRequired: true, - endpoints: [ - { - method: "GET", - path: "/:object", - handler: "findData", - category: "data", - public: false, - summary: "Query records", - description: "Query records with filtering, sorting, and pagination", - tags: ["Data"], - requestSchema: "FindDataRequestSchema", - responseSchema: "ListRecordResponseSchema", - permissions: ["data.read"], - cacheable: false - }, - { - method: "GET", - path: "/:object/:id", - handler: "getData", - category: "data", - public: false, - summary: "Get record by ID", - description: "Retrieve a single record by its ID", - tags: ["Data"], - requestSchema: "IdRequestSchema", - responseSchema: "SingleRecordResponseSchema", - permissions: ["data.read"], - cacheable: false - }, - { - method: "POST", - path: "/:object", - handler: "createData", - category: "data", - public: false, - summary: "Create record", - description: "Create a new record", - tags: ["Data"], - requestSchema: "CreateRequestSchema", - responseSchema: "SingleRecordResponseSchema", - permissions: ["data.create"], - cacheable: false - }, - { - method: "PATCH", - path: "/:object/:id", - handler: "updateData", - category: "data", - public: false, - summary: "Update record", - description: "Update an existing record", - tags: ["Data"], - requestSchema: "UpdateRequestSchema", - responseSchema: "SingleRecordResponseSchema", - permissions: ["data.update"], - cacheable: false - }, - { - method: "DELETE", - path: "/:object/:id", - handler: "deleteData", - category: "data", - public: false, - summary: "Delete record", - description: "Delete a record by ID", - tags: ["Data"], - requestSchema: "IdRequestSchema", - responseSchema: "DeleteResponseSchema", - permissions: ["data.delete"], - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, - { name: "error_handler", type: "error", enabled: true, order: 200 } - ] -}; -var DEFAULT_BATCH_ROUTES = { - prefix: "/api/v1/data/:object", - service: "data", - category: "batch", - methods: ["batchData", "createManyData", "updateManyData", "deleteManyData"], - authRequired: true, - endpoints: [ - { - method: "POST", - path: "/batch", - handler: "batchData", - category: "batch", - public: false, - summary: "Batch operation", - description: "Execute a batch operation (create, update, upsert, delete)", - tags: ["Batch"], - requestSchema: "BatchUpdateRequestSchema", - responseSchema: "BatchUpdateResponseSchema", - permissions: ["data.batch"], - timeout: 6e4, - // 60 seconds for batch operations - cacheable: false - }, - { - method: "POST", - path: "/createMany", - handler: "createManyData", - category: "batch", - public: false, - summary: "Batch create", - description: "Create multiple records in a single operation", - tags: ["Batch"], - requestSchema: "CreateManyRequestSchema", - responseSchema: "BatchUpdateResponseSchema", - permissions: ["data.create", "data.batch"], - timeout: 6e4, - cacheable: false - }, - { - method: "POST", - path: "/updateMany", - handler: "updateManyData", - category: "batch", - public: false, - summary: "Batch update", - description: "Update multiple records in a single operation", - tags: ["Batch"], - requestSchema: "UpdateManyRequestSchema", - responseSchema: "BatchUpdateResponseSchema", - permissions: ["data.update", "data.batch"], - timeout: 6e4, - cacheable: false - }, - { - method: "POST", - path: "/deleteMany", - handler: "deleteManyData", - category: "batch", - public: false, - summary: "Batch delete", - description: "Delete multiple records in a single operation", - tags: ["Batch"], - requestSchema: "DeleteManyRequestSchema", - responseSchema: "BatchUpdateResponseSchema", - permissions: ["data.delete", "data.batch"], - timeout: 6e4, - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, - { name: "error_handler", type: "error", enabled: true, order: 200 } - ] -}; -var DEFAULT_PERMISSION_ROUTES = { - prefix: "/api/v1/auth", - service: "auth", - category: "permission", - methods: ["checkPermission", "getObjectPermissions", "getEffectivePermissions"], - authRequired: true, - endpoints: [ - { - method: "POST", - path: "/check", - handler: "checkPermission", - category: "permission", - public: false, - summary: "Check permission", - description: "Check if current user has a specific permission", - tags: ["Permission"], - requestSchema: "CheckPermissionRequestSchema", - responseSchema: "CheckPermissionResponseSchema", - cacheable: false - }, - { - method: "GET", - path: "/permissions/:object", - handler: "getObjectPermissions", - category: "permission", - public: false, - summary: "Get object permissions", - description: "Get all permissions for a specific object", - tags: ["Permission"], - responseSchema: "ObjectPermissionsResponseSchema", - cacheable: true, - cacheTtl: 300 - }, - { - method: "GET", - path: "/permissions/effective", - handler: "getEffectivePermissions", - category: "permission", - public: false, - summary: "Get effective permissions", - description: "Get all effective permissions for current user", - tags: ["Permission"], - responseSchema: "EffectivePermissionsResponseSchema", - cacheable: true, - cacheTtl: 300 - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 } - ] -}; -var DEFAULT_VIEW_ROUTES = { - prefix: "/api/v1/ui", - service: "ui", - category: "ui", - methods: ["listViews", "getView", "createView", "updateView", "deleteView"], - authRequired: true, - endpoints: [ - { - method: "GET", - path: "/views/:object", - handler: "listViews", - category: "ui", - public: false, - summary: "List views for an object", - description: "Returns all views (list, form) for the specified object", - tags: ["Views", "UI"], - responseSchema: "ListViewsResponseSchema", - cacheable: true, - cacheTtl: 1800 - }, - { - method: "GET", - path: "/views/:object/:viewId", - handler: "getView", - category: "ui", - public: false, - summary: "Get a specific view", - description: "Returns a specific view definition by object and view ID", - tags: ["Views", "UI"], - responseSchema: "GetViewResponseSchema", - cacheable: true, - cacheTtl: 1800 - }, - { - method: "POST", - path: "/views/:object", - handler: "createView", - category: "ui", - public: false, - summary: "Create a new view", - description: "Creates a new view definition for the specified object", - tags: ["Views", "UI"], - requestSchema: "CreateViewRequestSchema", - responseSchema: "CreateViewResponseSchema", - permissions: ["ui.view.create"], - cacheable: false - }, - { - method: "PATCH", - path: "/views/:object/:viewId", - handler: "updateView", - category: "ui", - public: false, - summary: "Update a view", - description: "Updates an existing view definition", - tags: ["Views", "UI"], - requestSchema: "UpdateViewRequestSchema", - responseSchema: "UpdateViewResponseSchema", - permissions: ["ui.view.update"], - cacheable: false - }, - { - method: "DELETE", - path: "/views/:object/:viewId", - handler: "deleteView", - category: "ui", - public: false, - summary: "Delete a view", - description: "Deletes a view definition", - tags: ["Views", "UI"], - responseSchema: "DeleteViewResponseSchema", - permissions: ["ui.view.delete"], - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 } - ] -}; -var DEFAULT_WORKFLOW_ROUTES = { - prefix: "/api/v1/workflow", - service: "workflow", - category: "workflow", - methods: ["getWorkflowConfig", "getWorkflowState", "workflowTransition", "workflowApprove", "workflowReject"], - authRequired: true, - endpoints: [ - { - method: "GET", - path: "/:object/config", - handler: "getWorkflowConfig", - category: "workflow", - public: false, - summary: "Get workflow configuration", - description: "Returns workflow rules and state machine configuration for an object", - tags: ["Workflow"], - responseSchema: "GetWorkflowConfigResponseSchema", - cacheable: true, - cacheTtl: 3600 - }, - { - method: "GET", - path: "/:object/:recordId/state", - handler: "getWorkflowState", - category: "workflow", - public: false, - summary: "Get workflow state", - description: "Returns current workflow state and available transitions for a record", - tags: ["Workflow"], - responseSchema: "GetWorkflowStateResponseSchema", - cacheable: false - }, - { - method: "POST", - path: "/:object/:recordId/transition", - handler: "workflowTransition", - category: "workflow", - public: false, - summary: "Execute workflow transition", - description: "Transitions a record to a new workflow state", - tags: ["Workflow"], - requestSchema: "WorkflowTransitionRequestSchema", - responseSchema: "WorkflowTransitionResponseSchema", - permissions: ["workflow.transition"], - cacheable: false - }, - { - method: "POST", - path: "/:object/:recordId/approve", - handler: "workflowApprove", - category: "workflow", - public: false, - summary: "Approve workflow step", - description: "Approves a pending workflow approval step", - tags: ["Workflow"], - requestSchema: "WorkflowApproveRequestSchema", - responseSchema: "WorkflowApproveResponseSchema", - permissions: ["workflow.approve"], - cacheable: false - }, - { - method: "POST", - path: "/:object/:recordId/reject", - handler: "workflowReject", - category: "workflow", - public: false, - summary: "Reject workflow step", - description: "Rejects a pending workflow approval step", - tags: ["Workflow"], - requestSchema: "WorkflowRejectRequestSchema", - responseSchema: "WorkflowRejectResponseSchema", - permissions: ["workflow.reject"], - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, - { name: "error_handler", type: "error", enabled: true, order: 200 } - ] -}; -var DEFAULT_REALTIME_ROUTES = { - prefix: "/api/v1/realtime", - service: "realtime", - category: "realtime", - methods: ["realtimeConnect", "realtimeDisconnect", "realtimeSubscribe", "realtimeUnsubscribe", "setPresence", "getPresence"], - authRequired: true, - endpoints: [ - { - method: "POST", - path: "/connect", - handler: "realtimeConnect", - category: "realtime", - public: false, - summary: "Establish realtime connection", - description: "Negotiates a realtime connection (WebSocket/SSE) and returns connection details", - tags: ["Realtime"], - requestSchema: "RealtimeConnectRequestSchema", - responseSchema: "RealtimeConnectResponseSchema", - cacheable: false - }, - { - method: "POST", - path: "/disconnect", - handler: "realtimeDisconnect", - category: "realtime", - public: false, - summary: "Close realtime connection", - description: "Closes an active realtime connection", - tags: ["Realtime"], - requestSchema: "RealtimeDisconnectRequestSchema", - responseSchema: "RealtimeDisconnectResponseSchema", - cacheable: false - }, - { - method: "POST", - path: "/subscribe", - handler: "realtimeSubscribe", - category: "realtime", - public: false, - summary: "Subscribe to channel", - description: "Subscribes to a realtime channel for receiving events", - tags: ["Realtime"], - requestSchema: "RealtimeSubscribeRequestSchema", - responseSchema: "RealtimeSubscribeResponseSchema", - cacheable: false - }, - { - method: "POST", - path: "/unsubscribe", - handler: "realtimeUnsubscribe", - category: "realtime", - public: false, - summary: "Unsubscribe from channel", - description: "Unsubscribes from a realtime channel", - tags: ["Realtime"], - requestSchema: "RealtimeUnsubscribeRequestSchema", - responseSchema: "RealtimeUnsubscribeResponseSchema", - cacheable: false - }, - { - method: "PUT", - path: "/presence/:channel", - handler: "setPresence", - category: "realtime", - public: false, - summary: "Set presence state", - description: "Sets the current user's presence state in a channel", - tags: ["Realtime"], - requestSchema: "SetPresenceRequestSchema", - responseSchema: "SetPresenceResponseSchema", - cacheable: false - }, - { - method: "GET", - path: "/presence/:channel", - handler: "getPresence", - category: "realtime", - public: false, - summary: "Get channel presence", - description: "Returns all active members and their presence state in a channel", - tags: ["Realtime"], - responseSchema: "GetPresenceResponseSchema", - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 } - ] -}; -var DEFAULT_NOTIFICATION_ROUTES = { - prefix: "/api/v1/notifications", - service: "notification", - category: "notification", - methods: [ - "registerDevice", - "unregisterDevice", - "getNotificationPreferences", - "updateNotificationPreferences", - "listNotifications", - "markNotificationsRead", - "markAllNotificationsRead" - ], - authRequired: true, - endpoints: [ - { - method: "POST", - path: "/devices", - handler: "registerDevice", - category: "notification", - public: false, - summary: "Register device for push notifications", - description: "Registers a device token for receiving push notifications", - tags: ["Notifications"], - requestSchema: "RegisterDeviceRequestSchema", - responseSchema: "RegisterDeviceResponseSchema", - cacheable: false - }, - { - method: "DELETE", - path: "/devices/:deviceId", - handler: "unregisterDevice", - category: "notification", - public: false, - summary: "Unregister device", - description: "Removes a device from push notification registration", - tags: ["Notifications"], - responseSchema: "UnregisterDeviceResponseSchema", - cacheable: false - }, - { - method: "GET", - path: "/preferences", - handler: "getNotificationPreferences", - category: "notification", - public: false, - summary: "Get notification preferences", - description: "Returns current user notification preferences", - tags: ["Notifications"], - responseSchema: "GetNotificationPreferencesResponseSchema", - cacheable: false - }, - { - method: "PATCH", - path: "/preferences", - handler: "updateNotificationPreferences", - category: "notification", - public: false, - summary: "Update notification preferences", - description: "Updates user notification preferences", - tags: ["Notifications"], - requestSchema: "UpdateNotificationPreferencesRequestSchema", - responseSchema: "UpdateNotificationPreferencesResponseSchema", - cacheable: false - }, - { - method: "GET", - path: "", - handler: "listNotifications", - category: "notification", - public: false, - summary: "List notifications", - description: "Returns paginated list of notifications for the current user", - tags: ["Notifications"], - responseSchema: "ListNotificationsResponseSchema", - cacheable: false - }, - { - method: "POST", - path: "/read", - handler: "markNotificationsRead", - category: "notification", - public: false, - summary: "Mark notifications as read", - description: "Marks specific notifications as read by their IDs", - tags: ["Notifications"], - requestSchema: "MarkNotificationsReadRequestSchema", - responseSchema: "MarkNotificationsReadResponseSchema", - cacheable: false - }, - { - method: "POST", - path: "/read/all", - handler: "markAllNotificationsRead", - category: "notification", - public: false, - summary: "Mark all notifications as read", - description: "Marks all notifications as read for the current user", - tags: ["Notifications"], - responseSchema: "MarkAllNotificationsReadResponseSchema", - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 } - ] -}; -var DEFAULT_AI_ROUTES = { - prefix: "/api/v1/ai", - service: "ai", - category: "ai", - methods: ["aiNlq", "aiSuggest", "aiInsights"], - authRequired: true, - endpoints: [ - { - method: "POST", - path: "/nlq", - handler: "aiNlq", - category: "ai", - public: false, - summary: "Natural language query", - description: "Converts a natural language query to a structured query AST", - tags: ["AI"], - requestSchema: "AiNlqRequestSchema", - responseSchema: "AiNlqResponseSchema", - timeout: 3e4, - cacheable: false - }, - // AI chat route removed — wire protocol aligned with Vercel AI SDK. - // The chat endpoint should use Vercel's `toDataStreamResponse()` directly. - { - method: "POST", - path: "/suggest", - handler: "aiSuggest", - category: "ai", - public: false, - summary: "Get AI-powered suggestions", - description: "Returns AI-generated field value suggestions based on context", - tags: ["AI"], - requestSchema: "AiSuggestRequestSchema", - responseSchema: "AiSuggestResponseSchema", - timeout: 15e3, - cacheable: false - }, - { - method: "POST", - path: "/insights", - handler: "aiInsights", - category: "ai", - public: false, - summary: "Get AI-generated insights", - description: "Returns AI-generated insights (summaries, trends, anomalies, recommendations)", - tags: ["AI"], - requestSchema: "AiInsightsRequestSchema", - responseSchema: "AiInsightsResponseSchema", - timeout: 6e4, - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, - { name: "error_handler", type: "error", enabled: true, order: 200 } - ] -}; -var DEFAULT_I18N_ROUTES = { - prefix: "/api/v1/i18n", - service: "i18n", - category: "i18n", - methods: ["getLocales", "getTranslations", "getFieldLabels"], - authRequired: true, - endpoints: [ - { - method: "GET", - path: "/locales", - handler: "getLocales", - category: "i18n", - public: false, - summary: "Get available locales", - description: "Returns all available locales with their metadata", - tags: ["i18n"], - responseSchema: "GetLocalesResponseSchema", - cacheable: true, - cacheTtl: 86400 - // 24 hours — locales change very rarely - }, - { - method: "GET", - path: "/translations/:locale", - handler: "getTranslations", - category: "i18n", - public: false, - summary: "Get translations for a locale", - description: "Returns translation strings for the specified locale and optional namespace", - tags: ["i18n"], - responseSchema: "GetTranslationsResponseSchema", - cacheable: true, - cacheTtl: 3600 - }, - { - method: "GET", - path: "/labels/:object/:locale", - handler: "getFieldLabels", - category: "i18n", - public: false, - summary: "Get translated field labels", - description: "Returns translated field labels, help text, and option labels for an object", - tags: ["i18n"], - responseSchema: "GetFieldLabelsResponseSchema", - cacheable: true, - cacheTtl: 3600 - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 } - ] -}; -var DEFAULT_ANALYTICS_ROUTES = { - prefix: "/api/v1/analytics", - service: "analytics", - category: "analytics", - methods: ["analyticsQuery", "getAnalyticsMeta"], - authRequired: true, - endpoints: [ - { - method: "POST", - path: "/query", - handler: "analyticsQuery", - category: "analytics", - public: false, - summary: "Execute analytics query", - description: "Executes a structured analytics query against the semantic layer", - tags: ["Analytics"], - requestSchema: "AnalyticsQueryRequestSchema", - responseSchema: "AnalyticsResultResponseSchema", - permissions: ["analytics.query"], - timeout: 12e4, - // 2 minutes for analytics queries - cacheable: false - }, - { - method: "GET", - path: "/meta", - handler: "getAnalyticsMeta", - category: "analytics", - public: false, - summary: "Get analytics metadata", - description: "Returns available cubes, dimensions, measures, and segments", - tags: ["Analytics"], - responseSchema: "AnalyticsMetadataResponseSchema", - cacheable: true, - cacheTtl: 3600 - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, - { name: "error_handler", type: "error", enabled: true, order: 200 } - ] -}; -var DEFAULT_AUTOMATION_ROUTES = { - prefix: "/api/v1/automation", - service: "automation", - category: "automation", - methods: ["triggerAutomation"], - authRequired: true, - endpoints: [ - { - method: "POST", - path: "/trigger", - handler: "triggerAutomation", - category: "automation", - public: false, - summary: "Trigger automation", - description: "Triggers an automation flow or script by name", - tags: ["Automation"], - requestSchema: "AutomationTriggerRequestSchema", - responseSchema: "AutomationTriggerResponseSchema", - permissions: ["automation.trigger"], - timeout: 12e4, - // 2 minutes for long-running automations - cacheable: false - } - ], - middleware: [ - { name: "auth", type: "authentication", enabled: true, order: 10 }, - { name: "validation", type: "validation", enabled: true, order: 20 }, - { name: "response_envelope", type: "transformation", enabled: true, order: 100 }, - { name: "error_handler", type: "error", enabled: true, order: 200 } - ] -}; -var RestApiPluginConfig2 = Object.assign(RestApiPluginConfigSchema2, { - create: (config4) => config4 -}); -var RestApiRouteRegistration2 = Object.assign(RestApiRouteRegistrationSchema2, { - create: (registration) => registration -}); -function getDefaultRouteRegistrations() { - return [ - DEFAULT_DISCOVERY_ROUTES, - DEFAULT_METADATA_ROUTES, - DEFAULT_DATA_CRUD_ROUTES, - DEFAULT_BATCH_ROUTES, - DEFAULT_PERMISSION_ROUTES, - DEFAULT_VIEW_ROUTES, - DEFAULT_WORKFLOW_ROUTES, - DEFAULT_REALTIME_ROUTES, - DEFAULT_NOTIFICATION_ROUTES, - DEFAULT_AI_ROUTES, - DEFAULT_I18N_ROUTES, - DEFAULT_ANALYTICS_ROUTES, - DEFAULT_AUTOMATION_ROUTES - ]; -} -var RouteCoverageEntrySchema2 = external_exports.object({ - /** Full URL path of the endpoint */ - path: external_exports.string().describe("Full URL path (e.g. /api/v1/analytics/query)"), - /** HTTP method */ - method: HttpMethod5.describe("HTTP method (GET, POST, etc.)"), - /** Route category */ - category: RestApiRouteCategory2.describe("Route category"), - /** Handler implementation status */ - handlerStatus: HandlerStatusSchema2.describe("Handler status"), - /** Target service */ - service: external_exports.string().describe("Target service name"), - /** Whether the handler was successfully called during health check */ - healthCheckPassed: external_exports.boolean().optional().describe("Whether the health check probe succeeded") -}); -var RouteCoverageReportSchema2 = external_exports.object({ - /** ISO 8601 timestamp of report generation */ - timestamp: external_exports.string().describe("ISO 8601 timestamp"), - /** Adapter that generated the report */ - adapter: external_exports.string().describe('Adapter name (e.g. "hono", "express", "nextjs")'), - /** Summary counters */ - summary: external_exports.object({ - total: external_exports.number().int().describe("Total declared endpoints"), - implemented: external_exports.number().int().describe("Endpoints with real handlers"), - stub: external_exports.number().int().describe("Endpoints with stub handlers (501)"), - planned: external_exports.number().int().describe("Endpoints not yet implemented") - }), - /** Per-endpoint entries */ - entries: external_exports.array(RouteCoverageEntrySchema2).describe("Per-endpoint coverage entries") -}); -var QueryAdapterTargetSchema2 = external_exports.enum([ - "rest", - // REST API (?filter[field][op]=value) - "graphql", - // GraphQL (where: \{ field: \{ op: value \}\}) - "odata" - // OData ($filter=field op value) -]); -var OperatorMappingSchema2 = external_exports.object({ - /** Unified DSL operator (e.g., 'eq', 'gt', 'contains') */ - operator: external_exports.string().describe("Unified DSL operator"), - /** REST query parameter format (e.g., 'filter[{field}][{op}]') */ - rest: external_exports.string().optional().describe("REST query parameter template"), - /** GraphQL where clause format (e.g., '{field}: { {op}: $value }') */ - graphql: external_exports.string().optional().describe("GraphQL where clause template"), - /** OData $filter expression format (e.g., '{field} {op} {value}') */ - odata: external_exports.string().optional().describe("OData $filter expression template") -}); -var RestQueryAdapterSchema2 = external_exports.object({ - /** Filter parameter style */ - filterStyle: external_exports.enum([ - "bracket", - // ?filter[field][op]=value (JSON API style) - "dot", - // ?filter.field.op=value - "flat", - // ?field=value (simple equality) - "rsql" - // ?filter=field==value;field=gt=10 (RSQL / FIQL) - ]).default("bracket").describe("REST filter parameter encoding style"), - /** Pagination parameter names */ - pagination: external_exports.object({ - /** Page size parameter name */ - limitParam: external_exports.string().default("limit").describe("Page size parameter name"), - /** Offset parameter name */ - offsetParam: external_exports.string().default("offset").describe("Offset parameter name"), - /** Cursor parameter name (for cursor-based pagination) */ - cursorParam: external_exports.string().default("cursor").describe("Cursor parameter name"), - /** Page number parameter name (for page-based pagination) */ - pageParam: external_exports.string().default("page").describe("Page number parameter name") - }).optional().describe("Pagination parameter name mappings"), - /** Sort parameter name and format */ - sorting: external_exports.object({ - /** Sort parameter name */ - param: external_exports.string().default("sort").describe("Sort parameter name"), - /** Sort format */ - format: external_exports.enum([ - "comma", - // ?sort=field1,-field2 - "array", - // ?sort[]=field1&sort[]=-field2 - "pipe" - // ?sort=field1|asc,field2|desc - ]).default("comma").describe("Sort parameter encoding format") - }).optional().describe("Sort parameter mapping"), - /** Field selection parameter name */ - fieldsParam: external_exports.string().default("fields").describe("Field selection parameter name") -}); -var GraphQLQueryAdapterSchema2 = external_exports.object({ - /** Filter argument name in GraphQL queries */ - filterArgName: external_exports.string().default("where").describe("GraphQL filter argument name"), - /** Filter nesting style */ - filterStyle: external_exports.enum([ - "nested", - // where: { field: { op: value } } (Prisma style) - "flat", - // where: { field_op: value } (Hasura style) - "array" - // where: [{ field, op, value }] (Array of conditions) - ]).default("nested").describe("GraphQL filter nesting style"), - /** Pagination argument names */ - pagination: external_exports.object({ - limitArg: external_exports.string().default("limit").describe("Page size argument name"), - offsetArg: external_exports.string().default("offset").describe("Offset argument name"), - firstArg: external_exports.string().default("first").describe('Relay "first" argument name'), - afterArg: external_exports.string().default("after").describe('Relay "after" cursor argument name') - }).optional().describe("Pagination argument name mappings"), - /** Sort argument configuration */ - sorting: external_exports.object({ - argName: external_exports.string().default("orderBy").describe("Sort argument name"), - format: external_exports.enum([ - "enum", - // orderBy: { field: ASC } - "array" - // orderBy: [{ field: "name", direction: "ASC" }] - ]).default("enum").describe("Sort argument format") - }).optional().describe("Sort argument mapping") -}); -var ODataQueryAdapterSchema2 = external_exports.object({ - /** OData version */ - version: external_exports.enum(["v2", "v4"]).default("v4").describe("OData version"), - /** System query option prefixes */ - usePrefix: external_exports.boolean().default(true).describe("Use $ prefix for system query options ($filter vs filter)"), - /** String function support */ - stringFunctions: external_exports.array(external_exports.enum([ - "contains", - "startswith", - "endswith", - "tolower", - "toupper", - "trim", - "concat", - "substring", - "length" - ])).optional().describe("Supported OData string functions"), - /** Expand (nested resource) configuration */ - expand: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable $expand support"), - maxDepth: external_exports.number().int().min(1).default(3).describe("Maximum expand depth") - }).optional().describe("$expand configuration") -}); -var QueryAdapterConfigSchema2 = external_exports.object({ - /** Default operator mappings */ - operatorMappings: external_exports.array(OperatorMappingSchema2).optional().describe("Custom operator mappings"), - /** REST adapter configuration */ - rest: RestQueryAdapterSchema2.optional().describe("REST query adapter configuration"), - /** GraphQL adapter configuration */ - graphql: GraphQLQueryAdapterSchema2.optional().describe("GraphQL query adapter configuration"), - /** OData adapter configuration */ - odata: ODataQueryAdapterSchema2.optional().describe("OData query adapter configuration") -}); -var FeedPathParamsSchema2 = external_exports.object({ - object: external_exports.string().describe('Object name (e.g., "account")'), - recordId: external_exports.string().describe("Record ID") -}); -var FeedItemPathParamsSchema2 = FeedPathParamsSchema2.extend({ - feedId: external_exports.string().describe("Feed item ID") -}); -var FeedListFilterType2 = external_exports.enum([ - "all", - "comments_only", - "changes_only", - "tasks_only" -]); -var GetFeedRequestSchema2 = FeedPathParamsSchema2.extend({ - type: FeedListFilterType2.default("all").describe("Filter by feed item category"), - limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of items to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination (opaque string from previous response)") -}); -var GetFeedResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - items: external_exports.array(FeedItemSchema3).describe("Feed items in reverse chronological order"), - total: external_exports.number().int().optional().describe("Total feed items matching filter"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more items are available") - }) -}); -var CreateFeedItemRequestSchema2 = FeedPathParamsSchema2.extend({ - type: FeedItemType4.describe("Type of feed item to create"), - body: external_exports.string().optional().describe("Rich text body (Markdown supported)"), - mentions: external_exports.array(MentionSchema4).optional().describe("Mentioned users, teams, or records"), - parentId: external_exports.string().optional().describe("Parent feed item ID for threaded replies"), - visibility: FeedVisibility4.default("public").describe("Visibility: public, internal, or private") -}); -var CreateFeedItemResponseSchema2 = BaseResponseSchema2.extend({ - data: FeedItemSchema3.describe("The created feed item") -}); -var UpdateFeedItemRequestSchema2 = FeedItemPathParamsSchema2.extend({ - body: external_exports.string().optional().describe("Updated rich text body"), - mentions: external_exports.array(MentionSchema4).optional().describe("Updated mentions"), - visibility: FeedVisibility4.optional().describe("Updated visibility") -}); -var UpdateFeedItemResponseSchema2 = BaseResponseSchema2.extend({ - data: FeedItemSchema3.describe("The updated feed item") -}); -var DeleteFeedItemRequestSchema = FeedItemPathParamsSchema2; -var DeleteFeedItemResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the deleted feed item") - }) -}); -var AddReactionRequestSchema2 = FeedItemPathParamsSchema2.extend({ - emoji: external_exports.string().describe('Emoji character or shortcode (e.g., "\u{1F44D}", ":thumbsup:")') -}); -var AddReactionResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - reactions: external_exports.array(ReactionSchema4).describe("Updated reaction list for the feed item") - }) -}); -var RemoveReactionRequestSchema2 = FeedItemPathParamsSchema2.extend({ - emoji: external_exports.string().describe("Emoji character or shortcode to remove") -}); -var RemoveReactionResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - reactions: external_exports.array(ReactionSchema4).describe("Updated reaction list for the feed item") - }) -}); -var PinFeedItemRequestSchema = FeedItemPathParamsSchema2; -var PinFeedItemResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the pinned feed item"), - pinned: external_exports.boolean().describe("Whether the item is now pinned"), - pinnedAt: external_exports.string().datetime().describe("Timestamp when pinned") - }) -}); -var UnpinFeedItemRequestSchema = FeedItemPathParamsSchema2; -var UnpinFeedItemResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the unpinned feed item"), - pinned: external_exports.boolean().describe("Whether the item is now pinned (should be false)") - }) -}); -var StarFeedItemRequestSchema = FeedItemPathParamsSchema2; -var StarFeedItemResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the starred feed item"), - starred: external_exports.boolean().describe("Whether the item is now starred"), - starredAt: external_exports.string().datetime().describe("Timestamp when starred") - }) -}); -var UnstarFeedItemRequestSchema = FeedItemPathParamsSchema2; -var UnstarFeedItemResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - feedId: external_exports.string().describe("ID of the unstarred feed item"), - starred: external_exports.boolean().describe("Whether the item is now starred (should be false)") - }) -}); -var SearchFeedRequestSchema2 = FeedPathParamsSchema2.extend({ - query: external_exports.string().min(1).describe("Full-text search query against feed body content"), - type: FeedListFilterType2.optional().describe("Filter by feed item category"), - actorId: external_exports.string().optional().describe("Filter by actor user ID"), - dateFrom: external_exports.string().datetime().optional().describe("Filter feed items created after this timestamp"), - dateTo: external_exports.string().datetime().optional().describe("Filter feed items created before this timestamp"), - hasAttachments: external_exports.boolean().optional().describe("Filter for items with file attachments"), - pinnedOnly: external_exports.boolean().optional().describe("Return only pinned items"), - starredOnly: external_exports.boolean().optional().describe("Return only starred items"), - limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of items to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination") -}); -var SearchFeedResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - items: external_exports.array(FeedItemSchema3).describe("Matching feed items sorted by relevance"), - total: external_exports.number().int().optional().describe("Total matching items"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more items are available") - }) -}); -var GetChangelogRequestSchema2 = FeedPathParamsSchema2.extend({ - field: external_exports.string().optional().describe("Filter changelog to a specific field name"), - actorId: external_exports.string().optional().describe("Filter changelog by actor user ID"), - dateFrom: external_exports.string().datetime().optional().describe("Filter changes after this timestamp"), - dateTo: external_exports.string().datetime().optional().describe("Filter changes before this timestamp"), - limit: external_exports.number().int().min(1).max(200).default(50).describe("Maximum number of changelog entries to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination") -}); -var ChangelogEntrySchema2 = external_exports.object({ - id: external_exports.string().describe("Changelog entry ID"), - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - actor: external_exports.object({ - type: external_exports.enum(["user", "system", "service", "automation"]).describe("Actor type"), - id: external_exports.string().describe("Actor ID"), - name: external_exports.string().optional().describe("Actor display name") - }).describe("Who made the change"), - changes: external_exports.array(FieldChangeEntrySchema4).min(1).describe("Field-level changes"), - timestamp: external_exports.string().datetime().describe("When the change occurred"), - source: external_exports.string().optional().describe('Change source (e.g., "API", "UI", "automation")') -}); -var GetChangelogResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - entries: external_exports.array(ChangelogEntrySchema2).describe("Changelog entries in reverse chronological order"), - total: external_exports.number().int().optional().describe("Total changelog entries matching filter"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more entries are available") - }) -}); -var SubscribeRequestSchema2 = FeedPathParamsSchema2.extend({ - events: external_exports.array(SubscriptionEventType3).default(["all"]).describe("Event types to subscribe to"), - channels: external_exports.array(NotificationChannel3).default(["in_app"]).describe("Notification delivery channels") -}); -var SubscribeResponseSchema2 = BaseResponseSchema2.extend({ - data: RecordSubscriptionSchema3.describe("The created or updated subscription") -}); -var FeedUnsubscribeRequestSchema = FeedPathParamsSchema2; -var UnsubscribeResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - object: external_exports.string().describe("Object name"), - recordId: external_exports.string().describe("Record ID"), - unsubscribed: external_exports.boolean().describe("Whether the user was unsubscribed") - }) -}); -var FeedApiErrorCode2 = external_exports.enum([ - "feed_item_not_found", - "feed_permission_denied", - "feed_item_not_editable", - "feed_invalid_parent", - "reaction_already_exists", - "reaction_not_found", - "subscription_already_exists", - "subscription_not_found", - "invalid_feed_type", - "feed_already_pinned", - "feed_not_pinned", - "feed_already_starred", - "feed_not_starred", - "feed_search_query_too_short" -]); -var FeedApiContracts = { - listFeed: { - method: "GET", - path: "/api/data/:object/:recordId/feed", - input: GetFeedRequestSchema2, - output: GetFeedResponseSchema2 - }, - createFeedItem: { - method: "POST", - path: "/api/data/:object/:recordId/feed", - input: CreateFeedItemRequestSchema2, - output: CreateFeedItemResponseSchema2 - }, - updateFeedItem: { - method: "PUT", - path: "/api/data/:object/:recordId/feed/:feedId", - input: UpdateFeedItemRequestSchema2, - output: UpdateFeedItemResponseSchema2 - }, - deleteFeedItem: { - method: "DELETE", - path: "/api/data/:object/:recordId/feed/:feedId", - input: DeleteFeedItemRequestSchema, - output: DeleteFeedItemResponseSchema2 - }, - addReaction: { - method: "POST", - path: "/api/data/:object/:recordId/feed/:feedId/reactions", - input: AddReactionRequestSchema2, - output: AddReactionResponseSchema2 - }, - removeReaction: { - method: "DELETE", - path: "/api/data/:object/:recordId/feed/:feedId/reactions/:emoji", - input: RemoveReactionRequestSchema2, - output: RemoveReactionResponseSchema2 - }, - pinFeedItem: { - method: "POST", - path: "/api/data/:object/:recordId/feed/:feedId/pin", - input: PinFeedItemRequestSchema, - output: PinFeedItemResponseSchema2 - }, - unpinFeedItem: { - method: "DELETE", - path: "/api/data/:object/:recordId/feed/:feedId/pin", - input: UnpinFeedItemRequestSchema, - output: UnpinFeedItemResponseSchema2 - }, - starFeedItem: { - method: "POST", - path: "/api/data/:object/:recordId/feed/:feedId/star", - input: StarFeedItemRequestSchema, - output: StarFeedItemResponseSchema2 - }, - unstarFeedItem: { - method: "DELETE", - path: "/api/data/:object/:recordId/feed/:feedId/star", - input: UnstarFeedItemRequestSchema, - output: UnstarFeedItemResponseSchema2 - }, - searchFeed: { - method: "GET", - path: "/api/data/:object/:recordId/feed/search", - input: SearchFeedRequestSchema2, - output: SearchFeedResponseSchema2 - }, - getChangelog: { - method: "GET", - path: "/api/data/:object/:recordId/changelog", - input: GetChangelogRequestSchema2, - output: GetChangelogResponseSchema2 - }, - subscribe: { - method: "POST", - path: "/api/data/:object/:recordId/subscribe", - input: SubscribeRequestSchema2, - output: SubscribeResponseSchema2 - }, - unsubscribe: { - method: "DELETE", - path: "/api/data/:object/:recordId/subscribe", - input: FeedUnsubscribeRequestSchema, - output: UnsubscribeResponseSchema2 - } -}; -var ExportFormat2 = external_exports.enum([ - "csv", - "json", - "jsonl", - "xlsx", - "parquet" -]); -var ExportJobStatus2 = external_exports.enum([ - "pending", - "processing", - "completed", - "failed", - "cancelled", - "expired" -]); -var CreateExportJobRequestSchema2 = external_exports.object({ - object: external_exports.string().describe("Object name to export"), - format: ExportFormat2.default("csv").describe("Export file format"), - fields: external_exports.array(external_exports.string()).optional().describe("Specific fields to include (omit for all fields)"), - filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria for records to export"), - sort: external_exports.array(external_exports.object({ - field: external_exports.string().describe("Field name to sort by"), - direction: external_exports.enum(["asc", "desc"]).default("asc").describe("Sort direction") - })).optional().describe("Sort order for exported records"), - limit: external_exports.number().int().min(1).optional().describe("Maximum number of records to export"), - includeHeaders: external_exports.boolean().default(true).describe("Include header row (CSV/XLSX)"), - encoding: external_exports.string().default("utf-8").describe("Character encoding for the export file"), - templateId: external_exports.string().optional().describe("Export template ID for predefined field mappings") -}); -var CreateExportJobResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - jobId: external_exports.string().describe("Export job ID"), - status: ExportJobStatus2.describe("Initial job status"), - estimatedRecords: external_exports.number().int().optional().describe("Estimated total records"), - createdAt: external_exports.string().datetime().describe("Job creation timestamp") - }) -}); -var ExportJobProgressSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - jobId: external_exports.string().describe("Export job ID"), - status: ExportJobStatus2.describe("Current job status"), - format: ExportFormat2.describe("Export format"), - totalRecords: external_exports.number().int().optional().describe("Total records to export"), - processedRecords: external_exports.number().int().describe("Records processed so far"), - percentComplete: external_exports.number().min(0).max(100).describe("Export progress percentage"), - fileSize: external_exports.number().int().optional().describe("Current file size in bytes"), - downloadUrl: external_exports.string().optional().describe('Presigned download URL (available when status is "completed")'), - downloadExpiresAt: external_exports.string().datetime().optional().describe("Download URL expiration timestamp"), - error: external_exports.object({ - code: external_exports.string().describe("Error code"), - message: external_exports.string().describe("Error message") - }).optional().describe("Error details if job failed"), - startedAt: external_exports.string().datetime().optional().describe("Processing start timestamp"), - completedAt: external_exports.string().datetime().optional().describe("Completion timestamp") - }) -}); -var ImportValidationMode2 = external_exports.enum([ - "strict", - // Reject entire import on any validation error - "lenient", - // Skip invalid records, import valid ones - "dry_run" - // Validate all records without persisting -]); -var DeduplicationStrategy2 = external_exports.enum([ - "skip", - // Skip duplicates (keep existing) - "update", - // Update existing with import data - "create_new", - // Create new record even if duplicate - "fail" - // Fail the import if duplicates found -]); -var ImportValidationConfigSchema2 = external_exports.object({ - mode: ImportValidationMode2.default("strict").describe("Validation mode for the import"), - deduplication: external_exports.object({ - strategy: DeduplicationStrategy2.default("skip").describe("How to handle duplicate records"), - matchFields: external_exports.array(external_exports.string()).min(1).describe('Fields used to identify duplicates (e.g., "email", "external_id")') - }).optional().describe("Deduplication configuration"), - maxErrors: external_exports.number().int().min(1).default(100).describe("Maximum validation errors before aborting"), - trimWhitespace: external_exports.boolean().default(true).describe("Trim leading/trailing whitespace from string fields"), - dateFormat: external_exports.string().optional().describe('Expected date format in import data (e.g., "YYYY-MM-DD")'), - nullValues: external_exports.array(external_exports.string()).optional().describe('Strings to treat as null (e.g., ["", "N/A", "null"])') -}); -var ImportValidationResultSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - totalRecords: external_exports.number().int().describe("Total records in import file"), - validRecords: external_exports.number().int().describe("Records that passed validation"), - invalidRecords: external_exports.number().int().describe("Records that failed validation"), - duplicateRecords: external_exports.number().int().describe("Duplicate records detected"), - errors: external_exports.array(external_exports.object({ - row: external_exports.number().int().describe("Row number in the import file"), - field: external_exports.string().optional().describe("Field that failed validation"), - code: external_exports.string().describe("Validation error code"), - message: external_exports.string().describe("Validation error message") - })).describe("List of validation errors"), - preview: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional().describe("Preview of first N valid records (for dry_run mode)") - }) -}); -var FieldMappingEntrySchema2 = external_exports.object({ - sourceField: external_exports.string().describe("Field name in the source data (import) or object (export)"), - targetField: external_exports.string().describe("Field name in the target object (import) or file column (export)"), - targetLabel: external_exports.string().optional().describe("Display label for the target column (export)"), - transform: external_exports.enum(["none", "uppercase", "lowercase", "trim", "date_format", "lookup"]).default("none").describe("Transformation to apply during mapping"), - defaultValue: external_exports.unknown().optional().describe("Default value if source field is null/empty"), - required: external_exports.boolean().default(false).describe("Whether this field is required (import validation)") -}); -var ExportImportTemplateSchema2 = external_exports.object({ - id: external_exports.string().optional().describe("Template ID (generated on save)"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Template machine name (snake_case)"), - label: external_exports.string().describe("Human-readable template label"), - description: external_exports.string().optional().describe("Template description"), - object: external_exports.string().describe("Target object name"), - direction: external_exports.enum(["import", "export", "bidirectional"]).describe("Template direction"), - format: ExportFormat2.optional().describe("Default file format for this template"), - mappings: external_exports.array(FieldMappingEntrySchema2).min(1).describe("Field mapping entries"), - createdAt: external_exports.string().datetime().optional().describe("Template creation timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - createdBy: external_exports.string().optional().describe("User who created the template") -}); -var ScheduledExportSchema2 = external_exports.object({ - id: external_exports.string().optional().describe("Scheduled export ID"), - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Schedule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label"), - object: external_exports.string().describe("Object name to export"), - format: ExportFormat2.default("csv").describe("Export file format"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to include"), - filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record filter criteria"), - templateId: external_exports.string().optional().describe("Export template ID for field mappings"), - schedule: external_exports.object({ - cronExpression: external_exports.string().describe("Cron expression for schedule"), - timezone: external_exports.string().default("UTC").describe("IANA timezone") - }).describe("Schedule timing configuration"), - delivery: external_exports.object({ - method: external_exports.enum(["email", "storage", "webhook"]).describe("How to deliver the export file"), - recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients (for email delivery)"), - storagePath: external_exports.string().optional().describe("Storage path (for storage delivery)"), - webhookUrl: external_exports.string().optional().describe("Webhook URL (for webhook delivery)") - }).describe("Export delivery configuration"), - enabled: external_exports.boolean().default(true).describe("Whether the scheduled export is active"), - lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp"), - nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution"), - createdAt: external_exports.string().datetime().optional().describe("Creation timestamp"), - createdBy: external_exports.string().optional().describe("User who created the schedule") -}); -var GetExportJobDownloadRequestSchema2 = external_exports.object({ - jobId: external_exports.string().describe("Export job ID") -}); -var GetExportJobDownloadResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - jobId: external_exports.string().describe("Export job ID"), - downloadUrl: external_exports.string().describe("Presigned download URL"), - fileName: external_exports.string().describe("Suggested file name"), - fileSize: external_exports.number().int().describe("File size in bytes"), - format: ExportFormat2.describe("Export file format"), - expiresAt: external_exports.string().datetime().describe("Download URL expiration timestamp"), - checksum: external_exports.string().optional().describe("File checksum (SHA-256)") - }) -}); -var ListExportJobsRequestSchema2 = external_exports.object({ - object: external_exports.string().optional().describe("Filter by object name"), - status: ExportJobStatus2.optional().describe("Filter by job status"), - limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of jobs to return"), - cursor: external_exports.string().optional().describe("Pagination cursor from a previous response") -}); -var ExportJobSummarySchema2 = external_exports.object({ - jobId: external_exports.string().describe("Export job ID"), - object: external_exports.string().describe("Object name that was exported"), - status: ExportJobStatus2.describe("Current job status"), - format: ExportFormat2.describe("Export file format"), - totalRecords: external_exports.number().int().optional().describe("Total records exported"), - fileSize: external_exports.number().int().optional().describe("File size in bytes"), - createdAt: external_exports.string().datetime().describe("Job creation timestamp"), - completedAt: external_exports.string().datetime().optional().describe("Completion timestamp"), - createdBy: external_exports.string().optional().describe("User who initiated the export") -}); -var ListExportJobsResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - jobs: external_exports.array(ExportJobSummarySchema2).describe("List of export jobs"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more jobs are available") - }) -}); -var ScheduleExportRequestSchema2 = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Schedule name (snake_case)"), - label: external_exports.string().optional().describe("Human-readable label"), - object: external_exports.string().describe("Object name to export"), - format: ExportFormat2.default("csv").describe("Export file format"), - fields: external_exports.array(external_exports.string()).optional().describe("Fields to include"), - filter: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record filter criteria"), - templateId: external_exports.string().optional().describe("Export template ID for field mappings"), - schedule: external_exports.object({ - cronExpression: external_exports.string().describe("Cron expression for schedule"), - timezone: external_exports.string().default("UTC").describe("IANA timezone") - }).describe("Schedule timing configuration"), - delivery: external_exports.object({ - method: external_exports.enum(["email", "storage", "webhook"]).describe("How to deliver the export file"), - recipients: external_exports.array(external_exports.string()).optional().describe("Email recipients (for email delivery)"), - storagePath: external_exports.string().optional().describe("Storage path (for storage delivery)"), - webhookUrl: external_exports.string().optional().describe("Webhook URL (for webhook delivery)") - }).describe("Export delivery configuration") -}); -var ScheduleExportResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - id: external_exports.string().describe("Scheduled export ID"), - name: external_exports.string().describe("Schedule name"), - enabled: external_exports.boolean().describe("Whether the schedule is active"), - nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution"), - createdAt: external_exports.string().datetime().describe("Creation timestamp") - }) -}); -var ExportApiContracts2 = { - createExportJob: { - method: "POST", - path: "/api/v1/data/:object/export", - input: CreateExportJobRequestSchema2, - output: CreateExportJobResponseSchema2 - }, - getExportJobProgress: { - method: "GET", - path: "/api/v1/data/export/:jobId", - input: external_exports.object({ jobId: external_exports.string() }), - output: ExportJobProgressSchema2 - }, - getExportJobDownload: { - method: "GET", - path: "/api/v1/data/export/:jobId/download", - input: GetExportJobDownloadRequestSchema2, - output: GetExportJobDownloadResponseSchema2 - }, - listExportJobs: { - method: "GET", - path: "/api/v1/data/export", - input: ListExportJobsRequestSchema2, - output: ListExportJobsResponseSchema2 - }, - scheduleExport: { - method: "POST", - path: "/api/v1/data/export/schedules", - input: ScheduleExportRequestSchema2, - output: ScheduleExportResponseSchema2 - }, - cancelExportJob: { - method: "POST", - path: "/api/v1/data/export/:jobId/cancel", - input: external_exports.object({ jobId: external_exports.string() }), - output: BaseResponseSchema2 - } -}; -var FlowNodeAction2 = external_exports.enum([ - "start", - // Trigger - "end", - // Return/Stop - "decision", - // If/Else logic - "assignment", - // Set Variable - "loop", - // For Each - "create_record", - // CRUD: Create - "update_record", - // CRUD: Update - "delete_record", - // CRUD: Delete - "get_record", - // CRUD: Get/Query - "http_request", - // Webhook/API Call - "script", - // Custom Script (JS/TS) - "screen", - // Screen / User-Input Element - "wait", - // Delay/Sleep - "subflow", - // Call another flow - "connector_action", - // Zapier-style integration action - "parallel_gateway", - // BPMN Parallel Gateway — AND-split (all outgoing branches execute concurrently) - "join_gateway", - // BPMN Join Gateway — AND-join (waits for all incoming branches to complete) - "boundary_event" - // BPMN Boundary Event — attached to a host node for timer/error/signal interrupts -]); -var FlowVariableSchema2 = external_exports.object({ - name: external_exports.string().describe("Variable name"), - type: external_exports.string().describe("Data type (text, number, boolean, object, list)"), - isInput: external_exports.boolean().default(false).describe("Is input parameter"), - isOutput: external_exports.boolean().default(false).describe("Is output parameter") -}); -var FlowNodeSchema2 = external_exports.object({ - id: external_exports.string().describe("Node unique ID"), - type: FlowNodeAction2.describe("Action type"), - label: external_exports.string().describe("Node label"), - /** Node Configuration Options (Specific to type) */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Node configuration"), - /** - * Connector Action Configuration - * Used when type is 'connector_action' - */ - connectorConfig: external_exports.object({ - connectorId: external_exports.string(), - actionId: external_exports.string(), - input: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Mapped inputs for the action") - }).optional(), - /** UI Position (for the canvas) */ - position: external_exports.object({ x: external_exports.number(), y: external_exports.number() }).optional(), - /** Node-level execution timeout */ - timeoutMs: external_exports.number().int().min(0).optional().describe("Maximum execution time for this node in milliseconds"), - /** Node input schema declaration for Studio form generation and runtime validation */ - inputSchema: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["string", "number", "boolean", "object", "array"]).describe("Parameter type"), - required: external_exports.boolean().default(false).describe("Whether the parameter is required"), - description: external_exports.string().optional().describe("Parameter description") - })).optional().describe("Input parameter schema for this node"), - /** Node output schema declaration */ - outputSchema: external_exports.record(external_exports.string(), external_exports.object({ - type: external_exports.enum(["string", "number", "boolean", "object", "array"]).describe("Output type"), - description: external_exports.string().optional().describe("Output description") - })).optional().describe("Output schema declaration for this node"), - /** - * Wait Event Configuration (for 'wait' nodes) - * Defines what external event or condition should resume the paused execution. - * Industry alignment: BPMN Intermediate Catch Events, Temporal Signals. - */ - waitEventConfig: external_exports.object({ - /** Type of event to wait for */ - eventType: external_exports.enum(["timer", "signal", "webhook", "manual", "condition"]).describe("What kind of event resumes the execution"), - /** Duration to wait (ISO 8601 duration or milliseconds) — for timer events */ - timerDuration: external_exports.string().optional().describe('ISO 8601 duration (e.g., "PT1H") or wait time for timer events'), - /** Signal name to listen for — for signal/webhook events */ - signalName: external_exports.string().optional().describe("Named signal or webhook event to wait for"), - /** Timeout before auto-failing or continuing — optional guard */ - timeoutMs: external_exports.number().int().min(0).optional().describe("Maximum wait time before timeout (ms)"), - /** Action to take on timeout */ - onTimeout: external_exports.enum(["fail", "continue"]).default("fail").describe("Behavior when the wait times out") - }).optional().describe("Configuration for wait node event resumption"), - /** - * Boundary Event Configuration (for 'boundary_event' nodes) - * Attaches an event handler to a host activity node (BPMN Boundary Event pattern). - * Industry alignment: BPMN Boundary Error/Timer/Signal Events. - */ - boundaryConfig: external_exports.object({ - /** ID of the host node this boundary event is attached to */ - attachedToNodeId: external_exports.string().describe("Host node ID this boundary event monitors"), - /** Type of boundary event */ - eventType: external_exports.enum(["error", "timer", "signal", "cancel"]).describe("Boundary event trigger type"), - /** Whether the boundary event interrupts the host activity */ - interrupting: external_exports.boolean().default(true).describe("If true, the host activity is cancelled when this event fires"), - /** Error code filter — only for error boundary events */ - errorCode: external_exports.string().optional().describe("Specific error code to catch (empty = catch all errors)"), - /** Timer duration — only for timer boundary events */ - timerDuration: external_exports.string().optional().describe("ISO 8601 duration for timer boundary events"), - /** Signal name — only for signal boundary events */ - signalName: external_exports.string().optional().describe("Named signal to catch") - }).optional().describe("Configuration for boundary events attached to host nodes") -}); -var FlowEdgeSchema2 = external_exports.object({ - id: external_exports.string().describe("Edge unique ID"), - source: external_exports.string().describe("Source Node ID"), - target: external_exports.string().describe("Target Node ID"), - /** Condition for this path (only for decision/branch nodes) */ - condition: external_exports.string().optional().describe("Expression returning boolean used for branching"), - type: external_exports.enum(["default", "fault", "conditional"]).default("default").describe("Connection type: default (normal flow), fault (error path), or conditional (expression-guarded)"), - label: external_exports.string().optional().describe("Label on the connector"), - /** - * Default Sequence Flow marker (BPMN Default Flow semantics). - * When true, this edge is taken when no sibling conditional edges match. - * Only meaningful on outgoing edges of decision/gateway nodes. - */ - isDefault: external_exports.boolean().default(false).describe("Marks this edge as the default path when no other conditions match") -}); -var FlowSchema2 = external_exports.object({ - /** Identity */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name"), - label: external_exports.string().describe("Flow label"), - description: external_exports.string().optional(), - /** Metadata & Versioning */ - version: external_exports.number().int().default(1).describe("Version number"), - status: external_exports.enum(["draft", "active", "obsolete", "invalid"]).default("draft").describe("Deployment status"), - template: external_exports.boolean().default(false).describe("Is logic template (Subflow)"), - /** Trigger Type */ - type: external_exports.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).describe("Flow type"), - /** Configuration Variables */ - variables: external_exports.array(FlowVariableSchema2).optional().describe("Flow variables"), - /** Graph Definition */ - nodes: external_exports.array(FlowNodeSchema2).describe("Flow nodes"), - edges: external_exports.array(FlowEdgeSchema2).describe("Flow connections"), - /** Execution Config */ - active: external_exports.boolean().default(false).describe("Is active (Deprecated: use status)"), - runAs: external_exports.enum(["system", "user"]).default("user").describe("Execution context"), - /** Error Handling Strategy */ - errorHandling: external_exports.object({ - strategy: external_exports.enum(["fail", "retry", "continue"]).default("fail").describe("How to handle node execution errors"), - maxRetries: external_exports.number().int().min(0).max(10).default(0).describe("Number of retry attempts (only for retry strategy)"), - retryDelayMs: external_exports.number().int().min(0).default(1e3).describe("Delay between retries in milliseconds"), - backoffMultiplier: external_exports.number().min(1).default(1).describe("Multiplier for exponential backoff between retries"), - maxRetryDelayMs: external_exports.number().int().min(0).default(3e4).describe("Maximum delay between retries in milliseconds"), - jitter: external_exports.boolean().default(false).describe("Add random jitter to retry delay to avoid thundering herd"), - fallbackNodeId: external_exports.string().optional().describe("Node ID to jump to on unrecoverable error") - }).optional().describe("Flow-level error handling configuration") -}); -function defineFlow(config4) { - return FlowSchema2.parse(config4); -} -var FlowVersionHistorySchema = external_exports.object({ - flowName: external_exports.string().describe("Flow machine name"), - version: external_exports.number().int().min(1).describe("Version number"), - definition: FlowSchema2.describe("Complete flow definition snapshot"), - createdAt: external_exports.string().datetime().describe("When this version was created"), - createdBy: external_exports.string().optional().describe("User who created this version"), - changeNote: external_exports.string().optional().describe("Description of what changed in this version") -}); -var ExecutionStatus2 = external_exports.enum([ - "pending", - // Queued, not yet started - "running", - // Currently executing - "paused", - // Paused at a wait/checkpoint node - "completed", - // Successfully finished - "failed", - // Terminated with error - "cancelled", - // Manually cancelled - "timed_out", - // Exceeded max execution time - "retrying" - // Failed and retrying -]); -var ExecutionStepLogSchema2 = external_exports.object({ - nodeId: external_exports.string().describe("Node ID that was executed"), - nodeType: external_exports.string().describe('Node action type (e.g., "decision", "http_request")'), - nodeLabel: external_exports.string().optional().describe("Human-readable node label"), - status: external_exports.enum(["success", "failure", "skipped"]).describe("Step execution result"), - startedAt: external_exports.string().datetime().describe("When the step started"), - completedAt: external_exports.string().datetime().optional().describe("When the step completed"), - durationMs: external_exports.number().int().min(0).optional().describe("Step execution duration in milliseconds"), - input: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Input data passed to the node"), - output: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Output data produced by the node"), - error: external_exports.object({ - code: external_exports.string().describe("Error code"), - message: external_exports.string().describe("Error message"), - stack: external_exports.string().optional().describe("Stack trace") - }).optional().describe("Error details if step failed"), - retryAttempt: external_exports.number().int().min(0).optional().describe("Retry attempt number (0 = first try)") -}); -var ExecutionLogSchema2 = external_exports.object({ - /** Unique execution ID */ - id: external_exports.string().describe("Execution instance ID"), - /** Flow reference */ - flowName: external_exports.string().describe("Machine name of the executed flow"), - flowVersion: external_exports.number().int().optional().describe("Version of the flow that was executed"), - /** Execution status */ - status: ExecutionStatus2.describe("Current execution status"), - /** Trigger context */ - trigger: external_exports.object({ - type: external_exports.string().describe('Trigger type (e.g., "record_change", "schedule", "api", "manual")'), - recordId: external_exports.string().optional().describe("Triggering record ID"), - object: external_exports.string().optional().describe("Triggering object name"), - userId: external_exports.string().optional().describe("User who triggered the execution"), - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional trigger context") - }).describe("What triggered this execution"), - /** Step-by-step execution history */ - steps: external_exports.array(ExecutionStepLogSchema2).describe("Ordered list of executed steps"), - /** Execution variables snapshot */ - variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Final state of flow variables"), - /** Timing */ - startedAt: external_exports.string().datetime().describe("Execution start timestamp"), - completedAt: external_exports.string().datetime().optional().describe("Execution completion timestamp"), - durationMs: external_exports.number().int().min(0).optional().describe("Total execution duration in milliseconds"), - /** Context */ - runAs: external_exports.enum(["system", "user"]).optional().describe("Execution context identity"), - tenantId: external_exports.string().optional().describe("Tenant ID for multi-tenant isolation") -}); -var ExecutionErrorSeverity2 = external_exports.enum([ - "warning", - // Non-fatal issue (e.g., deprecated node type) - "error", - // Node-level failure (may be retried) - "critical" - // Flow-level failure (execution terminated) -]); -var ExecutionErrorSchema = external_exports.object({ - id: external_exports.string().describe("Error record ID"), - executionId: external_exports.string().describe("Parent execution ID"), - nodeId: external_exports.string().optional().describe("Node where the error occurred"), - severity: ExecutionErrorSeverity2.describe("Error severity level"), - code: external_exports.string().describe("Machine-readable error code"), - message: external_exports.string().describe("Human-readable error message"), - stack: external_exports.string().optional().describe("Stack trace for debugging"), - context: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional diagnostic context (input data, config snapshot)"), - timestamp: external_exports.string().datetime().describe("When the error occurred"), - retryable: external_exports.boolean().default(false).describe("Whether this error can be retried"), - resolvedAt: external_exports.string().datetime().optional().describe("When the error was resolved (e.g., after successful retry)") -}); -var CheckpointSchema = external_exports.object({ - /** Unique checkpoint ID */ - id: external_exports.string().describe("Checkpoint ID"), - /** Execution reference */ - executionId: external_exports.string().describe("Parent execution ID"), - flowName: external_exports.string().describe("Flow machine name"), - /** State snapshot */ - currentNodeId: external_exports.string().describe("Node ID where execution is paused"), - variables: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Flow variable state at checkpoint"), - completedNodeIds: external_exports.array(external_exports.string()).describe("List of node IDs already executed"), - /** Timing */ - createdAt: external_exports.string().datetime().describe("Checkpoint creation timestamp"), - expiresAt: external_exports.string().datetime().optional().describe("Checkpoint expiration (auto-cleanup)"), - /** Reason */ - reason: external_exports.enum(["wait", "screen_input", "approval", "error", "manual_pause", "parallel_join", "boundary_event"]).describe("Why the execution was checkpointed") -}); -var ConcurrencyPolicySchema = external_exports.object({ - /** Maximum concurrent executions of this flow */ - maxConcurrent: external_exports.number().int().min(1).default(1).describe("Maximum number of concurrent executions allowed"), - /** What to do when max concurrency is reached */ - onConflict: external_exports.enum(["queue", "reject", "cancel_existing"]).default("queue").describe("queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance"), - /** Lock scope for concurrency */ - lockScope: external_exports.enum(["global", "per_record", "per_user"]).default("global").describe("Scope of the concurrency lock"), - /** Queue timeout (only when onConflict is "queue") */ - queueTimeoutMs: external_exports.number().int().min(0).optional().describe("Maximum time to wait in queue before timing out (ms)") -}); -var ScheduleStateSchema = external_exports.object({ - /** Unique schedule ID */ - id: external_exports.string().describe("Schedule instance ID"), - /** Flow reference */ - flowName: external_exports.string().describe("Flow machine name"), - /** Schedule configuration */ - cronExpression: external_exports.string().describe('Cron expression (e.g., "0 9 * * MON-FRI")'), - timezone: external_exports.string().default("UTC").describe("IANA timezone for cron evaluation"), - /** Runtime state */ - status: external_exports.enum(["active", "paused", "disabled", "expired"]).default("active").describe("Current schedule status"), - nextRunAt: external_exports.string().datetime().optional().describe("Next scheduled execution timestamp"), - lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp"), - lastExecutionId: external_exports.string().optional().describe("Execution ID of the last run"), - lastRunStatus: ExecutionStatus2.optional().describe("Status of the last run"), - /** Execution tracking */ - totalRuns: external_exports.number().int().min(0).default(0).describe("Total number of executions"), - consecutiveFailures: external_exports.number().int().min(0).default(0).describe("Consecutive failed executions"), - /** Bounds */ - startDate: external_exports.string().datetime().optional().describe("Schedule effective start date"), - endDate: external_exports.string().datetime().optional().describe("Schedule expiration date"), - maxRuns: external_exports.number().int().min(1).optional().describe("Maximum total executions before auto-disable"), - /** Metadata */ - createdAt: external_exports.string().datetime().describe("Schedule creation timestamp"), - updatedAt: external_exports.string().datetime().optional().describe("Last update timestamp"), - createdBy: external_exports.string().optional().describe("User who created the schedule") -}); -var AutomationFlowPathParamsSchema2 = external_exports.object({ - name: external_exports.string().describe("Flow machine name (snake_case)") -}); -var AutomationRunPathParamsSchema2 = AutomationFlowPathParamsSchema2.extend({ - runId: external_exports.string().describe("Execution run ID") -}); -var ListFlowsRequestSchema2 = external_exports.object({ - status: external_exports.enum(["draft", "active", "obsolete", "invalid"]).optional().describe("Filter by flow status"), - type: external_exports.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).optional().describe("Filter by flow type"), - limit: external_exports.number().int().min(1).max(100).default(50).describe("Maximum number of flows to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination") -}); -var FlowSummarySchema2 = external_exports.object({ - name: external_exports.string().describe("Flow machine name"), - label: external_exports.string().describe("Flow display label"), - type: external_exports.string().describe("Flow type"), - status: external_exports.string().describe("Flow deployment status"), - version: external_exports.number().int().describe("Flow version number"), - enabled: external_exports.boolean().describe("Whether the flow is enabled for execution"), - nodeCount: external_exports.number().int().optional().describe("Number of nodes in the flow"), - lastRunAt: external_exports.string().datetime().optional().describe("Last execution timestamp") -}); -var ListFlowsResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - flows: external_exports.array(FlowSummarySchema2).describe("Flow summaries"), - total: external_exports.number().int().optional().describe("Total matching flows"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more flows are available") - }) -}); -var GetFlowRequestSchema = AutomationFlowPathParamsSchema2; -var GetFlowResponseSchema2 = BaseResponseSchema2.extend({ - data: FlowSchema2.describe("Full flow definition") -}); -var CreateFlowRequestSchema = FlowSchema2; -var CreateFlowResponseSchema2 = BaseResponseSchema2.extend({ - data: FlowSchema2.describe("The created flow definition") -}); -var UpdateFlowRequestSchema2 = AutomationFlowPathParamsSchema2.extend({ - definition: FlowSchema2.partial().describe("Partial flow definition to update") -}); -var UpdateFlowResponseSchema2 = BaseResponseSchema2.extend({ - data: FlowSchema2.describe("The updated flow definition") -}); -var DeleteFlowRequestSchema = AutomationFlowPathParamsSchema2; -var DeleteFlowResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - name: external_exports.string().describe("Name of the deleted flow"), - deleted: external_exports.boolean().describe("Whether the flow was deleted") - }) -}); -var TriggerFlowRequestSchema2 = AutomationFlowPathParamsSchema2.extend({ - record: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Record that triggered the automation"), - object: external_exports.string().optional().describe("Object name the record belongs to"), - event: external_exports.string().optional().describe("Trigger event type"), - userId: external_exports.string().optional().describe("User who triggered the automation"), - params: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional contextual data") -}); -var TriggerFlowResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - success: external_exports.boolean().describe("Whether the automation completed successfully"), - output: external_exports.unknown().optional().describe("Output data from the automation"), - error: external_exports.string().optional().describe("Error message if execution failed"), - durationMs: external_exports.number().optional().describe("Execution duration in milliseconds") - }) -}); -var ToggleFlowRequestSchema2 = AutomationFlowPathParamsSchema2.extend({ - enabled: external_exports.boolean().describe("Whether to enable (true) or disable (false) the flow") -}); -var ToggleFlowResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - name: external_exports.string().describe("Flow name"), - enabled: external_exports.boolean().describe("New enabled state") - }) -}); -var ListRunsRequestSchema2 = AutomationFlowPathParamsSchema2.extend({ - status: external_exports.enum(["pending", "running", "paused", "completed", "failed", "cancelled", "timed_out", "retrying"]).optional().describe("Filter by execution status"), - limit: external_exports.number().int().min(1).max(100).default(20).describe("Maximum number of runs to return"), - cursor: external_exports.string().optional().describe("Cursor for pagination") -}); -var ListRunsResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - runs: external_exports.array(ExecutionLogSchema2).describe("Execution run logs"), - total: external_exports.number().int().optional().describe("Total matching runs"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more runs are available") - }) -}); -var GetRunRequestSchema = AutomationRunPathParamsSchema2; -var GetRunResponseSchema2 = BaseResponseSchema2.extend({ - data: ExecutionLogSchema2.describe("Full execution log with step details") -}); -var AutomationApiErrorCode2 = external_exports.enum([ - "flow_not_found", - "flow_already_exists", - "flow_validation_failed", - "flow_disabled", - "execution_not_found", - "execution_failed", - "execution_timeout", - "node_executor_not_found", - "concurrent_execution_limit" -]); -var AutomationApiContracts = { - listFlows: { - method: "GET", - path: "/api/automation", - input: ListFlowsRequestSchema2, - output: ListFlowsResponseSchema2 - }, - getFlow: { - method: "GET", - path: "/api/automation/:name", - input: GetFlowRequestSchema, - output: GetFlowResponseSchema2 - }, - createFlow: { - method: "POST", - path: "/api/automation", - input: CreateFlowRequestSchema, - output: CreateFlowResponseSchema2 - }, - updateFlow: { - method: "PUT", - path: "/api/automation/:name", - input: UpdateFlowRequestSchema2, - output: UpdateFlowResponseSchema2 - }, - deleteFlow: { - method: "DELETE", - path: "/api/automation/:name", - input: DeleteFlowRequestSchema, - output: DeleteFlowResponseSchema2 - }, - triggerFlow: { - method: "POST", - path: "/api/automation/:name/trigger", - input: TriggerFlowRequestSchema2, - output: TriggerFlowResponseSchema2 - }, - toggleFlow: { - method: "POST", - path: "/api/automation/:name/toggle", - input: ToggleFlowRequestSchema2, - output: ToggleFlowResponseSchema2 - }, - listRuns: { - method: "GET", - path: "/api/automation/:name/runs", - input: ListRunsRequestSchema2, - output: ListRunsResponseSchema2 - }, - getRun: { - method: "GET", - path: "/api/automation/:name/runs/:runId", - input: GetRunRequestSchema, - output: GetRunResponseSchema2 - } -}; -var PackagePathParamsSchema2 = external_exports.object({ - packageId: external_exports.string().describe("Package identifier") -}); -var ListInstalledPackagesRequestSchema2 = external_exports.object({ - /** Filter by package status */ - status: external_exports.enum(["installed", "disabled", "installing", "upgrading", "uninstalling", "error"]).optional().describe("Filter by package status"), - /** Filter by enabled state */ - enabled: external_exports.boolean().optional().describe("Filter by enabled state"), - /** Maximum number of packages to return */ - limit: external_exports.number().int().min(1).max(100).default(50).describe("Maximum number of packages to return"), - /** Cursor for pagination */ - cursor: external_exports.string().optional().describe("Cursor for pagination") -}).describe("List installed packages request"); -var ListInstalledPackagesResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - packages: external_exports.array(InstalledPackageSchema3).describe("Installed packages"), - total: external_exports.number().int().optional().describe("Total matching packages"), - nextCursor: external_exports.string().optional().describe("Cursor for the next page"), - hasMore: external_exports.boolean().describe("Whether more packages are available") - }) -}).describe("List installed packages response"); -var GetInstalledPackageRequestSchema = PackagePathParamsSchema2; -var GetInstalledPackageResponseSchema2 = BaseResponseSchema2.extend({ - data: InstalledPackageSchema3.describe("Installed package details") -}).describe("Get installed package response"); -var PackageInstallRequestSchema2 = external_exports.object({ - /** Package manifest to install */ - manifest: ManifestSchema3.describe("Package manifest to install"), - /** User-provided settings at install time */ - settings: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("User-provided settings at install time"), - /** Whether to enable immediately after install */ - enableOnInstall: external_exports.boolean().default(true).describe("Whether to enable immediately after install"), - /** Current platform version for compatibility verification */ - platformVersion: external_exports.string().optional().describe("Current platform version for compatibility verification"), - /** Artifact reference for the package (if installing from marketplace) */ - artifactRef: ArtifactReferenceSchema2.optional().describe("Artifact reference for marketplace installation") -}).describe("Install package request"); -var PackageInstallResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - package: InstalledPackageSchema3.describe("Installed package details"), - dependencyResolution: DependencyResolutionResultSchema3.optional().describe("Dependency resolution result"), - namespaceConflicts: external_exports.array(external_exports.object({ - type: external_exports.literal("namespace_conflict").describe("Error type"), - requestedNamespace: external_exports.string().describe("Requested namespace"), - conflictingPackageId: external_exports.string().describe("Conflicting package ID"), - conflictingPackageName: external_exports.string().describe("Conflicting package name"), - suggestion: external_exports.string().optional().describe("Suggested alternative") - })).optional().describe("Namespace conflicts detected"), - message: external_exports.string().optional().describe("Installation status message") - }) -}).describe("Install package response"); -var PackageUpgradeRequestSchema2 = external_exports.object({ - /** Package ID to upgrade */ - packageId: external_exports.string().describe("Package ID to upgrade"), - /** Target version (defaults to latest) */ - targetVersion: external_exports.string().optional().describe("Target version (defaults to latest)"), - /** New manifest for the target version */ - manifest: ManifestSchema3.optional().describe("New manifest for the target version"), - /** Whether to create a pre-upgrade snapshot */ - createSnapshot: external_exports.boolean().default(true).describe("Whether to create a pre-upgrade backup snapshot"), - /** Merge strategy for handling customizations */ - mergeStrategy: external_exports.enum(["keep-custom", "accept-incoming", "three-way-merge"]).default("three-way-merge").describe("How to handle customer customizations"), - /** Preview upgrade without making changes */ - dryRun: external_exports.boolean().default(false).describe("Preview upgrade without making changes"), - /** Skip pre-upgrade compatibility checks */ - skipValidation: external_exports.boolean().default(false).describe("Skip pre-upgrade compatibility checks") -}).describe("Upgrade package request"); -var PackageUpgradeResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - success: external_exports.boolean().describe("Whether the upgrade succeeded"), - phase: external_exports.string().describe("Current upgrade phase"), - plan: UpgradePlanSchema3.optional().describe("Upgrade plan that was executed"), - snapshotId: external_exports.string().optional().describe("Snapshot ID for rollback"), - conflicts: external_exports.array(external_exports.object({ - path: external_exports.string().describe("Conflict path"), - baseValue: external_exports.unknown().describe("Base value"), - incomingValue: external_exports.unknown().describe("Incoming value"), - customValue: external_exports.unknown().describe("Custom value") - })).optional().describe("Unresolved merge conflicts"), - errorMessage: external_exports.string().optional().describe("Error message if failed"), - message: external_exports.string().optional().describe("Human-readable status message") - }) -}).describe("Upgrade package response"); -var ResolveDependenciesRequestSchema2 = external_exports.object({ - /** Package manifest whose dependencies to resolve */ - manifest: ManifestSchema3.describe("Package manifest to resolve dependencies for"), - /** Current platform version for compatibility checking */ - platformVersion: external_exports.string().optional().describe("Current platform version for compatibility filtering") -}).describe("Resolve dependencies request"); -var ResolveDependenciesResponseSchema2 = BaseResponseSchema2.extend({ - data: DependencyResolutionResultSchema3.describe("Dependency resolution result with topological sort") -}).describe("Resolve dependencies response"); -var UploadArtifactRequestSchema2 = external_exports.object({ - /** Artifact metadata */ - artifact: PackageArtifactSchema3.describe("Package artifact metadata"), - /** SHA256 checksum of the uploaded file (for verification) */ - sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).optional().describe("SHA256 checksum of the uploaded file"), - /** Publisher authentication token */ - token: external_exports.string().optional().describe("Publisher authentication token"), - /** Release notes for this version */ - releaseNotes: external_exports.string().optional().describe("Release notes for this version") -}).describe("Upload artifact request"); -var UploadArtifactResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - /** Whether the upload succeeded */ - success: external_exports.boolean().describe("Whether the upload succeeded"), - /** Artifact reference for the uploaded package */ - artifactRef: ArtifactReferenceSchema2.optional().describe("Artifact reference in the registry"), - /** Submission ID for review tracking */ - submissionId: external_exports.string().optional().describe("Marketplace submission ID for review tracking"), - /** Message */ - message: external_exports.string().optional().describe("Upload status message") - }) -}).describe("Upload artifact response"); -var PackageRollbackRequestSchema2 = PackagePathParamsSchema2.extend({ - /** Snapshot ID to restore from */ - snapshotId: external_exports.string().describe("Snapshot ID to restore from"), - /** Whether to also rollback customizations */ - rollbackCustomizations: external_exports.boolean().default(true).describe("Whether to restore pre-upgrade customizations") -}).describe("Rollback package request"); -var PackageRollbackResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - success: external_exports.boolean().describe("Whether the rollback succeeded"), - restoredVersion: external_exports.string().optional().describe("Restored version"), - message: external_exports.string().optional().describe("Rollback status message") - }) -}).describe("Rollback package response"); -var UninstallPackageApiRequestSchema = PackagePathParamsSchema2; -var UninstallPackageApiResponseSchema2 = BaseResponseSchema2.extend({ - data: external_exports.object({ - packageId: external_exports.string().describe("Uninstalled package ID"), - success: external_exports.boolean().describe("Whether uninstall succeeded"), - message: external_exports.string().optional().describe("Uninstall status message") - }) -}).describe("Uninstall package response"); -var PackageApiErrorCode2 = external_exports.enum([ - "package_not_found", - "package_already_installed", - "version_not_found", - "dependency_conflict", - "namespace_conflict", - "platform_incompatible", - "artifact_invalid", - "checksum_mismatch", - "signature_invalid", - "upgrade_failed", - "rollback_failed", - "snapshot_not_found", - "upload_failed" -]); -var PackageApiContracts = { - listPackages: { - method: "GET", - path: "/api/v1/packages", - input: ListInstalledPackagesRequestSchema2, - output: ListInstalledPackagesResponseSchema2 - }, - getPackage: { - method: "GET", - path: "/api/v1/packages/:packageId", - input: GetInstalledPackageRequestSchema, - output: GetInstalledPackageResponseSchema2 - }, - installPackage: { - method: "POST", - path: "/api/v1/packages/install", - input: PackageInstallRequestSchema2, - output: PackageInstallResponseSchema2 - }, - upgradePackage: { - method: "POST", - path: "/api/v1/packages/upgrade", - input: PackageUpgradeRequestSchema2, - output: PackageUpgradeResponseSchema2 - }, - resolveDependencies: { - method: "POST", - path: "/api/v1/packages/resolve-dependencies", - input: ResolveDependenciesRequestSchema2, - output: ResolveDependenciesResponseSchema2 - }, - uploadArtifact: { - method: "POST", - path: "/api/v1/packages/upload", - input: UploadArtifactRequestSchema2, - output: UploadArtifactResponseSchema2 - }, - rollbackPackage: { - method: "POST", - path: "/api/v1/packages/:packageId/rollback", - input: PackageRollbackRequestSchema2, - output: PackageRollbackResponseSchema2 - }, - uninstallPackage: { - method: "DELETE", - path: "/api/v1/packages/:packageId", - input: UninstallPackageApiRequestSchema, - output: UninstallPackageApiResponseSchema2 - } -}; -var automation_exports = {}; -__export4(automation_exports, { - ActionRefSchema: () => ActionRefSchema4, - ApprovalActionSchema: () => ApprovalActionSchema, - ApprovalActionType: () => ApprovalActionType, - ApprovalProcess: () => ApprovalProcess, - ApprovalProcessSchema: () => ApprovalProcessSchema, - ApprovalStepSchema: () => ApprovalStepSchema, - ApproverType: () => ApproverType, - AuthFieldSchema: () => AuthFieldSchema, - AuthenticationSchema: () => AuthenticationSchema, - AuthenticationTypeSchema: () => AuthenticationTypeSchema, - BUILT_IN_BPMN_MAPPINGS: () => BUILT_IN_BPMN_MAPPINGS, - BpmnDiagnosticSchema: () => BpmnDiagnosticSchema, - BpmnElementMappingSchema: () => BpmnElementMappingSchema, - BpmnExportOptionsSchema: () => BpmnExportOptionsSchema, - BpmnImportOptionsSchema: () => BpmnImportOptionsSchema, - BpmnInteropResultSchema: () => BpmnInteropResultSchema, - BpmnUnmappedStrategySchema: () => BpmnUnmappedStrategySchema, - BpmnVersionSchema: () => BpmnVersionSchema, - CheckpointSchema: () => CheckpointSchema, - ConcurrencyPolicySchema: () => ConcurrencyPolicySchema, - ConflictResolutionSchema: () => ConflictResolutionSchema22, - Connector: () => Connector, - ConnectorActionRefSchema: () => ConnectorActionRefSchema2, - ConnectorCategorySchema: () => ConnectorCategorySchema, - ConnectorInstanceSchema: () => ConnectorInstanceSchema, - ConnectorOperationSchema: () => ConnectorOperationSchema, - ConnectorSchema: () => ConnectorSchema, - ConnectorTriggerSchema: () => ConnectorTriggerSchema, - CustomScriptActionSchema: () => CustomScriptActionSchema2, - DataDestinationConfigSchema: () => DataDestinationConfigSchema, - DataSourceConfigSchema: () => DataSourceConfigSchema, - DataSyncConfigSchema: () => DataSyncConfigSchema, - ETL: () => ETL, - ETLDestinationSchema: () => ETLDestinationSchema, - ETLEndpointTypeSchema: () => ETLEndpointTypeSchema, - ETLPipelineRunSchema: () => ETLPipelineRunSchema, - ETLPipelineSchema: () => ETLPipelineSchema, - ETLRunStatusSchema: () => ETLRunStatusSchema, - ETLSourceSchema: () => ETLSourceSchema, - ETLSyncModeSchema: () => ETLSyncModeSchema, - ETLTransformationSchema: () => ETLTransformationSchema, - ETLTransformationTypeSchema: () => ETLTransformationTypeSchema, - EmailAlertActionSchema: () => EmailAlertActionSchema2, - EventSchema: () => EventSchema2, - ExecutionErrorSchema: () => ExecutionErrorSchema, - ExecutionErrorSeverity: () => ExecutionErrorSeverity2, - ExecutionLogSchema: () => ExecutionLogSchema2, - ExecutionStatus: () => ExecutionStatus2, - ExecutionStepLogSchema: () => ExecutionStepLogSchema2, - FieldUpdateActionSchema: () => FieldUpdateActionSchema2, - FlowEdgeSchema: () => FlowEdgeSchema2, - FlowNodeAction: () => FlowNodeAction2, - FlowNodeSchema: () => FlowNodeSchema2, - FlowSchema: () => FlowSchema2, - FlowVariableSchema: () => FlowVariableSchema2, - FlowVersionHistorySchema: () => FlowVersionHistorySchema, - GuardRefSchema: () => GuardRefSchema4, - HttpCallActionSchema: () => HttpCallActionSchema2, - NodeExecutorDescriptorSchema: () => NodeExecutorDescriptorSchema, - OAuth2ConfigSchema: () => OAuth2ConfigSchema, - OperationParameterSchema: () => OperationParameterSchema, - OperationTypeSchema: () => OperationTypeSchema, - PushNotificationActionSchema: () => PushNotificationActionSchema2, - ScheduleStateSchema: () => ScheduleStateSchema, - StateMachineSchema: () => StateMachineSchema4, - StateNodeSchema: () => StateNodeSchema4, - Sync: () => Sync, - SyncDirectionSchema: () => SyncDirectionSchema, - SyncExecutionResultSchema: () => SyncExecutionResultSchema, - SyncExecutionStatusSchema: () => SyncExecutionStatusSchema, - SyncModeSchema: () => SyncModeSchema, - TaskCreationActionSchema: () => TaskCreationActionSchema2, - TimeTriggerSchema: () => TimeTriggerSchema2, - TransitionSchema: () => TransitionSchema4, - WAIT_EXECUTOR_DESCRIPTOR: () => WAIT_EXECUTOR_DESCRIPTOR, - WaitEventTypeSchema: () => WaitEventTypeSchema, - WaitExecutorConfigSchema: () => WaitExecutorConfigSchema, - WaitResumePayloadSchema: () => WaitResumePayloadSchema, - WaitTimeoutBehaviorSchema: () => WaitTimeoutBehaviorSchema, - WebhookReceiverSchema: () => WebhookReceiverSchema, - WebhookSchema: () => WebhookSchema, - WebhookTriggerType: () => WebhookTriggerType, - WorkflowActionSchema: () => WorkflowActionSchema2, - WorkflowRuleSchema: () => WorkflowRuleSchema2, - WorkflowTriggerType: () => WorkflowTriggerType2, - defineFlow: () => defineFlow -}); -var WebhookTriggerType = external_exports.enum([ - "create", - "update", - "delete", - "undelete", - "api" - // Manually triggered -]); -var WebhookSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema7.describe("Webhook unique name (lowercase snake_case)"), - label: external_exports.string().optional().describe("Human-readable webhook label"), - /** Scope */ - object: external_exports.string().optional().describe("Object to listen to (optional for manual webhooks)"), - triggers: external_exports.array(WebhookTriggerType).optional().describe("Events that trigger execution"), - /** Target */ - url: external_exports.string().url().describe("External webhook endpoint URL"), - method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).default("POST").describe("HTTP method"), - /** Headers */ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers"), - /** Body/Payload */ - body: external_exports.unknown().optional().describe("Request body payload (if not using default record data)"), - /** Payload Configuration */ - payloadFields: external_exports.array(external_exports.string()).optional().describe("Fields to include. Empty = All"), - includeSession: external_exports.boolean().default(false).describe("Include user session info"), - /** Authentication */ - authentication: external_exports.object({ - type: external_exports.enum(["none", "bearer", "basic", "api-key"]).describe("Authentication type"), - credentials: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Authentication credentials") - }).optional().describe("Authentication configuration"), - /** Retry Policy */ - retryPolicy: external_exports.object({ - maxRetries: external_exports.number().int().min(0).max(10).default(3).describe("Maximum retry attempts"), - backoffStrategy: external_exports.enum(["exponential", "linear", "fixed"]).default("exponential").describe("Backoff strategy"), - initialDelayMs: external_exports.number().int().min(100).default(1e3).describe("Initial retry delay in milliseconds"), - maxDelayMs: external_exports.number().int().min(1e3).default(6e4).describe("Maximum retry delay in milliseconds") - }).optional().describe("Retry policy configuration"), - /** Timeout */ - timeoutMs: external_exports.number().int().min(1e3).max(3e5).default(3e4).describe("Request timeout in milliseconds"), - /** Security */ - secret: external_exports.string().optional().describe("Signing secret for HMAC signature verification"), - /** Status */ - isActive: external_exports.boolean().default(true).describe("Whether webhook is active"), - /** Metadata */ - description: external_exports.string().optional().describe("Webhook description"), - tags: external_exports.array(external_exports.string()).optional().describe("Tags for organization") -}); -var WebhookReceiverSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema7.describe("Webhook receiver unique name (lowercase snake_case)"), - path: external_exports.string().describe("URL Path (e.g. /webhooks/stripe)"), - /** Verification */ - verificationType: external_exports.enum(["none", "header_token", "hmac", "ip_whitelist"]).default("none"), - verificationParams: external_exports.object({ - header: external_exports.string().optional(), - secret: external_exports.string().optional(), - ips: external_exports.array(external_exports.string()).optional() - }).optional(), - /** Action */ - action: external_exports.enum(["trigger_flow", "script", "upsert_record"]).default("trigger_flow"), - target: external_exports.string().describe("Flow ID or Script name") -}); -var ApproverType = external_exports.enum([ - "user", - // Specific user(s) - "role", - // Users with specific role - "manager", - // Submitter's manager - "field", - // User ID defined in a record field - "queue" - // Data ownership queue -]); -var ApprovalActionType = external_exports.enum([ - "field_update", - "email_alert", - "webhook", - "script", - "connector_action" - // Added for Zapier-style integrations -]); -var ApprovalActionSchema = external_exports.object({ - type: ApprovalActionType, - name: external_exports.string().describe("Action name"), - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Action configuration"), - /** For connector actions */ - connectorId: external_exports.string().optional(), - actionId: external_exports.string().optional() -}); -var ApprovalStepSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema7.describe("Step machine name"), - label: external_exports.string().describe("Step display label"), - description: external_exports.string().optional(), - /** Entry criteria for this step */ - entryCriteria: external_exports.string().optional().describe("Formula expression to enter this step"), - /** Who can approve */ - approvers: external_exports.array(external_exports.object({ - type: ApproverType, - value: external_exports.string().describe("User ID, Role Name, or Field Name") - })).min(1).describe("List of allowed approvers"), - /** Approval Logic */ - behavior: external_exports.enum(["first_response", "unanimous"]).default("first_response").describe("How to handle multiple approvers"), - /** Rejection behavior */ - rejectionBehavior: external_exports.enum(["reject_process", "back_to_previous"]).default("reject_process").describe("What happens if rejected"), - /** Actions */ - onApprove: external_exports.array(ApprovalActionSchema).optional().describe("Actions on step approval"), - onReject: external_exports.array(ApprovalActionSchema).optional().describe("Actions on step rejection") -}); -var ApprovalProcessSchema = external_exports.object({ - name: SnakeCaseIdentifierSchema7.describe("Unique process name"), - label: external_exports.string().describe("Human readable label"), - object: external_exports.string().describe("Target Object Name"), - active: external_exports.boolean().default(false), - description: external_exports.string().optional(), - /** Entry Criteria for the entire process */ - entryCriteria: external_exports.string().optional().describe("Formula to allow submission"), - /** Record Locking */ - lockRecord: external_exports.boolean().default(true).describe("Lock record from editing during approval"), - /** Steps */ - steps: external_exports.array(ApprovalStepSchema).min(1).describe("Sequence of approval steps"), - /** Escalation Configuration (SLA-based auto-escalation) */ - escalation: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable SLA-based escalation"), - timeoutHours: external_exports.number().min(1).describe("Hours before escalation triggers"), - action: external_exports.enum(["reassign", "auto_approve", "auto_reject", "notify"]).default("notify").describe("Action to take on escalation timeout"), - escalateTo: external_exports.string().optional().describe("User ID, role, or manager level to escalate to"), - notifySubmitter: external_exports.boolean().default(true).describe("Notify the original submitter on escalation") - }).optional().describe("SLA escalation configuration for pending approval steps"), - /** Global Actions */ - onSubmit: external_exports.array(ApprovalActionSchema).optional().describe("Actions on initial submission"), - onFinalApprove: external_exports.array(ApprovalActionSchema).optional().describe("Actions on final approval"), - onFinalReject: external_exports.array(ApprovalActionSchema).optional().describe("Actions on final rejection"), - onRecall: external_exports.array(ApprovalActionSchema).optional().describe("Actions on recall") -}); -var ApprovalProcess = Object.assign(ApprovalProcessSchema, { - create: (config4) => config4 -}); -var ETLEndpointTypeSchema = external_exports.enum([ - "database", - // SQL/NoSQL databases - "api", - // REST/GraphQL APIs - "file", - // CSV, JSON, XML, Excel files - "stream", - // Kafka, RabbitMQ, Kinesis - "object", - // ObjectStack object - "warehouse", - // Data warehouse (Snowflake, BigQuery, Redshift) - "storage", - // S3, Azure Blob, Google Cloud Storage - "spreadsheet" - // Google Sheets, Excel Online -]); -var ETLSourceSchema = external_exports.object({ - /** - * Source type - */ - type: ETLEndpointTypeSchema.describe("Source type"), - /** - * Connector identifier - * References a registered connector - * - * @example "salesforce", "postgres", "mysql", "s3" - */ - connector: external_exports.string().optional().describe("Connector ID"), - /** - * Source-specific configuration - * Structure varies by source type - * - * @example For database: { table: 'customers', schema: 'public' } - * @example For API: { endpoint: '/api/users', method: 'GET' } - * @example For file: { path: 's3://bucket/data.csv', format: 'csv' } - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Source configuration"), - /** - * Incremental sync configuration - * Allows extracting only changed data - */ - incremental: external_exports.object({ - enabled: external_exports.boolean().default(false), - cursorField: external_exports.string().describe("Field to track progress (e.g., updated_at)"), - cursorValue: external_exports.unknown().optional().describe("Last processed value") - }).optional().describe("Incremental extraction config") -}); -var ETLDestinationSchema = external_exports.object({ - /** - * Destination type - */ - type: ETLEndpointTypeSchema.describe("Destination type"), - /** - * Connector identifier - */ - connector: external_exports.string().optional().describe("Connector ID"), - /** - * Destination-specific configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Destination configuration"), - /** - * Write mode - */ - writeMode: external_exports.enum([ - "append", - // Add new records - "overwrite", - // Replace all data - "upsert", - // Insert or update based on key - "merge" - // Smart merge based on business rules - ]).default("append").describe("How to write data"), - /** - * Primary key fields for upsert/merge - */ - primaryKey: external_exports.array(external_exports.string()).optional().describe("Primary key fields") -}); -var ETLTransformationTypeSchema = external_exports.enum([ - "map", - // Field mapping/renaming - "filter", - // Row filtering - "aggregate", - // Aggregation/grouping - "join", - // Joining with other data - "script", - // Custom JavaScript/Python script - "lookup", - // Enrich with lookup data - "split", - // Split one record into multiple - "merge", - // Merge multiple records into one - "normalize", - // Data normalization - "deduplicate" - // Remove duplicates -]); -var ETLTransformationSchema = external_exports.object({ - /** - * Transformation name - */ - name: external_exports.string().optional().describe("Transformation name"), - /** - * Transformation type - */ - type: ETLTransformationTypeSchema.describe("Transformation type"), - /** - * Transformation-specific configuration - * - * @example For map: { oldField: 'newField' } - * @example For filter: { condition: 'status == "active"' } - * @example For script: { language: 'javascript', code: '...' } - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Transformation config"), - /** - * Whether to continue on error - */ - continueOnError: external_exports.boolean().default(false).describe("Continue on error") -}); -var ETLSyncModeSchema = external_exports.enum([ - "full", - // Full refresh - extract all data every time - "incremental", - // Only extract changed data - "cdc" - // Change Data Capture - real-time streaming -]); -var ETLPipelineSchema = external_exports.object({ - /** - * Pipeline identifier (snake_case) - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Pipeline identifier (snake_case)"), - /** - * Human-readable pipeline name - */ - label: external_exports.string().optional().describe("Pipeline display name"), - /** - * Pipeline description - */ - description: external_exports.string().optional().describe("Pipeline description"), - /** - * Data source configuration - */ - source: ETLSourceSchema.describe("Data source"), - /** - * Data destination configuration - */ - destination: ETLDestinationSchema.describe("Data destination"), - /** - * Transformation steps - * Applied in order from source to destination - */ - transformations: external_exports.array(ETLTransformationSchema).optional().describe("Transformation pipeline"), - /** - * Sync mode - */ - syncMode: ETLSyncModeSchema.default("full").describe("Sync mode"), - /** - * Execution schedule (cron expression) - * - * @example "0 2 * * *" - Daily at 2 AM - * @example "0 *\/4 * * *" - Every 4 hours - * @example "0 0 * * 0" - Weekly on Sunday - */ - schedule: external_exports.string().optional().describe("Cron schedule expression"), - /** - * Whether pipeline is enabled - */ - enabled: external_exports.boolean().default(true).describe("Pipeline enabled status"), - /** - * Retry configuration for failed runs - */ - retry: external_exports.object({ - maxAttempts: external_exports.number().int().min(0).default(3).describe("Max retry attempts"), - backoffMs: external_exports.number().int().min(0).default(6e4).describe("Backoff in milliseconds") - }).optional().describe("Retry configuration"), - /** - * Notification configuration - */ - notifications: external_exports.object({ - onSuccess: external_exports.array(external_exports.string()).optional().describe("Email addresses for success notifications"), - onFailure: external_exports.array(external_exports.string()).optional().describe("Email addresses for failure notifications") - }).optional().describe("Notification settings"), - /** - * Pipeline tags for organization - */ - tags: external_exports.array(external_exports.string()).optional().describe("Pipeline tags"), - /** - * Custom metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") -}); -var ETLRunStatusSchema = external_exports.enum([ - "pending", - // Queued for execution - "running", - // Currently executing - "succeeded", - // Completed successfully - "failed", - // Failed with errors - "cancelled", - // Manually cancelled - "timeout" - // Timed out -]); -var ETLPipelineRunSchema = external_exports.object({ - /** - * Run ID - */ - id: external_exports.string().describe("Run identifier"), - /** - * Pipeline name - */ - pipelineName: external_exports.string().describe("Pipeline name"), - /** - * Run status - */ - status: ETLRunStatusSchema.describe("Run status"), - /** - * Start timestamp - */ - startedAt: external_exports.string().datetime().describe("Start time"), - /** - * End timestamp - */ - completedAt: external_exports.string().datetime().optional().describe("Completion time"), - /** - * Duration in milliseconds - */ - durationMs: external_exports.number().optional().describe("Duration in ms"), - /** - * Statistics - */ - stats: external_exports.object({ - recordsRead: external_exports.number().int().default(0).describe("Records extracted"), - recordsWritten: external_exports.number().int().default(0).describe("Records loaded"), - recordsErrored: external_exports.number().int().default(0).describe("Records with errors"), - bytesProcessed: external_exports.number().int().default(0).describe("Bytes processed") - }).optional().describe("Run statistics"), - /** - * Error information - */ - error: external_exports.object({ - message: external_exports.string().describe("Error message"), - code: external_exports.string().optional().describe("Error code"), - details: external_exports.unknown().optional().describe("Error details") - }).optional().describe("Error information"), - /** - * Execution logs - */ - logs: external_exports.array(external_exports.string()).optional().describe("Execution logs") -}); -var ETL = { - /** - * Create a simple database-to-database pipeline - */ - databaseSync: (params) => ({ - name: params.name, - source: { - type: "database", - config: { table: params.sourceTable } - }, - destination: { - type: "database", - config: { table: params.destTable }, - writeMode: "upsert" - }, - syncMode: "incremental", - schedule: params.schedule, - enabled: true - }), - /** - * Create an API to database pipeline - */ - apiToDatabase: (params) => ({ - name: params.name, - source: { - type: "api", - connector: params.apiConnector, - config: {} - }, - destination: { - type: "database", - config: { table: params.destTable }, - writeMode: "append" - }, - syncMode: "full", - schedule: params.schedule, - enabled: true - }) -}; -var ConnectorCategorySchema = external_exports.enum([ - "crm", - // Customer Relationship Management - "payment", - // Payment processors - "communication", - // Email, SMS, Chat - "storage", - // File storage - "analytics", - // Analytics platforms - "database", - // Databases - "marketing", - // Marketing automation - "accounting", - // Accounting software - "hr", - // Human resources - "productivity", - // Productivity tools - "ecommerce", - // E-commerce platforms - "support", - // Customer support - "devtools", - // Developer tools - "social", - // Social media - "other" - // Other category -]); -var AuthenticationTypeSchema = external_exports.enum([ - "none", - // No authentication - "apiKey", - // API key - "basic", - // Basic auth (username/password) - "bearer", - // Bearer token - "oauth1", - // OAuth 1.0 - "oauth2", - // OAuth 2.0 - "custom" - // Custom authentication -]); -var AuthFieldSchema = external_exports.object({ - /** - * Field name (machine name) - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Field name (snake_case)"), - /** - * Field label - */ - label: external_exports.string().describe("Field label"), - /** - * Field type - */ - type: external_exports.enum(["text", "password", "url", "select"]).default("text").describe("Field type"), - /** - * Field description - */ - description: external_exports.string().optional().describe("Field description"), - /** - * Whether field is required - */ - required: external_exports.boolean().default(true).describe("Required field"), - /** - * Default value - */ - default: external_exports.string().optional().describe("Default value"), - /** - * Options for select fields - */ - options: external_exports.array(external_exports.object({ - label: external_exports.string(), - value: external_exports.string() - })).optional().describe("Select field options"), - /** - * Placeholder text - */ - placeholder: external_exports.string().optional().describe("Placeholder text") -}); -var OAuth2ConfigSchema = external_exports.object({ - /** - * Authorization URL - */ - authorizationUrl: external_exports.string().url().describe("Authorization endpoint URL"), - /** - * Token URL - */ - tokenUrl: external_exports.string().url().describe("Token endpoint URL"), - /** - * Scopes to request - */ - scopes: external_exports.array(external_exports.string()).optional().describe("OAuth scopes"), - /** - * Client ID field name - */ - clientIdField: external_exports.string().default("client_id").describe("Client ID field name"), - /** - * Client secret field name - */ - clientSecretField: external_exports.string().default("client_secret").describe("Client secret field name") -}); -var AuthenticationSchema = external_exports.object({ - /** - * Authentication type - */ - type: AuthenticationTypeSchema.describe("Authentication type"), - /** - * Authentication fields - * Configuration fields needed for this auth type - */ - fields: external_exports.array(AuthFieldSchema).optional().describe("Authentication fields"), - /** - * OAuth 2.0 configuration (when type is oauth2) - */ - oauth2: OAuth2ConfigSchema.optional().describe("OAuth 2.0 configuration"), - /** - * Test authentication instructions - */ - test: external_exports.object({ - url: external_exports.string().optional().describe("Test endpoint URL"), - method: external_exports.enum(["GET", "POST", "PUT", "DELETE"]).default("GET").describe("HTTP method") - }).optional().describe("Authentication test configuration") -}); -var OperationTypeSchema = external_exports.enum([ - "read", - // Read/query data - "write", - // Create/update data - "delete", - // Delete data - "search", - // Search operation - "trigger", - // Webhook/polling trigger - "action" - // Custom action -]); -var OperationParameterSchema = external_exports.object({ - /** - * Parameter name - */ - name: external_exports.string().describe("Parameter name"), - /** - * Parameter label - */ - label: external_exports.string().describe("Parameter label"), - /** - * Parameter description - */ - description: external_exports.string().optional().describe("Parameter description"), - /** - * Parameter type - */ - type: external_exports.enum(["string", "number", "boolean", "array", "object", "date", "file"]).describe("Parameter type"), - /** - * Whether parameter is required - */ - required: external_exports.boolean().default(false).describe("Required parameter"), - /** - * Default value - */ - default: external_exports.unknown().optional().describe("Default value"), - /** - * Validation schema - */ - validation: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Validation rules"), - /** - * Dynamic options function - */ - dynamicOptions: external_exports.string().optional().describe("Function to load dynamic options") -}); -var ConnectorOperationSchema = external_exports.object({ - /** - * Operation identifier - */ - id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Operation ID (snake_case)"), - /** - * Operation name - */ - name: external_exports.string().describe("Operation name"), - /** - * Operation description - */ - description: external_exports.string().optional().describe("Operation description"), - /** - * Operation type - */ - type: OperationTypeSchema.describe("Operation type"), - /** - * Input parameters - */ - inputSchema: external_exports.array(OperationParameterSchema).optional().describe("Input parameters"), - /** - * Output schema - */ - outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Output schema"), - /** - * Sample output for documentation - */ - sampleOutput: external_exports.unknown().optional().describe("Sample output"), - /** - * Whether operation supports pagination - */ - supportsPagination: external_exports.boolean().default(false).describe("Supports pagination"), - /** - * Whether operation supports filtering - */ - supportsFiltering: external_exports.boolean().default(false).describe("Supports filtering") -}); -var ConnectorTriggerSchema = external_exports.object({ - /** - * Trigger identifier - */ - id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Trigger ID (snake_case)"), - /** - * Trigger name - */ - name: external_exports.string().describe("Trigger name"), - /** - * Trigger description - */ - description: external_exports.string().optional().describe("Trigger description"), - /** - * Trigger type - */ - type: external_exports.enum(["webhook", "polling", "stream"]).describe("Trigger mechanism"), - /** - * Trigger configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Trigger configuration"), - /** - * Output schema - */ - outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Event payload schema"), - /** - * Polling interval (for polling triggers) - * In milliseconds - */ - pollingIntervalMs: external_exports.number().int().min(1e3).optional().describe("Polling interval in ms") -}); -var ConnectorSchema = external_exports.object({ - /** - * Connector identifier - * Must be globally unique - */ - id: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Connector ID (snake_case)"), - /** - * Connector name - */ - name: external_exports.string().describe("Connector name"), - /** - * Connector description - */ - description: external_exports.string().optional().describe("Connector description"), - /** - * Connector version (semver) - */ - version: external_exports.string().optional().describe("Connector version"), - /** - * Connector icon URL or name - */ - icon: external_exports.string().optional().describe("Connector icon"), - /** - * Connector category - */ - category: ConnectorCategorySchema.describe("Connector category"), - /** - * Base URL for API calls - */ - baseUrl: external_exports.string().url().optional().describe("API base URL"), - /** - * Authentication configuration - */ - authentication: AuthenticationSchema.describe("Authentication config"), - /** - * Available operations - */ - operations: external_exports.array(ConnectorOperationSchema).optional().describe("Connector operations"), - /** - * Available triggers - */ - triggers: external_exports.array(ConnectorTriggerSchema).optional().describe("Connector triggers"), - /** - * Rate limiting information - */ - rateLimit: external_exports.object({ - requestsPerSecond: external_exports.number().optional().describe("Max requests per second"), - requestsPerMinute: external_exports.number().optional().describe("Max requests per minute"), - requestsPerHour: external_exports.number().optional().describe("Max requests per hour") - }).optional().describe("Rate limiting"), - /** - * Connector author - */ - author: external_exports.string().optional().describe("Connector author"), - /** - * Documentation URL - */ - documentation: external_exports.string().url().optional().describe("Documentation URL"), - /** - * Homepage URL - */ - homepage: external_exports.string().url().optional().describe("Homepage URL"), - /** - * License - */ - license: external_exports.string().optional().describe("License (SPDX identifier)"), - /** - * Tags for discovery - */ - tags: external_exports.array(external_exports.string()).optional().describe("Connector tags"), - /** - * Whether connector is verified/certified - */ - verified: external_exports.boolean().default(false).describe("Verified connector"), - /** - * Custom metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") -}); -var ConnectorInstanceSchema = external_exports.object({ - /** - * Instance ID - */ - id: external_exports.string().describe("Instance ID"), - /** - * Connector ID this instance uses - */ - connectorId: external_exports.string().describe("Connector ID"), - /** - * Instance name - */ - name: external_exports.string().describe("Instance name"), - /** - * Instance description - */ - description: external_exports.string().optional().describe("Instance description"), - /** - * Authentication credentials (encrypted) - */ - credentials: external_exports.record(external_exports.string(), external_exports.unknown()).describe("Encrypted credentials"), - /** - * Additional configuration - */ - config: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Additional config"), - /** - * Whether instance is active - */ - active: external_exports.boolean().default(true).describe("Instance active status"), - /** - * Created timestamp - */ - createdAt: external_exports.string().datetime().optional().describe("Creation time"), - /** - * Last tested timestamp - */ - lastTestedAt: external_exports.string().datetime().optional().describe("Last test time"), - /** - * Test status - */ - testStatus: external_exports.enum(["unknown", "success", "failed"]).default("unknown").describe("Connection test status") -}); -var Connector = { - /** - * Create a basic API key connector - */ - apiKey: (params) => ({ - id: params.id, - name: params.name, - category: params.category, - baseUrl: params.baseUrl, - authentication: { - type: "apiKey", - fields: [ - { - name: "api_key", - label: "API Key", - type: "password", - required: true - } - ] - }, - verified: false - }), - /** - * Create an OAuth 2.0 connector - */ - oauth2: (params) => ({ - id: params.id, - name: params.name, - category: params.category, - baseUrl: params.baseUrl, - authentication: { - type: "oauth2", - oauth2: { - authorizationUrl: params.authUrl, - tokenUrl: params.tokenUrl, - clientIdField: "client_id", - clientSecretField: "client_secret", - scopes: params.scopes - } - }, - verified: false - }) -}; -var SyncDirectionSchema = external_exports.enum([ - "push", - // ObjectStack -> External (one-way) - "pull", - // External -> ObjectStack (one-way) - "bidirectional" - // Both directions -]); -var SyncModeSchema = external_exports.enum([ - "full", - // Full refresh every time - "incremental", - // Only sync changed records - "realtime" - // Real-time streaming sync -]); -var ConflictResolutionSchema22 = external_exports.enum([ - "source_wins", - // Source system always wins - "destination_wins", - // Destination system always wins - "latest_wins", - // Most recently modified wins - "manual", - // Flag for manual resolution - "merge" - // Smart merge (custom logic) -]); -var DataSourceConfigSchema = external_exports.object({ - /** - * Source object name - * For ObjectStack objects - */ - object: external_exports.string().optional().describe("ObjectStack object name"), - /** - * Filter conditions - * Only sync records matching these filters - */ - filters: external_exports.unknown().optional().describe("Filter conditions"), - /** - * Fields to include - * If not specified, all fields are synced - */ - fields: external_exports.array(external_exports.string()).optional().describe("Fields to sync"), - /** - * External connector instance ID - * For external data sources - */ - connectorInstanceId: external_exports.string().optional().describe("Connector instance ID"), - /** - * External resource identifier - * e.g., Salesforce object name, database table, API endpoint - */ - externalResource: external_exports.string().optional().describe("External resource ID") -}); -var DataDestinationConfigSchema = external_exports.object({ - /** - * Destination object name - * For ObjectStack objects - */ - object: external_exports.string().optional().describe("ObjectStack object name"), - /** - * Connector instance ID - * For external destinations - */ - connectorInstanceId: external_exports.string().optional().describe("Connector instance ID"), - /** - * Operation to perform - */ - operation: external_exports.enum([ - "insert", - // Create new records only - "update", - // Update existing records only - "upsert", - // Insert or update based on key - "delete", - // Delete records - "sync" - // Full synchronization - ]).describe("Sync operation"), - /** - * Field mappings - * Maps source fields to destination fields - */ - mapping: external_exports.union([ - external_exports.record(external_exports.string(), external_exports.string()), - // Simple mapping: { sourceField: 'destField' } - external_exports.array(FieldMappingSchema4) - // Advanced mapping with transformations - ]).optional().describe("Field mappings"), - /** - * External resource identifier - */ - externalResource: external_exports.string().optional().describe("External resource ID"), - /** - * Match key for upsert operations - * Fields to use for matching existing records - */ - matchKey: external_exports.array(external_exports.string()).optional().describe("Match key fields") -}); -var DataSyncConfigSchema = external_exports.object({ - /** - * Sync configuration name (snake_case) - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Sync configuration name (snake_case)"), - /** - * Human-readable label - */ - label: external_exports.string().optional().describe("Sync display name"), - /** - * Description - */ - description: external_exports.string().optional().describe("Sync description"), - /** - * Source configuration - */ - source: DataSourceConfigSchema.describe("Data source"), - /** - * Destination configuration - */ - destination: DataDestinationConfigSchema.describe("Data destination"), - /** - * Sync direction - */ - direction: SyncDirectionSchema.default("push").describe("Sync direction"), - /** - * Sync mode - */ - syncMode: SyncModeSchema.default("incremental").describe("Sync mode"), - /** - * Conflict resolution strategy - */ - conflictResolution: ConflictResolutionSchema22.default("latest_wins").describe("Conflict resolution"), - /** - * Execution schedule (cron expression) - * For scheduled syncs - * - * @example "0 * * * *" - Hourly - * @example "*\/15 * * * *" - Every 15 minutes - */ - schedule: external_exports.string().optional().describe("Cron schedule"), - /** - * Whether sync is enabled - */ - enabled: external_exports.boolean().default(true).describe("Sync enabled"), - /** - * Change tracking field - * Field to track when records were last modified - * Used for incremental sync - * - * @example "updated_at", "modified_date" - */ - changeTrackingField: external_exports.string().optional().describe("Field for change tracking"), - /** - * Batch size - * Number of records to process per batch - */ - batchSize: external_exports.number().int().min(1).max(1e4).default(100).describe("Batch size for processing"), - /** - * Retry configuration - */ - retry: external_exports.object({ - maxAttempts: external_exports.number().int().min(0).default(3).describe("Max retries"), - backoffMs: external_exports.number().int().min(0).default(3e4).describe("Backoff duration") - }).optional().describe("Retry configuration"), - /** - * Pre-sync validation rules - */ - validation: external_exports.object({ - required: external_exports.array(external_exports.string()).optional().describe("Required fields"), - unique: external_exports.array(external_exports.string()).optional().describe("Unique constraint fields"), - custom: external_exports.array(external_exports.object({ - name: external_exports.string(), - condition: external_exports.string().describe("Validation condition"), - message: external_exports.string().describe("Error message") - })).optional().describe("Custom validation rules") - }).optional().describe("Validation rules"), - /** - * Error handling configuration - */ - errorHandling: external_exports.object({ - onValidationError: external_exports.enum(["skip", "fail", "log"]).default("skip"), - onSyncError: external_exports.enum(["skip", "fail", "retry"]).default("retry"), - notifyOnError: external_exports.array(external_exports.string()).optional().describe("Email notifications") - }).optional().describe("Error handling"), - /** - * Performance optimization - */ - optimization: external_exports.object({ - parallelBatches: external_exports.boolean().default(false).describe("Process batches in parallel"), - cacheEnabled: external_exports.boolean().default(true).describe("Enable caching"), - compressionEnabled: external_exports.boolean().default(false).describe("Enable compression") - }).optional().describe("Performance optimization"), - /** - * Audit and logging - */ - audit: external_exports.object({ - logLevel: external_exports.enum(["none", "error", "warn", "info", "debug"]).default("info"), - retainLogsForDays: external_exports.number().int().min(1).default(30), - trackChanges: external_exports.boolean().default(true).describe("Track all changes") - }).optional().describe("Audit configuration"), - /** - * Tags for organization - */ - tags: external_exports.array(external_exports.string()).optional().describe("Sync tags"), - /** - * Custom metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom metadata") -}); -var SyncExecutionStatusSchema = external_exports.enum([ - "pending", - // Queued - "running", - // Currently executing - "completed", - // Successfully completed - "partial", - // Completed with some errors - "failed", - // Failed - "cancelled" - // Manually cancelled -]); -var SyncExecutionResultSchema = external_exports.object({ - /** - * Execution ID - */ - id: external_exports.string().describe("Execution ID"), - /** - * Sync configuration name - */ - syncName: external_exports.string().describe("Sync name"), - /** - * Execution status - */ - status: SyncExecutionStatusSchema.describe("Execution status"), - /** - * Start timestamp - */ - startedAt: external_exports.string().datetime().describe("Start time"), - /** - * End timestamp - */ - completedAt: external_exports.string().datetime().optional().describe("Completion time"), - /** - * Duration in milliseconds - */ - durationMs: external_exports.number().optional().describe("Duration in ms"), - /** - * Statistics - */ - stats: external_exports.object({ - recordsProcessed: external_exports.number().int().default(0).describe("Total records processed"), - recordsInserted: external_exports.number().int().default(0).describe("Records inserted"), - recordsUpdated: external_exports.number().int().default(0).describe("Records updated"), - recordsDeleted: external_exports.number().int().default(0).describe("Records deleted"), - recordsSkipped: external_exports.number().int().default(0).describe("Records skipped"), - recordsErrored: external_exports.number().int().default(0).describe("Records with errors"), - conflictsDetected: external_exports.number().int().default(0).describe("Conflicts detected"), - conflictsResolved: external_exports.number().int().default(0).describe("Conflicts resolved") - }).optional().describe("Execution statistics"), - /** - * Errors encountered - */ - errors: external_exports.array(external_exports.object({ - recordId: external_exports.string().optional().describe("Record ID"), - field: external_exports.string().optional().describe("Field name"), - message: external_exports.string().describe("Error message"), - code: external_exports.string().optional().describe("Error code") - })).optional().describe("Errors"), - /** - * Execution logs - */ - logs: external_exports.array(external_exports.string()).optional().describe("Execution logs") -}); -var Sync = { - /** - * Create a simple object-to-object sync - */ - objectSync: (params) => ({ - name: params.name, - source: { - object: params.sourceObject - }, - destination: { - object: params.destObject, - operation: "upsert", - mapping: params.mapping - }, - direction: "push", - syncMode: "incremental", - conflictResolution: "latest_wins", - batchSize: 100, - schedule: params.schedule, - enabled: true - }), - /** - * Create a connector sync - */ - connectorSync: (params) => ({ - name: params.name, - source: { - object: params.sourceObject - }, - destination: { - connectorInstanceId: params.connectorInstanceId, - externalResource: params.externalResource, - operation: "upsert", - mapping: params.mapping - }, - direction: "push", - syncMode: "incremental", - conflictResolution: "latest_wins", - batchSize: 100, - schedule: params.schedule, - enabled: true - }), - /** - * Create a bidirectional sync - */ - bidirectionalSync: (params) => ({ - name: params.name, - source: { - object: params.object - }, - destination: { - connectorInstanceId: params.connectorInstanceId, - externalResource: params.externalResource, - operation: "sync", - mapping: params.mapping - }, - direction: "bidirectional", - syncMode: "incremental", - conflictResolution: "latest_wins", - batchSize: 100, - schedule: params.schedule, - enabled: true - }) -}; -var WaitEventTypeSchema = external_exports.enum([ - "timer", - // Resume after duration/datetime - "signal", - // Resume on named signal dispatch - "webhook", - // Resume on incoming webhook call - "manual", - // Resume by manual operator action - "condition" - // Resume when a data condition is met (polling) -]).describe("Wait event type determining how a paused flow is resumed"); -var WaitResumePayloadSchema = external_exports.object({ - /** The execution id of the paused flow */ - executionId: external_exports.string().describe("Execution ID of the paused flow"), - /** The checkpoint id being resumed */ - checkpointId: external_exports.string().describe("Checkpoint ID to resume from"), - /** The node id of the wait node being resumed */ - nodeId: external_exports.string().describe("Wait node ID being resumed"), - /** The event type that triggered the resume */ - eventType: WaitEventTypeSchema.describe("Event type that triggered resume"), - /** Signal name (for signal events) */ - signalName: external_exports.string().optional().describe("Signal name (when eventType is signal)"), - /** Webhook payload data (for webhook events) */ - webhookPayload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Webhook request payload (when eventType is webhook)"), - /** Who/what triggered the resume */ - resumedBy: external_exports.string().optional().describe("User ID or system identifier that triggered resume"), - /** Timestamp of the resume event */ - resumedAt: external_exports.string().datetime().describe("ISO 8601 timestamp of the resume event"), - /** Additional variables to merge into flow context on resume */ - variables: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Variables to merge into flow context upon resume") -}).describe("Payload for resuming a paused wait node"); -var WaitTimeoutBehaviorSchema = external_exports.enum([ - "fail", - // Mark execution as failed - "continue", - // Continue to next node (skip wait) - "fallback" - // Execute a fallback edge -]).describe("Behavior when a wait node exceeds its timeout"); -var WaitExecutorConfigSchema = external_exports.object({ - /** Default timeout for wait nodes without explicit timeout (ms) */ - defaultTimeoutMs: external_exports.number().int().min(0).default(864e5).describe("Default timeout in ms (default: 24 hours)"), - /** Default timeout behavior */ - defaultTimeoutBehavior: WaitTimeoutBehaviorSchema.default("fail").describe("Default behavior when wait timeout is exceeded"), - /** Polling interval for condition-based waits (ms) */ - conditionPollIntervalMs: external_exports.number().int().min(1e3).default(3e4).describe("Polling interval for condition waits in ms (default: 30s)"), - /** Maximum polling attempts for condition waits (0 = unlimited until timeout) */ - conditionMaxPolls: external_exports.number().int().min(0).default(0).describe("Max polling attempts for condition waits (0 = unlimited)"), - /** Webhook endpoint URL pattern (runtime fills in execution/node ids) */ - webhookUrlPattern: external_exports.string().default("/api/v1/automation/resume/{executionId}/{nodeId}").describe("URL pattern for webhook resume endpoints"), - /** Whether to persist checkpoints to durable storage */ - persistCheckpoints: external_exports.boolean().default(true).describe("Persist wait checkpoints to durable storage"), - /** Maximum concurrent paused executions (0 = unlimited) */ - maxPausedExecutions: external_exports.number().int().min(0).default(0).describe("Max concurrent paused executions (0 = unlimited)") -}).describe("Wait node executor plugin configuration"); -var NodeExecutorDescriptorSchema = external_exports.object({ - /** Unique executor identifier */ - id: external_exports.string().describe("Unique executor plugin identifier"), - /** Human-readable name */ - name: external_exports.string().describe("Display name"), - /** The FlowNodeAction types this executor handles */ - nodeTypes: external_exports.array(external_exports.string()).min(1).describe("FlowNodeAction types this executor handles"), - /** Executor plugin version (semver) */ - version: external_exports.string().describe("Plugin version (semver)"), - /** Description of the executor */ - description: external_exports.string().optional().describe("Executor description"), - /** Whether this executor supports async pause/resume */ - supportsPause: external_exports.boolean().default(false).describe("Whether the executor supports async pause/resume"), - /** Whether this executor supports cancellation mid-execution */ - supportsCancellation: external_exports.boolean().default(false).describe("Whether the executor supports mid-execution cancellation"), - /** Whether this executor supports retry on failure */ - supportsRetry: external_exports.boolean().default(true).describe("Whether the executor supports retry on failure"), - /** Executor-specific configuration schema (JSON Schema reference) */ - configSchemaRef: external_exports.string().optional().describe("JSON Schema $ref for executor-specific config") -}).describe("Node executor plugin descriptor"); -var WAIT_EXECUTOR_DESCRIPTOR = { - id: "objectstack:wait-executor", - name: "Wait Node Executor", - nodeTypes: ["wait"], - version: "1.0.0", - description: "Pauses flow execution and resumes on timer, signal, webhook, manual action, or condition events.", - supportsPause: true, - supportsCancellation: true, - supportsRetry: true -}; -var BpmnElementMappingSchema = external_exports.object({ - /** BPMN XML element type (e.g., "bpmn:parallelGateway", "bpmn:serviceTask") */ - bpmnType: external_exports.string().describe('BPMN XML element type (e.g., "bpmn:parallelGateway")'), - /** Corresponding ObjectStack FlowNodeAction */ - flowNodeAction: external_exports.string().describe("ObjectStack FlowNodeAction value"), - /** Whether this mapping is bidirectional (supports both import and export) */ - bidirectional: external_exports.boolean().default(true).describe("Whether the mapping supports both import and export"), - /** Notes about mapping limitations or special handling */ - notes: external_exports.string().optional().describe("Notes about mapping limitations") -}).describe("Mapping between BPMN XML element and ObjectStack FlowNodeAction"); -var BpmnUnmappedStrategySchema = external_exports.enum([ - "skip", - // Skip unmapped elements silently - "warn", - // Import with warnings - "error", - // Fail on unmapped elements - "comment" - // Import as annotation/comment nodes -]).describe("Strategy for unmapped BPMN elements during import"); -var BpmnImportOptionsSchema = external_exports.object({ - /** Strategy for unmapped BPMN elements */ - unmappedStrategy: BpmnUnmappedStrategySchema.default("warn").describe("How to handle unmapped BPMN elements"), - /** Custom element mappings (override or extend built-in mappings) */ - customMappings: external_exports.array(BpmnElementMappingSchema).optional().describe("Custom element mappings to override or extend defaults"), - /** Whether to import BPMN DI (diagram interchange) layout positions */ - importLayout: external_exports.boolean().default(true).describe("Import BPMN DI layout positions into canvas node coordinates"), - /** Whether to import BPMN documentation as node descriptions */ - importDocumentation: external_exports.boolean().default(true).describe("Import BPMN documentation elements as node descriptions"), - /** Target flow name (if not derived from BPMN process name) */ - flowName: external_exports.string().optional().describe("Override flow name (defaults to BPMN process name)"), - /** Whether to validate the imported flow against ObjectStack schema */ - validateAfterImport: external_exports.boolean().default(true).describe("Validate imported flow against FlowSchema after import") -}).describe("Options for importing BPMN 2.0 XML into an ObjectStack flow"); -var BpmnVersionSchema = external_exports.enum([ - "2.0", - // BPMN 2.0 (most common, default) - "2.0.2" - // BPMN 2.0.2 (latest revision) -]).describe("BPMN specification version for export"); -var BpmnExportOptionsSchema = external_exports.object({ - /** Target BPMN version */ - version: BpmnVersionSchema.default("2.0").describe("Target BPMN specification version"), - /** Whether to include BPMN DI (diagram interchange) layout data */ - includeLayout: external_exports.boolean().default(true).describe("Include BPMN DI layout data from canvas positions"), - /** Whether to include ObjectStack-specific extensions as BPMN extension elements */ - includeExtensions: external_exports.boolean().default(false).describe("Include ObjectStack extensions in BPMN extensionElements"), - /** Custom element mappings (override built-in for export) */ - customMappings: external_exports.array(BpmnElementMappingSchema).optional().describe("Custom element mappings for export"), - /** Whether to pretty-print the XML output */ - prettyPrint: external_exports.boolean().default(true).describe("Pretty-print XML output with indentation"), - /** XML namespace prefix for BPMN elements */ - namespacePrefix: external_exports.string().default("bpmn").describe("XML namespace prefix for BPMN elements") -}).describe("Options for exporting an ObjectStack flow as BPMN 2.0 XML"); -var BpmnDiagnosticSchema = external_exports.object({ - /** Severity level */ - severity: external_exports.enum(["info", "warning", "error"]).describe("Diagnostic severity"), - /** Human-readable message */ - message: external_exports.string().describe("Diagnostic message"), - /** BPMN element ID (if applicable) */ - bpmnElementId: external_exports.string().optional().describe("BPMN element ID related to this diagnostic"), - /** ObjectStack node ID (if applicable) */ - nodeId: external_exports.string().optional().describe("ObjectStack node ID related to this diagnostic") -}).describe("Diagnostic message from BPMN import/export"); -var BpmnInteropResultSchema = external_exports.object({ - /** Whether the operation completed successfully */ - success: external_exports.boolean().describe("Whether the operation completed successfully"), - /** Diagnostic messages (warnings, errors, info) */ - diagnostics: external_exports.array(BpmnDiagnosticSchema).default([]).describe("Diagnostic messages from the operation"), - /** Number of elements successfully mapped */ - mappedCount: external_exports.number().int().min(0).default(0).describe("Number of elements successfully mapped"), - /** Number of elements skipped or unmapped */ - unmappedCount: external_exports.number().int().min(0).default(0).describe("Number of elements that could not be mapped") -}).describe("Result of a BPMN import/export operation"); -var BUILT_IN_BPMN_MAPPINGS = [ - { bpmnType: "bpmn:startEvent", flowNodeAction: "start", bidirectional: true }, - { bpmnType: "bpmn:endEvent", flowNodeAction: "end", bidirectional: true }, - { bpmnType: "bpmn:exclusiveGateway", flowNodeAction: "decision", bidirectional: true }, - { bpmnType: "bpmn:parallelGateway", flowNodeAction: "parallel_gateway", bidirectional: true }, - { bpmnType: "bpmn:serviceTask", flowNodeAction: "http_request", bidirectional: true, notes: "Maps HTTP/connector tasks" }, - { bpmnType: "bpmn:scriptTask", flowNodeAction: "script", bidirectional: true }, - { bpmnType: "bpmn:userTask", flowNodeAction: "screen", bidirectional: true }, - { bpmnType: "bpmn:callActivity", flowNodeAction: "subflow", bidirectional: true }, - { bpmnType: "bpmn:intermediateCatchEvent", flowNodeAction: "wait", bidirectional: true, notes: "Timer/signal/message catch events" }, - { bpmnType: "bpmn:boundaryEvent", flowNodeAction: "boundary_event", bidirectional: true }, - { bpmnType: "bpmn:task", flowNodeAction: "assignment", bidirectional: true, notes: "Generic BPMN task maps to assignment" } -]; -var integration_exports = {}; -__export4(integration_exports, { - AckModeSchema: () => AckModeSchema, - ApiVersionConfigSchema: () => ApiVersionConfigSchema, - BuildConfigSchema: () => BuildConfigSchema, - CdcConfigSchema: () => CdcConfigSchema, - CircuitBreakerConfigSchema: () => CircuitBreakerConfigSchema, - ConflictResolutionSchema: () => ConflictResolutionSchema3, - ConnectorActionSchema: () => ConnectorActionSchema, - ConnectorHealthSchema: () => ConnectorHealthSchema, - ConnectorSchema: () => ConnectorSchema2, - ConnectorStatusSchema: () => ConnectorStatusSchema, - ConnectorTriggerSchema: () => ConnectorTriggerSchema2, - ConnectorTypeSchema: () => ConnectorTypeSchema, - ConsumerConfigSchema: () => ConsumerConfigSchema22, - DataSyncConfigSchema: () => DataSyncConfigSchema2, - DatabaseConnectorSchema: () => DatabaseConnectorSchema, - DatabasePoolConfigSchema: () => DatabasePoolConfigSchema, - DatabaseProviderSchema: () => DatabaseProviderSchema22, - DatabaseTableSchema: () => DatabaseTableSchema, - DeliveryGuaranteeSchema: () => DeliveryGuaranteeSchema, - DeploymentConfigSchema: () => DeploymentConfigSchema, - DlqConfigSchema: () => DlqConfigSchema, - DomainConfigSchema: () => DomainConfigSchema, - EdgeFunctionConfigSchema: () => EdgeFunctionConfigSchema, - EnvironmentVariablesSchema: () => EnvironmentVariablesSchema, - ErrorCategorySchema: () => ErrorCategorySchema, - ErrorMappingConfigSchema: () => ErrorMappingConfigSchema, - ErrorMappingRuleSchema: () => ErrorMappingRuleSchema, - FieldMappingSchema: () => FieldMappingSchema32, - FileAccessPatternSchema: () => FileAccessPatternSchema, - FileFilterConfigSchema: () => FileFilterConfigSchema, - FileMetadataConfigSchema: () => FileMetadataConfigSchema, - FileStorageConnectorSchema: () => FileStorageConnectorSchema, - FileStorageProviderSchema: () => FileStorageProviderSchema, - FileVersioningConfigSchema: () => FileVersioningConfigSchema, - GitHubActionsWorkflowSchema: () => GitHubActionsWorkflowSchema, - GitHubCommitConfigSchema: () => GitHubCommitConfigSchema, - GitHubConnectorSchema: () => GitHubConnectorSchema, - GitHubIssueTrackingSchema: () => GitHubIssueTrackingSchema, - GitHubProviderSchema: () => GitHubProviderSchema, - GitHubPullRequestConfigSchema: () => GitHubPullRequestConfigSchema, - GitHubReleaseConfigSchema: () => GitHubReleaseConfigSchema, - GitHubRepositorySchema: () => GitHubRepositorySchema, - GitRepositoryConfigSchema: () => GitRepositoryConfigSchema, - HealthCheckConfigSchema: () => HealthCheckConfigSchema, - MessageFormatSchema: () => MessageFormatSchema22, - MessageQueueConnectorSchema: () => MessageQueueConnectorSchema, - MessageQueueProviderSchema: () => MessageQueueProviderSchema22, - MultipartUploadConfigSchema: () => MultipartUploadConfigSchema22, - ProducerConfigSchema: () => ProducerConfigSchema, - RateLimitConfigSchema: () => RateLimitConfigSchema22, - RateLimitStrategySchema: () => RateLimitStrategySchema, - RetryConfigSchema: () => RetryConfigSchema, - RetryStrategySchema: () => RetryStrategySchema, - SaasConnectorSchema: () => SaasConnectorSchema, - SaasObjectTypeSchema: () => SaasObjectTypeSchema, - SaasProviderSchema: () => SaasProviderSchema, - SslConfigSchema: () => SslConfigSchema, - StorageBucketSchema: () => StorageBucketSchema, - SyncStrategySchema: () => SyncStrategySchema, - TopicQueueSchema: () => TopicQueueSchema, - VercelConnectorSchema: () => VercelConnectorSchema, - VercelFrameworkSchema: () => VercelFrameworkSchema, - VercelMonitoringSchema: () => VercelMonitoringSchema, - VercelProjectSchema: () => VercelProjectSchema, - VercelProviderSchema: () => VercelProviderSchema, - VercelTeamSchema: () => VercelTeamSchema, - WebhookConfigSchema: () => WebhookConfigSchema22, - WebhookEventSchema: () => WebhookEventSchema22, - WebhookSignatureAlgorithmSchema: () => WebhookSignatureAlgorithmSchema, - azureBlobConnectorExample: () => azureBlobConnectorExample, - githubEnterpriseConnectorExample: () => githubEnterpriseConnectorExample, - githubPublicConnectorExample: () => githubPublicConnectorExample, - googleDriveConnectorExample: () => googleDriveConnectorExample, - hubspotConnectorExample: () => hubspotConnectorExample, - kafkaConnectorExample: () => kafkaConnectorExample, - mongoConnectorExample: () => mongoConnectorExample, - postgresConnectorExample: () => postgresConnectorExample, - pubsubConnectorExample: () => pubsubConnectorExample, - rabbitmqConnectorExample: () => rabbitmqConnectorExample, - s3ConnectorExample: () => s3ConnectorExample, - salesforceConnectorExample: () => salesforceConnectorExample, - snowflakeConnectorExample: () => snowflakeConnectorExample, - sqsConnectorExample: () => sqsConnectorExample, - vercelNextJsConnectorExample: () => vercelNextJsConnectorExample, - vercelStaticSiteConnectorExample: () => vercelStaticSiteConnectorExample -}); -var ConnectorOAuth2Schema = external_exports.object({ - type: external_exports.literal("oauth2"), - authorizationUrl: external_exports.string().url().describe("OAuth2 authorization endpoint"), - tokenUrl: external_exports.string().url().describe("OAuth2 token endpoint"), - clientId: external_exports.string().describe("OAuth2 client ID"), - clientSecret: external_exports.string().describe("OAuth2 client secret (typically from ENV)"), - scopes: external_exports.array(external_exports.string()).optional().describe("Requested OAuth2 scopes"), - redirectUri: external_exports.string().url().optional().describe("OAuth2 redirect URI"), - refreshToken: external_exports.string().optional().describe("Refresh token for token renewal"), - tokenExpiry: external_exports.number().optional().describe("Token expiry timestamp") -}); -var ConnectorAPIKeySchema = external_exports.object({ - type: external_exports.literal("api-key"), - key: external_exports.string().describe("API key value"), - headerName: external_exports.string().default("X-API-Key").describe("HTTP header name for API key"), - paramName: external_exports.string().optional().describe("Query parameter name (alternative to header)") -}); -var ConnectorBasicAuthSchema = external_exports.object({ - type: external_exports.literal("basic"), - username: external_exports.string().describe("Username"), - password: external_exports.string().describe("Password") -}); -var ConnectorBearerAuthSchema = external_exports.object({ - type: external_exports.literal("bearer"), - token: external_exports.string().describe("Bearer token") -}); -var ConnectorNoAuthSchema = external_exports.object({ - type: external_exports.literal("none") -}); -var ConnectorAuthConfigSchema = external_exports.discriminatedUnion("type", [ - ConnectorOAuth2Schema, - ConnectorAPIKeySchema, - ConnectorBasicAuthSchema, - ConnectorBearerAuthSchema, - ConnectorNoAuthSchema -]); -var FieldMappingSchema32 = FieldMappingSchema4.extend({ - /** - * Data type mapping (connector-specific) - */ - dataType: external_exports.enum([ - "string", - "number", - "boolean", - "date", - "datetime", - "json", - "array" - ]).optional().describe("Target data type"), - /** - * Is this field required? - */ - required: external_exports.boolean().default(false).describe("Field is required"), - /** - * Bidirectional sync mode (connector-specific) - */ - syncMode: external_exports.enum([ - "read_only", - // Only sync from external to ObjectStack - "write_only", - // Only sync from ObjectStack to external - "bidirectional" - // Sync both ways - ]).default("bidirectional").describe("Sync mode") -}); -var SyncStrategySchema = external_exports.enum([ - "full", - // Full refresh (delete all and re-import) - "incremental", - // Only sync changes since last sync - "upsert", - // Insert new, update existing - "append_only" - // Only insert new records -]).describe("Synchronization strategy"); -var ConflictResolutionSchema3 = external_exports.enum([ - "source_wins", - // External system data takes precedence - "target_wins", - // ObjectStack data takes precedence - "latest_wins", - // Most recently modified wins - "manual" - // Flag for manual resolution -]).describe("Conflict resolution strategy"); -var DataSyncConfigSchema2 = external_exports.object({ - /** - * Sync strategy - */ - strategy: SyncStrategySchema.optional().default("incremental"), - /** - * Sync direction - */ - direction: external_exports.enum([ - "import", - // External → ObjectStack - "export", - // ObjectStack → External - "bidirectional" - // Both ways - ]).optional().default("import").describe("Sync direction"), - /** - * Sync frequency (cron expression) - */ - schedule: external_exports.string().optional().describe("Cron expression for scheduled sync"), - /** - * Enable real-time sync via webhooks - */ - realtimeSync: external_exports.boolean().optional().default(false).describe("Enable real-time sync"), - /** - * Field to track last sync timestamp - */ - timestampField: external_exports.string().optional().describe("Field to track last modification time"), - /** - * Conflict resolution strategy - */ - conflictResolution: ConflictResolutionSchema3.optional().default("latest_wins"), - /** - * Batch size for bulk operations - */ - batchSize: external_exports.number().min(1).max(1e4).optional().default(1e3).describe("Records per batch"), - /** - * Delete handling - */ - deleteMode: external_exports.enum([ - "hard_delete", - // Permanently delete - "soft_delete", - // Mark as deleted - "ignore" - // Don't sync deletions - ]).optional().default("soft_delete").describe("Delete handling mode"), - /** - * Filter criteria for selective sync - */ - filters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter criteria for selective sync") -}); -var WebhookEventSchema22 = external_exports.enum([ - "record.created", - "record.updated", - "record.deleted", - "sync.started", - "sync.completed", - "sync.failed", - "auth.expired", - "rate_limit.exceeded" -]).describe("Webhook event type"); -var WebhookSignatureAlgorithmSchema = external_exports.enum([ - "hmac_sha256", - "hmac_sha512", - "none" -]).describe("Webhook signature algorithm"); -var WebhookConfigSchema22 = WebhookSchema.extend({ - /** - * Events to listen for - * Connector-specific events like sync completion, auth expiry, etc. - */ - events: external_exports.array(WebhookEventSchema22).optional().describe("Connector events to subscribe to"), - /** - * Signature algorithm for webhook security - */ - signatureAlgorithm: WebhookSignatureAlgorithmSchema.optional().default("hmac_sha256") -}); -var RateLimitStrategySchema = external_exports.enum([ - "fixed_window", - // Fixed time window - "sliding_window", - // Sliding time window - "token_bucket", - // Token bucket algorithm - "leaky_bucket" - // Leaky bucket algorithm -]).describe("Rate limiting strategy"); -var RateLimitConfigSchema22 = external_exports.object({ - /** - * Rate limiting strategy - */ - strategy: RateLimitStrategySchema.optional().default("token_bucket"), - /** - * Maximum requests per window - */ - maxRequests: external_exports.number().min(1).describe("Maximum requests per window"), - /** - * Time window in seconds - */ - windowSeconds: external_exports.number().min(1).describe("Time window in seconds"), - /** - * Burst capacity (for token bucket) - */ - burstCapacity: external_exports.number().min(1).optional().describe("Burst capacity"), - /** - * Respect external system rate limits - */ - respectUpstreamLimits: external_exports.boolean().optional().default(true).describe("Respect external rate limit headers"), - /** - * Custom rate limit headers to check - */ - rateLimitHeaders: external_exports.object({ - remaining: external_exports.string().optional().default("X-RateLimit-Remaining").describe("Header for remaining requests"), - limit: external_exports.string().optional().default("X-RateLimit-Limit").describe("Header for rate limit"), - reset: external_exports.string().optional().default("X-RateLimit-Reset").describe("Header for reset time") - }).optional().describe("Custom rate limit headers") -}); -var RetryStrategySchema = external_exports.enum([ - "exponential_backoff", - "linear_backoff", - "fixed_delay", - "no_retry" -]).describe("Retry strategy"); -var RetryConfigSchema = external_exports.object({ - /** - * Retry strategy - */ - strategy: RetryStrategySchema.optional().default("exponential_backoff"), - /** - * Maximum retry attempts - */ - maxAttempts: external_exports.number().min(0).max(10).optional().default(3).describe("Maximum retry attempts"), - /** - * Initial delay in milliseconds - */ - initialDelayMs: external_exports.number().min(100).optional().default(1e3).describe("Initial retry delay in ms"), - /** - * Maximum delay in milliseconds - */ - maxDelayMs: external_exports.number().min(1e3).optional().default(6e4).describe("Maximum retry delay in ms"), - /** - * Backoff multiplier (for exponential backoff) - */ - backoffMultiplier: external_exports.number().min(1).optional().default(2).describe("Exponential backoff multiplier"), - /** - * HTTP status codes to retry - */ - retryableStatusCodes: external_exports.array(external_exports.number()).optional().default([408, 429, 500, 502, 503, 504]).describe("HTTP status codes to retry"), - /** - * Retry on network errors - */ - retryOnNetworkError: external_exports.boolean().optional().default(true).describe("Retry on network errors"), - /** - * Jitter to add randomness to retry delays - */ - jitter: external_exports.boolean().optional().default(true).describe("Add jitter to retry delays") -}); -var ErrorCategorySchema = external_exports.enum([ - "validation", - "authorization", - "not_found", - "conflict", - "rate_limit", - "timeout", - "server_error", - "integration_error" -]).describe("Standard error category"); -var ErrorMappingRuleSchema = external_exports.object({ - sourceCode: external_exports.union([external_exports.string(), external_exports.number()]).describe("External system error code"), - sourceMessage: external_exports.string().optional().describe("Pattern to match against error message"), - targetCode: external_exports.string().describe("ObjectStack standard error code"), - targetCategory: ErrorCategorySchema.describe("Error category"), - severity: external_exports.enum(["low", "medium", "high", "critical"]).describe("Error severity level"), - retryable: external_exports.boolean().describe("Whether the error is retryable"), - userMessage: external_exports.string().optional().describe("Human-readable message to show users") -}).describe("Error mapping rule"); -var ErrorMappingConfigSchema = external_exports.object({ - rules: external_exports.array(ErrorMappingRuleSchema).describe("Error mapping rules"), - defaultCategory: ErrorCategorySchema.optional().default("integration_error").describe("Default category for unmapped errors"), - unmappedBehavior: external_exports.enum(["passthrough", "generic_error", "throw"]).describe("What to do with unmapped errors"), - logUnmapped: external_exports.boolean().optional().default(true).describe("Log unmapped errors") -}).describe("Error mapping configuration"); -var HealthCheckConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable health checks"), - intervalMs: external_exports.number().optional().default(6e4).describe("Health check interval in milliseconds"), - timeoutMs: external_exports.number().optional().default(5e3).describe("Health check timeout in milliseconds"), - endpoint: external_exports.string().optional().describe("Health check endpoint path"), - method: external_exports.enum(["GET", "HEAD", "OPTIONS"]).optional().describe("HTTP method for health check"), - expectedStatus: external_exports.number().optional().default(200).describe("Expected HTTP status code"), - unhealthyThreshold: external_exports.number().optional().default(3).describe("Consecutive failures before marking unhealthy"), - healthyThreshold: external_exports.number().optional().default(1).describe("Consecutive successes before marking healthy") -}).describe("Health check configuration"); -var CircuitBreakerConfigSchema = external_exports.object({ - enabled: external_exports.boolean().describe("Enable circuit breaker"), - failureThreshold: external_exports.number().optional().default(5).describe("Failures before opening circuit"), - resetTimeoutMs: external_exports.number().optional().default(3e4).describe("Time in open state before half-open"), - halfOpenMaxRequests: external_exports.number().optional().default(1).describe("Requests allowed in half-open state"), - monitoringWindow: external_exports.number().optional().default(6e4).describe("Rolling window for failure count in ms"), - fallbackStrategy: external_exports.enum(["cache", "default_value", "error", "queue"]).optional().describe("Fallback strategy when circuit is open") -}).describe("Circuit breaker configuration"); -var ConnectorHealthSchema = external_exports.object({ - healthCheck: HealthCheckConfigSchema.optional().describe("Health check configuration"), - circuitBreaker: CircuitBreakerConfigSchema.optional().describe("Circuit breaker configuration") -}).describe("Connector health configuration"); -var ConnectorTypeSchema = external_exports.enum([ - "saas", - // SaaS application connector - "database", - // Database connector - "file_storage", - // File storage connector - "message_queue", - // Message queue connector - "api", - // Generic REST/GraphQL API - "custom" - // Custom connector -]).describe("Connector type"); -var ConnectorStatusSchema = external_exports.enum([ - "active", - // Connector is active and syncing - "inactive", - // Connector is configured but disabled - "error", - // Connector has errors - "configuring" - // Connector is being set up -]).describe("Connector status"); -var ConnectorActionSchema = external_exports.object({ - key: external_exports.string().describe("Action key (machine name)"), - label: external_exports.string().describe("Human readable label"), - description: external_exports.string().optional(), - inputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Input parameters schema (JSON Schema)"), - outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Output schema (JSON Schema)") -}); -var ConnectorTriggerSchema2 = external_exports.object({ - key: external_exports.string().describe("Trigger key"), - label: external_exports.string().describe("Trigger label"), - description: external_exports.string().optional(), - type: external_exports.enum(["polling", "webhook"]).describe("Trigger type"), - interval: external_exports.number().optional().describe("Polling interval in seconds") -}); -var ConnectorSchema2 = external_exports.object({ - /** - * Machine name (snake_case) - */ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique connector identifier"), - /** - * Human-readable label - */ - label: external_exports.string().describe("Display label"), - /** - * Connector type - */ - type: ConnectorTypeSchema.describe("Connector type"), - /** - * Description - */ - description: external_exports.string().optional().describe("Connector description"), - /** - * Icon identifier - */ - icon: external_exports.string().optional().describe("Icon identifier"), - /** - * Authentication configuration - */ - authentication: ConnectorAuthConfigSchema.describe("Authentication configuration"), - /** Zapier-style Capabilities */ - actions: external_exports.array(ConnectorActionSchema).optional(), - triggers: external_exports.array(ConnectorTriggerSchema2).optional(), - /** - * Data synchronization configuration - */ - syncConfig: DataSyncConfigSchema2.optional().describe("Data sync configuration"), - /** - * Field mappings - */ - fieldMappings: external_exports.array(FieldMappingSchema32).optional().describe("Field mapping rules"), - /** - * Webhook configuration - */ - webhooks: external_exports.array(WebhookConfigSchema22).optional().describe("Webhook configurations"), - /** - * Rate limiting configuration - */ - rateLimitConfig: RateLimitConfigSchema22.optional().describe("Rate limiting configuration"), - /** - * Retry configuration - */ - retryConfig: RetryConfigSchema.optional().describe("Retry configuration"), - /** - * Connection timeout in milliseconds - */ - connectionTimeoutMs: external_exports.number().min(1e3).max(3e5).optional().default(3e4).describe("Connection timeout in ms"), - /** - * Request timeout in milliseconds - */ - requestTimeoutMs: external_exports.number().min(1e3).max(3e5).optional().default(3e4).describe("Request timeout in ms"), - /** - * Connector status - */ - status: ConnectorStatusSchema.optional().default("inactive").describe("Connector status"), - /** - * Enable connector - */ - enabled: external_exports.boolean().optional().default(true).describe("Enable connector"), - /** - * Error mapping configuration - */ - errorMapping: ErrorMappingConfigSchema.optional().describe("Error mapping configuration"), - /** - * Health check and circuit breaker configuration - */ - health: ConnectorHealthSchema.optional().describe("Health and resilience configuration"), - /** - * Custom metadata - */ - metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Custom connector metadata") -}); -var SaasProviderSchema = external_exports.enum([ - "salesforce", - "hubspot", - "stripe", - "shopify", - "zendesk", - "intercom", - "mailchimp", - "slack", - "microsoft_dynamics", - "servicenow", - "netsuite", - "custom" -]).describe("SaaS provider type"); -var ApiVersionConfigSchema = external_exports.object({ - version: external_exports.string().describe('API version (e.g., "v2", "2023-10-01")'), - isDefault: external_exports.boolean().default(false).describe("Is this the default version"), - deprecationDate: external_exports.string().optional().describe("API version deprecation date (ISO 8601)"), - sunsetDate: external_exports.string().optional().describe("API version sunset date (ISO 8601)") -}); -var SaasObjectTypeSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Object type name (snake_case)"), - label: external_exports.string().describe("Display label"), - apiName: external_exports.string().describe("API name in external system"), - enabled: external_exports.boolean().default(true).describe("Enable sync for this object"), - supportsCreate: external_exports.boolean().default(true).describe("Supports record creation"), - supportsUpdate: external_exports.boolean().default(true).describe("Supports record updates"), - supportsDelete: external_exports.boolean().default(true).describe("Supports record deletion"), - fieldMappings: external_exports.array(FieldMappingSchema32).optional().describe("Object-specific field mappings") -}); -var SaasConnectorSchema = ConnectorSchema2.extend({ - type: external_exports.literal("saas"), - /** - * SaaS provider - */ - provider: SaasProviderSchema.describe("SaaS provider type"), - /** - * Base URL for API requests - */ - baseUrl: external_exports.string().url().describe("API base URL"), - /** - * API version configuration - */ - apiVersion: ApiVersionConfigSchema.optional().describe("API version configuration"), - /** - * Supported object types to sync - */ - objectTypes: external_exports.array(SaasObjectTypeSchema).describe("Syncable object types"), - /** - * OAuth-specific settings - */ - oauthSettings: external_exports.object({ - scopes: external_exports.array(external_exports.string()).describe("Required OAuth scopes"), - refreshTokenUrl: external_exports.string().url().optional().describe("Token refresh endpoint"), - revokeTokenUrl: external_exports.string().url().optional().describe("Token revocation endpoint"), - autoRefresh: external_exports.boolean().default(true).describe("Automatically refresh expired tokens") - }).optional().describe("OAuth-specific configuration"), - /** - * Pagination settings - */ - paginationConfig: external_exports.object({ - type: external_exports.enum(["cursor", "offset", "page"]).default("cursor").describe("Pagination type"), - defaultPageSize: external_exports.number().min(1).max(1e3).default(100).describe("Default page size"), - maxPageSize: external_exports.number().min(1).max(1e4).default(1e3).describe("Maximum page size") - }).optional().describe("Pagination configuration"), - /** - * Sandbox/test environment settings - */ - sandboxConfig: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Use sandbox environment"), - baseUrl: external_exports.string().url().optional().describe("Sandbox API base URL") - }).optional().describe("Sandbox environment configuration"), - /** - * Custom request headers - */ - customHeaders: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom HTTP headers for all requests") -}); -var salesforceConnectorExample = { - name: "salesforce_production", - label: "Salesforce Production", - type: "saas", - provider: "salesforce", - baseUrl: "https://example.my.salesforce.com", - apiVersion: { - version: "v59.0", - isDefault: true - }, - authentication: { - type: "oauth2", - clientId: "${SALESFORCE_CLIENT_ID}", - clientSecret: "${SALESFORCE_CLIENT_SECRET}", - authorizationUrl: "https://login.salesforce.com/services/oauth2/authorize", - tokenUrl: "https://login.salesforce.com/services/oauth2/token", - grantType: "authorization_code", - scopes: ["api", "refresh_token", "offline_access"] - }, - objectTypes: [ - { - name: "account", - label: "Account", - apiName: "Account", - enabled: true, - supportsCreate: true, - supportsUpdate: true, - supportsDelete: true - }, - { - name: "contact", - label: "Contact", - apiName: "Contact", - enabled: true, - supportsCreate: true, - supportsUpdate: true, - supportsDelete: true - } - ], - syncConfig: { - strategy: "incremental", - direction: "bidirectional", - schedule: "0 */6 * * *", - // Every 6 hours - realtimeSync: true, - conflictResolution: "latest_wins", - batchSize: 200, - deleteMode: "soft_delete" - }, - rateLimitConfig: { - strategy: "token_bucket", - maxRequests: 100, - windowSeconds: 20, - respectUpstreamLimits: true - }, - retryConfig: { - strategy: "exponential_backoff", - maxAttempts: 3, - initialDelayMs: 1e3, - maxDelayMs: 3e4, - backoffMultiplier: 2, - retryableStatusCodes: [408, 429, 500, 502, 503, 504], - retryOnNetworkError: true, - jitter: true - }, - status: "active", - enabled: true -}; -var hubspotConnectorExample = { - name: "hubspot_crm", - label: "HubSpot CRM", - type: "saas", - provider: "hubspot", - baseUrl: "https://api.hubapi.com", - authentication: { - type: "api_key", - apiKey: "${HUBSPOT_API_KEY}", - headerName: "Authorization" - }, - objectTypes: [ - { - name: "company", - label: "Company", - apiName: "companies", - enabled: true, - supportsCreate: true, - supportsUpdate: true, - supportsDelete: true - }, - { - name: "deal", - label: "Deal", - apiName: "deals", - enabled: true, - supportsCreate: true, - supportsUpdate: true, - supportsDelete: true - } - ], - syncConfig: { - strategy: "incremental", - direction: "import", - schedule: "0 */4 * * *", - // Every 4 hours - conflictResolution: "source_wins", - batchSize: 100 - }, - rateLimitConfig: { - strategy: "token_bucket", - maxRequests: 100, - windowSeconds: 10 - }, - status: "active", - enabled: true -}; -var DatabaseProviderSchema22 = external_exports.enum([ - "postgresql", - "mysql", - "mariadb", - "mssql", - "oracle", - "mongodb", - "redis", - "cassandra", - "snowflake", - "bigquery", - "redshift", - "custom" -]).describe("Database provider type"); -var DatabasePoolConfigSchema = external_exports.object({ - min: external_exports.number().min(0).default(2).describe("Minimum connections in pool"), - max: external_exports.number().min(1).default(10).describe("Maximum connections in pool"), - idleTimeoutMs: external_exports.number().min(1e3).default(3e4).describe("Idle connection timeout in ms"), - connectionTimeoutMs: external_exports.number().min(1e3).default(1e4).describe("Connection establishment timeout in ms"), - acquireTimeoutMs: external_exports.number().min(1e3).default(3e4).describe("Connection acquisition timeout in ms"), - evictionRunIntervalMs: external_exports.number().min(1e3).default(3e4).describe("Connection eviction check interval in ms"), - testOnBorrow: external_exports.boolean().default(true).describe("Test connection before use") -}); -var SslConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable SSL/TLS"), - rejectUnauthorized: external_exports.boolean().default(true).describe("Reject unauthorized certificates"), - ca: external_exports.string().optional().describe("Certificate Authority certificate"), - cert: external_exports.string().optional().describe("Client certificate"), - key: external_exports.string().optional().describe("Client private key") -}); -var CdcConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable CDC"), - method: external_exports.enum([ - "log_based", - // Transaction log parsing (e.g., PostgreSQL logical replication) - "trigger_based", - // Database triggers for change tracking - "query_based", - // Timestamp-based queries - "custom" - // Custom CDC implementation - ]).describe("CDC method"), - slotName: external_exports.string().optional().describe("Replication slot name (for log-based CDC)"), - publicationName: external_exports.string().optional().describe("Publication name (for PostgreSQL)"), - startPosition: external_exports.string().optional().describe("Starting position/LSN for CDC stream"), - batchSize: external_exports.number().min(1).max(1e4).default(1e3).describe("CDC batch size"), - pollIntervalMs: external_exports.number().min(100).default(1e3).describe("CDC polling interval in ms") -}); -var DatabaseTableSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Table name in ObjectStack (snake_case)"), - label: external_exports.string().describe("Display label"), - schema: external_exports.string().optional().describe("Database schema name"), - tableName: external_exports.string().describe("Actual table name in database"), - primaryKey: external_exports.string().describe("Primary key column"), - enabled: external_exports.boolean().default(true).describe("Enable sync for this table"), - fieldMappings: external_exports.array(FieldMappingSchema32).optional().describe("Table-specific field mappings"), - whereClause: external_exports.string().optional().describe("SQL WHERE clause for filtering") -}); -var DatabaseConnectorSchema = ConnectorSchema2.extend({ - type: external_exports.literal("database"), - /** - * Database provider - */ - provider: DatabaseProviderSchema22.describe("Database provider type"), - /** - * Connection configuration - */ - connectionConfig: external_exports.object({ - host: external_exports.string().describe("Database host"), - port: external_exports.number().min(1).max(65535).describe("Database port"), - database: external_exports.string().describe("Database name"), - username: external_exports.string().describe("Database username"), - password: external_exports.string().describe("Database password (typically from ENV)"), - options: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Driver-specific connection options") - }).describe("Database connection configuration"), - /** - * Connection pool configuration - */ - poolConfig: DatabasePoolConfigSchema.optional().describe("Connection pool configuration"), - /** - * SSL/TLS configuration - */ - sslConfig: SslConfigSchema.optional().describe("SSL/TLS configuration"), - /** - * Tables to sync - */ - tables: external_exports.array(DatabaseTableSchema).describe("Tables to sync"), - /** - * Change Data Capture configuration - */ - cdcConfig: CdcConfigSchema.optional().describe("CDC configuration"), - /** - * Read replica configuration - */ - readReplicaConfig: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Use read replicas"), - hosts: external_exports.array(external_exports.object({ - host: external_exports.string().describe("Replica host"), - port: external_exports.number().min(1).max(65535).describe("Replica port"), - weight: external_exports.number().min(0).max(1).default(1).describe("Load balancing weight") - })).describe("Read replica hosts") - }).optional().describe("Read replica configuration"), - /** - * Query timeout - */ - queryTimeoutMs: external_exports.number().min(1e3).max(3e5).optional().default(3e4).describe("Query timeout in ms"), - /** - * Enable query logging - */ - enableQueryLogging: external_exports.boolean().optional().default(false).describe("Enable SQL query logging") -}); -var postgresConnectorExample = { - name: "postgres_production", - label: "Production PostgreSQL", - type: "database", - provider: "postgresql", - authentication: { - type: "basic", - username: "${DB_USERNAME}", - password: "${DB_PASSWORD}" - }, - connectionConfig: { - host: "db.example.com", - port: 5432, - database: "production", - username: "${DB_USERNAME}", - password: "${DB_PASSWORD}" - }, - poolConfig: { - min: 2, - max: 20, - idleTimeoutMs: 3e4, - connectionTimeoutMs: 1e4, - acquireTimeoutMs: 3e4, - evictionRunIntervalMs: 3e4, - testOnBorrow: true - }, - sslConfig: { - enabled: true, - rejectUnauthorized: true - }, - tables: [ - { - name: "customer", - label: "Customer", - schema: "public", - tableName: "customers", - primaryKey: "id", - enabled: true - }, - { - name: "order", - label: "Order", - schema: "public", - tableName: "orders", - primaryKey: "id", - enabled: true, - whereClause: "status != 'archived'" - } - ], - cdcConfig: { - enabled: true, - method: "log_based", - slotName: "objectstack_replication_slot", - publicationName: "objectstack_publication", - batchSize: 1e3, - pollIntervalMs: 1e3 - }, - syncConfig: { - strategy: "incremental", - direction: "bidirectional", - realtimeSync: true, - conflictResolution: "latest_wins", - batchSize: 1e3, - deleteMode: "soft_delete" - }, - status: "active", - enabled: true -}; -var mongoConnectorExample = { - name: "mongodb_analytics", - label: "MongoDB Analytics", - type: "database", - provider: "mongodb", - authentication: { - type: "basic", - username: "${MONGO_USERNAME}", - password: "${MONGO_PASSWORD}" - }, - connectionConfig: { - host: "mongodb.example.com", - port: 27017, - database: "analytics", - username: "${MONGO_USERNAME}", - password: "${MONGO_PASSWORD}", - options: { - authSource: "admin", - replicaSet: "rs0" - } - }, - tables: [ - { - name: "event", - label: "Event", - tableName: "events", - primaryKey: "id", - enabled: true - } - ], - cdcConfig: { - enabled: true, - method: "log_based", - batchSize: 1e3, - pollIntervalMs: 500 - }, - syncConfig: { - strategy: "incremental", - direction: "import", - batchSize: 1e3 - }, - status: "active", - enabled: true -}; -var snowflakeConnectorExample = { - name: "snowflake_warehouse", - label: "Snowflake Data Warehouse", - type: "database", - provider: "snowflake", - authentication: { - type: "basic", - username: "${SNOWFLAKE_USERNAME}", - password: "${SNOWFLAKE_PASSWORD}" - }, - connectionConfig: { - host: "account.snowflakecomputing.com", - port: 443, - database: "ANALYTICS_DB", - username: "${SNOWFLAKE_USERNAME}", - password: "${SNOWFLAKE_PASSWORD}", - options: { - warehouse: "COMPUTE_WH", - schema: "PUBLIC", - role: "ANALYST" - } - }, - tables: [ - { - name: "sales_summary", - label: "Sales Summary", - schema: "PUBLIC", - tableName: "SALES_SUMMARY", - primaryKey: "ID", - enabled: true - } - ], - syncConfig: { - strategy: "full", - direction: "import", - schedule: "0 2 * * *", - // Daily at 2 AM - batchSize: 5e3 - }, - queryTimeoutMs: 6e4, - status: "active", - enabled: true -}; -var FileStorageProviderSchema = external_exports.enum([ - "s3", - // Amazon S3 - "azure_blob", - // Azure Blob Storage - "gcs", - // Google Cloud Storage - "dropbox", - // Dropbox - "box", - // Box - "onedrive", - // Microsoft OneDrive - "google_drive", - // Google Drive - "sharepoint", - // SharePoint - "ftp", - // FTP/SFTP - "local", - // Local file system - "custom" - // Custom file storage -]).describe("File storage provider type"); -var FileAccessPatternSchema = external_exports.enum([ - "public_read", - // Public read access - "private", - // Private access - "authenticated_read", - // Requires authentication - "bucket_owner_read", - // Bucket owner has read access - "bucket_owner_full" - // Bucket owner has full control -]).describe("File access pattern"); -var FileMetadataConfigSchema = external_exports.object({ - extractMetadata: external_exports.boolean().default(true).describe("Extract file metadata"), - metadataFields: external_exports.array(external_exports.enum([ - "content_type", - "file_size", - "last_modified", - "etag", - "checksum", - "creator", - "created_at", - "custom" - ])).optional().describe("Metadata fields to extract"), - customMetadata: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom metadata key-value pairs") -}); -var MultipartUploadConfigSchema22 = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable multipart uploads"), - partSize: external_exports.number().min(5 * 1024 * 1024).default(5 * 1024 * 1024).describe("Part size in bytes (min 5MB)"), - maxConcurrentParts: external_exports.number().min(1).max(10).default(5).describe("Maximum concurrent part uploads"), - threshold: external_exports.number().min(5 * 1024 * 1024).default(100 * 1024 * 1024).describe("File size threshold for multipart upload in bytes") -}); -var FileVersioningConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable file versioning"), - maxVersions: external_exports.number().min(1).max(100).optional().describe("Maximum versions to retain"), - retentionDays: external_exports.number().min(1).optional().describe("Version retention period in days") -}); -var FileFilterConfigSchema = external_exports.object({ - includePatterns: external_exports.array(external_exports.string()).optional().describe("File patterns to include (glob)"), - excludePatterns: external_exports.array(external_exports.string()).optional().describe("File patterns to exclude (glob)"), - minFileSize: external_exports.number().min(0).optional().describe("Minimum file size in bytes"), - maxFileSize: external_exports.number().min(1).optional().describe("Maximum file size in bytes"), - allowedExtensions: external_exports.array(external_exports.string()).optional().describe("Allowed file extensions"), - blockedExtensions: external_exports.array(external_exports.string()).optional().describe("Blocked file extensions") -}); -var StorageBucketSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Bucket identifier in ObjectStack (snake_case)"), - label: external_exports.string().describe("Display label"), - bucketName: external_exports.string().describe("Actual bucket/container name in storage system"), - region: external_exports.string().optional().describe("Storage region"), - enabled: external_exports.boolean().default(true).describe("Enable sync for this bucket"), - prefix: external_exports.string().optional().describe("Prefix/path within bucket"), - accessPattern: FileAccessPatternSchema.optional().describe("Access pattern"), - fileFilters: FileFilterConfigSchema.optional().describe("File filter configuration") -}); -var FileStorageConnectorSchema = ConnectorSchema2.extend({ - type: external_exports.literal("file_storage"), - /** - * File storage provider - */ - provider: FileStorageProviderSchema.describe("File storage provider type"), - /** - * Storage configuration - */ - storageConfig: external_exports.object({ - endpoint: external_exports.string().url().optional().describe("Custom endpoint URL"), - region: external_exports.string().optional().describe("Default region"), - pathStyle: external_exports.boolean().optional().default(false).describe("Use path-style URLs (for S3-compatible)") - }).optional().describe("Storage configuration"), - /** - * Buckets/containers to sync - */ - buckets: external_exports.array(StorageBucketSchema).describe("Buckets/containers to sync"), - /** - * File metadata configuration - */ - metadataConfig: FileMetadataConfigSchema.optional().describe("Metadata extraction configuration"), - /** - * Multipart upload configuration - */ - multipartConfig: MultipartUploadConfigSchema22.optional().describe("Multipart upload configuration"), - /** - * File versioning configuration - */ - versioningConfig: FileVersioningConfigSchema.optional().describe("File versioning configuration"), - /** - * Enable server-side encryption - */ - encryption: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable server-side encryption"), - algorithm: external_exports.enum(["AES256", "aws:kms", "custom"]).optional().describe("Encryption algorithm"), - kmsKeyId: external_exports.string().optional().describe("KMS key ID (for aws:kms)") - }).optional().describe("Encryption configuration"), - /** - * Lifecycle policy - */ - lifecyclePolicy: external_exports.object({ - enabled: external_exports.boolean().default(false).describe("Enable lifecycle policy"), - deleteAfterDays: external_exports.number().min(1).optional().describe("Delete files after N days"), - archiveAfterDays: external_exports.number().min(1).optional().describe("Archive files after N days") - }).optional().describe("Lifecycle policy"), - /** - * Content processing configuration - */ - contentProcessing: external_exports.object({ - extractText: external_exports.boolean().default(false).describe("Extract text from documents"), - generateThumbnails: external_exports.boolean().default(false).describe("Generate image thumbnails"), - thumbnailSizes: external_exports.array(external_exports.object({ - width: external_exports.number().min(1), - height: external_exports.number().min(1) - })).optional().describe("Thumbnail sizes"), - virusScan: external_exports.boolean().default(false).describe("Scan for viruses") - }).optional().describe("Content processing configuration"), - /** - * Download/upload buffer size - */ - bufferSize: external_exports.number().min(1024).default(64 * 1024).describe("Buffer size in bytes"), - /** - * Enable transfer acceleration (for supported providers) - */ - transferAcceleration: external_exports.boolean().default(false).describe("Enable transfer acceleration") -}); -var s3ConnectorExample = { - name: "s3_production_assets", - label: "Production S3 Assets", - type: "file_storage", - provider: "s3", - authentication: { - type: "api_key", - apiKey: "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}", - headerName: "Authorization" - }, - storageConfig: { - region: "us-east-1", - pathStyle: false - }, - buckets: [ - { - name: "product_images", - label: "Product Images", - bucketName: "my-company-product-images", - region: "us-east-1", - enabled: true, - prefix: "products/", - accessPattern: "public_read", - fileFilters: { - allowedExtensions: [".jpg", ".jpeg", ".png", ".webp"], - maxFileSize: 10 * 1024 * 1024 - // 10MB - } - }, - { - name: "customer_documents", - label: "Customer Documents", - bucketName: "my-company-customer-docs", - region: "us-east-1", - enabled: true, - accessPattern: "private", - fileFilters: { - allowedExtensions: [".pdf", ".docx", ".xlsx"], - maxFileSize: 50 * 1024 * 1024 - // 50MB - } - } - ], - metadataConfig: { - extractMetadata: true, - metadataFields: ["content_type", "file_size", "last_modified", "etag"] - }, - multipartConfig: { - enabled: true, - partSize: 5 * 1024 * 1024, - // 5MB - maxConcurrentParts: 5, - threshold: 100 * 1024 * 1024 - // 100MB - }, - versioningConfig: { - enabled: true, - maxVersions: 10 - }, - encryption: { - enabled: true, - algorithm: "aws:kms", - kmsKeyId: "${AWS_KMS_KEY_ID}" - }, - contentProcessing: { - extractText: true, - generateThumbnails: true, - thumbnailSizes: [ - { width: 150, height: 150 }, - { width: 300, height: 300 }, - { width: 600, height: 600 } - ], - virusScan: true - }, - syncConfig: { - strategy: "incremental", - direction: "bidirectional", - realtimeSync: true, - conflictResolution: "latest_wins", - batchSize: 100 - }, - transferAcceleration: true, - status: "active", - enabled: true -}; -var googleDriveConnectorExample = { - name: "google_drive_team", - label: "Google Drive Team Folder", - type: "file_storage", - provider: "google_drive", - authentication: { - type: "oauth2", - clientId: "${GOOGLE_CLIENT_ID}", - clientSecret: "${GOOGLE_CLIENT_SECRET}", - authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth", - tokenUrl: "https://oauth2.googleapis.com/token", - grantType: "authorization_code", - scopes: ["https://www.googleapis.com/auth/drive.file"] - }, - buckets: [ - { - name: "team_drive", - label: "Team Drive", - bucketName: "shared-team-drive", - enabled: true, - fileFilters: { - excludePatterns: ["*.tmp", "~$*"] - } - } - ], - metadataConfig: { - extractMetadata: true, - metadataFields: ["content_type", "file_size", "last_modified", "creator", "created_at"] - }, - versioningConfig: { - enabled: true, - maxVersions: 5 - }, - syncConfig: { - strategy: "incremental", - direction: "bidirectional", - realtimeSync: true, - conflictResolution: "latest_wins", - batchSize: 50 - }, - status: "active", - enabled: true -}; -var azureBlobConnectorExample = { - name: "azure_blob_storage", - label: "Azure Blob Storage", - type: "file_storage", - provider: "azure_blob", - authentication: { - type: "api_key", - apiKey: "${AZURE_STORAGE_ACCOUNT_KEY}", - headerName: "x-ms-blob-type" - }, - storageConfig: { - endpoint: "https://myaccount.blob.core.windows.net" - }, - buckets: [ - { - name: "archive_container", - label: "Archive Container", - bucketName: "archive", - enabled: true, - accessPattern: "private" - } - ], - metadataConfig: { - extractMetadata: true, - metadataFields: ["content_type", "file_size", "last_modified", "etag"] - }, - encryption: { - enabled: true, - algorithm: "AES256" - }, - lifecyclePolicy: { - enabled: true, - archiveAfterDays: 90, - deleteAfterDays: 365 - }, - syncConfig: { - strategy: "incremental", - direction: "import", - schedule: "0 1 * * *", - // Daily at 1 AM - batchSize: 200 - }, - status: "active", - enabled: true -}; -var MessageQueueProviderSchema22 = external_exports.enum([ - "rabbitmq", - // RabbitMQ - "kafka", - // Apache Kafka - "redis_pubsub", - // Redis Pub/Sub - "redis_streams", - // Redis Streams - "aws_sqs", - // Amazon SQS - "aws_sns", - // Amazon SNS - "google_pubsub", - // Google Cloud Pub/Sub - "azure_service_bus", - // Azure Service Bus - "azure_event_hubs", - // Azure Event Hubs - "nats", - // NATS - "pulsar", - // Apache Pulsar - "activemq", - // Apache ActiveMQ - "custom" - // Custom message queue -]).describe("Message queue provider type"); -var MessageFormatSchema22 = external_exports.enum([ - "json", - "xml", - "protobuf", - "avro", - "text", - "binary" -]).describe("Message format/serialization"); -var AckModeSchema = external_exports.enum([ - "auto", - // Auto-acknowledge - "manual", - // Manual acknowledge after processing - "client" - // Client-controlled acknowledge -]).describe("Message acknowledgment mode"); -var DeliveryGuaranteeSchema = external_exports.enum([ - "at_most_once", - // Fire and forget - "at_least_once", - // May deliver duplicates - "exactly_once" - // Guaranteed exactly once delivery -]).describe("Message delivery guarantee"); -var ConsumerConfigSchema22 = external_exports.object({ - enabled: external_exports.boolean().optional().default(true).describe("Enable consumer"), - consumerGroup: external_exports.string().optional().describe("Consumer group ID"), - concurrency: external_exports.number().min(1).max(100).optional().default(1).describe("Number of concurrent consumers"), - prefetchCount: external_exports.number().min(1).max(1e3).optional().default(10).describe("Prefetch count"), - ackMode: AckModeSchema.optional().default("manual"), - autoCommit: external_exports.boolean().optional().default(false).describe("Auto-commit offsets"), - autoCommitIntervalMs: external_exports.number().min(100).optional().default(5e3).describe("Auto-commit interval in ms"), - sessionTimeoutMs: external_exports.number().min(1e3).optional().default(3e4).describe("Session timeout in ms"), - rebalanceTimeoutMs: external_exports.number().min(1e3).optional().describe("Rebalance timeout in ms") -}); -var ProducerConfigSchema = external_exports.object({ - enabled: external_exports.boolean().optional().default(true).describe("Enable producer"), - acks: external_exports.enum(["0", "1", "all"]).optional().default("all").describe("Acknowledgment level"), - compressionType: external_exports.enum(["none", "gzip", "snappy", "lz4", "zstd"]).optional().default("none").describe("Compression type"), - batchSize: external_exports.number().min(1).optional().default(16384).describe("Batch size in bytes"), - lingerMs: external_exports.number().min(0).optional().default(0).describe("Linger time in ms"), - maxInFlightRequests: external_exports.number().min(1).optional().default(5).describe("Max in-flight requests"), - idempotence: external_exports.boolean().optional().default(true).describe("Enable idempotent producer"), - transactional: external_exports.boolean().optional().default(false).describe("Enable transactional producer"), - transactionTimeoutMs: external_exports.number().min(1e3).optional().describe("Transaction timeout in ms") -}); -var DlqConfigSchema = external_exports.object({ - enabled: external_exports.boolean().optional().default(false).describe("Enable DLQ"), - queueName: external_exports.string().describe("Dead letter queue/topic name"), - maxRetries: external_exports.number().min(0).max(100).optional().default(3).describe("Max retries before DLQ"), - retryDelayMs: external_exports.number().min(0).optional().default(6e4).describe("Retry delay in ms") -}); -var TopicQueueSchema = external_exports.object({ - name: external_exports.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Topic/queue identifier in ObjectStack (snake_case)"), - label: external_exports.string().describe("Display label"), - topicName: external_exports.string().describe("Actual topic/queue name in message queue system"), - enabled: external_exports.boolean().optional().default(true).describe("Enable sync for this topic/queue"), - /** - * Consumer or Producer - */ - mode: external_exports.enum(["consumer", "producer", "both"]).optional().default("both").describe("Consumer, producer, or both"), - /** - * Message format - */ - messageFormat: MessageFormatSchema22.optional().default("json"), - /** - * Partition/shard configuration - */ - partitions: external_exports.number().min(1).optional().describe("Number of partitions (for Kafka)"), - /** - * Replication factor - */ - replicationFactor: external_exports.number().min(1).optional().describe("Replication factor (for Kafka)"), - /** - * Consumer configuration - */ - consumerConfig: ConsumerConfigSchema22.optional().describe("Consumer-specific configuration"), - /** - * Producer configuration - */ - producerConfig: ProducerConfigSchema.optional().describe("Producer-specific configuration"), - /** - * Dead letter queue configuration - */ - dlqConfig: DlqConfigSchema.optional().describe("Dead letter queue configuration"), - /** - * Message routing key (for RabbitMQ) - */ - routingKey: external_exports.string().optional().describe("Routing key pattern"), - /** - * Message filter - */ - messageFilter: external_exports.object({ - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Filter by message headers"), - attributes: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Filter by message attributes") - }).optional().describe("Message filter criteria") -}); -var MessageQueueConnectorSchema = ConnectorSchema2.extend({ - type: external_exports.literal("message_queue"), - /** - * Message queue provider - */ - provider: MessageQueueProviderSchema22.describe("Message queue provider type"), - /** - * Broker configuration - */ - brokerConfig: external_exports.object({ - brokers: external_exports.array(external_exports.string()).describe("Broker addresses (host:port)"), - clientId: external_exports.string().optional().describe("Client ID"), - connectionTimeoutMs: external_exports.number().min(1e3).optional().default(3e4).describe("Connection timeout in ms"), - requestTimeoutMs: external_exports.number().min(1e3).optional().default(3e4).describe("Request timeout in ms") - }).describe("Broker connection configuration"), - /** - * Topics/queues to sync - */ - topics: external_exports.array(TopicQueueSchema).describe("Topics/queues to sync"), - /** - * Delivery guarantee - */ - deliveryGuarantee: DeliveryGuaranteeSchema.optional().default("at_least_once"), - /** - * SSL/TLS configuration - */ - sslConfig: external_exports.object({ - enabled: external_exports.boolean().optional().default(false).describe("Enable SSL/TLS"), - rejectUnauthorized: external_exports.boolean().optional().default(true).describe("Reject unauthorized certificates"), - ca: external_exports.string().optional().describe("CA certificate"), - cert: external_exports.string().optional().describe("Client certificate"), - key: external_exports.string().optional().describe("Client private key") - }).optional().describe("SSL/TLS configuration"), - /** - * SASL authentication (for Kafka) - */ - saslConfig: external_exports.object({ - mechanism: external_exports.enum(["plain", "scram-sha-256", "scram-sha-512", "aws"]).describe("SASL mechanism"), - username: external_exports.string().optional().describe("SASL username"), - password: external_exports.string().optional().describe("SASL password") - }).optional().describe("SASL authentication configuration"), - /** - * Schema registry configuration (for Kafka/Avro) - */ - schemaRegistry: external_exports.object({ - url: external_exports.string().url().describe("Schema registry URL"), - auth: external_exports.object({ - username: external_exports.string().optional(), - password: external_exports.string().optional() - }).optional() - }).optional().describe("Schema registry configuration"), - /** - * Message ordering - */ - preserveOrder: external_exports.boolean().optional().default(true).describe("Preserve message ordering"), - /** - * Enable metrics - */ - enableMetrics: external_exports.boolean().optional().default(true).describe("Enable message queue metrics"), - /** - * Enable distributed tracing - */ - enableTracing: external_exports.boolean().optional().default(false).describe("Enable distributed tracing") -}); -var kafkaConnectorExample = { - name: "kafka_production", - label: "Production Kafka Cluster", - type: "message_queue", - provider: "kafka", - authentication: { - type: "none" - }, - brokerConfig: { - brokers: ["kafka-1.example.com:9092", "kafka-2.example.com:9092", "kafka-3.example.com:9092"], - clientId: "objectstack-client", - connectionTimeoutMs: 3e4, - requestTimeoutMs: 3e4 - }, - topics: [ - { - name: "order_events", - label: "Order Events", - topicName: "orders", - enabled: true, - mode: "consumer", - messageFormat: "json", - partitions: 10, - replicationFactor: 3, - consumerConfig: { - enabled: true, - consumerGroup: "objectstack-consumer-group", - concurrency: 5, - prefetchCount: 100, - ackMode: "manual", - autoCommit: false, - sessionTimeoutMs: 3e4 - }, - dlqConfig: { - enabled: true, - queueName: "orders-dlq", - maxRetries: 3, - retryDelayMs: 6e4 - } - }, - { - name: "user_activity", - label: "User Activity", - topicName: "user-activity", - enabled: true, - mode: "producer", - messageFormat: "json", - partitions: 5, - replicationFactor: 3, - producerConfig: { - enabled: true, - acks: "all", - compressionType: "snappy", - batchSize: 16384, - lingerMs: 10, - maxInFlightRequests: 5, - idempotence: true - } - } - ], - deliveryGuarantee: "at_least_once", - saslConfig: { - mechanism: "scram-sha-256", - username: "${KAFKA_USERNAME}", - password: "${KAFKA_PASSWORD}" - }, - sslConfig: { - enabled: true, - rejectUnauthorized: true - }, - preserveOrder: true, - enableMetrics: true, - enableTracing: true, - status: "active", - enabled: true -}; -var rabbitmqConnectorExample = { - name: "rabbitmq_events", - label: "RabbitMQ Event Bus", - type: "message_queue", - provider: "rabbitmq", - authentication: { - type: "basic", - username: "${RABBITMQ_USERNAME}", - password: "${RABBITMQ_PASSWORD}" - }, - brokerConfig: { - brokers: ["amqp://rabbitmq.example.com:5672"], - clientId: "objectstack-rabbitmq-client" - }, - topics: [ - { - name: "notifications", - label: "Notifications", - topicName: "notifications", - enabled: true, - mode: "both", - messageFormat: "json", - routingKey: "notification.*", - consumerConfig: { - enabled: true, - prefetchCount: 10, - ackMode: "manual" - }, - producerConfig: { - enabled: true - }, - dlqConfig: { - enabled: true, - queueName: "notifications-dlq", - maxRetries: 3, - retryDelayMs: 3e4 - } - } - ], - deliveryGuarantee: "at_least_once", - status: "active", - enabled: true -}; -var sqsConnectorExample = { - name: "aws_sqs_queue", - label: "AWS SQS Queue", - type: "message_queue", - provider: "aws_sqs", - authentication: { - type: "api_key", - apiKey: "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}", - headerName: "Authorization" - }, - brokerConfig: { - brokers: ["https://sqs.us-east-1.amazonaws.com"] - }, - topics: [ - { - name: "task_queue", - label: "Task Queue", - topicName: "task-queue", - enabled: true, - mode: "consumer", - messageFormat: "json", - consumerConfig: { - enabled: true, - concurrency: 10, - prefetchCount: 10, - ackMode: "manual" - }, - dlqConfig: { - enabled: true, - queueName: "task-queue-dlq", - maxRetries: 3, - retryDelayMs: 12e4 - } - } - ], - deliveryGuarantee: "at_least_once", - retryConfig: { - strategy: "exponential_backoff", - maxAttempts: 3, - initialDelayMs: 1e3, - maxDelayMs: 6e4, - backoffMultiplier: 2 - }, - status: "active", - enabled: true -}; -var pubsubConnectorExample = { - name: "gcp_pubsub", - label: "Google Cloud Pub/Sub", - type: "message_queue", - provider: "google_pubsub", - authentication: { - type: "oauth2", - clientId: "${GCP_CLIENT_ID}", - clientSecret: "${GCP_CLIENT_SECRET}", - authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth", - tokenUrl: "https://oauth2.googleapis.com/token", - grantType: "client_credentials", - scopes: ["https://www.googleapis.com/auth/pubsub"] - }, - brokerConfig: { - brokers: ["pubsub.googleapis.com"] - }, - topics: [ - { - name: "analytics_events", - label: "Analytics Events", - topicName: "projects/my-project/topics/analytics-events", - enabled: true, - mode: "both", - messageFormat: "json", - consumerConfig: { - enabled: true, - consumerGroup: "objectstack-subscription", - concurrency: 5, - prefetchCount: 100, - ackMode: "manual" - } - } - ], - deliveryGuarantee: "at_least_once", - enableMetrics: true, - status: "active", - enabled: true -}; -var GitHubProviderSchema = external_exports.enum([ - "github", - // GitHub.com - "github_enterprise" - // GitHub Enterprise Server -]).describe("GitHub provider type"); -var GitHubRepositorySchema = external_exports.object({ - /** - * Repository owner (organization or user) - */ - owner: external_exports.string().describe("Repository owner (organization or username)"), - /** - * Repository name - */ - name: external_exports.string().describe("Repository name"), - /** - * Default branch name - */ - defaultBranch: external_exports.string().optional().default("main").describe("Default branch name"), - /** - * Enable auto-merge for PRs - */ - autoMerge: external_exports.boolean().optional().default(false).describe("Enable auto-merge for pull requests"), - /** - * Branch protection rules - */ - branchProtection: external_exports.object({ - requiredReviewers: external_exports.number().int().min(0).optional().default(1).describe("Required number of reviewers"), - requireStatusChecks: external_exports.boolean().optional().default(true).describe("Require status checks to pass"), - enforceAdmins: external_exports.boolean().optional().default(false).describe("Enforce protections for admins"), - allowForcePushes: external_exports.boolean().optional().default(false).describe("Allow force pushes"), - allowDeletions: external_exports.boolean().optional().default(false).describe("Allow branch deletions") - }).optional().describe("Branch protection configuration"), - /** - * Repository topics/tags - */ - topics: external_exports.array(external_exports.string()).optional().describe("Repository topics") -}); -var GitHubCommitConfigSchema = external_exports.object({ - /** - * Commit author name - */ - authorName: external_exports.string().optional().describe("Commit author name"), - /** - * Commit author email - */ - authorEmail: external_exports.string().email().optional().describe("Commit author email"), - /** - * GPG sign commits - */ - signCommits: external_exports.boolean().optional().default(false).describe("Sign commits with GPG"), - /** - * Commit message template - */ - messageTemplate: external_exports.string().optional().describe("Commit message template"), - /** - * Conventional commits format - */ - useConventionalCommits: external_exports.boolean().optional().default(true).describe("Use conventional commits format") -}); -var GitHubPullRequestConfigSchema = external_exports.object({ - /** - * Default PR title template - */ - titleTemplate: external_exports.string().optional().describe("PR title template"), - /** - * Default PR body template - */ - bodyTemplate: external_exports.string().optional().describe("PR body template"), - /** - * Default reviewers - */ - defaultReviewers: external_exports.array(external_exports.string()).optional().describe("Default reviewers (usernames)"), - /** - * Default assignees - */ - defaultAssignees: external_exports.array(external_exports.string()).optional().describe("Default assignees (usernames)"), - /** - * Default labels - */ - defaultLabels: external_exports.array(external_exports.string()).optional().describe("Default labels"), - /** - * Enable draft PRs by default - */ - draftByDefault: external_exports.boolean().optional().default(false).describe("Create draft PRs by default"), - /** - * Auto-delete head branch after merge - */ - deleteHeadBranch: external_exports.boolean().optional().default(true).describe("Delete head branch after merge") -}); -var GitHubActionsWorkflowSchema = external_exports.object({ - /** - * Workflow name - */ - name: external_exports.string().describe("Workflow name"), - /** - * Workflow file path - */ - path: external_exports.string().describe("Workflow file path (e.g., .github/workflows/ci.yml)"), - /** - * Enable workflow - */ - enabled: external_exports.boolean().optional().default(true).describe("Enable workflow"), - /** - * Workflow triggers - */ - triggers: external_exports.array(external_exports.enum([ - "push", - "pull_request", - "release", - "schedule", - "workflow_dispatch", - "repository_dispatch" - ])).optional().describe("Workflow triggers"), - /** - * Environment variables - */ - env: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Environment variables"), - /** - * Secrets required - */ - secrets: external_exports.array(external_exports.string()).optional().describe("Required secrets") -}); -var GitHubReleaseConfigSchema = external_exports.object({ - /** - * Tag name pattern - */ - tagPattern: external_exports.string().optional().default("v*").describe("Tag name pattern (e.g., v*, release/*)"), - /** - * Use semantic versioning - */ - semanticVersioning: external_exports.boolean().optional().default(true).describe("Use semantic versioning"), - /** - * Generate release notes automatically - */ - autoReleaseNotes: external_exports.boolean().optional().default(true).describe("Generate release notes automatically"), - /** - * Release name template - */ - releaseNameTemplate: external_exports.string().optional().describe("Release name template"), - /** - * Pre-release pattern - */ - preReleasePattern: external_exports.string().optional().describe("Pre-release pattern (e.g., *-alpha, *-beta)"), - /** - * Create draft releases - */ - draftByDefault: external_exports.boolean().optional().default(false).describe("Create draft releases by default") -}); -var GitHubIssueTrackingSchema = external_exports.object({ - /** - * Enable issue tracking - */ - enabled: external_exports.boolean().optional().default(true).describe("Enable issue tracking"), - /** - * Default issue labels - */ - defaultLabels: external_exports.array(external_exports.string()).optional().describe("Default issue labels"), - /** - * Issue template paths - */ - templatePaths: external_exports.array(external_exports.string()).optional().describe("Issue template paths"), - /** - * Auto-assign issues - */ - autoAssign: external_exports.boolean().optional().default(false).describe("Auto-assign issues"), - /** - * Auto-close stale issues - */ - autoCloseStale: external_exports.object({ - enabled: external_exports.boolean().default(false), - daysBeforeStale: external_exports.number().int().min(1).optional().default(60), - daysBeforeClose: external_exports.number().int().min(1).optional().default(7), - staleLabel: external_exports.string().optional().default("stale") - }).optional().describe("Auto-close stale issues configuration") -}); -var GitHubConnectorSchema = ConnectorSchema2.extend({ - type: external_exports.literal("saas"), - /** - * GitHub provider type - */ - provider: GitHubProviderSchema.describe("GitHub provider"), - /** - * GitHub API base URL - */ - baseUrl: external_exports.string().url().optional().default("https://api.github.com").describe("GitHub API base URL"), - /** - * Repositories to integrate - */ - repositories: external_exports.array(GitHubRepositorySchema).describe("Repositories to manage"), - /** - * Commit configuration - */ - commitConfig: GitHubCommitConfigSchema.optional().describe("Commit configuration"), - /** - * Pull request configuration - */ - pullRequestConfig: GitHubPullRequestConfigSchema.optional().describe("Pull request configuration"), - /** - * GitHub Actions workflows - */ - workflows: external_exports.array(GitHubActionsWorkflowSchema).optional().describe("GitHub Actions workflows"), - /** - * Release configuration - */ - releaseConfig: GitHubReleaseConfigSchema.optional().describe("Release configuration"), - /** - * Issue tracking configuration - */ - issueTracking: GitHubIssueTrackingSchema.optional().describe("Issue tracking configuration"), - /** - * Enable webhooks - */ - enableWebhooks: external_exports.boolean().optional().default(true).describe("Enable GitHub webhooks"), - /** - * Webhook events to subscribe - */ - webhookEvents: external_exports.array(external_exports.enum([ - "push", - "pull_request", - "issues", - "issue_comment", - "release", - "workflow_run", - "deployment", - "deployment_status", - "check_run", - "check_suite", - "status" - ])).optional().describe("Webhook events to subscribe to") -}); -var githubPublicConnectorExample = { - name: "github_public", - label: "GitHub.com", - type: "saas", - provider: "github", - baseUrl: "https://api.github.com", - authentication: { - type: "oauth2", - clientId: "${GITHUB_CLIENT_ID}", - clientSecret: "${GITHUB_CLIENT_SECRET}", - authorizationUrl: "https://github.com/login/oauth/authorize", - tokenUrl: "https://github.com/login/oauth/access_token", - scopes: ["repo", "workflow", "write:packages"] - }, - repositories: [ - { - owner: "objectstack-ai", - name: "spec", - defaultBranch: "main", - autoMerge: false, - branchProtection: { - requiredReviewers: 1, - requireStatusChecks: true, - enforceAdmins: false, - allowForcePushes: false, - allowDeletions: false - }, - topics: ["objectstack", "low-code", "metadata-driven"] - } - ], - commitConfig: { - authorName: "ObjectStack Bot", - authorEmail: "bot@objectstack.ai", - signCommits: false, - useConventionalCommits: true - }, - pullRequestConfig: { - titleTemplate: "{{type}}: {{description}}", - defaultReviewers: ["team-lead"], - defaultLabels: ["automated", "ai-generated"], - draftByDefault: false, - deleteHeadBranch: true - }, - workflows: [ - { - name: "CI", - path: ".github/workflows/ci.yml", - enabled: true, - triggers: ["push", "pull_request"] - }, - { - name: "Release", - path: ".github/workflows/release.yml", - enabled: true, - triggers: ["release"] - } - ], - releaseConfig: { - tagPattern: "v*", - semanticVersioning: true, - autoReleaseNotes: true, - releaseNameTemplate: "Release {{version}}", - draftByDefault: false - }, - issueTracking: { - enabled: true, - defaultLabels: ["needs-triage"], - autoAssign: false, - autoCloseStale: { - enabled: true, - daysBeforeStale: 60, - daysBeforeClose: 7, - staleLabel: "stale" - } - }, - enableWebhooks: true, - webhookEvents: ["push", "pull_request", "release", "workflow_run"], - status: "active", - enabled: true -}; -var githubEnterpriseConnectorExample = { - name: "github_enterprise", - label: "GitHub Enterprise", - type: "saas", - provider: "github_enterprise", - baseUrl: "https://github.enterprise.com/api/v3", - authentication: { - type: "oauth2", - clientId: "${GITHUB_ENTERPRISE_CLIENT_ID}", - clientSecret: "${GITHUB_ENTERPRISE_CLIENT_SECRET}", - authorizationUrl: "https://github.enterprise.com/login/oauth/authorize", - tokenUrl: "https://github.enterprise.com/login/oauth/access_token", - scopes: ["repo", "admin:org", "workflow"] - }, - repositories: [ - { - owner: "enterprise-org", - name: "internal-app", - defaultBranch: "develop", - autoMerge: true, - branchProtection: { - requiredReviewers: 2, - requireStatusChecks: true, - enforceAdmins: true, - allowForcePushes: false, - allowDeletions: false - } - } - ], - commitConfig: { - authorName: "CI Bot", - authorEmail: "ci-bot@enterprise.com", - signCommits: true, - useConventionalCommits: true - }, - pullRequestConfig: { - titleTemplate: "[{{branch}}] {{description}}", - bodyTemplate: `## Changes - -{{changes}} - -## Testing - -{{testing}}`, - defaultReviewers: ["tech-lead", "security-team"], - defaultLabels: ["automated"], - draftByDefault: true, - deleteHeadBranch: true - }, - releaseConfig: { - tagPattern: "release/*", - semanticVersioning: true, - autoReleaseNotes: true, - preReleasePattern: "*-rc*", - draftByDefault: true - }, - status: "active", - enabled: true -}; -var VercelProviderSchema = external_exports.enum([ - "vercel" -]).describe("Vercel provider type"); -var VercelFrameworkSchema = external_exports.enum([ - "nextjs", - "react", - "vue", - "nuxtjs", - "gatsby", - "remix", - "astro", - "sveltekit", - "solid", - "angular", - "static", - "other" -]).describe("Frontend framework"); -var GitRepositoryConfigSchema = external_exports.object({ - /** - * Git provider type - */ - type: external_exports.enum(["github", "gitlab", "bitbucket"]).describe("Git provider"), - /** - * Repository identifier (owner/repo) - */ - repo: external_exports.string().describe("Repository identifier (e.g., owner/repo)"), - /** - * Production branch - */ - productionBranch: external_exports.string().optional().default("main").describe("Production branch name"), - /** - * Auto-deploy production branch - */ - autoDeployProduction: external_exports.boolean().optional().default(true).describe("Auto-deploy production branch"), - /** - * Auto-deploy preview branches - */ - autoDeployPreview: external_exports.boolean().optional().default(true).describe("Auto-deploy preview branches") -}); -var BuildConfigSchema = external_exports.object({ - /** - * Build command - */ - buildCommand: external_exports.string().optional().describe("Build command (e.g., npm run build)"), - /** - * Output directory - */ - outputDirectory: external_exports.string().optional().describe("Output directory (e.g., .next, dist)"), - /** - * Install command - */ - installCommand: external_exports.string().optional().describe("Install command (e.g., npm install, pnpm install)"), - /** - * Development command - */ - devCommand: external_exports.string().optional().describe("Development command (e.g., npm run dev)"), - /** - * Node.js version - */ - nodeVersion: external_exports.string().optional().describe("Node.js version (e.g., 18.x, 20.x)"), - /** - * Environment variables - */ - env: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Build environment variables") -}); -var DeploymentConfigSchema = external_exports.object({ - /** - * Enable automatic deployments - */ - autoDeployment: external_exports.boolean().optional().default(true).describe("Enable automatic deployments"), - /** - * Deployment regions - */ - regions: external_exports.array(external_exports.enum([ - "iad1", - // US East (Washington, D.C.) - "sfo1", - // US West (San Francisco) - "gru1", - // South America (São Paulo) - "lhr1", - // Europe West (London) - "fra1", - // Europe Central (Frankfurt) - "sin1", - // Asia (Singapore) - "syd1", - // Australia (Sydney) - "hnd1", - // Asia (Tokyo) - "icn1" - // Asia (Seoul) - ])).optional().describe("Deployment regions"), - /** - * Enable preview deployments - */ - enablePreview: external_exports.boolean().optional().default(true).describe("Enable preview deployments"), - /** - * Preview deployment comments on PRs - */ - previewComments: external_exports.boolean().optional().default(true).describe("Post preview URLs in PR comments"), - /** - * Production deployment protection - */ - productionProtection: external_exports.boolean().optional().default(true).describe("Require approval for production deployments"), - /** - * Deploy hooks - */ - deployHooks: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Hook name"), - url: external_exports.string().url().describe("Deploy hook URL"), - branch: external_exports.string().optional().describe("Target branch") - })).optional().describe("Deploy hooks") -}); -var DomainConfigSchema = external_exports.object({ - /** - * Domain name - */ - domain: external_exports.string().describe("Domain name (e.g., app.example.com)"), - /** - * Enable HTTPS redirect - */ - httpsRedirect: external_exports.boolean().optional().default(true).describe("Redirect HTTP to HTTPS"), - /** - * Custom SSL certificate - */ - customCertificate: external_exports.object({ - cert: external_exports.string().describe("SSL certificate"), - key: external_exports.string().describe("Private key"), - ca: external_exports.string().optional().describe("Certificate authority") - }).optional().describe("Custom SSL certificate"), - /** - * Git branch for this domain - */ - gitBranch: external_exports.string().optional().describe("Git branch to deploy to this domain") -}); -var EnvironmentVariablesSchema = external_exports.object({ - /** - * Variable name - */ - key: external_exports.string().describe("Environment variable name"), - /** - * Variable value - */ - value: external_exports.string().describe("Environment variable value"), - /** - * Target environments - */ - target: external_exports.array(external_exports.enum(["production", "preview", "development"])).describe("Target environments"), - /** - * Is secret (encrypted) - */ - isSecret: external_exports.boolean().optional().default(false).describe("Encrypt this variable"), - /** - * Git branch (for preview/development) - */ - gitBranch: external_exports.string().optional().describe("Specific git branch") -}); -var EdgeFunctionConfigSchema = external_exports.object({ - /** - * Function name - */ - name: external_exports.string().describe("Edge function name"), - /** - * Function path - */ - path: external_exports.string().describe("Function path (e.g., /api/*)"), - /** - * Regions to deploy - */ - regions: external_exports.array(external_exports.string()).optional().describe("Specific regions for this function"), - /** - * Memory limit (MB) - */ - memoryLimit: external_exports.number().int().min(128).max(3008).optional().default(1024).describe("Memory limit in MB"), - /** - * Timeout (seconds) - */ - timeout: external_exports.number().int().min(1).max(300).optional().default(10).describe("Timeout in seconds") -}); -var VercelProjectSchema = external_exports.object({ - /** - * Project name - */ - name: external_exports.string().describe("Vercel project name"), - /** - * Framework - */ - framework: VercelFrameworkSchema.optional().describe("Frontend framework"), - /** - * Git repository - */ - gitRepository: GitRepositoryConfigSchema.optional().describe("Git repository configuration"), - /** - * Build configuration - */ - buildConfig: BuildConfigSchema.optional().describe("Build configuration"), - /** - * Deployment configuration - */ - deploymentConfig: DeploymentConfigSchema.optional().describe("Deployment configuration"), - /** - * Custom domains - */ - domains: external_exports.array(DomainConfigSchema).optional().describe("Custom domains"), - /** - * Environment variables - */ - environmentVariables: external_exports.array(EnvironmentVariablesSchema).optional().describe("Environment variables"), - /** - * Edge functions - */ - edgeFunctions: external_exports.array(EdgeFunctionConfigSchema).optional().describe("Edge functions"), - /** - * Root directory - */ - rootDirectory: external_exports.string().optional().describe("Root directory (for monorepos)") -}); -var VercelMonitoringSchema = external_exports.object({ - /** - * Enable Web Analytics - */ - enableWebAnalytics: external_exports.boolean().optional().default(false).describe("Enable Vercel Web Analytics"), - /** - * Enable Speed Insights - */ - enableSpeedInsights: external_exports.boolean().optional().default(false).describe("Enable Vercel Speed Insights"), - /** - * Enable Log Drains - */ - logDrains: external_exports.array(external_exports.object({ - name: external_exports.string().describe("Log drain name"), - url: external_exports.string().url().describe("Log drain URL"), - headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Custom headers"), - sources: external_exports.array(external_exports.enum(["static", "lambda", "edge"])).optional().describe("Log sources") - })).optional().describe("Log drains configuration") -}); -var VercelTeamSchema = external_exports.object({ - /** - * Team ID or slug - */ - teamId: external_exports.string().optional().describe("Team ID or slug"), - /** - * Team name - */ - teamName: external_exports.string().optional().describe("Team name") -}); -var VercelConnectorSchema = ConnectorSchema2.extend({ - type: external_exports.literal("saas"), - /** - * Vercel provider - */ - provider: VercelProviderSchema.describe("Vercel provider"), - /** - * Vercel API base URL - */ - baseUrl: external_exports.string().url().optional().default("https://api.vercel.com").describe("Vercel API base URL"), - /** - * Team configuration - */ - team: VercelTeamSchema.optional().describe("Vercel team configuration"), - /** - * Projects to manage - */ - projects: external_exports.array(VercelProjectSchema).describe("Vercel projects"), - /** - * Monitoring configuration - */ - monitoring: VercelMonitoringSchema.optional().describe("Monitoring configuration"), - /** - * Enable webhooks - */ - enableWebhooks: external_exports.boolean().optional().default(true).describe("Enable Vercel webhooks"), - /** - * Webhook events to subscribe - */ - webhookEvents: external_exports.array(external_exports.enum([ - "deployment.created", - "deployment.succeeded", - "deployment.failed", - "deployment.ready", - "deployment.error", - "deployment.canceled", - "deployment-checks-completed", - "deployment-prepared", - "project.created", - "project.removed" - ])).optional().describe("Webhook events to subscribe to") -}); -var vercelNextJsConnectorExample = { - name: "vercel_production", - label: "Vercel Production", - type: "saas", - provider: "vercel", - baseUrl: "https://api.vercel.com", - authentication: { - type: "bearer", - token: "${VERCEL_TOKEN}" - }, - projects: [ - { - name: "objectstack-app", - framework: "nextjs", - gitRepository: { - type: "github", - repo: "objectstack-ai/app", - productionBranch: "main", - autoDeployProduction: true, - autoDeployPreview: true - }, - buildConfig: { - buildCommand: "npm run build", - outputDirectory: ".next", - installCommand: "npm ci", - devCommand: "npm run dev", - nodeVersion: "20.x", - env: { - NEXT_PUBLIC_API_URL: "https://api.objectstack.ai" - } - }, - deploymentConfig: { - autoDeployment: true, - regions: ["iad1", "sfo1", "fra1"], - enablePreview: true, - previewComments: true, - productionProtection: true - }, - domains: [ - { - domain: "app.objectstack.ai", - httpsRedirect: true, - gitBranch: "main" - }, - { - domain: "staging.objectstack.ai", - httpsRedirect: true, - gitBranch: "develop" - } - ], - environmentVariables: [ - { - key: "DATABASE_URL", - value: "${DATABASE_URL}", - target: ["production", "preview"], - isSecret: true - }, - { - key: "NEXT_PUBLIC_ANALYTICS_ID", - value: "UA-XXXXXXXX-X", - target: ["production"], - isSecret: false - } - ], - edgeFunctions: [ - { - name: "api-middleware", - path: "/api/*", - regions: ["iad1", "sfo1"], - memoryLimit: 1024, - timeout: 10 - } - ] - } - ], - monitoring: { - enableWebAnalytics: true, - enableSpeedInsights: true, - logDrains: [ - { - name: "datadog-logs", - url: "https://http-intake.logs.datadoghq.com/api/v2/logs", - headers: { - "DD-API-KEY": "${DATADOG_API_KEY}" - }, - sources: ["lambda", "edge"] - } - ] - }, - enableWebhooks: true, - webhookEvents: [ - "deployment.succeeded", - "deployment.failed", - "deployment.ready" - ], - status: "active", - enabled: true -}; -var vercelStaticSiteConnectorExample = { - name: "vercel_docs", - label: "Vercel Documentation", - type: "saas", - provider: "vercel", - baseUrl: "https://api.vercel.com", - authentication: { - type: "bearer", - token: "${VERCEL_TOKEN}" - }, - team: { - teamId: "team_xxxxxx", - teamName: "ObjectStack" - }, - projects: [ - { - name: "objectstack-docs", - framework: "static", - gitRepository: { - type: "github", - repo: "objectstack-ai/docs", - productionBranch: "main", - autoDeployProduction: true, - autoDeployPreview: true - }, - buildConfig: { - buildCommand: "npm run build", - outputDirectory: "dist", - installCommand: "npm ci", - nodeVersion: "18.x" - }, - deploymentConfig: { - autoDeployment: true, - regions: ["iad1", "lhr1", "sin1"], - enablePreview: true, - previewComments: true, - productionProtection: false - }, - domains: [ - { - domain: "docs.objectstack.ai", - httpsRedirect: true - } - ], - environmentVariables: [ - { - key: "ALGOLIA_APP_ID", - value: "${ALGOLIA_APP_ID}", - target: ["production", "preview"], - isSecret: false - }, - { - key: "ALGOLIA_API_KEY", - value: "${ALGOLIA_API_KEY}", - target: ["production", "preview"], - isSecret: true - } - ] - } - ], - monitoring: { - enableWebAnalytics: true, - enableSpeedInsights: false - }, - enableWebhooks: false, - status: "active", - enabled: true -}; -var studio_exports = {}; -__export4(studio_exports, { - ActionContributionSchema: () => ActionContributionSchema, - ActionLocationSchema: () => ActionLocationSchema, - ActivationEventSchema: () => ActivationEventSchema22, - BUILT_IN_NODE_DESCRIPTORS: () => BUILT_IN_NODE_DESCRIPTORS, - CanvasSnapSettingsSchema: () => CanvasSnapSettingsSchema, - CanvasZoomSettingsSchema: () => CanvasZoomSettingsSchema, - CommandContributionSchema: () => CommandContributionSchema, - ERDiagramConfigSchema: () => ERDiagramConfigSchema, - ERLayoutAlgorithmSchema: () => ERLayoutAlgorithmSchema, - ERNodeDisplaySchema: () => ERNodeDisplaySchema, - ElementPaletteItemSchema: () => ElementPaletteItemSchema, - FieldEditorConfigSchema: () => FieldEditorConfigSchema, - FieldGroupSchema: () => FieldGroupSchema, - FieldPropertySectionSchema: () => FieldPropertySectionSchema, - FlowBuilderConfigSchema: () => FlowBuilderConfigSchema, - FlowCanvasEdgeSchema: () => FlowCanvasEdgeSchema, - FlowCanvasEdgeStyleSchema: () => FlowCanvasEdgeStyleSchema, - FlowCanvasNodeSchema: () => FlowCanvasNodeSchema, - FlowLayoutAlgorithmSchema: () => FlowLayoutAlgorithmSchema, - FlowLayoutDirectionSchema: () => FlowLayoutDirectionSchema, - FlowNodeRenderDescriptorSchema: () => FlowNodeRenderDescriptorSchema, - FlowNodeShapeSchema: () => FlowNodeShapeSchema, - InterfaceBuilderConfigSchema: () => InterfaceBuilderConfigSchema, - MetadataIconContributionSchema: () => MetadataIconContributionSchema, - MetadataViewerContributionSchema: () => MetadataViewerContributionSchema, - ObjectDesignerConfigSchema: () => ObjectDesignerConfigSchema, - ObjectDesignerDefaultViewSchema: () => ObjectDesignerDefaultViewSchema, - ObjectFilterSchema: () => ObjectFilterSchema, - ObjectListDisplayModeSchema: () => ObjectListDisplayModeSchema, - ObjectManagerConfigSchema: () => ObjectManagerConfigSchema, - ObjectPreviewConfigSchema: () => ObjectPreviewConfigSchema, - ObjectPreviewTabSchema: () => ObjectPreviewTabSchema, - ObjectSortFieldSchema: () => ObjectSortFieldSchema, - PageBuilderConfigSchema: () => PageBuilderConfigSchema, - PanelContributionSchema: () => PanelContributionSchema, - PanelLocationSchema: () => PanelLocationSchema, - RelationshipDisplaySchema: () => RelationshipDisplaySchema, - RelationshipMapperConfigSchema: () => RelationshipMapperConfigSchema, - SidebarGroupContributionSchema: () => SidebarGroupContributionSchema, - StudioPluginContributionsSchema: () => StudioPluginContributionsSchema, - StudioPluginManifestSchema: () => StudioPluginManifestSchema, - ViewModeSchema: () => ViewModeSchema, - defineFlowBuilderConfig: () => defineFlowBuilderConfig, - defineObjectDesignerConfig: () => defineObjectDesignerConfig, - defineStudioPlugin: () => defineStudioPlugin -}); -var ViewModeSchema = external_exports.enum(["preview", "design", "code", "data"]); -var MetadataViewerContributionSchema = external_exports.object({ - /** Unique viewer ID (namespaced: `pluginId.viewerId`) */ - id: external_exports.string().describe("Unique viewer identifier"), - /** Metadata type(s) this viewer handles (e.g., "object", "flow", "agent") */ - metadataTypes: external_exports.array(external_exports.string()).min(1).describe("Metadata types this viewer can handle"), - /** Human-readable label shown in the view switcher */ - label: external_exports.string().describe("Viewer display label"), - /** Priority — highest-priority viewer becomes default. Built-in default = 0 */ - priority: external_exports.number().default(0).describe("Viewer priority (higher wins)"), - /** View modes this viewer supports */ - modes: external_exports.array(ViewModeSchema).default(["preview"]).describe("Supported view modes") -}); -var SidebarGroupContributionSchema = external_exports.object({ - /** Unique group key */ - key: external_exports.string().describe("Unique group key"), - /** Display label */ - label: external_exports.string().describe("Group display label"), - /** Lucide icon name (e.g., "database", "workflow") */ - icon: external_exports.string().optional().describe("Lucide icon name"), - /** Metadata types belonging to this group */ - metadataTypes: external_exports.array(external_exports.string()).describe("Metadata types in this group"), - /** Sort order — lower values appear first */ - order: external_exports.number().default(100).describe("Sort order (lower = higher)") -}); -var ActionLocationSchema = external_exports.enum(["toolbar", "contextMenu", "commandPalette"]); -var ActionContributionSchema = external_exports.object({ - /** Unique action ID */ - id: external_exports.string().describe("Unique action identifier"), - /** Display label */ - label: external_exports.string().describe("Action display label"), - /** Lucide icon name */ - icon: external_exports.string().optional().describe("Lucide icon name"), - /** Where this action appears */ - location: ActionLocationSchema.describe("UI location"), - /** Metadata types this action applies to (empty = all types) */ - metadataTypes: external_exports.array(external_exports.string()).default([]).describe("Applicable metadata types") -}); -var MetadataIconContributionSchema = external_exports.object({ - /** Metadata type this icon represents */ - metadataType: external_exports.string().describe("Metadata type"), - /** Human-readable label */ - label: external_exports.string().describe("Display label"), - /** Lucide icon name */ - icon: external_exports.string().describe("Lucide icon name") -}); -var PanelLocationSchema = external_exports.enum(["bottom", "right", "modal"]); -var PanelContributionSchema = external_exports.object({ - /** Unique panel ID */ - id: external_exports.string().describe("Unique panel identifier"), - /** Display label */ - label: external_exports.string().describe("Panel display label"), - /** Lucide icon name */ - icon: external_exports.string().optional().describe("Lucide icon name"), - /** Panel placement */ - location: PanelLocationSchema.default("bottom").describe("Panel location") -}); -var CommandContributionSchema = external_exports.object({ - /** Unique command ID (namespaced: `pluginId.commandName`) */ - id: external_exports.string().describe("Unique command identifier"), - /** Display label */ - label: external_exports.string().describe("Command display label"), - /** Keyboard shortcut (e.g., "Ctrl+Shift+P") */ - shortcut: external_exports.string().optional().describe("Keyboard shortcut"), - /** Lucide icon name */ - icon: external_exports.string().optional().describe("Lucide icon name") -}); -var StudioPluginContributionsSchema = external_exports.object({ - /** Metadata viewer/designer components */ - metadataViewers: external_exports.array(MetadataViewerContributionSchema).default([]), - /** Sidebar navigation groups */ - sidebarGroups: external_exports.array(SidebarGroupContributionSchema).default([]), - /** Toolbar / context menu / command palette actions */ - actions: external_exports.array(ActionContributionSchema).default([]), - /** Metadata type icons & labels */ - metadataIcons: external_exports.array(MetadataIconContributionSchema).default([]), - /** Auxiliary panels */ - panels: external_exports.array(PanelContributionSchema).default([]), - /** Command palette entries */ - commands: external_exports.array(CommandContributionSchema).default([]) -}); -var ActivationEventSchema22 = external_exports.string().describe("Activation event pattern"); -var StudioPluginManifestSchema = external_exports.object({ - /** - * Unique plugin ID using reverse-domain notation. - * @example "objectstack.object-designer" - */ - id: external_exports.string().regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)*$/).describe("Plugin ID (dot-separated lowercase)"), - /** Human-readable plugin name */ - name: external_exports.string().describe("Plugin display name"), - /** Semantic version */ - version: external_exports.string().default("0.0.1").describe("Plugin version"), - /** Plugin description */ - description: external_exports.string().optional().describe("Plugin description"), - /** Author name */ - author: external_exports.string().optional().describe("Author"), - /** Declarative contribution points */ - contributes: StudioPluginContributionsSchema.default({ - metadataViewers: [], - sidebarGroups: [], - actions: [], - metadataIcons: [], - panels: [], - commands: [] - }), - /** - * Activation events — when to load this plugin. - * Default `['*']` means eager activation. - */ - activationEvents: external_exports.array(ActivationEventSchema22).default(["*"]) -}); -function defineStudioPlugin(input) { - return StudioPluginManifestSchema.parse(input); -} -var FieldPropertySectionSchema = external_exports.object({ - /** Unique section key */ - key: external_exports.string().describe('Section key (e.g., "basics", "constraints", "security")'), - /** Display label */ - label: external_exports.string().describe("Section display label"), - /** Lucide icon name */ - icon: external_exports.string().optional().describe("Lucide icon name"), - /** Whether section is expanded by default */ - defaultExpanded: external_exports.boolean().default(true).describe("Whether section is expanded by default"), - /** Sort order — lower values appear first */ - order: external_exports.number().default(0).describe("Sort order (lower = higher)") -}); -var FieldGroupSchema = external_exports.object({ - /** Group key (matches field.group value) */ - key: external_exports.string().describe("Group key matching field.group values"), - /** Display label */ - label: external_exports.string().describe("Group display label"), - /** Lucide icon name */ - icon: external_exports.string().optional().describe("Lucide icon name"), - /** Whether group is expanded by default */ - defaultExpanded: external_exports.boolean().default(true).describe("Whether group is expanded by default"), - /** Sort order — lower values appear first */ - order: external_exports.number().default(0).describe("Sort order (lower = higher)") -}); -var FieldEditorConfigSchema = external_exports.object({ - /** Enable inline editing of field properties in the table */ - inlineEditing: external_exports.boolean().default(true).describe("Enable inline editing of field properties"), - /** Enable drag-and-drop field reordering */ - dragReorder: external_exports.boolean().default(true).describe("Enable drag-and-drop field reordering"), - /** Show field group headers for organizing fields */ - showFieldGroups: external_exports.boolean().default(true).describe("Show field group headers"), - /** Show the type-specific property panel on the right */ - showPropertyPanel: external_exports.boolean().default(true).describe("Show the right-side property panel"), - /** Default property panel sections to display */ - propertySections: external_exports.array(FieldPropertySectionSchema).default([ - { key: "basics", label: "Basic Properties", defaultExpanded: true, order: 0 }, - { key: "constraints", label: "Constraints & Validation", defaultExpanded: true, order: 10 }, - { key: "relationship", label: "Relationship Config", defaultExpanded: true, order: 20 }, - { key: "display", label: "Display & UI", defaultExpanded: false, order: 30 }, - { key: "security", label: "Security & Compliance", defaultExpanded: false, order: 40 }, - { key: "advanced", label: "Advanced", defaultExpanded: false, order: 50 } - ]).describe("Property panel section definitions"), - /** Field groups for organizing fields in the editor */ - fieldGroups: external_exports.array(FieldGroupSchema).default([]).describe("Field group definitions"), - /** Maximum fields before pagination kicks in */ - paginationThreshold: external_exports.number().default(50).describe("Number of fields before pagination is enabled"), - /** Enable batch field operations (add multiple fields at once) */ - batchOperations: external_exports.boolean().default(true).describe("Enable batch add/remove field operations"), - /** Show field usage statistics (views, formulas, relationships referencing this field) */ - showUsageStats: external_exports.boolean().default(false).describe("Show field usage statistics") -}); -var RelationshipDisplaySchema = external_exports.object({ - /** Relationship type to configure */ - type: external_exports.enum(["lookup", "master_detail", "tree"]).describe("Relationship type"), - /** Line style for this relationship type */ - lineStyle: external_exports.enum(["solid", "dashed", "dotted"]).default("solid").describe("Line style in diagrams"), - /** Line color (CSS color value) */ - color: external_exports.string().default("#94a3b8").describe("Line color (CSS value)"), - /** Highlighted color on hover/select */ - highlightColor: external_exports.string().default("#0891b2").describe("Highlighted color on hover/select"), - /** Cardinality label to display */ - cardinalityLabel: external_exports.string().default("1:N").describe('Cardinality label (e.g., "1:N", "1:1", "N:M")') -}); -var RelationshipMapperConfigSchema = external_exports.object({ - /** Enable visual relationship creation (drag from source to target) */ - visualCreation: external_exports.boolean().default(true).describe("Enable drag-to-create relationships"), - /** Show reverse relationships (child → parent) */ - showReverseRelationships: external_exports.boolean().default(true).describe("Show reverse/child-to-parent relationships"), - /** Show cascade delete warnings */ - showCascadeWarnings: external_exports.boolean().default(true).describe("Show cascade delete behavior warnings"), - /** Relationship display configuration by type */ - displayConfig: external_exports.array(RelationshipDisplaySchema).default([ - { type: "lookup", lineStyle: "dashed", color: "#0891b2", highlightColor: "#06b6d4", cardinalityLabel: "1:N" }, - { type: "master_detail", lineStyle: "solid", color: "#ea580c", highlightColor: "#f97316", cardinalityLabel: "1:N" }, - { type: "tree", lineStyle: "dotted", color: "#8b5cf6", highlightColor: "#a78bfa", cardinalityLabel: "1:N" } - ]).describe("Visual config per relationship type") -}); -var ERLayoutAlgorithmSchema = external_exports.enum([ - "force", - // Force-directed graph (natural clustering) - "hierarchy", - // Top-down hierarchy (master → detail) - "grid", - // Uniform grid layout - "circular" - // Circular arrangement -]).describe("ER diagram layout algorithm"); -var ERNodeDisplaySchema = external_exports.object({ - /** Show field list within the node */ - showFields: external_exports.boolean().default(true).describe("Show field list inside entity nodes"), - /** Maximum fields to show before collapsing (0 = no limit) */ - maxFieldsVisible: external_exports.number().default(8).describe('Max fields visible before "N more..." collapse'), - /** Show field types alongside field names */ - showFieldTypes: external_exports.boolean().default(true).describe("Show field type badges"), - /** Show required field indicators */ - showRequiredIndicator: external_exports.boolean().default(true).describe("Show required field indicators"), - /** Show record count on each node (requires data access) */ - showRecordCount: external_exports.boolean().default(false).describe("Show live record count on nodes"), - /** Show object icon */ - showIcon: external_exports.boolean().default(true).describe("Show object icon on node header"), - /** Show object description on hover tooltip */ - showDescription: external_exports.boolean().default(true).describe("Show description tooltip on hover") -}); -var ERDiagramConfigSchema = external_exports.object({ - /** Enable the ER diagram panel */ - enabled: external_exports.boolean().default(true).describe("Enable ER diagram panel"), - /** Default layout algorithm */ - layout: ERLayoutAlgorithmSchema.default("force").describe("Default layout algorithm"), - /** Node display options */ - nodeDisplay: ERNodeDisplaySchema.default({ - showFields: true, - maxFieldsVisible: 8, - showFieldTypes: true, - showRequiredIndicator: true, - showRecordCount: false, - showIcon: true, - showDescription: true - }).describe("Node display configuration"), - /** Show minimap for navigation */ - showMinimap: external_exports.boolean().default(true).describe("Show minimap for large diagrams"), - /** Enable zoom controls */ - zoomControls: external_exports.boolean().default(true).describe("Show zoom in/out/fit controls"), - /** Minimum zoom level */ - minZoom: external_exports.number().default(0.1).describe("Minimum zoom level"), - /** Maximum zoom level */ - maxZoom: external_exports.number().default(3).describe("Maximum zoom level"), - /** Show relationship labels (cardinality) on edges */ - showEdgeLabels: external_exports.boolean().default(true).describe("Show cardinality labels on relationship edges"), - /** Highlight connected entities on hover */ - highlightOnHover: external_exports.boolean().default(true).describe("Highlight connected entities on node hover"), - /** Click behavior: navigate to object designer */ - clickToNavigate: external_exports.boolean().default(true).describe("Click node to navigate to object detail"), - /** Enable drag-and-drop to create relationships */ - dragToConnect: external_exports.boolean().default(true).describe("Drag between nodes to create relationships"), - /** Filter to show only objects with relationships (hide orphans) */ - hideOrphans: external_exports.boolean().default(false).describe("Hide objects with no relationships"), - /** Auto-fit diagram to viewport on initial load */ - autoFit: external_exports.boolean().default(true).describe("Auto-fit diagram to viewport on load"), - /** Export diagram options */ - exportFormats: external_exports.array(external_exports.enum(["png", "svg", "json"])).default(["png", "svg"]).describe("Available export formats for diagram") -}); -var ObjectListDisplayModeSchema = external_exports.enum([ - "table", - // Traditional table with columns - "cards", - // Card grid (visual overview) - "tree" - // Hierarchical tree (grouped by package/namespace) -]).describe("Object list display mode"); -var ObjectSortFieldSchema = external_exports.enum([ - "name", - // Sort by API name - "label", - // Sort by display label - "fieldCount", - // Sort by number of fields - "updatedAt" - // Sort by last modified -]).describe("Object list sort field"); -var ObjectFilterSchema = external_exports.object({ - /** Filter by package/namespace */ - package: external_exports.string().optional().describe("Filter by owning package"), - /** Filter by tags */ - tags: external_exports.array(external_exports.string()).optional().describe("Filter by object tags"), - /** Show system objects */ - includeSystem: external_exports.boolean().default(true).describe("Include system-level objects"), - /** Show abstract objects */ - includeAbstract: external_exports.boolean().default(false).describe("Include abstract base objects"), - /** Show only objects with specific field types */ - hasFieldType: external_exports.string().optional().describe("Filter to objects containing a specific field type"), - /** Show only objects with relationships */ - hasRelationships: external_exports.boolean().optional().describe("Filter to objects with lookup/master_detail fields"), - /** Text search across name, label, description */ - searchQuery: external_exports.string().optional().describe("Free-text search across name, label, and description") -}); -var ObjectManagerConfigSchema = external_exports.object({ - /** Default display mode */ - defaultDisplayMode: ObjectListDisplayModeSchema.default("table").describe("Default list display mode"), - /** Default sort field */ - defaultSortField: ObjectSortFieldSchema.default("label").describe("Default sort field"), - /** Default sort direction */ - defaultSortDirection: external_exports.enum(["asc", "desc"]).default("asc").describe("Default sort direction"), - /** Default filters */ - defaultFilter: ObjectFilterSchema.default({ - includeSystem: true, - includeAbstract: false - }).describe("Default filter configuration"), - /** Show field count badge on each object row */ - showFieldCount: external_exports.boolean().default(true).describe("Show field count badge"), - /** Show relationship count badge */ - showRelationshipCount: external_exports.boolean().default(true).describe("Show relationship count badge"), - /** Show quick-preview tooltip with field list on hover */ - showQuickPreview: external_exports.boolean().default(true).describe("Show quick field preview tooltip on hover"), - /** Enable object comparison (diff two objects side-by-side) */ - enableComparison: external_exports.boolean().default(false).describe("Enable side-by-side object comparison"), - /** Show ER diagram toggle button in the toolbar */ - showERDiagramToggle: external_exports.boolean().default(true).describe("Show ER diagram toggle in toolbar"), - /** Show "Create Object" quick action */ - showCreateAction: external_exports.boolean().default(true).describe("Show create object action"), - /** Show object statistics summary bar (total objects, fields, relationships) */ - showStatsSummary: external_exports.boolean().default(true).describe("Show statistics summary bar") -}); -var ObjectPreviewTabSchema = external_exports.object({ - /** Tab key */ - key: external_exports.string().describe("Tab key"), - /** Tab display label */ - label: external_exports.string().describe("Tab display label"), - /** Lucide icon name */ - icon: external_exports.string().optional().describe("Lucide icon name"), - /** Whether this tab is enabled */ - enabled: external_exports.boolean().default(true).describe("Whether this tab is available"), - /** Sort order */ - order: external_exports.number().default(0).describe("Sort order (lower = higher)") -}); -var ObjectPreviewConfigSchema = external_exports.object({ - /** Tabs to show in the object detail view */ - tabs: external_exports.array(ObjectPreviewTabSchema).default([ - { key: "fields", label: "Fields", icon: "list", enabled: true, order: 0 }, - { key: "relationships", label: "Relationships", icon: "link", enabled: true, order: 10 }, - { key: "indexes", label: "Indexes", icon: "zap", enabled: true, order: 20 }, - { key: "validations", label: "Validations", icon: "shield-check", enabled: true, order: 30 }, - { key: "capabilities", label: "Capabilities", icon: "settings", enabled: true, order: 40 }, - { key: "data", label: "Data", icon: "table-2", enabled: true, order: 50 }, - { key: "api", label: "API", icon: "globe", enabled: true, order: 60 }, - { key: "code", label: "Code", icon: "code-2", enabled: true, order: 70 } - ]).describe("Object detail preview tabs"), - /** Default active tab */ - defaultTab: external_exports.string().default("fields").describe("Default active tab key"), - /** Show object header with summary info */ - showHeader: external_exports.boolean().default(true).describe("Show object summary header"), - /** Show breadcrumbs */ - showBreadcrumbs: external_exports.boolean().default(true).describe("Show navigation breadcrumbs") -}); -var ObjectDesignerDefaultViewSchema = external_exports.enum([ - "field-editor", - // Field table editor (default) - "relationship-mapper", - // Visual relationship view - "er-diagram", - // Full ER diagram - "object-manager" - // Object list/manager -]).describe("Default view when entering the Object Designer"); -var ObjectDesignerConfigSchema = external_exports.object({ - /** Default view when opening the designer */ - defaultView: ObjectDesignerDefaultViewSchema.default("field-editor").describe("Default view"), - /** Field editor configuration */ - fieldEditor: FieldEditorConfigSchema.default({ - inlineEditing: true, - dragReorder: true, - showFieldGroups: true, - showPropertyPanel: true, - propertySections: [ - { key: "basics", label: "Basic Properties", defaultExpanded: true, order: 0 }, - { key: "constraints", label: "Constraints & Validation", defaultExpanded: true, order: 10 }, - { key: "relationship", label: "Relationship Config", defaultExpanded: true, order: 20 }, - { key: "display", label: "Display & UI", defaultExpanded: false, order: 30 }, - { key: "security", label: "Security & Compliance", defaultExpanded: false, order: 40 }, - { key: "advanced", label: "Advanced", defaultExpanded: false, order: 50 } - ], - fieldGroups: [], - paginationThreshold: 50, - batchOperations: true, - showUsageStats: false - }).describe("Field editor configuration"), - /** Relationship mapper configuration */ - relationshipMapper: RelationshipMapperConfigSchema.default({ - visualCreation: true, - showReverseRelationships: true, - showCascadeWarnings: true, - displayConfig: [ - { type: "lookup", lineStyle: "dashed", color: "#0891b2", highlightColor: "#06b6d4", cardinalityLabel: "1:N" }, - { type: "master_detail", lineStyle: "solid", color: "#ea580c", highlightColor: "#f97316", cardinalityLabel: "1:N" }, - { type: "tree", lineStyle: "dotted", color: "#8b5cf6", highlightColor: "#a78bfa", cardinalityLabel: "1:N" } - ] - }).describe("Relationship mapper configuration"), - /** ER diagram configuration */ - erDiagram: ERDiagramConfigSchema.default({ - enabled: true, - layout: "force", - nodeDisplay: { - showFields: true, - maxFieldsVisible: 8, - showFieldTypes: true, - showRequiredIndicator: true, - showRecordCount: false, - showIcon: true, - showDescription: true - }, - showMinimap: true, - zoomControls: true, - minZoom: 0.1, - maxZoom: 3, - showEdgeLabels: true, - highlightOnHover: true, - clickToNavigate: true, - dragToConnect: true, - hideOrphans: false, - autoFit: true, - exportFormats: ["png", "svg"] - }).describe("ER diagram configuration"), - /** Object manager configuration */ - objectManager: ObjectManagerConfigSchema.default({ - defaultDisplayMode: "table", - defaultSortField: "label", - defaultSortDirection: "asc", - defaultFilter: { - includeSystem: true, - includeAbstract: false - }, - showFieldCount: true, - showRelationshipCount: true, - showQuickPreview: true, - enableComparison: false, - showERDiagramToggle: true, - showCreateAction: true, - showStatsSummary: true - }).describe("Object manager configuration"), - /** Object preview configuration */ - objectPreview: ObjectPreviewConfigSchema.default({ - tabs: [ - { key: "fields", label: "Fields", icon: "list", enabled: true, order: 0 }, - { key: "relationships", label: "Relationships", icon: "link", enabled: true, order: 10 }, - { key: "indexes", label: "Indexes", icon: "zap", enabled: true, order: 20 }, - { key: "validations", label: "Validations", icon: "shield-check", enabled: true, order: 30 }, - { key: "capabilities", label: "Capabilities", icon: "settings", enabled: true, order: 40 }, - { key: "data", label: "Data", icon: "table-2", enabled: true, order: 50 }, - { key: "api", label: "API", icon: "globe", enabled: true, order: 60 }, - { key: "code", label: "Code", icon: "code-2", enabled: true, order: 70 } - ], - defaultTab: "fields", - showHeader: true, - showBreadcrumbs: true - }).describe("Object preview configuration") -}); -function defineObjectDesignerConfig(input) { - return ObjectDesignerConfigSchema.parse(input); -} -var CanvasSnapSettingsSchema = external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable snap-to-grid"), - gridSize: external_exports.number().int().min(1).default(8).describe("Snap grid size in pixels"), - showGrid: external_exports.boolean().default(true).describe("Show grid overlay on canvas"), - showGuides: external_exports.boolean().default(true).describe("Show alignment guides when dragging") -}); -var CanvasZoomSettingsSchema = external_exports.object({ - min: external_exports.number().min(0.1).default(0.25).describe("Minimum zoom level"), - max: external_exports.number().max(10).default(3).describe("Maximum zoom level"), - default: external_exports.number().default(1).describe("Default zoom level"), - step: external_exports.number().default(0.1).describe("Zoom step increment") -}); -var ElementPaletteItemSchema = external_exports.object({ - type: external_exports.string().describe('Component type (e.g. "element:button", "element:text")'), - label: external_exports.string().describe("Display label in palette"), - icon: external_exports.string().optional().describe("Icon name for palette display"), - category: external_exports.enum(["content", "interactive", "data", "layout"]).describe("Palette category grouping"), - defaultWidth: external_exports.number().int().min(1).default(4).describe("Default width in grid columns"), - defaultHeight: external_exports.number().int().min(1).default(2).describe("Default height in grid rows") -}); -var PageBuilderConfigSchema = external_exports.object({ - snap: CanvasSnapSettingsSchema.optional().describe("Canvas snap settings"), - zoom: CanvasZoomSettingsSchema.optional().describe("Canvas zoom settings"), - palette: external_exports.array(ElementPaletteItemSchema).optional().describe("Custom element palette (defaults to all registered elements)"), - showLayerPanel: external_exports.boolean().default(true).describe("Show layer ordering panel"), - showPropertyPanel: external_exports.boolean().default(true).describe("Show property inspector panel"), - undoLimit: external_exports.number().int().min(1).default(50).describe("Maximum undo history steps") -}); -var InterfaceBuilderConfigSchema = PageBuilderConfigSchema; -var FlowNodeShapeSchema = external_exports.enum([ - "rounded_rect", - // Default activity shape (assignments, CRUD, HTTP, script, subflow) - "circle", - // Start / End events - "diamond", - // Decision (XOR gateway) - "parallelogram", - // Loop / iteration - "hexagon", - // Wait / timer event - "diamond_thick", - // Parallel gateway (AND-split) & Join gateway (AND-join) - "attached_circle", - // Boundary event (attached to host node) - "screen_rect" - // Screen / user-interaction node -]).describe("Visual shape for rendering a flow node on the canvas"); -var FlowNodeRenderDescriptorSchema = external_exports.object({ - /** The node action type this descriptor applies to */ - action: external_exports.string().describe('FlowNodeAction value (e.g., "parallel_gateway")'), - /** Visual shape on the canvas */ - shape: FlowNodeShapeSchema.describe("Shape to render"), - /** Lucide icon name displayed inside the node */ - icon: external_exports.string().describe("Lucide icon name"), - /** Default label shown on the node when no user label is set */ - defaultLabel: external_exports.string().describe("Default display label"), - /** Default width in canvas pixels */ - defaultWidth: external_exports.number().int().min(20).default(120).describe("Default width in pixels"), - /** Default height in canvas pixels */ - defaultHeight: external_exports.number().int().min(20).default(60).describe("Default height in pixels"), - /** CSS color for the node fill */ - fillColor: external_exports.string().default("#ffffff").describe("Node fill color (CSS value)"), - /** CSS color for the node border */ - borderColor: external_exports.string().default("#94a3b8").describe("Node border color (CSS value)"), - /** Whether this node type can have boundary events attached */ - allowBoundaryEvents: external_exports.boolean().default(false).describe("Whether boundary events can be attached to this node type"), - /** Category for palette grouping */ - paletteCategory: external_exports.enum(["event", "gateway", "activity", "data", "subflow"]).describe("Palette category for grouping") -}).describe("Visual render descriptor for a flow node type"); -var FlowCanvasNodeSchema = external_exports.object({ - /** Reference to the flow node id */ - nodeId: external_exports.string().describe("Corresponding FlowNode.id"), - /** X position on the canvas (pixels) */ - x: external_exports.number().describe("X position on canvas"), - /** Y position on the canvas (pixels) */ - y: external_exports.number().describe("Y position on canvas"), - /** Width override (pixels, optional — uses descriptor default) */ - width: external_exports.number().int().min(20).optional().describe("Width override in pixels"), - /** Height override (pixels, optional — uses descriptor default) */ - height: external_exports.number().int().min(20).optional().describe("Height override in pixels"), - /** Whether the node is collapsed (hides internal details) */ - collapsed: external_exports.boolean().default(false).describe("Whether the node is collapsed"), - /** Custom fill color override */ - fillColor: external_exports.string().optional().describe("Fill color override"), - /** Custom border color override */ - borderColor: external_exports.string().optional().describe("Border color override"), - /** User-defined comment/annotation visible on canvas */ - annotation: external_exports.string().optional().describe("User annotation displayed near the node") -}).describe("Canvas layout data for a flow node"); -var FlowCanvasEdgeStyleSchema = external_exports.enum([ - "solid", - // Normal sequence flow - "dashed", - // Default sequence flow (isDefault: true) - "dotted", - // Conditional edge - "bold" - // Fault / error edge -]).describe("Edge line style"); -var FlowCanvasEdgeSchema = external_exports.object({ - /** Reference to the flow edge id */ - edgeId: external_exports.string().describe("Corresponding FlowEdge.id"), - /** Line style */ - style: FlowCanvasEdgeStyleSchema.default("solid").describe("Line style"), - /** Line color (CSS value) */ - color: external_exports.string().default("#94a3b8").describe("Edge line color"), - /** Label position along the edge (0–1, 0.5 = midpoint) */ - labelPosition: external_exports.number().min(0).max(1).default(0.5).describe("Position of the condition label along the edge"), - /** Optional waypoints for routing the edge around nodes */ - waypoints: external_exports.array(external_exports.object({ - x: external_exports.number().describe("Waypoint X"), - y: external_exports.number().describe("Waypoint Y") - })).optional().describe("Manual waypoints for edge routing"), - /** Whether to show an animated flow indicator */ - animated: external_exports.boolean().default(false).describe("Show animated flow indicator") -}).describe("Canvas layout and visual data for a flow edge"); -var FlowLayoutAlgorithmSchema = external_exports.enum([ - "dagre", - // Directed acyclic graph layout (top-down or left-right) - "elk", - // Eclipse Layout Kernel (advanced hierarchical) - "force", - // Force-directed graph - "manual" - // User-positioned (no auto-layout) -]).describe("Auto-layout algorithm for the flow canvas"); -var FlowLayoutDirectionSchema = external_exports.enum([ - "TB", - // Top to bottom - "BT", - // Bottom to top - "LR", - // Left to right - "RL" - // Right to left -]).describe("Auto-layout direction"); -var FlowBuilderConfigSchema = external_exports.object({ - /** Canvas snap settings */ - snap: external_exports.object({ - enabled: external_exports.boolean().default(true).describe("Enable snap-to-grid"), - gridSize: external_exports.number().int().min(1).default(16).describe("Snap grid size in pixels"), - showGrid: external_exports.boolean().default(true).describe("Show grid overlay") - }).default({ enabled: true, gridSize: 16, showGrid: true }).describe("Canvas snap-to-grid settings"), - /** Canvas zoom settings */ - zoom: external_exports.object({ - min: external_exports.number().min(0.1).default(0.25).describe("Minimum zoom level"), - max: external_exports.number().max(10).default(3).describe("Maximum zoom level"), - default: external_exports.number().default(1).describe("Default zoom level"), - step: external_exports.number().default(0.1).describe("Zoom step") - }).default({ min: 0.25, max: 3, default: 1, step: 0.1 }).describe("Canvas zoom settings"), - /** Auto-layout algorithm */ - layoutAlgorithm: FlowLayoutAlgorithmSchema.default("dagre").describe("Default auto-layout algorithm"), - /** Auto-layout direction */ - layoutDirection: FlowLayoutDirectionSchema.default("TB").describe("Default auto-layout direction"), - /** Node render descriptors (override defaults per node type) */ - nodeDescriptors: external_exports.array(FlowNodeRenderDescriptorSchema).optional().describe("Custom node render descriptors (merged with built-in defaults)"), - /** Show minimap for navigation */ - showMinimap: external_exports.boolean().default(true).describe("Show minimap panel"), - /** Show the node property panel */ - showPropertyPanel: external_exports.boolean().default(true).describe("Show property panel"), - /** Show the node palette sidebar */ - showPalette: external_exports.boolean().default(true).describe("Show node palette sidebar"), - /** Maximum undo history steps */ - undoLimit: external_exports.number().int().min(1).default(50).describe("Maximum undo history steps"), - /** Enable edge animation during execution preview */ - animateExecution: external_exports.boolean().default(true).describe("Animate edges during execution preview"), - /** Connection validation — prevent invalid edges (e.g., duplicate, self-loop) */ - connectionValidation: external_exports.boolean().default(true).describe("Validate connections before creating edges") -}).describe("Studio Flow Builder configuration"); -var BUILT_IN_NODE_DESCRIPTORS = [ - { action: "start", shape: "circle", icon: "play", defaultLabel: "Start", defaultWidth: 60, defaultHeight: 60, fillColor: "#dcfce7", borderColor: "#16a34a", allowBoundaryEvents: false, paletteCategory: "event" }, - { action: "end", shape: "circle", icon: "square", defaultLabel: "End", defaultWidth: 60, defaultHeight: 60, fillColor: "#fee2e2", borderColor: "#dc2626", allowBoundaryEvents: false, paletteCategory: "event" }, - { action: "decision", shape: "diamond", icon: "git-branch", defaultLabel: "Decision", defaultWidth: 80, defaultHeight: 80, fillColor: "#fef9c3", borderColor: "#ca8a04", allowBoundaryEvents: false, paletteCategory: "gateway" }, - { action: "parallel_gateway", shape: "diamond_thick", icon: "git-fork", defaultLabel: "Parallel Gateway", defaultWidth: 80, defaultHeight: 80, fillColor: "#dbeafe", borderColor: "#2563eb", allowBoundaryEvents: false, paletteCategory: "gateway" }, - { action: "join_gateway", shape: "diamond_thick", icon: "git-merge", defaultLabel: "Join Gateway", defaultWidth: 80, defaultHeight: 80, fillColor: "#dbeafe", borderColor: "#2563eb", allowBoundaryEvents: false, paletteCategory: "gateway" }, - { action: "wait", shape: "hexagon", icon: "clock", defaultLabel: "Wait", defaultWidth: 100, defaultHeight: 60, fillColor: "#f3e8ff", borderColor: "#7c3aed", allowBoundaryEvents: true, paletteCategory: "event" }, - { action: "boundary_event", shape: "attached_circle", icon: "alert-circle", defaultLabel: "Boundary Event", defaultWidth: 40, defaultHeight: 40, fillColor: "#fff7ed", borderColor: "#ea580c", allowBoundaryEvents: false, paletteCategory: "event" }, - { action: "assignment", shape: "rounded_rect", icon: "pen-line", defaultLabel: "Assignment", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "activity" }, - { action: "create_record", shape: "rounded_rect", icon: "plus-circle", defaultLabel: "Create Record", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "data" }, - { action: "update_record", shape: "rounded_rect", icon: "edit", defaultLabel: "Update Record", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "data" }, - { action: "delete_record", shape: "rounded_rect", icon: "trash-2", defaultLabel: "Delete Record", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "data" }, - { action: "get_record", shape: "rounded_rect", icon: "search", defaultLabel: "Get Record", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "data" }, - { action: "http_request", shape: "rounded_rect", icon: "globe", defaultLabel: "HTTP Request", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "activity" }, - { action: "script", shape: "rounded_rect", icon: "code", defaultLabel: "Script", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "activity" }, - { action: "screen", shape: "screen_rect", icon: "monitor", defaultLabel: "Screen", defaultWidth: 140, defaultHeight: 80, fillColor: "#f0f9ff", borderColor: "#0284c7", allowBoundaryEvents: false, paletteCategory: "activity" }, - { action: "loop", shape: "parallelogram", icon: "repeat", defaultLabel: "Loop", defaultWidth: 120, defaultHeight: 60, fillColor: "#fef3c7", borderColor: "#d97706", allowBoundaryEvents: true, paletteCategory: "activity" }, - { action: "subflow", shape: "rounded_rect", icon: "layers", defaultLabel: "Subflow", defaultWidth: 140, defaultHeight: 70, fillColor: "#ede9fe", borderColor: "#7c3aed", allowBoundaryEvents: true, paletteCategory: "subflow" }, - { action: "connector_action", shape: "rounded_rect", icon: "plug", defaultLabel: "Connector", defaultWidth: 120, defaultHeight: 60, fillColor: "#ffffff", borderColor: "#94a3b8", allowBoundaryEvents: true, paletteCategory: "activity" } -]; -function defineFlowBuilderConfig(input) { - return FlowBuilderConfigSchema.parse(input); -} -var ObjectStackDefinitionSchema = external_exports.object({ - /** System Configuration */ - manifest: ManifestSchema3.optional().describe("Project Package Configuration"), - datasources: external_exports.array(DatasourceSchema2).optional().describe("External Data Connections"), - translations: external_exports.array(TranslationBundleSchema2).optional().describe("I18n Translation Bundles"), - i18n: TranslationConfigSchema2.optional().describe("Internationalization configuration"), - /** - * ObjectQL: Data Layer - * All business objects and entities. - */ - objects: external_exports.array(ObjectSchema4).optional().describe("Business Objects definition (owned by this package)"), - /** - * Object Extensions: fields/config to merge into objects owned by other packages. - * Use this instead of redefining an object when you want to add fields to - * an existing object from another package. - * - * @example - * ```ts - * objectExtensions: [{ - * extend: 'contact', - * fields: { sales_stage: Field.select([...]) }, - * }] - * ``` - */ - objectExtensions: external_exports.array(ObjectExtensionSchema2).optional().describe("Extensions to objects owned by other packages"), - /** - * ObjectUI: User Interface Layer - * Apps, Menus, Pages, and Visualizations. - */ - apps: external_exports.array(AppSchema3).optional().describe("Applications"), - views: external_exports.array(ViewSchema3).optional().describe("List Views"), - pages: external_exports.array(PageSchema2).optional().describe("Custom Pages"), - dashboards: external_exports.array(DashboardSchema2).optional().describe("Dashboards"), - reports: external_exports.array(ReportSchema2).optional().describe("Analytics Reports"), - actions: external_exports.array(ActionSchema5).optional().describe("Global and Object Actions"), - themes: external_exports.array(ThemeSchema2).optional().describe("UI Themes"), - /** - * ObjectFlow: Automation Layer - * Business logic, approvals, and workflows. - */ - workflows: external_exports.array(WorkflowRuleSchema2).optional().describe("Event-driven workflows"), - approvals: external_exports.array(ApprovalProcessSchema).optional().describe("Approval processes"), - flows: external_exports.array(FlowSchema2).optional().describe("Screen Flows"), - /** - * ObjectGuard: Security Layer - */ - roles: external_exports.array(RoleSchema).optional().describe("User Roles hierarchy"), - permissions: external_exports.array(PermissionSetSchema2).optional().describe("Permission Sets and Profiles"), - sharingRules: external_exports.array(SharingRuleSchema).optional().describe("Record Sharing Rules"), - policies: external_exports.array(PolicySchema).optional().describe("Security & Compliance Policies"), - /** - * ObjectAPI: API Layer - */ - apis: external_exports.array(ApiEndpointSchema2).optional().describe("API Endpoints"), - webhooks: external_exports.array(WebhookSchema).optional().describe("Outbound Webhooks"), - /** - * ObjectAI: Artificial Intelligence Layer - */ - agents: external_exports.array(AgentSchema).optional().describe("AI Agents and Assistants"), - ragPipelines: external_exports.array(RAGPipelineConfigSchema).optional().describe("RAG Pipelines"), - /** - * ObjectQL: Data Extensions - * Hooks, mappings, and analytics cubes. - */ - hooks: external_exports.array(HookSchema2).optional().describe("Object Lifecycle Hooks"), - mappings: external_exports.array(MappingSchema2).optional().describe("Data Import/Export Mappings"), - analyticsCubes: external_exports.array(CubeSchema3).optional().describe("Analytics Semantic Layer Cubes"), - /** - * Integration Protocol - */ - connectors: external_exports.array(ConnectorSchema2).optional().describe("External System Connectors"), - /** - * Data Seeding Protocol - * - * Declarative seed data for bootstrapping, demos, and testing. - * Each entry targets a specific object and provides records to load - * using the specified conflict resolution strategy. - * - * Uses the standard DatasetSchema which supports: - * - `externalId`: Idempotency key for upsert matching (default: 'name') - * - `mode`: Conflict resolution (upsert, insert, ignore, replace) - * - `env`: Environment scoping (prod, dev, test) - * - * @example - * ```ts - * data: [ - * { - * object: 'account', - * mode: 'upsert', - * externalId: 'name', - * records: [ - * { name: 'Acme Corp', type: 'customer', industry: 'technology' }, - * ] - * } - * ] - * ``` - */ - data: external_exports.array(DatasetSchema4).optional().describe("Seed Data / Fixtures for bootstrapping"), - /** - * Plugins: External Capabilities - * List of plugins to load. Can be a Manifest object, a package name string, or a Runtime Plugin instance. - */ - plugins: external_exports.array(external_exports.unknown()).optional().describe("Plugins to load"), - /** - * DevPlugins: Development Capabilities - * List of plugins to load ONLY in development environment. - * Equivalent to `devDependencies` in package.json. - * Useful for loading dev-tools, mock data generators, or referencing local sibling packages for debugging. - */ - devPlugins: external_exports.array(external_exports.union([ManifestSchema3, external_exports.string()])).optional().describe("Plugins to load only in development (CLI dev command)") -}); -function collectObjectNames(config4) { - const names = /* @__PURE__ */ new Set(); - if (config4.objects) { - for (const obj of config4.objects) { - names.add(obj.name); - } - } - return names; -} -function validateCrossReferences(config4) { - const errors = []; - const objectNames = collectObjectNames(config4); - if (objectNames.size === 0) return errors; - if (config4.workflows) { - for (const workflow of config4.workflows) { - if (workflow.objectName && !objectNames.has(workflow.objectName)) { - errors.push( - `Workflow '${workflow.name}' references object '${workflow.objectName}' which is not defined in objects.` - ); - } - } - } - if (config4.approvals) { - for (const approval of config4.approvals) { - if (approval.object && !objectNames.has(approval.object)) { - errors.push( - `Approval '${approval.name}' references object '${approval.object}' which is not defined in objects.` - ); - } - } - } - if (config4.hooks) { - for (const hook of config4.hooks) { - if (hook.object) { - const hookObjects = Array.isArray(hook.object) ? hook.object : [hook.object]; - for (const obj of hookObjects) { - if (!objectNames.has(obj)) { - errors.push( - `Hook '${hook.name}' references object '${obj}' which is not defined in objects.` - ); - } - } - } - } - } - if (config4.views) { - for (const [i, view] of config4.views.entries()) { - const checkViewData = (data, viewLabel) => { - if (data && typeof data === "object" && "provider" in data && "object" in data) { - const d = data; - if (d.provider === "object" && d.object && !objectNames.has(d.object)) { - errors.push( - `${viewLabel} references object '${d.object}' which is not defined in objects.` - ); - } - } - }; - if (view.list?.data) { - checkViewData(view.list.data, `View[${i}].list`); - } - if (view.form?.data) { - checkViewData(view.form.data, `View[${i}].form`); - } - } - } - if (config4.data) { - for (const dataset of config4.data) { - if (dataset.object && !objectNames.has(dataset.object)) { - errors.push( - `Seed data references object '${dataset.object}' which is not defined in objects.` - ); - } - } - } - if (config4.apps) { - const dashboardNames = /* @__PURE__ */ new Set(); - if (config4.dashboards) { - for (const d of config4.dashboards) { - dashboardNames.add(d.name); - } - } - const pageNames = /* @__PURE__ */ new Set(); - if (config4.pages) { - for (const p of config4.pages) { - pageNames.add(p.name); - } - } - const reportNames = /* @__PURE__ */ new Set(); - if (config4.reports) { - for (const r of config4.reports) { - reportNames.add(r.name); - } - } - for (const app of config4.apps) { - if (!app.navigation) continue; - const checkNavItems = (items, appName) => { - for (const item of items) { - if (!item || typeof item !== "object") continue; - const nav = item; - if (nav.type === "object" && typeof nav.objectName === "string" && !objectNames.has(nav.objectName)) { - errors.push( - `App '${appName}' navigation references object '${nav.objectName}' which is not defined in objects.` - ); - } - if (nav.type === "dashboard" && typeof nav.dashboardName === "string" && dashboardNames.size > 0 && !dashboardNames.has(nav.dashboardName)) { - errors.push( - `App '${appName}' navigation references dashboard '${nav.dashboardName}' which is not defined in dashboards.` - ); - } - if (nav.type === "page" && typeof nav.pageName === "string" && pageNames.size > 0 && !pageNames.has(nav.pageName)) { - errors.push( - `App '${appName}' navigation references page '${nav.pageName}' which is not defined in pages.` - ); - } - if (nav.type === "report" && typeof nav.reportName === "string" && reportNames.size > 0 && !reportNames.has(nav.reportName)) { - errors.push( - `App '${appName}' navigation references report '${nav.reportName}' which is not defined in reports.` - ); - } - if (nav.type === "group" && Array.isArray(nav.children)) { - checkNavItems(nav.children, appName); - } - } - }; - checkNavItems(app.navigation, app.name); - } - } - if (config4.actions) { - const flowNames = /* @__PURE__ */ new Set(); - if (config4.flows) { - for (const flow of config4.flows) { - flowNames.add(flow.name); - } - } - const pageNames = /* @__PURE__ */ new Set(); - if (config4.pages) { - for (const page of config4.pages) { - pageNames.add(page.name); - } - } - for (const action of config4.actions) { - if (action.type === "flow" && action.target && flowNames.size > 0 && !flowNames.has(action.target)) { - errors.push( - `Action '${action.name}' references flow '${action.target}' which is not defined in flows.` - ); - } - if (action.type === "modal" && action.target && pageNames.size > 0 && !pageNames.has(action.target)) { - errors.push( - `Action '${action.name}' references page '${action.target}' (via modal target) which is not defined in pages.` - ); - } - if (action.objectName && !objectNames.has(action.objectName)) { - errors.push( - `Action '${action.name}' references object '${action.objectName}' which is not defined in objects.` - ); - } - } - } - return errors; -} -function mergeActionsIntoObjects(config4) { - if (!config4.actions || !config4.objects || config4.objects.length === 0) { - return config4; - } - const actionsByObject = /* @__PURE__ */ new Map(); - for (const action of config4.actions) { - if (action.objectName) { - const list = actionsByObject.get(action.objectName) ?? []; - list.push(action); - actionsByObject.set(action.objectName, list); - } - } - if (actionsByObject.size === 0) return config4; - const newObjects = config4.objects.map((obj) => { - const objActions = actionsByObject.get(obj.name); - if (!objActions) return obj; - return { - ...obj, - actions: [...obj.actions ?? [], ...objActions] - }; - }); - return { ...config4, objects: newObjects }; -} -function defineStack(config4, options) { - const strict = options?.strict !== false; - const normalized = normalizeStackInput(config4); - if (!strict) { - return mergeActionsIntoObjects(normalized); - } - const result = ObjectStackDefinitionSchema.safeParse(normalized, { - error: objectStackErrorMap - }); - if (!result.success) { - throw new Error(formatZodError(result.error, "defineStack validation failed")); - } - const crossRefErrors = validateCrossReferences(result.data); - if (crossRefErrors.length > 0) { - const header = `defineStack cross-reference validation failed (${crossRefErrors.length} issue${crossRefErrors.length === 1 ? "" : "s"}):`; - const lines = crossRefErrors.map((e) => ` \u2717 ${e}`); - throw new Error(`${header} - -${lines.join("\n")}`); - } - return mergeActionsIntoObjects(result.data); -} -var ConflictStrategySchema = external_exports.enum(["error", "override", "merge"]); -var ComposeStacksOptionsSchema = external_exports.object({ - /** - * How to handle same-name objects across stacks. - * @default 'error' - */ - objectConflict: ConflictStrategySchema.default("error"), - /** - * Which manifest to keep when multiple stacks provide one. - * - `'first'` — Use the first manifest found. - * - `'last'` — Use the last manifest found (default). - * - A number — Use the manifest from the stack at the given index. - * @default 'last' - */ - manifest: external_exports.union([external_exports.enum(["first", "last"]), external_exports.number().int().min(0)]).default("last"), - /** - * Optional namespace prefix (reserved for Phase 2 — Marketplace isolation). - * When set, object names from this composition are prefixed for isolation. - */ - namespace: external_exports.string().optional() -}); -var ObjectQLCapabilitiesSchema = external_exports.object({ - /** Query Capabilities */ - queryFilters: external_exports.boolean().default(true).describe("Supports WHERE clause filtering"), - queryAggregations: external_exports.boolean().default(true).describe("Supports GROUP BY and aggregation functions"), - querySorting: external_exports.boolean().default(true).describe("Supports ORDER BY sorting"), - queryPagination: external_exports.boolean().default(true).describe("Supports LIMIT/OFFSET pagination"), - queryWindowFunctions: external_exports.boolean().default(false).describe("Supports window functions with OVER clause"), - querySubqueries: external_exports.boolean().default(false).describe("Supports subqueries"), - queryDistinct: external_exports.boolean().default(true).describe("Supports SELECT DISTINCT"), - queryHaving: external_exports.boolean().default(false).describe("Supports HAVING clause for aggregations"), - queryJoins: external_exports.boolean().default(false).describe("Supports SQL-style joins"), - /** Advanced Data Features */ - fullTextSearch: external_exports.boolean().default(false).describe("Supports full-text search"), - vectorSearch: external_exports.boolean().default(false).describe("Supports vector embeddings and similarity search for AI/RAG"), - geoSpatial: external_exports.boolean().default(false).describe("Supports geospatial queries and location fields"), - /** Field Type Support */ - jsonFields: external_exports.boolean().default(true).describe("Supports JSON field types"), - arrayFields: external_exports.boolean().default(false).describe("Supports array field types"), - /** Data Validation & Logic */ - validationRules: external_exports.boolean().default(true).describe("Supports validation rules"), - workflows: external_exports.boolean().default(true).describe("Supports workflow automation"), - triggers: external_exports.boolean().default(true).describe("Supports database triggers"), - formulas: external_exports.boolean().default(true).describe("Supports formula fields"), - /** Transaction & Performance */ - transactions: external_exports.boolean().default(true).describe("Supports database transactions"), - bulkOperations: external_exports.boolean().default(true).describe("Supports bulk create/update/delete"), - /** Driver Support */ - supportedDrivers: external_exports.array(external_exports.string()).optional().describe("Available database drivers (e.g., postgresql, mongodb, excel)") -}); -var ObjectUICapabilitiesSchema = external_exports.object({ - /** View Types */ - listView: external_exports.boolean().default(true).describe("Supports list/grid views"), - formView: external_exports.boolean().default(true).describe("Supports form views"), - kanbanView: external_exports.boolean().default(false).describe("Supports kanban board views"), - calendarView: external_exports.boolean().default(false).describe("Supports calendar views"), - ganttView: external_exports.boolean().default(false).describe("Supports Gantt chart views"), - /** Analytics & Reporting */ - dashboards: external_exports.boolean().default(true).describe("Supports dashboard creation"), - reports: external_exports.boolean().default(true).describe("Supports report generation"), - charts: external_exports.boolean().default(true).describe("Supports chart widgets"), - /** Customization */ - customPages: external_exports.boolean().default(true).describe("Supports custom page creation"), - customThemes: external_exports.boolean().default(false).describe("Supports custom theme creation"), - customComponents: external_exports.boolean().default(false).describe("Supports custom UI components/widgets"), - /** Actions & Interactions */ - customActions: external_exports.boolean().default(true).describe("Supports custom button actions"), - screenFlows: external_exports.boolean().default(false).describe("Supports interactive screen flows"), - /** Responsive & Accessibility */ - mobileOptimized: external_exports.boolean().default(false).describe("UI optimized for mobile devices"), - accessibility: external_exports.boolean().default(false).describe("WCAG accessibility support") -}); -var ObjectOSCapabilitiesSchema = external_exports.object({ - /** System Identity */ - version: external_exports.string().describe("ObjectOS Kernel Version"), - environment: external_exports.enum(["development", "test", "staging", "production"]), - /** API Surface */ - restApi: external_exports.boolean().default(true).describe("REST API available"), - graphqlApi: external_exports.boolean().default(false).describe("GraphQL API available"), - odataApi: external_exports.boolean().default(false).describe("OData API available"), - /** Real-time & Events */ - websockets: external_exports.boolean().default(false).describe("WebSocket support for real-time updates"), - serverSentEvents: external_exports.boolean().default(false).describe("Server-Sent Events support"), - eventBus: external_exports.boolean().default(false).describe("Internal event bus for pub/sub"), - /** Integration */ - webhooks: external_exports.boolean().default(true).describe("Outbound webhook support"), - apiContracts: external_exports.boolean().default(false).describe("API contract definitions"), - /** Security & Access Control */ - authentication: external_exports.boolean().default(true).describe("Authentication system"), - rbac: external_exports.boolean().default(true).describe("Role-Based Access Control"), - fieldLevelSecurity: external_exports.boolean().default(false).describe("Field-level permissions"), - rowLevelSecurity: external_exports.boolean().default(false).describe("Row-level security/sharing rules"), - /** Multi-tenancy */ - multiTenant: external_exports.boolean().default(false).describe("Multi-tenant architecture support"), - /** Platform Services */ - backgroundJobs: external_exports.boolean().default(false).describe("Background job scheduling"), - auditLogging: external_exports.boolean().default(false).describe("Audit trail logging"), - fileStorage: external_exports.boolean().default(true).describe("File upload and storage"), - /** Internationalization */ - i18n: external_exports.boolean().default(true).describe("Internationalization support"), - /** Plugin System */ - pluginSystem: external_exports.boolean().default(false).describe("Plugin/extension system"), - /** Active Features & Flags */ - features: external_exports.array(FeatureFlagSchema2).optional().describe("Active Feature Flags"), - /** Available APIs */ - apis: external_exports.array(ApiEndpointSchema2).optional().describe("Available System & Business APIs"), - network: external_exports.object({ - graphql: external_exports.boolean().default(false), - search: external_exports.boolean().default(false), - websockets: external_exports.boolean().default(false), - files: external_exports.boolean().default(true), - analytics: external_exports.boolean().default(false).describe("Is the Analytics/BI engine enabled?"), - ai: external_exports.boolean().default(false).describe("Is the AI engine enabled?"), - workflow: external_exports.boolean().default(false).describe("Is the Workflow engine enabled?"), - notifications: external_exports.boolean().default(false).describe("Is the Notification service enabled?"), - i18n: external_exports.boolean().default(false).describe("Is the i18n service enabled?") - }).optional().describe("Network Capabilities (GraphQL, WS, etc.)"), - /** Introspection */ - systemObjects: external_exports.array(external_exports.string()).optional().describe("List of globally available System Objects"), - /** Constraints (for AI Generation) */ - limits: external_exports.object({ - maxObjects: external_exports.number().optional(), - maxFieldsPerObject: external_exports.number().optional(), - maxRecordsPerQuery: external_exports.number().optional(), - apiRateLimit: external_exports.number().optional(), - fileUploadSizeLimit: external_exports.number().optional().describe("Max file size in bytes") - }).optional() -}); -var ObjectStackCapabilitiesSchema = external_exports.object({ - /** Data Layer Capabilities (ObjectQL) */ - data: ObjectQLCapabilitiesSchema.describe("Data Layer capabilities"), - /** User Interface Layer Capabilities (ObjectUI) */ - ui: ObjectUICapabilitiesSchema.describe("UI Layer capabilities"), - /** System/Runtime Layer Capabilities (ObjectOS) */ - system: ObjectOSCapabilitiesSchema.describe("System/Runtime Layer capabilities") -}); - -// ../app-crm/src/objects/index.ts -var objects_exports = {}; -__export(objects_exports, { - Account: () => Account, - Campaign: () => Campaign, - Case: () => Case, - Contact: () => Contact, - Contract: () => Contract, - Lead: () => Lead, - Opportunity: () => Opportunity, - Product: () => Product, - Quote: () => Quote, - Task: () => Task3 -}); - -// ../app-crm/src/objects/account.object.ts -init_data(); -var Account = ObjectSchema3.create({ - name: "account", - label: "Account", - pluralLabel: "Accounts", - icon: "building", - description: "Companies and organizations doing business with us", - titleFormat: "{account_number} - {name}", - compactLayout: ["account_number", "name", "type", "owner"], - fields: { - // AutoNumber field - Unique account identifier - account_number: Field.autonumber({ - label: "Account Number", - format: "ACC-{0000}" - }), - // Basic Information - name: Field.text({ - label: "Account Name", - required: true, - searchable: true, - maxLength: 255 - }), - // Select fields with custom options - type: Field.select({ - label: "Account Type", - options: [ - { label: "Prospect", value: "prospect", color: "#FFA500", default: true }, - { label: "Customer", value: "customer", color: "#00AA00" }, - { label: "Partner", value: "partner", color: "#0000FF" }, - { label: "Former Customer", value: "former", color: "#999999" } - ] - }), - industry: Field.select({ - label: "Industry", - options: [ - { label: "Technology", value: "technology" }, - { label: "Finance", value: "finance" }, - { label: "Healthcare", value: "healthcare" }, - { label: "Retail", value: "retail" }, - { label: "Manufacturing", value: "manufacturing" }, - { label: "Education", value: "education" } - ] - }), - // Number fields - annual_revenue: Field.currency({ - label: "Annual Revenue", - scale: 2, - min: 0 - }), - number_of_employees: Field.number({ - label: "Employees", - min: 0 - }), - // Contact Information - phone: Field.text({ - label: "Phone", - format: "phone" - }), - website: Field.url({ - label: "Website" - }), - // Structured Address field (new field type) - billing_address: Field.address({ - label: "Billing Address", - addressFormat: "international" - }), - // Office Location (new field type) - office_location: Field.location({ - label: "Office Location", - displayMap: true, - allowGeocoding: true - }), - // Relationship fields - owner: Field.lookup("user", { - label: "Account Owner", - required: true - }), - parent_account: Field.lookup("account", { - label: "Parent Account", - description: "Parent company in hierarchy" - }), - // Rich text field - description: Field.markdown({ - label: "Description" - }), - // Boolean field - is_active: Field.boolean({ - label: "Active", - defaultValue: true - }), - // Date field - last_activity_date: Field.date({ - label: "Last Activity Date", - readonly: true - }), - // Brand color (new field type) - brand_color: Field.color({ - label: "Brand Color", - colorFormat: "hex", - presetColors: ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF"] - }) - }, - // Database indexes for performance - indexes: [ - { fields: ["name"] }, - { fields: ["owner"] }, - { fields: ["type", "is_active"] } - ], - // Enable advanced features - enable: { - trackHistory: true, - // Track field changes - searchable: true, - // Include in global search - apiEnabled: true, - // Expose via REST/GraphQL - apiMethods: ["get", "list", "create", "update", "delete", "search", "export"], - // Whitelist allowed API operations - files: true, - // Allow file attachments - feeds: true, - // Enable activity feed/chatter (Chatter-like) - activities: true, - // Enable tasks and events tracking - trash: true, - // Recycle bin support - mru: true - // Track Most Recently Used - }, - // Validation Rules - validations: [ - { - name: "revenue_positive", - type: "script", - severity: "error", - message: "Annual Revenue must be positive", - condition: "annual_revenue < 0" - }, - { - name: "account_name_unique", - type: "unique", - severity: "error", - message: "Account name must be unique", - fields: ["name"], - caseSensitive: false - } - ], - // Workflow Rules - workflows: [ - { - name: "update_last_activity", - objectName: "account", - triggerType: "on_update", - criteria: "ISCHANGED(owner) OR ISCHANGED(type)", - actions: [ - { - name: "set_activity_date", - type: "field_update", - field: "last_activity_date", - value: "TODAY()" - } - ], - active: true - } - ] -}); - -// ../app-crm/src/objects/campaign.object.ts -init_data(); -var Campaign = ObjectSchema3.create({ - name: "campaign", - label: "Campaign", - pluralLabel: "Campaigns", - icon: "megaphone", - description: "Marketing campaigns and initiatives", - titleFormat: "{campaign_code} - {name}", - compactLayout: ["campaign_code", "name", "type", "status", "start_date"], - fields: { - // AutoNumber field - campaign_code: Field.autonumber({ - label: "Campaign Code", - format: "CPG-{0000}" - }), - // Basic Information - name: Field.text({ - label: "Campaign Name", - required: true, - searchable: true, - maxLength: 255 - }), - description: Field.markdown({ - label: "Description" - }), - // Type & Channel - type: Field.select({ - label: "Campaign Type", - options: [ - { label: "Email", value: "email", default: true }, - { label: "Webinar", value: "webinar" }, - { label: "Trade Show", value: "trade_show" }, - { label: "Conference", value: "conference" }, - { label: "Direct Mail", value: "direct_mail" }, - { label: "Social Media", value: "social_media" }, - { label: "Content Marketing", value: "content" }, - { label: "Partner Marketing", value: "partner" } - ] - }), - channel: Field.select({ - label: "Primary Channel", - options: [ - { label: "Digital", value: "digital" }, - { label: "Social", value: "social" }, - { label: "Email", value: "email" }, - { label: "Events", value: "events" }, - { label: "Partner", value: "partner" } - ] - }), - // Status - status: Field.select({ - label: "Status", - options: [ - { label: "Planning", value: "planning", color: "#999999", default: true }, - { label: "In Progress", value: "in_progress", color: "#FFA500" }, - { label: "Completed", value: "completed", color: "#00AA00" }, - { label: "Aborted", value: "aborted", color: "#FF0000" } - ], - required: true - }), - // Dates - start_date: Field.date({ - label: "Start Date", - required: true - }), - end_date: Field.date({ - label: "End Date", - required: true - }), - // Budget & ROI - budgeted_cost: Field.currency({ - label: "Budgeted Cost", - scale: 2, - min: 0 - }), - actual_cost: Field.currency({ - label: "Actual Cost", - scale: 2, - min: 0 - }), - expected_revenue: Field.currency({ - label: "Expected Revenue", - scale: 2, - min: 0 - }), - actual_revenue: Field.currency({ - label: "Actual Revenue", - scale: 2, - min: 0, - readonly: true - }), - // Metrics - target_size: Field.number({ - label: "Target Size", - description: "Target number of leads/contacts", - min: 0 - }), - num_sent: Field.number({ - label: "Number Sent", - min: 0, - readonly: true - }), - num_responses: Field.number({ - label: "Number of Responses", - min: 0, - readonly: true - }), - num_leads: Field.number({ - label: "Number of Leads", - min: 0, - readonly: true - }), - num_converted_leads: Field.number({ - label: "Converted Leads", - min: 0, - readonly: true - }), - num_opportunities: Field.number({ - label: "Opportunities Created", - min: 0, - readonly: true - }), - num_won_opportunities: Field.number({ - label: "Won Opportunities", - min: 0, - readonly: true - }), - // Calculated Metrics (Formula Fields) - response_rate: Field.formula({ - label: "Response Rate %", - expression: "IF(num_sent > 0, (num_responses / num_sent) * 100, 0)", - scale: 2 - }), - roi: Field.formula({ - label: "ROI %", - expression: "IF(actual_cost > 0, ((actual_revenue - actual_cost) / actual_cost) * 100, 0)", - scale: 2 - }), - // Relationships - parent_campaign: Field.lookup("campaign", { - label: "Parent Campaign", - description: "Parent campaign in hierarchy" - }), - owner: Field.lookup("user", { - label: "Campaign Owner", - required: true - }), - // Campaign Assets - landing_page_url: Field.url({ - label: "Landing Page" - }), - is_active: Field.boolean({ - label: "Active", - defaultValue: true - }) - }, - // Database indexes - indexes: [ - { fields: ["name"] }, - { fields: ["type"] }, - { fields: ["status"] }, - { fields: ["start_date"] }, - { fields: ["owner"] } - ], - // Enable advanced features - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete", "search", "export"], - files: true, - feeds: true, - activities: true, - trash: true, - mru: true - }, - // Validation Rules - validations: [ - { - name: "end_after_start", - type: "script", - severity: "error", - message: "End Date must be after Start Date", - condition: "end_date < start_date" - }, - { - name: "actual_cost_within_budget", - type: "script", - severity: "warning", - message: "Actual Cost exceeds Budgeted Cost", - condition: "actual_cost > budgeted_cost" - } - ], - // Workflow Rules - workflows: [ - { - name: "campaign_completion_check", - objectName: "campaign", - triggerType: "on_read", - criteria: 'end_date < TODAY() AND status = "in_progress"', - actions: [ - { - name: "mark_completed", - type: "field_update", - field: "status", - value: '"completed"' - } - ], - active: true - } - ] -}); - -// ../app-crm/src/objects/case.object.ts -init_data(); -var Case = ObjectSchema3.create({ - name: "case", - label: "Case", - pluralLabel: "Cases", - icon: "life-buoy", - description: "Customer support cases and service requests", - fields: { - // Case Information - case_number: Field.autonumber({ - label: "Case Number", - format: "CASE-{00000}" - }), - subject: Field.text({ - label: "Subject", - required: true, - searchable: true, - maxLength: 255 - }), - description: Field.markdown({ - label: "Description", - required: true - }), - // Relationships - account: Field.lookup("account", { - label: "Account" - }), - contact: Field.lookup("contact", { - label: "Contact", - required: true, - referenceFilters: ["account = {case.account}"] - }), - // Case Management - status: Field.select({ - label: "Status", - required: true, - options: [ - { label: "New", value: "new", color: "#808080", default: true }, - { label: "In Progress", value: "in_progress", color: "#FFA500" }, - { label: "Waiting on Customer", value: "waiting_customer", color: "#FFD700" }, - { label: "Waiting on Support", value: "waiting_support", color: "#4169E1" }, - { label: "Escalated", value: "escalated", color: "#FF0000" }, - { label: "Resolved", value: "resolved", color: "#00AA00" }, - { label: "Closed", value: "closed", color: "#006400" } - ] - }), - priority: Field.select({ - label: "Priority", - required: true, - options: [ - { label: "Low", value: "low", color: "#4169E1", default: true }, - { label: "Medium", value: "medium", color: "#FFA500" }, - { label: "High", value: "high", color: "#FF4500" }, - { label: "Critical", value: "critical", color: "#FF0000" } - ] - }), - type: Field.select({ - label: "Case Type", - options: [ - { label: "Question", value: "question" }, - { label: "Problem", value: "problem" }, - { label: "Feature Request", value: "feature_request" }, - { label: "Bug", value: "bug" } - ] - }), - origin: Field.select({ - label: "Case Origin", - options: [ - { label: "Email", value: "email" }, - { label: "Phone", value: "phone" }, - { label: "Web", value: "web" }, - { label: "Chat", value: "chat" }, - { label: "Social Media", value: "social_media" } - ] - }), - // Assignment - owner: Field.lookup("user", { - label: "Case Owner", - required: true - }), - // SLA and Metrics - created_date: Field.datetime({ - label: "Created Date", - readonly: true - }), - closed_date: Field.datetime({ - label: "Closed Date", - readonly: true - }), - first_response_date: Field.datetime({ - label: "First Response Date", - readonly: true - }), - resolution_time_hours: Field.number({ - label: "Resolution Time (Hours)", - readonly: true, - scale: 2 - }), - sla_due_date: Field.datetime({ - label: "SLA Due Date" - }), - is_sla_violated: Field.boolean({ - label: "SLA Violated", - defaultValue: false, - readonly: true - }), - // Escalation - is_escalated: Field.boolean({ - label: "Escalated", - defaultValue: false - }), - escalation_reason: Field.textarea({ - label: "Escalation Reason" - }), - // Related case - parent_case: Field.lookup("case", { - label: "Parent Case", - description: "Related parent case" - }), - // Resolution - resolution: Field.markdown({ - label: "Resolution" - }), - // Customer satisfaction - customer_rating: Field.rating(5, { - label: "Customer Satisfaction", - description: "Customer satisfaction rating (1-5 stars)" - }), - customer_feedback: Field.textarea({ - label: "Customer Feedback" - }), - // Customer signature (for case resolution acknowledgment) - customer_signature: Field.signature({ - label: "Customer Signature", - description: "Digital signature acknowledging case resolution" - }), - // Internal notes - internal_notes: Field.markdown({ - label: "Internal Notes", - description: "Internal notes not visible to customer" - }), - // Flags - is_closed: Field.boolean({ - label: "Is Closed", - defaultValue: false, - readonly: true - }) - }, - // Database indexes for performance - indexes: [ - { fields: ["case_number"], unique: true }, - { fields: ["account"] }, - { fields: ["owner"] }, - { fields: ["status"] }, - { fields: ["priority"] } - ], - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - files: true, - feeds: true, - // Enable social feed, comments, and mentions - activities: true, - // Enable tasks and events tracking - trash: true, - mru: true - // Track Most Recently Used - }, - titleFormat: "{case_number} - {subject}", - compactLayout: ["case_number", "subject", "account", "status", "priority"], - // Removed: list_views and form_views belong in UI configuration, not object definition - validations: [ - { - name: "resolution_required_for_closed", - type: "script", - severity: "error", - message: "Resolution is required when closing a case", - condition: 'status = "closed" AND ISBLANK(resolution)' - }, - { - name: "escalation_reason_required", - type: "script", - severity: "error", - message: "Escalation reason is required when escalating a case", - condition: "is_escalated = true AND ISBLANK(escalation_reason)" - }, - { - name: "case_status_progression", - type: "state_machine", - severity: "warning", - message: "Invalid status transition", - field: "status", - transitions: { - "new": ["in_progress", "waiting_customer", "closed"], - "in_progress": ["waiting_customer", "waiting_support", "escalated", "resolved"], - "waiting_customer": ["in_progress", "closed"], - "waiting_support": ["in_progress", "escalated"], - "escalated": ["in_progress", "resolved"], - "resolved": ["closed", "in_progress"], - // Can reopen - "closed": ["in_progress"] - // Can reopen - } - } - ], - workflows: [ - { - name: "set_closed_flag", - objectName: "case", - triggerType: "on_create_or_update", - criteria: "ISCHANGED(status)", - active: true, - actions: [ - { - name: "update_closed_flag", - type: "field_update", - field: "is_closed", - value: 'status = "closed"' - } - ] - }, - { - name: "set_closed_date", - objectName: "case", - triggerType: "on_update", - criteria: 'ISCHANGED(status) AND status = "closed"', - active: true, - actions: [ - { - name: "set_date", - type: "field_update", - field: "closed_date", - value: "NOW()" - } - ] - }, - { - name: "calculate_resolution_time", - objectName: "case", - triggerType: "on_update", - criteria: "ISCHANGED(closed_date) AND NOT(ISBLANK(closed_date))", - active: true, - actions: [ - { - name: "calc_time", - type: "field_update", - field: "resolution_time_hours", - value: "HOURS(created_date, closed_date)" - } - ] - }, - { - name: "notify_on_critical", - objectName: "case", - triggerType: "on_create_or_update", - criteria: 'priority = "critical"', - active: true, - actions: [ - { - name: "email_support_manager", - type: "email_alert", - template: "critical_case_alert", - recipients: ["support_manager@example.com"] - } - ] - }, - { - name: "notify_on_escalation", - objectName: "case", - triggerType: "on_update", - criteria: "ISCHANGED(is_escalated) AND is_escalated = true", - active: true, - actions: [ - { - name: "email_escalation_team", - type: "email_alert", - template: "case_escalation_alert", - recipients: ["escalation_team@example.com"] - } - ] - } - ] -}); - -// ../app-crm/src/objects/contact.object.ts -init_data(); -var Contact = ObjectSchema3.create({ - name: "contact", - label: "Contact", - pluralLabel: "Contacts", - icon: "user", - description: "People associated with accounts", - fields: { - // Name fields - salutation: Field.select({ - label: "Salutation", - options: [ - { label: "Mr.", value: "mr" }, - { label: "Ms.", value: "ms" }, - { label: "Mrs.", value: "mrs" }, - { label: "Dr.", value: "dr" }, - { label: "Prof.", value: "prof" } - ] - }), - first_name: Field.text({ - label: "First Name", - required: true, - searchable: true - }), - last_name: Field.text({ - label: "Last Name", - required: true, - searchable: true - }), - // Formula field - Full name - full_name: Field.formula({ - label: "Full Name", - expression: 'CONCAT(salutation, " ", first_name, " ", last_name)' - }), - // Relationship: Link to Account (Master-Detail) - account: Field.masterDetail("account", { - label: "Account", - required: true, - writeRequiresMasterRead: true, - deleteBehavior: "cascade" - // Delete contacts when account is deleted - }), - // Contact Information - email: Field.email({ - label: "Email", - required: true, - unique: true - }), - phone: Field.text({ - label: "Phone", - format: "phone" - }), - mobile: Field.text({ - label: "Mobile", - format: "phone" - }), - // Professional Information - title: Field.text({ - label: "Job Title" - }), - department: Field.select({ - label: "Department", - options: [ - { label: "Executive", value: "executive" }, - { label: "Sales", value: "sales" }, - { label: "Marketing", value: "marketing" }, - { label: "Engineering", value: "engineering" }, - { label: "Support", value: "support" }, - { label: "Finance", value: "finance" }, - { label: "HR", value: "hr" }, - { label: "Operations", value: "operations" } - ] - }), - // Relationship fields - reports_to: Field.lookup("contact", { - label: "Reports To", - description: "Direct manager/supervisor" - }), - owner: Field.lookup("user", { - label: "Contact Owner", - required: true - }), - // Mailing Address - mailing_street: Field.textarea({ label: "Mailing Street" }), - mailing_city: Field.text({ label: "Mailing City" }), - mailing_state: Field.text({ label: "Mailing State/Province" }), - mailing_postal_code: Field.text({ label: "Mailing Postal Code" }), - mailing_country: Field.text({ label: "Mailing Country" }), - // Additional Information - birthdate: Field.date({ - label: "Birthdate" - }), - lead_source: Field.select({ - label: "Lead Source", - options: [ - { label: "Web", value: "web" }, - { label: "Referral", value: "referral" }, - { label: "Event", value: "event" }, - { label: "Partner", value: "partner" }, - { label: "Advertisement", value: "advertisement" } - ] - }), - description: Field.markdown({ - label: "Description" - }), - // Flags - is_primary: Field.boolean({ - label: "Primary Contact", - defaultValue: false, - description: "Is this the main contact for the account?" - }), - do_not_call: Field.boolean({ - label: "Do Not Call", - defaultValue: false - }), - email_opt_out: Field.boolean({ - label: "Email Opt Out", - defaultValue: false - }), - // Avatar field - avatar: Field.avatar({ - label: "Profile Picture" - }) - }, - // Enable features - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - files: true, - feeds: true, - // Enable social feed, comments, and mentions - activities: true, - // Enable tasks and events tracking - trash: true, - mru: true - // Track Most Recently Used - }, - // Database indexes for performance - indexes: [ - { fields: ["account"] }, - { fields: ["email"], unique: true }, - { fields: ["owner"] }, - { fields: ["last_name", "first_name"] } - ], - // Display configuration - titleFormat: "{full_name}", - compactLayout: ["full_name", "email", "account", "phone"], - // Validation Rules - validations: [ - { - name: "email_required_for_opt_in", - type: "script", - severity: "error", - message: "Email is required when Email Opt Out is not checked", - condition: "email_opt_out = false AND ISBLANK(email)" - }, - { - name: "email_unique_per_account", - type: "unique", - severity: "error", - message: "Email must be unique within an account", - fields: ["email", "account"], - caseSensitive: false - } - ], - // Workflow Rules - workflows: [ - { - name: "welcome_email", - objectName: "contact", - triggerType: "on_create", - active: true, - actions: [ - { - name: "send_welcome", - type: "email_alert", - template: "contact_welcome", - recipients: ["{contact.email}"] - } - ] - } - ] -}); - -// ../app-crm/src/objects/contract.object.ts -init_data(); -var Contract = ObjectSchema3.create({ - name: "contract", - label: "Contract", - pluralLabel: "Contracts", - icon: "file-signature", - description: "Legal contracts and agreements", - titleFormat: "{contract_number} - {account.name}", - compactLayout: ["contract_number", "account", "status", "start_date", "end_date"], - fields: { - // AutoNumber field - contract_number: Field.autonumber({ - label: "Contract Number", - format: "CTR-{0000}" - }), - // Relationships - account: Field.lookup("account", { - label: "Account", - required: true - }), - contact: Field.lookup("contact", { - label: "Primary Contact", - required: true, - referenceFilters: [ - "account = {account}" - ] - }), - opportunity: Field.lookup("opportunity", { - label: "Related Opportunity", - referenceFilters: [ - "account = {account}" - ] - }), - owner: Field.lookup("user", { - label: "Contract Owner", - required: true - }), - // Status - status: Field.select({ - label: "Status", - options: [ - { label: "Draft", value: "draft", color: "#999999", default: true }, - { label: "In Approval", value: "in_approval", color: "#FFA500" }, - { label: "Activated", value: "activated", color: "#00AA00" }, - { label: "Expired", value: "expired", color: "#FF0000" }, - { label: "Terminated", value: "terminated", color: "#666666" } - ], - required: true - }), - // Contract Terms - contract_term_months: Field.number({ - label: "Contract Term (Months)", - required: true, - min: 1 - }), - start_date: Field.date({ - label: "Start Date", - required: true - }), - end_date: Field.date({ - label: "End Date", - required: true - }), - // Financial - contract_value: Field.currency({ - label: "Contract Value", - scale: 2, - min: 0, - required: true - }), - billing_frequency: Field.select({ - label: "Billing Frequency", - options: [ - { label: "Monthly", value: "monthly", default: true }, - { label: "Quarterly", value: "quarterly" }, - { label: "Annually", value: "annually" }, - { label: "One-time", value: "one_time" } - ] - }), - payment_terms: Field.select({ - label: "Payment Terms", - options: [ - { label: "Net 15", value: "net_15" }, - { label: "Net 30", value: "net_30", default: true }, - { label: "Net 60", value: "net_60" }, - { label: "Net 90", value: "net_90" } - ] - }), - // Renewal - auto_renewal: Field.boolean({ - label: "Auto Renewal", - defaultValue: false - }), - renewal_notice_days: Field.number({ - label: "Renewal Notice (Days)", - min: 0, - defaultValue: 30 - }), - // Legal - contract_type: Field.select({ - label: "Contract Type", - options: [ - { label: "Subscription", value: "subscription" }, - { label: "Service Agreement", value: "service" }, - { label: "License", value: "license" }, - { label: "Partnership", value: "partnership" }, - { label: "NDA", value: "nda" }, - { label: "MSA", value: "msa" } - ] - }), - signed_date: Field.date({ - label: "Signed Date" - }), - signed_by: Field.text({ - label: "Signed By", - maxLength: 255 - }), - document_url: Field.url({ - label: "Contract Document" - }), - // Terms & Conditions - special_terms: Field.markdown({ - label: "Special Terms" - }), - description: Field.markdown({ - label: "Description" - }), - // Billing Address - billing_address: Field.address({ - label: "Billing Address", - addressFormat: "international" - }) - }, - // Database indexes - indexes: [ - { fields: ["account"] }, - { fields: ["status"] }, - { fields: ["start_date"] }, - { fields: ["end_date"] }, - { fields: ["owner"] } - ], - // Enable advanced features - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete", "search", "export"], - files: true, - feeds: true, - activities: true, - trash: true, - mru: true - }, - // Validation Rules - validations: [ - { - name: "end_after_start", - type: "script", - severity: "error", - message: "End Date must be after Start Date", - condition: "end_date <= start_date" - }, - { - name: "valid_contract_term", - type: "script", - severity: "error", - message: "Contract Term must match date range", - condition: "MONTH_DIFF(end_date, start_date) != contract_term_months" - } - ], - // Workflow Rules - workflows: [ - { - name: "contract_expiration_check", - objectName: "contract", - triggerType: "scheduled", - schedule: "0 0 * * *", - // Daily at midnight - criteria: 'end_date <= TODAY() AND status = "activated"', - actions: [ - { - name: "mark_expired", - type: "field_update", - field: "status", - value: '"expired"' - }, - { - name: "notify_owner", - type: "email_alert", - template: "contract_expired", - recipients: ["{owner}"] - } - ], - active: true - }, - { - name: "renewal_reminder", - objectName: "contract", - triggerType: "scheduled", - schedule: "0 0 * * *", - // Daily at midnight - criteria: 'DAYS_UNTIL(end_date) <= renewal_notice_days AND status = "activated"', - actions: [ - { - name: "notify_renewal", - type: "email_alert", - template: "contract_renewal_reminder", - recipients: ["{owner}", "{account.owner}"] - } - ], - active: true - } - ] -}); - -// ../app-crm/src/objects/lead.object.ts -init_data(); - -// ../app-crm/src/objects/lead.state.ts -var LeadStateMachine = { - id: "lead_process", - initial: "new", - states: { - new: { - on: { - CONTACT: { target: "contacted", description: "Log initial contact" }, - DISQUALIFY: { target: "unqualified", description: "Mark as unqualified early" } - }, - meta: { - aiInstructions: "New lead. Verify email and phone before contacting. Do not change status until contact is made." - } - }, - contacted: { - on: { - QUALIFY: { target: "qualified", cond: "has_budget_and_authority" }, - DISQUALIFY: { target: "unqualified" } - }, - meta: { - aiInstructions: "Engage with the lead. Qualify by asking about budget, authority, need, and timeline (BANT)." - } - }, - qualified: { - on: { - CONVERT: { target: "converted", cond: "is_ready_to_buy" }, - DISQUALIFY: { target: "unqualified" } - }, - meta: { - aiInstructions: "Lead is qualified. Prepare for conversion to Deal/Opportunity. Check for existing accounts." - } - }, - unqualified: { - on: { - REOPEN: { target: "new", description: "Re-evaluate lead" } - }, - meta: { - aiInstructions: "Lead is dead. Do not contact unless new information surfaces." - } - }, - converted: { - type: "final", - meta: { - aiInstructions: "Lead is converted. No further actions allowed on this record." - } - } - } -}; - -// ../app-crm/src/objects/lead.object.ts -var Lead = ObjectSchema3.create({ - name: "lead", - label: "Lead", - pluralLabel: "Leads", - icon: "user-plus", - description: "Potential customers not yet qualified", - fields: { - // Personal Information - salutation: Field.select({ - label: "Salutation", - options: [ - { label: "Mr.", value: "mr" }, - { label: "Ms.", value: "ms" }, - { label: "Mrs.", value: "mrs" }, - { label: "Dr.", value: "dr" } - ] - }), - first_name: Field.text({ - label: "First Name", - required: true, - searchable: true - }), - last_name: Field.text({ - label: "Last Name", - required: true, - searchable: true - }), - full_name: Field.formula({ - label: "Full Name", - expression: 'CONCAT(salutation, " ", first_name, " ", last_name)' - }), - // Company Information - company: Field.text({ - label: "Company", - required: true, - searchable: true - }), - title: Field.text({ - label: "Job Title" - }), - industry: Field.select({ - label: "Industry", - options: [ - { label: "Technology", value: "technology" }, - { label: "Finance", value: "finance" }, - { label: "Healthcare", value: "healthcare" }, - { label: "Retail", value: "retail" }, - { label: "Manufacturing", value: "manufacturing" }, - { label: "Education", value: "education" } - ] - }), - // Contact Information - email: Field.email({ - label: "Email", - required: true, - unique: true - }), - phone: Field.text({ - label: "Phone", - format: "phone" - }), - mobile: Field.text({ - label: "Mobile", - format: "phone" - }), - website: Field.url({ - label: "Website" - }), - // Lead Qualification - status: Field.select({ - label: "Lead Status", - required: true, - options: [ - { label: "New", value: "new", color: "#808080", default: true }, - { label: "Contacted", value: "contacted", color: "#FFA500" }, - { label: "Qualified", value: "qualified", color: "#4169E1" }, - { label: "Unqualified", value: "unqualified", color: "#FF0000" }, - { label: "Converted", value: "converted", color: "#00AA00" } - ] - }), - rating: Field.rating(5, { - label: "Lead Score", - description: "Lead quality score (1-5 stars)", - allowHalf: true - }), - lead_source: Field.select({ - label: "Lead Source", - options: [ - { label: "Web", value: "web" }, - { label: "Referral", value: "referral" }, - { label: "Event", value: "event" }, - { label: "Partner", value: "partner" }, - { label: "Advertisement", value: "advertisement" }, - { label: "Cold Call", value: "cold_call" } - ] - }), - // Assignment - owner: Field.lookup("user", { - label: "Lead Owner", - required: true - }), - // Conversion tracking - is_converted: Field.boolean({ - label: "Converted", - defaultValue: false, - readonly: true - }), - converted_account: Field.lookup("account", { - label: "Converted Account", - readonly: true - }), - converted_contact: Field.lookup("contact", { - label: "Converted Contact", - readonly: true - }), - converted_opportunity: Field.lookup("opportunity", { - label: "Converted Opportunity", - readonly: true - }), - converted_date: Field.datetime({ - label: "Converted Date", - readonly: true - }), - // Address (using new address field type) - address: Field.address({ - label: "Address", - addressFormat: "international" - }), - // Additional Info - annual_revenue: Field.currency({ - label: "Annual Revenue", - scale: 2 - }), - number_of_employees: Field.number({ - label: "Number of Employees" - }), - description: Field.markdown({ - label: "Description" - }), - // Custom notes with rich text formatting - notes: Field.richtext({ - label: "Notes", - description: "Rich text notes with formatting" - }), - // Flags - do_not_call: Field.boolean({ - label: "Do Not Call", - defaultValue: false - }), - email_opt_out: Field.boolean({ - label: "Email Opt Out", - defaultValue: false - }) - }, - // Lifecycle State Machine(s) - // Enforces valid status transitions to prevent AI hallucinations - // Using `stateMachines` (plural) for future extensibility. - // For simple objects with one lifecycle, `stateMachine` (singular) is also supported. - stateMachines: { - lifecycle: LeadStateMachine - }, - // Database indexes for performance - indexes: [ - { fields: ["email"], unique: true }, - { fields: ["owner"] }, - { fields: ["status"] }, - { fields: ["company"] } - ], - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - files: true, - feeds: true, - // Enable social feed, comments, and mentions - activities: true, - // Enable tasks and events tracking - trash: true, - mru: true - // Track Most Recently Used - }, - titleFormat: "{full_name} - {company}", - compactLayout: ["full_name", "company", "email", "status", "owner"], - // Removed: list_views and form_views belong in UI configuration, not object definition - validations: [ - { - name: "email_required", - type: "script", - severity: "error", - message: "Email is required", - condition: "ISBLANK(email)" - }, - { - name: "cannot_edit_converted", - type: "script", - severity: "error", - message: "Cannot edit a converted lead", - condition: "is_converted = true AND ISCHANGED(company, email, first_name, last_name)" - } - ], - workflows: [ - { - name: "auto_qualify_high_score_leads", - objectName: "lead", - triggerType: "on_create_or_update", - criteria: 'rating >= 4 AND status = "new"', - active: true, - actions: [ - { - name: "set_status", - type: "field_update", - field: "status", - value: "contacted" - } - ] - }, - { - name: "notify_owner_on_high_score_lead", - objectName: "lead", - triggerType: "on_create_or_update", - criteria: "ISCHANGED(rating) AND rating >= 4.5", - active: true, - actions: [ - { - name: "email_owner", - type: "email_alert", - template: "high_score_lead_notification", - recipients: ["{owner.email}"] - } - ] - } - ] -}); - -// ../app-crm/src/objects/opportunity.object.ts -init_data(); - -// ../app-crm/src/objects/opportunity.state.ts -var OpportunityStateMachine = { - id: "opportunity_pipeline", - initial: "prospecting", - states: { - prospecting: { - on: { - QUALIFY: { target: "qualification", description: "Initial qualification passed" }, - LOSE: { target: "closed_lost", description: "Lost at prospecting stage" } - }, - meta: { - aiInstructions: "New opportunity. Identify decision makers and confirm budget exists before advancing." - } - }, - qualification: { - on: { - ANALYZE: { target: "needs_analysis", description: "Begin needs analysis" }, - LOSE: { target: "closed_lost", description: "Lost at qualification stage" } - }, - meta: { - aiInstructions: "Qualifying opportunity. Gather BANT (Budget, Authority, Need, Timeline) details." - } - }, - needs_analysis: { - on: { - PROPOSE: { target: "proposal", description: "Submit proposal" }, - LOSE: { target: "closed_lost", description: "Lost during needs analysis" } - }, - meta: { - aiInstructions: "Analyzing customer needs. Document requirements and pain points before proposing." - } - }, - proposal: { - on: { - NEGOTIATE: { target: "negotiation", description: "Enter negotiation" }, - LOSE: { target: "closed_lost", description: "Proposal rejected" } - }, - meta: { - aiInstructions: "Proposal submitted. Follow up on pricing and terms. Prepare for negotiation." - } - }, - negotiation: { - on: { - WIN: { target: "closed_won", description: "Deal won" }, - LOSE: { target: "closed_lost", description: "Lost in negotiation" } - }, - meta: { - aiInstructions: "In negotiation. Focus on closing. Escalate blockers to management if needed." - } - }, - closed_won: { - type: "final", - meta: { - aiInstructions: "Deal won. No further stage changes allowed. Trigger contract creation." - } - }, - closed_lost: { - type: "final", - meta: { - aiInstructions: "Deal lost. Record loss reason. No further stage changes allowed." - } - } - } -}; - -// ../app-crm/src/objects/opportunity.object.ts -var Opportunity = ObjectSchema3.create({ - name: "opportunity", - label: "Opportunity", - pluralLabel: "Opportunities", - icon: "dollar-sign", - description: "Sales opportunities and deals in the pipeline", - titleFormat: "{name} - {stage}", - compactLayout: ["name", "account", "amount", "stage", "owner"], - fields: { - // Basic Information - name: Field.text({ - label: "Opportunity Name", - required: true, - searchable: true - }), - // Relationships - account: Field.lookup("account", { - label: "Account", - required: true - }), - primary_contact: Field.lookup("contact", { - label: "Primary Contact", - referenceFilters: ["account = {opportunity.account}"] - // Filter contacts by account - }), - owner: Field.lookup("user", { - label: "Opportunity Owner", - required: true - }), - // Financial Information - amount: Field.currency({ - label: "Amount", - required: true, - scale: 2, - min: 0 - }), - expected_revenue: Field.currency({ - label: "Expected Revenue", - scale: 2, - readonly: true - // Calculated field - }), - // Sales Process - stage: Field.select({ - label: "Stage", - required: true, - options: [ - { label: "Prospecting", value: "prospecting", color: "#808080", default: true }, - { label: "Qualification", value: "qualification", color: "#FFA500" }, - { label: "Needs Analysis", value: "needs_analysis", color: "#FFD700" }, - { label: "Proposal", value: "proposal", color: "#4169E1" }, - { label: "Negotiation", value: "negotiation", color: "#9370DB" }, - { label: "Closed Won", value: "closed_won", color: "#00AA00" }, - { label: "Closed Lost", value: "closed_lost", color: "#FF0000" } - ] - }), - probability: Field.percent({ - label: "Probability (%)", - min: 0, - max: 100, - defaultValue: 10 - }), - // Important Dates - close_date: Field.date({ - label: "Close Date", - required: true - }), - created_date: Field.datetime({ - label: "Created Date", - readonly: true - }), - // Additional Classification - type: Field.select({ - label: "Opportunity Type", - options: [ - { label: "New Business", value: "new_business" }, - { label: "Existing Customer - Upgrade", value: "existing_upgrade" }, - { label: "Existing Customer - Renewal", value: "existing_renewal" }, - { label: "Existing Customer - Expansion", value: "existing_expansion" } - ] - }), - lead_source: Field.select({ - label: "Lead Source", - options: [ - { label: "Web", value: "web" }, - { label: "Referral", value: "referral" }, - { label: "Event", value: "event" }, - { label: "Partner", value: "partner" }, - { label: "Advertisement", value: "advertisement" }, - { label: "Cold Call", value: "cold_call" } - ] - }), - // Competitor Analysis - competitors: Field.select({ - label: "Competitors", - multiple: true, - options: [ - { label: "Competitor A", value: "competitor_a" }, - { label: "Competitor B", value: "competitor_b" }, - { label: "Competitor C", value: "competitor_c" } - ] - }), - // Campaign tracking - campaign: Field.lookup("campaign", { - label: "Campaign", - description: "Marketing campaign that generated this opportunity" - }), - // Sales cycle metrics - days_in_stage: Field.number({ - label: "Days in Current Stage", - readonly: true - }), - // Additional information - description: Field.markdown({ - label: "Description" - }), - next_step: Field.textarea({ - label: "Next Steps" - }), - // Flags - is_private: Field.boolean({ - label: "Private", - defaultValue: false - }), - forecast_category: Field.select({ - label: "Forecast Category", - options: [ - { label: "Pipeline", value: "pipeline" }, - { label: "Best Case", value: "best_case" }, - { label: "Commit", value: "commit" }, - { label: "Omitted", value: "omitted" }, - { label: "Closed", value: "closed" } - ] - }) - }, - // Database indexes for performance - indexes: [ - { fields: ["name"] }, - { fields: ["account"] }, - { fields: ["owner"] }, - { fields: ["stage"] }, - { fields: ["close_date"] } - ], - // Enable advanced features - enable: { - trackHistory: true, - // Critical for tracking stage changes - searchable: true, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete", "aggregate", "search"], - // Whitelist allowed API operations - files: true, - // Attach proposals, contracts - feeds: true, - // Team collaboration (Chatter-like) - activities: true, - // Enable tasks and events tracking - trash: true, - mru: true - // Track Most Recently Used - }, - // Removed: list_views and form_views belong in UI configuration, not object definition - // Lifecycle State Machine(s) - stateMachines: { - lifecycle: OpportunityStateMachine - }, - // Validation Rules - validations: [ - { - name: "close_date_future", - type: "script", - severity: "warning", - message: "Close date should not be in the past unless opportunity is closed", - condition: 'close_date < TODAY() AND stage != "closed_won" AND stage != "closed_lost"' - }, - { - name: "amount_positive", - type: "script", - severity: "error", - message: "Amount must be greater than zero", - condition: "amount <= 0" - } - ], - // Workflow Rules - workflows: [ - { - name: "update_probability_by_stage", - objectName: "opportunity", - triggerType: "on_create_or_update", - criteria: "ISCHANGED(stage)", - active: true, - actions: [ - { - name: "set_probability", - type: "field_update", - field: "probability", - value: `CASE(stage, - "prospecting", 10, - "qualification", 25, - "needs_analysis", 40, - "proposal", 60, - "negotiation", 80, - "closed_won", 100, - "closed_lost", 0, - probability - )` - }, - { - name: "set_forecast_category", - type: "field_update", - field: "forecast_category", - value: `CASE(stage, - "prospecting", "pipeline", - "qualification", "pipeline", - "needs_analysis", "best_case", - "proposal", "commit", - "negotiation", "commit", - "closed_won", "closed", - "closed_lost", "omitted", - forecast_category - )` - } - ] - }, - { - name: "calculate_expected_revenue", - objectName: "opportunity", - triggerType: "on_create_or_update", - criteria: "ISCHANGED(amount) OR ISCHANGED(probability)", - active: true, - actions: [ - { - name: "update_expected_revenue", - type: "field_update", - field: "expected_revenue", - value: "amount * (probability / 100)" - } - ] - }, - { - name: "notify_on_large_deal_won", - objectName: "opportunity", - triggerType: "on_update", - criteria: 'ISCHANGED(stage) AND stage = "closed_won" AND amount > 100000', - active: true, - actions: [ - { - name: "notify_management", - type: "email_alert", - template: "large_deal_won", - recipients: ["sales_management@example.com"] - } - ] - } - ] -}); - -// ../app-crm/src/objects/product.object.ts -init_data(); -var Product = ObjectSchema3.create({ - name: "product", - label: "Product", - pluralLabel: "Products", - icon: "box", - description: "Products and services offered by the company", - titleFormat: "{product_code} - {name}", - compactLayout: ["product_code", "name", "category", "is_active"], - fields: { - // AutoNumber field - Unique product identifier - product_code: Field.autonumber({ - label: "Product Code", - format: "PRD-{0000}" - }), - // Basic Information - name: Field.text({ - label: "Product Name", - required: true, - searchable: true, - maxLength: 255 - }), - description: Field.markdown({ - label: "Description" - }), - // Categorization - category: Field.select({ - label: "Category", - options: [ - { label: "Software", value: "software", default: true }, - { label: "Hardware", value: "hardware" }, - { label: "Service", value: "service" }, - { label: "Subscription", value: "subscription" }, - { label: "Support", value: "support" } - ] - }), - family: Field.select({ - label: "Product Family", - options: [ - { label: "Enterprise Solutions", value: "enterprise" }, - { label: "SMB Solutions", value: "smb" }, - { label: "Professional Services", value: "services" }, - { label: "Cloud Services", value: "cloud" } - ] - }), - // Pricing - list_price: Field.currency({ - label: "List Price", - scale: 2, - min: 0, - required: true - }), - cost: Field.currency({ - label: "Cost", - scale: 2, - min: 0 - }), - // SKU and Inventory - sku: Field.text({ - label: "SKU", - maxLength: 50, - unique: true - }), - quantity_on_hand: Field.number({ - label: "Quantity on Hand", - min: 0, - defaultValue: 0 - }), - reorder_point: Field.number({ - label: "Reorder Point", - min: 0 - }), - // Status - is_active: Field.boolean({ - label: "Active", - defaultValue: true - }), - is_taxable: Field.boolean({ - label: "Taxable", - defaultValue: true - }), - // Relationships - product_manager: Field.lookup("user", { - label: "Product Manager" - }), - // Images and Assets - image_url: Field.url({ - label: "Product Image" - }), - datasheet_url: Field.url({ - label: "Datasheet URL" - }) - }, - // Database indexes - indexes: [ - { fields: ["name"] }, - { fields: ["sku"], unique: true }, - { fields: ["category"] }, - { fields: ["is_active"] } - ], - // Enable advanced features - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete", "search"], - files: true, - feeds: true, - trash: true, - mru: true - }, - // Validation Rules - validations: [ - { - name: "price_positive", - type: "script", - severity: "error", - message: "List Price must be positive", - condition: "list_price < 0" - }, - { - name: "cost_less_than_price", - type: "script", - severity: "warning", - message: "Cost should be less than List Price", - condition: "cost >= list_price" - } - ] -}); - -// ../app-crm/src/objects/quote.object.ts -init_data(); -var Quote = ObjectSchema3.create({ - name: "quote", - label: "Quote", - pluralLabel: "Quotes", - icon: "file-text", - description: "Price quotes for customers", - titleFormat: "{quote_number} - {name}", - compactLayout: ["quote_number", "name", "account", "status", "total_price"], - fields: { - // AutoNumber field - quote_number: Field.autonumber({ - label: "Quote Number", - format: "QTE-{0000}" - }), - // Basic Information - name: Field.text({ - label: "Quote Name", - required: true, - searchable: true, - maxLength: 255 - }), - // Relationships - account: Field.lookup("account", { - label: "Account", - required: true - }), - contact: Field.lookup("contact", { - label: "Contact", - required: true, - referenceFilters: [ - "account = {account}" - ] - }), - opportunity: Field.lookup("opportunity", { - label: "Opportunity", - referenceFilters: [ - "account = {account}" - ] - }), - owner: Field.lookup("user", { - label: "Quote Owner", - required: true - }), - // Status - status: Field.select({ - label: "Status", - options: [ - { label: "Draft", value: "draft", color: "#999999", default: true }, - { label: "In Review", value: "in_review", color: "#FFA500" }, - { label: "Presented", value: "presented", color: "#4169E1" }, - { label: "Accepted", value: "accepted", color: "#00AA00" }, - { label: "Rejected", value: "rejected", color: "#FF0000" }, - { label: "Expired", value: "expired", color: "#666666" } - ], - required: true - }), - // Dates - quote_date: Field.date({ - label: "Quote Date", - required: true, - defaultValue: "TODAY()" - }), - expiration_date: Field.date({ - label: "Expiration Date", - required: true - }), - // Pricing - subtotal: Field.currency({ - label: "Subtotal", - scale: 2, - readonly: true - }), - discount: Field.percent({ - label: "Discount %", - scale: 2, - min: 0, - max: 100 - }), - discount_amount: Field.currency({ - label: "Discount Amount", - scale: 2, - readonly: true - }), - tax: Field.currency({ - label: "Tax", - scale: 2 - }), - shipping_handling: Field.currency({ - label: "Shipping & Handling", - scale: 2 - }), - total_price: Field.currency({ - label: "Total Price", - scale: 2, - readonly: true - }), - // Terms - payment_terms: Field.select({ - label: "Payment Terms", - options: [ - { label: "Net 15", value: "net_15" }, - { label: "Net 30", value: "net_30", default: true }, - { label: "Net 60", value: "net_60" }, - { label: "Net 90", value: "net_90" }, - { label: "Due on Receipt", value: "due_on_receipt" } - ] - }), - shipping_terms: Field.text({ - label: "Shipping Terms", - maxLength: 255 - }), - // Billing & Shipping Address - billing_address: Field.address({ - label: "Billing Address", - addressFormat: "international" - }), - shipping_address: Field.address({ - label: "Shipping Address", - addressFormat: "international" - }), - // Notes - description: Field.markdown({ - label: "Description" - }), - internal_notes: Field.textarea({ - label: "Internal Notes" - }) - }, - // Database indexes - indexes: [ - { fields: ["account"] }, - { fields: ["opportunity"] }, - { fields: ["owner"] }, - { fields: ["status"] }, - { fields: ["quote_date"] } - ], - // Enable advanced features - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - apiMethods: ["get", "list", "create", "update", "delete", "search", "export"], - files: true, - feeds: true, - activities: true, - trash: true, - mru: true - }, - // Validation Rules - validations: [ - { - name: "expiration_after_quote", - type: "script", - severity: "error", - message: "Expiration Date must be after Quote Date", - condition: "expiration_date <= quote_date" - }, - { - name: "valid_discount", - type: "script", - severity: "error", - message: "Discount cannot exceed 100%", - condition: "discount > 100" - } - ], - // Workflow Rules - workflows: [ - { - name: "quote_expired_check", - objectName: "quote", - triggerType: "on_read", - criteria: 'expiration_date < TODAY() AND status NOT IN ("accepted", "rejected", "expired")', - actions: [ - { - name: "mark_expired", - type: "field_update", - field: "status", - value: '"expired"' - } - ], - active: true - } - ] -}); - -// ../app-crm/src/objects/task.object.ts -init_data(); -var Task3 = ObjectSchema3.create({ - name: "task", - label: "Task", - pluralLabel: "Tasks", - icon: "check-square", - description: "Activities and to-do items", - fields: { - // Task Information - subject: Field.text({ - label: "Subject", - required: true, - searchable: true, - maxLength: 255 - }), - description: Field.markdown({ - label: "Description" - }), - // Task Management - status: Field.select({ - label: "Status", - required: true, - options: [ - { label: "Not Started", value: "not_started", color: "#808080", default: true }, - { label: "In Progress", value: "in_progress", color: "#FFA500" }, - { label: "Waiting", value: "waiting", color: "#FFD700" }, - { label: "Completed", value: "completed", color: "#00AA00" }, - { label: "Deferred", value: "deferred", color: "#999999" } - ] - }), - priority: Field.select({ - label: "Priority", - required: true, - options: [ - { label: "Low", value: "low", color: "#4169E1", default: true }, - { label: "Normal", value: "normal", color: "#00AA00" }, - { label: "High", value: "high", color: "#FFA500" }, - { label: "Urgent", value: "urgent", color: "#FF0000" } - ] - }), - type: Field.select({ - label: "Task Type", - options: [ - { label: "Call", value: "call" }, - { label: "Email", value: "email" }, - { label: "Meeting", value: "meeting" }, - { label: "Follow-up", value: "follow_up" }, - { label: "Demo", value: "demo" }, - { label: "Other", value: "other" } - ] - }), - // Dates - due_date: Field.date({ - label: "Due Date" - }), - reminder_date: Field.datetime({ - label: "Reminder Date/Time" - }), - completed_date: Field.datetime({ - label: "Completed Date", - readonly: true - }), - // Assignment - owner: Field.lookup("user", { - label: "Assigned To", - required: true - }), - // Related To (Polymorphic relationship - can link to multiple object types) - related_to_type: Field.select({ - label: "Related To Type", - options: [ - { label: "Account", value: "account" }, - { label: "Contact", value: "contact" }, - { label: "Opportunity", value: "opportunity" }, - { label: "Lead", value: "lead" }, - { label: "Case", value: "case" } - ] - }), - related_to_account: Field.lookup("account", { - label: "Related Account" - }), - related_to_contact: Field.lookup("contact", { - label: "Related Contact" - }), - related_to_opportunity: Field.lookup("opportunity", { - label: "Related Opportunity" - }), - related_to_lead: Field.lookup("lead", { - label: "Related Lead" - }), - related_to_case: Field.lookup("case", { - label: "Related Case" - }), - // Recurrence (for recurring tasks) - is_recurring: Field.boolean({ - label: "Recurring Task", - defaultValue: false - }), - recurrence_type: Field.select({ - label: "Recurrence Type", - options: [ - { label: "Daily", value: "daily" }, - { label: "Weekly", value: "weekly" }, - { label: "Monthly", value: "monthly" }, - { label: "Yearly", value: "yearly" } - ] - }), - recurrence_interval: Field.number({ - label: "Recurrence Interval", - defaultValue: 1, - min: 1 - }), - recurrence_end_date: Field.date({ - label: "Recurrence End Date" - }), - // Flags - is_completed: Field.boolean({ - label: "Is Completed", - defaultValue: false, - readonly: true - }), - is_overdue: Field.boolean({ - label: "Is Overdue", - defaultValue: false, - readonly: true - }), - // Progress - progress_percent: Field.percent({ - label: "Progress (%)", - min: 0, - max: 100, - defaultValue: 0 - }), - // Time tracking - estimated_hours: Field.number({ - label: "Estimated Hours", - scale: 2, - min: 0 - }), - actual_hours: Field.number({ - label: "Actual Hours", - scale: 2, - min: 0 - }) - }, - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - files: true, - feeds: true, - // Enable social feed, comments, and mentions - activities: true, - // Enable tasks and events tracking - trash: true, - mru: true - // Track Most Recently Used - }, - // Database indexes for performance - indexes: [ - { fields: ["status"] }, - { fields: ["priority"] }, - { fields: ["owner"] }, - { fields: ["due_date"] } - ], - titleFormat: "{subject}", - compactLayout: ["subject", "status", "priority", "due_date", "owner"], - // Removed: list_views and form_views belong in UI configuration, not object definition - validations: [ - { - name: "completed_date_required", - type: "script", - severity: "error", - message: "Completed date is required when status is Completed", - condition: 'status = "completed" AND ISBLANK(completed_date)' - }, - { - name: "recurrence_fields_required", - type: "script", - severity: "error", - message: "Recurrence type is required for recurring tasks", - condition: "is_recurring = true AND ISBLANK(recurrence_type)" - }, - { - name: "related_to_required", - type: "script", - severity: "warning", - message: "At least one related record should be selected", - condition: "ISBLANK(related_to_account) AND ISBLANK(related_to_contact) AND ISBLANK(related_to_opportunity) AND ISBLANK(related_to_lead) AND ISBLANK(related_to_case)" - } - ], - workflows: [ - { - name: "set_completed_flag", - objectName: "task", - triggerType: "on_create_or_update", - criteria: "ISCHANGED(status)", - active: true, - actions: [ - { - name: "update_completed_flag", - type: "field_update", - field: "is_completed", - value: 'status = "completed"' - } - ] - }, - { - name: "set_completed_date", - objectName: "task", - triggerType: "on_update", - criteria: 'ISCHANGED(status) AND status = "completed"', - active: true, - actions: [ - { - name: "set_date", - type: "field_update", - field: "completed_date", - value: "NOW()" - }, - { - name: "set_progress", - type: "field_update", - field: "progress_percent", - value: "100" - } - ] - }, - { - name: "check_overdue", - objectName: "task", - triggerType: "on_create_or_update", - criteria: "due_date < TODAY() AND is_completed = false", - active: true, - actions: [ - { - name: "set_overdue_flag", - type: "field_update", - field: "is_overdue", - value: "true" - } - ] - }, - { - name: "notify_on_urgent", - objectName: "task", - triggerType: "on_create_or_update", - criteria: 'priority = "urgent" AND is_completed = false', - active: true, - actions: [ - { - name: "email_owner", - type: "email_alert", - template: "urgent_task_alert", - recipients: ["{owner.email}"] - } - ] - } - ] -}); - -// ../app-crm/src/apis/index.ts -var apis_exports = {}; -__export(apis_exports, { - LeadConvertApi: () => LeadConvertApi, - PipelineStatsApi: () => PipelineStatsApi -}); - -// ../app-crm/src/apis/lead-convert.api.ts -var LeadConvertApi = ApiEndpoint.create({ - name: "lead_convert", - path: "/api/v1/crm/leads/convert", - method: "POST", - summary: "Convert Lead to Account/Contact", - type: "flow", - target: "flow_lead_conversion_v2", - inputMapping: [ - { source: "body.leadId", target: "leadRecordId" }, - { source: "body.ownerId", target: "newOwnerId" } - ] -}); - -// ../app-crm/src/apis/pipeline-stats.api.ts -var PipelineStatsApi = ApiEndpoint.create({ - name: "get_pipeline_stats", - path: "/api/v1/crm/stats/pipeline", - method: "GET", - summary: "Get Pipeline Statistics", - description: "Returns the total value of open opportunities grouped by stage", - type: "script", - target: "server/scripts/pipeline_stats.ts", - authRequired: true, - cacheTtl: 300 -}); - -// ../app-crm/src/actions/index.ts -var actions_exports = {}; -__export(actions_exports, { - CloneOpportunityAction: () => CloneOpportunityAction, - CloseCaseAction: () => CloseCaseAction, - ConvertLeadAction: () => ConvertLeadAction, - CreateCampaignAction: () => CreateCampaignAction, - EscalateCaseAction: () => EscalateCaseAction, - ExportToCsvAction: () => ExportToCsvAction, - LogCallAction: () => LogCallAction, - MarkPrimaryContactAction: () => MarkPrimaryContactAction, - MassUpdateStageAction: () => MassUpdateStageAction, - SendEmailAction: () => SendEmailAction -}); - -// ../app-crm/src/actions/case.actions.ts -var EscalateCaseAction = { - name: "escalate_case", - label: "Escalate Case", - objectName: "case", - icon: "alert-triangle", - type: "modal", - target: "escalate_case_modal", - locations: ["record_header", "list_item"], - visible: "is_escalated = false AND is_closed = false", - params: [ - { - name: "reason", - label: "Escalation Reason", - type: "textarea", - required: true - } - ], - confirmText: "This will escalate the case to the escalation team. Continue?", - successMessage: "Case escalated successfully!", - refreshAfter: true -}; -var CloseCaseAction = { - name: "close_case", - label: "Close Case", - objectName: "case", - icon: "check-circle", - type: "modal", - target: "close_case_modal", - locations: ["record_header"], - visible: "is_closed = false", - params: [ - { - name: "resolution", - label: "Resolution", - type: "textarea", - required: true - } - ], - confirmText: "Are you sure you want to close this case?", - successMessage: "Case closed successfully!", - refreshAfter: true -}; - -// ../app-crm/src/actions/contact.actions.ts -var MarkPrimaryContactAction = { - name: "mark_primary", - label: "Mark as Primary Contact", - objectName: "contact", - icon: "star", - type: "script", - target: "markAsPrimaryContact", - locations: ["record_header", "list_item"], - visible: "is_primary = false", - confirmText: "Mark this contact as the primary contact for the account?", - successMessage: "Contact marked as primary!", - refreshAfter: true -}; -var SendEmailAction = { - name: "send_email", - label: "Send Email", - objectName: "contact", - icon: "mail", - type: "modal", - target: "email_composer", - locations: ["record_header", "list_item"], - visible: "email_opt_out = false", - refreshAfter: false -}; - -// ../app-crm/src/actions/global.actions.ts -var LogCallAction = { - name: "log_call", - label: "Log a Call", - icon: "phone", - type: "modal", - target: "call_log_modal", - locations: ["record_header", "list_item", "record_related"], - params: [ - { - name: "subject", - label: "Call Subject", - type: "text", - required: true - }, - { - name: "duration", - label: "Duration (minutes)", - type: "number", - required: true - }, - { - name: "notes", - label: "Call Notes", - type: "textarea", - required: false - } - ], - successMessage: "Call logged successfully!", - refreshAfter: true -}; -var ExportToCsvAction = { - name: "export_csv", - label: "Export to CSV", - icon: "download", - type: "script", - target: "exportToCSV", - locations: ["list_toolbar"], - successMessage: "Export completed!", - refreshAfter: false -}; - -// ../app-crm/src/actions/lead.actions.ts -var ConvertLeadAction = { - name: "convert_lead", - label: "Convert Lead", - objectName: "lead", - icon: "arrow-right-circle", - type: "flow", - target: "lead_conversion", - locations: ["record_header", "list_item"], - visible: 'status = "qualified" AND is_converted = false', - confirmText: "Are you sure you want to convert this lead?", - successMessage: "Lead converted successfully!", - refreshAfter: true -}; -var CreateCampaignAction = { - name: "create_campaign", - label: "Add to Campaign", - objectName: "lead", - icon: "send", - type: "modal", - target: "add_to_campaign_modal", - locations: ["list_toolbar"], - params: [ - { - name: "campaign", - label: "Campaign", - type: "lookup", - required: true - } - ], - successMessage: "Leads added to campaign!", - refreshAfter: true -}; - -// ../app-crm/src/actions/opportunity.actions.ts -var CloneOpportunityAction = { - name: "clone_opportunity", - label: "Clone Opportunity", - objectName: "opportunity", - icon: "copy", - type: "script", - target: "cloneRecord", - locations: ["record_header", "record_more"], - successMessage: "Opportunity cloned successfully!", - refreshAfter: true -}; -var MassUpdateStageAction = { - name: "mass_update_stage", - label: "Update Stage", - objectName: "opportunity", - icon: "layers", - type: "modal", - target: "mass_update_stage_modal", - locations: ["list_toolbar"], - params: [ - { - name: "stage", - label: "New Stage", - type: "select", - required: true, - options: [ - { label: "Prospecting", value: "prospecting" }, - { label: "Qualification", value: "qualification" }, - { label: "Needs Analysis", value: "needs_analysis" }, - { label: "Proposal", value: "proposal" }, - { label: "Negotiation", value: "negotiation" }, - { label: "Closed Won", value: "closed_won" }, - { label: "Closed Lost", value: "closed_lost" } - ] - } - ], - successMessage: "Opportunities updated successfully!", - refreshAfter: true -}; - -// ../app-crm/src/dashboards/index.ts -var dashboards_exports = {}; -__export(dashboards_exports, { - ExecutiveDashboard: () => ExecutiveDashboard, - SalesDashboard: () => SalesDashboard, - ServiceDashboard: () => ServiceDashboard -}); - -// ../app-crm/src/dashboards/executive.dashboard.ts -var ExecutiveDashboard = { - name: "executive_dashboard", - label: "Executive Overview", - description: "High-level business metrics", - widgets: [ - // Row 1: Revenue Metrics - { - id: "total_revenue_ytd", - title: "Total Revenue (YTD)", - type: "metric", - object: "opportunity", - filter: { stage: "closed_won", close_date: { $gte: "{current_year_start}" } }, - valueField: "amount", - aggregate: "sum", - layout: { x: 0, y: 0, w: 3, h: 2 }, - options: { prefix: "$", color: "#00AA00" } - }, - { - id: "total_accounts", - title: "Total Accounts", - type: "metric", - object: "account", - filter: { is_active: true }, - aggregate: "count", - layout: { x: 3, y: 0, w: 3, h: 2 }, - options: { color: "#4169E1" } - }, - { - id: "total_contacts", - title: "Total Contacts", - type: "metric", - object: "contact", - aggregate: "count", - layout: { x: 6, y: 0, w: 3, h: 2 }, - options: { color: "#9370DB" } - }, - { - id: "total_leads", - title: "Total Leads", - type: "metric", - object: "lead", - filter: { is_converted: false }, - aggregate: "count", - layout: { x: 9, y: 0, w: 3, h: 2 }, - options: { color: "#FFA500" } - }, - // Row 2: Revenue Analysis - { - id: "revenue_by_industry", - title: "Revenue by Industry", - type: "bar", - object: "opportunity", - filter: { stage: "closed_won", close_date: { $gte: "{current_year_start}" } }, - categoryField: "account.industry", - valueField: "amount", - aggregate: "sum", - layout: { x: 0, y: 2, w: 6, h: 4 } - }, - { - id: "quarterly_revenue_trend", - title: "Quarterly Revenue Trend", - type: "line", - object: "opportunity", - filter: { stage: "closed_won", close_date: { $gte: "{last_4_quarters}" } }, - categoryField: "close_date", - valueField: "amount", - aggregate: "sum", - layout: { x: 6, y: 2, w: 6, h: 4 }, - options: { dateGranularity: "quarter" } - }, - // Row 3: Customer & Activity Metrics - { - id: "new_accounts_by_month", - title: "New Accounts by Month", - type: "bar", - object: "account", - filter: { created_date: { $gte: "{last_6_months}" } }, - categoryField: "created_date", - aggregate: "count", - layout: { x: 0, y: 6, w: 4, h: 4 }, - options: { dateGranularity: "month" } - }, - { - id: "lead_conversion_rate", - title: "Lead Conversion Rate", - type: "metric", - object: "lead", - valueField: "is_converted", - aggregate: "avg", - layout: { x: 4, y: 6, w: 4, h: 4 }, - options: { suffix: "%", color: "#00AA00" } - }, - { - id: "top_accounts_by_revenue", - title: "Top Accounts by Revenue", - type: "table", - object: "account", - aggregate: "count", - layout: { x: 8, y: 6, w: 4, h: 4 }, - options: { - columns: ["name", "annual_revenue", "type"], - sortBy: "annual_revenue", - sortOrder: "desc", - limit: 10 - } - } - ] -}; - -// ../app-crm/src/dashboards/sales.dashboard.ts -var SalesDashboard = { - name: "sales_dashboard", - label: "Sales Performance", - description: "Key sales metrics and pipeline overview", - widgets: [ - // Row 1: Key Metrics - { - id: "total_pipeline_value", - title: "Total Pipeline Value", - type: "metric", - object: "opportunity", - filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, - valueField: "amount", - aggregate: "sum", - layout: { x: 0, y: 0, w: 3, h: 2 }, - options: { prefix: "$", color: "#4169E1" } - }, - { - id: "closed_won_this_quarter", - title: "Closed Won This Quarter", - type: "metric", - object: "opportunity", - filter: { stage: "closed_won", close_date: { $gte: "{current_quarter_start}" } }, - valueField: "amount", - aggregate: "sum", - layout: { x: 3, y: 0, w: 3, h: 2 }, - options: { prefix: "$", color: "#00AA00" } - }, - { - id: "open_opportunities", - title: "Open Opportunities", - type: "metric", - object: "opportunity", - filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, - aggregate: "count", - layout: { x: 6, y: 0, w: 3, h: 2 }, - options: { color: "#FFA500" } - }, - { - id: "win_rate", - title: "Win Rate", - type: "metric", - object: "opportunity", - filter: { close_date: { $gte: "{current_quarter_start}" } }, - valueField: "stage", - aggregate: "count", - layout: { x: 9, y: 0, w: 3, h: 2 }, - options: { suffix: "%", color: "#9370DB" } - }, - // Row 2: Pipeline Analysis - { - id: "pipeline_by_stage", - title: "Pipeline by Stage", - type: "funnel", - object: "opportunity", - filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, - categoryField: "stage", - valueField: "amount", - aggregate: "sum", - layout: { x: 0, y: 2, w: 6, h: 4 }, - options: { showValues: true } - }, - { - id: "opportunities_by_owner", - title: "Opportunities by Owner", - type: "bar", - object: "opportunity", - filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, - categoryField: "owner", - valueField: "amount", - aggregate: "sum", - layout: { x: 6, y: 2, w: 6, h: 4 }, - options: { horizontal: true } - }, - // Row 3: Trends - { - id: "monthly_revenue_trend", - title: "Monthly Revenue Trend", - type: "line", - object: "opportunity", - filter: { stage: "closed_won", close_date: { $gte: "{last_12_months}" } }, - categoryField: "close_date", - valueField: "amount", - aggregate: "sum", - layout: { x: 0, y: 6, w: 8, h: 4 }, - options: { dateGranularity: "month", showTrend: true } - }, - { - id: "top_opportunities", - title: "Top Opportunities", - type: "table", - object: "opportunity", - filter: { stage: { $nin: ["closed_won", "closed_lost"] } }, - aggregate: "count", - layout: { x: 8, y: 6, w: 4, h: 4 }, - options: { - columns: ["name", "amount", "stage", "close_date"], - sortBy: "amount", - sortOrder: "desc", - limit: 10 - } - } - ] -}; - -// ../app-crm/src/dashboards/service.dashboard.ts -var ServiceDashboard = { - name: "service_dashboard", - label: "Customer Service", - description: "Support case metrics and performance", - widgets: [ - // Row 1: Key Metrics - { - id: "open_cases", - title: "Open Cases", - type: "metric", - object: "case", - filter: { is_closed: false }, - aggregate: "count", - layout: { x: 0, y: 0, w: 3, h: 2 }, - options: { color: "#FFA500" } - }, - { - id: "critical_cases", - title: "Critical Cases", - type: "metric", - object: "case", - filter: { priority: "critical", is_closed: false }, - aggregate: "count", - layout: { x: 3, y: 0, w: 3, h: 2 }, - options: { color: "#FF0000" } - }, - { - id: "avg_resolution_time", - title: "Avg Resolution Time (hrs)", - type: "metric", - object: "case", - filter: { is_closed: true }, - valueField: "resolution_time_hours", - aggregate: "avg", - layout: { x: 6, y: 0, w: 3, h: 2 }, - options: { suffix: "h", color: "#4169E1" } - }, - { - id: "sla_violations", - title: "SLA Violations", - type: "metric", - object: "case", - filter: { is_sla_violated: true }, - aggregate: "count", - layout: { x: 9, y: 0, w: 3, h: 2 }, - options: { color: "#FF4500" } - }, - // Row 2: Case Distribution - { - id: "cases_by_status", - title: "Cases by Status", - type: "pie", - object: "case", - filter: { is_closed: false }, - categoryField: "status", - aggregate: "count", - layout: { x: 0, y: 2, w: 4, h: 4 }, - options: { showLegend: true } - }, - { - id: "cases_by_priority", - title: "Cases by Priority", - type: "pie", - object: "case", - filter: { is_closed: false }, - categoryField: "priority", - aggregate: "count", - layout: { x: 4, y: 2, w: 4, h: 4 }, - options: { showLegend: true } - }, - { - id: "cases_by_origin", - title: "Cases by Origin", - type: "bar", - object: "case", - categoryField: "origin", - aggregate: "count", - layout: { x: 8, y: 2, w: 4, h: 4 } - }, - // Row 3: Trends and Lists - { - id: "daily_case_volume", - title: "Daily Case Volume", - type: "line", - object: "case", - filter: { created_date: { $gte: "{last_30_days}" } }, - categoryField: "created_date", - aggregate: "count", - layout: { x: 0, y: 6, w: 8, h: 4 }, - options: { dateGranularity: "day" } - }, - { - id: "my_open_cases", - title: "My Open Cases", - type: "table", - object: "case", - filter: { owner: "{current_user}", is_closed: false }, - aggregate: "count", - layout: { x: 8, y: 6, w: 4, h: 4 }, - options: { - columns: ["case_number", "subject", "priority", "status"], - sortBy: "priority", - sortOrder: "desc", - limit: 10 - } - } - ] -}; - -// ../app-crm/src/reports/index.ts -var reports_exports = {}; -__export(reports_exports, { - AccountsByIndustryTypeReport: () => AccountsByIndustryTypeReport, - CasesByStatusPriorityReport: () => CasesByStatusPriorityReport, - ContactsByAccountReport: () => ContactsByAccountReport, - LeadsBySourceReport: () => LeadsBySourceReport, - OpportunitiesByStageReport: () => OpportunitiesByStageReport, - SlaPerformanceReport: () => SlaPerformanceReport, - TasksByOwnerReport: () => TasksByOwnerReport, - WonOpportunitiesByOwnerReport: () => WonOpportunitiesByOwnerReport -}); - -// ../app-crm/src/reports/account.report.ts -var AccountsByIndustryTypeReport = { - name: "accounts_by_industry_type", - label: "Accounts by Industry and Type", - description: "Matrix report showing accounts by industry and type", - objectName: "account", - type: "matrix", - columns: [ - { field: "name", aggregate: "count" }, - { field: "annual_revenue", aggregate: "sum" } - ], - groupingsDown: [{ field: "industry", sortOrder: "asc" }], - groupingsAcross: [{ field: "type", sortOrder: "asc" }], - filter: { is_active: true } -}; - -// ../app-crm/src/reports/case.report.ts -var CasesByStatusPriorityReport = { - name: "cases_by_status_priority", - label: "Cases by Status and Priority", - description: "Summary of cases by status and priority", - objectName: "case", - type: "summary", - columns: [ - { field: "case_number", label: "Case Number" }, - { field: "subject", label: "Subject" }, - { field: "account", label: "Account" }, - { field: "owner", label: "Owner" }, - { field: "resolution_time_hours", label: "Resolution Time", aggregate: "avg" } - ], - groupingsDown: [ - { field: "status", sortOrder: "asc" }, - { field: "priority", sortOrder: "desc" } - ], - chart: { type: "bar", title: "Cases by Status", showLegend: true, xAxis: "status", yAxis: "case_number" } -}; -var SlaPerformanceReport = { - name: "sla_performance", - label: "SLA Performance Report", - description: "Analysis of SLA compliance", - objectName: "case", - type: "summary", - columns: [ - { field: "case_number", aggregate: "count" }, - { field: "is_sla_violated", label: "SLA Violated", aggregate: "count" }, - { field: "resolution_time_hours", label: "Avg Resolution Time", aggregate: "avg" } - ], - groupingsDown: [{ field: "priority", sortOrder: "desc" }], - filter: { is_closed: true }, - chart: { type: "column", title: "SLA Violations by Priority", showLegend: false, xAxis: "priority", yAxis: "is_sla_violated" } -}; - -// ../app-crm/src/reports/contact.report.ts -var ContactsByAccountReport = { - name: "contacts_by_account", - label: "Contacts by Account", - description: "List of contacts grouped by account", - objectName: "contact", - type: "summary", - columns: [ - { field: "full_name", label: "Name" }, - { field: "title", label: "Title" }, - { field: "email", label: "Email" }, - { field: "phone", label: "Phone" }, - { field: "is_primary", label: "Primary Contact" } - ], - groupingsDown: [{ field: "account", sortOrder: "asc" }] -}; - -// ../app-crm/src/reports/lead.report.ts -var LeadsBySourceReport = { - name: "leads_by_source", - label: "Leads by Source and Status", - description: "Lead pipeline analysis", - objectName: "lead", - type: "summary", - columns: [ - { field: "full_name", label: "Name" }, - { field: "company", label: "Company" }, - { field: "rating", label: "Rating" } - ], - groupingsDown: [ - { field: "lead_source", sortOrder: "asc" }, - { field: "status", sortOrder: "asc" } - ], - filter: { is_converted: false }, - chart: { type: "pie", title: "Leads by Source", showLegend: true, xAxis: "lead_source", yAxis: "full_name" } -}; - -// ../app-crm/src/reports/opportunity.report.ts -var OpportunitiesByStageReport = { - name: "opportunities_by_stage", - label: "Opportunities by Stage", - description: "Summary of opportunities grouped by stage", - objectName: "opportunity", - type: "summary", - columns: [ - { field: "name", label: "Opportunity Name" }, - { field: "account", label: "Account" }, - { field: "amount", label: "Amount", aggregate: "sum" }, - { field: "close_date", label: "Close Date" }, - { field: "probability", label: "Probability", aggregate: "avg" } - ], - groupingsDown: [{ field: "stage", sortOrder: "asc" }], - filter: { stage: { $ne: "closed_lost" }, close_date: { $gte: "{current_year_start}" } }, - chart: { type: "bar", title: "Pipeline by Stage", showLegend: true, xAxis: "stage", yAxis: "amount" } -}; -var WonOpportunitiesByOwnerReport = { - name: "won_opportunities_by_owner", - label: "Won Opportunities by Owner", - description: "Closed won opportunities grouped by owner", - objectName: "opportunity", - type: "summary", - columns: [ - { field: "name", label: "Opportunity Name" }, - { field: "account", label: "Account" }, - { field: "amount", label: "Amount", aggregate: "sum" }, - { field: "close_date", label: "Close Date" } - ], - groupingsDown: [{ field: "owner", sortOrder: "desc" }], - filter: { stage: "closed_won" }, - chart: { type: "column", title: "Revenue by Sales Rep", showLegend: false, xAxis: "owner", yAxis: "amount" } -}; - -// ../app-crm/src/reports/task.report.ts -var TasksByOwnerReport = { - name: "tasks_by_owner", - label: "Tasks by Owner", - description: "Task summary by owner", - objectName: "task", - type: "summary", - columns: [ - { field: "subject", label: "Subject" }, - { field: "status", label: "Status" }, - { field: "priority", label: "Priority" }, - { field: "due_date", label: "Due Date" }, - { field: "actual_hours", label: "Hours", aggregate: "sum" } - ], - groupingsDown: [{ field: "owner", sortOrder: "asc" }], - filter: { is_completed: false } -}; - -// ../app-crm/src/flows/campaign-enrollment.flow.ts -var CampaignEnrollmentFlow = { - name: "campaign_enrollment", - label: "Enroll Leads in Campaign", - description: "Bulk enroll leads into marketing campaigns", - type: "schedule", - variables: [ - { name: "campaignId", type: "text", isInput: true, isOutput: false }, - { name: "leadStatus", type: "text", isInput: true, isOutput: false } - ], - nodes: [ - { id: "start", type: "start", label: "Start (Monday 9 AM)", config: { schedule: "0 9 * * 1" } }, - { - id: "get_campaign", - type: "get_record", - label: "Get Campaign", - config: { objectName: "campaign", filter: { id: "{campaignId}" }, outputVariable: "campaignRecord" } - }, - { - id: "query_leads", - type: "get_record", - label: "Find Eligible Leads", - config: { objectName: "lead", filter: { status: "{leadStatus}", is_converted: false, email: { $ne: null } }, limit: 1e3, outputVariable: "leadList" } - }, - { - id: "loop_leads", - type: "loop", - label: "Process Each Lead", - config: { collection: "{leadList}", iteratorVariable: "currentLead" } - }, - { - id: "create_campaign_member", - type: "create_record", - label: "Add to Campaign", - config: { - objectName: "campaign_member", - fields: { campaign: "{campaignId}", lead: "{currentLead.id}", status: "sent", added_date: "{NOW()}" } - } - }, - { - id: "update_campaign_stats", - type: "update_record", - label: "Update Campaign Stats", - config: { objectName: "campaign", filter: { id: "{campaignId}" }, fields: { num_sent: "{leadList.length}" } } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "get_campaign", type: "default" }, - { id: "e2", source: "get_campaign", target: "query_leads", type: "default" }, - { id: "e3", source: "query_leads", target: "loop_leads", type: "default" }, - { id: "e4", source: "loop_leads", target: "create_campaign_member", type: "default" }, - { id: "e5", source: "create_campaign_member", target: "update_campaign_stats", type: "default" }, - { id: "e6", source: "update_campaign_stats", target: "end", type: "default" } - ] -}; - -// ../app-crm/src/flows/case-escalation.flow.ts -var CaseEscalationFlow = { - name: "case_escalation", - label: "Case Escalation Process", - description: "Automatically escalate high-priority cases", - type: "record_change", - variables: [ - { name: "caseId", type: "text", isInput: true, isOutput: false } - ], - nodes: [ - { - id: "start", - type: "start", - label: "Start", - config: { objectName: "case", criteria: 'priority = "critical" OR (priority = "high" AND account.type = "customer")' } - }, - { - id: "get_case", - type: "get_record", - label: "Get Case Record", - config: { objectName: "case", filter: { id: "{caseId}" }, outputVariable: "caseRecord" } - }, - { - id: "assign_senior_agent", - type: "update_record", - label: "Assign to Senior Agent", - config: { - objectName: "case", - filter: { id: "{caseId}" }, - fields: { owner: "{caseRecord.owner.manager}", is_escalated: true, escalated_date: "{NOW()}" } - } - }, - { - id: "create_task", - type: "create_record", - label: "Create Follow-up Task", - config: { - objectName: "task", - fields: { - subject: "Follow up on escalated case: {caseRecord.case_number}", - related_to: "{caseId}", - owner: "{caseRecord.owner}", - priority: "high", - status: "not_started", - due_date: "{TODAY() + 1}" - } - } - }, - { - id: "notify_team", - type: "script", - label: "Notify Support Team", - config: { - actionType: "email", - template: "case_escalated", - recipients: ["{caseRecord.owner}", "{caseRecord.owner.manager}", "support-team@example.com"], - variables: { - caseNumber: "{caseRecord.case_number}", - priority: "{caseRecord.priority}", - accountName: "{caseRecord.account.name}" - } - } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "get_case", type: "default" }, - { id: "e2", source: "get_case", target: "assign_senior_agent", type: "default" }, - { id: "e3", source: "assign_senior_agent", target: "create_task", type: "default" }, - { id: "e4", source: "create_task", target: "notify_team", type: "default" }, - { id: "e5", source: "notify_team", target: "end", type: "default" } - ] -}; - -// ../app-crm/src/flows/lead-conversion.flow.ts -var LeadConversionFlow = { - name: "lead_conversion", - label: "Lead Conversion Process", - description: "Automated flow to convert qualified leads to accounts, contacts, and opportunities", - type: "screen", - variables: [ - { name: "leadId", type: "text", isInput: true, isOutput: false }, - { name: "createOpportunity", type: "boolean", isInput: true, isOutput: false }, - { name: "opportunityName", type: "text", isInput: true, isOutput: false }, - { name: "opportunityAmount", type: "text", isInput: true, isOutput: false } - ], - nodes: [ - { id: "start", type: "start", label: "Start", config: { objectName: "lead" } }, - { - id: "screen_1", - type: "screen", - label: "Conversion Details", - config: { - fields: [ - { name: "createOpportunity", label: "Create Opportunity?", type: "boolean", required: true }, - { name: "opportunityName", label: "Opportunity Name", type: "text", required: true, visibleWhen: "{createOpportunity} == true" }, - { name: "opportunityAmount", label: "Opportunity Amount", type: "currency", visibleWhen: "{createOpportunity} == true" } - ] - } - }, - { - id: "get_lead", - type: "get_record", - label: "Get Lead Record", - config: { objectName: "lead", filter: { id: "{leadId}" }, outputVariable: "leadRecord" } - }, - { - id: "create_account", - type: "create_record", - label: "Create Account", - config: { - objectName: "account", - fields: { - name: "{leadRecord.company}", - phone: "{leadRecord.phone}", - website: "{leadRecord.website}", - industry: "{leadRecord.industry}", - annual_revenue: "{leadRecord.annual_revenue}", - number_of_employees: "{leadRecord.number_of_employees}", - billing_address: "{leadRecord.address}", - owner: "{$User.Id}", - is_active: true - }, - outputVariable: "accountId" - } - }, - { - id: "create_contact", - type: "create_record", - label: "Create Contact", - config: { - objectName: "contact", - fields: { - first_name: "{leadRecord.first_name}", - last_name: "{leadRecord.last_name}", - email: "{leadRecord.email}", - phone: "{leadRecord.phone}", - title: "{leadRecord.title}", - account: "{accountId}", - is_primary: true, - owner: "{$User.Id}" - }, - outputVariable: "contactId" - } - }, - { - id: "decision_opportunity", - type: "decision", - label: "Create Opportunity?", - config: { condition: "{createOpportunity} == true" } - }, - { - id: "create_opportunity", - type: "create_record", - label: "Create Opportunity", - config: { - objectName: "opportunity", - fields: { - name: "{opportunityName}", - account: "{accountId}", - contact: "{contactId}", - amount: "{opportunityAmount}", - stage: "prospecting", - probability: 10, - lead_source: "{leadRecord.lead_source}", - close_date: "{TODAY() + 90}", - owner: "{$User.Id}" - }, - outputVariable: "opportunityId" - } - }, - { - id: "mark_converted", - type: "update_record", - label: "Mark Lead as Converted", - config: { - objectName: "lead", - filter: { id: "{leadId}" }, - fields: { - is_converted: true, - converted_date: "{NOW()}", - converted_account: "{accountId}", - converted_contact: "{contactId}", - converted_opportunity: "{opportunityId}" - } - } - }, - { - id: "send_notification", - type: "script", - label: "Send Confirmation Email", - config: { - actionType: "email", - template: "lead_converted_notification", - recipients: ["{$User.Email}"], - variables: { leadName: "{leadRecord.full_name}", accountName: "{accountId.name}", contactName: "{contactId.full_name}" } - } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "screen_1", type: "default" }, - { id: "e2", source: "screen_1", target: "get_lead", type: "default" }, - { id: "e3", source: "get_lead", target: "create_account", type: "default" }, - { id: "e4", source: "create_account", target: "create_contact", type: "default" }, - { id: "e5", source: "create_contact", target: "decision_opportunity", type: "default" }, - { id: "e6", source: "decision_opportunity", target: "create_opportunity", type: "default", condition: "{createOpportunity} == true", label: "Yes" }, - { id: "e7", source: "decision_opportunity", target: "mark_converted", type: "default", condition: "{createOpportunity} != true", label: "No" }, - { id: "e8", source: "create_opportunity", target: "mark_converted", type: "default" }, - { id: "e9", source: "mark_converted", target: "send_notification", type: "default" }, - { id: "e10", source: "send_notification", target: "end", type: "default" } - ] -}; - -// ../app-crm/src/flows/opportunity-approval.flow.ts -var OpportunityApprovalFlow = { - name: "opportunity_approval", - label: "Large Deal Approval", - description: "Approval process for opportunities over $100K", - type: "record_change", - variables: [ - { name: "opportunityId", type: "text", isInput: true, isOutput: false } - ], - nodes: [ - { - id: "start", - type: "start", - label: "Start", - config: { objectName: "opportunity", criteria: 'amount > 100000 AND stage = "proposal"' } - }, - { - id: "get_opportunity", - type: "get_record", - label: "Get Opportunity", - config: { objectName: "opportunity", filter: { id: "{opportunityId}" }, outputVariable: "oppRecord" } - }, - { - id: "approval_step_manager", - type: "connector_action", - label: "Sales Manager Approval", - config: { - actionType: "approval", - approver: "{oppRecord.owner.manager}", - emailTemplate: "opportunity_approval_request", - comments: "required" - } - }, - { - id: "decision_manager", - type: "decision", - label: "Manager Approved?", - config: { condition: '{approval_step_manager.result} == "approved"' } - }, - { - id: "approval_step_director", - type: "connector_action", - label: "Sales Director Approval", - config: { - actionType: "approval", - approver: "{oppRecord.owner.manager.manager}", - emailTemplate: "opportunity_approval_request" - } - }, - { - id: "decision_director", - type: "decision", - label: "Director Approved?", - config: { condition: '{approval_step_director.result} == "approved"' } - }, - { - id: "mark_approved", - type: "update_record", - label: "Mark as Approved", - config: { - objectName: "opportunity", - filter: { id: "{opportunityId}" }, - fields: { approval_status: "approved", approved_date: "{NOW()}" } - } - }, - { - id: "notify_approval", - type: "script", - label: "Send Approval Notification", - config: { actionType: "email", template: "opportunity_approved", recipients: ["{oppRecord.owner}"] } - }, - { - id: "notify_rejection", - type: "script", - label: "Send Rejection Notification", - config: { actionType: "email", template: "opportunity_rejected", recipients: ["{oppRecord.owner}"] } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "get_opportunity", type: "default" }, - { id: "e2", source: "get_opportunity", target: "approval_step_manager", type: "default" }, - { id: "e3", source: "approval_step_manager", target: "decision_manager", type: "default" }, - { id: "e4", source: "decision_manager", target: "approval_step_director", type: "default", condition: '{approval_step_manager.result} == "approved"', label: "Approved" }, - { id: "e5", source: "decision_manager", target: "notify_rejection", type: "default", condition: '{approval_step_manager.result} != "approved"', label: "Rejected" }, - { id: "e6", source: "approval_step_director", target: "decision_director", type: "default" }, - { id: "e7", source: "decision_director", target: "mark_approved", type: "default", condition: '{approval_step_director.result} == "approved"', label: "Approved" }, - { id: "e8", source: "decision_director", target: "notify_rejection", type: "default", condition: '{approval_step_director.result} != "approved"', label: "Rejected" }, - { id: "e9", source: "mark_approved", target: "notify_approval", type: "default" }, - { id: "e10", source: "notify_approval", target: "end", type: "default" }, - { id: "e11", source: "notify_rejection", target: "end", type: "default" } - ] -}; - -// ../app-crm/src/flows/quote-generation.flow.ts -var QuoteGenerationFlow = { - name: "quote_generation", - label: "Generate Quote from Opportunity", - description: "Create a quote based on opportunity details", - type: "screen", - variables: [ - { name: "opportunityId", type: "text", isInput: true, isOutput: false }, - { name: "quoteName", type: "text", isInput: true, isOutput: false }, - { name: "expirationDays", type: "number", isInput: true, isOutput: false }, - { name: "discount", type: "number", isInput: true, isOutput: false } - ], - nodes: [ - { id: "start", type: "start", label: "Start", config: { objectName: "opportunity" } }, - { - id: "screen_1", - type: "screen", - label: "Quote Details", - config: { - fields: [ - { name: "quoteName", label: "Quote Name", type: "text", required: true }, - { name: "expirationDays", label: "Valid For (Days)", type: "number", required: true, defaultValue: 30 }, - { name: "discount", label: "Discount %", type: "percent", defaultValue: 0 } - ] - } - }, - { - id: "get_opportunity", - type: "get_record", - label: "Get Opportunity", - config: { objectName: "opportunity", filter: { id: "{opportunityId}" }, outputVariable: "oppRecord" } - }, - { - id: "create_quote", - type: "create_record", - label: "Create Quote", - config: { - objectName: "quote", - fields: { - name: "{quoteName}", - opportunity: "{opportunityId}", - account: "{oppRecord.account}", - contact: "{oppRecord.contact}", - owner: "{$User.Id}", - status: "draft", - quote_date: "{TODAY()}", - expiration_date: "{TODAY() + expirationDays}", - subtotal: "{oppRecord.amount}", - discount: "{discount}", - discount_amount: "{oppRecord.amount * (discount / 100)}", - total_price: "{oppRecord.amount * (1 - discount / 100)}", - payment_terms: "net_30" - }, - outputVariable: "quoteId" - } - }, - { - id: "update_opportunity", - type: "update_record", - label: "Update Opportunity", - config: { - objectName: "opportunity", - filter: { id: "{opportunityId}" }, - fields: { stage: "proposal", last_activity_date: "{TODAY()}" } - } - }, - { - id: "notify_owner", - type: "script", - label: "Send Notification", - config: { - actionType: "email", - template: "quote_created", - recipients: ["{$User.Email}"], - variables: { quoteName: "{quoteName}", quoteId: "{quoteId}" } - } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "screen_1", type: "default" }, - { id: "e2", source: "screen_1", target: "get_opportunity", type: "default" }, - { id: "e3", source: "get_opportunity", target: "create_quote", type: "default" }, - { id: "e4", source: "create_quote", target: "update_opportunity", type: "default" }, - { id: "e5", source: "update_opportunity", target: "notify_owner", type: "default" }, - { id: "e6", source: "notify_owner", target: "end", type: "default" } - ] -}; - -// ../app-crm/src/flows/index.ts -var allFlows = [ - CampaignEnrollmentFlow, - CaseEscalationFlow, - LeadConversionFlow, - OpportunityApprovalFlow, - QuoteGenerationFlow -]; - -// ../app-crm/src/agents/email-campaign.agent.ts -var EmailCampaignAgent = { - name: "email_campaign", - label: "Email Campaign Agent", - role: "creator", - instructions: `You are an email marketing AI that creates and optimizes email campaigns. - -Your responsibilities: -1. Write compelling email copy -2. Optimize subject lines for open rates -3. Personalize content based on recipient data -4. A/B test different variations -5. Analyze campaign performance -6. Suggest improvements - -Follow email marketing best practices and maintain brand voice.`, - model: { provider: "anthropic", model: "claude-3-opus", temperature: 0.8, maxTokens: 2e3 }, - tools: [ - { type: "action", name: "generate_email_copy", description: "Generate email campaign copy" }, - { type: "action", name: "optimize_subject_line", description: "Optimize email subject line" }, - { type: "action", name: "personalize_content", description: "Personalize email content" } - ], - knowledge: { - topics: ["email_marketing", "brand_guidelines", "campaign_templates"], - indexes: ["sales_knowledge"] - } -}; - -// ../app-crm/src/agents/lead-enrichment.agent.ts -var LeadEnrichmentAgent = { - name: "lead_enrichment", - label: "Lead Enrichment Agent", - role: "worker", - instructions: `You are a lead enrichment AI that enhances lead records with additional data. - -Your responsibilities: -1. Look up company information from external databases -2. Enrich contact details (job title, LinkedIn, etc.) -3. Add firmographic data (industry, size, revenue) -4. Research company technology stack -5. Find social media profiles -6. Validate email addresses and phone numbers - -Always use reputable data sources and maintain data quality.`, - model: { provider: "openai", model: "gpt-3.5-turbo", temperature: 0.3, maxTokens: 1e3 }, - tools: [ - { type: "action", name: "lookup_company", description: "Look up company information" }, - { type: "action", name: "enrich_contact", description: "Enrich contact information" }, - { type: "action", name: "validate_email", description: "Validate email address" } - ], - knowledge: { - topics: ["lead_enrichment", "company_data"], - indexes: ["sales_knowledge"] - }, - triggers: [ - { type: "object_create", objectName: "lead" } - ], - schedule: { type: "cron", expression: "0 */4 * * *", timezone: "UTC" } -}; - -// ../app-crm/src/agents/revenue-intelligence.agent.ts -var RevenueIntelligenceAgent = { - name: "revenue_intelligence", - label: "Revenue Intelligence Agent", - role: "analyst", - instructions: `You are a revenue intelligence AI that analyzes sales data and provides insights. - -Your responsibilities: -1. Analyze pipeline health and quality -2. Identify at-risk deals -3. Forecast revenue with confidence intervals -4. Detect anomalies and trends -5. Suggest coaching opportunities -6. Generate executive summaries - -Use statistical analysis and machine learning to provide data-driven insights.`, - model: { provider: "openai", model: "gpt-4", temperature: 0.2, maxTokens: 3e3 }, - tools: [ - { type: "query", name: "analyze_pipeline", description: "Analyze sales pipeline health" }, - { type: "query", name: "identify_at_risk", description: "Identify at-risk opportunities" }, - { type: "query", name: "forecast_revenue", description: "Generate revenue forecast" } - ], - knowledge: { - topics: ["pipeline_analytics", "revenue_forecasting", "deal_risk"], - indexes: ["sales_knowledge"] - }, - schedule: { type: "cron", expression: "0 8 * * 1", timezone: "America/Los_Angeles" } -}; - -// ../app-crm/src/agents/sales.agent.ts -var SalesAssistantAgent = { - name: "sales_assistant", - label: "Sales Assistant", - role: "assistant", - instructions: `You are a sales assistant AI helping sales representatives manage their pipeline. - -Your responsibilities: -1. Qualify incoming leads based on BANT criteria (Budget, Authority, Need, Timeline) -2. Suggest next best actions for opportunities -3. Draft personalized email templates -4. Analyze win/loss patterns -5. Provide competitive intelligence -6. Generate sales forecasts - -Always be professional, data-driven, and focused on helping close deals.`, - model: { provider: "openai", model: "gpt-4", temperature: 0.7, maxTokens: 2e3 }, - tools: [ - { type: "action", name: "analyze_lead", description: "Analyze a lead and provide qualification score" }, - { type: "action", name: "suggest_next_action", description: "Suggest next best action for an opportunity" }, - { type: "action", name: "generate_email", description: "Generate a personalized email template" } - ], - knowledge: { - topics: ["sales_playbook", "product_catalog", "lead_qualification"], - indexes: ["sales_knowledge"] - }, - triggers: [ - { type: "object_create", objectName: "lead", condition: 'rating = "hot"' }, - { type: "object_update", objectName: "opportunity", condition: "ISCHANGED(stage)" } - ] -}; - -// ../app-crm/src/agents/service.agent.ts -var ServiceAgent = { - name: "service_agent", - label: "Customer Service Agent", - role: "assistant", - instructions: `You are a customer service AI agent helping support representatives resolve customer issues. - -Your responsibilities: -1. Triage incoming cases based on priority and category -2. Suggest relevant knowledge articles -3. Draft response templates -4. Escalate critical issues -5. Identify common problems and patterns -6. Recommend process improvements - -Always be empathetic, solution-focused, and customer-centric.`, - model: { provider: "openai", model: "gpt-4", temperature: 0.5, maxTokens: 1500 }, - tools: [ - { type: "action", name: "triage_case", description: "Analyze case and assign priority" }, - { type: "vector_search", name: "search_knowledge", description: "Search knowledge base for solutions" }, - { type: "action", name: "generate_response", description: "Generate customer response" } - ], - knowledge: { - topics: ["support_kb", "sla_policies", "case_resolution"], - indexes: ["support_knowledge"] - }, - triggers: [ - { type: "object_create", objectName: "case" }, - { type: "object_update", objectName: "case", condition: 'priority = "critical"' } - ] -}; - -// ../app-crm/src/agents/index.ts -var allAgents = [ - EmailCampaignAgent, - LeadEnrichmentAgent, - RevenueIntelligenceAgent, - SalesAssistantAgent, - ServiceAgent -]; - -// ../app-crm/src/rag/index.ts -var rag_exports = {}; -__export(rag_exports, { - CompetitiveIntelRAG: () => CompetitiveIntelRAG, - ProductInfoRAG: () => ProductInfoRAG, - SalesKnowledgeRAG: () => SalesKnowledgeRAG, - SupportKnowledgeRAG: () => SupportKnowledgeRAG -}); - -// ../app-crm/src/rag/competitive-intel.rag.ts -var CompetitiveIntelRAG = { - name: "competitive_intel", - label: "Competitive Intelligence Pipeline", - description: "RAG pipeline for competitive analysis and market insights", - embedding: { - provider: "openai", - model: "text-embedding-3-large", - dimensions: 1536 - }, - vectorStore: { - provider: "pgvector", - indexName: "competitive_index", - dimensions: 1536, - metric: "cosine" - }, - chunking: { - type: "semantic", - maxChunkSize: 1200 - }, - retrieval: { - type: "similarity", - topK: 7, - scoreThreshold: 0.65 - }, - reranking: { - enabled: true, - provider: "cohere", - model: "cohere-rerank", - topK: 5 - }, - loaders: [ - { type: "directory", source: "/knowledge/competitive", fileTypes: [".md"], recursive: true }, - { type: "directory", source: "/knowledge/market-research", fileTypes: [".pdf"], recursive: true } - ], - maxContextTokens: 5e3, - enableCache: true, - cacheTTL: 1800 -}; - -// ../app-crm/src/rag/product-info.rag.ts -var ProductInfoRAG = { - name: "product_info", - label: "Product Information Pipeline", - description: "RAG pipeline for product catalog and specifications", - embedding: { - provider: "openai", - model: "text-embedding-3-small", - dimensions: 768 - }, - vectorStore: { - provider: "pgvector", - indexName: "product_catalog_index", - dimensions: 768, - metric: "cosine" - }, - chunking: { - type: "semantic", - maxChunkSize: 800 - }, - retrieval: { - type: "hybrid", - topK: 8, - vectorWeight: 0.6, - keywordWeight: 0.4 - }, - loaders: [ - { type: "directory", source: "/knowledge/products", fileTypes: [".md", ".pdf"], recursive: true } - ], - maxContextTokens: 2e3, - enableCache: true, - cacheTTL: 3600 -}; - -// ../app-crm/src/rag/sales-knowledge.rag.ts -var SalesKnowledgeRAG = { - name: "sales_knowledge", - label: "Sales Knowledge Pipeline", - description: "RAG pipeline for sales team knowledge and best practices", - embedding: { - provider: "openai", - model: "text-embedding-3-large", - dimensions: 1536 - }, - vectorStore: { - provider: "pgvector", - indexName: "sales_playbook_index", - dimensions: 1536, - metric: "cosine" - }, - chunking: { - type: "semantic", - maxChunkSize: 1e3 - }, - retrieval: { - type: "hybrid", - topK: 10, - vectorWeight: 0.7, - keywordWeight: 0.3 - }, - reranking: { - enabled: true, - provider: "cohere", - model: "cohere-rerank", - topK: 5 - }, - loaders: [ - { type: "directory", source: "/knowledge/sales", fileTypes: [".md"], recursive: true }, - { type: "directory", source: "/knowledge/products", fileTypes: [".pdf"], recursive: true } - ], - maxContextTokens: 4e3, - enableCache: true, - cacheTTL: 3600 -}; - -// ../app-crm/src/rag/support-knowledge.rag.ts -var SupportKnowledgeRAG = { - name: "support_knowledge", - label: "Support Knowledge Pipeline", - description: "RAG pipeline for customer support knowledge base", - embedding: { - provider: "openai", - model: "text-embedding-3-small", - dimensions: 768 - }, - vectorStore: { - provider: "pgvector", - indexName: "support_kb_index", - dimensions: 768, - metric: "cosine" - }, - chunking: { - type: "fixed", - chunkSize: 512, - chunkOverlap: 100, - unit: "tokens" - }, - retrieval: { - type: "similarity", - topK: 5, - scoreThreshold: 0.75 - }, - loaders: [ - { type: "directory", source: "/knowledge/support", fileTypes: [".md"], recursive: true } - ], - maxContextTokens: 3e3, - enableCache: true, - cacheTTL: 3600 -}; - -// ../app-crm/src/profiles/index.ts -var profiles_exports = {}; -__export(profiles_exports, { - MarketingUserProfile: () => MarketingUserProfile, - SalesManagerProfile: () => SalesManagerProfile, - SalesRepProfile: () => SalesRepProfile, - ServiceAgentProfile: () => ServiceAgentProfile, - SystemAdminProfile: () => SystemAdminProfile -}); - -// ../app-crm/src/profiles/marketing-user.profile.ts -var MarketingUserProfile = { - name: "marketing_user", - label: "Marketing User", - isProfile: true, - objects: { - lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - account: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - opportunity: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false } - } -}; - -// ../app-crm/src/profiles/sales-manager.profile.ts -var SalesManagerProfile = { - name: "sales_manager", - label: "Sales Manager", - isProfile: true, - objects: { - lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - contract: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - product: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - case: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true } - } -}; - -// ../app-crm/src/profiles/sales-rep.profile.ts -var SalesRepProfile = { - name: "sales_rep", - label: "Sales Representative", - isProfile: true, - objects: { - lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - contract: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - product: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - campaign: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false }, - case: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: false, modifyAllRecords: false } - }, - fields: { - "account.annual_revenue": { readable: true, editable: false }, - "account.description": { readable: true, editable: true }, - "opportunity.amount": { readable: true, editable: true }, - "opportunity.probability": { readable: true, editable: true } - } -}; - -// ../app-crm/src/profiles/service-agent.profile.ts -var ServiceAgentProfile = { - name: "service_agent", - label: "Service Agent", - isProfile: true, - objects: { - lead: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - account: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - contact: { allowCreate: false, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - opportunity: { allowCreate: false, allowRead: false, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - case: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false }, - task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: false, modifyAllRecords: false }, - product: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false } - }, - fields: { - "case.is_sla_violated": { readable: true, editable: false }, - "case.resolution_time_hours": { readable: true, editable: false } - } -}; - -// ../app-crm/src/profiles/system-admin.profile.ts -var SystemAdminProfile = { - name: "system_admin", - label: "System Administrator", - isProfile: true, - objects: { - lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - contract: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - product: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - case: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, - task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true } - }, - systemPermissions: [ - "view_setup", - "manage_users", - "customize_application", - "view_all_data", - "modify_all_data", - "manage_profiles", - "manage_roles", - "manage_sharing" - ] -}; - -// ../app-crm/src/apps/index.ts -var apps_exports = {}; -__export(apps_exports, { - CrmApp: () => CrmApp -}); - -// ../app-crm/src/apps/crm.app.ts -var CrmApp = App.create({ - name: "crm_enterprise", - label: "Enterprise CRM", - icon: "briefcase", - branding: { - primaryColor: "#4169E1", - secondaryColor: "#00AA00", - logo: "/assets/crm-logo.png", - favicon: "/assets/crm-favicon.ico" - }, - navigation: [ - { - id: "group_sales", - type: "group", - label: "Sales", - icon: "chart-line", - children: [ - { id: "nav_lead", type: "object", objectName: "lead", label: "Leads", icon: "user-plus" }, - { id: "nav_account", type: "object", objectName: "account", label: "Accounts", icon: "building" }, - { id: "nav_contact", type: "object", objectName: "contact", label: "Contacts", icon: "user" }, - { id: "nav_opportunity", type: "object", objectName: "opportunity", label: "Opportunities", icon: "bullseye" }, - { id: "nav_quote", type: "object", objectName: "quote", label: "Quotes", icon: "file-invoice" }, - { id: "nav_contract", type: "object", objectName: "contract", label: "Contracts", icon: "file-signature" }, - { id: "nav_sales_dashboard", type: "dashboard", dashboardName: "sales_dashboard", label: "Sales Dashboard", icon: "chart-bar" } - ] - }, - { - id: "group_service", - type: "group", - label: "Service", - icon: "headset", - children: [ - { id: "nav_case", type: "object", objectName: "case", label: "Cases", icon: "life-ring" }, - { id: "nav_task", type: "object", objectName: "task", label: "Tasks", icon: "tasks" }, - { id: "nav_service_dashboard", type: "dashboard", dashboardName: "service_dashboard", label: "Service Dashboard", icon: "chart-pie" } - ] - }, - { - id: "group_marketing", - type: "group", - label: "Marketing", - icon: "megaphone", - children: [ - { id: "nav_campaign", type: "object", objectName: "campaign", label: "Campaigns", icon: "bullhorn" }, - { id: "nav_lead_marketing", type: "object", objectName: "lead", label: "Leads", icon: "user-plus" } - ] - }, - { - id: "group_products", - type: "group", - label: "Products", - icon: "box", - children: [ - { id: "nav_product", type: "object", objectName: "product", label: "Products", icon: "box-open" } - ] - }, - { - id: "group_analytics", - type: "group", - label: "Analytics", - icon: "chart-area", - children: [ - { id: "nav_exec_dashboard", type: "dashboard", dashboardName: "executive_dashboard", label: "Executive Dashboard", icon: "tachometer-alt" }, - { id: "nav_analytics_sales_db", type: "dashboard", dashboardName: "sales_dashboard", label: "Sales Analytics", icon: "chart-line" }, - { id: "nav_analytics_service_db", type: "dashboard", dashboardName: "service_dashboard", label: "Service Analytics", icon: "chart-pie" } - ] - } - ] -}); - -// ../app-crm/src/apps/crm_modern.app.ts -var CrmApp2 = defineApp({ - name: "crm", - label: "Sales CRM", - description: "Enterprise CRM with nested navigation tree", - icon: "briefcase", - branding: { - primaryColor: "#4169E1", - logo: "/assets/crm-logo.png", - favicon: "/assets/crm-favicon.ico" - }, - navigation: [ - // ── Sales Cloud ── - { - id: "grp_sales", - type: "group", - label: "Sales Cloud", - icon: "briefcase", - expanded: true, - children: [ - { id: "nav_pipeline", type: "page", label: "Pipeline", icon: "columns", pageName: "page_pipeline" }, - { id: "nav_accounts", type: "page", label: "Accounts", icon: "building", pageName: "page_accounts" }, - { id: "nav_leads", type: "page", label: "Leads", icon: "user-plus", pageName: "page_leads" }, - // Nested sub-group — impossible with the old Interface model - { - id: "grp_review", - type: "group", - label: "Lead Review", - icon: "clipboard-check", - expanded: false, - children: [ - { id: "nav_review_queue", type: "page", label: "Review Queue", icon: "check-square", pageName: "page_review_queue" }, - { id: "nav_qualified", type: "page", label: "Qualified", icon: "check-circle", pageName: "page_qualified" } - ] - } - ] - }, - // ── Analytics ── - { - id: "grp_analytics", - type: "group", - label: "Analytics", - icon: "chart-line", - expanded: false, - children: [ - { id: "nav_overview", type: "page", label: "Overview", icon: "gauge", pageName: "page_overview" }, - { id: "nav_pipeline_report", type: "page", label: "Pipeline Report", icon: "chart-bar", pageName: "page_pipeline_report" } - ] - }, - // ── Global Utility ── - { id: "nav_settings", type: "page", label: "Settings", icon: "settings", pageName: "admin_settings" }, - { id: "nav_help", type: "url", label: "Help", icon: "help-circle", url: "https://help.example.com", target: "_blank" } - ], - homePageId: "nav_pipeline", - requiredPermissions: ["app.access.crm"], - isDefault: true -}); - -// ../app-crm/src/translations/index.ts -var translations_exports = {}; -__export(translations_exports, { - CrmTranslations: () => CrmTranslations -}); - -// ../app-crm/src/translations/en.ts -var en = { - objects: { - account: { - label: "Account", - pluralLabel: "Accounts", - fields: { - account_number: { label: "Account Number" }, - name: { label: "Account Name", help: "Legal name of the company or organization" }, - type: { - label: "Type", - options: { prospect: "Prospect", customer: "Customer", partner: "Partner", former: "Former" } - }, - industry: { - label: "Industry", - options: { - technology: "Technology", - finance: "Finance", - healthcare: "Healthcare", - retail: "Retail", - manufacturing: "Manufacturing", - education: "Education" - } - }, - annual_revenue: { label: "Annual Revenue" }, - number_of_employees: { label: "Number of Employees" }, - phone: { label: "Phone" }, - website: { label: "Website" }, - billing_address: { label: "Billing Address" }, - office_location: { label: "Office Location" }, - owner: { label: "Account Owner" }, - parent_account: { label: "Parent Account" }, - description: { label: "Description" }, - is_active: { label: "Active" }, - last_activity_date: { label: "Last Activity Date" } - } - }, - contact: { - label: "Contact", - pluralLabel: "Contacts", - fields: { - salutation: { label: "Salutation" }, - first_name: { label: "First Name" }, - last_name: { label: "Last Name" }, - full_name: { label: "Full Name" }, - account: { label: "Account" }, - email: { label: "Email" }, - phone: { label: "Phone" }, - mobile: { label: "Mobile" }, - title: { label: "Title" }, - department: { - label: "Department", - options: { - Executive: "Executive", - Sales: "Sales", - Marketing: "Marketing", - Engineering: "Engineering", - Support: "Support", - Finance: "Finance", - HR: "Human Resources", - Operations: "Operations" - } - }, - owner: { label: "Contact Owner" }, - description: { label: "Description" }, - is_primary: { label: "Primary Contact" } - } - }, - lead: { - label: "Lead", - pluralLabel: "Leads", - fields: { - first_name: { label: "First Name" }, - last_name: { label: "Last Name" }, - company: { label: "Company" }, - title: { label: "Title" }, - email: { label: "Email" }, - phone: { label: "Phone" }, - status: { - label: "Status", - options: { - new: "New", - contacted: "Contacted", - qualified: "Qualified", - unqualified: "Unqualified", - converted: "Converted" - } - }, - lead_source: { - label: "Lead Source", - options: { - Web: "Web", - Referral: "Referral", - Event: "Event", - Partner: "Partner", - Advertisement: "Advertisement", - "Cold Call": "Cold Call" - } - }, - owner: { label: "Lead Owner" }, - is_converted: { label: "Converted" }, - description: { label: "Description" } - } - }, - opportunity: { - label: "Opportunity", - pluralLabel: "Opportunities", - fields: { - name: { label: "Opportunity Name" }, - account: { label: "Account" }, - primary_contact: { label: "Primary Contact" }, - owner: { label: "Opportunity Owner" }, - amount: { label: "Amount" }, - expected_revenue: { label: "Expected Revenue" }, - stage: { - label: "Stage", - options: { - prospecting: "Prospecting", - qualification: "Qualification", - needs_analysis: "Needs Analysis", - proposal: "Proposal", - negotiation: "Negotiation", - closed_won: "Closed Won", - closed_lost: "Closed Lost" - } - }, - probability: { label: "Probability (%)" }, - close_date: { label: "Close Date" }, - type: { - label: "Type", - options: { - "New Business": "New Business", - "Existing Customer - Upgrade": "Existing Customer - Upgrade", - "Existing Customer - Renewal": "Existing Customer - Renewal", - "Existing Customer - Expansion": "Existing Customer - Expansion" - } - }, - forecast_category: { - label: "Forecast Category", - options: { - Pipeline: "Pipeline", - "Best Case": "Best Case", - Commit: "Commit", - Omitted: "Omitted", - Closed: "Closed" - } - }, - description: { label: "Description" }, - next_step: { label: "Next Step" } - } - } - }, - apps: { - crm_enterprise: { - label: "Enterprise CRM", - description: "Customer relationship management for sales, service, and marketing" - } - }, - messages: { - "common.save": "Save", - "common.cancel": "Cancel", - "common.delete": "Delete", - "common.edit": "Edit", - "common.create": "Create", - "common.search": "Search", - "common.filter": "Filter", - "common.export": "Export", - "common.back": "Back", - "common.confirm": "Confirm", - "nav.sales": "Sales", - "nav.service": "Service", - "nav.marketing": "Marketing", - "nav.products": "Products", - "nav.analytics": "Analytics", - "success.saved": "Record saved successfully", - "success.converted": "Lead converted successfully", - "confirm.delete": "Are you sure you want to delete this record?", - "confirm.convert_lead": "Convert this lead to account, contact, and opportunity?", - "error.required": "This field is required", - "error.load_failed": "Failed to load data" - }, - validationMessages: { - amount_required_for_closed: "Amount is required when stage is Closed Won", - close_date_required: "Close date is required for opportunities", - discount_limit: "Discount cannot exceed 40%" - } -}; - -// ../app-crm/src/translations/zh-CN.ts -var zhCN = { - objects: { - account: { - label: "\u5BA2\u6237", - pluralLabel: "\u5BA2\u6237", - fields: { - account_number: { label: "\u5BA2\u6237\u7F16\u53F7" }, - name: { label: "\u5BA2\u6237\u540D\u79F0", help: "\u516C\u53F8\u6216\u7EC4\u7EC7\u7684\u6CD5\u5B9A\u540D\u79F0" }, - type: { - label: "\u7C7B\u578B", - options: { prospect: "\u6F5C\u5728\u5BA2\u6237", customer: "\u6B63\u5F0F\u5BA2\u6237", partner: "\u5408\u4F5C\u4F19\u4F34", former: "\u524D\u5BA2\u6237" } - }, - industry: { - label: "\u884C\u4E1A", - options: { - technology: "\u79D1\u6280", - finance: "\u91D1\u878D", - healthcare: "\u533B\u7597", - retail: "\u96F6\u552E", - manufacturing: "\u5236\u9020", - education: "\u6559\u80B2" - } - }, - annual_revenue: { label: "\u5E74\u8425\u6536" }, - number_of_employees: { label: "\u5458\u5DE5\u4EBA\u6570" }, - phone: { label: "\u7535\u8BDD" }, - website: { label: "\u7F51\u7AD9" }, - billing_address: { label: "\u8D26\u5355\u5730\u5740" }, - office_location: { label: "\u529E\u516C\u5730\u70B9" }, - owner: { label: "\u5BA2\u6237\u8D1F\u8D23\u4EBA" }, - parent_account: { label: "\u6BCD\u516C\u53F8" }, - description: { label: "\u63CF\u8FF0" }, - is_active: { label: "\u662F\u5426\u6D3B\u8DC3" }, - last_activity_date: { label: "\u6700\u8FD1\u6D3B\u52A8\u65E5\u671F" } - } - }, - contact: { - label: "\u8054\u7CFB\u4EBA", - pluralLabel: "\u8054\u7CFB\u4EBA", - fields: { - salutation: { label: "\u79F0\u8C13" }, - first_name: { label: "\u540D" }, - last_name: { label: "\u59D3" }, - full_name: { label: "\u5168\u540D" }, - account: { label: "\u6240\u5C5E\u5BA2\u6237" }, - email: { label: "\u90AE\u7BB1" }, - phone: { label: "\u7535\u8BDD" }, - mobile: { label: "\u624B\u673A" }, - title: { label: "\u804C\u4F4D" }, - department: { - label: "\u90E8\u95E8", - options: { - Executive: "\u7BA1\u7406\u5C42", - Sales: "\u9500\u552E\u90E8", - Marketing: "\u5E02\u573A\u90E8", - Engineering: "\u5DE5\u7A0B\u90E8", - Support: "\u652F\u6301\u90E8", - Finance: "\u8D22\u52A1\u90E8", - HR: "\u4EBA\u529B\u8D44\u6E90", - Operations: "\u8FD0\u8425\u90E8" - } - }, - owner: { label: "\u8054\u7CFB\u4EBA\u8D1F\u8D23\u4EBA" }, - description: { label: "\u63CF\u8FF0" }, - is_primary: { label: "\u4E3B\u8981\u8054\u7CFB\u4EBA" } - } - }, - lead: { - label: "\u7EBF\u7D22", - pluralLabel: "\u7EBF\u7D22", - fields: { - first_name: { label: "\u540D" }, - last_name: { label: "\u59D3" }, - company: { label: "\u516C\u53F8" }, - title: { label: "\u804C\u4F4D" }, - email: { label: "\u90AE\u7BB1" }, - phone: { label: "\u7535\u8BDD" }, - status: { - label: "\u72B6\u6001", - options: { - new: "\u65B0\u5EFA", - contacted: "\u5DF2\u8054\u7CFB", - qualified: "\u5DF2\u786E\u8BA4", - unqualified: "\u4E0D\u5408\u683C", - converted: "\u5DF2\u8F6C\u5316" - } - }, - lead_source: { - label: "\u7EBF\u7D22\u6765\u6E90", - options: { - Web: "\u7F51\u7AD9", - Referral: "\u63A8\u8350", - Event: "\u6D3B\u52A8", - Partner: "\u5408\u4F5C\u4F19\u4F34", - Advertisement: "\u5E7F\u544A", - "Cold Call": "\u964C\u751F\u62DC\u8BBF" - } - }, - owner: { label: "\u7EBF\u7D22\u8D1F\u8D23\u4EBA" }, - is_converted: { label: "\u5DF2\u8F6C\u5316" }, - description: { label: "\u63CF\u8FF0" } - } - }, - opportunity: { - label: "\u5546\u673A", - pluralLabel: "\u5546\u673A", - fields: { - name: { label: "\u5546\u673A\u540D\u79F0" }, - account: { label: "\u6240\u5C5E\u5BA2\u6237" }, - primary_contact: { label: "\u4E3B\u8981\u8054\u7CFB\u4EBA" }, - owner: { label: "\u5546\u673A\u8D1F\u8D23\u4EBA" }, - amount: { label: "\u91D1\u989D" }, - expected_revenue: { label: "\u9884\u671F\u6536\u5165" }, - stage: { - label: "\u9636\u6BB5", - options: { - prospecting: "\u5BFB\u627E\u5BA2\u6237", - qualification: "\u8D44\u683C\u5BA1\u67E5", - needs_analysis: "\u9700\u6C42\u5206\u6790", - proposal: "\u63D0\u6848", - negotiation: "\u8C08\u5224", - closed_won: "\u6210\u4EA4", - closed_lost: "\u5931\u8D25" - } - }, - probability: { label: "\u6210\u4EA4\u6982\u7387 (%)" }, - close_date: { label: "\u9884\u8BA1\u6210\u4EA4\u65E5\u671F" }, - type: { - label: "\u7C7B\u578B", - options: { - "New Business": "\u65B0\u4E1A\u52A1", - "Existing Customer - Upgrade": "\u8001\u5BA2\u6237\u5347\u7EA7", - "Existing Customer - Renewal": "\u8001\u5BA2\u6237\u7EED\u7EA6", - "Existing Customer - Expansion": "\u8001\u5BA2\u6237\u62D3\u5C55" - } - }, - forecast_category: { - label: "\u9884\u6D4B\u7C7B\u522B", - options: { - Pipeline: "\u7BA1\u9053", - "Best Case": "\u6700\u4F73\u60C5\u51B5", - Commit: "\u627F\u8BFA", - Omitted: "\u5DF2\u6392\u9664", - Closed: "\u5DF2\u5173\u95ED" - } - }, - description: { label: "\u63CF\u8FF0" }, - next_step: { label: "\u4E0B\u4E00\u6B65" } - } - } - }, - apps: { - crm_enterprise: { - label: "\u4F01\u4E1A CRM", - description: "\u6DB5\u76D6\u9500\u552E\u3001\u670D\u52A1\u548C\u5E02\u573A\u8425\u9500\u7684\u5BA2\u6237\u5173\u7CFB\u7BA1\u7406\u7CFB\u7EDF" - } - }, - messages: { - "common.save": "\u4FDD\u5B58", - "common.cancel": "\u53D6\u6D88", - "common.delete": "\u5220\u9664", - "common.edit": "\u7F16\u8F91", - "common.create": "\u65B0\u5EFA", - "common.search": "\u641C\u7D22", - "common.filter": "\u7B5B\u9009", - "common.export": "\u5BFC\u51FA", - "common.back": "\u8FD4\u56DE", - "common.confirm": "\u786E\u8BA4", - "nav.sales": "\u9500\u552E", - "nav.service": "\u670D\u52A1", - "nav.marketing": "\u8425\u9500", - "nav.products": "\u4EA7\u54C1", - "nav.analytics": "\u6570\u636E\u5206\u6790", - "success.saved": "\u8BB0\u5F55\u4FDD\u5B58\u6210\u529F", - "success.converted": "\u7EBF\u7D22\u8F6C\u5316\u6210\u529F", - "confirm.delete": "\u786E\u5B9A\u8981\u5220\u9664\u6B64\u8BB0\u5F55\u5417\uFF1F", - "confirm.convert_lead": "\u5C06\u6B64\u7EBF\u7D22\u8F6C\u5316\u4E3A\u5BA2\u6237\u3001\u8054\u7CFB\u4EBA\u548C\u5546\u673A\uFF1F", - "error.required": "\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879", - "error.load_failed": "\u6570\u636E\u52A0\u8F7D\u5931\u8D25" - }, - validationMessages: { - amount_required_for_closed: '\u9636\u6BB5\u4E3A"\u6210\u4EA4"\u65F6\uFF0C\u91D1\u989D\u4E3A\u5FC5\u586B\u9879', - close_date_required: "\u5546\u673A\u5FC5\u987B\u586B\u5199\u9884\u8BA1\u6210\u4EA4\u65E5\u671F", - discount_limit: "\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%" - } -}; - -// ../app-crm/src/translations/ja-JP.ts -var jaJP = { - objects: { - account: { - label: "\u53D6\u5F15\u5148", - pluralLabel: "\u53D6\u5F15\u5148", - fields: { - account_number: { label: "\u53D6\u5F15\u5148\u756A\u53F7" }, - name: { label: "\u53D6\u5F15\u5148\u540D", help: "\u4F1A\u793E\u307E\u305F\u306F\u7D44\u7E54\u306E\u6B63\u5F0F\u540D\u79F0" }, - type: { - label: "\u30BF\u30A4\u30D7", - options: { prospect: "\u898B\u8FBC\u307F\u5BA2", customer: "\u9867\u5BA2", partner: "\u30D1\u30FC\u30C8\u30CA\u30FC", former: "\u904E\u53BB\u306E\u53D6\u5F15\u5148" } - }, - industry: { - label: "\u696D\u7A2E", - options: { - technology: "\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC", - finance: "\u91D1\u878D", - healthcare: "\u30D8\u30EB\u30B9\u30B1\u30A2", - retail: "\u5C0F\u58F2", - manufacturing: "\u88FD\u9020", - education: "\u6559\u80B2" - } - }, - annual_revenue: { label: "\u5E74\u9593\u58F2\u4E0A" }, - number_of_employees: { label: "\u5F93\u696D\u54E1\u6570" }, - phone: { label: "\u96FB\u8A71\u756A\u53F7" }, - website: { label: "Web\u30B5\u30A4\u30C8" }, - billing_address: { label: "\u8ACB\u6C42\u5148\u4F4F\u6240" }, - office_location: { label: "\u30AA\u30D5\u30A3\u30B9\u6240\u5728\u5730" }, - owner: { label: "\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005" }, - parent_account: { label: "\u89AA\u53D6\u5F15\u5148" }, - description: { label: "\u8AAC\u660E" }, - is_active: { label: "\u6709\u52B9" }, - last_activity_date: { label: "\u6700\u7D42\u6D3B\u52D5\u65E5" } - } - }, - contact: { - label: "\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005", - pluralLabel: "\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005", - fields: { - salutation: { label: "\u656C\u79F0" }, - first_name: { label: "\u540D" }, - last_name: { label: "\u59D3" }, - full_name: { label: "\u6C0F\u540D" }, - account: { label: "\u53D6\u5F15\u5148" }, - email: { label: "\u30E1\u30FC\u30EB" }, - phone: { label: "\u96FB\u8A71" }, - mobile: { label: "\u643A\u5E2F\u96FB\u8A71" }, - title: { label: "\u5F79\u8077" }, - department: { - label: "\u90E8\u9580", - options: { - Executive: "\u7D4C\u55B6\u5C64", - Sales: "\u55B6\u696D\u90E8", - Marketing: "\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u90E8", - Engineering: "\u30A8\u30F3\u30B8\u30CB\u30A2\u30EA\u30F3\u30B0\u90E8", - Support: "\u30B5\u30DD\u30FC\u30C8\u90E8", - Finance: "\u7D4C\u7406\u90E8", - HR: "\u4EBA\u4E8B\u90E8", - Operations: "\u30AA\u30DA\u30EC\u30FC\u30B7\u30E7\u30F3\u90E8" - } - }, - owner: { label: "\u6240\u6709\u8005" }, - description: { label: "\u8AAC\u660E" }, - is_primary: { label: "\u4E3B\u62C5\u5F53\u8005" } - } - }, - lead: { - label: "\u30EA\u30FC\u30C9", - pluralLabel: "\u30EA\u30FC\u30C9", - fields: { - first_name: { label: "\u540D" }, - last_name: { label: "\u59D3" }, - company: { label: "\u4F1A\u793E\u540D" }, - title: { label: "\u5F79\u8077" }, - email: { label: "\u30E1\u30FC\u30EB" }, - phone: { label: "\u96FB\u8A71" }, - status: { - label: "\u30B9\u30C6\u30FC\u30BF\u30B9", - options: { - new: "\u65B0\u898F", - contacted: "\u30B3\u30F3\u30BF\u30AF\u30C8\u6E08\u307F", - qualified: "\u9069\u683C", - unqualified: "\u4E0D\u9069\u683C", - converted: "\u53D6\u5F15\u958B\u59CB\u6E08\u307F" - } - }, - lead_source: { - label: "\u30EA\u30FC\u30C9\u30BD\u30FC\u30B9", - options: { - Web: "Web", - Referral: "\u7D39\u4ECB", - Event: "\u30A4\u30D9\u30F3\u30C8", - Partner: "\u30D1\u30FC\u30C8\u30CA\u30FC", - Advertisement: "\u5E83\u544A", - "Cold Call": "\u30B3\u30FC\u30EB\u30C9\u30B3\u30FC\u30EB" - } - }, - owner: { label: "\u30EA\u30FC\u30C9\u6240\u6709\u8005" }, - is_converted: { label: "\u53D6\u5F15\u958B\u59CB\u6E08\u307F" }, - description: { label: "\u8AAC\u660E" } - } - }, - opportunity: { - label: "\u5546\u8AC7", - pluralLabel: "\u5546\u8AC7", - fields: { - name: { label: "\u5546\u8AC7\u540D" }, - account: { label: "\u53D6\u5F15\u5148" }, - primary_contact: { label: "\u4E3B\u62C5\u5F53\u8005" }, - owner: { label: "\u5546\u8AC7\u6240\u6709\u8005" }, - amount: { label: "\u91D1\u984D" }, - expected_revenue: { label: "\u671F\u5F85\u53CE\u76CA" }, - stage: { - label: "\u30D5\u30A7\u30FC\u30BA", - options: { - prospecting: "\u898B\u8FBC\u307F\u8ABF\u67FB", - qualification: "\u9078\u5B9A", - needs_analysis: "\u30CB\u30FC\u30BA\u5206\u6790", - proposal: "\u63D0\u6848", - negotiation: "\u4EA4\u6E09", - closed_won: "\u6210\u7ACB", - closed_lost: "\u4E0D\u6210\u7ACB" - } - }, - probability: { label: "\u78BA\u5EA6 (%)" }, - close_date: { label: "\u5B8C\u4E86\u4E88\u5B9A\u65E5" }, - type: { - label: "\u30BF\u30A4\u30D7", - options: { - "New Business": "\u65B0\u898F\u30D3\u30B8\u30CD\u30B9", - "Existing Customer - Upgrade": "\u65E2\u5B58\u9867\u5BA2 - \u30A2\u30C3\u30D7\u30B0\u30EC\u30FC\u30C9", - "Existing Customer - Renewal": "\u65E2\u5B58\u9867\u5BA2 - \u66F4\u65B0", - "Existing Customer - Expansion": "\u65E2\u5B58\u9867\u5BA2 - \u62E1\u5927" - } - }, - forecast_category: { - label: "\u58F2\u4E0A\u4E88\u6E2C\u30AB\u30C6\u30B4\u30EA", - options: { - Pipeline: "\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3", - "Best Case": "\u6700\u826F\u30B1\u30FC\u30B9", - Commit: "\u30B3\u30DF\u30C3\u30C8", - Omitted: "\u9664\u5916", - Closed: "\u5B8C\u4E86" - } - }, - description: { label: "\u8AAC\u660E" }, - next_step: { label: "\u6B21\u306E\u30B9\u30C6\u30C3\u30D7" } - } - } - }, - apps: { - crm_enterprise: { - label: "\u30A8\u30F3\u30BF\u30FC\u30D7\u30E9\u30A4\u30BA CRM", - description: "\u55B6\u696D\u30FB\u30B5\u30FC\u30D3\u30B9\u30FB\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u5411\u3051\u9867\u5BA2\u95A2\u4FC2\u7BA1\u7406\u30B7\u30B9\u30C6\u30E0" - } - }, - messages: { - "common.save": "\u4FDD\u5B58", - "common.cancel": "\u30AD\u30E3\u30F3\u30BB\u30EB", - "common.delete": "\u524A\u9664", - "common.edit": "\u7DE8\u96C6", - "common.create": "\u65B0\u898F\u4F5C\u6210", - "common.search": "\u691C\u7D22", - "common.filter": "\u30D5\u30A3\u30EB\u30BF\u30FC", - "common.export": "\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8", - "common.back": "\u623B\u308B", - "common.confirm": "\u78BA\u8A8D", - "nav.sales": "\u55B6\u696D", - "nav.service": "\u30B5\u30FC\u30D3\u30B9", - "nav.marketing": "\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0", - "nav.products": "\u88FD\u54C1", - "nav.analytics": "\u30A2\u30CA\u30EA\u30C6\u30A3\u30AF\u30B9", - "success.saved": "\u30EC\u30B3\u30FC\u30C9\u3092\u4FDD\u5B58\u3057\u307E\u3057\u305F", - "success.converted": "\u30EA\u30FC\u30C9\u3092\u53D6\u5F15\u958B\u59CB\u3057\u307E\u3057\u305F", - "confirm.delete": "\u3053\u306E\u30EC\u30B3\u30FC\u30C9\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F", - "confirm.convert_lead": "\u3053\u306E\u30EA\u30FC\u30C9\u3092\u53D6\u5F15\u5148\u30FB\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005\u30FB\u5546\u8AC7\u306B\u5909\u63DB\u3057\u307E\u3059\u304B\uFF1F", - "error.required": "\u3053\u306E\u9805\u76EE\u306F\u5FC5\u9808\u3067\u3059", - "error.load_failed": "\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F" - }, - validationMessages: { - amount_required_for_closed: "\u30D5\u30A7\u30FC\u30BA\u304C\u300C\u6210\u7ACB\u300D\u306E\u5834\u5408\u3001\u91D1\u984D\u306F\u5FC5\u9808\u3067\u3059", - close_date_required: "\u5546\u8AC7\u306B\u306F\u5B8C\u4E86\u4E88\u5B9A\u65E5\u304C\u5FC5\u8981\u3067\u3059", - discount_limit: "\u5272\u5F15\u306F40%\u3092\u8D85\u3048\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093" - } -}; - -// ../app-crm/src/translations/es-ES.ts -var esES = { - objects: { - account: { - label: "Cuenta", - pluralLabel: "Cuentas", - fields: { - account_number: { label: "N\xFAmero de Cuenta" }, - name: { label: "Nombre de Cuenta", help: "Nombre legal de la empresa u organizaci\xF3n" }, - type: { - label: "Tipo", - options: { prospect: "Prospecto", customer: "Cliente", partner: "Socio", former: "Anterior" } - }, - industry: { - label: "Industria", - options: { - technology: "Tecnolog\xEDa", - finance: "Finanzas", - healthcare: "Salud", - retail: "Comercio", - manufacturing: "Manufactura", - education: "Educaci\xF3n" - } - }, - annual_revenue: { label: "Ingresos Anuales" }, - number_of_employees: { label: "N\xFAmero de Empleados" }, - phone: { label: "Tel\xE9fono" }, - website: { label: "Sitio Web" }, - billing_address: { label: "Direcci\xF3n de Facturaci\xF3n" }, - office_location: { label: "Ubicaci\xF3n de Oficina" }, - owner: { label: "Propietario de Cuenta" }, - parent_account: { label: "Cuenta Matriz" }, - description: { label: "Descripci\xF3n" }, - is_active: { label: "Activo" }, - last_activity_date: { label: "Fecha de \xDAltima Actividad" } - } - }, - contact: { - label: "Contacto", - pluralLabel: "Contactos", - fields: { - salutation: { label: "T\xEDtulo" }, - first_name: { label: "Nombre" }, - last_name: { label: "Apellido" }, - full_name: { label: "Nombre Completo" }, - account: { label: "Cuenta" }, - email: { label: "Correo Electr\xF3nico" }, - phone: { label: "Tel\xE9fono" }, - mobile: { label: "M\xF3vil" }, - title: { label: "Cargo" }, - department: { - label: "Departamento", - options: { - Executive: "Ejecutivo", - Sales: "Ventas", - Marketing: "Marketing", - Engineering: "Ingenier\xEDa", - Support: "Soporte", - Finance: "Finanzas", - HR: "Recursos Humanos", - Operations: "Operaciones" - } - }, - owner: { label: "Propietario de Contacto" }, - description: { label: "Descripci\xF3n" }, - is_primary: { label: "Contacto Principal" } - } - }, - lead: { - label: "Prospecto", - pluralLabel: "Prospectos", - fields: { - first_name: { label: "Nombre" }, - last_name: { label: "Apellido" }, - company: { label: "Empresa" }, - title: { label: "Cargo" }, - email: { label: "Correo Electr\xF3nico" }, - phone: { label: "Tel\xE9fono" }, - status: { - label: "Estado", - options: { - new: "Nuevo", - contacted: "Contactado", - qualified: "Calificado", - unqualified: "No Calificado", - converted: "Convertido" - } - }, - lead_source: { - label: "Origen del Prospecto", - options: { - Web: "Web", - Referral: "Referencia", - Event: "Evento", - Partner: "Socio", - Advertisement: "Publicidad", - "Cold Call": "Llamada en Fr\xEDo" - } - }, - owner: { label: "Propietario" }, - is_converted: { label: "Convertido" }, - description: { label: "Descripci\xF3n" } - } - }, - opportunity: { - label: "Oportunidad", - pluralLabel: "Oportunidades", - fields: { - name: { label: "Nombre de Oportunidad" }, - account: { label: "Cuenta" }, - primary_contact: { label: "Contacto Principal" }, - owner: { label: "Propietario de Oportunidad" }, - amount: { label: "Monto" }, - expected_revenue: { label: "Ingreso Esperado" }, - stage: { - label: "Etapa", - options: { - prospecting: "Prospecci\xF3n", - qualification: "Calificaci\xF3n", - needs_analysis: "An\xE1lisis de Necesidades", - proposal: "Propuesta", - negotiation: "Negociaci\xF3n", - closed_won: "Cerrada Ganada", - closed_lost: "Cerrada Perdida" - } - }, - probability: { label: "Probabilidad (%)" }, - close_date: { label: "Fecha de Cierre" }, - type: { - label: "Tipo", - options: { - "New Business": "Nuevo Negocio", - "Existing Customer - Upgrade": "Cliente Existente - Mejora", - "Existing Customer - Renewal": "Cliente Existente - Renovaci\xF3n", - "Existing Customer - Expansion": "Cliente Existente - Expansi\xF3n" - } - }, - forecast_category: { - label: "Categor\xEDa de Pron\xF3stico", - options: { - Pipeline: "Pipeline", - "Best Case": "Mejor Caso", - Commit: "Compromiso", - Omitted: "Omitida", - Closed: "Cerrada" - } - }, - description: { label: "Descripci\xF3n" }, - next_step: { label: "Pr\xF3ximo Paso" } - } - } - }, - apps: { - crm_enterprise: { - label: "CRM Empresarial", - description: "Gesti\xF3n de relaciones con clientes para ventas, servicio y marketing" - } - }, - messages: { - "common.save": "Guardar", - "common.cancel": "Cancelar", - "common.delete": "Eliminar", - "common.edit": "Editar", - "common.create": "Crear", - "common.search": "Buscar", - "common.filter": "Filtrar", - "common.export": "Exportar", - "common.back": "Volver", - "common.confirm": "Confirmar", - "nav.sales": "Ventas", - "nav.service": "Servicio", - "nav.marketing": "Marketing", - "nav.products": "Productos", - "nav.analytics": "Anal\xEDtica", - "success.saved": "Registro guardado exitosamente", - "success.converted": "Prospecto convertido exitosamente", - "confirm.delete": "\xBFEst\xE1 seguro de que desea eliminar este registro?", - "confirm.convert_lead": "\xBFConvertir este prospecto en cuenta, contacto y oportunidad?", - "error.required": "Este campo es obligatorio", - "error.load_failed": "Error al cargar los datos" - }, - validationMessages: { - amount_required_for_closed: "El monto es obligatorio cuando la etapa es Cerrada Ganada", - close_date_required: "La fecha de cierre es obligatoria para las oportunidades", - discount_limit: "El descuento no puede superar el 40%" - } -}; - -// ../app-crm/src/translations/crm.translation.ts -var CrmTranslations = { - en, - "zh-CN": zhCN, - "ja-JP": jaJP, - "es-ES": esES -}; - -// ../app-crm/src/data/index.ts -var accounts = { - object: "account", - mode: "upsert", - externalId: "name", - records: [ - { - name: "Acme Corporation", - type: "customer", - industry: "technology", - annual_revenue: 5e6, - number_of_employees: 250, - phone: "+1-415-555-0100", - website: "https://acme.example.com" - }, - { - name: "Globex Industries", - type: "prospect", - industry: "manufacturing", - annual_revenue: 12e6, - number_of_employees: 800, - phone: "+1-312-555-0200", - website: "https://globex.example.com" - }, - { - name: "Initech Solutions", - type: "customer", - industry: "finance", - annual_revenue: 35e5, - number_of_employees: 150, - phone: "+1-212-555-0300", - website: "https://initech.example.com" - }, - { - name: "Stark Medical", - type: "partner", - industry: "healthcare", - annual_revenue: 8e6, - number_of_employees: 400, - phone: "+1-617-555-0400", - website: "https://starkmed.example.com" - }, - { - name: "Wayne Enterprises", - type: "customer", - industry: "technology", - annual_revenue: 25e6, - number_of_employees: 2e3, - phone: "+1-650-555-0500", - website: "https://wayne.example.com" - } - ] -}; -var contacts = { - object: "contact", - mode: "upsert", - externalId: "email", - records: [ - { - salutation: "Mr.", - first_name: "John", - last_name: "Smith", - email: "john.smith@acme.example.com", - phone: "+1-415-555-0101", - title: "VP of Engineering", - department: "Engineering" - }, - { - salutation: "Ms.", - first_name: "Sarah", - last_name: "Johnson", - email: "sarah.j@globex.example.com", - phone: "+1-312-555-0201", - title: "Chief Procurement Officer", - department: "Executive" - }, - { - salutation: "Dr.", - first_name: "Michael", - last_name: "Chen", - email: "mchen@initech.example.com", - phone: "+1-212-555-0301", - title: "Director of Operations", - department: "Operations" - }, - { - salutation: "Ms.", - first_name: "Emily", - last_name: "Davis", - email: "emily.d@starkmed.example.com", - phone: "+1-617-555-0401", - title: "Head of Partnerships", - department: "Sales" - }, - { - salutation: "Mr.", - first_name: "Robert", - last_name: "Wilson", - email: "rwilson@wayne.example.com", - phone: "+1-650-555-0501", - title: "CTO", - department: "Engineering" - } - ] -}; -var leads = { - object: "lead", - mode: "upsert", - externalId: "email", - records: [ - { - first_name: "Alice", - last_name: "Martinez", - company: "NextGen Retail", - email: "alice@nextgenretail.example.com", - phone: "+1-503-555-0600", - status: "new", - source: "website", - industry: "Retail" - }, - { - first_name: "David", - last_name: "Kim", - company: "EduTech Labs", - email: "dkim@edutechlabs.example.com", - phone: "+1-408-555-0700", - status: "contacted", - source: "referral", - industry: "Education" - }, - { - first_name: "Lisa", - last_name: "Thompson", - company: "CloudFirst Inc", - email: "lisa.t@cloudfirst.example.com", - phone: "+1-206-555-0800", - status: "qualified", - source: "trade_show", - industry: "Technology" - } - ] -}; -var opportunities = { - object: "opportunity", - mode: "upsert", - externalId: "name", - records: [ - { - name: "Acme Platform Upgrade", - amount: 15e4, - stage: "proposal", - probability: 60, - close_date: new Date(Date.now() + 864e5 * 30), - type: "existing_business", - forecast_category: "pipeline" - }, - { - name: "Globex Manufacturing Suite", - amount: 5e5, - stage: "qualification", - probability: 30, - close_date: new Date(Date.now() + 864e5 * 60), - type: "new_business", - forecast_category: "pipeline" - }, - { - name: "Wayne Enterprise License", - amount: 12e5, - stage: "negotiation", - probability: 75, - close_date: new Date(Date.now() + 864e5 * 14), - type: "new_business", - forecast_category: "commit" - }, - { - name: "Initech Cloud Migration", - amount: 8e4, - stage: "needs_analysis", - probability: 25, - close_date: new Date(Date.now() + 864e5 * 45), - type: "existing_business", - forecast_category: "best_case" - } - ] -}; -var products = { - object: "product", - mode: "upsert", - externalId: "name", - records: [ - { - name: "ObjectStack Platform", - category: "software", - family: "enterprise", - list_price: 5e4, - is_active: true - }, - { - name: "Cloud Hosting (Annual)", - category: "subscription", - family: "cloud", - list_price: 12e3, - is_active: true - }, - { - name: "Premium Support", - category: "support", - family: "services", - list_price: 25e3, - is_active: true - }, - { - name: "Implementation Services", - category: "service", - family: "services", - list_price: 75e3, - is_active: true - } - ] -}; -var tasks = { - object: "task", - mode: "upsert", - externalId: "subject", - records: [ - { - subject: "Follow up with Acme on proposal", - status: "not_started", - priority: "high", - due_date: new Date(Date.now() + 864e5 * 2) - }, - { - subject: "Schedule demo for Globex team", - status: "in_progress", - priority: "normal", - due_date: new Date(Date.now() + 864e5 * 5) - }, - { - subject: "Prepare contract for Wayne Enterprises", - status: "not_started", - priority: "urgent", - due_date: new Date(Date.now() + 864e5) - }, - { - subject: "Send welcome package to Stark Medical", - status: "completed", - priority: "low" - }, - { - subject: "Update CRM pipeline report", - status: "not_started", - priority: "normal", - due_date: new Date(Date.now() + 864e5 * 7) - } - ] -}; -var CrmSeedData = [ - accounts, - contacts, - leads, - opportunities, - products, - tasks -]; - -// ../app-crm/src/sharing/account.sharing.ts -var AccountTeamSharingRule = { - name: "account_team_sharing", - label: "Account Team Sharing", - object: "account", - type: "criteria", - condition: 'type = "customer" AND is_active = true', - accessLevel: "edit", - sharedWith: { type: "role", value: "sales_manager" } -}; -var TerritorySharingRules = [ - { - name: "north_america_territory", - label: "North America Territory", - object: "account", - type: "criteria", - condition: 'billing_country IN ("US", "CA", "MX")', - accessLevel: "edit", - sharedWith: { type: "role", value: "na_sales_team" } - }, - { - name: "europe_territory", - label: "Europe Territory", - object: "account", - type: "criteria", - condition: 'billing_country IN ("UK", "DE", "FR", "IT", "ES")', - accessLevel: "edit", - sharedWith: { type: "role", value: "eu_sales_team" } - } -]; - -// ../app-crm/src/sharing/case.sharing.ts -var CaseEscalationSharingRule = { - name: "case_escalation_sharing", - label: "Escalated Cases Sharing", - object: "case", - type: "criteria", - condition: 'priority = "critical" AND is_closed = false', - accessLevel: "edit", - sharedWith: { type: "role_and_subordinates", value: "service_manager" } -}; - -// ../app-crm/src/sharing/opportunity.sharing.ts -var OpportunitySalesSharingRule = { - name: "opportunity_sales_sharing", - label: "Opportunity Sales Team Sharing", - object: "opportunity", - type: "criteria", - condition: 'stage NOT IN ("closed_won", "closed_lost") AND amount >= 100000', - accessLevel: "read", - sharedWith: { type: "role_and_subordinates", value: "sales_director" } -}; - -// ../app-crm/src/sharing/role-hierarchy.ts -var RoleHierarchy = { - name: "crm_role_hierarchy", - label: "CRM Role Hierarchy", - roles: [ - { name: "executive", label: "Executive", parentRole: null }, - { name: "sales_director", label: "Sales Director", parentRole: "executive" }, - { name: "sales_manager", label: "Sales Manager", parentRole: "sales_director" }, - { name: "sales_rep", label: "Sales Representative", parentRole: "sales_manager" }, - { name: "service_director", label: "Service Director", parentRole: "executive" }, - { name: "service_manager", label: "Service Manager", parentRole: "service_director" }, - { name: "service_agent", label: "Service Agent", parentRole: "service_manager" }, - { name: "marketing_director", label: "Marketing Director", parentRole: "executive" }, - { name: "marketing_manager", label: "Marketing Manager", parentRole: "marketing_director" }, - { name: "marketing_user", label: "Marketing User", parentRole: "marketing_manager" } - ] -}; - -// ../app-crm/objectstack.config.ts -var objectstack_config_default = defineStack({ - manifest: { - id: "com.example.crm", - namespace: "crm", - version: "3.0.0", - type: "app", - name: "Enterprise CRM", - description: "Comprehensive enterprise CRM demonstrating all ObjectStack Protocol features including AI, security, and automation" - }, - // Auto-collected from barrel index files via Object.values() - objects: Object.values(objects_exports), - apis: Object.values(apis_exports), - actions: Object.values(actions_exports), - dashboards: Object.values(dashboards_exports), - reports: Object.values(reports_exports), - flows: allFlows, - agents: allAgents, - ragPipelines: Object.values(rag_exports), - permissions: Object.values(profiles_exports), - apps: Object.values(apps_exports), - // Seed Data (top-level, registered as metadata) - data: CrmSeedData, - // I18n Configuration — per-locale file organization - i18n: { - defaultLocale: "en", - supportedLocales: ["en", "zh-CN", "ja-JP", "es-ES"], - fallbackLocale: "en", - fileOrganization: "per_locale" - }, - // I18n Translation Bundles (en, zh-CN, ja-JP, es-ES) - translations: Object.values(translations_exports), - // Sharing & security - sharingRules: [ - AccountTeamSharingRule, - OpportunitySalesSharingRule, - CaseEscalationSharingRule, - ...TerritorySharingRules - ], - roles: RoleHierarchy.roles.map((r) => ({ - name: r.name, - label: r.label, - parent: r.parentRole ?? void 0 - })) -}); - -// ../app-todo/src/objects/index.ts -var objects_exports2 = {}; -__export(objects_exports2, { - Task: () => Task4 -}); - -// ../app-todo/src/objects/task.object.ts -init_data(); -var Task4 = ObjectSchema3.create({ - name: "task", - label: "Task", - pluralLabel: "Tasks", - icon: "check-square", - description: "Personal tasks and to-do items", - fields: { - // Task Information - subject: Field.text({ - label: "Subject", - required: true, - searchable: true, - maxLength: 255 - }), - description: Field.markdown({ - label: "Description" - }), - // Task Management - status: Field.select({ - label: "Status", - required: true, - options: [ - { label: "Not Started", value: "not_started", color: "#808080", default: true }, - { label: "In Progress", value: "in_progress", color: "#3B82F6" }, - { label: "Waiting", value: "waiting", color: "#F59E0B" }, - { label: "Completed", value: "completed", color: "#10B981" }, - { label: "Deferred", value: "deferred", color: "#6B7280" } - ] - }), - priority: Field.select({ - label: "Priority", - required: true, - options: [ - { label: "Low", value: "low", color: "#60A5FA", default: true }, - { label: "Normal", value: "normal", color: "#10B981" }, - { label: "High", value: "high", color: "#F59E0B" }, - { label: "Urgent", value: "urgent", color: "#EF4444" } - ] - }), - category: Field.select({ - label: "Category", - options: [ - { label: "Personal", value: "personal" }, - { label: "Work", value: "work" }, - { label: "Shopping", value: "shopping" }, - { label: "Health", value: "health" }, - { label: "Finance", value: "finance" }, - { label: "Other", value: "other" } - ] - }), - // Dates - due_date: Field.date({ - label: "Due Date" - }), - reminder_date: Field.datetime({ - label: "Reminder Date/Time" - }), - completed_date: Field.datetime({ - label: "Completed Date", - readonly: true - }), - // Assignment - owner: Field.lookup("user", { - label: "Assigned To", - required: true - }), - // Tags - tags: Field.select({ - label: "Tags", - multiple: true, - options: [ - { label: "Important", value: "important", color: "#EF4444" }, - { label: "Quick Win", value: "quick_win", color: "#10B981" }, - { label: "Blocked", value: "blocked", color: "#F59E0B" }, - { label: "Follow Up", value: "follow_up", color: "#3B82F6" }, - { label: "Review", value: "review", color: "#8B5CF6" } - ] - }), - // Recurrence - is_recurring: Field.boolean({ - label: "Recurring Task", - defaultValue: false - }), - recurrence_type: Field.select({ - label: "Recurrence Type", - options: [ - { label: "Daily", value: "daily" }, - { label: "Weekly", value: "weekly" }, - { label: "Monthly", value: "monthly" }, - { label: "Yearly", value: "yearly" } - ] - }), - recurrence_interval: Field.number({ - label: "Recurrence Interval", - defaultValue: 1, - min: 1 - }), - // Flags - is_completed: Field.boolean({ - label: "Is Completed", - defaultValue: false, - readonly: true - }), - is_overdue: Field.boolean({ - label: "Is Overdue", - defaultValue: false, - readonly: true - }), - // Progress - progress_percent: Field.percent({ - label: "Progress (%)", - min: 0, - max: 100, - defaultValue: 0 - }), - // Time Tracking - estimated_hours: Field.number({ - label: "Estimated Hours", - scale: 2, - min: 0 - }), - actual_hours: Field.number({ - label: "Actual Hours", - scale: 2, - min: 0 - }), - // Additional fields - notes: Field.richtext({ - label: "Notes", - description: "Rich text notes with formatting" - }), - category_color: Field.color({ - label: "Category Color", - colorFormat: "hex", - presetColors: ["#EF4444", "#F59E0B", "#10B981", "#3B82F6", "#8B5CF6"] - }) - }, - enable: { - trackHistory: true, - searchable: true, - apiEnabled: true, - files: true, - feeds: true, - activities: true, - trash: true, - mru: true - }, - // Database indexes for performance - indexes: [ - { fields: ["status"] }, - { fields: ["priority"] }, - { fields: ["owner"] }, - { fields: ["due_date"] }, - { fields: ["category"] } - ], - titleFormat: "{subject}", - compactLayout: ["subject", "status", "priority", "due_date", "owner"], - validations: [ - { - name: "completed_date_required", - type: "script", - severity: "error", - message: "Completed date is required when status is Completed", - condition: 'status = "completed" AND ISBLANK(completed_date)' - }, - { - name: "recurrence_fields_required", - type: "script", - severity: "error", - message: "Recurrence type is required for recurring tasks", - condition: "is_recurring = true AND ISBLANK(recurrence_type)" - } - ], - workflows: [ - { - name: "set_completed_flag", - objectName: "task", - triggerType: "on_create_or_update", - criteria: "ISCHANGED(status)", - active: true, - actions: [ - { - name: "update_completed_flag", - type: "field_update", - field: "is_completed", - value: 'status = "completed"' - } - ] - }, - { - name: "set_completed_date", - objectName: "task", - triggerType: "on_update", - criteria: 'ISCHANGED(status) AND status = "completed"', - active: true, - actions: [ - { - name: "set_date", - type: "field_update", - field: "completed_date", - value: "NOW()" - }, - { - name: "set_progress", - type: "field_update", - field: "progress_percent", - value: "100" - } - ] - }, - { - name: "check_overdue", - objectName: "task", - triggerType: "on_create_or_update", - criteria: "due_date < TODAY() AND is_completed = false", - active: true, - actions: [ - { - name: "set_overdue_flag", - type: "field_update", - field: "is_overdue", - value: "true" - } - ] - }, - { - name: "notify_on_urgent", - objectName: "task", - triggerType: "on_create_or_update", - criteria: 'priority = "urgent" AND is_completed = false', - active: true, - actions: [ - { - name: "email_owner", - type: "email_alert", - template: "urgent_task_alert", - recipients: ["{owner.email}"] - } - ] - } - ] -}); - -// ../app-todo/src/actions/index.ts -var actions_exports2 = {}; -__export(actions_exports2, { - CloneTaskAction: () => CloneTaskAction, - CompleteTaskAction: () => CompleteTaskAction, - DeferTaskAction: () => DeferTaskAction, - DeleteCompletedAction: () => DeleteCompletedAction, - ExportToCsvAction: () => ExportToCsvAction2, - MassCompleteTasksAction: () => MassCompleteTasksAction, - SetReminderAction: () => SetReminderAction, - StartTaskAction: () => StartTaskAction -}); - -// ../app-todo/src/actions/task.actions.ts -var CompleteTaskAction = { - name: "complete_task", - label: "Mark Complete", - objectName: "task", - icon: "check-circle", - type: "script", - target: "completeTask", - locations: ["record_header", "list_item"], - successMessage: "Task marked as complete!", - refreshAfter: true -}; -var StartTaskAction = { - name: "start_task", - label: "Start Task", - objectName: "task", - icon: "play-circle", - type: "script", - target: "startTask", - locations: ["record_header", "list_item"], - successMessage: "Task started!", - refreshAfter: true -}; -var DeferTaskAction = { - name: "defer_task", - label: "Defer Task", - objectName: "task", - icon: "clock", - type: "modal", - target: "defer_task_modal", - locations: ["record_header"], - params: [ - { - name: "new_due_date", - label: "New Due Date", - type: "date", - required: true - }, - { - name: "reason", - label: "Reason for Deferral", - type: "textarea", - required: false - } - ], - successMessage: "Task deferred successfully!", - refreshAfter: true -}; -var SetReminderAction = { - name: "set_reminder", - label: "Set Reminder", - objectName: "task", - icon: "bell", - type: "modal", - target: "set_reminder_modal", - locations: ["record_header", "list_item"], - params: [ - { - name: "reminder_date", - label: "Reminder Date/Time", - type: "datetime", - required: true - } - ], - successMessage: "Reminder set!", - refreshAfter: true -}; -var CloneTaskAction = { - name: "clone_task", - label: "Clone Task", - objectName: "task", - icon: "copy", - type: "script", - target: "cloneTask", - locations: ["record_header"], - successMessage: "Task cloned successfully!", - refreshAfter: true -}; -var MassCompleteTasksAction = { - name: "mass_complete", - label: "Complete Selected", - objectName: "task", - icon: "check-square", - type: "script", - target: "massCompleteTasks", - locations: ["list_toolbar"], - successMessage: "Selected tasks marked as complete!", - refreshAfter: true -}; -var DeleteCompletedAction = { - name: "delete_completed", - label: "Delete Completed", - objectName: "task", - icon: "trash-2", - type: "script", - target: "deleteCompletedTasks", - locations: ["list_toolbar"], - successMessage: "Completed tasks deleted!", - refreshAfter: true -}; -var ExportToCsvAction2 = { - name: "export_csv", - label: "Export to CSV", - objectName: "task", - icon: "download", - type: "script", - target: "exportTasksToCSV", - locations: ["list_toolbar"], - successMessage: "Export completed!", - refreshAfter: false -}; - -// ../app-todo/src/dashboards/index.ts -var dashboards_exports2 = {}; -__export(dashboards_exports2, { - TaskDashboard: () => TaskDashboard -}); - -// ../app-todo/src/dashboards/task.dashboard.ts -var TaskDashboard = { - name: "task_dashboard", - label: "Task Overview", - description: "Key task metrics and productivity overview", - widgets: [ - // Row 1: Key Metrics - { - id: "total_tasks", - title: "Total Tasks", - type: "metric", - object: "task", - aggregate: "count", - layout: { x: 0, y: 0, w: 3, h: 2 }, - options: { color: "#3B82F6" } - }, - { - id: "completed_today", - title: "Completed Today", - type: "metric", - object: "task", - filter: { is_completed: true, completed_date: { $gte: "{today_start}" } }, - aggregate: "count", - layout: { x: 3, y: 0, w: 3, h: 2 }, - options: { color: "#10B981" } - }, - { - id: "overdue_tasks", - title: "Overdue Tasks", - type: "metric", - object: "task", - filter: { is_overdue: true, is_completed: false }, - aggregate: "count", - layout: { x: 6, y: 0, w: 3, h: 2 }, - options: { color: "#EF4444" } - }, - { - id: "completion_rate", - title: "Completion Rate", - type: "metric", - object: "task", - filter: { created_date: { $gte: "{current_week_start}" } }, - valueField: "is_completed", - aggregate: "count", - layout: { x: 9, y: 0, w: 3, h: 2 }, - options: { suffix: "%", color: "#8B5CF6" } - }, - // Row 2: Task Distribution - { - id: "tasks_by_status", - title: "Tasks by Status", - type: "pie", - object: "task", - filter: { is_completed: false }, - categoryField: "status", - aggregate: "count", - layout: { x: 0, y: 2, w: 6, h: 4 }, - options: { showLegend: true } - }, - { - id: "tasks_by_priority", - title: "Tasks by Priority", - type: "bar", - object: "task", - filter: { is_completed: false }, - categoryField: "priority", - aggregate: "count", - layout: { x: 6, y: 2, w: 6, h: 4 }, - options: { horizontal: true } - }, - // Row 3: Trends - { - id: "weekly_task_completion", - title: "Weekly Task Completion", - type: "line", - object: "task", - filter: { is_completed: true, completed_date: { $gte: "{last_4_weeks}" } }, - categoryField: "completed_date", - aggregate: "count", - layout: { x: 0, y: 6, w: 8, h: 4 }, - options: { showDataLabels: true } - }, - { - id: "tasks_by_category", - title: "Tasks by Category", - type: "donut", - object: "task", - filter: { is_completed: false }, - categoryField: "category", - aggregate: "count", - layout: { x: 8, y: 6, w: 4, h: 4 }, - options: { showLegend: true } - }, - // Row 4: Tables - { - id: "overdue_tasks_table", - title: "Overdue Tasks", - type: "table", - object: "task", - filter: { is_overdue: true, is_completed: false }, - aggregate: "count", - layout: { x: 0, y: 10, w: 6, h: 4 } - }, - { - id: "due_today", - title: "Due Today", - type: "table", - object: "task", - filter: { due_date: "{today}", is_completed: false }, - aggregate: "count", - layout: { x: 6, y: 10, w: 6, h: 4 } - } - ] -}; - -// ../app-todo/src/reports/index.ts -var reports_exports2 = {}; -__export(reports_exports2, { - CompletedTasksReport: () => CompletedTasksReport, - OverdueTasksReport: () => OverdueTasksReport, - TasksByOwnerReport: () => TasksByOwnerReport2, - TasksByPriorityReport: () => TasksByPriorityReport, - TasksByStatusReport: () => TasksByStatusReport, - TimeTrackingReport: () => TimeTrackingReport -}); - -// ../app-todo/src/reports/task.report.ts -var TasksByStatusReport = { - name: "tasks_by_status", - label: "Tasks by Status", - description: "Summary of tasks grouped by status", - objectName: "task", - type: "summary", - columns: [ - { field: "subject", label: "Subject" }, - { field: "priority", label: "Priority" }, - { field: "due_date", label: "Due Date" }, - { field: "owner", label: "Assigned To" } - ], - groupingsDown: [{ field: "status", sortOrder: "asc" }] -}; -var TasksByPriorityReport = { - name: "tasks_by_priority", - label: "Tasks by Priority", - description: "Summary of tasks grouped by priority level", - objectName: "task", - type: "summary", - columns: [ - { field: "subject", label: "Subject" }, - { field: "status", label: "Status" }, - { field: "due_date", label: "Due Date" }, - { field: "category", label: "Category" } - ], - groupingsDown: [{ field: "priority", sortOrder: "desc" }], - filter: { is_completed: false } -}; -var TasksByOwnerReport2 = { - name: "tasks_by_owner", - label: "Tasks by Owner", - description: "Task summary by assignee", - objectName: "task", - type: "summary", - columns: [ - { field: "subject", label: "Subject" }, - { field: "status", label: "Status" }, - { field: "priority", label: "Priority" }, - { field: "due_date", label: "Due Date" }, - { field: "estimated_hours", label: "Est. Hours", aggregate: "sum" }, - { field: "actual_hours", label: "Actual Hours", aggregate: "sum" } - ], - groupingsDown: [{ field: "owner", sortOrder: "asc" }], - filter: { is_completed: false } -}; -var OverdueTasksReport = { - name: "overdue_tasks", - label: "Overdue Tasks", - description: "All overdue tasks that need attention", - objectName: "task", - type: "tabular", - columns: [ - { field: "subject", label: "Subject" }, - { field: "due_date", label: "Due Date" }, - { field: "priority", label: "Priority" }, - { field: "owner", label: "Assigned To" }, - { field: "category", label: "Category" } - ], - filter: { is_overdue: true, is_completed: false } -}; -var CompletedTasksReport = { - name: "completed_tasks", - label: "Completed Tasks", - description: "All completed tasks with time tracking", - objectName: "task", - type: "summary", - columns: [ - { field: "subject", label: "Subject" }, - { field: "completed_date", label: "Completed Date" }, - { field: "estimated_hours", label: "Est. Hours", aggregate: "sum" }, - { field: "actual_hours", label: "Actual Hours", aggregate: "sum" } - ], - groupingsDown: [{ field: "category", sortOrder: "asc" }], - filter: { is_completed: true } -}; -var TimeTrackingReport = { - name: "time_tracking", - label: "Time Tracking Report", - description: "Estimated vs actual hours analysis", - objectName: "task", - type: "matrix", - columns: [ - { field: "estimated_hours", label: "Estimated Hours", aggregate: "sum" }, - { field: "actual_hours", label: "Actual Hours", aggregate: "sum" } - ], - groupingsDown: [{ field: "owner", sortOrder: "asc" }], - groupingsAcross: [{ field: "category", sortOrder: "asc" }], - filter: { is_completed: true } -}; - -// ../app-todo/src/flows/task.flow.ts -var TaskReminderFlow = { - name: "task_reminder", - label: "Task Reminder Notification", - description: "Automated flow to send reminders for tasks approaching their due date", - type: "schedule", - variables: [ - { name: "tasksToRemind", type: "record_collection", isInput: false, isOutput: false } - ], - nodes: [ - { id: "start", type: "start", label: "Start (Daily 8 AM)", config: { schedule: "0 8 * * *", objectName: "task" } }, - { - id: "get_upcoming_tasks", - type: "get_record", - label: "Get Tasks Due Tomorrow", - config: { objectName: "task", filter: { due_date: "{tomorrow}", is_completed: false }, outputVariable: "tasksToRemind", getAll: true } - }, - { - id: "loop_tasks", - type: "loop", - label: "Loop Through Tasks", - config: { collection: "{tasksToRemind}", iteratorVariable: "currentTask" } - }, - { - id: "send_reminder", - type: "script", - label: "Send Reminder Email", - config: { - actionType: "email", - inputs: { - to: "{currentTask.owner.email}", - subject: "Task Due Tomorrow: {currentTask.subject}", - template: "task_reminder_email", - data: { taskSubject: "{currentTask.subject}", dueDate: "{currentTask.due_date}", priority: "{currentTask.priority}" } - } - } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "get_upcoming_tasks", type: "default" }, - { id: "e2", source: "get_upcoming_tasks", target: "loop_tasks", type: "default" }, - { id: "e3", source: "loop_tasks", target: "send_reminder", type: "default" }, - { id: "e4", source: "send_reminder", target: "end", type: "default" } - ] -}; -var OverdueEscalationFlow = { - name: "overdue_escalation", - label: "Overdue Task Escalation", - description: "Escalates tasks that have been overdue for more than 3 days", - type: "schedule", - variables: [ - { name: "overdueTasks", type: "record_collection", isInput: false, isOutput: false } - ], - nodes: [ - { id: "start", type: "start", label: "Start (Daily 9 AM)", config: { schedule: "0 9 * * *", objectName: "task" } }, - { - id: "get_overdue_tasks", - type: "get_record", - label: "Get Severely Overdue Tasks", - config: { - objectName: "task", - filter: { due_date: { $lt: "{3_days_ago}" }, is_completed: false, is_overdue: true }, - outputVariable: "overdueTasks", - getAll: true - } - }, - { - id: "loop_overdue", - type: "loop", - label: "Loop Through Overdue Tasks", - config: { collection: "{overdueTasks}", iteratorVariable: "currentTask" } - }, - { - id: "update_priority", - type: "update_record", - label: "Escalate Priority", - config: { - objectName: "task", - filter: { id: "{currentTask.id}" }, - fields: { priority: "urgent", tags: ["important", "follow_up"] } - } - }, - { - id: "notify_owner", - type: "script", - label: "Notify Task Owner", - config: { - actionType: "email", - inputs: { - to: "{currentTask.owner.email}", - subject: "URGENT: Task Overdue - {currentTask.subject}", - template: "overdue_escalation_email", - data: { taskSubject: "{currentTask.subject}", dueDate: "{currentTask.due_date}", daysOverdue: "{currentTask.days_overdue}" } - } - } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "get_overdue_tasks", type: "default" }, - { id: "e2", source: "get_overdue_tasks", target: "loop_overdue", type: "default" }, - { id: "e3", source: "loop_overdue", target: "update_priority", type: "default" }, - { id: "e4", source: "update_priority", target: "notify_owner", type: "default" }, - { id: "e5", source: "notify_owner", target: "end", type: "default" } - ] -}; -var TaskCompletionFlow = { - name: "task_completion", - label: "Task Completion Process", - description: "Flow triggered when a task is marked as complete", - type: "record_change", - variables: [ - { name: "taskId", type: "text", isInput: true, isOutput: false }, - { name: "completedTask", type: "record", isInput: false, isOutput: false } - ], - nodes: [ - { id: "start", type: "start", label: "Start", config: { objectName: "task", triggerCondition: 'ISCHANGED(status) AND status = "completed"' } }, - { - id: "get_task", - type: "get_record", - label: "Get Completed Task", - config: { objectName: "task", filter: { id: "{taskId}" }, outputVariable: "completedTask" } - }, - { - id: "check_recurring", - type: "decision", - label: "Is Recurring Task?", - config: { condition: "{completedTask.is_recurring} == true" } - }, - { - id: "create_next_task", - type: "create_record", - label: "Create Next Recurring Task", - config: { - objectName: "task", - fields: { - subject: "{completedTask.subject}", - description: "{completedTask.description}", - priority: "{completedTask.priority}", - category: "{completedTask.category}", - owner: "{completedTask.owner}", - is_recurring: true, - recurrence_type: "{completedTask.recurrence_type}", - recurrence_interval: "{completedTask.recurrence_interval}", - due_date: 'DATEADD({completedTask.due_date}, {completedTask.recurrence_interval}, "{completedTask.recurrence_type}")', - status: "not_started", - is_completed: false - }, - outputVariable: "newTaskId" - } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "get_task", type: "default" }, - { id: "e2", source: "get_task", target: "check_recurring", type: "default" }, - { id: "e3", source: "check_recurring", target: "create_next_task", type: "default", condition: "{completedTask.is_recurring} == true", label: "Yes" }, - { id: "e4", source: "check_recurring", target: "end", type: "default", condition: "{completedTask.is_recurring} != true", label: "No" }, - { id: "e5", source: "create_next_task", target: "end", type: "default" } - ] -}; -var QuickAddTaskFlow = { - name: "quick_add_task", - label: "Quick Add Task", - description: "Screen flow for quickly creating a new task", - type: "screen", - variables: [ - { name: "subject", type: "text", isInput: true, isOutput: false }, - { name: "priority", type: "text", isInput: true, isOutput: false }, - { name: "dueDate", type: "date", isInput: true, isOutput: false }, - { name: "newTaskId", type: "text", isInput: false, isOutput: true } - ], - nodes: [ - { id: "start", type: "start", label: "Start" }, - { - id: "screen_1", - type: "screen", - label: "Task Details", - config: { - fields: [ - { name: "subject", label: "Task Subject", type: "text", required: true }, - { name: "priority", label: "Priority", type: "select", options: ["low", "normal", "high", "urgent"], defaultValue: "normal" }, - { name: "dueDate", label: "Due Date", type: "date", required: false }, - { name: "category", label: "Category", type: "select", options: ["personal", "work", "shopping", "health", "finance", "other"] } - ] - } - }, - { - id: "create_task", - type: "create_record", - label: "Create Task", - config: { - objectName: "task", - fields: { subject: "{subject}", priority: "{priority}", due_date: "{dueDate}", category: "{category}", status: "not_started", owner: "{$User.Id}" }, - outputVariable: "newTaskId" - } - }, - { - id: "success_screen", - type: "screen", - label: "Success", - config: { - message: 'Task "{subject}" created successfully!', - buttons: [ - { label: "Create Another", action: "restart" }, - { label: "View Task", action: "navigate", target: "/task/{newTaskId}" }, - { label: "Done", action: "finish" } - ] - } - }, - { id: "end", type: "end", label: "End" } - ], - edges: [ - { id: "e1", source: "start", target: "screen_1", type: "default" }, - { id: "e2", source: "screen_1", target: "create_task", type: "default" }, - { id: "e3", source: "create_task", target: "success_screen", type: "default" }, - { id: "e4", source: "success_screen", target: "end", type: "default" } - ] -}; - -// ../app-todo/src/flows/index.ts -var allFlows2 = [ - TaskReminderFlow, - OverdueEscalationFlow, - TaskCompletionFlow, - QuickAddTaskFlow -]; - -// ../app-todo/src/apps/index.ts -var apps_exports2 = {}; -__export(apps_exports2, { - TodoApp: () => TodoApp -}); - -// ../app-todo/src/apps/todo.app.ts -var TodoApp = App.create({ - name: "todo_app", - label: "Todo Manager", - icon: "check-square", - branding: { - primaryColor: "#10B981", - secondaryColor: "#3B82F6", - logo: "/assets/todo-logo.png", - favicon: "/assets/todo-favicon.ico" - }, - navigation: [ - { - id: "group_tasks", - type: "group", - label: "Tasks", - icon: "check-square", - children: [ - { id: "nav_all_tasks", type: "object", objectName: "task", label: "All Tasks", icon: "list" }, - { id: "nav_my_tasks", type: "object", objectName: "task", label: "My Tasks", icon: "user-check" }, - { id: "nav_overdue", type: "object", objectName: "task", label: "Overdue", icon: "alert-circle" }, - { id: "nav_today", type: "object", objectName: "task", label: "Due Today", icon: "calendar" }, - { id: "nav_upcoming", type: "object", objectName: "task", label: "Upcoming", icon: "calendar-plus" } - ] - }, - { - id: "group_analytics", - type: "group", - label: "Analytics", - icon: "chart-bar", - children: [ - { id: "nav_dashboard", type: "dashboard", dashboardName: "task_dashboard", label: "Dashboard", icon: "layout-dashboard" } - ] - } - ] -}); - -// ../app-todo/src/translations/index.ts -var translations_exports2 = {}; -__export(translations_exports2, { - TodoTranslations: () => TodoTranslations -}); - -// ../app-todo/src/translations/en.ts -var en2 = { - objects: { - task: { - label: "Task", - pluralLabel: "Tasks", - fields: { - subject: { label: "Subject", help: "Brief title of the task" }, - description: { label: "Description" }, - status: { - label: "Status", - options: { - not_started: "Not Started", - in_progress: "In Progress", - waiting: "Waiting", - completed: "Completed", - deferred: "Deferred" - } - }, - priority: { - label: "Priority", - options: { - low: "Low", - normal: "Normal", - high: "High", - urgent: "Urgent" - } - }, - category: { - label: "Category", - options: { - personal: "Personal", - work: "Work", - shopping: "Shopping", - health: "Health", - finance: "Finance", - other: "Other" - } - }, - due_date: { label: "Due Date" }, - reminder_date: { label: "Reminder Date/Time" }, - completed_date: { label: "Completed Date" }, - owner: { label: "Assigned To" }, - tags: { - label: "Tags", - options: { - important: "Important", - quick_win: "Quick Win", - blocked: "Blocked", - follow_up: "Follow Up", - review: "Review" - } - }, - is_recurring: { label: "Recurring Task" }, - recurrence_type: { - label: "Recurrence Type", - options: { - daily: "Daily", - weekly: "Weekly", - monthly: "Monthly", - yearly: "Yearly" - } - }, - recurrence_interval: { label: "Recurrence Interval" }, - is_completed: { label: "Is Completed" }, - is_overdue: { label: "Is Overdue" }, - progress_percent: { label: "Progress (%)" }, - estimated_hours: { label: "Estimated Hours" }, - actual_hours: { label: "Actual Hours" }, - notes: { label: "Notes" }, - category_color: { label: "Category Color" } - } - } - }, - apps: { - todo_app: { - label: "Todo Manager", - description: "Personal task management application" - } - }, - messages: { - "common.save": "Save", - "common.cancel": "Cancel", - "common.delete": "Delete", - "common.edit": "Edit", - "common.create": "Create", - "common.search": "Search", - "common.filter": "Filter", - "common.sort": "Sort", - "common.refresh": "Refresh", - "common.export": "Export", - "common.back": "Back", - "common.confirm": "Confirm", - "success.saved": "Successfully saved", - "success.deleted": "Successfully deleted", - "success.completed": "Task marked as completed", - "confirm.delete": "Are you sure you want to delete this task?", - "confirm.complete": "Mark this task as completed?", - "error.required": "This field is required", - "error.load_failed": "Failed to load data" - }, - validationMessages: { - completed_date_required: "Completed date is required when status is Completed", - recurrence_fields_required: "Recurrence type is required for recurring tasks" - } -}; - -// ../app-todo/src/translations/zh-CN.ts -var zhCN2 = { - objects: { - task: { - label: "\u4EFB\u52A1", - pluralLabel: "\u4EFB\u52A1", - fields: { - subject: { label: "\u4E3B\u9898", help: "\u4EFB\u52A1\u7684\u7B80\u8981\u6807\u9898" }, - description: { label: "\u63CF\u8FF0" }, - status: { - label: "\u72B6\u6001", - options: { - not_started: "\u672A\u5F00\u59CB", - in_progress: "\u8FDB\u884C\u4E2D", - waiting: "\u7B49\u5F85\u4E2D", - completed: "\u5DF2\u5B8C\u6210", - deferred: "\u5DF2\u63A8\u8FDF" - } - }, - priority: { - label: "\u4F18\u5148\u7EA7", - options: { - low: "\u4F4E", - normal: "\u666E\u901A", - high: "\u9AD8", - urgent: "\u7D27\u6025" - } - }, - category: { - label: "\u5206\u7C7B", - options: { - personal: "\u4E2A\u4EBA", - work: "\u5DE5\u4F5C", - shopping: "\u8D2D\u7269", - health: "\u5065\u5EB7", - finance: "\u8D22\u52A1", - other: "\u5176\u4ED6" - } - }, - due_date: { label: "\u622A\u6B62\u65E5\u671F" }, - reminder_date: { label: "\u63D0\u9192\u65E5\u671F/\u65F6\u95F4" }, - completed_date: { label: "\u5B8C\u6210\u65E5\u671F" }, - owner: { label: "\u8D1F\u8D23\u4EBA" }, - tags: { - label: "\u6807\u7B7E", - options: { - important: "\u91CD\u8981", - quick_win: "\u901F\u80DC", - blocked: "\u53D7\u963B", - follow_up: "\u5F85\u8DDF\u8FDB", - review: "\u5F85\u5BA1\u6838" - } - }, - is_recurring: { label: "\u5468\u671F\u6027\u4EFB\u52A1" }, - recurrence_type: { - label: "\u91CD\u590D\u7C7B\u578B", - options: { - daily: "\u6BCF\u5929", - weekly: "\u6BCF\u5468", - monthly: "\u6BCF\u6708", - yearly: "\u6BCF\u5E74" - } - }, - recurrence_interval: { label: "\u91CD\u590D\u95F4\u9694" }, - is_completed: { label: "\u662F\u5426\u5B8C\u6210" }, - is_overdue: { label: "\u662F\u5426\u903E\u671F" }, - progress_percent: { label: "\u8FDB\u5EA6 (%)" }, - estimated_hours: { label: "\u9884\u4F30\u5DE5\u65F6" }, - actual_hours: { label: "\u5B9E\u9645\u5DE5\u65F6" }, - notes: { label: "\u5907\u6CE8" }, - category_color: { label: "\u5206\u7C7B\u989C\u8272" } - } - } - }, - apps: { - todo_app: { - label: "\u5F85\u529E\u7BA1\u7406", - description: "\u4E2A\u4EBA\u4EFB\u52A1\u7BA1\u7406\u5E94\u7528" - } - }, - messages: { - "common.save": "\u4FDD\u5B58", - "common.cancel": "\u53D6\u6D88", - "common.delete": "\u5220\u9664", - "common.edit": "\u7F16\u8F91", - "common.create": "\u65B0\u5EFA", - "common.search": "\u641C\u7D22", - "common.filter": "\u7B5B\u9009", - "common.sort": "\u6392\u5E8F", - "common.refresh": "\u5237\u65B0", - "common.export": "\u5BFC\u51FA", - "common.back": "\u8FD4\u56DE", - "common.confirm": "\u786E\u8BA4", - "success.saved": "\u4FDD\u5B58\u6210\u529F", - "success.deleted": "\u5220\u9664\u6210\u529F", - "success.completed": "\u4EFB\u52A1\u5DF2\u6807\u8BB0\u4E3A\u5B8C\u6210", - "confirm.delete": "\u786E\u5B9A\u8981\u5220\u9664\u6B64\u4EFB\u52A1\u5417\uFF1F", - "confirm.complete": "\u786E\u5B9A\u5C06\u6B64\u4EFB\u52A1\u6807\u8BB0\u4E3A\u5B8C\u6210\uFF1F", - "error.required": "\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879", - "error.load_failed": "\u6570\u636E\u52A0\u8F7D\u5931\u8D25" - }, - validationMessages: { - completed_date_required: '\u72B6\u6001\u4E3A"\u5DF2\u5B8C\u6210"\u65F6\uFF0C\u5B8C\u6210\u65E5\u671F\u4E3A\u5FC5\u586B\u9879', - recurrence_fields_required: "\u5468\u671F\u6027\u4EFB\u52A1\u5FC5\u987B\u6307\u5B9A\u91CD\u590D\u7C7B\u578B" - } -}; - -// ../app-todo/src/translations/ja-JP.ts -var jaJP2 = { - objects: { - task: { - label: "\u30BF\u30B9\u30AF", - pluralLabel: "\u30BF\u30B9\u30AF", - fields: { - subject: { label: "\u4EF6\u540D", help: "\u30BF\u30B9\u30AF\u306E\u7C21\u5358\u306A\u30BF\u30A4\u30C8\u30EB" }, - description: { label: "\u8AAC\u660E" }, - status: { - label: "\u30B9\u30C6\u30FC\u30BF\u30B9", - options: { - not_started: "\u672A\u7740\u624B", - in_progress: "\u9032\u884C\u4E2D", - waiting: "\u5F85\u6A5F\u4E2D", - completed: "\u5B8C\u4E86", - deferred: "\u5EF6\u671F" - } - }, - priority: { - label: "\u512A\u5148\u5EA6", - options: { - low: "\u4F4E", - normal: "\u901A\u5E38", - high: "\u9AD8", - urgent: "\u7DCA\u6025" - } - }, - category: { - label: "\u30AB\u30C6\u30B4\u30EA", - options: { - personal: "\u500B\u4EBA", - work: "\u4ED5\u4E8B", - shopping: "\u8CB7\u3044\u7269", - health: "\u5065\u5EB7", - finance: "\u8CA1\u52D9", - other: "\u305D\u306E\u4ED6" - } - }, - due_date: { label: "\u671F\u65E5" }, - reminder_date: { label: "\u30EA\u30DE\u30A4\u30F3\u30C0\u30FC\u65E5\u6642" }, - completed_date: { label: "\u5B8C\u4E86\u65E5" }, - owner: { label: "\u62C5\u5F53\u8005" }, - tags: { - label: "\u30BF\u30B0", - options: { - important: "\u91CD\u8981", - quick_win: "\u30AF\u30A4\u30C3\u30AF\u30A6\u30A3\u30F3", - blocked: "\u30D6\u30ED\u30C3\u30AF\u4E2D", - follow_up: "\u30D5\u30A9\u30ED\u30FC\u30A2\u30C3\u30D7", - review: "\u30EC\u30D3\u30E5\u30FC" - } - }, - is_recurring: { label: "\u7E70\u308A\u8FD4\u3057\u30BF\u30B9\u30AF" }, - recurrence_type: { - label: "\u7E70\u308A\u8FD4\u3057\u30BF\u30A4\u30D7", - options: { - daily: "\u6BCE\u65E5", - weekly: "\u6BCE\u9031", - monthly: "\u6BCE\u6708", - yearly: "\u6BCE\u5E74" - } - }, - recurrence_interval: { label: "\u7E70\u308A\u8FD4\u3057\u9593\u9694" }, - is_completed: { label: "\u5B8C\u4E86\u6E08\u307F" }, - is_overdue: { label: "\u671F\u9650\u8D85\u904E" }, - progress_percent: { label: "\u9032\u6357\u7387 (%)" }, - estimated_hours: { label: "\u898B\u7A4D\u6642\u9593" }, - actual_hours: { label: "\u5B9F\u7E3E\u6642\u9593" }, - notes: { label: "\u30E1\u30E2" }, - category_color: { label: "\u30AB\u30C6\u30B4\u30EA\u8272" } - } - } - }, - apps: { - todo_app: { - label: "ToDo \u30DE\u30CD\u30FC\u30B8\u30E3\u30FC", - description: "\u500B\u4EBA\u30BF\u30B9\u30AF\u7BA1\u7406\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3" - } - }, - messages: { - "common.save": "\u4FDD\u5B58", - "common.cancel": "\u30AD\u30E3\u30F3\u30BB\u30EB", - "common.delete": "\u524A\u9664", - "common.edit": "\u7DE8\u96C6", - "common.create": "\u65B0\u898F\u4F5C\u6210", - "common.search": "\u691C\u7D22", - "common.filter": "\u30D5\u30A3\u30EB\u30BF\u30FC", - "common.sort": "\u4E26\u3079\u66FF\u3048", - "common.refresh": "\u66F4\u65B0", - "common.export": "\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8", - "common.back": "\u623B\u308B", - "common.confirm": "\u78BA\u8A8D", - "success.saved": "\u4FDD\u5B58\u3057\u307E\u3057\u305F", - "success.deleted": "\u524A\u9664\u3057\u307E\u3057\u305F", - "success.completed": "\u30BF\u30B9\u30AF\u3092\u5B8C\u4E86\u306B\u3057\u307E\u3057\u305F", - "confirm.delete": "\u3053\u306E\u30BF\u30B9\u30AF\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F", - "confirm.complete": "\u3053\u306E\u30BF\u30B9\u30AF\u3092\u5B8C\u4E86\u306B\u3057\u307E\u3059\u304B\uFF1F", - "error.required": "\u3053\u306E\u9805\u76EE\u306F\u5FC5\u9808\u3067\u3059", - "error.load_failed": "\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F" - }, - validationMessages: { - completed_date_required: "\u30B9\u30C6\u30FC\u30BF\u30B9\u304C\u300C\u5B8C\u4E86\u300D\u306E\u5834\u5408\u3001\u5B8C\u4E86\u65E5\u306F\u5FC5\u9808\u3067\u3059", - recurrence_fields_required: "\u7E70\u308A\u8FD4\u3057\u30BF\u30B9\u30AF\u306B\u306F\u7E70\u308A\u8FD4\u3057\u30BF\u30A4\u30D7\u304C\u5FC5\u8981\u3067\u3059" - } -}; - -// ../app-todo/src/translations/todo.translation.ts -var TodoTranslations = { - en: en2, - "zh-CN": zhCN2, - "ja-JP": jaJP2 -}; - -// ../app-todo/objectstack.config.ts -var objectstack_config_default2 = defineStack({ - manifest: { - id: "com.example.todo", - namespace: "todo", - version: "2.0.0", - type: "app", - name: "Todo Manager", - description: "A comprehensive Todo app demonstrating ObjectStack Protocol features including automation, dashboards, and reports" - }, - // Seed Data (top-level, registered as metadata) - data: [ - { - object: "task", - mode: "upsert", - externalId: "subject", - records: [ - { subject: "Learn ObjectStack", status: "completed", priority: "high", category: "work" }, - { subject: "Build a cool app", status: "in_progress", priority: "normal", category: "work", due_date: new Date(Date.now() + 864e5 * 3) }, - { subject: "Review PR #102", status: "completed", priority: "high", category: "work" }, - { subject: "Write Documentation", status: "not_started", priority: "normal", category: "work", due_date: new Date(Date.now() + 864e5) }, - { subject: "Fix Server bug", status: "waiting", priority: "urgent", category: "work" }, - { subject: "Buy groceries", status: "not_started", priority: "low", category: "shopping", due_date: /* @__PURE__ */ new Date() }, - { subject: "Schedule dentist appointment", status: "not_started", priority: "normal", category: "health", due_date: new Date(Date.now() + 864e5 * 7) }, - { subject: "Pay utility bills", status: "not_started", priority: "high", category: "finance", due_date: new Date(Date.now() + 864e5 * 2) } - ] - } - ], - // Auto-collected from barrel index files via Object.values() - objects: Object.values(objects_exports2), - actions: Object.values(actions_exports2), - dashboards: Object.values(dashboards_exports2), - reports: Object.values(reports_exports2), - flows: allFlows2, - apps: Object.values(apps_exports2), - // I18n Configuration — per-locale file organization - i18n: { - defaultLocale: "en", - supportedLocales: ["en", "zh-CN", "ja-JP"], - fallbackLocale: "en", - fileOrganization: "per_locale" - }, - // I18n Translation Bundles (en, zh-CN, ja-JP) - translations: Object.values(translations_exports2) -}); - -// ../plugin-bi/objectstack.config.ts -var objectstack_config_default3 = defineStack({ - manifest: { - id: "com.example.bi", - namespace: "bi", - version: "1.0.0", - type: "plugin", - name: "BI Plugin", - description: "Business Intelligence dashboards and analytics" - }, - // Placeholder - no objects or dashboards yet - objects: [], - dashboards: [] -}); - -// server/index.ts -var _kernel = null; -var _app = null; -var _bootPromise = null; -async function ensureKernel() { - if (_kernel) return _kernel; - if (_bootPromise) return _bootPromise; - _bootPromise = (async () => { - console.log("[Vercel] Booting ObjectStack Kernel (app-host)..."); - try { - const kernel = new ObjectKernel(); - await kernel.use(new ObjectQLPlugin()); - await kernel.use(new DriverPlugin(new InMemoryDriver())); - const vercelUrl = process.env.VERCEL_PROJECT_PRODUCTION_URL ? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` : process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : "http://localhost:3000"; - await kernel.use(new AuthPlugin({ - secret: process.env.AUTH_SECRET || "dev-secret-please-change-in-production-min-32-chars", - baseUrl: vercelUrl - })); - await kernel.use(new AppPlugin(objectstack_config_default)); - await kernel.use(new AppPlugin(objectstack_config_default2)); - await kernel.use(new AppPlugin(objectstack_config_default3)); - await kernel.bootstrap(); - _kernel = kernel; - console.log("[Vercel] Kernel ready."); - return kernel; - } catch (err) { - _bootPromise = null; - console.error("[Vercel] Kernel boot failed:", err?.message || err); - throw err; - } - })(); - return _bootPromise; -} -async function ensureApp() { - if (_app) return _app; - const kernel = await ensureKernel(); - _app = createHonoApp({ kernel, prefix: "/api/v1" }); - return _app; -} -function extractBody(incoming, method, contentType) { - if (method === "GET" || method === "HEAD" || method === "OPTIONS") return null; - if (incoming.rawBody != null) { - return incoming.rawBody; - } - if (incoming.body != null) { - if (typeof incoming.body === "string") return incoming.body; - if (contentType?.includes("application/json")) return JSON.stringify(incoming.body); - return String(incoming.body); - } - return null; -} -function resolvePublicUrl(requestUrl, incoming) { - if (!incoming) return requestUrl; - const fwdProto = incoming.headers?.["x-forwarded-proto"]; - const rawProto = Array.isArray(fwdProto) ? fwdProto[0] : fwdProto; - const proto = rawProto === "https" || rawProto === "http" ? rawProto : void 0; - if (proto === "https" && requestUrl.startsWith("http:")) { - return requestUrl.replace(/^http:/, "https:"); - } - return requestUrl; -} -var index_default = getRequestListener(async (request, env2) => { - let app; - try { - app = await ensureApp(); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - console.error("[Vercel] Handler error \u2014 bootstrap did not complete:", message2); - return new Response( - JSON.stringify({ - success: false, - error: { - message: "Service Unavailable \u2014 kernel bootstrap failed.", - code: 503 - } - }), - { status: 503, headers: { "content-type": "application/json" } } - ); - } - const method = request.method.toUpperCase(); - const incoming = env2?.incoming; - const url2 = resolvePublicUrl(request.url, incoming); - console.log(`[Vercel] ${method} ${url2}`); - if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && incoming) { - const contentType = incoming.headers?.["content-type"]; - const contentTypeStr = Array.isArray(contentType) ? contentType[0] : contentType; - const body = extractBody(incoming, method, contentTypeStr); - if (body != null) { - return await app.fetch( - new Request(url2, { method, headers: request.headers, body }) - ); - } - } - return await app.fetch( - new Request(url2, { method, headers: request.headers }) - ); -}); -var config3 = { - memory: 1024, - maxDuration: 60 -}; -export { - config3 as config, - index_default as default -}; -/*! Bundled license information: - -@noble/ciphers/utils.js: - (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *) -*/ -//# sourceMappingURL=_handler.js.map diff --git a/examples/app-host/api/_handler.js.map b/examples/app-host/api/_handler.js.map deleted file mode 100644 index 7e3a3855a..000000000 --- a/examples/app-host/api/_handler.js.map +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 3, - "sources": ["../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js", "../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js", "../../../packages/spec/src/data/filter.zod.ts", "../../../packages/spec/src/data/query.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/data/validation.zod.ts", "../../../packages/spec/src/automation/state-machine.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/data/object.zod.ts", "../../../packages/spec/src/data/hook.zod.ts", "../../../packages/spec/src/data/mapping.zod.ts", "../../../packages/spec/src/kernel/execution-context.zod.ts", "../../../packages/spec/src/data/data-engine.zod.ts", "../../../packages/spec/src/shared/enums.zod.ts", "../../../packages/spec/src/data/driver.zod.ts", "../../../packages/spec/src/data/driver-sql.zod.ts", "../../../packages/spec/src/data/driver-nosql.zod.ts", "../../../packages/spec/src/data/dataset.zod.ts", "../../../packages/spec/src/data/seed-loader.zod.ts", "../../../packages/spec/src/data/document.zod.ts", "../../../packages/spec/src/shared/mapping.zod.ts", "../../../packages/spec/src/data/external-lookup.zod.ts", "../../../packages/spec/src/data/datasource.zod.ts", "../../../packages/spec/src/data/analytics.zod.ts", "../../../packages/spec/src/data/feed.zod.ts", "../../../packages/spec/src/data/subscription.zod.ts", "../../../packages/spec/src/data/driver/turso-multi-tenant.zod.ts", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_hash.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/util/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/lazy.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/aggregator.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/push.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/accumulator.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/addToSet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/avg.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sort.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottomN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/bottom.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/count.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covariancePop.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/covarianceSamp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/first.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/firstN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/last.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/lastN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/max.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/maxN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/percentile.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/median.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/mergeObjects.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/min.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/minN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevPop.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/stdDevSamp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/sum.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/topN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/top.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/accumulator/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/abs.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/add.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ceil.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/divide.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/exp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/floor.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/ln.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/log10.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/mod.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/multiply.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/pow.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/round.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sigmoid.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/sqrt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/subtract.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/trunc.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/arithmetic/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayElemAt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/arrayToObject.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/concatArrays.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/filter.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/first.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/firstN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/in.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/indexOfArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/isArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/last.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/lastN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/map.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/maxN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/minN.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/range.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reduce.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/reverseArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/size.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/slice.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/sortArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/zip.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/array/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitAnd.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitNot.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitOr.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/bitXor.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/bitwise/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/and.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/not.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/or.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/boolean/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/cmp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/limit.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/documents.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/project.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/skip.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/cursor.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/query.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/_predicates.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/eq.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/gte.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/lte.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/ne.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/comparison/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/cond.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/ifNull.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/switch.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/conditional/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/function.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/custom/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateAdd.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateDiff.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromParts.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateFromString.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateSubtract.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToParts.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateToString.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dateTrunc.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfMonth.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfWeek.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/dayOfYear.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/hour.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoDayOfWeek.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeek.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/isoWeekYear.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/millisecond.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/minute.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/month.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/second.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/week.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/year.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/date/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/literal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/median.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/getField.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/rand.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/sampleRate.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/misc/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/mergeObjects.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/objectToArray.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/setField.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/unsetField.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/object/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/percentile.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/allElementsTrue.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/anyElementTrue.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setDifference.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setEquals.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIntersection.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setIsSubset.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/setUnion.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/set/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/concat.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/indexOfBytes.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/ltrim.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFind.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexFindAll.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/regexMatch.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceAll.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/replaceOne.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/rtrim.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/split.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strcasecmp.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenBytes.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/strLenCP.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrBytes.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substr.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/substrCP.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toBool.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDate.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDouble.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toInt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toLong.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toString.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/convert.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/isNumber.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/toDecimal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/type.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/type/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toLower.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/toUpper.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/trim.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/string/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/toHashedIndexKey.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acos.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/acosh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asin.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/asinh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atan2.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/atanh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cos.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/cosh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/degreesToRadians.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/radiansToDegrees.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sin.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/sinh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tan.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/tanh.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/trignometry/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/let.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/variable/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/expression/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/addFields.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucket.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/bucketAuto.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/count.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/densify.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/facet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/linearFill.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/locf.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/group.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/setWindowFields.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/fill.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/lookup.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/graphLookup.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/match.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/merge.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/out.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/redact.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceRoot.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/replaceWith.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sample.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/set.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/sortByCount.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unionWith.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unset.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/unwind.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/pipeline/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/elemMatch.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/slice.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/projection/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/all.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/elemMatch.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/size.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/array/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllClear.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAllSet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnyClear.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/bitsAnySet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/bitwise/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/eq.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/gte.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/in.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lt.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/lte.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/ne.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/nin.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/comparison/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/exists.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/type.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/element/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/expr.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/jsonSchema.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/mod.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/regex.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/where.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/evaluation/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/and.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/or.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/nor.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/not.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/logical/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/query/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/denseRank.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/derivative.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/documentNumber.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/expMovingAvg.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/integral.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/minMaxScaler.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/rank.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/shift.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/window/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/_internal.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/addToSet.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/bit.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/currentDate.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/inc.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/max.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/min.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/mul.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pop.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pull.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/pullAll.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/push.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/set.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/rename.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/unset.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/operators/update/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/updater.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/core/index.js", "../../../node_modules/.pnpm/mingo@7.2.1/node_modules/mingo/cjs/index.js", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/env-impl.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/color-depth.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/logger.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/env/index.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/error-codes.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/codes.mjs", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/error.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/error/index.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/random.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/get-tables.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/json.mjs", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/trace/SemanticAttributes.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/trace/index.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/resource/SemanticResourceAttributes.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/resource/index.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/stable_attributes.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/stable_metrics.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/stable_events.ts", "../../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.40.0/node_modules/@opentelemetry/semantic-conventions/src/index.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/attributes.mjs", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/platform/node/globalThis.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/platform/node/index.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/platform/index.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/version.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/internal/semver.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/internal/global-utils.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/diag/types.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/api/diag.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/context/context.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/context/NoopContextManager.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/api/context.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/trace_flags.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/invalid-span-constants.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/NonRecordingSpan.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/context-utils.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/spancontext-utils.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/NoopTracer.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/ProxyTracer.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/NoopTracerProvider.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/ProxyTracerProvider.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace/status.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/api/trace.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/trace-api.ts", "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/src/index.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/tracer.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/id.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/utils.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/factory.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/adapter/index.mjs", "../../../node_modules/.pnpm/@better-auth+memory-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_9b6e7edc5b5cf527f9fdae30e619266b/node_modules/@better-auth/memory-adapter/dist/index.mjs", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js", "../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/string.mjs", "../../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/bun-sqlite-dialect-na--YwnN.mjs", "../../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/node-sqlite-dialect.mjs", "../../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/d1-sqlite-dialect-C2B7YsIT.mjs", "../../../node_modules/.pnpm/@better-auth+kysely-adapter@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@bet_ca3907a8728a7d3a657b0e649fbcc90b/node_modules/@better-auth/kysely-adapter/dist/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs", "../../../packages/spec/src/system/cache.zod.ts", "../../../packages/spec/src/system/disaster-recovery.zod.ts", "../../../packages/spec/src/system/message-queue.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/system/object-storage.zod.ts", "../../../packages/spec/src/system/search-engine.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/system/http-server.zod.ts", "../../../packages/spec/src/system/audit.zod.ts", "../../../packages/spec/src/system/logging.zod.ts", "../../../packages/spec/src/system/metrics.zod.ts", "../../../packages/spec/src/system/tracing.zod.ts", "../../../packages/spec/src/system/security-context.zod.ts", "../../../packages/spec/src/system/change-management.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/data/validation.zod.ts", "../../../packages/spec/src/automation/state-machine.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/data/object.zod.ts", "../../../packages/spec/src/system/migration.zod.ts", "../../../packages/spec/src/system/auth-config.zod.ts", "../../../packages/spec/src/system/compliance.zod.ts", "../../../packages/spec/src/system/incident-response.zod.ts", "../../../packages/spec/src/system/supplier-security.zod.ts", "../../../packages/spec/src/system/training.zod.ts", "../../../packages/spec/src/system/job.zod.ts", "../../../packages/spec/src/system/worker.zod.ts", "../../../packages/spec/src/system/notification.zod.ts", "../../../packages/spec/src/system/translation.zod.ts", "../../../packages/spec/src/system/translation-skeleton.ts", "../../../packages/spec/src/system/collaboration.zod.ts", "../../../packages/spec/src/system/metadata-persistence.zod.ts", "../../../packages/spec/src/system/core-services.zod.ts", "../../../packages/spec/src/system/tenant.zod.ts", "../../../packages/spec/src/system/license.zod.ts", "../../../packages/spec/src/system/registry-config.zod.ts", "../../../packages/spec/src/system/provisioning.zod.ts", "../../../packages/spec/src/system/deploy-bundle.zod.ts", "../../../packages/spec/src/system/app-install.zod.ts", "../../../packages/spec/src/system/constants/paths.ts", "../../../packages/spec/src/system/constants/system-names.ts", "../../../packages/core/src/kernel-base.ts", "../../../packages/core/src/utils/env.ts", "../../../packages/core/src/logger.ts", "../../../packages/core/src/kernel.ts", "../../../packages/core/src/security/plugin-config-validator.ts", "../../../packages/core/src/plugin-loader.ts", "../../../packages/core/src/fallbacks/memory-cache.ts", "../../../packages/core/src/fallbacks/memory-queue.ts", "../../../packages/core/src/fallbacks/memory-job.ts", "../../../packages/core/src/fallbacks/memory-i18n.ts", "../../../packages/core/src/fallbacks/memory-metadata.ts", "../../../packages/core/src/fallbacks/index.ts", "../../../packages/core/src/lite-kernel.ts", "../../../packages/core/src/api-registry.ts", "../../../packages/core/src/api-registry-plugin.ts", "../../../packages/core/src/qa/index.ts", "../../../packages/core/src/qa/runner.ts", "../../../packages/core/src/qa/http-adapter.ts", "../../../packages/core/src/security/plugin-signature-verifier.ts", "../../../packages/core/src/security/plugin-permission-enforcer.ts", "../../../packages/core/src/security/permission-manager.ts", "../../../packages/core/src/security/sandbox-runtime.ts", "../../../packages/core/src/security/security-scanner.ts", "../../../packages/core/src/health-monitor.ts", "../../../packages/core/src/hot-reload.ts", "../../../packages/core/src/dependency-resolver.ts", "../../../packages/core/src/namespace-resolver.ts", "../../../packages/core/src/package-manager.ts", "../../../packages/spec/src/data/filter.zod.ts", "../../../packages/spec/src/data/query.zod.ts", "../../../packages/spec/src/api/contract.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/api/endpoint.zod.ts", "../../../packages/spec/src/api/discovery.zod.ts", "../../../packages/spec/src/api/events.zod.ts", "../../../packages/spec/src/api/realtime-shared.zod.ts", "../../../packages/spec/src/api/realtime.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/api/websocket.zod.ts", "../../../packages/spec/src/api/router.zod.ts", "../../../packages/spec/src/api/odata.zod.ts", "../../../packages/spec/src/api/graphql.zod.ts", "../../../packages/spec/src/api/batch.zod.ts", "../../../packages/spec/src/api/http-cache.zod.ts", "../../../packages/spec/src/api/errors.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/sharing.zod.ts", "../../../packages/spec/src/ui/responsive.zod.ts", "../../../packages/spec/src/ui/view.zod.ts", "../../../packages/spec/src/security/rls.zod.ts", "../../../packages/spec/src/security/permission.zod.ts", "../../../packages/spec/src/automation/workflow.zod.ts", "../../../packages/spec/src/system/translation.zod.ts", "../../../packages/spec/src/kernel/plugin-capability.zod.ts", "../../../packages/spec/src/kernel/plugin-loading.zod.ts", "../../../packages/spec/src/kernel/plugin.zod.ts", "../../../packages/spec/src/data/dataset.zod.ts", "../../../packages/spec/src/kernel/manifest.zod.ts", "../../../packages/spec/src/kernel/dependency-resolution.zod.ts", "../../../packages/spec/src/kernel/package-registry.zod.ts", "../../../packages/spec/src/api/protocol.zod.ts", "../../../packages/spec/src/api/rest-server.zod.ts", "../../../packages/spec/src/api/registry.zod.ts", "../../../packages/spec/src/api/documentation.zod.ts", "../../../packages/spec/src/data/analytics.zod.ts", "../../../packages/spec/src/api/analytics.zod.ts", "../../../packages/spec/src/api/versioning.zod.ts", "../../../packages/spec/src/api/auth.zod.ts", "../../../packages/spec/src/api/auth-endpoints.zod.ts", "../../../packages/spec/src/system/object-storage.zod.ts", "../../../packages/spec/src/api/storage.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/data/validation.zod.ts", "../../../packages/spec/src/automation/state-machine.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/data/object.zod.ts", "../../../packages/spec/src/ui/app.zod.ts", "../../../packages/spec/src/kernel/metadata-loader.zod.ts", "../../../packages/spec/src/kernel/metadata-customization.zod.ts", "../../../packages/spec/src/kernel/metadata-plugin.zod.ts", "../../../packages/spec/src/api/metadata.zod.ts", "../../../packages/spec/src/system/core-services.zod.ts", "../../../packages/spec/src/api/dispatcher.zod.ts", "../../../packages/spec/src/system/http-server.zod.ts", "../../../packages/spec/src/api/plugin-rest-api.zod.ts", "../../../packages/spec/src/api/query-adapter.zod.ts", "../../../packages/spec/src/data/feed.zod.ts", "../../../packages/spec/src/data/subscription.zod.ts", "../../../packages/spec/src/api/feed-api.zod.ts", "../../../packages/spec/src/api/export.zod.ts", "../../../packages/spec/src/automation/flow.zod.ts", "../../../packages/spec/src/automation/execution.zod.ts", "../../../packages/spec/src/api/automation-api.zod.ts", "../../../packages/spec/src/kernel/package-upgrade.zod.ts", "../../../packages/spec/src/kernel/package-artifact.zod.ts", "../../../packages/spec/src/cloud/marketplace.zod.ts", "../../../packages/spec/src/api/package-api.zod.ts", "../../../packages/runtime/src/index.ts", "../../../packages/runtime/src/runtime.ts", "../../../packages/runtime/src/driver-plugin.ts", "../../../packages/runtime/src/seed-loader.ts", "../../../packages/runtime/src/app-plugin.ts", "../../../packages/runtime/src/http-dispatcher.ts", "../../../packages/runtime/src/dispatcher-plugin.ts", "../../../packages/runtime/src/http-server.ts", "../../../packages/runtime/src/middleware.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/shared/mapping.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/shared/enums.zod.ts", "../../../packages/spec/src/shared/metadata-types.zod.ts", "../../../packages/spec/src/shared/branded-types.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/shared/suggestions.zod.ts", "../../../packages/spec/src/shared/error-map.zod.ts", "../../../packages/spec/src/shared/metadata-collection.zod.ts", "../../../packages/objectql/src/registry.ts", "../../../packages/objectql/src/protocol.ts", "../../../packages/objectql/src/engine.ts", "../../../packages/objectql/src/metadata-facade.ts", "../../../packages/objectql/src/plugin.ts", "../../../packages/objectql/src/kernel-factory.ts", "../../../packages/objectql/src/util.ts", "../../../packages/spec/src/kernel/cli-extension.zod.ts", "../../../packages/spec/src/kernel/package-artifact.zod.ts", "../../../packages/spec/src/kernel/cli-plugin-commands.zod.ts", "../../../packages/spec/src/system/tenant.zod.ts", "../../../packages/spec/src/kernel/context.zod.ts", "../../../packages/spec/src/kernel/dependency-resolution.zod.ts", "../../../packages/spec/src/kernel/dev-plugin.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/kernel/events/core.zod.ts", "../../../packages/spec/src/kernel/events/handlers.zod.ts", "../../../packages/spec/src/kernel/events/queue.zod.ts", "../../../packages/spec/src/kernel/events/dlq.zod.ts", "../../../packages/spec/src/kernel/events/integrations.zod.ts", "../../../packages/spec/src/kernel/events/bus.zod.ts", "../../../packages/spec/src/kernel/feature.zod.ts", "../../../packages/spec/src/kernel/plugin-capability.zod.ts", "../../../packages/spec/src/kernel/plugin-loading.zod.ts", "../../../packages/spec/src/kernel/plugin.zod.ts", "../../../packages/spec/src/data/dataset.zod.ts", "../../../packages/spec/src/kernel/manifest.zod.ts", "../../../packages/spec/src/kernel/metadata-customization.zod.ts", "../../../packages/spec/src/kernel/metadata-loader.zod.ts", "../../../packages/spec/src/kernel/metadata-plugin.zod.ts", "../../../packages/spec/src/kernel/package-registry.zod.ts", "../../../packages/spec/src/kernel/package-upgrade.zod.ts", "../../../packages/spec/src/kernel/plugin-lifecycle-advanced.zod.ts", "../../../packages/spec/src/kernel/plugin-lifecycle-events.zod.ts", "../../../packages/spec/src/kernel/plugin-runtime.zod.ts", "../../../packages/spec/src/kernel/plugin-security-advanced.zod.ts", "../../../packages/spec/src/kernel/plugin-structure.zod.ts", "../../../packages/spec/src/kernel/plugin-validator.zod.ts", "../../../packages/spec/src/kernel/plugin-versioning.zod.ts", "../../../packages/spec/src/kernel/service-registry.zod.ts", "../../../packages/spec/src/kernel/startup-orchestrator.zod.ts", "../../../packages/spec/src/kernel/plugin-registry.zod.ts", "../../../packages/spec/src/kernel/plugin-security.zod.ts", "../../../packages/spec/src/kernel/execution-context.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/chart.zod.ts", "../../../packages/spec/src/ui/responsive.zod.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/ui/sharing.zod.ts", "../../../packages/spec/src/ui/app.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/ui/view.zod.ts", "../../../packages/spec/src/data/filter.zod.ts", "../../../packages/spec/src/ui/dashboard.zod.ts", "../../../packages/spec/src/ui/report.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/shared/enums.zod.ts", "../../../packages/spec/src/ui/page.zod.ts", "../../../packages/spec/src/ui/widget.zod.ts", "../../../packages/spec/src/data/feed.zod.ts", "../../../packages/spec/src/ui/component.zod.ts", "../../../packages/spec/src/ui/touch.zod.ts", "../../../packages/spec/src/ui/keyboard.zod.ts", "../../../packages/spec/src/ui/theme.zod.ts", "../../../packages/spec/src/ui/offline.zod.ts", "../../../packages/spec/src/ui/animation.zod.ts", "../../../packages/spec/src/ui/notification.zod.ts", "../../../packages/spec/src/ui/dnd.zod.ts", "../../../packages/plugins/driver-memory/src/persistence/local-storage-adapter.ts", "../../../packages/plugins/driver-memory/src/persistence/file-adapter.ts", "../../../packages/plugins/driver-memory/src/memory-driver.ts", "../../../packages/plugins/driver-memory/src/memory-matcher.ts", "../../../packages/plugins/driver-memory/src/index.ts", "../../../packages/plugins/driver-memory/src/memory-analytics.ts", "../../../packages/plugins/driver-memory/src/in-memory-strategy.ts", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/compose.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/request/constants.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/body.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/url.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/request.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/html.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/context.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/utils/constants.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/hono-base.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/matcher.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/node.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/trie.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/reg-exp-router/router.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/smart-router/router.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/trie-router/node.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/router/trie-router/router.js", "../../../node_modules/.pnpm/hono@4.12.12/node_modules/hono/dist/hono.js", "../../../packages/adapters/hono/src/index.ts", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/wildcard.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/url.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/random.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/buffer.mjs", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/hkdf.ts", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_md.ts", "../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/sha2.ts", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js", "../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/jwt.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/password.node.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/password.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/base64.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/index.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hash.mjs", "../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/utils.ts", "../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/_arx.ts", "../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/_poly1305.ts", "../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/chacha.ts", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/crypto/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/date.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/db/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/schema.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/db.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-promise.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/session-store.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/time.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/cookie-utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/cookies/index.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/binary.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hex.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/hmac.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/state.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/global.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/async_hooks/index.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/endpoint-context.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/request-state.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/context/transaction.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/state/oauth.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/state.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/hide-metadata.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/is-api-error.mjs", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/dist/index.mjs", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/utils.ts", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/crypto.ts", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/cookies.ts", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/validator.ts", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/openapi.ts", "../../../node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs", "../../../node_modules/.pnpm/better-call@1.3.5_zod@4.3.6/node_modules/better-call/src/router.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/api/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/trusted-origins.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/middlewares/origin-check.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/url.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/deprecate.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/get-request-ip.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/utils/ip.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/rate-limiter/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/state/should-session-refresh.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/session.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/verification-token-storage.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/instrumentation/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/with-hooks.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/internal-adapter.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/helpers.mjs", "../../../node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/account.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/apple.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/utils.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/create-authorization-url.mjs", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/error.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/plugins.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/retry.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/auth.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/utils.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/create-fetch/schema.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/create-fetch/index.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/url.ts", "../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/src/fetch.ts", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/refresh-access-token.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/oauth2/validate-authorization-code.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/atlassian.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/cognito.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/discord.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/dropbox.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/facebook.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/figma.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/github.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/gitlab.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/google.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/huggingface.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/kakao.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/kick.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/line.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/linear.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/linkedin.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/microsoft-entra-id.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/naver.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/notion.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/paybin.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/paypal.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/polar.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/railway.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/reddit.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/roblox.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/salesforce.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/slack.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/spotify.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/tiktok.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/twitch.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/twitter.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/vercel.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/vk.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/wechat.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/zoom.mjs", "../../../node_modules/.pnpm/@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_@openteleme_944bf6a573125ebe4f0d728a0e6637f8/node_modules/@better-auth/core/dist/social-providers/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/email-verification.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/oauth2/link-account.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/callback.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/error.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/ok.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/password.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/password.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-in.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-out.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/sign-up.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/update-session.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/routes/update-user.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/to-auth-endpoints.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/api/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/adapter-base.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/adapter-kysely.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/get-schema.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/get-migration.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/constants.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/secret-utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/create-context.mjs", "../../../node_modules/.pnpm/@better-auth+telemetry@1.6.2_@better-auth+core@1.6.2_@better-auth+utils@0.4.0_@better-f_04cb191a006c1c341def4e42b17bd9b5/node_modules/@better-auth/telemetry/dist/node.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/context/init.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/base.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/auth/full.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/client/parser.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/adapter.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/access/access.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/access/statement.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/permission.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/has-permission.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/package.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/version.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/error-codes.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/utils/shim.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/call.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/db/to-zod.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-access-control.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-invites.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-members.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-org.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/schema.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/routes/crud-team.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/organization/organization.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/error-code.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/constant.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/verify-two-factor.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/backup-codes/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/otp/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/schema.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/totp/index.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/base32.mjs", "../../../node_modules/.pnpm/@better-auth+utils@0.4.0/node_modules/@better-auth/utils/dist/otp.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/two-factor/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/magic-link/utils.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/plugins/magic-link/index.mjs", "../../../node_modules/.pnpm/better-auth@1.6.2_aa7ee3c8debfc7e26fcd97a3260e820f/node_modules/better-auth/dist/adapters/index.mjs", "../../../packages/plugins/plugin-auth/src/auth-manager.ts", "../../../packages/plugins/plugin-auth/src/objectql-adapter.ts", "../../../packages/plugins/plugin-auth/src/auth-schema-config.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-user.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-session.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-account.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-verification.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-organization.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-member.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-invitation.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-team.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-team-member.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-api-key.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-two-factor.object.ts", "../../../packages/plugins/plugin-auth/src/objects/sys-user-preference.object.ts", "../../../packages/plugins/plugin-auth/src/auth-plugin.ts", "../../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.12/node_modules/@hono/node-server/dist/index.mjs", "../../../packages/spec/src/shared/index.ts", "../../../packages/spec/src/shared/identifiers.zod.ts", "../../../packages/spec/src/shared/mapping.zod.ts", "../../../packages/spec/src/shared/http.zod.ts", "../../../packages/spec/src/shared/enums.zod.ts", "../../../packages/spec/src/shared/metadata-types.zod.ts", "../../../packages/spec/src/shared/branded-types.zod.ts", "../../../packages/spec/src/system/encryption.zod.ts", "../../../packages/spec/src/system/masking.zod.ts", "../../../packages/spec/src/data/field.zod.ts", "../../../packages/spec/src/shared/suggestions.zod.ts", "../../../packages/spec/src/shared/error-map.zod.ts", "../../../packages/spec/src/shared/metadata-collection.zod.ts", "../../../packages/spec/src/data/index.ts", "../../../packages/spec/src/data/filter.zod.ts", "../../../packages/spec/src/data/query.zod.ts", "../../../packages/spec/src/data/validation.zod.ts", "../../../packages/spec/src/automation/state-machine.zod.ts", "../../../packages/spec/src/ui/i18n.zod.ts", "../../../packages/spec/src/ui/action.zod.ts", "../../../packages/spec/src/data/object.zod.ts", "../../../packages/spec/src/data/hook.zod.ts", "../../../packages/spec/src/data/mapping.zod.ts", "../../../packages/spec/src/kernel/execution-context.zod.ts", "../../../packages/spec/src/data/data-engine.zod.ts", "../../../packages/spec/src/data/driver.zod.ts", "../../../packages/spec/src/data/driver-sql.zod.ts", "../../../packages/spec/src/data/driver-nosql.zod.ts", "../../../packages/spec/src/data/dataset.zod.ts", "../../../packages/spec/src/data/seed-loader.zod.ts", "../../../packages/spec/src/data/document.zod.ts", "../../../packages/spec/src/data/external-lookup.zod.ts", "../../../packages/spec/src/data/datasource.zod.ts", "../../../packages/spec/src/data/analytics.zod.ts", "../../../packages/spec/src/data/feed.zod.ts", "../../../packages/spec/src/data/subscription.zod.ts", "../../../packages/spec/src/data/driver/turso-multi-tenant.zod.ts", "../../../packages/spec/src/security/index.ts", "../../../packages/spec/src/security/rls.zod.ts", "../../../packages/spec/src/security/permission.zod.ts", "../../../packages/spec/src/security/sharing.zod.ts", "../../../packages/spec/src/security/territory.zod.ts", "../../../packages/spec/src/security/policy.zod.ts", "../../../packages/spec/src/ui/index.ts", "../../../packages/spec/src/ui/chart.zod.ts", "../../../packages/spec/src/ui/responsive.zod.ts", "../../../packages/spec/src/ui/sharing.zod.ts", "../../../packages/spec/src/ui/app.zod.ts", "../../../packages/spec/src/ui/view.zod.ts", "../../../packages/spec/src/ui/dashboard.zod.ts", "../../../packages/spec/src/ui/report.zod.ts", "../../../packages/spec/src/ui/page.zod.ts", "../../../packages/spec/src/ui/widget.zod.ts", "../../../packages/spec/src/ui/component.zod.ts", "../../../packages/spec/src/ui/touch.zod.ts", "../../../packages/spec/src/ui/keyboard.zod.ts", "../../../packages/spec/src/ui/theme.zod.ts", "../../../packages/spec/src/ui/offline.zod.ts", "../../../packages/spec/src/ui/animation.zod.ts", "../../../packages/spec/src/ui/notification.zod.ts", "../../../packages/spec/src/ui/dnd.zod.ts", "../../../packages/spec/src/system/index.ts", "../../../packages/spec/src/system/cache.zod.ts", "../../../packages/spec/src/system/disaster-recovery.zod.ts", "../../../packages/spec/src/system/message-queue.zod.ts", "../../../packages/spec/src/system/object-storage.zod.ts", "../../../packages/spec/src/system/search-engine.zod.ts", "../../../packages/spec/src/system/http-server.zod.ts", "../../../packages/spec/src/system/audit.zod.ts", "../../../packages/spec/src/system/logging.zod.ts", "../../../packages/spec/src/system/metrics.zod.ts", "../../../packages/spec/src/system/tracing.zod.ts", "../../../packages/spec/src/system/security-context.zod.ts", "../../../packages/spec/src/system/change-management.zod.ts", "../../../packages/spec/src/system/migration.zod.ts", "../../../packages/spec/src/system/auth-config.zod.ts", "../../../packages/spec/src/system/compliance.zod.ts", "../../../packages/spec/src/system/incident-response.zod.ts", "../../../packages/spec/src/system/supplier-security.zod.ts", "../../../packages/spec/src/system/training.zod.ts", "../../../packages/spec/src/system/job.zod.ts", "../../../packages/spec/src/system/worker.zod.ts", "../../../packages/spec/src/system/notification.zod.ts", "../../../packages/spec/src/system/translation.zod.ts", "../../../packages/spec/src/system/translation-skeleton.ts", "../../../packages/spec/src/system/collaboration.zod.ts", "../../../packages/spec/src/system/metadata-persistence.zod.ts", "../../../packages/spec/src/system/core-services.zod.ts", "../../../packages/spec/src/system/tenant.zod.ts", "../../../packages/spec/src/system/license.zod.ts", "../../../packages/spec/src/system/registry-config.zod.ts", "../../../packages/spec/src/system/provisioning.zod.ts", "../../../packages/spec/src/system/deploy-bundle.zod.ts", "../../../packages/spec/src/system/app-install.zod.ts", "../../../packages/spec/src/system/constants/paths.ts", "../../../packages/spec/src/system/constants/system-names.ts", "../../../packages/spec/src/kernel/index.ts", "../../../packages/spec/src/kernel/cli-extension.zod.ts", "../../../packages/spec/src/kernel/package-artifact.zod.ts", "../../../packages/spec/src/kernel/cli-plugin-commands.zod.ts", "../../../packages/spec/src/kernel/context.zod.ts", "../../../packages/spec/src/kernel/dependency-resolution.zod.ts", "../../../packages/spec/src/kernel/dev-plugin.zod.ts", "../../../packages/spec/src/kernel/events/core.zod.ts", "../../../packages/spec/src/kernel/events/handlers.zod.ts", "../../../packages/spec/src/kernel/events/queue.zod.ts", "../../../packages/spec/src/kernel/events/dlq.zod.ts", "../../../packages/spec/src/kernel/events/integrations.zod.ts", "../../../packages/spec/src/kernel/events/bus.zod.ts", "../../../packages/spec/src/kernel/feature.zod.ts", "../../../packages/spec/src/kernel/plugin-capability.zod.ts", "../../../packages/spec/src/kernel/plugin-loading.zod.ts", "../../../packages/spec/src/kernel/plugin.zod.ts", "../../../packages/spec/src/kernel/manifest.zod.ts", "../../../packages/spec/src/kernel/metadata-customization.zod.ts", "../../../packages/spec/src/kernel/metadata-loader.zod.ts", "../../../packages/spec/src/kernel/metadata-plugin.zod.ts", "../../../packages/spec/src/kernel/package-registry.zod.ts", "../../../packages/spec/src/kernel/package-upgrade.zod.ts", "../../../packages/spec/src/kernel/plugin-lifecycle-advanced.zod.ts", "../../../packages/spec/src/kernel/plugin-lifecycle-events.zod.ts", "../../../packages/spec/src/kernel/plugin-runtime.zod.ts", "../../../packages/spec/src/kernel/plugin-security-advanced.zod.ts", "../../../packages/spec/src/kernel/plugin-structure.zod.ts", "../../../packages/spec/src/kernel/plugin-validator.zod.ts", "../../../packages/spec/src/kernel/plugin-versioning.zod.ts", "../../../packages/spec/src/kernel/service-registry.zod.ts", "../../../packages/spec/src/kernel/startup-orchestrator.zod.ts", "../../../packages/spec/src/kernel/plugin-registry.zod.ts", "../../../packages/spec/src/kernel/plugin-security.zod.ts", "../../../packages/spec/src/cloud/index.ts", "../../../packages/spec/src/cloud/marketplace.zod.ts", "../../../packages/spec/src/cloud/developer-portal.zod.ts", "../../../packages/spec/src/cloud/marketplace-admin.zod.ts", "../../../packages/spec/src/cloud/app-store.zod.ts", "../../../packages/spec/src/qa/index.ts", "../../../packages/spec/src/qa/testing.zod.ts", "../../../packages/spec/src/identity/index.ts", "../../../packages/spec/src/identity/identity.zod.ts", "../../../packages/spec/src/identity/protocol.ts", "../../../packages/spec/src/identity/role.zod.ts", "../../../packages/spec/src/identity/organization.zod.ts", "../../../packages/spec/src/identity/scim.zod.ts", "../../../packages/spec/src/ai/index.ts", "../../../packages/spec/src/ai/agent.zod.ts", "../../../packages/spec/src/ai/tool.zod.ts", "../../../packages/spec/src/ai/skill.zod.ts", "../../../packages/spec/src/ai/agent-action.zod.ts", "../../../packages/spec/src/ai/devops-agent.zod.ts", "../../../packages/spec/src/ai/plugin-development.zod.ts", "../../../packages/spec/src/ai/runtime-ops.zod.ts", "../../../packages/spec/src/ai/model-registry.zod.ts", "../../../packages/spec/src/ai/mcp.zod.ts", "../../../packages/spec/src/ai/cost.zod.ts", "../../../packages/spec/src/ai/rag-pipeline.zod.ts", "../../../packages/spec/src/ai/nlq.zod.ts", "../../../packages/spec/src/ai/orchestration.zod.ts", "../../../packages/spec/src/ai/predictive.zod.ts", "../../../packages/spec/src/ai/conversation.zod.ts", "../../../packages/spec/src/ai/feedback-loop.zod.ts", "../../../packages/spec/src/api/index.ts", "../../../packages/spec/src/api/contract.zod.ts", "../../../packages/spec/src/api/endpoint.zod.ts", "../../../packages/spec/src/api/discovery.zod.ts", "../../../packages/spec/src/api/events.zod.ts", "../../../packages/spec/src/api/realtime-shared.zod.ts", "../../../packages/spec/src/api/realtime.zod.ts", "../../../packages/spec/src/api/websocket.zod.ts", "../../../packages/spec/src/api/router.zod.ts", "../../../packages/spec/src/api/odata.zod.ts", "../../../packages/spec/src/api/graphql.zod.ts", "../../../packages/spec/src/api/batch.zod.ts", "../../../packages/spec/src/api/http-cache.zod.ts", "../../../packages/spec/src/api/errors.zod.ts", "../../../packages/spec/src/automation/workflow.zod.ts", "../../../packages/spec/src/api/protocol.zod.ts", "../../../packages/spec/src/api/rest-server.zod.ts", "../../../packages/spec/src/api/registry.zod.ts", "../../../packages/spec/src/api/documentation.zod.ts", "../../../packages/spec/src/api/analytics.zod.ts", "../../../packages/spec/src/api/versioning.zod.ts", "../../../packages/spec/src/api/auth.zod.ts", "../../../packages/spec/src/api/auth-endpoints.zod.ts", "../../../packages/spec/src/api/storage.zod.ts", "../../../packages/spec/src/api/metadata.zod.ts", "../../../packages/spec/src/api/dispatcher.zod.ts", "../../../packages/spec/src/api/plugin-rest-api.zod.ts", "../../../packages/spec/src/api/query-adapter.zod.ts", "../../../packages/spec/src/api/feed-api.zod.ts", "../../../packages/spec/src/api/export.zod.ts", "../../../packages/spec/src/automation/flow.zod.ts", "../../../packages/spec/src/automation/execution.zod.ts", "../../../packages/spec/src/api/automation-api.zod.ts", "../../../packages/spec/src/api/package-api.zod.ts", "../../../packages/spec/src/automation/index.ts", "../../../packages/spec/src/automation/webhook.zod.ts", "../../../packages/spec/src/automation/approval.zod.ts", "../../../packages/spec/src/automation/etl.zod.ts", "../../../packages/spec/src/automation/trigger-registry.zod.ts", "../../../packages/spec/src/automation/sync.zod.ts", "../../../packages/spec/src/automation/node-executor.zod.ts", "../../../packages/spec/src/automation/bpmn-interop.zod.ts", "../../../packages/spec/src/integration/index.ts", "../../../packages/spec/src/shared/connector-auth.zod.ts", "../../../packages/spec/src/integration/connector.zod.ts", "../../../packages/spec/src/integration/connector/saas.zod.ts", "../../../packages/spec/src/integration/connector/database.zod.ts", "../../../packages/spec/src/integration/connector/file-storage.zod.ts", "../../../packages/spec/src/integration/connector/message-queue.zod.ts", "../../../packages/spec/src/integration/connector/github.zod.ts", "../../../packages/spec/src/integration/connector/vercel.zod.ts", "../../../packages/spec/src/contracts/index.ts", "../../../packages/spec/src/studio/index.ts", "../../../packages/spec/src/studio/plugin.zod.ts", "../../../packages/spec/src/studio/object-designer.zod.ts", "../../../packages/spec/src/studio/page-builder.zod.ts", "../../../packages/spec/src/studio/flow-builder.zod.ts", "../../../packages/spec/src/stack.zod.ts", "../../app-crm/src/objects/index.ts", "../../app-crm/src/objects/account.object.ts", "../../app-crm/src/objects/campaign.object.ts", "../../app-crm/src/objects/case.object.ts", "../../app-crm/src/objects/contact.object.ts", "../../app-crm/src/objects/contract.object.ts", "../../app-crm/src/objects/lead.object.ts", "../../app-crm/src/objects/lead.state.ts", "../../app-crm/src/objects/opportunity.object.ts", "../../app-crm/src/objects/opportunity.state.ts", "../../app-crm/src/objects/product.object.ts", "../../app-crm/src/objects/quote.object.ts", "../../app-crm/src/objects/task.object.ts", "../../app-crm/src/apis/index.ts", "../../app-crm/src/apis/lead-convert.api.ts", "../../app-crm/src/apis/pipeline-stats.api.ts", "../../app-crm/src/actions/index.ts", "../../app-crm/src/actions/case.actions.ts", "../../app-crm/src/actions/contact.actions.ts", "../../app-crm/src/actions/global.actions.ts", "../../app-crm/src/actions/lead.actions.ts", "../../app-crm/src/actions/opportunity.actions.ts", "../../app-crm/src/dashboards/index.ts", "../../app-crm/src/dashboards/executive.dashboard.ts", "../../app-crm/src/dashboards/sales.dashboard.ts", "../../app-crm/src/dashboards/service.dashboard.ts", "../../app-crm/src/reports/index.ts", "../../app-crm/src/reports/account.report.ts", "../../app-crm/src/reports/case.report.ts", "../../app-crm/src/reports/contact.report.ts", "../../app-crm/src/reports/lead.report.ts", "../../app-crm/src/reports/opportunity.report.ts", "../../app-crm/src/reports/task.report.ts", "../../app-crm/src/flows/campaign-enrollment.flow.ts", "../../app-crm/src/flows/case-escalation.flow.ts", "../../app-crm/src/flows/lead-conversion.flow.ts", "../../app-crm/src/flows/opportunity-approval.flow.ts", "../../app-crm/src/flows/quote-generation.flow.ts", "../../app-crm/src/flows/index.ts", "../../app-crm/src/agents/email-campaign.agent.ts", "../../app-crm/src/agents/lead-enrichment.agent.ts", "../../app-crm/src/agents/revenue-intelligence.agent.ts", "../../app-crm/src/agents/sales.agent.ts", "../../app-crm/src/agents/service.agent.ts", "../../app-crm/src/agents/index.ts", "../../app-crm/src/rag/index.ts", "../../app-crm/src/rag/competitive-intel.rag.ts", "../../app-crm/src/rag/product-info.rag.ts", "../../app-crm/src/rag/sales-knowledge.rag.ts", "../../app-crm/src/rag/support-knowledge.rag.ts", "../../app-crm/src/profiles/index.ts", "../../app-crm/src/profiles/marketing-user.profile.ts", "../../app-crm/src/profiles/sales-manager.profile.ts", "../../app-crm/src/profiles/sales-rep.profile.ts", "../../app-crm/src/profiles/service-agent.profile.ts", "../../app-crm/src/profiles/system-admin.profile.ts", "../../app-crm/src/apps/index.ts", "../../app-crm/src/apps/crm.app.ts", "../../app-crm/src/apps/crm_modern.app.ts", "../../app-crm/src/translations/index.ts", "../../app-crm/src/translations/en.ts", "../../app-crm/src/translations/zh-CN.ts", "../../app-crm/src/translations/ja-JP.ts", "../../app-crm/src/translations/es-ES.ts", "../../app-crm/src/translations/crm.translation.ts", "../../app-crm/src/data/index.ts", "../../app-crm/src/sharing/account.sharing.ts", "../../app-crm/src/sharing/case.sharing.ts", "../../app-crm/src/sharing/opportunity.sharing.ts", "../../app-crm/src/sharing/role-hierarchy.ts", "../../app-crm/objectstack.config.ts", "../../app-todo/src/objects/index.ts", "../../app-todo/src/objects/task.object.ts", "../../app-todo/src/actions/index.ts", "../../app-todo/src/actions/task.actions.ts", "../../app-todo/src/dashboards/index.ts", "../../app-todo/src/dashboards/task.dashboard.ts", "../../app-todo/src/reports/index.ts", "../../app-todo/src/reports/task.report.ts", "../../app-todo/src/flows/task.flow.ts", "../../app-todo/src/flows/index.ts", "../../app-todo/src/apps/index.ts", "../../app-todo/src/apps/todo.app.ts", "../../app-todo/src/translations/index.ts", "../../app-todo/src/translations/en.ts", "../../app-todo/src/translations/zh-CN.ts", "../../app-todo/src/translations/ja-JP.ts", "../../app-todo/src/translations/todo.translation.ts", "../../app-todo/objectstack.config.ts", "../../plugin-bi/objectstack.config.ts", "../server/index.ts"], - "sourcesContent": ["/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n", "// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n", "import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * \u2716 Expected number, received string at \"username\n * favoriteNumbers[0]\n * \u2716 Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`\u2716 ${issue.message}`);\n if (issue.path?.length)\n lines.push(` \u2192 at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n", "import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n", "import * as util from \"./util.js\";\nexport const cuid = /^[cC][^\\s-]{8,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){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}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n", "// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n", "export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n", "export const version = {\n major: 4,\n minor: 3,\n patch: 6,\n};\n", "import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalOut) {\n if (result.issues.length) {\n // For optional-out schemas, ignore errors on absent keys\n if (isOptionalOut && !(key in input)) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalOut) {\n // For optional-out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig\n ? { code: \"too_big\", maximum: items.length, inclusive: true }\n : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (result.issues.length && input === undefined) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u062D\u0631\u0641\", verb: \"\u0623\u0646 \u064A\u062D\u0648\u064A\" },\n file: { unit: \"\u0628\u0627\u064A\u062A\", verb: \"\u0623\u0646 \u064A\u062D\u0648\u064A\" },\n array: { unit: \"\u0639\u0646\u0635\u0631\", verb: \"\u0623\u0646 \u064A\u062D\u0648\u064A\" },\n set: { unit: \"\u0639\u0646\u0635\u0631\", verb: \"\u0623\u0646 \u064A\u062D\u0648\u064A\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0645\u062F\u062E\u0644\",\n email: \"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A\",\n url: \"\u0631\u0627\u0628\u0637\",\n emoji: \"\u0625\u064A\u0645\u0648\u062C\u064A\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO\",\n date: \"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO\",\n time: \"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO\",\n duration: \"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO\",\n ipv4: \"\u0639\u0646\u0648\u0627\u0646 IPv4\",\n ipv6: \"\u0639\u0646\u0648\u0627\u0646 IPv6\",\n cidrv4: \"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4\",\n cidrv6: \"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6\",\n base64: \"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded\",\n base64url: \"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded\",\n json_string: \"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON\",\n e164: \"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0645\u062F\u062E\u0644\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;\n }\n return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue.origin ?? \"\u0627\u0644\u0642\u064A\u0645\u0629\"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"\u0639\u0646\u0635\u0631\"}`;\n return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue.origin ?? \"\u0627\u0644\u0642\u064A\u0645\u0629\"} ${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 \"${issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;\n }\n case \"not_multiple_of\":\n return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u0645\u0639\u0631\u0641${issue.keys.length > 1 ? \"\u0627\u062A\" : \"\"} \u063A\u0631\u064A\u0628${issue.keys.length > 1 ? \"\u0629\" : \"\"}: ${util.joinValues(issue.keys, \"\u060C \")}`;\n case \"invalid_key\":\n return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue.origin}`;\n case \"invalid_union\":\n return \"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\";\n case \"invalid_element\":\n return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue.origin}`;\n default:\n return \"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\";\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"simvol\", verb: \"olmal\u0131d\u0131r\" },\n file: { unit: \"bayt\", verb: \"olmal\u0131d\u0131r\" },\n array: { unit: \"element\", verb: \"olmal\u0131d\u0131r\" },\n set: { unit: \"element\", verb: \"olmal\u0131d\u0131r\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Yanl\u0131\u015F d\u0259y\u0259r: g\u00F6zl\u0259nil\u0259n instanceof ${issue.expected}, daxil olan ${received}`;\n }\n return `Yanl\u0131\u015F d\u0259y\u0259r: g\u00F6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Yanl\u0131\u015F d\u0259y\u0259r: g\u00F6zl\u0259nil\u0259n ${util.stringifyPrimitive(issue.values[0])}`;\n return `Yanl\u0131\u015F se\u00E7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u00C7ox b\u00F6y\u00FCk: g\u00F6zl\u0259nil\u0259n ${issue.origin ?? \"d\u0259y\u0259r\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"element\"}`;\n return `\u00C7ox b\u00F6y\u00FCk: g\u00F6zl\u0259nil\u0259n ${issue.origin ?? \"d\u0259y\u0259r\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u00C7ox ki\u00E7ik: g\u00F6zl\u0259nil\u0259n ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n return `\u00C7ox ki\u00E7ik: g\u00F6zl\u0259nil\u0259n ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Yanl\u0131\u015F m\u0259tn: \"${_issue.prefix}\" il\u0259 ba\u015Flamal\u0131d\u0131r`;\n if (_issue.format === \"ends_with\")\n return `Yanl\u0131\u015F m\u0259tn: \"${_issue.suffix}\" il\u0259 bitm\u0259lidir`;\n if (_issue.format === \"includes\")\n return `Yanl\u0131\u015F m\u0259tn: \"${_issue.includes}\" daxil olmal\u0131d\u0131r`;\n if (_issue.format === \"regex\")\n return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;\n return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Yanl\u0131\u015F \u0259d\u0259d: ${issue.divisor} il\u0259 b\u00F6l\u00FCn\u0259 bil\u0259n olmal\u0131d\u0131r`;\n case \"unrecognized_keys\":\n return `Tan\u0131nmayan a\u00E7ar${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} daxilind\u0259 yanl\u0131\u015F a\u00E7ar`;\n case \"invalid_union\":\n return \"Yanl\u0131\u015F d\u0259y\u0259r\";\n case \"invalid_element\":\n return `${issue.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;\n default:\n return `Yanl\u0131\u015F d\u0259y\u0259r`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nfunction getBelarusianPlural(count, one, few, many) {\n const absCount = Math.abs(count);\n const lastDigit = absCount % 10;\n const lastTwoDigits = absCount % 100;\n if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {\n return many;\n }\n if (lastDigit === 1) {\n return one;\n }\n if (lastDigit >= 2 && lastDigit <= 4) {\n return few;\n }\n return many;\n}\nconst error = () => {\n const Sizable = {\n string: {\n unit: {\n one: \"\u0441\u0456\u043C\u0432\u0430\u043B\",\n few: \"\u0441\u0456\u043C\u0432\u0430\u043B\u044B\",\n many: \"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E\",\n },\n verb: \"\u043C\u0435\u0446\u044C\",\n },\n array: {\n unit: {\n one: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\",\n few: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B\",\n many: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E\",\n },\n verb: \"\u043C\u0435\u0446\u044C\",\n },\n set: {\n unit: {\n one: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\",\n few: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B\",\n many: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E\",\n },\n verb: \"\u043C\u0435\u0446\u044C\",\n },\n file: {\n unit: {\n one: \"\u0431\u0430\u0439\u0442\",\n few: \"\u0431\u0430\u0439\u0442\u044B\",\n many: \"\u0431\u0430\u0439\u0442\u0430\u045E\",\n },\n verb: \"\u043C\u0435\u0446\u044C\",\n },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0443\u0432\u043E\u0434\",\n email: \"email \u0430\u0434\u0440\u0430\u0441\",\n url: \"URL\",\n emoji: \"\u044D\u043C\u043E\u0434\u0437\u0456\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441\",\n date: \"ISO \u0434\u0430\u0442\u0430\",\n time: \"ISO \u0447\u0430\u0441\",\n duration: \"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C\",\n ipv4: \"IPv4 \u0430\u0434\u0440\u0430\u0441\",\n ipv6: \"IPv6 \u0430\u0434\u0440\u0430\u0441\",\n cidrv4: \"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D\",\n cidrv6: \"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D\",\n base64: \"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64\",\n base64url: \"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url\",\n json_string: \"JSON \u0440\u0430\u0434\u043E\u043A\",\n e164: \"\u043D\u0443\u043C\u0430\u0440 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0443\u0432\u043E\u0434\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u043B\u0456\u043A\",\n array: \"\u043C\u0430\u0441\u0456\u045E\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;\n }\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const maxValue = Number(issue.maximum);\n const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435\"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`;\n }\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435\"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const minValue = Number(issue.minimum);\n const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`;\n }\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue.keys.length > 1 ? \"\u043A\u043B\u044E\u0447\u044B\" : \"\u043A\u043B\u044E\u0447\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434\";\n case \"invalid_element\":\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue.origin}`;\n default:\n return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0441\u0438\u043C\u0432\u043E\u043B\u0430\", verb: \"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430\" },\n file: { unit: \"\u0431\u0430\u0439\u0442\u0430\", verb: \"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430\" },\n array: { unit: \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430\", verb: \"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430\" },\n set: { unit: \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430\", verb: \"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0432\u0445\u043E\u0434\",\n email: \"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441\",\n url: \"URL\",\n emoji: \"\u0435\u043C\u043E\u0434\u0436\u0438\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0432\u0440\u0435\u043C\u0435\",\n date: \"ISO \u0434\u0430\u0442\u0430\",\n time: \"ISO \u0432\u0440\u0435\u043C\u0435\",\n duration: \"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442\",\n ipv4: \"IPv4 \u0430\u0434\u0440\u0435\u0441\",\n ipv6: \"IPv6 \u0430\u0434\u0440\u0435\u0441\",\n cidrv4: \"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\",\n cidrv6: \"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\",\n base64: \"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437\",\n base64url: \"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437\",\n json_string: \"JSON \u043D\u0438\u0437\",\n e164: \"E.164 \u043D\u043E\u043C\u0435\u0440\",\n jwt: \"JWT\",\n template_literal: \"\u0432\u0445\u043E\u0434\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0447\u0438\u0441\u043B\u043E\",\n array: \"\u043C\u0430\u0441\u0438\u0432\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;\n }\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue.origin ?? \"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442\"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430\"}`;\n return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue.origin ?? \"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442\"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`;\n let invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D\";\n if (_issue.format === \"emoji\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E\";\n if (_issue.format === \"datetime\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E\";\n if (_issue.format === \"date\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430\";\n if (_issue.format === \"time\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E\";\n if (_issue.format === \"duration\")\n invalid_adj = \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430\";\n return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue.keys.length > 1 ? \"\u0438\" : \"\"} \u043A\u043B\u044E\u0447${issue.keys.length > 1 ? \"\u043E\u0432\u0435\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434\";\n case \"invalid_element\":\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue.origin}`;\n default:\n return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"car\u00E0cters\", verb: \"contenir\" },\n file: { unit: \"bytes\", verb: \"contenir\" },\n array: { unit: \"elements\", verb: \"contenir\" },\n set: { unit: \"elements\", verb: \"contenir\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"entrada\",\n email: \"adre\u00E7a electr\u00F2nica\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"data i hora ISO\",\n date: \"data ISO\",\n time: \"hora ISO\",\n duration: \"durada ISO\",\n ipv4: \"adre\u00E7a IPv4\",\n ipv6: \"adre\u00E7a IPv6\",\n cidrv4: \"rang IPv4\",\n cidrv6: \"rang IPv6\",\n base64: \"cadena codificada en base64\",\n base64url: \"cadena codificada en base64url\",\n json_string: \"cadena JSON\",\n e164: \"n\u00FAmero E.164\",\n jwt: \"JWT\",\n template_literal: \"entrada\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Tipus inv\u00E0lid: s'esperava instanceof ${issue.expected}, s'ha rebut ${received}`;\n }\n return `Tipus inv\u00E0lid: s'esperava ${expected}, s'ha rebut ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Valor inv\u00E0lid: s'esperava ${util.stringifyPrimitive(issue.values[0])}`;\n return `Opci\u00F3 inv\u00E0lida: s'esperava una de ${util.joinValues(issue.values, \" o \")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"com a m\u00E0xim\" : \"menys de\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Massa gran: s'esperava que ${issue.origin ?? \"el valor\"} contingu\u00E9s ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Massa gran: s'esperava que ${issue.origin ?? \"el valor\"} fos ${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"com a m\u00EDnim\" : \"m\u00E9s de\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Massa petit: s'esperava que ${issue.origin} contingu\u00E9s ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Format inv\u00E0lid: ha de comen\u00E7ar amb \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Format inv\u00E0lid: ha d'acabar amb \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Format inv\u00E0lid: ha d'incloure \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Format inv\u00E0lid: ha de coincidir amb el patr\u00F3 ${_issue.pattern}`;\n return `Format inv\u00E0lid per a ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `N\u00FAmero inv\u00E0lid: ha de ser m\u00FAltiple de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Clau${issue.keys.length > 1 ? \"s\" : \"\"} no reconeguda${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Clau inv\u00E0lida a ${issue.origin}`;\n case \"invalid_union\":\n return \"Entrada inv\u00E0lida\"; // Could also be \"Tipus d'uni\u00F3 inv\u00E0lid\" but \"Entrada inv\u00E0lida\" is more general\n case \"invalid_element\":\n return `Element inv\u00E0lid a ${issue.origin}`;\n default:\n return `Entrada inv\u00E0lida`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"znak\u016F\", verb: \"m\u00EDt\" },\n file: { unit: \"bajt\u016F\", verb: \"m\u00EDt\" },\n array: { unit: \"prvk\u016F\", verb: \"m\u00EDt\" },\n set: { unit: \"prvk\u016F\", verb: \"m\u00EDt\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"regul\u00E1rn\u00ED v\u00FDraz\",\n email: \"e-mailov\u00E1 adresa\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"datum a \u010Das ve form\u00E1tu ISO\",\n date: \"datum ve form\u00E1tu ISO\",\n time: \"\u010Das ve form\u00E1tu ISO\",\n duration: \"doba trv\u00E1n\u00ED ISO\",\n ipv4: \"IPv4 adresa\",\n ipv6: \"IPv6 adresa\",\n cidrv4: \"rozsah IPv4\",\n cidrv6: \"rozsah IPv6\",\n base64: \"\u0159et\u011Bzec zak\u00F3dovan\u00FD ve form\u00E1tu base64\",\n base64url: \"\u0159et\u011Bzec zak\u00F3dovan\u00FD ve form\u00E1tu base64url\",\n json_string: \"\u0159et\u011Bzec ve form\u00E1tu JSON\",\n e164: \"\u010D\u00EDslo E.164\",\n jwt: \"JWT\",\n template_literal: \"vstup\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u010D\u00EDslo\",\n string: \"\u0159et\u011Bzec\",\n function: \"funkce\",\n array: \"pole\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Neplatn\u00FD vstup: o\u010Dek\u00E1v\u00E1no instanceof ${issue.expected}, obdr\u017Eeno ${received}`;\n }\n return `Neplatn\u00FD vstup: o\u010Dek\u00E1v\u00E1no ${expected}, obdr\u017Eeno ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Neplatn\u00FD vstup: o\u010Dek\u00E1v\u00E1no ${util.stringifyPrimitive(issue.values[0])}`;\n return `Neplatn\u00E1 mo\u017Enost: o\u010Dek\u00E1v\u00E1na jedna z hodnot ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Hodnota je p\u0159\u00EDli\u0161 velk\u00E1: ${issue.origin ?? \"hodnota\"} mus\u00ED m\u00EDt ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"prvk\u016F\"}`;\n }\n return `Hodnota je p\u0159\u00EDli\u0161 velk\u00E1: ${issue.origin ?? \"hodnota\"} mus\u00ED b\u00FDt ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Hodnota je p\u0159\u00EDli\u0161 mal\u00E1: ${issue.origin ?? \"hodnota\"} mus\u00ED m\u00EDt ${adj}${issue.minimum.toString()} ${sizing.unit ?? \"prvk\u016F\"}`;\n }\n return `Hodnota je p\u0159\u00EDli\u0161 mal\u00E1: ${issue.origin ?? \"hodnota\"} mus\u00ED b\u00FDt ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Neplatn\u00FD \u0159et\u011Bzec: mus\u00ED za\u010D\u00EDnat na \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Neplatn\u00FD \u0159et\u011Bzec: mus\u00ED kon\u010Dit na \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Neplatn\u00FD \u0159et\u011Bzec: mus\u00ED obsahovat \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Neplatn\u00FD \u0159et\u011Bzec: mus\u00ED odpov\u00EDdat vzoru ${_issue.pattern}`;\n return `Neplatn\u00FD form\u00E1t ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Neplatn\u00E9 \u010D\u00EDslo: mus\u00ED b\u00FDt n\u00E1sobkem ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Nezn\u00E1m\u00E9 kl\u00ED\u010De: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Neplatn\u00FD kl\u00ED\u010D v ${issue.origin}`;\n case \"invalid_union\":\n return \"Neplatn\u00FD vstup\";\n case \"invalid_element\":\n return `Neplatn\u00E1 hodnota v ${issue.origin}`;\n default:\n return `Neplatn\u00FD vstup`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"tegn\", verb: \"havde\" },\n file: { unit: \"bytes\", verb: \"havde\" },\n array: { unit: \"elementer\", verb: \"indeholdt\" },\n set: { unit: \"elementer\", verb: \"indeholdt\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"e-mailadresse\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO dato- og klokkesl\u00E6t\",\n date: \"ISO-dato\",\n time: \"ISO-klokkesl\u00E6t\",\n duration: \"ISO-varighed\",\n ipv4: \"IPv4-omr\u00E5de\",\n ipv6: \"IPv6-omr\u00E5de\",\n cidrv4: \"IPv4-spektrum\",\n cidrv6: \"IPv6-spektrum\",\n base64: \"base64-kodet streng\",\n base64url: \"base64url-kodet streng\",\n json_string: \"JSON-streng\",\n e164: \"E.164-nummer\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n string: \"streng\",\n number: \"tal\",\n boolean: \"boolean\",\n array: \"liste\",\n object: \"objekt\",\n set: \"s\u00E6t\",\n file: \"fil\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ugyldigt input: forventede instanceof ${issue.expected}, fik ${received}`;\n }\n return `Ugyldigt input: forventede ${expected}, fik ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ugyldig v\u00E6rdi: forventede ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ugyldigt valg: forventede en af f\u00F8lgende ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n if (sizing)\n return `For stor: forventede ${origin ?? \"value\"} ${sizing.verb} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"elementer\"}`;\n return `For stor: forventede ${origin ?? \"value\"} havde ${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n if (sizing) {\n return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `For lille: forventede ${origin} havde ${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Ugyldig streng: skal starte med \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Ugyldig streng: skal ende med \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Ugyldig streng: skal indeholde \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Ugyldig streng: skal matche m\u00F8nsteret ${_issue.pattern}`;\n return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ugyldigt tal: skal v\u00E6re deleligt med ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Ukendte n\u00F8gler\" : \"Ukendt n\u00F8gle\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ugyldig n\u00F8gle i ${issue.origin}`;\n case \"invalid_union\":\n return \"Ugyldigt input: matcher ingen af de tilladte typer\";\n case \"invalid_element\":\n return `Ugyldig v\u00E6rdi i ${issue.origin}`;\n default:\n return `Ugyldigt input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"Zeichen\", verb: \"zu haben\" },\n file: { unit: \"Bytes\", verb: \"zu haben\" },\n array: { unit: \"Elemente\", verb: \"zu haben\" },\n set: { unit: \"Elemente\", verb: \"zu haben\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"Eingabe\",\n email: \"E-Mail-Adresse\",\n url: \"URL\",\n emoji: \"Emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO-Datum und -Uhrzeit\",\n date: \"ISO-Datum\",\n time: \"ISO-Uhrzeit\",\n duration: \"ISO-Dauer\",\n ipv4: \"IPv4-Adresse\",\n ipv6: \"IPv6-Adresse\",\n cidrv4: \"IPv4-Bereich\",\n cidrv6: \"IPv6-Bereich\",\n base64: \"Base64-codierter String\",\n base64url: \"Base64-URL-codierter String\",\n json_string: \"JSON-String\",\n e164: \"E.164-Nummer\",\n jwt: \"JWT\",\n template_literal: \"Eingabe\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"Zahl\",\n array: \"Array\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ung\u00FCltige Eingabe: erwartet instanceof ${issue.expected}, erhalten ${received}`;\n }\n return `Ung\u00FCltige Eingabe: erwartet ${expected}, erhalten ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ung\u00FCltige Eingabe: erwartet ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ung\u00FCltige Option: erwartet eine von ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Zu gro\u00DF: erwartet, dass ${issue.origin ?? \"Wert\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"Elemente\"} hat`;\n return `Zu gro\u00DF: erwartet, dass ${issue.origin ?? \"Wert\"} ${adj}${issue.maximum.toString()} ist`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`;\n }\n return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Ung\u00FCltiger String: muss mit \"${_issue.prefix}\" beginnen`;\n if (_issue.format === \"ends_with\")\n return `Ung\u00FCltiger String: muss mit \"${_issue.suffix}\" enden`;\n if (_issue.format === \"includes\")\n return `Ung\u00FCltiger String: muss \"${_issue.includes}\" enthalten`;\n if (_issue.format === \"regex\")\n return `Ung\u00FCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;\n return `Ung\u00FCltig: ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ung\u00FCltige Zahl: muss ein Vielfaches von ${issue.divisor} sein`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Unbekannte Schl\u00FCssel\" : \"Unbekannter Schl\u00FCssel\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ung\u00FCltiger Schl\u00FCssel in ${issue.origin}`;\n case \"invalid_union\":\n return \"Ung\u00FCltige Eingabe\";\n case \"invalid_element\":\n return `Ung\u00FCltiger Wert in ${issue.origin}`;\n default:\n return `Ung\u00FCltige Eingabe`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"karaktrojn\", verb: \"havi\" },\n file: { unit: \"bajtojn\", verb: \"havi\" },\n array: { unit: \"elementojn\", verb: \"havi\" },\n set: { unit: \"elementojn\", verb: \"havi\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"enigo\",\n email: \"retadreso\",\n url: \"URL\",\n emoji: \"emo\u011Dio\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO-datotempo\",\n date: \"ISO-dato\",\n time: \"ISO-tempo\",\n duration: \"ISO-da\u016Dro\",\n ipv4: \"IPv4-adreso\",\n ipv6: \"IPv6-adreso\",\n cidrv4: \"IPv4-rango\",\n cidrv6: \"IPv6-rango\",\n base64: \"64-ume kodita karaktraro\",\n base64url: \"URL-64-ume kodita karaktraro\",\n json_string: \"JSON-karaktraro\",\n e164: \"E.164-nombro\",\n jwt: \"JWT\",\n template_literal: \"enigo\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"nombro\",\n array: \"tabelo\",\n null: \"senvalora\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Nevalida enigo: atendi\u011Dis instanceof ${issue.expected}, ricevi\u011Dis ${received}`;\n }\n return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Nevalida enigo: atendi\u011Dis ${util.stringifyPrimitive(issue.values[0])}`;\n return `Nevalida opcio: atendi\u011Dis unu el ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Tro granda: atendi\u011Dis ke ${issue.origin ?? \"valoro\"} havu ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementojn\"}`;\n return `Tro granda: atendi\u011Dis ke ${issue.origin ?? \"valoro\"} havu ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Tro malgranda: atendi\u011Dis ke ${issue.origin} havu ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Tro malgranda: atendi\u011Dis ke ${issue.origin} estu ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Nevalida karaktraro: devas komenci\u011Di per \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Nevalida karaktraro: devas fini\u011Di per \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Nevalida karaktraro: devas inkluzivi \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;\n return `Nevalida ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Nevalida nombro: devas esti oblo de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Nekonata${issue.keys.length > 1 ? \"j\" : \"\"} \u015Dlosilo${issue.keys.length > 1 ? \"j\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Nevalida \u015Dlosilo en ${issue.origin}`;\n case \"invalid_union\":\n return \"Nevalida enigo\";\n case \"invalid_element\":\n return `Nevalida valoro en ${issue.origin}`;\n default:\n return `Nevalida enigo`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caracteres\", verb: \"tener\" },\n file: { unit: \"bytes\", verb: \"tener\" },\n array: { unit: \"elementos\", verb: \"tener\" },\n set: { unit: \"elementos\", verb: \"tener\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"entrada\",\n email: \"direcci\u00F3n de correo electr\u00F3nico\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"fecha y hora ISO\",\n date: \"fecha ISO\",\n time: \"hora ISO\",\n duration: \"duraci\u00F3n ISO\",\n ipv4: \"direcci\u00F3n IPv4\",\n ipv6: \"direcci\u00F3n IPv6\",\n cidrv4: \"rango IPv4\",\n cidrv6: \"rango IPv6\",\n base64: \"cadena codificada en base64\",\n base64url: \"URL codificada en base64\",\n json_string: \"cadena JSON\",\n e164: \"n\u00FAmero E.164\",\n jwt: \"JWT\",\n template_literal: \"entrada\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n string: \"texto\",\n number: \"n\u00FAmero\",\n boolean: \"booleano\",\n array: \"arreglo\",\n object: \"objeto\",\n set: \"conjunto\",\n file: \"archivo\",\n date: \"fecha\",\n bigint: \"n\u00FAmero grande\",\n symbol: \"s\u00EDmbolo\",\n undefined: \"indefinido\",\n null: \"nulo\",\n function: \"funci\u00F3n\",\n map: \"mapa\",\n record: \"registro\",\n tuple: \"tupla\",\n enum: \"enumeraci\u00F3n\",\n union: \"uni\u00F3n\",\n literal: \"literal\",\n promise: \"promesa\",\n void: \"vac\u00EDo\",\n never: \"nunca\",\n unknown: \"desconocido\",\n any: \"cualquiera\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Entrada inv\u00E1lida: se esperaba instanceof ${issue.expected}, recibido ${received}`;\n }\n return `Entrada inv\u00E1lida: se esperaba ${expected}, recibido ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Entrada inv\u00E1lida: se esperaba ${util.stringifyPrimitive(issue.values[0])}`;\n return `Opci\u00F3n inv\u00E1lida: se esperaba una de ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n if (sizing)\n return `Demasiado grande: se esperaba que ${origin ?? \"valor\"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementos\"}`;\n return `Demasiado grande: se esperaba que ${origin ?? \"valor\"} fuera ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n if (sizing) {\n return `Demasiado peque\u00F1o: se esperaba que ${origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Demasiado peque\u00F1o: se esperaba que ${origin} fuera ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Cadena inv\u00E1lida: debe comenzar con \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Cadena inv\u00E1lida: debe terminar en \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Cadena inv\u00E1lida: debe incluir \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Cadena inv\u00E1lida: debe coincidir con el patr\u00F3n ${_issue.pattern}`;\n return `Inv\u00E1lido ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `N\u00FAmero inv\u00E1lido: debe ser m\u00FAltiplo de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Llave${issue.keys.length > 1 ? \"s\" : \"\"} desconocida${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Llave inv\u00E1lida en ${TypeDictionary[issue.origin] ?? issue.origin}`;\n case \"invalid_union\":\n return \"Entrada inv\u00E1lida\";\n case \"invalid_element\":\n return `Valor inv\u00E1lido en ${TypeDictionary[issue.origin] ?? issue.origin}`;\n default:\n return `Entrada inv\u00E1lida`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631\", verb: \"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F\" },\n file: { unit: \"\u0628\u0627\u06CC\u062A\", verb: \"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F\" },\n array: { unit: \"\u0622\u06CC\u062A\u0645\", verb: \"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F\" },\n set: { unit: \"\u0622\u06CC\u062A\u0645\", verb: \"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0648\u0631\u0648\u062F\u06CC\",\n email: \"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644\",\n url: \"URL\",\n emoji: \"\u0627\u06CC\u0645\u0648\u062C\u06CC\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648\",\n date: \"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648\",\n time: \"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648\",\n duration: \"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648\",\n ipv4: \"IPv4 \u0622\u062F\u0631\u0633\",\n ipv6: \"IPv6 \u0622\u062F\u0631\u0633\",\n cidrv4: \"IPv4 \u062F\u0627\u0645\u0646\u0647\",\n cidrv6: \"IPv6 \u062F\u0627\u0645\u0646\u0647\",\n base64: \"base64-encoded \u0631\u0634\u062A\u0647\",\n base64url: \"base64url-encoded \u0631\u0634\u062A\u0647\",\n json_string: \"JSON \u0631\u0634\u062A\u0647\",\n e164: \"E.164 \u0639\u062F\u062F\",\n jwt: \"JWT\",\n template_literal: \"\u0648\u0631\u0648\u062F\u06CC\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0639\u062F\u062F\",\n array: \"\u0622\u0631\u0627\u06CC\u0647\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;\n }\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1) {\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${util.stringifyPrimitive(issue.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;\n }\n return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${util.joinValues(issue.values, \"|\")} \u0645\u06CC\u200C\u0628\u0648\u062F`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue.origin ?? \"\u0645\u0642\u062F\u0627\u0631\"} \u0628\u0627\u06CC\u062F ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0639\u0646\u0635\u0631\"} \u0628\u0627\u0634\u062F`;\n }\n return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue.origin ?? \"\u0645\u0642\u062F\u0627\u0631\"} \u0628\u0627\u06CC\u062F ${adj}${issue.maximum.toString()} \u0628\u0627\u0634\u062F`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue.origin} \u0628\u0627\u06CC\u062F ${adj}${issue.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;\n }\n return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue.origin} \u0628\u0627\u06CC\u062F ${adj}${issue.minimum.toString()} \u0628\u0627\u0634\u062F`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \"${_issue.prefix}\" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;\n }\n if (_issue.format === \"ends_with\") {\n return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \"${_issue.suffix}\" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;\n }\n if (_issue.format === \"includes\") {\n return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 \"${_issue.includes}\" \u0628\u0627\u0634\u062F`;\n }\n if (_issue.format === \"regex\") {\n return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;\n }\n return `${FormatDictionary[_issue.format] ?? issue.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;\n }\n case \"not_multiple_of\":\n return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue.divisor} \u0628\u0627\u0634\u062F`;\n case \"unrecognized_keys\":\n return `\u06A9\u0644\u06CC\u062F${issue.keys.length > 1 ? \"\u0647\u0627\u06CC\" : \"\"} \u0646\u0627\u0634\u0646\u0627\u0633: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue.origin}`;\n case \"invalid_union\":\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;\n case \"invalid_element\":\n return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue.origin}`;\n default:\n return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"merkki\u00E4\", subject: \"merkkijonon\" },\n file: { unit: \"tavua\", subject: \"tiedoston\" },\n array: { unit: \"alkiota\", subject: \"listan\" },\n set: { unit: \"alkiota\", subject: \"joukon\" },\n number: { unit: \"\", subject: \"luvun\" },\n bigint: { unit: \"\", subject: \"suuren kokonaisluvun\" },\n int: { unit: \"\", subject: \"kokonaisluvun\" },\n date: { unit: \"\", subject: \"p\u00E4iv\u00E4m\u00E4\u00E4r\u00E4n\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"s\u00E4\u00E4nn\u00F6llinen lauseke\",\n email: \"s\u00E4hk\u00F6postiosoite\",\n url: \"URL-osoite\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO-aikaleima\",\n date: \"ISO-p\u00E4iv\u00E4m\u00E4\u00E4r\u00E4\",\n time: \"ISO-aika\",\n duration: \"ISO-kesto\",\n ipv4: \"IPv4-osoite\",\n ipv6: \"IPv6-osoite\",\n cidrv4: \"IPv4-alue\",\n cidrv6: \"IPv6-alue\",\n base64: \"base64-koodattu merkkijono\",\n base64url: \"base64url-koodattu merkkijono\",\n json_string: \"JSON-merkkijono\",\n e164: \"E.164-luku\",\n jwt: \"JWT\",\n template_literal: \"templaattimerkkijono\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Virheellinen tyyppi: odotettiin instanceof ${issue.expected}, oli ${received}`;\n }\n return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Virheellinen sy\u00F6te: t\u00E4ytyy olla ${util.stringifyPrimitive(issue.values[0])}`;\n return `Virheellinen valinta: t\u00E4ytyy olla yksi seuraavista: ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Liian suuri: ${sizing.subject} t\u00E4ytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim();\n }\n return `Liian suuri: arvon t\u00E4ytyy olla ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Liian pieni: ${sizing.subject} t\u00E4ytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim();\n }\n return `Liian pieni: arvon t\u00E4ytyy olla ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Virheellinen sy\u00F6te: t\u00E4ytyy alkaa \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Virheellinen sy\u00F6te: t\u00E4ytyy loppua \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Virheellinen sy\u00F6te: t\u00E4ytyy sis\u00E4lt\u00E4\u00E4 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\") {\n return `Virheellinen sy\u00F6te: t\u00E4ytyy vastata s\u00E4\u00E4nn\u00F6llist\u00E4 lauseketta ${_issue.pattern}`;\n }\n return `Virheellinen ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Virheellinen luku: t\u00E4ytyy olla luvun ${issue.divisor} monikerta`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Tuntemattomat avaimet\" : \"Tuntematon avain\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return \"Virheellinen avain tietueessa\";\n case \"invalid_union\":\n return \"Virheellinen unioni\";\n case \"invalid_element\":\n return \"Virheellinen arvo joukossa\";\n default:\n return `Virheellinen sy\u00F6te`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caract\u00E8res\", verb: \"avoir\" },\n file: { unit: \"octets\", verb: \"avoir\" },\n array: { unit: \"\u00E9l\u00E9ments\", verb: \"avoir\" },\n set: { unit: \"\u00E9l\u00E9ments\", verb: \"avoir\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"entr\u00E9e\",\n email: \"adresse e-mail\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"date et heure ISO\",\n date: \"date ISO\",\n time: \"heure ISO\",\n duration: \"dur\u00E9e ISO\",\n ipv4: \"adresse IPv4\",\n ipv6: \"adresse IPv6\",\n cidrv4: \"plage IPv4\",\n cidrv6: \"plage IPv6\",\n base64: \"cha\u00EEne encod\u00E9e en base64\",\n base64url: \"cha\u00EEne encod\u00E9e en base64url\",\n json_string: \"cha\u00EEne JSON\",\n e164: \"num\u00E9ro E.164\",\n jwt: \"JWT\",\n template_literal: \"entr\u00E9e\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"nombre\",\n array: \"tableau\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Entr\u00E9e invalide : instanceof ${issue.expected} attendu, ${received} re\u00E7u`;\n }\n return `Entr\u00E9e invalide : ${expected} attendu, ${received} re\u00E7u`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Entr\u00E9e invalide : ${util.stringifyPrimitive(issue.values[0])} attendu`;\n return `Option invalide : une valeur parmi ${util.joinValues(issue.values, \"|\")} attendue`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Trop grand : ${issue.origin ?? \"valeur\"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u00E9l\u00E9ment(s)\"}`;\n return `Trop grand : ${issue.origin ?? \"valeur\"} doit \u00EAtre ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Trop petit : ${issue.origin} doit \u00EAtre ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Cha\u00EEne invalide : doit commencer par \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Cha\u00EEne invalide : doit se terminer par \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Cha\u00EEne invalide : doit inclure \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Cha\u00EEne invalide : doit correspondre au mod\u00E8le ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} invalide`;\n }\n case \"not_multiple_of\":\n return `Nombre invalide : doit \u00EAtre un multiple de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Cl\u00E9${issue.keys.length > 1 ? \"s\" : \"\"} non reconnue${issue.keys.length > 1 ? \"s\" : \"\"} : ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Cl\u00E9 invalide dans ${issue.origin}`;\n case \"invalid_union\":\n return \"Entr\u00E9e invalide\";\n case \"invalid_element\":\n return `Valeur invalide dans ${issue.origin}`;\n default:\n return `Entr\u00E9e invalide`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caract\u00E8res\", verb: \"avoir\" },\n file: { unit: \"octets\", verb: \"avoir\" },\n array: { unit: \"\u00E9l\u00E9ments\", verb: \"avoir\" },\n set: { unit: \"\u00E9l\u00E9ments\", verb: \"avoir\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"entr\u00E9e\",\n email: \"adresse courriel\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"date-heure ISO\",\n date: \"date ISO\",\n time: \"heure ISO\",\n duration: \"dur\u00E9e ISO\",\n ipv4: \"adresse IPv4\",\n ipv6: \"adresse IPv6\",\n cidrv4: \"plage IPv4\",\n cidrv6: \"plage IPv6\",\n base64: \"cha\u00EEne encod\u00E9e en base64\",\n base64url: \"cha\u00EEne encod\u00E9e en base64url\",\n json_string: \"cha\u00EEne JSON\",\n e164: \"num\u00E9ro E.164\",\n jwt: \"JWT\",\n template_literal: \"entr\u00E9e\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Entr\u00E9e invalide : attendu instanceof ${issue.expected}, re\u00E7u ${received}`;\n }\n return `Entr\u00E9e invalide : attendu ${expected}, re\u00E7u ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Entr\u00E9e invalide : attendu ${util.stringifyPrimitive(issue.values[0])}`;\n return `Option invalide : attendu l'une des valeurs suivantes ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"\u2264\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Trop grand : attendu que ${issue.origin ?? \"la valeur\"} ait ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n return `Trop grand : attendu que ${issue.origin ?? \"la valeur\"} soit ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"\u2265\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Trop petit : attendu que ${issue.origin} ait ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Trop petit : attendu que ${issue.origin} soit ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Cha\u00EEne invalide : doit commencer par \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Cha\u00EEne invalide : doit se terminer par \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Cha\u00EEne invalide : doit inclure \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Cha\u00EEne invalide : doit correspondre au motif ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} invalide`;\n }\n case \"not_multiple_of\":\n return `Nombre invalide : doit \u00EAtre un multiple de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Cl\u00E9${issue.keys.length > 1 ? \"s\" : \"\"} non reconnue${issue.keys.length > 1 ? \"s\" : \"\"} : ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Cl\u00E9 invalide dans ${issue.origin}`;\n case \"invalid_union\":\n return \"Entr\u00E9e invalide\";\n case \"invalid_element\":\n return `Valeur invalide dans ${issue.origin}`;\n default:\n return `Entr\u00E9e invalide`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n // Hebrew labels + grammatical gender\n const TypeNames = {\n string: { label: \"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA\", gender: \"f\" },\n number: { label: \"\u05DE\u05E1\u05E4\u05E8\", gender: \"m\" },\n boolean: { label: \"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9\", gender: \"m\" },\n bigint: { label: \"BigInt\", gender: \"m\" },\n date: { label: \"\u05EA\u05D0\u05E8\u05D9\u05DA\", gender: \"m\" },\n array: { label: \"\u05DE\u05E2\u05E8\u05DA\", gender: \"m\" },\n object: { label: \"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8\", gender: \"m\" },\n null: { label: \"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)\", gender: \"m\" },\n undefined: { label: \"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)\", gender: \"m\" },\n symbol: { label: \"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)\", gender: \"m\" },\n function: { label: \"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4\", gender: \"f\" },\n map: { label: \"\u05DE\u05E4\u05D4 (Map)\", gender: \"f\" },\n set: { label: \"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)\", gender: \"f\" },\n file: { label: \"\u05E7\u05D5\u05D1\u05E5\", gender: \"m\" },\n promise: { label: \"Promise\", gender: \"m\" },\n NaN: { label: \"NaN\", gender: \"m\" },\n unknown: { label: \"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2\", gender: \"m\" },\n value: { label: \"\u05E2\u05E8\u05DA\", gender: \"m\" },\n };\n // Sizing units for size-related messages + localized origin labels\n const Sizable = {\n string: { unit: \"\u05EA\u05D5\u05D5\u05D9\u05DD\", shortLabel: \"\u05E7\u05E6\u05E8\", longLabel: \"\u05D0\u05E8\u05D5\u05DA\" },\n file: { unit: \"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD\", shortLabel: \"\u05E7\u05D8\u05DF\", longLabel: \"\u05D2\u05D3\u05D5\u05DC\" },\n array: { unit: \"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD\", shortLabel: \"\u05E7\u05D8\u05DF\", longLabel: \"\u05D2\u05D3\u05D5\u05DC\" },\n set: { unit: \"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD\", shortLabel: \"\u05E7\u05D8\u05DF\", longLabel: \"\u05D2\u05D3\u05D5\u05DC\" },\n number: { unit: \"\", shortLabel: \"\u05E7\u05D8\u05DF\", longLabel: \"\u05D2\u05D3\u05D5\u05DC\" }, // no unit\n };\n // Helpers \u2014 labels, articles, and verbs\n const typeEntry = (t) => (t ? TypeNames[t] : undefined);\n const typeLabel = (t) => {\n const e = typeEntry(t);\n if (e)\n return e.label;\n // fallback: show raw string if unknown\n return t ?? TypeNames.unknown.label;\n };\n const withDefinite = (t) => `\u05D4${typeLabel(t)}`;\n const verbFor = (t) => {\n const e = typeEntry(t);\n const gender = e?.gender ?? \"m\";\n return gender === \"f\" ? \"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA\" : \"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA\";\n };\n const getSizing = (origin) => {\n if (!origin)\n return null;\n return Sizable[origin] ?? null;\n };\n const FormatDictionary = {\n regex: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n email: { label: \"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC\", gender: \"f\" },\n url: { label: \"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA\", gender: \"f\" },\n emoji: { label: \"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9\", gender: \"m\" },\n uuid: { label: \"UUID\", gender: \"m\" },\n nanoid: { label: \"nanoid\", gender: \"m\" },\n guid: { label: \"GUID\", gender: \"m\" },\n cuid: { label: \"cuid\", gender: \"m\" },\n cuid2: { label: \"cuid2\", gender: \"m\" },\n ulid: { label: \"ULID\", gender: \"m\" },\n xid: { label: \"XID\", gender: \"m\" },\n ksuid: { label: \"KSUID\", gender: \"m\" },\n datetime: { label: \"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO\", gender: \"m\" },\n date: { label: \"\u05EA\u05D0\u05E8\u05D9\u05DA ISO\", gender: \"m\" },\n time: { label: \"\u05D6\u05DE\u05DF ISO\", gender: \"m\" },\n duration: { label: \"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO\", gender: \"m\" },\n ipv4: { label: \"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4\", gender: \"f\" },\n ipv6: { label: \"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6\", gender: \"f\" },\n cidrv4: { label: \"\u05D8\u05D5\u05D5\u05D7 IPv4\", gender: \"m\" },\n cidrv6: { label: \"\u05D8\u05D5\u05D5\u05D7 IPv6\", gender: \"m\" },\n base64: { label: \"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64\", gender: \"f\" },\n base64url: { label: \"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA\", gender: \"f\" },\n json_string: { label: \"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON\", gender: \"f\" },\n e164: { label: \"\u05DE\u05E1\u05E4\u05E8 E.164\", gender: \"m\" },\n jwt: { label: \"JWT\", gender: \"m\" },\n ends_with: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n includes: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n lowercase: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n starts_with: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n uppercase: { label: \"\u05E7\u05DC\u05D8\", gender: \"m\" },\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n // Expected type: show without definite article for clearer Hebrew\n const expectedKey = issue.expected;\n const expected = TypeDictionary[expectedKey ?? \"\"] ?? typeLabel(expectedKey);\n // Received: show localized label if known, otherwise constructor/raw\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;\n }\n return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;\n }\n case \"invalid_value\": {\n if (issue.values.length === 1) {\n return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${util.stringifyPrimitive(issue.values[0])}`;\n }\n // Join values with proper Hebrew formatting\n const stringified = issue.values.map((v) => util.stringifyPrimitive(v));\n if (issue.values.length === 2) {\n return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`;\n }\n // For 3+ values: \"a\", \"b\" \u05D0\u05D5 \"c\"\n const lastValue = stringified[stringified.length - 1];\n const restValues = stringified.slice(0, -1).join(\", \");\n return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`;\n }\n case \"too_big\": {\n const sizing = getSizing(issue.origin);\n const subject = withDefinite(issue.origin ?? \"value\");\n if (issue.origin === \"string\") {\n // Special handling for strings - more natural Hebrew\n return `${sizing?.longLabel ?? \"\u05D0\u05E8\u05D5\u05DA\"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue.maximum.toString()} ${sizing?.unit ?? \"\"} ${issue.inclusive ? \"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA\" : \"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8\"}`.trim();\n }\n if (issue.origin === \"number\") {\n // Natural Hebrew for numbers\n const comparison = issue.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue.maximum}`;\n return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;\n }\n if (issue.origin === \"array\" || issue.origin === \"set\") {\n // Natural Hebrew for arrays and sets\n const verb = issue.origin === \"set\" ? \"\u05E6\u05E8\u05D9\u05DB\u05D4\" : \"\u05E6\u05E8\u05D9\u05DA\";\n const comparison = issue.inclusive\n ? `${issue.maximum} ${sizing?.unit ?? \"\"} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`\n : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue.maximum} ${sizing?.unit ?? \"\"}`;\n return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();\n }\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const be = verbFor(issue.origin ?? \"value\");\n if (sizing?.unit) {\n return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n }\n return `${sizing?.longLabel ?? \"\u05D2\u05D3\u05D5\u05DC\"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const sizing = getSizing(issue.origin);\n const subject = withDefinite(issue.origin ?? \"value\");\n if (issue.origin === \"string\") {\n // Special handling for strings - more natural Hebrew\n return `${sizing?.shortLabel ?? \"\u05E7\u05E6\u05E8\"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue.minimum.toString()} ${sizing?.unit ?? \"\"} ${issue.inclusive ? \"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8\" : \"\u05DC\u05E4\u05D7\u05D5\u05EA\"}`.trim();\n }\n if (issue.origin === \"number\") {\n // Natural Hebrew for numbers\n const comparison = issue.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue.minimum}`;\n return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;\n }\n if (issue.origin === \"array\" || issue.origin === \"set\") {\n // Natural Hebrew for arrays and sets\n const verb = issue.origin === \"set\" ? \"\u05E6\u05E8\u05D9\u05DB\u05D4\" : \"\u05E6\u05E8\u05D9\u05DA\";\n // Special case for singular (minimum === 1)\n if (issue.minimum === 1 && issue.inclusive) {\n const singularPhrase = issue.origin === \"set\" ? \"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3\" : \"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3\";\n return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`;\n }\n const comparison = issue.inclusive\n ? `${issue.minimum} ${sizing?.unit ?? \"\"} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`\n : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue.minimum} ${sizing?.unit ?? \"\"}`;\n return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();\n }\n const adj = issue.inclusive ? \">=\" : \">\";\n const be = verbFor(issue.origin ?? \"value\");\n if (sizing?.unit) {\n return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `${sizing?.shortLabel ?? \"\u05E7\u05D8\u05DF\"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n // These apply to strings \u2014 use feminine grammar + \u05D4\u05F3 \u05D4\u05D9\u05D3\u05D9\u05E2\u05D4\n if (_issue.format === \"starts_with\")\n return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;\n // Handle gender agreement for formats\n const nounEntry = FormatDictionary[_issue.format];\n const noun = nounEntry?.label ?? _issue.format;\n const gender = nounEntry?.gender ?? \"m\";\n const adjective = gender === \"f\" ? \"\u05EA\u05E7\u05D9\u05E0\u05D4\" : \"\u05EA\u05E7\u05D9\u05DF\";\n return `${noun} \u05DC\u05D0 ${adjective}`;\n }\n case \"not_multiple_of\":\n return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u05DE\u05E4\u05EA\u05D7${issue.keys.length > 1 ? \"\u05D5\u05EA\" : \"\"} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue.keys.length > 1 ? \"\u05D9\u05DD\" : \"\u05D4\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\": {\n return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`;\n }\n case \"invalid_union\":\n return \"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF\";\n case \"invalid_element\": {\n const place = withDefinite(issue.origin ?? \"array\");\n return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`;\n }\n default:\n return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"karakter\", verb: \"legyen\" },\n file: { unit: \"byte\", verb: \"legyen\" },\n array: { unit: \"elem\", verb: \"legyen\" },\n set: { unit: \"elem\", verb: \"legyen\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"bemenet\",\n email: \"email c\u00EDm\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO id\u0151b\u00E9lyeg\",\n date: \"ISO d\u00E1tum\",\n time: \"ISO id\u0151\",\n duration: \"ISO id\u0151intervallum\",\n ipv4: \"IPv4 c\u00EDm\",\n ipv6: \"IPv6 c\u00EDm\",\n cidrv4: \"IPv4 tartom\u00E1ny\",\n cidrv6: \"IPv6 tartom\u00E1ny\",\n base64: \"base64-k\u00F3dolt string\",\n base64url: \"base64url-k\u00F3dolt string\",\n json_string: \"JSON string\",\n e164: \"E.164 sz\u00E1m\",\n jwt: \"JWT\",\n template_literal: \"bemenet\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"sz\u00E1m\",\n array: \"t\u00F6mb\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u00C9rv\u00E9nytelen bemenet: a v\u00E1rt \u00E9rt\u00E9k instanceof ${issue.expected}, a kapott \u00E9rt\u00E9k ${received}`;\n }\n return `\u00C9rv\u00E9nytelen bemenet: a v\u00E1rt \u00E9rt\u00E9k ${expected}, a kapott \u00E9rt\u00E9k ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u00C9rv\u00E9nytelen bemenet: a v\u00E1rt \u00E9rt\u00E9k ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u00C9rv\u00E9nytelen opci\u00F3: valamelyik \u00E9rt\u00E9k v\u00E1rt ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `T\u00FAl nagy: ${issue.origin ?? \"\u00E9rt\u00E9k\"} m\u00E9rete t\u00FAl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elem\"}`;\n return `T\u00FAl nagy: a bemeneti \u00E9rt\u00E9k ${issue.origin ?? \"\u00E9rt\u00E9k\"} t\u00FAl nagy: ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `T\u00FAl kicsi: a bemeneti \u00E9rt\u00E9k ${issue.origin} m\u00E9rete t\u00FAl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `T\u00FAl kicsi: a bemeneti \u00E9rt\u00E9k ${issue.origin} t\u00FAl kicsi ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u00C9rv\u00E9nytelen string: \"${_issue.prefix}\" \u00E9rt\u00E9kkel kell kezd\u0151dnie`;\n if (_issue.format === \"ends_with\")\n return `\u00C9rv\u00E9nytelen string: \"${_issue.suffix}\" \u00E9rt\u00E9kkel kell v\u00E9gz\u0151dnie`;\n if (_issue.format === \"includes\")\n return `\u00C9rv\u00E9nytelen string: \"${_issue.includes}\" \u00E9rt\u00E9ket kell tartalmaznia`;\n if (_issue.format === \"regex\")\n return `\u00C9rv\u00E9nytelen string: ${_issue.pattern} mint\u00E1nak kell megfelelnie`;\n return `\u00C9rv\u00E9nytelen ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u00C9rv\u00E9nytelen sz\u00E1m: ${issue.divisor} t\u00F6bbsz\u00F6r\u00F6s\u00E9nek kell lennie`;\n case \"unrecognized_keys\":\n return `Ismeretlen kulcs${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u00C9rv\u00E9nytelen kulcs ${issue.origin}`;\n case \"invalid_union\":\n return \"\u00C9rv\u00E9nytelen bemenet\";\n case \"invalid_element\":\n return `\u00C9rv\u00E9nytelen \u00E9rt\u00E9k: ${issue.origin}`;\n default:\n return `\u00C9rv\u00E9nytelen bemenet`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nfunction getArmenianPlural(count, one, many) {\n return Math.abs(count) === 1 ? one : many;\n}\nfunction withDefiniteArticle(word) {\n if (!word)\n return \"\";\n const vowels = [\"\u0561\", \"\u0565\", \"\u0568\", \"\u056B\", \"\u0578\", \"\u0578\u0582\", \"\u0585\"];\n const lastChar = word[word.length - 1];\n return word + (vowels.includes(lastChar) ? \"\u0576\" : \"\u0568\");\n}\nconst error = () => {\n const Sizable = {\n string: {\n unit: {\n one: \"\u0576\u0577\u0561\u0576\",\n many: \"\u0576\u0577\u0561\u0576\u0576\u0565\u0580\",\n },\n verb: \"\u0578\u0582\u0576\u0565\u0576\u0561\u056C\",\n },\n file: {\n unit: {\n one: \"\u0562\u0561\u0575\u0569\",\n many: \"\u0562\u0561\u0575\u0569\u0565\u0580\",\n },\n verb: \"\u0578\u0582\u0576\u0565\u0576\u0561\u056C\",\n },\n array: {\n unit: {\n one: \"\u057F\u0561\u0580\u0580\",\n many: \"\u057F\u0561\u0580\u0580\u0565\u0580\",\n },\n verb: \"\u0578\u0582\u0576\u0565\u0576\u0561\u056C\",\n },\n set: {\n unit: {\n one: \"\u057F\u0561\u0580\u0580\",\n many: \"\u057F\u0561\u0580\u0580\u0565\u0580\",\n },\n verb: \"\u0578\u0582\u0576\u0565\u0576\u0561\u056C\",\n },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0574\u0578\u0582\u057F\u0584\",\n email: \"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565\",\n url: \"URL\",\n emoji: \"\u0567\u0574\u0578\u057B\u056B\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574\",\n date: \"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E\",\n time: \"ISO \u056A\u0561\u0574\",\n duration: \"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576\",\n ipv4: \"IPv4 \u0570\u0561\u057D\u0581\u0565\",\n ipv6: \"IPv6 \u0570\u0561\u057D\u0581\u0565\",\n cidrv4: \"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584\",\n cidrv6: \"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584\",\n base64: \"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572\",\n base64url: \"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572\",\n json_string: \"JSON \u057F\u0578\u0572\",\n e164: \"E.164 \u0570\u0561\u0574\u0561\u0580\",\n jwt: \"JWT\",\n template_literal: \"\u0574\u0578\u0582\u057F\u0584\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0569\u056B\u057E\",\n array: \"\u0566\u0561\u0576\u0563\u057E\u0561\u056E\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;\n }\n return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${util.stringifyPrimitive(issue.values[1])}`;\n return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const maxValue = Number(issue.maximum);\n const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);\n return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue.origin ?? \"\u0561\u0580\u056A\u0565\u0584\")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue.maximum.toString()} ${unit}`;\n }\n return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue.origin ?? \"\u0561\u0580\u056A\u0565\u0584\")} \u056C\u056B\u0576\u056B ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const minValue = Number(issue.minimum);\n const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);\n return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue.minimum.toString()} ${unit}`;\n }\n return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue.origin)} \u056C\u056B\u0576\u056B ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B \"${_issue.prefix}\"-\u0578\u057E`;\n if (_issue.format === \"ends_with\")\n return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B \"${_issue.suffix}\"-\u0578\u057E`;\n if (_issue.format === \"includes\")\n return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;\n return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue.divisor}-\u056B`;\n case \"unrecognized_keys\":\n return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue.keys.length > 1 ? \"\u0576\u0565\u0580\" : \"\"}. ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue.origin)}-\u0578\u0582\u0574`;\n case \"invalid_union\":\n return \"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\";\n case \"invalid_element\":\n return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue.origin)}-\u0578\u0582\u0574`;\n default:\n return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"karakter\", verb: \"memiliki\" },\n file: { unit: \"byte\", verb: \"memiliki\" },\n array: { unit: \"item\", verb: \"memiliki\" },\n set: { unit: \"item\", verb: \"memiliki\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"alamat email\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"tanggal dan waktu format ISO\",\n date: \"tanggal format ISO\",\n time: \"jam format ISO\",\n duration: \"durasi format ISO\",\n ipv4: \"alamat IPv4\",\n ipv6: \"alamat IPv6\",\n cidrv4: \"rentang alamat IPv4\",\n cidrv6: \"rentang alamat IPv6\",\n base64: \"string dengan enkode base64\",\n base64url: \"string dengan enkode base64url\",\n json_string: \"string JSON\",\n e164: \"angka E.164\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Input tidak valid: diharapkan instanceof ${issue.expected}, diterima ${received}`;\n }\n return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Input tidak valid: diharapkan ${util.stringifyPrimitive(issue.values[0])}`;\n return `Pilihan tidak valid: diharapkan salah satu dari ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Terlalu besar: diharapkan ${issue.origin ?? \"value\"} memiliki ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elemen\"}`;\n return `Terlalu besar: diharapkan ${issue.origin ?? \"value\"} menjadi ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Terlalu kecil: diharapkan ${issue.origin} memiliki ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Terlalu kecil: diharapkan ${issue.origin} menjadi ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `String tidak valid: harus dimulai dengan \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `String tidak valid: harus berakhir dengan \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `String tidak valid: harus menyertakan \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `String tidak valid: harus sesuai pola ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} tidak valid`;\n }\n case \"not_multiple_of\":\n return `Angka tidak valid: harus kelipatan dari ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Kunci tidak dikenali ${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Kunci tidak valid di ${issue.origin}`;\n case \"invalid_union\":\n return \"Input tidak valid\";\n case \"invalid_element\":\n return `Nilai tidak valid di ${issue.origin}`;\n default:\n return `Input tidak valid`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"stafi\", verb: \"a\u00F0 hafa\" },\n file: { unit: \"b\u00E6ti\", verb: \"a\u00F0 hafa\" },\n array: { unit: \"hluti\", verb: \"a\u00F0 hafa\" },\n set: { unit: \"hluti\", verb: \"a\u00F0 hafa\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"gildi\",\n email: \"netfang\",\n url: \"vefsl\u00F3\u00F0\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO dagsetning og t\u00EDmi\",\n date: \"ISO dagsetning\",\n time: \"ISO t\u00EDmi\",\n duration: \"ISO t\u00EDmalengd\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded strengur\",\n base64url: \"base64url-encoded strengur\",\n json_string: \"JSON strengur\",\n e164: \"E.164 t\u00F6lugildi\",\n jwt: \"JWT\",\n template_literal: \"gildi\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"n\u00FAmer\",\n array: \"fylki\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Rangt gildi: \u00DE\u00FA sl\u00F3st inn ${received} \u00FEar sem \u00E1 a\u00F0 vera instanceof ${issue.expected}`;\n }\n return `Rangt gildi: \u00DE\u00FA sl\u00F3st inn ${received} \u00FEar sem \u00E1 a\u00F0 vera ${expected}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Rangt gildi: gert r\u00E1\u00F0 fyrir ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u00D3gilt val: m\u00E1 vera eitt af eftirfarandi ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Of st\u00F3rt: gert er r\u00E1\u00F0 fyrir a\u00F0 ${issue.origin ?? \"gildi\"} hafi ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"hluti\"}`;\n return `Of st\u00F3rt: gert er r\u00E1\u00F0 fyrir a\u00F0 ${issue.origin ?? \"gildi\"} s\u00E9 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Of l\u00EDti\u00F0: gert er r\u00E1\u00F0 fyrir a\u00F0 ${issue.origin} hafi ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Of l\u00EDti\u00F0: gert er r\u00E1\u00F0 fyrir a\u00F0 ${issue.origin} s\u00E9 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u00D3gildur strengur: ver\u00F0ur a\u00F0 byrja \u00E1 \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u00D3gildur strengur: ver\u00F0ur a\u00F0 enda \u00E1 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u00D3gildur strengur: ver\u00F0ur a\u00F0 innihalda \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u00D3gildur strengur: ver\u00F0ur a\u00F0 fylgja mynstri ${_issue.pattern}`;\n return `Rangt ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `R\u00F6ng tala: ver\u00F0ur a\u00F0 vera margfeldi af ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u00D3\u00FEekkt ${issue.keys.length > 1 ? \"ir lyklar\" : \"ur lykill\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Rangur lykill \u00ED ${issue.origin}`;\n case \"invalid_union\":\n return \"Rangt gildi\";\n case \"invalid_element\":\n return `Rangt gildi \u00ED ${issue.origin}`;\n default:\n return `Rangt gildi`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caratteri\", verb: \"avere\" },\n file: { unit: \"byte\", verb: \"avere\" },\n array: { unit: \"elementi\", verb: \"avere\" },\n set: { unit: \"elementi\", verb: \"avere\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"indirizzo email\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"data e ora ISO\",\n date: \"data ISO\",\n time: \"ora ISO\",\n duration: \"durata ISO\",\n ipv4: \"indirizzo IPv4\",\n ipv6: \"indirizzo IPv6\",\n cidrv4: \"intervallo IPv4\",\n cidrv6: \"intervallo IPv6\",\n base64: \"stringa codificata in base64\",\n base64url: \"URL codificata in base64\",\n json_string: \"stringa JSON\",\n e164: \"numero E.164\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"numero\",\n array: \"vettore\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Input non valido: atteso instanceof ${issue.expected}, ricevuto ${received}`;\n }\n return `Input non valido: atteso ${expected}, ricevuto ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`;\n return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Troppo grande: ${issue.origin ?? \"valore\"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementi\"}`;\n return `Troppo grande: ${issue.origin ?? \"valore\"} deve essere ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Stringa non valida: deve iniziare con \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Stringa non valida: deve terminare con \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Stringa non valida: deve includere \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Chiav${issue.keys.length > 1 ? \"i\" : \"e\"} non riconosciut${issue.keys.length > 1 ? \"e\" : \"a\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Chiave non valida in ${issue.origin}`;\n case \"invalid_union\":\n return \"Input non valido\";\n case \"invalid_element\":\n return `Valore non valido in ${issue.origin}`;\n default:\n return `Input non valido`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u6587\u5B57\", verb: \"\u3067\u3042\u308B\" },\n file: { unit: \"\u30D0\u30A4\u30C8\", verb: \"\u3067\u3042\u308B\" },\n array: { unit: \"\u8981\u7D20\", verb: \"\u3067\u3042\u308B\" },\n set: { unit: \"\u8981\u7D20\", verb: \"\u3067\u3042\u308B\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u5165\u529B\u5024\",\n email: \"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9\",\n url: \"URL\",\n emoji: \"\u7D75\u6587\u5B57\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO\u65E5\u6642\",\n date: \"ISO\u65E5\u4ED8\",\n time: \"ISO\u6642\u523B\",\n duration: \"ISO\u671F\u9593\",\n ipv4: \"IPv4\u30A2\u30C9\u30EC\u30B9\",\n ipv6: \"IPv6\u30A2\u30C9\u30EC\u30B9\",\n cidrv4: \"IPv4\u7BC4\u56F2\",\n cidrv6: \"IPv6\u7BC4\u56F2\",\n base64: \"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217\",\n base64url: \"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217\",\n json_string: \"JSON\u6587\u5B57\u5217\",\n e164: \"E.164\u756A\u53F7\",\n jwt: \"JWT\",\n template_literal: \"\u5165\u529B\u5024\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u6570\u5024\",\n array: \"\u914D\u5217\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;\n }\n return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u7121\u52B9\u306A\u5165\u529B: ${util.stringifyPrimitive(issue.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;\n return `\u7121\u52B9\u306A\u9078\u629E: ${util.joinValues(issue.values, \"\u3001\")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"\u4EE5\u4E0B\u3067\u3042\u308B\" : \"\u3088\u308A\u5C0F\u3055\u3044\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue.origin ?? \"\u5024\"}\u306F${issue.maximum.toString()}${sizing.unit ?? \"\u8981\u7D20\"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue.origin ?? \"\u5024\"}\u306F${issue.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"\u4EE5\u4E0A\u3067\u3042\u308B\" : \"\u3088\u308A\u5927\u304D\u3044\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue.origin}\u306F${issue.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue.origin}\u306F${issue.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \"${_issue.prefix}\"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n if (_issue.format === \"ends_with\")\n return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \"${_issue.suffix}\"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n if (_issue.format === \"includes\")\n return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \"${_issue.includes}\"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n if (_issue.format === \"regex\")\n return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u7121\u52B9\u306A\u6570\u5024: ${issue.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;\n case \"unrecognized_keys\":\n return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue.keys.length > 1 ? \"\u7FA4\" : \"\"}: ${util.joinValues(issue.keys, \"\u3001\")}`;\n case \"invalid_key\":\n return `${issue.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;\n case \"invalid_union\":\n return \"\u7121\u52B9\u306A\u5165\u529B\";\n case \"invalid_element\":\n return `${issue.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;\n default:\n return `\u7121\u52B9\u306A\u5165\u529B`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD\", verb: \"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1\" },\n file: { unit: \"\u10D1\u10D0\u10D8\u10E2\u10D8\", verb: \"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1\" },\n array: { unit: \"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8\", verb: \"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1\" },\n set: { unit: \"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8\", verb: \"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0\",\n email: \"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8\",\n url: \"URL\",\n emoji: \"\u10D4\u10DB\u10DD\u10EF\u10D8\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD\",\n date: \"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8\",\n time: \"\u10D3\u10E0\u10DD\",\n duration: \"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0\",\n ipv4: \"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8\",\n ipv6: \"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8\",\n cidrv4: \"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8\",\n cidrv6: \"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8\",\n base64: \"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8\",\n base64url: \"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8\",\n json_string: \"JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8\",\n e164: \"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8\",\n jwt: \"JWT\",\n template_literal: \"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8\",\n string: \"\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8\",\n boolean: \"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8\",\n function: \"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0\",\n array: \"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;\n }\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${util.joinValues(issue.values, \"|\")}-\u10D3\u10D0\u10DC`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue.origin ?? \"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue.origin ?? \"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0\"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \"${_issue.prefix}\"-\u10D8\u10D7`;\n }\n if (_issue.format === \"ends_with\")\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \"${_issue.suffix}\"-\u10D8\u10D7`;\n if (_issue.format === \"includes\")\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 \"${_issue.includes}\"-\u10E1`;\n if (_issue.format === \"regex\")\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`;\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;\n case \"unrecognized_keys\":\n return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue.keys.length > 1 ? \"\u10D4\u10D1\u10D8\" : \"\u10D8\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue.origin}-\u10E8\u10D8`;\n case \"invalid_union\":\n return \"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0\";\n case \"invalid_element\":\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue.origin}-\u10E8\u10D8`;\n default:\n return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A\", verb: \"\u1782\u17BD\u179A\u1798\u17B6\u1793\" },\n file: { unit: \"\u1794\u17C3\", verb: \"\u1782\u17BD\u179A\u1798\u17B6\u1793\" },\n array: { unit: \"\u1792\u17B6\u178F\u17BB\", verb: \"\u1782\u17BD\u179A\u1798\u17B6\u1793\" },\n set: { unit: \"\u1792\u17B6\u178F\u17BB\", verb: \"\u1782\u17BD\u179A\u1798\u17B6\u1793\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\",\n email: \"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B\",\n url: \"URL\",\n emoji: \"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO\",\n date: \"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO\",\n time: \"\u1798\u17C9\u17C4\u1784 ISO\",\n duration: \"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO\",\n ipv4: \"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4\",\n ipv6: \"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6\",\n cidrv4: \"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4\",\n cidrv6: \"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6\",\n base64: \"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64\",\n base64url: \"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url\",\n json_string: \"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON\",\n e164: \"\u179B\u17C1\u1781 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u179B\u17C1\u1781\",\n array: \"\u17A2\u17B6\u179A\u17C1 (Array)\",\n null: \"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;\n }\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue.origin ?? \"\u178F\u1798\u17D2\u179B\u17C3\"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"\u1792\u17B6\u178F\u17BB\"}`;\n return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue.origin ?? \"\u178F\u1798\u17D2\u179B\u17C3\"} ${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue.origin} ${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;\n return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue.origin}`;\n case \"invalid_union\":\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;\n case \"invalid_element\":\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue.origin}`;\n default:\n return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import km from \"./km.js\";\n/** @deprecated Use `km` instead. */\nexport default function () {\n return km();\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\uBB38\uC790\", verb: \"to have\" },\n file: { unit: \"\uBC14\uC774\uD2B8\", verb: \"to have\" },\n array: { unit: \"\uAC1C\", verb: \"to have\" },\n set: { unit: \"\uAC1C\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\uC785\uB825\",\n email: \"\uC774\uBA54\uC77C \uC8FC\uC18C\",\n url: \"URL\",\n emoji: \"\uC774\uBAA8\uC9C0\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \uB0A0\uC9DC\uC2DC\uAC04\",\n date: \"ISO \uB0A0\uC9DC\",\n time: \"ISO \uC2DC\uAC04\",\n duration: \"ISO \uAE30\uAC04\",\n ipv4: \"IPv4 \uC8FC\uC18C\",\n ipv6: \"IPv6 \uC8FC\uC18C\",\n cidrv4: \"IPv4 \uBC94\uC704\",\n cidrv6: \"IPv6 \uBC94\uC704\",\n base64: \"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4\",\n base64url: \"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4\",\n json_string: \"JSON \uBB38\uC790\uC5F4\",\n e164: \"E.164 \uBC88\uD638\",\n jwt: \"JWT\",\n template_literal: \"\uC785\uB825\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;\n }\n return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${util.stringifyPrimitive(issue.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;\n return `\uC798\uBABB\uB41C \uC635\uC158: ${util.joinValues(issue.values, \"\uB610\uB294 \")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"\uC774\uD558\" : \"\uBBF8\uB9CC\";\n const suffix = adj === \"\uBBF8\uB9CC\" ? \"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4\" : \"\uC5EC\uC57C \uD569\uB2C8\uB2E4\";\n const sizing = getSizing(issue.origin);\n const unit = sizing?.unit ?? \"\uC694\uC18C\";\n if (sizing)\n return `${issue.origin ?? \"\uAC12\"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue.maximum.toString()}${unit} ${adj}${suffix}`;\n return `${issue.origin ?? \"\uAC12\"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue.maximum.toString()} ${adj}${suffix}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"\uC774\uC0C1\" : \"\uCD08\uACFC\";\n const suffix = adj === \"\uC774\uC0C1\" ? \"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4\" : \"\uC5EC\uC57C \uD569\uB2C8\uB2E4\";\n const sizing = getSizing(issue.origin);\n const unit = sizing?.unit ?? \"\uC694\uC18C\";\n if (sizing) {\n return `${issue.origin ?? \"\uAC12\"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue.minimum.toString()}${unit} ${adj}${suffix}`;\n }\n return `${issue.origin ?? \"\uAC12\"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue.minimum.toString()} ${adj}${suffix}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \"${_issue.prefix}\"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;\n }\n if (_issue.format === \"ends_with\")\n return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \"${_issue.suffix}\"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;\n if (_issue.format === \"includes\")\n return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \"${_issue.includes}\"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;\n if (_issue.format === \"regex\")\n return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;\n return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;\n case \"unrecognized_keys\":\n return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\uC798\uBABB\uB41C \uD0A4: ${issue.origin}`;\n case \"invalid_union\":\n return `\uC798\uBABB\uB41C \uC785\uB825`;\n case \"invalid_element\":\n return `\uC798\uBABB\uB41C \uAC12: ${issue.origin}`;\n default:\n return `\uC798\uBABB\uB41C \uC785\uB825`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst capitalizeFirstCharacter = (text) => {\n return text.charAt(0).toUpperCase() + text.slice(1);\n};\nfunction getUnitTypeFromNumber(number) {\n const abs = Math.abs(number);\n const last = abs % 10;\n const last2 = abs % 100;\n if ((last2 >= 11 && last2 <= 19) || last === 0)\n return \"many\";\n if (last === 1)\n return \"one\";\n return \"few\";\n}\nconst error = () => {\n const Sizable = {\n string: {\n unit: {\n one: \"simbolis\",\n few: \"simboliai\",\n many: \"simboli\u0173\",\n },\n verb: {\n smaller: {\n inclusive: \"turi b\u016Bti ne ilgesn\u0117 kaip\",\n notInclusive: \"turi b\u016Bti trumpesn\u0117 kaip\",\n },\n bigger: {\n inclusive: \"turi b\u016Bti ne trumpesn\u0117 kaip\",\n notInclusive: \"turi b\u016Bti ilgesn\u0117 kaip\",\n },\n },\n },\n file: {\n unit: {\n one: \"baitas\",\n few: \"baitai\",\n many: \"bait\u0173\",\n },\n verb: {\n smaller: {\n inclusive: \"turi b\u016Bti ne didesnis kaip\",\n notInclusive: \"turi b\u016Bti ma\u017Eesnis kaip\",\n },\n bigger: {\n inclusive: \"turi b\u016Bti ne ma\u017Eesnis kaip\",\n notInclusive: \"turi b\u016Bti didesnis kaip\",\n },\n },\n },\n array: {\n unit: {\n one: \"element\u0105\",\n few: \"elementus\",\n many: \"element\u0173\",\n },\n verb: {\n smaller: {\n inclusive: \"turi tur\u0117ti ne daugiau kaip\",\n notInclusive: \"turi tur\u0117ti ma\u017Eiau kaip\",\n },\n bigger: {\n inclusive: \"turi tur\u0117ti ne ma\u017Eiau kaip\",\n notInclusive: \"turi tur\u0117ti daugiau kaip\",\n },\n },\n },\n set: {\n unit: {\n one: \"element\u0105\",\n few: \"elementus\",\n many: \"element\u0173\",\n },\n verb: {\n smaller: {\n inclusive: \"turi tur\u0117ti ne daugiau kaip\",\n notInclusive: \"turi tur\u0117ti ma\u017Eiau kaip\",\n },\n bigger: {\n inclusive: \"turi tur\u0117ti ne ma\u017Eiau kaip\",\n notInclusive: \"turi tur\u0117ti daugiau kaip\",\n },\n },\n },\n };\n function getSizing(origin, unitType, inclusive, targetShouldBe) {\n const result = Sizable[origin] ?? null;\n if (result === null)\n return result;\n return {\n unit: result.unit[unitType],\n verb: result.verb[targetShouldBe][inclusive ? \"inclusive\" : \"notInclusive\"],\n };\n }\n const FormatDictionary = {\n regex: \"\u012Fvestis\",\n email: \"el. pa\u0161to adresas\",\n url: \"URL\",\n emoji: \"jaustukas\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO data ir laikas\",\n date: \"ISO data\",\n time: \"ISO laikas\",\n duration: \"ISO trukm\u0117\",\n ipv4: \"IPv4 adresas\",\n ipv6: \"IPv6 adresas\",\n cidrv4: \"IPv4 tinklo prefiksas (CIDR)\",\n cidrv6: \"IPv6 tinklo prefiksas (CIDR)\",\n base64: \"base64 u\u017Ekoduota eilut\u0117\",\n base64url: \"base64url u\u017Ekoduota eilut\u0117\",\n json_string: \"JSON eilut\u0117\",\n e164: \"E.164 numeris\",\n jwt: \"JWT\",\n template_literal: \"\u012Fvestis\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"skai\u010Dius\",\n bigint: \"sveikasis skai\u010Dius\",\n string: \"eilut\u0117\",\n boolean: \"login\u0117 reik\u0161m\u0117\",\n undefined: \"neapibr\u0117\u017Eta reik\u0161m\u0117\",\n function: \"funkcija\",\n symbol: \"simbolis\",\n array: \"masyvas\",\n object: \"objektas\",\n null: \"nulin\u0117 reik\u0161m\u0117\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue.expected}`;\n }\n return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Privalo b\u016Bti ${util.stringifyPrimitive(issue.values[0])}`;\n return `Privalo b\u016Bti vienas i\u0161 ${util.joinValues(issue.values, \"|\")} pasirinkim\u0173`;\n case \"too_big\": {\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.maximum)), issue.inclusive ?? false, \"smaller\");\n if (sizing?.verb)\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} ${sizing.verb} ${issue.maximum.toString()} ${sizing.unit ?? \"element\u0173\"}`;\n const adj = issue.inclusive ? \"ne didesnis kaip\" : \"ma\u017Eesnis kaip\";\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} turi b\u016Bti ${adj} ${issue.maximum.toString()} ${sizing?.unit}`;\n }\n case \"too_small\": {\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.minimum)), issue.inclusive ?? false, \"bigger\");\n if (sizing?.verb)\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} ${sizing.verb} ${issue.minimum.toString()} ${sizing.unit ?? \"element\u0173\"}`;\n const adj = issue.inclusive ? \"ne ma\u017Eesnis kaip\" : \"didesnis kaip\";\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} turi b\u016Bti ${adj} ${issue.minimum.toString()} ${sizing?.unit}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Eilut\u0117 privalo prasid\u0117ti \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Eilut\u0117 privalo pasibaigti \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Eilut\u0117 privalo \u012Ftraukti \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Eilut\u0117 privalo atitikti ${_issue.pattern}`;\n return `Neteisingas ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Skai\u010Dius privalo b\u016Bti ${issue.divisor} kartotinis.`;\n case \"unrecognized_keys\":\n return `Neatpa\u017Eint${issue.keys.length > 1 ? \"i\" : \"as\"} rakt${issue.keys.length > 1 ? \"ai\" : \"as\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return \"Rastas klaidingas raktas\";\n case \"invalid_union\":\n return \"Klaidinga \u012Fvestis\";\n case \"invalid_element\": {\n const origin = TypeDictionary[issue.origin] ?? issue.origin;\n return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reik\u0161m\u0117\")} turi klaiding\u0105 \u012Fvest\u012F`;\n }\n default:\n return \"Klaidinga \u012Fvestis\";\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0437\u043D\u0430\u0446\u0438\", verb: \"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442\" },\n file: { unit: \"\u0431\u0430\u0458\u0442\u0438\", verb: \"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442\" },\n array: { unit: \"\u0441\u0442\u0430\u0432\u043A\u0438\", verb: \"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442\" },\n set: { unit: \"\u0441\u0442\u0430\u0432\u043A\u0438\", verb: \"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0432\u043D\u0435\u0441\",\n email: \"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430\",\n url: \"URL\",\n emoji: \"\u0435\u043C\u043E\u045F\u0438\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435\",\n date: \"ISO \u0434\u0430\u0442\u0443\u043C\",\n time: \"ISO \u0432\u0440\u0435\u043C\u0435\",\n duration: \"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435\",\n ipv4: \"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430\",\n ipv6: \"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430\",\n cidrv4: \"IPv4 \u043E\u043F\u0441\u0435\u0433\",\n cidrv6: \"IPv6 \u043E\u043F\u0441\u0435\u0433\",\n base64: \"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430\",\n base64url: \"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430\",\n json_string: \"JSON \u043D\u0438\u0437\u0430\",\n e164: \"E.164 \u0431\u0440\u043E\u0458\",\n jwt: \"JWT\",\n template_literal: \"\u0432\u043D\u0435\u0441\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0431\u0440\u043E\u0458\",\n array: \"\u043D\u0438\u0437\u0430\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;\n }\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue.origin ?? \"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430\"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438\"}`;\n return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue.origin ?? \"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430\"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438\" : \"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue.origin}`;\n case \"invalid_union\":\n return \"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441\";\n case \"invalid_element\":\n return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue.origin}`;\n default:\n return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"aksara\", verb: \"mempunyai\" },\n file: { unit: \"bait\", verb: \"mempunyai\" },\n array: { unit: \"elemen\", verb: \"mempunyai\" },\n set: { unit: \"elemen\", verb: \"mempunyai\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"alamat e-mel\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"tarikh masa ISO\",\n date: \"tarikh ISO\",\n time: \"masa ISO\",\n duration: \"tempoh ISO\",\n ipv4: \"alamat IPv4\",\n ipv6: \"alamat IPv6\",\n cidrv4: \"julat IPv4\",\n cidrv6: \"julat IPv6\",\n base64: \"string dikodkan base64\",\n base64url: \"string dikodkan base64url\",\n json_string: \"string JSON\",\n e164: \"nombor E.164\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"nombor\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Input tidak sah: dijangka instanceof ${issue.expected}, diterima ${received}`;\n }\n return `Input tidak sah: dijangka ${expected}, diterima ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Input tidak sah: dijangka ${util.stringifyPrimitive(issue.values[0])}`;\n return `Pilihan tidak sah: dijangka salah satu daripada ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Terlalu besar: dijangka ${issue.origin ?? \"nilai\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elemen\"}`;\n return `Terlalu besar: dijangka ${issue.origin ?? \"nilai\"} adalah ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `String tidak sah: mesti bermula dengan \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `String tidak sah: mesti berakhir dengan \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `String tidak sah: mesti mengandungi \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} tidak sah`;\n }\n case \"not_multiple_of\":\n return `Nombor tidak sah: perlu gandaan ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Kunci tidak dikenali: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Kunci tidak sah dalam ${issue.origin}`;\n case \"invalid_union\":\n return \"Input tidak sah\";\n case \"invalid_element\":\n return `Nilai tidak sah dalam ${issue.origin}`;\n default:\n return `Input tidak sah`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"tekens\", verb: \"heeft\" },\n file: { unit: \"bytes\", verb: \"heeft\" },\n array: { unit: \"elementen\", verb: \"heeft\" },\n set: { unit: \"elementen\", verb: \"heeft\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"invoer\",\n email: \"emailadres\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datum en tijd\",\n date: \"ISO datum\",\n time: \"ISO tijd\",\n duration: \"ISO duur\",\n ipv4: \"IPv4-adres\",\n ipv6: \"IPv6-adres\",\n cidrv4: \"IPv4-bereik\",\n cidrv6: \"IPv6-bereik\",\n base64: \"base64-gecodeerde tekst\",\n base64url: \"base64 URL-gecodeerde tekst\",\n json_string: \"JSON string\",\n e164: \"E.164-nummer\",\n jwt: \"JWT\",\n template_literal: \"invoer\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"getal\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ongeldige invoer: verwacht instanceof ${issue.expected}, ontving ${received}`;\n }\n return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ongeldige invoer: verwacht ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ongeldige optie: verwacht \u00E9\u00E9n van ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n const longName = issue.origin === \"date\" ? \"laat\" : issue.origin === \"string\" ? \"lang\" : \"groot\";\n if (sizing)\n return `Te ${longName}: verwacht dat ${issue.origin ?? \"waarde\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementen\"} ${sizing.verb}`;\n return `Te ${longName}: verwacht dat ${issue.origin ?? \"waarde\"} ${adj}${issue.maximum.toString()} is`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n const shortName = issue.origin === \"date\" ? \"vroeg\" : issue.origin === \"string\" ? \"kort\" : \"klein\";\n if (sizing) {\n return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;\n }\n return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Ongeldige tekst: moet met \"${_issue.prefix}\" beginnen`;\n }\n if (_issue.format === \"ends_with\")\n return `Ongeldige tekst: moet op \"${_issue.suffix}\" eindigen`;\n if (_issue.format === \"includes\")\n return `Ongeldige tekst: moet \"${_issue.includes}\" bevatten`;\n if (_issue.format === \"regex\")\n return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;\n return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`;\n case \"unrecognized_keys\":\n return `Onbekende key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ongeldige key in ${issue.origin}`;\n case \"invalid_union\":\n return \"Ongeldige invoer\";\n case \"invalid_element\":\n return `Ongeldige waarde in ${issue.origin}`;\n default:\n return `Ongeldige invoer`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"tegn\", verb: \"\u00E5 ha\" },\n file: { unit: \"bytes\", verb: \"\u00E5 ha\" },\n array: { unit: \"elementer\", verb: \"\u00E5 inneholde\" },\n set: { unit: \"elementer\", verb: \"\u00E5 inneholde\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"e-postadresse\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO dato- og klokkeslett\",\n date: \"ISO-dato\",\n time: \"ISO-klokkeslett\",\n duration: \"ISO-varighet\",\n ipv4: \"IPv4-omr\u00E5de\",\n ipv6: \"IPv6-omr\u00E5de\",\n cidrv4: \"IPv4-spekter\",\n cidrv6: \"IPv6-spekter\",\n base64: \"base64-enkodet streng\",\n base64url: \"base64url-enkodet streng\",\n json_string: \"JSON-streng\",\n e164: \"E.164-nummer\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"tall\",\n array: \"liste\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ugyldig input: forventet instanceof ${issue.expected}, fikk ${received}`;\n }\n return `Ugyldig input: forventet ${expected}, fikk ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ugyldig verdi: forventet ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ugyldig valg: forventet en av ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `For stor(t): forventet ${issue.origin ?? \"value\"} til \u00E5 ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementer\"}`;\n return `For stor(t): forventet ${issue.origin ?? \"value\"} til \u00E5 ha ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `For lite(n): forventet ${issue.origin} til \u00E5 ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `For lite(n): forventet ${issue.origin} til \u00E5 ha ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Ugyldig streng: m\u00E5 starte med \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Ugyldig streng: m\u00E5 ende med \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Ugyldig streng: m\u00E5 inneholde \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Ugyldig streng: m\u00E5 matche m\u00F8nsteret ${_issue.pattern}`;\n return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ugyldig tall: m\u00E5 v\u00E6re et multiplum av ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Ukjente n\u00F8kler\" : \"Ukjent n\u00F8kkel\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ugyldig n\u00F8kkel i ${issue.origin}`;\n case \"invalid_union\":\n return \"Ugyldig input\";\n case \"invalid_element\":\n return `Ugyldig verdi i ${issue.origin}`;\n default:\n return `Ugyldig input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"harf\", verb: \"olmal\u0131d\u0131r\" },\n file: { unit: \"bayt\", verb: \"olmal\u0131d\u0131r\" },\n array: { unit: \"unsur\", verb: \"olmal\u0131d\u0131r\" },\n set: { unit: \"unsur\", verb: \"olmal\u0131d\u0131r\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"giren\",\n email: \"epostag\u00E2h\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO heng\u00E2m\u0131\",\n date: \"ISO tarihi\",\n time: \"ISO zaman\u0131\",\n duration: \"ISO m\u00FCddeti\",\n ipv4: \"IPv4 ni\u015F\u00E2n\u0131\",\n ipv6: \"IPv6 ni\u015F\u00E2n\u0131\",\n cidrv4: \"IPv4 menzili\",\n cidrv6: \"IPv6 menzili\",\n base64: \"base64-\u015Fifreli metin\",\n base64url: \"base64url-\u015Fifreli metin\",\n json_string: \"JSON metin\",\n e164: \"E.164 say\u0131s\u0131\",\n jwt: \"JWT\",\n template_literal: \"giren\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"numara\",\n array: \"saf\",\n null: \"gayb\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `F\u00E2sit giren: umulan instanceof ${issue.expected}, al\u0131nan ${received}`;\n }\n return `F\u00E2sit giren: umulan ${expected}, al\u0131nan ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `F\u00E2sit giren: umulan ${util.stringifyPrimitive(issue.values[0])}`;\n return `F\u00E2sit tercih: m\u00FBteberler ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Fazla b\u00FCy\u00FCk: ${issue.origin ?? \"value\"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"} sahip olmal\u0131yd\u0131.`;\n return `Fazla b\u00FCy\u00FCk: ${issue.origin ?? \"value\"}, ${adj}${issue.maximum.toString()} olmal\u0131yd\u0131.`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Fazla k\u00FC\u00E7\u00FCk: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;\n }\n return `Fazla k\u00FC\u00E7\u00FCk: ${issue.origin}, ${adj}${issue.minimum.toString()} olmal\u0131yd\u0131.`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `F\u00E2sit metin: \"${_issue.prefix}\" ile ba\u015Flamal\u0131.`;\n if (_issue.format === \"ends_with\")\n return `F\u00E2sit metin: \"${_issue.suffix}\" ile bitmeli.`;\n if (_issue.format === \"includes\")\n return `F\u00E2sit metin: \"${_issue.includes}\" ihtiv\u00E2 etmeli.`;\n if (_issue.format === \"regex\")\n return `F\u00E2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;\n return `F\u00E2sit ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `F\u00E2sit say\u0131: ${issue.divisor} kat\u0131 olmal\u0131yd\u0131.`;\n case \"unrecognized_keys\":\n return `Tan\u0131nmayan anahtar ${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} i\u00E7in tan\u0131nmayan anahtar var.`;\n case \"invalid_union\":\n return \"Giren tan\u0131namad\u0131.\";\n case \"invalid_element\":\n return `${issue.origin} i\u00E7in tan\u0131nmayan k\u0131ymet var.`;\n default:\n return `K\u0131ymet tan\u0131namad\u0131.`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u062A\u0648\u06A9\u064A\", verb: \"\u0648\u0644\u0631\u064A\" },\n file: { unit: \"\u0628\u0627\u06CC\u067C\u0633\", verb: \"\u0648\u0644\u0631\u064A\" },\n array: { unit: \"\u062A\u0648\u06A9\u064A\", verb: \"\u0648\u0644\u0631\u064A\" },\n set: { unit: \"\u062A\u0648\u06A9\u064A\", verb: \"\u0648\u0644\u0631\u064A\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0648\u0631\u0648\u062F\u064A\",\n email: \"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9\",\n url: \"\u06CC\u0648 \u0622\u0631 \u0627\u0644\",\n emoji: \"\u0627\u06CC\u0645\u0648\u062C\u064A\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A\",\n date: \"\u0646\u06D0\u067C\u0647\",\n time: \"\u0648\u062E\u062A\",\n duration: \"\u0645\u0648\u062F\u0647\",\n ipv4: \"\u062F IPv4 \u067E\u062A\u0647\",\n ipv6: \"\u062F IPv6 \u067E\u062A\u0647\",\n cidrv4: \"\u062F IPv4 \u0633\u0627\u062D\u0647\",\n cidrv6: \"\u062F IPv6 \u0633\u0627\u062D\u0647\",\n base64: \"base64-encoded \u0645\u062A\u0646\",\n base64url: \"base64url-encoded \u0645\u062A\u0646\",\n json_string: \"JSON \u0645\u062A\u0646\",\n e164: \"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647\",\n jwt: \"JWT\",\n template_literal: \"\u0648\u0631\u0648\u062F\u064A\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0639\u062F\u062F\",\n array: \"\u0627\u0631\u06D0\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;\n }\n return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1) {\n return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${util.stringifyPrimitive(issue.values[0])} \u0648\u0627\u06CC`;\n }\n return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${util.joinValues(issue.values, \"|\")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue.origin ?? \"\u0627\u0631\u0632\u069A\u062A\"} \u0628\u0627\u06CC\u062F ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0639\u0646\u0635\u0631\u0648\u0646\u0647\"} \u0648\u0644\u0631\u064A`;\n }\n return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue.origin ?? \"\u0627\u0631\u0632\u069A\u062A\"} \u0628\u0627\u06CC\u062F ${adj}${issue.maximum.toString()} \u0648\u064A`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue.origin} \u0628\u0627\u06CC\u062F ${adj}${issue.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;\n }\n return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue.origin} \u0628\u0627\u06CC\u062F ${adj}${issue.minimum.toString()} \u0648\u064A`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F \"${_issue.prefix}\" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;\n }\n if (_issue.format === \"ends_with\") {\n return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F \"${_issue.suffix}\" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;\n }\n if (_issue.format === \"includes\") {\n return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \"${_issue.includes}\" \u0648\u0644\u0631\u064A`;\n }\n if (_issue.format === \"regex\") {\n return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;\n }\n return `${FormatDictionary[_issue.format] ?? issue.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;\n }\n case \"not_multiple_of\":\n return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;\n case \"unrecognized_keys\":\n return `\u0646\u0627\u0633\u0645 ${issue.keys.length > 1 ? \"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647\" : \"\u06A9\u0644\u06CC\u0689\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue.origin} \u06A9\u06D0`;\n case \"invalid_union\":\n return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;\n case \"invalid_element\":\n return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue.origin} \u06A9\u06D0`;\n default:\n return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"znak\u00F3w\", verb: \"mie\u0107\" },\n file: { unit: \"bajt\u00F3w\", verb: \"mie\u0107\" },\n array: { unit: \"element\u00F3w\", verb: \"mie\u0107\" },\n set: { unit: \"element\u00F3w\", verb: \"mie\u0107\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"wyra\u017Cenie\",\n email: \"adres email\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"data i godzina w formacie ISO\",\n date: \"data w formacie ISO\",\n time: \"godzina w formacie ISO\",\n duration: \"czas trwania ISO\",\n ipv4: \"adres IPv4\",\n ipv6: \"adres IPv6\",\n cidrv4: \"zakres IPv4\",\n cidrv6: \"zakres IPv6\",\n base64: \"ci\u0105g znak\u00F3w zakodowany w formacie base64\",\n base64url: \"ci\u0105g znak\u00F3w zakodowany w formacie base64url\",\n json_string: \"ci\u0105g znak\u00F3w w formacie JSON\",\n e164: \"liczba E.164\",\n jwt: \"JWT\",\n template_literal: \"wej\u015Bcie\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"liczba\",\n array: \"tablica\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue.expected}, otrzymano ${received}`;\n }\n return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${util.stringifyPrimitive(issue.values[0])}`;\n return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue.origin ?? \"warto\u015B\u0107\"} b\u0119dzie mie\u0107 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"element\u00F3w\"}`;\n }\n return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue.origin ?? \"warto\u015B\u0107\"} b\u0119dzie wynosi\u0107 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue.origin ?? \"warto\u015B\u0107\"} b\u0119dzie mie\u0107 ${adj}${issue.minimum.toString()} ${sizing.unit ?? \"element\u00F3w\"}`;\n }\n return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue.origin ?? \"warto\u015B\u0107\"} b\u0119dzie wynosi\u0107 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Nieprawid\u0142owy ci\u0105g znak\u00F3w: musi zaczyna\u0107 si\u0119 od \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Nieprawid\u0142owy ci\u0105g znak\u00F3w: musi ko\u0144czy\u0107 si\u0119 na \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Nieprawid\u0142owy ci\u0105g znak\u00F3w: musi zawiera\u0107 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Nieprawid\u0142owy ci\u0105g znak\u00F3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;\n return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Nierozpoznane klucze${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Nieprawid\u0142owy klucz w ${issue.origin}`;\n case \"invalid_union\":\n return \"Nieprawid\u0142owe dane wej\u015Bciowe\";\n case \"invalid_element\":\n return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue.origin}`;\n default:\n return `Nieprawid\u0142owe dane wej\u015Bciowe`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"caracteres\", verb: \"ter\" },\n file: { unit: \"bytes\", verb: \"ter\" },\n array: { unit: \"itens\", verb: \"ter\" },\n set: { unit: \"itens\", verb: \"ter\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"padr\u00E3o\",\n email: \"endere\u00E7o de e-mail\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"data e hora ISO\",\n date: \"data ISO\",\n time: \"hora ISO\",\n duration: \"dura\u00E7\u00E3o ISO\",\n ipv4: \"endere\u00E7o IPv4\",\n ipv6: \"endere\u00E7o IPv6\",\n cidrv4: \"faixa de IPv4\",\n cidrv6: \"faixa de IPv6\",\n base64: \"texto codificado em base64\",\n base64url: \"URL codificada em base64\",\n json_string: \"texto JSON\",\n e164: \"n\u00FAmero E.164\",\n jwt: \"JWT\",\n template_literal: \"entrada\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"n\u00FAmero\",\n null: \"nulo\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Tipo inv\u00E1lido: esperado instanceof ${issue.expected}, recebido ${received}`;\n }\n return `Tipo inv\u00E1lido: esperado ${expected}, recebido ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Entrada inv\u00E1lida: esperado ${util.stringifyPrimitive(issue.values[0])}`;\n return `Op\u00E7\u00E3o inv\u00E1lida: esperada uma das ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Muito grande: esperado que ${issue.origin ?? \"valor\"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementos\"}`;\n return `Muito grande: esperado que ${issue.origin ?? \"valor\"} fosse ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Texto inv\u00E1lido: deve come\u00E7ar com \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Texto inv\u00E1lido: deve terminar com \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Texto inv\u00E1lido: deve incluir \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Texto inv\u00E1lido: deve corresponder ao padr\u00E3o ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} inv\u00E1lido`;\n }\n case \"not_multiple_of\":\n return `N\u00FAmero inv\u00E1lido: deve ser m\u00FAltiplo de ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Chave${issue.keys.length > 1 ? \"s\" : \"\"} desconhecida${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Chave inv\u00E1lida em ${issue.origin}`;\n case \"invalid_union\":\n return \"Entrada inv\u00E1lida\";\n case \"invalid_element\":\n return `Valor inv\u00E1lido em ${issue.origin}`;\n default:\n return `Campo inv\u00E1lido`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nfunction getRussianPlural(count, one, few, many) {\n const absCount = Math.abs(count);\n const lastDigit = absCount % 10;\n const lastTwoDigits = absCount % 100;\n if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {\n return many;\n }\n if (lastDigit === 1) {\n return one;\n }\n if (lastDigit >= 2 && lastDigit <= 4) {\n return few;\n }\n return many;\n}\nconst error = () => {\n const Sizable = {\n string: {\n unit: {\n one: \"\u0441\u0438\u043C\u0432\u043E\u043B\",\n few: \"\u0441\u0438\u043C\u0432\u043E\u043B\u0430\",\n many: \"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432\",\n },\n verb: \"\u0438\u043C\u0435\u0442\u044C\",\n },\n file: {\n unit: {\n one: \"\u0431\u0430\u0439\u0442\",\n few: \"\u0431\u0430\u0439\u0442\u0430\",\n many: \"\u0431\u0430\u0439\u0442\",\n },\n verb: \"\u0438\u043C\u0435\u0442\u044C\",\n },\n array: {\n unit: {\n one: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\",\n few: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\",\n many: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\",\n },\n verb: \"\u0438\u043C\u0435\u0442\u044C\",\n },\n set: {\n unit: {\n one: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\",\n few: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\",\n many: \"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\",\n },\n verb: \"\u0438\u043C\u0435\u0442\u044C\",\n },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0432\u0432\u043E\u0434\",\n email: \"email \u0430\u0434\u0440\u0435\u0441\",\n url: \"URL\",\n emoji: \"\u044D\u043C\u043E\u0434\u0437\u0438\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F\",\n date: \"ISO \u0434\u0430\u0442\u0430\",\n time: \"ISO \u0432\u0440\u0435\u043C\u044F\",\n duration: \"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C\",\n ipv4: \"IPv4 \u0430\u0434\u0440\u0435\u0441\",\n ipv6: \"IPv6 \u0430\u0434\u0440\u0435\u0441\",\n cidrv4: \"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\",\n cidrv6: \"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\",\n base64: \"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64\",\n base64url: \"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url\",\n json_string: \"JSON \u0441\u0442\u0440\u043E\u043A\u0430\",\n e164: \"\u043D\u043E\u043C\u0435\u0440 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0432\u0432\u043E\u0434\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0447\u0438\u0441\u043B\u043E\",\n array: \"\u043C\u0430\u0441\u0441\u0438\u0432\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;\n }\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const maxValue = Number(issue.maximum);\n const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue.maximum.toString()} ${unit}`;\n }\n return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n const minValue = Number(issue.minimum);\n const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue.minimum.toString()} ${unit}`;\n }\n return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue.keys.length > 1 ? \"\u044B\u0435\" : \"\u044B\u0439\"} \u043A\u043B\u044E\u0447${issue.keys.length > 1 ? \"\u0438\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435\";\n case \"invalid_element\":\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue.origin}`;\n default:\n return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"znakov\", verb: \"imeti\" },\n file: { unit: \"bajtov\", verb: \"imeti\" },\n array: { unit: \"elementov\", verb: \"imeti\" },\n set: { unit: \"elementov\", verb: \"imeti\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"vnos\",\n email: \"e-po\u0161tni naslov\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datum in \u010Das\",\n date: \"ISO datum\",\n time: \"ISO \u010Das\",\n duration: \"ISO trajanje\",\n ipv4: \"IPv4 naslov\",\n ipv6: \"IPv6 naslov\",\n cidrv4: \"obseg IPv4\",\n cidrv6: \"obseg IPv6\",\n base64: \"base64 kodiran niz\",\n base64url: \"base64url kodiran niz\",\n json_string: \"JSON niz\",\n e164: \"E.164 \u0161tevilka\",\n jwt: \"JWT\",\n template_literal: \"vnos\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0161tevilo\",\n array: \"tabela\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue.expected}, prejeto ${received}`;\n }\n return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Neveljaven vnos: pri\u010Dakovano ${util.stringifyPrimitive(issue.values[0])}`;\n return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Preveliko: pri\u010Dakovano, da bo ${issue.origin ?? \"vrednost\"} imelo ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementov\"}`;\n return `Preveliko: pri\u010Dakovano, da bo ${issue.origin ?? \"vrednost\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Premajhno: pri\u010Dakovano, da bo ${issue.origin} imelo ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Premajhno: pri\u010Dakovano, da bo ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Neveljaven niz: mora se za\u010Deti z \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Neveljaven niz: mora se kon\u010Dati z \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Neveljaven niz: mora vsebovati \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;\n return `Neveljaven ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Neprepoznan${issue.keys.length > 1 ? \"i klju\u010Di\" : \" klju\u010D\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Neveljaven klju\u010D v ${issue.origin}`;\n case \"invalid_union\":\n return \"Neveljaven vnos\";\n case \"invalid_element\":\n return `Neveljavna vrednost v ${issue.origin}`;\n default:\n return \"Neveljaven vnos\";\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"tecken\", verb: \"att ha\" },\n file: { unit: \"bytes\", verb: \"att ha\" },\n array: { unit: \"objekt\", verb: \"att inneh\u00E5lla\" },\n set: { unit: \"objekt\", verb: \"att inneh\u00E5lla\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"regulj\u00E4rt uttryck\",\n email: \"e-postadress\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO-datum och tid\",\n date: \"ISO-datum\",\n time: \"ISO-tid\",\n duration: \"ISO-varaktighet\",\n ipv4: \"IPv4-intervall\",\n ipv6: \"IPv6-intervall\",\n cidrv4: \"IPv4-spektrum\",\n cidrv6: \"IPv6-spektrum\",\n base64: \"base64-kodad str\u00E4ng\",\n base64url: \"base64url-kodad str\u00E4ng\",\n json_string: \"JSON-str\u00E4ng\",\n e164: \"E.164-nummer\",\n jwt: \"JWT\",\n template_literal: \"mall-literal\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"antal\",\n array: \"lista\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ogiltig inmatning: f\u00F6rv\u00E4ntat instanceof ${issue.expected}, fick ${received}`;\n }\n return `Ogiltig inmatning: f\u00F6rv\u00E4ntat ${expected}, fick ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ogiltig inmatning: f\u00F6rv\u00E4ntat ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ogiltigt val: f\u00F6rv\u00E4ntade en av ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `F\u00F6r stor(t): f\u00F6rv\u00E4ntade ${issue.origin ?? \"v\u00E4rdet\"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"element\"}`;\n }\n return `F\u00F6r stor(t): f\u00F6rv\u00E4ntat ${issue.origin ?? \"v\u00E4rdet\"} att ha ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `F\u00F6r lite(t): f\u00F6rv\u00E4ntade ${issue.origin ?? \"v\u00E4rdet\"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `F\u00F6r lite(t): f\u00F6rv\u00E4ntade ${issue.origin ?? \"v\u00E4rdet\"} att ha ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Ogiltig str\u00E4ng: m\u00E5ste b\u00F6rja med \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Ogiltig str\u00E4ng: m\u00E5ste sluta med \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Ogiltig str\u00E4ng: m\u00E5ste inneh\u00E5lla \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Ogiltig str\u00E4ng: m\u00E5ste matcha m\u00F6nstret \"${_issue.pattern}\"`;\n return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ogiltigt tal: m\u00E5ste vara en multipel av ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `${issue.keys.length > 1 ? \"Ok\u00E4nda nycklar\" : \"Ok\u00E4nd nyckel\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Ogiltig nyckel i ${issue.origin ?? \"v\u00E4rdet\"}`;\n case \"invalid_union\":\n return \"Ogiltig input\";\n case \"invalid_element\":\n return `Ogiltigt v\u00E4rde i ${issue.origin ?? \"v\u00E4rdet\"}`;\n default:\n return `Ogiltig input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD\", verb: \"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD\" },\n file: { unit: \"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD\", verb: \"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD\" },\n array: { unit: \"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD\", verb: \"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD\" },\n set: { unit: \"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD\", verb: \"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1\",\n email: \"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD\",\n date: \"ISO \u0BA4\u0BC7\u0BA4\u0BBF\",\n time: \"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD\",\n duration: \"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1\",\n ipv4: \"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF\",\n ipv6: \"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF\",\n cidrv4: \"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1\",\n cidrv6: \"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1\",\n base64: \"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD\",\n base64url: \"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD\",\n json_string: \"JSON \u0B9A\u0BB0\u0BAE\u0BCD\",\n e164: \"E.164 \u0B8E\u0BA3\u0BCD\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0B8E\u0BA3\u0BCD\",\n array: \"\u0B85\u0BA3\u0BBF\",\n null: \"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;\n }\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${util.joinValues(issue.values, \"|\")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue.origin ?? \"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD\"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n }\n return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue.origin ?? \"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1\"} ${adj}${issue.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; //\n }\n return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue.origin} ${adj}${issue.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: \"${_issue.prefix}\" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n if (_issue.format === \"ends_with\")\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: \"${_issue.suffix}\" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n if (_issue.format === \"includes\")\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: \"${_issue.includes}\" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n if (_issue.format === \"regex\")\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;\n case \"unrecognized_keys\":\n return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue.keys.length > 1 ? \"\u0B95\u0BB3\u0BCD\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;\n case \"invalid_union\":\n return \"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1\";\n case \"invalid_element\":\n return `${issue.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;\n default:\n return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\", verb: \"\u0E04\u0E27\u0E23\u0E21\u0E35\" },\n file: { unit: \"\u0E44\u0E1A\u0E15\u0E4C\", verb: \"\u0E04\u0E27\u0E23\u0E21\u0E35\" },\n array: { unit: \"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\", verb: \"\u0E04\u0E27\u0E23\u0E21\u0E35\" },\n set: { unit: \"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\", verb: \"\u0E04\u0E27\u0E23\u0E21\u0E35\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19\",\n email: \"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25\",\n url: \"URL\",\n emoji: \"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO\",\n date: \"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO\",\n time: \"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO\",\n duration: \"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO\",\n ipv4: \"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4\",\n ipv6: \"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6\",\n cidrv4: \"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4\",\n cidrv6: \"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6\",\n base64: \"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64\",\n base64url: \"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL\",\n json_string: \"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON\",\n e164: \"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)\",\n jwt: \"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT\",\n template_literal: \"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\",\n array: \"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)\",\n null: \"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;\n }\n return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19\" : \"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue.origin ?? \"\u0E04\u0E48\u0E32\"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\"}`;\n return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue.origin ?? \"\u0E04\u0E48\u0E32\"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22\" : \"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 \"${_issue.includes}\" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;\n if (_issue.format === \"regex\")\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;\n return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;\n case \"unrecognized_keys\":\n return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49\";\n case \"invalid_element\":\n return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue.origin}`;\n default:\n return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"karakter\", verb: \"olmal\u0131\" },\n file: { unit: \"bayt\", verb: \"olmal\u0131\" },\n array: { unit: \"\u00F6\u011Fe\", verb: \"olmal\u0131\" },\n set: { unit: \"\u00F6\u011Fe\", verb: \"olmal\u0131\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"girdi\",\n email: \"e-posta adresi\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO tarih ve saat\",\n date: \"ISO tarih\",\n time: \"ISO saat\",\n duration: \"ISO s\u00FCre\",\n ipv4: \"IPv4 adresi\",\n ipv6: \"IPv6 adresi\",\n cidrv4: \"IPv4 aral\u0131\u011F\u0131\",\n cidrv6: \"IPv6 aral\u0131\u011F\u0131\",\n base64: \"base64 ile \u015Fifrelenmi\u015F metin\",\n base64url: \"base64url ile \u015Fifrelenmi\u015F metin\",\n json_string: \"JSON dizesi\",\n e164: \"E.164 say\u0131s\u0131\",\n jwt: \"JWT\",\n template_literal: \"\u015Eablon dizesi\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Ge\u00E7ersiz de\u011Fer: beklenen instanceof ${issue.expected}, al\u0131nan ${received}`;\n }\n return `Ge\u00E7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Ge\u00E7ersiz de\u011Fer: beklenen ${util.stringifyPrimitive(issue.values[0])}`;\n return `Ge\u00E7ersiz se\u00E7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u00C7ok b\u00FCy\u00FCk: beklenen ${issue.origin ?? \"de\u011Fer\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u00F6\u011Fe\"}`;\n return `\u00C7ok b\u00FCy\u00FCk: beklenen ${issue.origin ?? \"de\u011Fer\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u00C7ok k\u00FC\u00E7\u00FCk: beklenen ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n return `\u00C7ok k\u00FC\u00E7\u00FCk: beklenen ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Ge\u00E7ersiz metin: \"${_issue.prefix}\" ile ba\u015Flamal\u0131`;\n if (_issue.format === \"ends_with\")\n return `Ge\u00E7ersiz metin: \"${_issue.suffix}\" ile bitmeli`;\n if (_issue.format === \"includes\")\n return `Ge\u00E7ersiz metin: \"${_issue.includes}\" i\u00E7ermeli`;\n if (_issue.format === \"regex\")\n return `Ge\u00E7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;\n return `Ge\u00E7ersiz ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Ge\u00E7ersiz say\u0131: ${issue.divisor} ile tam b\u00F6l\u00FCnebilmeli`;\n case \"unrecognized_keys\":\n return `Tan\u0131nmayan anahtar${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} i\u00E7inde ge\u00E7ersiz anahtar`;\n case \"invalid_union\":\n return \"Ge\u00E7ersiz de\u011Fer\";\n case \"invalid_element\":\n return `${issue.origin} i\u00E7inde ge\u00E7ersiz de\u011Fer`;\n default:\n return `Ge\u00E7ersiz de\u011Fer`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432\", verb: \"\u043C\u0430\u0442\u0438\u043C\u0435\" },\n file: { unit: \"\u0431\u0430\u0439\u0442\u0456\u0432\", verb: \"\u043C\u0430\u0442\u0438\u043C\u0435\" },\n array: { unit: \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432\", verb: \"\u043C\u0430\u0442\u0438\u043C\u0435\" },\n set: { unit: \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432\", verb: \"\u043C\u0430\u0442\u0438\u043C\u0435\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456\",\n email: \"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438\",\n url: \"URL\",\n emoji: \"\u0435\u043C\u043E\u0434\u0437\u0456\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO\",\n date: \"\u0434\u0430\u0442\u0430 ISO\",\n time: \"\u0447\u0430\u0441 ISO\",\n duration: \"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO\",\n ipv4: \"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4\",\n ipv6: \"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6\",\n cidrv4: \"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4\",\n cidrv6: \"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6\",\n base64: \"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64\",\n base64url: \"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url\",\n json_string: \"\u0440\u044F\u0434\u043E\u043A JSON\",\n e164: \"\u043D\u043E\u043C\u0435\u0440 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0447\u0438\u0441\u043B\u043E\",\n array: \"\u043C\u0430\u0441\u0438\u0432\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;\n }\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432\"}`;\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue.origin ?? \"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F\"} \u0431\u0443\u0434\u0435 ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue.origin} \u0431\u0443\u0434\u0435 ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue.keys.length > 1 ? \"\u0456\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue.origin}`;\n case \"invalid_union\":\n return \"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456\";\n case \"invalid_element\":\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue.origin}`;\n default:\n return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import uk from \"./uk.js\";\n/** @deprecated Use `uk` instead. */\nexport default function () {\n return uk();\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u062D\u0631\u0648\u0641\", verb: \"\u06C1\u0648\u0646\u0627\" },\n file: { unit: \"\u0628\u0627\u0626\u0679\u0633\", verb: \"\u06C1\u0648\u0646\u0627\" },\n array: { unit: \"\u0622\u0626\u0679\u0645\u0632\", verb: \"\u06C1\u0648\u0646\u0627\" },\n set: { unit: \"\u0622\u0626\u0679\u0645\u0632\", verb: \"\u06C1\u0648\u0646\u0627\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0627\u0646 \u067E\u0679\",\n email: \"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633\",\n url: \"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644\",\n emoji: \"\u0627\u06CC\u0645\u0648\u062C\u06CC\",\n uuid: \"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n uuidv4: \"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4\",\n uuidv6: \"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6\",\n nanoid: \"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n guid: \"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n cuid: \"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n cuid2: \"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2\",\n ulid: \"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC\",\n xid: \"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC\",\n ksuid: \"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC\",\n datetime: \"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645\",\n date: \"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E\",\n time: \"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A\",\n duration: \"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A\",\n ipv4: \"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633\",\n ipv6: \"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633\",\n cidrv4: \"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C\",\n cidrv6: \"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C\",\n base64: \"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF\",\n base64url: \"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF\",\n json_string: \"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF\",\n e164: \"\u0627\u06CC 164 \u0646\u0645\u0628\u0631\",\n jwt: \"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC\",\n template_literal: \"\u0627\u0646 \u067E\u0679\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u0646\u0645\u0628\u0631\",\n array: \"\u0622\u0631\u06D2\",\n null: \"\u0646\u0644\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;\n }\n return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${util.stringifyPrimitive(issue.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;\n return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${util.joinValues(issue.values, \"|\")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue.origin ?? \"\u0648\u06CC\u0644\u06CC\u0648\"} \u06A9\u06D2 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u0639\u0646\u0627\u0635\u0631\"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;\n return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue.origin ?? \"\u0648\u06CC\u0644\u06CC\u0648\"} \u06A9\u0627 ${adj}${issue.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue.origin} \u06A9\u06D2 ${adj}${issue.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;\n }\n return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue.origin} \u06A9\u0627 ${adj}${issue.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \"${_issue.prefix}\" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n }\n if (_issue.format === \"ends_with\")\n return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \"${_issue.suffix}\" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n if (_issue.format === \"includes\")\n return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \"${_issue.includes}\" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n if (_issue.format === \"regex\")\n return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;\n case \"unrecognized_keys\":\n return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue.keys.length > 1 ? \"\u0632\" : \"\"}: ${util.joinValues(issue.keys, \"\u060C \")}`;\n case \"invalid_key\":\n return `${issue.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;\n case \"invalid_union\":\n return \"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679\";\n case \"invalid_element\":\n return `${issue.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;\n default:\n return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"belgi\", verb: \"bo\u2018lishi kerak\" },\n file: { unit: \"bayt\", verb: \"bo\u2018lishi kerak\" },\n array: { unit: \"element\", verb: \"bo\u2018lishi kerak\" },\n set: { unit: \"element\", verb: \"bo\u2018lishi kerak\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"kirish\",\n email: \"elektron pochta manzili\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO sana va vaqti\",\n date: \"ISO sana\",\n time: \"ISO vaqt\",\n duration: \"ISO davomiylik\",\n ipv4: \"IPv4 manzil\",\n ipv6: \"IPv6 manzil\",\n mac: \"MAC manzil\",\n cidrv4: \"IPv4 diapazon\",\n cidrv6: \"IPv6 diapazon\",\n base64: \"base64 kodlangan satr\",\n base64url: \"base64url kodlangan satr\",\n json_string: \"JSON satr\",\n e164: \"E.164 raqam\",\n jwt: \"JWT\",\n template_literal: \"kirish\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"raqam\",\n array: \"massiv\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue.expected}, qabul qilingan ${received}`;\n }\n return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Noto\u2018g\u2018ri kirish: kutilgan ${util.stringifyPrimitive(issue.values[0])}`;\n return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Juda katta: kutilgan ${issue.origin ?? \"qiymat\"} ${adj}${issue.maximum.toString()} ${sizing.unit} ${sizing.verb}`;\n return `Juda katta: kutilgan ${issue.origin ?? \"qiymat\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;\n }\n return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Noto\u2018g\u2018ri satr: \"${_issue.prefix}\" bilan boshlanishi kerak`;\n if (_issue.format === \"ends_with\")\n return `Noto\u2018g\u2018ri satr: \"${_issue.suffix}\" bilan tugashi kerak`;\n if (_issue.format === \"includes\")\n return `Noto\u2018g\u2018ri satr: \"${_issue.includes}\" ni o\u2018z ichiga olishi kerak`;\n if (_issue.format === \"regex\")\n return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;\n return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Noto\u2018g\u2018ri raqam: ${issue.divisor} ning karralisi bo\u2018lishi kerak`;\n case \"unrecognized_keys\":\n return `Noma\u2019lum kalit${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} dagi kalit noto\u2018g\u2018ri`;\n case \"invalid_union\":\n return \"Noto\u2018g\u2018ri kirish\";\n case \"invalid_element\":\n return `${issue.origin} da noto\u2018g\u2018ri qiymat`;\n default:\n return `Noto\u2018g\u2018ri kirish`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"k\u00FD t\u1EF1\", verb: \"c\u00F3\" },\n file: { unit: \"byte\", verb: \"c\u00F3\" },\n array: { unit: \"ph\u1EA7n t\u1EED\", verb: \"c\u00F3\" },\n set: { unit: \"ph\u1EA7n t\u1EED\", verb: \"c\u00F3\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u0111\u1EA7u v\u00E0o\",\n email: \"\u0111\u1ECBa ch\u1EC9 email\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ng\u00E0y gi\u1EDD ISO\",\n date: \"ng\u00E0y ISO\",\n time: \"gi\u1EDD ISO\",\n duration: \"kho\u1EA3ng th\u1EDDi gian ISO\",\n ipv4: \"\u0111\u1ECBa ch\u1EC9 IPv4\",\n ipv6: \"\u0111\u1ECBa ch\u1EC9 IPv6\",\n cidrv4: \"d\u1EA3i IPv4\",\n cidrv6: \"d\u1EA3i IPv6\",\n base64: \"chu\u1ED7i m\u00E3 h\u00F3a base64\",\n base64url: \"chu\u1ED7i m\u00E3 h\u00F3a base64url\",\n json_string: \"chu\u1ED7i JSON\",\n e164: \"s\u1ED1 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u0111\u1EA7u v\u00E0o\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"s\u1ED1\",\n array: \"m\u1EA3ng\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;\n }\n return `\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${util.stringifyPrimitive(issue.values[0])}`;\n return `T\u00F9y ch\u1ECDn kh\u00F4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\u00E1c gi\u00E1 tr\u1ECB ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Qu\u00E1 l\u1EDBn: mong \u0111\u1EE3i ${issue.origin ?? \"gi\u00E1 tr\u1ECB\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"ph\u1EA7n t\u1EED\"}`;\n return `Qu\u00E1 l\u1EDBn: mong \u0111\u1EE3i ${issue.origin ?? \"gi\u00E1 tr\u1ECB\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Qu\u00E1 nh\u1ECF: mong \u0111\u1EE3i ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Qu\u00E1 nh\u1ECF: mong \u0111\u1EE3i ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `Chu\u1ED7i kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `Chu\u1ED7i kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\u00FAc b\u1EB1ng \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Chu\u1ED7i kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Chu\u1ED7i kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;\n return `${FormatDictionary[_issue.format] ?? issue.format} kh\u00F4ng h\u1EE3p l\u1EC7`;\n }\n case \"not_multiple_of\":\n return `S\u1ED1 kh\u00F4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\u00E0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Kh\u00F3a kh\u00F4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Kh\u00F3a kh\u00F4ng h\u1EE3p l\u1EC7 trong ${issue.origin}`;\n case \"invalid_union\":\n return \"\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7\";\n case \"invalid_element\":\n return `Gi\u00E1 tr\u1ECB kh\u00F4ng h\u1EE3p l\u1EC7 trong ${issue.origin}`;\n default:\n return `\u0110\u1EA7u v\u00E0o kh\u00F4ng h\u1EE3p l\u1EC7`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u5B57\u7B26\", verb: \"\u5305\u542B\" },\n file: { unit: \"\u5B57\u8282\", verb: \"\u5305\u542B\" },\n array: { unit: \"\u9879\", verb: \"\u5305\u542B\" },\n set: { unit: \"\u9879\", verb: \"\u5305\u542B\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u8F93\u5165\",\n email: \"\u7535\u5B50\u90AE\u4EF6\",\n url: \"URL\",\n emoji: \"\u8868\u60C5\u7B26\u53F7\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO\u65E5\u671F\u65F6\u95F4\",\n date: \"ISO\u65E5\u671F\",\n time: \"ISO\u65F6\u95F4\",\n duration: \"ISO\u65F6\u957F\",\n ipv4: \"IPv4\u5730\u5740\",\n ipv6: \"IPv6\u5730\u5740\",\n cidrv4: \"IPv4\u7F51\u6BB5\",\n cidrv6: \"IPv6\u7F51\u6BB5\",\n base64: \"base64\u7F16\u7801\u5B57\u7B26\u4E32\",\n base64url: \"base64url\u7F16\u7801\u5B57\u7B26\u4E32\",\n json_string: \"JSON\u5B57\u7B26\u4E32\",\n e164: \"E.164\u53F7\u7801\",\n jwt: \"JWT\",\n template_literal: \"\u8F93\u5165\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"\u6570\u5B57\",\n array: \"\u6570\u7EC4\",\n null: \"\u7A7A\u503C(null)\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;\n }\n return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue.origin ?? \"\u503C\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u4E2A\u5143\u7D20\"}`;\n return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue.origin ?? \"\u503C\"} ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue.origin} ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 \"${_issue.prefix}\" \u5F00\u5934`;\n if (_issue.format === \"ends_with\")\n return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 \"${_issue.suffix}\" \u7ED3\u5C3E`;\n if (_issue.format === \"includes\")\n return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;\n return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue.divisor} \u7684\u500D\u6570`;\n case \"unrecognized_keys\":\n return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `${issue.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;\n case \"invalid_union\":\n return \"\u65E0\u6548\u8F93\u5165\";\n case \"invalid_element\":\n return `${issue.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;\n default:\n return `\u65E0\u6548\u8F93\u5165`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u5B57\u5143\", verb: \"\u64C1\u6709\" },\n file: { unit: \"\u4F4D\u5143\u7D44\", verb: \"\u64C1\u6709\" },\n array: { unit: \"\u9805\u76EE\", verb: \"\u64C1\u6709\" },\n set: { unit: \"\u9805\u76EE\", verb: \"\u64C1\u6709\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u8F38\u5165\",\n email: \"\u90F5\u4EF6\u5730\u5740\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO \u65E5\u671F\u6642\u9593\",\n date: \"ISO \u65E5\u671F\",\n time: \"ISO \u6642\u9593\",\n duration: \"ISO \u671F\u9593\",\n ipv4: \"IPv4 \u4F4D\u5740\",\n ipv6: \"IPv6 \u4F4D\u5740\",\n cidrv4: \"IPv4 \u7BC4\u570D\",\n cidrv6: \"IPv6 \u7BC4\u570D\",\n base64: \"base64 \u7DE8\u78BC\u5B57\u4E32\",\n base64url: \"base64url \u7DE8\u78BC\u5B57\u4E32\",\n json_string: \"JSON \u5B57\u4E32\",\n e164: \"E.164 \u6578\u503C\",\n jwt: \"JWT\",\n template_literal: \"\u8F38\u5165\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue.expected}\uFF0C\u4F46\u6536\u5230 ${received}`;\n }\n return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue.origin ?? \"\u503C\"} \u61C9\u70BA ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"\u500B\u5143\u7D20\"}`;\n return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue.origin ?? \"\u503C\"} \u61C9\u70BA ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue.origin} \u61C9\u70BA ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue.origin} \u61C9\u70BA ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 \"${_issue.prefix}\" \u958B\u982D`;\n }\n if (_issue.format === \"ends_with\")\n return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 \"${_issue.suffix}\" \u7D50\u5C3E`;\n if (_issue.format === \"includes\")\n return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;\n return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue.divisor} \u7684\u500D\u6578`;\n case \"unrecognized_keys\":\n return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue.keys.length > 1 ? \"\u5011\" : \"\"}\uFF1A${util.joinValues(issue.keys, \"\u3001\")}`;\n case \"invalid_key\":\n return `${issue.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;\n case \"invalid_union\":\n return \"\u7121\u6548\u7684\u8F38\u5165\u503C\";\n case \"invalid_element\":\n return `${issue.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;\n default:\n return `\u7121\u6548\u7684\u8F38\u5165\u503C`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"\u00E0mi\", verb: \"n\u00ED\" },\n file: { unit: \"bytes\", verb: \"n\u00ED\" },\n array: { unit: \"nkan\", verb: \"n\u00ED\" },\n set: { unit: \"nkan\", verb: \"n\u00ED\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"\u1EB9\u0300r\u1ECD \u00ECb\u00E1w\u1ECDl\u00E9\",\n email: \"\u00E0d\u00EDr\u1EB9\u0301s\u00EC \u00ECm\u1EB9\u0301l\u00EC\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"\u00E0k\u00F3k\u00F2 ISO\",\n date: \"\u1ECDj\u1ECD\u0301 ISO\",\n time: \"\u00E0k\u00F3k\u00F2 ISO\",\n duration: \"\u00E0k\u00F3k\u00F2 t\u00F3 p\u00E9 ISO\",\n ipv4: \"\u00E0d\u00EDr\u1EB9\u0301s\u00EC IPv4\",\n ipv6: \"\u00E0d\u00EDr\u1EB9\u0301s\u00EC IPv6\",\n cidrv4: \"\u00E0gb\u00E8gb\u00E8 IPv4\",\n cidrv6: \"\u00E0gb\u00E8gb\u00E8 IPv6\",\n base64: \"\u1ECD\u0300r\u1ECD\u0300 t\u00ED a k\u1ECD\u0301 n\u00ED base64\",\n base64url: \"\u1ECD\u0300r\u1ECD\u0300 base64url\",\n json_string: \"\u1ECD\u0300r\u1ECD\u0300 JSON\",\n e164: \"n\u1ECD\u0301mb\u00E0 E.164\",\n jwt: \"JWT\",\n template_literal: \"\u1EB9\u0300r\u1ECD \u00ECb\u00E1w\u1ECDl\u00E9\",\n };\n const TypeDictionary = {\n nan: \"NaN\",\n number: \"n\u1ECD\u0301mb\u00E0\",\n array: \"akop\u1ECD\",\n };\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = TypeDictionary[issue.expected] ?? issue.expected;\n const receivedType = util.parsedType(issue.input);\n const received = TypeDictionary[receivedType] ?? receivedType;\n if (/^[A-Z]/.test(issue.expected)) {\n return `\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e: a n\u00ED l\u00E1ti fi instanceof ${issue.expected}, \u00E0m\u1ECD\u0300 a r\u00ED ${received}`;\n }\n return `\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e: a n\u00ED l\u00E1ti fi ${expected}, \u00E0m\u1ECD\u0300 a r\u00ED ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e: a n\u00ED l\u00E1ti fi ${util.stringifyPrimitive(issue.values[0])}`;\n return `\u00C0\u1E63\u00E0y\u00E0n a\u1E63\u00EC\u1E63e: yan \u1ECD\u0300kan l\u00E1ra ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `T\u00F3 p\u1ECD\u0300 j\u00F9: a n\u00ED l\u00E1ti j\u1EB9\u0301 p\u00E9 ${issue.origin ?? \"iye\"} ${sizing.verb} ${adj}${issue.maximum} ${sizing.unit}`;\n return `T\u00F3 p\u1ECD\u0300 j\u00F9: a n\u00ED l\u00E1ti j\u1EB9\u0301 ${adj}${issue.maximum}`;\n }\n case \"too_small\": {\n const adj = issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `K\u00E9r\u00E9 ju: a n\u00ED l\u00E1ti j\u1EB9\u0301 p\u00E9 ${issue.origin} ${sizing.verb} ${adj}${issue.minimum} ${sizing.unit}`;\n return `K\u00E9r\u00E9 ju: a n\u00ED l\u00E1ti j\u1EB9\u0301 ${adj}${issue.minimum}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\")\n return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\u00FA \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\")\n return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\u00ED p\u1EB9\u0300l\u00FA \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\u00ED \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u00E1 \u00E0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`;\n return `A\u1E63\u00EC\u1E63e: ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `N\u1ECD\u0301mb\u00E0 a\u1E63\u00EC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \u00E8y\u00E0 p\u00EDp\u00EDn ti ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `B\u1ECDt\u00ECn\u00EC \u00E0\u00ECm\u1ECD\u0300: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `B\u1ECDt\u00ECn\u00EC a\u1E63\u00EC\u1E63e n\u00EDn\u00FA ${issue.origin}`;\n case \"invalid_union\":\n return \"\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e\";\n case \"invalid_element\":\n return `Iye a\u1E63\u00EC\u1E63e n\u00EDn\u00FA ${issue.origin}`;\n default:\n return \"\u00CCb\u00E1w\u1ECDl\u00E9 a\u1E63\u00EC\u1E63e\";\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "export { default as ar } from \"./ar.js\";\nexport { default as az } from \"./az.js\";\nexport { default as be } from \"./be.js\";\nexport { default as bg } from \"./bg.js\";\nexport { default as ca } from \"./ca.js\";\nexport { default as cs } from \"./cs.js\";\nexport { default as da } from \"./da.js\";\nexport { default as de } from \"./de.js\";\nexport { default as en } from \"./en.js\";\nexport { default as eo } from \"./eo.js\";\nexport { default as es } from \"./es.js\";\nexport { default as fa } from \"./fa.js\";\nexport { default as fi } from \"./fi.js\";\nexport { default as fr } from \"./fr.js\";\nexport { default as frCA } from \"./fr-CA.js\";\nexport { default as he } from \"./he.js\";\nexport { default as hu } from \"./hu.js\";\nexport { default as hy } from \"./hy.js\";\nexport { default as id } from \"./id.js\";\nexport { default as is } from \"./is.js\";\nexport { default as it } from \"./it.js\";\nexport { default as ja } from \"./ja.js\";\nexport { default as ka } from \"./ka.js\";\nexport { default as kh } from \"./kh.js\";\nexport { default as km } from \"./km.js\";\nexport { default as ko } from \"./ko.js\";\nexport { default as lt } from \"./lt.js\";\nexport { default as mk } from \"./mk.js\";\nexport { default as ms } from \"./ms.js\";\nexport { default as nl } from \"./nl.js\";\nexport { default as no } from \"./no.js\";\nexport { default as ota } from \"./ota.js\";\nexport { default as ps } from \"./ps.js\";\nexport { default as pl } from \"./pl.js\";\nexport { default as pt } from \"./pt.js\";\nexport { default as ru } from \"./ru.js\";\nexport { default as sl } from \"./sl.js\";\nexport { default as sv } from \"./sv.js\";\nexport { default as ta } from \"./ta.js\";\nexport { default as th } from \"./th.js\";\nexport { default as tr } from \"./tr.js\";\nexport { default as ua } from \"./ua.js\";\nexport { default as uk } from \"./uk.js\";\nexport { default as ur } from \"./ur.js\";\nexport { default as uz } from \"./uz.js\";\nexport { default as vi } from \"./vi.js\";\nexport { default as zhCN } from \"./zh-CN.js\";\nexport { default as zhTW } from \"./zh-TW.js\";\nexport { default as yo } from \"./yo.js\";\n", "var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n", "import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n", "import { globalRegistry } from \"./registries.js\";\n// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && result.schema._prefault)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n", "import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, { ...params, path: [...params.path, \"items\"] });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n", "import { allProcessors } from \"./json-schema-processors.js\";\nimport { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\n/**\n * Legacy class-based interface for JSON Schema generation.\n * This class wraps the new functional implementation to provide backward compatibility.\n *\n * @deprecated Use the `toJSONSchema` function instead for new code.\n *\n * @example\n * ```typescript\n * // Legacy usage (still supported)\n * const gen = new JSONSchemaGenerator({ target: \"draft-07\" });\n * gen.process(schema);\n * const result = gen.emit(schema);\n *\n * // Preferred modern usage\n * const result = toJSONSchema(schema, { target: \"draft-07\" });\n * ```\n */\nexport class JSONSchemaGenerator {\n /** @deprecated Access via ctx instead */\n get metadataRegistry() {\n return this.ctx.metadataRegistry;\n }\n /** @deprecated Access via ctx instead */\n get target() {\n return this.ctx.target;\n }\n /** @deprecated Access via ctx instead */\n get unrepresentable() {\n return this.ctx.unrepresentable;\n }\n /** @deprecated Access via ctx instead */\n get override() {\n return this.ctx.override;\n }\n /** @deprecated Access via ctx instead */\n get io() {\n return this.ctx.io;\n }\n /** @deprecated Access via ctx instead */\n get counter() {\n return this.ctx.counter;\n }\n set counter(value) {\n this.ctx.counter = value;\n }\n /** @deprecated Access via ctx instead */\n get seen() {\n return this.ctx.seen;\n }\n constructor(params) {\n // Normalize target for internal context\n let normalizedTarget = params?.target ?? \"draft-2020-12\";\n if (normalizedTarget === \"draft-4\")\n normalizedTarget = \"draft-04\";\n if (normalizedTarget === \"draft-7\")\n normalizedTarget = \"draft-07\";\n this.ctx = initializeContext({\n processors: allProcessors,\n target: normalizedTarget,\n ...(params?.metadata && { metadata: params.metadata }),\n ...(params?.unrepresentable && { unrepresentable: params.unrepresentable }),\n ...(params?.override && { override: params.override }),\n ...(params?.io && { io: params.io }),\n });\n }\n /**\n * Process a schema to prepare it for JSON Schema generation.\n * This must be called before emit().\n */\n process(schema, _params = { path: [], schemaPath: [] }) {\n return process(schema, this.ctx, _params);\n }\n /**\n * Emit the final JSON Schema after processing.\n * Must call process() first.\n */\n emit(schema, _params) {\n // Apply emit params to the context\n if (_params) {\n if (_params.cycles)\n this.ctx.cycles = _params.cycles;\n if (_params.reused)\n this.ctx.reused = _params.reused;\n if (_params.external)\n this.ctx.external = _params.external;\n }\n extractDefs(this.ctx, schema);\n const result = finalize(this.ctx, schema);\n // Strip ~standard property to match old implementation's return type\n const { \"~standard\": _, ...plainResult } = result;\n return plainResult;\n }\n}\n", "export {};\n", "export * from \"./core.js\";\nexport * from \"./parse.js\";\nexport * from \"./errors.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./versions.js\";\nexport * as util from \"./util.js\";\nexport * as regexes from \"./regexes.js\";\nexport * as locales from \"../locales/index.js\";\nexport * from \"./registries.js\";\nexport * from \"./doc.js\";\nexport * from \"./api.js\";\nexport * from \"./to-json-schema.js\";\nexport { toJSONSchema } from \"./json-schema-processors.js\";\nexport { JSONSchemaGenerator } from \"./json-schema-generator.js\";\nexport * as JSONSchema from \"./json-schema.js\";\n", "export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, } from \"../core/index.js\";\n", "import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n", "import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n", "import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n", "import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // base methods\n inst.check = (...checks) => {\n return inst.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), {\n parent: true,\n });\n };\n inst.with = inst.check;\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n // encoding/decoding\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.exactOptional = () => exactOptional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n inst.apply = (fn) => fn(inst);\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n inst.slugify = () => inst.check(checks.slugify());\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: /^https?$/,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.safeExtend = (incoming) => {\n return util.safeExtend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn) {\n return core._superRefine(fn);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n", "// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n", "import { globalRegistry } from \"../core/registries.js\";\nimport * as _checks from \"./checks.js\";\nimport * as _iso from \"./iso.js\";\nimport * as _schemas from \"./schemas.js\";\n// Local z object to avoid circular dependency with ../index.js\nconst z = {\n ..._schemas,\n ..._checks,\n iso: _iso,\n};\n// Keys that are recognized and handled by the conversion logic\nconst RECOGNIZED_KEYS = new Set([\n // Schema identification\n \"$schema\",\n \"$ref\",\n \"$defs\",\n \"definitions\",\n // Core schema keywords\n \"$id\",\n \"id\",\n \"$comment\",\n \"$anchor\",\n \"$vocabulary\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n // Type\n \"type\",\n \"enum\",\n \"const\",\n // Composition\n \"anyOf\",\n \"oneOf\",\n \"allOf\",\n \"not\",\n // Object\n \"properties\",\n \"required\",\n \"additionalProperties\",\n \"patternProperties\",\n \"propertyNames\",\n \"minProperties\",\n \"maxProperties\",\n // Array\n \"items\",\n \"prefixItems\",\n \"additionalItems\",\n \"minItems\",\n \"maxItems\",\n \"uniqueItems\",\n \"contains\",\n \"minContains\",\n \"maxContains\",\n // String\n \"minLength\",\n \"maxLength\",\n \"pattern\",\n \"format\",\n // Number\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n // Already handled metadata\n \"description\",\n \"default\",\n // Content\n \"contentEncoding\",\n \"contentMediaType\",\n \"contentSchema\",\n // Unsupported (error-throwing)\n \"unevaluatedItems\",\n \"unevaluatedProperties\",\n \"if\",\n \"then\",\n \"else\",\n \"dependentSchemas\",\n \"dependentRequired\",\n // OpenAPI\n \"nullable\",\n \"readOnly\",\n]);\nfunction detectVersion(schema, defaultTarget) {\n const $schema = schema.$schema;\n if ($schema === \"https://json-schema.org/draft/2020-12/schema\") {\n return \"draft-2020-12\";\n }\n if ($schema === \"http://json-schema.org/draft-07/schema#\") {\n return \"draft-7\";\n }\n if ($schema === \"http://json-schema.org/draft-04/schema#\") {\n return \"draft-4\";\n }\n // Use defaultTarget if provided, otherwise default to draft-2020-12\n return defaultTarget ?? \"draft-2020-12\";\n}\nfunction resolveRef(ref, ctx) {\n if (!ref.startsWith(\"#\")) {\n throw new Error(\"External $ref is not supported, only local refs (#/...) are allowed\");\n }\n const path = ref.slice(1).split(\"/\").filter(Boolean);\n // Handle root reference \"#\"\n if (path.length === 0) {\n return ctx.rootSchema;\n }\n const defsKey = ctx.version === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (path[0] === defsKey) {\n const key = path[1];\n if (!key || !ctx.defs[key]) {\n throw new Error(`Reference not found: ${ref}`);\n }\n return ctx.defs[key];\n }\n throw new Error(`Reference not found: ${ref}`);\n}\nfunction convertBaseSchema(schema, ctx) {\n // Handle unsupported features\n if (schema.not !== undefined) {\n // Special case: { not: {} } represents never\n if (typeof schema.not === \"object\" && Object.keys(schema.not).length === 0) {\n return z.never();\n }\n throw new Error(\"not is not supported in Zod (except { not: {} } for never)\");\n }\n if (schema.unevaluatedItems !== undefined) {\n throw new Error(\"unevaluatedItems is not supported\");\n }\n if (schema.unevaluatedProperties !== undefined) {\n throw new Error(\"unevaluatedProperties is not supported\");\n }\n if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {\n throw new Error(\"Conditional schemas (if/then/else) are not supported\");\n }\n if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {\n throw new Error(\"dependentSchemas and dependentRequired are not supported\");\n }\n // Handle $ref\n if (schema.$ref) {\n const refPath = schema.$ref;\n if (ctx.refs.has(refPath)) {\n return ctx.refs.get(refPath);\n }\n if (ctx.processing.has(refPath)) {\n // Circular reference - use lazy\n return z.lazy(() => {\n if (!ctx.refs.has(refPath)) {\n throw new Error(`Circular reference not resolved: ${refPath}`);\n }\n return ctx.refs.get(refPath);\n });\n }\n ctx.processing.add(refPath);\n const resolved = resolveRef(refPath, ctx);\n const zodSchema = convertSchema(resolved, ctx);\n ctx.refs.set(refPath, zodSchema);\n ctx.processing.delete(refPath);\n return zodSchema;\n }\n // Handle enum\n if (schema.enum !== undefined) {\n const enumValues = schema.enum;\n // Special case: OpenAPI 3.0 null representation { type: \"string\", nullable: true, enum: [null] }\n if (ctx.version === \"openapi-3.0\" &&\n schema.nullable === true &&\n enumValues.length === 1 &&\n enumValues[0] === null) {\n return z.null();\n }\n if (enumValues.length === 0) {\n return z.never();\n }\n if (enumValues.length === 1) {\n return z.literal(enumValues[0]);\n }\n // Check if all values are strings\n if (enumValues.every((v) => typeof v === \"string\")) {\n return z.enum(enumValues);\n }\n // Mixed types - use union of literals\n const literalSchemas = enumValues.map((v) => z.literal(v));\n if (literalSchemas.length < 2) {\n return literalSchemas[0];\n }\n return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);\n }\n // Handle const\n if (schema.const !== undefined) {\n return z.literal(schema.const);\n }\n // Handle type\n const type = schema.type;\n if (Array.isArray(type)) {\n // Expand type array into anyOf union\n const typeSchemas = type.map((t) => {\n const typeSchema = { ...schema, type: t };\n return convertBaseSchema(typeSchema, ctx);\n });\n if (typeSchemas.length === 0) {\n return z.never();\n }\n if (typeSchemas.length === 1) {\n return typeSchemas[0];\n }\n return z.union(typeSchemas);\n }\n if (!type) {\n // No type specified - empty schema (any)\n return z.any();\n }\n let zodSchema;\n switch (type) {\n case \"string\": {\n let stringSchema = z.string();\n // Apply format using .check() with Zod format functions\n if (schema.format) {\n const format = schema.format;\n // Map common formats to Zod check functions\n if (format === \"email\") {\n stringSchema = stringSchema.check(z.email());\n }\n else if (format === \"uri\" || format === \"uri-reference\") {\n stringSchema = stringSchema.check(z.url());\n }\n else if (format === \"uuid\" || format === \"guid\") {\n stringSchema = stringSchema.check(z.uuid());\n }\n else if (format === \"date-time\") {\n stringSchema = stringSchema.check(z.iso.datetime());\n }\n else if (format === \"date\") {\n stringSchema = stringSchema.check(z.iso.date());\n }\n else if (format === \"time\") {\n stringSchema = stringSchema.check(z.iso.time());\n }\n else if (format === \"duration\") {\n stringSchema = stringSchema.check(z.iso.duration());\n }\n else if (format === \"ipv4\") {\n stringSchema = stringSchema.check(z.ipv4());\n }\n else if (format === \"ipv6\") {\n stringSchema = stringSchema.check(z.ipv6());\n }\n else if (format === \"mac\") {\n stringSchema = stringSchema.check(z.mac());\n }\n else if (format === \"cidr\") {\n stringSchema = stringSchema.check(z.cidrv4());\n }\n else if (format === \"cidr-v6\") {\n stringSchema = stringSchema.check(z.cidrv6());\n }\n else if (format === \"base64\") {\n stringSchema = stringSchema.check(z.base64());\n }\n else if (format === \"base64url\") {\n stringSchema = stringSchema.check(z.base64url());\n }\n else if (format === \"e164\") {\n stringSchema = stringSchema.check(z.e164());\n }\n else if (format === \"jwt\") {\n stringSchema = stringSchema.check(z.jwt());\n }\n else if (format === \"emoji\") {\n stringSchema = stringSchema.check(z.emoji());\n }\n else if (format === \"nanoid\") {\n stringSchema = stringSchema.check(z.nanoid());\n }\n else if (format === \"cuid\") {\n stringSchema = stringSchema.check(z.cuid());\n }\n else if (format === \"cuid2\") {\n stringSchema = stringSchema.check(z.cuid2());\n }\n else if (format === \"ulid\") {\n stringSchema = stringSchema.check(z.ulid());\n }\n else if (format === \"xid\") {\n stringSchema = stringSchema.check(z.xid());\n }\n else if (format === \"ksuid\") {\n stringSchema = stringSchema.check(z.ksuid());\n }\n // Note: json-string format is not currently supported by Zod\n // Custom formats are ignored - keep as plain string\n }\n // Apply constraints\n if (typeof schema.minLength === \"number\") {\n stringSchema = stringSchema.min(schema.minLength);\n }\n if (typeof schema.maxLength === \"number\") {\n stringSchema = stringSchema.max(schema.maxLength);\n }\n if (schema.pattern) {\n // JSON Schema patterns are not implicitly anchored (match anywhere in string)\n stringSchema = stringSchema.regex(new RegExp(schema.pattern));\n }\n zodSchema = stringSchema;\n break;\n }\n case \"number\":\n case \"integer\": {\n let numberSchema = type === \"integer\" ? z.number().int() : z.number();\n // Apply constraints\n if (typeof schema.minimum === \"number\") {\n numberSchema = numberSchema.min(schema.minimum);\n }\n if (typeof schema.maximum === \"number\") {\n numberSchema = numberSchema.max(schema.maximum);\n }\n if (typeof schema.exclusiveMinimum === \"number\") {\n numberSchema = numberSchema.gt(schema.exclusiveMinimum);\n }\n else if (schema.exclusiveMinimum === true && typeof schema.minimum === \"number\") {\n numberSchema = numberSchema.gt(schema.minimum);\n }\n if (typeof schema.exclusiveMaximum === \"number\") {\n numberSchema = numberSchema.lt(schema.exclusiveMaximum);\n }\n else if (schema.exclusiveMaximum === true && typeof schema.maximum === \"number\") {\n numberSchema = numberSchema.lt(schema.maximum);\n }\n if (typeof schema.multipleOf === \"number\") {\n numberSchema = numberSchema.multipleOf(schema.multipleOf);\n }\n zodSchema = numberSchema;\n break;\n }\n case \"boolean\": {\n zodSchema = z.boolean();\n break;\n }\n case \"null\": {\n zodSchema = z.null();\n break;\n }\n case \"object\": {\n const shape = {};\n const properties = schema.properties || {};\n const requiredSet = new Set(schema.required || []);\n // Convert properties - mark optional ones\n for (const [key, propSchema] of Object.entries(properties)) {\n const propZodSchema = convertSchema(propSchema, ctx);\n // If not in required array, make it optional\n shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();\n }\n // Handle propertyNames\n if (schema.propertyNames) {\n const keySchema = convertSchema(schema.propertyNames, ctx);\n const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === \"object\"\n ? convertSchema(schema.additionalProperties, ctx)\n : z.any();\n // Case A: No properties (pure record)\n if (Object.keys(shape).length === 0) {\n zodSchema = z.record(keySchema, valueSchema);\n break;\n }\n // Case B: With properties (intersection of object and looseRecord)\n const objectSchema = z.object(shape).passthrough();\n const recordSchema = z.looseRecord(keySchema, valueSchema);\n zodSchema = z.intersection(objectSchema, recordSchema);\n break;\n }\n // Handle patternProperties\n if (schema.patternProperties) {\n // patternProperties: keys matching pattern must satisfy corresponding schema\n // Use loose records so non-matching keys pass through\n const patternProps = schema.patternProperties;\n const patternKeys = Object.keys(patternProps);\n const looseRecords = [];\n for (const pattern of patternKeys) {\n const patternValue = convertSchema(patternProps[pattern], ctx);\n const keySchema = z.string().regex(new RegExp(pattern));\n looseRecords.push(z.looseRecord(keySchema, patternValue));\n }\n // Build intersection: object schema + all pattern property records\n const schemasToIntersect = [];\n if (Object.keys(shape).length > 0) {\n // Use passthrough so patternProperties can validate additional keys\n schemasToIntersect.push(z.object(shape).passthrough());\n }\n schemasToIntersect.push(...looseRecords);\n if (schemasToIntersect.length === 0) {\n zodSchema = z.object({}).passthrough();\n }\n else if (schemasToIntersect.length === 1) {\n zodSchema = schemasToIntersect[0];\n }\n else {\n // Chain intersections: (A & B) & C & D ...\n let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);\n for (let i = 2; i < schemasToIntersect.length; i++) {\n result = z.intersection(result, schemasToIntersect[i]);\n }\n zodSchema = result;\n }\n break;\n }\n // Handle additionalProperties\n // In JSON Schema, additionalProperties defaults to true (allow any extra properties)\n // In Zod, objects strip unknown keys by default, so we need to handle this explicitly\n const objectSchema = z.object(shape);\n if (schema.additionalProperties === false) {\n // Strict mode - no extra properties allowed\n zodSchema = objectSchema.strict();\n }\n else if (typeof schema.additionalProperties === \"object\") {\n // Extra properties must match the specified schema\n zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));\n }\n else {\n // additionalProperties is true or undefined - allow any extra properties (passthrough)\n zodSchema = objectSchema.passthrough();\n }\n break;\n }\n case \"array\": {\n // TODO: uniqueItems is not supported\n // TODO: contains/minContains/maxContains are not supported\n // Check if this is a tuple (prefixItems or items as array)\n const prefixItems = schema.prefixItems;\n const items = schema.items;\n if (prefixItems && Array.isArray(prefixItems)) {\n // Tuple with prefixItems (draft-2020-12)\n const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));\n const rest = items && typeof items === \"object\" && !Array.isArray(items)\n ? convertSchema(items, ctx)\n : undefined;\n if (rest) {\n zodSchema = z.tuple(tupleItems).rest(rest);\n }\n else {\n zodSchema = z.tuple(tupleItems);\n }\n // Apply minItems/maxItems constraints to tuples\n if (typeof schema.minItems === \"number\") {\n zodSchema = zodSchema.check(z.minLength(schema.minItems));\n }\n if (typeof schema.maxItems === \"number\") {\n zodSchema = zodSchema.check(z.maxLength(schema.maxItems));\n }\n }\n else if (Array.isArray(items)) {\n // Tuple with items array (draft-7)\n const tupleItems = items.map((item) => convertSchema(item, ctx));\n const rest = schema.additionalItems && typeof schema.additionalItems === \"object\"\n ? convertSchema(schema.additionalItems, ctx)\n : undefined; // additionalItems: false means no rest, handled by default tuple behavior\n if (rest) {\n zodSchema = z.tuple(tupleItems).rest(rest);\n }\n else {\n zodSchema = z.tuple(tupleItems);\n }\n // Apply minItems/maxItems constraints to tuples\n if (typeof schema.minItems === \"number\") {\n zodSchema = zodSchema.check(z.minLength(schema.minItems));\n }\n if (typeof schema.maxItems === \"number\") {\n zodSchema = zodSchema.check(z.maxLength(schema.maxItems));\n }\n }\n else if (items !== undefined) {\n // Regular array\n const element = convertSchema(items, ctx);\n let arraySchema = z.array(element);\n // Apply constraints\n if (typeof schema.minItems === \"number\") {\n arraySchema = arraySchema.min(schema.minItems);\n }\n if (typeof schema.maxItems === \"number\") {\n arraySchema = arraySchema.max(schema.maxItems);\n }\n zodSchema = arraySchema;\n }\n else {\n // No items specified - array of any\n zodSchema = z.array(z.any());\n }\n break;\n }\n default:\n throw new Error(`Unsupported type: ${type}`);\n }\n // Apply metadata\n if (schema.description) {\n zodSchema = zodSchema.describe(schema.description);\n }\n if (schema.default !== undefined) {\n zodSchema = zodSchema.default(schema.default);\n }\n return zodSchema;\n}\nfunction convertSchema(schema, ctx) {\n if (typeof schema === \"boolean\") {\n return schema ? z.any() : z.never();\n }\n // Convert base schema first (ignoring composition keywords)\n let baseSchema = convertBaseSchema(schema, ctx);\n const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;\n // Process composition keywords LAST (they can appear together)\n // Handle anyOf - wrap base schema with union\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n const options = schema.anyOf.map((s) => convertSchema(s, ctx));\n const anyOfUnion = z.union(options);\n baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;\n }\n // Handle oneOf - exclusive union (exactly one must match)\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n const options = schema.oneOf.map((s) => convertSchema(s, ctx));\n const oneOfUnion = z.xor(options);\n baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;\n }\n // Handle allOf - wrap base schema with intersection\n if (schema.allOf && Array.isArray(schema.allOf)) {\n if (schema.allOf.length === 0) {\n baseSchema = hasExplicitType ? baseSchema : z.any();\n }\n else {\n let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);\n const startIdx = hasExplicitType ? 0 : 1;\n for (let i = startIdx; i < schema.allOf.length; i++) {\n result = z.intersection(result, convertSchema(schema.allOf[i], ctx));\n }\n baseSchema = result;\n }\n }\n // Handle nullable (OpenAPI 3.0)\n if (schema.nullable === true && ctx.version === \"openapi-3.0\") {\n baseSchema = z.nullable(baseSchema);\n }\n // Handle readOnly\n if (schema.readOnly === true) {\n baseSchema = z.readonly(baseSchema);\n }\n // Collect metadata: core schema keywords and unrecognized keys\n const extraMeta = {};\n // Core schema keywords that should be captured as metadata\n const coreMetadataKeys = [\"$id\", \"id\", \"$comment\", \"$anchor\", \"$vocabulary\", \"$dynamicRef\", \"$dynamicAnchor\"];\n for (const key of coreMetadataKeys) {\n if (key in schema) {\n extraMeta[key] = schema[key];\n }\n }\n // Content keywords - store as metadata\n const contentMetadataKeys = [\"contentEncoding\", \"contentMediaType\", \"contentSchema\"];\n for (const key of contentMetadataKeys) {\n if (key in schema) {\n extraMeta[key] = schema[key];\n }\n }\n // Unrecognized keys (custom metadata)\n for (const key of Object.keys(schema)) {\n if (!RECOGNIZED_KEYS.has(key)) {\n extraMeta[key] = schema[key];\n }\n }\n if (Object.keys(extraMeta).length > 0) {\n ctx.registry.add(baseSchema, extraMeta);\n }\n return baseSchema;\n}\n/**\n * Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */\nexport function fromJSONSchema(schema, params) {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? z.any() : z.never();\n }\n const version = detectVersion(schema, params?.defaultTarget);\n const defs = (schema.$defs || schema.definitions || {});\n const ctx = {\n version,\n defs,\n refs: new Map(),\n processing: new Set(),\n rootSchema: schema,\n registry: params?.registry ?? globalRegistry,\n };\n return convertSchema(schema, ctx);\n}\n", "import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n", "export * as core from \"../core/index.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./errors.js\";\nexport * from \"./parse.js\";\nexport * from \"./compat.js\";\n// zod-specified\nimport { config } from \"../core/index.js\";\nimport en from \"../locales/en.js\";\nconfig(en());\nexport { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from \"../core/index.js\";\nexport { toJSONSchema } from \"../core/json-schema-processors.js\";\nexport { fromJSONSchema } from \"./from-json-schema.js\";\nexport * as locales from \"../locales/index.js\";\n// iso\n// must be exported from top-level\n// https://github.com/colinhacks/zod/issues/4491\nexport { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from \"./iso.js\";\nexport * as iso from \"./iso.js\";\nexport * as coerce from \"./coerce.js\";\n", "import * as z from \"./v4/classic/external.js\";\nexport * from \"./v4/classic/external.js\";\nexport { z };\nexport default z;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Query DSL Specification\n * \n * Based on industry best practices from:\n * - Prisma ORM\n * - Strapi CMS\n * - TypeORM\n * - LoopBack Framework\n * \n * Version: 1.0.0\n * Status: Draft\n * \n * Objective: Define a JSON-based, database-agnostic query syntax standard\n * for data filtering interactions between frontend and backend APIs.\n * \n * Design Principles:\n * 1. Declarative: Frontend describes \"what data to get\", not \"how to query\"\n * 2. Database Agnostic: Syntax contains no database-specific directives\n * 3. Type Safe: Structure can be statically inferred by TypeScript\n * 4. Convention over Configuration: Implicit syntax for common queries\n */\n\n/**\n * Field Reference\n * Represents a reference to another field/column instead of a literal value.\n * Used for joins (ON clause) and cross-field comparisons.\n * \n * @example\n * // user.id = order.owner_id\n * { \"$eq\": { \"$field\": \"order.owner_id\" } }\n */\nexport const FieldReferenceSchema = z.object({\n $field: z.string().describe('Field Reference/Column Name')\n});\n\nexport type FieldReference = z.infer;\n\n// ============================================================================\n// 3.1 Comparison Operators\n// ============================================================================\n\n/**\n * Comparison operators for equality and inequality checks.\n * Supported data types: Any\n */\nexport const EqualityOperatorSchema = z.object({\n /** Equal to (default) - SQL: = | MongoDB: $eq */\n $eq: z.any().optional(),\n \n /** Not equal to - SQL: <> or != | MongoDB: $ne */\n $ne: z.any().optional(),\n});\n\n/**\n * Comparison operators for numeric and date comparisons.\n * Supported data types: Number, Date\n */\nexport const ComparisonOperatorSchema = z.object({\n /** Greater than - SQL: > | MongoDB: $gt */\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Greater than or equal to - SQL: >= | MongoDB: $gte */\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than - SQL: < | MongoDB: $lt */\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than or equal to - SQL: <= | MongoDB: $lte */\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n});\n\n// ============================================================================\n// 3.2 Set & Range Operators\n// ============================================================================\n\n/**\n * Set operators for membership checks.\n */\nexport const SetOperatorSchema = z.object({\n /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */\n $in: z.array(z.any()).optional(),\n \n /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */\n $nin: z.array(z.any()).optional(),\n});\n\n/**\n * Range operator for interval checks (closed interval).\n * SQL: BETWEEN ? AND ? | MongoDB: $gte AND $lte\n */\nexport const RangeOperatorSchema = z.object({\n /** Between (inclusive) - takes [min, max] array */\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n});\n\n// ============================================================================\n// 3.3 String-Specific Operators\n// ============================================================================\n\n/**\n * String pattern matching operators.\n * Note: Case sensitivity should be handled at backend level.\n */\nexport const StringOperatorSchema = z.object({\n /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */\n $contains: z.string().optional(),\n \n /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */\n $notContains: z.string().optional(),\n \n /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */\n $startsWith: z.string().optional(),\n \n /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */\n $endsWith: z.string().optional(),\n});\n\n// ============================================================================\n// 3.5 Special Operators\n// ============================================================================\n\n/**\n * Special check operators for null and existence.\n */\nexport const SpecialOperatorSchema = z.object({\n /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */\n $null: z.boolean().optional(),\n \n /** Field exists check (primarily for NoSQL) - MongoDB: $exists */\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// Combined Field Operators\n// ============================================================================\n\n/**\n * All field-level operators combined.\n * These can be applied to individual fields in a filter.\n */\nexport const FieldOperatorsSchema = z.object({\n // Equality\n $eq: z.any().optional(),\n $ne: z.any().optional(),\n \n // Comparison (numeric/date)\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n // Set & Range\n $in: z.array(z.any()).optional(),\n $nin: z.array(z.any()).optional(),\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n \n // String-specific\n $contains: z.string().optional(),\n $notContains: z.string().optional(),\n $startsWith: z.string().optional(),\n $endsWith: z.string().optional(),\n \n // Special\n $null: z.boolean().optional(),\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// 3.4 Logical Operators & Recursive Filter Structure\n// ============================================================================\n\n/**\n * Recursive filter type that supports:\n * 1. Implicit equality: { field: value }\n * 2. Explicit operators: { field: { $op: value } }\n * 3. Logical combinations: { $and: [...], $or: [...], $not: {...} }\n * 4. Nested relations: { relation: { field: value } }\n */\nexport type FilterCondition = {\n [key: string]: \n | any // Implicit equality: key: value\n | z.infer // Explicit operators: key: { $op: value }\n | FilterCondition; // Nested relation: key: { nested: ... }\n} & {\n /** Logical AND - combines all conditions that must be true */\n $and?: FilterCondition[];\n \n /** Logical OR - at least one condition must be true */\n $or?: FilterCondition[];\n \n /** Logical NOT - negates the condition */\n $not?: FilterCondition;\n};\n\n/**\n * Zod schema for recursive filter validation.\n * Uses z.lazy() to handle recursive structure.\n */\nexport const FilterConditionSchema: z.ZodType = z.lazy(() =>\n z.record(z.string(), z.unknown()).and(\n z.object({\n $and: z.array(FilterConditionSchema).optional(),\n $or: z.array(FilterConditionSchema).optional(),\n $not: FilterConditionSchema.optional(),\n })\n )\n);\n\n// ============================================================================\n// Query Filter Wrapper\n// ============================================================================\n\n/**\n * Top-level query filter wrapper.\n * This is typically used as the \"where\" clause in a query.\n * \n * @example\n * ```typescript\n * const filter: QueryFilter = {\n * where: {\n * status: \"active\", // Implicit equality\n * age: { $gte: 18 }, // Explicit operator\n * $or: [ // Logical combination\n * { role: \"admin\" },\n * { email: { $contains: \"@company.com\" } }\n * ],\n * profile: { // Nested relation\n * verified: true\n * }\n * }\n * }\n * ```\n */\nexport const QueryFilterSchema = z.object({\n where: FilterConditionSchema.optional(),\n});\n\n// ============================================================================\n// TypeScript Type Exports\n// ============================================================================\n\n/**\n * Type-safe filter operators for use in TypeScript.\n * \n * @example\n * ```typescript\n * type UserFilter = Filter;\n * \n * const filter: UserFilter = {\n * age: { $gte: 18 },\n * email: { $contains: \"@example.com\" }\n * };\n * ```\n */\nexport type Filter = {\n [K in keyof T]?: \n | T[K] // Implicit equality\n | {\n $eq?: T[K];\n $ne?: T[K];\n $gt?: T[K] extends number | Date ? T[K] : never;\n $gte?: T[K] extends number | Date ? T[K] : never;\n $lt?: T[K] extends number | Date ? T[K] : never;\n $lte?: T[K] extends number | Date ? T[K] : never;\n $in?: T[K][];\n $nin?: T[K][];\n $between?: T[K] extends number | Date ? [T[K], T[K]] : never;\n $contains?: T[K] extends string ? string : never;\n $notContains?: T[K] extends string ? string : never;\n $startsWith?: T[K] extends string ? string : never;\n $endsWith?: T[K] extends string ? string : never;\n $null?: boolean;\n $exists?: boolean;\n }\n | (T[K] extends object ? Filter : never); // Nested relation\n} & {\n $and?: Filter[];\n $or?: Filter[];\n $not?: Filter;\n};\n\n/**\n * Scalar types supported by the filter system.\n */\nexport type Scalar = string | number | boolean | Date | null;\n\n// Export inferred types\nexport type FieldOperators = z.infer;\nexport type QueryFilter = z.infer;\n\n// ============================================================================\n// Normalization Utilities (Internal Representation)\n// ============================================================================\n\n/**\n * Normalized filter AST structure.\n * This is the internal representation after converting all syntactic sugar\n * to explicit operators.\n * \n * Stage 1: Normalization Pass\n * Input: { age: 18, role: \"admin\" }\n * Output: { $and: [{ age: { $eq: 18 } }, { role: { $eq: \"admin\" } }] }\n * \n * This simplifies adapter implementation by providing a consistent structure.\n */\nexport const NormalizedFilterSchema: z.ZodType = z.lazy(() => \n z.object({\n $and: z.array(\n z.union([\n // Field condition: { field: { $op: value } }\n z.record(z.string(), FieldOperatorsSchema),\n // Nested logical group\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $or: z.array(\n z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $not: z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ]).optional(),\n })\n);\n\nexport type NormalizedFilter = z.infer;\n\n// ============================================================================\n// AST Array Format Detection & Validation\n// ============================================================================\n\n/**\n * Set of valid AST comparison operators (case-insensitive).\n * Used by `isFilterAST()` to validate AST structure beyond `Array.isArray`.\n */\nexport const VALID_AST_OPERATORS = new Set([\n '=', '==', '!=', '<>', '>', '>=', '<', '<=',\n 'in', 'nin', 'not_in',\n 'contains', 'notcontains', 'not_contains', 'like',\n 'startswith', 'starts_with',\n 'endswith', 'ends_with',\n 'between',\n 'is_null', 'is_not_null',\n]);\n\n/**\n * Detect whether a value is a valid Filter AST array structure.\n *\n * A valid AST is one of:\n * - Comparison node: `[field: string, operator: string, value: unknown]` where operator is a known operator\n * - Logical node: `[\"and\" | \"or\", ...children]` where children are valid AST nodes\n * - Legacy flat array: `[[cond], [cond], ...]` where all elements are sub-arrays (each a valid AST node)\n *\n * This replaces the naïve `Array.isArray(filter)` check, preventing accidental\n * misidentification of arbitrary arrays as filter ASTs.\n *\n * @example\n * isFilterAST([\"status\", \"=\", \"active\"]) // true\n * isFilterAST([\"and\", [\"a\", \"=\", 1], [\"b\", \">\", 2]]) // true\n * isFilterAST([[\"a\", \"=\", 1], [\"b\", \"=\", 2]]) // true (legacy)\n * isFilterAST([1, 2, 3]) // false\n * isFilterAST(\"not an array\") // false\n * isFilterAST({ status: \"active\" }) // false\n */\nexport function isFilterAST(filter: unknown): boolean {\n if (!Array.isArray(filter) || filter.length === 0) return false;\n\n const first = filter[0];\n\n // Logical node: [\"and\", ...] or [\"or\", ...]\n if (typeof first === 'string') {\n const lower = first.toLowerCase();\n if (lower === 'and' || lower === 'or') {\n return filter.length >= 2 && filter.slice(1).every((child: unknown) => isFilterAST(child));\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof filter[1] === 'string') {\n return VALID_AST_OPERATORS.has(filter[1].toLowerCase());\n }\n }\n\n // Legacy flat array: [[cond], [cond], ...]\n if (filter.every((item: unknown) => isFilterAST(item))) {\n return filter.length > 0;\n }\n\n return false;\n}\n\n// ============================================================================\n// AST Array → FilterCondition Conversion\n// ============================================================================\n\n/**\n * Operator mapping from AST infix operators to FilterCondition `$`-prefixed operators.\n */\nconst AST_OPERATOR_MAP: Record = {\n '=': '$eq',\n '==': '$eq',\n '!=': '$ne',\n '<>': '$ne',\n '>': '$gt',\n '>=': '$gte',\n '<': '$lt',\n '<=': '$lte',\n 'in': '$in',\n 'nin': '$nin',\n 'not_in': '$nin',\n 'contains': '$contains',\n 'notcontains': '$notContains',\n 'not_contains': '$notContains',\n 'like': '$contains',\n 'startswith': '$startsWith',\n 'starts_with': '$startsWith',\n 'endswith': '$endsWith',\n 'ends_with': '$endsWith',\n 'between': '$between',\n 'is_null': '$null',\n 'is_not_null': '$null',\n};\n\n/**\n * Convert a single AST comparison node `[field, operator, value]` to a FilterCondition object.\n */\nfunction convertComparison(node: [string, string, unknown]): FilterCondition {\n const [field, operator, value] = node;\n const op = operator.toLowerCase();\n\n // Special case: equality shorthand\n if (op === '=' || op === '==') {\n return { [field]: value } as FilterCondition;\n }\n\n // Null check operators\n if (op === 'is_null') {\n return { [field]: { $null: true } } as FilterCondition;\n }\n if (op === 'is_not_null') {\n return { [field]: { $null: false } } as FilterCondition;\n }\n\n const mapped = AST_OPERATOR_MAP[op];\n if (mapped) {\n return { [field]: { [mapped]: value } } as FilterCondition;\n }\n\n // Fallback: use the operator as-is with $ prefix\n return { [field]: { [`$${op}`]: value } } as FilterCondition;\n}\n\n/**\n * Parse a filter from AST array format to FilterCondition object format.\n *\n * The AST array format is used by the ObjectUI client and the `FilterBuilder`:\n * - Comparison: `[field, operator, value]` → `{ field: value }` or `{ field: { $op: value } }`\n * - Logical AND: `[\"and\", cond1, cond2, ...]` → `{ $and: [...] }`\n * - Logical OR: `[\"or\", cond1, cond2, ...]` → `{ $or: [...] }`\n *\n * If the input is already a FilterCondition object (not an array), it is returned as-is.\n * If the input is `null` or `undefined`, it is returned as-is.\n *\n * @example\n * // Simple condition\n * parseFilterAST([\"status\", \"=\", \"active\"])\n * // → { status: \"active\" }\n *\n * @example\n * // Compound AND\n * parseFilterAST([\"and\", [\"priority\", \"=\", \"high\"], [\"status\", \"=\", \"active\"]])\n * // → { $and: [{ priority: \"high\" }, { status: \"active\" }] }\n *\n * @example\n * // Object passthrough\n * parseFilterAST({ status: \"active\" })\n * // → { status: \"active\" }\n */\nexport function parseFilterAST(filter: unknown): FilterCondition | undefined {\n if (filter == null) return undefined;\n if (!Array.isArray(filter)) return filter as FilterCondition;\n if (filter.length === 0) return undefined;\n\n const first = filter[0];\n\n // Logical node: [\"and\", cond1, cond2, ...] or [\"or\", cond1, cond2, ...]\n if (typeof first === 'string' && (first.toLowerCase() === 'and' || first.toLowerCase() === 'or')) {\n const logicOp = `$${first.toLowerCase()}` as '$and' | '$or';\n const children = filter.slice(1).map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { [logicOp]: children } as FilterCondition;\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof first === 'string') {\n return convertComparison(filter as [string, string, unknown]);\n }\n\n // Legacy flat array: [[field, op, val], [field, op, val], ...]\n // All elements are sub-arrays → treat as implicit AND\n if (filter.every((item: unknown) => Array.isArray(item))) {\n const children = filter.map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { $and: children } as FilterCondition;\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Constants & Metadata\n// ============================================================================\n\n/**\n * All supported operator keys.\n * Useful for validation and parsing.\n */\nexport const FILTER_OPERATORS = [\n // Equality\n '$eq', '$ne',\n // Comparison\n '$gt', '$gte', '$lt', '$lte',\n // Set & Range\n '$in', '$nin', '$between',\n // String\n '$contains', '$notContains', '$startsWith', '$endsWith',\n // Special\n '$null', '$exists',\n] as const;\n\n/**\n * Logical operator keys.\n */\nexport const LOGICAL_OPERATORS = ['$and', '$or', '$not'] as const;\n\n/**\n * All operator keys (field + logical).\n */\nexport const ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS] as const;\n\nexport type FilterOperatorKey = typeof FILTER_OPERATORS[number];\nexport type LogicalOperatorKey = typeof LOGICAL_OPERATORS[number];\nexport type OperatorKey = typeof ALL_OPERATORS[number];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\n\n/**\n * Sort Node\n * Represents \"Order By\".\n */\nexport const SortNodeSchema = z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc']).default('asc')\n});\n\n/**\n * Aggregation Function Enum\n * Standard aggregation functions for data analysis.\n * \n * Supported Functions:\n * - **count**: Count rows (SQL: COUNT(*) or COUNT(field))\n * - **sum**: Sum numeric values (SQL: SUM(field))\n * - **avg**: Average numeric values (SQL: AVG(field))\n * - **min**: Minimum value (SQL: MIN(field))\n * - **max**: Maximum value (SQL: MAX(field))\n * - **count_distinct**: Count unique values (SQL: COUNT(DISTINCT field))\n * - **array_agg**: Aggregate values into array (SQL: ARRAY_AGG(field))\n * - **string_agg**: Concatenate values (SQL: STRING_AGG(field, delimiter))\n * \n * Performance Considerations:\n * - COUNT(*) is typically faster than COUNT(field) as it doesn't check for nulls\n * - COUNT DISTINCT may require additional memory for tracking unique values\n * - Window aggregates (with OVER clause) can be more efficient than subqueries\n * - Large GROUP BY operations benefit from proper indexing on grouped fields\n * \n * @example\n * // SQL: SELECT region, SUM(amount) FROM sales GROUP BY region\n * {\n * object: 'sales',\n * fields: ['region'],\n * aggregations: [\n * { function: 'sum', field: 'amount', alias: 'total_sales' }\n * ],\n * groupBy: ['region']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT COUNT(Id) FROM Account\n * {\n * object: 'account',\n * aggregations: [\n * { function: 'count', alias: 'total_accounts' }\n * ]\n * }\n */\nexport const AggregationFunction = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'array_agg', 'string_agg'\n]);\n\n/**\n * Aggregation Node\n * Represents an aggregated field with function.\n * \n * Aggregations summarize data across groups of rows (GROUP BY).\n * Used with `groupBy` to create analytical queries.\n * \n * @example\n * // SQL: SELECT customer_id, COUNT(*), SUM(amount) FROM orders GROUP BY customer_id\n * {\n * object: 'order',\n * fields: ['customer_id'],\n * aggregations: [\n * { function: 'count', alias: 'order_count' },\n * { function: 'sum', field: 'amount', alias: 'total_amount' }\n * ],\n * groupBy: ['customer_id']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT LeadSource, COUNT(Id) FROM Lead GROUP BY LeadSource\n * {\n * object: 'lead',\n * fields: ['lead_source'],\n * aggregations: [\n * { function: 'count', alias: 'lead_count' }\n * ],\n * groupBy: ['lead_source']\n * }\n */\nexport const AggregationNodeSchema = z.object({\n function: AggregationFunction.describe('Aggregation function'),\n field: z.string().optional().describe('Field to aggregate (optional for COUNT(*))'),\n alias: z.string().describe('Result column alias'),\n distinct: z.boolean().optional().describe('Apply DISTINCT before aggregation'),\n filter: FilterConditionSchema.optional().describe('Filter/Condition to apply to the aggregation (FILTER WHERE clause)'),\n});\n\n/**\n * Join Type Enum\n * Standard SQL join types for combining tables.\n * \n * Join Types:\n * - **inner**: Returns only matching rows from both tables (SQL: INNER JOIN)\n * - **left**: Returns all rows from left table, matching rows from right (SQL: LEFT JOIN)\n * - **right**: Returns all rows from right table, matching rows from left (SQL: RIGHT JOIN)\n * - **full**: Returns all rows from both tables (SQL: FULL OUTER JOIN)\n * \n * @example\n * // SQL: SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * on: ['order.customer_id', '=', 'customer.id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL-style: Find all customers and their orders (if any)\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * on: ['customer.id', '=', 'order.customer_id']\n * }\n * ]\n * }\n */\nexport const JoinType = z.enum(['inner', 'left', 'right', 'full']);\n\n/**\n * Join Execution Strategy\n * Hints to the query engine on how to execute the join.\n * \n * Strategies:\n * - **auto**: Engine decides best strategy (Default).\n * - **database**: Push down join to the database (Requires same datasource).\n * - **hash**: Load both sets into memory and hash join (Cross-datasource, memory intensive).\n * - **loop**: Nested loop lookup (N+1 safe version). (Good for small right-side lookups).\n */\nexport const JoinStrategy = z.enum(['auto', 'database', 'hash', 'loop']);\n\n/**\n * Join Node\n * Represents table joins for combining data from multiple objects.\n * \n * Joins connect related data across multiple tables using ON conditions.\n * Supports both direct object joins and subquery joins.\n * \n * @example\n * // SQL: SELECT o.*, c.name FROM orders o INNER JOIN customers c ON o.customer_id = c.id\n * {\n * object: 'order',\n * fields: ['id', 'amount'],\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Multi-table join\n * // SELECT * FROM orders o\n * // INNER JOIN customers c ON o.customer_id = c.id\n * // LEFT JOIN shipments s ON o.id = s.order_id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * },\n * {\n * type: 'left',\n * object: 'shipment',\n * alias: 's',\n * on: ['order.id', '=', 's.order_id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT Name, (SELECT LastName FROM Contacts) FROM Account\n * {\n * object: 'account',\n * fields: ['name'],\n * joins: [\n * {\n * type: 'left',\n * object: 'contact',\n * on: ['account.id', '=', 'contact.account_id']\n * }\n * ]\n * }\n * \n * @example\n * // Subquery Join: Join with a filtered/aggregated dataset\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * alias: 'high_value_orders',\n * on: ['customer.id', '=', 'high_value_orders.customer_id'],\n * subquery: {\n * object: 'order',\n * fields: ['customer_id', 'total'],\n * filters: ['total', '>', 1000]\n * }\n * }\n * ]\n * }\n */\nexport const JoinNodeSchema: z.ZodType = z.lazy(() => \n z.object({\n type: JoinType.describe('Join type'),\n strategy: JoinStrategy.optional().describe('Execution strategy hint'),\n object: z.string().describe('Object/table to join'),\n alias: z.string().optional().describe('Table alias'),\n on: FilterConditionSchema.describe('Join condition'),\n subquery: z.lazy(() => QuerySchema).optional().describe('Subquery instead of object'),\n })\n);\n\n/**\n * Window Function Enum\n * Advanced analytical functions for row-based calculations.\n * \n * Window Functions:\n * - **row_number**: Sequential number within partition (SQL: ROW_NUMBER() OVER (...))\n * - **rank**: Rank with gaps for ties (SQL: RANK() OVER (...))\n * - **dense_rank**: Rank without gaps (SQL: DENSE_RANK() OVER (...))\n * - **percent_rank**: Relative rank as percentage (SQL: PERCENT_RANK() OVER (...))\n * - **lag**: Access previous row value (SQL: LAG(field) OVER (...))\n * - **lead**: Access next row value (SQL: LEAD(field) OVER (...))\n * - **first_value**: First value in window (SQL: FIRST_VALUE(field) OVER (...))\n * - **last_value**: Last value in window (SQL: LAST_VALUE(field) OVER (...))\n * - **sum/avg/count/min/max**: Aggregates over window (SQL: SUM(field) OVER (...))\n * \n * @example\n * // SQL: SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) as rank\n * // FROM orders\n * {\n * object: 'order',\n * fields: ['id', 'customer_id', 'amount'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'rank',\n * over: {\n * partitionBy: ['customer_id'],\n * orderBy: [{ field: 'amount', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Running total with SUM() OVER (...)\n * {\n * object: 'transaction',\n * fields: ['date', 'amount'],\n * windowFunctions: [\n * {\n * function: 'sum',\n * field: 'amount',\n * alias: 'running_total',\n * over: {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: 'UNBOUNDED PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunction = z.enum([\n 'row_number', 'rank', 'dense_rank', 'percent_rank',\n 'lag', 'lead', 'first_value', 'last_value',\n 'sum', 'avg', 'count', 'min', 'max'\n]);\n\n/**\n * Window Specification\n * Defines PARTITION BY and ORDER BY for window functions.\n * \n * Window specifications control how window functions compute values:\n * - **partitionBy**: Divide rows into groups (like GROUP BY but without collapsing rows)\n * - **orderBy**: Define order for ranking and offset functions\n * - **frame**: Specify which rows to include in aggregate calculations\n * \n * @example\n * // Partition by department, order by salary\n * {\n * partitionBy: ['department'],\n * orderBy: [{ field: 'salary', order: 'desc' }]\n * }\n * \n * @example\n * // Moving average with frame specification\n * {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: '6 PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n */\nexport const WindowSpecSchema = z.object({\n partitionBy: z.array(z.string()).optional().describe('PARTITION BY fields'),\n orderBy: z.array(SortNodeSchema).optional().describe('ORDER BY specification'),\n frame: z.object({\n type: z.enum(['rows', 'range']).optional(),\n start: z.string().optional().describe('Frame start (e.g., \"UNBOUNDED PRECEDING\", \"1 PRECEDING\")'),\n end: z.string().optional().describe('Frame end (e.g., \"CURRENT ROW\", \"1 FOLLOWING\")'),\n }).optional().describe('Window frame specification'),\n});\n\n/**\n * Window Function Node\n * Represents window function with OVER clause.\n * \n * Window functions perform calculations across a set of rows related to the current row,\n * without collapsing the result set (unlike GROUP BY aggregations).\n * \n * @example\n * // SQL: Top 3 products per category\n * // SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as rank\n * // FROM products\n * {\n * object: 'product',\n * fields: ['name', 'category', 'sales'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'category_rank',\n * over: {\n * partitionBy: ['category'],\n * orderBy: [{ field: 'sales', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Year-over-year comparison with LAG\n * {\n * object: 'monthly_sales',\n * fields: ['month', 'revenue'],\n * windowFunctions: [\n * {\n * function: 'lag',\n * field: 'revenue',\n * alias: 'prev_year_revenue',\n * over: {\n * orderBy: [{ field: 'month', order: 'asc' }]\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunctionNodeSchema = z.object({\n function: WindowFunction.describe('Window function name'),\n field: z.string().optional().describe('Field to operate on (for aggregate window functions)'),\n alias: z.string().describe('Result column alias'),\n over: WindowSpecSchema.describe('Window specification (OVER clause)'),\n});\n\n/**\n * Field Selection Node\n * Represents \"Select\" attributes, including joins.\n */\nexport const FieldNodeSchema: z.ZodType = z.lazy(() => \n z.union([\n z.string(), // Primitive field: \"name\"\n z.object({\n field: z.string(), // Relationship field: \"owner\"\n fields: z.array(FieldNodeSchema).optional(), // Nested select: [\"name\", \"email\"]\n alias: z.string().optional()\n })\n ])\n);\n\n/**\n * Full-Text Search Configuration\n * Defines full-text search parameters for text queries.\n * \n * Supports:\n * - Multi-field search\n * - Relevance scoring\n * - Fuzzy matching\n * - Language-specific analyzers\n * \n * @example\n * {\n * query: \"John Smith\",\n * fields: [\"name\", \"email\", \"description\"],\n * fuzzy: true,\n * boost: { \"name\": 2.0, \"email\": 1.5 }\n * }\n */\nexport const FullTextSearchSchema = z.object({\n query: z.string().describe('Search query text'),\n fields: z.array(z.string()).optional().describe('Fields to search in (if not specified, searches all text fields)'),\n fuzzy: z.boolean().optional().default(false).describe('Enable fuzzy matching (tolerates typos)'),\n operator: z.enum(['and', 'or']).optional().default('or').describe('Logical operator between terms'),\n boost: z.record(z.string(), z.number()).optional().describe('Field-specific relevance boosting (field name -> boost factor)'),\n minScore: z.number().optional().describe('Minimum relevance score threshold'),\n language: z.string().optional().describe('Language for text analysis (e.g., \"en\", \"zh\", \"es\")'),\n highlight: z.boolean().optional().default(false).describe('Enable search result highlighting'),\n});\n\nexport type FullTextSearch = z.infer;\n\n/**\n * Query AST Schema\n * The universal data retrieval contract defined in `ast-structure.mdx`.\n * \n * This schema represents ObjectQL - a universal query language that abstracts\n * SQL, NoSQL, and SaaS APIs into a single unified interface.\n * \n * Updates (v2):\n * - Aligned with modern ORM standards (Prisma/TypeORM)\n * - Added `cursor` based pagination support\n * - Renamed `top`/`skip` to `limit`/`offset`\n * - Unified filtering syntax with `FilterConditionSchema`\n * \n * Updates (v3):\n * - Added `search` parameter for full-text search (P2 requirement)\n * \n * @example\n * // Simple query: SELECT name, email FROM account WHERE status = 'active'\n * {\n * object: 'account',\n * fields: ['name', 'email'],\n * where: { status: 'active' }\n * }\n * \n * @example\n * // Pagination with Limit/Offset\n * {\n * object: 'post',\n * where: { published: true },\n * orderBy: [{ field: 'created_at', order: 'desc' }],\n * limit: 20,\n * offset: 40\n * }\n * \n * @example\n * // Full-text search\n * {\n * object: 'article',\n * search: {\n * query: \"machine learning\",\n * fields: [\"title\", \"content\"],\n * fuzzy: true,\n * boost: { \"title\": 2.0 }\n * },\n * limit: 10\n * }\n */\nconst BaseQuerySchema = z.object({\n /** Target Entity */\n object: z.string().describe('Object name (e.g. account)'),\n \n /** Select Clause */\n fields: z.array(FieldNodeSchema).optional().describe('Fields to retrieve'),\n \n /** Where Clause (Filtering) */\n where: FilterConditionSchema.optional().describe('Filtering criteria (WHERE)'),\n \n /** Full-Text Search */\n search: FullTextSearchSchema.optional().describe('Full-text search configuration ($search parameter)'),\n \n /** Order By Clause (Sorting) */\n orderBy: z.array(SortNodeSchema).optional().describe('Sorting instructions (ORDER BY)'),\n \n /** Pagination */\n limit: z.number().optional().describe('Max records to return (LIMIT)'),\n offset: z.number().optional().describe('Records to skip (OFFSET)'),\n top: z.number().optional().describe('Alias for limit (OData compatibility)'),\n cursor: z.record(z.string(), z.unknown()).optional().describe('Cursor for keyset pagination'),\n \n /** Joins */\n joins: z.array(JoinNodeSchema).optional().describe('Explicit Table Joins'),\n \n /** Aggregations */\n aggregations: z.array(AggregationNodeSchema).optional().describe('Aggregation functions'),\n \n /** Group By Clause */\n groupBy: z.array(z.string()).optional().describe('GROUP BY fields'),\n \n /** Having Clause */\n having: FilterConditionSchema.optional().describe('HAVING clause for aggregation filtering'),\n \n /** Window Functions */\n windowFunctions: z.array(WindowFunctionNodeSchema).optional().describe('Window functions with OVER clause'),\n \n /** Subquery flag */\n distinct: z.boolean().optional().describe('SELECT DISTINCT flag'),\n});\n\n/**\n * QueryAST — Abstract Syntax Tree for data queries.\n *\n * The `expand` property enables recursive loading of related records through\n * lookup and master_detail fields. Each key is a relationship field name; the\n * value is a nested QueryAST that can further filter, select, sort, and expand\n * the related records (up to a default max depth of 3).\n *\n * @example\n * ```ts\n * const ast: QueryAST = {\n * object: 'task',\n * fields: ['title', 'assignee'],\n * expand: {\n * assignee: { object: 'user', fields: ['name', 'email'] },\n * project: {\n * object: 'project',\n * expand: { org: { object: 'org' } } // nested expand\n * }\n * }\n * };\n * ```\n */\nexport type QueryAST = z.infer & {\n expand?: Record;\n};\n\nexport type QueryInput = z.input & {\n expand?: Record;\n};\n\nexport const QuerySchema: z.ZodType = BaseQuerySchema.extend({\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional().describe(\n 'Recursive relation loading map. Keys are lookup/master_detail field names; '\n + 'values are nested QueryAST objects that control select, filter, sort, and '\n + 'further expansion on the related object. The engine resolves expand via '\n + 'batch $in queries (driver-agnostic) with a default max depth of 3.'\n ),\n});\n\nexport type SortNode = z.infer;\nexport type AggregationNode = z.infer;\nexport type JoinNode = z.infer;\nexport type WindowFunctionNode = z.infer;\nexport type WindowSpec = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # ObjectStack Validation Protocol\n * \n * This module defines the validation schema protocol for ObjectStack, providing a comprehensive\n * type-safe validation system similar to Salesforce's validation rules but with enhanced capabilities.\n * \n * ## Overview\n * \n * Validation rules are applied at the data layer to ensure data integrity and enforce business logic.\n * The system supports multiple validation types:\n * \n * 1. **Script Validation**: Formula-based validation using expressions\n * 2. **Uniqueness Validation**: Enforce unique constraints across fields\n * 3. **State Machine Validation**: Control allowed state transitions\n * 4. **Format Validation**: Validate field formats (email, URL, regex, etc.)\n * 5. **Cross-Field Validation**: Validate relationships between multiple fields\n * 6. **Async Validation**: Remote validation via API calls\n * 7. **Custom Validation**: User-defined validation functions\n * 8. **Conditional Validation**: Apply validations based on conditions\n * \n * ## Salesforce Comparison\n * \n * ObjectStack validation rules are inspired by Salesforce validation rules but enhanced:\n * - Salesforce: Formula-based validation with `Error Condition Formula`\n * - ObjectStack: Multiple validation types with composable rules\n * \n * Example Salesforce validation rule:\n * ```\n * Rule Name: Discount_Cannot_Exceed_40_Percent\n * Error Condition Formula: Discount_Percent__c > 0.40\n * Error Message: Discount cannot exceed 40%.\n * ```\n * \n * Equivalent ObjectStack rule:\n * ```typescript\n * {\n * type: 'script',\n * name: 'discount_cannot_exceed_40_percent',\n * condition: 'discount_percent > 0.40',\n * message: 'Discount cannot exceed 40%',\n * severity: 'error'\n * }\n * ```\n */\n\n/**\n * Base Validation Rule\n * \n * All validation rules extend from this base schema with common properties.\n * \n * ## Industry Standard Enhancements\n * - **Label/Description**: Essential for governance in large systems with thousands of rules.\n * - **Events**: granular control over validation timing (Context-aware validation).\n * - **Tags**: categorization for reporting and management.\n */\nconst BaseValidationSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label for the rule listing'),\n description: z.string().optional().describe('Administrative notes explaining the business reason'),\n \n // Execution Control\n active: z.boolean().default(true),\n events: z.array(z.enum(['insert', 'update', 'delete'])).default(['insert', 'update']).describe('Validation contexts'),\n priority: z.number().int().min(0).max(9999).default(100).describe('Execution priority (lower runs first, default: 100)'),\n \n // Classification\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g., \"compliance\", \"billing\")'),\n \n // Feedback\n severity: z.enum(['error', 'warning', 'info']).default('error'),\n message: z.string().describe('Error message to display to the user'),\n});\n\n/**\n * 1. Script/Expression Validation\n * Generic formula-based validation.\n */\nexport const ScriptValidationSchema = BaseValidationSchema.extend({\n type: z.literal('script'),\n condition: z.string().describe('Formula expression. If TRUE, validation fails. (e.g. amount < 0)'),\n});\n\n/**\n * 2. Uniqueness Validation\n * specialized optimized check for unique constraints.\n */\nexport const UniquenessValidationSchema = BaseValidationSchema.extend({\n type: z.literal('unique'),\n fields: z.array(z.string()).describe('Fields that must be combined unique'),\n scope: z.string().optional().describe('Formula condition for scope (e.g. active = true)'),\n caseSensitive: z.boolean().default(true),\n});\n\n/**\n * 3. State Machine Validation\n * State transition logic.\n */\nexport const StateMachineValidationSchema = BaseValidationSchema.extend({\n type: z.literal('state_machine'),\n field: z.string().describe('State field (e.g. status)'),\n transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'),\n});\n\n/**\n * 4. Value Format Validation\n * Regex or specialized formats.\n */\nexport const FormatValidationSchema = BaseValidationSchema.extend({\n type: z.literal('format'),\n field: z.string(),\n regex: z.string().optional(),\n format: z.enum(['email', 'url', 'phone', 'json']).optional(),\n});\n\n/**\n * 5. Cross-Field Validation\n * Validates relationships between multiple fields.\n * \n * ## Use Cases\n * - Date range validations (end_date > start_date)\n * - Amount comparisons (discount < total)\n * - Complex business rules involving multiple fields\n * \n * ## Salesforce Examples\n * \n * ### Example 1: Close Date Must Be In Current or Future Month\n * **Salesforce Formula:**\n * ```\n * MONTH(CloseDate) < MONTH(TODAY()) ||\n * YEAR(CloseDate) < YEAR(TODAY())\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'close_date_future',\n * condition: 'MONTH(close_date) >= MONTH(TODAY()) AND YEAR(close_date) >= YEAR(TODAY())',\n * fields: ['close_date'],\n * message: 'Close Date must be in the current or a future month'\n * }\n * ```\n * \n * ### Example 2: Discount Validation\n * **Salesforce Formula:**\n * ```\n * Discount__c > (Amount__c * 0.40)\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'discount_limit',\n * condition: 'discount > (amount * 0.40)',\n * fields: ['discount', 'amount'],\n * message: 'Discount cannot exceed 40% of the amount'\n * }\n * ```\n * \n * ### Example 3: Opportunity Must Have Products\n * **Salesforce Formula:**\n * ```\n * ISBLANK(Products__c) && ISPICKVAL(StageName, \"Closed Won\")\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'products_required_for_won',\n * condition: 'products = null AND stage = \"closed_won\"',\n * fields: ['products', 'stage'],\n * message: 'Opportunity must have products to be marked as Closed Won'\n * }\n * ```\n */\nexport const CrossFieldValidationSchema = BaseValidationSchema.extend({\n type: z.literal('cross_field'),\n condition: z.string().describe('Formula expression comparing fields (e.g. \"end_date > start_date\")'),\n fields: z.array(z.string()).describe('Fields involved in the validation'),\n});\n\n/**\n * 6. JSON Structure Validation\n * Validates JSON fields against a JSON Schema.\n * \n * ## Use Cases\n * - Validating configuration objects stored in JSON fields\n * - Enforcing API payload structures\n * - Complex nested data validation\n */\nexport const JSONValidationSchema = BaseValidationSchema.extend({\n type: z.literal('json_schema'),\n field: z.string().describe('JSON field to validate'),\n schema: z.record(z.string(), z.unknown()).describe('JSON Schema object definition'),\n});\n\n/**\n * 7. Async Validation\n * Remote validation via API call or database query.\n * \n * ## Use Cases\n * \n * ### 1. Email Uniqueness Check\n * Check if an email address is already registered in the system.\n * ```typescript\n * {\n * type: 'async',\n * name: 'unique_email',\n * field: 'email',\n * validatorUrl: '/api/users/check-email',\n * message: 'This email address is already registered',\n * debounce: 500, // Wait 500ms after user stops typing\n * timeout: 3000\n * }\n * ```\n * \n * ### 2. Username Availability\n * Verify username is available before form submission.\n * ```typescript\n * {\n * type: 'async',\n * name: 'username_available',\n * field: 'username',\n * validatorUrl: '/api/users/check-username',\n * message: 'This username is already taken',\n * debounce: 300,\n * timeout: 2000\n * }\n * ```\n * \n * ### 3. Tax ID Validation\n * Validate tax ID with government API (e.g., IRS, HMRC).\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_tax_id',\n * field: 'tax_id',\n * validatorFunction: 'validateTaxIdWithIRS',\n * message: 'Invalid Tax ID number',\n * timeout: 10000, // Government APIs may be slow\n * params: { country: 'US', format: 'EIN' }\n * }\n * ```\n * \n * ### 4. Credit Card Validation\n * Verify credit card with payment gateway without charging.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_card',\n * field: 'card_number',\n * validatorUrl: 'https://api.stripe.com/v1/tokens/validate',\n * message: 'Invalid credit card number',\n * timeout: 5000,\n * params: { \n * mode: 'validate_only',\n * checkFunds: false \n * }\n * }\n * ```\n * \n * ### 5. Address Validation\n * Validate and standardize addresses using geocoding services.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_address',\n * field: 'street_address',\n * validatorFunction: 'validateAddressWithGoogleMaps',\n * message: 'Unable to verify address',\n * timeout: 4000,\n * params: {\n * includeFields: ['city', 'state', 'zip'],\n * strictMode: true,\n * country: 'US'\n * }\n * }\n * ```\n * \n * ### 6. Domain Name Availability\n * Check if domain name is available for registration.\n * ```typescript\n * {\n * type: 'async',\n * name: 'domain_available',\n * field: 'domain_name',\n * validatorUrl: '/api/domains/check-availability',\n * message: 'This domain is already taken or reserved',\n * debounce: 500,\n * timeout: 2000\n * }\n * ```\n * \n * ### 7. Coupon Code Validation\n * Verify coupon code is valid and not expired.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_coupon',\n * field: 'coupon_code',\n * validatorUrl: '/api/coupons/validate',\n * message: 'Invalid or expired coupon code',\n * timeout: 2000,\n * params: {\n * checkExpiration: true,\n * checkUsageLimit: true,\n * userId: '{{current_user_id}}'\n * }\n * }\n * ```\n */\nexport const AsyncValidationSchema = BaseValidationSchema.extend({\n type: z.literal('async'),\n field: z.string().describe('Field to validate'),\n validatorUrl: z.string().optional().describe('External API endpoint for validation'),\n method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method for external call'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for the request'),\n validatorFunction: z.string().optional().describe('Reference to custom validator function'),\n timeout: z.number().optional().default(5000).describe('Timeout in milliseconds'),\n debounce: z.number().optional().describe('Debounce delay in milliseconds'),\n params: z.record(z.string(), z.unknown()).optional().describe('Additional parameters to pass to validator'),\n});\n\n/**\n * 8. Custom Validator Function\n * User-defined validation logic with code reference.\n */\nexport const CustomValidatorSchema = BaseValidationSchema.extend({\n type: z.literal('custom'),\n handler: z.string().describe('Name of the custom validation function registered in the system'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the custom handler'),\n});\n\n/**\n * 9. Master Validation Rule Schema\n */\n/** Base type for validation rules - used for z.lazy() recursive type annotation */\nexport interface BaseValidationRuleShape {\n type: string;\n name: string;\n message: string;\n label?: string;\n description?: string;\n active?: boolean;\n events?: ('insert' | 'update' | 'delete')[];\n priority?: number;\n tags?: string[];\n severity?: 'error' | 'warning' | 'info';\n [key: string]: unknown;\n}\n\nexport const ValidationRuleSchema: z.ZodType = z.lazy(() =>\n z.discriminatedUnion('type', [\n ScriptValidationSchema,\n UniquenessValidationSchema,\n StateMachineValidationSchema,\n FormatValidationSchema,\n CrossFieldValidationSchema,\n JSONValidationSchema,\n AsyncValidationSchema,\n CustomValidatorSchema,\n ConditionalValidationSchema,\n ])\n);\n\n/**\n * 8. Conditional Validation\n * Validation that only applies when a condition is met.\n * \n * ## Overview\n * Conditional validations follow the pattern: \"Validate X only if Y is true\"\n * This allows for context-aware validation rules that adapt to different scenarios.\n * \n * ## Use Cases\n * \n * ### 1. Validate Based on Record Type\n * Apply different validation rules based on the type of record.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_approval_required',\n * when: 'account_type = \"enterprise\"',\n * message: 'Enterprise validation',\n * then: {\n * type: 'script',\n * name: 'require_approval',\n * message: 'Enterprise accounts require manager approval',\n * condition: 'approval_status = null'\n * }\n * }\n * ```\n * \n * ### 2. Conditional Field Requirements\n * Require certain fields only when specific conditions are met.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'shipping_address_when_required',\n * when: 'requires_shipping = true',\n * message: 'Shipping validation',\n * then: {\n * type: 'script',\n * name: 'shipping_address_required',\n * message: 'Shipping address is required for physical products',\n * condition: 'shipping_address = null OR shipping_address = \"\"'\n * }\n * }\n * ```\n * \n * ### 3. Amount-Based Validation\n * Apply different rules based on transaction amount.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'high_value_approval',\n * when: 'order_total > 10000',\n * message: 'High value order validation',\n * then: {\n * type: 'script',\n * name: 'manager_approval_required',\n * message: 'Orders over $10,000 require manager approval',\n * condition: 'manager_approval_id = null'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'standard_validation',\n * message: 'Payment method is required',\n * condition: 'payment_method = null'\n * }\n * }\n * ```\n * \n * ### 4. Regional Compliance\n * Apply region-specific validation rules.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'regional_compliance',\n * when: 'region = \"EU\"',\n * message: 'EU compliance validation',\n * then: {\n * type: 'script',\n * name: 'gdpr_consent',\n * message: 'GDPR consent is required for EU customers',\n * condition: 'gdpr_consent_given = false'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'tos_acceptance',\n * message: 'Terms of Service acceptance required',\n * condition: 'tos_accepted = false'\n * }\n * }\n * ```\n * \n * ### 5. Nested Conditional Validation\n * Create complex validation logic with nested conditions.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'country_state_validation',\n * when: 'country = \"US\"',\n * message: 'US-specific validation',\n * then: {\n * type: 'conditional',\n * name: 'california_validation',\n * when: 'state = \"CA\"',\n * message: 'California-specific validation',\n * then: {\n * type: 'script',\n * name: 'ca_tax_id_required',\n * message: 'California requires a valid tax ID',\n * condition: 'tax_id = null OR NOT(REGEX(tax_id, \"^\\\\d{2}-\\\\d{7}$\"))'\n * }\n * }\n * }\n * ```\n * \n * ### 6. Tax Validation for Taxable Items\n * Only validate tax fields when the item is taxable.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'tax_field_validation',\n * when: 'is_taxable = true',\n * message: 'Tax validation',\n * then: {\n * type: 'script',\n * name: 'tax_code_required',\n * message: 'Tax code is required for taxable items',\n * condition: 'tax_code = null OR tax_code = \"\"'\n * }\n * }\n * ```\n * \n * ### 7. Role-Based Validation\n * Apply validation based on user role.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'role_based_approval_limit',\n * when: 'user_role = \"manager\"',\n * message: 'Manager approval limits',\n * then: {\n * type: 'script',\n * name: 'manager_limit',\n * message: 'Managers can approve up to $50,000',\n * condition: 'approval_amount > 50000'\n * }\n * }\n * ```\n * \n * ## Salesforce Pattern Comparison\n * \n * Salesforce doesn't have explicit \"conditional validation\" rules but achieves similar\n * behavior using formula logic. ObjectStack makes this pattern explicit and composable.\n * \n * **Salesforce Approach:**\n * ```\n * IF(\n * ISPICKVAL(Type, \"Enterprise\"),\n * AND(Amount > 100000, ISBLANK(Approval__c)),\n * FALSE\n * )\n * ```\n * \n * **ObjectStack Approach:**\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_high_value',\n * when: 'type = \"enterprise\"',\n * then: {\n * type: 'cross_field',\n * name: 'amount_approval',\n * condition: 'amount > 100000 AND approval = null',\n * fields: ['amount', 'approval']\n * }\n * }\n * ```\n */\nexport const ConditionalValidationSchema = BaseValidationSchema.extend({\n type: z.literal('conditional'),\n when: z.string().describe('Condition formula (e.g. \"type = \\'enterprise\\'\")'),\n then: ValidationRuleSchema.describe('Validation rule to apply when condition is true'),\n otherwise: ValidationRuleSchema.optional().describe('Validation rule to apply when condition is false'),\n});\n\nexport type ValidationRule = z.infer;\nexport type ScriptValidation = z.infer;\nexport type UniquenessValidation = z.infer;\nexport type StateMachineValidation = z.infer;\nexport type FormatValidation = z.infer;\nexport type CrossFieldValidation = z.infer;\nexport type JSONValidation = z.infer;\nexport type AsyncValidation = z.infer;\nexport type CustomValidation = z.infer;\nexport type ConditionalValidation = z.infer;", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * XState-inspired State Machine Protocol\n * Used to define strict business logic constraints and lifecycle management.\n * Prevent AI \"hallucinations\" by enforcing valid valid transitions.\n */\n\n// --- Primitives ---\n\n/**\n * References a named action (side effect)\n * Can be a script, a webhook, or a field update.\n */\nexport const ActionRefSchema = z.union([\n z.string().describe('Action Name'),\n z.object({\n type: z.string(), // e.g., 'xstate.assign', 'log', 'email'\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n/**\n * References a named condition (guard)\n * Must evaluate to true for the transition to occur.\n */\nexport const GuardRefSchema = z.union([\n z.string().describe('Guard Name (e.g., \"isManager\", \"amountGT1000\")'),\n z.object({\n type: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n// --- Core Structure ---\n\n/**\n * State Transition Definition\n * \"When EVENT happens, if GUARD is true, go to TARGET and run ACTIONS\"\n */\nexport const TransitionSchema = z.object({\n target: z.string().optional().describe('Target State ID'),\n cond: GuardRefSchema.optional().describe('Condition (Guard) required to take this path'),\n actions: z.array(ActionRefSchema).optional().describe('Actions to execute during transition'),\n description: z.string().optional().describe('Human readable description of this rule'),\n});\n\n/**\n * Event Definition (Signals)\n */\nexport const EventSchema = z.object({\n type: z.string().describe('Event Type (e.g. \"APPROVE\", \"REJECT\", \"Submit\")'),\n // Payload validation schema could go here if we want deep validation\n schema: z.record(z.string(), z.unknown()).optional().describe('Expected event payload structure'),\n});\n\nexport type ActionRef = z.infer;\nexport type Transition = z.infer;\n\nexport type StateNodeConfig = {\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n entry?: ActionRef[];\n exit?: ActionRef[];\n on?: Record;\n always?: Transition[];\n initial?: string;\n states?: Record;\n meta?: {\n label?: string;\n description?: string;\n color?: string;\n aiInstructions?: string;\n };\n};\n\n/**\n * State Node Definition\n */\nexport const StateNodeSchema: z.ZodType = z.lazy(() => z.object({\n /** Type of state */\n type: z.enum(['atomic', 'compound', 'parallel', 'final', 'history']).default('atomic'),\n \n /** Entry/Exit Actions */\n entry: z.array(ActionRefSchema).optional().describe('Actions to run when entering this state'),\n exit: z.array(ActionRefSchema).optional().describe('Actions to run when leaving this state'),\n \n /** Transitions (Events) */\n on: z.record(z.string(), z.union([\n z.string(), // Shorthand target\n TransitionSchema, \n z.array(TransitionSchema)\n ])).optional().describe('Map of Event Type -> Transition Definition'),\n \n /** Always Transitions (Eventless) */\n always: z.array(TransitionSchema).optional(),\n\n /** Nesting (Hierarchical States) */\n initial: z.string().optional().describe('Initial child state (if compound)'),\n states: z.record(z.string(), StateNodeSchema).optional(),\n \n /** Metadata for UI/AI */\n meta: z.object({\n label: z.string().optional(),\n description: z.string().optional(),\n color: z.string().optional(), // For UI diagrams\n // Instructions for AI Agent when in this state\n aiInstructions: z.string().optional().describe('Specific instructions for AI when in this state'),\n }).optional(),\n}));\n\n/**\n * Top-Level State Machine Definition\n */\nexport const StateMachineSchema = z.object({\n id: SnakeCaseIdentifierSchema.describe('Unique Machine ID'),\n description: z.string().optional(),\n \n /** Context (Memory) Schema */\n contextSchema: z.record(z.string(), z.unknown()).optional().describe('Zod Schema for the machine context/memory'),\n \n /** Initial State */\n initial: z.string().describe('Initial State ID'),\n \n /** State Definitions */\n states: z.record(z.string(), StateNodeSchema).describe('State Nodes'),\n \n /** Global Listeners */\n on: z.record(z.string(), z.union([z.string(), TransitionSchema, z.array(TransitionSchema)])).optional(),\n});\n\nexport type StateMachineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from './field.zod';\nimport { ValidationRuleSchema } from './validation.zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\nimport { ActionSchema } from '../ui/action.zod';\n\n/**\n * API Operations Enum\n */\nexport const ApiMethod = z.enum([\n 'get', 'list', // Read\n 'create', 'update', 'delete', // Write\n 'upsert', // Idempotent Write\n 'bulk', // Batch operations\n 'aggregate', // Analytics (count, sum)\n 'history', // Audit access\n 'search', // Search access\n 'restore', 'purge', // Trash management\n 'import', 'export', // Data portability\n]);\nexport type ApiMethod = z.infer;\n\n/**\n * Capability Flags\n * Defines what system features are enabled for this object.\n * \n * Optimized based on industry standards (Salesforce, ServiceNow):\n * - Added `activities` (Tasks/Events)\n * - Added `mru` (Recent Items)\n * - Added `feeds` (Social/Chatter)\n * - Grouped API permissions\n * \n * @example\n * {\n * trackHistory: true,\n * searchable: true,\n * apiEnabled: true,\n * files: true\n * }\n */\nexport const ObjectCapabilities = z.object({\n /** Enable history tracking (Audit Trail) */\n trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),\n \n /** Enable global search indexing */\n searchable: z.boolean().default(true).describe('Index records for global search'),\n \n /** Enable REST/GraphQL API access */\n apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),\n\n /** \n * API Supported Operations\n * Granular control over API exposure.\n */\n apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),\n \n /** Enable standard attachments/files engine */\n files: z.boolean().default(false).describe('Enable file attachments and document management'),\n \n /** Enable social collaboration (Comments, Mentions, Feeds) */\n feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),\n \n /** Enable standard Activity suite (Tasks, Calendars, Events) */\n activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),\n \n /** Enable Recycle Bin / Soft Delete */\n trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),\n\n /** Enable \"Recently Viewed\" tracking */\n mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),\n \n /** Allow cloning records */\n clone: z.boolean().default(true).describe('Allow record deep cloning'),\n});\n\n/**\n * Schema for database indexes.\n * Enhanced with additional index types and configuration options\n * \n * @example\n * {\n * name: \"idx_account_name\",\n * fields: [\"name\"],\n * type: \"btree\",\n * unique: true\n * }\n */\nexport const IndexSchema = z.object({\n name: z.string().optional().describe('Index name (auto-generated if not provided)'),\n fields: z.array(z.string()).describe('Fields included in the index'),\n type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),\n unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),\n partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),\n});\n\n/**\n * Search Configuration\n * Defines how this object behaves in search results.\n * \n * @example\n * {\n * fields: [\"name\", \"email\", \"phone\"],\n * displayFields: [\"name\", \"title\"],\n * filters: [\"status = 'active'\"]\n * }\n */\nexport const SearchConfigSchema = z.object({\n fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),\n displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),\n filters: z.array(z.string()).optional().describe('Default filters for search results'),\n});\n\n/**\n * Multi-Tenancy Configuration Schema\n * Configures tenant isolation strategy for SaaS applications\n * \n * @example Shared database with tenant_id isolation\n * {\n * enabled: true,\n * strategy: 'shared',\n * tenantField: 'tenant_id',\n * crossTenantAccess: false\n * }\n */\nexport const TenancyConfigSchema = z.object({\n enabled: z.boolean().describe('Enable multi-tenancy for this object'),\n strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),\n tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),\n crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),\n});\n\n/**\n * Soft Delete Configuration Schema\n * Implements recycle bin / trash functionality\n * \n * @example Standard soft delete with cascade\n * {\n * enabled: true,\n * field: 'deleted_at',\n * cascadeDelete: true\n * }\n */\nexport const SoftDeleteConfigSchema = z.object({\n enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),\n field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),\n cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),\n});\n\n/**\n * Versioning Configuration Schema\n * Implements record versioning and history tracking\n * \n * @example Snapshot versioning with 90-day retention\n * {\n * enabled: true,\n * strategy: 'snapshot',\n * retentionDays: 90,\n * versionField: 'version'\n * }\n */\nexport const VersioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable record versioning'),\n strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),\n retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),\n versionField: z.string().default('version').describe('Field name for version number/timestamp'),\n});\n\n/**\n * Partitioning Strategy Schema\n * Configures table partitioning for performance at scale\n * \n * @example Range partitioning by date (monthly)\n * {\n * enabled: true,\n * strategy: 'range',\n * key: 'created_at',\n * interval: '1 month'\n * }\n */\nexport const PartitioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable table partitioning'),\n strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),\n key: z.string().describe('Field name to partition by'),\n interval: z.string().optional().describe('Partition interval for range strategy (e.g., \"1 month\", \"1 year\")'),\n}).refine((data) => {\n // If strategy is 'range', interval must be provided\n if (data.strategy === 'range' && !data.interval) {\n return false;\n }\n return true;\n}, {\n message: 'interval is required when strategy is \"range\"',\n});\n\n/**\n * Change Data Capture (CDC) Configuration Schema\n * Enables real-time data streaming to external systems\n * \n * @example Stream all changes to Kafka\n * {\n * enabled: true,\n * events: ['insert', 'update', 'delete'],\n * destination: 'kafka://events.objectstack'\n * }\n */\nexport const CDCConfigSchema = z.object({\n enabled: z.boolean().describe('Enable Change Data Capture'),\n events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),\n destination: z.string().describe('Destination endpoint (e.g., \"kafka://topic\", \"webhook://url\")'),\n});\n\n/**\n * Base Object Schema Definition\n * \n * The Blueprint of a Business Object.\n * Represents a table, a collection, or a virtual entity.\n * \n * @example\n * ```yaml\n * name: project_task\n * label: Project Task\n * icon: task\n * fields:\n * project:\n * type: lookup\n * reference: project\n * status:\n * type: select\n * options: [todo, in_progress, done]\n * enable:\n * trackHistory: true\n * files: true\n * ```\n */\nconst ObjectSchemaBase = z.object({\n /** \n * Identity & Metadata \n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),\n label: z.string().optional().describe('Human readable singular label (e.g. \"Account\")'),\n pluralLabel: z.string().optional().describe('Human readable plural label (e.g. \"Accounts\")'),\n description: z.string().optional().describe('Developer documentation / description'),\n icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),\n \n /**\n * Namespace & Domain Classification\n * \n * Groups objects into logical domains for routing, permissions, and discovery.\n * System objects use `'sys'`; business packages use their own namespace.\n * \n * When set, `tableName` is auto-derived as `{namespace}_{name}` by\n * `ObjectSchema.create()` unless an explicit `tableName` is provided.\n * \n * Namespace must be a single lowercase word (no underscores or hyphens)\n * to ensure clean auto-derivation of `{namespace}_{name}` table names.\n * \n * @example namespace: 'sys' → tableName defaults to 'sys_user'\n * @example namespace: 'crm' → tableName defaults to 'crm_account'\n */\n namespace: z.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace — single lowercase word (e.g. \"sys\", \"crm\"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'),\n\n /**\n * Taxonomy & Organization\n */\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g. \"sales\", \"system\", \"reference\")'),\n active: z.boolean().optional().default(true).describe('Is the object active and usable'),\n isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),\n abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),\n\n /** \n * Storage & Virtualization \n */\n datasource: z.string().optional().default('default').describe('Target Datasource ID. \"default\" is the primary DB.'),\n tableName: z.string().optional().describe('Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set.'),\n \n /** \n * Data Model \n */\n fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {\n message: 'Field names must be lowercase snake_case (e.g., \"first_name\", \"company\", \"annual_revenue\")',\n }), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),\n indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),\n \n /**\n * Advanced Data Management\n */\n \n // Multi-tenancy configuration\n tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),\n \n // Soft delete configuration\n softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),\n \n // Versioning configuration\n versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),\n \n // Partitioning strategy\n partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),\n \n // Change Data Capture\n cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),\n \n /**\n * Logic & Validation (Co-located)\n * Best Practice: Define rules close to data.\n */\n validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),\n \n /**\n * State Machine(s)\n * Named record of state machines, where each key is a unique machine identifier.\n * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).\n * \n * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }\n */\n stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),\n\n /** \n * Display & UI Hints (Data-Layer)\n */\n displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., \"name\", \"title\"). Defaults to \"name\" if present.'),\n recordName: z.object({\n type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),\n displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., \"CASE-{0000}\", \"INV-{YYYY}-{0000}\")'),\n startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),\n }).optional().describe('Record name generation configuration (Salesforce pattern)'),\n titleFormat: z.string().optional().describe('Title expression (e.g. \"{name} - {code}\"). Overrides displayNameField.'),\n compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),\n \n /** \n * Search Engine Config \n */\n search: SearchConfigSchema.optional().describe('Search engine configuration'),\n \n /** \n * System Capabilities \n */\n enable: ObjectCapabilities.optional().describe('Enabled system features modules'),\n\n /** Record Types */\n recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),\n\n /** Sharing Model */\n sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),\n\n /** Key Prefix */\n keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., \"001\" for Account)'),\n\n /**\n * Object Actions\n * \n * Actions associated with this object. Populated automatically by `defineStack()`\n * when top-level actions specify `objectName` matching this object.\n * Can also be defined directly on the object.\n * \n * Aligns with Salesforce/ServiceNow patterns where actions are part of the\n * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)\n * include the action list without requiring downstream merge.\n */\n actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),\n});\n\n/**\n * Converts a snake_case name to a human-readable Title Case label.\n * @example snakeCaseToLabel('project_task') → 'Project Task'\n */\nfunction snakeCaseToLabel(name: string): string {\n return name\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n}\n\n/**\n * Enhanced ObjectSchema with Factory\n */\nexport const ObjectSchema = Object.assign(ObjectSchemaBase, {\n /**\n * Type-safe factory for creating business object definitions.\n * \n * Enhancements over raw schema:\n * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).\n * - **Validation**: Runs Zod `.parse()` to validate the config at creation time.\n * \n * @example\n * ```ts\n * const Task = ObjectSchema.create({\n * name: 'project_task',\n * // label auto-generated as 'Project Task'\n * fields: {\n * subject: { type: 'text', label: 'Subject', required: true },\n * },\n * });\n * ```\n */\n create: >(config: T): Omit & Pick => {\n const withDefaults = {\n ...config,\n label: config.label ?? snakeCaseToLabel(config.name),\n // Auto-derive tableName as {namespace}_{name} when namespace is set\n tableName: config.tableName ?? (config.namespace ? `${config.namespace}_${config.name}` : undefined),\n };\n return ObjectSchemaBase.parse(withDefaults) as Omit & Pick;\n },\n});\n\nexport type ServiceObject = z.infer;\nexport type ServiceObjectInput = z.input;\nexport type ObjectCapabilities = z.infer;\nexport type ObjectIndex = z.infer;\nexport type TenancyConfig = z.infer;\nexport type SoftDeleteConfig = z.infer;\nexport type VersioningConfig = z.infer;\nexport type PartitioningConfig = z.infer;\nexport type CDCConfig = z.infer;\n\n// =================================================================\n// Object Ownership Model\n// =================================================================\n\n/**\n * How a package relates to an object it references.\n * \n * - `own`: This package is the original author/owner of the object.\n * Only one package may own a given object name. The owner defines\n * the base schema (table name, primary key, core fields).\n * \n * - `extend`: This package adds fields, views, or actions to an\n * existing object owned by another package. Multiple packages\n * may extend the same object. Extensions are merged at boot time.\n * \n * Follows Salesforce/ServiceNow patterns:\n * object name = database table name, globally unique, no namespace prefix.\n */\nexport const ObjectOwnershipEnum = z.enum(['own', 'extend']);\nexport type ObjectOwnership = z.infer;\n\n/**\n * Object Extension Entry — used in `objectExtensions` array.\n * Declares fields/config to merge into an existing object owned by another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact', // target object FQN\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\nexport const ObjectExtensionSchema = z.object({\n /** The target object name (FQN) to extend */\n extend: z.string().describe('Target object name (FQN) to extend'),\n \n /** Fields to merge into the target object (additive) */\n fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),\n \n /** Override label */\n label: z.string().optional().describe('Override label for the extended object'),\n \n /** Override plural label */\n pluralLabel: z.string().optional().describe('Override plural label for the extended object'),\n \n /** Override description */\n description: z.string().optional().describe('Override description for the extended object'),\n \n /** Additional validation rules to add */\n validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),\n \n /** Additional indexes to add */\n indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),\n \n /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */\n priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),\n});\n\nexport type ObjectExtension = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Hook Lifecycle Events\n * Defines the interception points in the ObjectQL execution pipeline.\n */\nexport const HookEvent = z.enum([\n // Read Operations\n 'beforeFind', 'afterFind',\n 'beforeFindOne', 'afterFindOne',\n 'beforeCount', 'afterCount',\n 'beforeAggregate', 'afterAggregate',\n\n // Write Operations\n 'beforeInsert', 'afterInsert',\n 'beforeUpdate', 'afterUpdate',\n 'beforeDelete', 'afterDelete',\n \n // Bulk Operations (Query-based)\n 'beforeUpdateMany', 'afterUpdateMany',\n 'beforeDeleteMany', 'afterDeleteMany',\n]);\n\n/**\n * Hook Definition Schema\n * \n * Hooks serve as the \"Logic Layer\" in ObjectStack, allowing developers to \n * inject custom code during the data access lifecycle.\n * \n * Use cases:\n * - Data Enrichment (Default values, Calculated fields)\n * - Validation (Complex business rules)\n * - Side Effects (Sending emails, Syncing to external systems)\n * - Security (Filtering data based on context)\n */\nexport const HookSchema = z.object({\n /**\n * Unique identifier for the hook\n * Required for debugging and overriding.\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Hook unique name (snake_case)'),\n\n /**\n * Human readable label\n */\n label: z.string().optional().describe('Description of what this hook does'),\n\n /**\n * Target Object(s)\n * can be:\n * - Single object: \"account\"\n * - List of objects: [\"account\", \"contact\"]\n * - Wildcard: \"*\" (All objects)\n */\n object: z.union([z.string(), z.array(z.string())]).describe('Target object(s)'),\n\n /**\n * Events to subscribe to\n * Combinations of timing (before/after) and action (find/insert/update/delete/etc)\n */\n events: z.array(HookEvent).describe('Lifecycle events'),\n\n /**\n * Handler Logic\n * Reference to a registered function in the plugin system OR a direct function (runtime only).\n */\n handler: z.union([z.string(), z.function()]).optional().describe('Handler function name (string) or inline function reference'),\n\n /**\n * Execution Order\n * Lower numbers run first.\n * - System Hooks: 0-99\n * - App Hooks: 100-999\n * - User Hooks: 1000+\n */\n priority: z.number().default(100).describe('Execution priority'),\n\n /**\n * Async / Background Execution\n * If true, the hook runs in the background and does not block the transaction.\n * Only applicable for 'after*' events.\n * Default: false (Blocking)\n */\n async: z.boolean().default(false).describe('Run specifically as fire-and-forget'),\n\n /**\n * Declarative Condition\n * Formula expression evaluated before the handler runs.\n * If provided and evaluates to FALSE, the hook is skipped entirely.\n * Useful for filtering by record data without writing handler code.\n * \n * @example \"status = 'active' AND amount > 1000\"\n */\n condition: z.string().optional().describe('Formula expression; hook runs only when TRUE (e.g., \"status = \\'closed\\' AND amount > 1000\")'),\n\n /**\n * Human-readable description\n */\n description: z.string().optional().describe('Human-readable description of what this hook does'),\n\n /**\n * Retry Policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().default(3).describe('Maximum retry attempts on failure'),\n backoffMs: z.number().default(1000).describe('Backoff delay between retries in milliseconds'),\n }).optional().describe('Retry policy for failed hook executions'),\n\n /**\n * Execution Timeout\n */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds before the hook is aborted'),\n\n /**\n * Error Policy\n * What to do if the hook throws an exception?\n * - abort: Rollback transaction (if blocking)\n * - log: Log error and continue\n */\n onError: z.enum(['abort', 'log']).default('abort').describe('Error handling strategy'),\n});\n\n/**\n * Hook Runtime Context\n * Defines what is available to the hook handler during execution.\n * \n * Best Practices:\n * - **Immutability**: `object`, `event`, `id` are immutable.\n * - **Mutability**: `input` and `result` are mutable to allow transformation.\n * - **Encapsulation**: `session` isolates auth info; `transaction` ensures atomicity.\n */\nexport const HookContextSchema = z.object({\n /** Tracing ID */\n id: z.string().optional().describe('Unique execution ID for tracing'),\n\n /** Target Object Name */\n object: z.string(),\n \n /** Current Lifecycle Event */\n event: HookEvent,\n\n /** \n * Input Parameters (Mutable)\n * Modify this to change the behavior of the operation.\n * \n * - find: { query: QueryAST, options: DriverOptions }\n * - insert: { doc: Record, options: DriverOptions }\n * - update: { id: ID, doc: Record, options: DriverOptions }\n * - delete: { id: ID, options: DriverOptions }\n * - updateMany: { query: QueryAST, doc: Record, options: DriverOptions }\n * - deleteMany: { query: QueryAST, options: DriverOptions }\n */\n input: z.record(z.string(), z.unknown()).describe('Mutable input parameters'),\n\n /** \n * Operation Result (Mutable)\n * Available in 'after*' events. Modify this to transform the output.\n */\n result: z.unknown().optional().describe('Operation result (After hooks only)'),\n\n /**\n * Data Snapshot\n * The state of the record BEFORE the operation (for update/delete).\n */\n previous: z.record(z.string(), z.unknown()).optional().describe('Record state before operation'),\n\n /**\n * Execution Session\n * Contains authentication and tenancy information.\n */\n session: z.object({\n userId: z.string().optional(),\n tenantId: z.string().optional(),\n roles: z.array(z.string()).optional(),\n accessToken: z.string().optional(),\n }).optional().describe('Current session context'),\n \n /**\n * Transaction Handle\n * If the operation is part of a transaction, use this handle for side-effects.\n */\n transaction: z.unknown().optional().describe('Database transaction handle'),\n\n /**\n * Engine Access\n * Reference to the ObjectQL engine for performing side effects.\n */\n ql: z.unknown().describe('ObjectQL Engine Reference'),\n\n /**\n * Cross-Object API\n * Provides a scoped data access interface for performing CRUD operations\n * on other objects within hooks. Bound to the current execution context\n * (userId, tenantId, transaction).\n *\n * Usage in hooks:\n * const users = ctx.api.object('user');\n * const admin = await users.findOne({ filter: { role: 'admin' } });\n */\n api: z.unknown().optional().describe('Cross-object data access (ScopedContext)'),\n\n /**\n * Current User Info\n * Convenience shortcut for session.userId + additional user metadata.\n * Populated by the engine when available.\n */\n user: z.object({\n id: z.string().optional(),\n name: z.string().optional(),\n email: z.string().optional(),\n }).optional().describe('Current user info shortcut'),\n});\n\nexport type Hook = z.input;\nexport type ResolvedHook = z.output;\nexport type HookEventType = z.infer;\nexport type HookContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { QuerySchema } from './query.zod';\n\n/**\n * Transformation Logic\n * Built-in helpers for converting data during import.\n */\nexport const TransformType = z.enum([\n 'none', // Direct copy\n 'constant', // Use a hardcoded value\n 'lookup', // Resolve FK (Name -> ID)\n 'split', // \"John Doe\" -> [\"John\", \"Doe\"]\n 'join', // [\"John\", \"Doe\"] -> \"John Doe\"\n 'javascript', // Custom script (Review security!)\n 'map' // Value mapping (e.g. \"Active\" -> \"active\")\n]);\n\n/**\n * Field Mapping Item\n */\nexport const FieldMappingSchema = z.object({\n /** Source Column */\n source: z.union([z.string(), z.array(z.string())]).describe('Source column header(s)'),\n \n /** Target Field */\n target: z.union([z.string(), z.array(z.string())]).describe('Target object field(s)'),\n \n /** Transformation */\n transform: TransformType.default('none'),\n \n /** Configuration for transform */\n params: z.object({\n // Constant\n value: z.unknown().optional(),\n \n // Lookup\n object: z.string().optional(), // Lookup Object\n fromField: z.string().optional(), // Match on (e.g. \"name\")\n toField: z.string().optional(), // Value to take (e.g. \"id\")\n autoCreate: z.boolean().optional(), // Create if missing\n \n // Map\n valueMap: z.record(z.string(), z.unknown()).optional(), // { \"Open\": \"draft\" }\n \n // Split/Join\n separator: z.string().optional()\n }).optional()\n});\n\n/**\n * Data Mapping Schema\n * Defines a reusable data mapping configuration for ETL operations.\n * \n * **NAMING CONVENTION:**\n * Mapping names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good mapping names\n * - 'salesforce_to_crm'\n * - 'csv_import_contacts'\n * - 'api_sync_orders'\n * \n * @example Bad mapping names (will be rejected)\n * - 'SalesforceToCRM' (PascalCase)\n * - 'CSV Import' (spaces)\n */\nexport const MappingSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Mapping unique name (lowercase snake_case)'),\n label: z.string().optional(),\n \n /** Scope */\n sourceFormat: z.enum(['csv', 'json', 'xml', 'sql']).default('csv'),\n targetObject: z.string().describe('Target Object Name'),\n \n /** Column Mappings */\n fieldMapping: z.array(FieldMappingSchema),\n \n /** Upsert Logic */\n mode: z.enum(['insert', 'update', 'upsert']).default('insert'),\n upsertKey: z.array(z.string()).optional().describe('Fields to match for upsert (e.g. email)'),\n \n /** Extract Logic (For Export) */\n extractQuery: QuerySchema.optional().describe('Query to run for export only'),\n \n /** Error Handling */\n errorPolicy: z.enum(['skip', 'abort', 'retry']).default('skip'),\n batchSize: z.number().default(1000)\n});\n\nexport type Mapping = z.infer;\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Execution Context Schema\n * \n * Defines the runtime context that flows from HTTP request → data operations.\n * This is the \"identity + environment\" envelope that every data operation can carry.\n * \n * Design:\n * - All fields are optional for backward compatibility\n * - `isSystem` bypasses permission checks (for internal/migration operations)\n * - `transaction` carries the database transaction handle for atomicity\n * - `traceId` enables distributed tracing across microservices\n * \n * Usage:\n * engine.find('account', { context: { userId: '...', tenantId: '...' } })\n */\nexport const ExecutionContextSchema = z.object({\n /** Current user ID (resolved from session) */\n userId: z.string().optional(),\n \n /** Current organization/tenant ID (resolved from session.activeOrganizationId) */\n tenantId: z.string().optional(),\n \n /** User role names (resolved from Member + Role) */\n roles: z.array(z.string()).default([]),\n \n /** Aggregated permission names (resolved from PermissionSet) */\n permissions: z.array(z.string()).default([]),\n \n /** Whether this is a system-level operation (bypasses permission checks) */\n isSystem: z.boolean().default(false),\n \n /** Raw access token (for external API call pass-through) */\n accessToken: z.string().optional(),\n \n /** Database transaction handle */\n transaction: z.unknown().optional(),\n \n /** Request trace ID (for distributed tracing) */\n traceId: z.string().optional(),\n});\n\nexport type ExecutionContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\nimport { SortNodeSchema, QuerySchema, FullTextSearchSchema, FieldNodeSchema, AggregationNodeSchema } from './query.zod';\nimport { ExecutionContextSchema } from '../kernel/execution-context.zod';\n\n/**\n * Data Engine Protocol\n * \n * Defines the standard interface for data persistence engines in ObjectStack.\n * This protocol abstracts the underlying storage mechanism (SQL, NoSQL, API, Memory),\n * allowing the ObjectQL engine to execute standardized CRUD and Aggregation operations\n * regardless of where the data resides.\n * \n * The Data Engine acts as the \"Driver\" layer in the Hexagonal Architecture.\n */\n\n// ==========================================================================\n// 1. Shared Definitions\n// ==========================================================================\n\n/**\n * Data Engine Query filter conditions\n * Supports simple key-value map or complex Logic/Field expressions (DSL)\n */\nexport const DataEngineFilterSchema = z.union([\n z.record(z.string(), z.unknown()),\n FilterConditionSchema\n]).describe('Data Engine query filter conditions');\n\n/**\n * Sort order definition\n * Supports:\n * - { name: 'asc' }\n * - { name: 1 }\n * - [{ field: 'name', order: 'asc' }]\n */\nexport const DataEngineSortSchema = z.union([\n z.record(z.string(), z.enum(['asc', 'desc'])), \n z.record(z.string(), z.union([z.literal(1), z.literal(-1)])),\n z.array(SortNodeSchema)\n]).describe('Sort order definition');\n\n// ==========================================================================\n// 1b. Base Engine Options (shared context)\n// ==========================================================================\n\n/**\n * Base Engine Options\n * \n * All Data Engine operation options extend this schema to carry\n * an optional ExecutionContext for identity, tenant, and transaction propagation.\n */\nexport const BaseEngineOptionsSchema = z.object({\n /** Execution context (identity, tenant, transaction) */\n context: ExecutionContextSchema.optional(),\n});\n\n// ==========================================================================\n// 2. method: FIND (QueryAST-aligned)\n// ==========================================================================\n\n/**\n * Engine Query Options — QueryAST-aligned parameters for IDataEngine.find/findOne.\n * \n * Uses standard QueryAST field names (where/fields/orderBy/limit/offset/expand)\n * so that no mechanical translation is needed between the Engine and Driver layers.\n * \n * @example\n * ```ts\n * engine.find('account', {\n * where: { status: 'active' },\n * fields: ['id', 'name', 'email'],\n * orderBy: [{ field: 'name', order: 'asc' }],\n * limit: 10,\n * offset: 20,\n * expand: { owner: { object: 'user', fields: ['name'] } },\n * });\n * ```\n */\nexport const EngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions (WHERE) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n\n /** Fields to retrieve (SELECT) — standard QueryAST `fields` */\n fields: z.array(FieldNodeSchema).optional(),\n\n /** Sorting instructions (ORDER BY) — standard QueryAST `orderBy` */\n orderBy: z.array(SortNodeSchema).optional(),\n\n /** Max records to return (LIMIT) */\n limit: z.number().optional(),\n\n /** Records to skip (OFFSET) — standard QueryAST `offset` */\n offset: z.number().optional(),\n\n /** Alias for limit (OData compatibility) */\n top: z.number().optional(),\n\n /** Cursor for keyset pagination */\n cursor: z.record(z.string(), z.unknown()).optional(),\n\n /** Full-text search configuration */\n search: FullTextSearchSchema.optional(),\n\n /**\n * Recursive relation loading map (expand).\n * \n * Keys are lookup/master_detail field names; values are nested QueryAST\n * objects that control select, filter, sort, and further expansion on\n * the related object. The engine resolves expand via batch $in queries\n * (driver-agnostic) with a default max depth of 3.\n */\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional(),\n\n /** SELECT DISTINCT flag */\n distinct: z.boolean().optional(),\n}).describe('QueryAST-aligned query options for IDataEngine.find() operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineQueryOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineQueryOptionsSchema` instead.\n * This schema uses legacy parameter names (filter/select/sort/skip/populate)\n * that require mechanical translation to QueryAST. Migrate to the\n * QueryAST-aligned `EngineQueryOptionsSchema` (where/fields/orderBy/offset/expand).\n */\nexport const DataEngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineQueryOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n /** @deprecated Use `fields` (EngineQueryOptionsSchema) */\n select: z.array(z.string()).optional(),\n /** @deprecated Use `orderBy` (EngineQueryOptionsSchema) */\n sort: DataEngineSortSchema.optional(),\n limit: z.number().int().min(1).optional(),\n /** @deprecated Use `offset` (EngineQueryOptionsSchema) */\n skip: z.number().int().min(0).optional(),\n top: z.number().int().min(1).optional(),\n /** @deprecated Use `expand` (EngineQueryOptionsSchema) */\n populate: z.array(z.string()).optional(),\n}).describe('Query options for IDataEngine.find() operations');\n\n// ==========================================================================\n// 3. method: INSERT\n// ==========================================================================\n\nexport const DataEngineInsertOptionsSchema = BaseEngineOptionsSchema.extend({\n /** \n * Return the inserted record(s)? \n * Some drivers support RETURNING clause for efficiency.\n * Default: true\n */\n returning: z.boolean().default(true).optional(),\n}).describe('Options for DataEngine.insert operations');\n\n// ==========================================================================\n// 4. method: UPDATE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions to identify records to update — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Perform an upsert? If true, insert if not found. */\n upsert: z.boolean().default(false).optional(),\n /** Update multiple records? If false, only the first match is updated. Default: false */\n multi: z.boolean().default(false).optional(),\n /** Return the updated record(s)? Default: false (returns update count/status) */\n returning: z.boolean().default(false).optional(),\n}).describe('QueryAST-aligned options for DataEngine.update operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineUpdateOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineUpdateOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineUpdateOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n upsert: z.boolean().default(false).optional(),\n multi: z.boolean().default(false).optional(),\n returning: z.boolean().default(false).optional(),\n}).describe('Options for DataEngine.update operations');\n\n// ==========================================================================\n// 5. method: DELETE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions to identify records to delete — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Delete multiple records? If false, only the first match is deleted. Default: false */\n multi: z.boolean().default(false).optional(),\n}).describe('QueryAST-aligned options for DataEngine.delete operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineDeleteOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineDeleteOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineDeleteOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n multi: z.boolean().default(false).optional(),\n}).describe('Options for DataEngine.delete operations');\n\n// ==========================================================================\n// 6. method: AGGREGATE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions (WHERE) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Group By fields */\n groupBy: z.array(z.string()).optional(),\n /** \n * Aggregation definitions — uses standard AggregationNodeSchema (`function` key).\n * e.g. [{ function: 'sum', field: 'amount', alias: 'total' }]\n */\n aggregations: z.array(AggregationNodeSchema).optional(),\n}).describe('QueryAST-aligned options for DataEngine.aggregate operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineAggregateOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineAggregateOptionsSchema` instead.\n * Migrate `filter` → `where`, aggregation `method` → `function`.\n */\nexport const DataEngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineAggregateOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n groupBy: z.array(z.string()).optional(),\n /** \n * @deprecated Use `EngineAggregateOptionsSchema` with standard AggregationNodeSchema (`function` key).\n */\n aggregations: z.array(z.object({\n field: z.string(),\n method: z.enum(['count', 'sum', 'avg', 'min', 'max', 'count_distinct']),\n alias: z.string().optional()\n })).optional(),\n}).describe('Options for DataEngine.aggregate operations');\n\n// ==========================================================================\n// 7. method: COUNT (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineCountOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n}).describe('QueryAST-aligned options for DataEngine.count operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineCountOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineCountOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineCountOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineCountOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n}).describe('Options for DataEngine.count operations');\n\n// ==========================================================================\n// 8. Definition (Contract)\n// ==========================================================================\n\nexport const DataEngineContractSchema = z.object({\n find: z.function()\n .input(z.tuple([z.string(), EngineQueryOptionsSchema.optional()]))\n .output(z.promise(z.array(z.unknown()))),\n \n findOne: z.function()\n .input(z.tuple([z.string(), EngineQueryOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n insert: z.function()\n .input(z.tuple([z.string(), z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]), DataEngineInsertOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n update: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), EngineUpdateOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n delete: z.function()\n .input(z.tuple([z.string(), EngineDeleteOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n count: z.function()\n .input(z.tuple([z.string(), EngineCountOptionsSchema.optional()]))\n .output(z.promise(z.number())),\n \n aggregate: z.function()\n .input(z.tuple([z.string(), EngineAggregateOptionsSchema]))\n .output(z.promise(z.array(z.unknown())))\n}).describe('Standard Data Engine Contract');\n\n// ==========================================================================\n// 9. Virtualization & RPC Protocol\n// ==========================================================================\n\n/**\n * Data Engine RPC Request (Virtual ObjectQL)\n * \n * This schema defines the serialized format for executing Data Engine operations\n * via HTTP, Message Queue, or Plugin boundaries.\n * \n * It enables \"Virtual Data Engines\" where the implementation resides in a \n * separate microservice or plugin.\n */\n\n/**\n * RPC backward-compatibility mixin — shared `@deprecated filter` field.\n * When both `filter` and `where` are present, the protocol/engine ignores\n * `filter` in favor of `where`; only one should be provided.\n */\nconst RpcLegacyFilterMixin = {\n /** @deprecated Use `where` */\n filter: DataEngineFilterSchema.optional(),\n};\n\n/**\n * RPC query options that accept BOTH new (where/fields/orderBy) and\n * legacy (filter/select/sort/skip/populate) parameter names.\n * \n * **Precedence:** When both legacy and new keys are present for the same\n * concern, the protocol normalizer uses the new key (`where` > `filter`,\n * `fields` > `select`, `orderBy` > `sort`, `offset` > `skip`,\n * `expand` > `populate`). Callers should not mix vocabularies.\n */\nconst RpcQueryOptionsSchema = EngineQueryOptionsSchema.extend({\n ...RpcLegacyFilterMixin,\n /** @deprecated Use `fields` */\n select: z.array(z.string()).optional(),\n /** @deprecated Use `orderBy` */\n sort: DataEngineSortSchema.optional(),\n /** @deprecated Use `offset` */\n skip: z.number().int().min(0).optional(),\n /** @deprecated Use `expand` */\n populate: z.array(z.string()).optional(),\n});\n\nexport const DataEngineFindRequestSchema = z.object({\n method: z.literal('find'),\n object: z.string(),\n query: RpcQueryOptionsSchema.optional()\n});\n\nexport const DataEngineFindOneRequestSchema = z.object({\n method: z.literal('findOne'),\n object: z.string(),\n query: RpcQueryOptionsSchema.optional()\n});\n\nexport const DataEngineInsertRequestSchema = z.object({\n method: z.literal('insert'),\n object: z.string(),\n data: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]),\n options: DataEngineInsertOptionsSchema.optional()\n});\n\nexport const DataEngineUpdateRequestSchema = z.object({\n method: z.literal('update'),\n object: z.string(),\n data: z.record(z.string(), z.unknown()),\n id: z.union([z.string(), z.number()]).optional().describe('ID for single update, or use where in options'),\n options: EngineUpdateOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineDeleteRequestSchema = z.object({\n method: z.literal('delete'),\n object: z.string(),\n id: z.union([z.string(), z.number()]).optional().describe('ID for single delete, or use where in options'),\n options: EngineDeleteOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineCountRequestSchema = z.object({\n method: z.literal('count'),\n object: z.string(),\n query: EngineCountOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineAggregateRequestSchema = z.object({\n method: z.literal('aggregate'),\n object: z.string(),\n query: EngineAggregateOptionsSchema.extend(RpcLegacyFilterMixin)\n});\n\n/**\n * Data Engine Execute Request (Raw Command)\n * Execute a raw command/query native to the driver (e.g. SQL, Shell, Remote API).\n */\nexport const DataEngineExecuteRequestSchema = z.object({\n method: z.literal('execute'),\n /** The abstract command (string SQL, or JSON object) */\n command: z.unknown(),\n /** Optional options */\n options: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Data Engine Vector Find Request (AI/RAG)\n * Perform a similarity search using vector embeddings.\n */\nexport const DataEngineVectorFindRequestSchema = z.object({\n method: z.literal('vectorFind'),\n object: z.string(),\n /** The vector embedding to search for */\n vector: z.array(z.number()),\n /** Optional pre-filter (Metadata filtering) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Fields to retrieve — standard QueryAST `fields` */\n fields: z.array(z.string()).optional(),\n /** Number of results */\n limit: z.number().int().default(5).optional(),\n /** Minimum similarity score (0-1) or distance threshold */\n threshold: z.number().optional()\n});\n\n/**\n * Data Engine Batch Request\n * Execute multiple operations in a single transaction/request efficiently.\n */\nexport const DataEngineBatchRequestSchema = z.object({\n method: z.literal('batch'),\n requests: z.array(z.discriminatedUnion('method', [\n DataEngineFindRequestSchema,\n DataEngineFindOneRequestSchema,\n DataEngineInsertRequestSchema,\n DataEngineUpdateRequestSchema,\n DataEngineDeleteRequestSchema,\n DataEngineCountRequestSchema,\n DataEngineAggregateRequestSchema,\n DataEngineExecuteRequestSchema,\n DataEngineVectorFindRequestSchema\n ])),\n /** \n * Transaction Mode\n * - true: All or nothing (Atomic)\n * - false: Best effort, continue on error\n */\n transaction: z.boolean().default(true).optional()\n});\n\n/**\n * Unified Data Engine Request Union\n * Use this to validate any incoming \"Virtual ObjectQL\" request.\n */\nexport const DataEngineRequestSchema = z.discriminatedUnion('method', [\n DataEngineFindRequestSchema,\n DataEngineFindOneRequestSchema,\n DataEngineInsertRequestSchema,\n DataEngineUpdateRequestSchema,\n DataEngineDeleteRequestSchema,\n DataEngineCountRequestSchema,\n DataEngineAggregateRequestSchema,\n DataEngineBatchRequestSchema,\n DataEngineExecuteRequestSchema,\n DataEngineVectorFindRequestSchema\n]).describe('Virtual ObjectQL Request Protocol');\n\n// ==========================================================================\n// 10. Type Exports\n// ==========================================================================\n\n// --- New: QueryAST-aligned types (preferred) ---\nexport type EngineQueryOptions = z.infer;\nexport type EngineUpdateOptions = z.infer;\nexport type EngineDeleteOptions = z.infer;\nexport type EngineAggregateOptions = z.infer;\nexport type EngineCountOptions = z.infer;\n\n// --- Legacy: deprecated types (kept for backward compatibility) ---\nexport type DataEngineFilter = z.infer;\n/** @deprecated Use standard `SortNode[]` from QueryAST instead. */\nexport type DataEngineSort = z.infer;\nexport type BaseEngineOptions = z.infer;\n/** @deprecated Use `EngineQueryOptions` instead. */\nexport type DataEngineQueryOptions = z.infer;\nexport type DataEngineInsertOptions = z.infer;\n/** @deprecated Use `EngineUpdateOptions` instead. */\nexport type DataEngineUpdateOptions = z.infer;\n/** @deprecated Use `EngineDeleteOptions` instead. */\nexport type DataEngineDeleteOptions = z.infer;\n/** @deprecated Use `EngineAggregateOptions` instead. */\nexport type DataEngineAggregateOptions = z.infer;\n/** @deprecated Use `EngineCountOptions` instead. */\nexport type DataEngineCountOptions = z.infer;\nexport type DataEngineRequest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Shared Enumerations\n// ============================================================================\n\n/** Aggregation functions used across query, data-engine, analytics, field */\nexport const AggregationFunctionEnum = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'percentile', 'median', 'stddev', 'variance',\n]).describe('Standard aggregation functions');\nexport type AggregationFunction = z.infer;\n\n/** Sort direction used across query, data-engine, analytics */\nexport const SortDirectionEnum = z.enum(['asc', 'desc'])\n .describe('Sort order direction');\nexport type SortDirection = z.infer;\n\n/** Reusable sort item — field + direction pair used across views, data sources, filters */\nexport const SortItemSchema = z.object({\n field: z.string().describe('Field name to sort by'),\n order: SortDirectionEnum.describe('Sort direction'),\n}).describe('Sort field and direction pair');\nexport type SortItem = z.infer;\n\n/** CRUD mutation events used across hook, validation, object CDC */\nexport const MutationEventEnum = z.enum([\n 'insert', 'update', 'delete', 'upsert',\n]).describe('Data mutation event types');\nexport type MutationEvent = z.infer;\n\n/** Database isolation levels — unified format */\nexport const IsolationLevelEnum = z.enum([\n 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable', 'snapshot',\n]).describe('Transaction isolation levels (snake_case standard)');\nexport type IsolationLevel = z.infer;\n\n/** Cache eviction strategies */\nexport const CacheStrategyEnum = z.enum(['lru', 'lfu', 'ttl', 'fifo'])\n .describe('Cache eviction strategy');\nexport type CacheStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { QuerySchema } from '../data/query.zod';\nimport { IsolationLevelEnum } from '../shared/enums.zod';\n\n/**\n * Common Driver Options\n * Passed to most driver methods to control behavior (transactions, timeouts, etc.)\n */\nexport const DriverOptionsSchema = z.object({\n /**\n * Transaction handle/identifier.\n * If provided, the operation must run within this transaction.\n */\n transaction: z.unknown().optional().describe('Transaction handle'),\n\n /**\n * Operation timeout in milliseconds.\n */\n timeout: z.number().optional().describe('Timeout in ms'),\n\n /**\n * Whether to bypass cache and force a fresh read.\n */\n skipCache: z.boolean().optional().describe('Bypass cache'),\n\n /**\n * Distributed Tracing Context.\n * Used for passing OpenTelemetry span context or request IDs for observability.\n */\n traceContext: z.record(z.string(), z.string()).optional().describe('OpenTelemetry context or request ID'),\n\n /**\n * Tenant Identifier.\n * For multi-tenant databases (row-level security or schema-per-tenant).\n */\n tenantId: z.string().optional().describe('Tenant Isolation identifier'),\n});\n\n/**\n * Driver Capabilities Schema\n * \n * Defines what features a database driver supports.\n * This allows ObjectQL to adapt its behavior based on underlying database capabilities.\n * Enhanced with granular capability flags for better feature detection.\n */\nexport const DriverCapabilitiesSchema = z.object({\n // ============================================================================\n // Basic CRUD Operations\n // ============================================================================\n \n /**\n * Whether the driver supports create operations.\n */\n create: z.boolean().default(true).describe('Supports CREATE operations'),\n \n /**\n * Whether the driver supports read operations.\n */\n read: z.boolean().default(true).describe('Supports READ operations'),\n \n /**\n * Whether the driver supports update operations.\n */\n update: z.boolean().default(true).describe('Supports UPDATE operations'),\n \n /**\n * Whether the driver supports delete operations.\n */\n delete: z.boolean().default(true).describe('Supports DELETE operations'),\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n \n /**\n * Whether the driver supports bulk create operations.\n */\n bulkCreate: z.boolean().default(false).describe('Supports bulk CREATE operations'),\n \n /**\n * Whether the driver supports bulk update operations.\n */\n bulkUpdate: z.boolean().default(false).describe('Supports bulk UPDATE operations'),\n \n /**\n * Whether the driver supports bulk delete operations.\n */\n bulkDelete: z.boolean().default(false).describe('Supports bulk DELETE operations'),\n\n // ============================================================================\n // Transaction & Connection Management\n // ============================================================================\n \n /**\n * Whether the driver supports database transactions.\n * If true, beginTransaction, commit, and rollback must be implemented.\n */\n transactions: z.boolean().default(false).describe('Supports ACID transactions'),\n \n /**\n * Whether the driver supports savepoints within transactions.\n */\n savepoints: z.boolean().default(false).describe('Supports transaction savepoints'),\n \n /**\n * Supported transaction isolation levels.\n */\n isolationLevels: z.array(IsolationLevelEnum).optional().describe('Supported isolation levels'),\n\n // ============================================================================\n // Query Operations\n // ============================================================================\n \n /**\n * Whether the driver supports WHERE clause filters.\n * If false, ObjectQL will fetch all records and filter in memory.\n * \n * Example: Memory driver might not support complex filter conditions.\n */\n queryFilters: z.boolean().default(true).describe('Supports WHERE clause filtering'),\n\n /**\n * Whether the driver supports aggregation functions (COUNT, SUM, AVG, etc.).\n * If false, ObjectQL will compute aggregations in memory.\n */\n queryAggregations: z.boolean().default(false).describe('Supports GROUP BY and aggregation functions'),\n\n /**\n * Whether the driver supports ORDER BY sorting.\n * If false, ObjectQL will sort results in memory.\n */\n querySorting: z.boolean().default(true).describe('Supports ORDER BY sorting'),\n\n /**\n * Whether the driver supports LIMIT/OFFSET pagination.\n * If false, ObjectQL will fetch all records and paginate in memory.\n */\n queryPagination: z.boolean().default(true).describe('Supports LIMIT/OFFSET pagination'),\n\n /**\n * Whether the driver supports window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.).\n * If false, ObjectQL will compute window functions in memory.\n */\n queryWindowFunctions: z.boolean().default(false).describe('Supports window functions with OVER clause'),\n\n /**\n * Whether the driver supports subqueries (nested SELECT statements).\n * If false, ObjectQL will execute queries separately and combine results.\n */\n querySubqueries: z.boolean().default(false).describe('Supports subqueries'),\n \n /**\n * Whether the driver supports Common Table Expressions (WITH clause).\n */\n queryCTE: z.boolean().default(false).describe('Supports Common Table Expressions (WITH clause)'),\n\n /**\n * Whether the driver supports SQL-style joins.\n * If false, ObjectQL will fetch related data separately and join in memory.\n */\n joins: z.boolean().default(false).describe('Supports SQL joins'),\n\n // ============================================================================\n // Advanced Features\n // ============================================================================\n \n /**\n * Whether the driver supports full-text search.\n * If true, text search queries can be pushed to the database.\n */\n fullTextSearch: z.boolean().default(false).describe('Supports full-text search'),\n \n /**\n * Whether the driver supports JSON querying capabilities.\n */\n jsonQuery: z.boolean().default(false).describe('Supports JSON field querying'),\n \n /**\n * Whether the driver supports geospatial queries.\n */\n geospatialQuery: z.boolean().default(false).describe('Supports geospatial queries'),\n \n /**\n * Whether the driver supports streaming large result sets.\n */\n streaming: z.boolean().default(false).describe('Supports result streaming (cursors/iterators)'),\n\n /**\n * Whether the driver supports JSON field types.\n * If false, JSON data will be serialized as strings.\n */\n jsonFields: z.boolean().default(false).describe('Supports JSON field types'),\n\n /**\n * Whether the driver supports array field types.\n * If false, arrays will be stored as JSON strings or in separate tables.\n */\n arrayFields: z.boolean().default(false).describe('Supports array field types'),\n\n /**\n * Whether the driver supports vector embeddings and similarity search.\n * Required for RAG (Retrieval-Augmented Generation) and AI features.\n */\n vectorSearch: z.boolean().default(false).describe('Supports vector embeddings and similarity search'),\n\n // ============================================================================\n // Schema Management\n // ============================================================================\n \n /**\n * Whether the driver supports automatic schema synchronization.\n */\n schemaSync: z.boolean().default(false).describe('Supports automatic schema synchronization'),\n\n /**\n * Whether the driver supports batching multiple schema sync operations\n * into a single (or fewer) round-trips for the DDL phase. When true,\n * the engine may call `syncSchemasBatch()` instead of calling\n * `syncSchema()` per object, reducing network round-trips for remote drivers.\n */\n batchSchemaSync: z.boolean().default(false).describe('Supports batched schema sync to reduce schema DDL round-trips'),\n \n /**\n * Whether the driver supports database migrations.\n */\n migrations: z.boolean().default(false).describe('Supports database migrations'),\n \n /**\n * Whether the driver supports index management.\n */\n indexes: z.boolean().default(false).describe('Supports index creation and management'),\n\n // ============================================================================\n // Performance & Optimization\n // ============================================================================\n \n /**\n * Whether the driver supports connection pooling.\n */\n connectionPooling: z.boolean().default(false).describe('Supports connection pooling'),\n \n /**\n * Whether the driver supports prepared statements.\n */\n preparedStatements: z.boolean().default(false).describe('Supports prepared statements (SQL injection prevention)'),\n \n /**\n * Whether the driver supports query result caching.\n */\n queryCache: z.boolean().default(false).describe('Supports query result caching'),\n});\n\n/**\n * Unified Database Driver Interface\n * \n * This is the contract that all storage adapters (Postgres, Mongo, Excel, Salesforce) must implement.\n * It abstracts the underlying engine, enabling ObjectStack to be \"Database Agnostic\".\n */\nexport const DriverInterfaceSchema = z.object({\n /**\n * Driver name (e.g., 'postgresql', 'mongodb', 'rest_api').\n */\n name: z.string().describe('Driver unique name'),\n\n /**\n * Driver version.\n */\n version: z.string().describe('Driver version'),\n\n /**\n * Capabilities descriptor.\n */\n supports: DriverCapabilitiesSchema,\n\n // ============================================================================\n // Lifecycle Management\n // ============================================================================\n\n /**\n * Initialize connection pool or authenticate.\n */\n connect: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.void()))\n .describe('Establish connection'),\n\n /**\n * Close connections and cleanup resources.\n */\n disconnect: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.void()))\n .describe('Close connection'),\n\n /**\n * Check connection health.\n * @returns true if healthy, false otherwise.\n */\n checkHealth: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.boolean()))\n .describe('Health check'),\n \n /**\n * Get Connection Pool Statistics.\n * Useful for monitoring database load.\n */\n getPoolStats: z.function()\n .input(z.tuple([]))\n .output(z.object({\n total: z.number(),\n idle: z.number(),\n active: z.number(),\n waiting: z.number(),\n }).optional())\n .optional()\n .describe('Get connection pool statistics'),\n\n // ============================================================================\n // Raw Execution (Escape Hatch)\n // ============================================================================\n\n /**\n * Execute a raw command/query native to the driver.\n * Useful for complex reports, stored procedures, or DDL not covered by standard sync.\n * \n * @param command - The raw command (e.g., SQL string, shell command, or remote API payload).\n * @param parameters - Optional array of bound parameters for safe execution (prevention of injection).\n * @param options - Driver options (transaction context, timeout).\n * @returns Promise resolving to the raw result from the driver.\n * \n * @example\n * // SQL Driver\n * await driver.execute('SELECT * FROM complex_view WHERE id = ?', [123]);\n * \n * // Mongo Driver\n * await driver.execute({ aggregate: 'orders', pipeline: [...] });\n */\n execute: z.function()\n .input(z.tuple([z.unknown(), z.array(z.unknown()).optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.unknown()))\n .describe('Execute raw command'),\n\n // ============================================================================\n // CRUD Operations\n // ============================================================================\n\n /**\n * Find multiple records matching the structured query.\n * Parsing the QueryAST is the responsibility of the driver implementation.\n * \n * @param object - The name of the object/table to query (e.g. 'account').\n * @param query - The structured QueryAST (filters, sorts, joins, pagination).\n * @param options - Driver options.\n * @returns Array of records.\n * \n * @example\n * await driver.find('account', {\n * filters: [['status', '=', 'active'], 'and', ['amount', '>', 500]],\n * sort: [{ field: 'created_at', order: 'desc' }],\n * top: 10\n * });\n * @returns Array of records.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n find: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown()))))\n .describe('Find records'),\n\n /**\n * Stream records matching the structured query.\n * Optimized for large datasets to avoid memory overflow.\n * \n * @param object - The name of the object.\n * @param query - The structured QueryAST.\n * @param options - Driver options.\n * @returns AsyncIterable/ReadableStream of records.\n */\n findStream: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.unknown())\n .describe('Stream records (AsyncIterable)'),\n\n /**\n * Find a single record by query.\n * Similar to find(), but returns only the first match or null.\n * \n * @param object - The name of the object.\n * @param query - QueryAST.\n * @param options - Driver options.\n * @returns The record or null.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n findOne: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown()).nullable()))\n .describe('Find one record'),\n\n /**\n * Create a new record.\n * \n * @param object - The object name.\n * @param data - Key-value map of field data.\n * @param options - Driver options.\n * @returns The created record, including server-generated fields (id, created_at, etc.).\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n create: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Create record'),\n\n /**\n * Update an existing record by ID.\n * \n * @param object - The object name.\n * @param id - The unique identifier of the record.\n * @param data - The fields to update.\n * @param options - Driver options.\n * @returns The updated record.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n update: z.function()\n .input(z.tuple([z.string(), z.string().or(z.number()), z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Update record'),\n\n /**\n * Upsert (Update or Insert) a record.\n * \n * @param object - The object name.\n * @param data - The data to upsert.\n * @param conflictKeys - Fields to check for conflict (uniqueness).\n * @param options - Driver options.\n * @returns The created or updated record.\n */\n upsert: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), z.array(z.string()).optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Upsert record'),\n\n /**\n * Delete a record by ID.\n * \n * @param object - The object name.\n * @param id - The unique identifier of the record.\n * @param options - Driver options.\n * @returns True if deleted, false if not found.\n */\n delete: z.function()\n .input(z.tuple([z.string(), z.string().or(z.number()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.boolean()))\n .describe('Delete record'),\n\n /**\n * Count records matching a query.\n * \n * @param object - The object name.\n * @param query - Optional filtering criteria.\n * @param options - Driver options.\n * @returns Total count.\n */\n count: z.function()\n .input(z.tuple([z.string(), QuerySchema.optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .describe('Count records'),\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n\n /**\n * Create multiple records in a single batch.\n * Optimized for performance.\n * \n * @param object - The object name.\n * @param dataArray - Array of record data.\n * @returns Array of created records.\n */\n bulkCreate: z.function()\n .input(z.tuple([z.string(), z.array(z.record(z.string(), z.unknown())), DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown())))),\n\n /**\n * Update multiple records in a single batch.\n * \n * @param object - The object name.\n * @param updates - Array of objects containing {id, data}.\n * @returns Array of updated records.\n */\n bulkUpdate: z.function()\n .input(z.tuple([z.string(), z.array(z.object({ id: z.string().or(z.number()), data: z.record(z.string(), z.unknown()) })), DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown())))),\n\n /**\n * Delete multiple records in a single batch.\n * \n * @param object - The object name.\n * @param ids - Array of record IDs.\n */\n bulkDelete: z.function()\n .input(z.tuple([z.string(), z.array(z.string().or(z.number())), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void())),\n\n /**\n * Update multiple records matching a query.\n * Direct database push-down. DOES NOT trigger per-record hooks.\n * \n * @param object - The object name.\n * @param query - The filtering criteria.\n * @param data - The data to update.\n * @returns Count of modified records.\n */\n updateMany: z.function()\n .input(z.tuple([z.string(), QuerySchema, z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .optional(),\n\n /**\n * Delete multiple records matching a query.\n * Direct database push-down. DOES NOT trigger per-record hooks.\n * \n * @param object - The object name.\n * @param query - The filtering criteria.\n * @returns Count of deleted records.\n */\n deleteMany: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .optional(),\n\n // ============================================================================\n // Transaction Management\n // ============================================================================\n\n /**\n * Begin a new database transaction.\n * @param options - Isolation level and other settings.\n * @returns A transaction handle to be passed to subsequent operations via `options.transaction`.\n */\n beginTransaction: z.function()\n .input(z.tuple([z.object({\n isolationLevel: IsolationLevelEnum.optional()\n }).optional()]))\n .output(z.promise(z.unknown()))\n .describe('Start transaction'),\n\n /**\n * Commit the transaction.\n * @param transaction - The transaction handle.\n */\n commit: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.promise(z.void()))\n .describe('Commit transaction'),\n\n /**\n * Rollback the transaction.\n * @param transaction - The transaction handle.\n */\n rollback: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.promise(z.void()))\n .describe('Rollback transaction'),\n\n // ============================================================================\n // Schema Management\n // ============================================================================\n\n /**\n * Synchronize the database schema with the Object definition.\n * This is an idempotent operation: it should create tables if missing, \n * add columns if missing, and update indexes.\n * \n * @param object - The object name.\n * @param schema - The full Object Schema (fields, indexes, etc).\n * @param options - Driver options.\n */\n syncSchema: z.function()\n .input(z.tuple([z.string(), z.unknown(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void()))\n .describe('Sync object schema to DB'),\n\n /**\n * Batch-synchronize multiple object schemas with fewer round-trips.\n *\n * Drivers that advertise `supports.batchSchemaSync = true` MUST implement\n * this method. The engine will call it once with every\n * `{ object, schema }` pair instead of calling `syncSchema()` N times.\n *\n * @param schemas - Array of `{ object: string; schema: unknown }` pairs.\n * @param options - Driver options.\n */\n syncSchemasBatch: z.function()\n .input(z.tuple([\n z.array(z.object({ object: z.string(), schema: z.unknown() })),\n DriverOptionsSchema.optional(),\n ]))\n .output(z.promise(z.void()))\n .optional()\n .describe('Batch sync multiple schemas in one round-trip'),\n \n /**\n * Drop the underlying table or collection for an object.\n * WARNING: Destructive operation.\n * \n * @param object - The object name.\n */\n dropTable: z.function()\n .input(z.tuple([z.string(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void())),\n\n /**\n * Analyze query performance.\n * Returns execution plan without executing the query (where possible).\n * \n * @param object - The object name.\n * @param query - The query to explain.\n * @returns The execution plan details.\n */\n explain: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.unknown()))\n .optional(),\n});\n\n/**\n * Connection Pool Configuration Schema\n * Manages database connection pooling for performance\n */\nexport const PoolConfigSchema = z.object({\n min: z.number().min(0).default(2).describe('Minimum number of connections in pool'),\n max: z.number().min(1).default(10).describe('Maximum number of connections in pool'),\n idleTimeoutMillis: z.number().min(0).default(30000).describe('Time in ms before idle connection is closed'),\n connectionTimeoutMillis: z.number().min(0).default(5000).describe('Time in ms to wait for available connection'),\n});\n\n/**\n * Driver Configuration Schema\n * Base configuration for database drivers\n */\nexport const DriverConfigSchema = z.object({\n name: z.string().describe('Driver instance name'),\n type: z.enum(['sql', 'nosql', 'cache', 'search', 'graph', 'timeseries']).describe('Driver type category'),\n capabilities: DriverCapabilitiesSchema.describe('Driver capability flags'),\n connectionString: z.string().optional().describe('Database connection string (driver-specific format)'),\n poolConfig: PoolConfigSchema.optional().describe('Connection pool configuration'),\n});\n\n/**\n * TypeScript types\n */\nexport type DriverOptions = z.infer;\nexport type DriverCapabilities = z.infer;\nexport type DriverInterface = z.infer;\nexport type DriverConfig = z.infer;\nexport type PoolConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DriverConfigSchema } from './driver.zod';\n\n/**\n * SQL Dialect Enumeration\n * Supported SQL database dialects\n */\nexport const SQLDialectSchema = z.enum([\n 'postgresql',\n 'mysql',\n 'sqlite',\n 'mssql',\n 'oracle',\n 'mariadb',\n]);\n\nexport type SQLDialect = z.infer;\n\n/**\n * Data Type Mapping Schema\n * Maps ObjectStack field types to SQL-specific data types\n * \n * @example PostgreSQL data type mapping\n * {\n * text: 'VARCHAR(255)',\n * number: 'NUMERIC',\n * boolean: 'BOOLEAN',\n * date: 'DATE',\n * datetime: 'TIMESTAMP',\n * json: 'JSONB',\n * uuid: 'UUID',\n * binary: 'BYTEA'\n * }\n */\nexport const DataTypeMappingSchema = z.object({\n text: z.string().describe('SQL type for text fields (e.g., VARCHAR, TEXT)'),\n number: z.string().describe('SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)'),\n boolean: z.string().describe('SQL type for boolean fields (e.g., BOOLEAN, BIT)'),\n date: z.string().describe('SQL type for date fields (e.g., DATE)'),\n datetime: z.string().describe('SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)'),\n json: z.string().optional().describe('SQL type for JSON fields (e.g., JSON, JSONB)'),\n uuid: z.string().optional().describe('SQL type for UUID fields (e.g., UUID, CHAR(36))'),\n binary: z.string().optional().describe('SQL type for binary fields (e.g., BLOB, BYTEA)'),\n});\n\nexport type DataTypeMapping = z.infer;\n\n/**\n * SSL Configuration Schema\n * SSL/TLS connection configuration for secure database connections\n * \n * @example PostgreSQL SSL configuration\n * {\n * rejectUnauthorized: true,\n * ca: '/path/to/ca-cert.pem',\n * cert: '/path/to/client-cert.pem',\n * key: '/path/to/client-key.pem'\n * }\n */\nexport const SSLConfigSchema = z.object({\n rejectUnauthorized: z.boolean().default(true).describe('Reject connections with invalid certificates'),\n ca: z.string().optional().describe('CA certificate file path or content'),\n cert: z.string().optional().describe('Client certificate file path or content'),\n key: z.string().optional().describe('Client private key file path or content'),\n}).refine((data) => {\n // If cert is provided, key must also be provided, and vice versa\n const hasCert = data.cert !== undefined;\n const hasKey = data.key !== undefined;\n return hasCert === hasKey;\n}, {\n message: 'Client certificate (cert) and private key (key) must be provided together',\n});\n\nexport type SSLConfig = z.infer;\n\n/**\n * SQL Driver Configuration Schema\n * Extended driver configuration specific to SQL databases\n * \n * @example PostgreSQL driver configuration\n * {\n * name: 'primary-db',\n * type: 'sql',\n * dialect: 'postgresql',\n * connectionString: 'postgresql://user:pass@localhost:5432/mydb',\n * dataTypeMapping: {\n * text: 'VARCHAR(255)',\n * number: 'NUMERIC',\n * boolean: 'BOOLEAN',\n * date: 'DATE',\n * datetime: 'TIMESTAMP',\n * json: 'JSONB',\n * uuid: 'UUID',\n * binary: 'BYTEA'\n * },\n * ssl: true,\n * sslConfig: {\n * rejectUnauthorized: true,\n * ca: '/etc/ssl/certs/ca.pem'\n * },\n * poolConfig: {\n * min: 2,\n * max: 10,\n * idleTimeoutMillis: 30000,\n * connectionTimeoutMillis: 5000\n * },\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: true,\n * bulkDelete: true,\n * transactions: true,\n * savepoints: true,\n * isolationLevels: ['read-committed', 'repeatable-read', 'serializable'],\n * queryFilters: true,\n * queryAggregations: true,\n * querySorting: true,\n * queryPagination: true,\n * queryWindowFunctions: true,\n * querySubqueries: true,\n * queryCTE: true,\n * joins: true,\n * fullTextSearch: true,\n * jsonQuery: true,\n * geospatialQuery: false,\n * streaming: true,\n * jsonFields: true,\n * arrayFields: true,\n * vectorSearch: true,\n * schemaSync: true,\n * migrations: true,\n * indexes: true,\n * connectionPooling: true,\n * preparedStatements: true,\n * queryCache: false\n * }\n * }\n */\nexport const SQLDriverConfigSchema = DriverConfigSchema.extend({\n type: z.literal('sql').describe('Driver type must be \"sql\"'),\n dialect: SQLDialectSchema.describe('SQL database dialect'),\n dataTypeMapping: DataTypeMappingSchema.describe('SQL data type mapping configuration'),\n ssl: z.boolean().default(false).describe('Enable SSL/TLS connection'),\n sslConfig: SSLConfigSchema.optional().describe('SSL/TLS configuration (required when ssl is true)'),\n}).refine((data) => {\n // If ssl is enabled, sslConfig must be provided\n if (data.ssl && !data.sslConfig) {\n return false;\n }\n return true;\n}, {\n message: 'sslConfig is required when ssl is true',\n});\n\nexport type SQLDriverConfig = z.infer;\n\n// ==========================================================================\n// SQLite-Specific Constants\n// ==========================================================================\n\n/**\n * Default data type mappings for SQLite/libSQL dialect.\n *\n * SQLite uses a simplified type system with type affinity:\n * - TEXT: strings, dates, UUIDs\n * - REAL: floating-point numbers\n * - INTEGER: integers, booleans\n * - BLOB: binary data\n *\n * @see https://www.sqlite.org/datatype3.html\n */\nexport const SQLiteDataTypeMappingDefaults: DataTypeMapping = {\n text: 'TEXT',\n number: 'REAL',\n boolean: 'INTEGER',\n date: 'TEXT',\n datetime: 'TEXT',\n json: 'TEXT',\n uuid: 'TEXT',\n binary: 'BLOB',\n};\n\n/**\n * SQLite ALTER TABLE Limitations.\n *\n * SQLite has limited ALTER TABLE support compared to other SQL databases.\n * This constant documents the known limitations that affect migration planning.\n * The schema diff service must use the \"table rebuild\" strategy for operations\n * that SQLite cannot perform natively.\n *\n * @see https://www.sqlite.org/lang_altertable.html\n */\nexport const SQLiteAlterTableLimitations = {\n /** SQLite supports ADD COLUMN */\n supportsAddColumn: true,\n /** SQLite supports RENAME COLUMN (3.25.0+) */\n supportsRenameColumn: true,\n /** SQLite supports DROP COLUMN (3.35.0+) */\n supportsDropColumn: true,\n /** SQLite does NOT support MODIFY/ALTER COLUMN type */\n supportsModifyColumn: false,\n /** SQLite does NOT support adding constraints to existing columns */\n supportsAddConstraint: false,\n /**\n * When an unsupported alteration is needed, the migration planner\n * must use the 12-step table rebuild strategy:\n * 1. CREATE new table with desired schema\n * 2. Copy data from old table\n * 3. DROP old table\n * 4. RENAME new table to old name\n */\n rebuildStrategy: 'create_copy_drop_rename',\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DriverConfigSchema } from './driver.zod';\n\n/**\n * NoSQL Database Type Enumeration\n * Supported NoSQL database types\n */\nexport const NoSQLDatabaseTypeSchema = z.enum([\n 'mongodb',\n 'couchdb',\n 'dynamodb',\n 'cassandra',\n 'redis',\n 'elasticsearch',\n 'neo4j',\n 'orientdb',\n]);\n\nexport type NoSQLDatabaseType = z.infer;\n\n/**\n * NoSQL Query Operation Types\n * Different types of operations supported by NoSQL databases\n */\nexport const NoSQLOperationTypeSchema = z.enum([\n 'find', // Query documents/records\n 'findOne', // Get single document\n 'insert', // Insert document\n 'update', // Update document\n 'delete', // Delete document\n 'aggregate', // Aggregation pipeline\n 'mapReduce', // MapReduce operation\n 'count', // Count documents\n 'distinct', // Get distinct values\n 'createIndex', // Create index\n 'dropIndex', // Drop index\n]);\n\nexport type NoSQLOperationType = z.infer;\n\n/**\n * NoSQL Consistency Level\n * Consistency guarantees for distributed NoSQL databases\n * \n * Consistency levels (from strongest to weakest):\n * - **all**: All replicas must respond (strongest consistency, lowest availability)\n * - **quorum**: Majority of replicas must respond (balanced)\n * - **one**: Any single replica responds (weakest consistency, highest availability)\n * - **local_quorum**: Majority of replicas in local datacenter\n * - **each_quorum**: Quorum of replicas in each datacenter\n * - **eventual**: Eventual consistency (highest availability, weakest consistency)\n */\nexport const ConsistencyLevelSchema = z.enum([\n 'all',\n 'quorum',\n 'one',\n 'local_quorum',\n 'each_quorum',\n 'eventual',\n]);\n\nexport type ConsistencyLevel = z.infer;\n\n/**\n * NoSQL Index Type\n * Types of indexes supported by NoSQL databases\n */\nexport const NoSQLIndexTypeSchema = z.enum([\n 'single', // Single field index\n 'compound', // Multiple fields index\n 'unique', // Unique constraint\n 'text', // Full-text search index\n 'geospatial', // Geospatial index (2d, 2dsphere)\n 'hashed', // Hashed index for sharding\n 'ttl', // Time-to-live index (auto-deletion)\n 'sparse', // Sparse index (only indexed documents with field)\n]);\n\nexport type NoSQLIndexType = z.infer;\n\n/**\n * NoSQL Sharding Configuration\n * Configuration for horizontal partitioning across multiple nodes\n */\nexport const ShardingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable sharding'),\n shardKey: z.string().optional().describe('Field to use as shard key'),\n shardingStrategy: z.enum(['hash', 'range', 'zone']).optional().describe('Sharding strategy'),\n numShards: z.number().int().positive().optional().describe('Number of shards'),\n});\n\nexport type ShardingConfig = z.infer;\n\n/**\n * NoSQL Replication Configuration\n * Configuration for data replication across nodes\n */\nexport const ReplicationConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable replication'),\n replicaSetName: z.string().optional().describe('Replica set name'),\n replicas: z.number().int().positive().optional().describe('Number of replicas'),\n readPreference: z.enum(['primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'])\n .optional()\n .describe('Read preference for replica set'),\n writeConcern: z.enum(['majority', 'acknowledged', 'unacknowledged'])\n .optional()\n .describe('Write concern level'),\n});\n\nexport type ReplicationConfig = z.infer;\n\n/**\n * Document Schema Validation\n * Schema validation rules for document-based NoSQL databases\n */\nexport const DocumentSchemaValidationSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable schema validation'),\n validationLevel: z.enum(['strict', 'moderate', 'off']).optional().describe('Validation strictness'),\n validationAction: z.enum(['error', 'warn']).optional().describe('Action on validation failure'),\n jsonSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for validation'),\n});\n\nexport type DocumentSchemaValidation = z.infer;\n\n/**\n * NoSQL Data Type Mapping Schema\n * Maps ObjectStack field types to NoSQL-specific data types\n * \n * @example MongoDB data type mapping\n * {\n * text: 'string',\n * number: 'double',\n * boolean: 'bool',\n * date: 'date',\n * datetime: 'date',\n * json: 'object',\n * uuid: 'string',\n * binary: 'binData',\n * array: 'array',\n * objectId: 'objectId'\n * }\n */\nexport const NoSQLDataTypeMappingSchema = z.object({\n text: z.string().describe('NoSQL type for text fields'),\n number: z.string().describe('NoSQL type for number fields'),\n boolean: z.string().describe('NoSQL type for boolean fields'),\n date: z.string().describe('NoSQL type for date fields'),\n datetime: z.string().describe('NoSQL type for datetime fields'),\n json: z.string().optional().describe('NoSQL type for JSON/object fields'),\n uuid: z.string().optional().describe('NoSQL type for UUID fields'),\n binary: z.string().optional().describe('NoSQL type for binary fields'),\n array: z.string().optional().describe('NoSQL type for array fields'),\n objectId: z.string().optional().describe('NoSQL type for ObjectID fields (MongoDB)'),\n geopoint: z.string().optional().describe('NoSQL type for geospatial point fields'),\n});\n\nexport type NoSQLDataTypeMapping = z.infer;\n\n/**\n * NoSQL Driver Configuration Schema\n * Extended driver configuration specific to NoSQL databases\n * \n * @example MongoDB driver configuration\n * {\n * name: 'primary-mongo',\n * type: 'nosql',\n * databaseType: 'mongodb',\n * connectionString: 'mongodb://user:pass@localhost:27017/mydb',\n * dataTypeMapping: {\n * text: 'string',\n * number: 'double',\n * boolean: 'bool',\n * date: 'date',\n * datetime: 'date',\n * json: 'object',\n * uuid: 'string',\n * binary: 'binData',\n * array: 'array',\n * objectId: 'objectId'\n * },\n * consistency: 'quorum',\n * replication: {\n * enabled: true,\n * replicaSetName: 'rs0',\n * replicas: 3,\n * readPreference: 'primaryPreferred',\n * writeConcern: 'majority'\n * },\n * sharding: {\n * enabled: true,\n * shardKey: '_id',\n * shardingStrategy: 'hash',\n * numShards: 4\n * },\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: true,\n * bulkDelete: true,\n * transactions: true,\n * savepoints: false,\n * queryFilters: true,\n * queryAggregations: true,\n * querySorting: true,\n * queryPagination: true,\n * queryWindowFunctions: false,\n * querySubqueries: false,\n * queryCTE: false,\n * joins: false,\n * fullTextSearch: true,\n * jsonQuery: true,\n * geospatialQuery: true,\n * streaming: true,\n * jsonFields: true,\n * arrayFields: true,\n * vectorSearch: false,\n * schemaSync: true,\n * migrations: false,\n * indexes: true,\n * connectionPooling: true,\n * preparedStatements: false,\n * queryCache: false\n * }\n * }\n * \n * @example DynamoDB driver configuration\n * {\n * name: 'dynamodb-main',\n * type: 'nosql',\n * databaseType: 'dynamodb',\n * region: 'us-east-1',\n * accessKeyId: 'AKIAIOSFODNN7EXAMPLE',\n * secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n * consistency: 'eventual',\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: false,\n * bulkDelete: false,\n * transactions: true,\n * queryFilters: true,\n * queryAggregations: false,\n * querySorting: true,\n * queryPagination: true,\n * fullTextSearch: false,\n * jsonQuery: true,\n * indexes: true\n * }\n * }\n */\nexport const NoSQLDriverConfigSchema = DriverConfigSchema.extend({\n type: z.literal('nosql').describe('Driver type must be \"nosql\"'),\n databaseType: NoSQLDatabaseTypeSchema.describe('Specific NoSQL database type'),\n dataTypeMapping: NoSQLDataTypeMappingSchema.describe('NoSQL data type mapping configuration'),\n \n /**\n * Consistency level for reads/writes\n */\n consistency: ConsistencyLevelSchema.optional().describe('Consistency level for operations'),\n \n /**\n * Replication configuration\n */\n replication: ReplicationConfigSchema.optional().describe('Replication configuration'),\n \n /**\n * Sharding configuration\n */\n sharding: ShardingConfigSchema.optional().describe('Sharding configuration'),\n \n /**\n * Schema validation rules (for document databases)\n */\n schemaValidation: DocumentSchemaValidationSchema.optional().describe('Document schema validation'),\n \n /**\n * AWS Region (for DynamoDB, DocumentDB, etc.)\n */\n region: z.string().optional().describe('AWS region (for managed NoSQL services)'),\n \n /**\n * AWS Access Key ID (for DynamoDB, DocumentDB, etc.)\n */\n accessKeyId: z.string().optional().describe('AWS access key ID'),\n \n /**\n * AWS Secret Access Key (for DynamoDB, DocumentDB, etc.)\n */\n secretAccessKey: z.string().optional().describe('AWS secret access key'),\n \n /**\n * Time-to-live (TTL) field name\n * Automatically delete documents after a specified time\n */\n ttlField: z.string().optional().describe('Field name for TTL (auto-deletion)'),\n \n /**\n * Maximum document size in bytes\n */\n maxDocumentSize: z.number().int().positive().optional().describe('Maximum document size in bytes'),\n \n /**\n * Collection/Table name prefix\n * Useful for multi-tenancy or environment isolation\n */\n collectionPrefix: z.string().optional().describe('Prefix for collection/table names'),\n});\n\nexport type NoSQLDriverConfig = z.infer;\n\n/**\n * NoSQL Query Options\n * Additional options for NoSQL queries\n */\nexport const NoSQLQueryOptionsSchema = z.object({\n /**\n * Consistency level for this query\n */\n consistency: ConsistencyLevelSchema.optional().describe('Consistency level override'),\n \n /**\n * Read from secondary replicas\n */\n readFromSecondary: z.boolean().optional().describe('Allow reading from secondary replicas'),\n \n /**\n * Projection (fields to include/exclude)\n */\n projection: z.record(z.string(), z.union([z.literal(0), z.literal(1)])).optional().describe('Field projection'),\n \n /**\n * Query timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().describe('Query timeout (ms)'),\n \n /**\n * Use cursor for large result sets\n */\n useCursor: z.boolean().optional().describe('Use cursor instead of loading all results'),\n \n /**\n * Batch size for cursor iteration\n */\n batchSize: z.number().int().positive().optional().describe('Cursor batch size'),\n \n /**\n * Enable query profiling\n */\n profile: z.boolean().optional().describe('Enable query profiling'),\n \n /**\n * Use hinted index\n */\n hint: z.string().optional().describe('Index hint for query optimization'),\n});\n\nexport type NoSQLQueryOptions = z.infer;\n\n/**\n * NoSQL Aggregation Pipeline Stage\n * Represents a single stage in an aggregation pipeline (MongoDB-style)\n */\nexport const AggregationStageSchema = z.object({\n /**\n * Stage operator (e.g., $match, $group, $sort, $project)\n */\n operator: z.string().describe('Aggregation operator (e.g., $match, $group, $sort)'),\n \n /**\n * Stage parameters/options\n */\n options: z.record(z.string(), z.unknown()).describe('Stage-specific options'),\n});\n\nexport type AggregationStage = z.infer;\n\n/**\n * NoSQL Aggregation Pipeline\n * Sequence of aggregation stages for complex data transformations\n */\nexport const AggregationPipelineSchema = z.object({\n /**\n * Collection/Table to aggregate\n */\n collection: z.string().describe('Collection/table name'),\n \n /**\n * Pipeline stages\n */\n stages: z.array(AggregationStageSchema).describe('Aggregation pipeline stages'),\n \n /**\n * Additional options\n */\n options: NoSQLQueryOptionsSchema.optional().describe('Query options'),\n});\n\nexport type AggregationPipeline = z.infer;\n\n/**\n * NoSQL Index Definition\n * Definition for creating indexes in NoSQL databases\n */\nexport const NoSQLIndexSchema = z.object({\n /**\n * Index name\n */\n name: z.string().describe('Index name'),\n \n /**\n * Index type\n */\n type: NoSQLIndexTypeSchema.describe('Index type'),\n \n /**\n * Fields to index\n * For compound indexes, order matters\n */\n fields: z.array(z.object({\n field: z.string().describe('Field name'),\n order: z.enum(['asc', 'desc', 'text', '2dsphere']).optional().describe('Index order or type'),\n })).describe('Fields to index'),\n \n /**\n * Unique constraint\n */\n unique: z.boolean().default(false).describe('Enforce uniqueness'),\n \n /**\n * Sparse index (only index documents with the field)\n */\n sparse: z.boolean().default(false).describe('Sparse index'),\n \n /**\n * TTL in seconds (for TTL indexes)\n */\n expireAfterSeconds: z.number().int().positive().optional().describe('TTL in seconds'),\n \n /**\n * Partial index filter\n */\n partialFilterExpression: z.record(z.string(), z.unknown()).optional().describe('Partial index filter'),\n \n /**\n * Background index creation\n */\n background: z.boolean().default(false).describe('Create index in background'),\n});\n\nexport type NoSQLIndex = z.infer;\n\n/**\n * NoSQL Transaction Options\n * Options for NoSQL transactions (where supported)\n */\nexport const NoSQLTransactionOptionsSchema = z.object({\n /**\n * Read concern level\n */\n readConcern: z.enum(['local', 'majority', 'linearizable', 'snapshot']).optional().describe('Read concern level'),\n \n /**\n * Write concern level\n */\n writeConcern: z.enum(['majority', 'acknowledged', 'unacknowledged']).optional().describe('Write concern level'),\n \n /**\n * Read preference\n */\n readPreference: z.enum(['primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'])\n .optional()\n .describe('Read preference'),\n \n /**\n * Transaction timeout in milliseconds\n */\n maxCommitTimeMS: z.number().int().positive().optional().describe('Transaction commit timeout (ms)'),\n});\n\nexport type NoSQLTransactionOptions = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data Import Strategy\n * Defines how the engine handles existing records.\n */\nexport const DatasetMode = z.enum([\n 'insert', // Try to insert, fail on duplicate\n 'update', // Only update found records, ignore new\n 'upsert', // Create new or Update existing (Standard)\n 'replace', // Delete ALL records in object then insert (Dangerous - use for cache tables)\n 'ignore' // Try to insert, silently skip duplicates\n]);\n\n/**\n * Dataset Schema (Seed Data / Fixtures)\n * \n * Standardized format for transporting data.\n * Used for:\n * 1. System Bootstrapping (Admin accounts, Standard Roles)\n * 2. Reference Data (Countries, Currencies)\n * 3. Demo/Test Data\n */\nexport const DatasetSchema = z.object({\n /** \n * Target Object \n * The machine name of the object to populate.\n */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target Object Name'),\n\n /** \n * Idempotency Key (The \"Upsert\" Key)\n * The field used to check if a record already exists.\n * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'.\n * Standard: 'id' is rarely used for portable seed data — prefer natural keys.\n */\n externalId: z.string().default('name').describe('Field match for uniqueness check'),\n\n /** \n * Import Strategy\n */\n mode: DatasetMode.default('upsert').describe('Conflict resolution strategy'),\n\n /**\n * Environment Scope\n * - 'all': Always load\n * - 'dev': Only for development/demo\n * - 'test': Only for CI/CD tests\n */\n env: z.array(z.enum(['prod', 'dev', 'test'])).default(['prod', 'dev', 'test']).describe('Applicable environments'),\n\n /** \n * The Payload\n * Array of raw JSON objects matching the Object Schema.\n */\n records: z.array(z.record(z.string(), z.unknown())).describe('Data records'),\n});\n\n/** Parsed/output type — all defaults are applied (env, mode, externalId always present) */\nexport type Dataset = z.infer;\n\n/** Input type — fields with defaults (env, mode, externalId) are optional */\nexport type DatasetInput = z.input;\n\nexport type DatasetImportMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DatasetSchema, DatasetMode } from './dataset.zod';\n\n/**\n * # Seed Loader Protocol\n *\n * Defines the schemas for metadata-driven seed data loading with automatic\n * relationship resolution, dependency ordering, and multi-pass insertion.\n *\n * ## Architecture Alignment\n * - **Salesforce Data Loader**: External ID-based upsert with relationship resolution\n * - **ServiceNow**: Sys ID and display value mapping during import\n * - **Airtable**: Linked record resolution via display names\n *\n * ## Loading Flow\n * ```\n * 1. Build object dependency graph from field metadata (lookup/master_detail)\n * 2. Topological sort → determine insert order (parents before children)\n * 3. Pass 1: Insert/upsert records, resolve references via externalId\n * 4. Pass 2: Fill deferred references (circular/delayed dependencies)\n * 5. Validate & report unresolved references\n * 6. Return structured result with per-object stats\n * ```\n */\n\n// ==========================================================================\n// 1. Reference Resolution\n// ==========================================================================\n\n/**\n * Describes how a single field reference should be resolved during seed loading.\n *\n * When a lookup/master_detail field value is not an internal ID, the loader\n * attempts to match it against the target object's externalId field.\n */\nexport const ReferenceResolutionSchema = z.object({\n /** The field name on the source object (e.g., 'account_id') */\n field: z.string().describe('Source field name containing the reference value'),\n\n /** The target object being referenced (e.g., 'account') */\n targetObject: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target object name (snake_case)'),\n\n /**\n * The field on the target object used to match the reference value.\n * Defaults to the target object's externalId (usually 'name').\n */\n targetField: z.string().default('name').describe('Field on target object used for matching'),\n\n /** The field type that triggered this resolution (lookup or master_detail) */\n fieldType: z.enum(['lookup', 'master_detail']).describe('Relationship field type'),\n}).describe('Describes how a field reference is resolved during seed loading');\n\nexport type ReferenceResolution = z.infer;\n\n// ==========================================================================\n// 2. Object Dependency Node\n// ==========================================================================\n\n/**\n * Represents a single object in the dependency graph.\n * Built from object metadata by inspecting lookup/master_detail fields.\n */\nexport const ObjectDependencyNodeSchema = z.object({\n /** Object machine name */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Object name (snake_case)'),\n\n /**\n * Objects that this object depends on (via lookup/master_detail fields).\n * These must be loaded before this object.\n */\n dependsOn: z.array(z.string()).describe('Objects this object depends on'),\n\n /**\n * Field-level reference details for each dependency.\n * Maps field name → reference resolution info.\n */\n references: z.array(ReferenceResolutionSchema).describe('Field-level reference details'),\n}).describe('Object node in the seed data dependency graph');\n\nexport type ObjectDependencyNode = z.infer;\n\n// ==========================================================================\n// 3. Object Dependency Graph\n// ==========================================================================\n\n/**\n * The complete object dependency graph for seed data loading.\n * Used to determine topological insert order and detect circular dependencies.\n */\nexport const ObjectDependencyGraphSchema = z.object({\n /** All object nodes in the graph */\n nodes: z.array(ObjectDependencyNodeSchema).describe('All objects in the dependency graph'),\n\n /**\n * Topologically sorted object names for insertion order.\n * Parent objects appear before child objects.\n */\n insertOrder: z.array(z.string()).describe('Topologically sorted insert order'),\n\n /**\n * Circular dependency chains detected in the graph.\n * Each chain is an array of object names forming a cycle.\n * When present, the loader must use a multi-pass strategy.\n *\n * @example [['project', 'task', 'project']]\n */\n circularDependencies: z.array(z.array(z.string())).default([])\n .describe('Circular dependency chains (e.g., [[\"a\", \"b\", \"a\"]])'),\n}).describe('Complete object dependency graph for seed data loading');\n\nexport type ObjectDependencyGraph = z.infer;\n\n// ==========================================================================\n// 4. Reference Resolution Error\n// ==========================================================================\n\n/**\n * Actionable error for a failed reference resolution.\n * Provides all context needed to diagnose and fix the broken reference.\n *\n * Aligns with Salesforce Data Loader error reporting patterns:\n * field name, target object, attempted value, and reason.\n */\nexport const ReferenceResolutionErrorSchema = z.object({\n /** The source object containing the broken reference */\n sourceObject: z.string().describe('Object with the broken reference'),\n\n /** The field containing the unresolved value */\n field: z.string().describe('Field name with unresolved reference'),\n\n /** The target object that was searched */\n targetObject: z.string().describe('Target object searched for the reference'),\n\n /** The externalId field used for matching on the target object */\n targetField: z.string().describe('ExternalId field used for matching'),\n\n /** The value that could not be resolved */\n attemptedValue: z.unknown().describe('Value that failed to resolve'),\n\n /** The index of the record in the dataset's records array */\n recordIndex: z.number().int().min(0).describe('Index of the record in the dataset'),\n\n /** Human-readable error message */\n message: z.string().describe('Human-readable error description'),\n}).describe('Actionable error for a failed reference resolution');\n\nexport type ReferenceResolutionError = z.infer;\n\n// ==========================================================================\n// 5. Seed Loader Configuration\n// ==========================================================================\n\n/**\n * Configuration for the seed data loader.\n * Controls behavior for reference resolution, error handling, and validation.\n */\nexport const SeedLoaderConfigSchema = z.object({\n /**\n * Dry-run mode: validate all references without writing data.\n * Surfaces broken references before any mutations occur.\n * @default false\n */\n dryRun: z.boolean().default(false)\n .describe('Validate references without writing data'),\n\n /**\n * Whether to halt on the first reference resolution error.\n * When false, collects all errors and continues loading.\n * @default false\n */\n haltOnError: z.boolean().default(false)\n .describe('Stop on first reference resolution error'),\n\n /**\n * Enable multi-pass loading for circular dependencies.\n * Pass 1: Insert records with null for circular references.\n * Pass 2: Update records to fill deferred references.\n * @default true\n */\n multiPass: z.boolean().default(true)\n .describe('Enable multi-pass loading for circular dependencies'),\n\n /**\n * Default dataset mode when not specified per-dataset.\n * @default 'upsert'\n */\n defaultMode: DatasetMode.default('upsert')\n .describe('Default conflict resolution strategy'),\n\n /**\n * Maximum number of records to process in a single batch.\n * Controls memory usage for large datasets.\n * @default 1000\n */\n batchSize: z.number().int().min(1).default(1000)\n .describe('Maximum records per batch insert/upsert'),\n\n /**\n * Whether to wrap the entire load operation in a transaction.\n * When true, all-or-nothing semantics apply.\n * @default false\n */\n transaction: z.boolean().default(false)\n .describe('Wrap entire load in a transaction (all-or-nothing)'),\n\n /**\n * Environment filter. Only datasets matching this environment are loaded.\n * When not specified, all datasets are loaded regardless of env scope.\n */\n env: z.enum(['prod', 'dev', 'test']).optional()\n .describe('Only load datasets matching this environment'),\n}).describe('Seed data loader configuration');\n\nexport type SeedLoaderConfig = z.infer;\n\n/** Input type — all fields with defaults are optional */\nexport type SeedLoaderConfigInput = z.input;\n\n// ==========================================================================\n// 6. Per-Object Load Result\n// ==========================================================================\n\n/**\n * Result of loading a single object's dataset.\n */\nexport const DatasetLoadResultSchema = z.object({\n /** Target object name */\n object: z.string().describe('Object that was loaded'),\n\n /** Import mode used */\n mode: DatasetMode.describe('Import mode used'),\n\n /** Number of records successfully inserted */\n inserted: z.number().int().min(0).describe('Records inserted'),\n\n /** Number of records successfully updated (upsert matched existing) */\n updated: z.number().int().min(0).describe('Records updated'),\n\n /** Number of records skipped (mode: ignore, or already exists) */\n skipped: z.number().int().min(0).describe('Records skipped'),\n\n /** Number of records with errors */\n errored: z.number().int().min(0).describe('Records with errors'),\n\n /** Total records in the dataset */\n total: z.number().int().min(0).describe('Total records in dataset'),\n\n /** Number of references resolved via externalId */\n referencesResolved: z.number().int().min(0).describe('References resolved via externalId'),\n\n /** Number of references deferred to pass 2 (circular dependencies) */\n referencesDeferred: z.number().int().min(0).describe('References deferred to second pass'),\n\n /** Reference resolution errors for this object */\n errors: z.array(ReferenceResolutionErrorSchema).default([])\n .describe('Reference resolution errors'),\n}).describe('Result of loading a single dataset');\n\nexport type DatasetLoadResult = z.infer;\n\n// ==========================================================================\n// 7. Seed Loader Result\n// ==========================================================================\n\n/**\n * Complete result of a seed loading operation.\n * Aggregates all per-object results and provides summary statistics.\n */\nexport const SeedLoaderResultSchema = z.object({\n /** Whether the overall load operation succeeded */\n success: z.boolean().describe('Overall success status'),\n\n /** Was this a dry-run (validation only, no writes)? */\n dryRun: z.boolean().describe('Whether this was a dry-run'),\n\n /** The dependency graph used for ordering */\n dependencyGraph: ObjectDependencyGraphSchema.describe('Object dependency graph'),\n\n /** Per-object load results, in the order they were processed */\n results: z.array(DatasetLoadResultSchema).describe('Per-object load results'),\n\n /** All reference resolution errors across all objects */\n errors: z.array(ReferenceResolutionErrorSchema).describe('All reference resolution errors'),\n\n /** Summary statistics */\n summary: z.object({\n /** Total objects processed */\n objectsProcessed: z.number().int().min(0).describe('Total objects processed'),\n\n /** Total records across all objects */\n totalRecords: z.number().int().min(0).describe('Total records across all objects'),\n\n /** Total records inserted */\n totalInserted: z.number().int().min(0).describe('Total records inserted'),\n\n /** Total records updated */\n totalUpdated: z.number().int().min(0).describe('Total records updated'),\n\n /** Total records skipped */\n totalSkipped: z.number().int().min(0).describe('Total records skipped'),\n\n /** Total records with errors */\n totalErrored: z.number().int().min(0).describe('Total records with errors'),\n\n /** Total references resolved via externalId */\n totalReferencesResolved: z.number().int().min(0).describe('Total references resolved'),\n\n /** Total references deferred to second pass */\n totalReferencesDeferred: z.number().int().min(0).describe('Total references deferred'),\n\n /** Number of circular dependency chains detected */\n circularDependencyCount: z.number().int().min(0).describe('Circular dependency chains detected'),\n\n /** Duration of the load operation in milliseconds */\n durationMs: z.number().min(0).describe('Load duration in milliseconds'),\n }).describe('Summary statistics'),\n}).describe('Complete seed loader result');\n\nexport type SeedLoaderResult = z.infer;\n\n// ==========================================================================\n// 8. Seed Loader Request\n// ==========================================================================\n\n/**\n * Input request for the seed loader.\n * Combines datasets with loader configuration.\n */\nexport const SeedLoaderRequestSchema = z.object({\n /** Datasets to load */\n datasets: z.array(DatasetSchema).min(1).describe('Datasets to load'),\n\n /** Loader configuration */\n config: z.preprocess((val) => val ?? {}, SeedLoaderConfigSchema).describe('Loader configuration'),\n}).describe('Seed loader request with datasets and configuration');\n\nexport type SeedLoaderRequest = z.infer;\n\n/** Input type — config defaults are optional */\nexport type SeedLoaderRequestInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Document Version Schema\n * \n * Represents a single version of a document in a version-controlled system.\n * Each version is immutable and maintains its own metadata and download URL.\n * \n * @example\n * ```json\n * {\n * \"versionNumber\": 2,\n * \"createdAt\": 1704067200000,\n * \"createdBy\": \"user_123\",\n * \"size\": 2048576,\n * \"checksum\": \"a1b2c3d4e5f6\",\n * \"downloadUrl\": \"https://storage.example.com/docs/v2/file.pdf\",\n * \"isLatest\": true\n * }\n * ```\n */\nexport const DocumentVersionSchema = z.object({\n /**\n * Sequential version number (increments with each new version)\n */\n versionNumber: z.number().describe('Version number'),\n\n /**\n * Timestamp when this version was created (Unix milliseconds)\n */\n createdAt: z.number().describe('Creation timestamp'),\n\n /**\n * User ID who created this version\n */\n createdBy: z.string().describe('Creator user ID'),\n\n /**\n * File size in bytes\n */\n size: z.number().describe('File size in bytes'),\n\n /**\n * Checksum/hash of the file content (for integrity verification)\n */\n checksum: z.string().describe('File checksum'),\n\n /**\n * URL to download this specific version\n */\n downloadUrl: z.string().url().describe('Download URL'),\n\n /**\n * Whether this is the latest version\n * @default false\n */\n isLatest: z.boolean().optional().default(false).describe('Is latest version'),\n});\n\n/**\n * Document Template Schema\n * \n * Defines a reusable document template with dynamic placeholders.\n * Templates can be used to generate documents with variable content.\n * \n * @example\n * ```json\n * {\n * \"id\": \"contract-template\",\n * \"name\": \"Service Agreement\",\n * \"description\": \"Standard service agreement template\",\n * \"fileUrl\": \"https://example.com/templates/contract.docx\",\n * \"fileType\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n * \"placeholders\": [\n * {\n * \"key\": \"client_name\",\n * \"label\": \"Client Name\",\n * \"type\": \"text\",\n * \"required\": true\n * },\n * {\n * \"key\": \"contract_date\",\n * \"label\": \"Contract Date\",\n * \"type\": \"date\",\n * \"required\": true\n * }\n * ]\n * }\n * ```\n */\nexport const DocumentTemplateSchema = z.object({\n /**\n * Unique identifier for the template\n */\n id: z.string().describe('Template ID'),\n\n /**\n * Human-readable name of the template\n */\n name: z.string().describe('Template name'),\n\n /**\n * Optional description of the template's purpose\n */\n description: z.string().optional().describe('Template description'),\n\n /**\n * URL to the template file\n */\n fileUrl: z.string().url().describe('Template file URL'),\n\n /**\n * MIME type of the template file\n */\n fileType: z.string().describe('File MIME type'),\n\n /**\n * List of dynamic placeholders in the template\n */\n placeholders: z.array(z.object({\n /**\n * Placeholder identifier (used in template)\n */\n key: z.string().describe('Placeholder key'),\n\n /**\n * Human-readable label for the placeholder\n */\n label: z.string().describe('Placeholder label'),\n\n /**\n * Data type of the placeholder value\n */\n type: z.enum(['text', 'number', 'date', 'image']).describe('Placeholder type'),\n\n /**\n * Whether this placeholder must be filled\n * @default false\n */\n required: z.boolean().optional().default(false).describe('Is required'),\n })).describe('Template placeholders'),\n});\n\n/**\n * E-Signature Configuration Schema\n * \n * Configuration for electronic signature workflows.\n * Supports integration with popular e-signature providers.\n * \n * @example\n * ```json\n * {\n * \"provider\": \"docusign\",\n * \"enabled\": true,\n * \"signers\": [\n * {\n * \"email\": \"client@example.com\",\n * \"name\": \"John Doe\",\n * \"role\": \"Client\",\n * \"order\": 1\n * },\n * {\n * \"email\": \"manager@example.com\",\n * \"name\": \"Jane Smith\",\n * \"role\": \"Manager\",\n * \"order\": 2\n * }\n * ],\n * \"expirationDays\": 30,\n * \"reminderDays\": 7\n * }\n * ```\n */\nexport const ESignatureConfigSchema = z.object({\n /**\n * E-signature service provider\n */\n provider: z.enum(['docusign', 'adobe-sign', 'hellosign', 'custom']).describe('E-signature provider'),\n\n /**\n * Whether e-signature is enabled for this document\n * @default false\n */\n enabled: z.boolean().optional().default(false).describe('E-signature enabled'),\n\n /**\n * List of signers in signing order\n */\n signers: z.array(z.object({\n /**\n * Signer's email address\n */\n email: z.string().email().describe('Signer email'),\n\n /**\n * Signer's full name\n */\n name: z.string().describe('Signer name'),\n\n /**\n * Signer's role in the document\n */\n role: z.string().describe('Signer role'),\n\n /**\n * Signing order (lower numbers sign first)\n */\n order: z.number().describe('Signing order'),\n })).describe('Document signers'),\n\n /**\n * Days until signature request expires\n * @default 30\n */\n expirationDays: z.number().optional().default(30).describe('Expiration days'),\n\n /**\n * Days between reminder emails\n * @default 7\n */\n reminderDays: z.number().optional().default(7).describe('Reminder interval days'),\n});\n\n/**\n * Document Schema\n * \n * Comprehensive document management protocol supporting versioning,\n * templates, e-signatures, and access control.\n * \n * @example\n * ```json\n * {\n * \"id\": \"doc_123\",\n * \"name\": \"Service Agreement 2024\",\n * \"description\": \"Annual service agreement\",\n * \"fileType\": \"application/pdf\",\n * \"fileSize\": 1048576,\n * \"category\": \"contracts\",\n * \"tags\": [\"legal\", \"2024\", \"services\"],\n * \"versioning\": {\n * \"enabled\": true,\n * \"versions\": [\n * {\n * \"versionNumber\": 1,\n * \"createdAt\": 1704067200000,\n * \"createdBy\": \"user_123\",\n * \"size\": 1048576,\n * \"checksum\": \"abc123\",\n * \"downloadUrl\": \"https://example.com/docs/v1.pdf\",\n * \"isLatest\": true\n * }\n * ],\n * \"majorVersion\": 1,\n * \"minorVersion\": 0\n * },\n * \"access\": {\n * \"isPublic\": false,\n * \"sharedWith\": [\"user_456\", \"team_789\"],\n * \"expiresAt\": 1735689600000\n * },\n * \"metadata\": {\n * \"author\": \"John Doe\",\n * \"department\": \"Legal\"\n * }\n * }\n * ```\n */\nexport const DocumentSchema = z.object({\n /**\n * Unique document identifier\n */\n id: z.string().describe('Document ID'),\n\n /**\n * Document name\n */\n name: z.string().describe('Document name'),\n\n /**\n * Optional document description\n */\n description: z.string().optional().describe('Document description'),\n\n /**\n * MIME type of the document\n */\n fileType: z.string().describe('File MIME type'),\n\n /**\n * File size in bytes\n */\n fileSize: z.number().describe('File size in bytes'),\n\n /**\n * Document category for organization\n */\n category: z.string().optional().describe('Document category'),\n\n /**\n * Tags for searchability and organization\n */\n tags: z.array(z.string()).optional().describe('Document tags'),\n\n /**\n * Version control configuration\n */\n versioning: z.object({\n /**\n * Whether versioning is enabled\n */\n enabled: z.boolean().describe('Versioning enabled'),\n\n /**\n * List of all document versions\n */\n versions: z.array(DocumentVersionSchema).describe('Version history'),\n\n /**\n * Current major version number\n */\n majorVersion: z.number().describe('Major version'),\n\n /**\n * Current minor version number\n */\n minorVersion: z.number().describe('Minor version'),\n }).optional().describe('Version control'),\n\n /**\n * Template configuration (if document is generated from template)\n */\n template: DocumentTemplateSchema.optional().describe('Document template'),\n\n /**\n * E-signature configuration\n */\n eSignature: ESignatureConfigSchema.optional().describe('E-signature config'),\n\n /**\n * Access control settings\n */\n access: z.object({\n /**\n * Whether document is publicly accessible\n * @default false\n */\n isPublic: z.boolean().optional().default(false).describe('Public access'),\n\n /**\n * List of user/team IDs with access\n */\n sharedWith: z.array(z.string()).optional().describe('Shared with'),\n\n /**\n * Timestamp when access expires (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Access expiration'),\n }).optional().describe('Access control'),\n\n /**\n * Custom metadata fields\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\n// Type exports\nexport type Document = z.infer;\nexport type DocumentVersion = z.infer;\nexport type DocumentTemplate = z.infer;\nexport type ESignatureConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Base Field Mapping Protocol\n * \n * Shared by: ETL, Sync, Connector, External Lookup\n * \n * This module provides the canonical field mapping schema used across\n * ObjectStack for data transformation and synchronization.\n * \n * **Use Cases:**\n * - ETL pipelines (data/mapping.zod.ts)\n * - Data synchronization (automation/sync.zod.ts)\n * - Integration connectors (integration/connector.zod.ts)\n * - External lookups (data/external-lookup.zod.ts)\n * \n * @example Basic field mapping\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'external_user_id',\n * target: 'user_id',\n * };\n * ```\n * \n * @example With transformation\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'user_name',\n * target: 'name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: 'Unknown'\n * };\n * ```\n */\n\n/**\n * Transform Type Schema\n * \n * Defines the type of transformation to apply to a field value.\n * Implementations can extend this for domain-specific transforms.\n */\nexport const TransformTypeSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('constant'),\n value: z.unknown().describe('Constant value to use'),\n }).describe('Set a constant value'),\n \n z.object({\n type: z.literal('cast'),\n targetType: z.enum(['string', 'number', 'boolean', 'date']).describe('Target data type'),\n }).describe('Cast to a specific data type'),\n \n z.object({\n type: z.literal('lookup'),\n table: z.string().describe('Lookup table name'),\n keyField: z.string().describe('Field to match on'),\n valueField: z.string().describe('Field to retrieve'),\n }).describe('Lookup value from another table'),\n \n z.object({\n type: z.literal('javascript'),\n expression: z.string().describe('JavaScript expression (e.g., \"value.toUpperCase()\")'),\n }).describe('Custom JavaScript transformation'),\n \n z.object({\n type: z.literal('map'),\n mappings: z.record(z.string(), z.unknown()).describe('Value mappings (e.g., {\"Active\": \"active\"})'),\n }).describe('Map values using a dictionary'),\n]);\n\nexport type TransformType = z.infer;\n\n/**\n * Field Mapping Schema\n * \n * Base schema for mapping fields between source and target systems.\n * \n * **NAMING CONVENTION:**\n * - source: Field name in the source system\n * - target: Field name in the target system (should be snake_case for ObjectStack)\n * \n * @example\n * ```typescript\n * {\n * source: 'FirstName',\n * target: 'first_name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: ''\n * }\n * ```\n */\nexport const FieldMappingSchema = z.object({\n /**\n * Source field name\n */\n source: z.string().describe('Source field name'),\n \n /**\n * Target field name (should be snake_case for ObjectStack)\n */\n target: z.string().describe('Target field name'),\n \n /**\n * Transformation to apply\n */\n transform: TransformTypeSchema.optional().describe('Transformation to apply'),\n \n /**\n * Default value if source is null/undefined\n */\n defaultValue: z.unknown().optional().describe('Default if source is null/undefined'),\n});\n\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldMappingSchema as BaseFieldMappingSchema } from '../shared/mapping.zod';\n\n/**\n * External Data Source Schema\n * \n * Configuration for connecting to external data systems.\n * Similar to Salesforce External Objects for real-time data integration.\n * \n * @example\n * ```json\n * {\n * \"id\": \"salesforce-accounts\",\n * \"name\": \"Salesforce Account Data\",\n * \"type\": \"rest-api\",\n * \"endpoint\": \"https://api.salesforce.com/services/data/v58.0\",\n * \"authentication\": {\n * \"type\": \"oauth2\",\n * \"config\": {\n * \"clientId\": \"...\",\n * \"clientSecret\": \"...\",\n * \"tokenUrl\": \"https://login.salesforce.com/services/oauth2/token\"\n * }\n * }\n * }\n * ```\n */\nexport const ExternalDataSourceSchema = z.object({\n /**\n * Unique identifier for the external data source\n */\n id: z.string().describe('Data source ID'),\n\n /**\n * Human-readable name of the data source\n */\n name: z.string().describe('Data source name'),\n\n /**\n * Protocol type for connecting to the data source\n */\n type: z.enum(['odata', 'rest-api', 'graphql', 'custom']).describe('Protocol type'),\n\n /**\n * Base URL endpoint for the external system\n */\n endpoint: z.string().url().describe('API endpoint URL'),\n\n /**\n * Authentication configuration\n */\n authentication: z.object({\n /**\n * Authentication method\n */\n type: z.enum(['oauth2', 'api-key', 'basic', 'none']).describe('Auth type'),\n\n /**\n * Authentication-specific configuration\n * Structure varies based on auth type\n */\n config: z.record(z.string(), z.unknown()).describe('Auth configuration'),\n }).describe('Authentication'),\n});\n\n/**\n * Field Mapping Schema for External Lookups\n * \n * Extends the base field mapping with external lookup specific features.\n * Uses the canonical field mapping protocol from shared/mapping.zod.ts.\n * \n * @see {@link BaseFieldMappingSchema} for the base field mapping schema\n * \n * @example\n * ```json\n * {\n * \"source\": \"AccountName\",\n * \"target\": \"name\",\n * \"readonly\": true\n * }\n * ```\n */\nexport const ExternalFieldMappingSchema = BaseFieldMappingSchema.extend({\n /**\n * Field data type\n */\n type: z.string().optional().describe('Field type'),\n\n /**\n * Whether the field is read-only\n * @default true\n */\n readonly: z.boolean().optional().default(true).describe('Read-only field'),\n});\n\n/**\n * External Lookup Schema\n * \n * Real-time data lookup protocol for external systems.\n * Enables querying external data sources without replication.\n * Inspired by Salesforce External Objects and OData protocols.\n * \n * @example\n * ```json\n * {\n * \"fieldName\": \"external_account\",\n * \"dataSource\": {\n * \"id\": \"salesforce-api\",\n * \"name\": \"Salesforce\",\n * \"type\": \"rest-api\",\n * \"endpoint\": \"https://api.salesforce.com/services/data/v58.0\",\n * \"authentication\": {\n * \"type\": \"oauth2\",\n * \"config\": {\"clientId\": \"...\"}\n * }\n * },\n * \"query\": {\n * \"endpoint\": \"/sobjects/Account\",\n * \"method\": \"GET\",\n * \"parameters\": {\"limit\": 100}\n * },\n * \"fieldMappings\": [\n * {\n * \"externalField\": \"Name\",\n * \"localField\": \"account_name\",\n * \"type\": \"text\",\n * \"readonly\": true\n * }\n * ],\n * \"caching\": {\n * \"enabled\": true,\n * \"ttl\": 300,\n * \"strategy\": \"ttl\"\n * },\n * \"fallback\": {\n * \"enabled\": true,\n * \"showError\": true\n * },\n * \"rateLimit\": {\n * \"requestsPerSecond\": 10,\n * \"burstSize\": 20\n * }\n * }\n * ```\n */\nexport const ExternalLookupSchema = z.object({\n /**\n * Name of the field that uses external lookup\n */\n fieldName: z.string().describe('Field name'),\n\n /**\n * External data source configuration\n */\n dataSource: ExternalDataSourceSchema.describe('External data source'),\n\n /**\n * Query configuration for fetching external data\n */\n query: z.object({\n /**\n * API endpoint path (relative to base endpoint)\n */\n endpoint: z.string().describe('Query endpoint path'),\n\n /**\n * HTTP method for the query\n * @default 'GET'\n */\n method: z.enum(['GET', 'POST']).optional().default('GET').describe('HTTP method'),\n\n /**\n * Query parameters or request body\n */\n parameters: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n }).describe('Query configuration'),\n\n /**\n * Mapping between external and local fields\n */\n fieldMappings: z.array(ExternalFieldMappingSchema).describe('Field mappings'),\n\n /**\n * Cache configuration for external data\n */\n caching: z.object({\n /**\n * Whether caching is enabled\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Cache enabled'),\n\n /**\n * Time-to-live in seconds\n * @default 300\n */\n ttl: z.number().optional().default(300).describe('Cache TTL (seconds)'),\n\n /**\n * Cache eviction strategy\n * @default 'ttl'\n */\n strategy: z.enum(['lru', 'lfu', 'ttl']).optional().default('ttl').describe('Cache strategy'),\n }).optional().describe('Caching configuration'),\n\n /**\n * Fallback behavior when external system is unavailable\n */\n fallback: z.object({\n /**\n * Whether fallback is enabled\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Fallback enabled'),\n\n /**\n * Default value to use when external system fails\n */\n defaultValue: z.unknown().optional().describe('Default fallback value'),\n\n /**\n * Whether to show error message to user\n * @default true\n */\n showError: z.boolean().optional().default(true).describe('Show error to user'),\n }).optional().describe('Fallback configuration'),\n\n /**\n * Rate limiting to prevent overwhelming external system\n */\n rateLimit: z.object({\n /**\n * Maximum requests per second\n */\n requestsPerSecond: z.number().describe('Requests per second limit'),\n\n /**\n * Burst size for handling spikes\n */\n burstSize: z.number().optional().describe('Burst size'),\n }).optional().describe('Rate limiting'),\n\n /**\n * Retry configuration with exponential backoff\n *\n * @example\n * ```json\n * {\n * \"maxRetries\": 3,\n * \"initialDelayMs\": 1000,\n * \"maxDelayMs\": 30000,\n * \"backoffMultiplier\": 2,\n * \"retryableStatusCodes\": [429, 500, 502, 503, 504]\n * }\n * ```\n */\n retry: z.object({\n /** Maximum number of retry attempts */\n maxRetries: z.number().min(0).default(3).describe('Maximum retry attempts'),\n /** Initial delay before first retry (ms) */\n initialDelayMs: z.number().default(1000).describe('Initial retry delay in milliseconds'),\n /** Maximum delay between retries (ms) */\n maxDelayMs: z.number().default(30000).describe('Maximum retry delay in milliseconds'),\n /** Backoff multiplier for exponential backoff */\n backoffMultiplier: z.number().default(2).describe('Exponential backoff multiplier'),\n /** HTTP status codes that trigger a retry */\n retryableStatusCodes: z.array(z.number()).default([429, 500, 502, 503, 504])\n .describe('HTTP status codes that are retryable'),\n }).optional().describe('Retry configuration with exponential backoff'),\n\n /**\n * Request/response transformation pipeline\n *\n * Allows transforming request parameters and response data\n * before they are processed by the external lookup system.\n */\n transform: z.object({\n /** Transform request parameters before sending */\n request: z.object({\n /** Header transformations (key-value additions) */\n headers: z.record(z.string(), z.string()).optional().describe('Additional request headers'),\n /** Query parameter transformations */\n queryParams: z.record(z.string(), z.string()).optional().describe('Additional query parameters'),\n }).optional().describe('Request transformation'),\n /** Transform response data after receiving */\n response: z.object({\n /** JSONPath expression to extract data from response */\n dataPath: z.string().optional().describe('JSONPath to extract data (e.g., \"$.data.results\")'),\n /** JSONPath expression to extract total count for pagination */\n totalPath: z.string().optional().describe('JSONPath to extract total count (e.g., \"$.meta.total\")'),\n }).optional().describe('Response transformation'),\n }).optional().describe('Request/response transformation pipeline'),\n\n /** Pagination support for external data sources */\n pagination: z.object({\n /** Pagination type */\n type: z.enum(['offset', 'cursor', 'page']).default('offset').describe('Pagination type'),\n /** Page size */\n pageSize: z.number().default(100).describe('Items per page'),\n /** Maximum pages to fetch */\n maxPages: z.number().optional().describe('Maximum number of pages to fetch'),\n }).optional().describe('Pagination configuration for external data'),\n});\n\n// Type exports\nexport type ExternalLookup = z.infer;\nexport type ExternalDataSource = z.infer;\nexport type ExternalFieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n\n/**\n * Driver Identifier\n * Can be a built-in driver or a plugin-contributed driver (e.g., \"com.vendor.snowflake\").\n */\nexport const DriverType = z.string().describe('Underlying driver identifier');\n\n/**\n * Driver Definition Schema\n * Metadata describing a Database Driver.\n * Plugins use this to register new connectivity options.\n */\nexport const DriverDefinitionSchema = z.object({\n id: z.string().describe('Unique driver identifier (e.g. \"postgres\")'),\n label: z.string().describe('Display label (e.g. \"PostgreSQL\")'),\n description: z.string().optional(),\n icon: z.string().optional(),\n \n /**\n * Configuration Schema (JSON Schema)\n * Describes the structure of the `config` object needed for this driver.\n * Used by the UI to generate the connection form.\n */\n configSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for connection configuration'),\n \n /**\n * Default Capabilities\n * What this driver supports out-of-the-box.\n */\n capabilities: z.lazy(() => DatasourceCapabilities).optional(),\n});\n\n/**\n * Datasource Capabilities Schema\n * Declares what this datasource naturally supports.\n * The ObjectQL engine uses this to determine what logic to push down\n * and what to compute in memory.\n */\nexport const DatasourceCapabilities = z.object({\n // ============================================================================\n // Transaction & Connection Management\n // ============================================================================\n \n /** Can handle ACID transactions? */\n transactions: z.boolean().default(false),\n \n // ============================================================================\n // Query Operations\n // ============================================================================\n \n /** Can execute WHERE clause filters natively? */\n queryFilters: z.boolean().default(false),\n \n /** Can perform aggregation (group by, sum, avg)? */\n queryAggregations: z.boolean().default(false),\n \n /** Can perform ORDER BY sorting? */\n querySorting: z.boolean().default(false),\n \n /** Can perform LIMIT/OFFSET pagination? */\n queryPagination: z.boolean().default(false),\n \n /** Can perform window functions? */\n queryWindowFunctions: z.boolean().default(false),\n \n /** Can perform subqueries? */\n querySubqueries: z.boolean().default(false),\n \n /** Can execute SQL-like joins natively? */\n joins: z.boolean().default(false),\n \n // ============================================================================\n // Advanced Features\n // ============================================================================\n \n /** Can perform full-text search? */\n fullTextSearch: z.boolean().default(false),\n \n /** Is read-only? */\n readOnly: z.boolean().default(false),\n \n /** Is scheme-less (needs schema inference)? */\n dynamicSchema: z.boolean().default(false),\n});\n\n/**\n * Datasource Schema\n * Represents a connection to an external data store.\n */\nexport const DatasourceSchema = z.object({\n /** Machine Name */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique datasource identifier'),\n \n /** Human Label */\n label: z.string().optional().describe('Display label'),\n \n /** Driver */\n driver: DriverType.describe('Underlying driver type'),\n \n /** \n * Connection Configuration \n * Specific to the driver (e.g., host, port, user, password, bucket, etc.)\n * Stored securely (passwords usually interpolated from ENV).\n */\n config: z.record(z.string(), z.unknown()).describe('Driver specific configuration'),\n \n /**\n * Connection Pool Configuration\n * Standard connection pooling settings.\n */\n pool: z.object({\n min: z.number().default(0).describe('Minimum connections'),\n max: z.number().default(10).describe('Maximum connections'),\n idleTimeoutMillis: z.number().default(30000).describe('Idle timeout'),\n connectionTimeoutMillis: z.number().default(3000).describe('Connection establishment timeout'),\n }).optional().describe('Connection pool settings'),\n\n /**\n * Read Replicas\n * Optional list of duplicate configurations for read-only operations.\n * Useful for scaling read throughput.\n */\n readReplicas: z.array(z.record(z.string(), z.unknown())).optional().describe('Read-only replica configurations'),\n\n /**\n * Capability Overrides\n * Manually override what the driver claims to support.\n */\n capabilities: DatasourceCapabilities.optional().describe('Capability overrides'),\n \n /** Health Check */\n healthCheck: z.object({\n enabled: z.boolean().default(true).describe('Enable health check endpoint'),\n intervalMs: z.number().default(30000).describe('Health check interval in milliseconds'),\n timeoutMs: z.number().default(5000).describe('Health check timeout in milliseconds'),\n }).optional().describe('Datasource health check configuration'),\n\n /** SSL/TLS Configuration */\n ssl: z.object({\n enabled: z.boolean().default(false).describe('Enable SSL/TLS for database connection'),\n rejectUnauthorized: z.boolean().default(true).describe('Reject connections with invalid/self-signed certificates'),\n ca: z.string().optional().describe('CA certificate (PEM format or path to file)'),\n cert: z.string().optional().describe('Client certificate (PEM format or path to file)'),\n key: z.string().optional().describe('Client private key (PEM format or path to file)'),\n }).optional().describe('SSL/TLS configuration for secure database connections'),\n\n /** Retry Policy */\n retryPolicy: z.object({\n maxRetries: z.number().default(3).describe('Maximum number of retry attempts'),\n baseDelayMs: z.number().default(1000).describe('Base delay between retries in milliseconds'),\n maxDelayMs: z.number().default(30000).describe('Maximum delay between retries in milliseconds'),\n backoffMultiplier: z.number().default(2).describe('Exponential backoff multiplier'),\n }).optional().describe('Connection retry policy for transient failures'),\n\n /** Description */\n description: z.string().optional().describe('Internal description'),\n \n /** Is enabled? */\n active: z.boolean().default(true).describe('Is datasource enabled'),\n});\n\nexport type Datasource = z.infer;\nexport type DatasourceCapabilitiesType = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Analytics/Semantic Layer Protocol\n * \n * Defines the \"Business Logic\" for data analysis.\n * Inspired by Cube.dev, LookML, and dbt MetricFlow.\n * \n * This layer decouples the \"Physical Data\" (Tables/Columns) from the \n * \"Business Data\" (Metrics/Dimensions).\n */\n\n/**\n * Aggregation Metric Type\n * The mathematical operation to perform on a metric.\n */\nexport const AggregationMetricType = z.enum([\n 'count', \n 'sum', \n 'avg', \n 'min', \n 'max', \n 'count_distinct', \n 'number', // Custom SQL expression returning a number\n 'string', // Custom SQL expression returning a string\n 'boolean' // Custom SQL expression returning a boolean\n]);\n\n/**\n * Dimension Type\n * The nature of the grouping field.\n */\nexport const DimensionType = z.enum([\n 'string', \n 'number', \n 'boolean', \n 'time', \n 'geo'\n]);\n\n/**\n * Time Interval for Time Dimensions\n */\nexport const TimeUpdateInterval = z.enum([\n 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'\n]);\n\n/**\n * Metric Schema\n * A quantitative measurement (e.g., \"Total Revenue\", \"Average Order Value\").\n */\nexport const MetricSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique metric ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: AggregationMetricType,\n \n /** Source Calculation */\n sql: z.string().describe('SQL expression or field reference'),\n \n /** Filtering for this specific metric (e.g. \"Revenue from Premium Users\") */\n filters: z.array(z.object({\n sql: z.string()\n })).optional(),\n \n /** Format for display (e.g. \"currency\", \"percent\") */\n format: z.string().optional(),\n});\n\n/**\n * Dimension Schema\n * A categorical attribute to group by (e.g., \"Product Category\", \"Order Date\").\n */\nexport const DimensionSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique dimension ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: DimensionType,\n \n /** Source Column */\n sql: z.string().describe('SQL expression or column reference'),\n \n /** For Time Dimensions: Supported Granularities */\n granularities: z.array(TimeUpdateInterval).optional(),\n});\n\n/**\n * Join Schema\n * Defines how this cube relates to others.\n */\nexport const CubeJoinSchema = z.object({\n name: z.string().describe('Target cube name'),\n relationship: z.enum(['one_to_one', 'one_to_many', 'many_to_one']).default('many_to_one'),\n sql: z.string().describe('Join condition (ON clause)'),\n});\n\n/**\n * Cube Schema\n * A logical data model representing a business entity or process for analysis.\n * Maps physical tables to business metrics and dimensions.\n */\nexport const CubeSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Cube name (snake_case)'),\n title: z.string().optional(),\n description: z.string().optional(),\n \n /** Physical Data Source */\n sql: z.string().describe('Base SQL statement or Table Name'),\n \n /** Semantic Definitions */\n measures: z.record(z.string(), MetricSchema).describe('Quantitative metrics'),\n dimensions: z.record(z.string(), DimensionSchema).describe('Qualitative attributes'),\n \n /** Relationships */\n joins: z.record(z.string(), CubeJoinSchema).optional(),\n \n /** Pre-aggregations / Caching */\n refreshKey: z.object({\n every: z.string().optional(), // e.g. \"1 hour\"\n sql: z.string().optional(), // SQL to check for data changes\n }).optional(),\n \n /** Access Control */\n public: z.boolean().default(false),\n});\n\n/**\n * Analytics Query Schema\n * The request format for the Analytics API.\n */\nexport const AnalyticsQuerySchema = z.object({\n cube: z.string().optional().describe('Target cube name (optional when provided externally, e.g. in API request wrapper)'),\n measures: z.array(z.string()).describe('List of metrics to calculate'),\n dimensions: z.array(z.string()).optional().describe('List of dimensions to group by'),\n \n filters: z.array(z.object({\n member: z.string().describe('Dimension or Measure'),\n operator: z.enum(['equals', 'notEquals', 'contains', 'notContains', 'gt', 'gte', 'lt', 'lte', 'set', 'notSet', 'inDateRange']),\n values: z.array(z.string()).optional(),\n })).optional(),\n \n timeDimensions: z.array(z.object({\n dimension: z.string(),\n granularity: TimeUpdateInterval.optional(),\n dateRange: z.union([\n z.string(), // \"Last 7 days\"\n z.array(z.string()) // [\"2023-01-01\", \"2023-01-31\"]\n ]).optional(),\n })).optional(),\n \n order: z.record(z.string(), z.enum(['asc', 'desc'])).optional(),\n \n limit: z.number().optional(),\n offset: z.number().optional(),\n \n timezone: z.string().optional().default('UTC'),\n});\n\nexport type Metric = z.infer;\nexport type Dimension = z.infer;\nexport type CubeJoin = z.infer;\nexport type Cube = z.infer;\nexport type AnalyticsQuery = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Feed Item Type\n * Unified activity types for the record timeline.\n * Covers comments, field changes, tasks, events, and system activities.\n */\nexport const FeedItemType = z.enum([\n 'comment',\n 'field_change',\n 'task',\n 'event',\n 'email',\n 'call',\n 'note',\n 'file',\n 'record_create',\n 'record_delete',\n 'approval',\n 'sharing',\n 'system',\n]);\nexport type FeedItemType = z.infer;\n\n/**\n * Mention Schema\n * Represents an @mention within comment body text.\n */\nexport const MentionSchema = z.object({\n type: z.enum(['user', 'team', 'record']).describe('Mention target type'),\n id: z.string().describe('Target ID'),\n name: z.string().describe('Display name for rendering'),\n offset: z.number().int().min(0).describe('Character offset in body text'),\n length: z.number().int().min(1).describe('Length of mention token in body text'),\n});\nexport type Mention = z.infer;\n\n/**\n * Field Change Entry Schema\n * Represents a single field-level change within a field_change feed item.\n */\nexport const FieldChangeEntrySchema = z.object({\n field: z.string().describe('Field machine name'),\n fieldLabel: z.string().optional().describe('Field display label'),\n oldValue: z.unknown().optional().describe('Previous value'),\n newValue: z.unknown().optional().describe('New value'),\n oldDisplayValue: z.string().optional().describe('Human-readable old value'),\n newDisplayValue: z.string().optional().describe('Human-readable new value'),\n});\nexport type FieldChangeEntry = z.infer;\n\n/**\n * Reaction Schema\n * Represents an emoji reaction on a feed item.\n */\nexport const ReactionSchema = z.object({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n userIds: z.array(z.string()).describe('Users who reacted'),\n count: z.number().int().min(1).describe('Total reaction count'),\n});\nexport type Reaction = z.infer;\n\n/**\n * Feed Actor Schema\n * Represents the actor who performed the action.\n */\nexport const FeedActorSchema = z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n avatarUrl: z.string().url().optional().describe('Actor avatar URL'),\n source: z.string().optional().describe('Source application (e.g., \"Omni\", \"API\", \"Studio\")'),\n});\nexport type FeedActor = z.infer;\n\n/**\n * Feed Item Visibility\n */\nexport const FeedVisibility = z.enum(['public', 'internal', 'private']);\nexport type FeedVisibility = z.infer;\n\n/**\n * Feed Item Schema\n * A single entry in the unified activity timeline.\n *\n * @example Comment\n * {\n * id: 'feed_001',\n * type: 'comment',\n * object: 'account',\n * recordId: 'rec_123',\n * body: 'Great progress! @jane.doe can you follow up?',\n * mentions: [{ type: 'user', id: 'user_123', name: 'Jane Doe', offset: 17, length: 9 }],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:30:00Z',\n * }\n *\n * @example Field Change\n * {\n * id: 'feed_002',\n * type: 'field_change',\n * object: 'account',\n * recordId: 'rec_123',\n * changes: [\n * { field: 'status', oldDisplayValue: 'New', newDisplayValue: 'Active' },\n * { field: 'region', oldDisplayValue: '', newDisplayValue: 'Asia-Pacific' },\n * ],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:25:00Z',\n * }\n */\nexport const FeedItemSchema = z.object({\n /** Unique identifier */\n id: z.string().describe('Feed item ID'),\n\n /** Feed item type */\n type: FeedItemType.describe('Activity type'),\n\n /** Target record reference */\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID this feed item belongs to'),\n\n /** Actor (who performed the action) */\n actor: FeedActorSchema.describe('Who performed this action'),\n\n /** Content (for comments/notes) */\n body: z.string().optional().describe('Rich text body (Markdown supported)'),\n\n /** @Mentions */\n mentions: z.array(MentionSchema).optional().describe('Mentioned users/teams/records'),\n\n /** Field changes (for field_change type) */\n changes: z.array(FieldChangeEntrySchema).optional().describe('Field-level changes'),\n\n /** Reactions */\n reactions: z.array(ReactionSchema).optional().describe('Emoji reactions on this item'),\n\n /** Reply threading */\n parentId: z.string().optional().describe('Parent feed item ID for threaded replies'),\n replyCount: z.number().int().min(0).default(0).describe('Number of replies'),\n\n /** Pin / Star */\n pinned: z.boolean().default(false).describe('Whether the feed item is pinned to the top of the timeline'),\n pinnedAt: z.string().datetime().optional().describe('Timestamp when the item was pinned'),\n pinnedBy: z.string().optional().describe('User ID who pinned the item'),\n starred: z.boolean().default(false).describe('Whether the feed item is starred/bookmarked by the current user'),\n starredAt: z.string().datetime().optional().describe('Timestamp when the item was starred'),\n\n /** Visibility */\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public (all users), internal (team only), private (author + mentioned)'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n editedAt: z.string().datetime().optional().describe('When comment was last edited'),\n isEdited: z.boolean().default(false).describe('Whether comment has been edited'),\n});\nexport type FeedItem = z.infer;\n\n/**\n * Feed Filter Mode\n * Controls which feed item types to display in the timeline.\n */\nexport const FeedFilterMode = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\nexport type FeedFilterMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Subscription Event Type\n * Event types that can be subscribed to for record-level notifications.\n */\nexport const SubscriptionEventType = z.enum([\n 'comment',\n 'mention',\n 'field_change',\n 'task',\n 'approval',\n 'all',\n]);\nexport type SubscriptionEventType = z.infer;\n\n/**\n * Notification Channel\n * Delivery channels for record subscription notifications.\n */\nexport const NotificationChannel = z.enum([\n 'in_app',\n 'email',\n 'push',\n 'slack',\n]);\nexport type NotificationChannel = z.infer;\n\n/**\n * Record Subscription Schema\n * Defines a user's subscription to record-level notifications.\n * Enables Airtable-style bell icon for record change notifications.\n */\nexport const RecordSubscriptionSchema = z.object({\n /** Target */\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n\n /** Subscriber */\n userId: z.string().describe('Subscribing user ID'),\n\n /** Events to subscribe to */\n events: z.array(SubscriptionEventType)\n .default(['all'])\n .describe('Event types to receive notifications for'),\n\n /** Notification channels */\n channels: z.array(NotificationChannel)\n .default(['in_app'])\n .describe('Notification delivery channels'),\n\n /** Active */\n active: z.boolean().default(true).describe('Whether the subscription is active'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Subscription creation timestamp'),\n});\nexport type RecordSubscription = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Turso Multi-Tenant Router Schema\n *\n * Defines the configuration for Turso DB-per-Tenant architectures where each\n * tenant receives an independent Turso/libSQL database. The router resolves\n * the correct database URL and auth token per request based on the current\n * tenant context.\n *\n * Architecture: Shared Compute + Isolated Data\n * - Serverless functions are shared across tenants\n * - Each tenant has a physically isolated Turso database\n * - Turso Platform API manages database lifecycle (create/delete/suspend)\n *\n * @see https://docs.turso.tech/features/multi-db-schemas\n */\n\n// ==========================================================================\n// 1. Tenant Resolver Strategy\n// ==========================================================================\n\n/**\n * Strategy for resolving which tenant database to connect to.\n */\nexport const TenantResolverStrategySchema = z.enum([\n 'header', // Resolve from X-Tenant-ID request header\n 'subdomain', // Resolve from subdomain (e.g., acme.app.com → acme)\n 'path', // Resolve from URL path segment (e.g., /api/acme/...)\n 'token', // Resolve from JWT claim (e.g., tenant_id in access token)\n 'lookup', // Resolve from control-plane database lookup\n]).describe('Strategy for resolving tenant identity from request context');\n\nexport type TenantResolverStrategy = z.infer;\n\n// ==========================================================================\n// 2. Turso Group Configuration\n// ==========================================================================\n\n/**\n * Turso Database Group Configuration.\n * Groups allow databases to share schema and be managed as a unit.\n * All databases in a group are deployed to the same set of locations.\n *\n * @see https://docs.turso.tech/features/multi-db-schemas\n */\nexport const TursoGroupSchema = z.object({\n /**\n * Group name identifier.\n * Used to reference the group when creating new tenant databases.\n */\n name: z.string().min(1).describe('Turso database group name'),\n\n /**\n * Primary location for the group (Turso region code).\n * Example: 'iad' (US East), 'lhr' (London), 'nrt' (Tokyo)\n */\n primaryLocation: z.string().min(2).describe('Primary Turso region code (e.g., iad, lhr, nrt)'),\n\n /**\n * Additional replica locations for read performance.\n * Databases in this group will have read replicas in these regions.\n */\n replicaLocations: z.array(z.string().min(2)).default([]).describe('Additional replica region codes'),\n\n /**\n * Schema database name within the group.\n * When using multi-db schemas, this is the \"parent\" database\n * whose schema is shared by all child (tenant) databases.\n */\n schemaDatabase: z.string().optional().describe('Schema database name for multi-db schemas'),\n}).describe('Turso database group configuration');\n\nexport type TursoGroup = z.infer;\n\n// ==========================================================================\n// 3. Tenant Database Lifecycle Hooks\n// ==========================================================================\n\n/**\n * Database Lifecycle Hook Schema.\n * Defines what happens at each tenant lifecycle event.\n */\nexport const TenantDatabaseLifecycleSchema = z.object({\n /**\n * Hook executed when a new tenant is created.\n * Defines how the tenant database is provisioned.\n */\n onTenantCreate: z.object({\n /** Whether to automatically create a Turso database */\n autoCreate: z.boolean().default(true).describe('Auto-create database on tenant registration'),\n\n /** Database group to create the database in */\n group: z.string().optional().describe('Turso group for the new database'),\n\n /** Whether to apply schema from the group schema database */\n applyGroupSchema: z.boolean().default(true).describe('Apply shared schema from group'),\n\n /** Seed data to populate on creation */\n seedData: z.boolean().default(false).describe('Populate seed data on creation'),\n }).describe('Tenant creation hook'),\n\n /**\n * Hook executed when a tenant is deleted/destroyed.\n */\n onTenantDelete: z.object({\n /** Whether to destroy the database immediately or schedule for deletion */\n immediate: z.boolean().default(false).describe('Destroy database immediately'),\n\n /** Grace period in hours before permanent deletion (soft-delete) */\n gracePeriodHours: z.number().int().min(0).default(72).describe('Grace period before permanent deletion'),\n\n /** Whether to create a final backup before deletion */\n createBackup: z.boolean().default(true).describe('Create backup before deletion'),\n }).describe('Tenant deletion hook'),\n\n /**\n * Hook executed when a tenant is suspended (e.g., unpaid, policy violation).\n */\n onTenantSuspend: z.object({\n /** Whether to revoke auth tokens on suspension */\n revokeTokens: z.boolean().default(true).describe('Revoke auth tokens on suspension'),\n\n /** Whether to set database to read-only mode */\n readOnly: z.boolean().default(true).describe('Set database to read-only on suspension'),\n }).describe('Tenant suspension hook'),\n}).describe('Tenant database lifecycle hooks');\n\nexport type TenantDatabaseLifecycle = z.infer;\n\n// ==========================================================================\n// 4. Multi-Tenant Router Configuration\n// ==========================================================================\n\n/**\n * Turso Multi-Tenant Configuration Schema.\n *\n * Configures the DB-per-Tenant router that resolves the correct Turso\n * database for each request. Works with the Turso Platform API to manage\n * database lifecycle.\n *\n * @example\n * ```ts\n * const config = TursoMultiTenantConfigSchema.parse({\n * organizationSlug: 'myorg',\n * urlTemplate: 'libsql://{tenant_id}-myorg.turso.io',\n * groupAuthToken: process.env.TURSO_GROUP_AUTH_TOKEN,\n * tenantResolverStrategy: 'token',\n * group: {\n * name: 'production',\n * primaryLocation: 'iad',\n * replicaLocations: ['lhr', 'nrt'],\n * schemaDatabase: 'schema-db',\n * },\n * lifecycle: {\n * onTenantCreate: { autoCreate: true, applyGroupSchema: true },\n * onTenantDelete: { gracePeriodHours: 168 },\n * onTenantSuspend: { revokeTokens: true },\n * },\n * });\n * ```\n */\nexport const TursoMultiTenantConfigSchema = z.object({\n /**\n * Turso organization slug.\n * Used for Platform API calls and URL construction.\n */\n organizationSlug: z.string().min(1).describe('Turso organization slug'),\n\n /**\n * URL template for constructing tenant database URLs.\n * Use `{tenant_id}` as placeholder for the tenant identifier.\n *\n * Example: 'libsql://{tenant_id}-myorg.turso.io'\n */\n urlTemplate: z.string().min(1).describe('URL template with {tenant_id} placeholder'),\n\n /**\n * Group-level auth token for Turso Platform API operations.\n * Used for database creation, deletion, and management.\n * This token has full access to all databases in the group.\n */\n groupAuthToken: z.string().min(1).describe('Group-level auth token for platform operations'),\n\n /**\n * Strategy for resolving tenant identity from the request context.\n */\n tenantResolverStrategy: TenantResolverStrategySchema.default('token'),\n\n /**\n * Turso database group configuration.\n */\n group: TursoGroupSchema.optional().describe('Database group configuration'),\n\n /**\n * Lifecycle hooks for tenant database management.\n */\n lifecycle: TenantDatabaseLifecycleSchema.optional().describe('Lifecycle hooks'),\n\n /**\n * Maximum number of cached tenant database connections.\n * Connections are evicted using LRU strategy when the limit is reached.\n */\n maxCachedConnections: z.number().int().min(1).default(100).describe('Max cached tenant connections (LRU)'),\n\n /**\n * Connection cache TTL in seconds.\n * Cached connections are refreshed after this period.\n */\n connectionCacheTTL: z.number().int().min(0).default(300).describe('Connection cache TTL in seconds'),\n}).describe('Turso multi-tenant router configuration');\n\nexport type TursoMultiTenantConfig = z.infer;\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar hash_exports = {};\n__export(hash_exports, {\n hashCode: () => hashCode\n});\nmodule.exports = __toCommonJS(hash_exports);\nconst MULTIPLIER = 16777619;\nfunction mix(h, x) {\n return h * MULTIPLIER ^ x >>> 0;\n}\nfunction hashNumber(n) {\n if (Number.isNaN(n)) return 2143289344;\n if (!Number.isFinite(n)) return n > 0 ? 2139095040 : 4286578688;\n const intPart = Math.trunc(n);\n const frac = n - intPart;\n let h = intPart | 0;\n if (frac !== 0) {\n const scaled = Math.floor(frac * 4294967296);\n h = mix(h, scaled | 0);\n }\n return h >>> 0;\n}\nfunction hashString(str) {\n let h = 0;\n for (let i = 0; i < str.length; i++) {\n h = mix(h, str.charCodeAt(i));\n }\n return h >>> 0;\n}\nfunction hashBigInt(b) {\n let h = 0;\n const isNegative = b < 0n;\n let x = isNegative ? -b : b;\n if (x === 0n) {\n h = mix(h, 0);\n } else {\n while (x > 0n) {\n const byte = Number(x & 0xffn);\n h = mix(h, byte);\n x >>= 8n;\n }\n }\n return mix(h, +isNegative) >>> 0;\n}\nfunction hashFunction(fn) {\n let h = hashString((fn.name || \"\") + fn.toString());\n h = mix(h, fn.length);\n return h >>> 0;\n}\nfunction hashBytes(bytes) {\n let h = 0;\n for (let i = 0; i < bytes.length; i++) {\n h = mix(h, bytes[i]);\n }\n return h >>> 0;\n}\nfunction hashTypedArray(view) {\n let h = hashString(view.constructor.name);\n const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n h = mix(h, hashBytes(bytes));\n return h >>> 0;\n}\nfunction hashArray(arr, seen) {\n if (seen.has(arr)) return 13 /* Cycle */;\n seen.add(arr);\n let h = 1;\n for (let i = 0; i < arr.length; i++) {\n h = mix(h, internalHash(arr[i], seen));\n }\n seen.delete(arr);\n return h >>> 0;\n}\nfunction hashObject(obj, seen) {\n if (seen.has(obj)) return 13 /* Cycle */;\n seen.add(obj);\n const keys = Object.keys(obj).sort();\n let h = hashString(obj?.constructor?.name);\n for (const k of keys) {\n h = mix(h, hashString(k));\n h = mix(h, internalHash(obj[k], seen));\n }\n seen.delete(obj);\n return h >>> 0;\n}\nconst BOOLEAN_HASH = [3735928559, 305441741].map((b) => mix(3 /* Boolean */, b));\nconst NULL_HASH = mix(1 /* Null */, 0);\nconst UNDEF_HASH = mix(2 /* Undefined */, 0);\nfunction internalHash(value, seen) {\n if (value === null) return NULL_HASH;\n const t = typeof value;\n switch (t) {\n case \"undefined\":\n return UNDEF_HASH;\n case \"boolean\":\n return BOOLEAN_HASH[+value];\n case \"number\":\n return mix(4 /* Number */, hashNumber(value));\n case \"string\":\n return mix(5 /* String */, hashString(value));\n case \"bigint\":\n return mix(6 /* BigInt */, hashBigInt(value));\n case \"function\":\n return mix(7 /* Function */, hashFunction(value));\n default: {\n if (ArrayBuffer.isView(value) && !(value instanceof DataView))\n return mix(12 /* TypedArray */, hashTypedArray(value));\n if (value instanceof Date)\n return mix(10 /* Date */, hashNumber(value.getTime()));\n if (value instanceof RegExp) {\n const h = hashString(value.source);\n return mix(11 /* RegExp */, mix(h, hashString(value.flags)));\n }\n if (Array.isArray(value)) return mix(8 /* Array */, hashArray(value, seen));\n return mix(\n 9 /* Object */,\n hashObject(value, seen)\n );\n }\n }\n}\nfunction hashCode(value) {\n return internalHash(value, /* @__PURE__ */ new WeakSet()) >>> 0;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n hashCode\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n HashMap: () => HashMap,\n MISSING: () => MISSING,\n MingoError: () => MingoError,\n PathValidator: () => PathValidator,\n assert: () => assert,\n cloneDeep: () => cloneDeep,\n compare: () => compare,\n ensureArray: () => ensureArray,\n filterMissing: () => filterMissing,\n findInsertIndex: () => findInsertIndex,\n flatten: () => flatten,\n groupBy: () => groupBy,\n has: () => has,\n hashCode: () => import_hash2.hashCode,\n intersection: () => intersection,\n isArray: () => isArray,\n isBoolean: () => isBoolean,\n isDate: () => isDate,\n isEmpty: () => isEmpty,\n isEqual: () => isEqual,\n isFunction: () => isFunction,\n isInteger: () => isInteger,\n isNil: () => isNil,\n isNumber: () => isNumber,\n isObject: () => isObject,\n isObjectLike: () => isObjectLike,\n isOperator: () => isOperator,\n isPrimitive: () => isPrimitive,\n isRegExp: () => isRegExp,\n isString: () => isString,\n isSymbol: () => isSymbol,\n normalize: () => normalize,\n removeValue: () => removeValue,\n resolve: () => resolve,\n resolveGraph: () => resolveGraph,\n setValue: () => setValue,\n simpleCmp: () => simpleCmp,\n truthy: () => truthy,\n typeOf: () => typeOf,\n unique: () => unique,\n walk: () => walk\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_hash = require(\"./_hash\");\nvar import_hash2 = require(\"./_hash\");\nclass MingoError extends Error {\n}\nconst MISSING = /* @__PURE__ */ Symbol(\"missing\");\nconst ERR_CYCLE_FOUND = \"mingo: cycle detected while processing object/array\";\nconst isPrimitive = (v) => typeof v !== \"object\" && typeof v !== \"function\" || v === null;\nconst isScalar = (v) => isPrimitive(v) || isDate(v) || isRegExp(v);\nconst SORT_ORDER = {\n undefined: 1,\n null: 2,\n number: 3,\n string: 4,\n symbol: 5,\n object: 6,\n array: 7,\n arraybuffer: 8,\n boolean: 9,\n date: 10,\n regexp: 11,\n function: 12\n};\nconst simpleCmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;\nconst typedArraysCmp = (a, b) => {\n const bytesA = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n const bytesB = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n const size = Math.min(bytesA.length, bytesB.length);\n for (let i = 0; i < size; i++) {\n const order = simpleCmp(bytesA[i], bytesB[i]);\n if (order !== 0) return order;\n }\n return simpleCmp(bytesA.length, bytesB.length);\n};\nfunction mingoCmp(a, b, descendArray = false) {\n if (a === MISSING) a = void 0;\n if (b === MISSING) b = void 0;\n if (a === b || Object.is(a, b)) return 0;\n const typeA = typeOf(a);\n const typeB = typeOf(b);\n let neq = 0;\n if (typeA === typeB) {\n switch (typeA) {\n case \"number\":\n case \"string\":\n case \"boolean\":\n return simpleCmp(a, b);\n case \"date\":\n return simpleCmp(+a, +b);\n case \"regexp\":\n if (neq = simpleCmp(a.source, b.source))\n return neq;\n return simpleCmp(a.flags, b.flags);\n case \"arraybuffer\":\n return typedArraysCmp(a, b);\n case \"array\": {\n const xs = a.slice().sort(mingoCmp);\n const ys = b.slice().sort(mingoCmp);\n const size = Math.min(xs.length, ys.length);\n for (let i = 0; i < size; i++)\n if (neq = mingoCmp(xs[i], ys[i])) return neq;\n return simpleCmp(xs.length, ys.length);\n }\n default: {\n if (typeA !== \"object\") {\n const isSameType = a?.constructor === b?.constructor;\n if (isSameType && hasCustomString(a))\n return simpleCmp(a.toString(), b.toString());\n if (neq = simpleCmp(a?.constructor?.name, b?.constructor?.name))\n return neq;\n }\n const keysA = Object.keys(a).sort();\n const keysB = Object.keys(b).sort();\n if (neq = mingoCmp(keysA, keysB)) return neq;\n for (const k of keysA)\n if (neq = mingoCmp(a[k], b[k]))\n return neq;\n return 0;\n }\n }\n }\n if (typeA == \"undefined\") return -1;\n if (typeB == \"undefined\") return 1;\n if (descendArray) {\n if (typeA == \"array\") {\n const xs = a;\n if (!xs.length) return -1;\n const sorted = xs.slice().sort(mingoCmp);\n neq = 1;\n for (const v of sorted)\n if ((neq = Math.min(neq, mingoCmp(v, b))) < 0) return neq;\n return neq;\n }\n if (typeB == \"array\") {\n const ys = b;\n if (!ys.length) return 1;\n const sorted = ys.slice().sort(mingoCmp);\n neq = -1;\n for (const v of sorted)\n if ((neq = Math.max(neq, mingoCmp(a, v))) > 0) return neq;\n return neq;\n }\n }\n const orderA = SORT_ORDER[typeA] ?? Number.MAX_VALUE;\n const orderB = SORT_ORDER[typeB] ?? Number.MAX_VALUE;\n return orderA !== orderB ? simpleCmp(orderA, orderB) : simpleCmp(typeA, typeB);\n}\nconst compare = (a, b) => mingoCmp(a, b, true);\nconst hasCustomString = (o) => o !== null && o !== void 0 && o[\"toString\"] !== Object.prototype.toString;\nfunction isEqual(a, b) {\n if (a === b || Object.is(a, b)) return true;\n if (a === null || b === null) return false;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return false;\n if (a.constructor !== b?.constructor) return false;\n if (isDate(a)) return isDate(b) && +a === +b;\n if (isRegExp(a))\n return isRegExp(b) && a.source === b.source && a.flags === b.flags;\n if (isArray(a) && isArray(b)) {\n return a.length === b.length && a.every((v, i) => isEqual(v, b[i]));\n }\n if (a?.constructor !== Object && hasCustomString(a)) {\n return a?.toString() === b?.toString();\n }\n const objA = a;\n const objB = b;\n const keysA = Object.keys(objA);\n const keysB = Object.keys(objB);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => has(objB, k) && isEqual(objA[k], objB[k]));\n}\nclass HashMap extends Map {\n // maps the hashcode to key set\n #keyMap = /* @__PURE__ */ new Map();\n // returns a tuple of [, ]. Expects an object key.\n #unpack = (key) => {\n const hash = (0, import_hash.hashCode)(key);\n const items = this.#keyMap.get(hash) ?? [];\n return [items.find((k) => isEqual(k, key)), hash];\n };\n constructor() {\n super();\n }\n /**\n * Returns a new {@link HashMap} object.\n * @param fn An optional custom hash function\n */\n static init() {\n return new HashMap();\n }\n clear() {\n super.clear();\n this.#keyMap.clear();\n }\n /**\n * @returns true if an element in the Map existed and has been removed, or false if the element does not exist.\n */\n delete(key) {\n if (isPrimitive(key)) return super.delete(key);\n const [masterKey, hash] = this.#unpack(key);\n if (!super.delete(masterKey)) return false;\n this.#keyMap.set(\n hash,\n this.#keyMap.get(hash).filter((k) => !isEqual(k, masterKey))\n );\n return true;\n }\n /**\n * Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.\n * @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.\n */\n get(key) {\n if (isPrimitive(key)) return super.get(key);\n const [masterKey, _] = this.#unpack(key);\n return super.get(masterKey);\n }\n /**\n * @returns boolean indicating whether an element with the specified key exists or not.\n */\n has(key) {\n if (isPrimitive(key)) return super.has(key);\n const [masterKey, _] = this.#unpack(key);\n return super.has(masterKey);\n }\n /**\n * Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.\n */\n set(key, value) {\n if (isPrimitive(key)) return super.set(key, value);\n const [masterKey, hash] = this.#unpack(key);\n if (super.has(masterKey)) {\n super.set(masterKey, value);\n } else {\n super.set(key, value);\n const keys = this.#keyMap.get(hash) || [];\n keys.push(key);\n this.#keyMap.set(hash, keys);\n }\n return this;\n }\n /**\n * @returns the number of elements in the Map.\n */\n get size() {\n return super.size;\n }\n}\nfunction assert(condition, msg) {\n if (!condition) throw new MingoError(msg);\n}\nfunction typeOf(v) {\n const t = typeof v;\n switch (t) {\n case \"number\":\n case \"string\":\n case \"boolean\":\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n return t;\n }\n if (v === null) return \"null\";\n if (isArray(v)) return \"array\";\n if (isDate(v)) return \"date\";\n if (isRegExp(v)) return \"regexp\";\n if (isTypedArray(v)) return \"arraybuffer\";\n if (v?.constructor === Object) return \"object\";\n return v?.constructor?.name?.toLowerCase() ?? \"object\";\n}\nconst isBoolean = (v) => typeof v === \"boolean\";\nconst isString = (v) => typeof v === \"string\";\nconst isSymbol = (v) => typeof v === \"symbol\";\nconst isNumber = (v) => !Number.isNaN(v) && typeof v === \"number\";\nconst isInteger = Number.isInteger;\nconst isArray = Array.isArray;\nconst isObject = (v) => typeOf(v) === \"object\";\nconst isObjectLike = (v) => !isPrimitive(v);\nconst isDate = (v) => v instanceof Date;\nconst isRegExp = (v) => v instanceof RegExp;\nconst isFunction = (v) => typeof v === \"function\";\nconst isNil = (v) => v === null || v === void 0;\nconst truthy = (arg, strict = true) => !!arg || strict && arg === \"\";\nconst isEmpty = (x) => isNil(x) || isString(x) && !x || isArray(x) && x.length === 0 || isObject(x) && Object.keys(x).length === 0;\nconst ensureArray = (x) => isArray(x) ? x : [x];\nconst has = (obj, ...props) => !!obj && props.every((p) => Object.prototype.hasOwnProperty.call(obj, p));\nconst isTypedArray = (v) => typeof ArrayBuffer !== \"undefined\" && ArrayBuffer.isView(v);\nconst cloneDeep = (v, refs) => {\n if (isNil(v) || isBoolean(v) || isNumber(v) || isString(v)) return v;\n if (isDate(v)) return new Date(v);\n if (isRegExp(v)) return new RegExp(v);\n if (isTypedArray(v)) {\n const ctor = v.constructor;\n return new ctor(v);\n }\n if (!(refs instanceof WeakSet)) refs = /* @__PURE__ */ new WeakSet();\n if (refs.has(v)) throw new Error(ERR_CYCLE_FOUND);\n refs.add(v);\n try {\n if (isArray(v)) {\n const arr = new Array(v.length);\n for (let i = 0; i < v.length; i++) arr[i] = cloneDeep(v[i], refs);\n return arr;\n }\n if (isObject(v)) {\n const obj = {};\n for (const k of Object.keys(v)) obj[k] = cloneDeep(v[k], refs);\n return obj;\n }\n } finally {\n refs.delete(v);\n }\n return v;\n};\nfunction intersection(input) {\n if (input.length === 0) return [];\n if (input.length === 1) return input[0].slice();\n for (const arr of input) if (arr.length === 0) return [];\n const maps = [HashMap.init(), HashMap.init()];\n let index = 0;\n for (const v of input[input.length - 1]) maps[0].set(v, true);\n for (let i = input.length - 2; i >= 0; i--) {\n for (let j = 0; j < input[i].length; j++) {\n const v = input[i][j];\n if (maps[index].has(v)) maps[index ^ 1].set(v, true);\n }\n if (maps[index ^ 1].size === 0) return [];\n maps[index].clear();\n index = index ^ 1;\n }\n return Array.from(maps[index].keys());\n}\nfunction flatten(xs, depth = 1) {\n const arr = new Array();\n function flatten2(ys, n) {\n for (let i = 0, len = ys.length; i < len; i++) {\n if (isArray(ys[i]) && (n > 0 || n < 0)) {\n flatten2(ys[i], Math.max(-1, n - 1));\n } else {\n arr.push(ys[i]);\n }\n }\n }\n flatten2(xs, depth);\n return arr;\n}\nfunction unique(input) {\n const m = HashMap.init();\n for (const v of input) m.set(v, true);\n return Array.from(m.keys());\n}\nfunction groupBy(collection, keyFunc) {\n if (collection.length < 1) return /* @__PURE__ */ new Map();\n const result = HashMap.init();\n for (let i = 0; i < collection.length; i++) {\n const obj = collection[i];\n const key = keyFunc(obj, i) ?? null;\n let a = result.get(key);\n if (!a) {\n a = [obj];\n result.set(key, a);\n } else {\n a.push(obj);\n }\n }\n return result;\n}\nfunction getValue(obj, key) {\n return isObjectLike(obj) ? obj[key] : void 0;\n}\nfunction unwrap(arr, depth) {\n if (depth < 1) return arr;\n while (depth-- && arr.length === 1 && isArray(arr[0])) arr = arr[0];\n return arr;\n}\nfunction resolve(obj, selector, options) {\n if (isScalar(obj)) return obj;\n const path = options?.pathArray ?? selector.split(\".\");\n if (path.length === 1 && !isArray(obj)) {\n return getValue(obj, path[0]);\n }\n if (path.length === 2 && !isArray(obj)) {\n const first = getValue(obj, path[0]);\n if (first == null) return void 0;\n if (!isArray(first)) return getValue(first, path[1]);\n }\n let depth = 0;\n function resolve2(o, path2) {\n let value = o;\n for (let i = 0; i < path2.length; i++) {\n const field = path2[i];\n const isText = !DIGITS_RE.test(field);\n if (isText && isArray(value)) {\n if (i === 0 && depth > 0) break;\n depth += 1;\n const subpath = path2.slice(i);\n value = value.reduce((acc, item) => {\n const v = resolve2(item, subpath);\n if (v !== void 0) acc.push(v);\n return acc;\n }, []);\n break;\n } else {\n value = getValue(value, field);\n }\n if (value === void 0) break;\n }\n return value;\n }\n const res = resolve2(obj, path);\n return isArray(res) && options?.unwrapArray ? unwrap(res, depth) : res;\n}\nfunction resolveGraph(obj, selector, options) {\n const sep = selector.indexOf(\".\");\n const key = sep == -1 ? selector : selector.substring(0, sep);\n const next = selector.substring(sep + 1);\n const hasNext = sep != -1;\n if (isArray(obj)) {\n const isIndex = /^\\d+$/.test(key);\n const arr = isIndex && options?.preserveIndex ? obj.slice() : [];\n if (isIndex) {\n const index = parseInt(key);\n let value2 = getValue(obj, index);\n if (hasNext) {\n value2 = resolveGraph(value2, next, options);\n }\n if (options?.preserveIndex) {\n arr[index] = value2;\n } else {\n arr.push(value2);\n }\n } else {\n for (const item of obj) {\n const value2 = resolveGraph(item, selector, options);\n if (options?.preserveMissing) {\n arr.push(value2 == void 0 ? MISSING : value2);\n } else if (value2 != void 0 || options?.preserveIndex) {\n arr.push(value2);\n }\n }\n }\n return arr;\n }\n const res = options?.preserveKeys ? { ...obj } : {};\n let value = getValue(obj, key);\n if (hasNext) {\n value = resolveGraph(value, next, options);\n }\n if (value === void 0) return void 0;\n res[key] = value;\n return res;\n}\nfunction filterMissing(obj) {\n if (isArray(obj)) {\n for (let i = obj.length - 1; i >= 0; i--) {\n if (obj[i] === MISSING) {\n obj.splice(i, 1);\n } else {\n filterMissing(obj[i]);\n }\n }\n } else if (isObject(obj)) {\n for (const k of Object.keys(obj)) {\n if (has(obj, k)) {\n filterMissing(obj[k]);\n }\n }\n }\n}\nconst DIGITS_RE = /^\\d+$/;\nfunction walk(obj, selector, fn, options) {\n const names = selector.split(\".\");\n const key = names[0];\n const next = names.slice(1).join(\".\");\n if (names.length === 1) {\n if (isObject(obj) || isArray(obj) && DIGITS_RE.test(key)) {\n fn(obj, key);\n }\n } else {\n if (options?.buildGraph && isNil(obj[key])) {\n obj[key] = {};\n }\n const item = obj[key];\n if (!item) return;\n const isNextArrayIndex = !!(names.length > 1 && DIGITS_RE.test(names[1]));\n if (isArray(item) && options?.descendArray && !isNextArrayIndex) {\n item.forEach(((e) => walk(e, next, fn, options)));\n } else {\n walk(item, next, fn, options);\n }\n }\n}\nfunction setValue(obj, selector, value) {\n walk(obj, selector, (item, key) => item[key] = value, {\n buildGraph: true\n });\n}\nfunction removeValue(obj, selector, options) {\n walk(\n obj,\n selector,\n ((item, key) => {\n if (isArray(item)) {\n item.splice(parseInt(key), 1);\n } else if (isObject(item)) {\n delete item[key];\n }\n }),\n options\n );\n}\nconst isOperator = (name) => !!name && name[0] === \"$\" && /^\\$[a-zA-Z0-9_]+$/.test(name);\nfunction normalize(expr) {\n if (isScalar(expr)) {\n return isRegExp(expr) ? { $regex: expr } : { $eq: expr };\n }\n if (isObjectLike(expr)) {\n if (!Object.keys(expr).some(isOperator)) return { $eq: expr };\n if (isObject(expr) && has(expr, \"$regex\")) {\n const newExpr = { ...expr };\n newExpr[\"$regex\"] = new RegExp(\n expr[\"$regex\"],\n expr[\"$options\"]\n );\n delete newExpr[\"$options\"];\n return newExpr;\n }\n }\n return expr;\n}\nfunction findInsertIndex(sorted, item, comparator = compare) {\n let lo = 0;\n let hi = sorted.length - 1;\n while (lo <= hi) {\n const mid = Math.round(lo + (hi - lo) / 2);\n if (comparator(item, sorted[mid]) < 0) {\n hi = mid - 1;\n } else if (comparator(item, sorted[mid]) > 0) {\n lo = mid + 1;\n } else {\n return mid;\n }\n }\n return lo;\n}\nclass PathValidator {\n constructor() {\n this.root = {\n children: /* @__PURE__ */ new Map(),\n isTerminal: false\n };\n }\n add(selector) {\n const parts = selector.split(\".\");\n let current = this.root;\n for (const part of parts) {\n if (current.isTerminal) return false;\n if (!current.children.has(part)) {\n current.children.set(part, {\n children: /* @__PURE__ */ new Map(),\n isTerminal: false\n });\n }\n current = current.children.get(part);\n }\n if (current.isTerminal || current.children.size) return false;\n return current.isTerminal = true;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n HashMap,\n MISSING,\n MingoError,\n PathValidator,\n assert,\n cloneDeep,\n compare,\n ensureArray,\n filterMissing,\n findInsertIndex,\n flatten,\n groupBy,\n has,\n hashCode,\n intersection,\n isArray,\n isBoolean,\n isDate,\n isEmpty,\n isEqual,\n isFunction,\n isInteger,\n isNil,\n isNumber,\n isObject,\n isObjectLike,\n isOperator,\n isPrimitive,\n isRegExp,\n isString,\n isSymbol,\n normalize,\n removeValue,\n resolve,\n resolveGraph,\n setValue,\n simpleCmp,\n truthy,\n typeOf,\n unique,\n walk\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar util_exports = {};\n__export(util_exports, {\n HashMap: () => import_internal.HashMap,\n MingoError: () => import_internal.MingoError,\n assert: () => import_internal.assert,\n cloneDeep: () => import_internal.cloneDeep,\n compare: () => import_internal.compare,\n ensureArray: () => import_internal.ensureArray,\n findInsertIndex: () => import_internal.findInsertIndex,\n flatten: () => import_internal.flatten,\n groupBy: () => import_internal.groupBy,\n has: () => import_internal.has,\n hashCode: () => import_internal.hashCode,\n intersection: () => import_internal.intersection,\n isArray: () => import_internal.isArray,\n isBoolean: () => import_internal.isBoolean,\n isDate: () => import_internal.isDate,\n isEmpty: () => import_internal.isEmpty,\n isEqual: () => import_internal.isEqual,\n isFunction: () => import_internal.isFunction,\n isInteger: () => import_internal.isInteger,\n isNil: () => import_internal.isNil,\n isNumber: () => import_internal.isNumber,\n isObject: () => import_internal.isObject,\n isObjectLike: () => import_internal.isObjectLike,\n isOperator: () => import_internal.isOperator,\n isRegExp: () => import_internal.isRegExp,\n isString: () => import_internal.isString,\n isSymbol: () => import_internal.isSymbol,\n normalize: () => import_internal.normalize,\n removeValue: () => import_internal.removeValue,\n resolve: () => import_internal.resolve,\n setValue: () => import_internal.setValue,\n typeOf: () => import_internal.typeOf,\n unique: () => import_internal.unique\n});\nmodule.exports = __toCommonJS(util_exports);\nvar import_internal = require(\"./_internal\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n HashMap,\n MingoError,\n assert,\n cloneDeep,\n compare,\n ensureArray,\n findInsertIndex,\n flatten,\n groupBy,\n has,\n hashCode,\n intersection,\n isArray,\n isBoolean,\n isDate,\n isEmpty,\n isEqual,\n isFunction,\n isInteger,\n isNil,\n isNumber,\n isObject,\n isObjectLike,\n isOperator,\n isRegExp,\n isString,\n isSymbol,\n normalize,\n removeValue,\n resolve,\n setValue,\n typeOf,\n unique\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n ComputeOptions: () => ComputeOptions,\n Context: () => Context,\n OpType: () => OpType,\n ProcessingMode: () => ProcessingMode,\n computeValue: () => computeValue,\n evalExpr: () => evalExpr\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../util\");\nvar ProcessingMode = /* @__PURE__ */ ((ProcessingMode2) => {\n ProcessingMode2[ProcessingMode2[\"CLONE_OFF\"] = 0] = \"CLONE_OFF\";\n ProcessingMode2[ProcessingMode2[\"CLONE_INPUT\"] = 1] = \"CLONE_INPUT\";\n ProcessingMode2[ProcessingMode2[\"CLONE_OUTPUT\"] = 2] = \"CLONE_OUTPUT\";\n ProcessingMode2[ProcessingMode2[\"CLONE_ALL\"] = 3] = \"CLONE_ALL\";\n return ProcessingMode2;\n})(ProcessingMode || {});\nclass ComputeOptions {\n constructor(options, locals) {\n this.options = options;\n this.#locals = locals ? { ...locals } : {};\n }\n #locals;\n /**\n * Initializes a new instance of the `ComputeOptions` class with the provided options.\n *\n * @param options - A partial set of options to configure the `ComputeOptions` instance.\n * If an instance of `ComputeOptions` is provided, its internal options and locals are used.\n * @returns A new `ComputeOptions` instance configured with the provided options and root.\n */\n static init(options) {\n return options instanceof ComputeOptions ? new ComputeOptions(options.options, options.#locals) : new ComputeOptions({\n idKey: \"_id\",\n scriptEnabled: true,\n useStrictMode: true,\n failOnError: true,\n processingMode: 0 /* CLONE_OFF */,\n ...options,\n context: options?.context ? Context.from(options?.context) : Context.init()\n });\n }\n update(locals) {\n Object.assign(this.#locals, locals, {\n // DO NOT override timestamp\n timestamp: this.#locals.timestamp,\n // merge variables.\n variables: { ...this.#locals?.variables, ...locals?.variables }\n });\n return this;\n }\n get local() {\n return this.#locals;\n }\n get now() {\n let timestamp = this.#locals.timestamp ?? 0;\n if (!timestamp) {\n timestamp = Date.now();\n Object.assign(this.#locals, { timestamp });\n }\n return new Date(timestamp);\n }\n get idKey() {\n return this.options.idKey;\n }\n get collation() {\n return this.options?.collation;\n }\n get processingMode() {\n return this.options?.processingMode;\n }\n get useStrictMode() {\n return this.options?.useStrictMode;\n }\n get scriptEnabled() {\n return this.options?.scriptEnabled;\n }\n get failOnError() {\n return this.options?.failOnError;\n }\n get collectionResolver() {\n return this.options?.collectionResolver;\n }\n get jsonSchemaValidator() {\n return this.options?.jsonSchemaValidator;\n }\n get variables() {\n return this.options?.variables;\n }\n get context() {\n return this.options?.context;\n }\n}\nvar OpType = /* @__PURE__ */ ((OpType2) => {\n OpType2[\"ACCUMULATOR\"] = \"accumulator\";\n OpType2[\"EXPRESSION\"] = \"expression\";\n OpType2[\"PIPELINE\"] = \"pipeline\";\n OpType2[\"PROJECTION\"] = \"projection\";\n OpType2[\"QUERY\"] = \"query\";\n OpType2[\"WINDOW\"] = \"window\";\n return OpType2;\n})(OpType || {});\nclass Context {\n #operators;\n constructor() {\n this.#operators = {\n [\"accumulator\" /* ACCUMULATOR */]: {},\n [\"expression\" /* EXPRESSION */]: {},\n [\"pipeline\" /* PIPELINE */]: {},\n [\"projection\" /* PROJECTION */]: {},\n [\"query\" /* QUERY */]: {},\n [\"window\" /* WINDOW */]: {}\n };\n }\n static init(ops = {}) {\n const ctx = new Context();\n for (const type of Object.keys(ops)) {\n ctx.#operators[type] = { ...ops[type] };\n }\n return ctx;\n }\n /** Returns a new context with the operators from the provided contexts merged left to right. */\n static from(...ctx) {\n if (ctx.length === 1) return Context.init(ctx[0].#operators);\n const newCtx = new Context();\n for (const context of ctx) {\n for (const type of Object.values(OpType)) {\n newCtx.addOps(type, context.#operators[type]);\n }\n }\n return newCtx;\n }\n addOps(type, operators) {\n this.#operators[type] = Object.assign({}, operators, this.#operators[type]);\n return this;\n }\n getOperator(type, name) {\n return this.#operators[type][name] ?? null;\n }\n addAccumulatorOps(ops) {\n return this.addOps(\"accumulator\" /* ACCUMULATOR */, ops);\n }\n addExpressionOps(ops) {\n return this.addOps(\"expression\" /* EXPRESSION */, ops);\n }\n addQueryOps(ops) {\n return this.addOps(\"query\" /* QUERY */, ops);\n }\n addPipelineOps(ops) {\n return this.addOps(\"pipeline\" /* PIPELINE */, ops);\n }\n addProjectionOps(ops) {\n return this.addOps(\"projection\" /* PROJECTION */, ops);\n }\n addWindowOps(ops) {\n return this.addOps(\"window\" /* WINDOW */, ops);\n }\n}\nfunction computeValue(obj, expr, operator, options) {\n return evalExpr(obj, { [operator]: expr }, options);\n}\nfunction evalExpr(obj, expr, options) {\n const copts = !(options instanceof ComputeOptions) || (0, import_util.isNil)(options.local.root) ? ComputeOptions.init(options).update({ root: obj }) : options;\n return computeExpression(obj, expr, copts);\n}\nconst SYSTEM_VARS = /* @__PURE__ */ new Set([\"$$ROOT\", \"$$CURRENT\", \"$$REMOVE\", \"$$NOW\"]);\nfunction computeExpression(obj, expr, options) {\n if ((0, import_util.isString)(expr) && expr.length > 0 && expr[0] === \"$\") {\n if (expr === \"$$KEEP\" || expr === \"$$PRUNE\" || expr === \"$$DESCEND\")\n return expr;\n let ctx = options.local.root;\n const arr = expr.split(\".\");\n const dotIdx = expr.indexOf(\".\");\n const prefix = dotIdx === -1 ? expr : expr.substring(0, dotIdx);\n if (SYSTEM_VARS.has(arr[0])) {\n switch (prefix) {\n case \"$$ROOT\":\n break;\n case \"$$CURRENT\":\n ctx = obj;\n break;\n case \"$$REMOVE\":\n ctx = void 0;\n break;\n case \"$$NOW\":\n ctx = new Date(options.now);\n break;\n }\n expr = dotIdx === -1 ? \"\" : expr.substring(dotIdx + 1);\n } else if (prefix.length >= 2 && prefix[1] === \"$\") {\n ctx = Object.assign(\n {},\n // global vars\n options.variables,\n // current item is added before local variables because the binding may be changed.\n { this: obj },\n // local vars\n options?.local?.variables\n );\n const name = prefix.substring(2);\n (0, import_util.assert)((0, import_util.has)(ctx, name), `Use of undefined variable: ${name}`);\n expr = expr.substring(2);\n } else {\n expr = expr.substring(1);\n }\n return expr === \"\" ? ctx : (0, import_util.resolve)(ctx, expr);\n }\n if ((0, import_util.isArray)(expr)) {\n return expr.map((item) => computeExpression(obj, item, options));\n }\n if ((0, import_util.isObject)(expr)) {\n const keys = Object.keys(expr);\n if ((0, import_util.isOperator)(keys[0])) {\n (0, import_util.assert)(keys.length === 1, \"Expression must contain a single operator.\");\n return computeOperator(obj, expr[keys[0]], keys[0], options);\n }\n const result = {};\n for (let i = 0; i < keys.length; i++) {\n result[keys[i]] = computeExpression(obj, expr[keys[i]], options);\n }\n return result;\n }\n return expr;\n}\nfunction computeOperator(obj, expr, operator, options) {\n const context = options.context;\n const fn = context.getOperator(\"expression\" /* EXPRESSION */, operator);\n if (fn) return fn(obj, expr, options);\n const accFn = context.getOperator(\"accumulator\" /* ACCUMULATOR */, operator);\n (0, import_util.assert)(!!accFn, `accumulator '${operator}' is not registered.`);\n if (!(0, import_util.isArray)(obj)) {\n obj = computeExpression(obj, expr, options);\n expr = null;\n }\n (0, import_util.assert)((0, import_util.isArray)(obj), `arguments must resolve to array for ${operator}.`);\n return accFn(obj, expr, options);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ComputeOptions,\n Context,\n OpType,\n ProcessingMode,\n computeValue,\n evalExpr\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lazy_exports = {};\n__export(lazy_exports, {\n Iterator: () => Iterator,\n Lazy: () => Lazy,\n concat: () => concat\n});\nmodule.exports = __toCommonJS(lazy_exports);\nvar import_util = require(\"./util\");\nfunction Lazy(source) {\n return new Iterator(source);\n}\nfunction concat(...iterators) {\n let index = 0;\n return Lazy(() => {\n while (index < iterators.length) {\n const o = iterators[index].next();\n if (!o.done) return o;\n index++;\n }\n return { done: true, value: void 0 };\n });\n}\nfunction isGenerator(o) {\n return !!o && typeof o === \"object\" && typeof o?.next === \"function\";\n}\nfunction isIterable(o) {\n return !!o && (typeof o === \"object\" || typeof o === \"function\") && typeof o[Symbol.iterator] === \"function\";\n}\nclass Iterator {\n #iteratees = [];\n #buffer = [];\n #getNext;\n #done = false;\n constructor(source) {\n let iter;\n if (isIterable(source))\n iter = source[Symbol.iterator]();\n else if (isGenerator(source)) iter = source;\n else if (typeof source === \"function\") iter = { next: source };\n else\n (0, import_util.assert)(0, \"mingo: iterator requires an iterable, generator or function\");\n let index = -1;\n this.#getNext = () => {\n while (true) {\n let { value, done } = iter.next();\n if (done) return { done };\n let ok = true;\n index++;\n for (let i = 0; i < this.#iteratees.length; i++) {\n const { op, fn } = this.#iteratees[i];\n const res = fn(value, index);\n if (op === \"map\") {\n value = res;\n } else if (!res) {\n ok = false;\n break;\n }\n }\n if (ok) return { value, done };\n }\n };\n }\n /**\n * Add an iteratee to this lazy sequence\n */\n push(op, fn) {\n this.#iteratees.push({ op, fn });\n return this;\n }\n next() {\n return this.#getNext();\n }\n // Iteratees methods\n /**\n * Transform each item in the sequence to a new value\n * @param {Function} f\n */\n map(f) {\n return this.push(\"map\", f);\n }\n /**\n * Select only items matching the given predicate\n * @param {Function} f\n */\n filter(f) {\n return this.push(\"filter\", f);\n }\n /**\n * Take given numbe for values from sequence\n * @param {Number} n A number greater than 0\n */\n take(n) {\n (0, import_util.assert)(n >= 0, \"value must be a non-negative integer\");\n return this.filter((_) => n-- > 0);\n }\n /**\n * Drop a number of values from the sequence\n * @param {Number} n Number of items to drop greater than 0\n */\n drop(n) {\n (0, import_util.assert)(n >= 0, \"value must be a non-negative integer\");\n return this.filter((_) => n-- <= 0);\n }\n // Transformations\n /**\n * Returns a new lazy object with results of the transformation\n * The entire sequence is realized.\n *\n * @param {Callback} f Tranform function of type (Array) => (Any)\n */\n transform(f) {\n const self = this;\n let iter;\n return Lazy(() => {\n if (!iter) iter = f(self.collect());\n return iter.next();\n });\n }\n /**\n * Retrieves all remaining values from the lazy evaluation and returns them as an array.\n * This method processes the underlying iterator until it is exhausted, storing the results\n * in an internal buffer to ensure subsequent calls return the same data.\n */\n collect() {\n while (!this.#done) {\n const { done, value } = this.#getNext();\n if (!done) this.#buffer.push(value);\n this.#done = done;\n }\n return this.#buffer;\n }\n /**\n * Execute the callback for each value.\n * @param f The callback function.\n */\n each(f) {\n for (let o = this.next(); o.done !== true; o = this.next()) f(o.value);\n }\n /**\n * Returns the reduction of sequence according the reducing function\n *\n * @param f The reducing function\n * @param initialValue The initial value\n */\n reduce(f, initialValue) {\n let o = this.next();\n if (initialValue === void 0 && !o.done) {\n initialValue = o.value;\n o = this.next();\n }\n while (!o.done) {\n initialValue = f(initialValue, o.value);\n o = this.next();\n }\n return initialValue;\n }\n /**\n * Returns the number of matched items in the sequence.\n * The stream is realized and buffered for later retrieval with {@link collect}.\n */\n size() {\n return this.collect().length;\n }\n [Symbol.iterator]() {\n return this;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Iterator,\n Lazy,\n concat\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar aggregator_exports = {};\n__export(aggregator_exports, {\n Aggregator: () => Aggregator\n});\nmodule.exports = __toCommonJS(aggregator_exports);\nvar import_internal = require(\"./core/_internal\");\nvar import_lazy = require(\"./lazy\");\nvar import_util = require(\"./util\");\nclass Aggregator {\n #pipeline;\n #options;\n /**\n * Creates an instance of the Aggregator class.\n *\n * @param pipeline - An array of objects representing the aggregation pipeline stages.\n * @param options - Optional configuration settings for the aggregator.\n */\n constructor(pipeline, options) {\n this.#pipeline = pipeline;\n this.#options = import_internal.ComputeOptions.init(options);\n }\n /**\n * Processes a collection through an aggregation pipeline and returns an iterator\n * for the transformed results.\n *\n * @param collection - The input collection to process. This can be any source\n * that implements the `Source` interface.\n * @param options - Optional configuration for processing. If not provided, the\n * default options of the aggregator instance will be used.\n * @returns An iterator that yields the results of the aggregation pipeline.\n *\n * @throws Will throw an error if:\n * - A pipeline stage contains more than one operator.\n * - The `$documents` operator is not the first stage in the pipeline.\n * - An unregistered pipeline operator is encountered.\n */\n stream(collection, options) {\n let iter = (0, import_lazy.Lazy)(collection);\n const opts = options ?? this.#options;\n const mode = opts.processingMode;\n if (mode & import_internal.ProcessingMode.CLONE_INPUT) iter.map((o) => (0, import_util.cloneDeep)(o));\n iter = this.#pipeline.map((stage, i) => {\n const keys = Object.keys(stage);\n (0, import_util.assert)(\n keys.length === 1,\n `aggregation stage must have single operator, got ${keys.toString()}.`\n );\n const name = keys[0];\n (0, import_util.assert)(\n name !== \"$documents\" || i == 0,\n \"$documents must be first stage in pipeline.\"\n );\n const op = opts.context.getOperator(import_internal.OpType.PIPELINE, name);\n (0, import_util.assert)(!!op, `unregistered pipeline operator ${name}.`);\n return [op, stage[name]];\n }).reduce((acc, [op, expr]) => op(acc, expr, opts), iter);\n if (mode & import_internal.ProcessingMode.CLONE_OUTPUT) iter.map((o) => (0, import_util.cloneDeep)(o));\n return iter;\n }\n /**\n * Executes the aggregation pipeline on the provided collection and returns the resulting array.\n *\n * @template T - The type of the objects in the resulting array.\n * @param collection - The input data source to run the aggregation on.\n * @param options - Optional settings to customize the aggregation behavior.\n * @returns An array of objects of type `T` resulting from the aggregation.\n */\n run(collection, options) {\n return this.stream(collection, options).collect();\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Aggregator\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar push_exports = {};\n__export(push_exports, {\n $push: () => $push\n});\nmodule.exports = __toCommonJS(push_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nconst $push = (coll, expr, options) => {\n if ((0, import_util.isNil)(expr)) return coll;\n const copts = import_internal.ComputeOptions.init(options);\n const result = new Array(coll.length);\n for (let i = 0; i < coll.length; i++) {\n const root = coll[i];\n result[i] = (0, import_internal.evalExpr)(root, expr, copts.update({ root })) ?? null;\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $push\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar accumulator_exports = {};\n__export(accumulator_exports, {\n $accumulator: () => $accumulator\n});\nmodule.exports = __toCommonJS(accumulator_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $accumulator = (coll, expr, options) => {\n (0, import_util.assert)(\n options.scriptEnabled,\n \"$accumulator requires 'scriptEnabled' option to be true\"\n );\n const copts = import_internal.ComputeOptions.init(options);\n const input = expr;\n const initArgs = (0, import_internal.evalExpr)(\n copts?.local?.groupId,\n input.initArgs || [],\n copts.update({ root: copts?.local?.groupId })\n );\n const args = (0, import_push.$push)(coll, input.accumulateArgs, copts);\n for (let i = 0; i < args.length; i++) {\n for (let j = 0; j < args[i].length; j++) {\n args[i][j] = args[i][j] ?? null;\n }\n }\n const initialValue = input.init.apply(null, initArgs);\n const f = input.accumulate;\n let result = initialValue;\n for (let i = 0; i < args.length; i++) {\n result = f.apply(null, [result, ...args[i]]);\n }\n if (input.finalize) result = input.finalize.call(null, result);\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $accumulator\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar addToSet_exports = {};\n__export(addToSet_exports, {\n $addToSet: () => $addToSet\n});\nmodule.exports = __toCommonJS(addToSet_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $addToSet = (coll, expr, options) => (0, import_util.unique)((0, import_push.$push)(coll, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $addToSet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar avg_exports = {};\n__export(avg_exports, {\n $avg: () => $avg\n});\nmodule.exports = __toCommonJS(avg_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $avg = (coll, expr, options) => {\n const data = (0, import_push.$push)(coll, expr, options).filter(import_util.isNumber);\n if (data.length === 0) return null;\n const sum = data.reduce((acc, n) => acc + n, 0);\n return sum / data.length;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $avg\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sort_exports = {};\n__export(sort_exports, {\n $sort: () => $sort\n});\nmodule.exports = __toCommonJS(sort_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $sort(coll, sortKeys, options) {\n (0, import_util.assert)(\n (0, import_util.isObject)(sortKeys) && Object.keys(sortKeys).length > 0,\n \"$sort specification is invalid\"\n );\n let cmp = import_util.compare;\n const collationSpec = options.collation;\n if ((0, import_util.isObject)(collationSpec) && (0, import_util.isString)(collationSpec.locale)) {\n cmp = collationComparator(collationSpec);\n }\n return coll.transform((coll2) => {\n const modifiers = Object.keys(sortKeys);\n for (const key of modifiers.reverse()) {\n const groups = (0, import_util.groupBy)(coll2, (obj) => (0, import_util.resolve)(obj, key));\n const sortedKeys = Array.from(groups.keys());\n let nativeSorted = false;\n if (cmp === import_util.compare) {\n let t_str = true;\n let t_num = true;\n for (const v of sortedKeys) {\n t_str &&= (0, import_util.isString)(v);\n t_num &&= (0, import_util.isNumber)(v);\n if (!t_str && !t_num) break;\n }\n nativeSorted = t_str || t_num;\n if (t_str) sortedKeys.sort();\n else if (t_num) {\n const numbers = new Float64Array(sortedKeys).sort();\n for (let i2 = 0; i2 < numbers.length; i2++) {\n sortedKeys[i2] = numbers[i2];\n }\n }\n }\n if (!nativeSorted) sortedKeys.sort(cmp);\n if (sortKeys[key] === -1) sortedKeys.reverse();\n let i = 0;\n for (const k of sortedKeys) for (const v of groups.get(k)) coll2[i++] = v;\n (0, import_util.assert)(i == coll2.length, \"bug: counter must match collection size.\");\n }\n return (0, import_lazy.Lazy)(coll2);\n });\n}\nconst COLLATION_STRENGTH = {\n // Only strings that differ in base letters compare as unequal. Examples: a \u2260 b, a = \u00E1, a = A.\n 1: \"base\",\n // Only strings that differ in base letters or accents and other diacritic marks compare as unequal.\n // Examples: a \u2260 b, a \u2260 \u00E1, a = A.\n 2: \"accent\",\n // Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal.\n // Other differences may also be taken into consideration. Examples: a \u2260 b, a \u2260 \u00E1, a \u2260 A\n 3: \"variant\"\n // case - Only strings that differ in base letters or case compare as unequal. Examples: a \u2260 b, a = \u00E1, a \u2260 A.\n};\nfunction collationComparator(spec) {\n const localeOpt = {\n sensitivity: COLLATION_STRENGTH[spec.strength || 3],\n caseFirst: spec.caseFirst === \"off\" ? \"false\" : spec.caseFirst,\n numeric: spec.numericOrdering || false,\n ignorePunctuation: spec.alternate === \"shifted\"\n };\n if (spec.caseLevel === true) {\n if (localeOpt.sensitivity === \"base\") localeOpt.sensitivity = \"case\";\n if (localeOpt.sensitivity === \"accent\") localeOpt.sensitivity = \"variant\";\n }\n const collator = new Intl.Collator(spec.locale, localeOpt);\n return (a, b) => (0, import_util.isString)(a) && (0, import_util.isString)(b) ? collator.compare(a, b) : (0, import_util.compare)(a, b);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sort\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bottomN_exports = {};\n__export(bottomN_exports, {\n $bottomN: () => $bottomN\n});\nmodule.exports = __toCommonJS(bottomN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_sort = require(\"../pipeline/sort\");\nvar import_push = require(\"./push\");\nconst $bottomN = (coll, expr, options) => {\n const copts = options;\n const args = expr;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, args.n, copts);\n const result = (0, import_sort.$sort)((0, import_lazy.Lazy)(coll), args.sortBy, options).collect();\n const m = result.length;\n return (0, import_push.$push)(m <= n ? result : result.slice(m - n), args.output, copts);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bottomN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bottom_exports = {};\n__export(bottom_exports, {\n $bottom: () => $bottom\n});\nmodule.exports = __toCommonJS(bottom_exports);\nvar import_bottomN = require(\"./bottomN\");\nconst $bottom = (coll, expr, options) => {\n return (0, import_bottomN.$bottomN)(coll, { ...expr, n: 1 }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bottom\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar count_exports = {};\n__export(count_exports, {\n $count: () => $count\n});\nmodule.exports = __toCommonJS(count_exports);\nconst $count = (coll, _expr, _opts) => coll.length;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $count\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n covariance: () => covariance,\n stddev: () => stddev\n});\nmodule.exports = __toCommonJS(internal_exports);\nfunction stddev(data, sampled = true) {\n const sum = data.reduce((acc, n) => acc + n, 0);\n const N = Math.max(data.length, 1);\n const avg = sum / N;\n return Math.sqrt(\n data.reduce((acc, n) => acc + Math.pow(n - avg, 2), 0) / (N - Number(sampled))\n );\n}\nfunction covariance(dataset, sampled = true) {\n if (dataset.length < 2) return sampled ? null : 0;\n let meanX = 0;\n let meanY = 0;\n for (const [x, y] of dataset) {\n meanX += x;\n meanY += y;\n }\n meanX /= dataset.length;\n meanY /= dataset.length;\n let result = 0;\n for (const [x, y] of dataset) {\n result += (x - meanX) * (y - meanY);\n }\n return result / (dataset.length - Number(sampled));\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n covariance,\n stddev\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar covariancePop_exports = {};\n__export(covariancePop_exports, {\n $covariancePop: () => $covariancePop\n});\nmodule.exports = __toCommonJS(covariancePop_exports);\nvar import_internal = require(\"./_internal\");\nvar import_push = require(\"./push\");\nconst $covariancePop = (coll, expr, options) => (0, import_internal.covariance)((0, import_push.$push)(coll, expr, options), false);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $covariancePop\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar covarianceSamp_exports = {};\n__export(covarianceSamp_exports, {\n $covarianceSamp: () => $covarianceSamp\n});\nmodule.exports = __toCommonJS(covarianceSamp_exports);\nvar import_internal = require(\"./_internal\");\nvar import_push = require(\"./push\");\nconst $covarianceSamp = (coll, expr, options) => (0, import_internal.covariance)((0, import_push.$push)(coll, expr, options), true);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $covarianceSamp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar first_exports = {};\n__export(first_exports, {\n $first: () => $first\n});\nmodule.exports = __toCommonJS(first_exports);\nvar import_internal = require(\"../../core/_internal\");\nconst $first = (coll, expr, options) => {\n const obj = coll[0];\n const copts = import_internal.ComputeOptions.init(options).update({ root: obj });\n return (0, import_internal.evalExpr)(obj, expr, copts) ?? null;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $first\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n ARR_OPTS: () => ARR_OPTS,\n INT_OPTS: () => INT_OPTS,\n errExpectArray: () => errExpectArray,\n errExpectNumber: () => errExpectNumber,\n errExpectObject: () => errExpectObject,\n errExpectString: () => errExpectString,\n errInvalidArgs: () => errInvalidArgs\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../../util\");\nconst INT_OPTS = {\n int: { int: true },\n // (-\u221E, \u221E)\n pos: { min: 1, int: true },\n // [1, \u221E]\n index: { min: 0, int: true },\n // [0, \u221E]\n nzero: { min: 0, max: 0, int: true }\n // non-zero\n};\nconst ARR_OPTS = {\n int: { type: \"integers\" },\n obj: { type: \"objects\" }\n};\nfunction errInvalidArgs(failOnError, message) {\n (0, import_util.assert)(!failOnError, message);\n return null;\n}\nfunction errExpectObject(failOnError, prefix) {\n const msg = `${prefix} expression must resolve to object`;\n (0, import_util.assert)(!failOnError, msg);\n return null;\n}\nfunction errExpectString(failOnError, prefix) {\n const msg = `${prefix} expression must resolve to string`;\n (0, import_util.assert)(!failOnError, msg);\n return null;\n}\nfunction errExpectNumber(failOnError, name, opts) {\n const type = opts?.int ? \"integer\" : \"number\";\n const min = opts?.min ?? -Infinity;\n const max = opts?.max ?? Infinity;\n let msg;\n if (min === 0 && max === 0) {\n msg = `${name} expression must resolve to non-zero ${type}`;\n } else if (min === 0 && max === Infinity) {\n msg = `${name} expression must resolve to non-negative ${type}`;\n } else if (min !== -Infinity && max !== Infinity) {\n msg = `${name} expression must resolve to ${type} in range [${min}, ${max}]`;\n } else if (min > 0) {\n msg = `${name} expression must resolve to positive ${type}`;\n } else {\n msg = `${name} expression must resolve to ${type}`;\n }\n (0, import_util.assert)(!failOnError, msg);\n return null;\n}\nfunction errExpectArray(failOnError, prefix, opts) {\n let suffix = \"array\";\n if (!(0, import_util.isNil)(opts?.size) && opts?.size >= 0)\n suffix = opts.size === 0 ? \"non-zero array\" : `array(${opts.size})`;\n if (opts?.type) suffix = `array of ${opts.type}`;\n const msg = `${prefix} expression must resolve to ${suffix}`;\n (0, import_util.assert)(!failOnError, msg);\n return null;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ARR_OPTS,\n INT_OPTS,\n errExpectArray,\n errExpectNumber,\n errExpectObject,\n errExpectString,\n errInvalidArgs\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar firstN_exports = {};\n__export(firstN_exports, {\n $firstN: () => $firstN\n});\nmodule.exports = __toCommonJS(firstN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $firstN = (coll, expr, options) => {\n const foe = options.failOnError;\n const copts = options;\n const m = coll.length;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts);\n if (!(0, import_util.isInteger)(n) || n < 1)\n return (0, import_internal2.errExpectNumber)(foe, \"$firstN 'n'\", import_internal2.INT_OPTS.pos);\n return (0, import_push.$push)(m <= n ? coll : coll.slice(0, n), expr.input, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $firstN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar last_exports = {};\n__export(last_exports, {\n $last: () => $last\n});\nmodule.exports = __toCommonJS(last_exports);\nvar import_internal = require(\"../../core/_internal\");\nconst $last = (coll, expr, options) => {\n const obj = coll[coll.length - 1];\n const copts = import_internal.ComputeOptions.init(options).update({ root: obj });\n return (0, import_internal.evalExpr)(obj, expr, copts) ?? null;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $last\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lastN_exports = {};\n__export(lastN_exports, {\n $lastN: () => $lastN\n});\nmodule.exports = __toCommonJS(lastN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $lastN = (coll, expr, options) => {\n const copts = options;\n const m = coll.length;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts);\n const foe = options.failOnError;\n if (!(0, import_util.isInteger)(n) || n < 1) {\n return (0, import_internal2.errExpectNumber)(foe, \"$lastN 'n'\", import_internal2.INT_OPTS.pos);\n }\n return (0, import_push.$push)(m <= n ? coll : coll.slice(m - n), expr.input, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lastN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar max_exports = {};\n__export(max_exports, {\n $max: () => $max\n});\nmodule.exports = __toCommonJS(max_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $max = (coll, expr, options) => {\n const items = (0, import_push.$push)(coll, expr, options).filter((v) => !(0, import_util.isNil)(v));\n if (!items.length) return null;\n return items.reduce((r, v) => (0, import_util.compare)(r, v) >= 0 ? r : v);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $max\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar maxN_exports = {};\n__export(maxN_exports, {\n $maxN: () => $maxN\n});\nmodule.exports = __toCommonJS(maxN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $maxN = (coll, expr, options) => {\n const copts = options;\n const m = coll.length;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts);\n if (!(0, import_util.isInteger)(n) || n < 1) {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$maxN 'n'\", import_internal2.INT_OPTS.pos);\n }\n const arr = (0, import_push.$push)(coll, expr.input, options).filter((o) => !(0, import_util.isNil)(o));\n arr.sort((a, b) => -1 * (0, import_util.compare)(a, b));\n return m <= n ? arr : arr.slice(0, n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $maxN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar percentile_exports = {};\n__export(percentile_exports, {\n $percentile: () => $percentile\n});\nmodule.exports = __toCommonJS(percentile_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $percentile = (coll, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"p\") && (0, import_util.isArray)(expr.p),\n \"$percentile expects object { input, p }\"\n );\n const X = (0, import_push.$push)(coll, expr.input, options).filter(import_util.isNumber).sort();\n const centiles = (0, import_push.$push)(expr.p, \"$$CURRENT\", options);\n const method = expr.method || \"approximate\";\n for (const n of centiles) {\n if (!(0, import_util.isNumber)(n) || n < 0 || n > 1) {\n return (0, import_internal.errInvalidArgs)(\n options.failOnError,\n \"$percentile 'p' must resolve to array of numbers between [0.0, 1.0]\"\n );\n }\n }\n return centiles.map((p) => {\n const r = p * (X.length - 1) + 1;\n const ri = Math.floor(r);\n const result = r === ri ? X[r - 1] : X[ri - 1] + r % 1 * (X[ri] - X[ri - 1]);\n switch (method) {\n case \"exact\":\n return result;\n case \"approximate\": {\n const i = (0, import_util.findInsertIndex)(X, result);\n return i / X.length >= p ? X[Math.max(i - 1, 0)] : X[i];\n }\n }\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $percentile\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar median_exports = {};\n__export(median_exports, {\n $median: () => $median\n});\nmodule.exports = __toCommonJS(median_exports);\nvar import_percentile = require(\"./percentile\");\nconst $median = (coll, expr, options) => (0, import_percentile.$percentile)(coll, { ...expr, p: [0.5] }, options)?.pop();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $median\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mergeObjects_exports = {};\n__export(mergeObjects_exports, {\n $mergeObjects: () => $mergeObjects\n});\nmodule.exports = __toCommonJS(mergeObjects_exports);\nvar import_util = require(\"../../util\");\nconst $mergeObjects = (coll, _expr, _options) => {\n const acc = {};\n for (const o of coll) {\n if ((0, import_util.isNil)(o)) continue;\n for (const k of Object.keys(o)) {\n if (o[k] !== void 0) acc[k] = o[k];\n }\n }\n return acc;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mergeObjects\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar min_exports = {};\n__export(min_exports, {\n $min: () => $min\n});\nmodule.exports = __toCommonJS(min_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $min = (coll, expr, options) => {\n const items = (0, import_push.$push)(coll, expr, options).filter((v) => !(0, import_util.isNil)(v));\n if (!items.length) return null;\n return items.reduce((r, v) => (0, import_util.compare)(r, v) <= 0 ? r : v);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $min\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar minN_exports = {};\n__export(minN_exports, {\n $minN: () => $minN\n});\nmodule.exports = __toCommonJS(minN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"../expression/_internal\");\nvar import_push = require(\"./push\");\nconst $minN = (coll, expr, options) => {\n const copts = options;\n const m = coll.length;\n const n = (0, import_internal.evalExpr)(copts?.local?.groupId, expr.n, copts);\n if (!(0, import_util.isInteger)(n) || n < 1) {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$minN 'n'\", import_internal2.INT_OPTS.pos);\n }\n const arr = (0, import_push.$push)(coll, expr.input, options).filter((o) => !(0, import_util.isNil)(o));\n arr.sort(import_util.compare);\n return m <= n ? arr : arr.slice(0, n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $minN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar stdDevPop_exports = {};\n__export(stdDevPop_exports, {\n $stdDevPop: () => $stdDevPop\n});\nmodule.exports = __toCommonJS(stdDevPop_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nvar import_push = require(\"./push\");\nconst $stdDevPop = (coll, expr, options) => (0, import_internal.stddev)((0, import_push.$push)(coll, expr, options).filter(import_util.isNumber), false);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $stdDevPop\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar stdDevSamp_exports = {};\n__export(stdDevSamp_exports, {\n $stdDevSamp: () => $stdDevSamp\n});\nmodule.exports = __toCommonJS(stdDevSamp_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nvar import_push = require(\"./push\");\nconst $stdDevSamp = (coll, expr, options) => (0, import_internal.stddev)((0, import_push.$push)(coll, expr, options).filter(import_util.isNumber), true);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $stdDevSamp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sum_exports = {};\n__export(sum_exports, {\n $sum: () => $sum\n});\nmodule.exports = __toCommonJS(sum_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"./push\");\nconst $sum = (coll, expr, options) => {\n if ((0, import_util.isNumber)(expr)) return coll.length * expr;\n const nums = (0, import_push.$push)(coll, expr, options).filter(import_util.isNumber);\n return nums.reduce((r, n) => r + n, 0);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sum\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar topN_exports = {};\n__export(topN_exports, {\n $topN: () => $topN\n});\nmodule.exports = __toCommonJS(topN_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_sort = require(\"../pipeline/sort\");\nvar import_push = require(\"./push\");\nconst $topN = (coll, expr, options) => {\n const copts = options;\n const { n, sortBy } = (0, import_internal.evalExpr)(copts?.local?.groupId, expr, copts);\n const result = (0, import_sort.$sort)((0, import_lazy.Lazy)(coll), sortBy, options).take(n).collect();\n return (0, import_push.$push)(result, expr.output, copts);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $topN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar top_exports = {};\n__export(top_exports, {\n $top: () => $top\n});\nmodule.exports = __toCommonJS(top_exports);\nvar import_topN = require(\"./topN\");\nconst $top = (coll, expr, options) => (0, import_topN.$topN)(coll, { ...expr, n: 1 }, options);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $top\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar accumulator_exports = {};\nmodule.exports = __toCommonJS(accumulator_exports);\n__reExport(accumulator_exports, require(\"./accumulator\"), module.exports);\n__reExport(accumulator_exports, require(\"./addToSet\"), module.exports);\n__reExport(accumulator_exports, require(\"./avg\"), module.exports);\n__reExport(accumulator_exports, require(\"./bottom\"), module.exports);\n__reExport(accumulator_exports, require(\"./bottomN\"), module.exports);\n__reExport(accumulator_exports, require(\"./count\"), module.exports);\n__reExport(accumulator_exports, require(\"./covariancePop\"), module.exports);\n__reExport(accumulator_exports, require(\"./covarianceSamp\"), module.exports);\n__reExport(accumulator_exports, require(\"./first\"), module.exports);\n__reExport(accumulator_exports, require(\"./firstN\"), module.exports);\n__reExport(accumulator_exports, require(\"./last\"), module.exports);\n__reExport(accumulator_exports, require(\"./lastN\"), module.exports);\n__reExport(accumulator_exports, require(\"./max\"), module.exports);\n__reExport(accumulator_exports, require(\"./maxN\"), module.exports);\n__reExport(accumulator_exports, require(\"./median\"), module.exports);\n__reExport(accumulator_exports, require(\"./mergeObjects\"), module.exports);\n__reExport(accumulator_exports, require(\"./min\"), module.exports);\n__reExport(accumulator_exports, require(\"./minN\"), module.exports);\n__reExport(accumulator_exports, require(\"./percentile\"), module.exports);\n__reExport(accumulator_exports, require(\"./push\"), module.exports);\n__reExport(accumulator_exports, require(\"./stdDevPop\"), module.exports);\n__reExport(accumulator_exports, require(\"./stdDevSamp\"), module.exports);\n__reExport(accumulator_exports, require(\"./sum\"), module.exports);\n__reExport(accumulator_exports, require(\"./top\"), module.exports);\n__reExport(accumulator_exports, require(\"./topN\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./accumulator\"),\n ...require(\"./addToSet\"),\n ...require(\"./avg\"),\n ...require(\"./bottom\"),\n ...require(\"./bottomN\"),\n ...require(\"./count\"),\n ...require(\"./covariancePop\"),\n ...require(\"./covarianceSamp\"),\n ...require(\"./first\"),\n ...require(\"./firstN\"),\n ...require(\"./last\"),\n ...require(\"./lastN\"),\n ...require(\"./max\"),\n ...require(\"./maxN\"),\n ...require(\"./median\"),\n ...require(\"./mergeObjects\"),\n ...require(\"./min\"),\n ...require(\"./minN\"),\n ...require(\"./percentile\"),\n ...require(\"./push\"),\n ...require(\"./stdDevPop\"),\n ...require(\"./stdDevSamp\"),\n ...require(\"./sum\"),\n ...require(\"./top\"),\n ...require(\"./topN\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar abs_exports = {};\n__export(abs_exports, {\n $abs: () => $abs\n});\nmodule.exports = __toCommonJS(abs_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $abs = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\")\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$abs\");\n return Math.abs(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $abs\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar add_exports = {};\n__export(add_exports, {\n $add: () => $add\n});\nmodule.exports = __toCommonJS(add_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst err = \"$add expression must resolve to array of numbers.\";\nconst $add = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const failOnError = options.failOnError;\n let dateFound = false;\n let result = 0;\n if (!(0, import_util.isArray)(args)) return (0, import_internal2.errInvalidArgs)(failOnError, err);\n for (const n of args) {\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n === \"number\") {\n result += n;\n } else if ((0, import_util.isDate)(n)) {\n if (dateFound) {\n return (0, import_internal2.errInvalidArgs)(failOnError, \"$add must only have one date\");\n }\n dateFound = true;\n result += +n;\n } else {\n return (0, import_internal2.errInvalidArgs)(failOnError, err);\n }\n }\n return dateFound ? new Date(result) : result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $add\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ceil_exports = {};\n__export(ceil_exports, {\n $ceil: () => $ceil\n});\nmodule.exports = __toCommonJS(ceil_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $ceil = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\")\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$ceil\");\n return Math.ceil(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ceil\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar divide_exports = {};\n__export(divide_exports, {\n $divide: () => $divide\n});\nmodule.exports = __toCommonJS(divide_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $divide = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$divide expects array(2)\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let t_num = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n t_num &&= (0, import_util.isNumber)(v);\n }\n if (!t_num) {\n return (0, import_internal2.errExpectArray)(foe, \"$divide\", {\n size: 2,\n type: \"number\"\n });\n }\n if (args[1] === 0)\n return (0, import_internal2.errInvalidArgs)(foe, \"$divide cannot divide by zero\");\n return args[0] / args[1];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $divide\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar exp_exports = {};\n__export(exp_exports, {\n $exp: () => $exp\n});\nmodule.exports = __toCommonJS(exp_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $exp = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\") {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$exp\");\n }\n return Math.exp(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $exp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar floor_exports = {};\n__export(floor_exports, {\n $floor: () => $floor\n});\nmodule.exports = __toCommonJS(floor_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $floor = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\") {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$floor\");\n }\n return Math.floor(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $floor\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ln_exports = {};\n__export(ln_exports, {\n $ln: () => $ln\n});\nmodule.exports = __toCommonJS(ln_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $ln = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\") {\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$ln\");\n }\n return Math.log(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ln\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar log_exports = {};\n__export(log_exports, {\n $log: () => $log\n});\nmodule.exports = __toCommonJS(log_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $log = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isArray)(args) && args.length == 2) {\n let t_num = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n t_num &&= typeof v === \"number\";\n }\n if (t_num) return Math.log10(args[0]) / Math.log10(args[1]);\n }\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$log\", {\n size: 2,\n type: \"number\"\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $log\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar log10_exports = {};\n__export(log10_exports, {\n $log10: () => $log10\n});\nmodule.exports = __toCommonJS(log10_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $log10 = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n === \"number\") return Math.log10(n);\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$log10\");\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $log10\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mod_exports = {};\n__export(mod_exports, {\n $mod: () => $mod\n});\nmodule.exports = __toCommonJS(mod_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $mod = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n let invalid = !(0, import_util.isArray)(args) || args.length != 2;\n invalid ||= !args.every((v) => typeof v === \"number\");\n if (invalid)\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$mod\", {\n size: 2,\n type: \"number\"\n });\n return args[0] % args[1];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mod\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar multiply_exports = {};\n__export(multiply_exports, {\n $multiply: () => $multiply\n});\nmodule.exports = __toCommonJS(multiply_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $multiply = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$multiply expects array\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if (args.some(import_util.isNil)) return null;\n let res = 1;\n for (const n of args) {\n if (!(0, import_util.isNumber)(n))\n return (0, import_internal2.errExpectArray)(foe, \"$multiply\", { type: \"number\" });\n res *= n;\n }\n return res;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $multiply\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pow_exports = {};\n__export(pow_exports, {\n $pow: () => $pow\n});\nmodule.exports = __toCommonJS(pow_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $pow = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, \"$pow expects array(2)\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let t_num = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n t_num &&= (0, import_util.isNumber)(v);\n }\n if (!t_num) {\n return (0, import_internal2.errExpectArray)(foe, \"$pow\", {\n size: 2,\n type: \"number\"\n });\n }\n if (args[0] === 0 && args[1] < 0)\n (0, import_internal2.errInvalidArgs)(foe, \"$pow cannot raise 0 to a negative exponent\");\n return Math.pow(args[0], args[1]);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $pow\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n truncate: () => truncate\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../../../util\");\nvar import_internal = require(\"../_internal\");\nfunction truncate(num, precision, opts) {\n const { name, roundOff, failOnError } = opts;\n if ((0, import_util.isNil)(num)) return null;\n if (Number.isNaN(num) || Math.abs(num) === Infinity) return num;\n if (!(0, import_util.isNumber)(num)) {\n return (0, import_internal.errExpectNumber)(failOnError, `${name} arg1 `);\n }\n if (!(0, import_util.isInteger)(precision) || precision < -20 || precision > 100) {\n return (0, import_internal.errExpectNumber)(failOnError, `${name} arg2 `, {\n min: -20,\n max: 100,\n int: true\n });\n }\n const sign = Math.abs(num) === num ? 1 : -1;\n num = Math.abs(num);\n let result = Math.trunc(num);\n const decimals = parseFloat((num - result).toFixed(Math.abs(precision) + 1));\n if (precision === 0) {\n const firstDigit = Math.trunc(10 * decimals);\n if (roundOff && ((result & 1) === 1 && firstDigit >= 5 || firstDigit > 5)) {\n result++;\n }\n } else if (precision > 0) {\n const offset = Math.pow(10, precision);\n let remainder = Math.trunc(decimals * offset);\n const lastDigit = Math.trunc(decimals * offset * 10) % 10;\n if (roundOff && lastDigit > 5) {\n remainder += 1;\n }\n result = (result * offset + remainder) / offset;\n } else if (precision < 0) {\n const offset = Math.pow(10, -1 * precision);\n let excess = result % offset;\n result = Math.max(0, result - excess);\n if (roundOff && sign === -1) {\n while (excess > 10) {\n excess -= excess / 10;\n }\n if (result > 0 && excess >= 5) {\n result += offset;\n }\n }\n }\n return result * sign;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n truncate\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar round_exports = {};\n__export(round_exports, {\n $round: () => $round\n});\nmodule.exports = __toCommonJS(round_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst $round = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$round expects array(2)\");\n const [n, precision] = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_internal2.truncate)(n, precision ?? 0, {\n name: \"$round\",\n roundOff: true,\n failOnError: options.failOnError\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $round\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sigmoid_exports = {};\n__export(sigmoid_exports, {\n $sigmoid: () => $sigmoid\n});\nmodule.exports = __toCommonJS(sigmoid_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst PRECISION = 1e10;\nconst $sigmoid = (obj, expr, options) => {\n if ((0, import_util.isNil)(expr)) return null;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const { input, onNull } = (0, import_util.isObject)(args) ? args : { input: args };\n if ((0, import_util.isNil)(input)) return (0, import_util.isNumber)(onNull) ? onNull : null;\n if ((0, import_util.isNumber)(input)) {\n const result = 1 / (1 + Math.exp(-input));\n return Math.round(result * PRECISION) / PRECISION;\n }\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$sigmoid\");\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sigmoid\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sqrt_exports = {};\n__export(sqrt_exports, {\n $sqrt: () => $sqrt\n});\nmodule.exports = __toCommonJS(sqrt_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $sqrt = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n const skip = !options.failOnError;\n if ((0, import_util.isNil)(n)) return null;\n if (typeof n !== \"number\" || n < 0) {\n (0, import_util.assert)(skip, \"$sqrt expression must resolve to non-negative number.\");\n return null;\n }\n return Math.sqrt(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sqrt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar subtract_exports = {};\n__export(subtract_exports, {\n $subtract: () => $subtract\n});\nmodule.exports = __toCommonJS(subtract_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $subtract = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$subtract expects array(2)\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (args.some(import_util.isNil)) return null;\n const foe = options.failOnError;\n const [a, b] = args;\n if ((0, import_util.isDate)(a) && (0, import_util.isNumber)(b)) return new Date(+a - Math.round(b));\n if ((0, import_util.isDate)(a) && (0, import_util.isDate)(b)) return +a - +b;\n if (args.every((v) => typeof v === \"number\")) return a - b;\n if ((0, import_util.isNumber)(a) && (0, import_util.isDate)(b)) {\n return (0, import_internal2.errInvalidArgs)(foe, \"$subtract cannot subtract date from number\");\n }\n return (0, import_internal2.errExpectArray)(foe, \"$subtract\", {\n size: 2,\n type: \"number|date\"\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $subtract\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar trunc_exports = {};\n__export(trunc_exports, {\n $trunc: () => $trunc\n});\nmodule.exports = __toCommonJS(trunc_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst $trunc = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$trunc expects array(2)\");\n const [n, precision] = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_internal2.truncate)(n, precision ?? 0, {\n name: \"$trunc\",\n roundOff: false,\n failOnError: options.failOnError\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $trunc\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar arithmetic_exports = {};\nmodule.exports = __toCommonJS(arithmetic_exports);\n__reExport(arithmetic_exports, require(\"./abs\"), module.exports);\n__reExport(arithmetic_exports, require(\"./add\"), module.exports);\n__reExport(arithmetic_exports, require(\"./ceil\"), module.exports);\n__reExport(arithmetic_exports, require(\"./divide\"), module.exports);\n__reExport(arithmetic_exports, require(\"./exp\"), module.exports);\n__reExport(arithmetic_exports, require(\"./floor\"), module.exports);\n__reExport(arithmetic_exports, require(\"./ln\"), module.exports);\n__reExport(arithmetic_exports, require(\"./log\"), module.exports);\n__reExport(arithmetic_exports, require(\"./log10\"), module.exports);\n__reExport(arithmetic_exports, require(\"./mod\"), module.exports);\n__reExport(arithmetic_exports, require(\"./multiply\"), module.exports);\n__reExport(arithmetic_exports, require(\"./pow\"), module.exports);\n__reExport(arithmetic_exports, require(\"./round\"), module.exports);\n__reExport(arithmetic_exports, require(\"./sigmoid\"), module.exports);\n__reExport(arithmetic_exports, require(\"./sqrt\"), module.exports);\n__reExport(arithmetic_exports, require(\"./subtract\"), module.exports);\n__reExport(arithmetic_exports, require(\"./trunc\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./abs\"),\n ...require(\"./add\"),\n ...require(\"./ceil\"),\n ...require(\"./divide\"),\n ...require(\"./exp\"),\n ...require(\"./floor\"),\n ...require(\"./ln\"),\n ...require(\"./log\"),\n ...require(\"./log10\"),\n ...require(\"./mod\"),\n ...require(\"./multiply\"),\n ...require(\"./pow\"),\n ...require(\"./round\"),\n ...require(\"./sigmoid\"),\n ...require(\"./sqrt\"),\n ...require(\"./subtract\"),\n ...require(\"./trunc\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar arrayElemAt_exports = {};\n__export(arrayElemAt_exports, {\n $arrayElemAt: () => $arrayElemAt\n});\nmodule.exports = __toCommonJS(arrayElemAt_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$arrayElemAt\";\nconst $arrayElemAt = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, `${OP} expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (args.some(import_util.isNil)) return null;\n const foe = options.failOnError;\n const [arr, index] = args;\n if (!(0, import_util.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, `${OP} arg1 `);\n if (!(0, import_util.isInteger)(index))\n return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `, import_internal2.INT_OPTS.int);\n if (index < 0 && Math.abs(index) <= arr.length) {\n return arr[(index + arr.length) % arr.length];\n } else if (index >= 0 && index < arr.length) {\n return arr[index];\n }\n return void 0;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $arrayElemAt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar arrayToObject_exports = {};\n__export(arrayToObject_exports, {\n $arrayToObject: () => $arrayToObject\n});\nmodule.exports = __toCommonJS(arrayToObject_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst ERR_OPTS = {\n generic: { type: \"key-value pairs\" },\n array: { type: \"[k,v]\" },\n object: { type: \"{k,v}\" }\n};\nconst $arrayToObject = (obj, expr, options) => {\n const foe = options.failOnError;\n const arr = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr))\n return (0, import_internal2.errExpectArray)(foe, \"$arrayToObject\", ERR_OPTS.generic);\n let tag = 0;\n const newObj = {};\n for (const item of arr) {\n if ((0, import_util.isArray)(item)) {\n const val = (0, import_util.flatten)(item);\n if (!tag) tag = 1;\n if (tag !== 1) {\n return (0, import_internal2.errExpectArray)(foe, \"$arrayToObject\", ERR_OPTS.object);\n }\n const [k, v] = val;\n newObj[k] = v;\n } else if ((0, import_util.isObject)(item) && (0, import_util.has)(item, \"k\", \"v\")) {\n if (!tag) tag = 2;\n if (tag !== 2) {\n return (0, import_internal2.errExpectArray)(foe, \"$arrayToObject\", ERR_OPTS.array);\n }\n const { k, v } = item;\n newObj[k] = v;\n } else {\n return (0, import_internal2.errExpectArray)(foe, \"$arrayToObject\", ERR_OPTS.generic);\n }\n }\n return newObj;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $arrayToObject\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar concatArrays_exports = {};\n__export(concatArrays_exports, {\n $concatArrays: () => $concatArrays\n});\nmodule.exports = __toCommonJS(concatArrays_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $concatArrays = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if ((0, import_util.isNil)(args)) return null;\n if (!(0, import_util.isArray)(args)) return (0, import_internal2.errExpectArray)(foe, \"$concatArrays\");\n let size = 0;\n for (const arr of args) {\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, \"$concatArrays\");\n size += arr.length;\n }\n const result = new Array(size);\n let i = 0;\n for (const arr of args) for (const item of arr) result[i++] = item;\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $concatArrays\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar filter_exports = {};\n__export(filter_exports, {\n $filter: () => $filter\n});\nmodule.exports = __toCommonJS(filter_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $filter = (obj, expr, options) => {\n (0, import_internal2.assert)(\n (0, import_internal2.isObject)(expr) && (0, import_internal2.has)(expr, \"input\", \"cond\"),\n \"$filter expects object { input, as, cond, limit }\"\n );\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n const foe = options.failOnError;\n if ((0, import_internal2.isNil)(input)) return null;\n if (!(0, import_internal2.isArray)(input)) return (0, import_internal3.errExpectArray)(foe, \"$filter 'input'\");\n const limit = expr.limit ?? Math.max(input.length, 1);\n if (!(0, import_internal2.isInteger)(limit) || limit < 1)\n return (0, import_internal3.errExpectNumber)(foe, \"$filter 'limit'\", { min: 1, int: true });\n if (input.length === 0) return [];\n const copts = import_internal.ComputeOptions.init(options);\n const k = expr?.as || \"this\";\n const locals = { variables: {} };\n const res = [];\n for (let i = 0, j = 0; i < input.length && j < limit; i++) {\n locals.variables[k] = input[i];\n const cond = (0, import_internal.evalExpr)(obj, expr.cond, copts.update(locals));\n if ((0, import_internal2.truthy)(cond, options.useStrictMode)) {\n res.push(input[i]);\n j++;\n }\n }\n return res;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $filter\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar first_exports = {};\n__export(first_exports, {\n $first: () => $first\n});\nmodule.exports = __toCommonJS(first_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_first = require(\"../../accumulator/first\");\nvar import_internal2 = require(\"../_internal\");\nconst $first = (obj, expr, options) => {\n if ((0, import_util.isArray)(obj)) return (0, import_first.$first)(obj, expr, options);\n const arr = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr)) {\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$first\");\n }\n return (0, import_util.flatten)(arr)[0];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $first\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar firstN_exports = {};\n__export(firstN_exports, {\n $firstN: () => $firstN\n});\nmodule.exports = __toCommonJS(firstN_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_firstN = require(\"../../accumulator/firstN\");\nvar import_internal2 = require(\"../_internal\");\nconst $firstN = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"n\"),\n \"$firstN expects object { input, n }\"\n );\n if ((0, import_util.isArray)(obj)) return (0, import_firstN.$firstN)(obj, expr, options);\n const { input, n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$firstN 'input'\");\n return (0, import_firstN.$firstN)(input, { n, input: \"$$this\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $firstN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar in_exports = {};\n__export(in_exports, {\n $in: () => $in\n});\nmodule.exports = __toCommonJS(in_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $in = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, \"$in expects array(2)\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const [item, arr] = args;\n if (!(0, import_util.isArray)(arr))\n return (0, import_internal2.errInvalidArgs)(options.failOnError, \"$in arg2 \");\n for (const v of arr) if ((0, import_util.isEqual)(v, item)) return true;\n return false;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $in\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar indexOfArray_exports = {};\n__export(indexOfArray_exports, {\n $indexOfArray: () => $indexOfArray\n});\nmodule.exports = __toCommonJS(indexOfArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst OP = \"$indexOfArray\";\nconst $indexOfArray = (obj, expr, options) => {\n (0, import_internal2.assert)(\n (0, import_internal2.isArray)(expr) && expr.length > 1 && expr.length < 5,\n `${OP} expects array(4)`\n );\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n const arr = args[0];\n if ((0, import_internal2.isNil)(arr)) return null;\n if (!(0, import_internal2.isArray)(arr)) return (0, import_internal3.errExpectArray)(foe, `${OP} arg1 `);\n const search = args[1];\n const start = args[2] ?? 0;\n const end = args[3] ?? arr.length;\n if (!(0, import_internal2.isInteger)(start) || start < 0)\n return (0, import_internal3.errExpectNumber)(foe, `${OP} arg3 `, import_internal3.INT_OPTS.pos);\n if (!(0, import_internal2.isInteger)(end) || end < 0)\n return (0, import_internal3.errExpectNumber)(foe, `${OP} arg4 `, import_internal3.INT_OPTS.pos);\n if (start > end) return -1;\n const input = start > 0 || end < arr.length ? arr.slice(start, end) : arr;\n return input.findIndex((v) => (0, import_internal2.isEqual)(v, search)) + start;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $indexOfArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isArray_exports = {};\n__export(isArray_exports, {\n $isArray: () => $isArray\n});\nmodule.exports = __toCommonJS(isArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $isArray = (obj, expr, options) => {\n let input = expr;\n if ((0, import_util.isArray)(expr)) {\n (0, import_util.assert)(expr.length === 1, \"$isArray expects array(1)\");\n input = expr[0];\n }\n return (0, import_util.isArray)((0, import_internal.evalExpr)(obj, input, options));\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar last_exports = {};\n__export(last_exports, {\n $last: () => $last\n});\nmodule.exports = __toCommonJS(last_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_last = require(\"../../accumulator/last\");\nvar import_internal2 = require(\"../_internal\");\nconst $last = (obj, expr, options) => {\n if ((0, import_util.isArray)(obj)) return (0, import_last.$last)(obj, expr, options);\n const arr = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr) || arr.length === 0) {\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$last\", { size: 0 });\n }\n return (0, import_util.flatten)(arr)[arr.length - 1];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $last\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lastN_exports = {};\n__export(lastN_exports, {\n $lastN: () => $lastN\n});\nmodule.exports = __toCommonJS(lastN_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_lastN = require(\"../../accumulator/lastN\");\nvar import_internal2 = require(\"../_internal\");\nconst $lastN = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"n\"),\n \"$lastN expects object { input, n }\"\n );\n if ((0, import_util.isArray)(obj)) return (0, import_lastN.$lastN)(obj, expr, options);\n const { input, n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input)) {\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$lastN 'input'\");\n }\n return (0, import_lastN.$lastN)(input, { n, input: \"$$this\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lastN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar map_exports = {};\n__export(map_exports, {\n $map: () => $map\n});\nmodule.exports = __toCommonJS(map_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $map = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"in\"),\n \"$map expects object { input, as, in }\"\n );\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n const foe = options.failOnError;\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input)) return (0, import_internal2.errExpectArray)(foe, \"$map 'input'\");\n if (!(0, import_util.isNil)(expr.as) && !(0, import_util.isString)(expr.as))\n return (0, import_internal2.errExpectString)(foe, \"$map 'as'\");\n const copts = import_internal.ComputeOptions.init(options);\n const k = expr.as || \"this\";\n const locals = { variables: {} };\n return input.map((o) => {\n locals.variables[k] = o;\n return (0, import_internal.evalExpr)(obj, expr.in, copts.update(locals));\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $map\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar maxN_exports = {};\n__export(maxN_exports, {\n $maxN: () => $maxN\n});\nmodule.exports = __toCommonJS(maxN_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_maxN = require(\"../../accumulator/maxN\");\nvar import_internal2 = require(\"../_internal\");\nconst $maxN = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"n\"),\n \"$maxN expects object { input, n }\"\n );\n if ((0, import_util.isArray)(obj)) return (0, import_maxN.$maxN)(obj, expr, options);\n const { input, n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$maxN 'input'\");\n return (0, import_maxN.$maxN)(input, { n, input: \"$$this\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $maxN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar minN_exports = {};\n__export(minN_exports, {\n $minN: () => $minN\n});\nmodule.exports = __toCommonJS(minN_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_minN = require(\"../../accumulator/minN\");\nvar import_internal2 = require(\"../_internal\");\nconst $minN = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"n\"),\n \"$minN expects object { input, n }\"\n );\n if ((0, import_util.isArray)(obj)) return (0, import_minN.$minN)(obj, expr, options);\n const { input, n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$minN 'input'\");\n return (0, import_minN.$minN)(input, { n, input: \"$$this\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $minN\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar range_exports = {};\n__export(range_exports, {\n $range: () => $range\n});\nmodule.exports = __toCommonJS(range_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $range = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isArray)(expr) && expr.length > 1 && expr.length < 4,\n \"$range expects array(3)\"\n );\n const [start, end, arg3] = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n const step = arg3 ?? 1;\n if (!(0, import_util.isInteger)(start))\n return (0, import_internal2.errExpectNumber)(foe, `$range arg1 `, import_internal2.INT_OPTS.int);\n if (!(0, import_util.isInteger)(end))\n return (0, import_internal2.errExpectNumber)(foe, `$range arg2 `, import_internal2.INT_OPTS.int);\n if (!(0, import_util.isInteger)(step) || step === 0)\n return (0, import_internal2.errExpectNumber)(foe, `$range arg3 `, import_internal2.INT_OPTS.nzero);\n const result = new Array();\n let counter = start;\n while (counter < end && step > 0 || counter > end && step < 0) {\n result.push(counter);\n counter += step;\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $range\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar reduce_exports = {};\n__export(reduce_exports, {\n $reduce: () => $reduce\n});\nmodule.exports = __toCommonJS(reduce_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nfunction $reduce(obj, expr, options) {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"initialValue\", \"in\"),\n \"$reduce expects object { input, initialValue, in }\"\n );\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n const initialValue = (0, import_internal.evalExpr)(obj, expr.initialValue, options);\n const inExpr = expr[\"in\"];\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$reduce 'input'\");\n const copts = import_internal.ComputeOptions.init(options);\n const locals = { variables: { value: null } };\n let result = initialValue;\n for (let i = 0; i < input.length; i++) {\n locals.variables.value = result;\n result = (0, import_internal.evalExpr)(input[i], inExpr, copts.update(locals));\n }\n return result;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $reduce\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar reverseArray_exports = {};\n__export(reverseArray_exports, {\n $reverseArray: () => $reverseArray\n});\nmodule.exports = __toCommonJS(reverseArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $reverseArray = (obj, expr, options) => {\n const arr = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(arr)) return null;\n if (!(0, import_util.isArray)(arr))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$reverseArray\");\n return arr.slice().reverse();\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $reverseArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar size_exports = {};\n__export(size_exports, {\n $size: () => $size\n});\nmodule.exports = __toCommonJS(size_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $size = (obj, expr, options) => {\n const value = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(value)) return null;\n return (0, import_util.isArray)(value) ? value.length : (0, import_internal2.errExpectNumber)(options.failOnError, \"$size\");\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $size\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar slice_exports = {};\n__export(slice_exports, {\n $slice: () => $slice\n});\nmodule.exports = __toCommonJS(slice_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $slice = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isArray)(expr) && expr.length > 1 && expr.length < 4,\n \"$slice expects array(3)\"\n );\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const arr = args[0];\n let skip = args[1];\n let limit = args[2];\n if (!(0, import_util.isArray)(arr)) return (0, import_internal2.errExpectArray)(foe, \"$slice arg1 \");\n if (!(0, import_util.isInteger)(skip))\n return (0, import_internal2.errExpectNumber)(foe, \"$slice arg2 \", import_internal2.INT_OPTS.int);\n if (!(0, import_util.isNil)(limit) && !(0, import_util.isInteger)(limit))\n return (0, import_internal2.errExpectNumber)(foe, \"$slice arg3 \", import_internal2.INT_OPTS.int);\n if ((0, import_util.isNil)(limit)) {\n if (skip < 0) {\n skip = Math.max(0, arr.length + skip);\n } else {\n limit = skip;\n skip = 0;\n }\n } else {\n if (skip < 0) {\n skip = Math.max(0, arr.length + skip);\n }\n if (limit < 1) {\n return (0, import_internal2.errExpectNumber)(foe, \"$slice arg3 \", import_internal2.INT_OPTS.pos);\n }\n limit += skip;\n }\n return arr.slice(skip, limit);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $slice\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sortArray_exports = {};\n__export(sortArray_exports, {\n $sortArray: () => $sortArray\n});\nmodule.exports = __toCommonJS(sortArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_lazy = require(\"../../../lazy\");\nvar import_util = require(\"../../../util\");\nvar import_sort = require(\"../../pipeline/sort\");\nvar import_internal2 = require(\"../_internal\");\nconst $sortArray = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && \"input\" in expr && \"sortBy\" in expr,\n \"$sortArray expects object { input, sortBy }\"\n );\n const { input, sortBy } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n if (!(0, import_util.isArray)(input))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$sortArray 'input'\");\n if ((0, import_util.isObject)(sortBy)) {\n return (0, import_sort.$sort)((0, import_lazy.Lazy)(input), sortBy, options).collect();\n }\n const result = input.slice().sort(import_util.compare);\n if (sortBy === -1) result.reverse();\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sortArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar zip_exports = {};\n__export(zip_exports, {\n $zip: () => $zip\n});\nmodule.exports = __toCommonJS(zip_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $zip = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"inputs\"),\n \"$zip received invalid arguments\"\n );\n const inputs = (0, import_internal.evalExpr)(obj, expr.inputs, options);\n const defaults = (0, import_internal.evalExpr)(obj, expr.defaults, options) ?? [];\n const useLongestLength = expr.useLongestLength ?? false;\n const foe = options.failOnError;\n if ((0, import_util.isNil)(inputs)) return null;\n if (!(0, import_util.isArray)(inputs)) return (0, import_internal2.errExpectArray)(foe, \"$zip 'inputs'\");\n let invalid = 0;\n for (const elem of inputs) {\n if ((0, import_util.isNil)(elem)) return null;\n if (!(0, import_util.isArray)(elem)) invalid++;\n }\n if (invalid) return (0, import_internal2.errExpectArray)(foe, \"$zip elements of 'inputs'\");\n if (!(0, import_util.isBoolean)(useLongestLength))\n (0, import_internal2.errInvalidArgs)(foe, \"$zip 'useLongestLength' must be boolean\");\n if ((0, import_util.isArray)(defaults) && defaults.length > 0) {\n (0, import_util.assert)(\n useLongestLength && defaults.length === inputs.length,\n \"$zip 'useLongestLength' must be set to true to use 'defaults'\"\n );\n }\n let zipCount = 0;\n for (const arr of inputs) {\n zipCount = useLongestLength ? Math.max(zipCount, arr.length) : Math.min(zipCount || arr.length, arr.length);\n }\n const result = [];\n for (let i = 0; i < zipCount; i++) {\n const temp = inputs.map((val, index) => {\n return (0, import_util.isNil)(val[i]) ? defaults[index] ?? null : val[i];\n });\n result.push(temp);\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $zip\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar array_exports = {};\nmodule.exports = __toCommonJS(array_exports);\n__reExport(array_exports, require(\"./arrayElemAt\"), module.exports);\n__reExport(array_exports, require(\"./arrayToObject\"), module.exports);\n__reExport(array_exports, require(\"./concatArrays\"), module.exports);\n__reExport(array_exports, require(\"./filter\"), module.exports);\n__reExport(array_exports, require(\"./first\"), module.exports);\n__reExport(array_exports, require(\"./firstN\"), module.exports);\n__reExport(array_exports, require(\"./in\"), module.exports);\n__reExport(array_exports, require(\"./indexOfArray\"), module.exports);\n__reExport(array_exports, require(\"./isArray\"), module.exports);\n__reExport(array_exports, require(\"./last\"), module.exports);\n__reExport(array_exports, require(\"./lastN\"), module.exports);\n__reExport(array_exports, require(\"./map\"), module.exports);\n__reExport(array_exports, require(\"./maxN\"), module.exports);\n__reExport(array_exports, require(\"./minN\"), module.exports);\n__reExport(array_exports, require(\"./range\"), module.exports);\n__reExport(array_exports, require(\"./reduce\"), module.exports);\n__reExport(array_exports, require(\"./reverseArray\"), module.exports);\n__reExport(array_exports, require(\"./size\"), module.exports);\n__reExport(array_exports, require(\"./slice\"), module.exports);\n__reExport(array_exports, require(\"./sortArray\"), module.exports);\n__reExport(array_exports, require(\"./zip\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./arrayElemAt\"),\n ...require(\"./arrayToObject\"),\n ...require(\"./concatArrays\"),\n ...require(\"./filter\"),\n ...require(\"./first\"),\n ...require(\"./firstN\"),\n ...require(\"./in\"),\n ...require(\"./indexOfArray\"),\n ...require(\"./isArray\"),\n ...require(\"./last\"),\n ...require(\"./lastN\"),\n ...require(\"./map\"),\n ...require(\"./maxN\"),\n ...require(\"./minN\"),\n ...require(\"./range\"),\n ...require(\"./reduce\"),\n ...require(\"./reverseArray\"),\n ...require(\"./size\"),\n ...require(\"./slice\"),\n ...require(\"./sortArray\"),\n ...require(\"./zip\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n processBitwise: () => processBitwise\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nfunction processBitwise(obj, expr, options, operator, fn) {\n (0, import_util.assert)((0, import_util.isArray)(expr), `${operator} expects array as argument`);\n const nums = (0, import_internal.evalExpr)(obj, expr, options);\n let t_num = true;\n for (const v of nums) {\n if ((0, import_util.isNil)(v)) return null;\n t_num &&= (0, import_util.isInteger)(v);\n }\n if (t_num) return fn(nums);\n return (0, import_internal2.errInvalidArgs)(\n options.failOnError,\n `${operator} array elements must resolve to integers`\n );\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n processBitwise\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitAnd_exports = {};\n__export(bitAnd_exports, {\n $bitAnd: () => $bitAnd\n});\nmodule.exports = __toCommonJS(bitAnd_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitAnd = (obj, expr, options) => (0, import_internal.processBitwise)(\n obj,\n expr,\n options,\n \"$bitAnd\",\n (nums) => nums.reduce((a, b) => a & b, -1)\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitAnd\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitNot_exports = {};\n__export(bitNot_exports, {\n $bitNot: () => $bitNot\n});\nmodule.exports = __toCommonJS(bitNot_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $bitNot = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(n)) return null;\n if (!(0, import_util.isInteger)(n))\n return (0, import_internal2.errExpectNumber)(options.failOnError, \"$bitNot\", import_internal2.INT_OPTS.int);\n return ~n;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitNot\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitOr_exports = {};\n__export(bitOr_exports, {\n $bitOr: () => $bitOr\n});\nmodule.exports = __toCommonJS(bitOr_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitOr = (obj, expr, options) => (0, import_internal.processBitwise)(\n obj,\n expr,\n options,\n \"$bitOr\",\n (nums) => nums.reduce((a, b) => a | b, 0)\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitOr\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitXor_exports = {};\n__export(bitXor_exports, {\n $bitXor: () => $bitXor\n});\nmodule.exports = __toCommonJS(bitXor_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitXor = (obj, expr, options) => (0, import_internal.processBitwise)(\n obj,\n expr,\n options,\n \"$bitXor\",\n (nums) => nums.reduce((a, b) => a ^ b, 0)\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitXor\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitwise_exports = {};\nmodule.exports = __toCommonJS(bitwise_exports);\n__reExport(bitwise_exports, require(\"./bitAnd\"), module.exports);\n__reExport(bitwise_exports, require(\"./bitNot\"), module.exports);\n__reExport(bitwise_exports, require(\"./bitOr\"), module.exports);\n__reExport(bitwise_exports, require(\"./bitXor\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./bitAnd\"),\n ...require(\"./bitNot\"),\n ...require(\"./bitOr\"),\n ...require(\"./bitXor\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar and_exports = {};\n__export(and_exports, {\n $and: () => $and\n});\nmodule.exports = __toCommonJS(and_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nconst $and = (obj, expr, options) => {\n (0, import_internal2.assert)((0, import_internal2.isArray)(expr), \"$and expects array\");\n const mode = options.useStrictMode;\n return expr.every((e) => (0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, e, options), mode));\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $and\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar not_exports = {};\n__export(not_exports, {\n $not: () => $not\n});\nmodule.exports = __toCommonJS(not_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $not = (obj, expr, options) => {\n const booleanExpr = (0, import_util.ensureArray)(expr);\n if (booleanExpr.length === 0) return false;\n if (booleanExpr.length > 1)\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$not\", { size: 1 });\n return !(0, import_internal.evalExpr)(obj, booleanExpr[0], options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $not\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar or_exports = {};\n__export(or_exports, {\n $or: () => $or\n});\nmodule.exports = __toCommonJS(or_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nconst $or = (obj, expr, options) => {\n (0, import_internal2.assert)((0, import_internal2.isArray)(expr), \"$or expects array of expressions\");\n const strict = options.useStrictMode;\n for (const v of expr)\n if ((0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, v, options), strict)) return true;\n return false;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $or\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar boolean_exports = {};\nmodule.exports = __toCommonJS(boolean_exports);\n__reExport(boolean_exports, require(\"./and\"), module.exports);\n__reExport(boolean_exports, require(\"./not\"), module.exports);\n__reExport(boolean_exports, require(\"./or\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./and\"),\n ...require(\"./not\"),\n ...require(\"./or\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cmp_exports = {};\n__export(cmp_exports, {\n $cmp: () => $cmp\n});\nmodule.exports = __toCommonJS(cmp_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $cmp = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, \"$cmp expects array(2)\");\n const [a, b] = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_util.compare)(a, b);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $cmp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar limit_exports = {};\n__export(limit_exports, {\n $limit: () => $limit\n});\nmodule.exports = __toCommonJS(limit_exports);\nfunction $limit(coll, expr, _options) {\n return coll.take(expr);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $limit\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar documents_exports = {};\n__export(documents_exports, {\n $documents: () => $documents\n});\nmodule.exports = __toCommonJS(documents_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $documents(_, expr, options) {\n const docs = (0, import_internal.evalExpr)(null, expr, options);\n (0, import_util.assert)((0, import_util.isArray)(docs), \"$documents expression must resolve to an array.\");\n const iter = (0, import_lazy.Lazy)(docs);\n const mode = options.processingMode;\n return mode & import_internal.ProcessingMode.CLONE_ALL ? iter.map((o) => (0, import_util.cloneDeep)(o)) : iter;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $documents\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n filterDocumentsStage: () => filterDocumentsStage,\n resolveCollection: () => resolveCollection,\n validateProjection: () => validateProjection\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"../../util/_internal\");\nvar import_documents = require(\"./documents\");\nconst EMPTY = (0, import_lazy.Lazy)([]);\nfunction filterDocumentsStage(pipeline, options) {\n if (!pipeline) return {};\n const docs = pipeline[0]?.$documents;\n if (!docs) return { pipeline };\n return {\n documents: (0, import_documents.$documents)(EMPTY, docs, options).collect(),\n pipeline: pipeline.slice(1)\n };\n}\nfunction validateProjection(expr, options, isRoot = true) {\n const res = {\n exclusions: [],\n inclusions: [],\n positional: 0\n };\n const keys = Object.keys(expr);\n (0, import_internal.assert)(keys.length, \"Invalid empty sub-projection\");\n const idKey = options?.idKey;\n let idKeyExcluded = false;\n for (const k of keys) {\n if (k.startsWith(\"$\")) {\n (0, import_internal.assert)(\n !isRoot && keys.length === 1,\n `FieldPath field names may not start with '$', given '${k}'.`\n );\n return res;\n }\n if (k.endsWith(\".$\")) res.positional++;\n const v = expr[k];\n if (v === false || (0, import_util.isNumber)(v) && v === 0) {\n if (k === idKey) {\n idKeyExcluded = true;\n } else res.exclusions.push(k);\n } else if (!(0, import_util.isObject)(v)) {\n res.inclusions.push(k);\n } else {\n const meta = validateProjection(v, options, false);\n if (!meta.inclusions.length && !meta.exclusions.length) {\n if (!res.inclusions.includes(k)) res.inclusions.push(k);\n } else {\n for (const n of meta.exclusions) res.exclusions.push(`${k}.${n}`);\n for (const n of meta.inclusions) res.inclusions.push(`${k}.${n}`);\n }\n res.positional += meta.positional;\n }\n (0, import_internal.assert)(\n !(res.exclusions.length && res.inclusions.length),\n \"Cannot do exclusion and inclusion in projection.\"\n );\n (0, import_internal.assert)(\n res.positional <= 1,\n \"Cannot specify more than one positional projection.\"\n );\n }\n if (idKeyExcluded) {\n res.exclusions.push(idKey);\n }\n if (isRoot) {\n const p = new import_internal.PathValidator();\n for (const k of res.exclusions) (0, import_internal.assert)(p.add(k), `Path collision at ${k}.`);\n for (const k of res.inclusions) (0, import_internal.assert)(p.add(k), `Path collision at ${k}.`);\n res.exclusions.sort();\n res.inclusions.sort();\n }\n return res;\n}\nfunction resolveCollection(op, expr, options) {\n if ((0, import_internal.isString)(expr)) {\n (0, import_internal.assert)(\n options.collectionResolver,\n `${op} requires 'collectionResolver' option to resolve named collection`\n );\n }\n const coll = (0, import_internal.isString)(expr) ? options.collectionResolver(expr) : expr;\n (0, import_internal.assert)((0, import_internal.isArray)(coll), `${op} could not resolve input collection`);\n return coll;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n filterDocumentsStage,\n resolveCollection,\n validateProjection\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar project_exports = {};\n__export(project_exports, {\n $project: () => $project\n});\nmodule.exports = __toCommonJS(project_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_internal2 = require(\"../../util/_internal\");\nvar import_internal3 = require(\"./_internal\");\nconst OP = \"$project\";\nfunction $project(coll, expr, options) {\n if ((0, import_internal2.isEmpty)(expr)) return coll;\n const meta = (0, import_internal3.validateProjection)(expr, options);\n const handler = createHandler(expr, import_internal.ComputeOptions.init(options), meta);\n return coll.map(handler);\n}\nfunction createHandler(expr, options, meta) {\n const idKey = options.idKey;\n const { exclusions, inclusions } = meta;\n const handlers = {};\n const resolveOpts = {\n preserveMissing: true\n };\n for (const k of exclusions) {\n handlers[k] = (t, _) => {\n (0, import_internal2.removeValue)(t, k, { descendArray: true });\n };\n }\n for (const selector of inclusions) {\n const v = (0, import_internal2.resolve)(expr, selector) ?? expr[selector];\n if (selector.endsWith(\".$\") && v === 1) {\n const cond = options?.local?.condition ?? {};\n (0, import_internal2.assert)(cond, `${OP}: positional operator '.$' requires array condition.`);\n const field = selector.slice(0, -2);\n handlers[field] = getPositionalFilter(field, cond, options);\n continue;\n }\n if ((0, import_internal2.isArray)(v)) {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const newVal = v.map((e) => (0, import_internal.evalExpr)(o, e, options) ?? null);\n (0, import_internal2.setValue)(t, selector, newVal);\n };\n } else if ((0, import_internal2.isNumber)(v) || v === true) {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const extractedVal = (0, import_internal2.resolveGraph)(o, selector, resolveOpts);\n mergeInto(t, extractedVal);\n };\n } else if (!(0, import_internal2.isObject)(v)) {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const newVal = (0, import_internal.evalExpr)(o, v, options);\n (0, import_internal2.setValue)(t, selector, newVal);\n };\n } else {\n const opKeys = Object.keys(v);\n (0, import_internal2.assert)(\n opKeys.length === 1 && (0, import_internal2.isOperator)(opKeys[0]),\n \"Not a valid operator\"\n );\n const operator = opKeys[0];\n const opExpr = v[operator];\n const fn = options.context.getOperator(import_internal.OpType.PROJECTION, operator);\n const foundSlice = operator === \"$slice\";\n if (!fn || foundSlice && !(0, import_internal2.ensureArray)(opExpr).every(import_internal2.isNumber)) {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const newval = (0, import_internal.evalExpr)(o, v, options);\n (0, import_internal2.setValue)(t, selector, newval);\n };\n } else {\n handlers[selector] = (t, o) => {\n options.update({ root: o });\n const newval = fn(o, opExpr, selector, options);\n (0, import_internal2.setValue)(t, selector, newval);\n };\n }\n }\n }\n const onlyIdKeyExcluded = exclusions.length === 1 && exclusions.includes(idKey);\n const noIdKeyExcluded = !exclusions.includes(idKey);\n const noInclusions = !inclusions.length;\n const allKeysIncluded = noInclusions && onlyIdKeyExcluded || noInclusions && exclusions.length && !onlyIdKeyExcluded;\n return (o) => {\n const newObj = {};\n if (allKeysIncluded) Object.assign(newObj, o);\n for (const k in handlers) {\n handlers[k](newObj, o);\n }\n if (!noInclusions) (0, import_internal2.filterMissing)(newObj);\n if (noIdKeyExcluded && !(0, import_internal2.has)(newObj, idKey) && (0, import_internal2.has)(o, idKey)) {\n newObj[idKey] = (0, import_internal2.resolve)(o, idKey);\n }\n return newObj;\n };\n}\nconst findMatches = (o, key, leaf, pred) => {\n let arr = (0, import_internal2.resolve)(o, key);\n if (!(0, import_internal2.isArray)(arr)) arr = (0, import_internal2.resolve)(arr, leaf);\n (0, import_internal2.assert)((0, import_internal2.isArray)(arr), `${OP}: field '${key}' must resolve to array`);\n const matches = [];\n for (let i = 0; i < arr.length; i++) {\n if (pred({ [leaf]: [arr[i]] })) matches.push(i);\n }\n return matches;\n};\nconst complement = (p) => ((e) => !p(e));\nconst COMPOUND_OPS = { $and: 1, $or: 1, $nor: 1 };\nfunction getPositionalFilter(field, condition, options) {\n const stack = Object.entries(condition).slice();\n const selectors = {\n $and: [],\n $or: []\n };\n for (let i = 0; i < stack.length; i++) {\n const [key, val, op] = stack[i];\n if (key === field || key.startsWith(field + \".\")) {\n const normalizedExpr = (0, import_internal2.normalize)(val);\n const operator = Object.keys(normalizedExpr)[0];\n const expr = normalizedExpr[operator];\n const fn = options.context.getOperator(\n import_internal.OpType.QUERY,\n operator\n );\n const leaf2 = key.substring(key.lastIndexOf(\".\") + 1);\n const pred = fn(leaf2, expr, options);\n if (!op || op === \"$and\") {\n selectors.$and.push([key, pred, leaf2]);\n } else if (op === \"$nor\") {\n selectors.$and.push([key, complement(pred), leaf2]);\n } else if (op === \"$or\") {\n selectors.$or.push([key, pred, leaf2]);\n }\n } else if ((0, import_internal2.isOperator)(key)) {\n (0, import_internal2.assert)(\n !!COMPOUND_OPS[key],\n `${OP}: '${key}' is not allowed in this context`\n );\n for (const item of val) {\n for (const k of Object.keys(item)) stack.push([k, item[k], key]);\n }\n }\n }\n const sep = field.lastIndexOf(\".\");\n const parent = field.substring(0, sep) || field;\n const leaf = field.substring(sep + 1);\n return (t, o) => {\n const matches = [];\n for (const [key, pred, leaf2] of selectors.$and) {\n matches.push(findMatches(o, key, leaf2, pred));\n }\n if (selectors.$or.length) {\n const orMatches = [];\n for (const [key, pred, leaf2] of selectors.$or) {\n orMatches.push(...findMatches(o, key, leaf2, pred));\n }\n matches.push((0, import_internal2.unique)(orMatches));\n }\n const i = (0, import_internal2.intersection)(matches).sort()[0];\n let first = (0, import_internal2.resolve)(o, field)[i];\n if (parent != leaf && !(0, import_internal2.isObject)(first)) {\n first = { [leaf]: first };\n }\n (0, import_internal2.setValue)(t, parent, [first]);\n };\n}\nfunction mergeInto(target, input) {\n if (target === import_internal2.MISSING || (0, import_internal2.isNil)(target)) return input;\n if ((0, import_internal2.isNil)(input)) return target;\n const out = target;\n const src = input;\n for (const k of Object.keys(input)) {\n out[k] = mergeInto(out[k], src[k]);\n }\n return out;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $project\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar skip_exports = {};\n__export(skip_exports, {\n $skip: () => $skip\n});\nmodule.exports = __toCommonJS(skip_exports);\nvar import_util = require(\"../../util\");\nfunction $skip(coll, expr, _options) {\n (0, import_util.assert)(expr >= 0, \"$skip value must be a non-negative integer\");\n return coll.drop(expr);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $skip\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cursor_exports = {};\n__export(cursor_exports, {\n Cursor: () => Cursor\n});\nmodule.exports = __toCommonJS(cursor_exports);\nvar import_internal = require(\"./core/_internal\");\nvar import_lazy = require(\"./lazy\");\nvar import_limit = require(\"./operators/pipeline/limit\");\nvar import_project = require(\"./operators/pipeline/project\");\nvar import_skip = require(\"./operators/pipeline/skip\");\nvar import_sort = require(\"./operators/pipeline/sort\");\nvar import_util = require(\"./util\");\nconst OPERATORS = { $sort: import_sort.$sort, $skip: import_skip.$skip, $limit: import_limit.$limit };\nclass Cursor {\n #source;\n #predicate;\n #projection;\n #options;\n #operators = {};\n #result = null;\n #buffer = [];\n /**\n * Creates an instance of the Cursor class.\n *\n * @param source - The source of data to be iterated over.\n * @param predicate - A function or condition to filter the data.\n * @param projection - An object specifying the fields to include or exclude in the result.\n * @param options - Optional settings to customize the behavior of the cursor.\n */\n constructor(source, predicate, projection, options) {\n this.#source = source;\n this.#predicate = predicate;\n this.#projection = projection;\n this.#options = options;\n }\n /** Returns the iterator from running the query */\n fetch() {\n if (this.#result) return this.#result;\n this.#result = (0, import_lazy.Lazy)(this.#source).filter(this.#predicate);\n const mode = this.#options.processingMode;\n if (mode & import_internal.ProcessingMode.CLONE_INPUT) this.#result.map((o) => (0, import_util.cloneDeep)(o));\n for (const op of Object.keys(OPERATORS)) {\n if ((0, import_util.has)(this.#operators, op)) {\n const f = OPERATORS[op];\n this.#result = f(this.#result, this.#operators[op], this.#options);\n }\n }\n if (Object.keys(this.#projection).length) {\n this.#result = (0, import_project.$project)(this.#result, this.#projection, this.#options);\n }\n if (mode & import_internal.ProcessingMode.CLONE_OUTPUT) this.#result.map((o) => (0, import_util.cloneDeep)(o));\n return this.#result;\n }\n /** Returns an iterator with the buffered data included */\n fetchAll() {\n const buffered = (0, import_lazy.Lazy)(Array.from(this.#buffer));\n this.#buffer.length = 0;\n return (0, import_lazy.concat)(buffered, this.fetch());\n }\n /**\n * Return remaining objects in the cursor as an array. This method exhausts the cursor\n * @returns {Array}\n */\n all() {\n return this.fetchAll().collect();\n }\n /**\n * Returns a cursor that begins returning results only after passing or skipping a number of documents.\n * @param {Number} n the number of results to skip.\n * @return {Cursor} Returns the cursor, so you can chain this call.\n */\n skip(n) {\n this.#operators[\"$skip\"] = n;\n return this;\n }\n /**\n * Limits the number of items returned by the cursor.\n *\n * @param n - The maximum number of items to return.\n * @returns The current cursor instance for chaining.\n */\n limit(n) {\n this.#operators[\"$limit\"] = n;\n return this;\n }\n /**\n * Returns results ordered according to a sort specification.\n * @param {AnyObject} modifier an object of key and values specifying the sort order. 1 for ascending and -1 for descending\n * @return {Cursor} Returns the cursor, so you can chain this call.\n */\n sort(modifier) {\n this.#operators[\"$sort\"] = modifier;\n return this;\n }\n /**\n * Sets the collation options for the cursor.\n * Collation allows users to specify language-specific rules for string comparison,\n * such as case sensitivity and accent marks.\n *\n * @param spec - The collation specification to apply.\n * @returns The current cursor instance for chaining.\n */\n collation(spec) {\n this.#options = { ...this.#options, collation: spec };\n return this;\n }\n /**\n * Retrieves the next item in the cursor.\n */\n next() {\n if (this.#buffer.length > 0) {\n return this.#buffer.pop();\n }\n const o = this.fetch().next();\n if (o.done) return void 0;\n return o.value;\n }\n /**\n * Determines if there are more elements available in the cursor.\n *\n * @returns {boolean} `true` if there are more elements to iterate over, otherwise `false`.\n */\n hasNext() {\n if (this.#buffer.length > 0) return true;\n const o = this.fetch().next();\n if (o.done) return false;\n this.#buffer.push(o.value);\n return true;\n }\n /**\n * Returns an iterator for the cursor, allowing it to be used in `for...of` loops.\n * The iterator fetches all the results from the cursor.\n *\n * @returns {Iterator} An iterator over the fetched results.\n */\n [Symbol.iterator]() {\n return this.fetchAll();\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Cursor\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar query_exports = {};\n__export(query_exports, {\n Query: () => Query\n});\nmodule.exports = __toCommonJS(query_exports);\nvar import_internal = require(\"./core/_internal\");\nvar import_cursor = require(\"./cursor\");\nvar import_util = require(\"./util\");\nconst TOP_LEVEL_OPS = /* @__PURE__ */ new Set([\"$and\", \"$or\", \"$nor\", \"$expr\", \"$jsonSchema\"]);\nclass Query {\n #compiled;\n #condition;\n #options;\n /**\n * Creates an instance of the query with the specified condition and options.\n * This object is preloaded with all query and projection operators.\n *\n * @param condition - The query condition object used to define the criteria for matching documents.\n * @param options - Optional configuration settings to customize the query behavior.\n */\n constructor(condition, options) {\n this.#condition = (0, import_util.cloneDeep)(condition);\n this.#options = import_internal.ComputeOptions.init(options).update({\n condition\n });\n this.#compiled = [];\n this.compile();\n }\n compile() {\n (0, import_util.assert)(\n (0, import_util.isObject)(this.#condition),\n `query criteria must be an object: ${JSON.stringify(this.#condition)}`\n );\n const whereOperator = {};\n for (const field of Object.keys(this.#condition)) {\n const expr = this.#condition[field];\n if (\"$where\" === field) {\n (0, import_util.assert)(\n this.#options.scriptEnabled,\n \"$where operator requires 'scriptEnabled' option to be true.\"\n );\n Object.assign(whereOperator, { field, expr });\n } else if (TOP_LEVEL_OPS.has(field)) {\n this.processOperator(field, field, expr);\n } else {\n (0, import_util.assert)(!(0, import_util.isOperator)(field), `unknown top level operator: ${field}`);\n const normalizedExpr = (0, import_util.normalize)(expr);\n for (const operator of Object.keys(normalizedExpr)) {\n this.processOperator(field, operator, normalizedExpr[operator]);\n }\n }\n if (whereOperator.field) {\n this.processOperator(\n whereOperator.field,\n whereOperator.field,\n whereOperator.expr\n );\n }\n }\n }\n processOperator(field, operator, value) {\n const fn = this.#options.context.getOperator(\n import_internal.OpType.QUERY,\n operator\n );\n (0, import_util.assert)(!!fn, `unknown query operator ${operator}`);\n this.#compiled.push(fn(field, value, this.#options));\n }\n /**\n * Tests whether the given object satisfies all compiled predicates.\n *\n * @template T - The type of the object to test.\n * @param obj - The object to be tested against the compiled predicates.\n * @returns `true` if the object satisfies all predicates, otherwise `false`.\n */\n test(obj) {\n return this.#compiled.every((p) => p(obj));\n }\n /**\n * Returns a cursor for iterating over the items in the given collection that match the query criteria.\n *\n * @typeParam T - The type of the items in the resulting cursor.\n * @param collection - The source collection to search through.\n * @param projection - An optional object specifying fields to include or exclude\n * in the returned items.\n * @returns A `Cursor` instance for iterating over the matching items.\n */\n find(collection, projection) {\n return new import_cursor.Cursor(\n collection,\n (o) => this.test(o),\n projection || {},\n this.#options\n );\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Query\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar predicates_exports = {};\n__export(predicates_exports, {\n $all: () => $all,\n $elemMatch: () => $elemMatch,\n $eq: () => $eq,\n $gt: () => $gt,\n $gte: () => $gte,\n $in: () => $in,\n $lt: () => $lt,\n $lte: () => $lte,\n $mod: () => $mod,\n $ne: () => $ne,\n $nin: () => $nin,\n $regex: () => $regex,\n $size: () => $size,\n $type: () => $type,\n processExpression: () => processExpression,\n processQuery: () => processQuery\n});\nmodule.exports = __toCommonJS(predicates_exports);\nvar import_internal = require(\"../core/_internal\");\nvar import_query = require(\"../query\");\nvar import_internal2 = require(\"../util/_internal\");\nfunction elemMatchPredicate(criteria, options) {\n let format = (x) => x;\n let wrap = true;\n for (const k of Object.keys(criteria)) {\n wrap &&= (0, import_internal2.isOperator)(k) && \"$and\" !== k && \"$or\" !== k && \"$nor\" !== k;\n if (!wrap) break;\n }\n if (wrap) {\n criteria = { field: criteria };\n format = (x) => ({ field: x });\n }\n const q = new import_query.Query(criteria, options);\n return (v) => q.test(format(v));\n}\nfunction processQuery(selector, value, options, predicate) {\n const pathArray = selector.split(\".\");\n const depth = Math.max(1, pathArray.length - 1);\n const copts = import_internal.ComputeOptions.init(options).update({ depth });\n const opts = { unwrapArray: true, pathArray };\n if (predicate === $elemMatch) {\n value = elemMatchPredicate(value, options);\n }\n return (o) => {\n const lhs = (0, import_internal2.resolve)(o, selector, opts);\n return predicate(lhs, value, copts);\n };\n}\nfunction processExpression(obj, expr, options, predicate) {\n (0, import_internal2.assert)(\n (0, import_internal2.isArray)(expr) && expr.length === 2,\n `${predicate.name} expects array(2)`\n );\n const [lhs, rhs] = (0, import_internal.evalExpr)(obj, expr, options);\n return predicate(lhs, rhs, options);\n}\nfunction $eq(a, b, options) {\n if ((0, import_internal2.isEqual)(a, b)) return true;\n if ((0, import_internal2.isNil)(a) && (0, import_internal2.isNil)(b)) return true;\n if ((0, import_internal2.isArray)(a)) {\n const depth = options?.local?.depth ?? 1;\n return a.some((v) => (0, import_internal2.isEqual)(v, b)) || (0, import_internal2.flatten)(a, depth).some((v) => (0, import_internal2.isEqual)(v, b));\n }\n return false;\n}\nfunction $ne(a, b, options) {\n return !$eq(a, b, options);\n}\nfunction $in(a, b, _options) {\n if ((0, import_internal2.isNil)(a)) return b.some((v) => v === null);\n return (0, import_internal2.intersection)([(0, import_internal2.ensureArray)(a), b]).length > 0;\n}\nfunction $nin(a, b, options) {\n return !$in(a, b, options);\n}\nfunction $lt(a, b, _options) {\n return compare(a, b, (x, y) => (0, import_internal2.compare)(x, y) < 0);\n}\nfunction $lte(a, b, _options) {\n return compare(a, b, (x, y) => (0, import_internal2.compare)(x, y) <= 0);\n}\nfunction $gt(a, b, _options) {\n return compare(a, b, (x, y) => (0, import_internal2.compare)(x, y) > 0);\n}\nfunction $gte(a, b, _options) {\n return compare(a, b, (x, y) => (0, import_internal2.compare)(x, y) >= 0);\n}\nfunction $mod(a, b, _options) {\n return (0, import_internal2.ensureArray)(a).some(\n ((x) => b.length === 2 && x % b[0] === b[1])\n );\n}\nfunction $regex(a, b, options) {\n const lhs = (0, import_internal2.ensureArray)(a);\n const match = (x) => (0, import_internal2.isString)(x) && (0, import_internal2.truthy)(b.exec(x), options?.useStrictMode);\n return lhs.some(match) || (0, import_internal2.flatten)(lhs, 1).some(match);\n}\nfunction $all(values, rhs, options) {\n if (!(0, import_internal2.isArray)(values) || !(0, import_internal2.isArray)(rhs) || !values.length || !rhs.length) {\n return false;\n }\n let matched = true;\n for (const expr of rhs) {\n if (!matched) break;\n if ((0, import_internal2.isObject)(expr) && Object.keys(expr)[0] === \"$elemMatch\") {\n const criteria = expr[\"$elemMatch\"];\n const pred = elemMatchPredicate(criteria, options);\n matched = $elemMatch(values, pred, options);\n } else if ((0, import_internal2.isRegExp)(expr)) {\n matched = values.some((s) => (0, import_internal2.isString)(s) && expr.test(s));\n } else {\n matched = values.some((v) => (0, import_internal2.isEqual)(expr, v));\n }\n }\n return matched;\n}\nfunction $size(a, b, _options) {\n return Array.isArray(a) && a.length === b;\n}\nfunction $elemMatch(a, b, _options) {\n if ((0, import_internal2.isArray)(a) && !(0, import_internal2.isEmpty)(a)) {\n for (let i = 0, len = a.length; i < len; i++) if (b(a[i])) return true;\n }\n return false;\n}\nconst isNull = (a) => a === null;\nconst compareFuncs = {\n array: import_internal2.isArray,\n boolean: import_internal2.isBoolean,\n bool: import_internal2.isBoolean,\n date: import_internal2.isDate,\n number: import_internal2.isNumber,\n int: import_internal2.isNumber,\n long: import_internal2.isNumber,\n double: import_internal2.isNumber,\n decimal: import_internal2.isNumber,\n null: isNull,\n object: import_internal2.isObject,\n regexp: import_internal2.isRegExp,\n regex: import_internal2.isRegExp,\n string: import_internal2.isString,\n // added for completeness\n undefined: import_internal2.isNil,\n // deprecated\n // Mongo identifiers\n 1: import_internal2.isNumber,\n //double\n 2: import_internal2.isString,\n 3: import_internal2.isObject,\n 4: import_internal2.isArray,\n 6: import_internal2.isNil,\n // deprecated\n 8: import_internal2.isBoolean,\n 9: import_internal2.isDate,\n 10: isNull,\n 11: import_internal2.isRegExp,\n 16: import_internal2.isNumber,\n //int\n 18: import_internal2.isNumber,\n //long\n 19: import_internal2.isNumber\n //decimal\n};\nfunction compareType(a, b, _) {\n const f = compareFuncs[b];\n return f ? f(a) : false;\n}\nfunction $type(a, b, options) {\n return (0, import_internal2.isArray)(b) ? b.findIndex((t) => compareType(a, t, options)) >= 0 : compareType(a, b, options);\n}\nfunction compare(a, b, f) {\n for (const v of (0, import_internal2.ensureArray)(a)) {\n if ((0, import_internal2.typeOf)(v) === (0, import_internal2.typeOf)(b) && f(v, b)) return true;\n }\n return false;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $all,\n $elemMatch,\n $eq,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $mod,\n $ne,\n $nin,\n $regex,\n $size,\n $type,\n processExpression,\n processQuery\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar eq_exports = {};\n__export(eq_exports, {\n $eq: () => $eq\n});\nmodule.exports = __toCommonJS(eq_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $eq = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$eq);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $eq\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar gt_exports = {};\n__export(gt_exports, {\n $gt: () => $gt\n});\nmodule.exports = __toCommonJS(gt_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $gt = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$gt);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $gt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar gte_exports = {};\n__export(gte_exports, {\n $gte: () => $gte\n});\nmodule.exports = __toCommonJS(gte_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $gte = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$gte);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $gte\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lt_exports = {};\n__export(lt_exports, {\n $lt: () => $lt\n});\nmodule.exports = __toCommonJS(lt_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $lt = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$lt);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lte_exports = {};\n__export(lte_exports, {\n $lte: () => $lte\n});\nmodule.exports = __toCommonJS(lte_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $lte = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$lte);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lte\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ne_exports = {};\n__export(ne_exports, {\n $ne: () => $ne\n});\nmodule.exports = __toCommonJS(ne_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $ne = (obj, expr, options) => (0, import_predicates.processExpression)(obj, expr, options, import_predicates.$ne);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ne\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar comparison_exports = {};\nmodule.exports = __toCommonJS(comparison_exports);\n__reExport(comparison_exports, require(\"./cmp\"), module.exports);\n__reExport(comparison_exports, require(\"./eq\"), module.exports);\n__reExport(comparison_exports, require(\"./gt\"), module.exports);\n__reExport(comparison_exports, require(\"./gte\"), module.exports);\n__reExport(comparison_exports, require(\"./lt\"), module.exports);\n__reExport(comparison_exports, require(\"./lte\"), module.exports);\n__reExport(comparison_exports, require(\"./ne\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./cmp\"),\n ...require(\"./eq\"),\n ...require(\"./gt\"),\n ...require(\"./gte\"),\n ...require(\"./lt\"),\n ...require(\"./lte\"),\n ...require(\"./ne\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cond_exports = {};\n__export(cond_exports, {\n $cond: () => $cond\n});\nmodule.exports = __toCommonJS(cond_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nconst err = \"$cond expects array(3) or object with 'if-then-else' expressions\";\nconst $cond = (obj, expr, options) => {\n let ifExpr;\n let thenExpr;\n let elseExpr;\n if ((0, import_internal2.isArray)(expr)) {\n (0, import_internal2.assert)(expr.length === 3, err);\n ifExpr = expr[0];\n thenExpr = expr[1];\n elseExpr = expr[2];\n } else {\n (0, import_internal2.assert)((0, import_internal2.isObject)(expr), err);\n ifExpr = expr.if;\n thenExpr = expr.then;\n elseExpr = expr.else;\n }\n const condition = (0, import_internal2.truthy)(\n (0, import_internal.evalExpr)(obj, ifExpr, options),\n options.useStrictMode\n );\n return (0, import_internal.evalExpr)(obj, condition ? thenExpr : elseExpr, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $cond\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ifNull_exports = {};\n__export(ifNull_exports, {\n $ifNull: () => $ifNull\n});\nmodule.exports = __toCommonJS(ifNull_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $ifNull = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$ifNull expects an array\");\n let val = void 0;\n for (const input of expr) {\n val = (0, import_internal.evalExpr)(obj, input, options);\n if (!(0, import_util.isNil)(val)) return val;\n }\n return val;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ifNull\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar switch_exports = {};\n__export(switch_exports, {\n $switch: () => $switch\n});\nmodule.exports = __toCommonJS(switch_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nconst $switch = (obj, expr, options) => {\n (0, import_internal2.assert)((0, import_internal2.isObject)(expr), \"$switch received invalid arguments\");\n for (const { case: caseExpr, then } of expr.branches) {\n const condition = (0, import_internal2.truthy)(\n (0, import_internal.evalExpr)(obj, caseExpr, options),\n options.useStrictMode\n );\n if (condition) return (0, import_internal.evalExpr)(obj, then, options);\n }\n return (0, import_internal.evalExpr)(obj, expr.default, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $switch\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar conditional_exports = {};\nmodule.exports = __toCommonJS(conditional_exports);\n__reExport(conditional_exports, require(\"./cond\"), module.exports);\n__reExport(conditional_exports, require(\"./ifNull\"), module.exports);\n__reExport(conditional_exports, require(\"./switch\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./cond\"),\n ...require(\"./ifNull\"),\n ...require(\"./switch\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar function_exports = {};\n__export(function_exports, {\n $function: () => $function\n});\nmodule.exports = __toCommonJS(function_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $function = (obj, expr, options) => {\n (0, import_util.assert)(\n options.scriptEnabled,\n \"$function requires 'scriptEnabled' option to be true\"\n );\n const fn = (0, import_internal.evalExpr)(obj, expr, options);\n return fn.body.apply(null, fn.args);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $function\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar custom_exports = {};\nmodule.exports = __toCommonJS(custom_exports);\n__reExport(custom_exports, require(\"./function\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./function\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n DATE_FORMAT: () => DATE_FORMAT,\n DATE_FORMAT_SEP_RE: () => DATE_FORMAT_SEP_RE,\n DATE_FORMAT_SYM_RE: () => DATE_FORMAT_SYM_RE,\n DATE_PART_INTERVAL: () => DATE_PART_INTERVAL,\n DATE_SYM_TABLE: () => DATE_SYM_TABLE,\n DAYS_PER_WEEK: () => DAYS_PER_WEEK,\n LEAP_YEAR_REF_POINT: () => LEAP_YEAR_REF_POINT,\n MINUTES_PER_HOUR: () => MINUTES_PER_HOUR,\n MONTHS: () => MONTHS,\n TIMEUNIT_IN_MILLIS: () => TIMEUNIT_IN_MILLIS,\n TIME_UNITS: () => TIME_UNITS,\n adjustDate: () => adjustDate,\n computeDate: () => computeDate,\n dateAdd: () => dateAdd,\n dateDiffDay: () => dateDiffDay,\n dateDiffHour: () => dateDiffHour,\n dateDiffMonth: () => dateDiffMonth,\n dateDiffQuarter: () => dateDiffQuarter,\n dateDiffWeek: () => dateDiffWeek,\n dateDiffYear: () => dateDiffYear,\n dayOfYear: () => dayOfYear,\n daysBetweenYears: () => daysBetweenYears,\n formatTimezone: () => formatTimezone,\n isDST: () => isDST,\n isLeapYear: () => isLeapYear,\n isoWeek: () => isoWeek,\n isoWeekYear: () => isoWeekYear,\n isoWeekday: () => isoWeekday,\n padDigits: () => padDigits,\n parseTimezone: () => parseTimezone,\n weekOfYear: () => weekOfYear\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst TIME_UNITS = [\n \"year\",\n \"quarter\",\n \"month\",\n \"week\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"millisecond\"\n];\nconst ISO_WEEKDAYS = {\n mon: 1,\n tue: 2,\n wed: 3,\n thu: 4,\n fri: 5,\n sat: 6,\n sun: 7\n};\nconst LEAP_YEAR_REF_POINT = -1e9;\nconst DAYS_PER_WEEK = 7;\nconst isLeapYear = (y) => (y & 3) == 0 && (y % 100 != 0 || y % 400 == 0);\nfunction isDST(date) {\n const jan = new Date(date.getFullYear(), 0, 1).getTimezoneOffset();\n const jul = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();\n return Math.max(jan, jul) !== date.getTimezoneOffset();\n}\nconst DAYS_IN_YEAR = [\n 365,\n 366\n /*leap*/\n];\nconst YEAR_DAYS_OFFSET = [\n [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],\n [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]\n /*leap*/\n];\nconst dayOfYear = (d) => YEAR_DAYS_OFFSET[+isLeapYear(d.getUTCFullYear())][d.getUTCMonth()] + d.getUTCDate();\nconst isoWeekday = (date, startOfWeek) => {\n const dow = date.getUTCDay() || 7;\n const name = startOfWeek.toLowerCase().substring(0, 3);\n return (dow - ISO_WEEKDAYS[name] + DAYS_PER_WEEK) % DAYS_PER_WEEK;\n};\nconst p = (y) => (y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400)) % 7;\nconst weeks = (y) => 52 + Number(p(y) == 4 || p(y - 1) == 3);\nfunction isoWeek(d) {\n const dow = d.getUTCDay() || 7;\n const w = Math.floor((10 + dayOfYear(d) - dow) / 7);\n if (w < 1) return weeks(d.getUTCFullYear() - 1);\n if (w > weeks(d.getUTCFullYear())) return 1;\n return w;\n}\nfunction weekOfYear(d) {\n const result = isoWeek(d);\n if (d.getUTCDay() > 0 && d.getUTCDate() == 1 && d.getUTCMonth() == 0)\n return 0;\n if (d.getUTCDay() == 0) return result + 1;\n return result;\n}\nfunction isoWeekYear(d) {\n return d.getUTCFullYear() - Number(d.getUTCMonth() === 0 && d.getUTCDate() == 1 && d.getUTCDay() < 1);\n}\nconst MINUTES_PER_HOUR = 60;\nconst TIMEUNIT_IN_MILLIS = {\n week: 6048e5,\n day: 864e5,\n hour: 36e5,\n minute: 6e4,\n second: 1e3,\n millisecond: 1\n};\nconst DATE_FORMAT = \"%Y-%m-%dT%H:%M:%S.%LZ\";\nconst DATE_PART_INTERVAL = [\n [\"year\", 0, 9999],\n [\"month\", 1, 12],\n [\"day\", 1, 31],\n [\"hour\", 0, 23],\n [\"minute\", 0, 59],\n [\"second\", 0, 59],\n [\"millisecond\", 0, 999]\n];\nconst MONTHS = {\n jan: 1,\n feb: 2,\n mar: 3,\n apr: 4,\n may: 5,\n jun: 6,\n jul: 7,\n aug: 8,\n sep: 9,\n oct: 10,\n nov: 11,\n dec: 12\n};\nconst DATE_SYM_TABLE = {\n \"%b\": {\n name: \"abbr_month\",\n padding: 3,\n re: /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i\n },\n \"%B\": {\n name: \"full_month\",\n padding: 0,\n re: /(January|February|March|April|May|June|July|August|September|October|November|December)/i\n },\n \"%Y\": { name: \"year\", padding: 4, re: /([0-9]{4})/ },\n \"%G\": { name: \"year\", padding: 4, re: /([0-9]{4})/ },\n \"%m\": { name: \"month\", padding: 2, re: /(0[1-9]|1[012])/ },\n \"%d\": { name: \"day\", padding: 2, re: /(0[1-9]|[12][0-9]|3[01])/ },\n \"%j\": {\n name: \"day_of_year\",\n padding: 3,\n re: /(0[0-9][1-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-6])/\n },\n \"%H\": { name: \"hour\", padding: 2, re: /([01][0-9]|2[0-3])/ },\n \"%M\": { name: \"minute\", padding: 2, re: /([0-5][0-9])/ },\n \"%S\": { name: \"second\", padding: 2, re: /([0-5][0-9]|60)/ },\n \"%L\": { name: \"millisecond\", padding: 3, re: /([0-9]{3})/ },\n \"%w\": { name: \"day_of_week\", padding: 1, re: /([0-6])/ },\n \"%u\": { name: \"day_of_week_iso\", padding: 1, re: /([1-7])/ },\n \"%U\": { name: \"week_of_year\", padding: 2, re: /([1-4][0-9]?|5[0-3]?)/ },\n \"%V\": { name: \"week_of_year_iso\", padding: 2, re: /([1-4][0-9]?|5[0-3]?)/ },\n \"%z\": {\n name: \"timezone\",\n padding: 2,\n re: /(([+-][01][0-9]|2[0-3]):?([0-5][0-9])?)/\n },\n \"%Z\": { name: \"minute_offset\", padding: 3, re: /([+-][0-9]{3})/ },\n \"%%\": { name: \"percent_literal\", padding: 1, re: /%%/ }\n};\nconst DATE_FORMAT_SYM_RE = /(%[bBYGmdjHMSLwuUVzZ%])/g;\nconst DATE_FORMAT_SEP_RE = /%[bBYGmdjHMSLwuUVzZ%]/;\nconst TIMEZONE_RE = /^[a-zA-Z_]+\\/[a-zA-Z_]+$/;\nfunction parseTimezone(timeZone, date) {\n if (timeZone === void 0) return 0;\n if (TIMEZONE_RE.test(timeZone)) {\n const utcDate = new Date(date.toLocaleString(\"en-US\", { timeZone: \"UTC\" }));\n const tzDate = new Date(date.toLocaleString(\"en-US\", { timeZone }));\n return Math.round((tzDate.getTime() - utcDate.getTime()) / 6e4);\n }\n const match = DATE_SYM_TABLE[\"%z\"].re.exec(timeZone) ?? [];\n (0, import_util.assert)(!!match, `timezone '${timeZone}' is invalid or not supported.`);\n const hr = parseInt(match[2]) || 0;\n const min = parseInt(match[3]) || 0;\n return (Math.abs(hr * MINUTES_PER_HOUR) + min) * (hr < 0 ? -1 : 1);\n}\nfunction formatTimezone(minuteOffset) {\n return (minuteOffset < 0 ? \"-\" : \"+\") + padDigits(Math.abs(Math.floor(minuteOffset / MINUTES_PER_HOUR)), 2) + padDigits(Math.abs(minuteOffset) % MINUTES_PER_HOUR, 2);\n}\nfunction adjustDate(d, minuteOffset) {\n d.setUTCMinutes(d.getUTCMinutes() + minuteOffset);\n}\nfunction computeDate(obj, expr, options) {\n if ((0, import_util.isDate)(obj)) return obj;\n const d = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isDate)(d)) return new Date(d);\n if ((0, import_util.isNumber)(d)) return new Date(d * 1e3);\n (0, import_util.assert)(!!d?.date, `cannot convert ${JSON.stringify(expr)} to date`);\n const date = (0, import_util.isDate)(d.date) ? new Date(d.date) : new Date(d.date * 1e3);\n if (d.timezone) adjustDate(date, parseTimezone(d.timezone, date));\n return date;\n}\nfunction padDigits(n, digits) {\n return new Array(Math.max(digits - String(n).length + 1, 0)).join(\"0\") + n.toString();\n}\nconst leapYearsSinceReferencePoint = (year) => {\n const yearsSinceReferencePoint = year - LEAP_YEAR_REF_POINT;\n return Math.trunc(yearsSinceReferencePoint / 4) - Math.trunc(yearsSinceReferencePoint / 100) + Math.trunc(yearsSinceReferencePoint / 400);\n};\nfunction daysBetweenYears(startYear, endYear) {\n return Math.trunc(\n leapYearsSinceReferencePoint(endYear - 1) - leapYearsSinceReferencePoint(startYear - 1) + (endYear - startYear) * DAYS_IN_YEAR[0]\n );\n}\nconst dateDiffYear = (start, end) => end.getUTCFullYear() - start.getUTCFullYear();\nconst dateDiffMonth = (start, end) => end.getUTCMonth() - start.getUTCMonth() + dateDiffYear(start, end) * 12;\nconst dateDiffQuarter = (start, end) => {\n const a = Math.trunc(start.getUTCMonth() / 3);\n const b = Math.trunc(end.getUTCMonth() / 3);\n return b - a + dateDiffYear(start, end) * 4;\n};\nconst dateDiffDay = (start, end) => dayOfYear(end) - dayOfYear(start) + daysBetweenYears(start.getUTCFullYear(), end.getUTCFullYear());\nconst dateDiffWeek = (start, end, startOfWeek) => {\n const wk = (startOfWeek || \"sun\").substring(0, 3);\n return Math.trunc(\n (dateDiffDay(start, end) + isoWeekday(start, wk) - isoWeekday(end, wk)) / DAYS_PER_WEEK\n );\n};\nconst dateDiffHour = (start, end) => end.getUTCHours() - start.getUTCHours() + dateDiffDay(start, end) * 24;\nconst addMonth = (d, amount) => {\n const m = d.getUTCMonth() + amount;\n const yearOffset = Math.floor(m / 12);\n if (m < 0) {\n const month = m % 12 + 12;\n d.setUTCFullYear(d.getUTCFullYear() + yearOffset, month, d.getUTCDate());\n } else {\n d.setUTCFullYear(d.getUTCFullYear() + yearOffset, m % 12, d.getUTCDate());\n }\n};\nconst dateAdd = (date, unit, amount, _timezone) => {\n const d = new Date(date);\n switch (unit) {\n case \"year\":\n d.setUTCFullYear(d.getUTCFullYear() + amount);\n break;\n case \"quarter\":\n addMonth(d, 3 * amount);\n break;\n case \"month\":\n addMonth(d, amount);\n break;\n default:\n d.setTime(d.getTime() + TIMEUNIT_IN_MILLIS[unit] * amount);\n }\n return d;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n DATE_FORMAT,\n DATE_FORMAT_SEP_RE,\n DATE_FORMAT_SYM_RE,\n DATE_PART_INTERVAL,\n DATE_SYM_TABLE,\n DAYS_PER_WEEK,\n LEAP_YEAR_REF_POINT,\n MINUTES_PER_HOUR,\n MONTHS,\n TIMEUNIT_IN_MILLIS,\n TIME_UNITS,\n adjustDate,\n computeDate,\n dateAdd,\n dateDiffDay,\n dateDiffHour,\n dateDiffMonth,\n dateDiffQuarter,\n dateDiffWeek,\n dateDiffYear,\n dayOfYear,\n daysBetweenYears,\n formatTimezone,\n isDST,\n isLeapYear,\n isoWeek,\n isoWeekYear,\n isoWeekday,\n padDigits,\n parseTimezone,\n weekOfYear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateAdd_exports = {};\n__export(dateAdd_exports, {\n $dateAdd: () => $dateAdd\n});\nmodule.exports = __toCommonJS(dateAdd_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst $dateAdd = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_internal2.dateAdd)(args.startDate, args.unit, args.amount, args.timezone);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateAdd\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateDiff_exports = {};\n__export(dateDiff_exports, {\n $dateDiff: () => $dateDiff\n});\nmodule.exports = __toCommonJS(dateDiff_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst $dateDiff = (obj, expr, options) => {\n const { startDate, endDate, unit, timezone, startOfWeek } = (0, import_internal.evalExpr)(\n obj,\n expr,\n options\n );\n const d1 = new Date(startDate);\n const d2 = new Date(endDate);\n (0, import_internal2.adjustDate)(d1, (0, import_internal2.parseTimezone)(timezone, d1));\n (0, import_internal2.adjustDate)(d2, (0, import_internal2.parseTimezone)(timezone, d2));\n switch (unit) {\n case \"year\":\n return (0, import_internal2.dateDiffYear)(d1, d2);\n case \"quarter\":\n return (0, import_internal2.dateDiffQuarter)(d1, d2);\n case \"month\":\n return (0, import_internal2.dateDiffMonth)(d1, d2);\n case \"week\":\n return (0, import_internal2.dateDiffWeek)(d1, d2, startOfWeek);\n case \"day\":\n return (0, import_internal2.dateDiffDay)(d1, d2);\n case \"hour\":\n return (0, import_internal2.dateDiffHour)(d1, d2);\n case \"minute\":\n d1.setUTCSeconds(0);\n d1.setUTCMilliseconds(0);\n d2.setUTCSeconds(0);\n d2.setUTCMilliseconds(0);\n return Math.round(\n (d2.getTime() - d1.getTime()) / import_internal2.TIMEUNIT_IN_MILLIS[unit]\n );\n default:\n return Math.round(\n (d2.getTime() - d1.getTime()) / import_internal2.TIMEUNIT_IN_MILLIS[unit]\n );\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateDiff\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateFromParts_exports = {};\n__export(dateFromParts_exports, {\n $dateFromParts: () => $dateFromParts\n});\nmodule.exports = __toCommonJS(dateFromParts_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst getDaysInMonth = (date) => {\n return date.month == 2 && (0, import_internal2.isLeapYear)(date.year) ? 29 : DAYS_IN_MONTH[date.month - 1];\n};\nconst $dateFromParts = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const minuteOffset = (0, import_internal2.parseTimezone)(args.timezone, /* @__PURE__ */ new Date());\n for (let i = import_internal2.DATE_PART_INTERVAL.length - 1, remainder = 0; i >= 0; i--) {\n const datePartInterval = import_internal2.DATE_PART_INTERVAL[i];\n const k = datePartInterval[0];\n const min = datePartInterval[1];\n const max = datePartInterval[2];\n let part = (args[k] || 0) + remainder;\n remainder = 0;\n const limit = max + 1;\n if (k == \"hour\") part += Math.floor(minuteOffset / import_internal2.MINUTES_PER_HOUR) * -1;\n if (k == \"minute\") part += minuteOffset % import_internal2.MINUTES_PER_HOUR * -1;\n if (part < min) {\n const delta = min - part;\n remainder = -1 * Math.ceil(delta / limit);\n part = limit - delta % limit;\n } else if (part > max) {\n part += min;\n remainder = Math.trunc(part / limit);\n part %= limit;\n }\n args[k] = part;\n }\n args.day = Math.min(args.day, getDaysInMonth(args));\n return new Date(\n Date.UTC(\n args.year,\n args.month - 1,\n args.day,\n args.hour,\n args.minute,\n args.second,\n args.millisecond\n )\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateFromParts\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateFromString_exports = {};\n__export(dateFromString_exports, {\n $dateFromString: () => $dateFromString\n});\nmodule.exports = __toCommonJS(dateFromString_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nfunction tzLetterOffset(c) {\n if (c === \"Z\") return 0;\n if (c >= \"A\" && c < \"N\") return c.charCodeAt(0) - 64;\n return 77 - c.charCodeAt(0);\n}\nconst regexStrip = (s) => s.replace(/^\\//, \"\").replace(/\\/$/, \"\").replace(/\\/i/, \"\");\nconst REGEX_SPECIAL_CHARS = [\"^\", \".\", \"-\", \"*\", \"?\", \"$\"];\nfunction regexQuote(s) {\n for (const c of REGEX_SPECIAL_CHARS) s = s.replace(c, `\\\\${c}`);\n return s;\n}\nfunction $dateFromString(obj, expr, options) {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const format = args.format || import_internal2.DATE_FORMAT;\n const onNull = args.onNull || null;\n let dateString = args.dateString;\n if ((0, import_util.isNil)(dateString)) return onNull;\n const separators = format.split(import_internal2.DATE_FORMAT_SEP_RE);\n separators.reverse();\n const matches = format.match(import_internal2.DATE_FORMAT_SYM_RE);\n const dateParts = {};\n let expectedPattern = \"\";\n for (let i = 0, len = matches.length; i < len; i++) {\n const formatSpecifier = matches[i];\n const props = import_internal2.DATE_SYM_TABLE[formatSpecifier];\n if ((0, import_util.isObject)(props)) {\n const m2 = props.re.exec(dateString);\n const delimiter = separators.pop() || \"\";\n if (m2 !== null) {\n dateParts[props.name] = /^\\d+$/.exec(m2[0]) ? parseInt(m2[0]) : m2[0];\n dateString = dateString.substring(m2.index + m2[0].length + 1);\n expectedPattern += regexQuote(delimiter) + regexStrip(props.re.toString());\n } else {\n dateParts[props.name] = null;\n }\n }\n }\n if ((0, import_util.isNil)(dateParts.month)) {\n const abbrMonth = (dateParts.full_month?.slice(0, 3) ?? dateParts.abbr_month ?? \"\").toLowerCase();\n if (import_internal2.MONTHS[abbrMonth]) {\n dateParts.month = import_internal2.MONTHS[abbrMonth];\n }\n }\n if ((0, import_util.isNil)(dateParts.year) || (0, import_util.isNil)(dateParts.month) || (0, import_util.isNil)(dateParts.day) || !new RegExp(\"^\" + expectedPattern + \"[A-Z]?$\").test(args.dateString)) {\n return args.onError;\n }\n const m = args.dateString.match(/([A-Z])$/);\n (0, import_util.assert)(\n // only one of in-date timeone or timezone argument but not both.\n !(m && args.timezone),\n `$dateFromString: you cannot pass in a date/time string with time zone information ('${m && m[0]}') together with a timezone argument`\n );\n const minuteOffset = m ? tzLetterOffset(m[0]) * import_internal2.MINUTES_PER_HOUR : (0, import_internal2.parseTimezone)(args.timezone, /* @__PURE__ */ new Date());\n const d = new Date(\n Date.UTC(dateParts.year, dateParts.month - 1, dateParts.day, 0, 0, 0)\n );\n if (!(0, import_util.isNil)(dateParts.hour)) d.setUTCHours(dateParts.hour);\n if (!(0, import_util.isNil)(dateParts.minute)) d.setUTCMinutes(dateParts.minute);\n if (!(0, import_util.isNil)(dateParts.second)) d.setUTCSeconds(dateParts.second);\n if (!(0, import_util.isNil)(dateParts.millisecond))\n d.setUTCMilliseconds(dateParts.millisecond);\n (0, import_internal2.adjustDate)(d, -minuteOffset);\n return d;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateFromString\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateSubtract_exports = {};\n__export(dateSubtract_exports, {\n $dateSubtract: () => $dateSubtract\n});\nmodule.exports = __toCommonJS(dateSubtract_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst $dateSubtract = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_internal2.dateAdd)(args.startDate, args.unit, -args.amount, args.timezone);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateSubtract\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateToParts_exports = {};\n__export(dateToParts_exports, {\n $dateToParts: () => $dateToParts\n});\nmodule.exports = __toCommonJS(dateToParts_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"./_internal\");\nconst $dateToParts = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const d = new Date(args.date);\n (0, import_internal2.adjustDate)(d, (0, import_internal2.parseTimezone)(args.timezone, d));\n const timePart = {\n hour: d.getUTCHours(),\n minute: d.getUTCMinutes(),\n second: d.getUTCSeconds(),\n millisecond: d.getUTCMilliseconds()\n };\n if (args.iso8601 == true) {\n return Object.assign(timePart, {\n isoWeekYear: (0, import_internal2.isoWeekYear)(d),\n isoWeek: (0, import_internal2.isoWeek)(d),\n isoDayOfWeek: d.getUTCDay() || 7\n });\n }\n return Object.assign(timePart, {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate()\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateToParts\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateToString_exports = {};\n__export(dateToString_exports, {\n $dateToString: () => $dateToString\n});\nmodule.exports = __toCommonJS(dateToString_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst DATE_FUNCTIONS = {\n \"%Y\": (d) => d.getUTCFullYear(),\n //year\n \"%G\": (d) => d.getUTCFullYear(),\n //year\n \"%m\": (d) => d.getUTCMonth() + 1,\n //month\n \"%d\": (d) => d.getUTCDate(),\n //dayOfMonth\n \"%H\": (d) => d.getUTCHours(),\n //hour\n \"%M\": (d) => d.getUTCMinutes(),\n //minutes\n \"%S\": (d) => d.getUTCSeconds(),\n //seconds\n \"%L\": (d) => d.getUTCMilliseconds(),\n //milliseconds\n \"%u\": (d) => d.getUTCDay() || 7,\n //isoDayOfWeek\n \"%U\": import_internal2.weekOfYear,\n \"%V\": import_internal2.isoWeek,\n \"%j\": import_internal2.dayOfYear,\n \"%w\": (d) => d.getUTCDay()\n //dayOfWeek\n};\nconst $dateToString = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(args.onNull)) args.onNull = null;\n if ((0, import_util.isNil)(args.date)) return args.onNull;\n const date = (0, import_internal2.computeDate)(obj, args.date, options);\n let format = args.format ?? import_internal2.DATE_FORMAT;\n const minuteOffset = (0, import_internal2.parseTimezone)(args.timezone, date);\n const matches = format.match(import_internal2.DATE_FORMAT_SYM_RE);\n if (!matches) return format;\n (0, import_internal2.adjustDate)(date, minuteOffset);\n for (let i = 0, len = matches.length; i < len; i++) {\n const formatSpec = matches[i];\n (0, import_util.assert)(\n formatSpec in import_internal2.DATE_SYM_TABLE,\n `$dateToString: invalid format specifier ${formatSpec}`\n );\n const { name, padding } = import_internal2.DATE_SYM_TABLE[formatSpec];\n const fn = DATE_FUNCTIONS[formatSpec];\n let value = \"\";\n if (fn) {\n value = (0, import_internal2.padDigits)(fn(date), padding);\n } else {\n switch (name) {\n case \"timezone\":\n value = (0, import_internal2.formatTimezone)(minuteOffset);\n break;\n case \"minute_offset\":\n value = minuteOffset.toString();\n break;\n case \"abbr_month\":\n case \"full_month\": {\n const format2 = name.startsWith(\"abbr\") ? \"short\" : \"long\";\n value = date.toLocaleString(\"en-US\", { month: format2 });\n break;\n }\n }\n }\n format = format.replace(formatSpec, value);\n }\n return format;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateToString\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dateTrunc_exports = {};\n__export(dateTrunc_exports, {\n $dateTrunc: () => $dateTrunc\n});\nmodule.exports = __toCommonJS(dateTrunc_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst REF_DATE_MILLIS = 9466848e5;\nconst distanceToBinLowerBound = (value, binSize) => {\n let remainder = value % binSize;\n if (remainder < 0) {\n remainder += binSize;\n }\n return remainder;\n};\nconst DATE_DIFF_FN = {\n day: import_internal2.dateDiffDay,\n month: import_internal2.dateDiffMonth,\n quarter: import_internal2.dateDiffQuarter,\n year: import_internal2.dateDiffYear\n};\nconst DAYS_OF_WEEK_RE = /(mon(day)?|tue(sday)?|wed(nesday)?|thu(rsday)?|fri(day)?|sat(urday)?|sun(day)?)/i;\nconst $dateTrunc = (obj, expr, options) => {\n const {\n date,\n unit,\n binSize: optBinSize,\n timezone,\n startOfWeek: optStartOfWeek\n } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(date) || (0, import_util.isNil)(unit)) return null;\n const startOfWeek = (optStartOfWeek ?? \"sun\").toLowerCase().substring(0, 3);\n (0, import_util.assert)(\n (0, import_util.isDate)(date),\n \"$dateTrunc: 'date' must resolve to a valid Date object.\"\n );\n (0, import_util.assert)(import_internal2.TIME_UNITS.includes(unit), \"$dateTrunc: unit is invalid.\");\n (0, import_util.assert)(\n unit != \"week\" || DAYS_OF_WEEK_RE.test(startOfWeek),\n `$dateTrunc: startOfWeek '${startOfWeek}' is not a valid.`\n );\n (0, import_util.assert)(\n (0, import_util.isNil)(optBinSize) || optBinSize > 0,\n \"$dateTrunc requires 'binSize' to be greater than 0, but got value 0.\"\n );\n const binSize = optBinSize ?? 1;\n switch (unit) {\n case \"millisecond\":\n case \"second\":\n case \"minute\":\n case \"hour\": {\n const binSizeMillis = binSize * import_internal2.TIMEUNIT_IN_MILLIS[unit];\n const shiftedDate = date.getTime() - REF_DATE_MILLIS;\n return new Date(\n date.getTime() - distanceToBinLowerBound(shiftedDate, binSizeMillis)\n );\n }\n default: {\n (0, import_util.assert)(binSize <= 1e11, \"dateTrunc unsupported binSize value\");\n const d = new Date(date);\n const refPointDate = new Date(REF_DATE_MILLIS);\n let distanceFromRefPoint = 0;\n if (unit == \"week\") {\n const refPointDayOfWeek = (0, import_internal2.isoWeekday)(refPointDate, startOfWeek);\n const daysToAdjustBy = (import_internal2.DAYS_PER_WEEK - refPointDayOfWeek) % import_internal2.DAYS_PER_WEEK;\n refPointDate.setTime(\n refPointDate.getTime() + daysToAdjustBy * import_internal2.TIMEUNIT_IN_MILLIS.day\n );\n distanceFromRefPoint = (0, import_internal2.dateDiffWeek)(refPointDate, d, startOfWeek);\n } else {\n distanceFromRefPoint = DATE_DIFF_FN[unit](refPointDate, d);\n }\n const binLowerBoundFromRefPoint = distanceFromRefPoint - distanceToBinLowerBound(distanceFromRefPoint, binSize);\n const newDate = (0, import_internal2.dateAdd)(\n refPointDate,\n unit,\n binLowerBoundFromRefPoint,\n timezone\n );\n const minuteOffset = (0, import_internal2.parseTimezone)(timezone, newDate);\n (0, import_internal2.adjustDate)(newDate, -minuteOffset);\n return newDate;\n }\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dateTrunc\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dayOfMonth_exports = {};\n__export(dayOfMonth_exports, {\n $dayOfMonth: () => $dayOfMonth\n});\nmodule.exports = __toCommonJS(dayOfMonth_exports);\nvar import_internal = require(\"./_internal\");\nconst $dayOfMonth = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDate();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dayOfMonth\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dayOfWeek_exports = {};\n__export(dayOfWeek_exports, {\n $dayOfWeek: () => $dayOfWeek\n});\nmodule.exports = __toCommonJS(dayOfWeek_exports);\nvar import_internal = require(\"./_internal\");\nconst $dayOfWeek = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDay() + 1;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dayOfWeek\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar dayOfYear_exports = {};\n__export(dayOfYear_exports, {\n $dayOfYear: () => $dayOfYear\n});\nmodule.exports = __toCommonJS(dayOfYear_exports);\nvar import_internal = require(\"./_internal\");\nconst $dayOfYear = (obj, expr, options) => (0, import_internal.dayOfYear)((0, import_internal.computeDate)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $dayOfYear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar hour_exports = {};\n__export(hour_exports, {\n $hour: () => $hour\n});\nmodule.exports = __toCommonJS(hour_exports);\nvar import_internal = require(\"./_internal\");\nconst $hour = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCHours();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $hour\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isoDayOfWeek_exports = {};\n__export(isoDayOfWeek_exports, {\n $isoDayOfWeek: () => $isoDayOfWeek\n});\nmodule.exports = __toCommonJS(isoDayOfWeek_exports);\nvar import_internal = require(\"./_internal\");\nconst $isoDayOfWeek = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCDay() || 7;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isoDayOfWeek\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isoWeek_exports = {};\n__export(isoWeek_exports, {\n $isoWeek: () => $isoWeek\n});\nmodule.exports = __toCommonJS(isoWeek_exports);\nvar import_internal = require(\"./_internal\");\nconst $isoWeek = (obj, expr, options) => (0, import_internal.isoWeek)((0, import_internal.computeDate)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isoWeek\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isoWeekYear_exports = {};\n__export(isoWeekYear_exports, {\n $isoWeekYear: () => $isoWeekYear\n});\nmodule.exports = __toCommonJS(isoWeekYear_exports);\nvar import_internal = require(\"./_internal\");\nconst $isoWeekYear = (obj, expr, options) => (0, import_internal.isoWeekYear)((0, import_internal.computeDate)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isoWeekYear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar millisecond_exports = {};\n__export(millisecond_exports, {\n $millisecond: () => $millisecond\n});\nmodule.exports = __toCommonJS(millisecond_exports);\nvar import_internal = require(\"./_internal\");\nconst $millisecond = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMilliseconds();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $millisecond\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar minute_exports = {};\n__export(minute_exports, {\n $minute: () => $minute\n});\nmodule.exports = __toCommonJS(minute_exports);\nvar import_internal = require(\"./_internal\");\nconst $minute = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMinutes();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $minute\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar month_exports = {};\n__export(month_exports, {\n $month: () => $month\n});\nmodule.exports = __toCommonJS(month_exports);\nvar import_internal = require(\"./_internal\");\nconst $month = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCMonth() + 1;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $month\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar second_exports = {};\n__export(second_exports, {\n $second: () => $second\n});\nmodule.exports = __toCommonJS(second_exports);\nvar import_internal = require(\"./_internal\");\nconst $second = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCSeconds();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $second\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar week_exports = {};\n__export(week_exports, {\n $week: () => $week\n});\nmodule.exports = __toCommonJS(week_exports);\nvar import_internal = require(\"./_internal\");\nconst $week = (obj, expr, options) => (0, import_internal.weekOfYear)((0, import_internal.computeDate)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $week\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar year_exports = {};\n__export(year_exports, {\n $year: () => $year\n});\nmodule.exports = __toCommonJS(year_exports);\nvar import_internal = require(\"./_internal\");\nconst $year = (obj, expr, options) => (0, import_internal.computeDate)(obj, expr, options).getUTCFullYear();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $year\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar date_exports = {};\nmodule.exports = __toCommonJS(date_exports);\n__reExport(date_exports, require(\"./dateAdd\"), module.exports);\n__reExport(date_exports, require(\"./dateDiff\"), module.exports);\n__reExport(date_exports, require(\"./dateFromParts\"), module.exports);\n__reExport(date_exports, require(\"./dateFromString\"), module.exports);\n__reExport(date_exports, require(\"./dateSubtract\"), module.exports);\n__reExport(date_exports, require(\"./dateToParts\"), module.exports);\n__reExport(date_exports, require(\"./dateToString\"), module.exports);\n__reExport(date_exports, require(\"./dateTrunc\"), module.exports);\n__reExport(date_exports, require(\"./dayOfMonth\"), module.exports);\n__reExport(date_exports, require(\"./dayOfWeek\"), module.exports);\n__reExport(date_exports, require(\"./dayOfYear\"), module.exports);\n__reExport(date_exports, require(\"./hour\"), module.exports);\n__reExport(date_exports, require(\"./isoDayOfWeek\"), module.exports);\n__reExport(date_exports, require(\"./isoWeek\"), module.exports);\n__reExport(date_exports, require(\"./isoWeekYear\"), module.exports);\n__reExport(date_exports, require(\"./millisecond\"), module.exports);\n__reExport(date_exports, require(\"./minute\"), module.exports);\n__reExport(date_exports, require(\"./month\"), module.exports);\n__reExport(date_exports, require(\"./second\"), module.exports);\n__reExport(date_exports, require(\"./week\"), module.exports);\n__reExport(date_exports, require(\"./year\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./dateAdd\"),\n ...require(\"./dateDiff\"),\n ...require(\"./dateFromParts\"),\n ...require(\"./dateFromString\"),\n ...require(\"./dateSubtract\"),\n ...require(\"./dateToParts\"),\n ...require(\"./dateToString\"),\n ...require(\"./dateTrunc\"),\n ...require(\"./dayOfMonth\"),\n ...require(\"./dayOfWeek\"),\n ...require(\"./dayOfYear\"),\n ...require(\"./hour\"),\n ...require(\"./isoDayOfWeek\"),\n ...require(\"./isoWeek\"),\n ...require(\"./isoWeekYear\"),\n ...require(\"./millisecond\"),\n ...require(\"./minute\"),\n ...require(\"./month\"),\n ...require(\"./second\"),\n ...require(\"./week\"),\n ...require(\"./year\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar literal_exports = {};\n__export(literal_exports, {\n $literal: () => $literal\n});\nmodule.exports = __toCommonJS(literal_exports);\nconst $literal = (_obj, expr, _options) => expr;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $literal\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar median_exports = {};\n__export(median_exports, {\n $median: () => $median\n});\nmodule.exports = __toCommonJS(median_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_median = require(\"../accumulator/median\");\nconst $median = (obj, expr, options) => {\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n return (0, import_median.$median)(input, { input: \"$$CURRENT\", method: expr.method }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $median\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar getField_exports = {};\n__export(getField_exports, {\n $getField: () => $getField\n});\nmodule.exports = __toCommonJS(getField_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $getField = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const { field, input } = (0, import_util.isString)(args) ? { field: args, input: obj } : { field: args.field, input: args.input ?? obj };\n return input[field];\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $getField\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar rand_exports = {};\n__export(rand_exports, {\n $rand: () => $rand\n});\nmodule.exports = __toCommonJS(rand_exports);\nconst $rand = (_obj, _expr, _options) => Math.random();\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $rand\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sampleRate_exports = {};\n__export(sampleRate_exports, {\n $sampleRate: () => $sampleRate\n});\nmodule.exports = __toCommonJS(sampleRate_exports);\nvar import_internal = require(\"../../../core/_internal\");\nconst $sampleRate = (obj, expr, options) => Math.random() <= (0, import_internal.evalExpr)(obj, expr, options);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sampleRate\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar misc_exports = {};\nmodule.exports = __toCommonJS(misc_exports);\n__reExport(misc_exports, require(\"./getField\"), module.exports);\n__reExport(misc_exports, require(\"./rand\"), module.exports);\n__reExport(misc_exports, require(\"./sampleRate\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./getField\"),\n ...require(\"./rand\"),\n ...require(\"./sampleRate\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mergeObjects_exports = {};\n__export(mergeObjects_exports, {\n $mergeObjects: () => $mergeObjects\n});\nmodule.exports = __toCommonJS(mergeObjects_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_mergeObjects = require(\"../../accumulator/mergeObjects\");\nvar import_internal2 = require(\"../_internal\");\nconst $mergeObjects = (obj, expr, options) => {\n const docs = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(docs)) return {};\n if (!(0, import_util.isArray)(docs))\n return (0, import_internal2.errExpectArray)(options.failOnError, \"$mergeObjects\", import_internal2.ARR_OPTS.obj);\n return (0, import_mergeObjects.$mergeObjects)(docs, expr, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mergeObjects\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar objectToArray_exports = {};\n__export(objectToArray_exports, {\n $objectToArray: () => $objectToArray\n});\nmodule.exports = __toCommonJS(objectToArray_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $objectToArray = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(val)) return null;\n if (!(0, import_util.isObject)(val))\n return (0, import_internal2.errExpectObject)(options.failOnError, \"$objectToArray\");\n const keys = Object.keys(val);\n const result = new Array(keys.length);\n let i = 0;\n for (const k of keys) {\n result[i++] = { k, v: val[k] };\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $objectToArray\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setField_exports = {};\n__export(setField_exports, {\n $setField: () => $setField\n});\nmodule.exports = __toCommonJS(setField_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$setField\";\nconst $setField = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"field\", \"value\"),\n \"$setField expects object { input, field, value }\"\n );\n const { input, field, value } = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(input)) return null;\n const foe = options.failOnError;\n if (!(0, import_util.isObject)(input)) return (0, import_internal2.errExpectObject)(foe, `${OP} 'input'`);\n if (!(0, import_util.isString)(field)) return (0, import_internal2.errExpectString)(foe, `${OP} 'field'`);\n const newObj = { ...input };\n if (expr.value == \"$$REMOVE\") {\n delete newObj[field];\n } else {\n newObj[field] = value;\n }\n return newObj;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setField\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unsetField_exports = {};\n__export(unsetField_exports, {\n $unsetField: () => $unsetField\n});\nmodule.exports = __toCommonJS(unsetField_exports);\nvar import_setField = require(\"./setField\");\nconst $unsetField = (obj, expr, options) => {\n return (0, import_setField.$setField)(obj, { ...expr, value: \"$$REMOVE\" }, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unsetField\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar object_exports = {};\nmodule.exports = __toCommonJS(object_exports);\n__reExport(object_exports, require(\"./mergeObjects\"), module.exports);\n__reExport(object_exports, require(\"./objectToArray\"), module.exports);\n__reExport(object_exports, require(\"./setField\"), module.exports);\n__reExport(object_exports, require(\"./unsetField\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./mergeObjects\"),\n ...require(\"./objectToArray\"),\n ...require(\"./setField\"),\n ...require(\"./unsetField\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar percentile_exports = {};\n__export(percentile_exports, {\n $percentile: () => $percentile\n});\nmodule.exports = __toCommonJS(percentile_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_percentile = require(\"../accumulator/percentile\");\nconst $percentile = (obj, expr, options) => {\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n return (0, import_percentile.$percentile)(\n input,\n { ...expr, input: \"$$CURRENT\" },\n options\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $percentile\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar allElementsTrue_exports = {};\n__export(allElementsTrue_exports, {\n $allElementsTrue: () => $allElementsTrue\n});\nmodule.exports = __toCommonJS(allElementsTrue_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $allElementsTrue = (obj, expr, options) => {\n if ((0, import_internal2.isArray)(expr)) {\n if (expr.length === 0) return true;\n (0, import_internal2.assert)(expr.length === 1, \"$allElementsTrue expects array(1)\");\n expr = expr[0];\n }\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_internal2.isArray)(args)) return (0, import_internal3.errExpectArray)(foe, `$allElementsTrue argument`);\n for (const v of args) if (!(0, import_internal2.truthy)(v, options.useStrictMode)) return false;\n return true;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $allElementsTrue\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar anyElementTrue_exports = {};\n__export(anyElementTrue_exports, {\n $anyElementTrue: () => $anyElementTrue\n});\nmodule.exports = __toCommonJS(anyElementTrue_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $anyElementTrue = (obj, expr, options) => {\n if ((0, import_internal2.isArray)(expr)) {\n if (expr.length === 0) return false;\n (0, import_internal2.assert)(expr.length === 1, \"$anyElementTrue expects array(1)\");\n expr = expr[0];\n }\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_internal2.isArray)(args)) return (0, import_internal3.errExpectArray)(foe, `$anyElementTrue argument`);\n for (const v of args) if ((0, import_internal2.truthy)(v, options.useStrictMode)) return true;\n return false;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $anyElementTrue\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setDifference_exports = {};\n__export(setDifference_exports, {\n $setDifference: () => $setDifference\n});\nmodule.exports = __toCommonJS(setDifference_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$setDifference\";\nconst $setDifference = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length == 2, `${OP} expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let ok = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n ok &&= (0, import_util.isArray)(v);\n }\n if (!ok) return (0, import_internal2.errExpectArray)(foe, `${OP} arguments`);\n const m = import_util.HashMap.init();\n for (const v of args[0]) m.set(v, true);\n for (const v of args[1]) m.delete(v);\n return Array.from(m.keys());\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setDifference\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setEquals_exports = {};\n__export(setEquals_exports, {\n $setEquals: () => $setEquals\n});\nmodule.exports = __toCommonJS(setEquals_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $setEquals = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$setEquals expects array\");\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if (!args.every(import_util.isArray)) return (0, import_internal2.errExpectArray)(foe, \"$setEquals arguments\");\n const map = import_util.HashMap.init();\n const first = args[0];\n for (let i = 0; i < first.length; i++) map.set(first[i], i);\n for (let i = 1; i < args.length; i++) {\n const arr = args[i];\n const set = /* @__PURE__ */ new Set();\n for (let j = 0; j < arr.length; j++) {\n const n = map.get(arr[j]) ?? -1;\n if (n === -1) return false;\n set.add(n);\n }\n if (set.size !== map.size) return false;\n }\n return true;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setEquals\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setIntersection_exports = {};\n__export(setIntersection_exports, {\n $setIntersection: () => $setIntersection\n});\nmodule.exports = __toCommonJS(setIntersection_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$setIntersection\";\nconst $setIntersection = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), `${OP} expects array`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let ok = true;\n for (const v of args) {\n if ((0, import_util.isNil)(v)) return null;\n ok &&= (0, import_util.isArray)(v);\n }\n if (!ok) return (0, import_internal2.errExpectArray)(foe, `${OP} arguments`);\n return (0, import_util.intersection)(args);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setIntersection\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setIsSubset_exports = {};\n__export(setIsSubset_exports, {\n $setIsSubset: () => $setIsSubset\n});\nmodule.exports = __toCommonJS(setIsSubset_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$setIsSubset\";\nconst $setIsSubset = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, `${OP} expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n if (!args.every(import_util.isArray))\n return (0, import_internal2.errExpectArray)(options.failOnError, `${OP} arguments`);\n const [first, second] = args;\n const map = import_util.HashMap.init();\n for (const v of second) map.set(v, 0);\n for (const v of first) if (!map.has(v)) return false;\n return true;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setIsSubset\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setUnion_exports = {};\n__export(setUnion_exports, {\n $setUnion: () => $setUnion\n});\nmodule.exports = __toCommonJS(setUnion_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $setUnion = (obj, expr, options) => {\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if ((0, import_util.isNil)(args)) return null;\n if (!(0, import_util.isArray)(args)) return (0, import_internal2.errExpectArray)(foe, \"$setUnion\");\n if ((0, import_util.isArray)(expr)) {\n if (!args.every(import_util.isArray)) return (0, import_internal2.errExpectArray)(foe, \"$setUnion arguments\");\n return (0, import_util.unique)((0, import_util.flatten)(args));\n }\n return (0, import_util.unique)(args);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setUnion\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar set_exports = {};\nmodule.exports = __toCommonJS(set_exports);\n__reExport(set_exports, require(\"./allElementsTrue\"), module.exports);\n__reExport(set_exports, require(\"./anyElementTrue\"), module.exports);\n__reExport(set_exports, require(\"./setDifference\"), module.exports);\n__reExport(set_exports, require(\"./setEquals\"), module.exports);\n__reExport(set_exports, require(\"./setIntersection\"), module.exports);\n__reExport(set_exports, require(\"./setIsSubset\"), module.exports);\n__reExport(set_exports, require(\"./setUnion\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./allElementsTrue\"),\n ...require(\"./anyElementTrue\"),\n ...require(\"./setDifference\"),\n ...require(\"./setEquals\"),\n ...require(\"./setIntersection\"),\n ...require(\"./setIsSubset\"),\n ...require(\"./setUnion\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar concat_exports = {};\n__export(concat_exports, {\n $concat: () => $concat\n});\nmodule.exports = __toCommonJS(concat_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $concat = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr), \"$concat expects array\");\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n let ok = true;\n for (const s of args) {\n if ((0, import_util.isNil)(s)) return null;\n ok &&= (0, import_util.isString)(s);\n }\n if (!ok) return (0, import_internal2.errExpectArray)(foe, \"$concat\", { type: \"string\" });\n return args.join(\"\");\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $concat\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar indexOfBytes_exports = {};\n__export(indexOfBytes_exports, {\n $indexOfBytes: () => $indexOfBytes\n});\nmodule.exports = __toCommonJS(indexOfBytes_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst OP = \"$indexOfBytes\";\nconst $indexOfBytes = (obj, expr, options) => {\n (0, import_internal2.assert)(\n (0, import_internal2.isArray)(expr) && expr.length > 1 && expr.length < 5,\n `${OP} expects array(4)`\n );\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n const str = args[0];\n if ((0, import_internal2.isNil)(str)) return null;\n if (!(0, import_internal2.isString)(str)) return (0, import_internal3.errExpectString)(foe, `${OP} arg1 `);\n const search = args[1];\n if (!(0, import_internal2.isString)(search)) return (0, import_internal3.errExpectString)(foe, `${OP} arg2 `);\n const start = args[2] ?? 0;\n const end = args[3] ?? str.length;\n if (!(0, import_internal2.isInteger)(start) || start < 0)\n return (0, import_internal3.errExpectNumber)(foe, `${OP} arg3 `, import_internal3.INT_OPTS.index);\n if (!(0, import_internal2.isInteger)(end) || end < 0)\n return (0, import_internal3.errExpectNumber)(foe, `${OP} arg4 `, import_internal3.INT_OPTS.index);\n if (start > end) return -1;\n const index = str.substring(start, end).indexOf(search);\n return index > -1 ? index + start : index;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $indexOfBytes\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n regexSearch: () => regexSearch,\n trimString: () => trimString\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst WHITESPACE_CHARS = [\n 0,\n // '\\0' Null character\n 32,\n // ' ', Space\n 9,\n // '\\t' Horizontal tab\n 10,\n // '\\n' Line feed/new line\n 11,\n // '\\v' Vertical tab\n 12,\n // '\\f' Form feed\n 13,\n // '\\r' Carriage return\n 160,\n // Non-breaking space\n 5760,\n // Ogham space mark\n 8192,\n // En quad\n 8193,\n // Em quad\n 8194,\n // En space\n 8195,\n // Em space\n 8196,\n // Three-per-em space\n 8197,\n // Four-per-em space\n 8198,\n // Six-per-em space\n 8199,\n // Figure space\n 8200,\n // Punctuation space\n 8201,\n // Thin space\n 8202\n // Hair space\n];\nfunction trimString(obj, expr, options, trimOpts) {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n const s = val.input;\n if ((0, import_util.isNil)(s)) return null;\n const codepoints = (0, import_util.isNil)(val.chars) ? WHITESPACE_CHARS : val.chars.split(\"\").map((c) => c.codePointAt(0));\n let i = 0;\n let j = s.length - 1;\n while (trimOpts.left && i <= j && codepoints.indexOf(s[i].codePointAt(0)) !== -1)\n i++;\n while (trimOpts.right && i <= j && codepoints.indexOf(s[j].codePointAt(0)) !== -1)\n j--;\n return s.substring(i, j + 1);\n}\nfunction regexSearch(obj, expr, options, reOpts) {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_util.isString)(val.input)) return [];\n const regexOptions = val.options;\n if (regexOptions) {\n (0, import_util.assert)(\n regexOptions.indexOf(\"x\") === -1,\n \"extended capability option 'x' not supported\"\n );\n (0, import_util.assert)(regexOptions.indexOf(\"g\") === -1, \"global option 'g' not supported\");\n }\n let input = val.input;\n const re = new RegExp(val.regex, regexOptions);\n let m;\n const matches = new Array();\n let offset = 0;\n while (m = re.exec(input)) {\n const result = {\n match: m[0],\n idx: m.index + offset,\n captures: []\n };\n for (let i = 1; i < m.length; i++) result.captures.push(m[i] || null);\n matches.push(result);\n if (!reOpts.global) break;\n offset = m.index + m[0].length;\n input = input.substring(offset);\n }\n return matches;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n regexSearch,\n trimString\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ltrim_exports = {};\n__export(ltrim_exports, {\n $ltrim: () => $ltrim\n});\nmodule.exports = __toCommonJS(ltrim_exports);\nvar import_internal = require(\"./_internal\");\nconst $ltrim = (obj, expr, options) => {\n return (0, import_internal.trimString)(obj, expr, options, { left: true, right: false });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ltrim\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar regexFind_exports = {};\n__export(regexFind_exports, {\n $regexFind: () => $regexFind\n});\nmodule.exports = __toCommonJS(regexFind_exports);\nvar import_util = require(\"../../../util\");\nvar import_internal = require(\"./_internal\");\nconst $regexFind = (obj, expr, options) => {\n const result = (0, import_internal.regexSearch)(obj, expr, options, { global: false });\n return (0, import_util.isArray)(result) && result.length > 0 ? result[0] : null;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $regexFind\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar regexFindAll_exports = {};\n__export(regexFindAll_exports, {\n $regexFindAll: () => $regexFindAll\n});\nmodule.exports = __toCommonJS(regexFindAll_exports);\nvar import_internal = require(\"./_internal\");\nconst $regexFindAll = (obj, expr, options) => {\n return (0, import_internal.regexSearch)(obj, expr, options, { global: true });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $regexFindAll\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar regexMatch_exports = {};\n__export(regexMatch_exports, {\n $regexMatch: () => $regexMatch\n});\nmodule.exports = __toCommonJS(regexMatch_exports);\nvar import_internal = require(\"./_internal\");\nconst $regexMatch = (obj, expr, options) => {\n return (0, import_internal.regexSearch)(obj, expr, options, { global: false })?.length != 0;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $regexMatch\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar replaceAll_exports = {};\n__export(replaceAll_exports, {\n $replaceAll: () => $replaceAll\n});\nmodule.exports = __toCommonJS(replaceAll_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$replaceAll\";\nconst $replaceAll = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isObject)(expr), `${OP} expects an object argument`);\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const { input, find, replacement } = args;\n if ((0, import_util.isNil)(input) || (0, import_util.isNil)(find) || (0, import_util.isNil)(replacement)) return null;\n if (!(0, import_util.isString)(input)) return (0, import_internal2.errExpectString)(foe, `${OP} 'input'`);\n if (!(0, import_util.isString)(find)) return (0, import_internal2.errExpectString)(foe, `${OP} 'find'`);\n if (!(0, import_util.isString)(replacement))\n return (0, import_internal2.errExpectString)(foe, `${OP} 'replacement'`);\n return input.replace(new RegExp(find, \"g\"), replacement);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $replaceAll\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar replaceOne_exports = {};\n__export(replaceOne_exports, {\n $replaceOne: () => $replaceOne\n});\nmodule.exports = __toCommonJS(replaceOne_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$replaceOne\";\nconst $replaceOne = (obj, expr, options) => {\n const foe = options.failOnError;\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const { input, find, replacement } = args;\n if ((0, import_util.isNil)(input) || (0, import_util.isNil)(find) || (0, import_util.isNil)(replacement)) return null;\n if (!(0, import_util.isString)(input)) return (0, import_internal2.errExpectString)(foe, `${OP} 'input'`);\n if (!(0, import_util.isString)(find)) return (0, import_internal2.errExpectString)(foe, `${OP} 'find'`);\n if (!(0, import_util.isString)(replacement))\n return (0, import_internal2.errExpectString)(foe, `${OP} 'replacement'`);\n return args.input.replace(args.find, args.replacement);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $replaceOne\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar rtrim_exports = {};\n__export(rtrim_exports, {\n $rtrim: () => $rtrim\n});\nmodule.exports = __toCommonJS(rtrim_exports);\nvar import_internal = require(\"./_internal\");\nconst $rtrim = (obj, expr, options) => {\n return (0, import_internal.trimString)(obj, expr, options, { left: false, right: true });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $rtrim\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar split_exports = {};\n__export(split_exports, {\n $split: () => $split\n});\nmodule.exports = __toCommonJS(split_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $split = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 2, `$split expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n if ((0, import_util.isNil)(args[0])) return null;\n if (!args.every(import_util.isString))\n return (0, import_internal2.errExpectArray)(foe, `$split `, { size: 2, type: \"string\" });\n return args[0].split(args[1]);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $split\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar strcasecmp_exports = {};\n__export(strcasecmp_exports, {\n $strcasecmp: () => $strcasecmp\n});\nmodule.exports = __toCommonJS(strcasecmp_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $strcasecmp = (obj, expr, options) => {\n (0, import_internal2.assert)((0, import_util.isArray)(expr) && expr.length === 2, `$strcasecmp expects array(2)`);\n const args = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n let t_nil = true;\n let t_str = true;\n for (const v of args) {\n t_nil &&= (0, import_util.isNil)(v);\n t_str &&= (0, import_util.isString)(v);\n }\n if (t_nil) return 0;\n if (!t_str)\n return (0, import_internal3.errExpectArray)(foe, `$strcasecmp arguments`, { type: \"string\" });\n return (0, import_internal2.simpleCmp)(args[0].toLowerCase(), args[1].toLowerCase());\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $strcasecmp\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar strLenBytes_exports = {};\n__export(strLenBytes_exports, {\n $strLenBytes: () => $strLenBytes\n});\nmodule.exports = __toCommonJS(strLenBytes_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $strLenBytes = (obj, expr, options) => {\n const s = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_util.isString)(s)) return (0, import_internal2.errExpectString)(options.failOnError, \"$strLenBytes\");\n return ~-encodeURI(s).split(/%..|./).length;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $strLenBytes\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar strLenCP_exports = {};\n__export(strLenCP_exports, {\n $strLenCP: () => $strLenCP\n});\nmodule.exports = __toCommonJS(strLenCP_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst $strLenCP = (obj, expr, options) => {\n const s = (0, import_internal.evalExpr)(obj, expr, options);\n if (!(0, import_util.isString)(s)) return (0, import_internal2.errExpectString)(options.failOnError, \"$strLenCP\");\n return s.length;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $strLenCP\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar substrBytes_exports = {};\n__export(substrBytes_exports, {\n $substrBytes: () => $substrBytes\n});\nmodule.exports = __toCommonJS(substrBytes_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$substrBytes\";\nconst $substrBytes = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 3, `${OP} expects array(3)`);\n const [s, index, count] = (0, import_internal.evalExpr)(obj, expr, options);\n const foe = options.failOnError;\n const nil = (0, import_util.isNil)(s);\n if (!nil && !(0, import_util.isString)(s)) return (0, import_internal2.errExpectString)(foe, `${OP} arg1 `);\n if (!(0, import_util.isInteger)(index) || index < 0)\n return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `, import_internal2.INT_OPTS.index);\n if (!(0, import_util.isInteger)(count) || count < 0)\n return (0, import_internal2.errExpectNumber)(foe, `${OP} arg3 `, import_internal2.INT_OPTS.index);\n if (nil) return \"\";\n let utf8Pos = 0;\n let start16 = null;\n let end16 = null;\n const err = `${OP} UTF-8 boundary falls inside a continuation byte`;\n for (let i = 0; i < s.length; ) {\n const cp = s.codePointAt(i);\n if (cp === void 0)\n return (0, import_internal2.errInvalidArgs)(foe, `${OP} byte index out of range`);\n const utf8Len = cp < 128 ? 1 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;\n const utf16Len = cp > 65535 ? 2 : 1;\n if (start16 === null) {\n if (index > utf8Pos && index < utf8Pos + utf8Len)\n return (0, import_internal2.errInvalidArgs)(foe, err);\n if (utf8Pos === index) {\n start16 = i;\n }\n }\n const endByte = index + count;\n if (start16 !== null && end16 === null) {\n if (endByte > utf8Pos && endByte < utf8Pos + utf8Len)\n return (0, import_internal2.errInvalidArgs)(foe, err);\n if (utf8Pos === endByte) {\n end16 = i;\n break;\n }\n }\n utf8Pos += utf8Len;\n i += utf16Len;\n }\n if (start16 === null) {\n if (index === utf8Pos) return \"\";\n return (0, import_internal2.errInvalidArgs)(foe, `${OP} byte index out of range`);\n }\n if (end16 === null) {\n const endByte = index + count;\n if (endByte !== utf8Pos)\n return (0, import_internal2.errInvalidArgs)(foe, `${OP} count extends beyond UTF-8 length`);\n end16 = s.length;\n }\n return s.slice(start16, end16);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $substrBytes\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar substr_exports = {};\n__export(substr_exports, {\n $substr: () => $substr\n});\nmodule.exports = __toCommonJS(substr_exports);\nvar import_substrBytes = require(\"./substrBytes\");\nconst $substr = import_substrBytes.$substrBytes;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $substr\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar substrCP_exports = {};\n__export(substrCP_exports, {\n $substrCP: () => $substrCP\n});\nmodule.exports = __toCommonJS(substrCP_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nconst OP = \"$substrCP\";\nconst $substrCP = (obj, expr, options) => {\n (0, import_util.assert)((0, import_util.isArray)(expr) && expr.length === 3, `${OP} expects array(3)`);\n const [s, index, count] = (0, import_internal.evalExpr)(obj, expr, options);\n const nil = (0, import_util.isNil)(s);\n const foe = options.failOnError;\n if (!nil && !(0, import_util.isString)(s)) return (0, import_internal2.errExpectString)(foe, `${OP} arg1 `);\n if (!(0, import_util.isInteger)(index)) return (0, import_internal2.errExpectNumber)(foe, `${OP} arg2 `);\n if (!(0, import_util.isInteger)(count)) return (0, import_internal2.errExpectNumber)(foe, `${OP} arg3 `);\n if (nil) return \"\";\n if (index < 0) return \"\";\n if (count < 0) return s.substring(index);\n return s.substring(index, index + count);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $substrCP\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toBool_exports = {};\n__export(toBool_exports, {\n $toBool: () => $toBool\n});\nmodule.exports = __toCommonJS(toBool_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $toBool = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(val)) return null;\n if ((0, import_util.isString)(val)) return true;\n return Boolean(val);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toBool\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toDate_exports = {};\n__export(toDate_exports, {\n $toDate: () => $toDate\n});\nmodule.exports = __toCommonJS(toDate_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $toDate = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isDate)(val)) return val;\n if ((0, import_util.isNil)(val)) return null;\n const d = new Date(val);\n (0, import_util.assert)(!isNaN(d.getTime()), `cannot convert '${val}' to date`);\n return d;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toDate\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toDouble_exports = {};\n__export(toDouble_exports, {\n $toDouble: () => $toDouble\n});\nmodule.exports = __toCommonJS(toDouble_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $toDouble = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_util.isNil)(val)) return null;\n if ((0, import_util.isDate)(val)) return val.getTime();\n if (val === true) return 1;\n if (val === false) return 0;\n const n = Number(val);\n (0, import_util.assert)((0, import_util.isNumber)(n), `cannot convert '${val}' to double/decimal`);\n return n;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toDouble\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n MAX_INT: () => MAX_INT,\n MAX_LONG: () => MAX_LONG,\n MIN_INT: () => MIN_INT,\n MIN_LONG: () => MIN_LONG,\n toInteger: () => toInteger\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst MAX_INT = 2147483647;\nconst MIN_INT = -2147483648;\nconst MAX_LONG = 9007199254740991;\nconst MIN_LONG = -9007199254740991;\nfunction toInteger(obj, expr, options, min, max) {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if (val === true) return 1;\n if (val === false) return 0;\n if ((0, import_util.isNil)(val)) return null;\n if ((0, import_util.isDate)(val)) return val.getTime();\n const n = Number(val);\n (0, import_util.assert)(\n (0, import_util.isNumber)(n) && n >= min && n <= max && (!(0, import_util.isString)(val) || n.toString().indexOf(\".\") === -1),\n `cannot convert '${val}' to ${max == MAX_INT ? \"int\" : \"long\"}`\n );\n return Math.trunc(n);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n MAX_INT,\n MAX_LONG,\n MIN_INT,\n MIN_LONG,\n toInteger\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toInt_exports = {};\n__export(toInt_exports, {\n $toInt: () => $toInt\n});\nmodule.exports = __toCommonJS(toInt_exports);\nvar import_internal = require(\"./_internal\");\nconst $toInt = (obj, expr, options) => (0, import_internal.toInteger)(obj, expr, options, import_internal.MIN_INT, import_internal.MAX_INT);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toInt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toLong_exports = {};\n__export(toLong_exports, {\n $toLong: () => $toLong\n});\nmodule.exports = __toCommonJS(toLong_exports);\nvar import_internal = require(\"./_internal\");\nconst $toLong = (obj, expr, options) => (0, import_internal.toInteger)(obj, expr, options, import_internal.MIN_LONG, import_internal.MAX_LONG);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toLong\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toString_exports = {};\n__export(toString_exports, {\n $toString: () => $toString\n});\nmodule.exports = __toCommonJS(toString_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nvar import_internal3 = require(\"../_internal\");\nconst $toString = (obj, expr, options) => {\n const val = (0, import_internal.evalExpr)(obj, expr, options);\n if ((0, import_internal2.isNil)(val)) return null;\n if ((0, import_internal2.isDate)(val)) return val.toISOString();\n if ((0, import_internal2.isPrimitive)(val) || (0, import_internal2.isRegExp)(val)) return String(val);\n return (0, import_internal3.errInvalidArgs)(\n options.failOnError,\n \"$toString cannot convert from object to string\"\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toString\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar convert_exports = {};\n__export(convert_exports, {\n $convert: () => $convert\n});\nmodule.exports = __toCommonJS(convert_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nvar import_toBool = require(\"./toBool\");\nvar import_toDate = require(\"./toDate\");\nvar import_toDouble = require(\"./toDouble\");\nvar import_toInt = require(\"./toInt\");\nvar import_toLong = require(\"./toLong\");\nvar import_toString = require(\"./toString\");\nconst $convert = (obj, expr, options) => {\n (0, import_util.assert)(\n (0, import_util.isObject)(expr) && (0, import_util.has)(expr, \"input\", \"to\"),\n \"$convert expects object { input, to, onError, onNull }\"\n );\n const input = (0, import_internal.evalExpr)(obj, expr.input, options);\n if ((0, import_util.isNil)(input)) return (0, import_internal.evalExpr)(obj, expr.onNull, options) ?? null;\n const toExpr = (0, import_internal.evalExpr)(obj, expr.to, options);\n try {\n switch (toExpr) {\n case 2:\n case \"string\":\n return (0, import_toString.$toString)(obj, input, options);\n case 8:\n case \"boolean\":\n case \"bool\":\n return (0, import_toBool.$toBool)(obj, input, options);\n case 9:\n case \"date\":\n return (0, import_toDate.$toDate)(obj, input, options);\n case 1:\n case 19:\n case \"double\":\n case \"decimal\":\n case \"number\":\n return (0, import_toDouble.$toDouble)(obj, input, options);\n case 16:\n case \"int\":\n return (0, import_toInt.$toInt)(obj, input, options);\n case 18:\n case \"long\":\n return (0, import_toLong.$toLong)(obj, input, options);\n }\n } catch {\n }\n if (expr.onError === void 0)\n return (0, import_internal2.errInvalidArgs)(\n options.failOnError,\n `$convert cannot convert from object to ${expr.to} with no onError value`\n );\n return (0, import_internal.evalExpr)(obj, expr.onError, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $convert\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar isNumber_exports = {};\n__export(isNumber_exports, {\n $isNumber: () => $isNumber\n});\nmodule.exports = __toCommonJS(isNumber_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $isNumber = (obj, expr, options) => {\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n return (0, import_util.isNumber)(n);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $isNumber\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toDecimal_exports = {};\n__export(toDecimal_exports, {\n $toDecimal: () => $toDecimal\n});\nmodule.exports = __toCommonJS(toDecimal_exports);\nvar import_toDouble = require(\"./toDouble\");\nconst $toDecimal = import_toDouble.$toDouble;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toDecimal\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar type_exports = {};\n__export(type_exports, {\n $type: () => $type\n});\nmodule.exports = __toCommonJS(type_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"./_internal\");\nconst $type = (obj, expr, options) => {\n const v = (0, import_internal.evalExpr)(obj, expr, options);\n if (options.useStrictMode) {\n if (v === void 0) return \"missing\";\n if (v === true || v === false) return \"bool\";\n if ((0, import_util.isNumber)(v)) {\n if (v % 1 != 0) return \"double\";\n return v >= import_internal2.MIN_INT && v <= import_internal2.MAX_INT ? \"int\" : \"long\";\n }\n if ((0, import_util.isRegExp)(v)) return \"regex\";\n }\n return (0, import_util.typeOf)(v);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $type\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar type_exports = {};\nmodule.exports = __toCommonJS(type_exports);\n__reExport(type_exports, require(\"./convert\"), module.exports);\n__reExport(type_exports, require(\"./isNumber\"), module.exports);\n__reExport(type_exports, require(\"./toBool\"), module.exports);\n__reExport(type_exports, require(\"./toDate\"), module.exports);\n__reExport(type_exports, require(\"./toDecimal\"), module.exports);\n__reExport(type_exports, require(\"./toDouble\"), module.exports);\n__reExport(type_exports, require(\"./toInt\"), module.exports);\n__reExport(type_exports, require(\"./toLong\"), module.exports);\n__reExport(type_exports, require(\"./toString\"), module.exports);\n__reExport(type_exports, require(\"./type\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./convert\"),\n ...require(\"./isNumber\"),\n ...require(\"./toBool\"),\n ...require(\"./toDate\"),\n ...require(\"./toDecimal\"),\n ...require(\"./toDouble\"),\n ...require(\"./toInt\"),\n ...require(\"./toLong\"),\n ...require(\"./toString\"),\n ...require(\"./type\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toLower_exports = {};\n__export(toLower_exports, {\n $toLower: () => $toLower\n});\nmodule.exports = __toCommonJS(toLower_exports);\nvar import_internal = require(\"../../../util/_internal\");\nvar import_type = require(\"../type\");\nconst $toLower = (obj, expr, options) => {\n if ((0, import_internal.isArray)(expr) && expr.length === 1) expr = expr[0];\n const s = (0, import_type.$toString)(obj, expr, options);\n return s === null ? s : s.toLowerCase();\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toLower\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toUpper_exports = {};\n__export(toUpper_exports, {\n $toUpper: () => $toUpper\n});\nmodule.exports = __toCommonJS(toUpper_exports);\nvar import_util = require(\"../../../util\");\nvar import_type = require(\"../type\");\nconst $toUpper = (obj, expr, options) => {\n if ((0, import_util.isArray)(expr) && expr.length === 1) expr = expr[0];\n const s = (0, import_type.$toString)(obj, expr, options);\n return s === null ? s : s.toUpperCase();\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toUpper\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar trim_exports = {};\n__export(trim_exports, {\n $trim: () => $trim\n});\nmodule.exports = __toCommonJS(trim_exports);\nvar import_internal = require(\"./_internal\");\nconst $trim = (obj, expr, options) => {\n return (0, import_internal.trimString)(obj, expr, options, { left: true, right: true });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $trim\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar string_exports = {};\nmodule.exports = __toCommonJS(string_exports);\n__reExport(string_exports, require(\"./concat\"), module.exports);\n__reExport(string_exports, require(\"./indexOfBytes\"), module.exports);\n__reExport(string_exports, require(\"./ltrim\"), module.exports);\n__reExport(string_exports, require(\"./regexFind\"), module.exports);\n__reExport(string_exports, require(\"./regexFindAll\"), module.exports);\n__reExport(string_exports, require(\"./regexMatch\"), module.exports);\n__reExport(string_exports, require(\"./replaceAll\"), module.exports);\n__reExport(string_exports, require(\"./replaceOne\"), module.exports);\n__reExport(string_exports, require(\"./rtrim\"), module.exports);\n__reExport(string_exports, require(\"./split\"), module.exports);\n__reExport(string_exports, require(\"./strcasecmp\"), module.exports);\n__reExport(string_exports, require(\"./strLenBytes\"), module.exports);\n__reExport(string_exports, require(\"./strLenCP\"), module.exports);\n__reExport(string_exports, require(\"./substr\"), module.exports);\n__reExport(string_exports, require(\"./substrBytes\"), module.exports);\n__reExport(string_exports, require(\"./substrCP\"), module.exports);\n__reExport(string_exports, require(\"./toLower\"), module.exports);\n__reExport(string_exports, require(\"./toUpper\"), module.exports);\n__reExport(string_exports, require(\"./trim\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./concat\"),\n ...require(\"./indexOfBytes\"),\n ...require(\"./ltrim\"),\n ...require(\"./regexFind\"),\n ...require(\"./regexFindAll\"),\n ...require(\"./regexMatch\"),\n ...require(\"./replaceAll\"),\n ...require(\"./replaceOne\"),\n ...require(\"./rtrim\"),\n ...require(\"./split\"),\n ...require(\"./strcasecmp\"),\n ...require(\"./strLenBytes\"),\n ...require(\"./strLenCP\"),\n ...require(\"./substr\"),\n ...require(\"./substrBytes\"),\n ...require(\"./substrCP\"),\n ...require(\"./toLower\"),\n ...require(\"./toUpper\"),\n ...require(\"./trim\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar toHashedIndexKey_exports = {};\n__export(toHashedIndexKey_exports, {\n $toHashedIndexKey: () => $toHashedIndexKey\n});\nmodule.exports = __toCommonJS(toHashedIndexKey_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nconst $toHashedIndexKey = (obj, expr, options) => (0, import_util.hashCode)((0, import_internal.evalExpr)(obj, expr, options));\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $toHashedIndexKey\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n processOperator: () => processOperator\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nvar import_internal2 = require(\"../_internal\");\nfunction processOperator(obj, expr, options, fn, fixedPoints) {\n const fp = {\n undefined: null,\n null: null,\n NaN: NaN,\n Infinity: new Error(),\n \"-Infinity\": new Error(),\n ...fixedPoints\n };\n const foe = options.failOnError;\n const op = fn.name;\n const n = (0, import_internal.evalExpr)(obj, expr, options);\n if (n in fp) {\n const res = fp[n];\n if (res instanceof Error)\n return (0, import_internal2.errExpectNumber)(foe, `$${op} invalid input '${n}'`);\n return res;\n }\n if (!(0, import_util.isNumber)(n)) return (0, import_internal2.errExpectNumber)(foe, `$${op}`);\n return fn(n);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n processOperator\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar acos_exports = {};\n__export(acos_exports, {\n $acos: () => $acos\n});\nmodule.exports = __toCommonJS(acos_exports);\nvar import_internal = require(\"./_internal\");\nconst $acos = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.acos, {\n Infinity: Infinity,\n 0: new Error()\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $acos\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar acosh_exports = {};\n__export(acosh_exports, {\n $acosh: () => $acosh\n});\nmodule.exports = __toCommonJS(acosh_exports);\nvar import_internal = require(\"./_internal\");\nconst $acosh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.acosh, {\n Infinity: Infinity,\n 0: new Error()\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $acosh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar asin_exports = {};\n__export(asin_exports, {\n $asin: () => $asin\n});\nmodule.exports = __toCommonJS(asin_exports);\nvar import_internal = require(\"./_internal\");\nconst $asin = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.asin);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $asin\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar asinh_exports = {};\n__export(asinh_exports, {\n $asinh: () => $asinh\n});\nmodule.exports = __toCommonJS(asinh_exports);\nvar import_internal = require(\"./_internal\");\nconst $asinh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.asinh, {\n Infinity: Infinity,\n \"-Infinity\": -Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $asinh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar atan_exports = {};\n__export(atan_exports, {\n $atan: () => $atan\n});\nmodule.exports = __toCommonJS(atan_exports);\nvar import_internal = require(\"./_internal\");\nconst $atan = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.atan);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $atan\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar atan2_exports = {};\n__export(atan2_exports, {\n $atan2: () => $atan2\n});\nmodule.exports = __toCommonJS(atan2_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_util = require(\"../../../util\");\nconst $atan2 = (obj, expr, options) => {\n const [y, x] = (0, import_internal.evalExpr)(obj, expr, options);\n if (isNaN(y) || (0, import_util.isNil)(y)) return y;\n if (isNaN(x) || (0, import_util.isNil)(x)) return x;\n return Math.atan2(y, x);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $atan2\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar atanh_exports = {};\n__export(atanh_exports, {\n $atanh: () => $atanh\n});\nmodule.exports = __toCommonJS(atanh_exports);\nvar import_internal = require(\"./_internal\");\nconst $atanh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.atanh, {\n 1: Infinity,\n \"-1\": -Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $atanh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cos_exports = {};\n__export(cos_exports, {\n $cos: () => $cos\n});\nmodule.exports = __toCommonJS(cos_exports);\nvar import_internal = require(\"./_internal\");\nconst $cos = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.cos);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $cos\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar cosh_exports = {};\n__export(cosh_exports, {\n $cosh: () => $cosh\n});\nmodule.exports = __toCommonJS(cosh_exports);\nvar import_internal = require(\"./_internal\");\nconst $cosh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.cosh, {\n \"-Infinity\": Infinity,\n Infinity: Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $cosh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar degreesToRadians_exports = {};\n__export(degreesToRadians_exports, {\n $degreesToRadians: () => $degreesToRadians\n});\nmodule.exports = __toCommonJS(degreesToRadians_exports);\nvar import_internal = require(\"./_internal\");\nconst degreesToRadians = (n) => n * (Math.PI / 180);\nconst $degreesToRadians = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, degreesToRadians, {\n Infinity: Infinity,\n \"-Infinity\": Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $degreesToRadians\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar radiansToDegrees_exports = {};\n__export(radiansToDegrees_exports, {\n $radiansToDegrees: () => $radiansToDegrees\n});\nmodule.exports = __toCommonJS(radiansToDegrees_exports);\nvar import_internal = require(\"./_internal\");\nconst radiansToDegrees = (n) => n * (180 / Math.PI);\nconst $radiansToDegrees = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, radiansToDegrees, {\n Infinity: Infinity,\n \"-Infinity\": Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $radiansToDegrees\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sin_exports = {};\n__export(sin_exports, {\n $sin: () => $sin\n});\nmodule.exports = __toCommonJS(sin_exports);\nvar import_internal = require(\"./_internal\");\nconst $sin = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.sin);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sin\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sinh_exports = {};\n__export(sinh_exports, {\n $sinh: () => $sinh\n});\nmodule.exports = __toCommonJS(sinh_exports);\nvar import_internal = require(\"./_internal\");\nconst $sinh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.sinh, {\n \"-Infinity\": -Infinity,\n Infinity: Infinity\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sinh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar tan_exports = {};\n__export(tan_exports, {\n $tan: () => $tan\n});\nmodule.exports = __toCommonJS(tan_exports);\nvar import_internal = require(\"./_internal\");\nconst $tan = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.tan);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $tan\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar tanh_exports = {};\n__export(tanh_exports, {\n $tanh: () => $tanh\n});\nmodule.exports = __toCommonJS(tanh_exports);\nvar import_internal = require(\"./_internal\");\nconst $tanh = (obj, expr, options) => (0, import_internal.processOperator)(obj, expr, options, Math.tanh, {\n Infinity: 1,\n \"-Infinity\": -1\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $tanh\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar trignometry_exports = {};\nmodule.exports = __toCommonJS(trignometry_exports);\n__reExport(trignometry_exports, require(\"./acos\"), module.exports);\n__reExport(trignometry_exports, require(\"./acosh\"), module.exports);\n__reExport(trignometry_exports, require(\"./asin\"), module.exports);\n__reExport(trignometry_exports, require(\"./asinh\"), module.exports);\n__reExport(trignometry_exports, require(\"./atan\"), module.exports);\n__reExport(trignometry_exports, require(\"./atan2\"), module.exports);\n__reExport(trignometry_exports, require(\"./atanh\"), module.exports);\n__reExport(trignometry_exports, require(\"./cos\"), module.exports);\n__reExport(trignometry_exports, require(\"./cosh\"), module.exports);\n__reExport(trignometry_exports, require(\"./degreesToRadians\"), module.exports);\n__reExport(trignometry_exports, require(\"./radiansToDegrees\"), module.exports);\n__reExport(trignometry_exports, require(\"./sin\"), module.exports);\n__reExport(trignometry_exports, require(\"./sinh\"), module.exports);\n__reExport(trignometry_exports, require(\"./tan\"), module.exports);\n__reExport(trignometry_exports, require(\"./tanh\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./acos\"),\n ...require(\"./acosh\"),\n ...require(\"./asin\"),\n ...require(\"./asinh\"),\n ...require(\"./atan\"),\n ...require(\"./atan2\"),\n ...require(\"./atanh\"),\n ...require(\"./cos\"),\n ...require(\"./cosh\"),\n ...require(\"./degreesToRadians\"),\n ...require(\"./radiansToDegrees\"),\n ...require(\"./sin\"),\n ...require(\"./sinh\"),\n ...require(\"./tan\"),\n ...require(\"./tanh\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar let_exports = {};\n__export(let_exports, {\n $let: () => $let\n});\nmodule.exports = __toCommonJS(let_exports);\nvar import_internal = require(\"../../../core/_internal\");\nconst $let = (obj, expr, options) => {\n const variables = {};\n for (const key of Object.keys(expr.vars)) {\n variables[key] = (0, import_internal.evalExpr)(obj, expr.vars[key], options);\n }\n return (0, import_internal.evalExpr)(\n obj,\n expr.in,\n import_internal.ComputeOptions.init(options).update({ variables })\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $let\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar variable_exports = {};\nmodule.exports = __toCommonJS(variable_exports);\n__reExport(variable_exports, require(\"./let\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./let\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar expression_exports = {};\nmodule.exports = __toCommonJS(expression_exports);\n__reExport(expression_exports, require(\"./arithmetic\"), module.exports);\n__reExport(expression_exports, require(\"./array\"), module.exports);\n__reExport(expression_exports, require(\"./bitwise\"), module.exports);\n__reExport(expression_exports, require(\"./boolean\"), module.exports);\n__reExport(expression_exports, require(\"./comparison\"), module.exports);\n__reExport(expression_exports, require(\"./conditional\"), module.exports);\n__reExport(expression_exports, require(\"./custom\"), module.exports);\n__reExport(expression_exports, require(\"./date\"), module.exports);\n__reExport(expression_exports, require(\"./literal\"), module.exports);\n__reExport(expression_exports, require(\"./median\"), module.exports);\n__reExport(expression_exports, require(\"./misc\"), module.exports);\n__reExport(expression_exports, require(\"./object\"), module.exports);\n__reExport(expression_exports, require(\"./percentile\"), module.exports);\n__reExport(expression_exports, require(\"./set\"), module.exports);\n__reExport(expression_exports, require(\"./string\"), module.exports);\n__reExport(expression_exports, require(\"./toHashedIndexKey\"), module.exports);\n__reExport(expression_exports, require(\"./trignometry\"), module.exports);\n__reExport(expression_exports, require(\"./type\"), module.exports);\n__reExport(expression_exports, require(\"./variable\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./arithmetic\"),\n ...require(\"./array\"),\n ...require(\"./bitwise\"),\n ...require(\"./boolean\"),\n ...require(\"./comparison\"),\n ...require(\"./conditional\"),\n ...require(\"./custom\"),\n ...require(\"./date\"),\n ...require(\"./literal\"),\n ...require(\"./median\"),\n ...require(\"./misc\"),\n ...require(\"./object\"),\n ...require(\"./percentile\"),\n ...require(\"./set\"),\n ...require(\"./string\"),\n ...require(\"./toHashedIndexKey\"),\n ...require(\"./trignometry\"),\n ...require(\"./type\"),\n ...require(\"./variable\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar addFields_exports = {};\n__export(addFields_exports, {\n $addFields: () => $addFields\n});\nmodule.exports = __toCommonJS(addFields_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nfunction $addFields(coll, expr, options) {\n const newFields = Object.keys(expr);\n if (newFields.length === 0) return coll;\n return coll.map((obj) => {\n const newObj = { ...obj };\n for (const field of newFields) {\n const newValue = (0, import_internal.evalExpr)(obj, expr[field], options);\n if (newValue !== void 0) {\n (0, import_util.setValue)(newObj, field, newValue);\n } else {\n (0, import_util.removeValue)(newObj, field);\n }\n }\n return newObj;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $addFields\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bucket_exports = {};\n__export(bucket_exports, {\n $bucket: () => $bucket\n});\nmodule.exports = __toCommonJS(bucket_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $bucket(coll, expr, options) {\n const bounds = expr.boundaries.slice();\n const defaultKey = expr.default;\n const lower = bounds[0];\n const upper = bounds[bounds.length - 1];\n const outputExpr = expr.output || { count: { $sum: 1 } };\n (0, import_util.assert)(bounds.length > 1, \"$bucket: must specify at least two boundaries.\");\n const isValid = bounds.every(\n (v, i) => i === 0 || (0, import_util.typeOf)(v) === (0, import_util.typeOf)(bounds[i - 1]) && (0, import_util.compare)(v, bounds[i - 1]) > 0\n );\n (0, import_util.assert)(\n isValid,\n `$bucket: bounds must be of same type and in ascending order`\n );\n (0, import_util.assert)(\n (0, import_util.isNil)(defaultKey) || (0, import_util.typeOf)(defaultKey) !== (0, import_util.typeOf)(lower) || (0, import_util.compare)(defaultKey, upper) >= 0 || (0, import_util.compare)(defaultKey, lower) < 0,\n \"$bucket: 'default' expression must be out of boundaries range\"\n );\n const createBuckets = () => {\n const buckets = /* @__PURE__ */ new Map();\n for (let i = 0; i < bounds.length - 1; i++) {\n buckets.set(bounds[i], []);\n }\n if (!(0, import_util.isNil)(defaultKey)) buckets.set(defaultKey, []);\n coll.each((obj) => {\n const key = (0, import_internal.evalExpr)(obj, expr.groupBy, options);\n if ((0, import_util.isNil)(key) || (0, import_util.compare)(key, lower) < 0 || (0, import_util.compare)(key, upper) >= 0) {\n (0, import_util.assert)(\n !(0, import_util.isNil)(defaultKey),\n \"$bucket require a default for out of range values\"\n );\n buckets.get(defaultKey)?.push(obj);\n } else {\n (0, import_util.assert)(\n (0, import_util.compare)(key, lower) >= 0 && (0, import_util.compare)(key, upper) < 0,\n \"$bucket 'groupBy' expression must resolve to a value in range of boundaries\"\n );\n const index = (0, import_util.findInsertIndex)(bounds, key);\n const boundKey = bounds[Math.max(0, index - 1)];\n buckets.get(boundKey)?.push(obj);\n }\n });\n bounds.pop();\n if (!(0, import_util.isNil)(defaultKey)) {\n if (buckets.get(defaultKey)?.length) bounds.push(defaultKey);\n else buckets.delete(defaultKey);\n }\n (0, import_util.assert)(\n buckets.size === bounds.length,\n \"bounds and groups must be of equal size.\"\n );\n return (0, import_lazy.Lazy)(bounds).map((key) => {\n return {\n ...(0, import_internal.evalExpr)(buckets.get(key), outputExpr, options),\n _id: key\n };\n });\n };\n let iterator;\n return (0, import_lazy.Lazy)(() => {\n if (!iterator) iterator = createBuckets();\n return iterator.next();\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bucket\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bucketAuto_exports = {};\n__export(bucketAuto_exports, {\n $bucketAuto: () => $bucketAuto\n});\nmodule.exports = __toCommonJS(bucketAuto_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $bucketAuto(coll, expr, options) {\n const {\n buckets: bucketCount,\n groupBy: groupByExpr,\n output: optOutputExpr,\n // Available only if the all groupBy values are numeric and none of them are NaN.\n granularity\n } = expr;\n const outputExpr = optOutputExpr ?? { count: { $sum: 1 } };\n (0, import_util.assert)(\n bucketCount > 0,\n `$bucketAuto: 'buckets' field must be greater than 0, but found: ${bucketCount}`\n );\n if (granularity) {\n (0, import_util.assert)(\n /^(POWERSOF2|1-2-5|E(6|12|24|48|96|192)|R(5|10|20|40|80))$/.test(\n granularity\n ),\n `$bucketAuto: invalid granularity '${granularity}'.`\n );\n }\n const keyMap = /* @__PURE__ */ new Map();\n const setKey = !granularity ? (o, k) => keyMap.set(o, k) : (_, _2) => {\n };\n const sorted = coll.map((o) => {\n const k = (0, import_internal.evalExpr)(o, groupByExpr, options) ?? null;\n (0, import_util.assert)(\n !granularity || (0, import_util.isNumber)(k),\n \"$bucketAuto: groupBy values must be numeric when granularity is specified.\"\n );\n setKey(o, k ?? null);\n return [k ?? null, o];\n }).collect();\n sorted.sort((x, y) => {\n if ((0, import_util.isNil)(x[0])) return -1;\n if ((0, import_util.isNil)(y[0])) return 1;\n return (0, import_util.compare)(x[0], y[0]);\n });\n let getNext;\n if (!granularity) {\n getNext = granularityDefault(sorted, bucketCount, keyMap);\n } else if (granularity == \"POWERSOF2\") {\n getNext = granularityPowerOfTwo(\n sorted,\n bucketCount\n );\n } else {\n getNext = granularityPreferredSeries(\n sorted,\n bucketCount,\n granularity\n );\n }\n let terminate = false;\n return (0, import_lazy.Lazy)(() => {\n if (terminate) return { done: true };\n const { min, max, bucket, done } = getNext();\n terminate = done;\n const outFields = (0, import_internal.evalExpr)(bucket, outputExpr, options);\n for (const k of Object.keys(outFields)) {\n const v = outFields[k];\n if ((0, import_util.isArray)(v)) outFields[k] = v.filter((v2) => !(0, import_util.isNil)(v2));\n }\n return {\n done: false,\n value: {\n ...outFields,\n _id: { min, max }\n }\n };\n });\n}\nfunction granularityDefault(sorted, bucketCount, keyMap) {\n const size = sorted.length;\n const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount));\n let index = 0;\n let nBuckets = 0;\n return () => {\n const isLastBucket = ++nBuckets == bucketCount;\n const bucket = new Array();\n while (index < size && (isLastBucket || bucket.length < approxBucketSize || index > 0 && (0, import_util.isEqual)(sorted[index - 1][0], sorted[index][0]))) {\n bucket.push(sorted[index++][1]);\n }\n const min = keyMap.get(bucket[0]);\n let max;\n if (index < size) {\n max = sorted[index][0];\n } else {\n max = keyMap.get(bucket[bucket.length - 1]);\n }\n (0, import_util.assert)(\n (0, import_util.isNil)(max) || (0, import_util.isNil)(min) || (0, import_util.compare)(min, max) <= 0,\n `error: $bucketAuto boundary must be in order.`\n );\n return {\n min,\n max,\n bucket,\n done: index >= size\n };\n };\n}\nfunction granularityPowerOfTwo(sorted, bucketCount) {\n const size = sorted.length;\n const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount));\n const roundUp2 = (n) => n === 0 ? 0 : 2 ** (Math.floor(Math.log2(n)) + 1);\n let index = 0;\n let min = 0;\n let max = 0;\n return () => {\n const bucket = new Array();\n const boundValue = roundUp2(max);\n min = index > 0 ? max : 0;\n while (bucket.length < approxBucketSize && index < size && (max === 0 || sorted[index][0] < boundValue)) {\n bucket.push(sorted[index++][1]);\n }\n max = max == 0 ? roundUp2(sorted[index - 1][0]) : boundValue;\n while (index < size && sorted[index][0] < max) {\n bucket.push(sorted[index++][1]);\n }\n return {\n min,\n max,\n bucket,\n done: index >= size\n };\n };\n}\nconst PREFERRED_NUMBERS = {\n // \"Least rounded\" Renard number series, taken from Wikipedia page on preferred\n // numbers: https://en.wikipedia.org/wiki/Preferred_number#Renard_numbers\n R5: [10, 16, 25, 40, 63],\n R10: [100, 125, 160, 200, 250, 315, 400, 500, 630, 800],\n R20: [\n 100,\n 112,\n 125,\n 140,\n 160,\n 180,\n 200,\n 224,\n 250,\n 280,\n 315,\n 355,\n 400,\n 450,\n 500,\n 560,\n 630,\n 710,\n 800,\n 900\n ],\n R40: [\n 100,\n 106,\n 112,\n 118,\n 125,\n 132,\n 140,\n 150,\n 160,\n 170,\n 180,\n 190,\n 200,\n 212,\n 224,\n 236,\n 250,\n 265,\n 280,\n 300,\n 315,\n 355,\n 375,\n 400,\n 425,\n 450,\n 475,\n 500,\n 530,\n 560,\n 600,\n 630,\n 670,\n 710,\n 750,\n 800,\n 850,\n 900,\n 950\n ],\n R80: [\n 103,\n 109,\n 115,\n 122,\n 128,\n 136,\n 145,\n 155,\n 165,\n 175,\n 185,\n 195,\n 206,\n 218,\n 230,\n 243,\n 258,\n 272,\n 290,\n 307,\n 325,\n 345,\n 365,\n 387,\n 412,\n 437,\n 462,\n 487,\n 515,\n 545,\n 575,\n 615,\n 650,\n 690,\n 730,\n 775,\n 825,\n 875,\n 925,\n 975\n ],\n // https://en.wikipedia.org/wiki/Preferred_number#1-2-5_series\n \"1-2-5\": [10, 20, 50],\n // E series, taken from Wikipedia page on preferred numbers:\n // https://en.wikipedia.org/wiki/Preferred_number#E_series\n E6: [10, 15, 22, 33, 47, 68],\n E12: [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82],\n E24: [\n 10,\n 11,\n 12,\n 13,\n 15,\n 16,\n 18,\n 20,\n 22,\n 24,\n 27,\n 30,\n 33,\n 36,\n 39,\n 43,\n 47,\n 51,\n 56,\n 62,\n 68,\n 75,\n 82,\n 91\n ],\n E48: [\n 100,\n 105,\n 110,\n 115,\n 121,\n 127,\n 133,\n 140,\n 147,\n 154,\n 162,\n 169,\n 178,\n 187,\n 196,\n 205,\n 215,\n 226,\n 237,\n 249,\n 261,\n 274,\n 287,\n 301,\n 316,\n 332,\n 348,\n 365,\n 383,\n 402,\n 422,\n 442,\n 464,\n 487,\n 511,\n 536,\n 562,\n 590,\n 619,\n 649,\n 681,\n 715,\n 750,\n 787,\n 825,\n 866,\n 909,\n 953\n ],\n E96: [\n 100,\n 102,\n 105,\n 107,\n 110,\n 113,\n 115,\n 118,\n 121,\n 124,\n 127,\n 130,\n 133,\n 137,\n 140,\n 143,\n 147,\n 150,\n 154,\n 158,\n 162,\n 165,\n 169,\n 174,\n 178,\n 182,\n 187,\n 191,\n 196,\n 200,\n 205,\n 210,\n 215,\n 221,\n 226,\n 232,\n 237,\n 243,\n 249,\n 255,\n 261,\n 267,\n 274,\n 280,\n 287,\n 294,\n 301,\n 309,\n 316,\n 324,\n 332,\n 340,\n 348,\n 357,\n 365,\n 374,\n 383,\n 392,\n 402,\n 412,\n 422,\n 432,\n 442,\n 453,\n 464,\n 475,\n 487,\n 499,\n 511,\n 523,\n 536,\n 549,\n 562,\n 576,\n 590,\n 604,\n 619,\n 634,\n 649,\n 665,\n 681,\n 698,\n 715,\n 732,\n 750,\n 768,\n 787,\n 806,\n 825,\n 845,\n 866,\n 887,\n 909,\n 931,\n 953,\n 976\n ],\n E192: [\n 100,\n 101,\n 102,\n 104,\n 105,\n 106,\n 107,\n 109,\n 110,\n 111,\n 113,\n 114,\n 115,\n 117,\n 118,\n 120,\n 121,\n 123,\n 124,\n 126,\n 127,\n 129,\n 130,\n 132,\n 133,\n 135,\n 137,\n 138,\n 140,\n 142,\n 143,\n 145,\n 147,\n 149,\n 150,\n 152,\n 154,\n 156,\n 158,\n 160,\n 162,\n 164,\n 165,\n 167,\n 169,\n 172,\n 174,\n 176,\n 178,\n 180,\n 182,\n 184,\n 187,\n 189,\n 191,\n 193,\n 196,\n 198,\n 200,\n 203,\n 205,\n 208,\n 210,\n 213,\n 215,\n 218,\n 221,\n 223,\n 226,\n 229,\n 232,\n 234,\n 237,\n 240,\n 243,\n 246,\n 249,\n 252,\n 255,\n 258,\n 261,\n 264,\n 267,\n 271,\n 274,\n 277,\n 280,\n 284,\n 287,\n 291,\n 294,\n 298,\n 301,\n 305,\n 309,\n 312,\n 316,\n 320,\n 324,\n 328,\n 332,\n 336,\n 340,\n 344,\n 348,\n 352,\n 357,\n 361,\n 365,\n 370,\n 374,\n 379,\n 383,\n 388,\n 392,\n 397,\n 402,\n 407,\n 412,\n 417,\n 422,\n 427,\n 432,\n 437,\n 442,\n 448,\n 453,\n 459,\n 464,\n 470,\n 475,\n 481,\n 487,\n 493,\n 499,\n 505,\n 511,\n 517,\n 523,\n 530,\n 536,\n 542,\n 549,\n 556,\n 562,\n 569,\n 576,\n 583,\n 590,\n 597,\n 604,\n 612,\n 619,\n 626,\n 634,\n 642,\n 649,\n 657,\n 665,\n 673,\n 681,\n 690,\n 698,\n 706,\n 715,\n 723,\n 732,\n 741,\n 750,\n 759,\n 768,\n 777,\n 787,\n 796,\n 806,\n 816,\n 825,\n 835,\n 845,\n 856,\n 866,\n 876,\n 887,\n 898,\n 909,\n 920,\n 931,\n 942,\n 953,\n 965,\n 976,\n 988\n ]\n};\nconst roundUp = (n, granularity) => {\n if (n == 0) return 0;\n const series = PREFERRED_NUMBERS[granularity];\n const first = series[0];\n const last = series[series.length - 1];\n let multiplier = 1;\n while (n >= last * multiplier) {\n multiplier *= 10;\n }\n let previousMin = 0;\n while (n < first * multiplier) {\n previousMin = first * multiplier;\n multiplier /= 10;\n if (n >= last * multiplier) {\n return previousMin;\n }\n }\n (0, import_util.assert)(\n n >= first * multiplier && n < last * multiplier,\n \"$bucketAuto: number out of range of series.\"\n );\n const i = (0, import_util.findInsertIndex)(series, n, (a, b) => {\n b *= multiplier;\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n });\n const seriesNumber = series[i] * multiplier;\n return n == seriesNumber ? series[i + 1] * multiplier : seriesNumber;\n};\nfunction granularityPreferredSeries(sorted, bucketCount, granularity) {\n const size = sorted.length;\n const approxBucketSize = Math.max(1, Math.round(sorted.length / bucketCount));\n let index = 0;\n let nBuckets = 0;\n let min = 0;\n let max = 0;\n return () => {\n const isLastBucket = ++nBuckets == bucketCount;\n const bucket = new Array();\n min = index > 0 ? max : 0;\n while (index < size && (isLastBucket || bucket.length < approxBucketSize)) {\n bucket.push(sorted[index++][1]);\n }\n max = roundUp(sorted[index - 1][0], granularity);\n const nItems = bucket.length;\n while (index < size && (isLastBucket || sorted[index][0] < max)) {\n bucket.push(sorted[index++][1]);\n }\n if (nItems != bucket.length) {\n max = roundUp(sorted[index - 1][0], granularity);\n }\n (0, import_util.assert)(min < max, `$bucketAuto: ${min} < ${max}.`);\n return { min, max, bucket, done: index >= size };\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bucketAuto\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar count_exports = {};\n__export(count_exports, {\n $count: () => $count\n});\nmodule.exports = __toCommonJS(count_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nfunction $count(coll, expr, _options) {\n (0, import_util.assert)(\n (0, import_util.isString)(expr) && expr.trim().length > 0 && !expr.includes(\".\") && expr[0] !== \"$\",\n \"$count expression must evaluate to valid field name\"\n );\n let i = 0;\n return (0, import_lazy.Lazy)(() => {\n if (i++ == 0) return { value: { [expr]: coll.size() }, done: false };\n return { done: true };\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $count\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar densify_exports = {};\n__export(densify_exports, {\n $densify: () => $densify\n});\nmodule.exports = __toCommonJS(densify_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"../expression/date/_internal\");\nvar import_dateAdd = require(\"../expression/date/dateAdd\");\nvar import_sort = require(\"./sort\");\nconst OP = \"$densify\";\nfunction $densify(coll, expr, options) {\n const { step, bounds, unit } = expr.range;\n if (unit) {\n (0, import_util.assert)(\n import_internal.TIME_UNITS.includes(unit),\n `${OP} 'range.unit' value is not supported.`\n );\n (0, import_util.assert)(\n (0, import_util.isInteger)(step) && step > 0,\n `${OP} 'range.step' must resolve to integer if 'range.unit' is specified.`\n );\n } else {\n (0, import_util.assert)((0, import_util.isNumber)(step), `${OP} 'range.step' must resolve to number.`);\n }\n if ((0, import_util.isArray)(bounds)) {\n (0, import_util.assert)(\n !!bounds && bounds.length === 2,\n `${OP} 'range.bounds' must have exactly two elements.`\n );\n (0, import_util.assert)(\n (bounds.every(import_util.isNumber) || bounds.every(import_util.isDate)) && bounds[0] < bounds[1],\n `${OP} 'range.bounds' must be ordered lower then upper.`\n );\n if (unit) {\n (0, import_util.assert)(\n bounds.every(import_util.isDate),\n `${OP} 'range.bounds' must be dates if 'range.unit' is specified.`\n );\n }\n }\n if (expr.partitionByFields) {\n (0, import_util.assert)(\n (0, import_util.isArray)(expr.partitionByFields),\n `${OP} 'partitionByFields' must resolve to array of strings.`\n );\n }\n const partitionByFields = expr.partitionByFields ?? [];\n coll = (0, import_sort.$sort)(coll, { [expr.field]: 1 }, options);\n const computeNextValue = (value) => {\n return (0, import_util.isNumber)(value) ? value + step : (0, import_dateAdd.$dateAdd)({}, { startDate: value, unit, amount: step }, options);\n };\n const isValidUnit = !!unit && import_internal.TIME_UNITS.includes(unit);\n const getFieldValue = (o) => {\n const v = (0, import_util.resolve)(o, expr.field);\n (0, import_util.assert)(\n (0, import_util.isNil)(v) || (0, import_util.isDate)(v) && isValidUnit || (0, import_util.isNumber)(v) && !isValidUnit,\n `${OP} Densify field type must be numeric with 'unit' unspecified, or a date with 'unit' specified.`\n );\n return v;\n };\n const peekItem = new Array();\n const nilFieldsIterator = (0, import_lazy.Lazy)(() => {\n const item = coll.next();\n const fieldValue = getFieldValue(item.value);\n if ((0, import_util.isNil)(fieldValue)) return item;\n peekItem.push(item);\n return { done: true };\n });\n const nextDensifyValueMap = import_util.HashMap.init();\n const [lower, upper] = (0, import_util.isArray)(bounds) ? bounds : [bounds, bounds];\n let maxFieldValue;\n const updateMaxFieldValue = (value) => {\n maxFieldValue = maxFieldValue === void 0 || maxFieldValue < value ? value : maxFieldValue;\n };\n const rootKey = [];\n const densifyIterator = (0, import_lazy.Lazy)(() => {\n const item = peekItem.pop() || coll.next();\n if (item.done) return item;\n let partitionKey = rootKey;\n if ((0, import_util.isArray)(partitionByFields)) {\n partitionKey = partitionByFields.map(\n (k) => (0, import_util.resolve)(item.value, k)\n );\n (0, import_util.assert)(\n partitionKey.every(import_util.isString),\n \"$densify: Partition fields must evaluate to string values.\"\n );\n }\n (0, import_util.assert)((0, import_util.isObject)(item.value), \"$densify: collection must contain documents\");\n const itemValue = getFieldValue(item.value);\n if (!nextDensifyValueMap.has(partitionKey)) {\n if (lower == \"full\") {\n if (!nextDensifyValueMap.has(rootKey)) {\n nextDensifyValueMap.set(rootKey, itemValue);\n }\n nextDensifyValueMap.set(\n partitionKey,\n nextDensifyValueMap.get(rootKey)\n );\n } else if (lower == \"partition\") {\n nextDensifyValueMap.set(partitionKey, itemValue);\n } else {\n nextDensifyValueMap.set(partitionKey, lower);\n }\n }\n const densifyValue = nextDensifyValueMap.get(partitionKey);\n if (\n // current item field value is lower than current densify value.\n itemValue <= densifyValue || // range value equals or exceeds upper bound\n upper != \"full\" && upper != \"partition\" && densifyValue >= upper\n ) {\n if (densifyValue <= itemValue) {\n nextDensifyValueMap.set(partitionKey, computeNextValue(densifyValue));\n }\n updateMaxFieldValue(itemValue);\n return item;\n }\n nextDensifyValueMap.set(partitionKey, computeNextValue(densifyValue));\n updateMaxFieldValue(densifyValue);\n const denseObj = { [expr.field]: densifyValue };\n if (partitionKey) {\n for (let i = 0; i < partitionKey.length; i++) {\n denseObj[partitionByFields[i]] = partitionKey[i];\n }\n }\n peekItem.push(item);\n return { done: false, value: denseObj };\n });\n if (lower !== \"full\") return (0, import_lazy.concat)(nilFieldsIterator, densifyIterator);\n let paritionIndex = -1;\n let partitionKeysSet;\n const fullBoundsIterator = (0, import_lazy.Lazy)(() => {\n if (paritionIndex === -1) {\n const fullDensifyValue = nextDensifyValueMap.get(rootKey);\n nextDensifyValueMap.delete(rootKey);\n partitionKeysSet = Array.from(nextDensifyValueMap.keys());\n if (partitionKeysSet.length === 0) {\n partitionKeysSet.push(rootKey);\n nextDensifyValueMap.set(rootKey, fullDensifyValue);\n }\n paritionIndex++;\n }\n do {\n const partitionKey = partitionKeysSet[paritionIndex];\n const partitionMaxValue = nextDensifyValueMap.get(partitionKey);\n if (partitionMaxValue < maxFieldValue) {\n nextDensifyValueMap.set(\n partitionKey,\n computeNextValue(partitionMaxValue)\n );\n const denseObj = { [expr.field]: partitionMaxValue };\n for (let i = 0; i < partitionKey.length; i++) {\n denseObj[partitionByFields[i]] = partitionKey[i];\n }\n return { done: false, value: denseObj };\n }\n paritionIndex++;\n } while (paritionIndex < partitionKeysSet.length);\n return { done: true };\n });\n return (0, import_lazy.concat)(nilFieldsIterator, densifyIterator, fullBoundsIterator);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $densify\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar facet_exports = {};\n__export(facet_exports, {\n $facet: () => $facet\n});\nmodule.exports = __toCommonJS(facet_exports);\nvar import_aggregator = require(\"../../aggregator\");\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nfunction $facet(coll, expr, options) {\n if (!(options.processingMode & import_internal.ProcessingMode.CLONE_INPUT)) {\n options = {\n ...import_internal.ComputeOptions.init(options).options,\n processingMode: import_internal.ProcessingMode.CLONE_INPUT\n };\n }\n return coll.transform((arr) => {\n const o = {};\n for (const k of Object.keys(expr)) {\n o[k] = new import_aggregator.Aggregator(expr[k], options).run(arr);\n }\n return (0, import_lazy.Lazy)([o]);\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $facet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n cached: () => cached,\n rank: () => rank,\n withMemo: () => withMemo\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nconst memo = /* @__PURE__ */ new WeakMap();\nconst cached = (xs) => memo.has(xs);\nfunction withMemo(collection, expr, initialize, fn) {\n if (!memo.has(collection)) {\n memo.set(collection, {});\n }\n const data = memo.get(collection);\n if (!(expr.field in data)) {\n data[expr.field] = initialize();\n }\n let ok = false;\n try {\n const res = fn(data[expr.field]);\n ok = true;\n return res;\n } finally {\n if (!ok) {\n memo.delete(collection);\n } else if (expr.documentNumber === collection.length) {\n delete data[expr.field];\n if (Object.keys(data).length === 0) memo.delete(collection);\n }\n }\n}\nfunction rank(_, collection, expr, options, dense) {\n return withMemo(\n collection,\n expr,\n () => {\n const sortKey = \"$\" + Object.keys(expr.parentExpr.sortBy)[0];\n const values = (0, import_push.$push)(collection, sortKey, options);\n const groups = (0, import_util.groupBy)(\n values,\n ((_2, n) => values[n])\n );\n let i = 0;\n let offset = 0;\n for (const key of groups.keys()) {\n const len = groups.get(key).length;\n groups.set(key, [i++, offset]);\n offset += len;\n }\n return { values, groups };\n },\n ({ values, groups }) => {\n if (groups.size == collection.length) return expr.documentNumber;\n const current = values[expr.documentNumber - 1];\n const [i, n] = groups.get(current);\n return (dense ? i : n) + 1;\n }\n );\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n cached,\n rank,\n withMemo\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar linearFill_exports = {};\n__export(linearFill_exports, {\n $linearFill: () => $linearFill\n});\nmodule.exports = __toCommonJS(linearFill_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"./_internal\");\nconst interpolate = (x1, y1, x2, y2, x) => y1 + (x - x1) * ((y2 - y1) / (x2 - x1));\nconst $linearFill = (_, coll, expr, options) => {\n return (0, import_internal.withMemo)(\n coll,\n expr,\n () => {\n const sortKey = \"$\" + Object.keys(expr.parentExpr.sortBy)[0];\n const points = (0, import_push.$push)(coll, [sortKey, expr.inputExpr], options).filter((([\n x,\n _2\n ]) => (0, import_util.isNumber)(+x)));\n let lindex = -1;\n let rindex = 0;\n while (rindex < points.length) {\n while (lindex + 1 < points.length && (0, import_util.isNumber)(points[lindex + 1][1])) {\n lindex++;\n rindex = lindex;\n }\n while (rindex + 1 < points.length && !(0, import_util.isNumber)(points[rindex + 1][1])) {\n rindex++;\n }\n if (rindex + 1 >= points.length) break;\n rindex++;\n while (lindex + 1 < rindex) {\n points[lindex + 1][1] = interpolate(\n points[lindex][0],\n points[lindex][1],\n points[rindex][0],\n points[rindex][1],\n points[lindex + 1][0]\n );\n lindex++;\n }\n lindex = rindex;\n }\n return points.map(([_2, y]) => y);\n },\n (values) => values[expr.documentNumber - 1]\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $linearFill\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar locf_exports = {};\n__export(locf_exports, {\n $locf: () => $locf\n});\nmodule.exports = __toCommonJS(locf_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"./_internal\");\nconst $locf = (_, coll, expr, options) => {\n return (0, import_internal.withMemo)(\n coll,\n expr,\n () => {\n const values = (0, import_push.$push)(coll, expr.inputExpr, options);\n for (let i = 1; i < values.length; i++) {\n if ((0, import_util.isNil)(values[i])) values[i] = values[i - 1];\n }\n return values;\n },\n (series) => series[expr.documentNumber - 1]\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $locf\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar group_exports = {};\n__export(group_exports, {\n $group: () => $group\n});\nmodule.exports = __toCommonJS(group_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nconst ID_KEY = \"_id\";\nfunction $group(coll, expr, options) {\n (0, import_util.assert)((0, import_util.has)(expr, ID_KEY), \"$group specification must include an '_id'\");\n const idExpr = expr[ID_KEY];\n const copts = import_internal.ComputeOptions.init(options);\n const newFields = Object.keys(expr).filter((k) => k != ID_KEY);\n return coll.transform((items) => {\n const partitions = (0, import_util.groupBy)(items, (obj) => (0, import_internal.evalExpr)(obj, idExpr, options));\n let i = -1;\n const partitionKeys = Array.from(partitions.keys());\n return (0, import_lazy.Lazy)(() => {\n if (++i === partitions.size) return { done: true };\n const groupId = partitionKeys[i];\n const obj = {};\n if (groupId !== void 0) {\n obj[ID_KEY] = groupId;\n }\n for (const key of newFields) {\n obj[key] = (0, import_internal.evalExpr)(\n partitions.get(groupId),\n expr[key],\n copts.update({ root: null, groupId })\n );\n }\n return { value: obj, done: false };\n });\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $group\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar setWindowFields_exports = {};\n__export(setWindowFields_exports, {\n $setWindowFields: () => $setWindowFields\n});\nmodule.exports = __toCommonJS(setWindowFields_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_function = require(\"../expression/custom/function\");\nvar import_dateAdd = require(\"../expression/date/dateAdd\");\nvar import_addFields = require(\"./addFields\");\nvar import_group = require(\"./group\");\nvar import_sort = require(\"./sort\");\nconst SORT_REQUIRED_OPS = [\n \"$denseRank\",\n \"$documentNumber\",\n \"$first\",\n \"$last\",\n \"$linearFill\",\n \"$rank\",\n \"$shift\"\n];\nconst WINDOW_UNBOUNDED_OPS = [\n \"$denseRank\",\n \"$expMovingAvg\",\n \"$linearFill\",\n \"$locf\",\n \"$rank\",\n \"$shift\"\n];\nconst isUnbounded = (window) => {\n const boundary = window?.documents || window?.range;\n return !boundary || boundary[0] === \"unbounded\" && boundary[1] === \"unbounded\";\n};\nconst OP = \"$setWindowFields\";\nfunction $setWindowFields(coll, expr, options) {\n options = import_internal.ComputeOptions.init(options);\n options.context.addExpressionOps({ $function: import_function.$function });\n const operators = {};\n const outputFields = Object.keys(expr.output);\n for (const field of outputFields) {\n const outputExpr = expr.output[field];\n const keys = Object.keys(outputExpr);\n const op = keys.find(import_util.isOperator);\n const context = options.context;\n (0, import_util.assert)(\n op && (!!context.getOperator(import_internal.OpType.WINDOW, op) || !!context.getOperator(import_internal.OpType.ACCUMULATOR, op)),\n `${OP} '${op}' is not a valid window operator`\n );\n (0, import_util.assert)(\n keys.length > 0 && keys.length <= 2 && (keys.length == 1 || keys.includes(\"window\")),\n `${OP} 'output' option should have a single window operator.`\n );\n if (outputExpr?.window) {\n const { documents, range } = outputExpr.window;\n (0, import_util.assert)(\n (+!!documents ^ +!!range) === 1,\n \"'window' option supports only one of 'documents' or 'range'.\"\n );\n }\n operators[field] = op;\n }\n if (expr.sortBy) {\n coll = (0, import_sort.$sort)(coll, expr.sortBy, options);\n }\n coll = (0, import_group.$group)(\n coll,\n {\n _id: expr.partitionBy,\n items: { $push: \"$$CURRENT\" }\n },\n options\n );\n return coll.transform((partitions) => {\n const iterators = [];\n const outputConfig = [];\n for (const field of outputFields) {\n const outputExpr = expr.output[field];\n const op = operators[field];\n const config = {\n operatorName: op,\n func: {\n left: options.context.getOperator(import_internal.OpType.ACCUMULATOR, op),\n right: options.context.getOperator(import_internal.OpType.WINDOW, op)\n },\n args: outputExpr[op],\n field,\n window: outputExpr.window\n };\n const unbounded = isUnbounded(config.window);\n if (unbounded == false || SORT_REQUIRED_OPS.includes(op)) {\n const suffix = unbounded ? `'${op}'` : \"bounded window operations\";\n (0, import_util.assert)(expr.sortBy, `${OP} 'sortBy' is required for ${suffix}.`);\n }\n (0, import_util.assert)(\n unbounded || !WINDOW_UNBOUNDED_OPS.includes(op),\n `${OP} cannot use bounded window for operator '${op}'.`\n );\n outputConfig.push(config);\n }\n for (const group of partitions) {\n const items = group.items;\n let iterator = (0, import_lazy.Lazy)(items);\n const windowResultMap = {};\n for (const config of outputConfig) {\n const { func, args, field, window } = config;\n const makeResultFunc = (getItemsFn) => {\n let index = -1;\n return (obj) => {\n ++index;\n if (func.left) {\n return func.left(getItemsFn(obj, index), args, options);\n } else if (func.right) {\n return func.right(\n obj,\n getItemsFn(obj, index),\n {\n parentExpr: expr,\n inputExpr: args,\n documentNumber: index + 1,\n field\n },\n // must use raw options only since it operates over a collection.\n options\n );\n }\n };\n };\n if (window) {\n const { documents, range, unit } = window;\n const boundary = documents || range;\n if (!isUnbounded(window)) {\n const [begin, end] = boundary;\n const toBeginIndex = (currentIndex) => {\n if (begin == \"current\") return currentIndex;\n if (begin == \"unbounded\") return 0;\n return Math.max(begin + currentIndex, 0);\n };\n const toEndIndex = (currentIndex) => {\n if (end == \"current\") return currentIndex + 1;\n if (end == \"unbounded\") return items.length;\n return end + currentIndex + 1;\n };\n const getItems = (current, index) => {\n if (!!documents || boundary?.every(import_util.isString)) {\n return items.slice(toBeginIndex(index), toEndIndex(index));\n }\n const sortKey = Object.keys(expr.sortBy)[0];\n let lower;\n let upper;\n if (unit) {\n const startDate = new Date(current[sortKey]);\n const getTime = (amount) => {\n const addExpr = { startDate, unit, amount };\n const d = (0, import_dateAdd.$dateAdd)(current, addExpr, options);\n return d.getTime();\n };\n lower = (0, import_util.isNumber)(begin) ? getTime(begin) : -Infinity;\n upper = (0, import_util.isNumber)(end) ? getTime(end) : Infinity;\n } else {\n const currentValue = current[sortKey];\n lower = (0, import_util.isNumber)(begin) ? currentValue + begin : -Infinity;\n upper = (0, import_util.isNumber)(end) ? currentValue + end : Infinity;\n }\n let i = begin == \"current\" ? index : 0;\n const sliceEnd = end == \"current\" ? index + 1 : items.length;\n const array = new Array();\n while (i < sliceEnd) {\n const o = items[i++];\n const n = +o[sortKey];\n if (n >= lower && n <= upper) array.push(o);\n }\n return array;\n };\n windowResultMap[field] = makeResultFunc(getItems);\n }\n }\n if (!windowResultMap[field]) {\n windowResultMap[field] = makeResultFunc((_) => items);\n }\n iterator = (0, import_addFields.$addFields)(\n iterator,\n {\n [field]: {\n $function: {\n body: (obj) => windowResultMap[field](obj),\n args: [\"$$CURRENT\"]\n }\n }\n },\n options\n );\n }\n iterators.push(iterator);\n }\n return (0, import_lazy.concat)(...iterators);\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $setWindowFields\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar fill_exports = {};\n__export(fill_exports, {\n $fill: () => $fill\n});\nmodule.exports = __toCommonJS(fill_exports);\nvar import_util = require(\"../../util\");\nvar import_ifNull = require(\"../expression/conditional/ifNull\");\nvar import_linearFill = require(\"../window/linearFill\");\nvar import_locf = require(\"../window/locf\");\nvar import_addFields = require(\"./addFields\");\nvar import_setWindowFields = require(\"./setWindowFields\");\nconst FILL_METHODS = { locf: \"$locf\", linear: \"$linearFill\" };\nfunction $fill(coll, expr, options) {\n (0, import_util.assert)(!expr.sortBy || (0, import_util.isObject)(expr.sortBy), \"sortBy must be an object.\");\n (0, import_util.assert)(\n !!expr.sortBy || Object.values(expr.output).every((m) => (0, import_util.has)(m, \"value\")),\n \"sortBy required if any output field specifies a 'method'.\"\n );\n (0, import_util.assert)(\n !(expr.partitionBy && expr.partitionByFields),\n \"specify either partitionBy or partitionByFields.\"\n );\n (0, import_util.assert)(\n !expr.partitionByFields || expr?.partitionByFields?.every((s) => s[0] !== \"$\"),\n \"fields in partitionByFields cannot begin with '$'.\"\n );\n options.context.addExpressionOps({ $ifNull: import_ifNull.$ifNull });\n options.context.addWindowOps({ $locf: import_locf.$locf, $linearFill: import_linearFill.$linearFill });\n const partitionExpr = expr.partitionBy || expr?.partitionByFields?.map((s) => \"$\" + s);\n const valueExpr = {};\n const methodExpr = {};\n for (const k of Object.keys(expr.output)) {\n const m = expr.output[k];\n if ((0, import_util.has)(m, \"value\")) {\n const out = m;\n valueExpr[k] = { $ifNull: [`$$CURRENT.${k}`, out.value] };\n } else {\n const out = m;\n const fillOp = FILL_METHODS[out.method];\n (0, import_util.assert)(!!fillOp, `invalid fill method '${out.method}'.`);\n methodExpr[k] = { [fillOp]: \"$\" + k };\n }\n }\n if (Object.keys(methodExpr).length > 0) {\n coll = (0, import_setWindowFields.$setWindowFields)(\n coll,\n {\n sortBy: expr.sortBy || {},\n partitionBy: partitionExpr,\n output: methodExpr\n },\n options\n );\n }\n if (Object.keys(valueExpr).length > 0) {\n coll = (0, import_addFields.$addFields)(coll, valueExpr, options);\n }\n return coll;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $fill\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lookup_exports = {};\n__export(lookup_exports, {\n $lookup: () => $lookup\n});\nmodule.exports = __toCommonJS(lookup_exports);\nvar import_aggregator = require(\"../../aggregator\");\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"./_internal\");\nfunction $lookup(coll, expr, options) {\n const { let: letExpr, foreignField, localField } = expr;\n let lookupEq = (_) => [true, []];\n let joinColl = (0, import_util.isString)(expr.from) ? (0, import_internal2.resolveCollection)(\"$lookup\", expr.from, options) : expr.from;\n const { documents, pipeline } = (0, import_internal2.filterDocumentsStage)(\n expr.pipeline ?? [],\n options\n );\n (0, import_util.assert)(\n !joinColl !== !documents,\n \"$lookup: must specify single join input with `expr.from` or `expr.pipeline`.\"\n );\n joinColl = joinColl ?? documents;\n (0, import_util.assert)(\n (0, import_util.isArray)(joinColl),\n \"$lookup: join collection must resolve to an array.\"\n );\n if (foreignField && localField) {\n const map = import_util.HashMap.init();\n for (const doc of joinColl) {\n for (const v of (0, import_util.ensureArray)((0, import_util.resolve)(doc, foreignField) ?? null)) {\n const xs = map.get(v);\n const arr = xs ?? [];\n arr.push(doc);\n if (arr !== xs) map.set(v, arr);\n }\n }\n lookupEq = (o) => {\n const local = (0, import_util.resolve)(o, localField) ?? null;\n if ((0, import_util.isArray)(local)) {\n if (pipeline?.length) {\n return [local.some((v) => map.has(v)), []];\n }\n const result2 = Array.from(new Set((0, import_util.flatten)(local.map((v) => map.get(v)))));\n return [result2.length > 0, result2];\n }\n const result = map.get(local) ?? null;\n return [result !== null, result ?? []];\n };\n if (pipeline?.length === 0) {\n return coll.map((obj) => {\n return { ...obj, [expr.as]: lookupEq(obj).pop() };\n });\n }\n }\n const agg = new import_aggregator.Aggregator(pipeline ?? [], options);\n const opts = import_internal.ComputeOptions.init(options);\n return coll.map((obj) => {\n const vars = (0, import_internal.evalExpr)(obj, letExpr, options);\n opts.update({ root: null, variables: vars });\n const [ok, res] = lookupEq(obj);\n return { ...obj, [expr.as]: ok ? agg.run(joinColl, opts) : res };\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lookup\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar graphLookup_exports = {};\n__export(graphLookup_exports, {\n $graphLookup: () => $graphLookup\n});\nmodule.exports = __toCommonJS(graphLookup_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_internal2 = require(\"./_internal\");\nvar import_lookup = require(\"./lookup\");\nfunction $graphLookup(coll, expr, options) {\n const fromColl = (0, import_internal2.resolveCollection)(\"$graphLookup\", expr.from, options);\n (0, import_util.assert)(\n (0, import_util.isArray)(fromColl),\n \"$graphLookup: expression 'from' must resolve to array\"\n );\n const {\n connectFromField,\n connectToField,\n as: asField,\n maxDepth,\n depthField,\n restrictSearchWithMatch: matchExpr\n } = expr;\n const pipelineExpr = matchExpr ? { pipeline: [{ $match: matchExpr }] } : {};\n return coll.map((obj) => {\n const matchObj = {};\n (0, import_util.setValue)(\n matchObj,\n connectFromField,\n (0, import_internal.evalExpr)(obj, expr.startWith, options)\n );\n let matches = [matchObj];\n let i = -1;\n const map = import_util.HashMap.init();\n do {\n i++;\n matches = (0, import_util.flatten)(\n (0, import_lookup.$lookup)(\n (0, import_lazy.Lazy)(matches),\n {\n from: fromColl,\n localField: connectFromField,\n foreignField: connectToField,\n as: asField,\n ...pipelineExpr\n },\n options\n ).map((o) => o[asField]).collect()\n );\n const oldSize = map.size;\n for (const k of matches) map.set(k, map.get(k) ?? i);\n if (oldSize == map.size) break;\n } while ((0, import_util.isNil)(maxDepth) || i < maxDepth);\n const result = new Array(map.size);\n let n = 0;\n for (const [k, v] of map.entries()) {\n result[n++] = Object.assign(depthField ? { [depthField]: v } : {}, k);\n }\n return { ...obj, [asField]: result };\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $graphLookup\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar match_exports = {};\n__export(match_exports, {\n $match: () => $match\n});\nmodule.exports = __toCommonJS(match_exports);\nvar import_query = require(\"../../query\");\nfunction $match(coll, expr, options) {\n const q = new import_query.Query(expr, options);\n return coll.filter((o) => q.test(o));\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $match\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar merge_exports = {};\n__export(merge_exports, {\n $merge: () => $merge\n});\nmodule.exports = __toCommonJS(merge_exports);\nvar import_aggregator = require(\"../../aggregator\");\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nvar import_expression = require(\"../expression\");\nvar import_internal2 = require(\"./_internal\");\nfunction $merge(coll, expr, options) {\n const output = (0, import_internal2.resolveCollection)(\"$merge\", expr.into, options);\n (0, import_util.assert)((0, import_util.isArray)(output), `$merge: expression 'into' must resolve to an array`);\n const onField = expr.on || options.idKey;\n const getHash = (0, import_util.isString)(onField) ? (o) => (0, import_util.hashCode)((0, import_util.resolve)(o, onField)) : (o) => (0, import_util.hashCode)(onField.map((s) => (0, import_util.resolve)(o, s)));\n const map = import_util.HashMap.init();\n for (let i = 0; i < output.length; i++) {\n const obj = output[i];\n const k = getHash(obj);\n (0, import_util.assert)(\n !map.has(k),\n \"$merge: 'into' collection must have unique entries for the 'on' field.\"\n );\n map.set(k, [obj, i]);\n }\n const copts = import_internal.ComputeOptions.init(options);\n return coll.map((o) => {\n const k = getHash(o);\n if (map.has(k)) {\n const [target, i] = map.get(k);\n const variables = (0, import_internal.evalExpr)(\n target,\n expr.let || { new: \"$$ROOT\" },\n // 'root' is the item from the iteration.\n copts.update({ root: o })\n );\n if ((0, import_util.isArray)(expr.whenMatched)) {\n const aggregator = new import_aggregator.Aggregator(\n expr.whenMatched,\n copts.update({ root: null, variables })\n );\n output[i] = aggregator.run([target])[0];\n } else {\n switch (expr.whenMatched) {\n case \"replace\":\n output[i] = o;\n break;\n case \"fail\":\n throw new import_util.MingoError(\n \"$merge: failed due to matching as specified by 'whenMatched' option.\"\n );\n case \"keepExisting\":\n break;\n case \"merge\":\n default:\n output[i] = (0, import_expression.$mergeObjects)(\n target,\n [target, o],\n // 'root' is the item from the iteration.\n copts.update({ root: o, variables })\n );\n break;\n }\n }\n } else {\n switch (expr.whenNotMatched) {\n case \"discard\":\n break;\n case \"fail\":\n throw new import_util.MingoError(\n \"$merge: failed due to matching as specified by 'whenMatched' option.\"\n );\n case \"insert\":\n default:\n output.push(o);\n break;\n }\n }\n return o;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $merge\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar out_exports = {};\n__export(out_exports, {\n $out: () => $out\n});\nmodule.exports = __toCommonJS(out_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $out(coll, expr, options) {\n const out = (0, import_internal.resolveCollection)(\"$out\", expr, options);\n (0, import_util.assert)((0, import_util.isArray)(out), `$out: expression must resolve to an array`);\n return coll.map((o) => {\n out.push((0, import_util.cloneDeep)(o));\n return o;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $out\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar redact_exports = {};\n__export(redact_exports, {\n $redact: () => $redact\n});\nmodule.exports = __toCommonJS(redact_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nfunction $redact(coll, expr, options) {\n const copts = import_internal.ComputeOptions.init(options);\n return coll.map(\n (root) => redact(root, expr, copts.update({ root }))\n );\n}\nfunction redact(obj, expr, options) {\n const action = (0, import_internal.evalExpr)(obj, expr, options);\n switch (action) {\n case \"$$KEEP\":\n return obj;\n case \"$$PRUNE\":\n return void 0;\n case \"$$DESCEND\": {\n if (!(0, import_util.has)(expr, \"$cond\")) return obj;\n const output = {};\n for (const key of Object.keys(obj)) {\n const value = obj[key];\n if ((0, import_util.isArray)(value)) {\n const res = new Array();\n for (let elem of value) {\n if ((0, import_util.isObject)(elem)) {\n elem = redact(elem, expr, options.update({ root: elem }));\n }\n if (!(0, import_util.isNil)(elem)) res.push(elem);\n }\n output[key] = res;\n } else if ((0, import_util.isObject)(value)) {\n const res = redact(\n value,\n expr,\n options.update({ root: value })\n );\n if (!(0, import_util.isNil)(res)) output[key] = res;\n } else {\n output[key] = value;\n }\n }\n return output;\n }\n default:\n return action;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $redact\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar replaceRoot_exports = {};\n__export(replaceRoot_exports, {\n $replaceRoot: () => $replaceRoot\n});\nmodule.exports = __toCommonJS(replaceRoot_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nfunction $replaceRoot(coll, expr, options) {\n return coll.map((obj) => {\n obj = (0, import_internal.evalExpr)(obj, expr.newRoot, options);\n (0, import_util.assert)((0, import_util.isObject)(obj), \"$replaceRoot expression must return an object\");\n return obj;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $replaceRoot\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar replaceWith_exports = {};\n__export(replaceWith_exports, {\n $replaceWith: () => $replaceWith\n});\nmodule.exports = __toCommonJS(replaceWith_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar import_util = require(\"../../util\");\nfunction $replaceWith(coll, expr, options) {\n return coll.map((obj) => {\n obj = (0, import_internal.evalExpr)(obj, expr, options);\n (0, import_util.assert)((0, import_util.isObject)(obj), \"$replaceWith expression must return an object\");\n return obj;\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $replaceWith\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sample_exports = {};\n__export(sample_exports, {\n $sample: () => $sample\n});\nmodule.exports = __toCommonJS(sample_exports);\nvar import_lazy = require(\"../../lazy\");\nfunction $sample(coll, expr, _options) {\n return coll.transform((xs) => {\n const len = xs.length;\n let i = -1;\n return (0, import_lazy.Lazy)(() => {\n if (++i === expr.size) return { done: true };\n const n = Math.floor(Math.random() * len);\n return { value: xs[n], done: false };\n });\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sample\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar set_exports = {};\n__export(set_exports, {\n $set: () => $set\n});\nmodule.exports = __toCommonJS(set_exports);\nvar import_addFields = require(\"./addFields\");\nconst $set = import_addFields.$addFields;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $set\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar sortByCount_exports = {};\n__export(sortByCount_exports, {\n $sortByCount: () => $sortByCount\n});\nmodule.exports = __toCommonJS(sortByCount_exports);\nvar import_group = require(\"./group\");\nvar import_sort = require(\"./sort\");\nfunction $sortByCount(coll, expr, options) {\n return (0, import_sort.$sort)(\n (0, import_group.$group)(coll, { _id: expr, count: { $sum: 1 } }, options),\n { count: -1 },\n options\n );\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $sortByCount\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unionWith_exports = {};\n__export(unionWith_exports, {\n $unionWith: () => $unionWith\n});\nmodule.exports = __toCommonJS(unionWith_exports);\nvar import_aggregator = require(\"../../aggregator\");\nvar import_lazy = require(\"../../lazy\");\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $unionWith(collection, expr, options) {\n const { coll: inputColl, pipeline: stages } = (0, import_util.isString)(expr) || (0, import_util.isArray)(expr) ? { coll: expr } : expr;\n const docsFromInput = (0, import_util.isString)(inputColl) ? (0, import_internal.resolveCollection)(\"$unionWith\", inputColl, options) : inputColl;\n const { documents, pipeline } = (0, import_internal.filterDocumentsStage)(stages, options);\n (0, import_util.assert)(\n docsFromInput || documents,\n \"$unionWith must specify single collection input with `expr.coll` or `expr.pipeline`.\"\n );\n const xs = docsFromInput ?? documents;\n return (0, import_lazy.concat)(\n collection,\n pipeline ? new import_aggregator.Aggregator(pipeline, options).stream(xs) : (0, import_lazy.Lazy)(xs)\n );\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unionWith\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unset_exports = {};\n__export(unset_exports, {\n $unset: () => $unset\n});\nmodule.exports = __toCommonJS(unset_exports);\nvar import_util = require(\"../../util\");\nvar import_project = require(\"./project\");\nfunction $unset(coll, expr, options) {\n expr = (0, import_util.ensureArray)(expr);\n const doc = {};\n for (const k of expr) doc[k] = 0;\n return (0, import_project.$project)(coll, doc, options);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unset\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unwind_exports = {};\n__export(unwind_exports, {\n $unwind: () => $unwind\n});\nmodule.exports = __toCommonJS(unwind_exports);\nvar import_lazy = require(\"../../lazy\");\nvar import_internal = require(\"../../util/_internal\");\nfunction $unwind(coll, expr, _options) {\n if ((0, import_internal.isString)(expr)) expr = { path: expr };\n const path = expr.path;\n const field = path.substring(1);\n const includeArrayIndex = expr?.includeArrayIndex || false;\n const preserveNullAndEmptyArrays = expr.preserveNullAndEmptyArrays || false;\n const format = (o, i) => {\n if (includeArrayIndex !== false) o[includeArrayIndex] = i;\n return o;\n };\n let value;\n return (0, import_lazy.Lazy)(() => {\n for (; ; ) {\n if (value instanceof import_lazy.Iterator) {\n const tmp = value.next();\n if (!tmp.done) return tmp;\n }\n const wrapper = coll.next();\n if (wrapper.done) return wrapper;\n const obj = wrapper.value;\n value = (0, import_internal.resolve)(obj, field);\n if ((0, import_internal.isArray)(value)) {\n if (value.length === 0 && preserveNullAndEmptyArrays === true) {\n value = null;\n (0, import_internal.removeValue)(obj, field);\n return { value: format(obj, null), done: false };\n } else {\n value = (0, import_lazy.Lazy)(value).map(((item, i) => {\n const newObj = (0, import_internal.resolveGraph)(obj, field, {\n preserveKeys: true\n });\n (0, import_internal.setValue)(newObj, field, item);\n return format(newObj, i);\n }));\n }\n } else if (!(0, import_internal.isEmpty)(value) || preserveNullAndEmptyArrays === true) {\n return { value: format(obj, null), done: false };\n }\n }\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unwind\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pipeline_exports = {};\nmodule.exports = __toCommonJS(pipeline_exports);\n__reExport(pipeline_exports, require(\"./addFields\"), module.exports);\n__reExport(pipeline_exports, require(\"./bucket\"), module.exports);\n__reExport(pipeline_exports, require(\"./bucketAuto\"), module.exports);\n__reExport(pipeline_exports, require(\"./count\"), module.exports);\n__reExport(pipeline_exports, require(\"./densify\"), module.exports);\n__reExport(pipeline_exports, require(\"./documents\"), module.exports);\n__reExport(pipeline_exports, require(\"./facet\"), module.exports);\n__reExport(pipeline_exports, require(\"./fill\"), module.exports);\n__reExport(pipeline_exports, require(\"./graphLookup\"), module.exports);\n__reExport(pipeline_exports, require(\"./group\"), module.exports);\n__reExport(pipeline_exports, require(\"./limit\"), module.exports);\n__reExport(pipeline_exports, require(\"./lookup\"), module.exports);\n__reExport(pipeline_exports, require(\"./match\"), module.exports);\n__reExport(pipeline_exports, require(\"./merge\"), module.exports);\n__reExport(pipeline_exports, require(\"./out\"), module.exports);\n__reExport(pipeline_exports, require(\"./project\"), module.exports);\n__reExport(pipeline_exports, require(\"./redact\"), module.exports);\n__reExport(pipeline_exports, require(\"./replaceRoot\"), module.exports);\n__reExport(pipeline_exports, require(\"./replaceWith\"), module.exports);\n__reExport(pipeline_exports, require(\"./sample\"), module.exports);\n__reExport(pipeline_exports, require(\"./set\"), module.exports);\n__reExport(pipeline_exports, require(\"./setWindowFields\"), module.exports);\n__reExport(pipeline_exports, require(\"./skip\"), module.exports);\n__reExport(pipeline_exports, require(\"./sort\"), module.exports);\n__reExport(pipeline_exports, require(\"./sortByCount\"), module.exports);\n__reExport(pipeline_exports, require(\"./unionWith\"), module.exports);\n__reExport(pipeline_exports, require(\"./unset\"), module.exports);\n__reExport(pipeline_exports, require(\"./unwind\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./addFields\"),\n ...require(\"./bucket\"),\n ...require(\"./bucketAuto\"),\n ...require(\"./count\"),\n ...require(\"./densify\"),\n ...require(\"./documents\"),\n ...require(\"./facet\"),\n ...require(\"./fill\"),\n ...require(\"./graphLookup\"),\n ...require(\"./group\"),\n ...require(\"./limit\"),\n ...require(\"./lookup\"),\n ...require(\"./match\"),\n ...require(\"./merge\"),\n ...require(\"./out\"),\n ...require(\"./project\"),\n ...require(\"./redact\"),\n ...require(\"./replaceRoot\"),\n ...require(\"./replaceWith\"),\n ...require(\"./sample\"),\n ...require(\"./set\"),\n ...require(\"./setWindowFields\"),\n ...require(\"./skip\"),\n ...require(\"./sort\"),\n ...require(\"./sortByCount\"),\n ...require(\"./unionWith\"),\n ...require(\"./unset\"),\n ...require(\"./unwind\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar elemMatch_exports = {};\n__export(elemMatch_exports, {\n $elemMatch: () => $elemMatch\n});\nmodule.exports = __toCommonJS(elemMatch_exports);\nvar import_query = require(\"../../query\");\nvar import_util = require(\"../../util\");\nconst $elemMatch = (obj, expr, field, options) => {\n const arr = (0, import_util.resolve)(obj, field);\n const query = new import_query.Query(expr, options);\n if (!(0, import_util.isArray)(arr)) return void 0;\n const result = [];\n for (let i = 0; i < arr.length; i++) {\n if (query.test(arr[i])) {\n if (options.useStrictMode) return [arr[i]];\n result.push(arr[i]);\n }\n }\n return result.length > 0 ? result : void 0;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $elemMatch\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar slice_exports = {};\n__export(slice_exports, {\n $slice: () => $slice\n});\nmodule.exports = __toCommonJS(slice_exports);\nvar import_util = require(\"../../util\");\nvar import_slice = require(\"../expression/array/slice\");\nconst $slice = (obj, expr, field, options) => {\n const xs = (0, import_util.resolve)(obj, field);\n if (!(0, import_util.isArray)(xs)) return xs;\n return (0, import_slice.$slice)(\n obj,\n (0, import_util.isArray)(expr) ? [xs, ...expr] : [xs, expr],\n options\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $slice\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar projection_exports = {};\nmodule.exports = __toCommonJS(projection_exports);\n__reExport(projection_exports, require(\"./elemMatch\"), module.exports);\n__reExport(projection_exports, require(\"./slice\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./elemMatch\"),\n ...require(\"./slice\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar all_exports = {};\n__export(all_exports, {\n $all: () => $all\n});\nmodule.exports = __toCommonJS(all_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $all = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$all);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $all\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar elemMatch_exports = {};\n__export(elemMatch_exports, {\n $elemMatch: () => $elemMatch\n});\nmodule.exports = __toCommonJS(elemMatch_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $elemMatch = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$elemMatch);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $elemMatch\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar size_exports = {};\n__export(size_exports, {\n $size: () => $size\n});\nmodule.exports = __toCommonJS(size_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $size = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$size);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $size\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar array_exports = {};\nmodule.exports = __toCommonJS(array_exports);\n__reExport(array_exports, require(\"./all\"), module.exports);\n__reExport(array_exports, require(\"./elemMatch\"), module.exports);\n__reExport(array_exports, require(\"./size\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./all\"),\n ...require(\"./elemMatch\"),\n ...require(\"./size\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n processBitwiseQuery: () => processBitwiseQuery\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_util = require(\"../../../util\");\nvar import_predicates = require(\"../../_predicates\");\nconst processBitwiseQuery = (selector, value, predicate) => {\n return (0, import_predicates.processQuery)(\n selector,\n value,\n null,\n (value2, mask) => {\n let b = 0;\n if ((0, import_util.isArray)(mask)) {\n for (const n of mask) b = b | 1 << n;\n } else {\n b = mask;\n }\n return predicate(value2 & b, b);\n }\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n processBitwiseQuery\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitsAllClear_exports = {};\n__export(bitsAllClear_exports, {\n $bitsAllClear: () => $bitsAllClear\n});\nmodule.exports = __toCommonJS(bitsAllClear_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitsAllClear = (selector, value, _options) => (0, import_internal.processBitwiseQuery)(selector, value, (result, _) => result == 0);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAllClear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitsAllSet_exports = {};\n__export(bitsAllSet_exports, {\n $bitsAllSet: () => $bitsAllSet\n});\nmodule.exports = __toCommonJS(bitsAllSet_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitsAllSet = (selector, value, _options) => (0, import_internal.processBitwiseQuery)(selector, value, (result, mask) => result == mask);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAllSet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitsAnyClear_exports = {};\n__export(bitsAnyClear_exports, {\n $bitsAnyClear: () => $bitsAnyClear\n});\nmodule.exports = __toCommonJS(bitsAnyClear_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitsAnyClear = (selector, value, _options) => (0, import_internal.processBitwiseQuery)(selector, value, (result, mask) => result < mask);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAnyClear\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitsAnySet_exports = {};\n__export(bitsAnySet_exports, {\n $bitsAnySet: () => $bitsAnySet\n});\nmodule.exports = __toCommonJS(bitsAnySet_exports);\nvar import_internal = require(\"./_internal\");\nconst $bitsAnySet = (selector, value, _options) => (0, import_internal.processBitwiseQuery)(selector, value, (result, _) => result > 0);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAnySet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bitwise_exports = {};\n__export(bitwise_exports, {\n $bitsAllClear: () => import_bitsAllClear.$bitsAllClear,\n $bitsAllSet: () => import_bitsAllSet.$bitsAllSet,\n $bitsAnyClear: () => import_bitsAnyClear.$bitsAnyClear,\n $bitsAnySet: () => import_bitsAnySet.$bitsAnySet\n});\nmodule.exports = __toCommonJS(bitwise_exports);\nvar import_bitsAllClear = require(\"./bitsAllClear\");\nvar import_bitsAllSet = require(\"./bitsAllSet\");\nvar import_bitsAnyClear = require(\"./bitsAnyClear\");\nvar import_bitsAnySet = require(\"./bitsAnySet\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bitsAllClear,\n $bitsAllSet,\n $bitsAnyClear,\n $bitsAnySet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar eq_exports = {};\n__export(eq_exports, {\n $eq: () => $eq\n});\nmodule.exports = __toCommonJS(eq_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $eq = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$eq);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $eq\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar gt_exports = {};\n__export(gt_exports, {\n $gt: () => $gt\n});\nmodule.exports = __toCommonJS(gt_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $gt = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$gt);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $gt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar gte_exports = {};\n__export(gte_exports, {\n $gte: () => $gte\n});\nmodule.exports = __toCommonJS(gte_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $gte = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$gte);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $gte\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar in_exports = {};\n__export(in_exports, {\n $in: () => $in\n});\nmodule.exports = __toCommonJS(in_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $in = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$in);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $in\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lt_exports = {};\n__export(lt_exports, {\n $lt: () => $lt\n});\nmodule.exports = __toCommonJS(lt_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $lt = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$lt);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lt\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar lte_exports = {};\n__export(lte_exports, {\n $lte: () => $lte\n});\nmodule.exports = __toCommonJS(lte_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $lte = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$lte);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $lte\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar ne_exports = {};\n__export(ne_exports, {\n $ne: () => $ne\n});\nmodule.exports = __toCommonJS(ne_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $ne = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$ne);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $ne\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar nin_exports = {};\n__export(nin_exports, {\n $nin: () => $nin\n});\nmodule.exports = __toCommonJS(nin_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $nin = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$nin);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $nin\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar comparison_exports = {};\n__export(comparison_exports, {\n $eq: () => import_eq.$eq,\n $gt: () => import_gt.$gt,\n $gte: () => import_gte.$gte,\n $in: () => import_in.$in,\n $lt: () => import_lt.$lt,\n $lte: () => import_lte.$lte,\n $ne: () => import_ne.$ne,\n $nin: () => import_nin.$nin\n});\nmodule.exports = __toCommonJS(comparison_exports);\nvar import_eq = require(\"./eq\");\nvar import_gt = require(\"./gt\");\nvar import_gte = require(\"./gte\");\nvar import_in = require(\"./in\");\nvar import_lt = require(\"./lt\");\nvar import_lte = require(\"./lte\");\nvar import_ne = require(\"./ne\");\nvar import_nin = require(\"./nin\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $eq,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar exists_exports = {};\n__export(exists_exports, {\n $exists: () => $exists\n});\nmodule.exports = __toCommonJS(exists_exports);\nvar import_internal = require(\"../../../util/_internal\");\nconst $exists = (selector, value, _options) => {\n const nested = selector.includes(\".\");\n const b = !!value;\n if (!nested || selector.match(/\\.\\d+$/)) {\n const opts2 = { pathArray: selector.split(\".\") };\n return (o) => (0, import_internal.resolve)(o, selector, opts2) !== void 0 === b;\n }\n const parentSelector = selector.substring(0, selector.lastIndexOf(\".\"));\n const opts = { pathArray: parentSelector.split(\".\"), preserveIndex: true };\n return (o) => {\n const path = (0, import_internal.resolveGraph)(o, selector, opts);\n const val = (0, import_internal.resolve)(path, parentSelector, opts);\n return (0, import_internal.isArray)(val) ? val.some((v) => v !== void 0) === b : val !== void 0 === b;\n };\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $exists\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar type_exports = {};\n__export(type_exports, {\n $type: () => $type\n});\nmodule.exports = __toCommonJS(type_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $type = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$type);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $type\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar element_exports = {};\nmodule.exports = __toCommonJS(element_exports);\n__reExport(element_exports, require(\"./exists\"), module.exports);\n__reExport(element_exports, require(\"./type\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./exists\"),\n ...require(\"./type\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar expr_exports = {};\n__export(expr_exports, {\n $expr: () => $expr\n});\nmodule.exports = __toCommonJS(expr_exports);\nvar import_internal = require(\"../../../core/_internal\");\nvar import_internal2 = require(\"../../../util/_internal\");\nfunction $expr(_, expr, options) {\n return (obj) => (0, import_internal2.truthy)((0, import_internal.evalExpr)(obj, expr, options), options.useStrictMode);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $expr\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar jsonSchema_exports = {};\n__export(jsonSchema_exports, {\n $jsonSchema: () => $jsonSchema\n});\nmodule.exports = __toCommonJS(jsonSchema_exports);\nvar import_util = require(\"../../../util\");\nfunction $jsonSchema(_, schema, options) {\n (0, import_util.assert)(\n !!options?.jsonSchemaValidator,\n \"$jsonSchema requires 'jsonSchemaValidator' option to be defined.\"\n );\n const validate = options.jsonSchemaValidator(schema);\n return (obj) => validate(obj);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $jsonSchema\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mod_exports = {};\n__export(mod_exports, {\n $mod: () => $mod\n});\nmodule.exports = __toCommonJS(mod_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $mod = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$mod);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mod\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar regex_exports = {};\n__export(regex_exports, {\n $regex: () => $regex\n});\nmodule.exports = __toCommonJS(regex_exports);\nvar import_predicates = require(\"../../_predicates\");\nconst $regex = (selector, value, options) => (0, import_predicates.processQuery)(selector, value, options, import_predicates.$regex);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $regex\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar where_exports = {};\n__export(where_exports, {\n $where: () => $where\n});\nmodule.exports = __toCommonJS(where_exports);\nvar import_internal = require(\"../../../util/_internal\");\nfunction $where(_, rhs, opts) {\n (0, import_internal.assert)(\n opts.scriptEnabled,\n \"$where requires 'scriptEnabled' option to be true\"\n );\n const f = rhs;\n (0, import_internal.assert)((0, import_internal.isFunction)(f), \"$where only accepts a Function objects\");\n return (obj) => (0, import_internal.truthy)(f.call(obj), opts?.useStrictMode);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $where\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar evaluation_exports = {};\nmodule.exports = __toCommonJS(evaluation_exports);\n__reExport(evaluation_exports, require(\"./expr\"), module.exports);\n__reExport(evaluation_exports, require(\"./jsonSchema\"), module.exports);\n__reExport(evaluation_exports, require(\"./mod\"), module.exports);\n__reExport(evaluation_exports, require(\"./regex\"), module.exports);\n__reExport(evaluation_exports, require(\"./where\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./expr\"),\n ...require(\"./jsonSchema\"),\n ...require(\"./mod\"),\n ...require(\"./regex\"),\n ...require(\"./where\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar and_exports = {};\n__export(and_exports, {\n $and: () => $and\n});\nmodule.exports = __toCommonJS(and_exports);\nvar import_query = require(\"../../../query\");\nvar import_util = require(\"../../../util\");\nconst $and = (_, rhs, options) => {\n (0, import_util.assert)((0, import_util.isArray)(rhs), \"$and expects value to be an Array.\");\n const queries = rhs.map((expr) => new import_query.Query(expr, options));\n return (obj) => queries.every((q) => q.test(obj));\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $and\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar or_exports = {};\n__export(or_exports, {\n $or: () => $or\n});\nmodule.exports = __toCommonJS(or_exports);\nvar import_query = require(\"../../../query\");\nvar import_util = require(\"../../../util\");\nfunction $or(_, rhs, options) {\n (0, import_util.assert)((0, import_util.isArray)(rhs), \"Invalid expression. $or expects value to be an Array\");\n const queries = rhs.map((expr) => new import_query.Query(expr, options));\n return (obj) => queries.some((q) => q.test(obj));\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $or\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar nor_exports = {};\n__export(nor_exports, {\n $nor: () => $nor\n});\nmodule.exports = __toCommonJS(nor_exports);\nvar import_util = require(\"../../../util\");\nvar import_or = require(\"./or\");\nfunction $nor(_, rhs, options) {\n (0, import_util.assert)(\n (0, import_util.isArray)(rhs),\n \"Invalid expression. $nor expects value to be an array.\"\n );\n const f = (0, import_or.$or)(\"$or\", rhs, options);\n return (obj) => !f(obj);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $nor\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar not_exports = {};\n__export(not_exports, {\n $not: () => $not\n});\nmodule.exports = __toCommonJS(not_exports);\nvar import_query = require(\"../../../query\");\nvar import_util = require(\"../../../util\");\nfunction $not(selector, rhs, options) {\n const criteria = {};\n criteria[selector] = (0, import_util.normalize)(rhs);\n const query = new import_query.Query(criteria, options);\n return (obj) => !query.test(obj);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $not\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar logical_exports = {};\nmodule.exports = __toCommonJS(logical_exports);\n__reExport(logical_exports, require(\"./and\"), module.exports);\n__reExport(logical_exports, require(\"./nor\"), module.exports);\n__reExport(logical_exports, require(\"./not\"), module.exports);\n__reExport(logical_exports, require(\"./or\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./and\"),\n ...require(\"./nor\"),\n ...require(\"./not\"),\n ...require(\"./or\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar query_exports = {};\nmodule.exports = __toCommonJS(query_exports);\n__reExport(query_exports, require(\"./array\"), module.exports);\n__reExport(query_exports, require(\"./bitwise\"), module.exports);\n__reExport(query_exports, require(\"./comparison\"), module.exports);\n__reExport(query_exports, require(\"./element\"), module.exports);\n__reExport(query_exports, require(\"./evaluation\"), module.exports);\n__reExport(query_exports, require(\"./logical\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./array\"),\n ...require(\"./bitwise\"),\n ...require(\"./comparison\"),\n ...require(\"./element\"),\n ...require(\"./evaluation\"),\n ...require(\"./logical\")\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar denseRank_exports = {};\n__export(denseRank_exports, {\n $denseRank: () => $denseRank\n});\nmodule.exports = __toCommonJS(denseRank_exports);\nvar import_internal = require(\"./_internal\");\nconst $denseRank = (obj, coll, expr, options) => (0, import_internal.rank)(\n obj,\n coll,\n expr,\n options,\n true\n /*dense*/\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $denseRank\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar derivative_exports = {};\n__export(derivative_exports, {\n $derivative: () => $derivative\n});\nmodule.exports = __toCommonJS(derivative_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"../expression/date/_internal\");\nconst $derivative = (_, coll, expr, options) => {\n if (coll.length < 2) return null;\n const { input, unit } = expr.inputExpr;\n const sortKey = \"$\" + Object.keys(expr.parentExpr.sortBy)[0];\n const values = [coll[0], coll[coll.length - 1]];\n const points = (0, import_push.$push)(values, [sortKey, input], options).filter(\n (([x, y]) => (0, import_util.isNumber)(+x) && (0, import_util.isNumber)(+y))\n );\n (0, import_util.assert)(points.length === 2, \"$derivative arguments must resolve to numeric\");\n const [[x1, y1], [x2, y2]] = points;\n const deltaX = (x2 - x1) / import_internal.TIMEUNIT_IN_MILLIS[unit ?? \"millisecond\"];\n return (y2 - y1) / deltaX;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $derivative\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar documentNumber_exports = {};\n__export(documentNumber_exports, {\n $documentNumber: () => $documentNumber\n});\nmodule.exports = __toCommonJS(documentNumber_exports);\nconst $documentNumber = (_obj, _coll, expr, _options) => expr.documentNumber;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $documentNumber\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar expMovingAvg_exports = {};\n__export(expMovingAvg_exports, {\n $expMovingAvg: () => $expMovingAvg\n});\nmodule.exports = __toCommonJS(expMovingAvg_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"./_internal\");\nconst $expMovingAvg = (_, coll, expr, options) => {\n const { input, N, alpha } = expr.inputExpr;\n (0, import_util.assert)(\n !(N && alpha),\n `$expMovingAvg: must provide either 'N' or 'alpha' field.`\n );\n (0, import_util.assert)(\n !N || (0, import_util.isNumber)(N) && N > 0,\n `$expMovingAvg: 'N' must be greater than zero. Got ${N}.`\n );\n (0, import_util.assert)(\n !alpha || (0, import_util.isNumber)(alpha) && alpha > 0 && alpha < 1,\n `$expMovingAvg: 'alpha' must be between 0 and 1 (exclusive), found alpha: ${alpha}`\n );\n return (0, import_internal.withMemo)(\n coll,\n expr,\n () => {\n const weight = N != void 0 ? 2 / (N + 1) : alpha;\n const values = (0, import_push.$push)(coll, input, options);\n for (let i = 0; i < values.length; i++) {\n if (i === 0) {\n if (!(0, import_util.isNumber)(values[i])) values[i] = null;\n continue;\n }\n if (!(0, import_util.isNumber)(values[i])) {\n values[i] = values[i - 1];\n continue;\n }\n if (!(0, import_util.isNumber)(values[i - 1])) continue;\n values[i] = values[i] * weight + values[i - 1] * (1 - weight);\n }\n return values;\n },\n (series) => series[expr.documentNumber - 1]\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $expMovingAvg\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar integral_exports = {};\n__export(integral_exports, {\n $integral: () => $integral\n});\nmodule.exports = __toCommonJS(integral_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"../expression/date/_internal\");\nconst $integral = (_, coll, expr, options) => {\n const { input, unit } = expr.inputExpr;\n const sortKey = \"$\" + Object.keys(expr.parentExpr.sortBy)[0];\n const points = (0, import_push.$push)(coll, [sortKey, input], options).filter(\n (([x, y]) => (0, import_util.isNumber)(+x) && (0, import_util.isNumber)(+y))\n );\n const size = points.length;\n (0, import_util.assert)(coll.length === size, \"$integral expects an array of numeric values\");\n let result = 0;\n for (let k = 1; k < size; k++) {\n const [x1, y1] = points[k - 1];\n const [x2, y2] = points[k];\n const deltaX = (x2 - x1) / import_internal.TIMEUNIT_IN_MILLIS[unit ?? \"millisecond\"];\n result += 0.5 * (y1 + y2) * deltaX;\n }\n return result;\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $integral\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar minMaxScaler_exports = {};\n__export(minMaxScaler_exports, {\n $minMaxScaler: () => $minMaxScaler\n});\nmodule.exports = __toCommonJS(minMaxScaler_exports);\nvar import_util = require(\"../../util\");\nvar import_push = require(\"../accumulator/push\");\nvar import_internal = require(\"./_internal\");\nconst $minMaxScaler = (_, coll, expr, options) => {\n return (0, import_internal.withMemo)(\n coll,\n expr,\n () => {\n const args = expr.inputExpr;\n const min = args.min || 0;\n const max = args.max || 1;\n const nums = (0, import_push.$push)(\n coll,\n args.input || expr.inputExpr,\n options\n );\n (0, import_util.assert)(\n (0, import_util.isArray)(nums) && nums.length > 0 && nums.every(import_util.isNumber),\n \"$minMaxScaler: input must be a numeric array\"\n );\n let rmin = nums[0];\n let rmax = nums[0];\n for (const n of nums) {\n if (n < rmin) rmin = n;\n else if (n > rmax) rmax = n;\n }\n const scale = max - min;\n const range = rmax - rmin;\n (0, import_util.assert)(range !== 0, \"$minMaxScaler: input range must not be zero\");\n return {\n min,\n scale,\n rmin,\n range,\n nums\n };\n },\n (data) => {\n const { min, rmin, scale, range, nums } = data;\n return (nums[expr.documentNumber - 1] - rmin) / range * scale + min;\n }\n );\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $minMaxScaler\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar rank_exports = {};\n__export(rank_exports, {\n $rank: () => $rank\n});\nmodule.exports = __toCommonJS(rank_exports);\nvar import_internal = require(\"./_internal\");\nconst $rank = (obj, coll, expr, options) => (0, import_internal.rank)(\n obj,\n coll,\n expr,\n options,\n false\n /*dense*/\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $rank\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar shift_exports = {};\n__export(shift_exports, {\n $shift: () => $shift\n});\nmodule.exports = __toCommonJS(shift_exports);\nvar import_internal = require(\"../../core/_internal\");\nconst $shift = (obj, coll, expr, options) => {\n const input = expr.inputExpr;\n const shiftedIndex = expr.documentNumber - 1 + input.by;\n if (shiftedIndex < 0 || shiftedIndex > coll.length - 1) {\n return (0, import_internal.evalExpr)(obj, input.default, options) ?? null;\n }\n return (0, import_internal.evalExpr)(coll[shiftedIndex], input.output, options);\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $shift\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar window_exports = {};\nmodule.exports = __toCommonJS(window_exports);\n__reExport(window_exports, require(\"./denseRank\"), module.exports);\n__reExport(window_exports, require(\"./derivative\"), module.exports);\n__reExport(window_exports, require(\"./documentNumber\"), module.exports);\n__reExport(window_exports, require(\"./expMovingAvg\"), module.exports);\n__reExport(window_exports, require(\"./integral\"), module.exports);\n__reExport(window_exports, require(\"./linearFill\"), module.exports);\n__reExport(window_exports, require(\"./locf\"), module.exports);\n__reExport(window_exports, require(\"./minMaxScaler\"), module.exports);\n__reExport(window_exports, require(\"./rank\"), module.exports);\n__reExport(window_exports, require(\"./shift\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./denseRank\"),\n ...require(\"./derivative\"),\n ...require(\"./documentNumber\"),\n ...require(\"./expMovingAvg\"),\n ...require(\"./integral\"),\n ...require(\"./linearFill\"),\n ...require(\"./locf\"),\n ...require(\"./minMaxScaler\"),\n ...require(\"./rank\"),\n ...require(\"./shift\")\n});\n", "var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar internal_exports = {};\n__export(internal_exports, {\n DEFAULT_OPTIONS: () => DEFAULT_OPTIONS,\n applyUpdate: () => applyUpdate,\n buildParams: () => buildParams,\n clone: () => clone,\n walkExpression: () => walkExpression\n});\nmodule.exports = __toCommonJS(internal_exports);\nvar import_internal = require(\"../../core/_internal\");\nvar booleanOperators = __toESM(require(\"../../operators/expression/boolean\"));\nvar comparisonOperators = __toESM(require(\"../../operators/expression/comparison\"));\nvar queryOperators = __toESM(require(\"../../operators/query\"));\nvar import_query = require(\"../../query\");\nvar import_internal2 = require(\"../../util/_internal\");\nconst DEFAULT_OPTIONS = import_internal.ComputeOptions.init({\n context: import_internal.Context.init().addQueryOps(queryOperators).addExpressionOps(booleanOperators).addExpressionOps(comparisonOperators)\n}).update({ updateConfig: { cloneMode: \"copy\" } });\nconst clone = (val, opts) => {\n const mode = opts?.local?.updateConfig?.cloneMode;\n switch (mode) {\n case \"deep\":\n return (0, import_internal2.cloneDeep)(val);\n case \"copy\": {\n if ((0, import_internal2.isDate)(val)) return new Date(val);\n if ((0, import_internal2.isArray)(val)) return val.slice();\n if ((0, import_internal2.isObject)(val)) return Object.assign({}, val);\n if ((0, import_internal2.isRegExp)(val)) return new RegExp(val);\n return val;\n }\n }\n return val;\n};\nconst FIRST_ONLY = \"$\";\nconst ARRAY_WIDE = \"$[]\";\nconst applyUpdate = (o, n, q, f, opts) => {\n const { selector, position: c, next } = n;\n if (!c) {\n let b = false;\n const g = (u, k) => b = Boolean(f(u, k)) || b;\n (0, import_internal2.walk)(o, selector, g, opts);\n return b;\n }\n const arr = (0, import_internal2.resolve)(o, selector);\n if (!(0, import_internal2.isArray)(arr) || !arr.length) return false;\n if (c === FIRST_ONLY) {\n const i = arr.findIndex((e) => q[selector].test({ [selector]: [e] }));\n (0, import_internal2.assert)(i > -1, \"BUG: positional operator found no match for \" + selector);\n return next ? applyUpdate(arr[i], next, q, f, opts) : f(arr, i);\n }\n return arr.map((e, i) => {\n if (c !== ARRAY_WIDE && q[c] && !q[c].test({ [c]: [e] })) return false;\n return next ? applyUpdate(e, next, q, f, opts) : f(arr, i);\n }).some((v) => !!v);\n};\nconst ERR_MISSING_FIELD = \"You must include the array field for '.$' as part of the query document.\";\nconst ERR_IMMUTABLE_FIELD = (path, idKey) => `Performing an update on the path '${path}' would modify the immutable field '${idKey}'.`;\nfunction walkExpression(expr, arrayFilters, options, callback) {\n const opts = options;\n const params = opts.local.updateParams ?? buildParams([expr], arrayFilters, opts);\n const modified = [];\n for (const key of Object.keys(expr)) {\n const { node, queries } = params[key];\n if (callback(expr[key], node, queries)) modified.push(node.selector);\n }\n return modified.sort();\n}\nfunction buildParams(exprList, arrayFilters, options) {\n const params = {};\n arrayFilters ||= [];\n const filterIndexMap = arrayFilters.reduce(\n (res, filter) => {\n for (const k of Object.keys(filter)) {\n const parent = k.split(\".\")[0];\n if (res[parent]) {\n res[parent][k] = filter[k];\n } else {\n res[parent] = { [k]: filter[k] };\n }\n }\n return res;\n },\n {}\n );\n let { condition } = options.local;\n condition = condition ?? {};\n const queryKeys = Object.keys(condition);\n const conflictDetector = new import_internal2.PathValidator();\n for (const expr of exprList) {\n for (const selector of Object.keys(expr)) {\n const identifiers = [];\n const node = selector.includes(\"$\") ? { selector: \"\" } : { selector };\n if (!node.selector) {\n selector.split(\".\").reduce((n, v) => {\n if (v === FIRST_ONLY || v === ARRAY_WIDE) {\n n.position = v;\n } else if (v.startsWith(\"$[\") && v.endsWith(\"]\")) {\n const id = v.slice(2, -1);\n (0, import_internal2.assert)(\n /^[a-z]+\\w*$/.test(id),\n `The filter must begin with a lowercase letter and contain only alphanumeric characters. '${v}' is invalid.`\n );\n identifiers.push(id);\n n.position = id;\n } else if (!n.selector) {\n n.selector = v;\n } else if (!n.position) {\n n.selector += \".\" + v;\n } else {\n n.next = { selector: v };\n return n.next;\n }\n return n;\n }, node);\n }\n const queries = {};\n if (identifiers.length) {\n const filters = {};\n for (const v of identifiers) filters[v] = filterIndexMap[v];\n for (const k of Object.keys(filters)) {\n queries[k] = new import_query.Query(filters[k], options);\n }\n }\n if (node.position === FIRST_ONLY) {\n const field = node.selector;\n (0, import_internal2.assert)(queryKeys && queryKeys.length, ERR_MISSING_FIELD);\n const matches = queryKeys.filter(\n (k2) => k2 === field || k2.startsWith(field + \".\")\n );\n (0, import_internal2.assert)(matches.length === 1, ERR_MISSING_FIELD);\n const k = matches[0];\n queries[field] = new import_query.Query({ [k]: condition[k] }, options);\n }\n const idKey = options.idKey;\n (0, import_internal2.assert)(\n node.selector !== idKey && !node.selector.startsWith(`${idKey}.`),\n ERR_IMMUTABLE_FIELD(node.selector, idKey)\n );\n (0, import_internal2.assert)(\n conflictDetector.add(node.selector),\n `updating the path '${node.selector}' would create a conflict at '${node.selector}'`\n );\n params[selector] = { node, queries };\n }\n }\n return params;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n DEFAULT_OPTIONS,\n applyUpdate,\n buildParams,\n clone,\n walkExpression\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar addToSet_exports = {};\n__export(addToSet_exports, {\n $addToSet: () => $addToSet\n});\nmodule.exports = __toCommonJS(addToSet_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $addToSet(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n const args = { $each: [val] };\n if ((0, import_util.isObject)(val) && (0, import_util.has)(val, \"$each\")) {\n Object.assign(args, val);\n }\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n const prev = o[k];\n if ((0, import_util.isArray)(prev)) {\n const set = (0, import_util.unique)(prev.concat(args.$each));\n if (set.length === prev.length) return false;\n o[k] = (0, import_internal.clone)(set, options);\n } else if (prev === void 0) {\n o[k] = (0, import_internal.clone)(args.$each, options);\n } else {\n return false;\n }\n return true;\n },\n { buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $addToSet\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar bit_exports = {};\n__export(bit_exports, {\n $bit: () => $bit\n});\nmodule.exports = __toCommonJS(bit_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nconst BIT_OPS = [\"and\", \"or\", \"xor\"];\nfunction $bit(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n for (const vals of Object.values(expr)) {\n (0, import_util.assert)((0, import_util.isObject)(vals), `$bit operator expression must be an object.`);\n const op = Object.keys(vals);\n (0, import_util.assert)(\n op.length === 1 && BIT_OPS.includes(op[0]),\n `$bit spec is invalid '${op[0]}'. Must be one of 'and', 'or', or 'xor'.`\n );\n (0, import_util.assert)(\n (0, import_util.isNumber)(vals[op[0]]),\n `$bit expression value must be a number. Got ${typeof vals[op[0]]}`\n );\n }\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n const op = Object.keys(val);\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n let n = o[k];\n const v = val[op[0]];\n if (n !== void 0 && !((0, import_util.isNumber)(n) && (0, import_util.isNumber)(v))) return false;\n n = n || 0;\n switch (op[0]) {\n case \"and\":\n return (o[k] = n & v) !== n;\n case \"or\":\n return (o[k] = n | v) !== n;\n case \"xor\":\n return (o[k] = n ^ v) !== n;\n }\n },\n { buildGraph: true }\n );\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $bit\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar currentDate_exports = {};\n__export(currentDate_exports, {\n $currentDate: () => $currentDate\n});\nmodule.exports = __toCommonJS(currentDate_exports);\nvar import_internal = require(\"./_internal\");\nfunction $currentDate(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n o[k] = val === true || val.$type === \"date\" ? options.now : options.now.getTime();\n return true;\n },\n { buildGraph: true }\n );\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $currentDate\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar inc_exports = {};\n__export(inc_exports, {\n $inc: () => $inc\n});\nmodule.exports = __toCommonJS(inc_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $inc(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n if ((0, import_util.isNumber)(o[k]) || o[k] === void 0) {\n o[k] ||= 0;\n o[k] += val;\n return true;\n }\n return false;\n },\n { buildGraph: true }\n );\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $inc\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar max_exports = {};\n__export(max_exports, {\n $max: () => $max\n});\nmodule.exports = __toCommonJS(max_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $max(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n if ((0, import_util.compare)(o[k], val) > -1) return false;\n o[k] = val;\n return true;\n },\n { buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $max\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar min_exports = {};\n__export(min_exports, {\n $min: () => $min\n});\nmodule.exports = __toCommonJS(min_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $min(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n if ((0, import_util.compare)(o[k], val) < 1) return false;\n o[k] = val;\n return true;\n },\n { buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $min\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar mul_exports = {};\n__export(mul_exports, {\n $mul: () => $mul\n});\nmodule.exports = __toCommonJS(mul_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $mul(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n const prev = o[k];\n if ((0, import_util.isNumber)(o[k])) o[k] = o[k] * val;\n else if (o[k] === void 0) o[k] = 0;\n return o[k] !== prev;\n },\n { buildGraph: true }\n );\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $mul\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pop_exports = {};\n__export(pop_exports, {\n $pop: () => $pop\n});\nmodule.exports = __toCommonJS(pop_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $pop(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => {\n const arr = o[k];\n if (!(0, import_util.isArray)(arr) || !arr.length) return false;\n if (val === -1) arr.splice(0, 1);\n else arr.pop();\n return true;\n });\n }\n );\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $pop\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pull_exports = {};\n__export(pull_exports, {\n $pull: () => $pull\n});\nmodule.exports = __toCommonJS(pull_exports);\nvar import_query = require(\"../../query\");\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $pull(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n const wrap = !(0, import_util.isObject)(val) || Object.keys(val).some(import_util.isOperator);\n const query = new import_query.Query(wrap ? { k: val } : val, options);\n const pred = wrap ? (v) => query.test({ k: v }) : (v) => query.test(v);\n return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => {\n const prev = o[k];\n if (!(0, import_util.isArray)(prev) || !prev.length) return false;\n const curr = new Array();\n let ok = false;\n for (const v of prev) {\n const b = pred(v);\n if (!b) curr.push(v);\n ok ||= b;\n }\n if (!ok) return false;\n o[k] = curr;\n return true;\n });\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $pull\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar pullAll_exports = {};\n__export(pullAll_exports, {\n $pullAll: () => $pullAll\n});\nmodule.exports = __toCommonJS(pullAll_exports);\nvar import_internal = require(\"./_internal\");\nvar import_pull = require(\"./pull\");\nfunction $pullAll(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n const pullExpr = {};\n for (const k of Object.keys(expr)) {\n pullExpr[k] = { $in: expr[k] };\n }\n return (0, import_pull.$pull)(pullExpr, arrayFilters, options);\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $pullAll\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar push_exports = {};\n__export(push_exports, {\n $push: () => $push\n});\nmodule.exports = __toCommonJS(push_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nconst MODIFIERS = [\"$each\", \"$slice\", \"$sort\", \"$position\"];\nfunction $push(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n const args = {\n $each: [val]\n };\n if ((0, import_util.isObject)(val) && MODIFIERS.some((m) => (0, import_util.has)(val, m))) {\n Object.assign(args, val);\n }\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n const arr = o[k];\n if (!(0, import_util.isArray)(arr)) {\n if (arr === void 0) {\n o[k] = (0, import_internal.clone)(args.$each, options);\n return true;\n }\n return false;\n }\n const prev = arr.slice(0, args.$slice || arr.length);\n const oldsize = arr.length;\n const pos = (0, import_util.isNumber)(args.$position) ? args.$position : arr.length;\n arr.splice(pos, 0, ...(0, import_internal.clone)(args.$each, options));\n if (args.$sort) {\n const sortKey = (0, import_util.isObject)(args.$sort) ? Object.keys(args.$sort)[0] : \"\";\n const order = !sortKey ? args.$sort : args.$sort[sortKey];\n const f = !sortKey ? (a) => a : (a) => (0, import_util.resolve)(a, sortKey);\n arr.sort((a, b) => order * (0, import_util.compare)(f(a), f(b)));\n }\n if ((0, import_util.isNumber)(args.$slice)) {\n if (args.$slice < 0) arr.splice(0, arr.length + args.$slice);\n else arr.splice(args.$slice);\n }\n return oldsize != arr.length || !(0, import_util.isEqual)(prev, arr);\n },\n { descendArray: true, buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $push\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar set_exports = {};\n__export(set_exports, {\n $set: () => $set\n});\nmodule.exports = __toCommonJS(set_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $set(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (val, node, queries) => {\n return (0, import_internal.applyUpdate)(\n obj,\n node,\n queries,\n (o, k) => {\n if ((0, import_util.isEqual)(o[k], val)) return false;\n o[k] = (0, import_internal.clone)(val, options);\n return true;\n },\n { buildGraph: true }\n );\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $set\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar rename_exports = {};\n__export(rename_exports, {\n $rename: () => $rename\n});\nmodule.exports = __toCommonJS(rename_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nvar import_set = require(\"./set\");\nconst isIdPath = (path, idKey) => path === idKey || path.startsWith(`${idKey}.`);\nfunction $rename(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n const idKey = options.idKey;\n for (const target of Object.values(expr)) {\n (0, import_util.assert)(\n !isIdPath(target, idKey),\n `Performing an update on the path '${target}' would modify the immutable field '${idKey}'.`\n );\n }\n return (obj) => {\n const res = [];\n const changed = (0, import_internal.walkExpression)(\n expr,\n arrayFilters,\n options,\n (val, node, queries) => {\n return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => {\n if (!(0, import_util.has)(o, k)) return false;\n Array.prototype.push.apply(\n res,\n (0, import_set.$set)({ [val]: o[k] }, arrayFilters, options)(obj)\n );\n delete o[k];\n return true;\n });\n }\n );\n return Array.from(new Set(changed.concat(res)));\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $rename\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar unset_exports = {};\n__export(unset_exports, {\n $unset: () => $unset\n});\nmodule.exports = __toCommonJS(unset_exports);\nvar import_util = require(\"../../util\");\nvar import_internal = require(\"./_internal\");\nfunction $unset(expr, arrayFilters = [], options = import_internal.DEFAULT_OPTIONS) {\n return (obj) => {\n return (0, import_internal.walkExpression)(expr, arrayFilters, options, (_, node, queries) => {\n return (0, import_internal.applyUpdate)(obj, node, queries, (o, k) => {\n if (!(0, import_util.has)(o, k)) return false;\n const prev = o[k];\n if ((0, import_util.isArray)(o)) o[k] = null;\n else delete o[k];\n return !(0, import_util.isEqual)(prev, o[k]);\n });\n });\n };\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n $unset\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, \"default\"), secondTarget && __copyProps(secondTarget, mod, \"default\"));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar update_exports = {};\nmodule.exports = __toCommonJS(update_exports);\n__reExport(update_exports, require(\"./addToSet\"), module.exports);\n__reExport(update_exports, require(\"./bit\"), module.exports);\n__reExport(update_exports, require(\"./currentDate\"), module.exports);\n__reExport(update_exports, require(\"./inc\"), module.exports);\n__reExport(update_exports, require(\"./max\"), module.exports);\n__reExport(update_exports, require(\"./min\"), module.exports);\n__reExport(update_exports, require(\"./mul\"), module.exports);\n__reExport(update_exports, require(\"./pop\"), module.exports);\n__reExport(update_exports, require(\"./pull\"), module.exports);\n__reExport(update_exports, require(\"./pullAll\"), module.exports);\n__reExport(update_exports, require(\"./push\"), module.exports);\n__reExport(update_exports, require(\"./rename\"), module.exports);\n__reExport(update_exports, require(\"./set\"), module.exports);\n__reExport(update_exports, require(\"./unset\"), module.exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n ...require(\"./addToSet\"),\n ...require(\"./bit\"),\n ...require(\"./currentDate\"),\n ...require(\"./inc\"),\n ...require(\"./max\"),\n ...require(\"./min\"),\n ...require(\"./mul\"),\n ...require(\"./pop\"),\n ...require(\"./pull\"),\n ...require(\"./pullAll\"),\n ...require(\"./push\"),\n ...require(\"./rename\"),\n ...require(\"./set\"),\n ...require(\"./unset\")\n});\n", "var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar updater_exports = {};\n__export(updater_exports, {\n update: () => update,\n updateMany: () => updateMany,\n updateOne: () => updateOne\n});\nmodule.exports = __toCommonJS(updater_exports);\nvar import_internal = require(\"./core/_internal\");\nvar import_lazy = require(\"./lazy\");\nvar booleanOperators = __toESM(require(\"./operators/expression/boolean\"));\nvar comparisonOperators = __toESM(require(\"./operators/expression/comparison\"));\nvar import_addFields = require(\"./operators/pipeline/addFields\");\nvar import_project = require(\"./operators/pipeline/project\");\nvar import_replaceRoot = require(\"./operators/pipeline/replaceRoot\");\nvar import_replaceWith = require(\"./operators/pipeline/replaceWith\");\nvar import_set = require(\"./operators/pipeline/set\");\nvar import_sort = require(\"./operators/pipeline/sort\");\nvar import_unset = require(\"./operators/pipeline/unset\");\nvar queryOperators = __toESM(require(\"./operators/query\"));\nvar updateOperators = __toESM(require(\"./operators/update\"));\nvar import_internal2 = require(\"./operators/update/_internal\");\nvar import_query = require(\"./query\");\nvar import_internal3 = require(\"./util/_internal\");\nconst UPDATE_OPERATORS = updateOperators;\nconst PIPELINE_OPERATORS = {\n $addFields: import_addFields.$addFields,\n $set: import_set.$set,\n $project: import_project.$project,\n $unset: import_unset.$unset,\n $replaceRoot: import_replaceRoot.$replaceRoot,\n $replaceWith: import_replaceWith.$replaceWith\n};\nfunction update(obj, modifier, arrayFilters, condition, options) {\n const docs = [obj];\n const res = updateOne(\n docs,\n condition || {},\n modifier,\n { arrayFilters, cloneMode: options?.cloneMode ?? \"copy\" },\n options?.queryOptions\n );\n return res.modifiedFields ?? [];\n}\nfunction updateMany(documents, condition, modifier, updateConfig = {}, options) {\n const { modifiedCount, matchedCount } = updateDocuments(\n documents,\n condition,\n modifier,\n updateConfig,\n options\n );\n return { modifiedCount, matchedCount };\n}\nfunction updateOne(documents, condition, modifier, updateConfig = {}, options) {\n return updateDocuments(documents, condition, modifier, updateConfig, {\n ...options,\n firstOnly: true\n });\n}\nfunction updateDocuments(documents, condition, modifier, updateConfig = {}, options) {\n options ||= {};\n const firstOnly = options?.firstOnly ?? false;\n const opts = import_internal.ComputeOptions.init({\n ...options,\n collation: Object.assign({}, options?.collation, updateConfig?.collation)\n }).update({\n condition,\n updateConfig: { cloneMode: \"copy\", ...updateConfig },\n variables: updateConfig.let,\n updateParams: {}\n });\n opts.context.addExpressionOps(booleanOperators).addExpressionOps(comparisonOperators).addQueryOps(queryOperators).addPipelineOps(PIPELINE_OPERATORS);\n const filterExists = Object.keys(condition).length > 0;\n const matchedDocs = /* @__PURE__ */ new Map();\n let docsIter = (0, import_lazy.Lazy)(documents);\n if (filterExists) {\n const query = new import_query.Query(condition, opts);\n docsIter = docsIter.filter((o, i) => {\n if (query.test(o)) {\n matchedDocs.set(o, i);\n return true;\n }\n return false;\n });\n }\n let modifiedIndex = -1;\n if (firstOnly) {\n const indexes = /* @__PURE__ */ new Map();\n if (updateConfig.sort) {\n if (!filterExists) {\n docsIter = docsIter.map((o, i) => {\n indexes.set(o, i);\n return o;\n });\n }\n docsIter = (0, import_sort.$sort)(docsIter, updateConfig.sort, opts);\n }\n docsIter = docsIter.take(1);\n const firstDoc = docsIter.collect()[0];\n modifiedIndex = matchedDocs.get(firstDoc) ?? indexes.get(firstDoc) ?? 0;\n }\n const foundDocs = docsIter.collect();\n if (foundDocs.length === 0) return { matchedCount: 0, modifiedCount: 0 };\n if ((0, import_internal3.isArray)(modifier)) {\n const indexes = firstOnly ? [modifiedIndex] : Array.from(matchedDocs.values());\n const hashes = indexes.length ? indexes.map((i) => (0, import_internal3.hashCode)(documents[i])) : foundDocs.map((o) => (0, import_internal3.hashCode)(o));\n const output2 = { matchedCount: hashes.length, modifiedCount: 0 };\n const oldFirstDoc = firstOnly ? (0, import_internal3.cloneDeep)(documents[indexes[0]]) : void 0;\n let updateIter = (0, import_lazy.Lazy)(foundDocs);\n for (const stage of modifier) {\n const [op, expr] = Object.entries(stage)[0];\n const pipelineOp = PIPELINE_OPERATORS[op];\n (0, import_internal3.assert)(pipelineOp, `Unknown pipeline operator: '${op}'.`);\n updateIter = pipelineOp(updateIter, expr, opts);\n }\n const matches = updateIter.collect();\n if (indexes.length) {\n (0, import_internal3.assert)(\n indexes.length === matches.length,\n \"bug: indexes and result size must match.\"\n );\n for (let i = 0; i < indexes.length; i++) {\n if ((0, import_internal3.hashCode)(matches[i]) !== hashes[i]) {\n documents[indexes[i]] = matches[i];\n output2.modifiedCount++;\n }\n }\n } else {\n for (let i = 0; i < documents.length; i++) {\n if ((0, import_internal3.hashCode)(matches[i]) !== hashes[i]) {\n documents[i] = matches[i];\n output2.modifiedCount++;\n }\n }\n }\n if (firstOnly && output2.modifiedCount && oldFirstDoc) {\n const newDoc = documents[indexes[0]];\n const modifiedFields2 = getModifiedFields(\n modifier,\n oldFirstDoc,\n newDoc\n );\n (0, import_internal3.assert)(modifiedFields2.length, \"bug: failed to retrieve modified fields\");\n Object.assign(output2, { modifiedFields: modifiedFields2, modifiedIndex });\n }\n return output2;\n }\n const unknownOp = Object.keys(modifier).find((op) => !UPDATE_OPERATORS[op]);\n (0, import_internal3.assert)(!unknownOp, `Unknown update operator: '${unknownOp}'.`);\n const arrayFilters = updateConfig?.arrayFilters ?? [];\n opts.update({\n updateParams: (0, import_internal2.buildParams)(\n Object.values(modifier),\n arrayFilters,\n opts\n )\n });\n const matchedCount = foundDocs.length;\n const output = { matchedCount, modifiedCount: 0 };\n const modifiedFields = [];\n const fns = [];\n for (const op of Object.keys(modifier)) {\n const fn = UPDATE_OPERATORS[op];\n const expr = modifier[op];\n fns.push(fn(expr, arrayFilters, opts));\n }\n for (const doc of foundDocs) {\n let modified = false;\n for (const mutate of fns) {\n const fields = mutate(doc);\n if (fields.length) {\n modified = true;\n if (firstOnly) Array.prototype.push.apply(modifiedFields, fields);\n }\n }\n output.modifiedCount += +modified;\n }\n if (firstOnly && modifiedFields.length) {\n modifiedFields.sort();\n Object.assign(output, { modifiedFields, modifiedIndex });\n }\n return output;\n}\nfunction getModifiedFields(pipeline, oldDoc, newDoc) {\n const stageFields = [];\n for (const stage of pipeline) {\n const op = Object.keys(stage)[0];\n const expr = stage[op];\n switch (op) {\n case \"$addFields\":\n case \"$set\":\n case \"$project\":\n case \"$replaceWith\":\n stageFields.push(...Object.keys(expr));\n break;\n case \"$unset\":\n stageFields.push(...(0, import_internal3.ensureArray)(expr));\n break;\n case \"$replaceRoot\":\n stageFields.length = 0;\n stageFields.push(\n ...Object.keys(expr?.newRoot)\n );\n break;\n }\n }\n const stageFieldsSet = new Set(stageFields.sort());\n const pathValidator = new import_internal3.PathValidator();\n const modifiedFields = [];\n for (const key of stageFieldsSet) {\n if (pathValidator.add(key) && !(0, import_internal3.isEqual)((0, import_internal3.resolve)(newDoc, key), (0, import_internal3.resolve)(oldDoc, key))) {\n modifiedFields.push(key);\n }\n }\n for (const key of Object.keys(oldDoc)) {\n if (stageFieldsSet.has(key)) continue;\n if (!pathValidator.add(key) || !(0, import_internal3.isEqual)(newDoc[key], oldDoc[key])) {\n modifiedFields.push(key);\n }\n }\n const topLevelValidator = new import_internal3.PathValidator();\n return modifiedFields.sort().filter((key) => topLevelValidator.add(key));\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n update,\n updateMany,\n updateOne\n});\n", "var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar core_exports = {};\n__export(core_exports, {\n Context: () => import_internal.Context,\n OpType: () => import_internal.OpType,\n ProcessingMode: () => import_internal.ProcessingMode,\n computeValue: () => import_internal.computeValue,\n evalExpr: () => import_internal.evalExpr\n});\nmodule.exports = __toCommonJS(core_exports);\nvar import_internal = require(\"./_internal\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Context,\n OpType,\n ProcessingMode,\n computeValue,\n evalExpr\n});\n", "var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar index_exports = {};\n__export(index_exports, {\n Aggregator: () => Aggregator,\n Context: () => import_core.Context,\n ProcessingMode: () => import_core.ProcessingMode,\n Query: () => Query,\n aggregate: () => aggregate,\n default: () => index_default,\n find: () => find,\n update: () => update,\n updateMany: () => updateMany,\n updateOne: () => updateOne\n});\nmodule.exports = __toCommonJS(index_exports);\nvar import_aggregator = require(\"./aggregator\");\nvar import_internal = require(\"./core/_internal\");\nvar accumulatorOperators = __toESM(require(\"./operators/accumulator\"));\nvar expressionOperators = __toESM(require(\"./operators/expression\"));\nvar pipelineOperators = __toESM(require(\"./operators/pipeline\"));\nvar projectionOperators = __toESM(require(\"./operators/projection\"));\nvar queryOperators = __toESM(require(\"./operators/query\"));\nvar windowOperators = __toESM(require(\"./operators/window\"));\nvar import_query = require(\"./query\");\nvar updater = __toESM(require(\"./updater\"));\nvar import_core = require(\"./core\");\nconst CONTEXT = import_internal.Context.init({\n accumulator: accumulatorOperators,\n expression: expressionOperators,\n pipeline: pipelineOperators,\n projection: projectionOperators,\n query: queryOperators,\n window: windowOperators\n});\nconst makeOpts = (options) => Object.assign({\n ...options,\n context: options?.context ? import_internal.Context.from(CONTEXT, options?.context) : CONTEXT\n});\nclass Query extends import_query.Query {\n constructor(condition, options) {\n super(condition, makeOpts(options));\n }\n}\nclass Aggregator extends import_aggregator.Aggregator {\n constructor(pipeline, options) {\n super(pipeline, makeOpts(options));\n }\n}\nfunction find(collection, condition, projection, options) {\n return new Query(condition, makeOpts(options)).find(\n collection,\n projection\n );\n}\nfunction aggregate(collection, pipeline, options) {\n return new Aggregator(pipeline, makeOpts(options)).run(collection);\n}\nfunction update(obj, modifier, arrayFilters, condition, options) {\n return updater.update(obj, modifier, arrayFilters, condition, {\n cloneMode: options?.cloneMode,\n queryOptions: makeOpts(options?.queryOptions)\n });\n}\nfunction updateMany(documents, condition, modifer, updateConfig = {}, options) {\n return updater.updateMany(\n documents,\n condition,\n modifer,\n updateConfig,\n makeOpts(options)\n );\n}\nfunction updateOne(documents, condition, modifier, updateConfig = {}, options) {\n return updater.updateOne(\n documents,\n condition,\n modifier,\n updateConfig,\n makeOpts(options)\n );\n}\nvar index_default = {\n Aggregator,\n Context: import_internal.Context,\n ProcessingMode: import_internal.ProcessingMode,\n Query,\n aggregate,\n find,\n update,\n updateMany,\n updateOne\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Aggregator,\n Context,\n ProcessingMode,\n Query,\n aggregate,\n find,\n update,\n updateMany,\n updateOne\n});\n", "//#region src/env/env-impl.ts\nconst _envShim = Object.create(null);\nconst _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis);\nconst env = new Proxy(_envShim, {\n\tget(_, prop) {\n\t\treturn _getEnv()[prop] ?? _envShim[prop];\n\t},\n\thas(_, prop) {\n\t\treturn prop in _getEnv() || prop in _envShim;\n\t},\n\tset(_, prop, value) {\n\t\tconst env = _getEnv(true);\n\t\tenv[prop] = value;\n\t\treturn true;\n\t},\n\tdeleteProperty(_, prop) {\n\t\tif (!prop) return false;\n\t\tconst env = _getEnv(true);\n\t\tdelete env[prop];\n\t\treturn true;\n\t},\n\townKeys() {\n\t\tconst env = _getEnv(true);\n\t\treturn Object.keys(env);\n\t}\n});\nfunction toBoolean(val) {\n\treturn val ? val !== \"false\" : false;\n}\nconst nodeENV = typeof process !== \"undefined\" && process.env && process.env.NODE_ENV || \"\";\n/** Detect if `NODE_ENV` environment variable is `production` */\nconst isProduction = nodeENV === \"production\";\n/** Detect if `NODE_ENV` environment variable is `dev` or `development` */\nconst isDevelopment = () => nodeENV === \"dev\" || nodeENV === \"development\";\n/** Detect if `NODE_ENV` environment variable is `test` */\nconst isTest = () => nodeENV === \"test\" || toBoolean(env.TEST);\n/**\n* Get environment variable with fallback\n*/\nfunction getEnvVar(key, fallback) {\n\tif (typeof process !== \"undefined\" && process.env) return process.env[key] ?? fallback;\n\tif (typeof Deno !== \"undefined\") return Deno.env.get(key) ?? fallback;\n\tif (typeof Bun !== \"undefined\") return Bun.env[key] ?? fallback;\n\treturn fallback;\n}\n/**\n* Get boolean environment variable\n*/\nfunction getBooleanEnvVar(key, fallback = true) {\n\tconst value = getEnvVar(key);\n\tif (!value) return fallback;\n\treturn value !== \"0\" && value.toLowerCase() !== \"false\" && value !== \"\";\n}\n/**\n* Common environment variables used in Better Auth\n*/\nconst ENV = Object.freeze({\n\tget BETTER_AUTH_SECRET() {\n\t\treturn getEnvVar(\"BETTER_AUTH_SECRET\");\n\t},\n\tget AUTH_SECRET() {\n\t\treturn getEnvVar(\"AUTH_SECRET\");\n\t},\n\tget BETTER_AUTH_TELEMETRY() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY\");\n\t},\n\tget BETTER_AUTH_TELEMETRY_ID() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY_ID\");\n\t},\n\tget NODE_ENV() {\n\t\treturn getEnvVar(\"NODE_ENV\", \"development\");\n\t},\n\tget PACKAGE_VERSION() {\n\t\treturn getEnvVar(\"PACKAGE_VERSION\", \"0.0.0\");\n\t},\n\tget BETTER_AUTH_TELEMETRY_ENDPOINT() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY_ENDPOINT\", \"\");\n\t}\n});\n//#endregion\nexport { ENV, env, getBooleanEnvVar, getEnvVar, isDevelopment, isProduction, isTest, nodeENV };\n", "import { env, getEnvVar } from \"./env-impl.mjs\";\n//#region src/env/color-depth.ts\nconst COLORS_2 = 1;\nconst COLORS_16 = 4;\nconst COLORS_256 = 8;\nconst COLORS_16m = 24;\nconst TERM_ENVS = {\n\teterm: COLORS_16,\n\tcons25: COLORS_16,\n\tconsole: COLORS_16,\n\tcygwin: COLORS_16,\n\tdtterm: COLORS_16,\n\tgnome: COLORS_16,\n\thurd: COLORS_16,\n\tjfbterm: COLORS_16,\n\tkonsole: COLORS_16,\n\tkterm: COLORS_16,\n\tmlterm: COLORS_16,\n\tmosh: COLORS_16m,\n\tputty: COLORS_16,\n\tst: COLORS_16,\n\t\"rxvt-unicode-24bit\": COLORS_16m,\n\tterminator: COLORS_16m,\n\t\"xterm-kitty\": COLORS_16m\n};\nconst CI_ENVS_MAP = new Map(Object.entries({\n\tAPPVEYOR: COLORS_256,\n\tBUILDKITE: COLORS_256,\n\tCIRCLECI: COLORS_16m,\n\tDRONE: COLORS_256,\n\tGITEA_ACTIONS: COLORS_16m,\n\tGITHUB_ACTIONS: COLORS_16m,\n\tGITLAB_CI: COLORS_256,\n\tTRAVIS: COLORS_256\n}));\nconst TERM_ENVS_REG_EXP = [\n\t/ansi/,\n\t/color/,\n\t/linux/,\n\t/direct/,\n\t/^con[0-9]*x[0-9]/,\n\t/^rxvt/,\n\t/^screen/,\n\t/^xterm/,\n\t/^vt100/,\n\t/^vt220/\n];\nfunction getColorDepth() {\n\tif (getEnvVar(\"FORCE_COLOR\") !== void 0) switch (getEnvVar(\"FORCE_COLOR\")) {\n\t\tcase \"\":\n\t\tcase \"1\":\n\t\tcase \"true\": return COLORS_16;\n\t\tcase \"2\": return COLORS_256;\n\t\tcase \"3\": return COLORS_16m;\n\t\tdefault: return COLORS_2;\n\t}\n\tif (getEnvVar(\"NODE_DISABLE_COLORS\") !== void 0 && getEnvVar(\"NODE_DISABLE_COLORS\") !== \"\" || getEnvVar(\"NO_COLOR\") !== void 0 && getEnvVar(\"NO_COLOR\") !== \"\" || getEnvVar(\"TERM\") === \"dumb\") return COLORS_2;\n\tif (getEnvVar(\"TMUX\")) return COLORS_16m;\n\tif (\"TF_BUILD\" in env && \"AGENT_NAME\" in env) return COLORS_16;\n\tif (\"CI\" in env) {\n\t\tfor (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors;\n\t\tif (getEnvVar(\"CI_NAME\") === \"codeship\") return COLORS_256;\n\t\treturn COLORS_2;\n\t}\n\tif (\"TEAMCITY_VERSION\" in env) return /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.exec(getEnvVar(\"TEAMCITY_VERSION\")) !== null ? COLORS_16 : COLORS_2;\n\tswitch (getEnvVar(\"TERM_PROGRAM\")) {\n\t\tcase \"iTerm.app\":\n\t\t\tif (!getEnvVar(\"TERM_PROGRAM_VERSION\") || /^[0-2]\\./.exec(getEnvVar(\"TERM_PROGRAM_VERSION\")) !== null) return COLORS_256;\n\t\t\treturn COLORS_16m;\n\t\tcase \"HyperTerm\":\n\t\tcase \"MacTerm\": return COLORS_16m;\n\t\tcase \"Apple_Terminal\": return COLORS_256;\n\t}\n\tif (getEnvVar(\"COLORTERM\") === \"truecolor\" || getEnvVar(\"COLORTERM\") === \"24bit\") return COLORS_16m;\n\tif (getEnvVar(\"TERM\")) {\n\t\tif (/truecolor/.exec(getEnvVar(\"TERM\")) !== null) return COLORS_16m;\n\t\tif (/^xterm-256/.exec(getEnvVar(\"TERM\")) !== null) return COLORS_256;\n\t\tconst termEnv = getEnvVar(\"TERM\").toLowerCase();\n\t\tif (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv];\n\t\tif (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16;\n\t}\n\tif (getEnvVar(\"COLORTERM\")) return COLORS_16;\n\treturn COLORS_2;\n}\n//#endregion\nexport { getColorDepth };\n", "import { getColorDepth } from \"./color-depth.mjs\";\n//#region src/env/logger.ts\nconst TTY_COLORS = {\n\treset: \"\\x1B[0m\",\n\tbright: \"\\x1B[1m\",\n\tdim: \"\\x1B[2m\",\n\tundim: \"\\x1B[22m\",\n\tunderscore: \"\\x1B[4m\",\n\tblink: \"\\x1B[5m\",\n\treverse: \"\\x1B[7m\",\n\thidden: \"\\x1B[8m\",\n\tfg: {\n\t\tblack: \"\\x1B[30m\",\n\t\tred: \"\\x1B[31m\",\n\t\tgreen: \"\\x1B[32m\",\n\t\tyellow: \"\\x1B[33m\",\n\t\tblue: \"\\x1B[34m\",\n\t\tmagenta: \"\\x1B[35m\",\n\t\tcyan: \"\\x1B[36m\",\n\t\twhite: \"\\x1B[37m\"\n\t},\n\tbg: {\n\t\tblack: \"\\x1B[40m\",\n\t\tred: \"\\x1B[41m\",\n\t\tgreen: \"\\x1B[42m\",\n\t\tyellow: \"\\x1B[43m\",\n\t\tblue: \"\\x1B[44m\",\n\t\tmagenta: \"\\x1B[45m\",\n\t\tcyan: \"\\x1B[46m\",\n\t\twhite: \"\\x1B[47m\"\n\t}\n};\nconst levels = [\n\t\"debug\",\n\t\"info\",\n\t\"success\",\n\t\"warn\",\n\t\"error\"\n];\nfunction shouldPublishLog(currentLogLevel, logLevel) {\n\treturn levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel);\n}\nconst levelColors = {\n\tinfo: TTY_COLORS.fg.blue,\n\tsuccess: TTY_COLORS.fg.green,\n\twarn: TTY_COLORS.fg.yellow,\n\terror: TTY_COLORS.fg.red,\n\tdebug: TTY_COLORS.fg.magenta\n};\nconst formatMessage = (level, message, colorsEnabled) => {\n\tconst timestamp = (/* @__PURE__ */ new Date()).toISOString();\n\tif (colorsEnabled) return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message}`;\n\treturn `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message}`;\n};\nconst createLogger = (options) => {\n\tconst enabled = options?.disabled !== true;\n\tconst logLevel = options?.level ?? \"warn\";\n\tconst colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1;\n\tconst LogFunc = (level, message, args = []) => {\n\t\tif (!enabled || !shouldPublishLog(logLevel, level)) return;\n\t\tconst formattedMessage = formatMessage(level, message, colorsEnabled);\n\t\tif (!options || typeof options.log !== \"function\") {\n\t\t\tif (level === \"error\") console.error(formattedMessage, ...args);\n\t\t\telse if (level === \"warn\") console.warn(formattedMessage, ...args);\n\t\t\telse console.log(formattedMessage, ...args);\n\t\t\treturn;\n\t\t}\n\t\toptions.log(level === \"success\" ? \"info\" : level, message, ...args);\n\t};\n\treturn {\n\t\t...Object.fromEntries(levels.map((level) => [level, (...[message, ...args]) => LogFunc(level, message, args)])),\n\t\tget level() {\n\t\t\treturn logLevel;\n\t\t}\n\t};\n};\nconst logger = createLogger();\n//#endregion\nexport { TTY_COLORS, createLogger, levels, logger, shouldPublishLog };\n", "import { ENV, env, getBooleanEnvVar, getEnvVar, isDevelopment, isProduction, isTest, nodeENV } from \"./env-impl.mjs\";\nimport { getColorDepth } from \"./color-depth.mjs\";\nimport { TTY_COLORS, createLogger, levels, logger, shouldPublishLog } from \"./logger.mjs\";\nexport { ENV, TTY_COLORS, createLogger, env, getBooleanEnvVar, getColorDepth, getEnvVar, isDevelopment, isProduction, isTest, levels, logger, nodeENV, shouldPublishLog };\n", "//#region src/utils/error-codes.ts\nfunction defineErrorCodes(codes) {\n\treturn Object.fromEntries(Object.entries(codes).map(([key, value]) => [key, {\n\t\tcode: key,\n\t\tmessage: value,\n\t\ttoString: () => key\n\t}]));\n}\n//#endregion\nexport { defineErrorCodes };\n", "import { defineErrorCodes } from \"../utils/error-codes.mjs\";\n//#region src/error/codes.ts\nconst BASE_ERROR_CODES = defineErrorCodes({\n\tUSER_NOT_FOUND: \"User not found\",\n\tFAILED_TO_CREATE_USER: \"Failed to create user\",\n\tFAILED_TO_CREATE_SESSION: \"Failed to create session\",\n\tFAILED_TO_UPDATE_USER: \"Failed to update user\",\n\tFAILED_TO_GET_SESSION: \"Failed to get session\",\n\tINVALID_PASSWORD: \"Invalid password\",\n\tINVALID_EMAIL: \"Invalid email\",\n\tINVALID_EMAIL_OR_PASSWORD: \"Invalid email or password\",\n\tINVALID_USER: \"Invalid user\",\n\tSOCIAL_ACCOUNT_ALREADY_LINKED: \"Social account already linked\",\n\tPROVIDER_NOT_FOUND: \"Provider not found\",\n\tINVALID_TOKEN: \"Invalid token\",\n\tTOKEN_EXPIRED: \"Token expired\",\n\tID_TOKEN_NOT_SUPPORTED: \"id_token not supported\",\n\tFAILED_TO_GET_USER_INFO: \"Failed to get user info\",\n\tUSER_EMAIL_NOT_FOUND: \"User email not found\",\n\tEMAIL_NOT_VERIFIED: \"Email not verified\",\n\tPASSWORD_TOO_SHORT: \"Password too short\",\n\tPASSWORD_TOO_LONG: \"Password too long\",\n\tUSER_ALREADY_EXISTS: \"User already exists.\",\n\tUSER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: \"User already exists. Use another email.\",\n\tEMAIL_CAN_NOT_BE_UPDATED: \"Email can not be updated\",\n\tCREDENTIAL_ACCOUNT_NOT_FOUND: \"Credential account not found\",\n\tSESSION_EXPIRED: \"Session expired. Re-authenticate to perform this action.\",\n\tFAILED_TO_UNLINK_LAST_ACCOUNT: \"You can't unlink your last account\",\n\tACCOUNT_NOT_FOUND: \"Account not found\",\n\tUSER_ALREADY_HAS_PASSWORD: \"User already has a password. Provide that to delete the account.\",\n\tCROSS_SITE_NAVIGATION_LOGIN_BLOCKED: \"Cross-site navigation login blocked. This request appears to be a CSRF attack.\",\n\tVERIFICATION_EMAIL_NOT_ENABLED: \"Verification email isn't enabled\",\n\tEMAIL_ALREADY_VERIFIED: \"Email is already verified\",\n\tEMAIL_MISMATCH: \"Email mismatch\",\n\tSESSION_NOT_FRESH: \"Session is not fresh\",\n\tLINKED_ACCOUNT_ALREADY_EXISTS: \"Linked account already exists\",\n\tINVALID_ORIGIN: \"Invalid origin\",\n\tINVALID_CALLBACK_URL: \"Invalid callbackURL\",\n\tINVALID_REDIRECT_URL: \"Invalid redirectURL\",\n\tINVALID_ERROR_CALLBACK_URL: \"Invalid errorCallbackURL\",\n\tINVALID_NEW_USER_CALLBACK_URL: \"Invalid newUserCallbackURL\",\n\tMISSING_OR_NULL_ORIGIN: \"Missing or null Origin\",\n\tCALLBACK_URL_REQUIRED: \"callbackURL is required\",\n\tFAILED_TO_CREATE_VERIFICATION: \"Unable to create verification\",\n\tFIELD_NOT_ALLOWED: \"Field not allowed to be set\",\n\tASYNC_VALIDATION_NOT_SUPPORTED: \"Async validation is not supported\",\n\tVALIDATION_ERROR: \"Validation Error\",\n\tMISSING_FIELD: \"Field is required\",\n\tMETHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED: \"POST method requires deferSessionRefresh to be enabled in session config\",\n\tBODY_MUST_BE_AN_OBJECT: \"Body must be an object\",\n\tPASSWORD_ALREADY_SET: \"User already has a password set\"\n});\n//#endregion\nexport { BASE_ERROR_CODES };\n", "import type { StandardSchemaV1 } from \"./standard-schema\";\n// https://github.com/nodejs/node/blob/360f7cc7867b43344aac00564286b895e15f21d7/lib/internal/errors.js#L246C1-L261C2\nfunction isErrorStackTraceLimitWritable() {\n\tconst desc = Object.getOwnPropertyDescriptor(Error, \"stackTraceLimit\");\n\tif (desc === undefined) {\n\t\treturn Object.isExtensible(Error);\n\t}\n\n\treturn Object.prototype.hasOwnProperty.call(desc, \"writable\")\n\t\t? desc.writable\n\t\t: desc.set !== undefined;\n}\n\n/**\n * Hide internal stack frames from the error stack trace.\n */\nexport function hideInternalStackFrames(stack: string): string {\n\tconst lines = stack.split(\"\\n at \");\n\tif (lines.length <= 1) {\n\t\treturn stack;\n\t}\n\tlines.splice(1, 1);\n\treturn lines.join(\"\\n at \");\n}\n\n// https://github.com/nodejs/node/blob/360f7cc7867b43344aac00564286b895e15f21d7/lib/internal/errors.js#L411-L432\n/**\n * Creates a custom error class that hides stack frames.\n */\nexport function makeErrorForHideStackFrame<\n\tB extends new (\n\t\t...args: any[]\n\t) => Error,\n>(\n\tBase: B,\n\tclazz: any,\n): {\n\tnew (\n\t\t...args: ConstructorParameters\n\t): InstanceType & { errorStack: string | undefined };\n} {\n\tclass HideStackFramesError extends Base {\n\t\t#hiddenStack: string | undefined;\n\n\t\tconstructor(...args: any[]) {\n\t\t\tif (isErrorStackTraceLimitWritable()) {\n\t\t\t\tconst limit = Error.stackTraceLimit;\n\t\t\t\tError.stackTraceLimit = 0;\n\t\t\t\tsuper(...args);\n\t\t\t\tError.stackTraceLimit = limit;\n\t\t\t} else {\n\t\t\t\tsuper(...args);\n\t\t\t}\n\t\t\tconst stack = new Error().stack;\n\t\t\tif (stack) {\n\t\t\t\tthis.#hiddenStack = hideInternalStackFrames(\n\t\t\t\t\tstack.replace(/^Error/, this.name),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// use `getter` here to avoid the stack trace being captured by loggers\n\t\tget errorStack() {\n\t\t\treturn this.#hiddenStack;\n\t\t}\n\t}\n\n\t// This is a workaround for wpt tests that expect that the error\n\t// constructor has a `name` property of the base class.\n\tObject.defineProperty(HideStackFramesError.prototype, \"constructor\", {\n\t\tget() {\n\t\t\treturn clazz;\n\t\t},\n\t\tenumerable: false,\n\t\tconfigurable: true,\n\t});\n\n\treturn HideStackFramesError as any;\n}\n\nexport const statusCodes = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n\nexport type Status =\n\t| 100\n\t| 101\n\t| 102\n\t| 103\n\t| 200\n\t| 201\n\t| 202\n\t| 203\n\t| 204\n\t| 205\n\t| 206\n\t| 207\n\t| 208\n\t| 226\n\t| 300\n\t| 301\n\t| 302\n\t| 303\n\t| 304\n\t| 305\n\t| 306\n\t| 307\n\t| 308\n\t| 400\n\t| 401\n\t| 402\n\t| 403\n\t| 404\n\t| 405\n\t| 406\n\t| 407\n\t| 408\n\t| 409\n\t| 410\n\t| 411\n\t| 412\n\t| 413\n\t| 414\n\t| 415\n\t| 416\n\t| 417\n\t| 418\n\t| 421\n\t| 422\n\t| 423\n\t| 424\n\t| 425\n\t| 426\n\t| 428\n\t| 429\n\t| 431\n\t| 451\n\t| 500\n\t| 501\n\t| 502\n\t| 503\n\t| 504\n\t| 505\n\t| 506\n\t| 507\n\t| 508\n\t| 510\n\t| 511;\n\nclass InternalAPIError extends Error {\n\tconstructor(\n\t\tpublic status: keyof typeof statusCodes | Status = \"INTERNAL_SERVER_ERROR\",\n\t\tpublic body:\n\t\t\t| ({\n\t\t\t\t\tmessage?: string;\n\t\t\t\t\tcode?: string;\n\t\t\t\t\tcause?: unknown;\n\t\t\t } & Record)\n\t\t\t| undefined = undefined,\n\t\tpublic headers: HeadersInit = {},\n\t\tpublic statusCode = typeof status === \"number\"\n\t\t\t? status\n\t\t\t: statusCodes[status],\n\t) {\n\t\tsuper(\n\t\t\tbody?.message,\n\t\t\tbody?.cause\n\t\t\t\t? {\n\t\t\t\t\t\tcause: body.cause,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t);\n\t\tthis.name = \"APIError\";\n\t\tthis.status = status;\n\t\tthis.headers = headers;\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body;\n\t}\n}\n\nexport class ValidationError extends InternalAPIError {\n\tconstructor(\n\t\tpublic message: string,\n\t\tpublic issues: readonly StandardSchemaV1.Issue[],\n\t) {\n\t\tsuper(400, {\n\t\t\tmessage: message,\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t});\n\n\t\tthis.issues = issues;\n\t}\n}\n\nexport class BetterCallError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"BetterCallError\";\n\t}\n}\n\nexport const kAPIErrorHeaderSymbol = Symbol.for(\n\t\"better-call:api-error-headers\",\n);\n\nexport type APIError = InstanceType;\nexport const APIError = makeErrorForHideStackFrame(InternalAPIError, Error);\n", "import { BASE_ERROR_CODES } from \"./codes.mjs\";\nimport { APIError as APIError$1 } from \"better-call/error\";\n//#region src/error/index.ts\nvar BetterAuthError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"BetterAuthError\";\n\t\tthis.message = message;\n\t\tthis.stack = \"\";\n\t}\n};\nvar APIError = class APIError extends APIError$1 {\n\tconstructor(...args) {\n\t\tsuper(...args);\n\t}\n\tstatic fromStatus(status, body) {\n\t\treturn new APIError(status, body);\n\t}\n\tstatic from(status, error) {\n\t\treturn new APIError(status, {\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code\n\t\t});\n\t}\n};\n//#endregion\nexport { APIError, BASE_ERROR_CODES, BetterAuthError };\n", "function expandAlphabet(alphabet) {\n switch (alphabet) {\n case \"a-z\":\n return \"abcdefghijklmnopqrstuvwxyz\";\n case \"A-Z\":\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n case \"0-9\":\n return \"0123456789\";\n case \"-_\":\n return \"-_\";\n default:\n throw new Error(`Unsupported alphabet: ${alphabet}`);\n }\n}\nfunction createRandomStringGenerator(...baseAlphabets) {\n const baseCharSet = baseAlphabets.map(expandAlphabet).join(\"\");\n if (baseCharSet.length === 0) {\n throw new Error(\n \"No valid characters provided for random string generation.\"\n );\n }\n const baseCharSetLength = baseCharSet.length;\n return (length, ...alphabets) => {\n if (length <= 0) {\n throw new Error(\"Length must be a positive integer.\");\n }\n let charSet = baseCharSet;\n let charSetLength = baseCharSetLength;\n if (alphabets.length > 0) {\n charSet = alphabets.map(expandAlphabet).join(\"\");\n charSetLength = charSet.length;\n }\n const maxValid = Math.floor(256 / charSetLength) * charSetLength;\n const buf = new Uint8Array(length * 2);\n const bufLength = buf.length;\n let result = \"\";\n let bufIndex = bufLength;\n let rand;\n while (result.length < length) {\n if (bufIndex >= bufLength) {\n crypto.getRandomValues(buf);\n bufIndex = 0;\n }\n rand = buf[bufIndex++];\n if (rand < maxValid) {\n result += charSet[rand % charSetLength];\n }\n }\n return result;\n };\n}\n\nexport { createRandomStringGenerator };\n", "//#region src/db/get-tables.ts\nconst getAuthTables = (options) => {\n\tconst pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => {\n\t\tconst schema = plugin.schema;\n\t\tif (!schema) return acc;\n\t\tfor (const [key, value] of Object.entries(schema)) acc[key] = {\n\t\t\tfields: {\n\t\t\t\t...acc[key]?.fields,\n\t\t\t\t...value.fields\n\t\t\t},\n\t\t\tmodelName: value.modelName || key\n\t\t};\n\t\treturn acc;\n\t}, {});\n\tconst shouldAddRateLimitTable = options.rateLimit?.storage === \"database\";\n\tconst rateLimitTable = { rateLimit: {\n\t\tmodelName: options.rateLimit?.modelName || \"rateLimit\",\n\t\tfields: {\n\t\t\tkey: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tunique: true,\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.rateLimit?.fields?.key || \"key\"\n\t\t\t},\n\t\t\tcount: {\n\t\t\t\ttype: \"number\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.rateLimit?.fields?.count || \"count\"\n\t\t\t},\n\t\t\tlastRequest: {\n\t\t\t\ttype: \"number\",\n\t\t\t\tbigint: true,\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.rateLimit?.fields?.lastRequest || \"lastRequest\",\n\t\t\t\tdefaultValue: () => Date.now()\n\t\t\t}\n\t\t}\n\t} };\n\tconst { user, session, account, verification, ...pluginTables } = pluginSchema;\n\tconst verificationTable = { verification: {\n\t\tmodelName: options.verification?.modelName || \"verification\",\n\t\tfields: {\n\t\t\tidentifier: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.verification?.fields?.identifier || \"identifier\",\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tvalue: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.verification?.fields?.value || \"value\"\n\t\t\t},\n\t\t\texpiresAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.verification?.fields?.expiresAt || \"expiresAt\"\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\tfieldName: options.verification?.fields?.createdAt || \"createdAt\"\n\t\t\t},\n\t\t\tupdatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date(),\n\t\t\t\tfieldName: options.verification?.fields?.updatedAt || \"updatedAt\"\n\t\t\t},\n\t\t\t...verification?.fields,\n\t\t\t...options.verification?.additionalFields\n\t\t},\n\t\torder: 4\n\t} };\n\tconst sessionTable = { session: {\n\t\tmodelName: options.session?.modelName || \"session\",\n\t\tfields: {\n\t\t\texpiresAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.session?.fields?.expiresAt || \"expiresAt\"\n\t\t\t},\n\t\t\ttoken: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.session?.fields?.token || \"token\",\n\t\t\t\tunique: true\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.session?.fields?.createdAt || \"createdAt\",\n\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date()\n\t\t\t},\n\t\t\tupdatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: options.session?.fields?.updatedAt || \"updatedAt\",\n\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date()\n\t\t\t},\n\t\t\tipAddress: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\tfieldName: options.session?.fields?.ipAddress || \"ipAddress\"\n\t\t\t},\n\t\t\tuserAgent: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\tfieldName: options.session?.fields?.userAgent || \"userAgent\"\n\t\t\t},\n\t\t\tuserId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tfieldName: options.session?.fields?.userId || \"userId\",\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: options.user?.modelName || \"user\",\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tonDelete: \"cascade\"\n\t\t\t\t},\n\t\t\t\trequired: true,\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\t...session?.fields,\n\t\t\t...options.session?.additionalFields\n\t\t},\n\t\torder: 2\n\t} };\n\treturn {\n\t\tuser: {\n\t\t\tmodelName: options.user?.modelName || \"user\",\n\t\t\tfields: {\n\t\t\t\tname: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.name || \"name\",\n\t\t\t\t\tsortable: true\n\t\t\t\t},\n\t\t\t\temail: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tunique: true,\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.email || \"email\",\n\t\t\t\t\tsortable: true\n\t\t\t\t},\n\t\t\t\temailVerified: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdefaultValue: false,\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.emailVerified || \"emailVerified\",\n\t\t\t\t\tinput: false\n\t\t\t\t},\n\t\t\t\timage: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: options.user?.fields?.image || \"image\"\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.createdAt || \"createdAt\"\n\t\t\t\t},\n\t\t\t\tupdatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date(),\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.user?.fields?.updatedAt || \"updatedAt\"\n\t\t\t\t},\n\t\t\t\t...user?.fields,\n\t\t\t\t...options.user?.additionalFields\n\t\t\t},\n\t\t\torder: 1\n\t\t},\n\t\t...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {},\n\t\taccount: {\n\t\t\tmodelName: options.account?.modelName || \"account\",\n\t\t\tfields: {\n\t\t\t\taccountId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.accountId || \"accountId\"\n\t\t\t\t},\n\t\t\t\tproviderId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.providerId || \"providerId\"\n\t\t\t\t},\n\t\t\t\tuserId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: options.user?.modelName || \"user\",\n\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\tonDelete: \"cascade\"\n\t\t\t\t\t},\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.userId || \"userId\",\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\taccessToken: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.accessToken || \"accessToken\"\n\t\t\t\t},\n\t\t\t\trefreshToken: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.refreshToken || \"refreshToken\"\n\t\t\t\t},\n\t\t\t\tidToken: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.idToken || \"idToken\"\n\t\t\t\t},\n\t\t\t\taccessTokenExpiresAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.accessTokenExpiresAt || \"accessTokenExpiresAt\"\n\t\t\t\t},\n\t\t\t\trefreshTokenExpiresAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.refreshTokenExpiresAt || \"refreshTokenExpiresAt\"\n\t\t\t\t},\n\t\t\t\tscope: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: options.account?.fields?.scope || \"scope\"\n\t\t\t\t},\n\t\t\t\tpassword: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\treturned: false,\n\t\t\t\t\tfieldName: options.account?.fields?.password || \"password\"\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.createdAt || \"createdAt\",\n\t\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date()\n\t\t\t\t},\n\t\t\t\tupdatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: options.account?.fields?.updatedAt || \"updatedAt\",\n\t\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date()\n\t\t\t\t},\n\t\t\t\t...account?.fields,\n\t\t\t\t...options.account?.additionalFields\n\t\t\t},\n\t\t\torder: 3\n\t\t},\n\t\t...!options.secondaryStorage || options.verification?.storeInDatabase ? verificationTable : {},\n\t\t...pluginTables,\n\t\t...shouldAddRateLimitTable ? rateLimitTable : {}\n\t};\n};\n//#endregion\nexport { getAuthTables };\n", "import { logger } from \"../env/logger.mjs\";\n//#region src/utils/json.ts\nconst iso8601Regex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/;\nfunction reviveDate(value) {\n\tif (typeof value === \"string\" && iso8601Regex.test(value)) {\n\t\tconst date = new Date(value);\n\t\tif (!isNaN(date.getTime())) return date;\n\t}\n\treturn value;\n}\n/**\n* Recursively walk a pre-parsed object and convert ISO 8601 date strings\n* to Date instances. This handles the case where a Redis client (or similar)\n* returns already-parsed JSON objects whose date fields are still strings.\n*/\nfunction reviveDates(value) {\n\tif (value === null || value === void 0) return value;\n\tif (typeof value === \"string\") return reviveDate(value);\n\tif (value instanceof Date) return value;\n\tif (Array.isArray(value)) return value.map(reviveDates);\n\tif (typeof value === \"object\") {\n\t\tconst result = {};\n\t\tfor (const key of Object.keys(value)) result[key] = reviveDates(value[key]);\n\t\treturn result;\n\t}\n\treturn value;\n}\nfunction safeJSONParse(data) {\n\ttry {\n\t\tif (typeof data !== \"string\") {\n\t\t\tif (data === null || data === void 0) return null;\n\t\t\treturn reviveDates(data);\n\t\t}\n\t\treturn JSON.parse(data, (_, value) => reviveDate(value));\n\t} catch (e) {\n\t\tlogger.error(\"Error parsing JSON\", { error: e });\n\t\treturn null;\n\t}\n}\n//#endregion\nexport { safeJSONParse };\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createConstMap } from '../internal/utils';\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------\n// Constant values for SemanticAttributes\n//----------------------------------------------------------------------------------------------------------\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_AWS_LAMBDA_INVOKED_ARN = 'aws.lambda.invoked_arn';\nconst TMP_DB_SYSTEM = 'db.system';\nconst TMP_DB_CONNECTION_STRING = 'db.connection_string';\nconst TMP_DB_USER = 'db.user';\nconst TMP_DB_JDBC_DRIVER_CLASSNAME = 'db.jdbc.driver_classname';\nconst TMP_DB_NAME = 'db.name';\nconst TMP_DB_STATEMENT = 'db.statement';\nconst TMP_DB_OPERATION = 'db.operation';\nconst TMP_DB_MSSQL_INSTANCE_NAME = 'db.mssql.instance_name';\nconst TMP_DB_CASSANDRA_KEYSPACE = 'db.cassandra.keyspace';\nconst TMP_DB_CASSANDRA_PAGE_SIZE = 'db.cassandra.page_size';\nconst TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = 'db.cassandra.consistency_level';\nconst TMP_DB_CASSANDRA_TABLE = 'db.cassandra.table';\nconst TMP_DB_CASSANDRA_IDEMPOTENCE = 'db.cassandra.idempotence';\nconst TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT =\n 'db.cassandra.speculative_execution_count';\nconst TMP_DB_CASSANDRA_COORDINATOR_ID = 'db.cassandra.coordinator.id';\nconst TMP_DB_CASSANDRA_COORDINATOR_DC = 'db.cassandra.coordinator.dc';\nconst TMP_DB_HBASE_NAMESPACE = 'db.hbase.namespace';\nconst TMP_DB_REDIS_DATABASE_INDEX = 'db.redis.database_index';\nconst TMP_DB_MONGODB_COLLECTION = 'db.mongodb.collection';\nconst TMP_DB_SQL_TABLE = 'db.sql.table';\nconst TMP_EXCEPTION_TYPE = 'exception.type';\nconst TMP_EXCEPTION_MESSAGE = 'exception.message';\nconst TMP_EXCEPTION_STACKTRACE = 'exception.stacktrace';\nconst TMP_EXCEPTION_ESCAPED = 'exception.escaped';\nconst TMP_FAAS_TRIGGER = 'faas.trigger';\nconst TMP_FAAS_EXECUTION = 'faas.execution';\nconst TMP_FAAS_DOCUMENT_COLLECTION = 'faas.document.collection';\nconst TMP_FAAS_DOCUMENT_OPERATION = 'faas.document.operation';\nconst TMP_FAAS_DOCUMENT_TIME = 'faas.document.time';\nconst TMP_FAAS_DOCUMENT_NAME = 'faas.document.name';\nconst TMP_FAAS_TIME = 'faas.time';\nconst TMP_FAAS_CRON = 'faas.cron';\nconst TMP_FAAS_COLDSTART = 'faas.coldstart';\nconst TMP_FAAS_INVOKED_NAME = 'faas.invoked_name';\nconst TMP_FAAS_INVOKED_PROVIDER = 'faas.invoked_provider';\nconst TMP_FAAS_INVOKED_REGION = 'faas.invoked_region';\nconst TMP_NET_TRANSPORT = 'net.transport';\nconst TMP_NET_PEER_IP = 'net.peer.ip';\nconst TMP_NET_PEER_PORT = 'net.peer.port';\nconst TMP_NET_PEER_NAME = 'net.peer.name';\nconst TMP_NET_HOST_IP = 'net.host.ip';\nconst TMP_NET_HOST_PORT = 'net.host.port';\nconst TMP_NET_HOST_NAME = 'net.host.name';\nconst TMP_NET_HOST_CONNECTION_TYPE = 'net.host.connection.type';\nconst TMP_NET_HOST_CONNECTION_SUBTYPE = 'net.host.connection.subtype';\nconst TMP_NET_HOST_CARRIER_NAME = 'net.host.carrier.name';\nconst TMP_NET_HOST_CARRIER_MCC = 'net.host.carrier.mcc';\nconst TMP_NET_HOST_CARRIER_MNC = 'net.host.carrier.mnc';\nconst TMP_NET_HOST_CARRIER_ICC = 'net.host.carrier.icc';\nconst TMP_PEER_SERVICE = 'peer.service';\nconst TMP_ENDUSER_ID = 'enduser.id';\nconst TMP_ENDUSER_ROLE = 'enduser.role';\nconst TMP_ENDUSER_SCOPE = 'enduser.scope';\nconst TMP_THREAD_ID = 'thread.id';\nconst TMP_THREAD_NAME = 'thread.name';\nconst TMP_CODE_FUNCTION = 'code.function';\nconst TMP_CODE_NAMESPACE = 'code.namespace';\nconst TMP_CODE_FILEPATH = 'code.filepath';\nconst TMP_CODE_LINENO = 'code.lineno';\nconst TMP_HTTP_METHOD = 'http.method';\nconst TMP_HTTP_URL = 'http.url';\nconst TMP_HTTP_TARGET = 'http.target';\nconst TMP_HTTP_HOST = 'http.host';\nconst TMP_HTTP_SCHEME = 'http.scheme';\nconst TMP_HTTP_STATUS_CODE = 'http.status_code';\nconst TMP_HTTP_FLAVOR = 'http.flavor';\nconst TMP_HTTP_USER_AGENT = 'http.user_agent';\nconst TMP_HTTP_REQUEST_CONTENT_LENGTH = 'http.request_content_length';\nconst TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED =\n 'http.request_content_length_uncompressed';\nconst TMP_HTTP_RESPONSE_CONTENT_LENGTH = 'http.response_content_length';\nconst TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED =\n 'http.response_content_length_uncompressed';\nconst TMP_HTTP_SERVER_NAME = 'http.server_name';\nconst TMP_HTTP_ROUTE = 'http.route';\nconst TMP_HTTP_CLIENT_IP = 'http.client_ip';\nconst TMP_AWS_DYNAMODB_TABLE_NAMES = 'aws.dynamodb.table_names';\nconst TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = 'aws.dynamodb.consumed_capacity';\nconst TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS =\n 'aws.dynamodb.item_collection_metrics';\nconst TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY =\n 'aws.dynamodb.provisioned_read_capacity';\nconst TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY =\n 'aws.dynamodb.provisioned_write_capacity';\nconst TMP_AWS_DYNAMODB_CONSISTENT_READ = 'aws.dynamodb.consistent_read';\nconst TMP_AWS_DYNAMODB_PROJECTION = 'aws.dynamodb.projection';\nconst TMP_AWS_DYNAMODB_LIMIT = 'aws.dynamodb.limit';\nconst TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = 'aws.dynamodb.attributes_to_get';\nconst TMP_AWS_DYNAMODB_INDEX_NAME = 'aws.dynamodb.index_name';\nconst TMP_AWS_DYNAMODB_SELECT = 'aws.dynamodb.select';\nconst TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES =\n 'aws.dynamodb.global_secondary_indexes';\nconst TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES =\n 'aws.dynamodb.local_secondary_indexes';\nconst TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE =\n 'aws.dynamodb.exclusive_start_table';\nconst TMP_AWS_DYNAMODB_TABLE_COUNT = 'aws.dynamodb.table_count';\nconst TMP_AWS_DYNAMODB_SCAN_FORWARD = 'aws.dynamodb.scan_forward';\nconst TMP_AWS_DYNAMODB_SEGMENT = 'aws.dynamodb.segment';\nconst TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = 'aws.dynamodb.total_segments';\nconst TMP_AWS_DYNAMODB_COUNT = 'aws.dynamodb.count';\nconst TMP_AWS_DYNAMODB_SCANNED_COUNT = 'aws.dynamodb.scanned_count';\nconst TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS =\n 'aws.dynamodb.attribute_definitions';\nconst TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES =\n 'aws.dynamodb.global_secondary_index_updates';\nconst TMP_MESSAGING_SYSTEM = 'messaging.system';\nconst TMP_MESSAGING_DESTINATION = 'messaging.destination';\nconst TMP_MESSAGING_DESTINATION_KIND = 'messaging.destination_kind';\nconst TMP_MESSAGING_TEMP_DESTINATION = 'messaging.temp_destination';\nconst TMP_MESSAGING_PROTOCOL = 'messaging.protocol';\nconst TMP_MESSAGING_PROTOCOL_VERSION = 'messaging.protocol_version';\nconst TMP_MESSAGING_URL = 'messaging.url';\nconst TMP_MESSAGING_MESSAGE_ID = 'messaging.message_id';\nconst TMP_MESSAGING_CONVERSATION_ID = 'messaging.conversation_id';\nconst TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES =\n 'messaging.message_payload_size_bytes';\nconst TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES =\n 'messaging.message_payload_compressed_size_bytes';\nconst TMP_MESSAGING_OPERATION = 'messaging.operation';\nconst TMP_MESSAGING_CONSUMER_ID = 'messaging.consumer_id';\nconst TMP_MESSAGING_RABBITMQ_ROUTING_KEY = 'messaging.rabbitmq.routing_key';\nconst TMP_MESSAGING_KAFKA_MESSAGE_KEY = 'messaging.kafka.message_key';\nconst TMP_MESSAGING_KAFKA_CONSUMER_GROUP = 'messaging.kafka.consumer_group';\nconst TMP_MESSAGING_KAFKA_CLIENT_ID = 'messaging.kafka.client_id';\nconst TMP_MESSAGING_KAFKA_PARTITION = 'messaging.kafka.partition';\nconst TMP_MESSAGING_KAFKA_TOMBSTONE = 'messaging.kafka.tombstone';\nconst TMP_RPC_SYSTEM = 'rpc.system';\nconst TMP_RPC_SERVICE = 'rpc.service';\nconst TMP_RPC_METHOD = 'rpc.method';\nconst TMP_RPC_GRPC_STATUS_CODE = 'rpc.grpc.status_code';\nconst TMP_RPC_JSONRPC_VERSION = 'rpc.jsonrpc.version';\nconst TMP_RPC_JSONRPC_REQUEST_ID = 'rpc.jsonrpc.request_id';\nconst TMP_RPC_JSONRPC_ERROR_CODE = 'rpc.jsonrpc.error_code';\nconst TMP_RPC_JSONRPC_ERROR_MESSAGE = 'rpc.jsonrpc.error_message';\nconst TMP_MESSAGE_TYPE = 'message.type';\nconst TMP_MESSAGE_ID = 'message.id';\nconst TMP_MESSAGE_COMPRESSED_SIZE = 'message.compressed_size';\nconst TMP_MESSAGE_UNCOMPRESSED_SIZE = 'message.uncompressed_size';\n\n/**\n * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable).\n *\n * Note: This may be different from `faas.id` if an alias is involved.\n *\n * @deprecated Use ATTR_AWS_LAMBDA_INVOKED_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use ATTR_DB_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM;\n\n/**\n * The connection string used to connect to the database. It is recommended to remove embedded credentials.\n *\n * @deprecated Use ATTR_DB_CONNECTION_STRING in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING;\n\n/**\n * Username for accessing the database.\n *\n * @deprecated Use ATTR_DB_USER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_USER = TMP_DB_USER;\n\n/**\n * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect.\n *\n * @deprecated Use ATTR_DB_JDBC_DRIVER_CLASSNAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME;\n\n/**\n * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails).\n *\n * Note: In some SQL databases, the database name to be used is called "schema name".\n *\n * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_NAME = TMP_DB_NAME;\n\n/**\n * The database statement being executed.\n *\n * Note: The value may be sanitized to exclude sensitive information.\n *\n * @deprecated Use ATTR_DB_STATEMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT;\n\n/**\n * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword.\n *\n * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted.\n *\n * @deprecated Use ATTR_DB_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_OPERATION = TMP_DB_OPERATION;\n\n/**\n * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance.\n *\n * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard).\n *\n * @deprecated Use ATTR_DB_MSSQL_INSTANCE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME;\n\n/**\n * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute.\n *\n * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE;\n\n/**\n * The fetch size used for paging, i.e. how many rows will be returned at once.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_PAGE_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL =\n TMP_DB_CASSANDRA_CONSISTENCY_LEVEL;\n\n/**\n * The name of the primary table that the operation is acting upon, including the schema name (if applicable).\n *\n * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE;\n\n/**\n * Whether or not the query is idempotent.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_IDEMPOTENCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE;\n\n/**\n * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT =\n TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT;\n\n/**\n * The ID of the coordinating node for a query.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_COORDINATOR_ID =\n TMP_DB_CASSANDRA_COORDINATOR_ID;\n\n/**\n * The data center of the coordinating node for a query.\n *\n * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_DC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_CASSANDRA_COORDINATOR_DC =\n TMP_DB_CASSANDRA_COORDINATOR_DC;\n\n/**\n * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute.\n *\n * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE;\n\n/**\n * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute.\n *\n * @deprecated Use ATTR_DB_REDIS_DATABASE_INDEX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX;\n\n/**\n * The collection being accessed within the database stated in `db.name`.\n *\n * @deprecated Use ATTR_DB_MONGODB_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION;\n\n/**\n * The name of the primary table that the operation is acting upon, including the schema name (if applicable).\n *\n * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set.\n *\n * @deprecated Use ATTR_DB_SQL_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @deprecated Use ATTR_EXCEPTION_TYPE.\n */\nexport const SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE;\n\n/**\n * The exception message.\n *\n * @deprecated Use ATTR_EXCEPTION_MESSAGE.\n */\nexport const SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @deprecated Use ATTR_EXCEPTION_STACKTRACE.\n */\nexport const SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE;\n\n/**\n* SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span.\n*\n* Note: An exception is considered to have escaped (or left) the scope of a span,\nif that span is ended while the exception is still logically "in flight".\nThis may be actually "in flight" in some languages (e.g. if the exception\nis passed to a Context manager's `__exit__` method in Python) but will\nusually be caught at the point of recording the exception in most languages.\n\nIt is usually not possible to determine at the point where an exception is thrown\nwhether it will escape the scope of a span.\nHowever, it is trivial to know that an exception\nwill escape, if one checks for an active exception just before ending the span,\nas done in the [example above](#exception-end-example).\n\nIt follows that an exception may still escape the scope of the span\neven if the `exception.escaped` attribute was not set or set to false,\nsince the event might have been recorded at a time where it was not\nclear whether the exception will escape.\n*\n* @deprecated Use ATTR_EXCEPTION_ESCAPED.\n*/\nexport const SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use ATTR_FAAS_TRIGGER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER;\n\n/**\n * The execution ID of the current function execution.\n *\n * @deprecated Use ATTR_FAAS_INVOCATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION;\n\n/**\n * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name.\n *\n * @deprecated Use ATTR_FAAS_DOCUMENT_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION;\n\n/**\n * Describes the type of the operation that was performed on the data.\n *\n * @deprecated Use ATTR_FAAS_DOCUMENT_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION;\n\n/**\n * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime).\n *\n * @deprecated Use ATTR_FAAS_DOCUMENT_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME;\n\n/**\n * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name.\n *\n * @deprecated Use ATTR_FAAS_DOCUMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME;\n\n/**\n * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime).\n *\n * @deprecated Use ATTR_FAAS_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_TIME = TMP_FAAS_TIME;\n\n/**\n * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm).\n *\n * @deprecated Use ATTR_FAAS_CRON in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_CRON = TMP_FAAS_CRON;\n\n/**\n * A boolean that is true if the serverless function is executed for the first time (aka cold-start).\n *\n * @deprecated Use ATTR_FAAS_COLDSTART in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART;\n\n/**\n * The name of the invoked function.\n *\n * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function.\n *\n * @deprecated Use ATTR_FAAS_INVOKED_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME;\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use ATTR_FAAS_INVOKED_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER;\n\n/**\n * The cloud region of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function.\n *\n * @deprecated Use ATTR_FAAS_INVOKED_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use ATTR_NET_TRANSPORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT;\n\n/**\n * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6).\n *\n * @deprecated Use ATTR_NET_PEER_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP;\n\n/**\n * Remote port number.\n *\n * @deprecated Use ATTR_NET_PEER_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT;\n\n/**\n * Remote hostname or similar, see note below.\n *\n * @deprecated Use ATTR_NET_PEER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME;\n\n/**\n * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host.\n *\n * @deprecated Use ATTR_NET_HOST_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP;\n\n/**\n * Like `net.peer.port` but for the host port.\n *\n * @deprecated Use ATTR_NET_HOST_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT;\n\n/**\n * Local hostname or similar, see note below.\n *\n * @deprecated Use ATTR_NET_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use ATTR_NETWORK_CONNECTION_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use ATTR_NETWORK_CONNECTION_SUBTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CONNECTION_SUBTYPE =\n TMP_NET_HOST_CONNECTION_SUBTYPE;\n\n/**\n * The name of the mobile carrier.\n *\n * @deprecated Use ATTR_NETWORK_CARRIER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME;\n\n/**\n * The mobile carrier country code.\n *\n * @deprecated Use ATTR_NETWORK_CARRIER_MCC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC;\n\n/**\n * The mobile carrier network code.\n *\n * @deprecated Use ATTR_NETWORK_CARRIER_MNC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC;\n\n/**\n * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network.\n *\n * @deprecated Use ATTR_NETWORK_CARRIER_ICC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC;\n\n/**\n * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any.\n *\n * @deprecated Use ATTR_PEER_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE;\n\n/**\n * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system.\n *\n * @deprecated Use ATTR_ENDUSER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID;\n\n/**\n * Actual/assumed role the client is making the request under extracted from token or application security context.\n *\n * @deprecated Use ATTR_ENDUSER_ROLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE;\n\n/**\n * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html).\n *\n * @deprecated Use ATTR_ENDUSER_SCOPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE;\n\n/**\n * Current "managed" thread ID (as opposed to OS thread ID).\n *\n * @deprecated Use ATTR_THREAD_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_THREAD_ID = TMP_THREAD_ID;\n\n/**\n * Current thread name.\n *\n * @deprecated Use ATTR_THREAD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_THREAD_NAME = TMP_THREAD_NAME;\n\n/**\n * The method or function name, or equivalent (usually rightmost part of the code unit's name).\n *\n * @deprecated Use ATTR_CODE_FUNCTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION;\n\n/**\n * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit.\n *\n * @deprecated Use ATTR_CODE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path).\n *\n * @deprecated Use ATTR_CODE_FILEPATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH;\n\n/**\n * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`.\n *\n * @deprecated Use ATTR_CODE_LINENO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_CODE_LINENO = TMP_CODE_LINENO;\n\n/**\n * HTTP request method.\n *\n * @deprecated Use ATTR_HTTP_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD;\n\n/**\n * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless.\n *\n * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`.\n *\n * @deprecated Use ATTR_HTTP_URL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_URL = TMP_HTTP_URL;\n\n/**\n * The full request target as passed in a HTTP request line or equivalent.\n *\n * @deprecated Use ATTR_HTTP_TARGET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET;\n\n/**\n * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note.\n *\n * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set.\n *\n * @deprecated Use ATTR_HTTP_HOST in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_HOST = TMP_HTTP_HOST;\n\n/**\n * The URI scheme identifying the used protocol.\n *\n * @deprecated Use ATTR_HTTP_SCHEME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @deprecated Use ATTR_HTTP_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use ATTR_HTTP_FLAVOR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR;\n\n/**\n * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client.\n *\n * @deprecated Use ATTR_HTTP_USER_AGENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT;\n\n/**\n * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size.\n *\n * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH =\n TMP_HTTP_REQUEST_CONTENT_LENGTH;\n\n/**\n * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used.\n *\n * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED =\n TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED;\n\n/**\n * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size.\n *\n * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH =\n TMP_HTTP_RESPONSE_CONTENT_LENGTH;\n\n/**\n * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used.\n *\n * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED =\n TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED;\n\n/**\n * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead).\n *\n * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available.\n *\n * @deprecated Use ATTR_HTTP_SERVER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME;\n\n/**\n * The matched route (path template).\n *\n * @deprecated Use ATTR_HTTP_ROUTE.\n */\nexport const SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE;\n\n/**\n* The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)).\n*\n* Note: This is not necessarily the same as `net.peer.ip`, which would\nidentify the network-level peer, which may be a proxy.\n\nThis attribute should be set when a source of information different\nfrom the one used for `net.peer.ip`, is available even if that other\nsource just confirms the same value as `net.peer.ip`.\nRationale: For `net.peer.ip`, one typically does not know if it\ncomes from a proxy, reverse proxy, or the actual client. Setting\n`http.client_ip` when it's the same as `net.peer.ip` means that\none is at least somewhat confident that the address is not that of\nthe closest proxy.\n*\n* @deprecated Use ATTR_HTTP_CLIENT_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n*/\nexport const SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP;\n\n/**\n * The keys in the `RequestItems` object field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES;\n\n/**\n * The JSON-serialized value of each item in the `ConsumedCapacity` response field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY =\n TMP_AWS_DYNAMODB_CONSUMED_CAPACITY;\n\n/**\n * The JSON-serialized value of the `ItemCollectionMetrics` response field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS =\n TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS;\n\n/**\n * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY =\n TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY;\n\n/**\n * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY =\n TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY;\n\n/**\n * The value of the `ConsistentRead` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_CONSISTENT_READ in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ =\n TMP_AWS_DYNAMODB_CONSISTENT_READ;\n\n/**\n * The value of the `ProjectionExpression` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_PROJECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION;\n\n/**\n * The value of the `Limit` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_LIMIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT;\n\n/**\n * The value of the `AttributesToGet` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTES_TO_GET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET =\n TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET;\n\n/**\n * The value of the `IndexName` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_INDEX_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME;\n\n/**\n * The value of the `Select` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_SELECT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT;\n\n/**\n * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES =\n TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES;\n\n/**\n * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES =\n TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES;\n\n/**\n * The value of the `ExclusiveStartTableName` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE =\n TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE;\n\n/**\n * The the number of items in the `TableNames` response parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT;\n\n/**\n * The value of the `ScanIndexForward` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_SCAN_FORWARD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD;\n\n/**\n * The value of the `Segment` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_SEGMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT;\n\n/**\n * The value of the `TotalSegments` request parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS =\n TMP_AWS_DYNAMODB_TOTAL_SEGMENTS;\n\n/**\n * The value of the `Count` response parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT;\n\n/**\n * The value of the `ScannedCount` response parameter.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_SCANNED_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT =\n TMP_AWS_DYNAMODB_SCANNED_COUNT;\n\n/**\n * The JSON-serialized value of each item in the `AttributeDefinitions` request field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS =\n TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS;\n\n/**\n * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field.\n *\n * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES =\n TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES;\n\n/**\n * A string identifying the messaging system.\n *\n * @deprecated Use ATTR_MESSAGING_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM;\n\n/**\n * The message destination name. This might be equal to the span name but is required nevertheless.\n *\n * @deprecated Use ATTR_MESSAGING_DESTINATION_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION;\n\n/**\n * The kind of message destination.\n *\n * @deprecated Removed in semconv v1.20.0.\n */\nexport const SEMATTRS_MESSAGING_DESTINATION_KIND =\n TMP_MESSAGING_DESTINATION_KIND;\n\n/**\n * A boolean that is true if the message destination is temporary.\n *\n * @deprecated Use ATTR_MESSAGING_DESTINATION_TEMPORARY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_TEMP_DESTINATION =\n TMP_MESSAGING_TEMP_DESTINATION;\n\n/**\n * The name of the transport protocol.\n *\n * @deprecated Use ATTR_NETWORK_PROTOCOL_NAME.\n */\nexport const SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL;\n\n/**\n * The version of the transport protocol.\n *\n * @deprecated Use ATTR_NETWORK_PROTOCOL_VERSION.\n */\nexport const SEMATTRS_MESSAGING_PROTOCOL_VERSION =\n TMP_MESSAGING_PROTOCOL_VERSION;\n\n/**\n * Connection string.\n *\n * @deprecated Removed in semconv v1.17.0.\n */\nexport const SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL;\n\n/**\n * A value used by the messaging system as an identifier for the message, represented as a string.\n *\n * @deprecated Use ATTR_MESSAGING_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID;\n\n/**\n * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID".\n *\n * @deprecated Use ATTR_MESSAGING_MESSAGE_CONVERSATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID;\n\n/**\n * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported.\n *\n * @deprecated Use ATTR_MESSAGING_MESSAGE_BODY_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES =\n TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES;\n\n/**\n * The compressed size of the message payload in bytes.\n *\n * @deprecated Removed in semconv v1.22.0.\n */\nexport const SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES =\n TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES;\n\n/**\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n *\n * @deprecated Use ATTR_MESSAGING_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION;\n\n/**\n * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message.\n *\n * @deprecated Removed in semconv v1.21.0.\n */\nexport const SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID;\n\n/**\n * RabbitMQ message routing key.\n *\n * @deprecated Use ATTR_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY =\n TMP_MESSAGING_RABBITMQ_ROUTING_KEY;\n\n/**\n * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set.\n *\n * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value.\n *\n * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY =\n TMP_MESSAGING_KAFKA_MESSAGE_KEY;\n\n/**\n * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers.\n *\n * @deprecated Use ATTR_MESSAGING_KAFKA_CONSUMER_GROUP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP =\n TMP_MESSAGING_KAFKA_CONSUMER_GROUP;\n\n/**\n * Client Id for the Consumer or Producer that is handling the message.\n *\n * @deprecated Use ATTR_MESSAGING_CLIENT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID;\n\n/**\n * Partition the message is sent to.\n *\n * @deprecated Use ATTR_MESSAGING_KAFKA_DESTINATION_PARTITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION;\n\n/**\n * A boolean that is true if the message is a tombstone.\n *\n * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE;\n\n/**\n * A string identifying the remoting system.\n *\n * @deprecated Use ATTR_RPC_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM;\n\n/**\n * The full (logical) name of the service being called, including its package name, if applicable.\n *\n * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side).\n *\n * @deprecated Use ATTR_RPC_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE;\n\n/**\n * The name of the (logical) method being called, must be equal to the $method part in the span name.\n *\n * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side).\n *\n * @deprecated Use ATTR_RPC_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_METHOD = TMP_RPC_METHOD;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use ATTR_RPC_GRPC_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE;\n\n/**\n * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted.\n *\n * @deprecated Use ATTR_RPC_JSONRPC_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION;\n\n/**\n * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification.\n *\n * @deprecated Use ATTR_RPC_JSONRPC_REQUEST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID;\n\n/**\n * `error.code` property of response if it is an error response.\n *\n * @deprecated Use ATTR_RPC_JSONRPC_ERROR_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE;\n\n/**\n * `error.message` property of response if it is an error response.\n *\n * @deprecated Use ATTR_RPC_JSONRPC_ERROR_MESSAGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE;\n\n/**\n * Whether this is a received or sent message.\n *\n * @deprecated Use ATTR_MESSAGE_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE;\n\n/**\n * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message.\n *\n * Note: This way we guarantee that the values will be consistent between different implementations.\n *\n * @deprecated Use ATTR_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID;\n\n/**\n * Compressed size of the message in bytes.\n *\n * @deprecated Use ATTR_MESSAGE_COMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE;\n\n/**\n * Uncompressed size of the message in bytes.\n *\n * @deprecated Use ATTR_MESSAGE_UNCOMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE;\n\n/**\n * Definition of available values for SemanticAttributes\n * This type is used for backward compatibility, you should use the individual exported\n * constants SemanticAttributes_XXXXX rather than the exported constant map. As any single reference\n * to a constant map value will result in all strings being included into your bundle.\n * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification.\n */\nexport type SemanticAttributes = {\n /**\n * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable).\n *\n * Note: This may be different from `faas.id` if an alias is involved.\n */\n AWS_LAMBDA_INVOKED_ARN: 'aws.lambda.invoked_arn';\n\n /**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n */\n DB_SYSTEM: 'db.system';\n\n /**\n * The connection string used to connect to the database. It is recommended to remove embedded credentials.\n */\n DB_CONNECTION_STRING: 'db.connection_string';\n\n /**\n * Username for accessing the database.\n */\n DB_USER: 'db.user';\n\n /**\n * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect.\n */\n DB_JDBC_DRIVER_CLASSNAME: 'db.jdbc.driver_classname';\n\n /**\n * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails).\n *\n * Note: In some SQL databases, the database name to be used is called "schema name".\n */\n DB_NAME: 'db.name';\n\n /**\n * The database statement being executed.\n *\n * Note: The value may be sanitized to exclude sensitive information.\n */\n DB_STATEMENT: 'db.statement';\n\n /**\n * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword.\n *\n * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted.\n */\n DB_OPERATION: 'db.operation';\n\n /**\n * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance.\n *\n * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard).\n */\n DB_MSSQL_INSTANCE_NAME: 'db.mssql.instance_name';\n\n /**\n * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute.\n */\n DB_CASSANDRA_KEYSPACE: 'db.cassandra.keyspace';\n\n /**\n * The fetch size used for paging, i.e. how many rows will be returned at once.\n */\n DB_CASSANDRA_PAGE_SIZE: 'db.cassandra.page_size';\n\n /**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n */\n DB_CASSANDRA_CONSISTENCY_LEVEL: 'db.cassandra.consistency_level';\n\n /**\n * The name of the primary table that the operation is acting upon, including the schema name (if applicable).\n *\n * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set.\n */\n DB_CASSANDRA_TABLE: 'db.cassandra.table';\n\n /**\n * Whether or not the query is idempotent.\n */\n DB_CASSANDRA_IDEMPOTENCE: 'db.cassandra.idempotence';\n\n /**\n * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively.\n */\n DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT: 'db.cassandra.speculative_execution_count';\n\n /**\n * The ID of the coordinating node for a query.\n */\n DB_CASSANDRA_COORDINATOR_ID: 'db.cassandra.coordinator.id';\n\n /**\n * The data center of the coordinating node for a query.\n */\n DB_CASSANDRA_COORDINATOR_DC: 'db.cassandra.coordinator.dc';\n\n /**\n * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute.\n */\n DB_HBASE_NAMESPACE: 'db.hbase.namespace';\n\n /**\n * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute.\n */\n DB_REDIS_DATABASE_INDEX: 'db.redis.database_index';\n\n /**\n * The collection being accessed within the database stated in `db.name`.\n */\n DB_MONGODB_COLLECTION: 'db.mongodb.collection';\n\n /**\n * The name of the primary table that the operation is acting upon, including the schema name (if applicable).\n *\n * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set.\n */\n DB_SQL_TABLE: 'db.sql.table';\n\n /**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n */\n EXCEPTION_TYPE: 'exception.type';\n\n /**\n * The exception message.\n */\n EXCEPTION_MESSAGE: 'exception.message';\n\n /**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n */\n EXCEPTION_STACKTRACE: 'exception.stacktrace';\n\n /**\n * SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span.\n *\n * Note: An exception is considered to have escaped (or left) the scope of a span,\nif that span is ended while the exception is still logically "in flight".\nThis may be actually "in flight" in some languages (e.g. if the exception\nis passed to a Context manager's `__exit__` method in Python) but will\nusually be caught at the point of recording the exception in most languages.\n\nIt is usually not possible to determine at the point where an exception is thrown\nwhether it will escape the scope of a span.\nHowever, it is trivial to know that an exception\nwill escape, if one checks for an active exception just before ending the span,\nas done in the [example above](#exception-end-example).\n\nIt follows that an exception may still escape the scope of the span\neven if the `exception.escaped` attribute was not set or set to false,\nsince the event might have been recorded at a time where it was not\nclear whether the exception will escape.\n */\n EXCEPTION_ESCAPED: 'exception.escaped';\n\n /**\n * Type of the trigger on which the function is executed.\n */\n FAAS_TRIGGER: 'faas.trigger';\n\n /**\n * The execution ID of the current function execution.\n */\n FAAS_EXECUTION: 'faas.execution';\n\n /**\n * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name.\n */\n FAAS_DOCUMENT_COLLECTION: 'faas.document.collection';\n\n /**\n * Describes the type of the operation that was performed on the data.\n */\n FAAS_DOCUMENT_OPERATION: 'faas.document.operation';\n\n /**\n * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime).\n */\n FAAS_DOCUMENT_TIME: 'faas.document.time';\n\n /**\n * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name.\n */\n FAAS_DOCUMENT_NAME: 'faas.document.name';\n\n /**\n * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime).\n */\n FAAS_TIME: 'faas.time';\n\n /**\n * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm).\n */\n FAAS_CRON: 'faas.cron';\n\n /**\n * A boolean that is true if the serverless function is executed for the first time (aka cold-start).\n */\n FAAS_COLDSTART: 'faas.coldstart';\n\n /**\n * The name of the invoked function.\n *\n * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function.\n */\n FAAS_INVOKED_NAME: 'faas.invoked_name';\n\n /**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n */\n FAAS_INVOKED_PROVIDER: 'faas.invoked_provider';\n\n /**\n * The cloud region of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function.\n */\n FAAS_INVOKED_REGION: 'faas.invoked_region';\n\n /**\n * Transport protocol used. See note below.\n */\n NET_TRANSPORT: 'net.transport';\n\n /**\n * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6).\n */\n NET_PEER_IP: 'net.peer.ip';\n\n /**\n * Remote port number.\n */\n NET_PEER_PORT: 'net.peer.port';\n\n /**\n * Remote hostname or similar, see note below.\n */\n NET_PEER_NAME: 'net.peer.name';\n\n /**\n * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host.\n */\n NET_HOST_IP: 'net.host.ip';\n\n /**\n * Like `net.peer.port` but for the host port.\n */\n NET_HOST_PORT: 'net.host.port';\n\n /**\n * Local hostname or similar, see note below.\n */\n NET_HOST_NAME: 'net.host.name';\n\n /**\n * The internet connection type currently being used by the host.\n */\n NET_HOST_CONNECTION_TYPE: 'net.host.connection.type';\n\n /**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n */\n NET_HOST_CONNECTION_SUBTYPE: 'net.host.connection.subtype';\n\n /**\n * The name of the mobile carrier.\n */\n NET_HOST_CARRIER_NAME: 'net.host.carrier.name';\n\n /**\n * The mobile carrier country code.\n */\n NET_HOST_CARRIER_MCC: 'net.host.carrier.mcc';\n\n /**\n * The mobile carrier network code.\n */\n NET_HOST_CARRIER_MNC: 'net.host.carrier.mnc';\n\n /**\n * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network.\n */\n NET_HOST_CARRIER_ICC: 'net.host.carrier.icc';\n\n /**\n * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any.\n */\n PEER_SERVICE: 'peer.service';\n\n /**\n * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system.\n */\n ENDUSER_ID: 'enduser.id';\n\n /**\n * Actual/assumed role the client is making the request under extracted from token or application security context.\n */\n ENDUSER_ROLE: 'enduser.role';\n\n /**\n * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html).\n */\n ENDUSER_SCOPE: 'enduser.scope';\n\n /**\n * Current "managed" thread ID (as opposed to OS thread ID).\n */\n THREAD_ID: 'thread.id';\n\n /**\n * Current thread name.\n */\n THREAD_NAME: 'thread.name';\n\n /**\n * The method or function name, or equivalent (usually rightmost part of the code unit's name).\n */\n CODE_FUNCTION: 'code.function';\n\n /**\n * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit.\n */\n CODE_NAMESPACE: 'code.namespace';\n\n /**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path).\n */\n CODE_FILEPATH: 'code.filepath';\n\n /**\n * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`.\n */\n CODE_LINENO: 'code.lineno';\n\n /**\n * HTTP request method.\n */\n HTTP_METHOD: 'http.method';\n\n /**\n * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless.\n *\n * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`.\n */\n HTTP_URL: 'http.url';\n\n /**\n * The full request target as passed in a HTTP request line or equivalent.\n */\n HTTP_TARGET: 'http.target';\n\n /**\n * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note.\n *\n * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set.\n */\n HTTP_HOST: 'http.host';\n\n /**\n * The URI scheme identifying the used protocol.\n */\n HTTP_SCHEME: 'http.scheme';\n\n /**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n */\n HTTP_STATUS_CODE: 'http.status_code';\n\n /**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n */\n HTTP_FLAVOR: 'http.flavor';\n\n /**\n * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client.\n */\n HTTP_USER_AGENT: 'http.user_agent';\n\n /**\n * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size.\n */\n HTTP_REQUEST_CONTENT_LENGTH: 'http.request_content_length';\n\n /**\n * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used.\n */\n HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED: 'http.request_content_length_uncompressed';\n\n /**\n * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size.\n */\n HTTP_RESPONSE_CONTENT_LENGTH: 'http.response_content_length';\n\n /**\n * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used.\n */\n HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED: 'http.response_content_length_uncompressed';\n\n /**\n * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead).\n *\n * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available.\n */\n HTTP_SERVER_NAME: 'http.server_name';\n\n /**\n * The matched route (path template).\n */\n HTTP_ROUTE: 'http.route';\n\n /**\n * The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)).\n *\n * Note: This is not necessarily the same as `net.peer.ip`, which would\nidentify the network-level peer, which may be a proxy.\n\nThis attribute should be set when a source of information different\nfrom the one used for `net.peer.ip`, is available even if that other\nsource just confirms the same value as `net.peer.ip`.\nRationale: For `net.peer.ip`, one typically does not know if it\ncomes from a proxy, reverse proxy, or the actual client. Setting\n`http.client_ip` when it's the same as `net.peer.ip` means that\none is at least somewhat confident that the address is not that of\nthe closest proxy.\n */\n HTTP_CLIENT_IP: 'http.client_ip';\n\n /**\n * The keys in the `RequestItems` object field.\n */\n AWS_DYNAMODB_TABLE_NAMES: 'aws.dynamodb.table_names';\n\n /**\n * The JSON-serialized value of each item in the `ConsumedCapacity` response field.\n */\n AWS_DYNAMODB_CONSUMED_CAPACITY: 'aws.dynamodb.consumed_capacity';\n\n /**\n * The JSON-serialized value of the `ItemCollectionMetrics` response field.\n */\n AWS_DYNAMODB_ITEM_COLLECTION_METRICS: 'aws.dynamodb.item_collection_metrics';\n\n /**\n * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter.\n */\n AWS_DYNAMODB_PROVISIONED_READ_CAPACITY: 'aws.dynamodb.provisioned_read_capacity';\n\n /**\n * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter.\n */\n AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY: 'aws.dynamodb.provisioned_write_capacity';\n\n /**\n * The value of the `ConsistentRead` request parameter.\n */\n AWS_DYNAMODB_CONSISTENT_READ: 'aws.dynamodb.consistent_read';\n\n /**\n * The value of the `ProjectionExpression` request parameter.\n */\n AWS_DYNAMODB_PROJECTION: 'aws.dynamodb.projection';\n\n /**\n * The value of the `Limit` request parameter.\n */\n AWS_DYNAMODB_LIMIT: 'aws.dynamodb.limit';\n\n /**\n * The value of the `AttributesToGet` request parameter.\n */\n AWS_DYNAMODB_ATTRIBUTES_TO_GET: 'aws.dynamodb.attributes_to_get';\n\n /**\n * The value of the `IndexName` request parameter.\n */\n AWS_DYNAMODB_INDEX_NAME: 'aws.dynamodb.index_name';\n\n /**\n * The value of the `Select` request parameter.\n */\n AWS_DYNAMODB_SELECT: 'aws.dynamodb.select';\n\n /**\n * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field.\n */\n AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES: 'aws.dynamodb.global_secondary_indexes';\n\n /**\n * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field.\n */\n AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES: 'aws.dynamodb.local_secondary_indexes';\n\n /**\n * The value of the `ExclusiveStartTableName` request parameter.\n */\n AWS_DYNAMODB_EXCLUSIVE_START_TABLE: 'aws.dynamodb.exclusive_start_table';\n\n /**\n * The the number of items in the `TableNames` response parameter.\n */\n AWS_DYNAMODB_TABLE_COUNT: 'aws.dynamodb.table_count';\n\n /**\n * The value of the `ScanIndexForward` request parameter.\n */\n AWS_DYNAMODB_SCAN_FORWARD: 'aws.dynamodb.scan_forward';\n\n /**\n * The value of the `Segment` request parameter.\n */\n AWS_DYNAMODB_SEGMENT: 'aws.dynamodb.segment';\n\n /**\n * The value of the `TotalSegments` request parameter.\n */\n AWS_DYNAMODB_TOTAL_SEGMENTS: 'aws.dynamodb.total_segments';\n\n /**\n * The value of the `Count` response parameter.\n */\n AWS_DYNAMODB_COUNT: 'aws.dynamodb.count';\n\n /**\n * The value of the `ScannedCount` response parameter.\n */\n AWS_DYNAMODB_SCANNED_COUNT: 'aws.dynamodb.scanned_count';\n\n /**\n * The JSON-serialized value of each item in the `AttributeDefinitions` request field.\n */\n AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS: 'aws.dynamodb.attribute_definitions';\n\n /**\n * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field.\n */\n AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES: 'aws.dynamodb.global_secondary_index_updates';\n\n /**\n * A string identifying the messaging system.\n */\n MESSAGING_SYSTEM: 'messaging.system';\n\n /**\n * The message destination name. This might be equal to the span name but is required nevertheless.\n */\n MESSAGING_DESTINATION: 'messaging.destination';\n\n /**\n * The kind of message destination.\n */\n MESSAGING_DESTINATION_KIND: 'messaging.destination_kind';\n\n /**\n * A boolean that is true if the message destination is temporary.\n */\n MESSAGING_TEMP_DESTINATION: 'messaging.temp_destination';\n\n /**\n * The name of the transport protocol.\n */\n MESSAGING_PROTOCOL: 'messaging.protocol';\n\n /**\n * The version of the transport protocol.\n */\n MESSAGING_PROTOCOL_VERSION: 'messaging.protocol_version';\n\n /**\n * Connection string.\n */\n MESSAGING_URL: 'messaging.url';\n\n /**\n * A value used by the messaging system as an identifier for the message, represented as a string.\n */\n MESSAGING_MESSAGE_ID: 'messaging.message_id';\n\n /**\n * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID".\n */\n MESSAGING_CONVERSATION_ID: 'messaging.conversation_id';\n\n /**\n * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported.\n */\n MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES: 'messaging.message_payload_size_bytes';\n\n /**\n * The compressed size of the message payload in bytes.\n */\n MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES: 'messaging.message_payload_compressed_size_bytes';\n\n /**\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n */\n MESSAGING_OPERATION: 'messaging.operation';\n\n /**\n * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message.\n */\n MESSAGING_CONSUMER_ID: 'messaging.consumer_id';\n\n /**\n * RabbitMQ message routing key.\n */\n MESSAGING_RABBITMQ_ROUTING_KEY: 'messaging.rabbitmq.routing_key';\n\n /**\n * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set.\n *\n * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value.\n */\n MESSAGING_KAFKA_MESSAGE_KEY: 'messaging.kafka.message_key';\n\n /**\n * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers.\n */\n MESSAGING_KAFKA_CONSUMER_GROUP: 'messaging.kafka.consumer_group';\n\n /**\n * Client Id for the Consumer or Producer that is handling the message.\n */\n MESSAGING_KAFKA_CLIENT_ID: 'messaging.kafka.client_id';\n\n /**\n * Partition the message is sent to.\n */\n MESSAGING_KAFKA_PARTITION: 'messaging.kafka.partition';\n\n /**\n * A boolean that is true if the message is a tombstone.\n */\n MESSAGING_KAFKA_TOMBSTONE: 'messaging.kafka.tombstone';\n\n /**\n * A string identifying the remoting system.\n */\n RPC_SYSTEM: 'rpc.system';\n\n /**\n * The full (logical) name of the service being called, including its package name, if applicable.\n *\n * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side).\n */\n RPC_SERVICE: 'rpc.service';\n\n /**\n * The name of the (logical) method being called, must be equal to the $method part in the span name.\n *\n * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side).\n */\n RPC_METHOD: 'rpc.method';\n\n /**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n */\n RPC_GRPC_STATUS_CODE: 'rpc.grpc.status_code';\n\n /**\n * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted.\n */\n RPC_JSONRPC_VERSION: 'rpc.jsonrpc.version';\n\n /**\n * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification.\n */\n RPC_JSONRPC_REQUEST_ID: 'rpc.jsonrpc.request_id';\n\n /**\n * `error.code` property of response if it is an error response.\n */\n RPC_JSONRPC_ERROR_CODE: 'rpc.jsonrpc.error_code';\n\n /**\n * `error.message` property of response if it is an error response.\n */\n RPC_JSONRPC_ERROR_MESSAGE: 'rpc.jsonrpc.error_message';\n\n /**\n * Whether this is a received or sent message.\n */\n MESSAGE_TYPE: 'message.type';\n\n /**\n * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message.\n *\n * Note: This way we guarantee that the values will be consistent between different implementations.\n */\n MESSAGE_ID: 'message.id';\n\n /**\n * Compressed size of the message in bytes.\n */\n MESSAGE_COMPRESSED_SIZE: 'message.compressed_size';\n\n /**\n * Uncompressed size of the message in bytes.\n */\n MESSAGE_UNCOMPRESSED_SIZE: 'message.uncompressed_size';\n};\n\n/**\n * Create exported Value Map for SemanticAttributes values\n * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification\n */\nexport const SemanticAttributes: SemanticAttributes =\n /*#__PURE__*/ createConstMap([\n TMP_AWS_LAMBDA_INVOKED_ARN,\n TMP_DB_SYSTEM,\n TMP_DB_CONNECTION_STRING,\n TMP_DB_USER,\n TMP_DB_JDBC_DRIVER_CLASSNAME,\n TMP_DB_NAME,\n TMP_DB_STATEMENT,\n TMP_DB_OPERATION,\n TMP_DB_MSSQL_INSTANCE_NAME,\n TMP_DB_CASSANDRA_KEYSPACE,\n TMP_DB_CASSANDRA_PAGE_SIZE,\n TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,\n TMP_DB_CASSANDRA_TABLE,\n TMP_DB_CASSANDRA_IDEMPOTENCE,\n TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,\n TMP_DB_CASSANDRA_COORDINATOR_ID,\n TMP_DB_CASSANDRA_COORDINATOR_DC,\n TMP_DB_HBASE_NAMESPACE,\n TMP_DB_REDIS_DATABASE_INDEX,\n TMP_DB_MONGODB_COLLECTION,\n TMP_DB_SQL_TABLE,\n TMP_EXCEPTION_TYPE,\n TMP_EXCEPTION_MESSAGE,\n TMP_EXCEPTION_STACKTRACE,\n TMP_EXCEPTION_ESCAPED,\n TMP_FAAS_TRIGGER,\n TMP_FAAS_EXECUTION,\n TMP_FAAS_DOCUMENT_COLLECTION,\n TMP_FAAS_DOCUMENT_OPERATION,\n TMP_FAAS_DOCUMENT_TIME,\n TMP_FAAS_DOCUMENT_NAME,\n TMP_FAAS_TIME,\n TMP_FAAS_CRON,\n TMP_FAAS_COLDSTART,\n TMP_FAAS_INVOKED_NAME,\n TMP_FAAS_INVOKED_PROVIDER,\n TMP_FAAS_INVOKED_REGION,\n TMP_NET_TRANSPORT,\n TMP_NET_PEER_IP,\n TMP_NET_PEER_PORT,\n TMP_NET_PEER_NAME,\n TMP_NET_HOST_IP,\n TMP_NET_HOST_PORT,\n TMP_NET_HOST_NAME,\n TMP_NET_HOST_CONNECTION_TYPE,\n TMP_NET_HOST_CONNECTION_SUBTYPE,\n TMP_NET_HOST_CARRIER_NAME,\n TMP_NET_HOST_CARRIER_MCC,\n TMP_NET_HOST_CARRIER_MNC,\n TMP_NET_HOST_CARRIER_ICC,\n TMP_PEER_SERVICE,\n TMP_ENDUSER_ID,\n TMP_ENDUSER_ROLE,\n TMP_ENDUSER_SCOPE,\n TMP_THREAD_ID,\n TMP_THREAD_NAME,\n TMP_CODE_FUNCTION,\n TMP_CODE_NAMESPACE,\n TMP_CODE_FILEPATH,\n TMP_CODE_LINENO,\n TMP_HTTP_METHOD,\n TMP_HTTP_URL,\n TMP_HTTP_TARGET,\n TMP_HTTP_HOST,\n TMP_HTTP_SCHEME,\n TMP_HTTP_STATUS_CODE,\n TMP_HTTP_FLAVOR,\n TMP_HTTP_USER_AGENT,\n TMP_HTTP_REQUEST_CONTENT_LENGTH,\n TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,\n TMP_HTTP_RESPONSE_CONTENT_LENGTH,\n TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,\n TMP_HTTP_SERVER_NAME,\n TMP_HTTP_ROUTE,\n TMP_HTTP_CLIENT_IP,\n TMP_AWS_DYNAMODB_TABLE_NAMES,\n TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,\n TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,\n TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,\n TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,\n TMP_AWS_DYNAMODB_CONSISTENT_READ,\n TMP_AWS_DYNAMODB_PROJECTION,\n TMP_AWS_DYNAMODB_LIMIT,\n TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,\n TMP_AWS_DYNAMODB_INDEX_NAME,\n TMP_AWS_DYNAMODB_SELECT,\n TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,\n TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,\n TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,\n TMP_AWS_DYNAMODB_TABLE_COUNT,\n TMP_AWS_DYNAMODB_SCAN_FORWARD,\n TMP_AWS_DYNAMODB_SEGMENT,\n TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,\n TMP_AWS_DYNAMODB_COUNT,\n TMP_AWS_DYNAMODB_SCANNED_COUNT,\n TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,\n TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,\n TMP_MESSAGING_SYSTEM,\n TMP_MESSAGING_DESTINATION,\n TMP_MESSAGING_DESTINATION_KIND,\n TMP_MESSAGING_TEMP_DESTINATION,\n TMP_MESSAGING_PROTOCOL,\n TMP_MESSAGING_PROTOCOL_VERSION,\n TMP_MESSAGING_URL,\n TMP_MESSAGING_MESSAGE_ID,\n TMP_MESSAGING_CONVERSATION_ID,\n TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,\n TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,\n TMP_MESSAGING_OPERATION,\n TMP_MESSAGING_CONSUMER_ID,\n TMP_MESSAGING_RABBITMQ_ROUTING_KEY,\n TMP_MESSAGING_KAFKA_MESSAGE_KEY,\n TMP_MESSAGING_KAFKA_CONSUMER_GROUP,\n TMP_MESSAGING_KAFKA_CLIENT_ID,\n TMP_MESSAGING_KAFKA_PARTITION,\n TMP_MESSAGING_KAFKA_TOMBSTONE,\n TMP_RPC_SYSTEM,\n TMP_RPC_SERVICE,\n TMP_RPC_METHOD,\n TMP_RPC_GRPC_STATUS_CODE,\n TMP_RPC_JSONRPC_VERSION,\n TMP_RPC_JSONRPC_REQUEST_ID,\n TMP_RPC_JSONRPC_ERROR_CODE,\n TMP_RPC_JSONRPC_ERROR_MESSAGE,\n TMP_MESSAGE_TYPE,\n TMP_MESSAGE_ID,\n TMP_MESSAGE_COMPRESSED_SIZE,\n TMP_MESSAGE_UNCOMPRESSED_SIZE,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for DbSystemValues enum definition\n *\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_DBSYSTEMVALUES_OTHER_SQL = 'other_sql';\nconst TMP_DBSYSTEMVALUES_MSSQL = 'mssql';\nconst TMP_DBSYSTEMVALUES_MYSQL = 'mysql';\nconst TMP_DBSYSTEMVALUES_ORACLE = 'oracle';\nconst TMP_DBSYSTEMVALUES_DB2 = 'db2';\nconst TMP_DBSYSTEMVALUES_POSTGRESQL = 'postgresql';\nconst TMP_DBSYSTEMVALUES_REDSHIFT = 'redshift';\nconst TMP_DBSYSTEMVALUES_HIVE = 'hive';\nconst TMP_DBSYSTEMVALUES_CLOUDSCAPE = 'cloudscape';\nconst TMP_DBSYSTEMVALUES_HSQLDB = 'hsqldb';\nconst TMP_DBSYSTEMVALUES_PROGRESS = 'progress';\nconst TMP_DBSYSTEMVALUES_MAXDB = 'maxdb';\nconst TMP_DBSYSTEMVALUES_HANADB = 'hanadb';\nconst TMP_DBSYSTEMVALUES_INGRES = 'ingres';\nconst TMP_DBSYSTEMVALUES_FIRSTSQL = 'firstsql';\nconst TMP_DBSYSTEMVALUES_EDB = 'edb';\nconst TMP_DBSYSTEMVALUES_CACHE = 'cache';\nconst TMP_DBSYSTEMVALUES_ADABAS = 'adabas';\nconst TMP_DBSYSTEMVALUES_FIREBIRD = 'firebird';\nconst TMP_DBSYSTEMVALUES_DERBY = 'derby';\nconst TMP_DBSYSTEMVALUES_FILEMAKER = 'filemaker';\nconst TMP_DBSYSTEMVALUES_INFORMIX = 'informix';\nconst TMP_DBSYSTEMVALUES_INSTANTDB = 'instantdb';\nconst TMP_DBSYSTEMVALUES_INTERBASE = 'interbase';\nconst TMP_DBSYSTEMVALUES_MARIADB = 'mariadb';\nconst TMP_DBSYSTEMVALUES_NETEZZA = 'netezza';\nconst TMP_DBSYSTEMVALUES_PERVASIVE = 'pervasive';\nconst TMP_DBSYSTEMVALUES_POINTBASE = 'pointbase';\nconst TMP_DBSYSTEMVALUES_SQLITE = 'sqlite';\nconst TMP_DBSYSTEMVALUES_SYBASE = 'sybase';\nconst TMP_DBSYSTEMVALUES_TERADATA = 'teradata';\nconst TMP_DBSYSTEMVALUES_VERTICA = 'vertica';\nconst TMP_DBSYSTEMVALUES_H2 = 'h2';\nconst TMP_DBSYSTEMVALUES_COLDFUSION = 'coldfusion';\nconst TMP_DBSYSTEMVALUES_CASSANDRA = 'cassandra';\nconst TMP_DBSYSTEMVALUES_HBASE = 'hbase';\nconst TMP_DBSYSTEMVALUES_MONGODB = 'mongodb';\nconst TMP_DBSYSTEMVALUES_REDIS = 'redis';\nconst TMP_DBSYSTEMVALUES_COUCHBASE = 'couchbase';\nconst TMP_DBSYSTEMVALUES_COUCHDB = 'couchdb';\nconst TMP_DBSYSTEMVALUES_COSMOSDB = 'cosmosdb';\nconst TMP_DBSYSTEMVALUES_DYNAMODB = 'dynamodb';\nconst TMP_DBSYSTEMVALUES_NEO4J = 'neo4j';\nconst TMP_DBSYSTEMVALUES_GEODE = 'geode';\nconst TMP_DBSYSTEMVALUES_ELASTICSEARCH = 'elasticsearch';\nconst TMP_DBSYSTEMVALUES_MEMCACHED = 'memcached';\nconst TMP_DBSYSTEMVALUES_COCKROACHDB = 'cockroachdb';\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_OTHER_SQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MSSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MYSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_ORACLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_DB2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_POSTGRESQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_REDSHIFT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_HIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_CLOUDSCAPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_HSQLDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_PROGRESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MAXDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_HANADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_INGRES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_FIRSTSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_EDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_CACHE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_ADABAS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_FIREBIRD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_DERBY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_FILEMAKER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_INFORMIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_INSTANTDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_INTERBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MARIADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_NETEZZA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_PERVASIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_POINTBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_SQLITE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_SYBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_TERADATA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_VERTICA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_H2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COLDFUSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_CASSANDRA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_HBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MONGODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_REDIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COUCHBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COUCHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COSMOSDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_DYNAMODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_NEO4J in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_GEODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_ELASTICSEARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_MEMCACHED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED;\n\n/**\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n *\n * @deprecated Use DB_SYSTEM_VALUE_COCKROACHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB;\n\n/**\n * Identifies the Values for DbSystemValues enum definition\n *\n * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers.\n * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification.\n */\nexport type DbSystemValues = {\n /** Some other SQL database. Fallback only. See notes. */\n OTHER_SQL: 'other_sql';\n\n /** Microsoft SQL Server. */\n MSSQL: 'mssql';\n\n /** MySQL. */\n MYSQL: 'mysql';\n\n /** Oracle Database. */\n ORACLE: 'oracle';\n\n /** IBM Db2. */\n DB2: 'db2';\n\n /** PostgreSQL. */\n POSTGRESQL: 'postgresql';\n\n /** Amazon Redshift. */\n REDSHIFT: 'redshift';\n\n /** Apache Hive. */\n HIVE: 'hive';\n\n /** Cloudscape. */\n CLOUDSCAPE: 'cloudscape';\n\n /** HyperSQL DataBase. */\n HSQLDB: 'hsqldb';\n\n /** Progress Database. */\n PROGRESS: 'progress';\n\n /** SAP MaxDB. */\n MAXDB: 'maxdb';\n\n /** SAP HANA. */\n HANADB: 'hanadb';\n\n /** Ingres. */\n INGRES: 'ingres';\n\n /** FirstSQL. */\n FIRSTSQL: 'firstsql';\n\n /** EnterpriseDB. */\n EDB: 'edb';\n\n /** InterSystems Caché. */\n CACHE: 'cache';\n\n /** Adabas (Adaptable Database System). */\n ADABAS: 'adabas';\n\n /** Firebird. */\n FIREBIRD: 'firebird';\n\n /** Apache Derby. */\n DERBY: 'derby';\n\n /** FileMaker. */\n FILEMAKER: 'filemaker';\n\n /** Informix. */\n INFORMIX: 'informix';\n\n /** InstantDB. */\n INSTANTDB: 'instantdb';\n\n /** InterBase. */\n INTERBASE: 'interbase';\n\n /** MariaDB. */\n MARIADB: 'mariadb';\n\n /** Netezza. */\n NETEZZA: 'netezza';\n\n /** Pervasive PSQL. */\n PERVASIVE: 'pervasive';\n\n /** PointBase. */\n POINTBASE: 'pointbase';\n\n /** SQLite. */\n SQLITE: 'sqlite';\n\n /** Sybase. */\n SYBASE: 'sybase';\n\n /** Teradata. */\n TERADATA: 'teradata';\n\n /** Vertica. */\n VERTICA: 'vertica';\n\n /** H2. */\n H2: 'h2';\n\n /** ColdFusion IMQ. */\n COLDFUSION: 'coldfusion';\n\n /** Apache Cassandra. */\n CASSANDRA: 'cassandra';\n\n /** Apache HBase. */\n HBASE: 'hbase';\n\n /** MongoDB. */\n MONGODB: 'mongodb';\n\n /** Redis. */\n REDIS: 'redis';\n\n /** Couchbase. */\n COUCHBASE: 'couchbase';\n\n /** CouchDB. */\n COUCHDB: 'couchdb';\n\n /** Microsoft Azure Cosmos DB. */\n COSMOSDB: 'cosmosdb';\n\n /** Amazon DynamoDB. */\n DYNAMODB: 'dynamodb';\n\n /** Neo4j. */\n NEO4J: 'neo4j';\n\n /** Apache Geode. */\n GEODE: 'geode';\n\n /** Elasticsearch. */\n ELASTICSEARCH: 'elasticsearch';\n\n /** Memcached. */\n MEMCACHED: 'memcached';\n\n /** CockroachDB. */\n COCKROACHDB: 'cockroachdb';\n};\n\n/**\n * The constant map of values for DbSystemValues.\n * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification.\n */\nexport const DbSystemValues: DbSystemValues =\n /*#__PURE__*/ createConstMap([\n TMP_DBSYSTEMVALUES_OTHER_SQL,\n TMP_DBSYSTEMVALUES_MSSQL,\n TMP_DBSYSTEMVALUES_MYSQL,\n TMP_DBSYSTEMVALUES_ORACLE,\n TMP_DBSYSTEMVALUES_DB2,\n TMP_DBSYSTEMVALUES_POSTGRESQL,\n TMP_DBSYSTEMVALUES_REDSHIFT,\n TMP_DBSYSTEMVALUES_HIVE,\n TMP_DBSYSTEMVALUES_CLOUDSCAPE,\n TMP_DBSYSTEMVALUES_HSQLDB,\n TMP_DBSYSTEMVALUES_PROGRESS,\n TMP_DBSYSTEMVALUES_MAXDB,\n TMP_DBSYSTEMVALUES_HANADB,\n TMP_DBSYSTEMVALUES_INGRES,\n TMP_DBSYSTEMVALUES_FIRSTSQL,\n TMP_DBSYSTEMVALUES_EDB,\n TMP_DBSYSTEMVALUES_CACHE,\n TMP_DBSYSTEMVALUES_ADABAS,\n TMP_DBSYSTEMVALUES_FIREBIRD,\n TMP_DBSYSTEMVALUES_DERBY,\n TMP_DBSYSTEMVALUES_FILEMAKER,\n TMP_DBSYSTEMVALUES_INFORMIX,\n TMP_DBSYSTEMVALUES_INSTANTDB,\n TMP_DBSYSTEMVALUES_INTERBASE,\n TMP_DBSYSTEMVALUES_MARIADB,\n TMP_DBSYSTEMVALUES_NETEZZA,\n TMP_DBSYSTEMVALUES_PERVASIVE,\n TMP_DBSYSTEMVALUES_POINTBASE,\n TMP_DBSYSTEMVALUES_SQLITE,\n TMP_DBSYSTEMVALUES_SYBASE,\n TMP_DBSYSTEMVALUES_TERADATA,\n TMP_DBSYSTEMVALUES_VERTICA,\n TMP_DBSYSTEMVALUES_H2,\n TMP_DBSYSTEMVALUES_COLDFUSION,\n TMP_DBSYSTEMVALUES_CASSANDRA,\n TMP_DBSYSTEMVALUES_HBASE,\n TMP_DBSYSTEMVALUES_MONGODB,\n TMP_DBSYSTEMVALUES_REDIS,\n TMP_DBSYSTEMVALUES_COUCHBASE,\n TMP_DBSYSTEMVALUES_COUCHDB,\n TMP_DBSYSTEMVALUES_COSMOSDB,\n TMP_DBSYSTEMVALUES_DYNAMODB,\n TMP_DBSYSTEMVALUES_NEO4J,\n TMP_DBSYSTEMVALUES_GEODE,\n TMP_DBSYSTEMVALUES_ELASTICSEARCH,\n TMP_DBSYSTEMVALUES_MEMCACHED,\n TMP_DBSYSTEMVALUES_COCKROACHDB,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for DbCassandraConsistencyLevelValues enum definition\n *\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = 'all';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = 'each_quorum';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = 'quorum';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = 'local_quorum';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = 'one';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = 'two';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = 'three';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = 'local_one';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = 'any';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = 'serial';\nconst TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = 'local_serial';\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ALL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_ALL =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_EACH_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_ONE =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_TWO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_TWO =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_THREE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_THREE =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ANY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_ANY =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL;\n\n/**\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n *\n * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL =\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL;\n\n/**\n * Identifies the Values for DbCassandraConsistencyLevelValues enum definition\n *\n * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html).\n * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification.\n */\nexport type DbCassandraConsistencyLevelValues = {\n /** all. */\n ALL: 'all';\n\n /** each_quorum. */\n EACH_QUORUM: 'each_quorum';\n\n /** quorum. */\n QUORUM: 'quorum';\n\n /** local_quorum. */\n LOCAL_QUORUM: 'local_quorum';\n\n /** one. */\n ONE: 'one';\n\n /** two. */\n TWO: 'two';\n\n /** three. */\n THREE: 'three';\n\n /** local_one. */\n LOCAL_ONE: 'local_one';\n\n /** any. */\n ANY: 'any';\n\n /** serial. */\n SERIAL: 'serial';\n\n /** local_serial. */\n LOCAL_SERIAL: 'local_serial';\n};\n\n/**\n * The constant map of values for DbCassandraConsistencyLevelValues.\n * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification.\n */\nexport const DbCassandraConsistencyLevelValues: DbCassandraConsistencyLevelValues =\n /*#__PURE__*/ createConstMap([\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,\n TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for FaasTriggerValues enum definition\n *\n * Type of the trigger on which the function is executed.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_FAASTRIGGERVALUES_DATASOURCE = 'datasource';\nconst TMP_FAASTRIGGERVALUES_HTTP = 'http';\nconst TMP_FAASTRIGGERVALUES_PUBSUB = 'pubsub';\nconst TMP_FAASTRIGGERVALUES_TIMER = 'timer';\nconst TMP_FAASTRIGGERVALUES_OTHER = 'other';\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_DATASOURCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_HTTP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_PUBSUB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_TIMER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER;\n\n/**\n * Type of the trigger on which the function is executed.\n *\n * @deprecated Use FAAS_TRIGGER_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER;\n\n/**\n * Identifies the Values for FaasTriggerValues enum definition\n *\n * Type of the trigger on which the function is executed.\n * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification.\n */\nexport type FaasTriggerValues = {\n /** A response to some data source operation such as a database or filesystem read/write. */\n DATASOURCE: 'datasource';\n\n /** To provide an answer to an inbound HTTP request. */\n HTTP: 'http';\n\n /** A function is set to be executed when messages are sent to a messaging system. */\n PUBSUB: 'pubsub';\n\n /** A function is scheduled to be executed regularly. */\n TIMER: 'timer';\n\n /** If none of the others apply. */\n OTHER: 'other';\n};\n\n/**\n * The constant map of values for FaasTriggerValues.\n * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification.\n */\nexport const FaasTriggerValues: FaasTriggerValues =\n /*#__PURE__*/ createConstMap([\n TMP_FAASTRIGGERVALUES_DATASOURCE,\n TMP_FAASTRIGGERVALUES_HTTP,\n TMP_FAASTRIGGERVALUES_PUBSUB,\n TMP_FAASTRIGGERVALUES_TIMER,\n TMP_FAASTRIGGERVALUES_OTHER,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for FaasDocumentOperationValues enum definition\n *\n * Describes the type of the operation that was performed on the data.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = 'insert';\nconst TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = 'edit';\nconst TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = 'delete';\n\n/**\n * Describes the type of the operation that was performed on the data.\n *\n * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_INSERT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASDOCUMENTOPERATIONVALUES_INSERT =\n TMP_FAASDOCUMENTOPERATIONVALUES_INSERT;\n\n/**\n * Describes the type of the operation that was performed on the data.\n *\n * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_EDIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASDOCUMENTOPERATIONVALUES_EDIT =\n TMP_FAASDOCUMENTOPERATIONVALUES_EDIT;\n\n/**\n * Describes the type of the operation that was performed on the data.\n *\n * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_DELETE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASDOCUMENTOPERATIONVALUES_DELETE =\n TMP_FAASDOCUMENTOPERATIONVALUES_DELETE;\n\n/**\n * Identifies the Values for FaasDocumentOperationValues enum definition\n *\n * Describes the type of the operation that was performed on the data.\n * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification.\n */\nexport type FaasDocumentOperationValues = {\n /** When a new object is created. */\n INSERT: 'insert';\n\n /** When an object is modified. */\n EDIT: 'edit';\n\n /** When an object is deleted. */\n DELETE: 'delete';\n};\n\n/**\n * The constant map of values for FaasDocumentOperationValues.\n * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification.\n */\nexport const FaasDocumentOperationValues: FaasDocumentOperationValues =\n /*#__PURE__*/ createConstMap([\n TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,\n TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,\n TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for FaasInvokedProviderValues enum definition\n *\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud';\nconst TMP_FAASINVOKEDPROVIDERVALUES_AWS = 'aws';\nconst TMP_FAASINVOKEDPROVIDERVALUES_AZURE = 'azure';\nconst TMP_FAASINVOKEDPROVIDERVALUES_GCP = 'gcp';\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD =\n TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD;\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS;\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASINVOKEDPROVIDERVALUES_AZURE =\n TMP_FAASINVOKEDPROVIDERVALUES_AZURE;\n\n/**\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n *\n * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP;\n\n/**\n * Identifies the Values for FaasInvokedProviderValues enum definition\n *\n * The cloud provider of the invoked function.\n *\n * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function.\n * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification.\n */\nexport type FaasInvokedProviderValues = {\n /** Alibaba Cloud. */\n ALIBABA_CLOUD: 'alibaba_cloud';\n\n /** Amazon Web Services. */\n AWS: 'aws';\n\n /** Microsoft Azure. */\n AZURE: 'azure';\n\n /** Google Cloud Platform. */\n GCP: 'gcp';\n};\n\n/**\n * The constant map of values for FaasInvokedProviderValues.\n * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification.\n */\nexport const FaasInvokedProviderValues: FaasInvokedProviderValues =\n /*#__PURE__*/ createConstMap([\n TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,\n TMP_FAASINVOKEDPROVIDERVALUES_AWS,\n TMP_FAASINVOKEDPROVIDERVALUES_AZURE,\n TMP_FAASINVOKEDPROVIDERVALUES_GCP,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for NetTransportValues enum definition\n *\n * Transport protocol used. See note below.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_NETTRANSPORTVALUES_IP_TCP = 'ip_tcp';\nconst TMP_NETTRANSPORTVALUES_IP_UDP = 'ip_udp';\nconst TMP_NETTRANSPORTVALUES_IP = 'ip';\nconst TMP_NETTRANSPORTVALUES_UNIX = 'unix';\nconst TMP_NETTRANSPORTVALUES_PIPE = 'pipe';\nconst TMP_NETTRANSPORTVALUES_INPROC = 'inproc';\nconst TMP_NETTRANSPORTVALUES_OTHER = 'other';\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_IP_TCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_IP_UDP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Removed in v1.21.0.\n */\nexport const NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Removed in v1.21.0.\n */\nexport const NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_PIPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_INPROC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC;\n\n/**\n * Transport protocol used. See note below.\n *\n * @deprecated Use NET_TRANSPORT_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER;\n\n/**\n * Identifies the Values for NetTransportValues enum definition\n *\n * Transport protocol used. See note below.\n * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification.\n */\nexport type NetTransportValues = {\n /** ip_tcp. */\n IP_TCP: 'ip_tcp';\n\n /** ip_udp. */\n IP_UDP: 'ip_udp';\n\n /** Another IP-based protocol. */\n IP: 'ip';\n\n /** Unix Domain socket. See below. */\n UNIX: 'unix';\n\n /** Named or anonymous pipe. See note below. */\n PIPE: 'pipe';\n\n /** In-process communication. */\n INPROC: 'inproc';\n\n /** Something else (non IP-based). */\n OTHER: 'other';\n};\n\n/**\n * The constant map of values for NetTransportValues.\n * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification.\n */\nexport const NetTransportValues: NetTransportValues =\n /*#__PURE__*/ createConstMap([\n TMP_NETTRANSPORTVALUES_IP_TCP,\n TMP_NETTRANSPORTVALUES_IP_UDP,\n TMP_NETTRANSPORTVALUES_IP,\n TMP_NETTRANSPORTVALUES_UNIX,\n TMP_NETTRANSPORTVALUES_PIPE,\n TMP_NETTRANSPORTVALUES_INPROC,\n TMP_NETTRANSPORTVALUES_OTHER,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for NetHostConnectionTypeValues enum definition\n *\n * The internet connection type currently being used by the host.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = 'wifi';\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = 'wired';\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = 'cell';\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = 'unavailable';\nconst TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = 'unknown';\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIFI in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_WIFI =\n TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIRED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_WIRED =\n TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_CELL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_CELL =\n TMP_NETHOSTCONNECTIONTYPEVALUES_CELL;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE =\n TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE;\n\n/**\n * The internet connection type currently being used by the host.\n *\n * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONTYPEVALUES_UNKNOWN =\n TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN;\n\n/**\n * Identifies the Values for NetHostConnectionTypeValues enum definition\n *\n * The internet connection type currently being used by the host.\n * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification.\n */\nexport type NetHostConnectionTypeValues = {\n /** wifi. */\n WIFI: 'wifi';\n\n /** wired. */\n WIRED: 'wired';\n\n /** cell. */\n CELL: 'cell';\n\n /** unavailable. */\n UNAVAILABLE: 'unavailable';\n\n /** unknown. */\n UNKNOWN: 'unknown';\n};\n\n/**\n * The constant map of values for NetHostConnectionTypeValues.\n * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification.\n */\nexport const NetHostConnectionTypeValues: NetHostConnectionTypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,\n TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,\n TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,\n TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,\n TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for NetHostConnectionSubtypeValues enum definition\n *\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = 'gprs';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = 'edge';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = 'umts';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = 'cdma';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = 'evdo_0';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = 'evdo_a';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = 'cdma2000_1xrtt';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = 'hsdpa';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = 'hsupa';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = 'hspa';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = 'iden';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = 'evdo_b';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = 'lte';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = 'ehrpd';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = 'hspap';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = 'gsm';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = 'td_scdma';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = 'iwlan';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = 'nr';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = 'nrnsa';\nconst TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = 'lte_ca';\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GPRS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_GPRS =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EDGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EDGE =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_UMTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_UMTS =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_CDMA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_A in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA2000_1XRTT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSDPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSUPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_HSPA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IDEN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_IDEN =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_B in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_LTE =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EHRPD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPAP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GSM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_GSM =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_TD_SCDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IWLAN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_NR =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NRNSA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA;\n\n/**\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n *\n * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE_CA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA =\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA;\n\n/**\n * Identifies the Values for NetHostConnectionSubtypeValues enum definition\n *\n * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection.\n * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification.\n */\nexport type NetHostConnectionSubtypeValues = {\n /** GPRS. */\n GPRS: 'gprs';\n\n /** EDGE. */\n EDGE: 'edge';\n\n /** UMTS. */\n UMTS: 'umts';\n\n /** CDMA. */\n CDMA: 'cdma';\n\n /** EVDO Rel. 0. */\n EVDO_0: 'evdo_0';\n\n /** EVDO Rev. A. */\n EVDO_A: 'evdo_a';\n\n /** CDMA2000 1XRTT. */\n CDMA2000_1XRTT: 'cdma2000_1xrtt';\n\n /** HSDPA. */\n HSDPA: 'hsdpa';\n\n /** HSUPA. */\n HSUPA: 'hsupa';\n\n /** HSPA. */\n HSPA: 'hspa';\n\n /** IDEN. */\n IDEN: 'iden';\n\n /** EVDO Rev. B. */\n EVDO_B: 'evdo_b';\n\n /** LTE. */\n LTE: 'lte';\n\n /** EHRPD. */\n EHRPD: 'ehrpd';\n\n /** HSPAP. */\n HSPAP: 'hspap';\n\n /** GSM. */\n GSM: 'gsm';\n\n /** TD-SCDMA. */\n TD_SCDMA: 'td_scdma';\n\n /** IWLAN. */\n IWLAN: 'iwlan';\n\n /** 5G NR (New Radio). */\n NR: 'nr';\n\n /** 5G NRNSA (New Radio Non-Standalone). */\n NRNSA: 'nrnsa';\n\n /** LTE CA. */\n LTE_CA: 'lte_ca';\n};\n\n/**\n * The constant map of values for NetHostConnectionSubtypeValues.\n * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification.\n */\nexport const NetHostConnectionSubtypeValues: NetHostConnectionSubtypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,\n TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for HttpFlavorValues enum definition\n *\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_HTTPFLAVORVALUES_HTTP_1_0 = '1.0';\nconst TMP_HTTPFLAVORVALUES_HTTP_1_1 = '1.1';\nconst TMP_HTTPFLAVORVALUES_HTTP_2_0 = '2.0';\nconst TMP_HTTPFLAVORVALUES_SPDY = 'SPDY';\nconst TMP_HTTPFLAVORVALUES_QUIC = 'QUIC';\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_1 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_2_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_SPDY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY;\n\n/**\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n *\n * @deprecated Use HTTP_FLAVOR_VALUE_QUIC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC;\n\n/**\n * Identifies the Values for HttpFlavorValues enum definition\n *\n * Kind of HTTP protocol used.\n *\n * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed.\n * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification.\n */\nexport type HttpFlavorValues = {\n /** HTTP 1.0. */\n HTTP_1_0: '1.0';\n\n /** HTTP 1.1. */\n HTTP_1_1: '1.1';\n\n /** HTTP 2. */\n HTTP_2_0: '2.0';\n\n /** SPDY protocol. */\n SPDY: 'SPDY';\n\n /** QUIC protocol. */\n QUIC: 'QUIC';\n};\n\n/**\n * The constant map of values for HttpFlavorValues.\n * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification.\n */\nexport const HttpFlavorValues: HttpFlavorValues = {\n HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0,\n HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1,\n HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0,\n SPDY: TMP_HTTPFLAVORVALUES_SPDY,\n QUIC: TMP_HTTPFLAVORVALUES_QUIC,\n};\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for MessagingDestinationKindValues enum definition\n *\n * The kind of message destination.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = 'queue';\nconst TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = 'topic';\n\n/**\n * The kind of message destination.\n *\n * @deprecated Removed in semconv v1.20.0.\n */\nexport const MESSAGINGDESTINATIONKINDVALUES_QUEUE =\n TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE;\n\n/**\n * The kind of message destination.\n *\n * @deprecated Removed in semconv v1.20.0.\n */\nexport const MESSAGINGDESTINATIONKINDVALUES_TOPIC =\n TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC;\n\n/**\n * Identifies the Values for MessagingDestinationKindValues enum definition\n *\n * The kind of message destination.\n * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification.\n */\nexport type MessagingDestinationKindValues = {\n /** A message sent to a queue. */\n QUEUE: 'queue';\n\n /** A message sent to a topic. */\n TOPIC: 'topic';\n};\n\n/**\n * The constant map of values for MessagingDestinationKindValues.\n * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification.\n */\nexport const MessagingDestinationKindValues: MessagingDestinationKindValues =\n /*#__PURE__*/ createConstMap([\n TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,\n TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for MessagingOperationValues enum definition\n *\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_MESSAGINGOPERATIONVALUES_RECEIVE = 'receive';\nconst TMP_MESSAGINGOPERATIONVALUES_PROCESS = 'process';\n\n/**\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n *\n * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_RECEIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const MESSAGINGOPERATIONVALUES_RECEIVE =\n TMP_MESSAGINGOPERATIONVALUES_RECEIVE;\n\n/**\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n *\n * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_PROCESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const MESSAGINGOPERATIONVALUES_PROCESS =\n TMP_MESSAGINGOPERATIONVALUES_PROCESS;\n\n/**\n * Identifies the Values for MessagingOperationValues enum definition\n *\n * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case.\n * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification.\n */\nexport type MessagingOperationValues = {\n /** receive. */\n RECEIVE: 'receive';\n\n /** process. */\n PROCESS: 'process';\n};\n\n/**\n * The constant map of values for MessagingOperationValues.\n * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification.\n */\nexport const MessagingOperationValues: MessagingOperationValues =\n /*#__PURE__*/ createConstMap([\n TMP_MESSAGINGOPERATIONVALUES_RECEIVE,\n TMP_MESSAGINGOPERATIONVALUES_PROCESS,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for RpcGrpcStatusCodeValues enum definition\n *\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_RPCGRPCSTATUSCODEVALUES_OK = 0;\nconst TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1;\nconst TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2;\nconst TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3;\nconst TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4;\nconst TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5;\nconst TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6;\nconst TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7;\nconst TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8;\nconst TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9;\nconst TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10;\nconst TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11;\nconst TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12;\nconst TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13;\nconst TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14;\nconst TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15;\nconst TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_CANCELLED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_CANCELLED =\n TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_UNKNOWN =\n TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INVALID_ARGUMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT =\n TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DEADLINE_EXCEEDED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED =\n TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_NOT_FOUND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_NOT_FOUND =\n TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ALREADY_EXISTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS =\n TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_PERMISSION_DENIED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED =\n TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_RESOURCE_EXHAUSTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED =\n TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_FAILED_PRECONDITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION =\n TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ABORTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_ABORTED =\n TMP_RPCGRPCSTATUSCODEVALUES_ABORTED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OUT_OF_RANGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE =\n TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNIMPLEMENTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED =\n TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INTERNAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_INTERNAL =\n TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_UNAVAILABLE =\n TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DATA_LOSS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_DATA_LOSS =\n TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS;\n\n/**\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n *\n * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAUTHENTICATED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED =\n TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED;\n\n/**\n * Identifies the Values for RpcGrpcStatusCodeValues enum definition\n *\n * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request.\n * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification.\n */\nexport type RpcGrpcStatusCodeValues = {\n /** OK. */\n OK: 0;\n\n /** CANCELLED. */\n CANCELLED: 1;\n\n /** UNKNOWN. */\n UNKNOWN: 2;\n\n /** INVALID_ARGUMENT. */\n INVALID_ARGUMENT: 3;\n\n /** DEADLINE_EXCEEDED. */\n DEADLINE_EXCEEDED: 4;\n\n /** NOT_FOUND. */\n NOT_FOUND: 5;\n\n /** ALREADY_EXISTS. */\n ALREADY_EXISTS: 6;\n\n /** PERMISSION_DENIED. */\n PERMISSION_DENIED: 7;\n\n /** RESOURCE_EXHAUSTED. */\n RESOURCE_EXHAUSTED: 8;\n\n /** FAILED_PRECONDITION. */\n FAILED_PRECONDITION: 9;\n\n /** ABORTED. */\n ABORTED: 10;\n\n /** OUT_OF_RANGE. */\n OUT_OF_RANGE: 11;\n\n /** UNIMPLEMENTED. */\n UNIMPLEMENTED: 12;\n\n /** INTERNAL. */\n INTERNAL: 13;\n\n /** UNAVAILABLE. */\n UNAVAILABLE: 14;\n\n /** DATA_LOSS. */\n DATA_LOSS: 15;\n\n /** UNAUTHENTICATED. */\n UNAUTHENTICATED: 16;\n};\n\n/**\n * The constant map of values for RpcGrpcStatusCodeValues.\n * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification.\n */\nexport const RpcGrpcStatusCodeValues: RpcGrpcStatusCodeValues = {\n OK: TMP_RPCGRPCSTATUSCODEVALUES_OK,\n CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,\n UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,\n INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,\n DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,\n NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,\n ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,\n PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,\n RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,\n FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,\n ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,\n OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,\n UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,\n INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,\n UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,\n DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,\n UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,\n};\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for MessageTypeValues enum definition\n *\n * Whether this is a received or sent message.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_MESSAGETYPEVALUES_SENT = 'SENT';\nconst TMP_MESSAGETYPEVALUES_RECEIVED = 'RECEIVED';\n\n/**\n * Whether this is a received or sent message.\n *\n * @deprecated Use MESSAGE_TYPE_VALUE_SENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT;\n\n/**\n * Whether this is a received or sent message.\n *\n * @deprecated Use MESSAGE_TYPE_VALUE_RECEIVED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED;\n\n/**\n * Identifies the Values for MessageTypeValues enum definition\n *\n * Whether this is a received or sent message.\n * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification.\n */\nexport type MessageTypeValues = {\n /** sent. */\n SENT: 'SENT';\n\n /** received. */\n RECEIVED: 'RECEIVED';\n};\n\n/**\n * The constant map of values for MessageTypeValues.\n * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification.\n */\nexport const MessageTypeValues: MessageTypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_MESSAGETYPEVALUES_SENT,\n TMP_MESSAGETYPEVALUES_RECEIVED,\n ]);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable no-restricted-syntax --\n * These re-exports are only of constants, only one-level deep at this point,\n * and should not cause problems for tree-shakers.\n */\nexport * from './SemanticAttributes';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createConstMap } from '../internal/utils';\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------\n// Constant values for SemanticResourceAttributes\n//----------------------------------------------------------------------------------------------------------\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_CLOUD_PROVIDER = 'cloud.provider';\nconst TMP_CLOUD_ACCOUNT_ID = 'cloud.account.id';\nconst TMP_CLOUD_REGION = 'cloud.region';\nconst TMP_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone';\nconst TMP_CLOUD_PLATFORM = 'cloud.platform';\nconst TMP_AWS_ECS_CONTAINER_ARN = 'aws.ecs.container.arn';\nconst TMP_AWS_ECS_CLUSTER_ARN = 'aws.ecs.cluster.arn';\nconst TMP_AWS_ECS_LAUNCHTYPE = 'aws.ecs.launchtype';\nconst TMP_AWS_ECS_TASK_ARN = 'aws.ecs.task.arn';\nconst TMP_AWS_ECS_TASK_FAMILY = 'aws.ecs.task.family';\nconst TMP_AWS_ECS_TASK_REVISION = 'aws.ecs.task.revision';\nconst TMP_AWS_EKS_CLUSTER_ARN = 'aws.eks.cluster.arn';\nconst TMP_AWS_LOG_GROUP_NAMES = 'aws.log.group.names';\nconst TMP_AWS_LOG_GROUP_ARNS = 'aws.log.group.arns';\nconst TMP_AWS_LOG_STREAM_NAMES = 'aws.log.stream.names';\nconst TMP_AWS_LOG_STREAM_ARNS = 'aws.log.stream.arns';\nconst TMP_CONTAINER_NAME = 'container.name';\nconst TMP_CONTAINER_ID = 'container.id';\nconst TMP_CONTAINER_RUNTIME = 'container.runtime';\nconst TMP_CONTAINER_IMAGE_NAME = 'container.image.name';\nconst TMP_CONTAINER_IMAGE_TAG = 'container.image.tag';\nconst TMP_DEPLOYMENT_ENVIRONMENT = 'deployment.environment';\nconst TMP_DEVICE_ID = 'device.id';\nconst TMP_DEVICE_MODEL_IDENTIFIER = 'device.model.identifier';\nconst TMP_DEVICE_MODEL_NAME = 'device.model.name';\nconst TMP_FAAS_NAME = 'faas.name';\nconst TMP_FAAS_ID = 'faas.id';\nconst TMP_FAAS_VERSION = 'faas.version';\nconst TMP_FAAS_INSTANCE = 'faas.instance';\nconst TMP_FAAS_MAX_MEMORY = 'faas.max_memory';\nconst TMP_HOST_ID = 'host.id';\nconst TMP_HOST_NAME = 'host.name';\nconst TMP_HOST_TYPE = 'host.type';\nconst TMP_HOST_ARCH = 'host.arch';\nconst TMP_HOST_IMAGE_NAME = 'host.image.name';\nconst TMP_HOST_IMAGE_ID = 'host.image.id';\nconst TMP_HOST_IMAGE_VERSION = 'host.image.version';\nconst TMP_K8S_CLUSTER_NAME = 'k8s.cluster.name';\nconst TMP_K8S_NODE_NAME = 'k8s.node.name';\nconst TMP_K8S_NODE_UID = 'k8s.node.uid';\nconst TMP_K8S_NAMESPACE_NAME = 'k8s.namespace.name';\nconst TMP_K8S_POD_UID = 'k8s.pod.uid';\nconst TMP_K8S_POD_NAME = 'k8s.pod.name';\nconst TMP_K8S_CONTAINER_NAME = 'k8s.container.name';\nconst TMP_K8S_REPLICASET_UID = 'k8s.replicaset.uid';\nconst TMP_K8S_REPLICASET_NAME = 'k8s.replicaset.name';\nconst TMP_K8S_DEPLOYMENT_UID = 'k8s.deployment.uid';\nconst TMP_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name';\nconst TMP_K8S_STATEFULSET_UID = 'k8s.statefulset.uid';\nconst TMP_K8S_STATEFULSET_NAME = 'k8s.statefulset.name';\nconst TMP_K8S_DAEMONSET_UID = 'k8s.daemonset.uid';\nconst TMP_K8S_DAEMONSET_NAME = 'k8s.daemonset.name';\nconst TMP_K8S_JOB_UID = 'k8s.job.uid';\nconst TMP_K8S_JOB_NAME = 'k8s.job.name';\nconst TMP_K8S_CRONJOB_UID = 'k8s.cronjob.uid';\nconst TMP_K8S_CRONJOB_NAME = 'k8s.cronjob.name';\nconst TMP_OS_TYPE = 'os.type';\nconst TMP_OS_DESCRIPTION = 'os.description';\nconst TMP_OS_NAME = 'os.name';\nconst TMP_OS_VERSION = 'os.version';\nconst TMP_PROCESS_PID = 'process.pid';\nconst TMP_PROCESS_EXECUTABLE_NAME = 'process.executable.name';\nconst TMP_PROCESS_EXECUTABLE_PATH = 'process.executable.path';\nconst TMP_PROCESS_COMMAND = 'process.command';\nconst TMP_PROCESS_COMMAND_LINE = 'process.command_line';\nconst TMP_PROCESS_COMMAND_ARGS = 'process.command_args';\nconst TMP_PROCESS_OWNER = 'process.owner';\nconst TMP_PROCESS_RUNTIME_NAME = 'process.runtime.name';\nconst TMP_PROCESS_RUNTIME_VERSION = 'process.runtime.version';\nconst TMP_PROCESS_RUNTIME_DESCRIPTION = 'process.runtime.description';\nconst TMP_SERVICE_NAME = 'service.name';\nconst TMP_SERVICE_NAMESPACE = 'service.namespace';\nconst TMP_SERVICE_INSTANCE_ID = 'service.instance.id';\nconst TMP_SERVICE_VERSION = 'service.version';\nconst TMP_TELEMETRY_SDK_NAME = 'telemetry.sdk.name';\nconst TMP_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language';\nconst TMP_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version';\nconst TMP_TELEMETRY_AUTO_VERSION = 'telemetry.auto.version';\nconst TMP_WEBENGINE_NAME = 'webengine.name';\nconst TMP_WEBENGINE_VERSION = 'webengine.version';\nconst TMP_WEBENGINE_DESCRIPTION = 'webengine.description';\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use ATTR_CLOUD_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER;\n\n/**\n * The cloud account ID the resource is assigned to.\n *\n * @deprecated Use ATTR_CLOUD_ACCOUNT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID;\n\n/**\n * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations).\n *\n * @deprecated Use ATTR_CLOUD_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION;\n\n/**\n * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running.\n *\n * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud.\n *\n * @deprecated Use ATTR_CLOUD_AVAILABILITY_ZONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use ATTR_CLOUD_PLATFORM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM;\n\n/**\n * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html).\n *\n * @deprecated Use ATTR_AWS_ECS_CONTAINER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN;\n\n/**\n * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html).\n *\n * @deprecated Use ATTR_AWS_ECS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN;\n\n/**\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n *\n * @deprecated Use ATTR_AWS_ECS_LAUNCHTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE;\n\n/**\n * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html).\n *\n * @deprecated Use ATTR_AWS_ECS_TASK_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN;\n\n/**\n * The task definition family this task definition is a member of.\n *\n * @deprecated Use ATTR_AWS_ECS_TASK_FAMILY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY;\n\n/**\n * The revision for this task definition.\n *\n * @deprecated Use ATTR_AWS_ECS_TASK_REVISION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION;\n\n/**\n * The ARN of an EKS cluster.\n *\n * @deprecated Use ATTR_AWS_EKS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN;\n\n/**\n * The name(s) of the AWS log group(s) an application is writing to.\n *\n * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group.\n *\n * @deprecated Use ATTR_AWS_LOG_GROUP_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES;\n\n/**\n * The Amazon Resource Name(s) (ARN) of the AWS log group(s).\n *\n * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format).\n *\n * @deprecated Use ATTR_AWS_LOG_GROUP_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS;\n\n/**\n * The name(s) of the AWS log stream(s) an application is writing to.\n *\n * @deprecated Use ATTR_AWS_LOG_STREAM_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES;\n\n/**\n * The ARN(s) of the AWS log stream(s).\n *\n * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream.\n *\n * @deprecated Use ATTR_AWS_LOG_STREAM_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS;\n\n/**\n * Container name.\n *\n * @deprecated Use ATTR_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME;\n\n/**\n * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated.\n *\n * @deprecated Use ATTR_CONTAINER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID;\n\n/**\n * The container runtime managing this container.\n *\n * @deprecated Use ATTR_CONTAINER_RUNTIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME;\n\n/**\n * Name of the image the container was built on.\n *\n * @deprecated Use ATTR_CONTAINER_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME;\n\n/**\n * Container image tag.\n *\n * @deprecated Use ATTR_CONTAINER_IMAGE_TAGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG;\n\n/**\n * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier).\n *\n * @deprecated Use ATTR_DEPLOYMENT_ENVIRONMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT;\n\n/**\n * A unique identifier representing the device.\n *\n * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence.\n *\n * @deprecated Use ATTR_DEVICE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID;\n\n/**\n * The model identifier for the device.\n *\n * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device.\n *\n * @deprecated Use ATTR_DEVICE_MODEL_IDENTIFIER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER;\n\n/**\n * The marketing name for the device model.\n *\n * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative.\n *\n * @deprecated Use ATTR_DEVICE_MODEL_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME;\n\n/**\n * The name of the single function that this runtime instance executes.\n *\n * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes).\n *\n * @deprecated Use ATTR_FAAS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME;\n\n/**\n* The unique ID of the single function that this runtime instance executes.\n*\n* Note: Depending on the cloud provider, use:\n\n* **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html).\nTake care not to use the "invoked ARN" directly but replace any\n[alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple\ndifferent aliases.\n* **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names)\n* **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id).\n\nOn some providers, it may not be possible to determine the full ID at startup,\nwhich is why this field cannot be made required. For example, on AWS the account ID\npart of the ARN is not available without calling another AWS API\nwhich may be deemed too slow for a short-running lambda function.\nAs an alternative, consider setting `faas.id` as a span attribute instead.\n*\n* @deprecated Use ATTR_CLOUD_RESOURCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n*/\nexport const SEMRESATTRS_FAAS_ID = TMP_FAAS_ID;\n\n/**\n* The immutable version of the function being executed.\n*\n* Note: Depending on the cloud provider and platform, use:\n\n* **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html)\n (an integer represented as a decimal string).\n* **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions)\n (i.e., the function name plus the revision suffix).\n* **Google Cloud Functions:** The value of the\n [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically).\n* **Azure Functions:** Not applicable. Do not set this attribute.\n*\n* @deprecated Use ATTR_FAAS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n*/\nexport const SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION;\n\n/**\n * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version.\n *\n * Note: * **AWS Lambda:** Use the (full) log stream name.\n *\n * @deprecated Use ATTR_FAAS_INSTANCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE;\n\n/**\n * The amount of memory available to the serverless function in MiB.\n *\n * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information.\n *\n * @deprecated Use ATTR_FAAS_MAX_MEMORY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY;\n\n/**\n * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider.\n *\n * @deprecated Use ATTR_HOST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_ID = TMP_HOST_ID;\n\n/**\n * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user.\n *\n * @deprecated Use ATTR_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_NAME = TMP_HOST_NAME;\n\n/**\n * Type of host. For Cloud, this must be the machine type.\n *\n * @deprecated Use ATTR_HOST_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use ATTR_HOST_ARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH;\n\n/**\n * Name of the VM image or OS install the host was instantiated from.\n *\n * @deprecated Use ATTR_HOST_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME;\n\n/**\n * VM image ID. For Cloud, this value is from the provider.\n *\n * @deprecated Use ATTR_HOST_IMAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID;\n\n/**\n * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes).\n *\n * @deprecated Use ATTR_HOST_IMAGE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION;\n\n/**\n * The name of the cluster.\n *\n * @deprecated Use ATTR_K8S_CLUSTER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME;\n\n/**\n * The name of the Node.\n *\n * @deprecated Use ATTR_K8S_NODE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME;\n\n/**\n * The UID of the Node.\n *\n * @deprecated Use ATTR_K8S_NODE_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID;\n\n/**\n * The name of the namespace that the pod is running in.\n *\n * @deprecated Use ATTR_K8S_NAMESPACE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME;\n\n/**\n * The UID of the Pod.\n *\n * @deprecated Use ATTR_K8S_POD_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID;\n\n/**\n * The name of the Pod.\n *\n * @deprecated Use ATTR_K8S_POD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME;\n\n/**\n * The name of the Container in a Pod template.\n *\n * @deprecated Use ATTR_K8S_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME;\n\n/**\n * The UID of the ReplicaSet.\n *\n * @deprecated Use ATTR_K8S_REPLICASET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID;\n\n/**\n * The name of the ReplicaSet.\n *\n * @deprecated Use ATTR_K8S_REPLICASET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME;\n\n/**\n * The UID of the Deployment.\n *\n * @deprecated Use ATTR_K8S_DEPLOYMENT_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID;\n\n/**\n * The name of the Deployment.\n *\n * @deprecated Use ATTR_K8S_DEPLOYMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME;\n\n/**\n * The UID of the StatefulSet.\n *\n * @deprecated Use ATTR_K8S_STATEFULSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID;\n\n/**\n * The name of the StatefulSet.\n *\n * @deprecated Use ATTR_K8S_STATEFULSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME;\n\n/**\n * The UID of the DaemonSet.\n *\n * @deprecated Use ATTR_K8S_DAEMONSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID;\n\n/**\n * The name of the DaemonSet.\n *\n * @deprecated Use ATTR_K8S_DAEMONSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME;\n\n/**\n * The UID of the Job.\n *\n * @deprecated Use ATTR_K8S_JOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID;\n\n/**\n * The name of the Job.\n *\n * @deprecated Use ATTR_K8S_JOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME;\n\n/**\n * The UID of the CronJob.\n *\n * @deprecated Use ATTR_K8S_CRONJOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID;\n\n/**\n * The name of the CronJob.\n *\n * @deprecated Use ATTR_K8S_CRONJOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME;\n\n/**\n * The operating system type.\n *\n * @deprecated Use ATTR_OS_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_OS_TYPE = TMP_OS_TYPE;\n\n/**\n * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands.\n *\n * @deprecated Use ATTR_OS_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION;\n\n/**\n * Human readable operating system name.\n *\n * @deprecated Use ATTR_OS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_OS_NAME = TMP_OS_NAME;\n\n/**\n * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes).\n *\n * @deprecated Use ATTR_OS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_OS_VERSION = TMP_OS_VERSION;\n\n/**\n * Process identifier (PID).\n *\n * @deprecated Use ATTR_PROCESS_PID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID;\n\n/**\n * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`.\n *\n * @deprecated Use ATTR_PROCESS_EXECUTABLE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME;\n\n/**\n * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`.\n *\n * @deprecated Use ATTR_PROCESS_EXECUTABLE_PATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH;\n\n/**\n * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`.\n *\n * @deprecated Use ATTR_PROCESS_COMMAND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND;\n\n/**\n * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead.\n *\n * @deprecated Use ATTR_PROCESS_COMMAND_LINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE;\n\n/**\n * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`.\n *\n * @deprecated Use ATTR_PROCESS_COMMAND_ARGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS;\n\n/**\n * The username of the user that owns the process.\n *\n * @deprecated Use ATTR_PROCESS_OWNER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER;\n\n/**\n * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler.\n *\n * @deprecated Use ATTR_PROCESS_RUNTIME_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME;\n\n/**\n * The version of the runtime of this process, as returned by the runtime without modification.\n *\n * @deprecated Use ATTR_PROCESS_RUNTIME_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION;\n\n/**\n * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment.\n *\n * @deprecated Use ATTR_PROCESS_RUNTIME_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION =\n TMP_PROCESS_RUNTIME_DESCRIPTION;\n\n/**\n * Logical name of the service.\n *\n * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`.\n *\n * @deprecated Use ATTR_SERVICE_NAME.\n */\nexport const SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME;\n\n/**\n * A namespace for `service.name`.\n *\n * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n *\n * @deprecated Use ATTR_SERVICE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE;\n\n/**\n * The string ID of the service instance.\n *\n * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations).\n *\n * @deprecated Use ATTR_SERVICE_INSTANCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID;\n\n/**\n * The version string of the service API or implementation.\n *\n * @deprecated Use ATTR_SERVICE_VERSION.\n */\nexport const SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @deprecated Use ATTR_TELEMETRY_SDK_NAME.\n */\nexport const SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use ATTR_TELEMETRY_SDK_LANGUAGE.\n */\nexport const SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @deprecated Use ATTR_TELEMETRY_SDK_VERSION.\n */\nexport const SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION;\n\n/**\n * The version string of the auto instrumentation agent, if used.\n *\n * @deprecated Use ATTR_TELEMETRY_DISTRO_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION;\n\n/**\n * The name of the web engine.\n *\n * @deprecated Use ATTR_WEBENGINE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME;\n\n/**\n * The version of the web engine.\n *\n * @deprecated Use ATTR_WEBENGINE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION;\n\n/**\n * Additional description of the web engine (e.g. detailed version and edition information).\n *\n * @deprecated Use ATTR_WEBENGINE_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION;\n\n/**\n * Definition of available values for SemanticResourceAttributes\n * This type is used for backward compatibility, you should use the individual exported\n * constants SemanticResourceAttributes_XXXXX rather than the exported constant map. As any single reference\n * to a constant map value will result in all strings being included into your bundle.\n * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification.\n */\nexport type SemanticResourceAttributes = {\n /**\n * Name of the cloud provider.\n */\n CLOUD_PROVIDER: 'cloud.provider';\n\n /**\n * The cloud account ID the resource is assigned to.\n */\n CLOUD_ACCOUNT_ID: 'cloud.account.id';\n\n /**\n * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations).\n */\n CLOUD_REGION: 'cloud.region';\n\n /**\n * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running.\n *\n * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud.\n */\n CLOUD_AVAILABILITY_ZONE: 'cloud.availability_zone';\n\n /**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n */\n CLOUD_PLATFORM: 'cloud.platform';\n\n /**\n * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html).\n */\n AWS_ECS_CONTAINER_ARN: 'aws.ecs.container.arn';\n\n /**\n * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html).\n */\n AWS_ECS_CLUSTER_ARN: 'aws.ecs.cluster.arn';\n\n /**\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n */\n AWS_ECS_LAUNCHTYPE: 'aws.ecs.launchtype';\n\n /**\n * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html).\n */\n AWS_ECS_TASK_ARN: 'aws.ecs.task.arn';\n\n /**\n * The task definition family this task definition is a member of.\n */\n AWS_ECS_TASK_FAMILY: 'aws.ecs.task.family';\n\n /**\n * The revision for this task definition.\n */\n AWS_ECS_TASK_REVISION: 'aws.ecs.task.revision';\n\n /**\n * The ARN of an EKS cluster.\n */\n AWS_EKS_CLUSTER_ARN: 'aws.eks.cluster.arn';\n\n /**\n * The name(s) of the AWS log group(s) an application is writing to.\n *\n * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group.\n */\n AWS_LOG_GROUP_NAMES: 'aws.log.group.names';\n\n /**\n * The Amazon Resource Name(s) (ARN) of the AWS log group(s).\n *\n * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format).\n */\n AWS_LOG_GROUP_ARNS: 'aws.log.group.arns';\n\n /**\n * The name(s) of the AWS log stream(s) an application is writing to.\n */\n AWS_LOG_STREAM_NAMES: 'aws.log.stream.names';\n\n /**\n * The ARN(s) of the AWS log stream(s).\n *\n * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream.\n */\n AWS_LOG_STREAM_ARNS: 'aws.log.stream.arns';\n\n /**\n * Container name.\n */\n CONTAINER_NAME: 'container.name';\n\n /**\n * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated.\n */\n CONTAINER_ID: 'container.id';\n\n /**\n * The container runtime managing this container.\n */\n CONTAINER_RUNTIME: 'container.runtime';\n\n /**\n * Name of the image the container was built on.\n */\n CONTAINER_IMAGE_NAME: 'container.image.name';\n\n /**\n * Container image tag.\n */\n CONTAINER_IMAGE_TAG: 'container.image.tag';\n\n /**\n * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier).\n */\n DEPLOYMENT_ENVIRONMENT: 'deployment.environment';\n\n /**\n * A unique identifier representing the device.\n *\n * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence.\n */\n DEVICE_ID: 'device.id';\n\n /**\n * The model identifier for the device.\n *\n * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device.\n */\n DEVICE_MODEL_IDENTIFIER: 'device.model.identifier';\n\n /**\n * The marketing name for the device model.\n *\n * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative.\n */\n DEVICE_MODEL_NAME: 'device.model.name';\n\n /**\n * The name of the single function that this runtime instance executes.\n *\n * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes).\n */\n FAAS_NAME: 'faas.name';\n\n /**\n * The unique ID of the single function that this runtime instance executes.\n *\n * Note: Depending on the cloud provider, use:\n\n* **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html).\nTake care not to use the "invoked ARN" directly but replace any\n[alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple\ndifferent aliases.\n* **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names)\n* **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id).\n\nOn some providers, it may not be possible to determine the full ID at startup,\nwhich is why this field cannot be made required. For example, on AWS the account ID\npart of the ARN is not available without calling another AWS API\nwhich may be deemed too slow for a short-running lambda function.\nAs an alternative, consider setting `faas.id` as a span attribute instead.\n */\n FAAS_ID: 'faas.id';\n\n /**\n * The immutable version of the function being executed.\n *\n * Note: Depending on the cloud provider and platform, use:\n\n* **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html)\n (an integer represented as a decimal string).\n* **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions)\n (i.e., the function name plus the revision suffix).\n* **Google Cloud Functions:** The value of the\n [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically).\n* **Azure Functions:** Not applicable. Do not set this attribute.\n */\n FAAS_VERSION: 'faas.version';\n\n /**\n * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version.\n *\n * Note: * **AWS Lambda:** Use the (full) log stream name.\n */\n FAAS_INSTANCE: 'faas.instance';\n\n /**\n * The amount of memory available to the serverless function in MiB.\n *\n * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information.\n */\n FAAS_MAX_MEMORY: 'faas.max_memory';\n\n /**\n * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider.\n */\n HOST_ID: 'host.id';\n\n /**\n * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user.\n */\n HOST_NAME: 'host.name';\n\n /**\n * Type of host. For Cloud, this must be the machine type.\n */\n HOST_TYPE: 'host.type';\n\n /**\n * The CPU architecture the host system is running on.\n */\n HOST_ARCH: 'host.arch';\n\n /**\n * Name of the VM image or OS install the host was instantiated from.\n */\n HOST_IMAGE_NAME: 'host.image.name';\n\n /**\n * VM image ID. For Cloud, this value is from the provider.\n */\n HOST_IMAGE_ID: 'host.image.id';\n\n /**\n * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes).\n */\n HOST_IMAGE_VERSION: 'host.image.version';\n\n /**\n * The name of the cluster.\n */\n K8S_CLUSTER_NAME: 'k8s.cluster.name';\n\n /**\n * The name of the Node.\n */\n K8S_NODE_NAME: 'k8s.node.name';\n\n /**\n * The UID of the Node.\n */\n K8S_NODE_UID: 'k8s.node.uid';\n\n /**\n * The name of the namespace that the pod is running in.\n */\n K8S_NAMESPACE_NAME: 'k8s.namespace.name';\n\n /**\n * The UID of the Pod.\n */\n K8S_POD_UID: 'k8s.pod.uid';\n\n /**\n * The name of the Pod.\n */\n K8S_POD_NAME: 'k8s.pod.name';\n\n /**\n * The name of the Container in a Pod template.\n */\n K8S_CONTAINER_NAME: 'k8s.container.name';\n\n /**\n * The UID of the ReplicaSet.\n */\n K8S_REPLICASET_UID: 'k8s.replicaset.uid';\n\n /**\n * The name of the ReplicaSet.\n */\n K8S_REPLICASET_NAME: 'k8s.replicaset.name';\n\n /**\n * The UID of the Deployment.\n */\n K8S_DEPLOYMENT_UID: 'k8s.deployment.uid';\n\n /**\n * The name of the Deployment.\n */\n K8S_DEPLOYMENT_NAME: 'k8s.deployment.name';\n\n /**\n * The UID of the StatefulSet.\n */\n K8S_STATEFULSET_UID: 'k8s.statefulset.uid';\n\n /**\n * The name of the StatefulSet.\n */\n K8S_STATEFULSET_NAME: 'k8s.statefulset.name';\n\n /**\n * The UID of the DaemonSet.\n */\n K8S_DAEMONSET_UID: 'k8s.daemonset.uid';\n\n /**\n * The name of the DaemonSet.\n */\n K8S_DAEMONSET_NAME: 'k8s.daemonset.name';\n\n /**\n * The UID of the Job.\n */\n K8S_JOB_UID: 'k8s.job.uid';\n\n /**\n * The name of the Job.\n */\n K8S_JOB_NAME: 'k8s.job.name';\n\n /**\n * The UID of the CronJob.\n */\n K8S_CRONJOB_UID: 'k8s.cronjob.uid';\n\n /**\n * The name of the CronJob.\n */\n K8S_CRONJOB_NAME: 'k8s.cronjob.name';\n\n /**\n * The operating system type.\n */\n OS_TYPE: 'os.type';\n\n /**\n * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands.\n */\n OS_DESCRIPTION: 'os.description';\n\n /**\n * Human readable operating system name.\n */\n OS_NAME: 'os.name';\n\n /**\n * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes).\n */\n OS_VERSION: 'os.version';\n\n /**\n * Process identifier (PID).\n */\n PROCESS_PID: 'process.pid';\n\n /**\n * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`.\n */\n PROCESS_EXECUTABLE_NAME: 'process.executable.name';\n\n /**\n * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`.\n */\n PROCESS_EXECUTABLE_PATH: 'process.executable.path';\n\n /**\n * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`.\n */\n PROCESS_COMMAND: 'process.command';\n\n /**\n * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead.\n */\n PROCESS_COMMAND_LINE: 'process.command_line';\n\n /**\n * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`.\n */\n PROCESS_COMMAND_ARGS: 'process.command_args';\n\n /**\n * The username of the user that owns the process.\n */\n PROCESS_OWNER: 'process.owner';\n\n /**\n * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler.\n */\n PROCESS_RUNTIME_NAME: 'process.runtime.name';\n\n /**\n * The version of the runtime of this process, as returned by the runtime without modification.\n */\n PROCESS_RUNTIME_VERSION: 'process.runtime.version';\n\n /**\n * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment.\n */\n PROCESS_RUNTIME_DESCRIPTION: 'process.runtime.description';\n\n /**\n * Logical name of the service.\n *\n * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`.\n */\n SERVICE_NAME: 'service.name';\n\n /**\n * A namespace for `service.name`.\n *\n * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\n SERVICE_NAMESPACE: 'service.namespace';\n\n /**\n * The string ID of the service instance.\n *\n * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations).\n */\n SERVICE_INSTANCE_ID: 'service.instance.id';\n\n /**\n * The version string of the service API or implementation.\n */\n SERVICE_VERSION: 'service.version';\n\n /**\n * The name of the telemetry SDK as defined above.\n */\n TELEMETRY_SDK_NAME: 'telemetry.sdk.name';\n\n /**\n * The language of the telemetry SDK.\n */\n TELEMETRY_SDK_LANGUAGE: 'telemetry.sdk.language';\n\n /**\n * The version string of the telemetry SDK.\n */\n TELEMETRY_SDK_VERSION: 'telemetry.sdk.version';\n\n /**\n * The version string of the auto instrumentation agent, if used.\n */\n TELEMETRY_AUTO_VERSION: 'telemetry.auto.version';\n\n /**\n * The name of the web engine.\n */\n WEBENGINE_NAME: 'webengine.name';\n\n /**\n * The version of the web engine.\n */\n WEBENGINE_VERSION: 'webengine.version';\n\n /**\n * Additional description of the web engine (e.g. detailed version and edition information).\n */\n WEBENGINE_DESCRIPTION: 'webengine.description';\n};\n\n/**\n * Create exported Value Map for SemanticResourceAttributes values\n * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification\n */\nexport const SemanticResourceAttributes: SemanticResourceAttributes =\n /*#__PURE__*/ createConstMap([\n TMP_CLOUD_PROVIDER,\n TMP_CLOUD_ACCOUNT_ID,\n TMP_CLOUD_REGION,\n TMP_CLOUD_AVAILABILITY_ZONE,\n TMP_CLOUD_PLATFORM,\n TMP_AWS_ECS_CONTAINER_ARN,\n TMP_AWS_ECS_CLUSTER_ARN,\n TMP_AWS_ECS_LAUNCHTYPE,\n TMP_AWS_ECS_TASK_ARN,\n TMP_AWS_ECS_TASK_FAMILY,\n TMP_AWS_ECS_TASK_REVISION,\n TMP_AWS_EKS_CLUSTER_ARN,\n TMP_AWS_LOG_GROUP_NAMES,\n TMP_AWS_LOG_GROUP_ARNS,\n TMP_AWS_LOG_STREAM_NAMES,\n TMP_AWS_LOG_STREAM_ARNS,\n TMP_CONTAINER_NAME,\n TMP_CONTAINER_ID,\n TMP_CONTAINER_RUNTIME,\n TMP_CONTAINER_IMAGE_NAME,\n TMP_CONTAINER_IMAGE_TAG,\n TMP_DEPLOYMENT_ENVIRONMENT,\n TMP_DEVICE_ID,\n TMP_DEVICE_MODEL_IDENTIFIER,\n TMP_DEVICE_MODEL_NAME,\n TMP_FAAS_NAME,\n TMP_FAAS_ID,\n TMP_FAAS_VERSION,\n TMP_FAAS_INSTANCE,\n TMP_FAAS_MAX_MEMORY,\n TMP_HOST_ID,\n TMP_HOST_NAME,\n TMP_HOST_TYPE,\n TMP_HOST_ARCH,\n TMP_HOST_IMAGE_NAME,\n TMP_HOST_IMAGE_ID,\n TMP_HOST_IMAGE_VERSION,\n TMP_K8S_CLUSTER_NAME,\n TMP_K8S_NODE_NAME,\n TMP_K8S_NODE_UID,\n TMP_K8S_NAMESPACE_NAME,\n TMP_K8S_POD_UID,\n TMP_K8S_POD_NAME,\n TMP_K8S_CONTAINER_NAME,\n TMP_K8S_REPLICASET_UID,\n TMP_K8S_REPLICASET_NAME,\n TMP_K8S_DEPLOYMENT_UID,\n TMP_K8S_DEPLOYMENT_NAME,\n TMP_K8S_STATEFULSET_UID,\n TMP_K8S_STATEFULSET_NAME,\n TMP_K8S_DAEMONSET_UID,\n TMP_K8S_DAEMONSET_NAME,\n TMP_K8S_JOB_UID,\n TMP_K8S_JOB_NAME,\n TMP_K8S_CRONJOB_UID,\n TMP_K8S_CRONJOB_NAME,\n TMP_OS_TYPE,\n TMP_OS_DESCRIPTION,\n TMP_OS_NAME,\n TMP_OS_VERSION,\n TMP_PROCESS_PID,\n TMP_PROCESS_EXECUTABLE_NAME,\n TMP_PROCESS_EXECUTABLE_PATH,\n TMP_PROCESS_COMMAND,\n TMP_PROCESS_COMMAND_LINE,\n TMP_PROCESS_COMMAND_ARGS,\n TMP_PROCESS_OWNER,\n TMP_PROCESS_RUNTIME_NAME,\n TMP_PROCESS_RUNTIME_VERSION,\n TMP_PROCESS_RUNTIME_DESCRIPTION,\n TMP_SERVICE_NAME,\n TMP_SERVICE_NAMESPACE,\n TMP_SERVICE_INSTANCE_ID,\n TMP_SERVICE_VERSION,\n TMP_TELEMETRY_SDK_NAME,\n TMP_TELEMETRY_SDK_LANGUAGE,\n TMP_TELEMETRY_SDK_VERSION,\n TMP_TELEMETRY_AUTO_VERSION,\n TMP_WEBENGINE_NAME,\n TMP_WEBENGINE_VERSION,\n TMP_WEBENGINE_DESCRIPTION,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for CloudProviderValues enum definition\n *\n * Name of the cloud provider.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud';\nconst TMP_CLOUDPROVIDERVALUES_AWS = 'aws';\nconst TMP_CLOUDPROVIDERVALUES_AZURE = 'azure';\nconst TMP_CLOUDPROVIDERVALUES_GCP = 'gcp';\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use CLOUD_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPROVIDERVALUES_ALIBABA_CLOUD =\n TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD;\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use CLOUD_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS;\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use CLOUD_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE;\n\n/**\n * Name of the cloud provider.\n *\n * @deprecated Use CLOUD_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP;\n\n/**\n * Identifies the Values for CloudProviderValues enum definition\n *\n * Name of the cloud provider.\n * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification.\n */\nexport type CloudProviderValues = {\n /** Alibaba Cloud. */\n ALIBABA_CLOUD: 'alibaba_cloud';\n\n /** Amazon Web Services. */\n AWS: 'aws';\n\n /** Microsoft Azure. */\n AZURE: 'azure';\n\n /** Google Cloud Platform. */\n GCP: 'gcp';\n};\n\n/**\n * The constant map of values for CloudProviderValues.\n * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification.\n */\nexport const CloudProviderValues: CloudProviderValues =\n /*#__PURE__*/ createConstMap([\n TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,\n TMP_CLOUDPROVIDERVALUES_AWS,\n TMP_CLOUDPROVIDERVALUES_AZURE,\n TMP_CLOUDPROVIDERVALUES_GCP,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for CloudPlatformValues enum definition\n *\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = 'alibaba_cloud_ecs';\nconst TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = 'alibaba_cloud_fc';\nconst TMP_CLOUDPLATFORMVALUES_AWS_EC2 = 'aws_ec2';\nconst TMP_CLOUDPLATFORMVALUES_AWS_ECS = 'aws_ecs';\nconst TMP_CLOUDPLATFORMVALUES_AWS_EKS = 'aws_eks';\nconst TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = 'aws_lambda';\nconst TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = 'aws_elastic_beanstalk';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_VM = 'azure_vm';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES =\n 'azure_container_instances';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_AKS = 'azure_aks';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = 'azure_functions';\nconst TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = 'azure_app_service';\nconst TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = 'gcp_compute_engine';\nconst TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = 'gcp_cloud_run';\nconst TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = 'gcp_kubernetes_engine';\nconst TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = 'gcp_cloud_functions';\nconst TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = 'gcp_app_engine';\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS =\n TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_FC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC =\n TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_LAMBDA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_LAMBDA =\n TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ELASTIC_BEANSTALK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK =\n TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_VM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_CONTAINER_INSTANCES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES =\n TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_AKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_FUNCTIONS =\n TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_APP_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_AZURE_APP_SERVICE =\n TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_COMPUTE_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE =\n TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_RUN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_CLOUD_RUN =\n TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_KUBERNETES_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE =\n TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS =\n TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS;\n\n/**\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n *\n * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_APP_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const CLOUDPLATFORMVALUES_GCP_APP_ENGINE =\n TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE;\n\n/**\n * Identifies the Values for CloudPlatformValues enum definition\n *\n * The cloud platform in use.\n *\n * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`.\n * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification.\n */\nexport type CloudPlatformValues = {\n /** Alibaba Cloud Elastic Compute Service. */\n ALIBABA_CLOUD_ECS: 'alibaba_cloud_ecs';\n\n /** Alibaba Cloud Function Compute. */\n ALIBABA_CLOUD_FC: 'alibaba_cloud_fc';\n\n /** AWS Elastic Compute Cloud. */\n AWS_EC2: 'aws_ec2';\n\n /** AWS Elastic Container Service. */\n AWS_ECS: 'aws_ecs';\n\n /** AWS Elastic Kubernetes Service. */\n AWS_EKS: 'aws_eks';\n\n /** AWS Lambda. */\n AWS_LAMBDA: 'aws_lambda';\n\n /** AWS Elastic Beanstalk. */\n AWS_ELASTIC_BEANSTALK: 'aws_elastic_beanstalk';\n\n /** Azure Virtual Machines. */\n AZURE_VM: 'azure_vm';\n\n /** Azure Container Instances. */\n AZURE_CONTAINER_INSTANCES: 'azure_container_instances';\n\n /** Azure Kubernetes Service. */\n AZURE_AKS: 'azure_aks';\n\n /** Azure Functions. */\n AZURE_FUNCTIONS: 'azure_functions';\n\n /** Azure App Service. */\n AZURE_APP_SERVICE: 'azure_app_service';\n\n /** Google Cloud Compute Engine (GCE). */\n GCP_COMPUTE_ENGINE: 'gcp_compute_engine';\n\n /** Google Cloud Run. */\n GCP_CLOUD_RUN: 'gcp_cloud_run';\n\n /** Google Cloud Kubernetes Engine (GKE). */\n GCP_KUBERNETES_ENGINE: 'gcp_kubernetes_engine';\n\n /** Google Cloud Functions (GCF). */\n GCP_CLOUD_FUNCTIONS: 'gcp_cloud_functions';\n\n /** Google Cloud App Engine (GAE). */\n GCP_APP_ENGINE: 'gcp_app_engine';\n};\n\n/**\n * The constant map of values for CloudPlatformValues.\n * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification.\n */\nexport const CloudPlatformValues: CloudPlatformValues =\n /*#__PURE__*/ createConstMap([\n TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,\n TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,\n TMP_CLOUDPLATFORMVALUES_AWS_EC2,\n TMP_CLOUDPLATFORMVALUES_AWS_ECS,\n TMP_CLOUDPLATFORMVALUES_AWS_EKS,\n TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,\n TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,\n TMP_CLOUDPLATFORMVALUES_AZURE_VM,\n TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,\n TMP_CLOUDPLATFORMVALUES_AZURE_AKS,\n TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,\n TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,\n TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,\n TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,\n TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,\n TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,\n TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for AwsEcsLaunchtypeValues enum definition\n *\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_AWSECSLAUNCHTYPEVALUES_EC2 = 'ec2';\nconst TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = 'fargate';\n\n/**\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n *\n * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2;\n\n/**\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n *\n * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_FARGATE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const AWSECSLAUNCHTYPEVALUES_FARGATE =\n TMP_AWSECSLAUNCHTYPEVALUES_FARGATE;\n\n/**\n * Identifies the Values for AwsEcsLaunchtypeValues enum definition\n *\n * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task.\n * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification.\n */\nexport type AwsEcsLaunchtypeValues = {\n /** ec2. */\n EC2: 'ec2';\n\n /** fargate. */\n FARGATE: 'fargate';\n};\n\n/**\n * The constant map of values for AwsEcsLaunchtypeValues.\n * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification.\n */\nexport const AwsEcsLaunchtypeValues: AwsEcsLaunchtypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_AWSECSLAUNCHTYPEVALUES_EC2,\n TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for HostArchValues enum definition\n *\n * The CPU architecture the host system is running on.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_HOSTARCHVALUES_AMD64 = 'amd64';\nconst TMP_HOSTARCHVALUES_ARM32 = 'arm32';\nconst TMP_HOSTARCHVALUES_ARM64 = 'arm64';\nconst TMP_HOSTARCHVALUES_IA64 = 'ia64';\nconst TMP_HOSTARCHVALUES_PPC32 = 'ppc32';\nconst TMP_HOSTARCHVALUES_PPC64 = 'ppc64';\nconst TMP_HOSTARCHVALUES_X86 = 'x86';\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_AMD64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_ARM32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_ARM64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_IA64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_PPC32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_PPC64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @deprecated Use HOST_ARCH_VALUE_X86 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86;\n\n/**\n * Identifies the Values for HostArchValues enum definition\n *\n * The CPU architecture the host system is running on.\n * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification.\n */\nexport type HostArchValues = {\n /** AMD64. */\n AMD64: 'amd64';\n\n /** ARM32. */\n ARM32: 'arm32';\n\n /** ARM64. */\n ARM64: 'arm64';\n\n /** Itanium. */\n IA64: 'ia64';\n\n /** 32-bit PowerPC. */\n PPC32: 'ppc32';\n\n /** 64-bit PowerPC. */\n PPC64: 'ppc64';\n\n /** 32-bit x86. */\n X86: 'x86';\n};\n\n/**\n * The constant map of values for HostArchValues.\n * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification.\n */\nexport const HostArchValues: HostArchValues =\n /*#__PURE__*/ createConstMap([\n TMP_HOSTARCHVALUES_AMD64,\n TMP_HOSTARCHVALUES_ARM32,\n TMP_HOSTARCHVALUES_ARM64,\n TMP_HOSTARCHVALUES_IA64,\n TMP_HOSTARCHVALUES_PPC32,\n TMP_HOSTARCHVALUES_PPC64,\n TMP_HOSTARCHVALUES_X86,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for OsTypeValues enum definition\n *\n * The operating system type.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_OSTYPEVALUES_WINDOWS = 'windows';\nconst TMP_OSTYPEVALUES_LINUX = 'linux';\nconst TMP_OSTYPEVALUES_DARWIN = 'darwin';\nconst TMP_OSTYPEVALUES_FREEBSD = 'freebsd';\nconst TMP_OSTYPEVALUES_NETBSD = 'netbsd';\nconst TMP_OSTYPEVALUES_OPENBSD = 'openbsd';\nconst TMP_OSTYPEVALUES_DRAGONFLYBSD = 'dragonflybsd';\nconst TMP_OSTYPEVALUES_HPUX = 'hpux';\nconst TMP_OSTYPEVALUES_AIX = 'aix';\nconst TMP_OSTYPEVALUES_SOLARIS = 'solaris';\nconst TMP_OSTYPEVALUES_Z_OS = 'z_os';\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_WINDOWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_LINUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_DARWIN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_FREEBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_NETBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_OPENBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_DRAGONFLYBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_HPUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_AIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_SOLARIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS;\n\n/**\n * The operating system type.\n *\n * @deprecated Use OS_TYPE_VALUE_Z_OS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}).\n */\nexport const OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS;\n\n/**\n * Identifies the Values for OsTypeValues enum definition\n *\n * The operating system type.\n * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification.\n */\nexport type OsTypeValues = {\n /** Microsoft Windows. */\n WINDOWS: 'windows';\n\n /** Linux. */\n LINUX: 'linux';\n\n /** Apple Darwin. */\n DARWIN: 'darwin';\n\n /** FreeBSD. */\n FREEBSD: 'freebsd';\n\n /** NetBSD. */\n NETBSD: 'netbsd';\n\n /** OpenBSD. */\n OPENBSD: 'openbsd';\n\n /** DragonFly BSD. */\n DRAGONFLYBSD: 'dragonflybsd';\n\n /** HP-UX (Hewlett Packard Unix). */\n HPUX: 'hpux';\n\n /** AIX (Advanced Interactive eXecutive). */\n AIX: 'aix';\n\n /** Oracle Solaris. */\n SOLARIS: 'solaris';\n\n /** IBM z/OS. */\n Z_OS: 'z_os';\n};\n\n/**\n * The constant map of values for OsTypeValues.\n * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification.\n */\nexport const OsTypeValues: OsTypeValues =\n /*#__PURE__*/ createConstMap([\n TMP_OSTYPEVALUES_WINDOWS,\n TMP_OSTYPEVALUES_LINUX,\n TMP_OSTYPEVALUES_DARWIN,\n TMP_OSTYPEVALUES_FREEBSD,\n TMP_OSTYPEVALUES_NETBSD,\n TMP_OSTYPEVALUES_OPENBSD,\n TMP_OSTYPEVALUES_DRAGONFLYBSD,\n TMP_OSTYPEVALUES_HPUX,\n TMP_OSTYPEVALUES_AIX,\n TMP_OSTYPEVALUES_SOLARIS,\n TMP_OSTYPEVALUES_Z_OS,\n ]);\n\n/* ----------------------------------------------------------------------------------------------------------\n * Constant values for TelemetrySdkLanguageValues enum definition\n *\n * The language of the telemetry SDK.\n * ---------------------------------------------------------------------------------------------------------- */\n\n// Temporary local constants to assign to the individual exports and the namespaced version\n// Required to avoid the namespace exports using the unminifiable export names for some package types\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = 'cpp';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = 'dotnet';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = 'erlang';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_GO = 'go';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = 'java';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = 'nodejs';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = 'php';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = 'python';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = 'ruby';\nconst TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = 'webjs';\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_CPP.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_CPP =\n TMP_TELEMETRYSDKLANGUAGEVALUES_CPP;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_DOTNET =\n TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_ERLANG =\n TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_GO.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_JAVA.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_JAVA =\n TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_NODEJS =\n TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PHP.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_PHP =\n TMP_TELEMETRYSDKLANGUAGEVALUES_PHP;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_PYTHON =\n TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_RUBY.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_RUBY =\n TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY;\n\n/**\n * The language of the telemetry SDK.\n *\n * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS.\n */\nexport const TELEMETRYSDKLANGUAGEVALUES_WEBJS =\n TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS;\n\n/**\n * Identifies the Values for TelemetrySdkLanguageValues enum definition\n *\n * The language of the telemetry SDK.\n * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification.\n */\nexport type TelemetrySdkLanguageValues = {\n /** cpp. */\n CPP: 'cpp';\n\n /** dotnet. */\n DOTNET: 'dotnet';\n\n /** erlang. */\n ERLANG: 'erlang';\n\n /** go. */\n GO: 'go';\n\n /** java. */\n JAVA: 'java';\n\n /** nodejs. */\n NODEJS: 'nodejs';\n\n /** php. */\n PHP: 'php';\n\n /** python. */\n PYTHON: 'python';\n\n /** ruby. */\n RUBY: 'ruby';\n\n /** webjs. */\n WEBJS: 'webjs';\n};\n\n/**\n * The constant map of values for TelemetrySdkLanguageValues.\n * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification.\n */\nexport const TelemetrySdkLanguageValues: TelemetrySdkLanguageValues =\n /*#__PURE__*/ createConstMap([\n TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,\n TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,\n TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,\n TMP_TELEMETRYSDKLANGUAGEVALUES_GO,\n TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,\n TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,\n TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,\n TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,\n TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,\n TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,\n ]);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable no-restricted-syntax --\n * These re-exports are only of constants, only one-level deep at this point,\n * and should not cause problems for tree-shakers.\n */\nexport * from './SemanticResourceAttributes';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result' as const;\n\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\" as const;\n\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\" as const;\n\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\" as const;\n\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\" as const;\n\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type' as const;\n\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy' as const;\n\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result' as const;\n\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\" as const;\n\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\" as const;\n\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\" as const;\n\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\" as const;\n\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled' as const;\n\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback' as const;\n\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status' as const;\n\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\" as const;\n\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\" as const;\n\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated' as const;\n\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address' as const;\n\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port' as const;\n\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number' as const;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path' as const;\n\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n * - Java method: `com.example.MyHttpService.serveRequest`\n * - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n * - PHP function: `GuzzleHttp\\Client::transfer`\n * - Go function: `github.com/my/repo/pkg.foo.func5`\n * - Elixir: `OpenTelemetry.Ctx.new`\n * - Erlang: `opentelemetry_ctx:new`\n * - Rust: `playground::my_module::my_cool_func`\n * - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name' as const;\n\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace' as const;\n\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name' as const;\n\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace' as const;\n\n/**\n * The number of queries included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size' as const;\n\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name' as const;\n\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query)\n * section.\n *\n * For batch operations, if the individual operations are known to have the same query summary\n * then that query summary **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary' as const;\n\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text' as const;\n\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code' as const;\n\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name' as const;\n\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name' as const;\n\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\" as const;\n\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\" as const;\n\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\" as const;\n\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\" as const;\n\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation' as const;\n\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\" as const;\n\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\" as const;\n\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\" as const;\n\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\" as const;\n\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\" as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped' as const;\n\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n *\n * @note > [!WARNING]\n *\n * > This attribute may contain sensitive information.\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace' as const;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type' as const;\n\n/**\n * HTTP request headers, `` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n * attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key: string) => `http.request.header.${key}`;\n\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods.\n *\n *\n * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property\n * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or\n * `.instrumentation/development.general.http.server`.\n *\n * In either case, this list **MUST** be a full override of the default known methods,\n * it is not a list of known methods in addition to the defaults.\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\" as const;\n\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\" as const;\n\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\" as const;\n\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\" as const;\n\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\" as const;\n\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\" as const;\n\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\" as const;\n\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\" as const;\n\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\" as const;\n\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original' as const;\n\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count' as const;\n\n/**\n * HTTP response headers, `` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n * attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key: string) => `http.response.header.${key}`;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code' as const;\n\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route' as const;\n\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action' as const;\n\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name' as const;\n\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name' as const;\n\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type' as const;\n\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\" as const;\n\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\" as const;\n\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon' as const;\n\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state' as const;\n\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\" as const;\n\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\" as const;\n\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\" as const;\n\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\" as const;\n\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\" as const;\n\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\" as const;\n\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address' as const;\n\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port' as const;\n\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address' as const;\n\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port' as const;\n\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name' as const;\n\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version' as const;\n\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport' as const;\n\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\" as const;\n\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\" as const;\n\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\" as const;\n\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\" as const;\n\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\" as const;\n\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type' as const;\n\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\" as const;\n\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\" as const;\n\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name' as const;\n\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version' as const;\n\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code' as const;\n\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\" as const;\n\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\" as const;\n\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description' as const;\n\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address' as const;\n\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port' as const;\n\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id' as const;\n\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`.\n */\nexport const ATTR_SERVICE_NAME = 'service.name' as const;\n\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace' as const;\n\n/**\n * The version string of the service component. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version' as const;\n\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status' as const;\n\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\" as const;\n\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\" as const;\n\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\" as const;\n\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport' as const;\n\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\" as const;\n\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\" as const;\n\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\" as const;\n\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language' as const;\n\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\" as const;\n\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\" as const;\n\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\" as const;\n\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\" as const;\n\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\" as const;\n\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\" as const;\n\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\" as const;\n\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\" as const;\n\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\" as const;\n\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\" as const;\n\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\" as const;\n\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\" as const;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name' as const;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version' as const;\n\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment' as const;\n\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full' as const;\n\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path' as const;\n\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query' as const;\n\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme' as const;\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original' as const;\n\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/register/stable/metrics.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * Number of exceptions caught by exception handling middleware.\n *\n * @note Meter name: `Microsoft.AspNetCore.Diagnostics`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = 'aspnetcore.diagnostics.exceptions' as const;\n\n/**\n * Number of requests that are currently active on the server that hold a rate limiting lease.\n *\n * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = 'aspnetcore.rate_limiting.active_request_leases' as const;\n\n/**\n * Number of requests that are currently queued, waiting to acquire a rate limiting lease.\n *\n * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = 'aspnetcore.rate_limiting.queued_requests' as const;\n\n/**\n * The time the request spent in a queue waiting to acquire a rate limiting lease.\n *\n * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = 'aspnetcore.rate_limiting.request.time_in_queue' as const;\n\n/**\n * The duration of rate limiting lease held by requests on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = 'aspnetcore.rate_limiting.request_lease.duration' as const;\n\n/**\n * Number of requests that tried to acquire a rate limiting lease.\n *\n * @note Requests could be:\n *\n * - Rejected by global or endpoint rate limiting policies\n * - Canceled while waiting for the lease.\n *\n * Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = 'aspnetcore.rate_limiting.requests' as const;\n\n/**\n * Number of requests that were attempted to be matched to an endpoint.\n *\n * @note Meter name: `Microsoft.AspNetCore.Routing`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = 'aspnetcore.routing.match_attempts' as const;\n\n/**\n * Duration of database client operations.\n *\n * @note Batch operations **SHOULD** be recorded as a single operation.\n */\nexport const METRIC_DB_CLIENT_OPERATION_DURATION = 'db.client.operation.duration' as const;\n\n/**\n * The number of .NET assemblies that are currently loaded.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`AppDomain.CurrentDomain.GetAssemblies().Length`](https://learn.microsoft.com/dotnet/api/system.appdomain.getassemblies).\n */\nexport const METRIC_DOTNET_ASSEMBLY_COUNT = 'dotnet.assembly.count' as const;\n\n/**\n * The number of exceptions that have been thrown in managed code.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as counting calls to [`AppDomain.CurrentDomain.FirstChanceException`](https://learn.microsoft.com/dotnet/api/system.appdomain.firstchanceexception).\n */\nexport const METRIC_DOTNET_EXCEPTIONS = 'dotnet.exceptions' as const;\n\n/**\n * The number of garbage collections that have occurred since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric uses the [`GC.CollectionCount(int generation)`](https://learn.microsoft.com/dotnet/api/system.gc.collectioncount) API to calculate exclusive collections per generation.\n */\nexport const METRIC_DOTNET_GC_COLLECTIONS = 'dotnet.gc.collections' as const;\n\n/**\n * The *approximate* number of bytes allocated on the managed GC heap since the process has started. The returned value does not include any native allocations.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetTotalAllocatedBytes()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalallocatedbytes).\n */\nexport const METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = 'dotnet.gc.heap.total_allocated' as const;\n\n/**\n * The heap fragmentation, as observed during the latest garbage collection.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.FragmentationAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.fragmentationafterbytes).\n */\nexport const METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = 'dotnet.gc.last_collection.heap.fragmentation.size' as const;\n\n/**\n * The managed GC heap size (including fragmentation), as observed during the latest garbage collection.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.SizeAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.sizeafterbytes).\n */\nexport const METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = 'dotnet.gc.last_collection.heap.size' as const;\n\n/**\n * The amount of committed virtual memory in use by the .NET GC, as observed during the latest garbage collection.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetGCMemoryInfo().TotalCommittedBytes`](https://learn.microsoft.com/dotnet/api/system.gcmemoryinfo.totalcommittedbytes). Committed virtual memory may be larger than the heap size because it includes both memory for storing existing objects (the heap size) and some extra memory that is ready to handle newly allocated objects in the future.\n */\nexport const METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = 'dotnet.gc.last_collection.memory.committed_size' as const;\n\n/**\n * The total amount of time paused in GC since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`GC.GetTotalPauseDuration()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalpauseduration).\n */\nexport const METRIC_DOTNET_GC_PAUSE_TIME = 'dotnet.gc.pause.time' as const;\n\n/**\n * The amount of time the JIT compiler has spent compiling methods since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`JitInfo.GetCompilationTime()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompilationtime).\n */\nexport const METRIC_DOTNET_JIT_COMPILATION_TIME = 'dotnet.jit.compilation.time' as const;\n\n/**\n * Count of bytes of intermediate language that have been compiled since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`JitInfo.GetCompiledILBytes()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledilbytes).\n */\nexport const METRIC_DOTNET_JIT_COMPILED_IL_SIZE = 'dotnet.jit.compiled_il.size' as const;\n\n/**\n * The number of times the JIT compiler (re)compiled methods since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`JitInfo.GetCompiledMethodCount()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledmethodcount).\n */\nexport const METRIC_DOTNET_JIT_COMPILED_METHODS = 'dotnet.jit.compiled_methods' as const;\n\n/**\n * The number of times there was contention when trying to acquire a monitor lock since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`Monitor.LockContentionCount`](https://learn.microsoft.com/dotnet/api/system.threading.monitor.lockcontentioncount).\n */\nexport const METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = 'dotnet.monitor.lock_contentions' as const;\n\n/**\n * The number of processors available to the process.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as accessing [`Environment.ProcessorCount`](https://learn.microsoft.com/dotnet/api/system.environment.processorcount).\n */\nexport const METRIC_DOTNET_PROCESS_CPU_COUNT = 'dotnet.process.cpu.count' as const;\n\n/**\n * CPU time used by the process.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as accessing the corresponding processor time properties on [`System.Diagnostics.Process`](https://learn.microsoft.com/dotnet/api/system.diagnostics.process).\n */\nexport const METRIC_DOTNET_PROCESS_CPU_TIME = 'dotnet.process.cpu.time' as const;\n\n/**\n * The number of bytes of physical memory mapped to the process context.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`Environment.WorkingSet`](https://learn.microsoft.com/dotnet/api/system.environment.workingset).\n */\nexport const METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = 'dotnet.process.memory.working_set' as const;\n\n/**\n * The number of work items that are currently queued to be processed by the thread pool.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`ThreadPool.PendingWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.pendingworkitemcount).\n */\nexport const METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = 'dotnet.thread_pool.queue.length' as const;\n\n/**\n * The number of thread pool threads that currently exist.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`ThreadPool.ThreadCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.threadcount).\n */\nexport const METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = 'dotnet.thread_pool.thread.count' as const;\n\n/**\n * The number of work items that the thread pool has completed since the process has started.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`ThreadPool.CompletedWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.completedworkitemcount).\n */\nexport const METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = 'dotnet.thread_pool.work_item.count' as const;\n\n/**\n * The number of timer instances that are currently active.\n *\n * @note Meter name: `System.Runtime`; Added in: .NET 9.0.\n * This metric reports the same values as calling [`Timer.ActiveCount`](https://learn.microsoft.com/dotnet/api/system.threading.timer.activecount).\n */\nexport const METRIC_DOTNET_TIMER_COUNT = 'dotnet.timer.count' as const;\n\n/**\n * Duration of HTTP client requests.\n */\nexport const METRIC_HTTP_CLIENT_REQUEST_DURATION = 'http.client.request.duration' as const;\n\n/**\n * Duration of HTTP server requests.\n */\nexport const METRIC_HTTP_SERVER_REQUEST_DURATION = 'http.server.request.duration' as const;\n\n/**\n * Number of classes currently loaded.\n */\nexport const METRIC_JVM_CLASS_COUNT = 'jvm.class.count' as const;\n\n/**\n * Number of classes loaded since JVM start.\n */\nexport const METRIC_JVM_CLASS_LOADED = 'jvm.class.loaded' as const;\n\n/**\n * Number of classes unloaded since JVM start.\n */\nexport const METRIC_JVM_CLASS_UNLOADED = 'jvm.class.unloaded' as const;\n\n/**\n * Number of processors available to the Java virtual machine.\n */\nexport const METRIC_JVM_CPU_COUNT = 'jvm.cpu.count' as const;\n\n/**\n * Recent CPU utilization for the process as reported by the JVM.\n *\n * @note The value range is [0.0,1.0]. This utilization is not defined as being for the specific interval since last measurement (unlike `system.cpu.utilization`). [Reference](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()).\n */\nexport const METRIC_JVM_CPU_RECENT_UTILIZATION = 'jvm.cpu.recent_utilization' as const;\n\n/**\n * CPU time used by the process as reported by the JVM.\n */\nexport const METRIC_JVM_CPU_TIME = 'jvm.cpu.time' as const;\n\n/**\n * Duration of JVM garbage collection actions.\n */\nexport const METRIC_JVM_GC_DURATION = 'jvm.gc.duration' as const;\n\n/**\n * Measure of memory committed.\n */\nexport const METRIC_JVM_MEMORY_COMMITTED = 'jvm.memory.committed' as const;\n\n/**\n * Measure of max obtainable memory.\n */\nexport const METRIC_JVM_MEMORY_LIMIT = 'jvm.memory.limit' as const;\n\n/**\n * Measure of memory used.\n */\nexport const METRIC_JVM_MEMORY_USED = 'jvm.memory.used' as const;\n\n/**\n * Measure of memory used, as measured after the most recent garbage collection event on this pool.\n */\nexport const METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = 'jvm.memory.used_after_last_gc' as const;\n\n/**\n * Number of executing platform threads.\n */\nexport const METRIC_JVM_THREAD_COUNT = 'jvm.thread.count' as const;\n\n/**\n * Number of connections that are currently active on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_ACTIVE_CONNECTIONS = 'kestrel.active_connections' as const;\n\n/**\n * Number of TLS handshakes that are currently in progress on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = 'kestrel.active_tls_handshakes' as const;\n\n/**\n * The duration of connections on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_CONNECTION_DURATION = 'kestrel.connection.duration' as const;\n\n/**\n * Number of connections that are currently queued and are waiting to start.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_QUEUED_CONNECTIONS = 'kestrel.queued_connections' as const;\n\n/**\n * Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_QUEUED_REQUESTS = 'kestrel.queued_requests' as const;\n\n/**\n * Number of connections rejected by the server.\n *\n * @note Connections are rejected when the currently active count exceeds the value configured with `MaxConcurrentConnections`.\n * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_REJECTED_CONNECTIONS = 'kestrel.rejected_connections' as const;\n\n/**\n * The duration of TLS handshakes on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_TLS_HANDSHAKE_DURATION = 'kestrel.tls_handshake.duration' as const;\n\n/**\n * Number of connections that are currently upgraded (WebSockets). .\n *\n * @note The counter only tracks HTTP/1.1 connections.\n *\n * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_KESTREL_UPGRADED_CONNECTIONS = 'kestrel.upgraded_connections' as const;\n\n/**\n * Number of connections that are currently active on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = 'signalr.server.active_connections' as const;\n\n/**\n * The duration of connections on the server.\n *\n * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0\n */\nexport const METRIC_SIGNALR_SERVER_CONNECTION_DURATION = 'signalr.server.connection.duration' as const;\n\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//-----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/ts-stable/events.ts.j2\n//-----------------------------------------------------------------------------------------------------------\n\n/**\n * This event describes a single exception.\n */\nexport const EVENT_EXCEPTION = 'exception' as const;\n\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable no-restricted-syntax --\n * These re-exports are only of constants, only two-levels deep, and\n * should not cause problems for tree-shakers.\n */\n\n// Deprecated. These are kept around for compatibility purposes\nexport * from './trace';\nexport * from './resource';\n\n// Use these instead\nexport * from './stable_attributes';\nexport * from './stable_metrics';\nexport * from './stable_events';\n", "import { ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE } from \"@opentelemetry/semantic-conventions\";\n//#region src/instrumentation/attributes.ts\n/** Operation identifier (e.g. getSession, signUpWithEmailAndPassword). Uses endpoint operationId when set, otherwise the endpoint key. */\nconst ATTR_OPERATION_ID = \"better_auth.operation_id\";\n/** Hook type (e.g. before, after, create.before). */\nconst ATTR_HOOK_TYPE = \"better_auth.hook.type\";\n/** Execution context (e.g. user, plugin:id). */\nconst ATTR_CONTEXT = \"better_auth.context\";\n//#endregion\nexport { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID };\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './node';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set([ownVersion]);\n const rejectedVersions = new Set();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters));\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with ReturnType>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return fn.call(thisArg, ...args);\n }\n\n bind(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum TraceFlags {\n /** Represents no flag set. */\n NONE = 0x0,\n /** Bit to represent whether trace is sampled in trace flags. */\n SAMPLED = 0x1 << 0,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\nexport const INVALID_SPANID = '0000000000000000';\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n traceId: INVALID_TRACEID,\n spanId: INVALID_SPANID,\n traceFlags: TraceFlags.NONE,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nexport class NonRecordingSpan implements Span {\n constructor(\n private readonly _spanContext: SpanContext = INVALID_SPAN_CONTEXT\n ) {}\n\n // Returns a SpanContext.\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n // By default does nothing\n setAttribute(_key: string, _value: unknown): this {\n return this;\n }\n\n // By default does nothing\n setAttributes(_attributes: SpanAttributes): this {\n return this;\n }\n\n // By default does nothing\n addEvent(_name: string, _attributes?: SpanAttributes): this {\n return this;\n }\n\n addLink(_link: Link): this {\n return this;\n }\n\n addLinks(_links: Link[]): this {\n return this;\n }\n\n // By default does nothing\n setStatus(_status: SpanStatus): this {\n return this;\n }\n\n // By default does nothing\n updateName(_name: string): this {\n return this;\n }\n\n // By default does nothing\n end(_endTime?: TimeInput): void {}\n\n // isRecording always returns false for NonRecordingSpan.\n isRecording(): boolean {\n return false;\n }\n\n // By default does nothing\n recordException(_exception: Exception, _time?: TimeInput): void {}\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n\n/**\n * span key\n */\nconst SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context: Context): Span | undefined {\n return (context.getValue(SPAN_KEY) as Span) || undefined;\n}\n\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan(): Span | undefined {\n return getSpan(ContextAPI.getInstance().active());\n}\n\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context: Context, span: Span): Context {\n return context.setValue(SPAN_KEY, span);\n}\n\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context: Context): Context {\n return context.deleteValue(SPAN_KEY);\n}\n\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(\n context: Context,\n spanContext: SpanContext\n): Context {\n return setSpan(context, new NonRecordingSpan(spanContext));\n}\n\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context: Context): SpanContext | undefined {\n return getSpan(context)?.spanContext();\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\n\nconst VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nconst VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\n\nexport function isValidTraceId(traceId: string): boolean {\n return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\n\nexport function isValidSpanId(spanId: string): boolean {\n return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext: SpanContext): boolean {\n return (\n isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)\n );\n}\n\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext: SpanContext): Span {\n return new NonRecordingSpan(spanContext);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { Context } from '../context/types';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { isSpanContextValid } from './spancontext-utils';\nimport { SpanOptions } from './SpanOptions';\nimport { SpanContext } from './span_context';\nimport { Tracer } from './tracer';\n\nconst contextApi = ContextAPI.getInstance();\n\n/**\n * No-op implementations of {@link Tracer}.\n */\nexport class NoopTracer implements Tracer {\n // startSpan starts a noop span.\n startSpan(\n name: string,\n options?: SpanOptions,\n context = contextApi.active()\n ): Span {\n const root = Boolean(options?.root);\n if (root) {\n return new NonRecordingSpan();\n }\n\n const parentFromContext = context && getSpanContext(context);\n\n if (\n isSpanContext(parentFromContext) &&\n isSpanContextValid(parentFromContext)\n ) {\n return new NonRecordingSpan(parentFromContext);\n } else {\n return new NonRecordingSpan();\n }\n }\n\n startActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n ctx: Context | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n arg2?: F | SpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType | undefined {\n let opts: SpanOptions | undefined;\n let ctx: Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as SpanOptions | undefined;\n ctx = arg3 as Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? contextApi.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = setSpan(parentContext, span);\n\n return contextApi.with(contextWithSpanSet, fn, undefined, span);\n }\n}\n\nfunction isSpanContext(spanContext: any): spanContext is SpanContext {\n return (\n typeof spanContext === 'object' &&\n typeof spanContext['spanId'] === 'string' &&\n typeof spanContext['traceId'] === 'string' &&\n typeof spanContext['traceFlags'] === 'number'\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { NoopTracer } from './NoopTracer';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER = new NoopTracer();\n\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nexport class ProxyTracer implements Tracer {\n // When a real implementation is provided, this will be it\n private _delegate?: Tracer;\n\n constructor(\n private _provider: TracerDelegator,\n public readonly name: string,\n public readonly version?: string,\n public readonly options?: TracerOptions\n ) {}\n\n startSpan(name: string, options?: SpanOptions, context?: Context): Span {\n return this._getTracer().startSpan(name, options, context);\n }\n\n startActiveSpan unknown>(\n _name: string,\n _options: F | SpanOptions,\n _context?: F | Context,\n _fn?: F\n ): ReturnType {\n const tracer = this._getTracer();\n return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n }\n\n /**\n * Try to get a tracer from the proxy tracer provider.\n * If the proxy tracer provider has no delegate, return a noop tracer.\n */\n private _getTracer() {\n if (this._delegate) {\n return this._delegate;\n }\n\n const tracer = this._provider.getDelegateTracer(\n this.name,\n this.version,\n this.options\n );\n\n if (!tracer) {\n return NOOP_TRACER;\n }\n\n this._delegate = tracer;\n return this._delegate;\n }\n}\n\nexport interface TracerDelegator {\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopTracer } from './NoopTracer';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\nimport { TracerProvider } from './tracer_provider';\n\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nexport class NoopTracerProvider implements TracerProvider {\n getTracer(\n _name?: string,\n _version?: string,\n _options?: TracerOptions\n ): Tracer {\n return new NoopTracer();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerProvider } from './tracer_provider';\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n * When a delegate is set, traces are provided from the delegate.\n * When a delegate is set after tracers have already been provided,\n * all tracers already provided will use the provided delegate implementation.\n */\nexport class ProxyTracerProvider implements TracerProvider {\n private _delegate?: TracerProvider;\n\n /**\n * Get a {@link ProxyTracer}\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer {\n return (\n this.getDelegateTracer(name, version, options) ??\n new ProxyTracer(this, name, version, options)\n );\n }\n\n getDelegate(): TracerProvider {\n return this._delegate ?? NOOP_TRACER_PROVIDER;\n }\n\n /**\n * Set the delegate tracer provider\n */\n setDelegate(delegate: TracerProvider) {\n this._delegate = delegate;\n }\n\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined {\n return this._delegate?.getTracer(name, version, options);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport {\n isSpanContextValid,\n wrapSpanContext,\n} from '../trace/spancontext-utils';\nimport { Tracer } from '../trace/tracer';\nimport { TracerProvider } from '../trace/tracer_provider';\nimport {\n deleteSpan,\n getActiveSpan,\n getSpan,\n getSpanContext,\n setSpan,\n setSpanContext,\n} from '../trace/context-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'trace';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nexport class TraceAPI {\n private static _instance?: TraceAPI;\n\n private _proxyTracerProvider = new ProxyTracerProvider();\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Trace API */\n public static getInstance(): TraceAPI {\n if (!this._instance) {\n this._instance = new TraceAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global tracer.\n *\n * @returns true if the tracer provider was successfully registered, else false\n */\n public setGlobalTracerProvider(provider: TracerProvider): boolean {\n const success = registerGlobal(\n API_NAME,\n this._proxyTracerProvider,\n DiagAPI.instance()\n );\n if (success) {\n this._proxyTracerProvider.setDelegate(provider);\n }\n return success;\n }\n\n /**\n * Returns the global tracer provider.\n */\n public getTracerProvider(): TracerProvider {\n return getGlobal(API_NAME) || this._proxyTracerProvider;\n }\n\n /**\n * Returns a tracer from the global tracer provider.\n */\n public getTracer(name: string, version?: string): Tracer {\n return this.getTracerProvider().getTracer(name, version);\n }\n\n /** Remove the global tracer provider */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n this._proxyTracerProvider = new ProxyTracerProvider();\n }\n\n public wrapSpanContext = wrapSpanContext;\n\n public isSpanContextValid = isSpanContextValid;\n\n public deleteSpan = deleteSpan;\n\n public getSpan = getSpan;\n\n public getActiveSpan = getActiveSpan;\n\n public getSpanContext = getSpanContext;\n\n public setSpan = setSpan;\n\n public setSpanContext = setSpanContext;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport const trace = TraceAPI.getInstance();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types';\nexport { baggageEntryMetadataFromString } from './baggage/utils';\nexport { Exception } from './common/Exception';\nexport { HrTime, TimeInput } from './common/Time';\nexport { Attributes, AttributeValue } from './common/Attributes';\n\n// Context APIs\nexport { createContextKey, ROOT_CONTEXT } from './context/context';\nexport { Context, ContextManager } from './context/types';\nexport type { ContextAPI } from './api/context';\n\n// Diag APIs\nexport { DiagConsoleLogger } from './diag/consoleLogger';\nexport {\n DiagLogFunction,\n DiagLogger,\n DiagLogLevel,\n ComponentLoggerOptions,\n DiagLoggerOptions,\n} from './diag/types';\nexport type { DiagAPI } from './api/diag';\n\n// Metrics APIs\nexport { createNoopMeter } from './metrics/NoopMeter';\nexport { MeterOptions, Meter } from './metrics/Meter';\nexport { MeterProvider } from './metrics/MeterProvider';\nexport {\n ValueType,\n Counter,\n Gauge,\n Histogram,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n BatchObservableCallback,\n MetricAdvice,\n MetricAttributes,\n MetricAttributeValue,\n ObservableCallback,\n} from './metrics/Metric';\nexport {\n BatchObservableResult,\n ObservableResult,\n} from './metrics/ObservableResult';\nexport type { MetricsAPI } from './api/metrics';\n\n// Propagation APIs\nexport {\n TextMapPropagator,\n TextMapSetter,\n TextMapGetter,\n defaultTextMapGetter,\n defaultTextMapSetter,\n} from './propagation/TextMapPropagator';\nexport type { PropagationAPI } from './api/propagation';\n\n// Trace APIs\nexport { SpanAttributes, SpanAttributeValue } from './trace/attributes';\nexport { Link } from './trace/link';\nexport { ProxyTracer, TracerDelegator } from './trace/ProxyTracer';\nexport { ProxyTracerProvider } from './trace/ProxyTracerProvider';\nexport { Sampler } from './trace/Sampler';\nexport { SamplingDecision, SamplingResult } from './trace/SamplingResult';\nexport { SpanContext } from './trace/span_context';\nexport { SpanKind } from './trace/span_kind';\nexport { Span } from './trace/span';\nexport { SpanOptions } from './trace/SpanOptions';\nexport { SpanStatus, SpanStatusCode } from './trace/status';\nexport { TraceFlags } from './trace/trace_flags';\nexport { TraceState } from './trace/trace_state';\nexport { createTraceState } from './trace/internal/utils';\nexport { TracerProvider } from './trace/tracer_provider';\nexport { Tracer } from './trace/tracer';\nexport { TracerOptions } from './trace/tracer_options';\nexport {\n isSpanContextValid,\n isValidTraceId,\n isValidSpanId,\n} from './trace/spancontext-utils';\nexport {\n INVALID_SPANID,\n INVALID_TRACEID,\n INVALID_SPAN_CONTEXT,\n} from './trace/invalid-span-constants';\nexport type { TraceAPI } from './api/trace';\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { context } from './context-api';\nimport { diag } from './diag-api';\nimport { metrics } from './metrics-api';\nimport { propagation } from './propagation-api';\nimport { trace } from './trace-api';\n\n// Named export.\nexport { context, diag, metrics, propagation, trace };\n// Default export.\nexport default {\n context,\n diag,\n metrics,\n propagation,\n trace,\n};\n", "import { ATTR_HTTP_RESPONSE_STATUS_CODE } from \"./attributes.mjs\";\nimport { SpanStatusCode, trace } from \"@opentelemetry/api\";\n//#region src/instrumentation/tracer.ts\nconst tracer = trace.getTracer(\"better-auth\", \"1.6.2\");\n/**\n* Better-auth uses `throw ctx.redirect(url)` for flow control (e.g. OAuth\n* callbacks). These are APIErrors with 3xx status codes and should not be\n* recorded as span errors.\n*/\nfunction isRedirectError(err) {\n\tif (err != null && typeof err === \"object\" && \"name\" in err && err.name === \"APIError\" && \"statusCode\" in err) {\n\t\tconst status = err.statusCode;\n\t\treturn status >= 300 && status < 400;\n\t}\n\treturn false;\n}\nfunction endSpanWithError(span, err) {\n\tif (isRedirectError(err)) {\n\t\tspan.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, err.statusCode);\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t} else {\n\t\tspan.recordException(err);\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: String(err?.message ?? err)\n\t\t});\n\t}\n\tspan.end();\n}\nfunction withSpan(name, attributes, fn) {\n\treturn tracer.startActiveSpan(name, { attributes }, (span) => {\n\t\ttry {\n\t\t\tconst result = fn();\n\t\t\tif (result instanceof Promise) return result.then((value) => {\n\t\t\t\tspan.end();\n\t\t\t\treturn value;\n\t\t\t}).catch((err) => {\n\t\t\t\tendSpanWithError(span, err);\n\t\t\t\tthrow err;\n\t\t\t});\n\t\t\tspan.end();\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tendSpanWithError(span, err);\n\t\t\tthrow err;\n\t\t}\n\t});\n}\n//#endregion\nexport { withSpan };\n", "import { createRandomStringGenerator } from \"@better-auth/utils/random\";\n//#region src/utils/id.ts\nconst generateId = (size) => {\n\treturn createRandomStringGenerator(\"a-z\", \"A-Z\", \"0-9\")(size || 32);\n};\n//#endregion\nexport { generateId };\n", "import { BetterAuthError } from \"../../error/index.mjs\";\n//#region src/db/adapter/get-default-model-name.ts\nconst initGetDefaultModelName = ({ usePlural, schema }) => {\n\t/**\n\t* This function helps us get the default model name from the schema defined by devs.\n\t* Often times, the user will be using the `modelName` which could had been customized by the users.\n\t* This function helps us get the actual model name useful to match against the schema. (eg: schema[model])\n\t*\n\t* If it's still unclear what this does:\n\t*\n\t* 1. User can define a custom modelName.\n\t* 2. When using a custom modelName, doing something like `schema[model]` will not work.\n\t* 3. Using this function helps us get the actual model name based on the user's defined custom modelName.\n\t*/\n\tconst getDefaultModelName = (model) => {\n\t\tif (usePlural && model.charAt(model.length - 1) === \"s\") {\n\t\t\tconst pluralessModel = model.slice(0, -1);\n\t\t\tlet m = schema[pluralessModel] ? pluralessModel : void 0;\n\t\t\tif (!m) m = Object.entries(schema).find(([_, f]) => f.modelName === pluralessModel)?.[0];\n\t\t\tif (m) return m;\n\t\t}\n\t\tlet m = schema[model] ? model : void 0;\n\t\tif (!m) m = Object.entries(schema).find(([_, f]) => f.modelName === model)?.[0];\n\t\tif (!m) throw new BetterAuthError(`Model \"${model}\" not found in schema`);\n\t\treturn m;\n\t};\n\treturn getDefaultModelName;\n};\n//#endregion\nexport { initGetDefaultModelName };\n", "import { BetterAuthError } from \"../../error/index.mjs\";\nimport { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\n//#region src/db/adapter/get-default-field-name.ts\nconst initGetDefaultFieldName = ({ schema, usePlural }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tschema,\n\t\tusePlural\n\t});\n\t/**\n\t* This function helps us get the default field name from the schema defined by devs.\n\t* Often times, the user will be using the `fieldName` which could had been customized by the users.\n\t* This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field])\n\t*\n\t* If it's still unclear what this does:\n\t*\n\t* 1. User can define a custom fieldName.\n\t* 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work.\n\t*/\n\tconst getDefaultFieldName = ({ field, model: unsafeModel }) => {\n\t\tif (field === \"id\" || field === \"_id\") return \"id\";\n\t\tconst model = getDefaultModelName(unsafeModel);\n\t\tlet f = schema[model]?.fields[field];\n\t\tif (!f) {\n\t\t\tconst result = Object.entries(schema[model].fields).find(([_, f]) => f.fieldName === field);\n\t\t\tif (result) {\n\t\t\t\tf = result[1];\n\t\t\t\tfield = result[0];\n\t\t\t}\n\t\t}\n\t\tif (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`);\n\t\treturn field;\n\t};\n\treturn getDefaultFieldName;\n};\n//#endregion\nexport { initGetDefaultFieldName };\n", "import { logger } from \"../../env/logger.mjs\";\nimport { generateId } from \"../../utils/id.mjs\";\nimport { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\n//#region src/db/adapter/get-id-field.ts\nconst initGetIdField = ({ usePlural, schema, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tusePlural,\n\t\tschema\n\t});\n\tconst idField = ({ customModelName, forceAllowId }) => {\n\t\tconst useNumberId = options.advanced?.database?.generateId === \"serial\";\n\t\tconst useUUIDs = options.advanced?.database?.generateId === \"uuid\";\n\t\tconst shouldGenerateId = (() => {\n\t\t\tif (disableIdGeneration) return false;\n\t\t\telse if (useNumberId && !forceAllowId) return false;\n\t\t\telse if (useUUIDs) return !supportsUUIDs;\n\t\t\telse return true;\n\t\t})();\n\t\tconst model = getDefaultModelName(customModelName ?? \"id\");\n\t\treturn {\n\t\t\ttype: useNumberId ? \"number\" : \"string\",\n\t\t\trequired: shouldGenerateId ? true : false,\n\t\t\t...shouldGenerateId ? { defaultValue() {\n\t\t\t\tif (disableIdGeneration) return void 0;\n\t\t\t\tconst generateId$1 = options.advanced?.database?.generateId;\n\t\t\t\tif (generateId$1 === false || generateId$1 === \"serial\") return void 0;\n\t\t\t\tif (typeof generateId$1 === \"function\") return generateId$1({ model });\n\t\t\t\tif (generateId$1 === \"uuid\") return crypto.randomUUID();\n\t\t\t\tif (customIdGenerator) return customIdGenerator({ model });\n\t\t\t\treturn generateId();\n\t\t\t} } : {},\n\t\t\ttransform: {\n\t\t\t\tinput: (value) => {\n\t\t\t\t\tif (!value) return void 0;\n\t\t\t\t\tif (useNumberId) {\n\t\t\t\t\t\tconst numberValue = Number(value);\n\t\t\t\t\t\tif (isNaN(numberValue)) return;\n\t\t\t\t\t\treturn numberValue;\n\t\t\t\t\t}\n\t\t\t\t\tif (useUUIDs) {\n\t\t\t\t\t\tif (shouldGenerateId && !forceAllowId) return value;\n\t\t\t\t\t\tif (disableIdGeneration) return void 0;\n\t\t\t\t\t\tif (supportsUUIDs) return void 0;\n\t\t\t\t\t\tif (forceAllowId && typeof value === \"string\") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst stack = (/* @__PURE__ */ new Error()).stack?.split(\"\\n\").filter((_, i) => i !== 1).join(\"\\n\").replace(\"Error:\", \"\");\n\t\t\t\t\t\t\tlogger.warn(\"[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.\", stack);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof value !== \"string\" && !supportsUUIDs) return crypto.randomUUID();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\treturn value;\n\t\t\t\t},\n\t\t\t\toutput: (value) => {\n\t\t\t\t\tif (!value) return void 0;\n\t\t\t\t\treturn String(value);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t};\n\treturn idField;\n};\n//#endregion\nexport { initGetIdField };\n", "import { BetterAuthError } from \"../../error/index.mjs\";\nimport { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\nimport { initGetDefaultFieldName } from \"./get-default-field-name.mjs\";\nimport { initGetIdField } from \"./get-id-field.mjs\";\n//#region src/db/adapter/get-field-attributes.ts\nconst initGetFieldAttributes = ({ usePlural, schema, options, customIdGenerator, disableIdGeneration }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tusePlural,\n\t\tschema\n\t});\n\tconst getDefaultFieldName = initGetDefaultFieldName({\n\t\tusePlural,\n\t\tschema\n\t});\n\tconst idField = initGetIdField({\n\t\tusePlural,\n\t\tschema,\n\t\toptions,\n\t\tcustomIdGenerator,\n\t\tdisableIdGeneration\n\t});\n\tconst getFieldAttributes = ({ model, field }) => {\n\t\tconst defaultModelName = getDefaultModelName(model);\n\t\tconst defaultFieldName = getDefaultFieldName({\n\t\t\tfield,\n\t\t\tmodel: defaultModelName\n\t\t});\n\t\tconst fields = schema[defaultModelName].fields;\n\t\tfields.id = idField({ customModelName: defaultModelName });\n\t\tconst fieldAttributes = fields[defaultFieldName];\n\t\tif (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`);\n\t\treturn fieldAttributes;\n\t};\n\treturn getFieldAttributes;\n};\n//#endregion\nexport { initGetFieldAttributes };\n", "import { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\nimport { initGetDefaultFieldName } from \"./get-default-field-name.mjs\";\n//#region src/db/adapter/get-field-name.ts\nconst initGetFieldName = ({ schema, usePlural }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tschema,\n\t\tusePlural\n\t});\n\tconst getDefaultFieldName = initGetDefaultFieldName({\n\t\tschema,\n\t\tusePlural\n\t});\n\t/**\n\t* Get the field name which is expected to be saved in the database based on the user's schema.\n\t*\n\t* This function is useful if you need to save the field name to the database.\n\t*\n\t* For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema.\n\t*/\n\tfunction getFieldName({ model: modelName, field: fieldName }) {\n\t\tconst model = getDefaultModelName(modelName);\n\t\tconst field = getDefaultFieldName({\n\t\t\tmodel,\n\t\t\tfield: fieldName\n\t\t});\n\t\treturn schema[model]?.fields[field]?.fieldName || field;\n\t}\n\treturn getFieldName;\n};\n//#endregion\nexport { initGetFieldName };\n", "import { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\n//#region src/db/adapter/get-model-name.ts\nconst initGetModelName = ({ usePlural, schema }) => {\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tschema,\n\t\tusePlural\n\t});\n\t/**\n\t* Users can overwrite the default model of some tables. This function helps find the correct model name.\n\t* Furthermore, if the user passes `usePlural` as true in their adapter config,\n\t* then we should return the model name ending with an `s`.\n\t*/\n\tconst getModelName = (model) => {\n\t\tconst defaultModelKey = getDefaultModelName(model);\n\t\tif (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName;\n\t\treturn usePlural ? `${model}s` : model;\n\t};\n\treturn getModelName;\n};\n//#endregion\nexport { initGetModelName };\n", "//#region src/db/adapter/utils.ts\nfunction withApplyDefault(value, field, action) {\n\tif (action === \"update\") {\n\t\tif (value === void 0 && field.onUpdate !== void 0) {\n\t\t\tif (typeof field.onUpdate === \"function\") return field.onUpdate();\n\t\t\treturn field.onUpdate;\n\t\t}\n\t\treturn value;\n\t}\n\tif (action === \"create\") {\n\t\tif (value === void 0 || field.required === true && value === null) {\n\t\t\tif (field.defaultValue !== void 0) {\n\t\t\t\tif (typeof field.defaultValue === \"function\") return field.defaultValue();\n\t\t\t\treturn field.defaultValue;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n}\nfunction isObject(item) {\n\treturn item !== null && typeof item === \"object\" && !Array.isArray(item);\n}\nfunction deepmerge(target, source) {\n\tif (Array.isArray(target) && Array.isArray(source)) return [...target, ...source];\n\telse if (isObject(target) && isObject(source)) {\n\t\tconst result = { ...target };\n\t\tfor (const [key, value] of Object.entries(source)) {\n\t\t\tif (value === void 0) continue;\n\t\t\tif (key in target) result[key] = deepmerge(target[key], value);\n\t\t\telse result[key] = value;\n\t\t}\n\t\treturn result;\n\t}\n\treturn source;\n}\n//#endregion\nexport { deepmerge, withApplyDefault };\n", "import { getAuthTables } from \"../get-tables.mjs\";\nimport { getColorDepth } from \"../../env/color-depth.mjs\";\nimport { TTY_COLORS, createLogger } from \"../../env/logger.mjs\";\nimport { BetterAuthError } from \"../../error/index.mjs\";\nimport { ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME } from \"../../instrumentation/attributes.mjs\";\nimport { withSpan } from \"../../instrumentation/tracer.mjs\";\nimport { safeJSONParse } from \"../../utils/json.mjs\";\nimport { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\nimport { initGetDefaultFieldName } from \"./get-default-field-name.mjs\";\nimport { initGetIdField } from \"./get-id-field.mjs\";\nimport { initGetFieldAttributes } from \"./get-field-attributes.mjs\";\nimport { initGetFieldName } from \"./get-field-name.mjs\";\nimport { initGetModelName } from \"./get-model-name.mjs\";\nimport { withApplyDefault } from \"./utils.mjs\";\n//#region src/db/adapter/factory.ts\nlet debugLogs = [];\nlet transactionId = -1;\nconst createAsIsTransaction = (adapter) => (fn) => fn(adapter);\nconst createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => {\n\tconst uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15);\n\tconst config = {\n\t\t...cfg,\n\t\tsupportsBooleans: cfg.supportsBooleans ?? true,\n\t\tsupportsDates: cfg.supportsDates ?? true,\n\t\tsupportsJSON: cfg.supportsJSON ?? false,\n\t\tadapterName: cfg.adapterName ?? cfg.adapterId,\n\t\tsupportsNumericIds: cfg.supportsNumericIds ?? true,\n\t\tsupportsUUIDs: cfg.supportsUUIDs ?? false,\n\t\tsupportsArrays: cfg.supportsArrays ?? false,\n\t\ttransaction: cfg.transaction ?? false,\n\t\tdisableTransformInput: cfg.disableTransformInput ?? false,\n\t\tdisableTransformOutput: cfg.disableTransformOutput ?? false,\n\t\tdisableTransformJoin: cfg.disableTransformJoin ?? false\n\t};\n\tif (options.advanced?.database?.generateId === \"serial\" && config.supportsNumericIds === false) throw new BetterAuthError(`[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable \"useNumberId\" in your config.`);\n\tconst schema = getAuthTables(options);\n\tconst debugLog = (...args) => {\n\t\tif (config.debugLogs === true || typeof config.debugLogs === \"object\") {\n\t\t\tconst logger = createLogger({ level: \"info\" });\n\t\t\tif (typeof config.debugLogs === \"object\" && \"isRunningAdapterTests\" in config.debugLogs) {\n\t\t\t\tif (config.debugLogs.isRunningAdapterTests) {\n\t\t\t\t\targs.shift();\n\t\t\t\t\tdebugLogs.push({\n\t\t\t\t\t\tinstance: uniqueAdapterFactoryInstanceId,\n\t\t\t\t\t\targs\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (typeof config.debugLogs === \"object\" && config.debugLogs.logCondition && !config.debugLogs.logCondition?.()) return;\n\t\t\tif (typeof args[0] === \"object\" && \"method\" in args[0]) {\n\t\t\t\tconst method = args.shift().method;\n\t\t\t\tif (typeof config.debugLogs === \"object\") {\n\t\t\t\t\tif (method === \"create\" && !config.debugLogs.create) return;\n\t\t\t\t\telse if (method === \"update\" && !config.debugLogs.update) return;\n\t\t\t\t\telse if (method === \"updateMany\" && !config.debugLogs.updateMany) return;\n\t\t\t\t\telse if (method === \"findOne\" && !config.debugLogs.findOne) return;\n\t\t\t\t\telse if (method === \"findMany\" && !config.debugLogs.findMany) return;\n\t\t\t\t\telse if (method === \"delete\" && !config.debugLogs.delete) return;\n\t\t\t\t\telse if (method === \"deleteMany\" && !config.debugLogs.deleteMany) return;\n\t\t\t\t\telse if (method === \"count\" && !config.debugLogs.count) return;\n\t\t\t\t}\n\t\t\t\tlogger.info(`[${config.adapterName}]`, ...args);\n\t\t\t} else logger.info(`[${config.adapterName}]`, ...args);\n\t\t}\n\t};\n\tconst logger = createLogger(options.logger);\n\tconst getDefaultModelName = initGetDefaultModelName({\n\t\tusePlural: config.usePlural,\n\t\tschema\n\t});\n\tconst getDefaultFieldName = initGetDefaultFieldName({\n\t\tusePlural: config.usePlural,\n\t\tschema\n\t});\n\tconst getModelName = initGetModelName({\n\t\tusePlural: config.usePlural,\n\t\tschema\n\t});\n\tconst getFieldName = initGetFieldName({\n\t\tschema,\n\t\tusePlural: config.usePlural\n\t});\n\tconst idField = initGetIdField({\n\t\tschema,\n\t\toptions,\n\t\tusePlural: config.usePlural,\n\t\tdisableIdGeneration: config.disableIdGeneration,\n\t\tcustomIdGenerator: config.customIdGenerator,\n\t\tsupportsUUIDs: config.supportsUUIDs\n\t});\n\tconst getFieldAttributes = initGetFieldAttributes({\n\t\tschema,\n\t\toptions,\n\t\tusePlural: config.usePlural,\n\t\tdisableIdGeneration: config.disableIdGeneration,\n\t\tcustomIdGenerator: config.customIdGenerator\n\t});\n\tconst transformInput = async (data, defaultModelName, action, forceAllowId) => {\n\t\tconst transformedData = {};\n\t\tconst fields = schema[defaultModelName].fields;\n\t\tconst newMappedKeys = config.mapKeysTransformInput ?? {};\n\t\tconst useNumberId = options.advanced?.database?.generateId === \"serial\";\n\t\tfields.id = idField({\n\t\t\tcustomModelName: defaultModelName,\n\t\t\tforceAllowId: forceAllowId && \"id\" in data\n\t\t});\n\t\tfor (const field in fields) {\n\t\t\tlet value = data[field];\n\t\t\tconst fieldAttributes = fields[field];\n\t\t\tconst newFieldName = newMappedKeys[field] || fields[field].fieldName || field;\n\t\t\tif (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === \"update\" && fieldAttributes.onUpdate) || action === \"update\" && !fieldAttributes.onUpdate)) continue;\n\t\t\tif (fieldAttributes && fieldAttributes.type === \"date\" && !(value instanceof Date) && typeof value === \"string\") try {\n\t\t\t\tvalue = new Date(value);\n\t\t\t} catch {\n\t\t\t\tlogger.error(\"[Adapter Factory] Failed to convert string to date\", {\n\t\t\t\t\tvalue,\n\t\t\t\t\tfield\n\t\t\t\t});\n\t\t\t}\n\t\t\tlet newValue = withApplyDefault(value, fieldAttributes, action);\n\t\t\tif (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue);\n\t\t\tif (fieldAttributes.references?.field === \"id\" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null);\n\t\t\telse newValue = newValue !== null ? Number(newValue) : null;\n\t\t\telse if (config.supportsJSON === false && typeof newValue === \"object\" && fieldAttributes.type === \"json\") newValue = JSON.stringify(newValue);\n\t\t\telse if (config.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === \"string[]\" || fieldAttributes.type === \"number[]\")) newValue = JSON.stringify(newValue);\n\t\t\telse if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === \"date\") newValue = newValue.toISOString();\n\t\t\telse if (config.supportsBooleans === false && typeof newValue === \"boolean\") newValue = newValue ? 1 : 0;\n\t\t\tif (config.customTransformInput) newValue = config.customTransformInput({\n\t\t\t\tdata: newValue,\n\t\t\t\taction,\n\t\t\t\tfield: newFieldName,\n\t\t\t\tfieldAttributes,\n\t\t\t\tmodel: getModelName(defaultModelName),\n\t\t\t\tschema,\n\t\t\t\toptions\n\t\t\t});\n\t\t\tif (newValue !== void 0) transformedData[newFieldName] = newValue;\n\t\t}\n\t\treturn transformedData;\n\t};\n\tconst transformOutput = async (data, unsafe_model, select = [], join) => {\n\t\tconst transformSingleOutput = async (data, unsafe_model, select = []) => {\n\t\t\tif (!data) return null;\n\t\t\tconst newMappedKeys = config.mapKeysTransformOutput ?? {};\n\t\t\tconst transformedData = {};\n\t\t\tconst tableSchema = schema[getDefaultModelName(unsafe_model)].fields;\n\t\t\tconst idKey = Object.entries(newMappedKeys).find(([_, v]) => v === \"id\")?.[0];\n\t\t\ttableSchema[idKey ?? \"id\"] = { type: options.advanced?.database?.generateId === \"serial\" ? \"number\" : \"string\" };\n\t\t\tfor (const key in tableSchema) {\n\t\t\t\tif (select.length && !select.includes(key)) continue;\n\t\t\t\tconst field = tableSchema[key];\n\t\t\t\tif (field) {\n\t\t\t\t\tconst originalKey = field.fieldName || key;\n\t\t\t\t\tlet newValue = data[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey];\n\t\t\t\t\tif (field.transform?.output) newValue = await field.transform.output(newValue);\n\t\t\t\t\tconst newFieldName = newMappedKeys[key] || key;\n\t\t\t\t\tif (originalKey === \"id\" || field.references?.field === \"id\") {\n\t\t\t\t\t\tif (typeof newValue !== \"undefined\" && newValue !== null) newValue = String(newValue);\n\t\t\t\t\t} else if (config.supportsJSON === false && typeof newValue === \"string\" && field.type === \"json\") newValue = safeJSONParse(newValue);\n\t\t\t\t\telse if (config.supportsArrays === false && typeof newValue === \"string\" && (field.type === \"string[]\" || field.type === \"number[]\")) newValue = safeJSONParse(newValue);\n\t\t\t\t\telse if (config.supportsDates === false && typeof newValue === \"string\" && field.type === \"date\") newValue = new Date(newValue);\n\t\t\t\t\telse if (config.supportsBooleans === false && typeof newValue === \"number\" && field.type === \"boolean\") newValue = newValue === 1;\n\t\t\t\t\tif (config.customTransformOutput) newValue = config.customTransformOutput({\n\t\t\t\t\t\tdata: newValue,\n\t\t\t\t\t\tfield: newFieldName,\n\t\t\t\t\t\tfieldAttributes: field,\n\t\t\t\t\t\tselect,\n\t\t\t\t\t\tmodel: getModelName(unsafe_model),\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\toptions\n\t\t\t\t\t});\n\t\t\t\t\ttransformedData[newFieldName] = newValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn transformedData;\n\t\t};\n\t\tif (!join || Object.keys(join).length === 0) return await transformSingleOutput(data, unsafe_model, select);\n\t\tunsafe_model = getDefaultModelName(unsafe_model);\n\t\tconst transformedData = await transformSingleOutput(data, unsafe_model, select);\n\t\tconst requiredModels = Object.entries(join).map(([model, joinConfig]) => ({\n\t\t\tmodelName: getModelName(model),\n\t\t\tdefaultModelName: getDefaultModelName(model),\n\t\t\tjoinConfig\n\t\t}));\n\t\tif (!data) return null;\n\t\tfor (const { modelName, defaultModelName, joinConfig } of requiredModels) {\n\t\t\tlet joinedData = await (async () => {\n\t\t\t\tif (options.experimental?.joins) return data[modelName];\n\t\t\t\telse return await handleFallbackJoin({\n\t\t\t\t\tbaseModel: unsafe_model,\n\t\t\t\t\tbaseData: transformedData,\n\t\t\t\t\tjoinModel: modelName,\n\t\t\t\t\tspecificJoinConfig: joinConfig\n\t\t\t\t});\n\t\t\t})();\n\t\t\tif (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === \"one-to-one\" ? null : [];\n\t\t\tif (joinConfig.relation === \"one-to-many\" && !Array.isArray(joinedData)) joinedData = [joinedData];\n\t\t\tconst transformed = [];\n\t\t\tif (Array.isArray(joinedData)) for (const item of joinedData) {\n\t\t\t\tconst transformedItem = await transformSingleOutput(item, modelName, []);\n\t\t\t\ttransformed.push(transformedItem);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst transformedItem = await transformSingleOutput(joinedData, modelName, []);\n\t\t\t\ttransformed.push(transformedItem);\n\t\t\t}\n\t\t\ttransformedData[defaultModelName] = (joinConfig.relation === \"one-to-one\" ? transformed[0] : transformed) ?? null;\n\t\t}\n\t\treturn transformedData;\n\t};\n\tconst transformWhereClause = ({ model, where, action }) => {\n\t\tif (!where) return void 0;\n\t\tconst newMappedKeys = config.mapKeysTransformInput ?? {};\n\t\treturn where.map((w) => {\n\t\t\tconst { field: unsafe_field, value, operator = \"eq\", connector = \"AND\", mode = \"sensitive\" } = w;\n\t\t\tif (operator === \"in\") {\n\t\t\t\tif (!Array.isArray(value)) throw new BetterAuthError(\"Value must be an array\");\n\t\t\t}\n\t\t\tlet newValue = value;\n\t\t\tconst defaultModelName = getDefaultModelName(model);\n\t\t\tconst defaultFieldName = getDefaultFieldName({\n\t\t\t\tfield: unsafe_field,\n\t\t\t\tmodel\n\t\t\t});\n\t\t\tconst fieldName = newMappedKeys[defaultFieldName] || getFieldName({\n\t\t\t\tfield: defaultFieldName,\n\t\t\t\tmodel: defaultModelName\n\t\t\t});\n\t\t\tconst fieldAttr = getFieldAttributes({\n\t\t\t\tfield: defaultFieldName,\n\t\t\t\tmodel: defaultModelName\n\t\t\t});\n\t\t\tconst useNumberId = options.advanced?.database?.generateId === \"serial\";\n\t\t\tif (defaultFieldName === \"id\" || fieldAttr.references?.field === \"id\") {\n\t\t\t\tif (useNumberId) if (Array.isArray(value)) newValue = value.map(Number);\n\t\t\t\telse newValue = Number(value);\n\t\t\t}\n\t\t\tif (fieldAttr.type === \"date\" && value instanceof Date && !config.supportsDates) newValue = value.toISOString();\n\t\t\tif (fieldAttr.type === \"boolean\" && typeof newValue === \"string\") newValue = newValue === \"true\";\n\t\t\tif (fieldAttr.type === \"number\") {\n\t\t\t\tif (typeof newValue === \"string\" && newValue.trim() !== \"\") {\n\t\t\t\t\tconst parsed = Number(newValue);\n\t\t\t\t\tif (!Number.isNaN(parsed)) newValue = parsed;\n\t\t\t\t} else if (Array.isArray(newValue)) {\n\t\t\t\t\tconst parsed = newValue.map((v) => typeof v === \"string\" && v.trim() !== \"\" ? Number(v) : NaN);\n\t\t\t\t\tif (parsed.every((n) => !Number.isNaN(n))) newValue = parsed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (fieldAttr.type === \"boolean\" && typeof newValue === \"boolean\" && !config.supportsBooleans) newValue = newValue ? 1 : 0;\n\t\t\tif (fieldAttr.type === \"json\" && typeof value === \"object\" && !config.supportsJSON) try {\n\t\t\t\tnewValue = JSON.stringify(value);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error });\n\t\t\t}\n\t\t\tif (config.customTransformInput) newValue = config.customTransformInput({\n\t\t\t\tdata: newValue,\n\t\t\t\tfieldAttributes: fieldAttr,\n\t\t\t\tfield: fieldName,\n\t\t\t\tmodel: getModelName(model),\n\t\t\t\tschema,\n\t\t\t\toptions,\n\t\t\t\taction\n\t\t\t});\n\t\t\treturn {\n\t\t\t\toperator,\n\t\t\t\tconnector,\n\t\t\t\tfield: fieldName,\n\t\t\t\tvalue: newValue,\n\t\t\t\tmode\n\t\t\t};\n\t\t});\n\t};\n\tconst transformJoinClause = (baseModel, unsanitizedJoin, select) => {\n\t\tif (!unsanitizedJoin) return void 0;\n\t\tif (Object.keys(unsanitizedJoin).length === 0) return void 0;\n\t\tconst transformedJoin = {};\n\t\tfor (const [model, join] of Object.entries(unsanitizedJoin)) {\n\t\t\tif (!join) continue;\n\t\t\tconst defaultModelName = getDefaultModelName(model);\n\t\t\tconst defaultBaseModelName = getDefaultModelName(baseModel);\n\t\t\tlet foreignKeys = Object.entries(schema[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName);\n\t\t\tlet isForwardJoin = true;\n\t\t\tif (!foreignKeys.length) {\n\t\t\t\tforeignKeys = Object.entries(schema[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName);\n\t\t\t\tisForwardJoin = false;\n\t\t\t}\n\t\t\tif (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`);\n\t\t\telse if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`);\n\t\t\tconst [foreignKey, foreignKeyAttributes] = foreignKeys[0];\n\t\t\tif (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`);\n\t\t\tlet from;\n\t\t\tlet to;\n\t\t\tlet requiredSelectField;\n\t\t\tif (isForwardJoin) {\n\t\t\t\trequiredSelectField = foreignKeyAttributes.references.field;\n\t\t\t\tfrom = getFieldName({\n\t\t\t\t\tmodel: baseModel,\n\t\t\t\t\tfield: requiredSelectField\n\t\t\t\t});\n\t\t\t\tto = getFieldName({\n\t\t\t\t\tmodel,\n\t\t\t\t\tfield: foreignKey\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\trequiredSelectField = foreignKey;\n\t\t\t\tfrom = getFieldName({\n\t\t\t\t\tmodel: baseModel,\n\t\t\t\t\tfield: requiredSelectField\n\t\t\t\t});\n\t\t\t\tto = getFieldName({\n\t\t\t\t\tmodel,\n\t\t\t\t\tfield: foreignKeyAttributes.references.field\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (select && !select.includes(requiredSelectField)) select.push(requiredSelectField);\n\t\t\tconst isUnique = to === \"id\" ? true : foreignKeyAttributes.unique ?? false;\n\t\t\tlet limit = options.advanced?.database?.defaultFindManyLimit ?? 100;\n\t\t\tif (isUnique) limit = 1;\n\t\t\telse if (typeof join === \"object\" && typeof join.limit === \"number\") limit = join.limit;\n\t\t\ttransformedJoin[getModelName(model)] = {\n\t\t\t\ton: {\n\t\t\t\t\tfrom,\n\t\t\t\t\tto\n\t\t\t\t},\n\t\t\t\tlimit,\n\t\t\t\trelation: isUnique ? \"one-to-one\" : \"one-to-many\"\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tjoin: transformedJoin,\n\t\t\tselect\n\t\t};\n\t};\n\t/**\n\t* Handle joins by making separate queries and combining results (fallback for adapters that don't support native joins).\n\t*/\n\tconst handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => {\n\t\tif (!baseData) return baseData;\n\t\tconst modelName = getModelName(joinModel);\n\t\tconst field = joinConfig.on.to;\n\t\tconst value = baseData[getDefaultFieldName({\n\t\t\tfield: joinConfig.on.from,\n\t\t\tmodel: baseModel\n\t\t})];\n\t\tif (value === null || value === void 0) return joinConfig.relation === \"one-to-one\" ? null : [];\n\t\tlet result;\n\t\tconst where = transformWhereClause({\n\t\t\tmodel: modelName,\n\t\t\twhere: [{\n\t\t\t\tfield,\n\t\t\t\tvalue,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}],\n\t\t\taction: \"findOne\"\n\t\t});\n\t\ttry {\n\t\t\tif (joinConfig.relation === \"one-to-one\") result = await withSpan(`db findOne ${modelName}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"findOne\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: modelName\n\t\t\t}, () => adapterInstance.findOne({\n\t\t\t\tmodel: modelName,\n\t\t\t\twhere\n\t\t\t}));\n\t\t\telse {\n\t\t\t\tconst limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;\n\t\t\t\tresult = await withSpan(`db findMany ${modelName}`, {\n\t\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"findMany\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: modelName\n\t\t\t\t}, () => adapterInstance.findMany({\n\t\t\t\t\tmodel: modelName,\n\t\t\t\t\twhere,\n\t\t\t\t\tlimit\n\t\t\t\t}));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Failed to query fallback join for model ${modelName}:`, {\n\t\t\t\twhere,\n\t\t\t\tlimit: joinConfig.limit\n\t\t\t});\n\t\t\tconsole.error(error);\n\t\t\tthrow error;\n\t\t}\n\t\treturn result;\n\t};\n\tconst adapterInstance = customAdapter({\n\t\toptions,\n\t\tschema,\n\t\tdebugLog,\n\t\tgetFieldName,\n\t\tgetModelName,\n\t\tgetDefaultModelName,\n\t\tgetDefaultFieldName,\n\t\tgetFieldAttributes,\n\t\ttransformInput,\n\t\ttransformOutput,\n\t\ttransformWhereClause\n\t});\n\tlet lazyLoadTransaction = null;\n\tconst adapter = {\n\t\ttransaction: async (cb) => {\n\t\t\tif (!lazyLoadTransaction) if (!config.transaction) lazyLoadTransaction = createAsIsTransaction(adapter);\n\t\t\telse {\n\t\t\t\tlogger.debug(`[${config.adapterName}] - Using provided transaction implementation.`);\n\t\t\t\tlazyLoadTransaction = config.transaction;\n\t\t\t}\n\t\t\treturn lazyLoadTransaction(cb);\n\t\t},\n\t\tcreate: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tif (\"id\" in unsafeData && typeof unsafeData.id !== \"undefined\" && !forceAllowId) {\n\t\t\t\tlogger.warn(`[${config.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \\`forceAllowId\\` parameter. The id will be ignored.`);\n\t\t\t\tconst stack = (/* @__PURE__ */ new Error()).stack?.split(\"\\n\").filter((_, i) => i !== 1).join(\"\\n\").replace(\"Error:\", \"Create method with `id` being called at:\");\n\t\t\t\tconsole.log(stack);\n\t\t\t\tunsafeData.id = void 0;\n\t\t\t}\n\t\t\tdebugLog({ method: \"create\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod(\"create\")} ${formatAction(\"Unsafe Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: unsafeData\n\t\t\t});\n\t\t\tlet data = unsafeData;\n\t\t\tif (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, \"create\", forceAllowId);\n\t\t\tdebugLog({ method: \"create\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod(\"create\")} ${formatAction(\"Parsed Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata\n\t\t\t});\n\t\t\tconst res = await withSpan(`db create ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"create\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.create({\n\t\t\t\tdata,\n\t\t\t\tmodel\n\t\t\t}));\n\t\t\tdebugLog({ method: \"create\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod(\"create\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tres\n\t\t\t});\n\t\t\tlet transformed = res;\n\t\t\tif (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0);\n\t\t\tdebugLog({ method: \"create\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod(\"create\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: transformed\n\t\t\t});\n\t\t\treturn transformed;\n\t\t},\n\t\tupdate: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"update\"\n\t\t\t});\n\t\t\tdebugLog({ method: \"update\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod(\"update\")} ${formatAction(\"Unsafe Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: unsafeData\n\t\t\t});\n\t\t\tlet data = unsafeData;\n\t\t\tif (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, \"update\");\n\t\t\tdebugLog({ method: \"update\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod(\"update\")} ${formatAction(\"Parsed Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata\n\t\t\t});\n\t\t\tconst res = await withSpan(`db update ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"update\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.update({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tupdate: data\n\t\t\t}));\n\t\t\tdebugLog({ method: \"update\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod(\"update\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\tlet transformed = res;\n\t\t\tif (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0);\n\t\t\tdebugLog({ method: \"update\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod(\"update\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: transformed\n\t\t\t});\n\t\t\treturn transformed;\n\t\t},\n\t\tupdateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"updateMany\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tdebugLog({ method: \"updateMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod(\"updateMany\")} ${formatAction(\"Unsafe Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: unsafeData\n\t\t\t});\n\t\t\tlet data = unsafeData;\n\t\t\tif (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, \"update\");\n\t\t\tdebugLog({ method: \"updateMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod(\"updateMany\")} ${formatAction(\"Parsed Input\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata\n\t\t\t});\n\t\t\tconst updatedCount = await withSpan(`db updateMany ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"updateMany\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.updateMany({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tupdate: data\n\t\t\t}));\n\t\t\tdebugLog({ method: \"updateMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod(\"updateMany\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: updatedCount\n\t\t\t});\n\t\t\tdebugLog({ method: \"updateMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod(\"updateMany\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: updatedCount\n\t\t\t});\n\t\t\treturn updatedCount;\n\t\t},\n\t\tfindOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"findOne\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tlet join;\n\t\t\tlet passJoinToAdapter = true;\n\t\t\tif (!config.disableTransformJoin) {\n\t\t\t\tconst result = transformJoinClause(unsafeModel, unsafeJoin, select);\n\t\t\t\tif (result) {\n\t\t\t\t\tjoin = result.join;\n\t\t\t\t\tselect = result.select;\n\t\t\t\t}\n\t\t\t\tif (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false;\n\t\t\t} else join = unsafeJoin;\n\t\t\tdebugLog({ method: \"findOne\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod(\"findOne\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tselect,\n\t\t\t\tjoin\n\t\t\t});\n\t\t\tconst res = await withSpan(`db findOne ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"findOne\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.findOne({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tselect,\n\t\t\t\tjoin: passJoinToAdapter ? join : void 0\n\t\t\t}));\n\t\t\tdebugLog({ method: \"findOne\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod(\"findOne\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\tlet transformed = res;\n\t\t\tif (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join);\n\t\t\tdebugLog({ method: \"findOne\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod(\"findOne\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: transformed\n\t\t\t});\n\t\t\treturn transformed;\n\t\t},\n\t\tfindMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, select, sortBy, offset, join: unsafeJoin }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"findMany\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tlet join;\n\t\t\tlet passJoinToAdapter = true;\n\t\t\tif (!config.disableTransformJoin) {\n\t\t\t\tconst result = transformJoinClause(unsafeModel, unsafeJoin, select);\n\t\t\t\tif (result) {\n\t\t\t\t\tjoin = result.join;\n\t\t\t\t\tselect = result.select;\n\t\t\t\t}\n\t\t\t\tif (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false;\n\t\t\t} else join = unsafeJoin;\n\t\t\tdebugLog({ method: \"findMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod(\"findMany\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\tsortBy,\n\t\t\t\toffset,\n\t\t\t\tjoin\n\t\t\t});\n\t\t\tconst res = await withSpan(`db findMany ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"findMany\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.findMany({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\tselect,\n\t\t\t\tsortBy,\n\t\t\t\toffset,\n\t\t\t\tjoin: passJoinToAdapter ? join : void 0\n\t\t\t}));\n\t\t\tdebugLog({ method: \"findMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod(\"findMany\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\tlet transformed = res;\n\t\t\tif (!config.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => {\n\t\t\t\treturn await transformOutput(r, unsafeModel, void 0, join);\n\t\t\t}));\n\t\t\tdebugLog({ method: \"findMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod(\"findMany\")} ${formatAction(\"Parsed Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: transformed\n\t\t\t});\n\t\t\treturn transformed;\n\t\t},\n\t\tdelete: async ({ model: unsafeModel, where: unsafeWhere }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"delete\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tdebugLog({ method: \"delete\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod(\"delete\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t});\n\t\t\tawait withSpan(`db delete ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"delete\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.delete({\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t}));\n\t\t\tdebugLog({ method: \"delete\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod(\"delete\")} ${formatAction(\"DB Result\")}:`, { model });\n\t\t},\n\t\tdeleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"deleteMany\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tdebugLog({ method: \"deleteMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod(\"deleteMany\")} ${formatAction(\"DeleteMany\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t});\n\t\t\tconst res = await withSpan(`db deleteMany ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"deleteMany\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.deleteMany({\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t}));\n\t\t\tdebugLog({ method: \"deleteMany\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod(\"deleteMany\")} ${formatAction(\"DB Result\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\treturn res;\n\t\t},\n\t\tcount: async ({ model: unsafeModel, where: unsafeWhere }) => {\n\t\t\ttransactionId++;\n\t\t\tconst thisTransactionId = transactionId;\n\t\t\tconst model = getModelName(unsafeModel);\n\t\t\tconst where = transformWhereClause({\n\t\t\t\tmodel: unsafeModel,\n\t\t\t\twhere: unsafeWhere,\n\t\t\t\taction: \"count\"\n\t\t\t});\n\t\t\tunsafeModel = getDefaultModelName(unsafeModel);\n\t\t\tdebugLog({ method: \"count\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod(\"count\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t});\n\t\t\tconst res = await withSpan(`db count ${model}`, {\n\t\t\t\t[ATTR_DB_OPERATION_NAME]: \"count\",\n\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model\n\t\t\t}, () => adapterInstance.count({\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t}));\n\t\t\tdebugLog({ method: \"count\" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod(\"count\")}:`, {\n\t\t\t\tmodel,\n\t\t\t\tdata: res\n\t\t\t});\n\t\t\treturn res;\n\t\t},\n\t\tcreateSchema: adapterInstance.createSchema ? async (_, file) => {\n\t\t\tconst tables = getAuthTables(options);\n\t\t\tif (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session;\n\t\t\treturn adapterInstance.createSchema({\n\t\t\t\tfile,\n\t\t\t\ttables\n\t\t\t});\n\t\t} : void 0,\n\t\toptions: {\n\t\t\tadapterConfig: config,\n\t\t\t...adapterInstance.options ?? {}\n\t\t},\n\t\tid: config.adapterId,\n\t\t...config.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: {\n\t\t\tresetDebugLogs() {\n\t\t\t\tdebugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId);\n\t\t\t},\n\t\t\tprintDebugLogs() {\n\t\t\t\tconst separator = `\u2500`.repeat(80);\n\t\t\t\tconst logs = debugLogs.filter((log) => log.instance === uniqueAdapterFactoryInstanceId);\n\t\t\t\tif (logs.length === 0) return;\n\t\t\t\tconst log = logs.reverse().map((log) => {\n\t\t\t\t\tlog.args[0] = `\\n${log.args[0]}`;\n\t\t\t\t\treturn [...log.args, \"\\n\"];\n\t\t\t\t}).reduce((prev, curr) => {\n\t\t\t\t\treturn [...curr, ...prev];\n\t\t\t\t}, [`\\n${separator}`]);\n\t\t\t\tconsole.log(...log);\n\t\t\t}\n\t\t} } : {}\n\t};\n\treturn adapter;\n};\nfunction formatTransactionId(transactionId) {\n\tif (getColorDepth() < 8) return `#${transactionId}`;\n\treturn `${TTY_COLORS.fg.magenta}#${transactionId}${TTY_COLORS.reset}`;\n}\nfunction formatStep(step, total) {\n\treturn `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`;\n}\nfunction formatMethod(method) {\n\treturn `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`;\n}\nfunction formatAction(action) {\n\treturn `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`;\n}\n//#endregion\nexport { createAdapterFactory };\n", "import { initGetDefaultModelName } from \"./get-default-model-name.mjs\";\nimport { initGetDefaultFieldName } from \"./get-default-field-name.mjs\";\nimport { initGetIdField } from \"./get-id-field.mjs\";\nimport { initGetFieldAttributes } from \"./get-field-attributes.mjs\";\nimport { initGetFieldName } from \"./get-field-name.mjs\";\nimport { initGetModelName } from \"./get-model-name.mjs\";\nimport { deepmerge, withApplyDefault } from \"./utils.mjs\";\nimport { createAdapterFactory } from \"./factory.mjs\";\n//#region src/db/adapter/index.ts\nconst whereOperators = [\n\t\"eq\",\n\t\"ne\",\n\t\"lt\",\n\t\"lte\",\n\t\"gt\",\n\t\"gte\",\n\t\"in\",\n\t\"not_in\",\n\t\"contains\",\n\t\"starts_with\",\n\t\"ends_with\"\n];\n//#endregion\nexport { createAdapterFactory, deepmerge, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName, whereOperators, withApplyDefault };\n", "import { createAdapterFactory } from \"@better-auth/core/db/adapter\";\nimport { logger } from \"@better-auth/core/env\";\n//#region src/query-builders.ts\n/**\n* Case-insensitive in-memory comparison helpers.\n* Used when evaluating where clauses in the memory adapter.\n*/\nfunction insensitiveCompare(a, b) {\n\tif (typeof a === \"string\" && typeof b === \"string\") return a.toLowerCase() === b.toLowerCase();\n\treturn a === b;\n}\nfunction insensitiveIn(recordVal, values) {\n\tif (typeof recordVal !== \"string\") return values.includes(recordVal);\n\treturn values.some((v) => typeof v === \"string\" && recordVal.toLowerCase() === v.toLowerCase());\n}\nfunction insensitiveNotIn(recordVal, values) {\n\treturn !insensitiveIn(recordVal, values);\n}\nfunction insensitiveContains(recordVal, value) {\n\tif (typeof recordVal !== \"string\" || typeof value !== \"string\") return false;\n\treturn recordVal.toLowerCase().includes(value.toLowerCase());\n}\nfunction insensitiveStartsWith(recordVal, value) {\n\tif (typeof recordVal !== \"string\" || typeof value !== \"string\") return false;\n\treturn recordVal.toLowerCase().startsWith(value.toLowerCase());\n}\nfunction insensitiveEndsWith(recordVal, value) {\n\tif (typeof recordVal !== \"string\" || typeof value !== \"string\") return false;\n\treturn recordVal.toLowerCase().endsWith(value.toLowerCase());\n}\n//#endregion\n//#region src/memory-adapter.ts\nconst memoryAdapter = (db, config) => {\n\tlet lazyOptions = null;\n\tconst adapterCreator = createAdapterFactory({\n\t\tconfig: {\n\t\t\tadapterId: \"memory\",\n\t\t\tadapterName: \"Memory Adapter\",\n\t\t\tusePlural: false,\n\t\t\tdebugLogs: config?.debugLogs || false,\n\t\t\tsupportsArrays: true,\n\t\t\tcustomTransformInput(props) {\n\t\t\t\tif (props.options.advanced?.database?.generateId === \"serial\" && props.field === \"id\" && props.action === \"create\") return db[props.model].length + 1;\n\t\t\t\treturn props.data;\n\t\t\t},\n\t\t\ttransaction: async (cb) => {\n\t\t\t\tconst clone = structuredClone(db);\n\t\t\t\ttry {\n\t\t\t\t\treturn await cb(adapterCreator(lazyOptions));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tObject.keys(db).forEach((key) => {\n\t\t\t\t\t\tdb[key] = clone[key];\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tadapter: ({ getFieldName, getDefaultFieldName, options, getModelName }) => {\n\t\t\tconst applySortToRecords = (records, sortBy, model) => {\n\t\t\t\tif (!sortBy) return records;\n\t\t\t\treturn records.sort((a, b) => {\n\t\t\t\t\tconst field = getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield: sortBy.field\n\t\t\t\t\t});\n\t\t\t\t\tconst aValue = a[field];\n\t\t\t\t\tconst bValue = b[field];\n\t\t\t\t\tlet comparison = 0;\n\t\t\t\t\tif (aValue == null && bValue == null) comparison = 0;\n\t\t\t\t\telse if (aValue == null) comparison = -1;\n\t\t\t\t\telse if (bValue == null) comparison = 1;\n\t\t\t\t\telse if (typeof aValue === \"string\" && typeof bValue === \"string\") comparison = aValue.localeCompare(bValue);\n\t\t\t\t\telse if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime();\n\t\t\t\t\telse if (typeof aValue === \"number\" && typeof bValue === \"number\") comparison = aValue - bValue;\n\t\t\t\t\telse if (typeof aValue === \"boolean\" && typeof bValue === \"boolean\") comparison = aValue === bValue ? 0 : aValue ? 1 : -1;\n\t\t\t\t\telse comparison = String(aValue).localeCompare(String(bValue));\n\t\t\t\t\treturn sortBy.direction === \"asc\" ? comparison : -comparison;\n\t\t\t\t});\n\t\t\t};\n\t\t\tfunction convertWhereClause(where, model, join, select) {\n\t\t\t\tconst baseRecords = (() => {\n\t\t\t\t\tconst table = db[model];\n\t\t\t\t\tif (!table) {\n\t\t\t\t\t\tlogger.error(`[MemoryAdapter] Model ${model} not found in the DB`, Object.keys(db));\n\t\t\t\t\t\tthrow new Error(`Model ${model} not found`);\n\t\t\t\t\t}\n\t\t\t\t\tconst evalClause = (record, clause) => {\n\t\t\t\t\t\tconst { field, value, operator, mode = \"sensitive\" } = clause;\n\t\t\t\t\t\tconst isInsensitive = mode === \"insensitive\" && (typeof value === \"string\" || Array.isArray(value) && value.every((v) => typeof v === \"string\"));\n\t\t\t\t\t\tswitch (operator) {\n\t\t\t\t\t\t\tcase \"in\":\n\t\t\t\t\t\t\t\tif (!Array.isArray(value)) throw new Error(\"Value must be an array\");\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveIn(record[field], value);\n\t\t\t\t\t\t\t\treturn value.includes(record[field]);\n\t\t\t\t\t\t\tcase \"not_in\":\n\t\t\t\t\t\t\t\tif (!Array.isArray(value)) throw new Error(\"Value must be an array\");\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveNotIn(record[field], value);\n\t\t\t\t\t\t\t\treturn !value.includes(record[field]);\n\t\t\t\t\t\t\tcase \"contains\":\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveContains(record[field], value);\n\t\t\t\t\t\t\t\treturn record[field]?.includes(value);\n\t\t\t\t\t\t\tcase \"starts_with\":\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveStartsWith(record[field], value);\n\t\t\t\t\t\t\t\treturn record[field].startsWith(value);\n\t\t\t\t\t\t\tcase \"ends_with\":\n\t\t\t\t\t\t\t\tif (isInsensitive) return insensitiveEndsWith(record[field], value);\n\t\t\t\t\t\t\t\treturn record[field].endsWith(value);\n\t\t\t\t\t\t\tcase \"ne\": return isInsensitive ? !insensitiveCompare(record[field], value) : record[field] !== value;\n\t\t\t\t\t\t\tcase \"gt\": return value != null && Boolean(record[field] > value);\n\t\t\t\t\t\t\tcase \"gte\": return value != null && Boolean(record[field] >= value);\n\t\t\t\t\t\t\tcase \"lt\": return value != null && Boolean(record[field] < value);\n\t\t\t\t\t\t\tcase \"lte\": return value != null && Boolean(record[field] <= value);\n\t\t\t\t\t\t\tdefault: return isInsensitive ? insensitiveCompare(record[field], value) : record[field] === value;\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\tlet records = table.filter((record) => {\n\t\t\t\t\t\tif (!where.length || where.length === 0) return true;\n\t\t\t\t\t\tlet result = evalClause(record, where[0]);\n\t\t\t\t\t\tfor (const clause of where) {\n\t\t\t\t\t\t\tconst clauseResult = evalClause(record, clause);\n\t\t\t\t\t\t\tif (clause.connector === \"OR\") result = result || clauseResult;\n\t\t\t\t\t\t\telse result = result && clauseResult;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t});\n\t\t\t\t\tif (select?.length && select.length > 0) records = records.map((record) => Object.fromEntries(Object.entries(record).filter(([key]) => select.includes(getDefaultFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield: key\n\t\t\t\t\t})))));\n\t\t\t\t\treturn records;\n\t\t\t\t})();\n\t\t\t\tif (!join) return baseRecords;\n\t\t\t\tconst grouped = /* @__PURE__ */ new Map();\n\t\t\t\tconst seenIds = /* @__PURE__ */ new Map();\n\t\t\t\tfor (const baseRecord of baseRecords) {\n\t\t\t\t\tconst baseId = String(baseRecord.id);\n\t\t\t\t\tif (!grouped.has(baseId)) {\n\t\t\t\t\t\tconst nested = { ...baseRecord };\n\t\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\t\tif (joinAttr.relation === \"one-to-one\") nested[joinModelName] = null;\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tnested[joinModelName] = [];\n\t\t\t\t\t\t\t\tseenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgrouped.set(baseId, nested);\n\t\t\t\t\t}\n\t\t\t\t\tconst nestedEntry = grouped.get(baseId);\n\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\tconst joinTable = db[joinModelName];\n\t\t\t\t\t\tif (!joinTable) {\n\t\t\t\t\t\t\tlogger.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db));\n\t\t\t\t\t\t\tthrow new Error(`JoinOption model ${joinModelName} not found`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]);\n\t\t\t\t\t\tif (joinAttr.relation === \"one-to-one\") nestedEntry[joinModelName] = matchingRecords[0] || null;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst seenSet = seenIds.get(`${baseId}-${joinModel}`);\n\t\t\t\t\t\t\tconst limit = joinAttr.limit ?? 100;\n\t\t\t\t\t\t\tlet count = 0;\n\t\t\t\t\t\t\tfor (const matchingRecord of matchingRecords) {\n\t\t\t\t\t\t\t\tif (count >= limit) break;\n\t\t\t\t\t\t\t\tif (!seenSet.has(matchingRecord.id)) {\n\t\t\t\t\t\t\t\t\tnestedEntry[joinModelName].push(matchingRecord);\n\t\t\t\t\t\t\t\t\tseenSet.add(matchingRecord.id);\n\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn Array.from(grouped.values());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcreate: async ({ model, data }) => {\n\t\t\t\t\tif (options.advanced?.database?.generateId === \"serial\") data.id = db[getModelName(model)].length + 1;\n\t\t\t\t\tif (!db[model]) db[model] = [];\n\t\t\t\t\tdb[model].push(data);\n\t\t\t\t\treturn data;\n\t\t\t\t},\n\t\t\t\tfindOne: async ({ model, where, select, join }) => {\n\t\t\t\t\tconst res = convertWhereClause(where, model, join, select);\n\t\t\t\t\tif (join) {\n\t\t\t\t\t\tconst resArray = res;\n\t\t\t\t\t\tif (!resArray.length) return null;\n\t\t\t\t\t\treturn resArray[0];\n\t\t\t\t\t}\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t},\n\t\t\t\tfindMany: async ({ model, where, sortBy, limit, select, offset, join }) => {\n\t\t\t\t\tconst res = convertWhereClause(where || [], model, join, select);\n\t\t\t\t\tif (join) {\n\t\t\t\t\t\tconst resArray = res;\n\t\t\t\t\t\tif (!resArray.length) return [];\n\t\t\t\t\t\tapplySortToRecords(resArray, sortBy, model);\n\t\t\t\t\t\tlet paginatedRecords = resArray;\n\t\t\t\t\t\tif (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset);\n\t\t\t\t\t\tif (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit);\n\t\t\t\t\t\treturn paginatedRecords;\n\t\t\t\t\t}\n\t\t\t\t\tlet table = applySortToRecords(res, sortBy, model);\n\t\t\t\t\tif (offset !== void 0) table = table.slice(offset);\n\t\t\t\t\tif (limit !== void 0) table = table.slice(0, limit);\n\t\t\t\t\treturn table || [];\n\t\t\t\t},\n\t\t\t\tcount: async ({ model, where }) => {\n\t\t\t\t\tif (where) return convertWhereClause(where, model).length;\n\t\t\t\t\treturn db[model].length;\n\t\t\t\t},\n\t\t\t\tupdate: async ({ model, where, update }) => {\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tres.forEach((record) => {\n\t\t\t\t\t\tObject.assign(record, update);\n\t\t\t\t\t});\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t},\n\t\t\t\tdelete: async ({ model, where }) => {\n\t\t\t\t\tconst table = db[model];\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tdb[model] = table.filter((record) => !res.includes(record));\n\t\t\t\t},\n\t\t\t\tdeleteMany: async ({ model, where }) => {\n\t\t\t\t\tconst table = db[model];\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tlet count = 0;\n\t\t\t\t\tdb[model] = table.filter((record) => {\n\t\t\t\t\t\tif (res.includes(record)) {\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn !res.includes(record);\n\t\t\t\t\t});\n\t\t\t\t\treturn count;\n\t\t\t\t},\n\t\t\t\tupdateMany({ model, where, update }) {\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tres.forEach((record) => {\n\t\t\t\t\t\tObject.assign(record, update);\n\t\t\t\t\t});\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n\treturn (options) => {\n\t\tlazyOptions = options;\n\t\treturn adapterCreator(options);\n\t};\n};\n//#endregion\nexport { memoryAdapter };\n", "/// \nexport function isEmpty(obj) {\n if (Array.isArray(obj) || isString(obj) || isBuffer(obj)) {\n return obj.length === 0;\n }\n else if (obj) {\n return Object.keys(obj).length === 0;\n }\n return false;\n}\nexport function isUndefined(obj) {\n return typeof obj === 'undefined' || obj === undefined;\n}\nexport function isString(obj) {\n return typeof obj === 'string';\n}\nexport function isNumber(obj) {\n return typeof obj === 'number';\n}\nexport function isBoolean(obj) {\n return typeof obj === 'boolean';\n}\nexport function isNull(obj) {\n return obj === null;\n}\nexport function isDate(obj) {\n return obj instanceof Date;\n}\nexport function isBigInt(obj) {\n return typeof obj === 'bigint';\n}\n// Don't change the returnd type to `obj is Buffer` to not create a\n// hard dependency to node.\nexport function isBuffer(obj) {\n return typeof Buffer !== 'undefined' && Buffer.isBuffer(obj);\n}\nexport function isFunction(obj) {\n return typeof obj === 'function';\n}\nexport function isObject(obj) {\n return typeof obj === 'object' && obj !== null;\n}\nexport function isArrayBufferOrView(obj) {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\nexport function isPlainObject(obj) {\n if (!isObject(obj) || getTag(obj) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(obj) === null) {\n return true;\n }\n let proto = obj;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(obj) === proto;\n}\nexport function getLast(arr) {\n return arr[arr.length - 1];\n}\nexport function freeze(obj) {\n return Object.freeze(obj);\n}\nexport function asArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return [arg];\n }\n}\nexport function asReadonlyArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return freeze([arg]);\n }\n}\nexport function isReadonlyArray(arg) {\n return Array.isArray(arg);\n}\nexport function noop(obj) {\n return obj;\n}\nexport function compare(obj1, obj2) {\n if (isReadonlyArray(obj1) && isReadonlyArray(obj2)) {\n return compareArrays(obj1, obj2);\n }\n else if (isObject(obj1) && isObject(obj2)) {\n return compareObjects(obj1, obj2);\n }\n return obj1 === obj2;\n}\nfunction compareArrays(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n for (let i = 0; i < arr1.length; ++i) {\n if (!compare(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nfunction compareObjects(obj1, obj2) {\n if (isBuffer(obj1) && isBuffer(obj2)) {\n return compareBuffers(obj1, obj2);\n }\n else if (isDate(obj1) && isDate(obj2)) {\n return compareDates(obj1, obj2);\n }\n return compareGenericObjects(obj1, obj2);\n}\nfunction compareBuffers(buf1, buf2) {\n return Buffer.compare(buf1, buf2) === 0;\n}\nfunction compareDates(date1, date2) {\n return date1.getTime() === date2.getTime();\n}\nfunction compareGenericObjects(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) {\n return false;\n }\n for (const key of keys1) {\n if (!compare(obj1[key], obj2[key])) {\n return false;\n }\n }\n return true;\n}\nconst toString = Object.prototype.toString;\nfunction getTag(value) {\n if (value == null) {\n return value === undefined ? '[object Undefined]' : '[object Null]';\n }\n return toString.call(value);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AlterTableNode = freeze({\n is(node) {\n return node.kind === 'AlterTableNode';\n },\n create(table) {\n return freeze({\n kind: 'AlterTableNode',\n table,\n });\n },\n cloneWithTableProps(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n cloneWithColumnAlteration(node, columnAlteration) {\n return freeze({\n ...node,\n columnAlterations: node.columnAlterations\n ? [...node.columnAlterations, columnAlteration]\n : [columnAlteration],\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const IdentifierNode = freeze({\n is(node) {\n return node.kind === 'IdentifierNode';\n },\n create(name) {\n return freeze({\n kind: 'IdentifierNode',\n name,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CreateIndexNode = freeze({\n is(node) {\n return node.kind === 'CreateIndexNode';\n },\n create(name) {\n return freeze({\n kind: 'CreateIndexNode',\n name: IdentifierNode.create(name),\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n cloneWithColumns(node, columns) {\n return freeze({\n ...node,\n columns: [...(node.columns || []), ...columns],\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CreateSchemaNode = freeze({\n is(node) {\n return node.kind === 'CreateSchemaNode';\n },\n create(schema, params) {\n return freeze({\n kind: 'CreateSchemaNode',\n schema: IdentifierNode.create(schema),\n ...params,\n });\n },\n cloneWith(createSchema, params) {\n return freeze({\n ...createSchema,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nexport const ON_COMMIT_ACTIONS = ['preserve rows', 'delete rows', 'drop'];\n/**\n * @internal\n */\nexport const CreateTableNode = freeze({\n is(node) {\n return node.kind === 'CreateTableNode';\n },\n create(table) {\n return freeze({\n kind: 'CreateTableNode',\n table,\n columns: freeze([]),\n });\n },\n cloneWithColumn(createTable, column) {\n return freeze({\n ...createTable,\n columns: freeze([...createTable.columns, column]),\n });\n },\n cloneWithConstraint(createTable, constraint) {\n return freeze({\n ...createTable,\n constraints: createTable.constraints\n ? freeze([...createTable.constraints, constraint])\n : freeze([constraint]),\n });\n },\n cloneWithFrontModifier(createTable, modifier) {\n return freeze({\n ...createTable,\n frontModifiers: createTable.frontModifiers\n ? freeze([...createTable.frontModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWithEndModifier(createTable, modifier) {\n return freeze({\n ...createTable,\n endModifiers: createTable.endModifiers\n ? freeze([...createTable.endModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWith(createTable, params) {\n return freeze({\n ...createTable,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const SchemableIdentifierNode = freeze({\n is(node) {\n return node.kind === 'SchemableIdentifierNode';\n },\n create(identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n identifier: IdentifierNode.create(identifier),\n });\n },\n createWithSchema(schema, identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n schema: IdentifierNode.create(schema),\n identifier: IdentifierNode.create(identifier),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const DropIndexNode = freeze({\n is(node) {\n return node.kind === 'DropIndexNode';\n },\n create(name, params) {\n return freeze({\n kind: 'DropIndexNode',\n name: SchemableIdentifierNode.create(name),\n ...params,\n });\n },\n cloneWith(dropIndex, props) {\n return freeze({\n ...dropIndex,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const DropSchemaNode = freeze({\n is(node) {\n return node.kind === 'DropSchemaNode';\n },\n create(schema, params) {\n return freeze({\n kind: 'DropSchemaNode',\n schema: IdentifierNode.create(schema),\n ...params,\n });\n },\n cloneWith(dropSchema, params) {\n return freeze({\n ...dropSchema,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const DropTableNode = freeze({\n is(node) {\n return node.kind === 'DropTableNode';\n },\n create(table, params) {\n return freeze({\n kind: 'DropTableNode',\n table,\n ...params,\n });\n },\n cloneWith(dropIndex, params) {\n return freeze({\n ...dropIndex,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AliasNode = freeze({\n is(node) {\n return node.kind === 'AliasNode';\n },\n create(node, alias) {\n return freeze({\n kind: 'AliasNode',\n node,\n alias,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const TableNode = freeze({\n is(node) {\n return node.kind === 'TableNode';\n },\n create(table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.create(table),\n });\n },\n createWithSchema(schema, table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.createWithSchema(schema, table),\n });\n },\n});\n", "/// \nimport { isFunction, isObject } from '../util/object-utils.js';\nexport function isOperationNodeSource(obj) {\n return isObject(obj) && isFunction(obj.toOperationNode);\n}\n", "/// \nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport function isExpression(obj) {\n return isObject(obj) && 'expressionType' in obj && isOperationNodeSource(obj);\n}\nexport function isAliasedExpression(obj) {\n return (isObject(obj) &&\n 'expression' in obj &&\n isString(obj.alias) &&\n isOperationNodeSource(obj));\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectModifierNode = freeze({\n is(node) {\n return node.kind === 'SelectModifierNode';\n },\n create(modifier, of) {\n return freeze({\n kind: 'SelectModifierNode',\n modifier,\n of,\n });\n },\n createWithExpression(modifier) {\n return freeze({\n kind: 'SelectModifierNode',\n rawModifier: modifier,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AndNode = freeze({\n is(node) {\n return node.kind === 'AndNode';\n },\n create(left, right) {\n return freeze({\n kind: 'AndNode',\n left,\n right,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrNode = freeze({\n is(node) {\n return node.kind === 'OrNode';\n },\n create(left, right) {\n return freeze({\n kind: 'OrNode',\n left,\n right,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const OnNode = freeze({\n is(node) {\n return node.kind === 'OnNode';\n },\n create(filter) {\n return freeze({\n kind: 'OnNode',\n on: filter,\n });\n },\n cloneWithOperation(onNode, operator, operation) {\n return freeze({\n ...onNode,\n on: operator === 'And'\n ? AndNode.create(onNode.on, operation)\n : OrNode.create(onNode.on, operation),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { OnNode } from './on-node.js';\n/**\n * @internal\n */\nexport const JoinNode = freeze({\n is(node) {\n return node.kind === 'JoinNode';\n },\n create(joinType, table) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: undefined,\n });\n },\n createWithOn(joinType, table, on) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: OnNode.create(on),\n });\n },\n cloneWithOn(joinNode, operation) {\n return freeze({\n ...joinNode,\n on: joinNode.on\n ? OnNode.cloneWithOperation(joinNode.on, 'And', operation)\n : OnNode.create(operation),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const BinaryOperationNode = freeze({\n is(node) {\n return node.kind === 'BinaryOperationNode';\n },\n create(leftOperand, operator, rightOperand) {\n return freeze({\n kind: 'BinaryOperationNode',\n leftOperand,\n operator,\n rightOperand,\n });\n },\n});\n", "/// \nimport { freeze, isString } from '../util/object-utils.js';\nexport const COMPARISON_OPERATORS = [\n '=',\n '==',\n '!=',\n '<>',\n '>',\n '>=',\n '<',\n '<=',\n 'in',\n 'not in',\n 'is',\n 'is not',\n 'like',\n 'not like',\n 'match',\n 'ilike',\n 'not ilike',\n '@>',\n '<@',\n '^@',\n '&&',\n '?',\n '?&',\n '?|',\n '!<',\n '!>',\n '<=>',\n '!~',\n '~',\n '~*',\n '!~*',\n '@@',\n '@@@',\n '!!',\n '<->',\n 'regexp',\n 'is distinct from',\n 'is not distinct from',\n];\nexport const ARITHMETIC_OPERATORS = [\n '+',\n '-',\n '*',\n '/',\n '%',\n '^',\n '&',\n '|',\n '#',\n '<<',\n '>>',\n];\nexport const JSON_OPERATORS = ['->', '->>'];\nexport const BINARY_OPERATORS = [\n ...COMPARISON_OPERATORS,\n ...ARITHMETIC_OPERATORS,\n '&&',\n '||',\n];\nexport const UNARY_FILTER_OPERATORS = ['exists', 'not exists'];\nexport const UNARY_OPERATORS = ['not', '-', ...UNARY_FILTER_OPERATORS];\nexport const OPERATORS = [\n ...BINARY_OPERATORS,\n ...JSON_OPERATORS,\n ...UNARY_OPERATORS,\n 'between',\n 'between symmetric',\n];\n/**\n * @internal\n */\nexport const OperatorNode = freeze({\n is(node) {\n return node.kind === 'OperatorNode';\n },\n create(operator) {\n return freeze({\n kind: 'OperatorNode',\n operator,\n });\n },\n});\nexport function isOperator(op) {\n return isString(op) && OPERATORS.includes(op);\n}\nexport function isBinaryOperator(op) {\n return isString(op) && BINARY_OPERATORS.includes(op);\n}\nexport function isComparisonOperator(op) {\n return isString(op) && COMPARISON_OPERATORS.includes(op);\n}\nexport function isArithmeticOperator(op) {\n return isString(op) && ARITHMETIC_OPERATORS.includes(op);\n}\nexport function isJSONOperator(op) {\n return isString(op) && JSON_OPERATORS.includes(op);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const ColumnNode = freeze({\n is(node) {\n return node.kind === 'ColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'ColumnNode',\n column: IdentifierNode.create(column),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectAllNode = freeze({\n is(node) {\n return node.kind === 'SelectAllNode';\n },\n create() {\n return freeze({\n kind: 'SelectAllNode',\n });\n },\n});\n", "/// \nimport { SelectAllNode } from './select-all-node.js';\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReferenceNode = freeze({\n is(node) {\n return node.kind === 'ReferenceNode';\n },\n create(column, table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column,\n });\n },\n createSelectAll(table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column: SelectAllNode.create(),\n });\n },\n});\n", "/// \nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseSimpleReferenceExpression } from '../parser/reference-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicReferenceBuilder {\n #dynamicReference;\n get dynamicReference() {\n return this.#dynamicReference;\n }\n /**\n * @private\n *\n * This needs to be here just so that the typings work. Without this\n * the generated .d.ts file contains no reference to the type param R\n * which causes this type to be equal to DynamicReferenceBuilder with\n * any R.\n */\n get refType() {\n return undefined;\n }\n constructor(reference) {\n this.#dynamicReference = reference;\n }\n toOperationNode() {\n return parseSimpleReferenceExpression(this.#dynamicReference);\n }\n}\nexport function isDynamicReferenceBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.dynamicReference));\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByItemNode = freeze({\n is(node) {\n return node.kind === 'OrderByItemNode';\n },\n create(orderBy, direction) {\n return freeze({\n kind: 'OrderByItemNode',\n orderBy,\n direction,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const RawNode = freeze({\n is(node) {\n return node.kind === 'RawNode';\n },\n create(sqlFragments, parameters) {\n return freeze({\n kind: 'RawNode',\n sqlFragments: freeze(sqlFragments),\n parameters: freeze(parameters),\n });\n },\n createWithSql(sql) {\n return RawNode.create([sql], []);\n },\n createWithChild(child) {\n return RawNode.create(['', ''], [child]);\n },\n createWithChildren(children) {\n return RawNode.create(new Array(children.length + 1).fill(''), children);\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CollateNode = freeze({\n is(node) {\n return node.kind === 'CollateNode';\n },\n create(collation) {\n return freeze({\n kind: 'CollateNode',\n collation: IdentifierNode.create(collation),\n });\n },\n});\n", "/// \nimport { CollateNode } from '../operation-node/collate-node.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OrderByItemBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds `desc` to the `order by` item.\n *\n * See {@link asc} for the opposite.\n */\n desc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('desc'),\n }),\n });\n }\n /**\n * Adds `asc` to the `order by` item.\n *\n * See {@link desc} for the opposite.\n */\n asc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('asc'),\n }),\n });\n }\n /**\n * Adds `nulls last` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsFirst} for the opposite.\n */\n nullsLast() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'last' }),\n });\n }\n /**\n * Adds `nulls first` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsLast} for the opposite.\n */\n nullsFirst() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'first' }),\n });\n }\n /**\n * Adds `collate ` to the `order by` item.\n */\n collate(collation) {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n collation: CollateNode.create(collation),\n }),\n });\n }\n toOperationNode() {\n return this.#props.node;\n }\n}\n", "/// \nconst LOGGED_MESSAGES = new Set();\n/**\n * Use for system-level logging, such as deprecation messages.\n * Logs a message and ensures it won't be logged again.\n */\nexport function logOnce(message) {\n if (LOGGED_MESSAGES.has(message)) {\n return;\n }\n LOGGED_MESSAGES.add(message);\n console.log(message);\n}\n", "/// \nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { isExpression } from '../expression/expression.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { OrderByItemBuilder } from '../query-builder/order-by-item-builder.js';\nimport { logOnce } from '../util/log-once.js';\nimport { isExpressionOrFactory, parseExpression, } from './expression-parser.js';\nimport { parseStringReference, } from './reference-parser.js';\nexport function isOrderByDirection(thing) {\n return thing === 'asc' || thing === 'desc';\n}\nexport function parseOrderBy(args) {\n if (args.length === 2) {\n return [parseOrderByItem(args[0], args[1])];\n }\n if (args.length === 1) {\n const [orderBy] = args;\n if (Array.isArray(orderBy)) {\n logOnce('orderBy(array) is deprecated, use multiple orderBy calls instead.');\n return orderBy.map((item) => parseOrderByItem(item));\n }\n return [parseOrderByItem(orderBy)];\n }\n throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`);\n}\nexport function parseOrderByItem(expr, modifiers) {\n const parsedRef = parseOrderByExpression(expr);\n if (OrderByItemNode.is(parsedRef)) {\n if (modifiers) {\n throw new Error('Cannot specify direction twice!');\n }\n return parsedRef;\n }\n return parseOrderByWithModifiers(parsedRef, modifiers);\n}\nfunction parseOrderByExpression(expr) {\n if (isExpressionOrFactory(expr)) {\n return parseExpression(expr);\n }\n if (isDynamicReferenceBuilder(expr)) {\n return expr.toOperationNode();\n }\n const [ref, direction] = expr.split(' ');\n if (direction) {\n logOnce(\"`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead.\");\n return parseOrderByWithModifiers(parseStringReference(ref), direction);\n }\n return parseStringReference(expr);\n}\nfunction parseOrderByWithModifiers(expr, modifiers) {\n if (typeof modifiers === 'string') {\n if (!isOrderByDirection(modifiers)) {\n throw new Error(`Invalid order by direction: ${modifiers}`);\n }\n return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers));\n }\n if (isExpression(modifiers)) {\n logOnce(\"`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead.\");\n return OrderByItemNode.create(expr, modifiers.toOperationNode());\n }\n const node = OrderByItemNode.create(expr);\n if (!modifiers) {\n return node;\n }\n return modifiers(new OrderByItemBuilder({ node })).toOperationNode();\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONReferenceNode = freeze({\n is(node) {\n return node.kind === 'JSONReferenceNode';\n },\n create(reference, traversal) {\n return freeze({\n kind: 'JSONReferenceNode',\n reference,\n traversal,\n });\n },\n cloneWithTraversal(node, traversal) {\n return freeze({\n ...node,\n traversal,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONOperatorChainNode = freeze({\n is(node) {\n return node.kind === 'JSONOperatorChainNode';\n },\n create(operator) {\n return freeze({\n kind: 'JSONOperatorChainNode',\n operator,\n values: freeze([]),\n });\n },\n cloneWithValue(node, value) {\n return freeze({\n ...node,\n values: freeze([...node.values, value]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathNode = freeze({\n is(node) {\n return node.kind === 'JSONPathNode';\n },\n create(inOperator) {\n return freeze({\n kind: 'JSONPathNode',\n inOperator,\n pathLegs: freeze([]),\n });\n },\n cloneWithLeg(jsonPathNode, pathLeg) {\n return freeze({\n ...jsonPathNode,\n pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg]),\n });\n },\n});\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ReferenceNode } from '../operation-node/reference-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOrderByDirection, parseOrderBy, } from './order-by-parser.js';\nimport { OperatorNode, isJSONOperator, } from '../operation-node/operator-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nexport function parseSimpleReferenceExpression(exp) {\n if (isString(exp)) {\n return parseStringReference(exp);\n }\n return exp.toOperationNode();\n}\nexport function parseReferenceExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return arg.map((it) => parseReferenceExpression(it));\n }\n else {\n return [parseReferenceExpression(arg)];\n }\n}\nexport function parseReferenceExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return parseSimpleReferenceExpression(exp);\n}\nexport function parseJSONReference(ref, op) {\n const referenceNode = parseStringReference(ref);\n if (isJSONOperator(op)) {\n return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op)));\n }\n const opWithoutLastChar = op.slice(0, -1);\n if (isJSONOperator(opWithoutLastChar)) {\n return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar)));\n }\n throw new Error(`Invalid JSON operator: ${op}`);\n}\nexport function parseStringReference(ref) {\n const COLUMN_SEPARATOR = '.';\n if (!ref.includes(COLUMN_SEPARATOR)) {\n return ReferenceNode.create(ColumnNode.create(ref));\n }\n const parts = ref.split(COLUMN_SEPARATOR).map(trim);\n if (parts.length === 3) {\n return parseStringReferenceWithTableAndSchema(parts);\n }\n if (parts.length === 2) {\n return parseStringReferenceWithTable(parts);\n }\n throw new Error(`invalid column reference ${ref}`);\n}\nexport function parseAliasedStringReference(ref) {\n const ALIAS_SEPARATOR = ' as ';\n if (ref.includes(ALIAS_SEPARATOR)) {\n const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias));\n }\n else {\n return parseStringReference(ref);\n }\n}\nexport function parseColumnName(column) {\n return ColumnNode.create(column);\n}\nexport function parseOrderedColumnName(column) {\n const ORDER_SEPARATOR = ' ';\n if (column.includes(ORDER_SEPARATOR)) {\n const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim);\n if (!isOrderByDirection(order)) {\n throw new Error(`invalid order direction \"${order}\" next to \"${columnName}\"`);\n }\n return parseOrderBy([columnName, order])[0];\n }\n else {\n return parseColumnName(column);\n }\n}\nfunction parseStringReferenceWithTableAndSchema(parts) {\n const [schema, table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema, table));\n}\nfunction parseStringReferenceWithTable(parts) {\n const [table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table));\n}\nfunction trim(str) {\n return str.trim();\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PrimitiveValueListNode = freeze({\n is(node) {\n return node.kind === 'PrimitiveValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'PrimitiveValueListNode',\n values: freeze([...values]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueListNode = freeze({\n is(node) {\n return node.kind === 'ValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'ValueListNode',\n values: freeze(values),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueNode = freeze({\n is(node) {\n return node.kind === 'ValueNode';\n },\n create(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n });\n },\n createImmediate(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n immediate: true,\n });\n },\n});\n", "/// \nimport { PrimitiveValueListNode } from '../operation-node/primitive-value-list-node.js';\nimport { ValueListNode } from '../operation-node/value-list-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { isBoolean, isNull, isNumber, isReadonlyArray, } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nexport function parseValueExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return parseValueExpressionList(arg);\n }\n return parseValueExpression(arg);\n}\nexport function parseValueExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return ValueNode.create(exp);\n}\nexport function isSafeImmediateValue(value) {\n return isNumber(value) || isBoolean(value) || isNull(value);\n}\nexport function parseSafeImmediateValue(value) {\n if (!isSafeImmediateValue(value)) {\n throw new Error(`unsafe immediate value ${JSON.stringify(value)}`);\n }\n return ValueNode.createImmediate(value);\n}\nfunction parseValueExpressionList(arg) {\n if (arg.some(isExpressionOrFactory)) {\n return ValueListNode.create(arg.map((it) => parseValueExpression(it)));\n }\n return PrimitiveValueListNode.create(arg);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ParensNode = freeze({\n is(node) {\n return node.kind === 'ParensNode';\n },\n create(node) {\n return freeze({\n kind: 'ParensNode',\n node,\n });\n },\n});\n", "/// \nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { isBoolean, isNull, isString, isUndefined, } from '../util/object-utils.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { OperatorNode, OPERATORS, } from '../operation-node/operator-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nimport { parseValueExpression, parseValueExpressionOrList, } from './value-parser.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { OrNode } from '../operation-node/or-node.js';\nexport function parseValueBinaryOperationOrExpression(args) {\n if (args.length === 3) {\n return parseValueBinaryOperation(args[0], args[1], args[2]);\n }\n else if (args.length === 1) {\n return parseValueExpression(args[0]);\n }\n throw new Error(`invalid arguments: ${JSON.stringify(args)}`);\n}\nexport function parseValueBinaryOperation(left, operator, right) {\n if (isIsOperator(operator) && needsIsOperator(right)) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right));\n }\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right));\n}\nexport function parseReferentialBinaryOperation(left, operator, right) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right));\n}\nexport function parseFilterObject(obj, combinator) {\n return parseFilterList(Object.entries(obj)\n .filter(([, v]) => !isUndefined(v))\n .map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? 'is' : '=', v)), combinator);\n}\nexport function parseFilterList(list, combinator, withParens = true) {\n const combine = combinator === 'and' ? AndNode.create : OrNode.create;\n if (list.length === 0) {\n return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create('='), ValueNode.createImmediate(combinator === 'and' ? 1 : 0));\n }\n let node = toOperationNode(list[0]);\n for (let i = 1; i < list.length; ++i) {\n node = combine(node, toOperationNode(list[i]));\n }\n if (list.length > 1 && withParens) {\n return ParensNode.create(node);\n }\n return node;\n}\nfunction isIsOperator(operator) {\n return operator === 'is' || operator === 'is not';\n}\nfunction needsIsOperator(value) {\n return isNull(value) || isBoolean(value);\n}\nfunction parseOperator(operator) {\n if (isString(operator) && OPERATORS.includes(operator)) {\n return OperatorNode.create(operator);\n }\n if (isOperationNodeSource(operator)) {\n return operator.toOperationNode();\n }\n throw new Error(`invalid operator ${JSON.stringify(operator)}`);\n}\nfunction toOperationNode(nodeOrSource) {\n return isOperationNodeSource(nodeOrSource)\n ? nodeOrSource.toOperationNode()\n : nodeOrSource;\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByNode = freeze({\n is(node) {\n return node.kind === 'OrderByNode';\n },\n create(items) {\n return freeze({\n kind: 'OrderByNode',\n items: freeze([...items]),\n });\n },\n cloneWithItems(orderBy, items) {\n return freeze({\n ...orderBy,\n items: freeze([...orderBy.items, ...items]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByNode = freeze({\n is(node) {\n return node.kind === 'PartitionByNode';\n },\n create(items) {\n return freeze({\n kind: 'PartitionByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(partitionBy, items) {\n return freeze({\n ...partitionBy,\n items: freeze([...partitionBy.items, ...items]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { OrderByNode } from './order-by-node.js';\nimport { PartitionByNode } from './partition-by-node.js';\n/**\n * @internal\n */\nexport const OverNode = freeze({\n is(node) {\n return node.kind === 'OverNode';\n },\n create() {\n return freeze({\n kind: 'OverNode',\n });\n },\n cloneWithOrderByItems(overNode, items) {\n return freeze({\n ...overNode,\n orderBy: overNode.orderBy\n ? OrderByNode.cloneWithItems(overNode.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithPartitionByItems(overNode, items) {\n return freeze({\n ...overNode,\n partitionBy: overNode.partitionBy\n ? PartitionByNode.cloneWithItems(overNode.partitionBy, items)\n : PartitionByNode.create(items),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FromNode = freeze({\n is(node) {\n return node.kind === 'FromNode';\n },\n create(froms) {\n return freeze({\n kind: 'FromNode',\n froms: freeze(froms),\n });\n },\n cloneWithFroms(from, froms) {\n return freeze({\n ...from,\n froms: freeze([...from.froms, ...froms]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByNode = freeze({\n is(node) {\n return node.kind === 'GroupByNode';\n },\n create(items) {\n return freeze({\n kind: 'GroupByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(groupBy, items) {\n return freeze({\n ...groupBy,\n items: freeze([...groupBy.items, ...items]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const HavingNode = freeze({\n is(node) {\n return node.kind === 'HavingNode';\n },\n create(filter) {\n return freeze({\n kind: 'HavingNode',\n having: filter,\n });\n },\n cloneWithOperation(havingNode, operator, operation) {\n return freeze({\n ...havingNode,\n having: operator === 'And'\n ? AndNode.create(havingNode.having, operation)\n : OrNode.create(havingNode.having, operation),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const InsertQueryNode = freeze({\n is(node) {\n return node.kind === 'InsertQueryNode';\n },\n create(into, withNode, replace) {\n return freeze({\n kind: 'InsertQueryNode',\n into,\n ...(withNode && { with: withNode }),\n replace,\n });\n },\n createWithoutInto() {\n return freeze({\n kind: 'InsertQueryNode',\n });\n },\n cloneWith(insertQuery, props) {\n return freeze({\n ...insertQuery,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ListNode = freeze({\n is(node) {\n return node.kind === 'ListNode';\n },\n create(items) {\n return freeze({\n kind: 'ListNode',\n items: freeze(items),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { ListNode } from './list-node.js';\n/**\n * @internal\n */\nexport const UpdateQueryNode = freeze({\n is(node) {\n return node.kind === 'UpdateQueryNode';\n },\n create(tables, withNode) {\n return freeze({\n kind: 'UpdateQueryNode',\n // For backwards compatibility, use the raw table node when there's only one table\n // and don't rename the property to something like `tables`.\n table: tables.length === 1 ? tables[0] : ListNode.create(tables),\n ...(withNode && { with: withNode }),\n });\n },\n createWithoutTable() {\n return freeze({\n kind: 'UpdateQueryNode',\n });\n },\n cloneWithFromItems(updateQuery, fromItems) {\n return freeze({\n ...updateQuery,\n from: updateQuery.from\n ? FromNode.cloneWithFroms(updateQuery.from, fromItems)\n : FromNode.create(fromItems),\n });\n },\n cloneWithUpdates(updateQuery, updates) {\n return freeze({\n ...updateQuery,\n updates: updateQuery.updates\n ? freeze([...updateQuery.updates, ...updates])\n : updates,\n });\n },\n cloneWithLimit(updateQuery, limit) {\n return freeze({\n ...updateQuery,\n limit,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UsingNode = freeze({\n is(node) {\n return node.kind === 'UsingNode';\n },\n create(tables) {\n return freeze({\n kind: 'UsingNode',\n tables: freeze(tables),\n });\n },\n cloneWithTables(using, tables) {\n return freeze({\n ...using,\n tables: freeze([...using.tables, ...tables]),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { UsingNode } from './using-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const DeleteQueryNode = freeze({\n is(node) {\n return node.kind === 'DeleteQueryNode';\n },\n create(fromItems, withNode) {\n return freeze({\n kind: 'DeleteQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithLimit(deleteNode, limit) {\n return freeze({\n ...deleteNode,\n limit,\n });\n },\n cloneWithoutLimit(deleteNode) {\n return freeze({\n ...deleteNode,\n limit: undefined,\n });\n },\n cloneWithUsing(deleteNode, tables) {\n return freeze({\n ...deleteNode,\n using: deleteNode.using !== undefined\n ? UsingNode.cloneWithTables(deleteNode.using, tables)\n : UsingNode.create(tables),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const WhereNode = freeze({\n is(node) {\n return node.kind === 'WhereNode';\n },\n create(filter) {\n return freeze({\n kind: 'WhereNode',\n where: filter,\n });\n },\n cloneWithOperation(whereNode, operator, operation) {\n return freeze({\n ...whereNode,\n where: operator === 'And'\n ? AndNode.create(whereNode.where, operation)\n : OrNode.create(whereNode.where, operation),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReturningNode = freeze({\n is(node) {\n return node.kind === 'ReturningNode';\n },\n create(selections) {\n return freeze({\n kind: 'ReturningNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(returning, selections) {\n return freeze({\n ...returning,\n selections: returning.selections\n ? freeze([...returning.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ExplainNode = freeze({\n is(node) {\n return node.kind === 'ExplainNode';\n },\n create(format, options) {\n return freeze({\n kind: 'ExplainNode',\n format,\n options,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const WhenNode = freeze({\n is(node) {\n return node.kind === 'WhenNode';\n },\n create(condition) {\n return freeze({\n kind: 'WhenNode',\n condition,\n });\n },\n cloneWithResult(whenNode, result) {\n return freeze({\n ...whenNode,\n result,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const MergeQueryNode = freeze({\n is(node) {\n return node.kind === 'MergeQueryNode';\n },\n create(into, withNode) {\n return freeze({\n kind: 'MergeQueryNode',\n into,\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithUsing(mergeNode, using) {\n return freeze({\n ...mergeNode,\n using,\n });\n },\n cloneWithWhen(mergeNode, when) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([...mergeNode.whens, when])\n : freeze([when]),\n });\n },\n cloneWithThen(mergeNode, then) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([\n ...mergeNode.whens.slice(0, -1),\n WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then),\n ])\n : undefined,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OutputNode = freeze({\n is(node) {\n return node.kind === 'OutputNode';\n },\n create(selections) {\n return freeze({\n kind: 'OutputNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(output, selections) {\n return freeze({\n ...output,\n selections: output.selections\n ? freeze([...output.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n", "/// \nimport { InsertQueryNode } from './insert-query-node.js';\nimport { SelectQueryNode } from './select-query-node.js';\nimport { UpdateQueryNode } from './update-query-node.js';\nimport { DeleteQueryNode } from './delete-query-node.js';\nimport { WhereNode } from './where-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { ReturningNode } from './returning-node.js';\nimport { ExplainNode } from './explain-node.js';\nimport { MergeQueryNode } from './merge-query-node.js';\nimport { OutputNode } from './output-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const QueryNode = freeze({\n is(node) {\n return (SelectQueryNode.is(node) ||\n InsertQueryNode.is(node) ||\n UpdateQueryNode.is(node) ||\n DeleteQueryNode.is(node) ||\n MergeQueryNode.is(node));\n },\n cloneWithEndModifier(node, modifier) {\n return freeze({\n ...node,\n endModifiers: node.endModifiers\n ? freeze([...node.endModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWithWhere(node, operation) {\n return freeze({\n ...node,\n where: node.where\n ? WhereNode.cloneWithOperation(node.where, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithJoin(node, join) {\n return freeze({\n ...node,\n joins: node.joins ? freeze([...node.joins, join]) : freeze([join]),\n });\n },\n cloneWithReturning(node, selections) {\n return freeze({\n ...node,\n returning: node.returning\n ? ReturningNode.cloneWithSelections(node.returning, selections)\n : ReturningNode.create(selections),\n });\n },\n cloneWithoutReturning(node) {\n return freeze({\n ...node,\n returning: undefined,\n });\n },\n cloneWithoutWhere(node) {\n return freeze({\n ...node,\n where: undefined,\n });\n },\n cloneWithExplain(node, format, options) {\n return freeze({\n ...node,\n explain: ExplainNode.create(format, options?.toOperationNode()),\n });\n },\n cloneWithTop(node, top) {\n return freeze({\n ...node,\n top,\n });\n },\n cloneWithOutput(node, selections) {\n return freeze({\n ...node,\n output: node.output\n ? OutputNode.cloneWithSelections(node.output, selections)\n : OutputNode.create(selections),\n });\n },\n cloneWithOrderByItems(node, items) {\n return freeze({\n ...node,\n orderBy: node.orderBy\n ? OrderByNode.cloneWithItems(node.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithoutOrderBy(node) {\n return freeze({\n ...node,\n orderBy: undefined,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { GroupByNode } from './group-by-node.js';\nimport { HavingNode } from './having-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const SelectQueryNode = freeze({\n is(node) {\n return node.kind === 'SelectQueryNode';\n },\n create(withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n ...(withNode && { with: withNode }),\n });\n },\n createFrom(fromItems, withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithSelections(select, selections) {\n return freeze({\n ...select,\n selections: select.selections\n ? freeze([...select.selections, ...selections])\n : freeze(selections),\n });\n },\n cloneWithDistinctOn(select, expressions) {\n return freeze({\n ...select,\n distinctOn: select.distinctOn\n ? freeze([...select.distinctOn, ...expressions])\n : freeze(expressions),\n });\n },\n cloneWithFrontModifier(select, modifier) {\n return freeze({\n ...select,\n frontModifiers: select.frontModifiers\n ? freeze([...select.frontModifiers, modifier])\n : freeze([modifier]),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n cloneWithGroupByItems(selectNode, items) {\n return freeze({\n ...selectNode,\n groupBy: selectNode.groupBy\n ? GroupByNode.cloneWithItems(selectNode.groupBy, items)\n : GroupByNode.create(items),\n });\n },\n cloneWithLimit(selectNode, limit) {\n return freeze({\n ...selectNode,\n limit,\n });\n },\n cloneWithOffset(selectNode, offset) {\n return freeze({\n ...selectNode,\n offset,\n });\n },\n cloneWithFetch(selectNode, fetch) {\n return freeze({\n ...selectNode,\n fetch,\n });\n },\n cloneWithHaving(selectNode, operation) {\n return freeze({\n ...selectNode,\n having: selectNode.having\n ? HavingNode.cloneWithOperation(selectNode.having, 'And', operation)\n : HavingNode.create(operation),\n });\n },\n cloneWithSetOperations(selectNode, setOperations) {\n return freeze({\n ...selectNode,\n setOperations: selectNode.setOperations\n ? freeze([...selectNode.setOperations, ...setOperations])\n : freeze([...setOperations]),\n });\n },\n cloneWithoutSelections(select) {\n return freeze({\n ...select,\n selections: [],\n });\n },\n cloneWithoutLimit(select) {\n return freeze({\n ...select,\n limit: undefined,\n });\n },\n cloneWithoutOffset(select) {\n return freeze({\n ...select,\n offset: undefined,\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithoutGroupBy(select) {\n return freeze({\n ...select,\n groupBy: undefined,\n });\n },\n});\n", "/// \nimport { JoinNode } from '../operation-node/join-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class JoinBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n on(...args) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Just like {@link WhereInterface.whereRef} but adds an item to the join's\n * `on` clause instead.\n *\n * See {@link WhereInterface.whereRef} for documentation and examples.\n */\n onRef(lhs, op, rhs) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds `on true`.\n */\n onTrue() {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql('true')),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.joinNode;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByItemNode = freeze({\n is(node) {\n return node.kind === 'PartitionByItemNode';\n },\n create(partitionBy) {\n return freeze({\n kind: 'PartitionByItemNode',\n partitionBy,\n });\n },\n});\n", "/// \nimport { PartitionByItemNode } from '../operation-node/partition-by-item-node.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parsePartitionBy(partitionBy) {\n return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create);\n}\n", "/// \nimport { OverNode } from '../operation-node/over-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { parsePartitionBy, } from '../parser/partition-by-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OverBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n orderBy(...args) {\n return new OverBuilder({\n overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new OverBuilder({\n overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode),\n });\n }\n partitionBy(partitionBy) {\n return new OverBuilder({\n overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy)),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.overNode;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ReferenceNode } from './reference-node.js';\nimport { SelectAllNode } from './select-all-node.js';\n/**\n * @internal\n */\nexport const SelectionNode = freeze({\n is(node) {\n return node.kind === 'SelectionNode';\n },\n create(selection) {\n return freeze({\n kind: 'SelectionNode',\n selection: selection,\n });\n },\n createSelectAll() {\n return freeze({\n kind: 'SelectionNode',\n selection: SelectAllNode.create(),\n });\n },\n createSelectAllFromTable(table) {\n return freeze({\n kind: 'SelectionNode',\n selection: ReferenceNode.createSelectAll(table),\n });\n },\n});\n", "/// \nimport { isFunction, isReadonlyArray, isString } from '../util/object-utils.js';\nimport { SelectionNode } from '../operation-node/selection-node.js';\nimport { parseAliasedStringReference } from './reference-parser.js';\nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { parseTable } from './table-parser.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nexport function parseSelectArg(selection) {\n if (isFunction(selection)) {\n return parseSelectArg(selection(expressionBuilder()));\n }\n else if (isReadonlyArray(selection)) {\n return selection.map((it) => parseSelectExpression(it));\n }\n else {\n return [parseSelectExpression(selection)];\n }\n}\nfunction parseSelectExpression(selection) {\n if (isString(selection)) {\n return SelectionNode.create(parseAliasedStringReference(selection));\n }\n else if (isDynamicReferenceBuilder(selection)) {\n return SelectionNode.create(selection.toOperationNode());\n }\n else {\n return SelectionNode.create(parseAliasedExpression(selection));\n }\n}\nexport function parseSelectAll(table) {\n if (!table) {\n return [SelectionNode.createSelectAll()];\n }\n else if (Array.isArray(table)) {\n return table.map(parseSelectAllArg);\n }\n else {\n return [parseSelectAllArg(table)];\n }\n}\nfunction parseSelectAllArg(table) {\n if (isString(table)) {\n return SelectionNode.createSelectAllFromTable(parseTable(table));\n }\n throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValuesNode = freeze({\n is(node) {\n return node.kind === 'ValuesNode';\n },\n create(values) {\n return freeze({\n kind: 'ValuesNode',\n values: freeze(values),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const DefaultInsertValueNode = freeze({\n is(node) {\n return node.kind === 'DefaultInsertValueNode';\n },\n create() {\n return freeze({\n kind: 'DefaultInsertValueNode',\n });\n },\n});\n", "/// \nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { PrimitiveValueListNode } from '../operation-node/primitive-value-list-node.js';\nimport { ValueListNode } from '../operation-node/value-list-node.js';\nimport { freeze, isFunction, isReadonlyArray, isUndefined, } from '../util/object-utils.js';\nimport { parseValueExpression } from './value-parser.js';\nimport { ValuesNode } from '../operation-node/values-node.js';\nimport { isExpressionOrFactory } from './expression-parser.js';\nimport { DefaultInsertValueNode } from '../operation-node/default-insert-value-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nexport function parseInsertExpression(arg) {\n const objectOrList = isFunction(arg) ? arg(expressionBuilder()) : arg;\n const list = isReadonlyArray(objectOrList)\n ? objectOrList\n : freeze([objectOrList]);\n return parseInsertColumnsAndValues(list);\n}\nfunction parseInsertColumnsAndValues(rows) {\n const columns = parseColumnNamesAndIndexes(rows);\n return [\n freeze([...columns.keys()].map(ColumnNode.create)),\n ValuesNode.create(rows.map((row) => parseRowValues(row, columns))),\n ];\n}\nfunction parseColumnNamesAndIndexes(rows) {\n const columns = new Map();\n for (const row of rows) {\n const cols = Object.keys(row);\n for (const col of cols) {\n if (!columns.has(col) && row[col] !== undefined) {\n columns.set(col, columns.size);\n }\n }\n }\n return columns;\n}\nfunction parseRowValues(row, columns) {\n const rowColumns = Object.keys(row);\n const rowValues = Array.from({\n length: columns.size,\n });\n let hasUndefinedOrComplexColumns = false;\n let indexedRowColumns = rowColumns.length;\n for (const col of rowColumns) {\n const columnIdx = columns.get(col);\n if (isUndefined(columnIdx)) {\n indexedRowColumns--;\n continue;\n }\n const value = row[col];\n if (isUndefined(value) || isExpressionOrFactory(value)) {\n hasUndefinedOrComplexColumns = true;\n }\n rowValues[columnIdx] = value;\n }\n const hasMissingColumns = indexedRowColumns < columns.size;\n if (hasMissingColumns || hasUndefinedOrComplexColumns) {\n const defaultValue = DefaultInsertValueNode.create();\n return ValueListNode.create(rowValues.map((it) => isUndefined(it) ? defaultValue : parseValueExpression(it)));\n }\n return PrimitiveValueListNode.create(rowValues);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ColumnUpdateNode = freeze({\n is(node) {\n return node.kind === 'ColumnUpdateNode';\n },\n create(column, value) {\n return freeze({\n kind: 'ColumnUpdateNode',\n column,\n value,\n });\n },\n});\n", "/// \nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ColumnUpdateNode } from '../operation-node/column-update-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { parseValueExpression } from './value-parser.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nexport function parseUpdate(...args) {\n if (args.length === 2) {\n return [\n ColumnUpdateNode.create(parseReferenceExpression(args[0]), parseValueExpression(args[1])),\n ];\n }\n return parseUpdateObjectExpression(args[0]);\n}\nexport function parseUpdateObjectExpression(update) {\n const updateObj = isFunction(update) ? update(expressionBuilder()) : update;\n return Object.entries(updateObj)\n .filter(([_, value]) => value !== undefined)\n .map(([key, value]) => {\n return ColumnUpdateNode.create(ColumnNode.create(key), parseValueExpression(value));\n });\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OnDuplicateKeyNode = freeze({\n is(node) {\n return node.kind === 'OnDuplicateKeyNode';\n },\n create(updates) {\n return freeze({\n kind: 'OnDuplicateKeyNode',\n updates,\n });\n },\n});\n", "/// \n/**\n * The result of an insert query.\n *\n * If the table has an auto incrementing primary key {@link insertId} will hold\n * the generated id on dialects that support it. For example PostgreSQL doesn't\n * return the id by default and {@link insertId} is undefined. On PostgreSQL you\n * need to use {@link ReturningInterface.returning} or {@link ReturningInterface.returningAll}\n * to get out the inserted id.\n *\n * {@link numInsertedOrUpdatedRows} holds the number of (actually) inserted rows.\n * On MySQL, updated rows are counted twice when using `on duplicate key update`.\n *\n * ### Examples\n *\n * ```ts\n * import type { NewPerson } from 'type-editor' // imaginary module\n *\n * async function insertPerson(person: NewPerson) {\n * const result = await db\n * .insertInto('person')\n * .values(person)\n * .executeTakeFirstOrThrow()\n *\n * console.log(result.insertId) // relevant on MySQL\n * console.log(result.numInsertedOrUpdatedRows) // always relevant\n * }\n * ```\n */\nexport class InsertResult {\n /**\n * The auto incrementing primary key of the inserted row.\n *\n * This property can be undefined when the query contains an `on conflict`\n * clause that makes the query succeed even when nothing gets inserted.\n *\n * This property is always undefined on dialects like PostgreSQL that\n * don't return the inserted id by default. On those dialects you need\n * to use the {@link ReturningInterface.returning | returning} method.\n */\n insertId;\n /**\n * Affected rows count.\n */\n numInsertedOrUpdatedRows;\n constructor(insertId, numInsertedOrUpdatedRows) {\n this.insertId = insertId;\n this.numInsertedOrUpdatedRows = numInsertedOrUpdatedRows;\n }\n}\n", "/// \nexport class NoResultError extends Error {\n /**\n * The operation node tree of the query that was executed.\n */\n node;\n constructor(node) {\n super('no result');\n this.node = node;\n }\n}\nexport function isNoResultErrorConstructor(fn) {\n return Object.prototype.hasOwnProperty.call(fn, 'prototype');\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { WhereNode } from './where-node.js';\n/**\n * @internal\n */\nexport const OnConflictNode = freeze({\n is(node) {\n return node.kind === 'OnConflictNode';\n },\n create() {\n return freeze({\n kind: 'OnConflictNode',\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n cloneWithIndexWhere(node, operation) {\n return freeze({\n ...node,\n indexWhere: node.indexWhere\n ? WhereNode.cloneWithOperation(node.indexWhere, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithIndexOrWhere(node, operation) {\n return freeze({\n ...node,\n indexWhere: node.indexWhere\n ? WhereNode.cloneWithOperation(node.indexWhere, 'Or', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithUpdateWhere(node, operation) {\n return freeze({\n ...node,\n updateWhere: node.updateWhere\n ? WhereNode.cloneWithOperation(node.updateWhere, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithUpdateOrWhere(node, operation) {\n return freeze({\n ...node,\n updateWhere: node.updateWhere\n ? WhereNode.cloneWithOperation(node.updateWhere, 'Or', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithoutIndexWhere(node) {\n return freeze({\n ...node,\n indexWhere: undefined,\n });\n },\n cloneWithoutUpdateWhere(node) {\n return freeze({\n ...node,\n updateWhere: undefined,\n });\n },\n});\n", "/// \nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { OnConflictNode } from '../operation-node/on-conflict-node.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { parseUpdateObjectExpression, } from '../parser/update-set-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OnConflictBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Specify a single column as the conflict target.\n *\n * Also see the {@link columns}, {@link constraint} and {@link expression}\n * methods for alternative ways to specify the conflict target.\n */\n column(column) {\n const columnNode = ColumnNode.create(column);\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n columns: this.#props.onConflictNode.columns\n ? freeze([...this.#props.onConflictNode.columns, columnNode])\n : freeze([columnNode]),\n }),\n });\n }\n /**\n * Specify a list of columns as the conflict target.\n *\n * Also see the {@link column}, {@link constraint} and {@link expression}\n * methods for alternative ways to specify the conflict target.\n */\n columns(columns) {\n const columnNodes = columns.map(ColumnNode.create);\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n columns: this.#props.onConflictNode.columns\n ? freeze([...this.#props.onConflictNode.columns, ...columnNodes])\n : freeze(columnNodes),\n }),\n });\n }\n /**\n * Specify a specific constraint by name as the conflict target.\n *\n * Also see the {@link column}, {@link columns} and {@link expression}\n * methods for alternative ways to specify the conflict target.\n */\n constraint(constraintName) {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n constraint: IdentifierNode.create(constraintName),\n }),\n });\n }\n /**\n * Specify an expression as the conflict target.\n *\n * This can be used if the unique index is an expression index.\n *\n * Also see the {@link column}, {@link columns} and {@link constraint}\n * methods for alternative ways to specify the conflict target.\n */\n expression(expression) {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n indexExpression: expression.toOperationNode(),\n }),\n });\n }\n where(...args) {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n clearWhere() {\n return new OnConflictBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithoutIndexWhere(this.#props.onConflictNode),\n });\n }\n /**\n * Adds the \"do nothing\" conflict action.\n *\n * ### Examples\n *\n * ```ts\n * const id = 1\n * const first_name = 'John'\n *\n * await db\n * .insertInto('person')\n * .values({\u00A0first_name, id })\n * .onConflict((oc) => oc\n * .column('id')\n * .doNothing()\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"id\")\n * values ($1, $2)\n * on conflict (\"id\") do nothing\n * ```\n */\n doNothing() {\n return new OnConflictDoNothingBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n doNothing: true,\n }),\n });\n }\n /**\n * Adds the \"do update set\" conflict action.\n *\n * ### Examples\n *\n * ```ts\n * const id = 1\n * const first_name = 'John'\n *\n * await db\n * .insertInto('person')\n * .values({\u00A0first_name, id })\n * .onConflict((oc) => oc\n * .column('id')\n * .doUpdateSet({ first_name })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"id\")\n * values ($1, $2)\n * on conflict (\"id\")\n * do update set \"first_name\" = $3\n * ```\n *\n * In the next example we use the `ref` method to reference\n * columns of the virtual table `excluded` in a type-safe way\n * to create an upsert operation:\n *\n * ```ts\n * import type { NewPerson } from 'type-editor' // imaginary module\n *\n * async function upsertPerson(person: NewPerson): Promise {\n * await db.insertInto('person')\n * .values(person)\n * .onConflict((oc) => oc\n * .column('id')\n * .doUpdateSet((eb) => ({\n * first_name: eb.ref('excluded.first_name'),\n * last_name: eb.ref('excluded.last_name')\n * })\n * )\n * )\n * .execute()\n * }\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\")\n * values ($1, $2)\n * on conflict (\"id\")\n * do update set\n * \"first_name\" = excluded.\"first_name\",\n * \"last_name\" = excluded.\"last_name\"\n * ```\n */\n doUpdateSet(update) {\n return new OnConflictUpdateBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {\n updates: parseUpdateObjectExpression(update),\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n}\nexport class OnConflictDoNothingBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n toOperationNode() {\n return this.#props.onConflictNode;\n }\n}\nexport class OnConflictUpdateBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n where(...args) {\n return new OnConflictUpdateBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Specify a where condition for the update operation.\n *\n * See {@link WhereInterface.whereRef} for more info.\n */\n whereRef(lhs, op, rhs) {\n return new OnConflictUpdateBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n clearWhere() {\n return new OnConflictUpdateBuilder({\n ...this.#props,\n onConflictNode: OnConflictNode.cloneWithoutUpdateWhere(this.#props.onConflictNode),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.onConflictNode;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TopNode = freeze({\n is(node) {\n return node.kind === 'TopNode';\n },\n create(expression, modifiers) {\n return freeze({\n kind: 'TopNode',\n expression,\n modifiers,\n });\n },\n});\n", "/// \nimport { TopNode } from '../operation-node/top-node.js';\nimport { isBigInt, isNumber, isUndefined } from '../util/object-utils.js';\nexport function parseTop(expression, modifiers) {\n if (!isNumber(expression) && !isBigInt(expression)) {\n throw new Error(`Invalid top expression: ${expression}`);\n }\n if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) {\n throw new Error(`Invalid top modifiers: ${modifiers}`);\n }\n return TopNode.create(expression, modifiers);\n}\nfunction isTopModifiers(modifiers) {\n return (modifiers === 'percent' ||\n modifiers === 'with ties' ||\n modifiers === 'percent with ties');\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrActionNode = freeze({\n is(node) {\n return node.kind === 'OrActionNode';\n },\n create(action) {\n return freeze({\n kind: 'OrActionNode',\n action,\n });\n },\n});\n", "/// \nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { parseInsertExpression, } from '../parser/insert-values-parser.js';\nimport { InsertQueryNode } from '../operation-node/insert-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseUpdateObjectExpression, } from '../parser/update-set-parser.js';\nimport { freeze } from '../util/object-utils.js';\nimport { OnDuplicateKeyNode } from '../operation-node/on-duplicate-key-node.js';\nimport { InsertResult } from './insert-result.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { parseExpression, } from '../parser/expression-parser.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { OnConflictBuilder, } from './on-conflict-builder.js';\nimport { OnConflictNode } from '../operation-node/on-conflict-node.js';\nimport { parseTop } from '../parser/top-parser.js';\nimport { OrActionNode } from '../operation-node/or-action-node.js';\nexport class InsertQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Sets the values to insert for an {@link Kysely.insertInto | insert} query.\n *\n * This method takes an object whose keys are column names and values are\n * values to insert. In addition to the column's type, the values can be\n * raw {@link sql} snippets or select queries.\n *\n * You must provide all fields you haven't explicitly marked as nullable\n * or optional using {@link Generated} or {@link ColumnType}.\n *\n * The return value of an `insert` query is an instance of {@link InsertResult}. The\n * {@link InsertResult.insertId | insertId} field holds the auto incremented primary\n * key if the database returned one.\n *\n * On PostgreSQL and some other dialects, you need to call `returning` to get\n * something out of the query.\n *\n * Also see the {@link expression} method for inserting the result of a select\n * query or any other expression.\n *\n * ### Examples\n *\n * \n *\n * Insert a single row:\n *\n * ```ts\n * const result = await db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40\n * })\n * .executeTakeFirst()\n *\n * // `insertId` is only available on dialects that\n * // automatically return the id of the inserted row\n * // such as MySQL and SQLite. On PostgreSQL, for example,\n * // you need to add a `returning` clause to the query to\n * // get anything out. See the \"returning data\" example.\n * console.log(result.insertId)\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert into `person` (`first_name`, `last_name`, `age`) values (?, ?, ?)\n * ```\n *\n * \n *\n * On dialects that support it (for example PostgreSQL) you can insert multiple\n * rows by providing an array. Note that the return value is once again very\n * dialect-specific. Some databases may only return the id of the *last* inserted\n * row and some return nothing at all unless you call `returning`.\n *\n * ```ts\n * await db\n * .insertInto('person')\n * .values([{\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * }, {\n * first_name: 'Arnold',\n * last_name: 'Schwarzenegger',\n * age: 70,\n * }])\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\", \"age\") values (($1, $2, $3), ($4, $5, $6))\n * ```\n *\n * \n *\n * On supported dialects like PostgreSQL you need to chain `returning` to the query to get\n * the inserted row's columns (or any other expression) as the return value. `returning`\n * works just like `select`. Refer to `select` method's examples and documentation for\n * more info.\n *\n * ```ts\n * const result = await db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * })\n * .returning(['id', 'first_name as name'])\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\", \"age\") values ($1, $2, $3) returning \"id\", \"first_name\" as \"name\"\n * ```\n *\n * \n *\n * In addition to primitives, the values can also be arbitrary expressions.\n * You can build the expressions by using a callback and calling the methods\n * on the expression builder passed to it:\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * const ani = \"Ani\"\n * const ston = \"ston\"\n *\n * const result = await db\n * .insertInto('person')\n * .values(({ ref, selectFrom, fn }) => ({\n * first_name: 'Jennifer',\n * last_name: sql`concat(${ani}, ${ston})`,\n * middle_name: ref('first_name'),\n * age: selectFrom('person')\n * .select(fn.avg('age').as('avg_age')),\n * }))\n * .executeTakeFirst()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\n * \"first_name\",\n * \"last_name\",\n * \"middle_name\",\n * \"age\"\n * )\n * values (\n * $1,\n * concat($2, $3),\n * \"first_name\",\n * (select avg(\"age\") as \"avg_age\" from \"person\")\n * )\n * ```\n *\n * You can also use the callback version of subqueries or raw expressions:\n *\n * ```ts\n * await db.with('jennifer', (db) => db\n * .selectFrom('person')\n * .where('first_name', '=', 'Jennifer')\n * .select(['id', 'first_name', 'gender'])\n * .limit(1)\n * ).insertInto('pet').values((eb) => ({\n * owner_id: eb.selectFrom('jennifer').select('id'),\n * name: eb.selectFrom('jennifer').select('first_name'),\n * species: 'cat',\n * }))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * with \"jennifer\" as (\n * select \"id\", \"first_name\", \"gender\"\n * from \"person\"\n * where \"first_name\" = $1\n * limit $2\n * )\n * insert into \"pet\" (\"owner_id\", \"name\", \"species\")\n * values (\n * (select \"id\" from \"jennifer\"),\n * (select \"first_name\" from \"jennifer\"),\n * $3\n * )\n * ```\n */\n values(insert) {\n const [columns, values] = parseInsertExpression(insert);\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n columns,\n values,\n }),\n });\n }\n /**\n * Sets the columns to insert.\n *\n * The {@link values} method sets both the columns and the values and this method\n * is not needed. But if you are using the {@link expression} method, you can use\n * this method to set the columns to insert.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .columns(['first_name'])\n * .expression((eb) => eb.selectFrom('pet').select('pet.name'))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\")\n * select \"pet\".\"name\" from \"pet\"\n * ```\n */\n columns(columns) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n columns: freeze(columns.map(ColumnNode.create)),\n }),\n });\n }\n /**\n * Insert an arbitrary expression. For example the result of a select query.\n *\n * ### Examples\n *\n * \n *\n * You can create an `INSERT INTO SELECT FROM` query using the `expression` method.\n * This API doesn't follow our WYSIWYG principles and might be a bit difficult to\n * remember. The reasons for this design stem from implementation difficulties.\n *\n * ```ts\n * const result = await db.insertInto('person')\n * .columns(['first_name', 'last_name', 'age'])\n * .expression((eb) => eb\n * .selectFrom('pet')\n * .select((eb) => [\n * 'pet.name',\n * eb.val('Petson').as('last_name'),\n * eb.lit(7).as('age'),\n * ])\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\", \"age\")\n * select \"pet\".\"name\", $1 as \"last_name\", 7 as \"age from \"pet\"\n * ```\n */\n expression(expression) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n values: parseExpression(expression),\n }),\n });\n }\n /**\n * Creates an `insert into \"person\" default values` query.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .defaultValues()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" default values\n * ```\n */\n defaultValues() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n defaultValues: true,\n }),\n });\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.insertInto('person')\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * })\n * .modifyEnd(sql`-- This is a comment`)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert into `person` (\"first_name\", \"last_name\", \"gender\")\n * values (?, ?, ?) -- This is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * Changes an `insert into` query to an `insert ignore into` query.\n *\n * This is only supported by some dialects like MySQL.\n *\n * To avoid a footgun, when invoked with the SQLite dialect, this method will\n * be handled like {@link orIgnore}. See also, {@link orAbort}, {@link orFail},\n * {@link orReplace}, and {@link orRollback}.\n *\n * If you use the ignore modifier, ignorable errors that occur while executing the\n * insert statement are ignored. For example, without ignore, a row that duplicates\n * an existing unique index or primary key value in the table causes a duplicate-key\n * error and the statement is aborted. With ignore, the row is discarded and no error\n * occurs.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .ignore()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or ignore into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n ignore() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('ignore'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or ignore into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * To avoid a footgun, when invoked with the MySQL dialect, this method will\n * be handled like {@link ignore}.\n *\n * See also, {@link orAbort}, {@link orFail}, {@link orReplace}, and {@link orRollback}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orIgnore()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or ignore into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)\n * ```\n */\n orIgnore() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('ignore'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or abort into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * See also, {@link orIgnore}, {@link orFail}, {@link orReplace}, and {@link orRollback}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orAbort()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or abort into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n orAbort() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('abort'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or fail into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * See also, {@link orIgnore}, {@link orAbort}, {@link orReplace}, and {@link orRollback}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orFail()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or fail into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n orFail() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('fail'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or replace into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * You can also use {@link Kysely.replaceInto} to achieve the same result.\n *\n * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orRollback}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orReplace()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or replace into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n orReplace() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('replace'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert or rollback into` query.\n *\n * This is only supported by some dialects like SQLite.\n *\n * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orReplace}.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .orRollback()\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'female',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * insert or rollback into \"person\" (\"first_name\", \"last_name\", \"gender\") values (?, ?, ?)\n * ```\n */\n orRollback() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n orAction: OrActionNode.create('rollback'),\n }),\n });\n }\n /**\n * Changes an `insert into` query to an `insert top into` query.\n *\n * `top` clause is only supported by some dialects like MS SQL Server.\n *\n * ### Examples\n *\n * Insert the first 5 rows:\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.insertInto('person')\n * .top(5)\n * .columns(['first_name', 'gender'])\n * .expression(\n * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')])\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * insert top(5) into \"person\" (\"first_name\", \"gender\") select \"name\", 'other' as \"gender\" from \"pet\"\n * ```\n *\n * Insert the first 50 percent of rows:\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.insertInto('person')\n * .top(50, 'percent')\n * .columns(['first_name', 'gender'])\n * .expression(\n * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')])\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * insert top(50) percent into \"person\" (\"first_name\", \"gender\") select \"name\", 'other' as \"gender\" from \"pet\"\n * ```\n */\n top(expression, modifiers) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n /**\n * Adds an `on conflict` clause to the query.\n *\n * `on conflict` is only supported by some dialects like PostgreSQL and SQLite. On MySQL\n * you can use {@link ignore} and {@link onDuplicateKeyUpdate} to achieve similar results.\n *\n * ### Examples\n *\n * ```ts\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .column('name')\n * .doUpdateSet({ species: 'hamster' })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict (\"name\")\n * do update set \"species\" = $4\n * ```\n *\n * You can provide the name of the constraint instead of a column name:\n *\n * ```ts\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .constraint('pet_name_key')\n * .doUpdateSet({ species: 'hamster' })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict on constraint \"pet_name_key\"\n * do update set \"species\" = $4\n * ```\n *\n * You can also specify an expression as the conflict target in case\n * the unique index is an expression index:\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .expression(sql`lower(name)`)\n * .doUpdateSet({ species: 'hamster' })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict (lower(name))\n * do update set \"species\" = $4\n * ```\n *\n * You can add a filter for the update statement like this:\n *\n * ```ts\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .column('name')\n * .doUpdateSet({ species: 'hamster' })\n * .where('excluded.name', '!=', 'Catto')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict (\"name\")\n * do update set \"species\" = $4\n * where \"excluded\".\"name\" != $5\n * ```\n *\n * You can create an `on conflict do nothing` clauses like this:\n *\n * ```ts\n * await db\n * .insertInto('pet')\n * .values({\n * name: 'Catto',\n * species: 'cat',\n * owner_id: 3,\n * })\n * .onConflict((oc) => oc\n * .column('name')\n * .doNothing()\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"pet\" (\"name\", \"species\", \"owner_id\")\n * values ($1, $2, $3)\n * on conflict (\"name\") do nothing\n * ```\n *\n * You can refer to the columns of the virtual `excluded` table\n * in a type-safe way using a callback and the `ref` method of\n * `ExpressionBuilder`:\n *\n * ```ts\n * await db.insertInto('person')\n * .values({\n * id: 1,\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * })\n * .onConflict(oc => oc\n * .column('id')\n * .doUpdateSet({\n * first_name: (eb) => eb.ref('excluded.first_name'),\n * last_name: (eb) => eb.ref('excluded.last_name')\n * })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"id\", \"first_name\", \"last_name\", \"gender\")\n * values ($1, $2, $3, $4)\n * on conflict (\"id\")\n * do update set\n * \"first_name\" = \"excluded\".\"first_name\",\n * \"last_name\" = \"excluded\".\"last_name\"\n * ```\n */\n onConflict(callback) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n onConflict: callback(new OnConflictBuilder({\n onConflictNode: OnConflictNode.create(),\n })).toOperationNode(),\n }),\n });\n }\n /**\n * Adds `on duplicate key update` to the query.\n *\n * If you specify `on duplicate key update`, and a row is inserted that would cause\n * a duplicate value in a unique index or primary key, an update of the old row occurs.\n *\n * This is only implemented by some dialects like MySQL. On most dialects you should\n * use {@link onConflict} instead.\n *\n * ### Examples\n *\n * ```ts\n * await db\n * .insertInto('person')\n * .values({\n * id: 1,\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * })\n * .onDuplicateKeyUpdate({ updated_at: new Date().toISOString() })\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * insert into `person` (`id`, `first_name`, `last_name`, `gender`)\n * values (?, ?, ?, ?)\n * on duplicate key update `updated_at` = ?\n * ```\n */\n onDuplicateKeyUpdate(update) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {\n onDuplicateKey: OnDuplicateKeyNode.create(parseUpdateObjectExpression(update)),\n }),\n });\n }\n returning(selection) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n returningAll() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll()),\n });\n }\n output(args) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n /**\n * Clears all `returning` clauses from the query.\n *\n * ### Examples\n *\n * ```ts\n * await db.insertInto('person')\n * .values({ first_name: 'James', last_name: 'Smith', gender: 'male' })\n * .returning(['first_name'])\n * .clearReturning()\n * .execute()\n * ```\n *\n * The generated SQL(PostgreSQL):\n *\n * ```sql\n * insert into \"person\" (\"first_name\", \"last_name\", \"gender\") values ($1, $2, $3)\n * ```\n */\n clearReturning() {\n return new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n *\n * If you want to conditionally call a method on `this`, see\n * the {@link $if} method.\n *\n * ### Examples\n *\n * The next example uses a helper function `log` to log a query:\n *\n * ```ts\n * import type { Compilable } from 'kysely'\n *\n * function log(qb: T): T {\n * console.log(qb.compile())\n * return qb\n * }\n *\n * await db.insertInto('person')\n * .values({ first_name: 'John', last_name: 'Doe', gender: 'male' })\n * .$call(log)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n /**\n * Call `func(this)` if `condition` is true.\n *\n * This method is especially handy with optional selects. Any `returning` or `returningAll`\n * method calls add columns as optional fields to the output type when called inside\n * the `func` callback. This is because we can't know if those selections were actually\n * made before running the code.\n *\n * You can also call any other methods inside the callback.\n *\n * ### Examples\n *\n * ```ts\n * import type { NewPerson } from 'type-editor' // imaginary module\n *\n * async function insertPerson(values: NewPerson, returnLastName: boolean) {\n * return await db\n * .insertInto('person')\n * .values(values)\n * .returning(['id', 'first_name'])\n * .$if(returnLastName, (qb) => qb.returning('last_name'))\n * .executeTakeFirstOrThrow()\n * }\n * ```\n *\n * Any selections added inside the `if` callback will be added as optional fields to the\n * output type since we can't know if the selections were actually made before running\n * the code. In the example above the return type of the `insertPerson` function is:\n *\n * ```ts\n * Promise<{\n * id: number\n * first_name: string\n * last_name?: string\n * }>\n * ```\n */\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new InsertQueryBuilder({\n ...this.#props,\n });\n }\n /**\n * Change the output type of the query.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `InsertQueryBuilder` with a new output type.\n */\n $castTo() {\n return new InsertQueryBuilder(this.#props);\n }\n /**\n * Narrows (parts of) the output type of the query.\n *\n * Kysely tries to be as type-safe as possible, but in some cases we have to make\n * compromises for better maintainability and compilation performance. At present,\n * Kysely doesn't narrow the output type of the query based on {@link values} input\n * when using {@link returning} or {@link returningAll}.\n *\n * This utility method is very useful for these situations, as it removes unncessary\n * runtime assertion/guard code. Its input type is limited to the output type\n * of the query, so you can't add a column that doesn't exist, or change a column's\n * type to something that doesn't exist in its union type.\n *\n * ### Examples\n *\n * Turn this code:\n *\n * ```ts\n * import type { Person } from 'type-editor' // imaginary module\n *\n * const person = await db.insertInto('person')\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * nullable_column: 'hell yeah!'\n * })\n * .returningAll()\n * .executeTakeFirstOrThrow()\n *\n * if (isWithNoNullValue(person)) {\n * functionThatExpectsPersonWithNonNullValue(person)\n * }\n *\n * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {\n * return person.nullable_column != null\n * }\n * ```\n *\n * Into this:\n *\n * ```ts\n * import type { NotNull } from 'kysely'\n *\n * const person = await db.insertInto('person')\n * .values({\n * first_name: 'John',\n * last_name: 'Doe',\n * gender: 'male',\n * nullable_column: 'hell yeah!'\n * })\n * .returningAll()\n * .$narrowType<{ nullable_column: NotNull }>()\n * .executeTakeFirstOrThrow()\n *\n * functionThatExpectsPersonWithNonNullValue(person)\n * ```\n */\n $narrowType() {\n return new InsertQueryBuilder(this.#props);\n }\n /**\n * Asserts that query's output row type equals the given type `T`.\n *\n * This method can be used to simplify excessively complex types to make TypeScript happy\n * and much faster.\n *\n * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much\n * for TypeScript and you get errors like this:\n *\n * ```\n * error TS2589: Type instantiation is excessively deep and possibly infinite.\n * ```\n *\n * In these case you can often use this method to help TypeScript a little bit. When you use this\n * method to assert the output type of a query, Kysely can drop the complex output type that\n * consists of multiple nested helper types and replace it with the simple asserted type.\n *\n * Using this method doesn't reduce type safety at all. You have to pass in a type that is\n * structurally equal to the current type.\n *\n * ### Examples\n *\n * ```ts\n * import type { NewPerson, NewPet, Species } from 'type-editor' // imaginary module\n *\n * async function insertPersonAndPet(person: NewPerson, pet: Omit) {\n * return await db\n * .with('new_person', (qb) => qb\n * .insertInto('person')\n * .values(person)\n * .returning('id')\n * .$assertType<{ id: number }>()\n * )\n * .with('new_pet', (qb) => qb\n * .insertInto('pet')\n * .values((eb) => ({\n * owner_id: eb.selectFrom('new_person').select('id'),\n * ...pet\n * }))\n * .returning(['name as pet_name', 'species'])\n * .$assertType<{ pet_name: string, species: Species }>()\n * )\n * .selectFrom(['new_person', 'new_pet'])\n * .selectAll()\n * .executeTakeFirstOrThrow()\n * }\n * ```\n */\n $assertType() {\n return new InsertQueryBuilder(this.#props);\n }\n /**\n * Returns a copy of this InsertQueryBuilder instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new InsertQueryBuilder({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n /**\n * Executes the query and returns an array of rows.\n *\n * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.\n */\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n const { adapter } = this.#props.executor;\n const query = compiledQuery.query;\n if ((query.returning && adapter.supportsReturning) ||\n (query.output && adapter.supportsOutput)) {\n return result.rows;\n }\n return [\n new InsertResult(result.insertId, result.numAffectedRows ?? BigInt(0)),\n ];\n }\n /**\n * Executes the query and returns the first result or undefined if\n * the query returned no result.\n */\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n /**\n * Executes the query and returns the first result or throws if\n * the query returned no result.\n *\n * By default an instance of {@link NoResultError} is thrown, but you can\n * provide a custom error class, or callback as the only argument to throw a different\n * error.\n */\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new InsertQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n", "/// \nexport class DeleteResult {\n numDeletedRows;\n constructor(numDeletedRows) {\n this.numDeletedRows = numDeletedRows;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const LimitNode = freeze({\n is(node) {\n return node.kind === 'LimitNode';\n },\n create(limit) {\n return freeze({\n kind: 'LimitNode',\n limit,\n });\n },\n});\n", "/// \nvar _a;\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTableExpressionOrList, } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { DeleteResult } from './delete-result.js';\nimport { DeleteQueryNode } from '../operation-node/delete-query-node.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nexport class DeleteQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n /**\n * Changes a `delete from` query into a `delete top from` query.\n *\n * `top` clause is only supported by some dialects like MS SQL Server.\n *\n * ### Examples\n *\n * Delete the first 5 rows:\n *\n * ```ts\n * await db\n * .deleteFrom('person')\n * .top(5)\n * .where('age', '>', 18)\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * delete top(5) from \"person\" where \"age\" > @1\n * ```\n *\n * Delete the first 50% of rows:\n *\n * ```ts\n * await db\n * .deleteFrom('person')\n * .top(50, 'percent')\n * .where('age', '>', 18)\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * delete top(50) percent from \"person\" where \"age\" > @1\n * ```\n */\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n using(tables) {\n return new _a({\n ...this.#props,\n queryNode: DeleteQueryNode.cloneWithUsing(this.#props.queryNode, parseTableExpressionOrList(tables)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n returning(selection) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n returningAll(table) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n output(args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n /**\n * Clears all `returning` clauses from the query.\n *\n * ### Examples\n *\n * ```ts\n * await db.deleteFrom('pet')\n * .returningAll()\n * .where('name', '=', 'Max')\n * .clearReturning()\n * .execute()\n * ```\n *\n * The generated SQL(PostgreSQL):\n *\n * ```sql\n * delete from \"pet\" where \"name\" = \"Max\"\n * ```\n */\n clearReturning() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode),\n });\n }\n /**\n * Clears the `limit` clause from the query.\n *\n * ### Examples\n *\n * ```ts\n * await db.deleteFrom('pet')\n * .returningAll()\n * .where('name', '=', 'Max')\n * .limit(5)\n * .clearLimit()\n * .execute()\n * ```\n *\n * The generated SQL(PostgreSQL):\n *\n * ```sql\n * delete from \"pet\" where \"name\" = \"Max\" returning *\n * ```\n */\n clearLimit() {\n return new _a({\n ...this.#props,\n queryNode: DeleteQueryNode.cloneWithoutLimit(this.#props.queryNode),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n /**\n * Adds a limit clause to the query.\n *\n * A limit clause in a delete query is only supported by some dialects\n * like MySQL.\n *\n * ### Examples\n *\n * Delete 5 oldest items in a table:\n *\n * ```ts\n * await db\n * .deleteFrom('pet')\n * .orderBy('created_at')\n * .limit(5)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * delete from `pet` order by `created_at` limit ?\n * ```\n */\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: DeleteQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.deleteFrom('person')\n * .where('first_name', '=', 'John')\n * .modifyEnd(sql`-- This is a comment`)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * delete from `person`\n * where `first_name` = \"John\" -- This is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n *\n * If you want to conditionally call a method on `this`, see\n * the {@link $if} method.\n *\n * ### Examples\n *\n * The next example uses a helper function `log` to log a query:\n *\n * ```ts\n * import type { Compilable } from 'kysely'\n *\n * function log(qb: T): T {\n * console.log(qb.compile())\n * return qb\n * }\n *\n * await db.deleteFrom('person')\n * .$call(log)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n /**\n * Call `func(this)` if `condition` is true.\n *\n * This method is especially handy with optional selects. Any `returning` or `returningAll`\n * method calls add columns as optional fields to the output type when called inside\n * the `func` callback. This is because we can't know if those selections were actually\n * made before running the code.\n *\n * You can also call any other methods inside the callback.\n *\n * ### Examples\n *\n * ```ts\n * async function deletePerson(id: number, returnLastName: boolean) {\n * return await db\n * .deleteFrom('person')\n * .where('id', '=', id)\n * .returning(['id', 'first_name'])\n * .$if(returnLastName, (qb) => qb.returning('last_name'))\n * .executeTakeFirstOrThrow()\n * }\n * ```\n *\n * Any selections added inside the `if` callback will be added as optional fields to the\n * output type since we can't know if the selections were actually made before running\n * the code. In the example above the return type of the `deletePerson` function is:\n *\n * ```ts\n * Promise<{\n * id: number\n * first_name: string\n * last_name?: string\n * }>\n * ```\n */\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n /**\n * Change the output type of the query.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `DeleteQueryBuilder` with a new output type.\n */\n $castTo() {\n return new _a(this.#props);\n }\n /**\n * Narrows (parts of) the output type of the query.\n *\n * Kysely tries to be as type-safe as possible, but in some cases we have to make\n * compromises for better maintainability and compilation performance. At present,\n * Kysely doesn't narrow the output type of the query when using {@link where} and {@link returning} or {@link returningAll}.\n *\n * This utility method is very useful for these situations, as it removes unncessary\n * runtime assertion/guard code. Its input type is limited to the output type\n * of the query, so you can't add a column that doesn't exist, or change a column's\n * type to something that doesn't exist in its union type.\n *\n * ### Examples\n *\n * Turn this code:\n *\n * ```ts\n * import type { Person } from 'type-editor' // imaginary module\n *\n * const person = await db.deleteFrom('person')\n * .where('id', '=', 3)\n * .where('nullable_column', 'is not', null)\n * .returningAll()\n * .executeTakeFirstOrThrow()\n *\n * if (isWithNoNullValue(person)) {\n * functionThatExpectsPersonWithNonNullValue(person)\n * }\n *\n * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {\n * return person.nullable_column != null\n * }\n * ```\n *\n * Into this:\n *\n * ```ts\n * import type { NotNull } from 'kysely'\n *\n * const person = await db.deleteFrom('person')\n * .where('id', '=', 3)\n * .where('nullable_column', 'is not', null)\n * .returningAll()\n * .$narrowType<{ nullable_column: NotNull }>()\n * .executeTakeFirstOrThrow()\n *\n * functionThatExpectsPersonWithNonNullValue(person)\n * ```\n */\n $narrowType() {\n return new _a(this.#props);\n }\n /**\n * Asserts that query's output row type equals the given type `T`.\n *\n * This method can be used to simplify excessively complex types to make TypeScript happy\n * and much faster.\n *\n * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much\n * for TypeScript and you get errors like this:\n *\n * ```\n * error TS2589: Type instantiation is excessively deep and possibly infinite.\n * ```\n *\n * In these case you can often use this method to help TypeScript a little bit. When you use this\n * method to assert the output type of a query, Kysely can drop the complex output type that\n * consists of multiple nested helper types and replace it with the simple asserted type.\n *\n * Using this method doesn't reduce type safety at all. You have to pass in a type that is\n * structurally equal to the current type.\n *\n * ### Examples\n *\n * ```ts\n * import type { Species } from 'type-editor' // imaginary module\n *\n * async function deletePersonAndPets(personId: number) {\n * return await db\n * .with('deleted_person', (qb) => qb\n * .deleteFrom('person')\n * .where('id', '=', personId)\n * .returning('first_name')\n * .$assertType<{ first_name: string }>()\n * )\n * .with('deleted_pets', (qb) => qb\n * .deleteFrom('pet')\n * .where('owner_id', '=', personId)\n * .returning(['name as pet_name', 'species'])\n * .$assertType<{ pet_name: string, species: Species }>()\n * )\n * .selectFrom(['deleted_person', 'deleted_pets'])\n * .selectAll()\n * .execute()\n * }\n * ```\n */\n $assertType() {\n return new _a(this.#props);\n }\n /**\n * Returns a copy of this DeleteQueryBuilder instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n /**\n * Executes the query and returns an array of rows.\n *\n * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.\n */\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n const { adapter } = this.#props.executor;\n const query = compiledQuery.query;\n if ((query.returning && adapter.supportsReturning) ||\n (query.output && adapter.supportsOutput)) {\n return result.rows;\n }\n return [new DeleteResult(result.numAffectedRows ?? BigInt(0))];\n }\n /**\n * Executes the query and returns the first result or undefined if\n * the query returned no result.\n */\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n /**\n * Executes the query and returns the first result or throws if\n * the query returned no result.\n *\n * By default an instance of {@link NoResultError} is thrown, but you can\n * provide a custom error class, or callback as the only argument to throw a different\n * error.\n */\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = DeleteQueryBuilder;\n", "/// \nexport class UpdateResult {\n /**\n * The number of rows the update query updated (even if not changed).\n */\n numUpdatedRows;\n /**\n * The number of rows the update query changed.\n *\n * This is **optional** and only supported in dialects such as MySQL.\n * You would probably use {@link numUpdatedRows} in most cases.\n */\n numChangedRows;\n constructor(numUpdatedRows, numChangedRows) {\n this.numUpdatedRows = numUpdatedRows;\n this.numChangedRows = numChangedRows;\n }\n}\n", "/// \nvar _a;\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTableExpressionOrList, } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { UpdateQueryNode } from '../operation-node/update-query-node.js';\nimport { parseUpdate, } from '../parser/update-set-parser.js';\nimport { freeze } from '../util/object-utils.js';\nimport { UpdateResult } from './update-result.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { parseTop } from '../parser/top-parser.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nexport class UpdateQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n /**\n * Changes an `update` query into a `update top` query.\n *\n * `top` clause is only supported by some dialects like MS SQL Server.\n *\n * ### Examples\n *\n * Update the first row:\n *\n * ```ts\n * await db.updateTable('person')\n * .top(1)\n * .set({ first_name: 'Foo' })\n * .where('age', '>', 18)\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * update top(1) \"person\" set \"first_name\" = @1 where \"age\" > @2\n * ```\n *\n * Update the 50% first rows:\n *\n * ```ts\n * await db.updateTable('person')\n * .top(50, 'percent')\n * .set({ first_name: 'Foo' })\n * .where('age', '>', 18)\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * update top(50) percent \"person\" set \"first_name\" = @1 where \"age\" > @2\n * ```\n */\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n from(from) {\n return new _a({\n ...this.#props,\n queryNode: UpdateQueryNode.cloneWithFromItems(this.#props.queryNode, parseTableExpressionOrList(from)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n /**\n * Adds a limit clause to the update query for supported databases, such as MySQL.\n *\n * ### Examples\n *\n * Update the first 2 rows in the 'person' table:\n *\n * ```ts\n * await db\n * .updateTable('person')\n * .set({ first_name: 'Foo' })\n * .limit(2)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * update `person` set `first_name` = ? limit ?\n * ```\n */\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: UpdateQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n set(...args) {\n return new _a({\n ...this.#props,\n queryNode: UpdateQueryNode.cloneWithUpdates(this.#props.queryNode, parseUpdate(...args)),\n });\n }\n returning(selection) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n returningAll(table) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n output(args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.updateTable('person')\n * .set({ age: 39 })\n * .where('first_name', '=', 'John')\n * .modifyEnd(sql.raw('-- This is a comment'))\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * update `person`\n * set `age` = 39\n * where `first_name` = \"John\" -- This is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * Clears all `returning` clauses from the query.\n *\n * ### Examples\n *\n * ```ts\n * db.updateTable('person')\n * .returningAll()\n * .set({ age: 39 })\n * .where('first_name', '=', 'John')\n * .clearReturning()\n * ```\n *\n * The generated SQL(PostgreSQL):\n *\n * ```sql\n * update \"person\" set \"age\" = 39 where \"first_name\" = \"John\"\n * ```\n */\n clearReturning() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n *\n * If you want to conditionally call a method on `this`, see\n * the {@link $if} method.\n *\n * ### Examples\n *\n * The next example uses a helper function `log` to log a query:\n *\n * ```ts\n * import type { Compilable } from 'kysely'\n * import type { PersonUpdate } from 'type-editor' // imaginary module\n *\n * function log(qb: T): T {\n * console.log(qb.compile())\n * return qb\n * }\n *\n * const values = {\n * first_name: 'John',\n * } satisfies PersonUpdate\n *\n * db.updateTable('person')\n * .set(values)\n * .$call(log)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n /**\n * Call `func(this)` if `condition` is true.\n *\n * This method is especially handy with optional selects. Any `returning` or `returningAll`\n * method calls add columns as optional fields to the output type when called inside\n * the `func` callback. This is because we can't know if those selections were actually\n * made before running the code.\n *\n * You can also call any other methods inside the callback.\n *\n * ### Examples\n *\n * ```ts\n * import type { PersonUpdate } from 'type-editor' // imaginary module\n *\n * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {\n * return await db\n * .updateTable('person')\n * .set(updates)\n * .where('id', '=', id)\n * .returning(['id', 'first_name'])\n * .$if(returnLastName, (qb) => qb.returning('last_name'))\n * .executeTakeFirstOrThrow()\n * }\n * ```\n *\n * Any selections added inside the `if` callback will be added as optional fields to the\n * output type since we can't know if the selections were actually made before running\n * the code. In the example above the return type of the `updatePerson` function is:\n *\n * ```ts\n * Promise<{\n * id: number\n * first_name: string\n * last_name?: string\n * }>\n * ```\n */\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n /**\n * Change the output type of the query.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `UpdateQueryBuilder` with a new output type.\n */\n $castTo() {\n return new _a(this.#props);\n }\n /**\n * Narrows (parts of) the output type of the query.\n *\n * Kysely tries to be as type-safe as possible, but in some cases we have to make\n * compromises for better maintainability and compilation performance. At present,\n * Kysely doesn't narrow the output type of the query based on {@link set} input\n * when using {@link where} and/or {@link returning} or {@link returningAll}.\n *\n * This utility method is very useful for these situations, as it removes unncessary\n * runtime assertion/guard code. Its input type is limited to the output type\n * of the query, so you can't add a column that doesn't exist, or change a column's\n * type to something that doesn't exist in its union type.\n *\n * ### Examples\n *\n * Turn this code:\n *\n * ```ts\n * import type { Person } from 'type-editor' // imaginary module\n *\n * const id = 1\n * const now = new Date().toISOString()\n *\n * const person = await db.updateTable('person')\n * .set({ deleted_at: now })\n * .where('id', '=', id)\n * .where('nullable_column', 'is not', null)\n * .returningAll()\n * .executeTakeFirstOrThrow()\n *\n * if (isWithNoNullValue(person)) {\n * functionThatExpectsPersonWithNonNullValue(person)\n * }\n *\n * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {\n * return person.nullable_column != null\n * }\n * ```\n *\n * Into this:\n *\n * ```ts\n * import type { NotNull } from 'kysely'\n *\n * const id = 1\n * const now = new Date().toISOString()\n *\n * const person = await db.updateTable('person')\n * .set({ deleted_at: now })\n * .where('id', '=', id)\n * .where('nullable_column', 'is not', null)\n * .returningAll()\n * .$narrowType<{ deleted_at: Date; nullable_column: NotNull }>()\n * .executeTakeFirstOrThrow()\n *\n * functionThatExpectsPersonWithNonNullValue(person)\n * ```\n */\n $narrowType() {\n return new _a(this.#props);\n }\n /**\n * Asserts that query's output row type equals the given type `T`.\n *\n * This method can be used to simplify excessively complex types to make TypeScript happy\n * and much faster.\n *\n * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much\n * for TypeScript and you get errors like this:\n *\n * ```\n * error TS2589: Type instantiation is excessively deep and possibly infinite.\n * ```\n *\n * In these case you can often use this method to help TypeScript a little bit. When you use this\n * method to assert the output type of a query, Kysely can drop the complex output type that\n * consists of multiple nested helper types and replace it with the simple asserted type.\n *\n * Using this method doesn't reduce type safety at all. You have to pass in a type that is\n * structurally equal to the current type.\n *\n * ### Examples\n *\n * ```ts\n * import type { PersonUpdate, PetUpdate, Species } from 'type-editor' // imaginary module\n *\n * const person = {\n * id: 1,\n * gender: 'other',\n * } satisfies PersonUpdate\n *\n * const pet = {\n * name: 'Fluffy',\n * } satisfies PetUpdate\n *\n * const result = await db\n * .with('updated_person', (qb) => qb\n * .updateTable('person')\n * .set(person)\n * .where('id', '=', person.id)\n * .returning('first_name')\n * .$assertType<{ first_name: string }>()\n * )\n * .with('updated_pet', (qb) => qb\n * .updateTable('pet')\n * .set(pet)\n * .where('owner_id', '=', person.id)\n * .returning(['name as pet_name', 'species'])\n * .$assertType<{ pet_name: string, species: Species }>()\n * )\n * .selectFrom(['updated_person', 'updated_pet'])\n * .selectAll()\n * .executeTakeFirstOrThrow()\n * ```\n */\n $assertType() {\n return new _a(this.#props);\n }\n /**\n * Returns a copy of this UpdateQueryBuilder instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n /**\n * Executes the query and returns an array of rows.\n *\n * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.\n */\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n const { adapter } = this.#props.executor;\n const query = compiledQuery.query;\n if ((query.returning && adapter.supportsReturning) ||\n (query.output && adapter.supportsOutput)) {\n return result.rows;\n }\n return [\n new UpdateResult(result.numAffectedRows ?? BigInt(0), result.numChangedRows),\n ];\n }\n /**\n * Executes the query and returns the first result or undefined if\n * the query returned no result.\n */\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n /**\n * Executes the query and returns the first result or throws if\n * the query returned no result.\n *\n * By default an instance of {@link NoResultError} is thrown, but you can\n * provide a custom error class, or callback as the only argument to throw a different\n * error.\n */\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = UpdateQueryBuilder;\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\nimport { TableNode } from './table-node.js';\n/**\n * @internal\n */\nexport const CommonTableExpressionNameNode = freeze({\n is(node) {\n return node.kind === 'CommonTableExpressionNameNode';\n },\n create(tableName, columnNames) {\n return freeze({\n kind: 'CommonTableExpressionNameNode',\n table: TableNode.create(tableName),\n columns: columnNames\n ? freeze(columnNames.map(ColumnNode.create))\n : undefined,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const CommonTableExpressionNode = freeze({\n is(node) {\n return node.kind === 'CommonTableExpressionNode';\n },\n create(name, expression) {\n return freeze({\n kind: 'CommonTableExpressionNode',\n name,\n expression,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { CommonTableExpressionNode } from '../operation-node/common-table-expression-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class CTEBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Makes the common table expression materialized.\n */\n materialized() {\n return new CTEBuilder({\n ...this.#props,\n node: CommonTableExpressionNode.cloneWith(this.#props.node, {\n materialized: true,\n }),\n });\n }\n /**\n * Makes the common table expression not materialized.\n */\n notMaterialized() {\n return new CTEBuilder({\n ...this.#props,\n node: CommonTableExpressionNode.cloneWith(this.#props.node, {\n materialized: false,\n }),\n });\n }\n toOperationNode() {\n return this.#props.node;\n }\n}\n", "/// \nimport { CommonTableExpressionNameNode } from '../operation-node/common-table-expression-name-node.js';\nimport { createQueryCreator } from './parse-utils.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { CTEBuilder, } from '../query-builder/cte-builder.js';\nimport { CommonTableExpressionNode } from '../operation-node/common-table-expression-node.js';\nexport function parseCommonTableExpression(nameOrBuilderCallback, expression) {\n const expressionNode = expression(createQueryCreator()).toOperationNode();\n if (isFunction(nameOrBuilderCallback)) {\n return nameOrBuilderCallback(cteBuilderFactory(expressionNode)).toOperationNode();\n }\n return CommonTableExpressionNode.create(parseCommonTableExpressionName(nameOrBuilderCallback), expressionNode);\n}\nfunction cteBuilderFactory(expressionNode) {\n return (name) => {\n return new CTEBuilder({\n node: CommonTableExpressionNode.create(parseCommonTableExpressionName(name), expressionNode),\n });\n };\n}\nfunction parseCommonTableExpressionName(name) {\n if (name.includes('(')) {\n const parts = name.split(/[\\(\\)]/);\n const table = parts[0];\n const columns = parts[1].split(',').map((it) => it.trim());\n return CommonTableExpressionNameNode.create(table, columns);\n }\n else {\n return CommonTableExpressionNameNode.create(name);\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const WithNode = freeze({\n is(node) {\n return node.kind === 'WithNode';\n },\n create(expression, params) {\n return freeze({\n kind: 'WithNode',\n expressions: freeze([expression]),\n ...params,\n });\n },\n cloneWithExpression(withNode, expression) {\n return freeze({\n ...withNode,\n expressions: freeze([...withNode.expressions, expression]),\n });\n },\n});\n", "/// \nconst CHARS = [\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n 'a',\n 'b',\n 'c',\n 'd',\n 'e',\n 'f',\n 'g',\n 'h',\n 'i',\n 'j',\n 'k',\n 'l',\n 'm',\n 'n',\n 'o',\n 'p',\n 'q',\n 'r',\n 's',\n 't',\n 'u',\n 'v',\n 'w',\n 'x',\n 'y',\n 'z',\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n];\nexport function randomString(length) {\n let chars = '';\n for (let i = 0; i < length; ++i) {\n chars += randomChar();\n }\n return chars;\n}\nfunction randomChar() {\n return CHARS[~~(Math.random() * CHARS.length)];\n}\n", "/// \nimport { randomString } from './random-string.js';\nexport function createQueryId() {\n return new LazyQueryId();\n}\nclass LazyQueryId {\n #queryId;\n get queryId() {\n if (this.#queryId === undefined) {\n this.#queryId = randomString(8);\n }\n return this.#queryId;\n }\n}\n", "/// \n/**\n * Helper function to check listed properties according to given type. Check if all properties has been used when object is initialised.\n *\n * Example use:\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n *\n * // propB has to be mentioned even it is optional. It still should be initialized with undefined.\n * const a: SomeType = requireAllProps({ propA: \"value A\", propB: undefined });\n *\n * // checked type is implicit for variable.\n * const b = requireAllProps({ propA: \"value A\", propB: undefined });\n * ```\n *\n * Wrong use of this helper:\n *\n * 1. Omit checked type - all checked properties will be expect as of type never\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * // const z: SomeType = requireAllProps({ propC: \"no type will work\" }); // Property 'propA' is missing in type '{ propC: string; }' but required in type 'SomeType'.\n * ```\n *\n * 2. Apply to spreaded object - there is no way how to check in compile time if spreaded object contains all properties\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * const y: SomeType = { propA: \"\" }; // valid object according to SomeType declaration\n * // const x = requireAllProps({ ...y }); // Argument of type '{ propA: string; propB?: number; }' is not assignable to parameter of type 'AllProps'.\n * ```\n *\n * @param obj object to check if all properties has been used\n * @returns untouched obj parameter is returned\n */\nexport function requireAllProps(obj) {\n return obj;\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { requireAllProps } from '../util/require-all-props.js';\n/**\n * Transforms an operation node tree into another one.\n *\n * Kysely queries are expressed internally as a tree of objects (operation nodes).\n * `OperationNodeTransformer` takes such a tree as its input and returns a\n * transformed deep copy of it. By default the `OperationNodeTransformer`\n * does nothing. You need to override one or more methods to make it do\n * something.\n *\n * There's a method for each node type. For example if you'd like to convert\n * each identifier (table name, column name, alias etc.) from camelCase to\n * snake_case, you'd do something like this:\n *\n * ```ts\n * import { type IdentifierNode, OperationNodeTransformer } from 'kysely'\n * import snakeCase from 'lodash/snakeCase'\n *\n * class CamelCaseTransformer extends OperationNodeTransformer {\n * override transformIdentifier(node: IdentifierNode): IdentifierNode {\n * node = super.transformIdentifier(node)\n *\n * return {\n * ...node,\n * name: snakeCase(node.name),\n * }\n * }\n * }\n *\n * const transformer = new CamelCaseTransformer()\n *\n * const query = db.selectFrom('person').select(['first_name', 'last_name'])\n *\n * const tree = transformer.transformNode(query.toOperationNode())\n * ```\n */\nexport class OperationNodeTransformer {\n nodeStack = [];\n #transformers = freeze({\n AliasNode: this.transformAlias.bind(this),\n ColumnNode: this.transformColumn.bind(this),\n IdentifierNode: this.transformIdentifier.bind(this),\n SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this),\n RawNode: this.transformRaw.bind(this),\n ReferenceNode: this.transformReference.bind(this),\n SelectQueryNode: this.transformSelectQuery.bind(this),\n SelectionNode: this.transformSelection.bind(this),\n TableNode: this.transformTable.bind(this),\n FromNode: this.transformFrom.bind(this),\n SelectAllNode: this.transformSelectAll.bind(this),\n AndNode: this.transformAnd.bind(this),\n OrNode: this.transformOr.bind(this),\n ValueNode: this.transformValue.bind(this),\n ValueListNode: this.transformValueList.bind(this),\n PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this),\n ParensNode: this.transformParens.bind(this),\n JoinNode: this.transformJoin.bind(this),\n OperatorNode: this.transformOperator.bind(this),\n WhereNode: this.transformWhere.bind(this),\n InsertQueryNode: this.transformInsertQuery.bind(this),\n DeleteQueryNode: this.transformDeleteQuery.bind(this),\n ReturningNode: this.transformReturning.bind(this),\n CreateTableNode: this.transformCreateTable.bind(this),\n AddColumnNode: this.transformAddColumn.bind(this),\n ColumnDefinitionNode: this.transformColumnDefinition.bind(this),\n DropTableNode: this.transformDropTable.bind(this),\n DataTypeNode: this.transformDataType.bind(this),\n OrderByNode: this.transformOrderBy.bind(this),\n OrderByItemNode: this.transformOrderByItem.bind(this),\n GroupByNode: this.transformGroupBy.bind(this),\n GroupByItemNode: this.transformGroupByItem.bind(this),\n UpdateQueryNode: this.transformUpdateQuery.bind(this),\n ColumnUpdateNode: this.transformColumnUpdate.bind(this),\n LimitNode: this.transformLimit.bind(this),\n OffsetNode: this.transformOffset.bind(this),\n OnConflictNode: this.transformOnConflict.bind(this),\n OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this),\n CreateIndexNode: this.transformCreateIndex.bind(this),\n DropIndexNode: this.transformDropIndex.bind(this),\n ListNode: this.transformList.bind(this),\n PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this),\n UniqueConstraintNode: this.transformUniqueConstraint.bind(this),\n ReferencesNode: this.transformReferences.bind(this),\n CheckConstraintNode: this.transformCheckConstraint.bind(this),\n WithNode: this.transformWith.bind(this),\n CommonTableExpressionNode: this.transformCommonTableExpression.bind(this),\n CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this),\n HavingNode: this.transformHaving.bind(this),\n CreateSchemaNode: this.transformCreateSchema.bind(this),\n DropSchemaNode: this.transformDropSchema.bind(this),\n AlterTableNode: this.transformAlterTable.bind(this),\n DropColumnNode: this.transformDropColumn.bind(this),\n RenameColumnNode: this.transformRenameColumn.bind(this),\n AlterColumnNode: this.transformAlterColumn.bind(this),\n ModifyColumnNode: this.transformModifyColumn.bind(this),\n AddConstraintNode: this.transformAddConstraint.bind(this),\n DropConstraintNode: this.transformDropConstraint.bind(this),\n RenameConstraintNode: this.transformRenameConstraint.bind(this),\n ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this),\n CreateViewNode: this.transformCreateView.bind(this),\n RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this),\n DropViewNode: this.transformDropView.bind(this),\n GeneratedNode: this.transformGenerated.bind(this),\n DefaultValueNode: this.transformDefaultValue.bind(this),\n OnNode: this.transformOn.bind(this),\n ValuesNode: this.transformValues.bind(this),\n SelectModifierNode: this.transformSelectModifier.bind(this),\n CreateTypeNode: this.transformCreateType.bind(this),\n DropTypeNode: this.transformDropType.bind(this),\n ExplainNode: this.transformExplain.bind(this),\n DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this),\n AggregateFunctionNode: this.transformAggregateFunction.bind(this),\n OverNode: this.transformOver.bind(this),\n PartitionByNode: this.transformPartitionBy.bind(this),\n PartitionByItemNode: this.transformPartitionByItem.bind(this),\n SetOperationNode: this.transformSetOperation.bind(this),\n BinaryOperationNode: this.transformBinaryOperation.bind(this),\n UnaryOperationNode: this.transformUnaryOperation.bind(this),\n UsingNode: this.transformUsing.bind(this),\n FunctionNode: this.transformFunction.bind(this),\n CaseNode: this.transformCase.bind(this),\n WhenNode: this.transformWhen.bind(this),\n JSONReferenceNode: this.transformJSONReference.bind(this),\n JSONPathNode: this.transformJSONPath.bind(this),\n JSONPathLegNode: this.transformJSONPathLeg.bind(this),\n JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this),\n TupleNode: this.transformTuple.bind(this),\n MergeQueryNode: this.transformMergeQuery.bind(this),\n MatchedNode: this.transformMatched.bind(this),\n AddIndexNode: this.transformAddIndex.bind(this),\n CastNode: this.transformCast.bind(this),\n FetchNode: this.transformFetch.bind(this),\n TopNode: this.transformTop.bind(this),\n OutputNode: this.transformOutput.bind(this),\n OrActionNode: this.transformOrAction.bind(this),\n CollateNode: this.transformCollate.bind(this),\n });\n transformNode(node, queryId) {\n if (!node) {\n return node;\n }\n this.nodeStack.push(node);\n const out = this.transformNodeImpl(node, queryId);\n this.nodeStack.pop();\n return freeze(out);\n }\n transformNodeImpl(node, queryId) {\n return this.#transformers[node.kind](node, queryId);\n }\n transformNodeList(list, queryId) {\n if (!list) {\n return list;\n }\n return freeze(list.map((node) => this.transformNode(node, queryId)));\n }\n transformSelectQuery(node, queryId) {\n return requireAllProps({\n kind: 'SelectQueryNode',\n from: this.transformNode(node.from, queryId),\n selections: this.transformNodeList(node.selections, queryId),\n distinctOn: this.transformNodeList(node.distinctOn, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n groupBy: this.transformNode(node.groupBy, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n where: this.transformNode(node.where, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n limit: this.transformNode(node.limit, queryId),\n offset: this.transformNode(node.offset, queryId),\n with: this.transformNode(node.with, queryId),\n having: this.transformNode(node.having, queryId),\n explain: this.transformNode(node.explain, queryId),\n setOperations: this.transformNodeList(node.setOperations, queryId),\n fetch: this.transformNode(node.fetch, queryId),\n top: this.transformNode(node.top, queryId),\n });\n }\n transformSelection(node, queryId) {\n return requireAllProps({\n kind: 'SelectionNode',\n selection: this.transformNode(node.selection, queryId),\n });\n }\n transformColumn(node, queryId) {\n return requireAllProps({\n kind: 'ColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAlias(node, queryId) {\n return requireAllProps({\n kind: 'AliasNode',\n node: this.transformNode(node.node, queryId),\n alias: this.transformNode(node.alias, queryId),\n });\n }\n transformTable(node, queryId) {\n return requireAllProps({\n kind: 'TableNode',\n table: this.transformNode(node.table, queryId),\n });\n }\n transformFrom(node, queryId) {\n return requireAllProps({\n kind: 'FromNode',\n froms: this.transformNodeList(node.froms, queryId),\n });\n }\n transformReference(node, queryId) {\n return requireAllProps({\n kind: 'ReferenceNode',\n column: this.transformNode(node.column, queryId),\n table: this.transformNode(node.table, queryId),\n });\n }\n transformAnd(node, queryId) {\n return requireAllProps({\n kind: 'AndNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformOr(node, queryId) {\n return requireAllProps({\n kind: 'OrNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformValueList(node, queryId) {\n return requireAllProps({\n kind: 'ValueListNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformParens(node, queryId) {\n return requireAllProps({\n kind: 'ParensNode',\n node: this.transformNode(node.node, queryId),\n });\n }\n transformJoin(node, queryId) {\n return requireAllProps({\n kind: 'JoinNode',\n joinType: node.joinType,\n table: this.transformNode(node.table, queryId),\n on: this.transformNode(node.on, queryId),\n });\n }\n transformRaw(node, queryId) {\n return requireAllProps({\n kind: 'RawNode',\n sqlFragments: freeze([...node.sqlFragments]),\n parameters: this.transformNodeList(node.parameters, queryId),\n });\n }\n transformWhere(node, queryId) {\n return requireAllProps({\n kind: 'WhereNode',\n where: this.transformNode(node.where, queryId),\n });\n }\n transformInsertQuery(node, queryId) {\n return requireAllProps({\n kind: 'InsertQueryNode',\n into: this.transformNode(node.into, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n values: this.transformNode(node.values, queryId),\n returning: this.transformNode(node.returning, queryId),\n onConflict: this.transformNode(node.onConflict, queryId),\n onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n ignore: node.ignore,\n orAction: this.transformNode(node.orAction, queryId),\n replace: node.replace,\n explain: this.transformNode(node.explain, queryId),\n defaultValues: node.defaultValues,\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformValues(node, queryId) {\n return requireAllProps({\n kind: 'ValuesNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformDeleteQuery(node, queryId) {\n return requireAllProps({\n kind: 'DeleteQueryNode',\n from: this.transformNode(node.from, queryId),\n using: this.transformNode(node.using, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n limit: this.transformNode(node.limit, queryId),\n explain: this.transformNode(node.explain, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformReturning(node, queryId) {\n return requireAllProps({\n kind: 'ReturningNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformCreateTable(node, queryId) {\n return requireAllProps({\n kind: 'CreateTableNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n constraints: this.transformNodeList(node.constraints, queryId),\n temporary: node.temporary,\n ifNotExists: node.ifNotExists,\n onCommit: node.onCommit,\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n selectQuery: this.transformNode(node.selectQuery, queryId),\n });\n }\n transformColumnDefinition(node, queryId) {\n return requireAllProps({\n kind: 'ColumnDefinitionNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n references: this.transformNode(node.references, queryId),\n primaryKey: node.primaryKey,\n autoIncrement: node.autoIncrement,\n unique: node.unique,\n notNull: node.notNull,\n unsigned: node.unsigned,\n defaultTo: this.transformNode(node.defaultTo, queryId),\n check: this.transformNode(node.check, queryId),\n generated: this.transformNode(node.generated, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n identity: node.identity,\n ifNotExists: node.ifNotExists,\n });\n }\n transformAddColumn(node, queryId) {\n return requireAllProps({\n kind: 'AddColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformDropTable(node, queryId) {\n return requireAllProps({\n kind: 'DropTableNode',\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformOrderBy(node, queryId) {\n return requireAllProps({\n kind: 'OrderByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformOrderByItem(node, queryId) {\n return requireAllProps({\n kind: 'OrderByItemNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n direction: this.transformNode(node.direction, queryId),\n collation: this.transformNode(node.collation, queryId),\n nulls: node.nulls,\n });\n }\n transformGroupBy(node, queryId) {\n return requireAllProps({\n kind: 'GroupByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformGroupByItem(node, queryId) {\n return requireAllProps({\n kind: 'GroupByItemNode',\n groupBy: this.transformNode(node.groupBy, queryId),\n });\n }\n transformUpdateQuery(node, queryId) {\n return requireAllProps({\n kind: 'UpdateQueryNode',\n table: this.transformNode(node.table, queryId),\n from: this.transformNode(node.from, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n explain: this.transformNode(node.explain, queryId),\n limit: this.transformNode(node.limit, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n });\n }\n transformColumnUpdate(node, queryId) {\n return requireAllProps({\n kind: 'ColumnUpdateNode',\n column: this.transformNode(node.column, queryId),\n value: this.transformNode(node.value, queryId),\n });\n }\n transformLimit(node, queryId) {\n return requireAllProps({\n kind: 'LimitNode',\n limit: this.transformNode(node.limit, queryId),\n });\n }\n transformOffset(node, queryId) {\n return requireAllProps({\n kind: 'OffsetNode',\n offset: this.transformNode(node.offset, queryId),\n });\n }\n transformOnConflict(node, queryId) {\n return requireAllProps({\n kind: 'OnConflictNode',\n columns: this.transformNodeList(node.columns, queryId),\n constraint: this.transformNode(node.constraint, queryId),\n indexExpression: this.transformNode(node.indexExpression, queryId),\n indexWhere: this.transformNode(node.indexWhere, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n updateWhere: this.transformNode(node.updateWhere, queryId),\n doNothing: node.doNothing,\n });\n }\n transformOnDuplicateKey(node, queryId) {\n return requireAllProps({\n kind: 'OnDuplicateKeyNode',\n updates: this.transformNodeList(node.updates, queryId),\n });\n }\n transformCreateIndex(node, queryId) {\n return requireAllProps({\n kind: 'CreateIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n where: this.transformNode(node.where, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n });\n }\n transformList(node, queryId) {\n return requireAllProps({\n kind: 'ListNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformDropIndex(node, queryId) {\n return requireAllProps({\n kind: 'DropIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformPrimaryKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'PrimaryKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformUniqueConstraint(node, queryId) {\n return requireAllProps({\n kind: 'UniqueConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformForeignKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'ForeignKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n references: this.transformNode(node.references, queryId),\n name: this.transformNode(node.name, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformSetOperation(node, queryId) {\n return requireAllProps({\n kind: 'SetOperationNode',\n operator: node.operator,\n expression: this.transformNode(node.expression, queryId),\n all: node.all,\n });\n }\n transformReferences(node, queryId) {\n return requireAllProps({\n kind: 'ReferencesNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n });\n }\n transformCheckConstraint(node, queryId) {\n return requireAllProps({\n kind: 'CheckConstraintNode',\n expression: this.transformNode(node.expression, queryId),\n name: this.transformNode(node.name, queryId),\n });\n }\n transformWith(node, queryId) {\n return requireAllProps({\n kind: 'WithNode',\n expressions: this.transformNodeList(node.expressions, queryId),\n recursive: node.recursive,\n });\n }\n transformCommonTableExpression(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNode',\n name: this.transformNode(node.name, queryId),\n materialized: node.materialized,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformCommonTableExpressionName(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNameNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n });\n }\n transformHaving(node, queryId) {\n return requireAllProps({\n kind: 'HavingNode',\n having: this.transformNode(node.having, queryId),\n });\n }\n transformCreateSchema(node, queryId) {\n return requireAllProps({\n kind: 'CreateSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformDropSchema(node, queryId) {\n return requireAllProps({\n kind: 'DropSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformAlterTable(node, queryId) {\n return requireAllProps({\n kind: 'AlterTableNode',\n table: this.transformNode(node.table, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n setSchema: this.transformNode(node.setSchema, queryId),\n columnAlterations: this.transformNodeList(node.columnAlterations, queryId),\n addConstraint: this.transformNode(node.addConstraint, queryId),\n dropConstraint: this.transformNode(node.dropConstraint, queryId),\n renameConstraint: this.transformNode(node.renameConstraint, queryId),\n addIndex: this.transformNode(node.addIndex, queryId),\n dropIndex: this.transformNode(node.dropIndex, queryId),\n });\n }\n transformDropColumn(node, queryId) {\n return requireAllProps({\n kind: 'DropColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformRenameColumn(node, queryId) {\n return requireAllProps({\n kind: 'RenameColumnNode',\n column: this.transformNode(node.column, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n });\n }\n transformAlterColumn(node, queryId) {\n return requireAllProps({\n kind: 'AlterColumnNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId),\n setDefault: this.transformNode(node.setDefault, queryId),\n dropDefault: node.dropDefault,\n setNotNull: node.setNotNull,\n dropNotNull: node.dropNotNull,\n });\n }\n transformModifyColumn(node, queryId) {\n return requireAllProps({\n kind: 'ModifyColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAddConstraint(node, queryId) {\n return requireAllProps({\n kind: 'AddConstraintNode',\n constraint: this.transformNode(node.constraint, queryId),\n });\n }\n transformDropConstraint(node, queryId) {\n return requireAllProps({\n kind: 'DropConstraintNode',\n constraintName: this.transformNode(node.constraintName, queryId),\n ifExists: node.ifExists,\n modifier: node.modifier,\n });\n }\n transformRenameConstraint(node, queryId) {\n return requireAllProps({\n kind: 'RenameConstraintNode',\n oldName: this.transformNode(node.oldName, queryId),\n newName: this.transformNode(node.newName, queryId),\n });\n }\n transformCreateView(node, queryId) {\n return requireAllProps({\n kind: 'CreateViewNode',\n name: this.transformNode(node.name, queryId),\n temporary: node.temporary,\n orReplace: node.orReplace,\n ifNotExists: node.ifNotExists,\n materialized: node.materialized,\n columns: this.transformNodeList(node.columns, queryId),\n as: this.transformNode(node.as, queryId),\n });\n }\n transformRefreshMaterializedView(node, queryId) {\n return requireAllProps({\n kind: 'RefreshMaterializedViewNode',\n name: this.transformNode(node.name, queryId),\n concurrently: node.concurrently,\n withNoData: node.withNoData,\n });\n }\n transformDropView(node, queryId) {\n return requireAllProps({\n kind: 'DropViewNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n materialized: node.materialized,\n cascade: node.cascade,\n });\n }\n transformGenerated(node, queryId) {\n return requireAllProps({\n kind: 'GeneratedNode',\n byDefault: node.byDefault,\n always: node.always,\n identity: node.identity,\n stored: node.stored,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformDefaultValue(node, queryId) {\n return requireAllProps({\n kind: 'DefaultValueNode',\n defaultValue: this.transformNode(node.defaultValue, queryId),\n });\n }\n transformOn(node, queryId) {\n return requireAllProps({\n kind: 'OnNode',\n on: this.transformNode(node.on, queryId),\n });\n }\n transformSelectModifier(node, queryId) {\n return requireAllProps({\n kind: 'SelectModifierNode',\n modifier: node.modifier,\n rawModifier: this.transformNode(node.rawModifier, queryId),\n of: this.transformNodeList(node.of, queryId),\n });\n }\n transformCreateType(node, queryId) {\n return requireAllProps({\n kind: 'CreateTypeNode',\n name: this.transformNode(node.name, queryId),\n enum: this.transformNode(node.enum, queryId),\n });\n }\n transformDropType(node, queryId) {\n return requireAllProps({\n kind: 'DropTypeNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n });\n }\n transformExplain(node, queryId) {\n return requireAllProps({\n kind: 'ExplainNode',\n format: node.format,\n options: this.transformNode(node.options, queryId),\n });\n }\n transformSchemableIdentifier(node, queryId) {\n return requireAllProps({\n kind: 'SchemableIdentifierNode',\n schema: this.transformNode(node.schema, queryId),\n identifier: this.transformNode(node.identifier, queryId),\n });\n }\n transformAggregateFunction(node, queryId) {\n return requireAllProps({\n kind: 'AggregateFunctionNode',\n func: node.func,\n aggregated: this.transformNodeList(node.aggregated, queryId),\n distinct: node.distinct,\n orderBy: this.transformNode(node.orderBy, queryId),\n withinGroup: this.transformNode(node.withinGroup, queryId),\n filter: this.transformNode(node.filter, queryId),\n over: this.transformNode(node.over, queryId),\n });\n }\n transformOver(node, queryId) {\n return requireAllProps({\n kind: 'OverNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformPartitionBy(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformPartitionByItem(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByItemNode',\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformBinaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'BinaryOperationNode',\n leftOperand: this.transformNode(node.leftOperand, queryId),\n operator: this.transformNode(node.operator, queryId),\n rightOperand: this.transformNode(node.rightOperand, queryId),\n });\n }\n transformUnaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'UnaryOperationNode',\n operator: this.transformNode(node.operator, queryId),\n operand: this.transformNode(node.operand, queryId),\n });\n }\n transformUsing(node, queryId) {\n return requireAllProps({\n kind: 'UsingNode',\n tables: this.transformNodeList(node.tables, queryId),\n });\n }\n transformFunction(node, queryId) {\n return requireAllProps({\n kind: 'FunctionNode',\n func: node.func,\n arguments: this.transformNodeList(node.arguments, queryId),\n });\n }\n transformCase(node, queryId) {\n return requireAllProps({\n kind: 'CaseNode',\n value: this.transformNode(node.value, queryId),\n when: this.transformNodeList(node.when, queryId),\n else: this.transformNode(node.else, queryId),\n isStatement: node.isStatement,\n });\n }\n transformWhen(node, queryId) {\n return requireAllProps({\n kind: 'WhenNode',\n condition: this.transformNode(node.condition, queryId),\n result: this.transformNode(node.result, queryId),\n });\n }\n transformJSONReference(node, queryId) {\n return requireAllProps({\n kind: 'JSONReferenceNode',\n reference: this.transformNode(node.reference, queryId),\n traversal: this.transformNode(node.traversal, queryId),\n });\n }\n transformJSONPath(node, queryId) {\n return requireAllProps({\n kind: 'JSONPathNode',\n inOperator: this.transformNode(node.inOperator, queryId),\n pathLegs: this.transformNodeList(node.pathLegs, queryId),\n });\n }\n transformJSONPathLeg(node, _queryId) {\n return requireAllProps({\n kind: 'JSONPathLegNode',\n type: node.type,\n value: node.value,\n });\n }\n transformJSONOperatorChain(node, queryId) {\n return requireAllProps({\n kind: 'JSONOperatorChainNode',\n operator: this.transformNode(node.operator, queryId),\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformTuple(node, queryId) {\n return requireAllProps({\n kind: 'TupleNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformMergeQuery(node, queryId) {\n return requireAllProps({\n kind: 'MergeQueryNode',\n into: this.transformNode(node.into, queryId),\n using: this.transformNode(node.using, queryId),\n whens: this.transformNodeList(node.whens, queryId),\n with: this.transformNode(node.with, queryId),\n top: this.transformNode(node.top, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n output: this.transformNode(node.output, queryId),\n returning: this.transformNode(node.returning, queryId),\n });\n }\n transformMatched(node, _queryId) {\n return requireAllProps({\n kind: 'MatchedNode',\n not: node.not,\n bySource: node.bySource,\n });\n }\n transformAddIndex(node, queryId) {\n return requireAllProps({\n kind: 'AddIndexNode',\n name: this.transformNode(node.name, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformCast(node, queryId) {\n return requireAllProps({\n kind: 'CastNode',\n expression: this.transformNode(node.expression, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n });\n }\n transformFetch(node, queryId) {\n return requireAllProps({\n kind: 'FetchNode',\n rowCount: this.transformNode(node.rowCount, queryId),\n modifier: node.modifier,\n });\n }\n transformTop(node, _queryId) {\n return requireAllProps({\n kind: 'TopNode',\n expression: node.expression,\n modifiers: node.modifiers,\n });\n }\n transformOutput(node, queryId) {\n return requireAllProps({\n kind: 'OutputNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformDataType(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformSelectAll(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformIdentifier(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformPrimitiveValueList(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOperator(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformDefaultInsertValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOrAction(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformCollate(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n}\n", "/// \nimport { AliasNode } from '../../operation-node/alias-node.js';\nimport { IdentifierNode } from '../../operation-node/identifier-node.js';\nimport { JoinNode } from '../../operation-node/join-node.js';\nimport { ListNode } from '../../operation-node/list-node.js';\nimport { OperationNodeTransformer } from '../../operation-node/operation-node-transformer.js';\nimport { SchemableIdentifierNode } from '../../operation-node/schemable-identifier-node.js';\nimport { TableNode } from '../../operation-node/table-node.js';\nimport { UsingNode } from '../../operation-node/using-node.js';\nimport { freeze } from '../../util/object-utils.js';\n// This object exist only so that we get a type error when a new RootOperationNode\n// is added. If you get a type error here, make sure to add the new root node and\n// handle it correctly in the transformer.\n//\n// DO NOT REFACTOR THIS EVEN IF IT SEEMS USELESS TO YOU!\nconst ROOT_OPERATION_NODES = freeze({\n AlterTableNode: true,\n CreateIndexNode: true,\n CreateSchemaNode: true,\n CreateTableNode: true,\n CreateTypeNode: true,\n CreateViewNode: true,\n RefreshMaterializedViewNode: true,\n DeleteQueryNode: true,\n DropIndexNode: true,\n DropSchemaNode: true,\n DropTableNode: true,\n DropTypeNode: true,\n DropViewNode: true,\n InsertQueryNode: true,\n RawNode: true,\n SelectQueryNode: true,\n UpdateQueryNode: true,\n MergeQueryNode: true,\n});\nconst SCHEMALESS_FUNCTIONS = {\n json_agg: true,\n to_json: true,\n};\nexport class WithSchemaTransformer extends OperationNodeTransformer {\n #schema;\n #schemableIds = new Set();\n #ctes = new Set();\n constructor(schema) {\n super();\n this.#schema = schema;\n }\n transformNodeImpl(node, queryId) {\n if (!this.#isRootOperationNode(node)) {\n return super.transformNodeImpl(node, queryId);\n }\n const ctes = this.#collectCTEs(node);\n for (const cte of ctes) {\n this.#ctes.add(cte);\n }\n const tables = this.#collectSchemableIds(node);\n for (const table of tables) {\n this.#schemableIds.add(table);\n }\n const transformed = super.transformNodeImpl(node, queryId);\n for (const table of tables) {\n this.#schemableIds.delete(table);\n }\n for (const cte of ctes) {\n this.#ctes.delete(cte);\n }\n return transformed;\n }\n transformSchemableIdentifier(node, queryId) {\n const transformed = super.transformSchemableIdentifier(node, queryId);\n if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) {\n return transformed;\n }\n return {\n ...transformed,\n schema: IdentifierNode.create(this.#schema),\n };\n }\n transformReferences(node, queryId) {\n const transformed = super.transformReferences(node, queryId);\n if (transformed.table.table.schema) {\n return transformed;\n }\n return {\n ...transformed,\n table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name),\n };\n }\n transformAggregateFunction(node, queryId) {\n return {\n ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId),\n aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, 'aggregated'),\n };\n }\n transformFunction(node, queryId) {\n return {\n ...super.transformFunction({ ...node, arguments: [] }, queryId),\n arguments: this.#transformTableArgsWithoutSchemas(node, queryId, 'arguments'),\n };\n }\n transformSelectModifier(node, queryId) {\n return {\n ...super.transformSelectModifier({ ...node, of: undefined }, queryId),\n of: node.of?.map((item) => TableNode.is(item) && !item.table.schema\n ? {\n ...item,\n table: this.transformIdentifier(item.table.identifier, queryId),\n }\n : this.transformNode(item, queryId)),\n };\n }\n #transformTableArgsWithoutSchemas(node, queryId, argsKey) {\n return SCHEMALESS_FUNCTIONS[node.func]\n ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema\n ? this.transformNode(arg, queryId)\n : {\n ...arg,\n table: this.transformIdentifier(arg.table.identifier, queryId),\n })\n : this.transformNodeList(node[argsKey], queryId);\n }\n #isRootOperationNode(node) {\n return node.kind in ROOT_OPERATION_NODES;\n }\n #collectSchemableIds(node) {\n const schemableIds = new Set();\n if ('name' in node && node.name && SchemableIdentifierNode.is(node.name)) {\n this.#collectSchemableId(node.name, schemableIds);\n }\n if ('from' in node && node.from) {\n for (const from of node.from.froms) {\n this.#collectSchemableIdsFromTableExpr(from, schemableIds);\n }\n }\n if ('into' in node && node.into) {\n this.#collectSchemableIdsFromTableExpr(node.into, schemableIds);\n }\n if ('table' in node && node.table) {\n this.#collectSchemableIdsFromTableExpr(node.table, schemableIds);\n }\n if ('joins' in node && node.joins) {\n for (const join of node.joins) {\n this.#collectSchemableIdsFromTableExpr(join.table, schemableIds);\n }\n }\n if ('using' in node && node.using) {\n if (JoinNode.is(node.using)) {\n this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds);\n }\n else {\n this.#collectSchemableIdsFromTableExpr(node.using, schemableIds);\n }\n }\n return schemableIds;\n }\n #collectCTEs(node) {\n const ctes = new Set();\n if ('with' in node && node.with) {\n this.#collectCTEIds(node.with, ctes);\n }\n return ctes;\n }\n #collectSchemableIdsFromTableExpr(node, schemableIds) {\n if (TableNode.is(node)) {\n return this.#collectSchemableId(node.table, schemableIds);\n }\n if (AliasNode.is(node) && TableNode.is(node.node)) {\n return this.#collectSchemableId(node.node.table, schemableIds);\n }\n if (ListNode.is(node)) {\n for (const table of node.items) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n if (UsingNode.is(node)) {\n for (const table of node.tables) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n }\n #collectSchemableId(node, schemableIds) {\n const id = node.identifier.name;\n if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) {\n schemableIds.add(id);\n }\n }\n #collectCTEIds(node, ctes) {\n for (const expr of node.expressions) {\n const cteId = expr.name.table.table.identifier.name;\n if (!this.#ctes.has(cteId)) {\n ctes.add(cteId);\n }\n }\n }\n}\n", "/// \nimport { WithSchemaTransformer } from './with-schema-transformer.js';\nexport class WithSchemaPlugin {\n #transformer;\n constructor(schema) {\n this.#transformer = new WithSchemaTransformer(schema);\n }\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n return args.result;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const MatchedNode = freeze({\n is(node) {\n return node.kind === 'MatchedNode';\n },\n create(not, bySource = false) {\n return freeze({\n kind: 'MatchedNode',\n not,\n bySource,\n });\n },\n});\n", "/// \nimport { MatchedNode } from '../operation-node/matched-node.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { isString } from '../util/object-utils.js';\nimport { parseFilterList, parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from './binary-operation-parser.js';\nexport function parseMergeWhen(type, args, refRight) {\n return WhenNode.create(parseFilterList([\n MatchedNode.create(!type.isMatched, type.bySource),\n ...(args && args.length > 0\n ? [\n args.length === 3 && refRight\n ? parseReferentialBinaryOperation(args[0], args[1], args[2])\n : parseValueBinaryOperationOrExpression(args),\n ]\n : []),\n ], 'and', false));\n}\nexport function parseMergeThen(result) {\n if (isString(result)) {\n return RawNode.create([result], []);\n }\n if (isOperationNodeSource(result)) {\n return result.toOperationNode();\n }\n return result;\n}\n", "/// \nexport class Deferred {\n #promise;\n #resolve;\n #reject;\n constructor() {\n this.#promise = new Promise((resolve, reject) => {\n this.#reject = reject;\n this.#resolve = resolve;\n });\n }\n get promise() {\n return this.#promise;\n }\n resolve = (value) => {\n if (this.#resolve) {\n this.#resolve(value);\n }\n };\n reject = (reason) => {\n if (this.#reject) {\n this.#reject(reason);\n }\n };\n}\n", "/// \nimport { Deferred } from './deferred.js';\nimport { freeze } from './object-utils.js';\nexport async function provideControlledConnection(connectionProvider) {\n const connectionDefer = new Deferred();\n const connectionReleaseDefer = new Deferred();\n connectionProvider\n .provideConnection(async (connection) => {\n connectionDefer.resolve(connection);\n return await connectionReleaseDefer.promise;\n })\n .catch((ex) => connectionDefer.reject(ex));\n // Create composite of the connection and the release method instead of\n // modifying the connection or creating a new nesting `DatabaseConnection`.\n // This way we don't accidentally override any methods of 3rd party\n // connections and don't return wrapped connections to drivers that\n // expect a certain specific connection class.\n return freeze({\n connection: await connectionDefer.promise,\n release: connectionReleaseDefer.resolve,\n });\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { provideControlledConnection } from '../util/provide-controlled-connection.js';\nimport { logOnce } from '../util/log-once.js';\nconst NO_PLUGINS = freeze([]);\nexport class QueryExecutorBase {\n #plugins;\n constructor(plugins = NO_PLUGINS) {\n this.#plugins = plugins;\n }\n get plugins() {\n return this.#plugins;\n }\n transformQuery(node, queryId) {\n for (const plugin of this.#plugins) {\n const transformedNode = plugin.transformQuery({ node, queryId });\n // We need to do a runtime check here. There is no good way\n // to write types that enforce this constraint.\n if (transformedNode.kind === node.kind) {\n node = transformedNode;\n }\n else {\n throw new Error([\n `KyselyPlugin.transformQuery must return a node`,\n `of the same kind that was given to it.`,\n `The plugin was given a ${node.kind}`,\n `but it returned a ${transformedNode.kind}`,\n ].join(' '));\n }\n }\n return node;\n }\n async executeQuery(compiledQuery) {\n return await this.provideConnection(async (connection) => {\n const result = await connection.executeQuery(compiledQuery);\n if ('numUpdatedOrDeletedRows' in result) {\n logOnce('kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.');\n }\n return await this.#transformResult(result, compiledQuery.queryId);\n });\n }\n async *stream(compiledQuery, chunkSize) {\n const { connection, release } = await provideControlledConnection(this);\n try {\n for await (const result of connection.streamQuery(compiledQuery, chunkSize)) {\n yield await this.#transformResult(result, compiledQuery.queryId);\n }\n }\n finally {\n release();\n }\n }\n async #transformResult(result, queryId) {\n for (const plugin of this.#plugins) {\n result = await plugin.transformResult({ result, queryId });\n }\n return result;\n }\n}\n", "/// \nimport { QueryExecutorBase } from './query-executor-base.js';\n/**\n * A {@link QueryExecutor} subclass that can be used when you don't\n * have a {@link QueryCompiler}, {@link ConnectionProvider} or any\n * other needed things to actually execute queries.\n */\nexport class NoopQueryExecutor extends QueryExecutorBase {\n get adapter() {\n throw new Error('this query cannot be compiled to SQL');\n }\n compileQuery() {\n throw new Error('this query cannot be compiled to SQL');\n }\n provideConnection() {\n throw new Error('this query cannot be executed');\n }\n withConnectionProvider() {\n throw new Error('this query cannot have a connection provider');\n }\n withPlugin(plugin) {\n return new NoopQueryExecutor([...this.plugins, plugin]);\n }\n withPlugins(plugins) {\n return new NoopQueryExecutor([...this.plugins, ...plugins]);\n }\n withPluginAtFront(plugin) {\n return new NoopQueryExecutor([plugin, ...this.plugins]);\n }\n withoutPlugins() {\n return new NoopQueryExecutor([]);\n }\n}\nexport const NOOP_QUERY_EXECUTOR = new NoopQueryExecutor();\n", "/// \nexport class MergeResult {\n numChangedRows;\n constructor(numChangedRows) {\n this.numChangedRows = numChangedRows;\n }\n}\n", "/// \nimport { InsertQueryNode } from '../operation-node/insert-query-node.js';\nimport { MergeQueryNode } from '../operation-node/merge-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { UpdateQueryNode } from '../operation-node/update-query-node.js';\nimport { parseInsertExpression, } from '../parser/insert-values-parser.js';\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseMergeThen, parseMergeWhen } from '../parser/merge-parser.js';\nimport { parseSelectAll, parseSelectArg, } from '../parser/select-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { freeze } from '../util/object-utils.js';\nimport { MergeResult } from './merge-result.js';\nimport { NoResultError, isNoResultErrorConstructor, } from './no-result-error.js';\nimport { UpdateQueryBuilder } from './update-query-builder.js';\nexport class MergeQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db\n * .mergeInto('person')\n * .using('pet', 'pet.owner_id', 'person.id')\n * .whenMatched()\n * .thenDelete()\n * .modifyEnd(sql.raw('-- this is a comment'))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\" using \"pet\" on \"pet\".\"owner_id\" = \"person\".\"id\" when matched then delete -- this is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * Changes a `merge into` query to an `merge top into` query.\n *\n * `top` clause is only supported by some dialects like MS SQL Server.\n *\n * ### Examples\n *\n * Affect 5 matched rows at most:\n *\n * ```ts\n * await db.mergeInto('person')\n * .top(5)\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDelete()\n * .execute()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * merge top(5) into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * delete\n * ```\n *\n * Affect 50% of matched rows:\n *\n * ```ts\n * await db.mergeInto('person')\n * .top(50, 'percent')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDelete()\n * .execute()\n * ```\n *\n * The generated SQL (MS SQL Server):\n *\n * ```sql\n * merge top(50) percent into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * delete\n * ```\n */\n top(expression, modifiers) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n using(...args) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithUsing(this.#props.queryNode, parseJoin('Using', args)),\n });\n }\n returning(args) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n returningAll(table) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n output(args) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new MergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n}\nexport class WheneableMergeQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db\n * .mergeInto('person')\n * .using('pet', 'pet.owner_id', 'person.id')\n * .whenMatched()\n * .thenDelete()\n * .modifyEnd(sql.raw('-- this is a comment'))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\" using \"pet\" on \"pet\".\"owner_id\" = \"person\".\"id\" when matched then delete -- this is a comment\n * ```\n */\n modifyEnd(modifier) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()),\n });\n }\n /**\n * See {@link MergeQueryBuilder.top}.\n */\n top(expression, modifiers) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n /**\n * Adds a simple `when matched` clause to the query.\n *\n * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}.\n *\n * For a simple `when not matched` clause, see {@link whenNotMatched}.\n *\n * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDelete()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * delete\n * ```\n */\n whenMatched() {\n return this.#whenMatched([]);\n }\n whenMatchedAnd(...args) {\n return this.#whenMatched(args);\n }\n /**\n * Adds the `when matched` clause to the query with an `and` condition. But unlike\n * {@link whenMatchedAnd}, this method accepts a column reference as the 3rd argument.\n *\n * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation\n * for that method for more examples.\n */\n whenMatchedAndRef(lhs, op, rhs) {\n return this.#whenMatched([lhs, op, rhs], true);\n }\n #whenMatched(args, refRight) {\n return new MatchedThenableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: true }, args, refRight)),\n });\n }\n /**\n * Adds a simple `when not matched` clause to the query.\n *\n * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}.\n *\n * For a simple `when matched` clause, see {@link whenMatched}.\n *\n * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenNotMatched()\n * .thenInsertValues({\n * first_name: 'John',\n * last_name: 'Doe',\n * })\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when not matched then\n * insert (\"first_name\", \"last_name\") values ($1, $2)\n * ```\n */\n whenNotMatched() {\n return this.#whenNotMatched([]);\n }\n whenNotMatchedAnd(...args) {\n return this.#whenNotMatched(args);\n }\n /**\n * Adds the `when not matched` clause to the query with an `and` condition. But unlike\n * {@link whenNotMatchedAnd}, this method accepts a column reference as the 3rd argument.\n *\n * Unlike {@link whenMatchedAndRef}, you cannot reference columns from the target table.\n *\n * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation\n * for that method for more examples.\n */\n whenNotMatchedAndRef(lhs, op, rhs) {\n return this.#whenNotMatched([lhs, op, rhs], true);\n }\n /**\n * Adds a simple `when not matched by source` clause to the query.\n *\n * Supported in MS SQL Server.\n *\n * Similar to {@link whenNotMatched}, but returns a {@link MatchedThenableMergeQueryBuilder}.\n */\n whenNotMatchedBySource() {\n return this.#whenNotMatched([], false, true);\n }\n whenNotMatchedBySourceAnd(...args) {\n return this.#whenNotMatched(args, false, true);\n }\n /**\n * Adds the `when not matched by source` clause to the query with an `and` condition.\n *\n * Similar to {@link whenNotMatchedAndRef}, but you can reference columns from\n * the target table, and not from source table and returns a {@link MatchedThenableMergeQueryBuilder}.\n */\n whenNotMatchedBySourceAndRef(lhs, op, rhs) {\n return this.#whenNotMatched([lhs, op, rhs], true, true);\n }\n returning(args) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n returningAll(table) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n output(args) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)),\n });\n }\n outputAll(table) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n #whenNotMatched(args, refRight = false, bySource = false) {\n const props = {\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: false, bySource }, args, refRight)),\n };\n const Builder = bySource\n ? MatchedThenableMergeQueryBuilder\n : NotMatchedThenableMergeQueryBuilder;\n return new Builder(props);\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n *\n * If you want to conditionally call a method on `this`, see\n * the {@link $if} method.\n *\n * ### Examples\n *\n * The next example uses a helper function `log` to log a query:\n *\n * ```ts\n * import type { Compilable } from 'kysely'\n *\n * function log(qb: T): T {\n * console.log(qb.compile())\n * return qb\n * }\n *\n * await db.updateTable('person')\n * .set({ first_name: 'John' })\n * .$call(log)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n /**\n * Call `func(this)` if `condition` is true.\n *\n * This method is especially handy with optional selects. Any `returning` or `returningAll`\n * method calls add columns as optional fields to the output type when called inside\n * the `func` callback. This is because we can't know if those selections were actually\n * made before running the code.\n *\n * You can also call any other methods inside the callback.\n *\n * ### Examples\n *\n * ```ts\n * import type { PersonUpdate } from 'type-editor' // imaginary module\n *\n * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {\n * return await db\n * .updateTable('person')\n * .set(updates)\n * .where('id', '=', id)\n * .returning(['id', 'first_name'])\n * .$if(returnLastName, (qb) => qb.returning('last_name'))\n * .executeTakeFirstOrThrow()\n * }\n * ```\n *\n * Any selections added inside the `if` callback will be added as optional fields to the\n * output type since we can't know if the selections were actually made before running\n * the code. In the example above the return type of the `updatePerson` function is:\n *\n * ```ts\n * Promise<{\n * id: number\n * first_name: string\n * last_name?: string\n * }>\n * ```\n */\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n /**\n * Executes the query and returns an array of rows.\n *\n * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.\n */\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n const { adapter } = this.#props.executor;\n const query = compiledQuery.query;\n if ((query.returning && adapter.supportsReturning) ||\n (query.output && adapter.supportsOutput)) {\n return result.rows;\n }\n return [new MergeResult(result.numAffectedRows)];\n }\n /**\n * Executes the query and returns the first result or undefined if\n * the query returned no result.\n */\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n /**\n * Executes the query and returns the first result or throws if\n * the query returned no result.\n *\n * By default an instance of {@link NoResultError} is thrown, but you can\n * provide a custom error class, or callback as the only argument to throw a different\n * error.\n */\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n}\nexport class MatchedThenableMergeQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Performs the `delete` action.\n *\n * To perform the `do nothing` action, see {@link thenDoNothing}.\n *\n * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDelete()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * delete\n * ```\n */\n thenDelete() {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen('delete')),\n });\n }\n /**\n * Performs the `do nothing` action.\n *\n * This is supported in PostgreSQL.\n *\n * To perform the `delete` action, see {@link thenDelete}.\n *\n * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenDoNothing()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * do nothing\n * ```\n */\n thenDoNothing() {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen('do nothing')),\n });\n }\n /**\n * Perform an `update` operation with a full-fledged {@link UpdateQueryBuilder}.\n * This is handy when multiple `set` invocations are needed.\n *\n * For a shorthand version of this method, see {@link thenUpdateSet}.\n *\n * To perform the `delete` action, see {@link thenDelete}.\n *\n * To perform the `do nothing` action, see {@link thenDoNothing}.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenMatched()\n * .thenUpdate((ub) => ub\n * .set(sql`metadata['has_pets']`, 'Y')\n * .set({\n * updated_at: new Date().toISOString(),\n * })\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when matched then\n * update set metadata['has_pets'] = $1, \"updated_at\" = $2\n * ```\n */\n thenUpdate(set) {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(set(new UpdateQueryBuilder({\n queryId: this.#props.queryId,\n executor: NOOP_QUERY_EXECUTOR,\n queryNode: UpdateQueryNode.createWithoutTable(),\n })))),\n });\n }\n thenUpdateSet(...args) {\n // @ts-ignore not sure how to type this so it won't complain about set(...args).\n return this.thenUpdate((ub) => ub.set(...args));\n }\n}\nexport class NotMatchedThenableMergeQueryBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Performs the `do nothing` action.\n *\n * This is supported in PostgreSQL.\n *\n * To perform the `insert` action, see {@link thenInsertValues}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db.mergeInto('person')\n * .using('pet', 'person.id', 'pet.owner_id')\n * .whenNotMatched()\n * .thenDoNothing()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\" on \"person\".\"id\" = \"pet\".\"owner_id\"\n * when not matched then\n * do nothing\n * ```\n */\n thenDoNothing() {\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen('do nothing')),\n });\n }\n thenInsertValues(insert) {\n const [columns, values] = parseInsertExpression(insert);\n return new WheneableMergeQueryBuilder({\n ...this.#props,\n queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(), {\n columns,\n values,\n }))),\n });\n }\n}\n", "/// \nimport { createSelectQueryBuilder, } from './query-builder/select-query-builder.js';\nimport { InsertQueryBuilder } from './query-builder/insert-query-builder.js';\nimport { DeleteQueryBuilder } from './query-builder/delete-query-builder.js';\nimport { UpdateQueryBuilder } from './query-builder/update-query-builder.js';\nimport { DeleteQueryNode } from './operation-node/delete-query-node.js';\nimport { InsertQueryNode } from './operation-node/insert-query-node.js';\nimport { SelectQueryNode } from './operation-node/select-query-node.js';\nimport { UpdateQueryNode } from './operation-node/update-query-node.js';\nimport { parseTable, parseTableExpressionOrList, parseAliasedTable, } from './parser/table-parser.js';\nimport { parseCommonTableExpression, } from './parser/with-parser.js';\nimport { WithNode } from './operation-node/with-node.js';\nimport { createQueryId } from './util/query-id.js';\nimport { WithSchemaPlugin } from './plugin/with-schema/with-schema-plugin.js';\nimport { freeze } from './util/object-utils.js';\nimport { parseSelectArg, } from './parser/select-parser.js';\nimport { MergeQueryBuilder } from './query-builder/merge-query-builder.js';\nimport { MergeQueryNode } from './operation-node/merge-query-node.js';\nexport class QueryCreator {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Creates a `select` query builder for the given table or tables.\n *\n * The tables passed to this method are built as the query's `from` clause.\n *\n * ### Examples\n *\n * Create a select query for one table:\n *\n * ```ts\n * db.selectFrom('person').selectAll()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select * from \"person\"\n * ```\n *\n * Create a select query for one table with an alias:\n *\n * ```ts\n * const persons = await db.selectFrom('person as p')\n * .select(['p.id', 'first_name'])\n * .execute()\n *\n * console.log(persons[0].id)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"p\".\"id\", \"first_name\" from \"person\" as \"p\"\n * ```\n *\n * Create a select query from a subquery:\n *\n * ```ts\n * const persons = await db.selectFrom(\n * (eb) => eb.selectFrom('person').select('person.id as identifier').as('p')\n * )\n * .select('p.identifier')\n * .execute()\n *\n * console.log(persons[0].identifier)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"p\".\"identifier\",\n * from (\n * select \"person\".\"id\" as \"identifier\" from \"person\"\n * ) as p\n * ```\n *\n * Create a select query from raw sql:\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * const items = await db\n * .selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q'))\n * .select('q.one')\n * .execute()\n *\n * console.log(items[0].one)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"q\".\"one\",\n * from (\n * select 1 as one\n * ) as q\n * ```\n *\n * When you use the `sql` tag you need to also provide the result type of the\n * raw snippet / query so that Kysely can figure out what columns are\n * available for the rest of the query.\n *\n * The `selectFrom` method also accepts an array for multiple tables. All\n * the above examples can also be used in an array.\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * const items = await db.selectFrom([\n * 'person as p',\n * db.selectFrom('pet').select('pet.species').as('a'),\n * sql<{ one: number }>`(select 1 as one)`.as('q')\n * ])\n * .select(['p.id', 'a.species', 'q.one'])\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"p\".id, \"a\".\"species\", \"q\".\"one\"\n * from\n * \"person\" as \"p\",\n * (select \"pet\".\"species\" from \"pet\") as a,\n * (select 1 as one) as \"q\"\n * ```\n */\n selectFrom(from) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(from), this.#props.withNode),\n });\n }\n selectNoFrom(selection) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: SelectQueryNode.cloneWithSelections(SelectQueryNode.create(this.#props.withNode), parseSelectArg(selection)),\n });\n }\n /**\n * Creates an insert query.\n *\n * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}\n * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of\n * the inserted row if the db returned one.\n *\n * See the {@link InsertQueryBuilder.values | values} method for more info and examples. Also see\n * the {@link ReturningInterface.returning | returning} method for a way to return columns\n * on supported databases like PostgreSQL.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston'\n * })\n * .executeTakeFirst()\n *\n * console.log(result.insertId)\n * ```\n *\n * Some databases like PostgreSQL support the `returning` method:\n *\n * ```ts\n * const { id } = await db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston'\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n * ```\n */\n insertInto(table) {\n return new InsertQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode),\n });\n }\n /**\n * Creates a \"replace into\" query.\n *\n * This is only supported by some dialects like MySQL or SQLite.\n *\n * Similar to MySQL's {@link InsertQueryBuilder.onDuplicateKeyUpdate} that deletes\n * and inserts values on collision instead of updating existing rows.\n *\n * An alias of SQLite's {@link InsertQueryBuilder.orReplace}.\n *\n * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}\n * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of\n * the inserted row if the db returned one.\n *\n * See the {@link InsertQueryBuilder.values | values} method for more info and examples.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .replaceInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston'\n * })\n * .executeTakeFirstOrThrow()\n *\n * console.log(result.insertId)\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * replace into `person` (`first_name`, `last_name`) values (?, ?)\n * ```\n */\n replaceInto(table) {\n return new InsertQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode, true),\n });\n }\n /**\n * Creates a delete query.\n *\n * See the {@link DeleteQueryBuilder.where} method for examples on how to specify\n * a where clause for the delete operation.\n *\n * The return value of the query is an instance of {@link DeleteResult}.\n *\n * ### Examples\n *\n * \n *\n * Delete a single row:\n *\n * ```ts\n * const result = await db\n * .deleteFrom('person')\n * .where('person.id', '=', 1)\n * .executeTakeFirst()\n *\n * console.log(result.numDeletedRows)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * delete from \"person\" where \"person\".\"id\" = $1\n * ```\n *\n * Some databases such as MySQL support deleting from multiple tables:\n *\n * ```ts\n * const result = await db\n * .deleteFrom(['person', 'pet'])\n * .using('person')\n * .innerJoin('pet', 'pet.owner_id', 'person.id')\n * .where('person.id', '=', 1)\n * .executeTakeFirst()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * delete from `person`, `pet`\n * using `person`\n * inner join `pet` on `pet`.`owner_id` = `person`.`id`\n * where `person`.`id` = ?\n * ```\n */\n deleteFrom(from) {\n return new DeleteQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: DeleteQueryNode.create(parseTableExpressionOrList(from), this.#props.withNode),\n });\n }\n /**\n * Creates an update query.\n *\n * See the {@link UpdateQueryBuilder.where} method for examples on how to specify\n * a where clause for the update operation.\n *\n * See the {@link UpdateQueryBuilder.set} method for examples on how to\n * specify the updates.\n *\n * The return value of the query is an {@link UpdateResult}.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .updateTable('person')\n * .set({ first_name: 'Jennifer' })\n * .where('person.id', '=', 1)\n * .executeTakeFirst()\n *\n * console.log(result.numUpdatedRows)\n * ```\n */\n updateTable(tables) {\n return new UpdateQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: UpdateQueryNode.create(parseTableExpressionOrList(tables), this.#props.withNode),\n });\n }\n /**\n * Creates a merge query.\n *\n * The return value of the query is a {@link MergeResult}.\n *\n * See the {@link MergeQueryBuilder.using} method for examples on how to specify\n * the other table.\n *\n * ### Examples\n *\n * \n *\n * Update a target column based on the existence of a source row:\n *\n * ```ts\n * const result = await db\n * .mergeInto('person as target')\n * .using('pet as source', 'source.owner_id', 'target.id')\n * .whenMatchedAnd('target.has_pets', '!=', 'Y')\n * .thenUpdateSet({ has_pets: 'Y' })\n * .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y')\n * .thenUpdateSet({ has_pets: 'N' })\n * .executeTakeFirstOrThrow()\n *\n * console.log(result.numChangedRows)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"person\"\n * using \"pet\"\n * on \"pet\".\"owner_id\" = \"person\".\"id\"\n * when matched and \"has_pets\" != $1\n * then update set \"has_pets\" = $2\n * when not matched by source and \"has_pets\" = $3\n * then update set \"has_pets\" = $4\n * ```\n *\n * \n *\n * Merge new entries from a temporary changes table:\n *\n * ```ts\n * const result = await db\n * .mergeInto('wine as target')\n * .using(\n * 'wine_stock_change as source',\n * 'source.wine_name',\n * 'target.name',\n * )\n * .whenNotMatchedAnd('source.stock_delta', '>', 0)\n * .thenInsertValues(({ ref }) => ({\n * name: ref('source.wine_name'),\n * stock: ref('source.stock_delta'),\n * }))\n * .whenMatchedAnd(\n * (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')),\n * '>',\n * 0,\n * )\n * .thenUpdateSet('stock', (eb) =>\n * eb('target.stock', '+', eb.ref('source.stock_delta')),\n * )\n * .whenMatched()\n * .thenDelete()\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * merge into \"wine\" as \"target\"\n * using \"wine_stock_change\" as \"source\"\n * on \"source\".\"wine_name\" = \"target\".\"name\"\n * when not matched and \"source\".\"stock_delta\" > $1\n * then insert (\"name\", \"stock\") values (\"source\".\"wine_name\", \"source\".\"stock_delta\")\n * when matched and \"target\".\"stock\" + \"source\".\"stock_delta\" > $2\n * then update set \"stock\" = \"target\".\"stock\" + \"source\".\"stock_delta\"\n * when matched\n * then delete\n * ```\n */\n mergeInto(targetTable) {\n return new MergeQueryBuilder({\n queryId: createQueryId(),\n executor: this.#props.executor,\n queryNode: MergeQueryNode.create(parseAliasedTable(targetTable), this.#props.withNode),\n });\n }\n /**\n * Creates a `with` query (Common Table Expression).\n *\n * ### Examples\n *\n * \n *\n * Common table expressions (CTE) are a great way to modularize complex queries.\n * Essentially they allow you to run multiple separate queries within a\n * single roundtrip to the DB.\n *\n * Since CTEs are a part of the main query, query optimizers inside DB\n * engines are able to optimize the overall query. For example, postgres\n * is able to inline the CTEs inside the using queries if it decides it's\n * faster.\n *\n * ```ts\n * const result = await db\n * // Create a CTE called `jennifers` that selects all\n * // persons named 'Jennifer'.\n * .with('jennifers', (db) => db\n * .selectFrom('person')\n * .where('first_name', '=', 'Jennifer')\n * .select(['id', 'age'])\n * )\n * // Select all rows from the `jennifers` CTE and\n * // further filter it.\n * .with('adult_jennifers', (db) => db\n * .selectFrom('jennifers')\n * .where('age', '>', 18)\n * .select(['id', 'age'])\n * )\n * // Finally select all adult jennifers that are\n * // also younger than 60.\n * .selectFrom('adult_jennifers')\n * .where('age', '<', 60)\n * .selectAll()\n * .execute()\n * ```\n *\n * \n *\n * Some databases like postgres also allow you to run other queries than selects\n * in CTEs. On these databases CTEs are extremely powerful:\n *\n * ```ts\n * const result = await db\n * .with('new_person', (db) => db\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * age: 35,\n * })\n * .returning('id')\n * )\n * .with('new_pet', (db) => db\n * .insertInto('pet')\n * .values({\n * name: 'Doggo',\n * species: 'dog',\n * is_favorite: true,\n * // Use the id of the person we just inserted.\n * owner_id: db\n * .selectFrom('new_person')\n * .select('id')\n * })\n * .returning('id')\n * )\n * .selectFrom(['new_person', 'new_pet'])\n * .select([\n * 'new_person.id as person_id',\n * 'new_pet.id as pet_id'\n * ])\n * .execute()\n * ```\n *\n * The CTE name can optionally specify column names in addition to\n * a name. In that case Kysely requires the expression to retun\n * rows with the same columns.\n *\n * ```ts\n * await db\n * .with('jennifers(id, age)', (db) => db\n * .selectFrom('person')\n * .where('first_name', '=', 'Jennifer')\n * // This is ok since we return columns with the same\n * // names as specified by `jennifers(id, age)`.\n * .select(['id', 'age'])\n * )\n * .selectFrom('jennifers')\n * .selectAll()\n * .execute()\n * ```\n *\n * The first argument can also be a callback. The callback is passed\n * a `CTEBuilder` instance that can be used to configure the CTE:\n *\n * ```ts\n * await db\n * .with(\n * (cte) => cte('jennifers').materialized(),\n * (db) => db\n * .selectFrom('person')\n * .where('first_name', '=', 'Jennifer')\n * .select(['id', 'age'])\n * )\n * .selectFrom('jennifers')\n * .selectAll()\n * .execute()\n * ```\n */\n with(nameOrBuilder, expression) {\n const cte = parseCommonTableExpression(nameOrBuilder, expression);\n return new QueryCreator({\n ...this.#props,\n withNode: this.#props.withNode\n ? WithNode.cloneWithExpression(this.#props.withNode, cte)\n : WithNode.create(cte),\n });\n }\n /**\n * Creates a recursive `with` query (Common Table Expression).\n *\n * Note that recursiveness is a property of the whole `with` statement.\n * You cannot have recursive and non-recursive CTEs in a same `with` statement.\n * Therefore the recursiveness is determined by the **first** `with` or\n * `withRecusive` call you make.\n *\n * See the {@link with} method for examples and more documentation.\n */\n withRecursive(nameOrBuilder, expression) {\n const cte = parseCommonTableExpression(nameOrBuilder, expression);\n return new QueryCreator({\n ...this.#props,\n withNode: this.#props.withNode\n ? WithNode.cloneWithExpression(this.#props.withNode, cte)\n : WithNode.create(cte, { recursive: true }),\n });\n }\n /**\n * Returns a copy of this query creator instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new QueryCreator({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n /**\n * Returns a copy of this query creator instance without any plugins.\n */\n withoutPlugins() {\n return new QueryCreator({\n ...this.#props,\n executor: this.#props.executor.withoutPlugins(),\n });\n }\n /**\n * Sets the schema to be used for all table references that don't explicitly\n * specify a schema.\n *\n * This only affects the query created through the builder returned from\n * this method and doesn't modify the `db` instance.\n *\n * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0007-schemas.md)\n * for a more detailed explanation.\n *\n * ### Examples\n *\n * ```\n * await db\n * .withSchema('mammals')\n * .selectFrom('pet')\n * .selectAll()\n * .innerJoin('public.person', 'public.person.id', 'pet.owner_id')\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select * from \"mammals\".\"pet\"\n * inner join \"public\".\"person\"\n * on \"public\".\"person\".\"id\" = \"mammals\".\"pet\".\"owner_id\"\n * ```\n *\n * `withSchema` is smart enough to not add schema for aliases,\n * common table expressions or other places where the schema\n * doesn't belong to:\n *\n * ```\n * await db\n * .withSchema('mammals')\n * .selectFrom('pet as p')\n * .select('p.name')\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"p\".\"name\" from \"mammals\".\"pet\" as \"p\"\n * ```\n */\n withSchema(schema) {\n return new QueryCreator({\n ...this.#props,\n executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema)),\n });\n }\n}\n", "/// \nimport { JoinNode } from '../operation-node/join-node.js';\nimport { OverNode } from '../operation-node/over-node.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { JoinBuilder } from '../query-builder/join-builder.js';\nimport { OverBuilder } from '../query-builder/over-builder.js';\nimport { createSelectQueryBuilder as newSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { QueryCreator } from '../query-creator.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { parseTableExpression, parseTableExpressionOrList, } from './table-parser.js';\nexport function createSelectQueryBuilder() {\n return newSelectQueryBuilder({\n queryId: createQueryId(),\n executor: NOOP_QUERY_EXECUTOR,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList([])),\n });\n}\nexport function createQueryCreator() {\n return new QueryCreator({\n executor: NOOP_QUERY_EXECUTOR,\n });\n}\nexport function createJoinBuilder(joinType, table) {\n return new JoinBuilder({\n joinNode: JoinNode.create(joinType, parseTableExpression(table)),\n });\n}\nexport function createOverBuilder() {\n return new OverBuilder({\n overNode: OverNode.create(),\n });\n}\n", "/// \nimport { JoinNode } from '../operation-node/join-node.js';\nimport { parseReferentialBinaryOperation } from './binary-operation-parser.js';\nimport { createJoinBuilder } from './parse-utils.js';\nimport { parseTableExpression, } from './table-parser.js';\nexport function parseJoin(joinType, args) {\n if (args.length === 3) {\n return parseSingleOnJoin(joinType, args[0], args[1], args[2]);\n }\n else if (args.length === 2) {\n return parseCallbackJoin(joinType, args[0], args[1]);\n }\n else if (args.length === 1) {\n return parseOnlessJoin(joinType, args[0]);\n }\n else {\n throw new Error('not implemented');\n }\n}\nfunction parseCallbackJoin(joinType, from, callback) {\n return callback(createJoinBuilder(joinType, from)).toOperationNode();\n}\nfunction parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) {\n return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, '=', rhsColumn));\n}\nfunction parseOnlessJoin(joinType, from) {\n return JoinNode.create(joinType, parseTableExpression(from));\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OffsetNode = freeze({\n is(node) {\n return node.kind === 'OffsetNode';\n },\n create(offset) {\n return freeze({\n kind: 'OffsetNode',\n offset,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByItemNode = freeze({\n is(node) {\n return node.kind === 'GroupByItemNode';\n },\n create(groupBy) {\n return freeze({\n kind: 'GroupByItemNode',\n groupBy,\n });\n },\n});\n", "/// \nimport { GroupByItemNode } from '../operation-node/group-by-item-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parseGroupBy(groupBy) {\n groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy;\n return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SetOperationNode = freeze({\n is(node) {\n return node.kind === 'SetOperationNode';\n },\n create(operator, expression, all) {\n return freeze({\n kind: 'SetOperationNode',\n operator,\n expression,\n all,\n });\n },\n});\n", "/// \nimport { createExpressionBuilder, } from '../expression/expression-builder.js';\nimport { SetOperationNode, } from '../operation-node/set-operation-node.js';\nimport { isFunction, isReadonlyArray } from '../util/object-utils.js';\nimport { parseExpression } from './expression-parser.js';\nexport function parseSetOperations(operator, expression, all) {\n if (isFunction(expression)) {\n expression = expression(createExpressionBuilder());\n }\n if (!isReadonlyArray(expression)) {\n expression = [expression];\n }\n return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all));\n}\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { OrNode } from '../operation-node/or-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nexport class ExpressionWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `ExpressionWrapper` with a new output type.\n */\n $castTo() {\n return new ExpressionWrapper(this.#node);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new ExpressionWrapper(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedExpressionWrapper {\n #expr;\n #alias;\n constructor(expr, alias) {\n this.#expr = expr;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#expr;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\nexport class OrWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `OrWrapper` with a new output type.\n */\n $castTo() {\n return new OrWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\nexport class AndWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AndWrapper` with a new output type.\n */\n $castTo() {\n return new AndWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ValueNode } from './value-node.js';\n/**\n * @internal\n */\nexport const FetchNode = freeze({\n is(node) {\n return node.kind === 'FetchNode';\n },\n create(rowCount, modifier) {\n return {\n kind: 'FetchNode',\n rowCount: ValueNode.create(rowCount),\n modifier,\n };\n },\n});\n", "/// \nimport { FetchNode } from '../operation-node/fetch-node.js';\nimport { isBigInt, isNumber } from '../util/object-utils.js';\nexport function parseFetch(rowCount, modifier) {\n if (!isNumber(rowCount) && !isBigInt(rowCount)) {\n throw new Error(`Invalid fetch row count: ${rowCount}`);\n }\n if (!isFetchModifier(modifier)) {\n throw new Error(`Invalid fetch modifier: ${modifier}`);\n }\n return FetchNode.create(rowCount, modifier);\n}\nfunction isFetchModifier(value) {\n return value === 'only' || value === 'with ties';\n}\n", "/// \nvar _a;\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { SelectModifierNode } from '../operation-node/select-modifier-node.js';\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { OffsetNode } from '../operation-node/offset-node.js';\nimport { asArray, freeze } from '../util/object-utils.js';\nimport { parseGroupBy } from '../parser/group-by-parser.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { parseSetOperations, } from '../parser/set-operation-parser.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { parseFetch } from '../parser/fetch-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nclass SelectQueryBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isSelectQueryBuilder() {\n return true;\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n having(...args) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n havingRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n select(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n distinctOn(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection)),\n });\n }\n modifyFront(modifier) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n distinct() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create('Distinct')),\n });\n }\n forUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forKeyShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForKeyShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forNoKeyUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForNoKeyUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n skipLocked() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('SkipLocked')),\n });\n }\n noWait() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('NoWait')),\n });\n }\n selectAll(table) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n crossJoin(...args) {\n return this.#join('CrossJoin', args);\n }\n innerJoinLateral(...args) {\n return this.#join('LateralInnerJoin', args);\n }\n leftJoinLateral(...args) {\n return this.#join('LateralLeftJoin', args);\n }\n crossJoinLateral(...args) {\n return this.#join('LateralCrossJoin', args);\n }\n crossApply(...args) {\n return this.#join('CrossApply', args);\n }\n outerApply(...args) {\n return this.#join('OuterApply', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n groupBy(groupBy) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy)),\n });\n }\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n offset(offset) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset))),\n });\n }\n fetch(rowCount, modifier = 'only') {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier)),\n });\n }\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n union(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, false)),\n });\n }\n unionAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, true)),\n });\n }\n intersect(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, false)),\n });\n }\n intersectAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, true)),\n });\n }\n except(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, false)),\n });\n }\n exceptAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, true)),\n });\n }\n as(alias) {\n return new AliasedSelectQueryBuilderImpl(this, alias);\n }\n clearSelect() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n clearLimit() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode),\n });\n }\n clearOffset() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n clearGroupBy() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode),\n });\n }\n $call(func) {\n return func(this);\n }\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n $castTo() {\n return new _a(this.#props);\n }\n $narrowType() {\n return new _a(this.#props);\n }\n $assertType() {\n return new _a(this.#props);\n }\n $asTuple() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n $asScalar() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n return result.rows;\n }\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = SelectQueryBuilderImpl;\nexport function createSelectQueryBuilder(props) {\n return new SelectQueryBuilderImpl(props);\n}\n/**\n * {@link SelectQueryBuilder} with an alias. The result of calling {@link SelectQueryBuilder.as}.\n */\nclass AliasedSelectQueryBuilderImpl {\n #queryBuilder;\n #alias;\n constructor(queryBuilder, alias) {\n this.#queryBuilder = queryBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#queryBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get isAliasedSelectQueryBuilder() {\n return true;\n }\n toOperationNode() {\n return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { WhereNode } from './where-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const AggregateFunctionNode = freeze({\n is(node) {\n return node.kind === 'AggregateFunctionNode';\n },\n create(aggregateFunction, aggregated = []) {\n return freeze({\n kind: 'AggregateFunctionNode',\n func: aggregateFunction,\n aggregated,\n });\n },\n cloneWithDistinct(aggregateFunctionNode) {\n return freeze({\n ...aggregateFunctionNode,\n distinct: true,\n });\n },\n cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) {\n const prop = withinGroup ? 'withinGroup' : 'orderBy';\n return freeze({\n ...aggregateFunctionNode,\n [prop]: aggregateFunctionNode[prop]\n ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems)\n : OrderByNode.create(orderItems),\n });\n },\n cloneWithFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'And', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOrFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'Or', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOver(aggregateFunctionNode, over) {\n return freeze({\n ...aggregateFunctionNode,\n over,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FunctionNode = freeze({\n is(node) {\n return node.kind === 'FunctionNode';\n },\n create(func, args) {\n return freeze({\n kind: 'FunctionNode',\n func,\n arguments: args,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { createOverBuilder } from '../parser/parse-utils.js';\nimport { parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nexport class AggregateFunctionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n /**\n * Returns an aliased version of the function.\n *\n * In addition to slapping `as \"the_alias\"` to the end of the SQL,\n * this method also provides strict typing:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.count('id').as('person_count')\n * )\n * .executeTakeFirstOrThrow()\n *\n * // `person_count: number` field exists in the result type.\n * console.log(result.person_count)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(\"id\") as \"person_count\"\n * from \"person\"\n * ```\n */\n as(alias) {\n return new AliasedAggregateFunctionBuilder(this, alias);\n }\n /**\n * Adds a `distinct` clause inside the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) =>\n * eb.fn.count('first_name').distinct().as('first_name_count')\n * )\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(distinct \"first_name\") as \"first_name_count\"\n * from \"person\"\n * ```\n */\n distinct() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode),\n });\n }\n orderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode),\n });\n }\n withinGroupOrderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true),\n });\n }\n filterWhere(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Adds a `filter` clause with a nested `where` clause after the function, where\n * both sides of the operator are references to columns.\n *\n * Similar to {@link WhereInterface}'s `whereRef` method.\n *\n * ### Examples\n *\n * Count people with same first and last names versus general public:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) => [\n * eb.fn\n * .count('id')\n * .filterWhereRef('first_name', '=', 'last_name')\n * .as('repeat_name_count'),\n * eb.fn.count('id').as('total_count'),\n * ])\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select\n * count(\"id\") filter(where \"first_name\" = \"last_name\") as \"repeat_name_count\",\n * count(\"id\") as \"total_count\"\n * from \"person\"\n * ```\n */\n filterWhereRef(lhs, op, rhs) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds an `over` clause (window functions) after the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg('age').over().as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over() as \"average_age\"\n * from \"person\"\n * ```\n *\n * Also supports passing a callback that returns an over builder,\n * allowing to add partition by and sort by clauses inside over.\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg('age').over(\n * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc')\n * ).as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over(partition by \"last_name\" order by \"first_name\" asc) as \"average_age\"\n * from \"person\"\n * ```\n */\n over(over) {\n const builder = createOverBuilder();\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n /**\n * Casts the expression to the given type.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AggregateFunctionBuilder` with a new output type.\n */\n $castTo() {\n return new AggregateFunctionBuilder(this.#props);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new AggregateFunctionBuilder(this.#props);\n }\n toOperationNode() {\n return this.#props.aggregateFunctionNode;\n }\n}\n/**\n * {@link AggregateFunctionBuilder} with an alias. The result of calling {@link AggregateFunctionBuilder.as}.\n */\nexport class AliasedAggregateFunctionBuilder {\n #aggregateFunctionBuilder;\n #alias;\n constructor(aggregateFunctionBuilder, alias) {\n this.#aggregateFunctionBuilder = aggregateFunctionBuilder;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#aggregateFunctionBuilder;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n", "/// \nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { FunctionNode } from '../operation-node/function-node.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { parseSelectAll } from '../parser/select-parser.js';\nimport { AggregateFunctionBuilder } from './aggregate-function-builder.js';\nimport { isString } from '../util/object-utils.js';\nimport { parseTable } from '../parser/table-parser.js';\nexport function createFunctionModule() {\n const fn = (name, args) => {\n return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? [])));\n };\n const agg = (name, args) => {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : undefined),\n });\n };\n return Object.assign(fn, {\n agg,\n avg(column) {\n return agg('avg', [column]);\n },\n coalesce(...values) {\n return fn('coalesce', values);\n },\n count(column) {\n return agg('count', [column]);\n },\n countAll(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('count', parseSelectAll(table)),\n });\n },\n max(column) {\n return agg('max', [column]);\n },\n min(column) {\n return agg('min', [column]);\n },\n sum(column) {\n return agg('sum', [column]);\n },\n any(column) {\n return fn('any', [column]);\n },\n jsonAgg(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('json_agg', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]),\n });\n },\n toJson(table) {\n return new ExpressionWrapper(FunctionNode.create('to_json', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]));\n },\n });\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UnaryOperationNode = freeze({\n is(node) {\n return node.kind === 'UnaryOperationNode';\n },\n create(operator, operand) {\n return freeze({\n kind: 'UnaryOperationNode',\n operator,\n operand,\n });\n },\n});\n", "/// \nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { UnaryOperationNode } from '../operation-node/unary-operation-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nexport function parseExists(operand) {\n return parseUnaryOperation('exists', operand);\n}\nexport function parseNotExists(operand) {\n return parseUnaryOperation('not exists', operand);\n}\nexport function parseUnaryOperation(operator, operand) {\n return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand));\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const CaseNode = freeze({\n is(node) {\n return node.kind === 'CaseNode';\n },\n create(value) {\n return freeze({\n kind: 'CaseNode',\n value,\n });\n },\n cloneWithWhen(caseNode, when) {\n return freeze({\n ...caseNode,\n when: freeze(caseNode.when ? [...caseNode.when, when] : [when]),\n });\n },\n cloneWithThen(caseNode, then) {\n return freeze({\n ...caseNode,\n when: caseNode.when\n ? freeze([\n ...caseNode.when.slice(0, -1),\n WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then),\n ])\n : undefined,\n });\n },\n cloneWith(caseNode, props) {\n return freeze({\n ...caseNode,\n ...props,\n });\n },\n});\n", "/// \nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { freeze } from '../util/object-utils.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { isSafeImmediateValue, parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nexport class CaseBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n}\nexport class CaseThenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n then(valueExpression) {\n return new CaseWhenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression)),\n });\n }\n}\nexport class CaseWhenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n else(valueExpression) {\n return new CaseEndBuilder({\n ...this.#props,\n node: CaseNode.cloneWith(this.#props.node, {\n else: isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression),\n }),\n });\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\nexport class CaseEndBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathLegNode = freeze({\n is(node) {\n return node.kind === 'JSONPathLegNode';\n },\n create(type, value) {\n return freeze({\n kind: 'JSONPathLegNode',\n type,\n value,\n });\n },\n});\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathLegNode, } from '../operation-node/json-path-leg-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nexport class JSONPathBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Access an element of a JSON array in a specific location.\n *\n * Since there's no guarantee an element exists in the given array location, the\n * resulting type is always nullable. If you're sure the element exists, you\n * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely.\n *\n * See also {@link key} to access properties of JSON objects.\n *\n * ### Examples\n *\n * ```ts\n * await db.selectFrom('person')\n * .select(eb =>\n * eb.ref('nicknames', '->').at(0).as('primary_nickname')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"nicknames\"->0 as \"primary_nickname\" from \"person\"\n *```\n *\n * Combined with {@link key}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('experience', '->').at(0).key('role').as('first_role')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"experience\"->0->'role' as \"first_role\" from \"person\"\n * ```\n *\n * You can use `'last'` to access the last element of the array in MySQL:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->$').at('last').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `nicknames`->'$[last]' as `last_nickname` from `person`\n * ```\n *\n * Or `'#-1'` in SQLite:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select \"nicknames\"->>'$[#-1]' as `last_nickname` from `person`\n * ```\n */\n at(index) {\n return this.#createBuilderWithPathLeg('ArrayLocation', index);\n }\n /**\n * Access a property of a JSON object.\n *\n * If a field is optional, the resulting type will be nullable.\n *\n * See also {@link at} to access elements of JSON arrays.\n *\n * ### Examples\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('address', '->').key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"address\"->'city' as \"city\" from \"person\"\n * ```\n *\n * Going deeper:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->$').key('website').key('url').as('website_url')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `profile`->'$.website.url' as `website_url` from `person`\n * ```\n *\n * Combined with {@link at}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"profile\"->'addresses'->0->'city' as \"city\" from \"person\"\n * ```\n */\n key(key) {\n return this.#createBuilderWithPathLeg('Member', key);\n }\n #createBuilderWithPathLeg(legType, value) {\n if (JSONReferenceNode.is(this.#node)) {\n return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal)\n ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value))\n : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value))));\n }\n return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value)));\n }\n}\nexport class TraversedJSONPathBuilder extends JSONPathBuilder {\n #node;\n constructor(node) {\n super(node);\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedJSONPathBuilder(this, alias);\n }\n /**\n * Change the output type of the json path.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `JSONPathBuilder` with a new output type.\n */\n $castTo() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n $notNull() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedJSONPathBuilder {\n #jsonPath;\n #alias;\n constructor(jsonPath, alias) {\n this.#jsonPath = jsonPath;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#jsonPath;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TupleNode = freeze({\n is(node) {\n return node.kind === 'TupleNode';\n },\n create(values) {\n return freeze({\n kind: 'TupleNode',\n values: freeze(values),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nconst SIMPLE_COLUMN_DATA_TYPES = [\n 'varchar',\n 'char',\n 'text',\n 'integer',\n 'int2',\n 'int4',\n 'int8',\n 'smallint',\n 'bigint',\n 'boolean',\n 'real',\n 'double precision',\n 'float4',\n 'float8',\n 'decimal',\n 'numeric',\n 'binary',\n 'bytea',\n 'date',\n 'datetime',\n 'time',\n 'timetz',\n 'timestamp',\n 'timestamptz',\n 'serial',\n 'bigserial',\n 'uuid',\n 'json',\n 'jsonb',\n 'blob',\n 'varbinary',\n 'int4range',\n 'int4multirange',\n 'int8range',\n 'int8multirange',\n 'numrange',\n 'nummultirange',\n 'tsrange',\n 'tsmultirange',\n 'tstzrange',\n 'tstzmultirange',\n 'daterange',\n 'datemultirange',\n];\nconst COLUMN_DATA_TYPE_REGEX = [\n /^varchar\\(\\d+\\)$/,\n /^char\\(\\d+\\)$/,\n /^decimal\\(\\d+, \\d+\\)$/,\n /^numeric\\(\\d+, \\d+\\)$/,\n /^binary\\(\\d+\\)$/,\n /^datetime\\(\\d+\\)$/,\n /^time\\(\\d+\\)$/,\n /^timetz\\(\\d+\\)$/,\n /^timestamp\\(\\d+\\)$/,\n /^timestamptz\\(\\d+\\)$/,\n /^varbinary\\(\\d+\\)$/,\n];\n/**\n * @internal\n */\nexport const DataTypeNode = freeze({\n is(node) {\n return node.kind === 'DataTypeNode';\n },\n create(dataType) {\n return freeze({\n kind: 'DataTypeNode',\n dataType,\n });\n },\n});\nexport function isColumnDataType(dataType) {\n if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) {\n return true;\n }\n if (COLUMN_DATA_TYPE_REGEX.some((r) => r.test(dataType))) {\n return true;\n }\n return false;\n}\n", "/// \nimport { DataTypeNode, isColumnDataType, } from '../operation-node/data-type-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nexport function parseDataTypeExpression(dataType) {\n if (isOperationNodeSource(dataType)) {\n return dataType.toOperationNode();\n }\n if (isColumnDataType(dataType)) {\n return DataTypeNode.create(dataType);\n }\n throw new Error(`invalid column data type ${JSON.stringify(dataType)}`);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const CastNode = freeze({\n is(node) {\n return node.kind === 'CastNode';\n },\n create(expression, dataType) {\n return freeze({\n kind: 'CastNode',\n expression,\n dataType,\n });\n },\n});\n", "/// \nimport { createSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { parseTableExpressionOrList, parseTable, } from '../parser/table-parser.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createFunctionModule, } from '../query-builder/function-module.js';\nimport { parseJSONReference, parseReferenceExpression, parseStringReference, } from '../parser/reference-parser.js';\nimport { parseFilterList, parseFilterObject, parseValueBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { ExpressionWrapper } from './expression-wrapper.js';\nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { parseUnaryOperation } from '../parser/unary-operation-parser.js';\nimport { parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { CaseBuilder } from '../query-builder/case-builder.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { isReadonlyArray, isUndefined } from '../util/object-utils.js';\nimport { JSONPathBuilder } from '../query-builder/json-path-builder.js';\nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { TupleNode } from '../operation-node/tuple-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { CastNode } from '../operation-node/cast-node.js';\nexport function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) {\n function binary(lhs, op, rhs) {\n return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs));\n }\n function unary(op, expr) {\n return new ExpressionWrapper(parseUnaryOperation(op, expr));\n }\n const eb = Object.assign(binary, {\n fn: undefined,\n eb: undefined,\n selectFrom(table) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)),\n });\n },\n case(reference) {\n return new CaseBuilder({\n node: CaseNode.create(isUndefined(reference)\n ? undefined\n : parseReferenceExpression(reference)),\n });\n },\n ref(reference, op) {\n if (isUndefined(op)) {\n return new ExpressionWrapper(parseStringReference(reference));\n }\n return new JSONPathBuilder(parseJSONReference(reference, op));\n },\n jsonPath() {\n return new JSONPathBuilder(JSONPathNode.create());\n },\n table(table) {\n return new ExpressionWrapper(parseTable(table));\n },\n val(value) {\n return new ExpressionWrapper(parseValueExpression(value));\n },\n refTuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression)));\n },\n tuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression)));\n },\n lit(value) {\n return new ExpressionWrapper(parseSafeImmediateValue(value));\n },\n unary,\n not(expr) {\n return unary('not', expr);\n },\n exists(expr) {\n return unary('exists', expr);\n },\n neg(expr) {\n return unary('-', expr);\n },\n between(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n betweenSymmetric(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between symmetric'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n and(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'and'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'and'));\n },\n or(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'or'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'or'));\n },\n parens(...args) {\n const node = parseValueBinaryOperationOrExpression(args);\n if (ParensNode.is(node)) {\n // No double wrapping.\n return new ExpressionWrapper(node);\n }\n else {\n return new ExpressionWrapper(ParensNode.create(node));\n }\n },\n cast(expr, dataType) {\n return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType)));\n },\n withSchema(schema) {\n return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema)));\n },\n });\n eb.fn = createFunctionModule();\n eb.eb = eb;\n return eb;\n}\nexport function expressionBuilder(_) {\n return createExpressionBuilder();\n}\n", "/// \nimport { isAliasedExpression, isExpression, } from '../expression/expression.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nexport function parseExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid expression: ${JSON.stringify(exp)}`);\n}\nexport function parseAliasedExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`);\n}\nexport function isExpressionOrFactory(obj) {\n return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj);\n}\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicTableBuilder {\n #table;\n get table() {\n return this.#table;\n }\n constructor(table) {\n this.#table = table;\n }\n as(alias) {\n return new AliasedDynamicTableBuilder(this.#table, alias);\n }\n}\nexport class AliasedDynamicTableBuilder {\n #table;\n #alias;\n get table() {\n return this.#table;\n }\n get alias() {\n return this.#alias;\n }\n constructor(table, alias) {\n this.#table = table;\n this.#alias = alias;\n }\n toOperationNode() {\n return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias));\n }\n}\nexport function isAliasedDynamicTableBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.table) &&\n isString(obj.alias));\n}\n", "/// \nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isAliasedDynamicTableBuilder, } from '../dynamic/dynamic-table-builder.js';\nexport function parseTableExpressionOrList(table) {\n if (isReadonlyArray(table)) {\n return table.map((it) => parseTableExpression(it));\n }\n else {\n return [parseTableExpression(table)];\n }\n}\nexport function parseTableExpression(table) {\n if (isString(table)) {\n return parseAliasedTable(table);\n }\n else if (isAliasedDynamicTableBuilder(table)) {\n return table.toOperationNode();\n }\n else {\n return parseAliasedExpression(table);\n }\n}\nexport function parseAliasedTable(from) {\n const ALIAS_SEPARATOR = ' as ';\n if (from.includes(ALIAS_SEPARATOR)) {\n const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseTable(table), IdentifierNode.create(alias));\n }\n else {\n return parseTable(from);\n }\n}\nexport function parseTable(from) {\n const SCHEMA_SEPARATOR = '.';\n if (from.includes(SCHEMA_SEPARATOR)) {\n const [schema, table] = from.split(SCHEMA_SEPARATOR).map(trim);\n return TableNode.createWithSchema(schema, table);\n }\n else {\n return TableNode.create(from);\n }\n}\nfunction trim(str) {\n return str.trim();\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AddColumnNode = freeze({\n is(node) {\n return node.kind === 'AddColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'AddColumnNode',\n column,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\n/**\n * @internal\n */\nexport const ColumnDefinitionNode = freeze({\n is(node) {\n return node.kind === 'ColumnDefinitionNode';\n },\n create(column, dataType) {\n return freeze({\n kind: 'ColumnDefinitionNode',\n column: ColumnNode.create(column),\n dataType,\n });\n },\n cloneWithFrontModifier(node, modifier) {\n return freeze({\n ...node,\n frontModifiers: node.frontModifiers\n ? freeze([...node.frontModifiers, modifier])\n : [modifier],\n });\n },\n cloneWithEndModifier(node, modifier) {\n return freeze({\n ...node,\n endModifiers: node.endModifiers\n ? freeze([...node.endModifiers, modifier])\n : [modifier],\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\n/**\n * @internal\n */\nexport const DropColumnNode = freeze({\n is(node) {\n return node.kind === 'DropColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'DropColumnNode',\n column: ColumnNode.create(column),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\n/**\n * @internal\n */\nexport const RenameColumnNode = freeze({\n is(node) {\n return node.kind === 'RenameColumnNode';\n },\n create(column, newColumn) {\n return freeze({\n kind: 'RenameColumnNode',\n column: ColumnNode.create(column),\n renameTo: ColumnNode.create(newColumn),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CheckConstraintNode = freeze({\n is(node) {\n return node.kind === 'CheckConstraintNode';\n },\n create(expression, constraintName) {\n return freeze({\n kind: 'CheckConstraintNode',\n expression,\n name: constraintName\n ? IdentifierNode.create(constraintName)\n : undefined,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nexport const ON_MODIFY_FOREIGN_ACTIONS = [\n 'no action',\n 'restrict',\n 'cascade',\n 'set null',\n 'set default',\n];\n/**\n * @internal\n */\nexport const ReferencesNode = freeze({\n is(node) {\n return node.kind === 'ReferencesNode';\n },\n create(table, columns) {\n return freeze({\n kind: 'ReferencesNode',\n table,\n columns: freeze([...columns]),\n });\n },\n cloneWithOnDelete(references, onDelete) {\n return freeze({\n ...references,\n onDelete,\n });\n },\n cloneWithOnUpdate(references, onUpdate) {\n return freeze({\n ...references,\n onUpdate,\n });\n },\n});\n", "/// \nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nexport function parseDefaultValueExpression(value) {\n return isOperationNodeSource(value)\n ? value.toOperationNode()\n : ValueNode.createImmediate(value);\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GeneratedNode = freeze({\n is(node) {\n return node.kind === 'GeneratedNode';\n },\n create(params) {\n return freeze({\n kind: 'GeneratedNode',\n ...params,\n });\n },\n createWithExpression(expression) {\n return freeze({\n kind: 'GeneratedNode',\n always: true,\n expression,\n });\n },\n cloneWith(node, params) {\n return freeze({\n ...node,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const DefaultValueNode = freeze({\n is(node) {\n return node.kind === 'DefaultValueNode';\n },\n create(defaultValue) {\n return freeze({\n kind: 'DefaultValueNode',\n defaultValue,\n });\n },\n});\n", "/// \nimport { ON_MODIFY_FOREIGN_ACTIONS, } from '../operation-node/references-node.js';\nexport function parseOnModifyForeignAction(action) {\n if (ON_MODIFY_FOREIGN_ACTIONS.includes(action)) {\n return action;\n }\n throw new Error(`invalid OnModifyForeignAction ${action}`);\n}\n", "/// \nimport { CheckConstraintNode } from '../operation-node/check-constraint-node.js';\nimport { ReferencesNode, } from '../operation-node/references-node.js';\nimport { SelectAllNode } from '../operation-node/select-all-node.js';\nimport { parseStringReference } from '../parser/reference-parser.js';\nimport { ColumnDefinitionNode } from '../operation-node/column-definition-node.js';\nimport { parseDefaultValueExpression, } from '../parser/default-value-parser.js';\nimport { GeneratedNode } from '../operation-node/generated-node.js';\nimport { DefaultValueNode } from '../operation-node/default-value-node.js';\nimport { parseOnModifyForeignAction } from '../parser/on-modify-action-parser.js';\nexport class ColumnDefinitionBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Adds `auto_increment` or `autoincrement` to the column definition\n * depending on the dialect.\n *\n * Some dialects like PostgreSQL don't support this. On PostgreSQL\n * you can use the `serial` or `bigserial` data type instead.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.autoIncrement().primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key auto_increment\n * )\n * ```\n */\n autoIncrement() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { autoIncrement: true }));\n }\n /**\n * Makes the column an identity column.\n *\n * This only works on some dialects like MS SQL Server (MSSQL).\n *\n * For PostgreSQL's `generated always as identity` use {@link generatedAlwaysAsIdentity}.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.identity().primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (MSSQL):\n *\n * ```sql\n * create table \"person\" (\n * \"id\" integer identity primary key\n * )\n * ```\n */\n identity() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { identity: true }));\n }\n /**\n * Makes the column the primary key.\n *\n * If you want to specify a composite primary key use the\n * {@link CreateTableBuilder.addPrimaryKeyConstraint} method.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key\n * )\n */\n primaryKey() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { primaryKey: true }));\n }\n /**\n * Adds a foreign key constraint for the column.\n *\n * If your database engine doesn't support foreign key constraints in the\n * column definition (like MySQL 5) you need to call the table level\n * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('owner_id', 'integer', (col) => col.references('person.id'))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"pet\" (\n * \"owner_id\" integer references \"person\" (\"id\")\n * )\n * ```\n */\n references(ref) {\n const references = parseStringReference(ref);\n if (!references.table || SelectAllNode.is(references.column)) {\n throw new Error(`invalid call references('${ref}'). The reference must have format table.column or schema.table.column`);\n }\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n references: ReferencesNode.create(references.table, [\n references.column,\n ]),\n }));\n }\n /**\n * Adds an `on delete` constraint for the foreign key column.\n *\n * If your database engine doesn't support foreign key constraints in the\n * column definition (like MySQL 5) you need to call the table level\n * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn(\n * 'owner_id',\n * 'integer',\n * (col) => col.references('person.id').onDelete('cascade')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"pet\" (\n * \"owner_id\" integer references \"person\" (\"id\") on delete cascade\n * )\n * ```\n */\n onDelete(onDelete) {\n if (!this.#node.references) {\n throw new Error('on delete constraint can only be added for foreign keys');\n }\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n references: ReferencesNode.cloneWithOnDelete(this.#node.references, parseOnModifyForeignAction(onDelete)),\n }));\n }\n /**\n * Adds an `on update` constraint for the foreign key column.\n *\n * If your database engine doesn't support foreign key constraints in the\n * column definition (like MySQL 5) you need to call the table level\n * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn(\n * 'owner_id',\n * 'integer',\n * (col) => col.references('person.id').onUpdate('cascade')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"pet\" (\n * \"owner_id\" integer references \"person\" (\"id\") on update cascade\n * )\n * ```\n */\n onUpdate(onUpdate) {\n if (!this.#node.references) {\n throw new Error('on update constraint can only be added for foreign keys');\n }\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n references: ReferencesNode.cloneWithOnUpdate(this.#node.references, parseOnModifyForeignAction(onUpdate)),\n }));\n }\n /**\n * Adds a unique constraint for the column.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('email', 'varchar(255)', col => col.unique())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `email` varchar(255) unique\n * )\n * ```\n */\n unique() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unique: true }));\n }\n /**\n * Adds a `not null` constraint for the column.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('first_name', 'varchar(255)', col => col.notNull())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `first_name` varchar(255) not null\n * )\n * ```\n */\n notNull() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { notNull: true }));\n }\n /**\n * Adds a `unsigned` modifier for the column.\n *\n * This only works on some dialects like MySQL.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('age', 'integer', col => col.unsigned())\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `age` integer unsigned\n * )\n * ```\n */\n unsigned() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unsigned: true }));\n }\n /**\n * Adds a default value constraint for the column.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('number_of_legs', 'integer', (col) => col.defaultTo(4))\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `pet` (\n * `number_of_legs` integer default 4\n * )\n * ```\n *\n * Values passed to `defaultTo` are interpreted as value literals by default. You can define\n * an arbitrary SQL expression using the {@link sql} template tag:\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('pet')\n * .addColumn(\n * 'created_at',\n * 'timestamp',\n * (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`)\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `pet` (\n * `created_at` timestamp default CURRENT_TIMESTAMP\n * )\n * ```\n */\n defaultTo(value) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n defaultTo: DefaultValueNode.create(parseDefaultValueExpression(value)),\n }));\n }\n /**\n * Adds a check constraint for the column.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('pet')\n * .addColumn('number_of_legs', 'integer', (col) =>\n * col.check(sql`number_of_legs < 5`)\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `pet` (\n * `number_of_legs` integer check (number_of_legs < 5)\n * )\n * ```\n */\n check(expression) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n check: CheckConstraintNode.create(expression.toOperationNode()),\n }));\n }\n /**\n * Makes the column a generated column using a `generated always as` statement.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('full_name', 'varchar(255)',\n * (col) => col.generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`)\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name))\n * )\n * ```\n */\n generatedAlwaysAs(expression) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n generated: GeneratedNode.createWithExpression(expression.toOperationNode()),\n }));\n }\n /**\n * Adds the `generated always as identity` specifier.\n *\n * This only works on some dialects like PostgreSQL.\n *\n * For MS SQL Server (MSSQL)'s identity column use {@link identity}.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.generatedAlwaysAsIdentity().primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"person\" (\n * \"id\" integer generated always as identity primary key\n * )\n * ```\n */\n generatedAlwaysAsIdentity() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n generated: GeneratedNode.create({ identity: true, always: true }),\n }));\n }\n /**\n * Adds the `generated by default as identity` specifier on supported dialects.\n *\n * This only works on some dialects like PostgreSQL.\n *\n * For MS SQL Server (MSSQL)'s identity column use {@link identity}.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.generatedByDefaultAsIdentity().primaryKey())\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"person\" (\n * \"id\" integer generated by default as identity primary key\n * )\n * ```\n */\n generatedByDefaultAsIdentity() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n generated: GeneratedNode.create({ identity: true, byDefault: true }),\n }));\n }\n /**\n * Makes a generated column stored instead of virtual. This method can only\n * be used with {@link generatedAlwaysAs}\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('full_name', 'varchar(255)', (col) => col\n * .generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`)\n * .stored()\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) stored\n * )\n * ```\n */\n stored() {\n if (!this.#node.generated) {\n throw new Error('stored() can only be called after generatedAlwaysAs');\n }\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {\n generated: GeneratedNode.cloneWith(this.#node.generated, {\n stored: true,\n }),\n }));\n }\n /**\n * This can be used to add any additional SQL right after the column's data type.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn(\n * 'first_name',\n * 'varchar(36)',\n * (col) => col.modifyFront(sql`collate utf8mb4_general_ci`).notNull()\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key,\n * `first_name` varchar(36) collate utf8mb4_general_ci not null\n * )\n * ```\n */\n modifyFront(modifier) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(this.#node, modifier.toOperationNode()));\n }\n /**\n * Adds `nulls not distinct` specifier.\n * Should be used with `unique` constraint.\n *\n * This only works on some dialects like PostgreSQL.\n *\n * ### Examples\n *\n * ```ts\n * db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn('first_name', 'varchar(30)', col => col.unique().nullsNotDistinct())\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create table \"person\" (\n * \"id\" integer primary key,\n * \"first_name\" varchar(30) unique nulls not distinct\n * )\n * ```\n */\n nullsNotDistinct() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { nullsNotDistinct: true }));\n }\n /**\n * Adds `if not exists` specifier. This only works for PostgreSQL.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .addColumn('email', 'varchar(255)', col => col.unique().ifNotExists())\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * alter table \"person\" add column if not exists \"email\" varchar(255) unique\n * ```\n */\n ifNotExists() {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { ifNotExists: true }));\n }\n /**\n * This can be used to add any additional SQL to the end of the column definition.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn(\n * 'age',\n * 'integer',\n * col => col.unsigned()\n * .notNull()\n * .modifyEnd(sql`comment ${sql.lit('it is not polite to ask a woman her age')}`)\n * )\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key,\n * `age` integer unsigned not null comment 'it is not polite to ask a woman her age'\n * )\n * ```\n */\n modifyEnd(modifier) {\n return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(this.#node, modifier.toOperationNode()));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ModifyColumnNode = freeze({\n is(node) {\n return node.kind === 'ModifyColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'ModifyColumnNode',\n column,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\nimport { ReferencesNode, } from './references-node.js';\n/**\n * @internal\n */\nexport const ForeignKeyConstraintNode = freeze({\n is(node) {\n return node.kind === 'ForeignKeyConstraintNode';\n },\n create(sourceColumns, targetTable, targetColumns, constraintName) {\n return freeze({\n kind: 'ForeignKeyConstraintNode',\n columns: sourceColumns,\n references: ReferencesNode.create(targetTable, targetColumns),\n name: constraintName\n ? IdentifierNode.create(constraintName)\n : undefined,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js';\nimport { parseOnModifyForeignAction } from '../parser/on-modify-action-parser.js';\nexport class ForeignKeyConstraintBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n onDelete(onDelete) {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {\n onDelete: parseOnModifyForeignAction(onDelete),\n }));\n }\n onUpdate(onUpdate) {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {\n onUpdate: parseOnModifyForeignAction(onUpdate),\n }));\n }\n deferrable() {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: true }));\n }\n notDeferrable() {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: false }));\n }\n initiallyDeferred() {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: true,\n }));\n }\n initiallyImmediate() {\n return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: false,\n }));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AddConstraintNode = freeze({\n is(node) {\n return node.kind === 'AddConstraintNode';\n },\n create(constraint) {\n return freeze({\n kind: 'AddConstraintNode',\n constraint,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const UniqueConstraintNode = freeze({\n is(node) {\n return node.kind === 'UniqueConstraintNode';\n },\n create(columns, constraintName, nullsNotDistinct) {\n return freeze({\n kind: 'UniqueConstraintNode',\n columns: freeze(columns.map(ColumnNode.create)),\n name: constraintName\n ? IdentifierNode.create(constraintName)\n : undefined,\n nullsNotDistinct,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const DropConstraintNode = freeze({\n is(node) {\n return node.kind === 'DropConstraintNode';\n },\n create(constraintName) {\n return freeze({\n kind: 'DropConstraintNode',\n constraintName: IdentifierNode.create(constraintName),\n });\n },\n cloneWith(dropConstraint, props) {\n return freeze({\n ...dropConstraint,\n ...props,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\n/**\n * @internal\n */\nexport const AlterColumnNode = freeze({\n is(node) {\n return node.kind === 'AlterColumnNode';\n },\n create(column, prop, value) {\n return freeze({\n kind: 'AlterColumnNode',\n column: ColumnNode.create(column),\n [prop]: value,\n });\n },\n});\n", "/// \nimport { AlterColumnNode } from '../operation-node/alter-column-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { parseDefaultValueExpression, } from '../parser/default-value-parser.js';\nexport class AlterColumnBuilder {\n #column;\n constructor(column) {\n this.#column = column;\n }\n setDataType(dataType) {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'dataType', parseDataTypeExpression(dataType)));\n }\n setDefault(value) {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'setDefault', parseDefaultValueExpression(value)));\n }\n dropDefault() {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'dropDefault', true));\n }\n setNotNull() {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'setNotNull', true));\n }\n dropNotNull() {\n return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, 'dropNotNull', true));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n}\n/**\n * Allows us to force consumers to do exactly one alteration to a column.\n *\n * One cannot do no alterations:\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * // .execute() // Property 'execute' does not exist on type 'AlteredColumnBuilder'.\n * ```\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * // .alterColumn('age', (ac) => ac) // Type 'AlterColumnBuilder' is not assignable to type 'AlteredColumnBuilder'.\n * // .execute()\n * ```\n *\n * One cannot do multiple alterations:\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * // .alterColumn('age', (ac) => ac.dropNotNull().setNotNull()) // Property 'setNotNull' does not exist on type 'AlteredColumnBuilder'.\n * // .execute()\n * ```\n *\n * Which would now throw a compilation error, instead of a runtime error.\n */\nexport class AlteredColumnBuilder {\n #alterColumnNode;\n constructor(alterColumnNode) {\n this.#alterColumnNode = alterColumnNode;\n }\n toOperationNode() {\n return this.#alterColumnNode;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nexport class AlterTableExecutor {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { AddConstraintNode } from '../operation-node/add-constraint-node.js';\nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class AlterTableAddForeignKeyConstraintBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n onDelete(onDelete) {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.onDelete(onDelete),\n });\n }\n onUpdate(onUpdate) {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.onUpdate(onUpdate),\n });\n }\n deferrable() {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.deferrable(),\n });\n }\n notDeferrable() {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.notDeferrable(),\n });\n }\n initiallyDeferred() {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.initiallyDeferred(),\n });\n }\n initiallyImmediate() {\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder: this.#props.constraintBuilder.initiallyImmediate(),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(AlterTableNode.cloneWithTableProps(this.#props.node, {\n addConstraint: AddConstraintNode.create(this.#props.constraintBuilder.toOperationNode()),\n }), this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { DropConstraintNode } from '../operation-node/drop-constraint-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class AlterTableDropConstraintBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifExists() {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {\n ifExists: true,\n }),\n }),\n });\n }\n cascade() {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {\n modifier: 'cascade',\n }),\n }),\n });\n }\n restrict() {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {\n modifier: 'restrict',\n }),\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ColumnNode } from './column-node.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const PrimaryKeyConstraintNode = freeze({\n is(node) {\n return node.kind === 'PrimaryKeyConstraintNode';\n },\n create(columns, constraintName) {\n return freeze({\n kind: 'PrimaryKeyConstraintNode',\n columns: freeze(columns.map(ColumnNode.create)),\n name: constraintName\n ? IdentifierNode.create(constraintName)\n : undefined,\n });\n },\n cloneWith(node, props) {\n return freeze({ ...node, ...props });\n },\n});\n/**\n * Backwards compatibility for a typo in the codebase.\n *\n * @deprecated Use {@link PrimaryKeyConstraintNode} instead.\n */\nexport const PrimaryConstraintNode = PrimaryKeyConstraintNode;\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const AddIndexNode = freeze({\n is(node) {\n return node.kind === 'AddIndexNode';\n },\n create(name) {\n return freeze({\n kind: 'AddIndexNode',\n name: IdentifierNode.create(name),\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n cloneWithColumns(node, columns) {\n return freeze({\n ...node,\n columns: [...(node.columns || []), ...columns],\n });\n },\n});\n", "/// \nimport { AddIndexNode } from '../operation-node/add-index-node.js';\nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseOrderedColumnName, } from '../parser/reference-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class AlterTableAddIndexBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Makes the index unique.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .addIndex('person_first_name_index')\n * .unique()\n * .column('email')\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add unique index `person_first_name_index` (`email`)\n * ```\n */\n unique() {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, {\n unique: true,\n }),\n }),\n });\n }\n /**\n * Adds a column to the index.\n *\n * Also see {@link columns} for adding multiple columns at once or {@link expression}\n * for specifying an arbitrary expression.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .addIndex('person_first_name_and_age_index')\n * .column('first_name')\n * .column('age desc')\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc)\n * ```\n */\n column(column) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [\n parseOrderedColumnName(column),\n ]),\n }),\n });\n }\n /**\n * Specifies a list of columns for the index.\n *\n * Also see {@link column} for adding a single column or {@link expression} for\n * specifying an arbitrary expression.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .addIndex('person_first_name_and_age_index')\n * .columns(['first_name', 'age desc'])\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc)\n * ```\n */\n columns(columns) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, columns.map(parseOrderedColumnName)),\n }),\n });\n }\n /**\n * Specifies an arbitrary expression for the index.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .alterTable('person')\n * .addIndex('person_first_name_index')\n * .expression(sql`(first_name < 'Sami')`)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add index `person_first_name_index` ((first_name < 'Sami'))\n * ```\n */\n expression(expression) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [\n expression.toOperationNode(),\n ]),\n }),\n });\n }\n using(indexType) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, {\n using: RawNode.createWithSql(indexType),\n }),\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { UniqueConstraintNode } from '../operation-node/unique-constraint-node.js';\nexport class UniqueConstraintNodeBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Adds `nulls not distinct` to the unique constraint definition\n *\n * Supported by PostgreSQL dialect only\n */\n nullsNotDistinct() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { nullsNotDistinct: true }));\n }\n deferrable() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: true }));\n }\n notDeferrable() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: false }));\n }\n initiallyDeferred() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: true,\n }));\n }\n initiallyImmediate() {\n return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: false,\n }));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nimport { PrimaryKeyConstraintNode } from '../operation-node/primary-key-constraint-node.js';\nexport class PrimaryKeyConstraintBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n deferrable() {\n return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: true }));\n }\n notDeferrable() {\n return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: false }));\n }\n initiallyDeferred() {\n return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: true,\n }));\n }\n initiallyImmediate() {\n return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, {\n initiallyDeferred: false,\n }));\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nexport class CheckConstraintBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#node;\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const RenameConstraintNode = freeze({\n is(node) {\n return node.kind === 'RenameConstraintNode';\n },\n create(oldName, newName) {\n return freeze({\n kind: 'RenameConstraintNode',\n oldName: IdentifierNode.create(oldName),\n newName: IdentifierNode.create(newName),\n });\n },\n});\n", "/// \nimport { AddColumnNode } from '../operation-node/add-column-node.js';\nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { ColumnDefinitionNode } from '../operation-node/column-definition-node.js';\nimport { DropColumnNode } from '../operation-node/drop-column-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { RenameColumnNode } from '../operation-node/rename-column-node.js';\nimport { freeze, noop } from '../util/object-utils.js';\nimport { ColumnDefinitionBuilder, } from './column-definition-builder.js';\nimport { ModifyColumnNode } from '../operation-node/modify-column-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { ForeignKeyConstraintBuilder, } from './foreign-key-constraint-builder.js';\nimport { AddConstraintNode } from '../operation-node/add-constraint-node.js';\nimport { UniqueConstraintNode } from '../operation-node/unique-constraint-node.js';\nimport { CheckConstraintNode } from '../operation-node/check-constraint-node.js';\nimport { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { DropConstraintNode } from '../operation-node/drop-constraint-node.js';\nimport { AlterColumnBuilder, } from './alter-column-builder.js';\nimport { AlterTableExecutor } from './alter-table-executor.js';\nimport { AlterTableAddForeignKeyConstraintBuilder } from './alter-table-add-foreign-key-constraint-builder.js';\nimport { AlterTableDropConstraintBuilder } from './alter-table-drop-constraint-builder.js';\nimport { PrimaryKeyConstraintNode } from '../operation-node/primary-key-constraint-node.js';\nimport { DropIndexNode } from '../operation-node/drop-index-node.js';\nimport { AddIndexNode } from '../operation-node/add-index-node.js';\nimport { AlterTableAddIndexBuilder } from './alter-table-add-index-builder.js';\nimport { UniqueConstraintNodeBuilder, } from './unique-constraint-builder.js';\nimport { PrimaryKeyConstraintBuilder, } from './primary-key-constraint-builder.js';\nimport { CheckConstraintBuilder, } from './check-constraint-builder.js';\nimport { RenameConstraintNode } from '../operation-node/rename-constraint-node.js';\n/**\n * This builder can be used to create a `alter table` query.\n */\nexport class AlterTableBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n renameTo(newTableName) {\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n renameTo: parseTable(newTableName),\n }),\n });\n }\n setSchema(newSchema) {\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n setSchema: IdentifierNode.create(newSchema),\n }),\n });\n }\n alterColumn(column, alteration) {\n const builder = alteration(new AlterColumnBuilder(column));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode()),\n });\n }\n dropColumn(column) {\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column)),\n });\n }\n renameColumn(column, newColumn) {\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn)),\n });\n }\n addColumn(columnName, dataType, build = noop) {\n const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode())),\n });\n }\n modifyColumn(columnName, dataType, build = noop) {\n const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode())),\n });\n }\n /**\n * See {@link CreateTableBuilder.addUniqueConstraint}\n */\n addUniqueConstraint(constraintName, columns, build = noop) {\n const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName)));\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addConstraint: AddConstraintNode.create(uniqueConstraintBuilder.toOperationNode()),\n }),\n });\n }\n /**\n * See {@link CreateTableBuilder.addCheckConstraint}\n */\n addCheckConstraint(constraintName, checkExpression, build = noop) {\n const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName)));\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()),\n }),\n });\n }\n /**\n * See {@link CreateTableBuilder.addForeignKeyConstraint}\n *\n * Unlike {@link CreateTableBuilder.addForeignKeyConstraint} this method returns\n * the constraint builder and doesn't take a callback as the last argument. This\n * is because you can only add one column per `ALTER TABLE` query.\n */\n addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) {\n const constraintBuilder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName)));\n return new AlterTableAddForeignKeyConstraintBuilder({\n ...this.#props,\n constraintBuilder,\n });\n }\n /**\n * See {@link CreateTableBuilder.addPrimaryKeyConstraint}\n */\n addPrimaryKeyConstraint(constraintName, columns, build = noop) {\n const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName)));\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()),\n }),\n });\n }\n dropConstraint(constraintName) {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropConstraint: DropConstraintNode.create(constraintName),\n }),\n });\n }\n renameConstraint(oldName, newName) {\n return new AlterTableDropConstraintBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n renameConstraint: RenameConstraintNode.create(oldName, newName),\n }),\n });\n }\n /**\n * This can be used to add index to table.\n *\n * ### Examples\n *\n * ```ts\n * db.schema.alterTable('person')\n * .addIndex('person_email_index')\n * .column('email')\n * .unique()\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` add unique index `person_email_index` (`email`)\n * ```\n */\n addIndex(indexName) {\n return new AlterTableAddIndexBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n addIndex: AddIndexNode.create(indexName),\n }),\n });\n }\n /**\n * This can be used to drop index from table.\n *\n * ### Examples\n *\n * ```ts\n * db.schema.alterTable('person')\n * .dropIndex('person_email_index')\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * alter table `person` drop index `test_first_name_index`\n * ```\n */\n dropIndex(indexName) {\n return new AlterTableExecutor({\n ...this.#props,\n node: AlterTableNode.cloneWithTableProps(this.#props.node, {\n dropIndex: DropIndexNode.create(indexName),\n }),\n });\n }\n /**\n * Calls the given function passing `this` as the only argument.\n *\n * See {@link CreateTableBuilder.$call}\n */\n $call(func) {\n return func(this);\n }\n}\nexport class AlterTableColumnAlteringBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n alterColumn(column, alteration) {\n const builder = alteration(new AlterColumnBuilder(column));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode()),\n });\n }\n dropColumn(column) {\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column)),\n });\n }\n renameColumn(column, newColumn) {\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn)),\n });\n }\n addColumn(columnName, dataType, build = noop) {\n const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode())),\n });\n }\n modifyColumn(columnName, dataType, build = noop) {\n const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new AlterTableColumnAlteringBuilder({\n ...this.#props,\n node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode())),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { OperationNodeTransformer } from '../../operation-node/operation-node-transformer.js';\nimport { ValueListNode } from '../../operation-node/value-list-node.js';\nimport { ValueNode } from '../../operation-node/value-node.js';\n/**\n * Transforms all ValueNodes to immediate.\n *\n * WARNING! This should never be part of the public API. Users should never use this.\n * This is an internal helper.\n *\n * @internal\n */\nexport class ImmediateValueTransformer extends OperationNodeTransformer {\n transformPrimitiveValueList(node) {\n return ValueListNode.create(node.values.map(ValueNode.createImmediate));\n }\n transformValue(node) {\n return ValueNode.createImmediate(node.value);\n }\n}\n", "/// \nimport { CreateIndexNode, } from '../operation-node/create-index-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseOrderedColumnName, } from '../parser/reference-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { freeze } from '../util/object-utils.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { ImmediateValueTransformer } from '../plugin/immediate-value/immediate-value-transformer.js';\nexport class CreateIndexBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds the \"if not exists\" modifier.\n *\n * If the index already exists, no error is thrown if this method has been called.\n */\n ifNotExists() {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n ifNotExists: true,\n }),\n });\n }\n /**\n * Makes the index unique.\n */\n unique() {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n unique: true,\n }),\n });\n }\n /**\n * Adds `nulls not distinct` specifier to index.\n * This only works on some dialects like PostgreSQL.\n *\n * ### Examples\n *\n * ```ts\n * db.schema.createIndex('person_first_name_index')\n * .on('person')\n * .column('first_name')\n * .nullsNotDistinct()\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create index \"person_first_name_index\"\n * on \"test\" (\"first_name\")\n * nulls not distinct;\n * ```\n */\n nullsNotDistinct() {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n nullsNotDistinct: true,\n }),\n });\n }\n /**\n * Specifies the table for the index.\n */\n on(table) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n table: parseTable(table),\n }),\n });\n }\n /**\n * Adds a column to the index.\n *\n * Also see {@link columns} for adding multiple columns at once or {@link expression}\n * for specifying an arbitrary expression.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createIndex('person_first_name_and_age_index')\n * .on('person')\n * .column('first_name')\n * .column('age desc')\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create index \"person_first_name_and_age_index\" on \"person\" (\"first_name\", \"age\" desc)\n * ```\n */\n column(column) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWithColumns(this.#props.node, [\n parseOrderedColumnName(column),\n ]),\n });\n }\n /**\n * Specifies a list of columns for the index.\n *\n * Also see {@link column} for adding a single column or {@link expression} for\n * specifying an arbitrary expression.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createIndex('person_first_name_and_age_index')\n * .on('person')\n * .columns(['first_name', 'age desc'])\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create index \"person_first_name_and_age_index\" on \"person\" (\"first_name\", \"age\" desc)\n * ```\n */\n columns(columns) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWithColumns(this.#props.node, columns.map(parseOrderedColumnName)),\n });\n }\n /**\n * Specifies an arbitrary expression for the index.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createIndex('person_first_name_index')\n * .on('person')\n * .expression(sql`first_name COLLATE \"fi_FI\"`)\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create index \"person_first_name_index\" on \"person\" (first_name COLLATE \"fi_FI\")\n * ```\n */\n expression(expression) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWithColumns(this.#props.node, [\n expression.toOperationNode(),\n ]),\n });\n }\n using(indexType) {\n return new CreateIndexBuilder({\n ...this.#props,\n node: CreateIndexNode.cloneWith(this.#props.node, {\n using: RawNode.createWithSql(indexType),\n }),\n });\n }\n where(...args) {\n const transformer = new ImmediateValueTransformer();\n return new CreateIndexBuilder({\n ...this.#props,\n node: QueryNode.cloneWithWhere(this.#props.node, transformer.transformNode(parseValueBinaryOperationOrExpression(args), this.#props.queryId)),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { CreateSchemaNode } from '../operation-node/create-schema-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class CreateSchemaBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifNotExists() {\n return new CreateSchemaBuilder({\n ...this.#props,\n node: CreateSchemaNode.cloneWith(this.#props.node, { ifNotExists: true }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { ON_COMMIT_ACTIONS, } from '../operation-node/create-table-node.js';\nexport function parseOnCommitAction(action) {\n if (ON_COMMIT_ACTIONS.includes(action)) {\n return action;\n }\n throw new Error(`invalid OnCommitAction ${action}`);\n}\n", "/// \nimport { ColumnDefinitionNode } from '../operation-node/column-definition-node.js';\nimport { CreateTableNode, } from '../operation-node/create-table-node.js';\nimport { ColumnDefinitionBuilder } from './column-definition-builder.js';\nimport { freeze, noop } from '../util/object-utils.js';\nimport { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ForeignKeyConstraintBuilder, } from './foreign-key-constraint-builder.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { PrimaryKeyConstraintNode } from '../operation-node/primary-key-constraint-node.js';\nimport { UniqueConstraintNode } from '../operation-node/unique-constraint-node.js';\nimport { CheckConstraintNode } from '../operation-node/check-constraint-node.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseOnCommitAction } from '../parser/on-commit-action-parse.js';\nimport { UniqueConstraintNodeBuilder, } from './unique-constraint-builder.js';\nimport { parseExpression } from '../parser/expression-parser.js';\nimport { PrimaryKeyConstraintBuilder, } from './primary-key-constraint-builder.js';\nimport { CheckConstraintBuilder, } from './check-constraint-builder.js';\n/**\n * This builder can be used to create a `create table` query.\n */\nexport class CreateTableBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds the \"temporary\" modifier.\n *\n * Use this to create a temporary table.\n */\n temporary() {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWith(this.#props.node, {\n temporary: true,\n }),\n });\n }\n /**\n * Adds an \"on commit\" statement.\n *\n * This can be used in conjunction with temporary tables on supported databases\n * like PostgreSQL.\n */\n onCommit(onCommit) {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWith(this.#props.node, {\n onCommit: parseOnCommitAction(onCommit),\n }),\n });\n }\n /**\n * Adds the \"if not exists\" modifier.\n *\n * If the table already exists, no error is thrown if this method has been called.\n */\n ifNotExists() {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWith(this.#props.node, {\n ifNotExists: true,\n }),\n });\n }\n /**\n * Adds a column to the table.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', (col) => col.autoIncrement().primaryKey())\n * .addColumn('first_name', 'varchar(50)', (col) => col.notNull())\n * .addColumn('last_name', 'varchar(255)')\n * .addColumn('bank_balance', 'numeric(8, 2)')\n * // You can specify any data type using the `sql` tag if the types\n * // don't include it.\n * .addColumn('data', sql`any_type_here`)\n * .addColumn('parent_id', 'integer', (col) =>\n * col.references('person.id').onDelete('cascade')\n * )\n * ```\n *\n * With this method, it's once again good to remember that Kysely just builds the\n * query and doesn't provide the same API for all databases. For example, some\n * databases like older MySQL don't support the `references` statement in the\n * column definition. Instead foreign key constraints need to be defined in the\n * `create table` query. See the next example:\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', (col) => col.primaryKey())\n * .addColumn('parent_id', 'integer')\n * .addForeignKeyConstraint(\n * 'person_parent_id_fk',\n * ['parent_id'],\n * 'person',\n * ['id'],\n * (cb) => cb.onDelete('cascade')\n * )\n * .execute()\n * ```\n *\n * Another good example is that PostgreSQL doesn't support the `auto_increment`\n * keyword and you need to define an autoincrementing column for example using\n * `serial`:\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'serial', (col) => col.primaryKey())\n * .execute()\n * ```\n */\n addColumn(columnName, dataType, build = noop) {\n const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithColumn(this.#props.node, columnBuilder.toOperationNode()),\n });\n }\n /**\n * Adds a primary key constraint for one or more columns.\n *\n * The constraint name can be anything you want, but it must be unique\n * across the whole database.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('first_name', 'varchar(64)')\n * .addColumn('last_name', 'varchar(64)')\n * .addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name'])\n * .execute()\n * ```\n */\n addPrimaryKeyConstraint(constraintName, columns, build = noop) {\n const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName)));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode()),\n });\n }\n /**\n * Adds a unique constraint for one or more columns.\n *\n * The constraint name can be anything you want, but it must be unique\n * across the whole database.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('first_name', 'varchar(64)')\n * .addColumn('last_name', 'varchar(64)')\n * .addUniqueConstraint(\n * 'first_name_last_name_unique',\n * ['first_name', 'last_name']\n * )\n * .execute()\n * ```\n *\n * In dialects such as PostgreSQL you can specify `nulls not distinct` as follows:\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('first_name', 'varchar(64)')\n * .addColumn('last_name', 'varchar(64)')\n * .addUniqueConstraint(\n * 'first_name_last_name_unique',\n * ['first_name', 'last_name'],\n * (cb) => cb.nullsNotDistinct()\n * )\n * .execute()\n * ```\n */\n addUniqueConstraint(constraintName, columns, build = noop) {\n const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName)));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithConstraint(this.#props.node, uniqueConstraintBuilder.toOperationNode()),\n });\n }\n /**\n * Adds a check constraint.\n *\n * The constraint name can be anything you want, but it must be unique\n * across the whole database.\n *\n * ### Examples\n *\n * ```ts\n * import {\u00A0sql } from 'kysely'\n *\n * await db.schema\n * .createTable('animal')\n * .addColumn('number_of_legs', 'integer')\n * .addCheckConstraint('check_legs', sql`number_of_legs < 5`)\n * .execute()\n * ```\n */\n addCheckConstraint(constraintName, checkExpression, build = noop) {\n const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName)));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode()),\n });\n }\n /**\n * Adds a foreign key constraint.\n *\n * The constraint name can be anything you want, but it must be unique\n * across the whole database.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('owner_id', 'integer')\n * .addForeignKeyConstraint(\n * 'owner_id_foreign',\n * ['owner_id'],\n * 'person',\n * ['id'],\n * )\n * .execute()\n * ```\n *\n * Add constraint for multiple columns:\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('owner_id1', 'integer')\n * .addColumn('owner_id2', 'integer')\n * .addForeignKeyConstraint(\n * 'owner_id_foreign',\n * ['owner_id1', 'owner_id2'],\n * 'person',\n * ['id1', 'id2'],\n * (cb) => cb.onDelete('cascade')\n * )\n * .execute()\n * ```\n */\n addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) {\n const builder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName)));\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithConstraint(this.#props.node, builder.toOperationNode()),\n });\n }\n /**\n * This can be used to add any additional SQL to the front of the query __after__ the `create` keyword.\n *\n * Also see {@link temporary}.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .modifyFront(sql`global temporary`)\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn('first_name', 'varchar(64)', col => col.notNull())\n * .addColumn('last_name', 'varchar(64)', col => col.notNull())\n * .execute()\n * ```\n *\n * The generated SQL (Postgres):\n *\n * ```sql\n * create global temporary table \"person\" (\n * \"id\" integer primary key,\n * \"first_name\" varchar(64) not null,\n * \"last_name\" varchar(64) not null\n * )\n * ```\n */\n modifyFront(modifier) {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithFrontModifier(this.#props.node, modifier.toOperationNode()),\n });\n }\n /**\n * This can be used to add any additional SQL to the end of the query.\n *\n * Also see {@link onCommit}.\n *\n * ### Examples\n *\n * ```ts\n * import { sql } from 'kysely'\n *\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey())\n * .addColumn('first_name', 'varchar(64)', col => col.notNull())\n * .addColumn('last_name', 'varchar(64)', col => col.notNull())\n * .modifyEnd(sql`collate utf8_unicode_ci`)\n * .execute()\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * create table `person` (\n * `id` integer primary key,\n * `first_name` varchar(64) not null,\n * `last_name` varchar(64) not null\n * ) collate utf8_unicode_ci\n * ```\n */\n modifyEnd(modifier) {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWithEndModifier(this.#props.node, modifier.toOperationNode()),\n });\n }\n /**\n * Allows to create table from `select` query.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('copy')\n * .temporary()\n * .as(db.selectFrom('person').select(['first_name', 'last_name']))\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * create temporary table \"copy\" as\n * select \"first_name\", \"last_name\" from \"person\"\n * ```\n */\n as(expression) {\n return new CreateTableBuilder({\n ...this.#props,\n node: CreateTableNode.cloneWith(this.#props.node, {\n selectQuery: parseExpression(expression),\n }),\n });\n }\n /**\n * Calls the given function passing `this` as the only argument.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createTable('test')\n * .$call((builder) => builder.addColumn('id', 'integer'))\n * .execute()\n * ```\n *\n * This is useful for creating reusable functions that can be called with a builder.\n *\n * ```ts\n * import { type CreateTableBuilder, sql } from 'kysely'\n *\n * const addDefaultColumns = (ctb: CreateTableBuilder) => {\n * return ctb\n * .addColumn('id', 'integer', (col) => col.notNull())\n * .addColumn('created_at', 'date', (col) =>\n * col.notNull().defaultTo(sql`now()`)\n * )\n * .addColumn('updated_at', 'date', (col) =>\n * col.notNull().defaultTo(sql`now()`)\n * )\n * }\n *\n * await db.schema\n * .createTable('test')\n * .$call(addDefaultColumns)\n * .execute()\n * ```\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { DropIndexNode } from '../operation-node/drop-index-node.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class DropIndexBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Specifies the table the index was created for. This is not needed\n * in all dialects.\n */\n on(table) {\n return new DropIndexBuilder({\n ...this.#props,\n node: DropIndexNode.cloneWith(this.#props.node, {\n table: parseTable(table),\n }),\n });\n }\n ifExists() {\n return new DropIndexBuilder({\n ...this.#props,\n node: DropIndexNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n cascade() {\n return new DropIndexBuilder({\n ...this.#props,\n node: DropIndexNode.cloneWith(this.#props.node, {\n cascade: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { DropSchemaNode } from '../operation-node/drop-schema-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class DropSchemaBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifExists() {\n return new DropSchemaBuilder({\n ...this.#props,\n node: DropSchemaNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n cascade() {\n return new DropSchemaBuilder({\n ...this.#props,\n node: DropSchemaNode.cloneWith(this.#props.node, {\n cascade: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { DropTableNode } from '../operation-node/drop-table-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class DropTableBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifExists() {\n return new DropTableBuilder({\n ...this.#props,\n node: DropTableNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n cascade() {\n return new DropTableBuilder({\n ...this.#props,\n node: DropTableNode.cloneWith(this.#props.node, {\n cascade: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const CreateViewNode = freeze({\n is(node) {\n return node.kind === 'CreateViewNode';\n },\n create(name) {\n return freeze({\n kind: 'CreateViewNode',\n name: SchemableIdentifierNode.create(name),\n });\n },\n cloneWith(createView, params) {\n return freeze({\n ...createView,\n ...params,\n });\n },\n});\n", "/// \nimport { ImmediateValueTransformer } from './immediate-value-transformer.js';\n/**\n * Transforms all ValueNodes to immediate.\n *\n * WARNING! This should never be part of the public API. Users should never use this.\n * This is an internal helper.\n *\n * @internal\n */\nexport class ImmediateValuePlugin {\n #transformer = new ImmediateValueTransformer();\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n transformResult(args) {\n return Promise.resolve(args.result);\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { CreateViewNode } from '../operation-node/create-view-node.js';\nimport { parseColumnName } from '../parser/reference-parser.js';\nimport { ImmediateValuePlugin } from '../plugin/immediate-value/immediate-value-plugin.js';\nexport class CreateViewBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds the \"temporary\" modifier.\n *\n * Use this to create a temporary view.\n */\n temporary() {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n temporary: true,\n }),\n });\n }\n materialized() {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n materialized: true,\n }),\n });\n }\n /**\n * Only implemented on some dialects like SQLite. On most dialects, use {@link orReplace}.\n */\n ifNotExists() {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n ifNotExists: true,\n }),\n });\n }\n orReplace() {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n orReplace: true,\n }),\n });\n }\n columns(columns) {\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n columns: columns.map(parseColumnName),\n }),\n });\n }\n /**\n * Sets the select query or a `values` statement that creates the view.\n *\n * WARNING!\n * Some dialects don't support parameterized queries in DDL statements and therefore\n * the query or raw {@link sql } expression passed here is interpolated into a single\n * string opening an SQL injection vulnerability. DO NOT pass unchecked user input\n * into the query or raw expression passed to this method!\n */\n as(query) {\n const queryNode = query\n .withPlugin(new ImmediateValuePlugin())\n .toOperationNode();\n return new CreateViewBuilder({\n ...this.#props,\n node: CreateViewNode.cloneWith(this.#props.node, {\n as: queryNode,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const DropViewNode = freeze({\n is(node) {\n return node.kind === 'DropViewNode';\n },\n create(name) {\n return freeze({\n kind: 'DropViewNode',\n name: SchemableIdentifierNode.create(name),\n });\n },\n cloneWith(dropView, params) {\n return freeze({\n ...dropView,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { DropViewNode } from '../operation-node/drop-view-node.js';\nexport class DropViewBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n materialized() {\n return new DropViewBuilder({\n ...this.#props,\n node: DropViewNode.cloneWith(this.#props.node, {\n materialized: true,\n }),\n });\n }\n ifExists() {\n return new DropViewBuilder({\n ...this.#props,\n node: DropViewNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n cascade() {\n return new DropViewBuilder({\n ...this.#props,\n node: DropViewNode.cloneWith(this.#props.node, {\n cascade: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { ValueListNode } from './value-list-node.js';\nimport { ValueNode } from './value-node.js';\n/**\n * @internal\n */\nexport const CreateTypeNode = freeze({\n is(node) {\n return node.kind === 'CreateTypeNode';\n },\n create(name) {\n return freeze({\n kind: 'CreateTypeNode',\n name,\n });\n },\n cloneWithEnum(createType, values) {\n return freeze({\n ...createType,\n enum: ValueListNode.create(values.map(ValueNode.createImmediate)),\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { CreateTypeNode } from '../operation-node/create-type-node.js';\nexport class CreateTypeBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n /**\n * Creates an anum type.\n *\n * ### Examples\n *\n * ```ts\n * db.schema.createType('species').asEnum(['cat', 'dog', 'frog'])\n * ```\n */\n asEnum(values) {\n return new CreateTypeBuilder({\n ...this.#props,\n node: CreateTypeNode.cloneWithEnum(this.#props.node, values),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const DropTypeNode = freeze({\n is(node) {\n return node.kind === 'DropTypeNode';\n },\n create(name) {\n return freeze({\n kind: 'DropTypeNode',\n name,\n });\n },\n cloneWith(dropType, params) {\n return freeze({\n ...dropType,\n ...params,\n });\n },\n});\n", "/// \nimport { DropTypeNode } from '../operation-node/drop-type-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class DropTypeBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n ifExists() {\n return new DropTypeBuilder({\n ...this.#props,\n node: DropTypeNode.cloneWith(this.#props.node, {\n ifExists: true,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { SchemableIdentifierNode } from '../operation-node/schemable-identifier-node.js';\nexport function parseSchemableIdentifier(id) {\n const SCHEMA_SEPARATOR = '.';\n if (id.includes(SCHEMA_SEPARATOR)) {\n const parts = id.split(SCHEMA_SEPARATOR).map(trim);\n if (parts.length === 2) {\n return SchemableIdentifierNode.createWithSchema(parts[0], parts[1]);\n }\n else {\n throw new Error(`invalid schemable identifier ${id}`);\n }\n }\n else {\n return SchemableIdentifierNode.create(id);\n }\n}\nfunction trim(str) {\n return str.trim();\n}\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const RefreshMaterializedViewNode = freeze({\n is(node) {\n return node.kind === 'RefreshMaterializedViewNode';\n },\n create(name) {\n return freeze({\n kind: 'RefreshMaterializedViewNode',\n name: SchemableIdentifierNode.create(name),\n });\n },\n cloneWith(createView, params) {\n return freeze({\n ...createView,\n ...params,\n });\n },\n});\n", "/// \nimport { freeze } from '../util/object-utils.js';\nimport { RefreshMaterializedViewNode } from '../operation-node/refresh-materialized-view-node.js';\nexport class RefreshMaterializedViewBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds the \"concurrently\" modifier.\n *\n * Use this to refresh the view without locking out concurrent selects on the materialized view.\n *\n * WARNING!\n * This cannot be used with the \"with no data\" modifier.\n */\n concurrently() {\n return new RefreshMaterializedViewBuilder({\n ...this.#props,\n node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {\n concurrently: true,\n withNoData: false,\n }),\n });\n }\n /**\n * Adds the \"with data\" modifier.\n *\n * If specified (or defaults) the backing query is executed to provide the new data, and the materialized view is left in a scannable state\n */\n withData() {\n return new RefreshMaterializedViewBuilder({\n ...this.#props,\n node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {\n withNoData: false,\n }),\n });\n }\n /**\n * Adds the \"with no data\" modifier.\n *\n * If specified, no new data is generated and the materialized view is left in an unscannable state.\n *\n * WARNING!\n * This cannot be used with the \"concurrently\" modifier.\n */\n withNoData() {\n return new RefreshMaterializedViewBuilder({\n ...this.#props,\n node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {\n withNoData: true,\n concurrently: false,\n }),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n await this.#props.executor.executeQuery(this.compile());\n }\n}\n", "/// \nimport { AlterTableNode } from '../operation-node/alter-table-node.js';\nimport { CreateIndexNode } from '../operation-node/create-index-node.js';\nimport { CreateSchemaNode } from '../operation-node/create-schema-node.js';\nimport { CreateTableNode } from '../operation-node/create-table-node.js';\nimport { DropIndexNode } from '../operation-node/drop-index-node.js';\nimport { DropSchemaNode } from '../operation-node/drop-schema-node.js';\nimport { DropTableNode } from '../operation-node/drop-table-node.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { AlterTableBuilder } from './alter-table-builder.js';\nimport { CreateIndexBuilder } from './create-index-builder.js';\nimport { CreateSchemaBuilder } from './create-schema-builder.js';\nimport { CreateTableBuilder } from './create-table-builder.js';\nimport { DropIndexBuilder } from './drop-index-builder.js';\nimport { DropSchemaBuilder } from './drop-schema-builder.js';\nimport { DropTableBuilder } from './drop-table-builder.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { CreateViewBuilder } from './create-view-builder.js';\nimport { CreateViewNode } from '../operation-node/create-view-node.js';\nimport { DropViewBuilder } from './drop-view-builder.js';\nimport { DropViewNode } from '../operation-node/drop-view-node.js';\nimport { CreateTypeBuilder } from './create-type-builder.js';\nimport { DropTypeBuilder } from './drop-type-builder.js';\nimport { CreateTypeNode } from '../operation-node/create-type-node.js';\nimport { DropTypeNode } from '../operation-node/drop-type-node.js';\nimport { parseSchemableIdentifier } from '../parser/identifier-parser.js';\nimport { RefreshMaterializedViewBuilder } from './refresh-materialized-view-builder.js';\nimport { RefreshMaterializedViewNode } from '../operation-node/refresh-materialized-view-node.js';\n/**\n * Provides methods for building database schema.\n */\nexport class SchemaModule {\n #executor;\n constructor(executor) {\n this.#executor = executor;\n }\n /**\n * Create a new table.\n *\n * ### Examples\n *\n * This example creates a new table with columns `id`, `first_name`,\n * `last_name` and `gender`:\n *\n * ```ts\n * await db.schema\n * .createTable('person')\n * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())\n * .addColumn('first_name', 'varchar', col => col.notNull())\n * .addColumn('last_name', 'varchar', col => col.notNull())\n * .addColumn('gender', 'varchar')\n * .execute()\n * ```\n *\n * This example creates a table with a foreign key. Not all database\n * engines support column-level foreign key constraint definitions.\n * For example if you are using MySQL 5.X see the next example after\n * this one.\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())\n * .addColumn('owner_id', 'integer', col => col\n * .references('person.id')\n * .onDelete('cascade')\n * )\n * .execute()\n * ```\n *\n * This example adds a foreign key constraint for a columns just\n * like the previous example, but using a table-level statement.\n * On MySQL 5.X you need to define foreign key constraints like\n * this:\n *\n * ```ts\n * await db.schema\n * .createTable('pet')\n * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())\n * .addColumn('owner_id', 'integer')\n * .addForeignKeyConstraint(\n * 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'],\n * (constraint) => constraint.onDelete('cascade')\n * )\n * .execute()\n * ```\n */\n createTable(table) {\n return new CreateTableBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateTableNode.create(parseTable(table)),\n });\n }\n /**\n * Drop a table.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropTable('person')\n * .execute()\n * ```\n */\n dropTable(table) {\n return new DropTableBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropTableNode.create(parseTable(table)),\n });\n }\n /**\n * Create a new index.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createIndex('person_full_name_unique_index')\n * .on('person')\n * .columns(['first_name', 'last_name'])\n * .execute()\n * ```\n */\n createIndex(indexName) {\n return new CreateIndexBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateIndexNode.create(indexName),\n });\n }\n /**\n * Drop an index.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropIndex('person_full_name_unique_index')\n * .execute()\n * ```\n */\n dropIndex(indexName) {\n return new DropIndexBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropIndexNode.create(indexName),\n });\n }\n /**\n * Create a new schema.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createSchema('some_schema')\n * .execute()\n * ```\n */\n createSchema(schema) {\n return new CreateSchemaBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateSchemaNode.create(schema),\n });\n }\n /**\n * Drop a schema.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropSchema('some_schema')\n * .execute()\n * ```\n */\n dropSchema(schema) {\n return new DropSchemaBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropSchemaNode.create(schema),\n });\n }\n /**\n * Alter a table.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .alterTable('person')\n * .alterColumn('first_name', (ac) => ac.setDataType('text'))\n * .execute()\n * ```\n */\n alterTable(table) {\n return new AlterTableBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: AlterTableNode.create(parseTable(table)),\n });\n }\n /**\n * Create a new view.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createView('dogs')\n * .orReplace()\n * .as(db.selectFrom('pet').selectAll().where('species', '=', 'dog'))\n * .execute()\n * ```\n */\n createView(viewName) {\n return new CreateViewBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateViewNode.create(viewName),\n });\n }\n /**\n * Refresh a materialized view.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .refreshMaterializedView('my_view')\n * .concurrently()\n * .execute()\n * ```\n */\n refreshMaterializedView(viewName) {\n return new RefreshMaterializedViewBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: RefreshMaterializedViewNode.create(viewName),\n });\n }\n /**\n * Drop a view.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropView('dogs')\n * .ifExists()\n * .execute()\n * ```\n */\n dropView(viewName) {\n return new DropViewBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropViewNode.create(viewName),\n });\n }\n /**\n * Create a new type.\n *\n * Only some dialects like PostgreSQL have user-defined types.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .createType('species')\n * .asEnum(['dog', 'cat', 'frog'])\n * .execute()\n * ```\n */\n createType(typeName) {\n return new CreateTypeBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: CreateTypeNode.create(parseSchemableIdentifier(typeName)),\n });\n }\n /**\n * Drop a type.\n *\n * Only some dialects like PostgreSQL have user-defined types.\n *\n * ### Examples\n *\n * ```ts\n * await db.schema\n * .dropType('species')\n * .ifExists()\n * .execute()\n * ```\n */\n dropType(typeName) {\n return new DropTypeBuilder({\n queryId: createQueryId(),\n executor: this.#executor,\n node: DropTypeNode.create(parseSchemableIdentifier(typeName)),\n });\n }\n /**\n * Returns a copy of this schema module with the given plugin installed.\n */\n withPlugin(plugin) {\n return new SchemaModule(this.#executor.withPlugin(plugin));\n }\n /**\n * Returns a copy of this schema module without any plugins.\n */\n withoutPlugins() {\n return new SchemaModule(this.#executor.withoutPlugins());\n }\n /**\n * See {@link QueryCreator.withSchema}\n */\n withSchema(schema) {\n return new SchemaModule(this.#executor.withPluginAtFront(new WithSchemaPlugin(schema)));\n }\n}\n", "/// \nimport { DynamicReferenceBuilder } from './dynamic-reference-builder.js';\nimport { DynamicTableBuilder } from './dynamic-table-builder.js';\nexport class DynamicModule {\n /**\n * Creates a dynamic reference to a column that is not know at compile time.\n *\n * Kysely is built in a way that by default you can't refer to tables or columns\n * that are not actually visible in the current query and context. This is all\n * done by TypeScript at compile time, which means that you need to know the\n * columns and tables at compile time. This is not always the case of course.\n *\n * This method is meant to be used in those cases where the column names\n * come from the user input or are not otherwise known at compile time.\n *\n * WARNING! Unlike values, column names are not escaped by the database engine\n * or Kysely and if you pass in unchecked column names using this method, you\n * create an SQL injection vulnerability. Always __always__ validate the user\n * input before passing it to this method.\n *\n * There are couple of examples below for some use cases, but you can pass\n * `ref` to other methods as well. If the types allow you to pass a `ref`\n * value to some place, it should work.\n *\n * ### Examples\n *\n * Filter by a column not know at compile time:\n *\n * ```ts\n * async function someQuery(filterColumn: string, filterValue: string) {\n * const { ref } = db.dynamic\n *\n * return await db\n * .selectFrom('person')\n * .selectAll()\n * .where(ref(filterColumn), '=', filterValue)\n * .execute()\n * }\n *\n * someQuery('first_name', 'Arnold')\n * someQuery('person.last_name', 'Aniston')\n * ```\n *\n * Order by a column not know at compile time:\n *\n * ```ts\n * async function someQuery(orderBy: string) {\n * const { ref } = db.dynamic\n *\n * return await db\n * .selectFrom('person')\n * .select('person.first_name as fn')\n * .orderBy(ref(orderBy))\n * .execute()\n * }\n *\n * someQuery('fn')\n * ```\n *\n * In this example we add selections dynamically:\n *\n * ```ts\n * const { ref } = db.dynamic\n *\n * // Some column name provided by the user. Value not known at compile time.\n * const columnFromUserInput: PossibleColumns = 'birthdate';\n *\n * // A type that lists all possible values `columnFromUserInput` can have.\n * // You can use `keyof Person` if any column of an interface is allowed.\n * type PossibleColumns = 'last_name' | 'first_name' | 'birthdate'\n *\n * const [person] = await db.selectFrom('person')\n * .select([\n * ref(columnFromUserInput),\n * 'id'\n * ])\n * .execute()\n *\n * // The resulting type contains all `PossibleColumns` as optional fields\n * // because we cannot know which field was actually selected before\n * // running the code.\n * const lastName: string | null | undefined = person?.last_name\n * const firstName: string | undefined = person?.first_name\n * const birthDate: Date | null | undefined = person?.birthdate\n *\n * // The result type also contains the compile time selection `id`.\n * person?.id\n * ```\n */\n ref(reference) {\n return new DynamicReferenceBuilder(reference);\n }\n /**\n * Creates a table reference to a table that's not fully known at compile time.\n *\n * The type `T` is allowed to be a union of multiple tables.\n *\n * \n *\n * A generic type-safe helper function for finding a row by a column value:\n *\n * ```ts\n * import { SelectType } from 'kysely'\n * import { Database } from 'type-editor'\n *\n * async function getRowByColumn<\n * T extends keyof Database,\n * C extends keyof Database[T] & string,\n * V extends SelectType,\n * >(t: T, c: C, v: V) {\n * // We need to use the dynamic module since the table name\n * // is not known at compile time.\n * const { table, ref } = db.dynamic\n *\n * return await db\n * .selectFrom(table(t).as('t'))\n * .selectAll()\n * .where(ref(c), '=', v)\n * .orderBy('t.id')\n * .executeTakeFirstOrThrow()\n * }\n *\n * const person = await getRowByColumn('person', 'first_name', 'Arnold')\n * ```\n */\n table(table) {\n return new DynamicTableBuilder(table);\n }\n}\n", "/// \nexport class DefaultConnectionProvider {\n #driver;\n constructor(driver) {\n this.#driver = driver;\n }\n async provideConnection(consumer) {\n const connection = await this.#driver.acquireConnection();\n try {\n return await consumer(connection);\n }\n finally {\n await this.#driver.releaseConnection(connection);\n }\n }\n}\n", "/// \nimport { QueryExecutorBase } from './query-executor-base.js';\nexport class DefaultQueryExecutor extends QueryExecutorBase {\n #compiler;\n #adapter;\n #connectionProvider;\n constructor(compiler, adapter, connectionProvider, plugins = []) {\n super(plugins);\n this.#compiler = compiler;\n this.#adapter = adapter;\n this.#connectionProvider = connectionProvider;\n }\n get adapter() {\n return this.#adapter;\n }\n compileQuery(node, queryId) {\n return this.#compiler.compileQuery(node, queryId);\n }\n provideConnection(consumer) {\n return this.#connectionProvider.provideConnection(consumer);\n }\n withPlugins(plugins) {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, ...plugins]);\n }\n withPlugin(plugin) {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, plugin]);\n }\n withPluginAtFront(plugin) {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [plugin, ...this.plugins]);\n }\n withConnectionProvider(connectionProvider) {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, connectionProvider, [...this.plugins]);\n }\n withoutPlugins() {\n return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, []);\n }\n}\n", "/// \nimport { isFunction } from './object-utils.js';\nexport function performanceNow() {\n if (typeof performance !== 'undefined' && isFunction(performance.now)) {\n return performance.now();\n }\n else {\n return Date.now();\n }\n}\n", "/// \nimport { performanceNow } from '../util/performance-now.js';\n/**\n * A small wrapper around {@link Driver} that makes sure the driver is\n * initialized before it is used, only initialized and destroyed\n * once etc.\n */\nexport class RuntimeDriver {\n #driver;\n #log;\n #initPromise;\n #initDone;\n #destroyPromise;\n #connections = new WeakSet();\n constructor(driver, log) {\n this.#initDone = false;\n this.#driver = driver;\n this.#log = log;\n }\n async init() {\n if (this.#destroyPromise) {\n throw new Error('driver has already been destroyed');\n }\n if (!this.#initPromise) {\n this.#initPromise = this.#driver\n .init()\n .then(() => {\n this.#initDone = true;\n })\n .catch((err) => {\n this.#initPromise = undefined;\n return Promise.reject(err);\n });\n }\n await this.#initPromise;\n }\n async acquireConnection() {\n if (this.#destroyPromise) {\n throw new Error('driver has already been destroyed');\n }\n if (!this.#initDone) {\n await this.init();\n }\n const connection = await this.#driver.acquireConnection();\n if (!this.#connections.has(connection)) {\n if (this.#needsLogging()) {\n this.#addLogging(connection);\n }\n this.#connections.add(connection);\n }\n return connection;\n }\n async releaseConnection(connection) {\n await this.#driver.releaseConnection(connection);\n }\n beginTransaction(connection, settings) {\n return this.#driver.beginTransaction(connection, settings);\n }\n commitTransaction(connection) {\n return this.#driver.commitTransaction(connection);\n }\n rollbackTransaction(connection) {\n return this.#driver.rollbackTransaction(connection);\n }\n savepoint(connection, savepointName, compileQuery) {\n if (this.#driver.savepoint) {\n return this.#driver.savepoint(connection, savepointName, compileQuery);\n }\n throw new Error('The `savepoint` method is not supported by this driver');\n }\n rollbackToSavepoint(connection, savepointName, compileQuery) {\n if (this.#driver.rollbackToSavepoint) {\n return this.#driver.rollbackToSavepoint(connection, savepointName, compileQuery);\n }\n throw new Error('The `rollbackToSavepoint` method is not supported by this driver');\n }\n releaseSavepoint(connection, savepointName, compileQuery) {\n if (this.#driver.releaseSavepoint) {\n return this.#driver.releaseSavepoint(connection, savepointName, compileQuery);\n }\n throw new Error('The `releaseSavepoint` method is not supported by this driver');\n }\n async destroy() {\n if (!this.#initPromise) {\n return;\n }\n await this.#initPromise;\n if (!this.#destroyPromise) {\n this.#destroyPromise = this.#driver.destroy().catch((err) => {\n this.#destroyPromise = undefined;\n return Promise.reject(err);\n });\n }\n await this.#destroyPromise;\n }\n #needsLogging() {\n return (this.#log.isLevelEnabled('query') || this.#log.isLevelEnabled('error'));\n }\n // This method monkey patches the database connection's executeQuery method\n // by adding logging code around it. Monkey patching is not pretty, but it's\n // the best option in this case.\n #addLogging(connection) {\n const executeQuery = connection.executeQuery;\n const streamQuery = connection.streamQuery;\n const dis = this;\n connection.executeQuery = async (compiledQuery) => {\n let caughtError;\n const startTime = performanceNow();\n try {\n return await executeQuery.call(connection, compiledQuery);\n }\n catch (error) {\n caughtError = error;\n await dis.#logError(error, compiledQuery, startTime);\n throw error;\n }\n finally {\n if (!caughtError) {\n await dis.#logQuery(compiledQuery, startTime);\n }\n }\n };\n connection.streamQuery = async function* (compiledQuery, chunkSize) {\n let caughtError;\n const startTime = performanceNow();\n try {\n for await (const result of streamQuery.call(connection, compiledQuery, chunkSize)) {\n yield result;\n }\n }\n catch (error) {\n caughtError = error;\n await dis.#logError(error, compiledQuery, startTime);\n throw error;\n }\n finally {\n if (!caughtError) {\n await dis.#logQuery(compiledQuery, startTime, true);\n }\n }\n };\n }\n async #logError(error, compiledQuery, startTime) {\n await this.#log.error(() => ({\n level: 'error',\n error,\n query: compiledQuery,\n queryDurationMillis: this.#calculateDurationMillis(startTime),\n }));\n }\n async #logQuery(compiledQuery, startTime, isStream = false) {\n await this.#log.query(() => ({\n level: 'query',\n isStream,\n query: compiledQuery,\n queryDurationMillis: this.#calculateDurationMillis(startTime),\n }));\n }\n #calculateDurationMillis(startTime) {\n return performanceNow() - startTime;\n }\n}\n", "/// \nconst ignoreError = () => { };\nexport class SingleConnectionProvider {\n #connection;\n #runningPromise;\n constructor(connection) {\n this.#connection = connection;\n }\n async provideConnection(consumer) {\n while (this.#runningPromise) {\n await this.#runningPromise.catch(ignoreError);\n }\n // `#runningPromise` must be set to undefined before it's\n // resolved or rejected. Otherwise the while loop above\n // will misbehave.\n this.#runningPromise = this.#run(consumer).finally(() => {\n this.#runningPromise = undefined;\n });\n return this.#runningPromise;\n }\n // Run the runner in an async function to make sure it doesn't\n // throw synchronous errors.\n async #run(runner) {\n return await runner(this.#connection);\n }\n}\n", "/// \nexport const TRANSACTION_ACCESS_MODES = ['read only', 'read write'];\nexport const TRANSACTION_ISOLATION_LEVELS = [\n 'read uncommitted',\n 'read committed',\n 'repeatable read',\n 'serializable',\n 'snapshot',\n];\nexport function validateTransactionSettings(settings) {\n if (settings.accessMode &&\n !TRANSACTION_ACCESS_MODES.includes(settings.accessMode)) {\n throw new Error(`invalid transaction access mode ${settings.accessMode}`);\n }\n if (settings.isolationLevel &&\n !TRANSACTION_ISOLATION_LEVELS.includes(settings.isolationLevel)) {\n throw new Error(`invalid transaction isolation level ${settings.isolationLevel}`);\n }\n}\n", "/// \nimport { freeze, isFunction } from './object-utils.js';\nconst logLevels = ['query', 'error'];\nexport const LOG_LEVELS = freeze(logLevels);\nexport class Log {\n #levels;\n #logger;\n constructor(config) {\n if (isFunction(config)) {\n this.#logger = config;\n this.#levels = freeze({\n query: true,\n error: true,\n });\n }\n else {\n this.#logger = defaultLogger;\n this.#levels = freeze({\n query: config.includes('query'),\n error: config.includes('error'),\n });\n }\n }\n isLevelEnabled(level) {\n return this.#levels[level];\n }\n async query(getEvent) {\n if (this.#levels.query) {\n await this.#logger(getEvent());\n }\n }\n async error(getEvent) {\n if (this.#levels.error) {\n await this.#logger(getEvent());\n }\n }\n}\nfunction defaultLogger(event) {\n if (event.level === 'query') {\n const prefix = `kysely:query:${event.isStream ? 'stream:' : ''}`;\n console.log(`${prefix} ${event.query.sql}`);\n console.log(`${prefix} duration: ${event.queryDurationMillis.toFixed(1)}ms`);\n }\n else if (event.level === 'error') {\n if (event.error instanceof Error) {\n console.error(`kysely:error: ${event.error.stack ?? event.error.message}`);\n }\n else {\n console.error(`kysely:error: ${JSON.stringify({\n error: event.error,\n query: event.query.sql,\n queryDurationMillis: event.queryDurationMillis,\n })}`);\n }\n }\n}\n", "/// \nimport { isFunction, isObject } from './object-utils.js';\nexport function isCompilable(value) {\n return isObject(value) && isFunction(value.compile);\n}\n", "/// \nimport { SchemaModule } from './schema/schema.js';\nimport { DynamicModule } from './dynamic/dynamic.js';\nimport { DefaultConnectionProvider } from './driver/default-connection-provider.js';\nimport { QueryCreator } from './query-creator.js';\nimport { DefaultQueryExecutor } from './query-executor/default-query-executor.js';\nimport { freeze, isObject, isUndefined } from './util/object-utils.js';\nimport { RuntimeDriver } from './driver/runtime-driver.js';\nimport { SingleConnectionProvider } from './driver/single-connection-provider.js';\nimport { validateTransactionSettings, } from './driver/driver.js';\nimport { createFunctionModule, } from './query-builder/function-module.js';\nimport { Log } from './util/log.js';\nimport { createQueryId } from './util/query-id.js';\nimport { isCompilable } from './util/compilable.js';\nimport { CaseBuilder } from './query-builder/case-builder.js';\nimport { CaseNode } from './operation-node/case-node.js';\nimport { parseExpression } from './parser/expression-parser.js';\nimport { WithSchemaPlugin } from './plugin/with-schema/with-schema-plugin.js';\nimport { provideControlledConnection, } from './util/provide-controlled-connection.js';\nimport { logOnce } from './util/log-once.js';\n// @ts-ignore\nSymbol.asyncDispose ??= Symbol('Symbol.asyncDispose');\n/**\n * The main Kysely class.\n *\n * You should create one instance of `Kysely` per database using the {@link Kysely}\n * constructor. Each `Kysely` instance maintains its own connection pool.\n *\n * ### Examples\n *\n * This example assumes your database has a \"person\" table:\n *\n * ```ts\n * import * as Sqlite from 'better-sqlite3'\n * import {\u00A0type Generated, Kysely, SqliteDialect } from 'kysely'\n *\n * interface Database {\n * person: {\n * id: Generated\n * first_name: string\n * last_name: string | null\n * }\n * }\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * })\n * })\n * ```\n *\n * @typeParam DB - The database interface type. Keys of this type must be table names\n * in the database and values must be interfaces that describe the rows in those\n * tables. See the examples above.\n */\nexport class Kysely extends QueryCreator {\n #props;\n constructor(args) {\n let superProps;\n let props;\n if (isKyselyProps(args)) {\n superProps = { executor: args.executor };\n props = { ...args };\n }\n else {\n const dialect = args.dialect;\n const driver = dialect.createDriver();\n const compiler = dialect.createQueryCompiler();\n const adapter = dialect.createAdapter();\n const log = new Log(args.log ?? []);\n const runtimeDriver = new RuntimeDriver(driver, log);\n const connectionProvider = new DefaultConnectionProvider(runtimeDriver);\n const executor = new DefaultQueryExecutor(compiler, adapter, connectionProvider, args.plugins ?? []);\n superProps = { executor };\n props = {\n config: args,\n executor,\n dialect,\n driver: runtimeDriver,\n };\n }\n super(superProps);\n this.#props = freeze(props);\n }\n /**\n * Returns the {@link SchemaModule} module for building database schema.\n */\n get schema() {\n return new SchemaModule(this.#props.executor);\n }\n /**\n * Returns a the {@link DynamicModule} module.\n *\n * The {@link DynamicModule} module can be used to bypass strict typing and\n * passing in dynamic values for the queries.\n */\n get dynamic() {\n return new DynamicModule();\n }\n /**\n * Returns a {@link DatabaseIntrospector | database introspector}.\n */\n get introspection() {\n return this.#props.dialect.createIntrospector(this.withoutPlugins());\n }\n case(value) {\n return new CaseBuilder({\n node: CaseNode.create(isUndefined(value) ? undefined : parseExpression(value)),\n });\n }\n /**\n * Returns a {@link FunctionModule} that can be used to write somewhat type-safe function\n * calls.\n *\n * ```ts\n * const { count } = db.fn\n *\n * await db.selectFrom('person')\n * .innerJoin('pet', 'pet.owner_id', 'person.id')\n * .select([\n * 'id',\n * count('pet.id').as('person_count'),\n * ])\n * .groupBy('person.id')\n * .having(count('pet.id'), '>', 10)\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"person\".\"id\", count(\"pet\".\"id\") as \"person_count\"\n * from \"person\"\n * inner join \"pet\" on \"pet\".\"owner_id\" = \"person\".\"id\"\n * group by \"person\".\"id\"\n * having count(\"pet\".\"id\") > $1\n * ```\n *\n * Why \"somewhat\" type-safe? Because the function calls are not bound to the\n * current query context. They allow you to reference columns and tables that\n * are not in the current query. E.g. remove the `innerJoin` from the previous\n * query and TypeScript won't even complain.\n *\n * If you want to make the function calls fully type-safe, you can use the\n * {@link ExpressionBuilder.fn} getter for a query context-aware, stricter {@link FunctionModule}.\n *\n * ```ts\n * await db.selectFrom('person')\n * .innerJoin('pet', 'pet.owner_id', 'person.id')\n * .select((eb) => [\n * 'person.id',\n * eb.fn.count('pet.id').as('pet_count')\n * ])\n * .groupBy('person.id')\n * .having((eb) => eb.fn.count('pet.id'), '>', 10)\n * .execute()\n * ```\n */\n get fn() {\n return createFunctionModule();\n }\n /**\n * Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction.\n *\n * The returned {@link TransactionBuilder} can be used to configure the transaction. The\n * {@link TransactionBuilder.execute} method can then be called to run the transaction.\n * {@link TransactionBuilder.execute} takes a function that is run inside the\n * transaction. If the function throws an exception,\n * 1. the exception is caught,\n * 2. the transaction is rolled back, and\n * 3. the exception is thrown again.\n * Otherwise the transaction is committed.\n *\n * The callback function passed to the {@link TransactionBuilder.execute | execute}\n * method gets the transaction object as its only argument. The transaction is\n * of type {@link Transaction} which inherits {@link Kysely}. Any query\n * started through the transaction object is executed inside the transaction.\n *\n * To run a controlled transaction, allowing you to commit and rollback manually,\n * use {@link startTransaction} instead.\n *\n * ### Examples\n *\n * \n *\n * This example inserts two rows in a transaction. If an exception is thrown inside\n * the callback passed to the `execute` method,\n * 1. the exception is caught,\n * 2. the transaction is rolled back, and\n * 3. the exception is thrown again.\n * Otherwise the transaction is committed.\n *\n * ```ts\n * const catto = await db.transaction().execute(async (trx) => {\n * const jennifer = await trx.insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n *\n * return await trx.insertInto('pet')\n * .values({\n * owner_id: jennifer.id,\n * name: 'Catto',\n * species: 'cat',\n * is_favorite: false,\n * })\n * .returningAll()\n * .executeTakeFirst()\n * })\n * ```\n *\n * Setting the isolation level:\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n *\n * await db\n * .transaction()\n * .setIsolationLevel('serializable')\n * .execute(async (trx) => {\n * await doStuff(trx)\n * })\n *\n * async function doStuff(kysely: typeof db) {\n * // ...\n * }\n * ```\n */\n transaction() {\n return new TransactionBuilder({ ...this.#props });\n }\n /**\n * Creates a {@link ControlledTransactionBuilder} that can be used to run queries inside a controlled transaction.\n *\n * The returned {@link ControlledTransactionBuilder} can be used to configure the transaction.\n * The {@link ControlledTransactionBuilder.execute} method can then be called\n * to start the transaction and return a {@link ControlledTransaction}.\n *\n * A {@link ControlledTransaction} allows you to commit and rollback manually,\n * execute savepoint commands. It extends {@link Transaction} which extends {@link Kysely},\n * so you can run queries inside the transaction. Once the transaction is committed,\n * or rolled back, it can't be used anymore - all queries will throw an error.\n * This is to prevent accidentally running queries outside the transaction - where\n * atomicity is not guaranteed anymore.\n *\n * ### Examples\n *\n * \n *\n * A controlled transaction allows you to commit and rollback manually, execute\n * savepoint commands, and queries in general.\n *\n * In this example we start a transaction, use it to insert two rows and then commit\n * the transaction. If an error is thrown, we catch it and rollback the transaction.\n *\n * ```ts\n * const trx = await db.startTransaction().execute()\n *\n * try {\n * const jennifer = await trx.insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n *\n * const catto = await trx.insertInto('pet')\n * .values({\n * owner_id: jennifer.id,\n * name: 'Catto',\n * species: 'cat',\n * is_favorite: false,\n * })\n * .returningAll()\n * .executeTakeFirstOrThrow()\n *\n * await trx.commit().execute()\n *\n * // ...\n * } catch (error) {\n * await trx.rollback().execute()\n * }\n * ```\n *\n * \n *\n * A controlled transaction allows you to commit and rollback manually, execute\n * savepoint commands, and queries in general.\n *\n * In this example we start a transaction, insert a person, create a savepoint,\n * try inserting a toy and a pet, and if an error is thrown, we rollback to the\n * savepoint. Eventually we release the savepoint, insert an audit record and\n * commit the transaction. If an error is thrown, we catch it and rollback the\n * transaction.\n *\n * ```ts\n * const trx = await db.startTransaction().execute()\n *\n * try {\n * const jennifer = await trx\n * .insertInto('person')\n * .values({\n * first_name: 'Jennifer',\n * last_name: 'Aniston',\n * age: 40,\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n *\n * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()\n *\n * try {\n * const catto = await trxAfterJennifer\n * .insertInto('pet')\n * .values({\n * owner_id: jennifer.id,\n * name: 'Catto',\n * species: 'cat',\n * })\n * .returning('id')\n * .executeTakeFirstOrThrow()\n *\n * await trxAfterJennifer\n * .insertInto('toy')\n * .values({ name: 'Bone', price: 1.99, pet_id: catto.id })\n * .execute()\n * } catch (error) {\n * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()\n * }\n *\n * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute()\n *\n * await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute()\n *\n * await trx.commit().execute()\n * } catch (error) {\n * await trx.rollback().execute()\n * }\n * ```\n */\n startTransaction() {\n return new ControlledTransactionBuilder({ ...this.#props });\n }\n /**\n * Provides a kysely instance bound to a single database connection.\n *\n * ### Examples\n *\n * ```ts\n * await db\n * .connection()\n * .execute(async (db) => {\n * // `db` is an instance of `Kysely` that's bound to a single\n * // database connection. All queries executed through `db` use\n * // the same connection.\n * await doStuff(db)\n * })\n *\n * async function doStuff(kysely: typeof db) {\n * // ...\n * }\n * ```\n */\n connection() {\n return new ConnectionBuilder({ ...this.#props });\n }\n /**\n * Returns a copy of this Kysely instance with the given plugin installed.\n */\n withPlugin(plugin) {\n return new Kysely({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n /**\n * Returns a copy of this Kysely instance without any plugins.\n */\n withoutPlugins() {\n return new Kysely({\n ...this.#props,\n executor: this.#props.executor.withoutPlugins(),\n });\n }\n /**\n * @override\n */\n withSchema(schema) {\n return new Kysely({\n ...this.#props,\n executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema)),\n });\n }\n /**\n * Returns a copy of this Kysely instance with tables added to its\n * database type.\n *\n * This method only modifies the types and doesn't affect any of the\n * executed queries in any way.\n *\n * ### Examples\n *\n * The following example adds and uses a temporary table:\n *\n * ```ts\n * await db.schema\n * .createTable('temp_table')\n * .temporary()\n * .addColumn('some_column', 'integer')\n * .execute()\n *\n * const tempDb = db.withTables<{\n * temp_table: {\n * some_column: number\n * }\n * }>()\n *\n * await tempDb\n * .insertInto('temp_table')\n * .values({ some_column: 100 })\n * .execute()\n * ```\n */\n withTables() {\n return new Kysely({ ...this.#props });\n }\n /**\n * Releases all resources and disconnects from the database.\n *\n * You need to call this when you are done using the `Kysely` instance.\n */\n async destroy() {\n await this.#props.driver.destroy();\n }\n /**\n * Returns true if this `Kysely` instance is a transaction.\n *\n * You can also use `db instanceof Transaction`.\n */\n get isTransaction() {\n return false;\n }\n /**\n * @internal\n * @private\n */\n getExecutor() {\n return this.#props.executor;\n }\n /**\n * Executes a given compiled query or query builder.\n *\n * See {@link https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0004-splitting-query-building-and-execution.md#execute-compiled-queries splitting build, compile and execute code recipe} for more information.\n */\n executeQuery(query, \n // TODO: remove this in the future. deprecated in 0.28.x\n queryId) {\n if (queryId !== undefined) {\n logOnce('Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.');\n }\n const compiledQuery = isCompilable(query) ? query.compile() : query;\n return this.getExecutor().executeQuery(compiledQuery);\n }\n async [Symbol.asyncDispose]() {\n await this.destroy();\n }\n}\nexport class Transaction extends Kysely {\n #props;\n constructor(props) {\n super(props);\n this.#props = props;\n }\n // The return type is `true` instead of `boolean` to make Kysely\n // unassignable to Transaction while allowing assignment the\n // other way around.\n get isTransaction() {\n return true;\n }\n transaction() {\n throw new Error('calling the transaction method for a Transaction is not supported');\n }\n connection() {\n throw new Error('calling the connection method for a Transaction is not supported');\n }\n async destroy() {\n throw new Error('calling the destroy method for a Transaction is not supported');\n }\n withPlugin(plugin) {\n return new Transaction({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n withoutPlugins() {\n return new Transaction({\n ...this.#props,\n executor: this.#props.executor.withoutPlugins(),\n });\n }\n withSchema(schema) {\n return new Transaction({\n ...this.#props,\n executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema)),\n });\n }\n withTables() {\n return new Transaction({ ...this.#props });\n }\n}\nexport function isKyselyProps(obj) {\n return (isObject(obj) &&\n isObject(obj.config) &&\n isObject(obj.driver) &&\n isObject(obj.executor) &&\n isObject(obj.dialect));\n}\nexport class ConnectionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n async execute(callback) {\n return this.#props.executor.provideConnection(async (connection) => {\n const executor = this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection));\n const db = new Kysely({\n ...this.#props,\n executor,\n });\n return await callback(db);\n });\n }\n}\nexport class TransactionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n setAccessMode(accessMode) {\n return new TransactionBuilder({\n ...this.#props,\n accessMode,\n });\n }\n setIsolationLevel(isolationLevel) {\n return new TransactionBuilder({\n ...this.#props,\n isolationLevel,\n });\n }\n async execute(callback) {\n const { isolationLevel, accessMode, ...kyselyProps } = this.#props;\n const settings = { isolationLevel, accessMode };\n validateTransactionSettings(settings);\n return this.#props.executor.provideConnection(async (connection) => {\n const state = { isCommitted: false, isRolledBack: false };\n const executor = new NotCommittedOrRolledBackAssertingExecutor(this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection)), state);\n const transaction = new Transaction({\n ...kyselyProps,\n executor,\n });\n let transactionBegun = false;\n try {\n await this.#props.driver.beginTransaction(connection, settings);\n transactionBegun = true;\n const result = await callback(transaction);\n await this.#props.driver.commitTransaction(connection);\n state.isCommitted = true;\n return result;\n }\n catch (error) {\n if (transactionBegun) {\n await this.#props.driver.rollbackTransaction(connection);\n state.isRolledBack = true;\n }\n throw error;\n }\n });\n }\n}\nexport class ControlledTransactionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n setAccessMode(accessMode) {\n return new ControlledTransactionBuilder({\n ...this.#props,\n accessMode,\n });\n }\n setIsolationLevel(isolationLevel) {\n return new ControlledTransactionBuilder({\n ...this.#props,\n isolationLevel,\n });\n }\n async execute() {\n const { isolationLevel, accessMode, ...props } = this.#props;\n const settings = { isolationLevel, accessMode };\n validateTransactionSettings(settings);\n const connection = await provideControlledConnection(this.#props.executor);\n await this.#props.driver.beginTransaction(connection.connection, settings);\n return new ControlledTransaction({\n ...props,\n connection,\n executor: this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection.connection)),\n });\n }\n}\nexport class ControlledTransaction extends Transaction {\n #props;\n #compileQuery;\n #state;\n constructor(props) {\n const state = { isCommitted: false, isRolledBack: false };\n props = {\n ...props,\n executor: new NotCommittedOrRolledBackAssertingExecutor(props.executor, state),\n };\n const { connection, ...transactionProps } = props;\n super(transactionProps);\n this.#props = freeze(props);\n this.#state = state;\n const queryId = createQueryId();\n this.#compileQuery = (node) => props.executor.compileQuery(node, queryId);\n }\n get isCommitted() {\n return this.#state.isCommitted;\n }\n get isRolledBack() {\n return this.#state.isRolledBack;\n }\n /**\n * Commits the transaction.\n *\n * See {@link rollback}.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * try {\n * await doSomething(trx)\n *\n * await trx.commit().execute()\n * } catch (error) {\n * await trx.rollback().execute()\n * }\n *\n * async function doSomething(kysely: Kysely) {}\n * ```\n */\n commit() {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.commitTransaction(this.#props.connection.connection);\n this.#state.isCommitted = true;\n this.#props.connection.release();\n });\n }\n /**\n * Rolls back the transaction.\n *\n * See {@link commit} and {@link rollbackToSavepoint}.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * try {\n * await doSomething(trx)\n *\n * await trx.commit().execute()\n * } catch (error) {\n * await trx.rollback().execute()\n * }\n *\n * async function doSomething(kysely: Kysely) {}\n * ```\n */\n rollback() {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.rollbackTransaction(this.#props.connection.connection);\n this.#state.isRolledBack = true;\n this.#props.connection.release();\n });\n }\n /**\n * Creates a savepoint with a given name.\n *\n * See {@link rollbackToSavepoint} and {@link releaseSavepoint}.\n *\n * For a type-safe experience, you should use the returned instance from now on.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * await insertJennifer(trx)\n *\n * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()\n *\n * try {\n * await doSomething(trxAfterJennifer)\n * } catch (error) {\n * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()\n * }\n *\n * async function insertJennifer(kysely: Kysely) {}\n * async function doSomething(kysely: Kysely) {}\n * ```\n */\n savepoint(savepointName) {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.savepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);\n return new ControlledTransaction({ ...this.#props });\n });\n }\n /**\n * Rolls back to a savepoint with a given name.\n *\n * See {@link savepoint} and {@link releaseSavepoint}.\n *\n * You must use the same instance returned by {@link savepoint}, or\n * escape the type-check by using `as any`.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * await insertJennifer(trx)\n *\n * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()\n *\n * try {\n * await doSomething(trxAfterJennifer)\n * } catch (error) {\n * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()\n * }\n *\n * async function insertJennifer(kysely: Kysely) {}\n * async function doSomething(kysely: Kysely) {}\n * ```\n */\n rollbackToSavepoint(savepointName) {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.rollbackToSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);\n return new ControlledTransaction({ ...this.#props });\n });\n }\n /**\n * Releases a savepoint with a given name.\n *\n * See {@link savepoint} and {@link rollbackToSavepoint}.\n *\n * You must use the same instance returned by {@link savepoint}, or\n * escape the type-check by using `as any`.\n *\n * ### Examples\n *\n * ```ts\n * import type { Kysely } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const trx = await db.startTransaction().execute()\n *\n * await insertJennifer(trx)\n *\n * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()\n *\n * try {\n * await doSomething(trxAfterJennifer)\n * } catch (error) {\n * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()\n * }\n *\n * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute()\n *\n * await doSomethingElse(trx)\n *\n * async function insertJennifer(kysely: Kysely) {}\n * async function doSomething(kysely: Kysely) {}\n * async function doSomethingElse(kysely: Kysely) {}\n * ```\n */\n releaseSavepoint(savepointName) {\n assertNotCommittedOrRolledBack(this.#state);\n return new Command(async () => {\n await this.#props.driver.releaseSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);\n return new ControlledTransaction({ ...this.#props });\n });\n }\n withPlugin(plugin) {\n return new ControlledTransaction({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n withoutPlugins() {\n return new ControlledTransaction({\n ...this.#props,\n executor: this.#props.executor.withoutPlugins(),\n });\n }\n withSchema(schema) {\n return new ControlledTransaction({\n ...this.#props,\n executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema)),\n });\n }\n withTables() {\n return new ControlledTransaction({ ...this.#props });\n }\n}\nexport class Command {\n #cb;\n constructor(cb) {\n this.#cb = cb;\n }\n /**\n * Executes the command.\n */\n async execute() {\n return await this.#cb();\n }\n}\nfunction assertNotCommittedOrRolledBack(state) {\n if (state.isCommitted) {\n throw new Error('Transaction is already committed');\n }\n if (state.isRolledBack) {\n throw new Error('Transaction is already rolled back');\n }\n}\n/**\n * An executor wrapper that asserts that the transaction state is not committed\n * or rolled back when a query is executed.\n *\n * @internal\n */\nclass NotCommittedOrRolledBackAssertingExecutor {\n #executor;\n #state;\n constructor(executor, state) {\n if (executor instanceof NotCommittedOrRolledBackAssertingExecutor) {\n this.#executor = executor.#executor;\n }\n else {\n this.#executor = executor;\n }\n this.#state = state;\n }\n get adapter() {\n return this.#executor.adapter;\n }\n get plugins() {\n return this.#executor.plugins;\n }\n transformQuery(node, queryId) {\n return this.#executor.transformQuery(node, queryId);\n }\n compileQuery(node, queryId) {\n return this.#executor.compileQuery(node, queryId);\n }\n provideConnection(consumer) {\n return this.#executor.provideConnection(consumer);\n }\n executeQuery(compiledQuery) {\n assertNotCommittedOrRolledBack(this.#state);\n return this.#executor.executeQuery(compiledQuery);\n }\n stream(compiledQuery, chunkSize) {\n assertNotCommittedOrRolledBack(this.#state);\n return this.#executor.stream(compiledQuery, chunkSize);\n }\n withConnectionProvider(connectionProvider) {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withConnectionProvider(connectionProvider), this.#state);\n }\n withPlugin(plugin) {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugin(plugin), this.#state);\n }\n withPlugins(plugins) {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugins(plugins), this.#state);\n }\n withPluginAtFront(plugin) {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPluginAtFront(plugin), this.#state);\n }\n withoutPlugins() {\n return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withoutPlugins(), this.#state);\n }\n}\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nclass RawBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isRawBuilder() {\n return true;\n }\n as(alias) {\n return new AliasedRawBuilderImpl(this, alias);\n }\n $castTo() {\n return new RawBuilderImpl({ ...this.#props });\n }\n $notNull() {\n return new RawBuilderImpl(this.#props);\n }\n withPlugin(plugin) {\n return new RawBuilderImpl({\n ...this.#props,\n plugins: this.#props.plugins !== undefined\n ? freeze([...this.#props.plugins, plugin])\n : freeze([plugin]),\n });\n }\n toOperationNode() {\n return this.#toOperationNode(this.#getExecutor());\n }\n compile(executorProvider) {\n return this.#compile(this.#getExecutor(executorProvider));\n }\n async execute(executorProvider) {\n const executor = this.#getExecutor(executorProvider);\n return executor.executeQuery(this.#compile(executor));\n }\n #getExecutor(executorProvider) {\n const executor = executorProvider !== undefined\n ? executorProvider.getExecutor()\n : NOOP_QUERY_EXECUTOR;\n return this.#props.plugins !== undefined\n ? executor.withPlugins(this.#props.plugins)\n : executor;\n }\n #toOperationNode(executor) {\n return executor.transformQuery(this.#props.rawNode, this.#props.queryId);\n }\n #compile(executor) {\n return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId);\n }\n}\nexport function createRawBuilder(props) {\n return new RawBuilderImpl(props);\n}\nclass AliasedRawBuilderImpl {\n #rawBuilder;\n #alias;\n constructor(rawBuilder, alias) {\n this.#rawBuilder = rawBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#rawBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get rawBuilder() {\n return this.#rawBuilder;\n }\n toOperationNode() {\n return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n", "/// \nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { parseStringReference } from '../parser/reference-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseValueExpression } from '../parser/value-parser.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createRawBuilder } from './raw-builder.js';\nexport const sql = Object.assign((sqlFragments, ...parameters) => {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []),\n });\n}, {\n ref(columnReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseStringReference(columnReference)),\n });\n },\n val(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseValueExpression(value)),\n });\n },\n value(value) {\n return this.val(value);\n },\n table(tableReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseTable(tableReference)),\n });\n },\n id(...ids) {\n const fragments = new Array(ids.length + 1).fill('.');\n fragments[0] = '';\n fragments[fragments.length - 1] = '';\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)),\n });\n },\n lit(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)),\n });\n },\n literal(value) {\n return this.lit(value);\n },\n raw(sql) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithSql(sql),\n });\n },\n join(array, separator = sql `, `) {\n const nodes = new Array(Math.max(2 * array.length - 1, 0));\n const sep = separator.toOperationNode();\n for (let i = 0; i < array.length; ++i) {\n nodes[2 * i] = parseParameter(array[i]);\n if (i !== array.length - 1) {\n nodes[2 * i + 1] = sep;\n }\n }\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChildren(nodes),\n });\n },\n});\nfunction parseParameter(param) {\n if (isOperationNodeSource(param)) {\n return param.toOperationNode();\n }\n return parseValueExpression(param);\n}\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nimport { freeze } from '../util/object-utils.js';\nexport class OperationNodeVisitor {\n nodeStack = [];\n get parentNode() {\n return this.nodeStack[this.nodeStack.length - 2];\n }\n #visitors = freeze({\n AliasNode: this.visitAlias.bind(this),\n ColumnNode: this.visitColumn.bind(this),\n IdentifierNode: this.visitIdentifier.bind(this),\n SchemableIdentifierNode: this.visitSchemableIdentifier.bind(this),\n RawNode: this.visitRaw.bind(this),\n ReferenceNode: this.visitReference.bind(this),\n SelectQueryNode: this.visitSelectQuery.bind(this),\n SelectionNode: this.visitSelection.bind(this),\n TableNode: this.visitTable.bind(this),\n FromNode: this.visitFrom.bind(this),\n SelectAllNode: this.visitSelectAll.bind(this),\n AndNode: this.visitAnd.bind(this),\n OrNode: this.visitOr.bind(this),\n ValueNode: this.visitValue.bind(this),\n ValueListNode: this.visitValueList.bind(this),\n PrimitiveValueListNode: this.visitPrimitiveValueList.bind(this),\n ParensNode: this.visitParens.bind(this),\n JoinNode: this.visitJoin.bind(this),\n OperatorNode: this.visitOperator.bind(this),\n WhereNode: this.visitWhere.bind(this),\n InsertQueryNode: this.visitInsertQuery.bind(this),\n DeleteQueryNode: this.visitDeleteQuery.bind(this),\n ReturningNode: this.visitReturning.bind(this),\n CreateTableNode: this.visitCreateTable.bind(this),\n AddColumnNode: this.visitAddColumn.bind(this),\n ColumnDefinitionNode: this.visitColumnDefinition.bind(this),\n DropTableNode: this.visitDropTable.bind(this),\n DataTypeNode: this.visitDataType.bind(this),\n OrderByNode: this.visitOrderBy.bind(this),\n OrderByItemNode: this.visitOrderByItem.bind(this),\n GroupByNode: this.visitGroupBy.bind(this),\n GroupByItemNode: this.visitGroupByItem.bind(this),\n UpdateQueryNode: this.visitUpdateQuery.bind(this),\n ColumnUpdateNode: this.visitColumnUpdate.bind(this),\n LimitNode: this.visitLimit.bind(this),\n OffsetNode: this.visitOffset.bind(this),\n OnConflictNode: this.visitOnConflict.bind(this),\n OnDuplicateKeyNode: this.visitOnDuplicateKey.bind(this),\n CreateIndexNode: this.visitCreateIndex.bind(this),\n DropIndexNode: this.visitDropIndex.bind(this),\n ListNode: this.visitList.bind(this),\n PrimaryKeyConstraintNode: this.visitPrimaryKeyConstraint.bind(this),\n UniqueConstraintNode: this.visitUniqueConstraint.bind(this),\n ReferencesNode: this.visitReferences.bind(this),\n CheckConstraintNode: this.visitCheckConstraint.bind(this),\n WithNode: this.visitWith.bind(this),\n CommonTableExpressionNode: this.visitCommonTableExpression.bind(this),\n CommonTableExpressionNameNode: this.visitCommonTableExpressionName.bind(this),\n HavingNode: this.visitHaving.bind(this),\n CreateSchemaNode: this.visitCreateSchema.bind(this),\n DropSchemaNode: this.visitDropSchema.bind(this),\n AlterTableNode: this.visitAlterTable.bind(this),\n DropColumnNode: this.visitDropColumn.bind(this),\n RenameColumnNode: this.visitRenameColumn.bind(this),\n AlterColumnNode: this.visitAlterColumn.bind(this),\n ModifyColumnNode: this.visitModifyColumn.bind(this),\n AddConstraintNode: this.visitAddConstraint.bind(this),\n DropConstraintNode: this.visitDropConstraint.bind(this),\n RenameConstraintNode: this.visitRenameConstraint.bind(this),\n ForeignKeyConstraintNode: this.visitForeignKeyConstraint.bind(this),\n CreateViewNode: this.visitCreateView.bind(this),\n RefreshMaterializedViewNode: this.visitRefreshMaterializedView.bind(this),\n DropViewNode: this.visitDropView.bind(this),\n GeneratedNode: this.visitGenerated.bind(this),\n DefaultValueNode: this.visitDefaultValue.bind(this),\n OnNode: this.visitOn.bind(this),\n ValuesNode: this.visitValues.bind(this),\n SelectModifierNode: this.visitSelectModifier.bind(this),\n CreateTypeNode: this.visitCreateType.bind(this),\n DropTypeNode: this.visitDropType.bind(this),\n ExplainNode: this.visitExplain.bind(this),\n DefaultInsertValueNode: this.visitDefaultInsertValue.bind(this),\n AggregateFunctionNode: this.visitAggregateFunction.bind(this),\n OverNode: this.visitOver.bind(this),\n PartitionByNode: this.visitPartitionBy.bind(this),\n PartitionByItemNode: this.visitPartitionByItem.bind(this),\n SetOperationNode: this.visitSetOperation.bind(this),\n BinaryOperationNode: this.visitBinaryOperation.bind(this),\n UnaryOperationNode: this.visitUnaryOperation.bind(this),\n UsingNode: this.visitUsing.bind(this),\n FunctionNode: this.visitFunction.bind(this),\n CaseNode: this.visitCase.bind(this),\n WhenNode: this.visitWhen.bind(this),\n JSONReferenceNode: this.visitJSONReference.bind(this),\n JSONPathNode: this.visitJSONPath.bind(this),\n JSONPathLegNode: this.visitJSONPathLeg.bind(this),\n JSONOperatorChainNode: this.visitJSONOperatorChain.bind(this),\n TupleNode: this.visitTuple.bind(this),\n MergeQueryNode: this.visitMergeQuery.bind(this),\n MatchedNode: this.visitMatched.bind(this),\n AddIndexNode: this.visitAddIndex.bind(this),\n CastNode: this.visitCast.bind(this),\n FetchNode: this.visitFetch.bind(this),\n TopNode: this.visitTop.bind(this),\n OutputNode: this.visitOutput.bind(this),\n OrActionNode: this.visitOrAction.bind(this),\n CollateNode: this.visitCollate.bind(this),\n });\n visitNode = (node) => {\n this.nodeStack.push(node);\n this.#visitors[node.kind](node);\n this.nodeStack.pop();\n };\n}\n", "/// \nimport { CreateTableNode } from '../operation-node/create-table-node.js';\nimport { InsertQueryNode } from '../operation-node/insert-query-node.js';\nimport { OperationNodeVisitor } from '../operation-node/operation-node-visitor.js';\nimport { OperatorNode } from '../operation-node/operator-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze, isString, isNumber, isBoolean, isNull, isDate, isBigInt, } from '../util/object-utils.js';\nimport { CreateViewNode } from '../operation-node/create-view-node.js';\nimport { SetOperationNode } from '../operation-node/set-operation-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { logOnce } from '../util/log-once.js';\nconst LIT_WRAP_REGEX = /'/g;\nexport class DefaultQueryCompiler extends OperationNodeVisitor {\n #sql = '';\n #parameters = [];\n get numParameters() {\n return this.#parameters.length;\n }\n compileQuery(node, queryId) {\n this.#sql = '';\n this.#parameters = [];\n this.nodeStack.splice(0, this.nodeStack.length);\n this.visitNode(node);\n return freeze({\n query: node,\n queryId,\n sql: this.getSql(),\n parameters: [...this.#parameters],\n });\n }\n getSql() {\n return this.#sql;\n }\n visitSelectQuery(node) {\n const wrapInParens = this.parentNode !== undefined &&\n !ParensNode.is(this.parentNode) &&\n !InsertQueryNode.is(this.parentNode) &&\n !CreateTableNode.is(this.parentNode) &&\n !CreateViewNode.is(this.parentNode) &&\n !SetOperationNode.is(this.parentNode);\n if (this.parentNode === undefined && node.explain) {\n this.visitNode(node.explain);\n this.append(' ');\n }\n if (wrapInParens) {\n this.append('(');\n }\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append('select');\n if (node.distinctOn) {\n this.append(' ');\n this.compileDistinctOn(node.distinctOn);\n }\n if (node.frontModifiers?.length) {\n this.append(' ');\n this.compileList(node.frontModifiers, ' ');\n }\n if (node.top) {\n this.append(' ');\n this.visitNode(node.top);\n }\n if (node.selections) {\n this.append(' ');\n this.compileList(node.selections);\n }\n if (node.from) {\n this.append(' ');\n this.visitNode(node.from);\n }\n if (node.joins) {\n this.append(' ');\n this.compileList(node.joins, ' ');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n if (node.groupBy) {\n this.append(' ');\n this.visitNode(node.groupBy);\n }\n if (node.having) {\n this.append(' ');\n this.visitNode(node.having);\n }\n if (node.setOperations) {\n this.append(' ');\n this.compileList(node.setOperations, ' ');\n }\n if (node.orderBy) {\n this.append(' ');\n this.visitNode(node.orderBy);\n }\n if (node.limit) {\n this.append(' ');\n this.visitNode(node.limit);\n }\n if (node.offset) {\n this.append(' ');\n this.visitNode(node.offset);\n }\n if (node.fetch) {\n this.append(' ');\n this.visitNode(node.fetch);\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(this.sortSelectModifiers([...node.endModifiers]), ' ');\n }\n if (wrapInParens) {\n this.append(')');\n }\n }\n visitFrom(node) {\n this.append('from ');\n this.compileList(node.froms);\n }\n visitSelection(node) {\n this.visitNode(node.selection);\n }\n visitColumn(node) {\n this.visitNode(node.column);\n }\n compileDistinctOn(expressions) {\n this.append('distinct on (');\n this.compileList(expressions);\n this.append(')');\n }\n compileList(nodes, separator = ', ') {\n const lastIndex = nodes.length - 1;\n for (let i = 0; i <= lastIndex; i++) {\n this.visitNode(nodes[i]);\n if (i < lastIndex) {\n this.append(separator);\n }\n }\n }\n visitWhere(node) {\n this.append('where ');\n this.visitNode(node.where);\n }\n visitHaving(node) {\n this.append('having ');\n this.visitNode(node.having);\n }\n visitInsertQuery(node) {\n const wrapInParens = this.parentNode !== undefined &&\n !ParensNode.is(this.parentNode) &&\n !RawNode.is(this.parentNode) &&\n !WhenNode.is(this.parentNode);\n if (this.parentNode === undefined && node.explain) {\n this.visitNode(node.explain);\n this.append(' ');\n }\n if (wrapInParens) {\n this.append('(');\n }\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append(node.replace ? 'replace' : 'insert');\n // TODO: remove in 0.29.\n if (node.ignore) {\n logOnce('`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead.');\n this.append(' ignore');\n }\n if (node.orAction) {\n this.append(' ');\n this.visitNode(node.orAction);\n }\n if (node.top) {\n this.append(' ');\n this.visitNode(node.top);\n }\n if (node.into) {\n this.append(' into ');\n this.visitNode(node.into);\n }\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n if (node.output) {\n this.append(' ');\n this.visitNode(node.output);\n }\n if (node.values) {\n this.append(' ');\n this.visitNode(node.values);\n }\n if (node.defaultValues) {\n this.append(' ');\n this.append('default values');\n }\n if (node.onConflict) {\n this.append(' ');\n this.visitNode(node.onConflict);\n }\n if (node.onDuplicateKey) {\n this.append(' ');\n this.visitNode(node.onDuplicateKey);\n }\n if (node.returning) {\n this.append(' ');\n this.visitNode(node.returning);\n }\n if (wrapInParens) {\n this.append(')');\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n visitValues(node) {\n this.append('values ');\n this.compileList(node.values);\n }\n visitDeleteQuery(node) {\n const wrapInParens = this.parentNode !== undefined &&\n !ParensNode.is(this.parentNode) &&\n !RawNode.is(this.parentNode);\n if (this.parentNode === undefined && node.explain) {\n this.visitNode(node.explain);\n this.append(' ');\n }\n if (wrapInParens) {\n this.append('(');\n }\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append('delete ');\n if (node.top) {\n this.visitNode(node.top);\n this.append(' ');\n }\n this.visitNode(node.from);\n if (node.output) {\n this.append(' ');\n this.visitNode(node.output);\n }\n if (node.using) {\n this.append(' ');\n this.visitNode(node.using);\n }\n if (node.joins) {\n this.append(' ');\n this.compileList(node.joins, ' ');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n if (node.orderBy) {\n this.append(' ');\n this.visitNode(node.orderBy);\n }\n if (node.limit) {\n this.append(' ');\n this.visitNode(node.limit);\n }\n if (node.returning) {\n this.append(' ');\n this.visitNode(node.returning);\n }\n if (wrapInParens) {\n this.append(')');\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n visitReturning(node) {\n this.append('returning ');\n this.compileList(node.selections);\n }\n visitAlias(node) {\n this.visitNode(node.node);\n this.append(' as ');\n this.visitNode(node.alias);\n }\n visitReference(node) {\n if (node.table) {\n this.visitNode(node.table);\n this.append('.');\n }\n this.visitNode(node.column);\n }\n visitSelectAll(_) {\n this.append('*');\n }\n visitIdentifier(node) {\n this.append(this.getLeftIdentifierWrapper());\n this.compileUnwrappedIdentifier(node);\n this.append(this.getRightIdentifierWrapper());\n }\n compileUnwrappedIdentifier(node) {\n if (!isString(node.name)) {\n throw new Error('a non-string identifier was passed to compileUnwrappedIdentifier.');\n }\n this.append(this.sanitizeIdentifier(node.name));\n }\n visitAnd(node) {\n this.visitNode(node.left);\n this.append(' and ');\n this.visitNode(node.right);\n }\n visitOr(node) {\n this.visitNode(node.left);\n this.append(' or ');\n this.visitNode(node.right);\n }\n visitValue(node) {\n if (node.immediate) {\n this.appendImmediateValue(node.value);\n }\n else {\n this.appendValue(node.value);\n }\n }\n visitValueList(node) {\n this.append('(');\n this.compileList(node.values);\n this.append(')');\n }\n visitTuple(node) {\n this.append('(');\n this.compileList(node.values);\n this.append(')');\n }\n visitPrimitiveValueList(node) {\n this.append('(');\n const { values } = node;\n for (let i = 0; i < values.length; ++i) {\n this.appendValue(values[i]);\n if (i !== values.length - 1) {\n this.append(', ');\n }\n }\n this.append(')');\n }\n visitParens(node) {\n this.append('(');\n this.visitNode(node.node);\n this.append(')');\n }\n visitJoin(node) {\n this.append(JOIN_TYPE_SQL[node.joinType]);\n this.append(' ');\n this.visitNode(node.table);\n if (node.on) {\n this.append(' ');\n this.visitNode(node.on);\n }\n }\n visitOn(node) {\n this.append('on ');\n this.visitNode(node.on);\n }\n visitRaw(node) {\n const { sqlFragments, parameters: params } = node;\n for (let i = 0; i < sqlFragments.length; ++i) {\n this.append(sqlFragments[i]);\n if (params.length > i) {\n this.visitNode(params[i]);\n }\n }\n }\n visitOperator(node) {\n this.append(node.operator);\n }\n visitTable(node) {\n this.visitNode(node.table);\n }\n visitSchemableIdentifier(node) {\n if (node.schema) {\n this.visitNode(node.schema);\n this.append('.');\n }\n this.visitNode(node.identifier);\n }\n visitCreateTable(node) {\n this.append('create ');\n if (node.frontModifiers?.length) {\n this.compileList(node.frontModifiers, ' ');\n this.append(' ');\n }\n if (node.temporary) {\n this.append('temporary ');\n }\n this.append('table ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.table);\n if (!node.selectQuery) {\n this.append(' (');\n this.compileList([...node.columns, ...(node.constraints ?? [])]);\n this.append(')');\n }\n if (node.onCommit) {\n this.append(' on commit ');\n this.append(node.onCommit);\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n if (node.selectQuery) {\n this.append(' as ');\n this.visitNode(node.selectQuery);\n }\n }\n visitColumnDefinition(node) {\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.column);\n this.append(' ');\n this.visitNode(node.dataType);\n if (node.unsigned) {\n this.append(' unsigned');\n }\n if (node.frontModifiers && node.frontModifiers.length > 0) {\n this.append(' ');\n this.compileList(node.frontModifiers, ' ');\n }\n if (node.generated) {\n this.append(' ');\n this.visitNode(node.generated);\n }\n if (node.identity) {\n this.append(' identity');\n }\n if (node.defaultTo) {\n this.append(' ');\n this.visitNode(node.defaultTo);\n }\n if (node.notNull) {\n this.append(' not null');\n }\n if (node.unique) {\n this.append(' unique');\n }\n if (node.nullsNotDistinct) {\n this.append(' nulls not distinct');\n }\n if (node.primaryKey) {\n this.append(' primary key');\n }\n if (node.autoIncrement) {\n this.append(' ');\n this.append(this.getAutoIncrement());\n }\n if (node.references) {\n this.append(' ');\n this.visitNode(node.references);\n }\n if (node.check) {\n this.append(' ');\n this.visitNode(node.check);\n }\n if (node.endModifiers && node.endModifiers.length > 0) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n getAutoIncrement() {\n return 'auto_increment';\n }\n visitReferences(node) {\n this.append('references ');\n this.visitNode(node.table);\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n if (node.onDelete) {\n this.append(' on delete ');\n this.append(node.onDelete);\n }\n if (node.onUpdate) {\n this.append(' on update ');\n this.append(node.onUpdate);\n }\n }\n visitDropTable(node) {\n this.append('drop table ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.table);\n if (node.cascade) {\n this.append(' cascade');\n }\n }\n visitDataType(node) {\n this.append(node.dataType);\n }\n visitOrderBy(node) {\n this.append('order by ');\n this.compileList(node.items);\n }\n visitOrderByItem(node) {\n this.visitNode(node.orderBy);\n if (node.collation) {\n this.append(' ');\n this.visitNode(node.collation);\n }\n if (node.direction) {\n this.append(' ');\n this.visitNode(node.direction);\n }\n if (node.nulls) {\n this.append(' nulls ');\n this.append(node.nulls);\n }\n }\n visitGroupBy(node) {\n this.append('group by ');\n this.compileList(node.items);\n }\n visitGroupByItem(node) {\n this.visitNode(node.groupBy);\n }\n visitUpdateQuery(node) {\n const wrapInParens = this.parentNode !== undefined &&\n !ParensNode.is(this.parentNode) &&\n !RawNode.is(this.parentNode) &&\n !WhenNode.is(this.parentNode);\n if (this.parentNode === undefined && node.explain) {\n this.visitNode(node.explain);\n this.append(' ');\n }\n if (wrapInParens) {\n this.append('(');\n }\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append('update ');\n if (node.top) {\n this.visitNode(node.top);\n this.append(' ');\n }\n if (node.table) {\n this.visitNode(node.table);\n this.append(' ');\n }\n this.append('set ');\n if (node.updates) {\n this.compileList(node.updates);\n }\n if (node.output) {\n this.append(' ');\n this.visitNode(node.output);\n }\n if (node.from) {\n this.append(' ');\n this.visitNode(node.from);\n }\n if (node.joins) {\n if (!node.from) {\n throw new Error(\"Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins\");\n }\n this.append(' ');\n this.compileList(node.joins, ' ');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n if (node.returning) {\n this.append(' ');\n this.visitNode(node.returning);\n }\n if (node.orderBy) {\n this.append(' ');\n this.visitNode(node.orderBy);\n }\n if (node.limit) {\n this.append(' ');\n this.visitNode(node.limit);\n }\n if (wrapInParens) {\n this.append(')');\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n visitColumnUpdate(node) {\n this.visitNode(node.column);\n this.append(' = ');\n this.visitNode(node.value);\n }\n visitLimit(node) {\n this.append('limit ');\n this.visitNode(node.limit);\n }\n visitOffset(node) {\n this.append('offset ');\n this.visitNode(node.offset);\n }\n visitOnConflict(node) {\n this.append('on conflict');\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n else if (node.constraint) {\n this.append(' on constraint ');\n this.visitNode(node.constraint);\n }\n else if (node.indexExpression) {\n this.append(' (');\n this.visitNode(node.indexExpression);\n this.append(')');\n }\n if (node.indexWhere) {\n this.append(' ');\n this.visitNode(node.indexWhere);\n }\n if (node.doNothing === true) {\n this.append(' do nothing');\n }\n else if (node.updates) {\n this.append(' do update set ');\n this.compileList(node.updates);\n if (node.updateWhere) {\n this.append(' ');\n this.visitNode(node.updateWhere);\n }\n }\n }\n visitOnDuplicateKey(node) {\n this.append('on duplicate key update ');\n this.compileList(node.updates);\n }\n visitCreateIndex(node) {\n this.append('create ');\n if (node.unique) {\n this.append('unique ');\n }\n this.append('index ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.name);\n if (node.table) {\n this.append(' on ');\n this.visitNode(node.table);\n }\n if (node.using) {\n this.append(' using ');\n this.visitNode(node.using);\n }\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n if (node.nullsNotDistinct) {\n this.append(' nulls not distinct');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n }\n visitDropIndex(node) {\n this.append('drop index ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.name);\n if (node.table) {\n this.append(' on ');\n this.visitNode(node.table);\n }\n if (node.cascade) {\n this.append(' cascade');\n }\n }\n visitCreateSchema(node) {\n this.append('create schema ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.schema);\n }\n visitDropSchema(node) {\n this.append('drop schema ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.schema);\n if (node.cascade) {\n this.append(' cascade');\n }\n }\n visitPrimaryKeyConstraint(node) {\n if (node.name) {\n this.append('constraint ');\n this.visitNode(node.name);\n this.append(' ');\n }\n this.append('primary key (');\n this.compileList(node.columns);\n this.append(')');\n this.buildDeferrable(node);\n }\n buildDeferrable(node) {\n if (node.deferrable !== undefined) {\n if (node.deferrable) {\n this.append(' deferrable');\n }\n else {\n this.append(' not deferrable');\n }\n }\n if (node.initiallyDeferred !== undefined) {\n if (node.initiallyDeferred) {\n this.append(' initially deferred');\n }\n else {\n this.append(' initially immediate');\n }\n }\n }\n visitUniqueConstraint(node) {\n if (node.name) {\n this.append('constraint ');\n this.visitNode(node.name);\n this.append(' ');\n }\n this.append('unique');\n if (node.nullsNotDistinct) {\n this.append(' nulls not distinct');\n }\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n this.buildDeferrable(node);\n }\n visitCheckConstraint(node) {\n if (node.name) {\n this.append('constraint ');\n this.visitNode(node.name);\n this.append(' ');\n }\n this.append('check (');\n this.visitNode(node.expression);\n this.append(')');\n }\n visitForeignKeyConstraint(node) {\n if (node.name) {\n this.append('constraint ');\n this.visitNode(node.name);\n this.append(' ');\n }\n this.append('foreign key (');\n this.compileList(node.columns);\n this.append(') ');\n this.visitNode(node.references);\n if (node.onDelete) {\n this.append(' on delete ');\n this.append(node.onDelete);\n }\n if (node.onUpdate) {\n this.append(' on update ');\n this.append(node.onUpdate);\n }\n this.buildDeferrable(node);\n }\n visitList(node) {\n this.compileList(node.items);\n }\n visitWith(node) {\n this.append('with ');\n if (node.recursive) {\n this.append('recursive ');\n }\n this.compileList(node.expressions);\n }\n visitCommonTableExpression(node) {\n this.visitNode(node.name);\n this.append(' as ');\n if (isBoolean(node.materialized)) {\n if (!node.materialized) {\n this.append('not ');\n }\n this.append('materialized ');\n }\n this.visitNode(node.expression);\n }\n visitCommonTableExpressionName(node) {\n this.visitNode(node.table);\n if (node.columns) {\n this.append('(');\n this.compileList(node.columns);\n this.append(')');\n }\n }\n visitAlterTable(node) {\n this.append('alter table ');\n this.visitNode(node.table);\n this.append(' ');\n if (node.renameTo) {\n this.append('rename to ');\n this.visitNode(node.renameTo);\n }\n if (node.setSchema) {\n this.append('set schema ');\n this.visitNode(node.setSchema);\n }\n if (node.addConstraint) {\n this.visitNode(node.addConstraint);\n }\n if (node.dropConstraint) {\n this.visitNode(node.dropConstraint);\n }\n if (node.renameConstraint) {\n this.visitNode(node.renameConstraint);\n }\n if (node.columnAlterations) {\n this.compileColumnAlterations(node.columnAlterations);\n }\n if (node.addIndex) {\n this.visitNode(node.addIndex);\n }\n if (node.dropIndex) {\n this.visitNode(node.dropIndex);\n }\n }\n visitAddColumn(node) {\n this.append('add column ');\n this.visitNode(node.column);\n }\n visitRenameColumn(node) {\n this.append('rename column ');\n this.visitNode(node.column);\n this.append(' to ');\n this.visitNode(node.renameTo);\n }\n visitDropColumn(node) {\n this.append('drop column ');\n this.visitNode(node.column);\n }\n visitAlterColumn(node) {\n this.append('alter column ');\n this.visitNode(node.column);\n this.append(' ');\n if (node.dataType) {\n if (this.announcesNewColumnDataType()) {\n this.append('type ');\n }\n this.visitNode(node.dataType);\n if (node.dataTypeExpression) {\n this.append('using ');\n this.visitNode(node.dataTypeExpression);\n }\n }\n if (node.setDefault) {\n this.append('set default ');\n this.visitNode(node.setDefault);\n }\n if (node.dropDefault) {\n this.append('drop default');\n }\n if (node.setNotNull) {\n this.append('set not null');\n }\n if (node.dropNotNull) {\n this.append('drop not null');\n }\n }\n visitModifyColumn(node) {\n this.append('modify column ');\n this.visitNode(node.column);\n }\n visitAddConstraint(node) {\n this.append('add ');\n this.visitNode(node.constraint);\n }\n visitDropConstraint(node) {\n this.append('drop constraint ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.constraintName);\n if (node.modifier === 'cascade') {\n this.append(' cascade');\n }\n else if (node.modifier === 'restrict') {\n this.append(' restrict');\n }\n }\n visitRenameConstraint(node) {\n this.append('rename constraint ');\n this.visitNode(node.oldName);\n this.append(' to ');\n this.visitNode(node.newName);\n }\n visitSetOperation(node) {\n this.append(node.operator);\n this.append(' ');\n if (node.all) {\n this.append('all ');\n }\n this.visitNode(node.expression);\n }\n visitCreateView(node) {\n this.append('create ');\n if (node.orReplace) {\n this.append('or replace ');\n }\n if (node.materialized) {\n this.append('materialized ');\n }\n if (node.temporary) {\n this.append('temporary ');\n }\n this.append('view ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.name);\n this.append(' ');\n if (node.columns) {\n this.append('(');\n this.compileList(node.columns);\n this.append(') ');\n }\n if (node.as) {\n this.append('as ');\n this.visitNode(node.as);\n }\n }\n visitRefreshMaterializedView(node) {\n this.append('refresh materialized view ');\n if (node.concurrently) {\n this.append('concurrently ');\n }\n this.visitNode(node.name);\n if (node.withNoData) {\n this.append(' with no data');\n }\n else {\n this.append(' with data');\n }\n }\n visitDropView(node) {\n this.append('drop ');\n if (node.materialized) {\n this.append('materialized ');\n }\n this.append('view ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.name);\n if (node.cascade) {\n this.append(' cascade');\n }\n }\n visitGenerated(node) {\n this.append('generated ');\n if (node.always) {\n this.append('always ');\n }\n if (node.byDefault) {\n this.append('by default ');\n }\n this.append('as ');\n if (node.identity) {\n this.append('identity');\n }\n if (node.expression) {\n this.append('(');\n this.visitNode(node.expression);\n this.append(')');\n }\n if (node.stored) {\n this.append(' stored');\n }\n }\n visitDefaultValue(node) {\n this.append('default ');\n this.visitNode(node.defaultValue);\n }\n visitSelectModifier(node) {\n if (node.rawModifier) {\n this.visitNode(node.rawModifier);\n }\n else {\n this.append(SELECT_MODIFIER_SQL[node.modifier]);\n }\n if (node.of) {\n this.append(' of ');\n this.compileList(node.of, ', ');\n }\n }\n visitCreateType(node) {\n this.append('create type ');\n this.visitNode(node.name);\n if (node.enum) {\n this.append(' as enum ');\n this.visitNode(node.enum);\n }\n }\n visitDropType(node) {\n this.append('drop type ');\n if (node.ifExists) {\n this.append('if exists ');\n }\n this.visitNode(node.name);\n }\n visitExplain(node) {\n this.append('explain');\n if (node.options || node.format) {\n this.append(' ');\n this.append(this.getLeftExplainOptionsWrapper());\n if (node.options) {\n this.visitNode(node.options);\n if (node.format) {\n this.append(this.getExplainOptionsDelimiter());\n }\n }\n if (node.format) {\n this.append('format');\n this.append(this.getExplainOptionAssignment());\n this.append(node.format);\n }\n this.append(this.getRightExplainOptionsWrapper());\n }\n }\n visitDefaultInsertValue(_) {\n this.append('default');\n }\n visitAggregateFunction(node) {\n this.append(node.func);\n this.append('(');\n if (node.distinct) {\n this.append('distinct ');\n }\n this.compileList(node.aggregated);\n if (node.orderBy) {\n this.append(' ');\n this.visitNode(node.orderBy);\n }\n this.append(')');\n if (node.withinGroup) {\n this.append(' within group (');\n this.visitNode(node.withinGroup);\n this.append(')');\n }\n if (node.filter) {\n this.append(' filter(');\n this.visitNode(node.filter);\n this.append(')');\n }\n if (node.over) {\n this.append(' ');\n this.visitNode(node.over);\n }\n }\n visitOver(node) {\n this.append('over(');\n if (node.partitionBy) {\n this.visitNode(node.partitionBy);\n if (node.orderBy) {\n this.append(' ');\n }\n }\n if (node.orderBy) {\n this.visitNode(node.orderBy);\n }\n this.append(')');\n }\n visitPartitionBy(node) {\n this.append('partition by ');\n this.compileList(node.items);\n }\n visitPartitionByItem(node) {\n this.visitNode(node.partitionBy);\n }\n visitBinaryOperation(node) {\n this.visitNode(node.leftOperand);\n this.append(' ');\n this.visitNode(node.operator);\n this.append(' ');\n this.visitNode(node.rightOperand);\n }\n visitUnaryOperation(node) {\n this.visitNode(node.operator);\n if (!this.isMinusOperator(node.operator)) {\n this.append(' ');\n }\n this.visitNode(node.operand);\n }\n isMinusOperator(node) {\n return OperatorNode.is(node) && node.operator === '-';\n }\n visitUsing(node) {\n this.append('using ');\n this.compileList(node.tables);\n }\n visitFunction(node) {\n this.append(node.func);\n this.append('(');\n this.compileList(node.arguments);\n this.append(')');\n }\n visitCase(node) {\n this.append('case');\n if (node.value) {\n this.append(' ');\n this.visitNode(node.value);\n }\n if (node.when) {\n this.append(' ');\n this.compileList(node.when, ' ');\n }\n if (node.else) {\n this.append(' else ');\n this.visitNode(node.else);\n }\n this.append(' end');\n if (node.isStatement) {\n this.append(' case');\n }\n }\n visitWhen(node) {\n this.append('when ');\n this.visitNode(node.condition);\n if (node.result) {\n this.append(' then ');\n this.visitNode(node.result);\n }\n }\n visitJSONReference(node) {\n this.visitNode(node.reference);\n this.visitNode(node.traversal);\n }\n visitJSONPath(node) {\n if (node.inOperator) {\n this.visitNode(node.inOperator);\n }\n this.append(\"'$\");\n for (const pathLeg of node.pathLegs) {\n this.visitNode(pathLeg);\n }\n this.append(\"'\");\n }\n visitJSONPathLeg(node) {\n const isArrayLocation = node.type === 'ArrayLocation';\n this.append(isArrayLocation ? '[' : '.');\n this.append(typeof node.value === 'string'\n ? this.sanitizeStringLiteral(node.value)\n : String(node.value));\n if (isArrayLocation) {\n this.append(']');\n }\n }\n visitJSONOperatorChain(node) {\n for (let i = 0, len = node.values.length; i < len; i++) {\n if (i === len - 1) {\n this.visitNode(node.operator);\n }\n else {\n this.append('->');\n }\n this.visitNode(node.values[i]);\n }\n }\n visitMergeQuery(node) {\n if (node.with) {\n this.visitNode(node.with);\n this.append(' ');\n }\n this.append('merge ');\n if (node.top) {\n this.visitNode(node.top);\n this.append(' ');\n }\n this.append('into ');\n this.visitNode(node.into);\n if (node.using) {\n this.append(' ');\n this.visitNode(node.using);\n }\n if (node.whens) {\n this.append(' ');\n this.compileList(node.whens, ' ');\n }\n if (node.returning) {\n this.append(' ');\n this.visitNode(node.returning);\n }\n if (node.output) {\n this.append(' ');\n this.visitNode(node.output);\n }\n if (node.endModifiers?.length) {\n this.append(' ');\n this.compileList(node.endModifiers, ' ');\n }\n }\n visitMatched(node) {\n if (node.not) {\n this.append('not ');\n }\n this.append('matched');\n if (node.bySource) {\n this.append(' by source');\n }\n }\n visitAddIndex(node) {\n this.append('add ');\n if (node.unique) {\n this.append('unique ');\n }\n this.append('index ');\n this.visitNode(node.name);\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n if (node.using) {\n this.append(' using ');\n this.visitNode(node.using);\n }\n }\n visitCast(node) {\n this.append('cast(');\n this.visitNode(node.expression);\n this.append(' as ');\n this.visitNode(node.dataType);\n this.append(')');\n }\n visitFetch(node) {\n this.append('fetch next ');\n this.visitNode(node.rowCount);\n this.append(` rows ${node.modifier}`);\n }\n visitOutput(node) {\n this.append('output ');\n this.compileList(node.selections);\n }\n visitTop(node) {\n this.append(`top(${node.expression})`);\n if (node.modifiers) {\n this.append(` ${node.modifiers}`);\n }\n }\n visitOrAction(node) {\n this.append(node.action);\n }\n visitCollate(node) {\n this.append('collate ');\n this.visitNode(node.collation);\n }\n append(str) {\n this.#sql += str;\n }\n appendValue(parameter) {\n this.addParameter(parameter);\n this.append(this.getCurrentParameterPlaceholder());\n }\n getLeftIdentifierWrapper() {\n return '\"';\n }\n getRightIdentifierWrapper() {\n return '\"';\n }\n getCurrentParameterPlaceholder() {\n return '$' + this.numParameters;\n }\n getLeftExplainOptionsWrapper() {\n return '(';\n }\n getExplainOptionAssignment() {\n return ' ';\n }\n getExplainOptionsDelimiter() {\n return ', ';\n }\n getRightExplainOptionsWrapper() {\n return ')';\n }\n sanitizeIdentifier(identifier) {\n const leftWrap = this.getLeftIdentifierWrapper();\n const rightWrap = this.getRightIdentifierWrapper();\n let sanitized = '';\n for (const c of identifier) {\n sanitized += c;\n if (c === leftWrap) {\n sanitized += leftWrap;\n }\n else if (c === rightWrap) {\n sanitized += rightWrap;\n }\n }\n return sanitized;\n }\n sanitizeStringLiteral(value) {\n return value.replace(LIT_WRAP_REGEX, \"''\");\n }\n addParameter(parameter) {\n this.#parameters.push(parameter);\n }\n appendImmediateValue(value) {\n if (isString(value)) {\n this.appendStringLiteral(value);\n }\n else if (isNumber(value) || isBoolean(value) || isBigInt(value)) {\n this.append(value.toString());\n }\n else if (isNull(value)) {\n this.append('null');\n }\n else if (isDate(value)) {\n this.appendImmediateValue(value.toISOString());\n }\n else {\n throw new Error(`invalid immediate value ${value}`);\n }\n }\n appendStringLiteral(value) {\n this.append(\"'\");\n this.append(this.sanitizeStringLiteral(value));\n this.append(\"'\");\n }\n sortSelectModifiers(arr) {\n arr.sort((left, right) => left.modifier && right.modifier\n ? SELECT_MODIFIER_PRIORITY[left.modifier] -\n SELECT_MODIFIER_PRIORITY[right.modifier]\n : 1);\n return freeze(arr);\n }\n compileColumnAlterations(columnAlterations) {\n this.compileList(columnAlterations);\n }\n /**\n * controls whether the dialect adds a \"type\" keyword before a column's new data\n * type in an ALTER TABLE statement.\n */\n announcesNewColumnDataType() {\n return true;\n }\n}\nconst SELECT_MODIFIER_SQL = freeze({\n ForKeyShare: 'for key share',\n ForNoKeyUpdate: 'for no key update',\n ForUpdate: 'for update',\n ForShare: 'for share',\n NoWait: 'nowait',\n SkipLocked: 'skip locked',\n Distinct: 'distinct',\n});\nconst SELECT_MODIFIER_PRIORITY = freeze({\n ForKeyShare: 1,\n ForNoKeyUpdate: 1,\n ForUpdate: 1,\n ForShare: 1,\n NoWait: 2,\n SkipLocked: 2,\n Distinct: 0,\n});\nconst JOIN_TYPE_SQL = freeze({\n InnerJoin: 'inner join',\n LeftJoin: 'left join',\n RightJoin: 'right join',\n FullJoin: 'full join',\n CrossJoin: 'cross join',\n LateralInnerJoin: 'inner join lateral',\n LateralLeftJoin: 'left join lateral',\n LateralCrossJoin: 'cross join lateral',\n OuterApply: 'outer apply',\n CrossApply: 'cross apply',\n Using: 'using',\n});\n", "/// \nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { createQueryId } from '../util/query-id.js';\nexport const CompiledQuery = freeze({\n raw(sql, parameters = []) {\n return freeze({\n sql,\n query: RawNode.createWithSql(sql),\n parameters: freeze(parameters),\n queryId: createQueryId(),\n });\n },\n});\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \n/**\n * A driver that does absolutely nothing.\n *\n * You can use this to create Kysely instances solely for building queries\n *\n * ### Examples\n *\n * This example creates a Kysely instance for building postgres queries:\n *\n * ```ts\n * import {\n * DummyDriver,\n * Kysely,\n * PostgresAdapter,\n * PostgresIntrospector,\n * PostgresQueryCompiler\n * } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: {\n * createAdapter: () => new PostgresAdapter(),\n * createDriver: () => new DummyDriver(),\n * createIntrospector: (db: Kysely) => new PostgresIntrospector(db),\n * createQueryCompiler: () => new PostgresQueryCompiler(),\n * },\n * })\n * ```\n *\n * You can use it to build a query and compile it to SQL but trying to\n * execute the query will throw an error.\n *\n * ```ts\n * const { sql } = db.selectFrom('person').selectAll().compile()\n * console.log(sql) // select * from \"person\"\n * ```\n */\nexport class DummyDriver {\n async init() {\n // Nothing to do here.\n }\n async acquireConnection() {\n return new DummyConnection();\n }\n async beginTransaction() {\n // Nothing to do here.\n }\n async commitTransaction() {\n // Nothing to do here.\n }\n async rollbackTransaction() {\n // Nothing to do here.\n }\n async releaseConnection() {\n // Nothing to do here.\n }\n async destroy() {\n // Nothing to do here.\n }\n async releaseSavepoint() {\n // Nothing to do here.\n }\n async rollbackToSavepoint() {\n // Nothing to do here.\n }\n async savepoint() {\n // Nothing to do here.\n }\n}\nclass DummyConnection {\n async executeQuery() {\n return {\n rows: [],\n };\n }\n async *streamQuery() {\n // Nothing to do here.\n }\n}\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \n/**\n * A basic implementation of `DialectAdapter` with sensible default values.\n * Third-party dialects can extend this instead of implementing the `DialectAdapter`\n * interface from scratch. That way all new settings will get default values when\n * they are added and there will be less breaking changes.\n */\nexport class DialectAdapterBase {\n get supportsCreateIfNotExists() {\n return true;\n }\n get supportsTransactionalDdl() {\n return false;\n }\n get supportsReturning() {\n return false;\n }\n get supportsOutput() {\n return false;\n }\n}\n", "/// \nexport {};\n", "/// \nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nexport function parseSavepointCommand(command, savepointName) {\n return RawNode.createWithChildren([\n RawNode.createWithSql(`${command} `),\n IdentifierNode.create(savepointName), // ensures savepointName gets sanitized\n ]);\n}\n", "/// \nimport { SelectQueryNode } from '../../operation-node/select-query-node.js';\nimport { parseSavepointCommand } from '../../parser/savepoint-parser.js';\nimport { CompiledQuery } from '../../query-compiler/compiled-query.js';\nimport { freeze, isFunction } from '../../util/object-utils.js';\nimport { createQueryId } from '../../util/query-id.js';\nexport class SqliteDriver {\n #config;\n #connectionMutex = new ConnectionMutex();\n #db;\n #connection;\n constructor(config) {\n this.#config = freeze({ ...config });\n }\n async init() {\n this.#db = isFunction(this.#config.database)\n ? await this.#config.database()\n : this.#config.database;\n this.#connection = new SqliteConnection(this.#db);\n if (this.#config.onCreateConnection) {\n await this.#config.onCreateConnection(this.#connection);\n }\n }\n async acquireConnection() {\n // SQLite only has one single connection. We use a mutex here to wait\n // until the single connection has been released.\n await this.#connectionMutex.lock();\n return this.#connection;\n }\n async beginTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('begin'));\n }\n async commitTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('commit'));\n }\n async rollbackTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('rollback'));\n }\n async savepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('savepoint', savepointName), createQueryId()));\n }\n async rollbackToSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('rollback to', savepointName), createQueryId()));\n }\n async releaseSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('release', savepointName), createQueryId()));\n }\n async releaseConnection() {\n this.#connectionMutex.unlock();\n }\n async destroy() {\n this.#db?.close();\n }\n}\nclass SqliteConnection {\n #db;\n constructor(db) {\n this.#db = db;\n }\n executeQuery(compiledQuery) {\n const { sql, parameters } = compiledQuery;\n const stmt = this.#db.prepare(sql);\n if (stmt.reader) {\n return Promise.resolve({\n rows: stmt.all(parameters),\n });\n }\n const { changes, lastInsertRowid } = stmt.run(parameters);\n return Promise.resolve({\n numAffectedRows: changes !== undefined && changes !== null ? BigInt(changes) : undefined,\n insertId: lastInsertRowid !== undefined && lastInsertRowid !== null\n ? BigInt(lastInsertRowid)\n : undefined,\n rows: [],\n });\n }\n async *streamQuery(compiledQuery, _chunkSize) {\n const { sql, parameters, query } = compiledQuery;\n const stmt = this.#db.prepare(sql);\n if (SelectQueryNode.is(query)) {\n const iter = stmt.iterate(parameters);\n for (const row of iter) {\n yield {\n rows: [row],\n };\n }\n }\n else {\n throw new Error('Sqlite driver only supports streaming of select queries');\n }\n }\n}\nclass ConnectionMutex {\n #promise;\n #resolve;\n async lock() {\n while (this.#promise) {\n await this.#promise;\n }\n this.#promise = new Promise((resolve) => {\n this.#resolve = resolve;\n });\n }\n unlock() {\n const resolve = this.#resolve;\n this.#promise = undefined;\n this.#resolve = undefined;\n resolve?.();\n }\n}\n", "/// \nimport { DefaultQueryCompiler } from '../../query-compiler/default-query-compiler.js';\nconst ID_WRAP_REGEX = /\"/g;\nexport class SqliteQueryCompiler extends DefaultQueryCompiler {\n visitOrAction(node) {\n this.append('or ');\n this.append(node.action);\n }\n getCurrentParameterPlaceholder() {\n return '?';\n }\n getLeftExplainOptionsWrapper() {\n return '';\n }\n getRightExplainOptionsWrapper() {\n return '';\n }\n getLeftIdentifierWrapper() {\n return '\"';\n }\n getRightIdentifierWrapper() {\n return '\"';\n }\n getAutoIncrement() {\n return 'autoincrement';\n }\n sanitizeIdentifier(identifier) {\n return identifier.replace(ID_WRAP_REGEX, '\"\"');\n }\n visitDefaultInsertValue(_) {\n // sqlite doesn't support the `default` keyword in inserts.\n this.append('null');\n }\n}\n", "/// \nimport { NoopPlugin } from '../plugin/noop-plugin.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { freeze, getLast, isObject } from '../util/object-utils.js';\nexport const DEFAULT_MIGRATION_TABLE = 'kysely_migration';\nexport const DEFAULT_MIGRATION_LOCK_TABLE = 'kysely_migration_lock';\nexport const DEFAULT_ALLOW_UNORDERED_MIGRATIONS = false;\nexport const MIGRATION_LOCK_ID = 'migration_lock';\nexport const NO_MIGRATIONS = freeze({ __noMigrations__: true });\n/**\n * A class for running migrations.\n *\n * ### Example\n *\n * This example uses the {@link FileMigrationProvider} that reads migrations\n * files from a single folder. You can easily implement your own\n * {@link MigrationProvider} if you want to provide migrations some\n * other way.\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import * as Sqlite from 'better-sqlite3'\n * import {\n * FileMigrationProvider,\n * Kysely,\n * Migrator,\n * SqliteDialect\n * } from 'kysely'\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: Sqlite(':memory:')\n * })\n * })\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n * ```\n */\nexport class Migrator {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Returns a {@link MigrationInfo} object for each migration.\n *\n * The returned array is sorted by migration name.\n */\n async getMigrations() {\n const tableExists = await this.#doesTableExist(this.#migrationTable);\n const executedMigrations = tableExists\n ? await this.#props.db\n .withPlugin(this.#schemaPlugin)\n .selectFrom(this.#migrationTable)\n .select(['name', 'timestamp'])\n .$narrowType()\n .execute()\n : [];\n const migrations = await this.#resolveMigrations();\n return migrations.map(({ name, ...migration }) => {\n const executed = executedMigrations.find((it) => it.name === name);\n return {\n name,\n migration,\n executedAt: executed ? new Date(executed.timestamp) : undefined,\n };\n });\n }\n /**\n * Runs all migrations that have not yet been run.\n *\n * This method returns a {@link MigrationResultSet} instance and _never_ throws.\n * {@link MigrationResultSet.error} holds the error if something went wrong.\n * {@link MigrationResultSet.results} contains information about which migrations\n * were executed and which failed. See the examples below.\n *\n * This method goes through all possible migrations provided by the provider and runs the\n * ones whose names come alphabetically after the last migration that has been run. If the\n * list of executed migrations doesn't match the beginning of the list of possible migrations\n * an error is returned.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import * as Sqlite from 'better-sqlite3'\n * import { FileMigrationProvider, Migrator } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * const { error, results } = await migrator.migrateToLatest()\n *\n * results?.forEach((it) => {\n * if (it.status === 'Success') {\n * console.log(`migration \"${it.migrationName}\" was executed successfully`)\n * } else if (it.status === 'Error') {\n * console.error(`failed to execute migration \"${it.migrationName}\"`)\n * }\n * })\n *\n * if (error) {\n * console.error('failed to run `migrateToLatest`')\n * console.error(error)\n * }\n * ```\n */\n async migrateToLatest() {\n return this.#migrate(() => ({ direction: 'Up', step: Infinity }));\n }\n /**\n * Migrate up/down to a specific migration.\n *\n * This method returns a {@link MigrationResultSet} instance and _never_ throws.\n * {@link MigrationResultSet.error} holds the error if something went wrong.\n * {@link MigrationResultSet.results} contains information about which migrations\n * were executed and which failed.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import { FileMigrationProvider, Migrator } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * await migrator.migrateTo('some_migration')\n * ```\n *\n * If you specify the name of the first migration, this method migrates\n * down to the first migration, but doesn't run the `down` method of\n * the first migration. In case you want to migrate all the way down,\n * you can use a special constant `NO_MIGRATIONS`:\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import { FileMigrationProvider, Migrator, NO_MIGRATIONS } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * await migrator.migrateTo(NO_MIGRATIONS)\n * ```\n */\n async migrateTo(targetMigrationName) {\n return this.#migrate(({ migrations, executedMigrations, pendingMigrations, }) => {\n if (isObject(targetMigrationName) &&\n targetMigrationName.__noMigrations__ === true) {\n return { direction: 'Down', step: Infinity };\n }\n if (!migrations.find((m) => m.name === targetMigrationName)) {\n throw new Error(`migration \"${targetMigrationName}\" doesn't exist`);\n }\n const executedIndex = executedMigrations.indexOf(targetMigrationName);\n const pendingIndex = pendingMigrations.findIndex((m) => m.name === targetMigrationName);\n if (executedIndex !== -1) {\n return {\n direction: 'Down',\n step: executedMigrations.length - executedIndex - 1,\n };\n }\n else if (pendingIndex !== -1) {\n return { direction: 'Up', step: pendingIndex + 1 };\n }\n else {\n throw new Error(`migration \"${targetMigrationName}\" isn't executed or pending`);\n }\n });\n }\n /**\n * Migrate one step up.\n *\n * This method returns a {@link MigrationResultSet} instance and _never_ throws.\n * {@link MigrationResultSet.error} holds the error if something went wrong.\n * {@link MigrationResultSet.results} contains information about which migrations\n * were executed and which failed.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import { FileMigrationProvider, Migrator } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * await migrator.migrateUp()\n * ```\n */\n async migrateUp() {\n return this.#migrate(() => ({ direction: 'Up', step: 1 }));\n }\n /**\n * Migrate one step down.\n *\n * This method returns a {@link MigrationResultSet} instance and _never_ throws.\n * {@link MigrationResultSet.error} holds the error if something went wrong.\n * {@link MigrationResultSet.results} contains information about which migrations\n * were executed and which failed.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n * import { FileMigrationProvider, Migrator } from 'kysely'\n *\n * const migrator = new Migrator({\n * db,\n * provider: new FileMigrationProvider({\n * fs,\n * // Path to the folder that contains all your migrations.\n * migrationFolder: 'some/path/to/migrations',\n * path,\n * })\n * })\n *\n * await migrator.migrateDown()\n * ```\n */\n async migrateDown() {\n return this.#migrate(() => ({ direction: 'Down', step: 1 }));\n }\n async #migrate(getMigrationDirectionAndStep) {\n try {\n await this.#ensureMigrationTableSchemaExists();\n await this.#ensureMigrationTableExists();\n await this.#ensureMigrationLockTableExists();\n await this.#ensureLockRowExists();\n return await this.#runMigrations(getMigrationDirectionAndStep);\n }\n catch (error) {\n if (error instanceof MigrationResultSetError) {\n return error.resultSet;\n }\n return { error };\n }\n }\n get #migrationTableSchema() {\n return this.#props.migrationTableSchema;\n }\n get #migrationTable() {\n return this.#props.migrationTableName ?? DEFAULT_MIGRATION_TABLE;\n }\n get #migrationLockTable() {\n return this.#props.migrationLockTableName ?? DEFAULT_MIGRATION_LOCK_TABLE;\n }\n get #allowUnorderedMigrations() {\n return (this.#props.allowUnorderedMigrations ?? DEFAULT_ALLOW_UNORDERED_MIGRATIONS);\n }\n get #schemaPlugin() {\n if (this.#migrationTableSchema) {\n return new WithSchemaPlugin(this.#migrationTableSchema);\n }\n return new NoopPlugin();\n }\n async #ensureMigrationTableSchemaExists() {\n if (!this.#migrationTableSchema) {\n // Use default schema. Nothing to do.\n return;\n }\n const schemaExists = await this.#doesSchemaExist();\n if (schemaExists) {\n return;\n }\n try {\n await this.#createIfNotExists(this.#props.db.schema.createSchema(this.#migrationTableSchema));\n }\n catch (error) {\n const schemaExists = await this.#doesSchemaExist();\n // At least on PostgreSQL, `if not exists` doesn't guarantee the `create schema`\n // query doesn't throw if the schema already exits. That's why we check if\n // the schema exist here and ignore the error if it does.\n if (!schemaExists) {\n throw error;\n }\n }\n }\n async #ensureMigrationTableExists() {\n const tableExists = await this.#doesTableExist(this.#migrationTable);\n if (tableExists) {\n return;\n }\n try {\n await this.#createIfNotExists(this.#props.db.schema\n .withPlugin(this.#schemaPlugin)\n .createTable(this.#migrationTable)\n .addColumn('name', 'varchar(255)', (col) => col.notNull().primaryKey())\n // The migration run time as ISO string. This is not a real date type as we\n // can't know which data type is supported by all future dialects.\n .addColumn('timestamp', 'varchar(255)', (col) => col.notNull()));\n }\n catch (error) {\n const tableExists = await this.#doesTableExist(this.#migrationTable);\n // At least on PostgreSQL, `if not exists` doesn't guarantee the `create table`\n // query doesn't throw if the table already exits. That's why we check if\n // the table exist here and ignore the error if it does.\n if (!tableExists) {\n throw error;\n }\n }\n }\n async #ensureMigrationLockTableExists() {\n const tableExists = await this.#doesTableExist(this.#migrationLockTable);\n if (tableExists) {\n return;\n }\n try {\n await this.#createIfNotExists(this.#props.db.schema\n .withPlugin(this.#schemaPlugin)\n .createTable(this.#migrationLockTable)\n .addColumn('id', 'varchar(255)', (col) => col.notNull().primaryKey())\n .addColumn('is_locked', 'integer', (col) => col.notNull().defaultTo(0)));\n }\n catch (error) {\n const tableExists = await this.#doesTableExist(this.#migrationLockTable);\n // At least on PostgreSQL, `if not exists` doesn't guarantee the `create table`\n // query doesn't throw if the table already exits. That's why we check if\n // the table exist here and ignore the error if it does.\n if (!tableExists) {\n throw error;\n }\n }\n }\n async #ensureLockRowExists() {\n const lockRowExists = await this.#doesLockRowExists();\n if (lockRowExists) {\n return;\n }\n try {\n await this.#props.db\n .withPlugin(this.#schemaPlugin)\n .insertInto(this.#migrationLockTable)\n .values({ id: MIGRATION_LOCK_ID, is_locked: 0 })\n .execute();\n }\n catch (error) {\n const lockRowExists = await this.#doesLockRowExists();\n if (!lockRowExists) {\n throw error;\n }\n }\n }\n async #doesSchemaExist() {\n const schemas = await this.#props.db.introspection.getSchemas();\n return schemas.some((it) => it.name === this.#migrationTableSchema);\n }\n async #doesTableExist(tableName) {\n const schema = this.#migrationTableSchema;\n const tables = await this.#props.db.introspection.getTables({\n withInternalKyselyTables: true,\n });\n return tables.some((it) => it.name === tableName && (!schema || it.schema === schema));\n }\n async #doesLockRowExists() {\n const lockRow = await this.#props.db\n .withPlugin(this.#schemaPlugin)\n .selectFrom(this.#migrationLockTable)\n .where('id', '=', MIGRATION_LOCK_ID)\n .select('id')\n .executeTakeFirst();\n return !!lockRow;\n }\n async #runMigrations(getMigrationDirectionAndStep) {\n const adapter = this.#props.db.getExecutor().adapter;\n const lockOptions = freeze({\n lockTable: this.#props.migrationLockTableName ?? DEFAULT_MIGRATION_LOCK_TABLE,\n lockRowId: MIGRATION_LOCK_ID,\n lockTableSchema: this.#props.migrationTableSchema,\n });\n const run = async (db) => {\n try {\n await adapter.acquireMigrationLock(db, lockOptions);\n const state = await this.#getState(db);\n if (state.migrations.length === 0) {\n return { results: [] };\n }\n const { direction, step } = getMigrationDirectionAndStep(state);\n if (step <= 0) {\n return { results: [] };\n }\n if (direction === 'Down') {\n return await this.#migrateDown(db, state, step);\n }\n else if (direction === 'Up') {\n return await this.#migrateUp(db, state, step);\n }\n return { results: [] };\n }\n finally {\n await adapter.releaseMigrationLock(db, lockOptions);\n }\n };\n if (adapter.supportsTransactionalDdl && !this.#props.disableTransactions) {\n return this.#props.db.transaction().execute(run);\n }\n else {\n return this.#props.db.connection().execute(run);\n }\n }\n async #getState(db) {\n const migrations = await this.#resolveMigrations();\n const executedMigrations = await this.#getExecutedMigrations(db);\n this.#ensureNoMissingMigrations(migrations, executedMigrations);\n if (!this.#allowUnorderedMigrations) {\n this.#ensureMigrationsInOrder(migrations, executedMigrations);\n }\n const pendingMigrations = this.#getPendingMigrations(migrations, executedMigrations);\n return freeze({\n migrations,\n executedMigrations,\n lastMigration: getLast(executedMigrations),\n pendingMigrations,\n });\n }\n #getPendingMigrations(migrations, executedMigrations) {\n return migrations.filter((migration) => {\n return !executedMigrations.includes(migration.name);\n });\n }\n async #resolveMigrations() {\n const allMigrations = await this.#props.provider.getMigrations();\n return Object.keys(allMigrations)\n .sort()\n .map((name) => ({\n ...allMigrations[name],\n name,\n }));\n }\n async #getExecutedMigrations(db) {\n const executedMigrations = await db\n .withPlugin(this.#schemaPlugin)\n .selectFrom(this.#migrationTable)\n .select(['name', 'timestamp'])\n .$narrowType()\n .execute();\n const nameComparator = this.#props.nameComparator || ((a, b) => a.localeCompare(b));\n return (executedMigrations\n // https://github.com/kysely-org/kysely/issues/843\n .sort((a, b) => {\n if (a.timestamp === b.timestamp) {\n return nameComparator(a.name, b.name);\n }\n return (new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());\n })\n .map((it) => it.name));\n }\n #ensureNoMissingMigrations(migrations, executedMigrations) {\n // Ensure all executed migrations exist in the `migrations` list.\n for (const executed of executedMigrations) {\n if (!migrations.some((it) => it.name === executed)) {\n throw new Error(`corrupted migrations: previously executed migration ${executed} is missing`);\n }\n }\n }\n #ensureMigrationsInOrder(migrations, executedMigrations) {\n // Ensure the executed migrations are the first ones in the migration list.\n for (let i = 0; i < executedMigrations.length; ++i) {\n if (migrations[i].name !== executedMigrations[i]) {\n throw new Error(`corrupted migrations: expected previously executed migration ${executedMigrations[i]} to be at index ${i} but ${migrations[i].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`);\n }\n }\n }\n async #migrateDown(db, state, step) {\n const migrationsToRollback = state.executedMigrations\n .slice()\n .reverse()\n .slice(0, step)\n .map((name) => {\n return state.migrations.find((it) => it.name === name);\n });\n const results = migrationsToRollback.map((migration) => {\n return {\n migrationName: migration.name,\n direction: 'Down',\n status: 'NotExecuted',\n };\n });\n for (let i = 0; i < results.length; ++i) {\n const migration = migrationsToRollback[i];\n try {\n if (migration.down) {\n await migration.down(db);\n await db\n .withPlugin(this.#schemaPlugin)\n .deleteFrom(this.#migrationTable)\n .where('name', '=', migration.name)\n .execute();\n results[i] = {\n migrationName: migration.name,\n direction: 'Down',\n status: 'Success',\n };\n }\n }\n catch (error) {\n results[i] = {\n migrationName: migration.name,\n direction: 'Down',\n status: 'Error',\n };\n throw new MigrationResultSetError({\n error,\n results,\n });\n }\n }\n return { results };\n }\n async #migrateUp(db, state, step) {\n const migrationsToRun = state.pendingMigrations.slice(0, step);\n const results = migrationsToRun.map((migration) => {\n return {\n migrationName: migration.name,\n direction: 'Up',\n status: 'NotExecuted',\n };\n });\n for (let i = 0; i < results.length; i++) {\n const migration = state.pendingMigrations[i];\n try {\n await migration.up(db);\n await db\n .withPlugin(this.#schemaPlugin)\n .insertInto(this.#migrationTable)\n .values({\n name: migration.name,\n timestamp: new Date().toISOString(),\n })\n .execute();\n results[i] = {\n migrationName: migration.name,\n direction: 'Up',\n status: 'Success',\n };\n }\n catch (error) {\n results[i] = {\n migrationName: migration.name,\n direction: 'Up',\n status: 'Error',\n };\n throw new MigrationResultSetError({\n error,\n results,\n });\n }\n }\n return { results };\n }\n async #createIfNotExists(qb) {\n if (this.#props.db.getExecutor().adapter.supportsCreateIfNotExists) {\n qb = qb.ifNotExists();\n }\n await qb.execute();\n }\n}\nclass MigrationResultSetError extends Error {\n #resultSet;\n constructor(result) {\n super();\n this.#resultSet = result;\n }\n get resultSet() {\n return this.#resultSet;\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';\nimport { sql } from '../../raw-builder/sql.js';\nexport class SqliteIntrospector {\n #db;\n constructor(db) {\n this.#db = db;\n }\n async getSchemas() {\n // Sqlite doesn't support schemas.\n return [];\n }\n async getTables(options = { withInternalKyselyTables: false }) {\n return await this.#getTableMetadata(options);\n }\n async getMetadata(options) {\n return {\n tables: await this.getTables(options),\n };\n }\n #tablesQuery(qb, options) {\n let tablesQuery = qb\n .selectFrom('sqlite_master')\n .where('type', 'in', ['table', 'view'])\n .where('name', 'not like', 'sqlite_%')\n .select(['name', 'sql', 'type'])\n .orderBy('name');\n if (!options.withInternalKyselyTables) {\n tablesQuery = tablesQuery\n .where('name', '!=', DEFAULT_MIGRATION_TABLE)\n .where('name', '!=', DEFAULT_MIGRATION_LOCK_TABLE);\n }\n return tablesQuery;\n }\n async #getTableMetadata(options) {\n const tablesResult = await this.#tablesQuery(this.#db, options).execute();\n const tableMetadata = await this.#db\n .with('table_list', (qb) => this.#tablesQuery(qb, options))\n .selectFrom([\n 'table_list as tl',\n sql `pragma_table_info(tl.name)`.as('p'),\n ])\n .select([\n 'tl.name as table',\n 'p.cid',\n 'p.name',\n 'p.type',\n 'p.notnull',\n 'p.dflt_value',\n 'p.pk',\n ])\n .orderBy('tl.name')\n .orderBy('p.cid')\n .execute();\n const columnsByTable = {};\n for (const row of tableMetadata) {\n columnsByTable[row.table] ??= [];\n columnsByTable[row.table].push(row);\n }\n return tablesResult.map(({ name, sql, type }) => {\n // // Try to find the name of the column that has `autoincrement` \uD83E\uDD26\n let autoIncrementCol = sql\n ?.split(/[\\(\\),]/)\n ?.find((it) => it.toLowerCase().includes('autoincrement'))\n ?.trimStart()\n ?.split(/\\s+/)?.[0]\n ?.replace(/[\"`]/g, '');\n const columns = columnsByTable[name] ?? [];\n // Otherwise, check for an INTEGER PRIMARY KEY\n // https://www.sqlite.org/autoinc.html\n if (!autoIncrementCol) {\n const pkCols = columns.filter((r) => r.pk > 0);\n if (pkCols.length === 1 && pkCols[0].type.toLowerCase() === 'integer') {\n autoIncrementCol = pkCols[0].name;\n }\n }\n return {\n name: name,\n isView: type === 'view',\n columns: columns.map((col) => ({\n name: col.name,\n dataType: col.type,\n isNullable: !col.notnull,\n isAutoIncrementing: col.name === autoIncrementCol,\n hasDefaultValue: col.dflt_value != null,\n comment: undefined,\n })),\n };\n });\n }\n}\n", "/// \nimport { DialectAdapterBase } from '../dialect-adapter-base.js';\nexport class SqliteAdapter extends DialectAdapterBase {\n get supportsTransactionalDdl() {\n return false;\n }\n get supportsReturning() {\n return true;\n }\n async acquireMigrationLock(_db, _opt) {\n // SQLite only has one connection that's reserved by the migration system\n // for the whole time between acquireMigrationLock and releaseMigrationLock.\n // We don't need to do anything here.\n }\n async releaseMigrationLock(_db, _opt) {\n // SQLite only has one connection that's reserved by the migration system\n // for the whole time between acquireMigrationLock and releaseMigrationLock.\n // We don't need to do anything here.\n }\n}\n", "/// \nimport { SqliteDriver } from './sqlite-driver.js';\nimport { SqliteQueryCompiler } from './sqlite-query-compiler.js';\nimport { SqliteIntrospector } from './sqlite-introspector.js';\nimport { SqliteAdapter } from './sqlite-adapter.js';\nimport { freeze } from '../../util/object-utils.js';\n/**\n * SQLite dialect that uses the [better-sqlite3](https://github.com/JoshuaWise/better-sqlite3) library.\n *\n * The constructor takes an instance of {@link SqliteDialectConfig}.\n *\n * ```ts\n * import Database from 'better-sqlite3'\n *\n * new SqliteDialect({\n * database: new Database('db.sqlite')\n * })\n * ```\n *\n * If you want the pool to only be created once it's first used, `database`\n * can be a function:\n *\n * ```ts\n * import Database from 'better-sqlite3'\n *\n * new SqliteDialect({\n * database: async () => new Database('db.sqlite')\n * })\n * ```\n */\nexport class SqliteDialect {\n #config;\n constructor(config) {\n this.#config = freeze({ ...config });\n }\n createDriver() {\n return new SqliteDriver(this.#config);\n }\n createQueryCompiler() {\n return new SqliteQueryCompiler();\n }\n createAdapter() {\n return new SqliteAdapter();\n }\n createIntrospector(db) {\n return new SqliteIntrospector(db);\n }\n}\n", "/// \nexport {};\n", "/// \nimport { DefaultQueryCompiler } from '../../query-compiler/default-query-compiler.js';\nconst ID_WRAP_REGEX = /\"/g;\nexport class PostgresQueryCompiler extends DefaultQueryCompiler {\n sanitizeIdentifier(identifier) {\n return identifier.replace(ID_WRAP_REGEX, '\"\"');\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';\nimport { freeze } from '../../util/object-utils.js';\nimport { sql } from '../../raw-builder/sql.js';\nexport class PostgresIntrospector {\n #db;\n constructor(db) {\n this.#db = db;\n }\n async getSchemas() {\n let rawSchemas = await this.#db\n .selectFrom('pg_catalog.pg_namespace')\n .select('nspname')\n .$castTo()\n .execute();\n return rawSchemas.map((it) => ({ name: it.nspname }));\n }\n async getTables(options = { withInternalKyselyTables: false }) {\n let query = this.#db\n // column\n .selectFrom('pg_catalog.pg_attribute as a')\n // table\n .innerJoin('pg_catalog.pg_class as c', 'a.attrelid', 'c.oid')\n // table schema\n .innerJoin('pg_catalog.pg_namespace as ns', 'c.relnamespace', 'ns.oid')\n // column data type\n .innerJoin('pg_catalog.pg_type as typ', 'a.atttypid', 'typ.oid')\n // column data type schema\n .innerJoin('pg_catalog.pg_namespace as dtns', 'typ.typnamespace', 'dtns.oid')\n .select([\n 'a.attname as column',\n 'a.attnotnull as not_null',\n 'a.atthasdef as has_default',\n 'c.relname as table',\n 'c.relkind as table_type',\n 'ns.nspname as schema',\n 'typ.typname as type',\n 'dtns.nspname as type_schema',\n sql `col_description(a.attrelid, a.attnum)`.as('column_description'),\n sql `pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as('auto_incrementing'),\n ])\n .where('c.relkind', 'in', [\n 'r' /*regular table*/,\n 'v' /*view*/,\n 'p' /*partitioned table*/,\n ])\n .where('ns.nspname', '!~', '^pg_')\n .where('ns.nspname', '!=', 'information_schema')\n // Filter out internal cockroachdb schema\n .where('ns.nspname', '!=', 'crdb_internal')\n // Only schemas where we are allowed access\n .where(sql `has_schema_privilege(ns.nspname, 'USAGE')`)\n // No system columns\n .where('a.attnum', '>=', 0)\n .where('a.attisdropped', '!=', true)\n .orderBy('ns.nspname')\n .orderBy('c.relname')\n .orderBy('a.attnum')\n .$castTo();\n if (!options.withInternalKyselyTables) {\n query = query\n .where('c.relname', '!=', DEFAULT_MIGRATION_TABLE)\n .where('c.relname', '!=', DEFAULT_MIGRATION_LOCK_TABLE);\n }\n const rawColumns = await query.execute();\n return this.#parseTableMetadata(rawColumns);\n }\n async getMetadata(options) {\n return {\n tables: await this.getTables(options),\n };\n }\n #parseTableMetadata(columns) {\n const tableDictionary = new Map();\n for (let i = 0, len = columns.length; i < len; i++) {\n const column = columns[i];\n const { schema, table } = column;\n const tableKey = `schema:${schema};table:${table}`;\n if (!tableDictionary.has(tableKey)) {\n tableDictionary.set(tableKey, freeze({\n columns: [],\n isView: column.table_type === 'v',\n name: table,\n schema,\n }));\n }\n tableDictionary.get(tableKey).columns.push(freeze({\n comment: column.column_description ?? undefined,\n dataType: column.type,\n dataTypeSchema: column.type_schema,\n hasDefaultValue: column.has_default,\n isAutoIncrementing: column.auto_incrementing !== null,\n isNullable: !column.not_null,\n name: column.column,\n }));\n }\n return Array.from(tableDictionary.values());\n }\n}\n", "/// \nimport { sql } from '../../raw-builder/sql.js';\nimport { DialectAdapterBase } from '../dialect-adapter-base.js';\n// Random id for our transaction lock.\nconst LOCK_ID = BigInt('3853314791062309107');\nexport class PostgresAdapter extends DialectAdapterBase {\n get supportsTransactionalDdl() {\n return true;\n }\n get supportsReturning() {\n return true;\n }\n async acquireMigrationLock(db, _opt) {\n // Acquire a transaction level advisory lock.\n await sql `select pg_advisory_xact_lock(${sql.lit(LOCK_ID)})`.execute(db);\n }\n async releaseMigrationLock(_db, _opt) {\n // Nothing to do here. `pg_advisory_xact_lock` is automatically released at the\n // end of the transaction and since `supportsTransactionalDdl` true, we know\n // the `db` instance passed to acquireMigrationLock is actually a transaction.\n }\n}\n", "/// \nimport { isObject, isString } from './object-utils.js';\nexport function extendStackTrace(err, stackError) {\n if (isStackHolder(err) && stackError.stack) {\n // Remove the first line that just says `Error`.\n const stackExtension = stackError.stack.split('\\n').slice(1).join('\\n');\n err.stack += `\\n${stackExtension}`;\n return err;\n }\n return err;\n}\nfunction isStackHolder(obj) {\n return isObject(obj) && isString(obj.stack);\n}\n", "/// \nimport { parseSavepointCommand } from '../../parser/savepoint-parser.js';\nimport { CompiledQuery } from '../../query-compiler/compiled-query.js';\nimport { isFunction, isObject, freeze } from '../../util/object-utils.js';\nimport { createQueryId } from '../../util/query-id.js';\nimport { extendStackTrace } from '../../util/stack-trace-utils.js';\nconst PRIVATE_RELEASE_METHOD = Symbol();\nexport class MysqlDriver {\n #config;\n #connections = new WeakMap();\n #pool;\n constructor(configOrPool) {\n this.#config = freeze({ ...configOrPool });\n }\n async init() {\n this.#pool = isFunction(this.#config.pool)\n ? await this.#config.pool()\n : this.#config.pool;\n }\n async acquireConnection() {\n const rawConnection = await this.#acquireConnection();\n let connection = this.#connections.get(rawConnection);\n if (!connection) {\n connection = new MysqlConnection(rawConnection);\n this.#connections.set(rawConnection, connection);\n // The driver must take care of calling `onCreateConnection` when a new\n // connection is created. The `mysql2` module doesn't provide an async hook\n // for the connection creation. We need to call the method explicitly.\n if (this.#config?.onCreateConnection) {\n await this.#config.onCreateConnection(connection);\n }\n }\n if (this.#config?.onReserveConnection) {\n await this.#config.onReserveConnection(connection);\n }\n return connection;\n }\n async #acquireConnection() {\n return new Promise((resolve, reject) => {\n this.#pool.getConnection(async (err, rawConnection) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(rawConnection);\n }\n });\n });\n }\n async beginTransaction(connection, settings) {\n if (settings.isolationLevel || settings.accessMode) {\n const parts = [];\n if (settings.isolationLevel) {\n parts.push(`isolation level ${settings.isolationLevel}`);\n }\n if (settings.accessMode) {\n parts.push(settings.accessMode);\n }\n const sql = `set transaction ${parts.join(', ')}`;\n // On MySQL this sets the isolation level of the next transaction.\n await connection.executeQuery(CompiledQuery.raw(sql));\n }\n await connection.executeQuery(CompiledQuery.raw('begin'));\n }\n async commitTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('commit'));\n }\n async rollbackTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('rollback'));\n }\n async savepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('savepoint', savepointName), createQueryId()));\n }\n async rollbackToSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('rollback to', savepointName), createQueryId()));\n }\n async releaseSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('release savepoint', savepointName), createQueryId()));\n }\n async releaseConnection(connection) {\n connection[PRIVATE_RELEASE_METHOD]();\n }\n async destroy() {\n return new Promise((resolve, reject) => {\n this.#pool.end((err) => {\n if (err) {\n reject(err);\n }\n else {\n resolve();\n }\n });\n });\n }\n}\nfunction isOkPacket(obj) {\n return isObject(obj) && 'insertId' in obj && 'affectedRows' in obj;\n}\nclass MysqlConnection {\n #rawConnection;\n constructor(rawConnection) {\n this.#rawConnection = rawConnection;\n }\n async executeQuery(compiledQuery) {\n try {\n const result = await this.#executeQuery(compiledQuery);\n if (isOkPacket(result)) {\n const { insertId, affectedRows, changedRows } = result;\n return {\n insertId: insertId !== undefined &&\n insertId !== null &&\n insertId.toString() !== '0'\n ? BigInt(insertId)\n : undefined,\n numAffectedRows: affectedRows !== undefined && affectedRows !== null\n ? BigInt(affectedRows)\n : undefined,\n numChangedRows: changedRows !== undefined && changedRows !== null\n ? BigInt(changedRows)\n : undefined,\n rows: [],\n };\n }\n else if (Array.isArray(result)) {\n return {\n rows: result,\n };\n }\n return {\n rows: [],\n };\n }\n catch (err) {\n throw extendStackTrace(err, new Error());\n }\n }\n #executeQuery(compiledQuery) {\n return new Promise((resolve, reject) => {\n this.#rawConnection.query(compiledQuery.sql, compiledQuery.parameters, (err, result) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(result);\n }\n });\n });\n }\n async *streamQuery(compiledQuery, _chunkSize) {\n const stream = this.#rawConnection\n .query(compiledQuery.sql, compiledQuery.parameters)\n .stream({\n objectMode: true,\n });\n try {\n for await (const row of stream) {\n yield {\n rows: [row],\n };\n }\n }\n catch (ex) {\n if (ex &&\n typeof ex === 'object' &&\n 'code' in ex &&\n // @ts-ignore\n ex.code === 'ERR_STREAM_PREMATURE_CLOSE') {\n // Most likely because of https://github.com/mysqljs/mysql/blob/master/lib/protocol/sequences/Query.js#L220\n return;\n }\n throw ex;\n }\n }\n [PRIVATE_RELEASE_METHOD]() {\n this.#rawConnection.release();\n }\n}\n", "/// \nimport { DefaultQueryCompiler } from '../../query-compiler/default-query-compiler.js';\nconst LITERAL_ESCAPE_REGEX = /\\\\|'/g;\nconst ID_WRAP_REGEX = /`/g;\nexport class MysqlQueryCompiler extends DefaultQueryCompiler {\n getCurrentParameterPlaceholder() {\n return '?';\n }\n getLeftExplainOptionsWrapper() {\n return '';\n }\n getExplainOptionAssignment() {\n return '=';\n }\n getExplainOptionsDelimiter() {\n return ' ';\n }\n getRightExplainOptionsWrapper() {\n return '';\n }\n getLeftIdentifierWrapper() {\n return ID_WRAP_REGEX.source;\n }\n getRightIdentifierWrapper() {\n return ID_WRAP_REGEX.source;\n }\n sanitizeIdentifier(identifier) {\n return identifier.replace(ID_WRAP_REGEX, '``');\n }\n /**\n * MySQL requires escaping backslashes in string literals when using the\n * default NO_BACKSLASH_ESCAPES=OFF mode. Without this, a backslash\n * followed by a quote (\\') can break out of the string literal.\n *\n * @see https://dev.mysql.com/doc/refman/9.6/en/string-literals.html\n */\n sanitizeStringLiteral(value) {\n return value.replace(LITERAL_ESCAPE_REGEX, (char) => char === '\\\\' ? '\\\\\\\\' : \"''\");\n }\n visitCreateIndex(node) {\n this.append('create ');\n if (node.unique) {\n this.append('unique ');\n }\n this.append('index ');\n if (node.ifNotExists) {\n this.append('if not exists ');\n }\n this.visitNode(node.name);\n if (node.using) {\n this.append(' using ');\n this.visitNode(node.using);\n }\n if (node.table) {\n this.append(' on ');\n this.visitNode(node.table);\n }\n if (node.columns) {\n this.append(' (');\n this.compileList(node.columns);\n this.append(')');\n }\n if (node.where) {\n this.append(' ');\n this.visitNode(node.where);\n }\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';\nimport { freeze } from '../../util/object-utils.js';\nimport { sql } from '../../raw-builder/sql.js';\nexport class MysqlIntrospector {\n #db;\n constructor(db) {\n this.#db = db;\n }\n async getSchemas() {\n let rawSchemas = await this.#db\n .selectFrom('information_schema.schemata')\n .select('schema_name')\n .$castTo()\n .execute();\n return rawSchemas.map((it) => ({ name: it.SCHEMA_NAME }));\n }\n async getTables(options = { withInternalKyselyTables: false }) {\n let query = this.#db\n .selectFrom('information_schema.columns as columns')\n .innerJoin('information_schema.tables as tables', (b) => b\n .onRef('columns.TABLE_CATALOG', '=', 'tables.TABLE_CATALOG')\n .onRef('columns.TABLE_SCHEMA', '=', 'tables.TABLE_SCHEMA')\n .onRef('columns.TABLE_NAME', '=', 'tables.TABLE_NAME'))\n .select([\n 'columns.COLUMN_NAME',\n 'columns.COLUMN_DEFAULT',\n 'columns.TABLE_NAME',\n 'columns.TABLE_SCHEMA',\n 'tables.TABLE_TYPE',\n 'columns.IS_NULLABLE',\n 'columns.DATA_TYPE',\n 'columns.EXTRA',\n 'columns.COLUMN_COMMENT',\n ])\n .where('columns.TABLE_SCHEMA', '=', sql `database()`)\n .orderBy('columns.TABLE_NAME')\n .orderBy('columns.ORDINAL_POSITION')\n .$castTo();\n if (!options.withInternalKyselyTables) {\n query = query\n .where('columns.TABLE_NAME', '!=', DEFAULT_MIGRATION_TABLE)\n .where('columns.TABLE_NAME', '!=', DEFAULT_MIGRATION_LOCK_TABLE);\n }\n const rawColumns = await query.execute();\n return this.#parseTableMetadata(rawColumns);\n }\n async getMetadata(options) {\n return {\n tables: await this.getTables(options),\n };\n }\n #parseTableMetadata(columns) {\n return columns.reduce((tables, it) => {\n let table = tables.find((tbl) => tbl.name === it.TABLE_NAME);\n if (!table) {\n table = freeze({\n name: it.TABLE_NAME,\n isView: it.TABLE_TYPE === 'VIEW',\n schema: it.TABLE_SCHEMA,\n columns: [],\n });\n tables.push(table);\n }\n table.columns.push(freeze({\n name: it.COLUMN_NAME,\n dataType: it.DATA_TYPE,\n isNullable: it.IS_NULLABLE === 'YES',\n isAutoIncrementing: it.EXTRA.toLowerCase().includes('auto_increment'),\n hasDefaultValue: it.COLUMN_DEFAULT !== null,\n comment: it.COLUMN_COMMENT === '' ? undefined : it.COLUMN_COMMENT,\n }));\n return tables;\n }, []);\n }\n}\n", "/// \nimport { sql } from '../../raw-builder/sql.js';\nimport { DialectAdapterBase } from '../dialect-adapter-base.js';\nconst LOCK_ID = 'ea586330-2c93-47c8-908d-981d9d270f9d';\nconst LOCK_TIMEOUT_SECONDS = 60 * 60;\nexport class MysqlAdapter extends DialectAdapterBase {\n get supportsTransactionalDdl() {\n return false;\n }\n get supportsReturning() {\n return false;\n }\n async acquireMigrationLock(db, _opt) {\n // Kysely uses a single connection to run the migrations. Because of that, we\n // can take a lock using `get_lock`. Locks acquired using `get_lock` get\n // released when the connection is destroyed (session ends) or when the lock\n // is released using `release_lock`. This way we know that the lock is either\n // released by us after successfull or failed migrations OR it's released by\n // MySQL if the process gets killed for some reason.\n await sql `select get_lock(${sql.lit(LOCK_ID)}, ${sql.lit(LOCK_TIMEOUT_SECONDS)})`.execute(db);\n }\n async releaseMigrationLock(db, _opt) {\n await sql `select release_lock(${sql.lit(LOCK_ID)})`.execute(db);\n }\n}\n", "/// \nimport { MysqlDriver } from './mysql-driver.js';\nimport { MysqlQueryCompiler } from './mysql-query-compiler.js';\nimport { MysqlIntrospector } from './mysql-introspector.js';\nimport { MysqlAdapter } from './mysql-adapter.js';\n/**\n * MySQL dialect that uses the [mysql2](https://github.com/sidorares/node-mysql2#readme) library.\n *\n * The constructor takes an instance of {@link MysqlDialectConfig}.\n *\n * ```ts\n * import { createPool } from 'mysql2'\n *\n * new MysqlDialect({\n * pool: createPool({\n * database: 'some_db',\n * host: 'localhost',\n * })\n * })\n * ```\n *\n * If you want the pool to only be created once it's first used, `pool`\n * can be a function:\n *\n * ```ts\n * import { createPool } from 'mysql2'\n *\n * new MysqlDialect({\n * pool: async () => createPool({\n * database: 'some_db',\n * host: 'localhost',\n * })\n * })\n * ```\n */\nexport class MysqlDialect {\n #config;\n constructor(config) {\n this.#config = config;\n }\n createDriver() {\n return new MysqlDriver(this.#config);\n }\n createQueryCompiler() {\n return new MysqlQueryCompiler();\n }\n createAdapter() {\n return new MysqlAdapter();\n }\n createIntrospector(db) {\n return new MysqlIntrospector(db);\n }\n}\n", "/// \nexport {};\n", "/// \nimport { parseSavepointCommand } from '../../parser/savepoint-parser.js';\nimport { CompiledQuery } from '../../query-compiler/compiled-query.js';\nimport { isFunction, freeze } from '../../util/object-utils.js';\nimport { createQueryId } from '../../util/query-id.js';\nimport { extendStackTrace } from '../../util/stack-trace-utils.js';\nconst PRIVATE_RELEASE_METHOD = Symbol();\nexport class PostgresDriver {\n #config;\n #connections = new WeakMap();\n #pool;\n constructor(config) {\n this.#config = freeze({ ...config });\n }\n async init() {\n this.#pool = isFunction(this.#config.pool)\n ? await this.#config.pool()\n : this.#config.pool;\n }\n async acquireConnection() {\n const client = await this.#pool.connect();\n let connection = this.#connections.get(client);\n if (!connection) {\n connection = new PostgresConnection(client, {\n cursor: this.#config.cursor ?? null,\n });\n this.#connections.set(client, connection);\n // The driver must take care of calling `onCreateConnection` when a new\n // connection is created. The `pg` module doesn't provide an async hook\n // for the connection creation. We need to call the method explicitly.\n if (this.#config.onCreateConnection) {\n await this.#config.onCreateConnection(connection);\n }\n }\n if (this.#config.onReserveConnection) {\n await this.#config.onReserveConnection(connection);\n }\n return connection;\n }\n async beginTransaction(connection, settings) {\n if (settings.isolationLevel || settings.accessMode) {\n let sql = 'start transaction';\n if (settings.isolationLevel) {\n sql += ` isolation level ${settings.isolationLevel}`;\n }\n if (settings.accessMode) {\n sql += ` ${settings.accessMode}`;\n }\n await connection.executeQuery(CompiledQuery.raw(sql));\n }\n else {\n await connection.executeQuery(CompiledQuery.raw('begin'));\n }\n }\n async commitTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('commit'));\n }\n async rollbackTransaction(connection) {\n await connection.executeQuery(CompiledQuery.raw('rollback'));\n }\n async savepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('savepoint', savepointName), createQueryId()));\n }\n async rollbackToSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('rollback to', savepointName), createQueryId()));\n }\n async releaseSavepoint(connection, savepointName, compileQuery) {\n await connection.executeQuery(compileQuery(parseSavepointCommand('release', savepointName), createQueryId()));\n }\n async releaseConnection(connection) {\n connection[PRIVATE_RELEASE_METHOD]();\n }\n async destroy() {\n if (this.#pool) {\n const pool = this.#pool;\n this.#pool = undefined;\n await pool.end();\n }\n }\n}\nclass PostgresConnection {\n #client;\n #options;\n constructor(client, options) {\n this.#client = client;\n this.#options = options;\n }\n async executeQuery(compiledQuery) {\n try {\n const { command, rowCount, rows } = await this.#client.query(compiledQuery.sql, [...compiledQuery.parameters]);\n return {\n numAffectedRows: command === 'INSERT' ||\n command === 'UPDATE' ||\n command === 'DELETE' ||\n command === 'MERGE'\n ? BigInt(rowCount)\n : undefined,\n rows: rows ?? [],\n };\n }\n catch (err) {\n throw extendStackTrace(err, new Error());\n }\n }\n async *streamQuery(compiledQuery, chunkSize) {\n if (!this.#options.cursor) {\n throw new Error(\"'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.\");\n }\n if (!Number.isInteger(chunkSize) || chunkSize <= 0) {\n throw new Error('chunkSize must be a positive integer');\n }\n const cursor = this.#client.query(new this.#options.cursor(compiledQuery.sql, compiledQuery.parameters.slice()));\n try {\n while (true) {\n const rows = await cursor.read(chunkSize);\n if (rows.length === 0) {\n break;\n }\n yield {\n rows,\n };\n }\n }\n finally {\n await cursor.close();\n }\n }\n [PRIVATE_RELEASE_METHOD]() {\n this.#client.release();\n }\n}\n", "/// \nexport {};\n", "/// \nimport { PostgresDriver } from './postgres-driver.js';\nimport { PostgresIntrospector } from './postgres-introspector.js';\nimport { PostgresQueryCompiler } from './postgres-query-compiler.js';\nimport { PostgresAdapter } from './postgres-adapter.js';\n/**\n * PostgreSQL dialect that uses the [pg](https://node-postgres.com/) library.\n *\n * The constructor takes an instance of {@link PostgresDialectConfig}.\n *\n * ```ts\n * import {\u00A0Pool } from 'pg'\n *\n * new PostgresDialect({\n * pool: new Pool({\n * database: 'some_db',\n * host: 'localhost',\n * })\n * })\n * ```\n *\n * If you want the pool to only be created once it's first used, `pool`\n * can be a function:\n *\n * ```ts\n * import {\u00A0Pool } from 'pg'\n *\n * new PostgresDialect({\n * pool: async () => new Pool({\n * database: 'some_db',\n * host: 'localhost',\n * })\n * })\n * ```\n */\nexport class PostgresDialect {\n #config;\n constructor(config) {\n this.#config = config;\n }\n createDriver() {\n return new PostgresDriver(this.#config);\n }\n createQueryCompiler() {\n return new PostgresQueryCompiler();\n }\n createAdapter() {\n return new PostgresAdapter();\n }\n createIntrospector(db) {\n return new PostgresIntrospector(db);\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_TABLE } from '../../migration/migrator.js';\nimport { sql } from '../../raw-builder/sql.js';\nimport { DialectAdapterBase } from '../dialect-adapter-base.js';\nexport class MssqlAdapter extends DialectAdapterBase {\n get supportsCreateIfNotExists() {\n return false;\n }\n get supportsTransactionalDdl() {\n return true;\n }\n get supportsOutput() {\n return true;\n }\n async acquireMigrationLock(db) {\n // Acquire a transaction-level exclusive lock on the migrations table.\n // https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-getapplock-transact-sql?view=sql-server-ver16\n await sql `exec sp_getapplock @DbPrincipal = ${sql.lit('dbo')}, @Resource = ${sql.lit(DEFAULT_MIGRATION_TABLE)}, @LockMode = ${sql.lit('Exclusive')}`.execute(db);\n }\n async releaseMigrationLock() {\n // Nothing to do here. `sp_getapplock` is automatically released at the\n // end of the transaction and since `supportsTransactionalDdl` true, we know\n // the `db` instance passed to acquireMigrationLock is actually a transaction.\n }\n}\n", "/// \nexport {};\n", "/// \nimport { freeze, isBigInt, isBoolean, isBuffer, isDate, isNull, isNumber, isString, isUndefined, } from '../../util/object-utils.js';\nimport { CompiledQuery } from '../../query-compiler/compiled-query.js';\nimport { extendStackTrace } from '../../util/stack-trace-utils.js';\nimport { randomString } from '../../util/random-string.js';\nimport { Deferred } from '../../util/deferred.js';\nconst PRIVATE_RESET_METHOD = Symbol();\nconst PRIVATE_DESTROY_METHOD = Symbol();\nconst PRIVATE_VALIDATE_METHOD = Symbol();\nexport class MssqlDriver {\n #config;\n #pool;\n constructor(config) {\n this.#config = freeze({ ...config });\n const { tarn, tedious, validateConnections } = this.#config;\n const { validateConnections: deprecatedValidateConnections, ...poolOptions } = tarn.options;\n this.#pool = new tarn.Pool({\n ...poolOptions,\n create: async () => {\n const connection = await tedious.connectionFactory();\n return await new MssqlConnection(connection, tedious).connect();\n },\n destroy: async (connection) => {\n await connection[PRIVATE_DESTROY_METHOD]();\n },\n // @ts-ignore `tarn` accepts a function that returns a promise here, but\n // the types are not aligned and it type errors.\n validate: validateConnections === false ||\n deprecatedValidateConnections === false\n ? undefined\n : (connection) => connection[PRIVATE_VALIDATE_METHOD](),\n });\n }\n async init() {\n // noop\n }\n async acquireConnection() {\n return await this.#pool.acquire().promise;\n }\n async beginTransaction(connection, settings) {\n await connection.beginTransaction(settings);\n }\n async commitTransaction(connection) {\n await connection.commitTransaction();\n }\n async rollbackTransaction(connection) {\n await connection.rollbackTransaction();\n }\n async savepoint(connection, savepointName) {\n await connection.savepoint(savepointName);\n }\n async rollbackToSavepoint(connection, savepointName) {\n await connection.rollbackTransaction(savepointName);\n }\n async releaseConnection(connection) {\n if (this.#config.resetConnectionsOnRelease ||\n this.#config.tedious.resetConnectionOnRelease) {\n await connection[PRIVATE_RESET_METHOD]();\n }\n this.#pool.release(connection);\n }\n async destroy() {\n await this.#pool.destroy();\n }\n}\nclass MssqlConnection {\n #connection;\n #hasSocketError;\n #tedious;\n constructor(connection, tedious) {\n this.#connection = connection;\n this.#hasSocketError = false;\n this.#tedious = tedious;\n }\n async beginTransaction(settings) {\n const { isolationLevel } = settings;\n await new Promise((resolve, reject) => this.#connection.beginTransaction((error) => {\n if (error)\n reject(error);\n else\n resolve(undefined);\n }, isolationLevel ? randomString(8) : undefined, isolationLevel\n ? this.#getTediousIsolationLevel(isolationLevel)\n : undefined));\n }\n async commitTransaction() {\n await new Promise((resolve, reject) => this.#connection.commitTransaction((error) => {\n if (error)\n reject(error);\n else\n resolve(undefined);\n }));\n }\n async connect() {\n const { promise: waitForConnected, reject, resolve } = new Deferred();\n this.#connection.connect((error) => {\n if (error) {\n return reject(error);\n }\n resolve();\n });\n this.#connection.on('error', (error) => {\n if (error instanceof Error &&\n 'code' in error &&\n error.code === 'ESOCKET') {\n this.#hasSocketError = true;\n }\n console.error(error);\n reject(error);\n });\n function endListener() {\n reject(new Error('The connection ended without ever completing the connection'));\n }\n this.#connection.once('end', endListener);\n await waitForConnected;\n this.#connection.off('end', endListener);\n return this;\n }\n async executeQuery(compiledQuery) {\n try {\n const deferred = new Deferred();\n const request = new MssqlRequest({\n compiledQuery,\n tedious: this.#tedious,\n onDone: deferred,\n });\n this.#connection.execSql(request.request);\n const { rowCount, rows } = await deferred.promise;\n return {\n numAffectedRows: rowCount !== undefined ? BigInt(rowCount) : undefined,\n rows,\n };\n }\n catch (err) {\n throw extendStackTrace(err, new Error());\n }\n }\n async rollbackTransaction(savepointName) {\n await new Promise((resolve, reject) => this.#connection.rollbackTransaction((error) => {\n if (error)\n reject(error);\n else\n resolve(undefined);\n }, savepointName));\n }\n async savepoint(savepointName) {\n await new Promise((resolve, reject) => this.#connection.saveTransaction((error) => {\n if (error)\n reject(error);\n else\n resolve(undefined);\n }, savepointName));\n }\n async *streamQuery(compiledQuery, chunkSize) {\n if (!Number.isInteger(chunkSize) || chunkSize <= 0) {\n throw new Error('chunkSize must be a positive integer');\n }\n const request = new MssqlRequest({\n compiledQuery,\n streamChunkSize: chunkSize,\n tedious: this.#tedious,\n });\n this.#connection.execSql(request.request);\n try {\n while (true) {\n const rows = await request.readChunk();\n if (rows.length === 0) {\n break;\n }\n yield { rows };\n if (rows.length < chunkSize) {\n break;\n }\n }\n }\n finally {\n await this.#cancelRequest(request);\n }\n }\n #getTediousIsolationLevel(isolationLevel) {\n const { ISOLATION_LEVEL } = this.#tedious;\n const mapper = {\n 'read committed': ISOLATION_LEVEL.READ_COMMITTED,\n 'read uncommitted': ISOLATION_LEVEL.READ_UNCOMMITTED,\n 'repeatable read': ISOLATION_LEVEL.REPEATABLE_READ,\n serializable: ISOLATION_LEVEL.SERIALIZABLE,\n snapshot: ISOLATION_LEVEL.SNAPSHOT,\n };\n const tediousIsolationLevel = mapper[isolationLevel];\n if (tediousIsolationLevel === undefined) {\n throw new Error(`Unknown isolation level: ${isolationLevel}`);\n }\n return tediousIsolationLevel;\n }\n #cancelRequest(request) {\n return new Promise((resolve) => {\n request.request.once('requestCompleted', resolve);\n const wasCanceled = this.#connection.cancel();\n if (!wasCanceled) {\n request.request.off('requestCompleted', resolve);\n resolve();\n }\n });\n }\n [PRIVATE_DESTROY_METHOD]() {\n if ('closed' in this.#connection && this.#connection.closed) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n this.#connection.once('end', resolve);\n this.#connection.close();\n });\n }\n async [PRIVATE_RESET_METHOD]() {\n await new Promise((resolve, reject) => {\n this.#connection.reset((error) => {\n if (error) {\n return reject(error);\n }\n resolve();\n });\n });\n }\n async [PRIVATE_VALIDATE_METHOD]() {\n if (this.#hasSocketError || this.#isConnectionClosed()) {\n return false;\n }\n try {\n const deferred = new Deferred();\n const request = new MssqlRequest({\n compiledQuery: CompiledQuery.raw('select 1'),\n onDone: deferred,\n tedious: this.#tedious,\n });\n this.#connection.execSql(request.request);\n await deferred.promise;\n return true;\n }\n catch {\n return false;\n }\n }\n #isConnectionClosed() {\n return 'closed' in this.#connection && Boolean(this.#connection.closed);\n }\n}\nclass MssqlRequest {\n #request;\n #rows;\n #streamChunkSize;\n #subscribers;\n #tedious;\n #rowCount;\n constructor(props) {\n const { compiledQuery, onDone, streamChunkSize, tedious } = props;\n this.#rows = [];\n this.#streamChunkSize = streamChunkSize;\n this.#subscribers = {};\n this.#tedious = tedious;\n if (onDone) {\n const subscriptionKey = 'onDone';\n this.#subscribers[subscriptionKey] = (event, error) => {\n if (event === 'chunkReady') {\n return;\n }\n delete this.#subscribers[subscriptionKey];\n if (event === 'error') {\n return onDone.reject(error);\n }\n onDone.resolve({\n rowCount: this.#rowCount,\n rows: this.#rows,\n });\n };\n }\n this.#request = new this.#tedious.Request(compiledQuery.sql, (err, rowCount) => {\n if (err) {\n return Object.values(this.#subscribers).forEach((subscriber) => subscriber('error', err instanceof AggregateError ? err.errors : err));\n }\n this.#rowCount = rowCount;\n });\n this.#addParametersToRequest(compiledQuery.parameters);\n this.#attachListeners();\n }\n get request() {\n return this.#request;\n }\n readChunk() {\n const subscriptionKey = this.readChunk.name;\n return new Promise((resolve, reject) => {\n this.#subscribers[subscriptionKey] = (event, error) => {\n delete this.#subscribers[subscriptionKey];\n if (event === 'error') {\n return reject(error);\n }\n resolve(this.#rows.splice(0, this.#streamChunkSize));\n };\n this.#request.resume();\n });\n }\n #addParametersToRequest(parameters) {\n for (let i = 0; i < parameters.length; i++) {\n const parameter = parameters[i];\n this.#request.addParameter(String(i + 1), this.#getTediousDataType(parameter), parameter);\n }\n }\n #attachListeners() {\n const pauseAndEmitChunkReady = this.#streamChunkSize\n ? () => {\n if (this.#streamChunkSize <= this.#rows.length) {\n this.#request.pause();\n Object.values(this.#subscribers).forEach((subscriber) => subscriber('chunkReady'));\n }\n }\n : () => { };\n const rowListener = (columns) => {\n const row = {};\n for (const column of columns) {\n row[column.metadata.colName] = column.value;\n }\n this.#rows.push(row);\n pauseAndEmitChunkReady();\n };\n this.#request.on('row', rowListener);\n this.#request.once('requestCompleted', () => {\n Object.values(this.#subscribers).forEach((subscriber) => subscriber('completed'));\n this.#request.off('row', rowListener);\n });\n }\n #getTediousDataType(value) {\n if (isNull(value) || isUndefined(value) || isString(value)) {\n return this.#tedious.TYPES.NVarChar;\n }\n if (isBigInt(value) || (isNumber(value) && value % 1 === 0)) {\n if (value < -2147483648 || value > 2147483647) {\n return this.#tedious.TYPES.BigInt;\n }\n else {\n return this.#tedious.TYPES.Int;\n }\n }\n if (isNumber(value)) {\n return this.#tedious.TYPES.Float;\n }\n if (isBoolean(value)) {\n return this.#tedious.TYPES.Bit;\n }\n if (isDate(value)) {\n return this.#tedious.TYPES.DateTime;\n }\n if (isBuffer(value)) {\n return this.#tedious.TYPES.VarBinary;\n }\n return this.#tedious.TYPES.NVarChar;\n }\n}\n", "/// \nimport { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';\nimport { freeze } from '../../util/object-utils.js';\nexport class MssqlIntrospector {\n #db;\n constructor(db) {\n this.#db = db;\n }\n async getSchemas() {\n return await this.#db.selectFrom('sys.schemas').select('name').execute();\n }\n async getTables(options = { withInternalKyselyTables: false }) {\n const rawColumns = await this.#db\n .selectFrom('sys.tables as tables')\n .leftJoin('sys.schemas as table_schemas', 'table_schemas.schema_id', 'tables.schema_id')\n .innerJoin('sys.columns as columns', 'columns.object_id', 'tables.object_id')\n .innerJoin('sys.types as types', 'types.user_type_id', 'columns.user_type_id')\n .leftJoin('sys.schemas as type_schemas', 'type_schemas.schema_id', 'types.schema_id')\n .leftJoin('sys.extended_properties as comments', (join) => join\n .onRef('comments.major_id', '=', 'tables.object_id')\n .onRef('comments.minor_id', '=', 'columns.column_id')\n .on('comments.name', '=', 'MS_Description'))\n .$if(!options.withInternalKyselyTables, (qb) => qb\n .where('tables.name', '!=', DEFAULT_MIGRATION_TABLE)\n .where('tables.name', '!=', DEFAULT_MIGRATION_LOCK_TABLE))\n .select([\n 'tables.name as table_name',\n (eb) => eb\n .ref('tables.type')\n .$castTo()\n .as('table_type'),\n 'table_schemas.name as table_schema_name',\n 'columns.default_object_id as column_default_object_id',\n 'columns.generated_always_type_desc as column_generated_always_type',\n 'columns.is_computed as column_is_computed',\n 'columns.is_identity as column_is_identity',\n 'columns.is_nullable as column_is_nullable',\n 'columns.is_rowguidcol as column_is_rowguidcol',\n 'columns.name as column_name',\n 'types.is_nullable as type_is_nullable',\n 'types.name as type_name',\n 'type_schemas.name as type_schema_name',\n 'comments.value as column_comment',\n ])\n .unionAll(this.#db\n .selectFrom('sys.views as views')\n .leftJoin('sys.schemas as view_schemas', 'view_schemas.schema_id', 'views.schema_id')\n .innerJoin('sys.columns as columns', 'columns.object_id', 'views.object_id')\n .innerJoin('sys.types as types', 'types.user_type_id', 'columns.user_type_id')\n .leftJoin('sys.schemas as type_schemas', 'type_schemas.schema_id', 'types.schema_id')\n .leftJoin('sys.extended_properties as comments', (join) => join\n .onRef('comments.major_id', '=', 'views.object_id')\n .onRef('comments.minor_id', '=', 'columns.column_id')\n .on('comments.name', '=', 'MS_Description'))\n .select([\n 'views.name as table_name',\n 'views.type as table_type',\n 'view_schemas.name as table_schema_name',\n 'columns.default_object_id as column_default_object_id',\n 'columns.generated_always_type_desc as column_generated_always_type',\n 'columns.is_computed as column_is_computed',\n 'columns.is_identity as column_is_identity',\n 'columns.is_nullable as column_is_nullable',\n 'columns.is_rowguidcol as column_is_rowguidcol',\n 'columns.name as column_name',\n 'types.is_nullable as type_is_nullable',\n 'types.name as type_name',\n 'type_schemas.name as type_schema_name',\n 'comments.value as column_comment',\n ]))\n .orderBy('table_schema_name')\n .orderBy('table_name')\n .orderBy('column_name')\n .execute();\n const tableDictionary = {};\n for (const rawColumn of rawColumns) {\n const key = `${rawColumn.table_schema_name}.${rawColumn.table_name}`;\n const table = (tableDictionary[key] =\n tableDictionary[key] ||\n freeze({\n columns: [],\n isView: rawColumn.table_type === 'V ',\n name: rawColumn.table_name,\n schema: rawColumn.table_schema_name ?? undefined,\n }));\n table.columns.push(freeze({\n dataType: rawColumn.type_name,\n dataTypeSchema: rawColumn.type_schema_name ?? undefined,\n hasDefaultValue: rawColumn.column_default_object_id > 0 ||\n rawColumn.column_generated_always_type !== 'NOT_APPLICABLE' ||\n rawColumn.column_is_identity ||\n rawColumn.column_is_computed ||\n rawColumn.column_is_rowguidcol,\n isAutoIncrementing: rawColumn.column_is_identity,\n isNullable: rawColumn.column_is_nullable && rawColumn.type_is_nullable,\n name: rawColumn.column_name,\n comment: rawColumn.column_comment ?? undefined,\n }));\n }\n return Object.values(tableDictionary);\n }\n async getMetadata(options) {\n return {\n tables: await this.getTables(options),\n };\n }\n}\n", "/// \nimport { DefaultQueryCompiler } from '../../query-compiler/default-query-compiler.js';\nconst COLLATION_CHAR_REGEX = /^[a-z0-9_]$/i;\nexport class MssqlQueryCompiler extends DefaultQueryCompiler {\n getCurrentParameterPlaceholder() {\n return `@${this.numParameters}`;\n }\n visitOffset(node) {\n super.visitOffset(node);\n this.append(' rows');\n }\n // mssql allows multi-column alterations in a single statement,\n // but you can only use the command keyword/s once.\n // it also doesn't support multiple kinds of commands in the same\n // alter table statement, but we compile that anyway for the sake\n // of WYSIWYG.\n compileColumnAlterations(columnAlterations) {\n const nodesByKind = {};\n for (const columnAlteration of columnAlterations) {\n if (!nodesByKind[columnAlteration.kind]) {\n nodesByKind[columnAlteration.kind] = [];\n }\n nodesByKind[columnAlteration.kind].push(columnAlteration);\n }\n let first = true;\n if (nodesByKind.AddColumnNode) {\n this.append('add ');\n this.compileList(nodesByKind.AddColumnNode);\n first = false;\n }\n // multiple of these are not really supported by mssql,\n // but for the sake of WYSIWYG.\n if (nodesByKind.AlterColumnNode) {\n if (!first)\n this.append(', ');\n this.compileList(nodesByKind.AlterColumnNode);\n }\n if (nodesByKind.DropColumnNode) {\n if (!first)\n this.append(', ');\n this.append('drop column ');\n this.compileList(nodesByKind.DropColumnNode);\n }\n // not really supported by mssql, but for the sake of WYSIWYG.\n if (nodesByKind.ModifyColumnNode) {\n if (!first)\n this.append(', ');\n this.compileList(nodesByKind.ModifyColumnNode);\n }\n // not really supported by mssql, but for the sake of WYSIWYG.\n if (nodesByKind.RenameColumnNode) {\n if (!first)\n this.append(', ');\n this.compileList(nodesByKind.RenameColumnNode);\n }\n }\n visitAddColumn(node) {\n this.visitNode(node.column);\n }\n visitDropColumn(node) {\n this.visitNode(node.column);\n }\n visitMergeQuery(node) {\n super.visitMergeQuery(node);\n this.append(';');\n }\n visitCollate(node) {\n this.append('collate ');\n const { name } = node.collation;\n for (const char of name) {\n if (!COLLATION_CHAR_REGEX.test(char)) {\n throw new Error(`Invalid collation: ${name}`);\n }\n }\n this.append(name);\n }\n announcesNewColumnDataType() {\n return false;\n }\n}\n", "/// \nimport { MssqlAdapter } from './mssql-adapter.js';\nimport { MssqlDriver } from './mssql-driver.js';\nimport { MssqlIntrospector } from './mssql-introspector.js';\nimport { MssqlQueryCompiler } from './mssql-query-compiler.js';\n/**\n * MS SQL Server dialect that uses the [tedious](https://tediousjs.github.io/tedious)\n * library.\n *\n * The constructor takes an instance of {@link MssqlDialectConfig}.\n *\n * ```ts\n * import * as Tedious from 'tedious'\n * import * as Tarn from 'tarn'\n *\n * const dialect = new MssqlDialect({\n * tarn: {\n * ...Tarn,\n * options: {\n * min: 0,\n * max: 10,\n * },\n * },\n * tedious: {\n * ...Tedious,\n * connectionFactory: () => new Tedious.Connection({\n * authentication: {\n * options: {\n * password: 'password',\n * userName: 'username',\n * },\n * type: 'default',\n * },\n * options: {\n * database: 'some_db',\n * port: 1433,\n * trustServerCertificate: true,\n * },\n * server: 'localhost',\n * }),\n * },\n * })\n * ```\n */\nexport class MssqlDialect {\n #config;\n constructor(config) {\n this.#config = config;\n }\n createDriver() {\n return new MssqlDriver(this.#config);\n }\n createQueryCompiler() {\n return new MssqlQueryCompiler();\n }\n createAdapter() {\n return new MssqlAdapter();\n }\n createIntrospector(db) {\n return new MssqlIntrospector(db);\n }\n}\n", "/// \nexport {};\n", "/// \nimport { isFunction, isObject } from '../util/object-utils.js';\n/**\n * Reads all migrations from a folder in node.js.\n *\n * ### Examples\n *\n * ```ts\n * import { promises as fs } from 'node:fs'\n * import path from 'node:path'\n *\n * new FileMigrationProvider({\n * fs,\n * path,\n * migrationFolder: 'path/to/migrations/folder'\n * })\n * ```\n */\nexport class FileMigrationProvider {\n #props;\n constructor(props) {\n this.#props = props;\n }\n async getMigrations() {\n const migrations = {};\n const files = await this.#props.fs.readdir(this.#props.migrationFolder);\n for (const fileName of files) {\n if (fileName.endsWith('.js') ||\n (fileName.endsWith('.ts') && !fileName.endsWith('.d.ts')) ||\n fileName.endsWith('.mjs') ||\n (fileName.endsWith('.mts') && !fileName.endsWith('.d.mts'))) {\n const migration = await import(\n /* webpackIgnore: true */ this.#props.path.join(this.#props.migrationFolder, fileName));\n const migrationKey = fileName.substring(0, fileName.lastIndexOf('.'));\n // Handle esModuleInterop export's `default` prop...\n if (isMigration(migration?.default)) {\n migrations[migrationKey] = migration.default;\n }\n else if (isMigration(migration)) {\n migrations[migrationKey] = migration;\n }\n }\n }\n return migrations;\n }\n}\nfunction isMigration(obj) {\n return isObject(obj) && isFunction(obj.up);\n}\n", "/// \nexport {};\n", "/// \nimport { isPlainObject } from '../../util/object-utils.js';\nimport { SnakeCaseTransformer } from './camel-case-transformer.js';\nimport { createCamelCaseMapper, createSnakeCaseMapper, } from './camel-case.js';\n/**\n * A plugin that converts snake_case identifiers in the database into\n * camelCase in the JavaScript side.\n *\n * For example let's assume we have a table called `person_table`\n * with columns `first_name` and `last_name` in the database. When\n * using `CamelCasePlugin` we would setup Kysely like this:\n *\n * ```ts\n * import * as Sqlite from 'better-sqlite3'\n * import { CamelCasePlugin, Kysely, SqliteDialect } from 'kysely'\n *\n * interface CamelCasedDatabase {\n * userMetadata: {\n * firstName: string\n * lastName: string\n * }\n * }\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [new CamelCasePlugin()],\n * })\n *\n * const person = await db.selectFrom('userMetadata')\n * .where('firstName', '=', 'Arnold')\n * .select(['firstName', 'lastName'])\n * .executeTakeFirst()\n *\n * if (person) {\n * console.log(person.firstName)\n * }\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select \"first_name\", \"last_name\" from \"user_metadata\" where \"first_name\" = ?\n * ```\n *\n * As you can see from the example, __everything__ needs to be defined\n * in camelCase in the TypeScript code: table names, columns, schemas,\n * __everything__. When using the `CamelCasePlugin` Kysely works as if\n * the database was defined in camelCase.\n *\n * There are various options you can give to the plugin to modify\n * the way identifiers are converted. See {@link CamelCasePluginOptions}.\n * If those options are not enough, you can override this plugin's\n * `snakeCase` and `camelCase` methods to make the conversion exactly\n * the way you like:\n *\n * ```ts\n * class MyCamelCasePlugin extends CamelCasePlugin {\n * protected override snakeCase(str: string): string {\n * // ...\n *\n * return str\n * }\n *\n * protected override camelCase(str: string): string {\n * // ...\n *\n * return str\n * }\n * }\n * ```\n */\nexport class CamelCasePlugin {\n opt;\n #camelCase;\n #snakeCase;\n #snakeCaseTransformer;\n constructor(opt = {}) {\n this.opt = opt;\n this.#camelCase = createCamelCaseMapper(opt);\n this.#snakeCase = createSnakeCaseMapper(opt);\n this.#snakeCaseTransformer = new SnakeCaseTransformer(this.snakeCase.bind(this));\n }\n transformQuery(args) {\n return this.#snakeCaseTransformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n if (args.result.rows && Array.isArray(args.result.rows)) {\n return {\n ...args.result,\n rows: args.result.rows.map((row) => this.mapRow(row)),\n };\n }\n return args.result;\n }\n mapRow(row) {\n return Object.keys(row).reduce((obj, key) => {\n let value = row[key];\n if (Array.isArray(value)) {\n value = value.map((it) => (canMap(it, this.opt) ? this.mapRow(it) : it));\n }\n else if (canMap(value, this.opt)) {\n value = this.mapRow(value);\n }\n obj[this.camelCase(key)] = value;\n return obj;\n }, {});\n }\n snakeCase(str) {\n return this.#snakeCase(str);\n }\n camelCase(str) {\n return this.#camelCase(str);\n }\n}\nfunction canMap(obj, opt) {\n return isPlainObject(obj) && !opt?.maintainNestedObjectKeys;\n}\n", "/// \nimport { DeduplicateJoinsTransformer } from './deduplicate-joins-transformer.js';\n/**\n * Plugin that removes duplicate joins from queries.\n *\n * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0008-deduplicate-joins.md)\n */\nexport class DeduplicateJoinsPlugin {\n #transformer = new DeduplicateJoinsTransformer();\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n transformResult(args) {\n return Promise.resolve(args.result);\n }\n}\n", "/// \nimport { isPlainObject, isString } from '../../util/object-utils.js';\n/**\n * Parses JSON strings in query results into JSON objects.\n *\n * This plugin can be useful with dialects that don't automatically parse\n * JSON into objects and arrays but return JSON strings instead.\n *\n * To apply this plugin globally, pass an instance of it to the `plugins` option\n * when creating a new `Kysely` instance:\n *\n * ```ts\n * import * as Sqlite from 'better-sqlite3'\n * import { Kysely, ParseJSONResultsPlugin, SqliteDialect } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [new ParseJSONResultsPlugin()],\n * })\n * ```\n *\n * To apply this plugin to a single query:\n *\n * ```ts\n * import { ParseJSONResultsPlugin } from 'kysely'\n * import { jsonArrayFrom } from 'kysely/helpers/sqlite'\n *\n * const result = await db\n * .selectFrom('person')\n * .select((eb) => [\n * 'id',\n * 'first_name',\n * 'last_name',\n * jsonArrayFrom(\n * eb.selectFrom('pet')\n * .whereRef('owner_id', '=', 'person.id')\n * .select(['name', 'species'])\n * ).as('pets')\n * ])\n * .withPlugin(new ParseJSONResultsPlugin())\n * .execute()\n * ```\n */\nexport class ParseJSONResultsPlugin {\n opt;\n #objectStrategy;\n constructor(opt = {}) {\n this.opt = opt;\n this.#objectStrategy = opt.objectStrategy || 'in-place';\n }\n // noop\n transformQuery(args) {\n return args.node;\n }\n async transformResult(args) {\n return {\n ...args.result,\n rows: parseArray(args.result.rows, this.#objectStrategy),\n };\n }\n}\nfunction parseArray(arr, objectStrategy) {\n const target = objectStrategy === 'create' ? new Array(arr.length) : arr;\n for (let i = 0; i < arr.length; ++i) {\n target[i] = parse(arr[i], objectStrategy);\n }\n return target;\n}\nfunction parse(obj, objectStrategy) {\n if (isString(obj)) {\n return parseString(obj);\n }\n if (Array.isArray(obj)) {\n return parseArray(obj, objectStrategy);\n }\n if (isPlainObject(obj)) {\n return parseObject(obj, objectStrategy);\n }\n return obj;\n}\nfunction parseString(str) {\n if (maybeJson(str)) {\n try {\n return parse(JSON.parse(str), 'in-place');\n }\n catch (err) {\n // this catch block is intentionally empty.\n }\n }\n return str;\n}\nfunction maybeJson(value) {\n return value.match(/^[\\[\\{]/) != null;\n}\nfunction parseObject(obj, objectStrategy) {\n const target = objectStrategy === 'create' ? {} : obj;\n for (const key in obj) {\n target[key] = parse(obj[key], objectStrategy);\n }\n return target;\n}\n", "/// \nimport { HandleEmptyInListsTransformer } from './handle-empty-in-lists-transformer.js';\n/**\n * A plugin that allows handling `in ()` and `not in ()` expressions.\n *\n * These expressions are invalid SQL syntax for many databases, and result in runtime\n * database errors.\n *\n * The workarounds used by other libraries always involve modifying the query under\n * the hood, which is not aligned with Kysely's philosophy of WYSIWYG. We recommend manually checking\n * for empty arrays before passing them as arguments to `in` and `not in` expressions\n * instead, but understand that this can be cumbersome. Hence we're going with an\n * opt-in approach where you can choose if and how to handle these cases. We do\n * not want to make this the default behavior, as it can lead to unexpected behavior.\n * Use it at your own risk. Test it. Make sure it works as expected for you.\n *\n * Using this plugin also allows you to throw an error (thus avoiding unnecessary\n * requests to the database) or print a warning in these cases.\n *\n * ### Examples\n *\n * The following strategy replaces the `in`/`not in` expression with a noncontingent\n * expression. A contradiction (falsy) `1 = 0` for `in`, and a tautology (truthy) `1 = 1` for `not in`),\n * similarily to how {@link https://github.com/knex/knex/blob/176151d8048b2a7feeb89a3d649a5580786d4f4e/docs/src/guide/query-builder.md#L1763 | Knex.js},\n * {@link https://github.com/prisma/prisma-engines/blob/99168c54187178484dae45d9478aa40cfd1866d2/quaint/src/visitor.rs#L804-L823 | PrismaORM},\n * {@link https://github.com/laravel/framework/blob/8.x/src/Illuminate/Database/Query/Grammars/Grammar.php#L284-L291 | Laravel},\n * {@link https://docs.sqlalchemy.org/en/13/core/engines.html#sqlalchemy.create_engine.params.empty_in_strategy | SQLAlchemy}\n * handle this.\n *\n * ```ts\n * import Sqlite from 'better-sqlite3'\n * import {\n * HandleEmptyInListsPlugin,\n * Kysely,\n * replaceWithNoncontingentExpression,\n * SqliteDialect,\n * } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [\n * new HandleEmptyInListsPlugin({\n * strategy: replaceWithNoncontingentExpression\n * })\n * ],\n * })\n *\n * const results = await db\n * .selectFrom('person')\n * .where('id', 'in', [])\n * .where('first_name', 'not in', [])\n * .selectAll()\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select * from \"person\" where 1 = 0 and 1 = 1\n * ```\n *\n * The following strategy does the following:\n *\n * When `in`, pushes a `null` value into the empty list resulting in `in (null)`,\n * similiarly to how {@link https://github.com/typeorm/typeorm/blob/0280cdc451c35ef73c830eb1191c95d34f6ce06e/src/query-builder/QueryBuilder.ts#L919-L922 | TypeORM}\n * and {@link https://github.com/sequelize/sequelize/blob/0f2891c6897e12bf9bf56df344aae5b698f58c7d/packages/core/src/abstract-dialect/where-sql-builder.ts#L368-L379 | Sequelize}\n * handle `in ()`. `in (null)` is logically the equivalent of `= null`, which returns\n * `null`, which is a falsy expression in most SQL databases. We recommend NOT\n * using this strategy if you plan to use `in` in `select`, `returning`, or `output`\n * clauses, as the return type differs from the `SqlBool` default type for comparisons.\n *\n * When `not in`, casts the left operand as `char` and pushes a unique value into\n * the empty list resulting in `cast({{lhs}} as char) not in ({{VALUE}})`. Casting\n * is required to avoid database errors with non-string values.\n *\n * ```ts\n * import Sqlite from 'better-sqlite3'\n * import {\n * HandleEmptyInListsPlugin,\n * Kysely,\n * pushValueIntoList,\n * SqliteDialect\n * } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [\n * new HandleEmptyInListsPlugin({\n * strategy: pushValueIntoList('__kysely_no_values_were_provided__') // choose a unique value for not in. has to be something with zero chance being in the data.\n * })\n * ],\n * })\n *\n * const results = await db\n * .selectFrom('person')\n * .where('id', 'in', [])\n * .where('first_name', 'not in', [])\n * .selectAll()\n * .execute()\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select * from \"person\" where \"id\" in (null) and cast(\"first_name\" as char) not in ('__kysely_no_values_were_provided__')\n * ```\n *\n * The following custom strategy throws an error when an empty list is encountered\n * to avoid unnecessary requests to the database:\n *\n * ```ts\n * import Sqlite from 'better-sqlite3'\n * import {\n * HandleEmptyInListsPlugin,\n * Kysely,\n * SqliteDialect\n * } from 'kysely'\n * import type { Database } from 'type-editor' // imaginary module\n *\n * const db = new Kysely({\n * dialect: new SqliteDialect({\n * database: new Sqlite(':memory:'),\n * }),\n * plugins: [\n * new HandleEmptyInListsPlugin({\n * strategy: () => {\n * throw new Error('Empty in/not-in is not allowed')\n * }\n * })\n * ],\n * })\n *\n * const results = await db\n * .selectFrom('person')\n * .where('id', 'in', [])\n * .selectAll()\n * .execute() // throws an error with 'Empty in/not-in is not allowed' message!\n * ```\n */\nexport class HandleEmptyInListsPlugin {\n opt;\n #transformer;\n constructor(opt) {\n this.opt = opt;\n this.#transformer = new HandleEmptyInListsTransformer(opt.strategy);\n }\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n return args.result;\n }\n}\n", "/// \nimport { BinaryOperationNode } from '../../operation-node/binary-operation-node.js';\nimport { CastNode } from '../../operation-node/cast-node.js';\nimport { DataTypeNode } from '../../operation-node/data-type-node.js';\nimport { OperatorNode } from '../../operation-node/operator-node.js';\nimport { ValueListNode } from '../../operation-node/value-list-node.js';\nimport { ValueNode } from '../../operation-node/value-node.js';\nimport { freeze } from '../../util/object-utils.js';\nlet contradiction;\nlet eq;\nlet one;\nlet tautology;\n/**\n * Replaces the `in`/`not in` expression with a noncontingent expression (always true or always\n * false) depending on the original operator.\n *\n * This is how Knex.js, PrismaORM, Laravel, and SQLAlchemy handle `in ()` and `not in ()`.\n *\n * See {@link pushValueIntoList} for an alternative strategy.\n */\nexport function replaceWithNoncontingentExpression(node) {\n const _one = (one ||= ValueNode.createImmediate(1));\n const _eq = (eq ||= OperatorNode.create('='));\n if (node.operator.operator === 'in') {\n return (contradiction ||= BinaryOperationNode.create(_one, _eq, ValueNode.createImmediate(0)));\n }\n return (tautology ||= BinaryOperationNode.create(_one, _eq, _one));\n}\nlet char;\nlet listNull;\nlet listVal;\n/**\n * When `in`, pushes a `null` value into the list resulting in `in (null)`. This\n * is how TypeORM and Sequelize handle `in ()`. `in (null)` is logically the equivalent\n * of `= null`, which returns `null`, which is a falsy expression in most SQL databases.\n * We recommend NOT using this strategy if you plan to use `in` in `select`, `returning`,\n * or `output` clauses, as the return type differs from the `SqlBool` default type.\n *\n * When `not in`, casts the left operand as `char` and pushes a literal value into\n * the list resulting in `cast({{lhs}} as char) not in ({{VALUE}})`. Casting\n * is required to avoid database errors with non-string columns.\n *\n * See {@link replaceWithNoncontingentExpression} for an alternative strategy.\n */\nexport function pushValueIntoList(uniqueNotInLiteral) {\n return function pushValueIntoList(node) {\n if (node.operator.operator === 'in') {\n return freeze({\n ...node,\n rightOperand: (listNull ||= ValueListNode.create([\n ValueNode.createImmediate(null),\n ])),\n });\n }\n return freeze({\n ...node,\n leftOperand: CastNode.create(node.leftOperand, (char ||= DataTypeNode.create('char'))),\n rightOperand: (listVal ||= ValueListNode.create([\n ValueNode.createImmediate(uniqueNotInLiteral),\n ])),\n });\n };\n}\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \nexport {};\n", "/// \n/**\n * @module\n * @mergeModuleWith \n */\nexport * from './kysely.js';\nexport * from './query-creator.js';\nexport * from './expression/expression.js';\nexport { expressionBuilder, } from './expression/expression-builder.js';\nexport * from './expression/expression-wrapper.js';\nexport * from './query-builder/where-interface.js';\nexport * from './query-builder/returning-interface.js';\nexport * from './query-builder/output-interface.js';\nexport * from './query-builder/having-interface.js';\nexport * from './query-builder/order-by-interface.js';\nexport * from './query-builder/select-query-builder.js';\nexport * from './query-builder/insert-query-builder.js';\nexport * from './query-builder/update-query-builder.js';\nexport * from './query-builder/delete-query-builder.js';\nexport * from './query-builder/no-result-error.js';\nexport * from './query-builder/join-builder.js';\nexport * from './query-builder/function-module.js';\nexport * from './query-builder/insert-result.js';\nexport * from './query-builder/delete-result.js';\nexport * from './query-builder/update-result.js';\nexport * from './query-builder/on-conflict-builder.js';\nexport * from './query-builder/aggregate-function-builder.js';\nexport * from './query-builder/case-builder.js';\nexport * from './query-builder/json-path-builder.js';\nexport * from './query-builder/merge-query-builder.js';\nexport * from './query-builder/merge-result.js';\nexport * from './query-builder/order-by-item-builder.js';\nexport * from './raw-builder/raw-builder.js';\nexport * from './raw-builder/sql.js';\nexport * from './query-executor/query-executor.js';\nexport * from './query-executor/default-query-executor.js';\nexport * from './query-executor/noop-query-executor.js';\nexport * from './query-executor/query-executor-provider.js';\nexport * from './query-compiler/default-query-compiler.js';\nexport * from './query-compiler/compiled-query.js';\nexport * from './schema/schema.js';\nexport * from './schema/create-table-builder.js';\nexport * from './schema/create-type-builder.js';\nexport * from './schema/drop-table-builder.js';\nexport * from './schema/drop-type-builder.js';\nexport * from './schema/create-index-builder.js';\nexport * from './schema/drop-index-builder.js';\nexport * from './schema/create-schema-builder.js';\nexport * from './schema/drop-schema-builder.js';\nexport * from './schema/column-definition-builder.js';\nexport * from './schema/foreign-key-constraint-builder.js';\nexport * from './schema/alter-table-builder.js';\nexport * from './schema/create-view-builder.js';\nexport * from './schema/refresh-materialized-view-builder.js';\nexport * from './schema/drop-view-builder.js';\nexport * from './schema/alter-column-builder.js';\nexport * from './dynamic/dynamic.js';\nexport * from './dynamic/dynamic-reference-builder.js';\nexport * from './dynamic/dynamic-table-builder.js';\nexport * from './driver/driver.js';\nexport * from './driver/database-connection.js';\nexport * from './driver/connection-provider.js';\nexport * from './driver/default-connection-provider.js';\nexport * from './driver/single-connection-provider.js';\nexport * from './driver/dummy-driver.js';\nexport * from './dialect/dialect.js';\nexport * from './dialect/dialect-adapter.js';\nexport * from './dialect/dialect-adapter-base.js';\nexport * from './dialect/database-introspector.js';\nexport * from './dialect/sqlite/sqlite-dialect.js';\nexport * from './dialect/sqlite/sqlite-dialect-config.js';\nexport * from './dialect/sqlite/sqlite-driver.js';\nexport * from './dialect/postgres/postgres-query-compiler.js';\nexport * from './dialect/postgres/postgres-introspector.js';\nexport * from './dialect/postgres/postgres-adapter.js';\nexport * from './dialect/mysql/mysql-dialect.js';\nexport * from './dialect/mysql/mysql-dialect-config.js';\nexport * from './dialect/mysql/mysql-driver.js';\nexport * from './dialect/mysql/mysql-query-compiler.js';\nexport * from './dialect/mysql/mysql-introspector.js';\nexport * from './dialect/mysql/mysql-adapter.js';\nexport * from './dialect/postgres/postgres-driver.js';\nexport * from './dialect/postgres/postgres-dialect-config.js';\nexport * from './dialect/postgres/postgres-dialect.js';\nexport * from './dialect/sqlite/sqlite-query-compiler.js';\nexport * from './dialect/sqlite/sqlite-introspector.js';\nexport * from './dialect/sqlite/sqlite-adapter.js';\nexport * from './dialect/mssql/mssql-adapter.js';\nexport * from './dialect/mssql/mssql-dialect-config.js';\nexport * from './dialect/mssql/mssql-dialect.js';\nexport * from './dialect/mssql/mssql-driver.js';\nexport * from './dialect/mssql/mssql-introspector.js';\nexport * from './dialect/mssql/mssql-query-compiler.js';\nexport * from './query-compiler/default-query-compiler.js';\nexport * from './query-compiler/query-compiler.js';\nexport * from './migration/migrator.js';\nexport * from './migration/file-migration-provider.js';\nexport * from './plugin/kysely-plugin.js';\nexport * from './plugin/camel-case/camel-case-plugin.js';\nexport * from './plugin/deduplicate-joins/deduplicate-joins-plugin.js';\nexport * from './plugin/with-schema/with-schema-plugin.js';\nexport * from './plugin/parse-json-results/parse-json-results-plugin.js';\nexport * from './plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js';\nexport * from './plugin/handle-empty-in-lists/handle-empty-in-lists.js';\nexport * from './operation-node/add-column-node.js';\nexport * from './operation-node/add-constraint-node.js';\nexport * from './operation-node/add-index-node.js';\nexport * from './operation-node/aggregate-function-node.js';\nexport * from './operation-node/alias-node.js';\nexport * from './operation-node/alter-column-node.js';\nexport * from './operation-node/alter-table-node.js';\nexport * from './operation-node/and-node.js';\nexport * from './operation-node/binary-operation-node.js';\nexport * from './operation-node/case-node.js';\nexport * from './operation-node/cast-node.js';\nexport * from './operation-node/check-constraint-node.js';\nexport * from './operation-node/collate-node.js';\nexport * from './operation-node/column-definition-node.js';\nexport * from './operation-node/column-node.js';\nexport * from './operation-node/column-update-node.js';\nexport * from './operation-node/common-table-expression-name-node.js';\nexport * from './operation-node/common-table-expression-node.js';\nexport * from './operation-node/constraint-node.js';\nexport * from './operation-node/create-index-node.js';\nexport * from './operation-node/create-schema-node.js';\nexport * from './operation-node/create-table-node.js';\nexport * from './operation-node/create-type-node.js';\nexport * from './operation-node/create-view-node.js';\nexport * from './operation-node/refresh-materialized-view-node.js';\nexport * from './operation-node/data-type-node.js';\nexport * from './operation-node/default-insert-value-node.js';\nexport * from './operation-node/default-value-node.js';\nexport * from './operation-node/delete-query-node.js';\nexport * from './operation-node/drop-column-node.js';\nexport * from './operation-node/drop-constraint-node.js';\nexport * from './operation-node/drop-index-node.js';\nexport * from './operation-node/drop-schema-node.js';\nexport * from './operation-node/drop-table-node.js';\nexport * from './operation-node/drop-type-node.js';\nexport * from './operation-node/drop-view-node.js';\nexport * from './operation-node/explain-node.js';\nexport * from './operation-node/fetch-node.js';\nexport * from './operation-node/foreign-key-constraint-node.js';\nexport * from './operation-node/from-node.js';\nexport * from './operation-node/function-node.js';\nexport * from './operation-node/generated-node.js';\nexport * from './operation-node/group-by-item-node.js';\nexport * from './operation-node/group-by-node.js';\nexport * from './operation-node/having-node.js';\nexport * from './operation-node/identifier-node.js';\nexport * from './operation-node/insert-query-node.js';\nexport * from './operation-node/join-node.js';\nexport * from './operation-node/json-operator-chain-node.js';\nexport * from './operation-node/json-path-leg-node.js';\nexport * from './operation-node/json-path-node.js';\nexport * from './operation-node/json-reference-node.js';\nexport * from './operation-node/limit-node.js';\nexport * from './operation-node/list-node.js';\nexport * from './operation-node/matched-node.js';\nexport * from './operation-node/merge-query-node.js';\nexport * from './operation-node/modify-column-node.js';\nexport * from './operation-node/offset-node.js';\nexport * from './operation-node/on-conflict-node.js';\nexport * from './operation-node/on-duplicate-key-node.js';\nexport * from './operation-node/on-node.js';\nexport * from './operation-node/operation-node-source.js';\nexport * from './operation-node/operation-node-transformer.js';\nexport * from './operation-node/operation-node-visitor.js';\nexport * from './operation-node/operation-node.js';\nexport * from './operation-node/operator-node.js';\nexport * from './operation-node/or-action-node.js';\nexport * from './operation-node/or-node.js';\nexport * from './operation-node/order-by-item-node.js';\nexport * from './operation-node/order-by-node.js';\nexport * from './operation-node/output-node.js';\nexport * from './operation-node/over-node.js';\nexport * from './operation-node/parens-node.js';\nexport * from './operation-node/partition-by-item-node.js';\nexport * from './operation-node/partition-by-node.js';\nexport * from './operation-node/primary-key-constraint-node.js';\nexport * from './operation-node/primitive-value-list-node.js';\nexport * from './operation-node/query-node.js';\nexport * from './operation-node/raw-node.js';\nexport * from './operation-node/reference-node.js';\nexport * from './operation-node/references-node.js';\nexport * from './operation-node/rename-column-node.js';\nexport * from './operation-node/rename-constraint-node.js';\nexport * from './operation-node/returning-node.js';\nexport * from './operation-node/schemable-identifier-node.js';\nexport * from './operation-node/select-all-node.js';\nexport * from './operation-node/select-modifier-node.js';\nexport * from './operation-node/select-query-node.js';\nexport * from './operation-node/selection-node.js';\nexport * from './operation-node/set-operation-node.js';\nexport * from './operation-node/simple-reference-expression-node.js';\nexport * from './operation-node/table-node.js';\nexport * from './operation-node/top-node.js';\nexport * from './operation-node/tuple-node.js';\nexport * from './operation-node/unary-operation-node.js';\nexport * from './operation-node/unique-constraint-node.js';\nexport * from './operation-node/update-query-node.js';\nexport * from './operation-node/using-node.js';\nexport * from './operation-node/value-list-node.js';\nexport * from './operation-node/value-node.js';\nexport * from './operation-node/values-node.js';\nexport * from './operation-node/when-node.js';\nexport * from './operation-node/where-node.js';\nexport * from './operation-node/with-node.js';\nexport * from './util/column-type.js';\nexport * from './util/compilable.js';\nexport * from './util/explainable.js';\nexport * from './util/streamable.js';\nexport * from './util/log.js';\nexport * from './util/infer-result.js';\nexport { logOnce } from './util/log-once.js';\nexport { createQueryId } from './util/query-id.js';\n", "//#region src/utils/string.ts\nfunction capitalizeFirstLetter(str) {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n//#endregion\nexport { capitalizeFirstLetter };\n", "import { CompiledQuery, DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, DefaultQueryCompiler, sql } from \"kysely\";\n//#region src/bun-sqlite-dialect.ts\nvar BunSqliteAdapter = class {\n\tget supportsCreateIfNotExists() {\n\t\treturn true;\n\t}\n\tget supportsTransactionalDdl() {\n\t\treturn false;\n\t}\n\tget supportsReturning() {\n\t\treturn true;\n\t}\n\tasync acquireMigrationLock() {}\n\tasync releaseMigrationLock() {}\n\tget supportsOutput() {\n\t\treturn true;\n\t}\n};\nvar BunSqliteDriver = class {\n\t#config;\n\t#connectionMutex = new ConnectionMutex();\n\t#db;\n\t#connection;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tasync init() {\n\t\tthis.#db = this.#config.database;\n\t\tthis.#connection = new BunSqliteConnection(this.#db);\n\t\tif (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);\n\t}\n\tasync acquireConnection() {\n\t\tawait this.#connectionMutex.lock();\n\t\treturn this.#connection;\n\t}\n\tasync beginTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"begin\"));\n\t}\n\tasync commitTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"commit\"));\n\t}\n\tasync rollbackTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"rollback\"));\n\t}\n\tasync releaseConnection() {\n\t\tthis.#connectionMutex.unlock();\n\t}\n\tasync destroy() {\n\t\tthis.#db?.close();\n\t}\n};\nvar BunSqliteConnection = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\texecuteQuery(compiledQuery) {\n\t\tconst { sql, parameters } = compiledQuery;\n\t\tconst stmt = this.#db.prepare(sql);\n\t\treturn Promise.resolve({ rows: stmt.all(parameters) });\n\t}\n\tasync *streamQuery() {\n\t\tthrow new Error(\"Streaming query is not supported by SQLite driver.\");\n\t}\n};\nvar ConnectionMutex = class {\n\t#promise;\n\t#resolve;\n\tasync lock() {\n\t\twhile (this.#promise !== void 0) await this.#promise;\n\t\tthis.#promise = new Promise((resolve) => {\n\t\t\tthis.#resolve = resolve;\n\t\t});\n\t}\n\tunlock() {\n\t\tconst resolve = this.#resolve;\n\t\tthis.#promise = void 0;\n\t\tthis.#resolve = void 0;\n\t\tresolve?.();\n\t}\n};\nvar BunSqliteIntrospector = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\tasync getSchemas() {\n\t\treturn [];\n\t}\n\tasync getTables(options = { withInternalKyselyTables: false }) {\n\t\tlet query = this.#db.selectFrom(\"sqlite_schema\").where(\"type\", \"=\", \"table\").where(\"name\", \"not like\", \"sqlite_%\").select(\"name\").$castTo();\n\t\tif (!options.withInternalKyselyTables) query = query.where(\"name\", \"!=\", DEFAULT_MIGRATION_TABLE).where(\"name\", \"!=\", DEFAULT_MIGRATION_LOCK_TABLE);\n\t\tconst tables = await query.execute();\n\t\treturn Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));\n\t}\n\tasync getMetadata(options) {\n\t\treturn { tables: await this.getTables(options) };\n\t}\n\tasync #getTableMetadata(table) {\n\t\tconst db = this.#db;\n\t\tconst autoIncrementCol = (await db.selectFrom(\"sqlite_master\").where(\"name\", \"=\", table).select(\"sql\").$castTo().execute())[0]?.sql?.split(/[\\(\\),]/)?.find((it) => it.toLowerCase().includes(\"autoincrement\"))?.split(/\\s+/)?.[0]?.replace(/[\"`]/g, \"\");\n\t\treturn {\n\t\t\tname: table,\n\t\t\tcolumns: (await db.selectFrom(sql`pragma_table_info(${table})`.as(\"table_info\")).select([\n\t\t\t\t\"name\",\n\t\t\t\t\"type\",\n\t\t\t\t\"notnull\",\n\t\t\t\t\"dflt_value\"\n\t\t\t]).execute()).map((col) => ({\n\t\t\t\tname: col.name,\n\t\t\t\tdataType: col.type,\n\t\t\t\tisNullable: !col.notnull,\n\t\t\t\tisAutoIncrementing: col.name === autoIncrementCol,\n\t\t\t\thasDefaultValue: col.dflt_value != null\n\t\t\t})),\n\t\t\tisView: true\n\t\t};\n\t}\n};\nvar BunSqliteQueryCompiler = class extends DefaultQueryCompiler {\n\tgetCurrentParameterPlaceholder() {\n\t\treturn \"?\";\n\t}\n\tgetLeftIdentifierWrapper() {\n\t\treturn \"\\\"\";\n\t}\n\tgetRightIdentifierWrapper() {\n\t\treturn \"\\\"\";\n\t}\n\tgetAutoIncrement() {\n\t\treturn \"autoincrement\";\n\t}\n};\nvar BunSqliteDialect = class {\n\t#config;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tcreateDriver() {\n\t\treturn new BunSqliteDriver(this.#config);\n\t}\n\tcreateQueryCompiler() {\n\t\treturn new BunSqliteQueryCompiler();\n\t}\n\tcreateAdapter() {\n\t\treturn new BunSqliteAdapter();\n\t}\n\tcreateIntrospector(db) {\n\t\treturn new BunSqliteIntrospector(db);\n\t}\n};\n//#endregion\nexport { BunSqliteDialect };\n", "import { CompiledQuery, DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, DefaultQueryCompiler, sql } from \"kysely\";\n//#region src/node-sqlite-dialect.ts\nvar NodeSqliteAdapter = class {\n\tget supportsCreateIfNotExists() {\n\t\treturn true;\n\t}\n\tget supportsTransactionalDdl() {\n\t\treturn false;\n\t}\n\tget supportsReturning() {\n\t\treturn true;\n\t}\n\tasync acquireMigrationLock() {}\n\tasync releaseMigrationLock() {}\n\tget supportsOutput() {\n\t\treturn true;\n\t}\n};\nvar NodeSqliteDriver = class {\n\t#config;\n\t#connectionMutex = new ConnectionMutex();\n\t#db;\n\t#connection;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tasync init() {\n\t\tthis.#db = this.#config.database;\n\t\tthis.#connection = new NodeSqliteConnection(this.#db);\n\t\tif (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);\n\t}\n\tasync acquireConnection() {\n\t\tawait this.#connectionMutex.lock();\n\t\treturn this.#connection;\n\t}\n\tasync beginTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"begin\"));\n\t}\n\tasync commitTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"commit\"));\n\t}\n\tasync rollbackTransaction(connection) {\n\t\tawait connection.executeQuery(CompiledQuery.raw(\"rollback\"));\n\t}\n\tasync releaseConnection() {\n\t\tthis.#connectionMutex.unlock();\n\t}\n\tasync destroy() {\n\t\tthis.#db?.close();\n\t}\n};\nvar NodeSqliteConnection = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\texecuteQuery(compiledQuery) {\n\t\tconst { sql, parameters } = compiledQuery;\n\t\tconst rows = this.#db.prepare(sql).all(...parameters);\n\t\treturn Promise.resolve({ rows });\n\t}\n\tasync *streamQuery() {\n\t\tthrow new Error(\"Streaming query is not supported by SQLite driver.\");\n\t}\n};\nvar ConnectionMutex = class {\n\t#promise;\n\t#resolve;\n\tasync lock() {\n\t\twhile (this.#promise !== void 0) await this.#promise;\n\t\tthis.#promise = new Promise((resolve) => {\n\t\t\tthis.#resolve = resolve;\n\t\t});\n\t}\n\tunlock() {\n\t\tconst resolve = this.#resolve;\n\t\tthis.#promise = void 0;\n\t\tthis.#resolve = void 0;\n\t\tresolve?.();\n\t}\n};\nvar NodeSqliteIntrospector = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\tasync getSchemas() {\n\t\treturn [];\n\t}\n\tasync getTables(options = { withInternalKyselyTables: false }) {\n\t\tlet query = this.#db.selectFrom(\"sqlite_schema\").where(\"type\", \"=\", \"table\").where(\"name\", \"not like\", \"sqlite_%\").select(\"name\").$castTo();\n\t\tif (!options.withInternalKyselyTables) query = query.where(\"name\", \"!=\", DEFAULT_MIGRATION_TABLE).where(\"name\", \"!=\", DEFAULT_MIGRATION_LOCK_TABLE);\n\t\tconst tables = await query.execute();\n\t\treturn Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));\n\t}\n\tasync getMetadata(options) {\n\t\treturn { tables: await this.getTables(options) };\n\t}\n\tasync #getTableMetadata(table) {\n\t\tconst db = this.#db;\n\t\tconst autoIncrementCol = (await db.selectFrom(\"sqlite_master\").where(\"name\", \"=\", table).select(\"sql\").$castTo().execute())[0]?.sql?.split(/[\\(\\),]/)?.find((it) => it.toLowerCase().includes(\"autoincrement\"))?.split(/\\s+/)?.[0]?.replace(/[\"`]/g, \"\");\n\t\treturn {\n\t\t\tname: table,\n\t\t\tcolumns: (await db.selectFrom(sql`pragma_table_info(${table})`.as(\"table_info\")).select([\n\t\t\t\t\"name\",\n\t\t\t\t\"type\",\n\t\t\t\t\"notnull\",\n\t\t\t\t\"dflt_value\"\n\t\t\t]).execute()).map((col) => ({\n\t\t\t\tname: col.name,\n\t\t\t\tdataType: col.type,\n\t\t\t\tisNullable: !col.notnull,\n\t\t\t\tisAutoIncrementing: col.name === autoIncrementCol,\n\t\t\t\thasDefaultValue: col.dflt_value != null\n\t\t\t})),\n\t\t\tisView: true\n\t\t};\n\t}\n};\nvar NodeSqliteQueryCompiler = class extends DefaultQueryCompiler {\n\tgetCurrentParameterPlaceholder() {\n\t\treturn \"?\";\n\t}\n\tgetLeftIdentifierWrapper() {\n\t\treturn \"\\\"\";\n\t}\n\tgetRightIdentifierWrapper() {\n\t\treturn \"\\\"\";\n\t}\n\tgetAutoIncrement() {\n\t\treturn \"autoincrement\";\n\t}\n};\nvar NodeSqliteDialect = class {\n\t#config;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tcreateDriver() {\n\t\treturn new NodeSqliteDriver(this.#config);\n\t}\n\tcreateQueryCompiler() {\n\t\treturn new NodeSqliteQueryCompiler();\n\t}\n\tcreateAdapter() {\n\t\treturn new NodeSqliteAdapter();\n\t}\n\tcreateIntrospector(db) {\n\t\treturn new NodeSqliteIntrospector(db);\n\t}\n};\n//#endregion\nexport { NodeSqliteDialect };\n", "import { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, SqliteAdapter, SqliteQueryCompiler } from \"kysely\";\n//#region src/d1-sqlite-dialect.ts\nvar D1SqliteAdapter = class extends SqliteAdapter {};\nvar D1SqliteDriver = class {\n\t#config;\n\t#connection;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tasync init() {\n\t\tthis.#connection = new D1SqliteConnection(this.#config.database);\n\t\tif (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);\n\t}\n\tasync acquireConnection() {\n\t\treturn this.#connection;\n\t}\n\tasync beginTransaction() {\n\t\tthrow new Error(\"D1 does not support interactive transactions. Use the D1 batch() API instead.\");\n\t}\n\tasync commitTransaction() {\n\t\tthrow new Error(\"D1 does not support interactive transactions. Use the D1 batch() API instead.\");\n\t}\n\tasync rollbackTransaction() {\n\t\tthrow new Error(\"D1 does not support interactive transactions. Use the D1 batch() API instead.\");\n\t}\n\tasync releaseConnection() {}\n\tasync destroy() {}\n};\nvar D1SqliteConnection = class {\n\t#db;\n\tconstructor(db) {\n\t\tthis.#db = db;\n\t}\n\tasync executeQuery(compiledQuery) {\n\t\tconst results = await this.#db.prepare(compiledQuery.sql).bind(...compiledQuery.parameters).all();\n\t\tconst numAffectedRows = results.meta.changes != null ? BigInt(results.meta.changes) : void 0;\n\t\treturn {\n\t\t\tinsertId: results.meta.last_row_id === void 0 || results.meta.last_row_id === null ? void 0 : BigInt(results.meta.last_row_id),\n\t\t\trows: results?.results || [],\n\t\t\tnumAffectedRows\n\t\t};\n\t}\n\tasync *streamQuery() {\n\t\tthrow new Error(\"D1 does not support streaming queries.\");\n\t}\n};\nvar D1SqliteIntrospector = class {\n\t#db;\n\t#d1;\n\tconstructor(db, d1) {\n\t\tthis.#db = db;\n\t\tthis.#d1 = d1;\n\t}\n\tasync getSchemas() {\n\t\treturn [];\n\t}\n\tasync getTables(options = { withInternalKyselyTables: false }) {\n\t\tlet query = this.#db.selectFrom(\"sqlite_master\").where(\"type\", \"in\", [\"table\", \"view\"]).where(\"name\", \"not like\", \"sqlite_%\").where(\"name\", \"not like\", \"_cf_%\").select([\n\t\t\t\"name\",\n\t\t\t\"type\",\n\t\t\t\"sql\"\n\t\t]).$castTo();\n\t\tif (!options.withInternalKyselyTables) query = query.where(\"name\", \"!=\", DEFAULT_MIGRATION_TABLE).where(\"name\", \"!=\", DEFAULT_MIGRATION_LOCK_TABLE);\n\t\tconst tables = await query.execute();\n\t\tif (tables.length === 0) return [];\n\t\tconst statements = tables.map((table) => this.#d1.prepare(\"SELECT * FROM pragma_table_info(?)\").bind(table.name));\n\t\tconst batchResults = await this.#d1.batch(statements);\n\t\treturn tables.map((table, index) => {\n\t\t\tconst columnInfo = batchResults[index]?.results ?? [];\n\t\t\tlet autoIncrementCol = table.sql?.split(/[(),]/)?.find((it) => it.toLowerCase().includes(\"autoincrement\"))?.split(/\\s+/)?.filter(Boolean)?.[0]?.replace(/[\"`]/g, \"\");\n\t\t\tif (!autoIncrementCol) {\n\t\t\t\tconst pkCols = columnInfo.filter((r) => r.pk > 0);\n\t\t\t\tconst singlePk = pkCols.length === 1 ? pkCols[0] : void 0;\n\t\t\t\tif (singlePk && singlePk.type.toLowerCase() === \"integer\") autoIncrementCol = singlePk.name;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tname: table.name,\n\t\t\t\tisView: table.type === \"view\",\n\t\t\t\tcolumns: columnInfo.map((col) => ({\n\t\t\t\t\tname: col.name,\n\t\t\t\t\tdataType: col.type,\n\t\t\t\t\tisNullable: !col.notnull,\n\t\t\t\t\tisAutoIncrementing: col.name === autoIncrementCol,\n\t\t\t\t\thasDefaultValue: col.dflt_value != null\n\t\t\t\t}))\n\t\t\t};\n\t\t});\n\t}\n\tasync getMetadata(options) {\n\t\treturn { tables: await this.getTables(options) };\n\t}\n};\nvar D1SqliteQueryCompiler = class extends SqliteQueryCompiler {};\nvar D1SqliteDialect = class {\n\t#config;\n\tconstructor(config) {\n\t\tthis.#config = { ...config };\n\t}\n\tcreateDriver() {\n\t\treturn new D1SqliteDriver(this.#config);\n\t}\n\tcreateQueryCompiler() {\n\t\treturn new D1SqliteQueryCompiler();\n\t}\n\tcreateAdapter() {\n\t\treturn new D1SqliteAdapter();\n\t}\n\tcreateIntrospector(db) {\n\t\treturn new D1SqliteIntrospector(db, this.#config.database);\n\t}\n};\n//#endregion\nexport { D1SqliteDialect };\n", "import { Kysely, MssqlDialect, MysqlDialect, PostgresDialect, SqliteDialect, sql } from \"kysely\";\nimport { createAdapterFactory } from \"@better-auth/core/db/adapter\";\nimport { capitalizeFirstLetter } from \"@better-auth/core/utils/string\";\n//#region src/dialect.ts\nfunction getKyselyDatabaseType(db) {\n\tif (!db) return null;\n\tif (\"dialect\" in db) return getKyselyDatabaseType(db.dialect);\n\tif (\"createDriver\" in db) {\n\t\tif (db instanceof SqliteDialect) return \"sqlite\";\n\t\tif (db instanceof MysqlDialect) return \"mysql\";\n\t\tif (db instanceof PostgresDialect) return \"postgres\";\n\t\tif (db instanceof MssqlDialect) return \"mssql\";\n\t}\n\tif (\"aggregate\" in db) return \"sqlite\";\n\tif (\"getConnection\" in db) return \"mysql\";\n\tif (\"connect\" in db) return \"postgres\";\n\tif (\"fileControl\" in db) return \"sqlite\";\n\tif (\"open\" in db && \"close\" in db && \"prepare\" in db) return \"sqlite\";\n\tif (\"batch\" in db && \"exec\" in db && \"prepare\" in db) return \"sqlite\";\n\treturn null;\n}\nconst createKyselyAdapter = async (config) => {\n\tconst db = config.database;\n\tif (!db) return {\n\t\tkysely: null,\n\t\tdatabaseType: null,\n\t\ttransaction: void 0\n\t};\n\tif (\"db\" in db) return {\n\t\tkysely: db.db,\n\t\tdatabaseType: db.type,\n\t\ttransaction: db.transaction\n\t};\n\tif (\"dialect\" in db) return {\n\t\tkysely: new Kysely({ dialect: db.dialect }),\n\t\tdatabaseType: db.type,\n\t\ttransaction: db.transaction\n\t};\n\tlet dialect = void 0;\n\tconst databaseType = getKyselyDatabaseType(db);\n\tif (\"createDriver\" in db) dialect = db;\n\tif (\"aggregate\" in db && !(\"createSession\" in db)) dialect = new SqliteDialect({ database: db });\n\tif (\"getConnection\" in db) dialect = new MysqlDialect(db);\n\tif (\"connect\" in db) dialect = new PostgresDialect({ pool: db });\n\tif (\"fileControl\" in db) {\n\t\tconst { BunSqliteDialect } = await import(\"./bun-sqlite-dialect-na--YwnN.mjs\");\n\t\tdialect = new BunSqliteDialect({ database: db });\n\t}\n\tif (\"createSession\" in db) {\n\t\tlet DatabaseSync = void 0;\n\t\ttry {\n\t\t\tconst nodeSqlite = \"node:sqlite\";\n\t\t\t({DatabaseSync} = await import(\n\t\t\t\t/* @vite-ignore */\n\t\t\t\t/* webpackIgnore: true */\n\t\t\t\tnodeSqlite\n));\n\t\t} catch (error) {\n\t\t\tif (error !== null && typeof error === \"object\" && \"code\" in error && error.code !== \"ERR_UNKNOWN_BUILTIN_MODULE\") throw error;\n\t\t}\n\t\tif (DatabaseSync && db instanceof DatabaseSync) {\n\t\t\tconst { NodeSqliteDialect } = await import(\"./node-sqlite-dialect.mjs\");\n\t\t\tdialect = new NodeSqliteDialect({ database: db });\n\t\t}\n\t}\n\tif (\"batch\" in db && \"exec\" in db && \"prepare\" in db) {\n\t\tconst { D1SqliteDialect } = await import(\"./d1-sqlite-dialect-C2B7YsIT.mjs\");\n\t\tdialect = new D1SqliteDialect({ database: db });\n\t}\n\treturn {\n\t\tkysely: dialect ? new Kysely({ dialect }) : null,\n\t\tdatabaseType,\n\t\ttransaction: void 0\n\t};\n};\n//#endregion\n//#region src/query-builders.ts\n/**\n* Case-insensitive ILIKE/LIKE for pattern matching.\n* Uses ILIKE on PostgreSQL, LOWER()+LIKE on MySQL/SQLite/MSSQL.\n*/\nfunction insensitiveIlike(columnRef, pattern, dbType) {\n\treturn dbType === \"postgres\" ? sql`${sql.ref(columnRef)} ILIKE ${pattern}` : sql`LOWER(${sql.ref(columnRef)}) LIKE LOWER(${pattern})`;\n}\n/**\n* Case-insensitive IN for string arrays.\n* Returns { lhs, values } for use with eb(lhs, \"in\", values).\n*/\nfunction insensitiveIn(columnRef, values) {\n\treturn {\n\t\tlhs: sql`LOWER(${sql.ref(columnRef)})`,\n\t\tvalues: values.map((v) => v.toLowerCase())\n\t};\n}\n/**\n* Case-insensitive NOT IN for string arrays.\n*/\nfunction insensitiveNotIn(columnRef, values) {\n\treturn {\n\t\tlhs: sql`LOWER(${sql.ref(columnRef)})`,\n\t\tvalues: values.map((v) => v.toLowerCase())\n\t};\n}\n/**\n* Case-insensitive equality for strings.\n* Returns { lhs, value } for use with eb(lhs, \"=\", value).\n*/\nfunction insensitiveEq(columnRef, value) {\n\treturn {\n\t\tlhs: sql`LOWER(${sql.ref(columnRef)})`,\n\t\tvalue: value.toLowerCase()\n\t};\n}\n/**\n* Case-insensitive inequality for strings.\n*/\nfunction insensitiveNe(columnRef, value) {\n\treturn {\n\t\tlhs: sql`LOWER(${sql.ref(columnRef)})`,\n\t\tvalue: value.toLowerCase()\n\t};\n}\n//#endregion\n//#region src/kysely-adapter.ts\nconst kyselyAdapter = (db, config) => {\n\tlet lazyOptions = null;\n\tconst createCustomAdapter = (db) => {\n\t\treturn ({ getFieldName, schema, getDefaultFieldName, getDefaultModelName, getFieldAttributes, getModelName }) => {\n\t\t\tconst selectAllJoins = (join) => {\n\t\t\t\tconst allSelects = [];\n\t\t\t\tconst allSelectsStr = [];\n\t\t\t\tif (join) for (const [joinModel, _] of Object.entries(join)) {\n\t\t\t\t\tconst fields = schema[getDefaultModelName(joinModel)]?.fields;\n\t\t\t\t\tconst [_joinModelSchema, joinModelName] = joinModel.includes(\".\") ? joinModel.split(\".\") : [void 0, joinModel];\n\t\t\t\t\tif (!fields) continue;\n\t\t\t\t\tfields.id = { type: \"string\" };\n\t\t\t\t\tfor (const [field, fieldAttr] of Object.entries(fields)) {\n\t\t\t\t\t\tallSelects.push(sql`${sql.ref(`join_${joinModelName}`)}.${sql.ref(fieldAttr.fieldName || field)} as ${sql.ref(`_joined_${joinModelName}_${fieldAttr.fieldName || field}`)}`);\n\t\t\t\t\t\tallSelectsStr.push({\n\t\t\t\t\t\t\tjoinModel,\n\t\t\t\t\t\t\tjoinModelRef: joinModelName,\n\t\t\t\t\t\t\tfieldName: fieldAttr.fieldName || field\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tallSelectsStr,\n\t\t\t\t\tallSelects\n\t\t\t\t};\n\t\t\t};\n\t\t\tconst withReturning = async (values, builder, model, where) => {\n\t\t\t\tlet res;\n\t\t\t\tif (config?.type === \"mysql\") {\n\t\t\t\t\tawait builder.execute();\n\t\t\t\t\tconst field = values.id ? \"id\" : where.length > 0 && where[0]?.field ? where[0].field : \"id\";\n\t\t\t\t\tif (!values.id && where.length === 0) {\n\t\t\t\t\t\tres = await db.selectFrom(model).selectAll().orderBy(getFieldName({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tfield\n\t\t\t\t\t\t}), \"desc\").limit(1).executeTakeFirst();\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tconst value = values[field] !== void 0 ? values[field] : where[0]?.value;\n\t\t\t\t\tres = await db.selectFrom(model).selectAll().orderBy(getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield\n\t\t\t\t\t}), \"desc\").where(getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield\n\t\t\t\t\t}), value === null ? \"is\" : \"=\", value).limit(1).executeTakeFirst();\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tif (config?.type === \"mssql\") {\n\t\t\t\t\tres = await builder.outputAll(\"inserted\").executeTakeFirst();\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tres = await builder.returningAll().executeTakeFirst();\n\t\t\t\treturn res;\n\t\t\t};\n\t\t\tfunction convertWhereClause(model, w) {\n\t\t\t\tif (!w) return {\n\t\t\t\t\tand: null,\n\t\t\t\t\tor: null\n\t\t\t\t};\n\t\t\t\tconst conditions = {\n\t\t\t\t\tand: [],\n\t\t\t\t\tor: []\n\t\t\t\t};\n\t\t\t\tw.forEach((condition) => {\n\t\t\t\t\tconst { field: _field, value: _value, operator = \"eq\", connector = \"AND\", mode = \"sensitive\" } = condition;\n\t\t\t\t\tconst value = _value;\n\t\t\t\t\tconst field = getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield: _field\n\t\t\t\t\t});\n\t\t\t\t\tconst isInsensitive = mode === \"insensitive\" && (typeof value === \"string\" || Array.isArray(value) && value.every((v) => typeof v === \"string\"));\n\t\t\t\t\tconst expr = (eb) => {\n\t\t\t\t\t\tconst f = `${model}.${field}`;\n\t\t\t\t\t\tif (operator.toLowerCase() === \"in\") {\n\t\t\t\t\t\t\tif (isInsensitive) {\n\t\t\t\t\t\t\t\tconst { lhs, values } = insensitiveIn(f, Array.isArray(value) ? value : [value]);\n\t\t\t\t\t\t\t\treturn eb(lhs, \"in\", values);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn eb(f, \"in\", Array.isArray(value) ? value : [value]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator.toLowerCase() === \"not_in\") {\n\t\t\t\t\t\t\tif (isInsensitive) {\n\t\t\t\t\t\t\t\tconst { lhs, values } = insensitiveNotIn(f, Array.isArray(value) ? value : [value]);\n\t\t\t\t\t\t\t\treturn eb(lhs, \"not in\", values);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn eb(f, \"not in\", Array.isArray(value) ? value : [value]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"contains\") {\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") return insensitiveIlike(f, `%${value}%`, config?.type);\n\t\t\t\t\t\t\treturn eb(f, \"like\", `%${value}%`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"starts_with\") {\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") return insensitiveIlike(f, `${value}%`, config?.type);\n\t\t\t\t\t\t\treturn eb(f, \"like\", `${value}%`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"ends_with\") {\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") return insensitiveIlike(f, `%${value}`, config?.type);\n\t\t\t\t\t\t\treturn eb(f, \"like\", `%${value}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"eq\") {\n\t\t\t\t\t\t\tif (value === null) return eb(f, \"is\", null);\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") {\n\t\t\t\t\t\t\t\tconst { lhs, value: v } = insensitiveEq(f, value);\n\t\t\t\t\t\t\t\treturn eb(lhs, \"=\", v);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn eb(f, \"=\", value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"ne\") {\n\t\t\t\t\t\t\tif (value === null) return eb(f, \"is not\", null);\n\t\t\t\t\t\t\tif (isInsensitive && typeof value === \"string\") {\n\t\t\t\t\t\t\t\tconst { lhs, value: v } = insensitiveNe(f, value);\n\t\t\t\t\t\t\t\treturn eb(lhs, \"<>\", v);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn eb(f, \"<>\", value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (operator === \"gt\") return eb(f, \">\", value);\n\t\t\t\t\t\tif (operator === \"gte\") return eb(f, \">=\", value);\n\t\t\t\t\t\tif (operator === \"lt\") return eb(f, \"<\", value);\n\t\t\t\t\t\tif (operator === \"lte\") return eb(f, \"<=\", value);\n\t\t\t\t\t\treturn eb(f, operator, value);\n\t\t\t\t\t};\n\t\t\t\t\tif (connector === \"OR\") conditions.or.push(expr);\n\t\t\t\t\telse conditions.and.push(expr);\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tand: conditions.and.length ? conditions.and : null,\n\t\t\t\t\tor: conditions.or.length ? conditions.or : null\n\t\t\t\t};\n\t\t\t}\n\t\t\tfunction processJoinedResults(rows, joinConfig, allSelectsStr) {\n\t\t\t\tif (!joinConfig || !rows.length) return rows;\n\t\t\t\tconst groupedByMainId = /* @__PURE__ */ new Map();\n\t\t\t\tfor (const currentRow of rows) {\n\t\t\t\t\tconst mainModelFields = {};\n\t\t\t\t\tconst joinedModelFields = {};\n\t\t\t\t\tfor (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[getModelName(joinModel)] = {};\n\t\t\t\t\tfor (const [key, value] of Object.entries(currentRow)) {\n\t\t\t\t\t\tconst keyStr = String(key);\n\t\t\t\t\t\tlet assigned = false;\n\t\t\t\t\t\tfor (const { joinModel, fieldName, joinModelRef } of allSelectsStr) if (keyStr === `_joined_${joinModelRef}_${fieldName}` || keyStr === `_Joined${capitalizeFirstLetter(joinModelRef)}${capitalizeFirstLetter(fieldName)}`) {\n\t\t\t\t\t\t\tjoinedModelFields[getModelName(joinModel)][getFieldName({\n\t\t\t\t\t\t\t\tmodel: joinModel,\n\t\t\t\t\t\t\t\tfield: fieldName\n\t\t\t\t\t\t\t})] = value;\n\t\t\t\t\t\t\tassigned = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!assigned) mainModelFields[key] = value;\n\t\t\t\t\t}\n\t\t\t\t\tconst mainId = mainModelFields.id;\n\t\t\t\t\tif (!mainId) continue;\n\t\t\t\t\tif (!groupedByMainId.has(mainId)) {\n\t\t\t\t\t\tconst entry = { ...mainModelFields };\n\t\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry[getModelName(joinModel)] = joinAttr.relation === \"one-to-one\" ? null : [];\n\t\t\t\t\t\tgroupedByMainId.set(mainId, entry);\n\t\t\t\t\t}\n\t\t\t\t\tconst entry = groupedByMainId.get(mainId);\n\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(joinConfig)) {\n\t\t\t\t\t\tconst isUnique = joinAttr.relation === \"one-to-one\";\n\t\t\t\t\t\tconst limit = joinAttr.limit ?? 100;\n\t\t\t\t\t\tconst joinedObj = joinedModelFields[getModelName(joinModel)];\n\t\t\t\t\t\tconst hasData = joinedObj && Object.keys(joinedObj).length > 0 && Object.values(joinedObj).some((value) => value !== null && value !== void 0);\n\t\t\t\t\t\tif (isUnique) entry[getModelName(joinModel)] = hasData ? joinedObj : null;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\t\tif (Array.isArray(entry[joinModelName]) && hasData) {\n\t\t\t\t\t\t\t\tif (entry[joinModelName].length >= limit) continue;\n\t\t\t\t\t\t\t\tconst idFieldName = getFieldName({\n\t\t\t\t\t\t\t\t\tmodel: joinModel,\n\t\t\t\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst joinedId = joinedObj[idFieldName];\n\t\t\t\t\t\t\t\tif (joinedId) {\n\t\t\t\t\t\t\t\t\tif (!entry[joinModelName].some((item) => item[idFieldName] === joinedId) && entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj);\n\t\t\t\t\t\t\t\t} else if (entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst result = Array.from(groupedByMainId.values());\n\t\t\t\tfor (const entry of result) for (const [joinModel, joinAttr] of Object.entries(joinConfig)) if (joinAttr.relation !== \"one-to-one\") {\n\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\tif (Array.isArray(entry[joinModelName])) {\n\t\t\t\t\t\tconst limit = joinAttr.limit ?? 100;\n\t\t\t\t\t\tif (entry[joinModelName].length > limit) entry[joinModelName] = entry[joinModelName].slice(0, limit);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tasync create({ data, model }) {\n\t\t\t\t\treturn await withReturning(data, db.insertInto(model).values(data), model, []);\n\t\t\t\t},\n\t\t\t\tasync findOne({ model, where, select, join }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.selectFrom((eb) => {\n\t\t\t\t\t\tlet b = eb.selectFrom(model);\n\t\t\t\t\t\tif (and) b = b.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\t\tif (or) b = b.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\t\tif (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tfield\n\t\t\t\t\t\t})));\n\t\t\t\t\t\telse b = b.selectAll();\n\t\t\t\t\t\treturn b.as(\"primary\");\n\t\t\t\t\t}).selectAll(\"primary\");\n\t\t\t\t\tif (join) for (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\tconst [_joinModelSchema, joinModelName] = joinModel.includes(\".\") ? joinModel.split(\".\") : [void 0, joinModel];\n\t\t\t\t\t\tquery = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join) => join.onRef(`join_${joinModelName}.${joinAttr.on.to}`, \"=\", `primary.${joinAttr.on.from}`));\n\t\t\t\t\t}\n\t\t\t\t\tconst { allSelectsStr, allSelects } = selectAllJoins(join);\n\t\t\t\t\tquery = query.select(allSelects);\n\t\t\t\t\tconst res = await query.execute();\n\t\t\t\t\tif (!res || !Array.isArray(res) || res.length === 0) return null;\n\t\t\t\t\tconst row = res[0];\n\t\t\t\t\tif (join) return processJoinedResults(res, join, allSelectsStr)[0];\n\t\t\t\t\treturn row;\n\t\t\t\t},\n\t\t\t\tasync findMany({ model, where, limit, select, offset, sortBy, join }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.selectFrom((eb) => {\n\t\t\t\t\t\tlet b = eb.selectFrom(model);\n\t\t\t\t\t\tif (config?.type === \"mssql\") {\n\t\t\t\t\t\t\tif (offset !== void 0) {\n\t\t\t\t\t\t\t\tif (!sortBy) b = b.orderBy(getFieldName({\n\t\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\tb = b.offset(offset).fetch(limit || 100);\n\t\t\t\t\t\t\t} else if (limit !== void 0) b = b.top(limit);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (limit !== void 0) b = b.limit(limit);\n\t\t\t\t\t\t\tif (offset !== void 0) b = b.offset(offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (sortBy?.field) b = b.orderBy(`${getFieldName({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tfield: sortBy.field\n\t\t\t\t\t\t})}`, sortBy.direction);\n\t\t\t\t\t\tif (and) b = b.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\t\tif (or) b = b.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\t\tif (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tfield\n\t\t\t\t\t\t})));\n\t\t\t\t\t\telse b = b.selectAll();\n\t\t\t\t\t\treturn b.as(\"primary\");\n\t\t\t\t\t}).selectAll(\"primary\");\n\t\t\t\t\tif (join) for (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\tconst [_joinModelSchema, joinModelName] = joinModel.includes(\".\") ? joinModel.split(\".\") : [void 0, joinModel];\n\t\t\t\t\t\tquery = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join) => join.onRef(`join_${joinModelName}.${joinAttr.on.to}`, \"=\", `primary.${joinAttr.on.from}`));\n\t\t\t\t\t}\n\t\t\t\t\tconst { allSelectsStr, allSelects } = selectAllJoins(join);\n\t\t\t\t\tquery = query.select(allSelects);\n\t\t\t\t\tif (sortBy?.field) query = query.orderBy(`${getFieldName({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tfield: sortBy.field\n\t\t\t\t\t})}`, sortBy.direction);\n\t\t\t\t\tconst res = await query.execute();\n\t\t\t\t\tif (!res) return [];\n\t\t\t\t\tif (join) return processJoinedResults(res, join, allSelectsStr);\n\t\t\t\t\treturn res;\n\t\t\t\t},\n\t\t\t\tasync update({ model, where, update: values }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.updateTable(model).set(values);\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\treturn await withReturning(values, query, model, where);\n\t\t\t\t},\n\t\t\t\tasync updateMany({ model, where, update: values }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.updateTable(model).set(values);\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\tconst res = (await query.executeTakeFirst()).numUpdatedRows;\n\t\t\t\t\treturn res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res);\n\t\t\t\t},\n\t\t\t\tasync count({ model, where }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.selectFrom(model).select(db.fn.count(\"id\").as(\"count\"));\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\tconst res = await query.execute();\n\t\t\t\t\tif (typeof res[0].count === \"number\") return res[0].count;\n\t\t\t\t\tif (typeof res[0].count === \"bigint\") return Number(res[0].count);\n\t\t\t\t\treturn parseInt(res[0].count);\n\t\t\t\t},\n\t\t\t\tasync delete({ model, where }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.deleteFrom(model);\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\tawait query.execute();\n\t\t\t\t},\n\t\t\t\tasync deleteMany({ model, where }) {\n\t\t\t\t\tconst { and, or } = convertWhereClause(model, where);\n\t\t\t\t\tlet query = db.deleteFrom(model);\n\t\t\t\t\tif (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t\t\tif (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t\t\tconst res = (await query.executeTakeFirst()).numDeletedRows;\n\t\t\t\t\treturn res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res);\n\t\t\t\t},\n\t\t\t\toptions: config\n\t\t\t};\n\t\t};\n\t};\n\tlet adapterOptions = null;\n\tadapterOptions = {\n\t\tconfig: {\n\t\t\tadapterId: \"kysely\",\n\t\t\tadapterName: \"Kysely Adapter\",\n\t\t\tusePlural: config?.usePlural,\n\t\t\tdebugLogs: config?.debugLogs,\n\t\t\tsupportsBooleans: config?.type === \"sqlite\" || config?.type === \"mssql\" || config?.type === \"mysql\" || !config?.type ? false : true,\n\t\t\tsupportsDates: config?.type === \"sqlite\" || config?.type === \"mssql\" || !config?.type ? false : true,\n\t\t\tsupportsJSON: config?.type === \"postgres\" ? true : false,\n\t\t\tsupportsArrays: false,\n\t\t\tsupportsUUIDs: config?.type === \"postgres\" ? true : false,\n\t\t\ttransaction: config?.transaction ? (cb) => db.transaction().execute((trx) => {\n\t\t\t\treturn cb(createAdapterFactory({\n\t\t\t\t\tconfig: adapterOptions.config,\n\t\t\t\t\tadapter: createCustomAdapter(trx)\n\t\t\t\t})(lazyOptions));\n\t\t\t}) : false\n\t\t},\n\t\tadapter: createCustomAdapter(db)\n\t};\n\tconst adapter = createAdapterFactory(adapterOptions);\n\treturn (options) => {\n\t\tlazyOptions = options;\n\t\treturn adapter(options);\n\t};\n};\n//#endregion\nexport { createKyselyAdapter, getKyselyDatabaseType, kyselyAdapter };\n", "export * from \"@better-auth/kysely-adapter\";\nexport {};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Application-Level Cache Protocol\n * \n * Multi-tier caching strategy for application data.\n * Supports Memory, Redis, Memcached, and CDN.\n * \n * ## Caching in ObjectStack\n * \n * **Application Cache (`system/cache.zod.ts`) - This File**\n * - **Purpose**: Cache computed data, query results, aggregations\n * - **Technologies**: Redis, Memcached, in-memory LRU\n * - **Configuration**: TTL, eviction policies, cache warming\n * - **Use case**: Cache expensive database queries, computed values\n * - **Scope**: Application layer, server-side data storage\n * \n * **HTTP Cache (`api/http-cache.zod.ts`)**\n * - **Purpose**: Cache API responses at HTTP protocol level\n * - **Technologies**: HTTP headers (ETag, Last-Modified, Cache-Control), CDN\n * - **Configuration**: Cache-Control headers, validation tokens\n * - **Use case**: Reduce API response time for repeated metadata requests\n * - **Scope**: HTTP layer, client-server communication\n * \n * @see ../../api/http-cache.zod.ts for HTTP-level caching\n */\nexport const CacheStrategySchema = z.enum([\n 'lru', // Least Recently Used\n 'lfu', // Least Frequently Used\n 'fifo', // First In First Out\n 'ttl', // Time To Live only\n 'adaptive', // Dynamic strategy selection\n]).describe('Cache eviction strategy');\n\nexport type CacheStrategy = z.infer;\n\nexport const CacheTierSchema = z.object({\n name: z.string().describe('Unique cache tier name'),\n type: z.enum(['memory', 'redis', 'memcached', 'cdn']).describe('Cache backend type'),\n maxSize: z.number().optional().describe('Max size in MB'),\n ttl: z.number().default(300).describe('Default TTL in seconds'),\n strategy: CacheStrategySchema.default('lru').describe('Eviction strategy'),\n warmup: z.boolean().default(false).describe('Pre-populate cache on startup'),\n}).describe('Configuration for a single cache tier in the hierarchy');\n\nexport type CacheTier = z.infer;\nexport type CacheTierInput = z.input;\n\nexport const CacheInvalidationSchema = z.object({\n trigger: z.enum(['create', 'update', 'delete', 'manual']).describe('Event that triggers invalidation'),\n scope: z.enum(['key', 'pattern', 'tag', 'all']).describe('Invalidation scope'),\n pattern: z.string().optional().describe('Key pattern for pattern-based invalidation'),\n tags: z.array(z.string()).optional().describe('Cache tags to invalidate'),\n}).describe('Rule defining when and how cached entries are invalidated');\n\nexport type CacheInvalidation = z.infer;\n\nexport const CacheConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable application-level caching'),\n tiers: z.array(CacheTierSchema).describe('Ordered cache tier hierarchy'),\n invalidation: z.array(CacheInvalidationSchema).describe('Cache invalidation rules'),\n prefetch: z.boolean().default(false).describe('Enable cache prefetching'),\n compression: z.boolean().default(false).describe('Enable data compression in cache'),\n encryption: z.boolean().default(false).describe('Enable encryption for cached data'),\n}).describe('Top-level application cache configuration');\n\nexport type CacheConfig = z.infer;\nexport type CacheConfigInput = z.input;\n\n/**\n * Distributed Cache Consistency Schema\n *\n * Defines write strategies for distributed cache consistency.\n *\n * - **write_through**: Write to cache and backend simultaneously\n * - **write_behind**: Write to cache first, async persist to backend\n * - **write_around**: Write to backend only, cache on next read\n * - **refresh_ahead**: Proactively refresh expiring entries before TTL\n */\nexport const CacheConsistencySchema = z.enum([\n 'write_through',\n 'write_behind',\n 'write_around',\n 'refresh_ahead',\n]).describe('Distributed cache write consistency strategy');\n\nexport type CacheConsistency = z.infer;\n\n/**\n * Cache Avalanche Prevention Schema\n *\n * Strategies to prevent cache stampede/avalanche when many keys expire simultaneously.\n *\n * @example\n * ```typescript\n * const prevention: CacheAvalanchePrevention = {\n * jitterTtl: { enabled: true, maxJitterSeconds: 60 },\n * circuitBreaker: { enabled: true, failureThreshold: 5, resetTimeout: 30 },\n * lockout: { enabled: true, lockTimeoutMs: 5000 },\n * };\n * ```\n */\nexport const CacheAvalanchePreventionSchema = z.object({\n /** TTL jitter to stagger cache expiration */\n jitterTtl: z.object({\n enabled: z.boolean().default(false).describe('Add random jitter to TTL values'),\n maxJitterSeconds: z.number().default(60).describe('Maximum jitter added to TTL in seconds'),\n }).optional().describe('TTL jitter to prevent simultaneous expiration'),\n\n /** Circuit breaker to protect backend under cache pressure */\n circuitBreaker: z.object({\n enabled: z.boolean().default(false).describe('Enable circuit breaker for backend protection'),\n failureThreshold: z.number().default(5).describe('Failures before circuit opens'),\n resetTimeout: z.number().default(30).describe('Seconds before half-open state'),\n }).optional().describe('Circuit breaker for backend protection'),\n\n /** Cache lock to prevent thundering herd on key miss */\n lockout: z.object({\n enabled: z.boolean().default(false).describe('Enable cache locking for key regeneration'),\n lockTimeoutMs: z.number().default(5000).describe('Maximum lock wait time in milliseconds'),\n }).optional().describe('Lock-based stampede prevention'),\n}).describe('Cache avalanche/stampede prevention configuration');\n\nexport type CacheAvalanchePrevention = z.infer;\n\n/**\n * Cache Warmup Strategy Schema\n *\n * Defines how cache is pre-populated on startup or after cache flush.\n */\nexport const CacheWarmupSchema = z.object({\n /** Enable cache warming */\n enabled: z.boolean().default(false).describe('Enable cache warmup'),\n /** Warmup strategy */\n strategy: z.enum(['eager', 'lazy', 'scheduled']).default('lazy')\n .describe('Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)'),\n /** Cron schedule for scheduled warmup */\n schedule: z.string().optional().describe('Cron expression for scheduled warmup'),\n /** Keys/patterns to warm up */\n patterns: z.array(z.string()).optional().describe('Key patterns to warm up (e.g., \"user:*\", \"config:*\")'),\n /** Maximum concurrent warmup operations */\n concurrency: z.number().default(10).describe('Maximum concurrent warmup operations'),\n}).describe('Cache warmup strategy');\n\nexport type CacheWarmup = z.infer;\n\n/**\n * Distributed Cache Configuration Schema\n *\n * Extended cache configuration for distributed multi-node deployments.\n * Adds consistency strategies, avalanche prevention, and warmup policies.\n *\n * @example\n * ```typescript\n * const distributedCache: DistributedCacheConfig = {\n * enabled: true,\n * tiers: [\n * { name: 'l1', type: 'memory', maxSize: 100, ttl: 60, strategy: 'lru' },\n * { name: 'l2', type: 'redis', maxSize: 1000, ttl: 300, strategy: 'lru' },\n * ],\n * invalidation: [\n * { trigger: 'update', scope: 'key' },\n * ],\n * consistency: 'write_through',\n * avalanchePrevention: {\n * jitterTtl: { enabled: true, maxJitterSeconds: 30 },\n * circuitBreaker: { enabled: true, failureThreshold: 5 },\n * },\n * warmup: { enabled: true, strategy: 'eager', patterns: ['config:*'] },\n * };\n * ```\n */\nexport const DistributedCacheConfigSchema = CacheConfigSchema.extend({\n /** Distributed write consistency strategy */\n consistency: CacheConsistencySchema.optional().describe('Distributed cache consistency strategy'),\n /** Avalanche/stampede prevention settings */\n avalanchePrevention: CacheAvalanchePreventionSchema.optional()\n .describe('Cache avalanche and stampede prevention'),\n /** Cache warmup configuration */\n warmup: CacheWarmupSchema.optional().describe('Cache warmup strategy'),\n}).describe('Distributed cache configuration with consistency and avalanche prevention');\n\nexport type DistributedCacheConfig = z.infer;\nexport type DistributedCacheConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Backup Strategy Schema\n *\n * Defines backup methods for disaster recovery.\n *\n * - **full**: Complete snapshot of all data\n * - **incremental**: Only changes since last backup\n * - **differential**: All changes since last full backup\n *\n * @example\n * ```typescript\n * const backup: BackupConfig = {\n * strategy: 'incremental',\n * schedule: '0 2 * * *',\n * retention: { days: 30, minCopies: 3 },\n * encryption: { enabled: true, algorithm: 'AES-256-GCM' },\n * };\n * ```\n */\nexport const BackupStrategySchema = z.enum([\n 'full',\n 'incremental',\n 'differential',\n]).describe('Backup strategy type');\n\nexport type BackupStrategy = z.infer;\n\n/**\n * Backup Retention Policy Schema\n */\nexport const BackupRetentionSchema = z.object({\n /** Number of days to retain backups */\n days: z.number().min(1).describe('Retention period in days'),\n /** Minimum number of backup copies to keep regardless of age */\n minCopies: z.number().min(1).default(3).describe('Minimum backup copies to retain'),\n /** Maximum number of backup copies */\n maxCopies: z.number().optional().describe('Maximum backup copies to store'),\n}).describe('Backup retention policy');\n\nexport type BackupRetention = z.infer;\n\n/**\n * Backup Configuration Schema\n */\nexport const BackupConfigSchema = z.object({\n /** Backup strategy */\n strategy: BackupStrategySchema.default('incremental').describe('Backup strategy'),\n /** Cron schedule for automated backups */\n schedule: z.string().optional().describe('Cron expression for backup schedule (e.g., \"0 2 * * *\")'),\n /** Retention policy */\n retention: BackupRetentionSchema.describe('Backup retention policy'),\n /** Storage destination */\n destination: z.object({\n type: z.enum(['s3', 'gcs', 'azure_blob', 'local']).describe('Storage backend type'),\n bucket: z.string().optional().describe('Cloud storage bucket/container name'),\n path: z.string().optional().describe('Storage path prefix'),\n region: z.string().optional().describe('Cloud storage region'),\n }).describe('Backup storage destination'),\n /** Encryption settings */\n encryption: z.object({\n enabled: z.boolean().default(true).describe('Enable backup encryption'),\n algorithm: z.enum(['AES-256-GCM', 'AES-256-CBC', 'ChaCha20-Poly1305']).default('AES-256-GCM')\n .describe('Encryption algorithm'),\n keyId: z.string().optional().describe('KMS key ID for encryption'),\n }).optional().describe('Backup encryption settings'),\n /** Compression settings */\n compression: z.object({\n enabled: z.boolean().default(true).describe('Enable backup compression'),\n algorithm: z.enum(['gzip', 'zstd', 'lz4', 'snappy']).default('zstd').describe('Compression algorithm'),\n }).optional().describe('Backup compression settings'),\n /** Verify backup integrity after creation */\n verifyAfterBackup: z.boolean().default(true).describe('Verify backup integrity after creation'),\n}).describe('Backup configuration');\n\nexport type BackupConfig = z.infer;\nexport type BackupConfigInput = z.input;\n\n/**\n * Failover Mode Schema\n *\n * Defines how traffic is routed between primary and secondary systems.\n *\n * - **active_passive**: Secondary is standby, activated on primary failure\n * - **active_active**: Both primary and secondary handle traffic\n * - **pilot_light**: Minimal secondary with quick scale-up capability\n * - **warm_standby**: Reduced-capacity secondary, faster failover than pilot light\n */\nexport const FailoverModeSchema = z.enum([\n 'active_passive',\n 'active_active',\n 'pilot_light',\n 'warm_standby',\n]).describe('Failover mode');\n\nexport type FailoverMode = z.infer;\n\n/**\n * Failover Configuration Schema\n */\nexport const FailoverConfigSchema = z.object({\n /** Failover mode */\n mode: FailoverModeSchema.default('active_passive').describe('Failover mode'),\n /** Automatic failover enabled */\n autoFailover: z.boolean().default(true).describe('Enable automatic failover'),\n /** Health check interval in seconds */\n healthCheckInterval: z.number().default(30).describe('Health check interval in seconds'),\n /** Number of consecutive failures before triggering failover */\n failureThreshold: z.number().default(3).describe('Consecutive failures before failover'),\n /** Regions/zones for disaster recovery */\n regions: z.array(z.object({\n name: z.string().describe('Region identifier (e.g., \"us-east-1\", \"eu-west-1\")'),\n role: z.enum(['primary', 'secondary', 'witness']).describe('Region role'),\n endpoint: z.string().optional().describe('Region endpoint URL'),\n priority: z.number().optional().describe('Failover priority (lower = higher priority)'),\n })).min(2).describe('Multi-region configuration (minimum 2 regions)'),\n /** DNS failover configuration */\n dns: z.object({\n ttl: z.number().default(60).describe('DNS TTL in seconds for failover'),\n provider: z.enum(['route53', 'cloudflare', 'azure_dns', 'custom']).optional()\n .describe('DNS provider for automatic failover'),\n }).optional().describe('DNS failover settings'),\n}).describe('Failover configuration');\n\nexport type FailoverConfig = z.infer;\nexport type FailoverConfigInput = z.input;\n\n/**\n * Recovery Point Objective (RPO) Schema\n *\n * Maximum acceptable amount of data loss measured in time.\n */\nexport const RPOSchema = z.object({\n /** RPO value */\n value: z.number().min(0).describe('RPO value'),\n /** RPO time unit */\n unit: z.enum(['seconds', 'minutes', 'hours']).default('minutes').describe('RPO time unit'),\n}).describe('Recovery Point Objective (maximum acceptable data loss)');\n\nexport type RPO = z.infer;\n\n/**\n * Recovery Time Objective (RTO) Schema\n *\n * Maximum acceptable time to restore service after a disaster.\n */\nexport const RTOSchema = z.object({\n /** RTO value */\n value: z.number().min(0).describe('RTO value'),\n /** RTO time unit */\n unit: z.enum(['seconds', 'minutes', 'hours']).default('minutes').describe('RTO time unit'),\n}).describe('Recovery Time Objective (maximum acceptable downtime)');\n\nexport type RTO = z.infer;\n\n/**\n * Disaster Recovery Plan Schema\n *\n * Complete disaster recovery configuration for an ObjectStack deployment.\n * Covers backup, failover, replication, and recovery objectives.\n *\n * Aligned with industry standards:\n * - ISO 22301 (Business Continuity Management)\n * - AWS Well-Architected Framework (Reliability Pillar)\n *\n * @example\n * ```typescript\n * const drPlan: DisasterRecoveryPlan = {\n * enabled: true,\n * rpo: { value: 15, unit: 'minutes' },\n * rto: { value: 1, unit: 'hours' },\n * backup: {\n * strategy: 'incremental',\n * schedule: '0 0/6 * * *',\n * retention: { days: 90, minCopies: 5 },\n * destination: { type: 's3', bucket: 'backup-bucket', region: 'us-east-1' },\n * },\n * failover: {\n * mode: 'active_passive',\n * autoFailover: true,\n * healthCheckInterval: 30,\n * failureThreshold: 3,\n * regions: [\n * { name: 'us-east-1', role: 'primary' },\n * { name: 'us-west-2', role: 'secondary' },\n * ],\n * },\n * };\n * ```\n */\nexport const DisasterRecoveryPlanSchema = z.object({\n /** Enable disaster recovery */\n enabled: z.boolean().default(false).describe('Enable disaster recovery plan'),\n\n /** Recovery Point Objective */\n rpo: RPOSchema.describe('Recovery Point Objective'),\n\n /** Recovery Time Objective */\n rto: RTOSchema.describe('Recovery Time Objective'),\n\n /** Backup configuration */\n backup: BackupConfigSchema.describe('Backup configuration'),\n\n /** Failover configuration */\n failover: FailoverConfigSchema.optional().describe('Multi-region failover configuration'),\n\n /** Data replication settings */\n replication: z.object({\n /** Replication mode */\n mode: z.enum(['synchronous', 'asynchronous', 'semi_synchronous']).default('asynchronous')\n .describe('Data replication mode'),\n /** Maximum replication lag allowed (seconds) */\n maxLagSeconds: z.number().optional().describe('Maximum acceptable replication lag in seconds'),\n /** Objects/tables to replicate (empty = all) */\n includeObjects: z.array(z.string()).optional().describe('Objects to replicate (empty = all)'),\n /** Objects/tables to exclude from replication */\n excludeObjects: z.array(z.string()).optional().describe('Objects to exclude from replication'),\n }).optional().describe('Data replication settings'),\n\n /** Automated recovery testing */\n testing: z.object({\n /** Enable periodic DR testing */\n enabled: z.boolean().default(false).describe('Enable automated DR testing'),\n /** Cron schedule for DR tests */\n schedule: z.string().optional().describe('Cron expression for DR test schedule'),\n /** Notification channel for test results */\n notificationChannel: z.string().optional().describe('Notification channel for DR test results'),\n }).optional().describe('Automated disaster recovery testing'),\n\n /** Runbook URL for manual procedures */\n runbookUrl: z.string().optional().describe('URL to disaster recovery runbook/playbook'),\n\n /** Contact list for DR incidents */\n contacts: z.array(z.object({\n name: z.string().describe('Contact name'),\n role: z.string().describe('Contact role (e.g., \"DBA\", \"SRE Lead\")'),\n email: z.string().optional().describe('Contact email'),\n phone: z.string().optional().describe('Contact phone'),\n })).optional().describe('Emergency contact list for DR incidents'),\n}).describe('Complete disaster recovery plan configuration');\n\nexport type DisasterRecoveryPlan = z.infer;\nexport type DisasterRecoveryPlanInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Message queue protocol for async communication\n * Supports Kafka, RabbitMQ, AWS SQS, Redis Pub/Sub\n */\nexport const MessageQueueProviderSchema = z.enum([\n 'kafka',\n 'rabbitmq',\n 'aws-sqs',\n 'redis-pubsub',\n 'google-pubsub',\n 'azure-service-bus',\n]).describe('Supported message queue backend provider');\n\nexport type MessageQueueProvider = z.infer;\n\nexport const TopicConfigSchema = z.object({\n name: z.string().describe('Topic name identifier'),\n partitions: z.number().default(1).describe('Number of partitions for parallel consumption'),\n replicationFactor: z.number().default(1).describe('Number of replicas for fault tolerance'),\n retentionMs: z.number().optional().describe('Message retention period in milliseconds'),\n compressionType: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression algorithm'),\n}).describe('Configuration for a message queue topic');\n\nexport type TopicConfig = z.infer;\n\nexport const ConsumerConfigSchema = z.object({\n groupId: z.string().describe('Consumer group identifier'),\n autoOffsetReset: z.enum(['earliest', 'latest']).default('latest').describe('Where to start reading when no offset exists'),\n enableAutoCommit: z.boolean().default(true).describe('Automatically commit consumed offsets'),\n maxPollRecords: z.number().default(500).describe('Maximum records returned per poll'),\n}).describe('Consumer group configuration for topic consumption');\n\nexport type ConsumerConfig = z.infer;\n\nexport const DeadLetterQueueSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable dead letter queue for failed messages'),\n maxRetries: z.number().default(3).describe('Maximum delivery attempts before sending to DLQ'),\n queueName: z.string().describe('Name of the dead letter queue'),\n}).describe('Dead letter queue configuration for unprocessable messages');\n\nexport type DeadLetterQueue = z.infer;\n\nexport const MessageQueueConfigSchema = z.object({\n provider: MessageQueueProviderSchema.describe('Message queue backend provider'),\n topics: z.array(TopicConfigSchema).describe('List of topic configurations'),\n consumers: z.array(ConsumerConfigSchema).optional().describe('Consumer group configurations'),\n deadLetterQueue: DeadLetterQueueSchema.optional().describe('Dead letter queue for failed messages'),\n ssl: z.boolean().default(false).describe('Enable SSL/TLS for broker connections'),\n sasl: z.object({\n mechanism: z.enum(['plain', 'scram-sha-256', 'scram-sha-512']).describe('SASL authentication mechanism'),\n username: z.string().describe('SASL username'),\n password: z.string().describe('SASL password'),\n }).optional().describe('SASL authentication configuration'),\n}).describe('Top-level message queue configuration');\n\nexport type MessageQueueConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Object Storage Protocol\n * \n * Unified storage protocol that combines:\n * - Object storage systems (S3, Azure Blob, GCS, MinIO)\n * - Scoped storage configuration (temp, cache, data, logs, config, public)\n * - Multi-cloud storage providers\n * - Bucket/container configuration\n * - Access control and permissions\n * - Lifecycle policies for data retention\n * - Presigned URLs for secure direct access\n * - Multipart uploads for large files\n */\n\n// ============================================================================\n// Storage Scope Protocol (formerly from scoped-storage.zod.ts)\n// ============================================================================\n\n/**\n * Storage Scope Enum\n * Defines the lifecycle and persistence guarantee of the storage area.\n */\nexport const StorageScopeSchema = z.enum([\n 'global', // Global application-wide storage\n 'tenant', // Tenant-scoped storage (multi-tenant apps)\n 'user', // User-scoped storage\n 'session', // Session-scoped storage (ephemeral)\n 'temp', // Ephemeral, cleared on restart\n 'cache', // Ephemeral, survives restarts, cleared on LRU/Expiration\n 'data', // Persistent, backed up\n 'logs', // Append-only, rotated\n 'config', // Read-heavy, versioned\n 'public' // Publicly accessible static assets\n]).describe('Storage scope classification');\n\nexport type StorageScope = z.infer;\n\n/**\n * File Metadata Schema\n * Standardized file attribute structure\n */\nexport const FileMetadataSchema = z.object({\n path: z.string().describe('File path'),\n name: z.string().describe('File name'),\n size: z.number().int().describe('File size in bytes'),\n mimeType: z.string().describe('MIME type'),\n lastModified: z.string().datetime().describe('Last modified timestamp'),\n created: z.string().datetime().describe('Creation timestamp'),\n etag: z.string().optional().describe('Entity tag'),\n});\n\nexport type FileMetadata = z.infer;\n\n// ============================================================================\n// Enums\n// ============================================================================\n\n/**\n * Storage Provider Types\n * \n * Supported cloud and self-hosted object storage providers.\n */\nexport const StorageProviderSchema = z.enum([\n 's3', // Amazon S3\n 'azure_blob', // Azure Blob Storage\n 'gcs', // Google Cloud Storage\n 'minio', // MinIO (self-hosted S3-compatible)\n 'r2', // Cloudflare R2\n 'spaces', // DigitalOcean Spaces\n 'wasabi', // Wasabi Hot Cloud Storage\n 'backblaze', // Backblaze B2\n 'local', // Local filesystem (development only)\n]).describe('Storage provider type');\n\nexport type StorageProvider = z.infer;\n\n/**\n * Storage Access Control List (ACL)\n * \n * Predefined access control configurations for objects and buckets.\n */\nexport const StorageAclSchema = z.enum([\n 'private', // Owner has full control, no one else has access\n 'public_read', // Owner has full control, everyone can read\n 'public_read_write', // Owner has full control, everyone can read/write (not recommended)\n 'authenticated_read', // Owner has full control, authenticated users can read\n 'bucket_owner_read', // Object owner has full control, bucket owner can read\n 'bucket_owner_full_control', // Both object and bucket owner have full control\n]).describe('Storage access control level');\n\nexport type StorageAcl = z.infer;\n\n/**\n * Storage Class / Tier\n * \n * Different storage tiers for cost optimization.\n * Maps to provider-specific storage classes.\n */\nexport const StorageClassSchema = z.enum([\n 'standard', // Standard/hot storage for frequently accessed data\n 'intelligent', // Intelligent tiering (auto-moves between hot/cool)\n 'infrequent_access', // Infrequent access/cool storage\n 'glacier', // Archive/cold storage (slower retrieval)\n 'deep_archive', // Deep archive (cheapest, slowest retrieval)\n]).describe('Storage class/tier for cost optimization');\n\nexport type StorageClass = z.infer;\n\n/**\n * Lifecycle Transition Action\n */\nexport const LifecycleActionSchema = z.enum([\n 'transition', // Move to different storage class\n 'delete', // Delete the object\n 'abort', // Abort incomplete multipart uploads\n]).describe('Lifecycle policy action type');\n\nexport type LifecycleAction = z.infer;\n\n// ============================================================================\n// Configuration Schemas\n// ============================================================================\n\n/**\n * Object Metadata Schema\n * \n * Standard and custom metadata attached to stored objects.\n * \n * @example\n * {\n * contentType: 'image/jpeg',\n * contentLength: 1024000,\n * etag: '\"abc123\"',\n * lastModified: new Date('2024-01-01'),\n * custom: {\n * uploadedBy: 'user123',\n * department: 'marketing'\n * }\n * }\n */\nexport const ObjectMetadataSchema = z.object({\n contentType: z.string().describe('MIME type (e.g., image/jpeg, application/pdf)'),\n contentLength: z.number().min(0).describe('File size in bytes'),\n contentEncoding: z.string().optional().describe('Content encoding (e.g., gzip)'),\n contentDisposition: z.string().optional().describe('Content disposition header'),\n contentLanguage: z.string().optional().describe('Content language'),\n cacheControl: z.string().optional().describe('Cache control directives'),\n etag: z.string().optional().describe('Entity tag for versioning/caching'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n versionId: z.string().optional().describe('Object version identifier'),\n storageClass: StorageClassSchema.optional().describe('Storage class/tier'),\n encryption: z.object({\n algorithm: z.string().describe('Encryption algorithm (e.g., AES256, aws:kms)'),\n keyId: z.string().optional().describe('KMS key ID if using managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n custom: z.record(z.string(), z.string()).optional().describe('Custom user-defined metadata'),\n});\n\nexport type ObjectMetadata = z.infer;\n\n/**\n * Presigned URL Configuration\n * \n * Configuration for generating temporary URLs for direct access to objects.\n * Useful for secure file uploads/downloads without exposing credentials.\n * \n * @example\n * // Generate download URL valid for 1 hour\n * {\n * operation: 'get',\n * expiresIn: 3600,\n * contentType: 'image/jpeg'\n * }\n * \n * @example\n * // Generate upload URL valid for 15 minutes with size limit\n * {\n * operation: 'put',\n * expiresIn: 900,\n * contentType: 'application/pdf',\n * maxSize: 10485760\n * }\n */\nexport const PresignedUrlConfigSchema = z.object({\n operation: z.enum(['get', 'put', 'delete', 'head']).describe('Allowed operation'),\n expiresIn: z.number().min(1).max(604800).describe('Expiration time in seconds (max 7 days)'),\n contentType: z.string().optional().describe('Required content type for PUT operations'),\n maxSize: z.number().min(0).optional().describe('Maximum file size in bytes for PUT operations'),\n responseContentType: z.string().optional().describe('Override content-type for GET operations'),\n responseContentDisposition: z.string().optional().describe('Override content-disposition for GET operations'),\n});\n\nexport type PresignedUrlConfig = z.infer;\n\n/**\n * Multipart Upload Configuration\n * \n * Configuration for chunked uploads of large files.\n * Enables resumable uploads and parallel transfer.\n * \n * @example\n * // Enable multipart for files > 100MB with 10MB chunks\n * {\n * enabled: true,\n * partSize: 10485760,\n * maxParts: 10000,\n * threshold: 104857600,\n * maxConcurrent: 4\n * }\n */\nexport const MultipartUploadConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable multipart uploads'),\n partSize: z.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe('Part size in bytes (min 5MB, max 5GB)'),\n maxParts: z.number().min(1).max(10000).default(10000).describe('Maximum number of parts (max 10,000)'),\n threshold: z.number().min(0).default(100 * 1024 * 1024).describe('File size threshold to trigger multipart upload (bytes)'),\n maxConcurrent: z.number().min(1).max(100).default(4).describe('Maximum concurrent part uploads'),\n abortIncompleteAfterDays: z.number().min(1).optional().describe('Auto-abort incomplete uploads after N days'),\n});\n\nexport type MultipartUploadConfig = z.infer;\n\n/**\n * Access Control Configuration\n * \n * Fine-grained access control for buckets and objects.\n * \n * @example\n * {\n * acl: 'private',\n * allowedOrigins: ['https://app.example.com'],\n * allowedMethods: ['GET', 'PUT'],\n * corsEnabled: true,\n * publicAccess: {\n * allowPublicRead: false,\n * allowPublicWrite: false\n * }\n * }\n */\nexport const AccessControlConfigSchema = z.object({\n acl: StorageAclSchema.default('private').describe('Default access control level'),\n allowedOrigins: z.array(z.string()).optional().describe('CORS allowed origins'),\n allowedMethods: z.array(z.enum(['GET', 'PUT', 'POST', 'DELETE', 'HEAD'])).optional().describe('CORS allowed HTTP methods'),\n allowedHeaders: z.array(z.string()).optional().describe('CORS allowed headers'),\n exposeHeaders: z.array(z.string()).optional().describe('CORS exposed headers'),\n maxAge: z.number().min(0).optional().describe('CORS preflight cache duration in seconds'),\n corsEnabled: z.boolean().default(false).describe('Enable CORS configuration'),\n publicAccess: z.object({\n allowPublicRead: z.boolean().default(false).describe('Allow public read access'),\n allowPublicWrite: z.boolean().default(false).describe('Allow public write access'),\n allowPublicList: z.boolean().default(false).describe('Allow public bucket listing'),\n }).optional().describe('Public access control'),\n allowedIps: z.array(z.string()).optional().describe('Allowed IP addresses/CIDR blocks'),\n blockedIps: z.array(z.string()).optional().describe('Blocked IP addresses/CIDR blocks'),\n});\n\nexport type AccessControlConfig = z.infer;\n\n/**\n * Lifecycle Policy Rule\n * \n * Individual rule for automatic object lifecycle management.\n * \n * @example\n * // Transition to infrequent access after 30 days\n * {\n * id: 'move_to_ia',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 30,\n * targetStorageClass: 'infrequent_access'\n * }\n * \n * @example\n * // Delete objects after 365 days\n * {\n * id: 'delete_old',\n * enabled: true,\n * action: 'delete',\n * daysAfterCreation: 365\n * }\n */\nexport const LifecyclePolicyRuleSchema = z.object({\n id: SystemIdentifierSchema.describe('Rule identifier'),\n enabled: z.boolean().default(true).describe('Enable this rule'),\n action: LifecycleActionSchema.describe('Action to perform'),\n prefix: z.string().optional().describe('Object key prefix filter (e.g., \"uploads/\")'),\n tags: z.record(z.string(), z.string()).optional().describe('Object tag filters'),\n daysAfterCreation: z.number().min(0).optional().describe('Days after object creation'),\n daysAfterModification: z.number().min(0).optional().describe('Days after last modification'),\n targetStorageClass: StorageClassSchema.optional().describe('Target storage class for transition action'),\n}).refine((data) => {\n // Validate that transition action has targetStorageClass\n if (data.action === 'transition' && !data.targetStorageClass) {\n return false;\n }\n return true;\n}, {\n message: 'targetStorageClass is required when action is \"transition\"',\n});\n\nexport type LifecyclePolicyRule = z.infer;\n\n/**\n * Lifecycle Policy Configuration\n * \n * Collection of lifecycle rules for automatic data management.\n * \n * @example\n * {\n * enabled: true,\n * rules: [\n * {\n * id: 'archive_old_files',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 90,\n * targetStorageClass: 'glacier'\n * },\n * {\n * id: 'delete_temp_files',\n * enabled: true,\n * action: 'delete',\n * prefix: 'temp/',\n * daysAfterCreation: 7\n * }\n * ]\n * }\n */\nexport const LifecyclePolicyConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable lifecycle policies'),\n rules: z.array(LifecyclePolicyRuleSchema).default([]).describe('Lifecycle rules'),\n});\n\nexport type LifecyclePolicyConfig = z.infer;\n\n/**\n * Bucket Configuration Schema\n * \n * Comprehensive configuration for a storage bucket/container.\n * \n * @example\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'my-app-uploads',\n * region: 'us-east-1',\n * provider: 's3',\n * versioning: true,\n * accessControl: {\n * acl: 'private',\n * corsEnabled: true,\n * allowedOrigins: ['https://app.example.com']\n * },\n * multipartConfig: {\n * enabled: true,\n * threshold: 104857600\n * }\n * }\n */\nexport const BucketConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Bucket identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n bucketName: z.string().describe('Actual bucket/container name in storage provider'),\n region: z.string().optional().describe('Storage region (e.g., us-east-1, westus)'),\n provider: StorageProviderSchema.describe('Storage provider'),\n endpoint: z.string().optional().describe('Custom endpoint URL (for S3-compatible providers)'),\n pathStyle: z.boolean().default(false).describe('Use path-style URLs (for S3-compatible providers)'),\n \n versioning: z.boolean().default(false).describe('Enable object versioning'),\n encryption: z.object({\n enabled: z.boolean().default(false).describe('Enable server-side encryption'),\n algorithm: z.enum(['AES256', 'aws:kms', 'azure:kms', 'gcp:kms']).default('AES256').describe('Encryption algorithm'),\n kmsKeyId: z.string().optional().describe('KMS key ID for managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n \n accessControl: AccessControlConfigSchema.optional().describe('Access control configuration'),\n lifecyclePolicy: LifecyclePolicyConfigSchema.optional().describe('Lifecycle policy configuration'),\n multipartConfig: MultipartUploadConfigSchema.optional().describe('Multipart upload configuration'),\n \n tags: z.record(z.string(), z.string()).optional().describe('Bucket tags for organization'),\n description: z.string().optional().describe('Bucket description'),\n enabled: z.boolean().default(true).describe('Enable this bucket'),\n});\n\nexport type BucketConfig = z.infer;\n\n/**\n * Storage Connection Configuration\n * \n * Provider-specific connection credentials and settings.\n * \n * @example S3\n * {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * sessionToken: '${AWS_SESSION_TOKEN}',\n * region: 'us-east-1'\n * }\n * \n * @example Azure\n * {\n * accountName: 'mystorageaccount',\n * accountKey: '${AZURE_STORAGE_KEY}',\n * endpoint: 'https://mystorageaccount.blob.core.windows.net'\n * }\n */\nexport const StorageConnectionSchema = z.object({\n // AWS S3 / MinIO\n accessKeyId: z.string().optional().describe('AWS access key ID or MinIO access key'),\n secretAccessKey: z.string().optional().describe('AWS secret access key or MinIO secret key'),\n sessionToken: z.string().optional().describe('AWS session token for temporary credentials'),\n \n // Azure Blob Storage\n accountName: z.string().optional().describe('Azure storage account name'),\n accountKey: z.string().optional().describe('Azure storage account key'),\n sasToken: z.string().optional().describe('Azure SAS token'),\n \n // Google Cloud Storage\n projectId: z.string().optional().describe('GCP project ID'),\n credentials: z.string().optional().describe('GCP service account credentials JSON'),\n \n // Common\n endpoint: z.string().optional().describe('Custom endpoint URL'),\n region: z.string().optional().describe('Default region'),\n useSSL: z.boolean().default(true).describe('Use SSL/TLS for connections'),\n timeout: z.number().min(0).optional().describe('Connection timeout in milliseconds'),\n});\n\nexport type StorageConnection = z.infer;\n\n/**\n * Object Storage Configuration\n * \n * Complete object storage system configuration.\n * \n * @example\n * {\n * name: 'production_storage',\n * label: 'Production File Storage',\n * provider: 's3',\n * scope: 'global',\n * connection: {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * region: 'us-east-1'\n * },\n * buckets: [\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'prod-uploads',\n * provider: 's3',\n * region: 'us-east-1'\n * }\n * ],\n * defaultBucket: 'user_uploads'\n * }\n */\nexport const ObjectStorageConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Storage configuration identifier'),\n label: z.string().describe('Display label'),\n provider: StorageProviderSchema.describe('Primary storage provider'),\n \n /**\n * Storage scope\n * Defines the lifecycle and access pattern for this storage\n */\n scope: StorageScopeSchema.optional().default('global').describe('Storage scope'),\n \n connection: StorageConnectionSchema.describe('Connection credentials'),\n buckets: z.array(BucketConfigSchema).default([]).describe('Configured buckets'),\n defaultBucket: z.string().optional().describe('Default bucket name for operations'),\n \n /**\n * Base path or location\n * For local/scoped storage configurations\n */\n location: z.string().optional().describe('Root path (local) or base location'),\n \n /**\n * Storage quota in bytes\n */\n quota: z.number().int().positive().optional().describe('Max size in bytes'),\n \n /**\n * Provider-specific options\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Provider-specific configuration options'),\n \n enabled: z.boolean().default(true).describe('Enable this storage configuration'),\n description: z.string().optional().describe('Configuration description'),\n});\n\nexport type ObjectStorageConfig = z.infer;\n\n// ============================================================================\n// Helper Examples\n// ============================================================================\n\n/**\n * Example: AWS S3 Configuration\n */\nexport const s3StorageExample = ObjectStorageConfigSchema.parse({\n name: 'aws_s3_storage',\n label: 'AWS S3 Production Storage',\n provider: 's3',\n connection: {\n accessKeyId: '${AWS_ACCESS_KEY_ID}',\n secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n region: 'us-east-1',\n },\n buckets: [\n {\n name: 'user_uploads',\n label: 'User Uploads',\n bucketName: 'my-app-user-uploads',\n region: 'us-east-1',\n provider: 's3',\n versioning: true,\n encryption: {\n enabled: true,\n algorithm: 'aws:kms',\n kmsKeyId: '${AWS_KMS_KEY_ID}',\n },\n accessControl: {\n acl: 'private',\n corsEnabled: true,\n allowedOrigins: ['https://app.example.com'],\n allowedMethods: ['GET', 'PUT', 'POST'],\n },\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'archive_old_uploads',\n enabled: true,\n action: 'transition',\n daysAfterCreation: 90,\n targetStorageClass: 'glacier',\n },\n ],\n },\n multipartConfig: {\n enabled: true,\n partSize: 10 * 1024 * 1024,\n threshold: 100 * 1024 * 1024,\n maxConcurrent: 4,\n },\n },\n ],\n defaultBucket: 'user_uploads',\n enabled: true,\n});\n\n/**\n * Example: MinIO Configuration\n */\nexport const minioStorageExample = ObjectStorageConfigSchema.parse({\n name: 'minio_local',\n label: 'MinIO Local Storage',\n provider: 'minio',\n connection: {\n accessKeyId: 'minioadmin',\n secretAccessKey: 'minioadmin',\n endpoint: 'http://localhost:9000',\n useSSL: false,\n },\n buckets: [\n {\n name: 'development_files',\n label: 'Development Files',\n bucketName: 'dev-files',\n provider: 'minio',\n endpoint: 'http://localhost:9000',\n pathStyle: true,\n accessControl: {\n acl: 'private',\n },\n },\n ],\n defaultBucket: 'development_files',\n enabled: true,\n});\n\n/**\n * Example: Azure Blob Storage Configuration\n */\nexport const azureBlobStorageExample = ObjectStorageConfigSchema.parse({\n name: 'azure_blob_storage',\n label: 'Azure Blob Storage',\n provider: 'azure_blob',\n connection: {\n accountName: 'mystorageaccount',\n accountKey: '${AZURE_STORAGE_KEY}',\n endpoint: 'https://mystorageaccount.blob.core.windows.net',\n },\n buckets: [\n {\n name: 'media_files',\n label: 'Media Files',\n bucketName: 'media',\n provider: 'azure_blob',\n region: 'eastus',\n accessControl: {\n acl: 'public_read',\n publicAccess: {\n allowPublicRead: true,\n allowPublicWrite: false,\n allowPublicList: false,\n },\n },\n },\n ],\n defaultBucket: 'media_files',\n enabled: true,\n});\n\n/**\n * Example: Google Cloud Storage Configuration\n */\nexport const gcsStorageExample = ObjectStorageConfigSchema.parse({\n name: 'gcs_storage',\n label: 'Google Cloud Storage',\n provider: 'gcs',\n connection: {\n projectId: 'my-gcp-project',\n credentials: '${GCP_SERVICE_ACCOUNT_JSON}',\n },\n buckets: [\n {\n name: 'backup_storage',\n label: 'Backup Storage',\n bucketName: 'my-app-backups',\n region: 'us-central1',\n provider: 'gcs',\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'delete_old_backups',\n enabled: true,\n action: 'delete',\n daysAfterCreation: 30,\n },\n ],\n },\n },\n ],\n defaultBucket: 'backup_storage',\n enabled: true,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Full-text search protocol\n * Supports Elasticsearch, Algolia, Meilisearch, Typesense\n */\nexport const SearchProviderSchema = z.enum([\n 'elasticsearch',\n 'algolia',\n 'meilisearch',\n 'typesense',\n 'opensearch',\n]).describe('Supported full-text search engine provider');\n\nexport type SearchProvider = z.infer;\n\nexport const AnalyzerConfigSchema = z.object({\n type: z.enum(['standard', 'simple', 'whitespace', 'keyword', 'pattern', 'language']).describe('Text analyzer type'),\n language: z.string().optional().describe('Language for language-specific analysis'),\n stopwords: z.array(z.string()).optional().describe('Custom stopwords to filter during analysis'),\n customFilters: z.array(z.string()).optional().describe('Additional token filter names to apply'),\n}).describe('Text analyzer configuration for index tokenization and normalization');\n\nexport type AnalyzerConfig = z.infer;\n\nexport const SearchIndexConfigSchema = z.object({\n indexName: z.string().describe('Name of the search index'),\n objectName: z.string().describe('Source ObjectQL object'),\n fields: z.array(z.object({\n name: z.string().describe('Field name to index'),\n type: z.enum(['text', 'keyword', 'number', 'date', 'boolean', 'geo']).describe('Index field data type'),\n analyzer: z.string().optional().describe('Named analyzer to use for this field'),\n searchable: z.boolean().default(true).describe('Include field in full-text search'),\n filterable: z.boolean().default(false).describe('Allow filtering on this field'),\n sortable: z.boolean().default(false).describe('Allow sorting by this field'),\n boost: z.number().default(1).describe('Relevance boost factor for this field'),\n })).describe('Fields to include in the search index'),\n replicas: z.number().default(1).describe('Number of index replicas for availability'),\n shards: z.number().default(1).describe('Number of index shards for distribution'),\n}).describe('Search index definition mapping an ObjectQL object to a search engine index');\n\nexport type SearchIndexConfig = z.infer;\n\nexport const FacetConfigSchema = z.object({\n field: z.string().describe('Field name to generate facets from'),\n maxValues: z.number().default(10).describe('Maximum number of facet values to return'),\n sort: z.enum(['count', 'alpha']).default('count').describe('Facet value sort order'),\n}).describe('Faceted search configuration for a single field');\n\nexport type FacetConfig = z.infer;\n\nexport const SearchConfigSchema = z.object({\n provider: SearchProviderSchema.describe('Search engine backend provider'),\n indexes: z.array(SearchIndexConfigSchema).describe('Search index definitions'),\n analyzers: z.record(z.string(), AnalyzerConfigSchema).optional().describe('Named text analyzer configurations'),\n facets: z.array(FacetConfigSchema).optional().describe('Faceted search configurations'),\n typoTolerance: z.boolean().default(true).describe('Enable typo-tolerant search'),\n synonyms: z.record(z.string(), z.array(z.string())).optional().describe('Synonym mappings for search expansion'),\n ranking: z.array(z.enum(['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom'])).optional().describe('Custom ranking rule order'),\n}).describe('Top-level full-text search engine configuration');\n\nexport type SearchConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, CorsConfigSchema, RateLimitConfigSchema, StaticMountSchema } from '../shared/http.zod';\n\n/**\n * HTTP Server Protocol\n * \n * Defines the runtime HTTP server configuration and capabilities.\n * Provides abstractions for HTTP server implementations (Express, Fastify, Hono, etc.)\n * \n * Architecture alignment:\n * - Kubernetes: Service and Ingress resources\n * - AWS: API Gateway configuration\n * - Spring Boot: Application properties\n */\n\n// ==========================================\n// Server Configuration\n// ==========================================\n\n/**\n * HTTP Server Configuration Schema\n * Core configuration for HTTP server instances\n * \n * @example\n * {\n * \"port\": 3000,\n * \"host\": \"0.0.0.0\",\n * \"cors\": {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\"]\n * },\n * \"compression\": true,\n * \"requestTimeout\": 30000\n * }\n */\nexport const HttpServerConfigSchema = z.object({\n /**\n * Server port number\n */\n port: z.number().int().min(1).max(65535).default(3000).describe('Port number to listen on'),\n \n /**\n * Server host address\n */\n host: z.string().default('0.0.0.0').describe('Host address to bind to'),\n \n /**\n * CORS configuration\n */\n cors: CorsConfigSchema.optional().describe('CORS configuration'),\n \n /**\n * Request handling options\n */\n requestTimeout: z.number().int().default(30000).describe('Request timeout in milliseconds'),\n bodyLimit: z.string().default('10mb').describe('Maximum request body size'),\n \n /**\n * Compression settings\n */\n compression: z.boolean().default(true).describe('Enable response compression'),\n \n /**\n * Security headers\n */\n security: z.object({\n helmet: z.boolean().default(true).describe('Enable security headers via helmet'),\n rateLimit: RateLimitConfigSchema.optional().describe('Global rate limiting configuration'),\n }).optional().describe('Security configuration'),\n \n /**\n * Static file serving\n */\n static: z.array(StaticMountSchema).optional().describe('Static file serving configuration'),\n \n /**\n * Trust proxy settings\n */\n trustProxy: z.boolean().default(false).describe('Trust X-Forwarded-* headers'),\n});\n\nexport type HttpServerConfig = z.infer;\nexport type HttpServerConfigInput = z.input;\n\n// ==========================================\n// Route Registration\n// ==========================================\n\n/**\n * Route Handler Metadata Schema\n * Metadata for route handlers used in registration\n */\nexport const RouteHandlerMetadataSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (supports parameters like /api/users/:id)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Handler function name or identifier\n */\n handler: z.string().describe('Handler identifier or name'),\n \n /**\n * Route metadata\n */\n metadata: z.object({\n summary: z.string().optional().describe('Route summary for documentation'),\n description: z.string().optional().describe('Route description'),\n tags: z.array(z.string()).optional().describe('Tags for grouping'),\n operationId: z.string().optional().describe('Unique operation identifier'),\n }).optional(),\n \n /**\n * Security requirements\n */\n security: z.object({\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n rateLimit: z.string().optional().describe('Rate limit policy override'),\n }).optional(),\n});\n\nexport type RouteHandlerMetadata = z.infer;\nexport type RouteHandlerMetadataInput = z.input;\n\n// ==========================================\n// Middleware Configuration\n// ==========================================\n\n/**\n * Middleware Type Enum\n */\nexport const MiddlewareType = z.enum([\n 'authentication', // Authentication middleware\n 'authorization', // Authorization/permission checks\n 'logging', // Request/response logging\n 'validation', // Input validation\n 'transformation', // Request/response transformation\n 'error', // Error handling\n 'custom', // Custom middleware\n]);\n\nexport type MiddlewareType = z.infer;\n\n/**\n * Middleware Configuration Schema\n * Defines middleware execution order and configuration\n * \n * @example\n * {\n * \"name\": \"auth_middleware\",\n * \"type\": \"authentication\",\n * \"enabled\": true,\n * \"order\": 10,\n * \"config\": {\n * \"jwtSecret\": \"secret\",\n * \"excludePaths\": [\"/health\", \"/metrics\"]\n * }\n * }\n */\nexport const MiddlewareConfigSchema = z.object({\n /**\n * Middleware identifier\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Middleware name (snake_case)'),\n \n /**\n * Middleware type\n */\n type: MiddlewareType.describe('Middleware type'),\n \n /**\n * Enable/disable middleware\n */\n enabled: z.boolean().default(true).describe('Whether middleware is enabled'),\n \n /**\n * Execution order (lower numbers execute first)\n */\n order: z.number().int().default(100).describe('Execution order priority'),\n \n /**\n * Middleware-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Middleware configuration object'),\n \n /**\n * Path patterns to apply middleware to\n */\n paths: z.object({\n include: z.array(z.string()).optional().describe('Include path patterns (glob)'),\n exclude: z.array(z.string()).optional().describe('Exclude path patterns (glob)'),\n }).optional().describe('Path filtering'),\n});\n\nexport type MiddlewareConfig = z.infer;\nexport type MiddlewareConfigInput = z.input;\n\n// ==========================================\n// Server Lifecycle Events\n// ==========================================\n\n/**\n * Server Event Type Enum\n */\nexport const ServerEventType = z.enum([\n 'starting', // Server is starting\n 'started', // Server has started and is listening\n 'stopping', // Server is stopping\n 'stopped', // Server has stopped\n 'request', // Request received\n 'response', // Response sent\n 'error', // Error occurred\n]);\n\nexport type ServerEventType = z.infer;\n\n/**\n * Server Event Schema\n * Events emitted by the HTTP server during lifecycle\n */\nexport const ServerEventSchema = z.object({\n /**\n * Event type\n */\n type: ServerEventType.describe('Event type'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp (ISO 8601)'),\n \n /**\n * Event payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Event-specific data'),\n});\n\nexport type ServerEvent = z.infer;\n\n// ==========================================\n// Server Capability Declaration\n// ==========================================\n\n/**\n * Server Capabilities Schema\n * Declares what features a server implementation supports\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Supported HTTP versions\n */\n httpVersions: z.array(z.enum(['1.0', '1.1', '2.0', '3.0'])).default(['1.1']).describe('Supported HTTP versions'),\n \n /**\n * WebSocket support\n */\n websocket: z.boolean().default(false).describe('WebSocket support'),\n \n /**\n * Server-Sent Events support\n */\n sse: z.boolean().default(false).describe('Server-Sent Events support'),\n \n /**\n * HTTP/2 Server Push\n */\n serverPush: z.boolean().default(false).describe('HTTP/2 Server Push support'),\n \n /**\n * Streaming support\n */\n streaming: z.boolean().default(true).describe('Response streaming support'),\n \n /**\n * Middleware support\n */\n middleware: z.boolean().default(true).describe('Middleware chain support'),\n \n /**\n * Route parameterization\n */\n routeParams: z.boolean().default(true).describe('URL parameter support (/users/:id)'),\n \n /**\n * Built-in compression\n */\n compression: z.boolean().default(true).describe('Built-in compression support'),\n});\n\nexport type ServerCapabilities = z.infer;\nexport type ServerCapabilitiesInput = z.input;\n\n// ==========================================\n// Server Status & Metrics\n// ==========================================\n\n/**\n * Server Status Schema\n * Current operational status of the server\n */\nexport const ServerStatusSchema = z.object({\n /**\n * Server state\n */\n state: z.enum(['stopped', 'starting', 'running', 'stopping', 'error']).describe('Current server state'),\n \n /**\n * Uptime in milliseconds\n */\n uptime: z.number().int().optional().describe('Server uptime in milliseconds'),\n \n /**\n * Server information\n */\n server: z.object({\n port: z.number().int().describe('Listening port'),\n host: z.string().describe('Bound host'),\n url: z.string().optional().describe('Full server URL'),\n }).optional(),\n \n /**\n * Connection metrics\n */\n connections: z.object({\n active: z.number().int().describe('Active connections'),\n total: z.number().int().describe('Total connections handled'),\n }).optional(),\n \n /**\n * Request metrics\n */\n requests: z.object({\n total: z.number().int().describe('Total requests processed'),\n success: z.number().int().describe('Successful requests'),\n errors: z.number().int().describe('Failed requests'),\n }).optional(),\n});\n\nexport type ServerStatus = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create HTTP server configuration\n */\nexport const HttpServerConfig = Object.assign(HttpServerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create middleware configuration\n */\nexport const MiddlewareConfig = Object.assign(MiddlewareConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Audit Log Architecture\n * \n * Comprehensive audit logging system for compliance and security.\n * Supports SOX, HIPAA, GDPR, and other regulatory requirements.\n * \n * Features:\n * - Records all CRUD operations on data\n * - Tracks authentication events (login, logout, password reset)\n * - Monitors authorization changes (permissions, roles)\n * - Configurable retention policies (180-day GDPR requirement)\n * - Suspicious activity detection and alerting\n */\n\n/**\n * Audit Event Type Enum\n * Categorizes different types of auditable events in the system\n */\nexport const AuditEventType = z.enum([\n // Data Operations (CRUD)\n 'data.create', // Record creation\n 'data.read', // Record retrieval/viewing\n 'data.update', // Record modification\n 'data.delete', // Record deletion\n 'data.export', // Data export operations\n 'data.import', // Data import operations\n 'data.bulk_update', // Bulk update operations\n 'data.bulk_delete', // Bulk delete operations\n \n // Authentication Events\n 'auth.login', // Successful login\n 'auth.login_failed', // Failed login attempt\n 'auth.logout', // User logout\n 'auth.session_created', // New session created\n 'auth.session_expired', // Session expiration\n 'auth.password_reset', // Password reset initiated\n 'auth.password_changed', // Password successfully changed\n 'auth.email_verified', // Email verification completed\n 'auth.mfa_enabled', // Multi-factor auth enabled\n 'auth.mfa_disabled', // Multi-factor auth disabled\n 'auth.account_locked', // Account locked (too many failures)\n 'auth.account_unlocked', // Account unlocked\n \n // Authorization Events\n 'authz.permission_granted', // Permission granted to user\n 'authz.permission_revoked', // Permission revoked from user\n 'authz.role_assigned', // Role assigned to user\n 'authz.role_removed', // Role removed from user\n 'authz.role_created', // New role created\n 'authz.role_updated', // Role permissions modified\n 'authz.role_deleted', // Role deleted\n 'authz.policy_created', // Security policy created\n 'authz.policy_updated', // Security policy updated\n 'authz.policy_deleted', // Security policy deleted\n \n // System Events\n 'system.config_changed', // System configuration modified\n 'system.plugin_installed', // Plugin installed\n 'system.plugin_uninstalled', // Plugin uninstalled\n 'system.backup_created', // Backup created\n 'system.backup_restored', // Backup restored\n 'system.integration_added', // External integration added\n 'system.integration_removed',// External integration removed\n \n // Security Events\n 'security.access_denied', // Access denied (authorization failure)\n 'security.suspicious_activity', // Suspicious activity detected\n 'security.data_breach', // Potential data breach detected\n 'security.api_key_created', // API key created\n 'security.api_key_revoked', // API key revoked\n]);\n\nexport type AuditEventType = z.infer;\n\n/**\n * Audit Event Severity Level\n * Indicates the importance/criticality of an audit event\n */\nexport const AuditEventSeverity = z.enum([\n 'debug', // Diagnostic information\n 'info', // Informational events (normal operations)\n 'notice', // Normal but significant events\n 'warning', // Warning conditions\n 'error', // Error conditions\n 'critical', // Critical conditions requiring immediate attention\n 'alert', // Action must be taken immediately\n 'emergency', // System is unusable\n]);\n\nexport type AuditEventSeverity = z.infer;\n\n/**\n * Audit Event Actor Schema\n * Identifies who/what performed the action\n */\nexport const AuditEventActorSchema = z.object({\n /**\n * Actor type (user, system, service, api_client, etc.)\n */\n type: z.enum(['user', 'system', 'service', 'api_client', 'integration']).describe('Actor type'),\n \n /**\n * Unique identifier for the actor\n */\n id: z.string().describe('Actor identifier'),\n \n /**\n * Display name of the actor\n */\n name: z.string().optional().describe('Actor display name'),\n \n /**\n * Email address (for user actors)\n */\n email: z.string().email().optional().describe('Actor email address'),\n \n /**\n * IP address of the actor\n */\n ipAddress: z.string().optional().describe('Actor IP address'),\n \n /**\n * User agent string (for web/API requests)\n */\n userAgent: z.string().optional().describe('User agent string'),\n});\n\nexport type AuditEventActor = z.infer;\n\n/**\n * Audit Event Target Schema\n * Identifies what was acted upon\n */\nexport const AuditEventTargetSchema = z.object({\n /**\n * Target type (e.g., 'object', 'record', 'user', 'role', 'config')\n */\n type: z.string().describe('Target type'),\n \n /**\n * Unique identifier for the target\n */\n id: z.string().describe('Target identifier'),\n \n /**\n * Display name of the target\n */\n name: z.string().optional().describe('Target display name'),\n \n /**\n * Additional metadata about the target\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Target metadata'),\n});\n\nexport type AuditEventTarget = z.infer;\n\n/**\n * Audit Event Change Schema\n * Describes what changed (for update operations)\n */\nexport const AuditEventChangeSchema = z.object({\n /**\n * Field/property that changed\n */\n field: z.string().describe('Changed field name'),\n \n /**\n * Value before the change\n */\n oldValue: z.unknown().optional().describe('Previous value'),\n \n /**\n * Value after the change\n */\n newValue: z.unknown().optional().describe('New value'),\n});\n\nexport type AuditEventChange = z.infer;\n\n/**\n * Audit Event Schema\n * Complete audit event record\n */\nexport const AuditEventSchema = z.object({\n /**\n * Unique identifier for this audit event\n */\n id: z.string().describe('Audit event ID'),\n \n /**\n * Type of event being audited\n */\n eventType: AuditEventType.describe('Event type'),\n \n /**\n * Severity level of the event\n */\n severity: AuditEventSeverity.default('info').describe('Event severity'),\n \n /**\n * Timestamp when the event occurred (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n \n /**\n * Who/what performed the action\n */\n actor: AuditEventActorSchema.describe('Event actor'),\n \n /**\n * What was acted upon\n */\n target: AuditEventTargetSchema.optional().describe('Event target'),\n \n /**\n * Human-readable description of the action\n */\n description: z.string().describe('Event description'),\n \n /**\n * Detailed changes (for update operations)\n */\n changes: z.array(AuditEventChangeSchema).optional().describe('List of changes'),\n \n /**\n * Result of the action (success, failure, partial)\n */\n result: z.enum(['success', 'failure', 'partial']).default('success').describe('Action result'),\n \n /**\n * Error message (if result is failure)\n */\n errorMessage: z.string().optional().describe('Error message'),\n \n /**\n * Tenant identifier (for multi-tenant systems)\n */\n tenantId: z.string().optional().describe('Tenant identifier'),\n \n /**\n * Request/trace ID for correlation\n */\n requestId: z.string().optional().describe('Request ID for tracing'),\n \n /**\n * Additional context and metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n \n /**\n * Geographic location (if available)\n */\n location: z.object({\n country: z.string().optional(),\n region: z.string().optional(),\n city: z.string().optional(),\n }).optional().describe('Geographic location'),\n});\n\nexport type AuditEvent = z.infer;\n\n/**\n * Audit Retention Policy Schema\n * Defines how long audit logs are retained\n */\nexport const AuditRetentionPolicySchema = z.object({\n /**\n * Retention period in days\n * Default: 180 days (GDPR 6-month requirement)\n */\n retentionDays: z.number().int().min(1).default(180).describe('Retention period in days'),\n \n /**\n * Whether to archive logs after retention period\n * If true, logs are moved to cold storage; if false, they are deleted\n */\n archiveAfterRetention: z.boolean().default(true).describe('Archive logs after retention period'),\n \n /**\n * Archive storage configuration\n */\n archiveStorage: z.object({\n type: z.enum(['s3', 'gcs', 'azure_blob', 'filesystem']).describe('Archive storage type'),\n endpoint: z.string().optional().describe('Storage endpoint URL'),\n bucket: z.string().optional().describe('Storage bucket/container name'),\n path: z.string().optional().describe('Storage path prefix'),\n credentials: z.record(z.string(), z.unknown()).optional().describe('Storage credentials'),\n }).optional().describe('Archive storage configuration'),\n \n /**\n * Event types that have different retention periods\n * Overrides the default retentionDays for specific event types\n */\n customRetention: z.record(z.string(), z.number().int().positive()).optional().describe('Custom retention by event type'),\n \n /**\n * Minimum retention period for compliance\n * Prevents accidental deletion below compliance requirements\n */\n minimumRetentionDays: z.number().int().positive().optional().describe('Minimum retention for compliance'),\n});\n\nexport type AuditRetentionPolicy = z.infer;\n\n/**\n * Suspicious Activity Rule Schema\n * Defines rules for detecting suspicious activities\n */\nexport const SuspiciousActivityRuleSchema = z.object({\n /**\n * Unique identifier for the rule\n */\n id: z.string().describe('Rule identifier'),\n \n /**\n * Rule name\n */\n name: z.string().describe('Rule name'),\n \n /**\n * Rule description\n */\n description: z.string().optional().describe('Rule description'),\n \n /**\n * Whether the rule is enabled\n */\n enabled: z.boolean().default(true).describe('Rule enabled status'),\n \n /**\n * Event types to monitor\n */\n eventTypes: z.array(AuditEventType).describe('Event types to monitor'),\n \n /**\n * Detection condition\n */\n condition: z.object({\n /**\n * Number of events that trigger the rule\n */\n threshold: z.number().int().positive().describe('Event threshold'),\n \n /**\n * Time window in seconds\n */\n windowSeconds: z.number().int().positive().describe('Time window in seconds'),\n \n /**\n * Grouping criteria (e.g., by actor.id, by ipAddress)\n */\n groupBy: z.array(z.string()).optional().describe('Grouping criteria'),\n \n /**\n * Additional filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters'),\n }).describe('Detection condition'),\n \n /**\n * Actions to take when rule is triggered\n */\n actions: z.array(z.enum([\n 'alert', // Send alert notification\n 'lock_account', // Lock the user account\n 'block_ip', // Block the IP address\n 'require_mfa', // Require multi-factor authentication\n 'log_critical', // Log as critical event\n 'webhook', // Call webhook\n ])).describe('Actions to take'),\n \n /**\n * Severity level for triggered alerts\n */\n alertSeverity: AuditEventSeverity.default('warning').describe('Alert severity'),\n \n /**\n * Notification configuration\n */\n notifications: z.object({\n /**\n * Email addresses to notify\n */\n email: z.array(z.string().email()).optional().describe('Email recipients'),\n \n /**\n * Slack webhook URL\n */\n slack: z.string().url().optional().describe('Slack webhook URL'),\n \n /**\n * Custom webhook URL\n */\n webhook: z.string().url().optional().describe('Custom webhook URL'),\n }).optional().describe('Notification configuration'),\n});\n\nexport type SuspiciousActivityRule = z.infer;\n\n/**\n * Audit Log Storage Configuration\n * Defines where and how audit logs are stored\n */\nexport const AuditStorageConfigSchema = z.object({\n /**\n * Storage backend type\n */\n type: z.enum([\n 'database', // Store in database (PostgreSQL, MySQL, etc.)\n 'elasticsearch', // Store in Elasticsearch\n 'mongodb', // Store in MongoDB\n 'clickhouse', // Store in ClickHouse (for analytics)\n 's3', // Store in S3-compatible storage\n 'gcs', // Store in Google Cloud Storage\n 'azure_blob', // Store in Azure Blob Storage\n 'custom', // Custom storage implementation\n ]).describe('Storage backend type'),\n \n /**\n * Connection string or configuration\n */\n connectionString: z.string().optional().describe('Connection string'),\n \n /**\n * Storage configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Storage-specific configuration'),\n \n /**\n * Whether to enable buffering/batching\n */\n bufferEnabled: z.boolean().default(true).describe('Enable buffering'),\n \n /**\n * Buffer size (number of events before flush)\n */\n bufferSize: z.number().int().positive().default(100).describe('Buffer size'),\n \n /**\n * Buffer flush interval in seconds\n */\n flushIntervalSeconds: z.number().int().positive().default(5).describe('Flush interval in seconds'),\n \n /**\n * Whether to compress stored data\n */\n compression: z.boolean().default(true).describe('Enable compression'),\n});\n\nexport type AuditStorageConfig = z.infer;\n\n/**\n * Audit Event Filter Schema\n * Defines filters for querying audit events\n */\nexport const AuditEventFilterSchema = z.object({\n /**\n * Filter by event types\n */\n eventTypes: z.array(AuditEventType).optional().describe('Event types to include'),\n \n /**\n * Filter by severity levels\n */\n severities: z.array(AuditEventSeverity).optional().describe('Severity levels to include'),\n \n /**\n * Filter by actor ID\n */\n actorId: z.string().optional().describe('Actor identifier'),\n \n /**\n * Filter by tenant ID\n */\n tenantId: z.string().optional().describe('Tenant identifier'),\n \n /**\n * Filter by time range\n */\n timeRange: z.object({\n from: z.string().datetime().describe('Start time'),\n to: z.string().datetime().describe('End time'),\n }).optional().describe('Time range filter'),\n \n /**\n * Filter by result status\n */\n result: z.enum(['success', 'failure', 'partial']).optional().describe('Result status'),\n \n /**\n * Search query (full-text search)\n */\n searchQuery: z.string().optional().describe('Search query'),\n \n /**\n * Custom filters\n */\n customFilters: z.record(z.string(), z.unknown()).optional().describe('Custom filters'),\n});\n\nexport type AuditEventFilter = z.infer;\n\n/**\n * Complete Audit Configuration Schema\n * Main configuration for the audit system\n */\nexport const AuditConfigSchema = z.object({\n /**\n * Unique identifier for this audit configuration\n * Must be in snake_case following ObjectStack conventions\n * Maximum length: 64 characters\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n \n /**\n * Human-readable label\n */\n label: z.string().describe('Display label'),\n \n /**\n * Whether audit logging is enabled\n */\n enabled: z.boolean().default(true).describe('Enable audit logging'),\n \n /**\n * Event types to audit\n * If not specified, all event types are audited\n */\n eventTypes: z.array(AuditEventType).optional().describe('Event types to audit'),\n \n /**\n * Event types to exclude from auditing\n */\n excludeEventTypes: z.array(AuditEventType).optional().describe('Event types to exclude'),\n \n /**\n * Minimum severity level to log\n * Events below this level are not logged\n */\n minimumSeverity: AuditEventSeverity.default('info').describe('Minimum severity level'),\n \n /**\n * Storage configuration\n */\n storage: AuditStorageConfigSchema.describe('Storage configuration'),\n \n /**\n * Retention policy\n */\n retentionPolicy: AuditRetentionPolicySchema.optional().describe('Retention policy'),\n \n /**\n * Suspicious activity detection rules\n */\n suspiciousActivityRules: z.array(SuspiciousActivityRuleSchema).default([]).describe('Suspicious activity rules'),\n \n /**\n * Whether to include sensitive data in audit logs\n * If false, sensitive fields are redacted/masked\n */\n includeSensitiveData: z.boolean().default(false).describe('Include sensitive data'),\n \n /**\n * Fields to redact from audit logs\n */\n redactFields: z.array(z.string()).default([\n 'password',\n 'passwordHash',\n 'token',\n 'apiKey',\n 'secret',\n 'creditCard',\n 'ssn',\n ]).describe('Fields to redact'),\n \n /**\n * Whether to log successful read operations\n * Can be disabled to reduce log volume\n */\n logReads: z.boolean().default(false).describe('Log read operations'),\n \n /**\n * Sampling rate for read operations (0.0 to 1.0)\n * Only applies if logReads is true\n */\n readSamplingRate: z.number().min(0).max(1).default(0.1).describe('Read sampling rate'),\n \n /**\n * Whether to log system/internal operations\n */\n logSystemEvents: z.boolean().default(true).describe('Log system events'),\n \n /**\n * Custom audit event handlers\n * Note: Function handlers are for runtime configuration only and will not be serialized to JSON Schema\n */\n customHandlers: z.array(z.object({\n eventType: AuditEventType.describe('Event type to handle'),\n handlerId: z.string().describe('Unique identifier for the handler'),\n })).optional().describe('Custom event handler references'),\n \n /**\n * Compliance mode configuration\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox', // Sarbanes-Oxley Act\n 'hipaa', // Health Insurance Portability and Accountability Act\n 'gdpr', // General Data Protection Regulation\n 'pci_dss', // Payment Card Industry Data Security Standard\n 'iso_27001',// ISO/IEC 27001\n 'fedramp', // Federal Risk and Authorization Management Program\n ])).optional().describe('Compliance standards'),\n \n /**\n * Whether to enforce immutable audit logs\n */\n immutableLogs: z.boolean().default(true).describe('Enforce immutable logs'),\n \n /**\n * Whether to require cryptographic signing\n */\n requireSigning: z.boolean().default(false).describe('Require log signing'),\n \n /**\n * Signing key configuration\n */\n signingKey: z.string().optional().describe('Signing key'),\n }).optional().describe('Compliance configuration'),\n});\n\nexport type AuditConfig = z.infer;\n\n/**\n * Default suspicious activity rules\n * Common security patterns to detect\n */\nexport const DEFAULT_SUSPICIOUS_ACTIVITY_RULES: SuspiciousActivityRule[] = [\n {\n id: 'multiple_failed_logins',\n name: 'Multiple Failed Login Attempts',\n description: 'Detects multiple failed login attempts from the same user or IP',\n enabled: true,\n eventTypes: ['auth.login_failed'],\n condition: {\n threshold: 5,\n windowSeconds: 600, // 10 minutes\n groupBy: ['actor.id', 'actor.ipAddress'],\n },\n actions: ['alert', 'lock_account'],\n alertSeverity: 'warning',\n },\n {\n id: 'bulk_data_export',\n name: 'Bulk Data Export',\n description: 'Detects large data export operations',\n enabled: true,\n eventTypes: ['data.export'],\n condition: {\n threshold: 3,\n windowSeconds: 3600, // 1 hour\n groupBy: ['actor.id'],\n },\n actions: ['alert', 'log_critical'],\n alertSeverity: 'warning',\n },\n {\n id: 'suspicious_permission_changes',\n name: 'Rapid Permission Changes',\n description: 'Detects rapid permission or role changes',\n enabled: true,\n eventTypes: ['authz.permission_granted', 'authz.role_assigned'],\n condition: {\n threshold: 10,\n windowSeconds: 300, // 5 minutes\n groupBy: ['actor.id'],\n },\n actions: ['alert', 'log_critical'],\n alertSeverity: 'critical',\n },\n {\n id: 'after_hours_access',\n name: 'After Hours Access',\n description: 'Detects access during non-business hours',\n enabled: false, // Disabled by default, requires time zone configuration\n eventTypes: ['auth.login'],\n condition: {\n threshold: 1,\n windowSeconds: 86400, // 24 hours\n },\n actions: ['alert'],\n alertSeverity: 'notice',\n },\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Logging Protocol - Comprehensive Observability Logging\n * \n * Unified logging protocol that combines:\n * - Basic kernel logging (LoggerConfig)\n * - Enterprise-grade features (LoggingConfig)\n * - Multiple log destinations (file, console, external services)\n * - Structured logging with enrichment\n * - Log aggregation and forwarding\n * - Integration with external log management systems\n */\n\n// ============================================================================\n// Basic Logger Protocol (formerly from logger.zod.ts)\n// ============================================================================\n\n/**\n * Log Level Enum\n * Standard RFC 5424 severity levels (simplified)\n */\nexport const LogLevel = z.enum([\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'fatal',\n 'silent'\n]).describe('Log severity level');\n\nexport type LogLevel = z.infer;\n\n/**\n * Log Format Enum\n */\nexport const LogFormat = z.enum([\n 'json', // Structured JSON for machine parsing\n 'text', // Simple text format\n 'pretty' // Colored human-readable output for CLI/console\n]).describe('Log output format');\n\nexport type LogFormat = z.infer;\n\n/**\n * Logger Configuration Schema\n * Configuration for the Kernel's internal logger\n */\nexport const LoggerConfigSchema = z.object({\n /**\n * Logger name\n */\n name: z.string().optional().describe('Logger name identifier'),\n\n /**\n * Minimum level to log\n */\n level: LogLevel.optional().default('info'),\n\n /**\n * Output format\n */\n format: LogFormat.optional().default('json'),\n\n /**\n * Redact sensitive keys\n */\n redact: z.array(z.string()).optional().default(['password', 'token', 'secret', 'key'])\n .describe('Keys to redact from log context'),\n\n /**\n * Enable source location (file/line)\n */\n sourceLocation: z.boolean().optional().default(false)\n .describe('Include file and line number'),\n\n /**\n * Log to file (optional)\n */\n file: z.string().optional().describe('Path to log file'),\n\n /**\n * Log rotation config (if file is set)\n */\n rotation: z.object({\n maxSize: z.string().optional().default('10m'),\n maxFiles: z.number().optional().default(5)\n }).optional()\n});\n\nexport type LoggerConfig = z.infer;\n\n/**\n * Log Entry Schema\n * The shape of a structured log record\n */\nexport const LogEntrySchema = z.object({\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n level: LogLevel,\n message: z.string().describe('Log message'),\n context: z.record(z.string(), z.unknown()).optional().describe('Structured context data'),\n error: z.record(z.string(), z.unknown()).optional().describe('Error object if present'),\n \n /** Tracing */\n traceId: z.string().optional().describe('Distributed trace ID'),\n spanId: z.string().optional().describe('Span ID'),\n \n /** Source */\n service: z.string().optional().describe('Service name'),\n component: z.string().optional().describe('Component name (e.g. plugin id)'),\n});\n\nexport type LogEntry = z.infer;\n\n// ============================================================================\n// Extended Logging Protocol (enterprise features)\n// ============================================================================\n\n/**\n * Extended Log Level Enum\n * Standard RFC 5424 severity levels with trace\n */\nexport const ExtendedLogLevel = z.enum([\n 'trace', // Very detailed debugging information\n 'debug', // Debugging information\n 'info', // Informational messages\n 'warn', // Warning messages\n 'error', // Error messages\n 'fatal', // Fatal errors causing shutdown\n]).describe('Extended log severity level');\n\nexport type ExtendedLogLevel = z.infer;\n\n/**\n * Log Destination Type Enum\n * Where logs can be sent\n */\nexport const LogDestinationType = z.enum([\n 'console', // Standard output/error\n 'file', // File system\n 'syslog', // System logger\n 'elasticsearch', // Elasticsearch\n 'cloudwatch', // AWS CloudWatch\n 'stackdriver', // Google Cloud Logging\n 'azure_monitor', // Azure Monitor\n 'datadog', // Datadog\n 'splunk', // Splunk\n 'loki', // Grafana Loki\n 'http', // HTTP endpoint\n 'kafka', // Apache Kafka\n 'redis', // Redis streams\n 'custom', // Custom implementation\n]).describe('Log destination type');\n\nexport type LogDestinationType = z.infer;\n\n/**\n * Console Destination Configuration\n */\nexport const ConsoleDestinationConfigSchema = z.object({\n /**\n * Output stream\n */\n stream: z.enum(['stdout', 'stderr']).optional().default('stdout'),\n\n /**\n * Enable colored output\n */\n colors: z.boolean().optional().default(true),\n\n /**\n * Pretty print JSON\n */\n prettyPrint: z.boolean().optional().default(false),\n}).describe('Console destination configuration');\n\nexport type ConsoleDestinationConfig = z.infer;\n\n/**\n * File Destination Configuration\n */\nexport const FileDestinationConfigSchema = z.object({\n /**\n * File path\n */\n path: z.string().describe('Log file path'),\n\n /**\n * Enable log rotation\n */\n rotation: z.object({\n /**\n * Maximum file size before rotation (e.g., '10m', '100k', '1g')\n */\n maxSize: z.string().optional().default('10m'),\n\n /**\n * Maximum number of files to keep\n */\n maxFiles: z.number().int().positive().optional().default(5),\n\n /**\n * Compress rotated files\n */\n compress: z.boolean().optional().default(true),\n\n /**\n * Rotation interval (e.g., 'daily', 'weekly')\n */\n interval: z.enum(['hourly', 'daily', 'weekly', 'monthly']).optional(),\n }).optional(),\n\n /**\n * File encoding\n */\n encoding: z.string().optional().default('utf8'),\n\n /**\n * Append to existing file\n */\n append: z.boolean().optional().default(true),\n}).describe('File destination configuration');\n\nexport type FileDestinationConfig = z.infer;\n\n/**\n * HTTP Destination Configuration\n */\nexport const HttpDestinationConfigSchema = z.object({\n /**\n * HTTP endpoint URL\n */\n url: z.string().url().describe('HTTP endpoint URL'),\n\n /**\n * HTTP method\n */\n method: z.enum(['POST', 'PUT']).optional().default('POST'),\n\n /**\n * Headers to include\n */\n headers: z.record(z.string(), z.string()).optional(),\n\n /**\n * Authentication\n */\n auth: z.object({\n type: z.enum(['basic', 'bearer', 'api_key']).describe('Auth type'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n apiKeyHeader: z.string().optional().default('X-API-Key'),\n }).optional(),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n /**\n * Maximum batch size\n */\n maxSize: z.number().int().positive().optional().default(100),\n\n /**\n * Flush interval in milliseconds\n */\n flushInterval: z.number().int().positive().optional().default(5000),\n }).optional(),\n\n /**\n * Retry configuration\n */\n retry: z.object({\n /**\n * Maximum retry attempts\n */\n maxAttempts: z.number().int().positive().optional().default(3),\n\n /**\n * Initial retry delay in milliseconds\n */\n initialDelay: z.number().int().positive().optional().default(1000),\n\n /**\n * Backoff multiplier\n */\n backoffMultiplier: z.number().positive().optional().default(2),\n }).optional(),\n\n /**\n * Timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().default(30000),\n}).describe('HTTP destination configuration');\n\nexport type HttpDestinationConfig = z.infer;\n\n/**\n * External Service Destination Configuration\n * Generic configuration for cloud logging services\n */\nexport const ExternalServiceDestinationConfigSchema = z.object({\n /**\n * Service-specific endpoint\n */\n endpoint: z.string().url().optional(),\n\n /**\n * Region (for cloud services)\n */\n region: z.string().optional(),\n\n /**\n * Credentials\n */\n credentials: z.object({\n accessKeyId: z.string().optional(),\n secretAccessKey: z.string().optional(),\n apiKey: z.string().optional(),\n projectId: z.string().optional(),\n }).optional(),\n\n /**\n * Log group/stream/index name\n */\n logGroup: z.string().optional(),\n logStream: z.string().optional(),\n index: z.string().optional(),\n\n /**\n * Service-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional(),\n}).describe('External service destination configuration');\n\nexport type ExternalServiceDestinationConfig = z.infer;\n\n/**\n * Log Destination Schema\n * Configuration for a single log destination\n */\nexport const LogDestinationSchema = z.object({\n /**\n * Destination name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Destination name (snake_case)'),\n\n /**\n * Destination type\n */\n type: LogDestinationType.describe('Destination type'),\n\n /**\n * Minimum log level for this destination\n */\n level: ExtendedLogLevel.optional().default('info'),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Console configuration\n */\n console: ConsoleDestinationConfigSchema.optional(),\n\n /**\n * File configuration\n */\n file: FileDestinationConfigSchema.optional(),\n\n /**\n * HTTP configuration\n */\n http: HttpDestinationConfigSchema.optional(),\n\n /**\n * External service configuration\n */\n externalService: ExternalServiceDestinationConfigSchema.optional(),\n\n /**\n * Format for this destination\n */\n format: z.enum(['json', 'text', 'pretty']).optional().default('json'),\n\n /**\n * Filter function reference (runtime only)\n */\n filterId: z.string().optional().describe('Filter function identifier'),\n}).describe('Log destination configuration');\n\nexport type LogDestination = z.infer;\n\n/**\n * Log Enrichment Configuration\n * Add contextual data to all log entries\n */\nexport const LogEnrichmentConfigSchema = z.object({\n /**\n * Static fields to add to all logs\n */\n staticFields: z.record(z.string(), z.unknown()).optional().describe('Static fields added to every log'),\n\n /**\n * Dynamic field enrichers (runtime only)\n * References to functions that add dynamic context\n */\n dynamicEnrichers: z.array(z.string()).optional().describe('Dynamic enricher function IDs'),\n\n /**\n * Add hostname\n */\n addHostname: z.boolean().optional().default(true),\n\n /**\n * Add process ID\n */\n addProcessId: z.boolean().optional().default(true),\n\n /**\n * Add environment info\n */\n addEnvironment: z.boolean().optional().default(true),\n\n /**\n * Add timestamp in additional formats\n */\n addTimestampFormats: z.object({\n unix: z.boolean().optional().default(false),\n iso: z.boolean().optional().default(true),\n }).optional(),\n\n /**\n * Add caller information (file, line, function)\n */\n addCaller: z.boolean().optional().default(false),\n\n /**\n * Add correlation IDs\n */\n addCorrelationIds: z.boolean().optional().default(true),\n}).describe('Log enrichment configuration');\n\nexport type LogEnrichmentConfig = z.infer;\n\n/**\n * Structured Log Entry Schema\n * Enhanced structured log record with enrichment\n */\nexport const StructuredLogEntrySchema = z.object({\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n\n /**\n * Log level\n */\n level: ExtendedLogLevel.describe('Log severity level'),\n\n /**\n * Log message\n */\n message: z.string().describe('Log message'),\n\n /**\n * Structured context data\n */\n context: z.record(z.string(), z.unknown()).optional().describe('Structured context'),\n\n /**\n * Error information\n */\n error: z.object({\n name: z.string().optional(),\n message: z.string().optional(),\n stack: z.string().optional(),\n code: z.string().optional(),\n details: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Error details'),\n\n /**\n * Trace context\n */\n trace: z.object({\n traceId: z.string().describe('Trace ID'),\n spanId: z.string().describe('Span ID'),\n parentSpanId: z.string().optional().describe('Parent span ID'),\n traceFlags: z.number().int().optional().describe('Trace flags'),\n }).optional().describe('Distributed tracing context'),\n\n /**\n * Source information\n */\n source: z.object({\n service: z.string().optional().describe('Service name'),\n component: z.string().optional().describe('Component name'),\n file: z.string().optional().describe('Source file'),\n line: z.number().int().optional().describe('Line number'),\n function: z.string().optional().describe('Function name'),\n }).optional().describe('Source information'),\n\n /**\n * Host information\n */\n host: z.object({\n hostname: z.string().optional(),\n pid: z.number().int().optional(),\n ip: z.string().optional(),\n }).optional().describe('Host information'),\n\n /**\n * Environment\n */\n environment: z.string().optional().describe('Environment (e.g., production, staging)'),\n\n /**\n * User information\n */\n user: z.object({\n id: z.string().optional(),\n username: z.string().optional(),\n email: z.string().optional(),\n }).optional().describe('User context'),\n\n /**\n * Request information\n */\n request: z.object({\n id: z.string().optional(),\n method: z.string().optional(),\n path: z.string().optional(),\n userAgent: z.string().optional(),\n ip: z.string().optional(),\n }).optional().describe('Request context'),\n\n /**\n * Custom labels/tags\n */\n labels: z.record(z.string(), z.string()).optional().describe('Custom labels'),\n\n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n}).describe('Structured log entry');\n\nexport type StructuredLogEntry = z.infer;\n\n/**\n * Logging Configuration Schema\n * Main configuration for the logging system\n */\nexport const LoggingConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable logging\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Global minimum log level\n */\n level: ExtendedLogLevel.optional().default('info'),\n\n /**\n * Default logger configuration\n * Basic logger config for the kernel\n */\n default: LoggerConfigSchema.optional().describe('Default logger configuration'),\n\n /**\n * Named logger configurations\n * Map of logger name to logger config for different components/modules\n */\n loggers: z.record(z.string(), LoggerConfigSchema).optional().describe('Named logger configurations'),\n\n /**\n * Log destinations\n */\n destinations: z.array(LogDestinationSchema).describe('Log destinations'),\n\n /**\n * Log enrichment configuration\n */\n enrichment: LogEnrichmentConfigSchema.optional(),\n\n /**\n * Fields to redact from logs\n */\n redact: z.array(z.string()).optional().default([\n 'password',\n 'passwordHash',\n 'token',\n 'apiKey',\n 'secret',\n 'creditCard',\n 'ssn',\n 'authorization',\n ]).describe('Fields to redact'),\n\n /**\n * Sampling configuration\n */\n sampling: z.object({\n /**\n * Enable sampling\n */\n enabled: z.boolean().optional().default(false),\n\n /**\n * Sample rate (0.0 to 1.0)\n */\n rate: z.number().min(0).max(1).optional().default(1.0),\n\n /**\n * Sample rate by level\n */\n rateByLevel: z.record(z.string(), z.number().min(0).max(1)).optional(),\n }).optional(),\n\n /**\n * Buffer configuration\n */\n buffer: z.object({\n /**\n * Enable buffering\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Buffer size\n */\n size: z.number().int().positive().optional().default(1000),\n\n /**\n * Flush interval in milliseconds\n */\n flushInterval: z.number().int().positive().optional().default(1000),\n\n /**\n * Flush on shutdown\n */\n flushOnShutdown: z.boolean().optional().default(true),\n }).optional(),\n\n /**\n * Performance configuration\n */\n performance: z.object({\n /**\n * Async logging\n */\n async: z.boolean().optional().default(true),\n\n /**\n * Worker threads for async logging\n */\n workers: z.number().int().positive().optional().default(1),\n }).optional(),\n}).describe('Logging configuration');\n\nexport type LoggingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metrics Protocol - Performance and Operational Metrics\n * \n * Comprehensive metrics collection and monitoring:\n * - Counter, Gauge, Histogram, Summary metric types\n * - Time-series data collection\n * - SLI/SLO definitions\n * - Metric aggregation and export\n * - Integration with monitoring systems (Prometheus, etc.)\n */\n\n/**\n * Metric Type Enum\n * Standard Prometheus metric types\n */\nexport const MetricType = z.enum([\n 'counter', // Monotonically increasing value\n 'gauge', // Value that can go up and down\n 'histogram', // Observations bucketed by configurable ranges\n 'summary', // Observations with quantiles\n]).describe('Metric type');\n\nexport type MetricType = z.infer;\n\n/**\n * Metric Unit Enum\n * Standard units for metrics\n */\nexport const MetricUnit = z.enum([\n // Time units\n 'nanoseconds',\n 'microseconds',\n 'milliseconds',\n 'seconds',\n 'minutes',\n 'hours',\n 'days',\n\n // Size units\n 'bytes',\n 'kilobytes',\n 'megabytes',\n 'gigabytes',\n 'terabytes',\n\n // Rate units\n 'requests_per_second',\n 'events_per_second',\n 'bytes_per_second',\n\n // Percentage\n 'percent',\n 'ratio',\n\n // Count\n 'count',\n 'operations',\n\n // Custom\n 'custom',\n]).describe('Metric unit');\n\nexport type MetricUnit = z.infer;\n\n/**\n * Metric Aggregation Type\n */\nexport const MetricAggregationType = z.enum([\n 'sum', // Sum of all values\n 'avg', // Average of all values\n 'min', // Minimum value\n 'max', // Maximum value\n 'count', // Count of observations\n 'p50', // 50th percentile (median)\n 'p75', // 75th percentile\n 'p90', // 90th percentile\n 'p95', // 95th percentile\n 'p99', // 99th percentile\n 'p999', // 99.9th percentile\n 'rate', // Rate of change\n 'stddev', // Standard deviation\n]).describe('Metric aggregation type');\n\nexport type MetricAggregationType = z.infer;\n\n/**\n * Histogram Bucket Configuration\n */\nexport const HistogramBucketConfigSchema = z.object({\n /**\n * Bucket type\n */\n type: z.enum(['linear', 'exponential', 'explicit']).describe('Bucket type'),\n\n /**\n * Linear bucket configuration\n */\n linear: z.object({\n start: z.number().describe('Start value'),\n width: z.number().positive().describe('Bucket width'),\n count: z.number().int().positive().describe('Number of buckets'),\n }).optional(),\n\n /**\n * Exponential bucket configuration\n */\n exponential: z.object({\n start: z.number().positive().describe('Start value'),\n factor: z.number().positive().describe('Growth factor'),\n count: z.number().int().positive().describe('Number of buckets'),\n }).optional(),\n\n /**\n * Explicit bucket boundaries\n */\n explicit: z.object({\n boundaries: z.array(z.number()).describe('Bucket boundaries'),\n }).optional(),\n}).describe('Histogram bucket configuration');\n\nexport type HistogramBucketConfig = z.infer;\n\n/**\n * Metric Labels Schema\n * Key-value pairs for metric dimensions\n */\nexport const MetricLabelsSchema = z.record(z.string(), z.string()).describe('Metric labels');\n\nexport type MetricLabels = z.infer;\n\n/**\n * Metric Definition Schema\n */\nexport const MetricDefinitionSchema = z.object({\n /**\n * Metric name (snake_case)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Metric name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().optional().describe('Display label'),\n\n /**\n * Metric type\n */\n type: MetricType.describe('Metric type'),\n\n /**\n * Metric unit\n */\n unit: MetricUnit.optional().describe('Metric unit'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('Metric description'),\n\n /**\n * Label names for this metric\n */\n labelNames: z.array(z.string()).optional().default([]).describe('Label names'),\n\n /**\n * Histogram configuration (for histogram type)\n */\n histogram: HistogramBucketConfigSchema.optional(),\n\n /**\n * Summary configuration (for summary type)\n */\n summary: z.object({\n /**\n * Quantiles to track\n */\n quantiles: z.array(z.number().min(0).max(1)).optional().default([0.5, 0.9, 0.99]),\n\n /**\n * Max age of observations in seconds\n */\n maxAge: z.number().int().positive().optional().default(600),\n\n /**\n * Number of age buckets\n */\n ageBuckets: z.number().int().positive().optional().default(5),\n }).optional(),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Metric definition');\n\nexport type MetricDefinition = z.infer;\n\n/**\n * Metric Data Point Schema\n * A single metric observation\n */\nexport const MetricDataPointSchema = z.object({\n /**\n * Metric name\n */\n name: z.string().describe('Metric name'),\n\n /**\n * Metric type\n */\n type: MetricType.describe('Metric type'),\n\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Observation timestamp'),\n\n /**\n * Value (for counter and gauge)\n */\n value: z.number().optional().describe('Metric value'),\n\n /**\n * Labels\n */\n labels: MetricLabelsSchema.optional().describe('Metric labels'),\n\n /**\n * Histogram data\n */\n histogram: z.object({\n count: z.number().int().nonnegative().describe('Total count'),\n sum: z.number().describe('Sum of all values'),\n buckets: z.array(z.object({\n upperBound: z.number().describe('Upper bound of bucket'),\n count: z.number().int().nonnegative().describe('Count in bucket'),\n })).describe('Histogram buckets'),\n }).optional(),\n\n /**\n * Summary data\n */\n summary: z.object({\n count: z.number().int().nonnegative().describe('Total count'),\n sum: z.number().describe('Sum of all values'),\n quantiles: z.array(z.object({\n quantile: z.number().min(0).max(1).describe('Quantile (0-1)'),\n value: z.number().describe('Quantile value'),\n })).describe('Summary quantiles'),\n }).optional(),\n}).describe('Metric data point');\n\nexport type MetricDataPoint = z.infer;\n\n/**\n * Time Series Data Point Schema\n */\nexport const TimeSeriesDataPointSchema = z.object({\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Timestamp'),\n\n /**\n * Value\n */\n value: z.number().describe('Value'),\n\n /**\n * Labels/tags\n */\n labels: z.record(z.string(), z.string()).optional().describe('Labels'),\n}).describe('Time series data point');\n\nexport type TimeSeriesDataPoint = z.infer;\n\n/**\n * Time Series Schema\n */\nexport const TimeSeriesSchema = z.object({\n /**\n * Series name\n */\n name: z.string().describe('Series name'),\n\n /**\n * Series labels\n */\n labels: z.record(z.string(), z.string()).optional().describe('Series labels'),\n\n /**\n * Data points\n */\n dataPoints: z.array(TimeSeriesDataPointSchema).describe('Data points'),\n\n /**\n * Start time\n */\n startTime: z.string().datetime().optional().describe('Start time'),\n\n /**\n * End time\n */\n endTime: z.string().datetime().optional().describe('End time'),\n}).describe('Time series');\n\nexport type TimeSeries = z.infer;\n\n/**\n * Metric Aggregation Configuration\n */\nexport const MetricAggregationConfigSchema = z.object({\n /**\n * Aggregation type\n */\n type: MetricAggregationType.describe('Aggregation type'),\n\n /**\n * Time window for aggregation\n */\n window: z.object({\n /**\n * Window size in seconds\n */\n size: z.number().int().positive().describe('Window size in seconds'),\n\n /**\n * Sliding window (true) or tumbling window (false)\n */\n sliding: z.boolean().optional().default(false),\n\n /**\n * Slide interval for sliding windows\n */\n slideInterval: z.number().int().positive().optional(),\n }).optional(),\n\n /**\n * Group by labels\n */\n groupBy: z.array(z.string()).optional().describe('Group by label names'),\n\n /**\n * Filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter criteria'),\n}).describe('Metric aggregation configuration');\n\nexport type MetricAggregationConfig = z.infer;\n\n/**\n * Service Level Indicator (SLI) Schema\n */\nexport const ServiceLevelIndicatorSchema = z.object({\n /**\n * SLI name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('SLI name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('SLI description'),\n\n /**\n * Metric name this SLI is based on\n */\n metric: z.string().describe('Base metric name'),\n\n /**\n * SLI type\n */\n type: z.enum([\n 'availability', // Percentage of successful requests\n 'latency', // Response time percentile\n 'throughput', // Requests per second\n 'error_rate', // Error percentage\n 'saturation', // Resource utilization\n 'custom', // Custom calculation\n ]).describe('SLI type'),\n\n /**\n * Success criteria\n */\n successCriteria: z.object({\n /**\n * Threshold value\n */\n threshold: z.number().describe('Threshold value'),\n\n /**\n * Comparison operator\n */\n operator: z.enum(['lt', 'lte', 'gt', 'gte', 'eq']).describe('Comparison operator'),\n\n /**\n * Percentile (for latency SLIs)\n */\n percentile: z.number().min(0).max(1).optional().describe('Percentile (0-1)'),\n }).describe('Success criteria'),\n\n /**\n * Measurement window\n */\n window: z.object({\n /**\n * Window size in seconds\n */\n size: z.number().int().positive().describe('Window size in seconds'),\n\n /**\n * Rolling window (true) or calendar-aligned (false)\n */\n rolling: z.boolean().optional().default(true),\n }).describe('Measurement window'),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Service Level Indicator');\n\nexport type ServiceLevelIndicator = z.infer;\n\n/**\n * Service Level Objective (SLO) Schema\n */\nexport const ServiceLevelObjectiveSchema = z.object({\n /**\n * SLO name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('SLO name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('SLO description'),\n\n /**\n * SLI this SLO is based on\n */\n sli: z.string().describe('SLI name'),\n\n /**\n * Target percentage (0-100)\n */\n target: z.number().min(0).max(100).describe('Target percentage'),\n\n /**\n * Time period for SLO\n */\n period: z.object({\n /**\n * Period type\n */\n type: z.enum(['rolling', 'calendar']).describe('Period type'),\n\n /**\n * Duration in seconds (for rolling)\n */\n duration: z.number().int().positive().optional().describe('Duration in seconds'),\n\n /**\n * Calendar period (for calendar)\n */\n calendar: z.enum(['daily', 'weekly', 'monthly', 'quarterly', 'yearly']).optional(),\n }).describe('Time period'),\n\n /**\n * Error budget configuration\n */\n errorBudget: z.object({\n /**\n * Auto-calculated budget (1 - target)\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Alert when budget consumed percentage exceeds threshold\n */\n alertThreshold: z.number().min(0).max(100).optional().default(80),\n\n /**\n * Burn rate alert windows\n */\n burnRateWindows: z.array(z.object({\n /**\n * Window size in seconds\n */\n window: z.number().int().positive().describe('Window size'),\n\n /**\n * Burn rate multiplier threshold\n */\n threshold: z.number().positive().describe('Burn rate threshold'),\n })).optional(),\n }).optional(),\n\n /**\n * Alert configuration\n */\n alerts: z.array(z.object({\n /**\n * Alert name\n */\n name: z.string().describe('Alert name'),\n\n /**\n * Severity\n */\n severity: z.enum(['info', 'warning', 'critical']).describe('Alert severity'),\n\n /**\n * Condition\n */\n condition: z.object({\n type: z.enum(['slo_breach', 'error_budget', 'burn_rate']).describe('Condition type'),\n threshold: z.number().optional().describe('Threshold value'),\n }).describe('Alert condition'),\n })).optional().default([]),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Service Level Objective');\n\nexport type ServiceLevelObjective = z.infer;\n\n/**\n * Metric Export Configuration\n */\nexport const MetricExportConfigSchema = z.object({\n /**\n * Export type\n */\n type: z.enum([\n 'prometheus', // Prometheus exposition format\n 'openmetrics', // OpenMetrics format\n 'graphite', // Graphite plaintext protocol\n 'statsd', // StatsD protocol\n 'influxdb', // InfluxDB line protocol\n 'datadog', // Datadog agent\n 'cloudwatch', // AWS CloudWatch\n 'stackdriver', // Google Cloud Monitoring\n 'azure_monitor', // Azure Monitor\n 'http', // HTTP push\n 'custom', // Custom exporter\n ]).describe('Export type'),\n\n /**\n * Endpoint configuration\n */\n endpoint: z.string().optional().describe('Export endpoint'),\n\n /**\n * Export interval in seconds\n */\n interval: z.number().int().positive().optional().default(60),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n enabled: z.boolean().optional().default(true),\n size: z.number().int().positive().optional().default(1000),\n }).optional(),\n\n /**\n * Authentication\n */\n auth: z.object({\n type: z.enum(['none', 'basic', 'bearer', 'api_key']).describe('Auth type'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n }).optional(),\n\n /**\n * Additional configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Additional configuration'),\n}).describe('Metric export configuration');\n\nexport type MetricExportConfig = z.infer;\n\n/**\n * Metrics Configuration Schema\n */\nexport const MetricsConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable metrics collection\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Metric definitions\n */\n metrics: z.array(MetricDefinitionSchema).optional().default([]),\n\n /**\n * Default labels applied to all metrics\n */\n defaultLabels: MetricLabelsSchema.optional().default({}),\n\n /**\n * Aggregation configurations\n */\n aggregations: z.array(MetricAggregationConfigSchema).optional().default([]),\n\n /**\n * Service Level Indicators\n */\n slis: z.array(ServiceLevelIndicatorSchema).optional().default([]),\n\n /**\n * Service Level Objectives\n */\n slos: z.array(ServiceLevelObjectiveSchema).optional().default([]),\n\n /**\n * Export configurations\n */\n exports: z.array(MetricExportConfigSchema).optional().default([]),\n\n /**\n * Collection interval in seconds\n */\n collectionInterval: z.number().int().positive().optional().default(15),\n\n /**\n * Retention configuration\n */\n retention: z.object({\n /**\n * Retention period in seconds\n */\n period: z.number().int().positive().optional().default(604800), // 7 days\n\n /**\n * Downsampling configuration\n */\n downsampling: z.array(z.object({\n /**\n * After this duration, downsample to this resolution\n */\n afterSeconds: z.number().int().positive().describe('Downsample after seconds'),\n\n /**\n * Resolution in seconds\n */\n resolution: z.number().int().positive().describe('Downsampled resolution'),\n })).optional(),\n }).optional(),\n\n /**\n * Cardinality limits\n */\n cardinalityLimits: z.object({\n /**\n * Maximum unique label combinations per metric\n */\n maxLabelCombinations: z.number().int().positive().optional().default(10000),\n\n /**\n * Action when limit exceeded\n */\n onLimitExceeded: z.enum(['drop', 'sample', 'alert']).optional().default('alert'),\n }).optional(),\n}).describe('Metrics configuration');\n\nexport type MetricsConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tracing Protocol - Distributed Tracing & Observability\n * \n * Comprehensive distributed tracing based on OpenTelemetry standards:\n * - Trace context propagation\n * - Span creation and management\n * - Sampling strategies\n * - Integration with tracing backends (Jaeger, Zipkin, etc.)\n * - W3C Trace Context standard compliance\n */\n\n/**\n * Trace State Schema\n * W3C Trace Context tracestate header\n */\nexport const TraceStateSchema = z.object({\n /**\n * Vendor-specific key-value pairs\n */\n entries: z.record(z.string(), z.string()).describe('Trace state entries'),\n}).describe('Trace state');\n\nexport type TraceState = z.infer;\n\n/**\n * Trace Flags Enum\n * W3C Trace Context trace flags\n */\nexport const TraceFlagsSchema = z.number().int().min(0).max(255).describe('Trace flags bitmap');\n\nexport type TraceFlags = z.infer;\n\n/**\n * Trace Context Schema\n * W3C Trace Context standard\n */\nexport const TraceContextSchema = z.object({\n /**\n * Trace ID (128-bit identifier, 32 hex chars)\n */\n traceId: z.string()\n .regex(/^[0-9a-f]{32}$/)\n .describe('Trace ID (32 hex chars)'),\n\n /**\n * Span ID (64-bit identifier, 16 hex chars)\n */\n spanId: z.string()\n .regex(/^[0-9a-f]{16}$/)\n .describe('Span ID (16 hex chars)'),\n\n /**\n * Trace flags (8-bit)\n */\n traceFlags: TraceFlagsSchema.optional().default(1),\n\n /**\n * Trace state (vendor-specific)\n */\n traceState: TraceStateSchema.optional(),\n\n /**\n * Parent span ID\n */\n parentSpanId: z.string()\n .regex(/^[0-9a-f]{16}$/)\n .optional()\n .describe('Parent span ID (16 hex chars)'),\n\n /**\n * Is sampled\n */\n sampled: z.boolean().optional().default(true),\n\n /**\n * Remote context (from incoming request)\n */\n remote: z.boolean().optional().default(false),\n}).describe('Trace context (W3C Trace Context)');\n\nexport type TraceContext = z.infer;\n\n/**\n * Span Kind Enum\n * OpenTelemetry span kinds\n */\nexport const SpanKind = z.enum([\n 'internal', // Internal operation\n 'server', // Server-side request handling\n 'client', // Client-side request\n 'producer', // Message producer\n 'consumer', // Message consumer\n]).describe('Span kind');\n\nexport type SpanKind = z.infer;\n\n/**\n * Span Status Enum\n * OpenTelemetry span status\n */\nexport const SpanStatus = z.enum([\n 'unset', // Default status\n 'ok', // Successful operation\n 'error', // Error occurred\n]).describe('Span status');\n\nexport type SpanStatus = z.infer;\n\n/**\n * Span Attribute Value Schema\n */\nexport const SpanAttributeValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.array(z.string()),\n z.array(z.number()),\n z.array(z.boolean()),\n]).describe('Span attribute value');\n\nexport type SpanAttributeValue = z.infer;\n\n/**\n * Span Attributes Schema\n * OpenTelemetry semantic conventions\n */\nexport const SpanAttributesSchema = z.record(z.string(), SpanAttributeValueSchema).describe('Span attributes');\n\nexport type SpanAttributes = z.infer;\n\n/**\n * Span Event Schema\n */\nexport const SpanEventSchema = z.object({\n /**\n * Event name\n */\n name: z.string().describe('Event name'),\n\n /**\n * Event timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /**\n * Event attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Event attributes'),\n}).describe('Span event');\n\nexport type SpanEvent = z.infer;\n\n/**\n * Span Link Schema\n * Links to other spans\n */\nexport const SpanLinkSchema = z.object({\n /**\n * Linked trace context\n */\n context: TraceContextSchema.describe('Linked trace context'),\n\n /**\n * Link attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Link attributes'),\n}).describe('Span link');\n\nexport type SpanLink = z.infer;\n\n/**\n * Span Schema\n * OpenTelemetry span representation\n */\nexport const SpanSchema = z.object({\n /**\n * Trace context\n */\n context: TraceContextSchema.describe('Trace context'),\n\n /**\n * Span name\n */\n name: z.string().describe('Span name'),\n\n /**\n * Span kind\n */\n kind: SpanKind.optional().default('internal'),\n\n /**\n * Start time (ISO 8601)\n */\n startTime: z.string().datetime().describe('Span start time'),\n\n /**\n * End time (ISO 8601)\n */\n endTime: z.string().datetime().optional().describe('Span end time'),\n\n /**\n * Duration in milliseconds\n */\n duration: z.number().nonnegative().optional().describe('Duration in milliseconds'),\n\n /**\n * Span status\n */\n status: z.object({\n code: SpanStatus.describe('Status code'),\n message: z.string().optional().describe('Status message'),\n }).optional(),\n\n /**\n * Span attributes\n */\n attributes: SpanAttributesSchema.optional().default({}),\n\n /**\n * Span events\n */\n events: z.array(SpanEventSchema).optional().default([]),\n\n /**\n * Span links\n */\n links: z.array(SpanLinkSchema).optional().default([]),\n\n /**\n * Resource attributes\n */\n resource: SpanAttributesSchema.optional().describe('Resource attributes'),\n\n /**\n * Instrumentation library\n */\n instrumentationLibrary: z.object({\n name: z.string().describe('Library name'),\n version: z.string().optional().describe('Library version'),\n }).optional(),\n}).describe('OpenTelemetry span');\n\nexport type Span = z.infer;\n\n/**\n * Sampling Decision Enum\n */\nexport const SamplingDecision = z.enum([\n 'drop', // Do not record or export\n 'record_only', // Record but do not export\n 'record_and_sample', // Record and export\n]).describe('Sampling decision');\n\nexport type SamplingDecision = z.infer;\n\n/**\n * Sampling Strategy Type Enum\n */\nexport const SamplingStrategyType = z.enum([\n 'always_on', // Always sample\n 'always_off', // Never sample\n 'trace_id_ratio', // Sample based on trace ID ratio\n 'rate_limiting', // Rate-limited sampling\n 'parent_based', // Respect parent span sampling decision\n 'probability', // Probability-based sampling\n 'composite', // Combine multiple strategies\n 'custom', // Custom sampling logic\n]).describe('Sampling strategy type');\n\nexport type SamplingStrategyType = z.infer;\n\n/**\n * Trace Sampling Configuration Schema\n */\nexport const TraceSamplingConfigSchema = z.object({\n /**\n * Sampling strategy type\n */\n type: SamplingStrategyType.describe('Sampling strategy'),\n\n /**\n * Sample ratio (0.0 to 1.0) for trace_id_ratio and probability strategies\n */\n ratio: z.number().min(0).max(1).optional().describe('Sample ratio (0-1)'),\n\n /**\n * Rate limit (traces per second) for rate_limiting strategy\n */\n rateLimit: z.number().positive().optional().describe('Traces per second'),\n\n /**\n * Parent-based configuration\n */\n parentBased: z.object({\n /**\n * Sampler to use when parent is sampled\n */\n whenParentSampled: SamplingStrategyType.optional().default('always_on'),\n\n /**\n * Sampler to use when parent is not sampled\n */\n whenParentNotSampled: SamplingStrategyType.optional().default('always_off'),\n\n /**\n * Sampler to use when there is no parent (root span)\n */\n root: SamplingStrategyType.optional().default('trace_id_ratio'),\n\n /**\n * Root sampler ratio\n */\n rootRatio: z.number().min(0).max(1).optional().default(0.1),\n }).optional(),\n\n /**\n * Composite sampling (multiple strategies)\n */\n composite: z.array(z.object({\n strategy: SamplingStrategyType.describe('Strategy type'),\n ratio: z.number().min(0).max(1).optional(),\n condition: z.record(z.string(), z.unknown()).optional().describe('Condition for this strategy'),\n })).optional(),\n\n /**\n * Sampling rules\n */\n rules: z.array(z.object({\n /**\n * Rule name\n */\n name: z.string().describe('Rule name'),\n\n /**\n * Match condition\n */\n match: z.object({\n /**\n * Service name pattern\n */\n service: z.string().optional(),\n\n /**\n * Span name pattern (regex)\n */\n spanName: z.string().optional(),\n\n /**\n * Attribute filters\n */\n attributes: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n\n /**\n * Sampling decision for matching spans\n */\n decision: SamplingDecision.describe('Sampling decision'),\n\n /**\n * Sample rate for this rule\n */\n rate: z.number().min(0).max(1).optional(),\n })).optional().default([]),\n\n /**\n * Custom sampler ID (for custom strategy)\n */\n customSamplerId: z.string().optional().describe('Custom sampler identifier'),\n}).describe('Trace sampling configuration');\n\nexport type TraceSamplingConfig = z.infer;\n\n/**\n * Trace Context Propagation Format Enum\n */\nexport const TracePropagationFormat = z.enum([\n 'w3c', // W3C Trace Context\n 'b3', // Zipkin B3 (single header)\n 'b3_multi', // Zipkin B3 (multi header)\n 'jaeger', // Jaeger propagation\n 'xray', // AWS X-Ray\n 'ottrace', // OpenTracing\n 'custom', // Custom format\n]).describe('Trace propagation format');\n\nexport type TracePropagationFormat = z.infer;\n\n/**\n * Trace Context Propagation Schema\n */\nexport const TraceContextPropagationSchema = z.object({\n /**\n * Propagation formats (in priority order)\n */\n formats: z.array(TracePropagationFormat).optional().default(['w3c']),\n\n /**\n * Extract context from incoming requests\n */\n extract: z.boolean().optional().default(true),\n\n /**\n * Inject context into outgoing requests\n */\n inject: z.boolean().optional().default(true),\n\n /**\n * Custom header mappings\n */\n headers: z.object({\n /**\n * Trace ID header name\n */\n traceId: z.string().optional(),\n\n /**\n * Span ID header name\n */\n spanId: z.string().optional(),\n\n /**\n * Trace flags header name\n */\n traceFlags: z.string().optional(),\n\n /**\n * Trace state header name\n */\n traceState: z.string().optional(),\n }).optional(),\n\n /**\n * Baggage propagation\n */\n baggage: z.object({\n /**\n * Enable baggage propagation\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Maximum baggage size in bytes\n */\n maxSize: z.number().int().positive().optional().default(8192),\n\n /**\n * Allowed baggage keys (whitelist)\n */\n allowedKeys: z.array(z.string()).optional(),\n }).optional(),\n}).describe('Trace context propagation');\n\nexport type TraceContextPropagation = z.infer;\n\n/**\n * OpenTelemetry Exporter Type Enum\n */\nexport const OtelExporterType = z.enum([\n 'otlp_http', // OTLP over HTTP\n 'otlp_grpc', // OTLP over gRPC\n 'jaeger', // Jaeger\n 'zipkin', // Zipkin\n 'console', // Console (for debugging)\n 'datadog', // Datadog\n 'honeycomb', // Honeycomb\n 'lightstep', // Lightstep\n 'newrelic', // New Relic\n 'custom', // Custom exporter\n]).describe('OpenTelemetry exporter type');\n\nexport type OtelExporterType = z.infer;\n\n/**\n * OpenTelemetry Compatibility Schema\n */\nexport const OpenTelemetryCompatibilitySchema = z.object({\n /**\n * OpenTelemetry SDK version\n */\n sdkVersion: z.string().optional().describe('OTel SDK version'),\n\n /**\n * Exporter configuration\n */\n exporter: z.object({\n /**\n * Exporter type\n */\n type: OtelExporterType.describe('Exporter type'),\n\n /**\n * Endpoint URL\n */\n endpoint: z.string().url().optional().describe('Exporter endpoint'),\n\n /**\n * Protocol version\n */\n protocol: z.string().optional().describe('Protocol version'),\n\n /**\n * Headers\n */\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n\n /**\n * Timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().default(10000),\n\n /**\n * Compression\n */\n compression: z.enum(['none', 'gzip']).optional().default('none'),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n /**\n * Maximum batch size\n */\n maxBatchSize: z.number().int().positive().optional().default(512),\n\n /**\n * Maximum queue size\n */\n maxQueueSize: z.number().int().positive().optional().default(2048),\n\n /**\n * Export timeout in milliseconds\n */\n exportTimeout: z.number().int().positive().optional().default(30000),\n\n /**\n * Scheduled delay in milliseconds\n */\n scheduledDelay: z.number().int().positive().optional().default(5000),\n }).optional(),\n }).describe('Exporter configuration'),\n\n /**\n * Resource attributes (service identification)\n */\n resource: z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Service name'),\n\n /**\n * Service version\n */\n serviceVersion: z.string().optional().describe('Service version'),\n\n /**\n * Service instance ID\n */\n serviceInstanceId: z.string().optional().describe('Service instance ID'),\n\n /**\n * Service namespace\n */\n serviceNamespace: z.string().optional().describe('Service namespace'),\n\n /**\n * Deployment environment\n */\n deploymentEnvironment: z.string().optional().describe('Deployment environment'),\n\n /**\n * Additional resource attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Additional resource attributes'),\n }).describe('Resource attributes'),\n\n /**\n * Instrumentation configuration\n */\n instrumentation: z.object({\n /**\n * Auto-instrumentation enabled\n */\n autoInstrumentation: z.boolean().optional().default(true),\n\n /**\n * Instrumentation libraries to enable\n */\n libraries: z.array(z.string()).optional().describe('Enabled libraries'),\n\n /**\n * Instrumentation libraries to disable\n */\n disabledLibraries: z.array(z.string()).optional().describe('Disabled libraries'),\n }).optional(),\n\n /**\n * Semantic conventions version\n */\n semanticConventionsVersion: z.string().optional().describe('Semantic conventions version'),\n}).describe('OpenTelemetry compatibility configuration');\n\nexport type OpenTelemetryCompatibility = z.infer;\n\n/**\n * Tracing Configuration Schema\n */\nexport const TracingConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable tracing\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Sampling configuration\n */\n sampling: TraceSamplingConfigSchema.optional().default({ type: 'always_on', rules: [] }),\n\n /**\n * Context propagation\n */\n propagation: TraceContextPropagationSchema.optional().default({ formats: ['w3c'], extract: true, inject: true }),\n\n /**\n * OpenTelemetry configuration\n */\n openTelemetry: OpenTelemetryCompatibilitySchema.optional(),\n\n /**\n * Span limits\n */\n spanLimits: z.object({\n /**\n * Maximum number of attributes per span\n */\n maxAttributes: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum number of events per span\n */\n maxEvents: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum number of links per span\n */\n maxLinks: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum attribute value length\n */\n maxAttributeValueLength: z.number().int().positive().optional().default(4096),\n }).optional(),\n\n /**\n * Trace ID generator\n */\n traceIdGenerator: z.enum(['random', 'uuid', 'custom']).optional().default('random'),\n\n /**\n * Custom trace ID generator ID\n */\n customTraceIdGeneratorId: z.string().optional().describe('Custom generator identifier'),\n\n /**\n * Performance configuration\n */\n performance: z.object({\n /**\n * Async span export\n */\n asyncExport: z.boolean().optional().default(true),\n\n /**\n * Background export interval in milliseconds\n */\n exportInterval: z.number().int().positive().optional().default(5000),\n }).optional(),\n}).describe('Tracing configuration');\n\nexport type TracingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Security Context Protocol\n *\n * Provides a central governance layer that correlates and unifies\n * the four independent security subsystems:\n * - **Audit** (audit.zod.ts): Event logging and suspicious activity detection\n * - **Encryption** (encryption.zod.ts): Field-level encryption and key management\n * - **Compliance** (compliance.zod.ts): Regulatory framework enforcement (GDPR/HIPAA/SOX/PCI-DSS)\n * - **Masking** (masking.zod.ts): PII data masking and tokenization\n *\n * This schema enforces cross-cutting security policies, ensuring compliance\n * frameworks drive encryption requirements, masking rules respect role-based\n * audit visibility, and all security operations are correlated in a single\n * governance context.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Shared data classification enum used across security subsystems.\n * Defines the canonical set of data sensitivity labels.\n */\nexport const DataClassificationSchema = z.enum([\n 'pii', 'phi', 'pci', 'financial', 'confidential', 'internal', 'public',\n]).describe('Data classification level');\n\nexport type DataClassification = z.infer;\n\n/**\n * Shared compliance framework enum used across compliance and security schemas.\n * Defines the canonical set of regulatory frameworks.\n */\nexport const ComplianceFrameworkSchema = z.enum([\n 'gdpr', 'hipaa', 'sox', 'pci_dss', 'ccpa', 'iso27001',\n]).describe('Compliance framework identifier');\n\nexport type ComplianceFramework = z.infer;\n\n/**\n * Compliance-driven audit requirement.\n * Maps specific compliance frameworks to the audit event types that MUST be captured.\n */\nexport const ComplianceAuditRequirementSchema = z.object({\n framework: ComplianceFrameworkSchema\n .describe('Compliance framework identifier'),\n requiredEvents: z.array(z.string())\n .describe('Audit event types required by this framework (e.g., \"data.delete\", \"auth.login\")'),\n retentionDays: z.number().min(1)\n .describe('Minimum audit log retention period required by this framework (in days)'),\n alertOnMissing: z.boolean().default(true)\n .describe('Raise alert if a required audit event is not being captured'),\n}).describe('Compliance framework audit event requirements');\n\nexport type ComplianceAuditRequirement = z.infer;\n\n/**\n * Compliance-driven encryption requirement.\n * Maps compliance frameworks to encryption mandates for specific data classifications.\n */\nexport const ComplianceEncryptionRequirementSchema = z.object({\n framework: ComplianceFrameworkSchema\n .describe('Compliance framework identifier'),\n dataClassifications: z.array(DataClassificationSchema)\n .describe('Data classifications that must be encrypted under this framework'),\n minimumAlgorithm: z.enum(['aes-256-gcm', 'aes-256-cbc', 'chacha20-poly1305']).default('aes-256-gcm')\n .describe('Minimum encryption algorithm strength required'),\n keyRotationMaxDays: z.number().min(1).default(90)\n .describe('Maximum key rotation interval required (in days)'),\n}).describe('Compliance framework encryption requirements');\n\nexport type ComplianceEncryptionRequirement = z.infer;\n\n/**\n * Masking visibility rule.\n * Controls which roles can view unmasked data with audit trail enforcement.\n */\nexport const MaskingVisibilityRuleSchema = z.object({\n dataClassification: DataClassificationSchema\n .describe('Data classification this rule applies to'),\n defaultMasked: z.boolean().default(true)\n .describe('Whether data is masked by default'),\n unmaskRoles: z.array(z.string()).optional()\n .describe('Roles allowed to view unmasked data'),\n auditUnmask: z.boolean().default(true)\n .describe('Log an audit event when data is unmasked'),\n requireApproval: z.boolean().default(false)\n .describe('Require explicit approval before unmasking'),\n approvalRoles: z.array(z.string()).optional()\n .describe('Roles that can approve unmasking requests'),\n}).describe('Masking visibility and audit rule per data classification');\n\nexport type MaskingVisibilityRule = z.infer;\n\n/**\n * Security Event Correlation Schema.\n * Defines how security events from different subsystems are correlated.\n */\nexport const SecurityEventCorrelationSchema = z.object({\n enabled: z.boolean().default(true)\n .describe('Enable cross-subsystem security event correlation'),\n correlationId: z.boolean().default(true)\n .describe('Inject a shared correlation ID into audit, encryption, and masking events'),\n linkAuthToAudit: z.boolean().default(true)\n .describe('Link authentication events to subsequent data operation audit trails'),\n linkEncryptionToAudit: z.boolean().default(true)\n .describe('Log encryption/decryption operations in the audit trail'),\n linkMaskingToAudit: z.boolean().default(true)\n .describe('Log masking/unmasking operations in the audit trail'),\n}).describe('Cross-subsystem security event correlation configuration');\n\nexport type SecurityEventCorrelation = z.infer;\n\n/**\n * Data Classification Policy Schema.\n * Assigns classification labels to fields/objects for unified security enforcement.\n */\nexport const DataClassificationPolicySchema = z.object({\n classification: DataClassificationSchema\n .describe('Data classification level'),\n requireEncryption: z.boolean().default(false)\n .describe('Encryption required for this classification'),\n requireMasking: z.boolean().default(false)\n .describe('Masking required for this classification'),\n requireAudit: z.boolean().default(false)\n .describe('Audit trail required for access to this classification'),\n retentionDays: z.number().optional()\n .describe('Data retention limit in days (for compliance)'),\n}).describe('Security policy for a specific data classification level');\n\nexport type DataClassificationPolicy = z.infer;\n\n/**\n * Security Context Configuration Schema\n *\n * Top-level unified security governance context that ties together\n * audit, encryption, compliance, and masking subsystems.\n */\nexport const SecurityContextConfigSchema = z.object({\n enabled: z.boolean().default(true)\n .describe('Enable unified security context governance'),\n\n complianceAuditRequirements: z.array(ComplianceAuditRequirementSchema).optional()\n .describe('Compliance-driven audit event requirements'),\n\n complianceEncryptionRequirements: z.array(ComplianceEncryptionRequirementSchema).optional()\n .describe('Compliance-driven encryption requirements by data classification'),\n\n maskingVisibility: z.array(MaskingVisibilityRuleSchema).optional()\n .describe('Masking visibility rules per data classification'),\n\n dataClassifications: z.array(DataClassificationPolicySchema).optional()\n .describe('Data classification policies for unified security enforcement'),\n\n eventCorrelation: SecurityEventCorrelationSchema.optional()\n .describe('Cross-subsystem security event correlation settings'),\n\n enforceOnWrite: z.boolean().default(true)\n .describe('Enforce encryption and masking requirements on data write operations'),\n\n enforceOnRead: z.boolean().default(true)\n .describe('Enforce masking and audit requirements on data read operations'),\n\n failOpen: z.boolean().default(false)\n .describe('When false (default), deny access if security context cannot be evaluated'),\n}).describe('Unified security context governance configuration');\n\nexport type SecurityContextConfig = z.infer;\nexport type SecurityContextConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Change Type Enum\n * \n * Classification of change requests based on risk and approval requirements.\n * Follows ITIL change management best practices.\n */\nexport const ChangeTypeSchema = z.enum([\n 'standard', // Pre-approved, low-risk changes\n 'normal', // Requires standard approval process\n 'emergency', // Fast-track approval for critical issues\n 'major', // Requires CAB (Change Advisory Board) approval\n]);\n\n/**\n * Change Priority Enum\n * \n * Priority level for change request processing.\n */\nexport const ChangePrioritySchema = z.enum([\n 'critical',\n 'high',\n 'medium',\n 'low',\n]);\n\n/**\n * Change Status Enum\n * \n * Current status of a change request in its lifecycle.\n */\nexport const ChangeStatusSchema = z.enum([\n 'draft',\n 'submitted',\n 'in-review',\n 'approved',\n 'scheduled',\n 'in-progress',\n 'completed',\n 'failed',\n 'rolled-back',\n 'cancelled',\n]);\n\n/**\n * Change Impact Schema\n * \n * Assessment of the impact and scope of a change request.\n * Used for risk evaluation and approval routing.\n * \n * @example\n * ```json\n * {\n * \"level\": \"high\",\n * \"affectedSystems\": [\"crm-api\", \"customer-portal\"],\n * \"affectedUsers\": 5000,\n * \"downtime\": {\n * \"required\": true,\n * \"durationMinutes\": 30\n * }\n * }\n * ```\n */\nexport const ChangeImpactSchema = z.object({\n /**\n * Overall impact level of the change\n */\n level: z.enum(['low', 'medium', 'high', 'critical']).describe('Impact level'),\n\n /**\n * List of systems affected by this change\n */\n affectedSystems: z.array(z.string()).describe('Affected systems'),\n\n /**\n * Estimated number of users affected\n */\n affectedUsers: z.number().optional().describe('Affected user count'),\n\n /**\n * Downtime requirements\n */\n downtime: z.object({\n /**\n * Whether downtime is required\n */\n required: z.boolean().describe('Downtime required'),\n\n /**\n * Duration of downtime in minutes\n */\n durationMinutes: z.number().optional().describe('Downtime duration'),\n }).optional().describe('Downtime information'),\n});\n\n/**\n * Rollback Plan Schema\n * \n * Detailed procedure for reverting changes if implementation fails.\n * Required for all non-standard changes.\n * \n * @example\n * ```json\n * {\n * \"description\": \"Revert database schema to previous version\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Stop application servers\",\n * \"estimatedMinutes\": 5\n * },\n * {\n * \"order\": 2,\n * \"description\": \"Restore database backup\",\n * \"estimatedMinutes\": 15\n * }\n * ],\n * \"testProcedure\": \"Verify application login and basic functionality\"\n * }\n * ```\n */\nexport const RollbackPlanSchema = z.object({\n /**\n * High-level description of the rollback approach\n */\n description: z.string().describe('Rollback description'),\n\n /**\n * Sequential steps to execute rollback\n */\n steps: z.array(z.object({\n /**\n * Step execution order\n */\n order: z.number().describe('Step order'),\n\n /**\n * Detailed description of this step\n */\n description: z.string().describe('Step description'),\n\n /**\n * Estimated time to complete this step\n */\n estimatedMinutes: z.number().describe('Estimated duration'),\n })).describe('Rollback steps'),\n\n /**\n * Testing procedure to verify successful rollback\n */\n testProcedure: z.string().optional().describe('Test procedure'),\n});\n\n/**\n * Change Request Schema\n * \n * Comprehensive change management protocol for IT governance.\n * Supports change requests, deployment tracking, and ITIL compliance.\n * \n * @example\n * ```json\n * {\n * \"id\": \"CHG-2024-001\",\n * \"title\": \"Upgrade CRM Database Schema\",\n * \"description\": \"Migrate customer database to new schema version 2.0\",\n * \"type\": \"normal\",\n * \"priority\": \"high\",\n * \"status\": \"approved\",\n * \"requestedBy\": \"user_123\",\n * \"requestedAt\": 1704067200000,\n * \"impact\": {\n * \"level\": \"high\",\n * \"affectedSystems\": [\"crm-api\", \"customer-portal\"],\n * \"affectedUsers\": 5000,\n * \"downtime\": {\n * \"required\": true,\n * \"durationMinutes\": 30\n * }\n * },\n * \"implementation\": {\n * \"description\": \"Execute database migration scripts\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Backup current database\",\n * \"estimatedMinutes\": 10\n * }\n * ],\n * \"testing\": \"Run integration test suite\"\n * },\n * \"rollbackPlan\": {\n * \"description\": \"Restore from backup\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Restore backup\",\n * \"estimatedMinutes\": 15\n * }\n * ]\n * },\n * \"schedule\": {\n * \"plannedStart\": 1704153600000,\n * \"plannedEnd\": 1704155400000\n * }\n * }\n * ```\n */\nexport const ChangeRequestSchema = z.object({\n /**\n * Unique change request identifier\n */\n id: z.string().describe('Change request ID'),\n\n /**\n * Short descriptive title of the change\n */\n title: z.string().describe('Change title'),\n\n /**\n * Detailed description of the change and its purpose\n */\n description: z.string().describe('Change description'),\n\n /**\n * Change classification type\n */\n type: ChangeTypeSchema.describe('Change type'),\n\n /**\n * Priority level for processing\n */\n priority: ChangePrioritySchema.describe('Change priority'),\n\n /**\n * Current status in the change lifecycle\n */\n status: ChangeStatusSchema.describe('Change status'),\n\n /**\n * User ID of the change requester\n */\n requestedBy: z.string().describe('Requester user ID'),\n\n /**\n * Timestamp when change was requested (Unix milliseconds)\n */\n requestedAt: z.number().describe('Request timestamp'),\n\n /**\n * Impact assessment of the change\n */\n impact: ChangeImpactSchema.describe('Impact assessment'),\n\n /**\n * Implementation plan and procedures\n */\n implementation: z.object({\n /**\n * High-level implementation description\n */\n description: z.string().describe('Implementation description'),\n\n /**\n * Sequential implementation steps\n */\n steps: z.array(z.object({\n /**\n * Step execution order\n */\n order: z.number().describe('Step order'),\n\n /**\n * Detailed description of this step\n */\n description: z.string().describe('Step description'),\n\n /**\n * Estimated time to complete this step\n */\n estimatedMinutes: z.number().describe('Estimated duration'),\n })).describe('Implementation steps'),\n\n /**\n * Testing procedures to verify successful implementation\n */\n testing: z.string().optional().describe('Testing procedure'),\n }).describe('Implementation plan'),\n\n /**\n * Rollback plan in case of failure\n */\n rollbackPlan: RollbackPlanSchema.describe('Rollback plan'),\n\n /**\n * Change schedule and timing\n */\n schedule: z.object({\n /**\n * Planned start time (Unix milliseconds)\n */\n plannedStart: z.number().describe('Planned start time'),\n\n /**\n * Planned end time (Unix milliseconds)\n */\n plannedEnd: z.number().describe('Planned end time'),\n\n /**\n * Actual start time (Unix milliseconds)\n */\n actualStart: z.number().optional().describe('Actual start time'),\n\n /**\n * Actual end time (Unix milliseconds)\n */\n actualEnd: z.number().optional().describe('Actual end time'),\n }).optional().describe('Schedule'),\n\n /**\n * Security impact assessment for the change (A.8.32)\n */\n securityImpact: z.object({\n /**\n * Whether a security impact assessment has been performed\n */\n assessed: z.boolean().describe('Whether security impact has been assessed'),\n\n /**\n * Security risk level of this change\n */\n riskLevel: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional()\n .describe('Security risk level'),\n\n /**\n * Data classifications affected by this change\n */\n affectedDataClassifications: z.array(DataClassificationSchema)\n .optional().describe('Affected data classifications'),\n\n /**\n * Whether the change requires security team approval\n */\n requiresSecurityApproval: z.boolean().default(false)\n .describe('Whether security team approval is required'),\n\n /**\n * Security reviewer user ID\n */\n reviewedBy: z.string().optional()\n .describe('Security reviewer user ID'),\n\n /**\n * Security review completion timestamp (Unix milliseconds)\n */\n reviewedAt: z.number().optional()\n .describe('Security review timestamp'),\n\n /**\n * Security review notes or conditions\n */\n reviewNotes: z.string().optional()\n .describe('Security review notes or conditions'),\n }).optional().describe('Security impact assessment per ISO 27001:2022 A.8.32'),\n\n /**\n * Approval workflow configuration\n */\n approval: z.object({\n /**\n * Whether approval is required for this change\n */\n required: z.boolean().describe('Approval required'),\n\n /**\n * List of approvers and their approval status\n */\n approvers: z.array(z.object({\n /**\n * Approver user ID\n */\n userId: z.string().describe('Approver user ID'),\n\n /**\n * Timestamp when approval was granted (Unix milliseconds)\n */\n approvedAt: z.number().optional().describe('Approval timestamp'),\n\n /**\n * Comments from the approver\n */\n comments: z.string().optional().describe('Approver comments'),\n })).describe('Approvers'),\n }).optional().describe('Approval workflow'),\n\n /**\n * Supporting documentation and files\n */\n attachments: z.array(z.object({\n /**\n * Attachment file name\n */\n name: z.string().describe('Attachment name'),\n\n /**\n * URL to download the attachment\n */\n url: z.string().url().describe('Attachment URL'),\n })).optional().describe('Attachments'),\n\n /**\n * Custom metadata key-value pairs for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n});\n\n// Type exports\nexport type ChangeRequest = z.infer;\nexport type ChangeType = z.infer;\nexport type ChangeStatus = z.infer;\nexport type ChangePriority = z.infer;\nexport type ChangeImpact = z.infer;\nexport type RollbackPlan = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # ObjectStack Validation Protocol\n * \n * This module defines the validation schema protocol for ObjectStack, providing a comprehensive\n * type-safe validation system similar to Salesforce's validation rules but with enhanced capabilities.\n * \n * ## Overview\n * \n * Validation rules are applied at the data layer to ensure data integrity and enforce business logic.\n * The system supports multiple validation types:\n * \n * 1. **Script Validation**: Formula-based validation using expressions\n * 2. **Uniqueness Validation**: Enforce unique constraints across fields\n * 3. **State Machine Validation**: Control allowed state transitions\n * 4. **Format Validation**: Validate field formats (email, URL, regex, etc.)\n * 5. **Cross-Field Validation**: Validate relationships between multiple fields\n * 6. **Async Validation**: Remote validation via API calls\n * 7. **Custom Validation**: User-defined validation functions\n * 8. **Conditional Validation**: Apply validations based on conditions\n * \n * ## Salesforce Comparison\n * \n * ObjectStack validation rules are inspired by Salesforce validation rules but enhanced:\n * - Salesforce: Formula-based validation with `Error Condition Formula`\n * - ObjectStack: Multiple validation types with composable rules\n * \n * Example Salesforce validation rule:\n * ```\n * Rule Name: Discount_Cannot_Exceed_40_Percent\n * Error Condition Formula: Discount_Percent__c > 0.40\n * Error Message: Discount cannot exceed 40%.\n * ```\n * \n * Equivalent ObjectStack rule:\n * ```typescript\n * {\n * type: 'script',\n * name: 'discount_cannot_exceed_40_percent',\n * condition: 'discount_percent > 0.40',\n * message: 'Discount cannot exceed 40%',\n * severity: 'error'\n * }\n * ```\n */\n\n/**\n * Base Validation Rule\n * \n * All validation rules extend from this base schema with common properties.\n * \n * ## Industry Standard Enhancements\n * - **Label/Description**: Essential for governance in large systems with thousands of rules.\n * - **Events**: granular control over validation timing (Context-aware validation).\n * - **Tags**: categorization for reporting and management.\n */\nconst BaseValidationSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label for the rule listing'),\n description: z.string().optional().describe('Administrative notes explaining the business reason'),\n \n // Execution Control\n active: z.boolean().default(true),\n events: z.array(z.enum(['insert', 'update', 'delete'])).default(['insert', 'update']).describe('Validation contexts'),\n priority: z.number().int().min(0).max(9999).default(100).describe('Execution priority (lower runs first, default: 100)'),\n \n // Classification\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g., \"compliance\", \"billing\")'),\n \n // Feedback\n severity: z.enum(['error', 'warning', 'info']).default('error'),\n message: z.string().describe('Error message to display to the user'),\n});\n\n/**\n * 1. Script/Expression Validation\n * Generic formula-based validation.\n */\nexport const ScriptValidationSchema = BaseValidationSchema.extend({\n type: z.literal('script'),\n condition: z.string().describe('Formula expression. If TRUE, validation fails. (e.g. amount < 0)'),\n});\n\n/**\n * 2. Uniqueness Validation\n * specialized optimized check for unique constraints.\n */\nexport const UniquenessValidationSchema = BaseValidationSchema.extend({\n type: z.literal('unique'),\n fields: z.array(z.string()).describe('Fields that must be combined unique'),\n scope: z.string().optional().describe('Formula condition for scope (e.g. active = true)'),\n caseSensitive: z.boolean().default(true),\n});\n\n/**\n * 3. State Machine Validation\n * State transition logic.\n */\nexport const StateMachineValidationSchema = BaseValidationSchema.extend({\n type: z.literal('state_machine'),\n field: z.string().describe('State field (e.g. status)'),\n transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'),\n});\n\n/**\n * 4. Value Format Validation\n * Regex or specialized formats.\n */\nexport const FormatValidationSchema = BaseValidationSchema.extend({\n type: z.literal('format'),\n field: z.string(),\n regex: z.string().optional(),\n format: z.enum(['email', 'url', 'phone', 'json']).optional(),\n});\n\n/**\n * 5. Cross-Field Validation\n * Validates relationships between multiple fields.\n * \n * ## Use Cases\n * - Date range validations (end_date > start_date)\n * - Amount comparisons (discount < total)\n * - Complex business rules involving multiple fields\n * \n * ## Salesforce Examples\n * \n * ### Example 1: Close Date Must Be In Current or Future Month\n * **Salesforce Formula:**\n * ```\n * MONTH(CloseDate) < MONTH(TODAY()) ||\n * YEAR(CloseDate) < YEAR(TODAY())\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'close_date_future',\n * condition: 'MONTH(close_date) >= MONTH(TODAY()) AND YEAR(close_date) >= YEAR(TODAY())',\n * fields: ['close_date'],\n * message: 'Close Date must be in the current or a future month'\n * }\n * ```\n * \n * ### Example 2: Discount Validation\n * **Salesforce Formula:**\n * ```\n * Discount__c > (Amount__c * 0.40)\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'discount_limit',\n * condition: 'discount > (amount * 0.40)',\n * fields: ['discount', 'amount'],\n * message: 'Discount cannot exceed 40% of the amount'\n * }\n * ```\n * \n * ### Example 3: Opportunity Must Have Products\n * **Salesforce Formula:**\n * ```\n * ISBLANK(Products__c) && ISPICKVAL(StageName, \"Closed Won\")\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'products_required_for_won',\n * condition: 'products = null AND stage = \"closed_won\"',\n * fields: ['products', 'stage'],\n * message: 'Opportunity must have products to be marked as Closed Won'\n * }\n * ```\n */\nexport const CrossFieldValidationSchema = BaseValidationSchema.extend({\n type: z.literal('cross_field'),\n condition: z.string().describe('Formula expression comparing fields (e.g. \"end_date > start_date\")'),\n fields: z.array(z.string()).describe('Fields involved in the validation'),\n});\n\n/**\n * 6. JSON Structure Validation\n * Validates JSON fields against a JSON Schema.\n * \n * ## Use Cases\n * - Validating configuration objects stored in JSON fields\n * - Enforcing API payload structures\n * - Complex nested data validation\n */\nexport const JSONValidationSchema = BaseValidationSchema.extend({\n type: z.literal('json_schema'),\n field: z.string().describe('JSON field to validate'),\n schema: z.record(z.string(), z.unknown()).describe('JSON Schema object definition'),\n});\n\n/**\n * 7. Async Validation\n * Remote validation via API call or database query.\n * \n * ## Use Cases\n * \n * ### 1. Email Uniqueness Check\n * Check if an email address is already registered in the system.\n * ```typescript\n * {\n * type: 'async',\n * name: 'unique_email',\n * field: 'email',\n * validatorUrl: '/api/users/check-email',\n * message: 'This email address is already registered',\n * debounce: 500, // Wait 500ms after user stops typing\n * timeout: 3000\n * }\n * ```\n * \n * ### 2. Username Availability\n * Verify username is available before form submission.\n * ```typescript\n * {\n * type: 'async',\n * name: 'username_available',\n * field: 'username',\n * validatorUrl: '/api/users/check-username',\n * message: 'This username is already taken',\n * debounce: 300,\n * timeout: 2000\n * }\n * ```\n * \n * ### 3. Tax ID Validation\n * Validate tax ID with government API (e.g., IRS, HMRC).\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_tax_id',\n * field: 'tax_id',\n * validatorFunction: 'validateTaxIdWithIRS',\n * message: 'Invalid Tax ID number',\n * timeout: 10000, // Government APIs may be slow\n * params: { country: 'US', format: 'EIN' }\n * }\n * ```\n * \n * ### 4. Credit Card Validation\n * Verify credit card with payment gateway without charging.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_card',\n * field: 'card_number',\n * validatorUrl: 'https://api.stripe.com/v1/tokens/validate',\n * message: 'Invalid credit card number',\n * timeout: 5000,\n * params: { \n * mode: 'validate_only',\n * checkFunds: false \n * }\n * }\n * ```\n * \n * ### 5. Address Validation\n * Validate and standardize addresses using geocoding services.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_address',\n * field: 'street_address',\n * validatorFunction: 'validateAddressWithGoogleMaps',\n * message: 'Unable to verify address',\n * timeout: 4000,\n * params: {\n * includeFields: ['city', 'state', 'zip'],\n * strictMode: true,\n * country: 'US'\n * }\n * }\n * ```\n * \n * ### 6. Domain Name Availability\n * Check if domain name is available for registration.\n * ```typescript\n * {\n * type: 'async',\n * name: 'domain_available',\n * field: 'domain_name',\n * validatorUrl: '/api/domains/check-availability',\n * message: 'This domain is already taken or reserved',\n * debounce: 500,\n * timeout: 2000\n * }\n * ```\n * \n * ### 7. Coupon Code Validation\n * Verify coupon code is valid and not expired.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_coupon',\n * field: 'coupon_code',\n * validatorUrl: '/api/coupons/validate',\n * message: 'Invalid or expired coupon code',\n * timeout: 2000,\n * params: {\n * checkExpiration: true,\n * checkUsageLimit: true,\n * userId: '{{current_user_id}}'\n * }\n * }\n * ```\n */\nexport const AsyncValidationSchema = BaseValidationSchema.extend({\n type: z.literal('async'),\n field: z.string().describe('Field to validate'),\n validatorUrl: z.string().optional().describe('External API endpoint for validation'),\n method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method for external call'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for the request'),\n validatorFunction: z.string().optional().describe('Reference to custom validator function'),\n timeout: z.number().optional().default(5000).describe('Timeout in milliseconds'),\n debounce: z.number().optional().describe('Debounce delay in milliseconds'),\n params: z.record(z.string(), z.unknown()).optional().describe('Additional parameters to pass to validator'),\n});\n\n/**\n * 8. Custom Validator Function\n * User-defined validation logic with code reference.\n */\nexport const CustomValidatorSchema = BaseValidationSchema.extend({\n type: z.literal('custom'),\n handler: z.string().describe('Name of the custom validation function registered in the system'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the custom handler'),\n});\n\n/**\n * 9. Master Validation Rule Schema\n */\n/** Base type for validation rules - used for z.lazy() recursive type annotation */\nexport interface BaseValidationRuleShape {\n type: string;\n name: string;\n message: string;\n label?: string;\n description?: string;\n active?: boolean;\n events?: ('insert' | 'update' | 'delete')[];\n priority?: number;\n tags?: string[];\n severity?: 'error' | 'warning' | 'info';\n [key: string]: unknown;\n}\n\nexport const ValidationRuleSchema: z.ZodType = z.lazy(() =>\n z.discriminatedUnion('type', [\n ScriptValidationSchema,\n UniquenessValidationSchema,\n StateMachineValidationSchema,\n FormatValidationSchema,\n CrossFieldValidationSchema,\n JSONValidationSchema,\n AsyncValidationSchema,\n CustomValidatorSchema,\n ConditionalValidationSchema,\n ])\n);\n\n/**\n * 8. Conditional Validation\n * Validation that only applies when a condition is met.\n * \n * ## Overview\n * Conditional validations follow the pattern: \"Validate X only if Y is true\"\n * This allows for context-aware validation rules that adapt to different scenarios.\n * \n * ## Use Cases\n * \n * ### 1. Validate Based on Record Type\n * Apply different validation rules based on the type of record.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_approval_required',\n * when: 'account_type = \"enterprise\"',\n * message: 'Enterprise validation',\n * then: {\n * type: 'script',\n * name: 'require_approval',\n * message: 'Enterprise accounts require manager approval',\n * condition: 'approval_status = null'\n * }\n * }\n * ```\n * \n * ### 2. Conditional Field Requirements\n * Require certain fields only when specific conditions are met.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'shipping_address_when_required',\n * when: 'requires_shipping = true',\n * message: 'Shipping validation',\n * then: {\n * type: 'script',\n * name: 'shipping_address_required',\n * message: 'Shipping address is required for physical products',\n * condition: 'shipping_address = null OR shipping_address = \"\"'\n * }\n * }\n * ```\n * \n * ### 3. Amount-Based Validation\n * Apply different rules based on transaction amount.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'high_value_approval',\n * when: 'order_total > 10000',\n * message: 'High value order validation',\n * then: {\n * type: 'script',\n * name: 'manager_approval_required',\n * message: 'Orders over $10,000 require manager approval',\n * condition: 'manager_approval_id = null'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'standard_validation',\n * message: 'Payment method is required',\n * condition: 'payment_method = null'\n * }\n * }\n * ```\n * \n * ### 4. Regional Compliance\n * Apply region-specific validation rules.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'regional_compliance',\n * when: 'region = \"EU\"',\n * message: 'EU compliance validation',\n * then: {\n * type: 'script',\n * name: 'gdpr_consent',\n * message: 'GDPR consent is required for EU customers',\n * condition: 'gdpr_consent_given = false'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'tos_acceptance',\n * message: 'Terms of Service acceptance required',\n * condition: 'tos_accepted = false'\n * }\n * }\n * ```\n * \n * ### 5. Nested Conditional Validation\n * Create complex validation logic with nested conditions.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'country_state_validation',\n * when: 'country = \"US\"',\n * message: 'US-specific validation',\n * then: {\n * type: 'conditional',\n * name: 'california_validation',\n * when: 'state = \"CA\"',\n * message: 'California-specific validation',\n * then: {\n * type: 'script',\n * name: 'ca_tax_id_required',\n * message: 'California requires a valid tax ID',\n * condition: 'tax_id = null OR NOT(REGEX(tax_id, \"^\\\\d{2}-\\\\d{7}$\"))'\n * }\n * }\n * }\n * ```\n * \n * ### 6. Tax Validation for Taxable Items\n * Only validate tax fields when the item is taxable.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'tax_field_validation',\n * when: 'is_taxable = true',\n * message: 'Tax validation',\n * then: {\n * type: 'script',\n * name: 'tax_code_required',\n * message: 'Tax code is required for taxable items',\n * condition: 'tax_code = null OR tax_code = \"\"'\n * }\n * }\n * ```\n * \n * ### 7. Role-Based Validation\n * Apply validation based on user role.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'role_based_approval_limit',\n * when: 'user_role = \"manager\"',\n * message: 'Manager approval limits',\n * then: {\n * type: 'script',\n * name: 'manager_limit',\n * message: 'Managers can approve up to $50,000',\n * condition: 'approval_amount > 50000'\n * }\n * }\n * ```\n * \n * ## Salesforce Pattern Comparison\n * \n * Salesforce doesn't have explicit \"conditional validation\" rules but achieves similar\n * behavior using formula logic. ObjectStack makes this pattern explicit and composable.\n * \n * **Salesforce Approach:**\n * ```\n * IF(\n * ISPICKVAL(Type, \"Enterprise\"),\n * AND(Amount > 100000, ISBLANK(Approval__c)),\n * FALSE\n * )\n * ```\n * \n * **ObjectStack Approach:**\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_high_value',\n * when: 'type = \"enterprise\"',\n * then: {\n * type: 'cross_field',\n * name: 'amount_approval',\n * condition: 'amount > 100000 AND approval = null',\n * fields: ['amount', 'approval']\n * }\n * }\n * ```\n */\nexport const ConditionalValidationSchema = BaseValidationSchema.extend({\n type: z.literal('conditional'),\n when: z.string().describe('Condition formula (e.g. \"type = \\'enterprise\\'\")'),\n then: ValidationRuleSchema.describe('Validation rule to apply when condition is true'),\n otherwise: ValidationRuleSchema.optional().describe('Validation rule to apply when condition is false'),\n});\n\nexport type ValidationRule = z.infer;\nexport type ScriptValidation = z.infer;\nexport type UniquenessValidation = z.infer;\nexport type StateMachineValidation = z.infer;\nexport type FormatValidation = z.infer;\nexport type CrossFieldValidation = z.infer;\nexport type JSONValidation = z.infer;\nexport type AsyncValidation = z.infer;\nexport type CustomValidation = z.infer;\nexport type ConditionalValidation = z.infer;", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * XState-inspired State Machine Protocol\n * Used to define strict business logic constraints and lifecycle management.\n * Prevent AI \"hallucinations\" by enforcing valid valid transitions.\n */\n\n// --- Primitives ---\n\n/**\n * References a named action (side effect)\n * Can be a script, a webhook, or a field update.\n */\nexport const ActionRefSchema = z.union([\n z.string().describe('Action Name'),\n z.object({\n type: z.string(), // e.g., 'xstate.assign', 'log', 'email'\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n/**\n * References a named condition (guard)\n * Must evaluate to true for the transition to occur.\n */\nexport const GuardRefSchema = z.union([\n z.string().describe('Guard Name (e.g., \"isManager\", \"amountGT1000\")'),\n z.object({\n type: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n// --- Core Structure ---\n\n/**\n * State Transition Definition\n * \"When EVENT happens, if GUARD is true, go to TARGET and run ACTIONS\"\n */\nexport const TransitionSchema = z.object({\n target: z.string().optional().describe('Target State ID'),\n cond: GuardRefSchema.optional().describe('Condition (Guard) required to take this path'),\n actions: z.array(ActionRefSchema).optional().describe('Actions to execute during transition'),\n description: z.string().optional().describe('Human readable description of this rule'),\n});\n\n/**\n * Event Definition (Signals)\n */\nexport const EventSchema = z.object({\n type: z.string().describe('Event Type (e.g. \"APPROVE\", \"REJECT\", \"Submit\")'),\n // Payload validation schema could go here if we want deep validation\n schema: z.record(z.string(), z.unknown()).optional().describe('Expected event payload structure'),\n});\n\nexport type ActionRef = z.infer;\nexport type Transition = z.infer;\n\nexport type StateNodeConfig = {\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n entry?: ActionRef[];\n exit?: ActionRef[];\n on?: Record;\n always?: Transition[];\n initial?: string;\n states?: Record;\n meta?: {\n label?: string;\n description?: string;\n color?: string;\n aiInstructions?: string;\n };\n};\n\n/**\n * State Node Definition\n */\nexport const StateNodeSchema: z.ZodType = z.lazy(() => z.object({\n /** Type of state */\n type: z.enum(['atomic', 'compound', 'parallel', 'final', 'history']).default('atomic'),\n \n /** Entry/Exit Actions */\n entry: z.array(ActionRefSchema).optional().describe('Actions to run when entering this state'),\n exit: z.array(ActionRefSchema).optional().describe('Actions to run when leaving this state'),\n \n /** Transitions (Events) */\n on: z.record(z.string(), z.union([\n z.string(), // Shorthand target\n TransitionSchema, \n z.array(TransitionSchema)\n ])).optional().describe('Map of Event Type -> Transition Definition'),\n \n /** Always Transitions (Eventless) */\n always: z.array(TransitionSchema).optional(),\n\n /** Nesting (Hierarchical States) */\n initial: z.string().optional().describe('Initial child state (if compound)'),\n states: z.record(z.string(), StateNodeSchema).optional(),\n \n /** Metadata for UI/AI */\n meta: z.object({\n label: z.string().optional(),\n description: z.string().optional(),\n color: z.string().optional(), // For UI diagrams\n // Instructions for AI Agent when in this state\n aiInstructions: z.string().optional().describe('Specific instructions for AI when in this state'),\n }).optional(),\n}));\n\n/**\n * Top-Level State Machine Definition\n */\nexport const StateMachineSchema = z.object({\n id: SnakeCaseIdentifierSchema.describe('Unique Machine ID'),\n description: z.string().optional(),\n \n /** Context (Memory) Schema */\n contextSchema: z.record(z.string(), z.unknown()).optional().describe('Zod Schema for the machine context/memory'),\n \n /** Initial State */\n initial: z.string().describe('Initial State ID'),\n \n /** State Definitions */\n states: z.record(z.string(), StateNodeSchema).describe('State Nodes'),\n \n /** Global Listeners */\n on: z.record(z.string(), z.union([z.string(), TransitionSchema, z.array(TransitionSchema)])).optional(),\n});\n\nexport type StateMachineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from './field.zod';\nimport { ValidationRuleSchema } from './validation.zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\nimport { ActionSchema } from '../ui/action.zod';\n\n/**\n * API Operations Enum\n */\nexport const ApiMethod = z.enum([\n 'get', 'list', // Read\n 'create', 'update', 'delete', // Write\n 'upsert', // Idempotent Write\n 'bulk', // Batch operations\n 'aggregate', // Analytics (count, sum)\n 'history', // Audit access\n 'search', // Search access\n 'restore', 'purge', // Trash management\n 'import', 'export', // Data portability\n]);\nexport type ApiMethod = z.infer;\n\n/**\n * Capability Flags\n * Defines what system features are enabled for this object.\n * \n * Optimized based on industry standards (Salesforce, ServiceNow):\n * - Added `activities` (Tasks/Events)\n * - Added `mru` (Recent Items)\n * - Added `feeds` (Social/Chatter)\n * - Grouped API permissions\n * \n * @example\n * {\n * trackHistory: true,\n * searchable: true,\n * apiEnabled: true,\n * files: true\n * }\n */\nexport const ObjectCapabilities = z.object({\n /** Enable history tracking (Audit Trail) */\n trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),\n \n /** Enable global search indexing */\n searchable: z.boolean().default(true).describe('Index records for global search'),\n \n /** Enable REST/GraphQL API access */\n apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),\n\n /** \n * API Supported Operations\n * Granular control over API exposure.\n */\n apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),\n \n /** Enable standard attachments/files engine */\n files: z.boolean().default(false).describe('Enable file attachments and document management'),\n \n /** Enable social collaboration (Comments, Mentions, Feeds) */\n feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),\n \n /** Enable standard Activity suite (Tasks, Calendars, Events) */\n activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),\n \n /** Enable Recycle Bin / Soft Delete */\n trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),\n\n /** Enable \"Recently Viewed\" tracking */\n mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),\n \n /** Allow cloning records */\n clone: z.boolean().default(true).describe('Allow record deep cloning'),\n});\n\n/**\n * Schema for database indexes.\n * Enhanced with additional index types and configuration options\n * \n * @example\n * {\n * name: \"idx_account_name\",\n * fields: [\"name\"],\n * type: \"btree\",\n * unique: true\n * }\n */\nexport const IndexSchema = z.object({\n name: z.string().optional().describe('Index name (auto-generated if not provided)'),\n fields: z.array(z.string()).describe('Fields included in the index'),\n type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),\n unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),\n partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),\n});\n\n/**\n * Search Configuration\n * Defines how this object behaves in search results.\n * \n * @example\n * {\n * fields: [\"name\", \"email\", \"phone\"],\n * displayFields: [\"name\", \"title\"],\n * filters: [\"status = 'active'\"]\n * }\n */\nexport const SearchConfigSchema = z.object({\n fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),\n displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),\n filters: z.array(z.string()).optional().describe('Default filters for search results'),\n});\n\n/**\n * Multi-Tenancy Configuration Schema\n * Configures tenant isolation strategy for SaaS applications\n * \n * @example Shared database with tenant_id isolation\n * {\n * enabled: true,\n * strategy: 'shared',\n * tenantField: 'tenant_id',\n * crossTenantAccess: false\n * }\n */\nexport const TenancyConfigSchema = z.object({\n enabled: z.boolean().describe('Enable multi-tenancy for this object'),\n strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),\n tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),\n crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),\n});\n\n/**\n * Soft Delete Configuration Schema\n * Implements recycle bin / trash functionality\n * \n * @example Standard soft delete with cascade\n * {\n * enabled: true,\n * field: 'deleted_at',\n * cascadeDelete: true\n * }\n */\nexport const SoftDeleteConfigSchema = z.object({\n enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),\n field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),\n cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),\n});\n\n/**\n * Versioning Configuration Schema\n * Implements record versioning and history tracking\n * \n * @example Snapshot versioning with 90-day retention\n * {\n * enabled: true,\n * strategy: 'snapshot',\n * retentionDays: 90,\n * versionField: 'version'\n * }\n */\nexport const VersioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable record versioning'),\n strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),\n retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),\n versionField: z.string().default('version').describe('Field name for version number/timestamp'),\n});\n\n/**\n * Partitioning Strategy Schema\n * Configures table partitioning for performance at scale\n * \n * @example Range partitioning by date (monthly)\n * {\n * enabled: true,\n * strategy: 'range',\n * key: 'created_at',\n * interval: '1 month'\n * }\n */\nexport const PartitioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable table partitioning'),\n strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),\n key: z.string().describe('Field name to partition by'),\n interval: z.string().optional().describe('Partition interval for range strategy (e.g., \"1 month\", \"1 year\")'),\n}).refine((data) => {\n // If strategy is 'range', interval must be provided\n if (data.strategy === 'range' && !data.interval) {\n return false;\n }\n return true;\n}, {\n message: 'interval is required when strategy is \"range\"',\n});\n\n/**\n * Change Data Capture (CDC) Configuration Schema\n * Enables real-time data streaming to external systems\n * \n * @example Stream all changes to Kafka\n * {\n * enabled: true,\n * events: ['insert', 'update', 'delete'],\n * destination: 'kafka://events.objectstack'\n * }\n */\nexport const CDCConfigSchema = z.object({\n enabled: z.boolean().describe('Enable Change Data Capture'),\n events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),\n destination: z.string().describe('Destination endpoint (e.g., \"kafka://topic\", \"webhook://url\")'),\n});\n\n/**\n * Base Object Schema Definition\n * \n * The Blueprint of a Business Object.\n * Represents a table, a collection, or a virtual entity.\n * \n * @example\n * ```yaml\n * name: project_task\n * label: Project Task\n * icon: task\n * fields:\n * project:\n * type: lookup\n * reference: project\n * status:\n * type: select\n * options: [todo, in_progress, done]\n * enable:\n * trackHistory: true\n * files: true\n * ```\n */\nconst ObjectSchemaBase = z.object({\n /** \n * Identity & Metadata \n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),\n label: z.string().optional().describe('Human readable singular label (e.g. \"Account\")'),\n pluralLabel: z.string().optional().describe('Human readable plural label (e.g. \"Accounts\")'),\n description: z.string().optional().describe('Developer documentation / description'),\n icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),\n \n /**\n * Namespace & Domain Classification\n * \n * Groups objects into logical domains for routing, permissions, and discovery.\n * System objects use `'sys'`; business packages use their own namespace.\n * \n * When set, `tableName` is auto-derived as `{namespace}_{name}` by\n * `ObjectSchema.create()` unless an explicit `tableName` is provided.\n * \n * Namespace must be a single lowercase word (no underscores or hyphens)\n * to ensure clean auto-derivation of `{namespace}_{name}` table names.\n * \n * @example namespace: 'sys' → tableName defaults to 'sys_user'\n * @example namespace: 'crm' → tableName defaults to 'crm_account'\n */\n namespace: z.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace — single lowercase word (e.g. \"sys\", \"crm\"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'),\n\n /**\n * Taxonomy & Organization\n */\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g. \"sales\", \"system\", \"reference\")'),\n active: z.boolean().optional().default(true).describe('Is the object active and usable'),\n isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),\n abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),\n\n /** \n * Storage & Virtualization \n */\n datasource: z.string().optional().default('default').describe('Target Datasource ID. \"default\" is the primary DB.'),\n tableName: z.string().optional().describe('Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set.'),\n \n /** \n * Data Model \n */\n fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {\n message: 'Field names must be lowercase snake_case (e.g., \"first_name\", \"company\", \"annual_revenue\")',\n }), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),\n indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),\n \n /**\n * Advanced Data Management\n */\n \n // Multi-tenancy configuration\n tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),\n \n // Soft delete configuration\n softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),\n \n // Versioning configuration\n versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),\n \n // Partitioning strategy\n partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),\n \n // Change Data Capture\n cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),\n \n /**\n * Logic & Validation (Co-located)\n * Best Practice: Define rules close to data.\n */\n validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),\n \n /**\n * State Machine(s)\n * Named record of state machines, where each key is a unique machine identifier.\n * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).\n * \n * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }\n */\n stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),\n\n /** \n * Display & UI Hints (Data-Layer)\n */\n displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., \"name\", \"title\"). Defaults to \"name\" if present.'),\n recordName: z.object({\n type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),\n displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., \"CASE-{0000}\", \"INV-{YYYY}-{0000}\")'),\n startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),\n }).optional().describe('Record name generation configuration (Salesforce pattern)'),\n titleFormat: z.string().optional().describe('Title expression (e.g. \"{name} - {code}\"). Overrides displayNameField.'),\n compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),\n \n /** \n * Search Engine Config \n */\n search: SearchConfigSchema.optional().describe('Search engine configuration'),\n \n /** \n * System Capabilities \n */\n enable: ObjectCapabilities.optional().describe('Enabled system features modules'),\n\n /** Record Types */\n recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),\n\n /** Sharing Model */\n sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),\n\n /** Key Prefix */\n keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., \"001\" for Account)'),\n\n /**\n * Object Actions\n * \n * Actions associated with this object. Populated automatically by `defineStack()`\n * when top-level actions specify `objectName` matching this object.\n * Can also be defined directly on the object.\n * \n * Aligns with Salesforce/ServiceNow patterns where actions are part of the\n * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)\n * include the action list without requiring downstream merge.\n */\n actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),\n});\n\n/**\n * Converts a snake_case name to a human-readable Title Case label.\n * @example snakeCaseToLabel('project_task') → 'Project Task'\n */\nfunction snakeCaseToLabel(name: string): string {\n return name\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n}\n\n/**\n * Enhanced ObjectSchema with Factory\n */\nexport const ObjectSchema = Object.assign(ObjectSchemaBase, {\n /**\n * Type-safe factory for creating business object definitions.\n * \n * Enhancements over raw schema:\n * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).\n * - **Validation**: Runs Zod `.parse()` to validate the config at creation time.\n * \n * @example\n * ```ts\n * const Task = ObjectSchema.create({\n * name: 'project_task',\n * // label auto-generated as 'Project Task'\n * fields: {\n * subject: { type: 'text', label: 'Subject', required: true },\n * },\n * });\n * ```\n */\n create: >(config: T): Omit & Pick => {\n const withDefaults = {\n ...config,\n label: config.label ?? snakeCaseToLabel(config.name),\n // Auto-derive tableName as {namespace}_{name} when namespace is set\n tableName: config.tableName ?? (config.namespace ? `${config.namespace}_${config.name}` : undefined),\n };\n return ObjectSchemaBase.parse(withDefaults) as Omit & Pick;\n },\n});\n\nexport type ServiceObject = z.infer;\nexport type ServiceObjectInput = z.input;\nexport type ObjectCapabilities = z.infer;\nexport type ObjectIndex = z.infer;\nexport type TenancyConfig = z.infer;\nexport type SoftDeleteConfig = z.infer;\nexport type VersioningConfig = z.infer;\nexport type PartitioningConfig = z.infer;\nexport type CDCConfig = z.infer;\n\n// =================================================================\n// Object Ownership Model\n// =================================================================\n\n/**\n * How a package relates to an object it references.\n * \n * - `own`: This package is the original author/owner of the object.\n * Only one package may own a given object name. The owner defines\n * the base schema (table name, primary key, core fields).\n * \n * - `extend`: This package adds fields, views, or actions to an\n * existing object owned by another package. Multiple packages\n * may extend the same object. Extensions are merged at boot time.\n * \n * Follows Salesforce/ServiceNow patterns:\n * object name = database table name, globally unique, no namespace prefix.\n */\nexport const ObjectOwnershipEnum = z.enum(['own', 'extend']);\nexport type ObjectOwnership = z.infer;\n\n/**\n * Object Extension Entry — used in `objectExtensions` array.\n * Declares fields/config to merge into an existing object owned by another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact', // target object FQN\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\nexport const ObjectExtensionSchema = z.object({\n /** The target object name (FQN) to extend */\n extend: z.string().describe('Target object name (FQN) to extend'),\n \n /** Fields to merge into the target object (additive) */\n fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),\n \n /** Override label */\n label: z.string().optional().describe('Override label for the extended object'),\n \n /** Override plural label */\n pluralLabel: z.string().optional().describe('Override plural label for the extended object'),\n \n /** Override description */\n description: z.string().optional().describe('Override description for the extended object'),\n \n /** Additional validation rules to add */\n validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),\n \n /** Additional indexes to add */\n indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),\n \n /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */\n priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),\n});\n\nexport type ObjectExtension = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from '../data/field.zod';\nimport { ObjectSchema } from '../data/object.zod';\n\n// --- Atomic Operations ---\n\nexport const AddFieldOperation = z.object({\n type: z.literal('add_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to add'),\n field: FieldSchema.describe('Full field definition to add')\n}).describe('Add a new field to an existing object');\n\nexport const ModifyFieldOperation = z.object({\n type: z.literal('modify_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to modify'),\n changes: z.record(z.string(), z.unknown()).describe('Partial field definition updates')\n}).describe('Modify properties of an existing field');\n\nexport const RemoveFieldOperation = z.object({\n type: z.literal('remove_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to remove')\n}).describe('Remove a field from an existing object');\n\nexport const CreateObjectOperation = z.object({\n type: z.literal('create_object'),\n object: ObjectSchema.describe('Full object definition to create')\n}).describe('Create a new object');\n\nexport const RenameObjectOperation = z.object({\n type: z.literal('rename_object'),\n oldName: z.string().describe('Current object name'),\n newName: z.string().describe('New object name')\n}).describe('Rename an existing object');\n\nexport const DeleteObjectOperation = z.object({\n type: z.literal('delete_object'),\n objectName: z.string().describe('Name of the object to delete')\n}).describe('Delete an existing object');\n\nexport const ExecuteSqlOperation = z.object({\n type: z.literal('execute_sql'),\n sql: z.string().describe('Raw SQL statement to execute'),\n description: z.string().optional().describe('Human-readable description of the SQL')\n}).describe('Execute a raw SQL statement');\n\n// Union of all possible operations\nexport const MigrationOperationSchema = z.discriminatedUnion('type', [\n AddFieldOperation,\n ModifyFieldOperation,\n RemoveFieldOperation,\n CreateObjectOperation,\n RenameObjectOperation,\n DeleteObjectOperation,\n ExecuteSqlOperation\n]);\n\n// --- Migration & ChangeSet ---\n\nexport const MigrationDependencySchema = z.object({\n migrationId: z.string().describe('ID of the migration this depends on'),\n package: z.string().optional().describe('Package that owns the dependency migration')\n}).describe('Dependency reference to another migration that must run first');\n\nexport const ChangeSetSchema = z.object({\n id: z.string().uuid().describe('Unique identifier for this change set'),\n name: z.string().describe('Human readable name for the migration'),\n description: z.string().optional().describe('Detailed description of what this migration does'),\n author: z.string().optional().describe('Author who created this migration'),\n createdAt: z.string().datetime().optional().describe('ISO 8601 timestamp when the migration was created'),\n \n // Dependencies ensure migrations run in order\n dependencies: z.array(MigrationDependencySchema).optional().describe('Migrations that must run before this one'),\n \n // The actual atomic operations\n operations: z.array(MigrationOperationSchema).describe('Ordered list of atomic migration operations'),\n \n // Rollback operations (AI should generate these too)\n rollback: z.array(MigrationOperationSchema).optional().describe('Operations to reverse this migration')\n}).describe('A versioned set of atomic schema migration operations');\n\nexport type ChangeSet = z.infer;\nexport type MigrationOperation = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Better-Auth Configuration Protocol\n * \n * Defines the configuration required to initialize the Better-Auth kernel.\n * Used in server-side configuration injection.\n */\n\nexport const AuthProviderConfigSchema = z.object({\n id: z.string().describe('Provider ID (github, google)'),\n clientId: z.string().describe('OAuth Client ID'),\n clientSecret: z.string().describe('OAuth Client Secret'),\n scope: z.array(z.string()).optional().describe('Requested permissions'),\n});\n\nexport const AuthPluginConfigSchema = z.object({\n organization: z.boolean().default(false).describe('Enable Organization/Teams support'),\n twoFactor: z.boolean().default(false).describe('Enable 2FA'),\n passkeys: z.boolean().default(false).describe('Enable Passkey support'),\n magicLink: z.boolean().default(false).describe('Enable Magic Link login'),\n});\n\n/**\n * Mutual TLS (mTLS) Configuration Schema\n * \n * Enables client certificate authentication for zero-trust architectures.\n */\nexport const MutualTLSConfigSchema = z.object({\n /** Enable mutual TLS authentication */\n enabled: z.boolean()\n .default(false)\n .describe('Enable mutual TLS authentication'),\n\n /** Require client certificates for all connections */\n clientCertRequired: z.boolean()\n .default(false)\n .describe('Require client certificates for all connections'),\n\n /** PEM-encoded CA certificates or file paths for trust validation */\n trustedCAs: z.array(z.string())\n .describe('PEM-encoded CA certificates or file paths'),\n\n /** Certificate Revocation List URL */\n crlUrl: z.string()\n .optional()\n .describe('Certificate Revocation List (CRL) URL'),\n\n /** Online Certificate Status Protocol URL */\n ocspUrl: z.string()\n .optional()\n .describe('Online Certificate Status Protocol (OCSP) URL'),\n\n /** Certificate validation strictness level */\n certificateValidation: z.enum(['strict', 'relaxed', 'none'])\n .describe('Certificate validation strictness level'),\n\n /** Allowed Common Names on client certificates */\n allowedCNs: z.array(z.string())\n .optional()\n .describe('Allowed Common Names (CN) on client certificates'),\n\n /** Allowed Organizational Units on client certificates */\n allowedOUs: z.array(z.string())\n .optional()\n .describe('Allowed Organizational Units (OU) on client certificates'),\n\n /** Certificate pinning configuration */\n pinning: z.object({\n /** Enable certificate pinning */\n enabled: z.boolean().describe('Enable certificate pinning'),\n /** Array of pinned certificate hashes */\n pins: z.array(z.string()).describe('Pinned certificate hashes'),\n })\n .optional()\n .describe('Certificate pinning configuration'),\n});\n\nexport type MutualTLSConfig = z.infer;\n\n/**\n * Social / OAuth Provider Configuration\n *\n * Maps provider id → { clientId, clientSecret, ... }.\n * Keys must match Better-Auth built-in provider names (google, github, etc.).\n */\nexport const SocialProviderConfigSchema = z.record(\n z.string(),\n z.object({\n clientId: z.string().describe('OAuth Client ID'),\n clientSecret: z.string().describe('OAuth Client Secret'),\n enabled: z.boolean().optional().default(true).describe('Enable this provider'),\n scope: z.array(z.string()).optional().describe('Additional OAuth scopes'),\n }).catchall(z.unknown()),\n).optional().describe(\n 'Social/OAuth provider map forwarded to better-auth socialProviders. ' +\n 'Keys are provider ids (google, github, apple, …).'\n);\n\n/**\n * Email + Password Configuration\n */\nexport const EmailAndPasswordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable email/password auth'),\n disableSignUp: z.boolean().optional().describe('Disable new user registration via email/password'),\n requireEmailVerification: z.boolean().optional().describe(\n 'Require email verification before creating a session'\n ),\n minPasswordLength: z.number().optional().describe('Minimum password length (default 8)'),\n maxPasswordLength: z.number().optional().describe('Maximum password length (default 128)'),\n resetPasswordTokenExpiresIn: z.number().optional().describe(\n 'Reset-password token TTL in seconds (default 3600)'\n ),\n autoSignIn: z.boolean().optional().describe('Auto sign-in after sign-up (default true)'),\n revokeSessionsOnPasswordReset: z.boolean().optional().describe(\n 'Revoke all other sessions on password reset'\n ),\n}).optional().describe('Email and password authentication options forwarded to better-auth');\n\n/**\n * Email Verification Configuration\n */\nexport const EmailVerificationConfigSchema = z.object({\n sendOnSignUp: z.boolean().optional().describe(\n 'Automatically send verification email after sign-up'\n ),\n sendOnSignIn: z.boolean().optional().describe(\n 'Send verification email on sign-in when not yet verified'\n ),\n autoSignInAfterVerification: z.boolean().optional().describe(\n 'Auto sign-in the user after email verification'\n ),\n expiresIn: z.number().optional().describe(\n 'Verification token TTL in seconds (default 3600)'\n ),\n}).optional().describe('Email verification options forwarded to better-auth');\n\n/**\n * Advanced / Low-level Better-Auth Options\n */\nexport const AdvancedAuthConfigSchema = z.object({\n crossSubDomainCookies: z.object({\n enabled: z.boolean().describe('Enable cross-subdomain cookies'),\n additionalCookies: z.array(z.string()).optional().describe('Extra cookies shared across subdomains'),\n domain: z.string().optional().describe(\n 'Cookie domain override — defaults to root domain derived from baseUrl'\n ),\n }).optional().describe(\n 'Share auth cookies across subdomains (critical for *.example.com multi-tenant)'\n ),\n useSecureCookies: z.boolean().optional().describe('Force Secure flag on cookies'),\n disableCSRFCheck: z.boolean().optional().describe(\n '⚠ Disable CSRF check — security risk, use with caution'\n ),\n cookiePrefix: z.string().optional().describe('Prefix for auth cookie names'),\n}).optional().describe('Advanced / low-level Better-Auth options');\n\nexport const AuthConfigSchema = z.object({\n secret: z.string().optional().describe('Encryption secret'),\n baseUrl: z.string().optional().describe('Base URL for auth routes'),\n databaseUrl: z.string().optional().describe('Database connection string'),\n providers: z.array(AuthProviderConfigSchema).optional(),\n plugins: AuthPluginConfigSchema.optional(),\n session: z.object({\n expiresIn: z.number().default(60 * 60 * 24 * 7).describe('Session duration in seconds'),\n updateAge: z.number().default(60 * 60 * 24).describe('Session update frequency'),\n }).optional(),\n trustedOrigins: z.array(z.string()).optional().describe(\n 'Trusted origins for CSRF protection. Supports wildcards (e.g. \"https://*.example.com\"). ' +\n 'The baseUrl origin is always trusted implicitly.'\n ),\n socialProviders: SocialProviderConfigSchema,\n emailAndPassword: EmailAndPasswordConfigSchema,\n emailVerification: EmailVerificationConfigSchema,\n advanced: AdvancedAuthConfigSchema,\n mutualTls: MutualTLSConfigSchema.optional().describe('Mutual TLS (mTLS) configuration'),\n}).catchall(z.unknown());\n\nexport type AuthProviderConfig = z.infer;\nexport type AuthPluginConfig = z.infer;\nexport type SocialProviderConfig = z.infer;\nexport type EmailAndPasswordConfig = z.infer;\nexport type EmailVerificationConfig = z.infer;\nexport type AdvancedAuthConfig = z.infer;\nexport type AuthConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ComplianceFrameworkSchema } from './security-context.zod';\n\n/**\n * Compliance protocol for GDPR, CCPA, HIPAA, SOX, PCI-DSS\n */\nexport const GDPRConfigSchema = z.object({\n enabled: z.boolean().describe('Enable GDPR compliance controls'),\n dataSubjectRights: z.object({\n rightToAccess: z.boolean().default(true).describe('Allow data subjects to access their data'),\n rightToRectification: z.boolean().default(true).describe('Allow data subjects to correct their data'),\n rightToErasure: z.boolean().default(true).describe('Allow data subjects to request deletion'),\n rightToRestriction: z.boolean().default(true).describe('Allow data subjects to restrict processing'),\n rightToPortability: z.boolean().default(true).describe('Allow data subjects to export their data'),\n rightToObjection: z.boolean().default(true).describe('Allow data subjects to object to processing'),\n }).describe('Data subject rights configuration per GDPR Articles 15-21'),\n legalBasis: z.enum([\n 'consent',\n 'contract',\n 'legal-obligation',\n 'vital-interests',\n 'public-task',\n 'legitimate-interests',\n ]).describe('Legal basis for data processing under GDPR Article 6'),\n consentTracking: z.boolean().default(true).describe('Track and record user consent'),\n dataRetentionDays: z.number().optional().describe('Maximum data retention period in days'),\n dataProcessingAgreement: z.string().optional().describe('URL or reference to the data processing agreement'),\n}).describe('GDPR (General Data Protection Regulation) compliance configuration');\n\nexport type GDPRConfig = z.infer;\nexport type GDPRConfigInput = z.input;\n\nexport const HIPAAConfigSchema = z.object({\n enabled: z.boolean().describe('Enable HIPAA compliance controls'),\n phi: z.object({\n encryption: z.boolean().default(true).describe('Encrypt Protected Health Information at rest'),\n accessControl: z.boolean().default(true).describe('Enforce role-based access to PHI'),\n auditTrail: z.boolean().default(true).describe('Log all PHI access events'),\n backupAndRecovery: z.boolean().default(true).describe('Enable PHI backup and disaster recovery'),\n }).describe('Protected Health Information safeguards'),\n businessAssociateAgreement: z.boolean().default(false).describe('BAA is in place with third-party processors'),\n}).describe('HIPAA (Health Insurance Portability and Accountability Act) compliance configuration');\n\nexport type HIPAAConfig = z.infer;\nexport type HIPAAConfigInput = z.input;\n\nexport const PCIDSSConfigSchema = z.object({\n enabled: z.boolean().describe('Enable PCI-DSS compliance controls'),\n level: z.enum(['1', '2', '3', '4']).describe('PCI-DSS compliance level (1 = highest)'),\n cardDataFields: z.array(z.string()).describe('Field names containing cardholder data'),\n tokenization: z.boolean().default(true).describe('Replace card data with secure tokens'),\n encryptionInTransit: z.boolean().default(true).describe('Encrypt cardholder data during transmission'),\n encryptionAtRest: z.boolean().default(true).describe('Encrypt stored cardholder data'),\n}).describe('PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration');\n\nexport type PCIDSSConfig = z.infer;\nexport type PCIDSSConfigInput = z.input;\n\nexport const AuditLogConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable audit logging'),\n retentionDays: z.number().default(365).describe('Number of days to retain audit logs'),\n immutable: z.boolean().default(true).describe('Prevent modification or deletion of audit logs'),\n signLogs: z.boolean().default(false).describe('Cryptographically sign log entries for tamper detection'),\n events: z.array(z.enum([\n 'create',\n 'read',\n 'update',\n 'delete',\n 'export',\n 'permission-change',\n 'login',\n 'logout',\n 'failed-login',\n ])).describe('Event types to capture in the audit log'),\n}).describe('Audit log configuration for compliance and security monitoring');\n\nexport type AuditLogConfig = z.infer;\nexport type AuditLogConfigInput = z.input;\n\n/**\n * Audit Finding Severity Schema\n *\n * Severity classification for audit findings.\n */\nexport const AuditFindingSeveritySchema = z.enum([\n 'critical', // Immediate remediation required\n 'major', // Significant non-conformity\n 'minor', // Minor non-conformity\n 'observation', // Improvement opportunity\n]);\n\n/**\n * Audit Finding Status Schema\n *\n * Lifecycle status of an audit finding.\n */\nexport const AuditFindingStatusSchema = z.enum([\n 'open', // Finding identified, not yet addressed\n 'in_remediation', // Remediation in progress\n 'remediated', // Remediation completed, pending verification\n 'verified', // Remediation verified and accepted\n 'accepted_risk', // Risk accepted by management\n 'closed', // Finding closed\n]);\n\n/**\n * Audit Finding Schema (A.5.35)\n *\n * Individual finding from a compliance or security audit.\n * Supports tracking from discovery through remediation and verification.\n *\n * @example\n * ```json\n * {\n * \"id\": \"FIND-2024-001\",\n * \"title\": \"Insufficient access logging\",\n * \"description\": \"PHI access events are not being logged for HIPAA compliance\",\n * \"severity\": \"major\",\n * \"status\": \"in_remediation\",\n * \"controlReference\": \"A.8.15\",\n * \"framework\": \"iso27001\",\n * \"identifiedAt\": 1704067200000,\n * \"identifiedBy\": \"external_auditor\",\n * \"remediationPlan\": \"Implement audit logging for all PHI access events\",\n * \"remediationDeadline\": 1706745600000\n * }\n * ```\n */\nexport const AuditFindingSchema = z.object({\n /**\n * Unique finding identifier\n */\n id: z.string().describe('Unique finding identifier'),\n\n /**\n * Short descriptive title\n */\n title: z.string().describe('Finding title'),\n\n /**\n * Detailed description of the finding\n */\n description: z.string().describe('Finding description'),\n\n /**\n * Finding severity\n */\n severity: AuditFindingSeveritySchema.describe('Finding severity'),\n\n /**\n * Current status\n */\n status: AuditFindingStatusSchema.describe('Finding status'),\n\n /**\n * ISO 27001 control reference (e.g., \"A.5.35\", \"A.8.15\")\n */\n controlReference: z.string().optional().describe('ISO 27001 control reference'),\n\n /**\n * Compliance framework\n */\n framework: ComplianceFrameworkSchema.optional()\n .describe('Related compliance framework'),\n\n /**\n * Timestamp when finding was identified (Unix milliseconds)\n */\n identifiedAt: z.number().describe('Identification timestamp'),\n\n /**\n * User or entity who identified the finding\n */\n identifiedBy: z.string().describe('Identifier (auditor name or system)'),\n\n /**\n * Planned remediation actions\n */\n remediationPlan: z.string().optional().describe('Remediation plan'),\n\n /**\n * Remediation deadline (Unix milliseconds)\n */\n remediationDeadline: z.number().optional().describe('Remediation deadline timestamp'),\n\n /**\n * Timestamp when remediation was verified (Unix milliseconds)\n */\n verifiedAt: z.number().optional().describe('Verification timestamp'),\n\n /**\n * Verifier name or role\n */\n verifiedBy: z.string().optional().describe('Verifier name or role'),\n\n /**\n * Notes or comments\n */\n notes: z.string().optional().describe('Additional notes'),\n}).describe('Audit finding with remediation tracking per ISO 27001:2022 A.5.35');\n\nexport type AuditFinding = z.infer;\n\n/**\n * Audit Schedule Schema (A.5.35)\n *\n * Defines audit scheduling for independent information security reviews.\n * Supports recurring audits, scope definition, and assessor assignment.\n *\n * @example\n * ```json\n * {\n * \"id\": \"AUDIT-2024-Q1\",\n * \"title\": \"Q1 ISO 27001 Internal Audit\",\n * \"scope\": [\"access_control\", \"encryption\", \"incident_response\"],\n * \"framework\": \"iso27001\",\n * \"scheduledAt\": 1711929600000,\n * \"assessor\": \"internal_audit_team\",\n * \"recurrenceMonths\": 3\n * }\n * ```\n */\nexport const AuditScheduleSchema = z.object({\n /**\n * Unique audit schedule identifier\n */\n id: z.string().describe('Unique audit schedule identifier'),\n\n /**\n * Audit title or name\n */\n title: z.string().describe('Audit title'),\n\n /**\n * Scope of areas to audit\n */\n scope: z.array(z.string()).describe('Audit scope areas'),\n\n /**\n * Target compliance framework\n */\n framework: ComplianceFrameworkSchema\n .describe('Target compliance framework'),\n\n /**\n * Scheduled audit date (Unix milliseconds)\n */\n scheduledAt: z.number().describe('Scheduled audit timestamp'),\n\n /**\n * Actual completion date (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Completion timestamp'),\n\n /**\n * Assessor name, team, or external firm\n */\n assessor: z.string().describe('Assessor or audit team'),\n\n /**\n * Whether this is an external (independent) audit\n */\n isExternal: z.boolean().default(false).describe('Whether this is an external audit'),\n\n /**\n * Recurrence interval in months (0 = one-time)\n */\n recurrenceMonths: z.number().default(0).describe('Recurrence interval in months (0 = one-time)'),\n\n /**\n * Findings from this audit\n */\n findings: z.array(AuditFindingSchema).optional().describe('Audit findings'),\n}).describe('Audit schedule for independent security reviews per ISO 27001:2022 A.5.35');\n\nexport type AuditSchedule = z.infer;\n\nexport const ComplianceConfigSchema = z.object({\n gdpr: GDPRConfigSchema.optional().describe('GDPR compliance settings'),\n hipaa: HIPAAConfigSchema.optional().describe('HIPAA compliance settings'),\n pciDss: PCIDSSConfigSchema.optional().describe('PCI-DSS compliance settings'),\n auditLog: AuditLogConfigSchema.describe('Audit log configuration'),\n auditSchedules: z.array(AuditScheduleSchema).optional()\n .describe('Scheduled compliance audits (A.5.35)'),\n}).describe('Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance');\n\nexport type ComplianceConfig = z.infer;\nexport type ComplianceConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Incident Response Protocol — ISO 27001:2022 (A.5.24–A.5.28)\n *\n * Defines schemas for information security event management including\n * incident classification, severity grading, response procedures,\n * and notification matrices.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Incident Severity Schema\n *\n * Severity grading for security incidents following ISO 27001 guidelines.\n * Determines response urgency and escalation requirements.\n */\nexport const IncidentSeveritySchema = z.enum([\n 'critical', // Immediate threat to business operations or data integrity\n 'high', // Significant impact requiring urgent response\n 'medium', // Moderate impact with controlled response timeline\n 'low', // Minor impact with standard response procedures\n]);\n\n/**\n * Incident Category Schema\n *\n * Classification of security incidents by type (A.5.25).\n * Used for routing, reporting, and trend analysis.\n */\nexport const IncidentCategorySchema = z.enum([\n 'data_breach', // Unauthorized access or disclosure of data\n 'malware', // Malicious software detection\n 'unauthorized_access', // Unauthorized system or data access\n 'denial_of_service', // Service availability attack\n 'social_engineering', // Phishing, pretexting, or manipulation\n 'insider_threat', // Threat originating from internal actors\n 'physical_security', // Physical security breach\n 'configuration_error', // Security misconfiguration\n 'vulnerability_exploit', // Exploitation of known vulnerability\n 'policy_violation', // Violation of security policies\n 'other', // Other security incidents\n]);\n\n/**\n * Incident Status Schema\n *\n * Current status of a security incident in its lifecycle.\n */\nexport const IncidentStatusSchema = z.enum([\n 'reported', // Initial report received\n 'triaged', // Severity and category assessed\n 'investigating', // Active investigation in progress\n 'containing', // Containment measures being applied\n 'eradicating', // Root cause being removed\n 'recovering', // Systems being restored to normal\n 'resolved', // Incident resolved\n 'closed', // Post-incident review complete\n]);\n\n/**\n * Incident Response Phase Schema\n *\n * Defines structured response phases per NIST SP 800-61 / ISO 27001 (A.5.26).\n */\nexport const IncidentResponsePhaseSchema = z.object({\n /**\n * Phase name identifier\n */\n phase: z.enum([\n 'identification',\n 'containment',\n 'eradication',\n 'recovery',\n 'lessons_learned',\n ]).describe('Response phase name'),\n\n /**\n * Phase description and objectives\n */\n description: z.string().describe('Phase description and objectives'),\n\n /**\n * Responsible team or role for this phase\n */\n assignedTo: z.string().describe('Responsible team or role'),\n\n /**\n * Target completion time in hours from incident start\n */\n targetHours: z.number().min(0).describe('Target completion time in hours'),\n\n /**\n * Actual completion timestamp (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Actual completion timestamp'),\n\n /**\n * Notes and findings during this phase\n */\n notes: z.string().optional().describe('Phase notes and findings'),\n}).describe('Incident response phase with timing and assignment');\n\nexport type IncidentResponsePhase = z.infer;\n\n/**\n * Notification Rule Schema\n *\n * Defines who must be notified and when, based on severity (A.5.27).\n */\nexport const IncidentNotificationRuleSchema = z.object({\n /**\n * Minimum severity level that triggers this notification\n */\n severity: IncidentSeveritySchema.describe('Minimum severity to trigger notification'),\n\n /**\n * Notification channels to use\n */\n channels: z.array(z.enum([\n 'email',\n 'sms',\n 'slack',\n 'pagerduty',\n 'webhook',\n ])).describe('Notification channels'),\n\n /**\n * Roles or teams to notify\n */\n recipients: z.array(z.string()).describe('Roles or teams to notify'),\n\n /**\n * Maximum time in minutes to send notification after incident detection\n */\n withinMinutes: z.number().min(1).describe('Notification deadline in minutes from detection'),\n\n /**\n * Whether to notify external regulators (for data breaches)\n */\n notifyRegulators: z.boolean().default(false)\n .describe('Whether to notify regulatory authorities'),\n\n /**\n * Regulatory notification deadline in hours (e.g., GDPR 72h)\n */\n regulatorDeadlineHours: z.number().optional()\n .describe('Regulatory notification deadline in hours'),\n}).describe('Incident notification rule per severity level');\n\nexport type IncidentNotificationRule = z.infer;\n\n/**\n * Notification Matrix Schema\n *\n * Complete notification matrix mapping severity levels to stakeholder groups (A.5.27).\n */\nexport const IncidentNotificationMatrixSchema = z.object({\n /**\n * Notification rules ordered by severity\n */\n rules: z.array(IncidentNotificationRuleSchema)\n .describe('Notification rules by severity level'),\n\n /**\n * Default escalation timeout in minutes before auto-escalation\n */\n escalationTimeoutMinutes: z.number().default(30)\n .describe('Auto-escalation timeout in minutes'),\n\n /**\n * Escalation chain: ordered list of roles to escalate to\n */\n escalationChain: z.array(z.string()).default([])\n .describe('Ordered escalation chain of roles'),\n}).describe('Incident notification matrix with escalation policies');\n\nexport type IncidentNotificationMatrix = z.infer;\n\n/**\n * Incident Schema\n *\n * Comprehensive security incident record following ISO 27001:2022 (A.5.24–A.5.28).\n * Tracks the full incident lifecycle from detection through post-incident review.\n *\n * @example\n * ```json\n * {\n * \"id\": \"INC-2024-001\",\n * \"title\": \"Unauthorized API Access Detected\",\n * \"description\": \"Multiple failed authentication attempts from unknown IP range\",\n * \"severity\": \"high\",\n * \"category\": \"unauthorized_access\",\n * \"status\": \"investigating\",\n * \"reportedBy\": \"monitoring_system\",\n * \"reportedAt\": 1704067200000,\n * \"affectedSystems\": [\"api-gateway\", \"auth-service\"],\n * \"affectedDataClassifications\": [\"pii\", \"confidential\"],\n * \"responsePhases\": [\n * {\n * \"phase\": \"identification\",\n * \"description\": \"Identify scope of unauthorized access\",\n * \"assignedTo\": \"security_team\",\n * \"targetHours\": 2\n * }\n * ]\n * }\n * ```\n */\nexport const IncidentSchema = z.object({\n /**\n * Unique incident identifier\n */\n id: z.string().describe('Unique incident identifier'),\n\n /**\n * Short descriptive title of the incident\n */\n title: z.string().describe('Incident title'),\n\n /**\n * Detailed description of the security event\n */\n description: z.string().describe('Detailed incident description'),\n\n /**\n * Severity classification\n */\n severity: IncidentSeveritySchema.describe('Incident severity level'),\n\n /**\n * Incident category / type\n */\n category: IncidentCategorySchema.describe('Incident category'),\n\n /**\n * Current status in the incident lifecycle\n */\n status: IncidentStatusSchema.describe('Current incident status'),\n\n /**\n * User or system that reported the incident\n */\n reportedBy: z.string().describe('Reporter user ID or system name'),\n\n /**\n * Timestamp when the incident was reported (Unix milliseconds)\n */\n reportedAt: z.number().describe('Report timestamp'),\n\n /**\n * Timestamp when the incident was detected (may differ from reported)\n */\n detectedAt: z.number().optional().describe('Detection timestamp'),\n\n /**\n * Timestamp when the incident was resolved\n */\n resolvedAt: z.number().optional().describe('Resolution timestamp'),\n\n /**\n * Systems affected by the incident\n */\n affectedSystems: z.array(z.string()).describe('Affected systems'),\n\n /**\n * Data classifications affected (for data breach assessment)\n */\n affectedDataClassifications: z.array(DataClassificationSchema)\n .optional().describe('Affected data classifications'),\n\n /**\n * Structured response phases tracking\n */\n responsePhases: z.array(IncidentResponsePhaseSchema).optional()\n .describe('Incident response phases'),\n\n /**\n * Root cause analysis (completed post-incident)\n */\n rootCause: z.string().optional().describe('Root cause analysis'),\n\n /**\n * Corrective actions taken or planned\n */\n correctiveActions: z.array(z.string()).optional()\n .describe('Corrective actions taken or planned'),\n\n /**\n * Lessons learned from the incident (A.5.28)\n */\n lessonsLearned: z.string().optional()\n .describe('Lessons learned from the incident'),\n\n /**\n * Related change request IDs (if changes resulted from incident)\n */\n relatedChangeRequestIds: z.array(z.string()).optional()\n .describe('Related change request IDs'),\n\n /**\n * Custom metadata for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Custom metadata key-value pairs'),\n}).describe('Security incident record per ISO 27001:2022 A.5.24–A.5.28');\n\n/**\n * Incident Response Policy Schema\n *\n * Organization-level incident response policy configuration (A.5.24).\n */\nexport const IncidentResponsePolicySchema = z.object({\n /**\n * Whether incident response is enabled\n */\n enabled: z.boolean().default(true)\n .describe('Enable incident response management'),\n\n /**\n * Notification matrix configuration\n */\n notificationMatrix: IncidentNotificationMatrixSchema\n .describe('Notification and escalation matrix'),\n\n /**\n * Default response team or role\n */\n defaultResponseTeam: z.string()\n .describe('Default incident response team or role'),\n\n /**\n * Maximum time in hours to begin initial triage\n */\n triageDeadlineHours: z.number().default(1)\n .describe('Maximum hours to begin triage after detection'),\n\n /**\n * Whether to require post-incident review for all incidents\n */\n requirePostIncidentReview: z.boolean().default(true)\n .describe('Require post-incident review for all incidents'),\n\n /**\n * Minimum severity level that requires regulatory notification\n */\n regulatoryNotificationThreshold: IncidentSeveritySchema.default('high')\n .describe('Minimum severity requiring regulatory notification'),\n\n /**\n * Retention period for incident records in days\n */\n retentionDays: z.number().default(2555)\n .describe('Incident record retention period in days (default ~7 years)'),\n}).describe('Organization-level incident response policy per ISO 27001:2022');\n\n// Type exports\nexport type IncidentSeverity = z.infer;\nexport type IncidentCategory = z.infer;\nexport type IncidentStatus = z.infer;\nexport type Incident = z.infer;\nexport type IncidentResponsePolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Supplier Security Protocol — ISO 27001:2022 (A.5.19–A.5.22)\n *\n * Defines schemas for supplier information security management including\n * risk assessment, security requirements, monitoring, and change control.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Supplier Risk Level Schema\n *\n * Risk classification for supplier relationships based on data access\n * and service criticality.\n */\nexport const SupplierRiskLevelSchema = z.enum([\n 'critical', // Direct access to sensitive data or core infrastructure\n 'high', // Significant data processing or service dependency\n 'medium', // Limited data access with moderate dependency\n 'low', // Minimal data access and low service dependency\n]);\n\n/**\n * Supplier Assessment Status Schema\n *\n * Current status of a supplier security assessment.\n */\nexport const SupplierAssessmentStatusSchema = z.enum([\n 'pending', // Assessment not yet started\n 'in_progress', // Assessment currently underway\n 'completed', // Assessment completed\n 'expired', // Assessment past its validity period\n 'failed', // Supplier did not meet security requirements\n]);\n\n/**\n * Supplier Security Requirement Schema\n *\n * Individual security requirement to assess against a supplier (A.5.20).\n */\nexport const SupplierSecurityRequirementSchema = z.object({\n /**\n * Requirement identifier\n */\n id: z.string().describe('Requirement identifier'),\n\n /**\n * Requirement description\n */\n description: z.string().describe('Requirement description'),\n\n /**\n * ISO 27001 control reference (e.g., \"A.5.19\")\n */\n controlReference: z.string().optional()\n .describe('ISO 27001 control reference'),\n\n /**\n * Whether this requirement is mandatory\n */\n mandatory: z.boolean().default(true)\n .describe('Whether this requirement is mandatory'),\n\n /**\n * Compliance status\n */\n compliant: z.boolean().optional()\n .describe('Whether the supplier meets this requirement'),\n\n /**\n * Evidence or notes for compliance assessment\n */\n evidence: z.string().optional()\n .describe('Compliance evidence or assessment notes'),\n}).describe('Individual supplier security requirement');\n\nexport type SupplierSecurityRequirement = z.infer;\n\n/**\n * Supplier Security Assessment Schema\n *\n * Comprehensive supplier security assessment record (A.5.19–A.5.21).\n *\n * @example\n * ```json\n * {\n * \"supplierId\": \"SUP-001\",\n * \"supplierName\": \"Cloud Provider Inc.\",\n * \"riskLevel\": \"critical\",\n * \"status\": \"completed\",\n * \"assessedBy\": \"security_team\",\n * \"assessedAt\": 1704067200000,\n * \"validUntil\": 1735689600000,\n * \"requirements\": [\n * {\n * \"id\": \"REQ-001\",\n * \"description\": \"Data encryption at rest using AES-256\",\n * \"controlReference\": \"A.8.24\",\n * \"mandatory\": true,\n * \"compliant\": true\n * }\n * ],\n * \"overallCompliant\": true,\n * \"dataClassificationsShared\": [\"pii\", \"confidential\"]\n * }\n * ```\n */\nexport const SupplierSecurityAssessmentSchema = z.object({\n /**\n * Unique supplier identifier\n */\n supplierId: z.string().describe('Unique supplier identifier'),\n\n /**\n * Supplier name\n */\n supplierName: z.string().describe('Supplier display name'),\n\n /**\n * Risk classification\n */\n riskLevel: SupplierRiskLevelSchema.describe('Supplier risk classification'),\n\n /**\n * Assessment status\n */\n status: SupplierAssessmentStatusSchema.describe('Assessment status'),\n\n /**\n * User or team who performed the assessment\n */\n assessedBy: z.string().describe('Assessor user ID or team'),\n\n /**\n * Assessment completion timestamp (Unix milliseconds)\n */\n assessedAt: z.number().describe('Assessment timestamp'),\n\n /**\n * Assessment validity expiry (Unix milliseconds)\n */\n validUntil: z.number().describe('Assessment validity expiry timestamp'),\n\n /**\n * Security requirements assessed\n */\n requirements: z.array(SupplierSecurityRequirementSchema)\n .describe('Security requirements and their compliance status'),\n\n /**\n * Overall compliance result\n */\n overallCompliant: z.boolean().describe('Whether supplier meets all mandatory requirements'),\n\n /**\n * Data classifications shared with this supplier\n */\n dataClassificationsShared: z.array(DataClassificationSchema)\n .optional().describe('Data classifications shared with supplier'),\n\n /**\n * Services provided by the supplier\n */\n servicesProvided: z.array(z.string()).optional()\n .describe('Services provided by this supplier'),\n\n /**\n * Certifications held by the supplier\n */\n certifications: z.array(z.string()).optional()\n .describe('Supplier certifications (e.g., ISO 27001, SOC 2)'),\n\n /**\n * Remediation items for non-compliant requirements\n */\n remediationItems: z.array(z.object({\n requirementId: z.string().describe('Non-compliant requirement ID'),\n action: z.string().describe('Required remediation action'),\n deadline: z.number().describe('Remediation deadline timestamp'),\n status: z.enum(['pending', 'in_progress', 'completed']).default('pending')\n .describe('Remediation status'),\n })).optional().describe('Remediation items for non-compliant requirements'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Custom metadata key-value pairs'),\n}).describe('Supplier security assessment record per ISO 27001:2022 A.5.19–A.5.21');\n\n/**\n * Supplier Security Policy Schema\n *\n * Organization-level supplier security management policy (A.5.22).\n */\nexport const SupplierSecurityPolicySchema = z.object({\n /**\n * Whether supplier security management is enabled\n */\n enabled: z.boolean().default(true)\n .describe('Enable supplier security management'),\n\n /**\n * Reassessment interval in days\n */\n reassessmentIntervalDays: z.number().default(365)\n .describe('Supplier reassessment interval in days'),\n\n /**\n * Whether to require supplier security assessment before onboarding\n */\n requirePreOnboardingAssessment: z.boolean().default(true)\n .describe('Require security assessment before supplier onboarding'),\n\n /**\n * Minimum risk level that requires formal assessment\n */\n formalAssessmentThreshold: SupplierRiskLevelSchema.default('medium')\n .describe('Minimum risk level requiring formal assessment'),\n\n /**\n * Whether to monitor supplier security changes (A.5.22)\n */\n monitorChanges: z.boolean().default(true)\n .describe('Monitor supplier security posture changes'),\n\n /**\n * Required certifications for critical suppliers\n */\n requiredCertifications: z.array(z.string()).default([])\n .describe('Required certifications for critical-risk suppliers'),\n}).describe('Organization-level supplier security management policy per ISO 27001:2022');\n\n// Type exports\nexport type SupplierRiskLevel = z.infer;\nexport type SupplierAssessmentStatus = z.infer;\nexport type SupplierSecurityAssessment = z.infer;\nexport type SupplierSecurityPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Information Security Training Protocol — ISO 27001:2022 (A.6.3)\n *\n * Defines schemas for security awareness and training management including\n * course definitions, completion tracking, and organizational training plans.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Training Category Schema\n *\n * Classification of training content by domain.\n */\nexport const TrainingCategorySchema = z.enum([\n 'security_awareness', // General security awareness\n 'data_protection', // Data handling and privacy\n 'incident_response', // Incident reporting and response\n 'access_control', // Access management best practices\n 'phishing_awareness', // Phishing and social engineering\n 'compliance', // Regulatory compliance (GDPR, HIPAA, etc.)\n 'secure_development', // Secure coding and development practices\n 'physical_security', // Physical security awareness\n 'business_continuity', // Business continuity and disaster recovery\n 'other', // Other training categories\n]);\n\n/**\n * Training Completion Status Schema\n */\nexport const TrainingCompletionStatusSchema = z.enum([\n 'not_started', // Training not yet begun\n 'in_progress', // Training currently underway\n 'completed', // Training completed successfully\n 'failed', // Training assessment not passed\n 'expired', // Training certification has expired\n]);\n\n/**\n * Training Course Schema\n *\n * Definition of a security training course or module.\n *\n * @example\n * ```json\n * {\n * \"id\": \"COURSE-SEC-001\",\n * \"title\": \"Information Security Fundamentals\",\n * \"description\": \"Annual security awareness training for all employees\",\n * \"category\": \"security_awareness\",\n * \"durationMinutes\": 60,\n * \"mandatory\": true,\n * \"targetRoles\": [\"all_employees\"],\n * \"validityDays\": 365,\n * \"passingScore\": 80\n * }\n * ```\n */\nexport const TrainingCourseSchema = z.object({\n /**\n * Unique course identifier\n */\n id: z.string().describe('Unique course identifier'),\n\n /**\n * Course title\n */\n title: z.string().describe('Course title'),\n\n /**\n * Course description and objectives\n */\n description: z.string().describe('Course description and learning objectives'),\n\n /**\n * Training category\n */\n category: TrainingCategorySchema.describe('Training category'),\n\n /**\n * Estimated duration in minutes\n */\n durationMinutes: z.number().min(1).describe('Estimated course duration in minutes'),\n\n /**\n * Whether this training is mandatory\n */\n mandatory: z.boolean().default(false).describe('Whether training is mandatory'),\n\n /**\n * Target roles or groups for this training\n */\n targetRoles: z.array(z.string()).describe('Target roles or groups'),\n\n /**\n * Validity period in days before recertification is needed\n */\n validityDays: z.number().optional().describe('Certification validity period in days'),\n\n /**\n * Minimum passing score (percentage) for assessment\n */\n passingScore: z.number().min(0).max(100).optional()\n .describe('Minimum passing score percentage'),\n\n /**\n * Course version for tracking content updates\n */\n version: z.string().optional().describe('Course content version'),\n}).describe('Security training course definition');\n\n/**\n * Training Record Schema\n *\n * Individual employee training completion record.\n */\nexport const TrainingRecordSchema = z.object({\n /**\n * Reference to the course ID\n */\n courseId: z.string().describe('Training course identifier'),\n\n /**\n * User who completed (or is assigned) the training\n */\n userId: z.string().describe('User identifier'),\n\n /**\n * Completion status\n */\n status: TrainingCompletionStatusSchema.describe('Training completion status'),\n\n /**\n * Training assignment date (Unix milliseconds)\n */\n assignedAt: z.number().describe('Assignment timestamp'),\n\n /**\n * Training completion date (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Completion timestamp'),\n\n /**\n * Assessment score (percentage)\n */\n score: z.number().min(0).max(100).optional().describe('Assessment score percentage'),\n\n /**\n * Certification expiry date (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Certification expiry timestamp'),\n\n /**\n * Notes or comments from instructor or system\n */\n notes: z.string().optional().describe('Training notes or comments'),\n}).describe('Individual training completion record');\n\n/**\n * Training Plan Schema\n *\n * Organizational training plan defining schedule and requirements (A.6.3).\n */\nexport const TrainingPlanSchema = z.object({\n /**\n * Whether training management is enabled\n */\n enabled: z.boolean().default(true).describe('Enable training management'),\n\n /**\n * Training courses in the plan\n */\n courses: z.array(TrainingCourseSchema).describe('Training courses'),\n\n /**\n * Default recertification interval in days\n */\n recertificationIntervalDays: z.number().default(365)\n .describe('Default recertification interval in days'),\n\n /**\n * Whether to track training completion for compliance reporting\n */\n trackCompletion: z.boolean().default(true)\n .describe('Track training completion for compliance'),\n\n /**\n * Grace period in days after expiry before non-compliance escalation\n */\n gracePeriodDays: z.number().default(30)\n .describe('Grace period in days after certification expiry'),\n\n /**\n * Whether to send reminders for upcoming training deadlines\n */\n sendReminders: z.boolean().default(true)\n .describe('Send reminders for upcoming training deadlines'),\n\n /**\n * Days before deadline to send first reminder\n */\n reminderDaysBefore: z.number().default(14)\n .describe('Days before deadline to send first reminder'),\n}).describe('Organizational training plan per ISO 27001:2022 A.6.3');\n\n// Type exports\nexport type TrainingCategory = z.infer;\nexport type TrainingCompletionStatus = z.infer;\nexport type TrainingCourse = z.infer;\nexport type TrainingRecord = z.infer;\nexport type TrainingPlan = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Cron Schedule Schema\n * Schedule jobs using cron expressions\n */\nexport const CronScheduleSchema = z.object({\n type: z.literal('cron'),\n expression: z.string().describe('Cron expression (e.g., \"0 0 * * *\" for daily at midnight)'),\n timezone: z.string().optional().default('UTC').describe('Timezone for cron execution (e.g., \"America/New_York\")'),\n});\n\n/**\n * Interval Schedule Schema\n * Schedule jobs at fixed intervals\n */\nexport const IntervalScheduleSchema = z.object({\n type: z.literal('interval'),\n intervalMs: z.number().int().positive().describe('Interval in milliseconds'),\n});\n\n/**\n * Once Schedule Schema\n * Schedule a job to run once at a specific time\n */\nexport const OnceScheduleSchema = z.object({\n type: z.literal('once'),\n at: z.string().datetime().describe('ISO 8601 datetime when to execute'),\n});\n\n/**\n * Schedule Schema\n * Discriminated union of all schedule types\n */\nexport const ScheduleSchema = z.discriminatedUnion('type', [\n CronScheduleSchema,\n IntervalScheduleSchema,\n OnceScheduleSchema,\n]);\n\nexport type Schedule = z.infer;\nexport type CronSchedule = z.infer;\nexport type IntervalSchedule = z.infer;\nexport type OnceSchedule = z.infer;\nexport type JobSchedule = Schedule; // Alias for backwards compatibility\n\n/**\n * Retry Policy Schema\n * Configuration for job retry behavior with exponential backoff\n */\nexport const RetryPolicySchema = z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum number of retry attempts'),\n backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay in milliseconds'),\n backoffMultiplier: z.number().positive().default(2).describe('Multiplier for exponential backoff'),\n});\n\nexport type RetryPolicy = z.infer;\n\n/**\n * Job Schema\n * Defines a scheduled job that executes background logic.\n * \n * @example Metadata Sync Job (Cron)\n * {\n * id: \"job_sync_meta\",\n * name: \"sync_metadata_nightly\",\n * schedule: {\n * type: \"cron\",\n * expression: \"0 0 * * *\", // Midnight\n * timezone: \"UTC\"\n * },\n * handler: \"services/syncStatus.ts:syncAll\", \n * retryPolicy: {\n * maxRetries: 3,\n * backoffMs: 5000\n * }\n * }\n */\nexport const JobSchema = z.object({\n id: z.string().describe('Unique job identifier'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Job name (snake_case)'),\n schedule: ScheduleSchema.describe('Job schedule configuration'),\n handler: z.string().describe('Handler path (e.g. \"path/to/file:functionName\") or script ID'),\n retryPolicy: RetryPolicySchema.optional().describe('Retry policy configuration'),\n timeout: z.number().int().positive().optional().describe('Timeout in milliseconds'),\n enabled: z.boolean().default(true).describe('Whether the job is enabled'),\n});\n\nexport type Job = z.infer;\n\n/**\n * Job Execution Status Enum\n * Status of job execution\n */\nexport const JobExecutionStatus = z.enum([\n 'running',\n 'success',\n 'failed',\n 'timeout',\n]);\n\nexport type JobExecutionStatus = z.infer;\n\n/**\n * Job Execution Schema\n * Logs for job execution\n */\nexport const JobExecutionSchema = z.object({\n jobId: z.string().describe('Job identifier'),\n startedAt: z.string().datetime().describe('ISO 8601 datetime when execution started'),\n completedAt: z.string().datetime().optional().describe('ISO 8601 datetime when execution completed'),\n status: JobExecutionStatus.describe('Execution status'),\n error: z.string().optional().describe('Error message if failed'),\n duration: z.number().int().optional().describe('Execution duration in milliseconds'),\n});\n\nexport type JobExecution = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Worker System Protocol\n * \n * Background task processing system with queues, priorities, and retry logic.\n * Provides a robust foundation for async task execution similar to:\n * - Sidekiq (Ruby)\n * - Celery (Python)\n * - Bull/BullMQ (Node.js)\n * - AWS SQS/Lambda\n * \n * Features:\n * - Task queues with priorities\n * - Task scheduling and retry logic\n * - Batch processing\n * - Dead letter queues\n * - Task monitoring and logging\n * \n * @example Basic task\n * ```typescript\n * const task: Task = {\n * id: 'task-123',\n * type: 'send_email',\n * payload: { to: 'user@example.com', subject: 'Welcome' },\n * queue: 'notifications',\n * priority: 5\n * };\n * ```\n */\n\n// ==========================================\n// Task Priority\n// ==========================================\n\n/**\n * Task Priority Enum\n * Lower numbers = higher priority\n */\nexport const TaskPriority = z.enum([\n 'critical', // 0 - Must execute immediately\n 'high', // 1 - Execute soon\n 'normal', // 2 - Default priority\n 'low', // 3 - Execute when resources available\n 'background', // 4 - Execute during low-traffic periods\n]);\n\nexport type TaskPriority = z.infer;\n\n/**\n * Task Priority Mapping\n * Maps priority names to numeric values for sorting\n */\nexport const TASK_PRIORITY_VALUES: Record = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n background: 4,\n};\n\n// ==========================================\n// Task Status\n// ==========================================\n\n/**\n * Task Status Enum\n * Lifecycle states of a task\n */\nexport const TaskStatus = z.enum([\n 'pending', // Waiting to be processed\n 'queued', // In queue, ready for worker\n 'processing', // Currently being executed\n 'completed', // Successfully completed\n 'failed', // Failed (may retry)\n 'cancelled', // Manually cancelled\n 'timeout', // Exceeded execution timeout\n 'dead', // Moved to dead letter queue\n]);\n\nexport type TaskStatus = z.infer;\n\n// ==========================================\n// Task Schema\n// ==========================================\n\n/**\n * Task Retry Policy Schema\n * Configuration for task retry behavior\n */\nexport const TaskRetryPolicySchema = z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy between retries'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay in milliseconds'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay in milliseconds'),\n backoffMultiplier: z.number().positive().default(2).describe('Multiplier for exponential backoff'),\n});\n\nexport type TaskRetryPolicy = z.infer;\nexport type TaskRetryPolicyInput = z.input;\n\n/**\n * Task Schema\n * Represents a background task to be executed\n * \n * @example\n * {\n * \"id\": \"task-abc123\",\n * \"type\": \"send_email\",\n * \"payload\": { \"to\": \"user@example.com\", \"template\": \"welcome\" },\n * \"queue\": \"notifications\",\n * \"priority\": \"high\",\n * \"retryPolicy\": {\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * }\n * }\n */\nexport const TaskSchema = z.object({\n /**\n * Unique task identifier\n */\n id: z.string().describe('Unique task identifier'),\n \n /**\n * Task type (handler identifier)\n */\n type: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Task type (snake_case)'),\n \n /**\n * Task payload data\n */\n payload: z.unknown().describe('Task payload data'),\n \n /**\n * Queue name\n */\n queue: z.string().default('default').describe('Queue name'),\n \n /**\n * Task priority\n */\n priority: TaskPriority.default('normal').describe('Task priority level'),\n \n /**\n * Retry policy\n */\n retryPolicy: TaskRetryPolicySchema.optional().describe('Retry policy configuration'),\n \n /**\n * Execution timeout in milliseconds\n */\n timeoutMs: z.number().int().positive().optional().describe('Task timeout in milliseconds'),\n \n /**\n * Scheduled execution time\n */\n scheduledAt: z.string().datetime().optional().describe('ISO 8601 datetime to execute task'),\n \n /**\n * Maximum execution attempts\n */\n attempts: z.number().int().min(0).default(0).describe('Number of execution attempts'),\n \n /**\n * Task status\n */\n status: TaskStatus.default('pending').describe('Current task status'),\n \n /**\n * Task metadata\n */\n metadata: z.object({\n createdAt: z.string().datetime().optional().describe('When task was created'),\n updatedAt: z.string().datetime().optional().describe('Last update time'),\n createdBy: z.string().optional().describe('User who created task'),\n tags: z.array(z.string()).optional().describe('Task tags for filtering'),\n }).optional().describe('Task metadata'),\n});\n\nexport type Task = z.infer;\nexport type TaskInput = z.input;\n\n// ==========================================\n// Task Execution Result\n// ==========================================\n\n/**\n * Task Execution Result Schema\n * Result of a task execution attempt\n */\nexport const TaskExecutionResultSchema = z.object({\n /**\n * Task identifier\n */\n taskId: z.string().describe('Task identifier'),\n \n /**\n * Execution status\n */\n status: TaskStatus.describe('Execution status'),\n \n /**\n * Execution result data\n */\n result: z.unknown().optional().describe('Execution result data'),\n \n /**\n * Error information\n */\n error: z.object({\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Error stack trace'),\n code: z.string().optional().describe('Error code'),\n }).optional().describe('Error details if failed'),\n \n /**\n * Execution duration\n */\n durationMs: z.number().int().optional().describe('Execution duration in milliseconds'),\n \n /**\n * Execution timestamps\n */\n startedAt: z.string().datetime().describe('When execution started'),\n completedAt: z.string().datetime().optional().describe('When execution completed'),\n \n /**\n * Retry information\n */\n attempt: z.number().int().min(1).describe('Attempt number (1-indexed)'),\n willRetry: z.boolean().describe('Whether task will be retried'),\n});\n\nexport type TaskExecutionResult = z.infer;\n\n// ==========================================\n// Queue Configuration\n// ==========================================\n\n/**\n * Queue Configuration Schema\n * Configuration for a task queue\n * \n * @example\n * {\n * \"name\": \"notifications\",\n * \"concurrency\": 10,\n * \"rateLimit\": {\n * \"max\": 100,\n * \"duration\": 60000\n * }\n * }\n */\nexport const QueueConfigSchema = z.object({\n /**\n * Queue name\n */\n name: z.string().describe('Queue name (snake_case)'),\n \n /**\n * Maximum concurrent workers\n */\n concurrency: z.number().int().min(1).default(5).describe('Max concurrent task executions'),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n max: z.number().int().positive().describe('Maximum tasks per duration'),\n duration: z.number().int().positive().describe('Duration in milliseconds'),\n }).optional().describe('Rate limit configuration'),\n \n /**\n * Default retry policy\n */\n defaultRetryPolicy: TaskRetryPolicySchema.optional().describe('Default retry policy for tasks'),\n \n /**\n * Dead letter queue\n */\n deadLetterQueue: z.string().optional().describe('Dead letter queue name'),\n \n /**\n * Queue priority\n */\n priority: z.number().int().min(0).default(0).describe('Queue priority (lower = higher priority)'),\n \n /**\n * Auto-scaling configuration\n */\n autoScale: z.object({\n enabled: z.boolean().default(false).describe('Enable auto-scaling'),\n minWorkers: z.number().int().min(1).default(1).describe('Minimum workers'),\n maxWorkers: z.number().int().min(1).default(10).describe('Maximum workers'),\n scaleUpThreshold: z.number().int().positive().default(100).describe('Queue size to scale up'),\n scaleDownThreshold: z.number().int().min(0).default(10).describe('Queue size to scale down'),\n }).optional().describe('Auto-scaling configuration'),\n});\n\nexport type QueueConfig = z.infer;\nexport type QueueConfigInput = z.input;\n\n// ==========================================\n// Batch Processing\n// ==========================================\n\n/**\n * Batch Task Schema\n * Configuration for batch processing multiple items\n * \n * @example\n * {\n * \"id\": \"batch-import-123\",\n * \"type\": \"import_records\",\n * \"items\": [{ \"name\": \"Item 1\" }, { \"name\": \"Item 2\" }],\n * \"batchSize\": 100,\n * \"queue\": \"batch_processing\"\n * }\n */\nexport const BatchTaskSchema = z.object({\n /**\n * Batch job identifier\n */\n id: z.string().describe('Unique batch job identifier'),\n \n /**\n * Task type for processing each item\n */\n type: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Task type (snake_case)'),\n \n /**\n * Items to process\n */\n items: z.array(z.unknown()).describe('Array of items to process'),\n \n /**\n * Batch size (items per task)\n */\n batchSize: z.number().int().min(1).default(100).describe('Number of items per batch'),\n \n /**\n * Queue name\n */\n queue: z.string().default('batch').describe('Queue for batch tasks'),\n \n /**\n * Priority\n */\n priority: TaskPriority.default('normal').describe('Batch task priority'),\n \n /**\n * Parallel processing\n */\n parallel: z.boolean().default(true).describe('Process batches in parallel'),\n \n /**\n * Stop on error\n */\n stopOnError: z.boolean().default(false).describe('Stop batch if any item fails'),\n \n /**\n * Progress callback\n * \n * Called after each batch completes to report progress.\n * Invoked asynchronously and should not throw errors.\n * If the callback throws, the error is logged but batch processing continues.\n * \n * @param progress - Object containing processed count, total count, and failed count\n */\n onProgress: z.function()\n .input(z.tuple([z.object({\n processed: z.number(),\n total: z.number(),\n failed: z.number(),\n })]))\n .output(z.void())\n .optional()\n .describe('Progress callback function (called after each batch)'),\n});\n\nexport type BatchTask = z.infer;\nexport type BatchTaskInput = z.input;\n\n/**\n * Batch Progress Schema\n * Tracks progress of a batch job\n */\nexport const BatchProgressSchema = z.object({\n /**\n * Batch job identifier\n */\n batchId: z.string().describe('Batch job identifier'),\n \n /**\n * Total items\n */\n total: z.number().int().min(0).describe('Total number of items'),\n \n /**\n * Processed items\n */\n processed: z.number().int().min(0).default(0).describe('Items processed'),\n \n /**\n * Successful items\n */\n succeeded: z.number().int().min(0).default(0).describe('Items succeeded'),\n \n /**\n * Failed items\n */\n failed: z.number().int().min(0).default(0).describe('Items failed'),\n \n /**\n * Progress percentage\n */\n percentage: z.number().min(0).max(100).describe('Progress percentage'),\n \n /**\n * Status\n */\n status: z.enum(['pending', 'running', 'completed', 'failed', 'cancelled']).describe('Batch status'),\n \n /**\n * Timestamps\n */\n startedAt: z.string().datetime().optional().describe('When batch started'),\n completedAt: z.string().datetime().optional().describe('When batch completed'),\n});\n\nexport type BatchProgress = z.infer;\nexport type BatchProgressInput = z.input;\n\n// ==========================================\n// Worker Configuration\n// ==========================================\n\n/**\n * Worker Configuration Schema\n * Configuration for a worker instance\n */\nexport const WorkerConfigSchema = z.object({\n /**\n * Worker name\n */\n name: z.string().describe('Worker name'),\n \n /**\n * Queues to process\n */\n queues: z.array(z.string()).min(1).describe('Queue names to process'),\n \n /**\n * Queue configurations\n */\n queueConfigs: z.array(QueueConfigSchema).optional().describe('Queue configurations'),\n \n /**\n * Polling interval\n */\n pollIntervalMs: z.number().int().positive().default(1000).describe('Queue polling interval in milliseconds'),\n \n /**\n * Visibility timeout\n */\n visibilityTimeoutMs: z.number().int().positive().default(30000)\n .describe('How long a task is invisible after being claimed'),\n \n /**\n * Task timeout\n */\n defaultTimeoutMs: z.number().int().positive().default(300000).describe('Default task timeout in milliseconds'),\n \n /**\n * Graceful shutdown timeout\n */\n shutdownTimeoutMs: z.number().int().positive().default(30000)\n .describe('Graceful shutdown timeout in milliseconds'),\n \n /**\n * Task handlers\n */\n handlers: z.record(z.string(), z.function()).optional().describe('Task type handlers'),\n});\n\nexport type WorkerConfig = z.infer;\nexport type WorkerConfigInput = z.input;\n\n// ==========================================\n// Worker Stats\n// ==========================================\n\n/**\n * Worker Stats Schema\n * Runtime statistics for a worker\n */\nexport const WorkerStatsSchema = z.object({\n /**\n * Worker name\n */\n workerName: z.string().describe('Worker name'),\n \n /**\n * Total tasks processed\n */\n totalProcessed: z.number().int().min(0).describe('Total tasks processed'),\n \n /**\n * Successful tasks\n */\n succeeded: z.number().int().min(0).describe('Successful tasks'),\n \n /**\n * Failed tasks\n */\n failed: z.number().int().min(0).describe('Failed tasks'),\n \n /**\n * Active tasks\n */\n active: z.number().int().min(0).describe('Currently active tasks'),\n \n /**\n * Average execution time\n */\n avgExecutionMs: z.number().min(0).optional().describe('Average execution time in milliseconds'),\n \n /**\n * Uptime\n */\n uptimeMs: z.number().int().min(0).describe('Worker uptime in milliseconds'),\n \n /**\n * Queue stats\n */\n queues: z.record(z.string(), z.object({\n pending: z.number().int().min(0).describe('Pending tasks'),\n active: z.number().int().min(0).describe('Active tasks'),\n completed: z.number().int().min(0).describe('Completed tasks'),\n failed: z.number().int().min(0).describe('Failed tasks'),\n })).optional().describe('Per-queue statistics'),\n});\n\nexport type WorkerStats = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create a task\n */\nexport const Task = Object.assign(TaskSchema, {\n create: >(task: T) => task,\n});\n\n/**\n * Helper to create a queue config\n */\nexport const QueueConfig = Object.assign(QueueConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create a worker config\n */\nexport const WorkerConfig = Object.assign(WorkerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create a batch task\n */\nexport const BatchTask = Object.assign(BatchTaskSchema, {\n create: >(batch: T) => batch,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Email Template Schema\n * \n * Defines the structure and content of email notifications.\n * Supports variables for personalization and file attachments.\n * \n * @example\n * ```json\n * {\n * \"id\": \"welcome-email\",\n * \"subject\": \"Welcome to {{company_name}}\",\n * \"body\": \"

Welcome {{user_name}}!

\",\n * \"bodyType\": \"html\",\n * \"variables\": [\"company_name\", \"user_name\"],\n * \"attachments\": [\n * {\n * \"name\": \"guide.pdf\",\n * \"url\": \"https://example.com/guide.pdf\"\n * }\n * ]\n * }\n * ```\n */\nexport const EmailTemplateSchema = z.object({\n /**\n * Unique identifier for the email template\n */\n id: z.string().describe('Template identifier'),\n\n /**\n * Email subject line (supports variable interpolation)\n */\n subject: z.string().describe('Email subject'),\n\n /**\n * Email body content\n */\n body: z.string().describe('Email body content'),\n\n /**\n * Content type of the email body\n * @default 'html'\n */\n bodyType: z.enum(['text', 'html', 'markdown']).optional().default('html').describe('Body content type'),\n\n /**\n * List of template variables for dynamic content\n */\n variables: z.array(z.string()).optional().describe('Template variables'),\n\n /**\n * File attachments to include with the email\n */\n attachments: z.array(z.object({\n name: z.string().describe('Attachment filename'),\n url: z.string().url().describe('Attachment URL'),\n })).optional().describe('Email attachments'),\n});\n\n/**\n * SMS Template Schema\n * \n * Defines the structure of SMS text message notifications.\n * Includes character limits and variable support.\n * \n * @example\n * ```json\n * {\n * \"id\": \"verification-sms\",\n * \"message\": \"Your code is {{code}}\",\n * \"maxLength\": 160,\n * \"variables\": [\"code\"]\n * }\n * ```\n */\nexport const SMSTemplateSchema = z.object({\n /**\n * Unique identifier for the SMS template\n */\n id: z.string().describe('Template identifier'),\n\n /**\n * SMS message content (supports variable interpolation)\n */\n message: z.string().describe('SMS message content'),\n\n /**\n * Maximum character length for the SMS\n * @default 160\n */\n maxLength: z.number().optional().default(160).describe('Maximum message length'),\n\n /**\n * List of template variables for dynamic content\n */\n variables: z.array(z.string()).optional().describe('Template variables'),\n});\n\n/**\n * Push Notification Schema\n * \n * Defines mobile and web push notification structure.\n * Supports rich notifications with actions and badges.\n * \n * @example\n * ```json\n * {\n * \"title\": \"New Message\",\n * \"body\": \"You have a new message from John\",\n * \"icon\": \"https://example.com/icon.png\",\n * \"badge\": 5,\n * \"data\": {\"messageId\": \"msg_123\"},\n * \"actions\": [\n * {\"action\": \"view\", \"title\": \"View\"},\n * {\"action\": \"dismiss\", \"title\": \"Dismiss\"}\n * ]\n * }\n * ```\n */\nexport const PushNotificationSchema = z.object({\n /**\n * Notification title\n */\n title: z.string().describe('Notification title'),\n\n /**\n * Notification body text\n */\n body: z.string().describe('Notification body'),\n\n /**\n * Icon URL to display with notification\n */\n icon: z.string().url().optional().describe('Notification icon URL'),\n\n /**\n * Badge count to display on app icon\n */\n badge: z.number().optional().describe('Badge count'),\n\n /**\n * Custom data payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Custom data'),\n\n /**\n * Action buttons for the notification\n */\n actions: z.array(z.object({\n action: z.string().describe('Action identifier'),\n title: z.string().describe('Action button title'),\n })).optional().describe('Notification actions'),\n});\n\n/**\n * In-App Notification Schema\n * \n * Defines in-application notification banners and toasts.\n * Includes severity levels and auto-dismiss settings.\n * \n * @example\n * ```json\n * {\n * \"title\": \"System Update\",\n * \"message\": \"New features are now available\",\n * \"type\": \"info\",\n * \"actionUrl\": \"/updates\",\n * \"dismissible\": true,\n * \"expiresAt\": 1704067200000\n * }\n * ```\n */\nexport const InAppNotificationSchema = z.object({\n /**\n * Notification title\n */\n title: z.string().describe('Notification title'),\n\n /**\n * Notification message content\n */\n message: z.string().describe('Notification message'),\n\n /**\n * Notification severity type\n */\n type: z.enum(['info', 'success', 'warning', 'error']).describe('Notification type'),\n\n /**\n * Optional URL to navigate to when clicked\n */\n actionUrl: z.string().optional().describe('Action URL'),\n\n /**\n * Whether the notification can be dismissed by the user\n * @default true\n */\n dismissible: z.boolean().optional().default(true).describe('User dismissible'),\n\n /**\n * Timestamp when notification expires (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Expiration timestamp'),\n});\n\n/**\n * Notification Channel Enum\n * \n * Supported notification delivery channels.\n */\nexport const NotificationChannelSchema = z.enum([\n 'email',\n 'sms',\n 'push',\n 'in-app',\n 'slack',\n 'teams',\n 'webhook',\n]);\n\n/**\n * Notification Configuration Schema\n * \n * Unified notification management protocol supporting multiple channels.\n * Includes scheduling, retry policies, and delivery tracking.\n * \n * @example\n * ```json\n * {\n * \"id\": \"welcome-notification\",\n * \"name\": \"Welcome Email\",\n * \"channel\": \"email\",\n * \"template\": {\n * \"id\": \"tpl-001\",\n * \"subject\": \"Welcome!\",\n * \"body\": \"

Welcome

\",\n * \"bodyType\": \"html\"\n * },\n * \"recipients\": {\n * \"to\": [\"user@example.com\"],\n * \"cc\": [\"admin@example.com\"]\n * },\n * \"schedule\": {\n * \"type\": \"immediate\"\n * },\n * \"retryPolicy\": {\n * \"enabled\": true,\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * },\n * \"tracking\": {\n * \"trackOpens\": true,\n * \"trackClicks\": true,\n * \"trackDelivery\": true\n * }\n * }\n * ```\n */\nexport const NotificationConfigSchema = z.object({\n /**\n * Unique identifier for this notification configuration\n */\n id: z.string().describe('Notification ID'),\n\n /**\n * Human-readable name for this notification\n */\n name: z.string().describe('Notification name'),\n\n /**\n * Delivery channel for the notification\n */\n channel: NotificationChannelSchema.describe('Notification channel'),\n\n /**\n * Notification template based on channel type\n */\n template: z.union([\n EmailTemplateSchema,\n SMSTemplateSchema,\n PushNotificationSchema,\n InAppNotificationSchema,\n ]).describe('Notification template'),\n\n /**\n * Recipient configuration\n */\n recipients: z.object({\n /**\n * Primary recipients\n */\n to: z.array(z.string()).describe('Primary recipients'),\n\n /**\n * CC recipients (email only)\n */\n cc: z.array(z.string()).optional().describe('CC recipients'),\n\n /**\n * BCC recipients (email only)\n */\n bcc: z.array(z.string()).optional().describe('BCC recipients'),\n }).describe('Recipients'),\n\n /**\n * Scheduling configuration\n */\n schedule: z.object({\n /**\n * Scheduling type\n */\n type: z.enum(['immediate', 'delayed', 'scheduled']).describe('Schedule type'),\n\n /**\n * Delay in milliseconds (for delayed type)\n */\n delay: z.number().optional().describe('Delay in milliseconds'),\n\n /**\n * Scheduled send time (Unix timestamp in milliseconds)\n */\n scheduledAt: z.number().optional().describe('Scheduled timestamp'),\n }).optional().describe('Scheduling'),\n\n /**\n * Retry policy for failed deliveries\n */\n retryPolicy: z.object({\n /**\n * Enable automatic retries\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Enable retries'),\n\n /**\n * Maximum number of retry attempts\n * @default 3\n */\n maxRetries: z.number().optional().default(3).describe('Max retry attempts'),\n\n /**\n * Backoff strategy for retries\n */\n backoffStrategy: z.enum(['exponential', 'linear', 'fixed']).describe('Backoff strategy'),\n }).optional().describe('Retry policy'),\n\n /**\n * Delivery tracking configuration\n */\n tracking: z.object({\n /**\n * Track when emails are opened\n * @default false\n */\n trackOpens: z.boolean().optional().default(false).describe('Track opens'),\n\n /**\n * Track when links are clicked\n * @default false\n */\n trackClicks: z.boolean().optional().default(false).describe('Track clicks'),\n\n /**\n * Track delivery status\n * @default true\n */\n trackDelivery: z.boolean().optional().default(true).describe('Track delivery'),\n }).optional().describe('Tracking configuration'),\n});\n\n// Type exports\nexport type NotificationConfig = z.infer;\nexport type NotificationChannel = z.infer;\nexport type EmailTemplate = z.infer;\nexport type SMSTemplate = z.infer;\nexport type PushNotification = z.infer;\nexport type InAppNotification = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const LocaleSchema = z.string().describe('BCP-47 Language Tag (e.g. en-US, zh-CN)');\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-level Translation (per-object file)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Field Translation Schema\n * Translation data for a single field.\n */\nexport const FieldTranslationSchema = z.object({\n label: z.string().optional().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n placeholder: z.string().optional().describe('Translated placeholder text for form inputs'),\n options: z.record(z.string(), z.string()).optional().describe('Option value to translated label map'),\n}).describe('Translation data for a single field');\n\nexport type FieldTranslation = z.infer;\n\n/**\n * Object Translation Data Schema\n *\n * Translation data for a **single object** in a **single locale**.\n * Use this schema to validate per-object translation files.\n *\n * File convention: `i18n/{locale}/{object_name}.json`\n *\n * @example\n * ```json\n * // i18n/en/account.json\n * {\n * \"label\": \"Account\",\n * \"pluralLabel\": \"Accounts\",\n * \"fields\": {\n * \"name\": { \"label\": \"Account Name\", \"help\": \"Legal name\" },\n * \"type\": { \"label\": \"Type\", \"options\": { \"customer\": \"Customer\" } }\n * }\n * }\n * ```\n */\nexport const ObjectTranslationDataSchema = z.object({\n /** Translated singular label for the object */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label for the object */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional().describe('Field-level translations'),\n}).describe('Translation data for a single object');\n\nexport type ObjectTranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale-level Translation Data (per-locale aggregate)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Data Schema\n * Supports i18n for labels, messages, and options within a single locale.\n * Example structure:\n * ```json\n * {\n * \"objects\": { \"account\": { \"label\": \"Account\" } },\n * \"apps\": { \"crm\": { \"label\": \"CRM\" } },\n * \"messages\": { \"common.save\": \"Save\" }\n * }\n * ```\n */\nexport const TranslationDataSchema = z.object({\n /** Object translations */\n objects: z.record(z.string(), ObjectTranslationDataSchema).optional().describe('Object translations keyed by object name'),\n \n /** App/Menu translations */\n apps: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** UI Messages */\n messages: z.record(z.string(), z.string()).optional().describe('UI message translations keyed by message ID'),\n \n /** Validation Error Messages */\n validationMessages: z.record(z.string(), z.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {\"discount_limit\": \"折扣不能超过40%\"})'),\n}).describe('Translation data for objects, apps, and UI messages');\n\nexport type TranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Bundle (all locales)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const TranslationBundleSchema = z.record(LocaleSchema, TranslationDataSchema).describe('Map of locale codes to translation data');\n\nexport type TranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// File Organization Convention\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation File Organization Strategy\n *\n * Defines how translation files are organized on disk.\n *\n * - `bundled` — All locales in a single `TranslationBundle` file.\n * Best for small projects with few objects.\n * ```\n * src/translations/\n * crm.translation.ts # { en: {...}, \"zh-CN\": {...} }\n * ```\n *\n * - `per_locale` — One file per locale containing all namespaces.\n * Recommended when a single locale file stays under ~500 lines.\n * ```\n * src/translations/\n * en.ts # TranslationData for English\n * zh-CN.ts # TranslationData for Chinese\n * ```\n *\n * - `per_namespace` — One file per namespace (object) per locale.\n * Recommended for large projects with many objects/languages.\n * Aligns with Salesforce DX and ServiceNow conventions.\n * ```\n * i18n/\n * en/\n * account.json # ObjectTranslationData\n * contact.json\n * common.json # messages + app labels\n * zh-CN/\n * account.json\n * contact.json\n * common.json\n * ```\n */\nexport const TranslationFileOrganizationSchema = z.enum([\n 'bundled',\n 'per_locale',\n 'per_namespace',\n]).describe('Translation file organization strategy');\n\nexport type TranslationFileOrganization = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Configuration\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Configuration Schema\n *\n * Defines internationalization settings for the stack.\n *\n * @example\n * ```typescript\n * export default defineStack({\n * i18n: {\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'zh-CN', 'ja-JP'],\n * fallbackLocale: 'en',\n * fileOrganization: 'per_locale',\n * },\n * translations: [...],\n * });\n * ```\n */\n/**\n * Message format standard used for interpolation, pluralization, and\n * gender-aware translations.\n *\n * - `icu` — ICU MessageFormat (recommended for complex plurals, gender, select).\n * Strings may contain `{count, plural, one {# item} other {# items}}` patterns.\n * - `simple` — Simple `{variable}` interpolation only (default).\n */\nexport const MessageFormatSchema = z.enum([\n 'icu',\n 'simple',\n]).describe('Message interpolation format: ICU MessageFormat or simple {variable} replacement');\n\nexport type MessageFormat = z.infer;\n\nexport const TranslationConfigSchema = z.object({\n /** Default locale for the application */\n defaultLocale: LocaleSchema.describe('Default locale (e.g., \"en\")'),\n /** Supported BCP-47 locale codes */\n supportedLocales: z.array(LocaleSchema).describe('Supported BCP-47 locale codes'),\n /** Fallback locale when translation is not found */\n fallbackLocale: LocaleSchema.optional().describe('Fallback locale code'),\n /** How translation files are organized on disk */\n fileOrganization: TranslationFileOrganizationSchema.default('per_locale')\n .describe('File organization strategy'),\n /**\n * Message interpolation format.\n * When set to `'icu'`, messages and validationMessages are expected to use\n * ICU MessageFormat syntax (plurals, select, number/date skeletons).\n * @default 'simple'\n */\n messageFormat: MessageFormatSchema.default('simple')\n .describe('Message interpolation format (ICU MessageFormat or simple)'),\n /** Load translations on demand instead of eagerly */\n lazyLoad: z.boolean().default(false).describe('Load translations on demand'),\n /** Cache loaded translations in memory */\n cache: z.boolean().default(true).describe('Cache loaded translations'),\n}).describe('Internationalization configuration');\n\nexport type TranslationConfig = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-First Translation Node (object-first aggregated structure)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Translatable option map: option value → translated label */\nconst OptionTranslationMapSchema = z.record(z.string(), z.string())\n .describe('Option value to translated label map');\n\n/**\n * ObjectTranslationNodeSchema\n *\n * Object-first aggregated translation node that groups **all** translatable\n * content for a single object under one key. Aligns with Salesforce / Dynamics\n * conventions where translations are organized per-object rather than per-category.\n *\n * Located at `o.{object_name}` inside an {@link AppTranslationBundle}.\n *\n * @example\n * ```typescript\n * const accountNode: ObjectTranslationNode = {\n * label: '客户',\n * pluralLabel: '客户',\n * description: '客户管理对象',\n * fields: {\n * name: { label: '客户名称', help: '公司或组织的法定名称' },\n * industry: { label: '行业', options: { tech: '科技', finance: '金融' } },\n * },\n * _options: { status: { active: '活跃', inactive: '停用' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: {\n * convert_lead: { label: '转换线索', confirmMessage: '确认转换?' },\n * },\n * };\n * ```\n */\nexport const ObjectTranslationNodeSchema = z.object({\n /** Translated singular label */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Translated object description */\n description: z.string().optional().describe('Translated object description'),\n /** Translated help text shown in tooltips or guidance panels */\n helpText: z.string().optional().describe('Translated help text for the object'),\n\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional()\n .describe('Field translations keyed by field name'),\n\n /**\n * Global picklist / select option overrides scoped to this object.\n * Keyed by field name → { optionValue: translatedLabel }.\n */\n _options: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Object-scoped picklist option translations keyed by field name'),\n\n /** View translations keyed by view name */\n _views: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated view label'),\n description: z.string().optional().describe('Translated view description'),\n })).optional().describe('View translations keyed by view name'),\n\n /** Section (form section / tab) translations keyed by section name */\n _sections: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated section label'),\n })).optional().describe('Section translations keyed by section name'),\n\n /** Action translations keyed by action name */\n _actions: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated action label'),\n confirmMessage: z.string().optional().describe('Translated confirmation message'),\n })).optional().describe('Action translations keyed by action name'),\n\n /** Notification message translations keyed by notification name */\n _notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Notification translations keyed by notification name'),\n\n /** Error message translations keyed by error code */\n _errors: z.record(z.string(), z.string()).optional()\n .describe('Error message translations keyed by error code'),\n}).describe('Object-first aggregated translation node');\n\nexport type ObjectTranslationNode = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// App Translation Bundle (object-first, full application)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * AppTranslationBundleSchema\n *\n * Complete application translation bundle for a **single locale** using\n * the **object-first** convention. All per-object translatable content\n * is aggregated under `o.{object_name}`, while global (non-object-bound)\n * translations are kept in dedicated top-level groups.\n *\n * This schema is designed for:\n * - Translation workbench UIs (object-level editing & coverage)\n * - CLI skeleton generation (`objectstack i18n extract`)\n * - Automated diff/coverage detection\n *\n * @example\n * ```typescript\n * const zh: AppTranslationBundle = {\n * o: {\n * account: {\n * label: '客户',\n * fields: { name: { label: '客户名称' } },\n * _options: { industry: { tech: '科技' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: { convert: { label: '转换' } },\n * },\n * },\n * _globalOptions: { currency: { usd: '美元', eur: '欧元' } },\n * app: { crm: { label: '客户关系管理', description: '管理销售流程' } },\n * nav: { home: '首页', settings: '设置' },\n * dashboard: { sales_overview: { label: '销售概览' } },\n * reports: { pipeline_report: { label: '管道报表' } },\n * pages: { landing: { title: '欢迎' } },\n * messages: { 'common.save': '保存' },\n * validationMessages: { 'discount_limit': '折扣不能超过40%' },\n * };\n * ```\n */\nexport const AppTranslationBundleSchema = z.object({\n /**\n * Bundle-level metadata.\n * Provides locale-aware rendering hints such as text direction (bidi)\n * and the canonical locale code this bundle represents.\n */\n _meta: z.object({\n /** BCP-47 locale code this bundle represents */\n locale: z.string().optional().describe('BCP-47 locale code for this bundle'),\n /** Text direction for the locale */\n direction: z.enum(['ltr', 'rtl']).optional().describe('Text direction: left-to-right or right-to-left'),\n }).optional().describe('Bundle-level metadata (locale, bidi direction)'),\n\n /**\n * Namespace for plugin/extension isolation.\n * When multiple plugins contribute translations, each should use a unique\n * namespace to avoid key collisions (e.g. \"crm\", \"helpdesk\", \"plugin-xyz\").\n */\n namespace: z.string().optional()\n .describe('Namespace for plugin isolation to avoid translation key collisions'),\n\n /** Object-first translations keyed by object name (snake_case) */\n o: z.record(z.string(), ObjectTranslationNodeSchema).optional()\n .describe('Object-first translations keyed by object name'),\n\n /** Global picklist options not bound to any specific object */\n _globalOptions: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Global picklist option translations keyed by option set name'),\n\n /** App-level translations */\n app: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** Navigation menu translations */\n nav: z.record(z.string(), z.string()).optional()\n .describe('Navigation item translations keyed by nav item name'),\n\n /** Dashboard translations keyed by dashboard name */\n dashboard: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated dashboard label'),\n description: z.string().optional().describe('Translated dashboard description'),\n })).optional().describe('Dashboard translations keyed by dashboard name'),\n\n /** Report translations keyed by report name */\n reports: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated report label'),\n description: z.string().optional().describe('Translated report description'),\n })).optional().describe('Report translations keyed by report name'),\n\n /** Page translations keyed by page name */\n pages: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated page title'),\n description: z.string().optional().describe('Translated page description'),\n })).optional().describe('Page translations keyed by page name'),\n\n /** UI message translations (supports ICU MessageFormat when enabled) */\n messages: z.record(z.string(), z.string()).optional()\n .describe('UI message translations keyed by message ID (supports ICU MessageFormat)'),\n\n /** Validation error message translations (supports ICU MessageFormat when enabled) */\n validationMessages: z.record(z.string(), z.string()).optional()\n .describe('Validation error message translations keyed by rule name (supports ICU MessageFormat)'),\n\n /** Global notification translations not bound to a specific object */\n notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Global notification translations keyed by notification name'),\n\n /** Global error message translations not bound to a specific object */\n errors: z.record(z.string(), z.string()).optional()\n .describe('Global error message translations keyed by error code'),\n}).describe('Object-first application translation bundle for a single locale');\n\nexport type AppTranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Diff & Coverage\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Diff Status\n *\n * Status of a single translation entry compared to the source metadata.\n */\nexport const TranslationDiffStatusSchema = z.enum([\n 'missing',\n 'redundant',\n 'stale',\n]).describe('Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)');\n\nexport type TranslationDiffStatus = z.infer;\n\n/**\n * TranslationDiffItemSchema\n *\n * Describes a single translation key that is missing, redundant, or stale\n * relative to the source metadata. Used by CLI/API diff detection.\n *\n * @example\n * ```typescript\n * const item: TranslationDiffItem = {\n * key: 'o.account.fields.website.label',\n * status: 'missing',\n * objectName: 'account',\n * locale: 'zh-CN',\n * };\n * ```\n */\nexport const TranslationDiffItemSchema = z.object({\n /** Dot-path translation key (e.g. \"o.account.fields.website.label\") */\n key: z.string().describe('Dot-path translation key'),\n /** Diff status */\n status: TranslationDiffStatusSchema.describe('Diff status of this translation key'),\n /** Object name if the key belongs to an object translation node */\n objectName: z.string().optional().describe('Associated object name (snake_case)'),\n /** Locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /**\n * Hash of the source metadata value at the time the translation was made.\n * Used by CLI/Workbench to detect stale translations without a full diff.\n */\n sourceHash: z.string().optional().describe('Hash of source metadata for precise stale detection'),\n /**\n * AI-suggested translation text for missing or stale entries.\n * Populated by AI translation hooks or TMS integrations.\n */\n aiSuggested: z.string().optional().describe('AI-suggested translation for this key'),\n /** Confidence score (0-1) for the AI suggestion */\n aiConfidence: z.number().min(0).max(1).optional().describe('AI suggestion confidence score (0–1)'),\n}).describe('A single translation diff item');\n\nexport type TranslationDiffItem = z.infer;\n\n/**\n * TranslationCoverageResultSchema\n *\n * Aggregated coverage result for a locale, optionally scoped to a single object.\n * Returned by the i18n diff detection API.\n *\n * @example\n * ```typescript\n * const result: TranslationCoverageResult = {\n * locale: 'zh-CN',\n * totalKeys: 120,\n * translatedKeys: 105,\n * missingKeys: 12,\n * redundantKeys: 3,\n * staleKeys: 0,\n * coveragePercent: 87.5,\n * items: [ ... ],\n * };\n * ```\n */\n/**\n * Per-group coverage breakdown entry.\n */\nexport const CoverageBreakdownEntrySchema = z.object({\n /** Group category (e.g. \"fields\", \"views\", \"actions\", \"messages\") */\n group: z.string().describe('Translation group category'),\n /** Total translatable keys in this group */\n totalKeys: z.number().int().nonnegative().describe('Total keys in this group'),\n /** Number of translated keys in this group */\n translatedKeys: z.number().int().nonnegative().describe('Translated keys in this group'),\n /** Coverage percentage for this group */\n coveragePercent: z.number().min(0).max(100).describe('Coverage percentage for this group'),\n}).describe('Coverage breakdown for a single translation group');\n\nexport type CoverageBreakdownEntry = z.infer;\n\nexport const TranslationCoverageResultSchema = z.object({\n /** BCP-47 locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /** Optional object name scope */\n objectName: z.string().optional().describe('Object name scope (omit for full bundle)'),\n /** Total translatable keys derived from metadata */\n totalKeys: z.number().int().nonnegative().describe('Total translatable keys from metadata'),\n /** Number of keys that have a translation */\n translatedKeys: z.number().int().nonnegative().describe('Number of translated keys'),\n /** Number of missing translations */\n missingKeys: z.number().int().nonnegative().describe('Number of missing translations'),\n /** Number of redundant (orphaned) translations */\n redundantKeys: z.number().int().nonnegative().describe('Number of redundant translations'),\n /** Number of stale translations */\n staleKeys: z.number().int().nonnegative().describe('Number of stale translations'),\n /** Coverage percentage (0-100) */\n coveragePercent: z.number().min(0).max(100).describe('Translation coverage percentage'),\n /** Individual diff items */\n items: z.array(TranslationDiffItemSchema).describe('Detailed diff items'),\n /**\n * Per-group coverage breakdown for translation project management.\n * Each entry represents a logical group (e.g. \"fields\", \"views\", \"actions\",\n * \"messages\") with its own coverage statistics.\n */\n breakdown: z.array(CoverageBreakdownEntrySchema).optional()\n .describe('Per-group coverage breakdown'),\n}).describe('Aggregated translation coverage result');\n\nexport type TranslationCoverageResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Translation Skeleton Protocol Constants\n *\n * Defines the placeholder convention used in AI-friendly translation\n * skeleton templates. Runtime implementations (skeleton generation,\n * validation) belong in implementation packages (CLI, service-i18n, etc.).\n *\n * @example\n * ```json\n * {\n * \"label\": \"__TRANSLATE__: \\\"Task\\\"\",\n * \"fields\": {\n * \"subject\": { \"label\": \"__TRANSLATE__: \\\"Subject\\\"\" }\n * }\n * }\n * ```\n */\n\n/** Placeholder prefix used in translation skeleton output */\nexport const TRANSLATE_PLACEHOLDER = '__TRANSLATE__';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Real-Time Collaboration Protocol\n * \n * Defines schemas for real-time collaborative editing in ObjectStack.\n * Supports Operational Transformation (OT), CRDT (Conflict-free Replicated Data Types),\n * cursor sharing, and awareness state for collaborative applications.\n * \n * Industry alignment: Google Docs, Figma, VSCode Live Share, Yjs\n */\n\n// ==========================================\n// Operational Transformation (OT)\n// ==========================================\n\n/**\n * OT Operation Type Enum\n * Types of operations in Operational Transformation\n */\nexport const OTOperationType = z.enum([\n 'insert', // Insert characters at position\n 'delete', // Delete characters at position\n 'retain', // Keep characters (used for composing operations)\n]);\n\nexport type OTOperationType = z.infer;\n\n/**\n * OT Operation Component\n * Single component of an OT operation\n */\nexport const OTComponentSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('insert'),\n text: z.string().describe('Text to insert'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Text formatting attributes (e.g., bold, italic)'),\n }),\n z.object({\n type: z.literal('delete'),\n count: z.number().int().positive().describe('Number of characters to delete'),\n }),\n z.object({\n type: z.literal('retain'),\n count: z.number().int().positive().describe('Number of characters to retain'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Attribute changes to apply'),\n }),\n]);\n\nexport type OTComponent = z.infer;\n\n/**\n * OT Operation Schema\n * Represents a complete OT operation\n * Based on the OT algorithm used by Google Docs and other collaborative editors\n */\nexport const OTOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n documentId: z.string().describe('Document identifier'),\n userId: z.string().describe('User who created the operation'),\n sessionId: z.string().uuid().describe('Session identifier'),\n components: z.array(OTComponentSchema).describe('Operation components'),\n baseVersion: z.number().int().nonnegative().describe('Document version this operation is based on'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional operation metadata'),\n});\n\nexport type OTOperation = z.infer;\n\n/**\n * OT Transform Result\n * Result of transforming one operation against another\n */\nexport const OTTransformResultSchema = z.object({\n operation: OTOperationSchema.describe('Transformed operation'),\n transformed: z.boolean().describe('Whether transformation was applied'),\n conflicts: z.array(z.string()).optional().describe('Conflict descriptions if any'),\n});\n\nexport type OTTransformResult = z.infer;\n\n// ==========================================\n// CRDT (Conflict-free Replicated Data Types)\n// ==========================================\n\n/**\n * CRDT Type Enum\n * Types of CRDTs supported\n */\nexport const CRDTType = z.enum([\n 'lww-register', // Last-Write-Wins Register\n 'g-counter', // Grow-only Counter\n 'pn-counter', // Positive-Negative Counter\n 'g-set', // Grow-only Set\n 'or-set', // Observed-Remove Set\n 'lww-map', // Last-Write-Wins Map\n 'text', // CRDT-based Text (e.g., Yjs, Automerge)\n 'tree', // CRDT-based Tree structure\n 'json', // CRDT-based JSON (e.g., Automerge)\n]);\n\nexport type CRDTType = z.infer;\n\n/**\n * Vector Clock Schema\n * Tracks causality in distributed systems\n */\nexport const VectorClockSchema = z.object({\n clock: z.record(z.string(), z.number().int().nonnegative()).describe('Map of replica ID to logical timestamp'),\n});\n\nexport type VectorClock = z.infer;\n\n/**\n * LWW-Register Schema\n * Last-Write-Wins Register CRDT\n */\nexport const LWWRegisterSchema = z.object({\n type: z.literal('lww-register'),\n value: z.unknown().describe('Current register value'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of last write'),\n replicaId: z.string().describe('ID of replica that performed last write'),\n vectorClock: VectorClockSchema.optional().describe('Optional vector clock for causality tracking'),\n});\n\nexport type LWWRegister = z.infer;\n\n/**\n * Counter Operation Schema\n * Operations for Counter CRDTs\n */\nexport const CounterOperationSchema = z.object({\n replicaId: z.string().describe('Replica identifier'),\n delta: z.number().int().describe('Change amount (positive for increment, negative for decrement)'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of operation'),\n});\n\nexport type CounterOperation = z.infer;\n\n/**\n * G-Counter Schema\n * Grow-only Counter CRDT\n */\nexport const GCounterSchema = z.object({\n type: z.literal('g-counter'),\n counts: z.record(z.string(), z.number().int().nonnegative()).describe('Map of replica ID to count'),\n});\n\nexport type GCounter = z.infer;\n\n/**\n * PN-Counter Schema\n * Positive-Negative Counter CRDT (supports increment and decrement)\n */\nexport const PNCounterSchema = z.object({\n type: z.literal('pn-counter'),\n positive: z.record(z.string(), z.number().int().nonnegative()).describe('Positive increments per replica'),\n negative: z.record(z.string(), z.number().int().nonnegative()).describe('Negative increments per replica'),\n});\n\nexport type PNCounter = z.infer;\n\n/**\n * OR-Set Element Schema\n * Element in an Observed-Remove Set\n */\nexport const ORSetElementSchema = z.object({\n value: z.unknown().describe('Element value'),\n timestamp: z.string().datetime().describe('Addition timestamp'),\n replicaId: z.string().describe('Replica that added the element'),\n uid: z.string().uuid().describe('Unique identifier for this addition'),\n removed: z.boolean().optional().default(false).describe('Whether element has been removed'),\n});\n\nexport type ORSetElement = z.infer;\n\n/**\n * OR-Set Schema\n * Observed-Remove Set CRDT\n */\nexport const ORSetSchema = z.object({\n type: z.literal('or-set'),\n elements: z.array(ORSetElementSchema).describe('Set elements with metadata'),\n});\n\nexport type ORSet = z.infer;\n\n/**\n * Text CRDT Operation Schema\n * Operations for text-based CRDTs (e.g., Yjs, Automerge)\n */\nexport const TextCRDTOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n replicaId: z.string().describe('Replica identifier'),\n position: z.number().int().nonnegative().describe('Position in document'),\n insert: z.string().optional().describe('Text to insert'),\n delete: z.number().int().positive().optional().describe('Number of characters to delete'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of operation'),\n lamportTimestamp: z.number().int().nonnegative().describe('Lamport timestamp for ordering'),\n});\n\nexport type TextCRDTOperation = z.infer;\n\n/**\n * Text CRDT State Schema\n * State of a text-based CRDT document\n */\nexport const TextCRDTStateSchema = z.object({\n type: z.literal('text'),\n documentId: z.string().describe('Document identifier'),\n content: z.string().describe('Current text content'),\n operations: z.array(TextCRDTOperationSchema).describe('History of operations'),\n lamportClock: z.number().int().nonnegative().describe('Current Lamport clock value'),\n vectorClock: VectorClockSchema.describe('Vector clock for causality'),\n});\n\nexport type TextCRDTState = z.infer;\n\n/**\n * CRDT State Union\n * Discriminated union of all CRDT types\n */\nexport const CRDTStateSchema = z.discriminatedUnion('type', [\n LWWRegisterSchema,\n GCounterSchema,\n PNCounterSchema,\n ORSetSchema,\n TextCRDTStateSchema,\n]);\n\nexport type CRDTState = z.infer;\n\n/**\n * CRDT Merge Schema\n * Result of merging two CRDT states\n */\nexport const CRDTMergeResultSchema = z.object({\n state: CRDTStateSchema.describe('Merged CRDT state'),\n conflicts: z.array(z.object({\n type: z.string().describe('Conflict type'),\n description: z.string().describe('Conflict description'),\n resolved: z.boolean().describe('Whether conflict was automatically resolved'),\n })).optional().describe('Conflicts encountered during merge'),\n});\n\nexport type CRDTMergeResult = z.infer;\n\n// ==========================================\n// Cursor Sharing\n// ==========================================\n\n/**\n * Cursor Color Preset Enum\n * Standard color presets for cursor visualization\n */\nexport const CursorColorPreset = z.enum([\n 'blue',\n 'green',\n 'red',\n 'yellow',\n 'purple',\n 'orange',\n 'pink',\n 'teal',\n 'indigo',\n 'cyan',\n]);\n\nexport type CursorColorPreset = z.infer;\n\n/**\n * Cursor Style Schema\n * Visual styling for collaborative cursors\n */\nexport const CursorStyleSchema = z.object({\n color: z.union([CursorColorPreset, z.string()]).describe('Cursor color (preset or custom hex)'),\n opacity: z.number().min(0).max(1).optional().default(1).describe('Cursor opacity (0-1)'),\n label: z.string().optional().describe('Label to display with cursor (usually username)'),\n showLabel: z.boolean().optional().default(true).describe('Whether to show label'),\n pulseOnUpdate: z.boolean().optional().default(true).describe('Whether to pulse when cursor moves'),\n});\n\nexport type CursorStyle = z.infer;\n\n/**\n * Cursor Selection Schema\n * Represents a text selection in collaborative editing\n */\nexport const CursorSelectionSchema = z.object({\n anchor: z.object({\n line: z.number().int().nonnegative().describe('Anchor line number'),\n column: z.number().int().nonnegative().describe('Anchor column number'),\n }).describe('Selection anchor (start point)'),\n focus: z.object({\n line: z.number().int().nonnegative().describe('Focus line number'),\n column: z.number().int().nonnegative().describe('Focus column number'),\n }).describe('Selection focus (end point)'),\n direction: z.enum(['forward', 'backward']).optional().describe('Selection direction'),\n});\n\nexport type CursorSelection = z.infer;\n\n/**\n * Collaborative Cursor Schema\n * Complete cursor state for a collaborative user\n */\nexport const CollaborativeCursorSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier'),\n userName: z.string().describe('Display name of user'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Cursor line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Cursor column number (0-indexed)'),\n }).describe('Current cursor position'),\n selection: CursorSelectionSchema.optional().describe('Current text selection'),\n style: CursorStyleSchema.describe('Visual style for this cursor'),\n isTyping: z.boolean().optional().default(false).describe('Whether user is currently typing'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional cursor metadata'),\n});\n\nexport type CollaborativeCursor = z.infer;\n\n/**\n * Cursor Update Schema\n * Update to a collaborative cursor\n */\nexport const CursorUpdateSchema = z.object({\n position: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }).optional().describe('Updated cursor position'),\n selection: CursorSelectionSchema.optional().describe('Updated selection'),\n isTyping: z.boolean().optional().describe('Updated typing state'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type CursorUpdate = z.infer;\n\n// ==========================================\n// Awareness State\n// ==========================================\n\n/**\n * User Activity Status Enum\n * User activity status for awareness\n */\nexport const UserActivityStatus = z.enum([\n 'active', // User is actively editing\n 'idle', // User is idle but connected\n 'viewing', // User is viewing but not editing\n 'disconnected', // User is disconnected\n]);\n\nexport type UserActivityStatus = z.infer;\n\n/**\n * Awareness User State Schema\n * Tracks what a user is doing in the collaborative session\n */\nexport const AwarenessUserStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n userName: z.string().describe('Display name'),\n userAvatar: z.string().optional().describe('User avatar URL'),\n status: UserActivityStatus.describe('Current activity status'),\n currentDocument: z.string().optional().describe('Document ID user is currently editing'),\n currentView: z.string().optional().describe('Current view/page user is on'),\n lastActivity: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n joinedAt: z.string().datetime().describe('ISO 8601 datetime when user joined session'),\n permissions: z.array(z.string()).optional().describe('User permissions in this session'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional user state metadata'),\n});\n\nexport type AwarenessUserState = z.infer;\n\n/**\n * Awareness Session Schema\n * Represents the complete awareness state for a collaboration session\n */\nexport const AwarenessSessionSchema = z.object({\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().optional().describe('Document ID this session is for'),\n users: z.array(AwarenessUserStateSchema).describe('Active users in session'),\n startedAt: z.string().datetime().describe('ISO 8601 datetime when session started'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last update'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Session metadata'),\n});\n\nexport type AwarenessSession = z.infer;\n\n/**\n * Awareness Update Schema\n * Update to awareness state\n */\nexport const AwarenessUpdateSchema = z.object({\n status: UserActivityStatus.optional().describe('Updated status'),\n currentDocument: z.string().optional().describe('Updated current document'),\n currentView: z.string().optional().describe('Updated current view'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type AwarenessUpdate = z.infer;\n\n/**\n * Awareness Event Schema\n * Events that occur in awareness tracking\n */\nexport const AwarenessEventSchema = z.object({\n eventId: z.string().uuid().describe('Event identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n eventType: z.enum([\n 'user.joined',\n 'user.left',\n 'user.updated',\n 'session.created',\n 'session.ended',\n ]).describe('Type of awareness event'),\n userId: z.string().optional().describe('User involved in event'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of event'),\n payload: z.unknown().describe('Event payload'),\n});\n\nexport type AwarenessEvent = z.infer;\n\n// ==========================================\n// Collaboration Session Management\n// ==========================================\n\n/**\n * Collaboration Mode Enum\n * Types of collaboration modes\n */\nexport const CollaborationMode = z.enum([\n 'ot', // Operational Transformation\n 'crdt', // CRDT-based\n 'lock', // Pessimistic locking (turn-based)\n 'hybrid', // Hybrid approach\n]);\n\nexport type CollaborationMode = z.infer;\n\n/**\n * Collaboration Session Config\n * Configuration for a collaboration session\n */\nexport const CollaborationSessionConfigSchema = z.object({\n mode: CollaborationMode.describe('Collaboration mode to use'),\n enableCursorSharing: z.boolean().optional().default(true).describe('Enable cursor sharing'),\n enablePresence: z.boolean().optional().default(true).describe('Enable presence tracking'),\n enableAwareness: z.boolean().optional().default(true).describe('Enable awareness state'),\n maxUsers: z.number().int().positive().optional().describe('Maximum concurrent users'),\n idleTimeout: z.number().int().positive().optional().default(300000).describe('Idle timeout in milliseconds'),\n conflictResolution: z.enum(['ot', 'crdt', 'manual']).optional().default('ot').describe('Conflict resolution strategy'),\n persistence: z.boolean().optional().default(true).describe('Enable operation persistence'),\n snapshot: z.object({\n enabled: z.boolean().describe('Enable periodic snapshots'),\n interval: z.number().int().positive().describe('Snapshot interval in milliseconds'),\n }).optional().describe('Snapshot configuration'),\n});\n\nexport type CollaborationSessionConfig = z.infer;\n\n/**\n * Collaboration Session Schema\n * Complete collaboration session state\n */\nexport const CollaborationSessionSchema = z.object({\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier'),\n config: CollaborationSessionConfigSchema.describe('Session configuration'),\n users: z.array(AwarenessUserStateSchema).describe('Active users'),\n cursors: z.array(CollaborativeCursorSchema).describe('Active cursors'),\n version: z.number().int().nonnegative().describe('Current document version'),\n operations: z.array(z.union([OTOperationSchema, TextCRDTOperationSchema])).optional().describe('Recent operations'),\n createdAt: z.string().datetime().describe('ISO 8601 datetime when session was created'),\n lastActivity: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n status: z.enum(['active', 'idle', 'ended']).describe('Session status'),\n});\n\nexport type CollaborationSession = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metadata Scope Enum\n * Defines the lifecycle and mutability of a metadata item.\n */\nexport const MetadataScopeSchema = z.enum([\n 'system', // Defined in Code (Files). Read-only at runtime. Upgraded via deployment.\n 'platform', // Defined in DB (Global). admin-configured. Overrides system.\n 'user', // Defined in DB (Personal). User-configured. Overrides platform/system.\n]);\n\n/**\n * Metadata Lifecycle State\n */\nexport const MetadataStateSchema = z.enum([\n 'draft', // Work in progress, not active\n 'active', // Live and running\n 'archived', // Soft deleted\n 'deprecated' // Running but flagged for removal\n]);\n\n/**\n * Unified Metadata Persistence Protocol\n * \n * Defines the standardized envelope for storing ANY metadata item (Object, View, Flow)\n * in the database (e.g. `_framework_metadata` or generic `metadata` table).\n * \n * This treats \"Metadata as Data\".\n */\nexport const MetadataRecordSchema = z.object({\n /** Primary Key (UUID) */\n id: z.string(),\n \n /** \n * Machine Name \n * The unique identifier used in code references (e.g. \"account_list_view\").\n */\n name: z.string(),\n \n /**\n * Metadata Type\n * e.g. \"object\", \"view\", \"permission_set\", \"flow\"\n */\n type: z.string(),\n \n /**\n * Namespace / Module\n * Groups metadata into packages (e.g. \"crm\", \"finance\", \"core\").\n */\n namespace: z.string().default('default'),\n\n /**\n * Package Ownership Reference\n * Links this metadata record to the package that delivered it.\n * When set, the record is \"managed\" by the package and should not be\n * directly edited — customizations go through the overlay system.\n * Null/undefined means the record was created independently (not from a package).\n */\n packageId: z.string().optional().describe('Package ID that owns/delivered this metadata'),\n\n /**\n * Managed By Indicator\n * Determines who controls this metadata record's lifecycle.\n * - \"package\": Delivered and upgraded by a plugin package (read-only base)\n * - \"platform\": Created by platform admin via UI\n * - \"user\": Created by end user\n */\n managedBy: z.enum(['package', 'platform', 'user']).optional()\n .describe('Who manages this metadata record lifecycle'),\n \n /**\n * Ownership differentiation\n */\n scope: MetadataScopeSchema.default('platform'),\n \n /**\n * The Payload\n * Stores the actual configuration JSON.\n * This field holds the value of `ViewSchema`, `ObjectSchema`, etc.\n */\n metadata: z.record(z.string(), z.unknown()),\n\n /**\n * Extension / Merge Strategy\n * If this record overrides a system record, how should it be applied?\n */\n extends: z.string().optional().describe('Name of the parent metadata to extend/override'),\n strategy: z.enum(['merge', 'replace']).default('merge'),\n\n /** Owner (for user-scope items) */\n owner: z.string().optional(),\n \n /** State */\n state: MetadataStateSchema.default('active'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant isolation'),\n\n /** Version number for optimistic concurrency */\n version: z.number().default(1).describe('Record version for optimistic concurrency control'),\n\n /** Checksum for change detection */\n checksum: z.string().optional().describe('Content checksum for change detection'),\n\n /** Source origin marker */\n source: z.enum(['filesystem', 'database', 'api', 'migration']).optional().describe('Origin of this metadata record'),\n\n /** Classification tags */\n tags: z.array(z.string()).optional().describe('Classification tags for filtering and grouping'),\n \n /** Package Publishing */\n publishedDefinition: z.unknown().optional()\n .describe('Snapshot of the last published definition'),\n publishedAt: z.string().datetime().optional()\n .describe('When this metadata was last published'),\n publishedBy: z.string().optional()\n .describe('Who published this version'),\n\n /** Audit */\n createdBy: z.string().optional(),\n createdAt: z.string().datetime().optional().describe('Creation timestamp'),\n updatedBy: z.string().optional(),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n});\n\nexport type MetadataRecord = z.infer;\nexport type MetadataScope = z.infer;\n\n/**\n * Package Publish Result\n * Returned by `publishPackage()` after a package-level metadata publish operation.\n */\nexport const PackagePublishResultSchema = z.object({\n success: z.boolean().describe('Whether the publish succeeded'),\n packageId: z.string().describe('The package ID that was published'),\n version: z.number().int().describe('New version number after publish'),\n publishedAt: z.string().datetime().describe('Publish timestamp'),\n itemsPublished: z.number().int().describe('Total metadata items published'),\n validationErrors: z.array(z.object({\n type: z.string().describe('Metadata type that failed validation'),\n name: z.string().describe('Item name that failed validation'),\n message: z.string().describe('Validation error message'),\n })).optional().describe('Validation errors if publish failed'),\n});\n\nexport type PackagePublishResult = z.infer;\n\n/**\n * Metadata Format\n * Supported file formats for metadata serialization.\n */\nexport const MetadataFormatSchema = z.enum([\n 'json', 'yaml', 'yml', 'ts', 'js',\n 'typescript', 'javascript' // Aliases\n]);\n\n/**\n * Metadata Stats\n * Statistics about a metadata item.\n */\nexport const MetadataStatsSchema = z.object({\n path: z.string().optional(),\n size: z.number().optional(),\n mtime: z.string().datetime().optional(),\n hash: z.string().optional(),\n etag: z.string().optional(), // Required by local cache\n modifiedAt: z.string().datetime().optional(), // Alias for mtime\n format: MetadataFormatSchema.optional(), // Required for serialization\n});\n\n/**\n * Metadata Loader Contract\n * Describes the capabilities and identity of a metadata loader.\n */\nexport const MetadataLoaderContractSchema = z.object({\n name: z.string(),\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Loader protocol identifier'),\n description: z.string().optional(),\n supportedFormats: z.array(z.string()).optional(),\n supportsWatch: z.boolean().optional(),\n supportsWrite: z.boolean().optional(),\n supportsCache: z.boolean().optional(),\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n scope: MetadataScopeSchema.optional(),\n namespace: z.string().optional(),\n raw: z.boolean().optional().describe('Return raw file content instead of parsed JSON'),\n cache: z.boolean().optional(),\n useCache: z.boolean().optional(), // Alias for cache\n validate: z.boolean().optional(),\n ifNoneMatch: z.string().optional(), // For caching\n recursive: z.boolean().optional(),\n limit: z.number().optional(),\n patterns: z.array(z.string()).optional(),\n loader: z.string().optional().describe('Specific loader to use (e.g. filesystem, database)'),\n});\n\n/**\n * Metadata Load Result\n */\nexport const MetadataLoadResultSchema = z.object({\n data: z.unknown(),\n stats: MetadataStatsSchema.optional(),\n format: MetadataFormatSchema.optional(),\n source: z.string().optional(), // File path or URL\n fromCache: z.boolean().optional(),\n etag: z.string().optional(),\n notModified: z.boolean().optional(),\n loadTime: z.number().optional(),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n format: MetadataFormatSchema.optional(),\n create: z.boolean().default(true),\n overwrite: z.boolean().default(true),\n path: z.string().optional(),\n prettify: z.boolean().optional(),\n indent: z.number().optional(),\n sortKeys: z.boolean().optional(),\n backup: z.boolean().optional(),\n atomic: z.boolean().optional(),\n loader: z.string().optional().describe('Specific loader to use (e.g. filesystem, database)'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n success: z.boolean(),\n path: z.string().optional(),\n stats: MetadataStatsSchema.optional(),\n etag: z.string().optional(),\n size: z.number().optional(),\n saveTime: z.number().optional(),\n backupPath: z.string().optional(),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n type: z.enum(['add', 'change', 'unlink', 'added', 'changed', 'deleted']),\n path: z.string(),\n name: z.string().optional(),\n stats: MetadataStatsSchema.optional(),\n metadataType: z.string().optional(),\n data: z.unknown().optional(),\n timestamp: z.string().datetime().optional(),\n});\n\n/**\n * Metadata Collection Info\n */\nexport const MetadataCollectionInfoSchema = z.object({\n type: z.string(),\n count: z.number(),\n namespaces: z.array(z.string()),\n});\n\n/**\n * Metadata Export/Import Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n types: z.array(z.string()).optional(),\n namespaces: z.array(z.string()).optional(),\n output: z.string().describe('Output directory or file'),\n format: MetadataFormatSchema.default('json'),\n});\n\nexport const MetadataImportOptionsSchema = z.object({\n source: z.string().describe('Input directory or file'),\n strategy: z.enum(['merge', 'replace', 'skip']).default('merge'),\n validate: z.boolean().default(true),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Source Origin\n * Indicates where a metadata record was loaded from.\n */\nexport const MetadataSourceSchema = z.enum([\n 'filesystem', // Loaded from local files\n 'database', // Loaded from database via datasource\n 'api', // Loaded from remote API\n 'migration', // Created during a migration process\n]);\n\n/**\n * Metadata Manager Config\n * \n * Unified configuration for the MetadataManager.\n * Supports datasource-backed persistence via `datasource` field,\n * which references a DatasourceSchema.name resolved at runtime.\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n * When provided, metadata is persisted to a database table.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory for filesystem-based metadata'),\n\n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).optional().describe('Enabled metadata formats'),\n\n /**\n * Enable file watching\n */\n watch: z.boolean().optional().describe('Enable file watching for filesystem loaders'),\n\n /**\n * Cache configuration\n */\n cache: z.boolean().optional().describe('Enable metadata caching'),\n\n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n }).optional().describe('File watcher options'),\n});\n\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataLoadOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\nexport type MetadataSource = z.infer;\n\n/**\n * Metadata History Record\n *\n * Represents a single version snapshot in the metadata change history.\n * Stored in the sys_metadata_history table for version tracking and rollback.\n */\nexport const MetadataHistoryRecordSchema = z.object({\n /** Primary Key (UUID) */\n id: z.string(),\n\n /** Reference to the parent metadata record ID */\n metadataId: z.string().describe('Foreign key to sys_metadata.id'),\n\n /**\n * Machine Name\n * Denormalized from parent for easier querying.\n */\n name: z.string(),\n\n /**\n * Metadata Type\n * Denormalized from parent for easier querying.\n */\n type: z.string(),\n\n /**\n * Version Number\n * Snapshot of the metadata version at this point in history.\n */\n version: z.number().describe('Version number at this snapshot'),\n\n /**\n * Operation Type\n * Indicates what kind of change triggered this history record.\n */\n operationType: z.enum(['create', 'update', 'publish', 'revert', 'delete']).describe('Type of operation that created this history entry'),\n\n /**\n * Historical Metadata Snapshot\n * Full JSON payload of the metadata definition at this version.\n * May be stored as a raw JSON string in the history table, or as a parsed object\n * in higher-level APIs. When `includeMetadata` is false, this field is null.\n */\n metadata: z\n .union([z.string(), z.record(z.string(), z.unknown())])\n .nullable()\n .optional()\n .describe('Snapshot of metadata definition at this version (raw JSON string or parsed object)'),\n\n /**\n * Content Checksum\n * SHA-256 checksum of the normalized metadata JSON for change detection.\n */\n checksum: z.string().describe('SHA-256 checksum of metadata content'),\n\n /**\n * Previous Checksum\n * Checksum of the previous version for diff optimization.\n */\n previousChecksum: z.string().optional().describe('Checksum of the previous version'),\n\n /**\n * Change Note\n * Human-readable description of what changed in this version.\n */\n changeNote: z.string().optional().describe('Description of changes made in this version'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant isolation'),\n\n /** Audit: who made this change */\n recordedBy: z.string().optional().describe('User who made this change'),\n\n /** Audit: when was this version recorded */\n recordedAt: z.string().datetime().describe('Timestamp when this version was recorded'),\n});\n\nexport type MetadataHistoryRecord = z.infer;\n\n/**\n * Metadata History Query Options\n * Options for retrieving metadata version history.\n */\nexport const MetadataHistoryQueryOptionsSchema = z.object({\n /** Limit number of history records returned */\n limit: z.number().int().positive().optional().describe('Maximum number of history records to return'),\n\n /** Offset for pagination */\n offset: z.number().int().nonnegative().optional().describe('Number of records to skip'),\n\n /** Only return versions after this timestamp */\n since: z.string().datetime().optional().describe('Only return history after this timestamp'),\n\n /** Only return versions before this timestamp */\n until: z.string().datetime().optional().describe('Only return history before this timestamp'),\n\n /** Filter by operation type */\n operationType: z.enum(['create', 'update', 'publish', 'revert', 'delete']).optional().describe('Filter by operation type'),\n\n /** Include full metadata payload in results (default: true) */\n includeMetadata: z.boolean().optional().default(true).describe('Include full metadata payload'),\n});\n\nexport type MetadataHistoryQueryOptions = z.infer;\n\n/**\n * Metadata History Query Result\n * Result of querying metadata version history.\n */\nexport const MetadataHistoryQueryResultSchema = z.object({\n /** Array of history records */\n records: z.array(MetadataHistoryRecordSchema),\n\n /** Total number of history records (for pagination) */\n total: z.number().int().nonnegative(),\n\n /** Whether there are more records available */\n hasMore: z.boolean(),\n});\n\nexport type MetadataHistoryQueryResult = z.infer;\n\n/**\n * Metadata Diff Result\n * Result of comparing two versions of metadata.\n */\nexport const MetadataDiffResultSchema = z.object({\n /** Metadata type */\n type: z.string(),\n\n /** Metadata name */\n name: z.string(),\n\n /** Version 1 (older) */\n version1: z.number(),\n\n /** Version 2 (newer) */\n version2: z.number(),\n\n /** Checksum of version 1 */\n checksum1: z.string(),\n\n /** Checksum of version 2 */\n checksum2: z.string(),\n\n /** Whether the versions are identical */\n identical: z.boolean(),\n\n /** JSON patch operations to transform v1 into v2 */\n patch: z.array(z.unknown()).optional().describe('JSON patch operations'),\n\n /** Human-readable diff summary */\n summary: z.string().optional().describe('Human-readable summary of changes'),\n});\n\nexport type MetadataDiffResult = z.infer;\n\n/**\n * Metadata History Retention Policy\n * Configuration for automatic cleanup of old history records.\n */\nexport const MetadataHistoryRetentionPolicySchema = z.object({\n /** Maximum number of versions to keep per metadata item */\n maxVersions: z.number().int().positive().optional().describe('Maximum number of versions to retain'),\n\n /** Maximum age of history records in days */\n maxAgeDays: z.number().int().positive().optional().describe('Maximum age of history records in days'),\n\n /** Whether to enable automatic cleanup */\n autoCleanup: z.boolean().default(false).describe('Enable automatic cleanup of old history'),\n\n /** Cleanup interval in hours */\n cleanupIntervalHours: z.number().int().positive().default(24).describe('How often to run cleanup (in hours)'),\n});\n\nexport type MetadataHistoryRetentionPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Service Registry Protocol\n * \n * Defines the standard built-in services that constitute the ObjectStack Kernel.\n * This registry is used by the `ObjectKernel` and `HttpDispatcher` to:\n * 1. Verify service availability.\n * 2. Route requests to the correct service handler.\n * 3. Type-check service interactions.\n */\n\n// ==========================================\n// Service Identifiers\n// ==========================================\n\nexport const CoreServiceName = z.enum([\n // Core Data & Metadata\n 'metadata', // Object/Field Definitions\n 'data', // CRUD & Query Engine\n 'auth', // Authentication & Identity\n \n // Infrastructure\n 'file-storage', // Storage Driver (Local/S3)\n 'search', // Search Engine (Elastic/Meili)\n 'cache', // Cache Driver (Redis/Memory)\n 'queue', // Job Queue (BullMQ/Redis)\n \n // Advanced Capabilities\n 'automation', // Flow & Script Engine\n 'graphql', // GraphQL API Engine\n 'analytics', // BI & Semantic Layer\n 'realtime', // WebSocket & PubSub\n 'job', // Background Job Manager\n 'notification', // Email/Push/SMS\n 'ai', // AI Engine (NLQ, Chat, Suggest, Insights)\n 'i18n', // Internationalization Service\n 'ui', // UI Metadata Service (View CRUD)\n 'workflow', // Workflow State Machine Engine\n]);\n\nexport type CoreServiceName = z.infer;\n\n/**\n * Service Criticality Level\n * Defines the startup behavior when a service is missing.\n */\nexport const ServiceCriticalitySchema = z.enum([\n 'required', // System fails to start if missing (Exit Code 1)\n 'core', // System warns if missing, functionality degraded (Warn)\n 'optional', // System ignores if missing, feature disabled (Info)\n]);\n\n/**\n * Service Requirement Definition\n */\nexport const ServiceRequirementDef = {\n // Required: The kernel cannot function without these\n data: 'required',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n metadata: 'core',\n auth: 'core',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n cache: 'core',\n queue: 'core',\n job: 'core',\n i18n: 'core',\n\n // Optional: Add-on capabilities\n 'file-storage': 'optional',\n search: 'optional',\n automation: 'optional',\n graphql: 'optional',\n analytics: 'optional',\n realtime: 'optional',\n notification: 'optional',\n ai: 'optional',\n ui: 'optional',\n workflow: 'optional',\n} as const;\n\n// ==========================================\n// Service Capabilities\n// ==========================================\n\n/**\n * Describes the availability and health of a service\n */\nexport const ServiceStatusSchema = z.object({\n name: CoreServiceName,\n enabled: z.boolean(),\n status: z.enum(['running', 'stopped', 'degraded', 'initializing']),\n version: z.string().optional(),\n provider: z.string().optional().describe('Implementation provider (e.g. \"s3\" for storage)'),\n features: z.array(z.string()).optional().describe('List of supported sub-features'),\n});\n\n/**\n * The Contract definition for what the Kernel MUST expose\n * map\n */\nexport const KernelServiceMapSchema = z.record(\n CoreServiceName, \n z.unknown().describe('Service Instance implementing the protocol interface')\n);\n\n// ==========================================\n// Service Interfaces (Stub definitions)\n// ==========================================\n// Ideally, we would define strict Typescript interfaces here \n// for what methods each service must expose to the Registry.\n// For Zod, we primarily validate configuration and status.\n\n// e.g.\nexport const ServiceConfigSchema = z.object({\n id: z.string(),\n name: CoreServiceName,\n options: z.record(z.string(), z.unknown()).optional(),\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Schema (Multi-Tenant Architecture)\n * \n * Defines the tenant/tenancy model for ObjectStack SaaS deployments.\n * Supports different levels of data isolation to meet varying security,\n * performance, and compliance requirements.\n * \n * Isolation Levels:\n * - shared_schema: All tenants share the same database and schema (row-level isolation)\n * - isolated_schema: Tenants have separate schemas within a shared database\n * - isolated_db: Each tenant has a completely separate database\n */\n\n/**\n * Tenant Isolation Level Enum\n * Defines how tenant data is separated in the system\n */\nexport const TenantIsolationLevel = z.enum([\n 'shared_schema', // Shared DB, shared schema, row-level isolation (most economical)\n 'isolated_schema', // Shared DB, separate schema per tenant (balanced)\n 'isolated_db', // Separate database per tenant (maximum isolation)\n]);\n\nexport type TenantIsolationLevel = z.infer;\n\n/**\n * Database Provider Enum\n * Defines which database backend is used for the tenant\n */\nexport const DatabaseProviderSchema = z.enum([\n 'turso', // Turso/libSQL (DB-per-Tenant, edge-native)\n 'postgres', // PostgreSQL (traditional, self-hosted or managed)\n 'memory', // In-memory (testing/development only)\n]).describe('Database provider for tenant data');\n\nexport type DatabaseProvider = z.infer;\n\n/**\n * Tenant Connection Config Schema\n * Stores the database connection details for a tenant (encrypted at rest)\n */\nexport const TenantConnectionConfigSchema = z.object({\n /** Database connection URL */\n url: z.string().min(1).describe('Database connection URL'),\n /** Authentication token (JWT for Turso, password for Postgres) */\n authToken: z.string().optional().describe('Database auth token (encrypted at rest)'),\n /** Turso database group name */\n group: z.string().optional().describe('Turso database group name'),\n}).describe('Tenant database connection configuration');\n\nexport type TenantConnectionConfig = z.infer;\n\n/**\n * Tenant Quota Schema\n * Defines resource limits and usage quotas for a tenant\n */\nexport const TenantQuotaSchema = z.object({\n /**\n * Maximum number of users allowed for this tenant\n */\n maxUsers: z.number().int().positive().optional().describe('Maximum number of users'),\n \n /**\n * Maximum storage space in bytes\n */\n maxStorage: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n \n /**\n * API rate limit (requests per minute)\n */\n apiRateLimit: z.number().int().positive().optional().describe('API requests per minute'),\n\n /**\n * Maximum number of custom objects the tenant can create\n */\n maxObjects: z.number().int().positive().optional().describe('Maximum number of custom objects'),\n\n /**\n * Maximum records per object/table\n */\n maxRecordsPerObject: z.number().int().positive().optional().describe('Maximum records per object'),\n\n /**\n * Maximum deployments allowed per day\n */\n maxDeploymentsPerDay: z.number().int().positive().optional().describe('Maximum deployments per day'),\n\n /**\n * Maximum storage in bytes\n */\n maxStorageBytes: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n});\n\nexport type TenantQuota = z.infer;\n\n/**\n * Tenant Usage Schema\n * Tracks current resource usage for quota enforcement\n */\nexport const TenantUsageSchema = z.object({\n /** Current number of custom objects */\n currentObjectCount: z.number().int().min(0).default(0).describe('Current number of custom objects'),\n /** Current total record count across all objects */\n currentRecordCount: z.number().int().min(0).default(0).describe('Total records across all objects'),\n /** Current storage usage in bytes */\n currentStorageBytes: z.number().int().min(0).default(0).describe('Current storage usage in bytes'),\n /** Deployments executed today */\n deploymentsToday: z.number().int().min(0).default(0).describe('Deployments executed today'),\n /** Current number of active users */\n currentUsers: z.number().int().min(0).default(0).describe('Current number of active users'),\n /** API requests in the current minute */\n apiRequestsThisMinute: z.number().int().min(0).default(0).describe('API requests in the current minute'),\n /** Last updated timestamp (ISO 8601) */\n lastUpdatedAt: z.string().datetime().optional().describe('Last usage update time'),\n}).describe('Current tenant resource usage');\n\nexport type TenantUsage = z.infer;\n\n/**\n * Quota Enforcement Result\n * Result of checking whether an operation would exceed tenant quotas\n */\nexport const QuotaEnforcementResultSchema = z.object({\n /** Whether the operation is allowed */\n allowed: z.boolean().describe('Whether the operation is within quota'),\n /** Quota that would be exceeded (if not allowed) */\n exceededQuota: z.string().optional().describe('Name of the exceeded quota'),\n /** Current usage value */\n currentUsage: z.number().optional().describe('Current usage value'),\n /** Quota limit value */\n limit: z.number().optional().describe('Quota limit'),\n /** Human-readable message */\n message: z.string().optional().describe('Human-readable quota message'),\n}).describe('Quota enforcement check result');\n\nexport type QuotaEnforcementResult = z.infer;\n\n/**\n * Tenant Schema\n * \n * @deprecated This schema is maintained for backward compatibility only.\n * New implementations should use HubSpaceSchema which embeds tenant concepts.\n * \n * **Migration Guide:**\n * ```typescript\n * // Old approach (deprecated):\n * const tenant: Tenant = {\n * id: 'tenant_123',\n * name: 'My Tenant',\n * isolationLevel: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * };\n * \n * // New approach (recommended):\n * const space: HubSpace = {\n * id: '...uuid...',\n * name: 'My Tenant',\n * slug: 'my-tenant',\n * ownerId: 'user_id',\n * runtime: {\n * isolation: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * },\n * bom: { ... }\n * };\n * ```\n * \n * See HubSpaceSchema in space.zod.ts for the recommended approach.\n */\nexport const TenantSchema = z.object({\n /**\n * Unique tenant identifier\n */\n id: z.string().describe('Unique tenant identifier'),\n \n /**\n * Tenant display name\n */\n name: z.string().describe('Tenant display name'),\n \n /**\n * Data isolation level\n */\n isolationLevel: TenantIsolationLevel,\n\n /**\n * Database provider for this tenant\n */\n databaseProvider: DatabaseProviderSchema.optional().describe('Database provider'),\n\n /**\n * Database connection configuration (encrypted at rest)\n */\n connectionConfig: TenantConnectionConfigSchema.optional().describe('Database connection config'),\n\n /**\n * Current provisioning status\n */\n provisioningStatus: z.enum([\n 'provisioning', 'active', 'suspended', 'failed', 'destroying',\n ]).optional().describe('Current provisioning lifecycle status'),\n\n /**\n * Tenant subscription plan\n */\n plan: z.enum(['free', 'pro', 'enterprise']).optional().describe('Subscription plan'),\n \n /**\n * Custom configuration values\n */\n customizations: z.record(z.string(), z.unknown()).optional().describe('Custom configuration values'),\n \n /**\n * Resource quotas\n */\n quotas: TenantQuotaSchema.optional(),\n});\n\nexport type Tenant = z.infer;\n\n/**\n * Tenant Isolation Strategy Documentation\n * \n * Comprehensive documentation of three isolation strategies for multi-tenant systems.\n * Each strategy has different trade-offs in terms of security, cost, complexity, and compliance.\n */\n\n/**\n * Row-Level Isolation Strategy (shared_schema)\n * \n * Recommended for: Most SaaS applications, cost-sensitive deployments\n * \n * IMPLEMENTATION:\n * - All tenants share the same database and schema\n * - Each table includes a tenant_id column\n * - PostgreSQL Row-Level Security (RLS) enforces isolation\n * - Queries automatically filter by tenant_id via RLS policies\n * \n * ADVANTAGES:\n * ✅ Simple backup and restore (single database)\n * ✅ Cost-effective (shared resources, minimal overhead)\n * ✅ Easy tenant migration (update tenant_id)\n * ✅ Efficient resource utilization (connection pooling)\n * ✅ Simple schema migrations (single schema to update)\n * ✅ Lower operational complexity\n * \n * DISADVANTAGES:\n * ❌ RLS misconfiguration can lead to data leakage\n * ❌ Performance impact from RLS policy evaluation\n * ❌ Noisy neighbor problem (one tenant can affect others)\n * ❌ Cannot easily isolate tenant to different hardware\n * ❌ Compliance challenges for regulated industries\n * \n * SECURITY CONSIDERATIONS:\n * - Requires careful RLS policy configuration\n * - Must validate tenant_id in all queries\n * - Need comprehensive testing of RLS policies\n * - Audit all database access patterns\n * - Implement application-level validation as defense-in-depth\n * \n * EXAMPLE RLS POLICY (PostgreSQL):\n * ```sql\n * -- Example: Apply RLS policy to a table (e.g., \"app_data\")\n * CREATE POLICY tenant_isolation ON app_data\n * USING (tenant_id = current_setting('app.current_tenant')::text);\n * \n * ALTER TABLE app_data ENABLE ROW LEVEL SECURITY;\n * ```\n */\nexport const RowLevelIsolationStrategySchema = z.object({\n strategy: z.literal('shared_schema').describe('Row-level isolation strategy'),\n \n /**\n * Database configuration for row-level isolation\n */\n database: z.object({\n /**\n * Whether to enable Row-Level Security (RLS)\n */\n enableRLS: z.boolean().default(true).describe('Enable PostgreSQL Row-Level Security'),\n \n /**\n * Tenant context setting method\n */\n contextMethod: z.enum([\n 'session_variable', // SET app.current_tenant = 'tenant_123'\n 'search_path', // SET search_path = tenant_123, public\n 'application_name', // SET application_name = 'tenant_123'\n ]).default('session_variable').describe('How to set tenant context'),\n \n /**\n * Session variable name for tenant context\n */\n contextVariable: z.string().default('app.current_tenant').describe('Session variable name'),\n \n /**\n * Whether to validate tenant_id at application level\n */\n applicationValidation: z.boolean().default(true).describe('Application-level tenant validation'),\n }).optional().describe('Database configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use partial indexes for tenant_id\n */\n usePartialIndexes: z.boolean().default(true).describe('Use partial indexes per tenant'),\n \n /**\n * Whether to use table partitioning\n */\n usePartitioning: z.boolean().default(false).describe('Use table partitioning by tenant_id'),\n \n /**\n * Connection pool size per tenant\n */\n poolSizePerTenant: z.number().int().positive().optional().describe('Connection pool size per tenant'),\n }).optional().describe('Performance settings'),\n});\n\nexport type RowLevelIsolationStrategy = z.infer;\nexport type RowLevelIsolationStrategyInput = z.input;\n\n/**\n * Schema-Level Isolation Strategy (isolated_schema)\n * \n * Recommended for: Enterprise SaaS, B2B platforms with compliance needs\n * \n * IMPLEMENTATION:\n * - All tenants share the same database server\n * - Each tenant has a separate database schema\n * - Schema name typically: tenant_\n * - Application switches schema using SET search_path\n * \n * ADVANTAGES:\n * ✅ Better isolation than row-level (schema boundaries)\n * ✅ Easier to debug (separate schemas)\n * ✅ Can grant different database permissions per schema\n * ✅ Reduced risk of data leakage\n * ✅ Performance isolation (indexes, statistics per schema)\n * ✅ Simplified queries (no tenant_id filtering needed)\n * \n * DISADVANTAGES:\n * ❌ More complex backups (must backup all schemas)\n * ❌ Higher migration costs (schema changes across all tenants)\n * ❌ Schema proliferation (PostgreSQL has limits)\n * ❌ Connection overhead (switching schemas)\n * ❌ More complex monitoring and maintenance\n * \n * SECURITY CONSIDERATIONS:\n * - Ensure proper schema permissions (GRANT USAGE ON SCHEMA)\n * - Validate schema name to prevent SQL injection\n * - Implement connection-level schema switching\n * - Audit schema access patterns\n * - Prevent cross-schema queries in application\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant schema\n * CREATE SCHEMA tenant_123;\n * \n * -- Grant access\n * GRANT USAGE ON SCHEMA tenant_123 TO app_user;\n * \n * -- Switch to tenant schema\n * SET search_path TO tenant_123, public;\n * ```\n */\nexport const SchemaLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_schema').describe('Schema-level isolation strategy'),\n \n /**\n * Schema configuration\n */\n schema: z.object({\n /**\n * Schema naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Schema naming pattern'),\n \n /**\n * Whether to include public schema in search_path\n */\n includePublicSchema: z.boolean().default(true).describe('Include public schema'),\n \n /**\n * Default schema for shared resources\n */\n sharedSchema: z.string().default('public').describe('Schema for shared resources'),\n \n /**\n * Whether to automatically create schema on tenant creation\n */\n autoCreateSchema: z.boolean().default(true).describe('Auto-create schema'),\n }).optional().describe('Schema configuration'),\n \n /**\n * Migration configuration\n */\n migrations: z.object({\n /**\n * Migration strategy\n */\n strategy: z.enum([\n 'parallel', // Run migrations on all schemas in parallel\n 'sequential', // Run migrations one schema at a time\n 'on_demand', // Run migrations when tenant accesses system\n ]).default('parallel').describe('Migration strategy'),\n \n /**\n * Maximum concurrent migrations\n */\n maxConcurrent: z.number().int().positive().default(10).describe('Max concurrent migrations'),\n \n /**\n * Whether to rollback on first failure\n */\n rollbackOnError: z.boolean().default(true).describe('Rollback on error'),\n }).optional().describe('Migration configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use connection pooling per schema\n */\n poolPerSchema: z.boolean().default(false).describe('Separate pool per schema'),\n \n /**\n * Schema cache TTL in seconds\n */\n schemaCacheTTL: z.number().int().positive().default(3600).describe('Schema cache TTL'),\n }).optional().describe('Performance settings'),\n});\n\nexport type SchemaLevelIsolationStrategy = z.infer;\nexport type SchemaLevelIsolationStrategyInput = z.input;\n\n/**\n * Database-Level Isolation Strategy (isolated_db)\n * \n * Recommended for: Regulated industries (healthcare, finance), strict compliance requirements\n * \n * IMPLEMENTATION:\n * - Each tenant has a completely separate database\n * - Database name typically: tenant_\n * - Requires separate connection pool per tenant\n * - Complete physical and logical isolation\n * \n * ADVANTAGES:\n * ✅ Perfect data isolation (strongest security)\n * ✅ Meets strict regulatory requirements (HIPAA, SOX, PCI-DSS)\n * ✅ Complete performance isolation (no noisy neighbors)\n * ✅ Can place databases on different hardware\n * ✅ Easy to backup/restore individual tenant\n * ✅ Simplified compliance auditing per tenant\n * ✅ Can apply different encryption keys per database\n * \n * DISADVANTAGES:\n * ❌ Most expensive option (resource overhead)\n * ❌ Complex database server management (many databases)\n * ❌ Connection pool limits (max connections per server)\n * ❌ Difficult cross-tenant analytics\n * ❌ Higher operational complexity\n * ❌ Schema migrations take longer (many databases)\n * \n * SECURITY CONSIDERATIONS:\n * - Each database can have separate credentials\n * - Enables per-tenant encryption at rest\n * - Simplifies compliance and audit trails\n * - Prevents any cross-tenant data access\n * - Supports tenant-specific backup schedules\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant database\n * CREATE DATABASE tenant_123\n * WITH OWNER = tenant_123_user\n * ENCODING = 'UTF8'\n * LC_COLLATE = 'en_US.UTF-8'\n * LC_CTYPE = 'en_US.UTF-8';\n * \n * -- Connect to tenant database\n * \\c tenant_123\n * ```\n */\nexport const DatabaseLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_db').describe('Database-level isolation strategy'),\n \n /**\n * Database configuration\n */\n database: z.object({\n /**\n * Database naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Database naming pattern'),\n \n /**\n * Database server/cluster assignment strategy\n */\n serverStrategy: z.enum([\n 'shared', // All tenant databases on same server\n 'sharded', // Tenant databases distributed across servers\n 'dedicated', // Each tenant gets dedicated server (enterprise)\n ]).default('shared').describe('Server assignment strategy'),\n \n /**\n * Whether to use separate credentials per tenant\n */\n separateCredentials: z.boolean().default(true).describe('Separate credentials per tenant'),\n \n /**\n * Whether to automatically create database on tenant creation\n */\n autoCreateDatabase: z.boolean().default(true).describe('Auto-create database'),\n }).optional().describe('Database configuration'),\n \n /**\n * Connection pooling configuration\n */\n connectionPool: z.object({\n /**\n * Pool size per tenant database\n */\n poolSize: z.number().int().positive().default(10).describe('Connection pool size'),\n \n /**\n * Maximum number of tenant pools to keep active\n */\n maxActivePools: z.number().int().positive().default(100).describe('Max active pools'),\n \n /**\n * Idle pool timeout in seconds\n */\n idleTimeout: z.number().int().positive().default(300).describe('Idle pool timeout'),\n \n /**\n * Whether to use connection pooler (PgBouncer, etc.)\n */\n usePooler: z.boolean().default(true).describe('Use connection pooler'),\n }).optional().describe('Connection pool configuration'),\n \n /**\n * Backup and restore configuration\n */\n backup: z.object({\n /**\n * Backup strategy per tenant\n */\n strategy: z.enum([\n 'individual', // Separate backup per tenant\n 'consolidated', // Combined backup with all tenants\n 'on_demand', // Backup only when requested\n ]).default('individual').describe('Backup strategy'),\n \n /**\n * Backup frequency in hours\n */\n frequencyHours: z.number().int().positive().default(24).describe('Backup frequency'),\n \n /**\n * Retention period in days\n */\n retentionDays: z.number().int().positive().default(30).describe('Backup retention days'),\n }).optional().describe('Backup configuration'),\n \n /**\n * Encryption configuration\n */\n encryption: z.object({\n /**\n * Whether to use per-tenant encryption keys\n */\n perTenantKeys: z.boolean().default(false).describe('Per-tenant encryption keys'),\n \n /**\n * Encryption algorithm\n */\n algorithm: z.string().default('AES-256-GCM').describe('Encryption algorithm'),\n \n /**\n * Key management service\n */\n keyManagement: z.enum(['aws_kms', 'azure_key_vault', 'gcp_kms', 'hashicorp_vault', 'custom']).optional().describe('Key management service'),\n }).optional().describe('Encryption configuration'),\n});\n\nexport type DatabaseLevelIsolationStrategy = z.infer;\nexport type DatabaseLevelIsolationStrategyInput = z.input;\n\n/**\n * Tenant Isolation Configuration Schema\n * \n * Complete configuration for tenant isolation strategy.\n * Supports all three isolation levels with detailed configuration options.\n */\nexport const TenantIsolationConfigSchema = z.discriminatedUnion('strategy', [\n RowLevelIsolationStrategySchema,\n SchemaLevelIsolationStrategySchema,\n DatabaseLevelIsolationStrategySchema,\n]);\n\nexport type TenantIsolationConfig = z.infer;\n\n/**\n * Tenant Security Policy Schema\n * Defines security policies and compliance requirements for tenants\n */\nexport const TenantSecurityPolicySchema = z.object({\n /**\n * Encryption requirements\n */\n encryption: z.object({\n /**\n * Require encryption at rest\n */\n atRest: z.boolean().default(true).describe('Require encryption at rest'),\n \n /**\n * Require encryption in transit\n */\n inTransit: z.boolean().default(true).describe('Require encryption in transit'),\n \n /**\n * Require field-level encryption for sensitive data\n */\n fieldLevel: z.boolean().default(false).describe('Require field-level encryption'),\n }).optional().describe('Encryption requirements'),\n \n /**\n * Access control requirements\n */\n accessControl: z.object({\n /**\n * Require multi-factor authentication\n */\n requireMFA: z.boolean().default(false).describe('Require MFA'),\n \n /**\n * Require SSO/SAML authentication\n */\n requireSSO: z.boolean().default(false).describe('Require SSO'),\n \n /**\n * IP whitelist\n */\n ipWhitelist: z.array(z.string()).optional().describe('Allowed IP addresses'),\n \n /**\n * Session timeout in seconds\n */\n sessionTimeout: z.number().int().positive().default(3600).describe('Session timeout'),\n }).optional().describe('Access control requirements'),\n \n /**\n * Audit and compliance requirements\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox',\n 'hipaa',\n 'gdpr',\n 'pci_dss',\n 'iso_27001',\n 'fedramp',\n ])).optional().describe('Compliance standards'),\n \n /**\n * Require audit logging for all operations\n */\n requireAuditLog: z.boolean().default(true).describe('Require audit logging'),\n \n /**\n * Audit log retention period in days\n */\n auditRetentionDays: z.number().int().positive().default(365).describe('Audit retention days'),\n \n /**\n * Data residency requirements\n */\n dataResidency: z.object({\n /**\n * Required geographic region\n */\n region: z.string().optional().describe('Required region (e.g., US, EU, APAC)'),\n \n /**\n * Prohibited regions\n */\n excludeRegions: z.array(z.string()).optional().describe('Prohibited regions'),\n }).optional().describe('Data residency requirements'),\n }).optional().describe('Compliance requirements'),\n});\n\nexport type TenantSecurityPolicy = z.infer;\nexport type TenantSecurityPolicyInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metric Type Classification\n */\nexport const LicenseMetricType = z.enum([\n 'boolean', // Feature Flag (Enabled/Disabled)\n 'counter', // Usage Count (e.g. API Calls, Records Created) - Accumulates\n 'gauge', // Current Level (e.g. Storage Used, Users Active) - Point in time\n]).describe('License metric type');\nexport type LicenseMetricType = z.infer;\n\n/**\n * Feature/Limit Definition Schema\n * Defines a controllable capability of the system.\n */\nexport const FeatureSchema = z.object({\n code: z.string().regex(/^[a-z_][a-z0-9_.]*$/).describe('Feature code (e.g. core.api_access)'),\n label: z.string(),\n description: z.string().optional(),\n \n type: LicenseMetricType.default('boolean'),\n \n /** For counters/gauges */\n unit: z.enum(['count', 'bytes', 'seconds', 'percent']).optional(),\n \n /** Dependencies (e.g. 'audit_log' requires 'enterprise_tier') */\n requires: z.array(z.string()).optional(),\n});\n\n/**\n * Subscription Plan Schema\n * Defines a tier of service (e.g. \"Free\", \"Pro\", \"Enterprise\").\n */\nexport const PlanSchema = z.object({\n code: z.string().describe('Plan code (e.g. pro_v1)'),\n label: z.string(),\n active: z.boolean().default(true),\n \n /** Feature Entitlements */\n features: z.array(z.string()).describe('List of enabled boolean features'),\n \n /** Limit Quotas */\n limits: z.record(z.string(), z.number()).describe('Map of metric codes to limit values (e.g. { storage_gb: 10 })'),\n \n /** Pricing (Optional Metadata) */\n currency: z.string().default('USD').optional(),\n priceMonthly: z.number().optional(),\n priceYearly: z.number().optional(),\n});\n\n/**\n * License Schema\n * The actual entitlement object assigned to a Space.\n * Often signed as a JWT.\n */\nexport const LicenseSchema = z.object({\n /** Identity */\n spaceId: z.string().describe('Target Space ID'),\n planCode: z.string(),\n \n /** Validity */\n issuedAt: z.string().datetime(),\n expiresAt: z.string().datetime().optional(), // Null = Perpetual\n \n /** Status */\n status: z.enum(['active', 'expired', 'suspended', 'trial']),\n \n /** Overrides (Specific to this space, exceeding the plan) */\n customFeatures: z.array(z.string()).optional(),\n customLimits: z.record(z.string(), z.number()).optional(),\n \n /** Authorized Add-ons */\n plugins: z.array(z.string()).optional().describe('List of enabled plugin package IDs'),\n\n /** Signature */\n signature: z.string().optional().describe('Cryptographic signature of the license'),\n});\n\nexport type Feature = z.infer;\nexport type FeatureInput = z.input;\nexport type Plan = z.infer;\nexport type PlanInput = z.input;\nexport type License = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Registry Configuration Protocol\n * \n * Defines the configuration for the ObjectStack Registry Service.\n * Includes federation, synchronization, and storage settings.\n */\n\n/**\n * Registry Sync Policy\n * Defines how registries synchronize with upstreams\n */\nexport const RegistrySyncPolicySchema = z.enum([\n 'manual', // Manual synchronization only\n 'auto', // Automatic synchronization\n 'proxy', // Proxy requests to upstream without caching\n]).describe('Registry synchronization strategy');\n\n/**\n * Registry Upstream Configuration\n * Configuration for upstream registry connection\n */\nexport const RegistryUpstreamSchema = z.object({\n /**\n * Upstream registry URL\n */\n url: z.string().url()\n .describe('Upstream registry endpoint'),\n \n /**\n * Synchronization policy\n */\n syncPolicy: RegistrySyncPolicySchema.default('auto'),\n \n /**\n * Sync interval in seconds (for auto sync)\n */\n syncInterval: z.number().int().min(60).optional()\n .describe('Auto-sync interval in seconds'),\n \n /**\n * Authentication credentials\n */\n auth: z.object({\n type: z.enum(['none', 'basic', 'bearer', 'api-key', 'oauth2']).default('none'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n }).optional(),\n \n /**\n * TLS/SSL configuration\n */\n tls: z.object({\n enabled: z.boolean().default(true),\n verifyCertificate: z.boolean().default(true),\n certificate: z.string().optional(),\n privateKey: z.string().optional(),\n }).optional(),\n \n /**\n * Timeout settings\n */\n timeout: z.number().int().min(1000).default(30000)\n .describe('Request timeout in milliseconds'),\n \n /**\n * Retry configuration\n */\n retry: z.object({\n maxAttempts: z.number().int().min(0).default(3),\n backoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),\n }).optional(),\n});\n\n/**\n * Registry Configuration\n * Complete registry configuration supporting federation\n */\nexport const RegistryConfigSchema = z.object({\n /**\n * Registry type\n */\n type: z.enum([\n 'public', // Public marketplace (e.g., plugins.objectstack.com)\n 'private', // Private enterprise registry\n 'hybrid', // Hybrid with upstream federation\n ]).describe('Registry deployment type'),\n \n /**\n * Upstream registries (for hybrid/private registries)\n */\n upstream: z.array(RegistryUpstreamSchema).optional()\n .describe('Upstream registries to sync from or proxy to'),\n \n /**\n * Scopes managed by this registry\n */\n scope: z.array(z.string()).optional()\n .describe('npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)'),\n \n /**\n * Default scope for new plugins\n */\n defaultScope: z.string().optional()\n .describe('Default scope prefix for new plugins'),\n \n /**\n * Registry storage configuration\n */\n storage: z.object({\n /**\n * Storage backend type\n */\n backend: z.enum(['local', 's3', 'gcs', 'azure-blob', 'oss']).default('local'),\n \n /**\n * Storage path or bucket name\n */\n path: z.string().optional(),\n \n /**\n * Credentials\n */\n credentials: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n \n /**\n * Registry visibility\n */\n visibility: z.enum(['public', 'private', 'internal']).default('private')\n .describe('Who can access this registry'),\n \n /**\n * Access control\n */\n accessControl: z.object({\n /**\n * Require authentication for read\n */\n requireAuthForRead: z.boolean().default(false),\n \n /**\n * Require authentication for write\n */\n requireAuthForWrite: z.boolean().default(true),\n \n /**\n * Allowed users/teams\n */\n allowedPrincipals: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Caching configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true),\n ttl: z.number().int().min(0).default(3600)\n .describe('Cache TTL in seconds'),\n maxSize: z.number().int().optional()\n .describe('Maximum cache size in bytes'),\n }).optional(),\n \n /**\n * Mirroring configuration (for high availability)\n */\n mirrors: z.array(z.object({\n url: z.string().url(),\n priority: z.number().int().min(1).default(1),\n })).optional()\n .describe('Mirror registries for redundancy'),\n});\n\nexport type RegistrySyncPolicy = z.infer;\nexport type RegistryUpstream = z.infer;\nexport type RegistryConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Provisioning Protocol\n *\n * Defines the schemas for the \"Register → Instant ObjectOS\" provisioning pipeline:\n * 1. User registers → ProvisioningRequest created\n * 2. Turso database created → Schema synced → Seed data applied\n * 3. Tenant status transitions: provisioning → active\n *\n * Provisioning is designed to be:\n * - **Idempotent**: Re-running the same request produces the same result\n * - **Observable**: Each step has explicit status tracking\n * - **Fast**: Target 2-5 seconds for complete provisioning\n */\n\n// ==========================================================================\n// 1. Enums & Constants\n// ==========================================================================\n\n/**\n * Tenant provisioning lifecycle status.\n */\nexport const TenantProvisioningStatusEnum = z.enum([\n 'provisioning', // Database creation in progress\n 'active', // Fully provisioned and operational\n 'suspended', // Temporarily disabled (billing, policy)\n 'failed', // Provisioning failed (requires retry or manual intervention)\n 'destroying', // Deletion in progress\n]).describe('Tenant provisioning lifecycle status');\n\nexport type TenantProvisioningStatus = z.infer;\n\n/**\n * Tenant subscription plan.\n */\nexport const TenantPlanSchema = z.enum([\n 'free', // Free tier with limited quotas\n 'pro', // Professional tier with higher quotas\n 'enterprise', // Enterprise tier with custom quotas and SLAs\n]).describe('Tenant subscription plan');\n\nexport type TenantPlan = z.infer;\n\n/**\n * Available deployment regions.\n */\nexport const TenantRegionSchema = z.enum([\n 'us-east', // US East (Virginia)\n 'us-west', // US West (Oregon)\n 'eu-west', // EU West (Ireland)\n 'eu-central', // EU Central (Frankfurt)\n 'ap-southeast',// Asia Pacific (Singapore)\n 'ap-northeast',// Asia Pacific (Tokyo)\n]).describe('Available deployment region');\n\nexport type TenantRegion = z.infer;\n\n// ==========================================================================\n// 2. Provisioning Step Tracking\n// ==========================================================================\n\n/**\n * Individual provisioning step status.\n * Tracks the progress of each step in the provisioning pipeline.\n */\nexport const ProvisioningStepSchema = z.object({\n /** Step identifier */\n name: z.string().min(1).describe('Step name (e.g., create_database, sync_schema)'),\n\n /** Step execution status */\n status: z.enum(['pending', 'running', 'completed', 'failed', 'skipped']).describe('Step status'),\n\n /** When the step started (ISO 8601) */\n startedAt: z.string().datetime().optional().describe('Step start time'),\n\n /** When the step completed (ISO 8601) */\n completedAt: z.string().datetime().optional().describe('Step completion time'),\n\n /** Duration in milliseconds */\n durationMs: z.number().int().min(0).optional().describe('Step duration in ms'),\n\n /** Error message if the step failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('Individual provisioning step status');\n\nexport type ProvisioningStep = z.infer;\n\n// ==========================================================================\n// 3. Provisioning Request & Result\n// ==========================================================================\n\n/**\n * Tenant Provisioning Request.\n * Input for creating a new tenant with its isolated database.\n */\nexport const TenantProvisioningRequestSchema = z.object({\n /** Organization ID that owns this tenant */\n orgId: z.string().min(1).describe('Organization ID'),\n\n /** Requested subscription plan */\n plan: TenantPlanSchema.default('free'),\n\n /** Preferred deployment region */\n region: TenantRegionSchema.default('us-east'),\n\n /** Optional tenant display name */\n displayName: z.string().optional().describe('Tenant display name'),\n\n /** Optional initial admin user email */\n adminEmail: z.string().email().optional().describe('Initial admin user email'),\n\n /** Optional metadata to attach to the tenant */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n}).describe('Tenant provisioning request');\n\nexport type TenantProvisioningRequest = z.infer;\n\n/**\n * Tenant Provisioning Result.\n * Output after provisioning completes (or fails).\n */\nexport const TenantProvisioningResultSchema = z.object({\n /** Unique tenant identifier */\n tenantId: z.string().min(1).describe('Provisioned tenant ID'),\n\n /** Database connection URL (libsql:// or https://) */\n connectionUrl: z.string().min(1).describe('Database connection URL'),\n\n /** Current provisioning status */\n status: TenantProvisioningStatusEnum,\n\n /** Deployment region */\n region: TenantRegionSchema,\n\n /** Active subscription plan */\n plan: TenantPlanSchema,\n\n /** Provisioning pipeline steps with status */\n steps: z.array(ProvisioningStepSchema).default([]).describe('Pipeline step statuses'),\n\n /** Total provisioning duration in milliseconds */\n totalDurationMs: z.number().int().min(0).optional().describe('Total provisioning duration'),\n\n /** Provisioned timestamp (ISO 8601) */\n provisionedAt: z.string().datetime().optional().describe('Provisioning completion time'),\n\n /** Error message if provisioning failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('Tenant provisioning result');\n\nexport type TenantProvisioningResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Deploy Bundle Protocol\n *\n * Defines the schemas for metadata-driven deployment:\n * Schema Push → Zod Validate → Diff → DDL Sync → Register\n *\n * This eliminates traditional CI/CD pipelines for schema changes.\n * A \"deploy\" is a bundle of metadata (objects, views, flows, permissions)\n * that is validated, diffed against the current state, and applied\n * as DDL migrations directly to the tenant database.\n *\n * Target: 2-5 second deploys vs. 2-15 minute traditional Docker/CI/CD.\n */\n\n// ==========================================================================\n// 1. Deploy Status\n// ==========================================================================\n\n/**\n * Deployment lifecycle status.\n */\nexport const DeployStatusEnum = z.enum([\n 'validating', // Zod schema validation in progress\n 'diffing', // Comparing desired state vs current state\n 'migrating', // Executing DDL statements\n 'registering', // Updating metadata registry\n 'ready', // Deployment complete and live\n 'failed', // Deployment failed at some stage\n 'rolling_back', // Rollback in progress\n]).describe('Deployment lifecycle status');\n\nexport type DeployStatus = z.infer;\n\n// ==========================================================================\n// 2. Deploy Diff\n// ==========================================================================\n\n/**\n * Schema change descriptor for a single entity (object/field).\n */\nexport const SchemaChangeSchema = z.object({\n /** Type of entity being changed */\n entityType: z.enum(['object', 'field', 'index', 'view', 'flow', 'permission']).describe('Entity type'),\n\n /** Name of the entity */\n entityName: z.string().min(1).describe('Entity name'),\n\n /** Parent entity name (e.g., object name for a field change) */\n parentEntity: z.string().optional().describe('Parent entity name'),\n\n /** Type of change */\n changeType: z.enum(['added', 'modified', 'removed']).describe('Change type'),\n\n /** Previous value (for modified/removed) */\n oldValue: z.unknown().optional().describe('Previous value'),\n\n /** New value (for added/modified) */\n newValue: z.unknown().optional().describe('New value'),\n}).describe('Individual schema change');\n\nexport type SchemaChange = z.infer;\n\n/**\n * Deploy Diff — what changed between current and desired state.\n */\nexport const DeployDiffSchema = z.object({\n /** List of all schema changes */\n changes: z.array(SchemaChangeSchema).default([]).describe('List of schema changes'),\n\n /** Summary counts */\n summary: z.object({\n added: z.number().int().min(0).default(0).describe('Number of added entities'),\n modified: z.number().int().min(0).default(0).describe('Number of modified entities'),\n removed: z.number().int().min(0).default(0).describe('Number of removed entities'),\n }).describe('Change summary counts'),\n\n /** Whether the diff contains breaking changes (e.g., column removal) */\n hasBreakingChanges: z.boolean().default(false).describe('Whether diff contains breaking changes'),\n}).describe('Schema diff between current and desired state');\n\nexport type DeployDiff = z.infer;\n\n// ==========================================================================\n// 3. Migration Plan\n// ==========================================================================\n\n/**\n * A single DDL migration statement.\n */\nexport const MigrationStatementSchema = z.object({\n /** SQL DDL statement to execute */\n sql: z.string().min(1).describe('SQL DDL statement'),\n\n /** Whether this statement is reversible */\n reversible: z.boolean().default(true).describe('Whether the statement can be reversed'),\n\n /** Reverse SQL statement (for rollback) */\n rollbackSql: z.string().optional().describe('Reverse SQL for rollback'),\n\n /** Execution order (lower = earlier) */\n order: z.number().int().min(0).describe('Execution order'),\n}).describe('Single DDL migration statement');\n\nexport type MigrationStatement = z.infer;\n\n/**\n * Migration Plan — ordered list of DDL statements to execute.\n */\nexport const MigrationPlanSchema = z.object({\n /** Ordered list of migration statements */\n statements: z.array(MigrationStatementSchema).default([]).describe('Ordered DDL statements'),\n\n /** SQL dialect the statements are written for */\n dialect: z.string().min(1).describe('Target SQL dialect'),\n\n /** Whether the entire plan is reversible */\n reversible: z.boolean().default(true).describe('Whether the plan can be fully rolled back'),\n\n /** Estimated execution time in milliseconds */\n estimatedDurationMs: z.number().int().min(0).optional().describe('Estimated execution time'),\n}).describe('Ordered migration plan');\n\nexport type MigrationPlan = z.infer;\n\n// ==========================================================================\n// 4. Deploy Validation\n// ==========================================================================\n\n/**\n * Validation issue found during bundle validation.\n */\nexport const DeployValidationIssueSchema = z.object({\n /** Severity of the issue */\n severity: z.enum(['error', 'warning', 'info']).describe('Issue severity'),\n\n /** Entity path where the issue was found */\n path: z.string().describe('Entity path (e.g., objects.project_task.fields.name)'),\n\n /** Human-readable issue description */\n message: z.string().describe('Issue description'),\n\n /** Zod error code if applicable */\n code: z.string().optional().describe('Validation error code'),\n}).describe('Validation issue');\n\nexport type DeployValidationIssue = z.infer;\n\n/**\n * Zod validation result for the entire deploy bundle.\n */\nexport const DeployValidationResultSchema = z.object({\n /** Whether the bundle passed validation */\n valid: z.boolean().describe('Whether the bundle is valid'),\n\n /** List of validation issues */\n issues: z.array(DeployValidationIssueSchema).default([]).describe('Validation issues'),\n\n /** Number of errors */\n errorCount: z.number().int().min(0).default(0).describe('Number of errors'),\n\n /** Number of warnings */\n warningCount: z.number().int().min(0).default(0).describe('Number of warnings'),\n}).describe('Bundle validation result');\n\nexport type DeployValidationResult = z.infer;\n\n// ==========================================================================\n// 5. Deploy Bundle & Manifest\n// ==========================================================================\n\n/**\n * Deploy Manifest — metadata about the deployment.\n */\nexport const DeployManifestSchema = z.object({\n /** Deployment version (semver) */\n version: z.string().min(1).describe('Deployment version'),\n\n /** SHA256 checksum of the bundle contents */\n checksum: z.string().optional().describe('SHA256 checksum'),\n\n /** Object definitions included in this deployment */\n objects: z.array(z.string()).default([]).describe('Object names included'),\n\n /** View definitions included */\n views: z.array(z.string()).default([]).describe('View names included'),\n\n /** Flow definitions included */\n flows: z.array(z.string()).default([]).describe('Flow names included'),\n\n /** Permission definitions included */\n permissions: z.array(z.string()).default([]).describe('Permission names included'),\n\n /** Timestamp of bundle creation (ISO 8601) */\n createdAt: z.string().datetime().optional().describe('Bundle creation time'),\n}).describe('Deployment manifest');\n\nexport type DeployManifest = z.infer;\n\n/**\n * Deploy Bundle — container for all metadata being deployed.\n * This is the primary input to the deploy pipeline.\n */\nexport const DeployBundleSchema = z.object({\n /** Bundle manifest with version and contents list */\n manifest: DeployManifestSchema,\n\n /** Object definitions (JSON-serialized ObjectStack objects) */\n objects: z.array(z.record(z.string(), z.unknown())).default([]).describe('Object definitions'),\n\n /** View definitions */\n views: z.array(z.record(z.string(), z.unknown())).default([]).describe('View definitions'),\n\n /** Flow definitions */\n flows: z.array(z.record(z.string(), z.unknown())).default([]).describe('Flow definitions'),\n\n /** Permission definitions */\n permissions: z.array(z.record(z.string(), z.unknown())).default([]).describe('Permission definitions'),\n\n /** Seed data records to populate after schema migration */\n seedData: z.array(z.record(z.string(), z.unknown())).default([]).describe('Seed data records'),\n}).describe('Deploy bundle containing all metadata for deployment');\n\nexport type DeployBundle = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * App Installation Protocol\n *\n * Defines the schemas for installing marketplace apps into tenant databases.\n * An \"app install\" injects metadata (objects, views, flows) + schema sync\n * into a tenant's isolated database.\n *\n * Install pipeline:\n * 1. Check compatibility (kernel version, existing objects, conflicts)\n * 2. Validate app manifest\n * 3. Apply schema changes (via deploy pipeline)\n * 4. Seed initial data\n * 5. Register app in tenant's metadata registry\n */\n\n// ==========================================================================\n// 1. App Manifest\n// ==========================================================================\n\n/**\n * App Manifest — describes an installable app package.\n */\nexport const AppManifestSchema = z.object({\n /** Unique app identifier (snake_case) */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('App identifier (snake_case)'),\n\n /** Display label for the app */\n label: z.string().min(1).describe('App display label'),\n\n /** App version (semver) */\n version: z.string().min(1).describe('App version (semver)'),\n\n /** App description */\n description: z.string().optional().describe('App description'),\n\n /** Minimum kernel version required */\n minKernelVersion: z.string().optional().describe('Minimum required kernel version'),\n\n /** Object definitions provided by this app */\n objects: z.array(z.string()).default([]).describe('Object names provided'),\n\n /** View definitions provided */\n views: z.array(z.string()).default([]).describe('View names provided'),\n\n /** Flow definitions provided */\n flows: z.array(z.string()).default([]).describe('Flow names provided'),\n\n /** Whether seed data is included */\n hasSeedData: z.boolean().default(false).describe('Whether app includes seed data'),\n\n /** Seed data records to populate on install */\n seedData: z.array(z.record(z.string(), z.unknown())).default([]).describe('Seed data records'),\n\n /** App dependencies (other apps that must be installed first) */\n dependencies: z.array(z.string()).default([]).describe('Required app dependencies'),\n}).describe('App manifest for marketplace installation');\n\nexport type AppManifest = z.infer;\n\n// ==========================================================================\n// 2. Compatibility Check\n// ==========================================================================\n\n/**\n * App Compatibility Check Result.\n */\nexport const AppCompatibilityCheckSchema = z.object({\n /** Whether the app is compatible with the current environment */\n compatible: z.boolean().describe('Whether the app is compatible'),\n\n /** Compatibility issues found */\n issues: z.array(z.object({\n /** Issue severity */\n severity: z.enum(['error', 'warning']).describe('Issue severity'),\n /** Issue description */\n message: z.string().describe('Issue description'),\n /** Issue category */\n category: z.enum([\n 'kernel_version', // Kernel version mismatch\n 'object_conflict', // Object name already exists\n 'dependency_missing', // Required dependency not installed\n 'quota_exceeded', // Tenant quota would be exceeded\n ]).describe('Issue category'),\n })).default([]).describe('Compatibility issues'),\n}).describe('App compatibility check result');\n\nexport type AppCompatibilityCheck = z.infer;\n\n// ==========================================================================\n// 3. Install Request & Result\n// ==========================================================================\n\n/**\n * App Install Request.\n */\nexport const AppInstallRequestSchema = z.object({\n /** Target tenant ID */\n tenantId: z.string().min(1).describe('Target tenant ID'),\n\n /** App identifier to install */\n appId: z.string().min(1).describe('App identifier'),\n\n /** Optional configuration overrides */\n configOverrides: z.record(z.string(), z.unknown()).optional().describe('Configuration overrides'),\n\n /** Whether to skip seed data */\n skipSeedData: z.boolean().default(false).describe('Skip seed data population'),\n}).describe('App install request');\n\nexport type AppInstallRequest = z.infer;\n\n/**\n * App Install Result.\n */\nexport const AppInstallResultSchema = z.object({\n /** Whether the installation succeeded */\n success: z.boolean().describe('Whether installation succeeded'),\n\n /** App identifier that was installed */\n appId: z.string().describe('Installed app identifier'),\n\n /** App version installed */\n version: z.string().describe('Installed app version'),\n\n /** Objects created or updated */\n installedObjects: z.array(z.string()).default([]).describe('Objects created/updated'),\n\n /** Tables created in the database */\n createdTables: z.array(z.string()).default([]).describe('Database tables created'),\n\n /** Number of seed records inserted */\n seededRecords: z.number().int().min(0).default(0).describe('Seed records inserted'),\n\n /** Installation duration in milliseconds */\n durationMs: z.number().int().min(0).optional().describe('Installation duration'),\n\n /** Error message if installation failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('App install result');\n\nexport type AppInstallResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Package conventions and directory structure constants.\n * These define the \"Law of Location\" - where things must be in ObjectStack packages.\n * \n * These paths are the source of truth used by:\n * - ObjectOS Runtime (to locate package components)\n * - ObjectStack CLI (to scaffold and validate packages)\n * - ObjectStudio IDE (to provide intelligent navigation and validation)\n */\nexport const PKG_CONVENTIONS = {\n /**\n * Standard directories within ObjectStack packages.\n * All packages MUST follow these conventions for the runtime to locate resources.\n */\n DIRS: {\n /** \n * Location for schema definitions (Zod schemas, JSON schemas).\n * Path: src/schemas\n */\n SCHEMA: 'src/schemas',\n \n /** \n * Location for server-side code and triggers.\n * Path: src/server\n */\n SERVER: 'src/server',\n \n /** \n * Location for server-side trigger functions.\n * Path: src/triggers\n */\n TRIGGERS: 'src/triggers',\n \n /** \n * Location for client-side code.\n * Path: src/client\n */\n CLIENT: 'src/client',\n \n /** \n * Location for client-side page components.\n * Path: src/client/pages\n */\n PAGES: 'src/client/pages',\n \n /** \n * Location for static assets (images, fonts, etc.).\n * Path: assets\n */\n ASSETS: 'assets',\n },\n \n /**\n * Standard file names within ObjectStack packages.\n */\n FILES: {\n /** \n * Package manifest configuration file.\n * File: objectstack.config.ts\n */\n MANIFEST: 'objectstack.config.ts',\n \n /** \n * Main entry point for the package.\n * File: src/index.ts\n */\n ENTRY: 'src/index.ts',\n },\n} as const;\n\n/**\n * Type helper to extract directory path values.\n */\nexport type PackageDirectory = typeof PKG_CONVENTIONS.DIRS[keyof typeof PKG_CONVENTIONS.DIRS];\n\n/**\n * Type helper to extract file path values.\n */\nexport type PackageFile = typeof PKG_CONVENTIONS.FILES[keyof typeof PKG_CONVENTIONS.FILES];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * System Object Names — Protocol Layer Constants\n *\n * These constants define the canonical, protocol-level names for system objects.\n * All API calls, SDK references, permissions checks, and metadata lookups MUST use\n * these names instead of hardcoded strings or physical table names.\n *\n * The actual storage table name may differ via `ObjectSchema.tableName`.\n * The mapping between protocol name and storage name is handled by the\n * ObjectQL Engine / Driver layer.\n *\n * @example\n * ```ts\n * import { SystemObjectName } from '@objectstack/spec/system';\n *\n * // Always use the constant for API / SDK / permission references\n * const users = await engine.find(SystemObjectName.USER, { ... });\n * ```\n */\nexport const SystemObjectName = {\n /** Authentication: user identity */\n USER: 'sys_user',\n /** Authentication: active session */\n SESSION: 'sys_session',\n /** Authentication: OAuth / credential account */\n ACCOUNT: 'sys_account',\n /** Authentication: email / phone verification */\n VERIFICATION: 'sys_verification',\n /** Authentication: organization (multi-org support) */\n ORGANIZATION: 'sys_organization',\n /** Authentication: organization member */\n MEMBER: 'sys_member',\n /** Authentication: organization invitation */\n INVITATION: 'sys_invitation',\n /** Authentication: team within an organization */\n TEAM: 'sys_team',\n /** Authentication: team membership */\n TEAM_MEMBER: 'sys_team_member',\n /** Authentication: API key for programmatic access */\n API_KEY: 'sys_api_key',\n /** Authentication: two-factor authentication credentials */\n TWO_FACTOR: 'sys_two_factor',\n /** Authentication: user preferences (theme, locale, etc.) */\n USER_PREFERENCE: 'sys_user_preference',\n /** Security: role definition for RBAC */\n ROLE: 'sys_role',\n /** Security: permission set grouping */\n PERMISSION_SET: 'sys_permission_set',\n /** Audit: system audit log */\n AUDIT_LOG: 'sys_audit_log',\n /** System metadata storage */\n METADATA: 'sys_metadata',\n /** Realtime: user presence state */\n PRESENCE: 'sys_presence',\n} as const;\n\n/** Union type of all system object names */\nexport type SystemObjectName = typeof SystemObjectName[keyof typeof SystemObjectName];\n\n/**\n * System Field Names — Protocol Layer Constants\n *\n * These constants define the canonical, protocol-level names for common system fields.\n * All API calls, SDK references, and permission checks MUST use these constants\n * instead of hardcoded strings or physical column names.\n *\n * The actual storage column name may differ via `FieldSchema.columnName`.\n *\n * @example\n * ```ts\n * import { SystemFieldName } from '@objectstack/spec/system';\n *\n * // Use the constant to reference the owner field in queries\n * const myRecords = await engine.find('project', {\n * filters: [SystemFieldName.OWNER_ID, '=', currentUserId],\n * });\n * ```\n */\nexport const SystemFieldName = {\n /** Primary key */\n ID: 'id',\n /** Record creation timestamp */\n CREATED_AT: 'created_at',\n /** Record last-updated timestamp */\n UPDATED_AT: 'updated_at',\n /** Record owner (lookup to user) */\n OWNER_ID: 'owner_id',\n /** Tenant isolation key */\n TENANT_ID: 'tenant_id',\n /** Foreign key to user on session / account objects */\n USER_ID: 'user_id',\n /** Soft-delete timestamp */\n DELETED_AT: 'deleted_at',\n} as const;\n\n/** Union type of all system field names */\nexport type SystemFieldName = typeof SystemFieldName[keyof typeof SystemFieldName];\n\n/**\n * Storage Name Mapping — Protocol ↔ Physical Name Resolution\n *\n * Provides pure utility functions for resolving protocol-level names to\n * physical storage names and vice-versa.\n *\n * These helpers are intended for use inside the ObjectQL Engine and Driver layers.\n * They are intentionally stateless — they receive the object definition and return\n * the resolved name.\n */\nexport const StorageNameMapping = {\n /**\n * Resolve the physical table name for an object.\n * Priority: explicit `tableName` → auto-derived `{namespace}_{name}` → `name`.\n *\n * @param object - Object definition (at minimum `{ name: string; namespace?: string; tableName?: string }`)\n * @returns The physical table / collection name to use in storage operations.\n */\n resolveTableName(object: { name: string; namespace?: string; tableName?: string }): string {\n return object.tableName ?? (object.namespace ? `${object.namespace}_${object.name}` : object.name);\n },\n\n /**\n * Resolve the physical column name for a field.\n * Falls back to `fieldKey` when `columnName` is not set on the field.\n *\n * @param fieldKey - The protocol-level field key (snake_case identifier).\n * @param field - Field definition (at minimum `{ columnName?: string }`).\n * @returns The physical column name to use in storage operations.\n */\n resolveColumnName(fieldKey: string, field: { columnName?: string }): string {\n return field.columnName ?? fieldKey;\n },\n\n /**\n * Build a complete field-key → column-name map for an entire object.\n *\n * @param fields - The fields record from an ObjectSchema.\n * @returns A record mapping every protocol field key to its physical column name.\n */\n buildColumnMap(fields: Record): Record {\n const map: Record = {};\n for (const key of Object.keys(fields)) {\n map[key] = fields[key].columnName ?? key;\n }\n return map;\n },\n\n /**\n * Build a reverse column-name → field-key map for an entire object.\n * Useful for translating storage-layer results back to protocol-level field keys.\n *\n * @param fields - The fields record from an ObjectSchema.\n * @returns A record mapping every physical column name back to its protocol field key.\n */\n buildReverseColumnMap(fields: Record): Record {\n const map: Record = {};\n for (const key of Object.keys(fields)) {\n const col = fields[key].columnName ?? key;\n map[col] = key;\n }\n return map;\n },\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from './types.js';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport type { IServiceRegistry } from '@objectstack/spec/contracts';\n\n/**\n * Kernel state machine\n */\nexport type KernelState = 'idle' | 'initializing' | 'running' | 'stopping' | 'stopped';\n\n/**\n * ObjectKernelBase - Abstract Base Class for Microkernel\n * \n * Provides common functionality for ObjectKernel and LiteKernel:\n * - Plugin management (Map storage)\n * - Dependency resolution (topological sort)\n * - Hook/Event system\n * - Context creation\n * - State validation\n * \n * This eliminates code duplication between the implementations.\n */\nexport abstract class ObjectKernelBase {\n protected plugins: Map = new Map();\n protected services: IServiceRegistry | Map = new Map();\n protected hooks: Map void | Promise>> = new Map();\n protected state: KernelState = 'idle';\n protected logger: Logger;\n protected context!: PluginContext;\n\n constructor(logger: Logger) {\n this.logger = logger;\n }\n\n /**\n * Validate kernel state\n * @param requiredState - Required state for the operation\n * @throws Error if current state doesn't match\n */\n protected validateState(requiredState: KernelState): void {\n if (this.state !== requiredState) {\n throw new Error(\n `[Kernel] Invalid state: expected '${requiredState}', got '${this.state}'`\n );\n }\n }\n\n /**\n * Validate kernel is in idle state (for plugin registration)\n */\n protected validateIdle(): void {\n if (this.state !== 'idle') {\n throw new Error('[Kernel] Cannot register plugins after bootstrap has started');\n }\n }\n\n /**\n * Create the plugin context\n * Subclasses can override to customize context creation\n */\n protected createContext(): PluginContext {\n return {\n registerService: (name, service) => {\n if (this.services instanceof Map) {\n if (this.services.has(name)) {\n throw new Error(`[Kernel] Service '${name}' already registered`);\n }\n this.services.set(name, service);\n } else {\n // IServiceRegistry implementation\n this.services.register(name, service);\n }\n this.logger.info(`Service '${name}' registered`, { service: name });\n },\n getService: (name: string): T => {\n if (this.services instanceof Map) {\n const service = this.services.get(name);\n if (!service) {\n throw new Error(`[Kernel] Service '${name}' not found`);\n }\n return service as T;\n } else {\n // IServiceRegistry implementation\n return this.services.get(name);\n }\n },\n replaceService: (name: string, implementation: T): void => {\n if (this.services instanceof Map) {\n if (!this.services.has(name)) {\n throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`);\n }\n this.services.set(name, implementation);\n } else {\n // IServiceRegistry implementation\n if (!this.services.has(name)) {\n throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`);\n }\n this.services.register(name, implementation);\n }\n this.logger.info(`Service '${name}' replaced`, { service: name });\n },\n hook: (name, handler) => {\n if (!this.hooks.has(name)) {\n this.hooks.set(name, []);\n }\n this.hooks.get(name)!.push(handler);\n },\n trigger: async (name, ...args) => {\n const handlers = this.hooks.get(name) || [];\n for (const handler of handlers) {\n await handler(...args);\n }\n },\n getServices: () => {\n if (this.services instanceof Map) {\n return new Map(this.services);\n } else {\n // For IServiceRegistry, we need to return the underlying Map\n // This is a compatibility method\n return new Map();\n }\n },\n logger: this.logger,\n getKernel: () => this as any,\n };\n }\n\n /**\n * Resolve plugin dependencies using topological sort\n * @returns Ordered list of plugins (dependencies first)\n */\n protected resolveDependencies(): Plugin[] {\n const resolved: Plugin[] = [];\n const visited = new Set();\n const visiting = new Set();\n\n const visit = (pluginName: string) => {\n if (visited.has(pluginName)) return;\n \n if (visiting.has(pluginName)) {\n throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`);\n }\n\n const plugin = this.plugins.get(pluginName);\n if (!plugin) {\n throw new Error(`[Kernel] Plugin '${pluginName}' not found`);\n }\n\n visiting.add(pluginName);\n\n // Visit dependencies first\n const deps = plugin.dependencies || [];\n for (const dep of deps) {\n if (!this.plugins.has(dep)) {\n throw new Error(\n `[Kernel] Dependency '${dep}' not found for plugin '${pluginName}'`\n );\n }\n visit(dep);\n }\n\n visiting.delete(pluginName);\n visited.add(pluginName);\n resolved.push(plugin);\n };\n\n // Visit all plugins\n for (const pluginName of this.plugins.keys()) {\n visit(pluginName);\n }\n\n return resolved;\n }\n\n /**\n * Run plugin init phase\n * @param plugin - Plugin to initialize\n */\n protected async runPluginInit(plugin: Plugin): Promise {\n const pluginName = plugin.name;\n this.logger.info(`Initializing plugin: ${pluginName}`);\n \n try {\n await plugin.init(this.context);\n this.logger.info(`Plugin initialized: ${pluginName}`);\n } catch (error) {\n this.logger.error(`Plugin init failed: ${pluginName}`, error as Error);\n throw error;\n }\n }\n\n /**\n * Run plugin start phase\n * @param plugin - Plugin to start\n */\n protected async runPluginStart(plugin: Plugin): Promise {\n if (!plugin.start) return;\n \n const pluginName = plugin.name;\n this.logger.info(`Starting plugin: ${pluginName}`);\n \n try {\n await plugin.start(this.context);\n this.logger.info(`Plugin started: ${pluginName}`);\n } catch (error) {\n this.logger.error(`Plugin start failed: ${pluginName}`, error as Error);\n throw error;\n }\n }\n\n /**\n * Run plugin destroy phase\n * @param plugin - Plugin to destroy\n */\n protected async runPluginDestroy(plugin: Plugin): Promise {\n if (!plugin.destroy) return;\n \n const pluginName = plugin.name;\n this.logger.info(`Destroying plugin: ${pluginName}`);\n \n try {\n await plugin.destroy();\n this.logger.info(`Plugin destroyed: ${pluginName}`);\n } catch (error) {\n this.logger.error(`Plugin destroy failed: ${pluginName}`, error as Error);\n throw error;\n }\n }\n\n /**\n * Trigger a hook with all registered handlers\n * @param name - Hook name\n * @param args - Arguments to pass to handlers\n */\n protected async triggerHook(name: string, ...args: any[]): Promise {\n const handlers = this.hooks.get(name) || [];\n this.logger.debug(`Triggering hook: ${name}`, { \n hook: name, \n handlerCount: handlers.length \n });\n \n for (const handler of handlers) {\n try {\n await handler(...args);\n } catch (error) {\n this.logger.error(`Hook handler failed: ${name}`, error as Error);\n // Continue with other handlers even if one fails\n }\n }\n }\n\n /**\n * Get current kernel state\n */\n getState(): KernelState {\n return this.state;\n }\n\n /**\n * Get all registered plugins\n */\n getPlugins(): Map {\n return new Map(this.plugins);\n }\n\n /**\n * Abstract methods to be implemented by subclasses\n */\n abstract use(plugin: Plugin): this | Promise;\n abstract bootstrap(): Promise;\n abstract destroy(): Promise;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Environment utilities for universal (Node/Browser) compatibility.\n */\n\n// Check if running in a Node.js environment\nexport const isNode = typeof process !== 'undefined' && \n process.versions != null && \n process.versions.node != null;\n\n/**\n * Safely access environment variables\n */\nexport function getEnv(key: string, defaultValue?: string): string | undefined {\n // Node.js\n if (typeof process !== 'undefined' && process.env) {\n return process.env[key] || defaultValue;\n }\n \n // Browser (Vite/Webpack replacement usually handles process.env, \n // but if not, we check safe global access)\n try {\n // @ts-ignore\n if (typeof globalThis !== 'undefined' && globalThis.process?.env) {\n // @ts-ignore\n return globalThis.process.env[key] || defaultValue;\n }\n } catch (e) {\n // Ignore access errors\n }\n \n return defaultValue;\n}\n\n/**\n * Safely exit the process if in Node.js\n */\nexport function safeExit(code: number = 0): void {\n if (isNode) {\n process.exit(code);\n }\n}\n\n/**\n * Safely get memory usage\n */\nexport function getMemoryUsage(): { heapUsed: number; heapTotal: number } {\n if (isNode) {\n return process.memoryUsage();\n }\n return { heapUsed: 0, heapTotal: 0 };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { LoggerConfig, LogLevel } from '@objectstack/spec/system';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport { isNode } from './utils/env.js';\n\n/**\n * Universal Logger Implementation\n * \n * A configurable logger that works in both browser and Node.js environments.\n * - Node.js: Uses Pino for high-performance structured logging\n * - Browser: Simple console-based implementation\n * \n * Features:\n * - Structured logging with multiple formats (json, text, pretty)\n * - Log level filtering\n * - Sensitive data redaction\n * - File logging with rotation (Node.js only via Pino)\n * - Browser console integration\n * - Distributed tracing support (traceId, spanId)\n */\nexport class ObjectLogger implements Logger {\n private config: Required> & { file?: string; rotation?: { maxSize: string; maxFiles: number }; name?: string };\n private isNode: boolean;\n private pinoLogger?: any; // Pino logger instance for Node.js\n private pinoInstance?: any; // Base Pino instance for creating child loggers\n private require?: any; // CommonJS require function for Node.js\n\n constructor(config: Partial = {}) {\n // Detect runtime environment\n this.isNode = isNode;\n\n // Set defaults\n this.config = {\n name: config.name,\n level: config.level ?? 'info',\n format: config.format ?? (this.isNode ? 'json' : 'pretty'),\n redact: config.redact ?? ['password', 'token', 'secret', 'key'],\n sourceLocation: config.sourceLocation ?? false,\n file: config.file,\n rotation: config.rotation ?? {\n maxSize: '10m',\n maxFiles: 5\n }\n };\n\n // Initialize Pino logger for Node.js\n if (this.isNode) {\n this.initPinoLogger();\n }\n }\n\n /**\n * Initialize Pino logger for Node.js\n */\n private async initPinoLogger() {\n if (!this.isNode) return;\n\n try {\n // Create require function dynamically for Node.js (avoids bundling issues in browser)\n // @ts-ignore - dynamic import of Node.js module\n const { createRequire } = await import('module');\n this.require = createRequire(import.meta.url);\n \n // Synchronous import for Pino using createRequire (works in ESM)\n const pino = this.require('pino');\n \n // Build Pino options\n const pinoOptions: any = {\n level: this.config.level,\n redact: {\n paths: this.config.redact,\n censor: '***REDACTED***'\n }\n };\n\n // Add name if provided\n if (this.config.name) {\n pinoOptions.name = this.config.name;\n }\n\n // Transport configuration for pretty printing or file output\n const targets: any[] = [];\n\n // Console transport\n if (this.config.format === 'pretty') {\n // Check if pino-pretty is available\n let hasPretty = false;\n try {\n this.require.resolve('pino-pretty');\n hasPretty = true;\n } catch (e) {\n // ignore\n }\n\n if (hasPretty) {\n targets.push({\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'SYS:standard',\n ignore: 'pid,hostname'\n },\n level: this.config.level\n });\n } else {\n console.warn('[Logger] pino-pretty not found. Install it for pretty logging: pnpm add -D pino-pretty');\n // Fallback to text/simple\n targets.push({\n target: 'pino/file',\n options: { destination: 1 },\n level: this.config.level\n });\n }\n } else if (this.config.format === 'json') {\n // JSON to stdout\n targets.push({\n target: 'pino/file',\n options: { destination: 1 }, // stdout\n level: this.config.level\n });\n } else {\n // text format (simple)\n targets.push({\n target: 'pino/file',\n options: { destination: 1 },\n level: this.config.level\n });\n }\n\n // File transport (if configured)\n if (this.config.file) {\n targets.push({\n target: 'pino/file',\n options: {\n destination: this.config.file,\n mkdir: true\n },\n level: this.config.level\n });\n }\n\n // Create transport\n if (targets.length > 0) {\n pinoOptions.transport = targets.length === 1 ? targets[0] : { targets };\n }\n\n // Create Pino logger\n this.pinoInstance = pino(pinoOptions);\n this.pinoLogger = this.pinoInstance;\n\n } catch (error) {\n // Fallback to console if Pino is not available\n console.warn('[Logger] Pino not available, falling back to console:', error);\n this.pinoLogger = null;\n }\n }\n\n /**\n * Redact sensitive keys from context object (for browser)\n */\n private redactSensitive(obj: any): any {\n if (!obj || typeof obj !== 'object') return obj;\n\n const redacted = Array.isArray(obj) ? [...obj] : { ...obj };\n\n for (const key in redacted) {\n const lowerKey = key.toLowerCase();\n const shouldRedact = this.config.redact.some((pattern: string) => \n lowerKey.includes(pattern.toLowerCase())\n );\n\n if (shouldRedact) {\n redacted[key] = '***REDACTED***';\n } else if (typeof redacted[key] === 'object' && redacted[key] !== null) {\n redacted[key] = this.redactSensitive(redacted[key]);\n }\n }\n\n return redacted;\n }\n\n /**\n * Format log entry for browser\n */\n private formatBrowserLog(level: LogLevel, message: string, context?: Record): string {\n if (this.config.format === 'json') {\n return JSON.stringify({\n timestamp: new Date().toISOString(),\n level,\n message,\n ...context\n });\n }\n\n if (this.config.format === 'text') {\n const parts = [new Date().toISOString(), level.toUpperCase(), message];\n if (context && Object.keys(context).length > 0) {\n parts.push(JSON.stringify(context));\n }\n return parts.join(' | ');\n }\n\n // Pretty format\n const levelColors: Record = {\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n fatal: '\\x1b[35m', // Magenta\n silent: ''\n };\n const reset = '\\x1b[0m';\n const color = levelColors[level] || '';\n\n let output = `${color}[${level.toUpperCase()}]${reset} ${message}`;\n \n if (context && Object.keys(context).length > 0) {\n output += ` ${JSON.stringify(context, null, 2)}`;\n }\n\n return output;\n }\n\n /**\n * Log using browser console\n */\n private logBrowser(level: LogLevel, message: string, context?: Record, error?: Error) {\n const redactedContext = context ? this.redactSensitive(context) : undefined;\n const mergedContext = error ? { ...redactedContext, error: { message: error.message, stack: error.stack } } : redactedContext;\n \n const formatted = this.formatBrowserLog(level, message, mergedContext);\n \n const consoleMethod = level === 'debug' ? 'debug' :\n level === 'info' ? 'log' :\n level === 'warn' ? 'warn' :\n level === 'error' || level === 'fatal' ? 'error' :\n 'log';\n \n console[consoleMethod](formatted);\n }\n\n /**\n * Public logging methods\n */\n debug(message: string, meta?: Record): void {\n if (this.isNode && this.pinoLogger) {\n this.pinoLogger.debug(meta || {}, message);\n } else {\n this.logBrowser('debug', message, meta);\n }\n }\n\n info(message: string, meta?: Record): void {\n if (this.isNode && this.pinoLogger) {\n this.pinoLogger.info(meta || {}, message);\n } else {\n this.logBrowser('info', message, meta);\n }\n }\n\n warn(message: string, meta?: Record): void {\n if (this.isNode && this.pinoLogger) {\n this.pinoLogger.warn(meta || {}, message);\n } else {\n this.logBrowser('warn', message, meta);\n }\n }\n\n error(message: string, errorOrMeta?: Error | Record, meta?: Record): void {\n let error: Error | undefined;\n let context: Record = {};\n\n if (errorOrMeta instanceof Error) {\n error = errorOrMeta;\n context = meta || {};\n } else {\n context = errorOrMeta || {};\n }\n\n if (this.isNode && this.pinoLogger) {\n const errorContext = error ? { err: error, ...context } : context;\n this.pinoLogger.error(errorContext, message);\n } else {\n this.logBrowser('error', message, context, error);\n }\n }\n\n fatal(message: string, errorOrMeta?: Error | Record, meta?: Record): void {\n let error: Error | undefined;\n let context: Record = {};\n\n if (errorOrMeta instanceof Error) {\n error = errorOrMeta;\n context = meta || {};\n } else {\n context = errorOrMeta || {};\n }\n\n if (this.isNode && this.pinoLogger) {\n const errorContext = error ? { err: error, ...context } : context;\n this.pinoLogger.fatal(errorContext, message);\n } else {\n this.logBrowser('fatal', message, context, error);\n }\n }\n\n /**\n * Create a child logger with additional context\n * Note: Child loggers share the parent's Pino instance\n */\n child(context: Record): ObjectLogger {\n const childLogger = new ObjectLogger(this.config);\n \n // For Node.js with Pino, create a Pino child logger\n if (this.isNode && this.pinoInstance) {\n childLogger.pinoLogger = this.pinoInstance.child(context);\n childLogger.pinoInstance = this.pinoInstance;\n }\n\n return childLogger;\n }\n\n /**\n * Set trace context for distributed tracing\n */\n withTrace(traceId: string, spanId?: string): ObjectLogger {\n return this.child({ traceId, spanId });\n }\n\n /**\n * Cleanup resources\n */\n async destroy(): Promise {\n if (this.pinoLogger && this.pinoLogger.flush) {\n await new Promise((resolve) => {\n this.pinoLogger.flush(() => resolve());\n });\n }\n }\n\n /**\n * Compatibility method for console.log usage\n */\n log(message: string, ...args: any[]): void {\n this.info(message, args.length > 0 ? { args } : undefined);\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(config?: Partial): ObjectLogger {\n return new ObjectLogger(config);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from './types.js';\nimport { createLogger, ObjectLogger } from './logger.js';\nimport type { LoggerConfig } from '@objectstack/spec/system';\nimport { ServiceRequirementDef } from '@objectstack/spec/system';\nimport { PluginLoader, PluginMetadata, ServiceLifecycle, ServiceFactory, PluginStartupResult } from './plugin-loader.js';\nimport { isNode, safeExit } from './utils/env.js';\nimport { CORE_FALLBACK_FACTORIES } from './fallbacks/index.js';\n\n/**\n * Enhanced Kernel Configuration\n */\nexport interface ObjectKernelConfig {\n logger?: Partial;\n \n /** Default plugin startup timeout in milliseconds */\n defaultStartupTimeout?: number;\n \n /** Whether to enable graceful shutdown */\n gracefulShutdown?: boolean;\n \n /** Graceful shutdown timeout in milliseconds */\n shutdownTimeout?: number;\n \n /** Whether to rollback on startup failure */\n rollbackOnFailure?: boolean;\n \n /** Whether to skip strict system requirement validation (Critical for testing) */\n skipSystemValidation?: boolean;\n}\n\n/**\n * Enhanced ObjectKernel with Advanced Plugin Management\n * \n * Extends the basic ObjectKernel with:\n * - Async plugin loading with validation\n * - Version compatibility checking\n * - Plugin signature verification\n * - Configuration validation (Zod)\n * - Factory-based dependency injection\n * - Service lifecycle management (singleton/transient/scoped)\n * - Circular dependency detection\n * - Lazy loading services\n * - Graceful shutdown\n * - Plugin startup timeout control\n * - Startup failure rollback\n * - Plugin health checks\n */\nexport class ObjectKernel {\n private plugins: Map = new Map();\n private services: Map = new Map();\n private hooks: Map void | Promise>> = new Map();\n private state: 'idle' | 'initializing' | 'running' | 'stopping' | 'stopped' = 'idle';\n private logger: ObjectLogger;\n private context: PluginContext;\n private pluginLoader: PluginLoader;\n private config: ObjectKernelConfig;\n private startedPlugins: Set = new Set();\n private pluginStartTimes: Map = new Map();\n private shutdownHandlers: Array<() => Promise> = [];\n\n constructor(config: ObjectKernelConfig = {}) {\n this.config = {\n defaultStartupTimeout: 30000, // 30 seconds\n gracefulShutdown: true,\n shutdownTimeout: 60000, // 60 seconds\n rollbackOnFailure: true,\n ...config,\n };\n\n this.logger = createLogger(config.logger);\n this.pluginLoader = new PluginLoader(this.logger);\n \n // Initialize context\n this.context = {\n registerService: (name, service) => {\n this.registerService(name, service);\n },\n getService: (name: string) => {\n // 1. Try direct service map first (synchronous cache)\n const service = this.services.get(name);\n if (service) {\n return service as T;\n }\n\n // 2. Try to get from plugin loader cache (Sync access to factories)\n const loaderService = this.pluginLoader.getServiceInstance(name);\n if (loaderService) {\n // Cache it locally for faster next access\n this.services.set(name, loaderService);\n return loaderService;\n }\n\n // 3. Try to get from plugin loader (support async factories)\n try {\n const service = this.pluginLoader.getService(name);\n if (service instanceof Promise) {\n // If we found it in the loader but not in the sync map, it's likely a factory-based service or still loading\n // We must silence any potential rejection from this promise since we are about to throw our own error\n // and abandon the promise. Without this, Node.js will crash with \"Unhandled Promise Rejection\".\n service.catch(() => {});\n throw new Error(`Service '${name}' is async - use await`);\n }\n return service as T;\n } catch (error: any) {\n if (error.message?.includes('is async')) {\n throw error;\n }\n \n // Re-throw critical factory errors instead of masking them as \"not found\"\n // If the error came from the factory execution (e.g. database connection failed), we must see it.\n // \"Service '${name}' not found\" comes from PluginLoader.getService fallback.\n const isNotFoundError = error.message === `Service '${name}' not found`;\n \n if (!isNotFoundError) {\n throw error;\n }\n\n throw new Error(`[Kernel] Service '${name}' not found`);\n }\n },\n replaceService: (name: string, implementation: T): void => {\n const hasService = this.services.has(name) || this.pluginLoader.hasService(name);\n if (!hasService) {\n throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`);\n }\n this.services.set(name, implementation);\n this.pluginLoader.replaceService(name, implementation);\n this.logger.info(`Service '${name}' replaced`, { service: name });\n },\n hook: (name, handler) => {\n if (!this.hooks.has(name)) {\n this.hooks.set(name, []);\n }\n this.hooks.get(name)!.push(handler);\n },\n trigger: async (name, ...args) => {\n const handlers = this.hooks.get(name) || [];\n for (const handler of handlers) {\n await handler(...args);\n }\n },\n getServices: () => {\n return new Map(this.services);\n },\n logger: this.logger,\n getKernel: () => this as any, // Type compatibility\n };\n\n this.pluginLoader.setContext(this.context);\n\n // Register shutdown handler\n if (this.config.gracefulShutdown) {\n this.registerShutdownSignals();\n }\n }\n\n /**\n * Register a plugin with enhanced validation\n */\n async use(plugin: Plugin): Promise {\n if (this.state !== 'idle') {\n throw new Error('[Kernel] Cannot register plugins after bootstrap has started');\n }\n\n // Load plugin through enhanced loader\n const result = await this.pluginLoader.loadPlugin(plugin);\n \n if (!result.success || !result.plugin) {\n throw new Error(`Failed to load plugin: ${plugin.name} - ${result.error?.message}`);\n }\n\n const pluginMeta = result.plugin;\n this.plugins.set(pluginMeta.name, pluginMeta);\n \n this.logger.info(`Plugin registered: ${pluginMeta.name}@${pluginMeta.version}`, {\n plugin: pluginMeta.name,\n version: pluginMeta.version,\n });\n\n return this;\n }\n\n /**\n * Register a service instance directly\n */\n registerService(name: string, service: T): this {\n if (this.services.has(name)) {\n throw new Error(`[Kernel] Service '${name}' already registered`);\n }\n this.services.set(name, service);\n this.pluginLoader.registerService(name, service);\n this.logger.info(`Service '${name}' registered`, { service: name });\n return this;\n }\n\n /**\n * Register a service factory with lifecycle management\n */\n registerServiceFactory(\n name: string,\n factory: ServiceFactory,\n lifecycle: ServiceLifecycle = ServiceLifecycle.SINGLETON,\n dependencies?: string[]\n ): this {\n this.pluginLoader.registerServiceFactory({\n name,\n factory,\n lifecycle,\n dependencies,\n });\n return this;\n }\n\n /**\n * Pre-inject in-memory fallbacks for 'core' services that were not registered\n * by plugins during Phase 1. Called before Phase 2 so that all core services\n * (e.g. 'metadata', 'cache', 'queue') are resolvable via ctx.getService()\n * when plugin start() methods execute.\n */\n private preInjectCoreFallbacks() {\n if (this.config.skipSystemValidation) return;\n for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) {\n if (criticality !== 'core') continue;\n const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName);\n if (!hasService) {\n const factory = CORE_FALLBACK_FACTORIES[serviceName];\n if (factory) {\n const fallback = factory();\n this.registerService(serviceName, fallback);\n this.logger.debug(`[Kernel] Pre-injected in-memory fallback for '${serviceName}' before Phase 2`);\n }\n }\n }\n }\n\n /**\n * Validate Critical System Requirements\n */\n private validateSystemRequirements() {\n if (this.config.skipSystemValidation) {\n this.logger.debug('System requirement validation skipped');\n return;\n }\n\n this.logger.debug('Validating system service requirements...');\n const missingServices: string[] = [];\n const missingCoreServices: string[] = [];\n \n // Iterate through all defined requirements\n for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) {\n const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName);\n \n if (!hasService) {\n if (criticality === 'required') {\n this.logger.error(`CRITICAL: Required service missing: ${serviceName}`);\n missingServices.push(serviceName);\n } else if (criticality === 'core') {\n // Auto-inject in-memory fallback if available\n const factory = CORE_FALLBACK_FACTORIES[serviceName];\n if (factory) {\n const fallback = factory();\n this.registerService(serviceName, fallback);\n this.logger.warn(`Service '${serviceName}' not provided — using in-memory fallback`);\n } else {\n this.logger.warn(`CORE: Core service missing, functionality may be degraded: ${serviceName}`);\n missingCoreServices.push(serviceName);\n }\n } else {\n this.logger.info(`Info: Optional service not present: ${serviceName}`);\n }\n }\n }\n\n if (missingServices.length > 0) {\n const errorMsg = `System failed to start. Missing critical services: ${missingServices.join(', ')}`;\n this.logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n if (missingCoreServices.length > 0) {\n this.logger.warn(`System started with degraded capabilities. Missing core services: ${missingCoreServices.join(', ')}`);\n }\n \n this.logger.info('System requirement check passed');\n }\n\n /**\n * Bootstrap the kernel with enhanced features\n */\n async bootstrap(): Promise {\n if (this.state !== 'idle') {\n throw new Error('[Kernel] Kernel already bootstrapped');\n }\n\n this.state = 'initializing';\n this.logger.info('Bootstrap started');\n\n try {\n // Check for circular dependencies\n const cycles = this.pluginLoader.detectCircularDependencies();\n if (cycles.length > 0) {\n this.logger.warn('Circular service dependencies detected:', { cycles });\n }\n\n // Resolve plugin dependencies\n const orderedPlugins = this.resolveDependencies();\n\n // Phase 1: Init - Plugins register services\n this.logger.info('Phase 1: Init plugins');\n for (const plugin of orderedPlugins) {\n await this.initPluginWithTimeout(plugin);\n }\n\n // Pre-inject in-memory fallbacks for 'core' services that were not\n // registered by any plugin during Phase 1. This ensures services like\n // 'metadata', 'cache', 'queue', etc. are always available when plugins\n // call ctx.getService() during their start() methods.\n this.preInjectCoreFallbacks();\n\n // Phase 2: Start - Plugins execute business logic\n this.logger.info('Phase 2: Start plugins');\n this.state = 'running';\n \n for (const plugin of orderedPlugins) {\n const result = await this.startPluginWithTimeout(plugin);\n \n if (!result.success) {\n this.logger.error(`Plugin startup failed: ${plugin.name}`, result.error);\n \n if (this.config.rollbackOnFailure) {\n this.logger.warn('Rolling back started plugins...');\n await this.rollbackStartedPlugins();\n throw new Error(`Plugin ${plugin.name} failed to start - rollback complete`);\n }\n }\n }\n\n // Phase 3: Trigger kernel:ready hook\n this.validateSystemRequirements(); // Final check before ready\n this.logger.debug('Triggering kernel:ready hook');\n await this.context.trigger('kernel:ready');\n\n this.logger.info('✅ Bootstrap complete');\n } catch (error) {\n this.state = 'stopped';\n throw error;\n }\n }\n\n /**\n * Graceful shutdown with timeout\n */\n async shutdown(): Promise {\n if (this.state === 'stopped' || this.state === 'stopping') {\n this.logger.warn('Kernel already stopped or stopping');\n return;\n }\n\n if (this.state !== 'running') {\n throw new Error('[Kernel] Kernel not running');\n }\n\n this.state = 'stopping';\n this.logger.info('Graceful shutdown started');\n\n try {\n // Create shutdown promise with timeout\n const shutdownPromise = this.performShutdown();\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error('Shutdown timeout exceeded'));\n }, this.config.shutdownTimeout);\n });\n\n // Race between shutdown and timeout\n await Promise.race([shutdownPromise, timeoutPromise]);\n\n this.state = 'stopped';\n this.logger.info('✅ Graceful shutdown complete');\n } catch (error) {\n this.logger.error('Shutdown error - forcing stop', error as Error);\n this.state = 'stopped';\n throw error;\n } finally {\n // Cleanup logger resources\n await this.logger.destroy();\n }\n }\n\n /**\n * Check health of a specific plugin\n */\n async checkPluginHealth(pluginName: string): Promise {\n return await this.pluginLoader.checkPluginHealth(pluginName);\n }\n\n /**\n * Check health of all plugins\n */\n async checkAllPluginsHealth(): Promise> {\n const results = new Map();\n \n for (const pluginName of this.plugins.keys()) {\n const health = await this.checkPluginHealth(pluginName);\n results.set(pluginName, health);\n }\n \n return results;\n }\n\n /**\n * Get plugin startup metrics\n */\n getPluginMetrics(): Map {\n return new Map(this.pluginStartTimes);\n }\n\n /**\n * Get a service (sync helper)\n */\n getService(name: string): T {\n return this.context.getService(name);\n }\n\n /**\n * Get a service asynchronously (supports factories)\n */\n async getServiceAsync(name: string, scopeId?: string): Promise {\n return await this.pluginLoader.getService(name, scopeId);\n }\n\n /**\n * Check if kernel is running\n */\n isRunning(): boolean {\n return this.state === 'running';\n }\n\n /**\n * Get kernel state\n */\n getState(): string {\n return this.state;\n }\n\n // Private methods\n\n private async initPluginWithTimeout(plugin: PluginMetadata): Promise {\n const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout!;\n \n this.logger.debug(`Init: ${plugin.name}`, { plugin: plugin.name });\n \n const initPromise = plugin.init(this.context);\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(`Plugin ${plugin.name} init timeout after ${timeout}ms`));\n }, timeout);\n });\n\n await Promise.race([initPromise, timeoutPromise]);\n }\n\n private async startPluginWithTimeout(plugin: PluginMetadata): Promise {\n if (!plugin.start) {\n return { success: true, pluginName: plugin.name };\n }\n\n const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout!;\n const startTime = Date.now();\n \n this.logger.debug(`Start: ${plugin.name}`, { plugin: plugin.name });\n \n try {\n const startPromise = plugin.start(this.context);\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(`Plugin ${plugin.name} start timeout after ${timeout}ms`));\n }, timeout);\n });\n\n await Promise.race([startPromise, timeoutPromise]);\n \n const duration = Date.now() - startTime;\n this.startedPlugins.add(plugin.name);\n this.pluginStartTimes.set(plugin.name, duration);\n \n this.logger.debug(`Plugin started: ${plugin.name} (${duration}ms)`);\n \n return {\n success: true,\n pluginName: plugin.name,\n startTime: duration,\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n const isTimeout = (error as Error).message.includes('timeout');\n \n return {\n success: false,\n pluginName: plugin.name,\n error: error as Error,\n startTime: duration,\n timedOut: isTimeout,\n };\n }\n }\n\n private async rollbackStartedPlugins(): Promise {\n const pluginsToRollback = Array.from(this.startedPlugins).reverse();\n \n for (const pluginName of pluginsToRollback) {\n const plugin = this.plugins.get(pluginName);\n if (plugin?.destroy) {\n try {\n this.logger.debug(`Rollback: ${pluginName}`);\n await plugin.destroy();\n } catch (error) {\n this.logger.error(`Rollback failed for ${pluginName}`, error as Error);\n }\n }\n }\n \n this.startedPlugins.clear();\n }\n\n private async performShutdown(): Promise {\n // Trigger shutdown hook\n await this.context.trigger('kernel:shutdown');\n\n // Destroy plugins in reverse order\n const orderedPlugins = Array.from(this.plugins.values()).reverse();\n for (const plugin of orderedPlugins) {\n if (plugin.destroy) {\n this.logger.debug(`Destroy: ${plugin.name}`, { plugin: plugin.name });\n try {\n await plugin.destroy();\n } catch (error) {\n this.logger.error(`Error destroying plugin ${plugin.name}`, error as Error);\n }\n }\n }\n\n // Execute custom shutdown handlers\n for (const handler of this.shutdownHandlers) {\n try {\n await handler();\n } catch (error) {\n this.logger.error('Shutdown handler error', error as Error);\n }\n }\n }\n\n private resolveDependencies(): PluginMetadata[] {\n const resolved: PluginMetadata[] = [];\n const visited = new Set();\n const visiting = new Set();\n\n const visit = (pluginName: string) => {\n if (visited.has(pluginName)) return;\n \n if (visiting.has(pluginName)) {\n throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`);\n }\n\n const plugin = this.plugins.get(pluginName);\n if (!plugin) {\n throw new Error(`[Kernel] Plugin '${pluginName}' not found`);\n }\n\n visiting.add(pluginName);\n\n // Visit dependencies first\n const deps = plugin.dependencies || [];\n for (const dep of deps) {\n if (!this.plugins.has(dep)) {\n throw new Error(`[Kernel] Dependency '${dep}' not found for plugin '${pluginName}'`);\n }\n visit(dep);\n }\n\n visiting.delete(pluginName);\n visited.add(pluginName);\n resolved.push(plugin);\n };\n\n // Visit all plugins\n for (const pluginName of this.plugins.keys()) {\n visit(pluginName);\n }\n\n return resolved;\n }\n\n private registerShutdownSignals(): void {\n const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGQUIT'];\n let shutdownInProgress = false;\n \n const handleShutdown = async (signal: string) => {\n if (shutdownInProgress) {\n this.logger.warn(`Shutdown already in progress, ignoring ${signal}`);\n return;\n }\n \n shutdownInProgress = true;\n this.logger.info(`Received ${signal} - initiating graceful shutdown`);\n \n try {\n await this.shutdown();\n safeExit(0);\n } catch (error) {\n this.logger.error('Shutdown failed', error as Error);\n safeExit(1);\n }\n };\n \n if (isNode) {\n for (const signal of signals) {\n process.on(signal, () => handleShutdown(signal));\n }\n }\n }\n\n /**\n * Register a custom shutdown handler\n */\n onShutdown(handler: () => Promise): void {\n this.shutdownHandlers.push(handler);\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport type { PluginMetadata } from '../plugin-loader.js';\n\n/**\n * Plugin Configuration Validator\n * \n * Validates plugin configurations against Zod schemas to ensure:\n * 1. Type safety - all config values have correct types\n * 2. Business rules - values meet constraints (min/max, regex, etc.)\n * 3. Required fields - all mandatory configuration is provided\n * 4. Default values - missing optional fields get defaults\n * \n * Architecture:\n * - Uses Zod for runtime validation\n * - Provides detailed error messages with field paths\n * - Supports nested configuration objects\n * - Allows partial validation for incremental updates\n * \n * Usage:\n * ```typescript\n * const validator = new PluginConfigValidator(logger);\n * const validConfig = validator.validatePluginConfig(plugin, userConfig);\n * ```\n */\nexport class PluginConfigValidator {\n private logger: Logger;\n \n constructor(logger: Logger) {\n this.logger = logger;\n }\n \n /**\n * Validate plugin configuration against its Zod schema\n * \n * @param plugin - Plugin metadata with configSchema\n * @param config - User-provided configuration\n * @returns Validated and typed configuration\n * @throws Error with detailed validation errors\n */\n validatePluginConfig(plugin: PluginMetadata, config: any): T {\n if (!plugin.configSchema) {\n this.logger.debug(`Plugin ${plugin.name} has no config schema - skipping validation`);\n return config as T;\n }\n \n try {\n // Use Zod to parse and validate\n const validatedConfig = plugin.configSchema.parse(config);\n \n this.logger.debug(`✅ Plugin config validated: ${plugin.name}`, {\n plugin: plugin.name,\n configKeys: Object.keys(config || {}).length,\n });\n \n return validatedConfig as T;\n } catch (error) {\n if (error instanceof z.ZodError) {\n const formattedErrors = this.formatZodErrors(error);\n const errorMessage = [\n `Plugin ${plugin.name} configuration validation failed:`,\n ...formattedErrors.map(e => ` - ${e.path}: ${e.message}`),\n ].join('\\n');\n \n this.logger.error(errorMessage, undefined, {\n plugin: plugin.name,\n errors: formattedErrors,\n });\n \n throw new Error(errorMessage);\n }\n \n // Re-throw other errors\n throw error;\n }\n }\n \n /**\n * Validate partial configuration (for incremental updates)\n * \n * @param plugin - Plugin metadata\n * @param partialConfig - Partial configuration to validate\n * @returns Validated partial configuration\n */\n validatePartialConfig(plugin: PluginMetadata, partialConfig: any): Partial {\n if (!plugin.configSchema) {\n return partialConfig as Partial;\n }\n \n try {\n // Use Zod's partial() method for partial validation\n // Cast to ZodObject to access partial() method\n const partialSchema = (plugin.configSchema as any).partial();\n const validatedConfig = partialSchema.parse(partialConfig);\n \n this.logger.debug(`✅ Partial config validated: ${plugin.name}`);\n return validatedConfig as Partial;\n } catch (error) {\n if (error instanceof z.ZodError) {\n const formattedErrors = this.formatZodErrors(error);\n const errorMessage = [\n `Plugin ${plugin.name} partial configuration validation failed:`,\n ...formattedErrors.map(e => ` - ${e.path}: ${e.message}`),\n ].join('\\n');\n \n throw new Error(errorMessage);\n }\n \n throw error;\n }\n }\n \n /**\n * Get default configuration from schema\n * \n * @param plugin - Plugin metadata\n * @returns Default configuration object\n */\n getDefaultConfig(plugin: PluginMetadata): T | undefined {\n if (!plugin.configSchema) {\n return undefined;\n }\n \n try {\n // Parse empty object to get defaults\n const defaults = plugin.configSchema.parse({});\n this.logger.debug(`Default config extracted: ${plugin.name}`);\n return defaults as T;\n } catch (error) {\n // Schema may require some fields - return undefined\n this.logger.debug(`No default config available: ${plugin.name}`);\n return undefined;\n }\n }\n \n /**\n * Check if configuration is valid without throwing\n * \n * @param plugin - Plugin metadata\n * @param config - Configuration to check\n * @returns True if valid, false otherwise\n */\n isConfigValid(plugin: PluginMetadata, config: any): boolean {\n if (!plugin.configSchema) {\n return true;\n }\n \n const result = plugin.configSchema.safeParse(config);\n return result.success;\n }\n \n /**\n * Get configuration errors without throwing\n * \n * @param plugin - Plugin metadata\n * @param config - Configuration to check\n * @returns Array of validation errors, or empty array if valid\n */\n getConfigErrors(plugin: PluginMetadata, config: any): Array<{path: string; message: string}> {\n if (!plugin.configSchema) {\n return [];\n }\n \n const result = plugin.configSchema.safeParse(config);\n \n if (result.success) {\n return [];\n }\n \n return this.formatZodErrors(result.error);\n }\n \n // Private methods\n \n private formatZodErrors(error: z.ZodError): Array<{path: string; message: string}> {\n return error.issues.map((e: z.ZodIssue) => ({\n path: e.path.join('.') || 'root',\n message: e.message,\n }));\n }\n}\n\n/**\n * Create a plugin config validator\n * \n * @param logger - Logger instance\n * @returns Plugin config validator\n */\nexport function createPluginConfigValidator(logger: Logger): PluginConfigValidator {\n return new PluginConfigValidator(logger);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from './types.js';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport { z } from 'zod';\nimport { PluginConfigValidator } from './security/plugin-config-validator.js';\n\n/**\n * Service Lifecycle Types\n * Defines how services are instantiated and managed\n */\nexport enum ServiceLifecycle {\n /** Single instance shared across all requests */\n SINGLETON = 'singleton',\n /** New instance created for each request */\n TRANSIENT = 'transient',\n /** New instance per scope (e.g., per HTTP request) */\n SCOPED = 'scoped',\n}\n\n/**\n * Service Factory\n * Function that creates a service instance\n */\nexport type ServiceFactory = (ctx: PluginContext) => T | Promise;\n\n/**\n * Service Registration Options\n */\nexport interface ServiceRegistration {\n name: string;\n factory: ServiceFactory;\n lifecycle: ServiceLifecycle;\n dependencies?: string[];\n}\n\n/**\n * Plugin Metadata with Enhanced Features\n */\nexport interface PluginMetadata extends Plugin {\n /** Semantic version (e.g., \"1.0.0\") */\n version: string;\n \n /** Configuration schema for validation */\n configSchema?: z.ZodSchema;\n \n /** Plugin signature for security verification */\n signature?: string;\n \n /** Plugin health check function */\n healthCheck?(): Promise;\n \n /** Startup timeout in milliseconds (default: 30000) */\n startupTimeout?: number;\n \n /** Whether plugin supports hot reload */\n hotReloadable?: boolean;\n}\n\n/**\n * Plugin Health Status\n */\nexport interface PluginHealthStatus {\n healthy: boolean;\n message?: string;\n details?: Record;\n lastCheck?: Date;\n}\n\n/**\n * Plugin Load Result\n */\nexport interface PluginLoadResult {\n success: boolean;\n plugin?: PluginMetadata;\n error?: Error;\n loadTime?: number;\n}\n\n/**\n * Plugin Startup Result\n */\nexport interface PluginStartupResult {\n success: boolean;\n pluginName: string;\n startTime?: number;\n error?: Error;\n timedOut?: boolean;\n}\n\n/**\n * Version Compatibility Result\n */\nexport interface VersionCompatibility {\n compatible: boolean;\n pluginVersion: string;\n requiredVersion?: string;\n message?: string;\n}\n\n/**\n * Enhanced Plugin Loader\n * Provides advanced plugin loading capabilities with validation, security, and lifecycle management\n */\nexport class PluginLoader {\n private logger: Logger;\n private context?: PluginContext;\n private configValidator: PluginConfigValidator;\n private loadedPlugins: Map = new Map();\n private serviceFactories: Map = new Map();\n private serviceInstances: Map = new Map();\n private scopedServices: Map> = new Map();\n private creating: Set = new Set();\n\n constructor(logger: Logger) {\n this.logger = logger;\n this.configValidator = new PluginConfigValidator(logger);\n }\n\n /**\n * Set the plugin context for service factories\n */\n setContext(context: PluginContext): void {\n this.context = context;\n }\n\n /**\n * Get a synchronous service instance if it exists (Sync Helper)\n */\n getServiceInstance(name: string): T | undefined {\n return this.serviceInstances.get(name) as T;\n }\n\n /**\n * Load a plugin asynchronously with validation\n */\n async loadPlugin(plugin: Plugin): Promise {\n const startTime = Date.now();\n \n try {\n this.logger.info(`Loading plugin: ${plugin.name}`);\n \n // Convert to PluginMetadata\n const metadata = this.toPluginMetadata(plugin);\n \n // Validate plugin structure\n this.validatePluginStructure(metadata);\n \n // Check version compatibility\n const versionCheck = this.checkVersionCompatibility(metadata);\n if (!versionCheck.compatible) {\n throw new Error(`Version incompatible: ${versionCheck.message}`);\n }\n \n // Validate configuration if schema is provided\n if (metadata.configSchema) {\n this.validatePluginConfig(metadata);\n }\n \n // Verify signature if provided\n if (metadata.signature) {\n await this.verifyPluginSignature(metadata);\n }\n \n // Store loaded plugin\n this.loadedPlugins.set(metadata.name, metadata);\n \n const loadTime = Date.now() - startTime;\n this.logger.info(`Plugin loaded: ${plugin.name} (${loadTime}ms)`);\n \n return {\n success: true,\n plugin: metadata,\n loadTime,\n };\n } catch (error) {\n this.logger.error(`Failed to load plugin: ${plugin.name}`, error as Error);\n return {\n success: false,\n error: error as Error,\n loadTime: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Register a service with factory function\n */\n registerServiceFactory(registration: ServiceRegistration): void {\n if (this.serviceFactories.has(registration.name)) {\n throw new Error(`Service factory '${registration.name}' already registered`);\n }\n \n this.serviceFactories.set(registration.name, registration);\n this.logger.debug(`Service factory registered: ${registration.name} (${registration.lifecycle})`);\n }\n\n /**\n * Get or create a service instance based on lifecycle type\n */\n async getService(name: string, scopeId?: string): Promise {\n const registration = this.serviceFactories.get(name);\n \n if (!registration) {\n // Fall back to static service instances\n const instance = this.serviceInstances.get(name);\n if (!instance) {\n throw new Error(`Service '${name}' not found`);\n }\n return instance as T;\n }\n \n switch (registration.lifecycle) {\n case ServiceLifecycle.SINGLETON:\n return await this.getSingletonService(registration);\n \n case ServiceLifecycle.TRANSIENT:\n return await this.createTransientService(registration);\n \n case ServiceLifecycle.SCOPED:\n if (!scopeId) {\n throw new Error(`Scope ID required for scoped service '${name}'`);\n }\n return await this.getScopedService(registration, scopeId);\n \n default:\n throw new Error(`Unknown service lifecycle: ${registration.lifecycle}`);\n }\n }\n\n /**\n * Register a static service instance (legacy support)\n */\n registerService(name: string, service: any): void {\n if (this.serviceInstances.has(name)) {\n throw new Error(`Service '${name}' already registered`);\n }\n this.serviceInstances.set(name, service);\n }\n\n /**\n * Replace an existing service instance.\n * Used by optimization plugins to swap kernel internals.\n * @throws Error if service does not exist\n */\n replaceService(name: string, service: any): void {\n if (!this.hasService(name)) {\n throw new Error(`Service '${name}' not found`);\n }\n this.serviceInstances.set(name, service);\n }\n\n /**\n * Check if a service is registered (either as instance or factory)\n */\n hasService(name: string): boolean {\n return this.serviceInstances.has(name) || this.serviceFactories.has(name);\n }\n\n /**\n * Detect circular dependencies in service factories\n * Note: This only detects cycles in service dependencies, not plugin dependencies.\n * Plugin dependency cycles are detected in the kernel's resolveDependencies method.\n */\n detectCircularDependencies(): string[] {\n const cycles: string[] = [];\n const visited = new Set();\n const visiting = new Set();\n \n const visit = (serviceName: string, path: string[] = []) => {\n if (visiting.has(serviceName)) {\n const cycle = [...path, serviceName].join(' -> ');\n cycles.push(cycle);\n return;\n }\n \n if (visited.has(serviceName)) {\n return;\n }\n \n visiting.add(serviceName);\n \n const registration = this.serviceFactories.get(serviceName);\n if (registration?.dependencies) {\n for (const dep of registration.dependencies) {\n visit(dep, [...path, serviceName]);\n }\n }\n \n visiting.delete(serviceName);\n visited.add(serviceName);\n };\n \n for (const serviceName of this.serviceFactories.keys()) {\n visit(serviceName);\n }\n \n return cycles;\n }\n\n /**\n * Check plugin health\n */\n async checkPluginHealth(pluginName: string): Promise {\n const plugin = this.loadedPlugins.get(pluginName);\n \n if (!plugin) {\n return {\n healthy: false,\n message: 'Plugin not found',\n lastCheck: new Date(),\n };\n }\n \n if (!plugin.healthCheck) {\n return {\n healthy: true,\n message: 'No health check defined',\n lastCheck: new Date(),\n };\n }\n \n try {\n const status = await plugin.healthCheck();\n return {\n ...status,\n lastCheck: new Date(),\n };\n } catch (error) {\n return {\n healthy: false,\n message: `Health check failed: ${(error as Error).message}`,\n lastCheck: new Date(),\n };\n }\n }\n\n /**\n * Clear scoped services for a scope\n */\n clearScope(scopeId: string): void {\n this.scopedServices.delete(scopeId);\n this.logger.debug(`Cleared scope: ${scopeId}`);\n }\n\n /**\n * Get all loaded plugins\n */\n getLoadedPlugins(): Map {\n return new Map(this.loadedPlugins);\n }\n\n // Private helper methods\n\n private toPluginMetadata(plugin: Plugin): PluginMetadata {\n // Fix: Do not use object spread {...plugin} as it destroys the prototype chain for Class-based plugins.\n // Instead, cast the original object and inject default values if missing.\n const metadata = plugin as PluginMetadata;\n \n if (!metadata.version) {\n metadata.version = '0.0.0';\n }\n \n return metadata;\n }\n\n private validatePluginStructure(plugin: PluginMetadata): void {\n if (!plugin.name) {\n throw new Error('Plugin name is required');\n }\n \n if (!plugin.init) {\n throw new Error('Plugin init function is required');\n }\n \n if (!this.isValidSemanticVersion(plugin.version)) {\n throw new Error(`Invalid semantic version: ${plugin.version}`);\n }\n }\n\n private checkVersionCompatibility(plugin: PluginMetadata): VersionCompatibility {\n // Basic semantic version compatibility check\n // In a real implementation, this would check against kernel version\n const version = plugin.version;\n \n if (!this.isValidSemanticVersion(version)) {\n return {\n compatible: false,\n pluginVersion: version,\n message: 'Invalid semantic version format',\n };\n }\n \n return {\n compatible: true,\n pluginVersion: version,\n };\n }\n\n private isValidSemanticVersion(version: string): boolean {\n const semverRegex = /^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?(\\+[a-zA-Z0-9.-]+)?$/;\n return semverRegex.test(version);\n }\n\n private validatePluginConfig(plugin: PluginMetadata, config?: any): void {\n if (!plugin.configSchema) {\n return;\n }\n\n if (config === undefined) {\n // In loadPlugin, we often don't have the config yet.\n // We skip validation here or valid against empty object if schema allows?\n // For now, let's keep the logging behavior but note it's delegating\n this.logger.debug(`Plugin ${plugin.name} has configuration schema (config validation postponed)`);\n return;\n }\n\n this.configValidator.validatePluginConfig(plugin, config);\n }\n\n private async verifyPluginSignature(plugin: PluginMetadata): Promise {\n if (!plugin.signature) {\n return;\n }\n \n // Plugin signature verification is now implemented in PluginSignatureVerifier\n // This is a placeholder that logs the verification would happen\n // The actual verification should be done by the caller with proper security config\n this.logger.debug(`Plugin ${plugin.name} has signature (use PluginSignatureVerifier for verification)`);\n }\n\n private async getSingletonService(registration: ServiceRegistration): Promise {\n let instance = this.serviceInstances.get(registration.name);\n \n if (!instance) {\n // Create instance (would need context)\n instance = await this.createServiceInstance(registration);\n this.serviceInstances.set(registration.name, instance);\n this.logger.debug(`Singleton service created: ${registration.name}`);\n }\n \n return instance as T;\n }\n\n private async createTransientService(registration: ServiceRegistration): Promise {\n const instance = await this.createServiceInstance(registration);\n this.logger.debug(`Transient service created: ${registration.name}`);\n return instance as T;\n }\n\n private async getScopedService(registration: ServiceRegistration, scopeId: string): Promise {\n if (!this.scopedServices.has(scopeId)) {\n this.scopedServices.set(scopeId, new Map());\n }\n \n const scope = this.scopedServices.get(scopeId)!;\n let instance = scope.get(registration.name);\n \n if (!instance) {\n instance = await this.createServiceInstance(registration);\n scope.set(registration.name, instance);\n this.logger.debug(`Scoped service created: ${registration.name} (scope: ${scopeId})`);\n }\n \n return instance as T;\n }\n\n private async createServiceInstance(registration: ServiceRegistration): Promise {\n if (!this.context) {\n throw new Error(`[PluginLoader] Context not set - cannot create service '${registration.name}'`);\n }\n\n if (this.creating.has(registration.name)) {\n throw new Error(`Circular dependency detected: ${Array.from(this.creating).join(' -> ')} -> ${registration.name}`);\n }\n\n this.creating.add(registration.name);\n try {\n return await registration.factory(this.context);\n } finally {\n this.creating.delete(registration.name);\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * In-memory Map-backed cache fallback.\n *\n * Implements the ICacheService contract with basic get/set/delete/has/clear\n * and TTL expiry. Used by ObjectKernel as an automatic fallback when no\n * real cache plugin (e.g. Redis) is registered.\n */\nexport function createMemoryCache() {\n const store = new Map();\n let hits = 0;\n let misses = 0;\n return {\n _fallback: true, _serviceName: 'cache',\n async get(key: string): Promise {\n const entry = store.get(key);\n if (!entry || (entry.expires && Date.now() > entry.expires)) {\n store.delete(key);\n misses++;\n return undefined;\n }\n hits++;\n return entry.value as T;\n },\n async set(key: string, value: T, ttl?: number): Promise {\n store.set(key, { value, expires: ttl ? Date.now() + ttl * 1000 : undefined });\n },\n async delete(key: string): Promise { return store.delete(key); },\n async has(key: string): Promise { return store.has(key); },\n async clear(): Promise { store.clear(); },\n async stats() { return { hits, misses, keyCount: store.size }; },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * In-memory publish/subscribe queue fallback.\n *\n * Implements the IQueueService contract with synchronous in-process delivery.\n * Used by ObjectKernel as an automatic fallback when no real queue plugin\n * (e.g. BullMQ / RabbitMQ) is registered.\n */\nexport function createMemoryQueue() {\n const handlers = new Map();\n let msgId = 0;\n return {\n _fallback: true, _serviceName: 'queue',\n async publish(queue: string, data: T): Promise {\n const id = `fallback-msg-${++msgId}`;\n const fns = handlers.get(queue) ?? [];\n for (const fn of fns) fn({ id, data, attempts: 1, timestamp: Date.now() });\n return id;\n },\n async subscribe(queue: string, handler: (msg: any) => Promise): Promise {\n handlers.set(queue, [...(handlers.get(queue) ?? []), handler]);\n },\n async unsubscribe(queue: string): Promise { handlers.delete(queue); },\n async getQueueSize(): Promise { return 0; },\n async purge(queue: string): Promise { handlers.delete(queue); },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * In-memory job scheduler fallback.\n *\n * Implements the IJobService contract with basic schedule/cancel/trigger\n * operations. Used by ObjectKernel as an automatic fallback when no real\n * job plugin (e.g. Agenda / BullMQ) is registered.\n */\nexport function createMemoryJob() {\n const jobs = new Map();\n return {\n _fallback: true, _serviceName: 'job',\n async schedule(name: string, schedule: any, handler: any): Promise { jobs.set(name, { schedule, handler }); },\n async cancel(name: string): Promise { jobs.delete(name); },\n async trigger(name: string, data?: unknown): Promise {\n const job = jobs.get(name);\n if (job?.handler) await job.handler({ jobId: name, data });\n },\n async getExecutions(): Promise { return []; },\n async listJobs(): Promise { return [...jobs.keys()]; },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Resolve a locale code against available locales with fallback.\n *\n * Fallback chain:\n * 1. Exact match (e.g. `zh-CN` → `zh-CN`)\n * 2. Case-insensitive match (e.g. `zh-cn` → `zh-CN`)\n * 3. Base language match (e.g. `zh-CN` → `zh`)\n * 4. Variant expansion (e.g. `zh` → `zh-CN`)\n *\n * Returns the matched locale code, or `undefined` when no match is found.\n */\nexport function resolveLocale(requestedLocale: string, availableLocales: string[]): string | undefined {\n if (availableLocales.length === 0) return undefined;\n\n // 1. Exact match\n if (availableLocales.includes(requestedLocale)) return requestedLocale;\n\n // 2. Case-insensitive match\n const lower = requestedLocale.toLowerCase();\n const caseMatch = availableLocales.find(l => l.toLowerCase() === lower);\n if (caseMatch) return caseMatch;\n\n // 3. Base language match (zh-CN → zh)\n const baseLang = requestedLocale.split('-')[0].toLowerCase();\n const baseMatch = availableLocales.find(l => l.toLowerCase() === baseLang);\n if (baseMatch) return baseMatch;\n\n // 4. Variant expansion (zh → zh-CN, zh-TW, etc. — first match wins)\n const variantMatch = availableLocales.find(l => l.split('-')[0].toLowerCase() === baseLang);\n if (variantMatch) return variantMatch;\n\n return undefined;\n}\n\n/**\n * In-memory i18n service fallback.\n *\n * Implements the II18nService contract with basic translate/load/getLocales\n * operations. Used by ObjectKernel as an automatic fallback when no real\n * i18n plugin (e.g. I18nServicePlugin) is registered.\n *\n * Supports runtime translation loading, locale management, and\n * locale code fallback (e.g. `zh` → `zh-CN`).\n * Does not load files from disk — operates purely in-memory.\n */\nexport function createMemoryI18n() {\n const translations = new Map>();\n let defaultLocale = 'en';\n\n /**\n * Resolve a dot-notation key from a nested object.\n */\n function resolveKey(data: Record, key: string): string | undefined {\n const parts = key.split('.');\n let current: unknown = data;\n for (const part of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n current = (current as Record)[part];\n }\n return typeof current === 'string' ? current : undefined;\n }\n\n /**\n * Find translation data for a locale, with fallback resolution.\n */\n function resolveTranslations(locale: string): Record | undefined {\n // Exact match\n if (translations.has(locale)) return translations.get(locale);\n\n // Locale fallback (zh → zh-CN, en-us → en-US, etc.)\n const resolved = resolveLocale(locale, [...translations.keys()]);\n if (resolved) return translations.get(resolved);\n\n return undefined;\n }\n\n return {\n _fallback: true, _serviceName: 'i18n',\n\n t(key: string, locale: string, params?: Record): string {\n const data = resolveTranslations(locale) ?? translations.get(defaultLocale);\n const value = data ? resolveKey(data, key) : undefined;\n if (value == null) return key;\n if (!params) return value;\n // Interpolation format: {{paramName}} — matches FileI18nAdapter convention\n return value.replace(/\\{\\{(\\w+)\\}\\}/g, (_, name) => String(params[name] ?? `{{${name}}}`));\n },\n\n getTranslations(locale: string): Record {\n return resolveTranslations(locale) ?? {};\n },\n\n loadTranslations(locale: string, data: Record): void {\n const existing = translations.get(locale) ?? {};\n translations.set(locale, { ...existing, ...data });\n },\n\n getLocales(): string[] {\n return [...translations.keys()];\n },\n\n getDefaultLocale(): string {\n return defaultLocale;\n },\n\n setDefaultLocale(locale: string): void {\n defaultLocale = locale;\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * In-memory metadata service fallback.\n *\n * Implements the IMetadataService contract with a simple Map-of-Maps store.\n * Used by ObjectKernel as an automatic fallback when no real metadata plugin\n * (e.g. MetadataPlugin with file-system persistence) is registered.\n */\nexport function createMemoryMetadata() {\n // type -> name -> data\n const store = new Map>();\n\n function getTypeMap(type: string): Map {\n let map = store.get(type);\n if (!map) {\n map = new Map();\n store.set(type, map);\n }\n return map;\n }\n\n return {\n _fallback: true, _serviceName: 'metadata',\n async register(type: string, name: string, data: any): Promise {\n getTypeMap(type).set(name, data);\n },\n async get(type: string, name: string): Promise {\n return getTypeMap(type).get(name);\n },\n async list(type: string): Promise {\n return Array.from(getTypeMap(type).values());\n },\n async unregister(type: string, name: string): Promise {\n getTypeMap(type).delete(name);\n },\n async exists(type: string, name: string): Promise {\n return getTypeMap(type).has(name);\n },\n async listNames(type: string): Promise {\n return Array.from(getTypeMap(type).keys());\n },\n async getObject(name: string): Promise {\n return getTypeMap('object').get(name);\n },\n async listObjects(): Promise {\n return Array.from(getTypeMap('object').values());\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { createMemoryCache } from './memory-cache.js';\nimport { createMemoryQueue } from './memory-queue.js';\nimport { createMemoryJob } from './memory-job.js';\nimport { createMemoryI18n } from './memory-i18n.js';\nimport { createMemoryMetadata } from './memory-metadata.js';\n\nexport { createMemoryCache } from './memory-cache.js';\nexport { createMemoryQueue } from './memory-queue.js';\nexport { createMemoryJob } from './memory-job.js';\nexport { createMemoryI18n, resolveLocale } from './memory-i18n.js';\nexport { createMemoryMetadata } from './memory-metadata.js';\n\n/**\n * Map of core-criticality service names to their in-memory fallback factories.\n * Used by ObjectKernel.validateSystemRequirements() to auto-inject fallbacks\n * when no real plugin provides the service.\n */\nexport const CORE_FALLBACK_FACTORIES: Record Record> = {\n metadata: createMemoryMetadata,\n cache: createMemoryCache,\n queue: createMemoryQueue,\n job: createMemoryJob,\n i18n: createMemoryI18n,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin } from './types.js';\nimport { createLogger, ObjectLogger } from './logger.js';\nimport type { LoggerConfig } from '@objectstack/spec/system';\nimport { ObjectKernelBase } from './kernel-base.js';\n\n/**\n * ObjectKernel - MiniKernel Architecture\n * \n * A highly modular, plugin-based microkernel that:\n * - Manages plugin lifecycle (init, start, destroy)\n * - Provides dependency injection via service registry\n * - Implements event/hook system for inter-plugin communication\n * - Handles dependency resolution (topological sort)\n * - Provides configurable logging for server and browser\n * \n * Core philosophy:\n * - Business logic is completely separated into plugins\n * - Kernel only manages lifecycle, DI, and hooks\n * - Plugins are loaded as equal building blocks\n */\nexport class LiteKernel extends ObjectKernelBase {\n constructor(config?: { logger?: Partial }) {\n const logger = createLogger(config?.logger);\n super(logger);\n \n // Initialize context after logger is created\n this.context = this.createContext();\n }\n\n /**\n * Register a plugin\n * @param plugin - Plugin instance\n */\n use(plugin: Plugin): this {\n this.validateIdle();\n\n const pluginName = plugin.name;\n if (this.plugins.has(pluginName)) {\n throw new Error(`[Kernel] Plugin '${pluginName}' already registered`);\n }\n\n this.plugins.set(pluginName, plugin);\n return this;\n }\n\n /**\n * Bootstrap the kernel\n * 1. Resolve dependencies (topological sort)\n * 2. Init phase - plugins register services\n * 3. Start phase - plugins execute business logic\n * 4. Trigger 'kernel:ready' hook\n */\n async bootstrap(): Promise {\n this.validateState('idle');\n\n this.state = 'initializing';\n this.logger.info('Bootstrap started');\n\n // Resolve dependencies\n const orderedPlugins = this.resolveDependencies();\n\n // Phase 1: Init - Plugins register services\n this.logger.info('Phase 1: Init plugins');\n for (const plugin of orderedPlugins) {\n await this.runPluginInit(plugin);\n }\n\n // Phase 2: Start - Plugins execute business logic\n this.logger.info('Phase 2: Start plugins');\n this.state = 'running';\n \n for (const plugin of orderedPlugins) {\n await this.runPluginStart(plugin);\n }\n\n // Trigger ready hook\n await this.triggerHook('kernel:ready');\n this.logger.info('✅ Bootstrap complete', { \n pluginCount: this.plugins.size \n });\n }\n\n /**\n * Shutdown the kernel\n * Calls destroy on all plugins in reverse order\n */\n async shutdown(): Promise {\n await this.destroy();\n }\n\n /**\n * Graceful shutdown - destroy all plugins in reverse order\n */\n async destroy(): Promise {\n if (this.state === 'stopped') {\n this.logger.warn('Kernel already stopped');\n return;\n }\n\n this.state = 'stopping';\n this.logger.info('Shutdown started');\n\n // Trigger shutdown hook\n await this.triggerHook('kernel:shutdown');\n\n // Destroy plugins in reverse order\n const orderedPlugins = this.resolveDependencies();\n for (const plugin of orderedPlugins.reverse()) {\n await this.runPluginDestroy(plugin);\n }\n\n this.state = 'stopped';\n this.logger.info('✅ Shutdown complete');\n \n // Cleanup logger resources\n if (this.logger && typeof (this.logger as ObjectLogger).destroy === 'function') {\n await (this.logger as ObjectLogger).destroy();\n }\n }\n\n /**\n * Get a service from the registry\n * Convenience method for external access\n */\n getService(name: string): T {\n return this.context.getService(name);\n }\n\n /**\n * Check if kernel is running\n */\n isRunning(): boolean {\n return this.state === 'running';\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n ApiRegistry as ApiRegistryType,\n ApiRegistryEntry,\n ApiRegistryEntryInput,\n ApiEndpointRegistration,\n ConflictResolutionStrategy,\n ApiDiscoveryQuery,\n ApiDiscoveryResponse,\n} from '@objectstack/spec/api';\nimport { ApiRegistryEntrySchema } from '@objectstack/spec/api';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport { getEnv } from './utils/env.js';\n\n/**\n * API Registry Service\n * \n * Central registry for managing API endpoints across different protocols.\n * Provides endpoint registration, discovery, and conflict resolution.\n * \n * **Features:**\n * - Multi-protocol support (REST, GraphQL, OData, WebSocket, etc.)\n * - Route conflict detection with configurable resolution strategies\n * - RBAC permission integration\n * - Dynamic schema linking with ObjectQL references\n * - Plugin API registration\n * \n * **Architecture Alignment:**\n * - Kubernetes: Service Discovery & API Server\n * - AWS API Gateway: Unified API Management\n * - Kong Gateway: Plugin-based API Management\n * \n * @example\n * ```typescript\n * const registry = new ApiRegistry(logger, 'priority');\n * \n * // Register an API\n * registry.registerApi({\n * id: 'customer_api',\n * name: 'Customer API',\n * type: 'rest',\n * version: 'v1',\n * basePath: '/api/v1/customers',\n * endpoints: [...]\n * });\n * \n * // Discover APIs\n * const apis = registry.findApis({ type: 'rest', status: 'active' });\n * \n * // Get registry snapshot\n * const snapshot = registry.getRegistry();\n * ```\n */\nexport class ApiRegistry {\n private apis: Map = new Map();\n private endpoints: Map = new Map();\n private routes: Map = new Map();\n \n // Performance optimization: Auxiliary indices for O(1) lookups\n private apisByType: Map> = new Map();\n private apisByTag: Map> = new Map();\n private apisByStatus: Map> = new Map();\n \n private conflictResolution: ConflictResolutionStrategy;\n private logger: Logger;\n private version: string;\n private updatedAt: string;\n\n constructor(\n logger: Logger,\n conflictResolution: ConflictResolutionStrategy = 'error',\n version: string = '1.0.0'\n ) {\n this.logger = logger;\n this.conflictResolution = conflictResolution;\n this.version = version;\n this.updatedAt = new Date().toISOString();\n }\n\n /**\n * Register an API with its endpoints\n * \n * @param api - API registry entry\n * @throws Error if API already registered or route conflicts detected\n */\n registerApi(api: ApiRegistryEntryInput): void {\n // Check if API already exists\n if (this.apis.has(api.id)) {\n throw new Error(`[ApiRegistry] API '${api.id}' already registered`);\n }\n\n // Parse and validate the input using Zod schema\n const fullApi = ApiRegistryEntrySchema.parse(api);\n\n // Validate and register endpoints\n for (const endpoint of fullApi.endpoints) {\n this.validateEndpoint(endpoint, fullApi.id);\n }\n\n // Register the API\n this.apis.set(fullApi.id, fullApi);\n \n // Register endpoints\n for (const endpoint of fullApi.endpoints) {\n this.registerEndpoint(fullApi.id, endpoint);\n }\n\n // Update auxiliary indices for performance optimization\n this.updateIndices(fullApi);\n\n this.updatedAt = new Date().toISOString();\n this.logger.info(`API registered: ${fullApi.id}`, {\n api: fullApi.id,\n type: fullApi.type,\n endpointCount: fullApi.endpoints.length,\n });\n }\n\n /**\n * Unregister an API and all its endpoints\n * \n * @param apiId - API identifier\n */\n unregisterApi(apiId: string): void {\n const api = this.apis.get(apiId);\n if (!api) {\n throw new Error(`[ApiRegistry] API '${apiId}' not found`);\n }\n\n // Remove all endpoints\n for (const endpoint of api.endpoints) {\n this.unregisterEndpoint(apiId, endpoint.id);\n }\n\n // Remove from auxiliary indices\n this.removeFromIndices(api);\n\n // Remove the API\n this.apis.delete(apiId);\n this.updatedAt = new Date().toISOString();\n \n this.logger.info(`API unregistered: ${apiId}`);\n }\n\n /**\n * Register a single endpoint\n * \n * @param apiId - API identifier\n * @param endpoint - Endpoint registration\n * @throws Error if route conflict detected\n */\n private registerEndpoint(apiId: string, endpoint: ApiEndpointRegistration): void {\n const endpointKey = `${apiId}:${endpoint.id}`;\n \n // Check if endpoint already registered\n if (this.endpoints.has(endpointKey)) {\n throw new Error(`[ApiRegistry] Endpoint '${endpoint.id}' already registered for API '${apiId}'`);\n }\n\n // Register endpoint\n this.endpoints.set(endpointKey, { api: apiId, endpoint });\n\n // Register route if path is defined\n if (endpoint.path) {\n this.registerRoute(apiId, endpoint);\n }\n }\n\n /**\n * Unregister a single endpoint\n * \n * @param apiId - API identifier\n * @param endpointId - Endpoint identifier\n */\n private unregisterEndpoint(apiId: string, endpointId: string): void {\n const endpointKey = `${apiId}:${endpointId}`;\n const entry = this.endpoints.get(endpointKey);\n \n if (!entry) {\n return; // Already unregistered\n }\n\n // Unregister route\n if (entry.endpoint.path) {\n const routeKey = this.getRouteKey(entry.endpoint);\n this.routes.delete(routeKey);\n }\n\n // Unregister endpoint\n this.endpoints.delete(endpointKey);\n }\n\n /**\n * Register a route with conflict detection\n * \n * @param apiId - API identifier\n * @param endpoint - Endpoint registration\n * @throws Error if route conflict detected (based on strategy)\n */\n private registerRoute(apiId: string, endpoint: ApiEndpointRegistration): void {\n const routeKey = this.getRouteKey(endpoint);\n const priority = endpoint.priority ?? 100;\n const existingRoute = this.routes.get(routeKey);\n\n if (existingRoute) {\n // Route conflict detected\n this.handleRouteConflict(routeKey, apiId, endpoint, existingRoute, priority);\n return;\n }\n\n // Register route\n this.routes.set(routeKey, {\n api: apiId,\n endpointId: endpoint.id,\n priority,\n });\n }\n\n /**\n * Handle route conflict based on resolution strategy\n * \n * @param routeKey - Route key\n * @param apiId - New API identifier\n * @param endpoint - New endpoint\n * @param existingRoute - Existing route registration\n * @param newPriority - New endpoint priority\n * @throws Error if strategy is 'error'\n */\n private handleRouteConflict(\n routeKey: string,\n apiId: string,\n endpoint: ApiEndpointRegistration,\n existingRoute: { api: string; endpointId: string; priority: number },\n newPriority: number\n ): void {\n const strategy = this.conflictResolution;\n\n switch (strategy) {\n case 'error':\n throw new Error(\n `[ApiRegistry] Route conflict detected: '${routeKey}' is already registered by API '${existingRoute.api}' endpoint '${existingRoute.endpointId}'`\n );\n\n case 'priority':\n if (newPriority > existingRoute.priority) {\n // New endpoint has higher priority, replace\n this.logger.warn(\n `Route conflict: replacing '${routeKey}' (priority ${existingRoute.priority} -> ${newPriority})`,\n {\n oldApi: existingRoute.api,\n oldEndpoint: existingRoute.endpointId,\n newApi: apiId,\n newEndpoint: endpoint.id,\n }\n );\n this.routes.set(routeKey, {\n api: apiId,\n endpointId: endpoint.id,\n priority: newPriority,\n });\n } else {\n // Existing endpoint has higher priority, keep it\n this.logger.warn(\n `Route conflict: keeping existing '${routeKey}' (priority ${existingRoute.priority} >= ${newPriority})`,\n {\n existingApi: existingRoute.api,\n existingEndpoint: existingRoute.endpointId,\n newApi: apiId,\n newEndpoint: endpoint.id,\n }\n );\n }\n break;\n\n case 'first-wins':\n // Keep existing route\n this.logger.warn(\n `Route conflict: keeping first registered '${routeKey}'`,\n {\n existingApi: existingRoute.api,\n newApi: apiId,\n }\n );\n break;\n\n case 'last-wins':\n // Replace with new route\n this.logger.warn(\n `Route conflict: replacing with last registered '${routeKey}'`,\n {\n oldApi: existingRoute.api,\n newApi: apiId,\n }\n );\n this.routes.set(routeKey, {\n api: apiId,\n endpointId: endpoint.id,\n priority: newPriority,\n });\n break;\n\n default:\n throw new Error(`[ApiRegistry] Unknown conflict resolution strategy: ${strategy}`);\n }\n }\n\n /**\n * Generate a unique route key for conflict detection\n * \n * NOTE: This implementation uses exact string matching for route conflict detection.\n * It works well for static paths but has limitations with parameterized routes.\n * For example, `/api/users/:id` and `/api/users/:userId` will NOT be detected as conflicts\n * even though they are semantically identical parameterized patterns. Similarly,\n * `/api/:resource/list` and `/api/:entity/list` would also not be detected as conflicting.\n * \n * For more advanced conflict detection (e.g., path-to-regexp pattern matching),\n * consider integrating with your routing library's conflict detection mechanism.\n * \n * @param endpoint - Endpoint registration\n * @returns Route key (e.g., \"GET:/api/v1/customers/:id\")\n */\n private getRouteKey(endpoint: ApiEndpointRegistration): string {\n const method = endpoint.method || 'ANY';\n return `${method}:${endpoint.path}`;\n }\n\n /**\n * Validate endpoint registration\n * \n * @param endpoint - Endpoint to validate\n * @param apiId - API identifier (for error messages)\n * @throws Error if endpoint is invalid\n */\n private validateEndpoint(endpoint: ApiEndpointRegistration, apiId: string): void {\n if (!endpoint.id) {\n throw new Error(`[ApiRegistry] Endpoint in API '${apiId}' missing 'id' field`);\n }\n\n if (!endpoint.path) {\n throw new Error(`[ApiRegistry] Endpoint '${endpoint.id}' in API '${apiId}' missing 'path' field`);\n }\n }\n\n /**\n * Get an API by ID\n * \n * @param apiId - API identifier\n * @returns API registry entry or undefined\n */\n getApi(apiId: string): ApiRegistryEntry | undefined {\n return this.apis.get(apiId);\n }\n\n /**\n * Get all registered APIs\n * \n * @returns Array of all APIs\n */\n getAllApis(): ApiRegistryEntry[] {\n return Array.from(this.apis.values());\n }\n\n /**\n * Find APIs matching query criteria\n * \n * Performance optimized with auxiliary indices for O(1) lookups on type, tags, and status.\n * \n * @param query - Discovery query parameters\n * @returns Matching APIs\n */\n findApis(query: ApiDiscoveryQuery): ApiDiscoveryResponse {\n let resultIds: Set | undefined;\n\n // Use indices for performance-optimized filtering\n // Start with the most restrictive filter to minimize subsequent filtering\n \n // Filter by type (using index for O(1) lookup)\n if (query.type) {\n const typeIds = this.apisByType.get(query.type);\n if (!typeIds || typeIds.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n resultIds = new Set(typeIds);\n }\n\n // Filter by status (using index for O(1) lookup)\n if (query.status) {\n const statusIds = this.apisByStatus.get(query.status);\n if (!statusIds || statusIds.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n \n if (resultIds) {\n // Intersect with previous results\n resultIds = new Set([...resultIds].filter(id => statusIds.has(id)));\n } else {\n resultIds = new Set(statusIds);\n }\n \n if (resultIds.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n }\n\n // Filter by tags (using index for O(M) lookup where M is number of tags)\n if (query.tags && query.tags.length > 0) {\n const tagMatches = new Set();\n \n for (const tag of query.tags) {\n const tagIds = this.apisByTag.get(tag);\n if (tagIds) {\n tagIds.forEach(id => tagMatches.add(id));\n }\n }\n \n if (tagMatches.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n \n if (resultIds) {\n // Intersect with previous results\n resultIds = new Set([...resultIds].filter(id => tagMatches.has(id)));\n } else {\n resultIds = tagMatches;\n }\n \n if (resultIds.size === 0) {\n return { apis: [], total: 0, filters: query };\n }\n }\n\n // Get the actual API objects\n let results: ApiRegistryEntry[];\n if (resultIds) {\n results = Array.from(resultIds)\n .map(id => this.apis.get(id))\n .filter((api): api is ApiRegistryEntry => api !== undefined);\n } else {\n results = Array.from(this.apis.values());\n }\n\n // Apply remaining filters that don't have indices (less common filters)\n \n // Filter by plugin source\n if (query.pluginSource) {\n results = results.filter(\n (api) => api.metadata?.pluginSource === query.pluginSource\n );\n }\n\n // Filter by version\n if (query.version) {\n results = results.filter((api) => api.version === query.version);\n }\n\n // Search in name/description\n if (query.search) {\n const searchLower = query.search.toLowerCase();\n results = results.filter(\n (api) =>\n api.name.toLowerCase().includes(searchLower) ||\n (api.description && api.description.toLowerCase().includes(searchLower))\n );\n }\n\n return {\n apis: results,\n total: results.length,\n filters: query,\n };\n }\n\n /**\n * Get endpoint by API ID and endpoint ID\n * \n * @param apiId - API identifier\n * @param endpointId - Endpoint identifier\n * @returns Endpoint registration or undefined\n */\n getEndpoint(apiId: string, endpointId: string): ApiEndpointRegistration | undefined {\n const key = `${apiId}:${endpointId}`;\n return this.endpoints.get(key)?.endpoint;\n }\n\n /**\n * Find endpoint by route (method + path)\n * \n * @param method - HTTP method\n * @param path - URL path\n * @returns Endpoint registration or undefined\n */\n findEndpointByRoute(method: string, path: string): {\n api: ApiRegistryEntry;\n endpoint: ApiEndpointRegistration;\n } | undefined {\n const routeKey = `${method}:${path}`;\n const route = this.routes.get(routeKey);\n \n if (!route) {\n return undefined;\n }\n\n const api = this.apis.get(route.api);\n const endpoint = this.getEndpoint(route.api, route.endpointId);\n\n if (!api || !endpoint) {\n return undefined;\n }\n\n return { api, endpoint };\n }\n\n /**\n * Get complete registry snapshot\n * \n * @returns Current registry state\n */\n getRegistry(): ApiRegistryType {\n const apis = Array.from(this.apis.values());\n \n // Group by type\n const byType: Record = {};\n for (const api of apis) {\n if (!byType[api.type]) {\n byType[api.type] = [];\n }\n byType[api.type].push(api);\n }\n\n // Group by status\n const byStatus: Record = {};\n for (const api of apis) {\n const status = api.metadata?.status || 'active';\n if (!byStatus[status]) {\n byStatus[status] = [];\n }\n byStatus[status].push(api);\n }\n\n // Count total endpoints\n const totalEndpoints = apis.reduce(\n (sum, api) => sum + api.endpoints.length,\n 0\n );\n\n return {\n version: this.version,\n conflictResolution: this.conflictResolution,\n apis,\n totalApis: apis.length,\n totalEndpoints,\n byType,\n byStatus,\n updatedAt: this.updatedAt,\n };\n }\n\n /**\n * Clear all registered APIs\n * \n * **⚠️ SAFETY WARNING:**\n * This method clears all registered APIs and should be used with caution.\n * \n * **Usage Restrictions:**\n * - In production environments (NODE_ENV=production), a `force: true` parameter is required\n * - Primarily intended for testing and development hot-reload scenarios\n * \n * @param options - Clear options\n * @param options.force - Force clear in production environment (default: false)\n * @throws Error if called in production without force flag\n * \n * @example Safe usage in tests\n * ```typescript\n * beforeEach(() => {\n * registry.clear(); // OK in test environment\n * });\n * ```\n * \n * @example Usage in production (requires explicit force)\n * ```typescript\n * // In production, explicit force is required\n * registry.clear({ force: true });\n * ```\n */\n clear(options: { force?: boolean } = {}): void {\n const isProduction = this.isProductionEnvironment();\n \n if (isProduction && !options.force) {\n throw new Error(\n '[ApiRegistry] Cannot clear registry in production environment without force flag. ' +\n 'Use clear({ force: true }) if you really want to clear the registry.'\n );\n }\n\n this.apis.clear();\n this.endpoints.clear();\n this.routes.clear();\n \n // Clear auxiliary indices\n this.apisByType.clear();\n this.apisByTag.clear();\n this.apisByStatus.clear();\n \n this.updatedAt = new Date().toISOString();\n \n if (isProduction) {\n this.logger.warn('API registry forcefully cleared in production', { force: options.force });\n } else {\n this.logger.info('API registry cleared');\n }\n }\n\n /**\n * Get registry statistics\n * \n * @returns Registry statistics\n */\n getStats(): {\n totalApis: number;\n totalEndpoints: number;\n totalRoutes: number;\n apisByType: Record;\n endpointsByApi: Record;\n } {\n const apis = Array.from(this.apis.values());\n \n const apisByType: Record = {};\n for (const api of apis) {\n apisByType[api.type] = (apisByType[api.type] || 0) + 1;\n }\n\n const endpointsByApi: Record = {};\n for (const api of apis) {\n endpointsByApi[api.id] = api.endpoints.length;\n }\n\n return {\n totalApis: this.apis.size,\n totalEndpoints: this.endpoints.size,\n totalRoutes: this.routes.size,\n apisByType,\n endpointsByApi,\n };\n }\n\n /**\n * Update auxiliary indices when an API is registered\n * \n * @param api - API entry to index\n * @private\n * @internal\n */\n private updateIndices(api: ApiRegistryEntry): void {\n // Index by type\n this.ensureIndexSet(this.apisByType, api.type).add(api.id);\n\n // Index by status\n const status = api.metadata?.status || 'active';\n this.ensureIndexSet(this.apisByStatus, status).add(api.id);\n\n // Index by tags\n const tags = api.metadata?.tags || [];\n for (const tag of tags) {\n this.ensureIndexSet(this.apisByTag, tag).add(api.id);\n }\n }\n\n /**\n * Remove API from auxiliary indices when unregistered\n * \n * @param api - API entry to remove from indices\n * @private\n * @internal\n */\n private removeFromIndices(api: ApiRegistryEntry): void {\n // Remove from type index\n this.removeFromIndexSet(this.apisByType, api.type, api.id);\n\n // Remove from status index\n const status = api.metadata?.status || 'active';\n this.removeFromIndexSet(this.apisByStatus, status, api.id);\n\n // Remove from tag indices\n const tags = api.metadata?.tags || [];\n for (const tag of tags) {\n this.removeFromIndexSet(this.apisByTag, tag, api.id);\n }\n }\n\n /**\n * Helper to ensure an index set exists and return it\n * \n * @param map - Index map\n * @param key - Index key\n * @returns The Set for this key (created if needed)\n * @private\n * @internal\n */\n private ensureIndexSet(map: Map>, key: string): Set {\n let set = map.get(key);\n if (!set) {\n set = new Set();\n map.set(key, set);\n }\n return set;\n }\n\n /**\n * Helper to remove an ID from an index set and clean up empty sets\n * \n * @param map - Index map\n * @param key - Index key\n * @param id - API ID to remove\n * @private\n * @internal\n */\n private removeFromIndexSet(map: Map>, key: string, id: string): void {\n const set = map.get(key);\n if (set) {\n set.delete(id);\n // Clean up empty sets to avoid memory leaks\n if (set.size === 0) {\n map.delete(key);\n }\n }\n }\n\n /**\n * Check if running in production environment\n * \n * @returns true if NODE_ENV is 'production'\n * @private\n * @internal\n */\n private isProductionEnvironment(): boolean {\n return getEnv('NODE_ENV') === 'production';\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from './types.js';\nimport { ApiRegistry } from './api-registry.js';\nimport type { ConflictResolutionStrategy } from '@objectstack/spec/api';\n\n/**\n * API Registry Plugin Configuration\n */\nexport interface ApiRegistryPluginConfig {\n /**\n * Conflict resolution strategy for route conflicts\n * @default 'error'\n */\n conflictResolution?: ConflictResolutionStrategy;\n \n /**\n * Registry version\n * @default '1.0.0'\n */\n version?: string;\n}\n\n/**\n * API Registry Plugin\n * \n * Registers the API Registry service in the kernel, making it available\n * to all plugins for endpoint registration and discovery.\n * \n * **Usage:**\n * ```typescript\n * const kernel = new ObjectKernel();\n * \n * // Register API Registry Plugin\n * kernel.use(createApiRegistryPlugin({ conflictResolution: 'priority' }));\n * \n * // In other plugins, access the API Registry\n * const plugin: Plugin = {\n * name: 'my-plugin',\n * init: async (ctx) => {\n * const registry = ctx.getService('api-registry');\n * \n * // Register plugin APIs\n * registry.registerApi({\n * id: 'my_plugin_api',\n * name: 'My Plugin API',\n * type: 'rest',\n * version: 'v1',\n * basePath: '/api/v1/my-plugin',\n * endpoints: [...]\n * });\n * }\n * };\n * ```\n * \n * @param config - Plugin configuration\n * @returns Plugin instance\n */\nexport function createApiRegistryPlugin(\n config: ApiRegistryPluginConfig = {}\n): Plugin {\n const {\n conflictResolution = 'error',\n version = '1.0.0',\n } = config;\n\n return {\n name: 'com.objectstack.core.api-registry',\n type: 'standard',\n version: '1.0.0',\n\n init: async (ctx: PluginContext) => {\n // Create API Registry instance\n const registry = new ApiRegistry(\n ctx.logger,\n conflictResolution,\n version\n );\n\n // Register as a service\n ctx.registerService('api-registry', registry);\n\n ctx.logger.info('API Registry plugin initialized', {\n conflictResolution,\n version,\n });\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './adapter.js';\nexport * from './runner.js';\nexport * from './http-adapter.js';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { QA } from '@objectstack/spec';\nimport { TestExecutionAdapter } from './adapter.js';\n\nexport interface TestResult {\n scenarioId: string;\n passed: boolean;\n steps: StepResult[];\n error?: unknown;\n duration: number;\n}\n\nexport interface StepResult {\n stepName: string;\n passed: boolean;\n error?: unknown;\n output?: unknown;\n duration: number;\n}\n\nexport class TestRunner {\n constructor(private adapter: TestExecutionAdapter) {}\n\n async runSuite(suite: QA.TestSuite): Promise {\n const results: TestResult[] = [];\n for (const scenario of suite.scenarios) {\n results.push(await this.runScenario(scenario));\n }\n return results;\n }\n\n async runScenario(scenario: QA.TestScenario): Promise {\n const startTime = Date.now();\n const context: Record = {}; // Variable context\n \n // Initialize context from initial payload if needed? Currently schema doesn't have initial context prop on Scenario\n // But we defined TestContextSchema separately.\n \n // Setup\n if (scenario.setup) {\n for (const step of scenario.setup) {\n try {\n await this.runStep(step, context);\n } catch (e) {\n return {\n scenarioId: scenario.id,\n passed: false,\n steps: [],\n error: `Setup failed: ${e instanceof Error ? e.message : String(e)}`,\n duration: Date.now() - startTime\n };\n }\n }\n }\n\n const stepResults: StepResult[] = [];\n let scenarioPassed = true;\n let scenarioError: unknown = undefined;\n\n // Main Steps\n for (const step of scenario.steps) {\n const stepStartTime = Date.now();\n try {\n const output = await this.runStep(step, context);\n stepResults.push({\n stepName: step.name,\n passed: true,\n output,\n duration: Date.now() - stepStartTime\n });\n } catch (e) {\n scenarioPassed = false;\n scenarioError = e;\n stepResults.push({\n stepName: step.name,\n passed: false,\n error: e,\n duration: Date.now() - stepStartTime\n });\n break; // Stop on first failure\n }\n }\n\n // Teardown (run even if failed)\n if (scenario.teardown) {\n for (const step of scenario.teardown) {\n try {\n await this.runStep(step, context);\n } catch (e) {\n // Log teardown failure but don't override main failure if it exists\n if (scenarioPassed) {\n scenarioPassed = false;\n scenarioError = `Teardown failed: ${e instanceof Error ? e.message : String(e)}`;\n }\n }\n }\n }\n\n return {\n scenarioId: scenario.id,\n passed: scenarioPassed,\n steps: stepResults,\n error: scenarioError,\n duration: Date.now() - startTime\n };\n }\n\n private async runStep(step: QA.TestStep, context: Record): Promise {\n // 1. Resolve Variables with Context (Simple interpolation or just pass context?)\n // For now, assume adpater handles context resolution or we do basic replacement\n const resolvedAction = this.resolveVariables(step.action, context);\n\n // 2. Execute Action\n const result = await this.adapter.execute(resolvedAction, context);\n\n // 3. Capture Outputs\n if (step.capture) {\n for (const [varName, path] of Object.entries(step.capture)) {\n context[varName] = this.getValueByPath(result, path);\n }\n }\n\n // 4. Run Assertions\n if (step.assertions) {\n for (const assertion of step.assertions) {\n this.assert(result, assertion, context);\n }\n }\n\n return result;\n }\n\n private resolveVariables(action: QA.TestAction, context: Record): QA.TestAction {\n const actionStr = JSON.stringify(action);\n const resolved = actionStr.replace(/\\{\\{([^}]+)\\}\\}/g, (_match, varPath: string) => {\n const value = this.getValueByPath(context, varPath.trim());\n if (value === undefined) return _match; // Keep unresolved\n return typeof value === 'string' ? value : JSON.stringify(value);\n });\n try {\n return JSON.parse(resolved) as QA.TestAction;\n } catch {\n return action; // Fallback to original if parse fails\n }\n }\n\n private getValueByPath(obj: unknown, path: string): unknown {\n if (!path) return obj;\n const parts = path.split('.');\n let current: any = obj;\n for (const part of parts) {\n if (current === null || current === undefined) return undefined;\n current = current[part];\n }\n return current;\n }\n\n private assert(result: unknown, assertion: QA.TestAssertion, _context: Record) {\n const actual = this.getValueByPath(result, assertion.field);\n // Resolve expected value if it's a variable ref? \n const expected = assertion.expectedValue; // Simplify for now\n\n switch (assertion.operator) {\n case 'equals':\n if (actual !== expected) throw new Error(`Assertion failed: ${assertion.field} expected ${expected}, got ${actual}`);\n break;\n case 'not_equals':\n if (actual === expected) throw new Error(`Assertion failed: ${assertion.field} expected not ${expected}, got ${actual}`);\n break;\n case 'contains':\n if (Array.isArray(actual)) {\n if (!actual.includes(expected)) throw new Error(`Assertion failed: ${assertion.field} array does not contain ${expected}`);\n } else if (typeof actual === 'string') {\n if (!actual.includes(String(expected))) throw new Error(`Assertion failed: ${assertion.field} string does not contain ${expected}`);\n }\n break;\n case 'not_null':\n if (actual === null || actual === undefined) throw new Error(`Assertion failed: ${assertion.field} is null`);\n break;\n case 'is_null':\n if (actual !== null && actual !== undefined) throw new Error(`Assertion failed: ${assertion.field} is not null`);\n break;\n // ... Add other operators\n default:\n throw new Error(`Unknown assertion operator: ${assertion.operator}`);\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { QA } from '@objectstack/spec';\nimport { TestExecutionAdapter } from './adapter.js';\n\nexport class HttpTestAdapter implements TestExecutionAdapter {\n constructor(private baseUrl: string, private authToken?: string) {}\n\n async execute(action: QA.TestAction, _context: Record): Promise {\n const headers: Record = {\n 'Content-Type': 'application/json',\n };\n if (this.authToken) {\n headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n // If action.user is specified, maybe add a specific header for impersonation if supported?\n if (action.user) {\n headers['X-Run-As'] = action.user;\n }\n\n switch (action.type) {\n case 'create_record':\n return this.createRecord(action.target, action.payload || {}, headers);\n case 'update_record':\n return this.updateRecord(action.target, action.payload || {}, headers);\n case 'delete_record':\n return this.deleteRecord(action.target, action.payload || {}, headers);\n case 'read_record':\n return this.readRecord(action.target, action.payload || {}, headers);\n case 'query_records':\n return this.queryRecords(action.target, action.payload || {}, headers);\n case 'api_call':\n return this.rawApiCall(action.target, action.payload || {}, headers);\n case 'wait':\n const ms = Number(action.payload?.duration || 1000);\n return new Promise(resolve => setTimeout(() => resolve({ waited: ms }), ms));\n default:\n throw new Error(`Unsupported action type in HttpAdapter: ${action.type}`);\n }\n }\n\n private async createRecord(objectName: string, data: Record, headers: Record) {\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}`, {\n method: 'POST',\n headers,\n body: JSON.stringify(data)\n });\n return this.handleResponse(response);\n }\n\n private async updateRecord(objectName: string, data: Record, headers: Record) {\n const id = data.id;\n if (!id) throw new Error('Update record requires id in payload');\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, {\n method: 'PUT',\n headers,\n body: JSON.stringify(data)\n });\n return this.handleResponse(response);\n }\n\n private async deleteRecord(objectName: string, data: Record, headers: Record) {\n const id = data.id;\n if (!id) throw new Error('Delete record requires id in payload');\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, {\n method: 'DELETE',\n headers\n });\n return this.handleResponse(response);\n }\n\n private async readRecord(objectName: string, data: Record, headers: Record) {\n const id = data.id;\n if (!id) throw new Error('Read record requires id in payload');\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}/${id}`, {\n method: 'GET',\n headers\n });\n return this.handleResponse(response);\n }\n\n private async queryRecords(objectName: string, data: Record, headers: Record) {\n // Assuming query via POST or GraphQL-like endpoint\n const response = await fetch(`${this.baseUrl}/api/data/${objectName}/query`, {\n method: 'POST',\n headers,\n body: JSON.stringify(data)\n });\n return this.handleResponse(response);\n }\n\n private async rawApiCall(endpoint: string, data: Record, headers: Record) {\n const method = (data.method as string) || 'GET';\n const body = data.body ? JSON.stringify(data.body) : undefined;\n const url = endpoint.startsWith('http') ? endpoint : `${this.baseUrl}${endpoint}`;\n \n const response = await fetch(url, {\n method,\n headers,\n body\n });\n return this.handleResponse(response);\n }\n\n private async handleResponse(response: Response) {\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`HTTP Error ${response.status}: ${text}`);\n }\n const contentType = response.headers.get('content-type');\n if (contentType && contentType.includes('application/json')) {\n return response.json();\n }\n return response.text();\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Logger } from '@objectstack/spec/contracts';\nimport type { PluginMetadata } from '../plugin-loader.js';\n\n// Conditionally import crypto for Node.js environments\nlet cryptoModule: typeof import('crypto') | null = null;\n\n\n/**\n * Plugin Signature Configuration\n * Controls how plugin signatures are verified\n */\nexport interface PluginSignatureConfig {\n /**\n * Map of publisher IDs to their trusted public keys\n * Format: { 'com.objectstack': '-----BEGIN PUBLIC KEY-----...' }\n */\n trustedPublicKeys: Map;\n \n /**\n * Signature algorithm to use\n * - RS256: RSA with SHA-256\n * - ES256: ECDSA with SHA-256\n */\n algorithm: 'RS256' | 'ES256';\n \n /**\n * Strict mode: reject plugins without signatures\n * - true: All plugins must be signed\n * - false: Unsigned plugins are allowed with warning\n */\n strictMode: boolean;\n \n /**\n * Allow self-signed plugins in development\n */\n allowSelfSigned?: boolean;\n}\n\n/**\n * Plugin Signature Verification Result\n */\nexport interface SignatureVerificationResult {\n verified: boolean;\n error?: string;\n publisherId?: string;\n algorithm?: string;\n signedAt?: Date;\n}\n\n/**\n * Plugin Signature Verifier\n * \n * Implements cryptographic verification of plugin signatures to ensure:\n * 1. Plugin integrity - code hasn't been tampered with\n * 2. Publisher authenticity - plugin comes from trusted source\n * 3. Non-repudiation - publisher cannot deny signing\n * \n * Architecture:\n * - Uses Node.js crypto module for signature verification\n * - Supports RSA (RS256) and ECDSA (ES256) algorithms\n * - Verifies against trusted public key registry\n * - Computes hash of plugin code for integrity check\n * \n * Security Model:\n * - Public keys are pre-registered and trusted\n * - Plugin signature is verified before loading\n * - Strict mode rejects unsigned plugins\n * - Development mode allows self-signed plugins\n */\nexport class PluginSignatureVerifier {\n private config: PluginSignatureConfig;\n private logger: Logger;\n \n constructor(config: PluginSignatureConfig, logger: Logger) {\n this.config = config;\n this.logger = logger;\n \n this.validateConfig();\n }\n \n /**\n * Verify plugin signature\n * \n * @param plugin - Plugin metadata with signature\n * @returns Verification result\n * @throws Error if verification fails in strict mode\n */\n async verifyPluginSignature(plugin: PluginMetadata): Promise {\n // Handle unsigned plugins\n if (!plugin.signature) {\n return this.handleUnsignedPlugin(plugin);\n }\n \n try {\n // 1. Extract publisher ID from plugin name (reverse domain notation)\n const publisherId = this.extractPublisherId(plugin.name);\n \n // 2. Get trusted public key for publisher\n const publicKey = this.config.trustedPublicKeys.get(publisherId);\n if (!publicKey) {\n const error = `No trusted public key for publisher: ${publisherId}`;\n this.logger.warn(error, { plugin: plugin.name, publisherId });\n \n if (this.config.strictMode && !this.config.allowSelfSigned) {\n throw new Error(error);\n }\n \n return {\n verified: false,\n error,\n publisherId,\n };\n }\n \n // 3. Compute plugin code hash\n const pluginHash = this.computePluginHash(plugin);\n \n // 4. Verify signature using crypto module\n const isValid = await this.verifyCryptoSignature(\n pluginHash,\n plugin.signature,\n publicKey\n );\n \n if (!isValid) {\n const error = `Signature verification failed for plugin: ${plugin.name}`;\n this.logger.error(error, undefined, { plugin: plugin.name, publisherId });\n throw new Error(error);\n }\n \n this.logger.info(`✅ Plugin signature verified: ${plugin.name}`, {\n plugin: plugin.name,\n publisherId,\n algorithm: this.config.algorithm,\n });\n \n return {\n verified: true,\n publisherId,\n algorithm: this.config.algorithm,\n };\n \n } catch (error) {\n this.logger.error(`Signature verification error: ${plugin.name}`, error as Error);\n \n if (this.config.strictMode) {\n throw error;\n }\n \n return {\n verified: false,\n error: (error as Error).message,\n };\n }\n }\n \n /**\n * Register a trusted public key for a publisher\n */\n registerPublicKey(publisherId: string, publicKey: string): void {\n this.config.trustedPublicKeys.set(publisherId, publicKey);\n this.logger.info(`Trusted public key registered for: ${publisherId}`);\n }\n \n /**\n * Remove a trusted public key\n */\n revokePublicKey(publisherId: string): void {\n this.config.trustedPublicKeys.delete(publisherId);\n this.logger.warn(`Public key revoked for: ${publisherId}`);\n }\n \n /**\n * Get list of trusted publishers\n */\n getTrustedPublishers(): string[] {\n return Array.from(this.config.trustedPublicKeys.keys());\n }\n \n // Private methods\n \n private handleUnsignedPlugin(plugin: PluginMetadata): SignatureVerificationResult {\n if (this.config.strictMode) {\n const error = `Plugin missing signature (strict mode): ${plugin.name}`;\n this.logger.error(error, undefined, { plugin: plugin.name });\n throw new Error(error);\n }\n \n this.logger.warn(`⚠️ Plugin not signed: ${plugin.name}`, {\n plugin: plugin.name,\n recommendation: 'Consider signing plugins for production environments',\n });\n \n return {\n verified: false,\n error: 'Plugin not signed',\n };\n }\n \n private extractPublisherId(pluginName: string): string {\n // Extract publisher from reverse domain notation\n // Example: \"com.objectstack.engine.objectql\" -> \"com.objectstack\"\n const parts = pluginName.split('.');\n \n if (parts.length < 2) {\n throw new Error(`Invalid plugin name format: ${pluginName} (expected reverse domain notation)`);\n }\n \n // Return first two parts (domain reversed)\n return `${parts[0]}.${parts[1]}`;\n }\n \n private computePluginHash(plugin: PluginMetadata): string {\n // In browser environment, use SubtleCrypto\n if (typeof (globalThis as any).window !== 'undefined') {\n return this.computePluginHashBrowser(plugin);\n }\n \n // In Node.js environment, use crypto module\n return this.computePluginHashNode(plugin);\n }\n \n private computePluginHashNode(plugin: PluginMetadata): string {\n // Use pre-loaded crypto module\n if (!cryptoModule) {\n this.logger.warn('crypto module not available, using fallback hash');\n return this.computePluginHashFallback(plugin);\n }\n \n // Compute hash of plugin code\n const pluginCode = this.serializePluginCode(plugin);\n return cryptoModule.createHash('sha256').update(pluginCode).digest('hex');\n }\n \n private computePluginHashBrowser(plugin: PluginMetadata): string {\n // Browser environment - use simple hash for now\n // In production, should use SubtleCrypto for proper cryptographic hash\n this.logger.debug('Using browser hash (SubtleCrypto integration pending)');\n return this.computePluginHashFallback(plugin);\n }\n \n private computePluginHashFallback(plugin: PluginMetadata): string {\n // Simple hash fallback (not cryptographically secure)\n const pluginCode = this.serializePluginCode(plugin);\n let hash = 0;\n \n for (let i = 0; i < pluginCode.length; i++) {\n const char = pluginCode.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n \n return hash.toString(16);\n }\n \n private serializePluginCode(plugin: PluginMetadata): string {\n // Serialize plugin code for hashing\n // Include init, start, destroy functions\n const parts: string[] = [\n plugin.name,\n plugin.version,\n plugin.init.toString(),\n ];\n \n if (plugin.start) {\n parts.push(plugin.start.toString());\n }\n \n if (plugin.destroy) {\n parts.push(plugin.destroy.toString());\n }\n \n return parts.join('|');\n }\n \n private async verifyCryptoSignature(\n data: string,\n signature: string,\n publicKey: string\n ): Promise {\n // In browser environment, use SubtleCrypto\n if (typeof (globalThis as any).window !== 'undefined') {\n return this.verifyCryptoSignatureBrowser(data, signature, publicKey);\n }\n \n // In Node.js environment, use crypto module\n return this.verifyCryptoSignatureNode(data, signature, publicKey);\n }\n \n private async verifyCryptoSignatureNode(\n data: string,\n signature: string,\n publicKey: string\n ): Promise {\n if (!cryptoModule) {\n try {\n // @ts-ignore\n cryptoModule = await import('crypto');\n } catch (e) {\n // ignore\n }\n }\n\n if (!cryptoModule) {\n this.logger.error('Crypto module not available for signature verification');\n return false;\n }\n \n try {\n // Create verify object based on algorithm\n if (this.config.algorithm === 'ES256') {\n // ECDSA verification - requires lowercase 'sha256'\n const verify = cryptoModule.createVerify('sha256');\n verify.update(data);\n return verify.verify(\n {\n key: publicKey,\n format: 'pem',\n type: 'spki',\n },\n signature,\n 'base64'\n );\n } else {\n // RSA verification (RS256)\n const verify = cryptoModule.createVerify('RSA-SHA256');\n verify.update(data);\n return verify.verify(publicKey, signature, 'base64');\n }\n } catch (error) {\n this.logger.error('Signature verification failed', error as Error);\n return false;\n }\n }\n \n private async verifyCryptoSignatureBrowser(\n data: string,\n signature: string,\n publicKey: string\n ): Promise {\n try {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n this.logger.error('SubtleCrypto not available in this environment');\n return false;\n }\n\n // Decode PEM public key to raw DER bytes\n const pemBody = publicKey\n .replace(/-----BEGIN PUBLIC KEY-----/, '')\n .replace(/-----END PUBLIC KEY-----/, '')\n .replace(/\\s/g, '');\n const keyBytes = Uint8Array.from(atob(pemBody), c => c.charCodeAt(0));\n\n // Configure algorithms based on RS256 or ES256\n let importAlgorithm: { name: string; hash?: string; namedCurve?: string };\n let verifyAlgorithm: { name: string; hash?: string };\n\n if (this.config.algorithm === 'ES256') {\n importAlgorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n verifyAlgorithm = { name: 'ECDSA', hash: 'SHA-256' };\n } else {\n importAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };\n verifyAlgorithm = { name: 'RSASSA-PKCS1-v1_5' };\n }\n\n const cryptoKey = await subtle.importKey(\n 'spki',\n keyBytes,\n importAlgorithm,\n false,\n ['verify']\n );\n\n // Decode base64 signature to ArrayBuffer\n const signatureBytes = Uint8Array.from(atob(signature), c => c.charCodeAt(0));\n\n // Encode data to ArrayBuffer\n const dataBytes = new TextEncoder().encode(data);\n\n return await subtle.verify(verifyAlgorithm, cryptoKey, signatureBytes, dataBytes);\n } catch (error) {\n this.logger.error('Browser signature verification failed', error as Error);\n return false;\n }\n }\n \n private validateConfig(): void {\n if (!this.config.trustedPublicKeys || this.config.trustedPublicKeys.size === 0) {\n this.logger.warn('No trusted public keys configured - all signatures will fail');\n }\n \n if (!this.config.algorithm) {\n throw new Error('Signature algorithm must be specified');\n }\n \n if (!['RS256', 'ES256'].includes(this.config.algorithm)) {\n throw new Error(`Unsupported algorithm: ${this.config.algorithm}`);\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Logger } from '@objectstack/spec/contracts';\nimport type { PluginCapability } from '@objectstack/spec/kernel';\nimport type { PluginContext } from '../types.js';\n\n/**\n * Plugin Permissions\n * Defines what actions a plugin is allowed to perform\n */\nexport interface PluginPermissions {\n canAccessService(serviceName: string): boolean;\n canTriggerHook(hookName: string): boolean;\n canReadFile(path: string): boolean;\n canWriteFile(path: string): boolean;\n canNetworkRequest(url: string): boolean;\n}\n\n/**\n * Permission Check Result\n */\nexport interface PermissionCheckResult {\n allowed: boolean;\n reason?: string;\n capability?: string;\n}\n\n/**\n * Plugin Permission Enforcer\n * \n * Implements capability-based security model to enforce:\n * 1. Service access control - which services a plugin can use\n * 2. Hook restrictions - which hooks a plugin can trigger\n * 3. File system permissions - what files a plugin can read/write\n * 4. Network permissions - what URLs a plugin can access\n * \n * Architecture:\n * - Uses capability declarations from plugin manifest\n * - Checks permissions before allowing operations\n * - Logs all permission denials for security audit\n * - Supports allowlist and denylist patterns\n * \n * Security Model:\n * - Principle of least privilege - plugins get minimal permissions\n * - Explicit declaration - all capabilities must be declared\n * - Runtime enforcement - checks happen at operation time\n * - Audit trail - all denials are logged\n * \n * Usage:\n * ```typescript\n * const enforcer = new PluginPermissionEnforcer(logger);\n * enforcer.registerPluginPermissions(pluginName, capabilities);\n * enforcer.enforceServiceAccess(pluginName, 'database');\n * ```\n */\nexport class PluginPermissionEnforcer {\n private logger: Logger;\n private permissionRegistry: Map = new Map();\n private capabilityRegistry: Map = new Map();\n \n constructor(logger: Logger) {\n this.logger = logger;\n }\n \n /**\n * Register plugin capabilities and build permission set\n * \n * @param pluginName - Plugin identifier\n * @param capabilities - Array of capability declarations\n */\n registerPluginPermissions(pluginName: string, capabilities: PluginCapability[]): void {\n this.capabilityRegistry.set(pluginName, capabilities);\n \n const permissions: PluginPermissions = {\n canAccessService: (service) => this.checkServiceAccess(capabilities, service),\n canTriggerHook: (hook) => this.checkHookAccess(capabilities, hook),\n canReadFile: (path) => this.checkFileRead(capabilities, path),\n canWriteFile: (path) => this.checkFileWrite(capabilities, path),\n canNetworkRequest: (url) => this.checkNetworkAccess(capabilities, url),\n };\n \n this.permissionRegistry.set(pluginName, permissions);\n \n this.logger.info(`Permissions registered for plugin: ${pluginName}`, {\n plugin: pluginName,\n capabilityCount: capabilities.length,\n });\n }\n \n /**\n * Enforce service access permission\n * \n * @param pluginName - Plugin requesting access\n * @param serviceName - Service to access\n * @throws Error if permission denied\n */\n enforceServiceAccess(pluginName: string, serviceName: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canAccessService(serviceName));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot access service ${serviceName}`;\n this.logger.warn(error, {\n plugin: pluginName,\n service: serviceName,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`Service access granted: ${pluginName} -> ${serviceName}`);\n }\n \n /**\n * Enforce hook trigger permission\n * \n * @param pluginName - Plugin requesting access\n * @param hookName - Hook to trigger\n * @throws Error if permission denied\n */\n enforceHookTrigger(pluginName: string, hookName: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canTriggerHook(hookName));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot trigger hook ${hookName}`;\n this.logger.warn(error, {\n plugin: pluginName,\n hook: hookName,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`Hook trigger granted: ${pluginName} -> ${hookName}`);\n }\n \n /**\n * Enforce file read permission\n * \n * @param pluginName - Plugin requesting access\n * @param path - File path to read\n * @throws Error if permission denied\n */\n enforceFileRead(pluginName: string, path: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canReadFile(path));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot read file ${path}`;\n this.logger.warn(error, {\n plugin: pluginName,\n path,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`File read granted: ${pluginName} -> ${path}`);\n }\n \n /**\n * Enforce file write permission\n * \n * @param pluginName - Plugin requesting access\n * @param path - File path to write\n * @throws Error if permission denied\n */\n enforceFileWrite(pluginName: string, path: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canWriteFile(path));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot write file ${path}`;\n this.logger.warn(error, {\n plugin: pluginName,\n path,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`File write granted: ${pluginName} -> ${path}`);\n }\n \n /**\n * Enforce network request permission\n * \n * @param pluginName - Plugin requesting access\n * @param url - URL to access\n * @throws Error if permission denied\n */\n enforceNetworkRequest(pluginName: string, url: string): void {\n const result = this.checkPermission(pluginName, (perms) => perms.canNetworkRequest(url));\n \n if (!result.allowed) {\n const error = `Permission denied: Plugin ${pluginName} cannot access URL ${url}`;\n this.logger.warn(error, {\n plugin: pluginName,\n url,\n reason: result.reason,\n });\n throw new Error(error);\n }\n \n this.logger.debug(`Network request granted: ${pluginName} -> ${url}`);\n }\n \n /**\n * Get plugin capabilities\n * \n * @param pluginName - Plugin identifier\n * @returns Array of capabilities or undefined\n */\n getPluginCapabilities(pluginName: string): PluginCapability[] | undefined {\n return this.capabilityRegistry.get(pluginName);\n }\n \n /**\n * Get plugin permissions\n * \n * @param pluginName - Plugin identifier\n * @returns Permissions object or undefined\n */\n getPluginPermissions(pluginName: string): PluginPermissions | undefined {\n return this.permissionRegistry.get(pluginName);\n }\n \n /**\n * Revoke all permissions for a plugin\n * \n * @param pluginName - Plugin identifier\n */\n revokePermissions(pluginName: string): void {\n this.permissionRegistry.delete(pluginName);\n this.capabilityRegistry.delete(pluginName);\n this.logger.warn(`Permissions revoked for plugin: ${pluginName}`);\n }\n \n // Private methods\n \n private checkPermission(\n pluginName: string,\n check: (perms: PluginPermissions) => boolean\n ): PermissionCheckResult {\n const permissions = this.permissionRegistry.get(pluginName);\n \n if (!permissions) {\n return {\n allowed: false,\n reason: 'Plugin permissions not registered',\n };\n }\n \n const allowed = check(permissions);\n \n return {\n allowed,\n reason: allowed ? undefined : 'No matching capability found',\n };\n }\n \n private checkServiceAccess(capabilities: PluginCapability[], serviceName: string): boolean {\n // Check if plugin has capability to access this service\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for wildcard service access\n if (protocolId.includes('protocol.service.all')) {\n return true;\n }\n \n // Check for specific service protocol\n if (protocolId.includes(`protocol.service.${serviceName}`)) {\n return true;\n }\n \n // Check for service category match\n const serviceCategory = serviceName.split('.')[0];\n if (protocolId.includes(`protocol.service.${serviceCategory}`)) {\n return true;\n }\n \n return false;\n });\n }\n \n private checkHookAccess(capabilities: PluginCapability[], hookName: string): boolean {\n // Check if plugin has capability to trigger this hook\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for wildcard hook access\n if (protocolId.includes('protocol.hook.all')) {\n return true;\n }\n \n // Check for specific hook protocol\n if (protocolId.includes(`protocol.hook.${hookName}`)) {\n return true;\n }\n \n // Check for hook category match\n const hookCategory = hookName.split(':')[0];\n if (protocolId.includes(`protocol.hook.${hookCategory}`)) {\n return true;\n }\n \n return false;\n });\n }\n \n private matchGlob(pattern: string, str: string): boolean {\n const regexStr = pattern\n .split('**')\n .map(segment => {\n const escaped = segment.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return escaped.replace(/\\*/g, '[^/]*');\n })\n .join('.*');\n return new RegExp(`^${regexStr}$`).test(str);\n }\n \n private checkFileRead(capabilities: PluginCapability[], path: string): boolean {\n // Check if plugin has capability to read this file\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for file read capability\n if (protocolId.includes('protocol.filesystem.read')) {\n const paths = cap.metadata?.paths;\n if (!Array.isArray(paths) || paths.length === 0) {\n return true;\n }\n return paths.some(p => typeof p === 'string' && this.matchGlob(p, path));\n }\n \n return false;\n });\n }\n \n private checkFileWrite(capabilities: PluginCapability[], path: string): boolean {\n // Check if plugin has capability to write this file\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for file write capability\n if (protocolId.includes('protocol.filesystem.write')) {\n const paths = cap.metadata?.paths;\n if (!Array.isArray(paths) || paths.length === 0) {\n return true;\n }\n return paths.some(p => typeof p === 'string' && this.matchGlob(p, path));\n }\n \n return false;\n });\n }\n \n private checkNetworkAccess(capabilities: PluginCapability[], url: string): boolean {\n // Check if plugin has capability to access this URL\n return capabilities.some(cap => {\n const protocolId = cap.protocol.id;\n \n // Check for network capability\n if (protocolId.includes('protocol.network')) {\n const hosts = cap.metadata?.hosts;\n if (!Array.isArray(hosts) || hosts.length === 0) {\n return true;\n }\n return hosts.some(h => typeof h === 'string' && this.matchGlob(h, url));\n }\n \n return false;\n });\n }\n}\n\n/**\n * Secure Plugin Context\n * Wraps PluginContext with permission checks\n */\nexport class SecurePluginContext implements PluginContext {\n constructor(\n private pluginName: string,\n private permissionEnforcer: PluginPermissionEnforcer,\n private baseContext: PluginContext\n ) {}\n \n registerService(name: string, service: any): void {\n // No permission check for service registration (handled during init)\n this.baseContext.registerService(name, service);\n }\n \n getService(name: string): T {\n // Check permission before accessing service\n this.permissionEnforcer.enforceServiceAccess(this.pluginName, name);\n return this.baseContext.getService(name);\n }\n \n replaceService(name: string, implementation: T): void {\n // Check permission before replacing service\n this.permissionEnforcer.enforceServiceAccess(this.pluginName, name);\n this.baseContext.replaceService(name, implementation);\n }\n \n getServices(): Map {\n // Return all services (no permission check for listing)\n return this.baseContext.getServices();\n }\n \n hook(name: string, handler: (...args: any[]) => void | Promise): void {\n // No permission check for registering hooks (handled during init)\n this.baseContext.hook(name, handler);\n }\n \n async trigger(name: string, ...args: any[]): Promise {\n // Check permission before triggering hook\n this.permissionEnforcer.enforceHookTrigger(this.pluginName, name);\n await this.baseContext.trigger(name, ...args);\n }\n \n get logger() {\n return this.baseContext.logger;\n }\n \n getKernel() {\n return this.baseContext.getKernel();\n }\n}\n\n/**\n * Create a plugin permission enforcer\n * \n * @param logger - Logger instance\n * @returns Plugin permission enforcer\n */\nexport function createPluginPermissionEnforcer(logger: Logger): PluginPermissionEnforcer {\n return new PluginPermissionEnforcer(logger);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { \n Permission,\n PermissionSet,\n PermissionAction,\n ResourceType\n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from '../logger.js';\n\n/**\n * Permission Grant\n * Represents a granted permission at runtime\n */\nexport interface PermissionGrant {\n permissionId: string;\n pluginId: string;\n grantedAt: Date;\n grantedBy?: string;\n expiresAt?: Date;\n conditions?: Record;\n}\n\n/**\n * Permission Check Result\n */\nexport interface PermissionCheckResult {\n allowed: boolean;\n reason?: string;\n requiredPermission?: string;\n grantedPermissions?: string[];\n}\n\n/**\n * Plugin Permission Manager\n * \n * Manages fine-grained permissions for plugin security and access control\n */\nexport class PluginPermissionManager {\n private logger: ObjectLogger;\n \n // Plugin permission definitions\n private permissionSets = new Map();\n \n // Granted permissions (pluginId -> Set of permission IDs)\n private grants = new Map>();\n \n // Permission grant details\n private grantDetails = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'PermissionManager' });\n }\n\n /**\n * Register permission requirements for a plugin\n */\n registerPermissions(pluginId: string, permissionSet: PermissionSet): void {\n this.permissionSets.set(pluginId, permissionSet);\n \n this.logger.info('Permissions registered for plugin', { \n pluginId,\n permissionCount: permissionSet.permissions.length\n });\n }\n\n /**\n * Grant a permission to a plugin\n */\n grantPermission(\n pluginId: string,\n permissionId: string,\n grantedBy?: string,\n expiresAt?: Date\n ): void {\n // Verify permission exists in plugin's declared permissions\n const permissionSet = this.permissionSets.get(pluginId);\n if (!permissionSet) {\n throw new Error(`No permissions registered for plugin: ${pluginId}`);\n }\n\n const permission = permissionSet.permissions.find(p => p.id === permissionId);\n if (!permission) {\n throw new Error(`Permission ${permissionId} not declared by plugin ${pluginId}`);\n }\n\n // Create grant\n if (!this.grants.has(pluginId)) {\n this.grants.set(pluginId, new Set());\n }\n this.grants.get(pluginId)!.add(permissionId);\n\n // Store grant details\n const grantKey = `${pluginId}:${permissionId}`;\n this.grantDetails.set(grantKey, {\n permissionId,\n pluginId,\n grantedAt: new Date(),\n grantedBy,\n expiresAt,\n });\n\n this.logger.info('Permission granted', { \n pluginId, \n permissionId,\n grantedBy \n });\n }\n\n /**\n * Revoke a permission from a plugin\n */\n revokePermission(pluginId: string, permissionId: string): void {\n const grants = this.grants.get(pluginId);\n if (grants) {\n grants.delete(permissionId);\n \n const grantKey = `${pluginId}:${permissionId}`;\n this.grantDetails.delete(grantKey);\n\n this.logger.info('Permission revoked', { pluginId, permissionId });\n }\n }\n\n /**\n * Grant all permissions for a plugin\n */\n grantAllPermissions(pluginId: string, grantedBy?: string): void {\n const permissionSet = this.permissionSets.get(pluginId);\n if (!permissionSet) {\n throw new Error(`No permissions registered for plugin: ${pluginId}`);\n }\n\n for (const permission of permissionSet.permissions) {\n this.grantPermission(pluginId, permission.id, grantedBy);\n }\n\n this.logger.info('All permissions granted', { pluginId, grantedBy });\n }\n\n /**\n * Check if a plugin has a specific permission\n */\n hasPermission(pluginId: string, permissionId: string): boolean {\n const grants = this.grants.get(pluginId);\n if (!grants) {\n return false;\n }\n\n // Check if granted\n if (!grants.has(permissionId)) {\n return false;\n }\n\n // Check expiration\n const grantKey = `${pluginId}:${permissionId}`;\n const grantDetails = this.grantDetails.get(grantKey);\n if (grantDetails?.expiresAt && grantDetails.expiresAt < new Date()) {\n this.revokePermission(pluginId, permissionId);\n return false;\n }\n\n return true;\n }\n\n /**\n * Check if plugin can perform an action on a resource\n */\n checkAccess(\n pluginId: string,\n resource: ResourceType,\n action: PermissionAction,\n resourceId?: string\n ): PermissionCheckResult {\n const permissionSet = this.permissionSets.get(pluginId);\n if (!permissionSet) {\n return {\n allowed: false,\n reason: 'No permissions registered for plugin',\n };\n }\n\n // Find matching permissions\n const matchingPermissions = permissionSet.permissions.filter(p => {\n // Check resource type\n if (p.resource !== resource) {\n return false;\n }\n\n // Check action\n if (!p.actions.includes(action)) {\n return false;\n }\n\n // Check resource filter if specified\n if (resourceId && p.filter?.resourceIds) {\n if (!p.filter.resourceIds.includes(resourceId)) {\n return false;\n }\n }\n\n return true;\n });\n\n if (matchingPermissions.length === 0) {\n return {\n allowed: false,\n reason: `No permission found for ${action} on ${resource}`,\n };\n }\n\n // Check if any matching permission is granted\n const grantedPermissions = matchingPermissions.filter(p => \n this.hasPermission(pluginId, p.id)\n );\n\n if (grantedPermissions.length === 0) {\n return {\n allowed: false,\n reason: 'Required permissions not granted',\n requiredPermission: matchingPermissions[0].id,\n };\n }\n\n return {\n allowed: true,\n grantedPermissions: grantedPermissions.map(p => p.id),\n };\n }\n\n /**\n * Get all permissions for a plugin\n */\n getPluginPermissions(pluginId: string): Permission[] {\n const permissionSet = this.permissionSets.get(pluginId);\n return permissionSet?.permissions || [];\n }\n\n /**\n * Get granted permissions for a plugin\n */\n getGrantedPermissions(pluginId: string): string[] {\n const grants = this.grants.get(pluginId);\n return grants ? Array.from(grants) : [];\n }\n\n /**\n * Get required but not granted permissions\n */\n getMissingPermissions(pluginId: string): Permission[] {\n const permissionSet = this.permissionSets.get(pluginId);\n if (!permissionSet) {\n return [];\n }\n\n const granted = this.grants.get(pluginId) || new Set();\n \n return permissionSet.permissions.filter(p => \n p.required && !granted.has(p.id)\n );\n }\n\n /**\n * Check if all required permissions are granted\n */\n hasAllRequiredPermissions(pluginId: string): boolean {\n return this.getMissingPermissions(pluginId).length === 0;\n }\n\n /**\n * Get permission grant details\n */\n getGrantDetails(pluginId: string, permissionId: string): PermissionGrant | undefined {\n const grantKey = `${pluginId}:${permissionId}`;\n return this.grantDetails.get(grantKey);\n }\n\n /**\n * Validate permission against scope constraints\n */\n validatePermissionScope(\n permission: Permission,\n context: {\n tenantId?: string;\n userId?: string;\n resourceId?: string;\n }\n ): boolean {\n switch (permission.scope) {\n case 'global':\n return true;\n\n case 'tenant':\n return !!context.tenantId;\n\n case 'user':\n return !!context.userId;\n\n case 'resource':\n return !!context.resourceId;\n\n case 'plugin':\n return true;\n\n default:\n return false;\n }\n }\n\n /**\n * Clear all permissions for a plugin\n */\n clearPluginPermissions(pluginId: string): void {\n this.permissionSets.delete(pluginId);\n \n const grants = this.grants.get(pluginId);\n if (grants) {\n for (const permissionId of grants) {\n const grantKey = `${pluginId}:${permissionId}`;\n this.grantDetails.delete(grantKey);\n }\n this.grants.delete(pluginId);\n }\n\n this.logger.info('All permissions cleared', { pluginId });\n }\n\n /**\n * Shutdown permission manager\n */\n shutdown(): void {\n this.permissionSets.clear();\n this.grants.clear();\n this.grantDetails.clear();\n \n this.logger.info('Permission manager shutdown complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport nodePath from 'node:path';\n\nimport type { \n SandboxConfig\n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from '../logger.js';\nimport { getMemoryUsage } from '../utils/env.js';\n\n/**\n * Resource Usage Statistics\n */\nexport interface ResourceUsage {\n memory: {\n current: number;\n peak: number;\n limit?: number;\n };\n cpu: {\n current: number;\n average: number;\n limit?: number;\n };\n connections: {\n current: number;\n limit?: number;\n };\n}\n\n/**\n * Sandbox Execution Context\n * Represents an isolated execution environment for a plugin\n */\nexport interface SandboxContext {\n pluginId: string;\n config: SandboxConfig;\n startTime: Date;\n resourceUsage: ResourceUsage;\n}\n\n/**\n * Plugin Sandbox Runtime\n * \n * Provides isolated execution environments for plugins with resource limits\n * and access controls\n */\nexport class PluginSandboxRuntime {\n private static readonly MONITORING_INTERVAL_MS = 5000;\n\n private logger: ObjectLogger;\n \n // Active sandboxes (pluginId -> context)\n private sandboxes = new Map();\n \n // Resource monitoring intervals\n private monitoringIntervals = new Map();\n\n // Per-plugin resource baselines for delta tracking\n private memoryBaselines = new Map();\n private cpuBaselines = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'SandboxRuntime' });\n }\n\n /**\n * Create a sandbox for a plugin\n */\n createSandbox(pluginId: string, config: SandboxConfig): SandboxContext {\n if (this.sandboxes.has(pluginId)) {\n throw new Error(`Sandbox already exists for plugin: ${pluginId}`);\n }\n\n const context: SandboxContext = {\n pluginId,\n config,\n startTime: new Date(),\n resourceUsage: {\n memory: { current: 0, peak: 0, limit: config.memory?.maxHeap },\n cpu: { current: 0, average: 0, limit: config.cpu?.maxCpuPercent },\n connections: { current: 0, limit: config.network?.maxConnections },\n },\n };\n\n this.sandboxes.set(pluginId, context);\n\n // Capture resource baselines for per-plugin delta tracking\n const baselineMemory = getMemoryUsage();\n this.memoryBaselines.set(pluginId, baselineMemory.heapUsed);\n this.cpuBaselines.set(pluginId, process.cpuUsage());\n\n // Start resource monitoring\n this.startResourceMonitoring(pluginId);\n\n this.logger.info('Sandbox created', { \n pluginId,\n level: config.level,\n memoryLimit: config.memory?.maxHeap,\n cpuLimit: config.cpu?.maxCpuPercent\n });\n\n return context;\n }\n\n /**\n * Destroy a sandbox\n */\n destroySandbox(pluginId: string): void {\n const context = this.sandboxes.get(pluginId);\n if (!context) {\n return;\n }\n\n // Stop monitoring\n this.stopResourceMonitoring(pluginId);\n\n this.memoryBaselines.delete(pluginId);\n this.cpuBaselines.delete(pluginId);\n this.sandboxes.delete(pluginId);\n\n this.logger.info('Sandbox destroyed', { pluginId });\n }\n\n /**\n * Check if resource access is allowed\n */\n checkResourceAccess(\n pluginId: string,\n resourceType: 'file' | 'network' | 'process' | 'env',\n resourcePath?: string\n ): { allowed: boolean; reason?: string } {\n const context = this.sandboxes.get(pluginId);\n if (!context) {\n return { allowed: false, reason: 'Sandbox not found' };\n }\n\n const { config } = context;\n\n switch (resourceType) {\n case 'file':\n return this.checkFileAccess(config, resourcePath);\n \n case 'network':\n return this.checkNetworkAccess(config, resourcePath);\n \n case 'process':\n return this.checkProcessAccess(config);\n \n case 'env':\n return this.checkEnvAccess(config, resourcePath);\n \n default:\n return { allowed: false, reason: 'Unknown resource type' };\n }\n }\n\n /**\n * Check file system access\n * Uses path.resolve() and path.normalize() to prevent directory traversal.\n */\n private checkFileAccess(\n config: SandboxConfig,\n filePath?: string\n ): { allowed: boolean; reason?: string } {\n if (config.level === 'none') {\n return { allowed: true };\n }\n\n if (!config.filesystem) {\n return { allowed: false, reason: 'File system access not configured' };\n }\n\n // If no path specified, check general access\n if (!filePath) {\n return { allowed: config.filesystem.mode !== 'none' };\n }\n\n // Check allowed paths using proper path resolution to prevent directory traversal\n const allowedPaths = config.filesystem.allowedPaths || [];\n const resolvedPath = nodePath.normalize(nodePath.resolve(filePath));\n const isAllowed = allowedPaths.some(allowed => {\n const resolvedAllowed = nodePath.normalize(nodePath.resolve(allowed));\n return resolvedPath.startsWith(resolvedAllowed);\n });\n\n if (allowedPaths.length > 0 && !isAllowed) {\n return { \n allowed: false, \n reason: `Path not in allowed list: ${filePath}` \n };\n }\n\n // Check denied paths using proper path resolution\n const deniedPaths = config.filesystem.deniedPaths || [];\n const isDenied = deniedPaths.some(denied => {\n const resolvedDenied = nodePath.normalize(nodePath.resolve(denied));\n return resolvedPath.startsWith(resolvedDenied);\n });\n\n if (isDenied) {\n return { \n allowed: false, \n reason: `Path is explicitly denied: ${filePath}` \n };\n }\n\n return { allowed: true };\n }\n\n /**\n * Check network access\n * Uses URL parsing to properly validate hostnames.\n */\n private checkNetworkAccess(\n config: SandboxConfig,\n url?: string\n ): { allowed: boolean; reason?: string } {\n if (config.level === 'none') {\n return { allowed: true };\n }\n\n if (!config.network) {\n return { allowed: false, reason: 'Network access not configured' };\n }\n\n // Check if network access is enabled\n if (config.network.mode === 'none') {\n return { allowed: false, reason: 'Network access disabled' };\n }\n\n // If no URL specified, check general access\n if (!url) {\n return { allowed: (config.network.mode as string) !== 'none' };\n }\n\n // Parse URL and check hostname against allowed/denied hosts\n let parsedHostname: string;\n try {\n parsedHostname = new URL(url).hostname;\n } catch {\n return { allowed: false, reason: `Invalid URL: ${url}` };\n }\n\n // Check allowed hosts\n const allowedHosts = config.network.allowedHosts || [];\n if (allowedHosts.length > 0) {\n const isAllowed = allowedHosts.some(host => {\n return parsedHostname === host;\n });\n\n if (!isAllowed) {\n return { \n allowed: false, \n reason: `Host not in allowed list: ${url}` \n };\n }\n }\n\n // Check denied hosts\n const deniedHosts = config.network.deniedHosts || [];\n const isDenied = deniedHosts.some(host => {\n return parsedHostname === host;\n });\n\n if (isDenied) {\n return { \n allowed: false, \n reason: `Host is blocked: ${url}` \n };\n }\n\n return { allowed: true };\n }\n\n /**\n * Check process spawning access\n */\n private checkProcessAccess(\n config: SandboxConfig\n ): { allowed: boolean; reason?: string } {\n if (config.level === 'none') {\n return { allowed: true };\n }\n\n if (!config.process) {\n return { allowed: false, reason: 'Process access not configured' };\n }\n\n if (!config.process.allowSpawn) {\n return { allowed: false, reason: 'Process spawning not allowed' };\n }\n\n return { allowed: true };\n }\n\n /**\n * Check environment variable access\n */\n private checkEnvAccess(\n config: SandboxConfig,\n varName?: string\n ): { allowed: boolean; reason?: string } {\n if (config.level === 'none') {\n return { allowed: true };\n }\n\n if (!config.process) {\n return { allowed: false, reason: 'Environment access not configured' };\n }\n\n // If no variable specified, check general access\n if (!varName) {\n return { allowed: true };\n }\n\n // For now, allow all env access if process is configured\n // In a real implementation, would check specific allowed vars\n return { allowed: true };\n }\n\n /**\n * Check resource limits\n */\n checkResourceLimits(pluginId: string): { \n withinLimits: boolean; \n violations: string[] \n } {\n const context = this.sandboxes.get(pluginId);\n if (!context) {\n return { withinLimits: true, violations: [] };\n }\n\n const violations: string[] = [];\n const { resourceUsage, config } = context;\n\n // Check memory limit\n if (config.memory?.maxHeap && \n resourceUsage.memory.current > config.memory.maxHeap) {\n violations.push(`Memory limit exceeded: ${resourceUsage.memory.current} > ${config.memory.maxHeap}`);\n }\n\n // Check CPU limit (would need runtime config)\n if (config.runtime?.resourceLimits?.maxCpu && \n resourceUsage.cpu.current > config.runtime.resourceLimits.maxCpu) {\n violations.push(`CPU limit exceeded: ${resourceUsage.cpu.current}% > ${config.runtime.resourceLimits.maxCpu}%`);\n }\n\n // Check connection limit\n if (config.network?.maxConnections && \n resourceUsage.connections.current > config.network.maxConnections) {\n violations.push(`Connection limit exceeded: ${resourceUsage.connections.current} > ${config.network.maxConnections}`);\n }\n\n return {\n withinLimits: violations.length === 0,\n violations,\n };\n }\n\n /**\n * Get resource usage for a plugin\n */\n getResourceUsage(pluginId: string): ResourceUsage | undefined {\n const context = this.sandboxes.get(pluginId);\n return context?.resourceUsage;\n }\n\n /**\n * Start monitoring resource usage\n */\n private startResourceMonitoring(pluginId: string): void {\n // Monitor at the configured interval\n const interval = setInterval(() => {\n this.updateResourceUsage(pluginId);\n }, PluginSandboxRuntime.MONITORING_INTERVAL_MS);\n\n this.monitoringIntervals.set(pluginId, interval);\n }\n\n /**\n * Stop monitoring resource usage\n */\n private stopResourceMonitoring(pluginId: string): void {\n const interval = this.monitoringIntervals.get(pluginId);\n if (interval) {\n clearInterval(interval);\n this.monitoringIntervals.delete(pluginId);\n }\n }\n\n /**\n * Update resource usage statistics\n * \n * Tracks per-plugin memory and CPU usage using delta from baseline\n * captured at sandbox creation time. This is an approximation since\n * true per-plugin isolation isn't possible in a single Node.js process.\n */\n private updateResourceUsage(pluginId: string): void {\n const context = this.sandboxes.get(pluginId);\n if (!context) {\n return;\n }\n\n // In a real implementation, this would collect actual metrics\n // For now, this is a placeholder structure\n \n // Update memory usage using delta from baseline for per-plugin approximation\n const memoryUsage = getMemoryUsage();\n const memoryBaseline = this.memoryBaselines.get(pluginId) ?? 0;\n const memoryDelta = Math.max(0, memoryUsage.heapUsed - memoryBaseline);\n context.resourceUsage.memory.current = memoryDelta;\n context.resourceUsage.memory.peak = Math.max(\n context.resourceUsage.memory.peak,\n memoryDelta\n );\n\n // Update CPU usage using delta from baseline for per-plugin approximation\n const cpuBaseline = this.cpuBaselines.get(pluginId) ?? { user: 0, system: 0 };\n const cpuCurrent = process.cpuUsage();\n const cpuDeltaUser = cpuCurrent.user - cpuBaseline.user;\n const cpuDeltaSystem = cpuCurrent.system - cpuBaseline.system;\n // Convert microseconds to a percentage approximation over the monitoring interval\n const totalCpuMicros = cpuDeltaUser + cpuDeltaSystem;\n const intervalMicros = PluginSandboxRuntime.MONITORING_INTERVAL_MS * 1000;\n context.resourceUsage.cpu.current = (totalCpuMicros / intervalMicros) * 100;\n // Update baseline for next interval\n this.cpuBaselines.set(pluginId, cpuCurrent);\n\n // Check for violations\n const { withinLimits, violations } = this.checkResourceLimits(pluginId);\n if (!withinLimits) {\n this.logger.warn('Resource limit violations detected', { \n pluginId, \n violations \n });\n }\n }\n\n /**\n * Get all active sandboxes\n */\n getAllSandboxes(): Map {\n return new Map(this.sandboxes);\n }\n\n /**\n * Shutdown sandbox runtime\n */\n shutdown(): void {\n // Stop all monitoring\n for (const pluginId of this.monitoringIntervals.keys()) {\n this.stopResourceMonitoring(pluginId);\n }\n\n this.sandboxes.clear();\n this.memoryBaselines.clear();\n this.cpuBaselines.clear();\n \n this.logger.info('Sandbox runtime shutdown complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { \n KernelSecurityVulnerability,\n KernelSecurityScanResult\n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from '../logger.js';\n\n/**\n * Scan Target\n */\nexport interface ScanTarget {\n pluginId: string;\n version: string;\n files?: string[];\n dependencies?: Record;\n}\n\n/**\n * Security Issue\n */\nexport interface SecurityIssue {\n id: string;\n severity: 'critical' | 'high' | 'medium' | 'low' | 'info';\n category: 'vulnerability' | 'malware' | 'license' | 'code-quality' | 'configuration';\n title: string;\n description: string;\n location?: {\n file?: string;\n line?: number;\n column?: number;\n };\n remediation?: string;\n cve?: string;\n cvss?: number;\n}\n\n/**\n * Plugin Security Scanner\n * \n * Scans plugins for security vulnerabilities, malware, and license issues\n */\nexport class PluginSecurityScanner {\n private logger: ObjectLogger;\n \n // Known vulnerabilities database (CVE cache)\n private vulnerabilityDb = new Map();\n \n // Scan results cache\n private scanResults = new Map();\n\n private passThreshold: number = 70;\n\n constructor(logger: ObjectLogger, config?: { passThreshold?: number }) {\n this.logger = logger.child({ component: 'SecurityScanner' });\n if (config?.passThreshold !== undefined) {\n this.passThreshold = config.passThreshold;\n }\n }\n\n /**\n * Perform a comprehensive security scan on a plugin\n */\n async scan(target: ScanTarget): Promise {\n this.logger.info('Starting security scan', { \n pluginId: target.pluginId,\n version: target.version \n });\n\n const issues: SecurityIssue[] = [];\n\n try {\n // 1. Scan for code vulnerabilities\n const codeIssues = await this.scanCode(target);\n issues.push(...codeIssues);\n\n // 2. Scan dependencies for known vulnerabilities\n const depIssues = await this.scanDependencies(target);\n issues.push(...depIssues);\n\n // 3. Scan for malware patterns\n const malwareIssues = await this.scanMalware(target);\n issues.push(...malwareIssues);\n\n // 4. Check license compliance\n const licenseIssues = await this.scanLicenses(target);\n issues.push(...licenseIssues);\n\n // 5. Check configuration security\n const configIssues = await this.scanConfiguration(target);\n issues.push(...configIssues);\n\n // Calculate security score (0-100, higher is better)\n const score = this.calculateSecurityScore(issues);\n\n const result: KernelSecurityScanResult = {\n timestamp: new Date().toISOString(),\n scanner: { name: 'ObjectStack Security Scanner', version: '1.0.0' },\n status: score >= this.passThreshold ? 'passed' : 'failed',\n vulnerabilities: issues.map(issue => ({\n id: issue.id,\n severity: issue.severity,\n category: issue.category,\n title: issue.title,\n description: issue.description,\n location: issue.location ? `${issue.location.file}:${issue.location.line}` : undefined,\n remediation: issue.remediation,\n affectedVersions: [],\n exploitAvailable: false,\n patchAvailable: false,\n })),\n summary: {\n totalVulnerabilities: issues.length,\n criticalCount: issues.filter(i => i.severity === 'critical').length,\n highCount: issues.filter(i => i.severity === 'high').length,\n mediumCount: issues.filter(i => i.severity === 'medium').length,\n lowCount: issues.filter(i => i.severity === 'low').length,\n infoCount: issues.filter(i => i.severity === 'info').length,\n },\n };\n\n this.scanResults.set(`${target.pluginId}:${target.version}`, result);\n\n this.logger.info('Security scan complete', { \n pluginId: target.pluginId,\n score,\n status: result.status,\n summary: result.summary\n });\n\n return result;\n } catch (error) {\n this.logger.error('Security scan failed', { \n pluginId: target.pluginId, \n error \n });\n\n throw error;\n }\n }\n\n /**\n * Scan code for vulnerabilities\n */\n private async scanCode(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n // In a real implementation, this would:\n // - Parse code with AST (e.g., using @typescript-eslint/parser)\n // - Check for dangerous patterns (eval, Function constructor, etc.)\n // - Check for XSS vulnerabilities\n // - Check for SQL injection patterns\n // - Check for insecure crypto usage\n // - Check for path traversal vulnerabilities\n\n this.logger.debug('Code scan complete', { \n pluginId: target.pluginId,\n issuesFound: issues.length \n });\n\n return issues;\n }\n\n /**\n * Scan dependencies for known vulnerabilities\n */\n private async scanDependencies(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n if (!target.dependencies) {\n return issues;\n }\n\n // In a real implementation, this would:\n // - Query npm audit API\n // - Check GitHub Advisory Database\n // - Check Snyk vulnerability database\n // - Check OSV (Open Source Vulnerabilities)\n\n for (const [depName, version] of Object.entries(target.dependencies)) {\n const vulnKey = `${depName}@${version}`;\n const vulnerability = this.vulnerabilityDb.get(vulnKey);\n\n if (vulnerability) {\n issues.push({\n id: `vuln-${vulnerability.cve || depName}`,\n severity: vulnerability.severity,\n category: 'vulnerability',\n title: `Vulnerable dependency: ${depName}`,\n description: `${depName}@${version} has known security vulnerabilities`,\n remediation: vulnerability.fixedIn \n ? `Upgrade to ${vulnerability.fixedIn.join(' or ')}`\n : 'No fix available',\n cve: vulnerability.cve,\n });\n }\n }\n\n this.logger.debug('Dependency scan complete', { \n pluginId: target.pluginId,\n dependencies: Object.keys(target.dependencies).length,\n vulnerabilities: issues.length \n });\n\n return issues;\n }\n\n /**\n * Scan for malware patterns\n */\n private async scanMalware(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n // In a real implementation, this would:\n // - Check for obfuscated code\n // - Check for suspicious network activity patterns\n // - Check for crypto mining patterns\n // - Check for data exfiltration patterns\n // - Use ML-based malware detection\n // - Check file hashes against known malware databases\n\n this.logger.debug('Malware scan complete', { \n pluginId: target.pluginId,\n issuesFound: issues.length \n });\n\n return issues;\n }\n\n /**\n * Check license compliance\n */\n private async scanLicenses(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n if (!target.dependencies) {\n return issues;\n }\n\n // In a real implementation, this would:\n // - Check license compatibility\n // - Detect GPL contamination\n // - Flag proprietary dependencies\n // - Check for missing licenses\n // - Verify SPDX identifiers\n\n this.logger.debug('License scan complete', { \n pluginId: target.pluginId,\n issuesFound: issues.length \n });\n\n return issues;\n }\n\n /**\n * Check configuration security\n */\n private async scanConfiguration(target: ScanTarget): Promise {\n const issues: SecurityIssue[] = [];\n\n // In a real implementation, this would:\n // - Check for hardcoded secrets\n // - Check for weak permissions\n // - Check for insecure defaults\n // - Check for missing security headers\n // - Check CSP policies\n\n this.logger.debug('Configuration scan complete', { \n pluginId: target.pluginId,\n issuesFound: issues.length \n });\n\n return issues;\n }\n\n /**\n * Calculate security score based on issues\n */\n private calculateSecurityScore(issues: SecurityIssue[]): number {\n // Start with perfect score\n let score = 100;\n\n // Deduct points based on severity\n for (const issue of issues) {\n switch (issue.severity) {\n case 'critical':\n score -= 20;\n break;\n case 'high':\n score -= 10;\n break;\n case 'medium':\n score -= 5;\n break;\n case 'low':\n score -= 2;\n break;\n case 'info':\n score -= 0;\n break;\n }\n }\n\n // Ensure score doesn't go below 0\n return Math.max(0, score);\n }\n\n /**\n * Add a vulnerability to the database\n */\n addVulnerability(\n packageName: string,\n version: string,\n vulnerability: KernelSecurityVulnerability\n ): void {\n const key = `${packageName}@${version}`;\n this.vulnerabilityDb.set(key, vulnerability);\n \n this.logger.debug('Vulnerability added to database', { \n package: packageName, \n version,\n cve: vulnerability.cve \n });\n }\n\n /**\n * Get scan result from cache\n */\n getScanResult(pluginId: string, version: string): KernelSecurityScanResult | undefined {\n return this.scanResults.get(`${pluginId}:${version}`);\n }\n\n /**\n * Clear scan results cache\n */\n clearCache(): void {\n this.scanResults.clear();\n this.logger.debug('Scan results cache cleared');\n }\n\n /**\n * Update vulnerability database from external source\n */\n async updateVulnerabilityDatabase(): Promise {\n this.logger.info('Updating vulnerability database');\n\n // In a real implementation, this would:\n // - Fetch from GitHub Advisory Database\n // - Fetch from npm audit\n // - Fetch from NVD (National Vulnerability Database)\n // - Parse and cache vulnerability data\n\n this.logger.info('Vulnerability database updated', { \n entries: this.vulnerabilityDb.size \n });\n }\n\n /**\n * Shutdown security scanner\n */\n shutdown(): void {\n this.vulnerabilityDb.clear();\n this.scanResults.clear();\n \n this.logger.info('Security scanner shutdown complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { \n PluginHealthStatus, \n PluginHealthCheck, \n PluginHealthReport \n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from './logger.js';\nimport type { Plugin } from './types.js';\n\n/**\n * Plugin Health Monitor\n * \n * Monitors plugin health status and performs automatic recovery actions.\n * Implements the advanced lifecycle health monitoring protocol.\n */\nexport class PluginHealthMonitor {\n private logger: ObjectLogger;\n private healthChecks = new Map();\n private healthStatus = new Map();\n private healthReports = new Map();\n private checkIntervals = new Map();\n private failureCounters = new Map();\n private successCounters = new Map();\n private restartAttempts = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'HealthMonitor' });\n }\n\n /**\n * Register a plugin for health monitoring\n */\n registerPlugin(pluginName: string, config: PluginHealthCheck): void {\n this.healthChecks.set(pluginName, config);\n this.healthStatus.set(pluginName, 'unknown');\n this.failureCounters.set(pluginName, 0);\n this.successCounters.set(pluginName, 0);\n this.restartAttempts.set(pluginName, 0);\n\n this.logger.info('Plugin registered for health monitoring', { \n plugin: pluginName,\n interval: config.interval \n });\n }\n\n /**\n * Start monitoring a plugin\n */\n startMonitoring(pluginName: string, plugin: Plugin): void {\n const config = this.healthChecks.get(pluginName);\n if (!config) {\n this.logger.warn('Cannot start monitoring - plugin not registered', { plugin: pluginName });\n return;\n }\n\n // Clear any existing interval\n this.stopMonitoring(pluginName);\n\n // Set up periodic health checks\n const interval = setInterval(() => {\n this.performHealthCheck(pluginName, plugin, config).catch(error => {\n this.logger.error('Health check failed with error', { \n plugin: pluginName, \n error \n });\n });\n }, config.interval);\n\n this.checkIntervals.set(pluginName, interval);\n this.logger.info('Health monitoring started', { plugin: pluginName });\n\n // Perform initial health check\n this.performHealthCheck(pluginName, plugin, config).catch(error => {\n this.logger.error('Initial health check failed', { \n plugin: pluginName, \n error \n });\n });\n }\n\n /**\n * Stop monitoring a plugin\n */\n stopMonitoring(pluginName: string): void {\n const interval = this.checkIntervals.get(pluginName);\n if (interval) {\n clearInterval(interval);\n this.checkIntervals.delete(pluginName);\n this.logger.info('Health monitoring stopped', { plugin: pluginName });\n }\n }\n\n /**\n * Perform a health check on a plugin\n */\n private async performHealthCheck(\n pluginName: string,\n plugin: Plugin,\n config: PluginHealthCheck\n ): Promise {\n const startTime = Date.now();\n let status: PluginHealthStatus = 'healthy';\n let message: string | undefined;\n const checks: Array<{ name: string; status: 'passed' | 'failed' | 'warning'; message?: string }> = [];\n\n try {\n // Check if plugin has a custom health check method\n if (config.checkMethod && typeof (plugin as any)[config.checkMethod] === 'function') {\n const checkResult = await Promise.race([\n (plugin as any)[config.checkMethod](),\n this.timeout(config.timeout, `Health check timeout after ${config.timeout}ms`)\n ]);\n\n if (checkResult === false || (checkResult && checkResult.status === 'unhealthy')) {\n status = 'unhealthy';\n message = checkResult?.message || 'Custom health check failed';\n checks.push({ name: config.checkMethod, status: 'failed', message });\n } else {\n checks.push({ name: config.checkMethod, status: 'passed' });\n }\n } else {\n // Default health check - just verify plugin is loaded\n checks.push({ name: 'plugin-loaded', status: 'passed' });\n }\n\n // Update counters based on result\n if (status === 'healthy') {\n this.successCounters.set(pluginName, (this.successCounters.get(pluginName) || 0) + 1);\n this.failureCounters.set(pluginName, 0);\n\n // Recover from unhealthy state if we have enough successes\n const currentStatus = this.healthStatus.get(pluginName);\n if (currentStatus === 'unhealthy' || currentStatus === 'degraded') {\n const successCount = this.successCounters.get(pluginName) || 0;\n if (successCount >= config.successThreshold) {\n this.healthStatus.set(pluginName, 'healthy');\n this.logger.info('Plugin recovered to healthy state', { plugin: pluginName });\n } else {\n this.healthStatus.set(pluginName, 'recovering');\n }\n } else {\n this.healthStatus.set(pluginName, 'healthy');\n }\n } else {\n this.failureCounters.set(pluginName, (this.failureCounters.get(pluginName) || 0) + 1);\n this.successCounters.set(pluginName, 0);\n\n const failureCount = this.failureCounters.get(pluginName) || 0;\n if (failureCount >= config.failureThreshold) {\n this.healthStatus.set(pluginName, 'unhealthy');\n this.logger.warn('Plugin marked as unhealthy', { \n plugin: pluginName, \n failures: failureCount \n });\n\n // Attempt auto-restart if configured\n if (config.autoRestart) {\n await this.attemptRestart(pluginName, plugin, config);\n }\n } else {\n this.healthStatus.set(pluginName, 'degraded');\n }\n }\n } catch (error) {\n status = 'failed';\n message = error instanceof Error ? error.message : 'Unknown error';\n this.failureCounters.set(pluginName, (this.failureCounters.get(pluginName) || 0) + 1);\n this.healthStatus.set(pluginName, 'failed');\n \n checks.push({ \n name: 'health-check', \n status: 'failed', \n message: message \n });\n\n this.logger.error('Health check exception', { \n plugin: pluginName, \n error \n });\n }\n\n // Create health report\n const report: PluginHealthReport = {\n status: this.healthStatus.get(pluginName) || 'unknown',\n timestamp: new Date().toISOString(),\n message,\n metrics: {\n uptime: Date.now() - startTime,\n },\n checks: checks.length > 0 ? checks : undefined,\n };\n\n this.healthReports.set(pluginName, report);\n }\n\n /**\n * Attempt to restart a plugin\n */\n private async attemptRestart(\n pluginName: string,\n plugin: Plugin,\n config: PluginHealthCheck\n ): Promise {\n const attempts = this.restartAttempts.get(pluginName) || 0;\n \n if (attempts >= config.maxRestartAttempts) {\n this.logger.error('Max restart attempts reached, giving up', { \n plugin: pluginName, \n attempts \n });\n this.healthStatus.set(pluginName, 'failed');\n return;\n }\n\n this.restartAttempts.set(pluginName, attempts + 1);\n \n // Calculate backoff delay\n const delay = this.calculateBackoff(attempts, config.restartBackoff);\n \n this.logger.info('Scheduling plugin restart', { \n plugin: pluginName, \n attempt: attempts + 1, \n delay \n });\n\n await new Promise(resolve => setTimeout(resolve, delay));\n\n try {\n // Call destroy and init to restart\n if (plugin.destroy) {\n await plugin.destroy();\n }\n \n // Note: Full restart would require kernel context\n // This is a simplified version - actual implementation would need kernel integration\n this.logger.info('Plugin restarted', { plugin: pluginName });\n \n // Reset counters on successful restart\n this.failureCounters.set(pluginName, 0);\n this.successCounters.set(pluginName, 0);\n this.healthStatus.set(pluginName, 'recovering');\n } catch (error) {\n this.logger.error('Plugin restart failed', { \n plugin: pluginName, \n error \n });\n this.healthStatus.set(pluginName, 'failed');\n }\n }\n\n /**\n * Calculate backoff delay for restarts\n */\n private calculateBackoff(attempt: number, strategy: 'fixed' | 'linear' | 'exponential'): number {\n const baseDelay = 1000; // 1 second base\n\n switch (strategy) {\n case 'fixed':\n return baseDelay;\n case 'linear':\n return baseDelay * (attempt + 1);\n case 'exponential':\n return baseDelay * Math.pow(2, attempt);\n default:\n return baseDelay;\n }\n }\n\n /**\n * Get current health status of a plugin\n */\n getHealthStatus(pluginName: string): PluginHealthStatus | undefined {\n return this.healthStatus.get(pluginName);\n }\n\n /**\n * Get latest health report for a plugin\n */\n getHealthReport(pluginName: string): PluginHealthReport | undefined {\n return this.healthReports.get(pluginName);\n }\n\n /**\n * Get all health statuses\n */\n getAllHealthStatuses(): Map {\n return new Map(this.healthStatus);\n }\n\n /**\n * Shutdown health monitor\n */\n shutdown(): void {\n // Stop all monitoring intervals\n for (const pluginName of this.checkIntervals.keys()) {\n this.stopMonitoring(pluginName);\n }\n \n this.healthChecks.clear();\n this.healthStatus.clear();\n this.healthReports.clear();\n this.failureCounters.clear();\n this.successCounters.clear();\n this.restartAttempts.clear();\n \n this.logger.info('Health monitor shutdown complete');\n }\n\n /**\n * Timeout helper\n */\n private timeout(ms: number, message: string): Promise {\n return new Promise((_, reject) => {\n setTimeout(() => reject(new Error(message)), ms);\n });\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { createHash } from 'node:crypto';\n\nimport type { \n HotReloadConfig, \n PluginStateSnapshot \n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from './logger.js';\nimport type { Plugin } from './types.js';\n\n// Polyfill for UUID generation to support both Node.js and Browser\nconst generateUUID = () => {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n // Basic UUID v4 fallback\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n};\n\n/**\n * Plugin State Manager\n * \n * Handles state persistence and restoration during hot reloads\n */\nclass PluginStateManager {\n private logger: ObjectLogger;\n private stateSnapshots = new Map();\n private memoryStore = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'StateManager' });\n }\n\n /**\n * Save plugin state before reload\n */\n async saveState(\n pluginId: string,\n version: string,\n state: Record,\n config: HotReloadConfig\n ): Promise {\n const snapshot: PluginStateSnapshot = {\n pluginId,\n version,\n timestamp: new Date().toISOString(),\n state,\n metadata: {\n checksum: this.calculateChecksum(state),\n compressed: false,\n },\n };\n\n const snapshotId = generateUUID();\n\n switch (config.stateStrategy) {\n case 'memory':\n this.memoryStore.set(snapshotId, snapshot);\n this.logger.debug('State saved to memory', { pluginId, snapshotId });\n break;\n\n case 'disk':\n // For disk storage, we would write to file system\n // For now, store in memory as fallback\n this.memoryStore.set(snapshotId, snapshot);\n this.logger.debug('State saved to disk (memory fallback)', { pluginId, snapshotId });\n break;\n\n case 'distributed':\n // For distributed storage, would use Redis/etcd\n // For now, store in memory as fallback\n this.memoryStore.set(snapshotId, snapshot);\n this.logger.debug('State saved to distributed store (memory fallback)', { \n pluginId, \n snapshotId \n });\n break;\n\n case 'none':\n this.logger.debug('State persistence disabled', { pluginId });\n break;\n }\n\n this.stateSnapshots.set(pluginId, snapshot);\n return snapshotId;\n }\n\n /**\n * Restore plugin state after reload\n */\n async restoreState(\n pluginId: string,\n snapshotId?: string\n ): Promise | undefined> {\n // Try to get from snapshot ID first, otherwise use latest for plugin\n let snapshot: PluginStateSnapshot | undefined;\n\n if (snapshotId) {\n snapshot = this.memoryStore.get(snapshotId);\n } else {\n snapshot = this.stateSnapshots.get(pluginId);\n }\n\n if (!snapshot) {\n this.logger.warn('No state snapshot found', { pluginId, snapshotId });\n return undefined;\n }\n\n // Verify checksum if available\n if (snapshot.metadata?.checksum) {\n const currentChecksum = this.calculateChecksum(snapshot.state);\n if (currentChecksum !== snapshot.metadata.checksum) {\n this.logger.error('State checksum mismatch - data may be corrupted', { \n pluginId,\n expected: snapshot.metadata.checksum,\n actual: currentChecksum\n });\n return undefined;\n }\n }\n\n this.logger.debug('State restored', { pluginId, version: snapshot.version });\n return snapshot.state;\n }\n\n /**\n * Clear state for a plugin\n */\n clearState(pluginId: string): void {\n this.stateSnapshots.delete(pluginId);\n // Note: We don't clear memory store as it might have multiple snapshots\n this.logger.debug('State cleared', { pluginId });\n }\n\n /**\n * Calculate checksum for state verification using SHA-256.\n */\n private calculateChecksum(state: Record): string {\n const stateStr = JSON.stringify(state);\n return createHash('sha256').update(stateStr).digest('hex');\n }\n\n /**\n * Shutdown state manager\n */\n shutdown(): void {\n this.stateSnapshots.clear();\n this.memoryStore.clear();\n this.logger.info('State manager shutdown complete');\n }\n}\n\n/**\n * Hot Reload Manager\n * \n * Manages hot reloading of plugins with state preservation\n */\nexport class HotReloadManager {\n private logger: ObjectLogger;\n private stateManager: PluginStateManager;\n private reloadConfigs = new Map();\n private watchHandles = new Map();\n private reloadTimers = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'HotReload' });\n this.stateManager = new PluginStateManager(logger);\n }\n\n /**\n * Register a plugin for hot reload\n */\n registerPlugin(pluginName: string, config: HotReloadConfig): void {\n if (!config.enabled) {\n this.logger.debug('Hot reload disabled for plugin', { plugin: pluginName });\n return;\n }\n\n this.reloadConfigs.set(pluginName, config);\n this.logger.info('Plugin registered for hot reload', { \n plugin: pluginName,\n watchPatterns: config.watchPatterns,\n stateStrategy: config.stateStrategy\n });\n }\n\n /**\n * Start watching for changes (requires file system integration)\n */\n startWatching(pluginName: string): void {\n const config = this.reloadConfigs.get(pluginName);\n if (!config || !config.enabled) {\n return;\n }\n\n // Note: Actual file watching would require chokidar or similar\n // This is a placeholder for the integration point\n this.logger.info('File watching started', { \n plugin: pluginName,\n patterns: config.watchPatterns \n });\n }\n\n /**\n * Stop watching for changes\n */\n stopWatching(pluginName: string): void {\n const handle = this.watchHandles.get(pluginName);\n if (handle) {\n // Stop watching (would call chokidar close())\n this.watchHandles.delete(pluginName);\n this.logger.info('File watching stopped', { plugin: pluginName });\n }\n\n // Clear any pending reload timers\n const timer = this.reloadTimers.get(pluginName);\n if (timer) {\n clearTimeout(timer);\n this.reloadTimers.delete(pluginName);\n }\n }\n\n /**\n * Trigger hot reload for a plugin\n */\n async reloadPlugin(\n pluginName: string,\n plugin: Plugin,\n version: string,\n getPluginState: () => Record,\n restorePluginState: (state: Record) => void\n ): Promise {\n const config = this.reloadConfigs.get(pluginName);\n if (!config) {\n this.logger.warn('Cannot reload - plugin not registered', { plugin: pluginName });\n return false;\n }\n\n this.logger.info('Starting hot reload', { plugin: pluginName });\n\n try {\n // Call before reload hooks\n if (config.beforeReload) {\n this.logger.debug('Executing before reload hooks', { \n plugin: pluginName,\n hooks: config.beforeReload \n });\n // Hook execution would be done through kernel's hook system\n }\n\n // Save state if configured\n let snapshotId: string | undefined;\n if (config.preserveState && config.stateStrategy !== 'none') {\n const state = getPluginState();\n snapshotId = await this.stateManager.saveState(\n pluginName,\n version,\n state,\n config\n );\n this.logger.debug('Plugin state saved', { plugin: pluginName, snapshotId });\n }\n\n // Gracefully shutdown the plugin\n if (plugin.destroy) {\n this.logger.debug('Destroying plugin', { plugin: pluginName });\n \n const shutdownPromise = plugin.destroy();\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => reject(new Error('Shutdown timeout')), config.shutdownTimeout);\n });\n\n await Promise.race([shutdownPromise, timeoutPromise]);\n this.logger.debug('Plugin destroyed successfully', { plugin: pluginName });\n }\n\n // At this point, the kernel would reload the plugin module\n // This would be handled by the plugin loader\n this.logger.debug('Plugin module would be reloaded here', { plugin: pluginName });\n\n // Restore state if we saved it\n if (snapshotId && config.preserveState) {\n const restoredState = await this.stateManager.restoreState(pluginName, snapshotId);\n if (restoredState) {\n restorePluginState(restoredState);\n this.logger.debug('Plugin state restored', { plugin: pluginName });\n }\n }\n\n // Call after reload hooks\n if (config.afterReload) {\n this.logger.debug('Executing after reload hooks', { \n plugin: pluginName,\n hooks: config.afterReload \n });\n // Hook execution would be done through kernel's hook system\n }\n\n this.logger.info('Hot reload completed successfully', { plugin: pluginName });\n return true;\n } catch (error) {\n this.logger.error('Hot reload failed', { \n plugin: pluginName, \n error \n });\n return false;\n }\n }\n\n /**\n * Schedule a reload with debouncing\n */\n scheduleReload(\n pluginName: string,\n reloadFn: () => Promise\n ): void {\n const config = this.reloadConfigs.get(pluginName);\n if (!config) {\n return;\n }\n\n // Clear existing timer\n const existingTimer = this.reloadTimers.get(pluginName);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Schedule new reload with debounce\n const timer = setTimeout(() => {\n this.logger.debug('Debounce period elapsed, executing reload', { \n plugin: pluginName \n });\n reloadFn().catch(error => {\n this.logger.error('Scheduled reload failed', { \n plugin: pluginName, \n error \n });\n });\n this.reloadTimers.delete(pluginName);\n }, config.debounceDelay);\n\n this.reloadTimers.set(pluginName, timer);\n this.logger.debug('Reload scheduled with debounce', { \n plugin: pluginName,\n delay: config.debounceDelay \n });\n }\n\n /**\n * Get state manager for direct access\n */\n getStateManager(): PluginStateManager {\n return this.stateManager;\n }\n\n /**\n * Shutdown hot reload manager\n */\n shutdown(): void {\n // Stop all watching\n for (const pluginName of this.watchHandles.keys()) {\n this.stopWatching(pluginName);\n }\n\n // Clear all timers\n for (const timer of this.reloadTimers.values()) {\n clearTimeout(timer);\n }\n\n this.reloadConfigs.clear();\n this.watchHandles.clear();\n this.reloadTimers.clear();\n this.stateManager.shutdown();\n \n this.logger.info('Hot reload manager shutdown complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { \n SemanticVersion,\n VersionConstraint,\n CompatibilityLevel,\n DependencyConflict\n} from '@objectstack/spec/kernel';\nimport type { ObjectLogger } from './logger.js';\n\n/**\n * Semantic Version Parser and Comparator\n * \n * Implements semantic versioning comparison and constraint matching\n */\nexport class SemanticVersionManager {\n /**\n * Parse a version string into semantic version components\n */\n static parse(versionStr: string): SemanticVersion {\n // Remove 'v' prefix if present\n const cleanVersion = versionStr.replace(/^v/, '');\n \n // Match semver pattern: major.minor.patch[-prerelease][+build]\n const match = cleanVersion.match(\n /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([a-zA-Z0-9.-]+))?(?:\\+([a-zA-Z0-9.-]+))?$/\n );\n\n if (!match) {\n throw new Error(`Invalid semantic version: ${versionStr}`);\n }\n\n return {\n major: parseInt(match[1], 10),\n minor: parseInt(match[2], 10),\n patch: parseInt(match[3], 10),\n preRelease: match[4],\n build: match[5],\n };\n }\n\n /**\n * Convert semantic version back to string\n */\n static toString(version: SemanticVersion): string {\n let str = `${version.major}.${version.minor}.${version.patch}`;\n if (version.preRelease) {\n str += `-${version.preRelease}`;\n }\n if (version.build) {\n str += `+${version.build}`;\n }\n return str;\n }\n\n /**\n * Compare two semantic versions\n * Returns: -1 if a < b, 0 if a === b, 1 if a > b\n */\n static compare(a: SemanticVersion, b: SemanticVersion): number {\n // Compare major, minor, patch\n if (a.major !== b.major) return a.major - b.major;\n if (a.minor !== b.minor) return a.minor - b.minor;\n if (a.patch !== b.patch) return a.patch - b.patch;\n\n // Pre-release versions have lower precedence\n if (a.preRelease && !b.preRelease) return -1;\n if (!a.preRelease && b.preRelease) return 1;\n \n // Compare pre-release versions\n if (a.preRelease && b.preRelease) {\n return a.preRelease.localeCompare(b.preRelease);\n }\n\n return 0;\n }\n\n /**\n * Check if version satisfies constraint\n */\n static satisfies(version: SemanticVersion, constraint: VersionConstraint): boolean {\n const constraintStr = constraint as string;\n\n // Any version\n if (constraintStr === '*' || constraintStr === 'latest') {\n return true;\n }\n\n // Exact version\n if (/^[\\d.]+$/.test(constraintStr)) {\n const exact = this.parse(constraintStr);\n return this.compare(version, exact) === 0;\n }\n\n // Caret range (^): Compatible with version\n if (constraintStr.startsWith('^')) {\n const base = this.parse(constraintStr.slice(1));\n return (\n version.major === base.major &&\n this.compare(version, base) >= 0\n );\n }\n\n // Tilde range (~): Approximately equivalent\n if (constraintStr.startsWith('~')) {\n const base = this.parse(constraintStr.slice(1));\n return (\n version.major === base.major &&\n version.minor === base.minor &&\n this.compare(version, base) >= 0\n );\n }\n\n // Greater than or equal\n if (constraintStr.startsWith('>=')) {\n const base = this.parse(constraintStr.slice(2));\n return this.compare(version, base) >= 0;\n }\n\n // Greater than\n if (constraintStr.startsWith('>')) {\n const base = this.parse(constraintStr.slice(1));\n return this.compare(version, base) > 0;\n }\n\n // Less than or equal\n if (constraintStr.startsWith('<=')) {\n const base = this.parse(constraintStr.slice(2));\n return this.compare(version, base) <= 0;\n }\n\n // Less than\n if (constraintStr.startsWith('<')) {\n const base = this.parse(constraintStr.slice(1));\n return this.compare(version, base) < 0;\n }\n\n // Range (1.2.3 - 2.3.4)\n const rangeMatch = constraintStr.match(/^([\\d.]+)\\s*-\\s*([\\d.]+)$/);\n if (rangeMatch) {\n const min = this.parse(rangeMatch[1]);\n const max = this.parse(rangeMatch[2]);\n return this.compare(version, min) >= 0 && this.compare(version, max) <= 0;\n }\n\n return false;\n }\n\n /**\n * Determine compatibility level between two versions\n */\n static getCompatibilityLevel(from: SemanticVersion, to: SemanticVersion): CompatibilityLevel {\n const cmp = this.compare(from, to);\n\n // Same version\n if (cmp === 0) {\n return 'fully-compatible';\n }\n\n // Major version changed - breaking changes\n if (from.major !== to.major) {\n return 'breaking-changes';\n }\n\n // Minor version increased - backward compatible\n if (from.minor < to.minor) {\n return 'backward-compatible';\n }\n\n // Patch version increased - fully compatible\n if (from.patch < to.patch) {\n return 'fully-compatible';\n }\n\n // Downgrade - incompatible\n return 'incompatible';\n }\n}\n\n/**\n * Plugin Dependency Resolver\n * \n * Resolves plugin dependencies using topological sorting and conflict detection\n */\nexport class DependencyResolver {\n private logger: ObjectLogger;\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'DependencyResolver' });\n }\n\n /**\n * Resolve dependencies using topological sort\n */\n resolve(\n plugins: Map\n ): string[] {\n const graph = new Map();\n const inDegree = new Map();\n\n // Build dependency graph\n for (const [pluginName, pluginInfo] of plugins) {\n if (!graph.has(pluginName)) {\n graph.set(pluginName, []);\n inDegree.set(pluginName, 0);\n }\n\n const deps = pluginInfo.dependencies || [];\n for (const dep of deps) {\n // Check if dependency exists\n if (!plugins.has(dep)) {\n throw new Error(`Missing dependency: ${pluginName} requires ${dep}`);\n }\n\n // Add edge\n if (!graph.has(dep)) {\n graph.set(dep, []);\n inDegree.set(dep, 0);\n }\n graph.get(dep)!.push(pluginName);\n inDegree.set(pluginName, (inDegree.get(pluginName) || 0) + 1);\n }\n }\n\n // Topological sort using Kahn's algorithm\n const queue: string[] = [];\n const result: string[] = [];\n\n // Add all nodes with no incoming edges\n for (const [node, degree] of inDegree) {\n if (degree === 0) {\n queue.push(node);\n }\n }\n\n while (queue.length > 0) {\n const node = queue.shift()!;\n result.push(node);\n\n // Reduce in-degree for dependent nodes\n const dependents = graph.get(node) || [];\n for (const dependent of dependents) {\n const newDegree = (inDegree.get(dependent) || 0) - 1;\n inDegree.set(dependent, newDegree);\n \n if (newDegree === 0) {\n queue.push(dependent);\n }\n }\n }\n\n // Check for circular dependencies\n if (result.length !== plugins.size) {\n const remaining = Array.from(plugins.keys()).filter(p => !result.includes(p));\n this.logger.error('Circular dependency detected', { remaining });\n throw new Error(`Circular dependency detected among: ${remaining.join(', ')}`);\n }\n\n this.logger.debug('Dependencies resolved', { order: result });\n return result;\n }\n\n /**\n * Detect dependency conflicts\n */\n detectConflicts(\n plugins: Map }>\n ): DependencyConflict[] {\n const conflicts: DependencyConflict[] = [];\n const versionRequirements = new Map>();\n\n // Collect all version requirements\n for (const [pluginName, pluginInfo] of plugins) {\n if (!pluginInfo.dependencies) continue;\n\n for (const [depName, constraint] of Object.entries(pluginInfo.dependencies)) {\n if (!versionRequirements.has(depName)) {\n versionRequirements.set(depName, new Map());\n }\n versionRequirements.get(depName)!.set(pluginName, constraint);\n }\n }\n\n // Check for version mismatches\n for (const [depName, requirements] of versionRequirements) {\n const depInfo = plugins.get(depName);\n if (!depInfo) continue;\n\n const depVersion = SemanticVersionManager.parse(depInfo.version);\n const unsatisfied: Array<{ pluginId: string; version: string }> = [];\n\n for (const [requiringPlugin, constraint] of requirements) {\n if (!SemanticVersionManager.satisfies(depVersion, constraint)) {\n unsatisfied.push({\n pluginId: requiringPlugin,\n version: constraint as string,\n });\n }\n }\n\n if (unsatisfied.length > 0) {\n conflicts.push({\n type: 'version-mismatch',\n severity: 'error',\n description: `Version mismatch for ${depName}: detected ${unsatisfied.length} unsatisfied requirements`,\n plugins: [\n { pluginId: depName, version: depInfo.version },\n ...unsatisfied,\n ],\n resolutions: [{\n strategy: 'upgrade',\n description: `Upgrade ${depName} to satisfy all constraints`,\n targetPlugins: [depName],\n automatic: false,\n } as any],\n });\n }\n }\n\n // Check for circular dependencies (will be caught by resolve())\n try {\n this.resolve(new Map(\n Array.from(plugins.entries()).map(([name, info]) => [\n name,\n { version: info.version, dependencies: info.dependencies ? Object.keys(info.dependencies) : [] }\n ])\n ));\n } catch (error) {\n if (error instanceof Error && error.message.includes('Circular dependency')) {\n conflicts.push({\n type: 'circular-dependency',\n severity: 'critical',\n description: error.message,\n plugins: [], // Would need to extract from error\n resolutions: [{\n strategy: 'manual',\n description: 'Remove circular dependency by restructuring plugins',\n automatic: false,\n } as any],\n });\n }\n }\n\n return conflicts;\n }\n\n /**\n * Find best version that satisfies all constraints\n */\n findBestVersion(\n availableVersions: string[],\n constraints: VersionConstraint[]\n ): string | undefined {\n // Parse and sort versions (highest first)\n const versions = availableVersions\n .map(v => ({ str: v, parsed: SemanticVersionManager.parse(v) }))\n .sort((a, b) => -SemanticVersionManager.compare(a.parsed, b.parsed));\n\n // Find highest version that satisfies all constraints\n for (const version of versions) {\n const satisfiesAll = constraints.every(constraint =>\n SemanticVersionManager.satisfies(version.parsed, constraint)\n );\n\n if (satisfiesAll) {\n return version.str;\n }\n }\n\n return undefined;\n }\n\n /**\n * Check if dependencies form a valid DAG (no cycles)\n */\n isAcyclic(dependencies: Map): boolean {\n try {\n const plugins = new Map(\n Array.from(dependencies.entries()).map(([name, deps]) => [\n name,\n { dependencies: deps }\n ])\n );\n this.resolve(plugins);\n return true;\n } catch {\n return false;\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ObjectLogger } from './logger.js';\n\n/**\n * Namespace entry representing an object/view/flow etc. registered by a package.\n */\nexport interface NamespaceEntry {\n /** The namespace path (e.g. \"objects.project_task\", \"views.task_list\") */\n namespace: string;\n /** The package that owns this namespace */\n packageId: string;\n /** When this entry was registered */\n registeredAt: string;\n}\n\n/**\n * Result of a namespace conflict check.\n */\nexport interface NamespaceConflict {\n /** The conflicting namespace path */\n namespace: string;\n /** The package that currently owns this namespace */\n existingPackageId: string;\n /** The package attempting to register the same namespace */\n incomingPackageId: string;\n /** A suggested alternative name to avoid the conflict */\n suggestion?: string;\n}\n\n/**\n * Result of namespace availability check.\n */\nexport interface NamespaceCheckResult {\n /** Whether all requested namespaces are available */\n available: boolean;\n /** List of conflicts detected */\n conflicts: NamespaceConflict[];\n /** Suggested alternatives for each conflict */\n suggestions: Record;\n}\n\n/**\n * Namespace Resolver\n *\n * Manages namespace registration for installed packages and detects collisions\n * during install-time. Each metadata item (object, view, flow, page, etc.)\n * produces a namespace like `objects.` or `views.`.\n *\n * When a new package declares objects, views, or other metadata that would\n * collide with an existing package's metadata, this resolver reports the\n * conflicts and suggests prefixed alternatives.\n */\nexport class NamespaceResolver {\n private logger: ObjectLogger;\n private registry: Map = new Map();\n\n constructor(logger: ObjectLogger) {\n this.logger = logger.child({ component: 'NamespaceResolver' });\n }\n\n /**\n * Register namespaces owned by a package.\n */\n register(packageId: string, namespaces: string[]): void {\n const now = new Date().toISOString();\n for (const ns of namespaces) {\n if (this.registry.has(ns)) {\n const existing = this.registry.get(ns)!;\n if (existing.packageId !== packageId) {\n this.logger.warn('Overwriting namespace entry', { namespace: ns, existing: existing.packageId, incoming: packageId });\n }\n }\n this.registry.set(ns, { namespace: ns, packageId, registeredAt: now });\n this.logger.debug('Namespace registered', { namespace: ns, packageId });\n }\n }\n\n /**\n * Unregister all namespaces belonging to a package.\n */\n unregister(packageId: string): string[] {\n const removed: string[] = [];\n for (const [ns, entry] of this.registry) {\n if (entry.packageId === packageId) {\n this.registry.delete(ns);\n removed.push(ns);\n }\n }\n this.logger.debug('Namespaces unregistered', { packageId, count: removed.length });\n return removed;\n }\n\n /**\n * Check whether a set of namespaces is available for a given package.\n */\n checkAvailability(packageId: string, namespaces: string[]): NamespaceCheckResult {\n const conflicts: NamespaceConflict[] = [];\n const suggestions: Record = {};\n\n for (const ns of namespaces) {\n const existing = this.registry.get(ns);\n if (existing && existing.packageId !== packageId) {\n const suggestion = this.suggestAlternative(ns, packageId);\n conflicts.push({\n namespace: ns,\n existingPackageId: existing.packageId,\n incomingPackageId: packageId,\n suggestion,\n });\n suggestions[ns] = suggestion;\n }\n }\n\n return {\n available: conflicts.length === 0,\n conflicts,\n suggestions,\n };\n }\n\n /**\n * Extract namespace strings from a package's metadata definition.\n */\n extractNamespaces(config: Record): string[] {\n const namespaces: string[] = [];\n const categories = [\n 'objects', 'views', 'pages', 'flows', 'workflows',\n 'apps', 'dashboards', 'reports', 'actions', 'agents',\n ];\n\n for (const category of categories) {\n const items = config[category];\n if (Array.isArray(items)) {\n for (const item of items) {\n const name = (item as Record)?.name;\n if (typeof name === 'string') {\n namespaces.push(`${category}.${name}`);\n }\n }\n } else if (items && typeof items === 'object') {\n for (const key of Object.keys(items as object)) {\n namespaces.push(`${category}.${key}`);\n }\n }\n }\n\n return namespaces;\n }\n\n /**\n * Get all registered entries.\n */\n getRegistry(): ReadonlyMap {\n return this.registry;\n }\n\n /**\n * Get all namespaces belonging to a specific package.\n */\n getPackageNamespaces(packageId: string): string[] {\n const namespaces: string[] = [];\n for (const [ns, entry] of this.registry) {\n if (entry.packageId === packageId) {\n namespaces.push(ns);\n }\n }\n return namespaces;\n }\n\n /**\n * Generate a prefixed alternative namespace to avoid conflicts.\n */\n private suggestAlternative(ns: string, packageId: string): string {\n // Extract the short package name for prefixing\n const shortName = packageId\n .replace(/^@[^/]+\\//, '')\n .replace(/^plugin-/, '')\n .replace(/-/g, '_');\n\n const parts = ns.split('.');\n if (parts.length >= 2) {\n // e.g. \"objects.task\" → \"objects.crm_task\"\n return `${parts[0]}.${shortName}_${parts.slice(1).join('.')}`;\n }\n return `${shortName}_${ns}`;\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ObjectLogger } from './logger.js';\nimport { DependencyResolver, SemanticVersionManager } from './dependency-resolver.js';\nimport { NamespaceResolver } from './namespace-resolver.js';\n\n/**\n * Installed package record in the runtime registry.\n */\nexport interface InstalledPackageRecord {\n /** Package identifier */\n packageId: string;\n /** Package version */\n version: string;\n /** Package manifest */\n manifest: Record;\n /** Installation timestamp */\n installedAt: string;\n /** Current status */\n status: 'installed' | 'disabled' | 'installing' | 'upgrading' | 'uninstalling' | 'error';\n /** Namespaces registered by this package */\n namespaces: string[];\n /** Dependencies of this package */\n dependencies: string[];\n}\n\n/**\n * Snapshot of a package's state before upgrade (for rollback).\n */\nexport interface PackageSnapshot {\n /** Package identifier */\n packageId: string;\n /** Version before upgrade */\n previousVersion: string;\n /** Full manifest before upgrade */\n previousManifest: Record;\n /** Namespaces before upgrade */\n previousNamespaces: string[];\n /** Original installation timestamp */\n installedAt: string;\n /** Snapshot timestamp */\n createdAt: string;\n}\n\n/**\n * Result of a package installation attempt.\n */\nexport interface InstallResult {\n success: boolean;\n packageId: string;\n version: string;\n installedDependencies: string[];\n namespaceConflicts: Array<{ namespace: string; existingPackageId: string }>;\n errorMessage?: string;\n}\n\n/**\n * Result of an upgrade attempt.\n */\nexport interface UpgradeResult {\n success: boolean;\n packageId: string;\n fromVersion: string;\n toVersion: string;\n snapshot: PackageSnapshot;\n errorMessage?: string;\n}\n\n/**\n * Result of a rollback attempt.\n */\nexport interface RollbackResult {\n success: boolean;\n packageId: string;\n restoredVersion: string;\n errorMessage?: string;\n}\n\n/**\n * Package Manager\n *\n * Runtime implementation for the full package lifecycle:\n * install → upgrade → rollback → uninstall.\n *\n * Consumes the protocol schemas defined in @objectstack/spec:\n * - DependencyResolutionResultSchema\n * - NamespaceConflictErrorSchema\n * - UpgradePlanSchema / UpgradeSnapshotSchema\n * - PackageArtifactSchema\n *\n * Coordinates with:\n * - DependencyResolver for topological ordering and conflict detection\n * - NamespaceResolver for metadata collision prevention\n */\nexport class PackageManager {\n private logger: ObjectLogger;\n private packages: Map = new Map();\n private snapshots: Map = new Map();\n private dependencyResolver: DependencyResolver;\n private namespaceResolver: NamespaceResolver;\n private platformVersion: string;\n\n constructor(\n logger: ObjectLogger,\n options: { platformVersion?: string } = {},\n ) {\n this.logger = logger.child({ component: 'PackageManager' });\n this.dependencyResolver = new DependencyResolver(logger);\n this.namespaceResolver = new NamespaceResolver(logger);\n this.platformVersion = options.platformVersion || '3.0.0';\n }\n\n /**\n * Install a package with full dependency resolution and namespace checking.\n */\n async install(\n packageId: string,\n version: string,\n manifest: Record,\n ): Promise {\n this.logger.info('Installing package', { packageId, version });\n\n // 1. Check if already installed\n if (this.packages.has(packageId)) {\n const existing = this.packages.get(packageId)!;\n if (existing.status === 'installed') {\n return {\n success: false,\n packageId,\n version,\n installedDependencies: [],\n namespaceConflicts: [],\n errorMessage: `Package ${packageId}@${existing.version} is already installed. Use upgrade instead.`,\n };\n }\n }\n\n // 2. Check platform compatibility\n const engine = (manifest as any).engine?.objectstack as string | undefined;\n if (engine) {\n const platformSemver = SemanticVersionManager.parse(this.platformVersion);\n if (!SemanticVersionManager.satisfies(platformSemver, engine)) {\n return {\n success: false,\n packageId,\n version,\n installedDependencies: [],\n namespaceConflicts: [],\n errorMessage: `Package requires platform ${engine}, but current platform is v${this.platformVersion}`,\n };\n }\n }\n\n // 3. Check namespace conflicts\n const namespaces = this.namespaceResolver.extractNamespaces(manifest);\n const nsCheck = this.namespaceResolver.checkAvailability(packageId, namespaces);\n if (!nsCheck.available) {\n return {\n success: false,\n packageId,\n version,\n installedDependencies: [],\n namespaceConflicts: nsCheck.conflicts.map(c => ({\n namespace: c.namespace,\n existingPackageId: c.existingPackageId,\n })),\n errorMessage: `Namespace conflicts detected: ${nsCheck.conflicts.map(c => c.namespace).join(', ')}`,\n };\n }\n\n // 4. Resolve dependencies\n const deps = (manifest as any).dependencies as Record | undefined;\n const depNames = deps ? Object.keys(deps) : [];\n const missingDeps = depNames.filter(d => !this.packages.has(d));\n if (missingDeps.length > 0) {\n return {\n success: false,\n packageId,\n version,\n installedDependencies: [],\n namespaceConflicts: [],\n errorMessage: `Missing dependencies: ${missingDeps.join(', ')}`,\n };\n }\n\n // 5. Register package\n this.packages.set(packageId, {\n packageId,\n version,\n manifest,\n installedAt: new Date().toISOString(),\n status: 'installed',\n namespaces,\n dependencies: depNames,\n });\n\n // 6. Register namespaces\n this.namespaceResolver.register(packageId, namespaces);\n\n this.logger.info('Package installed', { packageId, version, namespaces: namespaces.length });\n\n return {\n success: true,\n packageId,\n version,\n installedDependencies: depNames,\n namespaceConflicts: [],\n };\n }\n\n /**\n * Uninstall a package, checking for dependents first.\n */\n async uninstall(packageId: string): Promise<{ success: boolean; errorMessage?: string }> {\n const pkg = this.packages.get(packageId);\n if (!pkg) {\n return { success: false, errorMessage: `Package ${packageId} is not installed` };\n }\n\n // Check if other packages depend on this one\n const dependents: string[] = [];\n for (const [id, record] of this.packages) {\n if (id !== packageId && record.dependencies.includes(packageId)) {\n dependents.push(id);\n }\n }\n\n if (dependents.length > 0) {\n return {\n success: false,\n errorMessage: `Cannot uninstall ${packageId}: depended upon by ${dependents.join(', ')}`,\n };\n }\n\n // Remove namespaces and package\n this.namespaceResolver.unregister(packageId);\n this.packages.delete(packageId);\n this.snapshots.delete(packageId);\n\n this.logger.info('Package uninstalled', { packageId });\n return { success: true };\n }\n\n /**\n * Upgrade a package: snapshot → update → register.\n */\n async upgrade(\n packageId: string,\n newVersion: string,\n newManifest: Record,\n ): Promise {\n const existing = this.packages.get(packageId);\n if (!existing) {\n return {\n success: false,\n packageId,\n fromVersion: '',\n toVersion: newVersion,\n snapshot: { packageId, previousVersion: '', previousManifest: {}, previousNamespaces: [], installedAt: '', createdAt: new Date().toISOString() },\n errorMessage: `Package ${packageId} is not installed`,\n };\n }\n\n // 1. Create snapshot for rollback\n const snapshot: PackageSnapshot = {\n packageId,\n previousVersion: existing.version,\n previousManifest: existing.manifest,\n previousNamespaces: [...existing.namespaces],\n installedAt: existing.installedAt,\n createdAt: new Date().toISOString(),\n };\n this.snapshots.set(packageId, snapshot);\n\n // 2. Check platform compatibility\n const engine = (newManifest as any).engine?.objectstack as string | undefined;\n if (engine) {\n const platformSemver = SemanticVersionManager.parse(this.platformVersion);\n if (!SemanticVersionManager.satisfies(platformSemver, engine)) {\n return {\n success: false,\n packageId,\n fromVersion: existing.version,\n toVersion: newVersion,\n snapshot,\n errorMessage: `New version requires platform ${engine}, current is v${this.platformVersion}`,\n };\n }\n }\n\n // 3. Check namespace changes\n const newNamespaces = this.namespaceResolver.extractNamespaces(newManifest);\n // Temporarily remove old namespaces to check new ones\n this.namespaceResolver.unregister(packageId);\n const nsCheck = this.namespaceResolver.checkAvailability(packageId, newNamespaces);\n if (!nsCheck.available) {\n // Restore old namespaces on failure\n this.namespaceResolver.register(packageId, existing.namespaces);\n return {\n success: false,\n packageId,\n fromVersion: existing.version,\n toVersion: newVersion,\n snapshot,\n errorMessage: `Namespace conflicts in new version: ${nsCheck.conflicts.map(c => c.namespace).join(', ')}`,\n };\n }\n\n // 4. Register new namespaces and update record\n this.namespaceResolver.register(packageId, newNamespaces);\n const deps = (newManifest as any).dependencies as Record | undefined;\n\n this.packages.set(packageId, {\n packageId,\n version: newVersion,\n manifest: newManifest,\n installedAt: existing.installedAt,\n status: 'installed',\n namespaces: newNamespaces,\n dependencies: deps ? Object.keys(deps) : [],\n });\n\n this.logger.info('Package upgraded', { packageId, from: existing.version, to: newVersion });\n\n return {\n success: true,\n packageId,\n fromVersion: existing.version,\n toVersion: newVersion,\n snapshot,\n };\n }\n\n /**\n * Rollback a package to its pre-upgrade snapshot.\n */\n async rollback(packageId: string): Promise {\n const snapshot = this.snapshots.get(packageId);\n if (!snapshot) {\n return {\n success: false,\n packageId,\n restoredVersion: '',\n errorMessage: `No upgrade snapshot found for ${packageId}`,\n };\n }\n\n // Restore previous state\n this.namespaceResolver.unregister(packageId);\n this.namespaceResolver.register(packageId, snapshot.previousNamespaces);\n\n const deps = (snapshot.previousManifest as any).dependencies as Record | undefined;\n this.packages.set(packageId, {\n packageId,\n version: snapshot.previousVersion,\n manifest: snapshot.previousManifest,\n installedAt: snapshot.installedAt,\n status: 'installed',\n namespaces: snapshot.previousNamespaces,\n dependencies: deps ? Object.keys(deps) : [],\n });\n\n this.snapshots.delete(packageId);\n\n this.logger.info('Package rolled back', { packageId, to: snapshot.previousVersion });\n\n return {\n success: true,\n packageId,\n restoredVersion: snapshot.previousVersion,\n };\n }\n\n /**\n * Get an installed package record.\n */\n getPackage(packageId: string): InstalledPackageRecord | undefined {\n return this.packages.get(packageId);\n }\n\n /**\n * List all installed packages.\n */\n listPackages(): InstalledPackageRecord[] {\n return Array.from(this.packages.values());\n }\n\n /**\n * Resolve dependencies for a set of packages.\n */\n resolveDependencies(\n packages: Map,\n ): string[] {\n return this.dependencyResolver.resolve(packages);\n }\n\n /**\n * Check namespace availability for a package's metadata.\n */\n checkNamespaces(packageId: string, config: Record): {\n available: boolean;\n conflicts: Array<{ namespace: string; existingPackageId: string }>;\n } {\n const namespaces = this.namespaceResolver.extractNamespaces(config);\n const result = this.namespaceResolver.checkAvailability(packageId, namespaces);\n return {\n available: result.available,\n conflicts: result.conflicts.map(c => ({\n namespace: c.namespace,\n existingPackageId: c.existingPackageId,\n })),\n };\n }\n\n /**\n * Get the namespace resolver instance.\n */\n getNamespaceResolver(): NamespaceResolver {\n return this.namespaceResolver;\n }\n\n /**\n * Get a snapshot for a given package (if available).\n */\n getSnapshot(packageId: string): PackageSnapshot | undefined {\n return this.snapshots.get(packageId);\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Query DSL Specification\n * \n * Based on industry best practices from:\n * - Prisma ORM\n * - Strapi CMS\n * - TypeORM\n * - LoopBack Framework\n * \n * Version: 1.0.0\n * Status: Draft\n * \n * Objective: Define a JSON-based, database-agnostic query syntax standard\n * for data filtering interactions between frontend and backend APIs.\n * \n * Design Principles:\n * 1. Declarative: Frontend describes \"what data to get\", not \"how to query\"\n * 2. Database Agnostic: Syntax contains no database-specific directives\n * 3. Type Safe: Structure can be statically inferred by TypeScript\n * 4. Convention over Configuration: Implicit syntax for common queries\n */\n\n/**\n * Field Reference\n * Represents a reference to another field/column instead of a literal value.\n * Used for joins (ON clause) and cross-field comparisons.\n * \n * @example\n * // user.id = order.owner_id\n * { \"$eq\": { \"$field\": \"order.owner_id\" } }\n */\nexport const FieldReferenceSchema = z.object({\n $field: z.string().describe('Field Reference/Column Name')\n});\n\nexport type FieldReference = z.infer;\n\n// ============================================================================\n// 3.1 Comparison Operators\n// ============================================================================\n\n/**\n * Comparison operators for equality and inequality checks.\n * Supported data types: Any\n */\nexport const EqualityOperatorSchema = z.object({\n /** Equal to (default) - SQL: = | MongoDB: $eq */\n $eq: z.any().optional(),\n \n /** Not equal to - SQL: <> or != | MongoDB: $ne */\n $ne: z.any().optional(),\n});\n\n/**\n * Comparison operators for numeric and date comparisons.\n * Supported data types: Number, Date\n */\nexport const ComparisonOperatorSchema = z.object({\n /** Greater than - SQL: > | MongoDB: $gt */\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Greater than or equal to - SQL: >= | MongoDB: $gte */\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than - SQL: < | MongoDB: $lt */\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than or equal to - SQL: <= | MongoDB: $lte */\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n});\n\n// ============================================================================\n// 3.2 Set & Range Operators\n// ============================================================================\n\n/**\n * Set operators for membership checks.\n */\nexport const SetOperatorSchema = z.object({\n /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */\n $in: z.array(z.any()).optional(),\n \n /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */\n $nin: z.array(z.any()).optional(),\n});\n\n/**\n * Range operator for interval checks (closed interval).\n * SQL: BETWEEN ? AND ? | MongoDB: $gte AND $lte\n */\nexport const RangeOperatorSchema = z.object({\n /** Between (inclusive) - takes [min, max] array */\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n});\n\n// ============================================================================\n// 3.3 String-Specific Operators\n// ============================================================================\n\n/**\n * String pattern matching operators.\n * Note: Case sensitivity should be handled at backend level.\n */\nexport const StringOperatorSchema = z.object({\n /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */\n $contains: z.string().optional(),\n \n /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */\n $notContains: z.string().optional(),\n \n /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */\n $startsWith: z.string().optional(),\n \n /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */\n $endsWith: z.string().optional(),\n});\n\n// ============================================================================\n// 3.5 Special Operators\n// ============================================================================\n\n/**\n * Special check operators for null and existence.\n */\nexport const SpecialOperatorSchema = z.object({\n /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */\n $null: z.boolean().optional(),\n \n /** Field exists check (primarily for NoSQL) - MongoDB: $exists */\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// Combined Field Operators\n// ============================================================================\n\n/**\n * All field-level operators combined.\n * These can be applied to individual fields in a filter.\n */\nexport const FieldOperatorsSchema = z.object({\n // Equality\n $eq: z.any().optional(),\n $ne: z.any().optional(),\n \n // Comparison (numeric/date)\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n // Set & Range\n $in: z.array(z.any()).optional(),\n $nin: z.array(z.any()).optional(),\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n \n // String-specific\n $contains: z.string().optional(),\n $notContains: z.string().optional(),\n $startsWith: z.string().optional(),\n $endsWith: z.string().optional(),\n \n // Special\n $null: z.boolean().optional(),\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// 3.4 Logical Operators & Recursive Filter Structure\n// ============================================================================\n\n/**\n * Recursive filter type that supports:\n * 1. Implicit equality: { field: value }\n * 2. Explicit operators: { field: { $op: value } }\n * 3. Logical combinations: { $and: [...], $or: [...], $not: {...} }\n * 4. Nested relations: { relation: { field: value } }\n */\nexport type FilterCondition = {\n [key: string]: \n | any // Implicit equality: key: value\n | z.infer // Explicit operators: key: { $op: value }\n | FilterCondition; // Nested relation: key: { nested: ... }\n} & {\n /** Logical AND - combines all conditions that must be true */\n $and?: FilterCondition[];\n \n /** Logical OR - at least one condition must be true */\n $or?: FilterCondition[];\n \n /** Logical NOT - negates the condition */\n $not?: FilterCondition;\n};\n\n/**\n * Zod schema for recursive filter validation.\n * Uses z.lazy() to handle recursive structure.\n */\nexport const FilterConditionSchema: z.ZodType = z.lazy(() =>\n z.record(z.string(), z.unknown()).and(\n z.object({\n $and: z.array(FilterConditionSchema).optional(),\n $or: z.array(FilterConditionSchema).optional(),\n $not: FilterConditionSchema.optional(),\n })\n )\n);\n\n// ============================================================================\n// Query Filter Wrapper\n// ============================================================================\n\n/**\n * Top-level query filter wrapper.\n * This is typically used as the \"where\" clause in a query.\n * \n * @example\n * ```typescript\n * const filter: QueryFilter = {\n * where: {\n * status: \"active\", // Implicit equality\n * age: { $gte: 18 }, // Explicit operator\n * $or: [ // Logical combination\n * { role: \"admin\" },\n * { email: { $contains: \"@company.com\" } }\n * ],\n * profile: { // Nested relation\n * verified: true\n * }\n * }\n * }\n * ```\n */\nexport const QueryFilterSchema = z.object({\n where: FilterConditionSchema.optional(),\n});\n\n// ============================================================================\n// TypeScript Type Exports\n// ============================================================================\n\n/**\n * Type-safe filter operators for use in TypeScript.\n * \n * @example\n * ```typescript\n * type UserFilter = Filter;\n * \n * const filter: UserFilter = {\n * age: { $gte: 18 },\n * email: { $contains: \"@example.com\" }\n * };\n * ```\n */\nexport type Filter = {\n [K in keyof T]?: \n | T[K] // Implicit equality\n | {\n $eq?: T[K];\n $ne?: T[K];\n $gt?: T[K] extends number | Date ? T[K] : never;\n $gte?: T[K] extends number | Date ? T[K] : never;\n $lt?: T[K] extends number | Date ? T[K] : never;\n $lte?: T[K] extends number | Date ? T[K] : never;\n $in?: T[K][];\n $nin?: T[K][];\n $between?: T[K] extends number | Date ? [T[K], T[K]] : never;\n $contains?: T[K] extends string ? string : never;\n $notContains?: T[K] extends string ? string : never;\n $startsWith?: T[K] extends string ? string : never;\n $endsWith?: T[K] extends string ? string : never;\n $null?: boolean;\n $exists?: boolean;\n }\n | (T[K] extends object ? Filter : never); // Nested relation\n} & {\n $and?: Filter[];\n $or?: Filter[];\n $not?: Filter;\n};\n\n/**\n * Scalar types supported by the filter system.\n */\nexport type Scalar = string | number | boolean | Date | null;\n\n// Export inferred types\nexport type FieldOperators = z.infer;\nexport type QueryFilter = z.infer;\n\n// ============================================================================\n// Normalization Utilities (Internal Representation)\n// ============================================================================\n\n/**\n * Normalized filter AST structure.\n * This is the internal representation after converting all syntactic sugar\n * to explicit operators.\n * \n * Stage 1: Normalization Pass\n * Input: { age: 18, role: \"admin\" }\n * Output: { $and: [{ age: { $eq: 18 } }, { role: { $eq: \"admin\" } }] }\n * \n * This simplifies adapter implementation by providing a consistent structure.\n */\nexport const NormalizedFilterSchema: z.ZodType = z.lazy(() => \n z.object({\n $and: z.array(\n z.union([\n // Field condition: { field: { $op: value } }\n z.record(z.string(), FieldOperatorsSchema),\n // Nested logical group\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $or: z.array(\n z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $not: z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ]).optional(),\n })\n);\n\nexport type NormalizedFilter = z.infer;\n\n// ============================================================================\n// AST Array Format Detection & Validation\n// ============================================================================\n\n/**\n * Set of valid AST comparison operators (case-insensitive).\n * Used by `isFilterAST()` to validate AST structure beyond `Array.isArray`.\n */\nexport const VALID_AST_OPERATORS = new Set([\n '=', '==', '!=', '<>', '>', '>=', '<', '<=',\n 'in', 'nin', 'not_in',\n 'contains', 'notcontains', 'not_contains', 'like',\n 'startswith', 'starts_with',\n 'endswith', 'ends_with',\n 'between',\n 'is_null', 'is_not_null',\n]);\n\n/**\n * Detect whether a value is a valid Filter AST array structure.\n *\n * A valid AST is one of:\n * - Comparison node: `[field: string, operator: string, value: unknown]` where operator is a known operator\n * - Logical node: `[\"and\" | \"or\", ...children]` where children are valid AST nodes\n * - Legacy flat array: `[[cond], [cond], ...]` where all elements are sub-arrays (each a valid AST node)\n *\n * This replaces the naïve `Array.isArray(filter)` check, preventing accidental\n * misidentification of arbitrary arrays as filter ASTs.\n *\n * @example\n * isFilterAST([\"status\", \"=\", \"active\"]) // true\n * isFilterAST([\"and\", [\"a\", \"=\", 1], [\"b\", \">\", 2]]) // true\n * isFilterAST([[\"a\", \"=\", 1], [\"b\", \"=\", 2]]) // true (legacy)\n * isFilterAST([1, 2, 3]) // false\n * isFilterAST(\"not an array\") // false\n * isFilterAST({ status: \"active\" }) // false\n */\nexport function isFilterAST(filter: unknown): boolean {\n if (!Array.isArray(filter) || filter.length === 0) return false;\n\n const first = filter[0];\n\n // Logical node: [\"and\", ...] or [\"or\", ...]\n if (typeof first === 'string') {\n const lower = first.toLowerCase();\n if (lower === 'and' || lower === 'or') {\n return filter.length >= 2 && filter.slice(1).every((child: unknown) => isFilterAST(child));\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof filter[1] === 'string') {\n return VALID_AST_OPERATORS.has(filter[1].toLowerCase());\n }\n }\n\n // Legacy flat array: [[cond], [cond], ...]\n if (filter.every((item: unknown) => isFilterAST(item))) {\n return filter.length > 0;\n }\n\n return false;\n}\n\n// ============================================================================\n// AST Array → FilterCondition Conversion\n// ============================================================================\n\n/**\n * Operator mapping from AST infix operators to FilterCondition `$`-prefixed operators.\n */\nconst AST_OPERATOR_MAP: Record = {\n '=': '$eq',\n '==': '$eq',\n '!=': '$ne',\n '<>': '$ne',\n '>': '$gt',\n '>=': '$gte',\n '<': '$lt',\n '<=': '$lte',\n 'in': '$in',\n 'nin': '$nin',\n 'not_in': '$nin',\n 'contains': '$contains',\n 'notcontains': '$notContains',\n 'not_contains': '$notContains',\n 'like': '$contains',\n 'startswith': '$startsWith',\n 'starts_with': '$startsWith',\n 'endswith': '$endsWith',\n 'ends_with': '$endsWith',\n 'between': '$between',\n 'is_null': '$null',\n 'is_not_null': '$null',\n};\n\n/**\n * Convert a single AST comparison node `[field, operator, value]` to a FilterCondition object.\n */\nfunction convertComparison(node: [string, string, unknown]): FilterCondition {\n const [field, operator, value] = node;\n const op = operator.toLowerCase();\n\n // Special case: equality shorthand\n if (op === '=' || op === '==') {\n return { [field]: value } as FilterCondition;\n }\n\n // Null check operators\n if (op === 'is_null') {\n return { [field]: { $null: true } } as FilterCondition;\n }\n if (op === 'is_not_null') {\n return { [field]: { $null: false } } as FilterCondition;\n }\n\n const mapped = AST_OPERATOR_MAP[op];\n if (mapped) {\n return { [field]: { [mapped]: value } } as FilterCondition;\n }\n\n // Fallback: use the operator as-is with $ prefix\n return { [field]: { [`$${op}`]: value } } as FilterCondition;\n}\n\n/**\n * Parse a filter from AST array format to FilterCondition object format.\n *\n * The AST array format is used by the ObjectUI client and the `FilterBuilder`:\n * - Comparison: `[field, operator, value]` → `{ field: value }` or `{ field: { $op: value } }`\n * - Logical AND: `[\"and\", cond1, cond2, ...]` → `{ $and: [...] }`\n * - Logical OR: `[\"or\", cond1, cond2, ...]` → `{ $or: [...] }`\n *\n * If the input is already a FilterCondition object (not an array), it is returned as-is.\n * If the input is `null` or `undefined`, it is returned as-is.\n *\n * @example\n * // Simple condition\n * parseFilterAST([\"status\", \"=\", \"active\"])\n * // → { status: \"active\" }\n *\n * @example\n * // Compound AND\n * parseFilterAST([\"and\", [\"priority\", \"=\", \"high\"], [\"status\", \"=\", \"active\"]])\n * // → { $and: [{ priority: \"high\" }, { status: \"active\" }] }\n *\n * @example\n * // Object passthrough\n * parseFilterAST({ status: \"active\" })\n * // → { status: \"active\" }\n */\nexport function parseFilterAST(filter: unknown): FilterCondition | undefined {\n if (filter == null) return undefined;\n if (!Array.isArray(filter)) return filter as FilterCondition;\n if (filter.length === 0) return undefined;\n\n const first = filter[0];\n\n // Logical node: [\"and\", cond1, cond2, ...] or [\"or\", cond1, cond2, ...]\n if (typeof first === 'string' && (first.toLowerCase() === 'and' || first.toLowerCase() === 'or')) {\n const logicOp = `$${first.toLowerCase()}` as '$and' | '$or';\n const children = filter.slice(1).map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { [logicOp]: children } as FilterCondition;\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof first === 'string') {\n return convertComparison(filter as [string, string, unknown]);\n }\n\n // Legacy flat array: [[field, op, val], [field, op, val], ...]\n // All elements are sub-arrays → treat as implicit AND\n if (filter.every((item: unknown) => Array.isArray(item))) {\n const children = filter.map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { $and: children } as FilterCondition;\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Constants & Metadata\n// ============================================================================\n\n/**\n * All supported operator keys.\n * Useful for validation and parsing.\n */\nexport const FILTER_OPERATORS = [\n // Equality\n '$eq', '$ne',\n // Comparison\n '$gt', '$gte', '$lt', '$lte',\n // Set & Range\n '$in', '$nin', '$between',\n // String\n '$contains', '$notContains', '$startsWith', '$endsWith',\n // Special\n '$null', '$exists',\n] as const;\n\n/**\n * Logical operator keys.\n */\nexport const LOGICAL_OPERATORS = ['$and', '$or', '$not'] as const;\n\n/**\n * All operator keys (field + logical).\n */\nexport const ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS] as const;\n\nexport type FilterOperatorKey = typeof FILTER_OPERATORS[number];\nexport type LogicalOperatorKey = typeof LOGICAL_OPERATORS[number];\nexport type OperatorKey = typeof ALL_OPERATORS[number];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\n\n/**\n * Sort Node\n * Represents \"Order By\".\n */\nexport const SortNodeSchema = z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc']).default('asc')\n});\n\n/**\n * Aggregation Function Enum\n * Standard aggregation functions for data analysis.\n * \n * Supported Functions:\n * - **count**: Count rows (SQL: COUNT(*) or COUNT(field))\n * - **sum**: Sum numeric values (SQL: SUM(field))\n * - **avg**: Average numeric values (SQL: AVG(field))\n * - **min**: Minimum value (SQL: MIN(field))\n * - **max**: Maximum value (SQL: MAX(field))\n * - **count_distinct**: Count unique values (SQL: COUNT(DISTINCT field))\n * - **array_agg**: Aggregate values into array (SQL: ARRAY_AGG(field))\n * - **string_agg**: Concatenate values (SQL: STRING_AGG(field, delimiter))\n * \n * Performance Considerations:\n * - COUNT(*) is typically faster than COUNT(field) as it doesn't check for nulls\n * - COUNT DISTINCT may require additional memory for tracking unique values\n * - Window aggregates (with OVER clause) can be more efficient than subqueries\n * - Large GROUP BY operations benefit from proper indexing on grouped fields\n * \n * @example\n * // SQL: SELECT region, SUM(amount) FROM sales GROUP BY region\n * {\n * object: 'sales',\n * fields: ['region'],\n * aggregations: [\n * { function: 'sum', field: 'amount', alias: 'total_sales' }\n * ],\n * groupBy: ['region']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT COUNT(Id) FROM Account\n * {\n * object: 'account',\n * aggregations: [\n * { function: 'count', alias: 'total_accounts' }\n * ]\n * }\n */\nexport const AggregationFunction = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'array_agg', 'string_agg'\n]);\n\n/**\n * Aggregation Node\n * Represents an aggregated field with function.\n * \n * Aggregations summarize data across groups of rows (GROUP BY).\n * Used with `groupBy` to create analytical queries.\n * \n * @example\n * // SQL: SELECT customer_id, COUNT(*), SUM(amount) FROM orders GROUP BY customer_id\n * {\n * object: 'order',\n * fields: ['customer_id'],\n * aggregations: [\n * { function: 'count', alias: 'order_count' },\n * { function: 'sum', field: 'amount', alias: 'total_amount' }\n * ],\n * groupBy: ['customer_id']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT LeadSource, COUNT(Id) FROM Lead GROUP BY LeadSource\n * {\n * object: 'lead',\n * fields: ['lead_source'],\n * aggregations: [\n * { function: 'count', alias: 'lead_count' }\n * ],\n * groupBy: ['lead_source']\n * }\n */\nexport const AggregationNodeSchema = z.object({\n function: AggregationFunction.describe('Aggregation function'),\n field: z.string().optional().describe('Field to aggregate (optional for COUNT(*))'),\n alias: z.string().describe('Result column alias'),\n distinct: z.boolean().optional().describe('Apply DISTINCT before aggregation'),\n filter: FilterConditionSchema.optional().describe('Filter/Condition to apply to the aggregation (FILTER WHERE clause)'),\n});\n\n/**\n * Join Type Enum\n * Standard SQL join types for combining tables.\n * \n * Join Types:\n * - **inner**: Returns only matching rows from both tables (SQL: INNER JOIN)\n * - **left**: Returns all rows from left table, matching rows from right (SQL: LEFT JOIN)\n * - **right**: Returns all rows from right table, matching rows from left (SQL: RIGHT JOIN)\n * - **full**: Returns all rows from both tables (SQL: FULL OUTER JOIN)\n * \n * @example\n * // SQL: SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * on: ['order.customer_id', '=', 'customer.id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL-style: Find all customers and their orders (if any)\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * on: ['customer.id', '=', 'order.customer_id']\n * }\n * ]\n * }\n */\nexport const JoinType = z.enum(['inner', 'left', 'right', 'full']);\n\n/**\n * Join Execution Strategy\n * Hints to the query engine on how to execute the join.\n * \n * Strategies:\n * - **auto**: Engine decides best strategy (Default).\n * - **database**: Push down join to the database (Requires same datasource).\n * - **hash**: Load both sets into memory and hash join (Cross-datasource, memory intensive).\n * - **loop**: Nested loop lookup (N+1 safe version). (Good for small right-side lookups).\n */\nexport const JoinStrategy = z.enum(['auto', 'database', 'hash', 'loop']);\n\n/**\n * Join Node\n * Represents table joins for combining data from multiple objects.\n * \n * Joins connect related data across multiple tables using ON conditions.\n * Supports both direct object joins and subquery joins.\n * \n * @example\n * // SQL: SELECT o.*, c.name FROM orders o INNER JOIN customers c ON o.customer_id = c.id\n * {\n * object: 'order',\n * fields: ['id', 'amount'],\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Multi-table join\n * // SELECT * FROM orders o\n * // INNER JOIN customers c ON o.customer_id = c.id\n * // LEFT JOIN shipments s ON o.id = s.order_id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * },\n * {\n * type: 'left',\n * object: 'shipment',\n * alias: 's',\n * on: ['order.id', '=', 's.order_id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT Name, (SELECT LastName FROM Contacts) FROM Account\n * {\n * object: 'account',\n * fields: ['name'],\n * joins: [\n * {\n * type: 'left',\n * object: 'contact',\n * on: ['account.id', '=', 'contact.account_id']\n * }\n * ]\n * }\n * \n * @example\n * // Subquery Join: Join with a filtered/aggregated dataset\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * alias: 'high_value_orders',\n * on: ['customer.id', '=', 'high_value_orders.customer_id'],\n * subquery: {\n * object: 'order',\n * fields: ['customer_id', 'total'],\n * filters: ['total', '>', 1000]\n * }\n * }\n * ]\n * }\n */\nexport const JoinNodeSchema: z.ZodType = z.lazy(() => \n z.object({\n type: JoinType.describe('Join type'),\n strategy: JoinStrategy.optional().describe('Execution strategy hint'),\n object: z.string().describe('Object/table to join'),\n alias: z.string().optional().describe('Table alias'),\n on: FilterConditionSchema.describe('Join condition'),\n subquery: z.lazy(() => QuerySchema).optional().describe('Subquery instead of object'),\n })\n);\n\n/**\n * Window Function Enum\n * Advanced analytical functions for row-based calculations.\n * \n * Window Functions:\n * - **row_number**: Sequential number within partition (SQL: ROW_NUMBER() OVER (...))\n * - **rank**: Rank with gaps for ties (SQL: RANK() OVER (...))\n * - **dense_rank**: Rank without gaps (SQL: DENSE_RANK() OVER (...))\n * - **percent_rank**: Relative rank as percentage (SQL: PERCENT_RANK() OVER (...))\n * - **lag**: Access previous row value (SQL: LAG(field) OVER (...))\n * - **lead**: Access next row value (SQL: LEAD(field) OVER (...))\n * - **first_value**: First value in window (SQL: FIRST_VALUE(field) OVER (...))\n * - **last_value**: Last value in window (SQL: LAST_VALUE(field) OVER (...))\n * - **sum/avg/count/min/max**: Aggregates over window (SQL: SUM(field) OVER (...))\n * \n * @example\n * // SQL: SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) as rank\n * // FROM orders\n * {\n * object: 'order',\n * fields: ['id', 'customer_id', 'amount'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'rank',\n * over: {\n * partitionBy: ['customer_id'],\n * orderBy: [{ field: 'amount', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Running total with SUM() OVER (...)\n * {\n * object: 'transaction',\n * fields: ['date', 'amount'],\n * windowFunctions: [\n * {\n * function: 'sum',\n * field: 'amount',\n * alias: 'running_total',\n * over: {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: 'UNBOUNDED PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunction = z.enum([\n 'row_number', 'rank', 'dense_rank', 'percent_rank',\n 'lag', 'lead', 'first_value', 'last_value',\n 'sum', 'avg', 'count', 'min', 'max'\n]);\n\n/**\n * Window Specification\n * Defines PARTITION BY and ORDER BY for window functions.\n * \n * Window specifications control how window functions compute values:\n * - **partitionBy**: Divide rows into groups (like GROUP BY but without collapsing rows)\n * - **orderBy**: Define order for ranking and offset functions\n * - **frame**: Specify which rows to include in aggregate calculations\n * \n * @example\n * // Partition by department, order by salary\n * {\n * partitionBy: ['department'],\n * orderBy: [{ field: 'salary', order: 'desc' }]\n * }\n * \n * @example\n * // Moving average with frame specification\n * {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: '6 PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n */\nexport const WindowSpecSchema = z.object({\n partitionBy: z.array(z.string()).optional().describe('PARTITION BY fields'),\n orderBy: z.array(SortNodeSchema).optional().describe('ORDER BY specification'),\n frame: z.object({\n type: z.enum(['rows', 'range']).optional(),\n start: z.string().optional().describe('Frame start (e.g., \"UNBOUNDED PRECEDING\", \"1 PRECEDING\")'),\n end: z.string().optional().describe('Frame end (e.g., \"CURRENT ROW\", \"1 FOLLOWING\")'),\n }).optional().describe('Window frame specification'),\n});\n\n/**\n * Window Function Node\n * Represents window function with OVER clause.\n * \n * Window functions perform calculations across a set of rows related to the current row,\n * without collapsing the result set (unlike GROUP BY aggregations).\n * \n * @example\n * // SQL: Top 3 products per category\n * // SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as rank\n * // FROM products\n * {\n * object: 'product',\n * fields: ['name', 'category', 'sales'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'category_rank',\n * over: {\n * partitionBy: ['category'],\n * orderBy: [{ field: 'sales', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Year-over-year comparison with LAG\n * {\n * object: 'monthly_sales',\n * fields: ['month', 'revenue'],\n * windowFunctions: [\n * {\n * function: 'lag',\n * field: 'revenue',\n * alias: 'prev_year_revenue',\n * over: {\n * orderBy: [{ field: 'month', order: 'asc' }]\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunctionNodeSchema = z.object({\n function: WindowFunction.describe('Window function name'),\n field: z.string().optional().describe('Field to operate on (for aggregate window functions)'),\n alias: z.string().describe('Result column alias'),\n over: WindowSpecSchema.describe('Window specification (OVER clause)'),\n});\n\n/**\n * Field Selection Node\n * Represents \"Select\" attributes, including joins.\n */\nexport const FieldNodeSchema: z.ZodType = z.lazy(() => \n z.union([\n z.string(), // Primitive field: \"name\"\n z.object({\n field: z.string(), // Relationship field: \"owner\"\n fields: z.array(FieldNodeSchema).optional(), // Nested select: [\"name\", \"email\"]\n alias: z.string().optional()\n })\n ])\n);\n\n/**\n * Full-Text Search Configuration\n * Defines full-text search parameters for text queries.\n * \n * Supports:\n * - Multi-field search\n * - Relevance scoring\n * - Fuzzy matching\n * - Language-specific analyzers\n * \n * @example\n * {\n * query: \"John Smith\",\n * fields: [\"name\", \"email\", \"description\"],\n * fuzzy: true,\n * boost: { \"name\": 2.0, \"email\": 1.5 }\n * }\n */\nexport const FullTextSearchSchema = z.object({\n query: z.string().describe('Search query text'),\n fields: z.array(z.string()).optional().describe('Fields to search in (if not specified, searches all text fields)'),\n fuzzy: z.boolean().optional().default(false).describe('Enable fuzzy matching (tolerates typos)'),\n operator: z.enum(['and', 'or']).optional().default('or').describe('Logical operator between terms'),\n boost: z.record(z.string(), z.number()).optional().describe('Field-specific relevance boosting (field name -> boost factor)'),\n minScore: z.number().optional().describe('Minimum relevance score threshold'),\n language: z.string().optional().describe('Language for text analysis (e.g., \"en\", \"zh\", \"es\")'),\n highlight: z.boolean().optional().default(false).describe('Enable search result highlighting'),\n});\n\nexport type FullTextSearch = z.infer;\n\n/**\n * Query AST Schema\n * The universal data retrieval contract defined in `ast-structure.mdx`.\n * \n * This schema represents ObjectQL - a universal query language that abstracts\n * SQL, NoSQL, and SaaS APIs into a single unified interface.\n * \n * Updates (v2):\n * - Aligned with modern ORM standards (Prisma/TypeORM)\n * - Added `cursor` based pagination support\n * - Renamed `top`/`skip` to `limit`/`offset`\n * - Unified filtering syntax with `FilterConditionSchema`\n * \n * Updates (v3):\n * - Added `search` parameter for full-text search (P2 requirement)\n * \n * @example\n * // Simple query: SELECT name, email FROM account WHERE status = 'active'\n * {\n * object: 'account',\n * fields: ['name', 'email'],\n * where: { status: 'active' }\n * }\n * \n * @example\n * // Pagination with Limit/Offset\n * {\n * object: 'post',\n * where: { published: true },\n * orderBy: [{ field: 'created_at', order: 'desc' }],\n * limit: 20,\n * offset: 40\n * }\n * \n * @example\n * // Full-text search\n * {\n * object: 'article',\n * search: {\n * query: \"machine learning\",\n * fields: [\"title\", \"content\"],\n * fuzzy: true,\n * boost: { \"title\": 2.0 }\n * },\n * limit: 10\n * }\n */\nconst BaseQuerySchema = z.object({\n /** Target Entity */\n object: z.string().describe('Object name (e.g. account)'),\n \n /** Select Clause */\n fields: z.array(FieldNodeSchema).optional().describe('Fields to retrieve'),\n \n /** Where Clause (Filtering) */\n where: FilterConditionSchema.optional().describe('Filtering criteria (WHERE)'),\n \n /** Full-Text Search */\n search: FullTextSearchSchema.optional().describe('Full-text search configuration ($search parameter)'),\n \n /** Order By Clause (Sorting) */\n orderBy: z.array(SortNodeSchema).optional().describe('Sorting instructions (ORDER BY)'),\n \n /** Pagination */\n limit: z.number().optional().describe('Max records to return (LIMIT)'),\n offset: z.number().optional().describe('Records to skip (OFFSET)'),\n top: z.number().optional().describe('Alias for limit (OData compatibility)'),\n cursor: z.record(z.string(), z.unknown()).optional().describe('Cursor for keyset pagination'),\n \n /** Joins */\n joins: z.array(JoinNodeSchema).optional().describe('Explicit Table Joins'),\n \n /** Aggregations */\n aggregations: z.array(AggregationNodeSchema).optional().describe('Aggregation functions'),\n \n /** Group By Clause */\n groupBy: z.array(z.string()).optional().describe('GROUP BY fields'),\n \n /** Having Clause */\n having: FilterConditionSchema.optional().describe('HAVING clause for aggregation filtering'),\n \n /** Window Functions */\n windowFunctions: z.array(WindowFunctionNodeSchema).optional().describe('Window functions with OVER clause'),\n \n /** Subquery flag */\n distinct: z.boolean().optional().describe('SELECT DISTINCT flag'),\n});\n\n/**\n * QueryAST — Abstract Syntax Tree for data queries.\n *\n * The `expand` property enables recursive loading of related records through\n * lookup and master_detail fields. Each key is a relationship field name; the\n * value is a nested QueryAST that can further filter, select, sort, and expand\n * the related records (up to a default max depth of 3).\n *\n * @example\n * ```ts\n * const ast: QueryAST = {\n * object: 'task',\n * fields: ['title', 'assignee'],\n * expand: {\n * assignee: { object: 'user', fields: ['name', 'email'] },\n * project: {\n * object: 'project',\n * expand: { org: { object: 'org' } } // nested expand\n * }\n * }\n * };\n * ```\n */\nexport type QueryAST = z.infer & {\n expand?: Record;\n};\n\nexport type QueryInput = z.input & {\n expand?: Record;\n};\n\nexport const QuerySchema: z.ZodType = BaseQuerySchema.extend({\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional().describe(\n 'Recursive relation loading map. Keys are lookup/master_detail field names; '\n + 'values are nested QueryAST objects that control select, filter, sort, and '\n + 'further expansion on the related object. The engine resolves expand via '\n + 'batch $in queries (driver-agnostic) with a default max depth of 3.'\n ),\n});\n\nexport type SortNode = z.infer;\nexport type AggregationNode = z.infer;\nexport type JoinNode = z.infer;\nexport type WindowFunctionNode = z.infer;\nexport type WindowSpec = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { QuerySchema } from '../data/query.zod';\n\n// ==========================================\n// 1. Base Envelopes\n// ==========================================\n\nexport const ApiErrorSchema = z.object({\n code: z.string().describe('Error code (e.g. validation_error)'),\n message: z.string().describe('Readable error message'),\n category: z.string().optional().describe('Error category (e.g. validation, authorization)'),\n details: z.unknown().optional().describe('Additional error context (e.g. field validation errors)'),\n requestId: z.string().optional().describe('Request ID for tracking'),\n});\n\nexport const BaseResponseSchema = z.object({\n success: z.boolean().describe('Operation success status'),\n error: ApiErrorSchema.optional().describe('Error details if success is false'),\n meta: z.object({\n timestamp: z.string(),\n duration: z.number().optional(),\n requestId: z.string().optional(),\n traceId: z.string().optional(),\n }).optional().describe('Response metadata'),\n});\n\n// ==========================================\n// 2. Request Payloads (Inputs)\n// ==========================================\n\nexport const RecordDataSchema = z.record(z.string(), z.unknown()).describe('Key-value map of record data');\n\n/**\n * Standard Create Request\n */\nexport const CreateRequestSchema = z.object({\n data: RecordDataSchema.describe('Record data to insert'),\n});\n\n/**\n * Standard Update Request\n */\nexport const UpdateRequestSchema = z.object({\n data: RecordDataSchema.describe('Partial record data to update'),\n});\n\n/**\n * Standard Bulk Request\n */\nexport const BulkRequestSchema = z.object({\n records: z.array(RecordDataSchema).describe('Array of records to process'),\n allOrNone: z.boolean().default(true).describe('If true, rollback entire transaction on any failure'),\n});\n\n/**\n * Export Request\n */\nexport const ExportRequestSchema = z.intersection(\n QuerySchema,\n z.object({\n format: z.enum(['csv', 'json', 'xlsx']).default('csv'),\n })\n);\n\n// ==========================================\n// 3. Response Payloads (Outputs)\n// ==========================================\n\n/**\n * Single Record Response (Get/Create/Update)\n */\nexport const SingleRecordResponseSchema = BaseResponseSchema.extend({\n data: RecordDataSchema.describe('The requested or modified record'),\n});\n\n/**\n * List/Query Response\n */\nexport const ListRecordResponseSchema = BaseResponseSchema.extend({\n data: z.array(RecordDataSchema).describe('Array of matching records'),\n pagination: z.object({\n total: z.number().optional().describe('Total matching records count'),\n limit: z.number().optional().describe('Page size'),\n offset: z.number().optional().describe('Page offset'),\n cursor: z.string().optional().describe('Cursor for next page'),\n nextCursor: z.string().optional().describe('Next cursor for pagination'),\n hasMore: z.boolean().describe('Are there more pages?'),\n }).describe('Pagination info'),\n});\n\n/**\n * ID Request (Get/Delete)\n */\nexport const IdRequestSchema = z.object({\n id: z.string().describe('Record ID'),\n});\n\n/**\n * Modification Result (for Batch/Bulk operations)\n */\nexport const ModificationResultSchema = z.object({\n id: z.string().optional().describe('Record ID if processed'),\n success: z.boolean(),\n errors: z.array(ApiErrorSchema).optional(),\n index: z.number().optional().describe('Index in original request'),\n data: z.unknown().optional().describe('Result data (e.g. created record)'),\n});\n\n/**\n * Bulk Operation Response\n */\nexport const BulkResponseSchema = BaseResponseSchema.extend({\n data: z.array(ModificationResultSchema).describe('Results for each item in the batch'),\n});\n\n/**\n * Delete Response\n */\nexport const DeleteResponseSchema = BaseResponseSchema.extend({\n id: z.string().describe('ID of the deleted record'),\n});\n\n// ==========================================\n// 4. API Contract Registry\n// ==========================================\n\n/**\n * Standard API Contracts map\n * Used for generating SDKs and Documentation\n */\nexport const StandardApiContracts = {\n create: {\n input: CreateRequestSchema,\n output: SingleRecordResponseSchema\n },\n delete: {\n input: IdRequestSchema,\n output: DeleteResponseSchema\n },\n get: {\n input: IdRequestSchema,\n output: SingleRecordResponseSchema\n },\n update: {\n input: UpdateRequestSchema,\n output: SingleRecordResponseSchema\n },\n list: {\n input: QuerySchema,\n output: ListRecordResponseSchema\n },\n bulkCreate: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkUpdate: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkUpsert: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkDelete: {\n input: z.object({ ids: z.array(z.string()) }),\n output: BulkResponseSchema\n }\n};\n\n// ==========================================\n// 5. DataLoader / N+1 Query Prevention\n// ==========================================\n\n/**\n * DataLoader Configuration Schema\n * Batch loading configuration to prevent N+1 query problems\n */\nexport const DataLoaderConfigSchema = z.object({\n maxBatchSize: z.number().int().default(100).describe('Maximum number of keys per batch load'),\n batchScheduleFn: z.enum(['microtask', 'timeout', 'manual']).default('microtask')\n .describe('Scheduling strategy for collecting batch keys'),\n cacheEnabled: z.boolean().default(true).describe('Enable per-request result caching'),\n cacheKeyFn: z.string().optional().describe('Name or identifier of the cache key function'),\n cacheTtl: z.number().min(0).optional().describe('Cache time-to-live in seconds (0 = no expiration)'),\n coalesceRequests: z.boolean().default(true).describe('Deduplicate identical requests within a batch window'),\n maxConcurrency: z.number().int().optional().describe('Maximum parallel batch requests'),\n});\n\n/**\n * Batch Loading Strategy Schema\n * Defines how batched data loading is orchestrated\n */\nexport const BatchLoadingStrategySchema = z.object({\n strategy: z.enum(['dataloader', 'windowed', 'prefetch']).describe('Batch loading strategy type'),\n windowMs: z.number().optional().describe('Collection window duration in milliseconds (for windowed strategy)'),\n prefetchDepth: z.number().int().optional().describe('Depth of relation prefetching (for prefetch strategy)'),\n associationLoading: z.enum(['lazy', 'eager', 'batch']).default('batch')\n .describe('How to load related associations'),\n});\n\n/**\n * Query Optimization Configuration Schema\n * Top-level configuration for N+1 prevention and query optimization\n */\nexport const QueryOptimizationConfigSchema = z.object({\n preventNPlusOne: z.boolean().describe('Enable N+1 query detection and prevention'),\n dataLoader: DataLoaderConfigSchema.optional().describe('DataLoader batch loading configuration'),\n batchStrategy: BatchLoadingStrategySchema.optional().describe('Batch loading strategy configuration'),\n maxQueryDepth: z.number().int().describe('Maximum depth for nested relation queries'),\n queryComplexityLimit: z.number().optional().describe('Maximum allowed query complexity score'),\n enableQueryPlan: z.boolean().default(false).describe('Log query execution plans for debugging'),\n});\n\nexport type ApiError = z.infer;\nexport type BaseResponse = z.infer;\nexport type RecordData = z.infer;\nexport type CreateRequest = z.infer;\nexport type UpdateRequest = z.infer;\nexport type BulkRequest = z.infer;\nexport type ExportRequest = z.infer;\nexport type SingleRecordResponse = z.infer;\nexport type ListRecordResponse = z.infer;\nexport type IdRequest = z.infer;\nexport type ModificationResult = z.infer;\nexport type BulkResponse = z.infer;\nexport type DeleteResponse = z.infer;\nexport type DataLoaderConfig = z.infer;\nexport type BatchLoadingStrategy = z.infer;\nexport type QueryOptimizationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, RateLimitConfigSchema } from '../shared/http.zod';\n\n/**\n * API Mapping Schema\n * Transform input/output data.\n */\nexport const ApiMappingSchema = z.object({\n source: z.string().describe('Source field/path'),\n target: z.string().describe('Target field/path'),\n transform: z.string().optional().describe('Transformation function name'),\n});\n\n/**\n * API Endpoint Schema\n * Defines an external facing API contract.\n */\nexport const ApiEndpointSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique endpoint ID'),\n path: z.string().regex(/^\\//).describe('URL Path (e.g. /api/v1/customers)'),\n method: HttpMethod.describe('HTTP Method'),\n \n /** Documentation */\n summary: z.string().optional(),\n description: z.string().optional(),\n \n /** Execution Logic */\n type: z.enum(['flow', 'script', 'object_operation', 'proxy']).describe('Implementation type'),\n target: z.string().describe('Target Flow ID, Script Name, or Proxy URL'),\n \n /** Logic Config */\n objectParams: z.object({\n object: z.string().optional(),\n operation: z.enum(['find', 'get', 'create', 'update', 'delete']).optional(),\n }).optional().describe('For object_operation type'),\n \n /** Data Transformation */\n inputMapping: z.array(ApiMappingSchema).optional().describe('Map Request Body to Internal Params'),\n outputMapping: z.array(ApiMappingSchema).optional().describe('Map Internal Result to Response Body'),\n \n /** Policies */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n rateLimit: RateLimitConfigSchema.optional().describe('Rate limiting policy'),\n cacheTtl: z.number().optional().describe('Response cache TTL in seconds'),\n});\n\nexport const ApiEndpoint = Object.assign(ApiEndpointSchema, {\n create: >(config: T) => config,\n});\n\nexport type ApiEndpoint = z.infer;\nexport type ApiEndpointInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\n\n/**\n * Service Status Enum\n * Describes the operational state of a service in the discovery response.\n *\n * - `available` – Fully operational: service is registered AND HTTP handler is verified.\n * - `registered` – Route is declared in the dispatcher table but the HTTP handler has\n * not been verified (may 501 at runtime).\n * - `unavailable` – Service is not installed / not registered in the kernel.\n * - `degraded` – Partially working (e.g., in-memory fallback, missing persistence).\n * - `stub` – Placeholder handler that always returns 501 Not Implemented.\n */\nexport const ServiceStatus = z.enum([\n 'available',\n 'registered',\n 'unavailable',\n 'degraded',\n 'stub',\n]).describe(\n 'available = fully operational, registered = route declared but handler unverified, '\n + 'unavailable = not installed, degraded = partial, stub = placeholder that returns 501'\n);\n\nexport type ServiceStatus = z.infer;\n\n/**\n * Service Status in Discovery Response\n * Reports per-service availability so clients can adapt their UI accordingly.\n */\nexport const ServiceInfoSchema = z.object({\n /** Whether the service is enabled and available */\n enabled: z.boolean(),\n /** Current operational status */\n status: ServiceStatus,\n /**\n * Whether the HTTP handler for this service is confirmed to be mounted.\n *\n * Semantics:\n * - `undefined` (omitted) = handler readiness is unknown / not yet verified.\n * - `true` = handler is registered in the adapter / dispatcher (safe to call).\n * - `false` = route is declared but no handler exists or only a stub is present\n * — requests are expected to receive 501 Not Implemented.\n *\n * Clients SHOULD check this flag before displaying or invoking a service endpoint and may\n * distinguish between \"unknown\" (omitted) and \"known missing\" (`false`).\n */\n handlerReady: z.boolean().optional().describe(\n 'Whether the HTTP handler is confirmed to be mounted. '\n + 'Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501).'\n ),\n /** Route path (only present if enabled) */\n route: z.string().optional().describe('e.g. /api/v1/analytics'),\n /** Implementation provider name */\n provider: z.string().optional().describe('e.g. \"objectql\", \"plugin-redis\", \"driver-memory\"'),\n /** Service version */\n version: z.string().optional().describe('Semantic version of the service implementation (e.g. \"3.0.6\")'),\n /** Human-readable reason if unavailable */\n message: z.string().optional().describe('e.g. \"Install plugin-workflow to enable\"'),\n /** Rate limit configuration for this service */\n rateLimit: z.object({\n requestsPerMinute: z.number().int().optional().describe('Maximum requests per minute'),\n requestsPerHour: z.number().int().optional().describe('Maximum requests per hour'),\n burstLimit: z.number().int().optional().describe('Maximum burst request count'),\n retryAfterMs: z.number().int().optional().describe('Suggested retry-after delay in milliseconds when rate-limited'),\n }).optional().describe('Rate limit and quota info for this service'),\n});\n\n/**\n * API Routes Schema\n * The \"Map\" for the frontend to know where to send requests.\n * This decouples the frontend from hardcoded URL paths.\n */\nexport const ApiRoutesSchema = z.object({\n /** Base URL for Object CRUD (Data Protocol) */\n data: z.string().describe('e.g. /api/v1/data'),\n \n /** Base URL for Schema Definitions (Metadata Protocol) */\n metadata: z.string().describe('e.g. /api/v1/meta'),\n\n /** Base URL for API Discovery endpoint */\n discovery: z.string().optional().describe('e.g. /api/v1/discovery'),\n\n /** Base URL for UI Configurations (Views, Menus) */\n ui: z.string().optional().describe('e.g. /api/v1/ui'),\n \n /** Base URL for Authentication (plugin-provided) */\n auth: z.string().optional().describe('e.g. /api/v1/auth'),\n \n /** Base URL for Automation (Flows/Scripts) */\n automation: z.string().optional().describe('e.g. /api/v1/automation'),\n \n /** Base URL for File/Storage operations */\n storage: z.string().optional().describe('e.g. /api/v1/storage'),\n \n /** Base URL for Analytics/BI operations */\n analytics: z.string().optional().describe('e.g. /api/v1/analytics'),\n \n /** GraphQL Endpoint (if enabled) */\n graphql: z.string().optional().describe('e.g. /graphql'),\n\n /** Base URL for Package Management */\n packages: z.string().optional().describe('e.g. /api/v1/packages'),\n\n /** Base URL for Workflow Engine */\n workflow: z.string().optional().describe('e.g. /api/v1/workflow'),\n\n /** Base URL for Realtime (WebSocket/SSE) */\n realtime: z.string().optional().describe('e.g. /api/v1/realtime'),\n\n /** Base URL for Notification Service */\n notifications: z.string().optional().describe('e.g. /api/v1/notifications'),\n\n /** Base URL for AI Engine (NLQ, Chat, Suggest) */\n ai: z.string().optional().describe('e.g. /api/v1/ai'),\n\n /** Base URL for Internationalization */\n i18n: z.string().optional().describe('e.g. /api/v1/i18n'),\n\n /** Base URL for Feed / Chatter API */\n feed: z.string().optional().describe('e.g. /api/v1/feed'),\n});\n\n/**\n * Discovery Response Schema\n * The root object returned by the Metadata Discovery Endpoint.\n * \n * Design rationale:\n * - `services` is the single source of truth for service availability.\n * Each service entry includes `enabled`, `status`, `route`, and `provider`.\n * - `routes` is a convenience shortcut: a flat map of service-name → route-path\n * so that clients can resolve endpoints without iterating the services map.\n * - `capabilities`/`features` was removed because it was fully derivable\n * from `services[x].enabled`. Use `services` to determine feature availability.\n */\nexport const DiscoverySchema = z.object({\n /** System Identity */\n name: z.string(),\n version: z.string(),\n environment: z.enum(['production', 'sandbox', 'development']),\n \n /** Dynamic Routing — convenience shortcut for client routing */\n routes: ApiRoutesSchema,\n \n /** Localization Info (helping frontend init i18n) */\n locale: z.object({\n default: z.string(),\n supported: z.array(z.string()),\n timezone: z.string(),\n }),\n \n /**\n * Per-service status map.\n * This is the **single source of truth** for service availability.\n * Clients use this to determine which features are available,\n * show/hide UI elements, and display appropriate messages.\n */\n services: z.record(z.string(), ServiceInfoSchema).describe(\n 'Per-service availability map keyed by CoreServiceName'\n ),\n\n /**\n * Hierarchical capability descriptors.\n * Declares platform features so clients can adapt UI without probing individual services.\n * Each key is a capability domain (e.g., \"comments\", \"automation\", \"search\"),\n * and its value describes what sub-features are available.\n */\n capabilities: z.record(z.string(), z.object({\n enabled: z.boolean().describe('Whether this capability is available'),\n features: z.record(z.string(), z.boolean()).optional()\n .describe('Sub-feature flags within this capability'),\n description: z.string().optional()\n .describe('Human-readable capability description'),\n })).optional().describe('Hierarchical capability descriptors for frontend intelligent adaptation'),\n\n /**\n * Schema discovery URLs for cross-ecosystem interoperability.\n */\n schemaDiscovery: z.object({\n openapi: z.string().optional().describe('URL to OpenAPI (Swagger) specification (e.g., \"/api/v1/openapi.json\")'),\n graphql: z.string().optional().describe('URL to GraphQL schema endpoint (e.g., \"/graphql\")'),\n jsonSchema: z.string().optional().describe('URL to JSON Schema definitions'),\n }).optional().describe('Schema discovery endpoints for API toolchain integration'),\n\n /**\n * Custom metadata key-value pairs for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n});\n\n/**\n * Well-Known Capabilities Schema\n * Flat boolean flags for quick feature detection by clients (ObjectUI).\n * Each flag indicates whether the backend supports a specific capability.\n * Clients can use these to show/hide UI elements without probing individual endpoints.\n */\nexport const WellKnownCapabilitiesSchema = z.object({\n /** Whether the backend supports Feed / Chatter API */\n feed: z.boolean().describe('Whether the backend supports Feed / Chatter API'),\n /** Whether the backend supports comments (a subset of Feed) */\n comments: z.boolean().describe('Whether the backend supports comments (a subset of Feed)'),\n /** Whether the backend supports Automation CRUD (flows, triggers) */\n automation: z.boolean().describe('Whether the backend supports Automation CRUD (flows, triggers)'),\n /** Whether the backend supports cron scheduling */\n cron: z.boolean().describe('Whether the backend supports cron scheduling'),\n /** Whether the backend supports full-text search */\n search: z.boolean().describe('Whether the backend supports full-text search'),\n /** Whether the backend supports async export */\n export: z.boolean().describe('Whether the backend supports async export'),\n /** Whether the backend supports chunked (multipart) uploads */\n chunkedUpload: z.boolean().describe('Whether the backend supports chunked (multipart) uploads'),\n}).describe('Well-known capability flags for frontend intelligent adaptation');\n\nexport type WellKnownCapabilities = z.infer;\nexport type DiscoveryResponse = z.infer;\nexport type ApiRoutes = z.infer;\nexport type ServiceInfo = z.infer;\n\n// ============================================================================\n// Route Health Report\n// ============================================================================\n\n/**\n * Single route health entry for the coverage report.\n */\nexport const RouteHealthEntrySchema = z.object({\n /** Route path (e.g. /api/v1/analytics) */\n route: z.string().describe('Route path pattern'),\n /** HTTP method */\n method: HttpMethod.describe('HTTP method (GET, POST, etc.)'),\n /** Target service name */\n service: z.string().describe('Target service name'),\n /** Whether the route is declared in discovery */\n declared: z.boolean().describe('Whether the route is declared in discovery/metadata'),\n /** Whether the handler is actually registered in the adapter/dispatcher */\n handlerRegistered: z.boolean().describe('Whether the HTTP handler is registered'),\n /**\n * Health check result:\n * - `pass` – Handler exists and responds (2xx/4xx — i.e., not 404/501/503)\n * - `fail` – Handler returned 501 or 503\n * - `missing` – No handler registered (404)\n * - `skip` – Health check was not performed\n */\n healthStatus: z.enum(['pass', 'fail', 'missing', 'skip']).describe(\n 'pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked'\n ),\n /** Optional diagnostic message */\n message: z.string().optional().describe('Diagnostic message'),\n});\n\nexport type RouteHealthEntry = z.infer;\n\n/**\n * Route Health Report Schema\n * Aggregated route coverage report produced at startup or on demand.\n *\n * This report enables automated detection of routes that are declared\n * in discovery metadata but have no corresponding HTTP handler.\n */\nexport const RouteHealthReportSchema = z.object({\n /** ISO 8601 timestamp of when the report was generated */\n timestamp: z.string().describe('ISO 8601 timestamp of report generation'),\n /** Adapter name that generated the report (e.g. \"hono\", \"express\", \"nextjs\") */\n adapter: z.string().describe('Adapter or runtime that produced this report'),\n /** Total routes declared in discovery / dispatcher table */\n totalDeclared: z.number().int().describe('Total routes declared in discovery'),\n /** Routes with a confirmed handler registration */\n totalRegistered: z.number().int().describe('Routes with confirmed handler'),\n /** Routes missing a handler */\n totalMissing: z.number().int().describe('Routes missing a handler'),\n /** Per-route health entries */\n routes: z.array(RouteHealthEntrySchema).describe('Per-route health entries'),\n});\n\nexport type RouteHealthReport = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metadata Event Types\n *\n * Triggered when metadata items are created, updated, or deleted.\n * Follows the pattern: `metadata.{type}.{action}`\n *\n * Examples:\n * - `metadata.object.created` - A new object was created\n * - `metadata.view.updated` - A view was updated\n * - `metadata.agent.deleted` - An agent was deleted\n */\nexport const MetadataEventType = z.enum([\n 'metadata.object.created',\n 'metadata.object.updated',\n 'metadata.object.deleted',\n 'metadata.field.created',\n 'metadata.field.updated',\n 'metadata.field.deleted',\n 'metadata.view.created',\n 'metadata.view.updated',\n 'metadata.view.deleted',\n 'metadata.app.created',\n 'metadata.app.updated',\n 'metadata.app.deleted',\n 'metadata.agent.created',\n 'metadata.agent.updated',\n 'metadata.agent.deleted',\n 'metadata.tool.created',\n 'metadata.tool.updated',\n 'metadata.tool.deleted',\n 'metadata.flow.created',\n 'metadata.flow.updated',\n 'metadata.flow.deleted',\n 'metadata.action.created',\n 'metadata.action.updated',\n 'metadata.action.deleted',\n 'metadata.workflow.created',\n 'metadata.workflow.updated',\n 'metadata.workflow.deleted',\n 'metadata.dashboard.created',\n 'metadata.dashboard.updated',\n 'metadata.dashboard.deleted',\n 'metadata.report.created',\n 'metadata.report.updated',\n 'metadata.report.deleted',\n 'metadata.role.created',\n 'metadata.role.updated',\n 'metadata.role.deleted',\n 'metadata.permission.created',\n 'metadata.permission.updated',\n 'metadata.permission.deleted',\n]);\n\nexport type MetadataEventType = z.infer;\n\n/**\n * Data Event Types\n *\n * Triggered when data records are created, updated, or deleted.\n * Follows the pattern: `data.record.{action}`\n */\nexport const DataEventType = z.enum([\n 'data.record.created',\n 'data.record.updated',\n 'data.record.deleted',\n 'data.field.changed',\n]);\n\nexport type DataEventType = z.infer;\n\n/**\n * Metadata Event Payload\n *\n * Represents a metadata change event (create, update, delete).\n * Used for real-time synchronization of metadata across clients.\n */\nexport const MetadataEventSchema = z.object({\n /** Unique event identifier */\n id: z.string().uuid().describe('Unique event identifier'),\n\n /** Event type (metadata.{type}.{action}) */\n type: MetadataEventType.describe('Event type'),\n\n /** Metadata type (object, view, agent, tool, etc.) */\n metadataType: z.string().describe('Metadata type (object, view, agent, etc.)'),\n\n /** Metadata item name */\n name: z.string().describe('Metadata item name'),\n\n /** Package ID (if applicable) */\n packageId: z.string().optional().describe('Package ID'),\n\n /** Full definition (only for create/update events) */\n definition: z.unknown().optional().describe('Full definition (create/update only)'),\n\n /** User who triggered the event */\n userId: z.string().optional().describe('User who triggered the event'),\n\n /** Event timestamp (ISO 8601) */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\nexport type MetadataEvent = z.infer;\n\n/**\n * Data Event Payload\n *\n * Represents a data record change event (create, update, delete).\n * Used for real-time synchronization of data records across clients.\n */\nexport const DataEventSchema = z.object({\n /** Unique event identifier */\n id: z.string().uuid().describe('Unique event identifier'),\n\n /** Event type (data.record.{action}) */\n type: DataEventType.describe('Event type'),\n\n /** Object name */\n object: z.string().describe('Object name'),\n\n /** Record ID */\n recordId: z.string().describe('Record ID'),\n\n /** Changed fields (update events only) */\n changes: z.record(z.string(), z.unknown()).optional().describe('Changed fields'),\n\n /** Record before update (update events only) */\n before: z.record(z.string(), z.unknown()).optional().describe('Before state'),\n\n /** Record after update (create/update events) */\n after: z.record(z.string(), z.unknown()).optional().describe('After state'),\n\n /** User who triggered the event */\n userId: z.string().optional().describe('User who triggered the event'),\n\n /** Event timestamp (ISO 8601) */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\nexport type DataEvent = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Realtime Shared Protocol\n * \n * Shared schemas and types for real-time communication protocols.\n * This module consolidates overlapping definitions between the transport-level\n * realtime protocol (SSE/Polling/WebSocket) and the WebSocket collaboration protocol.\n * \n * **Architecture:**\n * - `realtime-shared.zod.ts` — Shared base schemas (Presence, Event types)\n * - `realtime.zod.ts` — Transport-layer protocol (Channel, Subscription, Transport selection)\n * - `websocket.zod.ts` — Collaboration protocol (Cursor, OT editing, Advanced presence)\n * \n * @see realtime.zod.ts for transport-layer configuration\n * @see websocket.zod.ts for collaborative editing protocol\n */\n\n// ==========================================\n// Shared Presence Status\n// ==========================================\n\n/**\n * Presence Status Enum (Unified)\n * \n * Canonical user presence status shared across all realtime protocols.\n * Used by both transport-level presence tracking (realtime.zod.ts)\n * and WebSocket collaboration presence (websocket.zod.ts).\n * \n * @example\n * ```typescript\n * import { PresenceStatus } from './realtime-shared.zod';\n * const status = PresenceStatus.parse('online'); // ✅\n * ```\n */\nexport const PresenceStatus = z.enum([\n 'online', // User is actively connected\n 'away', // User is idle/inactive\n 'busy', // User is busy (do not disturb)\n 'offline', // User is disconnected\n]);\n\nexport type PresenceStatus = z.infer;\n\n// ==========================================\n// Shared Realtime Actions\n// ==========================================\n\n/**\n * Realtime Record Action Enum (Unified)\n * \n * Canonical action types for real-time record change events.\n * Shared between transport-level events and WebSocket event messages.\n */\nexport const RealtimeRecordAction = z.enum([\n 'created',\n 'updated',\n 'deleted',\n]);\n\nexport type RealtimeRecordAction = z.infer;\n\n// ==========================================\n// Shared Base Presence Schema\n// ==========================================\n\n/**\n * Base Presence Schema (Unified)\n * \n * Core presence fields shared across all realtime protocols.\n * Transport-level (realtime.zod.ts) and collaboration-level (websocket.zod.ts)\n * presence schemas extend this base with protocol-specific fields.\n * \n * @example\n * ```typescript\n * const presence = BasePresenceSchema.parse({\n * userId: 'user-123',\n * status: 'online',\n * lastSeen: '2024-01-15T10:30:00Z',\n * });\n * ```\n */\nexport const BasePresenceSchema = z.object({\n /** User identifier */\n userId: z.string().describe('User identifier'),\n\n /** Current presence status */\n status: PresenceStatus.describe('Current presence status'),\n\n /** Last activity timestamp */\n lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n\n /** Custom metadata */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom presence data (e.g., current page, custom status)'),\n});\n\nexport type BasePresence = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { RealtimeRecordAction, BasePresenceSchema } from './realtime-shared.zod';\n\n// Re-export shared types for backward compatibility\nexport { PresenceStatus, RealtimeRecordAction, BasePresenceSchema } from './realtime-shared.zod';\nexport type { BasePresence } from './realtime-shared.zod';\n\n/**\n * Transport Protocol Enum\n * Defines the communication protocol for realtime data synchronization\n */\nexport const TransportProtocol = z.enum([\n 'websocket', // Full-duplex, low latency communication\n 'sse', // Server-Sent Events, unidirectional push\n 'polling', // Short polling, best compatibility\n]);\n\nexport type TransportProtocol = z.infer;\n\n/**\n * Event Type Enum\n * Types of realtime events that can be subscribed to\n */\nexport const RealtimeEventType = z.enum([\n 'record.created',\n 'record.updated',\n 'record.deleted',\n 'field.changed',\n]);\n\nexport type RealtimeEventType = z.infer;\n\n/**\n * Subscription Event Configuration\n * Defines what events to subscribe to with optional filtering\n */\nexport const SubscriptionEventSchema = z.object({\n type: RealtimeEventType.describe('Type of event to subscribe to'),\n object: z.string().optional().describe('Object name to subscribe to'),\n filters: z.unknown().optional().describe('Filter conditions'),\n});\n\n/**\n * Subscription Schema\n * Configuration for subscribing to realtime events\n */\nexport const SubscriptionSchema = z.object({\n id: z.string().uuid().describe('Unique subscription identifier'),\n events: z.array(SubscriptionEventSchema).describe('Array of events to subscribe to'),\n transport: TransportProtocol.describe('Transport protocol to use'),\n channel: z.string().optional().describe('Optional channel name for grouping subscriptions'),\n});\n\nexport type Subscription = z.infer;\n\n/**\n * Presence Schema\n * Tracks user online status and metadata.\n * Extends the shared BasePresenceSchema for transport-level presence tracking.\n */\nexport const RealtimePresenceSchema = BasePresenceSchema;\n\nexport type RealtimePresence = z.infer;\n\n/**\n * Realtime Event Schema\n * Represents a realtime synchronization event\n */\nexport const RealtimeEventSchema = z.object({\n id: z.string().uuid().describe('Unique event identifier'),\n type: z.string().describe('Event type (e.g., record.created, record.updated)'),\n object: z.string().optional().describe('Object name the event relates to'),\n action: RealtimeRecordAction.optional().describe('Action performed'),\n payload: z.record(z.string(), z.unknown()).describe('Event payload data'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when event occurred'),\n userId: z.string().optional().describe('User who triggered the event'),\n sessionId: z.string().optional().describe('Session identifier'),\n});\n\nexport type RealtimeEvent = z.infer;\n\n/**\n * Realtime Configuration Schema\n * \n * Configuration for enabling realtime data synchronization.\n */\nexport const RealtimeConfigSchema = z.object({\n /** Enable realtime sync */\n enabled: z.boolean().default(true).describe('Enable realtime synchronization'),\n \n /** Transport protocol */\n transport: TransportProtocol.default('websocket').describe('Transport protocol'),\n \n /** Default subscriptions */\n subscriptions: z.array(SubscriptionSchema).optional().describe('Default subscriptions'),\n}).passthrough(); // Allow additional properties\n\nexport type RealtimeConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventNameSchema } from '../shared/identifiers.zod';\nimport { PresenceStatus } from './realtime-shared.zod';\n\n// Re-export shared PresenceStatus for backward compatibility\nexport { PresenceStatus } from './realtime-shared.zod';\n\n/**\n * WebSocket Event Protocol\n * \n * Defines the schema for WebSocket-based real-time communication in ObjectStack.\n * Supports event subscriptions, filtering, presence tracking, and collaborative editing.\n * \n * Industry alignment: Firebase Realtime Database, Socket.IO, Pusher\n */\n\n// ==========================================\n// Message Types\n// ==========================================\n\n/**\n * WebSocket Message Type Enum\n * Defines the types of messages that can be sent over WebSocket\n */\nexport const WebSocketMessageType = z.enum([\n 'subscribe', // Client subscribes to events\n 'unsubscribe', // Client unsubscribes from events\n 'event', // Server sends event to client\n 'ping', // Keepalive ping\n 'pong', // Keepalive pong response\n 'ack', // Acknowledgment of message receipt\n 'error', // Error message\n 'presence', // Presence update (user status)\n 'cursor', // Cursor position update (collaborative editing)\n 'edit', // Document edit operation (collaborative editing)\n]);\n\nexport type WebSocketMessageType = z.infer;\n\n// ==========================================\n// Event Subscription\n// ==========================================\n\n/**\n * Event Filter Operator Enum\n * SQL-like filter operators for event filtering\n */\nexport const FilterOperator = z.enum([\n 'eq', // Equal\n 'ne', // Not equal\n 'gt', // Greater than\n 'gte', // Greater than or equal\n 'lt', // Less than\n 'lte', // Less than or equal\n 'in', // In array\n 'nin', // Not in array\n 'contains', // String contains\n 'startsWith', // String starts with\n 'endsWith', // String ends with\n 'exists', // Field exists\n 'regex', // Regex match\n]);\n\nexport type FilterOperator = z.infer;\n\n/**\n * Event Filter Condition\n * Defines a single filter condition for event filtering\n */\nexport const EventFilterCondition = z.object({\n field: z.string().describe('Field path to filter on (supports dot notation, e.g., \"user.email\")'),\n operator: FilterOperator.describe('Comparison operator'),\n value: z.unknown().optional().describe('Value to compare against (not needed for \"exists\" operator)'),\n});\n\nexport type EventFilterCondition = z.infer;\n\n/**\n * Event Filter Schema\n * Logical combination of filter conditions\n */\nexport const EventFilterSchema: z.ZodType<{\n conditions?: EventFilterCondition[];\n and?: EventFilter[];\n or?: EventFilter[];\n not?: EventFilter;\n}> = z.object({\n conditions: z.array(EventFilterCondition).optional().describe('Array of filter conditions'),\n and: z.lazy(() => z.array(EventFilterSchema)).optional().describe('AND logical combination of filters'),\n or: z.lazy(() => z.array(EventFilterSchema)).optional().describe('OR logical combination of filters'),\n not: z.lazy(() => EventFilterSchema).optional().describe('NOT logical negation of filter'),\n});\n\nexport type EventFilter = z.infer;\n\n/**\n * Event Pattern Schema\n * Event name pattern that supports wildcards for subscriptions\n */\nexport const EventPatternSchema = z\n .string()\n .min(1)\n .regex(/^[a-z*][a-z0-9_.*]*$/, {\n message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., \"record.*\", \"*.created\", \"user.login\")',\n })\n .describe('Event pattern (supports wildcards like \"record.*\" or \"*.created\")');\n\nexport type EventPattern = z.infer;\n\n/**\n * Event Subscription Config\n * Configuration for subscribing to specific events\n */\nexport const EventSubscriptionSchema = z.object({\n subscriptionId: z.string().uuid().describe('Unique subscription identifier'),\n events: z.array(EventPatternSchema).describe('Event patterns to subscribe to (supports wildcards, e.g., \"record.*\", \"user.created\")'),\n objects: z.array(z.string()).optional().describe('Object names to filter events by (e.g., [\"account\", \"contact\"])'),\n filters: EventFilterSchema.optional().describe('Advanced filter conditions for event payloads'),\n channels: z.array(z.string()).optional().describe('Channel names for scoped subscriptions'),\n});\n\nexport type EventSubscription = z.infer;\n\n/**\n * Unsubscribe Request\n * Request to unsubscribe from events\n */\nexport const UnsubscribeRequestSchema = z.object({\n subscriptionId: z.string().uuid().describe('Subscription ID to unsubscribe from'),\n});\n\nexport type UnsubscribeRequest = z.infer;\n\n// ==========================================\n// Presence Tracking\n// ==========================================\n\n/**\n * Presence Status Enum\n * Re-exported from realtime-shared.zod.ts for backward compatibility\n */\nexport const WebSocketPresenceStatus = PresenceStatus;\n\nexport type WebSocketPresenceStatus = z.infer;\n\n/**\n * Presence State Schema\n * Tracks real-time user presence and activity\n */\nexport const PresenceStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Unique session identifier'),\n status: WebSocketPresenceStatus.describe('Current presence status'),\n lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n currentLocation: z.string().optional().describe('Current page/route user is viewing'),\n device: z.enum(['desktop', 'mobile', 'tablet', 'other']).optional().describe('Device type'),\n customStatus: z.string().optional().describe('Custom user status message'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional custom presence data'),\n});\n\nexport type PresenceState = z.infer;\n\n/**\n * Presence Update Request\n * Client request to update presence status\n */\nexport const PresenceUpdateSchema = z.object({\n status: WebSocketPresenceStatus.optional().describe('Updated presence status'),\n currentLocation: z.string().optional().describe('Updated current location'),\n customStatus: z.string().optional().describe('Updated custom status message'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type PresenceUpdate = z.infer;\n\n// ==========================================\n// Collaborative Editing Protocol\n// ==========================================\n\n/**\n * Cursor Position Schema\n * Represents a cursor position in a document\n */\nexport const CursorPositionSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier being edited'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Column number (0-indexed)'),\n }).optional().describe('Cursor position in document'),\n selection: z.object({\n start: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }),\n end: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }),\n }).optional().describe('Selection range (if text is selected)'),\n color: z.string().optional().describe('Cursor color for visual representation'),\n userName: z.string().optional().describe('Display name of user'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),\n});\n\nexport type CursorPosition = z.infer;\n\n/**\n * Edit Operation Type Enum\n * Types of edit operations for collaborative editing\n */\nexport const EditOperationType = z.enum([\n 'insert', // Insert text at position\n 'delete', // Delete text from range\n 'replace', // Replace text in range\n]);\n\nexport type EditOperationType = z.infer;\n\n/**\n * Edit Operation Schema\n * Represents a single edit operation on a document\n * Supports Operational Transformation (OT) for conflict resolution\n */\nexport const EditOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n documentId: z.string().describe('Document identifier'),\n userId: z.string().describe('User who performed the edit'),\n sessionId: z.string().uuid().describe('Session identifier'),\n type: EditOperationType.describe('Type of edit operation'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Column number (0-indexed)'),\n }).describe('Starting position of the operation'),\n endPosition: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }).optional().describe('Ending position (for delete/replace operations)'),\n content: z.string().optional().describe('Content to insert/replace'),\n version: z.number().int().nonnegative().describe('Document version before this operation'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),\n baseOperationId: z.string().uuid().optional().describe('Previous operation ID this builds upon (for OT)'),\n});\n\nexport type EditOperation = z.infer;\n\n/**\n * Document State Schema\n * Represents the current state of a collaborative document\n */\nexport const DocumentStateSchema = z.object({\n documentId: z.string().describe('Document identifier'),\n version: z.number().int().nonnegative().describe('Current document version'),\n content: z.string().describe('Current document content'),\n lastModified: z.string().datetime().describe('ISO 8601 datetime of last modification'),\n activeSessions: z.array(z.string().uuid()).describe('Active editing session IDs'),\n checksum: z.string().optional().describe('Content checksum for integrity verification'),\n});\n\nexport type DocumentState = z.infer;\n\n// ==========================================\n// WebSocket Messages\n// ==========================================\n\n/**\n * Base WebSocket Message\n * All WebSocket messages extend this base structure\n */\nconst BaseWebSocketMessage = z.object({\n messageId: z.string().uuid().describe('Unique message identifier'),\n type: WebSocketMessageType.describe('Message type'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when message was sent'),\n});\n\n/**\n * Subscribe Message\n * Client sends this to subscribe to events\n */\nexport const SubscribeMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('subscribe'),\n subscription: EventSubscriptionSchema.describe('Subscription configuration'),\n});\n\nexport type SubscribeMessage = z.infer;\n\n/**\n * Unsubscribe Message\n * Client sends this to unsubscribe from events\n */\nexport const UnsubscribeMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('unsubscribe'),\n request: UnsubscribeRequestSchema.describe('Unsubscribe request'),\n});\n\nexport type UnsubscribeMessage = z.infer;\n\n/**\n * Event Message\n * Server sends this when a subscribed event occurs\n */\nexport const EventMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('event'),\n subscriptionId: z.string().uuid().describe('Subscription ID this event belongs to'),\n eventName: EventNameSchema.describe('Event name'),\n object: z.string().optional().describe('Object name the event relates to'),\n payload: z.unknown().describe('Event payload data'),\n userId: z.string().optional().describe('User who triggered the event'),\n});\n\nexport type EventMessage = z.infer;\n\n/**\n * Presence Message\n * Presence update message\n */\nexport const PresenceMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('presence'),\n presence: PresenceStateSchema.describe('Presence state'),\n});\n\nexport type PresenceMessage = z.infer;\n\n/**\n * Cursor Message\n * Cursor position update for collaborative editing\n */\nexport const CursorMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('cursor'),\n cursor: CursorPositionSchema.describe('Cursor position'),\n});\n\nexport type CursorMessage = z.infer;\n\n/**\n * Edit Message\n * Document edit operation for collaborative editing\n */\nexport const EditMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('edit'),\n operation: EditOperationSchema.describe('Edit operation'),\n});\n\nexport type EditMessage = z.infer;\n\n/**\n * Acknowledgment Message\n * Server acknowledges receipt of a message\n */\nexport const AckMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('ack'),\n ackMessageId: z.string().uuid().describe('ID of the message being acknowledged'),\n success: z.boolean().describe('Whether the operation was successful'),\n error: z.string().optional().describe('Error message if operation failed'),\n});\n\nexport type AckMessage = z.infer;\n\n/**\n * Error Message\n * Server sends error information\n */\nexport const ErrorMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('error'),\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n details: z.unknown().optional().describe('Additional error details'),\n});\n\nexport type ErrorMessage = z.infer;\n\n/**\n * Ping Message\n * Keepalive ping from client or server\n */\nexport const PingMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('ping'),\n});\n\nexport type PingMessage = z.infer;\n\n/**\n * Pong Message\n * Keepalive pong response\n */\nexport const PongMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('pong'),\n pingMessageId: z.string().uuid().optional().describe('ID of ping message being responded to'),\n});\n\nexport type PongMessage = z.infer;\n\n/**\n * WebSocket Message Union\n * Discriminated union of all WebSocket message types\n */\nexport const WebSocketMessageSchema = z.discriminatedUnion('type', [\n SubscribeMessageSchema,\n UnsubscribeMessageSchema,\n EventMessageSchema,\n PresenceMessageSchema,\n CursorMessageSchema,\n EditMessageSchema,\n AckMessageSchema,\n ErrorMessageSchema,\n PingMessageSchema,\n PongMessageSchema,\n]);\n\nexport type WebSocketMessage = z.infer;\n\n// ==========================================\n// Connection Configuration\n// ==========================================\n\n/**\n * WebSocket Connection Config\n * Configuration for WebSocket connections\n */\nexport const WebSocketConfigSchema = z.object({\n url: z.string().url().describe('WebSocket server URL'),\n protocols: z.array(z.string()).optional().describe('WebSocket sub-protocols'),\n reconnect: z.boolean().optional().default(true).describe('Enable automatic reconnection'),\n reconnectInterval: z.number().int().positive().optional().default(1000).describe('Reconnection interval in milliseconds'),\n maxReconnectAttempts: z.number().int().positive().optional().default(5).describe('Maximum reconnection attempts'),\n pingInterval: z.number().int().positive().optional().default(30000).describe('Ping interval in milliseconds'),\n timeout: z.number().int().positive().optional().default(5000).describe('Message timeout in milliseconds'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for WebSocket handshake'),\n});\n\nexport type WebSocketConfig = z.infer;\n\n// ==========================================\n// Simplified Collaboration API\n// ==========================================\n\n/**\n * Simplified WebSocket Event Schema\n * \n * A simplified event schema for basic WebSocket communication.\n * Complements the comprehensive WebSocketMessageSchema above for simpler use cases.\n * \n * @example Subscribe to channel\n * ```typescript\n * {\n * type: 'subscribe',\n * channel: 'record.account.123',\n * payload: { events: ['created', 'updated'] },\n * timestamp: Date.now()\n * }\n * ```\n * \n * @example Data change notification\n * ```typescript\n * {\n * type: 'data-change',\n * channel: 'record.account.123',\n * payload: { id: '123', action: 'updated', data: {...} },\n * timestamp: Date.now()\n * }\n * ```\n */\nexport const WebSocketEventSchema = z.object({\n type: z.enum([\n 'subscribe', // Client subscribes to channel\n 'unsubscribe', // Client unsubscribes from channel\n 'data-change', // Data modification event\n 'presence-update', // User presence change\n 'cursor-update', // Cursor position change (collaborative editing)\n 'error', // Error message\n ]).describe('Event type'),\n channel: z.string().describe('Channel identifier (e.g., \"record.account.123\", \"user.456\")'),\n payload: z.unknown().describe('Event payload data'),\n timestamp: z.number().describe('Unix timestamp in milliseconds'),\n});\n\nexport type WebSocketEvent = z.infer;\n\n/**\n * Simplified Presence State Schema\n * \n * A simplified presence schema for basic user presence tracking.\n * Complements the comprehensive PresenceStateSchema for simpler integrations.\n * \n * Use this for basic presence features. For advanced features like device tracking,\n * custom status, and session management, use the comprehensive PresenceStateSchema above.\n * \n * @example User online\n * ```typescript\n * {\n * userId: 'user123',\n * userName: 'John Doe',\n * status: 'online',\n * lastSeen: Date.now(),\n * metadata: { currentPage: '/dashboard' }\n * }\n * ```\n */\nexport const SimplePresenceStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n userName: z.string().describe('User display name'),\n status: z.enum(['online', 'away', 'offline']).describe('User presence status'),\n lastSeen: z.number().describe('Unix timestamp of last activity in milliseconds'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional presence metadata (e.g., current page, custom status)'),\n});\n\nexport type SimplePresenceState = z.infer;\n\n/**\n * Simplified Cursor Position Schema\n * \n * A simplified cursor position schema for basic collaborative editing.\n * Complements the comprehensive CursorPositionSchema for simpler use cases.\n * \n * Use this for basic cursor sharing. For advanced features like selections,\n * color coding, and document versioning, use the comprehensive CursorPositionSchema above.\n * \n * @example Cursor in text field\n * ```typescript\n * {\n * userId: 'user123',\n * recordId: 'account_456',\n * fieldName: 'description',\n * position: 42,\n * selection: { start: 42, end: 57 }\n * }\n * ```\n */\nexport const SimpleCursorPositionSchema = z.object({\n userId: z.string().describe('User identifier'),\n recordId: z.string().describe('Record identifier being edited'),\n fieldName: z.string().describe('Field name being edited'),\n position: z.number().describe('Cursor position (character offset from start)'),\n selection: z.object({\n start: z.number().describe('Selection start position'),\n end: z.number().describe('Selection end position'),\n }).optional().describe('Text selection range (if text is selected)'),\n});\n\nexport type SimpleCursorPosition = z.infer;\n\n/**\n * WebSocket Server Configuration Schema\n * \n * Server-side configuration for WebSocket services.\n * Controls features like presence tracking, cursor sharing, and connection management.\n * \n * @example Production configuration\n * ```typescript\n * {\n * enabled: true,\n * path: '/ws',\n * heartbeatInterval: 30000,\n * reconnectAttempts: 5,\n * presence: true,\n * cursorSharing: true\n * }\n * ```\n */\nexport const WebSocketServerConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable WebSocket server'),\n path: z.string().default('/ws').describe('WebSocket endpoint path'),\n heartbeatInterval: z.number().default(30000).describe('Heartbeat interval in milliseconds'),\n reconnectAttempts: z.number().default(5).describe('Maximum reconnection attempts for clients'),\n presence: z.boolean().default(false).describe('Enable presence tracking'),\n cursorSharing: z.boolean().default(false).describe('Enable collaborative cursor sharing'),\n});\n\nexport type WebSocketServerConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { CorsConfigSchema, StaticMountSchema, HttpMethod } from '../shared/http.zod';\n\n// Re-export HttpMethod for convenience\nexport { HttpMethod };\n\n/**\n * Route Category Enum\n * Classifies routes for middleware application and security policies.\n */\nexport const RouteCategory = z.enum([\n 'system', // Health, Metrics, Info (No Auth usually)\n 'api', // Business Logic API (Auth required)\n 'auth', // Login/Callback endpoints\n 'static', // Asset serving\n 'webhook', // External callbacks\n 'plugin' // Plugin extensions\n]);\n\nexport type RouteCategory = z.infer;\n\n/**\n * Route Definition Schema\n * Describes a single routable endpoint in the Kernel.\n */\nexport const RouteDefinitionSchema = z.object({\n /**\n * HTTP Method\n */\n method: HttpMethod,\n \n /**\n * URL Path Pattern (supports parameters like /user/:id)\n */\n path: z.string().describe('URL Path pattern'),\n \n /**\n * Route Type/Category\n */\n category: RouteCategory.default('api'),\n \n /**\n * Handler Identifier\n * References an internal function or plugin action ID.\n */\n handler: z.string().describe('Unique handler identifier'),\n \n /**\n * Route specific metadata\n */\n summary: z.string().optional().describe('OpenAPI summary'),\n description: z.string().optional().describe('OpenAPI description'),\n \n /**\n * Security constraints\n */\n public: z.boolean().default(false).describe('Is publicly accessible'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /**\n * Performance hints\n */\n timeout: z.number().int().optional().describe('Execution timeout in ms'),\n rateLimit: z.string().optional().describe('Rate limit policy name'),\n});\n\nexport type RouteDefinition = z.infer;\n\n/**\n * Router Configuration Schema\n * Global routing table configuration.\n */\nexport const RouterConfigSchema = z.object({\n /**\n * URL Prefix for all kernel routes\n */\n basePath: z.string().default('/api').describe('Global API prefix'),\n \n /**\n * Standard Protocol Mounts (Relative to basePath)\n */\n mounts: z.object({\n data: z.string().default('/data').describe('Data Protocol (CRUD)'),\n metadata: z.string().default('/meta').describe('Metadata Protocol (Schemas)'),\n auth: z.string().default('/auth').describe('Auth Protocol'),\n automation: z.string().default('/automation').describe('Automation Protocol'),\n storage: z.string().default('/storage').describe('Storage Protocol'),\n analytics: z.string().default('/analytics').describe('Analytics Protocol'),\n graphql: z.string().default('/graphql').describe('GraphQL Endpoint'),\n ui: z.string().default('/ui').describe('UI Metadata Protocol (Views, Layouts)'),\n workflow: z.string().default('/workflow').describe('Workflow Engine Protocol'),\n realtime: z.string().default('/realtime').describe('Realtime/WebSocket Protocol'),\n notifications: z.string().default('/notifications').describe('Notification Protocol'),\n ai: z.string().default('/ai').describe('AI Engine Protocol (NLQ, Chat, Suggest)'),\n i18n: z.string().default('/i18n').describe('Internationalization Protocol'),\n packages: z.string().default('/packages').describe('Package Management Protocol'),\n }).default({\n data: '/data',\n metadata: '/meta',\n auth: '/auth',\n automation: '/automation',\n storage: '/storage',\n analytics: '/analytics',\n graphql: '/graphql',\n ui: '/ui',\n workflow: '/workflow',\n realtime: '/realtime',\n notifications: '/notifications',\n ai: '/ai',\n i18n: '/i18n',\n packages: '/packages',\n }), // Defaults match standardized spec\n\n /**\n * Cross-Origin Resource Sharing\n */\n cors: CorsConfigSchema.optional(),\n \n /**\n * Static asset mounts\n */\n staticMounts: z.array(StaticMountSchema).optional(),\n});\n\nexport type RouterConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * OData v4 Protocol Support\n * \n * Open Data Protocol (OData) v4 is an industry-standard protocol for building\n * and consuming RESTful APIs. It provides a uniform way to expose, structure,\n * query, and manipulate data.\n * \n * ## Overview\n * \n * OData v4 provides standardized URL conventions for querying data including:\n * - $select: Choose which fields to return\n * - $filter: Filter results with complex expressions\n * - $orderby: Sort results\n * - $top/$skip: Pagination\n * - $expand: Include related entities\n * - $count: Get total count\n * \n * ## Use Cases\n * \n * 1. **Enterprise Integration**\n * - Integrate with Microsoft Dynamics 365\n * - Connect to SharePoint Online\n * - SAP OData services\n * \n * 2. **API Standardization**\n * - Provide consistent query interface\n * - Standard pagination and filtering\n * - Industry-recognized protocol\n * \n * 3. **External Data Sources**\n * - Connect to OData-compliant systems\n * - Federated queries\n * - Data virtualization\n * \n * @see https://www.odata.org/documentation/\n * @see https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html\n * \n * @example OData Query\n * ```\n * GET /api/odata/customers?\n * $select=name,email&\n * $filter=country eq 'US' and revenue gt 100000&\n * $orderby=revenue desc&\n * $top=10&\n * $skip=20&\n * $expand=orders&\n * $count=true\n * ```\n * \n * @example Programmatic Use\n * ```typescript\n * const query: ODataQuery = {\n * select: ['name', 'email'],\n * filter: \"country eq 'US' and revenue gt 100000\",\n * orderby: 'revenue desc',\n * top: 10,\n * skip: 20,\n * expand: ['orders'],\n * count: true\n * }\n * ```\n */\n\n/**\n * OData Query Options Schema\n * \n * System query options defined by OData v4 specification.\n * These are URL query parameters that control the query execution.\n * \n * @see https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html#sec_SystemQueryOptions\n */\nexport const ODataQuerySchema = z.object({\n /**\n * $select - Select specific fields to return\n * \n * Comma-separated list of field names to include in the response.\n * Reduces payload size and improves performance.\n * \n * @example \"name,email,phone\"\n * @example \"id,customer/name\" - With navigation path\n */\n $select: z.union([\n z.string(), // \"name,email\"\n z.array(z.string()), // [\"name\", \"email\"]\n ]).optional().describe('Fields to select'),\n\n /**\n * $filter - Filter results with conditions\n * \n * OData filter expression using comparison operators, logical operators,\n * and functions.\n * \n * Comparison: eq, ne, lt, le, gt, ge\n * Logical: and, or, not\n * Functions: contains, startswith, endswith, length, indexof, substring, etc.\n * \n * @example \"age gt 18\"\n * @example \"country eq 'US' and revenue gt 100000\"\n * @example \"contains(name, 'Smith')\"\n * @example \"startswith(email, 'admin') and isActive eq true\"\n */\n $filter: z.string().optional().describe('Filter expression (OData filter syntax)'),\n\n /**\n * $orderby - Sort results\n * \n * Comma-separated list of fields with optional asc/desc.\n * Default is ascending.\n * \n * @example \"name\"\n * @example \"revenue desc\"\n * @example \"country asc, revenue desc\"\n */\n $orderby: z.union([\n z.string(), // \"name desc\"\n z.array(z.string()), // [\"name desc\", \"email asc\"]\n ]).optional().describe('Sort order'),\n\n /**\n * $top - Limit number of results\n * \n * Maximum number of results to return.\n * Equivalent to SQL LIMIT or FETCH FIRST.\n * \n * @example 10\n * @example 100\n */\n $top: z.number().int().min(0).optional().describe('Max results to return'),\n\n /**\n * $skip - Skip results for pagination\n * \n * Number of results to skip before returning results.\n * Equivalent to SQL OFFSET.\n * \n * @example 20\n * @example 100\n */\n $skip: z.number().int().min(0).optional().describe('Results to skip'),\n\n /**\n * $expand - Include related entities (lookup/master_detail fields)\n * \n * Comma-separated list of navigation properties (relationship field names) to expand.\n * Loads related data in the same request by resolving lookup and master_detail fields.\n * The engine replaces foreign key IDs with full related objects via batch $in queries.\n * Supports nested expand via OData parenthetical syntax.\n * \n * Behavior:\n * - Only fields with `type: 'lookup'` or `type: 'master_detail'` and a valid `reference` are expanded.\n * - Fields without a schema or reference definition are silently skipped (ID returned as-is).\n * - Maximum expand depth defaults to 3 (configurable via QueryAdapterConfig).\n * \n * @example \"orders\"\n * @example \"customer,products\"\n * @example \"orders($select=id,total)\" - With nested query options\n */\n $expand: z.union([\n z.string(), // \"orders\"\n z.array(z.string()), // [\"orders\", \"customer\"]\n ]).optional().describe('Navigation properties to expand (lookup/master_detail fields)'),\n\n /**\n * $count - Include total count\n * \n * When true, includes totalResults count in response.\n * Useful for pagination UI.\n * \n * @example true\n */\n $count: z.boolean().optional().describe('Include total count'),\n\n /**\n * $search - Full-text search\n * \n * Free-text search expression.\n * Search implementation is service-specific.\n * \n * @example \"John Smith\"\n * @example \"urgent AND support\"\n */\n $search: z.string().optional().describe('Search expression'),\n\n /**\n * $format - Response format\n * \n * Preferred response format.\n * \n * @example \"json\"\n * @example \"xml\"\n */\n $format: z.enum(['json', 'xml', 'atom']).optional().describe('Response format'),\n\n /**\n * $apply - Data aggregation\n * \n * Aggregation transformations (groupby, aggregate, etc.)\n * Part of OData aggregation extension.\n * \n * @example \"groupby((country),aggregate(revenue with sum as totalRevenue))\"\n */\n $apply: z.string().optional().describe('Aggregation expression'),\n});\n\nexport type ODataQuery = z.infer;\n\n/**\n * OData Filter Operator\n * \n * Standard comparison and logical operators in OData filter expressions.\n */\nexport const ODataFilterOperatorSchema = z.enum([\n // Comparison Operators\n 'eq', // Equal to\n 'ne', // Not equal to\n 'lt', // Less than\n 'le', // Less than or equal to\n 'gt', // Greater than\n 'ge', // Greater than or equal to\n\n // Logical Operators\n 'and', // Logical AND\n 'or', // Logical OR\n 'not', // Logical NOT\n\n // Grouping\n '(', // Left parenthesis\n ')', // Right parenthesis\n\n // Other\n 'in', // Value in list\n 'has', // Has flag (for enum flags)\n]);\n\nexport type ODataFilterOperator = z.infer;\n\n/**\n * OData Filter Function\n * \n * Standard functions available in OData filter expressions.\n */\nexport const ODataFilterFunctionSchema = z.enum([\n // String Functions\n 'contains', // contains(field, 'value')\n 'startswith', // startswith(field, 'value')\n 'endswith', // endswith(field, 'value')\n 'length', // length(field)\n 'indexof', // indexof(field, 'substring')\n 'substring', // substring(field, start, length)\n 'tolower', // tolower(field)\n 'toupper', // toupper(field)\n 'trim', // trim(field)\n 'concat', // concat(field1, field2)\n\n // Date/Time Functions\n 'year', // year(dateField)\n 'month', // month(dateField)\n 'day', // day(dateField)\n 'hour', // hour(datetimeField)\n 'minute', // minute(datetimeField)\n 'second', // second(datetimeField)\n 'date', // date(datetimeField)\n 'time', // time(datetimeField)\n 'now', // now()\n 'maxdatetime', // maxdatetime()\n 'mindatetime', // mindatetime()\n\n // Math Functions\n 'round', // round(numField)\n 'floor', // floor(numField)\n 'ceiling', // ceiling(numField)\n\n // Type Functions\n 'cast', // cast(field, 'Edm.String')\n 'isof', // isof(field, 'Type')\n\n // Collection Functions\n 'any', // collection/any(d:d/prop eq value)\n 'all', // collection/all(d:d/prop eq value)\n]);\n\nexport type ODataFilterFunction = z.infer;\n\n/**\n * OData Response Schema\n * \n * Standard OData JSON response format.\n */\nexport const ODataResponseSchema = z.object({\n /**\n * OData context URL\n * Describes the payload structure\n */\n '@odata.context': z.string().url().optional().describe('Metadata context URL'),\n\n /**\n * Total count (when $count=true)\n */\n '@odata.count': z.number().int().optional().describe('Total results count'),\n\n /**\n * Next link for pagination\n */\n '@odata.nextLink': z.string().url().optional().describe('Next page URL'),\n\n /**\n * Result array\n */\n value: z.array(z.record(z.string(), z.unknown())).describe('Results array'),\n});\n\nexport type ODataResponse = z.infer;\n\n/**\n * OData Error Response Schema\n * \n * Standard OData error format.\n */\nexport const ODataErrorSchema = z.object({\n error: z.object({\n /**\n * Error code\n */\n code: z.string().describe('Error code'),\n\n /**\n * Error message\n */\n message: z.string().describe('Error message'),\n\n /**\n * Target of the error (field name, etc.)\n */\n target: z.string().optional().describe('Error target'),\n\n /**\n * Additional error details\n */\n details: z.array(z.object({\n code: z.string(),\n message: z.string(),\n target: z.string().optional(),\n })).optional().describe('Error details'),\n\n /**\n * Inner error for debugging\n */\n innererror: z.record(z.string(), z.unknown()).optional().describe('Inner error details'),\n }),\n});\n\nexport type ODataError = z.infer;\n\n/**\n * OData Metadata Configuration\n * \n * Configuration for OData metadata endpoint ($metadata).\n */\nexport const ODataMetadataSchema = z.object({\n /**\n * Service namespace\n */\n namespace: z.string().describe('Service namespace'),\n\n /**\n * Entity types to expose\n */\n entityTypes: z.array(z.object({\n name: z.string().describe('Entity type name'),\n key: z.array(z.string()).describe('Key fields'),\n properties: z.array(z.object({\n name: z.string(),\n type: z.string().describe('OData type (Edm.String, Edm.Int32, etc.)'),\n nullable: z.boolean().default(true),\n })),\n navigationProperties: z.array(z.object({\n name: z.string(),\n type: z.string(),\n partner: z.string().optional(),\n })).optional(),\n })).describe('Entity types'),\n\n /**\n * Entity sets\n */\n entitySets: z.array(z.object({\n name: z.string().describe('Entity set name'),\n entityType: z.string().describe('Entity type'),\n })).describe('Entity sets'),\n});\n\nexport type ODataMetadata = z.infer;\n\n/**\n * Helper functions for OData operations\n */\nexport const OData = {\n /**\n * Build OData query URL\n */\n buildUrl: (baseUrl: string, query: ODataQuery): string => {\n const params = new URLSearchParams();\n\n if (query.$select) {\n params.append('$select', Array.isArray(query.$select) ? query.$select.join(',') : query.$select);\n }\n if (query.$filter) {\n params.append('$filter', query.$filter);\n }\n if (query.$orderby) {\n params.append('$orderby', Array.isArray(query.$orderby) ? query.$orderby.join(',') : query.$orderby);\n }\n if (query.$top !== undefined) {\n params.append('$top', query.$top.toString());\n }\n if (query.$skip !== undefined) {\n params.append('$skip', query.$skip.toString());\n }\n if (query.$expand) {\n params.append('$expand', Array.isArray(query.$expand) ? query.$expand.join(',') : query.$expand);\n }\n if (query.$count !== undefined) {\n params.append('$count', query.$count.toString());\n }\n if (query.$search) {\n params.append('$search', query.$search);\n }\n if (query.$format) {\n params.append('$format', query.$format);\n }\n if (query.$apply) {\n params.append('$apply', query.$apply);\n }\n\n const queryString = params.toString();\n return queryString ? `${baseUrl}?${queryString}` : baseUrl;\n },\n\n /**\n * Create a simple filter expression\n */\n filter: {\n eq: (field: string, value: string | number | boolean) => \n `${field} eq ${typeof value === 'string' ? `'${value}'` : value}`,\n ne: (field: string, value: string | number | boolean) => \n `${field} ne ${typeof value === 'string' ? `'${value}'` : value}`,\n gt: (field: string, value: number) => `${field} gt ${value}`,\n lt: (field: string, value: number) => `${field} lt ${value}`,\n contains: (field: string, value: string) => `contains(${field}, '${value}')`,\n and: (...expressions: string[]) => expressions.join(' and '),\n or: (...expressions: string[]) => expressions.join(' or '),\n },\n} as const;\n\n/**\n * OData Configuration Schema\n * \n * Configuration for enabling OData v4 API endpoint.\n */\nexport const ODataConfigSchema = z.object({\n /** Enable OData endpoint */\n enabled: z.boolean().default(true).describe('Enable OData API'),\n \n /** OData endpoint path */\n path: z.string().default('/odata').describe('OData endpoint path'),\n \n /** Metadata configuration */\n metadata: ODataMetadataSchema.optional().describe('OData metadata configuration'),\n}).passthrough(); // Allow additional properties for flexibility\n\nexport type ODataConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\n\n/**\n * GraphQL Protocol Support\n * \n * GraphQL is a query language for APIs and a runtime for executing those queries.\n * It provides a complete and understandable description of the data in your API,\n * gives clients the power to ask for exactly what they need, and enables powerful\n * developer tools.\n * \n * ## Overview\n * \n * GraphQL provides:\n * - Type-safe schema definition\n * - Precise data fetching (no over/under-fetching)\n * - Introspection and documentation\n * - Real-time subscriptions\n * - Batched queries with DataLoader\n * \n * ## Use Cases\n * \n * 1. **Modern API Development**\n * - Mobile and web applications\n * - Microservices federation\n * - Real-time dashboards\n * \n * 2. **Data Aggregation**\n * - Multi-source data integration\n * - Complex nested queries\n * - Efficient data loading\n * \n * 3. **Developer Experience**\n * - Self-documenting API\n * - Type safety and validation\n * - GraphQL playground\n * \n * @see https://graphql.org/\n * @see https://spec.graphql.org/\n * \n * @example GraphQL Query\n * ```graphql\n * query GetCustomer($id: ID!) {\n * customer(id: $id) {\n * id\n * name\n * email\n * orders(limit: 10, status: \"active\") {\n * id\n * total\n * items {\n * product {\n * name\n * price\n * }\n * }\n * }\n * }\n * }\n * ```\n * \n * @example GraphQL Mutation\n * ```graphql\n * mutation CreateOrder($input: CreateOrderInput!) {\n * createOrder(input: $input) {\n * id\n * orderNumber\n * status\n * }\n * }\n * ```\n */\n\n// ==========================================\n// 1. GraphQL Type System\n// ==========================================\n\n/**\n * GraphQL Scalar Types\n * \n * Built-in scalar types in GraphQL plus custom scalars.\n */\nexport const GraphQLScalarType = z.enum([\n // Built-in GraphQL Scalars\n 'ID',\n 'String',\n 'Int',\n 'Float',\n 'Boolean',\n \n // Extended Scalars (common custom types)\n 'DateTime',\n 'Date',\n 'Time',\n 'JSON',\n 'JSONObject',\n 'Upload',\n 'URL',\n 'Email',\n 'PhoneNumber',\n 'Currency',\n 'Decimal',\n 'BigInt',\n 'Long',\n 'UUID',\n 'Base64',\n 'Void',\n]);\n\nexport type GraphQLScalarType = z.infer;\n\n/**\n * GraphQL Type Configuration\n * \n * Configuration for generating GraphQL types from Object definitions.\n */\nexport const GraphQLTypeConfigSchema = z.object({\n /** Type name in GraphQL schema */\n name: z.string().describe('GraphQL type name (PascalCase recommended)'),\n \n /** Source Object name */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Description for GraphQL schema documentation */\n description: z.string().optional().describe('Type description'),\n \n /** Fields to include/exclude */\n fields: z.object({\n /** Include only these fields (allow list) */\n include: z.array(z.string()).optional().describe('Fields to include'),\n \n /** Exclude these fields (deny list) */\n exclude: z.array(z.string()).optional().describe('Fields to exclude (e.g., sensitive fields)'),\n \n /** Custom field mappings */\n mappings: z.record(z.string(), z.object({\n graphqlName: z.string().optional().describe('Custom GraphQL field name'),\n graphqlType: z.string().optional().describe('Override GraphQL type'),\n description: z.string().optional().describe('Field description'),\n deprecationReason: z.string().optional().describe('Why field is deprecated'),\n nullable: z.boolean().optional().describe('Override nullable'),\n })).optional().describe('Field-level customizations'),\n }).optional().describe('Field configuration'),\n \n /** Interfaces this type implements */\n interfaces: z.array(z.string()).optional().describe('GraphQL interface names'),\n \n /** Whether this is an interface definition */\n isInterface: z.boolean().optional().default(false).describe('Define as GraphQL interface'),\n \n /** Custom directives */\n directives: z.array(z.object({\n name: z.string().describe('Directive name'),\n args: z.record(z.string(), z.unknown()).optional().describe('Directive arguments'),\n })).optional().describe('GraphQL directives'),\n});\n\nexport type GraphQLTypeConfig = z.infer;\nexport type GraphQLTypeConfigInput = z.input;\n\n// ==========================================\n// 2. Query Generation Configuration\n// ==========================================\n\n/**\n * GraphQL Query Configuration\n * \n * Configuration for auto-generating query fields from Objects.\n */\nexport const GraphQLQueryConfigSchema = z.object({\n /** Query name */\n name: z.string().describe('Query field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Query type: single record or list */\n type: z.enum(['get', 'list', 'search']).describe('Query type'),\n \n /** Description */\n description: z.string().optional().describe('Query description'),\n \n /** Input arguments */\n args: z.record(z.string(), z.object({\n type: z.string().describe('GraphQL type (e.g., \"ID!\", \"String\", \"Int\")'),\n description: z.string().optional().describe('Argument description'),\n defaultValue: z.unknown().optional().describe('Default value'),\n })).optional().describe('Query arguments'),\n \n /** Filtering configuration */\n filtering: z.object({\n enabled: z.boolean().default(true).describe('Allow filtering'),\n fields: z.array(z.string()).optional().describe('Filterable fields'),\n operators: z.array(z.enum([\n 'eq', 'ne', 'gt', 'gte', 'lt', 'lte',\n 'in', 'notIn', 'contains', 'startsWith', 'endsWith',\n 'isNull', 'isNotNull',\n ])).optional().describe('Allowed filter operators'),\n }).optional().describe('Filtering capabilities'),\n \n /** Sorting configuration */\n sorting: z.object({\n enabled: z.boolean().default(true).describe('Allow sorting'),\n fields: z.array(z.string()).optional().describe('Sortable fields'),\n defaultSort: z.object({\n field: z.string(),\n direction: z.enum(['ASC', 'DESC']),\n }).optional().describe('Default sort order'),\n }).optional().describe('Sorting capabilities'),\n \n /** Pagination configuration */\n pagination: z.object({\n enabled: z.boolean().default(true).describe('Enable pagination'),\n type: z.enum(['offset', 'cursor', 'relay']).default('offset').describe('Pagination style'),\n defaultLimit: z.number().int().min(1).default(20).describe('Default page size'),\n maxLimit: z.number().int().min(1).default(100).describe('Maximum page size'),\n cursors: z.object({\n field: z.string().default('id').describe('Field to use for cursor pagination'),\n }).optional(),\n }).optional().describe('Pagination configuration'),\n \n /** Field selection */\n fields: z.object({\n /** Always include these fields */\n required: z.array(z.string()).optional().describe('Required fields (always returned)'),\n \n /** Allow selecting these fields */\n selectable: z.array(z.string()).optional().describe('Selectable fields'),\n }).optional().describe('Field selection configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(false).describe('Enable caching'),\n ttl: z.number().int().min(0).optional().describe('Cache TTL in seconds'),\n key: z.string().optional().describe('Cache key template'),\n }).optional().describe('Query caching'),\n});\n\nexport type GraphQLQueryConfig = z.infer;\nexport type GraphQLQueryConfigInput = z.input;\n\n// ==========================================\n// 3. Mutation Generation Configuration\n// ==========================================\n\n/**\n * GraphQL Mutation Configuration\n * \n * Configuration for auto-generating mutation fields from Objects.\n */\nexport const GraphQLMutationConfigSchema = z.object({\n /** Mutation name */\n name: z.string().describe('Mutation field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Mutation type */\n type: z.enum(['create', 'update', 'delete', 'upsert', 'custom']).describe('Mutation type'),\n \n /** Description */\n description: z.string().optional().describe('Mutation description'),\n \n /** Input type configuration */\n input: z.object({\n /** Input type name */\n typeName: z.string().optional().describe('Custom input type name'),\n \n /** Fields to include in input */\n fields: z.object({\n include: z.array(z.string()).optional().describe('Fields to include'),\n exclude: z.array(z.string()).optional().describe('Fields to exclude'),\n required: z.array(z.string()).optional().describe('Required input fields'),\n }).optional().describe('Input field configuration'),\n \n /** Validation */\n validation: z.object({\n enabled: z.boolean().default(true).describe('Enable input validation'),\n rules: z.array(z.string()).optional().describe('Custom validation rules'),\n }).optional().describe('Input validation'),\n }).optional().describe('Input configuration'),\n \n /** Return type configuration */\n output: z.object({\n /** Type of output */\n type: z.enum(['object', 'payload', 'boolean', 'custom']).default('object').describe('Output type'),\n \n /** Include success/error envelope */\n includeEnvelope: z.boolean().optional().default(false).describe('Wrap in success/error payload'),\n \n /** Custom output type */\n customType: z.string().optional().describe('Custom output type name'),\n }).optional().describe('Output configuration'),\n \n /** Transaction handling */\n transaction: z.object({\n enabled: z.boolean().default(true).describe('Use database transaction'),\n isolationLevel: z.enum(['read_uncommitted', 'read_committed', 'repeatable_read', 'serializable']).optional().describe('Transaction isolation level'),\n }).optional().describe('Transaction configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Hooks */\n hooks: z.object({\n before: z.array(z.string()).optional().describe('Pre-mutation hooks'),\n after: z.array(z.string()).optional().describe('Post-mutation hooks'),\n }).optional().describe('Lifecycle hooks'),\n});\n\nexport type GraphQLMutationConfig = z.infer;\nexport type GraphQLMutationConfigInput = z.input;\n\n// ==========================================\n// 4. Subscription Configuration\n// ==========================================\n\n/**\n * GraphQL Subscription Configuration\n * \n * Configuration for real-time GraphQL subscriptions.\n */\nexport const GraphQLSubscriptionConfigSchema = z.object({\n /** Subscription name */\n name: z.string().describe('Subscription field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Subscription trigger events */\n events: z.array(z.enum(['created', 'updated', 'deleted', 'custom'])).describe('Events to subscribe to'),\n \n /** Description */\n description: z.string().optional().describe('Subscription description'),\n \n /** Filtering */\n filter: z.object({\n enabled: z.boolean().default(true).describe('Allow filtering subscriptions'),\n fields: z.array(z.string()).optional().describe('Filterable fields'),\n }).optional().describe('Subscription filtering'),\n \n /** Payload configuration */\n payload: z.object({\n /** Include the modified entity */\n includeEntity: z.boolean().default(true).describe('Include entity in payload'),\n \n /** Include previous values (for updates) */\n includePreviousValues: z.boolean().optional().default(false).describe('Include previous field values'),\n \n /** Include mutation metadata */\n includeMeta: z.boolean().optional().default(true).describe('Include metadata (timestamp, user, etc.)'),\n }).optional().describe('Payload configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Rate limiting for subscriptions */\n rateLimit: z.object({\n enabled: z.boolean().default(true).describe('Enable rate limiting'),\n maxSubscriptionsPerUser: z.number().int().min(1).default(10).describe('Max concurrent subscriptions per user'),\n throttleMs: z.number().int().min(0).optional().describe('Throttle interval in milliseconds'),\n }).optional().describe('Subscription rate limiting'),\n});\n\nexport type GraphQLSubscriptionConfig = z.infer;\nexport type GraphQLSubscriptionConfigInput = z.input;\n\n// ==========================================\n// 5. Resolver Configuration\n// ==========================================\n\n/**\n * GraphQL Resolver Configuration\n * \n * Configuration for custom resolver logic.\n */\nexport const GraphQLResolverConfigSchema = z.object({\n /** Field path (e.g., \"Query.users\", \"Mutation.createUser\") */\n path: z.string().describe('Resolver path (Type.field)'),\n \n /** Resolver implementation type */\n type: z.enum(['datasource', 'computed', 'script', 'proxy']).describe('Resolver implementation type'),\n \n /** Implementation details */\n implementation: z.object({\n /** For datasource type */\n datasource: z.string().optional().describe('Datasource ID'),\n query: z.string().optional().describe('Query/SQL to execute'),\n \n /** For computed type */\n expression: z.string().optional().describe('Computation expression'),\n dependencies: z.array(z.string()).optional().describe('Dependent fields'),\n \n /** For script type */\n script: z.string().optional().describe('Script ID or inline code'),\n \n /** For proxy type */\n url: z.string().optional().describe('Proxy URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).optional().describe('HTTP method'),\n }).optional().describe('Implementation configuration'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(false).describe('Enable resolver caching'),\n ttl: z.number().int().min(0).optional().describe('Cache TTL in seconds'),\n keyArgs: z.array(z.string()).optional().describe('Arguments to include in cache key'),\n }).optional().describe('Resolver caching'),\n});\n\nexport type GraphQLResolverConfig = z.infer;\nexport type GraphQLResolverConfigInput = z.input;\n\n// ==========================================\n// 6. DataLoader Configuration\n// ==========================================\n\n/**\n * GraphQL DataLoader Configuration\n * \n * Configuration for batching and caching with DataLoader pattern.\n * Prevents N+1 query problems in GraphQL.\n */\nexport const GraphQLDataLoaderConfigSchema = z.object({\n /** Loader name */\n name: z.string().describe('DataLoader name'),\n \n /** Source Object or datasource */\n source: z.string().describe('Source object or datasource'),\n \n /** Batch function configuration */\n batchFunction: z.object({\n /** Type of batch operation */\n type: z.enum(['findByIds', 'query', 'script', 'custom']).describe('Batch function type'),\n \n /** For findByIds */\n keyField: z.string().optional().describe('Field to batch on (e.g., \"id\")'),\n \n /** For query */\n query: z.string().optional().describe('Query template'),\n \n /** For script */\n script: z.string().optional().describe('Script ID'),\n \n /** Maximum batch size */\n maxBatchSize: z.number().int().min(1).optional().default(100).describe('Maximum batch size'),\n }).describe('Batch function configuration'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable per-request caching'),\n \n /** Cache key function */\n keyFn: z.string().optional().describe('Custom cache key function'),\n }).optional().describe('DataLoader caching'),\n \n /** Options */\n options: z.object({\n /** Batch multiple requests in single tick */\n batch: z.boolean().default(true).describe('Enable batching'),\n \n /** Cache loaded values */\n cache: z.boolean().default(true).describe('Enable caching'),\n \n /** Maximum cache size */\n maxCacheSize: z.number().int().min(0).optional().describe('Max cache entries'),\n }).optional().describe('DataLoader options'),\n});\n\nexport type GraphQLDataLoaderConfig = z.infer;\nexport type GraphQLDataLoaderConfigInput = z.input;\n\n// ==========================================\n// 7. GraphQL Directive Schema\n// ==========================================\n\n/**\n * GraphQL Directive Location\n * \n * Where a directive can be used in the schema.\n */\nexport const GraphQLDirectiveLocation = z.enum([\n // Executable Directive Locations\n 'QUERY',\n 'MUTATION',\n 'SUBSCRIPTION',\n 'FIELD',\n 'FRAGMENT_DEFINITION',\n 'FRAGMENT_SPREAD',\n 'INLINE_FRAGMENT',\n 'VARIABLE_DEFINITION',\n \n // Type System Directive Locations\n 'SCHEMA',\n 'SCALAR',\n 'OBJECT',\n 'FIELD_DEFINITION',\n 'ARGUMENT_DEFINITION',\n 'INTERFACE',\n 'UNION',\n 'ENUM',\n 'ENUM_VALUE',\n 'INPUT_OBJECT',\n 'INPUT_FIELD_DEFINITION',\n]);\n\nexport type GraphQLDirectiveLocation = z.infer;\n\n/**\n * GraphQL Directive Configuration\n * \n * Custom directives for schema metadata and behavior.\n */\nexport const GraphQLDirectiveConfigSchema = z.object({\n /** Directive name */\n name: z.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe('Directive name (camelCase)'),\n \n /** Description */\n description: z.string().optional().describe('Directive description'),\n \n /** Where directive can be used */\n locations: z.array(GraphQLDirectiveLocation).describe('Directive locations'),\n \n /** Arguments */\n args: z.record(z.string(), z.object({\n type: z.string().describe('Argument type'),\n description: z.string().optional().describe('Argument description'),\n defaultValue: z.unknown().optional().describe('Default value'),\n })).optional().describe('Directive arguments'),\n \n /** Is repeatable */\n repeatable: z.boolean().optional().default(false).describe('Can be applied multiple times'),\n \n /** Implementation */\n implementation: z.object({\n /** Directive behavior type */\n type: z.enum(['auth', 'validation', 'transform', 'cache', 'deprecation', 'custom']).describe('Directive type'),\n \n /** Handler function */\n handler: z.string().optional().describe('Handler function name or script'),\n }).optional().describe('Directive implementation'),\n});\n\nexport type GraphQLDirectiveConfig = z.infer;\nexport type GraphQLDirectiveConfigInput = z.input;\n\n// ==========================================\n// 8. GraphQL Security - Query Depth Limiting\n// ==========================================\n\n/**\n * Query Depth Limiting Configuration\n * \n * Prevents deeply nested queries that could cause performance issues.\n */\nexport const GraphQLQueryDepthLimitSchema = z.object({\n /** Enable depth limiting */\n enabled: z.boolean().default(true).describe('Enable query depth limiting'),\n \n /** Maximum allowed depth */\n maxDepth: z.number().int().min(1).default(10).describe('Maximum query depth'),\n \n /** Fields to ignore in depth calculation */\n ignoreFields: z.array(z.string()).optional().describe('Fields excluded from depth calculation'),\n \n /** Callback on depth exceeded */\n onDepthExceeded: z.enum(['reject', 'log', 'warn']).default('reject').describe('Action when depth exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for depth violations'),\n});\n\nexport type GraphQLQueryDepthLimit = z.infer;\nexport type GraphQLQueryDepthLimitInput = z.input;\n\n// ==========================================\n// 9. GraphQL Security - Query Complexity\n// ==========================================\n\n/**\n * Query Complexity Calculation Configuration\n * \n * Assigns complexity scores to fields and limits total query complexity.\n * Prevents expensive queries from overloading the server.\n */\nexport const GraphQLQueryComplexitySchema = z.object({\n /** Enable complexity limiting */\n enabled: z.boolean().default(true).describe('Enable query complexity limiting'),\n \n /** Maximum allowed complexity score */\n maxComplexity: z.number().int().min(1).default(1000).describe('Maximum query complexity'),\n \n /** Default field complexity */\n defaultFieldComplexity: z.number().int().min(0).default(1).describe('Default complexity per field'),\n \n /** Field-specific complexity scores */\n fieldComplexity: z.record(z.string(), z.union([\n z.number().int().min(0),\n z.object({\n /** Base complexity */\n base: z.number().int().min(0).describe('Base complexity'),\n \n /** Multiplier based on arguments */\n multiplier: z.string().optional().describe('Argument multiplier (e.g., \"limit\")'),\n \n /** Custom complexity calculation */\n calculator: z.string().optional().describe('Custom calculator function'),\n }),\n ])).optional().describe('Per-field complexity configuration'),\n \n /** List multiplier */\n listMultiplier: z.number().min(0).default(10).describe('Multiplier for list fields'),\n \n /** Callback on complexity exceeded */\n onComplexityExceeded: z.enum(['reject', 'log', 'warn']).default('reject').describe('Action when complexity exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for complexity violations'),\n});\n\nexport type GraphQLQueryComplexity = z.infer;\nexport type GraphQLQueryComplexityInput = z.input;\n\n// ==========================================\n// 10. GraphQL Security - Rate Limiting\n// ==========================================\n\n/**\n * GraphQL Rate Limiting Configuration\n * \n * Rate limiting for GraphQL operations.\n */\nexport const GraphQLRateLimitSchema = z.object({\n /** Enable rate limiting */\n enabled: z.boolean().default(true).describe('Enable rate limiting'),\n \n /** Rate limit strategy */\n strategy: z.enum(['token_bucket', 'fixed_window', 'sliding_window', 'cost_based']).default('token_bucket').describe('Rate limiting strategy'),\n \n /** Global rate limits */\n global: z.object({\n /** Requests per time window */\n maxRequests: z.number().int().min(1).default(1000).describe('Maximum requests per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n }).optional().describe('Global rate limits'),\n \n /** Per-user rate limits */\n perUser: z.object({\n /** Requests per time window */\n maxRequests: z.number().int().min(1).default(100).describe('Maximum requests per user per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n }).optional().describe('Per-user rate limits'),\n \n /** Cost-based rate limiting */\n costBased: z.object({\n /** Enable cost-based limiting */\n enabled: z.boolean().default(false).describe('Enable cost-based rate limiting'),\n \n /** Maximum cost per time window */\n maxCost: z.number().int().min(1).default(10000).describe('Maximum cost per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n \n /** Use complexity as cost */\n useComplexityAsCost: z.boolean().default(true).describe('Use query complexity as cost'),\n }).optional().describe('Cost-based rate limiting'),\n \n /** Operation-specific limits */\n operations: z.record(z.string(), z.object({\n maxRequests: z.number().int().min(1).describe('Max requests for this operation'),\n windowMs: z.number().int().min(1000).describe('Time window'),\n })).optional().describe('Per-operation rate limits'),\n \n /** Callback on limit exceeded */\n onLimitExceeded: z.enum(['reject', 'queue', 'log']).default('reject').describe('Action when rate limit exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for rate limit violations'),\n \n /** Headers to include in response */\n includeHeaders: z.boolean().default(true).describe('Include rate limit headers in response'),\n});\n\nexport type GraphQLRateLimit = z.infer;\nexport type GraphQLRateLimitInput = z.input;\n\n// ==========================================\n// 11. GraphQL Security - Persisted Queries\n// ==========================================\n\n/**\n * Persisted Queries Configuration\n * \n * Only allow pre-registered queries to execute (allow list approach).\n * Improves security and performance.\n */\nexport const GraphQLPersistedQuerySchema = z.object({\n /** Enable persisted queries */\n enabled: z.boolean().default(false).describe('Enable persisted queries'),\n \n /** Enforcement mode */\n mode: z.enum(['optional', 'required']).default('optional').describe('Persisted query mode (optional: allow both, required: only persisted)'),\n \n /** Query store configuration */\n store: z.object({\n /** Store type */\n type: z.enum(['memory', 'redis', 'database', 'file']).default('memory').describe('Query store type'),\n \n /** Store connection string */\n connection: z.string().optional().describe('Store connection string or path'),\n \n /** TTL for cached queries */\n ttl: z.number().int().min(0).optional().describe('TTL in seconds for stored queries'),\n }).optional().describe('Query store configuration'),\n \n /** Automatic Persisted Queries (APQ) */\n apq: z.object({\n /** Enable APQ */\n enabled: z.boolean().default(true).describe('Enable Automatic Persisted Queries'),\n \n /** Hash algorithm */\n hashAlgorithm: z.enum(['sha256', 'sha1', 'md5']).default('sha256').describe('Hash algorithm for query IDs'),\n \n /** Cache control */\n cache: z.object({\n /** Cache TTL */\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n \n /** Max cache size */\n maxSize: z.number().int().min(1).optional().describe('Maximum number of cached queries'),\n }).optional().describe('APQ cache configuration'),\n }).optional().describe('Automatic Persisted Queries configuration'),\n \n /** Query allow list */\n allowlist: z.object({\n /** Enable allow list mode */\n enabled: z.boolean().default(false).describe('Enable query allow list (reject queries not in list)'),\n \n /** Allowed query IDs */\n queries: z.array(z.object({\n id: z.string().describe('Query ID or hash'),\n operation: z.string().optional().describe('Operation name'),\n query: z.string().optional().describe('Query string'),\n })).optional().describe('Allowed queries'),\n \n /** External allow list source */\n source: z.string().optional().describe('External allow list source (file path or URL)'),\n }).optional().describe('Query allow list configuration'),\n \n /** Security */\n security: z.object({\n /** Maximum query size */\n maxQuerySize: z.number().int().min(1).optional().describe('Maximum query string size in bytes'),\n \n /** Reject introspection in production */\n rejectIntrospection: z.boolean().default(false).describe('Reject introspection queries'),\n }).optional().describe('Security configuration'),\n});\n\nexport type GraphQLPersistedQuery = z.infer;\nexport type GraphQLPersistedQueryInput = z.input;\n\n// ==========================================\n// 12. GraphQL Federation\n// ==========================================\n\n/**\n * Federation Entity Key Definition\n * \n * Defines how entities are uniquely identified across subgraphs.\n * Corresponds to the `@key` directive in Apollo Federation.\n * \n * @see https://www.apollographql.com/docs/federation/entities\n */\nexport const FederationEntityKeySchema = z.object({\n /** Fields composing the key (e.g., \"id\" or \"sku packageId\") */\n fields: z.string().describe('Selection set of fields composing the entity key'),\n\n /** Whether this key can be used for resolution across subgraphs */\n resolvable: z.boolean().optional().default(true).describe('Whether entities can be resolved from this subgraph'),\n});\n\nexport type FederationEntityKey = z.infer;\n\n/**\n * Federation External Field\n * \n * Marks a field as owned by another subgraph (`@external`).\n */\nexport const FederationExternalFieldSchema = z.object({\n /** Field name */\n field: z.string().describe('Field name marked as external'),\n\n /** The subgraph that owns this field */\n ownerSubgraph: z.string().optional().describe('Subgraph that owns this field'),\n});\n\nexport type FederationExternalField = z.infer;\n\n/**\n * Federation Requires Directive\n * \n * Specifies fields that must be fetched from other subgraphs\n * before resolving a computed field.\n * Corresponds to the `@requires` directive in Apollo Federation.\n */\nexport const FederationRequiresSchema = z.object({\n /** The field that has this requirement */\n field: z.string().describe('Field with the requirement'),\n\n /** Selection set of external fields required for resolution */\n fields: z.string().describe('Selection set of required fields (e.g., \"price weight\")'),\n});\n\nexport type FederationRequires = z.infer;\n\n/**\n * Federation Provides Directive\n * \n * Indicates that a field resolution provides additional fields\n * of a returned entity type.\n * Corresponds to the `@provides` directive in Apollo Federation.\n */\nexport const FederationProvidesSchema = z.object({\n /** The field that provides additional data */\n field: z.string().describe('Field that provides additional entity fields'),\n\n /** Selection set of fields provided during resolution */\n fields: z.string().describe('Selection set of provided fields (e.g., \"name price\")'),\n});\n\nexport type FederationProvides = z.infer;\n\n/**\n * Federation Entity Configuration\n * \n * Configures a type as a federated entity that can be referenced\n * and extended across multiple subgraphs.\n */\nexport const FederationEntitySchema = z.object({\n /** Type/Object name */\n typeName: z.string().describe('GraphQL type name for this entity'),\n\n /** Entity keys (`@key` directive) */\n keys: z.array(FederationEntityKeySchema).min(1).describe('Entity key definitions'),\n\n /** External fields (`@external`) */\n externalFields: z.array(FederationExternalFieldSchema).optional().describe('Fields owned by other subgraphs'),\n\n /** Requires directives (`@requires`) */\n requires: z.array(FederationRequiresSchema).optional().describe('Required external fields for computed fields'),\n\n /** Provides directives (`@provides`) */\n provides: z.array(FederationProvidesSchema).optional().describe('Fields provided during resolution'),\n\n /** Whether this subgraph owns this entity */\n owner: z.boolean().optional().default(false).describe('Whether this subgraph is the owner of this entity'),\n});\n\nexport type FederationEntity = z.infer;\n\n/**\n * Subgraph Configuration\n * \n * Configuration for an individual subgraph in a federated architecture.\n */\nexport const SubgraphConfigSchema = z.object({\n /** Subgraph name */\n name: z.string().describe('Unique subgraph identifier'),\n\n /** Subgraph URL */\n url: z.string().describe('Subgraph endpoint URL'),\n\n /** Schema source */\n schemaSource: z.enum(['introspection', 'file', 'registry']).default('introspection').describe('How to obtain the subgraph schema'),\n\n /** Schema file path (when schemaSource is \"file\") */\n schemaPath: z.string().optional().describe('Path to schema file (SDL format)'),\n\n /** Federated entities defined by this subgraph */\n entities: z.array(FederationEntitySchema).optional().describe('Entity definitions for this subgraph'),\n\n /** Health check endpoint */\n healthCheck: z.object({\n enabled: z.boolean().default(true).describe('Enable health checking'),\n path: z.string().default('/health').describe('Health check endpoint path'),\n intervalMs: z.number().int().min(1000).default(30000).describe('Health check interval in milliseconds'),\n }).optional().describe('Subgraph health check configuration'),\n\n /** Request headers to forward */\n forwardHeaders: z.array(z.string()).optional().describe('HTTP headers to forward to this subgraph'),\n});\n\nexport type SubgraphConfig = z.infer;\nexport type SubgraphConfigInput = z.input;\n\n/**\n * Federation Gateway Configuration\n * \n * Root-level gateway configuration for Apollo Federation or similar.\n * Manages query planning, routing, and composition across subgraphs.\n */\nexport const FederationGatewaySchema = z.object({\n /** Enable federation mode */\n enabled: z.boolean().default(false).describe('Enable GraphQL Federation gateway mode'),\n\n /** Federation specification version */\n version: z.enum(['v1', 'v2']).default('v2').describe('Federation specification version'),\n\n /** Registered subgraphs */\n subgraphs: z.array(SubgraphConfigSchema).describe('Subgraph configurations'),\n\n /** Service discovery */\n serviceDiscovery: z.object({\n /** Discovery mode */\n type: z.enum(['static', 'dns', 'consul', 'kubernetes']).default('static').describe('Service discovery method'),\n\n /** Poll interval for dynamic discovery */\n pollIntervalMs: z.number().int().min(1000).optional().describe('Discovery poll interval in milliseconds'),\n\n /** Kubernetes namespace (when type is \"kubernetes\") */\n namespace: z.string().optional().describe('Kubernetes namespace for subgraph discovery'),\n }).optional().describe('Service discovery configuration'),\n\n /** Query planning */\n queryPlanning: z.object({\n /** Execution strategy */\n strategy: z.enum(['parallel', 'sequential', 'adaptive']).default('parallel').describe('Query execution strategy across subgraphs'),\n\n /** Maximum query depth across subgraphs */\n maxDepth: z.number().int().min(1).optional().describe('Max query depth in federated execution'),\n\n /** Dry-run mode for debugging query plans */\n dryRun: z.boolean().optional().default(false).describe('Log query plans without executing'),\n }).optional().describe('Query planning configuration'),\n\n /** Schema composition settings */\n composition: z.object({\n /** How schema conflicts are resolved */\n conflictResolution: z.enum(['error', 'first_wins', 'last_wins']).default('error').describe('Strategy for resolving schema conflicts'),\n\n /** Whether to validate composed schema */\n validate: z.boolean().default(true).describe('Validate composed supergraph schema'),\n }).optional().describe('Schema composition configuration'),\n\n /** Gateway-level error handling */\n errorHandling: z.object({\n /** Whether to include subgraph names in errors */\n includeSubgraphName: z.boolean().default(false).describe('Include subgraph name in error responses'),\n\n /** Partial error behavior */\n partialErrors: z.enum(['propagate', 'nullify', 'reject']).default('propagate').describe('Behavior when a subgraph returns partial errors'),\n }).optional().describe('Error handling configuration'),\n});\n\nexport type FederationGateway = z.infer;\nexport type FederationGatewayInput = z.input;\n\n// ==========================================\n// 13. Complete GraphQL Configuration\n// ==========================================\n\n/**\n * Complete GraphQL Configuration\n * \n * Root configuration for GraphQL API generation and security.\n */\nexport const GraphQLConfigSchema = z.object({\n /** Enable GraphQL API */\n enabled: z.boolean().default(true).describe('Enable GraphQL API'),\n \n /** GraphQL endpoint path */\n path: z.string().default('/graphql').describe('GraphQL endpoint path'),\n \n /** GraphQL Playground */\n playground: z.object({\n enabled: z.boolean().default(true).describe('Enable GraphQL Playground'),\n path: z.string().default('/playground').describe('Playground path'),\n }).optional().describe('GraphQL Playground configuration'),\n \n /** Schema generation */\n schema: z.object({\n /** Auto-generate types from Objects */\n autoGenerateTypes: z.boolean().default(true).describe('Auto-generate types from Objects'),\n \n /** Type configurations */\n types: z.array(GraphQLTypeConfigSchema).optional().describe('Type configurations'),\n \n /** Query configurations */\n queries: z.array(GraphQLQueryConfigSchema).optional().describe('Query configurations'),\n \n /** Mutation configurations */\n mutations: z.array(GraphQLMutationConfigSchema).optional().describe('Mutation configurations'),\n \n /** Subscription configurations */\n subscriptions: z.array(GraphQLSubscriptionConfigSchema).optional().describe('Subscription configurations'),\n \n /** Custom resolvers */\n resolvers: z.array(GraphQLResolverConfigSchema).optional().describe('Custom resolver configurations'),\n \n /** Custom directives */\n directives: z.array(GraphQLDirectiveConfigSchema).optional().describe('Custom directive configurations'),\n }).optional().describe('Schema generation configuration'),\n \n /** DataLoader configurations */\n dataLoaders: z.array(GraphQLDataLoaderConfigSchema).optional().describe('DataLoader configurations'),\n \n /** Security configuration */\n security: z.object({\n /** Query depth limiting */\n depthLimit: GraphQLQueryDepthLimitSchema.optional().describe('Query depth limiting'),\n \n /** Query complexity */\n complexity: GraphQLQueryComplexitySchema.optional().describe('Query complexity calculation'),\n \n /** Rate limiting */\n rateLimit: GraphQLRateLimitSchema.optional().describe('Rate limiting'),\n \n /** Persisted queries */\n persistedQueries: GraphQLPersistedQuerySchema.optional().describe('Persisted queries'),\n }).optional().describe('Security configuration'),\n\n /** Federation configuration */\n federation: FederationGatewaySchema.optional().describe('GraphQL Federation gateway configuration'),\n});\n\nexport const GraphQLConfig = Object.assign(GraphQLConfigSchema, {\n create: >(config: T) => config,\n});\n\nexport type GraphQLConfig = z.infer;\nexport type GraphQLConfigInput = z.input;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to map ObjectQL field type to GraphQL scalar type\n */\nexport const mapFieldTypeToGraphQL = (fieldType: z.infer): string => {\n const mapping: Record = {\n // Core Text\n 'text': 'String',\n 'textarea': 'String',\n 'email': 'Email',\n 'url': 'URL',\n 'phone': 'PhoneNumber',\n 'password': 'String',\n \n // Rich Content\n 'markdown': 'String',\n 'html': 'String',\n 'richtext': 'String',\n \n // Numbers\n 'number': 'Float',\n 'currency': 'Currency',\n 'percent': 'Float',\n \n // Date & Time\n 'date': 'Date',\n 'datetime': 'DateTime',\n 'time': 'Time',\n \n // Logic\n 'boolean': 'Boolean',\n 'toggle': 'Boolean',\n \n // Selection\n 'select': 'String',\n 'multiselect': '[String]',\n 'radio': 'String',\n 'checkboxes': '[String]',\n \n // Relational\n 'lookup': 'ID',\n 'master_detail': 'ID',\n 'tree': 'ID',\n \n // Media\n 'image': 'URL',\n 'file': 'URL',\n 'avatar': 'URL',\n 'video': 'URL',\n 'audio': 'URL',\n \n // Calculated\n 'formula': 'String',\n 'summary': 'Float',\n 'autonumber': 'String',\n \n // Enhanced Types\n 'location': 'JSONObject',\n 'address': 'JSONObject',\n 'code': 'String',\n 'json': 'JSON',\n 'color': 'String',\n 'rating': 'Float',\n 'slider': 'Float',\n 'signature': 'String',\n 'qrcode': 'String',\n 'progress': 'Float',\n 'tags': '[String]',\n \n // AI/ML\n 'vector': '[Float]',\n };\n \n return mapping[fieldType] || 'String';\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ApiErrorSchema, BaseResponseSchema, RecordDataSchema } from './contract.zod';\n\n/**\n * Batch Operations API\n * \n * Provides efficient bulk data operations with transaction support.\n * Implements P0/P1 requirements for ObjectStack kernel.\n * \n * Features:\n * - Batch create/update/delete operations\n * - Atomic transaction support (all-or-none)\n * - Partial success handling\n * - Detailed error reporting per record\n * \n * Industry alignment: Salesforce Bulk API, Microsoft Dynamics Bulk Operations\n */\n\n// ==========================================\n// Batch Operation Types\n// ==========================================\n\n/**\n * Batch Operation Type Enum\n * Defines the type of batch operation to perform\n */\nexport const BatchOperationType = z.enum([\n 'create', // Batch insert\n 'update', // Batch update\n 'upsert', // Batch upsert (insert or update based on external ID)\n 'delete', // Batch delete\n]);\n\nexport type BatchOperationType = z.infer;\n\n// ==========================================\n// Batch Request Schemas\n// ==========================================\n\n/**\n * Batch Record Schema\n * Individual record in a batch operation\n */\nexport const BatchRecordSchema = z.object({\n id: z.string().optional().describe('Record ID (required for update/delete)'),\n data: RecordDataSchema.optional().describe('Record data (required for create/update/upsert)'),\n externalId: z.string().optional().describe('External ID for upsert matching'),\n});\n\nexport type BatchRecord = z.infer;\n\n/**\n * Batch Operation Options Schema\n * Configuration options for batch operations\n */\nexport const BatchOptionsSchema = z.object({\n atomic: z.boolean().optional().default(true).describe('If true, rollback entire batch on any failure (transaction mode)'),\n returnRecords: z.boolean().optional().default(false).describe('If true, return full record data in response'),\n continueOnError: z.boolean().optional().default(false).describe('If true (and atomic=false), continue processing remaining records after errors'),\n validateOnly: z.boolean().optional().default(false).describe('If true, validate records without persisting changes (dry-run mode)'),\n});\n\nexport type BatchOptions = z.infer;\n\n/**\n * Batch Update Request Schema\n * Request payload for batch update operations\n * \n * @example\n * // POST /api/v1/data/{object}/batch\n * {\n * \"operation\": \"update\",\n * \"records\": [\n * { \"id\": \"1\", \"data\": { \"name\": \"Updated Name 1\", \"status\": \"active\" } },\n * { \"id\": \"2\", \"data\": { \"name\": \"Updated Name 2\", \"status\": \"active\" } }\n * ],\n * \"options\": {\n * \"atomic\": true,\n * \"returnRecords\": true\n * }\n * }\n */\nexport const BatchUpdateRequestSchema = z.object({\n operation: BatchOperationType.describe('Type of batch operation'),\n records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to process (max 200 per batch)'),\n options: BatchOptionsSchema.optional().describe('Batch operation options'),\n});\n\nexport type BatchUpdateRequest = z.input;\n\n/**\n * Simplified Batch Update Request (for updateMany API)\n * Simplified request for batch updates without operation field\n * \n * @example\n * // POST /api/v1/data/{object}/updateMany\n * {\n * \"records\": [\n * { \"id\": \"1\", \"data\": { \"name\": \"Updated Name 1\" } },\n * { \"id\": \"2\", \"data\": { \"name\": \"Updated Name 2\" } }\n * ],\n * \"options\": { \"atomic\": true }\n * }\n */\nexport const UpdateManyRequestSchema = z.object({\n records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to update (max 200 per batch)'),\n options: BatchOptionsSchema.optional().describe('Update options'),\n});\n\nexport type UpdateManyRequest = z.input;\n\n// ==========================================\n// Batch Response Schemas\n// ==========================================\n\n/**\n * Batch Operation Result Schema\n * Result for a single record in a batch operation\n */\nexport const BatchOperationResultSchema = z.object({\n id: z.string().optional().describe('Record ID if operation succeeded'),\n success: z.boolean().describe('Whether this record was processed successfully'),\n errors: z.array(ApiErrorSchema).optional().describe('Array of errors if operation failed'),\n data: RecordDataSchema.optional().describe('Full record data (if returnRecords=true)'),\n index: z.number().optional().describe('Index of the record in the request array'),\n});\n\nexport type BatchOperationResult = z.infer;\n\n/**\n * Batch Update Response Schema\n * Response payload for batch operations\n * \n * @example Success Response\n * {\n * \"success\": true,\n * \"operation\": \"update\",\n * \"total\": 2,\n * \"succeeded\": 2,\n * \"failed\": 0,\n * \"results\": [\n * { \"id\": \"1\", \"success\": true, \"index\": 0 },\n * { \"id\": \"2\", \"success\": true, \"index\": 1 }\n * ],\n * \"meta\": {\n * \"timestamp\": \"2026-01-29T12:00:00Z\",\n * \"duration\": 150\n * }\n * }\n * \n * @example Partial Success Response (atomic=false)\n * {\n * \"success\": false,\n * \"operation\": \"update\",\n * \"total\": 2,\n * \"succeeded\": 1,\n * \"failed\": 1,\n * \"results\": [\n * { \"id\": \"1\", \"success\": true, \"index\": 0 },\n * { \n * \"success\": false, \n * \"index\": 1,\n * \"errors\": [{ \"code\": \"validation_error\", \"message\": \"Invalid email format\" }]\n * }\n * ],\n * \"meta\": {\n * \"timestamp\": \"2026-01-29T12:00:00Z\"\n * }\n * }\n */\nexport const BatchUpdateResponseSchema = BaseResponseSchema.extend({\n operation: BatchOperationType.optional().describe('Operation type that was performed'),\n total: z.number().describe('Total number of records in the batch'),\n succeeded: z.number().describe('Number of records that succeeded'),\n failed: z.number().describe('Number of records that failed'),\n results: z.array(BatchOperationResultSchema).describe('Detailed results for each record'),\n});\n\nexport type BatchUpdateResponse = z.infer;\n\n// ==========================================\n// Batch Delete Schemas\n// ==========================================\n\n/**\n * Batch Delete Request Schema\n * Simplified request for batch delete operations\n * \n * @example\n * // POST /api/v1/data/{object}/deleteMany\n * {\n * \"ids\": [\"1\", \"2\", \"3\"],\n * \"options\": { \"atomic\": true }\n * }\n */\nexport const DeleteManyRequestSchema = z.object({\n ids: z.array(z.string()).min(1).max(200).describe('Array of record IDs to delete (max 200)'),\n options: BatchOptionsSchema.optional().describe('Delete options'),\n});\n\nexport type DeleteManyRequest = z.infer;\n\n// ==========================================\n// API Contract Exports\n// ==========================================\n\n/**\n * Batch API Contracts\n * Standardized contracts for batch operations\n */\nexport const BatchApiContracts = {\n batchOperation: {\n input: BatchUpdateRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n updateMany: {\n input: UpdateManyRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n deleteMany: {\n input: DeleteManyRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n};\n\n/**\n * Batch Configuration Schema\n * \n * Configuration for enabling batch operations API.\n */\nexport const BatchConfigSchema = z.object({\n /** Enable batch operations */\n enabled: z.boolean().default(true).describe('Enable batch operations'),\n \n /** Maximum records per batch */\n maxRecordsPerBatch: z.number().int().min(1).max(1000).default(200).describe('Maximum records per batch'),\n \n /** Default options */\n defaultOptions: BatchOptionsSchema.optional().describe('Default batch options'),\n}).passthrough(); // Allow additional properties\n\nexport type BatchConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * HTTP Metadata Cache Protocol\n * \n * Implements efficient HTTP-level metadata caching with ETag support.\n * Implements P0 requirement for ObjectStack kernel.\n * \n * ## Caching in ObjectStack\n * \n * **HTTP Cache (`api/http-cache.zod.ts`) - This File**\n * - **Purpose**: Cache API responses at HTTP protocol level\n * - **Technologies**: HTTP headers (ETag, Last-Modified, Cache-Control), CDN\n * - **Configuration**: Cache-Control headers, validation tokens\n * - **Use case**: Reduce API response time for repeated metadata requests\n * - **Scope**: HTTP layer, client-server communication\n * \n * **Application Cache (`system/cache.zod.ts`)**\n * - **Purpose**: Cache computed data, query results, aggregations\n * - **Technologies**: Redis, Memcached, in-memory LRU\n * - **Configuration**: TTL, eviction policies, cache warming\n * - **Use case**: Cache expensive database queries, computed values\n * - **Scope**: Application layer, server-side data storage\n * \n * ## Features\n * - ETag-based conditional requests (HTTP 304 Not Modified)\n * - Cache-Control directives\n * - Metadata versioning\n * - Selective cache invalidation\n * \n * Industry alignment: HTTP Caching (RFC 7234), Salesforce Metadata API\n * \n * @see ../../system/cache.zod.ts for application-level caching\n */\n\n// ==========================================\n// Cache Control Headers\n// ==========================================\n\n/**\n * Cache Control Directive Enum\n * Standard HTTP cache control directives\n */\nexport const CacheDirective = z.enum([\n 'public', // Cacheable by any cache\n 'private', // Cacheable only by user-agent\n 'no-cache', // Must revalidate with server\n 'no-store', // Never cache\n 'must-revalidate', // Must revalidate stale responses\n 'max-age', // Maximum cache age in seconds\n]);\n\nexport type CacheDirective = z.infer;\n\n/**\n * Cache Control Schema\n * HTTP cache control configuration\n * \n * @example\n * {\n * \"directives\": [\"public\", \"max-age\"],\n * \"maxAge\": 3600,\n * \"staleWhileRevalidate\": 86400\n * }\n */\nexport const CacheControlSchema = z.object({\n directives: z.array(CacheDirective).describe('Cache control directives'),\n maxAge: z.number().optional().describe('Maximum cache age in seconds'),\n staleWhileRevalidate: z.number().optional().describe('Allow serving stale content while revalidating (seconds)'),\n staleIfError: z.number().optional().describe('Allow serving stale content on error (seconds)'),\n});\n\nexport type CacheControl = z.infer;\n\n// ==========================================\n// ETag Support\n// ==========================================\n\n/**\n * ETag Schema\n * Entity tag for cache validation\n * \n * ETags can be:\n * - Strong: Exact match required (e.g., \"686897696a7c876b7e\")\n * - Weak: Semantic equivalence (e.g., W/\"686897696a7c876b7e\")\n */\nexport const ETagSchema = z.object({\n value: z.string().describe('ETag value (hash or version identifier)'),\n weak: z.boolean().optional().default(false).describe('Whether this is a weak ETag'),\n});\n\nexport type ETag = z.infer;\n\n// ==========================================\n// Metadata Cache Request\n// ==========================================\n\n/**\n * Metadata Cache Request Schema\n * Request with cache validation headers\n * \n * @example\n * // GET /api/v1/metadata/objects/account\n * // Headers:\n * // If-None-Match: \"686897696a7c876b7e\"\n * // If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT\n */\nexport const MetadataCacheRequestSchema = z.object({\n ifNoneMatch: z.string().optional().describe('ETag value for conditional request (If-None-Match header)'),\n ifModifiedSince: z.string().datetime().optional().describe('Timestamp for conditional request (If-Modified-Since header)'),\n cacheControl: CacheControlSchema.optional().describe('Client cache control preferences'),\n});\n\nexport type MetadataCacheRequest = z.infer;\n\n// ==========================================\n// Metadata Cache Response\n// ==========================================\n\n/**\n * Metadata Cache Response Schema\n * Response with cache control headers\n * \n * @example Success Response (200 OK)\n * {\n * \"data\": { \"object\": \"account\" },\n * \"etag\": {\n * \"value\": \"686897696a7c876b7e\",\n * \"weak\": false\n * },\n * \"lastModified\": \"2026-01-29T12:00:00Z\",\n * \"cacheControl\": {\n * \"directives\": [\"public\", \"max-age\"],\n * \"maxAge\": 3600\n * }\n * }\n * \n * @example Not Modified Response (304 Not Modified)\n * {\n * \"notModified\": true,\n * \"etag\": {\n * \"value\": \"686897696a7c876b7e\"\n * }\n * }\n */\nexport const MetadataCacheResponseSchema = z.object({\n data: z.unknown().optional().describe('Metadata payload (omitted for 304 Not Modified)'),\n etag: ETagSchema.optional().describe('ETag for this resource version'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n cacheControl: CacheControlSchema.optional().describe('Cache control directives'),\n notModified: z.boolean().optional().default(false).describe('True if resource has not been modified (304 response)'),\n version: z.string().optional().describe('Metadata version identifier'),\n});\n\nexport type MetadataCacheResponse = z.infer;\n\n// ==========================================\n// Metadata Cache Invalidation\n// ==========================================\n\n/**\n * Cache Invalidation Target Enum\n * Specifies what to invalidate\n */\nexport const CacheInvalidationTarget = z.enum([\n 'all', // Invalidate all cached metadata\n 'object', // Invalidate specific object metadata\n 'field', // Invalidate specific field metadata\n 'permission', // Invalidate permission metadata\n 'layout', // Invalidate layout metadata\n 'custom', // Custom invalidation pattern\n]);\n\nexport type CacheInvalidationTarget = z.infer;\n\n/**\n * Cache Invalidation Request Schema\n * Request to invalidate cached metadata\n * \n * @example\n * // POST /api/v1/metadata/cache/invalidate\n * {\n * \"target\": \"object\",\n * \"identifiers\": [\"account\", \"contact\"],\n * \"cascade\": true\n * }\n */\nexport const CacheInvalidationRequestSchema = z.object({\n target: CacheInvalidationTarget.describe('What to invalidate'),\n identifiers: z.array(z.string()).optional().describe('Specific resources to invalidate (e.g., object names)'),\n cascade: z.boolean().optional().default(false).describe('If true, invalidate dependent resources'),\n pattern: z.string().optional().describe('Pattern for custom invalidation (supports wildcards)'),\n});\n\nexport type CacheInvalidationRequest = z.infer;\n\n/**\n * Cache Invalidation Response Schema\n * Response for cache invalidation\n * \n * @example\n * {\n * \"success\": true,\n * \"invalidated\": 5,\n * \"targets\": [\"account\", \"contact\", \"opportunity\"]\n * }\n */\nexport const CacheInvalidationResponseSchema = z.object({\n success: z.boolean().describe('Whether invalidation succeeded'),\n invalidated: z.number().describe('Number of cache entries invalidated'),\n targets: z.array(z.string()).optional().describe('List of invalidated resources'),\n});\n\nexport type CacheInvalidationResponse = z.infer;\n\n// ==========================================\n// Metadata Cache API Methods\n// ==========================================\n\n/**\n * Metadata Cache API Client Interface\n * \n * @example Usage\n * // Get metadata with cache support\n * const response = await client.meta.getCached('account', {\n * ifNoneMatch: '\"686897696a7c876b7e\"'\n * });\n * \n * if (response.notModified) {\n * // Use cached version\n * } else {\n * // Update cache with response.data\n * cache.set('account', response.data, {\n * etag: response.etag?.value,\n * maxAge: response.cacheControl?.maxAge\n * });\n * }\n */\nexport const MetadataCacheApi = {\n getCached: {\n input: MetadataCacheRequestSchema,\n output: MetadataCacheResponseSchema,\n },\n invalidate: {\n input: CacheInvalidationRequestSchema,\n output: CacheInvalidationResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Standardized Error Codes Protocol\n * \n * Implements P0 requirement for ObjectStack kernel.\n * Provides consistent, machine-readable error codes across the platform.\n * \n * Features:\n * - Categorized error codes (validation, authentication, authorization, etc.)\n * - HTTP status code mapping\n * - Localization support\n * - Retry guidance\n * \n * Industry alignment: Google Cloud Errors, AWS Error Codes, Stripe API Errors\n */\n\n// ==========================================\n// Error Code Categories\n// ==========================================\n\n/**\n * Error Category Enum\n * High-level categorization of errors\n */\nexport const ErrorCategory = z.enum([\n 'validation', // Input validation errors (400)\n 'authentication', // Authentication failures (401)\n 'authorization', // Permission denied errors (403)\n 'not_found', // Resource not found (404)\n 'conflict', // Resource conflict (409)\n 'rate_limit', // Rate limiting (429)\n 'server', // Internal server errors (500)\n 'external', // External service errors (502/503)\n 'maintenance', // Planned maintenance (503)\n]);\n\nexport type ErrorCategory = z.infer;\n\n// ==========================================\n// Standard Error Codes\n// ==========================================\n\n/**\n * Standard Error Code Enum\n * Machine-readable error codes for common error scenarios\n */\nexport const StandardErrorCode = z.enum([\n // Validation Errors (400)\n 'validation_error', // Generic validation failure\n 'invalid_field', // Invalid field value\n 'missing_required_field', // Required field missing\n 'invalid_format', // Field format invalid (e.g., email, date)\n 'value_too_long', // Field value exceeds max length\n 'value_too_short', // Field value below min length\n 'value_out_of_range', // Numeric value out of range\n 'invalid_reference', // Invalid foreign key reference\n 'duplicate_value', // Unique constraint violation\n 'invalid_query', // Malformed query syntax\n 'invalid_filter', // Invalid filter expression\n 'invalid_sort', // Invalid sort specification\n 'max_records_exceeded', // Query would return too many records\n \n // Authentication Errors (401)\n 'unauthenticated', // No valid authentication provided\n 'invalid_credentials', // Wrong username/password\n 'expired_token', // Authentication token expired\n 'invalid_token', // Authentication token invalid\n 'session_expired', // User session expired\n 'mfa_required', // Multi-factor authentication required\n 'email_not_verified', // Email verification required\n \n // Authorization Errors (403)\n 'permission_denied', // User lacks required permission\n 'insufficient_privileges', // Operation requires higher privileges\n 'field_not_accessible', // Field-level security restriction\n 'record_not_accessible', // Sharing rule restriction\n 'license_required', // Feature requires license\n 'ip_restricted', // IP address not allowed\n 'time_restricted', // Access outside allowed time window\n \n // Not Found Errors (404)\n 'resource_not_found', // Generic resource not found\n 'object_not_found', // Object/table not found\n 'record_not_found', // Record with given ID not found\n 'field_not_found', // Field not found in object\n 'endpoint_not_found', // API endpoint not found\n \n // Conflict Errors (409)\n 'resource_conflict', // Generic resource conflict\n 'concurrent_modification', // Record modified by another user\n 'delete_restricted', // Cannot delete due to dependencies\n 'duplicate_record', // Record already exists\n 'lock_conflict', // Record is locked by another process\n \n // Rate Limiting (429)\n 'rate_limit_exceeded', // Too many requests\n 'quota_exceeded', // API quota exceeded\n 'concurrent_limit_exceeded', // Too many concurrent requests\n \n // Server Errors (500)\n 'internal_error', // Generic internal server error\n 'database_error', // Database operation failed\n 'timeout', // Operation timed out\n 'service_unavailable', // Service temporarily unavailable\n 'not_implemented', // Feature not yet implemented\n \n // External Service Errors (502/503)\n 'external_service_error', // External API call failed\n 'integration_error', // Integration service error\n 'webhook_delivery_failed', // Webhook delivery failed\n \n // Batch Operation Errors\n 'batch_partial_failure', // Batch operation partially succeeded\n 'batch_complete_failure', // Batch operation completely failed\n 'transaction_failed', // Transaction rolled back\n]);\n\nexport type StandardErrorCode = z.infer;\n\n// ==========================================\n// Enhanced Error Schema\n// ==========================================\n\n/**\n * HTTP Status Code mapping for error categories\n */\nexport const ErrorHttpStatusMap: Record = {\n validation: 400,\n authentication: 401,\n authorization: 403,\n not_found: 404,\n conflict: 409,\n rate_limit: 429,\n server: 500,\n external: 502,\n maintenance: 503,\n};\n\n/**\n * Retry Strategy Enum\n * Guidance on whether to retry failed requests\n */\nexport const RetryStrategy = z.enum([\n 'no_retry', // Do not retry (permanent failure)\n 'retry_immediate', // Retry immediately\n 'retry_backoff', // Retry with exponential backoff\n 'retry_after', // Retry after specified delay\n]);\n\nexport type RetryStrategy = z.infer;\n\n/**\n * Field Error Schema\n * Detailed error for a specific field\n */\nexport const FieldErrorSchema = z.object({\n field: z.string().describe('Field path (supports dot notation)'),\n code: StandardErrorCode.describe('Error code for this field'),\n message: z.string().describe('Human-readable error message'),\n value: z.unknown().optional().describe('The invalid value that was provided'),\n constraint: z.unknown().optional().describe('The constraint that was violated (e.g., max length)'),\n});\n\nexport type FieldError = z.infer;\n\n/**\n * Enhanced API Error Schema\n * Standardized error response with detailed metadata\n * \n * @example Validation Error\n * {\n * \"code\": \"validation_error\",\n * \"message\": \"Validation failed for 2 fields\",\n * \"category\": \"validation\",\n * \"httpStatus\": 400,\n * \"retryable\": false,\n * \"retryStrategy\": \"no_retry\",\n * \"details\": {\n * \"fieldErrors\": [\n * {\n * \"field\": \"email\",\n * \"code\": \"invalid_format\",\n * \"message\": \"Email format is invalid\",\n * \"value\": \"not-an-email\"\n * },\n * {\n * \"field\": \"age\",\n * \"code\": \"value_out_of_range\",\n * \"message\": \"Age must be between 0 and 120\",\n * \"value\": 150,\n * \"constraint\": { \"min\": 0, \"max\": 120 }\n * }\n * ]\n * },\n * \"timestamp\": \"2026-01-29T12:00:00Z\",\n * \"requestId\": \"req_123456\",\n * \"documentation\": \"https://docs.objectstack.dev/errors/validation_error\"\n * }\n * \n * @example Rate Limit Error\n * {\n * \"code\": \"rate_limit_exceeded\",\n * \"message\": \"Rate limit exceeded. Try again in 60 seconds.\",\n * \"category\": \"rate_limit\",\n * \"httpStatus\": 429,\n * \"retryable\": true,\n * \"retryStrategy\": \"retry_after\",\n * \"retryAfter\": 60,\n * \"details\": {\n * \"limit\": 1000,\n * \"remaining\": 0,\n * \"resetAt\": \"2026-01-29T13:00:00Z\"\n * }\n * }\n */\nexport const EnhancedApiErrorSchema = z.object({\n code: StandardErrorCode.describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n category: ErrorCategory.optional().describe('Error category'),\n httpStatus: z.number().optional().describe('HTTP status code'),\n retryable: z.boolean().default(false).describe('Whether the request can be retried'),\n retryStrategy: RetryStrategy.optional().describe('Recommended retry strategy'),\n retryAfter: z.number().optional().describe('Seconds to wait before retrying'),\n details: z.unknown().optional().describe('Additional error context'),\n fieldErrors: z.array(FieldErrorSchema).optional().describe('Field-specific validation errors'),\n timestamp: z.string().datetime().optional().describe('When the error occurred'),\n requestId: z.string().optional().describe('Request ID for tracking'),\n traceId: z.string().optional().describe('Distributed trace ID'),\n documentation: z.string().url().optional().describe('URL to error documentation'),\n helpText: z.string().optional().describe('Suggested actions to resolve the error'),\n});\n\nexport type EnhancedApiError = z.infer;\n\n// ==========================================\n// Error Response Schema\n// ==========================================\n\n/**\n * Standardized Error Response Schema\n * Complete error response envelope\n * \n * @example\n * {\n * \"success\": false,\n * \"error\": {\n * \"code\": \"permission_denied\",\n * \"message\": \"You do not have permission to update this record\",\n * \"category\": \"authorization\",\n * \"httpStatus\": 403,\n * \"retryable\": false\n * }\n * }\n */\nexport const ErrorResponseSchema = z.object({\n success: z.literal(false).describe('Always false for error responses'),\n error: EnhancedApiErrorSchema.describe('Error details'),\n meta: z.object({\n timestamp: z.string().datetime().optional(),\n requestId: z.string().optional(),\n traceId: z.string().optional(),\n }).optional().describe('Response metadata'),\n});\n\nexport type ErrorResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module ui/sharing\n *\n * Sharing & Embedding Protocol\n *\n * Defines schemas for public link sharing, embed configuration,\n * domain restrictions, and password protection for apps, pages, and forms.\n */\n\nimport { z } from 'zod';\n\n/**\n * Sharing Config Schema\n * Configuration for public sharing of an app, page, or form.\n * Supports public links, password protection, domain restrictions, and expiration.\n */\nexport const SharingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable public sharing'),\n publicLink: z.string().optional().describe('Generated public share URL'),\n password: z.string().optional().describe('Password required to access shared link'),\n allowedDomains: z.array(z.string()).optional()\n .describe('Restrict access to specific email domains (e.g. [\"example.com\"])'),\n expiresAt: z.string().optional()\n .describe('Expiration date/time in ISO 8601 format'),\n allowAnonymous: z.boolean().optional().default(false)\n .describe('Allow access without authentication'),\n});\n\n/**\n * Embed Config Schema\n * Configuration for iframe embedding of an app, page, or form.\n * Supports origin restrictions, display options, and responsive sizing.\n */\nexport const EmbedConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable iframe embedding'),\n allowedOrigins: z.array(z.string()).optional()\n .describe('Allowed iframe parent origins (e.g. [\"https://example.com\"])'),\n width: z.string().optional().default('100%').describe('Embed width (CSS value)'),\n height: z.string().optional().default('600px').describe('Embed height (CSS value)'),\n showHeader: z.boolean().optional().default(true).describe('Show interface header in embed'),\n showNavigation: z.boolean().optional().default(false).describe('Show navigation in embed'),\n responsive: z.boolean().optional().default(true).describe('Enable responsive resizing'),\n});\n\n// Type Exports\nexport type SharingConfig = z.infer;\nexport type EmbedConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Breakpoint Name Enum\n * Matches the breakpoint names defined in theme.zod.ts BreakpointsSchema.\n */\nexport const BreakpointName = z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl']);\n\nexport type BreakpointName = z.infer;\n\n/**\n * Responsive Configuration Schema\n *\n * Provides responsive layout configuration for UI components.\n * Maps breakpoint names to layout behavior (columns, visibility, order).\n *\n * Aligned with theme.zod.ts BreakpointsSchema for a unified responsive system.\n *\n * @example\n * ```typescript\n * const config: ResponsiveConfig = {\n * columns: { xs: 12, sm: 6, lg: 4 },\n * hiddenOn: ['xs'],\n * order: { xs: 2, lg: 1 },\n * };\n * ```\n */\n/**\n * Breakpoint Column Map Schema\n * Maps breakpoint names to grid column counts (1-12).\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointColumnMapSchema = z.object({\n xs: z.number().min(1).max(12).optional(),\n sm: z.number().min(1).max(12).optional(),\n md: z.number().min(1).max(12).optional(),\n lg: z.number().min(1).max(12).optional(),\n xl: z.number().min(1).max(12).optional(),\n '2xl': z.number().min(1).max(12).optional(),\n}).describe('Grid columns per breakpoint (1-12)');\n\n/**\n * Breakpoint Order Map Schema\n * Maps breakpoint names to display order numbers.\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointOrderMapSchema = z.object({\n xs: z.number().optional(),\n sm: z.number().optional(),\n md: z.number().optional(),\n lg: z.number().optional(),\n xl: z.number().optional(),\n '2xl': z.number().optional(),\n}).describe('Display order per breakpoint');\n\nexport const ResponsiveConfigSchema = z.object({\n /** Minimum breakpoint for visibility */\n breakpoint: BreakpointName.optional()\n .describe('Minimum breakpoint for visibility'),\n\n /** Hide on specific breakpoints */\n hiddenOn: z.array(BreakpointName).optional()\n .describe('Hide on these breakpoints'),\n\n /** Grid columns per breakpoint (1-12 column grid) */\n columns: BreakpointColumnMapSchema.optional().describe('Grid columns per breakpoint'),\n\n /** Display order per breakpoint */\n order: BreakpointOrderMapSchema.optional().describe('Display order per breakpoint'),\n}).describe('Responsive layout configuration');\n\nexport type ResponsiveConfig = z.infer;\n\n/**\n * Performance Configuration Schema\n *\n * Defines performance optimization settings for UI components\n * such as lazy loading, virtual scrolling, and caching.\n *\n * @example\n * ```typescript\n * const perf: PerformanceConfig = {\n * lazyLoad: true,\n * virtualScroll: { enabled: true, itemHeight: 40, overscan: 5 },\n * cacheStrategy: 'stale-while-revalidate',\n * prefetch: true,\n * };\n * ```\n */\nexport const PerformanceConfigSchema = z.object({\n /** Enable lazy loading for this component */\n lazyLoad: z.boolean().optional()\n .describe('Enable lazy loading (defer rendering until visible)'),\n\n /** Virtual scrolling configuration for large datasets */\n virtualScroll: z.object({\n enabled: z.boolean().default(false).describe('Enable virtual scrolling'),\n itemHeight: z.number().optional().describe('Fixed item height in pixels (for estimation)'),\n overscan: z.number().optional().describe('Number of extra items to render outside viewport'),\n }).optional().describe('Virtual scrolling configuration'),\n\n /** Client-side caching strategy */\n cacheStrategy: z.enum([\n 'none',\n 'cache-first',\n 'network-first',\n 'stale-while-revalidate',\n ]).optional().describe('Client-side data caching strategy'),\n\n /** Enable data prefetching */\n prefetch: z.boolean().optional()\n .describe('Prefetch data before component is visible'),\n\n /** Maximum number of items to render before pagination */\n pageSize: z.number().optional()\n .describe('Number of items per page for pagination'),\n\n /** Debounce interval for user interactions (ms) */\n debounceMs: z.number().optional()\n .describe('Debounce interval for user interactions in milliseconds'),\n}).describe('Performance optimization configuration');\n\nexport type PerformanceConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema } from './sharing.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * HTTP Method Enum & HTTP Request Schema\n * Migrated to shared/http.zod.ts. Re-exported here for backward compatibility.\n */\nimport { HttpMethodSchema, HttpRequestSchema } from '../shared/http.zod';\nexport { HttpMethodSchema, HttpRequestSchema };\n\n/**\n * View Data Source Configuration\n * Supports three modes:\n * 1. 'object': Standard Protocol - Auto-connects to ObjectStack Metadata and Data APIs\n * 2. 'api': Custom API - Explicitly provided API URLs\n * 3. 'value': Static Data - Hardcoded data array\n */\nexport const ViewDataSchema = z.discriminatedUnion('provider', [\n z.object({\n provider: z.literal('object'),\n object: z.string().describe('Target object name'),\n }),\n z.object({\n provider: z.literal('api'),\n read: HttpRequestSchema.optional().describe('Configuration for fetching data'),\n write: HttpRequestSchema.optional().describe('Configuration for submitting data (for forms/editable tables)'),\n }),\n z.object({\n provider: z.literal('value'),\n items: z.array(z.unknown()).describe('Static data array'),\n }),\n]);\n\n/**\n * View Filter Rule Schema\n * Standardized filter condition used in list views, tabs, and page-level filters.\n * Uses a declarative array-of-objects format: [{ field, operator, value }].\n *\n * @example\n * ```ts\n * filter: [\n * { field: 'status', operator: 'equals', value: 'active' },\n * { field: 'close_date', operator: 'this_quarter' },\n * ]\n * ```\n */\nexport const ViewFilterRuleSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n /** Filter operator */\n operator: z.string().describe('Filter operator (e.g. equals, not_equals, contains, this_quarter)'),\n /** Filter value (optional for unary operators like is_null, this_quarter) */\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Filter value'),\n}).describe('View filter rule');\n\nexport type ViewFilterRule = z.infer;\n\n/**\n * Column Summary Function Schema\n * Aggregation function for column footer (Airtable-style column summaries)\n */\nexport const ColumnSummarySchema = z.enum([\n 'none',\n 'count',\n 'count_empty',\n 'count_filled',\n 'count_unique',\n 'percent_empty',\n 'percent_filled',\n 'sum',\n 'avg',\n 'min',\n 'max',\n]).describe('Aggregation function for column footer summary');\n\n/**\n * List Column Configuration Schema\n * Detailed configuration for individual list view columns\n */\nexport const ListColumnSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n width: z.number().positive().optional().describe('Column width in pixels'),\n align: z.enum(['left', 'center', 'right']).optional().describe('Text alignment'),\n hidden: z.boolean().optional().describe('Hide column by default'),\n sortable: z.boolean().optional().describe('Allow sorting by this column'),\n resizable: z.boolean().optional().describe('Allow resizing this column'),\n wrap: z.boolean().optional().describe('Allow text wrapping'),\n type: z.string().optional().describe('Renderer type override (e.g., \"currency\", \"date\")'),\n\n /** Pinning (Airtable-style frozen columns) */\n pinned: z.enum(['left', 'right']).optional().describe('Pin/freeze column to left or right side'),\n\n /** Column Footer Summary (Airtable-style aggregation) */\n summary: ColumnSummarySchema.optional().describe('Footer aggregation function for this column'),\n\n /** Interaction */\n link: z.boolean().optional().describe('Functions as the primary navigation link (triggers View navigation)'),\n action: z.string().optional().describe('Registered Action ID to execute when clicked'),\n});\n\n/**\n * List View Selection Configuration\n */\nexport const SelectionConfigSchema = z.object({\n type: z.enum(['none', 'single', 'multiple']).default('none').describe('Selection mode'),\n});\n\n/**\n * List View Pagination Configuration\n */\nexport const PaginationConfigSchema = z.object({\n pageSize: z.number().int().positive().default(25).describe('Number of records per page'),\n pageSizeOptions: z.array(z.number().int().positive()).optional().describe('Available page size options'),\n});\n\n/**\n * Row Height / Density Schema (Airtable-style)\n * Controls the visual density of rows in a list view.\n */\nexport const RowHeightSchema = z.enum([\n 'compact', // Minimal padding, single line\n 'short', // Reduced padding\n 'medium', // Default padding\n 'tall', // Extra padding, multi-line preview\n 'extra_tall', // Maximum padding, rich content preview\n]).describe('Row height / density setting for list view');\n\n/**\n * Grouping Field Configuration\n * Defines a single grouping level for record grouping.\n */\nexport const GroupingFieldSchema = z.object({\n field: z.string().describe('Field name to group by'),\n order: z.enum(['asc', 'desc']).default('asc').describe('Group sort order'),\n collapsed: z.boolean().default(false).describe('Collapse groups by default'),\n});\n\n/**\n * Grouping Configuration Schema (Airtable-style)\n * Supports multi-level grouping for grid/gallery views.\n */\nexport const GroupingConfigSchema = z.object({\n fields: z.array(GroupingFieldSchema).min(1).describe('Fields to group by (supports up to 3 levels)'),\n}).describe('Record grouping configuration');\n\n/**\n * Gallery View Configuration (Airtable-style)\n * Configures card layout for gallery/card views.\n */\nexport const GalleryConfigSchema = z.object({\n coverField: z.string().optional().describe('Attachment/image field to display as card cover'),\n coverFit: z.enum(['cover', 'contain']).default('cover').describe('Image fit mode for card cover'),\n cardSize: z.enum(['small', 'medium', 'large']).default('medium').describe('Card size in gallery view'),\n titleField: z.string().optional().describe('Field to display as card title'),\n visibleFields: z.array(z.string()).optional().describe('Fields to display on card body'),\n}).describe('Gallery/card view configuration');\n\n/**\n * Timeline View Configuration (Airtable-style)\n * Configures timeline/chronological views.\n */\nexport const TimelineConfigSchema = z.object({\n startDateField: z.string().describe('Field for timeline item start date'),\n endDateField: z.string().optional().describe('Field for timeline item end date'),\n titleField: z.string().describe('Field to display as timeline item title'),\n groupByField: z.string().optional().describe('Field to group timeline rows'),\n colorField: z.string().optional().describe('Field to determine item color'),\n scale: z.enum(['hour', 'day', 'week', 'month', 'quarter', 'year']).default('week').describe('Default timeline scale'),\n}).describe('Timeline view configuration');\n\n/**\n * View Sharing Configuration (Airtable-style)\n * Defines who can see and modify a view.\n */\nexport const ViewSharingSchema = z.object({\n type: z.enum(['personal', 'collaborative']).default('collaborative').describe('View ownership type'),\n lockedBy: z.string().optional().describe('User who locked the view configuration'),\n}).describe('View sharing and access configuration');\n\n/**\n * Row Color Configuration (Airtable-style)\n * Defines how rows are colored based on field values.\n */\nexport const RowColorConfigSchema = z.object({\n field: z.string().describe('Field to derive color from (typically a select/status field)'),\n colors: z.record(z.string(), z.string()).optional().describe('Map of field value to color (hex/token)'),\n}).describe('Row color configuration based on field values');\n\n/**\n * Visualization Type Schema\n * Whitelist of visualization types the user can switch between.\n * Maps to Airtable's \"Visualizations\" setting in Appearance panel.\n */\nexport const VisualizationTypeSchema = z.enum([\n 'grid',\n 'kanban',\n 'gallery',\n 'calendar',\n 'timeline',\n 'gantt',\n 'map',\n]).describe('Visualization type that users can switch to');\n\n/**\n * User Actions Configuration Schema (Airtable Interface parity)\n * Controls which interactive actions are available to users in the view toolbar.\n * Each boolean toggles the corresponding toolbar element on/off.\n *\n * @see Airtable Interface → \"User actions\" panel\n */\nexport const UserActionsConfigSchema = z.object({\n sort: z.boolean().default(true).describe('Allow users to sort records'),\n search: z.boolean().default(true).describe('Allow users to search records'),\n filter: z.boolean().default(true).describe('Allow users to filter records'),\n rowHeight: z.boolean().default(true).describe('Allow users to toggle row height/density'),\n addRecordForm: z.boolean().default(false).describe('Add records through a form instead of inline'),\n buttons: z.array(z.string()).optional().describe('Custom action button IDs to show in the toolbar'),\n}).describe('User action toggles for the view toolbar');\n\n/**\n * Appearance Configuration Schema (Airtable Interface parity)\n * Controls visual presentation options for the view.\n *\n * @see Airtable Interface → \"Appearance\" panel\n */\nexport const AppearanceConfigSchema = z.object({\n showDescription: z.boolean().default(true).describe('Show the view description text'),\n allowedVisualizations: z.array(VisualizationTypeSchema).optional()\n .describe('Whitelist of visualization types users can switch between (e.g. [\"grid\", \"gallery\", \"kanban\"])'),\n}).describe('Appearance and visualization configuration');\n\n/**\n * View Tab Schema (Airtable Interface parity)\n * Defines a tab in a multi-tab view interface.\n * Each tab references a named list view and can be ordered, pinned, or set as default.\n *\n * @see Airtable Interface → \"Tabs\" panel\n */\nexport const ViewTabSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Tab identifier (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label'),\n icon: z.string().optional().describe('Tab icon name'),\n view: z.string().optional().describe('Referenced list view name from listViews'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Tab-specific filter criteria'),\n order: z.number().int().min(0).optional().describe('Tab display order'),\n pinned: z.boolean().default(false).describe('Pin tab (cannot be removed by users)'),\n isDefault: z.boolean().default(false).describe('Set as the default active tab'),\n visible: z.boolean().default(true).describe('Tab visibility'),\n}).describe('Tab configuration for multi-tab view interface');\n\n/**\n * Add Record Configuration Schema (Airtable Interface parity)\n * Configures the \"Add Record\" entry point for a list view.\n *\n * @see Airtable Interface → \"+ Add record\" button\n */\nexport const AddRecordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Show the add record entry point'),\n position: z.enum(['top', 'bottom', 'both']).default('bottom').describe('Position of the add record button'),\n mode: z.enum(['inline', 'form', 'modal']).default('inline').describe('How to add a new record'),\n formView: z.string().optional().describe('Named form view to use when mode is \"form\" or \"modal\"'),\n}).describe('Add record entry point configuration');\n\n/**\n * Kanban Settings\n */\nexport const KanbanConfigSchema = z.object({\n groupByField: z.string().describe('Field to group columns by (usually status/select)'),\n summarizeField: z.string().optional().describe('Field to sum at top of column (e.g. amount)'),\n columns: z.array(z.string()).describe('Fields to show on cards'),\n});\n\n/**\n * Calendar Settings\n */\nexport const CalendarConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string().optional(),\n titleField: z.string(),\n colorField: z.string().optional(),\n});\n\n/**\n * Gantt Settings\n */\nexport const GanttConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string(),\n titleField: z.string(),\n progressField: z.string().optional(),\n dependenciesField: z.string().optional(),\n});\n\n/**\n * Navigation Mode Enum\n * Defines how to navigate to the detail view from a list item.\n */\nexport const NavigationModeSchema = z.enum([\n 'page', // Navigate to a new route (default)\n 'drawer', // Open details in a side drawer/panel\n 'modal', // Open details in a modal dialog\n 'split', // Show details side-by-side with the list (master-detail)\n 'popover', // Show details in a popover (lightweight)\n 'new_window', // Open in new browser tab/window\n 'none' // No navigation (read-only list)\n]);\n\n/**\n * Navigation Configuration Schema\n */\nexport const NavigationConfigSchema = z.object({\n mode: NavigationModeSchema.default('page'),\n \n /** Target View Config */\n view: z.string().optional().describe('Name of the form view to use for details (e.g. \"summary_view\", \"edit_form\")'),\n \n /** Interaction Triggers */\n preventNavigation: z.boolean().default(false).describe('Disable standard navigation entirely'),\n openNewTab: z.boolean().default(false).describe('Force open in new tab (applies to page mode)'),\n \n /** Dimensions (for modal/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Width of the drawer/modal (e.g. \"600px\", \"50%\")'),\n});\n\n/**\n * List View Schema (Expanded)\n * Defines how a collection of records is displayed to the user.\n * \n * **NAMING CONVENTION:**\n * View names (when provided) are machine identifiers and must be lowercase snake_case.\n * \n * @example Standard Grid\n * {\n * name: \"all_active\",\n * label: \"All Active\",\n * type: \"grid\",\n * columns: [\"name\", \"status\", \"created_at\"],\n * filter: [[\"status\", \"=\", \"active\"]]\n * }\n * \n * @example Kanban Board\n * {\n * type: \"kanban\",\n * columns: [\"name\", \"amount\"],\n * kanban: {\n * groupByField: \"stage\",\n * summarizeField: \"amount\",\n * columns: [\"name\", \"close_date\"]\n * }\n * }\n */\nexport const ListViewSchema = z.object({\n name: SnakeCaseIdentifierSchema.optional().describe('Internal view name (lowercase snake_case)'),\n label: I18nLabelSchema.optional(), // Display label override (supports i18n)\n type: z.enum([\n 'grid', // Standard Data Table\n 'kanban', // Board / Columns\n 'gallery', // Card Deck / Masonry\n 'calendar', // Monthly/Weekly/Daily\n 'timeline', // Chronological Stream (Feed)\n 'gantt', // Project Timeline\n 'map' // Geospatial\n ]).default('grid'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n /** Shared Query Config */\n columns: z.union([\n z.array(z.string()), // Legacy: simple field names\n z.array(ListColumnSchema), // Enhanced: detailed column config\n ]).describe('Fields to display as columns'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Filter criteria (JSON Rules)'),\n sort: z.union([\n z.string(), //Legacy \"field desc\"\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional(),\n \n /** Search & Filter */\n searchableFields: z.array(z.string()).optional().describe('Fields enabled for search'),\n filterableFields: z.array(z.string()).optional().describe('Fields enabled for end-user filtering in the top bar'),\n\n /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */\n quickFilters: z.array(z.object({\n field: z.string().describe('Field name to filter by'),\n label: z.string().optional().describe('Display label for the chip'),\n operator: z.enum(['equals', 'not_equals', 'contains', 'in', 'is_null', 'is_not_null']).default('equals').describe('Filter operator'),\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Preset filter value'),\n })).optional().describe('One-click filter chips for quick record filtering'),\n\n /** Grid Features */\n resizable: z.boolean().optional().describe('Enable column resizing'),\n striped: z.boolean().optional().describe('Striped row styling'),\n bordered: z.boolean().optional().describe('Show borders'),\n\n /** Selection */\n selection: SelectionConfigSchema.optional().describe('Row selection configuration'),\n\n /** Navigation / Interaction */\n navigation: NavigationConfigSchema.optional().describe('Configuration for item click navigation (page, drawer, modal, etc.)'),\n\n /** Pagination */\n pagination: PaginationConfigSchema.optional().describe('Pagination configuration'),\n\n /** Type Specific Config */\n kanban: KanbanConfigSchema.optional(),\n calendar: CalendarConfigSchema.optional(),\n gantt: GanttConfigSchema.optional(),\n gallery: GalleryConfigSchema.optional(),\n timeline: TimelineConfigSchema.optional(),\n\n /** View Metadata (Airtable-style view management) */\n description: I18nLabelSchema.optional().describe('View description for documentation/tooltips'),\n sharing: ViewSharingSchema.optional().describe('View sharing and access configuration'),\n\n /** Row Height / Density (Airtable-style) */\n rowHeight: RowHeightSchema.optional().describe('Row height / density setting'),\n\n /** Record Grouping (Airtable-style) */\n grouping: GroupingConfigSchema.optional().describe('Group records by one or more fields'),\n\n /** Row Color (Airtable-style) */\n rowColor: RowColorConfigSchema.optional().describe('Color rows based on field value'),\n\n /** Field Visibility & Ordering per View (Airtable-style) */\n hiddenFields: z.array(z.string()).optional().describe('Fields to hide in this specific view'),\n fieldOrder: z.array(z.string()).optional().describe('Explicit field display order for this view'),\n\n /** Row & Bulk Actions */\n rowActions: z.array(z.string()).optional().describe('Actions available for individual row items'),\n bulkActions: z.array(z.string()).optional().describe('Actions available when multiple rows are selected'),\n\n /** Performance */\n virtualScroll: z.boolean().optional().describe('Enable virtual scrolling for large datasets'),\n\n /** Conditional Formatting */\n conditionalFormatting: z.array(z.object({\n condition: z.string().describe('Condition expression to evaluate'),\n style: z.record(z.string(), z.string()).describe('CSS styles to apply when condition is true'),\n })).optional().describe('Conditional formatting rules for list rows'),\n\n /** Inline Edit */\n inlineEdit: z.boolean().optional().describe('Allow inline editing of records directly in the list view'),\n\n /** Export */\n exportOptions: z.array(z.enum(['csv', 'xlsx', 'pdf', 'json'])).optional().describe('Available export format options'),\n\n /** User Actions (Airtable Interface parity) */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles for the view toolbar'),\n\n /** Appearance (Airtable Interface parity) */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** Tabs (Airtable Interface parity) */\n tabs: z.array(ViewTabSchema).optional().describe('Tab definitions for multi-tab view interface'),\n\n /** Add Record (Airtable Interface parity) */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record Count Display (Airtable Interface parity) */\n showRecordCount: z.boolean().optional().describe('Show record count at the bottom of the list'),\n\n /** Advanced: Allow Printing (Airtable Interface parity) */\n allowPrinting: z.boolean().optional().describe('Allow users to print the view'),\n\n /** Empty State */\n emptyState: z.object({\n title: I18nLabelSchema.optional(),\n message: I18nLabelSchema.optional(),\n icon: z.string().optional(),\n }).optional().describe('Empty state configuration when no records found'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the list view'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Form Field Configuration Schema\n * Detailed configuration for individual form fields\n */\nexport const FormFieldSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n helpText: I18nLabelSchema.optional().describe('Help/hint text'),\n readonly: z.boolean().optional().describe('Read-only override'),\n required: z.boolean().optional().describe('Required override'),\n hidden: z.boolean().optional().describe('Hidden override'),\n colSpan: z.number().int().min(1).max(4).optional().describe('Column span in grid layout (1-4)'),\n widget: z.string().optional().describe('Custom widget/component name'),\n dependsOn: z.string().optional().describe('Parent field name for cascading'),\n visibleOn: z.string().optional().describe('Visibility condition expression'),\n});\n\n/**\n * Form Layout Section\n */\nexport const FormSectionSchema = z.object({\n label: I18nLabelSchema.optional(),\n collapsible: z.boolean().default(false),\n collapsed: z.boolean().default(false),\n columns: z.enum(['1', '2', '3', '4']).default('2').transform(val => parseInt(val) as 1 | 2 | 3 | 4),\n fields: z.array(z.union([\n z.string(), // Legacy: simple field name\n FormFieldSchema, // Enhanced: detailed field config\n ])),\n});\n\n/**\n * Form View Schema\n * Defines the layout for creating or editing a single record.\n * \n * @example Simple Sectioned Form\n * {\n * type: \"simple\",\n * sections: [\n * {\n * label: \"General Info\",\n * columns: 2,\n * fields: [\"name\", \"status\"]\n * },\n * {\n * label: \"Details\",\n * fields: [\"description\", { field: \"priority\", widget: \"rating\" }]\n * }\n * ]\n * }\n */\nexport const FormViewSchema = z.object({\n type: z.enum([\n 'simple', // Single column or sections\n 'tabbed', // Tabs\n 'wizard', // Step by step\n 'split', // Master-Detail split\n 'drawer', // Side panel\n 'modal' // Dialog\n ]).default('simple'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n sections: z.array(FormSectionSchema).optional(), // For simple layout\n groups: z.array(FormSectionSchema).optional(), // Legacy support -> alias to sections\n\n /** Default Sort for Related Lists (e.g., sort child records by date) */\n defaultSort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n order: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n })).optional().describe('Default sort order for related list views within this form'),\n\n /** Public form sharing configuration */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration for this form'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the form view'),\n});\n\n/**\n * Master View Schema\n * Can define multiple named views.\n */\n/**\n * View Container Schema\n * Aggregates all view definitions for a specific object or context.\n * \n * @example\n * {\n * list: { type: \"grid\", columns: [\"name\"] },\n * form: { type: \"simple\", fields: [\"name\"] },\n * listViews: {\n * \"all\": { label: \"All\", filter: [] },\n * \"my\": { label: \"Mine\", filter: [[\"owner\", \"=\", \"{user_id}\"]] }\n * }\n * }\n */\nexport const ViewSchema = z.object({\n list: ListViewSchema.optional(), // Default list view\n form: FormViewSchema.optional(), // Default form view\n listViews: z.record(z.string(), ListViewSchema).optional().describe('Additional named list views'),\n formViews: z.record(z.string(), FormViewSchema).optional().describe('Additional named form views'),\n});\n\n/**\n * Type-safe factory for creating view definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const taskViews = defineView({\n * list: {\n * type: 'grid',\n * data: { provider: 'object', object: 'task' },\n * columns: ['subject', 'status', 'priority', 'due_date'],\n * },\n * form: {\n * type: 'simple',\n * sections: [{ label: 'Details', fields: [{ field: 'subject' }] }],\n * },\n * });\n * ```\n */\nexport function defineView(config: z.input): View {\n return ViewSchema.parse(config);\n}\n\nexport type View = z.infer;\nexport type ListView = z.infer;\nexport type FormView = z.infer;\nexport type FormSection = z.infer;\nexport type ListColumn = z.infer;\nexport type FormField = z.infer;\nexport type SelectionConfig = z.infer;\nexport type NavigationConfig = z.infer;\nexport type PaginationConfig = z.infer;\nexport type ViewData = z.infer;\nexport type HttpRequest = z.infer;\nexport type HttpMethod = z.infer;\nexport type ColumnSummary = z.infer;\nexport type RowHeight = z.infer;\nexport type GroupingConfig = z.infer;\nexport type GalleryConfig = z.infer;\nexport type TimelineConfig = z.infer;\nexport type ViewSharing = z.infer;\nexport type RowColorConfig = z.infer;\nexport type VisualizationType = z.infer;\nexport type UserActionsConfig = z.infer;\nexport type AppearanceConfig = z.infer;\nexport type ViewTab = z.infer;\nexport type AddRecordConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Row-Level Security (RLS) Protocol\n * \n * Implements fine-grained record-level access control inspired by PostgreSQL RLS\n * and Salesforce Criteria-Based Sharing Rules.\n * \n * ## Overview\n * \n * Row-Level Security (RLS) allows you to control which rows users can access\n * in database tables based on their identity and role. Unlike object-level\n * permissions (CRUD), RLS provides record-level filtering.\n * \n * ## Use Cases\n * \n * 1. **Multi-Tenant Data Isolation**\n * - Users only see records from their organization\n * - `using: \"tenant_id = current_user.tenant_id\"`\n * \n * 2. **Ownership-Based Access**\n * - Users only see records they own\n * - `using: \"owner_id = current_user.id\"`\n * \n * 3. **Department-Based Access**\n * - Users only see records from their department\n * - `using: \"department = current_user.department\"`\n * \n * 4. **Regional Access Control**\n * - Sales reps only see accounts in their territory\n * - `using: \"region IN (current_user.assigned_regions)\"`\n * \n * 5. **Time-Based Access**\n * - Users can only access active records\n * - `using: \"status = 'active' AND expiry_date > NOW()\"`\n * \n * ## PostgreSQL RLS Comparison\n * \n * PostgreSQL RLS Example:\n * ```sql\n * CREATE POLICY tenant_isolation ON accounts\n * FOR SELECT\n * USING (tenant_id = current_setting('app.current_tenant_id')::uuid);\n * \n * CREATE POLICY account_insert ON accounts\n * FOR INSERT\n * WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);\n * ```\n * \n * ObjectStack RLS Equivalent:\n * ```typescript\n * {\n * name: 'tenant_isolation',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id'\n * }\n * ```\n * \n * ## Salesforce Sharing Rules Comparison\n * \n * Salesforce uses \"Sharing Rules\" and \"Role Hierarchy\" for record-level access.\n * ObjectStack RLS provides similar functionality with more flexibility.\n * \n * Salesforce:\n * - Criteria-Based Sharing: Share records matching criteria with users/roles\n * - Owner-Based Sharing: Share records based on owner's role\n * - Manual Sharing: Individual record sharing\n * \n * ObjectStack RLS:\n * - More flexible formula-based conditions\n * - Direct SQL-like syntax\n * - Supports complex logic with AND/OR/NOT\n * \n * ## Best Practices\n * \n * 1. **Always Define SELECT Policy**: Control what users can view\n * 2. **Define INSERT/UPDATE CHECK Policies**: Prevent data leakage\n * 3. **Use Role-Based Policies**: Apply different rules to different roles\n * 4. **Test Thoroughly**: RLS can have complex interactions\n * 5. **Monitor Performance**: Complex RLS policies can impact query performance\n * \n * ## Security Considerations\n * \n * 1. **Defense in Depth**: RLS is one layer; use with object permissions\n * 2. **Default Deny**: If no policy matches, access is denied\n * 3. **Policy Precedence**: More permissive policy wins (OR logic)\n * 4. **Context Variables**: Ensure current_user context is always set\n * \n * @see https://www.postgresql.org/docs/current/ddl-rowsecurity.html\n * @see https://help.salesforce.com/s/articleView?id=sf.security_sharing_rules.htm\n */\n\n/**\n * RLS Operation Enum\n * Specifies which database operation this policy applies to.\n * \n * - **select**: Controls which rows can be read (SELECT queries)\n * - **insert**: Controls which rows can be inserted (INSERT statements)\n * - **update**: Controls which rows can be updated (UPDATE statements)\n * - **delete**: Controls which rows can be deleted (DELETE statements)\n * - **all**: Shorthand for all operations (equivalent to defining 4 separate policies)\n */\nexport const RLSOperation = z.enum(['select', 'insert', 'update', 'delete', 'all']);\n\nexport type RLSOperation = z.infer;\n\n/**\n * Row-Level Security Policy Schema\n * \n * Defines a single RLS policy that filters records based on conditions.\n * Multiple policies can be defined for the same object, and they are\n * combined with OR logic (union of results).\n * \n * @example Multi-Tenant Isolation\n * ```typescript\n * {\n * name: 'tenant_isolation',\n * label: 'Multi-Tenant Data Isolation',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id',\n * enabled: true\n * }\n * ```\n * \n * @example Owner-Based Access\n * ```typescript\n * {\n * name: 'owner_access',\n * label: 'Users Can View Their Own Records',\n * object: 'opportunity',\n * operation: 'select',\n * using: 'owner_id = current_user.id',\n * enabled: true\n * }\n * ```\n * \n * @example Manager Can View Team Records\n * ```typescript\n * {\n * name: 'manager_team_access',\n * label: 'Managers Can View Team Records',\n * object: 'task',\n * operation: 'select',\n * using: 'assigned_to_id IN (SELECT id FROM users WHERE manager_id = current_user.id)',\n * roles: ['manager', 'director'],\n * enabled: true\n * }\n * ```\n * \n * @example Prevent Cross-Tenant Data Insertion\n * ```typescript\n * {\n * name: 'tenant_insert_check',\n * label: 'Prevent Cross-Tenant Data Creation',\n * object: 'account',\n * operation: 'insert',\n * check: 'tenant_id = current_user.tenant_id',\n * enabled: true\n * }\n * ```\n * \n * @example Regional Sales Access\n * ```typescript\n * {\n * name: 'regional_sales_access',\n * label: 'Sales Reps Access Regional Accounts',\n * object: 'account',\n * operation: 'select',\n * using: 'region = current_user.region OR region IS NULL',\n * roles: ['sales_rep'],\n * enabled: true\n * }\n * ```\n * \n * @example Time-Based Access Control\n * ```typescript\n * {\n * name: 'active_records_only',\n * label: 'Users Only Access Active Records',\n * object: 'contract',\n * operation: 'select',\n * using: 'status = \"active\" AND start_date <= NOW() AND end_date >= NOW()',\n * enabled: true\n * }\n * ```\n * \n * @example Hierarchical Access (Role-Based)\n * ```typescript\n * {\n * name: 'executive_full_access',\n * label: 'Executives See All Records',\n * object: 'account',\n * operation: 'all',\n * using: '1 = 1', // Always true - see everything\n * roles: ['ceo', 'cfo', 'cto'],\n * enabled: true\n * }\n * ```\n */\nexport const RowLevelSecurityPolicySchema = z.object({\n /**\n * Unique identifier for this policy.\n * Must be unique within the object.\n * Use snake_case following ObjectStack naming conventions.\n * \n * @example \"tenant_isolation\", \"owner_access\", \"manager_team_view\"\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Policy unique identifier (snake_case)'),\n\n /**\n * Human-readable label for the policy.\n * Used in admin UI and logs.\n * \n * @example \"Multi-Tenant Data Isolation\", \"Owner-Based Access\"\n */\n label: z.string()\n .optional()\n .describe('Human-readable policy label'),\n\n /**\n * Description explaining what this policy does and why.\n * Helps with governance and compliance.\n * \n * @example \"Ensures users can only access records from their own tenant organization\"\n */\n description: z.string()\n .optional()\n .describe('Policy description and business justification'),\n\n /**\n * Target object (table) this policy applies to.\n * Must reference a valid ObjectStack object name.\n * \n * @example \"account\", \"opportunity\", \"contact\", \"custom_object\"\n */\n object: z.string()\n .describe('Target object name'),\n\n /**\n * Database operation(s) this policy applies to.\n * \n * - **select**: Controls read access (SELECT queries)\n * - **insert**: Controls insert access (INSERT statements)\n * - **update**: Controls update access (UPDATE statements)\n * - **delete**: Controls delete access (DELETE statements)\n * - **all**: Applies to all operations\n * \n * @example \"select\" - Most common, controls what users can view\n * @example \"all\" - Apply same rule to all operations\n */\n operation: RLSOperation\n .describe('Database operation this policy applies to'),\n\n /**\n * USING clause - Filter condition for SELECT/UPDATE/DELETE.\n * \n * This is a SQL-like expression evaluated for each row.\n * Only rows where this expression returns TRUE are accessible.\n * \n * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed).\n * For SELECT/UPDATE/DELETE operations, USING is required.\n * \n * **Security Note**: RLS conditions are executed at the database level with\n * parameterized queries. The implementation must use prepared statements\n * to prevent SQL injection. Never concatenate user input directly into\n * RLS conditions.\n * \n * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations\n * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain\n * semantic equivalence.\n * \n * Available context variables:\n * - `current_user.id` - Current user's ID\n * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext)\n * - `current_user.role` - Current user's role\n * - `current_user.department` - Current user's department\n * - `current_user.*` - Any custom user field\n * - `NOW()` - Current timestamp\n * - `CURRENT_DATE` - Current date\n * - `CURRENT_TIME` - Current time\n * \n * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`),\n * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`).\n * Implementations must handle this mapping.\n * \n * Supported operators:\n * - Comparison: =, !=, <, >, <=, >=, <> (not equal)\n * - Logical: AND, OR, NOT\n * - NULL checks: IS NULL, IS NOT NULL\n * - Set operations: IN, NOT IN\n * - String: LIKE, NOT LIKE, ILIKE (case-insensitive)\n * - Pattern matching: ~ (regex), !~ (not regex)\n * - Subqueries: (SELECT ...)\n * - Array operations: ANY, ALL\n * \n * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE)\n * \n * @example \"tenant_id = current_user.tenant_id\"\n * @example \"owner_id = current_user.id OR created_by = current_user.id\"\n * @example \"department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)\"\n * @example \"status = 'active' AND expiry_date > NOW()\"\n */\n using: z.string()\n .optional()\n .describe('Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies.'),\n\n /**\n * CHECK clause - Validation for INSERT/UPDATE operations.\n * \n * Similar to USING but applies to new/modified rows.\n * Prevents users from creating/updating rows they wouldn't be able to see.\n * \n * **Default Behavior**: If not specified, implementations should use the\n * USING clause as the CHECK clause. This ensures data integrity by preventing\n * users from creating records they cannot view.\n * \n * Use cases:\n * - Prevent cross-tenant data creation\n * - Enforce mandatory field values\n * - Validate data integrity rules\n * - Restrict certain operations (e.g., only allow creating \"draft\" status)\n * \n * @example \"tenant_id = current_user.tenant_id\"\n * @example \"status IN ('draft', 'pending')\" - Only allow certain statuses\n * @example \"created_by = current_user.id\" - Must be the creator\n */\n check: z.string()\n .optional()\n .describe('Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)'),\n\n /**\n * Restrict this policy to specific roles.\n * If specified, only users with these roles will have this policy applied.\n * If omitted, policy applies to all users (except those with bypassRLS permission).\n * \n * Role names must match defined roles in the system.\n * \n * @example [\"sales_rep\", \"account_manager\"]\n * @example [\"employee\"] - Apply to all employees\n * @example [\"guest\"] - Special restrictions for guests\n */\n roles: z.array(z.string())\n .optional()\n .describe('Roles this policy applies to (omit for all roles)'),\n\n /**\n * Whether this policy is currently active.\n * Disabled policies are not evaluated.\n * Useful for temporary policy changes without deletion.\n * \n * @default true\n */\n enabled: z.boolean()\n .default(true)\n .describe('Whether this policy is active'),\n\n /**\n * Policy priority for conflict resolution.\n * Higher numbers = higher priority.\n * When multiple policies apply, the most permissive wins (OR logic).\n * Priority is only used for ordering evaluation (performance).\n * \n * @default 0\n */\n priority: z.number()\n .int()\n .default(0)\n .describe('Policy evaluation priority (higher = evaluated first)'),\n\n /**\n * Tags for policy categorization and reporting.\n * Useful for governance, compliance, and auditing.\n * \n * @example [\"compliance\", \"gdpr\", \"pci\"]\n * @example [\"multi-tenant\", \"security\"]\n */\n tags: z.array(z.string())\n .optional()\n .describe('Policy categorization tags'),\n}).superRefine((data, ctx) => {\n // Ensure at least one of USING or CHECK is provided\n if (!data.using && !data.check) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'At least one of \"using\" or \"check\" must be specified. For SELECT/UPDATE/DELETE operations, provide \"using\". For INSERT operations, provide \"check\".',\n });\n }\n \n // For non-insert operations, USING should typically be present\n // This is a soft warning through documentation, not enforced here\n // since 'all' and mixed operation types are valid\n});\n\n/**\n * RLS Audit Event Schema\n * \n * Records a single RLS policy evaluation event for compliance and debugging.\n */\nexport const RLSAuditEventSchema = z.object({\n /** ISO 8601 timestamp of the evaluation */\n timestamp: z.string()\n .describe('ISO 8601 timestamp of the evaluation'),\n\n /** ID of the user whose access was evaluated */\n userId: z.string()\n .describe('User ID whose access was evaluated'),\n\n /** Database operation being performed */\n operation: z.enum(['select', 'insert', 'update', 'delete'])\n .describe('Database operation being performed'),\n\n /** Target object (table) name */\n object: z.string()\n .describe('Target object name'),\n\n /** Name of the RLS policy evaluated */\n policyName: z.string()\n .describe('Name of the RLS policy evaluated'),\n\n /** Whether access was granted */\n granted: z.boolean()\n .describe('Whether access was granted'),\n\n /** Time taken to evaluate the policy in milliseconds */\n evaluationDurationMs: z.number()\n .describe('Policy evaluation duration in milliseconds'),\n\n /** Which USING/CHECK clause matched */\n matchedCondition: z.string()\n .optional()\n .describe('Which USING/CHECK clause matched'),\n\n /** Number of rows affected by the operation */\n rowCount: z.number()\n .optional()\n .describe('Number of rows affected'),\n\n /** Additional metadata for the audit event */\n metadata: z.record(z.string(), z.unknown())\n .optional()\n .describe('Additional audit event metadata'),\n});\n\nexport type RLSAuditEvent = z.infer;\n\n/**\n * RLS Audit Configuration Schema\n * \n * Controls how RLS policy evaluations are logged and monitored.\n */\nexport const RLSAuditConfigSchema = z.object({\n /** Enable RLS audit logging */\n enabled: z.boolean()\n .describe('Enable RLS audit logging'),\n\n /** Which evaluations to log */\n logLevel: z.enum(['all', 'denied_only', 'granted_only', 'none'])\n .describe('Which evaluations to log'),\n\n /** Where to send audit logs */\n destination: z.enum(['system_log', 'audit_trail', 'external'])\n .describe('Audit log destination'),\n\n /** Sampling rate for high-traffic environments (0-1) */\n sampleRate: z.number()\n .min(0)\n .max(1)\n .describe('Sampling rate (0-1) for high-traffic environments'),\n\n /** Number of days to retain audit logs */\n retentionDays: z.number()\n .int()\n .default(90)\n .describe('Audit log retention period in days'),\n\n /** Whether to include row data in audit logs (security-sensitive) */\n includeRowData: z.boolean()\n .default(false)\n .describe('Include row data in audit logs (security-sensitive)'),\n\n /** Alert when access is denied */\n alertOnDenied: z.boolean()\n .default(true)\n .describe('Send alerts when access is denied'),\n});\n\nexport type RLSAuditConfig = z.infer;\n\n/**\n * RLS Configuration Schema\n * \n * Global configuration for the Row-Level Security system.\n * Defines how RLS is enforced across the entire platform.\n */\nexport const RLSConfigSchema = z.object({\n /**\n * Global RLS enable/disable flag.\n * When false, all RLS policies are ignored (use with caution!).\n * \n * @default true\n */\n enabled: z.boolean()\n .default(true)\n .describe('Enable RLS enforcement globally'),\n\n /**\n * Default behavior when no policies match.\n * \n * - **deny**: Deny access (secure default)\n * - **allow**: Allow access (permissive mode, not recommended)\n * \n * @default \"deny\"\n */\n defaultPolicy: z.enum(['deny', 'allow'])\n .default('deny')\n .describe('Default action when no policies match'),\n\n /**\n * Whether to allow superusers to bypass RLS.\n * Superusers include system administrators and service accounts.\n * \n * @default true\n */\n allowSuperuserBypass: z.boolean()\n .default(true)\n .describe('Allow superusers to bypass RLS'),\n\n /**\n * List of roles that can bypass RLS.\n * Users with these roles see all records regardless of policies.\n * \n * @example [\"system_admin\", \"data_auditor\"]\n */\n bypassRoles: z.array(z.string())\n .optional()\n .describe('Roles that bypass RLS (see all data)'),\n\n /**\n * Whether to log RLS policy evaluations.\n * Useful for debugging and auditing.\n * Can impact performance if enabled globally.\n * \n * @default false\n */\n logEvaluations: z.boolean()\n .default(false)\n .describe('Log RLS policy evaluations for debugging'),\n\n /**\n * Cache RLS policy evaluation results.\n * Can improve performance for frequently accessed records.\n * Cache is invalidated when policies change or user context changes.\n * \n * @default true\n */\n cacheResults: z.boolean()\n .default(true)\n .describe('Cache RLS evaluation results'),\n\n /**\n * Cache TTL in seconds.\n * How long to cache RLS evaluation results.\n * \n * @default 300 (5 minutes)\n */\n cacheTtlSeconds: z.number()\n .int()\n .positive()\n .default(300)\n .describe('Cache TTL in seconds'),\n\n /**\n * Performance optimization: Pre-fetch user context.\n * Load user context once per request instead of per-query.\n * \n * @default true\n */\n prefetchUserContext: z.boolean()\n .default(true)\n .describe('Pre-fetch user context for performance'),\n\n /**\n * Audit logging configuration for RLS evaluations.\n */\n audit: RLSAuditConfigSchema\n .optional()\n .describe('RLS audit logging configuration'),\n});\n\n/**\n * User Context Schema\n * \n * Represents the current user's context for RLS evaluation.\n * This data is used to evaluate USING and CHECK clauses.\n */\nexport const RLSUserContextSchema = z.object({\n /**\n * User ID\n */\n id: z.string()\n .describe('User ID'),\n\n /**\n * User email\n */\n email: z.string()\n .email()\n .optional()\n .describe('User email'),\n\n /**\n * Tenant/Organization ID\n */\n tenantId: z.string()\n .optional()\n .describe('Tenant/Organization ID'),\n\n /**\n * User role(s)\n */\n role: z.union([\n z.string(),\n z.array(z.string()),\n ])\n .optional()\n .describe('User role(s)'),\n\n /**\n * User department\n */\n department: z.string()\n .optional()\n .describe('User department'),\n\n /**\n * Additional custom attributes\n * Can include any custom user fields for RLS evaluation\n */\n attributes: z.record(z.string(), z.unknown())\n .optional()\n .describe('Additional custom user attributes'),\n});\n\n/**\n * RLS Policy Evaluation Result\n * \n * Result of evaluating an RLS policy for a specific record.\n * Used for debugging and audit logging.\n */\nexport const RLSEvaluationResultSchema = z.object({\n /**\n * Policy name that was evaluated\n */\n policyName: z.string()\n .describe('Policy name'),\n\n /**\n * Whether access was granted\n */\n granted: z.boolean()\n .describe('Whether access was granted'),\n\n /**\n * Evaluation duration in milliseconds\n */\n durationMs: z.number()\n .optional()\n .describe('Evaluation duration in milliseconds'),\n\n /**\n * Error message if evaluation failed\n */\n error: z.string()\n .optional()\n .describe('Error message if evaluation failed'),\n\n /**\n * Evaluated USING clause result\n */\n usingResult: z.boolean()\n .optional()\n .describe('USING clause evaluation result'),\n\n /**\n * Evaluated CHECK clause result (for INSERT/UPDATE)\n */\n checkResult: z.boolean()\n .optional()\n .describe('CHECK clause evaluation result'),\n});\n\n/**\n * Type exports\n */\nexport type RowLevelSecurityPolicy = z.infer;\nexport type RLSConfig = z.infer;\nexport type RLSUserContext = z.infer;\nexport type RLSEvaluationResult = z.infer;\n\n/**\n * Helper factory for creating RLS policies\n */\nexport const RLS = {\n /**\n * Create a simple owner-based policy\n */\n ownerPolicy: (object: string, ownerField: string = 'owner_id'): RowLevelSecurityPolicy => ({\n name: `${object}_owner_access`,\n label: `Owner Access for ${object}`,\n object,\n operation: 'all',\n using: `${ownerField} = current_user.id`,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a tenant isolation policy\n */\n tenantPolicy: (object: string, tenantField: string = 'tenant_id'): RowLevelSecurityPolicy => ({\n name: `${object}_tenant_isolation`,\n label: `Tenant Isolation for ${object}`,\n object,\n operation: 'all',\n using: `${tenantField} = current_user.tenant_id`,\n check: `${tenantField} = current_user.tenant_id`,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a role-based policy\n */\n rolePolicy: (object: string, roles: string[], condition: string): RowLevelSecurityPolicy => ({\n name: `${object}_${roles.join('_')}_access`,\n label: `${roles.join(', ')} Access for ${object}`,\n object,\n operation: 'select',\n using: condition,\n roles,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a permissive policy (allow all for specific roles)\n */\n allowAllPolicy: (object: string, roles: string[]): RowLevelSecurityPolicy => ({\n name: `${object}_${roles.join('_')}_full_access`,\n label: `Full Access for ${roles.join(', ')}`,\n object,\n operation: 'all',\n using: '1 = 1', // Always true\n roles,\n enabled: true,\n priority: 0,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { RowLevelSecurityPolicySchema } from './rls.zod';\n\n/**\n * Entity (Object) Level Permissions\n * Defines CRUD + VAMA (View All / Modify All) + Lifecycle access.\n * \n * Refined with enterprise data lifecycle controls:\n * - Transfer (Ownership change)\n * - Restore (Soft delete recovery)\n * - Purge (Hard delete / Compliance)\n */\nexport const ObjectPermissionSchema = z.object({\n /** C: Create */\n allowCreate: z.boolean().default(false).describe('Create permission'),\n /** R: Read (Owned records or Shared records) */\n allowRead: z.boolean().default(false).describe('Read permission'),\n /** U: Edit (Owned records or Shared records) */\n allowEdit: z.boolean().default(false).describe('Edit permission'),\n /** D: Delete (Owned records or Shared records) */\n allowDelete: z.boolean().default(false).describe('Delete permission'),\n \n /** Lifecycle Operations */\n allowTransfer: z.boolean().default(false).describe('Change record ownership'),\n allowRestore: z.boolean().default(false).describe('Restore from trash (Undelete)'),\n allowPurge: z.boolean().default(false).describe('Permanently delete (Hard Delete/GDPR)'),\n\n /** \n * View All Records: Super-user read access. \n * Bypasses Sharing Rules and Ownership checks.\n * Equivalent to Microsoft Dataverse \"Organization\" level read access.\n */\n viewAllRecords: z.boolean().default(false).describe('View All Data (Bypass Sharing)'),\n \n /** \n * Modify All Records: Super-user write access. \n * Bypasses Sharing Rules and Ownership checks.\n * Equivalent to Microsoft Dataverse \"Organization\" level write access.\n */\n modifyAllRecords: z.boolean().default(false).describe('Modify All Data (Bypass Sharing)'),\n});\n\n/**\n * Field Level Security (FLS)\n */\nexport const FieldPermissionSchema = z.object({\n /** Can see this field */\n readable: z.boolean().default(true).describe('Field read access'),\n /** Can edit this field */\n editable: z.boolean().default(false).describe('Field edit access'),\n});\n\n/**\n * Permission Set Schema\n * Defines a collection of permissions that can be assigned to users.\n * \n * DIFFERENTIATION:\n * - Profile: The ONE primary functional definition of a user (e.g. Standard User).\n * - Permission Set: Add-on capabilities assigned to users (e.g. Export Reports).\n * - Role: (Defined in src/system/role.zod.ts) Defines data visibility hierarchy.\n * \n * **NAMING CONVENTION:**\n * Permission set names MUST be lowercase snake_case to prevent security issues.\n * \n * @example Good permission set names\n * - 'read_only'\n * - 'system_admin'\n * - 'standard_user'\n * - 'api_access'\n * \n * @example Bad permission set names (will be rejected)\n * - 'ReadOnly' (camelCase)\n * - 'SystemAdmin' (mixed case)\n * - 'Read Only' (spaces)\n */\nexport const PermissionSetSchema = z.object({\n /** Unique permission set name */\n name: SnakeCaseIdentifierSchema.describe('Permission set unique name (lowercase snake_case)'),\n \n /** Display label */\n label: z.string().optional().describe('Display label'),\n \n /** Is this a Profile? (Base set for a user) */\n isProfile: z.boolean().default(false).describe('Whether this is a user profile'),\n \n /** Object Permissions Map: -> permissions */\n objects: z.record(z.string(), ObjectPermissionSchema).describe('Entity permissions'),\n \n /** Field Permissions Map: . -> permissions */\n fields: z.record(z.string(), FieldPermissionSchema).optional().describe('Field level security'),\n \n /** System permissions (e.g., \"manage_users\") */\n systemPermissions: z.array(z.string()).optional().describe('System level capabilities'),\n \n /**\n * Tab/App Visibility Permissions (Salesforce Pattern)\n * Controls which app tabs are visible, hidden, or set as default for this permission set.\n * \n * @example\n * ```typescript\n * tabPermissions: {\n * 'app_crm': 'visible',\n * 'app_admin': 'hidden',\n * 'app_sales': 'default_on'\n * }\n * ```\n */\n tabPermissions: z.record(z.string(), z.enum(['visible', 'hidden', 'default_on', 'default_off'])).optional()\n .describe('App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)'),\n \n /** \n * Row-Level Security Rules\n * \n * Row-level security policies that filter records based on user context.\n * These rules are applied in addition to object-level permissions.\n * \n * Uses the canonical RLS protocol from rls.zod.ts for comprehensive\n * row-level security features including PostgreSQL-style USING and CHECK clauses.\n * \n * @see {@link RowLevelSecurityPolicySchema} for full RLS specification\n * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation\n * \n * @example Multi-tenant isolation\n * ```typescript\n * rls: [{\n * name: 'tenant_filter',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id'\n * }]\n * ```\n */\n rowLevelSecurity: z.array(RowLevelSecurityPolicySchema).optional()\n .describe('Row-level security policies (see rls.zod.ts for full spec)'),\n \n /**\n * Context-Based Access Control Variables\n * \n * Custom context variables that can be referenced in RLS rules.\n * These variables are evaluated at runtime based on the user's session.\n * \n * Common context variables:\n * - `current_user.id` - Current user ID\n * - `current_user.tenant_id` - User's tenant/organization ID\n * - `current_user.department` - User's department\n * - `current_user.role` - User's role\n * - `current_user.region` - User's geographic region\n * \n * @example Custom context\n * ```typescript\n * contextVariables: {\n * allowed_regions: ['US', 'EU'],\n * access_level: 2,\n * custom_attribute: 'value'\n * }\n * ```\n */\n contextVariables: z.record(z.string(), z.unknown()).optional().describe('Context variables for RLS evaluation'),\n});\n\nexport type PermissionSet = z.infer;\nexport type ObjectPermission = z.infer;\nexport type FieldPermission = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Trigger events for workflow automation\n */\nexport const WorkflowTriggerType = z.enum([\n 'on_create', // When record is created\n 'on_update', // When record is updated\n 'on_create_or_update', // Both\n 'on_delete', // When record is deleted\n 'schedule' // Time-based (cron)\n]);\n\n/**\n * Schema for Workflow Field Update Action\n * @example\n * {\n * name: \"update_status\",\n * type: \"field_update\",\n * field: \"status\",\n * value: \"approved\"\n * }\n */\nexport const FieldUpdateActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('field_update'),\n field: z.string().describe('Field to update'),\n value: z.unknown().describe('Value or Formula to set'),\n});\n\n/**\n * Schema for Workflow Email Alert Action\n * @example\n * {\n * name: \"send_approval_email\",\n * type: \"email_alert\",\n * template: \"approval_request_email\",\n * recipients: [\"user_id_123\", \"manager_field\"]\n * }\n */\nexport const EmailAlertActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('email_alert'),\n template: z.string().describe('Email template ID/DevName'),\n recipients: z.array(z.string()).describe('List of recipient emails or user IDs'),\n});\n\n/**\n * Schema for Connector Action Reference\n * Executes a capability defined in an integration connector.\n * Replaces hardcoded vendor actions (Slack, Twilio, etc).\n * \n * @example Send Slack Message\n * {\n * name: \"notify_slack\",\n * type: \"connector_action\",\n * connectorId: \"slack\",\n * actionId: \"post_message\",\n * input: {\n * channel: \"#general\",\n * text: \"New deal closed: {name}\"\n * }\n * }\n */\nexport const ConnectorActionRefSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('connector_action'),\n connectorId: z.string().describe('Target Connector ID (e.g. slack, twilio)'),\n actionId: z.string().describe('Target Action ID (e.g. send_message)'),\n input: z.record(z.string(), z.unknown()).describe('Input parameters matching the action schema'),\n});\n\n/**\n * Schema for HTTP Callout Action\n * Makes a REST API call to an external service.\n * @example\n * {\n * name: \"sync_to_erp\",\n * type: \"http_call\",\n * url: \"https://erp.api/orders\",\n * method: \"POST\",\n * headers: { \"Authorization\": \"Bearer {token}\" },\n * body: \"{ ... }\"\n * }\n */\nexport const HttpCallActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('http_call'),\n url: z.string().describe('Target URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).default('POST').describe('HTTP Method'),\n headers: z.record(z.string(), z.string()).optional().describe('HTTP Headers'),\n body: z.string().optional().describe('Request body (JSON or text)'),\n});\n\n/**\n * Schema for Workflow Task Creation Action\n * @example\n * {\n * name: \"create_followup_task\",\n * type: \"task_creation\",\n * taskObject: \"tasks\",\n * subject: \"Follow up with client\",\n * dueDate: \"TODAY() + 3\"\n * }\n */\nexport const TaskCreationActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('task_creation'),\n taskObject: z.string().describe('Task object name (e.g., \"task\", \"project_task\")'),\n subject: z.string().describe('Task subject/title'),\n description: z.string().optional().describe('Task description'),\n assignedTo: z.string().optional().describe('User ID or field reference for assignee'),\n dueDate: z.string().optional().describe('Due date (ISO string or formula)'),\n priority: z.string().optional().describe('Task priority'),\n relatedTo: z.string().optional().describe('Related record ID or field reference'),\n additionalFields: z.record(z.string(), z.unknown()).optional().describe('Additional custom fields'),\n});\n\n/**\n * Schema for Workflow Push Notification Action\n */\nexport const PushNotificationActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('push_notification'),\n title: z.string().describe('Notification title'),\n body: z.string().describe('Notification body text'),\n recipients: z.array(z.string()).describe('User IDs or device tokens'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data payload'),\n badge: z.number().optional().describe('Badge count (iOS)'),\n sound: z.string().optional().describe('Notification sound'),\n clickAction: z.string().optional().describe('Action/URL when notification is clicked'),\n});\n\n/**\n * Schema for Workflow Custom Script Action\n */\nexport const CustomScriptActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('custom_script'),\n language: z.enum(['javascript', 'typescript', 'python']).default('javascript').describe('Script language'),\n code: z.string().describe('Script code to execute'),\n timeout: z.number().default(30000).describe('Execution timeout in milliseconds'),\n context: z.record(z.string(), z.unknown()).optional().describe('Additional context variables'),\n});\n\n/**\n * Universal Workflow Action Schema\n * Union of all supported action types.\n */\nexport const WorkflowActionSchema = z.discriminatedUnion('type', [\n FieldUpdateActionSchema,\n EmailAlertActionSchema,\n HttpCallActionSchema,\n ConnectorActionRefSchema,\n TaskCreationActionSchema,\n PushNotificationActionSchema,\n CustomScriptActionSchema,\n]);\n\nexport type WorkflowAction = z.infer;\n\n/**\n * Time Trigger Definition\n * Schedules actions to run relative to a specific time or date field.\n */\nexport const TimeTriggerSchema = z.object({\n id: z.string().optional().describe('Unique identifier'),\n \n /** Timing Logic */\n timeLength: z.number().int().describe('Duration amount (e.g. 1, 30)'),\n timeUnit: z.enum(['minutes', 'hours', 'days']).describe('Unit of time'),\n \n /** Reference Point */\n offsetDirection: z.enum(['before', 'after']).describe('Before or After the reference date'),\n offsetFrom: z.enum(['trigger_date', 'date_field']).describe('Basis for calculation'),\n dateField: z.string().optional().describe('Date field to calculate from (required if offsetFrom is date_field)'),\n \n /** Actions */\n actions: z.array(WorkflowActionSchema).describe('Actions to execute at the scheduled time'),\n});\n\n/**\n * Schema for Workflow Rules (Automation)\n * \n * **NAMING CONVENTION:**\n * Workflow names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good workflow names\n * - 'send_welcome_email'\n * - 'update_lead_status'\n * - 'notify_manager_on_close'\n * - 'calculate_discount'\n * \n * @example Bad workflow names (will be rejected)\n * - 'SendWelcomeEmail' (PascalCase)\n * - 'updateLeadStatus' (camelCase)\n * - 'Send Welcome Email' (spaces)\n * \n * @example Complete Workflow\n * {\n * name: \"new_lead_process\",\n * objectName: \"lead\",\n * triggerType: \"on_create\",\n * criteria: \"amount > 1000\",\n * active: true,\n * actions: [\n * {\n * name: \"set_status\",\n * type: \"field_update\",\n * field: \"status\",\n * value: \"new\"\n * },\n * {\n * name: \"notify_team\",\n * type: \"connector_action\",\n * connectorId: \"slack\",\n * actionId: \"post_message\",\n * input: { channel: \"#sales\", text: \"New high value lead!\" }\n * }\n * ],\n * timeTriggers: [\n * {\n * timeLength: 2,\n * timeUnit: \"days\",\n * offsetDirection: \"after\",\n * offsetFrom: \"trigger_date\",\n * actions: [\n * {\n * name: \"followup_check\",\n * type: \"task_creation\",\n * taskObject: \"task\",\n * subject: \"Follow up lead\",\n * dueDate: \"TODAY()\"\n * }\n * ]\n * }\n * ]\n * }\n */\nexport const WorkflowRuleSchema = z.object({\n /** Machine name */\n name: SnakeCaseIdentifierSchema.describe('Unique workflow name (lowercase snake_case)'),\n \n /** Target Object */\n objectName: z.string().describe('Target Object'),\n \n /** When to evaluate the rule */\n triggerType: WorkflowTriggerType.describe('When to evaluate'),\n \n /** \n * Condition to start the workflow.\n * If empty, runs on every trigger event.\n */\n criteria: z.string().optional().describe('Formula condition. If TRUE, actions execute.'),\n \n /** Actions to execute immediately */\n actions: z.array(WorkflowActionSchema).optional().describe('Immediate actions'),\n \n /** \n * Time-Dependent Actions \n * Actions scheduled to run in the future.\n */\n timeTriggers: z.array(TimeTriggerSchema).optional().describe('Scheduled actions relative to trigger or date field'),\n \n /** Active status */\n active: z.boolean().default(true).describe('Whether this workflow is active'),\n\n /** Execution Order */\n executionOrder: z.number().int().min(0).default(100).describe('Deterministic execution order when multiple workflows match (lower runs first)'),\n \n /** Recursion Control */\n reevaluateOnChange: z.boolean().default(false).describe('Re-evaluate rule if field updates change the record validity'),\n});\n\nexport type WorkflowRule = z.infer;\nexport type TimeTrigger = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const LocaleSchema = z.string().describe('BCP-47 Language Tag (e.g. en-US, zh-CN)');\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-level Translation (per-object file)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Field Translation Schema\n * Translation data for a single field.\n */\nexport const FieldTranslationSchema = z.object({\n label: z.string().optional().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n placeholder: z.string().optional().describe('Translated placeholder text for form inputs'),\n options: z.record(z.string(), z.string()).optional().describe('Option value to translated label map'),\n}).describe('Translation data for a single field');\n\nexport type FieldTranslation = z.infer;\n\n/**\n * Object Translation Data Schema\n *\n * Translation data for a **single object** in a **single locale**.\n * Use this schema to validate per-object translation files.\n *\n * File convention: `i18n/{locale}/{object_name}.json`\n *\n * @example\n * ```json\n * // i18n/en/account.json\n * {\n * \"label\": \"Account\",\n * \"pluralLabel\": \"Accounts\",\n * \"fields\": {\n * \"name\": { \"label\": \"Account Name\", \"help\": \"Legal name\" },\n * \"type\": { \"label\": \"Type\", \"options\": { \"customer\": \"Customer\" } }\n * }\n * }\n * ```\n */\nexport const ObjectTranslationDataSchema = z.object({\n /** Translated singular label for the object */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label for the object */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional().describe('Field-level translations'),\n}).describe('Translation data for a single object');\n\nexport type ObjectTranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale-level Translation Data (per-locale aggregate)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Data Schema\n * Supports i18n for labels, messages, and options within a single locale.\n * Example structure:\n * ```json\n * {\n * \"objects\": { \"account\": { \"label\": \"Account\" } },\n * \"apps\": { \"crm\": { \"label\": \"CRM\" } },\n * \"messages\": { \"common.save\": \"Save\" }\n * }\n * ```\n */\nexport const TranslationDataSchema = z.object({\n /** Object translations */\n objects: z.record(z.string(), ObjectTranslationDataSchema).optional().describe('Object translations keyed by object name'),\n \n /** App/Menu translations */\n apps: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** UI Messages */\n messages: z.record(z.string(), z.string()).optional().describe('UI message translations keyed by message ID'),\n \n /** Validation Error Messages */\n validationMessages: z.record(z.string(), z.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {\"discount_limit\": \"折扣不能超过40%\"})'),\n}).describe('Translation data for objects, apps, and UI messages');\n\nexport type TranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Bundle (all locales)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const TranslationBundleSchema = z.record(LocaleSchema, TranslationDataSchema).describe('Map of locale codes to translation data');\n\nexport type TranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// File Organization Convention\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation File Organization Strategy\n *\n * Defines how translation files are organized on disk.\n *\n * - `bundled` — All locales in a single `TranslationBundle` file.\n * Best for small projects with few objects.\n * ```\n * src/translations/\n * crm.translation.ts # { en: {...}, \"zh-CN\": {...} }\n * ```\n *\n * - `per_locale` — One file per locale containing all namespaces.\n * Recommended when a single locale file stays under ~500 lines.\n * ```\n * src/translations/\n * en.ts # TranslationData for English\n * zh-CN.ts # TranslationData for Chinese\n * ```\n *\n * - `per_namespace` — One file per namespace (object) per locale.\n * Recommended for large projects with many objects/languages.\n * Aligns with Salesforce DX and ServiceNow conventions.\n * ```\n * i18n/\n * en/\n * account.json # ObjectTranslationData\n * contact.json\n * common.json # messages + app labels\n * zh-CN/\n * account.json\n * contact.json\n * common.json\n * ```\n */\nexport const TranslationFileOrganizationSchema = z.enum([\n 'bundled',\n 'per_locale',\n 'per_namespace',\n]).describe('Translation file organization strategy');\n\nexport type TranslationFileOrganization = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Configuration\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Configuration Schema\n *\n * Defines internationalization settings for the stack.\n *\n * @example\n * ```typescript\n * export default defineStack({\n * i18n: {\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'zh-CN', 'ja-JP'],\n * fallbackLocale: 'en',\n * fileOrganization: 'per_locale',\n * },\n * translations: [...],\n * });\n * ```\n */\n/**\n * Message format standard used for interpolation, pluralization, and\n * gender-aware translations.\n *\n * - `icu` — ICU MessageFormat (recommended for complex plurals, gender, select).\n * Strings may contain `{count, plural, one {# item} other {# items}}` patterns.\n * - `simple` — Simple `{variable}` interpolation only (default).\n */\nexport const MessageFormatSchema = z.enum([\n 'icu',\n 'simple',\n]).describe('Message interpolation format: ICU MessageFormat or simple {variable} replacement');\n\nexport type MessageFormat = z.infer;\n\nexport const TranslationConfigSchema = z.object({\n /** Default locale for the application */\n defaultLocale: LocaleSchema.describe('Default locale (e.g., \"en\")'),\n /** Supported BCP-47 locale codes */\n supportedLocales: z.array(LocaleSchema).describe('Supported BCP-47 locale codes'),\n /** Fallback locale when translation is not found */\n fallbackLocale: LocaleSchema.optional().describe('Fallback locale code'),\n /** How translation files are organized on disk */\n fileOrganization: TranslationFileOrganizationSchema.default('per_locale')\n .describe('File organization strategy'),\n /**\n * Message interpolation format.\n * When set to `'icu'`, messages and validationMessages are expected to use\n * ICU MessageFormat syntax (plurals, select, number/date skeletons).\n * @default 'simple'\n */\n messageFormat: MessageFormatSchema.default('simple')\n .describe('Message interpolation format (ICU MessageFormat or simple)'),\n /** Load translations on demand instead of eagerly */\n lazyLoad: z.boolean().default(false).describe('Load translations on demand'),\n /** Cache loaded translations in memory */\n cache: z.boolean().default(true).describe('Cache loaded translations'),\n}).describe('Internationalization configuration');\n\nexport type TranslationConfig = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-First Translation Node (object-first aggregated structure)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Translatable option map: option value → translated label */\nconst OptionTranslationMapSchema = z.record(z.string(), z.string())\n .describe('Option value to translated label map');\n\n/**\n * ObjectTranslationNodeSchema\n *\n * Object-first aggregated translation node that groups **all** translatable\n * content for a single object under one key. Aligns with Salesforce / Dynamics\n * conventions where translations are organized per-object rather than per-category.\n *\n * Located at `o.{object_name}` inside an {@link AppTranslationBundle}.\n *\n * @example\n * ```typescript\n * const accountNode: ObjectTranslationNode = {\n * label: '客户',\n * pluralLabel: '客户',\n * description: '客户管理对象',\n * fields: {\n * name: { label: '客户名称', help: '公司或组织的法定名称' },\n * industry: { label: '行业', options: { tech: '科技', finance: '金融' } },\n * },\n * _options: { status: { active: '活跃', inactive: '停用' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: {\n * convert_lead: { label: '转换线索', confirmMessage: '确认转换?' },\n * },\n * };\n * ```\n */\nexport const ObjectTranslationNodeSchema = z.object({\n /** Translated singular label */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Translated object description */\n description: z.string().optional().describe('Translated object description'),\n /** Translated help text shown in tooltips or guidance panels */\n helpText: z.string().optional().describe('Translated help text for the object'),\n\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional()\n .describe('Field translations keyed by field name'),\n\n /**\n * Global picklist / select option overrides scoped to this object.\n * Keyed by field name → { optionValue: translatedLabel }.\n */\n _options: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Object-scoped picklist option translations keyed by field name'),\n\n /** View translations keyed by view name */\n _views: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated view label'),\n description: z.string().optional().describe('Translated view description'),\n })).optional().describe('View translations keyed by view name'),\n\n /** Section (form section / tab) translations keyed by section name */\n _sections: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated section label'),\n })).optional().describe('Section translations keyed by section name'),\n\n /** Action translations keyed by action name */\n _actions: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated action label'),\n confirmMessage: z.string().optional().describe('Translated confirmation message'),\n })).optional().describe('Action translations keyed by action name'),\n\n /** Notification message translations keyed by notification name */\n _notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Notification translations keyed by notification name'),\n\n /** Error message translations keyed by error code */\n _errors: z.record(z.string(), z.string()).optional()\n .describe('Error message translations keyed by error code'),\n}).describe('Object-first aggregated translation node');\n\nexport type ObjectTranslationNode = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// App Translation Bundle (object-first, full application)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * AppTranslationBundleSchema\n *\n * Complete application translation bundle for a **single locale** using\n * the **object-first** convention. All per-object translatable content\n * is aggregated under `o.{object_name}`, while global (non-object-bound)\n * translations are kept in dedicated top-level groups.\n *\n * This schema is designed for:\n * - Translation workbench UIs (object-level editing & coverage)\n * - CLI skeleton generation (`objectstack i18n extract`)\n * - Automated diff/coverage detection\n *\n * @example\n * ```typescript\n * const zh: AppTranslationBundle = {\n * o: {\n * account: {\n * label: '客户',\n * fields: { name: { label: '客户名称' } },\n * _options: { industry: { tech: '科技' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: { convert: { label: '转换' } },\n * },\n * },\n * _globalOptions: { currency: { usd: '美元', eur: '欧元' } },\n * app: { crm: { label: '客户关系管理', description: '管理销售流程' } },\n * nav: { home: '首页', settings: '设置' },\n * dashboard: { sales_overview: { label: '销售概览' } },\n * reports: { pipeline_report: { label: '管道报表' } },\n * pages: { landing: { title: '欢迎' } },\n * messages: { 'common.save': '保存' },\n * validationMessages: { 'discount_limit': '折扣不能超过40%' },\n * };\n * ```\n */\nexport const AppTranslationBundleSchema = z.object({\n /**\n * Bundle-level metadata.\n * Provides locale-aware rendering hints such as text direction (bidi)\n * and the canonical locale code this bundle represents.\n */\n _meta: z.object({\n /** BCP-47 locale code this bundle represents */\n locale: z.string().optional().describe('BCP-47 locale code for this bundle'),\n /** Text direction for the locale */\n direction: z.enum(['ltr', 'rtl']).optional().describe('Text direction: left-to-right or right-to-left'),\n }).optional().describe('Bundle-level metadata (locale, bidi direction)'),\n\n /**\n * Namespace for plugin/extension isolation.\n * When multiple plugins contribute translations, each should use a unique\n * namespace to avoid key collisions (e.g. \"crm\", \"helpdesk\", \"plugin-xyz\").\n */\n namespace: z.string().optional()\n .describe('Namespace for plugin isolation to avoid translation key collisions'),\n\n /** Object-first translations keyed by object name (snake_case) */\n o: z.record(z.string(), ObjectTranslationNodeSchema).optional()\n .describe('Object-first translations keyed by object name'),\n\n /** Global picklist options not bound to any specific object */\n _globalOptions: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Global picklist option translations keyed by option set name'),\n\n /** App-level translations */\n app: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** Navigation menu translations */\n nav: z.record(z.string(), z.string()).optional()\n .describe('Navigation item translations keyed by nav item name'),\n\n /** Dashboard translations keyed by dashboard name */\n dashboard: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated dashboard label'),\n description: z.string().optional().describe('Translated dashboard description'),\n })).optional().describe('Dashboard translations keyed by dashboard name'),\n\n /** Report translations keyed by report name */\n reports: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated report label'),\n description: z.string().optional().describe('Translated report description'),\n })).optional().describe('Report translations keyed by report name'),\n\n /** Page translations keyed by page name */\n pages: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated page title'),\n description: z.string().optional().describe('Translated page description'),\n })).optional().describe('Page translations keyed by page name'),\n\n /** UI message translations (supports ICU MessageFormat when enabled) */\n messages: z.record(z.string(), z.string()).optional()\n .describe('UI message translations keyed by message ID (supports ICU MessageFormat)'),\n\n /** Validation error message translations (supports ICU MessageFormat when enabled) */\n validationMessages: z.record(z.string(), z.string()).optional()\n .describe('Validation error message translations keyed by rule name (supports ICU MessageFormat)'),\n\n /** Global notification translations not bound to a specific object */\n notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Global notification translations keyed by notification name'),\n\n /** Global error message translations not bound to a specific object */\n errors: z.record(z.string(), z.string()).optional()\n .describe('Global error message translations keyed by error code'),\n}).describe('Object-first application translation bundle for a single locale');\n\nexport type AppTranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Diff & Coverage\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Diff Status\n *\n * Status of a single translation entry compared to the source metadata.\n */\nexport const TranslationDiffStatusSchema = z.enum([\n 'missing',\n 'redundant',\n 'stale',\n]).describe('Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)');\n\nexport type TranslationDiffStatus = z.infer;\n\n/**\n * TranslationDiffItemSchema\n *\n * Describes a single translation key that is missing, redundant, or stale\n * relative to the source metadata. Used by CLI/API diff detection.\n *\n * @example\n * ```typescript\n * const item: TranslationDiffItem = {\n * key: 'o.account.fields.website.label',\n * status: 'missing',\n * objectName: 'account',\n * locale: 'zh-CN',\n * };\n * ```\n */\nexport const TranslationDiffItemSchema = z.object({\n /** Dot-path translation key (e.g. \"o.account.fields.website.label\") */\n key: z.string().describe('Dot-path translation key'),\n /** Diff status */\n status: TranslationDiffStatusSchema.describe('Diff status of this translation key'),\n /** Object name if the key belongs to an object translation node */\n objectName: z.string().optional().describe('Associated object name (snake_case)'),\n /** Locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /**\n * Hash of the source metadata value at the time the translation was made.\n * Used by CLI/Workbench to detect stale translations without a full diff.\n */\n sourceHash: z.string().optional().describe('Hash of source metadata for precise stale detection'),\n /**\n * AI-suggested translation text for missing or stale entries.\n * Populated by AI translation hooks or TMS integrations.\n */\n aiSuggested: z.string().optional().describe('AI-suggested translation for this key'),\n /** Confidence score (0-1) for the AI suggestion */\n aiConfidence: z.number().min(0).max(1).optional().describe('AI suggestion confidence score (0–1)'),\n}).describe('A single translation diff item');\n\nexport type TranslationDiffItem = z.infer;\n\n/**\n * TranslationCoverageResultSchema\n *\n * Aggregated coverage result for a locale, optionally scoped to a single object.\n * Returned by the i18n diff detection API.\n *\n * @example\n * ```typescript\n * const result: TranslationCoverageResult = {\n * locale: 'zh-CN',\n * totalKeys: 120,\n * translatedKeys: 105,\n * missingKeys: 12,\n * redundantKeys: 3,\n * staleKeys: 0,\n * coveragePercent: 87.5,\n * items: [ ... ],\n * };\n * ```\n */\n/**\n * Per-group coverage breakdown entry.\n */\nexport const CoverageBreakdownEntrySchema = z.object({\n /** Group category (e.g. \"fields\", \"views\", \"actions\", \"messages\") */\n group: z.string().describe('Translation group category'),\n /** Total translatable keys in this group */\n totalKeys: z.number().int().nonnegative().describe('Total keys in this group'),\n /** Number of translated keys in this group */\n translatedKeys: z.number().int().nonnegative().describe('Translated keys in this group'),\n /** Coverage percentage for this group */\n coveragePercent: z.number().min(0).max(100).describe('Coverage percentage for this group'),\n}).describe('Coverage breakdown for a single translation group');\n\nexport type CoverageBreakdownEntry = z.infer;\n\nexport const TranslationCoverageResultSchema = z.object({\n /** BCP-47 locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /** Optional object name scope */\n objectName: z.string().optional().describe('Object name scope (omit for full bundle)'),\n /** Total translatable keys derived from metadata */\n totalKeys: z.number().int().nonnegative().describe('Total translatable keys from metadata'),\n /** Number of keys that have a translation */\n translatedKeys: z.number().int().nonnegative().describe('Number of translated keys'),\n /** Number of missing translations */\n missingKeys: z.number().int().nonnegative().describe('Number of missing translations'),\n /** Number of redundant (orphaned) translations */\n redundantKeys: z.number().int().nonnegative().describe('Number of redundant translations'),\n /** Number of stale translations */\n staleKeys: z.number().int().nonnegative().describe('Number of stale translations'),\n /** Coverage percentage (0-100) */\n coveragePercent: z.number().min(0).max(100).describe('Translation coverage percentage'),\n /** Individual diff items */\n items: z.array(TranslationDiffItemSchema).describe('Detailed diff items'),\n /**\n * Per-group coverage breakdown for translation project management.\n * Each entry represents a logical group (e.g. \"fields\", \"views\", \"actions\",\n * \"messages\") with its own coverage statistics.\n */\n breakdown: z.array(CoverageBreakdownEntrySchema).optional()\n .describe('Per-group coverage breakdown'),\n}).describe('Aggregated translation coverage result');\n\nexport type TranslationCoverageResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Capability Protocol\n * \n * Defines the standard way plugins declare their capabilities, implementations,\n * and conformance levels to ensure interoperability across vendors.\n * \n * Based on the Protocol-Oriented Architecture pattern similar to:\n * - Kubernetes CRDs (Custom Resource Definitions)\n * - OSGi Service Registry\n * - Eclipse Extension Points\n */\n\n/**\n * Capability Conformance Level\n * Indicates how completely a plugin implements a given protocol.\n */\nexport const CapabilityConformanceLevelSchema = z.enum([\n 'full', // Complete implementation of all protocol features\n 'partial', // Subset implementation with specific features listed\n 'experimental', // Unstable/preview implementation\n 'deprecated', // Still supported but scheduled for removal\n]).describe('Level of protocol conformance');\n\n/**\n * Protocol Version Schema\n * Uses semantic versioning to track protocol evolution.\n */\nexport const ProtocolVersionSchema = z.object({\n major: z.number().int().min(0),\n minor: z.number().int().min(0),\n patch: z.number().int().min(0),\n}).describe('Semantic version of the protocol');\n\n/**\n * Protocol Reference\n * Uniquely identifies a protocol/interface that a plugin can implement.\n * \n * Examples:\n * - com.objectstack.protocol.storage.v1\n * - com.objectstack.protocol.auth.oauth2.v2\n * - com.acme.protocol.payment.stripe.v1\n */\nexport const ProtocolReferenceSchema = z.object({\n /**\n * Protocol identifier using reverse domain notation.\n * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+protocol\\.[a-z][a-z0-9._]*\\.v\\d+$/)\n .describe('Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)'),\n \n /**\n * Human-readable protocol name\n */\n label: z.string(),\n \n /**\n * Protocol version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Detailed protocol specification URL or file reference\n */\n specification: z.string().optional().describe('URL or path to protocol specification'),\n \n /**\n * Brief description of what this protocol defines\n */\n description: z.string().optional(),\n});\n\n/**\n * Protocol Feature\n * Represents a specific capability within a protocol.\n */\nexport const ProtocolFeatureSchema = z.object({\n name: z.string().describe('Feature identifier within the protocol'),\n enabled: z.boolean().default(true),\n description: z.string().optional(),\n sinceVersion: z.string().optional().describe('Version when this feature was added'),\n deprecatedSince: z.string().optional().describe('Version when deprecated'),\n});\n\n/**\n * Plugin Capability Declaration\n * Documents what protocols a plugin implements and to what extent.\n */\nexport const PluginCapabilitySchema = z.object({\n /**\n * The protocol being implemented\n */\n protocol: ProtocolReferenceSchema,\n \n /**\n * Conformance level\n */\n conformance: CapabilityConformanceLevelSchema.default('full'),\n \n /**\n * Specific features implemented (required if conformance is 'partial')\n */\n implementedFeatures: z.array(z.string()).optional().describe('List of implemented feature names'),\n \n /**\n * Optional feature flags indicating advanced capabilities\n */\n features: z.array(ProtocolFeatureSchema).optional(),\n \n /**\n * Custom metadata for vendor-specific information\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Testing/Certification status\n */\n certified: z.boolean().default(false).describe('Has passed official conformance tests'),\n certificationDate: z.string().datetime().optional(),\n});\n\n/**\n * Plugin Interface Declaration\n * Defines the contract for services this plugin provides to other plugins.\n */\nexport const PluginInterfaceSchema = z.object({\n /**\n * Unique interface identifier\n * Format: {plugin-id}.interface.{name}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+interface\\.[a-z][a-z0-9._]+$/)\n .describe('Unique interface identifier'),\n \n /**\n * Interface name\n */\n name: z.string(),\n \n /**\n * Description of what this interface provides\n */\n description: z.string().optional(),\n \n /**\n * Interface version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Methods exposed by this interface\n */\n methods: z.array(z.object({\n name: z.string().describe('Method name'),\n description: z.string().optional(),\n parameters: z.array(z.object({\n name: z.string(),\n type: z.string().describe('Type notation (e.g., string, number, User)'),\n required: z.boolean().default(true),\n description: z.string().optional(),\n })).optional(),\n returnType: z.string().optional().describe('Return value type'),\n async: z.boolean().default(false).describe('Whether method returns a Promise'),\n })),\n \n /**\n * Events emitted by this interface\n */\n events: z.array(z.object({\n name: z.string().describe('Event name'),\n description: z.string().optional(),\n payload: z.string().optional().describe('Event payload type'),\n })).optional(),\n \n /**\n * Stability level\n */\n stability: z.enum(['stable', 'beta', 'alpha', 'experimental']).default('stable'),\n});\n\n/**\n * Plugin Dependency Declaration\n * Specifies what other plugins or capabilities this plugin requires.\n */\nexport const PluginDependencySchema = z.object({\n /**\n * Plugin ID using reverse domain notation\n */\n pluginId: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Required plugin identifier'),\n \n /**\n * Version constraint (supports semver ranges)\n * Examples: \"1.0.0\", \"^1.2.3\", \">=2.0.0 <3.0.0\"\n */\n version: z.string().describe('Semantic version constraint'),\n \n /**\n * Whether this dependency is optional\n */\n optional: z.boolean().default(false),\n \n /**\n * Reason for the dependency\n */\n reason: z.string().optional(),\n \n /**\n * Minimum required capabilities from the dependency\n */\n requiredCapabilities: z.array(z.string()).optional().describe('Protocol IDs the dependency must support'),\n});\n\n/**\n * Extension Point Declaration\n * Defines hooks where other plugins can extend this plugin's functionality.\n */\nexport const ExtensionPointSchema = z.object({\n /**\n * Extension point identifier\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+extension\\.[a-z][a-z0-9._]+$/)\n .describe('Unique extension point identifier'),\n \n /**\n * Extension point name\n */\n name: z.string(),\n \n /**\n * Description\n */\n description: z.string().optional(),\n \n /**\n * Type of extension point\n */\n type: z.enum([\n 'action', // Plugins can register executable actions\n 'hook', // Plugins can listen to lifecycle events\n 'widget', // Plugins can contribute UI widgets\n 'provider', // Plugins can provide data/services\n 'transformer', // Plugins can transform data\n 'validator', // Plugins can validate data\n 'decorator', // Plugins can enhance/wrap functionality\n ]),\n \n /**\n * Expected interface contract for extensions\n */\n contract: z.object({\n input: z.string().optional().describe('Input type/schema'),\n output: z.string().optional().describe('Output type/schema'),\n signature: z.string().optional().describe('Function signature if applicable'),\n }).optional(),\n \n /**\n * Cardinality\n */\n cardinality: z.enum(['single', 'multiple']).default('multiple')\n .describe('Whether multiple extensions can register to this point'),\n});\n\n/**\n * Complete Plugin Capability Manifest\n * This is included in the main plugin manifest to declare all capabilities.\n */\nexport const PluginCapabilityManifestSchema = z.object({\n /**\n * Protocols this plugin implements\n */\n implements: z.array(PluginCapabilitySchema).optional()\n .describe('List of protocols this plugin conforms to'),\n \n /**\n * Interfaces this plugin exposes to other plugins\n */\n provides: z.array(PluginInterfaceSchema).optional()\n .describe('Services/APIs this plugin offers to others'),\n \n /**\n * Dependencies on other plugins\n */\n requires: z.array(PluginDependencySchema).optional()\n .describe('Required plugins and their capabilities'),\n \n /**\n * Extension points this plugin defines\n */\n extensionPoints: z.array(ExtensionPointSchema).optional()\n .describe('Points where other plugins can extend this plugin'),\n \n /**\n * Extensions this plugin contributes to other plugins\n */\n extensions: z.array(z.object({\n targetPluginId: z.string().describe('Plugin ID being extended'),\n extensionPointId: z.string().describe('Extension point identifier'),\n implementation: z.string().describe('Path to implementation module'),\n priority: z.number().int().default(100).describe('Registration priority (lower = higher priority)'),\n })).optional().describe('Extensions contributed to other plugins'),\n});\n\n// Export types\nexport type CapabilityConformanceLevel = z.infer;\nexport type ProtocolVersion = z.infer;\nexport type ProtocolReference = z.infer;\nexport type ProtocolFeature = z.infer;\nexport type PluginCapability = z.infer;\nexport type PluginInterface = z.infer;\nexport type PluginDependency = z.infer;\nexport type ExtensionPoint = z.infer;\nexport type PluginCapabilityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Loading Protocol\n * \n * Defines the enhanced plugin loading mechanism for the microkernel architecture.\n * Inspired by industry best practices from:\n * - Kubernetes CRDs and Operators\n * - OSGi Dynamic Module System\n * - Eclipse Plugin Framework\n * - Webpack Module Federation\n * \n * This protocol enables:\n * - Lazy loading and code splitting\n * - Dynamic imports and parallel initialization\n * - Capability-based discovery\n * - Hot reload in development\n * - Advanced caching strategies\n */\n\n/**\n * Plugin Loading Strategy\n * Determines how and when a plugin is loaded into memory\n */\nexport const PluginLoadingStrategySchema = z.enum([\n 'eager', // Load immediately during bootstrap (critical plugins)\n 'lazy', // Load on first use (feature plugins)\n 'parallel', // Load in parallel with other plugins\n 'deferred', // Load after initial bootstrap complete\n 'on-demand', // Load only when explicitly requested\n]).describe('Plugin loading strategy');\n\n/**\n * Plugin Preloading Configuration\n * Configures preloading behavior for faster activation\n */\nexport const PluginPreloadConfigSchema = z.object({\n /**\n * Enable preloading for this plugin\n */\n enabled: z.boolean().default(false),\n \n /**\n * Preload priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Resources to preload\n */\n resources: z.array(z.enum([\n 'metadata', // Plugin manifest and metadata\n 'dependencies', // Plugin dependencies\n 'assets', // Static assets (icons, translations)\n 'code', // JavaScript code chunks\n 'services', // Service definitions\n ])).optional(),\n \n /**\n * Conditions for preloading\n */\n conditions: z.object({\n /**\n * Preload only on specific routes\n */\n routes: z.array(z.string()).optional(),\n \n /**\n * Preload only for specific user roles\n */\n roles: z.array(z.string()).optional(),\n \n /**\n * Preload based on device type\n */\n deviceType: z.array(z.enum(['desktop', 'mobile', 'tablet'])).optional(),\n \n /**\n * Network connection quality threshold\n */\n minNetworkSpeed: z.enum(['slow-2g', '2g', '3g', '4g']).optional(),\n }).optional(),\n}).describe('Plugin preloading configuration');\n\n/**\n * Plugin Code Splitting Configuration\n * Configures how plugin code is split for optimal loading\n */\nexport const PluginCodeSplittingSchema = z.object({\n /**\n * Enable code splitting for this plugin\n */\n enabled: z.boolean().default(true),\n \n /**\n * Split strategy\n */\n strategy: z.enum([\n 'route', // Split by UI routes\n 'feature', // Split by feature modules\n 'size', // Split by bundle size threshold\n 'custom', // Custom split points defined by plugin\n ]).default('feature'),\n \n /**\n * Chunk naming strategy\n */\n chunkNaming: z.enum(['hashed', 'named', 'sequential']).default('hashed'),\n \n /**\n * Maximum chunk size in KB\n */\n maxChunkSize: z.number().int().min(10).optional().describe('Max chunk size in KB'),\n \n /**\n * Shared dependencies optimization\n */\n sharedDependencies: z.object({\n enabled: z.boolean().default(true),\n /**\n * Minimum times a module must be shared before extraction\n */\n minChunks: z.number().int().min(1).default(2),\n }).optional(),\n}).describe('Plugin code splitting configuration');\n\n/**\n * Plugin Dynamic Import Configuration\n * Configures dynamic import behavior for runtime module loading\n */\nexport const PluginDynamicImportSchema = z.object({\n /**\n * Enable dynamic imports\n */\n enabled: z.boolean().default(true),\n \n /**\n * Import mode\n */\n mode: z.enum([\n 'async', // Asynchronous import (recommended)\n 'sync', // Synchronous import (blocking)\n 'eager', // Eager evaluation\n 'lazy', // Lazy evaluation\n ]).default('async'),\n \n /**\n * Prefetch strategy\n */\n prefetch: z.boolean().default(false).describe('Prefetch module in idle time'),\n \n /**\n * Preload strategy\n */\n preload: z.boolean().default(false).describe('Preload module in parallel with parent'),\n \n /**\n * Webpack magic comments support\n */\n webpackChunkName: z.string().optional().describe('Custom chunk name for webpack'),\n \n /**\n * Import timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000).describe('Dynamic import timeout (ms)'),\n \n /**\n * Retry configuration on import failure\n */\n retry: z.object({\n enabled: z.boolean().default(true),\n maxAttempts: z.number().int().min(1).max(10).default(3),\n backoffMs: z.number().int().min(0).default(1000).describe('Exponential backoff base delay'),\n }).optional(),\n}).describe('Plugin dynamic import configuration');\n\n/**\n * Plugin Initialization Configuration\n * Configures how plugin initialization is executed\n */\nexport const PluginInitializationSchema = z.object({\n /**\n * Initialization mode\n */\n mode: z.enum([\n 'sync', // Synchronous initialization\n 'async', // Asynchronous initialization\n 'parallel', // Parallel with other plugins\n 'sequential', // Must complete before next plugin\n ]).default('async'),\n \n /**\n * Initialization timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000),\n \n /**\n * Startup priority (lower = higher priority, earlier initialization)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Whether to continue bootstrap if this plugin fails\n */\n critical: z.boolean().default(false).describe('If true, kernel bootstrap fails if plugin fails'),\n \n /**\n * Retry configuration on initialization failure\n */\n retry: z.object({\n enabled: z.boolean().default(false),\n maxAttempts: z.number().int().min(1).max(5).default(3),\n backoffMs: z.number().int().min(0).default(1000),\n }).optional(),\n \n /**\n * Health check interval for monitoring\n */\n healthCheckInterval: z.number().int().min(0).optional().describe('Health check interval in ms (0 = disabled)'),\n}).describe('Plugin initialization configuration');\n\n/**\n * Plugin Dependency Resolution Configuration\n * Advanced dependency resolution using semantic versioning\n */\nexport const PluginDependencyResolutionSchema = z.object({\n /**\n * Dependency resolution strategy\n */\n strategy: z.enum([\n 'strict', // Exact version match required\n 'compatible', // Semver compatible versions (^)\n 'latest', // Always use latest compatible\n 'pinned', // Lock to specific version\n ]).default('compatible'),\n \n /**\n * Peer dependency handling\n */\n peerDependencies: z.object({\n /**\n * Whether to resolve peer dependencies\n */\n resolve: z.boolean().default(true),\n \n /**\n * Action on missing peer dependency\n */\n onMissing: z.enum(['error', 'warn', 'ignore']).default('warn'),\n \n /**\n * Action on peer version mismatch\n */\n onMismatch: z.enum(['error', 'warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Optional dependency handling\n */\n optionalDependencies: z.object({\n /**\n * Whether to attempt loading optional dependencies\n */\n load: z.boolean().default(true),\n \n /**\n * Action on optional dependency load failure\n */\n onFailure: z.enum(['warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Conflict resolution\n */\n conflictResolution: z.enum([\n 'fail', // Fail on any version conflict\n 'latest', // Use latest version\n 'oldest', // Use oldest version\n 'manual', // Require manual resolution\n ]).default('latest'),\n \n /**\n * Circular dependency handling\n */\n circularDependencies: z.enum([\n 'error', // Throw error on circular dependency\n 'warn', // Warn but continue\n 'allow', // Allow circular dependencies\n ]).default('warn'),\n}).describe('Plugin dependency resolution configuration');\n\n/**\n * Plugin Hot Reload Configuration\n * Enables hot module replacement for development and production environments.\n * \n * Production mode adds safety features: health validation, rollback on failure,\n * connection draining, and concurrency control for zero-downtime reloads.\n */\nexport const PluginHotReloadSchema = z.object({\n /**\n * Enable hot reload\n */\n enabled: z.boolean().default(false),\n \n /**\n * Target environment for hot reload behavior\n */\n environment: z.enum([\n 'development', // Fast reload with relaxed safety (file watchers, no health validation)\n 'staging', // Production-like reload with validation but relaxed rollback\n 'production', // Full safety: health validation, rollback, connection draining\n ]).default('development').describe('Target environment controlling safety level'),\n \n /**\n * Hot reload strategy\n */\n strategy: z.enum([\n 'full', // Full plugin reload (destroy and reinitialize)\n 'partial', // Partial reload (update changed modules only)\n 'state-preserve', // Preserve plugin state during reload\n ]).default('full'),\n \n /**\n * Files to watch for changes\n */\n watchPatterns: z.array(z.string()).optional().describe('Glob patterns for files to watch'),\n \n /**\n * Files to ignore\n */\n ignorePatterns: z.array(z.string()).optional().describe('Glob patterns for files to ignore'),\n \n /**\n * Debounce delay in milliseconds\n */\n debounceMs: z.number().int().min(0).default(300),\n \n /**\n * Whether to preserve state during reload\n */\n preserveState: z.boolean().default(false),\n \n /**\n * State serialization\n */\n stateSerialization: z.object({\n enabled: z.boolean().default(false),\n /**\n * Path to state serialization handler\n */\n handler: z.string().optional(),\n }).optional(),\n \n /**\n * Hooks for hot reload lifecycle\n */\n hooks: z.object({\n beforeReload: z.string().optional().describe('Function to call before reload'),\n afterReload: z.string().optional().describe('Function to call after reload'),\n onError: z.string().optional().describe('Function to call on reload error'),\n }).optional(),\n \n /**\n * Production safety configuration\n * Applied when environment is 'staging' or 'production'\n */\n productionSafety: z.object({\n /**\n * Validate plugin health before completing reload\n */\n healthValidation: z.boolean().default(true)\n .describe('Run health checks after reload before accepting traffic'),\n \n /**\n * Automatically rollback to previous version on reload failure\n */\n rollbackOnFailure: z.boolean().default(true)\n .describe('Auto-rollback if reloaded plugin fails health check'),\n \n /**\n * Maximum time to wait for health validation after reload (ms)\n */\n healthTimeout: z.number().int().min(1000).default(30000)\n .describe('Health check timeout after reload in ms'),\n \n /**\n * Drain active connections before reload\n */\n drainConnections: z.boolean().default(true)\n .describe('Gracefully drain active requests before reloading'),\n \n /**\n * Maximum time to wait for connection draining (ms)\n */\n drainTimeout: z.number().int().min(0).default(15000)\n .describe('Max wait time for connection draining in ms'),\n \n /**\n * Maximum number of concurrent plugin reloads\n */\n maxConcurrentReloads: z.number().int().min(1).default(1)\n .describe('Limit concurrent reloads to prevent system instability'),\n \n /**\n * Minimum interval between reloads of the same plugin (ms)\n */\n minReloadInterval: z.number().int().min(1000).default(5000)\n .describe('Cooldown period between reloads of the same plugin'),\n }).optional(),\n}).describe('Plugin hot reload configuration');\n\n/**\n * Plugin Caching Configuration\n * Configures caching strategy for faster subsequent loads\n */\nexport const PluginCachingSchema = z.object({\n /**\n * Enable caching\n */\n enabled: z.boolean().default(true),\n \n /**\n * Cache storage type\n */\n storage: z.enum([\n 'memory', // In-memory cache (fastest, not persistent)\n 'disk', // Disk cache (persistent)\n 'indexeddb', // Browser IndexedDB (persistent, browser only)\n 'hybrid', // Memory + Disk hybrid\n ]).default('memory'),\n \n /**\n * Cache key strategy\n */\n keyStrategy: z.enum([\n 'version', // Cache by plugin version\n 'hash', // Cache by content hash\n 'timestamp', // Cache by last modified timestamp\n ]).default('version'),\n \n /**\n * Cache TTL in seconds\n */\n ttl: z.number().int().min(0).optional().describe('Time to live in seconds (0 = infinite)'),\n \n /**\n * Maximum cache size in MB\n */\n maxSize: z.number().int().min(1).optional().describe('Max cache size in MB'),\n \n /**\n * Cache invalidation triggers\n */\n invalidateOn: z.array(z.enum([\n 'version-change',\n 'dependency-change',\n 'manual',\n 'error',\n ])).optional(),\n \n /**\n * Compression\n */\n compression: z.object({\n enabled: z.boolean().default(false),\n algorithm: z.enum(['gzip', 'brotli', 'deflate']).default('gzip'),\n }).optional(),\n}).describe('Plugin caching configuration');\n\n/**\n * Plugin Sandboxing Configuration\n * Security isolation for plugins with configurable scope.\n * \n * Supports isolation beyond automation scripts: any plugin can be sandboxed\n * with process-level isolation and inter-plugin communication (IPC).\n */\nexport const PluginSandboxingSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(false),\n \n /**\n * Isolation scope - which plugins are subject to sandboxing\n */\n scope: z.enum([\n 'automation-only', // Sandbox automation/scripting plugins only (current behavior)\n 'untrusted-only', // Sandbox plugins below a trust threshold\n 'all-plugins', // Sandbox all plugins (maximum isolation)\n ]).default('automation-only').describe('Which plugins are subject to isolation'),\n \n /**\n * Sandbox isolation level\n */\n isolationLevel: z.enum([\n 'none', // No isolation\n 'process', // Separate process (Node.js worker threads)\n 'vm', // VM context isolation\n 'iframe', // iframe isolation (browser)\n 'web-worker', // Web Worker (browser)\n ]).default('none'),\n \n /**\n * Allowed capabilities\n */\n allowedCapabilities: z.array(z.string()).optional().describe('List of allowed capability IDs'),\n \n /**\n * Resource quotas\n */\n resourceQuotas: z.object({\n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(1).optional(),\n \n /**\n * Maximum CPU time in milliseconds\n */\n maxCpuTimeMs: z.number().int().min(100).optional(),\n \n /**\n * Maximum number of file descriptors\n */\n maxFileDescriptors: z.number().int().min(1).optional(),\n \n /**\n * Maximum network bandwidth in KB/s\n */\n maxNetworkKBps: z.number().int().min(1).optional(),\n }).optional(),\n \n /**\n * Permissions\n */\n permissions: z.object({\n /**\n * Allowed API access\n */\n allowedAPIs: z.array(z.string()).optional(),\n \n /**\n * Allowed file system paths\n */\n allowedPaths: z.array(z.string()).optional(),\n \n /**\n * Allowed network endpoints\n */\n allowedEndpoints: z.array(z.string()).optional(),\n \n /**\n * Allowed environment variables\n */\n allowedEnvVars: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Inter-Plugin Communication (IPC) configuration\n * Enables isolated plugins to communicate with the kernel and other plugins\n */\n ipc: z.object({\n /**\n * Enable IPC for sandboxed plugins\n */\n enabled: z.boolean().default(true)\n .describe('Allow sandboxed plugins to communicate via IPC'),\n \n /**\n * IPC transport mechanism\n */\n transport: z.enum([\n 'message-port', // MessagePort (worker threads / Web Workers)\n 'unix-socket', // Unix domain sockets (process isolation)\n 'tcp', // TCP sockets (container isolation)\n 'memory', // Shared memory channel (in-process VM)\n ]).default('message-port')\n .describe('IPC transport for cross-boundary communication'),\n \n /**\n * Maximum message size in bytes\n */\n maxMessageSize: z.number().int().min(1024).default(1048576)\n .describe('Maximum IPC message size in bytes (default 1MB)'),\n \n /**\n * Message timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000)\n .describe('IPC message response timeout in ms'),\n \n /**\n * Allowed service calls through IPC\n */\n allowedServices: z.array(z.string()).optional()\n .describe('Service names the sandboxed plugin may invoke via IPC'),\n }).optional(),\n}).describe('Plugin sandboxing configuration');\n\n/**\n * Plugin Performance Monitoring Configuration\n * Telemetry and performance tracking\n */\nexport const PluginPerformanceMonitoringSchema = z.object({\n /**\n * Enable performance monitoring\n */\n enabled: z.boolean().default(false),\n \n /**\n * Metrics to collect\n */\n metrics: z.array(z.enum([\n 'load-time',\n 'init-time',\n 'memory-usage',\n 'cpu-usage',\n 'api-calls',\n 'error-rate',\n 'cache-hit-rate',\n ])).optional(),\n \n /**\n * Sampling rate (0-1, where 1 = 100%)\n */\n samplingRate: z.number().min(0).max(1).default(1),\n \n /**\n * Reporting interval in seconds\n */\n reportingInterval: z.number().int().min(1).default(60),\n \n /**\n * Performance budget thresholds\n */\n budgets: z.object({\n /**\n * Maximum load time in milliseconds\n */\n maxLoadTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum init time in milliseconds\n */\n maxInitTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(0).optional(),\n }).optional(),\n \n /**\n * Action on budget violation\n */\n onBudgetViolation: z.enum(['warn', 'error', 'ignore']).default('warn'),\n}).describe('Plugin performance monitoring configuration');\n\n/**\n * Complete Plugin Loading Configuration\n * Combines all loading-related configurations\n */\nexport const PluginLoadingConfigSchema = z.object({\n /**\n * Loading strategy\n */\n strategy: PluginLoadingStrategySchema.default('lazy'),\n \n /**\n * Preloading configuration\n */\n preload: PluginPreloadConfigSchema.optional(),\n \n /**\n * Code splitting configuration\n */\n codeSplitting: PluginCodeSplittingSchema.optional(),\n \n /**\n * Dynamic import configuration\n */\n dynamicImport: PluginDynamicImportSchema.optional(),\n \n /**\n * Initialization configuration\n */\n initialization: PluginInitializationSchema.optional(),\n \n /**\n * Dependency resolution configuration\n */\n dependencyResolution: PluginDependencyResolutionSchema.optional(),\n \n /**\n * Hot reload configuration (development and production)\n */\n hotReload: PluginHotReloadSchema.optional(),\n \n /**\n * Caching configuration\n */\n caching: PluginCachingSchema.optional(),\n \n /**\n * Sandboxing configuration\n */\n sandboxing: PluginSandboxingSchema.optional(),\n \n /**\n * Performance monitoring\n */\n monitoring: PluginPerformanceMonitoringSchema.optional(),\n}).describe('Complete plugin loading configuration');\n\n/**\n * Plugin Loading Event\n * Emitted during plugin loading lifecycle\n */\nexport const PluginLoadingEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'load-started',\n 'load-completed',\n 'load-failed',\n 'init-started',\n 'init-completed',\n 'init-failed',\n 'preload-started',\n 'preload-completed',\n 'cache-hit',\n 'cache-miss',\n 'hot-reload',\n 'dynamic-load', // Plugin loaded at runtime\n 'dynamic-unload', // Plugin unloaded at runtime\n 'dynamic-discover', // Plugin discovered via registry\n ]),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Timestamp\n */\n timestamp: z.number().int().min(0),\n \n /**\n * Duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Error if event represents a failure\n */\n error: z.object({\n message: z.string(),\n code: z.string().optional(),\n stack: z.string().optional(),\n }).optional(),\n}).describe('Plugin loading lifecycle event');\n\n/**\n * Plugin Loading State\n * Tracks the current loading state of a plugin\n */\nexport const PluginLoadingStateSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current state\n */\n state: z.enum([\n 'pending', // Not yet loaded\n 'loading', // Currently loading\n 'loaded', // Code loaded, not initialized\n 'initializing', // Currently initializing\n 'ready', // Fully initialized and ready\n 'failed', // Failed to load or initialize\n 'reloading', // Hot reloading in progress\n 'unloading', // Being unloaded at runtime\n 'unloaded', // Successfully unloaded (dynamic loading)\n ]),\n \n /**\n * Load progress (0-100)\n */\n progress: z.number().min(0).max(100).default(0),\n \n /**\n * Loading start time\n */\n startedAt: z.number().int().min(0).optional(),\n \n /**\n * Loading completion time\n */\n completedAt: z.number().int().min(0).optional(),\n \n /**\n * Last error\n */\n lastError: z.string().optional(),\n \n /**\n * Retry count\n */\n retryCount: z.number().int().min(0).default(0),\n}).describe('Plugin loading state');\n\n// Export types\nexport type PluginLoadingStrategy = z.infer;\nexport type PluginPreloadConfig = z.infer;\nexport type PluginCodeSplitting = z.infer;\nexport type PluginDynamicImport = z.infer;\nexport type PluginInitialization = z.infer;\nexport type PluginDependencyResolution = z.infer;\nexport type PluginHotReload = z.infer;\nexport type PluginCaching = z.infer;\nexport type PluginSandboxing = z.infer;\nexport type PluginPerformanceMonitoring = z.infer;\nexport type PluginLoadingConfig = z.infer;\nexport type PluginLoadingEvent = z.infer;\nexport type PluginLoadingState = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// Service method interfaces use z.function() instead of z.any() for type safety.\n// Generic data fields use z.unknown() for type safety.\nexport const PluginContextSchema = z.object({\n ql: z.object({\n object: z.function().describe('Get object handle for method chaining'),\n query: z.function().describe('Execute a query'),\n }).passthrough().describe('ObjectQL Engine Interface'),\n\n os: z.object({\n getCurrentUser: z.function().describe('Get the current authenticated user'),\n getConfig: z.function().describe('Get platform configuration'),\n }).passthrough().describe('ObjectStack Kernel Interface'),\n\n logger: z.object({\n debug: z.function().describe('Log debug message'),\n info: z.function().describe('Log info message'),\n warn: z.function().describe('Log warning message'),\n error: z.function().describe('Log error message'),\n }).passthrough().describe('Logger Interface'),\n\n storage: z.object({\n get: z.function().describe('Get a value from storage'),\n set: z.function().describe('Set a value in storage'),\n delete: z.function().describe('Delete a value from storage'),\n }).passthrough().describe('Storage Interface'),\n\n i18n: z.object({\n t: z.function().describe('Translate a key'),\n getLocale: z.function().describe('Get current locale'),\n }).passthrough().describe('Internationalization Interface'),\n\n metadata: z.record(z.string(), z.unknown()),\n events: z.record(z.string(), z.unknown()),\n \n app: z.object({\n router: z.object({\n get: z.function().describe('Register GET route handler'),\n post: z.function().describe('Register POST route handler'),\n use: z.function().describe('Register middleware'),\n }).passthrough()\n }).passthrough().describe('App Framework Interface'),\n\n drivers: z.object({\n register: z.function().describe('Register a driver'),\n }).passthrough().describe('Driver Registry'),\n});\n\nexport type PluginContextData = z.infer;\nexport type PluginContext = PluginContextData;\n\n/**\n * Upgrade Context Schema\n *\n * Provides version migration context to the `onUpgrade` lifecycle hook.\n * Enables developers to write conditional migration logic based on\n * the previous and new versions.\n */\nexport const UpgradeContextSchema = z.object({\n /** Version before upgrade */\n previousVersion: z.string().describe('Version before upgrade'),\n\n /** Version after upgrade */\n newVersion: z.string().describe('Version after upgrade'),\n\n /** Whether this is a major version bump */\n isMajorUpgrade: z.boolean().describe('Whether this is a major version bump'),\n\n /** Metadata snapshot before upgrade (for migration logic) */\n previousMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Metadata snapshot before upgrade'),\n}).describe('Version migration context for onUpgrade hook');\n\nexport type UpgradeContext = z.infer;\n\nexport const PluginLifecycleSchema = z.object({\n onInstall: z.function().optional().describe('Called when plugin is installed'),\n \n onEnable: z.function().optional().describe('Called when plugin is enabled'),\n \n onDisable: z.function().optional().describe('Called when plugin is disabled'),\n \n onUninstall: z.function().optional().describe('Called when plugin is uninstalled'),\n \n onUpgrade: z.function().optional().describe('Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade'),\n});\n\nexport type PluginLifecycleHooks = z.infer;\n\n/**\n * Shared Plugin Types\n * These are the specialized plugin types common between Manifest (Package) and Plugin (Runtime).\n */\nexport const CORE_PLUGIN_TYPES = [\n 'ui', // Frontend: Serves static assets/SPA (e.g. Console, Studio)\n 'driver', // Connectivity: Database or Storage adapters (e.g. SQL, S3)\n 'server', // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL)\n 'app', // Business: Vertical Solution Bundle (Metadata + Logic)\n 'theme', // Appearance: UI Overrides & CSS Variables\n 'agent', // AI: Autonomous Agent & Tool Definitions\n 'objectql' // Core: ObjectQL Engine Data Provider\n] as const;\n\nexport const PluginSchema = PluginLifecycleSchema.extend({\n id: z.string().min(1).optional().describe('Unique Plugin ID (e.g. com.example.crm)'),\n type: z.enum([\n 'standard', // Default: General purpose backend logic (Service, Hook, etc.)\n ...CORE_PLUGIN_TYPES\n ]).default('standard').optional().describe('Plugin Type categorization for runtime behavior'),\n \n staticPath: z.string().optional().describe('Absolute path to static assets (Required for type=\"ui-plugin\")'),\n slug: z.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type=\"ui-plugin\")'),\n default: z.boolean().optional().describe('Serve at root path (Only one \"ui-plugin\" can be default)'),\n \n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic Version'),\n description: z.string().optional(),\n author: z.string().optional(),\n homepage: z.string().url().optional(),\n});\n\nexport type PluginDefinition = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data Import Strategy\n * Defines how the engine handles existing records.\n */\nexport const DatasetMode = z.enum([\n 'insert', // Try to insert, fail on duplicate\n 'update', // Only update found records, ignore new\n 'upsert', // Create new or Update existing (Standard)\n 'replace', // Delete ALL records in object then insert (Dangerous - use for cache tables)\n 'ignore' // Try to insert, silently skip duplicates\n]);\n\n/**\n * Dataset Schema (Seed Data / Fixtures)\n * \n * Standardized format for transporting data.\n * Used for:\n * 1. System Bootstrapping (Admin accounts, Standard Roles)\n * 2. Reference Data (Countries, Currencies)\n * 3. Demo/Test Data\n */\nexport const DatasetSchema = z.object({\n /** \n * Target Object \n * The machine name of the object to populate.\n */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target Object Name'),\n\n /** \n * Idempotency Key (The \"Upsert\" Key)\n * The field used to check if a record already exists.\n * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'.\n * Standard: 'id' is rarely used for portable seed data — prefer natural keys.\n */\n externalId: z.string().default('name').describe('Field match for uniqueness check'),\n\n /** \n * Import Strategy\n */\n mode: DatasetMode.default('upsert').describe('Conflict resolution strategy'),\n\n /**\n * Environment Scope\n * - 'all': Always load\n * - 'dev': Only for development/demo\n * - 'test': Only for CI/CD tests\n */\n env: z.array(z.enum(['prod', 'dev', 'test'])).default(['prod', 'dev', 'test']).describe('Applicable environments'),\n\n /** \n * The Payload\n * Array of raw JSON objects matching the Object Schema.\n */\n records: z.array(z.record(z.string(), z.unknown())).describe('Data records'),\n});\n\n/** Parsed/output type — all defaults are applied (env, mode, externalId always present) */\nexport type Dataset = z.infer;\n\n/** Input type — fields with defaults (env, mode, externalId) are optional */\nexport type DatasetInput = z.input;\n\nexport type DatasetImportMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\nimport { PluginLoadingConfigSchema } from './plugin-loading.zod';\nimport { CORE_PLUGIN_TYPES } from './plugin.zod';\nimport { DatasetSchema } from '../data/dataset.zod';\n\n/**\n * Schema for the ObjectStack Manifest.\n * This defines the structure of a package configuration in the ObjectStack ecosystem.\n * All packages (apps, plugins, drivers, modules) must conform to this schema.\n * \n * @example App Package\n * ```yaml\n * id: com.acme.crm\n * version: 1.0.0\n * type: app\n * name: Acme CRM\n * description: Customer Relationship Management system\n * permissions:\n * - system.user.read\n * - system.object.create\n * objects:\n * - \"./src/objects/*.object.yml\"\n * ```\n */\nexport const ManifestSchema = z.object({\n /** \n * Unique package identifier using reverse domain notation.\n * Must be unique across the entire ecosystem.\n * \n * @example \"com.steedos.crm\"\n * @example \"org.apache.superset\"\n */\n id: z.string().describe('Unique package identifier (reverse domain style)'),\n \n /**\n * Short namespace identifier for metadata scoping.\n * Used as a prefix for objects and other metadata to prevent naming collisions\n * across packages from different vendors.\n * \n * Rules:\n * - 2-20 characters, lowercase letters, digits, and underscores only.\n * - Must be unique within a running instance.\n * - Platform-reserved namespaces (no prefix applied): \"base\", \"system\".\n * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator).\n * \n * @example \"crm\" → objects become crm__account, crm__deal\n * @example \"todo\" → objects become todo__task\n * @example \"base\" → objects keep short name (platform reserved)\n */\n namespace: z.string()\n .regex(/^[a-z][a-z0-9_]{1,19}$/, 'Namespace must be 2-20 chars, lowercase alphanumeric + underscore')\n .optional()\n .describe('Short namespace identifier for metadata scoping (e.g. \"crm\", \"todo\")'),\n \n /** \n * Package version following semantic versioning (major.minor.patch).\n * \n * @example \"1.0.0\"\n * @example \"2.1.0-beta.1\"\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Package version (semantic versioning)'),\n \n /** \n * Type of the package in the ObjectStack ecosystem.\n * - plugin: General-purpose functionality extension (Runtime: standard)\n * - app: Business application package\n * - driver: Connectivity adapter\n * - server: Protocol gateway (Hono, GraphQL)\n * - ui: Frontend package (Static/SPA)\n * - theme: UI Theme\n * - agent: AI Agent\n * - module: Reusable code library/shared module\n * - objectql: Core engine\n * - adapter: Host adapter (Express, Fastify)\n */\n type: z.enum([\n 'plugin', \n ...CORE_PLUGIN_TYPES,\n 'module', \n 'gateway', // Deprecated: use 'server'\n 'adapter'\n ]).describe('Type of package'),\n \n /** \n * Human-readable name of the package.\n * Displayed in the UI for users.\n * \n * @example \"Project Management\"\n */\n name: z.string().describe('Human-readable package name'),\n \n /** \n * Brief description of the package functionality.\n * Displayed in the marketplace and plugin manager.\n */\n description: z.string().optional().describe('Package description'),\n \n /** \n * Array of permission strings that the package requires.\n * These form the \"Scope\" requested by the package at installation.\n * \n * @example [\"system.user.read\", \"system.data.write\"]\n */\n permissions: z.array(z.string()).optional().describe('Array of required permission strings'),\n \n /** \n * Glob patterns specifying ObjectQL schemas files.\n * Matches `*.object.yml` or `*.object.ts` files to load business objects.\n * \n * @example [\"./src/objects/*.object.yml\"]\n */\n objects: z.array(z.string()).optional().describe('Glob patterns for ObjectQL schemas files'),\n\n /**\n * Defines system level DataSources.\n * Matches `*.datasource.yml` files.\n * \n * @example [\"./src/datasources/*.datasource.mongo.yml\"]\n */\n datasources: z.array(z.string()).optional().describe('Glob patterns for Datasource definitions'),\n\n /**\n * Package Dependencies.\n * Map of package IDs to version requirements.\n * \n * @example { \"@steedos/plugin-auth\": \"^2.0.0\" }\n */\n dependencies: z.record(z.string(), z.string()).optional().describe('Package dependencies'),\n\n /**\n * Plugin Configuration Schema.\n * Defines the settings this plugin exposes to the user via UI/ENV.\n * Uses a simplified JSON Schema format.\n * \n * @example\n * {\n * \"title\": \"Stripe Config\",\n * \"properties\": {\n * \"apiKey\": { \"type\": \"string\", \"secret\": true },\n * \"currency\": { \"type\": \"string\", \"default\": \"USD\" }\n * }\n * }\n */\n configuration: z.object({\n title: z.string().optional(),\n properties: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']).describe('Data type of the setting'),\n default: z.unknown().optional().describe('Default value'),\n description: z.string().optional().describe('Tooltip description'),\n required: z.boolean().optional().describe('Is this setting required?'),\n secret: z.boolean().optional().describe('If true, value is encrypted/masked (e.g. API Keys)'),\n enum: z.array(z.string()).optional().describe('Allowed values for select inputs'),\n })).describe('Map of configuration keys to their definitions')\n }).optional().describe('Plugin configuration settings'),\n\n /**\n * Contribution Points (VS Code Style).\n * formalized way to extend the platform capabilities.\n */\n contributes: z.object({\n /**\n * Register new Metadata Kinds (CRDs).\n * Enables the system to parse and validate new file types.\n * Example: Registering a BI plugin to handle *.report.ts\n */\n kinds: z.array(z.object({\n id: z.string().describe('The generic identifier of the kind (e.g., \"sys.bi.report\")'),\n globs: z.array(z.string()).describe('File patterns to watch (e.g., [\"**/*.report.ts\"])'),\n description: z.string().optional().describe('Description of what this kind represents'),\n })).optional().describe('New Metadata Types to recognize'),\n\n /**\n * Register System Hooks.\n * Declares that this plugin listens to specific system events.\n */\n events: z.array(z.string()).optional().describe('Events this plugin listens to'),\n\n /**\n * Register UI Menus.\n */\n menus: z.record(z.string(), z.array(z.object({\n id: z.string(),\n label: z.string(),\n command: z.string().optional(),\n }))).optional().describe('UI Menu contributions'),\n\n /**\n * Register Custom Themes.\n */\n themes: z.array(z.object({\n id: z.string(),\n label: z.string(),\n path: z.string(),\n })).optional().describe('Theme contributions'),\n\n /**\n * Register Translations.\n * Path to translation files (e.g. \"locales/en.json\").\n */\n translations: z.array(z.object({\n locale: z.string(),\n path: z.string(),\n })).optional().describe('Translation resources'),\n\n /**\n * Register Server Actions.\n * Invocable functions exposed to Flows or API.\n */\n actions: z.array(z.object({\n name: z.string().describe('Unique action name'),\n label: z.string().optional(),\n description: z.string().optional(),\n input: z.unknown().optional().describe('Input validation schema'),\n output: z.unknown().optional().describe('Output schema'),\n })).optional().describe('Exposed server actions'),\n\n /**\n * Register Storage Drivers.\n * Enables connecting to new types of datasources.\n */\n drivers: z.array(z.object({\n id: z.string().describe('Driver unique identifier (e.g. \"postgres\", \"mongo\")'),\n label: z.string().describe('Human readable name'),\n description: z.string().optional(),\n })).optional().describe('Driver contributions'),\n\n /**\n * Register Custom Field Types.\n * Extends the data model with new widget types.\n */\n fieldTypes: z.array(z.object({\n name: z.string().describe('Unique field type name (e.g. \"vector\")'),\n label: z.string().describe('Display label'),\n description: z.string().optional(),\n })).optional().describe('Field Type contributions'),\n \n /**\n * Register Custom Query Operators/Functions.\n * Extends ObjectQL with new functions (e.g. distance()).\n */\n functions: z.array(z.object({\n name: z.string().describe('Function name (e.g. \"distance\")'),\n description: z.string().optional(),\n args: z.array(z.string()).optional().describe('Argument types'),\n returnType: z.string().optional(),\n })).optional().describe('Query Function contributions'),\n\n /**\n * Register API Route Namespaces.\n * Declares the API endpoints this plugin provides to the HttpDispatcher.\n * The kernel routes matching prefixes to this plugin's handler.\n * \n * @example\n * routes: [\n * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] }\n * ]\n */\n routes: z.array(z.object({\n /** URL path prefix (e.g. \"/api/v1/ai\") */\n prefix: z.string().regex(/^\\//).describe('API path prefix'),\n /** Service name this plugin provides */\n service: z.string().describe('Service name this plugin provides'),\n /** Protocol method names implemented */\n methods: z.array(z.string()).optional()\n .describe('Protocol method names implemented (e.g. [\"aiNlq\", \"aiChat\"])'),\n })).optional().describe('API route contributions to HttpDispatcher'),\n\n /**\n * Register CLI Commands.\n * Allows plugins to extend the ObjectStack CLI with custom commands.\n * Each command entry declares metadata; the actual Commander.js command\n * is resolved at runtime by importing the plugin's module.\n * \n * The plugin package must export a `commands` array of Commander.js `Command` instances\n * from its main entry point or from the path specified in `module`.\n * \n * @example\n * ```yaml\n * commands:\n * - name: marketplace\n * description: \"Manage marketplace apps\"\n * module: \"./cli\" # optional, defaults to package main\n * - name: deploy\n * description: \"Deploy to cloud\"\n * ```\n */\n commands: z.array(z.object({\n /** CLI command name (e.g., \"marketplace\", \"deploy\"). Must be a valid CLI identifier. */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n /** Brief description shown in `os --help` */\n description: z.string().optional().describe('Command description for help text'),\n /** \n * Optional module path (relative to package root) that exports the Commander.js commands.\n * If omitted, the CLI will import from the package's main entry point.\n * The module must export a `commands` array of Commander.js `Command` instances,\n * or a single `Command` instance as default export.\n */\n module: z.string().optional().describe('Module path exporting Commander.js commands'),\n })).optional().describe('CLI command contributions'),\n }).optional().describe('Platform contributions'),\n\n /** \n * Initial data seeding configuration.\n * Defines default records to be inserted when the package is installed.\n * \n * Uses the standard DatasetSchema which supports idempotent upsert via\n * `externalId`, environment scoping via `env`, and multiple conflict\n * resolution modes.\n * \n * @deprecated Prefer using the top-level `data` field on the Stack Definition\n * (defineStack({ data: [...] })) for better visibility and metadata registration.\n * This field is retained for backward compatibility with manifest-only packages.\n */\n data: z.array(DatasetSchema).optional().describe('Initial seed data (prefer top-level data field)'),\n\n /**\n * Plugin Capability Manifest.\n * Declares protocols implemented, interfaces provided, dependencies, and extension points.\n * This enables plugin interoperability and automatic discovery.\n */\n capabilities: PluginCapabilityManifestSchema.optional()\n .describe('Plugin capability declarations for interoperability'),\n\n /** \n * Extension points contributed by this package.\n * Allows packages to extend UI components, add functionality, etc.\n */\n extensions: z.record(z.string(), z.unknown()).optional().describe('Extension points and contributions'),\n\n /**\n * Plugin Loading Configuration.\n * Configures how the plugin is loaded, initialized, and managed at runtime.\n * Includes strategies for lazy loading, code splitting, caching, and hot reload.\n */\n loading: PluginLoadingConfigSchema.optional()\n .describe('Plugin loading and runtime behavior configuration'),\n\n /**\n * Platform Compatibility Requirements.\n * Specifies the minimum ObjectStack platform version required to run this package.\n * Used at install time to prevent incompatible packages from being installed.\n *\n * @example\n * ```yaml\n * engine:\n * objectstack: \">=3.0.0\"\n * ```\n */\n engine: z.object({\n /** ObjectStack platform version requirement (SemVer range) */\n objectstack: z.string()\n .regex(/^[><=~^]*\\d+\\.\\d+\\.\\d+/)\n .describe('ObjectStack platform version requirement (SemVer range, e.g. \">=3.0.0\")'),\n }).optional().describe('Platform compatibility requirements'),\n});\n\n/**\n * TypeScript type inferred from the ManifestSchema.\n * Use this type for type-safe manifest handling in TypeScript code.\n */\nexport type ObjectStackManifest = z.infer;\nexport type ObjectStackManifestInput = z.input;\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dependency Resolution Protocol\n *\n * Defines schemas for runtime dependency resolution when installing,\n * upgrading, or managing packages. Provides a standardized way to\n * express dependency conflicts, resolution results, and installation order.\n *\n * ## Architecture Alignment\n * - **npm**: Dependency tree resolution with conflict detection\n * - **Helm**: Dependency management with version constraints\n * - **Salesforce**: Package dependency validation at install time\n *\n * ## Resolution Flow\n * ```\n * 1. Parse manifest.dependencies (SemVer ranges)\n * 2. Check installed packages registry\n * 3. Resolve each dependency → satisfied | needs_install | needs_upgrade | conflict\n * 4. Detect circular dependencies\n * 5. Compute topological install order\n * 6. Return resolution result with required actions\n * ```\n */\n\n// ==========================================\n// Dependency Resolution Status\n// ==========================================\n\n/**\n * Resolution status for a single dependency.\n */\nexport const DependencyStatusEnum = z.enum([\n 'satisfied', // Already installed and version compatible\n 'needs_install', // Not installed, needs to be installed\n 'needs_upgrade', // Installed but version incompatible, needs upgrade\n 'conflict', // Conflicts with another package's dependency\n]).describe('Resolution status for a dependency');\n\nexport type DependencyStatus = z.infer;\n\n// ==========================================\n// Resolved Dependency\n// ==========================================\n\n/**\n * Single dependency resolution result.\n * Describes the state of one dependency after resolution.\n */\nexport const ResolvedDependencySchema = z.object({\n /** Package identifier of the dependency */\n packageId: z.string().describe('Dependency package identifier'),\n\n /** SemVer range required by the parent package */\n requiredRange: z.string().describe('SemVer range required (e.g. \"^2.0.0\")'),\n\n /** Actual version resolved (if available) */\n resolvedVersion: z.string().optional()\n .describe('Actual version resolved from registry'),\n\n /** Currently installed version (if any) */\n installedVersion: z.string().optional()\n .describe('Currently installed version'),\n\n /** Resolution status */\n status: DependencyStatusEnum.describe('Resolution status'),\n\n /** Conflict details (when status is \"conflict\") */\n conflictReason: z.string().optional()\n .describe('Explanation of the conflict'),\n}).describe('Resolution result for a single dependency');\n\nexport type ResolvedDependency = z.infer;\n\n// ==========================================\n// Required Action\n// ==========================================\n\n/**\n * An action required before installation can proceed.\n */\nexport const RequiredActionSchema = z.object({\n /** Type of action required */\n type: z.enum(['install', 'upgrade', 'confirm_conflict'])\n .describe('Type of action required'),\n\n /** Target package identifier */\n packageId: z.string().describe('Target package identifier'),\n\n /** Human-readable description of the action */\n description: z.string().describe('Human-readable action description'),\n}).describe('Action required before installation can proceed');\n\nexport type RequiredAction = z.infer;\n\n// ==========================================\n// Dependency Resolution Result\n// ==========================================\n\n/**\n * Complete dependency resolution result.\n * Aggregates all dependency statuses and computes installation feasibility.\n */\nexport const DependencyResolutionResultSchema = z.object({\n /** All dependencies and their resolution results */\n dependencies: z.array(ResolvedDependencySchema)\n .describe('Resolution result for each dependency'),\n\n /** Whether installation can proceed without conflicts */\n canProceed: z.boolean()\n .describe('Whether installation can proceed'),\n\n /** Actions that require user confirmation or system execution */\n requiredActions: z.array(RequiredActionSchema)\n .describe('Actions required before proceeding'),\n\n /** Topologically sorted package IDs for installation order */\n installOrder: z.array(z.string())\n .describe('Topologically sorted package IDs for installation'),\n\n /** Detected circular dependency chains */\n circularDependencies: z.array(z.array(z.string())).optional()\n .describe('Circular dependency chains detected (e.g. [[\"A\", \"B\", \"A\"]])'),\n}).describe('Complete dependency resolution result');\n\nexport type DependencyResolutionResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\nimport { DependencyResolutionResultSchema } from './dependency-resolution.zod';\n\n/**\n * # Package Registry Protocol\n * \n * Defines the runtime state and lifecycle operations for installed packages.\n * \n * ## Key Distinction: Package vs App\n * - **Package (Manifest)**: The unit of installation — a deployable artifact containing\n * metadata (objects, actions, flows, etc.) and optionally one or more Apps.\n * - **App (AppSchema)**: A UI navigation shell defined inside a package.\n * \n * A package may contain:\n * - Zero apps (pure functionality plugin, e.g. a storage driver)\n * - One app (typical business application)\n * - Multiple apps (suite of applications)\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Packages with install/uninstall lifecycle\n * - **VS Code**: Extension marketplace with enable/disable per-workspace\n * - **Kubernetes**: Helm charts with release state tracking\n * - **npm**: Package registry with install/uninstall/version management\n */\n\n// ==========================================\n// Package Status & Lifecycle\n// ==========================================\n\n/**\n * Package installation status.\n */\nexport const PackageStatusEnum = z.enum([\n 'installed', // Successfully installed and enabled\n 'disabled', // Installed but disabled (metadata not active)\n 'installing', // Installation in progress\n 'upgrading', // Upgrade in progress\n 'uninstalling', // Removal in progress\n 'error', // Installation or runtime error\n]).describe('Package installation status');\nexport type PackageStatus = z.infer;\n\n/**\n * Installed Package Schema\n * \n * Wraps a ManifestSchema with runtime lifecycle state.\n * This is the \"row\" in the installed packages table.\n */\nexport const InstalledPackageSchema = z.object({\n /** \n * The full package manifest (source of truth for package definition).\n */\n manifest: ManifestSchema.describe('Full package manifest'),\n\n /**\n * Current lifecycle status.\n */\n status: PackageStatusEnum.default('installed')\n .describe('Package state: installed, disabled, installing, upgrading, uninstalling, or error'),\n\n /**\n * Whether the package is currently enabled (active).\n * When disabled, the package's metadata is not loaded into the registry.\n */\n enabled: z.boolean().default(true)\n .describe('Whether the package is currently enabled'),\n\n /**\n * ISO 8601 timestamp of when the package was installed.\n */\n installedAt: z.string().datetime().optional()\n .describe('Installation timestamp'),\n\n /**\n * ISO 8601 timestamp of last update.\n */\n updatedAt: z.string().datetime().optional()\n .describe('Last update timestamp'),\n\n /**\n * The currently installed version string.\n * Mirrors manifest.version for quick access without parsing the full manifest.\n */\n installedVersion: z.string().optional()\n .describe('Currently installed version for quick access'),\n\n /**\n * The previously installed version (before last upgrade).\n * Useful for rollback and upgrade tracking.\n */\n previousVersion: z.string().optional()\n .describe('Version before the last upgrade'),\n\n /**\n * ISO 8601 timestamp of when the package was last enabled/disabled.\n */\n statusChangedAt: z.string().datetime().optional()\n .describe('Status change timestamp'),\n\n /**\n * Error message if status is 'error'.\n */\n errorMessage: z.string().optional()\n .describe('Error message when status is error'),\n\n /**\n * Configuration values set by the user for this package.\n * Keys correspond to the package's `configuration.properties`.\n */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided configuration settings'),\n\n /**\n * Upgrade history for this package.\n * Records each version migration with status and optional log.\n */\n upgradeHistory: z.array(z.object({\n /** Previous version before upgrade */\n fromVersion: z.string().describe('Version before upgrade'),\n /** New version after upgrade */\n toVersion: z.string().describe('Version after upgrade'),\n /** Timestamp of the upgrade */\n upgradedAt: z.string().datetime().describe('Upgrade timestamp'),\n /** Outcome of the upgrade */\n status: z.enum(['success', 'failed', 'rolled_back']).describe('Upgrade outcome'),\n /** Migration log entries */\n migrationLog: z.array(z.string()).optional().describe('Migration step logs'),\n })).optional().describe('Version upgrade history'),\n\n /**\n * Namespaces registered by this package.\n * Tracks which namespace prefixes are occupied by this package.\n */\n registeredNamespaces: z.array(z.string()).optional()\n .describe('Namespace prefixes registered by this package'),\n}).describe('Installed package with runtime lifecycle state');\nexport type InstalledPackage = z.infer;\n\n// ==========================================\n// Namespace Registry\n// ==========================================\n\n/**\n * Namespace Registry Entry\n * Tracks namespace ownership within the platform instance.\n */\nexport const NamespaceRegistryEntrySchema = z.object({\n /** Namespace prefix */\n namespace: z.string().describe('Namespace prefix'),\n\n /** Package that owns this namespace */\n packageId: z.string().describe('Owning package ID'),\n\n /** Registration timestamp */\n registeredAt: z.string().datetime().describe('Registration timestamp'),\n\n /** Namespace status */\n status: z.enum(['active', 'disabled', 'reserved'])\n .describe('Namespace status'),\n}).describe('Namespace ownership entry in the registry');\n\nexport type NamespaceRegistryEntry = z.infer;\n\n/**\n * Namespace Conflict Error\n * Describes a namespace collision detected during package installation.\n */\nexport const NamespaceConflictErrorSchema = z.object({\n /** Error type discriminator */\n type: z.literal('namespace_conflict').describe('Error type'),\n\n /** Namespace that was requested */\n requestedNamespace: z.string().describe('Requested namespace'),\n\n /** ID of the package that already owns the namespace */\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n\n /** Name of the conflicting package */\n conflictingPackageName: z.string().describe('Conflicting package display name'),\n\n /** Suggested alternative namespace */\n suggestion: z.string().optional()\n .describe('Suggested alternative namespace'),\n}).describe('Namespace collision error during installation');\n\nexport type NamespaceConflictError = z.infer;\n\n// ==========================================\n// Package Registry Request/Response Schemas\n// ==========================================\n\n/**\n * List Packages Request\n */\nexport const ListPackagesRequestSchema = z.object({\n /** Filter by status */\n status: PackageStatusEnum.optional().describe('Filter by package status'),\n /** Filter by package type */\n type: ManifestSchema.shape.type.optional().describe('Filter by package type'),\n /** Filter by enabled state */\n enabled: z.boolean().optional().describe('Filter by enabled state'),\n}).describe('List packages request');\nexport type ListPackagesRequest = z.infer;\n\n/**\n * List Packages Response\n */\nexport const ListPackagesResponseSchema = z.object({\n packages: z.array(InstalledPackageSchema).describe('List of installed packages'),\n total: z.number().describe('Total package count'),\n}).describe('List packages response');\nexport type ListPackagesResponse = z.infer;\n\n/**\n * Get Package Request\n */\nexport const GetPackageRequestSchema = z.object({\n /** Package ID (reverse domain identifier from manifest) */\n id: z.string().describe('Package identifier'),\n}).describe('Get package request');\nexport type GetPackageRequest = z.infer;\n\n/**\n * Get Package Response\n */\nexport const GetPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Package details'),\n}).describe('Get package response');\nexport type GetPackageResponse = z.infer;\n\n/**\n * Install Package Request\n * \n * Accepts a full manifest to install. In a production system,\n * this might also accept a package ID to fetch from a marketplace.\n */\nexport const InstallPackageRequestSchema = z.object({\n /** The package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n /** Optional: user-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n /** Whether to enable immediately after install (default: true) */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n /**\n * Current platform version for compatibility checking.\n * When provided, the system compares this against the package's\n * `engine.objectstack` requirement to verify compatibility.\n */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n}).describe('Install package request');\nexport type InstallPackageRequest = z.infer;\n\n/**\n * Install Package Response\n */\nexport const InstallPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n message: z.string().optional().describe('Installation status message'),\n /** Dependency resolution result (when dependencies were analyzed) */\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result from install analysis'),\n}).describe('Install package response');\nexport type InstallPackageResponse = z.infer;\n\n/**\n * Uninstall Package Request\n */\nexport const UninstallPackageRequestSchema = z.object({\n /** Package ID to uninstall */\n id: z.string().describe('Package ID to uninstall'),\n}).describe('Uninstall package request');\nexport type UninstallPackageRequest = z.infer;\n\n/**\n * Uninstall Package Response\n */\nexport const UninstallPackageResponseSchema = z.object({\n id: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n}).describe('Uninstall package response');\nexport type UninstallPackageResponse = z.infer;\n\n/**\n * Enable Package Request\n */\nexport const EnablePackageRequestSchema = z.object({\n /** Package ID to enable */\n id: z.string().describe('Package ID to enable'),\n}).describe('Enable package request');\nexport type EnablePackageRequest = z.infer;\n\n/**\n * Enable Package Response\n */\nexport const EnablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Enabled package details'),\n message: z.string().optional().describe('Enable status message'),\n}).describe('Enable package response');\nexport type EnablePackageResponse = z.infer;\n\n/**\n * Disable Package Request\n */\nexport const DisablePackageRequestSchema = z.object({\n /** Package ID to disable */\n id: z.string().describe('Package ID to disable'),\n}).describe('Disable package request');\nexport type DisablePackageRequest = z.infer;\n\n/**\n * Disable Package Response\n */\nexport const DisablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Disabled package details'),\n message: z.string().optional().describe('Disable status message'),\n}).describe('Disable package response');\nexport type DisablePackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ViewSchema } from '../ui/view.zod';\nimport { DiscoverySchema } from './discovery.zod';\nimport { BatchUpdateRequestSchema, BatchUpdateResponseSchema, BatchOptionsSchema } from './batch.zod';\nimport { MetadataCacheRequestSchema, MetadataCacheResponseSchema } from './http-cache.zod';\nimport { QuerySchema } from '../data/query.zod';\nimport { \n AnalyticsQueryRequestSchema, \n AnalyticsResultResponseSchema, \n GetAnalyticsMetaRequestSchema, \n AnalyticsMetadataResponseSchema \n} from './analytics.zod';\nimport { RealtimePresenceSchema, TransportProtocol } from './realtime.zod';\nimport { ObjectPermissionSchema, FieldPermissionSchema } from '../security/permission.zod';\nimport { WorkflowRuleSchema } from '../automation/workflow.zod';\nimport { TranslationDataSchema } from '../system/translation.zod';\nimport type {\n GetFeedRequest,\n GetFeedResponse,\n CreateFeedItemRequest,\n CreateFeedItemResponse,\n UpdateFeedItemRequest,\n UpdateFeedItemResponse,\n DeleteFeedItemRequest,\n DeleteFeedItemResponse,\n AddReactionRequest,\n AddReactionResponse,\n RemoveReactionRequest,\n RemoveReactionResponse,\n PinFeedItemRequest,\n PinFeedItemResponse,\n UnpinFeedItemRequest,\n UnpinFeedItemResponse,\n StarFeedItemRequest,\n StarFeedItemResponse,\n UnstarFeedItemRequest,\n UnstarFeedItemResponse,\n SearchFeedRequest,\n SearchFeedResponse,\n GetChangelogRequest,\n GetChangelogResponse,\n SubscribeRequest,\n SubscribeResponse,\n FeedUnsubscribeRequest,\n UnsubscribeResponse,\n} from './feed-api.zod';\nimport {\n ListPackagesRequestSchema,\n ListPackagesResponseSchema,\n GetPackageRequestSchema,\n GetPackageResponseSchema,\n InstallPackageRequestSchema,\n InstallPackageResponseSchema,\n UninstallPackageRequestSchema,\n UninstallPackageResponseSchema,\n EnablePackageRequestSchema,\n EnablePackageResponseSchema,\n DisablePackageRequestSchema,\n DisablePackageResponseSchema,\n} from '../kernel/package-registry.zod';\nimport type {\n ListPackagesRequest,\n ListPackagesResponse,\n GetPackageRequest,\n GetPackageResponse,\n InstallPackageRequest,\n InstallPackageResponse,\n UninstallPackageRequest,\n UninstallPackageResponse,\n EnablePackageRequest,\n EnablePackageResponse,\n DisablePackageRequest,\n DisablePackageResponse,\n InstalledPackage,\n PackageStatus,\n} from '../kernel/package-registry.zod';\n\nexport const AutomationTriggerRequestSchema = z.object({\n trigger: z.string(),\n payload: z.record(z.string(), z.unknown())\n});\n\nexport const AutomationTriggerResponseSchema = z.object({\n success: z.boolean(),\n jobId: z.string().optional(),\n result: z.unknown().optional()\n});\n\n/**\n * ObjectStack Protocol - Zod Schema Definitions\n * \n * Defines the runtime-validated contract for interacting with ObjectStack metadata and data.\n * Used by API adapters (HTTP, WebSocket, gRPC) to fetch data/metadata without knowing engine internals.\n * \n * This protocol enables:\n * - Runtime request/response validation at API gateway level\n * - Automatic API documentation generation\n * - Type-safe RPC communication between microservices\n * - Client SDK generation from schemas\n * \n * Architecture Alignment:\n * - Salesforce: REST API Request/Response schemas\n * - Kubernetes: API Resource schemas with runtime validation\n * - GraphQL: Schema-first API design\n */\n\n// ==========================================\n// Discovery & Metadata Operations\n// ==========================================\n\n/**\n * Get API Discovery Request\n * No parameters needed\n */\nexport const GetDiscoveryRequestSchema = z.object({});\n\n/**\n * Get API Discovery Response\n * Derived from DiscoverySchema (single source of truth) for protocol-level use.\n * \n * All fields from DiscoverySchema are available but made optional (except `version`)\n * to support progressive disclosure and backward compatibility with existing clients.\n * \n * - `routes` provides a flat endpoint map for client routing.\n * - `services` is the single source of truth for service availability.\n * - `apiName` is kept as an optional alias for `name` for backward compatibility.\n * \n * @see DiscoverySchema in ./discovery.zod.ts — the canonical definition.\n */\nexport const GetDiscoveryResponseSchema = DiscoverySchema\n .partial()\n .required({ version: true })\n .extend({\n /** @deprecated Use `name` instead. Kept for backward compatibility. */\n apiName: z.string().optional().describe('API name (deprecated — use name)'),\n });\n\n/**\n * Get Metadata Types Request\n */\nexport const GetMetaTypesRequestSchema = z.object({});\n\n/**\n * Get Metadata Types Response\n */\nexport const GetMetaTypesResponseSchema = z.object({\n types: z.array(z.string()).describe('Available metadata type names (e.g., \"object\", \"plugin\", \"view\")'),\n});\n\n/**\n * Get Metadata Items Request\n * Get all items of a specific metadata type\n */\nexport const GetMetaItemsRequestSchema = z.object({\n type: z.string().describe('Metadata type name (e.g., \"object\", \"plugin\")'),\n packageId: z.string().optional().describe('Optional package ID to filter items by'),\n});\n\n/**\n * Get Metadata Items Response\n */\nexport const GetMetaItemsResponseSchema = z.object({\n type: z.string().describe('Metadata type name'),\n items: z.array(z.unknown()).describe('Array of metadata items'),\n});\n\n/**\n * Get Metadata Item Request\n * Get a specific metadata item by type and name\n */\nexport const GetMetaItemRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name (snake_case identifier)'),\n packageId: z.string().optional().describe('Optional package ID to filter items by'),\n});\n\n/**\n * Get Metadata Item Response\n */\nexport const GetMetaItemResponseSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n item: z.unknown().describe('Metadata item definition'),\n});\n\n/**\n * Save Metadata Item Request\n * Create or update a metadata item\n */\nexport const SaveMetaItemRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n item: z.unknown().describe('Metadata item definition'),\n});\n\n/**\n * Save Metadata Item Response\n */\nexport const SaveMetaItemResponseSchema = z.object({\n success: z.boolean(),\n message: z.string().optional(),\n});\n\n/**\n * Get Metadata Item with Cache Request\n * Get a specific metadata item with HTTP cache validation support\n */\nexport const GetMetaItemCachedRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n cacheRequest: MetadataCacheRequestSchema.optional().describe('Cache validation parameters'),\n});\n\n/**\n * Get Metadata Item with Cache Response\n * Uses MetadataCacheResponse from http-cache.zod.ts\n */\nexport const GetMetaItemCachedResponseSchema = MetadataCacheResponseSchema;\n\n/**\n * Get UI View Request\n * Resolves the appropriate UI view for an object based on context.\n * Unlike getMetaItem, this does not require a specific View ID.\n */\nexport const GetUiViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n type: z.enum(['list', 'form']).describe('View type'),\n});\n\n/**\n * Get UI View Response\n */\nexport const GetUiViewResponseSchema = ViewSchema;\n\n// ==========================================\n// Data Operations\n// ==========================================\n\n/**\n * Find Data Request\n * Defines a query to retrieve records from a specific object.\n * Supports filtering, sorting, pagination, and field selection.\n * \n * @example\n * {\n * \"object\": \"customers\",\n * \"query\": {\n * \"where\": { \"status\": \"active\", \"revenue\": { \"$gt\": 10000 } },\n * \"orderBy\": [{ \"field\": \"name\", \"order\": \"desc\" }],\n * \"limit\": 10\n * }\n * }\n */\nexport const FindDataRequestSchema = z.object({\n object: z.string().describe('The unique machine name of the object to query (e.g. \"account\").'),\n query: QuerySchema.optional().describe('Structured query definition (filter, sort, select, pagination).'),\n});\n\n/**\n * Find Data Response\n * Returns a list of records matching the query criteria.\n */\nexport const FindDataResponseSchema = z.object({\n object: z.string().describe('The object name for the returned records.'),\n records: z.array(z.record(z.string(), z.unknown())).describe('The list of matching records.'),\n total: z.number().optional().describe('Total number of records matching the filter (if requested).'),\n nextCursor: z.string().optional().describe('Cursor for the next page of results (cursor-based pagination).'),\n hasMore: z.boolean().optional().describe('True if there are more records available (pagination).'),\n});\n\n/**\n * HTTP Find Query Parameters\n * \n * Canonical HTTP query parameter names for GET /data/:object list endpoints.\n * The canonical filter parameter is `filter` (singular). The plural `filters` is\n * accepted for backward compatibility but `filter` is the standard going forward.\n * \n * This schema defines the allowlisted query parameters for HTTP GET list requests.\n * Server-side parsers (protocol.ts) should accept both `filter` and `filters` and\n * normalize to `filter` (singular) internally.\n * \n * @example\n * GET /api/v1/data/contacts?filter={\"status\":\"active\"}&select=name,email&top=10&sort=name\n */\nexport const HttpFindQueryParamsSchema = z.object({\n /** @canonical Singular form — the standard going forward. JSON string of filter expression or AST. */\n filter: z.string().optional().describe('JSON-encoded filter expression (canonical, singular).'),\n /** @deprecated Use `filter` (singular). Accepted for backward compatibility. */\n filters: z.string().optional().describe('JSON-encoded filter expression (deprecated plural alias).'),\n select: z.string().optional().describe('Comma-separated list of fields to retrieve.'),\n sort: z.string().optional().describe('Sort expression (e.g. \"name asc,created_at desc\" or \"-created_at\").'),\n orderBy: z.string().optional().describe('Alias for sort (OData compatibility).'),\n top: z.coerce.number().optional().describe('Max records to return (limit).'),\n skip: z.coerce.number().optional().describe('Records to skip (offset).'),\n expand: z.string().optional().describe(\n 'Comma-separated list of lookup/master_detail field names to expand. '\n + 'Resolved to populate array and passed to the engine for batch $in expansion.'\n ),\n search: z.string().optional().describe('Full-text search query.'),\n distinct: z.coerce.boolean().optional().describe('SELECT DISTINCT flag.'),\n count: z.coerce.boolean().optional().describe('Include total count in response.'),\n});\n\n/**\n * Get Data Request\n * Retrieval of a single record by its unique identifier.\n * Only `select` and `expand` are permitted as additional query parameters.\n * All other query parameters should be discarded to prevent parameter pollution.\n * \n * @example\n * {\n * \"object\": \"contracts\",\n * \"id\": \"cnt_123456\",\n * \"select\": [\"name\", \"status\", \"amount\"],\n * \"expand\": [\"owner\", \"account\"]\n * }\n */\nexport const GetDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The unique record identifier (primary key).'),\n select: z.array(z.string()).optional().describe('Fields to include in the response (allowlisted query param).'),\n expand: z.array(z.string()).optional().describe(\n 'Lookup/master_detail field names to expand. '\n + 'The engine resolves these via batch $in queries, replacing foreign key IDs with full objects.'\n ),\n});\n\n/**\n * Get Data Response\n */\nexport const GetDataResponseSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The record ID.'),\n record: z.record(z.string(), z.unknown()).describe('The complete record data.'),\n});\n\n/**\n * Create Data Request\n * Creation of a new record.\n * \n * @example\n * {\n * \"object\": \"leads\",\n * \"data\": {\n * \"first_name\": \"John\",\n * \"last_name\": \"Doe\",\n * \"company\": \"Acme Inc\"\n * }\n * }\n */\nexport const CreateDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n data: z.record(z.string(), z.unknown()).describe('The dictionary of field values to insert.'),\n});\n\n/**\n * Create Data Response\n */\nexport const CreateDataResponseSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The ID of the newly created record.'),\n record: z.record(z.string(), z.unknown()).describe('The created record, including server-generated fields (created_at, owner).'),\n});\n\n/**\n * Update Data Request\n * Modification of an existing record.\n * \n * @example\n * {\n * \"object\": \"tasks\",\n * \"id\": \"tsk_001\",\n * \"data\": {\n * \"status\": \"completed\",\n * \"percent_complete\": 100\n * }\n * }\n */\nexport const UpdateDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The ID of the record to update.'),\n data: z.record(z.string(), z.unknown()).describe('The fields to update (partial update).'),\n});\n\n/**\n * Update Data Response\n */\nexport const UpdateDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Updated record ID'),\n record: z.record(z.string(), z.unknown()).describe('Updated record'),\n});\n\n/**\n * Delete Data Request\n */\nexport const DeleteDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Record ID to delete'),\n});\n\n/**\n * Delete Data Response\n */\nexport const DeleteDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Deleted record ID'),\n success: z.boolean().describe('Whether deletion succeeded'),\n});\n\n// ==========================================\n// Batch Operations\n// ==========================================\n\n/**\n * Batch Data Request\n */\nexport const BatchDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n request: BatchUpdateRequestSchema.describe('Batch operation request'),\n});\n\n/**\n * Batch Data Response\n * Uses BatchUpdateResponse from batch.zod.ts\n */\nexport const BatchDataResponseSchema = BatchUpdateResponseSchema;\n\n/**\n * Create Many Data Request\n */\nexport const CreateManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.record(z.string(), z.unknown())).describe('Array of records to create'),\n});\n\n/**\n * Create Many Data Response\n */\nexport const CreateManyDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.record(z.string(), z.unknown())).describe('Created records'),\n count: z.number().describe('Number of records created'),\n});\n\n/**\n * Update Many Data Request\n */\nexport const UpdateManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.object({\n id: z.string().describe('Record ID'),\n data: z.record(z.string(), z.unknown()).describe('Fields to update'),\n })).describe('Array of updates'),\n options: BatchOptionsSchema.optional().describe('Update options'),\n});\n\n/**\n * Update Many Data Response\n * Uses BatchUpdateResponse for consistency\n */\nexport const UpdateManyDataResponseSchema = BatchUpdateResponseSchema;\n\n/**\n * Delete Many Data Request\n */\nexport const DeleteManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n ids: z.array(z.string()).describe('Array of record IDs to delete'),\n options: BatchOptionsSchema.optional().describe('Delete options'),\n});\n\n/**\n * Delete Many Data Response\n */\nexport const DeleteManyDataResponseSchema = BatchUpdateResponseSchema;\n\n// ==========================================\n// Package Management Operations\n// ==========================================\n\n/**\n * Re-export Package Management Request/Response schemas from kernel.\n * These define the contract for package lifecycle management:\n * - List installed packages (with filters)\n * - Get a specific package by ID\n * - Install a new package (from manifest)\n * - Uninstall a package\n * - Enable/Disable a package\n * \n * Key distinction: Package (ManifestSchema) is the unit of installation.\n * An App (AppSchema) is a UI navigation entity within a package.\n * A package may contain 0, 1, or many apps.\n */\nexport {\n ListPackagesRequestSchema,\n ListPackagesResponseSchema,\n GetPackageRequestSchema,\n GetPackageResponseSchema,\n InstallPackageRequestSchema,\n InstallPackageResponseSchema,\n UninstallPackageRequestSchema,\n UninstallPackageResponseSchema,\n EnablePackageRequestSchema,\n EnablePackageResponseSchema,\n DisablePackageRequestSchema,\n DisablePackageResponseSchema,\n};\n\n// ==========================================\n// View Management Operations\n// ==========================================\n\nexport const ListViewsRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n type: z.enum(['list', 'form']).optional().describe('Filter by view type'),\n});\n\nexport const ListViewsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n views: z.array(ViewSchema).describe('Array of view definitions'),\n});\n\nexport const GetViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier'),\n});\n\nexport const GetViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n view: ViewSchema.describe('View definition'),\n});\n\nexport const CreateViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n data: ViewSchema.describe('View definition to create'),\n});\n\nexport const CreateViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Created view identifier'),\n view: ViewSchema.describe('Created view definition'),\n});\n\nexport const UpdateViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier'),\n data: ViewSchema.partial().describe('Partial view data to update'),\n});\n\nexport const UpdateViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Updated view identifier'),\n view: ViewSchema.describe('Updated view definition'),\n});\n\nexport const DeleteViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier to delete'),\n});\n\nexport const DeleteViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Deleted view identifier'),\n success: z.boolean().describe('Whether deletion succeeded'),\n});\n\n// ==========================================\n// Permission Operations\n// ==========================================\n\nexport const CheckPermissionRequestSchema = z.object({\n object: z.string().describe('Object name to check permissions for'),\n action: z.enum(['create', 'read', 'edit', 'delete', 'transfer', 'restore', 'purge']).describe('Action to check'),\n recordId: z.string().optional().describe('Specific record ID (for record-level checks)'),\n field: z.string().optional().describe('Specific field name (for field-level checks)'),\n});\n\nexport const CheckPermissionResponseSchema = z.object({\n allowed: z.boolean().describe('Whether the action is permitted'),\n reason: z.string().optional().describe('Reason if denied'),\n});\n\nexport const GetObjectPermissionsRequestSchema = z.object({\n object: z.string().describe('Object name to get permissions for'),\n});\n\nexport const GetObjectPermissionsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n permissions: ObjectPermissionSchema.describe('Object-level permissions'),\n fieldPermissions: z.record(z.string(), FieldPermissionSchema).optional().describe('Field-level permissions keyed by field name'),\n});\n\nexport const GetEffectivePermissionsRequestSchema = z.object({});\n\nexport const GetEffectivePermissionsResponseSchema = z.object({\n objects: z.record(z.string(), ObjectPermissionSchema).describe('Effective object permissions keyed by object name'),\n systemPermissions: z.array(z.string()).describe('Effective system-level permissions'),\n});\n\n// ==========================================\n// Workflow Operations\n// ==========================================\n\nexport const GetWorkflowConfigRequestSchema = z.object({\n object: z.string().describe('Object name to get workflow config for'),\n});\n\nexport const GetWorkflowConfigResponseSchema = z.object({\n object: z.string().describe('Object name'),\n workflows: z.array(WorkflowRuleSchema).describe('Active workflow rules for this object'),\n});\n\nexport const WorkflowStateSchema = z.object({\n currentState: z.string().describe('Current workflow state name'),\n availableTransitions: z.array(z.object({\n name: z.string().describe('Transition name'),\n targetState: z.string().describe('Target state after transition'),\n label: z.string().optional().describe('Display label'),\n requiresApproval: z.boolean().default(false).describe('Whether transition requires approval'),\n })).describe('Available transitions from current state'),\n history: z.array(z.object({\n fromState: z.string().describe('Previous state'),\n toState: z.string().describe('New state'),\n action: z.string().describe('Action that triggered the transition'),\n userId: z.string().describe('User who performed the action'),\n timestamp: z.string().datetime().describe('When the transition occurred'),\n comment: z.string().optional().describe('Optional comment'),\n })).optional().describe('State transition history'),\n});\n\nexport const GetWorkflowStateRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID to get workflow state for'),\n});\n\nexport const GetWorkflowStateResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n state: WorkflowStateSchema.describe('Current workflow state and available transitions'),\n});\n\nexport const WorkflowTransitionRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n transition: z.string().describe('Transition name to execute'),\n comment: z.string().optional().describe('Optional comment for the transition'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data for the transition'),\n});\n\nexport const WorkflowTransitionResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the transition succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after transition'),\n});\n\nexport const WorkflowApproveRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n comment: z.string().optional().describe('Approval comment'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data'),\n});\n\nexport const WorkflowApproveResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the approval succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after approval'),\n});\n\nexport const WorkflowRejectRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n reason: z.string().describe('Rejection reason'),\n comment: z.string().optional().describe('Additional comment'),\n});\n\nexport const WorkflowRejectResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the rejection succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after rejection'),\n});\n\n// ==========================================\n// Realtime Operations\n// ==========================================\n\nexport const RealtimeConnectRequestSchema = z.object({\n transport: TransportProtocol.optional().describe('Preferred transport protocol'),\n channels: z.array(z.string()).optional().describe('Channels to subscribe to on connect'),\n token: z.string().optional().describe('Authentication token'),\n});\n\nexport const RealtimeConnectResponseSchema = z.object({\n connectionId: z.string().describe('Unique connection identifier'),\n transport: TransportProtocol.describe('Negotiated transport protocol'),\n url: z.string().optional().describe('WebSocket/SSE endpoint URL'),\n});\n\nexport const RealtimeDisconnectRequestSchema = z.object({\n connectionId: z.string().optional().describe('Connection ID to disconnect'),\n});\n\nexport const RealtimeDisconnectResponseSchema = z.object({\n success: z.boolean().describe('Whether disconnection succeeded'),\n});\n\nexport const RealtimeSubscribeRequestSchema = z.object({\n channel: z.string().describe('Channel name to subscribe to'),\n events: z.array(z.string()).optional().describe('Specific event types to listen for'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Event filter criteria'),\n});\n\nexport const RealtimeSubscribeResponseSchema = z.object({\n subscriptionId: z.string().describe('Unique subscription identifier'),\n channel: z.string().describe('Subscribed channel name'),\n});\n\nexport const RealtimeUnsubscribeRequestSchema = z.object({\n subscriptionId: z.string().describe('Subscription ID to cancel'),\n});\n\nexport const RealtimeUnsubscribeResponseSchema = z.object({\n success: z.boolean().describe('Whether unsubscription succeeded'),\n});\n\nexport const SetPresenceRequestSchema = z.object({\n channel: z.string().describe('Channel to set presence in'),\n state: RealtimePresenceSchema.describe('Presence state to set'),\n});\n\nexport const SetPresenceResponseSchema = z.object({\n success: z.boolean().describe('Whether presence was set'),\n});\n\nexport const GetPresenceRequestSchema = z.object({\n channel: z.string().describe('Channel to get presence for'),\n});\n\nexport const GetPresenceResponseSchema = z.object({\n channel: z.string().describe('Channel name'),\n members: z.array(RealtimePresenceSchema).describe('Active members and their presence state'),\n});\n\n// ==========================================\n// Notification Operations\n// ==========================================\n\nexport const RegisterDeviceRequestSchema = z.object({\n token: z.string().describe('Device push notification token'),\n platform: z.enum(['ios', 'android', 'web']).describe('Device platform'),\n deviceId: z.string().optional().describe('Unique device identifier'),\n name: z.string().optional().describe('Device friendly name'),\n});\n\nexport const RegisterDeviceResponseSchema = z.object({\n deviceId: z.string().describe('Registered device ID'),\n success: z.boolean().describe('Whether registration succeeded'),\n});\n\nexport const UnregisterDeviceRequestSchema = z.object({\n deviceId: z.string().describe('Device ID to unregister'),\n});\n\nexport const UnregisterDeviceResponseSchema = z.object({\n success: z.boolean().describe('Whether unregistration succeeded'),\n});\n\nexport const NotificationPreferencesSchema = z.object({\n email: z.boolean().default(true).describe('Receive email notifications'),\n push: z.boolean().default(true).describe('Receive push notifications'),\n inApp: z.boolean().default(true).describe('Receive in-app notifications'),\n digest: z.enum(['none', 'daily', 'weekly']).default('none').describe('Email digest frequency'),\n channels: z.record(z.string(), z.object({\n enabled: z.boolean().default(true).describe('Whether this channel is enabled'),\n email: z.boolean().optional().describe('Override email setting'),\n push: z.boolean().optional().describe('Override push setting'),\n })).optional().describe('Per-channel notification preferences'),\n});\n\nexport const GetNotificationPreferencesRequestSchema = z.object({});\n\nexport const GetNotificationPreferencesResponseSchema = z.object({\n preferences: NotificationPreferencesSchema.describe('Current notification preferences'),\n});\n\nexport const UpdateNotificationPreferencesRequestSchema = z.object({\n preferences: NotificationPreferencesSchema.partial().describe('Preferences to update'),\n});\n\nexport const UpdateNotificationPreferencesResponseSchema = z.object({\n preferences: NotificationPreferencesSchema.describe('Updated notification preferences'),\n});\n\nexport const NotificationSchema = z.object({\n id: z.string().describe('Notification ID'),\n type: z.string().describe('Notification type'),\n title: z.string().describe('Notification title'),\n body: z.string().describe('Notification body text'),\n read: z.boolean().default(false).describe('Whether notification has been read'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional notification data'),\n actionUrl: z.string().optional().describe('URL to navigate to when clicked'),\n createdAt: z.string().datetime().describe('When notification was created'),\n});\n\nexport const ListNotificationsRequestSchema = z.object({\n read: z.boolean().optional().describe('Filter by read status'),\n type: z.string().optional().describe('Filter by notification type'),\n limit: z.number().default(20).describe('Maximum number of notifications to return'),\n cursor: z.string().optional().describe('Pagination cursor'),\n});\n\nexport const ListNotificationsResponseSchema = z.object({\n notifications: z.array(NotificationSchema).describe('List of notifications'),\n unreadCount: z.number().describe('Total number of unread notifications'),\n cursor: z.string().optional().describe('Next page cursor'),\n});\n\nexport const MarkNotificationsReadRequestSchema = z.object({\n ids: z.array(z.string()).describe('Notification IDs to mark as read'),\n});\n\nexport const MarkNotificationsReadResponseSchema = z.object({\n success: z.boolean().describe('Whether the operation succeeded'),\n readCount: z.number().describe('Number of notifications marked as read'),\n});\n\nexport const MarkAllNotificationsReadRequestSchema = z.object({});\n\nexport const MarkAllNotificationsReadResponseSchema = z.object({\n success: z.boolean().describe('Whether the operation succeeded'),\n readCount: z.number().describe('Number of notifications marked as read'),\n});\n\n// ==========================================\n// AI Operations\n// ==========================================\n\nexport const AiNlqRequestSchema = z.object({\n query: z.string().describe('Natural language query string'),\n object: z.string().optional().describe('Target object context'),\n conversationId: z.string().optional().describe('Conversation ID for multi-turn queries'),\n});\n\nexport const AiNlqResponseSchema = z.object({\n query: z.unknown().describe('Generated structured query (AST)'),\n explanation: z.string().optional().describe('Human-readable explanation of the query'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n suggestions: z.array(z.string()).optional().describe('Suggested follow-up queries'),\n});\n\n// AiChatRequestSchema and AiChatResponseSchema have been removed.\n// The AI chat wire protocol is now fully aligned with the Vercel AI SDK (`ai`).\n// Frontend consumers should use `@ai-sdk/react/useChat` directly.\n// See: https://ai-sdk.dev/docs\n\nexport const AiSuggestRequestSchema = z.object({\n object: z.string().describe('Object name for context'),\n field: z.string().optional().describe('Field to suggest values for'),\n recordId: z.string().optional().describe('Record ID for context'),\n partial: z.string().optional().describe('Partial input for completion'),\n});\n\nexport const AiSuggestResponseSchema = z.object({\n suggestions: z.array(z.object({\n value: z.unknown().describe('Suggested value'),\n label: z.string().describe('Display label'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n reason: z.string().optional().describe('Reason for this suggestion'),\n })).describe('Suggested values'),\n});\n\nexport const AiInsightsRequestSchema = z.object({\n object: z.string().describe('Object name to analyze'),\n recordId: z.string().optional().describe('Specific record to analyze'),\n type: z.enum(['summary', 'trends', 'anomalies', 'recommendations']).optional().describe('Type of insight'),\n});\n\nexport const AiInsightsResponseSchema = z.object({\n insights: z.array(z.object({\n type: z.string().describe('Insight type'),\n title: z.string().describe('Insight title'),\n description: z.string().describe('Detailed description'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n data: z.record(z.string(), z.unknown()).optional().describe('Supporting data'),\n })).describe('Generated insights'),\n});\n\n// ==========================================\n// i18n Operations\n// ==========================================\n\nexport const GetLocalesRequestSchema = z.object({});\n\nexport const GetLocalesResponseSchema = z.object({\n locales: z.array(z.object({\n code: z.string().describe('BCP-47 locale code (e.g., en-US, zh-CN)'),\n label: z.string().describe('Display name of the locale'),\n isDefault: z.boolean().default(false).describe('Whether this is the default locale'),\n })).describe('Available locales'),\n});\n\nexport const GetTranslationsRequestSchema = z.object({\n locale: z.string().describe('BCP-47 locale code'),\n namespace: z.string().optional().describe('Translation namespace (e.g., objects, apps, messages)'),\n keys: z.array(z.string()).optional().describe('Specific translation keys to fetch'),\n});\n\nexport const GetTranslationsResponseSchema = z.object({\n locale: z.string().describe('Locale code'),\n translations: TranslationDataSchema.describe('Translation data'),\n});\n\nexport const GetFieldLabelsRequestSchema = z.object({\n object: z.string().describe('Object name'),\n locale: z.string().describe('BCP-47 locale code'),\n});\n\nexport const GetFieldLabelsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n locale: z.string().describe('Locale code'),\n labels: z.record(z.string(), z.object({\n label: z.string().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n options: z.record(z.string(), z.string()).optional().describe('Translated option labels'),\n })).describe('Field labels keyed by field name'),\n});\n\n// ==========================================\n// Protocol Interface Schema\n// ==========================================\n\n/**\n * ObjectStack Protocol Contract\n * \n * This schema defines the complete API contract as a Zod schema.\n * Unlike the old TypeScript interface, this provides runtime validation\n * and can be used for:\n * - API Gateway validation\n * - RPC call validation\n * - Client SDK generation\n * - API documentation generation\n * \n * Each method is defined with its request and response schemas.\n */\nexport const ObjectStackProtocolSchema = z.object({\n // Discovery & Metadata\n getDiscovery: z.function()\n .describe('Get API discovery information'),\n\n getMetaTypes: z.function()\n .describe('Get available metadata types'),\n\n getMetaItems: z.function()\n .describe('Get all items of a metadata type'),\n\n getMetaItem: z.function()\n .describe('Get a specific metadata item'),\n saveMetaItem: z.function()\n .describe('Save metadata item'),\n getMetaItemCached: z.function()\n .describe('Get a metadata item with cache validation'),\n\n getUiView: z.function()\n .describe('Get UI view definition'),\n\n // Analytics Operations\n analyticsQuery: z.function()\n .describe('Execute analytics query'),\n\n getAnalyticsMeta: z.function()\n .describe('Get analytics metadata (cubes)'),\n\n // Automation Operations\n triggerAutomation: z.function()\n .describe('Trigger an automation flow or script'),\n\n // Package Management Operations\n listPackages: z.function()\n .describe('List installed packages with optional filters'),\n\n getPackage: z.function()\n .describe('Get a specific installed package by ID'),\n\n installPackage: z.function()\n .describe('Install a new package from manifest'),\n\n uninstallPackage: z.function()\n .describe('Uninstall a package by ID'),\n\n enablePackage: z.function()\n .describe('Enable a disabled package'),\n\n disablePackage: z.function()\n .describe('Disable an installed package'),\n\n // Data Operations\n findData: z.function()\n .describe('Find data records'),\n\n getData: z.function()\n .describe('Get single data record'),\n\n createData: z.function()\n .describe('Create a data record'),\n\n updateData: z.function()\n .describe('Update a data record'),\n\n deleteData: z.function()\n .describe('Delete a data record'),\n\n // Batch Operations\n batchData: z.function()\n .describe('Perform batch operations'),\n\n createManyData: z.function()\n .describe('Create multiple records'),\n\n updateManyData: z.function()\n .describe('Update multiple records'),\n\n deleteManyData: z.function()\n .describe('Delete multiple records'),\n\n // View Management Operations\n listViews: z.function()\n .describe('List views for an object'),\n getView: z.function()\n .describe('Get a specific view'),\n createView: z.function()\n .describe('Create a new view'),\n updateView: z.function()\n .describe('Update an existing view'),\n deleteView: z.function()\n .describe('Delete a view'),\n\n // Permission Operations\n checkPermission: z.function()\n .describe('Check if an action is permitted'),\n getObjectPermissions: z.function()\n .describe('Get permissions for an object'),\n getEffectivePermissions: z.function()\n .describe('Get effective permissions for current user'),\n\n // Workflow Operations\n getWorkflowConfig: z.function()\n .describe('Get workflow configuration for an object'),\n getWorkflowState: z.function()\n .describe('Get workflow state for a record'),\n workflowTransition: z.function()\n .describe('Execute a workflow state transition'),\n workflowApprove: z.function()\n .describe('Approve a workflow step'),\n workflowReject: z.function()\n .describe('Reject a workflow step'),\n\n // Realtime Operations\n realtimeConnect: z.function()\n .describe('Establish realtime connection'),\n realtimeDisconnect: z.function()\n .describe('Close realtime connection'),\n realtimeSubscribe: z.function()\n .describe('Subscribe to a realtime channel'),\n realtimeUnsubscribe: z.function()\n .describe('Unsubscribe from a realtime channel'),\n setPresence: z.function()\n .describe('Set user presence state'),\n getPresence: z.function()\n .describe('Get channel presence information'),\n\n // Notification Operations\n registerDevice: z.function()\n .describe('Register a device for push notifications'),\n unregisterDevice: z.function()\n .describe('Unregister a device'),\n getNotificationPreferences: z.function()\n .describe('Get notification preferences'),\n updateNotificationPreferences: z.function()\n .describe('Update notification preferences'),\n listNotifications: z.function()\n .describe('List notifications'),\n markNotificationsRead: z.function()\n .describe('Mark specific notifications as read'),\n markAllNotificationsRead: z.function()\n .describe('Mark all notifications as read'),\n\n // AI Operations\n aiNlq: z.function()\n .describe('Natural language query'),\n aiChat: z.function()\n .describe('AI chat interaction'),\n aiSuggest: z.function()\n .describe('Get AI-powered suggestions'),\n aiInsights: z.function()\n .describe('Get AI-generated insights'),\n\n // i18n Operations\n getLocales: z.function()\n .describe('Get available locales'),\n getTranslations: z.function()\n .describe('Get translations for a locale'),\n getFieldLabels: z.function()\n .describe('Get translated field labels for an object'),\n\n // Feed Operations\n listFeed: z.function()\n .describe('List feed items for a record'),\n createFeedItem: z.function()\n .describe('Create a new feed item'),\n updateFeedItem: z.function()\n .describe('Update an existing feed item'),\n deleteFeedItem: z.function()\n .describe('Delete a feed item'),\n addReaction: z.function()\n .describe('Add an emoji reaction to a feed item'),\n removeReaction: z.function()\n .describe('Remove an emoji reaction from a feed item'),\n pinFeedItem: z.function()\n .describe('Pin a feed item'),\n unpinFeedItem: z.function()\n .describe('Unpin a feed item'),\n starFeedItem: z.function()\n .describe('Star a feed item'),\n unstarFeedItem: z.function()\n .describe('Unstar a feed item'),\n searchFeed: z.function()\n .describe('Search feed items'),\n getChangelog: z.function()\n .describe('Get field-level changelog for a record'),\n feedSubscribe: z.function()\n .describe('Subscribe to record notifications'),\n feedUnsubscribe: z.function()\n .describe('Unsubscribe from record notifications'),\n});\n\n/**\n * TypeScript Types\n * Derived from Zod schemas using z.infer\n */\nexport type GetDiscoveryRequest = z.infer;\nexport type GetDiscoveryResponse = z.infer;\nexport type GetMetaTypesRequest = z.infer;\nexport type GetMetaTypesResponse = z.infer;\nexport type GetMetaItemsRequest = z.infer;\nexport type GetMetaItemsResponse = z.infer;\nexport type GetMetaItemRequest = z.infer;\nexport type GetMetaItemResponse = z.infer;\nexport type SaveMetaItemRequest = z.infer;\nexport type SaveMetaItemResponse = z.infer;\nexport type GetMetaItemCachedRequest = z.infer;\nexport type GetMetaItemCachedResponse = z.infer;\nexport type GetUiViewRequest = z.infer;\nexport type GetUiViewResponse = z.infer;\n\ntype AnalyticsQueryRequest = z.infer;\ntype AnalyticsResultResponse = z.infer;\ntype GetAnalyticsMetaRequest = z.infer;\ntype GetAnalyticsMetaResponse = z.infer;\n\nexport type AutomationTriggerRequest = z.infer;\nexport type AutomationTriggerResponse = z.infer;\n\nexport type FindDataRequest = z.input;\nexport type FindDataResponse = z.infer;\nexport type GetDataRequest = z.input;\nexport type GetDataResponse = z.infer;\nexport type CreateDataRequest = z.input;\nexport type CreateDataResponse = z.infer;\nexport type UpdateDataRequest = z.input;\nexport type UpdateDataResponse = z.infer;\nexport type DeleteDataRequest = z.input;\nexport type DeleteDataResponse = z.infer;\n\nexport type BatchDataRequest = z.input;\nexport type BatchDataResponse = z.infer;\nexport type CreateManyDataRequest = z.input;\nexport type CreateManyDataResponse = z.infer;\nexport type UpdateManyDataRequest = z.input;\nexport type UpdateManyDataResponse = z.infer;\nexport type DeleteManyDataRequest = z.input;\nexport type DeleteManyDataResponse = z.infer;\n\n// View Management Types\nexport type ListViewsRequest = z.input;\nexport type ListViewsResponse = z.infer;\nexport type GetViewRequest = z.input;\nexport type GetViewResponse = z.infer;\nexport type CreateViewRequest = z.input;\nexport type CreateViewResponse = z.infer;\nexport type UpdateViewRequest = z.input;\nexport type UpdateViewResponse = z.infer;\nexport type DeleteViewRequest = z.input;\nexport type DeleteViewResponse = z.infer;\n\n// Permission Types\nexport type CheckPermissionRequest = z.input;\nexport type CheckPermissionResponse = z.infer;\nexport type GetObjectPermissionsRequest = z.input;\nexport type GetObjectPermissionsResponse = z.infer;\nexport type GetEffectivePermissionsRequest = z.input;\nexport type GetEffectivePermissionsResponse = z.infer;\n\n// Workflow Types\nexport type GetWorkflowConfigRequest = z.input;\nexport type GetWorkflowConfigResponse = z.infer;\nexport type WorkflowState = z.infer;\nexport type GetWorkflowStateRequest = z.input;\nexport type GetWorkflowStateResponse = z.infer;\nexport type WorkflowTransitionRequest = z.input;\nexport type WorkflowTransitionResponse = z.infer;\nexport type WorkflowApproveRequest = z.input;\nexport type WorkflowApproveResponse = z.infer;\nexport type WorkflowRejectRequest = z.input;\nexport type WorkflowRejectResponse = z.infer;\n\n// Realtime Types\nexport type RealtimeConnectRequest = z.input;\nexport type RealtimeConnectResponse = z.infer;\nexport type RealtimeDisconnectRequest = z.input;\nexport type RealtimeDisconnectResponse = z.infer;\nexport type RealtimeSubscribeRequest = z.input;\nexport type RealtimeSubscribeResponse = z.infer;\nexport type RealtimeUnsubscribeRequest = z.input;\nexport type RealtimeUnsubscribeResponse = z.infer;\nexport type SetPresenceRequest = z.input;\nexport type SetPresenceResponse = z.infer;\nexport type GetPresenceRequest = z.input;\nexport type GetPresenceResponse = z.infer;\n\n// Notification Types\nexport type RegisterDeviceRequest = z.input;\nexport type RegisterDeviceResponse = z.infer;\nexport type UnregisterDeviceRequest = z.input;\nexport type UnregisterDeviceResponse = z.infer;\nexport type NotificationPreferences = z.infer;\nexport type NotificationPreferencesInput = z.input;\nexport type GetNotificationPreferencesRequest = z.input;\nexport type GetNotificationPreferencesResponse = z.infer;\nexport type UpdateNotificationPreferencesRequest = z.input;\nexport type UpdateNotificationPreferencesResponse = z.infer;\nexport type Notification = z.infer;\nexport type NotificationInput = z.input;\nexport type ListNotificationsRequest = z.input;\nexport type ListNotificationsResponse = z.infer;\nexport type MarkNotificationsReadRequest = z.input;\nexport type MarkNotificationsReadResponse = z.infer;\nexport type MarkAllNotificationsReadRequest = z.input;\nexport type MarkAllNotificationsReadResponse = z.infer;\n\n// AI Types\nexport type AiNlqRequest = z.input;\nexport type AiNlqResponse = z.infer;\nexport type AiSuggestRequest = z.input;\nexport type AiSuggestResponse = z.infer;\nexport type AiInsightsRequest = z.input;\nexport type AiInsightsResponse = z.infer;\n\n// i18n Types\nexport type GetLocalesRequest = z.input;\nexport type GetLocalesResponse = z.infer;\nexport type GetTranslationsRequest = z.input;\nexport type GetTranslationsResponse = z.infer;\nexport type GetFieldLabelsRequest = z.input;\nexport type GetFieldLabelsResponse = z.infer;\n\n// Feed Types (re-exported from feed-api.zod.ts for convenience)\nexport type {\n GetFeedRequest,\n GetFeedResponse,\n CreateFeedItemRequest,\n CreateFeedItemResponse,\n UpdateFeedItemRequest,\n UpdateFeedItemResponse,\n DeleteFeedItemRequest,\n DeleteFeedItemResponse,\n AddReactionRequest,\n AddReactionResponse,\n RemoveReactionRequest,\n RemoveReactionResponse,\n PinFeedItemRequest,\n PinFeedItemResponse,\n UnpinFeedItemRequest,\n UnpinFeedItemResponse,\n StarFeedItemRequest,\n StarFeedItemResponse,\n UnstarFeedItemRequest,\n UnstarFeedItemResponse,\n SearchFeedRequest,\n SearchFeedResponse,\n GetChangelogRequest,\n GetChangelogResponse,\n SubscribeRequest,\n SubscribeResponse,\n FeedUnsubscribeRequest,\n UnsubscribeResponse,\n} from './feed-api.zod';\n\n// Package Management Types (re-exported from kernel for convenience)\nexport type { \n ListPackagesRequest,\n ListPackagesResponse,\n GetPackageRequest,\n GetPackageResponse,\n InstallPackageRequest,\n InstallPackageResponse,\n UninstallPackageRequest,\n UninstallPackageResponse,\n EnablePackageRequest,\n EnablePackageResponse,\n DisablePackageRequest,\n DisablePackageResponse,\n InstalledPackage,\n PackageStatus,\n};\n\n/**\n * Zod-inferred protocol type (for runtime validation only).\n * Use ObjectStackProtocol interface for implementation contracts.\n */\nexport type ObjectStackProtocolZod = z.infer;\n\n/**\n * ObjectStack Protocol Interface\n * \n * Properly typed interface for implementing the ObjectStack API protocol.\n * The Zod schema (ObjectStackProtocolSchema) is used for runtime validation,\n * while this interface provides compile-time type safety for implementations.\n */\nexport interface ObjectStackProtocol {\n // Discovery & Metadata (core)\n getDiscovery(request?: GetDiscoveryRequest): Promise;\n getMetaTypes(request?: GetMetaTypesRequest): Promise;\n getMetaItems(request: GetMetaItemsRequest): Promise;\n getMetaItem(request: GetMetaItemRequest): Promise;\n saveMetaItem(request: SaveMetaItemRequest): Promise;\n getMetaItemCached?(request: GetMetaItemCachedRequest): Promise;\n getUiView?(request: GetUiViewRequest): Promise;\n \n // Analytics (optional)\n analyticsQuery?(request: AnalyticsQueryRequest): Promise;\n getAnalyticsMeta?(request: GetAnalyticsMetaRequest): Promise;\n\n // Automation (optional)\n triggerAutomation?(request: AutomationTriggerRequest): Promise;\n\n // Package Management (optional)\n listPackages?(request: ListPackagesRequest): Promise;\n getPackage?(request: GetPackageRequest): Promise;\n installPackage?(request: InstallPackageRequest): Promise;\n uninstallPackage?(request: UninstallPackageRequest): Promise;\n enablePackage?(request: EnablePackageRequest): Promise;\n disablePackage?(request: DisablePackageRequest): Promise;\n\n // Data Operations (core)\n findData(request: FindDataRequest): Promise;\n getData(request: GetDataRequest): Promise;\n createData(request: CreateDataRequest): Promise;\n updateData(request: UpdateDataRequest): Promise;\n deleteData(request: DeleteDataRequest): Promise;\n \n // Batch Operations (optional)\n batchData?(request: BatchDataRequest): Promise;\n createManyData?(request: CreateManyDataRequest): Promise;\n updateManyData?(request: UpdateManyDataRequest): Promise;\n deleteManyData?(request: DeleteManyDataRequest): Promise;\n\n // View Management (optional)\n listViews?(request: ListViewsRequest): Promise;\n getView?(request: GetViewRequest): Promise;\n createView?(request: CreateViewRequest): Promise;\n updateView?(request: UpdateViewRequest): Promise;\n deleteView?(request: DeleteViewRequest): Promise;\n\n // Permissions (optional)\n checkPermission?(request: CheckPermissionRequest): Promise;\n getObjectPermissions?(request: GetObjectPermissionsRequest): Promise;\n getEffectivePermissions?(request: GetEffectivePermissionsRequest): Promise;\n\n // Workflows (optional)\n getWorkflowConfig?(request: GetWorkflowConfigRequest): Promise;\n getWorkflowState?(request: GetWorkflowStateRequest): Promise;\n workflowTransition?(request: WorkflowTransitionRequest): Promise;\n workflowApprove?(request: WorkflowApproveRequest): Promise;\n workflowReject?(request: WorkflowRejectRequest): Promise;\n\n // Realtime (optional)\n realtimeConnect?(request: RealtimeConnectRequest): Promise;\n realtimeDisconnect?(request: RealtimeDisconnectRequest): Promise;\n realtimeSubscribe?(request: RealtimeSubscribeRequest): Promise;\n realtimeUnsubscribe?(request: RealtimeUnsubscribeRequest): Promise;\n setPresence?(request: SetPresenceRequest): Promise;\n getPresence?(request: GetPresenceRequest): Promise;\n\n // Notifications (optional)\n registerDevice?(request: RegisterDeviceRequest): Promise;\n unregisterDevice?(request: UnregisterDeviceRequest): Promise;\n getNotificationPreferences?(request: GetNotificationPreferencesRequest): Promise;\n updateNotificationPreferences?(request: UpdateNotificationPreferencesRequest): Promise;\n listNotifications?(request: ListNotificationsRequest): Promise;\n markNotificationsRead?(request: MarkNotificationsReadRequest): Promise;\n markAllNotificationsRead?(request: MarkAllNotificationsReadRequest): Promise;\n\n // AI (optional — chat is now handled by Vercel AI SDK wire protocol)\n aiNlq?(request: AiNlqRequest): Promise;\n aiSuggest?(request: AiSuggestRequest): Promise;\n aiInsights?(request: AiInsightsRequest): Promise;\n\n // i18n (optional)\n getLocales?(request: GetLocalesRequest): Promise;\n getTranslations?(request: GetTranslationsRequest): Promise;\n getFieldLabels?(request: GetFieldLabelsRequest): Promise;\n\n // Feed (optional)\n listFeed?(request: GetFeedRequest): Promise;\n createFeedItem?(request: CreateFeedItemRequest): Promise;\n updateFeedItem?(request: UpdateFeedItemRequest): Promise;\n deleteFeedItem?(request: DeleteFeedItemRequest): Promise;\n addReaction?(request: AddReactionRequest): Promise;\n removeReaction?(request: RemoveReactionRequest): Promise;\n pinFeedItem?(request: PinFeedItemRequest): Promise;\n unpinFeedItem?(request: UnpinFeedItemRequest): Promise;\n starFeedItem?(request: StarFeedItemRequest): Promise;\n unstarFeedItem?(request: UnstarFeedItemRequest): Promise;\n searchFeed?(request: SearchFeedRequest): Promise;\n getChangelog?(request: GetChangelogRequest): Promise;\n feedSubscribe?(request: SubscribeRequest): Promise;\n feedUnsubscribe?(request: FeedUnsubscribeRequest): Promise;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\n\n/**\n * REST API Server Protocol\n * \n * Defines the REST API server configuration for automatically generating\n * RESTful CRUD endpoints, metadata endpoints, and batch operations.\n * \n * Features:\n * - Automatic CRUD endpoint generation from Object definitions\n * - Standard REST conventions (GET, POST, PUT, PATCH, DELETE)\n * - Metadata API endpoints\n * - Batch operation endpoints\n * - OpenAPI/Swagger documentation generation\n * \n * Architecture alignment:\n * - Salesforce: REST API with Object CRUD\n * - Microsoft Dynamics: Web API with entity operations\n * - Strapi: Auto-generated REST endpoints\n */\n\n// ==========================================\n// REST API Configuration\n// ==========================================\n\n/**\n * REST API Configuration Schema\n * Core configuration for REST API server\n * \n * @example\n * {\n * \"version\": \"v1\",\n * \"basePath\": \"/api\",\n * \"enableCrud\": true,\n * \"enableMetadata\": true,\n * \"enableBatch\": true,\n * \"documentation\": {\n * \"enabled\": true,\n * \"title\": \"ObjectStack API\"\n * }\n * }\n */\nexport const RestApiConfigSchema = z.object({\n /**\n * API version identifier\n */\n version: z.string().regex(/^[a-zA-Z0-9_\\-\\.]+$/).default('v1').describe('API version (e.g., v1, v2, 2024-01)'),\n \n /**\n * Base path for all API routes\n */\n basePath: z.string().default('/api').describe('Base URL path for API'),\n \n /**\n * Full API path (combines basePath and version)\n */\n apiPath: z.string().optional().describe('Full API path (defaults to {basePath}/{version})'),\n \n /**\n * Enable automatic CRUD endpoints\n */\n enableCrud: z.boolean().default(true).describe('Enable automatic CRUD endpoint generation'),\n \n /**\n * Enable metadata endpoints\n */\n enableMetadata: z.boolean().default(true).describe('Enable metadata API endpoints'),\n \n /**\n * Enable UI API endpoints\n */\n enableUi: z.boolean().default(true).describe('Enable UI API endpoints (Views, Menus, Layouts)'),\n \n /**\n * Enable batch operation endpoints\n */\n enableBatch: z.boolean().default(true).describe('Enable batch operation endpoints'),\n \n /**\n * Enable discovery endpoint\n */\n enableDiscovery: z.boolean().default(true).describe('Enable API discovery endpoint'),\n\n /**\n * API documentation configuration\n */\n documentation: z.object({\n enabled: z.boolean().default(true).describe('Enable API documentation'),\n title: z.string().default('ObjectStack API').describe('API documentation title'),\n description: z.string().optional().describe('API description'),\n version: z.string().optional().describe('Documentation version'),\n termsOfService: z.string().optional().describe('Terms of service URL'),\n contact: z.object({\n name: z.string().optional(),\n url: z.string().optional(),\n email: z.string().optional(),\n }).optional(),\n license: z.object({\n name: z.string(),\n url: z.string().optional(),\n }).optional(),\n }).optional().describe('OpenAPI/Swagger documentation config'),\n \n /**\n * Response format configuration\n */\n responseFormat: z.object({\n envelope: z.boolean().default(true).describe('Wrap responses in standard envelope'),\n includeMetadata: z.boolean().default(true).describe('Include response metadata (timestamp, requestId)'),\n includePagination: z.boolean().default(true).describe('Include pagination info in list responses'),\n }).optional().describe('Response format options'),\n});\n\nexport type RestApiConfig = z.infer;\nexport type RestApiConfigInput = z.input;\n\n// ==========================================\n// CRUD Endpoint Configuration\n// ==========================================\n\n/**\n * CRUD Operation Type Enum\n */\nexport const CrudOperation = z.enum([\n 'create', // POST /api/v1/data/{object}\n 'read', // GET /api/v1/data/{object}/:id\n 'update', // PATCH /api/v1/data/{object}/:id\n 'delete', // DELETE /api/v1/data/{object}/:id\n 'list', // GET /api/v1/data/{object}\n]);\n\nexport type CrudOperation = z.infer;\n\n/**\n * CRUD Endpoint Pattern Schema\n * Defines the URL pattern for CRUD operations\n * \n * @example\n * {\n * \"create\": { \"method\": \"POST\", \"path\": \"/data/{object}\" },\n * \"read\": { \"method\": \"GET\", \"path\": \"/data/{object}/:id\" },\n * \"update\": { \"method\": \"PATCH\", \"path\": \"/data/{object}/:id\" },\n * \"delete\": { \"method\": \"DELETE\", \"path\": \"/data/{object}/:id\" },\n * \"list\": { \"method\": \"GET\", \"path\": \"/data/{object}\" }\n * }\n */\nexport const CrudEndpointPatternSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (relative to API base)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Operation summary for documentation\n */\n summary: z.string().optional().describe('Operation summary'),\n \n /**\n * Operation description\n */\n description: z.string().optional().describe('Operation description'),\n});\n\nexport type CrudEndpointPattern = z.infer;\n\n/**\n * CRUD Endpoints Configuration Schema\n * Configuration for automatic CRUD endpoint generation\n */\nexport const CrudEndpointsConfigSchema = z.object({\n /**\n * Enable/disable specific CRUD operations\n */\n operations: z.object({\n create: z.boolean().default(true).describe('Enable create operation'),\n read: z.boolean().default(true).describe('Enable read operation'),\n update: z.boolean().default(true).describe('Enable update operation'),\n delete: z.boolean().default(true).describe('Enable delete operation'),\n list: z.boolean().default(true).describe('Enable list operation'),\n }).optional().describe('Enable/disable operations'),\n \n /**\n * Custom endpoint patterns (override defaults)\n */\n patterns: z.record(CrudOperation, CrudEndpointPatternSchema.optional()).optional()\n .describe('Custom URL patterns for operations'),\n \n /**\n * Path prefix for data operations\n */\n dataPrefix: z.string().default('/data').describe('URL prefix for data endpoints'),\n \n /**\n * Object name parameter style\n */\n objectParamStyle: z.enum(['path', 'query']).default('path')\n .describe('How object name is passed (path param or query param)'),\n});\n\nexport type CrudEndpointsConfig = z.infer;\nexport type CrudEndpointsConfigInput = z.input;\n\n// ==========================================\n// Metadata Endpoint Configuration\n// ==========================================\n\n/**\n * Metadata Endpoint Configuration Schema\n * Configuration for metadata API endpoints\n * \n * @example\n * {\n * \"prefix\": \"/meta\",\n * \"enableCache\": true,\n * \"endpoints\": {\n * \"types\": true,\n * \"objects\": true,\n * \"fields\": true\n * }\n * }\n */\nexport const MetadataEndpointsConfigSchema = z.object({\n /**\n * Path prefix for metadata operations\n */\n prefix: z.string().default('/meta').describe('URL prefix for metadata endpoints'),\n \n /**\n * Enable HTTP caching for metadata\n */\n enableCache: z.boolean().default(true).describe('Enable HTTP cache headers (ETag, Last-Modified)'),\n \n /**\n * Cache TTL in seconds\n */\n cacheTtl: z.number().int().default(3600).describe('Cache TTL in seconds'),\n \n /**\n * Enable specific metadata endpoints\n */\n endpoints: z.object({\n types: z.boolean().default(true).describe('GET /meta - List all metadata types'),\n items: z.boolean().default(true).describe('GET /meta/:type - List items of type'),\n item: z.boolean().default(true).describe('GET /meta/:type/:name - Get specific item'),\n schema: z.boolean().default(true).describe('GET /meta/:type/:name/schema - Get JSON schema'),\n }).optional().describe('Enable/disable specific endpoints'),\n});\n\nexport type MetadataEndpointsConfig = z.infer;\nexport type MetadataEndpointsConfigInput = z.input;\n\n// ==========================================\n// Batch Operation Endpoint Configuration\n// ==========================================\n\n/**\n * Batch Operation Endpoint Configuration Schema\n * Configuration for batch/bulk operation endpoints\n * \n * @example\n * {\n * \"maxBatchSize\": 200,\n * \"enableBatchEndpoint\": true,\n * \"enableCreateMany\": true,\n * \"enableUpdateMany\": true,\n * \"enableDeleteMany\": true\n * }\n */\nexport const BatchEndpointsConfigSchema = z.object({\n /**\n * Maximum batch size\n */\n maxBatchSize: z.number().int().min(1).max(1000).default(200)\n .describe('Maximum records per batch operation'),\n \n /**\n * Enable generic batch endpoint\n */\n enableBatchEndpoint: z.boolean().default(true)\n .describe('Enable POST /data/:object/batch endpoint'),\n \n /**\n * Enable specific batch operations\n */\n operations: z.object({\n createMany: z.boolean().default(true).describe('Enable POST /data/:object/createMany'),\n updateMany: z.boolean().default(true).describe('Enable POST /data/:object/updateMany'),\n deleteMany: z.boolean().default(true).describe('Enable POST /data/:object/deleteMany'),\n upsertMany: z.boolean().default(true).describe('Enable POST /data/:object/upsertMany'),\n }).optional().describe('Enable/disable specific batch operations'),\n \n /**\n * Transaction mode default\n */\n defaultAtomic: z.boolean().default(true)\n .describe('Default atomic/transaction mode for batch operations'),\n});\n\nexport type BatchEndpointsConfig = z.infer;\nexport type BatchEndpointsConfigInput = z.input;\n\n// ==========================================\n// Route Generation Configuration\n// ==========================================\n\n/**\n * Route Generation Configuration Schema\n * Controls automatic route generation for objects\n */\nexport const RouteGenerationConfigSchema = z.object({\n /**\n * Objects to include (if empty, include all)\n */\n includeObjects: z.array(z.string()).optional()\n .describe('Specific objects to generate routes for (empty = all)'),\n \n /**\n * Objects to exclude\n */\n excludeObjects: z.array(z.string()).optional()\n .describe('Objects to exclude from route generation'),\n \n /**\n * Object name transformations\n */\n nameTransform: z.enum(['none', 'plural', 'kebab-case', 'camelCase']).default('none')\n .describe('Transform object names in URLs'),\n \n /**\n * Custom route overrides per object\n */\n overrides: z.record(z.string(), z.object({\n enabled: z.boolean().optional().describe('Enable/disable routes for this object'),\n basePath: z.string().optional().describe('Custom base path'),\n operations: z.record(CrudOperation, z.boolean()).optional()\n .describe('Enable/disable specific operations'),\n })).optional().describe('Per-object route customization'),\n});\n\nexport type RouteGenerationConfig = z.infer;\nexport type RouteGenerationConfigInput = z.input;\n\n// ==========================================\n// OpenAPI 3.1 Webhooks & Callbacks\n// ==========================================\n\n/**\n * Webhook Event Schema\n * Defines an event that can trigger a webhook delivery\n */\nexport const WebhookEventSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Webhook event identifier (snake_case)'),\n description: z.string().describe('Human-readable event description'),\n method: HttpMethod.default('POST').describe('HTTP method for webhook delivery'),\n payloadSchema: z.string().describe('JSON Schema $ref for the webhook payload'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers to include in webhook delivery'),\n security: z.array(\n z.enum(['hmac_sha256', 'basic', 'bearer', 'api_key'])\n ).describe('Supported authentication methods for webhook verification'),\n});\n\nexport type WebhookEvent = z.infer;\n\n/**\n * Webhook Configuration Schema\n * Top-level webhook configuration for the REST API\n */\nexport const WebhookConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable webhook support'),\n events: z.array(WebhookEventSchema).describe('Registered webhook events'),\n deliveryConfig: z.object({\n maxRetries: z.number().int().default(3).describe('Maximum delivery retry attempts'),\n retryIntervalMs: z.number().int().default(5000).describe('Milliseconds between retry attempts'),\n timeoutMs: z.number().int().default(30000).describe('Delivery request timeout in milliseconds'),\n signatureHeader: z.string().default('X-Signature-256').describe('Header name for webhook signature'),\n }).describe('Webhook delivery configuration'),\n registrationEndpoint: z.string().default('/webhooks').describe('URL path for webhook registration'),\n});\n\nexport type WebhookConfig = z.infer;\n\n/**\n * Callback Schema\n * OpenAPI 3.1 callback definition for asynchronous API responses\n */\nexport const CallbackSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Callback identifier (snake_case)'),\n expression: z.string().describe('Runtime expression (e.g., {$request.body#/callbackUrl})'),\n method: HttpMethod.describe('HTTP method for callback request'),\n url: z.string().describe('Callback URL template with runtime expressions'),\n});\n\nexport type Callback = z.infer;\n\n/**\n * OpenAPI 3.1 Extensions Schema\n * Extensions specific to OpenAPI 3.1 specification\n */\nexport const OpenApi31ExtensionsSchema = z.object({\n webhooks: z.record(z.string(), WebhookEventSchema).optional()\n .describe('OpenAPI 3.1 webhooks (top-level webhook definitions)'),\n callbacks: z.record(z.string(), z.array(CallbackSchema)).optional()\n .describe('OpenAPI 3.1 callbacks (async response definitions)'),\n jsonSchemaDialect: z.string().default('https://json-schema.org/draft/2020-12/schema')\n .describe('JSON Schema dialect for schema definitions'),\n pathItemReferences: z.boolean().default(false)\n .describe('Allow $ref in path items (OpenAPI 3.1 feature)'),\n});\n\nexport type OpenApi31Extensions = z.infer;\n\n// ==========================================\n// Complete REST Server Configuration\n// ==========================================\n\n/**\n * REST Server Configuration Schema\n * Complete configuration for REST API server with auto-generated endpoints\n * \n * @example\n * {\n * \"api\": {\n * \"version\": \"v1\",\n * \"basePath\": \"/api\",\n * \"enableCrud\": true,\n * \"enableMetadata\": true,\n * \"enableBatch\": true\n * },\n * \"crud\": {\n * \"dataPrefix\": \"/data\"\n * },\n * \"metadata\": {\n * \"prefix\": \"/meta\",\n * \"enableCache\": true\n * },\n * \"batch\": {\n * \"maxBatchSize\": 200\n * },\n * \"routes\": {\n * \"excludeObjects\": [\"system_log\"]\n * }\n * }\n */\nexport const RestServerConfigSchema = z.object({\n /**\n * API configuration\n */\n api: RestApiConfigSchema.optional().describe('REST API configuration'),\n \n /**\n * CRUD endpoints configuration\n */\n crud: CrudEndpointsConfigSchema.optional().describe('CRUD endpoints configuration'),\n \n /**\n * Metadata endpoints configuration\n */\n metadata: MetadataEndpointsConfigSchema.optional().describe('Metadata endpoints configuration'),\n \n /**\n * Batch endpoints configuration\n */\n batch: BatchEndpointsConfigSchema.optional().describe('Batch endpoints configuration'),\n \n /**\n * Route generation configuration\n */\n routes: RouteGenerationConfigSchema.optional().describe('Route generation configuration'),\n \n /**\n * OpenAPI 3.1 extensions (webhooks, callbacks)\n */\n openApi31: OpenApi31ExtensionsSchema.optional().describe('OpenAPI 3.1 extensions configuration'),\n});\n\nexport type RestServerConfig = z.infer;\nexport type RestServerConfigInput = z.input;\n\n// ==========================================\n// Endpoint Registry\n// ==========================================\n\n/**\n * Generated Endpoint Schema\n * Represents a generated REST endpoint\n */\nexport const GeneratedEndpointSchema = z.object({\n /**\n * Endpoint identifier\n */\n id: z.string().describe('Unique endpoint identifier'),\n \n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * Full URL path\n */\n path: z.string().describe('Full URL path'),\n \n /**\n * Object this endpoint operates on\n */\n object: z.string().describe('Object name (snake_case)'),\n \n /**\n * Operation type\n */\n operation: z.union([CrudOperation, z.string()]).describe('Operation type'),\n \n /**\n * Handler reference\n */\n handler: z.string().describe('Handler function identifier'),\n \n /**\n * Endpoint metadata\n */\n metadata: z.object({\n summary: z.string().optional(),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n deprecated: z.boolean().optional(),\n }).optional(),\n});\n\nexport type GeneratedEndpoint = z.infer;\n\n/**\n * Endpoint Registry Schema\n * Registry of all generated endpoints\n */\nexport const EndpointRegistrySchema = z.object({\n /**\n * Generated endpoints\n */\n endpoints: z.array(GeneratedEndpointSchema).describe('All generated endpoints'),\n \n /**\n * Total endpoint count\n */\n total: z.number().int().describe('Total number of endpoints'),\n \n /**\n * Endpoints by object\n */\n byObject: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()\n .describe('Endpoints grouped by object'),\n \n /**\n * Endpoints by operation\n */\n byOperation: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()\n .describe('Endpoints grouped by operation'),\n});\n\nexport type EndpointRegistry = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create REST API configuration\n */\nexport const RestApiConfig = Object.assign(RestApiConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create REST server configuration\n */\nexport const RestServerConfig = Object.assign(RestServerConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, RateLimitConfigSchema } from '../shared/http.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Unified API Registry Protocol\n * \n * Provides a centralized registry for managing all API endpoints across different\n * API types (REST, GraphQL, OData, WebSocket, Auth, File, Plugin-registered).\n * \n * This enables:\n * - Unified API discovery and documentation (similar to Swagger/OpenAPI)\n * - API testing interfaces\n * - API governance and monitoring\n * - Plugin API registration\n * - Multi-protocol support\n * \n * Architecture Alignment:\n * - Kubernetes: Service Discovery & API Server\n * - AWS API Gateway: Unified API Management\n * - Kong Gateway: Plugin-based API Management\n * \n * @example API Registry Entry\n * ```typescript\n * const apiEntry: ApiRegistryEntry = {\n * id: 'customer_crud',\n * name: 'Customer CRUD API',\n * type: 'rest',\n * version: 'v1',\n * basePath: '/api/v1/data/customer',\n * endpoints: [...],\n * metadata: {\n * owner: 'sales_team',\n * tags: ['customer', 'crm']\n * }\n * }\n * ```\n */\n\n// ==========================================\n// API Type Enumeration\n// ==========================================\n\n/**\n * API Protocol Type\n * \n * Defines the different types of APIs supported by ObjectStack.\n */\nexport const ApiProtocolType = z.enum([\n 'rest', // RESTful API (CRUD operations)\n 'graphql', // GraphQL API (flexible queries)\n 'odata', // OData v4 API (enterprise integration)\n 'websocket', // WebSocket API (real-time)\n 'file', // File/Storage API (uploads/downloads)\n 'auth', // Authentication/Authorization API\n 'metadata', // Metadata/Schema API\n 'plugin', // Plugin-registered custom API\n 'webhook', // Webhook endpoints\n 'rpc', // JSON-RPC or similar\n]);\n\nexport type ApiProtocolType = z.infer;\n\n// ==========================================\n// API Endpoint Registration\n// ==========================================\n\n/**\n * HTTP Status Code\n */\nexport const HttpStatusCode = z.union([\n z.number().int().min(100).max(599),\n z.enum(['2xx', '3xx', '4xx', '5xx']), // Pattern matching\n]);\n\nexport type HttpStatusCode = z.infer;\n\n// ==========================================\n// Schema Reference Types\n// ==========================================\n\n/**\n * ObjectQL Reference Schema\n * \n * Allows referencing ObjectStack data objects instead of static JSON schemas.\n * When an API parameter or response references an ObjectQL object, the schema\n * is dynamically derived from the object definition, enabling automatic updates\n * when the object schema changes.\n * \n * **IMPORTANT - Schema Resolution Responsibility:**\n * The API Registry STORES these references as metadata but does NOT resolve them.\n * Schema resolution (expanding references into actual JSON Schema) is performed by:\n * - **API Gateway**: For runtime request/response validation\n * - **OpenAPI Generator**: For Swagger/OpenAPI documentation\n * - **GraphQL Schema Builder**: For GraphQL type generation\n * - **Documentation Tools**: For developer documentation\n * \n * This separation allows the Registry to remain lightweight and focused on\n * registration/discovery, while specialized tools handle schema transformation.\n * \n * **Benefits:**\n * - Auto-updating API documentation when object schemas change\n * - Consistent type definitions across API and database\n * - Reduced duplication and maintenance\n * - Registry remains protocol-agnostic and lightweight\n * \n * @example Reference Customer object\n * ```json\n * {\n * \"objectId\": \"customer\",\n * \"includeFields\": [\"id\", \"name\", \"email\"],\n * \"excludeFields\": [\"internal_notes\"]\n * }\n * ```\n */\nexport const ObjectQLReferenceSchema = z.object({\n /** Referenced object name (snake_case) */\n objectId: SnakeCaseIdentifierSchema.describe('Object name to reference'),\n \n /** Include only specific fields (optional) */\n includeFields: z.array(z.string()).optional()\n .describe('Include only these fields in the schema'),\n \n /** Exclude specific fields (optional) */\n excludeFields: z.array(z.string()).optional()\n .describe('Exclude these fields from the schema'),\n \n /** Include related objects via lookup fields */\n includeRelated: z.array(z.string()).optional()\n .describe('Include related objects via lookup fields'),\n});\n\nexport type ObjectQLReference = z.infer;\n\n/**\n * Schema Definition\n * \n * Unified schema definition that supports both:\n * 1. Static JSON Schema (traditional approach)\n * 2. Dynamic ObjectQL reference (linked to object definitions)\n * \n * When using ObjectQL references, the API documentation and validation\n * automatically update when object schemas change, eliminating the need\n * to manually sync API schemas with data models.\n */\nexport const SchemaDefinition = z.union([\n z.unknown().describe('Static JSON Schema definition'),\n z.object({\n $ref: ObjectQLReferenceSchema.describe('Dynamic reference to ObjectQL object'),\n }).describe('Dynamic ObjectQL reference'),\n]);\n\nexport type SchemaDefinition = z.infer;\n\n// ==========================================\n// API Parameter & Response Schemas\n// ==========================================\n\n/**\n * API Parameter Schema\n * \n * Defines a single API parameter (path, query, header, or body).\n * \n * **Enhancement: Dynamic Schema Linking**\n * - Supports both static JSON Schema and dynamic ObjectQL references\n * - When using ObjectQL references, parameter validation automatically updates\n * when the referenced object schema changes\n * \n * @example Static schema\n * ```json\n * {\n * \"name\": \"customer_id\",\n * \"in\": \"path\",\n * \"schema\": {\n * \"type\": \"string\",\n * \"format\": \"uuid\"\n * }\n * }\n * ```\n * \n * @example Dynamic ObjectQL reference\n * ```json\n * {\n * \"name\": \"customer\",\n * \"in\": \"body\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\",\n * \"excludeFields\": [\"internal_notes\"]\n * }\n * }\n * }\n * ```\n */\nexport const ApiParameterSchema = z.object({\n /** Parameter name */\n name: z.string().describe('Parameter name'),\n \n /** Parameter location */\n in: z.enum(['path', 'query', 'header', 'body', 'cookie']).describe('Parameter location'),\n \n /** Parameter description */\n description: z.string().optional().describe('Parameter description'),\n \n /** Required flag */\n required: z.boolean().default(false).describe('Whether parameter is required'),\n \n /** Parameter type/schema - supports static or dynamic (ObjectQL) schemas */\n schema: z.union([\n z.object({\n type: z.enum(['string', 'number', 'integer', 'boolean', 'array', 'object']).describe('Parameter type'),\n format: z.string().optional().describe('Format (e.g., date-time, email, uuid)'),\n enum: z.array(z.unknown()).optional().describe('Allowed values'),\n default: z.unknown().optional().describe('Default value'),\n items: z.unknown().optional().describe('Array item schema'),\n properties: z.record(z.string(), z.unknown()).optional().describe('Object properties'),\n }).describe('Static JSON Schema'),\n z.object({\n $ref: ObjectQLReferenceSchema,\n }).describe('Dynamic ObjectQL reference'),\n ]).describe('Parameter schema definition'),\n \n /** Example value */\n example: z.unknown().optional().describe('Example value'),\n});\n\nexport type ApiParameter = z.infer;\n\n/**\n * API Response Schema\n * \n * Defines an API response for a specific status code.\n * \n * **Enhancement: Dynamic Schema Linking**\n * - Response schema can reference ObjectQL objects\n * - When object definitions change, response documentation auto-updates\n * \n * @example Response with ObjectQL reference\n * ```json\n * {\n * \"statusCode\": 200,\n * \"description\": \"Customer retrieved successfully\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\",\n * \"excludeFields\": [\"password_hash\"]\n * }\n * }\n * }\n * ```\n */\nexport const ApiResponseSchema = z.object({\n /** HTTP status code */\n statusCode: HttpStatusCode.describe('HTTP status code'),\n \n /** Response description */\n description: z.string().describe('Response description'),\n \n /** Response content type */\n contentType: z.string().default('application/json').describe('Response content type'),\n \n /** Response schema - supports static or dynamic (ObjectQL) schemas */\n schema: z.union([\n z.unknown().describe('Static JSON Schema'),\n z.object({\n $ref: ObjectQLReferenceSchema,\n }).describe('Dynamic ObjectQL reference'),\n ]).optional().describe('Response body schema'),\n \n /** Response headers */\n headers: z.record(z.string(), z.object({\n description: z.string().optional(),\n schema: z.unknown(),\n })).optional().describe('Response headers'),\n \n /** Example response */\n example: z.unknown().optional().describe('Example response'),\n});\n\nexport type ApiResponse = z.infer;\nexport type ApiResponseInput = z.input;\n\n/**\n * API Endpoint Registration Schema\n * \n * Represents a single API endpoint registration with complete metadata.\n * \n * **Enhancements:**\n * 1. **RBAC Integration**: `requiredPermissions` field for automatic permission checking\n * 2. **Dynamic Schema Linking**: Parameters and responses can reference ObjectQL objects\n * 3. **Route Priority**: `priority` field for conflict resolution\n * 4. **Protocol Config**: `protocolConfig` for protocol-specific extensions\n * \n * @example REST Endpoint with RBAC\n * ```json\n * {\n * \"id\": \"get_customer_by_id\",\n * \"method\": \"GET\",\n * \"path\": \"/api/v1/data/customer/:id\",\n * \"summary\": \"Get customer by ID\",\n * \"requiredPermissions\": [\"customer.read\"],\n * \"parameters\": [\n * {\n * \"name\": \"id\",\n * \"in\": \"path\",\n * \"required\": true,\n * \"schema\": { \"type\": \"string\" }\n * }\n * ],\n * \"responses\": [\n * {\n * \"statusCode\": 200,\n * \"description\": \"Customer found\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\"\n * }\n * }\n * }\n * ],\n * \"priority\": 100\n * }\n * ```\n * \n * @example Plugin Endpoint with Protocol Config\n * ```json\n * {\n * \"id\": \"grpc_service_method\",\n * \"path\": \"/grpc/ServiceName/MethodName\",\n * \"summary\": \"gRPC service method\",\n * \"protocolConfig\": {\n * \"subProtocol\": \"grpc\",\n * \"serviceName\": \"CustomerService\",\n * \"methodName\": \"GetCustomer\"\n * },\n * \"priority\": 50\n * }\n * ```\n */\nexport const ApiEndpointRegistrationSchema = z.object({\n /** Unique endpoint identifier */\n id: z.string().describe('Unique endpoint identifier'),\n \n /** HTTP method (for HTTP-based APIs) */\n method: HttpMethod.optional().describe('HTTP method'),\n \n /** URL path pattern */\n path: z.string().describe('URL path pattern'),\n \n /** Short summary */\n summary: z.string().optional().describe('Short endpoint summary'),\n \n /** Detailed description */\n description: z.string().optional().describe('Detailed endpoint description'),\n \n /** Operation ID (OpenAPI) */\n operationId: z.string().optional().describe('Unique operation identifier'),\n \n /** Tags for grouping */\n tags: z.array(z.string()).optional().default([]).describe('Tags for categorization'),\n \n /** Parameters */\n parameters: z.array(ApiParameterSchema).optional().default([]).describe('Endpoint parameters'),\n \n /** Request body schema */\n requestBody: z.object({\n description: z.string().optional(),\n required: z.boolean().default(false),\n contentType: z.string().default('application/json'),\n schema: z.unknown().optional(),\n example: z.unknown().optional(),\n }).optional().describe('Request body specification'),\n \n /** Response definitions */\n responses: z.array(ApiResponseSchema).optional().default([]).describe('Possible responses'),\n \n /** Rate Limiting */\n rateLimit: RateLimitConfigSchema.optional().describe('Endpoint specific rate limiting'),\n\n /** Security Requirements */\n security: z.array(z.record(z.string(), z.array(z.string()))).optional().describe('Security requirements (e.g. [{\"bearerAuth\": []}])'),\n \n /**\n * Required Permissions (RBAC Integration)\n * \n * Array of permission names required to access this endpoint.\n * The gateway layer automatically validates these permissions before\n * allowing the request to proceed, eliminating the need for permission\n * checks in individual API handlers.\n * \n * **Format:** `.` or system permission name\n * \n * **Object Permissions:**\n * - `customer.read` - Read customer records\n * - `customer.create` - Create customer records\n * - `customer.edit` - Update customer records\n * - `customer.delete` - Delete customer records\n * - `customer.viewAll` - View all customer records (bypass sharing)\n * - `customer.modifyAll` - Modify all customer records (bypass sharing)\n * \n * **System Permissions:**\n * - `manage_users` - User management\n * - `view_setup` - Access to system setup\n * - `customize_application` - Modify metadata\n * - `api_enabled` - API access\n * \n * @example Object-level permissions\n * ```json\n * {\n * \"requiredPermissions\": [\"customer.read\"]\n * }\n * ```\n * \n * @example Multiple permissions (ALL required)\n * ```json\n * {\n * \"requiredPermissions\": [\"customer.read\", \"account.read\"]\n * }\n * ```\n * \n * @example System permission\n * ```json\n * {\n * \"requiredPermissions\": [\"manage_users\"]\n * }\n * ```\n * \n * @see {@link file://../../permission/permission.zod.ts} for permission definitions\n */\n requiredPermissions: z.array(z.string()).optional().default([])\n .describe('Required RBAC permissions (e.g., \"customer.read\", \"manage_users\")'),\n \n /**\n * Route Priority\n * \n * Priority level for route conflict resolution. Higher priority routes\n * are registered first and take precedence when multiple routes match\n * the same path pattern.\n * \n * **Default:** 100 (medium priority)\n * **Range:** 0-1000 (higher = more important)\n * \n * **Use Cases:**\n * - Core system APIs: 900-1000\n * - Plugin APIs: 100-500\n * - Custom/override APIs: 500-900\n * - Fallback routes: 0-100\n * \n * @example High priority core endpoint\n * ```json\n * {\n * \"path\": \"/api/v1/data/:object/:id\",\n * \"priority\": 950\n * }\n * ```\n * \n * @example Medium priority plugin endpoint\n * ```json\n * {\n * \"path\": \"/api/v1/custom/action\",\n * \"priority\": 300\n * }\n * ```\n */\n priority: z.number().int().min(0).max(1000).optional().default(100)\n .describe('Route priority for conflict resolution (0-1000, higher = more important)'),\n \n /**\n * Protocol-Specific Configuration\n * \n * Allows plugins and custom APIs to define protocol-specific metadata\n * that can be used for specialized handling or documentation generation.\n * \n * **Examples:**\n * - gRPC: Service and method names\n * - tRPC: Procedure type (query/mutation)\n * - WebSocket: Event names and handlers\n * - Custom protocols: Any metadata needed\n * \n * @example gRPC configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"grpc\",\n * \"serviceName\": \"CustomerService\",\n * \"methodName\": \"GetCustomer\",\n * \"streaming\": false\n * }\n * }\n * ```\n * \n * @example tRPC configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"trpc\",\n * \"procedureType\": \"query\",\n * \"router\": \"customer\"\n * }\n * }\n * ```\n * \n * @example WebSocket configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"websocket\",\n * \"eventName\": \"customer.updated\",\n * \"direction\": \"server-to-client\"\n * }\n * }\n * ```\n */\n protocolConfig: z.record(z.string(), z.unknown()).optional()\n .describe('Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)'),\n \n /** Deprecation flag */\n deprecated: z.boolean().default(false).describe('Whether endpoint is deprecated'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation link'),\n});\n\nexport type ApiEndpointRegistration = z.infer;\nexport type ApiEndpointRegistrationInput = z.input;\n\n// ==========================================\n// API Registry Entry\n// ==========================================\n\n/**\n * API Metadata Schema\n * \n * Additional metadata for an API registration.\n */\nexport const ApiMetadataSchema = z.object({\n /** API owner/team */\n owner: z.string().optional().describe('Owner team or person'),\n \n /** API status */\n status: z.enum(['active', 'deprecated', 'experimental', 'beta']).default('active')\n .describe('API lifecycle status'),\n \n /** Categorization tags */\n tags: z.array(z.string()).optional().default([]).describe('Classification tags'),\n \n /** Plugin source (if plugin-registered) */\n pluginSource: z.string().optional().describe('Source plugin name'),\n \n /** Custom metadata */\n custom: z.record(z.string(), z.unknown()).optional().describe('Custom metadata fields'),\n});\n\nexport type ApiMetadata = z.infer;\nexport type ApiMetadataInput = z.input;\n\n/**\n * API Registry Entry Schema\n * \n * Complete registration entry for an API in the unified registry.\n * \n * @example REST API Entry\n * ```json\n * {\n * \"id\": \"customer_api\",\n * \"name\": \"Customer Management API\",\n * \"type\": \"rest\",\n * \"version\": \"v1\",\n * \"basePath\": \"/api/v1/data/customer\",\n * \"description\": \"CRUD operations for customer records\",\n * \"endpoints\": [...],\n * \"metadata\": {\n * \"owner\": \"sales_team\",\n * \"status\": \"active\",\n * \"tags\": [\"customer\", \"crm\"]\n * }\n * }\n * ```\n * \n * @example Plugin API Entry\n * ```json\n * {\n * \"id\": \"payment_webhook\",\n * \"name\": \"Payment Webhook API\",\n * \"type\": \"plugin\",\n * \"version\": \"1.0.0\",\n * \"basePath\": \"/plugins/payment/webhook\",\n * \"endpoints\": [...],\n * \"metadata\": {\n * \"pluginSource\": \"payment_gateway_plugin\",\n * \"status\": \"active\"\n * }\n * }\n * ```\n */\nexport const ApiRegistryEntrySchema = z.object({\n /** Unique API identifier */\n id: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique API identifier (snake_case)'),\n \n /** Human-readable name */\n name: z.string().describe('API display name'),\n \n /** API protocol type */\n type: ApiProtocolType.describe('API protocol type'),\n \n /** API version */\n version: z.string().describe('API version (e.g., v1, 2024-01)'),\n \n /** Base URL path */\n basePath: z.string().describe('Base URL path for this API'),\n \n /** API description */\n description: z.string().optional().describe('API description'),\n \n /** Endpoints in this API */\n endpoints: z.array(ApiEndpointRegistrationSchema).describe('Registered endpoints'),\n \n /** OpenAPI/GraphQL/OData specific configuration */\n config: z.record(z.string(), z.unknown()).optional().describe('Protocol-specific configuration'),\n \n /** API metadata */\n metadata: ApiMetadataSchema.optional().describe('Additional metadata'),\n \n /** Terms of service URL */\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n \n /** Contact information */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('Contact information'),\n \n /** License information */\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional().describe('License information'),\n});\n\nexport type ApiRegistryEntry = z.infer;\nexport type ApiRegistryEntryInput = z.input;\n\n// ==========================================\n// API Registry\n// ==========================================\n\n/**\n * Route Conflict Resolution Strategy\n * \n * Defines how to handle conflicts when multiple endpoints register\n * the same or overlapping URL patterns.\n */\nexport const ConflictResolutionStrategy = z.enum([\n 'error', // Throw error on conflict (safest, default)\n 'priority', // Use priority field to resolve (highest priority wins)\n 'first-wins', // First registered endpoint wins\n 'last-wins', // Last registered endpoint wins (override mode)\n]);\n\nexport type ConflictResolutionStrategy = z.infer;\n\n/**\n * API Registry Schema\n * \n * Central registry containing all registered APIs.\n * \n * **Enhancement: Route Conflict Detection**\n * - `conflictResolution`: Strategy for handling route conflicts\n * - Prevents silent overwrites and unexpected routing behavior\n * \n * @example\n * ```json\n * {\n * \"version\": \"1.0.0\",\n * \"conflictResolution\": \"priority\",\n * \"apis\": [\n * { \"id\": \"customer_api\", \"type\": \"rest\", ... },\n * { \"id\": \"graphql_api\", \"type\": \"graphql\", ... },\n * { \"id\": \"file_upload_api\", \"type\": \"file\", ... }\n * ],\n * \"totalApis\": 3,\n * \"totalEndpoints\": 47\n * }\n * ```\n * \n * @example Priority-based conflict resolution\n * ```json\n * {\n * \"conflictResolution\": \"priority\",\n * \"apis\": [\n * {\n * \"id\": \"core_api\",\n * \"endpoints\": [\n * {\n * \"path\": \"/api/v1/data/:object\",\n * \"priority\": 950\n * }\n * ]\n * },\n * {\n * \"id\": \"plugin_api\",\n * \"endpoints\": [\n * {\n * \"path\": \"/api/v1/data/custom\",\n * \"priority\": 300\n * }\n * ]\n * }\n * ]\n * }\n * ```\n */\nexport const ApiRegistrySchema = z.object({\n /** Registry version */\n version: z.string().describe('Registry version'),\n \n /**\n * Conflict Resolution Strategy\n * \n * Defines how to handle route conflicts when multiple endpoints\n * register the same or overlapping URL patterns.\n * \n * **Strategies:**\n * - `error`: Throw error on conflict (safest, prevents silent overwrites)\n * - `priority`: Use endpoint priority field (highest priority wins)\n * - `first-wins`: First registered endpoint wins (stable, predictable)\n * - `last-wins`: Last registered endpoint wins (allows overrides)\n * \n * **Default:** `error`\n * \n * **Best Practices:**\n * - Use `error` in production to catch configuration issues\n * - Use `priority` when mixing core and plugin APIs\n * - Use `last-wins` for development/testing overrides\n * \n * @example Prevent accidental conflicts\n * ```json\n * {\n * \"conflictResolution\": \"error\"\n * }\n * ```\n * \n * @example Allow plugin overrides with priority\n * ```json\n * {\n * \"conflictResolution\": \"priority\"\n * }\n * ```\n */\n conflictResolution: ConflictResolutionStrategy.optional().default('error')\n .describe('Strategy for handling route conflicts'),\n \n /** Registered APIs */\n apis: z.array(ApiRegistryEntrySchema).describe('All registered APIs'),\n \n /** Total API count */\n totalApis: z.number().int().describe('Total number of registered APIs'),\n \n /** Total endpoint count across all APIs */\n totalEndpoints: z.number().int().describe('Total number of endpoints'),\n \n /** APIs grouped by type */\n byType: z.record(ApiProtocolType, z.array(ApiRegistryEntrySchema)).optional()\n .describe('APIs grouped by protocol type'),\n \n /** APIs grouped by status */\n byStatus: z.record(z.string(), z.array(ApiRegistryEntrySchema)).optional()\n .describe('APIs grouped by status'),\n \n /** Last updated timestamp */\n updatedAt: z.string().datetime().optional().describe('Last registry update time'),\n});\n\nexport type ApiRegistry = z.infer;\n\n// ==========================================\n// API Discovery & Query\n// ==========================================\n\n/**\n * API Discovery Query Schema\n * \n * Query parameters for discovering/filtering APIs in the registry.\n * \n * @example\n * ```json\n * {\n * \"type\": \"rest\",\n * \"tags\": [\"customer\"],\n * \"status\": \"active\"\n * }\n * ```\n */\nexport const ApiDiscoveryQuerySchema = z.object({\n /** Filter by API type */\n type: ApiProtocolType.optional().describe('Filter by API protocol type'),\n \n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags (ANY match)'),\n \n /** Filter by status */\n status: z.enum(['active', 'deprecated', 'experimental', 'beta']).optional()\n .describe('Filter by lifecycle status'),\n \n /** Filter by plugin source */\n pluginSource: z.string().optional().describe('Filter by plugin name'),\n \n /** Search in name/description */\n search: z.string().optional().describe('Full-text search in name/description'),\n \n /** Filter by version */\n version: z.string().optional().describe('Filter by specific version'),\n});\n\nexport type ApiDiscoveryQuery = z.infer;\n\n/**\n * API Discovery Response Schema\n * \n * Response for API discovery queries.\n */\nexport const ApiDiscoveryResponseSchema = z.object({\n /** Matching APIs */\n apis: z.array(ApiRegistryEntrySchema).describe('Matching API entries'),\n \n /** Total matches */\n total: z.number().int().describe('Total matching APIs'),\n \n /** Applied filters */\n filters: ApiDiscoveryQuerySchema.optional().describe('Applied query filters'),\n});\n\nexport type ApiDiscoveryResponse = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create API endpoint registration\n */\nexport const ApiEndpointRegistration = Object.assign(ApiEndpointRegistrationSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API registry entry\n */\nexport const ApiRegistryEntry = Object.assign(ApiRegistryEntrySchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API registry\n */\nexport const ApiRegistry = Object.assign(ApiRegistrySchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * API Documentation & Testing Interface Protocol\n * \n * Provides schemas for generating interactive API documentation and testing\n * interfaces similar to Swagger UI, GraphQL Playground, Postman, etc.\n * \n * Features:\n * - OpenAPI/Swagger specification generation\n * - Interactive API testing playground\n * - API versioning and changelog\n * - Code generation templates\n * - Mock server configuration\n * \n * Architecture Alignment:\n * - Swagger UI: Interactive API documentation\n * - Postman: API testing collections\n * - GraphQL Playground: GraphQL-specific testing\n * - Redoc: Documentation rendering\n * \n * @example Documentation Config\n * ```typescript\n * const docConfig: ApiDocumentationConfig = {\n * enabled: true,\n * title: 'ObjectStack API',\n * version: '1.0.0',\n * servers: [{ url: 'https://api.example.com', description: 'Production' }],\n * ui: {\n * type: 'swagger-ui',\n * theme: 'light',\n * enableTryItOut: true\n * }\n * }\n * ```\n */\n\n// ==========================================\n// OpenAPI Specification\n// ==========================================\n\n/**\n * OpenAPI Server Schema\n * \n * Server configuration for OpenAPI specification.\n */\nexport const OpenApiServerSchema = z.object({\n /** Server URL */\n url: z.string().url().describe('Server base URL'),\n \n /** Server description */\n description: z.string().optional().describe('Server description'),\n \n /** Server variables */\n variables: z.record(z.string(), z.object({\n default: z.string(),\n description: z.string().optional(),\n enum: z.array(z.string()).optional(),\n })).optional().describe('URL template variables'),\n});\n\nexport type OpenApiServer = z.infer;\n\n/**\n * OpenAPI Security Scheme Schema\n * \n * Security scheme definition for OpenAPI.\n */\nexport const OpenApiSecuritySchemeSchema = z.object({\n /** Security scheme type */\n type: z.enum(['apiKey', 'http', 'oauth2', 'openIdConnect']).describe('Security type'),\n \n /** Scheme name */\n scheme: z.string().optional().describe('HTTP auth scheme (bearer, basic, etc.)'),\n \n /** Bearer format */\n bearerFormat: z.string().optional().describe('Bearer token format (e.g., JWT)'),\n \n /** API key name */\n name: z.string().optional().describe('API key parameter name'),\n \n /** API key location */\n in: z.enum(['header', 'query', 'cookie']).optional().describe('API key location'),\n \n /** OAuth flows */\n flows: z.object({\n implicit: z.unknown().optional(),\n password: z.unknown().optional(),\n clientCredentials: z.unknown().optional(),\n authorizationCode: z.unknown().optional(),\n }).optional().describe('OAuth2 flows'),\n \n /** OpenID Connect URL */\n openIdConnectUrl: z.string().url().optional().describe('OpenID Connect discovery URL'),\n \n /** Description */\n description: z.string().optional().describe('Security scheme description'),\n});\n\nexport type OpenApiSecurityScheme = z.infer;\n\n/**\n * OpenAPI Specification Schema\n * \n * Complete OpenAPI 3.0 specification structure.\n * \n * @see https://swagger.io/specification/\n * \n * @example\n * ```json\n * {\n * \"openapi\": \"3.0.0\",\n * \"info\": {\n * \"title\": \"ObjectStack API\",\n * \"version\": \"1.0.0\",\n * \"description\": \"ObjectStack unified API\"\n * },\n * \"servers\": [\n * { \"url\": \"https://api.example.com\" }\n * ],\n * \"paths\": { ... },\n * \"components\": { ... }\n * }\n * ```\n */\nexport const OpenApiSpecSchema = z.object({\n /** OpenAPI version */\n openapi: z.string().default('3.0.0').describe('OpenAPI specification version'),\n \n /** API information */\n info: z.object({\n title: z.string().describe('API title'),\n version: z.string().describe('API version'),\n description: z.string().optional().describe('API description'),\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional(),\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional(),\n }).describe('API metadata'),\n \n /** Servers */\n servers: z.array(OpenApiServerSchema).optional().default([]).describe('API servers'),\n \n /** API paths */\n paths: z.record(z.string(), z.unknown()).describe('API paths and operations'),\n \n /** Reusable components */\n components: z.object({\n schemas: z.record(z.string(), z.unknown()).optional(),\n responses: z.record(z.string(), z.unknown()).optional(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n examples: z.record(z.string(), z.unknown()).optional(),\n requestBodies: z.record(z.string(), z.unknown()).optional(),\n headers: z.record(z.string(), z.unknown()).optional(),\n securitySchemes: z.record(z.string(), OpenApiSecuritySchemeSchema).optional(),\n links: z.record(z.string(), z.unknown()).optional(),\n callbacks: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Reusable components'),\n \n /** Security requirements */\n security: z.array(z.record(z.string(), z.array(z.string()))).optional()\n .describe('Global security requirements'),\n \n /** Tags */\n tags: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional(),\n })).optional().describe('Tag definitions'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation'),\n});\n\nexport type OpenApiSpec = z.infer;\n\n// ==========================================\n// API Testing Playground\n// ==========================================\n\n/**\n * API Testing UI Type\n */\nexport const ApiTestingUiType = z.enum([\n 'swagger-ui', // Swagger UI\n 'redoc', // Redoc\n 'rapidoc', // RapiDoc\n 'stoplight', // Stoplight Elements\n 'scalar', // Scalar API Reference\n 'graphql-playground', // GraphQL Playground\n 'graphiql', // GraphiQL\n 'postman', // Postman-like interface\n 'custom', // Custom implementation\n]);\n\nexport type ApiTestingUiType = z.infer;\n\n/**\n * API Testing UI Configuration Schema\n * \n * Configuration for interactive API testing interface.\n * \n * @example Swagger UI Config\n * ```json\n * {\n * \"type\": \"swagger-ui\",\n * \"path\": \"/api-docs\",\n * \"theme\": \"light\",\n * \"enableTryItOut\": true,\n * \"enableFilter\": true,\n * \"enableCors\": true,\n * \"defaultModelsExpandDepth\": 1\n * }\n * ```\n */\nexport const ApiTestingUiConfigSchema = z.object({\n /** UI type */\n type: ApiTestingUiType.describe('Testing UI implementation'),\n \n /** UI path */\n path: z.string().default('/api-docs').describe('URL path for documentation UI'),\n \n /** UI theme */\n theme: z.enum(['light', 'dark', 'auto']).default('light').describe('UI color theme'),\n \n /** Enable try-it-out feature */\n enableTryItOut: z.boolean().default(true).describe('Enable interactive API testing'),\n \n /** Enable filtering */\n enableFilter: z.boolean().default(true).describe('Enable endpoint filtering'),\n \n /** Enable CORS for testing */\n enableCors: z.boolean().default(true).describe('Enable CORS for browser testing'),\n \n /** Default expand depth for models */\n defaultModelsExpandDepth: z.number().int().min(-1).default(1)\n .describe('Default expand depth for schemas (-1 = fully expand)'),\n \n /** Display request duration */\n displayRequestDuration: z.boolean().default(true).describe('Show request duration'),\n \n /** Syntax highlighting */\n syntaxHighlighting: z.boolean().default(true).describe('Enable syntax highlighting'),\n \n /** Custom CSS URL */\n customCssUrl: z.string().url().optional().describe('Custom CSS stylesheet URL'),\n \n /** Custom JavaScript URL */\n customJsUrl: z.string().url().optional().describe('Custom JavaScript URL'),\n \n /** Layout options */\n layout: z.object({\n showExtensions: z.boolean().default(false).describe('Show vendor extensions'),\n showCommonExtensions: z.boolean().default(false).describe('Show common extensions'),\n deepLinking: z.boolean().default(true).describe('Enable deep linking'),\n displayOperationId: z.boolean().default(false).describe('Display operation IDs'),\n defaultModelRendering: z.enum(['example', 'model']).default('example')\n .describe('Default model rendering mode'),\n defaultModelsExpandDepth: z.number().int().default(1).describe('Models expand depth'),\n defaultModelExpandDepth: z.number().int().default(1).describe('Single model expand depth'),\n docExpansion: z.enum(['list', 'full', 'none']).default('list')\n .describe('Documentation expansion mode'),\n }).optional().describe('Layout configuration'),\n});\n\nexport type ApiTestingUiConfig = z.infer;\n\n/**\n * API Test Request Schema\n * \n * Represents a saved/example API test request.\n * \n * @example\n * ```json\n * {\n * \"name\": \"Get Customer by ID\",\n * \"description\": \"Retrieves a customer record\",\n * \"method\": \"GET\",\n * \"url\": \"/api/v1/data/customer/123\",\n * \"headers\": {\n * \"Authorization\": \"Bearer {{token}}\"\n * },\n * \"variables\": {\n * \"token\": \"sample_token\"\n * }\n * }\n * ```\n */\nexport const ApiTestRequestSchema = z.object({\n /** Request name */\n name: z.string().describe('Test request name'),\n \n /** Request description */\n description: z.string().optional().describe('Request description'),\n \n /** HTTP method */\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])\n .describe('HTTP method'),\n \n /** Request URL */\n url: z.string().describe('Request URL (can include variables)'),\n \n /** Request headers */\n headers: z.record(z.string(), z.string()).optional().default({})\n .describe('Request headers'),\n \n /** Query parameters */\n queryParams: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional().default({}).describe('Query parameters'),\n \n /** Request body */\n body: z.unknown().optional().describe('Request body'),\n \n /** Environment variables */\n variables: z.record(z.string(), z.unknown()).optional().default({})\n .describe('Template variables'),\n \n /** Expected response */\n expectedResponse: z.object({\n statusCode: z.number().int(),\n body: z.unknown().optional(),\n }).optional().describe('Expected response for validation'),\n});\n\nexport type ApiTestRequest = z.infer;\n\n/**\n * API Test Collection Schema\n * \n * Collection of test requests (similar to Postman collections).\n * \n * @example\n * ```json\n * {\n * \"name\": \"Customer API Tests\",\n * \"description\": \"Test collection for customer endpoints\",\n * \"variables\": {\n * \"baseUrl\": \"https://api.example.com\",\n * \"apiKey\": \"test_key\"\n * },\n * \"requests\": [...]\n * }\n * ```\n */\nexport const ApiTestCollectionSchema = z.object({\n /** Collection name */\n name: z.string().describe('Collection name'),\n \n /** Collection description */\n description: z.string().optional().describe('Collection description'),\n \n /** Collection variables */\n variables: z.record(z.string(), z.unknown()).optional().default({})\n .describe('Shared variables'),\n \n /** Test requests */\n requests: z.array(ApiTestRequestSchema).describe('Test requests in this collection'),\n \n /** Folders/grouping */\n folders: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n requests: z.array(ApiTestRequestSchema),\n })).optional().describe('Request folders for organization'),\n});\n\nexport type ApiTestCollection = z.infer;\n\n// ==========================================\n// API Documentation Configuration\n// ==========================================\n\n/**\n * API Changelog Entry Schema\n * \n * Documents changes in API versions.\n */\nexport const ApiChangelogEntrySchema = z.object({\n /** Version */\n version: z.string().describe('API version'),\n \n /** Release date */\n date: z.string().date().describe('Release date'),\n \n /** Changes */\n changes: z.object({\n added: z.array(z.string()).optional().default([]).describe('New features'),\n changed: z.array(z.string()).optional().default([]).describe('Changes'),\n deprecated: z.array(z.string()).optional().default([]).describe('Deprecations'),\n removed: z.array(z.string()).optional().default([]).describe('Removed features'),\n fixed: z.array(z.string()).optional().default([]).describe('Bug fixes'),\n security: z.array(z.string()).optional().default([]).describe('Security fixes'),\n }).describe('Version changes'),\n \n /** Migration guide */\n migrationGuide: z.string().optional().describe('Migration guide URL or text'),\n});\n\nexport type ApiChangelogEntry = z.infer;\n\n/**\n * Code Generation Template Schema\n * \n * Templates for generating client code.\n */\nexport const CodeGenerationTemplateSchema = z.object({\n /** Language/framework */\n language: z.string().describe('Target language/framework (e.g., typescript, python, curl)'),\n \n /** Template name */\n name: z.string().describe('Template name'),\n \n /** Template content */\n template: z.string().describe('Code template with placeholders'),\n \n /** Template variables */\n variables: z.array(z.string()).optional().describe('Required template variables'),\n});\n\nexport type CodeGenerationTemplate = z.infer;\n\n/**\n * API Documentation Configuration Schema\n * \n * Complete configuration for API documentation and testing interface.\n * \n * @example\n * ```json\n * {\n * \"enabled\": true,\n * \"title\": \"ObjectStack API Documentation\",\n * \"version\": \"1.0.0\",\n * \"description\": \"Unified API for ObjectStack platform\",\n * \"servers\": [\n * { \"url\": \"https://api.example.com\", \"description\": \"Production\" }\n * ],\n * \"ui\": {\n * \"type\": \"swagger-ui\",\n * \"theme\": \"light\",\n * \"enableTryItOut\": true\n * },\n * \"generateOpenApi\": true,\n * \"generateTestCollections\": true\n * }\n * ```\n */\nexport const ApiDocumentationConfigSchema = z.object({\n /** Enable documentation */\n enabled: z.boolean().default(true).describe('Enable API documentation'),\n \n /** Documentation title */\n title: z.string().default('API Documentation').describe('Documentation title'),\n \n /** API version */\n version: z.string().describe('API version'),\n \n /** API description */\n description: z.string().optional().describe('API description'),\n \n /** Server configurations */\n servers: z.array(OpenApiServerSchema).optional().default([])\n .describe('API server URLs'),\n \n /** UI configuration */\n ui: ApiTestingUiConfigSchema.optional().describe('Testing UI configuration'),\n \n /** Generate OpenAPI spec */\n generateOpenApi: z.boolean().default(true).describe('Generate OpenAPI 3.0 specification'),\n \n /** Generate test collections */\n generateTestCollections: z.boolean().default(true)\n .describe('Generate API test collections'),\n \n /** Test collections */\n testCollections: z.array(ApiTestCollectionSchema).optional().default([])\n .describe('Predefined test collections'),\n \n /** API changelog */\n changelog: z.array(ApiChangelogEntrySchema).optional().default([])\n .describe('API version changelog'),\n \n /** Code generation templates */\n codeTemplates: z.array(CodeGenerationTemplateSchema).optional().default([])\n .describe('Code generation templates'),\n \n /** Terms of service */\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n \n /** Contact information */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('Contact information'),\n \n /** License */\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional().describe('API license'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation link'),\n \n /** Security schemes */\n securitySchemes: z.record(z.string(), OpenApiSecuritySchemeSchema).optional()\n .describe('Security scheme definitions'),\n \n /** Global tags */\n tags: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional(),\n })).optional().describe('Global tag definitions'),\n});\n\nexport type ApiDocumentationConfig = z.infer;\n\n// ==========================================\n// API Documentation Generation\n// ==========================================\n\n/**\n * Generated API Documentation Schema\n * \n * Output of documentation generation process.\n */\nexport const GeneratedApiDocumentationSchema = z.object({\n /** OpenAPI specification */\n openApiSpec: OpenApiSpecSchema.optional().describe('Generated OpenAPI specification'),\n \n /** Test collections */\n testCollections: z.array(ApiTestCollectionSchema).optional()\n .describe('Generated test collections'),\n \n /** Markdown documentation */\n markdown: z.string().optional().describe('Generated markdown documentation'),\n \n /** HTML documentation */\n html: z.string().optional().describe('Generated HTML documentation'),\n \n /** Generation timestamp */\n generatedAt: z.string().datetime().describe('Generation timestamp'),\n \n /** Source APIs */\n sourceApis: z.array(z.string()).describe('Source API IDs used for generation'),\n});\n\nexport type GeneratedApiDocumentation = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create API documentation config\n */\nexport const ApiDocumentationConfig = Object.assign(ApiDocumentationConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API test collection\n */\nexport const ApiTestCollection = Object.assign(ApiTestCollectionSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create OpenAPI specification\n */\nexport const OpenApiSpec = Object.assign(OpenApiSpecSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Analytics/Semantic Layer Protocol\n * \n * Defines the \"Business Logic\" for data analysis.\n * Inspired by Cube.dev, LookML, and dbt MetricFlow.\n * \n * This layer decouples the \"Physical Data\" (Tables/Columns) from the \n * \"Business Data\" (Metrics/Dimensions).\n */\n\n/**\n * Aggregation Metric Type\n * The mathematical operation to perform on a metric.\n */\nexport const AggregationMetricType = z.enum([\n 'count', \n 'sum', \n 'avg', \n 'min', \n 'max', \n 'count_distinct', \n 'number', // Custom SQL expression returning a number\n 'string', // Custom SQL expression returning a string\n 'boolean' // Custom SQL expression returning a boolean\n]);\n\n/**\n * Dimension Type\n * The nature of the grouping field.\n */\nexport const DimensionType = z.enum([\n 'string', \n 'number', \n 'boolean', \n 'time', \n 'geo'\n]);\n\n/**\n * Time Interval for Time Dimensions\n */\nexport const TimeUpdateInterval = z.enum([\n 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'\n]);\n\n/**\n * Metric Schema\n * A quantitative measurement (e.g., \"Total Revenue\", \"Average Order Value\").\n */\nexport const MetricSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique metric ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: AggregationMetricType,\n \n /** Source Calculation */\n sql: z.string().describe('SQL expression or field reference'),\n \n /** Filtering for this specific metric (e.g. \"Revenue from Premium Users\") */\n filters: z.array(z.object({\n sql: z.string()\n })).optional(),\n \n /** Format for display (e.g. \"currency\", \"percent\") */\n format: z.string().optional(),\n});\n\n/**\n * Dimension Schema\n * A categorical attribute to group by (e.g., \"Product Category\", \"Order Date\").\n */\nexport const DimensionSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique dimension ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: DimensionType,\n \n /** Source Column */\n sql: z.string().describe('SQL expression or column reference'),\n \n /** For Time Dimensions: Supported Granularities */\n granularities: z.array(TimeUpdateInterval).optional(),\n});\n\n/**\n * Join Schema\n * Defines how this cube relates to others.\n */\nexport const CubeJoinSchema = z.object({\n name: z.string().describe('Target cube name'),\n relationship: z.enum(['one_to_one', 'one_to_many', 'many_to_one']).default('many_to_one'),\n sql: z.string().describe('Join condition (ON clause)'),\n});\n\n/**\n * Cube Schema\n * A logical data model representing a business entity or process for analysis.\n * Maps physical tables to business metrics and dimensions.\n */\nexport const CubeSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Cube name (snake_case)'),\n title: z.string().optional(),\n description: z.string().optional(),\n \n /** Physical Data Source */\n sql: z.string().describe('Base SQL statement or Table Name'),\n \n /** Semantic Definitions */\n measures: z.record(z.string(), MetricSchema).describe('Quantitative metrics'),\n dimensions: z.record(z.string(), DimensionSchema).describe('Qualitative attributes'),\n \n /** Relationships */\n joins: z.record(z.string(), CubeJoinSchema).optional(),\n \n /** Pre-aggregations / Caching */\n refreshKey: z.object({\n every: z.string().optional(), // e.g. \"1 hour\"\n sql: z.string().optional(), // SQL to check for data changes\n }).optional(),\n \n /** Access Control */\n public: z.boolean().default(false),\n});\n\n/**\n * Analytics Query Schema\n * The request format for the Analytics API.\n */\nexport const AnalyticsQuerySchema = z.object({\n cube: z.string().optional().describe('Target cube name (optional when provided externally, e.g. in API request wrapper)'),\n measures: z.array(z.string()).describe('List of metrics to calculate'),\n dimensions: z.array(z.string()).optional().describe('List of dimensions to group by'),\n \n filters: z.array(z.object({\n member: z.string().describe('Dimension or Measure'),\n operator: z.enum(['equals', 'notEquals', 'contains', 'notContains', 'gt', 'gte', 'lt', 'lte', 'set', 'notSet', 'inDateRange']),\n values: z.array(z.string()).optional(),\n })).optional(),\n \n timeDimensions: z.array(z.object({\n dimension: z.string(),\n granularity: TimeUpdateInterval.optional(),\n dateRange: z.union([\n z.string(), // \"Last 7 days\"\n z.array(z.string()) // [\"2023-01-01\", \"2023-01-31\"]\n ]).optional(),\n })).optional(),\n \n order: z.record(z.string(), z.enum(['asc', 'desc'])).optional(),\n \n limit: z.number().optional(),\n offset: z.number().optional(),\n \n timezone: z.string().optional().default('UTC'),\n});\n\nexport type Metric = z.infer;\nexport type Dimension = z.infer;\nexport type CubeJoin = z.infer;\nexport type Cube = z.infer;\nexport type AnalyticsQuery = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { AnalyticsQuerySchema, CubeSchema } from '../data/analytics.zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Analytics API Protocol\n * \n * Defines the HTTP interface for the Semantic Layer.\n * Provides endpoints for executing analytical queries and discovering metadata.\n */\n\n// ==========================================\n// 1. API Endpoints\n// ==========================================\n\nexport const AnalyticsEndpoint = z.enum([\n '/api/v1/analytics/query', // Execute analysis\n '/api/v1/analytics/meta', // Discover cubes/metrics\n '/api/v1/analytics/sql', // Dry-run SQL generation\n]);\n\n// ==========================================\n// 2. Query Execution\n// ==========================================\n\n/**\n * Query Request Body\n */\nexport const AnalyticsQueryRequestSchema = z.object({\n query: AnalyticsQuerySchema.describe('The analytic query definition'),\n cube: z.string().describe('Target cube name'),\n format: z.enum(['json', 'csv', 'xlsx']).default('json').describe('Response format'),\n});\n\n/**\n * Query Response (JSON)\n */\nexport const AnalyticsResultResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n rows: z.array(z.record(z.string(), z.unknown())).describe('Result rows'),\n fields: z.array(z.object({\n name: z.string(),\n type: z.string(),\n })).describe('Column metadata'),\n sql: z.string().optional().describe('Executed SQL (if debug enabled)'),\n }),\n});\n\n// ==========================================\n// 3. Metadata Discovery\n// ==========================================\n\n/**\n * Meta Request\n */\nexport const GetAnalyticsMetaRequestSchema = z.object({\n cube: z.string().optional().describe('Optional cube name to filter'),\n});\n\n/**\n * Meta Response\n * Returns available cubes, metrics, and dimensions.\n */\nexport const AnalyticsMetadataResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n cubes: z.array(CubeSchema).describe('Available cubes'),\n }),\n});\n\n// ==========================================\n// 4. SQL Dry-Run\n// ==========================================\n\nexport const AnalyticsSqlResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n sql: z.string(),\n params: z.array(z.unknown()),\n }),\n});\n\nexport type AnalyticsEndpoint = z.infer;\nexport type AnalyticsQueryRequest = z.infer;\nexport type AnalyticsMetadataResponse = z.infer;\nexport type AnalyticsSqlResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # API Versioning Protocol\n * \n * Defines how API versions are negotiated between client and server.\n * Supports multiple versioning strategies and deprecation lifecycle management.\n * \n * Architecture Alignment:\n * - Salesforce: URL path versioning (v57.0, v58.0)\n * - Stripe: Date-based versioning (2024-01-01)\n * - Kubernetes: API group versioning (v1, v1beta1)\n * - GitHub: Accept header versioning (application/vnd.github.v3+json)\n * - Microsoft Graph: URL path versioning (v1.0, beta)\n */\n\n// ==========================================\n// Versioning Strategy\n// ==========================================\n\n/**\n * API Versioning Strategy\n * Determines how the API version is specified by clients.\n * \n * - `urlPath`: Version in URL path (e.g., /api/v1/data) — Most common, easy to understand\n * - `header`: Version in Accept header (e.g., Accept: application/vnd.objectstack.v1+json)\n * - `queryParam`: Version in query parameter (e.g., /api/data?version=v1)\n * - `dateBased`: Date-based version in header (e.g., ObjectStack-Version: 2025-01-01) — Stripe-style\n */\nexport const VersioningStrategy = z.enum([\n 'urlPath',\n 'header',\n 'queryParam',\n 'dateBased',\n]);\n\nexport type VersioningStrategy = z.infer;\n\n// ==========================================\n// Version Lifecycle\n// ==========================================\n\n/**\n * API Version Status\n * Lifecycle state of an API version.\n * \n * - `preview`: Available for testing, may change without notice (e.g., v2beta1)\n * - `current`: The recommended stable version\n * - `supported`: Older but still maintained (receives security fixes)\n * - `deprecated`: Scheduled for removal, clients should migrate\n * - `retired`: No longer available, requests return 410 Gone\n */\nexport const VersionStatus = z.enum([\n 'preview',\n 'current',\n 'supported',\n 'deprecated',\n 'retired',\n]);\n\nexport type VersionStatus = z.infer;\n\n// ==========================================\n// Version Definition\n// ==========================================\n\n/**\n * API Version Definition Schema\n * Describes a single API version and its lifecycle metadata.\n * \n * @example\n * {\n * \"version\": \"v1\",\n * \"status\": \"current\",\n * \"releasedAt\": \"2025-01-15\",\n * \"description\": \"Initial stable release\"\n * }\n * \n * @example Deprecated version\n * {\n * \"version\": \"v0\",\n * \"status\": \"deprecated\",\n * \"releasedAt\": \"2024-06-01\",\n * \"deprecatedAt\": \"2025-01-15\",\n * \"sunsetAt\": \"2025-07-15\",\n * \"migrationGuide\": \"https://docs.objectstack.dev/migrate/v0-to-v1\",\n * \"description\": \"Legacy API version\"\n * }\n */\nexport const VersionDefinitionSchema = z.object({\n /** Version identifier (e.g., \"v1\", \"v2beta1\", \"2025-01-01\") */\n version: z.string().describe('Version identifier (e.g., \"v1\", \"v2beta1\", \"2025-01-01\")'),\n\n /** Current lifecycle status */\n status: VersionStatus.describe('Lifecycle status of this version'),\n\n /** Date this version was released (ISO 8601 date) */\n releasedAt: z.string().describe('Release date (ISO 8601, e.g., \"2025-01-15\")'),\n\n /** Date this version was deprecated (ISO 8601 date) */\n deprecatedAt: z.string().optional()\n .describe('Deprecation date (ISO 8601). Only set for deprecated/retired versions'),\n\n /** Date this version will be retired (ISO 8601 date) */\n sunsetAt: z.string().optional()\n .describe('Sunset date (ISO 8601). After this date, the version returns 410 Gone'),\n\n /** URL to migration guide for moving to a newer version */\n migrationGuide: z.string().url().optional()\n .describe('URL to migration guide for upgrading from this version'),\n\n /** Human-readable description of this version */\n description: z.string().optional()\n .describe('Human-readable description or release notes summary'),\n\n /** Breaking changes introduced in or since this version */\n breakingChanges: z.array(z.string()).optional()\n .describe('List of breaking changes (for preview/new versions)'),\n});\n\nexport type VersionDefinition = z.infer;\n\n// ==========================================\n// Versioning Configuration\n// ==========================================\n\n/**\n * API Versioning Configuration Schema\n * Complete configuration for API version management.\n * \n * @example\n * {\n * \"strategy\": \"urlPath\",\n * \"current\": \"v1\",\n * \"default\": \"v1\",\n * \"versions\": [\n * { \"version\": \"v1\", \"status\": \"current\", \"releasedAt\": \"2025-01-15\" },\n * { \"version\": \"v2beta1\", \"status\": \"preview\", \"releasedAt\": \"2025-06-01\" }\n * ],\n * \"deprecation\": {\n * \"warnHeader\": true,\n * \"sunsetHeader\": true\n * }\n * }\n */\nexport const VersioningConfigSchema = z.object({\n /** Versioning strategy */\n strategy: VersioningStrategy.default('urlPath')\n .describe('How the API version is specified by clients'),\n\n /** Current (recommended) API version */\n current: z.string().describe('The current/recommended API version identifier'),\n\n /** Default version when none specified by client */\n default: z.string().describe('Fallback version when client does not specify one'),\n\n /** All available API versions */\n versions: z.array(VersionDefinitionSchema)\n .min(1)\n .describe('All available API versions with lifecycle metadata'),\n\n /** Header name for header-based versioning */\n headerName: z.string().default('ObjectStack-Version')\n .describe('HTTP header name for version negotiation (header/dateBased strategies)'),\n\n /** Query parameter name for queryParam strategy */\n queryParamName: z.string().default('version')\n .describe('Query parameter name for version specification (queryParam strategy)'),\n\n /** URL prefix pattern for urlPath strategy */\n urlPrefix: z.string().default('/api')\n .describe('URL prefix before version segment (urlPath strategy)'),\n\n /** Deprecation behavior */\n deprecation: z.object({\n /** Include Deprecation header in responses for deprecated versions */\n warnHeader: z.boolean().default(true)\n .describe('Include Deprecation header (RFC 8594) in responses'),\n\n /** Include Sunset header with retirement date */\n sunsetHeader: z.boolean().default(true)\n .describe('Include Sunset header (RFC 8594) with retirement date'),\n\n /** Include Link header pointing to migration guide */\n linkHeader: z.boolean().default(true)\n .describe('Include Link header pointing to migration guide URL'),\n\n /** Whether to reject requests to retired versions */\n rejectRetired: z.boolean().default(true)\n .describe('Return 410 Gone for retired API versions'),\n\n /** Custom deprecation warning message */\n warningMessage: z.string().optional()\n .describe('Custom warning message for deprecated version responses'),\n }).optional().describe('Deprecation lifecycle behavior'),\n\n /** Whether to include version info in discovery response */\n includeInDiscovery: z.boolean().default(true)\n .describe('Include version information in the API discovery endpoint'),\n});\n\nexport type VersioningConfig = z.infer;\nexport type VersioningConfigInput = z.input;\n\n// ==========================================\n// Version Negotiation Response\n// ==========================================\n\n/**\n * Version Negotiation Response Schema\n * Returned when a client requests version information or\n * included in the discovery endpoint response.\n * \n * @example\n * {\n * \"current\": \"v1\",\n * \"requested\": \"v1\",\n * \"resolved\": \"v1\",\n * \"supported\": [\"v1\", \"v2beta1\"],\n * \"deprecated\": [\"v0\"],\n * \"versions\": [...]\n * }\n */\nexport const VersionNegotiationResponseSchema = z.object({\n /** The current/recommended version */\n current: z.string().describe('Current recommended API version'),\n\n /** The version the client requested (if any) */\n requested: z.string().optional().describe('Version requested by the client'),\n\n /** The version actually being used for this request */\n resolved: z.string().describe('Resolved API version for this request'),\n\n /** All supported (non-retired) version identifiers */\n supported: z.array(z.string()).describe('All supported version identifiers'),\n\n /** Deprecated version identifiers (still functional but will be removed) */\n deprecated: z.array(z.string()).optional()\n .describe('Deprecated version identifiers'),\n\n /** Full version definitions (optional, for detailed clients) */\n versions: z.array(VersionDefinitionSchema).optional()\n .describe('Full version definitions with lifecycle metadata'),\n});\n\nexport type VersionNegotiationResponse = z.infer;\n\n// ==========================================\n// Default Versioning Configuration\n// ==========================================\n\n/**\n * Default versioning configuration for ObjectStack.\n * Uses URL path strategy with v1 as the current/default version.\n */\nexport const DEFAULT_VERSIONING_CONFIG: VersioningConfigInput = {\n strategy: 'urlPath',\n current: 'v1',\n default: 'v1',\n versions: [\n {\n version: 'v1',\n status: 'current',\n releasedAt: '2025-01-15',\n description: 'ObjectStack API v1 — Initial stable release',\n },\n ],\n deprecation: {\n warnHeader: true,\n sunsetHeader: true,\n linkHeader: true,\n rejectRetired: true,\n },\n includeInDiscovery: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Authentication Service Protocol\n * \n * Defines the standard API contracts for Identity, Session Management,\n * and Access Control.\n */\n\n// ==========================================\n// Authentication Types\n// ==========================================\n\nexport const AuthProvider = z.enum([\n 'local',\n 'google',\n 'github',\n 'microsoft',\n 'ldap',\n 'saml'\n]);\n\nexport const SessionUserSchema = z.object({\n id: z.string().describe('User ID'),\n email: z.string().email().describe('Email address'),\n emailVerified: z.boolean().default(false).describe('Is email verified?'),\n name: z.string().describe('Display name'),\n image: z.string().optional().describe('Avatar URL'),\n username: z.string().optional().describe('Username (optional)'),\n roles: z.array(z.string()).optional().default([]).describe('Assigned role IDs'),\n tenantId: z.string().optional().describe('Current tenant ID'),\n language: z.string().default('en').describe('Preferred language'),\n timezone: z.string().optional().describe('Preferred timezone'),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n});\n\nexport const SessionSchema = z.object({\n id: z.string(),\n expiresAt: z.string().datetime(),\n token: z.string().optional(),\n ipAddress: z.string().optional(),\n userAgent: z.string().optional(),\n userId: z.string(),\n});\n\n// ==========================================\n// Requests\n// ==========================================\n\nexport const LoginType = z.enum(['email', 'username', 'phone', 'magic-link', 'social']);\n\nexport const LoginRequestSchema = z.object({\n type: LoginType.default('email').describe('Login method'),\n email: z.string().email().optional().describe('Required for email/magic-link'),\n username: z.string().optional().describe('Required for username login'),\n password: z.string().optional().describe('Required for password login'),\n provider: z.string().optional().describe('Required for social (google, github)'),\n redirectTo: z.string().optional().describe('Redirect URL after successful login'),\n});\n\nexport const RegisterRequestSchema = z.object({\n email: z.string().email(),\n password: z.string(),\n name: z.string(),\n image: z.string().optional(),\n});\n\nexport const RefreshTokenRequestSchema = z.object({\n refreshToken: z.string().describe('Refresh token'),\n});\n\n// ==========================================\n// Responses\n// ==========================================\n\nexport const SessionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n session: SessionSchema.describe('Active Session Info'),\n user: SessionUserSchema.describe('Current User Details'),\n token: z.string().optional().describe('Bearer token if not using cookies'),\n }),\n});\n\nexport const UserProfileResponseSchema = BaseResponseSchema.extend({\n data: SessionUserSchema,\n});\n\nexport type AuthProvider = z.infer;\nexport type SessionUser = z.infer;\nexport type SessionUserInput = z.input;\nexport type Session = z.infer;\nexport type LoginType = z.infer;\nexport type LoginRequest = z.infer;\nexport type LoginRequestInput = z.input;\nexport type RegisterRequest = z.infer;\nexport type RefreshTokenRequest = z.infer;\nexport type SessionResponse = z.infer;\nexport type UserProfileResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Authentication Endpoint Specification\n * \n * Defines the canonical HTTP endpoints for the authentication service.\n * Based on better-auth v1.4.18 endpoint conventions.\n * \n * NOTE: ObjectStack's auth implementation uses better-auth library which has\n * established endpoint conventions. This spec documents those conventions as\n * the canonical API contract.\n */\n\n// ==========================================\n// Endpoint Path Definitions\n// ==========================================\n\n/**\n * Authentication Endpoint Paths\n * \n * These are the paths relative to the auth base route (e.g., /api/v1/auth).\n * Based on better-auth's endpoint structure.\n */\nexport const AuthEndpointPaths = {\n // Email/Password Authentication\n signInEmail: '/sign-in/email',\n signUpEmail: '/sign-up/email',\n signOut: '/sign-out',\n \n // Session Management\n getSession: '/get-session',\n \n // Password Management\n forgetPassword: '/forget-password',\n resetPassword: '/reset-password',\n \n // Email Verification\n sendVerificationEmail: '/send-verification-email',\n verifyEmail: '/verify-email',\n \n // OAuth (dynamic based on provider)\n // authorize: '/authorize/:provider'\n // callback: '/callback/:provider'\n \n // 2FA (when enabled)\n twoFactorEnable: '/two-factor/enable',\n twoFactorVerify: '/two-factor/verify',\n \n // Passkeys (when enabled)\n passkeyRegister: '/passkey/register',\n passkeyAuthenticate: '/passkey/authenticate',\n \n // Magic Links (when enabled)\n magicLinkSend: '/magic-link/send',\n magicLinkVerify: '/magic-link/verify',\n} as const;\n\n/**\n * HTTP Method + Path Specification\n * \n * Defines the complete HTTP contract for each endpoint.\n */\nexport const AuthEndpointSchema = z.object({\n /** Sign in with email and password */\n signInEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signInEmail),\n description: z.literal('Sign in with email and password'),\n }),\n \n /** Register new user with email and password */\n signUpEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signUpEmail),\n description: z.literal('Register new user with email and password'),\n }),\n \n /** Sign out current user */\n signOut: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signOut),\n description: z.literal('Sign out current user'),\n }),\n \n /** Get current user session */\n getSession: z.object({\n method: z.literal('GET'),\n path: z.literal(AuthEndpointPaths.getSession),\n description: z.literal('Get current user session'),\n }),\n \n /** Request password reset email */\n forgetPassword: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.forgetPassword),\n description: z.literal('Request password reset email'),\n }),\n \n /** Reset password with token */\n resetPassword: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.resetPassword),\n description: z.literal('Reset password with token'),\n }),\n \n /** Send email verification */\n sendVerificationEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.sendVerificationEmail),\n description: z.literal('Send email verification link'),\n }),\n \n /** Verify email with token */\n verifyEmail: z.object({\n method: z.literal('GET'),\n path: z.literal(AuthEndpointPaths.verifyEmail),\n description: z.literal('Verify email with token'),\n }),\n});\n\n/**\n * Endpoint Aliases\n * \n * Common aliases for better developer experience.\n * These map to the canonical better-auth endpoints.\n */\nexport const AuthEndpointAliases = {\n login: AuthEndpointPaths.signInEmail,\n register: AuthEndpointPaths.signUpEmail,\n logout: AuthEndpointPaths.signOut,\n me: AuthEndpointPaths.getSession,\n} as const;\n\n/**\n * Full Endpoint URLs\n * \n * Helper to construct full endpoint URLs given a base path.\n */\nexport function getAuthEndpointUrl(basePath: string, endpoint: keyof typeof AuthEndpointPaths): string {\n const cleanBase = basePath.replace(/\\/$/, '');\n return `${cleanBase}${AuthEndpointPaths[endpoint]}`;\n}\n\n/**\n * Endpoint Mapping\n * \n * Maps common/legacy endpoint names to canonical better-auth paths.\n * This allows clients to use simpler names while maintaining compatibility.\n */\nexport const EndpointMapping = {\n '/login': AuthEndpointPaths.signInEmail,\n '/register': AuthEndpointPaths.signUpEmail,\n '/logout': AuthEndpointPaths.signOut,\n '/me': AuthEndpointPaths.getSession,\n '/refresh': AuthEndpointPaths.getSession, // Session refresh handled by better-auth automatically\n} as const;\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type AuthEndpoint = z.infer;\nexport type AuthEndpointPath = typeof AuthEndpointPaths[keyof typeof AuthEndpointPaths];\nexport type AuthEndpointAlias = keyof typeof AuthEndpointAliases;\nexport type EndpointMappingKey = keyof typeof EndpointMapping;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Object Storage Protocol\n * \n * Unified storage protocol that combines:\n * - Object storage systems (S3, Azure Blob, GCS, MinIO)\n * - Scoped storage configuration (temp, cache, data, logs, config, public)\n * - Multi-cloud storage providers\n * - Bucket/container configuration\n * - Access control and permissions\n * - Lifecycle policies for data retention\n * - Presigned URLs for secure direct access\n * - Multipart uploads for large files\n */\n\n// ============================================================================\n// Storage Scope Protocol (formerly from scoped-storage.zod.ts)\n// ============================================================================\n\n/**\n * Storage Scope Enum\n * Defines the lifecycle and persistence guarantee of the storage area.\n */\nexport const StorageScopeSchema = z.enum([\n 'global', // Global application-wide storage\n 'tenant', // Tenant-scoped storage (multi-tenant apps)\n 'user', // User-scoped storage\n 'session', // Session-scoped storage (ephemeral)\n 'temp', // Ephemeral, cleared on restart\n 'cache', // Ephemeral, survives restarts, cleared on LRU/Expiration\n 'data', // Persistent, backed up\n 'logs', // Append-only, rotated\n 'config', // Read-heavy, versioned\n 'public' // Publicly accessible static assets\n]).describe('Storage scope classification');\n\nexport type StorageScope = z.infer;\n\n/**\n * File Metadata Schema\n * Standardized file attribute structure\n */\nexport const FileMetadataSchema = z.object({\n path: z.string().describe('File path'),\n name: z.string().describe('File name'),\n size: z.number().int().describe('File size in bytes'),\n mimeType: z.string().describe('MIME type'),\n lastModified: z.string().datetime().describe('Last modified timestamp'),\n created: z.string().datetime().describe('Creation timestamp'),\n etag: z.string().optional().describe('Entity tag'),\n});\n\nexport type FileMetadata = z.infer;\n\n// ============================================================================\n// Enums\n// ============================================================================\n\n/**\n * Storage Provider Types\n * \n * Supported cloud and self-hosted object storage providers.\n */\nexport const StorageProviderSchema = z.enum([\n 's3', // Amazon S3\n 'azure_blob', // Azure Blob Storage\n 'gcs', // Google Cloud Storage\n 'minio', // MinIO (self-hosted S3-compatible)\n 'r2', // Cloudflare R2\n 'spaces', // DigitalOcean Spaces\n 'wasabi', // Wasabi Hot Cloud Storage\n 'backblaze', // Backblaze B2\n 'local', // Local filesystem (development only)\n]).describe('Storage provider type');\n\nexport type StorageProvider = z.infer;\n\n/**\n * Storage Access Control List (ACL)\n * \n * Predefined access control configurations for objects and buckets.\n */\nexport const StorageAclSchema = z.enum([\n 'private', // Owner has full control, no one else has access\n 'public_read', // Owner has full control, everyone can read\n 'public_read_write', // Owner has full control, everyone can read/write (not recommended)\n 'authenticated_read', // Owner has full control, authenticated users can read\n 'bucket_owner_read', // Object owner has full control, bucket owner can read\n 'bucket_owner_full_control', // Both object and bucket owner have full control\n]).describe('Storage access control level');\n\nexport type StorageAcl = z.infer;\n\n/**\n * Storage Class / Tier\n * \n * Different storage tiers for cost optimization.\n * Maps to provider-specific storage classes.\n */\nexport const StorageClassSchema = z.enum([\n 'standard', // Standard/hot storage for frequently accessed data\n 'intelligent', // Intelligent tiering (auto-moves between hot/cool)\n 'infrequent_access', // Infrequent access/cool storage\n 'glacier', // Archive/cold storage (slower retrieval)\n 'deep_archive', // Deep archive (cheapest, slowest retrieval)\n]).describe('Storage class/tier for cost optimization');\n\nexport type StorageClass = z.infer;\n\n/**\n * Lifecycle Transition Action\n */\nexport const LifecycleActionSchema = z.enum([\n 'transition', // Move to different storage class\n 'delete', // Delete the object\n 'abort', // Abort incomplete multipart uploads\n]).describe('Lifecycle policy action type');\n\nexport type LifecycleAction = z.infer;\n\n// ============================================================================\n// Configuration Schemas\n// ============================================================================\n\n/**\n * Object Metadata Schema\n * \n * Standard and custom metadata attached to stored objects.\n * \n * @example\n * {\n * contentType: 'image/jpeg',\n * contentLength: 1024000,\n * etag: '\"abc123\"',\n * lastModified: new Date('2024-01-01'),\n * custom: {\n * uploadedBy: 'user123',\n * department: 'marketing'\n * }\n * }\n */\nexport const ObjectMetadataSchema = z.object({\n contentType: z.string().describe('MIME type (e.g., image/jpeg, application/pdf)'),\n contentLength: z.number().min(0).describe('File size in bytes'),\n contentEncoding: z.string().optional().describe('Content encoding (e.g., gzip)'),\n contentDisposition: z.string().optional().describe('Content disposition header'),\n contentLanguage: z.string().optional().describe('Content language'),\n cacheControl: z.string().optional().describe('Cache control directives'),\n etag: z.string().optional().describe('Entity tag for versioning/caching'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n versionId: z.string().optional().describe('Object version identifier'),\n storageClass: StorageClassSchema.optional().describe('Storage class/tier'),\n encryption: z.object({\n algorithm: z.string().describe('Encryption algorithm (e.g., AES256, aws:kms)'),\n keyId: z.string().optional().describe('KMS key ID if using managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n custom: z.record(z.string(), z.string()).optional().describe('Custom user-defined metadata'),\n});\n\nexport type ObjectMetadata = z.infer;\n\n/**\n * Presigned URL Configuration\n * \n * Configuration for generating temporary URLs for direct access to objects.\n * Useful for secure file uploads/downloads without exposing credentials.\n * \n * @example\n * // Generate download URL valid for 1 hour\n * {\n * operation: 'get',\n * expiresIn: 3600,\n * contentType: 'image/jpeg'\n * }\n * \n * @example\n * // Generate upload URL valid for 15 minutes with size limit\n * {\n * operation: 'put',\n * expiresIn: 900,\n * contentType: 'application/pdf',\n * maxSize: 10485760\n * }\n */\nexport const PresignedUrlConfigSchema = z.object({\n operation: z.enum(['get', 'put', 'delete', 'head']).describe('Allowed operation'),\n expiresIn: z.number().min(1).max(604800).describe('Expiration time in seconds (max 7 days)'),\n contentType: z.string().optional().describe('Required content type for PUT operations'),\n maxSize: z.number().min(0).optional().describe('Maximum file size in bytes for PUT operations'),\n responseContentType: z.string().optional().describe('Override content-type for GET operations'),\n responseContentDisposition: z.string().optional().describe('Override content-disposition for GET operations'),\n});\n\nexport type PresignedUrlConfig = z.infer;\n\n/**\n * Multipart Upload Configuration\n * \n * Configuration for chunked uploads of large files.\n * Enables resumable uploads and parallel transfer.\n * \n * @example\n * // Enable multipart for files > 100MB with 10MB chunks\n * {\n * enabled: true,\n * partSize: 10485760,\n * maxParts: 10000,\n * threshold: 104857600,\n * maxConcurrent: 4\n * }\n */\nexport const MultipartUploadConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable multipart uploads'),\n partSize: z.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe('Part size in bytes (min 5MB, max 5GB)'),\n maxParts: z.number().min(1).max(10000).default(10000).describe('Maximum number of parts (max 10,000)'),\n threshold: z.number().min(0).default(100 * 1024 * 1024).describe('File size threshold to trigger multipart upload (bytes)'),\n maxConcurrent: z.number().min(1).max(100).default(4).describe('Maximum concurrent part uploads'),\n abortIncompleteAfterDays: z.number().min(1).optional().describe('Auto-abort incomplete uploads after N days'),\n});\n\nexport type MultipartUploadConfig = z.infer;\n\n/**\n * Access Control Configuration\n * \n * Fine-grained access control for buckets and objects.\n * \n * @example\n * {\n * acl: 'private',\n * allowedOrigins: ['https://app.example.com'],\n * allowedMethods: ['GET', 'PUT'],\n * corsEnabled: true,\n * publicAccess: {\n * allowPublicRead: false,\n * allowPublicWrite: false\n * }\n * }\n */\nexport const AccessControlConfigSchema = z.object({\n acl: StorageAclSchema.default('private').describe('Default access control level'),\n allowedOrigins: z.array(z.string()).optional().describe('CORS allowed origins'),\n allowedMethods: z.array(z.enum(['GET', 'PUT', 'POST', 'DELETE', 'HEAD'])).optional().describe('CORS allowed HTTP methods'),\n allowedHeaders: z.array(z.string()).optional().describe('CORS allowed headers'),\n exposeHeaders: z.array(z.string()).optional().describe('CORS exposed headers'),\n maxAge: z.number().min(0).optional().describe('CORS preflight cache duration in seconds'),\n corsEnabled: z.boolean().default(false).describe('Enable CORS configuration'),\n publicAccess: z.object({\n allowPublicRead: z.boolean().default(false).describe('Allow public read access'),\n allowPublicWrite: z.boolean().default(false).describe('Allow public write access'),\n allowPublicList: z.boolean().default(false).describe('Allow public bucket listing'),\n }).optional().describe('Public access control'),\n allowedIps: z.array(z.string()).optional().describe('Allowed IP addresses/CIDR blocks'),\n blockedIps: z.array(z.string()).optional().describe('Blocked IP addresses/CIDR blocks'),\n});\n\nexport type AccessControlConfig = z.infer;\n\n/**\n * Lifecycle Policy Rule\n * \n * Individual rule for automatic object lifecycle management.\n * \n * @example\n * // Transition to infrequent access after 30 days\n * {\n * id: 'move_to_ia',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 30,\n * targetStorageClass: 'infrequent_access'\n * }\n * \n * @example\n * // Delete objects after 365 days\n * {\n * id: 'delete_old',\n * enabled: true,\n * action: 'delete',\n * daysAfterCreation: 365\n * }\n */\nexport const LifecyclePolicyRuleSchema = z.object({\n id: SystemIdentifierSchema.describe('Rule identifier'),\n enabled: z.boolean().default(true).describe('Enable this rule'),\n action: LifecycleActionSchema.describe('Action to perform'),\n prefix: z.string().optional().describe('Object key prefix filter (e.g., \"uploads/\")'),\n tags: z.record(z.string(), z.string()).optional().describe('Object tag filters'),\n daysAfterCreation: z.number().min(0).optional().describe('Days after object creation'),\n daysAfterModification: z.number().min(0).optional().describe('Days after last modification'),\n targetStorageClass: StorageClassSchema.optional().describe('Target storage class for transition action'),\n}).refine((data) => {\n // Validate that transition action has targetStorageClass\n if (data.action === 'transition' && !data.targetStorageClass) {\n return false;\n }\n return true;\n}, {\n message: 'targetStorageClass is required when action is \"transition\"',\n});\n\nexport type LifecyclePolicyRule = z.infer;\n\n/**\n * Lifecycle Policy Configuration\n * \n * Collection of lifecycle rules for automatic data management.\n * \n * @example\n * {\n * enabled: true,\n * rules: [\n * {\n * id: 'archive_old_files',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 90,\n * targetStorageClass: 'glacier'\n * },\n * {\n * id: 'delete_temp_files',\n * enabled: true,\n * action: 'delete',\n * prefix: 'temp/',\n * daysAfterCreation: 7\n * }\n * ]\n * }\n */\nexport const LifecyclePolicyConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable lifecycle policies'),\n rules: z.array(LifecyclePolicyRuleSchema).default([]).describe('Lifecycle rules'),\n});\n\nexport type LifecyclePolicyConfig = z.infer;\n\n/**\n * Bucket Configuration Schema\n * \n * Comprehensive configuration for a storage bucket/container.\n * \n * @example\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'my-app-uploads',\n * region: 'us-east-1',\n * provider: 's3',\n * versioning: true,\n * accessControl: {\n * acl: 'private',\n * corsEnabled: true,\n * allowedOrigins: ['https://app.example.com']\n * },\n * multipartConfig: {\n * enabled: true,\n * threshold: 104857600\n * }\n * }\n */\nexport const BucketConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Bucket identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n bucketName: z.string().describe('Actual bucket/container name in storage provider'),\n region: z.string().optional().describe('Storage region (e.g., us-east-1, westus)'),\n provider: StorageProviderSchema.describe('Storage provider'),\n endpoint: z.string().optional().describe('Custom endpoint URL (for S3-compatible providers)'),\n pathStyle: z.boolean().default(false).describe('Use path-style URLs (for S3-compatible providers)'),\n \n versioning: z.boolean().default(false).describe('Enable object versioning'),\n encryption: z.object({\n enabled: z.boolean().default(false).describe('Enable server-side encryption'),\n algorithm: z.enum(['AES256', 'aws:kms', 'azure:kms', 'gcp:kms']).default('AES256').describe('Encryption algorithm'),\n kmsKeyId: z.string().optional().describe('KMS key ID for managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n \n accessControl: AccessControlConfigSchema.optional().describe('Access control configuration'),\n lifecyclePolicy: LifecyclePolicyConfigSchema.optional().describe('Lifecycle policy configuration'),\n multipartConfig: MultipartUploadConfigSchema.optional().describe('Multipart upload configuration'),\n \n tags: z.record(z.string(), z.string()).optional().describe('Bucket tags for organization'),\n description: z.string().optional().describe('Bucket description'),\n enabled: z.boolean().default(true).describe('Enable this bucket'),\n});\n\nexport type BucketConfig = z.infer;\n\n/**\n * Storage Connection Configuration\n * \n * Provider-specific connection credentials and settings.\n * \n * @example S3\n * {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * sessionToken: '${AWS_SESSION_TOKEN}',\n * region: 'us-east-1'\n * }\n * \n * @example Azure\n * {\n * accountName: 'mystorageaccount',\n * accountKey: '${AZURE_STORAGE_KEY}',\n * endpoint: 'https://mystorageaccount.blob.core.windows.net'\n * }\n */\nexport const StorageConnectionSchema = z.object({\n // AWS S3 / MinIO\n accessKeyId: z.string().optional().describe('AWS access key ID or MinIO access key'),\n secretAccessKey: z.string().optional().describe('AWS secret access key or MinIO secret key'),\n sessionToken: z.string().optional().describe('AWS session token for temporary credentials'),\n \n // Azure Blob Storage\n accountName: z.string().optional().describe('Azure storage account name'),\n accountKey: z.string().optional().describe('Azure storage account key'),\n sasToken: z.string().optional().describe('Azure SAS token'),\n \n // Google Cloud Storage\n projectId: z.string().optional().describe('GCP project ID'),\n credentials: z.string().optional().describe('GCP service account credentials JSON'),\n \n // Common\n endpoint: z.string().optional().describe('Custom endpoint URL'),\n region: z.string().optional().describe('Default region'),\n useSSL: z.boolean().default(true).describe('Use SSL/TLS for connections'),\n timeout: z.number().min(0).optional().describe('Connection timeout in milliseconds'),\n});\n\nexport type StorageConnection = z.infer;\n\n/**\n * Object Storage Configuration\n * \n * Complete object storage system configuration.\n * \n * @example\n * {\n * name: 'production_storage',\n * label: 'Production File Storage',\n * provider: 's3',\n * scope: 'global',\n * connection: {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * region: 'us-east-1'\n * },\n * buckets: [\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'prod-uploads',\n * provider: 's3',\n * region: 'us-east-1'\n * }\n * ],\n * defaultBucket: 'user_uploads'\n * }\n */\nexport const ObjectStorageConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Storage configuration identifier'),\n label: z.string().describe('Display label'),\n provider: StorageProviderSchema.describe('Primary storage provider'),\n \n /**\n * Storage scope\n * Defines the lifecycle and access pattern for this storage\n */\n scope: StorageScopeSchema.optional().default('global').describe('Storage scope'),\n \n connection: StorageConnectionSchema.describe('Connection credentials'),\n buckets: z.array(BucketConfigSchema).default([]).describe('Configured buckets'),\n defaultBucket: z.string().optional().describe('Default bucket name for operations'),\n \n /**\n * Base path or location\n * For local/scoped storage configurations\n */\n location: z.string().optional().describe('Root path (local) or base location'),\n \n /**\n * Storage quota in bytes\n */\n quota: z.number().int().positive().optional().describe('Max size in bytes'),\n \n /**\n * Provider-specific options\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Provider-specific configuration options'),\n \n enabled: z.boolean().default(true).describe('Enable this storage configuration'),\n description: z.string().optional().describe('Configuration description'),\n});\n\nexport type ObjectStorageConfig = z.infer;\n\n// ============================================================================\n// Helper Examples\n// ============================================================================\n\n/**\n * Example: AWS S3 Configuration\n */\nexport const s3StorageExample = ObjectStorageConfigSchema.parse({\n name: 'aws_s3_storage',\n label: 'AWS S3 Production Storage',\n provider: 's3',\n connection: {\n accessKeyId: '${AWS_ACCESS_KEY_ID}',\n secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n region: 'us-east-1',\n },\n buckets: [\n {\n name: 'user_uploads',\n label: 'User Uploads',\n bucketName: 'my-app-user-uploads',\n region: 'us-east-1',\n provider: 's3',\n versioning: true,\n encryption: {\n enabled: true,\n algorithm: 'aws:kms',\n kmsKeyId: '${AWS_KMS_KEY_ID}',\n },\n accessControl: {\n acl: 'private',\n corsEnabled: true,\n allowedOrigins: ['https://app.example.com'],\n allowedMethods: ['GET', 'PUT', 'POST'],\n },\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'archive_old_uploads',\n enabled: true,\n action: 'transition',\n daysAfterCreation: 90,\n targetStorageClass: 'glacier',\n },\n ],\n },\n multipartConfig: {\n enabled: true,\n partSize: 10 * 1024 * 1024,\n threshold: 100 * 1024 * 1024,\n maxConcurrent: 4,\n },\n },\n ],\n defaultBucket: 'user_uploads',\n enabled: true,\n});\n\n/**\n * Example: MinIO Configuration\n */\nexport const minioStorageExample = ObjectStorageConfigSchema.parse({\n name: 'minio_local',\n label: 'MinIO Local Storage',\n provider: 'minio',\n connection: {\n accessKeyId: 'minioadmin',\n secretAccessKey: 'minioadmin',\n endpoint: 'http://localhost:9000',\n useSSL: false,\n },\n buckets: [\n {\n name: 'development_files',\n label: 'Development Files',\n bucketName: 'dev-files',\n provider: 'minio',\n endpoint: 'http://localhost:9000',\n pathStyle: true,\n accessControl: {\n acl: 'private',\n },\n },\n ],\n defaultBucket: 'development_files',\n enabled: true,\n});\n\n/**\n * Example: Azure Blob Storage Configuration\n */\nexport const azureBlobStorageExample = ObjectStorageConfigSchema.parse({\n name: 'azure_blob_storage',\n label: 'Azure Blob Storage',\n provider: 'azure_blob',\n connection: {\n accountName: 'mystorageaccount',\n accountKey: '${AZURE_STORAGE_KEY}',\n endpoint: 'https://mystorageaccount.blob.core.windows.net',\n },\n buckets: [\n {\n name: 'media_files',\n label: 'Media Files',\n bucketName: 'media',\n provider: 'azure_blob',\n region: 'eastus',\n accessControl: {\n acl: 'public_read',\n publicAccess: {\n allowPublicRead: true,\n allowPublicWrite: false,\n allowPublicList: false,\n },\n },\n },\n ],\n defaultBucket: 'media_files',\n enabled: true,\n});\n\n/**\n * Example: Google Cloud Storage Configuration\n */\nexport const gcsStorageExample = ObjectStorageConfigSchema.parse({\n name: 'gcs_storage',\n label: 'Google Cloud Storage',\n provider: 'gcs',\n connection: {\n projectId: 'my-gcp-project',\n credentials: '${GCP_SERVICE_ACCOUNT_JSON}',\n },\n buckets: [\n {\n name: 'backup_storage',\n label: 'Backup Storage',\n bucketName: 'my-app-backups',\n region: 'us-central1',\n provider: 'gcs',\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'delete_old_backups',\n enabled: true,\n action: 'delete',\n daysAfterCreation: 30,\n },\n ],\n },\n },\n ],\n defaultBucket: 'backup_storage',\n enabled: true,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { FileMetadataSchema } from '../system/object-storage.zod';\n\n/**\n * Storage Service Protocol\n * \n * Defines the API contract for client-side file operations.\n * Focuses on secure, direct-to-cloud uploads (Presigned URLs)\n * rather than proxying bytes through the API server.\n */\n\n// ==========================================\n// Requests\n// ==========================================\n\nexport const GetPresignedUrlRequestSchema = z.object({\n filename: z.string().describe('Original filename'),\n mimeType: z.string().describe('File MIME type'),\n size: z.number().describe('File size in bytes'),\n scope: z.string().default('user').describe('Target storage scope (e.g. user, private, public)'),\n bucket: z.string().optional().describe('Specific bucket override (admin only)'),\n});\n\nexport const CompleteUploadRequestSchema = z.object({\n fileId: z.string().describe('File ID returned from presigned request'),\n eTag: z.string().optional().describe('S3 ETag verification'),\n});\n\n// ==========================================\n// Responses\n// ==========================================\n\nexport const PresignedUrlResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadUrl: z.string().describe('PUT/POST URL for direct upload'),\n downloadUrl: z.string().optional().describe('Public/Private preview URL'),\n fileId: z.string().describe('Temporary File ID'),\n method: z.enum(['PUT', 'POST']).describe('HTTP Method to use'),\n headers: z.record(z.string(), z.string()).optional().describe('Required headers for upload'),\n expiresIn: z.number().describe('URL expiry in seconds'),\n }),\n});\n\nexport const FileUploadResponseSchema = BaseResponseSchema.extend({\n data: FileMetadataSchema.describe('Uploaded file metadata'),\n});\n\nexport type GetPresignedUrlRequest = z.infer;\nexport type CompleteUploadRequest = z.infer;\nexport type PresignedUrlResponse = z.infer;\nexport type FileUploadResponse = z.infer;\n\n// ==========================================\n// Chunked / Resumable Upload Protocol\n// ==========================================\n\n/**\n * File Type Validation Schema\n * Configures allowed and blocked file types for upload endpoints.\n *\n * @example Allow images only\n * { mode: 'whitelist', mimeTypes: ['image/jpeg', 'image/png', 'image/webp'], maxFileSize: 10485760 }\n */\nexport const FileTypeValidationSchema = z.object({\n mode: z.enum(['whitelist', 'blacklist'])\n .describe('whitelist = only allow listed types, blacklist = block listed types'),\n mimeTypes: z.array(z.string()).min(1)\n .describe('List of MIME types to allow or block (e.g., \"image/jpeg\", \"application/pdf\")'),\n extensions: z.array(z.string()).optional()\n .describe('List of file extensions to allow or block (e.g., \".jpg\", \".pdf\")'),\n maxFileSize: z.number().int().min(1).optional()\n .describe('Maximum file size in bytes'),\n minFileSize: z.number().int().min(0).optional()\n .describe('Minimum file size in bytes (e.g., reject empty files)'),\n});\nexport type FileTypeValidation = z.infer;\n\n/**\n * Initiate Chunked Upload Request\n * Starts a resumable multipart upload session.\n *\n * @example POST /api/v1/storage/upload/chunked\n * { filename: 'large-video.mp4', mimeType: 'video/mp4', totalSize: 1073741824, chunkSize: 5242880 }\n */\nexport const InitiateChunkedUploadRequestSchema = z.object({\n filename: z.string().describe('Original filename'),\n mimeType: z.string().describe('File MIME type'),\n totalSize: z.number().int().min(1).describe('Total file size in bytes'),\n chunkSize: z.number().int().min(5242880).default(5242880)\n .describe('Size of each chunk in bytes (minimum 5MB per S3 spec)'),\n scope: z.string().default('user').describe('Target storage scope'),\n bucket: z.string().optional().describe('Specific bucket override (admin only)'),\n metadata: z.record(z.string(), z.string()).optional().describe('Custom metadata key-value pairs'),\n});\nexport type InitiateChunkedUploadRequest = z.infer;\n\n/**\n * Initiate Chunked Upload Response\n * Returns a resume token and upload session details.\n */\nexport const InitiateChunkedUploadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n resumeToken: z.string().describe('Opaque token for resuming interrupted uploads'),\n fileId: z.string().describe('Assigned file ID'),\n totalChunks: z.number().int().min(1).describe('Expected number of chunks'),\n chunkSize: z.number().int().describe('Chunk size in bytes'),\n expiresAt: z.string().datetime().describe('Upload session expiration timestamp'),\n }),\n});\nexport type InitiateChunkedUploadResponse = z.infer;\n\n/**\n * Upload Chunk Request\n * Uploads a single chunk of a multipart upload.\n *\n * @example PUT /api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex\n */\nexport const UploadChunkRequestSchema = z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n chunkIndex: z.number().int().min(0).describe('Zero-based chunk index'),\n resumeToken: z.string().describe('Resume token from initiate response'),\n});\nexport type UploadChunkRequest = z.infer;\n\n/**\n * Upload Chunk Response\n * Confirms a single chunk upload with ETag for assembly.\n */\nexport const UploadChunkResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n chunkIndex: z.number().int().describe('Chunk index that was uploaded'),\n eTag: z.string().describe('Chunk ETag for multipart completion'),\n bytesReceived: z.number().int().describe('Bytes received for this chunk'),\n }),\n});\nexport type UploadChunkResponse = z.infer;\n\n/**\n * Complete Chunked Upload Request\n * Assembles all uploaded chunks into a final file.\n *\n * @example POST /api/v1/storage/upload/chunked/:uploadId/complete\n */\nexport const CompleteChunkedUploadRequestSchema = z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n parts: z.array(z.object({\n chunkIndex: z.number().int().describe('Chunk index'),\n eTag: z.string().describe('ETag returned from chunk upload'),\n })).min(1).describe('Ordered list of uploaded parts for assembly'),\n});\nexport type CompleteChunkedUploadRequest = z.infer;\n\n/**\n * Complete Chunked Upload Response\n * Confirms that all chunks have been assembled into the final file.\n */\nexport const CompleteChunkedUploadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n fileId: z.string().describe('Final file ID'),\n key: z.string().describe('Storage key/path of the assembled file'),\n size: z.number().int().describe('Total file size in bytes'),\n mimeType: z.string().describe('File MIME type'),\n eTag: z.string().optional().describe('Final ETag of the assembled file'),\n url: z.string().optional().describe('Download URL for the assembled file'),\n }),\n});\nexport type CompleteChunkedUploadResponse = z.infer;\n\n/**\n * Upload Progress Schema\n * Represents the current progress of an active upload session.\n *\n * @example GET /api/v1/storage/upload/chunked/:uploadId/progress\n */\nexport const UploadProgressSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n fileId: z.string().describe('Assigned file ID'),\n filename: z.string().describe('Original filename'),\n totalSize: z.number().int().describe('Total file size in bytes'),\n uploadedSize: z.number().int().describe('Bytes uploaded so far'),\n totalChunks: z.number().int().describe('Total expected chunks'),\n uploadedChunks: z.number().int().describe('Number of chunks uploaded'),\n percentComplete: z.number().min(0).max(100).describe('Upload progress percentage'),\n status: z.enum(['in_progress', 'completing', 'completed', 'failed', 'expired'])\n .describe('Current upload session status'),\n startedAt: z.string().datetime().describe('Upload session start timestamp'),\n expiresAt: z.string().datetime().describe('Session expiration timestamp'),\n }),\n});\nexport type UploadProgress = z.infer;\n\n// ==========================================\n// Storage API Contract Registry\n// ==========================================\n\n/**\n * Standard Storage API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const StorageApiContracts = {\n getPresignedUrl: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/presigned',\n input: GetPresignedUrlRequestSchema,\n output: PresignedUrlResponseSchema,\n },\n completeUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/complete',\n input: CompleteUploadRequestSchema,\n output: FileUploadResponseSchema,\n },\n initiateChunkedUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/chunked',\n input: InitiateChunkedUploadRequestSchema,\n output: InitiateChunkedUploadResponseSchema,\n },\n uploadChunk: {\n method: 'PUT' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex',\n input: UploadChunkRequestSchema,\n output: UploadChunkResponseSchema,\n },\n completeChunkedUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/complete',\n input: CompleteChunkedUploadRequestSchema,\n output: CompleteChunkedUploadResponseSchema,\n },\n getUploadProgress: {\n method: 'GET' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/progress',\n output: UploadProgressSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # ObjectStack Validation Protocol\n * \n * This module defines the validation schema protocol for ObjectStack, providing a comprehensive\n * type-safe validation system similar to Salesforce's validation rules but with enhanced capabilities.\n * \n * ## Overview\n * \n * Validation rules are applied at the data layer to ensure data integrity and enforce business logic.\n * The system supports multiple validation types:\n * \n * 1. **Script Validation**: Formula-based validation using expressions\n * 2. **Uniqueness Validation**: Enforce unique constraints across fields\n * 3. **State Machine Validation**: Control allowed state transitions\n * 4. **Format Validation**: Validate field formats (email, URL, regex, etc.)\n * 5. **Cross-Field Validation**: Validate relationships between multiple fields\n * 6. **Async Validation**: Remote validation via API calls\n * 7. **Custom Validation**: User-defined validation functions\n * 8. **Conditional Validation**: Apply validations based on conditions\n * \n * ## Salesforce Comparison\n * \n * ObjectStack validation rules are inspired by Salesforce validation rules but enhanced:\n * - Salesforce: Formula-based validation with `Error Condition Formula`\n * - ObjectStack: Multiple validation types with composable rules\n * \n * Example Salesforce validation rule:\n * ```\n * Rule Name: Discount_Cannot_Exceed_40_Percent\n * Error Condition Formula: Discount_Percent__c > 0.40\n * Error Message: Discount cannot exceed 40%.\n * ```\n * \n * Equivalent ObjectStack rule:\n * ```typescript\n * {\n * type: 'script',\n * name: 'discount_cannot_exceed_40_percent',\n * condition: 'discount_percent > 0.40',\n * message: 'Discount cannot exceed 40%',\n * severity: 'error'\n * }\n * ```\n */\n\n/**\n * Base Validation Rule\n * \n * All validation rules extend from this base schema with common properties.\n * \n * ## Industry Standard Enhancements\n * - **Label/Description**: Essential for governance in large systems with thousands of rules.\n * - **Events**: granular control over validation timing (Context-aware validation).\n * - **Tags**: categorization for reporting and management.\n */\nconst BaseValidationSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label for the rule listing'),\n description: z.string().optional().describe('Administrative notes explaining the business reason'),\n \n // Execution Control\n active: z.boolean().default(true),\n events: z.array(z.enum(['insert', 'update', 'delete'])).default(['insert', 'update']).describe('Validation contexts'),\n priority: z.number().int().min(0).max(9999).default(100).describe('Execution priority (lower runs first, default: 100)'),\n \n // Classification\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g., \"compliance\", \"billing\")'),\n \n // Feedback\n severity: z.enum(['error', 'warning', 'info']).default('error'),\n message: z.string().describe('Error message to display to the user'),\n});\n\n/**\n * 1. Script/Expression Validation\n * Generic formula-based validation.\n */\nexport const ScriptValidationSchema = BaseValidationSchema.extend({\n type: z.literal('script'),\n condition: z.string().describe('Formula expression. If TRUE, validation fails. (e.g. amount < 0)'),\n});\n\n/**\n * 2. Uniqueness Validation\n * specialized optimized check for unique constraints.\n */\nexport const UniquenessValidationSchema = BaseValidationSchema.extend({\n type: z.literal('unique'),\n fields: z.array(z.string()).describe('Fields that must be combined unique'),\n scope: z.string().optional().describe('Formula condition for scope (e.g. active = true)'),\n caseSensitive: z.boolean().default(true),\n});\n\n/**\n * 3. State Machine Validation\n * State transition logic.\n */\nexport const StateMachineValidationSchema = BaseValidationSchema.extend({\n type: z.literal('state_machine'),\n field: z.string().describe('State field (e.g. status)'),\n transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'),\n});\n\n/**\n * 4. Value Format Validation\n * Regex or specialized formats.\n */\nexport const FormatValidationSchema = BaseValidationSchema.extend({\n type: z.literal('format'),\n field: z.string(),\n regex: z.string().optional(),\n format: z.enum(['email', 'url', 'phone', 'json']).optional(),\n});\n\n/**\n * 5. Cross-Field Validation\n * Validates relationships between multiple fields.\n * \n * ## Use Cases\n * - Date range validations (end_date > start_date)\n * - Amount comparisons (discount < total)\n * - Complex business rules involving multiple fields\n * \n * ## Salesforce Examples\n * \n * ### Example 1: Close Date Must Be In Current or Future Month\n * **Salesforce Formula:**\n * ```\n * MONTH(CloseDate) < MONTH(TODAY()) ||\n * YEAR(CloseDate) < YEAR(TODAY())\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'close_date_future',\n * condition: 'MONTH(close_date) >= MONTH(TODAY()) AND YEAR(close_date) >= YEAR(TODAY())',\n * fields: ['close_date'],\n * message: 'Close Date must be in the current or a future month'\n * }\n * ```\n * \n * ### Example 2: Discount Validation\n * **Salesforce Formula:**\n * ```\n * Discount__c > (Amount__c * 0.40)\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'discount_limit',\n * condition: 'discount > (amount * 0.40)',\n * fields: ['discount', 'amount'],\n * message: 'Discount cannot exceed 40% of the amount'\n * }\n * ```\n * \n * ### Example 3: Opportunity Must Have Products\n * **Salesforce Formula:**\n * ```\n * ISBLANK(Products__c) && ISPICKVAL(StageName, \"Closed Won\")\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'products_required_for_won',\n * condition: 'products = null AND stage = \"closed_won\"',\n * fields: ['products', 'stage'],\n * message: 'Opportunity must have products to be marked as Closed Won'\n * }\n * ```\n */\nexport const CrossFieldValidationSchema = BaseValidationSchema.extend({\n type: z.literal('cross_field'),\n condition: z.string().describe('Formula expression comparing fields (e.g. \"end_date > start_date\")'),\n fields: z.array(z.string()).describe('Fields involved in the validation'),\n});\n\n/**\n * 6. JSON Structure Validation\n * Validates JSON fields against a JSON Schema.\n * \n * ## Use Cases\n * - Validating configuration objects stored in JSON fields\n * - Enforcing API payload structures\n * - Complex nested data validation\n */\nexport const JSONValidationSchema = BaseValidationSchema.extend({\n type: z.literal('json_schema'),\n field: z.string().describe('JSON field to validate'),\n schema: z.record(z.string(), z.unknown()).describe('JSON Schema object definition'),\n});\n\n/**\n * 7. Async Validation\n * Remote validation via API call or database query.\n * \n * ## Use Cases\n * \n * ### 1. Email Uniqueness Check\n * Check if an email address is already registered in the system.\n * ```typescript\n * {\n * type: 'async',\n * name: 'unique_email',\n * field: 'email',\n * validatorUrl: '/api/users/check-email',\n * message: 'This email address is already registered',\n * debounce: 500, // Wait 500ms after user stops typing\n * timeout: 3000\n * }\n * ```\n * \n * ### 2. Username Availability\n * Verify username is available before form submission.\n * ```typescript\n * {\n * type: 'async',\n * name: 'username_available',\n * field: 'username',\n * validatorUrl: '/api/users/check-username',\n * message: 'This username is already taken',\n * debounce: 300,\n * timeout: 2000\n * }\n * ```\n * \n * ### 3. Tax ID Validation\n * Validate tax ID with government API (e.g., IRS, HMRC).\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_tax_id',\n * field: 'tax_id',\n * validatorFunction: 'validateTaxIdWithIRS',\n * message: 'Invalid Tax ID number',\n * timeout: 10000, // Government APIs may be slow\n * params: { country: 'US', format: 'EIN' }\n * }\n * ```\n * \n * ### 4. Credit Card Validation\n * Verify credit card with payment gateway without charging.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_card',\n * field: 'card_number',\n * validatorUrl: 'https://api.stripe.com/v1/tokens/validate',\n * message: 'Invalid credit card number',\n * timeout: 5000,\n * params: { \n * mode: 'validate_only',\n * checkFunds: false \n * }\n * }\n * ```\n * \n * ### 5. Address Validation\n * Validate and standardize addresses using geocoding services.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_address',\n * field: 'street_address',\n * validatorFunction: 'validateAddressWithGoogleMaps',\n * message: 'Unable to verify address',\n * timeout: 4000,\n * params: {\n * includeFields: ['city', 'state', 'zip'],\n * strictMode: true,\n * country: 'US'\n * }\n * }\n * ```\n * \n * ### 6. Domain Name Availability\n * Check if domain name is available for registration.\n * ```typescript\n * {\n * type: 'async',\n * name: 'domain_available',\n * field: 'domain_name',\n * validatorUrl: '/api/domains/check-availability',\n * message: 'This domain is already taken or reserved',\n * debounce: 500,\n * timeout: 2000\n * }\n * ```\n * \n * ### 7. Coupon Code Validation\n * Verify coupon code is valid and not expired.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_coupon',\n * field: 'coupon_code',\n * validatorUrl: '/api/coupons/validate',\n * message: 'Invalid or expired coupon code',\n * timeout: 2000,\n * params: {\n * checkExpiration: true,\n * checkUsageLimit: true,\n * userId: '{{current_user_id}}'\n * }\n * }\n * ```\n */\nexport const AsyncValidationSchema = BaseValidationSchema.extend({\n type: z.literal('async'),\n field: z.string().describe('Field to validate'),\n validatorUrl: z.string().optional().describe('External API endpoint for validation'),\n method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method for external call'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for the request'),\n validatorFunction: z.string().optional().describe('Reference to custom validator function'),\n timeout: z.number().optional().default(5000).describe('Timeout in milliseconds'),\n debounce: z.number().optional().describe('Debounce delay in milliseconds'),\n params: z.record(z.string(), z.unknown()).optional().describe('Additional parameters to pass to validator'),\n});\n\n/**\n * 8. Custom Validator Function\n * User-defined validation logic with code reference.\n */\nexport const CustomValidatorSchema = BaseValidationSchema.extend({\n type: z.literal('custom'),\n handler: z.string().describe('Name of the custom validation function registered in the system'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the custom handler'),\n});\n\n/**\n * 9. Master Validation Rule Schema\n */\n/** Base type for validation rules - used for z.lazy() recursive type annotation */\nexport interface BaseValidationRuleShape {\n type: string;\n name: string;\n message: string;\n label?: string;\n description?: string;\n active?: boolean;\n events?: ('insert' | 'update' | 'delete')[];\n priority?: number;\n tags?: string[];\n severity?: 'error' | 'warning' | 'info';\n [key: string]: unknown;\n}\n\nexport const ValidationRuleSchema: z.ZodType = z.lazy(() =>\n z.discriminatedUnion('type', [\n ScriptValidationSchema,\n UniquenessValidationSchema,\n StateMachineValidationSchema,\n FormatValidationSchema,\n CrossFieldValidationSchema,\n JSONValidationSchema,\n AsyncValidationSchema,\n CustomValidatorSchema,\n ConditionalValidationSchema,\n ])\n);\n\n/**\n * 8. Conditional Validation\n * Validation that only applies when a condition is met.\n * \n * ## Overview\n * Conditional validations follow the pattern: \"Validate X only if Y is true\"\n * This allows for context-aware validation rules that adapt to different scenarios.\n * \n * ## Use Cases\n * \n * ### 1. Validate Based on Record Type\n * Apply different validation rules based on the type of record.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_approval_required',\n * when: 'account_type = \"enterprise\"',\n * message: 'Enterprise validation',\n * then: {\n * type: 'script',\n * name: 'require_approval',\n * message: 'Enterprise accounts require manager approval',\n * condition: 'approval_status = null'\n * }\n * }\n * ```\n * \n * ### 2. Conditional Field Requirements\n * Require certain fields only when specific conditions are met.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'shipping_address_when_required',\n * when: 'requires_shipping = true',\n * message: 'Shipping validation',\n * then: {\n * type: 'script',\n * name: 'shipping_address_required',\n * message: 'Shipping address is required for physical products',\n * condition: 'shipping_address = null OR shipping_address = \"\"'\n * }\n * }\n * ```\n * \n * ### 3. Amount-Based Validation\n * Apply different rules based on transaction amount.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'high_value_approval',\n * when: 'order_total > 10000',\n * message: 'High value order validation',\n * then: {\n * type: 'script',\n * name: 'manager_approval_required',\n * message: 'Orders over $10,000 require manager approval',\n * condition: 'manager_approval_id = null'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'standard_validation',\n * message: 'Payment method is required',\n * condition: 'payment_method = null'\n * }\n * }\n * ```\n * \n * ### 4. Regional Compliance\n * Apply region-specific validation rules.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'regional_compliance',\n * when: 'region = \"EU\"',\n * message: 'EU compliance validation',\n * then: {\n * type: 'script',\n * name: 'gdpr_consent',\n * message: 'GDPR consent is required for EU customers',\n * condition: 'gdpr_consent_given = false'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'tos_acceptance',\n * message: 'Terms of Service acceptance required',\n * condition: 'tos_accepted = false'\n * }\n * }\n * ```\n * \n * ### 5. Nested Conditional Validation\n * Create complex validation logic with nested conditions.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'country_state_validation',\n * when: 'country = \"US\"',\n * message: 'US-specific validation',\n * then: {\n * type: 'conditional',\n * name: 'california_validation',\n * when: 'state = \"CA\"',\n * message: 'California-specific validation',\n * then: {\n * type: 'script',\n * name: 'ca_tax_id_required',\n * message: 'California requires a valid tax ID',\n * condition: 'tax_id = null OR NOT(REGEX(tax_id, \"^\\\\d{2}-\\\\d{7}$\"))'\n * }\n * }\n * }\n * ```\n * \n * ### 6. Tax Validation for Taxable Items\n * Only validate tax fields when the item is taxable.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'tax_field_validation',\n * when: 'is_taxable = true',\n * message: 'Tax validation',\n * then: {\n * type: 'script',\n * name: 'tax_code_required',\n * message: 'Tax code is required for taxable items',\n * condition: 'tax_code = null OR tax_code = \"\"'\n * }\n * }\n * ```\n * \n * ### 7. Role-Based Validation\n * Apply validation based on user role.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'role_based_approval_limit',\n * when: 'user_role = \"manager\"',\n * message: 'Manager approval limits',\n * then: {\n * type: 'script',\n * name: 'manager_limit',\n * message: 'Managers can approve up to $50,000',\n * condition: 'approval_amount > 50000'\n * }\n * }\n * ```\n * \n * ## Salesforce Pattern Comparison\n * \n * Salesforce doesn't have explicit \"conditional validation\" rules but achieves similar\n * behavior using formula logic. ObjectStack makes this pattern explicit and composable.\n * \n * **Salesforce Approach:**\n * ```\n * IF(\n * ISPICKVAL(Type, \"Enterprise\"),\n * AND(Amount > 100000, ISBLANK(Approval__c)),\n * FALSE\n * )\n * ```\n * \n * **ObjectStack Approach:**\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_high_value',\n * when: 'type = \"enterprise\"',\n * then: {\n * type: 'cross_field',\n * name: 'amount_approval',\n * condition: 'amount > 100000 AND approval = null',\n * fields: ['amount', 'approval']\n * }\n * }\n * ```\n */\nexport const ConditionalValidationSchema = BaseValidationSchema.extend({\n type: z.literal('conditional'),\n when: z.string().describe('Condition formula (e.g. \"type = \\'enterprise\\'\")'),\n then: ValidationRuleSchema.describe('Validation rule to apply when condition is true'),\n otherwise: ValidationRuleSchema.optional().describe('Validation rule to apply when condition is false'),\n});\n\nexport type ValidationRule = z.infer;\nexport type ScriptValidation = z.infer;\nexport type UniquenessValidation = z.infer;\nexport type StateMachineValidation = z.infer;\nexport type FormatValidation = z.infer;\nexport type CrossFieldValidation = z.infer;\nexport type JSONValidation = z.infer;\nexport type AsyncValidation = z.infer;\nexport type CustomValidation = z.infer;\nexport type ConditionalValidation = z.infer;", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * XState-inspired State Machine Protocol\n * Used to define strict business logic constraints and lifecycle management.\n * Prevent AI \"hallucinations\" by enforcing valid valid transitions.\n */\n\n// --- Primitives ---\n\n/**\n * References a named action (side effect)\n * Can be a script, a webhook, or a field update.\n */\nexport const ActionRefSchema = z.union([\n z.string().describe('Action Name'),\n z.object({\n type: z.string(), // e.g., 'xstate.assign', 'log', 'email'\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n/**\n * References a named condition (guard)\n * Must evaluate to true for the transition to occur.\n */\nexport const GuardRefSchema = z.union([\n z.string().describe('Guard Name (e.g., \"isManager\", \"amountGT1000\")'),\n z.object({\n type: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n// --- Core Structure ---\n\n/**\n * State Transition Definition\n * \"When EVENT happens, if GUARD is true, go to TARGET and run ACTIONS\"\n */\nexport const TransitionSchema = z.object({\n target: z.string().optional().describe('Target State ID'),\n cond: GuardRefSchema.optional().describe('Condition (Guard) required to take this path'),\n actions: z.array(ActionRefSchema).optional().describe('Actions to execute during transition'),\n description: z.string().optional().describe('Human readable description of this rule'),\n});\n\n/**\n * Event Definition (Signals)\n */\nexport const EventSchema = z.object({\n type: z.string().describe('Event Type (e.g. \"APPROVE\", \"REJECT\", \"Submit\")'),\n // Payload validation schema could go here if we want deep validation\n schema: z.record(z.string(), z.unknown()).optional().describe('Expected event payload structure'),\n});\n\nexport type ActionRef = z.infer;\nexport type Transition = z.infer;\n\nexport type StateNodeConfig = {\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n entry?: ActionRef[];\n exit?: ActionRef[];\n on?: Record;\n always?: Transition[];\n initial?: string;\n states?: Record;\n meta?: {\n label?: string;\n description?: string;\n color?: string;\n aiInstructions?: string;\n };\n};\n\n/**\n * State Node Definition\n */\nexport const StateNodeSchema: z.ZodType = z.lazy(() => z.object({\n /** Type of state */\n type: z.enum(['atomic', 'compound', 'parallel', 'final', 'history']).default('atomic'),\n \n /** Entry/Exit Actions */\n entry: z.array(ActionRefSchema).optional().describe('Actions to run when entering this state'),\n exit: z.array(ActionRefSchema).optional().describe('Actions to run when leaving this state'),\n \n /** Transitions (Events) */\n on: z.record(z.string(), z.union([\n z.string(), // Shorthand target\n TransitionSchema, \n z.array(TransitionSchema)\n ])).optional().describe('Map of Event Type -> Transition Definition'),\n \n /** Always Transitions (Eventless) */\n always: z.array(TransitionSchema).optional(),\n\n /** Nesting (Hierarchical States) */\n initial: z.string().optional().describe('Initial child state (if compound)'),\n states: z.record(z.string(), StateNodeSchema).optional(),\n \n /** Metadata for UI/AI */\n meta: z.object({\n label: z.string().optional(),\n description: z.string().optional(),\n color: z.string().optional(), // For UI diagrams\n // Instructions for AI Agent when in this state\n aiInstructions: z.string().optional().describe('Specific instructions for AI when in this state'),\n }).optional(),\n}));\n\n/**\n * Top-Level State Machine Definition\n */\nexport const StateMachineSchema = z.object({\n id: SnakeCaseIdentifierSchema.describe('Unique Machine ID'),\n description: z.string().optional(),\n \n /** Context (Memory) Schema */\n contextSchema: z.record(z.string(), z.unknown()).optional().describe('Zod Schema for the machine context/memory'),\n \n /** Initial State */\n initial: z.string().describe('Initial State ID'),\n \n /** State Definitions */\n states: z.record(z.string(), StateNodeSchema).describe('State Nodes'),\n \n /** Global Listeners */\n on: z.record(z.string(), z.union([z.string(), TransitionSchema, z.array(TransitionSchema)])).optional(),\n});\n\nexport type StateMachineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from './field.zod';\nimport { ValidationRuleSchema } from './validation.zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\nimport { ActionSchema } from '../ui/action.zod';\n\n/**\n * API Operations Enum\n */\nexport const ApiMethod = z.enum([\n 'get', 'list', // Read\n 'create', 'update', 'delete', // Write\n 'upsert', // Idempotent Write\n 'bulk', // Batch operations\n 'aggregate', // Analytics (count, sum)\n 'history', // Audit access\n 'search', // Search access\n 'restore', 'purge', // Trash management\n 'import', 'export', // Data portability\n]);\nexport type ApiMethod = z.infer;\n\n/**\n * Capability Flags\n * Defines what system features are enabled for this object.\n * \n * Optimized based on industry standards (Salesforce, ServiceNow):\n * - Added `activities` (Tasks/Events)\n * - Added `mru` (Recent Items)\n * - Added `feeds` (Social/Chatter)\n * - Grouped API permissions\n * \n * @example\n * {\n * trackHistory: true,\n * searchable: true,\n * apiEnabled: true,\n * files: true\n * }\n */\nexport const ObjectCapabilities = z.object({\n /** Enable history tracking (Audit Trail) */\n trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),\n \n /** Enable global search indexing */\n searchable: z.boolean().default(true).describe('Index records for global search'),\n \n /** Enable REST/GraphQL API access */\n apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),\n\n /** \n * API Supported Operations\n * Granular control over API exposure.\n */\n apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),\n \n /** Enable standard attachments/files engine */\n files: z.boolean().default(false).describe('Enable file attachments and document management'),\n \n /** Enable social collaboration (Comments, Mentions, Feeds) */\n feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),\n \n /** Enable standard Activity suite (Tasks, Calendars, Events) */\n activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),\n \n /** Enable Recycle Bin / Soft Delete */\n trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),\n\n /** Enable \"Recently Viewed\" tracking */\n mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),\n \n /** Allow cloning records */\n clone: z.boolean().default(true).describe('Allow record deep cloning'),\n});\n\n/**\n * Schema for database indexes.\n * Enhanced with additional index types and configuration options\n * \n * @example\n * {\n * name: \"idx_account_name\",\n * fields: [\"name\"],\n * type: \"btree\",\n * unique: true\n * }\n */\nexport const IndexSchema = z.object({\n name: z.string().optional().describe('Index name (auto-generated if not provided)'),\n fields: z.array(z.string()).describe('Fields included in the index'),\n type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),\n unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),\n partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),\n});\n\n/**\n * Search Configuration\n * Defines how this object behaves in search results.\n * \n * @example\n * {\n * fields: [\"name\", \"email\", \"phone\"],\n * displayFields: [\"name\", \"title\"],\n * filters: [\"status = 'active'\"]\n * }\n */\nexport const SearchConfigSchema = z.object({\n fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),\n displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),\n filters: z.array(z.string()).optional().describe('Default filters for search results'),\n});\n\n/**\n * Multi-Tenancy Configuration Schema\n * Configures tenant isolation strategy for SaaS applications\n * \n * @example Shared database with tenant_id isolation\n * {\n * enabled: true,\n * strategy: 'shared',\n * tenantField: 'tenant_id',\n * crossTenantAccess: false\n * }\n */\nexport const TenancyConfigSchema = z.object({\n enabled: z.boolean().describe('Enable multi-tenancy for this object'),\n strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),\n tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),\n crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),\n});\n\n/**\n * Soft Delete Configuration Schema\n * Implements recycle bin / trash functionality\n * \n * @example Standard soft delete with cascade\n * {\n * enabled: true,\n * field: 'deleted_at',\n * cascadeDelete: true\n * }\n */\nexport const SoftDeleteConfigSchema = z.object({\n enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),\n field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),\n cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),\n});\n\n/**\n * Versioning Configuration Schema\n * Implements record versioning and history tracking\n * \n * @example Snapshot versioning with 90-day retention\n * {\n * enabled: true,\n * strategy: 'snapshot',\n * retentionDays: 90,\n * versionField: 'version'\n * }\n */\nexport const VersioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable record versioning'),\n strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),\n retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),\n versionField: z.string().default('version').describe('Field name for version number/timestamp'),\n});\n\n/**\n * Partitioning Strategy Schema\n * Configures table partitioning for performance at scale\n * \n * @example Range partitioning by date (monthly)\n * {\n * enabled: true,\n * strategy: 'range',\n * key: 'created_at',\n * interval: '1 month'\n * }\n */\nexport const PartitioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable table partitioning'),\n strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),\n key: z.string().describe('Field name to partition by'),\n interval: z.string().optional().describe('Partition interval for range strategy (e.g., \"1 month\", \"1 year\")'),\n}).refine((data) => {\n // If strategy is 'range', interval must be provided\n if (data.strategy === 'range' && !data.interval) {\n return false;\n }\n return true;\n}, {\n message: 'interval is required when strategy is \"range\"',\n});\n\n/**\n * Change Data Capture (CDC) Configuration Schema\n * Enables real-time data streaming to external systems\n * \n * @example Stream all changes to Kafka\n * {\n * enabled: true,\n * events: ['insert', 'update', 'delete'],\n * destination: 'kafka://events.objectstack'\n * }\n */\nexport const CDCConfigSchema = z.object({\n enabled: z.boolean().describe('Enable Change Data Capture'),\n events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),\n destination: z.string().describe('Destination endpoint (e.g., \"kafka://topic\", \"webhook://url\")'),\n});\n\n/**\n * Base Object Schema Definition\n * \n * The Blueprint of a Business Object.\n * Represents a table, a collection, or a virtual entity.\n * \n * @example\n * ```yaml\n * name: project_task\n * label: Project Task\n * icon: task\n * fields:\n * project:\n * type: lookup\n * reference: project\n * status:\n * type: select\n * options: [todo, in_progress, done]\n * enable:\n * trackHistory: true\n * files: true\n * ```\n */\nconst ObjectSchemaBase = z.object({\n /** \n * Identity & Metadata \n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),\n label: z.string().optional().describe('Human readable singular label (e.g. \"Account\")'),\n pluralLabel: z.string().optional().describe('Human readable plural label (e.g. \"Accounts\")'),\n description: z.string().optional().describe('Developer documentation / description'),\n icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),\n \n /**\n * Namespace & Domain Classification\n * \n * Groups objects into logical domains for routing, permissions, and discovery.\n * System objects use `'sys'`; business packages use their own namespace.\n * \n * When set, `tableName` is auto-derived as `{namespace}_{name}` by\n * `ObjectSchema.create()` unless an explicit `tableName` is provided.\n * \n * Namespace must be a single lowercase word (no underscores or hyphens)\n * to ensure clean auto-derivation of `{namespace}_{name}` table names.\n * \n * @example namespace: 'sys' → tableName defaults to 'sys_user'\n * @example namespace: 'crm' → tableName defaults to 'crm_account'\n */\n namespace: z.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace — single lowercase word (e.g. \"sys\", \"crm\"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'),\n\n /**\n * Taxonomy & Organization\n */\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g. \"sales\", \"system\", \"reference\")'),\n active: z.boolean().optional().default(true).describe('Is the object active and usable'),\n isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),\n abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),\n\n /** \n * Storage & Virtualization \n */\n datasource: z.string().optional().default('default').describe('Target Datasource ID. \"default\" is the primary DB.'),\n tableName: z.string().optional().describe('Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set.'),\n \n /** \n * Data Model \n */\n fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {\n message: 'Field names must be lowercase snake_case (e.g., \"first_name\", \"company\", \"annual_revenue\")',\n }), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),\n indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),\n \n /**\n * Advanced Data Management\n */\n \n // Multi-tenancy configuration\n tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),\n \n // Soft delete configuration\n softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),\n \n // Versioning configuration\n versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),\n \n // Partitioning strategy\n partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),\n \n // Change Data Capture\n cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),\n \n /**\n * Logic & Validation (Co-located)\n * Best Practice: Define rules close to data.\n */\n validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),\n \n /**\n * State Machine(s)\n * Named record of state machines, where each key is a unique machine identifier.\n * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).\n * \n * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }\n */\n stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),\n\n /** \n * Display & UI Hints (Data-Layer)\n */\n displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., \"name\", \"title\"). Defaults to \"name\" if present.'),\n recordName: z.object({\n type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),\n displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., \"CASE-{0000}\", \"INV-{YYYY}-{0000}\")'),\n startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),\n }).optional().describe('Record name generation configuration (Salesforce pattern)'),\n titleFormat: z.string().optional().describe('Title expression (e.g. \"{name} - {code}\"). Overrides displayNameField.'),\n compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),\n \n /** \n * Search Engine Config \n */\n search: SearchConfigSchema.optional().describe('Search engine configuration'),\n \n /** \n * System Capabilities \n */\n enable: ObjectCapabilities.optional().describe('Enabled system features modules'),\n\n /** Record Types */\n recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),\n\n /** Sharing Model */\n sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),\n\n /** Key Prefix */\n keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., \"001\" for Account)'),\n\n /**\n * Object Actions\n * \n * Actions associated with this object. Populated automatically by `defineStack()`\n * when top-level actions specify `objectName` matching this object.\n * Can also be defined directly on the object.\n * \n * Aligns with Salesforce/ServiceNow patterns where actions are part of the\n * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)\n * include the action list without requiring downstream merge.\n */\n actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),\n});\n\n/**\n * Converts a snake_case name to a human-readable Title Case label.\n * @example snakeCaseToLabel('project_task') → 'Project Task'\n */\nfunction snakeCaseToLabel(name: string): string {\n return name\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n}\n\n/**\n * Enhanced ObjectSchema with Factory\n */\nexport const ObjectSchema = Object.assign(ObjectSchemaBase, {\n /**\n * Type-safe factory for creating business object definitions.\n * \n * Enhancements over raw schema:\n * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).\n * - **Validation**: Runs Zod `.parse()` to validate the config at creation time.\n * \n * @example\n * ```ts\n * const Task = ObjectSchema.create({\n * name: 'project_task',\n * // label auto-generated as 'Project Task'\n * fields: {\n * subject: { type: 'text', label: 'Subject', required: true },\n * },\n * });\n * ```\n */\n create: >(config: T): Omit & Pick => {\n const withDefaults = {\n ...config,\n label: config.label ?? snakeCaseToLabel(config.name),\n // Auto-derive tableName as {namespace}_{name} when namespace is set\n tableName: config.tableName ?? (config.namespace ? `${config.namespace}_${config.name}` : undefined),\n };\n return ObjectSchemaBase.parse(withDefaults) as Omit & Pick;\n },\n});\n\nexport type ServiceObject = z.infer;\nexport type ServiceObjectInput = z.input;\nexport type ObjectCapabilities = z.infer;\nexport type ObjectIndex = z.infer;\nexport type TenancyConfig = z.infer;\nexport type SoftDeleteConfig = z.infer;\nexport type VersioningConfig = z.infer;\nexport type PartitioningConfig = z.infer;\nexport type CDCConfig = z.infer;\n\n// =================================================================\n// Object Ownership Model\n// =================================================================\n\n/**\n * How a package relates to an object it references.\n * \n * - `own`: This package is the original author/owner of the object.\n * Only one package may own a given object name. The owner defines\n * the base schema (table name, primary key, core fields).\n * \n * - `extend`: This package adds fields, views, or actions to an\n * existing object owned by another package. Multiple packages\n * may extend the same object. Extensions are merged at boot time.\n * \n * Follows Salesforce/ServiceNow patterns:\n * object name = database table name, globally unique, no namespace prefix.\n */\nexport const ObjectOwnershipEnum = z.enum(['own', 'extend']);\nexport type ObjectOwnership = z.infer;\n\n/**\n * Object Extension Entry — used in `objectExtensions` array.\n * Declares fields/config to merge into an existing object owned by another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact', // target object FQN\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\nexport const ObjectExtensionSchema = z.object({\n /** The target object name (FQN) to extend */\n extend: z.string().describe('Target object name (FQN) to extend'),\n \n /** Fields to merge into the target object (additive) */\n fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),\n \n /** Override label */\n label: z.string().optional().describe('Override label for the extended object'),\n \n /** Override plural label */\n pluralLabel: z.string().optional().describe('Override plural label for the extended object'),\n \n /** Override description */\n description: z.string().optional().describe('Override description for the extended object'),\n \n /** Additional validation rules to add */\n validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),\n \n /** Additional indexes to add */\n indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),\n \n /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */\n priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),\n});\n\nexport type ObjectExtension = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema, EmbedConfigSchema } from './sharing.zod';\n\n/**\n * Base Navigation Item Schema\n * Shared properties for all navigation types.\n * \n * **NAMING CONVENTION:**\n * Navigation item IDs are used in URLs and configuration and must be lowercase snake_case.\n * \n * @example Good IDs\n * - 'menu_accounts'\n * - 'page_dashboard'\n * - 'nav_settings'\n * \n * @example Bad IDs (will be rejected)\n * - 'MenuAccounts' (PascalCase)\n * - 'Page Dashboard' (spaces)\n */\nconst BaseNavItemSchema = z.object({\n /** Unique identifier for the item */\n id: SnakeCaseIdentifierSchema.describe('Unique identifier for this navigation item (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display proper label'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Sort order within the same level (lower numbers appear first) */\n order: z.number().optional().describe('Sort order within the same level (lower = first)'),\n\n /** Badge text or count displayed on the navigation item (e.g. \"3\", \"New\") */\n badge: z.union([z.string(), z.number()]).optional().describe('Badge text or count displayed on the item'),\n\n /** \n * Visibility condition. \n * Formula expression returning boolean. \n * e.g. \"user.is_admin || user.department == 'sales'\"\n */\n visible: z.string().optional().describe('Visibility formula condition'),\n\n /** Permissions required to see/access this navigation item */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this item'),\n});\n\n/**\n * 1. Object Navigation Item\n * Navigates to an object's list view.\n */\nexport const ObjectNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('object'),\n objectName: z.string().describe('Target object name'),\n viewName: z.string().optional().describe('Default list view to open. Defaults to \"all\"'),\n});\n\n/**\n * 2. Dashboard Navigation Item\n * Navigates to a specific dashboard.\n */\nexport const DashboardNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('dashboard'),\n dashboardName: z.string().describe('Target dashboard name'),\n});\n\n/**\n * 3. Page Navigation Item\n * Navigates to a custom UI page/component.\n */\nexport const PageNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('page'),\n pageName: z.string().describe('Target custom page component name'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the page context'),\n});\n\n/**\n * 4. URL Navigation Item\n * Navigates to an external or absolute URL.\n */\nexport const UrlNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('url'),\n url: z.string().describe('Target external URL'),\n target: z.enum(['_self', '_blank']).default('_self').describe('Link target window'),\n});\n\n/**\n * 5. Report Navigation Item\n * Navigates to a specific report.\n */\nexport const ReportNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('report'),\n reportName: z.string().describe('Target report name'),\n});\n\n/**\n * 6. Action Navigation Item\n * Triggers an action (e.g. opening a flow, running a script, or launching a screen action).\n */\nexport const ActionNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('action'),\n actionDef: z.object({\n actionName: z.string().describe('Action machine name to execute'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the action'),\n }).describe('Action definition to execute when clicked'),\n});\n\n/**\n * 7. Group Navigation Item\n * A container for child navigation items (Sub-menu).\n * Does not perform navigation itself.\n */\nexport const GroupNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('group'),\n expanded: z.boolean().default(false).describe('Default expansion state in sidebar'),\n // children property is added in the recursive definition below\n});\n\n/**\n * Recursive Union of all navigation item types.\n * Allows constructing an unlimited-depth navigation tree.\n */\nexport const NavigationItemSchema: z.ZodType = z.lazy(() => \n z.union([\n ObjectNavItemSchema.extend({\n children: z.array(NavigationItemSchema).optional().describe('Child navigation items (e.g. specific views)'),\n }),\n DashboardNavItemSchema,\n PageNavItemSchema,\n UrlNavItemSchema,\n ReportNavItemSchema,\n ActionNavItemSchema,\n GroupNavItemSchema.extend({\n children: z.array(NavigationItemSchema).describe('Child navigation items'),\n })\n ])\n);\n\n/**\n * App Branding Configuration\n * Allows configuring the look and feel of the specific app.\n */\nexport const AppBrandingSchema = z.object({\n primaryColor: z.string().optional().describe('Primary theme color hex code'),\n logo: z.string().optional().describe('Custom logo URL for this app'),\n favicon: z.string().optional().describe('Custom favicon URL for this app'),\n});\n\n/**\n * Navigation Area Schema\n * \n * A logical grouping (zone/section) of navigation items, similar to Salesforce \"App Areas\"\n * or Dynamics 365 \"Site Map Areas\". Each area represents a business domain (e.g. Sales, Service, Settings)\n * and contains its own independent navigation tree.\n * \n * Areas allow large applications to partition navigation by business function while\n * keeping a single AppSchema definition. The runtime may render areas as top-level tabs,\n * sidebar sections, or a switchable navigation context.\n * \n * @example\n * ```ts\n * const salesArea: NavigationArea = {\n * id: 'area_sales',\n * label: 'Sales',\n * icon: 'briefcase',\n * order: 1,\n * navigation: [\n * { id: 'nav_leads', type: 'object', label: 'Leads', objectName: 'lead' },\n * { id: 'nav_opportunities', type: 'object', label: 'Opportunities', objectName: 'opportunity' },\n * ],\n * };\n * ```\n */\nexport const NavigationAreaSchema = z.object({\n /** Unique area identifier */\n id: SnakeCaseIdentifierSchema.describe('Unique area identifier (lowercase snake_case)'),\n\n /** Display label */\n label: I18nLabelSchema.describe('Area display label'),\n\n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Area icon name'),\n\n /** Sort order among areas (lower = first) */\n order: z.number().optional().describe('Sort order among areas (lower = first)'),\n\n /** Area description */\n description: I18nLabelSchema.optional().describe('Area description'),\n\n /** \n * Visibility condition.\n * Formula expression returning boolean.\n */\n visible: z.string().optional().describe('Visibility formula condition for this area'),\n\n /** Permissions required to access this area */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this area'),\n\n /** Navigation items within this area */\n navigation: z.array(NavigationItemSchema).describe('Navigation items within this area'),\n});\n\n/**\n * Schema for Applications (Apps).\n * A logical container for business functionality (e.g., \"Sales CRM\", \"HR Portal\").\n * \n * **NAMING CONVENTION:**\n * App names are used in URLs and routing and must be lowercase snake_case.\n * Prefix with 'app_' is recommended for clarity.\n * \n * @example Good app names\n * - 'app_crm'\n * - 'app_finance'\n * - 'app_portal'\n * - 'sales_app'\n * \n * @example Bad app names (will be rejected)\n * - 'CRM' (uppercase)\n * - 'FinanceApp' (mixed case)\n * - 'Sales App' (spaces)\n */\n/**\n * App Configuration Schema\n * Defines a business application container, including its navigation, branding, and permissions.\n * \n * The App is the top-level navigation shell. The `navigation[]` field holds the complete\n * sidebar tree with unlimited nesting depth via `type: 'group'` items. Pages are referenced\n * by name via `type: 'page'` items and defined independently.\n * \n * @example CRM App with nested navigation tree\n * {\n * name: \"crm\",\n * label: \"Sales CRM\",\n * icon: \"briefcase\",\n * navigation: [\n * { type: \"group\", id: \"grp_sales\", label: \"Sales Cloud\", expanded: true, children: [\n * { type: \"page\", id: \"nav_pipeline\", label: \"Pipeline\", pageName: \"page_pipeline\" },\n * { type: \"page\", id: \"nav_accounts\", label: \"Accounts\", pageName: \"page_accounts\" },\n * ]},\n * { type: \"page\", id: \"nav_settings\", label: \"Settings\", pageName: \"admin_settings\" },\n * ]\n * }\n */\nexport const AppSchema = z.object({\n /** Machine name (id) */\n name: SnakeCaseIdentifierSchema.describe('App unique machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('App display label'),\n\n /** App version */\n version: z.string().optional().describe('App version'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('App description'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('App icon used in the App Launcher'),\n \n /** Branding/Theming Configuration */\n branding: AppBrandingSchema.optional().describe('App-specific branding'),\n \n /** Application status */\n active: z.boolean().optional().default(true).describe('Whether the app is enabled'),\n\n /** Is this the default app for new users? */\n isDefault: z.boolean().optional().default(false).describe('Is default app'),\n \n /** \n * Full Navigation Tree — supports unlimited nesting depth.\n * Pages are referenced by name via `type: 'page'` items.\n * Groups can contain other groups for arbitrary sidebar depth.\n * \n * For simple apps, use `navigation` directly.\n * For enterprise apps with multiple business domains, use `areas` instead.\n */\n navigation: z.array(NavigationItemSchema).optional()\n .describe('Full navigation tree for the app sidebar'),\n\n /**\n * Navigation Areas — partitions navigation by business domain.\n * Each area defines an independent navigation tree (e.g. Sales, Service, Settings).\n * When areas are defined, they take precedence over the top-level `navigation` array.\n * \n * @example\n * ```ts\n * areas: [\n * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] },\n * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] },\n * ]\n * ```\n */\n areas: z.array(NavigationAreaSchema).optional()\n .describe('Navigation areas for partitioning navigation by business domain'),\n \n /** \n * App-level Home Page Override\n * ID of the navigation item to act as the landing page.\n * If not set, usually defaults to the first navigation item.\n */\n homePageId: z.string().optional().describe('ID of the navigation item to serve as landing page'),\n\n /** \n * Access Control\n * List of permissions required to access this app.\n * Modern replacement for role/profile based assignment.\n * Example: [\"app.access.crm\"]\n */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this app'),\n \n /** \n * Package Components (For config file convenience)\n * In a real monorepo these might be auto-discovered, but here we allow explicit registration.\n */\n objects: z.array(z.unknown()).optional().describe('Objects belonging to this app'),\n apis: z.array(z.unknown()).optional().describe('Custom APIs belonging to this app'),\n\n /** Sharing configuration for public access */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration'),\n\n /** Embed configuration for iframe embedding */\n embed: EmbedConfigSchema.optional().describe('Iframe embedding configuration'),\n\n /** Mobile navigation mode */\n mobileNavigation: z.object({\n mode: z.enum(['drawer', 'bottom_nav', 'hamburger']).default('drawer')\n .describe('Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu'),\n bottomNavItems: z.array(z.string()).optional()\n .describe('Navigation item IDs to show in bottom nav (max 5)'),\n }).optional().describe('Mobile-specific navigation configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the application'),\n});\n\n/**\n * App Factory Helper\n */\nexport const App = {\n create: (config: z.input): App => AppSchema.parse(config),\n} as const;\n\n/**\n * Type-safe factory for creating application definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example CRM App with nested navigation tree\n * ```ts\n * const crmApp = defineApp({\n * name: 'crm',\n * label: 'Sales CRM',\n * navigation: [\n * { id: 'grp_sales', type: 'group', label: 'Sales Cloud', expanded: true, children: [\n * { id: 'nav_pipeline', type: 'page', label: 'Pipeline', pageName: 'page_pipeline' },\n * { id: 'nav_accounts', type: 'page', label: 'Accounts', pageName: 'page_accounts' },\n * ]},\n * { id: 'nav_settings', type: 'page', label: 'Settings', pageName: 'admin_settings' },\n * ],\n * });\n * ```\n */\nexport function defineApp(config: z.input): App {\n return AppSchema.parse(config);\n}\n\n// Main Types\nexport type App = z.infer;\nexport type AppInput = z.input;\nexport type AppBranding = z.infer;\nexport type NavigationItem = z.infer;\nexport type NavigationArea = z.infer;\n\n// Discriminated Item Types (Helper exports)\nexport type ObjectNavItem = z.infer;\nexport type DashboardNavItem = z.infer;\nexport type PageNavItem = z.infer;\nexport type UrlNavItem = z.infer;\nexport type ReportNavItem = z.infer;\nexport type ActionNavItem = z.infer;\nexport type GroupNavItem = z.infer & { children: NavigationItem[] };\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Loader Protocol\n * \n * Defines the standard interface for loading and saving metadata in ObjectStack.\n * This protocol enables consistent metadata operations across different storage backends\n * (filesystem, HTTP, S3, databases) and serialization formats (JSON, YAML, TypeScript).\n */\n\n/**\n * Metadata Format Enum\n * Supported serialization formats for metadata\n */\nexport const MetadataFormatSchema = z.enum(['json', 'yaml', 'typescript', 'javascript']);\n\n/**\n * Metadata Statistics\n * Information about a metadata item without loading its full content\n */\nexport const MetadataStatsSchema = z.object({\n /**\n * Size of the metadata file in bytes\n */\n size: z.number().int().min(0).describe('File size in bytes'),\n \n /**\n * Last modification timestamp\n */\n modifiedAt: z.string().datetime().describe('Last modified date'),\n \n /**\n * ETag for cache validation\n * Used for conditional requests (If-None-Match header)\n */\n etag: z.string().describe('Entity tag for cache validation'),\n \n /**\n * Serialization format\n */\n format: MetadataFormatSchema.describe('Serialization format'),\n \n /**\n * Full file path (if applicable)\n */\n path: z.string().optional().describe('File system path'),\n \n /**\n * Additional metadata provider-specific properties\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Provider-specific metadata'),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n /**\n * Glob patterns to match files\n * Example: [\"**\\/*.object.ts\", \"**\\/*.object.json\"]\n */\n patterns: z.array(z.string()).optional().describe('File glob patterns'),\n \n /**\n * If-None-Match header for conditional loading\n * Only load if ETag doesn't match\n */\n ifNoneMatch: z.string().optional().describe('ETag for conditional request'),\n \n /**\n * If-Modified-Since header for conditional loading\n */\n ifModifiedSince: z.string().datetime().optional().describe('Only load if modified after this date'),\n \n /**\n * Whether to validate against Zod schema\n */\n validate: z.boolean().default(true).describe('Validate against schema'),\n \n /**\n * Whether to use cache if available\n */\n useCache: z.boolean().default(true).describe('Enable caching'),\n \n /**\n * Filter function (serialized as string)\n * Example: \"(item) => item.name.startsWith('sys_')\"\n */\n filter: z.string().optional().describe('Filter predicate as string'),\n \n /**\n * Maximum number of items to load\n */\n limit: z.number().int().min(1).optional().describe('Maximum items to load'),\n \n /**\n * Recursively search subdirectories\n */\n recursive: z.boolean().default(true).describe('Search subdirectories'),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n /**\n * Serialization format\n */\n format: MetadataFormatSchema.default('typescript').describe('Output format'),\n \n /**\n * Prettify output (formatted with indentation)\n */\n prettify: z.boolean().default(true).describe('Format with indentation'),\n \n /**\n * Indentation size (spaces)\n */\n indent: z.number().int().min(0).max(8).default(2).describe('Indentation spaces'),\n \n /**\n * Sort object keys alphabetically\n */\n sortKeys: z.boolean().default(false).describe('Sort object keys'),\n \n /**\n * Include default values in output\n */\n includeDefaults: z.boolean().default(false).describe('Include default values'),\n \n /**\n * Create backup before overwriting\n */\n backup: z.boolean().default(false).describe('Create backup file'),\n \n /**\n * Overwrite if exists\n */\n overwrite: z.boolean().default(true).describe('Overwrite existing file'),\n \n /**\n * Atomic write (write to temp file, then rename)\n */\n atomic: z.boolean().default(true).describe('Use atomic write operation'),\n \n /**\n * Custom file path (overrides default location)\n */\n path: z.string().optional().describe('Custom output path'),\n});\n\n/**\n * Metadata Export Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n /**\n * Output file path\n */\n output: z.string().describe('Output file path'),\n \n /**\n * Export format\n */\n format: MetadataFormatSchema.default('json').describe('Export format'),\n \n /**\n * Filter predicate as string\n */\n filter: z.string().optional().describe('Filter items to export'),\n \n /**\n * Include statistics in export\n */\n includeStats: z.boolean().default(false).describe('Include metadata statistics'),\n \n /**\n * Compress output\n */\n compress: z.boolean().default(false).describe('Compress output (gzip)'),\n \n /**\n * Pretty print output\n */\n prettify: z.boolean().default(true).describe('Pretty print output'),\n});\n\n/**\n * Metadata Import Options\n */\nexport const MetadataImportOptionsSchema = z.object({\n /**\n * Conflict resolution strategy\n */\n conflictResolution: z.enum(['skip', 'overwrite', 'merge', 'fail'])\n .default('merge')\n .describe('How to handle existing items'),\n \n /**\n * Validate items against schema\n */\n validate: z.boolean().default(true).describe('Validate before import'),\n \n /**\n * Dry run (don't actually save)\n */\n dryRun: z.boolean().default(false).describe('Simulate import without saving'),\n \n /**\n * Continue on errors\n */\n continueOnError: z.boolean().default(false).describe('Continue if validation fails'),\n \n /**\n * Transform function (as string)\n * Example: \"(item) => ({ ...item, imported: true })\"\n */\n transform: z.string().optional().describe('Transform items before import'),\n});\n\n/**\n * Metadata Loader Result\n * Result of a metadata load operation\n */\nexport const MetadataLoadResultSchema = z.object({\n /**\n * Loaded data\n */\n data: z.unknown().nullable().describe('Loaded metadata'),\n \n /**\n * Whether data came from cache (304 Not Modified)\n */\n fromCache: z.boolean().default(false).describe('Loaded from cache'),\n \n /**\n * Not modified (conditional request matched)\n */\n notModified: z.boolean().default(false).describe('Not modified since last request'),\n \n /**\n * ETag of loaded data\n */\n etag: z.string().optional().describe('Entity tag'),\n \n /**\n * Statistics about loaded data\n */\n stats: MetadataStatsSchema.optional().describe('Metadata statistics'),\n \n /**\n * Load time in milliseconds\n */\n loadTime: z.number().min(0).optional().describe('Load duration in ms'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n /**\n * Whether save was successful\n */\n success: z.boolean().describe('Save successful'),\n \n /**\n * Path where file was saved\n */\n path: z.string().describe('Output path'),\n \n /**\n * Generated ETag\n */\n etag: z.string().optional().describe('Generated entity tag'),\n \n /**\n * File size in bytes\n */\n size: z.number().int().min(0).optional().describe('File size'),\n \n /**\n * Save time in milliseconds\n */\n saveTime: z.number().min(0).optional().describe('Save duration in ms'),\n \n /**\n * Backup path (if created)\n */\n backupPath: z.string().optional().describe('Backup file path'),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum(['added', 'changed', 'deleted']).describe('Event type'),\n \n /**\n * Metadata type (e.g., 'object', 'view', 'app')\n */\n metadataType: z.string().describe('Type of metadata'),\n \n /**\n * Item name/identifier\n */\n name: z.string().describe('Item identifier'),\n \n /**\n * Full file path\n */\n path: z.string().describe('File path'),\n \n /**\n * Loaded item data (for added/changed events)\n */\n data: z.unknown().optional().describe('Item data'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\n/**\n * Metadata Collection Info\n * Summary of a metadata collection\n */\nexport const MetadataCollectionInfoSchema = z.object({\n /**\n * Collection type (e.g., 'object', 'view', 'app')\n */\n type: z.string().describe('Collection type'),\n \n /**\n * Total items in collection\n */\n count: z.number().int().min(0).describe('Number of items'),\n \n /**\n * Formats found in collection\n */\n formats: z.array(MetadataFormatSchema).describe('Formats in collection'),\n \n /**\n * Total size in bytes\n */\n totalSize: z.number().int().min(0).optional().describe('Total size in bytes'),\n \n /**\n * Last modified timestamp\n */\n lastModified: z.string().datetime().optional().describe('Last modification date'),\n \n /**\n * Collection location (path or URL)\n */\n location: z.string().optional().describe('Collection location'),\n});\n\n/**\n * Metadata Loader Interface Contract\n * Defines the standard methods all metadata loaders must implement\n */\nexport const MetadataLoaderContractSchema = z.object({\n /**\n * Loader name/identifier\n */\n name: z.string().describe('Loader identifier'),\n\n /**\n * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:')\n */\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Protocol identifier'),\n\n /**\n * Detailed capabilities\n */\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }).describe('Loader capabilities'),\n \n /**\n * Supported formats\n */\n supportedFormats: z.array(MetadataFormatSchema).describe('Supported formats'),\n \n /**\n * Whether loader supports watching for changes\n */\n supportsWatch: z.boolean().default(false).describe('Supports file watching'),\n \n /**\n * Whether loader supports saving\n */\n supportsWrite: z.boolean().default(true).describe('Supports write operations'),\n \n /**\n * Whether loader supports caching\n */\n supportsCache: z.boolean().default(true).describe('Supports caching'),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Manager Configuration\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory path'),\n \n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).default(['typescript', 'json', 'yaml']).describe('Enabled formats'),\n \n /**\n * Cache configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable caching'),\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n maxSize: z.number().int().min(0).optional().describe('Max cache size in bytes'),\n }).optional().describe('Cache settings'),\n \n /**\n * Watch for file changes\n */\n watch: z.boolean().default(false).describe('Enable file watching'),\n \n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n ignoreInitial: z.boolean().default(true).describe('Ignore initial add events'),\n }).optional().describe('File watcher options'),\n \n /**\n * Validation settings\n */\n validation: z.object({\n strict: z.boolean().default(true).describe('Strict validation'),\n throwOnError: z.boolean().default(true).describe('Throw on validation error'),\n }).optional().describe('Validation settings'),\n \n /**\n * Loader-specific options\n */\n loaderOptions: z.record(z.string(), z.unknown()).optional().describe('Loader-specific configuration'),\n});\n\n// Export types\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoadOptions = z.input;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Customization Layer Protocol\n * \n * Defines the overlay system for managing user customizations on top of\n * package-delivered metadata. This protocol solves the critical challenge\n * of separating \"vendor-managed\" metadata from \"customer-customized\" metadata,\n * enabling safe package upgrades without losing user changes.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed vs Unmanaged metadata components\n * - **ServiceNow**: Update Sets with collision detection\n * - **WordPress**: Parent/child theme overlay model\n * - **Kubernetes**: Strategic merge patch for resource customization\n * \n * ## Three-Layer Model\n * ```\n * ┌─────────────────────────────────┐\n * │ User Layer (scope: user) │ ← Personal overrides (per-user)\n * ├─────────────────────────────────┤\n * │ Platform Layer (scope: platform)│ ← Admin customizations (per-tenant)\n * ├─────────────────────────────────┤\n * │ System Layer (scope: system) │ ← Package-delivered metadata (read-only)\n * └─────────────────────────────────┘\n * ```\n * \n * ## Merge Resolution Order\n * Effective metadata = System ← merge(Platform) ← merge(User)\n * Each layer only stores the delta (changed fields), not the full definition.\n */\n\n// ==========================================\n// Customization Tracking\n// ==========================================\n\n/**\n * Customization Origin\n * Identifies who created the customization.\n */\nexport const CustomizationOriginSchema = z.enum([\n 'package', // Delivered by a plugin package (system layer, read-only)\n 'admin', // Created/modified by platform admin via UI\n 'user', // Created/modified by end user via UI\n 'migration', // Created during data migration\n 'api', // Created via API\n]);\n\n/**\n * Field-Level Change Tracking\n * Records exactly which fields were modified by the customer.\n */\nexport const FieldChangeSchema = z.object({\n /** JSON path to the changed field (e.g. \"fields.status.label\") */\n path: z.string().describe('JSON path to the changed field'),\n\n /** Original value from the package (for diff/rollback) */\n originalValue: z.unknown().optional().describe('Original value from the package'),\n\n /** Current customized value */\n currentValue: z.unknown().describe('Current customized value'),\n\n /** Who made this change */\n changedBy: z.string().optional().describe('User or admin who made this change'),\n\n /** When this change was made */\n changedAt: z.string().datetime().optional().describe('Timestamp of the change'),\n});\n\n/**\n * Metadata Overlay Schema\n * \n * Represents a customization layer on top of package-delivered metadata.\n * Each overlay stores only the delta (changed fields) relative to the base definition.\n * \n * During package upgrades, the system performs a 3-way merge:\n * 1. Old package version (base)\n * 2. New package version (theirs)\n * 3. Customer customizations (ours)\n * \n * @example\n * ```yaml\n * # Package delivers: object \"crm__account\" with field \"status\" label \"Status\"\n * # Admin changes label to \"Account Status\"\n * # Overlay record:\n * baseType: object\n * baseName: crm__account\n * packageId: com.acme.crm\n * packageVersion: \"1.0.0\"\n * changes:\n * - path: \"fields.status.label\"\n * originalValue: \"Status\"\n * currentValue: \"Account Status\"\n * ```\n */\nexport const MetadataOverlaySchema = z.object({\n /** Primary key */\n id: z.string().describe('Overlay record ID (UUID)'),\n\n /** The metadata type being customized (e.g. \"object\", \"view\", \"flow\") */\n baseType: z.string().describe('Metadata type being customized'),\n\n /** The metadata name being customized (e.g. \"crm__account\") */\n baseName: z.string().describe('Metadata name being customized'),\n\n /** Package that owns the base metadata (null for platform-created metadata) */\n packageId: z.string().optional().describe('Package ID that delivered the base metadata'),\n\n /** Package version when the customization was made (for upgrade diffing) */\n packageVersion: z.string().optional().describe('Package version when overlay was created'),\n\n /** Customization scope */\n scope: z.enum(['platform', 'user']).default('platform')\n .describe('Customization scope (platform=admin, user=personal)'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Owner user ID (for user-scope overlays) */\n owner: z.string().optional().describe('Owner user ID for user-scope overlays'),\n\n /**\n * The overlay payload.\n * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396).\n * - To modify a field: include the field with its new value\n * - To delete a field: set its value to null\n * - Omitted fields remain unchanged from base\n */\n patch: z.record(z.string(), z.unknown()).describe('JSON Merge Patch payload (changed fields only)'),\n\n /**\n * Detailed change tracking for each modified field.\n * Enables field-level conflict detection during upgrades.\n */\n changes: z.array(FieldChangeSchema).optional()\n .describe('Field-level change tracking for conflict detection'),\n\n /** Whether this overlay is currently active */\n active: z.boolean().default(true).describe('Whether this overlay is active'),\n\n /** Audit timestamps */\n createdAt: z.string().datetime().optional(),\n createdBy: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n updatedBy: z.string().optional(),\n});\n\n// ==========================================\n// Merge & Conflict Resolution\n// ==========================================\n\n/**\n * Merge Conflict\n * Represents a conflict between package update and customer customization.\n */\nexport const MergeConflictSchema = z.object({\n /** JSON path to the conflicting field */\n path: z.string().describe('JSON path to the conflicting field'),\n\n /** Value in the old package version */\n baseValue: z.unknown().describe('Value in the old package version'),\n\n /** Value in the new package version */\n incomingValue: z.unknown().describe('Value in the new package version'),\n\n /** Customer's customized value */\n customValue: z.unknown().describe('Customer customized value'),\n\n /** Suggested resolution strategy */\n suggestedResolution: z.enum([\n 'keep-custom', // Keep customer's customization\n 'accept-incoming', // Accept package update\n 'manual', // Requires manual resolution\n ]).describe('Suggested resolution strategy'),\n\n /** Reason for the suggested resolution */\n reason: z.string().optional().describe('Explanation for the suggested resolution'),\n});\n\n/**\n * Merge Strategy Configuration\n * Controls how metadata merging behaves during package upgrades.\n */\nexport const MergeStrategyConfigSchema = z.object({\n /** Default strategy when no field-level rule matches */\n defaultStrategy: z.enum([\n 'keep-custom', // Preserve all customer customizations (safe)\n 'accept-incoming', // Accept all package updates (overwrite)\n 'three-way-merge', // Intelligent 3-way merge with conflict detection\n ]).default('three-way-merge').describe('Default merge strategy'),\n\n /** \n * Field paths that should always accept incoming package updates.\n * Use for fields that the package vendor considers \"owned\" and should not be customized.\n * @example [\"fields.*.type\", \"triggers.*\"]\n */\n alwaysAcceptIncoming: z.array(z.string()).optional()\n .describe('Field paths that always accept package updates'),\n\n /**\n * Field paths where customer customizations always win.\n * Use for UI-facing fields like labels, descriptions, help text.\n * @example [\"fields.*.label\", \"fields.*.helpText\", \"description\"]\n */\n alwaysKeepCustom: z.array(z.string()).optional()\n .describe('Field paths where customer customizations always win'),\n\n /** Whether to automatically resolve non-conflicting changes */\n autoResolveNonConflicting: z.boolean().default(true)\n .describe('Auto-resolve changes that do not conflict'),\n});\n\n/**\n * Merge Result\n * Result of a 3-way merge operation during package upgrade.\n */\nexport const MergeResultSchema = z.object({\n /** Whether the merge completed successfully (no unresolved conflicts) */\n success: z.boolean().describe('Whether merge completed without unresolved conflicts'),\n\n /** The merged metadata payload */\n mergedMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Merged metadata result'),\n\n /** Updated overlay with remaining customizations */\n updatedOverlay: z.record(z.string(), z.unknown()).optional()\n .describe('Updated overlay after merge'),\n\n /** List of conflicts that require manual resolution */\n conflicts: z.array(MergeConflictSchema).optional()\n .describe('Unresolved merge conflicts'),\n\n /** Summary of automatically resolved changes */\n autoResolved: z.array(z.object({\n path: z.string(),\n resolution: z.string(),\n description: z.string().optional(),\n })).optional().describe('Summary of auto-resolved changes'),\n\n /** Statistics */\n stats: z.object({\n totalFields: z.number().int().min(0).describe('Total fields evaluated'),\n unchanged: z.number().int().min(0).describe('Fields with no changes'),\n autoResolved: z.number().int().min(0).describe('Fields auto-resolved'),\n conflicts: z.number().int().min(0).describe('Fields with conflicts'),\n }).optional(),\n});\n\n// ==========================================\n// Customization Management\n// ==========================================\n\n/**\n * Customizable Metadata Policy\n * Defines what parts of a metadata item can be customized by admins/users.\n * Package vendors use this to control customization boundaries.\n */\nexport const CustomizationPolicySchema = z.object({\n /** Metadata type this policy applies to */\n metadataType: z.string().describe('Metadata type (e.g. \"object\", \"view\")'),\n\n /** Whether customization is allowed at all for this type */\n allowCustomization: z.boolean().default(true),\n\n /**\n * Field paths that are locked (cannot be customized).\n * @example [\"name\", \"type\", \"fields.*.type\"]\n */\n lockedFields: z.array(z.string()).optional()\n .describe('Field paths that cannot be customized'),\n\n /**\n * Field paths that are customizable.\n * If specified, only these fields can be customized (whitelist mode).\n * @example [\"label\", \"description\", \"fields.*.label\", \"fields.*.helpText\"]\n */\n customizableFields: z.array(z.string()).optional()\n .describe('Field paths that can be customized (whitelist)'),\n\n /**\n * Whether users can add new fields to package objects.\n * When true, admins can extend package objects with custom fields.\n */\n allowAddFields: z.boolean().default(true)\n .describe('Whether admins can add new fields to package objects'),\n\n /**\n * Whether users can delete package-delivered fields.\n * Typically false — fields can only be hidden, not deleted.\n */\n allowDeleteFields: z.boolean().default(false)\n .describe('Whether admins can delete package-delivered fields'),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type CustomizationOrigin = z.infer;\nexport type FieldChange = z.infer;\nexport type MetadataOverlay = z.infer;\nexport type MergeConflict = z.infer;\nexport type MergeStrategyConfig = z.infer;\nexport type MergeResult = z.infer;\nexport type CustomizationPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { MetadataManagerConfigSchema } from './metadata-loader.zod';\nimport { MergeStrategyConfigSchema, CustomizationPolicySchema } from './metadata-customization.zod';\n\n/**\n * # Metadata Plugin Protocol\n *\n * Defines the specification for the **Metadata Plugin** — the central authority\n * responsible for managing ALL metadata across the ObjectStack platform.\n *\n * ## Architecture\n * The Metadata Plugin consolidates all scattered metadata operations into a single,\n * cohesive plugin that \"takes over\" the entire platform's metadata management:\n *\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ Metadata Plugin │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Type Registry │ │ Loader │ │ Customization Layer │ │\n * │ │ (all types) │ │ (file/db/s3)│ │ (overlay / merge) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Persistence │ │ Query │ │ Lifecycle │ │\n * │ │ (db records) │ │ (search) │ │ (validate/deploy) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n *\n * ## References\n * - kernel/metadata-loader.zod.ts — Storage backend protocol\n * - kernel/metadata-customization.zod.ts — Overlay/merge protocol\n * - system/metadata-persistence.zod.ts — Database record format\n * - contracts/metadata-service.ts — Service interface\n */\n\n// ==========================================\n// Metadata Type Registry\n// ==========================================\n\n/**\n * Platform Metadata Type Enum\n *\n * The canonical list of all metadata types managed by the platform.\n * Each type maps to a specific Zod schema (e.g., ObjectSchema, ViewSchema).\n * Plugins can extend this registry via `contributes.kinds` in the manifest.\n *\n * ## Naming Convention\n * **IMPORTANT:** All metadata type names are in **SINGULAR** form:\n * - ✅ Use: `'agent'`, `'tool'`, `'skill'`, `'view'`, `'flow'`, `'action'`\n * - ❌ NOT: `'agents'`, `'tools'`, `'skills'`, `'views'`, `'flows'`, `'actions'`\n *\n * This convention applies to:\n * - Protocol definitions (this enum)\n * - UI plugin registrations (`metadataTypes`, `metadataIcons`)\n * - Metadata service operations\n * - File patterns (`*.agent.ts`, `*.tool.ts`)\n *\n * REST API endpoints continue to use plural forms per REST conventions:\n * - `/api/v1/ai/agents`, `/api/v1/ai/conversations`\n */\nexport const MetadataTypeSchema = z.enum([\n // Data Protocol\n 'object', // Business entity definition (ObjectSchema)\n 'field', // Standalone field definition (FieldSchema)\n 'trigger', // Data-layer event triggers (TriggerSchema)\n 'validation', // Validation rules (ValidationSchema)\n 'hook', // Data hooks (HookSchema)\n\n // UI Protocol\n 'view', // List/form views (ViewSchema)\n 'page', // Standalone pages (PageSchema)\n 'dashboard', // Dashboard layouts (DashboardSchema)\n 'app', // Application shell (AppSchema)\n 'action', // UI/Server actions (ActionSchema)\n 'report', // Report definitions (ReportSchema)\n\n // Automation Protocol\n 'flow', // Visual logic flows (FlowSchema)\n 'workflow', // State machines (WorkflowSchema)\n 'approval', // Approval processes (ApprovalSchema)\n\n // System Protocol\n 'datasource', // Data connections (DatasourceSchema)\n 'translation', // i18n resources (TranslationSchema)\n 'router', // API routes\n 'function', // Serverless functions\n 'service', // Service definitions\n\n // Security Protocol\n 'permission', // Permission sets (PermissionSetSchema)\n 'profile', // User profiles (ProfileSchema)\n 'role', // Security roles\n\n // AI Protocol\n 'agent', // AI agent definitions (AgentSchema)\n 'tool', // AI tool definitions (ToolSchema)\n 'skill', // AI skill definitions (SkillSchema)\n]);\n\nexport type MetadataType = z.infer;\n\n// ==========================================\n// Type Registry Entry\n// ==========================================\n\n/**\n * Metadata Type Registry Entry\n *\n * Describes a registered metadata type, including its validation schema,\n * file patterns, and capabilities. Used by the metadata plugin to:\n * 1. Discover metadata files on disk\n * 2. Validate metadata payloads\n * 3. Determine storage behavior\n */\nexport const MetadataTypeRegistryEntrySchema = z.object({\n /** Metadata type identifier (e.g., 'object', 'view') */\n type: MetadataTypeSchema.describe('Metadata type identifier'),\n\n /** Human-readable label */\n label: z.string().describe('Display label for the metadata type'),\n\n /** Brief description */\n description: z.string().optional().describe('Description of the metadata type'),\n\n /**\n * File glob patterns for this type.\n * Used to discover metadata files on disk.\n * @example [\"**\\/*.object.ts\", \"**\\/*.object.yml\"]\n */\n filePatterns: z.array(z.string()).describe('Glob patterns to discover files of this type'),\n\n /**\n * Whether this type supports the customization overlay system.\n * When true, platform/user overlays can be applied on top of package-delivered metadata.\n */\n supportsOverlay: z.boolean().default(true).describe('Whether overlay customization is supported'),\n\n /**\n * Whether metadata of this type can be created at runtime via API.\n * Some types (e.g., 'object') may be restricted to deployment-only.\n */\n allowRuntimeCreate: z.boolean().default(true).describe('Allow runtime creation via API'),\n\n /**\n * Whether this type supports versioning.\n * When true, changes are tracked with version history.\n */\n supportsVersioning: z.boolean().default(false).describe('Whether version history is tracked'),\n\n /**\n * Priority order for loading (lower = earlier).\n * Objects load before views, views before dashboards.\n */\n loadOrder: z.number().int().min(0).default(100).describe('Loading priority (lower = earlier)'),\n\n /** The domain this type belongs to */\n domain: z.enum(['data', 'ui', 'automation', 'system', 'security', 'ai'])\n .describe('Protocol domain'),\n});\n\nexport type MetadataTypeRegistryEntry = z.infer;\n\n// ==========================================\n// Metadata Query Protocol\n// ==========================================\n\n/**\n * Metadata Query Schema\n *\n * Standard protocol for searching and filtering metadata items.\n * Used by the metadata service to support advanced metadata discovery.\n */\nexport const MetadataQuerySchema = z.object({\n /** Filter by metadata type(s) */\n types: z.array(MetadataTypeSchema).optional().describe('Filter by metadata types'),\n\n /** Filter by namespace(s) */\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n\n /** Filter by package ID */\n packageId: z.string().optional().describe('Filter by owning package'),\n\n /** Full-text search across name, label, description */\n search: z.string().optional().describe('Full-text search query'),\n\n /** Filter by scope */\n scope: z.enum(['system', 'platform', 'user']).optional().describe('Filter by scope'),\n\n /** Filter by state */\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional().describe('Filter by lifecycle state'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Sort field */\n sortBy: z.enum(['name', 'type', 'updatedAt', 'createdAt']).default('name').describe('Sort field'),\n\n /** Sort direction */\n sortOrder: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n\n /** Pagination: page number (1-based) */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(500).default(50).describe('Items per page'),\n});\n\nexport type MetadataQuery = z.input;\n\n/**\n * Metadata Query Result\n */\nexport const MetadataQueryResultSchema = z.object({\n /** Matched items */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n namespace: z.string().optional().describe('Namespace'),\n label: z.string().optional().describe('Display label'),\n scope: z.enum(['system', 'platform', 'user']).optional(),\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional(),\n packageId: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n })).describe('Matched metadata items'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching items'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page'),\n\n /** Page size */\n pageSize: z.number().int().min(1).describe('Page size'),\n});\n\nexport type MetadataQueryResult = z.infer;\n\n// ==========================================\n// Metadata Lifecycle Events\n// ==========================================\n\n/**\n * Metadata Event Schema\n *\n * Events emitted by the metadata plugin when metadata changes.\n * Enables reactive patterns across the platform (cache invalidation,\n * UI refresh, dependency tracking, etc.).\n */\nexport const MetadataEventSchema = z.object({\n /** Event type */\n event: z.enum([\n 'metadata.registered',\n 'metadata.updated',\n 'metadata.unregistered',\n 'metadata.validated',\n 'metadata.deployed',\n 'metadata.overlay.applied',\n 'metadata.overlay.removed',\n 'metadata.imported',\n 'metadata.exported',\n ]).describe('Event type'),\n\n /** Metadata type */\n metadataType: MetadataTypeSchema.describe('Metadata type'),\n\n /** Item name */\n name: z.string().describe('Metadata item name'),\n\n /** Namespace */\n namespace: z.string().optional().describe('Namespace'),\n\n /** Package ID (if package-managed) */\n packageId: z.string().optional().describe('Owning package ID'),\n\n /** Timestamp */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /** Actor who caused the event */\n actor: z.string().optional().describe('User or system that triggered the event'),\n\n /** Additional event-specific payload */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event-specific payload'),\n});\n\nexport type MetadataEvent = z.infer;\n\n// ==========================================\n// Metadata Validation\n// ==========================================\n\n/**\n * Metadata Validation Result\n */\nexport const MetadataValidationResultSchema = z.object({\n /** Whether validation passed */\n valid: z.boolean().describe('Whether the metadata is valid'),\n\n /** Validation errors */\n errors: z.array(z.object({\n path: z.string().describe('JSON path to the invalid field'),\n message: z.string().describe('Error description'),\n code: z.string().optional().describe('Error code'),\n })).optional().describe('Validation errors'),\n\n /** Validation warnings (non-blocking) */\n warnings: z.array(z.object({\n path: z.string().describe('JSON path to the field'),\n message: z.string().describe('Warning description'),\n })).optional().describe('Validation warnings'),\n});\n\nexport type MetadataValidationResult = z.infer;\n\n// ==========================================\n// Metadata Plugin Configuration\n// ==========================================\n\n/**\n * Metadata Plugin Configuration\n *\n * The unified configuration for the metadata plugin, combining\n * storage, caching, customization, and type registry settings.\n */\nexport const MetadataPluginConfigSchema = z.object({\n /**\n * Storage configuration.\n * References MetadataManagerConfigSchema for the underlying storage backend.\n */\n storage: MetadataManagerConfigSchema.describe('Storage backend configuration'),\n\n /**\n * Default customization policies per metadata type.\n * Controls what parts of metadata can be customized by admins/users.\n */\n customizationPolicies: z.array(CustomizationPolicySchema).optional()\n .describe('Default customization policies per type'),\n\n /**\n * Merge strategy for package upgrades.\n */\n mergeStrategy: MergeStrategyConfigSchema.optional()\n .describe('Merge strategy for package upgrades'),\n\n /**\n * Additional metadata type registrations.\n * Used by plugins to register custom metadata types beyond the built-in set.\n */\n additionalTypes: z.array(MetadataTypeRegistryEntrySchema.omit({ type: true }).extend({\n type: z.string().describe('Custom metadata type identifier'),\n })).optional().describe('Additional custom metadata types'),\n\n /**\n * Enable metadata change events.\n * When true, the plugin emits events on every metadata change.\n */\n enableEvents: z.boolean().default(true).describe('Emit metadata change events'),\n\n /**\n * Enable metadata validation on write operations.\n * When true, all metadata is validated against its type schema before saving.\n */\n validateOnWrite: z.boolean().default(true).describe('Validate metadata on write'),\n\n /**\n * Enable metadata versioning.\n * When true, changes to metadata are tracked with version history.\n */\n enableVersioning: z.boolean().default(false).describe('Track metadata version history'),\n\n /**\n * Maximum number of metadata items to keep in memory cache.\n */\n cacheMaxItems: z.number().int().min(0).default(10000).describe('Max items in memory cache'),\n});\n\nexport type MetadataPluginConfig = z.input;\n\n// ==========================================\n// Metadata Plugin Manifest\n// ==========================================\n\n/**\n * Metadata Plugin Manifest\n *\n * The complete manifest for the Metadata Plugin, declaring its identity,\n * capabilities, and configuration. This is the \"contract\" between the\n * metadata plugin and the kernel.\n */\nexport const MetadataPluginManifestSchema = z.object({\n /** Plugin identifier */\n id: z.literal('com.objectstack.metadata').describe('Metadata plugin ID'),\n\n /** Plugin name */\n name: z.literal('ObjectStack Metadata Service').describe('Plugin name'),\n\n /** Plugin version */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Plugin version'),\n\n /** Plugin type */\n type: z.literal('standard').describe('Plugin type'),\n\n /** Plugin description */\n description: z.string().default('Core metadata management service for ObjectStack platform')\n .describe('Plugin description'),\n\n /**\n * Capabilities this plugin provides.\n * The kernel uses this to route metadata requests to this plugin.\n */\n capabilities: z.object({\n /** Supports CRUD operations on metadata */\n crud: z.boolean().default(true).describe('Supports metadata CRUD'),\n\n /** Supports metadata query/search */\n query: z.boolean().default(true).describe('Supports metadata query'),\n\n /** Supports the overlay/customization system */\n overlay: z.boolean().default(true).describe('Supports customization overlays'),\n\n /** Supports file watching for hot reload */\n watch: z.boolean().default(false).describe('Supports file watching'),\n\n /** Supports bulk import/export */\n importExport: z.boolean().default(true).describe('Supports import/export'),\n\n /** Supports metadata validation */\n validation: z.boolean().default(true).describe('Supports schema validation'),\n\n /** Supports metadata versioning */\n versioning: z.boolean().default(false).describe('Supports version history'),\n\n /** Supports metadata events */\n events: z.boolean().default(true).describe('Emits metadata events'),\n }).describe('Plugin capabilities'),\n\n /** Plugin configuration */\n config: MetadataPluginConfigSchema.optional().describe('Plugin configuration'),\n});\n\nexport type MetadataPluginManifest = z.input;\n\n// ==========================================\n// Built-in Type Registry Defaults\n// ==========================================\n\n/**\n * Default Type Registry\n *\n * The built-in metadata type registry with default configurations.\n * Plugins extend this via `contributes.kinds` in the manifest.\n */\nexport const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntry[] = [\n // Data Protocol (load first)\n { type: 'object', label: 'Object', filePatterns: ['**/*.object.ts', '**/*.object.yml', '**/*.object.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 10, domain: 'data' },\n { type: 'field', label: 'Field', filePatterns: ['**/*.field.ts', '**/*.field.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 20, domain: 'data' },\n { type: 'trigger', label: 'Trigger', filePatterns: ['**/*.trigger.ts', '**/*.trigger.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'validation', label: 'Validation Rule', filePatterns: ['**/*.validation.ts', '**/*.validation.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'hook', label: 'Hook', filePatterns: ['**/*.hook.ts', '**/*.hook.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n\n // UI Protocol\n { type: 'view', label: 'View', filePatterns: ['**/*.view.ts', '**/*.view.yml', '**/*.view.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'page', label: 'Page', filePatterns: ['**/*.page.ts', '**/*.page.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'dashboard', label: 'Dashboard', filePatterns: ['**/*.dashboard.ts', '**/*.dashboard.yml', '**/*.dashboard.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n { type: 'app', label: 'Application', filePatterns: ['**/*.app.ts', '**/*.app.yml', '**/*.app.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 70, domain: 'ui' },\n { type: 'action', label: 'Action', filePatterns: ['**/*.action.ts', '**/*.action.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'report', label: 'Report', filePatterns: ['**/*.report.ts', '**/*.report.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n\n // Automation Protocol\n { type: 'flow', label: 'Flow', filePatterns: ['**/*.flow.ts', '**/*.flow.yml', '**/*.flow.json'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'workflow', label: 'Workflow', filePatterns: ['**/*.workflow.ts', '**/*.workflow.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'approval', label: 'Approval Process', filePatterns: ['**/*.approval.ts', '**/*.approval.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 80, domain: 'automation' },\n\n // System Protocol\n { type: 'datasource', label: 'Datasource', filePatterns: ['**/*.datasource.ts', '**/*.datasource.yml'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 5, domain: 'system' },\n { type: 'translation', label: 'Translation', filePatterns: ['**/*.translation.ts', '**/*.translation.yml', '**/*.translation.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 90, domain: 'system' },\n { type: 'router', label: 'Router', filePatterns: ['**/*.router.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'function', label: 'Function', filePatterns: ['**/*.function.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'service', label: 'Service', filePatterns: ['**/*.service.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n\n // Security Protocol\n { type: 'permission', label: 'Permission Set', filePatterns: ['**/*.permission.ts', '**/*.permission.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 15, domain: 'security' },\n { type: 'profile', label: 'Profile', filePatterns: ['**/*.profile.ts', '**/*.profile.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n { type: 'role', label: 'Role', filePatterns: ['**/*.role.ts', '**/*.role.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n\n // AI Protocol\n { type: 'agent', label: 'AI Agent', filePatterns: ['**/*.agent.ts', '**/*.agent.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 90, domain: 'ai' },\n { type: 'tool', label: 'AI Tool', filePatterns: ['**/*.tool.ts', '**/*.tool.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 85, domain: 'ai' },\n { type: 'skill', label: 'AI Skill', filePatterns: ['**/*.skill.ts', '**/*.skill.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 88, domain: 'ai' },\n];\n\n// ==========================================\n// Bulk Operation Types\n// ==========================================\n\n/**\n * Bulk Register Request\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n /** Items to register */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Namespace'),\n })).min(1).describe('Items to register'),\n\n /** Continue on individual item failure */\n continueOnError: z.boolean().default(false).describe('Continue if individual item fails'),\n\n /** Validate items before registering */\n validate: z.boolean().default(true).describe('Validate before register'),\n});\n\nexport type MetadataBulkRegisterRequest = z.input;\n\n/**\n * Bulk Operation Result\n */\nexport const MetadataBulkResultSchema = z.object({\n /** Total items processed */\n total: z.number().int().min(0).describe('Total items processed'),\n\n /** Successfully processed items */\n succeeded: z.number().int().min(0).describe('Successfully processed'),\n\n /** Failed items */\n failed: z.number().int().min(0).describe('Failed items'),\n\n /** Per-item error details */\n errors: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n error: z.string().describe('Error message'),\n })).optional().describe('Per-item errors'),\n});\n\nexport type MetadataBulkResult = z.infer;\n\n// ==========================================\n// Metadata Dependency\n// ==========================================\n\n/**\n * Metadata Dependency Schema\n *\n * Tracks dependencies between metadata items.\n * Used for impact analysis and safe deletion checks.\n */\nexport const MetadataDependencySchema = z.object({\n /** Source metadata type */\n sourceType: z.string().describe('Dependent metadata type'),\n\n /** Source metadata name */\n sourceName: z.string().describe('Dependent metadata name'),\n\n /** Target metadata type */\n targetType: z.string().describe('Referenced metadata type'),\n\n /** Target metadata name */\n targetName: z.string().describe('Referenced metadata name'),\n\n /** Dependency kind */\n kind: z.enum(['reference', 'extends', 'includes', 'triggers'])\n .describe('How the dependency is formed'),\n});\n\nexport type MetadataDependency = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { ObjectSchema } from '../data/object.zod';\nimport { AppSchema } from '../ui/app.zod';\nimport { MetadataTypeSchema, MetadataQuerySchema, MetadataQueryResultSchema, MetadataValidationResultSchema, MetadataBulkResultSchema, MetadataDependencySchema } from '../kernel/metadata-plugin.zod';\nimport { MetadataOverlaySchema } from '../kernel/metadata-customization.zod';\n\n/**\n * Metadata Service Protocol\n *\n * Defines the standard API contracts for the **@objectstack/metadata** package.\n * This is the single authority for ALL metadata-related services and APIs across\n * the entire platform, including Hono, Next.js, and NestJS adapters.\n *\n * ## Architecture\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ @objectstack/metadata — API Contracts │\n * │ │\n * │ CRUD │ Query/Search │ Bulk Ops │ Overlay │ Watch │\n * │ Import/Export│ Validation │ Type Reg │ Deps │ │\n * ├──────────────────────────────────────────────────────────────────┤\n * │ Hono Adapter │ Next.js Adapter │ NestJS Adapter │ CLI │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n */\n\n// ==========================================\n// 1. Legacy Responses (existing)\n// ==========================================\n\n/**\n * Single Object Definition Response\n * Returns the full JSON schema for an Entity (Fields, Actions, Config).\n */\nexport const ObjectDefinitionResponseSchema = BaseResponseSchema.extend({\n data: ObjectSchema.describe('Full Object Schema'),\n});\n\n/**\n * App Definition Response\n * Returns the navigation, branding, and layout for an App.\n */\nexport const AppDefinitionResponseSchema = BaseResponseSchema.extend({\n data: AppSchema.describe('Full App Configuration'),\n});\n\n/**\n * All Concepts Response\n * Bulk load lightweight definitions for autocomplete/pickers.\n */\nexport const ConceptListResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.object({\n name: z.string(),\n label: z.string(),\n icon: z.string().optional(),\n description: z.string().optional(),\n })).describe('List of available concepts (Objects, Apps, Flows)'),\n});\n\n// ==========================================\n// 2. CRUD Request / Response Schemas\n// ==========================================\n\n/**\n * Register (Create/Update) Metadata Request\n * POST /api/meta/:type\n * PUT /api/meta/:type/:name\n */\nexport const MetadataRegisterRequestSchema = z.object({\n type: MetadataTypeSchema.describe('Metadata type'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Item name (snake_case)'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Optional namespace'),\n});\n\n/**\n * Single Metadata Item Response\n * GET /api/meta/:type/:name\n */\nexport const MetadataItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n definition: z.record(z.string(), z.unknown()).describe('Metadata definition payload'),\n }).describe('Metadata item'),\n});\n\n/**\n * Metadata List Response\n * GET /api/meta/:type\n */\nexport const MetadataListResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.record(z.string(), z.unknown())).describe('Array of metadata definitions'),\n});\n\n/**\n * Metadata Names Response\n * GET /api/meta/:type/names\n */\nexport const MetadataNamesResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.string()).describe('Array of metadata item names'),\n});\n\n/**\n * Metadata Exists Response\n * GET /api/meta/:type/:name/exists\n */\nexport const MetadataExistsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n exists: z.boolean().describe('Whether the item exists'),\n }),\n});\n\n/**\n * Metadata Delete Response\n * DELETE /api/meta/:type/:name\n */\nexport const MetadataDeleteResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Deleted item name'),\n }),\n});\n\n// ==========================================\n// 3. Query / Search\n// ==========================================\n\n/**\n * Metadata Query Request\n * POST /api/meta/query\n */\nexport const MetadataQueryRequestSchema = MetadataQuerySchema.describe(\n 'Metadata query with filtering, sorting, and pagination',\n);\n\n/**\n * Metadata Query Response\n * POST /api/meta/query\n */\nexport const MetadataQueryResponseSchema = BaseResponseSchema.extend({\n data: MetadataQueryResultSchema.describe('Paginated query result'),\n});\n\n// ==========================================\n// 4. Bulk Operations\n// ==========================================\n\n/**\n * Bulk Register Request\n * POST /api/meta/bulk/register\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n })).min(1).describe('Items to register'),\n continueOnError: z.boolean().default(false).describe('Continue on individual failure'),\n validate: z.boolean().default(true).describe('Validate before registering'),\n});\n\n/**\n * Bulk Unregister Request\n * POST /api/meta/bulk/unregister\n */\nexport const MetadataBulkUnregisterRequestSchema = z.object({\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n })).min(1).describe('Items to unregister'),\n});\n\n/**\n * Bulk Operation Response\n * POST /api/meta/bulk/*\n */\nexport const MetadataBulkResponseSchema = BaseResponseSchema.extend({\n data: MetadataBulkResultSchema.describe('Bulk operation result'),\n});\n\n// ==========================================\n// 5. Overlay / Customization\n// ==========================================\n\n/**\n * Get Overlay Response\n * GET /api/meta/:type/:name/overlay\n */\nexport const MetadataOverlayResponseSchema = BaseResponseSchema.extend({\n data: MetadataOverlaySchema.optional().describe('Overlay definition, undefined if none'),\n});\n\n/**\n * Save Overlay Request\n * PUT /api/meta/:type/:name/overlay\n */\nexport const MetadataOverlaySaveRequestSchema = MetadataOverlaySchema.describe(\n 'Overlay to save',\n);\n\n/**\n * Get Effective (merged) Response\n * GET /api/meta/:type/:name/effective\n */\nexport const MetadataEffectiveResponseSchema = BaseResponseSchema.extend({\n data: z.record(z.string(), z.unknown()).optional()\n .describe('Effective metadata with all overlays applied'),\n});\n\n// ==========================================\n// 6. Import / Export\n// ==========================================\n\n/**\n * Export Metadata Request\n * POST /api/meta/export\n */\nexport const MetadataExportRequestSchema = z.object({\n types: z.array(z.string()).optional().describe('Filter by metadata types'),\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n format: z.enum(['json', 'yaml']).default('json').describe('Export format'),\n});\n\n/**\n * Export Metadata Response\n * POST /api/meta/export\n */\nexport const MetadataExportResponseSchema = BaseResponseSchema.extend({\n data: z.unknown().describe('Exported metadata bundle'),\n});\n\n/**\n * Import Metadata Request\n * POST /api/meta/import\n */\nexport const MetadataImportRequestSchema = z.object({\n data: z.unknown().describe('Metadata bundle to import'),\n conflictResolution: z.enum(['skip', 'overwrite', 'merge']).default('skip')\n .describe('Conflict resolution strategy'),\n validate: z.boolean().default(true).describe('Validate before import'),\n dryRun: z.boolean().default(false).describe('Dry run (no save)'),\n});\n\n/**\n * Import Metadata Response\n * POST /api/meta/import\n */\nexport const MetadataImportResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n total: z.number().int().min(0),\n imported: z.number().int().min(0),\n skipped: z.number().int().min(0),\n failed: z.number().int().min(0),\n errors: z.array(z.object({\n type: z.string(),\n name: z.string(),\n error: z.string(),\n })).optional(),\n }).describe('Import result'),\n});\n\n// ==========================================\n// 7. Validation\n// ==========================================\n\n/**\n * Validate Metadata Request\n * POST /api/meta/validate\n */\nexport const MetadataValidateRequestSchema = z.object({\n type: z.string().describe('Metadata type to validate against'),\n data: z.unknown().describe('Metadata payload to validate'),\n});\n\n/**\n * Validate Metadata Response\n * POST /api/meta/validate\n */\nexport const MetadataValidateResponseSchema = BaseResponseSchema.extend({\n data: MetadataValidationResultSchema.describe('Validation result'),\n});\n\n// ==========================================\n// 8. Type Registry\n// ==========================================\n\n/**\n * List Registered Types Response\n * GET /api/meta/types\n */\nexport const MetadataTypesResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.string()).describe('Registered metadata type identifiers'),\n});\n\n/**\n * Type Info Response\n * GET /api/meta/types/:type\n */\nexport const MetadataTypeInfoResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type identifier'),\n label: z.string().describe('Display label'),\n description: z.string().optional().describe('Description'),\n filePatterns: z.array(z.string()).describe('File glob patterns'),\n supportsOverlay: z.boolean().describe('Overlay support'),\n domain: z.string().describe('Protocol domain'),\n }).optional().describe('Type info'),\n});\n\n// ==========================================\n// 9. Dependency Tracking\n// ==========================================\n\n/**\n * Dependencies Response\n * GET /api/meta/:type/:name/dependencies\n */\nexport const MetadataDependenciesResponseSchema = BaseResponseSchema.extend({\n data: z.array(MetadataDependencySchema).describe('Items this item depends on'),\n});\n\n/**\n * Dependents Response\n * GET /api/meta/:type/:name/dependents\n */\nexport const MetadataDependentsResponseSchema = BaseResponseSchema.extend({\n data: z.array(MetadataDependencySchema).describe('Items that depend on this item'),\n});\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type ObjectDefinitionResponse = z.infer;\nexport type AppDefinitionResponse = z.infer;\nexport type ConceptListResponse = z.infer;\nexport type MetadataRegisterRequest = z.infer;\nexport type MetadataItemResponse = z.infer;\nexport type MetadataListResponse = z.infer;\nexport type MetadataNamesResponse = z.infer;\nexport type MetadataExistsResponse = z.infer;\nexport type MetadataDeleteResponse = z.infer;\nexport type MetadataQueryResponse = z.infer;\nexport type MetadataBulkResponse = z.infer;\nexport type MetadataOverlayResponse = z.infer;\nexport type MetadataEffectiveResponse = z.infer;\nexport type MetadataExportResponse = z.infer;\nexport type MetadataImportResponse = z.infer;\nexport type MetadataValidateResponse = z.infer;\nexport type MetadataTypesResponse = z.infer;\nexport type MetadataTypeInfoResponse = z.infer;\nexport type MetadataDependenciesResponse = z.infer;\nexport type MetadataDependentsResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Service Registry Protocol\n * \n * Defines the standard built-in services that constitute the ObjectStack Kernel.\n * This registry is used by the `ObjectKernel` and `HttpDispatcher` to:\n * 1. Verify service availability.\n * 2. Route requests to the correct service handler.\n * 3. Type-check service interactions.\n */\n\n// ==========================================\n// Service Identifiers\n// ==========================================\n\nexport const CoreServiceName = z.enum([\n // Core Data & Metadata\n 'metadata', // Object/Field Definitions\n 'data', // CRUD & Query Engine\n 'auth', // Authentication & Identity\n \n // Infrastructure\n 'file-storage', // Storage Driver (Local/S3)\n 'search', // Search Engine (Elastic/Meili)\n 'cache', // Cache Driver (Redis/Memory)\n 'queue', // Job Queue (BullMQ/Redis)\n \n // Advanced Capabilities\n 'automation', // Flow & Script Engine\n 'graphql', // GraphQL API Engine\n 'analytics', // BI & Semantic Layer\n 'realtime', // WebSocket & PubSub\n 'job', // Background Job Manager\n 'notification', // Email/Push/SMS\n 'ai', // AI Engine (NLQ, Chat, Suggest, Insights)\n 'i18n', // Internationalization Service\n 'ui', // UI Metadata Service (View CRUD)\n 'workflow', // Workflow State Machine Engine\n]);\n\nexport type CoreServiceName = z.infer;\n\n/**\n * Service Criticality Level\n * Defines the startup behavior when a service is missing.\n */\nexport const ServiceCriticalitySchema = z.enum([\n 'required', // System fails to start if missing (Exit Code 1)\n 'core', // System warns if missing, functionality degraded (Warn)\n 'optional', // System ignores if missing, feature disabled (Info)\n]);\n\n/**\n * Service Requirement Definition\n */\nexport const ServiceRequirementDef = {\n // Required: The kernel cannot function without these\n data: 'required',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n metadata: 'core',\n auth: 'core',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n cache: 'core',\n queue: 'core',\n job: 'core',\n i18n: 'core',\n\n // Optional: Add-on capabilities\n 'file-storage': 'optional',\n search: 'optional',\n automation: 'optional',\n graphql: 'optional',\n analytics: 'optional',\n realtime: 'optional',\n notification: 'optional',\n ai: 'optional',\n ui: 'optional',\n workflow: 'optional',\n} as const;\n\n// ==========================================\n// Service Capabilities\n// ==========================================\n\n/**\n * Describes the availability and health of a service\n */\nexport const ServiceStatusSchema = z.object({\n name: CoreServiceName,\n enabled: z.boolean(),\n status: z.enum(['running', 'stopped', 'degraded', 'initializing']),\n version: z.string().optional(),\n provider: z.string().optional().describe('Implementation provider (e.g. \"s3\" for storage)'),\n features: z.array(z.string()).optional().describe('List of supported sub-features'),\n});\n\n/**\n * The Contract definition for what the Kernel MUST expose\n * map\n */\nexport const KernelServiceMapSchema = z.record(\n CoreServiceName, \n z.unknown().describe('Service Instance implementing the protocol interface')\n);\n\n// ==========================================\n// Service Interfaces (Stub definitions)\n// ==========================================\n// Ideally, we would define strict Typescript interfaces here \n// for what methods each service must expose to the Registry.\n// For Zod, we primarily validate configuration and status.\n\n// e.g.\nexport const ServiceConfigSchema = z.object({\n id: z.string(),\n name: CoreServiceName,\n options: z.record(z.string(), z.unknown()).optional(),\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { CoreServiceName, ServiceCriticalitySchema } from '../system/core-services.zod';\n\n/**\n * # HttpDispatcher Protocol\n * \n * Defines how the ObjectStack HttpDispatcher routes incoming API requests\n * to the correct kernel service based on URL prefix matching.\n * \n * The dispatcher is the central routing component that:\n * 1. Matches incoming request URLs against registered route prefixes\n * 2. Delegates to the corresponding CoreService implementation\n * 3. Returns 503 Service Unavailable when a service is not registered\n * 4. Supports dynamic route registration from plugins via contributes.routes\n * \n * Architecture alignment:\n * - Kubernetes: API server aggregation layer\n * - Eclipse: Extension registry routing\n * - VS Code: Command palette routing\n */\n\n// ============================================================================\n// Route Definition\n// ============================================================================\n\n/**\n * Dispatcher Route Schema\n * Maps a URL prefix to a kernel service.\n * \n * @example\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"authRequired\": true,\n * \"criticality\": \"required\"\n * }\n */\nexport const DispatcherRouteSchema = z.object({\n /**\n * URL path prefix for routing.\n * Incoming requests matching this prefix are routed to the target service.\n * Must start with '/'.\n */\n prefix: z.string().regex(/^\\//).describe('URL path prefix for routing (e.g. /api/v1/data)'),\n \n /**\n * Target core service name.\n * The service that handles requests matching this prefix.\n */\n service: CoreServiceName.describe('Target core service name'),\n \n /**\n * Whether requests to this route require authentication.\n * Discovery endpoint is typically public; most others require auth.\n * @default true\n */\n authRequired: z.boolean().default(true).describe('Whether authentication is required'),\n \n /**\n * Service criticality level.\n * Determines behavior when the service is unavailable:\n * - required: return 500 Internal Server Error\n * - core: return 503 with degraded notice\n * - optional: return 503 Service Unavailable\n * @default 'optional'\n */\n criticality: ServiceCriticalitySchema.default('optional')\n .describe('Service criticality level for unavailability handling'),\n \n /**\n * Required permissions for accessing this route namespace.\n * Applied as a baseline before individual endpoint permission checks.\n */\n permissions: z.array(z.string()).optional()\n .describe('Required permissions for this route namespace'),\n});\n\nexport type DispatcherRoute = z.infer;\nexport type DispatcherRouteInput = z.input;\n\n// ============================================================================\n// Dispatcher Configuration\n// ============================================================================\n\n/**\n * Dispatcher Configuration Schema\n * Complete configuration for the HttpDispatcher routing table.\n * \n * @example\n * {\n * \"routes\": [\n * { \"prefix\": \"/api/v1/discovery\", \"service\": \"metadata\", \"authRequired\": false },\n * { \"prefix\": \"/api/v1/meta\", \"service\": \"metadata\" },\n * { \"prefix\": \"/api/v1/data\", \"service\": \"data\", \"criticality\": \"required\" },\n * { \"prefix\": \"/api/v1/auth\", \"service\": \"auth\", \"criticality\": \"required\" },\n * { \"prefix\": \"/api/v1/ai\", \"service\": \"ai\" }\n * ],\n * \"fallback\": \"404\"\n * }\n */\nexport const DispatcherConfigSchema = z.object({\n /**\n * Registered route mappings.\n * Routes are matched by longest-prefix-first strategy.\n */\n routes: z.array(DispatcherRouteSchema).describe('Route-to-service mappings'),\n \n /**\n * Behavior when no route matches the request.\n * - 404: Return 404 Not Found (default)\n * - proxy: Forward to a configured proxy target\n * - custom: Delegate to a custom handler\n * @default '404'\n */\n fallback: z.enum(['404', 'proxy', 'custom']).default('404')\n .describe('Behavior when no route matches'),\n \n /**\n * Proxy target URL for fallback: 'proxy' mode.\n */\n proxyTarget: z.string().url().optional()\n .describe('Proxy target URL when fallback is \"proxy\"'),\n});\n\nexport type DispatcherConfig = z.infer;\nexport type DispatcherConfigInput = z.input;\n\n// ============================================================================\n// Default Route Table\n// ============================================================================\n\n/**\n * Default route table for the ObjectStack HttpDispatcher.\n * Maps all Protocol namespaces to their corresponding services.\n * \n * This is the recommended baseline configuration. Plugins can extend\n * this table by declaring routes in their manifest's contributes.routes.\n */\nexport const DEFAULT_DISPATCHER_ROUTES: DispatcherRouteInput[] = [\n // Discovery (public)\n { prefix: '/api/v1/discovery', service: 'metadata', authRequired: false, criticality: 'required' },\n \n // Health (public)\n { prefix: '/api/v1/health', service: 'metadata', authRequired: false, criticality: 'required' },\n \n // Required Services\n { prefix: '/api/v1/meta', service: 'metadata', criticality: 'required' },\n { prefix: '/api/v1/data', service: 'data', criticality: 'required' },\n { prefix: '/api/v1/auth', service: 'auth', criticality: 'required' },\n \n // Optional Services (plugin-provided)\n { prefix: '/api/v1/packages', service: 'metadata' },\n { prefix: '/api/v1/ui', service: 'ui' }, // @deprecated — use /api/v1/meta/view and /api/v1/meta/dashboard instead\n { prefix: '/api/v1/workflow', service: 'workflow' },\n { prefix: '/api/v1/analytics', service: 'analytics' },\n { prefix: '/api/v1/automation', service: 'automation' },\n { prefix: '/api/v1/storage', service: 'file-storage' },\n { prefix: '/api/v1/feed', service: 'data' },\n { prefix: '/api/v1/i18n', service: 'i18n' },\n { prefix: '/api/v1/notifications', service: 'notification' },\n { prefix: '/api/v1/realtime', service: 'realtime' },\n { prefix: '/api/v1/ai', service: 'ai' },\n];\n\n// ============================================================================\n// Dispatcher Error Codes\n// ============================================================================\n\n/**\n * Semantic HTTP error codes used by the Dispatcher.\n *\n * The dispatcher MUST distinguish between these four failure modes so that\n * clients (and developers) can understand *why* an API call failed:\n *\n * - `404` – Route Not Found: no route is registered for this path.\n * - `405` – Method Not Allowed: route exists but the HTTP method is not supported.\n * - `501` – Not Implemented: route is declared but the handler is a stub / not yet coded.\n * - `503` – Service Unavailable: service exists but is temporarily down or not loaded.\n *\n * Note: These are string representations of HTTP status codes for use in enum\n * matching. The `DispatcherErrorResponseSchema.error.code` field carries the\n * numeric HTTP status code for direct use in HTTP responses.\n */\nexport const DispatcherErrorCode = z.enum(['404', '405', '501', '503']).describe(\n '404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable'\n);\n\nexport type DispatcherErrorCode = z.infer;\n\n/**\n * Dispatcher Error Response Schema\n *\n * Standardised error envelope returned by the dispatcher when a request cannot\n * be fulfilled. Adapters MUST use this shape (or a superset) for all non-2xx\n * responses so that clients can programmatically distinguish failure modes.\n */\nexport const DispatcherErrorResponseSchema = z.object({\n /** Always `false` for error responses */\n success: z.literal(false),\n error: z.object({\n /** HTTP status code */\n code: z.number().int().describe('HTTP status code (404, 405, 501, 503, …)'),\n /** Human-readable error message */\n message: z.string().describe('Human-readable error message'),\n /**\n * Machine-readable error type for programmatic branching.\n */\n type: z.enum([\n 'ROUTE_NOT_FOUND',\n 'METHOD_NOT_ALLOWED',\n 'NOT_IMPLEMENTED',\n 'SERVICE_UNAVAILABLE',\n ]).optional().describe('Machine-readable error type'),\n /** Route that was requested */\n route: z.string().optional().describe('Requested route path'),\n /** Service that the route maps to (if known) */\n service: z.string().optional().describe('Target service name, if resolvable'),\n /** Guidance for the developer */\n hint: z.string().optional().describe('Actionable hint for the developer (e.g., \"Install plugin-workflow\")'),\n }),\n});\n\nexport type DispatcherErrorResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, CorsConfigSchema, RateLimitConfigSchema, StaticMountSchema } from '../shared/http.zod';\n\n/**\n * HTTP Server Protocol\n * \n * Defines the runtime HTTP server configuration and capabilities.\n * Provides abstractions for HTTP server implementations (Express, Fastify, Hono, etc.)\n * \n * Architecture alignment:\n * - Kubernetes: Service and Ingress resources\n * - AWS: API Gateway configuration\n * - Spring Boot: Application properties\n */\n\n// ==========================================\n// Server Configuration\n// ==========================================\n\n/**\n * HTTP Server Configuration Schema\n * Core configuration for HTTP server instances\n * \n * @example\n * {\n * \"port\": 3000,\n * \"host\": \"0.0.0.0\",\n * \"cors\": {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\"]\n * },\n * \"compression\": true,\n * \"requestTimeout\": 30000\n * }\n */\nexport const HttpServerConfigSchema = z.object({\n /**\n * Server port number\n */\n port: z.number().int().min(1).max(65535).default(3000).describe('Port number to listen on'),\n \n /**\n * Server host address\n */\n host: z.string().default('0.0.0.0').describe('Host address to bind to'),\n \n /**\n * CORS configuration\n */\n cors: CorsConfigSchema.optional().describe('CORS configuration'),\n \n /**\n * Request handling options\n */\n requestTimeout: z.number().int().default(30000).describe('Request timeout in milliseconds'),\n bodyLimit: z.string().default('10mb').describe('Maximum request body size'),\n \n /**\n * Compression settings\n */\n compression: z.boolean().default(true).describe('Enable response compression'),\n \n /**\n * Security headers\n */\n security: z.object({\n helmet: z.boolean().default(true).describe('Enable security headers via helmet'),\n rateLimit: RateLimitConfigSchema.optional().describe('Global rate limiting configuration'),\n }).optional().describe('Security configuration'),\n \n /**\n * Static file serving\n */\n static: z.array(StaticMountSchema).optional().describe('Static file serving configuration'),\n \n /**\n * Trust proxy settings\n */\n trustProxy: z.boolean().default(false).describe('Trust X-Forwarded-* headers'),\n});\n\nexport type HttpServerConfig = z.infer;\nexport type HttpServerConfigInput = z.input;\n\n// ==========================================\n// Route Registration\n// ==========================================\n\n/**\n * Route Handler Metadata Schema\n * Metadata for route handlers used in registration\n */\nexport const RouteHandlerMetadataSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (supports parameters like /api/users/:id)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Handler function name or identifier\n */\n handler: z.string().describe('Handler identifier or name'),\n \n /**\n * Route metadata\n */\n metadata: z.object({\n summary: z.string().optional().describe('Route summary for documentation'),\n description: z.string().optional().describe('Route description'),\n tags: z.array(z.string()).optional().describe('Tags for grouping'),\n operationId: z.string().optional().describe('Unique operation identifier'),\n }).optional(),\n \n /**\n * Security requirements\n */\n security: z.object({\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n rateLimit: z.string().optional().describe('Rate limit policy override'),\n }).optional(),\n});\n\nexport type RouteHandlerMetadata = z.infer;\nexport type RouteHandlerMetadataInput = z.input;\n\n// ==========================================\n// Middleware Configuration\n// ==========================================\n\n/**\n * Middleware Type Enum\n */\nexport const MiddlewareType = z.enum([\n 'authentication', // Authentication middleware\n 'authorization', // Authorization/permission checks\n 'logging', // Request/response logging\n 'validation', // Input validation\n 'transformation', // Request/response transformation\n 'error', // Error handling\n 'custom', // Custom middleware\n]);\n\nexport type MiddlewareType = z.infer;\n\n/**\n * Middleware Configuration Schema\n * Defines middleware execution order and configuration\n * \n * @example\n * {\n * \"name\": \"auth_middleware\",\n * \"type\": \"authentication\",\n * \"enabled\": true,\n * \"order\": 10,\n * \"config\": {\n * \"jwtSecret\": \"secret\",\n * \"excludePaths\": [\"/health\", \"/metrics\"]\n * }\n * }\n */\nexport const MiddlewareConfigSchema = z.object({\n /**\n * Middleware identifier\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Middleware name (snake_case)'),\n \n /**\n * Middleware type\n */\n type: MiddlewareType.describe('Middleware type'),\n \n /**\n * Enable/disable middleware\n */\n enabled: z.boolean().default(true).describe('Whether middleware is enabled'),\n \n /**\n * Execution order (lower numbers execute first)\n */\n order: z.number().int().default(100).describe('Execution order priority'),\n \n /**\n * Middleware-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Middleware configuration object'),\n \n /**\n * Path patterns to apply middleware to\n */\n paths: z.object({\n include: z.array(z.string()).optional().describe('Include path patterns (glob)'),\n exclude: z.array(z.string()).optional().describe('Exclude path patterns (glob)'),\n }).optional().describe('Path filtering'),\n});\n\nexport type MiddlewareConfig = z.infer;\nexport type MiddlewareConfigInput = z.input;\n\n// ==========================================\n// Server Lifecycle Events\n// ==========================================\n\n/**\n * Server Event Type Enum\n */\nexport const ServerEventType = z.enum([\n 'starting', // Server is starting\n 'started', // Server has started and is listening\n 'stopping', // Server is stopping\n 'stopped', // Server has stopped\n 'request', // Request received\n 'response', // Response sent\n 'error', // Error occurred\n]);\n\nexport type ServerEventType = z.infer;\n\n/**\n * Server Event Schema\n * Events emitted by the HTTP server during lifecycle\n */\nexport const ServerEventSchema = z.object({\n /**\n * Event type\n */\n type: ServerEventType.describe('Event type'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp (ISO 8601)'),\n \n /**\n * Event payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Event-specific data'),\n});\n\nexport type ServerEvent = z.infer;\n\n// ==========================================\n// Server Capability Declaration\n// ==========================================\n\n/**\n * Server Capabilities Schema\n * Declares what features a server implementation supports\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Supported HTTP versions\n */\n httpVersions: z.array(z.enum(['1.0', '1.1', '2.0', '3.0'])).default(['1.1']).describe('Supported HTTP versions'),\n \n /**\n * WebSocket support\n */\n websocket: z.boolean().default(false).describe('WebSocket support'),\n \n /**\n * Server-Sent Events support\n */\n sse: z.boolean().default(false).describe('Server-Sent Events support'),\n \n /**\n * HTTP/2 Server Push\n */\n serverPush: z.boolean().default(false).describe('HTTP/2 Server Push support'),\n \n /**\n * Streaming support\n */\n streaming: z.boolean().default(true).describe('Response streaming support'),\n \n /**\n * Middleware support\n */\n middleware: z.boolean().default(true).describe('Middleware chain support'),\n \n /**\n * Route parameterization\n */\n routeParams: z.boolean().default(true).describe('URL parameter support (/users/:id)'),\n \n /**\n * Built-in compression\n */\n compression: z.boolean().default(true).describe('Built-in compression support'),\n});\n\nexport type ServerCapabilities = z.infer;\nexport type ServerCapabilitiesInput = z.input;\n\n// ==========================================\n// Server Status & Metrics\n// ==========================================\n\n/**\n * Server Status Schema\n * Current operational status of the server\n */\nexport const ServerStatusSchema = z.object({\n /**\n * Server state\n */\n state: z.enum(['stopped', 'starting', 'running', 'stopping', 'error']).describe('Current server state'),\n \n /**\n * Uptime in milliseconds\n */\n uptime: z.number().int().optional().describe('Server uptime in milliseconds'),\n \n /**\n * Server information\n */\n server: z.object({\n port: z.number().int().describe('Listening port'),\n host: z.string().describe('Bound host'),\n url: z.string().optional().describe('Full server URL'),\n }).optional(),\n \n /**\n * Connection metrics\n */\n connections: z.object({\n active: z.number().int().describe('Active connections'),\n total: z.number().int().describe('Total connections handled'),\n }).optional(),\n \n /**\n * Request metrics\n */\n requests: z.object({\n total: z.number().int().describe('Total requests processed'),\n success: z.number().int().describe('Successful requests'),\n errors: z.number().int().describe('Failed requests'),\n }).optional(),\n});\n\nexport type ServerStatus = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create HTTP server configuration\n */\nexport const HttpServerConfig = Object.assign(HttpServerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create middleware configuration\n */\nexport const MiddlewareConfig = Object.assign(MiddlewareConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\nimport { MiddlewareConfigSchema } from '../system/http-server.zod';\n\n/**\n * REST API Plugin Protocol\n * \n * Defines the schema for REST API plugins that register Discovery, Metadata,\n * Data CRUD, Batch, and Permission routes with the HTTP Dispatcher.\n * \n * This plugin type implements Phase 2 of the API Protocol implementation plan,\n * providing standardized REST endpoints with:\n * - Request validation middleware using Zod schemas\n * - Response envelope wrapping with BaseResponseSchema\n * - Error handling using ApiErrorSchema\n * - OpenAPI documentation auto-generation\n * \n * Features:\n * - Route registration for core API endpoints\n * - Automatic schema-based validation\n * - Standardized request/response envelopes\n * - OpenAPI/Swagger documentation generation\n * \n * Architecture Alignment:\n * - Salesforce: REST API with metadata and data CRUD\n * - Microsoft Dynamics: Web API with entity operations\n * - Strapi: Auto-generated REST endpoints from schemas\n * \n * @example Plugin Manifest\n * ```typescript\n * {\n * \"name\": \"rest_api\",\n * \"version\": \"1.0.0\",\n * \"type\": \"server\",\n * \"contributes\": {\n * \"routes\": [\n * {\n * \"prefix\": \"/api/v1/discovery\",\n * \"service\": \"metadata\",\n * \"methods\": [\"getDiscovery\"],\n * \"middleware\": [\n * { \"name\": \"response_envelope\", \"type\": \"transformation\", \"enabled\": true }\n * ]\n * },\n * {\n * \"prefix\": \"/api/v1/meta\",\n * \"service\": \"metadata\",\n * \"methods\": [\"getMetaTypes\", \"getMetaItems\", \"getMetaItem\", \"saveMetaItem\"],\n * \"middleware\": [\n * { \"name\": \"auth\", \"type\": \"authentication\", \"enabled\": true },\n * { \"name\": \"request_validation\", \"type\": \"validation\", \"enabled\": true }\n * ]\n * },\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"methods\": [\"findData\", \"getData\", \"createData\", \"updateData\", \"deleteData\"]\n * }\n * ]\n * }\n * }\n * ```\n */\n\n// ==========================================\n// REST API Route Categories\n// ==========================================\n\n/**\n * REST API Route Category Enum\n * Categorizes REST API routes by their primary function\n */\nexport const RestApiRouteCategory = z.enum([\n 'discovery', // API discovery and capabilities\n 'metadata', // Metadata operations (objects, fields, views)\n 'data', // Data CRUD operations\n 'batch', // Batch/bulk operations\n 'permission', // Permission/authorization checks\n 'analytics', // Analytics and reporting\n 'automation', // Automation triggers and flows\n 'workflow', // Workflow state management\n 'ui', // UI metadata (views, layouts)\n 'realtime', // Realtime/WebSocket\n 'notification', // Notification management\n 'ai', // AI operations (NLQ, chat)\n 'i18n', // Internationalization\n]);\n\nexport type RestApiRouteCategory = z.infer;\n\n// ==========================================\n// Route Registration Schema\n// ==========================================\n\n/**\n * Handler Implementation Status\n * Shared enum for tracking whether an endpoint has a real handler.\n * Used by both `RestApiEndpointSchema` and `RouteCoverageEntrySchema`.\n *\n * - `implemented` – A real handler is coded and registered.\n * - `stub` – A placeholder handler exists that returns 501 Not Implemented.\n * - `planned` – Declared in the protocol spec but not yet implemented.\n */\nexport const HandlerStatusSchema = z.enum(['implemented', 'stub', 'planned']);\nexport type HandlerStatus = z.infer;\n\n/**\n * REST API Endpoint Schema\n * Defines a single REST API endpoint with its metadata\n * \n * @example Discovery Endpoint\n * {\n * \"method\": \"GET\",\n * \"path\": \"/api/v1/discovery\",\n * \"handler\": \"getDiscovery\",\n * \"category\": \"discovery\",\n * \"public\": true,\n * \"description\": \"Get API discovery information\"\n * }\n */\nexport const RestApiEndpointSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method for this endpoint'),\n \n /**\n * URL path pattern (supports parameters like :id)\n */\n path: z.string().describe('URL path pattern (e.g., /api/v1/data/:object/:id)'),\n \n /**\n * Handler reference (protocol method name)\n */\n handler: z.string().describe('Protocol method name or handler identifier'),\n \n /**\n * Route category\n */\n category: RestApiRouteCategory.describe('Route category'),\n \n /**\n * Whether endpoint is publicly accessible (no auth required)\n */\n public: z.boolean().default(false).describe('Is publicly accessible without authentication'),\n \n /**\n * Required permissions\n */\n permissions: z.array(z.string()).optional().describe('Required permissions (e.g., [\"data.read\", \"object.account.read\"])'),\n \n /**\n * OpenAPI documentation metadata\n */\n summary: z.string().optional().describe('Short description for OpenAPI'),\n description: z.string().optional().describe('Detailed description for OpenAPI'),\n tags: z.array(z.string()).optional().describe('OpenAPI tags for grouping'),\n \n /**\n * Request/Response schema references\n */\n requestSchema: z.string().optional().describe('Request schema name (for validation)'),\n responseSchema: z.string().optional().describe('Response schema name (for documentation)'),\n \n /**\n * Performance and reliability settings\n */\n timeout: z.number().int().optional().describe('Request timeout in milliseconds'),\n rateLimit: z.string().optional().describe('Rate limit policy name'),\n cacheable: z.boolean().default(false).describe('Whether response can be cached'),\n cacheTtl: z.number().int().optional().describe('Cache TTL in seconds'),\n\n /**\n * Handler implementation status.\n * Tracks whether this endpoint has a real handler or is only declared.\n *\n * - `implemented` – A real handler is coded and registered.\n * - `stub` – A placeholder handler exists that returns 501 Not Implemented.\n * - `planned` – Declared in the protocol spec but not yet implemented.\n * @default 'implemented'\n */\n handlerStatus: HandlerStatusSchema.optional()\n .describe('Handler implementation status: implemented (default if omitted), stub, or planned'),\n});\n\nexport type RestApiEndpoint = z.infer;\n\n/**\n * REST API Route Registration Schema\n * Registers a group of related endpoints under a common prefix\n * \n * @example Data CRUD Routes\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"category\": \"data\",\n * \"endpoints\": [\n * { \"method\": \"GET\", \"path\": \"/:object\", \"handler\": \"findData\" },\n * { \"method\": \"GET\", \"path\": \"/:object/:id\", \"handler\": \"getData\" },\n * { \"method\": \"POST\", \"path\": \"/:object\", \"handler\": \"createData\" },\n * { \"method\": \"PATCH\", \"path\": \"/:object/:id\", \"handler\": \"updateData\" },\n * { \"method\": \"DELETE\", \"path\": \"/:object/:id\", \"handler\": \"deleteData\" }\n * ],\n * \"middleware\": [\n * { \"name\": \"auth\", \"type\": \"authentication\", \"enabled\": true },\n * { \"name\": \"validation\", \"type\": \"validation\", \"enabled\": true },\n * { \"name\": \"response_envelope\", \"type\": \"transformation\", \"enabled\": true }\n * ]\n * }\n */\nexport const RestApiRouteRegistrationSchema = z.object({\n /**\n * URL prefix for this route group (e.g., /api/v1/data)\n */\n prefix: z.string().regex(/^\\//).describe('URL path prefix for this route group'),\n \n /**\n * Service name that handles these routes\n */\n service: z.string().describe('Core service name (metadata, data, auth, etc.)'),\n \n /**\n * Route category\n */\n category: RestApiRouteCategory.describe('Primary category for this route group'),\n \n /**\n * Protocol methods implemented\n */\n methods: z.array(z.string()).optional().describe('Protocol method names implemented'),\n \n /**\n * Detailed endpoint definitions\n */\n endpoints: z.array(RestApiEndpointSchema).optional().describe('Endpoint definitions'),\n \n /**\n * Middleware applied to all routes in this group\n */\n middleware: z.array(MiddlewareConfigSchema).optional().describe('Middleware stack for this route group'),\n \n /**\n * Whether authentication is required for all routes\n */\n authRequired: z.boolean().default(true).describe('Whether authentication is required by default'),\n \n /**\n * OpenAPI documentation\n */\n documentation: z.object({\n title: z.string().optional().describe('Route group title'),\n description: z.string().optional().describe('Route group description'),\n tags: z.array(z.string()).optional().describe('OpenAPI tags'),\n }).optional().describe('Documentation metadata for this route group'),\n});\n\nexport type RestApiRouteRegistration = z.infer;\n\n// ==========================================\n// Request Validation Configuration\n// ==========================================\n\n/**\n * Request Validation Mode Enum\n * Defines how validation errors are handled\n */\nexport const ValidationMode = z.enum([\n 'strict', // Reject requests with validation errors (400 Bad Request)\n 'permissive', // Log validation errors but allow request to proceed\n 'strip', // Remove invalid fields and continue with valid data\n]);\n\nexport type ValidationMode = z.infer;\n\n/**\n * Request Validation Configuration Schema\n * Configures Zod-based request validation middleware\n * \n * @example\n * {\n * \"enabled\": true,\n * \"mode\": \"strict\",\n * \"validateBody\": true,\n * \"validateQuery\": true,\n * \"validateParams\": true,\n * \"includeFieldErrors\": true\n * }\n */\nexport const RequestValidationConfigSchema = z.object({\n /**\n * Enable request validation\n */\n enabled: z.boolean().default(true).describe('Enable automatic request validation'),\n \n /**\n * Validation mode\n */\n mode: ValidationMode.default('strict').describe('How to handle validation errors'),\n \n /**\n * Validate request body\n */\n validateBody: z.boolean().default(true).describe('Validate request body against schema'),\n \n /**\n * Validate query parameters\n */\n validateQuery: z.boolean().default(true).describe('Validate query string parameters'),\n \n /**\n * Validate URL parameters\n */\n validateParams: z.boolean().default(true).describe('Validate URL path parameters'),\n \n /**\n * Validate request headers\n */\n validateHeaders: z.boolean().default(false).describe('Validate request headers'),\n \n /**\n * Include detailed field errors in response\n */\n includeFieldErrors: z.boolean().default(true).describe('Include field-level error details in response'),\n \n /**\n * Custom error message prefix\n */\n errorPrefix: z.string().optional().describe('Custom prefix for validation error messages'),\n \n /**\n * Schema registry reference\n */\n schemaRegistry: z.string().optional().describe('Schema registry name to use for validation'),\n});\n\nexport type RequestValidationConfig = z.infer;\nexport type RequestValidationConfigInput = z.input;\n\n// ==========================================\n// Response Envelope Configuration\n// ==========================================\n\n/**\n * Response Envelope Configuration Schema\n * Configures automatic response wrapping with BaseResponseSchema\n * \n * @example\n * {\n * \"enabled\": true,\n * \"includeMetadata\": true,\n * \"includeTimestamp\": true,\n * \"includeRequestId\": true,\n * \"includeDuration\": true\n * }\n */\nexport const ResponseEnvelopeConfigSchema = z.object({\n /**\n * Enable response envelope wrapping\n */\n enabled: z.boolean().default(true).describe('Enable automatic response envelope wrapping'),\n \n /**\n * Include metadata object\n */\n includeMetadata: z.boolean().default(true).describe('Include meta object in responses'),\n \n /**\n * Include timestamp in metadata\n */\n includeTimestamp: z.boolean().default(true).describe('Include timestamp in response metadata'),\n \n /**\n * Include request ID in metadata\n */\n includeRequestId: z.boolean().default(true).describe('Include requestId in response metadata'),\n \n /**\n * Include request duration in metadata\n */\n includeDuration: z.boolean().default(false).describe('Include request duration in ms'),\n \n /**\n * Include trace ID for distributed tracing\n */\n includeTraceId: z.boolean().default(false).describe('Include distributed traceId'),\n \n /**\n * Custom metadata fields\n */\n customMetadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata fields to include'),\n \n /**\n * Whether to wrap already-wrapped responses\n */\n skipIfWrapped: z.boolean().default(true).describe('Skip wrapping if response already has success field'),\n});\n\nexport type ResponseEnvelopeConfig = z.infer;\nexport type ResponseEnvelopeConfigInput = z.input;\n\n// ==========================================\n// Error Handling Configuration\n// ==========================================\n\n/**\n * Error Handling Configuration Schema\n * Configures error handling and ApiErrorSchema formatting\n * \n * @example\n * {\n * \"enabled\": true,\n * \"includeStackTrace\": false,\n * \"logErrors\": true,\n * \"exposeInternalErrors\": false,\n * \"customErrorMessages\": {\n * \"validation_error\": \"The request data is invalid. Please check your input.\"\n * }\n * }\n */\nexport const ErrorHandlingConfigSchema = z.object({\n /**\n * Enable standardized error handling\n */\n enabled: z.boolean().default(true).describe('Enable standardized error handling'),\n \n /**\n * Include stack traces in error responses (dev only)\n */\n includeStackTrace: z.boolean().default(false).describe('Include stack traces in error responses'),\n \n /**\n * Log errors to logger\n */\n logErrors: z.boolean().default(true).describe('Log errors to system logger'),\n \n /**\n * Expose internal error details\n */\n exposeInternalErrors: z.boolean().default(false).describe('Expose internal error details in responses'),\n \n /**\n * Include request ID in errors\n */\n includeRequestId: z.boolean().default(true).describe('Include requestId in error responses'),\n \n /**\n * Include timestamp in errors\n */\n includeTimestamp: z.boolean().default(true).describe('Include timestamp in error responses'),\n \n /**\n * Include error documentation URLs\n */\n includeDocumentation: z.boolean().default(true).describe('Include documentation URLs for errors'),\n \n /**\n * Documentation base URL\n */\n documentationBaseUrl: z.string().url().optional().describe('Base URL for error documentation'),\n \n /**\n * Custom error messages by code\n */\n customErrorMessages: z.record(z.string(), z.string()).optional()\n .describe('Custom error messages by error code'),\n \n /**\n * Sensitive fields to redact from error details\n */\n redactFields: z.array(z.string()).optional().describe('Field names to redact from error details'),\n});\n\nexport type ErrorHandlingConfig = z.infer;\nexport type ErrorHandlingConfigInput = z.input;\n\n// ==========================================\n// OpenAPI Documentation Configuration\n// ==========================================\n\n/**\n * OpenAPI Generation Configuration Schema\n * Configures automatic OpenAPI documentation generation\n * \n * @example\n * {\n * \"enabled\": true,\n * \"version\": \"3.0.0\",\n * \"title\": \"ObjectStack API\",\n * \"description\": \"ObjectStack REST API\",\n * \"outputPath\": \"/api/docs/openapi.json\",\n * \"uiPath\": \"/api/docs\",\n * \"includeInternal\": false,\n * \"generateSchemas\": true\n * }\n */\nexport const OpenApiGenerationConfigSchema = z.object({\n /**\n * Enable OpenAPI generation\n */\n enabled: z.boolean().default(true).describe('Enable automatic OpenAPI documentation generation'),\n \n /**\n * OpenAPI specification version\n */\n version: z.enum(['3.0.0', '3.0.1', '3.0.2', '3.0.3', '3.1.0']).default('3.0.3')\n .describe('OpenAPI specification version'),\n \n /**\n * API title\n */\n title: z.string().default('ObjectStack API').describe('API title'),\n \n /**\n * API description\n */\n description: z.string().optional().describe('API description'),\n \n /**\n * API version\n */\n apiVersion: z.string().default('1.0.0').describe('API version'),\n \n /**\n * Output path for OpenAPI spec\n */\n outputPath: z.string().default('/api/docs/openapi.json').describe('URL path to serve OpenAPI JSON'),\n \n /**\n * UI path for Swagger/Redoc\n */\n uiPath: z.string().default('/api/docs').describe('URL path to serve documentation UI'),\n \n /**\n * UI framework to use\n */\n uiFramework: z.enum(['swagger-ui', 'redoc', 'rapidoc', 'elements']).default('swagger-ui')\n .describe('Documentation UI framework'),\n \n /**\n * Include internal/admin endpoints\n */\n includeInternal: z.boolean().default(false).describe('Include internal endpoints in documentation'),\n \n /**\n * Generate JSON schemas from Zod\n */\n generateSchemas: z.boolean().default(true).describe('Auto-generate schemas from Zod definitions'),\n \n /**\n * Include examples in documentation\n */\n includeExamples: z.boolean().default(true).describe('Include request/response examples'),\n \n /**\n * Server URLs\n */\n servers: z.array(z.object({\n url: z.string().describe('Server URL'),\n description: z.string().optional().describe('Server description'),\n })).optional().describe('Server URLs for API'),\n \n /**\n * Contact information\n */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('API contact information'),\n \n /**\n * License information\n */\n license: z.object({\n name: z.string().describe('License name'),\n url: z.string().url().optional().describe('License URL'),\n }).optional().describe('API license information'),\n \n /**\n * Security schemes\n */\n securitySchemes: z.record(z.string(), z.object({\n type: z.enum(['apiKey', 'http', 'oauth2', 'openIdConnect']),\n scheme: z.string().optional(),\n bearerFormat: z.string().optional(),\n })).optional().describe('Security scheme definitions'),\n});\n\nexport type OpenApiGenerationConfig = z.infer;\nexport type OpenApiGenerationConfigInput = z.input;\n\n// ==========================================\n// REST API Plugin Configuration\n// ==========================================\n\n/**\n * REST API Plugin Configuration Schema\n * Complete configuration for REST API plugin\n * \n * @example\n * {\n * \"enabled\": true,\n * \"basePath\": \"/api\",\n * \"version\": \"v1\",\n * \"routes\": [...],\n * \"validation\": { \"enabled\": true, \"mode\": \"strict\" },\n * \"responseEnvelope\": { \"enabled\": true, \"includeMetadata\": true },\n * \"errorHandling\": { \"enabled\": true, \"includeStackTrace\": false },\n * \"openApi\": { \"enabled\": true, \"title\": \"ObjectStack API\" }\n * }\n */\nexport const RestApiPluginConfigSchema = z.object({\n /**\n * Enable REST API plugin\n */\n enabled: z.boolean().default(true).describe('Enable REST API plugin'),\n \n /**\n * API base path\n */\n basePath: z.string().default('/api').describe('Base path for all API routes'),\n \n /**\n * API version\n */\n version: z.string().default('v1').describe('API version identifier'),\n \n /**\n * Route registrations\n */\n routes: z.array(RestApiRouteRegistrationSchema).describe('Route registrations'),\n \n /**\n * Request validation configuration\n */\n validation: RequestValidationConfigSchema.optional().describe('Request validation configuration'),\n \n /**\n * Response envelope configuration\n */\n responseEnvelope: ResponseEnvelopeConfigSchema.optional().describe('Response envelope configuration'),\n \n /**\n * Error handling configuration\n */\n errorHandling: ErrorHandlingConfigSchema.optional().describe('Error handling configuration'),\n \n /**\n * OpenAPI documentation configuration\n */\n openApi: OpenApiGenerationConfigSchema.optional().describe('OpenAPI documentation configuration'),\n \n /**\n * Global middleware applied to all routes\n */\n globalMiddleware: z.array(MiddlewareConfigSchema).optional().describe('Global middleware stack'),\n \n /**\n * CORS configuration\n */\n cors: z.object({\n enabled: z.boolean().default(true),\n origins: z.array(z.string()).optional(),\n methods: z.array(HttpMethod).optional(),\n credentials: z.boolean().default(true),\n }).optional().describe('CORS configuration'),\n \n /**\n * Performance settings\n */\n performance: z.object({\n enableCompression: z.boolean().default(true).describe('Enable response compression'),\n enableETag: z.boolean().default(true).describe('Enable ETag generation'),\n enableCaching: z.boolean().default(true).describe('Enable HTTP caching'),\n defaultCacheTtl: z.number().int().default(300).describe('Default cache TTL in seconds'),\n }).optional().describe('Performance optimization settings'),\n});\n\nexport type RestApiPluginConfig = z.infer;\nexport type RestApiPluginConfigInput = z.input;\n\n// ==========================================\n// Default Route Registrations\n// ==========================================\n\n/**\n * Default Discovery Routes\n * Standard routes for API discovery endpoint\n */\nexport const DEFAULT_DISCOVERY_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/discovery',\n service: 'metadata',\n category: 'discovery',\n methods: ['getDiscovery'],\n authRequired: false,\n endpoints: [{\n method: 'GET',\n path: '',\n handler: 'getDiscovery',\n category: 'discovery',\n public: true,\n summary: 'Get API discovery information',\n description: 'Returns API version, capabilities, and available routes',\n tags: ['Discovery'],\n responseSchema: 'GetDiscoveryResponseSchema',\n cacheable: true,\n cacheTtl: 3600, // Cache for 1 hour as discovery info rarely changes\n }],\n middleware: [\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n/**\n * Default Metadata Routes\n * Standard routes for metadata operations\n * \n * Note: getMetaItemCached is not a separate endpoint - it's handled by the getMetaItem\n * endpoint with HTTP cache headers (ETag, If-None-Match, etc.) for conditional requests.\n */\nexport const DEFAULT_METADATA_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/meta',\n service: 'metadata',\n category: 'metadata',\n methods: ['getMetaTypes', 'getMetaItems', 'getMetaItem', 'saveMetaItem'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '',\n handler: 'getMetaTypes',\n category: 'metadata',\n public: false,\n summary: 'List all metadata types',\n description: 'Returns available metadata types (object, field, view, etc.)',\n tags: ['Metadata'],\n responseSchema: 'GetMetaTypesResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:type',\n handler: 'getMetaItems',\n category: 'metadata',\n public: false,\n summary: 'List metadata items of a type',\n description: 'Returns all items of the specified metadata type',\n tags: ['Metadata'],\n responseSchema: 'GetMetaItemsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:type/:name',\n handler: 'getMetaItem',\n category: 'metadata',\n public: false,\n summary: 'Get specific metadata item',\n description: 'Returns a specific metadata item by type and name',\n tags: ['Metadata'],\n requestSchema: 'GetMetaItemRequestSchema',\n responseSchema: 'GetMetaItemResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'PUT',\n path: '/:type/:name',\n handler: 'saveMetaItem',\n category: 'metadata',\n public: false,\n summary: 'Create or update metadata item',\n description: 'Creates or updates a metadata item',\n tags: ['Metadata'],\n requestSchema: 'SaveMetaItemRequestSchema',\n responseSchema: 'SaveMetaItemResponseSchema',\n permissions: ['metadata.write'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n/**\n * Default Data CRUD Routes\n * Standard routes for data operations\n */\nexport const DEFAULT_DATA_CRUD_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/data',\n service: 'data',\n category: 'data',\n methods: ['findData', 'getData', 'createData', 'updateData', 'deleteData'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/:object',\n handler: 'findData',\n category: 'data',\n public: false,\n summary: 'Query records',\n description: 'Query records with filtering, sorting, and pagination',\n tags: ['Data'],\n requestSchema: 'FindDataRequestSchema',\n responseSchema: 'ListRecordResponseSchema',\n permissions: ['data.read'],\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/:object/:id',\n handler: 'getData',\n category: 'data',\n public: false,\n summary: 'Get record by ID',\n description: 'Retrieve a single record by its ID',\n tags: ['Data'],\n requestSchema: 'IdRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.read'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object',\n handler: 'createData',\n category: 'data',\n public: false,\n summary: 'Create record',\n description: 'Create a new record',\n tags: ['Data'],\n requestSchema: 'CreateRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.create'],\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/:object/:id',\n handler: 'updateData',\n category: 'data',\n public: false,\n summary: 'Update record',\n description: 'Update an existing record',\n tags: ['Data'],\n requestSchema: 'UpdateRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.update'],\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/:object/:id',\n handler: 'deleteData',\n category: 'data',\n public: false,\n summary: 'Delete record',\n description: 'Delete a record by ID',\n tags: ['Data'],\n requestSchema: 'IdRequestSchema',\n responseSchema: 'DeleteResponseSchema',\n permissions: ['data.delete'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n/**\n * Default Batch Routes\n * Standard routes for batch operations\n */\nexport const DEFAULT_BATCH_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/data/:object',\n service: 'data',\n category: 'batch',\n methods: ['batchData', 'createManyData', 'updateManyData', 'deleteManyData'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/batch',\n handler: 'batchData',\n category: 'batch',\n public: false,\n summary: 'Batch operation',\n description: 'Execute a batch operation (create, update, upsert, delete)',\n tags: ['Batch'],\n requestSchema: 'BatchUpdateRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.batch'],\n timeout: 60000, // 60 seconds for batch operations\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/createMany',\n handler: 'createManyData',\n category: 'batch',\n public: false,\n summary: 'Batch create',\n description: 'Create multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'CreateManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.create', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/updateMany',\n handler: 'updateManyData',\n category: 'batch',\n public: false,\n summary: 'Batch update',\n description: 'Update multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'UpdateManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.update', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/deleteMany',\n handler: 'deleteManyData',\n category: 'batch',\n public: false,\n summary: 'Batch delete',\n description: 'Delete multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'DeleteManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.delete', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n/**\n * Default Permission Routes\n * Standard routes for permission checking\n */\nexport const DEFAULT_PERMISSION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/auth',\n service: 'auth',\n category: 'permission',\n methods: ['checkPermission', 'getObjectPermissions', 'getEffectivePermissions'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/check',\n handler: 'checkPermission',\n category: 'permission',\n public: false,\n summary: 'Check permission',\n description: 'Check if current user has a specific permission',\n tags: ['Permission'],\n requestSchema: 'CheckPermissionRequestSchema',\n responseSchema: 'CheckPermissionResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/permissions/:object',\n handler: 'getObjectPermissions',\n category: 'permission',\n public: false,\n summary: 'Get object permissions',\n description: 'Get all permissions for a specific object',\n tags: ['Permission'],\n responseSchema: 'ObjectPermissionsResponseSchema',\n cacheable: true,\n cacheTtl: 300,\n },\n {\n method: 'GET',\n path: '/permissions/effective',\n handler: 'getEffectivePermissions',\n category: 'permission',\n public: false,\n summary: 'Get effective permissions',\n description: 'Get all effective permissions for current user',\n tags: ['Permission'],\n responseSchema: 'EffectivePermissionsResponseSchema',\n cacheable: true,\n cacheTtl: 300,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// View Management Routes\n// ==========================================\n\n/**\n * Default View Management Routes\n * Standard routes for UI view CRUD operations\n */\nexport const DEFAULT_VIEW_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/ui',\n service: 'ui',\n category: 'ui',\n methods: ['listViews', 'getView', 'createView', 'updateView', 'deleteView'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/views/:object',\n handler: 'listViews',\n category: 'ui',\n public: false,\n summary: 'List views for an object',\n description: 'Returns all views (list, form) for the specified object',\n tags: ['Views', 'UI'],\n responseSchema: 'ListViewsResponseSchema',\n cacheable: true,\n cacheTtl: 1800,\n },\n {\n method: 'GET',\n path: '/views/:object/:viewId',\n handler: 'getView',\n category: 'ui',\n public: false,\n summary: 'Get a specific view',\n description: 'Returns a specific view definition by object and view ID',\n tags: ['Views', 'UI'],\n responseSchema: 'GetViewResponseSchema',\n cacheable: true,\n cacheTtl: 1800,\n },\n {\n method: 'POST',\n path: '/views/:object',\n handler: 'createView',\n category: 'ui',\n public: false,\n summary: 'Create a new view',\n description: 'Creates a new view definition for the specified object',\n tags: ['Views', 'UI'],\n requestSchema: 'CreateViewRequestSchema',\n responseSchema: 'CreateViewResponseSchema',\n permissions: ['ui.view.create'],\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/views/:object/:viewId',\n handler: 'updateView',\n category: 'ui',\n public: false,\n summary: 'Update a view',\n description: 'Updates an existing view definition',\n tags: ['Views', 'UI'],\n requestSchema: 'UpdateViewRequestSchema',\n responseSchema: 'UpdateViewResponseSchema',\n permissions: ['ui.view.update'],\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/views/:object/:viewId',\n handler: 'deleteView',\n category: 'ui',\n public: false,\n summary: 'Delete a view',\n description: 'Deletes a view definition',\n tags: ['Views', 'UI'],\n responseSchema: 'DeleteViewResponseSchema',\n permissions: ['ui.view.delete'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Workflow Routes\n// ==========================================\n\n/**\n * Default Workflow Routes\n * Standard routes for workflow state management and transitions\n */\nexport const DEFAULT_WORKFLOW_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/workflow',\n service: 'workflow',\n category: 'workflow',\n methods: ['getWorkflowConfig', 'getWorkflowState', 'workflowTransition', 'workflowApprove', 'workflowReject'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/:object/config',\n handler: 'getWorkflowConfig',\n category: 'workflow',\n public: false,\n summary: 'Get workflow configuration',\n description: 'Returns workflow rules and state machine configuration for an object',\n tags: ['Workflow'],\n responseSchema: 'GetWorkflowConfigResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:object/:recordId/state',\n handler: 'getWorkflowState',\n category: 'workflow',\n public: false,\n summary: 'Get workflow state',\n description: 'Returns current workflow state and available transitions for a record',\n tags: ['Workflow'],\n responseSchema: 'GetWorkflowStateResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/transition',\n handler: 'workflowTransition',\n category: 'workflow',\n public: false,\n summary: 'Execute workflow transition',\n description: 'Transitions a record to a new workflow state',\n tags: ['Workflow'],\n requestSchema: 'WorkflowTransitionRequestSchema',\n responseSchema: 'WorkflowTransitionResponseSchema',\n permissions: ['workflow.transition'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/approve',\n handler: 'workflowApprove',\n category: 'workflow',\n public: false,\n summary: 'Approve workflow step',\n description: 'Approves a pending workflow approval step',\n tags: ['Workflow'],\n requestSchema: 'WorkflowApproveRequestSchema',\n responseSchema: 'WorkflowApproveResponseSchema',\n permissions: ['workflow.approve'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/reject',\n handler: 'workflowReject',\n category: 'workflow',\n public: false,\n summary: 'Reject workflow step',\n description: 'Rejects a pending workflow approval step',\n tags: ['Workflow'],\n requestSchema: 'WorkflowRejectRequestSchema',\n responseSchema: 'WorkflowRejectResponseSchema',\n permissions: ['workflow.reject'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Realtime Routes\n// ==========================================\n\n/**\n * Default Realtime Routes\n * Standard routes for realtime connection management and subscriptions\n */\nexport const DEFAULT_REALTIME_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/realtime',\n service: 'realtime',\n category: 'realtime',\n methods: ['realtimeConnect', 'realtimeDisconnect', 'realtimeSubscribe', 'realtimeUnsubscribe', 'setPresence', 'getPresence'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/connect',\n handler: 'realtimeConnect',\n category: 'realtime',\n public: false,\n summary: 'Establish realtime connection',\n description: 'Negotiates a realtime connection (WebSocket/SSE) and returns connection details',\n tags: ['Realtime'],\n requestSchema: 'RealtimeConnectRequestSchema',\n responseSchema: 'RealtimeConnectResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/disconnect',\n handler: 'realtimeDisconnect',\n category: 'realtime',\n public: false,\n summary: 'Close realtime connection',\n description: 'Closes an active realtime connection',\n tags: ['Realtime'],\n requestSchema: 'RealtimeDisconnectRequestSchema',\n responseSchema: 'RealtimeDisconnectResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/subscribe',\n handler: 'realtimeSubscribe',\n category: 'realtime',\n public: false,\n summary: 'Subscribe to channel',\n description: 'Subscribes to a realtime channel for receiving events',\n tags: ['Realtime'],\n requestSchema: 'RealtimeSubscribeRequestSchema',\n responseSchema: 'RealtimeSubscribeResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/unsubscribe',\n handler: 'realtimeUnsubscribe',\n category: 'realtime',\n public: false,\n summary: 'Unsubscribe from channel',\n description: 'Unsubscribes from a realtime channel',\n tags: ['Realtime'],\n requestSchema: 'RealtimeUnsubscribeRequestSchema',\n responseSchema: 'RealtimeUnsubscribeResponseSchema',\n cacheable: false,\n },\n {\n method: 'PUT',\n path: '/presence/:channel',\n handler: 'setPresence',\n category: 'realtime',\n public: false,\n summary: 'Set presence state',\n description: 'Sets the current user\\'s presence state in a channel',\n tags: ['Realtime'],\n requestSchema: 'SetPresenceRequestSchema',\n responseSchema: 'SetPresenceResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/presence/:channel',\n handler: 'getPresence',\n category: 'realtime',\n public: false,\n summary: 'Get channel presence',\n description: 'Returns all active members and their presence state in a channel',\n tags: ['Realtime'],\n responseSchema: 'GetPresenceResponseSchema',\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Notification Routes\n// ==========================================\n\n/**\n * Default Notification Routes\n * Standard routes for notification management (device registration, preferences, listing)\n */\nexport const DEFAULT_NOTIFICATION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/notifications',\n service: 'notification',\n category: 'notification',\n methods: [\n 'registerDevice', 'unregisterDevice',\n 'getNotificationPreferences', 'updateNotificationPreferences',\n 'listNotifications', 'markNotificationsRead', 'markAllNotificationsRead',\n ],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/devices',\n handler: 'registerDevice',\n category: 'notification',\n public: false,\n summary: 'Register device for push notifications',\n description: 'Registers a device token for receiving push notifications',\n tags: ['Notifications'],\n requestSchema: 'RegisterDeviceRequestSchema',\n responseSchema: 'RegisterDeviceResponseSchema',\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/devices/:deviceId',\n handler: 'unregisterDevice',\n category: 'notification',\n public: false,\n summary: 'Unregister device',\n description: 'Removes a device from push notification registration',\n tags: ['Notifications'],\n responseSchema: 'UnregisterDeviceResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/preferences',\n handler: 'getNotificationPreferences',\n category: 'notification',\n public: false,\n summary: 'Get notification preferences',\n description: 'Returns current user notification preferences',\n tags: ['Notifications'],\n responseSchema: 'GetNotificationPreferencesResponseSchema',\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/preferences',\n handler: 'updateNotificationPreferences',\n category: 'notification',\n public: false,\n summary: 'Update notification preferences',\n description: 'Updates user notification preferences',\n tags: ['Notifications'],\n requestSchema: 'UpdateNotificationPreferencesRequestSchema',\n responseSchema: 'UpdateNotificationPreferencesResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '',\n handler: 'listNotifications',\n category: 'notification',\n public: false,\n summary: 'List notifications',\n description: 'Returns paginated list of notifications for the current user',\n tags: ['Notifications'],\n responseSchema: 'ListNotificationsResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/read',\n handler: 'markNotificationsRead',\n category: 'notification',\n public: false,\n summary: 'Mark notifications as read',\n description: 'Marks specific notifications as read by their IDs',\n tags: ['Notifications'],\n requestSchema: 'MarkNotificationsReadRequestSchema',\n responseSchema: 'MarkNotificationsReadResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/read/all',\n handler: 'markAllNotificationsRead',\n category: 'notification',\n public: false,\n summary: 'Mark all notifications as read',\n description: 'Marks all notifications as read for the current user',\n tags: ['Notifications'],\n responseSchema: 'MarkAllNotificationsReadResponseSchema',\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// AI Routes\n// ==========================================\n\n/**\n * Default AI Routes\n * Standard routes for AI operations (NLQ, Chat, Suggest, Insights)\n */\nexport const DEFAULT_AI_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/ai',\n service: 'ai',\n category: 'ai',\n methods: ['aiNlq', 'aiSuggest', 'aiInsights'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/nlq',\n handler: 'aiNlq',\n category: 'ai',\n public: false,\n summary: 'Natural language query',\n description: 'Converts a natural language query to a structured query AST',\n tags: ['AI'],\n requestSchema: 'AiNlqRequestSchema',\n responseSchema: 'AiNlqResponseSchema',\n timeout: 30000,\n cacheable: false,\n },\n // AI chat route removed — wire protocol aligned with Vercel AI SDK.\n // The chat endpoint should use Vercel's `toDataStreamResponse()` directly.\n {\n method: 'POST',\n path: '/suggest',\n handler: 'aiSuggest',\n category: 'ai',\n public: false,\n summary: 'Get AI-powered suggestions',\n description: 'Returns AI-generated field value suggestions based on context',\n tags: ['AI'],\n requestSchema: 'AiSuggestRequestSchema',\n responseSchema: 'AiSuggestResponseSchema',\n timeout: 15000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/insights',\n handler: 'aiInsights',\n category: 'ai',\n public: false,\n summary: 'Get AI-generated insights',\n description: 'Returns AI-generated insights (summaries, trends, anomalies, recommendations)',\n tags: ['AI'],\n requestSchema: 'AiInsightsRequestSchema',\n responseSchema: 'AiInsightsResponseSchema',\n timeout: 60000,\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// i18n Routes\n// ==========================================\n\n/**\n * Default i18n Routes\n * Standard routes for internationalization operations\n */\nexport const DEFAULT_I18N_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/i18n',\n service: 'i18n',\n category: 'i18n',\n methods: ['getLocales', 'getTranslations', 'getFieldLabels'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/locales',\n handler: 'getLocales',\n category: 'i18n',\n public: false,\n summary: 'Get available locales',\n description: 'Returns all available locales with their metadata',\n tags: ['i18n'],\n responseSchema: 'GetLocalesResponseSchema',\n cacheable: true,\n cacheTtl: 86400, // 24 hours — locales change very rarely\n },\n {\n method: 'GET',\n path: '/translations/:locale',\n handler: 'getTranslations',\n category: 'i18n',\n public: false,\n summary: 'Get translations for a locale',\n description: 'Returns translation strings for the specified locale and optional namespace',\n tags: ['i18n'],\n responseSchema: 'GetTranslationsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/labels/:object/:locale',\n handler: 'getFieldLabels',\n category: 'i18n',\n public: false,\n summary: 'Get translated field labels',\n description: 'Returns translated field labels, help text, and option labels for an object',\n tags: ['i18n'],\n responseSchema: 'GetFieldLabelsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Analytics Routes\n// ==========================================\n\n/**\n * Default Analytics Routes\n * Standard routes for analytics and BI operations\n */\nexport const DEFAULT_ANALYTICS_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/analytics',\n service: 'analytics',\n category: 'analytics',\n methods: ['analyticsQuery', 'getAnalyticsMeta'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/query',\n handler: 'analyticsQuery',\n category: 'analytics',\n public: false,\n summary: 'Execute analytics query',\n description: 'Executes a structured analytics query against the semantic layer',\n tags: ['Analytics'],\n requestSchema: 'AnalyticsQueryRequestSchema',\n responseSchema: 'AnalyticsResultResponseSchema',\n permissions: ['analytics.query'],\n timeout: 120000, // 2 minutes for analytics queries\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/meta',\n handler: 'getAnalyticsMeta',\n category: 'analytics',\n public: false,\n summary: 'Get analytics metadata',\n description: 'Returns available cubes, dimensions, measures, and segments',\n tags: ['Analytics'],\n responseSchema: 'AnalyticsMetadataResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Automation Routes\n// ==========================================\n\n/**\n * Default Automation Routes\n * Standard routes for automation triggers\n */\nexport const DEFAULT_AUTOMATION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/automation',\n service: 'automation',\n category: 'automation',\n methods: ['triggerAutomation'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/trigger',\n handler: 'triggerAutomation',\n category: 'automation',\n public: false,\n summary: 'Trigger automation',\n description: 'Triggers an automation flow or script by name',\n tags: ['Automation'],\n requestSchema: 'AutomationTriggerRequestSchema',\n responseSchema: 'AutomationTriggerResponseSchema',\n permissions: ['automation.trigger'],\n timeout: 120000, // 2 minutes for long-running automations\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create REST API plugin configuration\n */\nexport const RestApiPluginConfig = Object.assign(RestApiPluginConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create route registration\n */\nexport const RestApiRouteRegistration = Object.assign(RestApiRouteRegistrationSchema, {\n create: >(registration: T) => registration,\n});\n\n/**\n * Get all default route registrations.\n * Returns the complete set of standard REST API routes covering all protocol namespaces.\n * \n * Route groups (13 total):\n * 1. Discovery - API capabilities and routing info\n * 2. Metadata - Object/field schema CRUD\n * 3. Data CRUD - Record operations\n * 4. Batch - Bulk operations\n * 5. Permission - Authorization checks\n * 6. Views - UI view CRUD\n * 7. Workflow - State machine transitions\n * 8. Realtime - WebSocket/SSE connections\n * 9. Notification - Push notifications and preferences\n * 10. AI - NLQ, chat, suggestions, insights\n * 11. i18n - Locales and translations\n * 12. Analytics - BI queries and metadata\n * 13. Automation - Trigger flows and scripts\n */\nexport function getDefaultRouteRegistrations(): RestApiRouteRegistration[] {\n return [\n DEFAULT_DISCOVERY_ROUTES,\n DEFAULT_METADATA_ROUTES,\n DEFAULT_DATA_CRUD_ROUTES,\n DEFAULT_BATCH_ROUTES,\n DEFAULT_PERMISSION_ROUTES,\n DEFAULT_VIEW_ROUTES,\n DEFAULT_WORKFLOW_ROUTES,\n DEFAULT_REALTIME_ROUTES,\n DEFAULT_NOTIFICATION_ROUTES,\n DEFAULT_AI_ROUTES,\n DEFAULT_I18N_ROUTES,\n DEFAULT_ANALYTICS_ROUTES,\n DEFAULT_AUTOMATION_ROUTES,\n ];\n}\n\n// ==========================================\n// Route Coverage Report\n// ==========================================\n\n/**\n * Route Coverage Entry Schema\n * Reports the coverage status of a single declared endpoint.\n */\nexport const RouteCoverageEntrySchema = z.object({\n /** Full URL path of the endpoint */\n path: z.string().describe('Full URL path (e.g. /api/v1/analytics/query)'),\n /** HTTP method */\n method: HttpMethod.describe('HTTP method (GET, POST, etc.)'),\n /** Route category */\n category: RestApiRouteCategory.describe('Route category'),\n /** Handler implementation status */\n handlerStatus: HandlerStatusSchema.describe('Handler status'),\n /** Target service */\n service: z.string().describe('Target service name'),\n /** Whether the handler was successfully called during health check */\n healthCheckPassed: z.boolean().optional().describe('Whether the health check probe succeeded'),\n});\n\nexport type RouteCoverageEntry = z.infer;\n\n/**\n * Route Coverage Report Schema\n *\n * Aggregated report generated by the adapter/dispatcher at startup.\n * Lists every declared endpoint and whether a handler is confirmed.\n *\n * Adapters SHOULD log a warning for every endpoint where\n * `handlerStatus !== 'implemented'` and emit this report as part\n * of the startup health diagnostics.\n */\nexport const RouteCoverageReportSchema = z.object({\n /** ISO 8601 timestamp of report generation */\n timestamp: z.string().describe('ISO 8601 timestamp'),\n /** Adapter that generated the report */\n adapter: z.string().describe('Adapter name (e.g. \"hono\", \"express\", \"nextjs\")'),\n /** Summary counters */\n summary: z.object({\n total: z.number().int().describe('Total declared endpoints'),\n implemented: z.number().int().describe('Endpoints with real handlers'),\n stub: z.number().int().describe('Endpoints with stub handlers (501)'),\n planned: z.number().int().describe('Endpoints not yet implemented'),\n }),\n /** Per-endpoint entries */\n entries: z.array(RouteCoverageEntrySchema).describe('Per-endpoint coverage entries'),\n});\n\nexport type RouteCoverageReport = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * API Query DSL Adapter Protocol\n * \n * Defines mapping rules between the internal unified query DSL\n * (defined in `data/query.zod.ts`) and external API protocol formats:\n * REST, GraphQL, and OData.\n * \n * This enables ObjectStack to expose a single internal query representation\n * while supporting multiple API standards for external consumers.\n * \n * @see data/query.zod.ts - Unified internal query DSL\n * @see api/rest-server.zod.ts - REST API configuration\n * @see api/graphql.zod.ts - GraphQL API configuration\n * @see api/odata.zod.ts - OData API configuration\n */\n\n// ==========================================\n// 1. Shared Adapter Types\n// ==========================================\n\n/**\n * Query Adapter Target Protocol\n */\nexport const QueryAdapterTargetSchema = z.enum([\n 'rest', // REST API (?filter[field][op]=value)\n 'graphql', // GraphQL (where: \\{ field: \\{ op: value \\}\\})\n 'odata', // OData ($filter=field op value)\n]);\n\nexport type QueryAdapterTarget = z.infer;\n\n/**\n * Operator Mapping Entry\n * \n * Maps a unified DSL operator to its protocol-specific syntax.\n */\nexport const OperatorMappingSchema = z.object({\n /** Unified DSL operator (e.g., 'eq', 'gt', 'contains') */\n operator: z.string().describe('Unified DSL operator'),\n\n /** REST query parameter format (e.g., 'filter[{field}][{op}]') */\n rest: z.string().optional().describe('REST query parameter template'),\n\n /** GraphQL where clause format (e.g., '{field}: { {op}: $value }') */\n graphql: z.string().optional().describe('GraphQL where clause template'),\n\n /** OData $filter expression format (e.g., '{field} {op} {value}') */\n odata: z.string().optional().describe('OData $filter expression template'),\n});\n\nexport type OperatorMapping = z.infer;\n\n// ==========================================\n// 2. REST Adapter Configuration\n// ==========================================\n\n/**\n * REST Query Adapter Configuration\n * \n * Defines how unified query DSL maps to REST query parameters.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10 }\n * REST: ?filter[status][eq]=active&limit=10\n */\nexport const RestQueryAdapterSchema = z.object({\n /** Filter parameter style */\n filterStyle: z.enum([\n 'bracket', // ?filter[field][op]=value (JSON API style)\n 'dot', // ?filter.field.op=value\n 'flat', // ?field=value (simple equality)\n 'rsql', // ?filter=field==value;field=gt=10 (RSQL / FIQL)\n ]).default('bracket').describe('REST filter parameter encoding style'),\n\n /** Pagination parameter names */\n pagination: z.object({\n /** Page size parameter name */\n limitParam: z.string().default('limit').describe('Page size parameter name'),\n\n /** Offset parameter name */\n offsetParam: z.string().default('offset').describe('Offset parameter name'),\n\n /** Cursor parameter name (for cursor-based pagination) */\n cursorParam: z.string().default('cursor').describe('Cursor parameter name'),\n\n /** Page number parameter name (for page-based pagination) */\n pageParam: z.string().default('page').describe('Page number parameter name'),\n }).optional().describe('Pagination parameter name mappings'),\n\n /** Sort parameter name and format */\n sorting: z.object({\n /** Sort parameter name */\n param: z.string().default('sort').describe('Sort parameter name'),\n\n /** Sort format */\n format: z.enum([\n 'comma', // ?sort=field1,-field2\n 'array', // ?sort[]=field1&sort[]=-field2\n 'pipe', // ?sort=field1|asc,field2|desc\n ]).default('comma').describe('Sort parameter encoding format'),\n }).optional().describe('Sort parameter mapping'),\n\n /** Field selection parameter name */\n fieldsParam: z.string().default('fields').describe('Field selection parameter name'),\n});\n\nexport type RestQueryAdapter = z.infer;\nexport type RestQueryAdapterInput = z.input;\n\n// ==========================================\n// 3. GraphQL Adapter Configuration\n// ==========================================\n\n/**\n * GraphQL Query Adapter Configuration\n * \n * Defines how unified query DSL maps to GraphQL arguments.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10, sort: [{ field: 'name', order: 'asc' }] }\n * GraphQL: query { items(where: { status: { eq: \"active\" } }, limit: 10, orderBy: { name: ASC }) { ... } }\n */\nexport const GraphQLQueryAdapterSchema = z.object({\n /** Filter argument name in GraphQL queries */\n filterArgName: z.string().default('where').describe('GraphQL filter argument name'),\n\n /** Filter nesting style */\n filterStyle: z.enum([\n 'nested', // where: { field: { op: value } } (Prisma style)\n 'flat', // where: { field_op: value } (Hasura style)\n 'array', // where: [{ field, op, value }] (Array of conditions)\n ]).default('nested').describe('GraphQL filter nesting style'),\n\n /** Pagination argument names */\n pagination: z.object({\n limitArg: z.string().default('limit').describe('Page size argument name'),\n offsetArg: z.string().default('offset').describe('Offset argument name'),\n firstArg: z.string().default('first').describe('Relay \"first\" argument name'),\n afterArg: z.string().default('after').describe('Relay \"after\" cursor argument name'),\n }).optional().describe('Pagination argument name mappings'),\n\n /** Sort argument configuration */\n sorting: z.object({\n argName: z.string().default('orderBy').describe('Sort argument name'),\n format: z.enum([\n 'enum', // orderBy: { field: ASC }\n 'array', // orderBy: [{ field: \"name\", direction: \"ASC\" }]\n ]).default('enum').describe('Sort argument format'),\n }).optional().describe('Sort argument mapping'),\n});\n\nexport type GraphQLQueryAdapter = z.infer;\nexport type GraphQLQueryAdapterInput = z.input;\n\n// ==========================================\n// 4. OData Adapter Configuration\n// ==========================================\n\n/**\n * OData Query Adapter Configuration\n * \n * Defines how unified query DSL maps to OData system query options.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10, sort: [{ field: 'name', order: 'asc' }] }\n * OData: ?$filter=status eq 'active'&$top=10&$orderby=name asc\n */\nexport const ODataQueryAdapterSchema = z.object({\n /** OData version */\n version: z.enum(['v2', 'v4']).default('v4').describe('OData version'),\n\n /** System query option prefixes */\n usePrefix: z.boolean().default(true).describe('Use $ prefix for system query options ($filter vs filter)'),\n\n /** String function support */\n stringFunctions: z.array(z.enum([\n 'contains',\n 'startswith',\n 'endswith',\n 'tolower',\n 'toupper',\n 'trim',\n 'concat',\n 'substring',\n 'length',\n ])).optional().describe('Supported OData string functions'),\n\n /** Expand (nested resource) configuration */\n expand: z.object({\n enabled: z.boolean().default(true).describe('Enable $expand support'),\n maxDepth: z.number().int().min(1).default(3).describe('Maximum expand depth'),\n }).optional().describe('$expand configuration'),\n});\n\nexport type ODataQueryAdapter = z.infer;\nexport type ODataQueryAdapterInput = z.input;\n\n// ==========================================\n// 5. Complete Query Adapter Configuration\n// ==========================================\n\n/**\n * Query Adapter Configuration\n * \n * Root configuration for query DSL adapters across all supported protocols.\n * Controls how the internal unified DSL is translated to external API formats.\n */\nexport const QueryAdapterConfigSchema = z.object({\n /** Default operator mappings */\n operatorMappings: z.array(OperatorMappingSchema).optional().describe('Custom operator mappings'),\n\n /** REST adapter configuration */\n rest: RestQueryAdapterSchema.optional().describe('REST query adapter configuration'),\n\n /** GraphQL adapter configuration */\n graphql: GraphQLQueryAdapterSchema.optional().describe('GraphQL query adapter configuration'),\n\n /** OData adapter configuration */\n odata: ODataQueryAdapterSchema.optional().describe('OData query adapter configuration'),\n});\n\nexport type QueryAdapterConfig = z.infer;\nexport type QueryAdapterConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Feed Item Type\n * Unified activity types for the record timeline.\n * Covers comments, field changes, tasks, events, and system activities.\n */\nexport const FeedItemType = z.enum([\n 'comment',\n 'field_change',\n 'task',\n 'event',\n 'email',\n 'call',\n 'note',\n 'file',\n 'record_create',\n 'record_delete',\n 'approval',\n 'sharing',\n 'system',\n]);\nexport type FeedItemType = z.infer;\n\n/**\n * Mention Schema\n * Represents an @mention within comment body text.\n */\nexport const MentionSchema = z.object({\n type: z.enum(['user', 'team', 'record']).describe('Mention target type'),\n id: z.string().describe('Target ID'),\n name: z.string().describe('Display name for rendering'),\n offset: z.number().int().min(0).describe('Character offset in body text'),\n length: z.number().int().min(1).describe('Length of mention token in body text'),\n});\nexport type Mention = z.infer;\n\n/**\n * Field Change Entry Schema\n * Represents a single field-level change within a field_change feed item.\n */\nexport const FieldChangeEntrySchema = z.object({\n field: z.string().describe('Field machine name'),\n fieldLabel: z.string().optional().describe('Field display label'),\n oldValue: z.unknown().optional().describe('Previous value'),\n newValue: z.unknown().optional().describe('New value'),\n oldDisplayValue: z.string().optional().describe('Human-readable old value'),\n newDisplayValue: z.string().optional().describe('Human-readable new value'),\n});\nexport type FieldChangeEntry = z.infer;\n\n/**\n * Reaction Schema\n * Represents an emoji reaction on a feed item.\n */\nexport const ReactionSchema = z.object({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n userIds: z.array(z.string()).describe('Users who reacted'),\n count: z.number().int().min(1).describe('Total reaction count'),\n});\nexport type Reaction = z.infer;\n\n/**\n * Feed Actor Schema\n * Represents the actor who performed the action.\n */\nexport const FeedActorSchema = z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n avatarUrl: z.string().url().optional().describe('Actor avatar URL'),\n source: z.string().optional().describe('Source application (e.g., \"Omni\", \"API\", \"Studio\")'),\n});\nexport type FeedActor = z.infer;\n\n/**\n * Feed Item Visibility\n */\nexport const FeedVisibility = z.enum(['public', 'internal', 'private']);\nexport type FeedVisibility = z.infer;\n\n/**\n * Feed Item Schema\n * A single entry in the unified activity timeline.\n *\n * @example Comment\n * {\n * id: 'feed_001',\n * type: 'comment',\n * object: 'account',\n * recordId: 'rec_123',\n * body: 'Great progress! @jane.doe can you follow up?',\n * mentions: [{ type: 'user', id: 'user_123', name: 'Jane Doe', offset: 17, length: 9 }],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:30:00Z',\n * }\n *\n * @example Field Change\n * {\n * id: 'feed_002',\n * type: 'field_change',\n * object: 'account',\n * recordId: 'rec_123',\n * changes: [\n * { field: 'status', oldDisplayValue: 'New', newDisplayValue: 'Active' },\n * { field: 'region', oldDisplayValue: '', newDisplayValue: 'Asia-Pacific' },\n * ],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:25:00Z',\n * }\n */\nexport const FeedItemSchema = z.object({\n /** Unique identifier */\n id: z.string().describe('Feed item ID'),\n\n /** Feed item type */\n type: FeedItemType.describe('Activity type'),\n\n /** Target record reference */\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID this feed item belongs to'),\n\n /** Actor (who performed the action) */\n actor: FeedActorSchema.describe('Who performed this action'),\n\n /** Content (for comments/notes) */\n body: z.string().optional().describe('Rich text body (Markdown supported)'),\n\n /** @Mentions */\n mentions: z.array(MentionSchema).optional().describe('Mentioned users/teams/records'),\n\n /** Field changes (for field_change type) */\n changes: z.array(FieldChangeEntrySchema).optional().describe('Field-level changes'),\n\n /** Reactions */\n reactions: z.array(ReactionSchema).optional().describe('Emoji reactions on this item'),\n\n /** Reply threading */\n parentId: z.string().optional().describe('Parent feed item ID for threaded replies'),\n replyCount: z.number().int().min(0).default(0).describe('Number of replies'),\n\n /** Pin / Star */\n pinned: z.boolean().default(false).describe('Whether the feed item is pinned to the top of the timeline'),\n pinnedAt: z.string().datetime().optional().describe('Timestamp when the item was pinned'),\n pinnedBy: z.string().optional().describe('User ID who pinned the item'),\n starred: z.boolean().default(false).describe('Whether the feed item is starred/bookmarked by the current user'),\n starredAt: z.string().datetime().optional().describe('Timestamp when the item was starred'),\n\n /** Visibility */\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public (all users), internal (team only), private (author + mentioned)'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n editedAt: z.string().datetime().optional().describe('When comment was last edited'),\n isEdited: z.boolean().default(false).describe('Whether comment has been edited'),\n});\nexport type FeedItem = z.infer;\n\n/**\n * Feed Filter Mode\n * Controls which feed item types to display in the timeline.\n */\nexport const FeedFilterMode = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\nexport type FeedFilterMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Subscription Event Type\n * Event types that can be subscribed to for record-level notifications.\n */\nexport const SubscriptionEventType = z.enum([\n 'comment',\n 'mention',\n 'field_change',\n 'task',\n 'approval',\n 'all',\n]);\nexport type SubscriptionEventType = z.infer;\n\n/**\n * Notification Channel\n * Delivery channels for record subscription notifications.\n */\nexport const NotificationChannel = z.enum([\n 'in_app',\n 'email',\n 'push',\n 'slack',\n]);\nexport type NotificationChannel = z.infer;\n\n/**\n * Record Subscription Schema\n * Defines a user's subscription to record-level notifications.\n * Enables Airtable-style bell icon for record change notifications.\n */\nexport const RecordSubscriptionSchema = z.object({\n /** Target */\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n\n /** Subscriber */\n userId: z.string().describe('Subscribing user ID'),\n\n /** Events to subscribe to */\n events: z.array(SubscriptionEventType)\n .default(['all'])\n .describe('Event types to receive notifications for'),\n\n /** Notification channels */\n channels: z.array(NotificationChannel)\n .default(['in_app'])\n .describe('Notification delivery channels'),\n\n /** Active */\n active: z.boolean().default(true).describe('Whether the subscription is active'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Subscription creation timestamp'),\n});\nexport type RecordSubscription = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport {\n FeedItemType,\n FeedItemSchema,\n FeedVisibility,\n MentionSchema,\n ReactionSchema,\n FieldChangeEntrySchema,\n} from '../data/feed.zod';\nimport {\n SubscriptionEventType,\n NotificationChannel,\n RecordSubscriptionSchema,\n} from '../data/subscription.zod';\n\n/**\n * Feed / Chatter API Protocol\n *\n * Defines the HTTP interface for the unified activity timeline (Feed).\n * Covers Feed CRUD, Emoji Reactions, Pin/Star, Search, Changelog,\n * and Record Subscription endpoints.\n *\n * Base path: /api/data/{object}/{recordId}/feed\n *\n * @example Endpoints\n * GET /api/data/{object}/{recordId}/feed — List feed items\n * POST /api/data/{object}/{recordId}/feed — Create feed item\n * PUT /api/data/{object}/{recordId}/feed/{feedId} — Update feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId} — Delete feed item\n * POST /api/data/{object}/{recordId}/feed/{feedId}/reactions — Add reaction\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/reactions/{emoji} — Remove reaction\n * POST /api/data/{object}/{recordId}/feed/{feedId}/pin — Pin feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/pin — Unpin feed item\n * POST /api/data/{object}/{recordId}/feed/{feedId}/star — Star feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/star — Unstar feed item\n * GET /api/data/{object}/{recordId}/feed/search — Search feed items\n * GET /api/data/{object}/{recordId}/changelog — Get field-level changelog\n * POST /api/data/{object}/{recordId}/subscribe — Subscribe\n * DELETE /api/data/{object}/{recordId}/subscribe — Unsubscribe\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Common path parameters shared across all feed endpoints.\n */\nexport const FeedPathParamsSchema = z.object({\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID'),\n});\nexport type FeedPathParams = z.infer;\n\n/**\n * Path parameters for single-feed-item operations (update, delete).\n */\nexport const FeedItemPathParamsSchema = FeedPathParamsSchema.extend({\n feedId: z.string().describe('Feed item ID'),\n});\nexport type FeedItemPathParams = z.infer;\n\n// ==========================================\n// 2. Feed List (GET)\n// ==========================================\n\n/**\n * Feed filter type for the list query.\n * Maps to FeedFilterMode: all | comments_only | changes_only | tasks_only\n */\nexport const FeedListFilterType = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\n\n/**\n * Query parameters for listing feed items.\n *\n * @example GET /api/data/account/rec_123/feed?type=all&limit=20&cursor=xxx\n */\nexport const GetFeedRequestSchema = FeedPathParamsSchema.extend({\n type: FeedListFilterType.default('all')\n .describe('Filter by feed item category'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of items to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination (opaque string from previous response)'),\n});\nexport type GetFeedRequest = z.infer;\n\n/**\n * Response for the feed list endpoint.\n */\nexport const GetFeedResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n items: z.array(FeedItemSchema).describe('Feed items in reverse chronological order'),\n total: z.number().int().optional().describe('Total feed items matching filter'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more items are available'),\n }),\n});\nexport type GetFeedResponse = z.infer;\n\n// ==========================================\n// 3. Feed Create (POST)\n// ==========================================\n\n/**\n * Request body for creating a new feed item (comment, note, task, etc.).\n *\n * @example POST /api/data/account/rec_123/feed\n * { type: 'comment', body: 'Great progress! @jane can you follow up?', mentions: [...] }\n */\nexport const CreateFeedItemRequestSchema = FeedPathParamsSchema.extend({\n type: FeedItemType.describe('Type of feed item to create'),\n body: z.string().optional()\n .describe('Rich text body (Markdown supported)'),\n mentions: z.array(MentionSchema).optional()\n .describe('Mentioned users, teams, or records'),\n parentId: z.string().optional()\n .describe('Parent feed item ID for threaded replies'),\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public, internal, or private'),\n});\nexport type CreateFeedItemRequest = z.infer;\n\n/**\n * Response after creating a feed item.\n */\nexport const CreateFeedItemResponseSchema = BaseResponseSchema.extend({\n data: FeedItemSchema.describe('The created feed item'),\n});\nexport type CreateFeedItemResponse = z.infer;\n\n// ==========================================\n// 4. Feed Update (PUT)\n// ==========================================\n\n/**\n * Request body for updating an existing feed item (e.g., editing a comment).\n *\n * @example PUT /api/data/account/rec_123/feed/feed_001\n * { body: 'Updated comment text', mentions: [...] }\n */\nexport const UpdateFeedItemRequestSchema = FeedItemPathParamsSchema.extend({\n body: z.string().optional()\n .describe('Updated rich text body'),\n mentions: z.array(MentionSchema).optional()\n .describe('Updated mentions'),\n visibility: FeedVisibility.optional()\n .describe('Updated visibility'),\n});\nexport type UpdateFeedItemRequest = z.infer;\n\n/**\n * Response after updating a feed item.\n */\nexport const UpdateFeedItemResponseSchema = BaseResponseSchema.extend({\n data: FeedItemSchema.describe('The updated feed item'),\n});\nexport type UpdateFeedItemResponse = z.infer;\n\n// ==========================================\n// 5. Feed Delete (DELETE)\n// ==========================================\n\n/**\n * Request parameters for deleting a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001\n */\nexport const DeleteFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type DeleteFeedItemRequest = z.infer;\n\n/**\n * Response after deleting a feed item.\n */\nexport const DeleteFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the deleted feed item'),\n }),\n});\nexport type DeleteFeedItemResponse = z.infer;\n\n// ==========================================\n// 6. Reactions (POST / DELETE)\n// ==========================================\n\n/**\n * Request for adding an emoji reaction to a feed item.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/reactions\n * { emoji: '👍' }\n */\nexport const AddReactionRequestSchema = FeedItemPathParamsSchema.extend({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n});\nexport type AddReactionRequest = z.infer;\n\n/**\n * Response after adding a reaction.\n */\nexport const AddReactionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n reactions: z.array(ReactionSchema).describe('Updated reaction list for the feed item'),\n }),\n});\nexport type AddReactionResponse = z.infer;\n\n/**\n * Request for removing an emoji reaction from a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/reactions/👍\n */\nexport const RemoveReactionRequestSchema = FeedItemPathParamsSchema.extend({\n emoji: z.string().describe('Emoji character or shortcode to remove'),\n});\nexport type RemoveReactionRequest = z.infer;\n\n/**\n * Response after removing a reaction.\n */\nexport const RemoveReactionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n reactions: z.array(ReactionSchema).describe('Updated reaction list for the feed item'),\n }),\n});\nexport type RemoveReactionResponse = z.infer;\n\n// ==========================================\n// 7. Pin / Star\n// ==========================================\n\n/**\n * Request for pinning a feed item to the top of the timeline.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/pin\n */\nexport const PinFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type PinFeedItemRequest = z.infer;\n\n/**\n * Response after pinning a feed item.\n */\nexport const PinFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the pinned feed item'),\n pinned: z.boolean().describe('Whether the item is now pinned'),\n pinnedAt: z.string().datetime().describe('Timestamp when pinned'),\n }),\n});\nexport type PinFeedItemResponse = z.infer;\n\n/**\n * Request for unpinning a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/pin\n */\nexport const UnpinFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type UnpinFeedItemRequest = z.infer;\n\n/**\n * Response after unpinning a feed item.\n */\nexport const UnpinFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the unpinned feed item'),\n pinned: z.boolean().describe('Whether the item is now pinned (should be false)'),\n }),\n});\nexport type UnpinFeedItemResponse = z.infer;\n\n/**\n * Request for starring (bookmarking) a feed item.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/star\n */\nexport const StarFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type StarFeedItemRequest = z.infer;\n\n/**\n * Response after starring a feed item.\n */\nexport const StarFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the starred feed item'),\n starred: z.boolean().describe('Whether the item is now starred'),\n starredAt: z.string().datetime().describe('Timestamp when starred'),\n }),\n});\nexport type StarFeedItemResponse = z.infer;\n\n/**\n * Request for unstarring a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/star\n */\nexport const UnstarFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type UnstarFeedItemRequest = z.infer;\n\n/**\n * Response after unstarring a feed item.\n */\nexport const UnstarFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the unstarred feed item'),\n starred: z.boolean().describe('Whether the item is now starred (should be false)'),\n }),\n});\nexport type UnstarFeedItemResponse = z.infer;\n\n// ==========================================\n// 8. Activity Feed Search & Filter\n// ==========================================\n\n/**\n * Request for searching feed items with full-text query and advanced filters.\n *\n * @example GET /api/data/account/rec_123/feed/search?query=follow+up&actorId=user_456&dateFrom=2026-01-01T00:00:00Z\n */\nexport const SearchFeedRequestSchema = FeedPathParamsSchema.extend({\n query: z.string().min(1).describe('Full-text search query against feed body content'),\n type: FeedListFilterType.optional()\n .describe('Filter by feed item category'),\n actorId: z.string().optional()\n .describe('Filter by actor user ID'),\n dateFrom: z.string().datetime().optional()\n .describe('Filter feed items created after this timestamp'),\n dateTo: z.string().datetime().optional()\n .describe('Filter feed items created before this timestamp'),\n hasAttachments: z.boolean().optional()\n .describe('Filter for items with file attachments'),\n pinnedOnly: z.boolean().optional()\n .describe('Return only pinned items'),\n starredOnly: z.boolean().optional()\n .describe('Return only starred items'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of items to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type SearchFeedRequest = z.infer;\n\n/**\n * Response for the feed search endpoint.\n */\nexport const SearchFeedResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n items: z.array(FeedItemSchema).describe('Matching feed items sorted by relevance'),\n total: z.number().int().optional().describe('Total matching items'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more items are available'),\n }),\n});\nexport type SearchFeedResponse = z.infer;\n\n// ==========================================\n// 9. Changelog (Field-Level Audit Trail)\n// ==========================================\n\n/**\n * Request for retrieving the field-level changelog of a record.\n *\n * @example GET /api/data/account/rec_123/changelog?field=status&limit=50\n */\nexport const GetChangelogRequestSchema = FeedPathParamsSchema.extend({\n field: z.string().optional()\n .describe('Filter changelog to a specific field name'),\n actorId: z.string().optional()\n .describe('Filter changelog by actor user ID'),\n dateFrom: z.string().datetime().optional()\n .describe('Filter changes after this timestamp'),\n dateTo: z.string().datetime().optional()\n .describe('Filter changes before this timestamp'),\n limit: z.number().int().min(1).max(200).default(50)\n .describe('Maximum number of changelog entries to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type GetChangelogRequest = z.infer;\n\n/**\n * A single changelog entry representing one or more field changes at a point in time.\n */\nexport const ChangelogEntrySchema = z.object({\n id: z.string().describe('Changelog entry ID'),\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n actor: z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n }).describe('Who made the change'),\n changes: z.array(FieldChangeEntrySchema).min(1).describe('Field-level changes'),\n timestamp: z.string().datetime().describe('When the change occurred'),\n source: z.string().optional().describe('Change source (e.g., \"API\", \"UI\", \"automation\")'),\n});\nexport type ChangelogEntry = z.infer;\n\n/**\n * Response for the changelog endpoint.\n */\nexport const GetChangelogResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n entries: z.array(ChangelogEntrySchema).describe('Changelog entries in reverse chronological order'),\n total: z.number().int().optional().describe('Total changelog entries matching filter'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more entries are available'),\n }),\n});\nexport type GetChangelogResponse = z.infer;\n\n// ==========================================\n// 10. Record Subscription (POST / DELETE)\n// ==========================================\n\n/**\n * Request for subscribing to record notifications.\n *\n * @example POST /api/data/account/rec_123/subscribe\n * { events: ['comment', 'field_change'], channels: ['in_app', 'email'] }\n */\nexport const SubscribeRequestSchema = FeedPathParamsSchema.extend({\n events: z.array(SubscriptionEventType).default(['all'])\n .describe('Event types to subscribe to'),\n channels: z.array(NotificationChannel).default(['in_app'])\n .describe('Notification delivery channels'),\n});\nexport type SubscribeRequest = z.infer;\n\n/**\n * Response after subscribing.\n */\nexport const SubscribeResponseSchema = BaseResponseSchema.extend({\n data: RecordSubscriptionSchema.describe('The created or updated subscription'),\n});\nexport type SubscribeResponse = z.infer;\n\n/**\n * Request for unsubscribing from record notifications.\n *\n * @example DELETE /api/data/account/rec_123/subscribe\n */\nexport const FeedUnsubscribeRequestSchema = FeedPathParamsSchema;\nexport type FeedUnsubscribeRequest = z.infer;\n\n/**\n * Response after unsubscribing.\n */\nexport const UnsubscribeResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n unsubscribed: z.boolean().describe('Whether the user was unsubscribed'),\n }),\n});\nexport type UnsubscribeResponse = z.infer;\n\n// ==========================================\n// 11. Feed API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Feed/Chatter operations.\n */\nexport const FeedApiErrorCode = z.enum([\n 'feed_item_not_found',\n 'feed_permission_denied',\n 'feed_item_not_editable',\n 'feed_invalid_parent',\n 'reaction_already_exists',\n 'reaction_not_found',\n 'subscription_already_exists',\n 'subscription_not_found',\n 'invalid_feed_type',\n 'feed_already_pinned',\n 'feed_not_pinned',\n 'feed_already_starred',\n 'feed_not_starred',\n 'feed_search_query_too_short',\n]);\nexport type FeedApiErrorCode = z.infer;\n\n// ==========================================\n// 12. Feed API Contract Registry\n// ==========================================\n\n/**\n * Standard Feed API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const FeedApiContracts = {\n listFeed: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/feed',\n input: GetFeedRequestSchema,\n output: GetFeedResponseSchema,\n },\n createFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed',\n input: CreateFeedItemRequestSchema,\n output: CreateFeedItemResponseSchema,\n },\n updateFeedItem: {\n method: 'PUT' as const,\n path: '/api/data/:object/:recordId/feed/:feedId',\n input: UpdateFeedItemRequestSchema,\n output: UpdateFeedItemResponseSchema,\n },\n deleteFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId',\n input: DeleteFeedItemRequestSchema,\n output: DeleteFeedItemResponseSchema,\n },\n addReaction: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/reactions',\n input: AddReactionRequestSchema,\n output: AddReactionResponseSchema,\n },\n removeReaction: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/reactions/:emoji',\n input: RemoveReactionRequestSchema,\n output: RemoveReactionResponseSchema,\n },\n pinFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/pin',\n input: PinFeedItemRequestSchema,\n output: PinFeedItemResponseSchema,\n },\n unpinFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/pin',\n input: UnpinFeedItemRequestSchema,\n output: UnpinFeedItemResponseSchema,\n },\n starFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/star',\n input: StarFeedItemRequestSchema,\n output: StarFeedItemResponseSchema,\n },\n unstarFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/star',\n input: UnstarFeedItemRequestSchema,\n output: UnstarFeedItemResponseSchema,\n },\n searchFeed: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/feed/search',\n input: SearchFeedRequestSchema,\n output: SearchFeedResponseSchema,\n },\n getChangelog: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/changelog',\n input: GetChangelogRequestSchema,\n output: GetChangelogResponseSchema,\n },\n subscribe: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/subscribe',\n input: SubscribeRequestSchema,\n output: SubscribeResponseSchema,\n },\n unsubscribe: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/subscribe',\n input: FeedUnsubscribeRequestSchema,\n output: UnsubscribeResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Data Export & Import Protocol\n *\n * Defines schemas for streaming data export, import validation,\n * template-based field mapping, and scheduled export jobs.\n *\n * Industry alignment: Salesforce Data Export, Airtable CSV Export,\n * Dynamics 365 Data Management.\n *\n * Base path: /api/v1/data/{object}/export\n */\n\n// ==========================================\n// 1. Export Format & Configuration\n// ==========================================\n\n/**\n * Export Format Enum\n * Supported file formats for data export.\n */\nexport const ExportFormat = z.enum([\n 'csv',\n 'json',\n 'jsonl',\n 'xlsx',\n 'parquet',\n]);\nexport type ExportFormat = z.infer;\n\n/**\n * Export Job Status\n */\nexport const ExportJobStatus = z.enum([\n 'pending',\n 'processing',\n 'completed',\n 'failed',\n 'cancelled',\n 'expired',\n]);\nexport type ExportJobStatus = z.infer;\n\n// ==========================================\n// 2. Export Job Request / Response\n// ==========================================\n\n/**\n * Create Export Job Request\n * Initiates an asynchronous streaming export.\n *\n * @example POST /api/v1/data/account/export\n * { format: 'csv', fields: ['name', 'email', 'status'], filter: { status: 'active' }, limit: 10000 }\n */\nexport const CreateExportJobRequestSchema = z.object({\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional()\n .describe('Specific fields to include (omit for all fields)'),\n filter: z.record(z.string(), z.unknown()).optional()\n .describe('Filter criteria for records to export'),\n sort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n direction: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n })).optional().describe('Sort order for exported records'),\n limit: z.number().int().min(1).optional()\n .describe('Maximum number of records to export'),\n includeHeaders: z.boolean().default(true)\n .describe('Include header row (CSV/XLSX)'),\n encoding: z.string().default('utf-8')\n .describe('Character encoding for the export file'),\n templateId: z.string().optional()\n .describe('Export template ID for predefined field mappings'),\n});\nexport type CreateExportJobRequest = z.infer;\n\n/**\n * Export Job Response\n * Returns the created export job with tracking info.\n */\nexport const CreateExportJobResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n status: ExportJobStatus.describe('Initial job status'),\n estimatedRecords: z.number().int().optional().describe('Estimated total records'),\n createdAt: z.string().datetime().describe('Job creation timestamp'),\n }),\n});\nexport type CreateExportJobResponse = z.infer;\n\n/**\n * Export Job Progress\n * Tracks the progress of an active export job.\n *\n * @example GET /api/v1/data/export/:jobId\n */\nexport const ExportJobProgressSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n status: ExportJobStatus.describe('Current job status'),\n format: ExportFormat.describe('Export format'),\n totalRecords: z.number().int().optional().describe('Total records to export'),\n processedRecords: z.number().int().describe('Records processed so far'),\n percentComplete: z.number().min(0).max(100).describe('Export progress percentage'),\n fileSize: z.number().int().optional().describe('Current file size in bytes'),\n downloadUrl: z.string().optional()\n .describe('Presigned download URL (available when status is \"completed\")'),\n downloadExpiresAt: z.string().datetime().optional()\n .describe('Download URL expiration timestamp'),\n error: z.object({\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n }).optional().describe('Error details if job failed'),\n startedAt: z.string().datetime().optional().describe('Processing start timestamp'),\n completedAt: z.string().datetime().optional().describe('Completion timestamp'),\n }),\n});\nexport type ExportJobProgress = z.infer;\n\n// ==========================================\n// 3. Import Validation & Deduplication\n// ==========================================\n\n/**\n * Import Validation Mode\n */\nexport const ImportValidationMode = z.enum([\n 'strict', // Reject entire import on any validation error\n 'lenient', // Skip invalid records, import valid ones\n 'dry_run', // Validate all records without persisting\n]);\nexport type ImportValidationMode = z.infer;\n\n/**\n * Deduplication Strategy\n * How to handle duplicate records during import.\n */\nexport const DeduplicationStrategy = z.enum([\n 'skip', // Skip duplicates (keep existing)\n 'update', // Update existing with import data\n 'create_new', // Create new record even if duplicate\n 'fail', // Fail the import if duplicates found\n]);\nexport type DeduplicationStrategy = z.infer;\n\n/**\n * Import Validation Config Schema\n * Configuration for validating and deduplicating imported data.\n *\n * @example\n * {\n * mode: 'lenient',\n * deduplication: { strategy: 'update', matchFields: ['email', 'external_id'] },\n * maxErrors: 50,\n * trimWhitespace: true,\n * }\n */\nexport const ImportValidationConfigSchema = z.object({\n mode: ImportValidationMode.default('strict')\n .describe('Validation mode for the import'),\n deduplication: z.object({\n strategy: DeduplicationStrategy.default('skip')\n .describe('How to handle duplicate records'),\n matchFields: z.array(z.string()).min(1)\n .describe('Fields used to identify duplicates (e.g., \"email\", \"external_id\")'),\n }).optional().describe('Deduplication configuration'),\n maxErrors: z.number().int().min(1).default(100)\n .describe('Maximum validation errors before aborting'),\n trimWhitespace: z.boolean().default(true)\n .describe('Trim leading/trailing whitespace from string fields'),\n dateFormat: z.string().optional()\n .describe('Expected date format in import data (e.g., \"YYYY-MM-DD\")'),\n nullValues: z.array(z.string()).optional()\n .describe('Strings to treat as null (e.g., [\"\", \"N/A\", \"null\"])'),\n});\nexport type ImportValidationConfig = z.infer;\n\n/**\n * Import Validation Result Schema\n * Summary of the import validation pass.\n */\nexport const ImportValidationResultSchema = BaseResponseSchema.extend({\n data: z.object({\n totalRecords: z.number().int().describe('Total records in import file'),\n validRecords: z.number().int().describe('Records that passed validation'),\n invalidRecords: z.number().int().describe('Records that failed validation'),\n duplicateRecords: z.number().int().describe('Duplicate records detected'),\n errors: z.array(z.object({\n row: z.number().int().describe('Row number in the import file'),\n field: z.string().optional().describe('Field that failed validation'),\n code: z.string().describe('Validation error code'),\n message: z.string().describe('Validation error message'),\n })).describe('List of validation errors'),\n preview: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Preview of first N valid records (for dry_run mode)'),\n }),\n});\nexport type ImportValidationResult = z.infer;\n\n// ==========================================\n// 4. Export/Import Template\n// ==========================================\n\n/**\n * Field Mapping Entry Schema\n * Maps a source field to a target field with optional transformation.\n */\nexport const FieldMappingEntrySchema = z.object({\n sourceField: z.string().describe('Field name in the source data (import) or object (export)'),\n targetField: z.string().describe('Field name in the target object (import) or file column (export)'),\n targetLabel: z.string().optional().describe('Display label for the target column (export)'),\n transform: z.enum(['none', 'uppercase', 'lowercase', 'trim', 'date_format', 'lookup'])\n .default('none')\n .describe('Transformation to apply during mapping'),\n defaultValue: z.unknown().optional()\n .describe('Default value if source field is null/empty'),\n required: z.boolean().default(false)\n .describe('Whether this field is required (import validation)'),\n});\nexport type FieldMappingEntry = z.infer;\n\n/**\n * Export/Import Template Schema\n * Reusable template for predefined field mappings.\n *\n * @example\n * {\n * name: 'account_export_v1',\n * label: 'Account Export (Standard)',\n * object: 'account',\n * direction: 'export',\n * mappings: [\n * { sourceField: 'name', targetField: 'Company Name' },\n * { sourceField: 'email', targetField: 'Email', transform: 'lowercase' },\n * ],\n * }\n */\nexport const ExportImportTemplateSchema = z.object({\n id: z.string().optional().describe('Template ID (generated on save)'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Template machine name (snake_case)'),\n label: z.string().describe('Human-readable template label'),\n description: z.string().optional().describe('Template description'),\n object: z.string().describe('Target object name'),\n direction: z.enum(['import', 'export', 'bidirectional'])\n .describe('Template direction'),\n format: ExportFormat.optional().describe('Default file format for this template'),\n mappings: z.array(FieldMappingEntrySchema).min(1)\n .describe('Field mapping entries'),\n createdAt: z.string().datetime().optional().describe('Template creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n createdBy: z.string().optional().describe('User who created the template'),\n});\nexport type ExportImportTemplate = z.infer;\n\n// ==========================================\n// 5. Scheduled Export Jobs\n// ==========================================\n\n/**\n * Scheduled Export Schema\n * Defines a recurring data export job.\n *\n * @example\n * {\n * name: 'weekly_account_export',\n * object: 'account',\n * format: 'csv',\n * schedule: { cronExpression: '0 6 * * MON', timezone: 'America/New_York' },\n * delivery: { method: 'email', recipients: ['admin@example.com'] },\n * }\n */\nexport const ScheduledExportSchema = z.object({\n id: z.string().optional().describe('Scheduled export ID'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Schedule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional().describe('Fields to include'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Record filter criteria'),\n templateId: z.string().optional().describe('Export template ID for field mappings'),\n schedule: z.object({\n cronExpression: z.string().describe('Cron expression for schedule'),\n timezone: z.string().default('UTC').describe('IANA timezone'),\n }).describe('Schedule timing configuration'),\n delivery: z.object({\n method: z.enum(['email', 'storage', 'webhook'])\n .describe('How to deliver the export file'),\n recipients: z.array(z.string()).optional()\n .describe('Email recipients (for email delivery)'),\n storagePath: z.string().optional()\n .describe('Storage path (for storage delivery)'),\n webhookUrl: z.string().optional()\n .describe('Webhook URL (for webhook delivery)'),\n }).describe('Export delivery configuration'),\n enabled: z.boolean().default(true).describe('Whether the scheduled export is active'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution'),\n createdAt: z.string().datetime().optional().describe('Creation timestamp'),\n createdBy: z.string().optional().describe('User who created the schedule'),\n});\nexport type ScheduledExport = z.infer;\n\n// ==========================================\n// 6. Get Export Job Download\n// ==========================================\n\n/**\n * Get Export Job Download Request\n * Retrieves a presigned download link for a completed export job.\n *\n * @example GET /api/v1/data/export/:jobId/download\n */\nexport const GetExportJobDownloadRequestSchema = z.object({\n jobId: z.string().describe('Export job ID'),\n});\nexport type GetExportJobDownloadRequest = z.infer;\n\n/**\n * Get Export Job Download Response\n * Returns the presigned download URL and metadata.\n */\nexport const GetExportJobDownloadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n downloadUrl: z.string().describe('Presigned download URL'),\n fileName: z.string().describe('Suggested file name'),\n fileSize: z.number().int().describe('File size in bytes'),\n format: ExportFormat.describe('Export file format'),\n expiresAt: z.string().datetime().describe('Download URL expiration timestamp'),\n checksum: z.string().optional().describe('File checksum (SHA-256)'),\n }),\n});\nexport type GetExportJobDownloadResponse = z.infer;\n\n// ==========================================\n// 7. List Export Jobs\n// ==========================================\n\n/**\n * List Export Jobs Request\n * Retrieves a paginated list of historical export jobs.\n *\n * @example GET /api/v1/data/export?object=account&status=completed&limit=20\n */\nexport const ListExportJobsRequestSchema = z.object({\n object: z.string().optional().describe('Filter by object name'),\n status: ExportJobStatus.optional().describe('Filter by job status'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of jobs to return'),\n cursor: z.string().optional()\n .describe('Pagination cursor from a previous response'),\n});\nexport type ListExportJobsRequest = z.infer;\n\n/**\n * Export Job Summary\n * Compact representation of an export job for list views.\n */\nexport const ExportJobSummarySchema = z.object({\n jobId: z.string().describe('Export job ID'),\n object: z.string().describe('Object name that was exported'),\n status: ExportJobStatus.describe('Current job status'),\n format: ExportFormat.describe('Export file format'),\n totalRecords: z.number().int().optional().describe('Total records exported'),\n fileSize: z.number().int().optional().describe('File size in bytes'),\n createdAt: z.string().datetime().describe('Job creation timestamp'),\n completedAt: z.string().datetime().optional().describe('Completion timestamp'),\n createdBy: z.string().optional().describe('User who initiated the export'),\n});\nexport type ExportJobSummary = z.infer;\n\n/**\n * List Export Jobs Response\n * Paginated list of export jobs with cursor-based pagination.\n */\nexport const ListExportJobsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobs: z.array(ExportJobSummarySchema).describe('List of export jobs'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more jobs are available'),\n }),\n});\nexport type ListExportJobsResponse = z.infer;\n\n// ==========================================\n// 8. Schedule Export Request/Response\n// ==========================================\n\n/**\n * Schedule Export Request\n * Creates a new scheduled (recurring) export job.\n *\n * @example POST /api/v1/data/export/schedules\n */\nexport const ScheduleExportRequestSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Schedule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional().describe('Fields to include'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Record filter criteria'),\n templateId: z.string().optional().describe('Export template ID for field mappings'),\n schedule: z.object({\n cronExpression: z.string().describe('Cron expression for schedule'),\n timezone: z.string().default('UTC').describe('IANA timezone'),\n }).describe('Schedule timing configuration'),\n delivery: z.object({\n method: z.enum(['email', 'storage', 'webhook'])\n .describe('How to deliver the export file'),\n recipients: z.array(z.string()).optional()\n .describe('Email recipients (for email delivery)'),\n storagePath: z.string().optional()\n .describe('Storage path (for storage delivery)'),\n webhookUrl: z.string().optional()\n .describe('Webhook URL (for webhook delivery)'),\n }).describe('Export delivery configuration'),\n});\nexport type ScheduleExportRequest = z.infer;\n\n/**\n * Schedule Export Response\n * Returns the created scheduled export with generated ID and next run info.\n */\nexport const ScheduleExportResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n id: z.string().describe('Scheduled export ID'),\n name: z.string().describe('Schedule name'),\n enabled: z.boolean().describe('Whether the schedule is active'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution'),\n createdAt: z.string().datetime().describe('Creation timestamp'),\n }),\n});\nexport type ScheduleExportResponse = z.infer;\n\n// ==========================================\n// 9. Export API Contracts\n// ==========================================\n\n/**\n * Export API Contract Registry\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const ExportApiContracts = {\n createExportJob: {\n method: 'POST' as const,\n path: '/api/v1/data/:object/export',\n input: CreateExportJobRequestSchema,\n output: CreateExportJobResponseSchema,\n },\n getExportJobProgress: {\n method: 'GET' as const,\n path: '/api/v1/data/export/:jobId',\n input: z.object({ jobId: z.string() }),\n output: ExportJobProgressSchema,\n },\n getExportJobDownload: {\n method: 'GET' as const,\n path: '/api/v1/data/export/:jobId/download',\n input: GetExportJobDownloadRequestSchema,\n output: GetExportJobDownloadResponseSchema,\n },\n listExportJobs: {\n method: 'GET' as const,\n path: '/api/v1/data/export',\n input: ListExportJobsRequestSchema,\n output: ListExportJobsResponseSchema,\n },\n scheduleExport: {\n method: 'POST' as const,\n path: '/api/v1/data/export/schedules',\n input: ScheduleExportRequestSchema,\n output: ScheduleExportResponseSchema,\n },\n cancelExportJob: {\n method: 'POST' as const,\n path: '/api/v1/data/export/:jobId/cancel',\n input: z.object({ jobId: z.string() }),\n output: BaseResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Flow Node Types\n */\nexport const FlowNodeAction = z.enum([\n 'start', // Trigger\n 'end', // Return/Stop\n 'decision', // If/Else logic\n 'assignment', // Set Variable\n 'loop', // For Each\n 'create_record', // CRUD: Create\n 'update_record', // CRUD: Update\n 'delete_record', // CRUD: Delete\n 'get_record', // CRUD: Get/Query\n 'http_request', // Webhook/API Call\n 'script', // Custom Script (JS/TS)\n 'screen', // Screen / User-Input Element\n 'wait', // Delay/Sleep\n 'subflow', // Call another flow\n 'connector_action', // Zapier-style integration action\n 'parallel_gateway', // BPMN Parallel Gateway — AND-split (all outgoing branches execute concurrently)\n 'join_gateway', // BPMN Join Gateway — AND-join (waits for all incoming branches to complete)\n 'boundary_event', // BPMN Boundary Event — attached to a host node for timer/error/signal interrupts\n]);\n\n/**\n * Flow Variable Schema\n * Variables available within the flow execution context.\n */\nexport const FlowVariableSchema = z.object({\n name: z.string().describe('Variable name'),\n type: z.string().describe('Data type (text, number, boolean, object, list)'),\n isInput: z.boolean().default(false).describe('Is input parameter'),\n isOutput: z.boolean().default(false).describe('Is output parameter'),\n});\n\n/**\n * Flow Node Schema\n * A single step in the visual logic graph.\n * \n * @example Decision Node\n * {\n * id: \"dec_1\",\n * type: \"decision\",\n * label: \"Is High Value?\",\n * config: {\n * conditions: [\n * { label: \"Yes\", expression: \"{amount} > 10000\" },\n * { label: \"No\", expression: \"true\" } // default\n * ]\n * },\n * position: { x: 300, y: 200 }\n * }\n */\nexport const FlowNodeSchema = z.object({\n id: z.string().describe('Node unique ID'),\n type: FlowNodeAction.describe('Action type'),\n label: z.string().describe('Node label'),\n \n /** Node Configuration Options (Specific to type) */\n config: z.record(z.string(), z.unknown()).optional().describe('Node configuration'),\n \n /** \n * Connector Action Configuration\n * Used when type is 'connector_action'\n */\n connectorConfig: z.object({\n connectorId: z.string(),\n actionId: z.string(),\n input: z.record(z.string(), z.unknown()).describe('Mapped inputs for the action'),\n }).optional(),\n\n /** UI Position (for the canvas) */\n position: z.object({ x: z.number(), y: z.number() }).optional(),\n\n /** Node-level execution timeout */\n timeoutMs: z.number().int().min(0).optional().describe('Maximum execution time for this node in milliseconds'),\n\n /** Node input schema declaration for Studio form generation and runtime validation */\n inputSchema: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).describe('Parameter type'),\n required: z.boolean().default(false).describe('Whether the parameter is required'),\n description: z.string().optional().describe('Parameter description'),\n })).optional().describe('Input parameter schema for this node'),\n\n /** Node output schema declaration */\n outputSchema: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).describe('Output type'),\n description: z.string().optional().describe('Output description'),\n })).optional().describe('Output schema declaration for this node'),\n\n /**\n * Wait Event Configuration (for 'wait' nodes)\n * Defines what external event or condition should resume the paused execution.\n * Industry alignment: BPMN Intermediate Catch Events, Temporal Signals.\n */\n waitEventConfig: z.object({\n /** Type of event to wait for */\n eventType: z.enum(['timer', 'signal', 'webhook', 'manual', 'condition'])\n .describe('What kind of event resumes the execution'),\n /** Duration to wait (ISO 8601 duration or milliseconds) — for timer events */\n timerDuration: z.string().optional().describe('ISO 8601 duration (e.g., \"PT1H\") or wait time for timer events'),\n /** Signal name to listen for — for signal/webhook events */\n signalName: z.string().optional().describe('Named signal or webhook event to wait for'),\n /** Timeout before auto-failing or continuing — optional guard */\n timeoutMs: z.number().int().min(0).optional().describe('Maximum wait time before timeout (ms)'),\n /** Action to take on timeout */\n onTimeout: z.enum(['fail', 'continue']).default('fail').describe('Behavior when the wait times out'),\n }).optional().describe('Configuration for wait node event resumption'),\n\n /**\n * Boundary Event Configuration (for 'boundary_event' nodes)\n * Attaches an event handler to a host activity node (BPMN Boundary Event pattern).\n * Industry alignment: BPMN Boundary Error/Timer/Signal Events.\n */\n boundaryConfig: z.object({\n /** ID of the host node this boundary event is attached to */\n attachedToNodeId: z.string().describe('Host node ID this boundary event monitors'),\n /** Type of boundary event */\n eventType: z.enum(['error', 'timer', 'signal', 'cancel'])\n .describe('Boundary event trigger type'),\n /** Whether the boundary event interrupts the host activity */\n interrupting: z.boolean().default(true)\n .describe('If true, the host activity is cancelled when this event fires'),\n /** Error code filter — only for error boundary events */\n errorCode: z.string().optional().describe('Specific error code to catch (empty = catch all errors)'),\n /** Timer duration — only for timer boundary events */\n timerDuration: z.string().optional().describe('ISO 8601 duration for timer boundary events'),\n /** Signal name — only for signal boundary events */\n signalName: z.string().optional().describe('Named signal to catch'),\n }).optional().describe('Configuration for boundary events attached to host nodes'),\n});\n\n/**\n * Flow Edge Schema\n * Connections between nodes.\n */\nexport const FlowEdgeSchema = z.object({\n id: z.string().describe('Edge unique ID'),\n source: z.string().describe('Source Node ID'),\n target: z.string().describe('Target Node ID'),\n \n /** Condition for this path (only for decision/branch nodes) */\n condition: z.string().optional().describe('Expression returning boolean used for branching'),\n \n type: z.enum(['default', 'fault', 'conditional']).default('default')\n .describe('Connection type: default (normal flow), fault (error path), or conditional (expression-guarded)'),\n label: z.string().optional().describe('Label on the connector'),\n\n /**\n * Default Sequence Flow marker (BPMN Default Flow semantics).\n * When true, this edge is taken when no sibling conditional edges match.\n * Only meaningful on outgoing edges of decision/gateway nodes.\n */\n isDefault: z.boolean().default(false)\n .describe('Marks this edge as the default path when no other conditions match'),\n});\n\n/**\n * Flow Schema\n * Visual Business Logic Orchestration.\n * \n * @example Simple Approval Logic\n * {\n * name: \"approve_order_flow\",\n * label: \"Approve Large Orders\",\n * type: \"record_change\",\n * status: \"active\",\n * nodes: [\n * { id: \"start\", type: \"start\", label: \"Start\", position: {x: 0, y: 0} },\n * { id: \"check_amount\", type: \"decision\", label: \"Check Amount\", position: {x: 0, y: 100} },\n * { id: \"auto_approve\", type: \"update_record\", label: \"Auto Approve\", position: {x: -100, y: 200} },\n * { id: \"submit_for_approval\", type: \"connector_action\", label: \"Submit\", position: {x: 100, y: 200} }\n * ],\n * edges: [\n * { id: \"e1\", source: \"start\", target: \"check_amount\" },\n * { id: \"e2\", source: \"check_amount\", target: \"auto_approve\", condition: \"{amount} < 500\" },\n * { id: \"e3\", source: \"check_amount\", target: \"submit_for_approval\", condition: \"{amount} >= 500\" }\n * ]\n * }\n */\nexport const FlowSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name'),\n label: z.string().describe('Flow label'),\n description: z.string().optional(),\n \n /** Metadata & Versioning */\n version: z.number().int().default(1).describe('Version number'),\n status: z.enum(['draft', 'active', 'obsolete', 'invalid']).default('draft').describe('Deployment status'),\n template: z.boolean().default(false).describe('Is logic template (Subflow)'),\n\n /** Trigger Type */\n type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).describe('Flow type'),\n \n /** Configuration Variables */\n variables: z.array(FlowVariableSchema).optional().describe('Flow variables'),\n \n /** Graph Definition */\n nodes: z.array(FlowNodeSchema).describe('Flow nodes'),\n edges: z.array(FlowEdgeSchema).describe('Flow connections'),\n \n /** Execution Config */\n active: z.boolean().default(false).describe('Is active (Deprecated: use status)'),\n runAs: z.enum(['system', 'user']).default('user').describe('Execution context'),\n\n /** Error Handling Strategy */\n errorHandling: z.object({\n strategy: z.enum(['fail', 'retry', 'continue']).default('fail').describe('How to handle node execution errors'),\n maxRetries: z.number().int().min(0).max(10).default(0).describe('Number of retry attempts (only for retry strategy)'),\n retryDelayMs: z.number().int().min(0).default(1000).describe('Delay between retries in milliseconds'),\n backoffMultiplier: z.number().min(1).default(1).describe('Multiplier for exponential backoff between retries'),\n maxRetryDelayMs: z.number().int().min(0).default(30000).describe('Maximum delay between retries in milliseconds'),\n jitter: z.boolean().default(false).describe('Add random jitter to retry delay to avoid thundering herd'),\n fallbackNodeId: z.string().optional().describe('Node ID to jump to on unrecoverable error'),\n }).optional().describe('Flow-level error handling configuration'),\n});\n\n/**\n * Type-safe factory for creating flow definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const onCreateFlow = defineFlow({\n * name: 'on_task_create',\n * label: 'On Task Create',\n * type: 'record_change',\n * nodes: [\n * { id: 'start', type: 'start', label: 'Start' },\n * { id: 'end', type: 'end', label: 'End' },\n * ],\n * edges: [{ id: 'e1', source: 'start', target: 'end' }],\n * });\n * ```\n */\nexport function defineFlow(config: z.input): FlowParsed {\n return FlowSchema.parse(config);\n}\n\nexport type Flow = z.input;\nexport type FlowParsed = z.infer;\nexport type FlowNode = z.input;\nexport type FlowNodeParsed = z.infer;\nexport type FlowEdge = z.input;\nexport type FlowEdgeParsed = z.infer;\n\n/**\n * Flow Version History Schema\n * Tracks historical versions of flow definitions for rollback support.\n *\n * Industry alignment: Salesforce Flow Versions, n8n Workflow History.\n */\nexport const FlowVersionHistorySchema = z.object({\n flowName: z.string().describe('Flow machine name'),\n version: z.number().int().min(1).describe('Version number'),\n definition: FlowSchema.describe('Complete flow definition snapshot'),\n createdAt: z.string().datetime().describe('When this version was created'),\n createdBy: z.string().optional().describe('User who created this version'),\n changeNote: z.string().optional().describe('Description of what changed in this version'),\n});\n\nexport type FlowVersionHistory = z.input;\nexport type FlowVersionHistoryParsed = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Automation Execution Protocol\n *\n * Defines schemas for execution logging, error tracking, checkpointing,\n * concurrency control, and scheduled execution persistence.\n *\n * Industry alignment: Salesforce Flow Interviews, Temporal Workflow History,\n * AWS Step Functions execution logs.\n */\n\n// ==========================================\n// 1. Execution Status\n// ==========================================\n\n/**\n * Execution Status Enum\n * Tracks the lifecycle of a flow execution instance.\n */\nexport const ExecutionStatus = z.enum([\n 'pending', // Queued, not yet started\n 'running', // Currently executing\n 'paused', // Paused at a wait/checkpoint node\n 'completed', // Successfully finished\n 'failed', // Terminated with error\n 'cancelled', // Manually cancelled\n 'timed_out', // Exceeded max execution time\n 'retrying', // Failed and retrying\n]);\nexport type ExecutionStatus = z.infer;\n\n// ==========================================\n// 2. Execution Log\n// ==========================================\n\n/**\n * Execution Step Log Entry\n * Records the result of executing a single node in the flow graph.\n */\nexport const ExecutionStepLogSchema = z.object({\n nodeId: z.string().describe('Node ID that was executed'),\n nodeType: z.string().describe('Node action type (e.g., \"decision\", \"http_request\")'),\n nodeLabel: z.string().optional().describe('Human-readable node label'),\n status: z.enum(['success', 'failure', 'skipped']).describe('Step execution result'),\n startedAt: z.string().datetime().describe('When the step started'),\n completedAt: z.string().datetime().optional().describe('When the step completed'),\n durationMs: z.number().int().min(0).optional().describe('Step execution duration in milliseconds'),\n input: z.record(z.string(), z.unknown()).optional().describe('Input data passed to the node'),\n output: z.record(z.string(), z.unknown()).optional().describe('Output data produced by the node'),\n error: z.object({\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n }).optional().describe('Error details if step failed'),\n retryAttempt: z.number().int().min(0).optional().describe('Retry attempt number (0 = first try)'),\n});\nexport type ExecutionStepLog = z.infer;\n\n/**\n * Execution Log Schema\n * Full execution history for a single flow run.\n *\n * @example\n * {\n * id: 'exec_001',\n * flowName: 'approve_order_flow',\n * flowVersion: 1,\n * status: 'completed',\n * trigger: { type: 'record_change', recordId: 'rec_123', object: 'order' },\n * steps: [\n * { nodeId: 'start', nodeType: 'start', status: 'success', startedAt: '...', durationMs: 1 },\n * { nodeId: 'check_amount', nodeType: 'decision', status: 'success', startedAt: '...', durationMs: 5 },\n * ],\n * startedAt: '2026-02-01T10:00:00Z',\n * completedAt: '2026-02-01T10:00:01Z',\n * durationMs: 1050,\n * }\n */\nexport const ExecutionLogSchema = z.object({\n /** Unique execution ID */\n id: z.string().describe('Execution instance ID'),\n\n /** Flow reference */\n flowName: z.string().describe('Machine name of the executed flow'),\n flowVersion: z.number().int().optional().describe('Version of the flow that was executed'),\n\n /** Execution status */\n status: ExecutionStatus.describe('Current execution status'),\n\n /** Trigger context */\n trigger: z.object({\n type: z.string().describe('Trigger type (e.g., \"record_change\", \"schedule\", \"api\", \"manual\")'),\n recordId: z.string().optional().describe('Triggering record ID'),\n object: z.string().optional().describe('Triggering object name'),\n userId: z.string().optional().describe('User who triggered the execution'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional trigger context'),\n }).describe('What triggered this execution'),\n\n /** Step-by-step execution history */\n steps: z.array(ExecutionStepLogSchema).describe('Ordered list of executed steps'),\n\n /** Execution variables snapshot */\n variables: z.record(z.string(), z.unknown()).optional().describe('Final state of flow variables'),\n\n /** Timing */\n startedAt: z.string().datetime().describe('Execution start timestamp'),\n completedAt: z.string().datetime().optional().describe('Execution completion timestamp'),\n durationMs: z.number().int().min(0).optional().describe('Total execution duration in milliseconds'),\n\n /** Context */\n runAs: z.enum(['system', 'user']).optional().describe('Execution context identity'),\n tenantId: z.string().optional().describe('Tenant ID for multi-tenant isolation'),\n});\nexport type ExecutionLog = z.infer;\n\n// ==========================================\n// 3. Execution Error Tracking & Diagnostics\n// ==========================================\n\n/**\n * Execution Error Severity\n */\nexport const ExecutionErrorSeverity = z.enum([\n 'warning', // Non-fatal issue (e.g., deprecated node type)\n 'error', // Node-level failure (may be retried)\n 'critical', // Flow-level failure (execution terminated)\n]);\nexport type ExecutionErrorSeverity = z.infer;\n\n/**\n * Execution Error Schema\n * Detailed error record for diagnostics and troubleshooting.\n */\nexport const ExecutionErrorSchema = z.object({\n id: z.string().describe('Error record ID'),\n executionId: z.string().describe('Parent execution ID'),\n nodeId: z.string().optional().describe('Node where the error occurred'),\n severity: ExecutionErrorSeverity.describe('Error severity level'),\n code: z.string().describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n stack: z.string().optional().describe('Stack trace for debugging'),\n context: z.record(z.string(), z.unknown()).optional()\n .describe('Additional diagnostic context (input data, config snapshot)'),\n timestamp: z.string().datetime().describe('When the error occurred'),\n retryable: z.boolean().default(false).describe('Whether this error can be retried'),\n resolvedAt: z.string().datetime().optional().describe('When the error was resolved (e.g., after successful retry)'),\n});\nexport type ExecutionError = z.infer;\n\n// ==========================================\n// 4. Checkpointing / Resume\n// ==========================================\n\n/**\n * Checkpoint Schema\n * Captures the execution state at a specific node for pause/resume.\n *\n * Used by wait nodes, user-input screens, and crash recovery.\n */\nexport const CheckpointSchema = z.object({\n /** Unique checkpoint ID */\n id: z.string().describe('Checkpoint ID'),\n\n /** Execution reference */\n executionId: z.string().describe('Parent execution ID'),\n flowName: z.string().describe('Flow machine name'),\n\n /** State snapshot */\n currentNodeId: z.string().describe('Node ID where execution is paused'),\n variables: z.record(z.string(), z.unknown()).describe('Flow variable state at checkpoint'),\n completedNodeIds: z.array(z.string()).describe('List of node IDs already executed'),\n\n /** Timing */\n createdAt: z.string().datetime().describe('Checkpoint creation timestamp'),\n expiresAt: z.string().datetime().optional().describe('Checkpoint expiration (auto-cleanup)'),\n\n /** Reason */\n reason: z.enum(['wait', 'screen_input', 'approval', 'error', 'manual_pause', 'parallel_join', 'boundary_event'])\n .describe('Why the execution was checkpointed'),\n});\nexport type Checkpoint = z.infer;\n\n// ==========================================\n// 5. Concurrency Control\n// ==========================================\n\n/**\n * Concurrency Policy Schema\n * Controls how concurrent executions of the same flow are handled.\n *\n * Industry alignment: Salesforce \"Allow multiple instances\", Temporal \"Workflow ID reuse policy\"\n */\nexport const ConcurrencyPolicySchema = z.object({\n /** Maximum concurrent executions of this flow */\n maxConcurrent: z.number().int().min(1).default(1)\n .describe('Maximum number of concurrent executions allowed'),\n\n /** What to do when max concurrency is reached */\n onConflict: z.enum(['queue', 'reject', 'cancel_existing'])\n .default('queue')\n .describe('queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance'),\n\n /** Lock scope for concurrency */\n lockScope: z.enum(['global', 'per_record', 'per_user'])\n .default('global')\n .describe('Scope of the concurrency lock'),\n\n /** Queue timeout (only when onConflict is \"queue\") */\n queueTimeoutMs: z.number().int().min(0).optional()\n .describe('Maximum time to wait in queue before timing out (ms)'),\n});\nexport type ConcurrencyPolicy = z.infer;\n\n// ==========================================\n// 6. Scheduled Execution Persistence\n// ==========================================\n\n/**\n * Schedule State Schema\n * Tracks the runtime state of scheduled flow executions.\n *\n * Persists next-run times, pause/resume state, and execution history references.\n */\nexport const ScheduleStateSchema = z.object({\n /** Unique schedule ID */\n id: z.string().describe('Schedule instance ID'),\n\n /** Flow reference */\n flowName: z.string().describe('Flow machine name'),\n\n /** Schedule configuration */\n cronExpression: z.string().describe('Cron expression (e.g., \"0 9 * * MON-FRI\")'),\n timezone: z.string().default('UTC').describe('IANA timezone for cron evaluation'),\n\n /** Runtime state */\n status: z.enum(['active', 'paused', 'disabled', 'expired'])\n .default('active')\n .describe('Current schedule status'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution timestamp'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n lastExecutionId: z.string().optional().describe('Execution ID of the last run'),\n lastRunStatus: ExecutionStatus.optional().describe('Status of the last run'),\n\n /** Execution tracking */\n totalRuns: z.number().int().min(0).default(0).describe('Total number of executions'),\n consecutiveFailures: z.number().int().min(0).default(0).describe('Consecutive failed executions'),\n\n /** Bounds */\n startDate: z.string().datetime().optional().describe('Schedule effective start date'),\n endDate: z.string().datetime().optional().describe('Schedule expiration date'),\n maxRuns: z.number().int().min(1).optional().describe('Maximum total executions before auto-disable'),\n\n /** Metadata */\n createdAt: z.string().datetime().describe('Schedule creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n createdBy: z.string().optional().describe('User who created the schedule'),\n});\nexport type ScheduleState = z.infer;\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type ExecutionStepLogParsed = z.infer;\nexport type ExecutionLogParsed = z.infer;\nexport type ExecutionErrorParsed = z.infer;\nexport type CheckpointParsed = z.infer;\nexport type ConcurrencyPolicyParsed = z.infer;\nexport type ScheduleStateParsed = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { FlowSchema } from '../automation/flow.zod';\nimport { ExecutionLogSchema } from '../automation/execution.zod';\n\n/**\n * Automation API Protocol\n *\n * Defines REST CRUD endpoint schemas for managing automation flows,\n * triggering executions, and querying execution history.\n *\n * Base path: /api/automation\n *\n * @example Endpoints\n * GET /api/automation — List flows\n * GET /api/automation/:name — Get flow\n * POST /api/automation — Create flow\n * PUT /api/automation/:name — Update flow\n * DELETE /api/automation/:name — Delete flow\n * POST /api/automation/:name/trigger — Trigger flow execution\n * POST /api/automation/:name/toggle — Enable/disable flow\n * GET /api/automation/:name/runs — List execution runs\n * GET /api/automation/:name/runs/:runId — Get single execution run\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Path parameters for flow-level operations.\n */\nexport const AutomationFlowPathParamsSchema = z.object({\n name: z.string().describe('Flow machine name (snake_case)'),\n});\nexport type AutomationFlowPathParams = z.infer;\n\n/**\n * Path parameters for run-level operations.\n */\nexport const AutomationRunPathParamsSchema = AutomationFlowPathParamsSchema.extend({\n runId: z.string().describe('Execution run ID'),\n});\nexport type AutomationRunPathParams = z.infer;\n\n// ==========================================\n// 2. List Flows (GET /api/automation)\n// ==========================================\n\n/**\n * Query parameters for listing automation flows.\n *\n * @example GET /api/automation?status=active&limit=20\n */\nexport const ListFlowsRequestSchema = z.object({\n status: z.enum(['draft', 'active', 'obsolete', 'invalid']).optional()\n .describe('Filter by flow status'),\n type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).optional()\n .describe('Filter by flow type'),\n limit: z.number().int().min(1).max(100).default(50)\n .describe('Maximum number of flows to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type ListFlowsRequest = z.infer;\n\n/**\n * Summary information for a flow in list results.\n */\nexport const FlowSummarySchema = z.object({\n name: z.string().describe('Flow machine name'),\n label: z.string().describe('Flow display label'),\n type: z.string().describe('Flow type'),\n status: z.string().describe('Flow deployment status'),\n version: z.number().int().describe('Flow version number'),\n enabled: z.boolean().describe('Whether the flow is enabled for execution'),\n nodeCount: z.number().int().optional().describe('Number of nodes in the flow'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n});\nexport type FlowSummary = z.infer;\n\n/**\n * Response for the list flows endpoint.\n */\nexport const ListFlowsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n flows: z.array(FlowSummarySchema).describe('Flow summaries'),\n total: z.number().int().optional().describe('Total matching flows'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more flows are available'),\n }),\n});\nexport type ListFlowsResponse = z.infer;\n\n// ==========================================\n// 3. Get Flow (GET /api/automation/:name)\n// ==========================================\n\n/**\n * Request parameters for getting a single flow.\n */\nexport const GetFlowRequestSchema = AutomationFlowPathParamsSchema;\nexport type GetFlowRequest = z.infer;\n\n/**\n * Response for the get flow endpoint.\n */\nexport const GetFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('Full flow definition'),\n});\nexport type GetFlowResponse = z.infer;\n\n// ==========================================\n// 4. Create Flow (POST /api/automation)\n// ==========================================\n\n/**\n * Request body for creating a new flow.\n *\n * @example POST /api/automation\n * { name: 'approval_flow', label: 'Approval Flow', type: 'autolaunched', ... }\n */\nexport const CreateFlowRequestSchema = FlowSchema;\nexport type CreateFlowRequest = z.input;\n\n/**\n * Response after creating a flow.\n */\nexport const CreateFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('The created flow definition'),\n});\nexport type CreateFlowResponse = z.infer;\n\n// ==========================================\n// 5. Update Flow (PUT /api/automation/:name)\n// ==========================================\n\n/**\n * Request body for updating an existing flow.\n *\n * @example PUT /api/automation/approval_flow\n * { label: 'Updated Label', nodes: [...], edges: [...] }\n */\nexport const UpdateFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n definition: FlowSchema.partial().describe('Partial flow definition to update'),\n});\nexport type UpdateFlowRequest = z.infer;\n\n/**\n * Response after updating a flow.\n */\nexport const UpdateFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('The updated flow definition'),\n});\nexport type UpdateFlowResponse = z.infer;\n\n// ==========================================\n// 6. Delete Flow (DELETE /api/automation/:name)\n// ==========================================\n\n/**\n * Request parameters for deleting a flow.\n */\nexport const DeleteFlowRequestSchema = AutomationFlowPathParamsSchema;\nexport type DeleteFlowRequest = z.infer;\n\n/**\n * Response after deleting a flow.\n */\nexport const DeleteFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n name: z.string().describe('Name of the deleted flow'),\n deleted: z.boolean().describe('Whether the flow was deleted'),\n }),\n});\nexport type DeleteFlowResponse = z.infer;\n\n// ==========================================\n// 7. Trigger Flow (POST /api/automation/:name/trigger)\n// ==========================================\n\n/**\n * Request body for triggering a flow execution.\n *\n * @example POST /api/automation/approval_flow/trigger\n * { record: { id: 'rec-1' }, object: 'account', event: 'on_create' }\n */\nexport const TriggerFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n record: z.record(z.string(), z.unknown()).optional()\n .describe('Record that triggered the automation'),\n object: z.string().optional()\n .describe('Object name the record belongs to'),\n event: z.string().optional()\n .describe('Trigger event type'),\n userId: z.string().optional()\n .describe('User who triggered the automation'),\n params: z.record(z.string(), z.unknown()).optional()\n .describe('Additional contextual data'),\n});\nexport type TriggerFlowRequest = z.infer;\n\n/**\n * Response after triggering a flow execution.\n */\nexport const TriggerFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the automation completed successfully'),\n output: z.unknown().optional().describe('Output data from the automation'),\n error: z.string().optional().describe('Error message if execution failed'),\n durationMs: z.number().optional().describe('Execution duration in milliseconds'),\n }),\n});\nexport type TriggerFlowResponse = z.infer;\n\n// ==========================================\n// 8. Toggle Flow (POST /api/automation/:name/toggle)\n// ==========================================\n\n/**\n * Request body for enabling/disabling a flow.\n *\n * @example POST /api/automation/approval_flow/toggle\n * { enabled: true }\n */\nexport const ToggleFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n enabled: z.boolean().describe('Whether to enable (true) or disable (false) the flow'),\n});\nexport type ToggleFlowRequest = z.infer;\n\n/**\n * Response after toggling a flow.\n */\nexport const ToggleFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n name: z.string().describe('Flow name'),\n enabled: z.boolean().describe('New enabled state'),\n }),\n});\nexport type ToggleFlowResponse = z.infer;\n\n// ==========================================\n// 9. List Runs (GET /api/automation/:name/runs)\n// ==========================================\n\n/**\n * Query parameters for listing execution runs.\n *\n * @example GET /api/automation/approval_flow/runs?status=completed&limit=10\n */\nexport const ListRunsRequestSchema = AutomationFlowPathParamsSchema.extend({\n status: z.enum(['pending', 'running', 'paused', 'completed', 'failed', 'cancelled', 'timed_out', 'retrying']).optional()\n .describe('Filter by execution status'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of runs to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type ListRunsRequest = z.infer;\n\n/**\n * Response for the list runs endpoint.\n */\nexport const ListRunsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n runs: z.array(ExecutionLogSchema).describe('Execution run logs'),\n total: z.number().int().optional().describe('Total matching runs'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more runs are available'),\n }),\n});\nexport type ListRunsResponse = z.infer;\n\n// ==========================================\n// 10. Get Run (GET /api/automation/:name/runs/:runId)\n// ==========================================\n\n/**\n * Request parameters for getting a single execution run.\n */\nexport const GetRunRequestSchema = AutomationRunPathParamsSchema;\nexport type GetRunRequest = z.infer;\n\n/**\n * Response for the get run endpoint.\n */\nexport const GetRunResponseSchema = BaseResponseSchema.extend({\n data: ExecutionLogSchema.describe('Full execution log with step details'),\n});\nexport type GetRunResponse = z.infer;\n\n// ==========================================\n// 11. Automation API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Automation operations.\n */\nexport const AutomationApiErrorCode = z.enum([\n 'flow_not_found',\n 'flow_already_exists',\n 'flow_validation_failed',\n 'flow_disabled',\n 'execution_not_found',\n 'execution_failed',\n 'execution_timeout',\n 'node_executor_not_found',\n 'concurrent_execution_limit',\n]);\nexport type AutomationApiErrorCode = z.infer;\n\n// ==========================================\n// 12. Automation API Contract Registry\n// ==========================================\n\n/**\n * Standard Automation API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const AutomationApiContracts = {\n listFlows: {\n method: 'GET' as const,\n path: '/api/automation',\n input: ListFlowsRequestSchema,\n output: ListFlowsResponseSchema,\n },\n getFlow: {\n method: 'GET' as const,\n path: '/api/automation/:name',\n input: GetFlowRequestSchema,\n output: GetFlowResponseSchema,\n },\n createFlow: {\n method: 'POST' as const,\n path: '/api/automation',\n input: CreateFlowRequestSchema,\n output: CreateFlowResponseSchema,\n },\n updateFlow: {\n method: 'PUT' as const,\n path: '/api/automation/:name',\n input: UpdateFlowRequestSchema,\n output: UpdateFlowResponseSchema,\n },\n deleteFlow: {\n method: 'DELETE' as const,\n path: '/api/automation/:name',\n input: DeleteFlowRequestSchema,\n output: DeleteFlowResponseSchema,\n },\n triggerFlow: {\n method: 'POST' as const,\n path: '/api/automation/:name/trigger',\n input: TriggerFlowRequestSchema,\n output: TriggerFlowResponseSchema,\n },\n toggleFlow: {\n method: 'POST' as const,\n path: '/api/automation/:name/toggle',\n input: ToggleFlowRequestSchema,\n output: ToggleFlowResponseSchema,\n },\n listRuns: {\n method: 'GET' as const,\n path: '/api/automation/:name/runs',\n input: ListRunsRequestSchema,\n output: ListRunsResponseSchema,\n },\n getRun: {\n method: 'GET' as const,\n path: '/api/automation/:name/runs/:runId',\n input: GetRunRequestSchema,\n output: GetRunResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\n\n/**\n * # Package Upgrade Protocol\n * \n * Defines the complete lifecycle for upgrading installed packages,\n * including pre-upgrade analysis, snapshot/backup, execution, validation,\n * and rollback capabilities.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Package upgrade with push upgrades and subscriber control\n * - **ServiceNow**: Update Sets with preview, commit, and back-out support\n * - **Helm**: Helm upgrade with rollback to previous release\n * - **Kubernetes**: Rolling update with readiness probes and automatic rollback\n * \n * ## Upgrade Flow\n * ```\n * 1. PreCheck → Validate compatibility, check dependencies\n * 2. Plan → Generate upgrade plan with metadata diff\n * 3. Snapshot → Backup current state (metadata + customizations)\n * 4. Execute → Apply new package metadata with 3-way merge\n * 5. Validate → Run post-upgrade health checks\n * 6. Commit → Finalize upgrade (or Rollback on failure)\n * ```\n */\n\n// ==========================================\n// Upgrade Plan & Analysis\n// ==========================================\n\n/**\n * Metadata Change Type\n * Type of change detected between package versions.\n */\nexport const MetadataChangeTypeSchema = z.enum([\n 'added', // New metadata item added in new version\n 'modified', // Existing metadata item modified\n 'removed', // Metadata item removed in new version\n 'renamed', // Metadata item renamed\n]).describe('Type of metadata change between package versions');\n\n/**\n * Metadata Diff Item\n * Describes a single metadata change between two package versions.\n */\nexport const MetadataDiffItemSchema = z.object({\n /** Metadata type (e.g. \"object\", \"view\", \"flow\") */\n type: z.string().describe('Metadata type'),\n\n /** Metadata name */\n name: z.string().describe('Metadata name'),\n\n /** Type of change */\n changeType: MetadataChangeTypeSchema.describe('Category of metadata modification (added, modified, removed, or renamed)'),\n\n /** Whether this change has potential conflicts with customizations */\n hasConflict: z.boolean().default(false)\n .describe('Whether this change may conflict with customizations'),\n\n /** Human-readable summary of the change */\n summary: z.string().optional().describe('Human-readable change summary'),\n\n /** Previous name (for renames) */\n previousName: z.string().optional().describe('Previous name if renamed'),\n}).describe('Single metadata change between package versions');\n\n/**\n * Upgrade Impact Level\n * Indicates the severity of impact the upgrade will have.\n */\nexport const UpgradeImpactLevelSchema = z.enum([\n 'none', // No impact, seamless upgrade\n 'low', // Minor changes, no user action needed\n 'medium', // Some changes that may affect workflows\n 'high', // Significant changes, user review recommended\n 'critical', // Breaking changes, manual intervention required\n]).describe('Severity of upgrade impact');\n\n/**\n * Upgrade Plan Schema\n * The analysis result before executing an upgrade.\n * Generated by comparing old version metadata with new version metadata.\n */\nexport const UpgradePlanSchema = z.object({\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Current installed version */\n fromVersion: z.string().describe('Currently installed version'),\n\n /** Target version to upgrade to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Overall impact level */\n impactLevel: UpgradeImpactLevelSchema.describe('Severity assessment from none (seamless) to critical (breaking changes)'),\n\n /** List of all metadata changes between versions */\n changes: z.array(MetadataDiffItemSchema).describe('All metadata changes'),\n\n /** Number of customer customizations that may be affected */\n affectedCustomizations: z.number().int().min(0).default(0)\n .describe('Count of customizations that may be affected'),\n\n /** Whether any migration scripts need to run */\n requiresMigration: z.boolean().default(false)\n .describe('Whether data migration scripts are needed'),\n\n /** Migration script paths (relative to package root) */\n migrationScripts: z.array(z.string()).optional()\n .describe('Paths to migration scripts'),\n\n /** Dependencies that also need upgrading */\n dependencyUpgrades: z.array(z.object({\n packageId: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n })).optional().describe('Dependent packages that also need upgrading'),\n\n /** Estimated upgrade duration in seconds */\n estimatedDuration: z.number().int().min(0).optional()\n .describe('Estimated upgrade duration in seconds'),\n\n /** Human-readable summary */\n summary: z.string().optional().describe('Human-readable upgrade summary'),\n}).describe('Upgrade analysis plan generated before execution');\n\n// ==========================================\n// Upgrade Snapshot (Pre-Upgrade Backup)\n// ==========================================\n\n/**\n * Upgrade Snapshot Schema\n * Captures the complete state before an upgrade for rollback capability.\n */\nexport const UpgradeSnapshotSchema = z.object({\n /** Snapshot ID (UUID) */\n id: z.string().describe('Snapshot identifier'),\n\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being upgraded from */\n fromVersion: z.string().describe('Version before upgrade'),\n\n /** Version being upgraded to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Complete manifest of the old package version */\n previousManifest: ManifestSchema.describe('Complete manifest of the previous package version'),\n\n /**\n * Snapshot of all metadata records owned by this package.\n * Stored as array of { type, name, metadata } tuples.\n */\n metadataSnapshot: z.array(z.object({\n type: z.string(),\n name: z.string(),\n metadata: z.record(z.string(), z.unknown()),\n })).describe('Snapshot of all package metadata'),\n\n /**\n * Snapshot of all customer customizations (overlays) for this package's metadata.\n */\n customizationSnapshot: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Snapshot of customer customizations'),\n\n /** When the snapshot was created */\n createdAt: z.string().datetime().describe('Snapshot creation timestamp'),\n\n /** Expiry time for snapshot cleanup */\n expiresAt: z.string().datetime().optional().describe('Snapshot expiry timestamp'),\n}).describe('Pre-upgrade state snapshot for rollback capability');\n\n// ==========================================\n// Upgrade Request/Response\n// ==========================================\n\n/**\n * Upgrade Package Request\n */\nexport const UpgradePackageRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (if omitted, upgrades to latest) */\n targetVersion: z.string().optional().describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional().describe('New manifest (if installing from local)'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum([\n 'keep-custom',\n 'accept-incoming',\n 'three-way-merge',\n ]).default('three-way-merge').describe('How to handle customer customizations'),\n\n /** Whether to run in dry-run mode (preview only, no changes) */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Whether to skip pre-upgrade validation */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\n\n/**\n * Upgrade Phase\n * Current phase of the upgrade process.\n */\nexport const UpgradePhaseSchema = z.enum([\n 'pending', // Upgrade requested but not started\n 'analyzing', // Generating upgrade plan\n 'snapshot', // Creating pre-upgrade snapshot\n 'executing', // Applying metadata changes\n 'migrating', // Running migration scripts\n 'validating', // Post-upgrade validation\n 'completed', // Upgrade completed successfully\n 'failed', // Upgrade failed\n 'rolling-back', // Rollback in progress\n 'rolled-back', // Rollback completed\n]).describe('Current phase of the upgrade process');\n\n/**\n * Upgrade Package Response\n */\nexport const UpgradePackageResponseSchema = z.object({\n /** Whether the upgrade was successful */\n success: z.boolean().describe('Whether the upgrade succeeded'),\n\n /** Current upgrade phase */\n phase: UpgradePhaseSchema.describe('Current upgrade phase'),\n\n /** The upgrade plan that was executed */\n plan: UpgradePlanSchema.optional().describe('Upgrade plan'),\n\n /** Snapshot ID for rollback */\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n\n /** Merge conflicts that need manual resolution (if any) */\n conflicts: z.array(z.object({\n path: z.string(),\n baseValue: z.unknown(),\n incomingValue: z.unknown(),\n customValue: z.unknown(),\n })).optional().describe('Unresolved merge conflicts'),\n\n /** Error message (if failed) */\n errorMessage: z.string().optional().describe('Error message if upgrade failed'),\n\n /** Human-readable summary */\n message: z.string().optional().describe('Human-readable status message'),\n}).describe('Upgrade package response');\n\n// ==========================================\n// Rollback\n// ==========================================\n\n/**\n * Rollback Package Request\n */\nexport const RollbackPackageRequestSchema = z.object({\n /** Package ID to rollback */\n packageId: z.string().describe('Package ID to rollback'),\n\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\n\n/**\n * Rollback Package Response\n */\nexport const RollbackPackageResponseSchema = z.object({\n /** Whether the rollback was successful */\n success: z.boolean().describe('Whether the rollback succeeded'),\n\n /** Restored version */\n restoredVersion: z.string().optional().describe('Version restored to'),\n\n /** Message */\n message: z.string().optional().describe('Rollback status message'),\n}).describe('Rollback package response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type MetadataChangeType = z.infer;\nexport type MetadataDiffItem = z.infer;\nexport type UpgradeImpactLevel = z.infer;\nexport type UpgradePlan = z.infer;\nexport type UpgradeSnapshot = z.infer;\nexport type UpgradePackageRequest = z.infer;\nexport type UpgradePhase = z.infer;\nexport type UpgradePackageResponse = z.infer;\nexport type RollbackPackageRequest = z.infer;\nexport type RollbackPackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Package Artifact Format Protocol\n *\n * Defines the standard structure of a package artifact (.tgz) produced by\n * `os plugin build`. The marketplace uses these schemas to validate, store,\n * and distribute package artifacts.\n *\n * ## Artifact Internal Structure\n * ```\n * ├── manifest.json ← ManifestSchema serialized\n * ├── metadata/ ← 30+ metadata types (JSON)\n * │ ├── objects/ ← *.object.json\n * │ ├── views/ ← *.view.json\n * │ ├── pages/ ← *.page.json\n * │ ├── flows/ ← *.flow.json\n * │ ├── dashboards/ ← *.dashboard.json\n * │ ├── permissions/ ← *.permission.json\n * │ ├── agents/ ← *.agent.json\n * │ └── ... ← Other metadata types\n * ├── assets/ ← Static resources\n * │ ├── icon.svg\n * │ └── screenshots/\n * ├── data/ ← Seed data (DatasetSchema serialized)\n * ├── locales/ ← i18n translation files\n * ├── checksums.json ← SHA256 checksum per file\n * └── signature.sig ← RSA-SHA256 package signature\n * ```\n *\n * ## Architecture Alignment\n * - **Salesforce**: Managed Package .zip with metadata components\n * - **npm**: .tgz with package.json + contents\n * - **Helm**: Chart .tgz with Chart.yaml + templates\n * - **VS Code**: .vsix (zip) with extension manifest + assets\n */\n\n// ==========================================\n// Metadata Category Definitions\n// ==========================================\n\n/**\n * Supported metadata categories within an artifact.\n * Each category maps to a subdirectory under `metadata/`.\n */\nexport const MetadataCategoryEnum = z.enum([\n 'objects',\n 'views',\n 'pages',\n 'flows',\n 'dashboards',\n 'permissions',\n 'agents',\n 'reports',\n 'actions',\n 'translations',\n 'themes',\n 'datasets',\n 'apis',\n 'triggers',\n 'workflows',\n]).describe('Metadata category within the artifact');\n\nexport type MetadataCategory = z.infer;\n\n// ==========================================\n// Artifact File Entry\n// ==========================================\n\n/**\n * A single file entry within the artifact.\n */\nexport const ArtifactFileEntrySchema = z.object({\n /** Relative path within the artifact (e.g. \"metadata/objects/account.object.json\") */\n path: z.string().describe('Relative file path within the artifact'),\n\n /** File size in bytes */\n size: z.number().int().nonnegative().describe('File size in bytes'),\n\n /** Metadata category (if under metadata/) */\n category: MetadataCategoryEnum.optional()\n .describe('Metadata category this file belongs to'),\n}).describe('A single file entry within the artifact');\n\nexport type ArtifactFileEntry = z.infer;\n\n// ==========================================\n// Artifact Checksum\n// ==========================================\n\n/**\n * Checksum map for artifact integrity verification.\n * Maps relative file paths to their SHA256 hash values.\n *\n * @example\n * {\n * \"manifest.json\": \"a1b2c3...\",\n * \"metadata/objects/account.object.json\": \"d4e5f6...\"\n * }\n */\nexport const ArtifactChecksumSchema = z.object({\n /** Hash algorithm used (default: SHA256) */\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm used for checksums'),\n\n /** Map of relative file paths to their hash values */\n files: z.record(z.string(), z.string().regex(/^[a-f0-9]+$/))\n .describe('File path to hash value mapping'),\n}).describe('Checksum manifest for artifact integrity verification');\n\nexport type ArtifactChecksum = z.infer;\n\n// ==========================================\n// Artifact Signature\n// ==========================================\n\n/**\n * Digital signature for artifact authenticity verification.\n * Ensures the artifact was produced by a trusted publisher and has not been tampered with.\n */\nexport const ArtifactSignatureSchema = z.object({\n /** Signature algorithm */\n algorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).default('RSA-SHA256')\n .describe('Signing algorithm used'),\n\n /** Public key reference (URL or fingerprint) for verification */\n publicKeyRef: z.string()\n .describe('Public key reference (URL or fingerprint) for signature verification'),\n\n /** Base64-encoded signature value */\n signature: z.string()\n .describe('Base64-encoded digital signature'),\n\n /** Timestamp of when the artifact was signed */\n signedAt: z.string().datetime().optional()\n .describe('ISO 8601 timestamp of when the artifact was signed'),\n\n /** Signer identity (publisher ID or email) */\n signedBy: z.string().optional()\n .describe('Identity of the signer (publisher ID or email)'),\n}).describe('Digital signature for artifact authenticity verification');\n\nexport type ArtifactSignature = z.infer;\n\n// ==========================================\n// Package Artifact Schema\n// ==========================================\n\n/**\n * Package Artifact Schema\n *\n * Describes the complete structure and metadata of a built package artifact.\n * This schema is used to validate artifacts before upload to the marketplace.\n */\nexport const PackageArtifactSchema = z.object({\n /** Artifact format version (for forward compatibility) */\n formatVersion: z.string().regex(/^\\d+\\.\\d+$/).default('1.0')\n .describe('Artifact format version (e.g. \"1.0\")'),\n\n /** Package ID from the manifest */\n packageId: z.string().describe('Package identifier from manifest'),\n\n /** Package version from the manifest */\n version: z.string().describe('Package version from manifest'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format of the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().positive().optional()\n .describe('Total artifact file size in bytes'),\n\n /** Build timestamp */\n builtAt: z.string().datetime()\n .describe('ISO 8601 timestamp of when the artifact was built'),\n\n /** Build tool and version that produced this artifact */\n builtWith: z.string().optional()\n .describe('Build tool identifier (e.g. \"os-cli@3.2.0\")'),\n\n /** File listing within the artifact */\n files: z.array(ArtifactFileEntrySchema).optional()\n .describe('List of files contained in the artifact'),\n\n /** Metadata categories present in the artifact */\n metadataCategories: z.array(MetadataCategoryEnum).optional()\n .describe('Metadata categories included in this artifact'),\n\n /** Integrity checksums for all files */\n checksums: ArtifactChecksumSchema.optional()\n .describe('SHA256 checksums for artifact integrity verification'),\n\n /** Digital signature for authenticity */\n signature: ArtifactSignatureSchema.optional()\n .describe('Digital signature for artifact authenticity verification'),\n}).describe('Package artifact structure and metadata');\n\nexport type PackageArtifact = z.infer;\nexport type PackageArtifactInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Marketplace Protocol\n * \n * Defines the core schemas for the plugin marketplace ecosystem, covering:\n * - **Developer Side**: Package publishing, submission, and version releases\n * - **Platform Side**: Marketplace listing, review, approval, and discovery\n * \n * This protocol defines the contract between plugin developers, the marketplace\n * platform, and customers who install plugins.\n * \n * ## Architecture Alignment\n * - **Salesforce AppExchange**: Security review, managed packages, listing profiles\n * - **VS Code Marketplace**: Extension publishing, ratings, verified publishers\n * - **npm Registry**: Package publishing, versioning, scoped packages\n * - **Shopify App Store**: App review process, billing integration, merchant installs\n * \n * ## Developer Publishing Flow\n * ```\n * 1. Develop → Build plugin locally using ObjectStack CLI\n * 2. Validate → Run `os plugin validate` (schema + security checks)\n * 3. Build → Run `os plugin build` (bundle + sign)\n * 4. Submit → Run `os plugin publish` (submit to marketplace)\n * 5. Review → Platform conducts automated + manual review\n * 6. Publish → Approved listing goes live on marketplace\n * ```\n * \n * ## Platform Management Flow\n * ```\n * 1. Receive → Accept submissions from verified publishers\n * 2. Scan → Automated security scan and compatibility check\n * 3. Review → Human review for quality and policy compliance\n * 4. Catalog → Index in marketplace search catalog\n * 5. Monitor → Track installs, ratings, issues, and enforce SLAs\n * ```\n */\n\n// ==========================================\n// Publisher Identity\n// ==========================================\n\n/**\n * Publisher Verification Status\n */\nexport const PublisherVerificationSchema = z.enum([\n 'unverified', // Not yet verified\n 'pending', // Verification in progress\n 'verified', // Identity verified by platform\n 'trusted', // Trusted publisher (track record of quality)\n 'partner', // Official platform partner\n]).describe('Publisher verification status');\n\n/**\n * Publisher Schema\n * Represents a developer or organization that publishes packages.\n */\nexport const PublisherSchema = z.object({\n /** Publisher unique identifier */\n id: z.string().describe('Publisher ID'),\n\n /** Display name */\n name: z.string().describe('Publisher display name'),\n\n /** Publisher type */\n type: z.enum(['individual', 'organization']).describe('Publisher type'),\n\n /** Verification status */\n verification: PublisherVerificationSchema.default('unverified')\n .describe('Publisher verification status'),\n\n /** Contact email */\n email: z.string().email().optional().describe('Contact email'),\n\n /** Website URL */\n website: z.string().url().optional().describe('Publisher website'),\n\n /** Organization logo URL */\n logoUrl: z.string().url().optional().describe('Publisher logo URL'),\n\n /** Short description/bio */\n description: z.string().optional().describe('Publisher description'),\n\n /** Registration date */\n registeredAt: z.string().datetime().optional()\n .describe('Publisher registration timestamp'),\n}).describe('Developer or organization that publishes packages');\n\n// ==========================================\n// Artifact Reference & Distribution\n// ==========================================\n\n/**\n * Artifact Reference Schema\n *\n * Points to a downloadable package artifact with integrity verification.\n * Used in marketplace listings and install workflows.\n */\nexport const ArtifactReferenceSchema = z.object({\n /** Artifact download URL */\n url: z.string().url().describe('Artifact download URL'),\n\n /** SHA256 integrity checksum */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA256 checksum'),\n\n /** File size in bytes */\n size: z.number().int().positive().describe('Artifact size in bytes'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz').describe('Artifact format'),\n\n /** Upload timestamp */\n uploadedAt: z.string().datetime().describe('Upload timestamp'),\n}).describe('Reference to a downloadable package artifact');\n\nexport type ArtifactReference = z.infer;\n\n/**\n * Artifact Download Response Schema\n *\n * Response from the artifact download API endpoint.\n * Provides a time-limited download URL with integrity metadata.\n */\nexport const ArtifactDownloadResponseSchema = z.object({\n /** Pre-signed or direct download URL */\n downloadUrl: z.string().url().describe('Artifact download URL (may be pre-signed)'),\n\n /** SHA256 checksum for download verification */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA256 checksum for verification'),\n\n /** File size in bytes */\n size: z.number().int().positive().describe('Artifact size in bytes'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).describe('Artifact format'),\n\n /** URL expiration time (for pre-signed URLs) */\n expiresAt: z.string().datetime().optional()\n .describe('URL expiration timestamp for pre-signed URLs'),\n}).describe('Artifact download response with integrity metadata');\n\nexport type ArtifactDownloadResponse = z.infer;\n\n// ==========================================\n// Marketplace Listing\n// ==========================================\n\n/**\n * Marketplace Category\n */\nexport const MarketplaceCategorySchema = z.enum([\n 'crm', // Customer Relationship Management\n 'erp', // Enterprise Resource Planning\n 'hr', // Human Resources\n 'finance', // Finance & Accounting\n 'project', // Project Management\n 'collaboration', // Collaboration & Communication\n 'analytics', // Analytics & Reporting\n 'integration', // Integrations & Connectors\n 'automation', // Automation & Workflows\n 'ai', // AI & Machine Learning\n 'security', // Security & Compliance\n 'developer-tools', // Developer Tools\n 'ui-theme', // UI Themes & Appearance\n 'storage', // Storage & Drivers\n 'other', // Other / Uncategorized\n]).describe('Marketplace package category');\n\n/**\n * Listing Status\n */\nexport const ListingStatusSchema = z.enum([\n 'draft', // Not yet submitted\n 'submitted', // Submitted for review\n 'in-review', // Under review\n 'approved', // Approved, ready to publish\n 'published', // Live on marketplace\n 'rejected', // Review rejected\n 'suspended', // Suspended by platform (policy violation)\n 'deprecated', // Deprecated by publisher\n 'unlisted', // Available by direct link only\n]).describe('Marketplace listing status');\n\n/**\n * Pricing Model\n */\nexport const PricingModelSchema = z.enum([\n 'free', // Free to install\n 'freemium', // Free with paid premium features\n 'paid', // Requires purchase\n 'subscription', // Recurring subscription\n 'usage-based', // Pay per usage\n 'contact-sales', // Enterprise pricing, contact for quote\n]).describe('Package pricing model');\n\n/**\n * Marketplace Listing Schema\n * \n * The public-facing profile of a package on the marketplace.\n * Contains marketing information, pricing, and installation metadata.\n */\nexport const MarketplaceListingSchema = z.object({\n /** Listing ID (matches package ID) */\n id: z.string().describe('Listing ID (matches package manifest ID)'),\n\n /** Package ID (reverse domain notation) */\n packageId: z.string().describe('Package identifier'),\n\n /** Publisher information */\n publisherId: z.string().describe('Publisher ID'),\n\n /** Current listing status */\n status: ListingStatusSchema.default('draft')\n .describe('Publication state: draft, published, under-review, suspended, deprecated, or unlisted'),\n\n /** Display name */\n name: z.string().describe('Display name'),\n\n /** Tagline (short description for cards/search results) */\n tagline: z.string().max(120).optional().describe('Short tagline (max 120 chars)'),\n\n /** Full description (supports Markdown) */\n description: z.string().optional().describe('Full description (Markdown)'),\n\n /** Category */\n category: MarketplaceCategorySchema.describe('Package category'),\n\n /** Additional tags for search discovery */\n tags: z.array(z.string()).optional().describe('Search tags'),\n\n /** Icon/logo URL */\n iconUrl: z.string().url().optional().describe('Package icon URL'),\n\n /** Screenshot URLs */\n screenshots: z.array(z.object({\n url: z.string().url(),\n caption: z.string().optional(),\n })).optional().describe('Screenshots'),\n\n /** Documentation URL */\n documentationUrl: z.string().url().optional()\n .describe('Documentation URL'),\n\n /** Support URL */\n supportUrl: z.string().url().optional()\n .describe('Support URL'),\n\n /** Source repository URL (if open source) */\n repositoryUrl: z.string().url().optional()\n .describe('Source repository URL'),\n\n /** Pricing model */\n pricing: PricingModelSchema.default('free')\n .describe('Pricing model'),\n\n /** Price in cents (if paid) */\n priceInCents: z.number().int().min(0).optional()\n .describe('Price in cents (e.g. 999 = $9.99)'),\n\n /** Latest published version */\n latestVersion: z.string().describe('Latest published version'),\n\n /** Minimum platform version required */\n minPlatformVersion: z.string().optional()\n .describe('Minimum ObjectStack platform version'),\n\n /** Available versions for installation */\n versions: z.array(z.object({\n version: z.string().describe('Version string'),\n releaseDate: z.string().datetime().describe('Release date'),\n releaseNotes: z.string().optional().describe('Release notes'),\n minPlatformVersion: z.string().optional().describe('Minimum platform version'),\n deprecated: z.boolean().default(false).describe('Whether this version is deprecated'),\n /** Artifact reference for this version */\n artifact: ArtifactReferenceSchema.optional()\n .describe('Downloadable artifact for this version'),\n })).optional().describe('Published versions'),\n\n /** Aggregate statistics */\n stats: z.object({\n totalInstalls: z.number().int().min(0).default(0).describe('Total installs'),\n activeInstalls: z.number().int().min(0).default(0).describe('Active installs'),\n averageRating: z.number().min(0).max(5).optional().describe('Average user rating (0-5)'),\n totalRatings: z.number().int().min(0).default(0).describe('Total ratings count'),\n totalReviews: z.number().int().min(0).default(0).describe('Total reviews count'),\n }).optional().describe('Aggregate marketplace statistics'),\n\n /** First published date */\n publishedAt: z.string().datetime().optional()\n .describe('First published timestamp'),\n\n /** Last updated date */\n updatedAt: z.string().datetime().optional()\n .describe('Last updated timestamp'),\n}).describe('Public-facing package listing on the marketplace');\n\n// ==========================================\n// Package Submission & Review\n// ==========================================\n\n/**\n * Package Submission Schema\n * A developer's submission of a package version for marketplace review.\n */\nexport const PackageSubmissionSchema = z.object({\n /** Submission ID */\n id: z.string().describe('Submission ID'),\n\n /** Package ID */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being submitted */\n version: z.string().describe('Version being submitted'),\n\n /** Publisher ID */\n publisherId: z.string().describe('Publisher submitting'),\n\n /** Submission status */\n status: z.enum([\n 'pending', // Awaiting review\n 'scanning', // Automated scan in progress\n 'in-review', // Under manual review\n 'changes-requested', // Reviewer requests changes\n 'approved', // Approved for publishing\n 'rejected', // Rejected\n ]).default('pending').describe('Review status'),\n\n /**\n * Package artifact URL or reference.\n * Points to the built package bundle for review.\n */\n artifactUrl: z.string().describe('Package artifact URL for review'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional().describe('Release notes for this version'),\n\n /** Whether this is the first submission (new listing) vs version update */\n isNewListing: z.boolean().default(false).describe('Whether this is a new listing submission'),\n\n /** Automated scan results */\n scanResults: z.object({\n /** Whether automated scan passed */\n passed: z.boolean(),\n /** Security scan score (0-100) */\n securityScore: z.number().min(0).max(100).optional(),\n /** Compatibility check passed */\n compatibilityCheck: z.boolean().optional(),\n /** Issues found during scan */\n issues: z.array(z.object({\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),\n message: z.string(),\n file: z.string().optional(),\n line: z.number().optional(),\n })).optional(),\n }).optional().describe('Automated scan results'),\n\n /** Reviewer notes (from platform reviewer) */\n reviewerNotes: z.string().optional().describe('Notes from the platform reviewer'),\n\n /** Submitted timestamp */\n submittedAt: z.string().datetime().optional().describe('Submission timestamp'),\n\n /** Review completed timestamp */\n reviewedAt: z.string().datetime().optional().describe('Review completion timestamp'),\n}).describe('Developer submission of a package version for review');\n\n// ==========================================\n// Marketplace Search & Discovery\n// ==========================================\n\n/**\n * Marketplace Search Request\n */\nexport const MarketplaceSearchRequestSchema = z.object({\n /** Search query string */\n query: z.string().optional().describe('Full-text search query'),\n\n /** Filter by category */\n category: MarketplaceCategorySchema.optional().describe('Filter by category'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Filter by pricing model */\n pricing: PricingModelSchema.optional().describe('Filter by pricing model'),\n\n /** Filter by publisher verification level */\n publisherVerification: PublisherVerificationSchema.optional()\n .describe('Filter by publisher verification level'),\n\n /** Sort by */\n sortBy: z.enum([\n 'relevance', // Best match (default for search)\n 'popularity', // Most installs\n 'rating', // Highest rated\n 'newest', // Most recently published\n 'updated', // Most recently updated\n 'name', // Alphabetical\n ]).default('relevance').describe('Sort field'),\n\n /** Sort direction */\n sortDirection: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n\n /** Pagination: page number */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(100).default(20).describe('Items per page'),\n\n /** Filter by minimum platform version compatibility */\n platformVersion: z.string().optional()\n .describe('Filter by platform version compatibility'),\n}).describe('Marketplace search request');\n\n/**\n * Marketplace Search Response\n */\nexport const MarketplaceSearchResponseSchema = z.object({\n /** Search results */\n items: z.array(MarketplaceListingSchema).describe('Search result listings'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching results'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page number'),\n\n /** Items per page */\n pageSize: z.number().int().min(1).describe('Items per page'),\n\n /** Facets for filtering */\n facets: z.object({\n categories: z.array(z.object({\n category: MarketplaceCategorySchema,\n count: z.number().int().min(0),\n })).optional(),\n pricing: z.array(z.object({\n model: PricingModelSchema,\n count: z.number().int().min(0),\n })).optional(),\n }).optional().describe('Aggregation facets for refining search'),\n}).describe('Marketplace search response');\n\n// ==========================================\n// Marketplace Install from Marketplace\n// ==========================================\n\n/**\n * Install from Marketplace Request\n * Extends the basic package install with marketplace-specific fields.\n */\nexport const MarketplaceInstallRequestSchema = z.object({\n /** Listing ID to install */\n listingId: z.string().describe('Marketplace listing ID'),\n\n /** Specific version to install (defaults to latest) */\n version: z.string().optional().describe('Version to install'),\n\n /** License key (for paid packages) */\n licenseKey: z.string().optional().describe('License key for paid packages'),\n\n /** User-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n\n /** Whether to enable immediately after install */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n\n /** Artifact reference (resolved from listing version, or provided directly) */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference for direct installation'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n}).describe('Install from marketplace request');\n\n/**\n * Install from Marketplace Response\n */\nexport const MarketplaceInstallResponseSchema = z.object({\n /** Whether installation was successful */\n success: z.boolean().describe('Whether installation succeeded'),\n\n /** Installed package ID */\n packageId: z.string().optional().describe('Installed package identifier'),\n\n /** Installed version */\n version: z.string().optional().describe('Installed version'),\n\n /** Human-readable message */\n message: z.string().optional().describe('Installation status message'),\n}).describe('Install from marketplace response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type PublisherVerification = z.infer;\nexport type Publisher = z.infer;\nexport type MarketplaceCategory = z.infer;\nexport type ListingStatus = z.infer;\nexport type PricingModel = z.infer;\nexport type MarketplaceListing = z.infer;\nexport type PackageSubmission = z.infer;\nexport type MarketplaceSearchRequest = z.infer;\nexport type MarketplaceSearchResponse = z.infer;\nexport type MarketplaceInstallRequest = z.infer;\nexport type MarketplaceInstallResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { InstalledPackageSchema } from '../kernel/package-registry.zod';\nimport { DependencyResolutionResultSchema } from '../kernel/dependency-resolution.zod';\nimport { UpgradePlanSchema } from '../kernel/package-upgrade.zod';\nimport { PackageArtifactSchema } from '../kernel/package-artifact.zod';\nimport { ManifestSchema } from '../kernel/manifest.zod';\nimport { ArtifactReferenceSchema } from '../cloud/marketplace.zod';\n\n/**\n * # Package API Protocol\n *\n * REST API endpoint schemas for package lifecycle management.\n *\n * Base path: /api/v1/packages\n *\n * @example Endpoints\n * POST /api/v1/packages/install — Install a package\n * POST /api/v1/packages/upgrade — Upgrade a package\n * POST /api/v1/packages/resolve-dependencies — Resolve dependencies\n * POST /api/v1/packages/upload — Upload an artifact\n * GET /api/v1/packages — List installed packages\n * GET /api/v1/packages/:packageId — Get package details\n * POST /api/v1/packages/:packageId/rollback — Rollback a package\n * DELETE /api/v1/packages/:packageId — Uninstall a package\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Path parameters for package-level operations.\n */\nexport const PackagePathParamsSchema = z.object({\n packageId: z.string().describe('Package identifier'),\n});\nexport type PackagePathParams = z.infer;\n\n// ==========================================\n// 2. List Packages (GET /api/v1/packages)\n// ==========================================\n\n/**\n * Query parameters for listing installed packages.\n */\nexport const ListInstalledPackagesRequestSchema = z.object({\n /** Filter by package status */\n status: z.enum(['installed', 'disabled', 'installing', 'upgrading', 'uninstalling', 'error']).optional()\n .describe('Filter by package status'),\n /** Filter by enabled state */\n enabled: z.boolean().optional()\n .describe('Filter by enabled state'),\n /** Maximum number of packages to return */\n limit: z.number().int().min(1).max(100).default(50)\n .describe('Maximum number of packages to return'),\n /** Cursor for pagination */\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n}).describe('List installed packages request');\nexport type ListInstalledPackagesRequest = z.infer;\n\n/**\n * Response for listing installed packages.\n */\nexport const ListInstalledPackagesResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n packages: z.array(InstalledPackageSchema).describe('Installed packages'),\n total: z.number().int().optional().describe('Total matching packages'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more packages are available'),\n }),\n}).describe('List installed packages response');\nexport type ListInstalledPackagesResponse = z.infer;\n\n// ==========================================\n// 3. Get Package (GET /api/v1/packages/:packageId)\n// ==========================================\n\n/**\n * Request for getting a single installed package.\n */\nexport const GetInstalledPackageRequestSchema = PackagePathParamsSchema;\nexport type GetInstalledPackageRequest = z.infer;\n\n/**\n * Response for getting a single installed package.\n */\nexport const GetInstalledPackageResponseSchema = BaseResponseSchema.extend({\n data: InstalledPackageSchema.describe('Installed package details'),\n}).describe('Get installed package response');\nexport type GetInstalledPackageResponse = z.infer;\n\n// ==========================================\n// 4. Install Package (POST /api/v1/packages/install)\n// ==========================================\n\n/**\n * Request body for installing a package.\n *\n * @example POST /api/v1/packages/install\n * { manifest: {...}, platformVersion: '3.2.0', enableOnInstall: true }\n */\nexport const PackageInstallRequestSchema = z.object({\n /** Package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n\n /** User-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n\n /** Whether to enable immediately after install */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n\n /** Current platform version for compatibility verification */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n\n /** Artifact reference for the package (if installing from marketplace) */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference for marketplace installation'),\n}).describe('Install package request');\nexport type PackageInstallRequest = z.infer;\n\n/**\n * Response after installing a package.\n */\nexport const PackageInstallResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result'),\n namespaceConflicts: z.array(z.object({\n type: z.literal('namespace_conflict').describe('Error type'),\n requestedNamespace: z.string().describe('Requested namespace'),\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n conflictingPackageName: z.string().describe('Conflicting package name'),\n suggestion: z.string().optional().describe('Suggested alternative'),\n })).optional().describe('Namespace conflicts detected'),\n message: z.string().optional().describe('Installation status message'),\n }),\n}).describe('Install package response');\nexport type PackageInstallResponse = z.infer;\n\n// ==========================================\n// 5. Upgrade Package (POST /api/v1/packages/upgrade)\n// ==========================================\n\n/**\n * Request body for upgrading a package.\n *\n * @example POST /api/v1/packages/upgrade\n * { packageId: 'com.acme.crm', targetVersion: '2.0.0', createSnapshot: true }\n */\nexport const PackageUpgradeRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (defaults to latest) */\n targetVersion: z.string().optional()\n .describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional()\n .describe('New manifest for the target version'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum(['keep-custom', 'accept-incoming', 'three-way-merge'])\n .default('three-way-merge')\n .describe('How to handle customer customizations'),\n\n /** Preview upgrade without making changes */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Skip pre-upgrade compatibility checks */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\nexport type PackageUpgradeRequest = z.infer;\n\n/**\n * Response after upgrading a package.\n */\nexport const PackageUpgradeResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the upgrade succeeded'),\n phase: z.string().describe('Current upgrade phase'),\n plan: UpgradePlanSchema.optional().describe('Upgrade plan that was executed'),\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n conflicts: z.array(z.object({\n path: z.string().describe('Conflict path'),\n baseValue: z.unknown().describe('Base value'),\n incomingValue: z.unknown().describe('Incoming value'),\n customValue: z.unknown().describe('Custom value'),\n })).optional().describe('Unresolved merge conflicts'),\n errorMessage: z.string().optional().describe('Error message if failed'),\n message: z.string().optional().describe('Human-readable status message'),\n }),\n}).describe('Upgrade package response');\nexport type PackageUpgradeResponse = z.infer;\n\n// ==========================================\n// 6. Resolve Dependencies (POST /api/v1/packages/resolve-dependencies)\n// ==========================================\n\n/**\n * Request body for resolving package dependencies.\n *\n * @example POST /api/v1/packages/resolve-dependencies\n * { manifest: {...}, platformVersion: '3.2.0' }\n */\nexport const ResolveDependenciesRequestSchema = z.object({\n /** Package manifest whose dependencies to resolve */\n manifest: ManifestSchema.describe('Package manifest to resolve dependencies for'),\n\n /** Current platform version for compatibility checking */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility filtering'),\n}).describe('Resolve dependencies request');\nexport type ResolveDependenciesRequest = z.infer;\n\n/**\n * Response with dependency resolution results.\n */\nexport const ResolveDependenciesResponseSchema = BaseResponseSchema.extend({\n data: DependencyResolutionResultSchema.describe('Dependency resolution result with topological sort'),\n}).describe('Resolve dependencies response');\nexport type ResolveDependenciesResponse = z.infer;\n\n// ==========================================\n// 7. Upload Artifact (POST /api/v1/packages/upload)\n// ==========================================\n\n/**\n * Request body for uploading a package artifact.\n *\n * @example POST /api/v1/packages/upload\n * Content-Type: multipart/form-data\n * { artifact: , file: }\n */\nexport const UploadArtifactRequestSchema = z.object({\n /** Artifact metadata */\n artifact: PackageArtifactSchema.describe('Package artifact metadata'),\n\n /** SHA256 checksum of the uploaded file (for verification) */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).optional()\n .describe('SHA256 checksum of the uploaded file'),\n\n /** Publisher authentication token */\n token: z.string().optional()\n .describe('Publisher authentication token'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional()\n .describe('Release notes for this version'),\n}).describe('Upload artifact request');\nexport type UploadArtifactRequest = z.infer;\n\n/**\n * Response after uploading a package artifact.\n */\nexport const UploadArtifactResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n /** Whether the upload succeeded */\n success: z.boolean().describe('Whether the upload succeeded'),\n /** Artifact reference for the uploaded package */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference in the registry'),\n /** Submission ID for review tracking */\n submissionId: z.string().optional()\n .describe('Marketplace submission ID for review tracking'),\n /** Message */\n message: z.string().optional().describe('Upload status message'),\n }),\n}).describe('Upload artifact response');\nexport type UploadArtifactResponse = z.infer;\n\n// ==========================================\n// 8. Rollback Package (POST /api/v1/packages/:packageId/rollback)\n// ==========================================\n\n/**\n * Request body for rolling back a package upgrade.\n */\nexport const PackageRollbackRequestSchema = PackagePathParamsSchema.extend({\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\nexport type PackageRollbackRequest = z.infer;\n\n/**\n * Response after rolling back a package.\n */\nexport const PackageRollbackResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the rollback succeeded'),\n restoredVersion: z.string().optional().describe('Restored version'),\n message: z.string().optional().describe('Rollback status message'),\n }),\n}).describe('Rollback package response');\nexport type PackageRollbackResponse = z.infer;\n\n// ==========================================\n// 9. Uninstall Package (DELETE /api/v1/packages/:packageId)\n// ==========================================\n\n/**\n * Request for uninstalling a package.\n */\nexport const UninstallPackageApiRequestSchema = PackagePathParamsSchema;\nexport type UninstallPackageApiRequest = z.infer;\n\n/**\n * Response after uninstalling a package.\n */\nexport const UninstallPackageApiResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n packageId: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n }),\n}).describe('Uninstall package response');\nexport type UninstallPackageApiResponse = z.infer;\n\n// ==========================================\n// 10. Package API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Package operations.\n */\nexport const PackageApiErrorCode = z.enum([\n 'package_not_found',\n 'package_already_installed',\n 'version_not_found',\n 'dependency_conflict',\n 'namespace_conflict',\n 'platform_incompatible',\n 'artifact_invalid',\n 'checksum_mismatch',\n 'signature_invalid',\n 'upgrade_failed',\n 'rollback_failed',\n 'snapshot_not_found',\n 'upload_failed',\n]);\nexport type PackageApiErrorCode = z.infer;\n\n// ==========================================\n// 11. Package API Contract Registry\n// ==========================================\n\n/**\n * Standard Package API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const PackageApiContracts = {\n listPackages: {\n method: 'GET' as const,\n path: '/api/v1/packages',\n input: ListInstalledPackagesRequestSchema,\n output: ListInstalledPackagesResponseSchema,\n },\n getPackage: {\n method: 'GET' as const,\n path: '/api/v1/packages/:packageId',\n input: GetInstalledPackageRequestSchema,\n output: GetInstalledPackageResponseSchema,\n },\n installPackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/install',\n input: PackageInstallRequestSchema,\n output: PackageInstallResponseSchema,\n },\n upgradePackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/upgrade',\n input: PackageUpgradeRequestSchema,\n output: PackageUpgradeResponseSchema,\n },\n resolveDependencies: {\n method: 'POST' as const,\n path: '/api/v1/packages/resolve-dependencies',\n input: ResolveDependenciesRequestSchema,\n output: ResolveDependenciesResponseSchema,\n },\n uploadArtifact: {\n method: 'POST' as const,\n path: '/api/v1/packages/upload',\n input: UploadArtifactRequestSchema,\n output: UploadArtifactResponseSchema,\n },\n rollbackPackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/:packageId/rollback',\n input: PackageRollbackRequestSchema,\n output: PackageRollbackResponseSchema,\n },\n uninstallPackage: {\n method: 'DELETE' as const,\n path: '/api/v1/packages/:packageId',\n input: UninstallPackageApiRequestSchema,\n output: UninstallPackageApiResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n// Export Kernels\nexport { ObjectKernel } from '@objectstack/core';\n\n// Export Runtime\nexport { Runtime } from './runtime.js';\nexport type { RuntimeConfig } from './runtime.js';\n\n// Export Plugins\nexport { DriverPlugin } from './driver-plugin.js';\nexport { AppPlugin } from './app-plugin.js';\nexport { SeedLoaderService } from './seed-loader.js';\nexport { createDispatcherPlugin } from './dispatcher-plugin.js';\nexport type { DispatcherPluginConfig } from './dispatcher-plugin.js';\n\n// Export HTTP Server Components\nexport { HttpServer } from './http-server.js';\nexport { HttpDispatcher } from './http-dispatcher.js';\nexport type { HttpProtocolContext, HttpDispatcherResult } from './http-dispatcher.js';\nexport { MiddlewareManager } from './middleware.js';\n\n// Re-export from @objectstack/rest\nexport {\n RestServer,\n RouteManager,\n RouteGroupBuilder,\n createRestApiPlugin,\n} from '@objectstack/rest';\nexport type {\n RouteEntry,\n RestApiPluginConfig,\n} from '@objectstack/rest';\n\n// Export Types\nexport * from '@objectstack/core';\n\n\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectKernel, Plugin, IHttpServer, ObjectKernelConfig } from '@objectstack/core';\n\nexport interface RuntimeConfig {\n /**\n * Optional existing server instance (e.g. Hono, Express app)\n * If provided, Runtime will use it as the 'http.server' service.\n * If not provided, Runtime expects a server plugin (like HonoServerPlugin) to be registered manually.\n */\n server?: IHttpServer;\n\n /**\n * Kernel Configuration\n */\n kernel?: ObjectKernelConfig;\n}\n\n/**\n * ObjectStack Runtime\n * \n * High-level entry point for bootstrapping an ObjectStack application.\n * Wraps ObjectKernel and provides standard orchestration for:\n * - HTTP Server binding\n * - Plugin Management\n * \n * REST API is opt-in — register it explicitly:\n * ```ts\n * import { createRestApiPlugin } from '@objectstack/rest';\n * runtime.use(createRestApiPlugin());\n * ```\n */\nexport class Runtime {\n readonly kernel: ObjectKernel;\n \n constructor(config: RuntimeConfig = {}) {\n this.kernel = new ObjectKernel(config.kernel);\n \n // If external server provided, register it immediately\n if (config.server) {\n this.kernel.registerService('http.server', config.server);\n }\n }\n \n /**\n * Register a plugin\n */\n use(plugin: Plugin) {\n this.kernel.use(plugin);\n return this;\n }\n \n /**\n * Start the runtime\n * 1. Initializes all plugins (init phase)\n * 2. Starts all plugins (start phase)\n */\n async start() {\n await this.kernel.bootstrap();\n return this;\n }\n \n /**\n * Get the kernel instance\n */\n getKernel() {\n return this.kernel;\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from '@objectstack/core';\n\n/**\n * Driver Plugin\n * \n * Generic plugin wrapper for ObjectQL drivers.\n * Registers a driver with the ObjectQL engine.\n * \n * Dependencies: None (Registers service for ObjectQL to discover)\n * Services: driver.{name}\n * \n * @example\n * const memoryDriver = new InMemoryDriver();\n * const driverPlugin = new DriverPlugin(memoryDriver, 'memory');\n * kernel.use(driverPlugin);\n */\nexport class DriverPlugin implements Plugin {\n name: string;\n type = 'driver';\n version = '1.0.0';\n // dependencies = ['com.objectstack.engine.objectql']; // Removed: Driver is a producer, not strictly a consumer during init\n\n private driver: any;\n\n constructor(driver: any, driverName?: string) {\n this.driver = driver;\n this.name = `com.objectstack.driver.${driverName || driver.name || 'unknown'}`;\n }\n\n init = async (ctx: PluginContext) => {\n // Register driver as a service instead of directly to objectql\n const serviceName = `driver.${this.driver.name || 'unknown'}`;\n ctx.registerService(serviceName, this.driver);\n ctx.logger.info('Driver service registered', { \n serviceName, \n driverName: this.driver.name,\n driverVersion: this.driver.version \n });\n }\n\n start = async (ctx: PluginContext) => {\n // Drivers don't need start phase, initialization happens in init\n // Auto-configure alias for shorter access if it follows reverse domain standard\n if (this.name.startsWith('com.objectstack.driver.')) {\n // const shortName = this.name.split('.').pop();\n // Optional: ctx.registerService(`driver.${shortName}`, this.driver);\n }\n\n // Auto-configure 'default' datasource if none exists\n // We do this in 'start' phase to ensure metadata service is likely available\n try {\n const metadata = ctx.getService('metadata');\n if (metadata && metadata.addDatasource) {\n // Check if default datasource exists\n const datasources = metadata.getDatasources ? metadata.getDatasources() : [];\n const hasDefault = datasources.some((ds: any) => ds.name === 'default');\n\n if (!hasDefault) {\n ctx.logger.info(`[DriverPlugin] No 'default' datasource found. Auto-configuring '${this.driver.name}' as default.`);\n await metadata.addDatasource({\n name: 'default',\n driver: this.driver.name, // The driver's internal name (e.g. com.objectstack.driver.memory)\n });\n }\n }\n } catch (e) {\n // Metadata service might not be ready or available, which is fine\n // We just skip auto-configuration\n ctx.logger.debug('[DriverPlugin] Failed to auto-configure default datasource (Metadata service missing?)', { error: e });\n }\n\n ctx.logger.debug('Driver plugin started', { driverName: this.driver.name || 'unknown' });\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IDataEngine, IMetadataService, ISeedLoaderService } from '@objectstack/spec/contracts';\nimport type {\n SeedLoaderRequest,\n SeedLoaderResult,\n SeedLoaderConfig,\n SeedLoaderConfigInput,\n ObjectDependencyGraph,\n ObjectDependencyNode,\n ReferenceResolution,\n ReferenceResolutionError,\n DatasetLoadResult,\n Dataset,\n} from '@objectstack/spec/data';\nimport { SeedLoaderConfigSchema } from '@objectstack/spec/data';\n\ninterface Logger {\n info(message: string, meta?: Record): void;\n warn(message: string, meta?: Record): void;\n error(message: string, error?: Error, meta?: Record): void;\n debug(message: string, meta?: Record): void;\n}\n\n/** Default field used for externalId matching on target objects */\nconst DEFAULT_EXTERNAL_ID_FIELD = 'name';\n\n/**\n * SeedLoaderService — Runtime implementation of ISeedLoaderService\n *\n * Provides metadata-driven seed data loading with:\n * - Automatic lookup/master_detail reference resolution via externalId\n * - Topological dependency ordering (parents before children)\n * - Multi-pass loading for circular references\n * - Dry-run validation mode\n * - Upsert support honoring DatasetSchema mode\n * - Actionable error reporting\n */\nexport class SeedLoaderService implements ISeedLoaderService {\n private engine: IDataEngine;\n private metadata: IMetadataService;\n private logger: Logger;\n\n constructor(engine: IDataEngine, metadata: IMetadataService, logger: Logger) {\n this.engine = engine;\n this.metadata = metadata;\n this.logger = logger;\n }\n\n // ==========================================================================\n // Public API\n // ==========================================================================\n\n async load(request: SeedLoaderRequest): Promise {\n const startTime = Date.now();\n const config = request.config;\n const allErrors: ReferenceResolutionError[] = [];\n const allResults: DatasetLoadResult[] = [];\n\n // 1. Filter datasets by environment\n const datasets = this.filterByEnv(request.datasets, config.env);\n\n if (datasets.length === 0) {\n return this.buildEmptyResult(config, Date.now() - startTime);\n }\n\n // 2. Build dependency graph\n const objectNames = datasets.map(d => d.object);\n const graph = await this.buildDependencyGraph(objectNames);\n\n this.logger.info('[SeedLoader] Dependency graph built', {\n objects: objectNames.length,\n insertOrder: graph.insertOrder,\n circularDeps: graph.circularDependencies.length,\n });\n\n // 3. Order datasets by topological insert order\n const orderedDatasets = this.orderDatasets(datasets, graph.insertOrder);\n\n // 4. Build reference lookup map from metadata (field → target object)\n const refMap = this.buildReferenceMap(graph);\n\n // 5. Pass 1: Insert/upsert records, resolving references\n const insertedRecords = new Map>(); // object → externalIdValue → internalId\n const deferredUpdates: DeferredUpdate[] = [];\n\n for (const dataset of orderedDatasets) {\n const result = await this.loadDataset(\n dataset, config, refMap, insertedRecords, deferredUpdates, allErrors\n );\n allResults.push(result);\n\n if (config.haltOnError && result.errored > 0) {\n this.logger.warn('[SeedLoader] Halting on first error', { object: dataset.object });\n break;\n }\n }\n\n // 6. Pass 2: Resolve deferred references (circular dependencies)\n if (config.multiPass && deferredUpdates.length > 0 && !config.dryRun) {\n this.logger.info('[SeedLoader] Pass 2: resolving deferred references', {\n count: deferredUpdates.length,\n });\n await this.resolveDeferredUpdates(deferredUpdates, insertedRecords, allResults, allErrors);\n }\n\n // 7. Build final result\n const durationMs = Date.now() - startTime;\n return this.buildResult(config, graph, allResults, allErrors, durationMs);\n }\n\n async buildDependencyGraph(objectNames: string[]): Promise {\n const nodes: ObjectDependencyNode[] = [];\n const objectSet = new Set(objectNames);\n\n for (const objectName of objectNames) {\n const objDef = await this.metadata.getObject(objectName) as any;\n const dependsOn: string[] = [];\n const references: ReferenceResolution[] = [];\n\n if (objDef && objDef.fields) {\n const fields = objDef.fields as Record;\n for (const [fieldName, fieldDef] of Object.entries(fields)) {\n if (\n (fieldDef.type === 'lookup' || fieldDef.type === 'master_detail') &&\n fieldDef.reference\n ) {\n const targetObject = fieldDef.reference as string;\n\n // Track dependency ordering only for objects within the graph\n if (objectSet.has(targetObject) && !dependsOn.includes(targetObject)) {\n dependsOn.push(targetObject);\n }\n\n // Track ALL references for resolution (target may exist in database)\n references.push({\n field: fieldName,\n targetObject,\n targetField: DEFAULT_EXTERNAL_ID_FIELD,\n fieldType: fieldDef.type as 'lookup' | 'master_detail',\n });\n }\n }\n }\n\n nodes.push({ object: objectName, dependsOn, references });\n }\n\n // Topological sort\n const { insertOrder, circularDependencies } = this.topologicalSort(nodes);\n\n return { nodes, insertOrder, circularDependencies };\n }\n\n async validate(datasets: Dataset[], config?: SeedLoaderConfigInput): Promise {\n const parsedConfig = SeedLoaderConfigSchema.parse({ ...config, dryRun: true });\n return this.load({ datasets, config: parsedConfig });\n }\n\n // ==========================================================================\n // Internal: Dataset Loading\n // ==========================================================================\n\n private async loadDataset(\n dataset: Dataset,\n config: SeedLoaderConfig,\n refMap: Map,\n insertedRecords: Map>,\n deferredUpdates: DeferredUpdate[],\n allErrors: ReferenceResolutionError[],\n ): Promise {\n const objectName = dataset.object;\n const mode = dataset.mode || config.defaultMode;\n const externalId = dataset.externalId || 'name';\n\n let inserted = 0;\n let updated = 0;\n let skipped = 0;\n let errored = 0;\n let referencesResolved = 0;\n let referencesDeferred = 0;\n const errors: ReferenceResolutionError[] = [];\n\n // Ensure the object's record map exists\n if (!insertedRecords.has(objectName)) {\n insertedRecords.set(objectName, new Map());\n }\n\n // Pre-load existing records for upsert matching\n let existingRecords: Map | undefined;\n if ((mode === 'upsert' || mode === 'update' || mode === 'ignore') && !config.dryRun) {\n existingRecords = await this.loadExistingRecords(objectName, externalId);\n }\n\n // Get reference resolutions for this object\n const objectRefs = refMap.get(objectName) || [];\n\n for (let i = 0; i < dataset.records.length; i++) {\n const record = { ...dataset.records[i] }; // Clone to avoid mutation\n\n // Resolve references\n for (const ref of objectRefs) {\n const fieldValue = record[ref.field];\n if (fieldValue === undefined || fieldValue === null) continue;\n\n // Skip if value looks like an internal ID (not a natural key)\n if (typeof fieldValue !== 'string' || this.looksLikeInternalId(fieldValue)) continue;\n\n // Try to resolve via already-inserted records\n const targetMap = insertedRecords.get(ref.targetObject);\n const resolvedId = targetMap?.get(String(fieldValue));\n\n if (resolvedId) {\n record[ref.field] = resolvedId;\n referencesResolved++;\n } else if (!config.dryRun) {\n // Try to resolve from existing data in the database\n const dbId = await this.resolveFromDatabase(ref.targetObject, ref.targetField, fieldValue);\n if (dbId) {\n record[ref.field] = dbId;\n referencesResolved++;\n } else if (config.multiPass) {\n // Defer to pass 2\n record[ref.field] = null;\n deferredUpdates.push({\n objectName,\n recordExternalId: String(record[externalId] ?? ''),\n field: ref.field,\n targetObject: ref.targetObject,\n targetField: ref.targetField,\n attemptedValue: fieldValue,\n recordIndex: i,\n });\n referencesDeferred++;\n } else {\n // Cannot resolve - record error\n const error: ReferenceResolutionError = {\n sourceObject: objectName,\n field: ref.field,\n targetObject: ref.targetObject,\n targetField: ref.targetField,\n attemptedValue: fieldValue,\n recordIndex: i,\n message: `Cannot resolve reference: ${objectName}.${ref.field} = '${fieldValue}' → ${ref.targetObject}.${ref.targetField} not found`,\n };\n errors.push(error);\n allErrors.push(error);\n }\n } else {\n // Dry-run: attempt resolution, report error if not found\n const targetMap2 = insertedRecords.get(ref.targetObject);\n if (!targetMap2?.has(String(fieldValue))) {\n const error: ReferenceResolutionError = {\n sourceObject: objectName,\n field: ref.field,\n targetObject: ref.targetObject,\n targetField: ref.targetField,\n attemptedValue: fieldValue,\n recordIndex: i,\n message: `[dry-run] Reference may not resolve: ${objectName}.${ref.field} = '${fieldValue}' → ${ref.targetObject}.${ref.targetField}`,\n };\n errors.push(error);\n allErrors.push(error);\n }\n }\n }\n\n // Insert/upsert the record\n if (!config.dryRun) {\n try {\n const result = await this.writeRecord(\n objectName, record, mode, externalId, existingRecords\n );\n\n if (result.action === 'inserted') inserted++;\n else if (result.action === 'updated') updated++;\n else if (result.action === 'skipped') skipped++;\n\n // Track the inserted/updated record's ID for reference resolution\n const externalIdValue = String(record[externalId] ?? '');\n const internalId = result.id;\n if (externalIdValue && internalId) {\n insertedRecords.get(objectName)!.set(externalIdValue, String(internalId));\n }\n } catch (err: any) {\n errored++;\n this.logger.warn(`[SeedLoader] Failed to write ${objectName} record`, {\n error: err.message,\n recordIndex: i,\n });\n }\n } else {\n // Dry-run: simulate insert tracking\n const externalIdValue = String(record[externalId] ?? '');\n if (externalIdValue) {\n insertedRecords.get(objectName)!.set(externalIdValue, `dry-run-id-${i}`);\n }\n inserted++; // Count as \"would be inserted\"\n }\n }\n\n return {\n object: objectName,\n mode,\n inserted,\n updated,\n skipped,\n errored,\n total: dataset.records.length,\n referencesResolved,\n referencesDeferred,\n errors,\n };\n }\n\n // ==========================================================================\n // Internal: Reference Resolution\n // ==========================================================================\n\n private async resolveFromDatabase(\n targetObject: string,\n targetField: string,\n value: unknown,\n ): Promise {\n try {\n const records = await this.engine.find(targetObject, {\n where: { [targetField]: value },\n fields: ['id'],\n limit: 1,\n });\n if (records && records.length > 0) {\n return String(records[0].id || records[0]._id);\n }\n } catch {\n // Target object may not exist yet\n }\n return null;\n }\n\n private async resolveDeferredUpdates(\n deferredUpdates: DeferredUpdate[],\n insertedRecords: Map>,\n allResults: DatasetLoadResult[],\n allErrors: ReferenceResolutionError[],\n ): Promise {\n for (const deferred of deferredUpdates) {\n // Try to resolve from inserted records\n const targetMap = insertedRecords.get(deferred.targetObject);\n let resolvedId = targetMap?.get(String(deferred.attemptedValue));\n\n // Try database fallback\n if (!resolvedId) {\n resolvedId = (await this.resolveFromDatabase(\n deferred.targetObject, deferred.targetField, deferred.attemptedValue\n )) ?? undefined;\n }\n\n if (resolvedId) {\n // Find the record and update the reference\n const objectRecordMap = insertedRecords.get(deferred.objectName);\n const recordId = objectRecordMap?.get(deferred.recordExternalId);\n\n if (recordId) {\n try {\n await this.engine.update(deferred.objectName, {\n id: recordId,\n [deferred.field]: resolvedId,\n });\n\n // Update result stats\n const resultEntry = allResults.find(r => r.object === deferred.objectName);\n if (resultEntry) {\n resultEntry.referencesResolved++;\n resultEntry.referencesDeferred--;\n }\n } catch (err: any) {\n this.logger.warn('[SeedLoader] Failed to resolve deferred reference', {\n object: deferred.objectName,\n field: deferred.field,\n error: err.message,\n });\n }\n }\n } else {\n // Still unresolved after pass 2\n const error: ReferenceResolutionError = {\n sourceObject: deferred.objectName,\n field: deferred.field,\n targetObject: deferred.targetObject,\n targetField: deferred.targetField,\n attemptedValue: deferred.attemptedValue,\n recordIndex: deferred.recordIndex,\n message: `Deferred reference unresolved after pass 2: ${deferred.objectName}.${deferred.field} = '${deferred.attemptedValue}' → ${deferred.targetObject}.${deferred.targetField} not found`,\n };\n\n const resultEntry = allResults.find(r => r.object === deferred.objectName);\n if (resultEntry) {\n resultEntry.errors.push(error);\n }\n allErrors.push(error);\n }\n }\n }\n\n // ==========================================================================\n // Internal: Write Operations\n // ==========================================================================\n\n private async writeRecord(\n objectName: string,\n record: Record,\n mode: string,\n externalId: string,\n existingRecords?: Map,\n ): Promise<{ action: 'inserted' | 'updated' | 'skipped'; id?: string }> {\n const externalIdValue = record[externalId];\n const existing = existingRecords?.get(String(externalIdValue ?? ''));\n\n switch (mode) {\n case 'insert': {\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n\n case 'update': {\n if (!existing) {\n return { action: 'skipped' };\n }\n const id = this.extractId(existing);\n await this.engine.update(objectName, { ...record, id });\n return { action: 'updated', id };\n }\n\n case 'upsert': {\n if (existing) {\n const id = this.extractId(existing);\n await this.engine.update(objectName, { ...record, id });\n return { action: 'updated', id };\n } else {\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n }\n\n case 'ignore': {\n if (existing) {\n return { action: 'skipped', id: this.extractId(existing) };\n }\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n\n case 'replace': {\n // Replace mode: just insert (caller should have cleared the table)\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n\n default: {\n const result = await this.engine.insert(objectName, record);\n return { action: 'inserted', id: this.extractId(result) };\n }\n }\n }\n\n // ==========================================================================\n // Internal: Dependency Graph\n // ==========================================================================\n\n /**\n * Kahn's algorithm for topological sort with cycle detection.\n */\n private topologicalSort(\n nodes: ObjectDependencyNode[],\n ): { insertOrder: string[]; circularDependencies: string[][] } {\n const inDegree = new Map();\n const adjacency = new Map();\n const objectSet = new Set(nodes.map(n => n.object));\n\n // Initialize\n for (const node of nodes) {\n inDegree.set(node.object, 0);\n adjacency.set(node.object, []);\n }\n\n // Build adjacency list and in-degree counts\n for (const node of nodes) {\n for (const dep of node.dependsOn) {\n // Exclude self-references from ordering (e.g., employee.manager_id → employee).\n // Self-referencing fields are still tracked in node.references for resolution.\n if (objectSet.has(dep) && dep !== node.object) {\n adjacency.get(dep)!.push(node.object);\n inDegree.set(node.object, (inDegree.get(node.object) || 0) + 1);\n }\n }\n }\n\n // Kahn's algorithm\n const queue: string[] = [];\n for (const [obj, degree] of inDegree) {\n if (degree === 0) queue.push(obj);\n }\n\n const insertOrder: string[] = [];\n while (queue.length > 0) {\n const current = queue.shift()!;\n insertOrder.push(current);\n\n for (const neighbor of (adjacency.get(current) || [])) {\n const newDegree = (inDegree.get(neighbor) || 0) - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) {\n queue.push(neighbor);\n }\n }\n }\n\n // Detect circular dependencies\n const circularDependencies: string[][] = [];\n const remaining = nodes.filter(n => !insertOrder.includes(n.object));\n\n if (remaining.length > 0) {\n // Find cycles using DFS\n const cycles = this.findCycles(remaining);\n circularDependencies.push(...cycles);\n\n // Add remaining objects to insertOrder (they'll need multi-pass)\n for (const node of remaining) {\n if (!insertOrder.includes(node.object)) {\n insertOrder.push(node.object);\n }\n }\n }\n\n return { insertOrder, circularDependencies };\n }\n\n private findCycles(nodes: ObjectDependencyNode[]): string[][] {\n const cycles: string[][] = [];\n const nodeMap = new Map(nodes.map(n => [n.object, n]));\n const visited = new Set();\n const inStack = new Set();\n\n const dfs = (current: string, path: string[]) => {\n if (inStack.has(current)) {\n // Found a cycle\n const cycleStart = path.indexOf(current);\n if (cycleStart !== -1) {\n cycles.push([...path.slice(cycleStart), current]);\n }\n return;\n }\n if (visited.has(current)) return;\n\n visited.add(current);\n inStack.add(current);\n path.push(current);\n\n const node = nodeMap.get(current);\n if (node) {\n for (const dep of node.dependsOn) {\n if (nodeMap.has(dep)) {\n dfs(dep, [...path]);\n }\n }\n }\n\n inStack.delete(current);\n };\n\n for (const node of nodes) {\n if (!visited.has(node.object)) {\n dfs(node.object, []);\n }\n }\n\n return cycles;\n }\n\n // ==========================================================================\n // Internal: Helpers\n // ==========================================================================\n\n private filterByEnv(datasets: Dataset[], env?: string): Dataset[] {\n if (!env) return datasets;\n return datasets.filter(d => (d.env as string[]).includes(env));\n }\n\n private orderDatasets(datasets: Dataset[], insertOrder: string[]): Dataset[] {\n const orderMap = new Map(insertOrder.map((name, i) => [name, i]));\n return [...datasets].sort((a, b) => {\n const orderA = orderMap.get(a.object) ?? Number.MAX_SAFE_INTEGER;\n const orderB = orderMap.get(b.object) ?? Number.MAX_SAFE_INTEGER;\n return orderA - orderB;\n });\n }\n\n private buildReferenceMap(graph: ObjectDependencyGraph): Map {\n const map = new Map();\n for (const node of graph.nodes) {\n if (node.references.length > 0) {\n map.set(node.object, node.references);\n }\n }\n return map;\n }\n\n private async loadExistingRecords(\n objectName: string,\n externalId: string,\n ): Promise> {\n const map = new Map();\n try {\n const records = await this.engine.find(objectName, {\n fields: ['id', externalId],\n });\n for (const record of records || []) {\n const key = String(record[externalId] ?? '');\n if (key) {\n map.set(key, record);\n }\n }\n } catch {\n // Object may not have records yet\n }\n return map;\n }\n\n private looksLikeInternalId(value: string): boolean {\n // UUID v4 pattern\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {\n return true;\n }\n // MongoDB ObjectId pattern (24 hex chars)\n if (/^[0-9a-f]{24}$/i.test(value)) {\n return true;\n }\n return false;\n }\n\n private extractId(record: any): string | undefined {\n if (!record) return undefined;\n return String(record.id || record._id || '');\n }\n\n private buildEmptyResult(config: SeedLoaderConfig, durationMs: number): SeedLoaderResult {\n return {\n success: true,\n dryRun: config.dryRun,\n dependencyGraph: { nodes: [], insertOrder: [], circularDependencies: [] },\n results: [],\n errors: [],\n summary: {\n objectsProcessed: 0,\n totalRecords: 0,\n totalInserted: 0,\n totalUpdated: 0,\n totalSkipped: 0,\n totalErrored: 0,\n totalReferencesResolved: 0,\n totalReferencesDeferred: 0,\n circularDependencyCount: 0,\n durationMs,\n },\n };\n }\n\n private buildResult(\n config: SeedLoaderConfig,\n graph: ObjectDependencyGraph,\n results: DatasetLoadResult[],\n errors: ReferenceResolutionError[],\n durationMs: number,\n ): SeedLoaderResult {\n const summary = {\n objectsProcessed: results.length,\n totalRecords: results.reduce((sum, r) => sum + r.total, 0),\n totalInserted: results.reduce((sum, r) => sum + r.inserted, 0),\n totalUpdated: results.reduce((sum, r) => sum + r.updated, 0),\n totalSkipped: results.reduce((sum, r) => sum + r.skipped, 0),\n totalErrored: results.reduce((sum, r) => sum + r.errored, 0),\n totalReferencesResolved: results.reduce((sum, r) => sum + r.referencesResolved, 0),\n totalReferencesDeferred: results.reduce((sum, r) => sum + r.referencesDeferred, 0),\n circularDependencyCount: graph.circularDependencies.length,\n durationMs,\n };\n\n const hasErrors = errors.length > 0 || summary.totalErrored > 0;\n\n return {\n success: !hasErrors,\n dryRun: config.dryRun,\n dependencyGraph: graph,\n results,\n errors,\n summary,\n };\n }\n}\n\n// ==========================================================================\n// Internal Types\n// ==========================================================================\n\ninterface DeferredUpdate {\n objectName: string;\n recordExternalId: string;\n field: string;\n targetObject: string;\n targetField: string;\n attemptedValue: unknown;\n recordIndex: number;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from '@objectstack/core';\nimport { SeedLoaderService } from './seed-loader.js';\nimport type { IMetadataService, II18nService } from '@objectstack/spec/contracts';\n\n/**\n * AppPlugin\n * \n * Adapts a generic App Bundle (Manifest + Runtime Code) into a Kernel Plugin.\n * \n * Responsibilities:\n * 1. Register App Manifest as a service (for ObjectQL discovery)\n * 2. Execute Runtime `onEnable` hook (for code logic)\n * 3. Auto-load i18n translation bundles into the kernel's i18n service\n */\nexport class AppPlugin implements Plugin {\n name: string;\n type = 'app';\n version?: string;\n \n private bundle: any;\n\n constructor(bundle: any) {\n this.bundle = bundle;\n // Support both direct manifest (legacy) and Stack Definition (nested manifest)\n const sys = bundle.manifest || bundle;\n const appId = sys.id || sys.name || 'unnamed-app';\n \n this.name = `plugin.app.${appId}`;\n this.version = sys.version;\n }\n\n init = async (ctx: PluginContext) => {\n const sys = this.bundle.manifest || this.bundle;\n const appId = sys.id || sys.name;\n\n ctx.logger.info('Registering App Service', { \n appId, \n pluginName: this.name,\n version: this.version \n });\n \n // Register the app manifest directly via the manifest service.\n // This immediately decomposes the manifest into SchemaRegistry entries.\n const servicePayload = this.bundle.manifest\n ? { ...this.bundle.manifest, ...this.bundle }\n : this.bundle;\n\n ctx.getService<{ register(m: any): void }>('manifest').register(servicePayload);\n }\n\n start = async (ctx: PluginContext) => {\n const sys = this.bundle.manifest || this.bundle;\n const appId = sys.id || sys.name;\n \n // Execute Runtime Step\n // Retrieve ObjectQL engine from services\n // ctx.getService throws when a service is not registered, so we\n // must use try/catch instead of a null-check.\n let ql: any;\n try {\n ql = ctx.getService('objectql');\n } catch {\n // Service not registered — handled below\n }\n\n if (!ql) {\n ctx.logger.warn('ObjectQL engine service not found', { \n appName: this.name,\n appId \n });\n return;\n }\n\n ctx.logger.debug('Retrieved ObjectQL engine service', { appId });\n\n const runtime = this.bundle.default || this.bundle;\n \n if (runtime && typeof runtime.onEnable === 'function') {\n ctx.logger.info('Executing runtime.onEnable', { \n appName: this.name,\n appId \n });\n \n // Construct the Host Context (mirroring old ObjectQL.use logic)\n const hostContext = {\n ...ctx,\n ql,\n logger: ctx.logger,\n drivers: {\n register: (driver: any) => {\n ctx.logger.debug('Registering driver via app runtime', { \n driverName: driver.name,\n appId \n });\n ql.registerDriver(driver);\n }\n },\n };\n \n await runtime.onEnable(hostContext);\n ctx.logger.debug('Runtime.onEnable completed', { appId });\n } else {\n ctx.logger.debug('No runtime.onEnable function found', { appId });\n }\n\n // ── i18n Translation Loading ─────────────────────────────────────\n // Auto-load translation bundles from the app config into the\n // kernel's i18n service, so discovery and handlers stay consistent.\n this.loadTranslations(ctx, appId);\n\n // Data Seeding\n // Collect seed data from multiple locations (top-level `data` preferred, `manifest.data` for backward compat)\n const seedDatasets: any[] = [];\n \n // 1. Top-level `data` field (new standard location on ObjectStackDefinition)\n if (Array.isArray(this.bundle.data)) {\n seedDatasets.push(...this.bundle.data);\n }\n \n // 2. Legacy: `manifest.data` (backward compatibility)\n const manifest = this.bundle.manifest || this.bundle;\n if (manifest && Array.isArray(manifest.data)) {\n seedDatasets.push(...manifest.data);\n }\n\n // Resolve short object names to FQN using the package's namespace.\n // e.g., seed `object: 'task'` in namespace 'todo' → 'todo__task'\n // Reserved namespaces ('base', 'system') are not prefixed.\n const namespace = (this.bundle.manifest || this.bundle)?.namespace as string | undefined;\n const RESERVED_NS = new Set(['base', 'system']);\n const toFQN = (name: string) => {\n if (name.includes('__') || !namespace || RESERVED_NS.has(namespace)) return name;\n return `${namespace}__${name}`;\n };\n \n if (seedDatasets.length > 0) {\n ctx.logger.info(`[AppPlugin] Found ${seedDatasets.length} seed datasets for ${appId}`);\n\n // Normalize dataset object names to FQN\n const normalizedDatasets = seedDatasets\n .filter((d: any) => d.object && Array.isArray(d.records))\n .map((d: any) => ({\n ...d,\n object: toFQN(d.object),\n }));\n\n // Use SeedLoaderService for metadata-driven loading with reference resolution\n try {\n const metadata = ctx.getService('metadata') as IMetadataService | undefined;\n if (metadata) {\n const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger);\n const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data');\n const request = SeedLoaderRequestSchema.parse({\n datasets: normalizedDatasets,\n config: { defaultMode: 'upsert', multiPass: true },\n });\n const result = await seedLoader.load(request);\n ctx.logger.info('[Seeder] Seed loading complete', {\n inserted: result.summary.totalInserted,\n updated: result.summary.totalUpdated,\n errors: result.errors.length,\n });\n } else {\n // Fallback: basic insert when metadata service is not available\n ctx.logger.debug('[Seeder] No metadata service; using basic insert fallback');\n for (const dataset of normalizedDatasets) {\n ctx.logger.info(`[Seeder] Seeding ${dataset.records.length} records for ${dataset.object}`);\n for (const record of dataset.records) {\n try {\n await ql.insert(dataset.object, record);\n } catch (err: any) {\n ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: err.message });\n }\n }\n }\n ctx.logger.info('[Seeder] Data seeding complete.');\n }\n } catch (err: any) {\n // If SeedLoaderService fails (e.g., metadata not available), fall back to basic insert\n ctx.logger.warn('[Seeder] SeedLoaderService failed, falling back to basic insert', { error: err.message });\n for (const dataset of normalizedDatasets) {\n for (const record of dataset.records) {\n try {\n await ql.insert(dataset.object, record);\n } catch (insertErr: any) {\n ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: insertErr.message });\n }\n }\n }\n ctx.logger.info('[Seeder] Data seeding complete (fallback).');\n }\n }\n }\n\n /**\n * Auto-load i18n translation bundles from the app config into the\n * kernel's i18n service. Handles both `translations` (array of\n * TranslationBundle) and `i18n` config (default locale, etc.).\n *\n * Gracefully skips when the i18n service is not registered —\n * this keeps AppPlugin resilient across server/dev/mock environments.\n */\n private loadTranslations(ctx: PluginContext, appId: string): void {\n // ctx.getService throws when a service is not registered, so we\n // must use try/catch to gracefully skip when no i18n plugin is loaded.\n let i18nService: II18nService | undefined;\n try {\n i18nService = ctx.getService('i18n') as II18nService;\n } catch {\n // Service not registered — handled below\n }\n\n // Collect translation bundles early to determine if we have data\n const bundles: Array> = [];\n if (Array.isArray(this.bundle.translations)) {\n bundles.push(...this.bundle.translations);\n }\n const manifest = this.bundle.manifest || this.bundle;\n if (manifest && Array.isArray(manifest.translations) && manifest.translations !== this.bundle.translations) {\n bundles.push(...manifest.translations);\n }\n\n if (!i18nService) {\n if (bundles.length > 0) {\n ctx.logger.warn(\n `[i18n] App \"${appId}\" has ${bundles.length} translation bundle(s) but no i18n service is registered. ` +\n 'Translations will not be served via REST API. ' +\n 'Register I18nServicePlugin from @objectstack/service-i18n, or use DevPlugin ' +\n 'which auto-detects translations and registers the i18n service automatically.'\n );\n } else {\n ctx.logger.debug('[i18n] No i18n service registered; skipping translation loading', { appId });\n }\n return;\n }\n\n // Apply i18n config (default locale, etc.)\n const i18nConfig = this.bundle.i18n || (this.bundle.manifest || this.bundle)?.i18n;\n if (i18nConfig?.defaultLocale && typeof i18nService.setDefaultLocale === 'function') {\n i18nService.setDefaultLocale(i18nConfig.defaultLocale);\n ctx.logger.debug('[i18n] Set default locale', { appId, locale: i18nConfig.defaultLocale });\n }\n\n if (bundles.length === 0) {\n return;\n }\n\n let loadedLocales = 0;\n for (const bundle of bundles) {\n // Each bundle is a TranslationBundle: Record\n for (const [locale, data] of Object.entries(bundle)) {\n if (data && typeof data === 'object') {\n try {\n i18nService.loadTranslations(locale, data as Record);\n loadedLocales++;\n } catch (err: any) {\n ctx.logger.warn('[i18n] Failed to load translations', { appId, locale, error: err.message });\n }\n }\n }\n }\n\n // Emit diagnostic when the active i18n service is a fallback/stub\n const svcAny = i18nService as unknown as Record;\n if (svcAny._fallback || svcAny._dev) {\n ctx.logger.info(\n `[i18n] Loaded ${loadedLocales} locale(s) into in-memory i18n fallback for \"${appId}\". ` +\n 'For production, consider registering I18nServicePlugin from @objectstack/service-i18n.'\n );\n } else {\n ctx.logger.info('[i18n] Loaded translation bundles', { appId, bundles: bundles.length, locales: loadedLocales });\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectKernel, getEnv, resolveLocale } from '@objectstack/core';\nimport { CoreServiceName } from '@objectstack/spec/system';\nimport { pluralToSingular } from '@objectstack/spec/shared';\n\n/** Browser-safe UUID generator — prefers Web Crypto, falls back to RFC 4122 v4 */\nfunction randomUUID(): string {\n if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\nexport interface HttpProtocolContext {\n request: any;\n response?: any;\n}\n\nexport interface HttpDispatcherResult {\n handled: boolean;\n response?: {\n status: number;\n body?: any;\n headers?: Record;\n };\n result?: any; // For flexible return types or direct response objects (Response/NextResponse)\n}\n\n/**\n * @deprecated Use `createDispatcherPlugin()` from `@objectstack/runtime` instead.\n * This class will be removed in v2. Prefer the plugin-based approach:\n * ```ts\n * import { createDispatcherPlugin } from '@objectstack/runtime';\n * kernel.use(createDispatcherPlugin({ prefix: '/api/v1' }));\n * ```\n */\nexport class HttpDispatcher {\n private kernel: any; // Casting to any to access dynamic props like broker, services, graphql\n\n constructor(kernel: ObjectKernel) {\n this.kernel = kernel;\n }\n\n private success(data: any, meta?: any) {\n return {\n status: 200,\n body: { success: true, data, meta }\n };\n }\n\n private error(message: string, code: number = 500, details?: any) {\n return {\n status: code,\n body: { success: false, error: { message, code, details } }\n };\n }\n\n /**\n * 404 Route Not Found — no route is registered for this path.\n */\n private routeNotFound(route: string) {\n return {\n status: 404,\n body: {\n success: false,\n error: {\n code: 404,\n message: `Route Not Found: ${route}`,\n type: 'ROUTE_NOT_FOUND' as const,\n route,\n hint: 'No route is registered for this path. Check the API discovery endpoint for available routes.',\n },\n },\n };\n }\n\n private ensureBroker() {\n if (!this.kernel.broker) {\n throw { statusCode: 500, message: 'Kernel Broker not available' };\n }\n return this.kernel.broker;\n }\n\n /**\n * Generates the discovery JSON response for the API root.\n *\n * Uses the same async `resolveService()` fallback chain that request\n * handlers use, so the reported service status is always consistent\n * with the actual runtime availability.\n */\n async getDiscoveryInfo(prefix: string) {\n // Resolve all services through the same async fallback chain\n // that request handlers (handleI18n, handleAuth, …) use.\n const [\n authSvc, graphqlSvc, searchSvc, realtimeSvc, filesSvc,\n analyticsSvc, workflowSvc, aiSvc, notificationSvc, i18nSvc,\n uiSvc, automationSvc, cacheSvc, queueSvc, jobSvc,\n ] = await Promise.all([\n this.resolveService(CoreServiceName.enum.auth),\n this.resolveService(CoreServiceName.enum.graphql),\n this.resolveService(CoreServiceName.enum.search),\n this.resolveService(CoreServiceName.enum.realtime),\n this.resolveService(CoreServiceName.enum['file-storage']),\n this.resolveService(CoreServiceName.enum.analytics),\n this.resolveService(CoreServiceName.enum.workflow),\n this.resolveService(CoreServiceName.enum.ai),\n this.resolveService(CoreServiceName.enum.notification),\n this.resolveService(CoreServiceName.enum.i18n),\n this.resolveService(CoreServiceName.enum.ui),\n this.resolveService(CoreServiceName.enum.automation),\n this.resolveService(CoreServiceName.enum.cache),\n this.resolveService(CoreServiceName.enum.queue),\n this.resolveService(CoreServiceName.enum.job),\n ]);\n\n const hasAuth = !!authSvc;\n const hasGraphQL = !!(graphqlSvc || this.kernel.graphql);\n const hasSearch = !!searchSvc;\n const hasWebSockets = !!realtimeSvc;\n const hasFiles = !!filesSvc;\n const hasAnalytics = !!analyticsSvc;\n const hasWorkflow = !!workflowSvc;\n const hasAi = !!aiSvc;\n const hasNotification = !!notificationSvc;\n const hasI18n = !!i18nSvc;\n const hasUi = !!uiSvc;\n const hasAutomation = !!automationSvc;\n const hasCache = !!cacheSvc;\n const hasQueue = !!queueSvc;\n const hasJob = !!jobSvc;\n\n // Routes are only exposed when a plugin provides the service\n const routes = {\n data: `${prefix}/data`,\n metadata: `${prefix}/meta`,\n packages: `${prefix}/packages`,\n auth: hasAuth ? `${prefix}/auth` : undefined,\n ui: hasUi ? `${prefix}/ui` : undefined,\n graphql: hasGraphQL ? `${prefix}/graphql` : undefined,\n storage: hasFiles ? `${prefix}/storage` : undefined,\n analytics: hasAnalytics ? `${prefix}/analytics` : undefined,\n automation: hasAutomation ? `${prefix}/automation` : undefined,\n workflow: hasWorkflow ? `${prefix}/workflow` : undefined,\n realtime: hasWebSockets ? `${prefix}/realtime` : undefined,\n notifications: hasNotification ? `${prefix}/notifications` : undefined,\n ai: hasAi ? `${prefix}/ai` : undefined,\n i18n: hasI18n ? `${prefix}/i18n` : undefined,\n };\n\n // Build per-service status map\n // handlerReady: true means the dispatcher has a real, bound handler for this route.\n // handlerReady: false means the route is present in the discovery table but may not\n // yet have a concrete implementation or may be served by a stub.\n const svcAvailable = (route?: string, provider?: string) => ({\n enabled: true, status: 'available' as const, handlerReady: true, route, provider,\n });\n const svcUnavailable = (name: string) => ({\n enabled: false, status: 'unavailable' as const, handlerReady: false,\n message: `Install a ${name} plugin to enable`,\n });\n\n // Derive locale info from actual i18n service when available\n let locale = { default: 'en', supported: ['en'], timezone: 'UTC' };\n if (hasI18n && i18nSvc) {\n const defaultLocale = typeof i18nSvc.getDefaultLocale === 'function'\n ? i18nSvc.getDefaultLocale() : 'en';\n const locales = typeof i18nSvc.getLocales === 'function'\n ? i18nSvc.getLocales() : [];\n locale = {\n default: defaultLocale,\n supported: locales.length > 0 ? locales : [defaultLocale],\n timezone: 'UTC',\n };\n }\n\n return {\n name: 'ObjectOS',\n version: '1.0.0',\n environment: getEnv('NODE_ENV', 'development'),\n routes,\n endpoints: routes, // Alias for backward compatibility with some clients\n features: {\n graphql: hasGraphQL,\n search: hasSearch,\n websockets: hasWebSockets,\n files: hasFiles,\n analytics: hasAnalytics,\n ai: hasAi,\n workflow: hasWorkflow,\n notifications: hasNotification,\n i18n: hasI18n,\n },\n services: {\n // Kernel-provided (always available via protocol implementation)\n metadata: { enabled: true, status: 'degraded' as const, handlerReady: true, route: routes.metadata, provider: 'kernel', message: 'In-memory registry; DB persistence pending' },\n data: svcAvailable(routes.data, 'kernel'),\n // Plugin-provided — only available when a plugin registers the service\n auth: hasAuth ? svcAvailable(routes.auth) : svcUnavailable('auth'),\n automation: hasAutomation ? svcAvailable(routes.automation) : svcUnavailable('automation'),\n analytics: hasAnalytics ? svcAvailable(routes.analytics) : svcUnavailable('analytics'),\n cache: hasCache ? svcAvailable() : svcUnavailable('cache'),\n queue: hasQueue ? svcAvailable() : svcUnavailable('queue'),\n job: hasJob ? svcAvailable() : svcUnavailable('job'),\n ui: hasUi ? svcAvailable(routes.ui) : svcUnavailable('ui'),\n workflow: hasWorkflow ? svcAvailable(routes.workflow) : svcUnavailable('workflow'),\n realtime: hasWebSockets ? svcAvailable(routes.realtime) : svcUnavailable('realtime'),\n notification: hasNotification ? svcAvailable(routes.notifications) : svcUnavailable('notification'),\n ai: hasAi ? svcAvailable(routes.ai) : svcUnavailable('ai'),\n i18n: hasI18n ? svcAvailable(routes.i18n) : svcUnavailable('i18n'),\n graphql: hasGraphQL ? svcAvailable(routes.graphql) : svcUnavailable('graphql'),\n 'file-storage': hasFiles ? svcAvailable(routes.storage) : svcUnavailable('file-storage'),\n search: hasSearch ? svcAvailable() : svcUnavailable('search'),\n },\n locale,\n };\n }\n\n /**\n * Handles GraphQL requests\n */\n async handleGraphQL(body: { query: string; variables?: any }, context: HttpProtocolContext) {\n if (!body || !body.query) {\n throw { statusCode: 400, message: 'Missing query in request body' };\n }\n \n if (typeof this.kernel.graphql !== 'function') {\n throw { statusCode: 501, message: 'GraphQL service not available' };\n }\n\n return this.kernel.graphql(body.query, body.variables, { \n request: context.request \n });\n }\n\n /**\n * Handles Auth requests\n * path: sub-path after /auth/\n */\n async handleAuth(path: string, method: string, body: any, context: HttpProtocolContext): Promise {\n // 1. Try generic Auth Service\n const authService = await this.getService(CoreServiceName.enum.auth);\n if (authService && typeof authService.handler === 'function') {\n const response = await authService.handler(context.request, context.response);\n return { handled: true, result: response };\n }\n\n // 2. Legacy Login via broker\n const normalizedPath = path.replace(/^\\/+/, '');\n if (normalizedPath === 'login' && method.toUpperCase() === 'POST') {\n try {\n const broker = this.ensureBroker();\n const data = await broker.call('auth.login', body, { request: context.request });\n return { handled: true, response: { status: 200, body: data } };\n } catch (error: any) {\n // Only fall through to mock when the broker is truly unavailable\n // (ensureBroker throws statusCode 500 when kernel.broker is null)\n const statusCode = error?.statusCode ?? error?.status;\n if (statusCode !== 500 || !error?.message?.includes('Broker not available')) {\n throw error;\n }\n }\n }\n\n // 3. Mock fallback for MSW/test environments when no auth service is registered\n return this.mockAuthFallback(normalizedPath, method, body);\n }\n\n /**\n * Provides mock auth responses for core better-auth endpoints when\n * AuthPlugin is not loaded (e.g. MSW/browser-only environments).\n * This ensures registration/sign-in flows do not 404 in mock mode.\n */\n private mockAuthFallback(path: string, method: string, body: any): HttpDispatcherResult {\n const m = method.toUpperCase();\n const MOCK_SESSION_EXPIRY_MS = 86_400_000; // 24 hours\n\n // POST sign-up/email\n if ((path === 'sign-up/email' || path === 'register') && m === 'POST') {\n const id = `mock_${randomUUID()}`;\n return {\n handled: true,\n response: {\n status: 200,\n body: {\n user: { id, name: body?.name || 'Mock User', email: body?.email || 'mock@test.local', emailVerified: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },\n session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() },\n },\n },\n };\n }\n\n // POST sign-in/email or login\n if ((path === 'sign-in/email' || path === 'login') && m === 'POST') {\n const id = `mock_${randomUUID()}`;\n return {\n handled: true,\n response: {\n status: 200,\n body: {\n user: { id, name: 'Mock User', email: body?.email || 'mock@test.local', emailVerified: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },\n session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() },\n },\n },\n };\n }\n\n // GET get-session\n if (path === 'get-session' && m === 'GET') {\n return {\n handled: true,\n response: { status: 200, body: { session: null, user: null } },\n };\n }\n\n // POST sign-out\n if (path === 'sign-out' && m === 'POST') {\n return {\n handled: true,\n response: { status: 200, body: { success: true } },\n };\n }\n\n return { handled: false };\n }\n\n /**\n * Handles Metadata requests\n * Standard: /metadata/:type/:name\n * Fallback for backward compat: /metadata (all objects), /metadata/:objectName (get object)\n */\n async handleMetadata(path: string, context: HttpProtocolContext, method?: string, body?: any, query?: any): Promise {\n // Broker is used as a fallback — not required upfront.\n // This allows metadata to be served when only the protocol service\n // or ObjectQL service is available (e.g. lightweight / serverless setups).\n const broker = this.kernel.broker ?? null;\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n \n // GET /metadata/types\n if (parts[0] === 'types') {\n // PRIORITY 1: Try MetadataService directly (includes both typeRegistry with agent/tool AND runtime-registered types)\n console.log('[HttpDispatcher] Attempting to resolve MetadataService...');\n console.log('[HttpDispatcher] Available kernel methods:', {\n hasGetServiceAsync: typeof this.kernel.getServiceAsync === 'function',\n hasGetService: typeof this.kernel.getService === 'function',\n hasContext: !!this.kernel.context,\n hasContextGetService: typeof this.kernel.context?.getService === 'function',\n });\n\n // Try all service resolution paths with detailed logging\n let metadataService: any = null;\n\n // Path 1: kernel.getServiceAsync\n if (typeof this.kernel.getServiceAsync === 'function') {\n try {\n metadataService = await this.kernel.getServiceAsync('metadata');\n console.log('[HttpDispatcher] kernel.getServiceAsync(\"metadata\") returned:', !!metadataService);\n } catch (e: any) {\n console.log('[HttpDispatcher] kernel.getServiceAsync(\"metadata\") failed:', e.message);\n }\n }\n\n // Path 2: kernel.getService (if not found via async)\n if (!metadataService && typeof this.kernel.getService === 'function') {\n try {\n metadataService = await this.kernel.getService('metadata');\n console.log('[HttpDispatcher] kernel.getService(\"metadata\") returned:', !!metadataService);\n } catch (e: any) {\n console.log('[HttpDispatcher] kernel.getService(\"metadata\") failed:', e.message);\n }\n }\n\n // Path 3: kernel.context.getService (if not found)\n if (!metadataService && this.kernel.context?.getService) {\n try {\n metadataService = await this.kernel.context.getService('metadata');\n console.log('[HttpDispatcher] kernel.context.getService(\"metadata\") returned:', !!metadataService);\n } catch (e: any) {\n console.log('[HttpDispatcher] kernel.context.getService(\"metadata\") failed:', e.message);\n }\n }\n\n console.log('[HttpDispatcher] Final metadataService:', !!metadataService, 'has getRegisteredTypes:', typeof (metadataService as any)?.getRegisteredTypes);\n\n if (metadataService && typeof (metadataService as any).getRegisteredTypes === 'function') {\n try {\n const types = await (metadataService as any).getRegisteredTypes();\n console.log('[HttpDispatcher] MetadataService.getRegisteredTypes() returned:', types);\n return { handled: true, response: this.success({ types }) };\n } catch (e: any) {\n // Log error but continue to fallbacks\n console.warn('[HttpDispatcher] MetadataService.getRegisteredTypes() failed:', e.message, e.stack);\n }\n } else {\n console.log('[HttpDispatcher] MetadataService not available or missing getRegisteredTypes, falling back to protocol service');\n }\n // PRIORITY 2: Try protocol service (returns SchemaRegistry types only - missing agent/tool)\n const protocol = await this.resolveService('protocol');\n if (protocol && typeof protocol.getMetaTypes === 'function') {\n const result = await protocol.getMetaTypes({});\n console.log('[HttpDispatcher] Protocol service returned types:', result);\n return { handled: true, response: this.success(result) };\n }\n // PRIORITY 3: ask broker for registered types\n if (broker) {\n try {\n const data = await broker.call('metadata.types', {}, { request: context.request });\n console.log('[HttpDispatcher] Broker returned types:', data);\n return { handled: true, response: this.success(data) };\n } catch (e) {\n console.log('[HttpDispatcher] Broker call failed:', e);\n // fall through to hardcoded defaults\n }\n }\n // Last resort: hardcoded defaults\n console.warn('[HttpDispatcher] Falling back to hardcoded defaults for metadata types');\n return { handled: true, response: this.success({ types: ['object', 'app', 'plugin'] }) };\n }\n\n // GET /metadata/:type/:name/published → get published version\n if (parts.length === 3 && parts[2] === 'published' && (!method || method === 'GET')) {\n const [type, name] = parts;\n const metadataService = await this.getService(CoreServiceName.enum.metadata);\n if (metadataService && typeof (metadataService as any).getPublished === 'function') {\n const data = await (metadataService as any).getPublished(type, name);\n if (data === undefined) return { handled: true, response: this.error('Not found', 404) };\n return { handled: true, response: this.success(data) };\n }\n // Broker fallback\n if (broker) {\n try {\n const data = await broker.call('metadata.getPublished', { type, name }, { request: context.request });\n return { handled: true, response: this.success(data) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, 404) };\n }\n }\n return { handled: true, response: this.error('Not found', 404) };\n }\n\n // /metadata/:type/:name\n if (parts.length === 2) {\n const [type, name] = parts;\n // Extract optional package filter from query string\n const packageId = query?.package || undefined;\n\n // PUT /metadata/:type/:name (Save)\n if (method === 'PUT' && body) {\n // Try to get the protocol service directly\n const protocol = await this.resolveService('protocol');\n\n if (protocol && typeof protocol.saveMetaItem === 'function') {\n try {\n const result = await protocol.saveMetaItem({ type, name, item: body });\n return { handled: true, response: this.success(result) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, 400) };\n }\n }\n\n // Fallback to broker if protocol not available (legacy)\n if (broker) {\n try {\n const data = await broker.call('metadata.saveItem', { type, name, item: body }, { request: context.request });\n return { handled: true, response: this.success(data) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message || 'Save not supported', 501) };\n }\n }\n return { handled: true, response: this.error('Save not supported', 501) };\n }\n\n try {\n // Try specific calls based on type\n if (type === 'objects' || type === 'object') {\n if (broker) {\n const data = await broker.call('metadata.getObject', { objectName: name }, { request: context.request });\n return { handled: true, response: this.success(data) };\n }\n // Try ObjectQL service directly when broker is unavailable\n const qlService = await this.getObjectQLService();\n if (qlService?.registry) {\n const data = qlService.registry.getObject(name);\n if (data) return { handled: true, response: this.success(data) };\n }\n return { handled: true, response: this.error('Not found', 404) };\n }\n\n // Normalize plural URL paths to singular registry type names\n const singularType = pluralToSingular(type);\n\n // Try Protocol Service First (Preferred)\n const protocol = await this.resolveService('protocol');\n if (protocol && typeof protocol.getMetaItem === 'function') {\n try {\n const data = await protocol.getMetaItem({ type: singularType, name, packageId });\n return { handled: true, response: this.success(data) };\n } catch (e: any) {\n // Protocol might throw if not found or not supported\n // Fallback to broker?\n }\n }\n\n // Generic call for other types if supported via Broker (Legacy)\n if (broker) {\n const method = `metadata.get${this.capitalize(singularType)}`;\n const data = await broker.call(method, { name }, { request: context.request });\n return { handled: true, response: this.success(data) };\n }\n return { handled: true, response: this.error('Not found', 404) };\n } catch (e: any) {\n // Fallback: treat first part as object name if only 1 part (handled below)\n // But here we are deep in 2 parts. Must be an error.\n return { handled: true, response: this.error(e.message, 404) };\n }\n }\n \n // GET /metadata/:type (List items of type) OR /metadata/:objectName (Legacy)\n if (parts.length === 1) {\n const typeOrName = parts[0];\n // Extract optional package filter from query string\n const packageId = query?.package || undefined;\n\n // Try protocol service first for any type\n const protocol = await this.resolveService('protocol');\n if (protocol && typeof protocol.getMetaItems === 'function') {\n try {\n const data = await protocol.getMetaItems({ type: typeOrName, packageId });\n // Return any valid response from protocol (including empty items arrays)\n if (data && (data.items !== undefined || Array.isArray(data))) {\n return { handled: true, response: this.success(data) };\n }\n } catch {\n // Protocol doesn't know this type, fall through\n }\n }\n\n // Try MetadataService directly for runtime-registered metadata (agents, tools, etc.)\n const metadataService = await this.getService(CoreServiceName.enum.metadata);\n if (metadataService && typeof (metadataService as any).list === 'function') {\n try {\n const items = await (metadataService as any).list(typeOrName);\n if (items && items.length > 0) {\n return { handled: true, response: this.success({ type: typeOrName, items }) };\n }\n } catch (e: any) {\n // MetadataService doesn't know this type or failed, continue to other fallbacks\n // Sanitize typeOrName to prevent log injection (CodeQL warning)\n const sanitizedType = String(typeOrName).replace(/[\\r\\n\\t]/g, '');\n console.debug(`[HttpDispatcher] MetadataService.list() failed for type:`, sanitizedType, 'error:', e.message);\n }\n }\n\n // Try broker for the type\n if (broker) {\n try {\n if (typeOrName === 'objects') {\n const data = await broker.call('metadata.objects', { packageId }, { request: context.request });\n return { handled: true, response: this.success(data) };\n }\n const data = await broker.call(`metadata.${typeOrName}`, { packageId }, { request: context.request });\n if (data !== null && data !== undefined) {\n return { handled: true, response: this.success(data) };\n }\n } catch {\n // Broker doesn't support this action, fall through\n }\n\n // Legacy: /metadata/:objectName (treat as single object lookup)\n try {\n const data = await broker.call('metadata.getObject', { objectName: typeOrName }, { request: context.request });\n return { handled: true, response: this.success(data) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, 404) };\n }\n }\n\n // No broker — try ObjectQL registry directly for object lookups\n const qlService = await this.getObjectQLService();\n if (qlService?.registry) {\n if (typeOrName === 'objects') {\n const objs = qlService.registry.getAllObjects(packageId);\n return { handled: true, response: this.success({ type: 'object', items: objs }) };\n }\n // Try listing items of the given type\n const items = qlService.registry.listItems?.(typeOrName, packageId);\n if (items && items.length > 0) {\n return { handled: true, response: this.success({ type: typeOrName, items }) };\n }\n // Legacy: treat as object name\n const obj = qlService.registry.getObject(typeOrName);\n if (obj) return { handled: true, response: this.success(obj) };\n }\n return { handled: true, response: this.error('Not found', 404) };\n }\n\n // GET /metadata — return available metadata types\n if (parts.length === 0) {\n // Try protocol service for dynamic types\n const protocol = await this.resolveService('protocol');\n if (protocol && typeof protocol.getMetaTypes === 'function') {\n const result = await protocol.getMetaTypes({});\n return { handled: true, response: this.success(result) };\n }\n // Fallback: ask broker for registered types\n if (broker) {\n try {\n const data = await broker.call('metadata.types', {}, { request: context.request });\n return { handled: true, response: this.success(data) };\n } catch {\n // fall through to hardcoded defaults\n }\n }\n return { handled: true, response: this.success({ types: ['object', 'app', 'plugin'] }) };\n }\n \n return { handled: false };\n }\n\n /**\n * Handles Data requests\n * path: sub-path after /data/ (e.g. \"contacts\", \"contacts/123\", \"contacts/query\")\n */\n async handleData(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise {\n const broker = this.ensureBroker();\n const parts = path.replace(/^\\/+/, '').split('/');\n const objectName = parts[0];\n \n if (!objectName) {\n return { handled: true, response: this.error('Object name required', 400) };\n }\n\n const m = method.toUpperCase();\n\n // 1. Custom Actions (query, batch)\n if (parts.length > 1) {\n const action = parts[1];\n \n // POST /data/:object/query\n if (action === 'query' && m === 'POST') {\n // Spec: broker returns FindDataResponse = { object, records, total?, hasMore? }\n const result = await broker.call('data.query', { object: objectName, ...body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // POST /data/:object/batch\n if (action === 'batch' && m === 'POST') {\n const result = await broker.call('data.batch', { object: objectName, ...body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // GET /data/:object/:id\n if (parts.length === 2 && m === 'GET') {\n const id = parts[1];\n // Spec: Only select/expand are allowlisted query params for GET by ID.\n // All other query parameters are discarded to prevent parameter pollution.\n const { select, expand } = query || {};\n const allowedParams: Record = {};\n if (select != null) allowedParams.select = select;\n if (expand != null) allowedParams.expand = expand;\n // Spec: broker returns GetDataResponse = { object, id, record }\n const result = await broker.call('data.get', { object: objectName, id, ...allowedParams }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // PATCH /data/:object/:id\n if (parts.length === 2 && m === 'PATCH') {\n const id = parts[1];\n // Spec: broker returns UpdateDataResponse = { object, id, record }\n const result = await broker.call('data.update', { object: objectName, id, data: body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // DELETE /data/:object/:id\n if (parts.length === 2 && m === 'DELETE') {\n const id = parts[1];\n // Spec: broker returns DeleteDataResponse = { object, id, deleted }\n const result = await broker.call('data.delete', { object: objectName, id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n } else {\n // GET /data/:object (List)\n if (m === 'GET') {\n // ── Normalize HTTP transport params → Spec canonical (QueryAST) ──\n // HTTP GET query params use transport-level names (filter, sort, top,\n // skip, select, expand) which are normalized here to canonical\n // QueryAST field names (where, orderBy, limit, offset, fields,\n // expand) before forwarding to the broker layer.\n // The protocol.ts findData() method performs a deeper normalization\n // pass, but pre-normalizing here ensures the broker always receives\n // Spec-canonical keys.\n const normalized: Record = { ...query };\n\n // filter/filters → where\n // Note: `filter` is the canonical HTTP *transport* parameter name\n // (see HttpFindQueryParamsSchema). It is normalized here to the\n // canonical *QueryAST* field name `where` before broker dispatch.\n // `filters` (plural) is a deprecated alias for `filter`.\n if (normalized.filter != null || normalized.filters != null) {\n normalized.where = normalized.where ?? normalized.filter ?? normalized.filters;\n delete normalized.filter;\n delete normalized.filters;\n }\n // select → fields\n if (normalized.select != null && normalized.fields == null) {\n normalized.fields = normalized.select;\n delete normalized.select;\n }\n // sort → orderBy\n if (normalized.sort != null && normalized.orderBy == null) {\n normalized.orderBy = normalized.sort;\n delete normalized.sort;\n }\n // top → limit\n if (normalized.top != null && normalized.limit == null) {\n normalized.limit = normalized.top;\n delete normalized.top;\n }\n // skip → offset\n if (normalized.skip != null && normalized.offset == null) {\n normalized.offset = normalized.skip;\n delete normalized.skip;\n }\n\n // Spec: broker returns FindDataResponse = { object, records, total?, hasMore? }\n const result = await broker.call('data.query', { object: objectName, query: normalized }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n // POST /data/:object (Create)\n if (m === 'POST') {\n // Spec: broker returns CreateDataResponse = { object, id, record }\n const result = await broker.call('data.create', { object: objectName, data: body }, { request: context.request });\n const res = this.success(result);\n res.status = 201;\n return { handled: true, response: res };\n }\n }\n \n return { handled: false };\n }\n\n /**\n * Handles Analytics requests\n * path: sub-path after /analytics/\n */\n async handleAnalytics(path: string, method: string, body: any, _context: HttpProtocolContext): Promise {\n const analyticsService = await this.getService(CoreServiceName.enum.analytics);\n if (!analyticsService) return { handled: false }; // 404 handled by caller if unhandled\n\n const m = method.toUpperCase();\n const subPath = path.replace(/^\\/+/, '');\n\n // POST /analytics/query\n if (subPath === 'query' && m === 'POST') {\n const result = await analyticsService.query(body);\n return { handled: true, response: this.success(result) };\n }\n\n // GET /analytics/meta\n if (subPath === 'meta' && m === 'GET') {\n const result = await analyticsService.getMeta();\n return { handled: true, response: this.success(result) };\n }\n\n // POST /analytics/sql (Dry-run or debug)\n if (subPath === 'sql' && m === 'POST') {\n // Assuming service has generateSql method\n const result = await analyticsService.generateSql(body);\n return { handled: true, response: this.success(result) };\n }\n\n return { handled: false };\n }\n\n /**\n * Handles i18n requests\n * path: sub-path after /i18n/\n *\n * Routes:\n * GET /locales → getLocales\n * GET /translations/:locale → getTranslations (locale from path)\n * GET /translations?locale=xx → getTranslations (locale from query)\n * GET /labels/:object/:locale → getFieldLabels (both from path)\n * GET /labels/:object?locale=xx → getFieldLabels (locale from query)\n */\n async handleI18n(path: string, method: string, query: any, _context: HttpProtocolContext): Promise {\n const i18nService = await this.getService(CoreServiceName.enum.i18n);\n if (!i18nService) return { handled: true, response: this.error('i18n service not available', 501) };\n\n const m = method.toUpperCase();\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n\n if (m !== 'GET') return { handled: false };\n\n // GET /i18n/locales\n if (parts[0] === 'locales' && parts.length === 1) {\n const locales = i18nService.getLocales();\n return { handled: true, response: this.success({ locales }) };\n }\n\n // GET /i18n/translations/:locale OR /i18n/translations?locale=xx\n if (parts[0] === 'translations') {\n const locale = parts[1] ? decodeURIComponent(parts[1]) : query?.locale;\n if (!locale) return { handled: true, response: this.error('Missing locale parameter', 400) };\n\n let translations = i18nService.getTranslations(locale);\n\n // Locale fallback: try resolving to an available locale when\n // the exact code yields empty translations (e.g. zh → zh-CN).\n if (Object.keys(translations).length === 0) {\n const availableLocales = typeof i18nService.getLocales === 'function'\n ? i18nService.getLocales() : [];\n const resolved = resolveLocale(locale, availableLocales);\n if (resolved && resolved !== locale) {\n translations = i18nService.getTranslations(resolved);\n return { handled: true, response: this.success({ locale: resolved, requestedLocale: locale, translations }) };\n }\n }\n\n return { handled: true, response: this.success({ locale, translations }) };\n }\n\n // GET /i18n/labels/:object/:locale OR /i18n/labels/:object?locale=xx\n if (parts[0] === 'labels' && parts.length >= 2) {\n const objectName = decodeURIComponent(parts[1]);\n let locale = parts[2] ? decodeURIComponent(parts[2]) : query?.locale;\n if (!locale) return { handled: true, response: this.error('Missing locale parameter', 400) };\n\n // Locale fallback for labels endpoint\n const availableLocales = typeof i18nService.getLocales === 'function'\n ? i18nService.getLocales() : [];\n const resolved = resolveLocale(locale, availableLocales);\n if (resolved) locale = resolved;\n\n if (typeof i18nService.getFieldLabels === 'function') {\n const labels = i18nService.getFieldLabels(objectName, locale);\n return { handled: true, response: this.success({ object: objectName, locale, labels }) };\n }\n // Fallback: derive field labels from full translation bundle\n const translations = i18nService.getTranslations(locale);\n const prefix = `o.${objectName}.fields.`;\n const labels: Record = {};\n for (const [key, value] of Object.entries(translations)) {\n if (key.startsWith(prefix)) {\n labels[key.substring(prefix.length)] = value as string;\n }\n }\n return { handled: true, response: this.success({ object: objectName, locale, labels }) };\n }\n\n return { handled: false };\n }\n\n /**\n * Handles Package Management requests\n * \n * REST Endpoints:\n * - GET /packages → list all installed packages\n * - GET /packages/:id → get a specific package\n * - POST /packages → install a new package\n * - DELETE /packages/:id → uninstall a package\n * - PATCH /packages/:id/enable → enable a package\n * - PATCH /packages/:id/disable → disable a package\n * - POST /packages/:id/publish → publish a package (metadata snapshot)\n * - POST /packages/:id/revert → revert a package to last published state\n * \n * Uses ObjectQL SchemaRegistry directly (via the 'objectql' service)\n * with broker fallback for backward compatibility.\n */\n async handlePackages(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise {\n const m = method.toUpperCase();\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n\n // Try to get SchemaRegistry from the ObjectQL service\n const qlService = await this.getObjectQLService();\n const registry = qlService?.registry;\n\n // If no registry available, try broker as fallback\n if (!registry) {\n if (this.kernel.broker) {\n return this.handlePackagesViaBroker(parts, m, body, query, context);\n }\n return { handled: true, response: this.error('Package service not available', 503) };\n }\n\n try {\n // GET /packages → list packages\n if (parts.length === 0 && m === 'GET') {\n let packages = registry.getAllPackages();\n // Apply optional filters\n if (query?.status) {\n packages = packages.filter((p: any) => p.status === query.status);\n }\n if (query?.type) {\n packages = packages.filter((p: any) => p.manifest?.type === query.type);\n }\n return { handled: true, response: this.success({ packages, total: packages.length }) };\n }\n\n // POST /packages → install package\n if (parts.length === 0 && m === 'POST') {\n const pkg = registry.installPackage(body.manifest || body, body.settings);\n const res = this.success(pkg);\n res.status = 201;\n return { handled: true, response: res };\n }\n\n // PATCH /packages/:id/enable\n if (parts.length === 2 && parts[1] === 'enable' && m === 'PATCH') {\n const id = decodeURIComponent(parts[0]);\n const pkg = registry.enablePackage(id);\n if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };\n return { handled: true, response: this.success(pkg) };\n }\n\n // PATCH /packages/:id/disable\n if (parts.length === 2 && parts[1] === 'disable' && m === 'PATCH') {\n const id = decodeURIComponent(parts[0]);\n const pkg = registry.disablePackage(id);\n if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };\n return { handled: true, response: this.success(pkg) };\n }\n\n // POST /packages/:id/publish → publish package metadata\n if (parts.length === 2 && parts[1] === 'publish' && m === 'POST') {\n const id = decodeURIComponent(parts[0]);\n const metadataService = await this.getService(CoreServiceName.enum.metadata);\n if (metadataService && typeof (metadataService as any).publishPackage === 'function') {\n const result = await (metadataService as any).publishPackage(id, body || {});\n return { handled: true, response: this.success(result) };\n }\n // Broker fallback\n if (this.kernel.broker) {\n const result = await this.kernel.broker.call('metadata.publishPackage', { packageId: id, ...body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n return { handled: true, response: this.error('Metadata service not available', 503) };\n }\n\n // POST /packages/:id/revert → revert package to last published state\n if (parts.length === 2 && parts[1] === 'revert' && m === 'POST') {\n const id = decodeURIComponent(parts[0]);\n const metadataService = await this.getService(CoreServiceName.enum.metadata);\n if (metadataService && typeof (metadataService as any).revertPackage === 'function') {\n await (metadataService as any).revertPackage(id);\n return { handled: true, response: this.success({ success: true }) };\n }\n // Broker fallback\n if (this.kernel.broker) {\n await this.kernel.broker.call('metadata.revertPackage', { packageId: id }, { request: context.request });\n return { handled: true, response: this.success({ success: true }) };\n }\n return { handled: true, response: this.error('Metadata service not available', 503) };\n }\n\n // GET /packages/:id → get package\n if (parts.length === 1 && m === 'GET') {\n const id = decodeURIComponent(parts[0]);\n const pkg = registry.getPackage(id);\n if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };\n return { handled: true, response: this.success(pkg) };\n }\n\n // DELETE /packages/:id → uninstall package\n if (parts.length === 1 && m === 'DELETE') {\n const id = decodeURIComponent(parts[0]);\n const success = registry.uninstallPackage(id);\n if (!success) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };\n return { handled: true, response: this.success({ success: true }) };\n }\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, e.statusCode || 500) };\n }\n\n return { handled: false };\n }\n\n /**\n * Fallback: handle packages via broker (for backward compatibility)\n */\n private async handlePackagesViaBroker(parts: string[], m: string, body: any, query: any, context: HttpProtocolContext): Promise {\n const broker = this.kernel.broker;\n try {\n if (parts.length === 0 && m === 'GET') {\n const result = await broker.call('package.list', query || {}, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (parts.length === 0 && m === 'POST') {\n const result = await broker.call('package.install', body, { request: context.request });\n const res = this.success(result);\n res.status = 201;\n return { handled: true, response: res };\n }\n if (parts.length === 2 && parts[1] === 'enable' && m === 'PATCH') {\n const id = decodeURIComponent(parts[0]);\n const result = await broker.call('package.enable', { id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (parts.length === 2 && parts[1] === 'disable' && m === 'PATCH') {\n const id = decodeURIComponent(parts[0]);\n const result = await broker.call('package.disable', { id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (parts.length === 1 && m === 'GET') {\n const id = decodeURIComponent(parts[0]);\n const result = await broker.call('package.get', { id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (parts.length === 1 && m === 'DELETE') {\n const id = decodeURIComponent(parts[0]);\n const result = await broker.call('package.uninstall', { id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, e.statusCode || 500) };\n }\n return { handled: false };\n }\n\n /**\n * Handles Storage requests\n * path: sub-path after /storage/\n */\n async handleStorage(path: string, method: string, file: any, context: HttpProtocolContext): Promise {\n const storageService = await this.getService(CoreServiceName.enum['file-storage']) || this.kernel.services?.['file-storage'];\n if (!storageService) {\n return { handled: true, response: this.error('File storage not configured', 501) };\n }\n \n const m = method.toUpperCase();\n const parts = path.replace(/^\\/+/, '').split('/');\n \n // POST /storage/upload\n if (parts[0] === 'upload' && m === 'POST') {\n if (!file) {\n return { handled: true, response: this.error('No file provided', 400) };\n }\n const result = await storageService.upload(file, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n \n // GET /storage/file/:id\n if (parts[0] === 'file' && parts[1] && m === 'GET') {\n const id = parts[1];\n const result = await storageService.download(id, { request: context.request });\n \n // Result can be URL (redirect), Stream/Blob, or metadata\n if (result.url && result.redirect) {\n // Must be handled by adapter to do actual redirect\n return { handled: true, result: { type: 'redirect', url: result.url } };\n }\n \n if (result.stream) {\n // Must be handled by adapter to pipe stream\n return { \n handled: true, \n result: { \n type: 'stream', \n stream: result.stream, \n headers: {\n 'Content-Type': result.mimeType || 'application/octet-stream',\n 'Content-Length': result.size\n }\n } \n };\n }\n \n return { handled: true, response: this.success(result) };\n }\n \n return { handled: false };\n }\n\n /**\n * Handles UI requests\n * path: sub-path after /ui/\n */\n async handleUi(path: string, query: any, _context: HttpProtocolContext): Promise {\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n \n // GET /ui/view/:object (with optional type param)\n if (parts[0] === 'view' && parts[1]) {\n const objectName = parts[1];\n // Support both path param /view/obj/list AND query param /view/obj?type=list\n const type = parts[2] || query?.type || 'list';\n\n const protocol = await this.resolveService('protocol');\n \n if (protocol && typeof protocol.getUiView === 'function') {\n try {\n const result = await protocol.getUiView({ object: objectName, type });\n return { handled: true, response: this.success(result) };\n } catch (e: any) {\n return { handled: true, response: this.error(e.message, 500) };\n }\n } else {\n return { handled: true, response: this.error('Protocol service not available', 503) };\n }\n }\n\n return { handled: false };\n }\n\n /**\n * Handles Automation requests\n * path: sub-path after /automation/\n *\n * Routes:\n * GET / → listFlows\n * GET /:name → getFlow\n * POST / → createFlow (registerFlow)\n * PUT /:name → updateFlow\n * DELETE /:name → deleteFlow (unregisterFlow)\n * POST /:name/trigger → execute (legacy: trigger/:name also supported)\n * POST /:name/toggle → toggleFlow\n * GET /:name/runs → listRuns\n * GET /:name/runs/:runId → getRun\n */\n async handleAutomation(path: string, method: string, body: any, context: HttpProtocolContext, query?: any): Promise {\n const automationService = await this.getService(CoreServiceName.enum.automation);\n if (!automationService) return { handled: false };\n\n const m = method.toUpperCase();\n const parts = path.replace(/^\\/+/, '').split('/').filter(Boolean);\n\n // Legacy: POST /automation/trigger/:name\n if (parts[0] === 'trigger' && parts[1] && m === 'POST') {\n const triggerName = parts[1];\n if (typeof automationService.trigger === 'function') {\n const result = await automationService.trigger(triggerName, body, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n // Fallback to execute\n if (typeof automationService.execute === 'function') {\n const result = await automationService.execute(triggerName, body);\n return { handled: true, response: this.success(result) };\n }\n }\n\n // GET / → listFlows\n if (parts.length === 0 && m === 'GET') {\n if (typeof automationService.listFlows === 'function') {\n const names = await automationService.listFlows();\n return { handled: true, response: this.success({ flows: names, total: names.length, hasMore: false }) };\n }\n }\n\n // POST / → createFlow\n if (parts.length === 0 && m === 'POST') {\n if (typeof automationService.registerFlow === 'function') {\n automationService.registerFlow(body?.name, body);\n return { handled: true, response: this.success(body) };\n }\n }\n\n // Routes with :name\n if (parts.length >= 1) {\n const name = parts[0];\n\n // POST /:name/trigger → execute\n if (parts[1] === 'trigger' && m === 'POST') {\n if (typeof automationService.execute === 'function') {\n const result = await automationService.execute(name, body);\n return { handled: true, response: this.success(result) };\n }\n }\n\n // POST /:name/toggle → toggleFlow\n if (parts[1] === 'toggle' && m === 'POST') {\n if (typeof automationService.toggleFlow === 'function') {\n await automationService.toggleFlow(name, body?.enabled ?? true);\n return { handled: true, response: this.success({ name, enabled: body?.enabled ?? true }) };\n }\n }\n\n // GET /:name/runs/:runId → getRun\n if (parts[1] === 'runs' && parts[2] && m === 'GET') {\n if (typeof automationService.getRun === 'function') {\n const run = await automationService.getRun(parts[2]);\n if (!run) return { handled: true, response: this.error('Execution not found', 404) };\n return { handled: true, response: this.success(run) };\n }\n }\n\n // GET /:name/runs → listRuns\n if (parts[1] === 'runs' && !parts[2] && m === 'GET') {\n if (typeof automationService.listRuns === 'function') {\n const options = query ? { limit: query.limit ? Number(query.limit) : undefined, cursor: query.cursor } : undefined;\n const runs = await automationService.listRuns(name, options);\n return { handled: true, response: this.success({ runs, hasMore: false }) };\n }\n }\n\n // GET /:name → getFlow (no sub-path)\n if (parts.length === 1 && m === 'GET') {\n if (typeof automationService.getFlow === 'function') {\n const flow = await automationService.getFlow(name);\n if (!flow) return { handled: true, response: this.error('Flow not found', 404) };\n return { handled: true, response: this.success(flow) };\n }\n }\n\n // PUT /:name → updateFlow\n if (parts.length === 1 && m === 'PUT') {\n if (typeof automationService.registerFlow === 'function') {\n automationService.registerFlow(name, body?.definition ?? body);\n return { handled: true, response: this.success(body?.definition ?? body) };\n }\n }\n\n // DELETE /:name → deleteFlow\n if (parts.length === 1 && m === 'DELETE') {\n if (typeof automationService.unregisterFlow === 'function') {\n automationService.unregisterFlow(name);\n return { handled: true, response: this.success({ name, deleted: true }) };\n }\n }\n }\n \n return { handled: false };\n }\n\n private getServicesMap(): Record {\n if (this.kernel.services instanceof Map) {\n return Object.fromEntries(this.kernel.services);\n }\n return this.kernel.services || {};\n }\n\n private async getService(name: CoreServiceName) {\n return this.resolveService(name);\n }\n\n /**\n * Resolve any service by name, supporting async factories.\n * Fallback chain: getServiceAsync → getService (sync) → context.getService → services map.\n * Only returns when a non-null service is found; otherwise falls through to the next step.\n */\n private async resolveService(name: string) {\n // Prefer async resolution to support factory-based services (e.g. auth, analytics, protocol)\n if (typeof this.kernel.getServiceAsync === 'function') {\n try {\n const svc = await this.kernel.getServiceAsync(name);\n if (svc != null) return svc;\n } catch {\n // Service not registered or async resolution failed — fall through\n }\n }\n if (typeof this.kernel.getService === 'function') {\n try {\n const svc = await this.kernel.getService(name);\n if (svc != null) return svc;\n } catch {\n // Service not registered or sync resolution threw \"is async\" — fall through\n }\n }\n if (this.kernel?.context?.getService) {\n try {\n const svc = await this.kernel.context.getService(name);\n if (svc != null) return svc;\n } catch {\n // Service not registered — fall through\n }\n }\n const services = this.getServicesMap();\n return services[name];\n }\n\n /**\n * Get the ObjectQL service which provides access to SchemaRegistry.\n * Tries multiple access patterns since kernel structure varies.\n */\n private async getObjectQLService(): Promise {\n // 1. Try via resolveService (handles async factories, sync, context, and map)\n try {\n const svc = await this.resolveService('objectql');\n if (svc?.registry) return svc;\n } catch { /* service not available */ }\n return null;\n }\n\n private capitalize(s: string) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n }\n\n /**\n * Handle AI service routes (/ai/chat, /ai/models, /ai/conversations, etc.)\n * Resolves the AI service and its built-in route handlers, then dispatches.\n */\n async handleAI(subPath: string, method: string, body: any, query: any, _context: HttpProtocolContext): Promise {\n let aiService: any;\n try {\n aiService = await this.resolveService('ai');\n } catch {\n // AI service not registered\n }\n\n if (!aiService) {\n return {\n handled: true,\n response: {\n status: 404,\n body: { success: false, error: { message: 'AI service is not configured', code: 404 } },\n },\n };\n }\n\n // The AI service exposes route definitions via buildAIRoutes.\n // We match the request path against known AI route patterns.\n const fullPath = `/api/v1${subPath}`;\n\n // Build a simple param-extracting matcher for route patterns like /api/v1/ai/conversations/:id\n const matchRoute = (pattern: string, path: string): Record | null => {\n const patternParts = pattern.split('/');\n const pathParts = path.split('/');\n if (patternParts.length !== pathParts.length) return null;\n const params: Record = {};\n for (let i = 0; i < patternParts.length; i++) {\n if (patternParts[i].startsWith(':')) {\n params[patternParts[i].substring(1)] = pathParts[i];\n } else if (patternParts[i] !== pathParts[i]) {\n return null;\n }\n }\n return params;\n };\n\n // Try to get route definitions from the AI service's cached routes\n const routes = (this.kernel as any).__aiRoutes as Array<{\n method: string; path: string; handler: (req: any) => Promise;\n }> | undefined;\n\n if (!routes) {\n return {\n handled: true,\n response: {\n status: 503,\n body: { success: false, error: { message: 'AI service routes not yet initialized', code: 503 } },\n },\n };\n }\n\n for (const route of routes) {\n if (route.method !== method) continue;\n const params = matchRoute(route.path, fullPath);\n if (params === null) continue;\n\n const result = await route.handler({ body, params, query });\n\n if (result.stream && result.events) {\n // Return a streaming result for the adapter to handle\n return {\n handled: true,\n result: {\n type: 'stream',\n contentType: result.vercelDataStream\n ? 'text/plain; charset=utf-8'\n : 'text/event-stream',\n events: result.events,\n vercelDataStream: result.vercelDataStream,\n headers: {\n 'Content-Type': result.vercelDataStream\n ? 'text/plain; charset=utf-8'\n : 'text/event-stream',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n },\n },\n };\n }\n\n return {\n handled: true,\n response: {\n status: result.status,\n body: result.body,\n },\n };\n }\n\n return {\n handled: true,\n response: this.routeNotFound(subPath),\n };\n }\n\n /**\n * Main Dispatcher Entry Point\n * Routes the request to the appropriate handler based on path and precedence\n */\n async dispatch(method: string, path: string, body: any, query: any, context: HttpProtocolContext, prefix?: string): Promise {\n const cleanPath = path.replace(/\\/$/, ''); // Remove trailing slash if present, but strict on clean paths\n\n // 0. Discovery Endpoint (GET /discovery or GET /)\n // Standard route: /discovery (protocol-compliant)\n // Legacy route: / (empty path, for backward compatibility — MSW strips base URL)\n if ((cleanPath === '/discovery' || cleanPath === '') && method === 'GET') {\n const info = await this.getDiscoveryInfo(prefix ?? '');\n return { \n handled: true, \n response: this.success(info) \n };\n }\n\n // 0b. Health Endpoint (GET /health)\n if (cleanPath === '/health' && method === 'GET') {\n return {\n handled: true,\n response: this.success({\n status: 'ok',\n timestamp: new Date().toISOString(),\n version: '1.0.0',\n uptime: typeof process !== 'undefined' ? process.uptime() : undefined,\n }),\n };\n }\n\n // 1. System Protocols (Prefix-based)\n if (cleanPath.startsWith('/auth')) {\n return this.handleAuth(cleanPath.substring(5), method, body, context);\n }\n \n if (cleanPath.startsWith('/meta')) {\n return this.handleMetadata(cleanPath.substring(5), context, method, body, query);\n }\n\n if (cleanPath.startsWith('/data')) {\n return this.handleData(cleanPath.substring(5), method, body, query, context);\n }\n \n if (cleanPath.startsWith('/graphql')) {\n if (method === 'POST') return this.handleGraphQL(body, context);\n // GraphQL usually GET for Playground is handled by middleware but we can return 405 or handle it\n }\n\n if (cleanPath.startsWith('/storage')) {\n return this.handleStorage(cleanPath.substring(8), method, body, context); // body here is file/stream for upload\n }\n \n if (cleanPath.startsWith('/ui')) {\n return this.handleUi(cleanPath.substring(3), query, context);\n }\n\n if (cleanPath.startsWith('/automation')) {\n return this.handleAutomation(cleanPath.substring(11), method, body, context, query);\n }\n \n if (cleanPath.startsWith('/analytics')) {\n return this.handleAnalytics(cleanPath.substring(10), method, body, context);\n }\n\n if (cleanPath.startsWith('/packages')) {\n return this.handlePackages(cleanPath.substring(9), method, body, query, context);\n }\n\n if (cleanPath.startsWith('/i18n')) {\n return this.handleI18n(cleanPath.substring(5), method, query, context);\n }\n\n // AI Service — delegate to the registered AI route handlers\n if (cleanPath.startsWith('/ai')) {\n return this.handleAI(cleanPath, method, body, query, context);\n }\n\n // OpenAPI Specification\n if (cleanPath === '/openapi.json' && method === 'GET') {\n const broker = this.ensureBroker();\n try {\n const result = await broker.call('metadata.generateOpenApi', {}, { request: context.request });\n return { handled: true, response: this.success(result) };\n } catch (e) {\n // If not implemented, fall through or return 404\n }\n }\n\n // 2. Custom API Endpoints (Registry lookup)\n // Check if there is a custom endpoint defined for this path\n const result = await this.handleApiEndpoint(cleanPath, method, body, query, context);\n if (result.handled) return result;\n\n // 3. Fallback — return semantic 404 with diagnostic info\n return {\n handled: true,\n response: this.routeNotFound(cleanPath),\n };\n }\n\n /**\n * Handles Custom API Endpoints defined in metadata\n */\n async handleApiEndpoint(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise {\n const broker = this.ensureBroker();\n try {\n // Attempt to find a matching endpoint in the registry\n // This assumes a 'metadata.matchEndpoint' action exists in the kernel/registry\n // path should include initial slash e.g. /api/v1/customers\n const endpoint = await broker.call('metadata.matchEndpoint', { path, method });\n \n if (endpoint) {\n // Execute the endpoint target logic\n if (endpoint.type === 'flow') {\n const result = await broker.call('automation.runFlow', { \n flowId: endpoint.target, \n inputs: { ...query, ...body, _request: context.request } \n });\n return { handled: true, response: this.success(result) };\n }\n \n if (endpoint.type === 'script') {\n const result = await broker.call('automation.runScript', { \n scriptName: endpoint.target, \n context: { ...query, ...body, request: context.request } \n }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n\n if (endpoint.type === 'object_operation') {\n // e.g. Proxy to an object action\n if (endpoint.objectParams) {\n const { object, operation } = endpoint.objectParams;\n // Map standard CRUD operations\n if (operation === 'find') {\n const result = await broker.call('data.query', { object, query }, { request: context.request });\n // Spec: FindDataResponse = { object, records, total?, hasMore? }\n return { handled: true, response: this.success(result.records, { total: result.total }) };\n }\n if (operation === 'get' && query.id) {\n const result = await broker.call('data.get', { object, id: query.id }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n if (operation === 'create') {\n const result = await broker.call('data.create', { object, data: body }, { request: context.request });\n return { handled: true, response: this.success(result) };\n }\n }\n }\n\n if (endpoint.type === 'proxy') {\n // Simple proxy implementation (requires a network call, which usually is done by a service but here we can stub return)\n // In real implementation this might fetch(endpoint.target)\n // For now, return target info\n return { \n handled: true, \n response: { \n status: 200, \n body: { proxy: true, target: endpoint.target, note: 'Proxy execution requires http-client service' } \n } \n };\n }\n }\n } catch (e) {\n // If matchEndpoint fails (e.g. not found), we just return not handled\n // so we can fallback to 404 or other handlers\n }\n\n return { handled: false };\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext, IHttpServer } from '@objectstack/core';\nimport { HttpDispatcher, HttpDispatcherResult } from './http-dispatcher.js';\n\nexport interface DispatcherPluginConfig {\n /**\n * API path prefix for all endpoints.\n * @default '/api/v1'\n */\n prefix?: string;\n}\n\n/**\n * Route definition emitted by service plugins (e.g. AIServicePlugin) via hooks.\n * Minimal interface — matches the shape produced by `buildAIRoutes()`.\n */\ninterface RouteDefinition {\n method: 'GET' | 'POST' | 'DELETE';\n path: string;\n description: string;\n handler: (req: any) => Promise;\n}\n\n/**\n * Register a single RouteDefinition on the HTTP server.\n * Returns true if the route was successfully registered.\n */\nfunction mountRouteOnServer(route: RouteDefinition, server: IHttpServer, routePath: string): boolean {\n const handler = async (req: any, res: any) => {\n try {\n const result = await route.handler({\n body: req.body,\n params: req.params,\n query: req.query,\n });\n\n if (result.stream && result.events) {\n // SSE streaming response\n res.status(result.status);\n\n // Apply headers from the route result if available\n if (result.headers) {\n for (const [k, v] of Object.entries(result.headers)) {\n res.header(k, String(v));\n }\n } else {\n res.header('Content-Type', 'text/event-stream');\n res.header('Cache-Control', 'no-cache');\n res.header('Connection', 'keep-alive');\n }\n\n // Write the stream — events are pre-encoded SSE strings\n if (typeof res.write === 'function' && typeof res.end === 'function') {\n for await (const event of result.events) {\n res.write(typeof event === 'string' ? event : `data: ${JSON.stringify(event)}\\n\\n`);\n }\n res.end();\n } else {\n // Fallback: collect events into array\n const events = [];\n for await (const event of result.events) {\n events.push(event);\n }\n res.json({ events });\n }\n } else {\n res.status(result.status);\n if (result.body !== undefined) {\n res.json(result.body);\n } else {\n res.end();\n }\n }\n } catch (err: any) {\n errorResponse(err, res);\n }\n };\n\n const m = route.method.toLowerCase();\n if (m === 'get' && typeof server.get === 'function') {\n server.get(routePath, handler);\n return true;\n } else if (m === 'post' && typeof server.post === 'function') {\n server.post(routePath, handler);\n return true;\n } else if (m === 'delete' && typeof server.delete === 'function') {\n server.delete(routePath, handler);\n return true;\n }\n return false;\n}\n\n/**\n * Send an HttpDispatcherResult through IHttpResponse.\n * Differentiates between handled, unhandled (404), and special results.\n */\nfunction sendResult(result: HttpDispatcherResult, res: any): void {\n if (result.handled) {\n if (result.response) {\n res.status(result.response.status);\n if (result.response.headers) {\n for (const [k, v] of Object.entries(result.response.headers)) {\n res.header(k, v);\n }\n }\n res.json(result.response.body);\n return;\n }\n if (result.result) {\n // Special results (redirect, stream) — pass through as JSON for now\n res.status(200).json(result.result);\n return;\n }\n }\n // Semantic 404: no route matched — include diagnostic info\n res.status(404).json({\n success: false,\n error: {\n message: 'Not Found',\n code: 404,\n type: 'ROUTE_NOT_FOUND',\n hint: 'No handler matched this request. Check the API discovery endpoint for available routes.',\n },\n });\n}\n\nfunction errorResponse(err: any, res: any): void {\n const code = err.statusCode || 500;\n res.status(code).json({\n success: false,\n error: { message: err.message || 'Internal Server Error', code },\n });\n}\n\n/**\n * Dispatcher Plugin\n *\n * Bridges legacy HttpDispatcher handlers to the IHttpServer route-registration model.\n * Registers routes for domains NOT covered by @objectstack/rest:\n * - /.well-known/objectstack (discovery)\n * - /auth (authentication)\n * - /graphql (GraphQL)\n * - /analytics (BI queries)\n * - /packages (package management)\n * - /i18n (internationalization — locales, translations, field labels)\n * - /storage (file storage)\n * - /automation (CRUD + triggers + runs)\n *\n * Usage:\n * ```ts\n * import { createDispatcherPlugin } from '@objectstack/runtime';\n * runtime.use(createDispatcherPlugin({ prefix: '/api/v1' }));\n * ```\n */\nexport function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plugin {\n return {\n name: 'com.objectstack.runtime.dispatcher',\n version: '1.0.0',\n\n init: async (_ctx: PluginContext) => {\n // Consumer-only plugin — no services registered\n },\n\n start: async (ctx: PluginContext) => {\n let server: IHttpServer | undefined;\n try {\n server = ctx.getService('http.server');\n } catch {\n // No HTTP server available — skip silently\n return;\n }\n if (!server) return;\n\n const kernel = ctx.getKernel();\n const dispatcher = new HttpDispatcher(kernel);\n const prefix = config.prefix || '/api/v1';\n\n // ── Discovery (.well-known) ─────────────────────────────────\n server.get('/.well-known/objectstack', async (_req: any, res: any) => {\n res.json({ data: await dispatcher.getDiscoveryInfo(prefix) });\n });\n\n // ── Discovery (versioned API path) ──────────────────────────\n server.get(`${prefix}/discovery`, async (_req: any, res: any) => {\n res.json({ data: await dispatcher.getDiscoveryInfo(prefix) });\n });\n\n // ── Health ──────────────────────────────────────────────────\n server.get(`${prefix}/health`, async (_req: any, res: any) => {\n try {\n const result = await dispatcher.dispatch('GET', '/health', undefined, {}, { request: _req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Auth ────────────────────────────────────────────────────\n server.post(`${prefix}/auth/login`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAuth('login', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── GraphQL ─────────────────────────────────────────────────\n server.post(`${prefix}/graphql`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleGraphQL(req.body, { request: req });\n res.json(result);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Analytics ───────────────────────────────────────────────\n server.post(`${prefix}/analytics/query`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAnalytics('query', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/analytics/meta`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAnalytics('meta', 'GET', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/analytics/sql`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAnalytics('sql', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Packages ────────────────────────────────────────────────\n server.get(`${prefix}/packages`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages('', 'GET', {}, req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/packages`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages('', 'POST', req.body, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/packages/:id`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}`, 'GET', {}, req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.delete(`${prefix}/packages/:id`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}`, 'DELETE', {}, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.patch(`${prefix}/packages/:id/enable`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}/enable`, 'PATCH', {}, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.patch(`${prefix}/packages/:id/disable`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}/disable`, 'PATCH', {}, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/packages/:id/publish`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}/publish`, 'POST', req.body, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/packages/:id/revert`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handlePackages(`/${req.params.id}/revert`, 'POST', req.body, {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Storage ─────────────────────────────────────────────────\n server.post(`${prefix}/storage/upload`, async (req: any, res: any) => {\n try {\n // For file uploads the body *is* the file (parsed by adapter)\n const result = await dispatcher.handleStorage('upload', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/storage/file/:id`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleStorage(`file/${req.params.id}`, 'GET', undefined, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── i18n ────────────────────────────────────────────────────\n // Bridges to HttpDispatcher.handleI18n() which resolves the i18n\n // service from the kernel (either I18nServicePlugin or memory fallback).\n server.get(`${prefix}/i18n/locales`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleI18n('/locales', 'GET', req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/i18n/translations/:locale`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleI18n(`/translations/${req.params.locale}`, 'GET', req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/i18n/labels/:object/:locale`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleI18n(`/labels/${req.params.object}/${req.params.locale}`, 'GET', req.query, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n // ── Automation ──────────────────────────────────────────────\n server.get(`${prefix}/automation`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation('', 'GET', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/automation`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation('', 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/automation/:name`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}`, 'GET', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.put(`${prefix}/automation/:name`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}`, 'PUT', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.delete(`${prefix}/automation/:name`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}`, 'DELETE', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/automation/trigger/:name`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`trigger/${req.params.name}`, 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/automation/:name/trigger`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}/trigger`, 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.post(`${prefix}/automation/:name/toggle`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}/toggle`, 'POST', req.body, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/automation/:name/runs`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}/runs`, 'GET', {}, { request: req }, req.query);\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n server.get(`${prefix}/automation/:name/runs/:runId`, async (req: any, res: any) => {\n try {\n const result = await dispatcher.handleAutomation(`${req.params.name}/runs/${req.params.runId}`, 'GET', {}, { request: req });\n sendResult(result, res);\n } catch (err: any) {\n errorResponse(err, res);\n }\n });\n\n ctx.logger.info('Dispatcher bridge routes registered', { prefix });\n\n // ── Dynamic service routes (AI, etc.) ───────────────────\n // Listen for route definitions emitted by service plugins.\n // The AIServicePlugin emits 'ai:routes' with RouteDefinition[].\n ctx.hook('ai:routes', async (routes: RouteDefinition[]) => {\n if (!server) return;\n for (const route of routes) {\n // Strip the /api/v1 prefix if present (it's already in the path)\n // and register on the HTTP server with the configured prefix.\n const routePath = route.path.startsWith('/api/v1')\n ? route.path\n : `${prefix}${route.path}`;\n mountRouteOnServer(route, server, routePath);\n }\n ctx.logger.info(`[Dispatcher] Registered ${routes.length} AI routes`);\n });\n\n // ── Fallback: recover routes cached before hook was registered ──\n // If AIServicePlugin.start() ran before DispatcherPlugin.start()\n // (possible when plugin start order differs from registration order),\n // the 'ai:routes' trigger fires with no listener. The AIServicePlugin\n // caches the routes on the kernel as __aiRoutes (see AIServicePlugin.start())\n // as an internal cross-plugin protocol so we can recover them here.\n // TODO: replace with a formal kernel.getCachedRoutes('ai') API in a future release.\n const cachedRoutes = (kernel as any).__aiRoutes as RouteDefinition[] | undefined;\n if (cachedRoutes && Array.isArray(cachedRoutes) && cachedRoutes.length > 0) {\n let registered = 0;\n for (const route of cachedRoutes) {\n const routePath = route.path.startsWith('/api/v1')\n ? route.path\n : `${prefix}${route.path}`;\n if (mountRouteOnServer(route, server, routePath)) {\n registered++;\n }\n }\n if (registered > 0) {\n ctx.logger.info(`[Dispatcher] Recovered ${registered} cached AI routes (hook timing fallback)`);\n }\n }\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { IHttpServer, RouteHandler, Middleware } from '@objectstack/core';\n\n/**\n * HttpServer - Unified HTTP Server Abstraction\n * \n * Provides a framework-agnostic HTTP server interface that wraps\n * underlying server implementations (Hono, Express, Fastify, etc.)\n * \n * This class serves as an adapter between the IHttpServer interface\n * and concrete server implementations, allowing plugins to register\n * routes and middleware without depending on specific frameworks.\n * \n * Features:\n * - Unified route registration API\n * - Middleware management with ordering\n * - Request/response lifecycle hooks\n * - Framework-agnostic abstractions\n */\nexport class HttpServer implements IHttpServer {\n protected server: IHttpServer;\n protected routes: Map;\n protected middlewares: Middleware[];\n \n /**\n * Create an HTTP server wrapper\n * @param server - The underlying server implementation (Hono, Express, etc.)\n */\n constructor(server: IHttpServer) {\n this.server = server;\n this.routes = new Map();\n this.middlewares = [];\n }\n \n /**\n * Register a GET route handler\n * @param path - Route path (e.g., '/api/users/:id')\n * @param handler - Route handler function\n */\n get(path: string, handler: RouteHandler): void {\n const key = `GET:${path}`;\n this.routes.set(key, handler);\n this.server.get(path, handler);\n }\n \n /**\n * Register a POST route handler\n * @param path - Route path\n * @param handler - Route handler function\n */\n post(path: string, handler: RouteHandler): void {\n const key = `POST:${path}`;\n this.routes.set(key, handler);\n this.server.post(path, handler);\n }\n \n /**\n * Register a PUT route handler\n * @param path - Route path\n * @param handler - Route handler function\n */\n put(path: string, handler: RouteHandler): void {\n const key = `PUT:${path}`;\n this.routes.set(key, handler);\n this.server.put(path, handler);\n }\n \n /**\n * Register a DELETE route handler\n * @param path - Route path\n * @param handler - Route handler function\n */\n delete(path: string, handler: RouteHandler): void {\n const key = `DELETE:${path}`;\n this.routes.set(key, handler);\n this.server.delete(path, handler);\n }\n \n /**\n * Register a PATCH route handler\n * @param path - Route path\n * @param handler - Route handler function\n */\n patch(path: string, handler: RouteHandler): void {\n const key = `PATCH:${path}`;\n this.routes.set(key, handler);\n this.server.patch(path, handler);\n }\n \n /**\n * Register middleware\n * @param path - Optional path to apply middleware to (if omitted, applies globally)\n * @param handler - Middleware function\n */\n use(path: string | Middleware, handler?: Middleware): void {\n if (typeof path === 'function') {\n // Global middleware\n this.middlewares.push(path);\n this.server.use(path);\n } else if (handler) {\n // Path-specific middleware\n this.middlewares.push(handler);\n this.server.use(path, handler);\n }\n }\n \n /**\n * Start the HTTP server\n * @param port - Port number to listen on\n * @returns Promise that resolves when server is ready\n */\n async listen(port: number): Promise {\n await this.server.listen(port);\n }\n \n /**\n * Stop the HTTP server\n * @returns Promise that resolves when server is stopped\n */\n async close(): Promise {\n if (this.server.close) {\n await this.server.close();\n }\n }\n \n /**\n * Get registered routes\n * @returns Map of route keys to handlers\n */\n getRoutes(): Map {\n return new Map(this.routes);\n }\n \n /**\n * Get registered middlewares\n * @returns Array of middleware functions\n */\n getMiddlewares(): Middleware[] {\n return [...this.middlewares];\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Middleware, IHttpRequest, IHttpResponse } from '@objectstack/core';\nimport { MiddlewareConfig, MiddlewareType } from '@objectstack/spec/system';\n\n/**\n * Middleware Entry\n * Internal representation of registered middleware\n */\ninterface MiddlewareEntry {\n name: string;\n type: MiddlewareType;\n middleware: Middleware;\n order: number;\n enabled: boolean;\n paths?: {\n include?: string[];\n exclude?: string[];\n };\n}\n\n/**\n * MiddlewareManager\n * \n * Manages middleware registration, ordering, and execution.\n * Provides fine-grained control over middleware chains with:\n * - Execution order management\n * - Path-based filtering\n * - Enable/disable individual middleware\n * - Middleware categorization by type\n * \n * @example\n * const manager = new MiddlewareManager();\n * \n * // Register middleware with configuration\n * manager.register({\n * name: 'auth',\n * type: 'authentication',\n * order: 10,\n * paths: { exclude: ['/health', '/metrics'] }\n * }, authMiddleware);\n * \n * // Get sorted middleware chain\n * const chain = manager.getMiddlewareChain();\n * chain.forEach(mw => server.use(mw));\n */\nexport class MiddlewareManager {\n private middlewares: Map;\n \n constructor() {\n this.middlewares = new Map();\n }\n \n /**\n * Register middleware with configuration\n * @param config - Middleware configuration\n * @param middleware - Middleware function\n */\n register(config: MiddlewareConfig, middleware: Middleware): void {\n const entry: MiddlewareEntry = {\n name: config.name,\n type: config.type,\n middleware,\n order: config.order ?? 100,\n enabled: config.enabled ?? true,\n paths: config.paths,\n };\n \n this.middlewares.set(config.name, entry);\n }\n \n /**\n * Unregister middleware by name\n * @param name - Middleware name\n */\n unregister(name: string): void {\n this.middlewares.delete(name);\n }\n \n /**\n * Enable middleware by name\n * @param name - Middleware name\n */\n enable(name: string): void {\n const entry = this.middlewares.get(name);\n if (entry) {\n entry.enabled = true;\n }\n }\n \n /**\n * Disable middleware by name\n * @param name - Middleware name\n */\n disable(name: string): void {\n const entry = this.middlewares.get(name);\n if (entry) {\n entry.enabled = false;\n }\n }\n \n /**\n * Get middleware entry by name\n * @param name - Middleware name\n */\n get(name: string): MiddlewareEntry | undefined {\n return this.middlewares.get(name);\n }\n \n /**\n * Get all middleware entries\n */\n getAll(): MiddlewareEntry[] {\n return Array.from(this.middlewares.values());\n }\n \n /**\n * Get middleware by type\n * @param type - Middleware type\n */\n getByType(type: MiddlewareType): MiddlewareEntry[] {\n return this.getAll().filter(entry => entry.type === type);\n }\n \n /**\n * Get middleware chain sorted by order\n * Returns only enabled middleware\n */\n getMiddlewareChain(): Middleware[] {\n return this.getAll()\n .filter(entry => entry.enabled)\n .sort((a, b) => a.order - b.order)\n .map(entry => entry.middleware);\n }\n \n /**\n * Get middleware chain with path filtering\n * @param path - Request path to match against\n */\n getMiddlewareChainForPath(path: string): Middleware[] {\n return this.getAll()\n .filter(entry => {\n if (!entry.enabled) return false;\n \n // Check path filters\n if (entry.paths) {\n // Check exclude patterns\n if (entry.paths.exclude) {\n const excluded = entry.paths.exclude.some(pattern => \n this.matchPath(path, pattern)\n );\n if (excluded) return false;\n }\n \n // Check include patterns (if specified)\n if (entry.paths.include) {\n const included = entry.paths.include.some(pattern => \n this.matchPath(path, pattern)\n );\n if (!included) return false;\n }\n }\n \n return true;\n })\n .sort((a, b) => a.order - b.order)\n .map(entry => entry.middleware);\n }\n \n /**\n * Match path against pattern (simple glob matching)\n * @param path - Request path\n * @param pattern - Pattern to match (supports * wildcard)\n */\n private matchPath(path: string, pattern: string): boolean {\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n \n const regex = new RegExp(`^${regexPattern}$`);\n return regex.test(path);\n }\n \n /**\n * Clear all middleware\n */\n clear(): void {\n this.middlewares.clear();\n }\n \n /**\n * Get middleware count\n */\n count(): number {\n return this.middlewares.size;\n }\n \n /**\n * Create a composite middleware from the chain\n * This can be used to apply all middleware at once\n */\n createCompositeMiddleware(): Middleware {\n const chain = this.getMiddlewareChain();\n \n return async (req: IHttpRequest, res: IHttpResponse, next: () => void | Promise) => {\n let index = 0;\n \n const executeNext = async (): Promise => {\n if (index >= chain.length) {\n await next();\n return;\n }\n \n const middleware = chain[index++];\n await middleware(req, res, executeNext);\n };\n \n await executeNext();\n };\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Base Field Mapping Protocol\n * \n * Shared by: ETL, Sync, Connector, External Lookup\n * \n * This module provides the canonical field mapping schema used across\n * ObjectStack for data transformation and synchronization.\n * \n * **Use Cases:**\n * - ETL pipelines (data/mapping.zod.ts)\n * - Data synchronization (automation/sync.zod.ts)\n * - Integration connectors (integration/connector.zod.ts)\n * - External lookups (data/external-lookup.zod.ts)\n * \n * @example Basic field mapping\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'external_user_id',\n * target: 'user_id',\n * };\n * ```\n * \n * @example With transformation\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'user_name',\n * target: 'name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: 'Unknown'\n * };\n * ```\n */\n\n/**\n * Transform Type Schema\n * \n * Defines the type of transformation to apply to a field value.\n * Implementations can extend this for domain-specific transforms.\n */\nexport const TransformTypeSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('constant'),\n value: z.unknown().describe('Constant value to use'),\n }).describe('Set a constant value'),\n \n z.object({\n type: z.literal('cast'),\n targetType: z.enum(['string', 'number', 'boolean', 'date']).describe('Target data type'),\n }).describe('Cast to a specific data type'),\n \n z.object({\n type: z.literal('lookup'),\n table: z.string().describe('Lookup table name'),\n keyField: z.string().describe('Field to match on'),\n valueField: z.string().describe('Field to retrieve'),\n }).describe('Lookup value from another table'),\n \n z.object({\n type: z.literal('javascript'),\n expression: z.string().describe('JavaScript expression (e.g., \"value.toUpperCase()\")'),\n }).describe('Custom JavaScript transformation'),\n \n z.object({\n type: z.literal('map'),\n mappings: z.record(z.string(), z.unknown()).describe('Value mappings (e.g., {\"Active\": \"active\"})'),\n }).describe('Map values using a dictionary'),\n]);\n\nexport type TransformType = z.infer;\n\n/**\n * Field Mapping Schema\n * \n * Base schema for mapping fields between source and target systems.\n * \n * **NAMING CONVENTION:**\n * - source: Field name in the source system\n * - target: Field name in the target system (should be snake_case for ObjectStack)\n * \n * @example\n * ```typescript\n * {\n * source: 'FirstName',\n * target: 'first_name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: ''\n * }\n * ```\n */\nexport const FieldMappingSchema = z.object({\n /**\n * Source field name\n */\n source: z.string().describe('Source field name'),\n \n /**\n * Target field name (should be snake_case for ObjectStack)\n */\n target: z.string().describe('Target field name'),\n \n /**\n * Transformation to apply\n */\n transform: TransformTypeSchema.optional().describe('Transformation to apply'),\n \n /**\n * Default value if source is null/undefined\n */\n defaultValue: z.unknown().optional().describe('Default if source is null/undefined'),\n});\n\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Shared Enumerations\n// ============================================================================\n\n/** Aggregation functions used across query, data-engine, analytics, field */\nexport const AggregationFunctionEnum = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'percentile', 'median', 'stddev', 'variance',\n]).describe('Standard aggregation functions');\nexport type AggregationFunction = z.infer;\n\n/** Sort direction used across query, data-engine, analytics */\nexport const SortDirectionEnum = z.enum(['asc', 'desc'])\n .describe('Sort order direction');\nexport type SortDirection = z.infer;\n\n/** Reusable sort item — field + direction pair used across views, data sources, filters */\nexport const SortItemSchema = z.object({\n field: z.string().describe('Field name to sort by'),\n order: SortDirectionEnum.describe('Sort direction'),\n}).describe('Sort field and direction pair');\nexport type SortItem = z.infer;\n\n/** CRUD mutation events used across hook, validation, object CDC */\nexport const MutationEventEnum = z.enum([\n 'insert', 'update', 'delete', 'upsert',\n]).describe('Data mutation event types');\nexport type MutationEvent = z.infer;\n\n/** Database isolation levels — unified format */\nexport const IsolationLevelEnum = z.enum([\n 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable', 'snapshot',\n]).describe('Transaction isolation levels (snake_case standard)');\nexport type IsolationLevel = z.infer;\n\n/** Cache eviction strategies */\nexport const CacheStrategyEnum = z.enum(['lru', 'lfu', 'ttl', 'fifo'])\n .describe('Cache eviction strategy');\nexport type CacheStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from './identifiers.zod';\n\n// ============================================================================\n// Shared Metadata Types\n// ============================================================================\n\n/** Supported metadata file formats */\nexport const MetadataFormatSchema = z.enum(['yaml', 'json', 'typescript', 'javascript'])\n .describe('Metadata file format');\nexport type MetadataFormat = z.infer;\n\n/** Base metadata record fields shared across kernel and system layers */\nexport const BaseMetadataRecordSchema = z.object({\n id: z.string().describe('Unique metadata record identifier'),\n type: z.string().describe('Metadata type (e.g. \"object\", \"view\", \"flow\")'),\n name: SnakeCaseIdentifierSchema.describe('Machine name (snake_case)'),\n format: MetadataFormatSchema.optional().describe('Source file format'),\n}).describe('Base metadata record fields shared across kernel and system');\nexport type BaseMetadataRecord = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema, SystemIdentifierSchema } from './identifiers.zod';\n\n/**\n * Branded Types for ObjectStack Identifiers\n *\n * Branded types provide compile-time safety by preventing accidental mixing\n * of different identifier kinds. For example, you cannot pass an ObjectName\n * where a FieldName is expected, even though both are strings at runtime.\n *\n * @example\n * ```ts\n * import { ObjectNameSchema, FieldNameSchema } from '@objectstack/spec';\n *\n * const objName = ObjectNameSchema.parse('project_task'); // ObjectName\n * const fieldName = FieldNameSchema.parse('task_name'); // FieldName\n *\n * // TypeScript will catch this at compile time:\n * // const fn: FieldName = objName; // Error!\n * ```\n */\n\n/**\n * ObjectName — Branded type for business object names.\n *\n * Must be snake_case (no dots). Used for table/collection names.\n *\n * @example 'project_task', 'crm_account', 'user_profile'\n */\nexport const ObjectNameSchema = SnakeCaseIdentifierSchema\n .brand<'ObjectName'>()\n .describe('Branded object name (snake_case, no dots)');\n\nexport type ObjectName = z.infer;\n\n/**\n * FieldName — Branded type for field (column) names.\n *\n * Must be snake_case (no dots). Used for column/property names within objects.\n *\n * @example 'first_name', 'created_at', 'total_amount'\n */\nexport const FieldNameSchema = SnakeCaseIdentifierSchema\n .brand<'FieldName'>()\n .describe('Branded field name (snake_case, no dots)');\n\nexport type FieldName = z.infer;\n\n/**\n * ViewName — Branded type for view identifiers.\n *\n * Must be a valid system identifier (lowercase, may contain dots for namespacing).\n *\n * @example 'all_tasks', 'my_open_deals', 'contact.recent'\n */\nexport const ViewNameSchema = SystemIdentifierSchema\n .brand<'ViewName'>()\n .describe('Branded view name (system identifier)');\n\nexport type ViewName = z.infer;\n\n/**\n * AppName — Branded type for application identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'crm', 'helpdesk', 'project_management'\n */\nexport const AppNameSchema = SystemIdentifierSchema\n .brand<'AppName'>()\n .describe('Branded app name (system identifier)');\n\nexport type AppName = z.infer;\n\n/**\n * FlowName — Branded type for flow identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'approval_flow', 'onboarding_wizard', 'lead_qualification'\n */\nexport const FlowNameSchema = SystemIdentifierSchema\n .brand<'FlowName'>()\n .describe('Branded flow name (system identifier)');\n\nexport type FlowName = z.infer;\n\n/**\n * RoleName — Branded type for role identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'admin', 'sales_manager', 'read_only'\n */\nexport const RoleNameSchema = SystemIdentifierSchema\n .brand<'RoleName'>()\n .describe('Branded role name (system identifier)');\n\nexport type RoleName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { FieldType } from '../data/field.zod';\n\n/**\n * \"Did you mean?\" Suggestion Utilities\n *\n * Provides fuzzy matching for common ObjectStack identifiers.\n * Used by the custom error map to suggest corrections for typos.\n *\n * @example\n * ```ts\n * suggestFieldType('text_area'); // ['textarea']\n * suggestFieldType('String'); // ['text']\n * suggestFieldType('int'); // ['number']\n * ```\n */\n\n/**\n * Compute Levenshtein edit distance between two strings.\n * Uses space-optimized two-row approach (O(min(m,n)) space).\n */\nexport function levenshteinDistance(a: string, b: string): number {\n const la = a.length;\n const lb = b.length;\n\n if (la === 0) return lb;\n if (lb === 0) return la;\n\n // Use only two rows for space efficiency\n let prev = new Array(lb + 1);\n let curr = new Array(lb + 1);\n\n for (let j = 0; j <= lb; j++) {\n prev[j] = j;\n }\n\n for (let i = 1; i <= la; i++) {\n curr[0] = i;\n for (let j = 1; j <= lb; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n prev[j] + 1, // deletion\n curr[j - 1] + 1, // insertion\n prev[j - 1] + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n\n return prev[lb];\n}\n\n/**\n * Find the closest matches from a list of candidates.\n *\n * @param input - The user-provided (possibly invalid) value\n * @param candidates - Array of valid values to compare against\n * @param maxDistance - Maximum edit distance to consider (default: 3)\n * @param maxResults - Maximum number of suggestions to return (default: 3)\n * @returns Array of suggested values, sorted by similarity\n */\nexport function findClosestMatches(\n input: string,\n candidates: readonly string[],\n maxDistance = 3,\n maxResults = 3,\n): string[] {\n const normalized = input.toLowerCase().replace(/[-\\s]/g, '_');\n\n const scored = candidates\n .map((candidate) => ({\n value: candidate,\n distance: levenshteinDistance(normalized, candidate),\n }))\n .filter((s) => s.distance <= maxDistance && s.distance > 0)\n .sort((a, b) => a.distance - b.distance);\n\n return scored.slice(0, maxResults).map((s) => s.value);\n}\n\n/**\n * Well-known aliases that map common typos / alternative names to valid FieldTypes.\n */\nconst FIELD_TYPE_ALIASES: Record = {\n // Common alternative names\n string: 'text',\n str: 'text',\n varchar: 'text',\n char: 'text',\n int: 'number',\n integer: 'number',\n float: 'number',\n double: 'number',\n decimal: 'number',\n numeric: 'number',\n bool: 'boolean',\n checkbox: 'boolean',\n check: 'boolean',\n date_time: 'datetime',\n timestamp: 'datetime',\n // Common typos\n text_area: 'textarea',\n textarea_: 'textarea',\n textfield: 'text',\n dropdown: 'select',\n picklist: 'select',\n enum: 'select',\n multi_select: 'multiselect',\n multiselect_: 'multiselect',\n reference: 'lookup',\n ref: 'lookup',\n foreign_key: 'lookup',\n fk: 'lookup',\n relation: 'lookup',\n master: 'master_detail',\n richtext_: 'richtext',\n rich_text: 'richtext',\n upload: 'file',\n attachment: 'file',\n photo: 'image',\n picture: 'image',\n img: 'image',\n percent_: 'percent',\n percentage: 'percent',\n money: 'currency',\n price: 'currency',\n auto_number: 'autonumber',\n auto_increment: 'autonumber',\n sequence: 'autonumber',\n markdown_: 'markdown',\n md: 'markdown',\n barcode: 'qrcode',\n tag: 'tags',\n star: 'rating',\n stars: 'rating',\n geo: 'location',\n gps: 'location',\n coordinates: 'location',\n embed: 'vector',\n embedding: 'vector',\n embeddings: 'vector',\n};\n\n/**\n * Suggest valid FieldType values for an invalid input.\n *\n * First checks known aliases, then falls back to fuzzy matching.\n *\n * @param input - Invalid field type string\n * @returns Array of suggested valid FieldType values\n *\n * @example\n * ```ts\n * suggestFieldType('text_area'); // ['textarea']\n * suggestFieldType('String'); // ['text']\n * suggestFieldType('int'); // ['number']\n * suggestFieldType('dropdown'); // ['select']\n * ```\n */\nexport function suggestFieldType(input: string): string[] {\n const normalized = input.toLowerCase().replace(/[-\\s]/g, '_');\n\n // Check alias map first\n const alias = FIELD_TYPE_ALIASES[normalized];\n if (alias) {\n return [alias];\n }\n\n // Fall back to fuzzy matching\n return findClosestMatches(normalized, FieldType.options);\n}\n\n/**\n * Format a \"Did you mean?\" message for display.\n *\n * @param suggestions - Array of suggested values\n * @returns Formatted string or empty string if no suggestions\n */\nexport function formatSuggestion(suggestions: string[]): string {\n if (suggestions.length === 0) return '';\n if (suggestions.length === 1) return `Did you mean '${suggestions[0]}'?`;\n return `Did you mean one of: ${suggestions.map((s) => `'${s}'`).join(', ')}?`;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { suggestFieldType, formatSuggestion, findClosestMatches } from './suggestions.zod';\nimport { FieldType } from '../data/field.zod';\n\n/**\n * Zod v4 raw issue type used by the error map.\n */\nexport type ObjectStackRawIssue = z.core.$ZodRawIssue;\n\n/**\n * ObjectStack Custom Zod Error Map\n *\n * Provides contextual, actionable error messages for ObjectStack schema validation.\n * Instead of generic Zod messages like \"Invalid option\", this error map returns\n * messages that explain the ObjectStack context and suggest fixes.\n *\n * In Zod v4, the error map is a function `(issue) => { message: string } | string | null`.\n * Pass it via the `error` option on `.safeParse()` / `.parse()`.\n *\n * @example\n * ```ts\n * import { objectStackErrorMap } from '@objectstack/spec';\n *\n * // Per-parse usage\n * SomeSchema.safeParse(data, { error: objectStackErrorMap });\n * ```\n */\nexport const objectStackErrorMap = (issue: ObjectStackRawIssue): { message: string } | null => {\n // --- Invalid value (enum) with suggestions ---\n if (issue.code === 'invalid_value') {\n const values = issue.values as unknown[];\n const input = issue.input;\n const received = String(input ?? '');\n const options = values.map(String);\n\n // Check if this looks like a FieldType enum\n const fieldTypeOptions = FieldType.options as readonly string[];\n const isFieldTypeEnum = options.length > 10 &&\n fieldTypeOptions.every((ft) => options.includes(ft));\n\n if (isFieldTypeEnum) {\n const suggestions = suggestFieldType(received);\n const suggestion = formatSuggestion(suggestions);\n const base = `Invalid field type '${received}'.`;\n return {\n message: suggestion ? `${base} ${suggestion}` : `${base} Valid types: ${options.slice(0, 10).join(', ')}...`,\n };\n }\n\n // Generic enum suggestion\n const suggestions = findClosestMatches(received, options);\n const suggestion = formatSuggestion(suggestions);\n const base = `Invalid value '${received}'.`;\n return {\n message: suggestion\n ? `${base} ${suggestion}`\n : `${base} Expected one of: ${options.join(', ')}.`,\n };\n }\n\n // --- String/array/number size validation ---\n if (issue.code === 'too_small') {\n const origin = issue.origin as string;\n const minimum = issue.minimum as number;\n if (origin === 'string') {\n return {\n message: `Must be at least ${minimum} character${minimum === 1 ? '' : 's'} long.`,\n };\n }\n }\n\n if (issue.code === 'too_big') {\n const origin = issue.origin as string;\n const maximum = issue.maximum as number;\n if (origin === 'string') {\n return {\n message: `Must be at most ${maximum} character${maximum === 1 ? '' : 's'} long.`,\n };\n }\n }\n\n // --- String format validation (regex) ---\n if (issue.code === 'invalid_format') {\n const format = issue.format as string;\n const input = issue.input as string | undefined;\n if (format === 'regex' && input) {\n const pathArr = issue.path as (string | number)[] | undefined;\n const pathStr = pathArr?.join('.') ?? '';\n if (pathStr.endsWith('name') || pathStr === 'name') {\n return {\n message: `Invalid identifier '${input}'. Must be lowercase snake_case (e.g., 'my_object', 'task_name'). No uppercase, spaces, or hyphens allowed.`,\n };\n }\n }\n }\n\n // --- Missing required / type mismatch ---\n if (issue.code === 'invalid_type') {\n const expected = issue.expected as string;\n const input = issue.input;\n if (input === undefined) {\n const pathArr = issue.path as (string | number)[] | undefined;\n const field = pathArr?.[pathArr.length - 1] ?? '';\n return {\n message: `Required property '${field}' is missing.`,\n };\n }\n const receivedType = input === null ? 'null' : typeof input;\n return {\n message: `Expected ${expected} but received ${receivedType}.`,\n };\n }\n\n // --- Unrecognized keys ---\n if (issue.code === 'unrecognized_keys') {\n const keys = issue.keys as string[];\n const keyStr = keys.join(', ');\n return {\n message: `Unrecognized key${keys.length > 1 ? 's' : ''}: ${keyStr}. Check for typos in property names.`,\n };\n }\n\n // Fallback to Zod default\n return null;\n};\n\n/**\n * Zod Issue interface (subset needed for formatting).\n */\ninterface ZodIssueMinimal {\n path: PropertyKey[];\n message: string;\n code?: string;\n}\n\n/**\n * Format a single Zod issue into a human-readable line.\n *\n * @param issue - A single Zod issue\n * @returns Formatted string with path and message\n */\nexport function formatZodIssue(issue: ZodIssueMinimal): string {\n const path = issue.path.length > 0\n ? issue.path.join('.')\n : '(root)';\n return ` ✗ ${path}: ${issue.message}`;\n}\n\n/**\n * Pretty-print Zod validation errors for CLI output.\n *\n * Formats a ZodError into a readable block suitable for terminal display.\n * Groups errors by path depth and includes a summary count.\n *\n * @param error - A ZodError to format\n * @param label - Optional label for the error block (e.g., 'Stack validation failed')\n * @returns Formatted multi-line string\n *\n * @example\n * ```ts\n * import { formatZodError, ObjectStackDefinitionSchema } from '@objectstack/spec';\n *\n * const result = ObjectStackDefinitionSchema.safeParse(data);\n * if (!result.success) {\n * console.error(formatZodError(result.error, 'Stack validation failed'));\n * }\n * ```\n *\n * Output:\n * ```\n * Stack validation failed (3 issues):\n *\n * ✗ manifest.name: Required property 'name' is missing.\n * ✗ objects[0].fields.status.type: Invalid field type 'dropdown'. Did you mean 'select'?\n * ✗ views[0].object: Invalid identifier 'MyTasks'. Must be lowercase snake_case.\n * ```\n */\nexport function formatZodError(error: z.ZodError, label?: string): string {\n const count = error.issues.length;\n const header = label\n ? `${label} (${count} issue${count === 1 ? '' : 's'}):`\n : `Validation failed (${count} issue${count === 1 ? '' : 's'}):`;\n\n const lines = error.issues.map(formatZodIssue);\n\n return `${header}\\n\\n${lines.join('\\n')}`;\n}\n\n/**\n * Parse with the ObjectStack error map and return formatted errors.\n *\n * A convenience function that combines parsing with the custom error map\n * and pretty-print formatting. Returns a discriminated union result.\n *\n * @param schema - Any Zod schema to parse with\n * @param data - Data to validate\n * @param label - Optional label for error formatting\n * @returns Object with `success`, `data`, and optional `formatted` error string\n *\n * @example\n * ```ts\n * const result = safeParsePretty(ObjectStackDefinitionSchema, config, 'objectstack.config.ts');\n * if (!result.success) {\n * console.error(result.formatted);\n * process.exit(1);\n * }\n * ```\n */\nexport function safeParsePretty(\n schema: T,\n data: unknown,\n label?: string,\n): { success: true; data: z.infer } | { success: false; error: z.ZodError; formatted: string } {\n const result = schema.safeParse(data, { error: objectStackErrorMap });\n if (result.success) {\n return { success: true, data: result.data };\n }\n return {\n success: false,\n error: result.error,\n formatted: formatZodError(result.error, label),\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Metadata Collection Utilities\n * \n * Provides support for defining metadata collections in either array or map (Record) format.\n * Map format automatically injects the key as the `name` field, following the same pattern\n * used by `fields` in ObjectSchema (which already uses `z.record(key, FieldSchema)`).\n * \n * ## Usage\n * \n * Both formats are accepted and normalized to arrays:\n * \n * ```ts\n * // Array format (traditional)\n * defineStack({\n * objects: [\n * { name: 'account', fields: { ... } },\n * { name: 'contact', fields: { ... } },\n * ]\n * });\n * \n * // Map format (key becomes `name`)\n * defineStack({\n * objects: {\n * account: { fields: { ... } },\n * contact: { fields: { ... } },\n * }\n * });\n * ```\n * \n * @module\n */\n\n/**\n * Input type for metadata collections: accepts either an array or a named map.\n * When using map format, the key is injected as the `name` field of each item.\n * \n * @typeParam T - The metadata item type (e.g., `ObjectSchema`, `AppSchema`)\n * \n * @example\n * ```ts\n * // Array format — name is required in each item\n * const apps: MetadataCollectionInput = [\n * { name: 'sales', label: 'Sales' },\n * { name: 'service', label: 'Service' },\n * ];\n * \n * // Map format — key serves as name, so name is optional in value\n * const apps: MetadataCollectionInput = {\n * sales: { label: 'Sales' },\n * service: { label: 'Service' },\n * };\n * ```\n */\nexport type MetadataCollectionInput =\n | T[]\n | Record & { name?: string }>;\n\n/**\n * List of metadata fields in ObjectStackDefinitionSchema that support map format.\n * These are fields where each item has a `name` field that can be inferred from the map key.\n * \n * Excluded fields:\n * - `views` — ViewSchema has no `name` field (it's a container with `list`/`form`)\n * - `objectExtensions` — uses `extend` as its identifier, not `name`\n * - `data` — DatasetSchema uses `object` as its identifier\n * - `translations` — TranslationBundleSchema is a record, not a named object\n * - `plugins` / `devPlugins` — not named metadata schemas\n */\nexport const MAP_SUPPORTED_FIELDS = [\n 'objects',\n 'apps',\n 'pages',\n 'dashboards',\n 'reports',\n 'actions',\n 'themes',\n 'workflows',\n 'approvals',\n 'flows',\n 'roles',\n 'permissions',\n 'sharingRules',\n 'policies',\n 'apis',\n 'webhooks',\n 'agents',\n 'ragPipelines',\n 'hooks',\n 'mappings',\n 'analyticsCubes',\n 'connectors',\n 'datasources',\n] as const;\n\nexport type MapSupportedField = (typeof MAP_SUPPORTED_FIELDS)[number];\n\n/**\n * Mapping from plural manifest field names to singular metadata type names.\n *\n * Manifest / `defineStack()` uses plural property names because they are\n * collection fields (e.g. `objects: [...]`, `apps: [...]`). The metadata\n * registry and `MetadataTypeSchema` use singular names as the canonical form.\n *\n * Use this mapping at the boundary where manifest fields are fed into the\n * metadata registry to ensure a consistent singular naming convention.\n */\nexport const PLURAL_TO_SINGULAR: Record = {\n objects: 'object',\n apps: 'app',\n pages: 'page',\n dashboards: 'dashboard',\n reports: 'report',\n actions: 'action',\n themes: 'theme',\n workflows: 'workflow',\n approvals: 'approval',\n flows: 'flow',\n roles: 'role',\n permissions: 'permission',\n profiles: 'profile',\n sharingRules: 'sharingRule',\n policies: 'policy',\n apis: 'api',\n webhooks: 'webhook',\n agents: 'agent',\n ragPipelines: 'ragPipeline',\n hooks: 'hook',\n mappings: 'mapping',\n analyticsCubes: 'analyticsCube',\n connectors: 'connector',\n datasources: 'datasource',\n views: 'view',\n};\n\n/** Reverse mapping: singular metadata type → plural manifest field name. */\nexport const SINGULAR_TO_PLURAL: Record = Object.fromEntries(\n Object.entries(PLURAL_TO_SINGULAR).map(([plural, singular]) => [singular, plural]),\n);\n\n/** Convert a plural manifest field name to its singular metadata type name. Returns the input unchanged if no mapping exists. */\nexport function pluralToSingular(key: string): string {\n return PLURAL_TO_SINGULAR[key] ?? key;\n}\n\n/** Convert a singular metadata type name to its plural manifest field name. Returns the input unchanged if no mapping exists. */\nexport function singularToPlural(key: string): string {\n return SINGULAR_TO_PLURAL[key] ?? key;\n}\n\n\n/**\n * Normalize a single metadata collection value from map format to array format.\n * If the input is already an array (or nullish), it is returned unchanged.\n * If the input is a plain object (map), it is converted to an array where\n * each key is injected as the `name` field of the corresponding item.\n * \n * **Precedence:** If an item already has a `name` property, it is preserved\n * (the map key is only used as a fallback).\n * \n * @param value - The raw input value (array, map, or nullish)\n * @param keyField - The field name to inject the key into (default: `'name'`)\n * @returns The normalized array, or the original value if already an array/nullish\n * \n * @example\n * ```ts\n * // Map input\n * normalizeMetadataCollection({\n * account: { fields: { name: { type: 'text' } } },\n * contact: { fields: { email: { type: 'email' } } },\n * });\n * // → [\n * // { name: 'account', fields: { name: { type: 'text' } } },\n * // { name: 'contact', fields: { email: { type: 'email' } } },\n * // ]\n * \n * // Array input (pass-through)\n * normalizeMetadataCollection([{ name: 'account', fields: {} }]);\n * // → [{ name: 'account', fields: {} }]\n * ```\n */\nexport function normalizeMetadataCollection(value: unknown, keyField = 'name'): unknown {\n // Nullish or already an array — pass through\n if (value == null || Array.isArray(value)) return value;\n\n // Plain object — treat as map and convert to array\n if (typeof value === 'object') {\n return Object.entries(value as Record).map(([key, item]) => {\n if (item && typeof item === 'object' && !Array.isArray(item)) {\n const obj = item as Record;\n // Only inject key if the item doesn't already have the field set\n if (!(keyField in obj) || obj[keyField] === undefined) {\n return { ...obj, [keyField]: key };\n }\n return obj;\n }\n // Non-object values (shouldn't happen, but let Zod handle the error)\n return item;\n });\n }\n\n // Other types — return as-is and let Zod validation handle the error\n return value;\n}\n\n/**\n * Normalize all metadata collections in a stack definition input.\n * Converts any map-formatted collections to arrays with key→name injection.\n * \n * This function is applied to the raw input before Zod validation,\n * ensuring the canonical internal format is always arrays.\n * \n * @param input - The raw stack definition input\n * @returns A new object with all map collections normalized to arrays\n */\nexport function normalizeStackInput>(input: T): T {\n const result = { ...input };\n for (const field of MAP_SUPPORTED_FIELDS) {\n if (field in result) {\n (result as Record)[field] = normalizeMetadataCollection(result[field]);\n }\n }\n return result;\n}\n\n/**\n * Mapping of legacy / alternative field names to their canonical names\n * in `ObjectStackDefinitionSchema`.\n *\n * Plugins may use legacy names (e.g., `triggers` instead of `hooks`).\n * This map lets `normalizePluginMetadata()` rewrite them automatically.\n */\nexport const METADATA_ALIASES: Record = {\n triggers: 'hooks',\n};\n\n/**\n * Normalize plugin metadata so it matches the canonical format expected by the runtime.\n *\n * This handles two issues that commonly arise when loading third-party plugin metadata:\n *\n * 1. **Map → Array conversion** — plugins often define metadata as maps\n * (e.g., `actions: { convert_lead: { ... } }`), but the runtime expects arrays.\n * Every key listed in {@link MAP_SUPPORTED_FIELDS} is normalized via\n * {@link normalizeMetadataCollection}.\n *\n * 2. **Field aliasing** — plugins may use legacy or alternative field names\n * (e.g., `triggers` instead of `hooks`). {@link METADATA_ALIASES} maps them\n * to their canonical counterparts.\n *\n * 3. **Recursive normalization** — if the plugin itself contains nested `plugins`,\n * each nested plugin is normalized recursively.\n *\n * @param metadata - Raw plugin metadata object\n * @returns A new object with all collections normalized to arrays, aliases resolved,\n * and nested plugins recursively normalized\n *\n * @example\n * ```ts\n * const raw = {\n * actions: { lead_convert: { type: 'custom', label: 'Convert' } },\n * triggers: { lead_scoring: { object: 'lead', event: 'afterInsert' } },\n * };\n * const normalized = normalizePluginMetadata(raw);\n * // normalized.actions → [{ name: 'lead_convert', type: 'custom', label: 'Convert' }]\n * // normalized.hooks → [{ name: 'lead_scoring', object: 'lead', event: 'afterInsert' }]\n * // normalized.triggers → removed (merged into hooks)\n * ```\n */\nexport function normalizePluginMetadata>(metadata: T): T {\n const result = { ...metadata };\n\n // 1. Resolve aliases (e.g. triggers → hooks), merging with any existing canonical values\n for (const [alias, canonical] of Object.entries(METADATA_ALIASES)) {\n if (alias in result) {\n const aliasValue = normalizeMetadataCollection(result[alias]);\n const canonicalValue = normalizeMetadataCollection(result[canonical]);\n\n // Merge: canonical array wins; alias values are appended\n if (Array.isArray(aliasValue)) {\n (result as Record)[canonical] = Array.isArray(canonicalValue)\n ? [...canonicalValue, ...aliasValue]\n : aliasValue;\n }\n\n delete (result as Record)[alias];\n }\n }\n\n // 2. Normalize map-formatted collections → arrays\n for (const field of MAP_SUPPORTED_FIELDS) {\n if (field in result) {\n (result as Record)[field] = normalizeMetadataCollection(result[field]);\n }\n }\n\n // 3. Recursively normalize nested plugins\n if (Array.isArray(result.plugins)) {\n (result as Record).plugins = result.plugins.map((p: unknown) => {\n if (p && typeof p === 'object' && !Array.isArray(p)) {\n return normalizePluginMetadata(p as Record);\n }\n return p;\n });\n }\n\n return result;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ServiceObject, ObjectSchema, ObjectOwnership } from '@objectstack/spec/data';\nimport { ObjectStackManifest, ManifestSchema, InstalledPackage, InstalledPackageSchema } from '@objectstack/spec/kernel';\nimport { AppSchema } from '@objectstack/spec/ui';\n\n/**\n * Reserved namespaces that do not get FQN prefix applied.\n * Objects in these namespaces keep their short names (e.g., \"user\" not \"base__user\").\n */\nexport const RESERVED_NAMESPACES = new Set(['base', 'system']);\n\n/**\n * Default priorities for ownership types.\n */\nexport const DEFAULT_OWNER_PRIORITY = 100;\nexport const DEFAULT_EXTENDER_PRIORITY = 200;\n\n/**\n * Contributor Record\n * Tracks how a package contributes to an object (own or extend).\n */\nexport interface ObjectContributor {\n packageId: string;\n namespace: string;\n ownership: ObjectOwnership;\n priority: number;\n definition: ServiceObject;\n}\n\n/**\n * Compute Fully Qualified Name (FQN) for an object.\n * \n * @param namespace - The package namespace (e.g., \"crm\", \"todo\")\n * @param shortName - The object's short name (e.g., \"task\", \"account\")\n * @returns FQN string (e.g., \"crm__task\") or just shortName for reserved namespaces\n * \n * @example\n * computeFQN('crm', 'account') // => 'crm__account'\n * computeFQN('base', 'user') // => 'user' (reserved, no prefix)\n * computeFQN(undefined, 'task') // => 'task' (legacy, no namespace)\n */\nexport function computeFQN(namespace: string | undefined, shortName: string): string {\n if (!namespace || RESERVED_NAMESPACES.has(namespace)) {\n return shortName;\n }\n return `${namespace}__${shortName}`;\n}\n\n/**\n * Parse FQN back to namespace and short name.\n * \n * @param fqn - Fully qualified name (e.g., \"crm__account\" or \"user\")\n * @returns { namespace, shortName } - namespace is undefined for unprefixed names\n */\nexport function parseFQN(fqn: string): { namespace: string | undefined; shortName: string } {\n const idx = fqn.indexOf('__');\n if (idx === -1) {\n return { namespace: undefined, shortName: fqn };\n }\n return {\n namespace: fqn.slice(0, idx),\n shortName: fqn.slice(idx + 2),\n };\n}\n\n/**\n * Deep merge two ServiceObject definitions.\n * Fields are merged additively. Other props: later value wins.\n */\nfunction mergeObjectDefinitions(base: ServiceObject, extension: Partial): ServiceObject {\n const merged = { ...base };\n\n // Merge fields additively\n if (extension.fields) {\n merged.fields = { ...base.fields, ...extension.fields };\n }\n\n // Merge validations additively\n if (extension.validations) {\n merged.validations = [...(base.validations || []), ...extension.validations];\n }\n\n // Merge indexes additively\n if (extension.indexes) {\n merged.indexes = [...(base.indexes || []), ...extension.indexes];\n }\n\n // Override scalar props (last writer wins)\n if (extension.label !== undefined) merged.label = extension.label;\n if (extension.pluralLabel !== undefined) merged.pluralLabel = extension.pluralLabel;\n if (extension.description !== undefined) merged.description = extension.description;\n\n return merged;\n}\n\n/**\n * Global Schema Registry\n * Unified storage for all metadata types (Objects, Apps, Flows, Layouts, etc.)\n * \n * ## Namespace & Ownership Model\n * \n * Objects use a namespace-based FQN system:\n * - `namespace`: Short identifier from package manifest (e.g., \"crm\", \"todo\")\n * - `FQN`: `{namespace}__{short_name}` (e.g., \"crm__account\")\n * - Reserved namespaces (`base`, `system`) don't get prefixed\n * \n * Ownership modes:\n * - `own`: One package owns the object (creates the table, defines base schema)\n * - `extend`: Multiple packages can extend an object (add fields, merge by priority)\n * \n * ## Package vs App Distinction\n * - **Package**: The unit of installation, stored under type 'package'.\n * Each InstalledPackage wraps a ManifestSchema with lifecycle state.\n * - **App**: A UI navigation shell (AppSchema), registered under type 'apps'.\n * Apps are extracted from packages during registration.\n * - A package may contain 0, 1, or many apps.\n */\nexport type RegistryLogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\nexport class SchemaRegistry {\n // ==========================================\n // Logging control\n // ==========================================\n\n /** Controls verbosity of registry console messages. Default: 'info'. */\n private static _logLevel: RegistryLogLevel = 'info';\n\n static get logLevel(): RegistryLogLevel { return this._logLevel; }\n static set logLevel(level: RegistryLogLevel) { this._logLevel = level; }\n\n private static log(msg: string): void {\n if (this._logLevel === 'silent' || this._logLevel === 'error' || this._logLevel === 'warn') return;\n console.log(msg);\n }\n\n // ==========================================\n // Object-specific storage (Ownership Model)\n // ==========================================\n \n /** FQN → Contributor[] (all packages that own/extend this object) */\n private static objectContributors = new Map();\n \n /** FQN → Merged ServiceObject (cached, invalidated on changes) */\n private static mergedObjectCache = new Map();\n \n /** Namespace → Set (multiple packages can share a namespace) */\n private static namespaceRegistry = new Map>();\n\n // ==========================================\n // Generic metadata storage (non-object types)\n // ==========================================\n \n /** Type → Name/ID → MetadataItem */\n private static metadata = new Map>();\n\n // ==========================================\n // Namespace Management\n // ==========================================\n\n /**\n * Register a namespace for a package.\n * Multiple packages can share the same namespace (e.g. 'sys').\n */\n static registerNamespace(namespace: string, packageId: string): void {\n if (!namespace) return;\n\n let owners = this.namespaceRegistry.get(namespace);\n if (!owners) {\n owners = new Set();\n this.namespaceRegistry.set(namespace, owners);\n }\n owners.add(packageId);\n this.log(`[Registry] Registered namespace: ${namespace} → ${packageId}`);\n }\n\n /**\n * Unregister a namespace when a package is uninstalled.\n */\n static unregisterNamespace(namespace: string, packageId: string): void {\n const owners = this.namespaceRegistry.get(namespace);\n if (owners) {\n owners.delete(packageId);\n if (owners.size === 0) {\n this.namespaceRegistry.delete(namespace);\n }\n this.log(`[Registry] Unregistered namespace: ${namespace} ← ${packageId}`);\n }\n }\n\n /**\n * Get the packages that use a namespace.\n */\n static getNamespaceOwner(namespace: string): string | undefined {\n const owners = this.namespaceRegistry.get(namespace);\n if (!owners || owners.size === 0) return undefined;\n // Return the first registered package for backwards compatibility\n return owners.values().next().value;\n }\n\n /**\n * Get all packages that share a namespace.\n */\n static getNamespaceOwners(namespace: string): string[] {\n const owners = this.namespaceRegistry.get(namespace);\n return owners ? Array.from(owners) : [];\n }\n\n // ==========================================\n // Object Registration (Ownership Model)\n // ==========================================\n\n /**\n * Register an object with ownership semantics.\n * \n * @param schema - The object definition\n * @param packageId - The owning package ID\n * @param namespace - The package namespace (for FQN computation)\n * @param ownership - 'own' (single owner) or 'extend' (additive merge)\n * @param priority - Merge priority (lower applied first, higher wins on conflict)\n * \n * @throws Error if trying to 'own' an object that already has an owner\n */\n static registerObject(\n schema: ServiceObject,\n packageId: string,\n namespace?: string,\n ownership: ObjectOwnership = 'own',\n priority: number = ownership === 'own' ? DEFAULT_OWNER_PRIORITY : DEFAULT_EXTENDER_PRIORITY\n ): string {\n const shortName = schema.name;\n const fqn = computeFQN(namespace, shortName);\n\n // Ensure namespace is registered\n if (namespace) {\n this.registerNamespace(namespace, packageId);\n }\n\n // Get or create contributor list\n let contributors = this.objectContributors.get(fqn);\n if (!contributors) {\n contributors = [];\n this.objectContributors.set(fqn, contributors);\n }\n\n // Validate ownership rules\n if (ownership === 'own') {\n const existingOwner = contributors.find(c => c.ownership === 'own');\n if (existingOwner && existingOwner.packageId !== packageId) {\n throw new Error(\n `Object \"${fqn}\" is already owned by package \"${existingOwner.packageId}\". ` +\n `Package \"${packageId}\" cannot claim ownership. Use 'extend' to add fields.`\n );\n }\n // Remove existing owner contribution from same package (re-registration)\n const idx = contributors.findIndex(c => c.packageId === packageId && c.ownership === 'own');\n if (idx !== -1) {\n contributors.splice(idx, 1);\n console.warn(`[Registry] Re-registering owned object: ${fqn} from ${packageId}`);\n }\n } else {\n // extend mode: remove existing extension from same package\n const idx = contributors.findIndex(c => c.packageId === packageId && c.ownership === 'extend');\n if (idx !== -1) {\n contributors.splice(idx, 1);\n }\n }\n\n // Add new contributor\n const contributor: ObjectContributor = {\n packageId,\n namespace: namespace || '',\n ownership,\n priority,\n definition: { ...schema, name: fqn }, // Store with FQN as name\n };\n contributors.push(contributor);\n\n // Sort by priority (ascending: lower priority applied first)\n contributors.sort((a, b) => a.priority - b.priority);\n\n // Invalidate merge cache\n this.mergedObjectCache.delete(fqn);\n\n this.log(`[Registry] Registered object: ${fqn} (${ownership}, priority=${priority}) from ${packageId}`);\n return fqn;\n }\n\n /**\n * Resolve an object by FQN, merging all contributions.\n * Returns the merged object or undefined if not found.\n */\n static resolveObject(fqn: string): ServiceObject | undefined {\n // Check cache first\n const cached = this.mergedObjectCache.get(fqn);\n if (cached) return cached;\n\n const contributors = this.objectContributors.get(fqn);\n if (!contributors || contributors.length === 0) {\n return undefined;\n }\n\n // Find owner (must exist for a valid object)\n const ownerContrib = contributors.find(c => c.ownership === 'own');\n if (!ownerContrib) {\n console.warn(`[Registry] Object \"${fqn}\" has extenders but no owner. Skipping.`);\n return undefined;\n }\n\n // Start with owner's definition\n let merged = { ...ownerContrib.definition };\n\n // Apply extensions in priority order (already sorted)\n for (const contrib of contributors) {\n if (contrib.ownership === 'extend') {\n merged = mergeObjectDefinitions(merged, contrib.definition);\n }\n }\n\n // Cache the result\n this.mergedObjectCache.set(fqn, merged);\n return merged;\n }\n\n /**\n * Get object by name (FQN, short name, or physical table name).\n *\n * Resolution order:\n * 1. Exact FQN match (e.g., 'crm__account')\n * 2. Short name fallback (e.g., 'account' → 'crm__account')\n * 3. Physical table name match (e.g., 'sys_user' → 'sys__user')\n * ObjectSchema.create() auto-derives tableName as {namespace}_{name},\n * which uses a single underscore — different from the FQN double underscore.\n */\n static getObject(name: string): ServiceObject | undefined {\n // Direct FQN lookup\n const direct = this.resolveObject(name);\n if (direct) return direct;\n\n // Fallback: scan for objects ending with the short name\n // This handles legacy code that doesn't use FQN\n for (const fqn of this.objectContributors.keys()) {\n const { shortName } = parseFQN(fqn);\n if (shortName === name) {\n return this.resolveObject(fqn);\n }\n }\n\n // Fallback: match by physical table name (e.g., 'sys_user' → FQN 'sys__user')\n // This bridges the gap between protocol names (SystemObjectName) and FQN.\n for (const fqn of this.objectContributors.keys()) {\n const resolved = this.resolveObject(fqn);\n if (resolved?.tableName === name) {\n return resolved;\n }\n }\n\n return undefined;\n }\n\n /**\n * Get all registered objects (merged).\n * \n * @param packageId - Optional filter: only objects contributed by this package\n */\n static getAllObjects(packageId?: string): ServiceObject[] {\n const results: ServiceObject[] = [];\n\n for (const fqn of this.objectContributors.keys()) {\n // If filtering by package, check if this package contributes\n if (packageId) {\n const contributors = this.objectContributors.get(fqn);\n const hasContribution = contributors?.some(c => c.packageId === packageId);\n if (!hasContribution) continue;\n }\n\n const merged = this.resolveObject(fqn);\n if (merged) {\n // Tag with contributor info for UI\n (merged as any)._packageId = this.getObjectOwner(fqn)?.packageId;\n results.push(merged);\n }\n }\n\n return results;\n }\n\n /**\n * Get all contributors for an object.\n */\n static getObjectContributors(fqn: string): ObjectContributor[] {\n return this.objectContributors.get(fqn) || [];\n }\n\n /**\n * Get the owner contributor for an object.\n */\n static getObjectOwner(fqn: string): ObjectContributor | undefined {\n const contributors = this.objectContributors.get(fqn);\n return contributors?.find(c => c.ownership === 'own');\n }\n\n /**\n * Unregister all objects contributed by a package.\n * \n * @throws Error if trying to uninstall an owner that has extenders\n */\n static unregisterObjectsByPackage(packageId: string, force: boolean = false): void {\n for (const [fqn, contributors] of this.objectContributors.entries()) {\n // Find this package's contributions\n const packageContribs = contributors.filter(c => c.packageId === packageId);\n \n for (const contrib of packageContribs) {\n if (contrib.ownership === 'own' && !force) {\n // Check if there are extenders from other packages\n const otherExtenders = contributors.filter(\n c => c.packageId !== packageId && c.ownership === 'extend'\n );\n if (otherExtenders.length > 0) {\n throw new Error(\n `Cannot uninstall package \"${packageId}\": object \"${fqn}\" is extended by ` +\n `${otherExtenders.map(c => c.packageId).join(', ')}. Uninstall extenders first.`\n );\n }\n }\n\n // Remove contribution\n const idx = contributors.indexOf(contrib);\n if (idx !== -1) {\n contributors.splice(idx, 1);\n this.log(`[Registry] Removed ${contrib.ownership} contribution to ${fqn} from ${packageId}`);\n }\n }\n\n // Clean up empty contributor lists\n if (contributors.length === 0) {\n this.objectContributors.delete(fqn);\n }\n\n // Invalidate cache\n this.mergedObjectCache.delete(fqn);\n }\n }\n\n // ==========================================\n // Generic Metadata (Non-Object Types)\n // ==========================================\n\n /**\n * Universal Register Method for non-object metadata.\n */\n static registerItem(type: string, item: T, keyField: keyof T = 'name' as keyof T, packageId?: string) {\n if (!this.metadata.has(type)) {\n this.metadata.set(type, new Map());\n }\n const collection = this.metadata.get(type)!;\n const baseName = String(item[keyField]);\n \n // Tag item with owning package for scoped queries\n if (packageId) {\n (item as any)._packageId = packageId;\n }\n\n // Validation Hook\n try {\n this.validate(type, item);\n } catch (e: any) {\n console.error(`[Registry] Validation failed for ${type} ${baseName}: ${e.message}`);\n }\n\n // Use composite key (packageId:name) when packageId is provided\n const storageKey = packageId ? `${packageId}:${baseName}` : baseName;\n\n if (collection.has(storageKey)) {\n console.warn(`[Registry] Overwriting ${type}: ${storageKey}`);\n }\n collection.set(storageKey, item);\n this.log(`[Registry] Registered ${type}: ${storageKey}`);\n }\n\n /**\n * Validate Metadata against Spec Zod Schemas\n */\n static validate(type: string, item: any) {\n if (type === 'object') {\n return ObjectSchema.parse(item);\n }\n if (type === 'app') {\n return AppSchema.parse(item);\n }\n if (type === 'package') {\n return InstalledPackageSchema.parse(item);\n }\n if (type === 'plugin') {\n return ManifestSchema.parse(item);\n }\n return true;\n }\n\n /**\n * Universal Unregister Method\n */\n static unregisterItem(type: string, name: string) {\n const collection = this.metadata.get(type);\n if (!collection) {\n console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`);\n return;\n }\n if (collection.has(name)) {\n collection.delete(name);\n this.log(`[Registry] Unregistered ${type}: ${name}`);\n return;\n }\n // Scan composite keys\n for (const key of collection.keys()) {\n if (key.endsWith(`:${name}`)) {\n collection.delete(key);\n this.log(`[Registry] Unregistered ${type}: ${key}`);\n return;\n }\n }\n console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`);\n }\n\n /**\n * Universal Get Method\n */\n static getItem(type: string, name: string): T | undefined {\n // Special handling for 'object' and 'objects' types - use objectContributors\n if (type === 'object' || type === 'objects') {\n return this.getObject(name) as unknown as T | undefined;\n }\n \n const collection = this.metadata.get(type);\n if (!collection) return undefined;\n const direct = collection.get(name);\n if (direct) return direct as T;\n // Scan for composite keys\n for (const [key, item] of collection) {\n if (key.endsWith(`:${name}`)) return item as T;\n }\n return undefined;\n }\n\n /**\n * Universal List Method\n */\n static listItems(type: string, packageId?: string): T[] {\n // Special handling for 'object' and 'objects' types - use objectContributors\n if (type === 'object' || type === 'objects') {\n return this.getAllObjects(packageId) as unknown as T[];\n }\n\n const items = Array.from(this.metadata.get(type)?.values() || []) as T[];\n if (packageId) {\n return items.filter((item: any) => item._packageId === packageId);\n }\n return items;\n }\n\n /**\n * Get all registered metadata types (Kinds)\n */\n static getRegisteredTypes(): string[] {\n const types = Array.from(this.metadata.keys());\n // Always include 'object' even if stored separately\n if (!types.includes('object') && this.objectContributors.size > 0) {\n types.push('object');\n }\n return types;\n }\n\n // ==========================================\n // Package Management\n // ==========================================\n\n static installPackage(manifest: ObjectStackManifest, settings?: Record): InstalledPackage {\n const now = new Date().toISOString();\n const pkg: InstalledPackage = {\n manifest,\n status: 'installed',\n enabled: true,\n installedAt: now,\n updatedAt: now,\n settings,\n };\n \n // Register namespace if present\n if (manifest.namespace) {\n this.registerNamespace(manifest.namespace, manifest.id);\n }\n \n if (!this.metadata.has('package')) {\n this.metadata.set('package', new Map());\n }\n const collection = this.metadata.get('package')!;\n if (collection.has(manifest.id)) {\n console.warn(`[Registry] Overwriting package: ${manifest.id}`);\n }\n collection.set(manifest.id, pkg);\n this.log(`[Registry] Installed package: ${manifest.id} (${manifest.name})`);\n return pkg;\n }\n\n static uninstallPackage(id: string): boolean {\n const pkg = this.getPackage(id);\n if (!pkg) {\n console.warn(`[Registry] Package not found for uninstall: ${id}`);\n return false;\n }\n\n // Unregister namespace\n if (pkg.manifest.namespace) {\n this.unregisterNamespace(pkg.manifest.namespace, id);\n }\n\n // Unregister objects (will throw if extenders exist)\n this.unregisterObjectsByPackage(id);\n\n // Remove package record\n const collection = this.metadata.get('package');\n if (collection) {\n collection.delete(id);\n this.log(`[Registry] Uninstalled package: ${id}`);\n return true;\n }\n return false;\n }\n\n static getPackage(id: string): InstalledPackage | undefined {\n return this.metadata.get('package')?.get(id) as InstalledPackage | undefined;\n }\n\n static getAllPackages(): InstalledPackage[] {\n return this.listItems('package');\n }\n\n static enablePackage(id: string): InstalledPackage | undefined {\n const pkg = this.getPackage(id);\n if (pkg) {\n pkg.enabled = true;\n pkg.status = 'installed';\n pkg.statusChangedAt = new Date().toISOString();\n pkg.updatedAt = new Date().toISOString();\n this.log(`[Registry] Enabled package: ${id}`);\n }\n return pkg;\n }\n\n static disablePackage(id: string): InstalledPackage | undefined {\n const pkg = this.getPackage(id);\n if (pkg) {\n pkg.enabled = false;\n pkg.status = 'disabled';\n pkg.statusChangedAt = new Date().toISOString();\n pkg.updatedAt = new Date().toISOString();\n this.log(`[Registry] Disabled package: ${id}`);\n }\n return pkg;\n }\n\n // ==========================================\n // App Helpers\n // ==========================================\n\n static registerApp(app: any, packageId?: string) {\n this.registerItem('app', app, 'name', packageId);\n }\n\n static getApp(name: string): any {\n return this.getItem('app', name);\n }\n\n static getAllApps(): any[] {\n return this.listItems('app');\n }\n\n // ==========================================\n // Plugin Helpers\n // ==========================================\n\n static registerPlugin(manifest: ObjectStackManifest) {\n this.registerItem('plugin', manifest, 'id');\n }\n\n static getAllPlugins(): ObjectStackManifest[] {\n return this.listItems('plugin');\n }\n\n // ==========================================\n // Kind Helpers\n // ==========================================\n\n static registerKind(kind: { id: string, globs: string[] }) {\n this.registerItem('kind', kind, 'id');\n }\n \n static getAllKinds(): { id: string, globs: string[] }[] {\n return this.listItems('kind');\n }\n\n // ==========================================\n // Reset (for testing)\n // ==========================================\n\n /**\n * Clear all registry state. Use only for testing.\n */\n static reset(): void {\n this.objectContributors.clear();\n this.mergedObjectCache.clear();\n this.namespaceRegistry.clear();\n this.metadata.clear();\n this.log('[Registry] Reset complete');\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectStackProtocol } from '@objectstack/spec/api';\nimport { IDataEngine } from '@objectstack/core';\nimport type {\n BatchUpdateRequest,\n BatchUpdateResponse,\n UpdateManyDataRequest,\n DeleteManyDataRequest\n} from '@objectstack/spec/api';\nimport type { MetadataCacheRequest, MetadataCacheResponse, ServiceInfo, ApiRoutes, WellKnownCapabilities } from '@objectstack/spec/api';\nimport type { IFeedService } from '@objectstack/spec/contracts';\nimport { parseFilterAST, isFilterAST } from '@objectstack/spec/data';\nimport { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared';\n\n// We import SchemaRegistry directly since this class lives in the same package\nimport { SchemaRegistry } from './registry.js';\n\n/**\n * Simple hash function for ETag generation (browser-compatible)\n * Uses a basic hash algorithm instead of crypto.createHash\n */\nfunction simpleHash(str: string): string {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return Math.abs(hash).toString(16);\n}\n\n/**\n * Service Configuration for Discovery\n * Maps service names to their routes and plugin providers\n */\nconst SERVICE_CONFIG: Record = {\n auth: { route: '/api/v1/auth', plugin: 'plugin-auth' },\n automation: { route: '/api/v1/automation', plugin: 'plugin-automation' },\n cache: { route: '/api/v1/cache', plugin: 'plugin-redis' },\n queue: { route: '/api/v1/queue', plugin: 'plugin-bullmq' },\n job: { route: '/api/v1/jobs', plugin: 'job-scheduler' },\n ui: { route: '/api/v1/ui', plugin: 'ui-plugin' },\n workflow: { route: '/api/v1/workflow', plugin: 'plugin-workflow' },\n realtime: { route: '/api/v1/realtime', plugin: 'plugin-realtime' },\n notification: { route: '/api/v1/notifications', plugin: 'plugin-notifications' },\n ai: { route: '/api/v1/ai', plugin: 'plugin-ai' },\n i18n: { route: '/api/v1/i18n', plugin: 'service-i18n' },\n graphql: { route: '/graphql', plugin: 'plugin-graphql' }, // GraphQL uses /graphql by convention (not versioned REST)\n 'file-storage': { route: '/api/v1/storage', plugin: 'plugin-storage' },\n search: { route: '/api/v1/search', plugin: 'plugin-search' },\n};\n\nexport class ObjectStackProtocolImplementation implements ObjectStackProtocol {\n private engine: IDataEngine;\n private getServicesRegistry?: () => Map;\n private getFeedService?: () => IFeedService | undefined;\n\n constructor(engine: IDataEngine, getServicesRegistry?: () => Map, getFeedService?: () => IFeedService | undefined) {\n this.engine = engine;\n this.getServicesRegistry = getServicesRegistry;\n this.getFeedService = getFeedService;\n }\n\n private requireFeedService(): IFeedService {\n const svc = this.getFeedService?.();\n if (!svc) {\n throw new Error('Feed service not available. Install and register service-feed to enable feed operations.');\n }\n return svc;\n }\n\n async getDiscovery() {\n // Get registered services from kernel if available\n const registeredServices = this.getServicesRegistry ? this.getServicesRegistry() : new Map();\n \n // Build dynamic service info with proper typing\n const services: Record = {\n // --- Kernel-provided (objectql is an example kernel implementation) ---\n metadata: { enabled: true, status: 'available' as const, route: '/api/v1/meta', provider: 'objectql' },\n data: { enabled: true, status: 'available' as const, route: '/api/v1/data', provider: 'objectql' },\n analytics: { enabled: true, status: 'available' as const, route: '/api/v1/analytics', provider: 'objectql' },\n };\n\n // Check which services are actually registered\n for (const [serviceName, config] of Object.entries(SERVICE_CONFIG)) {\n if (registeredServices.has(serviceName)) {\n // Service is registered and available\n services[serviceName] = {\n enabled: true,\n status: 'available' as const,\n route: config.route,\n provider: config.plugin,\n };\n } else {\n // Service is not registered\n services[serviceName] = {\n enabled: false,\n status: 'unavailable' as const,\n message: `Install ${config.plugin} to enable`,\n };\n }\n }\n\n // Build routes from services — a flat convenience map for client routing\n const serviceToRouteKey: Record = {\n auth: 'auth',\n automation: 'automation',\n ui: 'ui',\n workflow: 'workflow',\n realtime: 'realtime',\n notification: 'notifications',\n ai: 'ai',\n i18n: 'i18n',\n graphql: 'graphql',\n 'file-storage': 'storage',\n };\n\n const optionalRoutes: Partial = {\n analytics: '/api/v1/analytics',\n };\n\n // Add routes for available plugin services\n for (const [serviceName, config] of Object.entries(SERVICE_CONFIG)) {\n if (registeredServices.has(serviceName)) {\n const routeKey = serviceToRouteKey[serviceName];\n if (routeKey) {\n optionalRoutes[routeKey] = config.route;\n }\n }\n }\n\n // Add feed service status\n if (registeredServices.has('feed')) {\n services['feed'] = {\n enabled: true,\n status: 'available' as const,\n route: '/api/v1/data',\n provider: 'service-feed',\n };\n } else {\n services['feed'] = {\n enabled: false,\n status: 'unavailable' as const,\n message: 'Install service-feed to enable',\n };\n }\n\n const routes: ApiRoutes = {\n data: '/api/v1/data',\n metadata: '/api/v1/meta',\n ...optionalRoutes,\n };\n\n // Build well-known capabilities from registered services.\n // DiscoverySchema defines capabilities as Record\n // (hierarchical format). We also keep a flat WellKnownCapabilities for backward compat.\n const wellKnown: WellKnownCapabilities = {\n feed: registeredServices.has('feed'),\n comments: registeredServices.has('feed'),\n automation: registeredServices.has('automation'),\n cron: registeredServices.has('job'),\n search: registeredServices.has('search'),\n export: registeredServices.has('automation') || registeredServices.has('queue'),\n chunkedUpload: registeredServices.has('file-storage'),\n };\n\n // Convert flat booleans → hierarchical capability objects\n const capabilities: Record = {};\n for (const [key, enabled] of Object.entries(wellKnown)) {\n capabilities[key] = { enabled };\n }\n\n return {\n version: '1.0',\n apiName: 'ObjectStack API',\n routes,\n services,\n capabilities,\n };\n }\n\n async getMetaTypes() {\n const schemaTypes = SchemaRegistry.getRegisteredTypes();\n\n // Also include types from MetadataService (runtime-registered: agent, tool, etc.)\n let runtimeTypes: string[] = [];\n try {\n const services = this.getServicesRegistry?.();\n const metadataService = services?.get('metadata');\n if (metadataService && typeof metadataService.getRegisteredTypes === 'function') {\n runtimeTypes = await metadataService.getRegisteredTypes();\n }\n } catch {\n // MetadataService not available\n }\n\n const allTypes = Array.from(new Set([...schemaTypes, ...runtimeTypes]));\n return { types: allTypes };\n }\n\n async getMetaItems(request: { type: string; packageId?: string }) {\n const { packageId } = request;\n let items = SchemaRegistry.listItems(request.type, packageId);\n // Normalize singular/plural using explicit mapping\n if (items.length === 0) {\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) items = SchemaRegistry.listItems(alt, packageId);\n }\n\n // Fallback to database if registry is empty for this type\n if (items.length === 0) {\n try {\n const whereClause: any = { type: request.type, state: 'active' };\n if (packageId) whereClause._packageId = packageId;\n const allRecords = await this.engine.find('sys_metadata', {\n where: whereClause\n });\n if (allRecords && allRecords.length > 0) {\n items = allRecords.map((record: any) => {\n const data = typeof record.metadata === 'string'\n ? JSON.parse(record.metadata)\n : record.metadata;\n // Hydrate back into registry\n SchemaRegistry.registerItem(request.type, data, 'name' as any);\n return data;\n });\n } else {\n // Try alternate type name in DB using explicit mapping\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) {\n const altRecords = await this.engine.find('sys_metadata', {\n where: { type: alt, state: 'active' }\n });\n if (altRecords && altRecords.length > 0) {\n items = altRecords.map((record: any) => {\n const data = typeof record.metadata === 'string'\n ? JSON.parse(record.metadata)\n : record.metadata;\n SchemaRegistry.registerItem(request.type, data, 'name' as any);\n return data;\n });\n }\n }\n }\n } catch {\n // DB not available, return registry results (empty)\n }\n }\n\n // Merge with MetadataService (runtime-registered items: agents, tools, etc.)\n try {\n const services = this.getServicesRegistry?.();\n const metadataService = services?.get('metadata');\n if (metadataService && typeof metadataService.list === 'function') {\n const runtimeItems = await metadataService.list(request.type);\n if (runtimeItems && runtimeItems.length > 0) {\n // Merge, avoiding duplicates by name\n const itemMap = new Map();\n for (const item of items) {\n const entry = item as any;\n if (entry && typeof entry === 'object' && 'name' in entry) {\n itemMap.set(entry.name, entry);\n }\n }\n for (const item of runtimeItems) {\n const entry = item as any;\n if (entry && typeof entry === 'object' && 'name' in entry) {\n itemMap.set(entry.name, entry);\n }\n }\n items = Array.from(itemMap.values());\n }\n }\n } catch {\n // MetadataService not available or doesn't support this type\n }\n\n return {\n type: request.type,\n items\n };\n }\n\n async getMetaItem(request: { type: string, name: string, packageId?: string }) {\n let item = SchemaRegistry.getItem(request.type, request.name);\n // Normalize singular/plural using explicit mapping\n if (item === undefined) {\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) item = SchemaRegistry.getItem(alt, request.name);\n }\n\n // Fallback to database if not in registry\n if (item === undefined) {\n try {\n const record = await this.engine.findOne('sys_metadata', {\n where: { type: request.type, name: request.name, state: 'active' }\n });\n if (record) {\n item = typeof record.metadata === 'string'\n ? JSON.parse(record.metadata)\n : record.metadata;\n // Hydrate back into registry for next time\n SchemaRegistry.registerItem(request.type, item, 'name' as any);\n } else {\n // Try alternate type name using explicit mapping\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) {\n const altRecord = await this.engine.findOne('sys_metadata', {\n where: { type: alt, name: request.name, state: 'active' }\n });\n if (altRecord) {\n item = typeof altRecord.metadata === 'string'\n ? JSON.parse(altRecord.metadata)\n : altRecord.metadata;\n // Hydrate back into registry for next time\n SchemaRegistry.registerItem(request.type, item, 'name' as any);\n }\n }\n }\n } catch {\n // DB not available, return undefined\n }\n }\n\n // Fallback to MetadataService for runtime-registered items (agents, tools, etc.)\n if (item === undefined) {\n try {\n const services = this.getServicesRegistry?.();\n const metadataService = services?.get('metadata');\n if (metadataService && typeof metadataService.get === 'function') {\n item = await metadataService.get(request.type, request.name);\n }\n } catch {\n // MetadataService not available\n }\n }\n\n return {\n type: request.type,\n name: request.name,\n item\n };\n }\n\n async getUiView(request: { object: string, type: 'list' | 'form' }) {\n const schema = SchemaRegistry.getObject(request.object);\n if (!schema) throw new Error(`Object ${request.object} not found`);\n\n const fields = schema.fields || {};\n const fieldKeys = Object.keys(fields);\n\n if (request.type === 'list') {\n // Intelligent Column Selection\n // 1. Always include 'name' or name-like fields\n // 2. Limit to 6 columns by default\n const priorityFields = ['name', 'title', 'label', 'subject', 'email', 'status', 'type', 'category', 'created_at'];\n \n let columns = fieldKeys.filter(k => priorityFields.includes(k));\n \n // If few priority fields, add others until 5\n if (columns.length < 5) {\n const remaining = fieldKeys.filter(k => !columns.includes(k) && k !== 'id' && !fields[k].hidden);\n columns = [...columns, ...remaining.slice(0, 5 - columns.length)];\n }\n \n // Sort columns by priority then alphabet or schema order\n // For now, just keep them roughly in order they appear in schema or priority list\n \n return {\n list: {\n type: 'grid' as const,\n object: request.object,\n label: schema.label || schema.name,\n columns: columns.map(f => ({\n field: f,\n label: fields[f]?.label || f,\n sortable: true\n })),\n sort: fields['created_at'] ? ([{ field: 'created_at', order: 'desc' }] as any) : undefined,\n searchableFields: columns.slice(0, 3) // Make first few textual columns searchable\n }\n };\n } else {\n // Form View Generation\n // Simple single-section layout for now\n const formFields = fieldKeys\n .filter(k => k !== 'id' && k !== 'created_at' && k !== 'updated_at' && !fields[k].hidden)\n .map(f => ({\n field: f,\n label: fields[f]?.label,\n required: fields[f]?.required,\n readonly: fields[f]?.readonly,\n type: fields[f]?.type,\n // Default to 2 columns for most, 1 for textareas\n colSpan: (fields[f]?.type === 'textarea' || fields[f]?.type === 'html') ? 2 : 1\n }));\n\n return {\n form: {\n type: 'simple' as const,\n object: request.object,\n label: `Edit ${schema.label || schema.name}`,\n sections: [\n {\n label: 'General Information',\n columns: 2 as const,\n collapsible: false,\n collapsed: false,\n fields: formFields\n }\n ]\n }\n };\n }\n }\n\n async findData(request: { object: string, query?: any }) {\n const options: any = { ...request.query };\n\n // ====================================================================\n // Normalize legacy params → QueryAST standard (where/fields/orderBy/offset/expand)\n // ====================================================================\n\n // Numeric fields — normalize top → limit, skip → offset\n if (options.top != null) {\n options.limit = Number(options.top);\n delete options.top;\n }\n if (options.skip != null) {\n options.offset = Number(options.skip);\n delete options.skip;\n }\n if (options.limit != null) options.limit = Number(options.limit);\n if (options.offset != null) options.offset = Number(options.offset);\n\n // Select → fields: comma-separated string → array\n if (typeof options.select === 'string') {\n options.fields = options.select.split(',').map((s: string) => s.trim()).filter(Boolean);\n } else if (Array.isArray(options.select)) {\n options.fields = options.select;\n }\n if (options.select !== undefined) delete options.select;\n\n // Sort/orderBy → orderBy: string → SortNode[] array\n const sortValue = options.orderBy ?? options.sort;\n if (typeof sortValue === 'string') {\n const parsed = sortValue.split(',').map((part: string) => {\n const trimmed = part.trim();\n if (trimmed.startsWith('-')) {\n return { field: trimmed.slice(1), order: 'desc' as const };\n }\n const [field, order] = trimmed.split(/\\s+/);\n return { field, order: (order?.toLowerCase() === 'desc' ? 'desc' : 'asc') as 'asc' | 'desc' };\n }).filter((s: any) => s.field);\n options.orderBy = parsed;\n } else if (Array.isArray(sortValue)) {\n options.orderBy = sortValue;\n }\n delete options.sort;\n\n // Filter/filters/$filter → where: normalize all filter aliases\n const filterValue = options.filter ?? options.filters ?? options.$filter ?? options.where;\n delete options.filter;\n delete options.filters;\n delete options.$filter;\n\n if (filterValue !== undefined) {\n let parsedFilter = filterValue;\n // JSON string → object\n if (typeof parsedFilter === 'string') {\n try { parsedFilter = JSON.parse(parsedFilter); } catch { /* keep as-is */ }\n }\n // Filter AST array → FilterCondition object\n if (isFilterAST(parsedFilter)) {\n parsedFilter = parseFilterAST(parsedFilter);\n }\n options.where = parsedFilter;\n }\n\n // Populate/expand/$expand → expand (Record)\n const populateValue = options.populate;\n const expandValue = options.$expand ?? options.expand;\n const expandNames: string[] = [];\n if (typeof populateValue === 'string') {\n expandNames.push(...populateValue.split(',').map((s: string) => s.trim()).filter(Boolean));\n } else if (Array.isArray(populateValue)) {\n expandNames.push(...populateValue);\n }\n if (!expandNames.length && expandValue) {\n if (typeof expandValue === 'string') {\n expandNames.push(...expandValue.split(',').map((s: string) => s.trim()).filter(Boolean));\n } else if (Array.isArray(expandValue)) {\n expandNames.push(...expandValue);\n }\n }\n delete options.populate;\n delete options.$expand;\n // Clean up non-object expand (e.g. string) BEFORE the Record conversion\n // below, so that populate-derived names can create the expand Record even\n // when a legacy string expand was also present.\n if (typeof options.expand !== 'object' || options.expand === null) {\n delete options.expand;\n }\n // Only set expand if not already an object (advanced usage)\n if (expandNames.length > 0 && !options.expand) {\n options.expand = {} as Record;\n for (const rel of expandNames) {\n options.expand[rel] = { object: rel };\n }\n }\n\n // Boolean fields\n for (const key of ['distinct', 'count']) {\n if (options[key] === 'true') options[key] = true;\n else if (options[key] === 'false') options[key] = false;\n }\n \n // Flat field filters: REST-style query params like ?id=abc&status=open\n // After extracting all known query parameters, any remaining keys are\n // treated as implicit field-level equality filters merged into `where`.\n const knownParams = new Set([\n 'top', 'limit', 'offset',\n 'orderBy',\n 'fields',\n 'where',\n 'expand',\n 'distinct', 'count',\n 'aggregations', 'groupBy',\n 'search', 'context', 'cursor',\n ]);\n if (!options.where) {\n const implicitFilters: Record = {};\n for (const key of Object.keys(options)) {\n if (!knownParams.has(key)) {\n implicitFilters[key] = options[key];\n delete options[key];\n }\n }\n if (Object.keys(implicitFilters).length > 0) {\n options.where = implicitFilters;\n }\n }\n \n const records = await this.engine.find(request.object, options);\n // Spec: FindDataResponseSchema — only `records` is returned.\n // OData `value` adaptation (if needed) is handled in the HTTP dispatch layer.\n return {\n object: request.object,\n records,\n total: records.length,\n hasMore: false\n };\n }\n\n async getData(request: { object: string, id: string, expand?: string | string[], select?: string | string[] }) {\n const queryOptions: any = {\n where: { id: request.id }\n };\n\n // Support fields for single-record retrieval\n if (request.select) {\n queryOptions.fields = typeof request.select === 'string'\n ? request.select.split(',').map((s: string) => s.trim()).filter(Boolean)\n : request.select;\n }\n\n // Support expand for single-record retrieval\n if (request.expand) {\n const expandNames = typeof request.expand === 'string'\n ? request.expand.split(',').map((s: string) => s.trim()).filter(Boolean)\n : request.expand;\n queryOptions.expand = {} as Record;\n for (const rel of expandNames) {\n queryOptions.expand[rel] = { object: rel };\n }\n }\n\n const result = await this.engine.findOne(request.object, queryOptions);\n if (result) {\n return {\n object: request.object,\n id: request.id,\n record: result\n };\n }\n throw new Error(`Record ${request.id} not found in ${request.object}`);\n }\n\n async createData(request: { object: string, data: any }) {\n const result = await this.engine.insert(request.object, request.data);\n return {\n object: request.object,\n id: result.id,\n record: result\n };\n }\n\n async updateData(request: { object: string, id: string, data: any }) {\n // Adapt: update(obj, id, data) -> update(obj, data, options)\n const result = await this.engine.update(request.object, request.data, { where: { id: request.id } });\n return {\n object: request.object,\n id: request.id,\n record: result\n };\n }\n\n async deleteData(request: { object: string, id: string }) {\n // Adapt: delete(obj, id) -> delete(obj, options)\n await this.engine.delete(request.object, { where: { id: request.id } });\n return {\n object: request.object,\n id: request.id,\n success: true\n };\n }\n\n // ==========================================\n // Metadata Caching\n // ==========================================\n\n async getMetaItemCached(request: { type: string, name: string, cacheRequest?: MetadataCacheRequest }): Promise {\n try {\n let item = SchemaRegistry.getItem(request.type, request.name);\n\n // Normalize singular/plural using explicit mapping\n if (!item) {\n const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];\n if (alt) item = SchemaRegistry.getItem(alt, request.name);\n }\n\n // Fallback to MetadataService (e.g. agents, tools registered in MetadataManager)\n if (!item) {\n try {\n const services = this.getServicesRegistry?.();\n const metadataService = services?.get('metadata');\n if (metadataService && typeof metadataService.get === 'function') {\n item = await metadataService.get(request.type, request.name);\n }\n } catch {\n // MetadataService not available\n }\n }\n\n if (!item) {\n throw new Error(`Metadata item ${request.type}/${request.name} not found`);\n }\n\n // Calculate ETag (simple hash of the stringified metadata)\n const content = JSON.stringify(item);\n const hash = simpleHash(content);\n const etag = { value: hash, weak: false };\n\n // Check If-None-Match header\n if (request.cacheRequest?.ifNoneMatch) {\n const clientEtag = request.cacheRequest.ifNoneMatch.replace(/^\"(.*)\"$/, '$1').replace(/^W\\/\"(.*)\"$/, '$1');\n if (clientEtag === hash) {\n // Return 304 Not Modified\n return {\n notModified: true,\n etag,\n };\n }\n }\n\n // Return full metadata with cache headers\n return {\n data: item,\n etag,\n lastModified: new Date().toISOString(),\n cacheControl: {\n directives: ['public', 'max-age'],\n maxAge: 3600, // 1 hour\n },\n notModified: false,\n };\n } catch (error: any) {\n throw error;\n }\n }\n\n // ==========================================\n // Batch Operations\n // ==========================================\n\n async batchData(request: { object: string, request: BatchUpdateRequest }): Promise {\n const { object, request: batchReq } = request;\n const { operation, records, options } = batchReq;\n const results: Array<{ id?: string; success: boolean; error?: string; record?: any }> = [];\n let succeeded = 0;\n let failed = 0;\n\n for (const record of records) {\n try {\n switch (operation) {\n case 'create': {\n const created = await this.engine.insert(object, record.data || record);\n results.push({ id: created.id, success: true, record: created });\n succeeded++;\n break;\n }\n case 'update': {\n if (!record.id) throw new Error('Record id is required for update');\n const updated = await this.engine.update(object, record.data || {}, { where: { id: record.id } });\n results.push({ id: record.id, success: true, record: updated });\n succeeded++;\n break;\n }\n case 'upsert': {\n // Try update first, then create if not found\n if (record.id) {\n try {\n const existing = await this.engine.findOne(object, { where: { id: record.id } });\n if (existing) {\n const updated = await this.engine.update(object, record.data || {}, { where: { id: record.id } });\n results.push({ id: record.id, success: true, record: updated });\n } else {\n const created = await this.engine.insert(object, { id: record.id, ...(record.data || {}) });\n results.push({ id: created.id, success: true, record: created });\n }\n } catch {\n const created = await this.engine.insert(object, { id: record.id, ...(record.data || {}) });\n results.push({ id: created.id, success: true, record: created });\n }\n } else {\n const created = await this.engine.insert(object, record.data || record);\n results.push({ id: created.id, success: true, record: created });\n }\n succeeded++;\n break;\n }\n case 'delete': {\n if (!record.id) throw new Error('Record id is required for delete');\n await this.engine.delete(object, { where: { id: record.id } });\n results.push({ id: record.id, success: true });\n succeeded++;\n break;\n }\n default:\n results.push({ id: record.id, success: false, error: `Unknown operation: ${operation}` });\n failed++;\n }\n } catch (err: any) {\n results.push({ id: record.id, success: false, error: err.message });\n failed++;\n if (options?.atomic) {\n // Abort remaining operations on first failure in atomic mode\n break;\n }\n if (!options?.continueOnError) {\n break;\n }\n }\n }\n\n return {\n success: failed === 0,\n operation,\n total: records.length,\n succeeded,\n failed,\n results: options?.returnRecords !== false ? results : results.map(r => ({ id: r.id, success: r.success, error: r.error })),\n } as BatchUpdateResponse;\n }\n \n async createManyData(request: { object: string, records: any[] }): Promise {\n const records = await this.engine.insert(request.object, request.records);\n return {\n object: request.object,\n records,\n count: records.length\n };\n }\n \n async updateManyData(request: UpdateManyDataRequest): Promise {\n const { object, records, options } = request;\n const results: Array<{ id?: string; success: boolean; error?: string; record?: any }> = [];\n let succeeded = 0;\n let failed = 0;\n\n for (const record of records) {\n try {\n const updated = await this.engine.update(object, record.data, { where: { id: record.id } });\n results.push({ id: record.id, success: true, record: updated });\n succeeded++;\n } catch (err: any) {\n results.push({ id: record.id, success: false, error: err.message });\n failed++;\n if (!options?.continueOnError) {\n break;\n }\n }\n }\n\n return {\n success: failed === 0,\n operation: 'update',\n total: records.length,\n succeeded,\n failed,\n results,\n } as BatchUpdateResponse;\n }\n\n async analyticsQuery(request: any): Promise {\n // Map AnalyticsQuery (cube-style) to engine aggregation.\n // cube name maps to object name; measures → aggregations; dimensions → groupBy.\n const { query, cube } = request;\n const object = cube;\n\n // Build groupBy from dimensions\n const groupBy = query.dimensions || [];\n\n // Build aggregations from measures\n // Measures can be simple field names like \"count\" or \"field_name.sum\"\n // Or cube-defined measure names. We support: field.function or just function(field).\n const aggregations: Array<{ field: string; method: string; alias: string }> = [];\n if (query.measures) {\n for (const measure of query.measures) {\n // Support formats: \"count\", \"amount.sum\", \"revenue.avg\"\n if (measure === 'count' || measure === 'count_all') {\n aggregations.push({ field: '*', method: 'count', alias: 'count' });\n } else if (measure.includes('.')) {\n const [field, method] = measure.split('.');\n aggregations.push({ field, method, alias: `${field}_${method}` });\n } else {\n // Treat as count of the field\n aggregations.push({ field: measure, method: 'sum', alias: measure });\n }\n }\n }\n\n // Build filter from analytics filters\n let filter: any = undefined;\n if (query.filters && query.filters.length > 0) {\n const conditions: any[] = query.filters.map((f: any) => {\n const op = this.mapAnalyticsOperator(f.operator);\n if (f.values && f.values.length === 1) {\n return { [f.member]: { [op]: f.values[0] } };\n } else if (f.values && f.values.length > 1) {\n return { [f.member]: { $in: f.values } };\n }\n return { [f.member]: { [op]: true } };\n });\n filter = conditions.length === 1 ? conditions[0] : { $and: conditions };\n }\n\n // Execute via engine.aggregate (which delegates to driver.find with groupBy/aggregations)\n const rows = await this.engine.aggregate(object, {\n where: filter,\n groupBy: groupBy.length > 0 ? groupBy : undefined,\n aggregations: aggregations.length > 0\n ? aggregations.map(a => ({ function: a.method as any, field: a.field, alias: a.alias }))\n : [{ function: 'count' as any, alias: 'count' }],\n });\n\n // Build field metadata\n const fields = [\n ...groupBy.map((d: string) => ({ name: d, type: 'string' })),\n ...aggregations.map(a => ({ name: a.alias, type: 'number' })),\n ];\n\n return {\n success: true,\n data: {\n rows,\n fields,\n },\n };\n }\n\n async getAnalyticsMeta(request: any): Promise {\n // Auto-generate cube metadata from registered objects in SchemaRegistry.\n // Each object becomes a cube; number fields → measures; other fields → dimensions.\n const objects = SchemaRegistry.listItems('object');\n const cubeFilter = request?.cube;\n\n const cubes: any[] = [];\n for (const obj of objects) {\n const schema = obj as any;\n if (cubeFilter && schema.name !== cubeFilter) continue;\n\n const measures: Record = {};\n const dimensions: Record = {};\n const fields = schema.fields || {};\n\n // Always add a count measure\n measures['count'] = {\n name: 'count',\n label: 'Count',\n type: 'count',\n sql: '*',\n };\n\n for (const [fieldName, fieldDef] of Object.entries(fields)) {\n const fd = fieldDef as any;\n const fieldType = fd.type || 'text';\n\n if (['number', 'currency', 'percent'].includes(fieldType)) {\n // Numeric fields become both measures and dimensions\n measures[`${fieldName}_sum`] = {\n name: `${fieldName}_sum`,\n label: `${fd.label || fieldName} (Sum)`,\n type: 'sum',\n sql: fieldName,\n };\n measures[`${fieldName}_avg`] = {\n name: `${fieldName}_avg`,\n label: `${fd.label || fieldName} (Avg)`,\n type: 'avg',\n sql: fieldName,\n };\n dimensions[fieldName] = {\n name: fieldName,\n label: fd.label || fieldName,\n type: 'number',\n sql: fieldName,\n };\n } else if (['date', 'datetime'].includes(fieldType)) {\n dimensions[fieldName] = {\n name: fieldName,\n label: fd.label || fieldName,\n type: 'time',\n sql: fieldName,\n granularities: ['day', 'week', 'month', 'quarter', 'year'],\n };\n } else if (['boolean'].includes(fieldType)) {\n dimensions[fieldName] = {\n name: fieldName,\n label: fd.label || fieldName,\n type: 'boolean',\n sql: fieldName,\n };\n } else {\n // text, select, lookup, etc. → dimension\n dimensions[fieldName] = {\n name: fieldName,\n label: fd.label || fieldName,\n type: 'string',\n sql: fieldName,\n };\n }\n }\n\n cubes.push({\n name: schema.name,\n title: schema.label || schema.name,\n description: schema.description,\n sql: schema.name,\n measures,\n dimensions,\n public: true,\n });\n }\n\n return {\n success: true,\n data: { cubes },\n };\n }\n\n private mapAnalyticsOperator(op: string): string {\n const map: Record = {\n equals: '$eq',\n notEquals: '$ne',\n contains: '$contains',\n notContains: '$notContains',\n gt: '$gt',\n gte: '$gte',\n lt: '$lt',\n lte: '$lte',\n set: '$ne',\n notSet: '$eq',\n };\n return map[op] || '$eq';\n }\n\n async triggerAutomation(_request: any): Promise {\n throw new Error('triggerAutomation requires plugin-automation service. Install and register a plugin that provides the \"automation\" service.');\n }\n\n async deleteManyData(request: DeleteManyDataRequest): Promise {\n // This expects deleting by IDs.\n return this.engine.delete(request.object, {\n where: { id: { $in: request.ids } },\n ...request.options\n });\n }\n\n async saveMetaItem(request: { type: string, name: string, item?: any }) {\n if (!request.item) {\n throw new Error('Item data is required');\n }\n\n // 1. Always update the in-memory registry (runtime cache)\n SchemaRegistry.registerItem(request.type, request.item, 'name');\n\n // 2. Persist to database via data engine\n try {\n const now = new Date().toISOString();\n // Check if record exists\n const existing = await this.engine.findOne('sys_metadata', {\n where: { type: request.type, name: request.name }\n });\n\n if (existing) {\n await this.engine.update('sys_metadata', {\n metadata: JSON.stringify(request.item),\n updated_at: now,\n version: (existing.version || 0) + 1,\n }, {\n where: { id: existing.id }\n });\n } else {\n // Use crypto.randomUUID() when available (modern browsers and Node ≥ 14.17);\n // fall back to a time+random ID for older or restricted environments.\n const id = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : `meta_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n await this.engine.insert('sys_metadata', {\n id,\n name: request.name,\n type: request.type,\n scope: 'platform',\n metadata: JSON.stringify(request.item),\n state: 'active',\n version: 1,\n created_at: now,\n updated_at: now,\n });\n }\n\n return {\n success: true,\n message: 'Saved to database and registry'\n };\n } catch (dbError: any) {\n // DB write failed but in-memory registry was updated — degrade gracefully\n console.warn(`[Protocol] DB persistence failed for ${request.type}/${request.name}: ${dbError.message}`);\n return {\n success: true,\n message: 'Saved to memory registry (DB persistence unavailable)',\n warning: dbError.message\n };\n }\n }\n\n /**\n * Hydrate SchemaRegistry from the database on startup.\n * Loads all active metadata records and registers them in the in-memory registry.\n * Safe to call repeatedly — idempotent (latest DB record wins).\n */\n async loadMetaFromDb(): Promise<{ loaded: number; errors: number }> {\n let loaded = 0;\n let errors = 0;\n try {\n const records = await this.engine.find('sys_metadata', {\n where: { state: 'active' }\n });\n for (const record of records) {\n try {\n const data = typeof record.metadata === 'string'\n ? JSON.parse(record.metadata)\n : record.metadata;\n // Normalize DB type to singular (DB may store legacy plural forms)\n const normalizedType = PLURAL_TO_SINGULAR[record.type] ?? record.type;\n if (normalizedType === 'object') {\n SchemaRegistry.registerObject(data as any, record.packageId || 'sys_metadata');\n } else {\n SchemaRegistry.registerItem(normalizedType, data, 'name' as any);\n }\n loaded++;\n } catch (e) {\n errors++;\n console.warn(`[Protocol] Failed to hydrate ${record.type}/${record.name}: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n } catch (e: any) {\n console.warn(`[Protocol] DB hydration skipped: ${e.message}`);\n }\n return { loaded, errors };\n }\n\n // ==========================================\n // Feed Operations\n // ==========================================\n\n async listFeed(request: any): Promise {\n const svc = this.requireFeedService();\n const result = await svc.listFeed({\n object: request.object,\n recordId: request.recordId,\n filter: request.type,\n limit: request.limit,\n cursor: request.cursor,\n });\n return { success: true, data: result };\n }\n\n async createFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.createFeedItem({\n object: request.object,\n recordId: request.recordId,\n type: request.type,\n actor: { type: 'user', id: 'current_user' },\n body: request.body,\n mentions: request.mentions,\n parentId: request.parentId,\n visibility: request.visibility,\n });\n return { success: true, data: item };\n }\n\n async updateFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.updateFeedItem(request.feedId, {\n body: request.body,\n mentions: request.mentions,\n visibility: request.visibility,\n });\n return { success: true, data: item };\n }\n\n async deleteFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n await svc.deleteFeedItem(request.feedId);\n return { success: true, data: { feedId: request.feedId } };\n }\n\n async addReaction(request: any): Promise {\n const svc = this.requireFeedService();\n const reactions = await svc.addReaction(request.feedId, request.emoji, 'current_user');\n return { success: true, data: { reactions } };\n }\n\n async removeReaction(request: any): Promise {\n const svc = this.requireFeedService();\n const reactions = await svc.removeReaction(request.feedId, request.emoji, 'current_user');\n return { success: true, data: { reactions } };\n }\n\n async pinFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.getFeedItem(request.feedId);\n if (!item) throw new Error(`Feed item ${request.feedId} not found`);\n // IFeedService doesn't have dedicated pin/unpin — use updateFeedItem to persist pin state\n await svc.updateFeedItem(request.feedId, { visibility: item.visibility });\n return { success: true, data: { feedId: request.feedId, pinned: true, pinnedAt: new Date().toISOString() } };\n }\n\n async unpinFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.getFeedItem(request.feedId);\n if (!item) throw new Error(`Feed item ${request.feedId} not found`);\n await svc.updateFeedItem(request.feedId, { visibility: item.visibility });\n return { success: true, data: { feedId: request.feedId, pinned: false } };\n }\n\n async starFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.getFeedItem(request.feedId);\n if (!item) throw new Error(`Feed item ${request.feedId} not found`);\n // IFeedService doesn't have dedicated star/unstar — verify item exists then return state\n await svc.updateFeedItem(request.feedId, { visibility: item.visibility });\n return { success: true, data: { feedId: request.feedId, starred: true, starredAt: new Date().toISOString() } };\n }\n\n async unstarFeedItem(request: any): Promise {\n const svc = this.requireFeedService();\n const item = await svc.getFeedItem(request.feedId);\n if (!item) throw new Error(`Feed item ${request.feedId} not found`);\n await svc.updateFeedItem(request.feedId, { visibility: item.visibility });\n return { success: true, data: { feedId: request.feedId, starred: false } };\n }\n\n async searchFeed(request: any): Promise {\n const svc = this.requireFeedService();\n // Search delegates to listFeed with filter since IFeedService doesn't have a dedicated search\n const result = await svc.listFeed({\n object: request.object,\n recordId: request.recordId,\n filter: request.type,\n limit: request.limit,\n cursor: request.cursor,\n });\n // Filter by query text in body\n const queryLower = (request.query || '').toLowerCase();\n const filtered = result.items.filter((item: any) =>\n item.body?.toLowerCase().includes(queryLower)\n );\n return { success: true, data: { items: filtered, total: filtered.length, hasMore: false } };\n }\n\n async getChangelog(request: any): Promise {\n const svc = this.requireFeedService();\n // Changelog retrieves field_change type feed items\n const result = await svc.listFeed({\n object: request.object,\n recordId: request.recordId,\n filter: 'changes_only',\n limit: request.limit,\n cursor: request.cursor,\n });\n const entries = result.items.map((item: any) => ({\n id: item.id,\n object: item.object,\n recordId: item.recordId,\n actor: item.actor,\n changes: item.changes || [],\n timestamp: item.createdAt,\n source: item.source,\n }));\n return { success: true, data: { entries, total: result.total, nextCursor: result.nextCursor, hasMore: result.hasMore } };\n }\n\n async feedSubscribe(request: any): Promise {\n const svc = this.requireFeedService();\n const subscription = await svc.subscribe({\n object: request.object,\n recordId: request.recordId,\n userId: 'current_user',\n events: request.events,\n channels: request.channels,\n });\n return { success: true, data: subscription };\n }\n\n async feedUnsubscribe(request: any): Promise {\n const svc = this.requireFeedService();\n const unsubscribed = await svc.unsubscribe(request.object, request.recordId, 'current_user');\n return { success: true, data: { object: request.object, recordId: request.recordId, unsubscribed } };\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { QueryAST, HookContext, ServiceObject } from '@objectstack/spec/data';\nimport {\n EngineQueryOptions,\n DataEngineInsertOptions,\n EngineUpdateOptions,\n EngineDeleteOptions,\n EngineAggregateOptions,\n EngineCountOptions\n} from '@objectstack/spec/data';\nimport { ExecutionContext, ExecutionContextSchema } from '@objectstack/spec/kernel';\nimport { DriverInterface, IDataEngine, Logger, createLogger } from '@objectstack/core';\nimport { CoreServiceName } from '@objectstack/spec/system';\nimport { IRealtimeService, RealtimeEventPayload } from '@objectstack/spec/contracts';\nimport { pluralToSingular } from '@objectstack/spec/shared';\nimport { SchemaRegistry } from './registry.js';\n\nexport type HookHandler = (context: HookContext) => Promise | void;\n\n/**\n * Per-object hook entry with priority support\n */\nexport interface HookEntry {\n handler: HookHandler;\n object?: string | string[]; // undefined = global hook\n priority: number;\n packageId?: string;\n}\n\n/**\n * Operation Context for Middleware Chain\n */\nexport interface OperationContext {\n object: string;\n operation: 'find' | 'findOne' | 'insert' | 'update' | 'delete' | 'count' | 'aggregate';\n ast?: QueryAST;\n data?: any;\n options?: any;\n context?: ExecutionContext;\n result?: any;\n}\n\n/**\n * Engine Middleware (Onion model)\n */\nexport type EngineMiddleware = (\n ctx: OperationContext,\n next: () => Promise\n) => Promise;\n\n/**\n * Host Context provided to plugins (Internal ObjectQL Plugin System)\n */\nexport interface ObjectQLHostContext {\n ql: ObjectQL;\n logger: Logger;\n // Extensible map for host-specific globals (like HTTP Router, etc.)\n [key: string]: any;\n}\n\n/**\n * ObjectQL Engine\n * \n * Implements the IDataEngine interface for data persistence.\n * Acts as the reference implementation for:\n * - CoreServiceName.data (CRUD)\n * - CoreServiceName.metadata (Schema Registry)\n */\nexport class ObjectQL implements IDataEngine {\n private drivers = new Map();\n private defaultDriver: string | null = null;\n private logger: Logger;\n\n // Per-object hooks with priority support\n private hooks: Map = new Map([\n ['beforeFind', []], ['afterFind', []],\n ['beforeInsert', []], ['afterInsert', []],\n ['beforeUpdate', []], ['afterUpdate', []],\n ['beforeDelete', []], ['afterDelete', []],\n ]);\n\n // Middleware chain (onion model)\n private middlewares: Array<{\n fn: EngineMiddleware;\n object?: string;\n }> = [];\n\n // Action registry: key = \"objectName:actionName\"\n private actions = new Map Promise | any; package?: string }>();\n\n // Host provided context additions (e.g. Server router)\n private hostContext: Record = {};\n\n // Realtime service for event publishing\n private realtimeService?: IRealtimeService;\n\n constructor(hostContext: Record = {}) {\n this.hostContext = hostContext;\n // Use provided logger or create a new one\n this.logger = hostContext.logger || createLogger({ level: 'info', format: 'pretty' });\n this.logger.info('ObjectQL Engine Instance Created');\n }\n\n /**\n * Service Status Report\n * Used by Kernel to verify health and capabilities.\n */\n getStatus() {\n return {\n name: CoreServiceName.enum.data,\n status: 'running',\n version: '0.9.0',\n features: ['crud', 'query', 'aggregate', 'transactions', 'metadata']\n };\n }\n\n /**\n * Expose the SchemaRegistry for plugins to register metadata\n */\n get registry() {\n return SchemaRegistry;\n }\n\n /**\n * Load and Register a Plugin\n */\n async use(manifestPart: any, runtimePart?: any) {\n this.logger.debug('Loading plugin', { \n hasManifest: !!manifestPart, \n hasRuntime: !!runtimePart \n });\n\n // 1. Validate / Register Manifest\n if (manifestPart) {\n this.registerApp(manifestPart);\n }\n\n // 2. Execute Runtime\n if (runtimePart) {\n const pluginDef = (runtimePart as any).default || runtimePart;\n if (pluginDef.onEnable) {\n this.logger.debug('Executing plugin runtime onEnable');\n \n const context: ObjectQLHostContext = {\n ql: this,\n logger: this.logger,\n // Expose the driver registry helper explicitly if needed\n drivers: {\n register: (driver: DriverInterface) => this.registerDriver(driver)\n },\n ...this.hostContext\n };\n \n await pluginDef.onEnable(context);\n this.logger.debug('Plugin runtime onEnable completed');\n }\n }\n }\n\n /**\n * Register a hook\n * @param event The event name (e.g. 'beforeFind', 'afterInsert')\n * @param handler The handler function\n * @param options Optional: target object(s) and priority\n */\n registerHook(event: string, handler: HookHandler, options?: {\n object?: string | string[];\n priority?: number;\n packageId?: string;\n }) {\n if (!this.hooks.has(event)) {\n this.hooks.set(event, []);\n }\n const entries = this.hooks.get(event)!;\n entries.push({\n handler,\n object: options?.object,\n priority: options?.priority ?? 100,\n packageId: options?.packageId,\n });\n // Sort by priority (lower runs first)\n entries.sort((a, b) => a.priority - b.priority);\n this.logger.debug('Registered hook', { event, object: options?.object, priority: options?.priority ?? 100, totalHandlers: entries.length });\n }\n\n public async triggerHooks(event: string, context: HookContext) {\n const entries = this.hooks.get(event) || [];\n \n if (entries.length === 0) {\n this.logger.debug('No hooks registered for event', { event });\n return;\n }\n\n this.logger.debug('Triggering hooks', { event, count: entries.length });\n \n for (const entry of entries) {\n // Per-object matching\n if (entry.object) {\n const targets = Array.isArray(entry.object) ? entry.object : [entry.object];\n if (!targets.includes('*') && !targets.includes(context.object)) {\n continue; // Skip non-matching hooks\n }\n }\n await entry.handler(context);\n }\n }\n\n // ========================================\n // Action System\n // ========================================\n\n /**\n * Register a named action on an object.\n * Actions are custom business logic callable via `repo.execute(actionName, params)`.\n *\n * @param objectName Target object\n * @param actionName Unique action name within the object\n * @param handler Handler function\n * @param packageName Optional package owner (for cleanup)\n */\n registerAction(objectName: string, actionName: string, handler: (ctx: any) => Promise | any, packageName?: string): void {\n const key = `${objectName}:${actionName}`;\n this.actions.set(key, { handler, package: packageName });\n this.logger.debug('Registered action', { objectName, actionName, package: packageName });\n }\n\n /**\n * Execute a named action on an object.\n */\n async executeAction(objectName: string, actionName: string, ctx: any): Promise {\n const entry = this.actions.get(`${objectName}:${actionName}`);\n if (!entry) {\n throw new Error(`Action '${actionName}' on object '${objectName}' not found`);\n }\n return entry.handler(ctx);\n }\n\n /**\n * Remove all actions registered by a specific package.\n */\n removeActionsByPackage(packageName: string): void {\n for (const [key, entry] of this.actions.entries()) {\n if (entry.package === packageName) {\n this.actions.delete(key);\n }\n }\n }\n\n /**\n * Register a middleware function\n * Middlewares execute in onion model around every data operation.\n * @param fn The middleware function\n * @param options Optional: target object filter\n */\n registerMiddleware(fn: EngineMiddleware, options?: { object?: string }): void {\n this.middlewares.push({ fn, object: options?.object });\n this.logger.debug('Registered middleware', { object: options?.object, total: this.middlewares.length });\n }\n\n /**\n * Execute an operation through the middleware chain\n */\n private async executeWithMiddleware(ctx: OperationContext, executor: () => Promise): Promise {\n const applicable = this.middlewares.filter(m =>\n !m.object || m.object === '*' || m.object === ctx.object\n );\n\n let index = 0;\n const next = async (): Promise => {\n if (index < applicable.length) {\n const mw = applicable[index++];\n await mw.fn(ctx, next);\n } else {\n ctx.result = await executor();\n }\n };\n\n await next();\n return ctx.result;\n }\n\n /**\n * Build a HookContext.session from ExecutionContext\n */\n private buildSession(execCtx?: ExecutionContext): HookContext['session'] {\n if (!execCtx) return undefined;\n return {\n userId: execCtx.userId,\n tenantId: execCtx.tenantId,\n roles: execCtx.roles,\n accessToken: execCtx.accessToken,\n };\n }\n\n /**\n * Register contribution (Manifest)\n * \n * Installs the manifest as a Package (the unit of installation),\n * then decomposes it into individual metadata items (objects, apps, actions, etc.)\n * and registers each into the SchemaRegistry.\n * \n * Key: Package ≠ App. The manifest is the package. The apps[] array inside\n * the manifest contains UI navigation definitions (AppSchema).\n */\n registerApp(manifest: any) {\n const id = manifest.id || manifest.name;\n const namespace = manifest.namespace as string | undefined;\n this.logger.debug('Registering package manifest', { id, namespace });\n\n // 1. Register the Package (manifest + lifecycle state)\n SchemaRegistry.installPackage(manifest);\n this.logger.debug('Installed Package', { id: manifest.id, name: manifest.name, namespace });\n\n // 2. Register owned objects\n if (manifest.objects) {\n if (Array.isArray(manifest.objects)) {\n this.logger.debug('Registering objects from manifest (Array)', { id, objectCount: manifest.objects.length });\n for (const objDef of manifest.objects) {\n const fqn = SchemaRegistry.registerObject(objDef, id, namespace, 'own');\n this.logger.debug('Registered Object', { fqn, from: id });\n }\n } else {\n this.logger.debug('Registering objects from manifest (Map)', { id, objectCount: Object.keys(manifest.objects).length });\n for (const [name, objDef] of Object.entries(manifest.objects)) {\n // Ensure name in definition matches key\n (objDef as any).name = name;\n const fqn = SchemaRegistry.registerObject(objDef as any, id, namespace, 'own');\n this.logger.debug('Registered Object', { fqn, from: id });\n }\n }\n }\n\n // 2b. Register object extensions (fields added to objects owned by other packages)\n if (Array.isArray(manifest.objectExtensions) && manifest.objectExtensions.length > 0) {\n this.logger.debug('Registering object extensions', { id, count: manifest.objectExtensions.length });\n for (const ext of manifest.objectExtensions) {\n const targetFqn = ext.extend;\n const priority = ext.priority ?? 200;\n // Create a partial object definition for the extension\n const extDef = {\n name: targetFqn, // Use the target FQN as name\n fields: ext.fields,\n label: ext.label,\n pluralLabel: ext.pluralLabel,\n description: ext.description,\n validations: ext.validations,\n indexes: ext.indexes,\n };\n // Register as extension (namespace is undefined since we're targeting by FQN)\n SchemaRegistry.registerObject(extDef as any, id, undefined, 'extend', priority);\n this.logger.debug('Registered Object Extension', { target: targetFqn, priority, from: id });\n }\n }\n\n // 3. Register apps (UI navigation definitions) as their own metadata type\n if (Array.isArray(manifest.apps) && manifest.apps.length > 0) {\n this.logger.debug('Registering apps from manifest', { id, count: manifest.apps.length });\n for (const app of manifest.apps) {\n const appName = app.name || app.id;\n if (appName) {\n SchemaRegistry.registerApp(app, id);\n this.logger.debug('Registered App', { app: appName, from: id });\n }\n }\n }\n\n // 4. If manifest itself looks like an App (has navigation), also register as app\n // This handles the case where the manifest IS the app definition (legacy/simple packages)\n if (manifest.name && manifest.navigation && !manifest.apps?.length) {\n SchemaRegistry.registerApp(manifest, id);\n this.logger.debug('Registered manifest-as-app', { app: manifest.name, from: id });\n }\n\n // 5. Register all other metadata types generically\n const metadataArrayKeys = [\n // UI Protocol\n 'actions', 'views', 'pages', 'dashboards', 'reports', 'themes',\n // Automation Protocol\n 'flows', 'workflows', 'approvals', 'webhooks',\n // Security Protocol\n 'roles', 'permissions', 'profiles', 'sharingRules', 'policies',\n // AI Protocol\n 'agents', 'ragPipelines',\n // API Protocol\n 'apis',\n // Data Extensions\n 'hooks', 'mappings', 'analyticsCubes',\n // Integration Protocol\n 'connectors',\n ];\n for (const key of metadataArrayKeys) {\n const items = (manifest as any)[key];\n if (Array.isArray(items) && items.length > 0) {\n this.logger.debug(`Registering ${key} from manifest`, { id, count: items.length });\n for (const item of items) {\n const itemName = item.name || item.id;\n if (itemName) {\n SchemaRegistry.registerItem(pluralToSingular(key), item, 'name' as any, id);\n }\n }\n }\n }\n\n // 6. Register seed data as metadata (keyed by target object name)\n const seedData = (manifest as any).data;\n if (Array.isArray(seedData) && seedData.length > 0) {\n this.logger.debug('Registering seed data datasets', { id, count: seedData.length });\n for (const dataset of seedData) {\n if (dataset.object) {\n SchemaRegistry.registerItem('data', dataset, 'object' as any, id);\n }\n }\n }\n\n // 6. Register contributions\n if (manifest.contributes?.kinds) {\n this.logger.debug('Registering kinds from manifest', { id, kindCount: manifest.contributes.kinds.length });\n for (const kind of manifest.contributes.kinds) {\n SchemaRegistry.registerKind(kind);\n this.logger.debug('Registered Kind', { kind: kind.name || kind.type, from: id });\n }\n }\n\n // 7. Recursively register nested plugins\n if (Array.isArray(manifest.plugins) && manifest.plugins.length > 0) {\n this.logger.debug('Processing nested plugins', { id, count: manifest.plugins.length });\n for (const plugin of manifest.plugins) {\n if (plugin && typeof plugin === 'object') {\n const pluginName = plugin.name || plugin.id || 'unnamed-plugin';\n this.logger.debug('Registering nested plugin', { pluginName, parentId: id });\n this.registerPlugin(plugin, id, namespace);\n }\n }\n }\n }\n\n /**\n * Register a nested plugin's metadata (objects, actions, views, etc.)\n *\n * Unlike registerApp(), this does NOT call SchemaRegistry.installPackage()\n * because plugins are not formal manifests — they are lightweight config\n * bundles with objects, actions, triggers, and navigation.\n *\n * @param plugin - The plugin config object\n * @param parentId - The parent package ID (for ownership tracking)\n * @param parentNamespace - The parent package's namespace (for FQN resolution)\n */\n private registerPlugin(plugin: any, parentId: string, parentNamespace?: string) {\n const pluginName = plugin.name || plugin.id || 'unnamed';\n const pluginNamespace = plugin.namespace || parentNamespace;\n\n // Use parentId as the owning package for namespace consistency.\n // The parent package already claimed the namespace — nested plugins\n // contribute objects UNDER the parent's ownership.\n const ownerId = parentId;\n\n // Register objects (supports both Array and Map formats)\n if (plugin.objects) {\n try {\n if (Array.isArray(plugin.objects)) {\n this.logger.debug('Registering plugin objects (Array)', { pluginName, count: plugin.objects.length });\n for (const objDef of plugin.objects) {\n const fqn = SchemaRegistry.registerObject(objDef, ownerId, pluginNamespace, 'own');\n this.logger.debug('Registered Object', { fqn, from: pluginName });\n }\n } else {\n const entries = Object.entries(plugin.objects);\n this.logger.debug('Registering plugin objects (Map)', { pluginName, count: entries.length });\n for (const [name, objDef] of entries) {\n (objDef as any).name = name;\n const fqn = SchemaRegistry.registerObject(objDef as any, ownerId, pluginNamespace, 'own');\n this.logger.debug('Registered Object', { fqn, from: pluginName });\n }\n }\n } catch (err: any) {\n this.logger.warn('Failed to register plugin objects', { pluginName, error: err.message });\n }\n }\n\n // Register plugin as app if it has navigation (for sidebar display)\n if (plugin.name && plugin.navigation) {\n try {\n SchemaRegistry.registerApp(plugin, ownerId);\n this.logger.debug('Registered plugin-as-app', { app: plugin.name, from: pluginName });\n } catch (err: any) {\n this.logger.warn('Failed to register plugin as app', { pluginName, error: err.message });\n }\n }\n\n // Register metadata arrays (actions, views, triggers, etc.)\n const metadataArrayKeys = [\n 'actions', 'views', 'pages', 'dashboards', 'reports', 'themes',\n 'flows', 'workflows', 'approvals', 'webhooks',\n 'roles', 'permissions', 'profiles', 'sharingRules', 'policies',\n 'agents', 'ragPipelines', 'apis',\n 'hooks', 'mappings', 'analyticsCubes', 'connectors',\n ];\n for (const key of metadataArrayKeys) {\n const items = (plugin as any)[key];\n if (Array.isArray(items) && items.length > 0) {\n for (const item of items) {\n const itemName = item.name || item.id;\n if (itemName) {\n SchemaRegistry.registerItem(pluralToSingular(key), item, 'name' as any, ownerId);\n }\n }\n }\n }\n }\n\n /**\n * Register a new storage driver\n */\n registerDriver(driver: DriverInterface, isDefault: boolean = false) {\n if (this.drivers.has(driver.name)) {\n this.logger.warn('Driver already registered, skipping', { driverName: driver.name });\n return;\n }\n\n this.drivers.set(driver.name, driver);\n this.logger.info('Registered driver', {\n driverName: driver.name,\n version: driver.version\n });\n\n if (isDefault || this.drivers.size === 1) {\n this.defaultDriver = driver.name;\n this.logger.info('Set default driver', { driverName: driver.name });\n }\n }\n\n /**\n * Set the realtime service for publishing data change events.\n * Should be called after kernel resolves the realtime service.\n *\n * @param service - An IRealtimeService instance for event publishing\n */\n setRealtimeService(service: IRealtimeService): void {\n this.realtimeService = service;\n this.logger.info('RealtimeService configured for data events');\n }\n\n /**\n * Helper to get object definition\n */\n getSchema(objectName: string): ServiceObject | undefined {\n return SchemaRegistry.getObject(objectName);\n }\n\n /**\n * Resolve an object name to its Fully Qualified Name (FQN).\n * \n * Short names like 'task' are resolved to FQN like 'todo__task'\n * via SchemaRegistry lookup. If no match is found, the name is\n * returned as-is (for ad-hoc / unregistered objects).\n * \n * This ensures that all driver operations use a consistent key\n * regardless of whether the caller uses the short name or FQN.\n */\n private resolveObjectName(name: string): string {\n const schema = SchemaRegistry.getObject(name);\n if (schema) {\n // Prefer the physical table name (e.g., 'sys_user') over the FQN\n // (e.g., 'sys__user'). ObjectSchema.create() auto-derives tableName\n // as {namespace}_{name} which matches the storage convention.\n return schema.tableName || schema.name;\n }\n return name; // Ad-hoc object, keep as-is\n }\n\n /**\n * Helper to get the target driver\n */\n private getDriver(objectName: string): DriverInterface {\n const object = SchemaRegistry.getObject(objectName);\n \n // 1. If object definition exists, check for explicit datasource\n if (object) {\n const datasourceName = object.datasource || 'default';\n \n // If configured for 'default', try to find the default driver\n if (datasourceName === 'default') {\n if (this.defaultDriver && this.drivers.has(this.defaultDriver)) {\n return this.drivers.get(this.defaultDriver)!;\n }\n } else {\n // Specific datasource requested\n if (this.drivers.has(datasourceName)) {\n return this.drivers.get(datasourceName)!;\n }\n throw new Error(`[ObjectQL] Datasource '${datasourceName}' configured for object '${objectName}' is not registered.`);\n }\n }\n\n // 2. Fallback for ad-hoc objects or missing definitions\n if (this.defaultDriver) {\n return this.drivers.get(this.defaultDriver)!;\n }\n\n throw new Error(`[ObjectQL] No driver available for object '${objectName}'`);\n }\n\n /**\n * Initialize the engine and all registered drivers\n */\n async init() {\n this.logger.info('Initializing ObjectQL engine', { \n driverCount: this.drivers.size,\n drivers: Array.from(this.drivers.keys())\n });\n \n const failedDrivers: string[] = [];\n for (const [name, driver] of this.drivers) {\n try {\n await driver.connect();\n this.logger.info('Driver connected successfully', { driverName: name });\n } catch (e) {\n failedDrivers.push(name);\n this.logger.error('Failed to connect driver', e as Error, { driverName: name });\n }\n }\n\n if (failedDrivers.length > 0) {\n this.logger.warn(\n `${failedDrivers.length} of ${this.drivers.size} driver(s) failed initial connect. ` +\n `Operations may recover via lazy reconnection or fail at query time.`,\n { failedDrivers }\n );\n }\n \n this.logger.info('ObjectQL engine initialization complete');\n }\n\n async destroy() {\n this.logger.info('Destroying ObjectQL engine', { driverCount: this.drivers.size });\n \n for (const [name, driver] of this.drivers.entries()) {\n try {\n await driver.disconnect();\n } catch (e) {\n this.logger.error('Error disconnecting driver', e as Error, { driverName: name });\n }\n }\n \n this.logger.info('ObjectQL engine destroyed');\n }\n\n // ============================================\n // Helper: Expand Related Records\n // ============================================\n\n /** Maximum depth for recursive expand to prevent infinite loops */\n private static readonly MAX_EXPAND_DEPTH = 3;\n\n /**\n * Post-process expand: resolve lookup/master_detail fields by batch-loading related records.\n * \n * This is a driver-agnostic implementation that uses secondary queries ($in batches)\n * to load related records, then injects them into the result set.\n * \n * @param objectName - The source object name\n * @param records - The records returned by the driver\n * @param expand - The expand map from QueryAST (field name → nested QueryAST)\n * @param depth - Current recursion depth (0-based)\n * @returns Records with expanded lookup fields (IDs replaced by full objects)\n */\n private async expandRelatedRecords(\n objectName: string,\n records: any[],\n expand: Record,\n depth: number = 0,\n ): Promise {\n if (!records || records.length === 0) return records;\n if (depth >= ObjectQL.MAX_EXPAND_DEPTH) return records;\n\n const objectSchema = SchemaRegistry.getObject(objectName);\n // If no schema registered, skip expand — return raw data\n if (!objectSchema || !objectSchema.fields) return records;\n\n for (const [fieldName, nestedAST] of Object.entries(expand)) {\n const fieldDef = objectSchema.fields[fieldName];\n\n // Skip if field not found or not a relationship type\n if (!fieldDef || !fieldDef.reference) continue;\n if (fieldDef.type !== 'lookup' && fieldDef.type !== 'master_detail') continue;\n\n const referenceObject = fieldDef.reference;\n\n // Collect all foreign key IDs from records (handle both single and multiple values)\n const allIds: any[] = [];\n for (const record of records) {\n const val = record[fieldName];\n if (val == null) continue;\n if (Array.isArray(val)) {\n allIds.push(...val.filter((id: any) => id != null));\n } else if (typeof val === 'object') {\n // Already expanded — skip\n continue;\n } else {\n allIds.push(val);\n }\n }\n\n // De-duplicate IDs\n const uniqueIds = [...new Set(allIds)];\n if (uniqueIds.length === 0) continue;\n\n // Batch-load related records using $in query\n try {\n const relatedQuery: QueryAST = {\n object: referenceObject,\n where: { id: { $in: uniqueIds } },\n ...(nestedAST.fields ? { fields: nestedAST.fields } : {}),\n ...(nestedAST.orderBy ? { orderBy: nestedAST.orderBy } : {}),\n };\n\n const driver = this.getDriver(referenceObject);\n const relatedRecords = await driver.find(referenceObject, relatedQuery) ?? [];\n\n // Build a lookup map: id → record\n const recordMap = new Map();\n for (const rec of relatedRecords) {\n const id = rec.id;\n if (id != null) recordMap.set(String(id), rec);\n }\n\n // Recursively expand nested relations if present\n if (nestedAST.expand && Object.keys(nestedAST.expand).length > 0) {\n const expandedRelated = await this.expandRelatedRecords(\n referenceObject,\n relatedRecords,\n nestedAST.expand,\n depth + 1,\n );\n // Rebuild map with expanded records\n recordMap.clear();\n for (const rec of expandedRelated) {\n const id = rec.id;\n if (id != null) recordMap.set(String(id), rec);\n }\n }\n\n // Inject expanded records back into the original result set\n for (const record of records) {\n const val = record[fieldName];\n if (val == null) continue;\n\n if (Array.isArray(val)) {\n record[fieldName] = val.map((id: any) => recordMap.get(String(id)) ?? id);\n } else if (typeof val !== 'object') {\n record[fieldName] = recordMap.get(String(val)) ?? val;\n }\n // If val is already an object, leave it as-is\n }\n } catch (e) {\n // Graceful degradation: if expand fails, keep original IDs\n this.logger.warn('Failed to expand relationship field; retaining foreign key IDs', {\n object: objectName,\n field: fieldName,\n reference: referenceObject,\n error: (e as Error).message,\n });\n }\n }\n\n return records;\n }\n\n // ============================================\n // Data Access Methods (IDataEngine Interface)\n // ============================================\n\n async find(object: string, query?: EngineQueryOptions): Promise {\n object = this.resolveObjectName(object);\n this.logger.debug('Find operation starting', { object, query });\n const driver = this.getDriver(object);\n const ast: QueryAST = { object, ...query };\n // Remove context from the AST — it's not a driver concern\n delete (ast as any).context;\n // Normalize OData `top` alias → standard `limit`\n if ((ast as any).top != null && ast.limit == null) {\n ast.limit = (ast as any).top;\n }\n delete (ast as any).top;\n\n const opCtx: OperationContext = {\n object,\n operation: 'find',\n ast,\n options: query,\n context: query?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const hookContext: HookContext = {\n object,\n event: 'beforeFind',\n input: { ast: opCtx.ast, options: opCtx.options },\n session: this.buildSession(opCtx.context),\n transaction: opCtx.context?.transaction,\n ql: this\n };\n await this.triggerHooks('beforeFind', hookContext);\n\n try {\n let result = await driver.find(object, hookContext.input.ast as QueryAST, hookContext.input.options as any);\n\n // Post-process: expand related records if expand is requested\n if (ast.expand && Object.keys(ast.expand).length > 0 && Array.isArray(result)) {\n result = await this.expandRelatedRecords(object, result, ast.expand, 0);\n }\n \n hookContext.event = 'afterFind';\n hookContext.result = result;\n await this.triggerHooks('afterFind', hookContext);\n \n return hookContext.result;\n } catch (e) {\n this.logger.error('Find operation failed', e as Error, { object });\n throw e;\n }\n });\n\n return opCtx.result as any[];\n }\n\n async findOne(objectName: string, query?: EngineQueryOptions): Promise {\n objectName = this.resolveObjectName(objectName);\n this.logger.debug('FindOne operation', { objectName });\n const driver = this.getDriver(objectName);\n const ast: QueryAST = { object: objectName, ...query, limit: 1 };\n // Remove context and top alias from the AST\n delete (ast as any).context;\n delete (ast as any).top;\n\n const opCtx: OperationContext = {\n object: objectName,\n operation: 'findOne',\n ast,\n options: query,\n context: query?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n let result = await driver.findOne(objectName, opCtx.ast as QueryAST);\n\n // Post-process: expand related records if expand is requested\n if (ast.expand && Object.keys(ast.expand).length > 0 && result != null) {\n const expanded = await this.expandRelatedRecords(objectName, [result], ast.expand, 0);\n result = expanded[0];\n }\n\n return result;\n });\n\n return opCtx.result;\n }\n\n async insert(object: string, data: any | any[], options?: DataEngineInsertOptions): Promise {\n object = this.resolveObjectName(object);\n this.logger.debug('Insert operation starting', { object, isBatch: Array.isArray(data) });\n const driver = this.getDriver(object);\n\n const opCtx: OperationContext = {\n object,\n operation: 'insert',\n data,\n options,\n context: options?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const hookContext: HookContext = {\n object,\n event: 'beforeInsert',\n input: { data: opCtx.data, options: opCtx.options },\n session: this.buildSession(opCtx.context),\n transaction: opCtx.context?.transaction,\n ql: this\n };\n await this.triggerHooks('beforeInsert', hookContext);\n\n try {\n let result;\n if (Array.isArray(hookContext.input.data)) {\n // Bulk Create\n if (driver.bulkCreate) {\n result = await driver.bulkCreate(object, hookContext.input.data as any[], hookContext.input.options as any);\n } else {\n // Fallback loop\n result = await Promise.all((hookContext.input.data as any[]).map((item: any) => driver.create(object, item, hookContext.input.options as any)));\n }\n } else {\n result = await driver.create(object, hookContext.input.data as Record, hookContext.input.options as any);\n }\n\n hookContext.event = 'afterInsert';\n hookContext.result = result;\n await this.triggerHooks('afterInsert', hookContext);\n\n // Publish data.record.created event to realtime service\n if (this.realtimeService) {\n try {\n if (Array.isArray(result)) {\n // Bulk insert - publish event for each record\n for (const record of result) {\n const event: RealtimeEventPayload = {\n type: 'data.record.created',\n object,\n payload: {\n recordId: record.id,\n after: record,\n },\n timestamp: new Date().toISOString(),\n };\n await this.realtimeService.publish(event);\n }\n this.logger.debug(`Published ${result.length} data.record.created events`, { object });\n } else {\n const event: RealtimeEventPayload = {\n type: 'data.record.created',\n object,\n payload: {\n recordId: result.id,\n after: result,\n },\n timestamp: new Date().toISOString(),\n };\n await this.realtimeService.publish(event);\n this.logger.debug('Published data.record.created event', { object, recordId: result.id });\n }\n } catch (error) {\n this.logger.warn('Failed to publish data event', { object, error });\n }\n }\n\n return hookContext.result;\n } catch (e) {\n this.logger.error('Insert operation failed', e as Error, { object });\n throw e;\n }\n });\n\n return opCtx.result;\n }\n\n async update(object: string, data: any, options?: EngineUpdateOptions): Promise {\n object = this.resolveObjectName(object);\n this.logger.debug('Update operation starting', { object });\n const driver = this.getDriver(object);\n \n // 1. Extract ID from data or where if it's a single update by ID\n let id = data.id;\n if (!id && options?.where && typeof options.where === 'object' && 'id' in options.where) {\n id = (options.where as Record).id;\n }\n\n const opCtx: OperationContext = {\n object,\n operation: 'update',\n data,\n options,\n context: options?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const hookContext: HookContext = {\n object,\n event: 'beforeUpdate',\n input: { id, data: opCtx.data, options: opCtx.options },\n session: this.buildSession(opCtx.context),\n transaction: opCtx.context?.transaction,\n ql: this\n };\n await this.triggerHooks('beforeUpdate', hookContext);\n\n try {\n let result;\n if (hookContext.input.id) {\n result = await driver.update(object, hookContext.input.id as string, hookContext.input.data as Record, hookContext.input.options as any);\n } else if (options?.multi && driver.updateMany) {\n const ast: QueryAST = { object, where: options.where };\n result = await driver.updateMany(object, ast, hookContext.input.data as Record, hookContext.input.options as any);\n } else {\n throw new Error('Update requires an ID or options.multi=true');\n }\n\n hookContext.event = 'afterUpdate';\n hookContext.result = result;\n await this.triggerHooks('afterUpdate', hookContext);\n\n // Publish data.record.updated event to realtime service\n if (this.realtimeService) {\n try {\n const resultId = (typeof result === 'object' && result && 'id' in result) ? (result as any).id : undefined;\n const recordId = String(hookContext.input.id || resultId || '');\n const event: RealtimeEventPayload = {\n type: 'data.record.updated',\n object,\n payload: {\n recordId,\n changes: hookContext.input.data,\n after: result,\n },\n timestamp: new Date().toISOString(),\n };\n await this.realtimeService.publish(event);\n this.logger.debug('Published data.record.updated event', { object, recordId });\n } catch (error) {\n this.logger.warn('Failed to publish data event', { object, error });\n }\n }\n\n return hookContext.result;\n } catch (e) {\n this.logger.error('Update operation failed', e as Error, { object });\n throw e;\n }\n });\n\n return opCtx.result;\n }\n\n async delete(object: string, options?: EngineDeleteOptions): Promise {\n object = this.resolveObjectName(object);\n this.logger.debug('Delete operation starting', { object });\n const driver = this.getDriver(object);\n\n // Extract ID logic similar to update\n let id: any = undefined;\n if (options?.where && typeof options.where === 'object' && 'id' in options.where) {\n id = (options.where as Record).id;\n }\n\n const opCtx: OperationContext = {\n object,\n operation: 'delete',\n options,\n context: options?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const hookContext: HookContext = {\n object,\n event: 'beforeDelete',\n input: { id, options: opCtx.options },\n session: this.buildSession(opCtx.context),\n transaction: opCtx.context?.transaction,\n ql: this\n };\n await this.triggerHooks('beforeDelete', hookContext);\n\n try {\n let result;\n if (hookContext.input.id) {\n result = await driver.delete(object, hookContext.input.id as string, hookContext.input.options as any);\n } else if (options?.multi && driver.deleteMany) {\n const ast: QueryAST = { object, where: options.where };\n result = await driver.deleteMany(object, ast, hookContext.input.options as any);\n } else {\n throw new Error('Delete requires an ID or options.multi=true');\n }\n\n hookContext.event = 'afterDelete';\n hookContext.result = result;\n await this.triggerHooks('afterDelete', hookContext);\n\n // Publish data.record.deleted event to realtime service\n if (this.realtimeService) {\n try {\n const resultId = (typeof result === 'object' && result && 'id' in result) ? (result as any).id : undefined;\n const recordId = String(hookContext.input.id || resultId || '');\n const event: RealtimeEventPayload = {\n type: 'data.record.deleted',\n object,\n payload: {\n recordId,\n },\n timestamp: new Date().toISOString(),\n };\n await this.realtimeService.publish(event);\n this.logger.debug('Published data.record.deleted event', { object, recordId });\n } catch (error) {\n this.logger.warn('Failed to publish data event', { object, error });\n }\n }\n\n return hookContext.result;\n } catch (e) {\n this.logger.error('Delete operation failed', e as Error, { object });\n throw e;\n }\n });\n\n return opCtx.result;\n }\n\n async count(object: string, query?: EngineCountOptions): Promise {\n object = this.resolveObjectName(object);\n const driver = this.getDriver(object);\n\n const opCtx: OperationContext = {\n object,\n operation: 'count',\n options: query,\n context: query?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n if (driver.count) {\n const ast: QueryAST = { object, where: query?.where };\n return driver.count(object, ast);\n }\n // Fallback to find().length\n const res = await this.find(object, { where: query?.where, fields: ['id'] });\n return res.length;\n });\n\n return opCtx.result as number;\n }\n\n async aggregate(object: string, query: EngineAggregateOptions): Promise {\n object = this.resolveObjectName(object);\n const driver = this.getDriver(object);\n this.logger.debug(`Aggregate on ${object} using ${driver.name}`, query);\n\n const opCtx: OperationContext = {\n object,\n operation: 'aggregate',\n options: query,\n context: query?.context,\n };\n\n await this.executeWithMiddleware(opCtx, async () => {\n const ast: QueryAST = {\n object,\n where: query.where,\n groupBy: query.groupBy,\n aggregations: query.aggregations,\n };\n\n return driver.find(object, ast);\n });\n\n return opCtx.result as any[];\n }\n \n async execute(command: any, options?: Record): Promise {\n // Direct pass-through implies we know which driver to use?\n // Usually execute is tied to a specific object context OR we need a way to select driver.\n // If command has 'object', we use that.\n if (options?.object) {\n const driver = this.getDriver(options.object);\n if (driver.execute) {\n return driver.execute(command, undefined, options);\n }\n }\n throw new Error('Execute requires options.object to select driver');\n }\n\n // ============================================\n // Compatibility / Convenience API\n // ============================================\n // These methods provide a higher-level API matching the @objectql/core\n // ObjectQL interface, enabling painless migration from the legacy layer.\n\n /**\n * Register a single object definition.\n * \n * Proxies to SchemaRegistry.registerObject() with sensible defaults.\n * Fields without a `name` property are auto-assigned from their key.\n */\n registerObject(\n schema: ServiceObject,\n packageId: string = '__runtime__',\n namespace?: string\n ): string {\n // Auto-assign field names from keys\n if (schema.fields) {\n for (const [key, field] of Object.entries(schema.fields)) {\n if (field && typeof field === 'object' && !('name' in field)) {\n (field as any).name = key;\n }\n }\n }\n return SchemaRegistry.registerObject(schema, packageId, namespace);\n }\n\n /**\n * Unregister a single object by name.\n */\n unregisterObject(name: string, packageId?: string): void {\n if (packageId) {\n SchemaRegistry.unregisterObjectsByPackage(packageId);\n } else {\n // Remove from generic metadata as fallback\n SchemaRegistry.unregisterItem('object', name);\n }\n }\n\n /**\n * Get an object definition by name.\n * Alias for getSchema() — matches @objectql/core API.\n */\n getObject(name: string): ServiceObject | undefined {\n return this.getSchema(name);\n }\n\n /**\n * Get all registered object configs as a name→config map.\n * Matches @objectql/core getConfigs() API.\n */\n getConfigs(): Record {\n const result: Record = {};\n const objects = SchemaRegistry.getAllObjects();\n for (const obj of objects) {\n if (obj.name) {\n result[obj.name] = obj;\n }\n }\n return result;\n }\n\n /**\n * Get a registered driver by datasource name.\n * \n * Unlike the private getDriver() (which resolves by object name),\n * this method directly looks up a driver by its registered name.\n */\n getDriverByName(name: string): DriverInterface | undefined {\n return this.drivers.get(name);\n }\n\n /**\n * Get the driver responsible for the given object.\n *\n * Resolves datasource binding from the object's schema definition,\n * falling back to the default driver. This is a public version of\n * the internal getDriver() used by CRUD operations.\n *\n * @param objectName - FQN or short name of the registered object.\n * @returns The resolved DriverInterface, or undefined if no driver is available.\n */\n getDriverForObject(objectName: string): DriverInterface | undefined {\n try {\n return this.getDriver(objectName);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Get a registered driver by datasource name.\n * Alias matching @objectql/core datasource() API.\n * \n * @throws Error if the datasource is not found\n */\n datasource(name: string): DriverInterface {\n const driver = this.drivers.get(name);\n if (!driver) {\n throw new Error(`[ObjectQL] Datasource '${name}' not found`);\n }\n return driver;\n }\n\n /**\n * Register a hook handler.\n * Convenience alias for registerHook() matching @objectql/core on() API.\n * \n * Usage:\n * ql.on('beforeInsert', 'user', async (ctx) => { ... });\n */\n on(\n event: string,\n objectName: string,\n handler: (ctx: HookContext) => Promise | void,\n packageId?: string\n ): void {\n this.registerHook(event, handler, { object: objectName, packageId });\n }\n\n /**\n * Remove all hooks, actions, and objects contributed by a package.\n */\n removePackage(packageId: string): void {\n // Remove hooks\n for (const [key, handlers] of this.hooks.entries()) {\n const filtered = handlers.filter(h => h.packageId !== packageId);\n if (filtered.length !== handlers.length) {\n this.hooks.set(key, filtered);\n }\n }\n // Remove actions\n this.removeActionsByPackage(packageId);\n // Remove objects\n SchemaRegistry.unregisterObjectsByPackage(packageId, true);\n }\n\n /**\n * Gracefully shut down the engine, disconnecting all drivers.\n * Alias for destroy() — matches @objectql/core close() API.\n */\n async close(): Promise {\n return this.destroy();\n }\n\n /**\n * Create a scoped execution context bound to this engine.\n * \n * Usage:\n * const ctx = engine.createContext({ userId: '...', tenantId: '...' });\n * const users = ctx.object('user');\n * await users.find({ filter: { status: 'active' } });\n */\n createContext(ctx: Partial): ScopedContext {\n return new ScopedContext(\n ExecutionContextSchema.parse(ctx),\n this\n );\n }\n\n /**\n * Static factory: create a fully configured ObjectQL instance.\n * \n * Matches @objectql/core's `new ObjectQL(config)` pattern but also\n * registers drivers and objects, then calls init().\n * \n * Usage:\n * const ql = await ObjectQL.create({\n * datasources: { default: myDriver },\n * objects: { user: { name: 'user', fields: { ... } } }\n * });\n */\n static async create(config: {\n datasources?: Record;\n objects?: Record;\n hooks?: Array<{ event: string; object: string; handler: (ctx: HookContext) => Promise | void }>;\n }): Promise {\n const ql = new ObjectQL();\n\n // Register drivers\n if (config.datasources) {\n for (const [name, driver] of Object.entries(config.datasources)) {\n // Set driver name if not already set\n if (!driver.name) {\n (driver as any).name = name;\n }\n ql.registerDriver(driver, name === 'default');\n }\n }\n\n // Register objects\n if (config.objects) {\n for (const [_key, schema] of Object.entries(config.objects)) {\n ql.registerObject(schema);\n }\n }\n\n // Register hooks\n if (config.hooks) {\n for (const hook of config.hooks) {\n ql.on(hook.event, hook.object, hook.handler);\n }\n }\n\n // Initialize (connect drivers)\n await ql.init();\n\n return ql;\n }\n}\n\n/**\n * Repository scoped to a single object, bound to an execution context.\n *\n * Provides both IDataEngine-style methods (find, insert, update, delete)\n * and convenience aliases (create, updateById, deleteById) matching\n * the @objectql/core ObjectRepository API.\n */\nexport class ObjectRepository {\n constructor(\n private objectName: string,\n private context: ExecutionContext,\n private engine: IDataEngine & { executeAction?: (o: string, a: string, c: any) => Promise }\n ) {}\n\n async find(query: any = {}): Promise {\n return this.engine.find(this.objectName, {\n ...query,\n context: this.context,\n });\n }\n\n async findOne(query: any = {}): Promise {\n return this.engine.findOne(this.objectName, {\n ...query,\n context: this.context,\n });\n }\n\n async insert(data: any): Promise {\n return this.engine.insert(this.objectName, data, {\n context: this.context,\n });\n }\n\n /** Alias for insert() — matches @objectql/core convention */\n async create(data: any): Promise {\n return this.insert(data);\n }\n\n async update(data: any, options: any = {}): Promise {\n return this.engine.update(this.objectName, data, {\n ...options,\n context: this.context,\n });\n }\n\n /** Update a single record by ID */\n async updateById(id: string | number, data: any): Promise {\n return this.engine.update(this.objectName, { ...data, id: id }, {\n where: { id: id },\n context: this.context,\n });\n }\n\n async delete(options: any = {}): Promise {\n return this.engine.delete(this.objectName, {\n ...options,\n context: this.context,\n });\n }\n\n /** Delete a single record by ID */\n async deleteById(id: string | number): Promise {\n return this.engine.delete(this.objectName, {\n where: { id: id },\n context: this.context,\n });\n }\n\n async count(query: any = {}): Promise {\n return this.engine.count(this.objectName, {\n ...query,\n context: this.context,\n });\n }\n\n /** Aggregate query */\n async aggregate(query: any = {}): Promise {\n return this.engine.aggregate(this.objectName, {\n ...query,\n context: this.context,\n });\n }\n\n /** Execute a named action registered on this object */\n async execute(actionName: string, params?: any): Promise {\n if (this.engine.executeAction) {\n return this.engine.executeAction(this.objectName, actionName, {\n ...params,\n userId: this.context.userId,\n tenantId: this.context.tenantId,\n roles: this.context.roles,\n });\n }\n throw new Error(`Actions not supported by engine`);\n }\n}\n\n/**\n * Scoped execution context with object() accessor.\n * \n * Provides identity (userId, tenantId/spaceId, roles),\n * repository access via object(), privilege escalation via sudo(),\n * and transactional execution via transaction().\n */\nexport class ScopedContext {\n constructor(\n private executionContext: ExecutionContext,\n private engine: IDataEngine\n ) {}\n\n /** Get a repository scoped to this context */\n object(name: string): ObjectRepository {\n return new ObjectRepository(name, this.executionContext, this.engine as any);\n }\n\n /** Create an elevated (system) context */\n sudo(): ScopedContext {\n return new ScopedContext(\n { ...this.executionContext, isSystem: true },\n this.engine\n );\n }\n\n /**\n * Execute a callback within a database transaction.\n *\n * The callback receives a new ScopedContext whose operations\n * share the same transaction handle. If the callback throws,\n * the transaction is rolled back; otherwise it is committed.\n *\n * Falls back to non-transactional execution if the driver\n * does not support transactions.\n */\n async transaction(callback: (trxCtx: ScopedContext) => Promise): Promise {\n const engine = this.engine as any;\n\n // Find the default driver for transaction support\n const driver = engine.defaultDriver\n ? engine.drivers?.get(engine.defaultDriver)\n : undefined;\n\n if (!driver?.beginTransaction) {\n // No transaction support — execute directly\n return callback(this);\n }\n\n const trx = await driver.beginTransaction();\n const trxCtx = new ScopedContext(\n { ...this.executionContext, transaction: trx },\n this.engine\n );\n\n try {\n const result = await callback(trxCtx);\n if (driver.commit) await driver.commit(trx);\n else if (driver.commitTransaction) await driver.commitTransaction(trx);\n return result;\n } catch (error) {\n if (driver.rollback) await driver.rollback(trx);\n else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx);\n throw error;\n }\n }\n\n get userId() { return this.executionContext.userId; }\n get tenantId() { return this.executionContext.tenantId; }\n /** Alias for tenantId — matches ObjectQLContext.spaceId convention */\n get spaceId() { return this.executionContext.tenantId; }\n get roles() { return this.executionContext.roles; }\n get isSystem() { return this.executionContext.isSystem; }\n\n /** Internal: expose the transaction handle for driver-level access */\n get transactionHandle() { return this.executionContext.transaction; }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { SchemaRegistry } from './registry.js';\n\n/**\n * MetadataFacade\n * \n * Provides a clean, injectable interface over SchemaRegistry.\n * Registered as the 'metadata' kernel service to eliminate\n * downstream packages needing to manually wrap SchemaRegistry.\n * \n * Implements the async IMetadataService interface.\n * Internally delegates to SchemaRegistry (in-memory) with Promise wrappers.\n */\nexport class MetadataFacade {\n /**\n * Register a metadata item\n */\n async register(type: string, name: string, data: any): Promise {\n const definition = typeof data === 'object' && data !== null\n ? { ...data, name: data.name ?? name }\n : data;\n if (type === 'object') {\n SchemaRegistry.registerItem(type, definition, 'name' as any);\n } else {\n SchemaRegistry.registerItem(type, definition, definition.id ? 'id' as any : 'name' as any);\n }\n }\n\n /**\n * Get a metadata item by type and name\n */\n async get(type: string, name: string): Promise {\n const item = SchemaRegistry.getItem(type, name) as any;\n return item?.content ?? item;\n }\n\n /**\n * Get the raw entry (with metadata wrapper)\n */\n getEntry(type: string, name: string): any {\n return SchemaRegistry.getItem(type, name);\n }\n\n /**\n * List all items of a type\n */\n async list(type: string): Promise {\n const items = SchemaRegistry.listItems(type);\n return items.map((item: any) => item?.content ?? item);\n }\n\n /**\n * Unregister a metadata item\n */\n async unregister(type: string, name: string): Promise {\n SchemaRegistry.unregisterItem(type, name);\n }\n\n /**\n * Check if a metadata item exists\n */\n async exists(type: string, name: string): Promise {\n const item = SchemaRegistry.getItem(type, name);\n return item !== undefined && item !== null;\n }\n\n /**\n * List all names of metadata items of a given type\n */\n async listNames(type: string): Promise {\n const items = SchemaRegistry.listItems(type);\n return items.map((item: any) => item?.name ?? item?.content?.name ?? '').filter(Boolean);\n }\n\n /**\n * Unregister all metadata from a package\n */\n async unregisterPackage(packageName: string): Promise {\n SchemaRegistry.unregisterObjectsByPackage(packageName);\n }\n\n /**\n * Convenience: get object definition\n */\n async getObject(name: string): Promise {\n return SchemaRegistry.getObject(name);\n }\n\n /**\n * Convenience: list all objects\n */\n async listObjects(): Promise {\n return SchemaRegistry.getAllObjects();\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectQL } from './engine.js';\nimport { ObjectStackProtocolImplementation } from './protocol.js';\nimport { Plugin, PluginContext } from '@objectstack/core';\n\nexport type { Plugin, PluginContext };\n\n/**\n * Protocol extension for DB-based metadata hydration.\n * `loadMetaFromDb` is implemented by ObjectStackProtocolImplementation but\n * is NOT (yet) part of the canonical ObjectStackProtocol wire-contract in\n * `@objectstack/spec`, since it is a server-side bootstrap concern only.\n */\ninterface ProtocolWithDbRestore {\n loadMetaFromDb(): Promise<{ loaded: number; errors: number }>;\n}\n\n/** Type guard — checks whether the service exposes `loadMetaFromDb`. */\nfunction hasLoadMetaFromDb(service: unknown): service is ProtocolWithDbRestore {\n return (\n typeof service === 'object' &&\n service !== null &&\n typeof (service as Record)['loadMetaFromDb'] === 'function'\n );\n}\n\nexport class ObjectQLPlugin implements Plugin {\n name = 'com.objectstack.engine.objectql';\n type = 'objectql';\n version = '1.0.0';\n \n private ql: ObjectQL | undefined;\n private hostContext?: Record;\n\n constructor(ql?: ObjectQL, hostContext?: Record) {\n if (ql) {\n this.ql = ql;\n } else {\n this.hostContext = hostContext;\n // Lazily created in init\n }\n }\n\n init = async (ctx: PluginContext) => {\n if (!this.ql) {\n // Pass kernel logger to engine to avoid creating a separate pino instance\n const hostCtx = { ...this.hostContext, logger: ctx.logger };\n this.ql = new ObjectQL(hostCtx);\n }\n \n // Register as provider for Core Kernel Services\n ctx.registerService('objectql', this.ql);\n\n ctx.registerService('data', this.ql); // ObjectQL implements IDataEngine\n\n // Register manifest service for direct app/package registration.\n // Plugins call ctx.getService('manifest').register(manifestData)\n // instead of the legacy ctx.registerService('app.', manifestData) convention.\n const ql = this.ql;\n ctx.registerService('manifest', {\n register: (manifest: any) => {\n ql.registerApp(manifest);\n ctx.logger.debug('Manifest registered via manifest service', {\n id: manifest.id || manifest.name\n });\n }\n });\n\n ctx.logger.info('ObjectQL engine registered', {\n services: ['objectql', 'data', 'manifest'],\n });\n\n // Register Protocol Implementation\n const protocolShim = new ObjectStackProtocolImplementation(\n this.ql, \n () => ctx.getServices ? ctx.getServices() : new Map()\n );\n\n ctx.registerService('protocol', protocolShim);\n ctx.logger.info('Protocol service registered');\n }\n\n start = async (ctx: PluginContext) => {\n ctx.logger.info('ObjectQL engine starting...');\n\n // Sync from external metadata service (e.g. MetadataPlugin) if available\n try {\n const metadataService = ctx.getService('metadata') as any;\n if (metadataService && typeof metadataService.loadMany === 'function' && this.ql) {\n await this.loadMetadataFromService(metadataService, ctx);\n }\n } catch (e: any) {\n ctx.logger.debug('No external metadata service to sync from');\n }\n \n // Discover features from Kernel Services\n if (ctx.getServices && this.ql) {\n const services = ctx.getServices();\n for (const [name, service] of services.entries()) {\n if (name.startsWith('driver.')) {\n // Register Driver\n this.ql.registerDriver(service);\n ctx.logger.debug('Discovered and registered driver service', { serviceName: name });\n }\n if (name.startsWith('app.')) {\n // Legacy fallback: discover app.* services (DEPRECATED)\n ctx.logger.warn(\n `[DEPRECATED] Service \"${name}\" uses legacy app.* convention. ` +\n `Migrate to ctx.getService('manifest').register(data).`\n );\n this.ql.registerApp(service); // service is Manifest\n ctx.logger.debug('Discovered and registered app service (legacy)', { serviceName: name });\n }\n }\n\n // Bridge realtime service from kernel service registry to ObjectQL.\n // RealtimeServicePlugin registers as 'realtime' service during init().\n // This enables ObjectQL to publish data change events.\n try {\n const realtimeService = ctx.getService('realtime');\n if (realtimeService && typeof realtimeService === 'object' && 'publish' in realtimeService) {\n ctx.logger.info('[ObjectQLPlugin] Bridging realtime service to ObjectQL for event publishing');\n this.ql.setRealtimeService(realtimeService as any);\n }\n } catch (e: any) {\n ctx.logger.debug('[ObjectQLPlugin] No realtime service found — data events will not be published', {\n error: e.message,\n });\n }\n }\n\n // Initialize drivers (calls driver.connect() which sets up persistence)\n await this.ql?.init();\n\n // Restore persisted metadata from sys_metadata table.\n // This hydrates SchemaRegistry with objects/views/apps that were saved\n // via protocol.saveMetaItem() in a previous session, ensuring custom\n // schemas survive cold starts and redeployments.\n await this.restoreMetadataFromDb(ctx);\n\n // Sync all registered object schemas to database\n // This ensures tables/collections are created or updated for every\n // object registered by plugins (e.g., sys_user from plugin-auth).\n await this.syncRegisteredSchemas(ctx);\n\n // Bridge all SchemaRegistry objects to metadata service\n // This ensures AI tools and other IMetadataService consumers can see all objects\n await this.bridgeObjectsToMetadataService(ctx);\n\n // Register built-in audit hooks\n this.registerAuditHooks(ctx);\n\n // Register tenant isolation middleware\n this.registerTenantMiddleware(ctx);\n\n ctx.logger.info('ObjectQL engine started', {\n driversRegistered: this.ql?.['drivers']?.size || 0,\n objectsRegistered: this.ql?.registry?.getAllObjects?.()?.length || 0\n });\n }\n\n /**\n * Register built-in audit hooks for auto-stamping created_by/updated_by\n * and fetching previousData for update/delete operations.\n */\n private registerAuditHooks(ctx: PluginContext) {\n if (!this.ql) return;\n\n // Auto-stamp created_by/updated_by on insert\n this.ql.registerHook('beforeInsert', async (hookCtx) => {\n if (hookCtx.session?.userId && hookCtx.input?.data) {\n const data = hookCtx.input.data as Record;\n if (typeof data === 'object' && data !== null) {\n data.created_by = data.created_by ?? hookCtx.session.userId;\n data.updated_by = hookCtx.session.userId;\n data.created_at = data.created_at ?? new Date().toISOString();\n data.updated_at = new Date().toISOString();\n if (hookCtx.session.tenantId) {\n data.tenant_id = data.tenant_id ?? hookCtx.session.tenantId;\n }\n }\n }\n }, { object: '*', priority: 10 });\n\n // Auto-stamp updated_by on update\n this.ql.registerHook('beforeUpdate', async (hookCtx) => {\n if (hookCtx.session?.userId && hookCtx.input?.data) {\n const data = hookCtx.input.data as Record;\n if (typeof data === 'object' && data !== null) {\n data.updated_by = hookCtx.session.userId;\n data.updated_at = new Date().toISOString();\n }\n }\n }, { object: '*', priority: 10 });\n\n // Auto-fetch previousData for update hooks\n this.ql.registerHook('beforeUpdate', async (hookCtx) => {\n if (hookCtx.input?.id && !hookCtx.previous) {\n try {\n const existing = await this.ql!.findOne(hookCtx.object, {\n where: { id: hookCtx.input.id }\n });\n if (existing) {\n hookCtx.previous = existing;\n }\n } catch (_e) {\n // Non-fatal: some objects may not support findOne\n }\n }\n }, { object: '*', priority: 5 });\n\n // Auto-fetch previousData for delete hooks\n this.ql.registerHook('beforeDelete', async (hookCtx) => {\n if (hookCtx.input?.id && !hookCtx.previous) {\n try {\n const existing = await this.ql!.findOne(hookCtx.object, {\n where: { id: hookCtx.input.id }\n });\n if (existing) {\n hookCtx.previous = existing;\n }\n } catch (_e) {\n // Non-fatal\n }\n }\n }, { object: '*', priority: 5 });\n\n ctx.logger.debug('Audit hooks registered (created_by/updated_by, previousData)');\n }\n\n /**\n * Register tenant isolation middleware that auto-injects tenant_id filter\n * for multi-tenant operations.\n */\n private registerTenantMiddleware(ctx: PluginContext) {\n if (!this.ql) return;\n\n this.ql.registerMiddleware(async (opCtx, next) => {\n // Only apply to operations with tenantId that are not system-level\n if (!opCtx.context?.tenantId || opCtx.context?.isSystem) {\n return next();\n }\n\n // Read operations: inject tenant_id filter into AST\n if (['find', 'findOne', 'count', 'aggregate'].includes(opCtx.operation)) {\n if (opCtx.ast) {\n const tenantFilter = { tenant_id: opCtx.context.tenantId };\n if (opCtx.ast.where) {\n opCtx.ast.where = { $and: [opCtx.ast.where, tenantFilter] };\n } else {\n opCtx.ast.where = tenantFilter;\n }\n }\n }\n\n await next();\n });\n\n ctx.logger.debug('Tenant isolation middleware registered');\n }\n\n /**\n * Synchronize all registered object schemas to the database.\n *\n * Groups objects by their responsible driver, then:\n * - If the driver advertises `supports.batchSchemaSync` and implements\n * `syncSchemasBatch()`, submits all schemas in a single call (reducing\n * network round-trips for remote drivers like Turso).\n * - Otherwise falls back to sequential `syncSchema()` per object.\n *\n * This is idempotent — drivers must tolerate repeated calls without\n * duplicating tables or erroring out.\n *\n * Drivers that do not implement `syncSchema` are silently skipped.\n */\n private async syncRegisteredSchemas(ctx: PluginContext) {\n if (!this.ql) return;\n\n const allObjects = this.ql.registry?.getAllObjects?.() ?? [];\n if (allObjects.length === 0) return;\n\n let synced = 0;\n let skipped = 0;\n\n // Group objects by driver for potential batch optimization\n const driverGroups = new Map>();\n\n for (const obj of allObjects) {\n const driver = this.ql.getDriverForObject(obj.name);\n if (!driver) {\n ctx.logger.debug('No driver available for object, skipping schema sync', {\n object: obj.name,\n });\n skipped++;\n continue;\n }\n\n if (typeof driver.syncSchema !== 'function') {\n ctx.logger.debug('Driver does not support syncSchema, skipping', {\n object: obj.name,\n driver: driver.name,\n });\n skipped++;\n continue;\n }\n\n const tableName = obj.tableName || obj.name;\n\n let group = driverGroups.get(driver);\n if (!group) {\n group = [];\n driverGroups.set(driver, group);\n }\n group.push({ obj, tableName });\n }\n\n // Process each driver group\n for (const [driver, entries] of driverGroups) {\n // Batch path: driver supports batch schema sync\n if (\n driver.supports?.batchSchemaSync &&\n typeof driver.syncSchemasBatch === 'function'\n ) {\n const batchPayload = entries.map((e) => ({\n object: e.tableName,\n schema: e.obj,\n }));\n try {\n await driver.syncSchemasBatch(batchPayload);\n synced += entries.length;\n ctx.logger.debug('Batch schema sync succeeded', {\n driver: driver.name,\n count: entries.length,\n });\n } catch (e: unknown) {\n ctx.logger.warn('Batch schema sync failed, falling back to sequential', {\n driver: driver.name,\n error: e instanceof Error ? e.message : String(e),\n });\n // Fallback: sequential sync for this driver's objects\n for (const { obj, tableName } of entries) {\n try {\n await driver.syncSchema(tableName, obj);\n synced++;\n } catch (seqErr: unknown) {\n ctx.logger.warn('Failed to sync schema for object', {\n object: obj.name,\n tableName,\n driver: driver.name,\n error: seqErr instanceof Error ? seqErr.message : String(seqErr),\n });\n }\n }\n }\n } else {\n // Sequential path: no batch support\n for (const { obj, tableName } of entries) {\n try {\n await driver.syncSchema(tableName, obj);\n synced++;\n } catch (e: unknown) {\n ctx.logger.warn('Failed to sync schema for object', {\n object: obj.name,\n tableName,\n driver: driver.name,\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n }\n }\n\n if (synced > 0 || skipped > 0) {\n ctx.logger.info('Schema sync complete', { synced, skipped, total: allObjects.length });\n }\n }\n\n /**\n * Restore persisted metadata from the database (sys_metadata) on startup.\n *\n * Calls `protocol.loadMetaFromDb()` to bulk-load all active metadata\n * records (objects, views, apps, etc.) into the in-memory SchemaRegistry.\n * This closes the persistence loop so that user-created schemas survive\n * kernel cold starts and redeployments.\n *\n * Gracefully degrades when:\n * - The protocol service is unavailable (e.g., in-memory-only mode).\n * - `loadMetaFromDb` is not implemented by the protocol shim.\n * - The underlying driver/table does not exist yet (first-run scenario).\n */\n private async restoreMetadataFromDb(ctx: PluginContext): Promise {\n // Phase 1: Resolve protocol service (separate from DB I/O for clearer diagnostics)\n let protocol: ProtocolWithDbRestore;\n try {\n const service = ctx.getService('protocol');\n if (!service || !hasLoadMetaFromDb(service)) {\n ctx.logger.debug('Protocol service does not support loadMetaFromDb, skipping DB restore');\n return;\n }\n protocol = service;\n } catch (e: unknown) {\n ctx.logger.debug('Protocol service unavailable, skipping DB restore', {\n error: e instanceof Error ? e.message : String(e),\n });\n return;\n }\n\n // Phase 2: DB hydration (loads into SchemaRegistry)\n try {\n const { loaded, errors } = await protocol.loadMetaFromDb();\n\n if (loaded > 0 || errors > 0) {\n ctx.logger.info('Metadata restored from database to SchemaRegistry', { loaded, errors });\n } else {\n ctx.logger.debug('No persisted metadata found in database');\n }\n } catch (e: unknown) {\n // Non-fatal: first-run or in-memory driver may not have sys_metadata yet\n ctx.logger.debug('DB metadata restore failed (non-fatal)', {\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n /**\n * Bridge all SchemaRegistry objects to the metadata service.\n *\n * This ensures objects registered by plugins and loaded from sys_metadata\n * are visible to AI tools and other consumers that query IMetadataService.\n *\n * Runs after both restoreMetadataFromDb() and syncRegisteredSchemas() to\n * catch all objects in the SchemaRegistry regardless of their source.\n */\n private async bridgeObjectsToMetadataService(ctx: PluginContext): Promise {\n try {\n const metadataService = ctx.getService('metadata');\n if (!metadataService || typeof metadataService.register !== 'function') {\n ctx.logger.debug('Metadata service unavailable for bridging, skipping');\n return;\n }\n\n if (!this.ql?.registry) {\n ctx.logger.debug('SchemaRegistry unavailable for bridging, skipping');\n return;\n }\n\n const objects = this.ql.registry.getAllObjects();\n let bridged = 0;\n\n for (const obj of objects) {\n try {\n // Check if object is already in metadata service to avoid duplicates\n const existing = await metadataService.getObject(obj.name);\n if (!existing) {\n // Register object that exists in SchemaRegistry but not in metadata service\n await metadataService.register('object', obj.name, obj);\n bridged++;\n }\n } catch (e: unknown) {\n ctx.logger.debug('Failed to bridge object to metadata service', {\n object: obj.name,\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n if (bridged > 0) {\n ctx.logger.info('Bridged objects from SchemaRegistry to metadata service', {\n count: bridged,\n total: objects.length\n });\n } else {\n ctx.logger.debug('No objects needed bridging (all already in metadata service)');\n }\n } catch (e: unknown) {\n ctx.logger.debug('Failed to bridge objects to metadata service', {\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n /**\n * Load metadata from external metadata service into ObjectQL registry\n * This enables ObjectQL to use file-based or remote metadata\n */\n private async loadMetadataFromService(metadataService: any, ctx: PluginContext) {\n ctx.logger.info('Syncing metadata from external service into ObjectQL registry...');\n \n // Metadata types to sync\n const metadataTypes = ['object', 'view', 'app', 'flow', 'workflow', 'function'];\n let totalLoaded = 0;\n \n for (const type of metadataTypes) {\n try {\n // Check if service has loadMany method\n if (typeof metadataService.loadMany === 'function') {\n const items = await metadataService.loadMany(type);\n \n if (items && items.length > 0) {\n items.forEach((item: any) => {\n // Determine key field (usually 'name' or 'id')\n const keyField = item.id ? 'id' : 'name';\n \n // For objects, use the ownership-aware registration\n if (type === 'object' && this.ql) {\n // Objects are registered differently (ownership model)\n // Skip for now - handled by app registration\n return;\n }\n \n // Register other types in the registry\n if (this.ql?.registry?.registerItem) {\n this.ql.registry.registerItem(type, item, keyField);\n }\n });\n \n totalLoaded += items.length;\n ctx.logger.info(`Synced ${items.length} ${type}(s) from metadata service`);\n }\n }\n } catch (e: any) {\n // Type might not exist in metadata service - that's ok\n ctx.logger.debug(`No ${type} metadata found or error loading`, { \n error: e.message \n });\n }\n }\n \n if (totalLoaded > 0) {\n ctx.logger.info(`Metadata sync complete: ${totalLoaded} items loaded into ObjectQL registry`);\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectKernel } from '@objectstack/core';\nimport { ObjectQLPlugin } from './plugin.js';\nimport type { Plugin } from '@objectstack/core';\n\n/**\n * Options for creating an ObjectQL Kernel.\n */\nexport interface ObjectQLKernelOptions {\n /**\n * Additional plugins to register with the kernel.\n */\n plugins?: Plugin[];\n}\n\n/**\n * Convenience factory for creating an ObjectQL-ready kernel.\n *\n * Creates an ObjectKernel pre-configured with the ObjectQLPlugin\n * (data engine, schema registry, protocol implementation) plus any\n * additional plugins provided.\n *\n * @example\n * ```typescript\n * import { createObjectQLKernel } from '@objectstack/objectql';\n *\n * const kernel = createObjectQLKernel({\n * plugins: [myDriverPlugin, myAuthPlugin],\n * });\n * await kernel.bootstrap();\n * ```\n */\nexport async function createObjectQLKernel(options: ObjectQLKernelOptions = {}): Promise {\n const kernel = new ObjectKernel();\n\n // Register the core ObjectQLPlugin first\n await kernel.use(new ObjectQLPlugin());\n\n // Register any additional plugins\n if (options.plugins) {\n for (const plugin of options.plugins) {\n await kernel.use(plugin);\n }\n }\n\n return kernel;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ServiceObject } from '@objectstack/spec/data';\n\n// ── Introspection Types ──────────────────────────────────────────────────────\n\n/**\n * Column metadata from database introspection.\n */\nexport interface IntrospectedColumn {\n /** Column name */\n name: string;\n /** Native database type (e.g., 'varchar', 'integer', 'timestamp') */\n type: string;\n /** Whether the column is nullable */\n nullable: boolean;\n /** Default value if any */\n defaultValue?: unknown;\n /** Whether this is a primary key */\n isPrimary?: boolean;\n /** Whether this column has a unique constraint */\n isUnique?: boolean;\n /** Maximum length for string types */\n maxLength?: number;\n}\n\n/**\n * Foreign key relationship metadata.\n */\nexport interface IntrospectedForeignKey {\n /** Column name in the source table */\n columnName: string;\n /** Referenced table name */\n referencedTable: string;\n /** Referenced column name */\n referencedColumn: string;\n /** Constraint name */\n constraintName?: string;\n}\n\n/**\n * Table metadata from database introspection.\n */\nexport interface IntrospectedTable {\n /** Table name */\n name: string;\n /** List of columns */\n columns: IntrospectedColumn[];\n /** List of foreign key relationships */\n foreignKeys: IntrospectedForeignKey[];\n /** Primary key columns */\n primaryKeys: string[];\n}\n\n/**\n * Complete database schema introspection result.\n */\nexport interface IntrospectedSchema {\n /** Map of table name to table metadata */\n tables: Record;\n}\n\n// ── Utility Functions ────────────────────────────────────────────────────────\n\n/**\n * Convert a snake_case or plain string to Title Case.\n *\n * @example\n * toTitleCase('first_name') // => 'First Name'\n * toTitleCase('project_task') // => 'Project Task'\n */\nexport function toTitleCase(str: string): string {\n return str\n .replace(/_/g, ' ')\n .replace(/\\b\\w/g, (char) => char.toUpperCase());\n}\n\n/**\n * Map a native database column type to an ObjectStack FieldType.\n */\nfunction mapDatabaseTypeToFieldType(\n dbType: string\n): 'text' | 'textarea' | 'number' | 'boolean' | 'datetime' | 'date' | 'time' | 'json' {\n const type = dbType.toLowerCase();\n\n // Text types\n if (type.includes('char') || type.includes('varchar') || type.includes('text')) {\n if (type.includes('text')) return 'textarea';\n return 'text';\n }\n\n // Numeric types\n if (\n type.includes('int') || type === 'integer' || type === 'bigint' || type === 'smallint'\n ) {\n return 'number';\n }\n if (\n type.includes('float') || type.includes('double') || type.includes('decimal') ||\n type.includes('numeric') || type === 'real'\n ) {\n return 'number';\n }\n\n // Boolean\n if (type.includes('bool')) {\n return 'boolean';\n }\n\n // Date / Time types\n if (type.includes('timestamp') || type === 'datetime') {\n return 'datetime';\n }\n if (type === 'date') {\n return 'date';\n }\n if (type === 'time') {\n return 'time';\n }\n\n // JSON types\n if (type === 'json' || type === 'jsonb') {\n return 'json';\n }\n\n // Default to text\n return 'text';\n}\n\n/**\n * Convert an introspected database schema to ObjectStack object definitions.\n *\n * This allows using existing database tables without manually defining metadata.\n *\n * @param introspectedSchema - The schema returned from driver.introspectSchema()\n * @param options - Optional filtering / conversion settings\n * @returns Array of ServiceObject definitions that can be registered with ObjectQL\n *\n * @example\n * ```typescript\n * const schema = await driver.introspectSchema();\n * const objects = convertIntrospectedSchemaToObjects(schema);\n * for (const obj of objects) {\n * engine.registerObject(obj);\n * }\n * ```\n */\nexport function convertIntrospectedSchemaToObjects(\n introspectedSchema: IntrospectedSchema,\n options?: {\n /** Tables to exclude from conversion */\n excludeTables?: string[];\n /** Tables to include (if specified, only these will be converted) */\n includeTables?: string[];\n /** Whether to skip system columns like id, created_at, updated_at (default: true) */\n skipSystemColumns?: boolean;\n }\n): ServiceObject[] {\n const objects: ServiceObject[] = [];\n const excludeTables = options?.excludeTables || [];\n const includeTables = options?.includeTables;\n const skipSystemColumns = options?.skipSystemColumns !== false;\n\n for (const [tableName, table] of Object.entries(introspectedSchema.tables)) {\n if (excludeTables.includes(tableName)) continue;\n if (includeTables && !includeTables.includes(tableName)) continue;\n\n const fields: Record = {};\n\n for (const column of table.columns) {\n // Skip system columns if requested\n if (skipSystemColumns && ['id', 'created_at', 'updated_at'].includes(column.name)) {\n continue;\n }\n\n // Check for foreign key → lookup field\n const foreignKey = table.foreignKeys.find((fk) => fk.columnName === column.name);\n\n if (foreignKey) {\n fields[column.name] = {\n name: column.name,\n type: 'lookup' as const,\n reference: foreignKey.referencedTable,\n label: toTitleCase(column.name),\n required: !column.nullable,\n };\n } else {\n const fieldType = mapDatabaseTypeToFieldType(column.type);\n\n const field: Record = {\n name: column.name,\n type: fieldType,\n label: toTitleCase(column.name),\n required: !column.nullable,\n };\n\n if (column.isUnique) {\n field.unique = true;\n }\n if (column.maxLength && (fieldType === 'text' || fieldType === 'textarea')) {\n field.maxLength = column.maxLength;\n }\n if (column.defaultValue != null) {\n field.defaultValue = column.defaultValue;\n }\n\n fields[column.name] = field;\n }\n }\n\n objects.push({\n name: tableName,\n label: toTitleCase(tableName),\n fields,\n } as ServiceObject);\n }\n\n return objects;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # CLI Extension Protocol\n * \n * Defines the contract for plugins that extend the ObjectStack CLI with\n * custom commands. This enables third-party packages (e.g., marketplace,\n * cloud deployment tools) to register new CLI commands via oclif's\n * built-in plugin system.\n * \n * ## How It Works (oclif Plugin Model)\n * \n * 1. **Declare** — Plugin's `package.json` includes an `oclif` config section\n * declaring its commands directory and any topics.\n * 2. **Discover** — The main CLI (`@objectstack/cli`) lists the plugin in its\n * `oclif.plugins` array, or users install it via `os plugins install `.\n * 3. **Load** — oclif automatically discovers and registers all Command classes\n * exported from the plugin's commands directory.\n * \n * ## Plugin Package Contract\n * \n * The plugin must be a valid oclif plugin:\n * \n * ```json\n * // package.json of the plugin\n * {\n * \"name\": \"@acme/plugin-marketplace\",\n * \"oclif\": {\n * \"commands\": {\n * \"strategy\": \"pattern\",\n * \"target\": \"./dist/commands\",\n * \"glob\": \"**\\/*.js\"\n * }\n * }\n * }\n * ```\n * \n * Commands are standard oclif Command classes:\n * \n * ```typescript\n * // src/commands/marketplace/search.ts\n * import { Args, Command, Flags } from '@oclif/core';\n * \n * export default class MarketplaceSearch extends Command {\n * static override description = 'Search marketplace apps';\n * static override args = {\n * query: Args.string({ description: 'Search query', required: true }),\n * };\n * async run() {\n * const { args } = await this.parse(MarketplaceSearch);\n * // ...\n * }\n * }\n * ```\n * \n * ## Migration from Commander.js\n * \n * The previous plugin model required `contributes.commands` in the manifest\n * and exported Commander.js `Command` instances. The new model uses oclif's\n * native plugin system for automatic command discovery and registration.\n * The `objectstack.config.ts` plugins array no longer determines CLI commands.\n */\n\n/**\n * Schema for a CLI Command Contribution declaration in the manifest.\n * \n * This declarative metadata describes CLI commands contributed by a plugin.\n * With the oclif migration, commands are auto-discovered from the plugin's\n * commands directory. This schema is retained for backward compatibility\n * and for describing command metadata in plugin manifests.\n */\nexport const CLICommandContributionSchema = z.object({\n /** \n * CLI command name. Must be a valid identifier: lowercase alphanumeric with hyphens.\n * This becomes a top-level subcommand of the `os` CLI.\n * \n * @example \"marketplace\"\n * @example \"deploy\"\n * @example \"cloud-sync\"\n */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n\n /** Brief description shown in `os --help` output. */\n description: z.string().optional().describe('Command description for help text'),\n\n /** \n * Module path that exports the oclif Command class(es).\n * Relative to the plugin package root. With oclif, this is typically\n * auto-discovered from the `commands` directory, but can be specified\n * for documentation or manifest purposes.\n * \n * @example \"./dist/commands/marketplace.js\"\n * @example \"./dist/commands\"\n */\n module: z.string().optional().describe('Module path exporting oclif Command classes'),\n});\n\n/**\n * Schema for oclif plugin configuration in package.json.\n * Validates the shape of the `oclif` section in a plugin's package.json.\n */\nexport const OclifPluginConfigSchema = z.object({\n /** Command discovery configuration */\n commands: z.object({\n /** Discovery strategy — typically \"pattern\" for file-based discovery */\n strategy: z.enum(['pattern', 'explicit', 'single']).optional()\n .describe('Command discovery strategy'),\n /** Directory path containing compiled command files */\n target: z.string().optional()\n .describe('Target directory for command files'),\n /** Glob pattern for matching command files */\n glob: z.string().optional()\n .describe('Glob pattern for command file matching'),\n }).optional().describe('Command discovery configuration'),\n\n /** Topic separator character (default: space) */\n topicSeparator: z.string().optional()\n .describe('Character separating topic and command names'),\n}).describe('oclif plugin configuration section');\n\n// ─── Types ───────────────────────────────────────────────────────────\n\nexport type CLICommandContribution = z.infer;\nexport type OclifPluginConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Package Artifact Format Protocol\n *\n * Defines the standard structure of a package artifact (.tgz) produced by\n * `os plugin build`. The marketplace uses these schemas to validate, store,\n * and distribute package artifacts.\n *\n * ## Artifact Internal Structure\n * ```\n * ├── manifest.json ← ManifestSchema serialized\n * ├── metadata/ ← 30+ metadata types (JSON)\n * │ ├── objects/ ← *.object.json\n * │ ├── views/ ← *.view.json\n * │ ├── pages/ ← *.page.json\n * │ ├── flows/ ← *.flow.json\n * │ ├── dashboards/ ← *.dashboard.json\n * │ ├── permissions/ ← *.permission.json\n * │ ├── agents/ ← *.agent.json\n * │ └── ... ← Other metadata types\n * ├── assets/ ← Static resources\n * │ ├── icon.svg\n * │ └── screenshots/\n * ├── data/ ← Seed data (DatasetSchema serialized)\n * ├── locales/ ← i18n translation files\n * ├── checksums.json ← SHA256 checksum per file\n * └── signature.sig ← RSA-SHA256 package signature\n * ```\n *\n * ## Architecture Alignment\n * - **Salesforce**: Managed Package .zip with metadata components\n * - **npm**: .tgz with package.json + contents\n * - **Helm**: Chart .tgz with Chart.yaml + templates\n * - **VS Code**: .vsix (zip) with extension manifest + assets\n */\n\n// ==========================================\n// Metadata Category Definitions\n// ==========================================\n\n/**\n * Supported metadata categories within an artifact.\n * Each category maps to a subdirectory under `metadata/`.\n */\nexport const MetadataCategoryEnum = z.enum([\n 'objects',\n 'views',\n 'pages',\n 'flows',\n 'dashboards',\n 'permissions',\n 'agents',\n 'reports',\n 'actions',\n 'translations',\n 'themes',\n 'datasets',\n 'apis',\n 'triggers',\n 'workflows',\n]).describe('Metadata category within the artifact');\n\nexport type MetadataCategory = z.infer;\n\n// ==========================================\n// Artifact File Entry\n// ==========================================\n\n/**\n * A single file entry within the artifact.\n */\nexport const ArtifactFileEntrySchema = z.object({\n /** Relative path within the artifact (e.g. \"metadata/objects/account.object.json\") */\n path: z.string().describe('Relative file path within the artifact'),\n\n /** File size in bytes */\n size: z.number().int().nonnegative().describe('File size in bytes'),\n\n /** Metadata category (if under metadata/) */\n category: MetadataCategoryEnum.optional()\n .describe('Metadata category this file belongs to'),\n}).describe('A single file entry within the artifact');\n\nexport type ArtifactFileEntry = z.infer;\n\n// ==========================================\n// Artifact Checksum\n// ==========================================\n\n/**\n * Checksum map for artifact integrity verification.\n * Maps relative file paths to their SHA256 hash values.\n *\n * @example\n * {\n * \"manifest.json\": \"a1b2c3...\",\n * \"metadata/objects/account.object.json\": \"d4e5f6...\"\n * }\n */\nexport const ArtifactChecksumSchema = z.object({\n /** Hash algorithm used (default: SHA256) */\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm used for checksums'),\n\n /** Map of relative file paths to their hash values */\n files: z.record(z.string(), z.string().regex(/^[a-f0-9]+$/))\n .describe('File path to hash value mapping'),\n}).describe('Checksum manifest for artifact integrity verification');\n\nexport type ArtifactChecksum = z.infer;\n\n// ==========================================\n// Artifact Signature\n// ==========================================\n\n/**\n * Digital signature for artifact authenticity verification.\n * Ensures the artifact was produced by a trusted publisher and has not been tampered with.\n */\nexport const ArtifactSignatureSchema = z.object({\n /** Signature algorithm */\n algorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).default('RSA-SHA256')\n .describe('Signing algorithm used'),\n\n /** Public key reference (URL or fingerprint) for verification */\n publicKeyRef: z.string()\n .describe('Public key reference (URL or fingerprint) for signature verification'),\n\n /** Base64-encoded signature value */\n signature: z.string()\n .describe('Base64-encoded digital signature'),\n\n /** Timestamp of when the artifact was signed */\n signedAt: z.string().datetime().optional()\n .describe('ISO 8601 timestamp of when the artifact was signed'),\n\n /** Signer identity (publisher ID or email) */\n signedBy: z.string().optional()\n .describe('Identity of the signer (publisher ID or email)'),\n}).describe('Digital signature for artifact authenticity verification');\n\nexport type ArtifactSignature = z.infer;\n\n// ==========================================\n// Package Artifact Schema\n// ==========================================\n\n/**\n * Package Artifact Schema\n *\n * Describes the complete structure and metadata of a built package artifact.\n * This schema is used to validate artifacts before upload to the marketplace.\n */\nexport const PackageArtifactSchema = z.object({\n /** Artifact format version (for forward compatibility) */\n formatVersion: z.string().regex(/^\\d+\\.\\d+$/).default('1.0')\n .describe('Artifact format version (e.g. \"1.0\")'),\n\n /** Package ID from the manifest */\n packageId: z.string().describe('Package identifier from manifest'),\n\n /** Package version from the manifest */\n version: z.string().describe('Package version from manifest'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format of the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().positive().optional()\n .describe('Total artifact file size in bytes'),\n\n /** Build timestamp */\n builtAt: z.string().datetime()\n .describe('ISO 8601 timestamp of when the artifact was built'),\n\n /** Build tool and version that produced this artifact */\n builtWith: z.string().optional()\n .describe('Build tool identifier (e.g. \"os-cli@3.2.0\")'),\n\n /** File listing within the artifact */\n files: z.array(ArtifactFileEntrySchema).optional()\n .describe('List of files contained in the artifact'),\n\n /** Metadata categories present in the artifact */\n metadataCategories: z.array(MetadataCategoryEnum).optional()\n .describe('Metadata categories included in this artifact'),\n\n /** Integrity checksums for all files */\n checksums: ArtifactChecksumSchema.optional()\n .describe('SHA256 checksums for artifact integrity verification'),\n\n /** Digital signature for authenticity */\n signature: ArtifactSignatureSchema.optional()\n .describe('Digital signature for artifact authenticity verification'),\n}).describe('Package artifact structure and metadata');\n\nexport type PackageArtifact = z.infer;\nexport type PackageArtifactInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PackageArtifactSchema, ArtifactChecksumSchema, ArtifactSignatureSchema } from './package-artifact.zod';\n\n/**\n * # CLI Plugin Commands Protocol\n *\n * Defines the input/output schemas for the `os plugin` CLI commands\n * that manage the package build → validate → publish lifecycle.\n *\n * ## Commands\n * ```\n * os plugin build — Build a .tgz artifact from the current project\n * os plugin validate — Validate an artifact's structure, checksums, and signature\n * os plugin publish — Upload an artifact to the marketplace\n * ```\n *\n * ## Architecture Alignment\n * - **npm**: `npm pack` → `npm publish`\n * - **Helm**: `helm package` → `helm push`\n * - **VS Code**: `vsce package` → `vsce publish`\n * - **Salesforce**: `sf package version create` → `sf package version promote`\n */\n\n// ==========================================\n// os plugin build\n// ==========================================\n\n/**\n * Options for the `os plugin build` command.\n * Reads the project manifest and produces a .tgz artifact.\n */\nexport const PluginBuildOptionsSchema = z.object({\n /** Project root directory (defaults to cwd) */\n directory: z.string().optional()\n .describe('Project root directory (defaults to current working directory)'),\n\n /** Output directory for the built artifact */\n outDir: z.string().optional()\n .describe('Output directory for the built artifact (defaults to ./dist)'),\n\n /** Archive format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format for the artifact'),\n\n /** Whether to sign the artifact */\n sign: z.boolean().default(false)\n .describe('Whether to digitally sign the artifact'),\n\n /** Path to the private key for signing */\n privateKeyPath: z.string().optional()\n .describe('Path to RSA/ECDSA private key file for signing'),\n\n /** Signing algorithm */\n signAlgorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).optional()\n .describe('Signing algorithm to use'),\n\n /** Checksum algorithm */\n checksumAlgorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm for file checksums'),\n\n /** Whether to include seed data */\n includeData: z.boolean().default(true)\n .describe('Whether to include seed data in the artifact'),\n\n /** Whether to include locale/translation files */\n includeLocales: z.boolean().default(true)\n .describe('Whether to include locale/translation files'),\n}).describe('Options for the os plugin build command');\n\nexport type PluginBuildOptions = z.infer;\n\n/**\n * Result of the `os plugin build` command.\n */\nexport const PluginBuildResultSchema = z.object({\n /** Whether the build succeeded */\n success: z.boolean().describe('Whether the build succeeded'),\n\n /** Path to the generated artifact file */\n artifactPath: z.string().optional()\n .describe('Absolute path to the generated artifact file'),\n\n /** Artifact metadata (validated against PackageArtifactSchema) */\n artifact: PackageArtifactSchema.optional()\n .describe('Artifact metadata'),\n\n /** Total file count in the artifact */\n fileCount: z.number().int().min(0).optional()\n .describe('Total number of files in the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().min(0).optional()\n .describe('Total artifact size in bytes'),\n\n /** Build duration in milliseconds */\n durationMs: z.number().optional()\n .describe('Build duration in milliseconds'),\n\n /** Error message if build failed */\n errorMessage: z.string().optional()\n .describe('Error message if build failed'),\n\n /** Warnings emitted during build */\n warnings: z.array(z.string()).optional()\n .describe('Warnings emitted during build'),\n}).describe('Result of the os plugin build command');\n\nexport type PluginBuildResult = z.infer;\n\n// ==========================================\n// os plugin validate\n// ==========================================\n\n/**\n * Validation severity levels.\n */\nexport const ValidationSeverityEnum = z.enum([\n 'error', // Must fix — artifact is invalid\n 'warning', // Should fix — may cause issues\n 'info', // Informational — suggestion\n]).describe('Validation issue severity');\n\n/**\n * A single validation finding.\n */\nexport const ValidationFindingSchema = z.object({\n /** Finding severity */\n severity: ValidationSeverityEnum.describe('Issue severity level'),\n\n /** Rule or check that produced this finding */\n rule: z.string().describe('Validation rule identifier'),\n\n /** Human-readable message */\n message: z.string().describe('Human-readable finding description'),\n\n /** File path within the artifact (if applicable) */\n path: z.string().optional()\n .describe('Relative file path within the artifact'),\n}).describe('A single validation finding');\n\nexport type ValidationFinding = z.infer;\n\n/**\n * Options for the `os plugin validate` command.\n */\nexport const PluginValidateOptionsSchema = z.object({\n /** Path to the .tgz artifact file to validate */\n artifactPath: z.string()\n .describe('Path to the artifact file to validate'),\n\n /** Whether to verify the digital signature */\n verifySignature: z.boolean().default(true)\n .describe('Whether to verify the digital signature'),\n\n /** Path to the public key for signature verification */\n publicKeyPath: z.string().optional()\n .describe('Path to the public key for signature verification'),\n\n /** Whether to verify SHA256 checksums of all files */\n verifyChecksums: z.boolean().default(true)\n .describe('Whether to verify checksums of all files'),\n\n /** Whether to validate metadata schema compliance */\n validateMetadata: z.boolean().default(true)\n .describe('Whether to validate metadata against schemas'),\n\n /** Target platform version for compatibility check */\n platformVersion: z.string().optional()\n .describe('Platform version for compatibility verification'),\n}).describe('Options for the os plugin validate command');\n\nexport type PluginValidateOptions = z.infer;\n\n/**\n * Result of the `os plugin validate` command.\n */\nexport const PluginValidateResultSchema = z.object({\n /** Whether the artifact is valid (no error-level findings) */\n valid: z.boolean().describe('Whether the artifact passed validation'),\n\n /** Artifact metadata extracted from the archive */\n artifact: PackageArtifactSchema.optional()\n .describe('Extracted artifact metadata'),\n\n /** Checksum verification result */\n checksumVerification: z.object({\n /** Whether all checksums match */\n passed: z.boolean().describe('Whether all checksums match'),\n /** Checksum details */\n checksums: ArtifactChecksumSchema.optional().describe('Verified checksums'),\n /** Files with mismatched checksums */\n mismatches: z.array(z.string()).optional()\n .describe('Files with checksum mismatches'),\n }).optional().describe('Checksum verification result'),\n\n /** Signature verification result */\n signatureVerification: z.object({\n /** Whether the signature is valid */\n passed: z.boolean().describe('Whether the signature is valid'),\n /** Signature details */\n signature: ArtifactSignatureSchema.optional().describe('Signature details'),\n /** Reason for failure */\n failureReason: z.string().optional().describe('Signature verification failure reason'),\n }).optional().describe('Signature verification result'),\n\n /** Platform compatibility result */\n platformCompatibility: z.object({\n /** Whether the artifact is compatible with the target platform */\n compatible: z.boolean().describe('Whether artifact is compatible'),\n /** Required platform version range */\n requiredRange: z.string().optional().describe('Required platform version range'),\n /** Target platform version checked against */\n targetVersion: z.string().optional().describe('Target platform version'),\n }).optional().describe('Platform compatibility check result'),\n\n /** All validation findings */\n findings: z.array(ValidationFindingSchema)\n .describe('All validation findings'),\n\n /** Counts by severity */\n summary: z.object({\n errors: z.number().int().min(0).describe('Error count'),\n warnings: z.number().int().min(0).describe('Warning count'),\n infos: z.number().int().min(0).describe('Info count'),\n }).optional().describe('Finding counts by severity'),\n}).describe('Result of the os plugin validate command');\n\nexport type PluginValidateResult = z.infer;\n\n// ==========================================\n// os plugin publish\n// ==========================================\n\n/**\n * Options for the `os plugin publish` command.\n */\nexport const PluginPublishOptionsSchema = z.object({\n /** Path to the .tgz artifact file to publish */\n artifactPath: z.string()\n .describe('Path to the artifact file to publish'),\n\n /** Marketplace API base URL */\n registryUrl: z.string().url().optional()\n .describe('Marketplace API base URL'),\n\n /** Authentication token for the marketplace API */\n token: z.string().optional()\n .describe('Authentication token for marketplace API'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional()\n .describe('Release notes for this version'),\n\n /** Whether this is a pre-release */\n preRelease: z.boolean().default(false)\n .describe('Whether this is a pre-release version'),\n\n /** Whether to skip validation before publishing */\n skipValidation: z.boolean().default(false)\n .describe('Whether to skip local validation before publish'),\n\n /** Access level for the published package */\n access: z.enum(['public', 'restricted']).default('public')\n .describe('Package access level on the marketplace'),\n\n /** Tags for categorization */\n tags: z.array(z.string()).optional()\n .describe('Tags for marketplace categorization'),\n}).describe('Options for the os plugin publish command');\n\nexport type PluginPublishOptions = z.infer;\n\n/**\n * Result of the `os plugin publish` command.\n */\nexport const PluginPublishResultSchema = z.object({\n /** Whether the publish succeeded */\n success: z.boolean().describe('Whether the publish succeeded'),\n\n /** Package ID that was published */\n packageId: z.string().optional()\n .describe('Published package identifier'),\n\n /** Version that was published */\n version: z.string().optional()\n .describe('Published version string'),\n\n /** Artifact reference in the marketplace */\n artifactUrl: z.string().url().optional()\n .describe('URL of the published artifact in the marketplace'),\n\n /** SHA256 checksum of the uploaded artifact */\n sha256: z.string().optional()\n .describe('SHA256 checksum of the uploaded artifact'),\n\n /** Submission ID for tracking the review process */\n submissionId: z.string().optional()\n .describe('Marketplace submission ID for review tracking'),\n\n /** Error message if publish failed */\n errorMessage: z.string().optional()\n .describe('Error message if publish failed'),\n\n /** Human-readable status message */\n message: z.string().optional()\n .describe('Human-readable status message'),\n}).describe('Result of the os plugin publish command');\n\nexport type PluginPublishResult = z.infer;\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type ValidationSeverity = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Schema (Multi-Tenant Architecture)\n * \n * Defines the tenant/tenancy model for ObjectStack SaaS deployments.\n * Supports different levels of data isolation to meet varying security,\n * performance, and compliance requirements.\n * \n * Isolation Levels:\n * - shared_schema: All tenants share the same database and schema (row-level isolation)\n * - isolated_schema: Tenants have separate schemas within a shared database\n * - isolated_db: Each tenant has a completely separate database\n */\n\n/**\n * Tenant Isolation Level Enum\n * Defines how tenant data is separated in the system\n */\nexport const TenantIsolationLevel = z.enum([\n 'shared_schema', // Shared DB, shared schema, row-level isolation (most economical)\n 'isolated_schema', // Shared DB, separate schema per tenant (balanced)\n 'isolated_db', // Separate database per tenant (maximum isolation)\n]);\n\nexport type TenantIsolationLevel = z.infer;\n\n/**\n * Database Provider Enum\n * Defines which database backend is used for the tenant\n */\nexport const DatabaseProviderSchema = z.enum([\n 'turso', // Turso/libSQL (DB-per-Tenant, edge-native)\n 'postgres', // PostgreSQL (traditional, self-hosted or managed)\n 'memory', // In-memory (testing/development only)\n]).describe('Database provider for tenant data');\n\nexport type DatabaseProvider = z.infer;\n\n/**\n * Tenant Connection Config Schema\n * Stores the database connection details for a tenant (encrypted at rest)\n */\nexport const TenantConnectionConfigSchema = z.object({\n /** Database connection URL */\n url: z.string().min(1).describe('Database connection URL'),\n /** Authentication token (JWT for Turso, password for Postgres) */\n authToken: z.string().optional().describe('Database auth token (encrypted at rest)'),\n /** Turso database group name */\n group: z.string().optional().describe('Turso database group name'),\n}).describe('Tenant database connection configuration');\n\nexport type TenantConnectionConfig = z.infer;\n\n/**\n * Tenant Quota Schema\n * Defines resource limits and usage quotas for a tenant\n */\nexport const TenantQuotaSchema = z.object({\n /**\n * Maximum number of users allowed for this tenant\n */\n maxUsers: z.number().int().positive().optional().describe('Maximum number of users'),\n \n /**\n * Maximum storage space in bytes\n */\n maxStorage: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n \n /**\n * API rate limit (requests per minute)\n */\n apiRateLimit: z.number().int().positive().optional().describe('API requests per minute'),\n\n /**\n * Maximum number of custom objects the tenant can create\n */\n maxObjects: z.number().int().positive().optional().describe('Maximum number of custom objects'),\n\n /**\n * Maximum records per object/table\n */\n maxRecordsPerObject: z.number().int().positive().optional().describe('Maximum records per object'),\n\n /**\n * Maximum deployments allowed per day\n */\n maxDeploymentsPerDay: z.number().int().positive().optional().describe('Maximum deployments per day'),\n\n /**\n * Maximum storage in bytes\n */\n maxStorageBytes: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n});\n\nexport type TenantQuota = z.infer;\n\n/**\n * Tenant Usage Schema\n * Tracks current resource usage for quota enforcement\n */\nexport const TenantUsageSchema = z.object({\n /** Current number of custom objects */\n currentObjectCount: z.number().int().min(0).default(0).describe('Current number of custom objects'),\n /** Current total record count across all objects */\n currentRecordCount: z.number().int().min(0).default(0).describe('Total records across all objects'),\n /** Current storage usage in bytes */\n currentStorageBytes: z.number().int().min(0).default(0).describe('Current storage usage in bytes'),\n /** Deployments executed today */\n deploymentsToday: z.number().int().min(0).default(0).describe('Deployments executed today'),\n /** Current number of active users */\n currentUsers: z.number().int().min(0).default(0).describe('Current number of active users'),\n /** API requests in the current minute */\n apiRequestsThisMinute: z.number().int().min(0).default(0).describe('API requests in the current minute'),\n /** Last updated timestamp (ISO 8601) */\n lastUpdatedAt: z.string().datetime().optional().describe('Last usage update time'),\n}).describe('Current tenant resource usage');\n\nexport type TenantUsage = z.infer;\n\n/**\n * Quota Enforcement Result\n * Result of checking whether an operation would exceed tenant quotas\n */\nexport const QuotaEnforcementResultSchema = z.object({\n /** Whether the operation is allowed */\n allowed: z.boolean().describe('Whether the operation is within quota'),\n /** Quota that would be exceeded (if not allowed) */\n exceededQuota: z.string().optional().describe('Name of the exceeded quota'),\n /** Current usage value */\n currentUsage: z.number().optional().describe('Current usage value'),\n /** Quota limit value */\n limit: z.number().optional().describe('Quota limit'),\n /** Human-readable message */\n message: z.string().optional().describe('Human-readable quota message'),\n}).describe('Quota enforcement check result');\n\nexport type QuotaEnforcementResult = z.infer;\n\n/**\n * Tenant Schema\n * \n * @deprecated This schema is maintained for backward compatibility only.\n * New implementations should use HubSpaceSchema which embeds tenant concepts.\n * \n * **Migration Guide:**\n * ```typescript\n * // Old approach (deprecated):\n * const tenant: Tenant = {\n * id: 'tenant_123',\n * name: 'My Tenant',\n * isolationLevel: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * };\n * \n * // New approach (recommended):\n * const space: HubSpace = {\n * id: '...uuid...',\n * name: 'My Tenant',\n * slug: 'my-tenant',\n * ownerId: 'user_id',\n * runtime: {\n * isolation: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * },\n * bom: { ... }\n * };\n * ```\n * \n * See HubSpaceSchema in space.zod.ts for the recommended approach.\n */\nexport const TenantSchema = z.object({\n /**\n * Unique tenant identifier\n */\n id: z.string().describe('Unique tenant identifier'),\n \n /**\n * Tenant display name\n */\n name: z.string().describe('Tenant display name'),\n \n /**\n * Data isolation level\n */\n isolationLevel: TenantIsolationLevel,\n\n /**\n * Database provider for this tenant\n */\n databaseProvider: DatabaseProviderSchema.optional().describe('Database provider'),\n\n /**\n * Database connection configuration (encrypted at rest)\n */\n connectionConfig: TenantConnectionConfigSchema.optional().describe('Database connection config'),\n\n /**\n * Current provisioning status\n */\n provisioningStatus: z.enum([\n 'provisioning', 'active', 'suspended', 'failed', 'destroying',\n ]).optional().describe('Current provisioning lifecycle status'),\n\n /**\n * Tenant subscription plan\n */\n plan: z.enum(['free', 'pro', 'enterprise']).optional().describe('Subscription plan'),\n \n /**\n * Custom configuration values\n */\n customizations: z.record(z.string(), z.unknown()).optional().describe('Custom configuration values'),\n \n /**\n * Resource quotas\n */\n quotas: TenantQuotaSchema.optional(),\n});\n\nexport type Tenant = z.infer;\n\n/**\n * Tenant Isolation Strategy Documentation\n * \n * Comprehensive documentation of three isolation strategies for multi-tenant systems.\n * Each strategy has different trade-offs in terms of security, cost, complexity, and compliance.\n */\n\n/**\n * Row-Level Isolation Strategy (shared_schema)\n * \n * Recommended for: Most SaaS applications, cost-sensitive deployments\n * \n * IMPLEMENTATION:\n * - All tenants share the same database and schema\n * - Each table includes a tenant_id column\n * - PostgreSQL Row-Level Security (RLS) enforces isolation\n * - Queries automatically filter by tenant_id via RLS policies\n * \n * ADVANTAGES:\n * ✅ Simple backup and restore (single database)\n * ✅ Cost-effective (shared resources, minimal overhead)\n * ✅ Easy tenant migration (update tenant_id)\n * ✅ Efficient resource utilization (connection pooling)\n * ✅ Simple schema migrations (single schema to update)\n * ✅ Lower operational complexity\n * \n * DISADVANTAGES:\n * ❌ RLS misconfiguration can lead to data leakage\n * ❌ Performance impact from RLS policy evaluation\n * ❌ Noisy neighbor problem (one tenant can affect others)\n * ❌ Cannot easily isolate tenant to different hardware\n * ❌ Compliance challenges for regulated industries\n * \n * SECURITY CONSIDERATIONS:\n * - Requires careful RLS policy configuration\n * - Must validate tenant_id in all queries\n * - Need comprehensive testing of RLS policies\n * - Audit all database access patterns\n * - Implement application-level validation as defense-in-depth\n * \n * EXAMPLE RLS POLICY (PostgreSQL):\n * ```sql\n * -- Example: Apply RLS policy to a table (e.g., \"app_data\")\n * CREATE POLICY tenant_isolation ON app_data\n * USING (tenant_id = current_setting('app.current_tenant')::text);\n * \n * ALTER TABLE app_data ENABLE ROW LEVEL SECURITY;\n * ```\n */\nexport const RowLevelIsolationStrategySchema = z.object({\n strategy: z.literal('shared_schema').describe('Row-level isolation strategy'),\n \n /**\n * Database configuration for row-level isolation\n */\n database: z.object({\n /**\n * Whether to enable Row-Level Security (RLS)\n */\n enableRLS: z.boolean().default(true).describe('Enable PostgreSQL Row-Level Security'),\n \n /**\n * Tenant context setting method\n */\n contextMethod: z.enum([\n 'session_variable', // SET app.current_tenant = 'tenant_123'\n 'search_path', // SET search_path = tenant_123, public\n 'application_name', // SET application_name = 'tenant_123'\n ]).default('session_variable').describe('How to set tenant context'),\n \n /**\n * Session variable name for tenant context\n */\n contextVariable: z.string().default('app.current_tenant').describe('Session variable name'),\n \n /**\n * Whether to validate tenant_id at application level\n */\n applicationValidation: z.boolean().default(true).describe('Application-level tenant validation'),\n }).optional().describe('Database configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use partial indexes for tenant_id\n */\n usePartialIndexes: z.boolean().default(true).describe('Use partial indexes per tenant'),\n \n /**\n * Whether to use table partitioning\n */\n usePartitioning: z.boolean().default(false).describe('Use table partitioning by tenant_id'),\n \n /**\n * Connection pool size per tenant\n */\n poolSizePerTenant: z.number().int().positive().optional().describe('Connection pool size per tenant'),\n }).optional().describe('Performance settings'),\n});\n\nexport type RowLevelIsolationStrategy = z.infer;\nexport type RowLevelIsolationStrategyInput = z.input;\n\n/**\n * Schema-Level Isolation Strategy (isolated_schema)\n * \n * Recommended for: Enterprise SaaS, B2B platforms with compliance needs\n * \n * IMPLEMENTATION:\n * - All tenants share the same database server\n * - Each tenant has a separate database schema\n * - Schema name typically: tenant_\n * - Application switches schema using SET search_path\n * \n * ADVANTAGES:\n * ✅ Better isolation than row-level (schema boundaries)\n * ✅ Easier to debug (separate schemas)\n * ✅ Can grant different database permissions per schema\n * ✅ Reduced risk of data leakage\n * ✅ Performance isolation (indexes, statistics per schema)\n * ✅ Simplified queries (no tenant_id filtering needed)\n * \n * DISADVANTAGES:\n * ❌ More complex backups (must backup all schemas)\n * ❌ Higher migration costs (schema changes across all tenants)\n * ❌ Schema proliferation (PostgreSQL has limits)\n * ❌ Connection overhead (switching schemas)\n * ❌ More complex monitoring and maintenance\n * \n * SECURITY CONSIDERATIONS:\n * - Ensure proper schema permissions (GRANT USAGE ON SCHEMA)\n * - Validate schema name to prevent SQL injection\n * - Implement connection-level schema switching\n * - Audit schema access patterns\n * - Prevent cross-schema queries in application\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant schema\n * CREATE SCHEMA tenant_123;\n * \n * -- Grant access\n * GRANT USAGE ON SCHEMA tenant_123 TO app_user;\n * \n * -- Switch to tenant schema\n * SET search_path TO tenant_123, public;\n * ```\n */\nexport const SchemaLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_schema').describe('Schema-level isolation strategy'),\n \n /**\n * Schema configuration\n */\n schema: z.object({\n /**\n * Schema naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Schema naming pattern'),\n \n /**\n * Whether to include public schema in search_path\n */\n includePublicSchema: z.boolean().default(true).describe('Include public schema'),\n \n /**\n * Default schema for shared resources\n */\n sharedSchema: z.string().default('public').describe('Schema for shared resources'),\n \n /**\n * Whether to automatically create schema on tenant creation\n */\n autoCreateSchema: z.boolean().default(true).describe('Auto-create schema'),\n }).optional().describe('Schema configuration'),\n \n /**\n * Migration configuration\n */\n migrations: z.object({\n /**\n * Migration strategy\n */\n strategy: z.enum([\n 'parallel', // Run migrations on all schemas in parallel\n 'sequential', // Run migrations one schema at a time\n 'on_demand', // Run migrations when tenant accesses system\n ]).default('parallel').describe('Migration strategy'),\n \n /**\n * Maximum concurrent migrations\n */\n maxConcurrent: z.number().int().positive().default(10).describe('Max concurrent migrations'),\n \n /**\n * Whether to rollback on first failure\n */\n rollbackOnError: z.boolean().default(true).describe('Rollback on error'),\n }).optional().describe('Migration configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use connection pooling per schema\n */\n poolPerSchema: z.boolean().default(false).describe('Separate pool per schema'),\n \n /**\n * Schema cache TTL in seconds\n */\n schemaCacheTTL: z.number().int().positive().default(3600).describe('Schema cache TTL'),\n }).optional().describe('Performance settings'),\n});\n\nexport type SchemaLevelIsolationStrategy = z.infer;\nexport type SchemaLevelIsolationStrategyInput = z.input;\n\n/**\n * Database-Level Isolation Strategy (isolated_db)\n * \n * Recommended for: Regulated industries (healthcare, finance), strict compliance requirements\n * \n * IMPLEMENTATION:\n * - Each tenant has a completely separate database\n * - Database name typically: tenant_\n * - Requires separate connection pool per tenant\n * - Complete physical and logical isolation\n * \n * ADVANTAGES:\n * ✅ Perfect data isolation (strongest security)\n * ✅ Meets strict regulatory requirements (HIPAA, SOX, PCI-DSS)\n * ✅ Complete performance isolation (no noisy neighbors)\n * ✅ Can place databases on different hardware\n * ✅ Easy to backup/restore individual tenant\n * ✅ Simplified compliance auditing per tenant\n * ✅ Can apply different encryption keys per database\n * \n * DISADVANTAGES:\n * ❌ Most expensive option (resource overhead)\n * ❌ Complex database server management (many databases)\n * ❌ Connection pool limits (max connections per server)\n * ❌ Difficult cross-tenant analytics\n * ❌ Higher operational complexity\n * ❌ Schema migrations take longer (many databases)\n * \n * SECURITY CONSIDERATIONS:\n * - Each database can have separate credentials\n * - Enables per-tenant encryption at rest\n * - Simplifies compliance and audit trails\n * - Prevents any cross-tenant data access\n * - Supports tenant-specific backup schedules\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant database\n * CREATE DATABASE tenant_123\n * WITH OWNER = tenant_123_user\n * ENCODING = 'UTF8'\n * LC_COLLATE = 'en_US.UTF-8'\n * LC_CTYPE = 'en_US.UTF-8';\n * \n * -- Connect to tenant database\n * \\c tenant_123\n * ```\n */\nexport const DatabaseLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_db').describe('Database-level isolation strategy'),\n \n /**\n * Database configuration\n */\n database: z.object({\n /**\n * Database naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Database naming pattern'),\n \n /**\n * Database server/cluster assignment strategy\n */\n serverStrategy: z.enum([\n 'shared', // All tenant databases on same server\n 'sharded', // Tenant databases distributed across servers\n 'dedicated', // Each tenant gets dedicated server (enterprise)\n ]).default('shared').describe('Server assignment strategy'),\n \n /**\n * Whether to use separate credentials per tenant\n */\n separateCredentials: z.boolean().default(true).describe('Separate credentials per tenant'),\n \n /**\n * Whether to automatically create database on tenant creation\n */\n autoCreateDatabase: z.boolean().default(true).describe('Auto-create database'),\n }).optional().describe('Database configuration'),\n \n /**\n * Connection pooling configuration\n */\n connectionPool: z.object({\n /**\n * Pool size per tenant database\n */\n poolSize: z.number().int().positive().default(10).describe('Connection pool size'),\n \n /**\n * Maximum number of tenant pools to keep active\n */\n maxActivePools: z.number().int().positive().default(100).describe('Max active pools'),\n \n /**\n * Idle pool timeout in seconds\n */\n idleTimeout: z.number().int().positive().default(300).describe('Idle pool timeout'),\n \n /**\n * Whether to use connection pooler (PgBouncer, etc.)\n */\n usePooler: z.boolean().default(true).describe('Use connection pooler'),\n }).optional().describe('Connection pool configuration'),\n \n /**\n * Backup and restore configuration\n */\n backup: z.object({\n /**\n * Backup strategy per tenant\n */\n strategy: z.enum([\n 'individual', // Separate backup per tenant\n 'consolidated', // Combined backup with all tenants\n 'on_demand', // Backup only when requested\n ]).default('individual').describe('Backup strategy'),\n \n /**\n * Backup frequency in hours\n */\n frequencyHours: z.number().int().positive().default(24).describe('Backup frequency'),\n \n /**\n * Retention period in days\n */\n retentionDays: z.number().int().positive().default(30).describe('Backup retention days'),\n }).optional().describe('Backup configuration'),\n \n /**\n * Encryption configuration\n */\n encryption: z.object({\n /**\n * Whether to use per-tenant encryption keys\n */\n perTenantKeys: z.boolean().default(false).describe('Per-tenant encryption keys'),\n \n /**\n * Encryption algorithm\n */\n algorithm: z.string().default('AES-256-GCM').describe('Encryption algorithm'),\n \n /**\n * Key management service\n */\n keyManagement: z.enum(['aws_kms', 'azure_key_vault', 'gcp_kms', 'hashicorp_vault', 'custom']).optional().describe('Key management service'),\n }).optional().describe('Encryption configuration'),\n});\n\nexport type DatabaseLevelIsolationStrategy = z.infer;\nexport type DatabaseLevelIsolationStrategyInput = z.input;\n\n/**\n * Tenant Isolation Configuration Schema\n * \n * Complete configuration for tenant isolation strategy.\n * Supports all three isolation levels with detailed configuration options.\n */\nexport const TenantIsolationConfigSchema = z.discriminatedUnion('strategy', [\n RowLevelIsolationStrategySchema,\n SchemaLevelIsolationStrategySchema,\n DatabaseLevelIsolationStrategySchema,\n]);\n\nexport type TenantIsolationConfig = z.infer;\n\n/**\n * Tenant Security Policy Schema\n * Defines security policies and compliance requirements for tenants\n */\nexport const TenantSecurityPolicySchema = z.object({\n /**\n * Encryption requirements\n */\n encryption: z.object({\n /**\n * Require encryption at rest\n */\n atRest: z.boolean().default(true).describe('Require encryption at rest'),\n \n /**\n * Require encryption in transit\n */\n inTransit: z.boolean().default(true).describe('Require encryption in transit'),\n \n /**\n * Require field-level encryption for sensitive data\n */\n fieldLevel: z.boolean().default(false).describe('Require field-level encryption'),\n }).optional().describe('Encryption requirements'),\n \n /**\n * Access control requirements\n */\n accessControl: z.object({\n /**\n * Require multi-factor authentication\n */\n requireMFA: z.boolean().default(false).describe('Require MFA'),\n \n /**\n * Require SSO/SAML authentication\n */\n requireSSO: z.boolean().default(false).describe('Require SSO'),\n \n /**\n * IP whitelist\n */\n ipWhitelist: z.array(z.string()).optional().describe('Allowed IP addresses'),\n \n /**\n * Session timeout in seconds\n */\n sessionTimeout: z.number().int().positive().default(3600).describe('Session timeout'),\n }).optional().describe('Access control requirements'),\n \n /**\n * Audit and compliance requirements\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox',\n 'hipaa',\n 'gdpr',\n 'pci_dss',\n 'iso_27001',\n 'fedramp',\n ])).optional().describe('Compliance standards'),\n \n /**\n * Require audit logging for all operations\n */\n requireAuditLog: z.boolean().default(true).describe('Require audit logging'),\n \n /**\n * Audit log retention period in days\n */\n auditRetentionDays: z.number().int().positive().default(365).describe('Audit retention days'),\n \n /**\n * Data residency requirements\n */\n dataResidency: z.object({\n /**\n * Required geographic region\n */\n region: z.string().optional().describe('Required region (e.g., US, EU, APAC)'),\n \n /**\n * Prohibited regions\n */\n excludeRegions: z.array(z.string()).optional().describe('Prohibited regions'),\n }).optional().describe('Data residency requirements'),\n }).optional().describe('Compliance requirements'),\n});\n\nexport type TenantSecurityPolicy = z.infer;\nexport type TenantSecurityPolicyInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TenantQuotaSchema } from '../system/tenant.zod.js';\n\n/**\n * Runtime Mode Enum\n * Defines the operating mode of the kernel\n */\nexport const RuntimeMode = z.enum([\n 'development', // Hot-reload, verbose logging\n 'production', // Optimized, strict security\n 'test', // Mocked interfaces\n 'provisioning', // Setup/Migration mode\n 'preview', // Demo/preview mode — bypass auth, simulate admin identity\n]).describe('Kernel operating mode');\n\nexport type RuntimeMode = z.infer;\n\n/**\n * Preview Mode Configuration Schema\n *\n * Configures the kernel's preview/demo mode behaviour.\n * When `mode` is set to `'preview'`, the platform skips authentication\n * screens and optionally simulates an admin identity so that visitors\n * (e.g. app-marketplace customers) can explore the system without\n * registering or logging in.\n *\n * **Security note:** preview mode should NEVER be used in production.\n * The runtime must enforce this constraint.\n *\n * @example\n * ```ts\n * const ctx = KernelContextSchema.parse({\n * instanceId: '550e8400-e29b-41d4-a716-446655440000',\n * mode: 'preview',\n * version: '1.0.0',\n * cwd: '/app',\n * startTime: Date.now(),\n * previewMode: {\n * autoLogin: true,\n * simulatedRole: 'admin',\n * },\n * });\n * ```\n */\nexport const PreviewModeConfigSchema = z.object({\n /**\n * Automatically log in as a simulated user on startup.\n * When enabled, the frontend skips login/registration screens entirely.\n */\n autoLogin: z.boolean().default(true)\n .describe('Auto-login as simulated user, skipping login/registration pages'),\n\n /**\n * Role of the simulated user.\n * Determines the permission level of the auto-created preview session.\n */\n simulatedRole: z.enum(['admin', 'user', 'viewer']).default('admin')\n .describe('Permission role for the simulated preview user'),\n\n /**\n * Display name for the simulated user shown in the UI.\n */\n simulatedUserName: z.string().default('Preview User')\n .describe('Display name for the simulated preview user'),\n\n /**\n * Whether the preview session is read-only.\n * When true, all write operations (create, update, delete) are blocked.\n */\n readOnly: z.boolean().default(false)\n .describe('Restrict the preview session to read-only operations'),\n\n /**\n * Session duration in seconds. After expiry the preview session ends.\n * 0 means no expiration.\n */\n expiresInSeconds: z.number().int().min(0).default(0)\n .describe('Preview session duration in seconds (0 = no expiration)'),\n\n /**\n * Optional banner message shown in the UI to indicate preview mode.\n * Useful for marketplace demos so visitors know they are in a sandbox.\n */\n bannerMessage: z.string().optional()\n .describe('Banner message displayed in the UI during preview mode'),\n});\n\nexport type PreviewModeConfig = z.infer;\n\n/**\n * Kernel Context Schema\n * Defines the static environment information available to the Kernel at boot.\n */\nexport const KernelContextSchema = z.object({\n /**\n * Instance Identity\n */\n instanceId: z.string().uuid().describe('Unique UUID for this running kernel process'),\n \n /**\n * Environment Metadata\n */\n mode: RuntimeMode.default('production'),\n version: z.string().describe('Kernel version'),\n appName: z.string().optional().describe('Host application name'),\n \n /**\n * Paths\n */\n cwd: z.string().describe('Current working directory'),\n workspaceRoot: z.string().optional().describe('Workspace root if different from cwd'),\n \n /**\n * Telemetry\n */\n startTime: z.number().int().describe('Boot timestamp (ms)'),\n \n /**\n * Feature Flags (Global)\n */\n features: z.record(z.string(), z.boolean()).default({}).describe('Global feature toggles'),\n\n /**\n * Preview Mode Configuration.\n * Only relevant when `mode` is `'preview'`. Configures auto-login,\n * simulated identity, read-only restrictions, and UI banner.\n */\n previewMode: PreviewModeConfigSchema.optional()\n .describe('Preview/demo mode configuration (used when mode is \"preview\")'),\n});\n\nexport type KernelContext = z.infer;\n\n// ==========================================================================\n// Tenant Runtime Context\n// ==========================================================================\n\n/**\n * Tenant Runtime Context Schema.\n *\n * Extends the base KernelContext with tenant-specific information.\n * Constructed per-request from: session → org → tenant lookup.\n * Provides the tenant identity, plan, region, and database URL to all\n * downstream services during request processing.\n */\nexport const TenantRuntimeContextSchema = KernelContextSchema.extend({\n /** Unique tenant identifier resolved from the current session */\n tenantId: z.string().min(1).describe('Resolved tenant identifier'),\n\n /** Tenant subscription plan */\n tenantPlan: z.enum(['free', 'pro', 'enterprise']).describe('Tenant subscription plan'),\n\n /** Tenant deployment region */\n tenantRegion: z.string().optional().describe('Tenant deployment region'),\n\n /** Tenant database connection URL */\n tenantDbUrl: z.string().min(1).describe('Tenant database connection URL'),\n\n /** Optional tenant quotas for the current plan */\n tenantQuotas: TenantQuotaSchema.optional().describe('Tenant resource quotas'),\n}).describe('Tenant-aware kernel runtime context');\n\nexport type TenantRuntimeContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dependency Resolution Protocol\n *\n * Defines schemas for runtime dependency resolution when installing,\n * upgrading, or managing packages. Provides a standardized way to\n * express dependency conflicts, resolution results, and installation order.\n *\n * ## Architecture Alignment\n * - **npm**: Dependency tree resolution with conflict detection\n * - **Helm**: Dependency management with version constraints\n * - **Salesforce**: Package dependency validation at install time\n *\n * ## Resolution Flow\n * ```\n * 1. Parse manifest.dependencies (SemVer ranges)\n * 2. Check installed packages registry\n * 3. Resolve each dependency → satisfied | needs_install | needs_upgrade | conflict\n * 4. Detect circular dependencies\n * 5. Compute topological install order\n * 6. Return resolution result with required actions\n * ```\n */\n\n// ==========================================\n// Dependency Resolution Status\n// ==========================================\n\n/**\n * Resolution status for a single dependency.\n */\nexport const DependencyStatusEnum = z.enum([\n 'satisfied', // Already installed and version compatible\n 'needs_install', // Not installed, needs to be installed\n 'needs_upgrade', // Installed but version incompatible, needs upgrade\n 'conflict', // Conflicts with another package's dependency\n]).describe('Resolution status for a dependency');\n\nexport type DependencyStatus = z.infer;\n\n// ==========================================\n// Resolved Dependency\n// ==========================================\n\n/**\n * Single dependency resolution result.\n * Describes the state of one dependency after resolution.\n */\nexport const ResolvedDependencySchema = z.object({\n /** Package identifier of the dependency */\n packageId: z.string().describe('Dependency package identifier'),\n\n /** SemVer range required by the parent package */\n requiredRange: z.string().describe('SemVer range required (e.g. \"^2.0.0\")'),\n\n /** Actual version resolved (if available) */\n resolvedVersion: z.string().optional()\n .describe('Actual version resolved from registry'),\n\n /** Currently installed version (if any) */\n installedVersion: z.string().optional()\n .describe('Currently installed version'),\n\n /** Resolution status */\n status: DependencyStatusEnum.describe('Resolution status'),\n\n /** Conflict details (when status is \"conflict\") */\n conflictReason: z.string().optional()\n .describe('Explanation of the conflict'),\n}).describe('Resolution result for a single dependency');\n\nexport type ResolvedDependency = z.infer;\n\n// ==========================================\n// Required Action\n// ==========================================\n\n/**\n * An action required before installation can proceed.\n */\nexport const RequiredActionSchema = z.object({\n /** Type of action required */\n type: z.enum(['install', 'upgrade', 'confirm_conflict'])\n .describe('Type of action required'),\n\n /** Target package identifier */\n packageId: z.string().describe('Target package identifier'),\n\n /** Human-readable description of the action */\n description: z.string().describe('Human-readable action description'),\n}).describe('Action required before installation can proceed');\n\nexport type RequiredAction = z.infer;\n\n// ==========================================\n// Dependency Resolution Result\n// ==========================================\n\n/**\n * Complete dependency resolution result.\n * Aggregates all dependency statuses and computes installation feasibility.\n */\nexport const DependencyResolutionResultSchema = z.object({\n /** All dependencies and their resolution results */\n dependencies: z.array(ResolvedDependencySchema)\n .describe('Resolution result for each dependency'),\n\n /** Whether installation can proceed without conflicts */\n canProceed: z.boolean()\n .describe('Whether installation can proceed'),\n\n /** Actions that require user confirmation or system execution */\n requiredActions: z.array(RequiredActionSchema)\n .describe('Actions required before proceeding'),\n\n /** Topologically sorted package IDs for installation order */\n installOrder: z.array(z.string())\n .describe('Topologically sorted package IDs for installation'),\n\n /** Detected circular dependency chains */\n circularDependencies: z.array(z.array(z.string())).optional()\n .describe('Circular dependency chains detected (e.g. [[\"A\", \"B\", \"A\"]])'),\n}).describe('Complete dependency resolution result');\n\nexport type DependencyResolutionResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dev Mode Plugin Protocol\n *\n * Defines the schema for a development-mode plugin that automatically enables\n * all platform services for local simulation. When loaded as a `devPlugin`,\n * the kernel bootstraps every subsystem (data, UI, API, auth, events, jobs, …)\n * using in-memory or stub implementations so that developers can exercise the\n * full stack without external dependencies.\n *\n * Design goals:\n * - Zero-config by default: `devPlugins: ['@objectstack/plugin-dev']`\n * - Every service can be overridden or disabled individually\n * - Preset profiles (minimal / standard / full) for common scenarios\n *\n * Inspired by:\n * - Spring Boot DevTools (auto-configuration)\n * - Next.js Dev Server (HMR + mock APIs)\n * - Vite Plugin Dev Mode (instant startup)\n */\n\n// ============================================================================\n// Dev Service Override\n// ============================================================================\n\n/**\n * Dev Service Override Schema\n *\n * Allows fine-grained control over a single service in development mode.\n * Each override targets a service by name and specifies whether it should\n * be enabled, which implementation strategy to use, and optional config.\n */\nexport const DevServiceOverrideSchema = z.object({\n /** Service identifier (e.g. 'auth', 'eventBus', 'fileStorage') */\n service: z.string().min(1).describe('Target service identifier'),\n\n /** Whether this service is enabled in dev mode */\n enabled: z.boolean().default(true).describe('Enable or disable this service'),\n\n /**\n * Implementation strategy for the service in dev mode.\n * - mock: Use a mock/stub that records calls (for assertions)\n * - memory: Use a real but in-memory implementation (e.g. SQLite, Map)\n * - stub: Use a static/no-op implementation\n * - passthrough: Use the real production implementation (for integration testing)\n */\n strategy: z.enum(['mock', 'memory', 'stub', 'passthrough']).default('memory')\n .describe('Implementation strategy for development'),\n\n /** Optional per-service configuration (strategy-specific) */\n config: z.record(z.string(), z.unknown()).optional()\n .describe('Strategy-specific configuration for this service override'),\n});\n\nexport type DevServiceOverride = z.infer;\n\n// ============================================================================\n// Dev Fixture Configuration\n// ============================================================================\n\n/**\n * Dev Fixture Config Schema\n *\n * Configures automatic seed/fixture data loading in development mode.\n * Fixtures provide a reproducible dataset for local development and demos.\n */\nexport const DevFixtureConfigSchema = z.object({\n /** Whether to load fixtures on startup */\n enabled: z.boolean().default(true).describe('Load fixture data on startup'),\n\n /**\n * Glob patterns pointing to fixture files\n * (e.g. `[\"./fixtures/*.json\", \"./test/data/*.yml\"]`)\n */\n paths: z.array(z.string()).optional()\n .describe('Glob patterns for fixture files'),\n\n /** Whether to reset data before loading fixtures */\n resetBeforeLoad: z.boolean().default(true)\n .describe('Clear existing data before loading fixtures'),\n\n /**\n * Environment tag filter – only load fixtures tagged for these environments.\n * When omitted, all fixtures are loaded.\n */\n envFilter: z.array(z.string()).optional()\n .describe('Only load fixtures matching these environment tags'),\n});\n\nexport type DevFixtureConfig = z.infer;\n\n// ============================================================================\n// Dev Tools Configuration\n// ============================================================================\n\n/**\n * Dev Tools Config Schema\n *\n * Optional developer tooling that can be enabled alongside the dev plugin.\n */\nexport const DevToolsConfigSchema = z.object({\n /** Enable hot-module replacement / live reload */\n hotReload: z.boolean().default(true).describe('Enable HMR / live-reload'),\n\n /** Enable request inspector UI for debugging HTTP traffic */\n requestInspector: z.boolean().default(false).describe('Enable request inspector'),\n\n /** Enable an in-browser database explorer */\n dbExplorer: z.boolean().default(false).describe('Enable database explorer UI'),\n\n /** Enable verbose logging across all services */\n verboseLogging: z.boolean().default(true).describe('Enable verbose logging'),\n\n /** Enable OpenAPI / Swagger documentation endpoint */\n apiDocs: z.boolean().default(true).describe('Serve OpenAPI docs at /_dev/docs'),\n\n /** Enable a mail catcher for outbound email (like MailHog) */\n mailCatcher: z.boolean().default(false).describe('Capture outbound emails in dev'),\n});\n\nexport type DevToolsConfig = z.infer;\n\n// ============================================================================\n// Dev Plugin Preset\n// ============================================================================\n\n/**\n * Dev Plugin Preset\n *\n * Predefined configuration profiles for common development scenarios.\n * - minimal: Only core data services (fast startup, low memory)\n * - standard: Core + API + auth + events (typical full-stack dev)\n * - full: Every service enabled, including background jobs and AI agents\n */\nexport const DevPluginPreset = z.enum([\n 'minimal',\n 'standard',\n 'full',\n]).describe('Predefined dev configuration profile');\n\nexport type DevPluginPreset = z.infer;\n\n// ============================================================================\n// Dev Plugin Configuration\n// ============================================================================\n\n/**\n * Dev Plugin Config Schema\n *\n * Top-level configuration for the development-mode plugin.\n * This is the shape of the configuration payload that\n * `@objectstack/plugin-dev` (or equivalent) understands.\n *\n * The outer wiring (e.g. how a stack declares `devPlugins`) is defined\n * by the stack/manifest schemas; this type only describes the plugin's\n * own config object.\n *\n * @example Minimal usage (zero-config)\n * ```ts\n * const devConfig: DevPluginConfig = {};\n * ```\n *\n * @example With preset\n * ```ts\n * const devConfig: DevPluginConfig = {\n * preset: 'full',\n * };\n * ```\n *\n * @example Fine-grained overrides\n * ```ts\n * const devConfig: DevPluginConfig = {\n * preset: 'standard',\n * services: {\n * auth: { enabled: true, strategy: 'mock' },\n * fileStorage: { enabled: false },\n * },\n * fixtures: { paths: ['./fixtures/*.json'] },\n * tools: { dbExplorer: true },\n * };\n * ```\n */\nexport const DevPluginConfigSchema = z.object({\n /**\n * Configuration preset.\n * When provided, services and tools are pre-configured for the selected\n * profile. Individual `services` and `tools` settings override the preset.\n * @default 'standard'\n */\n preset: DevPluginPreset.default('standard')\n .describe('Base configuration preset'),\n\n /**\n * Per-service overrides.\n * Keys are service names; values configure the dev strategy.\n * Only services explicitly listed here override the preset defaults.\n */\n services: z.record(\n z.string().min(1),\n DevServiceOverrideSchema.omit({ service: true }),\n ).optional().describe('Per-service dev overrides keyed by service name'),\n\n /** Fixture / seed data configuration */\n fixtures: DevFixtureConfigSchema.optional()\n .describe('Fixture data loading configuration'),\n\n /** Developer tooling configuration */\n tools: DevToolsConfigSchema.optional()\n .describe('Developer tooling settings'),\n\n /**\n * Port for the dev-tools UI dashboard.\n * Serves a lightweight web dashboard for inspecting services, events,\n * and request logs during development.\n * @default 4400\n */\n port: z.number().int().min(1).max(65535).default(4400)\n .describe('Port for the dev-tools dashboard'),\n\n /**\n * Auto-open the dev-tools dashboard in the default browser on startup.\n */\n open: z.boolean().default(false)\n .describe('Auto-open dev dashboard in browser'),\n\n /**\n * Seed a default admin user for development.\n * When enabled, the dev plugin creates a pre-authenticated admin user\n * so that developers can bypass login flows.\n */\n seedAdminUser: z.boolean().default(true)\n .describe('Create a default admin user for development'),\n\n /**\n * Simulated latency (ms) to add to service calls.\n * Helps developers build UIs that handle loading states correctly.\n * Set to 0 to disable.\n */\n simulatedLatency: z.number().int().min(0).default(0)\n .describe('Artificial latency (ms) added to service calls'),\n});\n\nexport type DevPluginConfig = z.infer;\nexport type DevPluginConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventNameSchema } from '../../shared/identifiers.zod';\n\n// ==========================================\n// Event Priority\n// ==========================================\n\n/**\n * Event Priority Enum\n * Priority levels for event processing\n * Lower numbers = higher priority\n */\nexport const EventPriority = z.enum([\n 'critical', // 0 - Process immediately, block if necessary\n 'high', // 1 - Process soon, minimal delay\n 'normal', // 2 - Default priority\n 'low', // 3 - Process when resources available\n 'background', // 4 - Process during idle time\n]);\n\nexport type EventPriority = z.infer;\n\n/**\n * Event Priority Values\n * Maps priority names to numeric values for sorting\n */\nexport const EVENT_PRIORITY_VALUES: Record = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n background: 4,\n};\n\n// ==========================================\n// Event Metadata\n// ==========================================\n\n/**\n * Event Metadata Schema\n * Metadata associated with every event\n */\nexport const EventMetadataSchema = z.object({\n source: z.string().describe('Event source (e.g., plugin name, system component)'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when event was created'),\n userId: z.string().optional().describe('User who triggered the event'),\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant systems'),\n correlationId: z.string().optional().describe('Correlation ID for event tracing'),\n causationId: z.string().optional().describe('ID of the event that caused this event'),\n priority: EventPriority.optional().default('normal').describe('Event priority'),\n});\n\n// ==========================================\n// Event Schema\n// ==========================================\n\n/**\n * Event Type Definition Schema\n * Defines the structure of an event type\n * \n * @example\n * {\n * \"name\": \"order.created\",\n * \"version\": \"1.0.0\",\n * \"schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"orderId\": { \"type\": \"string\" },\n * \"customerId\": { \"type\": \"string\" },\n * \"total\": { \"type\": \"number\" }\n * }\n * }\n * }\n */\nexport const EventTypeDefinitionSchema = z.object({\n name: EventNameSchema.describe('Event type name (lowercase with dots)'),\n version: z.string().default('1.0.0').describe('Event schema version'),\n schema: z.unknown().optional().describe('JSON Schema for event payload validation'),\n description: z.string().optional().describe('Event type description'),\n deprecated: z.boolean().optional().default(false).describe('Whether this event type is deprecated'),\n tags: z.array(z.string()).optional().describe('Event type tags'),\n});\n\nexport type EventTypeDefinition = z.infer;\n\n/**\n * Event Schema\n * Base schema for all events in the system\n * \n * Event names follow dot notation for namespacing (e.g., 'user.created', 'order.paid').\n * This aligns with industry standards for event-driven architectures and message queues.\n */\nexport const EventSchema = z.object({\n /**\n * Event identifier (for tracking and deduplication)\n */\n id: z.string().optional().describe('Unique event identifier'),\n \n /**\n * Event name\n */\n name: EventNameSchema.describe('Event name (lowercase with dots, e.g., user.created, order.paid)'),\n \n /**\n * Event payload\n */\n payload: z.unknown().describe('Event payload schema'),\n \n /**\n * Event metadata\n */\n metadata: EventMetadataSchema.describe('Event metadata'),\n});\n\nexport type Event = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Event Handlers\n// ==========================================\n\n/**\n * Event Handler Schema\n * Defines how to handle a specific event\n */\nexport const EventHandlerSchema = z.object({\n /**\n * Handler identifier\n */\n id: z.string().optional().describe('Unique handler identifier'),\n \n /**\n * Event name pattern\n */\n eventName: z.string().describe('Name of event to handle (supports wildcards like user.*)'),\n \n /**\n * Handler function\n */\n handler: z.unknown()\n .describe('Handler function'),\n \n /**\n * Execution priority\n */\n priority: z.number().int().default(0).describe('Execution priority (lower numbers execute first)'),\n \n /**\n * Async execution\n */\n async: z.boolean().default(true).describe('Execute in background (true) or block (false)'),\n \n /**\n * Retry configuration\n */\n retry: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),\n backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay'),\n backoffMultiplier: z.number().positive().default(2).describe('Backoff multiplier'),\n }).optional().describe('Retry policy for failed handlers'),\n \n /**\n * Timeout\n */\n timeoutMs: z.number().int().positive().optional().describe('Handler timeout in milliseconds'),\n \n /**\n * Filter function\n */\n filter: z.unknown()\n .optional()\n .describe('Optional filter to determine if handler should execute'),\n});\n\nexport type EventHandler = z.infer;\n\n/**\n * Event Route Schema\n * Routes events from one pattern to multiple targets with optional transformation\n */\nexport const EventRouteSchema = z.object({\n from: z.string().describe('Source event pattern (supports wildcards, e.g., user.* or *.created)'),\n to: z.array(z.string()).describe('Target event names to route to'),\n transform: z.unknown().optional().describe('Optional function to transform payload'),\n});\n\nexport type EventRoute = z.infer;\n\n/**\n * Event Persistence Schema\n * Configuration for persisting events to storage\n */\nexport const EventPersistenceSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable event persistence'),\n retention: z.number().int().positive().describe('Days to retain persisted events'),\n filter: z.unknown().optional().describe('Optional filter function to select which events to persist'),\n storage: z.enum(['database', 'file', 's3', 'custom']).default('database')\n .describe('Storage backend for persisted events'),\n});\n\nexport type EventPersistence = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Event Queue\n// ==========================================\n\n/**\n * Event Queue Configuration Schema\n * Configuration for async event processing queue\n * \n * @example\n * {\n * \"name\": \"event_queue\",\n * \"concurrency\": 10,\n * \"retryPolicy\": {\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * }\n * }\n */\nexport const EventQueueConfigSchema = z.object({\n /**\n * Queue name\n */\n name: z.string().default('events').describe('Event queue name'),\n \n /**\n * Concurrency\n */\n concurrency: z.number().int().min(1).default(10).describe('Max concurrent event handlers'),\n \n /**\n * Retry policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Max retries for failed events'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay'),\n }).optional().describe('Default retry policy for events'),\n \n /**\n * Dead letter queue\n */\n deadLetterQueue: z.string().optional().describe('Dead letter queue name for failed events'),\n \n /**\n * Enable priority processing\n */\n priorityEnabled: z.boolean().default(true).describe('Process events based on priority'),\n});\n\nexport type EventQueueConfig = z.infer;\n\n// ==========================================\n// Event Replay\n// ==========================================\n\n/**\n * Event Replay Configuration Schema\n * Configuration for replaying historical events\n * \n * @example\n * {\n * \"fromTimestamp\": \"2024-01-01T00:00:00Z\",\n * \"toTimestamp\": \"2024-01-31T23:59:59Z\",\n * \"eventTypes\": [\"order.created\", \"order.updated\"],\n * \"speed\": 10\n * }\n */\nexport const EventReplayConfigSchema = z.object({\n /**\n * Start timestamp\n */\n fromTimestamp: z.string().datetime().describe('Start timestamp for replay (ISO 8601)'),\n \n /**\n * End timestamp\n */\n toTimestamp: z.string().datetime().optional().describe('End timestamp for replay (ISO 8601)'),\n \n /**\n * Event types to replay\n */\n eventTypes: z.array(z.string()).optional().describe('Event types to replay (empty = all)'),\n \n /**\n * Event filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters for event selection'),\n \n /**\n * Replay speed multiplier\n */\n speed: z.number().positive().default(1).describe('Replay speed multiplier (1 = real-time)'),\n \n /**\n * Target handlers\n */\n targetHandlers: z.array(z.string()).optional().describe('Handler IDs to execute (empty = all)'),\n});\n\nexport type EventReplayConfig = z.infer;\n\n// ==========================================\n// Event Sourcing\n// ==========================================\n\n/**\n * Event Sourcing Configuration Schema\n * Configuration for event sourcing pattern\n * \n * Event sourcing stores all changes to application state as a sequence of events.\n * The current state can be reconstructed by replaying the events.\n * \n * @example\n * {\n * \"enabled\": true,\n * \"snapshotInterval\": 100,\n * \"retention\": 365\n * }\n */\nexport const EventSourcingConfigSchema = z.object({\n /**\n * Enable event sourcing\n */\n enabled: z.boolean().default(false).describe('Enable event sourcing'),\n \n /**\n * Snapshot interval\n */\n snapshotInterval: z.number().int().positive().default(100)\n .describe('Create snapshot every N events'),\n \n /**\n * Snapshot retention\n */\n snapshotRetention: z.number().int().positive().default(10)\n .describe('Number of snapshots to retain'),\n \n /**\n * Event retention\n */\n retention: z.number().int().positive().default(365)\n .describe('Days to retain events'),\n \n /**\n * Aggregate types\n */\n aggregateTypes: z.array(z.string()).optional()\n .describe('Aggregate types to enable event sourcing for'),\n \n /**\n * Storage configuration\n */\n storage: z.object({\n type: z.enum(['database', 'file', 's3', 'eventstore']).default('database')\n .describe('Storage backend'),\n options: z.record(z.string(), z.unknown()).optional().describe('Storage-specific options'),\n }).optional().describe('Event store configuration'),\n});\n\nexport type EventSourcingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventSchema } from './core.zod';\n\n// ==========================================\n// Dead Letter Queue\n// ==========================================\n\n/**\n * Dead Letter Queue Entry Schema\n * Represents a failed event in the dead letter queue\n */\nexport const DeadLetterQueueEntrySchema = z.object({\n /**\n * Entry identifier\n */\n id: z.string().describe('Unique entry identifier'),\n \n /**\n * Original event\n */\n event: EventSchema.describe('Original event'),\n \n /**\n * Failure reason\n */\n error: z.object({\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Error stack trace'),\n code: z.string().optional().describe('Error code'),\n }).describe('Failure details'),\n \n /**\n * Retry count\n */\n retries: z.number().int().min(0).describe('Number of retry attempts'),\n \n /**\n * Timestamps\n */\n firstFailedAt: z.string().datetime().describe('When event first failed'),\n lastFailedAt: z.string().datetime().describe('When event last failed'),\n \n /**\n * Handler that failed\n */\n failedHandler: z.string().optional().describe('Handler ID that failed'),\n});\n\nexport type DeadLetterQueueEntry = z.infer;\n\n// ==========================================\n// Event Log\n// ==========================================\n\n/**\n * Event Log Entry Schema\n * Represents a logged event\n */\nexport const EventLogEntrySchema = z.object({\n /**\n * Log entry ID\n */\n id: z.string().describe('Unique log entry identifier'),\n \n /**\n * Event\n */\n event: EventSchema.describe('The event'),\n \n /**\n * Status\n */\n status: z.enum(['pending', 'processing', 'completed', 'failed']).describe('Processing status'),\n \n /**\n * Handlers executed\n */\n handlersExecuted: z.array(z.object({\n handlerId: z.string().describe('Handler identifier'),\n status: z.enum(['success', 'failed', 'timeout']).describe('Handler execution status'),\n durationMs: z.number().int().optional().describe('Execution duration'),\n error: z.string().optional().describe('Error message if failed'),\n })).optional().describe('Handlers that processed this event'),\n \n /**\n * Timestamps\n */\n receivedAt: z.string().datetime().describe('When event was received'),\n processedAt: z.string().datetime().optional().describe('When event was processed'),\n \n /**\n * Total duration\n */\n totalDurationMs: z.number().int().optional().describe('Total processing time'),\n});\n\nexport type EventLogEntry = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Webhook Integration\n// ==========================================\n\n/**\n * Event Webhook Configuration Schema\n * Configuration for sending events to webhooks\n * \n * @example\n * {\n * \"eventPattern\": \"order.*\",\n * \"url\": \"https://api.example.com/webhooks/orders\",\n * \"method\": \"POST\",\n * \"headers\": { \"Authorization\": \"Bearer token\" }\n * }\n */\nexport const EventWebhookConfigSchema = z.object({\n /**\n * Webhook identifier\n */\n id: z.string().optional().describe('Unique webhook identifier'),\n \n /**\n * Event pattern to match\n */\n eventPattern: z.string().describe('Event name pattern (supports wildcards)'),\n \n /**\n * Target URL\n */\n url: z.string().url().describe('Webhook endpoint URL'),\n \n /**\n * HTTP method\n */\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH']).default('POST').describe('HTTP method'),\n \n /**\n * Headers\n */\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n \n /**\n * Authentication\n */\n authentication: z.object({\n type: z.enum(['none', 'bearer', 'basic', 'api-key']).describe('Auth type'),\n credentials: z.record(z.string(), z.string()).optional().describe('Auth credentials'),\n }).optional().describe('Authentication configuration'),\n \n /**\n * Retry policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Max retry attempts'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Max retry delay'),\n }).optional().describe('Retry policy'),\n \n /**\n * Timeout\n */\n timeoutMs: z.number().int().positive().default(30000).describe('Request timeout in milliseconds'),\n \n /**\n * Event transformation\n */\n transform: z.unknown()\n .optional()\n .describe('Transform event before sending'),\n \n /**\n * Enabled\n */\n enabled: z.boolean().default(true).describe('Whether webhook is enabled'),\n});\n\nexport type EventWebhookConfig = z.infer;\n\n// ==========================================\n// Message Queue Integration\n// ==========================================\n\n/**\n * Event Message Queue Configuration Schema\n * Configuration for publishing events to message queues\n * \n * @example\n * {\n * \"provider\": \"kafka\",\n * \"topic\": \"events\",\n * \"eventPattern\": \"*\",\n * \"partitionKey\": \"metadata.tenantId\"\n * }\n */\nexport const EventMessageQueueConfigSchema = z.object({\n /**\n * Provider\n */\n provider: z.enum(['kafka', 'rabbitmq', 'aws-sqs', 'redis-pubsub', 'google-pubsub', 'azure-service-bus'])\n .describe('Message queue provider'),\n \n /**\n * Topic/Queue name\n */\n topic: z.string().describe('Topic or queue name'),\n \n /**\n * Event pattern\n */\n eventPattern: z.string().default('*').describe('Event name pattern to publish (supports wildcards)'),\n \n /**\n * Partition key\n */\n partitionKey: z.string().optional().describe('JSON path for partition key (e.g., \"metadata.tenantId\")'),\n \n /**\n * Message format\n */\n format: z.enum(['json', 'avro', 'protobuf']).default('json').describe('Message serialization format'),\n \n /**\n * Include metadata\n */\n includeMetadata: z.boolean().default(true).describe('Include event metadata in message'),\n \n /**\n * Compression\n */\n compression: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression'),\n \n /**\n * Batch size\n */\n batchSize: z.number().int().min(1).default(1).describe('Batch size for publishing'),\n \n /**\n * Flush interval\n */\n flushIntervalMs: z.number().int().positive().default(1000).describe('Flush interval for batching'),\n});\n\nexport type EventMessageQueueConfig = z.infer;\n\n// ==========================================\n// Real-time Notifications\n// ==========================================\n\n/**\n * Real-time Notification Configuration Schema\n * Configuration for real-time event notifications via WebSocket/SSE\n * \n * @example\n * {\n * \"enabled\": true,\n * \"protocol\": \"websocket\",\n * \"eventPattern\": \"notification.*\",\n * \"userFilter\": true\n * }\n */\nexport const RealTimeNotificationConfigSchema = z.object({\n /**\n * Enable real-time notifications\n */\n enabled: z.boolean().default(true).describe('Enable real-time notifications'),\n \n /**\n * Protocol\n */\n protocol: z.enum(['websocket', 'sse', 'long-polling']).default('websocket')\n .describe('Real-time protocol'),\n \n /**\n * Event pattern\n */\n eventPattern: z.string().default('*').describe('Event pattern to broadcast'),\n \n /**\n * User-specific filtering\n */\n userFilter: z.boolean().default(true).describe('Filter events by user'),\n \n /**\n * Tenant-specific filtering\n */\n tenantFilter: z.boolean().default(true).describe('Filter events by tenant'),\n \n /**\n * Channels\n */\n channels: z.array(z.object({\n name: z.string().describe('Channel name'),\n eventPattern: z.string().describe('Event pattern for channel'),\n filter: z.unknown()\n .optional()\n .describe('Additional filter function'),\n })).optional().describe('Named channels for event broadcasting'),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n maxEventsPerSecond: z.number().int().positive().describe('Max events per second per client'),\n windowMs: z.number().int().positive().default(1000).describe('Rate limit window'),\n }).optional().describe('Rate limiting configuration'),\n});\n\nexport type RealTimeNotificationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventTypeDefinitionSchema } from './core.zod';\nimport { EventHandlerSchema, EventPersistenceSchema } from './handlers.zod';\nimport { EventQueueConfigSchema, EventSourcingConfigSchema } from './queue.zod';\nimport { EventWebhookConfigSchema, EventMessageQueueConfigSchema, RealTimeNotificationConfigSchema } from './integrations.zod';\n\n// ==========================================\n// Complete Event Bus Configuration\n// ==========================================\n\n/**\n * Event Bus Configuration Schema\n * Complete configuration for the event bus system\n * \n * @example\n * {\n * \"persistence\": { \"enabled\": true, \"retention\": 365 },\n * \"queue\": { \"concurrency\": 20 },\n * \"eventSourcing\": { \"enabled\": true },\n * \"webhooks\": [],\n * \"messageQueue\": { \"provider\": \"kafka\", \"topic\": \"events\" },\n * \"realtime\": { \"enabled\": true, \"protocol\": \"websocket\" }\n * }\n */\nexport const EventBusConfigSchema = z.object({\n /**\n * Event persistence\n */\n persistence: EventPersistenceSchema.optional().describe('Event persistence configuration'),\n \n /**\n * Event queue\n */\n queue: EventQueueConfigSchema.optional().describe('Event queue configuration'),\n \n /**\n * Event sourcing\n */\n eventSourcing: EventSourcingConfigSchema.optional().describe('Event sourcing configuration'),\n \n /**\n * Event replay\n */\n replay: z.object({\n enabled: z.boolean().default(true).describe('Enable event replay capability'),\n }).optional().describe('Event replay configuration'),\n \n /**\n * Webhooks\n */\n webhooks: z.array(EventWebhookConfigSchema).optional().describe('Webhook configurations'),\n \n /**\n * Message queue integration\n */\n messageQueue: EventMessageQueueConfigSchema.optional().describe('Message queue integration'),\n \n /**\n * Real-time notifications\n */\n realtime: RealTimeNotificationConfigSchema.optional().describe('Real-time notification configuration'),\n \n /**\n * Event type definitions\n */\n eventTypes: z.array(EventTypeDefinitionSchema).optional().describe('Event type definitions'),\n \n /**\n * Global handlers\n */\n handlers: z.array(EventHandlerSchema).optional().describe('Global event handlers'),\n});\n\nexport type EventBusConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Feature Rollout Strategy\n */\nexport const FeatureStrategy = z.enum([\n 'boolean', // Simple On/Off\n 'percentage', // Gradual rollout (0-100%)\n 'user_list', // Specific users\n 'group', // Specific groups/roles\n 'custom' // Custom constraint/script\n]);\n\n/**\n * Feature Flag Protocol\n * \n * Manages feature toggles and gradual rollouts.\n * Used for CI/CD, A/B Testing, and Trunk-Based Development.\n */\nexport const FeatureFlagSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Feature key (snake_case)'),\n label: z.string().optional().describe('Display label'),\n description: z.string().optional(),\n \n /** Default state */\n enabled: z.boolean().default(false).describe('Is globally enabled'),\n \n /** Rollout Strategy */\n strategy: FeatureStrategy.default('boolean'),\n \n /** Strategy Configuration */\n conditions: z.object({\n percentage: z.number().min(0).max(100).optional(),\n users: z.array(z.string()).optional(),\n groups: z.array(z.string()).optional(),\n expression: z.string().optional().describe('Custom formula expression')\n }).optional(),\n \n /** Integration */\n environment: z.enum(['dev', 'staging', 'prod', 'all']).default('all')\n .describe('Environment validity'),\n \n /** Expiration */\n expiresAt: z.string().datetime().optional().describe('Feature flag expiration date'),\n});\n\nexport const FeatureFlag = Object.assign(FeatureFlagSchema, {\n create: >(config: T) => config,\n});\n\nexport type FeatureFlag = z.infer;\nexport type FeatureFlagInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Capability Protocol\n * \n * Defines the standard way plugins declare their capabilities, implementations,\n * and conformance levels to ensure interoperability across vendors.\n * \n * Based on the Protocol-Oriented Architecture pattern similar to:\n * - Kubernetes CRDs (Custom Resource Definitions)\n * - OSGi Service Registry\n * - Eclipse Extension Points\n */\n\n/**\n * Capability Conformance Level\n * Indicates how completely a plugin implements a given protocol.\n */\nexport const CapabilityConformanceLevelSchema = z.enum([\n 'full', // Complete implementation of all protocol features\n 'partial', // Subset implementation with specific features listed\n 'experimental', // Unstable/preview implementation\n 'deprecated', // Still supported but scheduled for removal\n]).describe('Level of protocol conformance');\n\n/**\n * Protocol Version Schema\n * Uses semantic versioning to track protocol evolution.\n */\nexport const ProtocolVersionSchema = z.object({\n major: z.number().int().min(0),\n minor: z.number().int().min(0),\n patch: z.number().int().min(0),\n}).describe('Semantic version of the protocol');\n\n/**\n * Protocol Reference\n * Uniquely identifies a protocol/interface that a plugin can implement.\n * \n * Examples:\n * - com.objectstack.protocol.storage.v1\n * - com.objectstack.protocol.auth.oauth2.v2\n * - com.acme.protocol.payment.stripe.v1\n */\nexport const ProtocolReferenceSchema = z.object({\n /**\n * Protocol identifier using reverse domain notation.\n * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+protocol\\.[a-z][a-z0-9._]*\\.v\\d+$/)\n .describe('Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)'),\n \n /**\n * Human-readable protocol name\n */\n label: z.string(),\n \n /**\n * Protocol version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Detailed protocol specification URL or file reference\n */\n specification: z.string().optional().describe('URL or path to protocol specification'),\n \n /**\n * Brief description of what this protocol defines\n */\n description: z.string().optional(),\n});\n\n/**\n * Protocol Feature\n * Represents a specific capability within a protocol.\n */\nexport const ProtocolFeatureSchema = z.object({\n name: z.string().describe('Feature identifier within the protocol'),\n enabled: z.boolean().default(true),\n description: z.string().optional(),\n sinceVersion: z.string().optional().describe('Version when this feature was added'),\n deprecatedSince: z.string().optional().describe('Version when deprecated'),\n});\n\n/**\n * Plugin Capability Declaration\n * Documents what protocols a plugin implements and to what extent.\n */\nexport const PluginCapabilitySchema = z.object({\n /**\n * The protocol being implemented\n */\n protocol: ProtocolReferenceSchema,\n \n /**\n * Conformance level\n */\n conformance: CapabilityConformanceLevelSchema.default('full'),\n \n /**\n * Specific features implemented (required if conformance is 'partial')\n */\n implementedFeatures: z.array(z.string()).optional().describe('List of implemented feature names'),\n \n /**\n * Optional feature flags indicating advanced capabilities\n */\n features: z.array(ProtocolFeatureSchema).optional(),\n \n /**\n * Custom metadata for vendor-specific information\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Testing/Certification status\n */\n certified: z.boolean().default(false).describe('Has passed official conformance tests'),\n certificationDate: z.string().datetime().optional(),\n});\n\n/**\n * Plugin Interface Declaration\n * Defines the contract for services this plugin provides to other plugins.\n */\nexport const PluginInterfaceSchema = z.object({\n /**\n * Unique interface identifier\n * Format: {plugin-id}.interface.{name}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+interface\\.[a-z][a-z0-9._]+$/)\n .describe('Unique interface identifier'),\n \n /**\n * Interface name\n */\n name: z.string(),\n \n /**\n * Description of what this interface provides\n */\n description: z.string().optional(),\n \n /**\n * Interface version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Methods exposed by this interface\n */\n methods: z.array(z.object({\n name: z.string().describe('Method name'),\n description: z.string().optional(),\n parameters: z.array(z.object({\n name: z.string(),\n type: z.string().describe('Type notation (e.g., string, number, User)'),\n required: z.boolean().default(true),\n description: z.string().optional(),\n })).optional(),\n returnType: z.string().optional().describe('Return value type'),\n async: z.boolean().default(false).describe('Whether method returns a Promise'),\n })),\n \n /**\n * Events emitted by this interface\n */\n events: z.array(z.object({\n name: z.string().describe('Event name'),\n description: z.string().optional(),\n payload: z.string().optional().describe('Event payload type'),\n })).optional(),\n \n /**\n * Stability level\n */\n stability: z.enum(['stable', 'beta', 'alpha', 'experimental']).default('stable'),\n});\n\n/**\n * Plugin Dependency Declaration\n * Specifies what other plugins or capabilities this plugin requires.\n */\nexport const PluginDependencySchema = z.object({\n /**\n * Plugin ID using reverse domain notation\n */\n pluginId: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Required plugin identifier'),\n \n /**\n * Version constraint (supports semver ranges)\n * Examples: \"1.0.0\", \"^1.2.3\", \">=2.0.0 <3.0.0\"\n */\n version: z.string().describe('Semantic version constraint'),\n \n /**\n * Whether this dependency is optional\n */\n optional: z.boolean().default(false),\n \n /**\n * Reason for the dependency\n */\n reason: z.string().optional(),\n \n /**\n * Minimum required capabilities from the dependency\n */\n requiredCapabilities: z.array(z.string()).optional().describe('Protocol IDs the dependency must support'),\n});\n\n/**\n * Extension Point Declaration\n * Defines hooks where other plugins can extend this plugin's functionality.\n */\nexport const ExtensionPointSchema = z.object({\n /**\n * Extension point identifier\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+extension\\.[a-z][a-z0-9._]+$/)\n .describe('Unique extension point identifier'),\n \n /**\n * Extension point name\n */\n name: z.string(),\n \n /**\n * Description\n */\n description: z.string().optional(),\n \n /**\n * Type of extension point\n */\n type: z.enum([\n 'action', // Plugins can register executable actions\n 'hook', // Plugins can listen to lifecycle events\n 'widget', // Plugins can contribute UI widgets\n 'provider', // Plugins can provide data/services\n 'transformer', // Plugins can transform data\n 'validator', // Plugins can validate data\n 'decorator', // Plugins can enhance/wrap functionality\n ]),\n \n /**\n * Expected interface contract for extensions\n */\n contract: z.object({\n input: z.string().optional().describe('Input type/schema'),\n output: z.string().optional().describe('Output type/schema'),\n signature: z.string().optional().describe('Function signature if applicable'),\n }).optional(),\n \n /**\n * Cardinality\n */\n cardinality: z.enum(['single', 'multiple']).default('multiple')\n .describe('Whether multiple extensions can register to this point'),\n});\n\n/**\n * Complete Plugin Capability Manifest\n * This is included in the main plugin manifest to declare all capabilities.\n */\nexport const PluginCapabilityManifestSchema = z.object({\n /**\n * Protocols this plugin implements\n */\n implements: z.array(PluginCapabilitySchema).optional()\n .describe('List of protocols this plugin conforms to'),\n \n /**\n * Interfaces this plugin exposes to other plugins\n */\n provides: z.array(PluginInterfaceSchema).optional()\n .describe('Services/APIs this plugin offers to others'),\n \n /**\n * Dependencies on other plugins\n */\n requires: z.array(PluginDependencySchema).optional()\n .describe('Required plugins and their capabilities'),\n \n /**\n * Extension points this plugin defines\n */\n extensionPoints: z.array(ExtensionPointSchema).optional()\n .describe('Points where other plugins can extend this plugin'),\n \n /**\n * Extensions this plugin contributes to other plugins\n */\n extensions: z.array(z.object({\n targetPluginId: z.string().describe('Plugin ID being extended'),\n extensionPointId: z.string().describe('Extension point identifier'),\n implementation: z.string().describe('Path to implementation module'),\n priority: z.number().int().default(100).describe('Registration priority (lower = higher priority)'),\n })).optional().describe('Extensions contributed to other plugins'),\n});\n\n// Export types\nexport type CapabilityConformanceLevel = z.infer;\nexport type ProtocolVersion = z.infer;\nexport type ProtocolReference = z.infer;\nexport type ProtocolFeature = z.infer;\nexport type PluginCapability = z.infer;\nexport type PluginInterface = z.infer;\nexport type PluginDependency = z.infer;\nexport type ExtensionPoint = z.infer;\nexport type PluginCapabilityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Loading Protocol\n * \n * Defines the enhanced plugin loading mechanism for the microkernel architecture.\n * Inspired by industry best practices from:\n * - Kubernetes CRDs and Operators\n * - OSGi Dynamic Module System\n * - Eclipse Plugin Framework\n * - Webpack Module Federation\n * \n * This protocol enables:\n * - Lazy loading and code splitting\n * - Dynamic imports and parallel initialization\n * - Capability-based discovery\n * - Hot reload in development\n * - Advanced caching strategies\n */\n\n/**\n * Plugin Loading Strategy\n * Determines how and when a plugin is loaded into memory\n */\nexport const PluginLoadingStrategySchema = z.enum([\n 'eager', // Load immediately during bootstrap (critical plugins)\n 'lazy', // Load on first use (feature plugins)\n 'parallel', // Load in parallel with other plugins\n 'deferred', // Load after initial bootstrap complete\n 'on-demand', // Load only when explicitly requested\n]).describe('Plugin loading strategy');\n\n/**\n * Plugin Preloading Configuration\n * Configures preloading behavior for faster activation\n */\nexport const PluginPreloadConfigSchema = z.object({\n /**\n * Enable preloading for this plugin\n */\n enabled: z.boolean().default(false),\n \n /**\n * Preload priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Resources to preload\n */\n resources: z.array(z.enum([\n 'metadata', // Plugin manifest and metadata\n 'dependencies', // Plugin dependencies\n 'assets', // Static assets (icons, translations)\n 'code', // JavaScript code chunks\n 'services', // Service definitions\n ])).optional(),\n \n /**\n * Conditions for preloading\n */\n conditions: z.object({\n /**\n * Preload only on specific routes\n */\n routes: z.array(z.string()).optional(),\n \n /**\n * Preload only for specific user roles\n */\n roles: z.array(z.string()).optional(),\n \n /**\n * Preload based on device type\n */\n deviceType: z.array(z.enum(['desktop', 'mobile', 'tablet'])).optional(),\n \n /**\n * Network connection quality threshold\n */\n minNetworkSpeed: z.enum(['slow-2g', '2g', '3g', '4g']).optional(),\n }).optional(),\n}).describe('Plugin preloading configuration');\n\n/**\n * Plugin Code Splitting Configuration\n * Configures how plugin code is split for optimal loading\n */\nexport const PluginCodeSplittingSchema = z.object({\n /**\n * Enable code splitting for this plugin\n */\n enabled: z.boolean().default(true),\n \n /**\n * Split strategy\n */\n strategy: z.enum([\n 'route', // Split by UI routes\n 'feature', // Split by feature modules\n 'size', // Split by bundle size threshold\n 'custom', // Custom split points defined by plugin\n ]).default('feature'),\n \n /**\n * Chunk naming strategy\n */\n chunkNaming: z.enum(['hashed', 'named', 'sequential']).default('hashed'),\n \n /**\n * Maximum chunk size in KB\n */\n maxChunkSize: z.number().int().min(10).optional().describe('Max chunk size in KB'),\n \n /**\n * Shared dependencies optimization\n */\n sharedDependencies: z.object({\n enabled: z.boolean().default(true),\n /**\n * Minimum times a module must be shared before extraction\n */\n minChunks: z.number().int().min(1).default(2),\n }).optional(),\n}).describe('Plugin code splitting configuration');\n\n/**\n * Plugin Dynamic Import Configuration\n * Configures dynamic import behavior for runtime module loading\n */\nexport const PluginDynamicImportSchema = z.object({\n /**\n * Enable dynamic imports\n */\n enabled: z.boolean().default(true),\n \n /**\n * Import mode\n */\n mode: z.enum([\n 'async', // Asynchronous import (recommended)\n 'sync', // Synchronous import (blocking)\n 'eager', // Eager evaluation\n 'lazy', // Lazy evaluation\n ]).default('async'),\n \n /**\n * Prefetch strategy\n */\n prefetch: z.boolean().default(false).describe('Prefetch module in idle time'),\n \n /**\n * Preload strategy\n */\n preload: z.boolean().default(false).describe('Preload module in parallel with parent'),\n \n /**\n * Webpack magic comments support\n */\n webpackChunkName: z.string().optional().describe('Custom chunk name for webpack'),\n \n /**\n * Import timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000).describe('Dynamic import timeout (ms)'),\n \n /**\n * Retry configuration on import failure\n */\n retry: z.object({\n enabled: z.boolean().default(true),\n maxAttempts: z.number().int().min(1).max(10).default(3),\n backoffMs: z.number().int().min(0).default(1000).describe('Exponential backoff base delay'),\n }).optional(),\n}).describe('Plugin dynamic import configuration');\n\n/**\n * Plugin Initialization Configuration\n * Configures how plugin initialization is executed\n */\nexport const PluginInitializationSchema = z.object({\n /**\n * Initialization mode\n */\n mode: z.enum([\n 'sync', // Synchronous initialization\n 'async', // Asynchronous initialization\n 'parallel', // Parallel with other plugins\n 'sequential', // Must complete before next plugin\n ]).default('async'),\n \n /**\n * Initialization timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000),\n \n /**\n * Startup priority (lower = higher priority, earlier initialization)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Whether to continue bootstrap if this plugin fails\n */\n critical: z.boolean().default(false).describe('If true, kernel bootstrap fails if plugin fails'),\n \n /**\n * Retry configuration on initialization failure\n */\n retry: z.object({\n enabled: z.boolean().default(false),\n maxAttempts: z.number().int().min(1).max(5).default(3),\n backoffMs: z.number().int().min(0).default(1000),\n }).optional(),\n \n /**\n * Health check interval for monitoring\n */\n healthCheckInterval: z.number().int().min(0).optional().describe('Health check interval in ms (0 = disabled)'),\n}).describe('Plugin initialization configuration');\n\n/**\n * Plugin Dependency Resolution Configuration\n * Advanced dependency resolution using semantic versioning\n */\nexport const PluginDependencyResolutionSchema = z.object({\n /**\n * Dependency resolution strategy\n */\n strategy: z.enum([\n 'strict', // Exact version match required\n 'compatible', // Semver compatible versions (^)\n 'latest', // Always use latest compatible\n 'pinned', // Lock to specific version\n ]).default('compatible'),\n \n /**\n * Peer dependency handling\n */\n peerDependencies: z.object({\n /**\n * Whether to resolve peer dependencies\n */\n resolve: z.boolean().default(true),\n \n /**\n * Action on missing peer dependency\n */\n onMissing: z.enum(['error', 'warn', 'ignore']).default('warn'),\n \n /**\n * Action on peer version mismatch\n */\n onMismatch: z.enum(['error', 'warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Optional dependency handling\n */\n optionalDependencies: z.object({\n /**\n * Whether to attempt loading optional dependencies\n */\n load: z.boolean().default(true),\n \n /**\n * Action on optional dependency load failure\n */\n onFailure: z.enum(['warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Conflict resolution\n */\n conflictResolution: z.enum([\n 'fail', // Fail on any version conflict\n 'latest', // Use latest version\n 'oldest', // Use oldest version\n 'manual', // Require manual resolution\n ]).default('latest'),\n \n /**\n * Circular dependency handling\n */\n circularDependencies: z.enum([\n 'error', // Throw error on circular dependency\n 'warn', // Warn but continue\n 'allow', // Allow circular dependencies\n ]).default('warn'),\n}).describe('Plugin dependency resolution configuration');\n\n/**\n * Plugin Hot Reload Configuration\n * Enables hot module replacement for development and production environments.\n * \n * Production mode adds safety features: health validation, rollback on failure,\n * connection draining, and concurrency control for zero-downtime reloads.\n */\nexport const PluginHotReloadSchema = z.object({\n /**\n * Enable hot reload\n */\n enabled: z.boolean().default(false),\n \n /**\n * Target environment for hot reload behavior\n */\n environment: z.enum([\n 'development', // Fast reload with relaxed safety (file watchers, no health validation)\n 'staging', // Production-like reload with validation but relaxed rollback\n 'production', // Full safety: health validation, rollback, connection draining\n ]).default('development').describe('Target environment controlling safety level'),\n \n /**\n * Hot reload strategy\n */\n strategy: z.enum([\n 'full', // Full plugin reload (destroy and reinitialize)\n 'partial', // Partial reload (update changed modules only)\n 'state-preserve', // Preserve plugin state during reload\n ]).default('full'),\n \n /**\n * Files to watch for changes\n */\n watchPatterns: z.array(z.string()).optional().describe('Glob patterns for files to watch'),\n \n /**\n * Files to ignore\n */\n ignorePatterns: z.array(z.string()).optional().describe('Glob patterns for files to ignore'),\n \n /**\n * Debounce delay in milliseconds\n */\n debounceMs: z.number().int().min(0).default(300),\n \n /**\n * Whether to preserve state during reload\n */\n preserveState: z.boolean().default(false),\n \n /**\n * State serialization\n */\n stateSerialization: z.object({\n enabled: z.boolean().default(false),\n /**\n * Path to state serialization handler\n */\n handler: z.string().optional(),\n }).optional(),\n \n /**\n * Hooks for hot reload lifecycle\n */\n hooks: z.object({\n beforeReload: z.string().optional().describe('Function to call before reload'),\n afterReload: z.string().optional().describe('Function to call after reload'),\n onError: z.string().optional().describe('Function to call on reload error'),\n }).optional(),\n \n /**\n * Production safety configuration\n * Applied when environment is 'staging' or 'production'\n */\n productionSafety: z.object({\n /**\n * Validate plugin health before completing reload\n */\n healthValidation: z.boolean().default(true)\n .describe('Run health checks after reload before accepting traffic'),\n \n /**\n * Automatically rollback to previous version on reload failure\n */\n rollbackOnFailure: z.boolean().default(true)\n .describe('Auto-rollback if reloaded plugin fails health check'),\n \n /**\n * Maximum time to wait for health validation after reload (ms)\n */\n healthTimeout: z.number().int().min(1000).default(30000)\n .describe('Health check timeout after reload in ms'),\n \n /**\n * Drain active connections before reload\n */\n drainConnections: z.boolean().default(true)\n .describe('Gracefully drain active requests before reloading'),\n \n /**\n * Maximum time to wait for connection draining (ms)\n */\n drainTimeout: z.number().int().min(0).default(15000)\n .describe('Max wait time for connection draining in ms'),\n \n /**\n * Maximum number of concurrent plugin reloads\n */\n maxConcurrentReloads: z.number().int().min(1).default(1)\n .describe('Limit concurrent reloads to prevent system instability'),\n \n /**\n * Minimum interval between reloads of the same plugin (ms)\n */\n minReloadInterval: z.number().int().min(1000).default(5000)\n .describe('Cooldown period between reloads of the same plugin'),\n }).optional(),\n}).describe('Plugin hot reload configuration');\n\n/**\n * Plugin Caching Configuration\n * Configures caching strategy for faster subsequent loads\n */\nexport const PluginCachingSchema = z.object({\n /**\n * Enable caching\n */\n enabled: z.boolean().default(true),\n \n /**\n * Cache storage type\n */\n storage: z.enum([\n 'memory', // In-memory cache (fastest, not persistent)\n 'disk', // Disk cache (persistent)\n 'indexeddb', // Browser IndexedDB (persistent, browser only)\n 'hybrid', // Memory + Disk hybrid\n ]).default('memory'),\n \n /**\n * Cache key strategy\n */\n keyStrategy: z.enum([\n 'version', // Cache by plugin version\n 'hash', // Cache by content hash\n 'timestamp', // Cache by last modified timestamp\n ]).default('version'),\n \n /**\n * Cache TTL in seconds\n */\n ttl: z.number().int().min(0).optional().describe('Time to live in seconds (0 = infinite)'),\n \n /**\n * Maximum cache size in MB\n */\n maxSize: z.number().int().min(1).optional().describe('Max cache size in MB'),\n \n /**\n * Cache invalidation triggers\n */\n invalidateOn: z.array(z.enum([\n 'version-change',\n 'dependency-change',\n 'manual',\n 'error',\n ])).optional(),\n \n /**\n * Compression\n */\n compression: z.object({\n enabled: z.boolean().default(false),\n algorithm: z.enum(['gzip', 'brotli', 'deflate']).default('gzip'),\n }).optional(),\n}).describe('Plugin caching configuration');\n\n/**\n * Plugin Sandboxing Configuration\n * Security isolation for plugins with configurable scope.\n * \n * Supports isolation beyond automation scripts: any plugin can be sandboxed\n * with process-level isolation and inter-plugin communication (IPC).\n */\nexport const PluginSandboxingSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(false),\n \n /**\n * Isolation scope - which plugins are subject to sandboxing\n */\n scope: z.enum([\n 'automation-only', // Sandbox automation/scripting plugins only (current behavior)\n 'untrusted-only', // Sandbox plugins below a trust threshold\n 'all-plugins', // Sandbox all plugins (maximum isolation)\n ]).default('automation-only').describe('Which plugins are subject to isolation'),\n \n /**\n * Sandbox isolation level\n */\n isolationLevel: z.enum([\n 'none', // No isolation\n 'process', // Separate process (Node.js worker threads)\n 'vm', // VM context isolation\n 'iframe', // iframe isolation (browser)\n 'web-worker', // Web Worker (browser)\n ]).default('none'),\n \n /**\n * Allowed capabilities\n */\n allowedCapabilities: z.array(z.string()).optional().describe('List of allowed capability IDs'),\n \n /**\n * Resource quotas\n */\n resourceQuotas: z.object({\n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(1).optional(),\n \n /**\n * Maximum CPU time in milliseconds\n */\n maxCpuTimeMs: z.number().int().min(100).optional(),\n \n /**\n * Maximum number of file descriptors\n */\n maxFileDescriptors: z.number().int().min(1).optional(),\n \n /**\n * Maximum network bandwidth in KB/s\n */\n maxNetworkKBps: z.number().int().min(1).optional(),\n }).optional(),\n \n /**\n * Permissions\n */\n permissions: z.object({\n /**\n * Allowed API access\n */\n allowedAPIs: z.array(z.string()).optional(),\n \n /**\n * Allowed file system paths\n */\n allowedPaths: z.array(z.string()).optional(),\n \n /**\n * Allowed network endpoints\n */\n allowedEndpoints: z.array(z.string()).optional(),\n \n /**\n * Allowed environment variables\n */\n allowedEnvVars: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Inter-Plugin Communication (IPC) configuration\n * Enables isolated plugins to communicate with the kernel and other plugins\n */\n ipc: z.object({\n /**\n * Enable IPC for sandboxed plugins\n */\n enabled: z.boolean().default(true)\n .describe('Allow sandboxed plugins to communicate via IPC'),\n \n /**\n * IPC transport mechanism\n */\n transport: z.enum([\n 'message-port', // MessagePort (worker threads / Web Workers)\n 'unix-socket', // Unix domain sockets (process isolation)\n 'tcp', // TCP sockets (container isolation)\n 'memory', // Shared memory channel (in-process VM)\n ]).default('message-port')\n .describe('IPC transport for cross-boundary communication'),\n \n /**\n * Maximum message size in bytes\n */\n maxMessageSize: z.number().int().min(1024).default(1048576)\n .describe('Maximum IPC message size in bytes (default 1MB)'),\n \n /**\n * Message timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000)\n .describe('IPC message response timeout in ms'),\n \n /**\n * Allowed service calls through IPC\n */\n allowedServices: z.array(z.string()).optional()\n .describe('Service names the sandboxed plugin may invoke via IPC'),\n }).optional(),\n}).describe('Plugin sandboxing configuration');\n\n/**\n * Plugin Performance Monitoring Configuration\n * Telemetry and performance tracking\n */\nexport const PluginPerformanceMonitoringSchema = z.object({\n /**\n * Enable performance monitoring\n */\n enabled: z.boolean().default(false),\n \n /**\n * Metrics to collect\n */\n metrics: z.array(z.enum([\n 'load-time',\n 'init-time',\n 'memory-usage',\n 'cpu-usage',\n 'api-calls',\n 'error-rate',\n 'cache-hit-rate',\n ])).optional(),\n \n /**\n * Sampling rate (0-1, where 1 = 100%)\n */\n samplingRate: z.number().min(0).max(1).default(1),\n \n /**\n * Reporting interval in seconds\n */\n reportingInterval: z.number().int().min(1).default(60),\n \n /**\n * Performance budget thresholds\n */\n budgets: z.object({\n /**\n * Maximum load time in milliseconds\n */\n maxLoadTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum init time in milliseconds\n */\n maxInitTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(0).optional(),\n }).optional(),\n \n /**\n * Action on budget violation\n */\n onBudgetViolation: z.enum(['warn', 'error', 'ignore']).default('warn'),\n}).describe('Plugin performance monitoring configuration');\n\n/**\n * Complete Plugin Loading Configuration\n * Combines all loading-related configurations\n */\nexport const PluginLoadingConfigSchema = z.object({\n /**\n * Loading strategy\n */\n strategy: PluginLoadingStrategySchema.default('lazy'),\n \n /**\n * Preloading configuration\n */\n preload: PluginPreloadConfigSchema.optional(),\n \n /**\n * Code splitting configuration\n */\n codeSplitting: PluginCodeSplittingSchema.optional(),\n \n /**\n * Dynamic import configuration\n */\n dynamicImport: PluginDynamicImportSchema.optional(),\n \n /**\n * Initialization configuration\n */\n initialization: PluginInitializationSchema.optional(),\n \n /**\n * Dependency resolution configuration\n */\n dependencyResolution: PluginDependencyResolutionSchema.optional(),\n \n /**\n * Hot reload configuration (development and production)\n */\n hotReload: PluginHotReloadSchema.optional(),\n \n /**\n * Caching configuration\n */\n caching: PluginCachingSchema.optional(),\n \n /**\n * Sandboxing configuration\n */\n sandboxing: PluginSandboxingSchema.optional(),\n \n /**\n * Performance monitoring\n */\n monitoring: PluginPerformanceMonitoringSchema.optional(),\n}).describe('Complete plugin loading configuration');\n\n/**\n * Plugin Loading Event\n * Emitted during plugin loading lifecycle\n */\nexport const PluginLoadingEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'load-started',\n 'load-completed',\n 'load-failed',\n 'init-started',\n 'init-completed',\n 'init-failed',\n 'preload-started',\n 'preload-completed',\n 'cache-hit',\n 'cache-miss',\n 'hot-reload',\n 'dynamic-load', // Plugin loaded at runtime\n 'dynamic-unload', // Plugin unloaded at runtime\n 'dynamic-discover', // Plugin discovered via registry\n ]),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Timestamp\n */\n timestamp: z.number().int().min(0),\n \n /**\n * Duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Error if event represents a failure\n */\n error: z.object({\n message: z.string(),\n code: z.string().optional(),\n stack: z.string().optional(),\n }).optional(),\n}).describe('Plugin loading lifecycle event');\n\n/**\n * Plugin Loading State\n * Tracks the current loading state of a plugin\n */\nexport const PluginLoadingStateSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current state\n */\n state: z.enum([\n 'pending', // Not yet loaded\n 'loading', // Currently loading\n 'loaded', // Code loaded, not initialized\n 'initializing', // Currently initializing\n 'ready', // Fully initialized and ready\n 'failed', // Failed to load or initialize\n 'reloading', // Hot reloading in progress\n 'unloading', // Being unloaded at runtime\n 'unloaded', // Successfully unloaded (dynamic loading)\n ]),\n \n /**\n * Load progress (0-100)\n */\n progress: z.number().min(0).max(100).default(0),\n \n /**\n * Loading start time\n */\n startedAt: z.number().int().min(0).optional(),\n \n /**\n * Loading completion time\n */\n completedAt: z.number().int().min(0).optional(),\n \n /**\n * Last error\n */\n lastError: z.string().optional(),\n \n /**\n * Retry count\n */\n retryCount: z.number().int().min(0).default(0),\n}).describe('Plugin loading state');\n\n// Export types\nexport type PluginLoadingStrategy = z.infer;\nexport type PluginPreloadConfig = z.infer;\nexport type PluginCodeSplitting = z.infer;\nexport type PluginDynamicImport = z.infer;\nexport type PluginInitialization = z.infer;\nexport type PluginDependencyResolution = z.infer;\nexport type PluginHotReload = z.infer;\nexport type PluginCaching = z.infer;\nexport type PluginSandboxing = z.infer;\nexport type PluginPerformanceMonitoring = z.infer;\nexport type PluginLoadingConfig = z.infer;\nexport type PluginLoadingEvent = z.infer;\nexport type PluginLoadingState = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// Service method interfaces use z.function() instead of z.any() for type safety.\n// Generic data fields use z.unknown() for type safety.\nexport const PluginContextSchema = z.object({\n ql: z.object({\n object: z.function().describe('Get object handle for method chaining'),\n query: z.function().describe('Execute a query'),\n }).passthrough().describe('ObjectQL Engine Interface'),\n\n os: z.object({\n getCurrentUser: z.function().describe('Get the current authenticated user'),\n getConfig: z.function().describe('Get platform configuration'),\n }).passthrough().describe('ObjectStack Kernel Interface'),\n\n logger: z.object({\n debug: z.function().describe('Log debug message'),\n info: z.function().describe('Log info message'),\n warn: z.function().describe('Log warning message'),\n error: z.function().describe('Log error message'),\n }).passthrough().describe('Logger Interface'),\n\n storage: z.object({\n get: z.function().describe('Get a value from storage'),\n set: z.function().describe('Set a value in storage'),\n delete: z.function().describe('Delete a value from storage'),\n }).passthrough().describe('Storage Interface'),\n\n i18n: z.object({\n t: z.function().describe('Translate a key'),\n getLocale: z.function().describe('Get current locale'),\n }).passthrough().describe('Internationalization Interface'),\n\n metadata: z.record(z.string(), z.unknown()),\n events: z.record(z.string(), z.unknown()),\n \n app: z.object({\n router: z.object({\n get: z.function().describe('Register GET route handler'),\n post: z.function().describe('Register POST route handler'),\n use: z.function().describe('Register middleware'),\n }).passthrough()\n }).passthrough().describe('App Framework Interface'),\n\n drivers: z.object({\n register: z.function().describe('Register a driver'),\n }).passthrough().describe('Driver Registry'),\n});\n\nexport type PluginContextData = z.infer;\nexport type PluginContext = PluginContextData;\n\n/**\n * Upgrade Context Schema\n *\n * Provides version migration context to the `onUpgrade` lifecycle hook.\n * Enables developers to write conditional migration logic based on\n * the previous and new versions.\n */\nexport const UpgradeContextSchema = z.object({\n /** Version before upgrade */\n previousVersion: z.string().describe('Version before upgrade'),\n\n /** Version after upgrade */\n newVersion: z.string().describe('Version after upgrade'),\n\n /** Whether this is a major version bump */\n isMajorUpgrade: z.boolean().describe('Whether this is a major version bump'),\n\n /** Metadata snapshot before upgrade (for migration logic) */\n previousMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Metadata snapshot before upgrade'),\n}).describe('Version migration context for onUpgrade hook');\n\nexport type UpgradeContext = z.infer;\n\nexport const PluginLifecycleSchema = z.object({\n onInstall: z.function().optional().describe('Called when plugin is installed'),\n \n onEnable: z.function().optional().describe('Called when plugin is enabled'),\n \n onDisable: z.function().optional().describe('Called when plugin is disabled'),\n \n onUninstall: z.function().optional().describe('Called when plugin is uninstalled'),\n \n onUpgrade: z.function().optional().describe('Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade'),\n});\n\nexport type PluginLifecycleHooks = z.infer;\n\n/**\n * Shared Plugin Types\n * These are the specialized plugin types common between Manifest (Package) and Plugin (Runtime).\n */\nexport const CORE_PLUGIN_TYPES = [\n 'ui', // Frontend: Serves static assets/SPA (e.g. Console, Studio)\n 'driver', // Connectivity: Database or Storage adapters (e.g. SQL, S3)\n 'server', // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL)\n 'app', // Business: Vertical Solution Bundle (Metadata + Logic)\n 'theme', // Appearance: UI Overrides & CSS Variables\n 'agent', // AI: Autonomous Agent & Tool Definitions\n 'objectql' // Core: ObjectQL Engine Data Provider\n] as const;\n\nexport const PluginSchema = PluginLifecycleSchema.extend({\n id: z.string().min(1).optional().describe('Unique Plugin ID (e.g. com.example.crm)'),\n type: z.enum([\n 'standard', // Default: General purpose backend logic (Service, Hook, etc.)\n ...CORE_PLUGIN_TYPES\n ]).default('standard').optional().describe('Plugin Type categorization for runtime behavior'),\n \n staticPath: z.string().optional().describe('Absolute path to static assets (Required for type=\"ui-plugin\")'),\n slug: z.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type=\"ui-plugin\")'),\n default: z.boolean().optional().describe('Serve at root path (Only one \"ui-plugin\" can be default)'),\n \n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic Version'),\n description: z.string().optional(),\n author: z.string().optional(),\n homepage: z.string().url().optional(),\n});\n\nexport type PluginDefinition = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data Import Strategy\n * Defines how the engine handles existing records.\n */\nexport const DatasetMode = z.enum([\n 'insert', // Try to insert, fail on duplicate\n 'update', // Only update found records, ignore new\n 'upsert', // Create new or Update existing (Standard)\n 'replace', // Delete ALL records in object then insert (Dangerous - use for cache tables)\n 'ignore' // Try to insert, silently skip duplicates\n]);\n\n/**\n * Dataset Schema (Seed Data / Fixtures)\n * \n * Standardized format for transporting data.\n * Used for:\n * 1. System Bootstrapping (Admin accounts, Standard Roles)\n * 2. Reference Data (Countries, Currencies)\n * 3. Demo/Test Data\n */\nexport const DatasetSchema = z.object({\n /** \n * Target Object \n * The machine name of the object to populate.\n */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target Object Name'),\n\n /** \n * Idempotency Key (The \"Upsert\" Key)\n * The field used to check if a record already exists.\n * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'.\n * Standard: 'id' is rarely used for portable seed data — prefer natural keys.\n */\n externalId: z.string().default('name').describe('Field match for uniqueness check'),\n\n /** \n * Import Strategy\n */\n mode: DatasetMode.default('upsert').describe('Conflict resolution strategy'),\n\n /**\n * Environment Scope\n * - 'all': Always load\n * - 'dev': Only for development/demo\n * - 'test': Only for CI/CD tests\n */\n env: z.array(z.enum(['prod', 'dev', 'test'])).default(['prod', 'dev', 'test']).describe('Applicable environments'),\n\n /** \n * The Payload\n * Array of raw JSON objects matching the Object Schema.\n */\n records: z.array(z.record(z.string(), z.unknown())).describe('Data records'),\n});\n\n/** Parsed/output type — all defaults are applied (env, mode, externalId always present) */\nexport type Dataset = z.infer;\n\n/** Input type — fields with defaults (env, mode, externalId) are optional */\nexport type DatasetInput = z.input;\n\nexport type DatasetImportMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\nimport { PluginLoadingConfigSchema } from './plugin-loading.zod';\nimport { CORE_PLUGIN_TYPES } from './plugin.zod';\nimport { DatasetSchema } from '../data/dataset.zod';\n\n/**\n * Schema for the ObjectStack Manifest.\n * This defines the structure of a package configuration in the ObjectStack ecosystem.\n * All packages (apps, plugins, drivers, modules) must conform to this schema.\n * \n * @example App Package\n * ```yaml\n * id: com.acme.crm\n * version: 1.0.0\n * type: app\n * name: Acme CRM\n * description: Customer Relationship Management system\n * permissions:\n * - system.user.read\n * - system.object.create\n * objects:\n * - \"./src/objects/*.object.yml\"\n * ```\n */\nexport const ManifestSchema = z.object({\n /** \n * Unique package identifier using reverse domain notation.\n * Must be unique across the entire ecosystem.\n * \n * @example \"com.steedos.crm\"\n * @example \"org.apache.superset\"\n */\n id: z.string().describe('Unique package identifier (reverse domain style)'),\n \n /**\n * Short namespace identifier for metadata scoping.\n * Used as a prefix for objects and other metadata to prevent naming collisions\n * across packages from different vendors.\n * \n * Rules:\n * - 2-20 characters, lowercase letters, digits, and underscores only.\n * - Must be unique within a running instance.\n * - Platform-reserved namespaces (no prefix applied): \"base\", \"system\".\n * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator).\n * \n * @example \"crm\" → objects become crm__account, crm__deal\n * @example \"todo\" → objects become todo__task\n * @example \"base\" → objects keep short name (platform reserved)\n */\n namespace: z.string()\n .regex(/^[a-z][a-z0-9_]{1,19}$/, 'Namespace must be 2-20 chars, lowercase alphanumeric + underscore')\n .optional()\n .describe('Short namespace identifier for metadata scoping (e.g. \"crm\", \"todo\")'),\n \n /** \n * Package version following semantic versioning (major.minor.patch).\n * \n * @example \"1.0.0\"\n * @example \"2.1.0-beta.1\"\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Package version (semantic versioning)'),\n \n /** \n * Type of the package in the ObjectStack ecosystem.\n * - plugin: General-purpose functionality extension (Runtime: standard)\n * - app: Business application package\n * - driver: Connectivity adapter\n * - server: Protocol gateway (Hono, GraphQL)\n * - ui: Frontend package (Static/SPA)\n * - theme: UI Theme\n * - agent: AI Agent\n * - module: Reusable code library/shared module\n * - objectql: Core engine\n * - adapter: Host adapter (Express, Fastify)\n */\n type: z.enum([\n 'plugin', \n ...CORE_PLUGIN_TYPES,\n 'module', \n 'gateway', // Deprecated: use 'server'\n 'adapter'\n ]).describe('Type of package'),\n \n /** \n * Human-readable name of the package.\n * Displayed in the UI for users.\n * \n * @example \"Project Management\"\n */\n name: z.string().describe('Human-readable package name'),\n \n /** \n * Brief description of the package functionality.\n * Displayed in the marketplace and plugin manager.\n */\n description: z.string().optional().describe('Package description'),\n \n /** \n * Array of permission strings that the package requires.\n * These form the \"Scope\" requested by the package at installation.\n * \n * @example [\"system.user.read\", \"system.data.write\"]\n */\n permissions: z.array(z.string()).optional().describe('Array of required permission strings'),\n \n /** \n * Glob patterns specifying ObjectQL schemas files.\n * Matches `*.object.yml` or `*.object.ts` files to load business objects.\n * \n * @example [\"./src/objects/*.object.yml\"]\n */\n objects: z.array(z.string()).optional().describe('Glob patterns for ObjectQL schemas files'),\n\n /**\n * Defines system level DataSources.\n * Matches `*.datasource.yml` files.\n * \n * @example [\"./src/datasources/*.datasource.mongo.yml\"]\n */\n datasources: z.array(z.string()).optional().describe('Glob patterns for Datasource definitions'),\n\n /**\n * Package Dependencies.\n * Map of package IDs to version requirements.\n * \n * @example { \"@steedos/plugin-auth\": \"^2.0.0\" }\n */\n dependencies: z.record(z.string(), z.string()).optional().describe('Package dependencies'),\n\n /**\n * Plugin Configuration Schema.\n * Defines the settings this plugin exposes to the user via UI/ENV.\n * Uses a simplified JSON Schema format.\n * \n * @example\n * {\n * \"title\": \"Stripe Config\",\n * \"properties\": {\n * \"apiKey\": { \"type\": \"string\", \"secret\": true },\n * \"currency\": { \"type\": \"string\", \"default\": \"USD\" }\n * }\n * }\n */\n configuration: z.object({\n title: z.string().optional(),\n properties: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']).describe('Data type of the setting'),\n default: z.unknown().optional().describe('Default value'),\n description: z.string().optional().describe('Tooltip description'),\n required: z.boolean().optional().describe('Is this setting required?'),\n secret: z.boolean().optional().describe('If true, value is encrypted/masked (e.g. API Keys)'),\n enum: z.array(z.string()).optional().describe('Allowed values for select inputs'),\n })).describe('Map of configuration keys to their definitions')\n }).optional().describe('Plugin configuration settings'),\n\n /**\n * Contribution Points (VS Code Style).\n * formalized way to extend the platform capabilities.\n */\n contributes: z.object({\n /**\n * Register new Metadata Kinds (CRDs).\n * Enables the system to parse and validate new file types.\n * Example: Registering a BI plugin to handle *.report.ts\n */\n kinds: z.array(z.object({\n id: z.string().describe('The generic identifier of the kind (e.g., \"sys.bi.report\")'),\n globs: z.array(z.string()).describe('File patterns to watch (e.g., [\"**/*.report.ts\"])'),\n description: z.string().optional().describe('Description of what this kind represents'),\n })).optional().describe('New Metadata Types to recognize'),\n\n /**\n * Register System Hooks.\n * Declares that this plugin listens to specific system events.\n */\n events: z.array(z.string()).optional().describe('Events this plugin listens to'),\n\n /**\n * Register UI Menus.\n */\n menus: z.record(z.string(), z.array(z.object({\n id: z.string(),\n label: z.string(),\n command: z.string().optional(),\n }))).optional().describe('UI Menu contributions'),\n\n /**\n * Register Custom Themes.\n */\n themes: z.array(z.object({\n id: z.string(),\n label: z.string(),\n path: z.string(),\n })).optional().describe('Theme contributions'),\n\n /**\n * Register Translations.\n * Path to translation files (e.g. \"locales/en.json\").\n */\n translations: z.array(z.object({\n locale: z.string(),\n path: z.string(),\n })).optional().describe('Translation resources'),\n\n /**\n * Register Server Actions.\n * Invocable functions exposed to Flows or API.\n */\n actions: z.array(z.object({\n name: z.string().describe('Unique action name'),\n label: z.string().optional(),\n description: z.string().optional(),\n input: z.unknown().optional().describe('Input validation schema'),\n output: z.unknown().optional().describe('Output schema'),\n })).optional().describe('Exposed server actions'),\n\n /**\n * Register Storage Drivers.\n * Enables connecting to new types of datasources.\n */\n drivers: z.array(z.object({\n id: z.string().describe('Driver unique identifier (e.g. \"postgres\", \"mongo\")'),\n label: z.string().describe('Human readable name'),\n description: z.string().optional(),\n })).optional().describe('Driver contributions'),\n\n /**\n * Register Custom Field Types.\n * Extends the data model with new widget types.\n */\n fieldTypes: z.array(z.object({\n name: z.string().describe('Unique field type name (e.g. \"vector\")'),\n label: z.string().describe('Display label'),\n description: z.string().optional(),\n })).optional().describe('Field Type contributions'),\n \n /**\n * Register Custom Query Operators/Functions.\n * Extends ObjectQL with new functions (e.g. distance()).\n */\n functions: z.array(z.object({\n name: z.string().describe('Function name (e.g. \"distance\")'),\n description: z.string().optional(),\n args: z.array(z.string()).optional().describe('Argument types'),\n returnType: z.string().optional(),\n })).optional().describe('Query Function contributions'),\n\n /**\n * Register API Route Namespaces.\n * Declares the API endpoints this plugin provides to the HttpDispatcher.\n * The kernel routes matching prefixes to this plugin's handler.\n * \n * @example\n * routes: [\n * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] }\n * ]\n */\n routes: z.array(z.object({\n /** URL path prefix (e.g. \"/api/v1/ai\") */\n prefix: z.string().regex(/^\\//).describe('API path prefix'),\n /** Service name this plugin provides */\n service: z.string().describe('Service name this plugin provides'),\n /** Protocol method names implemented */\n methods: z.array(z.string()).optional()\n .describe('Protocol method names implemented (e.g. [\"aiNlq\", \"aiChat\"])'),\n })).optional().describe('API route contributions to HttpDispatcher'),\n\n /**\n * Register CLI Commands.\n * Allows plugins to extend the ObjectStack CLI with custom commands.\n * Each command entry declares metadata; the actual Commander.js command\n * is resolved at runtime by importing the plugin's module.\n * \n * The plugin package must export a `commands` array of Commander.js `Command` instances\n * from its main entry point or from the path specified in `module`.\n * \n * @example\n * ```yaml\n * commands:\n * - name: marketplace\n * description: \"Manage marketplace apps\"\n * module: \"./cli\" # optional, defaults to package main\n * - name: deploy\n * description: \"Deploy to cloud\"\n * ```\n */\n commands: z.array(z.object({\n /** CLI command name (e.g., \"marketplace\", \"deploy\"). Must be a valid CLI identifier. */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n /** Brief description shown in `os --help` */\n description: z.string().optional().describe('Command description for help text'),\n /** \n * Optional module path (relative to package root) that exports the Commander.js commands.\n * If omitted, the CLI will import from the package's main entry point.\n * The module must export a `commands` array of Commander.js `Command` instances,\n * or a single `Command` instance as default export.\n */\n module: z.string().optional().describe('Module path exporting Commander.js commands'),\n })).optional().describe('CLI command contributions'),\n }).optional().describe('Platform contributions'),\n\n /** \n * Initial data seeding configuration.\n * Defines default records to be inserted when the package is installed.\n * \n * Uses the standard DatasetSchema which supports idempotent upsert via\n * `externalId`, environment scoping via `env`, and multiple conflict\n * resolution modes.\n * \n * @deprecated Prefer using the top-level `data` field on the Stack Definition\n * (defineStack({ data: [...] })) for better visibility and metadata registration.\n * This field is retained for backward compatibility with manifest-only packages.\n */\n data: z.array(DatasetSchema).optional().describe('Initial seed data (prefer top-level data field)'),\n\n /**\n * Plugin Capability Manifest.\n * Declares protocols implemented, interfaces provided, dependencies, and extension points.\n * This enables plugin interoperability and automatic discovery.\n */\n capabilities: PluginCapabilityManifestSchema.optional()\n .describe('Plugin capability declarations for interoperability'),\n\n /** \n * Extension points contributed by this package.\n * Allows packages to extend UI components, add functionality, etc.\n */\n extensions: z.record(z.string(), z.unknown()).optional().describe('Extension points and contributions'),\n\n /**\n * Plugin Loading Configuration.\n * Configures how the plugin is loaded, initialized, and managed at runtime.\n * Includes strategies for lazy loading, code splitting, caching, and hot reload.\n */\n loading: PluginLoadingConfigSchema.optional()\n .describe('Plugin loading and runtime behavior configuration'),\n\n /**\n * Platform Compatibility Requirements.\n * Specifies the minimum ObjectStack platform version required to run this package.\n * Used at install time to prevent incompatible packages from being installed.\n *\n * @example\n * ```yaml\n * engine:\n * objectstack: \">=3.0.0\"\n * ```\n */\n engine: z.object({\n /** ObjectStack platform version requirement (SemVer range) */\n objectstack: z.string()\n .regex(/^[><=~^]*\\d+\\.\\d+\\.\\d+/)\n .describe('ObjectStack platform version requirement (SemVer range, e.g. \">=3.0.0\")'),\n }).optional().describe('Platform compatibility requirements'),\n});\n\n/**\n * TypeScript type inferred from the ManifestSchema.\n * Use this type for type-safe manifest handling in TypeScript code.\n */\nexport type ObjectStackManifest = z.infer;\nexport type ObjectStackManifestInput = z.input;\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Customization Layer Protocol\n * \n * Defines the overlay system for managing user customizations on top of\n * package-delivered metadata. This protocol solves the critical challenge\n * of separating \"vendor-managed\" metadata from \"customer-customized\" metadata,\n * enabling safe package upgrades without losing user changes.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed vs Unmanaged metadata components\n * - **ServiceNow**: Update Sets with collision detection\n * - **WordPress**: Parent/child theme overlay model\n * - **Kubernetes**: Strategic merge patch for resource customization\n * \n * ## Three-Layer Model\n * ```\n * ┌─────────────────────────────────┐\n * │ User Layer (scope: user) │ ← Personal overrides (per-user)\n * ├─────────────────────────────────┤\n * │ Platform Layer (scope: platform)│ ← Admin customizations (per-tenant)\n * ├─────────────────────────────────┤\n * │ System Layer (scope: system) │ ← Package-delivered metadata (read-only)\n * └─────────────────────────────────┘\n * ```\n * \n * ## Merge Resolution Order\n * Effective metadata = System ← merge(Platform) ← merge(User)\n * Each layer only stores the delta (changed fields), not the full definition.\n */\n\n// ==========================================\n// Customization Tracking\n// ==========================================\n\n/**\n * Customization Origin\n * Identifies who created the customization.\n */\nexport const CustomizationOriginSchema = z.enum([\n 'package', // Delivered by a plugin package (system layer, read-only)\n 'admin', // Created/modified by platform admin via UI\n 'user', // Created/modified by end user via UI\n 'migration', // Created during data migration\n 'api', // Created via API\n]);\n\n/**\n * Field-Level Change Tracking\n * Records exactly which fields were modified by the customer.\n */\nexport const FieldChangeSchema = z.object({\n /** JSON path to the changed field (e.g. \"fields.status.label\") */\n path: z.string().describe('JSON path to the changed field'),\n\n /** Original value from the package (for diff/rollback) */\n originalValue: z.unknown().optional().describe('Original value from the package'),\n\n /** Current customized value */\n currentValue: z.unknown().describe('Current customized value'),\n\n /** Who made this change */\n changedBy: z.string().optional().describe('User or admin who made this change'),\n\n /** When this change was made */\n changedAt: z.string().datetime().optional().describe('Timestamp of the change'),\n});\n\n/**\n * Metadata Overlay Schema\n * \n * Represents a customization layer on top of package-delivered metadata.\n * Each overlay stores only the delta (changed fields) relative to the base definition.\n * \n * During package upgrades, the system performs a 3-way merge:\n * 1. Old package version (base)\n * 2. New package version (theirs)\n * 3. Customer customizations (ours)\n * \n * @example\n * ```yaml\n * # Package delivers: object \"crm__account\" with field \"status\" label \"Status\"\n * # Admin changes label to \"Account Status\"\n * # Overlay record:\n * baseType: object\n * baseName: crm__account\n * packageId: com.acme.crm\n * packageVersion: \"1.0.0\"\n * changes:\n * - path: \"fields.status.label\"\n * originalValue: \"Status\"\n * currentValue: \"Account Status\"\n * ```\n */\nexport const MetadataOverlaySchema = z.object({\n /** Primary key */\n id: z.string().describe('Overlay record ID (UUID)'),\n\n /** The metadata type being customized (e.g. \"object\", \"view\", \"flow\") */\n baseType: z.string().describe('Metadata type being customized'),\n\n /** The metadata name being customized (e.g. \"crm__account\") */\n baseName: z.string().describe('Metadata name being customized'),\n\n /** Package that owns the base metadata (null for platform-created metadata) */\n packageId: z.string().optional().describe('Package ID that delivered the base metadata'),\n\n /** Package version when the customization was made (for upgrade diffing) */\n packageVersion: z.string().optional().describe('Package version when overlay was created'),\n\n /** Customization scope */\n scope: z.enum(['platform', 'user']).default('platform')\n .describe('Customization scope (platform=admin, user=personal)'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Owner user ID (for user-scope overlays) */\n owner: z.string().optional().describe('Owner user ID for user-scope overlays'),\n\n /**\n * The overlay payload.\n * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396).\n * - To modify a field: include the field with its new value\n * - To delete a field: set its value to null\n * - Omitted fields remain unchanged from base\n */\n patch: z.record(z.string(), z.unknown()).describe('JSON Merge Patch payload (changed fields only)'),\n\n /**\n * Detailed change tracking for each modified field.\n * Enables field-level conflict detection during upgrades.\n */\n changes: z.array(FieldChangeSchema).optional()\n .describe('Field-level change tracking for conflict detection'),\n\n /** Whether this overlay is currently active */\n active: z.boolean().default(true).describe('Whether this overlay is active'),\n\n /** Audit timestamps */\n createdAt: z.string().datetime().optional(),\n createdBy: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n updatedBy: z.string().optional(),\n});\n\n// ==========================================\n// Merge & Conflict Resolution\n// ==========================================\n\n/**\n * Merge Conflict\n * Represents a conflict between package update and customer customization.\n */\nexport const MergeConflictSchema = z.object({\n /** JSON path to the conflicting field */\n path: z.string().describe('JSON path to the conflicting field'),\n\n /** Value in the old package version */\n baseValue: z.unknown().describe('Value in the old package version'),\n\n /** Value in the new package version */\n incomingValue: z.unknown().describe('Value in the new package version'),\n\n /** Customer's customized value */\n customValue: z.unknown().describe('Customer customized value'),\n\n /** Suggested resolution strategy */\n suggestedResolution: z.enum([\n 'keep-custom', // Keep customer's customization\n 'accept-incoming', // Accept package update\n 'manual', // Requires manual resolution\n ]).describe('Suggested resolution strategy'),\n\n /** Reason for the suggested resolution */\n reason: z.string().optional().describe('Explanation for the suggested resolution'),\n});\n\n/**\n * Merge Strategy Configuration\n * Controls how metadata merging behaves during package upgrades.\n */\nexport const MergeStrategyConfigSchema = z.object({\n /** Default strategy when no field-level rule matches */\n defaultStrategy: z.enum([\n 'keep-custom', // Preserve all customer customizations (safe)\n 'accept-incoming', // Accept all package updates (overwrite)\n 'three-way-merge', // Intelligent 3-way merge with conflict detection\n ]).default('three-way-merge').describe('Default merge strategy'),\n\n /** \n * Field paths that should always accept incoming package updates.\n * Use for fields that the package vendor considers \"owned\" and should not be customized.\n * @example [\"fields.*.type\", \"triggers.*\"]\n */\n alwaysAcceptIncoming: z.array(z.string()).optional()\n .describe('Field paths that always accept package updates'),\n\n /**\n * Field paths where customer customizations always win.\n * Use for UI-facing fields like labels, descriptions, help text.\n * @example [\"fields.*.label\", \"fields.*.helpText\", \"description\"]\n */\n alwaysKeepCustom: z.array(z.string()).optional()\n .describe('Field paths where customer customizations always win'),\n\n /** Whether to automatically resolve non-conflicting changes */\n autoResolveNonConflicting: z.boolean().default(true)\n .describe('Auto-resolve changes that do not conflict'),\n});\n\n/**\n * Merge Result\n * Result of a 3-way merge operation during package upgrade.\n */\nexport const MergeResultSchema = z.object({\n /** Whether the merge completed successfully (no unresolved conflicts) */\n success: z.boolean().describe('Whether merge completed without unresolved conflicts'),\n\n /** The merged metadata payload */\n mergedMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Merged metadata result'),\n\n /** Updated overlay with remaining customizations */\n updatedOverlay: z.record(z.string(), z.unknown()).optional()\n .describe('Updated overlay after merge'),\n\n /** List of conflicts that require manual resolution */\n conflicts: z.array(MergeConflictSchema).optional()\n .describe('Unresolved merge conflicts'),\n\n /** Summary of automatically resolved changes */\n autoResolved: z.array(z.object({\n path: z.string(),\n resolution: z.string(),\n description: z.string().optional(),\n })).optional().describe('Summary of auto-resolved changes'),\n\n /** Statistics */\n stats: z.object({\n totalFields: z.number().int().min(0).describe('Total fields evaluated'),\n unchanged: z.number().int().min(0).describe('Fields with no changes'),\n autoResolved: z.number().int().min(0).describe('Fields auto-resolved'),\n conflicts: z.number().int().min(0).describe('Fields with conflicts'),\n }).optional(),\n});\n\n// ==========================================\n// Customization Management\n// ==========================================\n\n/**\n * Customizable Metadata Policy\n * Defines what parts of a metadata item can be customized by admins/users.\n * Package vendors use this to control customization boundaries.\n */\nexport const CustomizationPolicySchema = z.object({\n /** Metadata type this policy applies to */\n metadataType: z.string().describe('Metadata type (e.g. \"object\", \"view\")'),\n\n /** Whether customization is allowed at all for this type */\n allowCustomization: z.boolean().default(true),\n\n /**\n * Field paths that are locked (cannot be customized).\n * @example [\"name\", \"type\", \"fields.*.type\"]\n */\n lockedFields: z.array(z.string()).optional()\n .describe('Field paths that cannot be customized'),\n\n /**\n * Field paths that are customizable.\n * If specified, only these fields can be customized (whitelist mode).\n * @example [\"label\", \"description\", \"fields.*.label\", \"fields.*.helpText\"]\n */\n customizableFields: z.array(z.string()).optional()\n .describe('Field paths that can be customized (whitelist)'),\n\n /**\n * Whether users can add new fields to package objects.\n * When true, admins can extend package objects with custom fields.\n */\n allowAddFields: z.boolean().default(true)\n .describe('Whether admins can add new fields to package objects'),\n\n /**\n * Whether users can delete package-delivered fields.\n * Typically false — fields can only be hidden, not deleted.\n */\n allowDeleteFields: z.boolean().default(false)\n .describe('Whether admins can delete package-delivered fields'),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type CustomizationOrigin = z.infer;\nexport type FieldChange = z.infer;\nexport type MetadataOverlay = z.infer;\nexport type MergeConflict = z.infer;\nexport type MergeStrategyConfig = z.infer;\nexport type MergeResult = z.infer;\nexport type CustomizationPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Loader Protocol\n * \n * Defines the standard interface for loading and saving metadata in ObjectStack.\n * This protocol enables consistent metadata operations across different storage backends\n * (filesystem, HTTP, S3, databases) and serialization formats (JSON, YAML, TypeScript).\n */\n\n/**\n * Metadata Format Enum\n * Supported serialization formats for metadata\n */\nexport const MetadataFormatSchema = z.enum(['json', 'yaml', 'typescript', 'javascript']);\n\n/**\n * Metadata Statistics\n * Information about a metadata item without loading its full content\n */\nexport const MetadataStatsSchema = z.object({\n /**\n * Size of the metadata file in bytes\n */\n size: z.number().int().min(0).describe('File size in bytes'),\n \n /**\n * Last modification timestamp\n */\n modifiedAt: z.string().datetime().describe('Last modified date'),\n \n /**\n * ETag for cache validation\n * Used for conditional requests (If-None-Match header)\n */\n etag: z.string().describe('Entity tag for cache validation'),\n \n /**\n * Serialization format\n */\n format: MetadataFormatSchema.describe('Serialization format'),\n \n /**\n * Full file path (if applicable)\n */\n path: z.string().optional().describe('File system path'),\n \n /**\n * Additional metadata provider-specific properties\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Provider-specific metadata'),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n /**\n * Glob patterns to match files\n * Example: [\"**\\/*.object.ts\", \"**\\/*.object.json\"]\n */\n patterns: z.array(z.string()).optional().describe('File glob patterns'),\n \n /**\n * If-None-Match header for conditional loading\n * Only load if ETag doesn't match\n */\n ifNoneMatch: z.string().optional().describe('ETag for conditional request'),\n \n /**\n * If-Modified-Since header for conditional loading\n */\n ifModifiedSince: z.string().datetime().optional().describe('Only load if modified after this date'),\n \n /**\n * Whether to validate against Zod schema\n */\n validate: z.boolean().default(true).describe('Validate against schema'),\n \n /**\n * Whether to use cache if available\n */\n useCache: z.boolean().default(true).describe('Enable caching'),\n \n /**\n * Filter function (serialized as string)\n * Example: \"(item) => item.name.startsWith('sys_')\"\n */\n filter: z.string().optional().describe('Filter predicate as string'),\n \n /**\n * Maximum number of items to load\n */\n limit: z.number().int().min(1).optional().describe('Maximum items to load'),\n \n /**\n * Recursively search subdirectories\n */\n recursive: z.boolean().default(true).describe('Search subdirectories'),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n /**\n * Serialization format\n */\n format: MetadataFormatSchema.default('typescript').describe('Output format'),\n \n /**\n * Prettify output (formatted with indentation)\n */\n prettify: z.boolean().default(true).describe('Format with indentation'),\n \n /**\n * Indentation size (spaces)\n */\n indent: z.number().int().min(0).max(8).default(2).describe('Indentation spaces'),\n \n /**\n * Sort object keys alphabetically\n */\n sortKeys: z.boolean().default(false).describe('Sort object keys'),\n \n /**\n * Include default values in output\n */\n includeDefaults: z.boolean().default(false).describe('Include default values'),\n \n /**\n * Create backup before overwriting\n */\n backup: z.boolean().default(false).describe('Create backup file'),\n \n /**\n * Overwrite if exists\n */\n overwrite: z.boolean().default(true).describe('Overwrite existing file'),\n \n /**\n * Atomic write (write to temp file, then rename)\n */\n atomic: z.boolean().default(true).describe('Use atomic write operation'),\n \n /**\n * Custom file path (overrides default location)\n */\n path: z.string().optional().describe('Custom output path'),\n});\n\n/**\n * Metadata Export Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n /**\n * Output file path\n */\n output: z.string().describe('Output file path'),\n \n /**\n * Export format\n */\n format: MetadataFormatSchema.default('json').describe('Export format'),\n \n /**\n * Filter predicate as string\n */\n filter: z.string().optional().describe('Filter items to export'),\n \n /**\n * Include statistics in export\n */\n includeStats: z.boolean().default(false).describe('Include metadata statistics'),\n \n /**\n * Compress output\n */\n compress: z.boolean().default(false).describe('Compress output (gzip)'),\n \n /**\n * Pretty print output\n */\n prettify: z.boolean().default(true).describe('Pretty print output'),\n});\n\n/**\n * Metadata Import Options\n */\nexport const MetadataImportOptionsSchema = z.object({\n /**\n * Conflict resolution strategy\n */\n conflictResolution: z.enum(['skip', 'overwrite', 'merge', 'fail'])\n .default('merge')\n .describe('How to handle existing items'),\n \n /**\n * Validate items against schema\n */\n validate: z.boolean().default(true).describe('Validate before import'),\n \n /**\n * Dry run (don't actually save)\n */\n dryRun: z.boolean().default(false).describe('Simulate import without saving'),\n \n /**\n * Continue on errors\n */\n continueOnError: z.boolean().default(false).describe('Continue if validation fails'),\n \n /**\n * Transform function (as string)\n * Example: \"(item) => ({ ...item, imported: true })\"\n */\n transform: z.string().optional().describe('Transform items before import'),\n});\n\n/**\n * Metadata Loader Result\n * Result of a metadata load operation\n */\nexport const MetadataLoadResultSchema = z.object({\n /**\n * Loaded data\n */\n data: z.unknown().nullable().describe('Loaded metadata'),\n \n /**\n * Whether data came from cache (304 Not Modified)\n */\n fromCache: z.boolean().default(false).describe('Loaded from cache'),\n \n /**\n * Not modified (conditional request matched)\n */\n notModified: z.boolean().default(false).describe('Not modified since last request'),\n \n /**\n * ETag of loaded data\n */\n etag: z.string().optional().describe('Entity tag'),\n \n /**\n * Statistics about loaded data\n */\n stats: MetadataStatsSchema.optional().describe('Metadata statistics'),\n \n /**\n * Load time in milliseconds\n */\n loadTime: z.number().min(0).optional().describe('Load duration in ms'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n /**\n * Whether save was successful\n */\n success: z.boolean().describe('Save successful'),\n \n /**\n * Path where file was saved\n */\n path: z.string().describe('Output path'),\n \n /**\n * Generated ETag\n */\n etag: z.string().optional().describe('Generated entity tag'),\n \n /**\n * File size in bytes\n */\n size: z.number().int().min(0).optional().describe('File size'),\n \n /**\n * Save time in milliseconds\n */\n saveTime: z.number().min(0).optional().describe('Save duration in ms'),\n \n /**\n * Backup path (if created)\n */\n backupPath: z.string().optional().describe('Backup file path'),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum(['added', 'changed', 'deleted']).describe('Event type'),\n \n /**\n * Metadata type (e.g., 'object', 'view', 'app')\n */\n metadataType: z.string().describe('Type of metadata'),\n \n /**\n * Item name/identifier\n */\n name: z.string().describe('Item identifier'),\n \n /**\n * Full file path\n */\n path: z.string().describe('File path'),\n \n /**\n * Loaded item data (for added/changed events)\n */\n data: z.unknown().optional().describe('Item data'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\n/**\n * Metadata Collection Info\n * Summary of a metadata collection\n */\nexport const MetadataCollectionInfoSchema = z.object({\n /**\n * Collection type (e.g., 'object', 'view', 'app')\n */\n type: z.string().describe('Collection type'),\n \n /**\n * Total items in collection\n */\n count: z.number().int().min(0).describe('Number of items'),\n \n /**\n * Formats found in collection\n */\n formats: z.array(MetadataFormatSchema).describe('Formats in collection'),\n \n /**\n * Total size in bytes\n */\n totalSize: z.number().int().min(0).optional().describe('Total size in bytes'),\n \n /**\n * Last modified timestamp\n */\n lastModified: z.string().datetime().optional().describe('Last modification date'),\n \n /**\n * Collection location (path or URL)\n */\n location: z.string().optional().describe('Collection location'),\n});\n\n/**\n * Metadata Loader Interface Contract\n * Defines the standard methods all metadata loaders must implement\n */\nexport const MetadataLoaderContractSchema = z.object({\n /**\n * Loader name/identifier\n */\n name: z.string().describe('Loader identifier'),\n\n /**\n * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:')\n */\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Protocol identifier'),\n\n /**\n * Detailed capabilities\n */\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }).describe('Loader capabilities'),\n \n /**\n * Supported formats\n */\n supportedFormats: z.array(MetadataFormatSchema).describe('Supported formats'),\n \n /**\n * Whether loader supports watching for changes\n */\n supportsWatch: z.boolean().default(false).describe('Supports file watching'),\n \n /**\n * Whether loader supports saving\n */\n supportsWrite: z.boolean().default(true).describe('Supports write operations'),\n \n /**\n * Whether loader supports caching\n */\n supportsCache: z.boolean().default(true).describe('Supports caching'),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Manager Configuration\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory path'),\n \n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).default(['typescript', 'json', 'yaml']).describe('Enabled formats'),\n \n /**\n * Cache configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable caching'),\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n maxSize: z.number().int().min(0).optional().describe('Max cache size in bytes'),\n }).optional().describe('Cache settings'),\n \n /**\n * Watch for file changes\n */\n watch: z.boolean().default(false).describe('Enable file watching'),\n \n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n ignoreInitial: z.boolean().default(true).describe('Ignore initial add events'),\n }).optional().describe('File watcher options'),\n \n /**\n * Validation settings\n */\n validation: z.object({\n strict: z.boolean().default(true).describe('Strict validation'),\n throwOnError: z.boolean().default(true).describe('Throw on validation error'),\n }).optional().describe('Validation settings'),\n \n /**\n * Loader-specific options\n */\n loaderOptions: z.record(z.string(), z.unknown()).optional().describe('Loader-specific configuration'),\n});\n\n// Export types\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoadOptions = z.input;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { MetadataManagerConfigSchema } from './metadata-loader.zod';\nimport { MergeStrategyConfigSchema, CustomizationPolicySchema } from './metadata-customization.zod';\n\n/**\n * # Metadata Plugin Protocol\n *\n * Defines the specification for the **Metadata Plugin** — the central authority\n * responsible for managing ALL metadata across the ObjectStack platform.\n *\n * ## Architecture\n * The Metadata Plugin consolidates all scattered metadata operations into a single,\n * cohesive plugin that \"takes over\" the entire platform's metadata management:\n *\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ Metadata Plugin │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Type Registry │ │ Loader │ │ Customization Layer │ │\n * │ │ (all types) │ │ (file/db/s3)│ │ (overlay / merge) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Persistence │ │ Query │ │ Lifecycle │ │\n * │ │ (db records) │ │ (search) │ │ (validate/deploy) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n *\n * ## References\n * - kernel/metadata-loader.zod.ts — Storage backend protocol\n * - kernel/metadata-customization.zod.ts — Overlay/merge protocol\n * - system/metadata-persistence.zod.ts — Database record format\n * - contracts/metadata-service.ts — Service interface\n */\n\n// ==========================================\n// Metadata Type Registry\n// ==========================================\n\n/**\n * Platform Metadata Type Enum\n *\n * The canonical list of all metadata types managed by the platform.\n * Each type maps to a specific Zod schema (e.g., ObjectSchema, ViewSchema).\n * Plugins can extend this registry via `contributes.kinds` in the manifest.\n *\n * ## Naming Convention\n * **IMPORTANT:** All metadata type names are in **SINGULAR** form:\n * - ✅ Use: `'agent'`, `'tool'`, `'skill'`, `'view'`, `'flow'`, `'action'`\n * - ❌ NOT: `'agents'`, `'tools'`, `'skills'`, `'views'`, `'flows'`, `'actions'`\n *\n * This convention applies to:\n * - Protocol definitions (this enum)\n * - UI plugin registrations (`metadataTypes`, `metadataIcons`)\n * - Metadata service operations\n * - File patterns (`*.agent.ts`, `*.tool.ts`)\n *\n * REST API endpoints continue to use plural forms per REST conventions:\n * - `/api/v1/ai/agents`, `/api/v1/ai/conversations`\n */\nexport const MetadataTypeSchema = z.enum([\n // Data Protocol\n 'object', // Business entity definition (ObjectSchema)\n 'field', // Standalone field definition (FieldSchema)\n 'trigger', // Data-layer event triggers (TriggerSchema)\n 'validation', // Validation rules (ValidationSchema)\n 'hook', // Data hooks (HookSchema)\n\n // UI Protocol\n 'view', // List/form views (ViewSchema)\n 'page', // Standalone pages (PageSchema)\n 'dashboard', // Dashboard layouts (DashboardSchema)\n 'app', // Application shell (AppSchema)\n 'action', // UI/Server actions (ActionSchema)\n 'report', // Report definitions (ReportSchema)\n\n // Automation Protocol\n 'flow', // Visual logic flows (FlowSchema)\n 'workflow', // State machines (WorkflowSchema)\n 'approval', // Approval processes (ApprovalSchema)\n\n // System Protocol\n 'datasource', // Data connections (DatasourceSchema)\n 'translation', // i18n resources (TranslationSchema)\n 'router', // API routes\n 'function', // Serverless functions\n 'service', // Service definitions\n\n // Security Protocol\n 'permission', // Permission sets (PermissionSetSchema)\n 'profile', // User profiles (ProfileSchema)\n 'role', // Security roles\n\n // AI Protocol\n 'agent', // AI agent definitions (AgentSchema)\n 'tool', // AI tool definitions (ToolSchema)\n 'skill', // AI skill definitions (SkillSchema)\n]);\n\nexport type MetadataType = z.infer;\n\n// ==========================================\n// Type Registry Entry\n// ==========================================\n\n/**\n * Metadata Type Registry Entry\n *\n * Describes a registered metadata type, including its validation schema,\n * file patterns, and capabilities. Used by the metadata plugin to:\n * 1. Discover metadata files on disk\n * 2. Validate metadata payloads\n * 3. Determine storage behavior\n */\nexport const MetadataTypeRegistryEntrySchema = z.object({\n /** Metadata type identifier (e.g., 'object', 'view') */\n type: MetadataTypeSchema.describe('Metadata type identifier'),\n\n /** Human-readable label */\n label: z.string().describe('Display label for the metadata type'),\n\n /** Brief description */\n description: z.string().optional().describe('Description of the metadata type'),\n\n /**\n * File glob patterns for this type.\n * Used to discover metadata files on disk.\n * @example [\"**\\/*.object.ts\", \"**\\/*.object.yml\"]\n */\n filePatterns: z.array(z.string()).describe('Glob patterns to discover files of this type'),\n\n /**\n * Whether this type supports the customization overlay system.\n * When true, platform/user overlays can be applied on top of package-delivered metadata.\n */\n supportsOverlay: z.boolean().default(true).describe('Whether overlay customization is supported'),\n\n /**\n * Whether metadata of this type can be created at runtime via API.\n * Some types (e.g., 'object') may be restricted to deployment-only.\n */\n allowRuntimeCreate: z.boolean().default(true).describe('Allow runtime creation via API'),\n\n /**\n * Whether this type supports versioning.\n * When true, changes are tracked with version history.\n */\n supportsVersioning: z.boolean().default(false).describe('Whether version history is tracked'),\n\n /**\n * Priority order for loading (lower = earlier).\n * Objects load before views, views before dashboards.\n */\n loadOrder: z.number().int().min(0).default(100).describe('Loading priority (lower = earlier)'),\n\n /** The domain this type belongs to */\n domain: z.enum(['data', 'ui', 'automation', 'system', 'security', 'ai'])\n .describe('Protocol domain'),\n});\n\nexport type MetadataTypeRegistryEntry = z.infer;\n\n// ==========================================\n// Metadata Query Protocol\n// ==========================================\n\n/**\n * Metadata Query Schema\n *\n * Standard protocol for searching and filtering metadata items.\n * Used by the metadata service to support advanced metadata discovery.\n */\nexport const MetadataQuerySchema = z.object({\n /** Filter by metadata type(s) */\n types: z.array(MetadataTypeSchema).optional().describe('Filter by metadata types'),\n\n /** Filter by namespace(s) */\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n\n /** Filter by package ID */\n packageId: z.string().optional().describe('Filter by owning package'),\n\n /** Full-text search across name, label, description */\n search: z.string().optional().describe('Full-text search query'),\n\n /** Filter by scope */\n scope: z.enum(['system', 'platform', 'user']).optional().describe('Filter by scope'),\n\n /** Filter by state */\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional().describe('Filter by lifecycle state'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Sort field */\n sortBy: z.enum(['name', 'type', 'updatedAt', 'createdAt']).default('name').describe('Sort field'),\n\n /** Sort direction */\n sortOrder: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n\n /** Pagination: page number (1-based) */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(500).default(50).describe('Items per page'),\n});\n\nexport type MetadataQuery = z.input;\n\n/**\n * Metadata Query Result\n */\nexport const MetadataQueryResultSchema = z.object({\n /** Matched items */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n namespace: z.string().optional().describe('Namespace'),\n label: z.string().optional().describe('Display label'),\n scope: z.enum(['system', 'platform', 'user']).optional(),\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional(),\n packageId: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n })).describe('Matched metadata items'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching items'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page'),\n\n /** Page size */\n pageSize: z.number().int().min(1).describe('Page size'),\n});\n\nexport type MetadataQueryResult = z.infer;\n\n// ==========================================\n// Metadata Lifecycle Events\n// ==========================================\n\n/**\n * Metadata Event Schema\n *\n * Events emitted by the metadata plugin when metadata changes.\n * Enables reactive patterns across the platform (cache invalidation,\n * UI refresh, dependency tracking, etc.).\n */\nexport const MetadataEventSchema = z.object({\n /** Event type */\n event: z.enum([\n 'metadata.registered',\n 'metadata.updated',\n 'metadata.unregistered',\n 'metadata.validated',\n 'metadata.deployed',\n 'metadata.overlay.applied',\n 'metadata.overlay.removed',\n 'metadata.imported',\n 'metadata.exported',\n ]).describe('Event type'),\n\n /** Metadata type */\n metadataType: MetadataTypeSchema.describe('Metadata type'),\n\n /** Item name */\n name: z.string().describe('Metadata item name'),\n\n /** Namespace */\n namespace: z.string().optional().describe('Namespace'),\n\n /** Package ID (if package-managed) */\n packageId: z.string().optional().describe('Owning package ID'),\n\n /** Timestamp */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /** Actor who caused the event */\n actor: z.string().optional().describe('User or system that triggered the event'),\n\n /** Additional event-specific payload */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event-specific payload'),\n});\n\nexport type MetadataEvent = z.infer;\n\n// ==========================================\n// Metadata Validation\n// ==========================================\n\n/**\n * Metadata Validation Result\n */\nexport const MetadataValidationResultSchema = z.object({\n /** Whether validation passed */\n valid: z.boolean().describe('Whether the metadata is valid'),\n\n /** Validation errors */\n errors: z.array(z.object({\n path: z.string().describe('JSON path to the invalid field'),\n message: z.string().describe('Error description'),\n code: z.string().optional().describe('Error code'),\n })).optional().describe('Validation errors'),\n\n /** Validation warnings (non-blocking) */\n warnings: z.array(z.object({\n path: z.string().describe('JSON path to the field'),\n message: z.string().describe('Warning description'),\n })).optional().describe('Validation warnings'),\n});\n\nexport type MetadataValidationResult = z.infer;\n\n// ==========================================\n// Metadata Plugin Configuration\n// ==========================================\n\n/**\n * Metadata Plugin Configuration\n *\n * The unified configuration for the metadata plugin, combining\n * storage, caching, customization, and type registry settings.\n */\nexport const MetadataPluginConfigSchema = z.object({\n /**\n * Storage configuration.\n * References MetadataManagerConfigSchema for the underlying storage backend.\n */\n storage: MetadataManagerConfigSchema.describe('Storage backend configuration'),\n\n /**\n * Default customization policies per metadata type.\n * Controls what parts of metadata can be customized by admins/users.\n */\n customizationPolicies: z.array(CustomizationPolicySchema).optional()\n .describe('Default customization policies per type'),\n\n /**\n * Merge strategy for package upgrades.\n */\n mergeStrategy: MergeStrategyConfigSchema.optional()\n .describe('Merge strategy for package upgrades'),\n\n /**\n * Additional metadata type registrations.\n * Used by plugins to register custom metadata types beyond the built-in set.\n */\n additionalTypes: z.array(MetadataTypeRegistryEntrySchema.omit({ type: true }).extend({\n type: z.string().describe('Custom metadata type identifier'),\n })).optional().describe('Additional custom metadata types'),\n\n /**\n * Enable metadata change events.\n * When true, the plugin emits events on every metadata change.\n */\n enableEvents: z.boolean().default(true).describe('Emit metadata change events'),\n\n /**\n * Enable metadata validation on write operations.\n * When true, all metadata is validated against its type schema before saving.\n */\n validateOnWrite: z.boolean().default(true).describe('Validate metadata on write'),\n\n /**\n * Enable metadata versioning.\n * When true, changes to metadata are tracked with version history.\n */\n enableVersioning: z.boolean().default(false).describe('Track metadata version history'),\n\n /**\n * Maximum number of metadata items to keep in memory cache.\n */\n cacheMaxItems: z.number().int().min(0).default(10000).describe('Max items in memory cache'),\n});\n\nexport type MetadataPluginConfig = z.input;\n\n// ==========================================\n// Metadata Plugin Manifest\n// ==========================================\n\n/**\n * Metadata Plugin Manifest\n *\n * The complete manifest for the Metadata Plugin, declaring its identity,\n * capabilities, and configuration. This is the \"contract\" between the\n * metadata plugin and the kernel.\n */\nexport const MetadataPluginManifestSchema = z.object({\n /** Plugin identifier */\n id: z.literal('com.objectstack.metadata').describe('Metadata plugin ID'),\n\n /** Plugin name */\n name: z.literal('ObjectStack Metadata Service').describe('Plugin name'),\n\n /** Plugin version */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Plugin version'),\n\n /** Plugin type */\n type: z.literal('standard').describe('Plugin type'),\n\n /** Plugin description */\n description: z.string().default('Core metadata management service for ObjectStack platform')\n .describe('Plugin description'),\n\n /**\n * Capabilities this plugin provides.\n * The kernel uses this to route metadata requests to this plugin.\n */\n capabilities: z.object({\n /** Supports CRUD operations on metadata */\n crud: z.boolean().default(true).describe('Supports metadata CRUD'),\n\n /** Supports metadata query/search */\n query: z.boolean().default(true).describe('Supports metadata query'),\n\n /** Supports the overlay/customization system */\n overlay: z.boolean().default(true).describe('Supports customization overlays'),\n\n /** Supports file watching for hot reload */\n watch: z.boolean().default(false).describe('Supports file watching'),\n\n /** Supports bulk import/export */\n importExport: z.boolean().default(true).describe('Supports import/export'),\n\n /** Supports metadata validation */\n validation: z.boolean().default(true).describe('Supports schema validation'),\n\n /** Supports metadata versioning */\n versioning: z.boolean().default(false).describe('Supports version history'),\n\n /** Supports metadata events */\n events: z.boolean().default(true).describe('Emits metadata events'),\n }).describe('Plugin capabilities'),\n\n /** Plugin configuration */\n config: MetadataPluginConfigSchema.optional().describe('Plugin configuration'),\n});\n\nexport type MetadataPluginManifest = z.input;\n\n// ==========================================\n// Built-in Type Registry Defaults\n// ==========================================\n\n/**\n * Default Type Registry\n *\n * The built-in metadata type registry with default configurations.\n * Plugins extend this via `contributes.kinds` in the manifest.\n */\nexport const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntry[] = [\n // Data Protocol (load first)\n { type: 'object', label: 'Object', filePatterns: ['**/*.object.ts', '**/*.object.yml', '**/*.object.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 10, domain: 'data' },\n { type: 'field', label: 'Field', filePatterns: ['**/*.field.ts', '**/*.field.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 20, domain: 'data' },\n { type: 'trigger', label: 'Trigger', filePatterns: ['**/*.trigger.ts', '**/*.trigger.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'validation', label: 'Validation Rule', filePatterns: ['**/*.validation.ts', '**/*.validation.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'hook', label: 'Hook', filePatterns: ['**/*.hook.ts', '**/*.hook.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n\n // UI Protocol\n { type: 'view', label: 'View', filePatterns: ['**/*.view.ts', '**/*.view.yml', '**/*.view.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'page', label: 'Page', filePatterns: ['**/*.page.ts', '**/*.page.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'dashboard', label: 'Dashboard', filePatterns: ['**/*.dashboard.ts', '**/*.dashboard.yml', '**/*.dashboard.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n { type: 'app', label: 'Application', filePatterns: ['**/*.app.ts', '**/*.app.yml', '**/*.app.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 70, domain: 'ui' },\n { type: 'action', label: 'Action', filePatterns: ['**/*.action.ts', '**/*.action.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'report', label: 'Report', filePatterns: ['**/*.report.ts', '**/*.report.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n\n // Automation Protocol\n { type: 'flow', label: 'Flow', filePatterns: ['**/*.flow.ts', '**/*.flow.yml', '**/*.flow.json'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'workflow', label: 'Workflow', filePatterns: ['**/*.workflow.ts', '**/*.workflow.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'approval', label: 'Approval Process', filePatterns: ['**/*.approval.ts', '**/*.approval.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 80, domain: 'automation' },\n\n // System Protocol\n { type: 'datasource', label: 'Datasource', filePatterns: ['**/*.datasource.ts', '**/*.datasource.yml'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 5, domain: 'system' },\n { type: 'translation', label: 'Translation', filePatterns: ['**/*.translation.ts', '**/*.translation.yml', '**/*.translation.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 90, domain: 'system' },\n { type: 'router', label: 'Router', filePatterns: ['**/*.router.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'function', label: 'Function', filePatterns: ['**/*.function.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'service', label: 'Service', filePatterns: ['**/*.service.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n\n // Security Protocol\n { type: 'permission', label: 'Permission Set', filePatterns: ['**/*.permission.ts', '**/*.permission.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 15, domain: 'security' },\n { type: 'profile', label: 'Profile', filePatterns: ['**/*.profile.ts', '**/*.profile.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n { type: 'role', label: 'Role', filePatterns: ['**/*.role.ts', '**/*.role.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n\n // AI Protocol\n { type: 'agent', label: 'AI Agent', filePatterns: ['**/*.agent.ts', '**/*.agent.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 90, domain: 'ai' },\n { type: 'tool', label: 'AI Tool', filePatterns: ['**/*.tool.ts', '**/*.tool.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 85, domain: 'ai' },\n { type: 'skill', label: 'AI Skill', filePatterns: ['**/*.skill.ts', '**/*.skill.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 88, domain: 'ai' },\n];\n\n// ==========================================\n// Bulk Operation Types\n// ==========================================\n\n/**\n * Bulk Register Request\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n /** Items to register */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Namespace'),\n })).min(1).describe('Items to register'),\n\n /** Continue on individual item failure */\n continueOnError: z.boolean().default(false).describe('Continue if individual item fails'),\n\n /** Validate items before registering */\n validate: z.boolean().default(true).describe('Validate before register'),\n});\n\nexport type MetadataBulkRegisterRequest = z.input;\n\n/**\n * Bulk Operation Result\n */\nexport const MetadataBulkResultSchema = z.object({\n /** Total items processed */\n total: z.number().int().min(0).describe('Total items processed'),\n\n /** Successfully processed items */\n succeeded: z.number().int().min(0).describe('Successfully processed'),\n\n /** Failed items */\n failed: z.number().int().min(0).describe('Failed items'),\n\n /** Per-item error details */\n errors: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n error: z.string().describe('Error message'),\n })).optional().describe('Per-item errors'),\n});\n\nexport type MetadataBulkResult = z.infer;\n\n// ==========================================\n// Metadata Dependency\n// ==========================================\n\n/**\n * Metadata Dependency Schema\n *\n * Tracks dependencies between metadata items.\n * Used for impact analysis and safe deletion checks.\n */\nexport const MetadataDependencySchema = z.object({\n /** Source metadata type */\n sourceType: z.string().describe('Dependent metadata type'),\n\n /** Source metadata name */\n sourceName: z.string().describe('Dependent metadata name'),\n\n /** Target metadata type */\n targetType: z.string().describe('Referenced metadata type'),\n\n /** Target metadata name */\n targetName: z.string().describe('Referenced metadata name'),\n\n /** Dependency kind */\n kind: z.enum(['reference', 'extends', 'includes', 'triggers'])\n .describe('How the dependency is formed'),\n});\n\nexport type MetadataDependency = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\nimport { DependencyResolutionResultSchema } from './dependency-resolution.zod';\n\n/**\n * # Package Registry Protocol\n * \n * Defines the runtime state and lifecycle operations for installed packages.\n * \n * ## Key Distinction: Package vs App\n * - **Package (Manifest)**: The unit of installation — a deployable artifact containing\n * metadata (objects, actions, flows, etc.) and optionally one or more Apps.\n * - **App (AppSchema)**: A UI navigation shell defined inside a package.\n * \n * A package may contain:\n * - Zero apps (pure functionality plugin, e.g. a storage driver)\n * - One app (typical business application)\n * - Multiple apps (suite of applications)\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Packages with install/uninstall lifecycle\n * - **VS Code**: Extension marketplace with enable/disable per-workspace\n * - **Kubernetes**: Helm charts with release state tracking\n * - **npm**: Package registry with install/uninstall/version management\n */\n\n// ==========================================\n// Package Status & Lifecycle\n// ==========================================\n\n/**\n * Package installation status.\n */\nexport const PackageStatusEnum = z.enum([\n 'installed', // Successfully installed and enabled\n 'disabled', // Installed but disabled (metadata not active)\n 'installing', // Installation in progress\n 'upgrading', // Upgrade in progress\n 'uninstalling', // Removal in progress\n 'error', // Installation or runtime error\n]).describe('Package installation status');\nexport type PackageStatus = z.infer;\n\n/**\n * Installed Package Schema\n * \n * Wraps a ManifestSchema with runtime lifecycle state.\n * This is the \"row\" in the installed packages table.\n */\nexport const InstalledPackageSchema = z.object({\n /** \n * The full package manifest (source of truth for package definition).\n */\n manifest: ManifestSchema.describe('Full package manifest'),\n\n /**\n * Current lifecycle status.\n */\n status: PackageStatusEnum.default('installed')\n .describe('Package state: installed, disabled, installing, upgrading, uninstalling, or error'),\n\n /**\n * Whether the package is currently enabled (active).\n * When disabled, the package's metadata is not loaded into the registry.\n */\n enabled: z.boolean().default(true)\n .describe('Whether the package is currently enabled'),\n\n /**\n * ISO 8601 timestamp of when the package was installed.\n */\n installedAt: z.string().datetime().optional()\n .describe('Installation timestamp'),\n\n /**\n * ISO 8601 timestamp of last update.\n */\n updatedAt: z.string().datetime().optional()\n .describe('Last update timestamp'),\n\n /**\n * The currently installed version string.\n * Mirrors manifest.version for quick access without parsing the full manifest.\n */\n installedVersion: z.string().optional()\n .describe('Currently installed version for quick access'),\n\n /**\n * The previously installed version (before last upgrade).\n * Useful for rollback and upgrade tracking.\n */\n previousVersion: z.string().optional()\n .describe('Version before the last upgrade'),\n\n /**\n * ISO 8601 timestamp of when the package was last enabled/disabled.\n */\n statusChangedAt: z.string().datetime().optional()\n .describe('Status change timestamp'),\n\n /**\n * Error message if status is 'error'.\n */\n errorMessage: z.string().optional()\n .describe('Error message when status is error'),\n\n /**\n * Configuration values set by the user for this package.\n * Keys correspond to the package's `configuration.properties`.\n */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided configuration settings'),\n\n /**\n * Upgrade history for this package.\n * Records each version migration with status and optional log.\n */\n upgradeHistory: z.array(z.object({\n /** Previous version before upgrade */\n fromVersion: z.string().describe('Version before upgrade'),\n /** New version after upgrade */\n toVersion: z.string().describe('Version after upgrade'),\n /** Timestamp of the upgrade */\n upgradedAt: z.string().datetime().describe('Upgrade timestamp'),\n /** Outcome of the upgrade */\n status: z.enum(['success', 'failed', 'rolled_back']).describe('Upgrade outcome'),\n /** Migration log entries */\n migrationLog: z.array(z.string()).optional().describe('Migration step logs'),\n })).optional().describe('Version upgrade history'),\n\n /**\n * Namespaces registered by this package.\n * Tracks which namespace prefixes are occupied by this package.\n */\n registeredNamespaces: z.array(z.string()).optional()\n .describe('Namespace prefixes registered by this package'),\n}).describe('Installed package with runtime lifecycle state');\nexport type InstalledPackage = z.infer;\n\n// ==========================================\n// Namespace Registry\n// ==========================================\n\n/**\n * Namespace Registry Entry\n * Tracks namespace ownership within the platform instance.\n */\nexport const NamespaceRegistryEntrySchema = z.object({\n /** Namespace prefix */\n namespace: z.string().describe('Namespace prefix'),\n\n /** Package that owns this namespace */\n packageId: z.string().describe('Owning package ID'),\n\n /** Registration timestamp */\n registeredAt: z.string().datetime().describe('Registration timestamp'),\n\n /** Namespace status */\n status: z.enum(['active', 'disabled', 'reserved'])\n .describe('Namespace status'),\n}).describe('Namespace ownership entry in the registry');\n\nexport type NamespaceRegistryEntry = z.infer;\n\n/**\n * Namespace Conflict Error\n * Describes a namespace collision detected during package installation.\n */\nexport const NamespaceConflictErrorSchema = z.object({\n /** Error type discriminator */\n type: z.literal('namespace_conflict').describe('Error type'),\n\n /** Namespace that was requested */\n requestedNamespace: z.string().describe('Requested namespace'),\n\n /** ID of the package that already owns the namespace */\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n\n /** Name of the conflicting package */\n conflictingPackageName: z.string().describe('Conflicting package display name'),\n\n /** Suggested alternative namespace */\n suggestion: z.string().optional()\n .describe('Suggested alternative namespace'),\n}).describe('Namespace collision error during installation');\n\nexport type NamespaceConflictError = z.infer;\n\n// ==========================================\n// Package Registry Request/Response Schemas\n// ==========================================\n\n/**\n * List Packages Request\n */\nexport const ListPackagesRequestSchema = z.object({\n /** Filter by status */\n status: PackageStatusEnum.optional().describe('Filter by package status'),\n /** Filter by package type */\n type: ManifestSchema.shape.type.optional().describe('Filter by package type'),\n /** Filter by enabled state */\n enabled: z.boolean().optional().describe('Filter by enabled state'),\n}).describe('List packages request');\nexport type ListPackagesRequest = z.infer;\n\n/**\n * List Packages Response\n */\nexport const ListPackagesResponseSchema = z.object({\n packages: z.array(InstalledPackageSchema).describe('List of installed packages'),\n total: z.number().describe('Total package count'),\n}).describe('List packages response');\nexport type ListPackagesResponse = z.infer;\n\n/**\n * Get Package Request\n */\nexport const GetPackageRequestSchema = z.object({\n /** Package ID (reverse domain identifier from manifest) */\n id: z.string().describe('Package identifier'),\n}).describe('Get package request');\nexport type GetPackageRequest = z.infer;\n\n/**\n * Get Package Response\n */\nexport const GetPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Package details'),\n}).describe('Get package response');\nexport type GetPackageResponse = z.infer;\n\n/**\n * Install Package Request\n * \n * Accepts a full manifest to install. In a production system,\n * this might also accept a package ID to fetch from a marketplace.\n */\nexport const InstallPackageRequestSchema = z.object({\n /** The package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n /** Optional: user-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n /** Whether to enable immediately after install (default: true) */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n /**\n * Current platform version for compatibility checking.\n * When provided, the system compares this against the package's\n * `engine.objectstack` requirement to verify compatibility.\n */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n}).describe('Install package request');\nexport type InstallPackageRequest = z.infer;\n\n/**\n * Install Package Response\n */\nexport const InstallPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n message: z.string().optional().describe('Installation status message'),\n /** Dependency resolution result (when dependencies were analyzed) */\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result from install analysis'),\n}).describe('Install package response');\nexport type InstallPackageResponse = z.infer;\n\n/**\n * Uninstall Package Request\n */\nexport const UninstallPackageRequestSchema = z.object({\n /** Package ID to uninstall */\n id: z.string().describe('Package ID to uninstall'),\n}).describe('Uninstall package request');\nexport type UninstallPackageRequest = z.infer;\n\n/**\n * Uninstall Package Response\n */\nexport const UninstallPackageResponseSchema = z.object({\n id: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n}).describe('Uninstall package response');\nexport type UninstallPackageResponse = z.infer;\n\n/**\n * Enable Package Request\n */\nexport const EnablePackageRequestSchema = z.object({\n /** Package ID to enable */\n id: z.string().describe('Package ID to enable'),\n}).describe('Enable package request');\nexport type EnablePackageRequest = z.infer;\n\n/**\n * Enable Package Response\n */\nexport const EnablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Enabled package details'),\n message: z.string().optional().describe('Enable status message'),\n}).describe('Enable package response');\nexport type EnablePackageResponse = z.infer;\n\n/**\n * Disable Package Request\n */\nexport const DisablePackageRequestSchema = z.object({\n /** Package ID to disable */\n id: z.string().describe('Package ID to disable'),\n}).describe('Disable package request');\nexport type DisablePackageRequest = z.infer;\n\n/**\n * Disable Package Response\n */\nexport const DisablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Disabled package details'),\n message: z.string().optional().describe('Disable status message'),\n}).describe('Disable package response');\nexport type DisablePackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\n\n/**\n * # Package Upgrade Protocol\n * \n * Defines the complete lifecycle for upgrading installed packages,\n * including pre-upgrade analysis, snapshot/backup, execution, validation,\n * and rollback capabilities.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Package upgrade with push upgrades and subscriber control\n * - **ServiceNow**: Update Sets with preview, commit, and back-out support\n * - **Helm**: Helm upgrade with rollback to previous release\n * - **Kubernetes**: Rolling update with readiness probes and automatic rollback\n * \n * ## Upgrade Flow\n * ```\n * 1. PreCheck → Validate compatibility, check dependencies\n * 2. Plan → Generate upgrade plan with metadata diff\n * 3. Snapshot → Backup current state (metadata + customizations)\n * 4. Execute → Apply new package metadata with 3-way merge\n * 5. Validate → Run post-upgrade health checks\n * 6. Commit → Finalize upgrade (or Rollback on failure)\n * ```\n */\n\n// ==========================================\n// Upgrade Plan & Analysis\n// ==========================================\n\n/**\n * Metadata Change Type\n * Type of change detected between package versions.\n */\nexport const MetadataChangeTypeSchema = z.enum([\n 'added', // New metadata item added in new version\n 'modified', // Existing metadata item modified\n 'removed', // Metadata item removed in new version\n 'renamed', // Metadata item renamed\n]).describe('Type of metadata change between package versions');\n\n/**\n * Metadata Diff Item\n * Describes a single metadata change between two package versions.\n */\nexport const MetadataDiffItemSchema = z.object({\n /** Metadata type (e.g. \"object\", \"view\", \"flow\") */\n type: z.string().describe('Metadata type'),\n\n /** Metadata name */\n name: z.string().describe('Metadata name'),\n\n /** Type of change */\n changeType: MetadataChangeTypeSchema.describe('Category of metadata modification (added, modified, removed, or renamed)'),\n\n /** Whether this change has potential conflicts with customizations */\n hasConflict: z.boolean().default(false)\n .describe('Whether this change may conflict with customizations'),\n\n /** Human-readable summary of the change */\n summary: z.string().optional().describe('Human-readable change summary'),\n\n /** Previous name (for renames) */\n previousName: z.string().optional().describe('Previous name if renamed'),\n}).describe('Single metadata change between package versions');\n\n/**\n * Upgrade Impact Level\n * Indicates the severity of impact the upgrade will have.\n */\nexport const UpgradeImpactLevelSchema = z.enum([\n 'none', // No impact, seamless upgrade\n 'low', // Minor changes, no user action needed\n 'medium', // Some changes that may affect workflows\n 'high', // Significant changes, user review recommended\n 'critical', // Breaking changes, manual intervention required\n]).describe('Severity of upgrade impact');\n\n/**\n * Upgrade Plan Schema\n * The analysis result before executing an upgrade.\n * Generated by comparing old version metadata with new version metadata.\n */\nexport const UpgradePlanSchema = z.object({\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Current installed version */\n fromVersion: z.string().describe('Currently installed version'),\n\n /** Target version to upgrade to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Overall impact level */\n impactLevel: UpgradeImpactLevelSchema.describe('Severity assessment from none (seamless) to critical (breaking changes)'),\n\n /** List of all metadata changes between versions */\n changes: z.array(MetadataDiffItemSchema).describe('All metadata changes'),\n\n /** Number of customer customizations that may be affected */\n affectedCustomizations: z.number().int().min(0).default(0)\n .describe('Count of customizations that may be affected'),\n\n /** Whether any migration scripts need to run */\n requiresMigration: z.boolean().default(false)\n .describe('Whether data migration scripts are needed'),\n\n /** Migration script paths (relative to package root) */\n migrationScripts: z.array(z.string()).optional()\n .describe('Paths to migration scripts'),\n\n /** Dependencies that also need upgrading */\n dependencyUpgrades: z.array(z.object({\n packageId: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n })).optional().describe('Dependent packages that also need upgrading'),\n\n /** Estimated upgrade duration in seconds */\n estimatedDuration: z.number().int().min(0).optional()\n .describe('Estimated upgrade duration in seconds'),\n\n /** Human-readable summary */\n summary: z.string().optional().describe('Human-readable upgrade summary'),\n}).describe('Upgrade analysis plan generated before execution');\n\n// ==========================================\n// Upgrade Snapshot (Pre-Upgrade Backup)\n// ==========================================\n\n/**\n * Upgrade Snapshot Schema\n * Captures the complete state before an upgrade for rollback capability.\n */\nexport const UpgradeSnapshotSchema = z.object({\n /** Snapshot ID (UUID) */\n id: z.string().describe('Snapshot identifier'),\n\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being upgraded from */\n fromVersion: z.string().describe('Version before upgrade'),\n\n /** Version being upgraded to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Complete manifest of the old package version */\n previousManifest: ManifestSchema.describe('Complete manifest of the previous package version'),\n\n /**\n * Snapshot of all metadata records owned by this package.\n * Stored as array of { type, name, metadata } tuples.\n */\n metadataSnapshot: z.array(z.object({\n type: z.string(),\n name: z.string(),\n metadata: z.record(z.string(), z.unknown()),\n })).describe('Snapshot of all package metadata'),\n\n /**\n * Snapshot of all customer customizations (overlays) for this package's metadata.\n */\n customizationSnapshot: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Snapshot of customer customizations'),\n\n /** When the snapshot was created */\n createdAt: z.string().datetime().describe('Snapshot creation timestamp'),\n\n /** Expiry time for snapshot cleanup */\n expiresAt: z.string().datetime().optional().describe('Snapshot expiry timestamp'),\n}).describe('Pre-upgrade state snapshot for rollback capability');\n\n// ==========================================\n// Upgrade Request/Response\n// ==========================================\n\n/**\n * Upgrade Package Request\n */\nexport const UpgradePackageRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (if omitted, upgrades to latest) */\n targetVersion: z.string().optional().describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional().describe('New manifest (if installing from local)'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum([\n 'keep-custom',\n 'accept-incoming',\n 'three-way-merge',\n ]).default('three-way-merge').describe('How to handle customer customizations'),\n\n /** Whether to run in dry-run mode (preview only, no changes) */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Whether to skip pre-upgrade validation */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\n\n/**\n * Upgrade Phase\n * Current phase of the upgrade process.\n */\nexport const UpgradePhaseSchema = z.enum([\n 'pending', // Upgrade requested but not started\n 'analyzing', // Generating upgrade plan\n 'snapshot', // Creating pre-upgrade snapshot\n 'executing', // Applying metadata changes\n 'migrating', // Running migration scripts\n 'validating', // Post-upgrade validation\n 'completed', // Upgrade completed successfully\n 'failed', // Upgrade failed\n 'rolling-back', // Rollback in progress\n 'rolled-back', // Rollback completed\n]).describe('Current phase of the upgrade process');\n\n/**\n * Upgrade Package Response\n */\nexport const UpgradePackageResponseSchema = z.object({\n /** Whether the upgrade was successful */\n success: z.boolean().describe('Whether the upgrade succeeded'),\n\n /** Current upgrade phase */\n phase: UpgradePhaseSchema.describe('Current upgrade phase'),\n\n /** The upgrade plan that was executed */\n plan: UpgradePlanSchema.optional().describe('Upgrade plan'),\n\n /** Snapshot ID for rollback */\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n\n /** Merge conflicts that need manual resolution (if any) */\n conflicts: z.array(z.object({\n path: z.string(),\n baseValue: z.unknown(),\n incomingValue: z.unknown(),\n customValue: z.unknown(),\n })).optional().describe('Unresolved merge conflicts'),\n\n /** Error message (if failed) */\n errorMessage: z.string().optional().describe('Error message if upgrade failed'),\n\n /** Human-readable summary */\n message: z.string().optional().describe('Human-readable status message'),\n}).describe('Upgrade package response');\n\n// ==========================================\n// Rollback\n// ==========================================\n\n/**\n * Rollback Package Request\n */\nexport const RollbackPackageRequestSchema = z.object({\n /** Package ID to rollback */\n packageId: z.string().describe('Package ID to rollback'),\n\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\n\n/**\n * Rollback Package Response\n */\nexport const RollbackPackageResponseSchema = z.object({\n /** Whether the rollback was successful */\n success: z.boolean().describe('Whether the rollback succeeded'),\n\n /** Restored version */\n restoredVersion: z.string().optional().describe('Version restored to'),\n\n /** Message */\n message: z.string().optional().describe('Rollback status message'),\n}).describe('Rollback package response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type MetadataChangeType = z.infer;\nexport type MetadataDiffItem = z.infer;\nexport type UpgradeImpactLevel = z.infer;\nexport type UpgradePlan = z.infer;\nexport type UpgradeSnapshot = z.infer;\nexport type UpgradePackageRequest = z.infer;\nexport type UpgradePhase = z.infer;\nexport type UpgradePackageResponse = z.infer;\nexport type RollbackPackageRequest = z.infer;\nexport type RollbackPackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Advanced Plugin Lifecycle Protocol\n * \n * Defines advanced lifecycle management capabilities including:\n * - Hot reload and live updates\n * - Graceful degradation and fallback mechanisms\n * - Health monitoring and auto-recovery\n * - State preservation during updates\n * \n * This protocol extends the basic plugin lifecycle with enterprise-grade\n * features for production environments.\n */\n\n/**\n * Plugin Health Status\n * Represents the current operational state of a plugin\n */\nexport const PluginHealthStatusSchema = z.enum([\n 'healthy', // Plugin is operating normally\n 'degraded', // Plugin is operational but with reduced functionality\n 'unhealthy', // Plugin has critical issues but still running\n 'failed', // Plugin has failed and is not operational\n 'recovering', // Plugin is in recovery process\n 'unknown', // Health status cannot be determined\n]).describe('Current health status of the plugin');\n\n/**\n * Plugin Health Check Configuration\n * Defines how to check plugin health\n */\nexport const PluginHealthCheckSchema = z.object({\n /**\n * Health check interval in milliseconds\n */\n interval: z.number().int().min(1000).default(30000)\n .describe('How often to perform health checks (default: 30s)'),\n \n /**\n * Timeout for health check in milliseconds\n */\n timeout: z.number().int().min(100).default(5000)\n .describe('Maximum time to wait for health check response'),\n \n /**\n * Number of consecutive failures before marking as unhealthy\n */\n failureThreshold: z.number().int().min(1).default(3)\n .describe('Consecutive failures needed to mark unhealthy'),\n \n /**\n * Number of consecutive successes to recover from unhealthy state\n */\n successThreshold: z.number().int().min(1).default(1)\n .describe('Consecutive successes needed to mark healthy'),\n \n /**\n * Custom health check function name or endpoint\n */\n checkMethod: z.string().optional()\n .describe('Method name to call for health check'),\n \n /**\n * Enable automatic restart on failure\n */\n autoRestart: z.boolean().default(false)\n .describe('Automatically restart plugin on health check failure'),\n \n /**\n * Maximum number of restart attempts\n */\n maxRestartAttempts: z.number().int().min(0).default(3)\n .describe('Maximum restart attempts before giving up'),\n \n /**\n * Backoff strategy for restarts\n */\n restartBackoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy for restart delays'),\n});\n\n/**\n * Plugin Health Report\n * Detailed health information from a plugin\n */\nexport const PluginHealthReportSchema = z.object({\n /**\n * Overall health status\n */\n status: PluginHealthStatusSchema,\n \n /**\n * Timestamp of the health check\n */\n timestamp: z.string().datetime(),\n \n /**\n * Human-readable message about health status\n */\n message: z.string().optional(),\n \n /**\n * Detailed metrics\n */\n metrics: z.object({\n uptime: z.number().describe('Plugin uptime in milliseconds'),\n memoryUsage: z.number().optional().describe('Memory usage in bytes'),\n cpuUsage: z.number().optional().describe('CPU usage percentage'),\n activeConnections: z.number().optional().describe('Number of active connections'),\n errorRate: z.number().optional().describe('Error rate (errors per minute)'),\n responseTime: z.number().optional().describe('Average response time in ms'),\n }).partial().optional(),\n \n /**\n * List of checks performed\n */\n checks: z.array(z.object({\n name: z.string().describe('Check name'),\n status: z.enum(['passed', 'failed', 'warning']),\n message: z.string().optional(),\n data: z.record(z.string(), z.unknown()).optional(),\n })).optional(),\n \n /**\n * Dependencies health\n */\n dependencies: z.array(z.object({\n pluginId: z.string(),\n status: PluginHealthStatusSchema,\n message: z.string().optional(),\n })).optional(),\n});\n\n/**\n * Distributed State Configuration\n * Configuration for distributed state management in cluster environments\n */\nexport const DistributedStateConfigSchema = z.object({\n /**\n * Distributed cache provider\n */\n provider: z.enum(['redis', 'etcd', 'custom'])\n .describe('Distributed state backend provider'),\n \n /**\n * Connection URL or endpoints\n */\n endpoints: z.array(z.string()).optional()\n .describe('Backend connection endpoints'),\n \n /**\n * Key prefix for namespacing\n */\n keyPrefix: z.string().optional()\n .describe('Prefix for all keys (e.g., \"plugin:my-plugin:\")'),\n \n /**\n * Time to live in seconds\n */\n ttl: z.number().int().min(0).optional()\n .describe('State expiration time in seconds'),\n \n /**\n * Authentication configuration\n */\n auth: z.object({\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n certificate: z.string().optional(),\n }).optional(),\n \n /**\n * Replication settings\n */\n replication: z.object({\n enabled: z.boolean().default(true),\n minReplicas: z.number().int().min(1).default(1),\n }).optional(),\n \n /**\n * Custom provider configuration\n */\n customConfig: z.record(z.string(), z.unknown()).optional()\n .describe('Provider-specific configuration'),\n});\n\n/**\n * Hot Reload Configuration\n * Controls how plugins handle live updates\n */\nexport const HotReloadConfigSchema = z.object({\n /**\n * Enable hot reload capability\n */\n enabled: z.boolean().default(false),\n \n /**\n * Watch file patterns for auto-reload\n */\n watchPatterns: z.array(z.string()).optional()\n .describe('Glob patterns to watch for changes'),\n \n /**\n * Debounce delay before reloading (milliseconds)\n */\n debounceDelay: z.number().int().min(0).default(1000)\n .describe('Wait time after change detection before reload'),\n \n /**\n * Preserve plugin state during reload\n */\n preserveState: z.boolean().default(true)\n .describe('Keep plugin state across reloads'),\n \n /**\n * State serialization strategy\n */\n stateStrategy: z.enum(['memory', 'disk', 'distributed', 'none']).default('memory')\n .describe('How to preserve state during reload'),\n \n /**\n * Distributed state configuration (required when stateStrategy is \"distributed\")\n */\n distributedConfig: DistributedStateConfigSchema.optional()\n .describe('Configuration for distributed state management'),\n \n /**\n * Graceful shutdown timeout\n */\n shutdownTimeout: z.number().int().min(0).default(30000)\n .describe('Maximum time to wait for graceful shutdown'),\n \n /**\n * Pre-reload hooks\n */\n beforeReload: z.array(z.string()).optional()\n .describe('Hook names to call before reload'),\n \n /**\n * Post-reload hooks\n */\n afterReload: z.array(z.string()).optional()\n .describe('Hook names to call after reload'),\n});\n\n/**\n * Graceful Degradation Configuration\n * Defines how plugin degrades when dependencies fail\n */\nexport const GracefulDegradationSchema = z.object({\n /**\n * Enable graceful degradation\n */\n enabled: z.boolean().default(true),\n \n /**\n * Fallback mode when dependencies fail\n */\n fallbackMode: z.enum([\n 'minimal', // Provide minimal functionality\n 'cached', // Use cached data\n 'readonly', // Allow read-only operations\n 'offline', // Offline mode with local data\n 'disabled', // Disable plugin functionality\n ]).default('minimal'),\n \n /**\n * Critical dependencies that must be available\n */\n criticalDependencies: z.array(z.string()).optional()\n .describe('Plugin IDs that are required for operation'),\n \n /**\n * Optional dependencies that can fail\n */\n optionalDependencies: z.array(z.string()).optional()\n .describe('Plugin IDs that are nice to have but not required'),\n \n /**\n * Feature flags for degraded mode\n */\n degradedFeatures: z.array(z.object({\n feature: z.string().describe('Feature name'),\n enabled: z.boolean().describe('Whether feature is available in degraded mode'),\n reason: z.string().optional(),\n })).optional(),\n \n /**\n * Automatic recovery attempts\n */\n autoRecovery: z.object({\n enabled: z.boolean().default(true),\n retryInterval: z.number().int().min(1000).default(60000)\n .describe('Interval between recovery attempts (ms)'),\n maxAttempts: z.number().int().min(0).default(5)\n .describe('Maximum recovery attempts before giving up'),\n }).optional(),\n});\n\n/**\n * Plugin Update Strategy\n * Defines how plugin handles version updates\n */\nexport const PluginUpdateStrategySchema = z.object({\n /**\n * Update mode\n */\n mode: z.enum([\n 'manual', // Manual updates only\n 'automatic', // Automatic updates\n 'scheduled', // Scheduled update windows\n 'rolling', // Rolling updates with zero downtime\n ]).default('manual'),\n \n /**\n * Version constraints for automatic updates\n */\n autoUpdateConstraints: z.object({\n major: z.boolean().default(false).describe('Allow major version updates'),\n minor: z.boolean().default(true).describe('Allow minor version updates'),\n patch: z.boolean().default(true).describe('Allow patch version updates'),\n }).optional(),\n \n /**\n * Update schedule (for scheduled mode)\n */\n schedule: z.object({\n /**\n * Cron expression for update window\n */\n cron: z.string().optional(),\n \n /**\n * Timezone for schedule\n */\n timezone: z.string().default('UTC'),\n \n /**\n * Maintenance window duration in minutes\n */\n maintenanceWindow: z.number().int().min(1).default(60),\n }).optional(),\n \n /**\n * Rollback configuration\n */\n rollback: z.object({\n enabled: z.boolean().default(true),\n \n /**\n * Automatic rollback on failure\n */\n automatic: z.boolean().default(true),\n \n /**\n * Keep N previous versions for rollback\n */\n keepVersions: z.number().int().min(1).default(3),\n \n /**\n * Rollback timeout in milliseconds\n */\n timeout: z.number().int().min(1000).default(30000),\n }).optional(),\n \n /**\n * Pre-update validation\n */\n validation: z.object({\n /**\n * Run compatibility checks before update\n */\n checkCompatibility: z.boolean().default(true),\n \n /**\n * Run tests before applying update\n */\n runTests: z.boolean().default(false),\n \n /**\n * Test suite to run\n */\n testSuite: z.string().optional(),\n }).optional(),\n});\n\n/**\n * Plugin State Snapshot\n * Captures plugin state for preservation during updates/reloads\n */\nexport const PluginStateSnapshotSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Version at time of snapshot\n */\n version: z.string(),\n \n /**\n * Snapshot timestamp\n */\n timestamp: z.string().datetime(),\n \n /**\n * Serialized state data\n */\n state: z.record(z.string(), z.unknown()),\n \n /**\n * State metadata\n */\n metadata: z.object({\n checksum: z.string().optional().describe('State checksum for verification'),\n compressed: z.boolean().default(false),\n encryption: z.string().optional().describe('Encryption algorithm if encrypted'),\n }).optional(),\n});\n\n/**\n * Advanced Plugin Lifecycle Configuration\n * Complete configuration for advanced lifecycle management\n */\nexport const AdvancedPluginLifecycleConfigSchema = z.object({\n /**\n * Health monitoring configuration\n */\n health: PluginHealthCheckSchema.optional(),\n \n /**\n * Hot reload configuration\n */\n hotReload: HotReloadConfigSchema.optional(),\n \n /**\n * Graceful degradation configuration\n */\n degradation: GracefulDegradationSchema.optional(),\n \n /**\n * Update strategy\n */\n updates: PluginUpdateStrategySchema.optional(),\n \n /**\n * Resource limits\n */\n resources: z.object({\n maxMemory: z.number().int().optional().describe('Maximum memory in bytes'),\n maxCpu: z.number().min(0).max(100).optional().describe('Maximum CPU percentage'),\n maxConnections: z.number().int().optional().describe('Maximum concurrent connections'),\n timeout: z.number().int().optional().describe('Operation timeout in milliseconds'),\n }).optional(),\n \n /**\n * Monitoring and observability\n */\n observability: z.object({\n enableMetrics: z.boolean().default(true),\n enableTracing: z.boolean().default(true),\n enableProfiling: z.boolean().default(false),\n metricsInterval: z.number().int().min(1000).default(60000)\n .describe('Metrics collection interval in ms'),\n }).optional(),\n});\n\n// Export types\nexport type PluginHealthStatus = z.infer;\nexport type PluginHealthCheck = z.infer;\nexport type PluginHealthReport = z.infer;\nexport type DistributedStateConfig = z.infer;\nexport type HotReloadConfig = z.infer;\nexport type GracefulDegradation = z.infer;\nexport type PluginUpdateStrategy = z.infer;\nexport type PluginStateSnapshot = z.infer;\nexport type AdvancedPluginLifecycleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Plugin Lifecycle Events Protocol\n * \n * Zod schemas for plugin lifecycle event data structures.\n * These schemas align with the IPluginLifecycleEvents contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Event Payload Schemas\n// ============================================================================\n\n/**\n * Event Phase Enum\n * Lifecycle phase where an error occurred\n */\nexport const EventPhaseSchema = z.enum(['init', 'start', 'destroy'])\n .describe('Plugin lifecycle phase');\n\nexport type EventPhase = z.infer;\n\n/**\n * Plugin Event Base Schema\n * Common fields for all plugin events\n */\nexport const PluginEventBaseSchema = z.object({\n /**\n * Plugin name\n */\n pluginName: z.string().describe('Name of the plugin'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds when event occurred'),\n});\n\n/**\n * Plugin Registered Event Schema\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"version\": \"1.0.0\"\n * }\n */\nexport const PluginRegisteredEventSchema = PluginEventBaseSchema.extend({\n /**\n * Plugin version (optional)\n */\n version: z.string().optional().describe('Plugin version'),\n});\n\nexport type PluginRegisteredEvent = z.infer;\n\n/**\n * Plugin Lifecycle Phase Event Schema\n * For init, start, destroy phases\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"duration\": 1250,\n * \"phase\": \"init\"\n * }\n */\nexport const PluginLifecyclePhaseEventSchema = PluginEventBaseSchema.extend({\n /**\n * Duration of the phase (milliseconds)\n */\n duration: z.number().min(0).optional().describe('Duration of the lifecycle phase in milliseconds'),\n \n /**\n * Lifecycle phase\n */\n phase: EventPhaseSchema.optional().describe('Lifecycle phase'),\n});\n\nexport type PluginLifecyclePhaseEvent = z.infer;\n\n/**\n * Plugin Error Event Schema\n * When a plugin encounters an error\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"error\": Error(\"Connection failed\"),\n * \"phase\": \"start\",\n * \"errorMessage\": \"Connection failed\",\n * \"errorStack\": \"Error: Connection failed\\n at ...\"\n * }\n */\nexport const PluginErrorEventSchema = PluginEventBaseSchema.extend({\n /**\n * Error object\n */\n error: z.object({\n name: z.string().describe('Error class name'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n code: z.string().optional().describe('Error code'),\n }).describe('Serializable error representation'),\n \n /**\n * Lifecycle phase where error occurred\n */\n phase: EventPhaseSchema.describe('Lifecycle phase where error occurred'),\n \n /**\n * Error message (for serialization)\n */\n errorMessage: z.string().optional().describe('Error message'),\n \n /**\n * Error stack trace (for debugging)\n */\n errorStack: z.string().optional().describe('Error stack trace'),\n});\n\nexport type PluginErrorEvent = z.infer;\n\n// ============================================================================\n// Service Event Schemas\n// ============================================================================\n\n/**\n * Service Registered Event Schema\n * \n * @example\n * {\n * \"serviceName\": \"database\",\n * \"timestamp\": 1706659200000,\n * \"serviceType\": \"IDataEngine\"\n * }\n */\nexport const ServiceRegisteredEventSchema = z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Name of the registered service'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Service type (optional)\n */\n serviceType: z.string().optional().describe('Type or interface name of the service'),\n});\n\nexport type ServiceRegisteredEvent = z.infer;\n\n/**\n * Service Unregistered Event Schema\n * \n * @example\n * {\n * \"serviceName\": \"database\",\n * \"timestamp\": 1706659200000\n * }\n */\nexport const ServiceUnregisteredEventSchema = z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Name of the unregistered service'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n});\n\nexport type ServiceUnregisteredEvent = z.infer;\n\n// ============================================================================\n// Hook Event Schemas\n// ============================================================================\n\n/**\n * Hook Registered Event Schema\n * \n * @example\n * {\n * \"hookName\": \"data.beforeInsert\",\n * \"timestamp\": 1706659200000,\n * \"handlerCount\": 3\n * }\n */\nexport const HookRegisteredEventSchema = z.object({\n /**\n * Hook name\n */\n hookName: z.string().describe('Name of the hook'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Number of handlers registered for this hook\n */\n handlerCount: z.number().int().min(0).describe('Number of handlers registered for this hook'),\n});\n\nexport type HookRegisteredEvent = z.infer;\n\n/**\n * Hook Triggered Event Schema\n * \n * @example\n * {\n * \"hookName\": \"data.beforeInsert\",\n * \"timestamp\": 1706659200000,\n * \"args\": [{ \"object\": \"customer\", \"data\": {...} }],\n * \"handlerCount\": 3\n * }\n */\nexport const HookTriggeredEventSchema = z.object({\n /**\n * Hook name\n */\n hookName: z.string().describe('Name of the hook'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Arguments passed to the hook\n */\n args: z.array(z.unknown()).describe('Arguments passed to the hook handlers'),\n \n /**\n * Number of handlers that will handle this event\n */\n handlerCount: z.number().int().min(0).optional().describe('Number of handlers that will handle this event'),\n});\n\nexport type HookTriggeredEvent = z.infer;\n\n// ============================================================================\n// Kernel Event Schemas\n// ============================================================================\n\n/**\n * Kernel Event Base Schema\n * Common fields for kernel events\n */\nexport const KernelEventBaseSchema = z.object({\n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n});\n\n/**\n * Kernel Ready Event Schema\n * \n * @example\n * {\n * \"timestamp\": 1706659200000,\n * \"duration\": 5400,\n * \"pluginCount\": 12\n * }\n */\nexport const KernelReadyEventSchema = KernelEventBaseSchema.extend({\n /**\n * Total initialization duration (milliseconds)\n */\n duration: z.number().min(0).optional().describe('Total initialization duration in milliseconds'),\n \n /**\n * Number of plugins initialized\n */\n pluginCount: z.number().int().min(0).optional().describe('Number of plugins initialized'),\n});\n\nexport type KernelReadyEvent = z.infer;\n\n/**\n * Kernel Shutdown Event Schema\n * \n * @example\n * {\n * \"timestamp\": 1706659200000,\n * \"reason\": \"SIGTERM received\"\n * }\n */\nexport const KernelShutdownEventSchema = KernelEventBaseSchema.extend({\n /**\n * Shutdown reason (optional)\n */\n reason: z.string().optional().describe('Reason for kernel shutdown'),\n});\n\nexport type KernelShutdownEvent = z.infer;\n\n// ============================================================================\n// Event Type Registry\n// ============================================================================\n\n/**\n * Plugin Lifecycle Event Type Enum\n * All possible plugin lifecycle event types\n */\nexport const PluginLifecycleEventType = z.enum([\n 'kernel:ready',\n 'kernel:shutdown',\n 'kernel:before-init',\n 'kernel:after-init',\n 'plugin:registered',\n 'plugin:before-init',\n 'plugin:init',\n 'plugin:after-init',\n 'plugin:before-start',\n 'plugin:started',\n 'plugin:after-start',\n 'plugin:before-destroy',\n 'plugin:destroyed',\n 'plugin:after-destroy',\n 'plugin:error',\n 'service:registered',\n 'service:unregistered',\n 'hook:registered',\n 'hook:triggered',\n]).describe('Plugin lifecycle event type');\n\nexport type PluginLifecycleEventType = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Runtime Management Protocol\n * \n * Defines the protocol for dynamic plugin loading, unloading, and discovery\n * at runtime. Addresses the \"Dynamic Loading\" gap in the microkernel architecture\n * by enabling plugins to be loaded and unloaded without restarting the kernel.\n * \n * Inspired by:\n * - OSGi Dynamic Module System (bundle lifecycle)\n * - Kubernetes Operator pattern (reconciliation loop)\n * - VS Code Extension Host (activation events)\n * \n * This protocol enables:\n * - Runtime load/unload of plugins without kernel restart\n * - Plugin discovery from registries and local filesystem\n * - Activation events (load plugin only when needed)\n * - Safe unload with dependency awareness\n */\n\n/**\n * Dynamic Plugin Operation Type\n * Operations that can be performed on plugins at runtime\n */\nexport const DynamicPluginOperationSchema = z.enum([\n 'load', // Load and initialize a plugin at runtime\n 'unload', // Gracefully unload a running plugin\n 'reload', // Unload then load (e.g., version upgrade)\n 'enable', // Enable a loaded but disabled plugin\n 'disable', // Disable a running plugin without unloading\n]).describe('Runtime plugin operation type');\n\n/**\n * Plugin Source\n * Where to resolve a plugin for dynamic loading\n */\nexport const PluginSourceSchema = z.object({\n /**\n * Source type\n */\n type: z.enum([\n 'npm', // npm registry package\n 'local', // Local filesystem path\n 'url', // Remote URL (tarball or module)\n 'registry', // ObjectStack plugin registry\n 'git', // Git repository\n ]).describe('Plugin source type'),\n \n /**\n * Source location (package name, path, URL, or git repo)\n */\n location: z.string().describe('Package name, file path, URL, or git repository'),\n \n /**\n * Version constraint (semver range)\n */\n version: z.string().optional().describe('Semver version range (e.g., \"^1.0.0\")'),\n \n /**\n * Integrity hash for verification\n */\n integrity: z.string().optional().describe('Subresource Integrity hash (e.g., \"sha384-...\")'),\n}).describe('Plugin source location for dynamic resolution');\n\n/**\n * Activation Event\n * Defines when a dynamically available plugin should be activated.\n * Plugins remain dormant until an activation event fires.\n */\nexport const ActivationEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'onCommand', // Activate when a specific command is executed\n 'onRoute', // Activate when a URL route is matched\n 'onObject', // Activate when a specific object type is accessed\n 'onEvent', // Activate when a system event fires\n 'onService', // Activate when a service is requested\n 'onSchedule', // Activate on a cron schedule\n 'onStartup', // Activate immediately on kernel startup\n ]).describe('Trigger type for lazy activation'),\n \n /**\n * Pattern to match (command name, route glob, object name, event pattern, etc.)\n */\n pattern: z.string().describe('Match pattern for the activation trigger'),\n}).describe('Lazy activation trigger for a dynamic plugin');\n\n/**\n * Dynamic Load Request\n * Request to load a plugin at runtime\n */\nexport const DynamicLoadRequestSchema = z.object({\n /**\n * Plugin identifier to load\n */\n pluginId: z.string().describe('Unique plugin identifier'),\n \n /**\n * Plugin source\n */\n source: PluginSourceSchema,\n \n /**\n * Activation events (if omitted, plugin activates immediately)\n */\n activationEvents: z.array(ActivationEventSchema).optional()\n .describe('Lazy activation triggers; if omitted plugin starts immediately'),\n \n /**\n * Configuration overrides for the plugin\n */\n config: z.record(z.string(), z.unknown()).optional()\n .describe('Runtime configuration overrides'),\n \n /**\n * Loading priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100)\n .describe('Loading priority (lower is higher)'),\n \n /**\n * Whether to enable sandboxing for this dynamically loaded plugin\n */\n sandbox: z.boolean().default(false)\n .describe('Run in an isolated sandbox'),\n \n /**\n * Timeout for the load operation in milliseconds\n */\n timeout: z.number().int().min(1000).default(60000)\n .describe('Maximum time to complete loading in ms'),\n}).describe('Request to dynamically load a plugin at runtime');\n\n/**\n * Dynamic Unload Request\n * Request to unload a plugin at runtime\n */\nexport const DynamicUnloadRequestSchema = z.object({\n /**\n * Plugin identifier to unload\n */\n pluginId: z.string().describe('Plugin to unload'),\n \n /**\n * Unload strategy\n */\n strategy: z.enum([\n 'graceful', // Wait for in-flight requests, then unload\n 'forceful', // Unload immediately, cancel pending work\n 'drain', // Stop accepting new work, finish existing, then unload\n ]).default('graceful').describe('How to handle in-flight work during unload'),\n \n /**\n * Timeout for the unload operation in milliseconds\n */\n timeout: z.number().int().min(1000).default(30000)\n .describe('Maximum time to complete unloading in ms'),\n \n /**\n * Whether to remove cached artifacts\n */\n cleanupCache: z.boolean().default(false)\n .describe('Remove cached code and assets after unload'),\n \n /**\n * Action for dependents: plugins that depend on this one\n */\n dependentAction: z.enum([\n 'cascade', // Also unload dependent plugins\n 'warn', // Warn about dependents but proceed\n 'block', // Block unload if dependents exist\n ]).default('block').describe('How to handle plugins that depend on this one'),\n}).describe('Request to dynamically unload a plugin at runtime');\n\n/**\n * Dynamic Plugin Operation Result\n * Result of a dynamic load/unload/reload operation\n */\nexport const DynamicPluginResultSchema = z.object({\n /**\n * Whether the operation succeeded\n */\n success: z.boolean(),\n \n /**\n * The operation that was performed\n */\n operation: DynamicPluginOperationSchema,\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Operation duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Resulting plugin version (for load/reload)\n */\n version: z.string().optional(),\n \n /**\n * Error details if operation failed\n */\n error: z.object({\n code: z.string().describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n details: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n \n /**\n * Warnings (e.g., dependents affected)\n */\n warnings: z.array(z.string()).optional(),\n}).describe('Result of a dynamic plugin operation');\n\n/**\n * Plugin Discovery Source\n * Defines where to discover available plugins at runtime\n */\nexport const PluginDiscoverySourceSchema = z.object({\n /**\n * Discovery source type\n */\n type: z.enum([\n 'registry', // ObjectStack plugin registry API\n 'npm', // npm registry search\n 'directory', // Local filesystem directory scan\n 'url', // Remote manifest URL\n ]).describe('Discovery source type'),\n \n /**\n * Source endpoint or path\n */\n endpoint: z.string().describe('Registry URL, directory path, or manifest URL'),\n \n /**\n * Polling interval in milliseconds (0 = manual only)\n */\n pollInterval: z.number().int().min(0).default(0)\n .describe('How often to re-scan for new plugins (0 = manual)'),\n \n /**\n * Filter criteria for discovered plugins\n */\n filter: z.object({\n /**\n * Only discover plugins matching these tags\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Only discover plugins from these vendors\n */\n vendors: z.array(z.string()).optional(),\n \n /**\n * Minimum trust level\n */\n minTrustLevel: z.enum(['verified', 'trusted', 'community', 'untrusted']).optional(),\n }).optional(),\n}).describe('Source for runtime plugin discovery');\n\n/**\n * Plugin Discovery Configuration\n * Controls how the kernel discovers available plugins at runtime\n */\nexport const PluginDiscoveryConfigSchema = z.object({\n /**\n * Enable runtime plugin discovery\n */\n enabled: z.boolean().default(false),\n \n /**\n * Discovery sources\n */\n sources: z.array(PluginDiscoverySourceSchema).default([]),\n \n /**\n * Auto-load discovered plugins matching criteria\n */\n autoLoad: z.boolean().default(false)\n .describe('Automatically load newly discovered plugins'),\n \n /**\n * Require approval before loading discovered plugins\n */\n requireApproval: z.boolean().default(true)\n .describe('Require admin approval before loading discovered plugins'),\n}).describe('Runtime plugin discovery configuration');\n\n/**\n * Dynamic Loading Configuration\n * Top-level configuration for the dynamic plugin loading subsystem\n */\nexport const DynamicLoadingConfigSchema = z.object({\n /**\n * Enable dynamic loading/unloading at runtime\n */\n enabled: z.boolean().default(false)\n .describe('Enable runtime load/unload of plugins'),\n \n /**\n * Maximum number of dynamically loaded plugins\n */\n maxDynamicPlugins: z.number().int().min(1).default(50)\n .describe('Upper limit on runtime-loaded plugins'),\n \n /**\n * Plugin discovery configuration\n */\n discovery: PluginDiscoveryConfigSchema.optional(),\n \n /**\n * Default sandbox policy for dynamically loaded plugins\n */\n defaultSandbox: z.boolean().default(true)\n .describe('Sandbox dynamically loaded plugins by default'),\n \n /**\n * Allowed plugin sources (empty = all allowed)\n */\n allowedSources: z.array(z.enum(['npm', 'local', 'url', 'registry', 'git'])).optional()\n .describe('Restrict which source types are permitted'),\n \n /**\n * Require integrity verification for remote plugins\n */\n requireIntegrity: z.boolean().default(true)\n .describe('Require integrity hash verification for remote sources'),\n \n /**\n * Global timeout for dynamic operations in milliseconds\n */\n operationTimeout: z.number().int().min(1000).default(60000)\n .describe('Default timeout for load/unload operations in ms'),\n}).describe('Dynamic plugin loading subsystem configuration');\n\n// Export types\nexport type DynamicPluginOperation = z.infer;\nexport type PluginSource = z.infer;\nexport type ActivationEvent = z.infer;\nexport type DynamicLoadRequest = z.infer;\nexport type DynamicUnloadRequest = z.infer;\nexport type DynamicPluginResult = z.infer;\nexport type PluginDiscoverySource = z.infer;\nexport type PluginDiscoveryConfig = z.infer;\nexport type DynamicLoadingConfig = z.infer;\n\n// Export input types for schemas with defaults\nexport type DynamicLoadRequestInput = z.input;\nexport type DynamicUnloadRequestInput = z.input;\nexport type DynamicLoadingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Security and Sandboxing Protocol\n * \n * Defines comprehensive security mechanisms for plugin isolation, permission\n * management, and threat protection in the ObjectStack ecosystem.\n * \n * Features:\n * - Fine-grained permission system\n * - Resource access control\n * - Sandboxing and isolation\n * - Security scanning and verification\n * - Runtime security monitoring\n */\n\n/**\n * Permission Scope\n * Defines the scope of a permission\n */\nexport const PermissionScopeSchema = z.enum([\n 'global', // Applies to entire system\n 'tenant', // Applies to specific tenant\n 'user', // Applies to specific user\n 'resource', // Applies to specific resource\n 'plugin', // Applies within plugin boundaries\n]).describe('Scope of permission application');\n\n/**\n * Permission Action\n * Standard CRUD + extended actions\n */\nexport const PermissionActionSchema = z.enum([\n 'create', // Create new resources\n 'read', // Read existing resources\n 'update', // Update existing resources\n 'delete', // Delete resources\n 'execute', // Execute operations/functions\n 'manage', // Full management rights\n 'configure', // Configuration changes\n 'share', // Share with others\n 'export', // Export data\n 'import', // Import data\n 'admin', // Administrative access\n]).describe('Type of action being permitted');\n\n/**\n * Resource Type\n * Types of resources that can be accessed\n */\nexport const ResourceTypeSchema = z.enum([\n 'data.object', // ObjectQL objects\n 'data.record', // Individual records\n 'data.field', // Specific fields\n 'ui.view', // UI views\n 'ui.dashboard', // Dashboards\n 'ui.report', // Reports\n 'system.config', // System configuration\n 'system.plugin', // Other plugins\n 'system.api', // API endpoints\n 'system.service', // System services\n 'storage.file', // File storage\n 'storage.database', // Database access\n 'network.http', // HTTP requests\n 'network.websocket', // WebSocket connections\n 'process.spawn', // Process spawning\n 'process.env', // Environment variables\n]).describe('Type of resource being accessed');\n\n/**\n * Permission Definition\n * Defines a single permission requirement\n */\nexport const PermissionSchema = z.object({\n /**\n * Permission identifier\n */\n id: z.string().describe('Unique permission identifier'),\n \n /**\n * Resource type\n */\n resource: ResourceTypeSchema,\n \n /**\n * Allowed actions\n */\n actions: z.array(PermissionActionSchema),\n \n /**\n * Permission scope\n */\n scope: PermissionScopeSchema.default('plugin'),\n \n /**\n * Resource filter\n */\n filter: z.object({\n /**\n * Specific resource IDs\n */\n resourceIds: z.array(z.string()).optional(),\n \n /**\n * Filter condition\n */\n condition: z.string().optional().describe('Filter expression (e.g., owner = currentUser)'),\n \n /**\n * Field-level access\n */\n fields: z.array(z.string()).optional().describe('Allowed fields for data resources'),\n }).optional(),\n \n /**\n * Human-readable description\n */\n description: z.string(),\n \n /**\n * Whether this permission is required or optional\n */\n required: z.boolean().default(true),\n \n /**\n * Justification for permission\n */\n justification: z.string().optional().describe('Why this permission is needed'),\n});\n\n/**\n * Permission Set\n * Collection of permissions for a plugin\n */\nexport const PermissionSetSchema = z.object({\n /**\n * All permissions required by plugin\n */\n permissions: z.array(PermissionSchema),\n \n /**\n * Permission groups for easier management\n */\n groups: z.array(z.object({\n name: z.string().describe('Group name'),\n description: z.string(),\n permissions: z.array(z.string()).describe('Permission IDs in this group'),\n })).optional(),\n \n /**\n * Default grant strategy\n */\n defaultGrant: z.enum([\n 'prompt', // Always prompt user\n 'allow', // Allow by default\n 'deny', // Deny by default\n 'inherit', // Inherit from parent\n ]).default('prompt'),\n});\n\n/**\n * Runtime Configuration\n * Defines the execution environment for plugin isolation\n */\nexport const RuntimeConfigSchema = z.object({\n /**\n * Runtime engine type\n */\n engine: z.enum([\n 'v8-isolate', // V8 isolate-based isolation (lightweight, fast)\n 'wasm', // WebAssembly-based isolation (secure, portable)\n 'container', // Container-based isolation (Docker, podman)\n 'process', // Process-based isolation (traditional)\n ]).default('v8-isolate')\n .describe('Execution environment engine'),\n \n /**\n * Engine-specific configuration\n */\n engineConfig: z.object({\n /**\n * WASM-specific settings (when engine is \"wasm\")\n */\n wasm: z.object({\n /**\n * Maximum memory pages (64KB per page)\n */\n maxMemoryPages: z.number().int().min(1).max(65536).optional()\n .describe('Maximum WASM memory pages (64KB each)'),\n \n /**\n * Instruction execution limit\n */\n instructionLimit: z.number().int().min(1).optional()\n .describe('Maximum instructions before timeout'),\n \n /**\n * Enable SIMD instructions\n */\n enableSimd: z.boolean().default(false)\n .describe('Enable WebAssembly SIMD support'),\n \n /**\n * Enable threads\n */\n enableThreads: z.boolean().default(false)\n .describe('Enable WebAssembly threads'),\n \n /**\n * Enable bulk memory operations\n */\n enableBulkMemory: z.boolean().default(true)\n .describe('Enable bulk memory operations'),\n }).optional(),\n \n /**\n * Container-specific settings (when engine is \"container\")\n */\n container: z.object({\n /**\n * Container image\n */\n image: z.string().optional()\n .describe('Container image to use'),\n \n /**\n * Container runtime\n */\n runtime: z.enum(['docker', 'podman', 'containerd']).default('docker'),\n \n /**\n * Resource limits\n */\n resources: z.object({\n cpuLimit: z.string().optional().describe('CPU limit (e.g., \"0.5\", \"2\")'),\n memoryLimit: z.string().optional().describe('Memory limit (e.g., \"512m\", \"1g\")'),\n }).optional(),\n \n /**\n * Network mode\n */\n networkMode: z.enum(['none', 'bridge', 'host']).default('bridge'),\n }).optional(),\n \n /**\n * V8 Isolate-specific settings (when engine is \"v8-isolate\")\n */\n v8Isolate: z.object({\n /**\n * Heap size limit in MB\n */\n heapSizeMb: z.number().int().min(1).optional(),\n \n /**\n * Enable snapshot\n */\n enableSnapshot: z.boolean().default(true),\n }).optional(),\n }).optional(),\n \n /**\n * General resource limits (applies to all engines)\n */\n resourceLimits: z.object({\n /**\n * Maximum memory in bytes\n */\n maxMemory: z.number().int().optional()\n .describe('Maximum memory allocation'),\n \n /**\n * Maximum CPU percentage\n */\n maxCpu: z.number().min(0).max(100).optional()\n .describe('Maximum CPU usage percentage'),\n \n /**\n * Execution timeout in milliseconds\n */\n timeout: z.number().int().min(0).optional()\n .describe('Maximum execution time'),\n }).optional(),\n});\n\n/**\n * Sandbox Configuration\n * Defines how plugin is isolated\n */\nexport const SandboxConfigSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(true),\n \n /**\n * Sandboxing level\n */\n level: z.enum([\n 'none', // No sandboxing\n 'minimal', // Basic isolation\n 'standard', // Standard sandboxing\n 'strict', // Strict isolation\n 'paranoid', // Maximum isolation\n ]).default('standard'),\n \n /**\n * Runtime environment configuration\n */\n runtime: RuntimeConfigSchema.optional()\n .describe('Execution environment and isolation settings'),\n \n /**\n * File system access\n */\n filesystem: z.object({\n mode: z.enum(['none', 'readonly', 'restricted', 'full']).default('restricted'),\n allowedPaths: z.array(z.string()).optional().describe('Whitelisted paths'),\n deniedPaths: z.array(z.string()).optional().describe('Blacklisted paths'),\n maxFileSize: z.number().int().optional().describe('Maximum file size in bytes'),\n }).optional(),\n \n /**\n * Network access\n */\n network: z.object({\n mode: z.enum(['none', 'local', 'restricted', 'full']).default('restricted'),\n allowedHosts: z.array(z.string()).optional().describe('Whitelisted hosts'),\n deniedHosts: z.array(z.string()).optional().describe('Blacklisted hosts'),\n allowedPorts: z.array(z.number()).optional().describe('Allowed port numbers'),\n maxConnections: z.number().int().optional(),\n }).optional(),\n \n /**\n * Process execution\n */\n process: z.object({\n allowSpawn: z.boolean().default(false).describe('Allow spawning child processes'),\n allowedCommands: z.array(z.string()).optional().describe('Whitelisted commands'),\n timeout: z.number().int().optional().describe('Process timeout in ms'),\n }).optional(),\n \n /**\n * Memory limits\n */\n memory: z.object({\n maxHeap: z.number().int().optional().describe('Maximum heap size in bytes'),\n maxStack: z.number().int().optional().describe('Maximum stack size in bytes'),\n }).optional(),\n \n /**\n * CPU limits\n */\n cpu: z.object({\n maxCpuPercent: z.number().min(0).max(100).optional(),\n maxThreads: z.number().int().optional(),\n }).optional(),\n \n /**\n * Environment variables\n */\n environment: z.object({\n mode: z.enum(['none', 'readonly', 'restricted', 'full']).default('readonly'),\n allowedVars: z.array(z.string()).optional(),\n deniedVars: z.array(z.string()).optional(),\n }).optional(),\n});\n\n/**\n * Security Vulnerability\n * Represents a known security vulnerability\n */\nexport const KernelSecurityVulnerabilitySchema = z.object({\n /**\n * CVE identifier\n */\n cve: z.string().optional(),\n \n /**\n * Vulnerability identifier\n */\n id: z.string(),\n \n /**\n * Severity level\n */\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),\n \n /**\n * Category (e.g., SAST, DAST, Dependency)\n */\n category: z.string().optional(),\n\n /**\n * Title\n */\n title: z.string(),\n \n /**\n * Location of the vulnerability\n */\n location: z.string().optional(),\n\n /**\n * Remediation steps\n */\n remediation: z.string().optional(),\n\n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Affected versions\n */\n affectedVersions: z.array(z.string()),\n \n /**\n * Fixed in versions\n */\n fixedIn: z.array(z.string()).optional(),\n \n /**\n * CVSS score\n */\n cvssScore: z.number().min(0).max(10).optional(),\n \n /**\n * Exploit availability\n */\n exploitAvailable: z.boolean().default(false),\n \n /**\n * Patch available\n */\n patchAvailable: z.boolean().default(false),\n \n /**\n * Workaround\n */\n workaround: z.string().optional(),\n \n /**\n * References\n */\n references: z.array(z.string()).optional(),\n \n /**\n * Discovered date\n */\n discoveredDate: z.string().datetime().optional(),\n \n /**\n * Published date\n */\n publishedDate: z.string().datetime().optional(),\n});\n\n/**\n * Security Scan Result\n * Result of security scanning\n */\nexport const KernelSecurityScanResultSchema = z.object({\n /**\n * Scan timestamp\n */\n timestamp: z.string().datetime(),\n \n /**\n * Scanner information\n */\n scanner: z.object({\n name: z.string(),\n version: z.string(),\n }),\n \n /**\n * Overall status\n */\n status: z.enum(['passed', 'failed', 'warning']),\n \n /**\n * Vulnerabilities found\n */\n vulnerabilities: z.array(KernelSecurityVulnerabilitySchema).optional(),\n \n /**\n * Code quality issues\n */\n codeIssues: z.array(z.object({\n severity: z.enum(['error', 'warning', 'info']),\n type: z.string().describe('Issue type (e.g., sql-injection, xss)'),\n file: z.string(),\n line: z.number().int().optional(),\n message: z.string(),\n suggestion: z.string().optional(),\n })).optional(),\n \n /**\n * Dependency vulnerabilities\n */\n dependencyVulnerabilities: z.array(z.object({\n package: z.string(),\n version: z.string(),\n vulnerability: KernelSecurityVulnerabilitySchema,\n })).optional(),\n \n /**\n * License compliance\n */\n licenseCompliance: z.object({\n status: z.enum(['compliant', 'non-compliant', 'unknown']),\n issues: z.array(z.object({\n package: z.string(),\n license: z.string(),\n reason: z.string(),\n })).optional(),\n }).optional(),\n \n /**\n * Summary statistics\n */\n summary: z.object({\n totalVulnerabilities: z.number().int(),\n criticalCount: z.number().int(),\n highCount: z.number().int(),\n mediumCount: z.number().int(),\n lowCount: z.number().int(),\n infoCount: z.number().int(),\n }),\n});\n\n/**\n * Security Policy\n * Defines security policies for plugin\n */\nexport const KernelSecurityPolicySchema = z.object({\n /**\n * Content Security Policy\n */\n csp: z.object({\n directives: z.record(z.string(), z.array(z.string())).optional(),\n reportOnly: z.boolean().default(false),\n }).optional(),\n \n /**\n * CORS policy\n */\n cors: z.object({\n allowedOrigins: z.array(z.string()),\n allowedMethods: z.array(z.string()),\n allowedHeaders: z.array(z.string()),\n allowCredentials: z.boolean().default(false),\n maxAge: z.number().int().optional(),\n }).optional(),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n enabled: z.boolean().default(true),\n maxRequests: z.number().int(),\n windowMs: z.number().int().describe('Time window in milliseconds'),\n strategy: z.enum(['fixed', 'sliding', 'token-bucket']).default('sliding'),\n }).optional(),\n \n /**\n * Authentication requirements\n */\n authentication: z.object({\n required: z.boolean().default(true),\n methods: z.array(z.enum(['jwt', 'oauth2', 'api-key', 'session', 'certificate'])),\n tokenExpiration: z.number().int().optional().describe('Token expiration in seconds'),\n }).optional(),\n \n /**\n * Encryption requirements\n */\n encryption: z.object({\n dataAtRest: z.boolean().default(false).describe('Encrypt data at rest'),\n dataInTransit: z.boolean().default(true).describe('Enforce HTTPS/TLS'),\n algorithm: z.string().optional().describe('Encryption algorithm'),\n minKeyLength: z.number().int().optional().describe('Minimum key length in bits'),\n }).optional(),\n \n /**\n * Audit logging\n */\n auditLog: z.object({\n enabled: z.boolean().default(true),\n events: z.array(z.string()).optional().describe('Events to log'),\n retention: z.number().int().optional().describe('Log retention in days'),\n }).optional(),\n});\n\n/**\n * Plugin Trust Level\n * Indicates trust level of plugin\n */\nexport const PluginTrustLevelSchema = z.enum([\n 'verified', // Official/verified plugin\n 'trusted', // Trusted third-party\n 'community', // Community plugin\n 'untrusted', // Unverified plugin\n 'blocked', // Blocked/malicious\n]).describe('Trust level of the plugin');\n\n/**\n * Plugin Security Manifest\n * Complete security information for plugin\n */\nexport const PluginSecurityManifestSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Trust level\n */\n trustLevel: PluginTrustLevelSchema,\n \n /**\n * Required permissions\n */\n permissions: PermissionSetSchema,\n \n /**\n * Sandbox configuration\n */\n sandbox: SandboxConfigSchema,\n \n /**\n * Security policy\n */\n policy: KernelSecurityPolicySchema.optional(),\n \n /**\n * Security scan results\n */\n scanResults: z.array(KernelSecurityScanResultSchema).optional(),\n \n /**\n * Known vulnerabilities\n */\n vulnerabilities: z.array(KernelSecurityVulnerabilitySchema).optional(),\n \n /**\n * Code signing\n */\n codeSigning: z.object({\n signed: z.boolean(),\n signature: z.string().optional(),\n certificate: z.string().optional(),\n algorithm: z.string().optional(),\n timestamp: z.string().datetime().optional(),\n }).optional(),\n \n /**\n * Security certifications\n */\n certifications: z.array(z.object({\n name: z.string().describe('Certification name (e.g., SOC 2, ISO 27001)'),\n issuer: z.string(),\n issuedDate: z.string().datetime(),\n expiryDate: z.string().datetime().optional(),\n certificateUrl: z.string().url().optional(),\n })).optional(),\n \n /**\n * Security contact\n */\n securityContact: z.object({\n email: z.string().email().optional(),\n url: z.string().url().optional(),\n pgpKey: z.string().optional(),\n }).optional(),\n \n /**\n * Vulnerability disclosure policy\n */\n vulnerabilityDisclosure: z.object({\n policyUrl: z.string().url().optional(),\n responseTime: z.number().int().optional().describe('Expected response time in hours'),\n bugBounty: z.boolean().default(false),\n }).optional(),\n});\n\n// Export types\nexport type PermissionScope = z.infer;\nexport type PermissionAction = z.infer;\nexport type ResourceType = z.infer;\nexport type Permission = z.infer;\nexport type PermissionSet = z.infer;\nexport type RuntimeConfig = z.infer;\nexport type SandboxConfig = z.infer;\nexport type KernelSecurityVulnerability = z.infer;\nexport type KernelSecurityScanResult = z.infer;\nexport type KernelSecurityPolicy = z.infer;\nexport type PluginTrustLevel = z.infer;\nexport type PluginSecurityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * ObjectStack Plugin Structure Standards (OPS)\n * \n * Formal Zod definitions for the Plugin Directory Structure and File Naming conventions.\n * This can be used by the CLI or IDE extensions to lint project structure.\n * \n * @see PLUGIN_STANDARDS.md\n */\n\n// REGEX: snake_case identifiers\nconst SNAKE_CASE_REGEX = /^[a-z][a-z0-9_]*$/;\n\n// REGEX: Standard File Suffixes\nconst OPS_FILE_SUFFIX_REGEX = /\\.(object|field|trigger|function|view|page|dashboard|flow|app|router|service)\\.ts$/;\n\n/**\n * Validates a single file path against OPS Naming Conventions.\n * \n * @example Valid Paths\n * - \"src/crm/lead.object.ts\"\n * - \"src/finance/invoice_payment.trigger.ts\"\n * - \"src/index.ts\"\n * \n * @example Invalid Paths\n * - \"src/CRM/LeadObject.ts\" (PascalCase)\n * - \"src/utils/helper.js\" (Wrong extension)\n */\nexport const OpsFilePathSchema = z.string().describe('Validates a file path against OPS naming conventions').superRefine((path, ctx) => {\n // 1. Must be in src/\n if (!path.startsWith('src/')) {\n // Non-source files (package.json, config) are ignored by this specific validator\n // or handled separately.\n return; \n }\n\n const parts = path.split('/');\n \n // 2. Validate Domain Directory (src/[domain])\n if (parts.length > 2) {\n const domainDir = parts[1];\n if (!SNAKE_CASE_REGEX.test(domainDir)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Domain directory '${domainDir}' must be lowercase snake_case`\n });\n }\n }\n\n // 3. Validate Filename suffix\n const filename = parts[parts.length - 1];\n \n // Skip index.ts and utility files if they don't match the specific resource pattern\n // But strict OPS encourages explicit suffixes for resources.\n if (filename === 'index.ts' || filename === 'main.ts') return;\n\n if (!SNAKE_CASE_REGEX.test(filename.split('.')[0])) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Filename '${filename}' base name must be lowercase snake_case`\n });\n }\n\n if (!OPS_FILE_SUFFIX_REGEX.test(filename)) {\n // We allow other files, but we warn or mark them as non-standard resources\n // For strict mode:\n // ctx.addIssue({\n // code: z.ZodIssueCode.custom,\n // message: `Filename '${filename}' does not end with a valid semantic suffix (.object.ts, .view.ts, etc.)`\n // });\n }\n});\n\n/**\n * Schema for a \"Scanned Module\" structure.\n * Represents the contents of a domain folder.\n */\nexport const OpsDomainModuleSchema = z.object({\n name: z.string().regex(SNAKE_CASE_REGEX).describe('Module name (snake_case)'),\n files: z.array(z.string()).describe('List of files in this module'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n}).describe('Scanned domain module representing a plugin folder').superRefine((module, ctx) => {\n // Rule: Must have an index.ts\n if (!module.files.includes('index.ts')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Module '${module.name}' is missing an 'index.ts' entry point.`\n });\n }\n});\n\n/**\n * Schema for a full Plugin Project Layout\n */\nexport const OpsPluginStructureSchema = z.object({\n root: z.string().describe('Root directory path of the plugin project'),\n files: z.array(z.string()).describe('List of all file paths relative to root'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n}).describe('Full plugin project layout validated against OPS conventions').superRefine((project, ctx) => {\n // Check for configuration file\n if (!project.files.includes('objectstack.config.ts')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"Missing 'objectstack.config.ts' configuration file.\"\n });\n }\n \n // Validate each source file individually\n project.files.filter(f => f.startsWith('src/')).forEach(file => {\n const result = OpsFilePathSchema.safeParse(file);\n if (!result.success) {\n result.error.issues.forEach(issue => {\n ctx.addIssue({ ...issue, path: [file] });\n })\n }\n });\n});\n\nexport type OpsFilePath = z.infer;\nexport type OpsDomainModule = z.infer;\nexport type OpsPluginStructure = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Plugin Validator Protocol\n * \n * Zod schemas for plugin validation data structures.\n * These schemas align with the IPluginValidator contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Validation Result Schemas\n// ============================================================================\n\n/**\n * Validation Error Schema\n * Represents a single validation error\n * \n * @example\n * {\n * \"field\": \"version\",\n * \"message\": \"Invalid semver format\",\n * \"code\": \"INVALID_VERSION\"\n * }\n */\nexport const ValidationErrorSchema = z.object({\n /**\n * Field that failed validation\n */\n field: z.string().describe('Field name that failed validation'),\n \n /**\n * Human-readable error message\n */\n message: z.string().describe('Human-readable error message'),\n \n /**\n * Machine-readable error code (optional)\n */\n code: z.string().optional().describe('Machine-readable error code'),\n});\n\nexport type ValidationError = z.infer;\n\n/**\n * Validation Warning Schema\n * Represents a non-fatal validation warning\n * \n * @example\n * {\n * \"field\": \"description\",\n * \"message\": \"Description is empty\",\n * \"code\": \"MISSING_DESCRIPTION\"\n * }\n */\nexport const ValidationWarningSchema = z.object({\n /**\n * Field with warning\n */\n field: z.string().describe('Field name with warning'),\n \n /**\n * Human-readable warning message\n */\n message: z.string().describe('Human-readable warning message'),\n \n /**\n * Machine-readable warning code (optional)\n */\n code: z.string().optional().describe('Machine-readable warning code'),\n});\n\nexport type ValidationWarning = z.infer;\n\n/**\n * Validation Result Schema\n * Result of plugin validation operation\n * \n * @example\n * {\n * \"valid\": false,\n * \"errors\": [{\n * \"field\": \"name\",\n * \"message\": \"Plugin name is required\",\n * \"code\": \"REQUIRED_FIELD\"\n * }],\n * \"warnings\": [{\n * \"field\": \"description\",\n * \"message\": \"Description is recommended\",\n * \"code\": \"MISSING_DESCRIPTION\"\n * }]\n * }\n */\nexport const ValidationResultSchema = z.object({\n /**\n * Whether validation passed\n */\n valid: z.boolean().describe('Whether the plugin passed validation'),\n \n /**\n * Validation errors (if any)\n */\n errors: z.array(ValidationErrorSchema).optional().describe('Validation errors'),\n \n /**\n * Validation warnings (non-fatal issues)\n */\n warnings: z.array(ValidationWarningSchema).optional().describe('Validation warnings'),\n});\n\nexport type ValidationResult = z.infer;\n\n// ============================================================================\n// Plugin Metadata Schema\n// ============================================================================\n\n/**\n * Plugin Schema\n * Metadata structure for a plugin\n * \n * This aligns with and extends the existing PluginSchema from plugin.zod.ts\n * \n * @example\n * {\n * \"name\": \"crm-plugin\",\n * \"version\": \"1.0.0\",\n * \"dependencies\": [\"core-plugin\"]\n * }\n */\nexport const PluginMetadataSchema = z.object({\n /**\n * Unique plugin identifier (snake_case)\n */\n name: z.string().min(1).describe('Unique plugin identifier'),\n \n /**\n * Plugin version (semver)\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic version (e.g., 1.0.0)'),\n \n /**\n * Plugin dependencies (array of plugin names)\n */\n dependencies: z.array(z.string()).optional().describe('Array of plugin names this plugin depends on'),\n \n /**\n * Plugin signature for cryptographic verification (optional)\n */\n signature: z.string().optional().describe('Cryptographic signature for plugin verification'),\n \n /**\n * Additional plugin metadata\n */\n}).passthrough().describe('Plugin metadata for validation');\n\nexport type PluginMetadata = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Versioning and Compatibility Protocol\n * \n * Defines comprehensive versioning, compatibility checking, and dependency\n * resolution mechanisms for the plugin ecosystem.\n * \n * Based on semantic versioning (SemVer) with extensions for:\n * - Compatibility matrices\n * - Breaking change detection\n * - Migration paths\n * - Multi-version support\n */\n\n/**\n * Semantic Version Schema\n * Standard SemVer format with optional pre-release and build metadata\n */\nexport const SemanticVersionSchema = z.object({\n major: z.number().int().min(0).describe('Major version (breaking changes)'),\n minor: z.number().int().min(0).describe('Minor version (backward compatible features)'),\n patch: z.number().int().min(0).describe('Patch version (backward compatible fixes)'),\n preRelease: z.string().optional().describe('Pre-release identifier (alpha, beta, rc.1)'),\n build: z.string().optional().describe('Build metadata'),\n}).describe('Semantic version number');\n\n/**\n * Version Constraint Schema\n * Defines version requirements using SemVer ranges\n */\nexport const VersionConstraintSchema = z.union([\n z.string().regex(/^[\\d.]+$/).describe('Exact version: `1.2.3`'),\n z.string().regex(/^\\^[\\d.]+$/).describe('Compatible with: `^1.2.3` (`>=1.2.3 <2.0.0`)'),\n z.string().regex(/^~[\\d.]+$/).describe('Approximately: `~1.2.3` (`>=1.2.3 <1.3.0`)'),\n z.string().regex(/^>=[\\d.]+$/).describe('Greater than or equal: `>=1.2.3`'),\n z.string().regex(/^>[\\d.]+$/).describe('Greater than: `>1.2.3`'),\n z.string().regex(/^<=[\\d.]+$/).describe('Less than or equal: `<=1.2.3`'),\n z.string().regex(/^<[\\d.]+$/).describe('Less than: `<1.2.3`'),\n z.string().regex(/^[\\d.]+ - [\\d.]+$/).describe('Range: `1.2.3 - 2.3.4`'),\n z.literal('*').describe('Any version'),\n z.literal('latest').describe('Latest stable version'),\n]);\n\n/**\n * Compatibility Level\n * Describes the level of compatibility between versions\n */\nexport const CompatibilityLevelSchema = z.enum([\n 'fully-compatible', // 100% compatible, drop-in replacement\n 'backward-compatible', // Backward compatible, new features added\n 'deprecated-compatible', // Compatible but uses deprecated features\n 'breaking-changes', // Breaking changes, migration required\n 'incompatible', // Completely incompatible\n]).describe('Compatibility level between versions');\n\n/**\n * Breaking Change\n * Documents a breaking change in a version\n */\nexport const BreakingChangeSchema = z.object({\n /**\n * Version where the change was introduced\n */\n introducedIn: z.string().describe('Version that introduced this breaking change'),\n \n /**\n * Type of breaking change\n */\n type: z.enum([\n 'api-removed', // API removed\n 'api-renamed', // API renamed\n 'api-signature-changed', // Function signature changed\n 'behavior-changed', // Behavior changed\n 'dependency-changed', // Dependency requirement changed\n 'configuration-changed', // Configuration schema changed\n 'protocol-changed', // Protocol implementation changed\n ]),\n \n /**\n * What was changed\n */\n description: z.string(),\n \n /**\n * Migration guide\n */\n migrationGuide: z.string().optional().describe('How to migrate from old to new'),\n \n /**\n * Deprecated in version\n */\n deprecatedIn: z.string().optional().describe('Version where old API was deprecated'),\n \n /**\n * Will be removed in version\n */\n removedIn: z.string().optional().describe('Version where old API will be removed'),\n \n /**\n * Automated migration available\n */\n automatedMigration: z.boolean().default(false)\n .describe('Whether automated migration tool is available'),\n \n /**\n * Impact severity\n */\n severity: z.enum(['critical', 'major', 'minor']).describe('Impact severity'),\n});\n\n/**\n * Deprecation Notice\n * Information about deprecated features\n */\nexport const DeprecationNoticeSchema = z.object({\n /**\n * Feature or API being deprecated\n */\n feature: z.string().describe('Deprecated feature identifier'),\n \n /**\n * Version when deprecated\n */\n deprecatedIn: z.string(),\n \n /**\n * Planned removal version\n */\n removeIn: z.string().optional(),\n \n /**\n * Reason for deprecation\n */\n reason: z.string(),\n \n /**\n * Recommended alternative\n */\n alternative: z.string().optional().describe('What to use instead'),\n \n /**\n * Migration path\n */\n migrationPath: z.string().optional().describe('How to migrate to alternative'),\n});\n\n/**\n * Compatibility Matrix Entry\n * Maps compatibility between different plugin versions\n */\nexport const CompatibilityMatrixEntrySchema = z.object({\n /**\n * Source version\n */\n from: z.string().describe('Version being upgraded from'),\n \n /**\n * Target version\n */\n to: z.string().describe('Version being upgraded to'),\n \n /**\n * Compatibility level\n */\n compatibility: CompatibilityLevelSchema,\n \n /**\n * Breaking changes list\n */\n breakingChanges: z.array(BreakingChangeSchema).optional(),\n \n /**\n * Migration required\n */\n migrationRequired: z.boolean().default(false),\n \n /**\n * Migration complexity\n */\n migrationComplexity: z.enum(['trivial', 'simple', 'moderate', 'complex', 'major']).optional(),\n \n /**\n * Estimated migration time in hours\n */\n estimatedMigrationTime: z.number().optional(),\n \n /**\n * Migration script available\n */\n migrationScript: z.string().optional().describe('Path to migration script'),\n \n /**\n * Test coverage for migration\n */\n testCoverage: z.number().min(0).max(100).optional()\n .describe('Percentage of migration covered by tests'),\n});\n\n/**\n * Plugin Compatibility Matrix\n * Complete compatibility information for a plugin\n */\nexport const PluginCompatibilityMatrixSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current version\n */\n currentVersion: z.string(),\n \n /**\n * Compatibility entries\n */\n compatibilityMatrix: z.array(CompatibilityMatrixEntrySchema),\n \n /**\n * Supported versions\n */\n supportedVersions: z.array(z.object({\n version: z.string(),\n supported: z.boolean(),\n endOfLife: z.string().datetime().optional().describe('End of support date'),\n securitySupport: z.boolean().default(false).describe('Still receives security updates'),\n })),\n \n /**\n * Minimum compatible version\n */\n minimumCompatibleVersion: z.string().optional()\n .describe('Oldest version that can be directly upgraded'),\n});\n\n/**\n * Dependency Conflict\n * Represents a conflict in plugin dependencies at the kernel level.\n * Models plugin-to-plugin dependency conflicts with typed conflict categories.\n * \n * @see hub/plugin-security.zod.ts DependencyConflictSchema for hub-level package version conflicts\n * which focuses on marketplace registry resolution.\n */\nexport const DependencyConflictSchema = z.object({\n /**\n * Type of conflict\n */\n type: z.enum([\n 'version-mismatch', // Different versions required\n 'missing-dependency', // Required dependency not found\n 'circular-dependency', // Circular dependency detected\n 'incompatible-versions', // Incompatible versions required by different plugins\n 'conflicting-interfaces', // Plugins implement conflicting interfaces\n ]),\n \n /**\n * Plugins involved in conflict\n */\n plugins: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n requirement: z.string().optional().describe('What this plugin requires'),\n })),\n \n /**\n * Conflict description\n */\n description: z.string(),\n \n /**\n * Possible resolutions\n */\n resolutions: z.array(z.object({\n strategy: z.enum([\n 'upgrade', // Upgrade one or more plugins\n 'downgrade', // Downgrade one or more plugins\n 'replace', // Replace with alternative plugin\n 'disable', // Disable conflicting plugin\n 'manual', // Manual intervention required\n ]),\n description: z.string(),\n automaticResolution: z.boolean().default(false),\n riskLevel: z.enum(['low', 'medium', 'high']),\n })).optional(),\n \n /**\n * Severity of conflict\n */\n severity: z.enum(['critical', 'error', 'warning', 'info']),\n});\n\n/**\n * Dependency Resolution Result\n * Result of dependency resolution process\n */\nexport const PluginDependencyResolutionResultSchema = z.object({\n /**\n * Resolution successful\n */\n success: z.boolean(),\n \n /**\n * Resolved plugin versions\n */\n resolved: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n resolvedVersion: z.string(),\n })).optional(),\n \n /**\n * Conflicts found\n */\n conflicts: z.array(DependencyConflictSchema).optional(),\n \n /**\n * Warnings\n */\n warnings: z.array(z.string()).optional(),\n \n /**\n * Installation order (topologically sorted)\n */\n installationOrder: z.array(z.string()).optional()\n .describe('Plugin IDs in order they should be installed'),\n \n /**\n * Dependency graph\n */\n dependencyGraph: z.record(z.string(), z.array(z.string())).optional()\n .describe('Map of plugin ID to its dependencies'),\n});\n\n/**\n * Multi-Version Support Configuration\n * Allows running multiple versions of a plugin simultaneously\n */\nexport const MultiVersionSupportSchema = z.object({\n /**\n * Enable multi-version support\n */\n enabled: z.boolean().default(false),\n \n /**\n * Maximum concurrent versions\n */\n maxConcurrentVersions: z.number().int().min(1).default(2)\n .describe('How many versions can run at the same time'),\n \n /**\n * Version selection strategy\n */\n selectionStrategy: z.enum([\n 'latest', // Always use latest version\n 'stable', // Use latest stable version\n 'compatible', // Use version compatible with dependencies\n 'pinned', // Use pinned version\n 'canary', // Use canary/preview version\n 'custom', // Custom selection logic\n ]).default('latest'),\n \n /**\n * Version routing rules\n */\n routing: z.array(z.object({\n condition: z.string().describe('Routing condition (e.g., tenant, user, feature flag)'),\n version: z.string().describe('Version to use when condition matches'),\n priority: z.number().int().default(100).describe('Rule priority'),\n })).optional(),\n \n /**\n * Gradual rollout configuration\n */\n rollout: z.object({\n enabled: z.boolean().default(false),\n strategy: z.enum(['percentage', 'blue-green', 'canary']),\n percentage: z.number().min(0).max(100).optional()\n .describe('Percentage of traffic to new version'),\n duration: z.number().int().optional()\n .describe('Rollout duration in milliseconds'),\n }).optional(),\n});\n\n/**\n * Plugin Version Metadata\n * Complete version information for a plugin\n */\nexport const PluginVersionMetadataSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Version number\n */\n version: SemanticVersionSchema,\n \n /**\n * Version string (computed)\n */\n versionString: z.string().describe('Full version string (e.g., 1.2.3-beta.1+build.123)'),\n \n /**\n * Release date\n */\n releaseDate: z.string().datetime(),\n \n /**\n * Release notes\n */\n releaseNotes: z.string().optional(),\n \n /**\n * Breaking changes\n */\n breakingChanges: z.array(BreakingChangeSchema).optional(),\n \n /**\n * Deprecations\n */\n deprecations: z.array(DeprecationNoticeSchema).optional(),\n \n /**\n * Compatibility matrix\n */\n compatibilityMatrix: z.array(CompatibilityMatrixEntrySchema).optional(),\n \n /**\n * Security vulnerabilities fixed\n */\n securityFixes: z.array(z.object({\n cve: z.string().optional().describe('CVE identifier'),\n severity: z.enum(['critical', 'high', 'medium', 'low']),\n description: z.string(),\n fixedIn: z.string().describe('Version where vulnerability was fixed'),\n })).optional(),\n \n /**\n * Download statistics\n */\n statistics: z.object({\n downloads: z.number().int().min(0).optional(),\n installations: z.number().int().min(0).optional(),\n ratings: z.number().min(0).max(5).optional(),\n }).optional(),\n \n /**\n * Support status\n */\n support: z.object({\n status: z.enum(['active', 'maintenance', 'deprecated', 'eol']),\n endOfLife: z.string().datetime().optional(),\n securitySupport: z.boolean().default(true),\n }),\n});\n\n// Export types\nexport type SemanticVersion = z.infer;\nexport type VersionConstraint = z.infer;\nexport type CompatibilityLevel = z.infer;\nexport type BreakingChange = z.infer;\nexport type DeprecationNotice = z.infer;\nexport type CompatibilityMatrixEntry = z.infer;\nexport type PluginCompatibilityMatrix = z.infer;\nexport type DependencyConflict = z.infer;\nexport type PluginDependencyResolutionResult = z.infer;\nexport type MultiVersionSupport = z.infer;\nexport type PluginVersionMetadata = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Service Registry Protocol\n * \n * Zod schemas for service registry data structures.\n * These schemas align with the IServiceRegistry contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n * \n * Note: IServiceRegistry itself is a runtime interface (methods only),\n * so it correctly remains a TypeScript interface. This file contains\n * schemas for configuration and metadata related to service registry.\n */\n\n// ============================================================================\n// Service Metadata Schemas\n// ============================================================================\n\n/**\n * Service Scope Type Enum\n * Different service scoping strategies\n */\nexport const ServiceScopeType = z.enum([\n 'singleton', // Single instance shared across the application\n 'transient', // New instance created each time\n 'scoped', // Instance per scope (request, session, transaction, etc.)\n]).describe('Service scope type');\n\nexport type ServiceScopeType = z.infer;\n\n/**\n * Service Metadata Schema\n * Metadata about a registered service\n * \n * @example\n * {\n * \"name\": \"database\",\n * \"scope\": \"singleton\",\n * \"type\": \"IDataEngine\",\n * \"registeredAt\": 1706659200000\n * }\n */\nexport const ServiceMetadataSchema = z.object({\n /**\n * Service name (unique identifier)\n */\n name: z.string().min(1).describe('Unique service name identifier'),\n \n /**\n * Service scope type\n */\n scope: ServiceScopeType.optional().default('singleton')\n .describe('Service scope type'),\n \n /**\n * Service type or interface name (optional)\n */\n type: z.string().optional().describe('Service type or interface name'),\n \n /**\n * Registration timestamp (Unix milliseconds)\n */\n registeredAt: z.number().int().optional()\n .describe('Unix timestamp in milliseconds when service was registered'),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Additional service-specific metadata'),\n});\n\nexport type ServiceMetadata = z.infer;\n\n// ============================================================================\n// Service Registry Configuration Schemas\n// ============================================================================\n\n/**\n * Service Registry Configuration Schema\n * Configuration for service registry behavior\n * \n * @example\n * {\n * \"strictMode\": true,\n * \"allowOverwrite\": false,\n * \"enableLogging\": true,\n * \"scopeTypes\": [\"singleton\", \"transient\", \"request\", \"session\"]\n * }\n */\nexport const ServiceRegistryConfigSchema = z.object({\n /**\n * Strict mode: throw errors on invalid operations\n * @default true\n */\n strictMode: z.boolean().optional().default(true)\n .describe('Throw errors on invalid operations (duplicate registration, service not found, etc.)'),\n \n /**\n * Allow overwriting existing services\n * @default false\n */\n allowOverwrite: z.boolean().optional().default(false)\n .describe('Allow overwriting existing service registrations'),\n \n /**\n * Enable logging for service operations\n * @default false\n */\n enableLogging: z.boolean().optional().default(false)\n .describe('Enable logging for service registration and retrieval'),\n \n /**\n * Custom scope types (beyond singleton, transient, scoped)\n * @default ['singleton', 'transient', 'scoped']\n */\n scopeTypes: z.array(z.string()).optional()\n .describe('Supported scope types'),\n \n /**\n * Maximum number of services (prevent memory leaks)\n */\n maxServices: z.number().int().min(1).optional()\n .describe('Maximum number of services that can be registered'),\n});\n\nexport type ServiceRegistryConfig = z.infer;\nexport type ServiceRegistryConfigInput = z.input;\n\n// ============================================================================\n// Service Factory Schemas\n// ============================================================================\n\n/**\n * Service Factory Registration Schema\n * Configuration for registering a service factory\n * \n * @example\n * {\n * \"name\": \"logger\",\n * \"scope\": \"singleton\",\n * \"factoryType\": \"sync\"\n * }\n */\nexport const ServiceFactoryRegistrationSchema = z.object({\n /**\n * Service name (unique identifier)\n */\n name: z.string().min(1).describe('Unique service name identifier'),\n \n /**\n * Service scope type\n */\n scope: ServiceScopeType.optional().default('singleton')\n .describe('Service scope type'),\n \n /**\n * Factory type (sync or async)\n */\n factoryType: z.enum(['sync', 'async']).optional().default('sync')\n .describe('Whether factory is synchronous or asynchronous'),\n \n /**\n * Whether this is a singleton (cache factory result)\n */\n singleton: z.boolean().optional().default(true)\n .describe('Whether to cache the factory result (singleton pattern)'),\n});\n\nexport type ServiceFactoryRegistration = z.infer;\n\n// ============================================================================\n// Scoped Service Schemas\n// ============================================================================\n\n/**\n * Scope Configuration Schema\n * Configuration for creating a new scope\n * \n * @example\n * {\n * \"scopeType\": \"request\",\n * \"scopeId\": \"req-12345\",\n * \"metadata\": {\n * \"userId\": \"user-123\",\n * \"requestId\": \"req-12345\"\n * }\n * }\n */\nexport const ScopeConfigSchema = z.object({\n /**\n * Type of scope (request, session, transaction, etc.)\n */\n scopeType: z.string().describe('Type of scope'),\n \n /**\n * Scope identifier (optional, auto-generated if not provided)\n */\n scopeId: z.string().optional().describe('Unique scope identifier'),\n \n /**\n * Scope metadata (context information)\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Scope-specific context metadata'),\n});\n\nexport type ScopeConfig = z.infer;\n\n/**\n * Scope Info Schema\n * Information about an active scope\n * \n * @example\n * {\n * \"scopeId\": \"req-12345\",\n * \"scopeType\": \"request\",\n * \"createdAt\": 1706659200000,\n * \"serviceCount\": 5,\n * \"metadata\": {\n * \"userId\": \"user-123\"\n * }\n * }\n */\nexport const ScopeInfoSchema = z.object({\n /**\n * Scope identifier\n */\n scopeId: z.string().describe('Unique scope identifier'),\n \n /**\n * Type of scope\n */\n scopeType: z.string().describe('Type of scope'),\n \n /**\n * Creation timestamp (Unix milliseconds)\n */\n createdAt: z.number().int().describe('Unix timestamp in milliseconds when scope was created'),\n \n /**\n * Number of services in this scope\n */\n serviceCount: z.number().int().min(0).optional()\n .describe('Number of services registered in this scope'),\n \n /**\n * Scope metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Scope-specific context metadata'),\n});\n\nexport type ScopeInfo = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Startup Orchestrator Protocol\n * \n * Zod schemas for plugin startup orchestration data structures.\n * These schemas align with the IStartupOrchestrator contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Startup Configuration Schemas\n// ============================================================================\n\n/**\n * Startup Options Schema\n * Configuration for plugin startup orchestration\n * \n * @example\n * {\n * \"timeout\": 30000,\n * \"rollbackOnFailure\": true,\n * \"healthCheck\": false,\n * \"parallel\": false\n * }\n */\nexport const StartupOptionsSchema = z.object({\n /**\n * Maximum time (ms) to wait for each plugin to start\n * @default 30000 (30 seconds)\n */\n timeout: z.number().int().min(0).optional().default(30000)\n .describe('Maximum time in milliseconds to wait for each plugin to start'),\n \n /**\n * Whether to rollback (destroy) already-started plugins on failure\n * @default true\n */\n rollbackOnFailure: z.boolean().optional().default(true)\n .describe('Whether to rollback already-started plugins if any plugin fails'),\n \n /**\n * Whether to run health checks after startup\n * @default false\n */\n healthCheck: z.boolean().optional().default(false)\n .describe('Whether to run health checks after plugin startup'),\n \n /**\n * Whether to run plugins in parallel (if dependencies allow)\n * @default false (sequential startup)\n */\n parallel: z.boolean().optional().default(false)\n .describe('Whether to start plugins in parallel when dependencies allow'),\n \n /**\n * Custom context to pass to plugin lifecycle methods\n */\n context: z.unknown().optional().describe('Custom context object to pass to plugin lifecycle methods'),\n});\n\nexport type StartupOptions = z.infer;\nexport type StartupOptionsInput = z.input;\n\n// ============================================================================\n// Health Status Schemas\n// ============================================================================\n\n/**\n * Health Status Schema\n * Health status for a plugin\n * \n * @example\n * {\n * \"healthy\": true,\n * \"timestamp\": 1706659200000,\n * \"details\": {\n * \"databaseConnected\": true,\n * \"memoryUsage\": 45.2\n * }\n * }\n */\nexport const HealthStatusSchema = z.object({\n /**\n * Whether the plugin is healthy\n */\n healthy: z.boolean().describe('Whether the plugin is healthy'),\n \n /**\n * Health check timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds when health check was performed'),\n \n /**\n * Optional health details (plugin-specific)\n */\n details: z.record(z.string(), z.unknown()).optional().describe('Optional plugin-specific health details'),\n \n /**\n * Optional error message if unhealthy\n */\n message: z.string().optional().describe('Error message if plugin is unhealthy'),\n});\n\nexport type HealthStatus = z.infer;\n\n// ============================================================================\n// Startup Result Schemas\n// ============================================================================\n\n/**\n * Plugin Startup Result Schema\n * Result of a single plugin startup operation\n * \n * @example\n * {\n * \"plugin\": { \"name\": \"crm-plugin\", \"version\": \"1.0.0\" },\n * \"success\": true,\n * \"duration\": 1250,\n * \"health\": {\n * \"healthy\": true,\n * \"timestamp\": 1706659200000\n * }\n * }\n */\nexport const PluginStartupResultSchema = z.object({\n /**\n * Plugin that was started\n */\n plugin: z.object({\n name: z.string(),\n version: z.string().optional(),\n }).passthrough().describe('Plugin metadata'),\n \n /**\n * Whether startup was successful\n */\n success: z.boolean().describe('Whether the plugin started successfully'),\n \n /**\n * Time taken to start (milliseconds)\n */\n duration: z.number().min(0).describe('Time taken to start the plugin in milliseconds'),\n \n /**\n * Error if startup failed\n */\n error: z.object({\n name: z.string().describe('Error class name'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n code: z.string().optional().describe('Error code'),\n }).optional().describe('Serializable error representation if startup failed'),\n \n /**\n * Health status after startup (if healthCheck enabled)\n */\n health: HealthStatusSchema.optional().describe('Health status after startup if health check was enabled'),\n});\n\nexport type PluginStartupResult = z.infer;\n\n// ============================================================================\n// Startup Orchestration Result Schema\n// ============================================================================\n\n/**\n * Startup Orchestration Result Schema\n * Overall result of orchestrating startup for multiple plugins\n * \n * @example\n * {\n * \"results\": [\n * { \"plugin\": { \"name\": \"plugin1\" }, \"success\": true, \"duration\": 1200 },\n * { \"plugin\": { \"name\": \"plugin2\" }, \"success\": true, \"duration\": 850 }\n * ],\n * \"totalDuration\": 2050,\n * \"allSuccessful\": true\n * }\n */\nexport const StartupOrchestrationResultSchema = z.object({\n /**\n * Individual plugin startup results\n */\n results: z.array(PluginStartupResultSchema).describe('Startup results for each plugin'),\n \n /**\n * Total time taken for all plugins (milliseconds)\n */\n totalDuration: z.number().min(0).describe('Total time taken for all plugins in milliseconds'),\n \n /**\n * Whether all plugins started successfully\n */\n allSuccessful: z.boolean().describe('Whether all plugins started successfully'),\n \n /**\n * Plugins that were rolled back (if rollbackOnFailure was enabled)\n */\n rolledBack: z.array(z.string()).optional().describe('Names of plugins that were rolled back'),\n});\n\nexport type StartupOrchestrationResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\n\n/**\n * # Plugin Registry Protocol\n * \n * Defines the schema for the plugin discovery and registry system.\n * This enables plugins from different vendors to be discovered, validated,\n * and composed together in the ObjectStack ecosystem.\n */\n\n/**\n * Plugin Vendor Information\n */\nexport const PluginVendorSchema = z.object({\n /**\n * Vendor identifier (reverse domain notation)\n * Example: \"com.acme\", \"org.apache\", \"com.objectstack\"\n */\n id: z.string()\n .regex(/^[a-z][a-z0-9]*(\\.[a-z][a-z0-9]*)+$/)\n .describe('Vendor identifier (reverse domain)'),\n \n /**\n * Vendor display name\n */\n name: z.string(),\n \n /**\n * Vendor website\n */\n website: z.string().url().optional(),\n \n /**\n * Contact email\n */\n email: z.string().email().optional(),\n \n /**\n * Verification status\n */\n verified: z.boolean().default(false).describe('Whether vendor is verified by ObjectStack'),\n \n /**\n * Trust level\n */\n trustLevel: z.enum(['official', 'verified', 'community', 'unverified']).default('unverified'),\n});\n\n/**\n * Plugin Quality Metrics\n */\nexport const PluginQualityMetricsSchema = z.object({\n /**\n * Test coverage percentage\n */\n testCoverage: z.number().min(0).max(100).optional(),\n \n /**\n * Documentation score (0-100)\n */\n documentationScore: z.number().min(0).max(100).optional(),\n \n /**\n * Code quality score (0-100)\n */\n codeQuality: z.number().min(0).max(100).optional(),\n \n /**\n * Security scan status\n */\n securityScan: z.object({\n lastScanDate: z.string().datetime().optional(),\n vulnerabilities: z.object({\n critical: z.number().int().min(0).default(0),\n high: z.number().int().min(0).default(0),\n medium: z.number().int().min(0).default(0),\n low: z.number().int().min(0).default(0),\n }).optional(),\n passed: z.boolean().default(false),\n }).optional(),\n \n /**\n * Conformance test results\n */\n conformanceTests: z.array(z.object({\n protocolId: z.string().describe('Protocol being tested'),\n passed: z.boolean(),\n totalTests: z.number().int().min(0),\n passedTests: z.number().int().min(0),\n lastRunDate: z.string().datetime().optional(),\n })).optional(),\n});\n\n/**\n * Plugin Usage Statistics\n */\nexport const PluginStatisticsSchema = z.object({\n /**\n * Total downloads\n */\n downloads: z.number().int().min(0).default(0),\n \n /**\n * Downloads in the last 30 days\n */\n downloadsLastMonth: z.number().int().min(0).default(0),\n \n /**\n * Number of active installations\n */\n activeInstallations: z.number().int().min(0).default(0),\n \n /**\n * User ratings\n */\n ratings: z.object({\n average: z.number().min(0).max(5).default(0),\n count: z.number().int().min(0).default(0),\n distribution: z.object({\n '5': z.number().int().min(0).default(0),\n '4': z.number().int().min(0).default(0),\n '3': z.number().int().min(0).default(0),\n '2': z.number().int().min(0).default(0),\n '1': z.number().int().min(0).default(0),\n }).optional(),\n }).optional(),\n \n /**\n * GitHub stars (if open source)\n */\n stars: z.number().int().min(0).optional(),\n \n /**\n * Number of dependent plugins\n */\n dependents: z.number().int().min(0).default(0),\n});\n\n/**\n * Plugin Registry Entry\n * Complete metadata for a plugin in the registry.\n */\nexport const PluginRegistryEntrySchema = z.object({\n /**\n * Plugin identifier (must match manifest.id)\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Plugin identifier (reverse domain notation)'),\n \n /**\n * Current version\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/),\n \n /**\n * Plugin display name\n */\n name: z.string(),\n \n /**\n * Short description\n */\n description: z.string().optional(),\n \n /**\n * Detailed documentation/README\n */\n readme: z.string().optional(),\n \n /**\n * Plugin type/category\n */\n category: z.enum([\n 'data', // Data management, storage, databases\n 'integration', // External service integrations\n 'ui', // UI components and themes\n 'analytics', // Analytics and reporting\n 'security', // Security, auth, compliance\n 'automation', // Workflows and automation\n 'ai', // AI/ML capabilities\n 'utility', // General utilities\n 'driver', // Database/storage drivers\n 'gateway', // API gateways\n 'adapter', // Runtime adapters\n ]).optional(),\n \n /**\n * Tags for categorization\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Vendor information\n */\n vendor: PluginVendorSchema,\n \n /**\n * Capability manifest (what the plugin implements/provides)\n */\n capabilities: PluginCapabilityManifestSchema.optional(),\n \n /**\n * Compatibility information\n */\n compatibility: z.object({\n /**\n * Minimum ObjectStack version required\n */\n minObjectStackVersion: z.string().optional(),\n \n /**\n * Maximum ObjectStack version supported\n */\n maxObjectStackVersion: z.string().optional(),\n \n /**\n * Node.js version requirement\n */\n nodeVersion: z.string().optional(),\n \n /**\n * Supported platforms\n */\n platforms: z.array(z.enum(['linux', 'darwin', 'win32', 'browser'])).optional(),\n }).optional(),\n \n /**\n * Links and resources\n */\n links: z.object({\n homepage: z.string().url().optional(),\n repository: z.string().url().optional(),\n documentation: z.string().url().optional(),\n bugs: z.string().url().optional(),\n changelog: z.string().url().optional(),\n }).optional(),\n \n /**\n * Media assets\n */\n media: z.object({\n icon: z.string().url().optional(),\n logo: z.string().url().optional(),\n screenshots: z.array(z.string().url()).optional(),\n video: z.string().url().optional(),\n }).optional(),\n \n /**\n * Quality metrics\n */\n quality: PluginQualityMetricsSchema.optional(),\n \n /**\n * Usage statistics\n */\n statistics: PluginStatisticsSchema.optional(),\n \n /**\n * License information\n */\n license: z.string().optional().describe('SPDX license identifier'),\n \n /**\n * Pricing (if commercial)\n */\n pricing: z.object({\n model: z.enum(['free', 'freemium', 'paid', 'enterprise']),\n price: z.number().min(0).optional(),\n currency: z.string().default('USD').optional(),\n billingPeriod: z.enum(['one-time', 'monthly', 'yearly']).optional(),\n }).optional(),\n \n /**\n * Publication dates\n */\n publishedAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n \n /**\n * Deprecation status\n */\n deprecated: z.boolean().default(false),\n deprecationMessage: z.string().optional(),\n replacedBy: z.string().optional().describe('Plugin ID that replaces this one'),\n \n /**\n * Feature flags\n */\n flags: z.object({\n experimental: z.boolean().default(false),\n beta: z.boolean().default(false),\n featured: z.boolean().default(false),\n verified: z.boolean().default(false),\n }).optional(),\n});\n\n/**\n * Plugin Search Filters\n */\nexport const PluginSearchFiltersSchema = z.object({\n /**\n * Search query\n */\n query: z.string().optional(),\n \n /**\n * Filter by category\n */\n category: z.array(z.string()).optional(),\n \n /**\n * Filter by tags\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Filter by vendor trust level\n */\n trustLevel: z.array(z.enum(['official', 'verified', 'community', 'unverified'])).optional(),\n \n /**\n * Filter by protocols implemented\n */\n implementsProtocols: z.array(z.string()).optional(),\n \n /**\n * Filter by pricing model\n */\n pricingModel: z.array(z.enum(['free', 'freemium', 'paid', 'enterprise'])).optional(),\n \n /**\n * Minimum rating\n */\n minRating: z.number().min(0).max(5).optional(),\n \n /**\n * Sort options\n */\n sortBy: z.enum([\n 'relevance',\n 'downloads',\n 'rating',\n 'updated',\n 'name',\n ]).optional(),\n \n /**\n * Sort order\n */\n sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),\n \n /**\n * Pagination\n */\n page: z.number().int().min(1).default(1).optional(),\n limit: z.number().int().min(1).max(100).default(20).optional(),\n});\n\n/**\n * Plugin Installation Configuration\n */\nexport const PluginInstallConfigSchema = z.object({\n /**\n * Plugin identifier to install\n */\n pluginId: z.string(),\n \n /**\n * Version to install (supports semver ranges)\n */\n version: z.string().optional().describe('Defaults to latest'),\n \n /**\n * Plugin-specific configuration values\n */\n config: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Whether to auto-update\n */\n autoUpdate: z.boolean().default(false).optional(),\n \n /**\n * Installation options\n */\n options: z.object({\n /**\n * Skip dependency installation\n */\n skipDependencies: z.boolean().default(false).optional(),\n \n /**\n * Force reinstall\n */\n force: z.boolean().default(false).optional(),\n \n /**\n * Installation target\n */\n target: z.enum(['system', 'space', 'user']).default('space').optional(),\n }).optional(),\n});\n\n// Export types\nexport type PluginVendor = z.infer;\nexport type PluginVendorInput = z.input;\nexport type PluginQualityMetrics = z.infer;\nexport type PluginQualityMetricsInput = z.input;\nexport type PluginStatistics = z.infer;\nexport type PluginStatisticsInput = z.input;\nexport type PluginRegistryEntry = z.infer;\nexport type PluginRegistryEntryInput = z.input;\nexport type PluginSearchFilters = z.infer;\nexport type PluginSearchFiltersInput = z.input;\nexport type PluginInstallConfig = z.infer;\nexport type PluginInstallConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Security & Dependency Resolution Protocol\n * \n * Provides comprehensive security scanning, vulnerability management,\n * and dependency resolution for the ObjectStack plugin ecosystem.\n * \n * Features:\n * - CVE/vulnerability scanning\n * - Dependency graph resolution\n * - Semantic version conflict detection\n * - Supply chain security\n * - Plugin sandboxing policies\n * - Trust and verification workflows\n */\n\n// ============================================================================\n// Security Scanning\n// ============================================================================\n\n/**\n * Vulnerability Severity\n */\nexport const VulnerabilitySeverity = z.enum([\n 'critical',\n 'high',\n 'medium',\n 'low',\n 'info',\n]).describe('Severity level of a security vulnerability');\n\nexport type VulnerabilitySeverity = z.infer;\n\n/**\n * Security Vulnerability\n */\nexport const SecurityVulnerabilitySchema = z.object({\n /**\n * CVE identifier (if applicable)\n */\n cve: z.string().regex(/^CVE-\\d{4}-\\d+$/).optional().describe('CVE identifier'),\n \n /**\n * Vulnerability identifier (GHSA, SNYK, etc.)\n */\n id: z.string().describe('Vulnerability ID'),\n \n /**\n * Title\n */\n title: z.string().describe('Short title summarizing the vulnerability'),\n \n /**\n * Description\n */\n description: z.string().describe('Detailed description of the vulnerability'),\n \n /**\n * Severity\n */\n severity: VulnerabilitySeverity.describe('Severity level of this vulnerability'),\n \n /**\n * CVSS score (0-10)\n */\n cvss: z.number().min(0).max(10).optional().describe('CVSS score ranging from 0 to 10'),\n \n /**\n * Affected package\n */\n package: z.object({\n name: z.string().describe('Name of the affected package'),\n version: z.string().describe('Version of the affected package'),\n ecosystem: z.string().optional().describe('Package ecosystem (e.g., npm, pip, maven)'),\n }).describe('Affected package information'),\n \n /**\n * Vulnerable version range\n */\n vulnerableVersions: z.string().describe('Semver range of vulnerable versions'),\n \n /**\n * Patched versions\n */\n patchedVersions: z.string().optional().describe('Semver range of patched versions'),\n \n /**\n * References\n */\n references: z.array(z.object({\n type: z.enum(['advisory', 'article', 'report', 'web']).describe('Type of reference source'),\n url: z.string().url().describe('URL of the reference'),\n })).default([]).describe('External references related to the vulnerability'),\n \n /**\n * CWE (Common Weakness Enumeration)\n */\n cwe: z.array(z.string()).default([]).describe('CWE identifiers associated with this vulnerability'),\n \n /**\n * Published date\n */\n publishedAt: z.string().datetime().optional().describe('ISO 8601 date when the vulnerability was published'),\n \n /**\n * Mitigation advice\n */\n mitigation: z.string().optional().describe('Recommended steps to mitigate the vulnerability'),\n}).describe('A known security vulnerability in a package dependency');\n\nexport type SecurityVulnerability = z.infer;\n\n/**\n * Security Scan Result\n */\nexport const SecurityScanResultSchema = z.object({\n /**\n * Scan identifier\n */\n scanId: z.string().uuid().describe('Unique identifier for this security scan'),\n \n /**\n * Plugin being scanned\n */\n plugin: z.object({\n id: z.string().describe('Plugin identifier'),\n version: z.string().describe('Plugin version that was scanned'),\n }).describe('Plugin that was scanned'),\n \n /**\n * Scan timestamp\n */\n scannedAt: z.string().datetime().describe('ISO 8601 timestamp when the scan was performed'),\n \n /**\n * Scanner information\n */\n scanner: z.object({\n name: z.string().describe('Scanner name (e.g., snyk, osv, trivy)'),\n version: z.string().describe('Version of the scanner tool'),\n }).describe('Information about the scanner tool used'),\n \n /**\n * Scan status\n */\n status: z.enum(['passed', 'failed', 'warning']).describe('Overall result status of the security scan'),\n \n /**\n * Vulnerabilities found\n */\n vulnerabilities: z.array(SecurityVulnerabilitySchema).describe('List of vulnerabilities discovered during the scan'),\n \n /**\n * Vulnerability summary\n */\n summary: z.object({\n critical: z.number().int().min(0).default(0).describe('Count of critical severity vulnerabilities'),\n high: z.number().int().min(0).default(0).describe('Count of high severity vulnerabilities'),\n medium: z.number().int().min(0).default(0).describe('Count of medium severity vulnerabilities'),\n low: z.number().int().min(0).default(0).describe('Count of low severity vulnerabilities'),\n info: z.number().int().min(0).default(0).describe('Count of informational severity vulnerabilities'),\n total: z.number().int().min(0).default(0).describe('Total count of all vulnerabilities'),\n }).describe('Summary counts of vulnerabilities by severity'),\n \n /**\n * License compliance issues\n */\n licenseIssues: z.array(z.object({\n package: z.string().describe('Name of the package with a license issue'),\n license: z.string().describe('License identifier of the package'),\n reason: z.string().describe('Reason the license is flagged'),\n severity: z.enum(['error', 'warning', 'info']).describe('Severity of the license compliance issue'),\n })).default([]).describe('License compliance issues found during the scan'),\n \n /**\n * Code quality issues\n */\n codeQuality: z.object({\n score: z.number().min(0).max(100).optional().describe('Overall code quality score from 0 to 100'),\n issues: z.array(z.object({\n type: z.enum(['security', 'quality', 'style']).describe('Category of the code quality issue'),\n severity: z.enum(['error', 'warning', 'info']).describe('Severity of the code quality issue'),\n message: z.string().describe('Description of the code quality issue'),\n file: z.string().optional().describe('File path where the issue was found'),\n line: z.number().int().optional().describe('Line number where the issue was found'),\n })).default([]).describe('List of individual code quality issues'),\n }).optional().describe('Code quality analysis results'),\n \n /**\n * Next scan scheduled\n */\n nextScanAt: z.string().datetime().optional().describe('ISO 8601 timestamp for the next scheduled scan'),\n}).describe('Result of a security scan performed on a plugin');\n\nexport type SecurityScanResult = z.infer;\n\n/**\n * Security Policy\n */\nexport const SecurityPolicySchema = z.object({\n /**\n * Policy identifier\n */\n id: z.string().describe('Unique identifier for the security policy'),\n \n /**\n * Policy name\n */\n name: z.string().describe('Human-readable name of the security policy'),\n \n /**\n * Automatic scanning\n */\n autoScan: z.object({\n enabled: z.boolean().default(true).describe('Whether automatic scanning is enabled'),\n frequency: z.enum(['on-publish', 'daily', 'weekly', 'monthly']).default('daily').describe('How often automatic scans are performed'),\n }).describe('Automatic security scanning configuration'),\n \n /**\n * Vulnerability thresholds\n */\n thresholds: z.object({\n /**\n * Block plugin if critical vulnerabilities exceed this\n */\n maxCritical: z.number().int().min(0).default(0).describe('Maximum allowed critical vulnerabilities before blocking'),\n \n /**\n * Block plugin if high vulnerabilities exceed this\n */\n maxHigh: z.number().int().min(0).default(0).describe('Maximum allowed high vulnerabilities before blocking'),\n \n /**\n * Warn if medium vulnerabilities exceed this\n */\n maxMedium: z.number().int().min(0).default(5).describe('Maximum allowed medium vulnerabilities before warning'),\n }).describe('Vulnerability count thresholds for policy enforcement'),\n \n /**\n * Allowed licenses\n */\n allowedLicenses: z.array(z.string()).default([\n 'MIT',\n 'Apache-2.0',\n 'BSD-3-Clause',\n 'BSD-2-Clause',\n 'ISC',\n ]).describe('List of SPDX license identifiers that are permitted'),\n \n /**\n * Prohibited licenses\n */\n prohibitedLicenses: z.array(z.string()).default([\n 'GPL-3.0',\n 'AGPL-3.0',\n ]).describe('List of SPDX license identifiers that are prohibited'),\n \n /**\n * Code signing requirements\n */\n codeSigning: z.object({\n required: z.boolean().default(false).describe('Whether code signing is required for plugins'),\n allowedSigners: z.array(z.string()).default([]).describe('List of trusted signer identities'),\n }).optional().describe('Code signing requirements for plugin artifacts'),\n \n /**\n * Sandbox restrictions\n */\n sandbox: z.object({\n /**\n * Restrict network access\n */\n networkAccess: z.enum(['none', 'localhost', 'allowlist', 'all']).default('all').describe('Level of network access granted to the plugin'),\n \n /**\n * Allowed network destinations (if allowlist)\n */\n allowedDestinations: z.array(z.string()).default([]).describe('Permitted network destinations when using allowlist mode'),\n \n /**\n * File system access\n */\n filesystemAccess: z.enum(['none', 'read-only', 'temp-only', 'full']).default('full').describe('Level of file system access granted to the plugin'),\n \n /**\n * Maximum memory (MB)\n */\n maxMemoryMB: z.number().int().positive().optional().describe('Maximum memory allocation in megabytes'),\n \n /**\n * Maximum CPU time (seconds)\n */\n maxCPUSeconds: z.number().int().positive().optional().describe('Maximum CPU time allowed in seconds'),\n }).optional().describe('Sandbox restrictions for plugin execution'),\n}).describe('Security policy governing plugin scanning and enforcement');\n\nexport type SecurityPolicy = z.infer;\n\n// ============================================================================\n// Dependency Resolution\n// ============================================================================\n\n/**\n * Package Dependency\n */\nexport const PackageDependencySchema = z.object({\n /**\n * Package name/ID\n */\n name: z.string().describe('Package name or identifier'),\n \n /**\n * Version constraint (semver range)\n */\n versionConstraint: z.string().describe('Semver range (e.g., `^1.0.0`, `>=2.0.0 <3.0.0`)'),\n \n /**\n * Dependency type\n */\n type: z.enum(['required', 'optional', 'peer', 'dev']).default('required').describe('Category of the dependency relationship'),\n \n /**\n * Resolved version (filled during resolution)\n */\n resolvedVersion: z.string().optional().describe('Concrete version resolved during dependency resolution'),\n}).describe('A package dependency with its version constraint');\n\nexport type PackageDependency = z.infer;\n\n/**\n * Dependency Graph Node\n */\nexport const DependencyGraphNodeSchema = z.object({\n /**\n * Package identifier\n */\n id: z.string().describe('Unique identifier of the package'),\n \n /**\n * Package version\n */\n version: z.string().describe('Resolved version of the package'),\n \n /**\n * Dependencies of this package\n */\n dependencies: z.array(PackageDependencySchema).default([]).describe('Dependencies required by this package'),\n \n /**\n * Depth in dependency tree\n */\n depth: z.number().int().min(0).describe('Depth level in the dependency tree (0 = root)'),\n \n /**\n * Whether this is a direct dependency\n */\n isDirect: z.boolean().describe('Whether this is a direct (top-level) dependency'),\n \n /**\n * Package metadata\n */\n metadata: z.object({\n name: z.string().describe('Display name of the package'),\n description: z.string().optional().describe('Short description of the package'),\n license: z.string().optional().describe('SPDX license identifier of the package'),\n homepage: z.string().url().optional().describe('Homepage URL of the package'),\n }).optional().describe('Additional metadata about the package'),\n}).describe('A node in the dependency graph representing a resolved package');\n\nexport type DependencyGraphNode = z.infer;\n\n/**\n * Dependency Graph\n */\nexport const DependencyGraphSchema = z.object({\n /**\n * Root package\n */\n root: z.object({\n id: z.string().describe('Identifier of the root package'),\n version: z.string().describe('Version of the root package'),\n }).describe('Root package of the dependency graph'),\n \n /**\n * All nodes in the graph\n */\n nodes: z.array(DependencyGraphNodeSchema).describe('All resolved package nodes in the dependency graph'),\n \n /**\n * Edges (dependency relationships)\n */\n edges: z.array(z.object({\n from: z.string().describe('Package ID'),\n to: z.string().describe('Package ID'),\n constraint: z.string().describe('Version constraint'),\n })).describe('Directed edges representing dependency relationships'),\n \n /**\n * Resolution statistics\n */\n stats: z.object({\n totalDependencies: z.number().int().min(0).describe('Total number of resolved dependencies'),\n directDependencies: z.number().int().min(0).describe('Number of direct (top-level) dependencies'),\n maxDepth: z.number().int().min(0).describe('Maximum depth of the dependency tree'),\n }).describe('Summary statistics for the dependency graph'),\n}).describe('Complete dependency graph for a package and its transitive dependencies');\n\nexport type DependencyGraph = z.infer;\n\n/**\n * Dependency Conflict\n * \n * Hub-level dependency conflict detected during plugin resolution.\n * Focuses on package version conflicts across the marketplace/registry.\n * \n * @see kernel/plugin-versioning.zod.ts DependencyConflictSchema for kernel-level plugin conflicts\n * which models plugin-to-plugin conflicts with richer resolution strategies.\n */\nexport const PackageDependencyConflictSchema = z.object({\n /**\n * Package with conflict\n */\n package: z.string().describe('Name of the package with conflicting version requirements'),\n \n /**\n * Conflicting versions\n */\n conflicts: z.array(z.object({\n version: z.string().describe('Conflicting version of the package'),\n requestedBy: z.array(z.string()).describe('Packages that require this version'),\n constraint: z.string().describe('Semver constraint that produced this version requirement'),\n })).describe('List of conflicting version requirements'),\n \n /**\n * Suggested resolution\n */\n resolution: z.object({\n strategy: z.enum(['pick-highest', 'pick-lowest', 'manual']).describe('Strategy used to resolve the conflict'),\n version: z.string().optional().describe('Resolved version selected by the strategy'),\n reason: z.string().optional().describe('Explanation of why this resolution was chosen'),\n }).optional().describe('Suggested resolution for the conflict'),\n \n /**\n * Severity\n */\n severity: z.enum(['error', 'warning', 'info']).describe('Severity level of the dependency conflict'),\n}).describe('A detected conflict between dependency version requirements');\n\nexport type PackageDependencyConflict = z.infer;\n\n/**\n * Dependency Resolution Result\n */\nexport const PackageDependencyResolutionResultSchema = z.object({\n /**\n * Resolution status\n */\n status: z.enum(['success', 'conflict', 'error']).describe('Overall status of the dependency resolution'),\n \n /**\n * Resolved dependency graph\n */\n graph: DependencyGraphSchema.optional().describe('Resolved dependency graph if resolution succeeded'),\n \n /**\n * Conflicts detected\n */\n conflicts: z.array(PackageDependencyConflictSchema).default([]).describe('List of dependency conflicts detected during resolution'),\n \n /**\n * Errors encountered\n */\n errors: z.array(z.object({\n package: z.string().describe('Name of the package that caused the error'),\n error: z.string().describe('Error message describing what went wrong'),\n })).default([]).describe('Errors encountered during dependency resolution'),\n \n /**\n * Installation order (topological sort)\n */\n installOrder: z.array(z.string()).default([]).describe('Topologically sorted list of package IDs for installation'),\n \n /**\n * Resolution time (ms)\n */\n resolvedIn: z.number().int().min(0).optional().describe('Time taken to resolve dependencies in milliseconds'),\n}).describe('Result of a dependency resolution process');\n\nexport type PackageDependencyResolutionResult = z.infer;\n\n// ============================================================================\n// Supply Chain Security\n// ============================================================================\n\n/**\n * SBOM (Software Bill of Materials) Entry\n */\nexport const SBOMEntrySchema = z.object({\n /**\n * Component name\n */\n name: z.string().describe('Name of the software component'),\n \n /**\n * Component version\n */\n version: z.string().describe('Version of the software component'),\n \n /**\n * Package URL (purl)\n */\n purl: z.string().optional().describe('Package URL identifier'),\n \n /**\n * License\n */\n license: z.string().optional().describe('SPDX license identifier of the component'),\n \n /**\n * Hashes\n */\n hashes: z.object({\n sha256: z.string().optional().describe('SHA-256 hash of the component artifact'),\n sha512: z.string().optional().describe('SHA-512 hash of the component artifact'),\n }).optional().describe('Cryptographic hashes for integrity verification'),\n \n /**\n * Supplier\n */\n supplier: z.object({\n name: z.string().describe('Name of the component supplier'),\n url: z.string().url().optional().describe('URL of the component supplier'),\n }).optional().describe('Supplier information for the component'),\n \n /**\n * External references\n */\n externalRefs: z.array(z.object({\n type: z.enum(['website', 'repository', 'documentation', 'issue-tracker']).describe('Type of external reference'),\n url: z.string().url().describe('URL of the external reference'),\n })).default([]).describe('External references related to the component'),\n}).describe('A single entry in a Software Bill of Materials');\n\nexport type SBOMEntry = z.infer;\n\n/**\n * Software Bill of Materials (SBOM)\n */\nexport const SBOMSchema = z.object({\n /**\n * SBOM format\n */\n format: z.enum(['spdx', 'cyclonedx']).default('cyclonedx').describe('SBOM standard format used'),\n \n /**\n * SBOM version\n */\n version: z.string().describe('Version of the SBOM specification'),\n \n /**\n * Plugin metadata\n */\n plugin: z.object({\n id: z.string().describe('Plugin identifier'),\n version: z.string().describe('Plugin version'),\n name: z.string().describe('Human-readable plugin name'),\n }).describe('Metadata about the plugin this SBOM describes'),\n \n /**\n * Components (dependencies)\n */\n components: z.array(SBOMEntrySchema).describe('List of software components included in the plugin'),\n \n /**\n * Generation timestamp\n */\n generatedAt: z.string().datetime().describe('ISO 8601 timestamp when the SBOM was generated'),\n \n /**\n * Generator tool\n */\n generator: z.object({\n name: z.string().describe('Name of the SBOM generator tool'),\n version: z.string().describe('Version of the SBOM generator tool'),\n }).optional().describe('Tool used to generate this SBOM'),\n}).describe('Software Bill of Materials for a plugin');\n\nexport type SBOM = z.infer;\n\n/**\n * Plugin Provenance\n * Verifiable chain of custody for plugin artifacts\n */\nexport const PluginProvenanceSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string().describe('Unique identifier of the plugin'),\n \n /**\n * Plugin version\n */\n version: z.string().describe('Version of the plugin artifact'),\n \n /**\n * Build information\n */\n build: z.object({\n /**\n * Build timestamp\n */\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the build was produced'),\n \n /**\n * Build environment\n */\n environment: z.object({\n os: z.string().describe('Operating system used for the build'),\n arch: z.string().describe('CPU architecture used for the build'),\n nodeVersion: z.string().describe('Node.js version used for the build'),\n }).optional().describe('Environment details where the build was executed'),\n \n /**\n * Source repository\n */\n source: z.object({\n repository: z.string().url().describe('URL of the source repository'),\n commit: z.string().regex(/^[a-f0-9]{40}$/).describe('Full SHA-1 commit hash of the source'),\n branch: z.string().optional().describe('Branch name the build was produced from'),\n tag: z.string().optional().describe('Git tag associated with the build'),\n }).optional().describe('Source repository information for the build'),\n \n /**\n * Builder identity\n */\n builder: z.object({\n name: z.string().describe('Name of the person or system that produced the build'),\n email: z.string().email().optional().describe('Email address of the builder'),\n }).optional().describe('Identity of the builder who produced the artifact'),\n }).describe('Build provenance information'),\n \n /**\n * Artifact hashes\n */\n artifacts: z.array(z.object({\n filename: z.string().describe('Name of the artifact file'),\n sha256: z.string().describe('SHA-256 hash of the artifact'),\n size: z.number().int().positive().describe('Size of the artifact in bytes'),\n })).describe('List of build artifacts with integrity hashes'),\n \n /**\n * Signatures\n */\n signatures: z.array(z.object({\n algorithm: z.enum(['rsa', 'ecdsa', 'ed25519']).describe('Cryptographic algorithm used for signing'),\n publicKey: z.string().describe('Public key used to verify the signature'),\n signature: z.string().describe('Digital signature value'),\n signedBy: z.string().describe('Identity of the signer'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the signature was created'),\n })).default([]).describe('Cryptographic signatures for the plugin artifact'),\n \n /**\n * Attestations\n */\n attestations: z.array(z.object({\n type: z.enum(['code-review', 'security-scan', 'test-results', 'ci-build']).describe('Type of attestation'),\n status: z.enum(['passed', 'failed']).describe('Result status of the attestation'),\n url: z.string().url().optional().describe('URL with details about the attestation'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the attestation was issued'),\n })).default([]).describe('Verification attestations for the plugin'),\n}).describe('Verifiable provenance and chain of custody for a plugin artifact');\n\nexport type PluginProvenance = z.infer;\n\n// ============================================================================\n// Trust & Verification\n// ============================================================================\n\n/**\n * Plugin Trust Score\n */\nexport const PluginTrustScoreSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string().describe('Unique identifier of the plugin'),\n \n /**\n * Overall trust score (0-100)\n */\n score: z.number().min(0).max(100).describe('Overall trust score from 0 to 100'),\n \n /**\n * Score components\n */\n components: z.object({\n /**\n * Vendor reputation (0-100)\n */\n vendorReputation: z.number().min(0).max(100).describe('Vendor reputation score from 0 to 100'),\n \n /**\n * Security scan results (0-100)\n */\n securityScore: z.number().min(0).max(100).describe('Security scan results score from 0 to 100'),\n \n /**\n * Code quality (0-100)\n */\n codeQuality: z.number().min(0).max(100).describe('Code quality score from 0 to 100'),\n \n /**\n * Community engagement (0-100)\n */\n communityScore: z.number().min(0).max(100).describe('Community engagement score from 0 to 100'),\n \n /**\n * Update frequency (0-100)\n */\n maintenanceScore: z.number().min(0).max(100).describe('Maintenance and update frequency score from 0 to 100'),\n }).describe('Individual score components contributing to the overall trust score'),\n \n /**\n * Trust level\n */\n level: z.enum(['verified', 'trusted', 'neutral', 'untrusted', 'blocked']).describe('Computed trust level based on the overall score'),\n \n /**\n * Verification badges\n */\n badges: z.array(z.enum([\n 'official', // Official ObjectStack plugin\n 'verified-vendor', // Verified vendor\n 'security-scanned', // Passed security scan\n 'code-signed', // Digitally signed\n 'open-source', // Open source\n 'popular', // High downloads\n ])).default([]).describe('Verification badges earned by the plugin'),\n \n /**\n * Last updated\n */\n updatedAt: z.string().datetime().describe('ISO 8601 timestamp when the trust score was last updated'),\n}).describe('Trust score and verification status for a plugin');\n\nexport type PluginTrustScore = z.infer;\n\n// ============================================================================\n// Export All\n// ============================================================================\n\nexport const PluginSecurityProtocol = {\n VulnerabilitySeverity,\n SecurityVulnerability: SecurityVulnerabilitySchema,\n SecurityScanResult: SecurityScanResultSchema,\n SecurityPolicy: SecurityPolicySchema,\n PackageDependency: PackageDependencySchema,\n DependencyGraphNode: DependencyGraphNodeSchema,\n DependencyGraph: DependencyGraphSchema,\n DependencyConflict: PackageDependencyConflictSchema,\n DependencyResolutionResult: PackageDependencyResolutionResultSchema,\n SBOMEntry: SBOMEntrySchema,\n SBOM: SBOMSchema,\n PluginProvenance: PluginProvenanceSchema,\n PluginTrustScore: PluginTrustScoreSchema,\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Execution Context Schema\n * \n * Defines the runtime context that flows from HTTP request → data operations.\n * This is the \"identity + environment\" envelope that every data operation can carry.\n * \n * Design:\n * - All fields are optional for backward compatibility\n * - `isSystem` bypasses permission checks (for internal/migration operations)\n * - `transaction` carries the database transaction handle for atomicity\n * - `traceId` enables distributed tracing across microservices\n * \n * Usage:\n * engine.find('account', { context: { userId: '...', tenantId: '...' } })\n */\nexport const ExecutionContextSchema = z.object({\n /** Current user ID (resolved from session) */\n userId: z.string().optional(),\n \n /** Current organization/tenant ID (resolved from session.activeOrganizationId) */\n tenantId: z.string().optional(),\n \n /** User role names (resolved from Member + Role) */\n roles: z.array(z.string()).default([]),\n \n /** Aggregated permission names (resolved from PermissionSet) */\n permissions: z.array(z.string()).default([]),\n \n /** Whether this is a system-level operation (bypasses permission checks) */\n isSystem: z.boolean().default(false),\n \n /** Raw access token (for external API call pass-through) */\n accessToken: z.string().optional(),\n \n /** Database transaction handle */\n transaction: z.unknown().optional(),\n \n /** Request trace ID (for distributed tracing) */\n traceId: z.string().optional(),\n});\n\nexport type ExecutionContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Unified Chart Type Taxonomy\n * \n * Shared by Dashboard and Report widgets.\n * Provides a comprehensive set of chart types for data visualization.\n */\n\n/**\n * Chart Type Enum\n * Categorized by visualization purpose\n */\nexport const ChartTypeSchema = z.enum([\n // Comparison\n 'bar',\n 'horizontal-bar',\n 'column',\n 'grouped-bar',\n 'stacked-bar',\n 'bi-polar-bar',\n \n // Trend\n 'line',\n 'area',\n 'stacked-area',\n 'step-line',\n 'spline',\n \n // Distribution\n 'pie',\n 'donut',\n 'funnel',\n 'pyramid',\n \n // Relationship\n 'scatter',\n 'bubble',\n \n // Composition\n 'treemap',\n 'sunburst',\n 'sankey',\n 'word-cloud',\n \n // Performance\n 'gauge',\n 'solid-gauge',\n 'metric',\n 'kpi',\n 'bullet',\n \n // Geo\n 'choropleth',\n 'bubble-map',\n 'gl-map',\n \n // Advanced\n 'heatmap',\n 'radar',\n 'waterfall',\n 'box-plot',\n 'violin',\n 'candlestick',\n 'stock',\n \n // Tabular\n 'table',\n 'pivot',\n]);\n\nexport type ChartType = z.infer;\n\n/**\n * Chart Axis Schema\n * Definition for X and Y axes\n */\nexport const ChartAxisSchema = z.object({\n /** Data field to map to this axis */\n field: z.string().describe('Data field key'),\n \n /** Axis title */\n title: I18nLabelSchema.optional().describe('Axis display title'),\n\n /** Value formatting (d3-format or similar) */\n format: z.string().optional().describe('Value format string (e.g., \"$0,0.00\")'),\n \n /** Axis scale settings */\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n stepSize: z.number().optional().describe('Step size for ticks'),\n \n /** Appearance */\n showGridLines: z.boolean().default(true),\n position: z.enum(['left', 'right', 'top', 'bottom']).optional().describe('Axis position'),\n \n /** Logarithmic scale */\n logarithmic: z.boolean().default(false),\n});\n\n/**\n * Chart Series Schema\n * Defines a single data series in the chart\n */\nexport const ChartSeriesSchema = z.object({\n /** Field name for values */\n name: z.string().describe('Field name or series identifier'),\n \n /** Display label */\n label: I18nLabelSchema.optional().describe('Series display label'),\n \n /** Series type override (combo charts) */\n type: ChartTypeSchema.optional().describe('Override chart type for this series'),\n \n /** Specific color */\n color: z.string().optional().describe('Series color (hex/rgb/token)'),\n \n /** Stacking group */\n stack: z.string().optional().describe('Stack identifier to group series'),\n \n /** Axis binding */\n yAxis: z.enum(['left', 'right']).default('left').describe('Bind to specific Y-Axis'),\n});\n\n/**\n * Chart Annotation Schema\n * Static lines or regions to highlight data\n */\nexport const ChartAnnotationSchema = z.object({\n type: z.enum(['line', 'region']).default('line'),\n axis: z.enum(['x', 'y']).default('y'),\n value: z.union([z.number(), z.string()]).describe('Start value'),\n endValue: z.union([z.number(), z.string()]).optional().describe('End value for regions'),\n color: z.string().optional(),\n label: I18nLabelSchema.optional(),\n style: z.enum(['solid', 'dashed', 'dotted']).default('dashed'),\n});\n\n/**\n * Chart Interaction Schema\n */\nexport const ChartInteractionSchema = z.object({\n tooltips: z.boolean().default(true),\n zoom: z.boolean().default(false),\n brush: z.boolean().default(false),\n clickAction: z.string().optional().describe('Action ID to trigger on click'),\n});\n\n/**\n * Chart Configuration Base\n * Common configuration for all chart types\n */\nexport const ChartConfigSchema = z.object({\n /** Chart Type */\n type: ChartTypeSchema,\n \n /** Titles */\n title: I18nLabelSchema.optional().describe('Chart title'),\n subtitle: I18nLabelSchema.optional().describe('Chart subtitle'),\n description: I18nLabelSchema.optional().describe('Accessibility description'),\n \n /** Axes Mapping */\n xAxis: ChartAxisSchema.optional().describe('X-Axis configuration'),\n yAxis: z.array(ChartAxisSchema).optional().describe('Y-Axis configuration (support dual axis)'),\n \n /** Series Configuration */\n series: z.array(ChartSeriesSchema).optional().describe('Defined series configuration'),\n \n /** Appearance */\n colors: z.array(z.string()).optional().describe('Color palette'),\n height: z.number().optional().describe('Fixed height in pixels'),\n \n /** Components */\n showLegend: z.boolean().default(true).describe('Display legend'),\n showDataLabels: z.boolean().default(false).describe('Display data labels'),\n \n /** Annotations & Reference Lines */\n annotations: z.array(ChartAnnotationSchema).optional(),\n \n /** Interactions */\n interaction: ChartInteractionSchema.optional(),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport type ChartConfig = z.infer;\nexport type ChartAxis = z.infer;\nexport type ChartSeries = z.infer;\nexport type ChartAnnotation = z.infer;\nexport type ChartInteraction = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Breakpoint Name Enum\n * Matches the breakpoint names defined in theme.zod.ts BreakpointsSchema.\n */\nexport const BreakpointName = z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl']);\n\nexport type BreakpointName = z.infer;\n\n/**\n * Responsive Configuration Schema\n *\n * Provides responsive layout configuration for UI components.\n * Maps breakpoint names to layout behavior (columns, visibility, order).\n *\n * Aligned with theme.zod.ts BreakpointsSchema for a unified responsive system.\n *\n * @example\n * ```typescript\n * const config: ResponsiveConfig = {\n * columns: { xs: 12, sm: 6, lg: 4 },\n * hiddenOn: ['xs'],\n * order: { xs: 2, lg: 1 },\n * };\n * ```\n */\n/**\n * Breakpoint Column Map Schema\n * Maps breakpoint names to grid column counts (1-12).\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointColumnMapSchema = z.object({\n xs: z.number().min(1).max(12).optional(),\n sm: z.number().min(1).max(12).optional(),\n md: z.number().min(1).max(12).optional(),\n lg: z.number().min(1).max(12).optional(),\n xl: z.number().min(1).max(12).optional(),\n '2xl': z.number().min(1).max(12).optional(),\n}).describe('Grid columns per breakpoint (1-12)');\n\n/**\n * Breakpoint Order Map Schema\n * Maps breakpoint names to display order numbers.\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointOrderMapSchema = z.object({\n xs: z.number().optional(),\n sm: z.number().optional(),\n md: z.number().optional(),\n lg: z.number().optional(),\n xl: z.number().optional(),\n '2xl': z.number().optional(),\n}).describe('Display order per breakpoint');\n\nexport const ResponsiveConfigSchema = z.object({\n /** Minimum breakpoint for visibility */\n breakpoint: BreakpointName.optional()\n .describe('Minimum breakpoint for visibility'),\n\n /** Hide on specific breakpoints */\n hiddenOn: z.array(BreakpointName).optional()\n .describe('Hide on these breakpoints'),\n\n /** Grid columns per breakpoint (1-12 column grid) */\n columns: BreakpointColumnMapSchema.optional().describe('Grid columns per breakpoint'),\n\n /** Display order per breakpoint */\n order: BreakpointOrderMapSchema.optional().describe('Display order per breakpoint'),\n}).describe('Responsive layout configuration');\n\nexport type ResponsiveConfig = z.infer;\n\n/**\n * Performance Configuration Schema\n *\n * Defines performance optimization settings for UI components\n * such as lazy loading, virtual scrolling, and caching.\n *\n * @example\n * ```typescript\n * const perf: PerformanceConfig = {\n * lazyLoad: true,\n * virtualScroll: { enabled: true, itemHeight: 40, overscan: 5 },\n * cacheStrategy: 'stale-while-revalidate',\n * prefetch: true,\n * };\n * ```\n */\nexport const PerformanceConfigSchema = z.object({\n /** Enable lazy loading for this component */\n lazyLoad: z.boolean().optional()\n .describe('Enable lazy loading (defer rendering until visible)'),\n\n /** Virtual scrolling configuration for large datasets */\n virtualScroll: z.object({\n enabled: z.boolean().default(false).describe('Enable virtual scrolling'),\n itemHeight: z.number().optional().describe('Fixed item height in pixels (for estimation)'),\n overscan: z.number().optional().describe('Number of extra items to render outside viewport'),\n }).optional().describe('Virtual scrolling configuration'),\n\n /** Client-side caching strategy */\n cacheStrategy: z.enum([\n 'none',\n 'cache-first',\n 'network-first',\n 'stale-while-revalidate',\n ]).optional().describe('Client-side data caching strategy'),\n\n /** Enable data prefetching */\n prefetch: z.boolean().optional()\n .describe('Prefetch data before component is visible'),\n\n /** Maximum number of items to render before pagination */\n pageSize: z.number().optional()\n .describe('Number of items per page for pagination'),\n\n /** Debounce interval for user interactions (ms) */\n debounceMs: z.number().optional()\n .describe('Debounce interval for user interactions in milliseconds'),\n}).describe('Performance optimization configuration');\n\nexport type PerformanceConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module ui/sharing\n *\n * Sharing & Embedding Protocol\n *\n * Defines schemas for public link sharing, embed configuration,\n * domain restrictions, and password protection for apps, pages, and forms.\n */\n\nimport { z } from 'zod';\n\n/**\n * Sharing Config Schema\n * Configuration for public sharing of an app, page, or form.\n * Supports public links, password protection, domain restrictions, and expiration.\n */\nexport const SharingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable public sharing'),\n publicLink: z.string().optional().describe('Generated public share URL'),\n password: z.string().optional().describe('Password required to access shared link'),\n allowedDomains: z.array(z.string()).optional()\n .describe('Restrict access to specific email domains (e.g. [\"example.com\"])'),\n expiresAt: z.string().optional()\n .describe('Expiration date/time in ISO 8601 format'),\n allowAnonymous: z.boolean().optional().default(false)\n .describe('Allow access without authentication'),\n});\n\n/**\n * Embed Config Schema\n * Configuration for iframe embedding of an app, page, or form.\n * Supports origin restrictions, display options, and responsive sizing.\n */\nexport const EmbedConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable iframe embedding'),\n allowedOrigins: z.array(z.string()).optional()\n .describe('Allowed iframe parent origins (e.g. [\"https://example.com\"])'),\n width: z.string().optional().default('100%').describe('Embed width (CSS value)'),\n height: z.string().optional().default('600px').describe('Embed height (CSS value)'),\n showHeader: z.boolean().optional().default(true).describe('Show interface header in embed'),\n showNavigation: z.boolean().optional().default(false).describe('Show navigation in embed'),\n responsive: z.boolean().optional().default(true).describe('Enable responsive resizing'),\n});\n\n// Type Exports\nexport type SharingConfig = z.infer;\nexport type EmbedConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema, EmbedConfigSchema } from './sharing.zod';\n\n/**\n * Base Navigation Item Schema\n * Shared properties for all navigation types.\n * \n * **NAMING CONVENTION:**\n * Navigation item IDs are used in URLs and configuration and must be lowercase snake_case.\n * \n * @example Good IDs\n * - 'menu_accounts'\n * - 'page_dashboard'\n * - 'nav_settings'\n * \n * @example Bad IDs (will be rejected)\n * - 'MenuAccounts' (PascalCase)\n * - 'Page Dashboard' (spaces)\n */\nconst BaseNavItemSchema = z.object({\n /** Unique identifier for the item */\n id: SnakeCaseIdentifierSchema.describe('Unique identifier for this navigation item (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display proper label'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Sort order within the same level (lower numbers appear first) */\n order: z.number().optional().describe('Sort order within the same level (lower = first)'),\n\n /** Badge text or count displayed on the navigation item (e.g. \"3\", \"New\") */\n badge: z.union([z.string(), z.number()]).optional().describe('Badge text or count displayed on the item'),\n\n /** \n * Visibility condition. \n * Formula expression returning boolean. \n * e.g. \"user.is_admin || user.department == 'sales'\"\n */\n visible: z.string().optional().describe('Visibility formula condition'),\n\n /** Permissions required to see/access this navigation item */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this item'),\n});\n\n/**\n * 1. Object Navigation Item\n * Navigates to an object's list view.\n */\nexport const ObjectNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('object'),\n objectName: z.string().describe('Target object name'),\n viewName: z.string().optional().describe('Default list view to open. Defaults to \"all\"'),\n});\n\n/**\n * 2. Dashboard Navigation Item\n * Navigates to a specific dashboard.\n */\nexport const DashboardNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('dashboard'),\n dashboardName: z.string().describe('Target dashboard name'),\n});\n\n/**\n * 3. Page Navigation Item\n * Navigates to a custom UI page/component.\n */\nexport const PageNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('page'),\n pageName: z.string().describe('Target custom page component name'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the page context'),\n});\n\n/**\n * 4. URL Navigation Item\n * Navigates to an external or absolute URL.\n */\nexport const UrlNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('url'),\n url: z.string().describe('Target external URL'),\n target: z.enum(['_self', '_blank']).default('_self').describe('Link target window'),\n});\n\n/**\n * 5. Report Navigation Item\n * Navigates to a specific report.\n */\nexport const ReportNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('report'),\n reportName: z.string().describe('Target report name'),\n});\n\n/**\n * 6. Action Navigation Item\n * Triggers an action (e.g. opening a flow, running a script, or launching a screen action).\n */\nexport const ActionNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('action'),\n actionDef: z.object({\n actionName: z.string().describe('Action machine name to execute'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the action'),\n }).describe('Action definition to execute when clicked'),\n});\n\n/**\n * 7. Group Navigation Item\n * A container for child navigation items (Sub-menu).\n * Does not perform navigation itself.\n */\nexport const GroupNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('group'),\n expanded: z.boolean().default(false).describe('Default expansion state in sidebar'),\n // children property is added in the recursive definition below\n});\n\n/**\n * Recursive Union of all navigation item types.\n * Allows constructing an unlimited-depth navigation tree.\n */\nexport const NavigationItemSchema: z.ZodType = z.lazy(() => \n z.union([\n ObjectNavItemSchema.extend({\n children: z.array(NavigationItemSchema).optional().describe('Child navigation items (e.g. specific views)'),\n }),\n DashboardNavItemSchema,\n PageNavItemSchema,\n UrlNavItemSchema,\n ReportNavItemSchema,\n ActionNavItemSchema,\n GroupNavItemSchema.extend({\n children: z.array(NavigationItemSchema).describe('Child navigation items'),\n })\n ])\n);\n\n/**\n * App Branding Configuration\n * Allows configuring the look and feel of the specific app.\n */\nexport const AppBrandingSchema = z.object({\n primaryColor: z.string().optional().describe('Primary theme color hex code'),\n logo: z.string().optional().describe('Custom logo URL for this app'),\n favicon: z.string().optional().describe('Custom favicon URL for this app'),\n});\n\n/**\n * Navigation Area Schema\n * \n * A logical grouping (zone/section) of navigation items, similar to Salesforce \"App Areas\"\n * or Dynamics 365 \"Site Map Areas\". Each area represents a business domain (e.g. Sales, Service, Settings)\n * and contains its own independent navigation tree.\n * \n * Areas allow large applications to partition navigation by business function while\n * keeping a single AppSchema definition. The runtime may render areas as top-level tabs,\n * sidebar sections, or a switchable navigation context.\n * \n * @example\n * ```ts\n * const salesArea: NavigationArea = {\n * id: 'area_sales',\n * label: 'Sales',\n * icon: 'briefcase',\n * order: 1,\n * navigation: [\n * { id: 'nav_leads', type: 'object', label: 'Leads', objectName: 'lead' },\n * { id: 'nav_opportunities', type: 'object', label: 'Opportunities', objectName: 'opportunity' },\n * ],\n * };\n * ```\n */\nexport const NavigationAreaSchema = z.object({\n /** Unique area identifier */\n id: SnakeCaseIdentifierSchema.describe('Unique area identifier (lowercase snake_case)'),\n\n /** Display label */\n label: I18nLabelSchema.describe('Area display label'),\n\n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Area icon name'),\n\n /** Sort order among areas (lower = first) */\n order: z.number().optional().describe('Sort order among areas (lower = first)'),\n\n /** Area description */\n description: I18nLabelSchema.optional().describe('Area description'),\n\n /** \n * Visibility condition.\n * Formula expression returning boolean.\n */\n visible: z.string().optional().describe('Visibility formula condition for this area'),\n\n /** Permissions required to access this area */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this area'),\n\n /** Navigation items within this area */\n navigation: z.array(NavigationItemSchema).describe('Navigation items within this area'),\n});\n\n/**\n * Schema for Applications (Apps).\n * A logical container for business functionality (e.g., \"Sales CRM\", \"HR Portal\").\n * \n * **NAMING CONVENTION:**\n * App names are used in URLs and routing and must be lowercase snake_case.\n * Prefix with 'app_' is recommended for clarity.\n * \n * @example Good app names\n * - 'app_crm'\n * - 'app_finance'\n * - 'app_portal'\n * - 'sales_app'\n * \n * @example Bad app names (will be rejected)\n * - 'CRM' (uppercase)\n * - 'FinanceApp' (mixed case)\n * - 'Sales App' (spaces)\n */\n/**\n * App Configuration Schema\n * Defines a business application container, including its navigation, branding, and permissions.\n * \n * The App is the top-level navigation shell. The `navigation[]` field holds the complete\n * sidebar tree with unlimited nesting depth via `type: 'group'` items. Pages are referenced\n * by name via `type: 'page'` items and defined independently.\n * \n * @example CRM App with nested navigation tree\n * {\n * name: \"crm\",\n * label: \"Sales CRM\",\n * icon: \"briefcase\",\n * navigation: [\n * { type: \"group\", id: \"grp_sales\", label: \"Sales Cloud\", expanded: true, children: [\n * { type: \"page\", id: \"nav_pipeline\", label: \"Pipeline\", pageName: \"page_pipeline\" },\n * { type: \"page\", id: \"nav_accounts\", label: \"Accounts\", pageName: \"page_accounts\" },\n * ]},\n * { type: \"page\", id: \"nav_settings\", label: \"Settings\", pageName: \"admin_settings\" },\n * ]\n * }\n */\nexport const AppSchema = z.object({\n /** Machine name (id) */\n name: SnakeCaseIdentifierSchema.describe('App unique machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('App display label'),\n\n /** App version */\n version: z.string().optional().describe('App version'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('App description'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('App icon used in the App Launcher'),\n \n /** Branding/Theming Configuration */\n branding: AppBrandingSchema.optional().describe('App-specific branding'),\n \n /** Application status */\n active: z.boolean().optional().default(true).describe('Whether the app is enabled'),\n\n /** Is this the default app for new users? */\n isDefault: z.boolean().optional().default(false).describe('Is default app'),\n \n /** \n * Full Navigation Tree — supports unlimited nesting depth.\n * Pages are referenced by name via `type: 'page'` items.\n * Groups can contain other groups for arbitrary sidebar depth.\n * \n * For simple apps, use `navigation` directly.\n * For enterprise apps with multiple business domains, use `areas` instead.\n */\n navigation: z.array(NavigationItemSchema).optional()\n .describe('Full navigation tree for the app sidebar'),\n\n /**\n * Navigation Areas — partitions navigation by business domain.\n * Each area defines an independent navigation tree (e.g. Sales, Service, Settings).\n * When areas are defined, they take precedence over the top-level `navigation` array.\n * \n * @example\n * ```ts\n * areas: [\n * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] },\n * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] },\n * ]\n * ```\n */\n areas: z.array(NavigationAreaSchema).optional()\n .describe('Navigation areas for partitioning navigation by business domain'),\n \n /** \n * App-level Home Page Override\n * ID of the navigation item to act as the landing page.\n * If not set, usually defaults to the first navigation item.\n */\n homePageId: z.string().optional().describe('ID of the navigation item to serve as landing page'),\n\n /** \n * Access Control\n * List of permissions required to access this app.\n * Modern replacement for role/profile based assignment.\n * Example: [\"app.access.crm\"]\n */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this app'),\n \n /** \n * Package Components (For config file convenience)\n * In a real monorepo these might be auto-discovered, but here we allow explicit registration.\n */\n objects: z.array(z.unknown()).optional().describe('Objects belonging to this app'),\n apis: z.array(z.unknown()).optional().describe('Custom APIs belonging to this app'),\n\n /** Sharing configuration for public access */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration'),\n\n /** Embed configuration for iframe embedding */\n embed: EmbedConfigSchema.optional().describe('Iframe embedding configuration'),\n\n /** Mobile navigation mode */\n mobileNavigation: z.object({\n mode: z.enum(['drawer', 'bottom_nav', 'hamburger']).default('drawer')\n .describe('Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu'),\n bottomNavItems: z.array(z.string()).optional()\n .describe('Navigation item IDs to show in bottom nav (max 5)'),\n }).optional().describe('Mobile-specific navigation configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the application'),\n});\n\n/**\n * App Factory Helper\n */\nexport const App = {\n create: (config: z.input): App => AppSchema.parse(config),\n} as const;\n\n/**\n * Type-safe factory for creating application definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example CRM App with nested navigation tree\n * ```ts\n * const crmApp = defineApp({\n * name: 'crm',\n * label: 'Sales CRM',\n * navigation: [\n * { id: 'grp_sales', type: 'group', label: 'Sales Cloud', expanded: true, children: [\n * { id: 'nav_pipeline', type: 'page', label: 'Pipeline', pageName: 'page_pipeline' },\n * { id: 'nav_accounts', type: 'page', label: 'Accounts', pageName: 'page_accounts' },\n * ]},\n * { id: 'nav_settings', type: 'page', label: 'Settings', pageName: 'admin_settings' },\n * ],\n * });\n * ```\n */\nexport function defineApp(config: z.input): App {\n return AppSchema.parse(config);\n}\n\n// Main Types\nexport type App = z.infer;\nexport type AppInput = z.input;\nexport type AppBranding = z.infer;\nexport type NavigationItem = z.infer;\nexport type NavigationArea = z.infer;\n\n// Discriminated Item Types (Helper exports)\nexport type ObjectNavItem = z.infer;\nexport type DashboardNavItem = z.infer;\nexport type PageNavItem = z.infer;\nexport type UrlNavItem = z.infer;\nexport type ReportNavItem = z.infer;\nexport type ActionNavItem = z.infer;\nexport type GroupNavItem = z.infer & { children: NavigationItem[] };\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema } from './sharing.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * HTTP Method Enum & HTTP Request Schema\n * Migrated to shared/http.zod.ts. Re-exported here for backward compatibility.\n */\nimport { HttpMethodSchema, HttpRequestSchema } from '../shared/http.zod';\nexport { HttpMethodSchema, HttpRequestSchema };\n\n/**\n * View Data Source Configuration\n * Supports three modes:\n * 1. 'object': Standard Protocol - Auto-connects to ObjectStack Metadata and Data APIs\n * 2. 'api': Custom API - Explicitly provided API URLs\n * 3. 'value': Static Data - Hardcoded data array\n */\nexport const ViewDataSchema = z.discriminatedUnion('provider', [\n z.object({\n provider: z.literal('object'),\n object: z.string().describe('Target object name'),\n }),\n z.object({\n provider: z.literal('api'),\n read: HttpRequestSchema.optional().describe('Configuration for fetching data'),\n write: HttpRequestSchema.optional().describe('Configuration for submitting data (for forms/editable tables)'),\n }),\n z.object({\n provider: z.literal('value'),\n items: z.array(z.unknown()).describe('Static data array'),\n }),\n]);\n\n/**\n * View Filter Rule Schema\n * Standardized filter condition used in list views, tabs, and page-level filters.\n * Uses a declarative array-of-objects format: [{ field, operator, value }].\n *\n * @example\n * ```ts\n * filter: [\n * { field: 'status', operator: 'equals', value: 'active' },\n * { field: 'close_date', operator: 'this_quarter' },\n * ]\n * ```\n */\nexport const ViewFilterRuleSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n /** Filter operator */\n operator: z.string().describe('Filter operator (e.g. equals, not_equals, contains, this_quarter)'),\n /** Filter value (optional for unary operators like is_null, this_quarter) */\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Filter value'),\n}).describe('View filter rule');\n\nexport type ViewFilterRule = z.infer;\n\n/**\n * Column Summary Function Schema\n * Aggregation function for column footer (Airtable-style column summaries)\n */\nexport const ColumnSummarySchema = z.enum([\n 'none',\n 'count',\n 'count_empty',\n 'count_filled',\n 'count_unique',\n 'percent_empty',\n 'percent_filled',\n 'sum',\n 'avg',\n 'min',\n 'max',\n]).describe('Aggregation function for column footer summary');\n\n/**\n * List Column Configuration Schema\n * Detailed configuration for individual list view columns\n */\nexport const ListColumnSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n width: z.number().positive().optional().describe('Column width in pixels'),\n align: z.enum(['left', 'center', 'right']).optional().describe('Text alignment'),\n hidden: z.boolean().optional().describe('Hide column by default'),\n sortable: z.boolean().optional().describe('Allow sorting by this column'),\n resizable: z.boolean().optional().describe('Allow resizing this column'),\n wrap: z.boolean().optional().describe('Allow text wrapping'),\n type: z.string().optional().describe('Renderer type override (e.g., \"currency\", \"date\")'),\n\n /** Pinning (Airtable-style frozen columns) */\n pinned: z.enum(['left', 'right']).optional().describe('Pin/freeze column to left or right side'),\n\n /** Column Footer Summary (Airtable-style aggregation) */\n summary: ColumnSummarySchema.optional().describe('Footer aggregation function for this column'),\n\n /** Interaction */\n link: z.boolean().optional().describe('Functions as the primary navigation link (triggers View navigation)'),\n action: z.string().optional().describe('Registered Action ID to execute when clicked'),\n});\n\n/**\n * List View Selection Configuration\n */\nexport const SelectionConfigSchema = z.object({\n type: z.enum(['none', 'single', 'multiple']).default('none').describe('Selection mode'),\n});\n\n/**\n * List View Pagination Configuration\n */\nexport const PaginationConfigSchema = z.object({\n pageSize: z.number().int().positive().default(25).describe('Number of records per page'),\n pageSizeOptions: z.array(z.number().int().positive()).optional().describe('Available page size options'),\n});\n\n/**\n * Row Height / Density Schema (Airtable-style)\n * Controls the visual density of rows in a list view.\n */\nexport const RowHeightSchema = z.enum([\n 'compact', // Minimal padding, single line\n 'short', // Reduced padding\n 'medium', // Default padding\n 'tall', // Extra padding, multi-line preview\n 'extra_tall', // Maximum padding, rich content preview\n]).describe('Row height / density setting for list view');\n\n/**\n * Grouping Field Configuration\n * Defines a single grouping level for record grouping.\n */\nexport const GroupingFieldSchema = z.object({\n field: z.string().describe('Field name to group by'),\n order: z.enum(['asc', 'desc']).default('asc').describe('Group sort order'),\n collapsed: z.boolean().default(false).describe('Collapse groups by default'),\n});\n\n/**\n * Grouping Configuration Schema (Airtable-style)\n * Supports multi-level grouping for grid/gallery views.\n */\nexport const GroupingConfigSchema = z.object({\n fields: z.array(GroupingFieldSchema).min(1).describe('Fields to group by (supports up to 3 levels)'),\n}).describe('Record grouping configuration');\n\n/**\n * Gallery View Configuration (Airtable-style)\n * Configures card layout for gallery/card views.\n */\nexport const GalleryConfigSchema = z.object({\n coverField: z.string().optional().describe('Attachment/image field to display as card cover'),\n coverFit: z.enum(['cover', 'contain']).default('cover').describe('Image fit mode for card cover'),\n cardSize: z.enum(['small', 'medium', 'large']).default('medium').describe('Card size in gallery view'),\n titleField: z.string().optional().describe('Field to display as card title'),\n visibleFields: z.array(z.string()).optional().describe('Fields to display on card body'),\n}).describe('Gallery/card view configuration');\n\n/**\n * Timeline View Configuration (Airtable-style)\n * Configures timeline/chronological views.\n */\nexport const TimelineConfigSchema = z.object({\n startDateField: z.string().describe('Field for timeline item start date'),\n endDateField: z.string().optional().describe('Field for timeline item end date'),\n titleField: z.string().describe('Field to display as timeline item title'),\n groupByField: z.string().optional().describe('Field to group timeline rows'),\n colorField: z.string().optional().describe('Field to determine item color'),\n scale: z.enum(['hour', 'day', 'week', 'month', 'quarter', 'year']).default('week').describe('Default timeline scale'),\n}).describe('Timeline view configuration');\n\n/**\n * View Sharing Configuration (Airtable-style)\n * Defines who can see and modify a view.\n */\nexport const ViewSharingSchema = z.object({\n type: z.enum(['personal', 'collaborative']).default('collaborative').describe('View ownership type'),\n lockedBy: z.string().optional().describe('User who locked the view configuration'),\n}).describe('View sharing and access configuration');\n\n/**\n * Row Color Configuration (Airtable-style)\n * Defines how rows are colored based on field values.\n */\nexport const RowColorConfigSchema = z.object({\n field: z.string().describe('Field to derive color from (typically a select/status field)'),\n colors: z.record(z.string(), z.string()).optional().describe('Map of field value to color (hex/token)'),\n}).describe('Row color configuration based on field values');\n\n/**\n * Visualization Type Schema\n * Whitelist of visualization types the user can switch between.\n * Maps to Airtable's \"Visualizations\" setting in Appearance panel.\n */\nexport const VisualizationTypeSchema = z.enum([\n 'grid',\n 'kanban',\n 'gallery',\n 'calendar',\n 'timeline',\n 'gantt',\n 'map',\n]).describe('Visualization type that users can switch to');\n\n/**\n * User Actions Configuration Schema (Airtable Interface parity)\n * Controls which interactive actions are available to users in the view toolbar.\n * Each boolean toggles the corresponding toolbar element on/off.\n *\n * @see Airtable Interface → \"User actions\" panel\n */\nexport const UserActionsConfigSchema = z.object({\n sort: z.boolean().default(true).describe('Allow users to sort records'),\n search: z.boolean().default(true).describe('Allow users to search records'),\n filter: z.boolean().default(true).describe('Allow users to filter records'),\n rowHeight: z.boolean().default(true).describe('Allow users to toggle row height/density'),\n addRecordForm: z.boolean().default(false).describe('Add records through a form instead of inline'),\n buttons: z.array(z.string()).optional().describe('Custom action button IDs to show in the toolbar'),\n}).describe('User action toggles for the view toolbar');\n\n/**\n * Appearance Configuration Schema (Airtable Interface parity)\n * Controls visual presentation options for the view.\n *\n * @see Airtable Interface → \"Appearance\" panel\n */\nexport const AppearanceConfigSchema = z.object({\n showDescription: z.boolean().default(true).describe('Show the view description text'),\n allowedVisualizations: z.array(VisualizationTypeSchema).optional()\n .describe('Whitelist of visualization types users can switch between (e.g. [\"grid\", \"gallery\", \"kanban\"])'),\n}).describe('Appearance and visualization configuration');\n\n/**\n * View Tab Schema (Airtable Interface parity)\n * Defines a tab in a multi-tab view interface.\n * Each tab references a named list view and can be ordered, pinned, or set as default.\n *\n * @see Airtable Interface → \"Tabs\" panel\n */\nexport const ViewTabSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Tab identifier (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label'),\n icon: z.string().optional().describe('Tab icon name'),\n view: z.string().optional().describe('Referenced list view name from listViews'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Tab-specific filter criteria'),\n order: z.number().int().min(0).optional().describe('Tab display order'),\n pinned: z.boolean().default(false).describe('Pin tab (cannot be removed by users)'),\n isDefault: z.boolean().default(false).describe('Set as the default active tab'),\n visible: z.boolean().default(true).describe('Tab visibility'),\n}).describe('Tab configuration for multi-tab view interface');\n\n/**\n * Add Record Configuration Schema (Airtable Interface parity)\n * Configures the \"Add Record\" entry point for a list view.\n *\n * @see Airtable Interface → \"+ Add record\" button\n */\nexport const AddRecordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Show the add record entry point'),\n position: z.enum(['top', 'bottom', 'both']).default('bottom').describe('Position of the add record button'),\n mode: z.enum(['inline', 'form', 'modal']).default('inline').describe('How to add a new record'),\n formView: z.string().optional().describe('Named form view to use when mode is \"form\" or \"modal\"'),\n}).describe('Add record entry point configuration');\n\n/**\n * Kanban Settings\n */\nexport const KanbanConfigSchema = z.object({\n groupByField: z.string().describe('Field to group columns by (usually status/select)'),\n summarizeField: z.string().optional().describe('Field to sum at top of column (e.g. amount)'),\n columns: z.array(z.string()).describe('Fields to show on cards'),\n});\n\n/**\n * Calendar Settings\n */\nexport const CalendarConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string().optional(),\n titleField: z.string(),\n colorField: z.string().optional(),\n});\n\n/**\n * Gantt Settings\n */\nexport const GanttConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string(),\n titleField: z.string(),\n progressField: z.string().optional(),\n dependenciesField: z.string().optional(),\n});\n\n/**\n * Navigation Mode Enum\n * Defines how to navigate to the detail view from a list item.\n */\nexport const NavigationModeSchema = z.enum([\n 'page', // Navigate to a new route (default)\n 'drawer', // Open details in a side drawer/panel\n 'modal', // Open details in a modal dialog\n 'split', // Show details side-by-side with the list (master-detail)\n 'popover', // Show details in a popover (lightweight)\n 'new_window', // Open in new browser tab/window\n 'none' // No navigation (read-only list)\n]);\n\n/**\n * Navigation Configuration Schema\n */\nexport const NavigationConfigSchema = z.object({\n mode: NavigationModeSchema.default('page'),\n \n /** Target View Config */\n view: z.string().optional().describe('Name of the form view to use for details (e.g. \"summary_view\", \"edit_form\")'),\n \n /** Interaction Triggers */\n preventNavigation: z.boolean().default(false).describe('Disable standard navigation entirely'),\n openNewTab: z.boolean().default(false).describe('Force open in new tab (applies to page mode)'),\n \n /** Dimensions (for modal/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Width of the drawer/modal (e.g. \"600px\", \"50%\")'),\n});\n\n/**\n * List View Schema (Expanded)\n * Defines how a collection of records is displayed to the user.\n * \n * **NAMING CONVENTION:**\n * View names (when provided) are machine identifiers and must be lowercase snake_case.\n * \n * @example Standard Grid\n * {\n * name: \"all_active\",\n * label: \"All Active\",\n * type: \"grid\",\n * columns: [\"name\", \"status\", \"created_at\"],\n * filter: [[\"status\", \"=\", \"active\"]]\n * }\n * \n * @example Kanban Board\n * {\n * type: \"kanban\",\n * columns: [\"name\", \"amount\"],\n * kanban: {\n * groupByField: \"stage\",\n * summarizeField: \"amount\",\n * columns: [\"name\", \"close_date\"]\n * }\n * }\n */\nexport const ListViewSchema = z.object({\n name: SnakeCaseIdentifierSchema.optional().describe('Internal view name (lowercase snake_case)'),\n label: I18nLabelSchema.optional(), // Display label override (supports i18n)\n type: z.enum([\n 'grid', // Standard Data Table\n 'kanban', // Board / Columns\n 'gallery', // Card Deck / Masonry\n 'calendar', // Monthly/Weekly/Daily\n 'timeline', // Chronological Stream (Feed)\n 'gantt', // Project Timeline\n 'map' // Geospatial\n ]).default('grid'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n /** Shared Query Config */\n columns: z.union([\n z.array(z.string()), // Legacy: simple field names\n z.array(ListColumnSchema), // Enhanced: detailed column config\n ]).describe('Fields to display as columns'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Filter criteria (JSON Rules)'),\n sort: z.union([\n z.string(), //Legacy \"field desc\"\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional(),\n \n /** Search & Filter */\n searchableFields: z.array(z.string()).optional().describe('Fields enabled for search'),\n filterableFields: z.array(z.string()).optional().describe('Fields enabled for end-user filtering in the top bar'),\n\n /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */\n quickFilters: z.array(z.object({\n field: z.string().describe('Field name to filter by'),\n label: z.string().optional().describe('Display label for the chip'),\n operator: z.enum(['equals', 'not_equals', 'contains', 'in', 'is_null', 'is_not_null']).default('equals').describe('Filter operator'),\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Preset filter value'),\n })).optional().describe('One-click filter chips for quick record filtering'),\n\n /** Grid Features */\n resizable: z.boolean().optional().describe('Enable column resizing'),\n striped: z.boolean().optional().describe('Striped row styling'),\n bordered: z.boolean().optional().describe('Show borders'),\n\n /** Selection */\n selection: SelectionConfigSchema.optional().describe('Row selection configuration'),\n\n /** Navigation / Interaction */\n navigation: NavigationConfigSchema.optional().describe('Configuration for item click navigation (page, drawer, modal, etc.)'),\n\n /** Pagination */\n pagination: PaginationConfigSchema.optional().describe('Pagination configuration'),\n\n /** Type Specific Config */\n kanban: KanbanConfigSchema.optional(),\n calendar: CalendarConfigSchema.optional(),\n gantt: GanttConfigSchema.optional(),\n gallery: GalleryConfigSchema.optional(),\n timeline: TimelineConfigSchema.optional(),\n\n /** View Metadata (Airtable-style view management) */\n description: I18nLabelSchema.optional().describe('View description for documentation/tooltips'),\n sharing: ViewSharingSchema.optional().describe('View sharing and access configuration'),\n\n /** Row Height / Density (Airtable-style) */\n rowHeight: RowHeightSchema.optional().describe('Row height / density setting'),\n\n /** Record Grouping (Airtable-style) */\n grouping: GroupingConfigSchema.optional().describe('Group records by one or more fields'),\n\n /** Row Color (Airtable-style) */\n rowColor: RowColorConfigSchema.optional().describe('Color rows based on field value'),\n\n /** Field Visibility & Ordering per View (Airtable-style) */\n hiddenFields: z.array(z.string()).optional().describe('Fields to hide in this specific view'),\n fieldOrder: z.array(z.string()).optional().describe('Explicit field display order for this view'),\n\n /** Row & Bulk Actions */\n rowActions: z.array(z.string()).optional().describe('Actions available for individual row items'),\n bulkActions: z.array(z.string()).optional().describe('Actions available when multiple rows are selected'),\n\n /** Performance */\n virtualScroll: z.boolean().optional().describe('Enable virtual scrolling for large datasets'),\n\n /** Conditional Formatting */\n conditionalFormatting: z.array(z.object({\n condition: z.string().describe('Condition expression to evaluate'),\n style: z.record(z.string(), z.string()).describe('CSS styles to apply when condition is true'),\n })).optional().describe('Conditional formatting rules for list rows'),\n\n /** Inline Edit */\n inlineEdit: z.boolean().optional().describe('Allow inline editing of records directly in the list view'),\n\n /** Export */\n exportOptions: z.array(z.enum(['csv', 'xlsx', 'pdf', 'json'])).optional().describe('Available export format options'),\n\n /** User Actions (Airtable Interface parity) */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles for the view toolbar'),\n\n /** Appearance (Airtable Interface parity) */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** Tabs (Airtable Interface parity) */\n tabs: z.array(ViewTabSchema).optional().describe('Tab definitions for multi-tab view interface'),\n\n /** Add Record (Airtable Interface parity) */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record Count Display (Airtable Interface parity) */\n showRecordCount: z.boolean().optional().describe('Show record count at the bottom of the list'),\n\n /** Advanced: Allow Printing (Airtable Interface parity) */\n allowPrinting: z.boolean().optional().describe('Allow users to print the view'),\n\n /** Empty State */\n emptyState: z.object({\n title: I18nLabelSchema.optional(),\n message: I18nLabelSchema.optional(),\n icon: z.string().optional(),\n }).optional().describe('Empty state configuration when no records found'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the list view'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Form Field Configuration Schema\n * Detailed configuration for individual form fields\n */\nexport const FormFieldSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n helpText: I18nLabelSchema.optional().describe('Help/hint text'),\n readonly: z.boolean().optional().describe('Read-only override'),\n required: z.boolean().optional().describe('Required override'),\n hidden: z.boolean().optional().describe('Hidden override'),\n colSpan: z.number().int().min(1).max(4).optional().describe('Column span in grid layout (1-4)'),\n widget: z.string().optional().describe('Custom widget/component name'),\n dependsOn: z.string().optional().describe('Parent field name for cascading'),\n visibleOn: z.string().optional().describe('Visibility condition expression'),\n});\n\n/**\n * Form Layout Section\n */\nexport const FormSectionSchema = z.object({\n label: I18nLabelSchema.optional(),\n collapsible: z.boolean().default(false),\n collapsed: z.boolean().default(false),\n columns: z.enum(['1', '2', '3', '4']).default('2').transform(val => parseInt(val) as 1 | 2 | 3 | 4),\n fields: z.array(z.union([\n z.string(), // Legacy: simple field name\n FormFieldSchema, // Enhanced: detailed field config\n ])),\n});\n\n/**\n * Form View Schema\n * Defines the layout for creating or editing a single record.\n * \n * @example Simple Sectioned Form\n * {\n * type: \"simple\",\n * sections: [\n * {\n * label: \"General Info\",\n * columns: 2,\n * fields: [\"name\", \"status\"]\n * },\n * {\n * label: \"Details\",\n * fields: [\"description\", { field: \"priority\", widget: \"rating\" }]\n * }\n * ]\n * }\n */\nexport const FormViewSchema = z.object({\n type: z.enum([\n 'simple', // Single column or sections\n 'tabbed', // Tabs\n 'wizard', // Step by step\n 'split', // Master-Detail split\n 'drawer', // Side panel\n 'modal' // Dialog\n ]).default('simple'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n sections: z.array(FormSectionSchema).optional(), // For simple layout\n groups: z.array(FormSectionSchema).optional(), // Legacy support -> alias to sections\n\n /** Default Sort for Related Lists (e.g., sort child records by date) */\n defaultSort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n order: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n })).optional().describe('Default sort order for related list views within this form'),\n\n /** Public form sharing configuration */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration for this form'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the form view'),\n});\n\n/**\n * Master View Schema\n * Can define multiple named views.\n */\n/**\n * View Container Schema\n * Aggregates all view definitions for a specific object or context.\n * \n * @example\n * {\n * list: { type: \"grid\", columns: [\"name\"] },\n * form: { type: \"simple\", fields: [\"name\"] },\n * listViews: {\n * \"all\": { label: \"All\", filter: [] },\n * \"my\": { label: \"Mine\", filter: [[\"owner\", \"=\", \"{user_id}\"]] }\n * }\n * }\n */\nexport const ViewSchema = z.object({\n list: ListViewSchema.optional(), // Default list view\n form: FormViewSchema.optional(), // Default form view\n listViews: z.record(z.string(), ListViewSchema).optional().describe('Additional named list views'),\n formViews: z.record(z.string(), FormViewSchema).optional().describe('Additional named form views'),\n});\n\n/**\n * Type-safe factory for creating view definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const taskViews = defineView({\n * list: {\n * type: 'grid',\n * data: { provider: 'object', object: 'task' },\n * columns: ['subject', 'status', 'priority', 'due_date'],\n * },\n * form: {\n * type: 'simple',\n * sections: [{ label: 'Details', fields: [{ field: 'subject' }] }],\n * },\n * });\n * ```\n */\nexport function defineView(config: z.input): View {\n return ViewSchema.parse(config);\n}\n\nexport type View = z.infer;\nexport type ListView = z.infer;\nexport type FormView = z.infer;\nexport type FormSection = z.infer;\nexport type ListColumn = z.infer;\nexport type FormField = z.infer;\nexport type SelectionConfig = z.infer;\nexport type NavigationConfig = z.infer;\nexport type PaginationConfig = z.infer;\nexport type ViewData = z.infer;\nexport type HttpRequest = z.infer;\nexport type HttpMethod = z.infer;\nexport type ColumnSummary = z.infer;\nexport type RowHeight = z.infer;\nexport type GroupingConfig = z.infer;\nexport type GalleryConfig = z.infer;\nexport type TimelineConfig = z.infer;\nexport type ViewSharing = z.infer;\nexport type RowColorConfig = z.infer;\nexport type VisualizationType = z.infer;\nexport type UserActionsConfig = z.infer;\nexport type AppearanceConfig = z.infer;\nexport type ViewTab = z.infer;\nexport type AddRecordConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Query DSL Specification\n * \n * Based on industry best practices from:\n * - Prisma ORM\n * - Strapi CMS\n * - TypeORM\n * - LoopBack Framework\n * \n * Version: 1.0.0\n * Status: Draft\n * \n * Objective: Define a JSON-based, database-agnostic query syntax standard\n * for data filtering interactions between frontend and backend APIs.\n * \n * Design Principles:\n * 1. Declarative: Frontend describes \"what data to get\", not \"how to query\"\n * 2. Database Agnostic: Syntax contains no database-specific directives\n * 3. Type Safe: Structure can be statically inferred by TypeScript\n * 4. Convention over Configuration: Implicit syntax for common queries\n */\n\n/**\n * Field Reference\n * Represents a reference to another field/column instead of a literal value.\n * Used for joins (ON clause) and cross-field comparisons.\n * \n * @example\n * // user.id = order.owner_id\n * { \"$eq\": { \"$field\": \"order.owner_id\" } }\n */\nexport const FieldReferenceSchema = z.object({\n $field: z.string().describe('Field Reference/Column Name')\n});\n\nexport type FieldReference = z.infer;\n\n// ============================================================================\n// 3.1 Comparison Operators\n// ============================================================================\n\n/**\n * Comparison operators for equality and inequality checks.\n * Supported data types: Any\n */\nexport const EqualityOperatorSchema = z.object({\n /** Equal to (default) - SQL: = | MongoDB: $eq */\n $eq: z.any().optional(),\n \n /** Not equal to - SQL: <> or != | MongoDB: $ne */\n $ne: z.any().optional(),\n});\n\n/**\n * Comparison operators for numeric and date comparisons.\n * Supported data types: Number, Date\n */\nexport const ComparisonOperatorSchema = z.object({\n /** Greater than - SQL: > | MongoDB: $gt */\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Greater than or equal to - SQL: >= | MongoDB: $gte */\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than - SQL: < | MongoDB: $lt */\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than or equal to - SQL: <= | MongoDB: $lte */\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n});\n\n// ============================================================================\n// 3.2 Set & Range Operators\n// ============================================================================\n\n/**\n * Set operators for membership checks.\n */\nexport const SetOperatorSchema = z.object({\n /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */\n $in: z.array(z.any()).optional(),\n \n /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */\n $nin: z.array(z.any()).optional(),\n});\n\n/**\n * Range operator for interval checks (closed interval).\n * SQL: BETWEEN ? AND ? | MongoDB: $gte AND $lte\n */\nexport const RangeOperatorSchema = z.object({\n /** Between (inclusive) - takes [min, max] array */\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n});\n\n// ============================================================================\n// 3.3 String-Specific Operators\n// ============================================================================\n\n/**\n * String pattern matching operators.\n * Note: Case sensitivity should be handled at backend level.\n */\nexport const StringOperatorSchema = z.object({\n /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */\n $contains: z.string().optional(),\n \n /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */\n $notContains: z.string().optional(),\n \n /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */\n $startsWith: z.string().optional(),\n \n /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */\n $endsWith: z.string().optional(),\n});\n\n// ============================================================================\n// 3.5 Special Operators\n// ============================================================================\n\n/**\n * Special check operators for null and existence.\n */\nexport const SpecialOperatorSchema = z.object({\n /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */\n $null: z.boolean().optional(),\n \n /** Field exists check (primarily for NoSQL) - MongoDB: $exists */\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// Combined Field Operators\n// ============================================================================\n\n/**\n * All field-level operators combined.\n * These can be applied to individual fields in a filter.\n */\nexport const FieldOperatorsSchema = z.object({\n // Equality\n $eq: z.any().optional(),\n $ne: z.any().optional(),\n \n // Comparison (numeric/date)\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n // Set & Range\n $in: z.array(z.any()).optional(),\n $nin: z.array(z.any()).optional(),\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n \n // String-specific\n $contains: z.string().optional(),\n $notContains: z.string().optional(),\n $startsWith: z.string().optional(),\n $endsWith: z.string().optional(),\n \n // Special\n $null: z.boolean().optional(),\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// 3.4 Logical Operators & Recursive Filter Structure\n// ============================================================================\n\n/**\n * Recursive filter type that supports:\n * 1. Implicit equality: { field: value }\n * 2. Explicit operators: { field: { $op: value } }\n * 3. Logical combinations: { $and: [...], $or: [...], $not: {...} }\n * 4. Nested relations: { relation: { field: value } }\n */\nexport type FilterCondition = {\n [key: string]: \n | any // Implicit equality: key: value\n | z.infer // Explicit operators: key: { $op: value }\n | FilterCondition; // Nested relation: key: { nested: ... }\n} & {\n /** Logical AND - combines all conditions that must be true */\n $and?: FilterCondition[];\n \n /** Logical OR - at least one condition must be true */\n $or?: FilterCondition[];\n \n /** Logical NOT - negates the condition */\n $not?: FilterCondition;\n};\n\n/**\n * Zod schema for recursive filter validation.\n * Uses z.lazy() to handle recursive structure.\n */\nexport const FilterConditionSchema: z.ZodType = z.lazy(() =>\n z.record(z.string(), z.unknown()).and(\n z.object({\n $and: z.array(FilterConditionSchema).optional(),\n $or: z.array(FilterConditionSchema).optional(),\n $not: FilterConditionSchema.optional(),\n })\n )\n);\n\n// ============================================================================\n// Query Filter Wrapper\n// ============================================================================\n\n/**\n * Top-level query filter wrapper.\n * This is typically used as the \"where\" clause in a query.\n * \n * @example\n * ```typescript\n * const filter: QueryFilter = {\n * where: {\n * status: \"active\", // Implicit equality\n * age: { $gte: 18 }, // Explicit operator\n * $or: [ // Logical combination\n * { role: \"admin\" },\n * { email: { $contains: \"@company.com\" } }\n * ],\n * profile: { // Nested relation\n * verified: true\n * }\n * }\n * }\n * ```\n */\nexport const QueryFilterSchema = z.object({\n where: FilterConditionSchema.optional(),\n});\n\n// ============================================================================\n// TypeScript Type Exports\n// ============================================================================\n\n/**\n * Type-safe filter operators for use in TypeScript.\n * \n * @example\n * ```typescript\n * type UserFilter = Filter;\n * \n * const filter: UserFilter = {\n * age: { $gte: 18 },\n * email: { $contains: \"@example.com\" }\n * };\n * ```\n */\nexport type Filter = {\n [K in keyof T]?: \n | T[K] // Implicit equality\n | {\n $eq?: T[K];\n $ne?: T[K];\n $gt?: T[K] extends number | Date ? T[K] : never;\n $gte?: T[K] extends number | Date ? T[K] : never;\n $lt?: T[K] extends number | Date ? T[K] : never;\n $lte?: T[K] extends number | Date ? T[K] : never;\n $in?: T[K][];\n $nin?: T[K][];\n $between?: T[K] extends number | Date ? [T[K], T[K]] : never;\n $contains?: T[K] extends string ? string : never;\n $notContains?: T[K] extends string ? string : never;\n $startsWith?: T[K] extends string ? string : never;\n $endsWith?: T[K] extends string ? string : never;\n $null?: boolean;\n $exists?: boolean;\n }\n | (T[K] extends object ? Filter : never); // Nested relation\n} & {\n $and?: Filter[];\n $or?: Filter[];\n $not?: Filter;\n};\n\n/**\n * Scalar types supported by the filter system.\n */\nexport type Scalar = string | number | boolean | Date | null;\n\n// Export inferred types\nexport type FieldOperators = z.infer;\nexport type QueryFilter = z.infer;\n\n// ============================================================================\n// Normalization Utilities (Internal Representation)\n// ============================================================================\n\n/**\n * Normalized filter AST structure.\n * This is the internal representation after converting all syntactic sugar\n * to explicit operators.\n * \n * Stage 1: Normalization Pass\n * Input: { age: 18, role: \"admin\" }\n * Output: { $and: [{ age: { $eq: 18 } }, { role: { $eq: \"admin\" } }] }\n * \n * This simplifies adapter implementation by providing a consistent structure.\n */\nexport const NormalizedFilterSchema: z.ZodType = z.lazy(() => \n z.object({\n $and: z.array(\n z.union([\n // Field condition: { field: { $op: value } }\n z.record(z.string(), FieldOperatorsSchema),\n // Nested logical group\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $or: z.array(\n z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $not: z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ]).optional(),\n })\n);\n\nexport type NormalizedFilter = z.infer;\n\n// ============================================================================\n// AST Array Format Detection & Validation\n// ============================================================================\n\n/**\n * Set of valid AST comparison operators (case-insensitive).\n * Used by `isFilterAST()` to validate AST structure beyond `Array.isArray`.\n */\nexport const VALID_AST_OPERATORS = new Set([\n '=', '==', '!=', '<>', '>', '>=', '<', '<=',\n 'in', 'nin', 'not_in',\n 'contains', 'notcontains', 'not_contains', 'like',\n 'startswith', 'starts_with',\n 'endswith', 'ends_with',\n 'between',\n 'is_null', 'is_not_null',\n]);\n\n/**\n * Detect whether a value is a valid Filter AST array structure.\n *\n * A valid AST is one of:\n * - Comparison node: `[field: string, operator: string, value: unknown]` where operator is a known operator\n * - Logical node: `[\"and\" | \"or\", ...children]` where children are valid AST nodes\n * - Legacy flat array: `[[cond], [cond], ...]` where all elements are sub-arrays (each a valid AST node)\n *\n * This replaces the naïve `Array.isArray(filter)` check, preventing accidental\n * misidentification of arbitrary arrays as filter ASTs.\n *\n * @example\n * isFilterAST([\"status\", \"=\", \"active\"]) // true\n * isFilterAST([\"and\", [\"a\", \"=\", 1], [\"b\", \">\", 2]]) // true\n * isFilterAST([[\"a\", \"=\", 1], [\"b\", \"=\", 2]]) // true (legacy)\n * isFilterAST([1, 2, 3]) // false\n * isFilterAST(\"not an array\") // false\n * isFilterAST({ status: \"active\" }) // false\n */\nexport function isFilterAST(filter: unknown): boolean {\n if (!Array.isArray(filter) || filter.length === 0) return false;\n\n const first = filter[0];\n\n // Logical node: [\"and\", ...] or [\"or\", ...]\n if (typeof first === 'string') {\n const lower = first.toLowerCase();\n if (lower === 'and' || lower === 'or') {\n return filter.length >= 2 && filter.slice(1).every((child: unknown) => isFilterAST(child));\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof filter[1] === 'string') {\n return VALID_AST_OPERATORS.has(filter[1].toLowerCase());\n }\n }\n\n // Legacy flat array: [[cond], [cond], ...]\n if (filter.every((item: unknown) => isFilterAST(item))) {\n return filter.length > 0;\n }\n\n return false;\n}\n\n// ============================================================================\n// AST Array → FilterCondition Conversion\n// ============================================================================\n\n/**\n * Operator mapping from AST infix operators to FilterCondition `$`-prefixed operators.\n */\nconst AST_OPERATOR_MAP: Record = {\n '=': '$eq',\n '==': '$eq',\n '!=': '$ne',\n '<>': '$ne',\n '>': '$gt',\n '>=': '$gte',\n '<': '$lt',\n '<=': '$lte',\n 'in': '$in',\n 'nin': '$nin',\n 'not_in': '$nin',\n 'contains': '$contains',\n 'notcontains': '$notContains',\n 'not_contains': '$notContains',\n 'like': '$contains',\n 'startswith': '$startsWith',\n 'starts_with': '$startsWith',\n 'endswith': '$endsWith',\n 'ends_with': '$endsWith',\n 'between': '$between',\n 'is_null': '$null',\n 'is_not_null': '$null',\n};\n\n/**\n * Convert a single AST comparison node `[field, operator, value]` to a FilterCondition object.\n */\nfunction convertComparison(node: [string, string, unknown]): FilterCondition {\n const [field, operator, value] = node;\n const op = operator.toLowerCase();\n\n // Special case: equality shorthand\n if (op === '=' || op === '==') {\n return { [field]: value } as FilterCondition;\n }\n\n // Null check operators\n if (op === 'is_null') {\n return { [field]: { $null: true } } as FilterCondition;\n }\n if (op === 'is_not_null') {\n return { [field]: { $null: false } } as FilterCondition;\n }\n\n const mapped = AST_OPERATOR_MAP[op];\n if (mapped) {\n return { [field]: { [mapped]: value } } as FilterCondition;\n }\n\n // Fallback: use the operator as-is with $ prefix\n return { [field]: { [`$${op}`]: value } } as FilterCondition;\n}\n\n/**\n * Parse a filter from AST array format to FilterCondition object format.\n *\n * The AST array format is used by the ObjectUI client and the `FilterBuilder`:\n * - Comparison: `[field, operator, value]` → `{ field: value }` or `{ field: { $op: value } }`\n * - Logical AND: `[\"and\", cond1, cond2, ...]` → `{ $and: [...] }`\n * - Logical OR: `[\"or\", cond1, cond2, ...]` → `{ $or: [...] }`\n *\n * If the input is already a FilterCondition object (not an array), it is returned as-is.\n * If the input is `null` or `undefined`, it is returned as-is.\n *\n * @example\n * // Simple condition\n * parseFilterAST([\"status\", \"=\", \"active\"])\n * // → { status: \"active\" }\n *\n * @example\n * // Compound AND\n * parseFilterAST([\"and\", [\"priority\", \"=\", \"high\"], [\"status\", \"=\", \"active\"]])\n * // → { $and: [{ priority: \"high\" }, { status: \"active\" }] }\n *\n * @example\n * // Object passthrough\n * parseFilterAST({ status: \"active\" })\n * // → { status: \"active\" }\n */\nexport function parseFilterAST(filter: unknown): FilterCondition | undefined {\n if (filter == null) return undefined;\n if (!Array.isArray(filter)) return filter as FilterCondition;\n if (filter.length === 0) return undefined;\n\n const first = filter[0];\n\n // Logical node: [\"and\", cond1, cond2, ...] or [\"or\", cond1, cond2, ...]\n if (typeof first === 'string' && (first.toLowerCase() === 'and' || first.toLowerCase() === 'or')) {\n const logicOp = `$${first.toLowerCase()}` as '$and' | '$or';\n const children = filter.slice(1).map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { [logicOp]: children } as FilterCondition;\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof first === 'string') {\n return convertComparison(filter as [string, string, unknown]);\n }\n\n // Legacy flat array: [[field, op, val], [field, op, val], ...]\n // All elements are sub-arrays → treat as implicit AND\n if (filter.every((item: unknown) => Array.isArray(item))) {\n const children = filter.map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { $and: children } as FilterCondition;\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Constants & Metadata\n// ============================================================================\n\n/**\n * All supported operator keys.\n * Useful for validation and parsing.\n */\nexport const FILTER_OPERATORS = [\n // Equality\n '$eq', '$ne',\n // Comparison\n '$gt', '$gte', '$lt', '$lte',\n // Set & Range\n '$in', '$nin', '$between',\n // String\n '$contains', '$notContains', '$startsWith', '$endsWith',\n // Special\n '$null', '$exists',\n] as const;\n\n/**\n * Logical operator keys.\n */\nexport const LOGICAL_OPERATORS = ['$and', '$or', '$not'] as const;\n\n/**\n * All operator keys (field + logical).\n */\nexport const ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS] as const;\n\nexport type FilterOperatorKey = typeof FILTER_OPERATORS[number];\nexport type LogicalOperatorKey = typeof LOGICAL_OPERATORS[number];\nexport type OperatorKey = typeof ALL_OPERATORS[number];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ChartTypeSchema, ChartConfigSchema } from './chart.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Color variant for dashboard widgets (e.g., KPI cards).\n */\nexport const WidgetColorVariantSchema = z.enum([\n 'default',\n 'blue',\n 'teal',\n 'orange',\n 'purple',\n 'success',\n 'warning',\n 'danger',\n]).describe('Widget color variant');\n\n/**\n * Action type for widget action buttons.\n */\nexport const WidgetActionTypeSchema = z.enum([\n 'script',\n 'url',\n 'modal',\n 'flow',\n 'api',\n]).describe('Widget action type');\n\n/**\n * Dashboard Header Action Schema\n * An action button displayed in the dashboard header area.\n */\nexport const DashboardHeaderActionSchema = z.object({\n /** Action label */\n label: I18nLabelSchema.describe('Action button label'),\n\n /** Action URL or target */\n actionUrl: z.string().describe('URL or target for the action'),\n\n /** Action type */\n actionType: WidgetActionTypeSchema.optional().describe('Type of action'),\n\n /** Icon identifier */\n icon: z.string().optional().describe('Icon identifier for the action button'),\n}).describe('Dashboard header action');\n\n/**\n * Dashboard Header Schema\n * Structured header configuration for the dashboard.\n */\nexport const DashboardHeaderSchema = z.object({\n /** Whether to show the dashboard title in the header */\n showTitle: z.boolean().default(true).describe('Show dashboard title in header'),\n\n /** Whether to show the dashboard description in the header */\n showDescription: z.boolean().default(true).describe('Show dashboard description in header'),\n\n /** Action buttons displayed in the header */\n actions: z.array(DashboardHeaderActionSchema).optional().describe('Header action buttons'),\n}).describe('Dashboard header configuration');\n\n/**\n * Widget Measure Schema\n * A single measure definition for multi-measure pivot/matrix widgets.\n */\nexport const WidgetMeasureSchema = z.object({\n /** Value field to aggregate */\n valueField: z.string().describe('Field to aggregate'),\n\n /** Aggregate function */\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max']).default('count').describe('Aggregate function'),\n\n /** Display label for the measure */\n label: I18nLabelSchema.optional().describe('Measure display label'),\n\n /** Number format string (e.g., \"$0,0.00\", \"0.0%\") */\n format: z.string().optional().describe('Number format string'),\n}).describe('Widget measure definition');\n\n/**\n * Dashboard Widget Schema\n * A single component on the dashboard grid.\n */\nexport const DashboardWidgetSchema = z.object({\n /** Unique widget identifier (snake_case, used for targetWidgets references) */\n id: SnakeCaseIdentifierSchema.describe('Unique widget identifier (snake_case)'),\n\n /** Widget Title */\n title: I18nLabelSchema.optional().describe('Widget title'),\n\n /** Widget Description (displayed below the title) */\n description: I18nLabelSchema.optional().describe('Widget description text below the header'),\n \n /** Visualization Type */\n type: ChartTypeSchema.default('metric').describe('Visualization type'),\n \n /** Chart Configuration */\n chartConfig: ChartConfigSchema.optional().describe('Chart visualization configuration'),\n\n /** Color variant for the widget (e.g., KPI card accent color) */\n colorVariant: WidgetColorVariantSchema.optional().describe('Widget color variant for theming'),\n\n /** Action URL for the widget header action button */\n actionUrl: z.string().optional().describe('URL or target for the widget action button'),\n\n /** Action type for the widget header action button */\n actionType: WidgetActionTypeSchema.optional().describe('Type of action for the widget action button'),\n\n /** Icon for the widget header action button */\n actionIcon: z.string().optional().describe('Icon identifier for the widget action button'),\n \n /** Data Source Object */\n object: z.string().optional().describe('Data source object name'),\n \n /** Data Filter (MongoDB-style FilterCondition) */\n filter: FilterConditionSchema.optional().describe('Data filter criteria'),\n \n /** Category Field (X-Axis / Group By) */\n categoryField: z.string().optional().describe('Field for grouping (X-Axis)'),\n \n /** Value Field (Y-Axis) */\n valueField: z.string().optional().describe('Field for values (Y-Axis)'),\n \n /** Aggregate operation */\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max']).optional().default('count').describe('Aggregate function'),\n \n /** Multi-measure definitions for pivot/matrix widgets */\n measures: z.array(WidgetMeasureSchema).optional().describe('Multiple measures for pivot/matrix analysis'),\n \n /** \n * Layout Position (React-Grid-Layout style)\n * x: column (0-11)\n * y: row\n * w: width (1-12)\n * h: height\n */\n layout: z.object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n }).describe('Grid layout position'),\n \n /** Widget specific options (colors, legend, etc.) */\n options: z.unknown().optional().describe('Widget specific configuration'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * Dynamic options binding for global filters.\n * Allows dropdown options to be fetched from an object at runtime.\n */\nexport const GlobalFilterOptionsFromSchema = z.object({\n /** Source object name to fetch options from */\n object: z.string().describe('Source object name'),\n\n /** Field to use as option value */\n valueField: z.string().describe('Field to use as option value'),\n\n /** Field to use as option label */\n labelField: z.string().describe('Field to use as option label'),\n\n /** Optional filter to apply when fetching options */\n filter: FilterConditionSchema.optional().describe('Filter to apply to source object'),\n}).describe('Dynamic filter options from object');\n\n/**\n * Global Filter Schema\n * Defines a single global filter control for the dashboard filter bar.\n */\nexport const GlobalFilterSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n\n /** Display label for the filter */\n label: I18nLabelSchema.optional().describe('Display label for the filter'),\n\n /** Filter input type */\n type: z.enum(['text', 'select', 'date', 'number', 'lookup']).optional().describe('Filter input type'),\n\n /** Static options for select/lookup filters */\n options: z.array(z.object({\n value: z.union([z.string(), z.number(), z.boolean()]).describe('Option value'),\n label: I18nLabelSchema,\n })).optional().describe('Static filter options'),\n\n /** Dynamic data binding for filter options */\n optionsFrom: GlobalFilterOptionsFromSchema.optional().describe('Dynamic filter options from object'),\n\n /** Default filter value */\n defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional().describe('Default filter value'),\n\n /** Filter application scope */\n scope: z.enum(['dashboard', 'widget']).default('dashboard').describe('Filter application scope'),\n\n /** Widget IDs to apply this filter to (when scope is widget) */\n targetWidgets: z.array(z.string()).optional().describe('Widget IDs to apply this filter to'),\n});\n\n/**\n * Dashboard Schema\n * Represents a page containing multiple visualizations.\n * \n * @example Sales Executive Dashboard\n * {\n * name: \"sales_overview\",\n * label: \"Sales Executive Overview\",\n * widgets: [\n * {\n * title: \"Total Pipe\",\n * type: \"metric\",\n * object: \"opportunity\",\n * valueField: \"amount\",\n * aggregate: \"sum\",\n * layout: { x: 0, y: 0, w: 3, h: 2 }\n * },\n * {\n * title: \"Revenue by Region\",\n * type: \"bar\",\n * object: \"order\",\n * categoryField: \"region\",\n * valueField: \"total\",\n * aggregate: \"sum\",\n * layout: { x: 3, y: 0, w: 6, h: 4 }\n * }\n * ]\n * }\n */\nexport const DashboardSchema = z.object({\n /** Machine name */\n name: SnakeCaseIdentifierSchema.describe('Dashboard unique name'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Dashboard label'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('Dashboard description'),\n\n /** Structured header configuration */\n header: DashboardHeaderSchema.optional().describe('Dashboard header configuration'),\n \n /** Collection of widgets */\n widgets: z.array(DashboardWidgetSchema).describe('Widgets to display'),\n\n /** Auto-refresh */\n refreshInterval: z.number().optional().describe('Auto-refresh interval in seconds'),\n\n /** Dashboard Date Range (Global time filter) */\n dateRange: z.object({\n field: z.string().optional().describe('Default date field name for time-based filtering'),\n defaultRange: z.enum(['today', 'yesterday', 'this_week', 'last_week', 'this_month', 'last_month', 'this_quarter', 'last_quarter', 'this_year', 'last_year', 'last_7_days', 'last_30_days', 'last_90_days', 'custom']).default('this_month').describe('Default date range preset'),\n allowCustomRange: z.boolean().default(true).describe('Allow users to pick a custom date range'),\n }).optional().describe('Global dashboard date range filter configuration'),\n\n /** Global Filters */\n globalFilters: z.array(GlobalFilterSchema).optional().describe('Global filters that apply to all widgets in the dashboard'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\nexport type Dashboard = z.infer;\nexport type DashboardInput = z.input;\nexport type DashboardWidget = z.infer;\nexport type DashboardHeader = z.infer;\nexport type DashboardHeaderAction = z.infer;\nexport type WidgetMeasure = z.infer;\nexport type WidgetColorVariant = z.infer;\nexport type WidgetActionType = z.infer;\nexport type GlobalFilter = z.infer;\nexport type GlobalFilterOptionsFrom = z.infer;\n\n/**\n * Dashboard Factory Helper\n */\nexport const Dashboard = {\n create: (config: z.input): Dashboard => DashboardSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ChartConfigSchema } from './chart.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Report Type Enum\n */\nexport const ReportType = z.enum([\n 'tabular', // Simple list\n 'summary', // Grouped by row\n 'matrix', // Grouped by row and column\n 'joined' // Joined multiple blocks\n]);\n\n/**\n * Report Column Schema\n */\nexport const ReportColumnSchema = z.object({\n field: z.string().describe('Field name'),\n label: I18nLabelSchema.optional().describe('Override label'),\n aggregate: z.enum(['sum', 'avg', 'max', 'min', 'count', 'unique']).optional().describe('Aggregation function'),\n /** Responsive visibility/priority per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive visibility for this column'),\n});\n\n/**\n * Report Grouping Schema\n */\nexport const ReportGroupingSchema = z.object({\n field: z.string().describe('Field to group by'),\n sortOrder: z.enum(['asc', 'desc']).default('asc'),\n dateGranularity: z.enum(['day', 'week', 'month', 'quarter', 'year']).optional().describe('For date fields'),\n});\n\n/**\n * Report Chart Schema\n * Embedded visualization configuration using unified chart taxonomy.\n */\nexport const ReportChartSchema = ChartConfigSchema.extend({\n /** Report-specific chart configuration */\n xAxis: z.string().describe('Grouping field for X-Axis'),\n yAxis: z.string().describe('Summary field for Y-Axis'),\n groupBy: z.string().optional().describe('Additional grouping field'),\n});\n\n/**\n * Report Schema\n * Deep data analysis definition.\n */\nexport const ReportSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Report unique name'),\n label: I18nLabelSchema.describe('Report label'),\n description: I18nLabelSchema.optional(),\n \n /** Data Source */\n objectName: z.string().describe('Primary object'),\n \n /** Report Configuration */\n type: ReportType.default('tabular').describe('Report format type'),\n \n columns: z.array(ReportColumnSchema).describe('Columns to display'),\n \n /** Grouping (for Summary/Matrix) */\n groupingsDown: z.array(ReportGroupingSchema).optional().describe('Row groupings'),\n groupingsAcross: z.array(ReportGroupingSchema).optional().describe('Column groupings (Matrix only)'),\n \n /** Filtering (MongoDB-style FilterCondition) */\n filter: FilterConditionSchema.optional().describe('Filter criteria'),\n \n /** Visualization */\n chart: ReportChartSchema.optional().describe('Embedded chart configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Report Types\n * \n * Note: For configuration/definition contexts, use the Input types (e.g., ReportInput)\n * which allow optional fields with defaults to be omitted.\n */\nexport type Report = z.infer;\nexport type ReportColumn = z.infer;\nexport type ReportGrouping = z.infer;\nexport type ReportChart = z.infer;\n\n/**\n * Input Types for Report Configuration\n * Use these when defining reports in configuration files.\n */\nexport type ReportInput = z.input;\nexport type ReportColumnInput = z.input;\nexport type ReportGroupingInput = z.input;\nexport type ReportChartInput = z.input;\n\n/**\n * Report Factory Helper\n */\nexport const Report = {\n create: (config: ReportInput): Report => ReportSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Shared Enumerations\n// ============================================================================\n\n/** Aggregation functions used across query, data-engine, analytics, field */\nexport const AggregationFunctionEnum = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'percentile', 'median', 'stddev', 'variance',\n]).describe('Standard aggregation functions');\nexport type AggregationFunction = z.infer;\n\n/** Sort direction used across query, data-engine, analytics */\nexport const SortDirectionEnum = z.enum(['asc', 'desc'])\n .describe('Sort order direction');\nexport type SortDirection = z.infer;\n\n/** Reusable sort item — field + direction pair used across views, data sources, filters */\nexport const SortItemSchema = z.object({\n field: z.string().describe('Field name to sort by'),\n order: SortDirectionEnum.describe('Sort direction'),\n}).describe('Sort field and direction pair');\nexport type SortItem = z.infer;\n\n/** CRUD mutation events used across hook, validation, object CDC */\nexport const MutationEventEnum = z.enum([\n 'insert', 'update', 'delete', 'upsert',\n]).describe('Data mutation event types');\nexport type MutationEvent = z.infer;\n\n/** Database isolation levels — unified format */\nexport const IsolationLevelEnum = z.enum([\n 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable', 'snapshot',\n]).describe('Transaction isolation levels (snake_case standard)');\nexport type IsolationLevel = z.infer;\n\n/** Cache eviction strategies */\nexport const CacheStrategyEnum = z.enum(['lru', 'lfu', 'ttl', 'fifo'])\n .describe('Cache eviction strategy');\nexport type CacheStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { SortItemSchema } from '../shared/enums.zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema } from './responsive.zod';\nimport {\n UserActionsConfigSchema,\n AppearanceConfigSchema,\n ViewTabSchema,\n ViewFilterRuleSchema,\n AddRecordConfigSchema,\n} from './view.zod';\n\n/**\n * Page Region Schema\n * A named region in the template where components are dropped.\n */\nexport const PageRegionSchema = z.object({\n name: z.string().describe('Region name (e.g. \"sidebar\", \"main\", \"header\")'),\n width: z.enum(['small', 'medium', 'large', 'full']).optional(),\n components: z.array(z.lazy(() => PageComponentSchema)).describe('Components in this region')\n});\n\n/**\n * Standard Page Component Types\n */\nexport const PageComponentType = z.enum([\n // Structure\n 'page:header', 'page:footer', 'page:sidebar', 'page:tabs', 'page:accordion', 'page:card', 'page:section',\n // Record Context\n 'record:details', 'record:highlights', 'record:related_list', 'record:activity', 'record:chatter', 'record:path',\n // Navigation\n 'app:launcher', 'nav:menu', 'nav:breadcrumb',\n // Utility\n 'global:search', 'global:notifications', 'user:profile',\n // AI\n 'ai:chat_window', 'ai:suggestion',\n // Content Elements (Airtable Interface parity)\n 'element:text', 'element:number', 'element:image', 'element:divider',\n // Interactive Elements (Phase B — Element Library)\n 'element:button', 'element:filter', 'element:form', 'element:record_picker'\n]);\n\n/**\n * Element Data Source Schema\n * Per-element data binding for multi-object pages.\n * Overrides page-level object context so each element can query a different object.\n */\nexport const ElementDataSourceSchema = z.object({\n object: z.string().describe('Object to query'),\n view: z.string().optional().describe('Named view to apply'),\n filter: FilterConditionSchema.optional().describe('Additional filter criteria'),\n sort: z.array(SortItemSchema).optional().describe('Sort order'),\n limit: z.number().int().positive().optional().describe('Max records to display'),\n});\n\n/**\n * Page Component Schema\n * A configured instance of a UI component.\n */\nexport const PageComponentSchema = z.object({\n /** Definition */\n type: z.union([\n PageComponentType,\n z.string()\n ]).describe('Component Type (Standard enum or custom string)'),\n id: z.string().optional().describe('Unique instance ID'),\n \n /** Configuration */\n label: I18nLabelSchema.optional(),\n properties: z.record(z.string(), z.unknown()).describe('Component props passed to the widget. See component.zod.ts for schemas.'),\n \n /** \n * Event Handlers \n * Map event names to Action expressions.\n * \"onClick\": \"set_variable('userId', $event.id)\"\n * \"onRowSelect\": \"navigate_to('page_detail', { id: $event.id })\"\n */\n events: z.record(z.string(), z.string()).optional().describe('Event handlers map'),\n\n /** Appearance */\n style: z.record(z.string(), z.string()).optional().describe('Inline styles or utility classes'),\n className: z.string().optional().describe('CSS class names'),\n\n /** Visibility Rule */\n visibility: z.string().optional().describe('Visibility filter/formula'),\n\n /** Per-element data binding, overrides page-level object context */\n dataSource: ElementDataSourceSchema.optional().describe('Per-element data binding for multi-object pages'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * Page Variable Schema\n * Defines local state for the page.\n * Variables can be bound to interactive elements (e.g. element:record_picker, element:filter).\n */\nexport const PageVariableSchema = z.object({\n name: z.string().describe('Variable name'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array', 'record_id']).default('string'),\n defaultValue: z.unknown().optional(),\n /** Source element binding (e.g. element:record_picker writes to this variable) */\n source: z.string().optional().describe('Component ID that writes to this variable'),\n});\n\n/**\n * Blank Page Layout Item Schema\n * Positions a component on a free-form grid canvas.\n */\nexport const BlankPageLayoutItemSchema = z.object({\n componentId: z.string().describe('Reference to a PageComponent.id in the page'),\n x: z.number().int().min(0).describe('Grid column position (0-based)'),\n y: z.number().int().min(0).describe('Grid row position (0-based)'),\n width: z.number().int().min(1).describe('Width in grid columns'),\n height: z.number().int().min(1).describe('Height in grid rows'),\n});\n\n/**\n * Blank Page Layout Schema\n * Free-form canvas composition with grid-based positioning.\n * Used when page type is 'blank' to enable drag-and-drop element placement.\n */\nexport const BlankPageLayoutSchema = z.object({\n columns: z.number().int().min(1).default(12).describe('Number of grid columns'),\n rowHeight: z.number().int().min(1).default(40).describe('Height of each grid row in pixels'),\n gap: z.number().int().min(0).default(8).describe('Gap between grid items in pixels'),\n items: z.array(BlankPageLayoutItemSchema).describe('Positioned components on the canvas'),\n});\n\n/**\n * Page Type Schema\n * Unified page type enum covering both platform pages (Salesforce FlexiPage style)\n * and Airtable-inspired interface page types.\n *\n * **Disambiguation of similar types:**\n * - `record` vs `record_detail`: `record` is a component-based layout page (FlexiPage style with regions),\n * `record_detail` is a field-display page showing all fields of a single record (Airtable style).\n * Use `record` for custom record pages with regions/components, `record_detail` for auto-generated detail views.\n * - `home` vs `overview`: `home` is the platform-level landing page (tab landing),\n * `overview` is an interface-level navigation hub with links/instructions.\n * Use `home` for app-level landing, `overview` for in-interface navigation hubs.\n * - `app` vs `utility` vs `blank`: `app` is an app-level page with navigation context,\n * `utility` is a floating utility panel (e.g. notes, phone), `blank` is a free-form canvas\n * for custom composition. They serve distinct layout purposes.\n */\nexport const PageTypeSchema = z.enum([\n // Platform page types (Salesforce FlexiPage style)\n 'record', // Component-based record layout page with regions\n 'home', // Platform-level home/landing page\n 'app', // App-level page with navigation context\n 'utility', // Floating utility panel (e.g. notes, phone dialer)\n // Interface page types (Airtable Interface parity)\n 'dashboard', // KPI summary with charts/metrics\n 'grid', // Spreadsheet-like data table\n 'list', // Record list with quick actions\n 'gallery', // Card-based visual browsing\n 'kanban', // Status-based board\n 'calendar', // Date-based scheduling\n 'timeline', // Gantt-like project timeline\n 'form', // Data entry form\n 'record_detail', // Auto-generated single record field display\n 'record_review', // Sequential record review/approval\n 'overview', // Interface-level navigation/landing hub\n 'blank', // Free-form canvas for custom composition\n]).describe('Page type — platform or interface page types');\n\n/**\n * Record Review Config Schema\n * Configuration for a sequential record review/approval page.\n * Users navigate through records one-by-one, taking actions (approve/reject/skip).\n * Only applicable when page type is 'record_review'.\n */\nexport const RecordReviewConfigSchema = z.object({\n object: z.string().describe('Target object for review'),\n filter: FilterConditionSchema.optional().describe('Filter criteria for review queue'),\n sort: z.array(SortItemSchema).optional().describe('Sort order for review queue'),\n displayFields: z.array(z.string()).optional()\n .describe('Fields to display on the review page'),\n actions: z.array(z.object({\n label: z.string().describe('Action button label'),\n type: z.enum(['approve', 'reject', 'skip', 'custom'])\n .describe('Action type'),\n field: z.string().optional()\n .describe('Field to update on action'),\n value: z.union([z.string(), z.number(), z.boolean()]).optional()\n .describe('Value to set on action'),\n nextRecord: z.boolean().optional().default(true)\n .describe('Auto-advance to next record after action'),\n })).describe('Review actions'),\n navigation: z.enum(['sequential', 'random', 'filtered'])\n .optional().default('sequential')\n .describe('Record navigation mode'),\n showProgress: z.boolean().optional().default(true)\n .describe('Show review progress indicator'),\n});\n\n/**\n * Interface Page Configuration Schema (Airtable Interface parity)\n * Page-level declarative configuration for Airtable-style interface pages.\n * Covers title/data binding, levels, filter by, appearance, user actions,\n * tabs, record count, add record, and advanced options (printing).\n *\n * @see Airtable Interface → right panel (Page / Data / Appearance / User filters / User actions / Advanced)\n */\nexport const InterfacePageConfigSchema = z.object({\n /** Data binding */\n source: z.string().optional().describe('Source object name for the page'),\n levels: z.number().int().min(1).optional().describe('Number of hierarchy levels to display'),\n filterBy: z.array(ViewFilterRuleSchema).optional().describe('Page-level filter criteria'),\n\n /** Appearance */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** User filters */\n userFilters: z.object({\n elements: z.array(z.enum(['grid', 'gallery', 'kanban'])).optional()\n .describe('Visualization element types available in user filter bar'),\n tabs: z.array(ViewTabSchema).optional().describe('User-configurable tabs'),\n }).optional().describe('User filter configuration'),\n\n /** User actions */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles'),\n\n /** Add record */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record count */\n showRecordCount: z.boolean().optional().describe('Show record count at page bottom'),\n\n /** Advanced */\n allowPrinting: z.boolean().optional().describe('Allow users to print the page'),\n}).describe('Interface-level page configuration (Airtable parity)');\n\n/**\n * Page Schema\n * Defines a composition of components for a specific context.\n * Supports both platform pages (Salesforce FlexiPage style: record, home, app, utility)\n * and interface pages (Airtable Interface style: dashboard, grid, kanban, record_review, etc.).\n * \n * **NAMING CONVENTION:**\n * Page names are used in routing and must be lowercase snake_case.\n * Prefix with 'page_' is recommended for clarity.\n * \n * @example Good page names\n * - 'page_dashboard'\n * - 'page_settings'\n * - 'home_page'\n * - 'record_detail'\n * \n * @example Bad page names (will be rejected)\n * - 'PageDashboard' (PascalCase)\n * - 'Settings Page' (spaces)\n */\nexport const PageSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Page unique name (lowercase snake_case)'),\n label: I18nLabelSchema,\n description: I18nLabelSchema.optional(),\n\n /** Icon (used in interface navigation) */\n icon: z.string().optional().describe('Page icon name'),\n \n /** Page Type */\n type: PageTypeSchema.default('record').describe('Page type'),\n \n /** Page State Definitions */\n variables: z.array(PageVariableSchema).optional().describe('Local page state variables'),\n\n /** Context */\n object: z.string().optional().describe('Bound object (for Record pages)'),\n\n /** Record Review Configuration (only for record_review pages) */\n recordReview: RecordReviewConfigSchema.optional()\n .describe('Record review configuration (required when type is \"record_review\")'),\n\n /** Blank Page Layout (only for blank pages) */\n blankLayout: BlankPageLayoutSchema.optional()\n .describe('Free-form grid layout for blank pages (used when type is \"blank\")'),\n \n /** Layout Template */\n template: z.string().default('default').describe('Layout template name (e.g. \"header-sidebar-main\")'),\n \n /** Regions & Content */\n regions: z.array(PageRegionSchema).describe('Defined regions with components'),\n \n /** Activation */\n isDefault: z.boolean().default(false),\n assignedProfiles: z.array(z.string()).optional(),\n\n /** Interface Page Configuration (Airtable Interface parity) */\n interfaceConfig: InterfacePageConfigSchema.optional()\n .describe('Interface-level page configuration (for Airtable-style interface pages)'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).superRefine((data, ctx) => {\n if (data.type === 'record_review' && !data.recordReview) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['recordReview'],\n message: 'recordReview is required when type is \"record_review\"',\n });\n }\n if (data.type === 'blank' && !data.blankLayout) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['blankLayout'],\n message: 'blankLayout is required when type is \"blank\"',\n });\n }\n});\n\nexport type Page = z.infer;\nexport type PageType = z.infer;\nexport type PageComponent = z.infer;\nexport type PageRegion = z.infer;\nexport type PageVariable = z.infer;\nexport type ElementDataSource = z.infer;\nexport type RecordReviewConfig = z.infer;\nexport type BlankPageLayoutItem = z.infer;\nexport type BlankPageLayout = z.infer;\nexport type InterfacePageConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Widget Lifecycle Hooks Schema\n * \n * Defines lifecycle callbacks for custom widgets inspired by Web Components and React.\n * These hooks allow widgets to perform initialization, cleanup, and respond to changes.\n * \n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components\n * @see https://react.dev/reference/react/Component#component-lifecycle\n * \n * @example\n * ```typescript\n * const widget = {\n * lifecycle: {\n * onMount: \"console.log('Widget mounted')\",\n * onUpdate: \"if (prevProps.value !== props.value) { updateUI() }\",\n * onUnmount: \"cleanup()\",\n * onValidate: \"return value.length > 0 ? null : 'Required field'\"\n * }\n * }\n * ```\n */\nexport const WidgetLifecycleSchema = z.object({\n /**\n * Called when widget is mounted/rendered for the first time\n * Use for initialization, setting up event listeners, loading data, etc.\n * \n * @example \"initializeDatePicker(); loadOptions();\"\n */\n onMount: z.string().optional().describe('Initialization code when widget mounts'),\n\n /**\n * Called when widget props change\n * Receives previous props for comparison\n * \n * @example \"if (prevProps.value !== props.value) { updateDisplay() }\"\n */\n onUpdate: z.string().optional().describe('Code to run when props change'),\n\n /**\n * Called when widget is about to be removed from DOM\n * Use for cleanup, removing event listeners, canceling timers, etc.\n * \n * @example \"destroyDatePicker(); cancelPendingRequests();\"\n */\n onUnmount: z.string().optional().describe('Cleanup code when widget unmounts'),\n\n /**\n * Custom validation logic for this widget\n * Should return error message string if invalid, null/undefined if valid\n * \n * @example \"return value && value.length >= 10 ? null : 'Minimum 10 characters'\"\n */\n onValidate: z.string().optional().describe('Custom validation logic'),\n\n /**\n * Called when widget receives focus\n * \n * @example \"highlightField(); logFocusEvent();\"\n */\n onFocus: z.string().optional().describe('Code to run on focus'),\n\n /**\n * Called when widget loses focus\n * \n * @example \"validateField(); saveFieldState();\"\n */\n onBlur: z.string().optional().describe('Code to run on blur'),\n\n /**\n * Called on any error in the widget\n * \n * @example \"logError(error); showErrorNotification();\"\n */\n onError: z.string().optional().describe('Error handling code'),\n});\n\nexport type WidgetLifecycle = z.infer;\n\n/**\n * Widget Event Schema\n * \n * Defines custom events that widgets can emit, inspired by DOM Events and Lightning Web Components.\n * \n * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events\n * @see https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.events\n * \n * @example\n * ```typescript\n * const searchEvent = {\n * name: 'search',\n * bubbles: true,\n * cancelable: false,\n * payload: {\n * query: 'string',\n * filters: 'object'\n * }\n * }\n * ```\n */\nexport const WidgetEventSchema = z.object({\n /**\n * Event name\n * Should be lowercase, dash-separated for consistency\n * \n * @example \"value-change\", \"item-selected\", \"search-complete\"\n */\n name: z.string().describe('Event name'),\n\n /**\n * Event label for documentation\n */\n label: I18nLabelSchema.optional().describe('Human-readable event label'),\n\n /**\n * Event description\n */\n description: I18nLabelSchema.optional().describe('Event description and usage'),\n\n /**\n * Whether event bubbles up through the DOM hierarchy\n * \n * @default false\n */\n bubbles: z.boolean().default(false).describe('Whether event bubbles'),\n\n /**\n * Whether event can be cancelled\n * \n * @default false\n */\n cancelable: z.boolean().default(false).describe('Whether event is cancelable'),\n\n /**\n * Event payload schema\n * Defines the data structure sent with the event\n * \n * @example { userId: 'string', timestamp: 'number' }\n */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event payload schema'),\n});\n\nexport type WidgetEvent = z.infer;\n\n/**\n * Widget Property Definition Schema\n * \n * Defines the contract for widget configuration properties.\n * Inspired by React PropTypes and Web Component attributes.\n * \n * @see https://react.dev/reference/react/Component#static-proptypes\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements\n * \n * @example\n * ```typescript\n * const widgetProps = {\n * maxLength: {\n * type: 'number',\n * required: false,\n * default: 100,\n * description: 'Maximum input length'\n * }\n * }\n * ```\n */\nexport const WidgetPropertySchema = z.object({\n /**\n * Property name\n * Should be camelCase following ObjectStack conventions\n */\n name: z.string().describe('Property name (camelCase)'),\n\n /**\n * Property label for UI\n */\n label: I18nLabelSchema.optional().describe('Human-readable label'),\n\n /**\n * Property data type\n * \n * @example \"string\", \"number\", \"boolean\", \"array\", \"object\", \"function\"\n */\n type: z.enum(['string', 'number', 'boolean', 'array', 'object', 'function', 'any'])\n .describe('TypeScript type'),\n\n /**\n * Whether property is required\n * \n * @default false\n */\n required: z.boolean().default(false).describe('Whether property is required'),\n\n /**\n * Default value for the property\n */\n default: z.unknown().optional().describe('Default value'),\n\n /**\n * Property description\n */\n description: I18nLabelSchema.optional().describe('Property description'),\n\n /**\n * Property validation schema\n * Can include min/max, regex, enum values, etc.\n */\n validation: z.record(z.string(), z.unknown()).optional().describe('Validation rules'),\n\n /**\n * Property category for grouping in UI\n */\n category: z.string().optional().describe('Property category'),\n});\n\nexport type WidgetProperty = z.infer;\n\n/**\n * Widget Manifest Schema\n * \n * Complete definition for a custom widget including metadata, lifecycle, events, and props.\n * This is used for widget registration and discovery.\n * \n * @example\n * ```typescript\n * const customWidget = {\n * name: 'custom_date_picker',\n * label: 'Custom Date Picker',\n * version: '1.0.0',\n * author: 'Company Name',\n * fieldTypes: ['date', 'datetime'],\n * lifecycle: { ... },\n * events: [ ... ],\n * properties: [ ... ]\n * }\n * ```\n */\n/**\n * Widget Source Schema\n * Defines how the widget code is loaded.\n */\nexport const WidgetSourceSchema = z.discriminatedUnion('type', [\n // NPM Registry (standard)\n z.object({\n type: z.literal('npm'),\n packageName: z.string().describe('NPM package name'),\n version: z.string().default('latest'),\n exportName: z.string().optional().describe('Named export (default: default)'),\n }),\n // Module Federation (Remote)\n z.object({\n type: z.literal('remote'),\n url: z.string().url().describe('Remote entry URL (.js)'),\n moduleName: z.string().describe('Exposed module name'),\n scope: z.string().describe('Remote scope name'),\n }),\n // Inline Code (Simple scripts)\n z.object({\n type: z.literal('inline'),\n code: z.string().describe('JavaScript code body'),\n }),\n]);\n\nexport type WidgetSource = z.infer;\n\nexport const WidgetManifestSchema = z.object({\n /**\n * Widget identifier (snake_case)\n */\n name: SnakeCaseIdentifierSchema\n .describe('Widget identifier (snake_case)'),\n\n /**\n * Human-readable widget name\n */\n label: I18nLabelSchema.describe('Widget display name'),\n\n /**\n * Widget description\n */\n description: I18nLabelSchema.optional().describe('Widget description'),\n\n /**\n * Widget version (semver)\n */\n version: z.string().optional().describe('Widget version (semver)'),\n\n /**\n * Widget author/organization\n */\n author: z.string().optional().describe('Widget author'),\n\n /**\n * Icon name or URL\n */\n icon: z.string().optional().describe('Widget icon'),\n\n /**\n * Field types this widget supports\n * \n * @example [\"text\", \"email\", \"url\"]\n */\n fieldTypes: z.array(z.string()).optional().describe('Supported field types'),\n\n /**\n * Widget category for organization\n */\n category: z.enum(['input', 'display', 'picker', 'editor', 'custom'])\n .default('custom')\n .describe('Widget category'),\n\n /**\n * Widget lifecycle hooks\n */\n lifecycle: WidgetLifecycleSchema.optional().describe('Lifecycle hooks'),\n\n /**\n * Custom events this widget emits\n */\n events: z.array(WidgetEventSchema).optional().describe('Custom events'),\n\n /**\n * Widget configuration properties\n */\n properties: z.array(WidgetPropertySchema).optional().describe('Configuration properties'),\n\n /**\n * Widget implementation\n * Defines how to load the widget code\n */\n implementation: WidgetSourceSchema.optional().describe('Widget implementation source'),\n\n /**\n * Widget dependencies\n * External libraries or scripts needed\n */\n dependencies: z.array(z.object({\n name: z.string(),\n version: z.string().optional(),\n url: z.string().url().optional(),\n })).optional().describe('Widget dependencies'),\n\n /**\n * Widget screenshots for showcase\n */\n screenshots: z.array(z.string().url()).optional().describe('Screenshot URLs'),\n\n /**\n * Widget documentation URL\n */\n documentation: z.string().url().optional().describe('Documentation URL'),\n\n /**\n * License information\n */\n license: z.string().optional().describe('License (SPDX identifier)'),\n\n /**\n * Tags for discovery\n */\n tags: z.array(z.string()).optional().describe('Tags for categorization'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\nexport type WidgetManifest = z.infer;\n\n/**\n * Field Widget Props Schema\n * \n * This defines the contract for custom field components and plugin UI extensions.\n * Third-party developers use this interface to build custom field widgets that integrate\n * seamlessly with the ObjectStack UI system.\n * \n * @example\n * // Custom widget implementation\n * function CustomDatePicker(props: FieldWidgetProps) {\n * const { value, onChange, readonly, required, error, field, record, options } = props;\n * // Widget implementation...\n * }\n */\nexport const FieldWidgetPropsSchema = z.object({\n /**\n * Current field value.\n * Type depends on the field type (string, number, boolean, array, object, etc.)\n */\n value: z.unknown().describe('Current field value'),\n\n /**\n * Callback function to update the field value.\n * Should be called when user interaction changes the value.\n * \n * @param newValue - The new value to set\n */\n onChange: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.void())\n .describe('Callback to update field value'),\n\n /**\n * Whether the field is in read-only mode.\n * When true, the widget should display the value but not allow editing.\n */\n readonly: z.boolean().default(false).describe('Read-only mode flag'),\n\n /**\n * Whether the field is required.\n * Widget should indicate required state visually and validate accordingly.\n */\n required: z.boolean().default(false).describe('Required field flag'),\n\n /**\n * Validation error message to display.\n * When present, widget should display the error in its UI.\n */\n error: z.string().optional().describe('Validation error message'),\n\n /**\n * Complete field definition from the schema.\n * Contains metadata like type, constraints, options, etc.\n */\n field: FieldSchema.describe('Field schema definition'),\n\n /**\n * The complete record/document being edited.\n * Useful for conditional logic and cross-field dependencies.\n */\n record: z.record(z.string(), z.unknown()).optional().describe('Complete record data'),\n\n /**\n * Custom options passed to the widget.\n * Can contain widget-specific configuration like themes, behaviors, etc.\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Custom widget options'),\n});\n\n/**\n * TypeScript type for Field Widget Props\n */\nexport type FieldWidgetProps = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Feed Item Type\n * Unified activity types for the record timeline.\n * Covers comments, field changes, tasks, events, and system activities.\n */\nexport const FeedItemType = z.enum([\n 'comment',\n 'field_change',\n 'task',\n 'event',\n 'email',\n 'call',\n 'note',\n 'file',\n 'record_create',\n 'record_delete',\n 'approval',\n 'sharing',\n 'system',\n]);\nexport type FeedItemType = z.infer;\n\n/**\n * Mention Schema\n * Represents an @mention within comment body text.\n */\nexport const MentionSchema = z.object({\n type: z.enum(['user', 'team', 'record']).describe('Mention target type'),\n id: z.string().describe('Target ID'),\n name: z.string().describe('Display name for rendering'),\n offset: z.number().int().min(0).describe('Character offset in body text'),\n length: z.number().int().min(1).describe('Length of mention token in body text'),\n});\nexport type Mention = z.infer;\n\n/**\n * Field Change Entry Schema\n * Represents a single field-level change within a field_change feed item.\n */\nexport const FieldChangeEntrySchema = z.object({\n field: z.string().describe('Field machine name'),\n fieldLabel: z.string().optional().describe('Field display label'),\n oldValue: z.unknown().optional().describe('Previous value'),\n newValue: z.unknown().optional().describe('New value'),\n oldDisplayValue: z.string().optional().describe('Human-readable old value'),\n newDisplayValue: z.string().optional().describe('Human-readable new value'),\n});\nexport type FieldChangeEntry = z.infer;\n\n/**\n * Reaction Schema\n * Represents an emoji reaction on a feed item.\n */\nexport const ReactionSchema = z.object({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n userIds: z.array(z.string()).describe('Users who reacted'),\n count: z.number().int().min(1).describe('Total reaction count'),\n});\nexport type Reaction = z.infer;\n\n/**\n * Feed Actor Schema\n * Represents the actor who performed the action.\n */\nexport const FeedActorSchema = z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n avatarUrl: z.string().url().optional().describe('Actor avatar URL'),\n source: z.string().optional().describe('Source application (e.g., \"Omni\", \"API\", \"Studio\")'),\n});\nexport type FeedActor = z.infer;\n\n/**\n * Feed Item Visibility\n */\nexport const FeedVisibility = z.enum(['public', 'internal', 'private']);\nexport type FeedVisibility = z.infer;\n\n/**\n * Feed Item Schema\n * A single entry in the unified activity timeline.\n *\n * @example Comment\n * {\n * id: 'feed_001',\n * type: 'comment',\n * object: 'account',\n * recordId: 'rec_123',\n * body: 'Great progress! @jane.doe can you follow up?',\n * mentions: [{ type: 'user', id: 'user_123', name: 'Jane Doe', offset: 17, length: 9 }],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:30:00Z',\n * }\n *\n * @example Field Change\n * {\n * id: 'feed_002',\n * type: 'field_change',\n * object: 'account',\n * recordId: 'rec_123',\n * changes: [\n * { field: 'status', oldDisplayValue: 'New', newDisplayValue: 'Active' },\n * { field: 'region', oldDisplayValue: '', newDisplayValue: 'Asia-Pacific' },\n * ],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:25:00Z',\n * }\n */\nexport const FeedItemSchema = z.object({\n /** Unique identifier */\n id: z.string().describe('Feed item ID'),\n\n /** Feed item type */\n type: FeedItemType.describe('Activity type'),\n\n /** Target record reference */\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID this feed item belongs to'),\n\n /** Actor (who performed the action) */\n actor: FeedActorSchema.describe('Who performed this action'),\n\n /** Content (for comments/notes) */\n body: z.string().optional().describe('Rich text body (Markdown supported)'),\n\n /** @Mentions */\n mentions: z.array(MentionSchema).optional().describe('Mentioned users/teams/records'),\n\n /** Field changes (for field_change type) */\n changes: z.array(FieldChangeEntrySchema).optional().describe('Field-level changes'),\n\n /** Reactions */\n reactions: z.array(ReactionSchema).optional().describe('Emoji reactions on this item'),\n\n /** Reply threading */\n parentId: z.string().optional().describe('Parent feed item ID for threaded replies'),\n replyCount: z.number().int().min(0).default(0).describe('Number of replies'),\n\n /** Pin / Star */\n pinned: z.boolean().default(false).describe('Whether the feed item is pinned to the top of the timeline'),\n pinnedAt: z.string().datetime().optional().describe('Timestamp when the item was pinned'),\n pinnedBy: z.string().optional().describe('User ID who pinned the item'),\n starred: z.boolean().default(false).describe('Whether the feed item is starred/bookmarked by the current user'),\n starredAt: z.string().datetime().optional().describe('Timestamp when the item was starred'),\n\n /** Visibility */\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public (all users), internal (team only), private (author + mentioned)'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n editedAt: z.string().datetime().optional().describe('When comment was last edited'),\n isEdited: z.boolean().default(false).describe('Whether comment has been edited'),\n});\nexport type FeedItem = z.infer;\n\n/**\n * Feed Filter Mode\n * Controls which feed item types to display in the timeline.\n */\nexport const FeedFilterMode = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\nexport type FeedFilterMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ViewFilterRuleSchema } from './view.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { FeedItemType, FeedFilterMode } from '../data/feed.zod';\n\n/**\n * Empty Properties Schema\n */\nconst EmptyProps = z.object({});\n\n/**\n * ----------------------------------------------------------------------\n * 1. Structure Components\n * ----------------------------------------------------------------------\n */\n\nexport const PageHeaderProps = z.object({\n title: I18nLabelSchema.describe('Page title'),\n subtitle: I18nLabelSchema.optional().describe('Page subtitle'),\n icon: z.string().optional().describe('Icon name'),\n breadcrumb: z.boolean().default(true).describe('Show breadcrumb'),\n actions: z.array(z.string()).optional().describe('Action IDs to show in header'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageTabsProps = z.object({\n type: z.enum(['line', 'card', 'pill']).default('line'),\n position: z.enum(['top', 'left']).default('top'),\n items: z.array(z.object({\n label: I18nLabelSchema,\n icon: z.string().optional(),\n children: z.array(z.unknown()).describe('Child components')\n })),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageCardProps = z.object({\n title: I18nLabelSchema.optional(),\n bordered: z.boolean().default(true),\n actions: z.array(z.string()).optional(),\n /** Slot for nested content in the Card body */\n body: z.array(z.unknown()).optional().describe('Card content components (slot)'),\n /** Slot for footer content */\n footer: z.array(z.unknown()).optional().describe('Card footer components (slot)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 2. Record Context Components\n * ----------------------------------------------------------------------\n */\n\nexport const RecordDetailsProps = z.object({\n columns: z.enum(['1', '2', '3', '4']).default('2').describe('Number of columns for field layout (1-4)'),\n layout: z.enum(['auto', 'custom']).default('auto').describe('Layout mode: auto uses object compactLayout, custom uses explicit sections'),\n sections: z.array(z.string()).optional().describe('Section IDs to show (required when layout is \"custom\")'),\n fields: z.array(z.string()).optional().describe('Explicit field list to display (optional, overrides compactLayout)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordRelatedListProps = z.object({\n objectName: z.string().describe('Related object name (e.g., \"task\", \"opportunity\")'),\n relationshipField: z.string().describe('Field on related object that points to this record (e.g., \"account_id\")'),\n columns: z.array(z.string()).describe('Fields to display in the related list'),\n sort: z.union([\n z.string(),\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional().describe('Sort order for related records'),\n limit: z.number().int().positive().default(5).describe('Number of records to display initially'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Additional filter criteria for related records'),\n title: I18nLabelSchema.optional().describe('Custom title for the related list'),\n showViewAll: z.boolean().default(true).describe('Show \"View All\" link to see all related records'),\n actions: z.array(z.string()).optional().describe('Action IDs available for related records'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordHighlightsProps = z.object({\n fields: z.array(z.string()).min(1).max(7).describe('Key fields to highlight (1-7 fields max, typically displayed as prominent cards)'),\n layout: z.enum(['horizontal', 'vertical']).default('horizontal').describe('Layout orientation for highlight fields'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordActivityProps = z.object({\n /** Activity types to display (unified enum including comment, field_change, etc.) */\n types: z.array(FeedItemType).optional().describe('Feed item types to show (default: all)'),\n /** Default filter mode (Airtable-style dropdown) */\n filterMode: FeedFilterMode.default('all').describe('Default activity filter'),\n /** Allow user to switch filter modes */\n showFilterToggle: z.boolean().default(true).describe('Show filter dropdown in panel header'),\n /** Pagination */\n limit: z.number().int().positive().default(20).describe('Number of items to load per page'),\n /** Show completed activities */\n showCompleted: z.boolean().default(false).describe('Include completed activities'),\n /** Merge field_change + comment in a unified timeline */\n unifiedTimeline: z.boolean().default(true).describe('Mix field changes and comments in one timeline (Airtable style)'),\n /** Show the comment input box at the bottom */\n showCommentInput: z.boolean().default(true).describe('Show \"Leave a comment\" input at the bottom'),\n /** Enable @mentions in comments */\n enableMentions: z.boolean().default(true).describe('Enable @mentions in comments'),\n /** Enable emoji reactions */\n enableReactions: z.boolean().default(false).describe('Enable emoji reactions on feed items'),\n /** Enable threaded replies */\n enableThreading: z.boolean().default(false).describe('Enable threaded replies on comments'),\n /** Show notification subscription toggle (bell icon) */\n showSubscriptionToggle: z.boolean().default(true).describe('Show bell icon for record-level notification subscription'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordChatterProps = z.object({\n /** Panel position */\n position: z.enum(['sidebar', 'inline', 'drawer']).default('sidebar').describe('Where to render the chatter panel'),\n /** Panel width (for sidebar/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Panel width (e.g., \"350px\", \"30%\")'),\n /** Collapsible */\n collapsible: z.boolean().default(true).describe('Whether the panel can be collapsed'),\n /** Default collapsed state */\n defaultCollapsed: z.boolean().default(false).describe('Whether the panel starts collapsed'),\n /** Feed configuration (delegates to RecordActivityProps) */\n feed: RecordActivityProps.optional().describe('Embedded activity feed configuration'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordPathProps = z.object({\n statusField: z.string().describe('Field name representing the current status/stage'),\n stages: z.array(z.object({\n value: z.string(),\n label: I18nLabelSchema,\n })).optional().describe('Explicit stage definitions (if not using field metadata)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageAccordionProps = z.object({\n items: z.array(z.object({\n label: I18nLabelSchema,\n icon: z.string().optional(),\n collapsed: z.boolean().default(false),\n children: z.array(z.unknown()).describe('Child components'),\n })),\n allowMultiple: z.boolean().default(false).describe('Allow multiple panels to be expanded simultaneously'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const AIChatWindowProps = z.object({\n mode: z.enum(['float', 'sidebar', 'inline']).default('float').describe('Display mode for the chat window'),\n agentId: z.string().optional().describe('Specific AI agent to use'),\n context: z.record(z.string(), z.unknown()).optional().describe('Contextual data to pass to the AI'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 3. Content Element Components (Airtable Interface Parity)\n * ----------------------------------------------------------------------\n */\n\nexport const ElementTextPropsSchema = z.object({\n content: z.string().describe('Text or Markdown content'),\n variant: z.enum(['heading', 'subheading', 'body', 'caption'])\n .optional().default('body').describe('Text style variant'),\n align: z.enum(['left', 'center', 'right'])\n .optional().default('left').describe('Text alignment'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementNumberPropsSchema = z.object({\n object: z.string().describe('Source object'),\n field: z.string().optional().describe('Field to aggregate'),\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max'])\n .describe('Aggregation function'),\n filter: FilterConditionSchema.optional().describe('Filter criteria'),\n format: z.enum(['number', 'currency', 'percent']).optional().describe('Number display format'),\n prefix: z.string().optional().describe('Prefix text (e.g. \"$\")'),\n suffix: z.string().optional().describe('Suffix text (e.g. \"%\")'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementImagePropsSchema = z.object({\n src: z.string().describe('Image URL or attachment field'),\n alt: z.string().optional().describe('Alt text for accessibility'),\n fit: z.enum(['cover', 'contain', 'fill'])\n .optional().default('cover').describe('Image object-fit mode'),\n height: z.number().optional().describe('Fixed height in pixels'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 4. Interactive Element Components (Phase B — Element Library)\n * ----------------------------------------------------------------------\n */\n\nexport const ElementButtonPropsSchema = z.object({\n label: I18nLabelSchema.describe('Button display label'),\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link'])\n .optional().default('primary').describe('Button visual variant'),\n size: z.enum(['small', 'medium', 'large'])\n .optional().default('medium').describe('Button size'),\n icon: z.string().optional().describe('Icon name (Lucide icon)'),\n iconPosition: z.enum(['left', 'right'])\n .optional().default('left').describe('Icon position relative to label'),\n disabled: z.boolean().optional().default(false).describe('Disable the button'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementFilterPropsSchema = z.object({\n object: z.string().describe('Object to filter'),\n fields: z.array(z.string()).describe('Filterable field names'),\n targetVariable: z.string().optional().describe('Page variable to store filter state'),\n layout: z.enum(['inline', 'dropdown', 'sidebar'])\n .optional().default('inline').describe('Filter display layout'),\n showSearch: z.boolean().optional().default(true).describe('Show search input'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementFormPropsSchema = z.object({\n object: z.string().describe('Object for the form'),\n fields: z.array(z.string()).optional().describe('Fields to display (defaults to all editable fields)'),\n mode: z.enum(['create', 'edit']).optional().default('create').describe('Form mode'),\n submitLabel: I18nLabelSchema.optional().describe('Submit button label'),\n onSubmit: z.string().optional().describe('Action expression on form submit'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementRecordPickerPropsSchema = z.object({\n object: z.string().describe('Object to pick records from'),\n displayField: z.string().describe('Field to display as the record label'),\n searchFields: z.array(z.string()).optional().describe('Fields to search against'),\n filter: FilterConditionSchema.optional().describe('Filter criteria for available records'),\n multiple: z.boolean().optional().default(false).describe('Allow multiple record selection'),\n targetVariable: z.string().optional().describe('Page variable to bind selected record ID(s)'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * Component Props Map\n * Maps Component Type to its Property Schema\n * ----------------------------------------------------------------------\n */\nexport const ComponentPropsMap = {\n // Structure\n 'page:header': PageHeaderProps,\n 'page:tabs': PageTabsProps,\n 'page:card': PageCardProps,\n 'page:footer': EmptyProps,\n 'page:sidebar': EmptyProps,\n 'page:accordion': PageAccordionProps,\n 'page:section': EmptyProps,\n\n // Record\n 'record:details': RecordDetailsProps,\n 'record:related_list': RecordRelatedListProps,\n 'record:highlights': RecordHighlightsProps,\n 'record:activity': RecordActivityProps,\n 'record:chatter': RecordChatterProps,\n 'record:path': RecordPathProps,\n\n // Navigation\n 'app:launcher': EmptyProps,\n 'nav:menu': EmptyProps,\n 'nav:breadcrumb': EmptyProps,\n\n // Utility\n 'global:search': EmptyProps,\n 'global:notifications': EmptyProps,\n 'user:profile': EmptyProps,\n \n // AI\n 'ai:chat_window': AIChatWindowProps,\n 'ai:suggestion': z.object({ context: z.string().optional() }),\n\n // Content Elements\n 'element:text': ElementTextPropsSchema,\n 'element:number': ElementNumberPropsSchema,\n 'element:image': ElementImagePropsSchema,\n 'element:divider': EmptyProps,\n\n // Interactive Elements\n 'element:button': ElementButtonPropsSchema,\n 'element:filter': ElementFilterPropsSchema,\n 'element:form': ElementFormPropsSchema,\n 'element:record_picker': ElementRecordPickerPropsSchema,\n} as const;\n\n/**\n * Type Helper to extract props from map\n */\nexport type ComponentProps = z.infer;\nexport type ComponentPropsInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Touch Target Configuration Schema\n * Ensures touch targets meet WCAG 2.5.5 minimum size requirements (44x44px).\n */\nexport const TouchTargetConfigSchema = z.object({\n minWidth: z.number().default(44).describe('Minimum touch target width in pixels (WCAG 2.5.5: 44px)'),\n minHeight: z.number().default(44).describe('Minimum touch target height in pixels (WCAG 2.5.5: 44px)'),\n padding: z.number().optional().describe('Additional padding around touch target in pixels'),\n hitSlop: z.object({\n top: z.number().optional().describe('Extra hit area above the element'),\n right: z.number().optional().describe('Extra hit area to the right of the element'),\n bottom: z.number().optional().describe('Extra hit area below the element'),\n left: z.number().optional().describe('Extra hit area to the left of the element'),\n }).optional().describe('Invisible hit area extension beyond the visible bounds'),\n}).describe('Touch target sizing configuration (WCAG accessible)');\n\nexport type TouchTargetConfig = z.infer;\n\n/**\n * Gesture Type Enum\n * Supported touch gesture types.\n */\nexport const GestureTypeSchema = z.enum([\n 'swipe',\n 'pinch',\n 'long_press',\n 'double_tap',\n 'drag',\n 'rotate',\n 'pan',\n]).describe('Touch gesture type');\n\nexport type GestureType = z.infer;\n\n/**\n * Swipe Direction Enum\n */\nexport const SwipeDirectionSchema = z.enum(['up', 'down', 'left', 'right']);\n\nexport type SwipeDirection = z.infer;\n\n/**\n * Swipe Gesture Configuration Schema\n */\nexport const SwipeGestureConfigSchema = z.object({\n direction: z.array(SwipeDirectionSchema).describe('Allowed swipe directions'),\n threshold: z.number().optional().describe('Minimum distance in pixels to recognize swipe'),\n velocity: z.number().optional().describe('Minimum velocity (px/ms) to trigger swipe'),\n}).describe('Swipe gesture recognition settings');\n\nexport type SwipeGestureConfig = z.infer;\n\n/**\n * Pinch Gesture Configuration Schema\n */\nexport const PinchGestureConfigSchema = z.object({\n minScale: z.number().optional().describe('Minimum scale factor (e.g., 0.5 for 50%)'),\n maxScale: z.number().optional().describe('Maximum scale factor (e.g., 3.0 for 300%)'),\n}).describe('Pinch/zoom gesture recognition settings');\n\nexport type PinchGestureConfig = z.infer;\n\n/**\n * Long Press Gesture Configuration Schema\n */\nexport const LongPressGestureConfigSchema = z.object({\n duration: z.number().default(500).describe('Hold duration in milliseconds to trigger long press'),\n moveTolerance: z.number().optional().describe('Max movement in pixels allowed during press'),\n}).describe('Long press gesture recognition settings');\n\nexport type LongPressGestureConfig = z.infer;\n\n/**\n * Gesture Configuration Schema\n * Unified configuration for all supported gesture types.\n */\nexport const GestureConfigSchema = z.object({\n type: GestureTypeSchema.describe('Gesture type to configure'),\n label: I18nLabelSchema.optional().describe('Descriptive label for the gesture action'),\n enabled: z.boolean().default(true).describe('Whether this gesture is active'),\n swipe: SwipeGestureConfigSchema.optional().describe('Swipe gesture settings (when type is swipe)'),\n pinch: PinchGestureConfigSchema.optional().describe('Pinch gesture settings (when type is pinch)'),\n longPress: LongPressGestureConfigSchema.optional().describe('Long press settings (when type is long_press)'),\n}).describe('Per-gesture configuration');\n\nexport type GestureConfig = z.infer;\n\n/**\n * Touch Interaction Schema\n * Top-level touch and gesture interaction configuration for a component.\n */\nexport const TouchInteractionSchema = z.object({\n gestures: z.array(GestureConfigSchema).optional().describe('Configured gesture recognizers'),\n touchTarget: TouchTargetConfigSchema.optional().describe('Touch target sizing and hit area'),\n hapticFeedback: z.boolean().optional().describe('Enable haptic feedback on touch interactions'),\n}).merge(AriaPropsSchema.partial()).describe('Touch and gesture interaction configuration');\n\nexport type TouchInteraction = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Focus Trap Configuration Schema\n * Constrains keyboard focus within a specific container (e.g., modals, dialogs).\n */\nexport const FocusTrapConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable focus trapping within this container'),\n initialFocus: z.string().optional().describe('CSS selector for the element to focus on activation'),\n returnFocus: z.boolean().default(true).describe('Return focus to trigger element on deactivation'),\n escapeDeactivates: z.boolean().default(true).describe('Allow Escape key to deactivate the focus trap'),\n}).describe('Focus trap configuration for modal-like containers');\n\nexport type FocusTrapConfig = z.infer;\n\n/**\n * Keyboard Shortcut Schema\n * Defines a single keyboard shortcut binding.\n */\nexport const KeyboardShortcutSchema = z.object({\n key: z.string().describe('Key combination (e.g., \"Ctrl+S\", \"Alt+N\", \"Escape\")'),\n action: z.string().describe('Action identifier to invoke when shortcut is triggered'),\n description: I18nLabelSchema.optional().describe('Human-readable description of what the shortcut does'),\n scope: z.enum(['global', 'view', 'form', 'modal', 'list']).default('global')\n .describe('Scope in which this shortcut is active'),\n}).describe('Keyboard shortcut binding');\n\nexport type KeyboardShortcut = z.infer;\n\n/**\n * Focus Management Schema\n * Controls tab order, focus visibility, and navigation behavior.\n */\nexport const FocusManagementSchema = z.object({\n tabOrder: z.enum(['auto', 'manual']).default('auto')\n .describe('Tab order strategy: auto (DOM order) or manual (explicit tabIndex)'),\n skipLinks: z.boolean().default(false).describe('Provide skip-to-content navigation links'),\n focusVisible: z.boolean().default(true).describe('Show visible focus indicators for keyboard users'),\n focusTrap: FocusTrapConfigSchema.optional().describe('Focus trap settings'),\n arrowNavigation: z.boolean().default(false)\n .describe('Enable arrow key navigation between focusable items'),\n}).describe('Focus and tab navigation management');\n\nexport type FocusManagement = z.infer;\n\n/**\n * Keyboard Navigation Configuration Schema\n * Top-level keyboard navigation and shortcut configuration.\n */\nexport const KeyboardNavigationConfigSchema = z.object({\n shortcuts: z.array(KeyboardShortcutSchema).optional().describe('Registered keyboard shortcuts'),\n focusManagement: FocusManagementSchema.optional().describe('Focus and tab order management'),\n rovingTabindex: z.boolean().default(false)\n .describe('Enable roving tabindex pattern for composite widgets'),\n}).merge(AriaPropsSchema.partial()).describe('Keyboard navigation and shortcut configuration');\n\nexport type KeyboardNavigationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { TouchTargetConfigSchema } from './touch.zod';\nimport { FocusManagementSchema } from './keyboard.zod';\n\n/**\n * Color Palette Schema\n * Defines brand colors and their variants.\n */\nexport const ColorPaletteSchema = z.object({\n primary: z.string().describe('Primary brand color (hex, rgb, or hsl)'),\n secondary: z.string().optional().describe('Secondary brand color'),\n accent: z.string().optional().describe('Accent color for highlights'),\n success: z.string().optional().describe('Success state color (default: green)'),\n warning: z.string().optional().describe('Warning state color (default: yellow)'),\n error: z.string().optional().describe('Error state color (default: red)'),\n info: z.string().optional().describe('Info state color (default: blue)'),\n \n // Neutral colors\n background: z.string().optional().describe('Background color'),\n surface: z.string().optional().describe('Surface/card background color'),\n text: z.string().optional().describe('Primary text color'),\n textSecondary: z.string().optional().describe('Secondary text color'),\n border: z.string().optional().describe('Border color'),\n disabled: z.string().optional().describe('Disabled state color'),\n \n // Color variants (shades)\n primaryLight: z.string().optional().describe('Lighter shade of primary'),\n primaryDark: z.string().optional().describe('Darker shade of primary'),\n secondaryLight: z.string().optional().describe('Lighter shade of secondary'),\n secondaryDark: z.string().optional().describe('Darker shade of secondary'),\n});\n\n/**\n * Typography Settings Schema\n * Font families, sizes, weights, and line heights.\n */\nexport const TypographySchema = z.object({\n fontFamily: z.object({\n base: z.string().optional().describe('Base font family (default: system fonts)'),\n heading: z.string().optional().describe('Heading font family'),\n mono: z.string().optional().describe('Monospace font family for code'),\n }).optional(),\n \n fontSize: z.object({\n xs: z.string().optional().describe('Extra small font size (e.g., 0.75rem)'),\n sm: z.string().optional().describe('Small font size (e.g., 0.875rem)'),\n base: z.string().optional().describe('Base font size (e.g., 1rem)'),\n lg: z.string().optional().describe('Large font size (e.g., 1.125rem)'),\n xl: z.string().optional().describe('Extra large font size (e.g., 1.25rem)'),\n '2xl': z.string().optional().describe('2X large font size (e.g., 1.5rem)'),\n '3xl': z.string().optional().describe('3X large font size (e.g., 1.875rem)'),\n '4xl': z.string().optional().describe('4X large font size (e.g., 2.25rem)'),\n }).optional(),\n \n fontWeight: z.object({\n light: z.number().optional().describe('Light weight (default: 300)'),\n normal: z.number().optional().describe('Normal weight (default: 400)'),\n medium: z.number().optional().describe('Medium weight (default: 500)'),\n semibold: z.number().optional().describe('Semibold weight (default: 600)'),\n bold: z.number().optional().describe('Bold weight (default: 700)'),\n }).optional(),\n \n lineHeight: z.object({\n tight: z.string().optional().describe('Tight line height (e.g., 1.25)'),\n normal: z.string().optional().describe('Normal line height (e.g., 1.5)'),\n relaxed: z.string().optional().describe('Relaxed line height (e.g., 1.75)'),\n loose: z.string().optional().describe('Loose line height (e.g., 2)'),\n }).optional(),\n \n letterSpacing: z.object({\n tighter: z.string().optional().describe('Tighter letter spacing (e.g., -0.05em)'),\n tight: z.string().optional().describe('Tight letter spacing (e.g., -0.025em)'),\n normal: z.string().optional().describe('Normal letter spacing (e.g., 0)'),\n wide: z.string().optional().describe('Wide letter spacing (e.g., 0.025em)'),\n wider: z.string().optional().describe('Wider letter spacing (e.g., 0.05em)'),\n }).optional(),\n});\n\n/**\n * Spacing Units Schema\n * Defines spacing scale for margins, padding, gaps.\n */\nexport const SpacingSchema = z.object({\n '0': z.string().optional().describe('0 spacing (0)'),\n '1': z.string().optional().describe('Spacing unit 1 (e.g., 0.25rem)'),\n '2': z.string().optional().describe('Spacing unit 2 (e.g., 0.5rem)'),\n '3': z.string().optional().describe('Spacing unit 3 (e.g., 0.75rem)'),\n '4': z.string().optional().describe('Spacing unit 4 (e.g., 1rem)'),\n '5': z.string().optional().describe('Spacing unit 5 (e.g., 1.25rem)'),\n '6': z.string().optional().describe('Spacing unit 6 (e.g., 1.5rem)'),\n '8': z.string().optional().describe('Spacing unit 8 (e.g., 2rem)'),\n '10': z.string().optional().describe('Spacing unit 10 (e.g., 2.5rem)'),\n '12': z.string().optional().describe('Spacing unit 12 (e.g., 3rem)'),\n '16': z.string().optional().describe('Spacing unit 16 (e.g., 4rem)'),\n '20': z.string().optional().describe('Spacing unit 20 (e.g., 5rem)'),\n '24': z.string().optional().describe('Spacing unit 24 (e.g., 6rem)'),\n});\n\n/**\n * Border Radius Schema\n * Rounded corners configuration.\n */\nexport const BorderRadiusSchema = z.object({\n none: z.string().optional().describe('No border radius (0)'),\n sm: z.string().optional().describe('Small border radius (e.g., 0.125rem)'),\n base: z.string().optional().describe('Base border radius (e.g., 0.25rem)'),\n md: z.string().optional().describe('Medium border radius (e.g., 0.375rem)'),\n lg: z.string().optional().describe('Large border radius (e.g., 0.5rem)'),\n xl: z.string().optional().describe('Extra large border radius (e.g., 0.75rem)'),\n '2xl': z.string().optional().describe('2X large border radius (e.g., 1rem)'),\n full: z.string().optional().describe('Full border radius (50%)'),\n});\n\n/**\n * Shadow Schema\n * Box shadow effects.\n */\nexport const ShadowSchema = z.object({\n none: z.string().optional().describe('No shadow'),\n sm: z.string().optional().describe('Small shadow'),\n base: z.string().optional().describe('Base shadow'),\n md: z.string().optional().describe('Medium shadow'),\n lg: z.string().optional().describe('Large shadow'),\n xl: z.string().optional().describe('Extra large shadow'),\n '2xl': z.string().optional().describe('2X large shadow'),\n inner: z.string().optional().describe('Inner shadow (inset)'),\n});\n\n/**\n * Breakpoints Schema\n * Responsive design breakpoints.\n */\nexport const BreakpointsSchema = z.object({\n xs: z.string().optional().describe('Extra small breakpoint (e.g., 480px)'),\n sm: z.string().optional().describe('Small breakpoint (e.g., 640px)'),\n md: z.string().optional().describe('Medium breakpoint (e.g., 768px)'),\n lg: z.string().optional().describe('Large breakpoint (e.g., 1024px)'),\n xl: z.string().optional().describe('Extra large breakpoint (e.g., 1280px)'),\n '2xl': z.string().optional().describe('2X large breakpoint (e.g., 1536px)'),\n});\n\n/**\n * Animation Schema\n * Animation timing and duration settings.\n */\nexport const AnimationSchema = z.object({\n duration: z.object({\n fast: z.string().optional().describe('Fast animation (e.g., 150ms)'),\n base: z.string().optional().describe('Base animation (e.g., 300ms)'),\n slow: z.string().optional().describe('Slow animation (e.g., 500ms)'),\n }).optional(),\n \n timing: z.object({\n linear: z.string().optional().describe('Linear timing function'),\n ease: z.string().optional().describe('Ease timing function'),\n ease_in: z.string().optional().describe('Ease-in timing function'),\n ease_out: z.string().optional().describe('Ease-out timing function'),\n ease_in_out: z.string().optional().describe('Ease-in-out timing function'),\n }).optional(),\n});\n\n/**\n * Z-Index Scale Schema\n * Layering and stacking order.\n */\nexport const ZIndexSchema = z.object({\n base: z.number().optional().describe('Base z-index (e.g., 0)'),\n dropdown: z.number().optional().describe('Dropdown z-index (e.g., 1000)'),\n sticky: z.number().optional().describe('Sticky z-index (e.g., 1020)'),\n fixed: z.number().optional().describe('Fixed z-index (e.g., 1030)'),\n modalBackdrop: z.number().optional().describe('Modal backdrop z-index (e.g., 1040)'),\n modal: z.number().optional().describe('Modal z-index (e.g., 1050)'),\n popover: z.number().optional().describe('Popover z-index (e.g., 1060)'),\n tooltip: z.number().optional().describe('Tooltip z-index (e.g., 1070)'),\n});\n\n/**\n * Theme Mode Schema\n */\nexport const ThemeModeSchema = z.enum(['light', 'dark', 'auto']);\n\n/** @deprecated Use ThemeModeSchema instead */\nexport const ThemeMode = ThemeModeSchema;\n\n/**\n * Density Mode Schema\n * Controls spacing and sizing for different use cases.\n */\nexport const DensityModeSchema = z.enum(['compact', 'regular', 'spacious']);\n\n/** @deprecated Use DensityModeSchema instead */\nexport const DensityMode = DensityModeSchema;\n\n/**\n * WCAG Contrast Level Schema\n * Web Content Accessibility Guidelines color contrast requirements.\n */\nexport const WcagContrastLevelSchema = z.enum(['AA', 'AAA']);\n\n/** @deprecated Use WcagContrastLevelSchema instead */\nexport const WcagContrastLevel = WcagContrastLevelSchema;\n\n/**\n * Theme Configuration Schema\n * Complete theme definition for brand customization.\n */\nexport const ThemeSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Unique theme identifier (snake_case)'),\n label: z.string().describe('Human-readable theme name'),\n description: z.string().optional().describe('Theme description'),\n \n /** Theme mode */\n mode: ThemeModeSchema.default('light').describe('Theme mode (light, dark, or auto)'),\n \n /** Color system */\n colors: ColorPaletteSchema.describe('Color palette configuration'),\n \n /** Typography */\n typography: TypographySchema.optional().describe('Typography settings'),\n \n /** Spacing */\n spacing: SpacingSchema.optional().describe('Spacing scale'),\n \n /** Border radius */\n borderRadius: BorderRadiusSchema.optional().describe('Border radius scale'),\n \n /** Shadows */\n shadows: ShadowSchema.optional().describe('Box shadow effects'),\n \n /** Breakpoints */\n breakpoints: BreakpointsSchema.optional().describe('Responsive breakpoints'),\n \n /** Animation */\n animation: AnimationSchema.optional().describe('Animation settings'),\n \n /** Z-Index */\n zIndex: ZIndexSchema.optional().describe('Z-index scale for layering'),\n \n /** Custom CSS variables */\n customVars: z.record(z.string(), z.string()).optional().describe('Custom CSS variables (key-value pairs)'),\n \n /** Logo */\n logo: z.object({\n light: z.string().optional().describe('Logo URL for light mode'),\n dark: z.string().optional().describe('Logo URL for dark mode'),\n favicon: z.string().optional().describe('Favicon URL'),\n }).optional().describe('Logo assets'),\n \n /** Extends another theme */\n extends: z.string().optional().describe('Base theme to extend from'),\n\n /** Display density mode */\n density: DensityModeSchema.optional().describe('Display density: compact, regular, or spacious'),\n\n /** WCAG contrast level requirement */\n wcagContrast: WcagContrastLevelSchema.optional().describe('WCAG color contrast level (AA or AAA)'),\n\n /** Right-to-left language support */\n rtl: z.boolean().optional().describe('Enable right-to-left layout direction'),\n\n /** Touch target accessibility configuration */\n touchTarget: TouchTargetConfigSchema.optional().describe('Touch target sizing defaults'),\n\n /** Keyboard navigation and focus management */\n keyboardNavigation: FocusManagementSchema.optional().describe('Keyboard focus management settings'),\n});\n\nexport type Theme = z.infer;\nexport type ColorPalette = z.infer;\nexport type Typography = z.infer;\nexport type Spacing = z.infer;\nexport type BorderRadius = z.infer;\nexport type Shadow = z.infer;\nexport type Breakpoints = z.infer;\nexport type Animation = z.infer;\nexport type ZIndex = z.infer;\nexport type ThemeMode = z.infer;\nexport type DensityMode = z.infer;\nexport type WcagContrastLevel = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema } from './i18n.zod';\n\n/**\n * Offline Strategy Schema\n * Determines how data is fetched when connectivity is limited.\n */\nexport const OfflineStrategySchema = z.enum([\n 'cache_first',\n 'network_first',\n 'stale_while_revalidate',\n 'network_only',\n 'cache_only',\n]).describe('Data fetching strategy for offline/online transitions');\n\nexport type OfflineStrategy = z.infer;\n\n/**\n * Conflict Resolution Strategy Enum\n */\nexport const ConflictResolutionSchema = z.enum([\n 'client_wins',\n 'server_wins',\n 'manual',\n 'last_write_wins',\n]).describe('How to resolve conflicts when syncing offline changes');\n\nexport type ConflictResolution = z.infer;\n\n/**\n * Sync Configuration Schema\n * Controls how offline mutations are synchronized with the server.\n */\nexport const SyncConfigSchema = z.object({\n strategy: OfflineStrategySchema.default('network_first').describe('Sync fetch strategy'),\n conflictResolution: ConflictResolutionSchema.default('last_write_wins').describe('Conflict resolution policy'),\n retryInterval: z.number().optional().describe('Retry interval in milliseconds between sync attempts'),\n maxRetries: z.number().optional().describe('Maximum number of sync retry attempts'),\n batchSize: z.number().optional().describe('Number of mutations to sync per batch'),\n}).describe('Offline-to-online synchronization configuration');\n\nexport type SyncConfig = z.infer;\n\n/**\n * Persist Storage Backend Enum\n */\nexport const PersistStorageSchema = z.enum([\n 'indexeddb',\n 'localstorage',\n 'sqlite',\n]).describe('Client-side storage backend for offline cache');\n\nexport type PersistStorage = z.infer;\n\n/**\n * Eviction Policy Enum\n */\nexport const EvictionPolicySchema = z.enum([\n 'lru',\n 'lfu',\n 'fifo',\n]).describe('Cache eviction policy');\n\nexport type EvictionPolicy = z.infer;\n\n/**\n * Offline Cache Configuration Schema\n * Controls how data is persisted on the client for offline access.\n */\nexport const OfflineCacheConfigSchema = z.object({\n maxSize: z.number().optional().describe('Maximum cache size in bytes'),\n ttl: z.number().optional().describe('Time-to-live for cached entries in milliseconds'),\n persistStorage: PersistStorageSchema.default('indexeddb').describe('Storage backend'),\n evictionPolicy: EvictionPolicySchema.default('lru').describe('Cache eviction policy when full'),\n}).describe('Client-side offline cache configuration');\n\nexport type OfflineCacheConfig = z.infer;\n\n/**\n * Offline Configuration Schema\n * Top-level offline support configuration for an application or component.\n */\nexport const OfflineConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable offline support'),\n strategy: OfflineStrategySchema.default('network_first').describe('Default offline fetch strategy'),\n cache: OfflineCacheConfigSchema.optional().describe('Cache settings for offline data'),\n sync: SyncConfigSchema.optional().describe('Sync settings for offline mutations'),\n offlineIndicator: z.boolean().default(true).describe('Show a visual indicator when offline'),\n offlineMessage: I18nLabelSchema.optional().describe('Customizable offline status message shown to users'),\n queueMaxSize: z.number().optional().describe('Maximum number of queued offline mutations'),\n}).describe('Offline support configuration');\n\nexport type OfflineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Transition Preset Schema\n * Common animation transition presets.\n */\nexport const TransitionPresetSchema = z.enum([\n 'fade',\n 'slide_up',\n 'slide_down',\n 'slide_left',\n 'slide_right',\n 'scale',\n 'rotate',\n 'flip',\n 'none',\n]).describe('Transition preset type');\n\nexport type TransitionPreset = z.infer;\n\n/**\n * Easing Function Schema\n * Supported animation easing/timing functions.\n */\nexport const EasingFunctionSchema = z.enum([\n 'linear',\n 'ease',\n 'ease_in',\n 'ease_out',\n 'ease_in_out',\n 'spring',\n]).describe('Animation easing function');\n\nexport type EasingFunction = z.infer;\n\n/**\n * Transition Configuration Schema\n * Defines a single animation transition with timing and easing options.\n */\nexport const TransitionConfigSchema = z.object({\n preset: TransitionPresetSchema.optional().describe('Transition preset to apply'),\n duration: z.number().optional().describe('Transition duration in milliseconds'),\n easing: EasingFunctionSchema.optional().describe('Easing function for the transition'),\n delay: z.number().optional().describe('Delay before transition starts in milliseconds'),\n customKeyframes: z.string().optional().describe('CSS @keyframes name for custom animations'),\n themeToken: z.string().optional().describe('Reference to a theme animation token (e.g. \"animation.duration.fast\")'),\n}).describe('Animation transition configuration');\n\nexport type TransitionConfig = z.infer;\n\n/**\n * Animation Trigger Schema\n * Events that can trigger an animation.\n */\nexport const AnimationTriggerSchema = z.enum([\n 'on_mount',\n 'on_unmount',\n 'on_hover',\n 'on_focus',\n 'on_click',\n 'on_scroll',\n 'on_visible',\n]).describe('Event that triggers the animation');\n\nexport type AnimationTrigger = z.infer;\n\n/**\n * Component Animation Schema\n * Animation configuration for an individual UI component.\n */\nexport const ComponentAnimationSchema = z.object({\n label: I18nLabelSchema.optional().describe('Descriptive label for this animation configuration'),\n enter: TransitionConfigSchema.optional().describe('Enter/mount animation'),\n exit: TransitionConfigSchema.optional().describe('Exit/unmount animation'),\n hover: TransitionConfigSchema.optional().describe('Hover state animation'),\n trigger: AnimationTriggerSchema.optional().describe('When to trigger the animation'),\n reducedMotion: z.enum(['respect', 'disable', 'alternative']).default('respect')\n .describe('Accessibility: how to handle prefers-reduced-motion'),\n}).merge(AriaPropsSchema.partial()).describe('Component-level animation configuration');\n\nexport type ComponentAnimation = z.infer;\n\n/**\n * Page Transition Schema\n * Defines the animation used when navigating between pages.\n */\nexport const PageTransitionSchema = z.object({\n type: TransitionPresetSchema.default('fade').describe('Page transition type'),\n duration: z.number().default(300).describe('Transition duration in milliseconds'),\n easing: EasingFunctionSchema.default('ease_in_out').describe('Easing function for the transition'),\n crossFade: z.boolean().default(false).describe('Whether to cross-fade between pages'),\n}).describe('Page-level transition configuration');\n\nexport type PageTransition = z.infer;\n\n/**\n * Motion Configuration Schema\n * Top-level animation and motion design configuration.\n */\nexport const MotionConfigSchema = z.object({\n label: I18nLabelSchema.optional().describe('Descriptive label for the motion configuration'),\n defaultTransition: TransitionConfigSchema.optional().describe('Default transition applied to all animations'),\n pageTransitions: PageTransitionSchema.optional().describe('Page navigation transition settings'),\n componentAnimations: z.record(z.string(), ComponentAnimationSchema).optional()\n .describe('Component name to animation configuration mapping'),\n reducedMotion: z.boolean().default(false).describe('When true, respect prefers-reduced-motion and suppress animations globally'),\n enabled: z.boolean().default(true).describe('Enable or disable all animations globally'),\n}).describe('Top-level motion and animation design configuration');\n\nexport type MotionConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Notification Type Schema\n * Defines the visual presentation style of the notification.\n */\nexport const NotificationTypeSchema = z.enum([\n 'toast',\n 'snackbar',\n 'banner',\n 'alert',\n 'inline',\n]).describe('Notification presentation style');\n\nexport type NotificationType = z.infer;\n\n/**\n * Notification Severity Schema\n * Indicates the urgency and visual treatment of the notification.\n */\nexport const NotificationSeveritySchema = z.enum([\n 'info',\n 'success',\n 'warning',\n 'error',\n]).describe('Notification severity level');\n\nexport type NotificationSeverity = z.infer;\n\n/**\n * Notification Position Schema\n * Screen position for rendering notifications.\n */\nexport const NotificationPositionSchema = z.enum([\n 'top_left',\n 'top_center',\n 'top_right',\n 'bottom_left',\n 'bottom_center',\n 'bottom_right',\n]).describe('Screen position for notification placement');\n\nexport type NotificationPosition = z.infer;\n\n/**\n * Notification Action Schema\n * Defines an interactive action button within a notification.\n */\nexport const NotificationActionSchema = z.object({\n label: I18nLabelSchema.describe('Action button label'),\n action: z.string().describe('Action identifier to execute'),\n variant: z.enum(['primary', 'secondary', 'link']).default('primary')\n .describe('Button variant style'),\n}).describe('Notification action button');\n\nexport type NotificationAction = z.infer;\n\n/**\n * Notification Schema\n * Defines a single notification instance with content, behavior, and positioning.\n */\nexport const NotificationSchema = z.object({\n type: NotificationTypeSchema.default('toast').describe('Notification presentation style'),\n severity: NotificationSeveritySchema.default('info').describe('Notification severity level'),\n title: I18nLabelSchema.optional().describe('Notification title'),\n message: I18nLabelSchema.describe('Notification message body'),\n icon: z.string().optional().describe('Icon name override'),\n duration: z.number().optional().describe('Auto-dismiss duration in ms, omit for persistent'),\n dismissible: z.boolean().default(true).describe('Allow user to dismiss the notification'),\n actions: z.array(NotificationActionSchema).optional().describe('Action buttons'),\n position: NotificationPositionSchema.optional().describe('Override default position'),\n}).merge(AriaPropsSchema.partial()).describe('Notification instance definition');\n\nexport type Notification = z.infer;\n\n/**\n * Notification Config Schema\n * Top-level notification system configuration.\n */\nexport const NotificationConfigSchema = z.object({\n defaultPosition: NotificationPositionSchema.default('top_right')\n .describe('Default screen position for notifications'),\n defaultDuration: z.number().default(5000)\n .describe('Default auto-dismiss duration in ms'),\n maxVisible: z.number().default(5)\n .describe('Maximum number of notifications visible at once'),\n stackDirection: z.enum(['up', 'down']).default('down')\n .describe('Stack direction for multiple notifications'),\n pauseOnHover: z.boolean().default(true)\n .describe('Pause auto-dismiss timer on hover'),\n}).describe('Global notification system configuration');\n\nexport type NotificationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Drag Handle Schema\n * Defines how a drag interaction is initiated on an element.\n */\nexport const DragHandleSchema = z.enum([\n 'element',\n 'handle',\n 'grip_icon',\n]).describe('Drag initiation method');\n\nexport type DragHandle = z.infer;\n\n/**\n * Drop Effect Schema\n * Visual feedback indicating the result of a drop operation.\n */\nexport const DropEffectSchema = z.enum([\n 'move',\n 'copy',\n 'link',\n 'none',\n]).describe('Drop operation effect');\n\nexport type DropEffect = z.infer;\n\n/**\n * Drag Constraint Schema\n * Constrains drag movement along axes, within bounds, or to a grid.\n */\nexport const DragConstraintSchema = z.object({\n axis: z.enum(['x', 'y', 'both']).default('both').describe('Constrain drag axis'),\n bounds: z.enum(['parent', 'viewport', 'none']).default('none').describe('Constrain within bounds'),\n grid: z.tuple([z.number(), z.number()]).optional().describe('Snap to grid [x, y] in pixels'),\n}).describe('Drag movement constraints');\n\nexport type DragConstraint = z.infer;\n\n/**\n * Drop Zone Schema\n * Configures a container that accepts dragged items.\n */\nexport const DropZoneSchema = z.object({\n label: I18nLabelSchema.optional().describe('Accessible label for the drop zone'),\n accept: z.array(z.string()).describe('Accepted drag item types'),\n maxItems: z.number().optional().describe('Maximum items allowed in drop zone'),\n highlightOnDragOver: z.boolean().default(true).describe('Highlight drop zone when dragging over'),\n dropEffect: DropEffectSchema.default('move').describe('Visual effect on drop'),\n}).merge(AriaPropsSchema.partial()).describe('Drop zone configuration');\n\nexport type DropZone = z.infer;\n\n/**\n * Drag Item Schema\n * Configures a draggable element including handle, constraints, and preview.\n */\nexport const DragItemSchema = z.object({\n type: z.string().describe('Drag item type identifier for matching with drop zones'),\n label: I18nLabelSchema.optional().describe('Accessible label describing the draggable item'),\n handle: DragHandleSchema.default('element').describe('How to initiate drag'),\n constraint: DragConstraintSchema.optional().describe('Drag movement constraints'),\n preview: z.enum(['element', 'custom', 'none']).default('element').describe('Drag preview type'),\n disabled: z.boolean().default(false).describe('Disable dragging'),\n}).merge(AriaPropsSchema.partial()).describe('Draggable item configuration');\n\nexport type DragItem = z.infer;\n\n/**\n * Drag and Drop Configuration Schema\n * Top-level drag-and-drop interaction configuration for a component.\n */\nexport const DndConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable drag and drop'),\n dragItem: DragItemSchema.optional().describe('Configuration for draggable item'),\n dropZone: DropZoneSchema.optional().describe('Configuration for drop target'),\n sortable: z.boolean().default(false).describe('Enable sortable list behavior'),\n autoScroll: z.boolean().default(true).describe('Auto-scroll during drag near edges'),\n touchDelay: z.number().default(200).describe('Delay in ms before drag starts on touch devices'),\n}).describe('Drag and drop interaction configuration');\n\nexport type DndConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * LocalStoragePersistenceAdapter\n *\n * Persists the in-memory database to browser localStorage.\n * Synchronous storage with a ~5MB size limit warning.\n *\n * Browser only — will throw if used in non-browser environments.\n */\nexport class LocalStoragePersistenceAdapter {\n private readonly storageKey: string;\n private static readonly SIZE_WARNING_BYTES = 4.5 * 1024 * 1024; // 4.5MB warning threshold\n\n constructor(options?: { key?: string }) {\n this.storageKey = options?.key || 'objectstack:memory-db';\n }\n\n /**\n * Load persisted data from localStorage.\n * Returns null if no data exists.\n */\n async load(): Promise | null> {\n try {\n const raw = localStorage.getItem(this.storageKey);\n if (!raw) return null;\n return JSON.parse(raw) as Record;\n } catch {\n return null;\n }\n }\n\n /**\n * Save data to localStorage.\n * Warns if data size approaches the ~5MB localStorage limit.\n */\n async save(db: Record): Promise {\n const json = JSON.stringify(db);\n\n if (json.length > LocalStoragePersistenceAdapter.SIZE_WARNING_BYTES) {\n console.warn(\n `[ObjectStack] localStorage persistence data size (${(json.length / 1024 / 1024).toFixed(2)}MB) ` +\n `is approaching the ~5MB limit. Consider using a different persistence strategy.`\n );\n }\n\n try {\n localStorage.setItem(this.storageKey, json);\n } catch (e: any) {\n console.error('[ObjectStack] Failed to persist data to localStorage:', e?.message || e);\n }\n }\n\n /**\n * Flush is a no-op for localStorage (writes are synchronous).\n */\n async flush(): Promise {\n // localStorage writes are synchronous, no flushing needed\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * FileSystemPersistenceAdapter\n *\n * Persists the in-memory database to a JSON file on disk.\n * Supports atomic writes (write to temp file then rename) and auto-save with dirty tracking.\n *\n * Node.js only — will throw if used in non-Node.js environments.\n */\nexport class FileSystemPersistenceAdapter {\n private readonly filePath: string;\n private readonly autoSaveInterval: number;\n private dirty = false;\n private timer: ReturnType | null = null;\n private currentDb: Record | null = null;\n\n constructor(options?: { path?: string; autoSaveInterval?: number }) {\n this.filePath = options?.path || path.join('.objectstack', 'data', 'memory-driver.json');\n this.autoSaveInterval = options?.autoSaveInterval ?? 2000;\n }\n\n /**\n * Load persisted data from disk.\n * Returns null if no file exists.\n */\n async load(): Promise | null> {\n try {\n if (!fs.existsSync(this.filePath)) {\n return null;\n }\n const raw = fs.readFileSync(this.filePath, 'utf-8');\n const data = JSON.parse(raw);\n return data as Record;\n } catch {\n return null;\n }\n }\n\n /**\n * Save data to disk using atomic write (temp file + rename).\n */\n async save(db: Record): Promise {\n this.currentDb = db;\n this.dirty = true;\n }\n\n /**\n * Flush pending writes to disk immediately.\n */\n async flush(): Promise {\n if (!this.dirty || !this.currentDb) return;\n await this.writeToDisk(this.currentDb);\n this.dirty = false;\n }\n\n /**\n * Start the auto-save timer.\n */\n startAutoSave(): void {\n if (this.timer) return;\n this.timer = setInterval(async () => {\n if (this.dirty && this.currentDb) {\n await this.writeToDisk(this.currentDb);\n this.dirty = false;\n }\n }, this.autoSaveInterval);\n\n // Allow process to exit even if timer is running\n if (this.timer) {\n this.timer.unref();\n }\n }\n\n /**\n * Stop the auto-save timer and flush pending writes.\n */\n async stopAutoSave(): Promise {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n await this.flush();\n }\n\n /**\n * Atomic write: write to temp file, then rename.\n */\n private async writeToDisk(db: Record): Promise {\n const dir = path.dirname(this.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n const tmpPath = this.filePath + '.tmp';\n const json = JSON.stringify(db, null, 2);\n fs.writeFileSync(tmpPath, json, 'utf-8');\n fs.renameSync(tmpPath, this.filePath);\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { QueryAST, QueryInput, DriverOptions } from '@objectstack/spec/data';\nimport type { IDataDriver } from '@objectstack/spec/contracts';\nimport { Logger, createLogger } from '@objectstack/core';\nimport { Query, Aggregator } from 'mingo';\nimport { getValueByPath } from './memory-matcher.js';\n\n/**\n * Persistence adapter interface.\n * Matches the PersistenceAdapterSchema contract from @objectstack/spec.\n */\nexport interface PersistenceAdapterInterface {\n load(): Promise | null>;\n save(db: Record): Promise;\n flush(): Promise;\n /** Optional: Start periodic auto-save (used by FileSystemPersistenceAdapter). */\n startAutoSave?(): void;\n /** Optional: Stop auto-save timer and flush pending writes. */\n stopAutoSave?(): Promise;\n}\n\n/**\n * Configuration options for the InMemory driver.\n * Aligned with @objectstack/spec MemoryConfigSchema.\n */\nexport interface InMemoryDriverConfig {\n /** Optional: Initial data to populate the store */\n initialData?: Record[]>;\n /** Optional: Enable strict mode (throw on missing records) */\n strictMode?: boolean;\n /** Optional: Logger instance */\n logger?: Logger;\n /**\n * Persistence configuration. Defaults to `'auto'`.\n * - `'auto'` (default) — Auto-detect environment (browser → localStorage, Node.js → file, serverless → disabled)\n * - `'file'` — File-system persistence with defaults (Node.js only)\n * - `'local'` — localStorage persistence with defaults (Browser only)\n * - `{ type: 'file', path?: string, autoSaveInterval?: number }` — File-system with options\n * - `{ type: 'local', key?: string }` — localStorage with options\n * - `{ type: 'auto', path?: string, key?: string, autoSaveInterval?: number }` — Auto-detect with options\n * - `{ adapter: PersistenceAdapterInterface }` — Custom adapter\n * - `false` — Disable persistence (pure in-memory)\n *\n * ⚠️ In serverless environments (Vercel, AWS Lambda, Netlify, etc.),\n * auto mode disables file persistence to prevent silent data loss.\n * Use `persistence: false` or supply a custom adapter for serverless deployments.\n */\n persistence?: string | false | {\n type?: 'file' | 'local' | 'auto';\n path?: string;\n key?: string;\n autoSaveInterval?: number;\n adapter?: PersistenceAdapterInterface;\n };\n}\n\n/**\n * Snapshot for in-memory transactions.\n */\ninterface MemoryTransaction {\n id: string;\n snapshot: Record;\n}\n\n/**\n * In-Memory Driver for ObjectStack\n * \n * A production-ready implementation of the ObjectStack Driver Protocol\n * powered by Mingo — a MongoDB-compatible query and aggregation engine.\n * \n * Features:\n * - MongoDB-compatible query engine (Mingo) for filtering, projection, aggregation\n * - Full CRUD and bulk operations\n * - Aggregation pipeline support ($match, $group, $sort, $project, $unwind, etc.)\n * - Snapshot-based transactions (begin/commit/rollback)\n * - Field projection and distinct values\n * - Strict mode and initial data loading\n * \n * Reference: objectql/packages/drivers/memory\n */\nexport class InMemoryDriver implements IDataDriver {\n readonly name = 'com.objectstack.driver.memory';\n type = 'driver';\n readonly version = '1.0.0';\n private config: InMemoryDriverConfig;\n private logger: Logger;\n private idCounters: Map = new Map();\n private transactions: Map = new Map();\n private persistenceAdapter: PersistenceAdapterInterface | null = null;\n\n constructor(config?: InMemoryDriverConfig) {\n this.config = config || {};\n this.logger = config?.logger || createLogger({ level: 'info', format: 'pretty' });\n this.logger.debug('InMemory driver instance created');\n }\n\n // Duck-typed RuntimePlugin hook\n install(ctx: any) {\n this.logger.debug('Installing InMemory driver via plugin hook');\n if (ctx.engine && ctx.engine.ql && typeof ctx.engine.ql.registerDriver === 'function') {\n ctx.engine.ql.registerDriver(this);\n this.logger.info('InMemory driver registered with ObjectQL engine');\n } else {\n this.logger.warn('Could not register driver - ObjectQL engine not found in context');\n }\n }\n \n readonly supports = {\n // Basic CRUD Operations\n create: true,\n read: true,\n update: true,\n delete: true,\n\n // Bulk Operations\n bulkCreate: true,\n bulkUpdate: true,\n bulkDelete: true,\n\n // Transaction & Connection Management\n transactions: true, // Snapshot-based transactions\n savepoints: false,\n \n // Query Operations\n queryFilters: true, // Implemented via memory-matcher\n queryAggregations: true, // Implemented\n querySorting: true, // Implemented via JS sort\n queryPagination: true, // Implemented\n queryWindowFunctions: false, // @planned: Window functions (ROW_NUMBER, RANK, etc.)\n querySubqueries: false, // @planned: Subquery execution\n queryCTE: false,\n joins: false, // @planned: In-memory join operations\n \n // Advanced Features\n fullTextSearch: false, // @planned: Text tokenization + matching\n jsonQuery: false,\n geospatialQuery: false,\n streaming: true, // Implemented via findStream()\n jsonFields: true, // Native JS object support\n arrayFields: true, // Native JS array support\n vectorSearch: false, // @planned: Cosine similarity search\n\n // Schema Management\n schemaSync: true, // Implemented via syncSchema()\n batchSchemaSync: false,\n migrations: false,\n indexes: false,\n\n // Performance & Optimization\n connectionPooling: false,\n preparedStatements: false,\n queryCache: false,\n };\n\n /**\n * The \"Database\": A map of TableName -> Array of Records\n */\n private db: Record = {};\n\n // ===================================\n // Lifecycle\n // ===================================\n\n async connect() {\n // Initialize persistence adapter if configured\n await this.initPersistence();\n\n // Load persisted data if available\n if (this.persistenceAdapter) {\n const persisted = await this.persistenceAdapter.load();\n if (persisted) {\n for (const [objectName, records] of Object.entries(persisted)) {\n this.db[objectName] = records;\n // Update ID counters based on persisted data\n for (const record of records) {\n if (record.id && typeof record.id === 'string') {\n // ID format: {objectName}-{timestamp}-{counter}\n const parts = record.id.split('-');\n const lastPart = parts[parts.length - 1];\n const counter = parseInt(lastPart, 10);\n if (!isNaN(counter)) {\n const current = this.idCounters.get(objectName) || 0;\n if (counter > current) {\n this.idCounters.set(objectName, counter);\n }\n }\n }\n }\n }\n this.logger.info('InMemory Database restored from persistence', {\n tables: Object.keys(persisted).length,\n });\n }\n }\n\n // Load initial data if provided\n if (this.config.initialData) {\n for (const [objectName, records] of Object.entries(this.config.initialData)) {\n const table = this.getTable(objectName);\n for (const record of records) {\n const id = (record as any).id || this.generateId(objectName);\n table.push({ ...record, id });\n }\n }\n this.logger.info('InMemory Database Connected with initial data', {\n tables: Object.keys(this.config.initialData).length,\n });\n } else {\n this.logger.info('InMemory Database Connected (Virtual)');\n }\n\n // Start auto-save if using file adapter\n if (this.persistenceAdapter?.startAutoSave) {\n this.persistenceAdapter.startAutoSave();\n }\n }\n\n async disconnect() {\n // Stop auto-save and flush pending writes\n if (this.persistenceAdapter) {\n if (this.persistenceAdapter.stopAutoSave) {\n await this.persistenceAdapter.stopAutoSave();\n }\n await this.persistenceAdapter.flush();\n }\n\n const tableCount = Object.keys(this.db).length;\n const recordCount = Object.values(this.db).reduce((sum, table) => sum + table.length, 0);\n \n this.db = {};\n this.logger.info('InMemory Database Disconnected & Cleared', { \n tableCount, \n recordCount \n });\n }\n\n async checkHealth() {\n this.logger.debug('Health check performed', { \n tableCount: Object.keys(this.db).length,\n status: 'healthy' \n });\n return true; \n }\n\n // ===================================\n // Execution\n // ===================================\n\n async execute(command: any, params?: any[]) {\n this.logger.warn('Raw execution not supported in InMemory driver', { command });\n return null;\n }\n\n // ===================================\n // CRUD\n // ===================================\n\n async find(object: string, query: QueryAST, options?: DriverOptions) {\n this.logger.debug('Find operation', { object, query });\n \n const table = this.getTable(object);\n let results = [...table]; // Work on copy\n\n // 1. Filter using Mingo\n if (query.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n results = mingoQuery.find(results).all();\n }\n }\n\n // 1.5 Aggregation & Grouping\n if (query.groupBy || (query.aggregations && query.aggregations.length > 0)) {\n results = this.performAggregation(results, query);\n }\n\n // 2. Sort\n if (query.orderBy) {\n const sortFields = Array.isArray(query.orderBy) ? query.orderBy : [query.orderBy];\n results = this.applySort(results, sortFields);\n }\n\n // 3. Pagination (Offset)\n if (query.offset) {\n results = results.slice(query.offset);\n }\n\n // 4. Pagination (Limit)\n if (query.limit) {\n results = results.slice(0, query.limit);\n }\n\n // 5. Field Projection\n if (query.fields && Array.isArray(query.fields) && query.fields.length > 0) {\n results = results.map(record => this.projectFields(record, query.fields as string[]));\n }\n\n this.logger.debug('Find completed', { object, resultCount: results.length });\n return results;\n }\n\n async *findStream(object: string, query: QueryAST, options?: DriverOptions) {\n this.logger.debug('FindStream operation', { object });\n \n const results = await this.find(object, query, options);\n for (const record of results) {\n yield record;\n }\n }\n\n async findOne(object: string, query: QueryAST, options?: DriverOptions) {\n this.logger.debug('FindOne operation', { object, query });\n \n const results = await this.find(object, { ...query, limit: 1 }, options);\n const result = results[0] || null;\n \n this.logger.debug('FindOne completed', { object, found: !!result });\n return result;\n }\n\n async create(object: string, data: Record, options?: DriverOptions) {\n this.logger.debug('Create operation', { object, hasData: !!data });\n \n const table = this.getTable(object);\n \n const newRecord = {\n id: data.id || this.generateId(object),\n ...data,\n created_at: data.created_at || new Date().toISOString(),\n updated_at: data.updated_at || new Date().toISOString(),\n };\n\n table.push(newRecord);\n this.markDirty();\n this.logger.debug('Record created', { object, id: newRecord.id, tableSize: table.length });\n return { ...newRecord };\n }\n\n async update(object: string, id: string | number, data: Record, options?: DriverOptions) {\n this.logger.debug('Update operation', { object, id });\n \n const table = this.getTable(object);\n const index = table.findIndex(r => r.id == id);\n \n if (index === -1) {\n if (this.config.strictMode) {\n this.logger.warn('Record not found for update', { object, id });\n throw new Error(`Record with ID ${id} not found in ${object}`);\n }\n return null;\n }\n\n const updatedRecord = {\n ...table[index],\n ...data,\n id: table[index].id, // Preserve original ID\n created_at: table[index].created_at, // Preserve created_at\n updated_at: new Date().toISOString(),\n };\n \n table[index] = updatedRecord;\n this.markDirty();\n this.logger.debug('Record updated', { object, id });\n return { ...updatedRecord };\n }\n\n async upsert(object: string, data: Record, conflictKeys?: string[], options?: DriverOptions) {\n this.logger.debug('Upsert operation', { object, conflictKeys });\n \n const table = this.getTable(object);\n let existingRecord: any = null;\n\n if (data.id) {\n existingRecord = table.find(r => r.id === data.id);\n } else if (conflictKeys && conflictKeys.length > 0) {\n existingRecord = table.find(r => conflictKeys.every(key => r[key] === data[key]));\n }\n\n if (existingRecord) {\n this.logger.debug('Record exists, updating', { object, id: existingRecord.id });\n return this.update(object, existingRecord.id, data, options);\n } else {\n this.logger.debug('Record does not exist, creating', { object });\n return this.create(object, data, options);\n }\n }\n\n async delete(object: string, id: string | number, options?: DriverOptions) {\n this.logger.debug('Delete operation', { object, id });\n \n const table = this.getTable(object);\n const index = table.findIndex(r => r.id == id);\n \n if (index === -1) {\n if (this.config.strictMode) {\n throw new Error(`Record with ID ${id} not found in ${object}`);\n }\n this.logger.warn('Record not found for deletion', { object, id });\n return false;\n }\n\n table.splice(index, 1);\n this.markDirty();\n this.logger.debug('Record deleted', { object, id, tableSize: table.length });\n return true;\n }\n\n async count(object: string, query?: QueryAST, options?: DriverOptions) {\n let records = this.getTable(object);\n if (query?.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n records = mingoQuery.find(records).all();\n }\n }\n const count = records.length;\n this.logger.debug('Count operation', { object, count });\n return count;\n }\n\n // ===================================\n // Bulk Operations\n // ===================================\n\n async bulkCreate(object: string, dataArray: Record[], options?: DriverOptions) {\n this.logger.debug('BulkCreate operation', { object, count: dataArray.length });\n const results = await Promise.all(dataArray.map(data => this.create(object, data, options)));\n this.logger.debug('BulkCreate completed', { object, count: results.length });\n return results;\n }\n \n async updateMany(object: string, query: QueryAST, data: Record, options?: DriverOptions): Promise {\n this.logger.debug('UpdateMany operation', { object, query });\n \n const table = this.getTable(object);\n let targetRecords = table;\n \n if (query && query.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n targetRecords = mingoQuery.find(targetRecords).all();\n }\n }\n \n const count = targetRecords.length;\n \n for (const record of targetRecords) {\n const index = table.findIndex(r => r.id === record.id);\n if (index !== -1) {\n const updated = {\n ...table[index],\n ...data,\n updated_at: new Date().toISOString()\n };\n table[index] = updated;\n }\n }\n \n if (count > 0) this.markDirty();\n this.logger.debug('UpdateMany completed', { object, count });\n return count;\n }\n\n async deleteMany(object: string, query: QueryAST, options?: DriverOptions): Promise {\n this.logger.debug('DeleteMany operation', { object, query });\n \n const table = this.getTable(object);\n const initialLength = table.length;\n \n if (query && query.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n const matched = mingoQuery.find(table).all();\n const matchedIds = new Set(matched.map((r: any) => r.id));\n this.db[object] = table.filter(r => !matchedIds.has(r.id));\n } else {\n // Empty query = delete all\n this.db[object] = [];\n }\n } else {\n // No where clause = delete all\n this.db[object] = [];\n }\n \n const count = initialLength - this.db[object].length;\n if (count > 0) this.markDirty();\n this.logger.debug('DeleteMany completed', { object, count });\n return count;\n }\n\n // Compatibility aliases\n async bulkUpdate(object: string, updates: { id: string | number, data: Record }[], options?: DriverOptions) {\n this.logger.debug('BulkUpdate operation', { object, count: updates.length });\n const results = await Promise.all(updates.map(u => this.update(object, u.id, u.data, options)));\n this.logger.debug('BulkUpdate completed', { object, count: results.length });\n return results;\n }\n\n async bulkDelete(object: string, ids: (string | number)[], options?: DriverOptions) {\n this.logger.debug('BulkDelete operation', { object, count: ids.length });\n await Promise.all(ids.map(id => this.delete(object, id, options)));\n this.logger.debug('BulkDelete completed', { object, count: ids.length });\n }\n\n // ===================================\n // Transaction Management\n // ===================================\n\n async beginTransaction() {\n const txId = `tx_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\n // Deep-clone current database state as a snapshot\n const snapshot: Record = {};\n for (const [table, records] of Object.entries(this.db)) {\n snapshot[table] = records.map(r => ({ ...r }));\n }\n\n const transaction: MemoryTransaction = { id: txId, snapshot };\n this.transactions.set(txId, transaction);\n this.logger.debug('Transaction started', { txId });\n return { id: txId };\n }\n\n async commit(txHandle?: unknown) {\n const txId = (txHandle as any)?.id;\n if (!txId || !this.transactions.has(txId)) {\n this.logger.warn('Commit called with unknown transaction');\n return;\n }\n // Data is already in the store; just remove the snapshot\n this.transactions.delete(txId);\n this.logger.debug('Transaction committed', { txId });\n }\n\n async rollback(txHandle?: unknown) {\n const txId = (txHandle as any)?.id;\n if (!txId || !this.transactions.has(txId)) {\n this.logger.warn('Rollback called with unknown transaction');\n return;\n }\n const tx = this.transactions.get(txId)!;\n // Restore the snapshot\n this.db = tx.snapshot;\n this.transactions.delete(txId);\n this.markDirty();\n this.logger.debug('Transaction rolled back', { txId });\n }\n\n // ===================================\n // Utility Methods\n // ===================================\n\n /**\n * Remove all data from the store.\n */\n async clear() {\n this.db = {};\n this.idCounters.clear();\n this.markDirty();\n this.logger.debug('All data cleared');\n }\n\n /**\n * Get total number of records across all tables.\n */\n getSize(): number {\n return Object.values(this.db).reduce((sum, table) => sum + table.length, 0);\n }\n\n /**\n * Get distinct values for a field, optionally filtered.\n */\n async distinct(object: string, field: string, query?: QueryInput): Promise {\n let records = this.getTable(object);\n if (query?.where) {\n const mongoQuery = this.convertToMongoQuery(query.where);\n if (mongoQuery && Object.keys(mongoQuery).length > 0) {\n const mingoQuery = new Query(mongoQuery);\n records = mingoQuery.find(records).all();\n }\n }\n const values = new Set();\n for (const record of records) {\n const value = getValueByPath(record, field);\n if (value !== undefined && value !== null) {\n values.add(value);\n }\n }\n return Array.from(values);\n }\n\n /**\n * Execute a MongoDB-style aggregation pipeline using Mingo.\n * \n * Supports all standard MongoDB pipeline stages:\n * - $match, $group, $sort, $project, $unwind, $limit, $skip\n * - $addFields, $replaceRoot, $lookup (limited), $count\n * - Accumulator operators: $sum, $avg, $min, $max, $first, $last, $push, $addToSet\n * \n * @example\n * // Group by status and count\n * const results = await driver.aggregate('orders', [\n * { $match: { status: 'completed' } },\n * { $group: { _id: '$customer', totalAmount: { $sum: '$amount' } } }\n * ]);\n * \n * @example\n * // Calculate average with filter\n * const results = await driver.aggregate('products', [\n * { $match: { category: 'electronics' } },\n * { $group: { _id: null, avgPrice: { $avg: '$price' } } }\n * ]);\n */\n async aggregate(object: string, pipeline: Record[], options?: DriverOptions): Promise {\n this.logger.debug('Aggregate operation', { object, stageCount: pipeline.length });\n \n const records = this.getTable(object).map(r => ({ ...r }));\n const aggregator = new Aggregator(pipeline);\n const results = aggregator.run(records);\n \n this.logger.debug('Aggregate completed', { object, resultCount: results.length });\n return results;\n }\n\n // ===================================\n // Query Conversion (ObjectQL → MongoDB)\n // ===================================\n\n /**\n * Convert ObjectQL filter format to MongoDB query format for Mingo.\n * \n * Supports:\n * 1. AST Comparison Node: { type: 'comparison', field, operator, value }\n * 2. AST Logical Node: { type: 'logical', operator: 'and'|'or', conditions: [...] }\n * 3. Legacy Array Format: [['field', 'op', value], 'and', ['field2', 'op', value2]]\n * 4. MongoDB Format: { field: value } or { field: { $eq: value } } (passthrough)\n */\n private convertToMongoQuery(filters?: any): Record {\n if (!filters) return {};\n\n // AST node format (ObjectQL QueryAST)\n if (!Array.isArray(filters) && typeof filters === 'object') {\n if (filters.type === 'comparison') {\n return this.convertConditionToMongo(filters.field, filters.operator, filters.value) || {};\n }\n if (filters.type === 'logical') {\n const conditions = filters.conditions?.map((c: any) => this.convertToMongoQuery(c)) || [];\n if (conditions.length === 0) return {};\n if (conditions.length === 1) return conditions[0];\n const op = filters.operator === 'or' ? '$or' : '$and';\n return { [op]: conditions };\n }\n // MongoDB/FilterCondition format: { field: value } or { field: { $op: value } }\n // Translate non-standard operators ($contains, $notContains, etc.) to Mingo-compatible format\n return this.normalizeFilterCondition(filters);\n }\n\n // Legacy array format\n if (!Array.isArray(filters) || filters.length === 0) return {};\n\n const logicGroups: { logic: 'and' | 'or'; conditions: Record[] }[] = [\n { logic: 'and', conditions: [] },\n ];\n let currentLogic: 'and' | 'or' = 'and';\n\n for (const item of filters) {\n if (typeof item === 'string') {\n const newLogic = item.toLowerCase() as 'and' | 'or';\n if (newLogic !== currentLogic) {\n currentLogic = newLogic;\n logicGroups.push({ logic: currentLogic, conditions: [] });\n }\n } else if (Array.isArray(item)) {\n const [field, operator, value] = item;\n const cond = this.convertConditionToMongo(field, operator, value);\n if (cond) logicGroups[logicGroups.length - 1].conditions.push(cond);\n }\n }\n\n const allConditions: Record[] = [];\n for (const group of logicGroups) {\n if (group.conditions.length === 0) continue;\n if (group.conditions.length === 1) {\n allConditions.push(group.conditions[0]);\n } else {\n const op = group.logic === 'or' ? '$or' : '$and';\n allConditions.push({ [op]: group.conditions });\n }\n }\n\n if (allConditions.length === 0) return {};\n if (allConditions.length === 1) return allConditions[0];\n return { $and: allConditions };\n }\n\n /**\n * Convert a single ObjectQL condition to MongoDB operator format.\n */\n private convertConditionToMongo(field: string, operator: string, value: any): Record | null {\n switch (operator) {\n case '=': case '==':\n return { [field]: value };\n case '!=': case '<>':\n return { [field]: { $ne: value } };\n case '>':\n return { [field]: { $gt: value } };\n case '>=':\n return { [field]: { $gte: value } };\n case '<':\n return { [field]: { $lt: value } };\n case '<=':\n return { [field]: { $lte: value } };\n case 'in':\n return { [field]: { $in: value } };\n case 'nin': case 'not in':\n return { [field]: { $nin: value } };\n case 'contains': case 'like':\n return { [field]: { $regex: new RegExp(this.escapeRegex(value), 'i') } };\n case 'notcontains': case 'not_contains':\n return { [field]: { $not: { $regex: new RegExp(this.escapeRegex(value), 'i') } } };\n case 'startswith': case 'starts_with':\n return { [field]: { $regex: new RegExp(`^${this.escapeRegex(value)}`, 'i') } };\n case 'endswith': case 'ends_with':\n return { [field]: { $regex: new RegExp(`${this.escapeRegex(value)}$`, 'i') } };\n case 'between':\n if (Array.isArray(value) && value.length === 2) {\n return { [field]: { $gte: value[0], $lte: value[1] } };\n }\n return null;\n default:\n return null;\n }\n }\n\n /**\n * Normalize a FilterCondition object by converting non-standard $-prefixed\n * operators ($contains, $notContains, $startsWith, $endsWith, $between, $null)\n * to Mingo-compatible equivalents ($regex, $gte/$lte, null checks).\n */\n private normalizeFilterCondition(filter: Record): Record {\n const result: Record = {};\n const extraAndConditions: Record[] = [];\n\n for (const key of Object.keys(filter)) {\n const value = filter[key];\n // Recurse into logical operators\n if (key === '$and' || key === '$or') {\n result[key] = Array.isArray(value)\n ? value.map((child: any) => this.normalizeFilterCondition(child))\n : value;\n continue;\n }\n if (key === '$not') {\n result[key] = value && typeof value === 'object'\n ? this.normalizeFilterCondition(value)\n : value;\n continue;\n }\n // Skip $-prefixed keys that aren't field names (already handled or unknown)\n if (key.startsWith('$')) {\n result[key] = value;\n continue;\n }\n // Field-level: value may be primitive (implicit eq) or operator object\n if (value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp)) {\n const normalized = this.normalizeFieldOperators(value);\n // Handle multiple regex conditions on the same field (e.g. $startsWith + $endsWith)\n if (normalized._multiRegex) {\n const regexConditions: Record[] = normalized._multiRegex;\n delete normalized._multiRegex;\n // Each regex becomes its own { field: { $regex: ... } } inside $and\n for (const rc of regexConditions) {\n extraAndConditions.push({ [key]: { ...normalized, ...rc } });\n }\n } else {\n result[key] = normalized;\n }\n } else {\n result[key] = value;\n }\n }\n\n // Merge extra $and conditions from multi-regex fields\n if (extraAndConditions.length > 0) {\n const existing = result.$and;\n const andArray = Array.isArray(existing) ? existing : [];\n // Include the rest of result as a condition too\n if (Object.keys(result).filter(k => k !== '$and').length > 0) {\n const rest = { ...result };\n delete rest.$and;\n andArray.push(rest);\n }\n andArray.push(...extraAndConditions);\n return { $and: andArray };\n }\n\n return result;\n }\n\n /**\n * Convert non-standard field operators to Mingo-compatible format.\n * When multiple regex-producing operators appear on the same field\n * (e.g. $startsWith + $endsWith), they are combined via $and.\n */\n private normalizeFieldOperators(ops: Record): Record {\n const result: Record = {};\n const regexConditions: Record[] = [];\n\n for (const op of Object.keys(ops)) {\n const val = ops[op];\n switch (op) {\n case '$contains':\n regexConditions.push({ $regex: new RegExp(this.escapeRegex(val), 'i') });\n break;\n case '$notContains':\n result.$not = { $regex: new RegExp(this.escapeRegex(val), 'i') };\n break;\n case '$startsWith':\n regexConditions.push({ $regex: new RegExp(`^${this.escapeRegex(val)}`, 'i') });\n break;\n case '$endsWith':\n regexConditions.push({ $regex: new RegExp(`${this.escapeRegex(val)}$`, 'i') });\n break;\n case '$between':\n if (Array.isArray(val) && val.length === 2) {\n result.$gte = val[0];\n result.$lte = val[1];\n }\n break;\n case '$null':\n // $null: true → field is null, $null: false → field is not null\n // Use $eq/$ne null for Mingo compatibility\n if (val === true) {\n result.$eq = null;\n } else {\n result.$ne = null;\n }\n break;\n default:\n result[op] = val;\n break;\n }\n }\n\n // Merge regex conditions: single → inline, multiple → wrap with $and\n if (regexConditions.length === 1) {\n Object.assign(result, regexConditions[0]);\n } else if (regexConditions.length > 1) {\n // Cannot have multiple $regex on one object; promote to top-level $and.\n // _multiRegex is an internal sentinel consumed by normalizeFilterCondition().\n result._multiRegex = regexConditions;\n }\n\n return result;\n }\n\n /**\n * Escape special regex characters for safe literal matching.\n */\n private escapeRegex(str: string): string {\n return String(str).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n\n // ===================================\n // Aggregation Logic\n // ===================================\n\n private performAggregation(records: any[], query: QueryInput): any[] {\n const { groupBy, aggregations } = query;\n const groups: Map = new Map();\n\n // 1. Group records\n if (groupBy && groupBy.length > 0) {\n for (const record of records) {\n // Create a composite key from group values\n const keyParts = groupBy.map(field => {\n const val = getValueByPath(record, field);\n return val === undefined || val === null ? 'null' : String(val);\n });\n const key = JSON.stringify(keyParts);\n \n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key)!.push(record);\n }\n } else {\n groups.set('all', records);\n }\n\n // 2. Compute aggregates for each group\n const resultRows: any[] = [];\n \n for (const [_key, groupRecords] of groups.entries()) {\n const row: any = {};\n \n // A. Add Group fields to row (if groupBy exists)\n if (groupBy && groupBy.length > 0) {\n if (groupRecords.length > 0) {\n const firstRecord = groupRecords[0];\n for (const field of groupBy) {\n this.setValueByPath(row, field, getValueByPath(firstRecord, field));\n }\n }\n }\n \n // B. Compute Aggregations\n if (aggregations) {\n for (const agg of aggregations) {\n const value = this.computeAggregate(groupRecords, agg);\n row[agg.alias] = value;\n }\n }\n \n resultRows.push(row);\n }\n \n return resultRows;\n }\n \n private computeAggregate(records: any[], agg: any): any {\n const { function: func, field } = agg;\n \n const values = field ? records.map(r => getValueByPath(r, field)) : [];\n \n switch (func) {\n case 'count':\n if (!field || field === '*') return records.length;\n return values.filter(v => v !== null && v !== undefined).length;\n \n case 'sum':\n case 'avg': {\n const nums = values.filter(v => typeof v === 'number');\n const sum = nums.reduce((a, b) => a + b, 0);\n if (func === 'sum') return sum;\n return nums.length > 0 ? sum / nums.length : null;\n }\n \n case 'min': {\n // Handle comparable values\n const valid = values.filter(v => v !== null && v !== undefined);\n if (valid.length === 0) return null;\n // Works for numbers and strings\n return valid.reduce((min, v) => (v < min ? v : min), valid[0]);\n }\n\n case 'max': {\n const valid = values.filter(v => v !== null && v !== undefined);\n if (valid.length === 0) return null;\n return valid.reduce((max, v) => (v > max ? v : max), valid[0]);\n }\n\n default:\n return null;\n }\n }\n\n private setValueByPath(obj: any, path: string, value: any) {\n const parts = path.split('.');\n let current = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!current[part]) current[part] = {};\n current = current[part];\n }\n current[parts[parts.length - 1]] = value;\n }\n\n // ===================================\n // Schema Management\n // ===================================\n\n async syncSchema(object: string, schema: any, options?: DriverOptions) {\n if (!this.db[object]) {\n this.db[object] = [];\n this.logger.info('Created in-memory table', { object });\n }\n }\n\n async dropTable(object: string, options?: DriverOptions) {\n if (this.db[object]) {\n const recordCount = this.db[object].length;\n delete this.db[object];\n this.logger.info('Dropped in-memory table', { object, recordCount });\n }\n }\n\n // ===================================\n // Helpers\n // ===================================\n\n /**\n * Apply manual sorting (Mingo sort has CJS build issues).\n */\n private applySort(records: any[], sortFields: any[]): any[] {\n const sorted = [...records];\n for (let i = sortFields.length - 1; i >= 0; i--) {\n const sortItem = sortFields[i];\n let field: string;\n let direction: string;\n if (typeof sortItem === 'object' && !Array.isArray(sortItem)) {\n field = sortItem.field;\n direction = sortItem.order || sortItem.direction || 'asc';\n } else if (Array.isArray(sortItem)) {\n [field, direction] = sortItem;\n } else {\n continue;\n }\n sorted.sort((a, b) => {\n const aVal = getValueByPath(a, field);\n const bVal = getValueByPath(b, field);\n if (aVal == null && bVal == null) return 0;\n if (aVal == null) return 1;\n if (bVal == null) return -1;\n if (aVal < bVal) return direction === 'desc' ? 1 : -1;\n if (aVal > bVal) return direction === 'desc' ? -1 : 1;\n return 0;\n });\n }\n return sorted;\n }\n\n /**\n * Project specific fields from a record.\n */\n private projectFields(record: any, fields: string[]): any {\n const result: any = {};\n for (const field of fields) {\n const value = getValueByPath(record, field);\n if (value !== undefined) {\n result[field] = value;\n }\n }\n // Always include id if not explicitly listed\n if (!fields.includes('id') && record.id !== undefined) {\n result.id = record.id;\n }\n return result;\n }\n\n private getTable(name: string) {\n if (!this.db[name]) {\n this.db[name] = [];\n }\n return this.db[name];\n }\n\n private generateId(objectName?: string) {\n const key = objectName || '_global';\n const counter = (this.idCounters.get(key) || 0) + 1;\n this.idCounters.set(key, counter);\n const timestamp = Date.now();\n return `${key}-${timestamp}-${counter}`;\n }\n\n // ===================================\n // Persistence\n // ===================================\n\n /**\n * Mark the database as dirty, triggering persistence save.\n */\n private markDirty(): void {\n if (this.persistenceAdapter) {\n this.persistenceAdapter.save(this.db);\n }\n }\n\n /**\n * Flush pending persistence writes to ensure data is safely stored.\n */\n async flush(): Promise {\n if (this.persistenceAdapter) {\n await this.persistenceAdapter.flush();\n }\n }\n\n /**\n * Detect whether the current runtime is a browser environment.\n */\n private isBrowserEnvironment(): boolean {\n return typeof globalThis.localStorage !== 'undefined';\n }\n\n /**\n * Detect whether the current runtime is a serverless/edge environment.\n *\n * Checks well-known environment variables set by serverless platforms:\n * - `VERCEL` / `VERCEL_ENV` — Vercel Functions / Edge\n * - `AWS_LAMBDA_FUNCTION_NAME` — AWS Lambda\n * - `NETLIFY` — Netlify Functions\n * - `FUNCTIONS_WORKER_RUNTIME` — Azure Functions\n * - `K_SERVICE` — Google Cloud Run / Cloud Functions\n * - `FUNCTION_TARGET` — Google Cloud Functions (Node.js)\n * - `DENO_DEPLOYMENT_ID` — Deno Deploy\n *\n * Returns `false` when `process` or `process.env` is unavailable\n * (e.g. browser or edge runtimes without a Node.js process object).\n */\n private isServerlessEnvironment(): boolean {\n if (typeof globalThis.process === 'undefined' || !globalThis.process.env) {\n return false;\n }\n const env = globalThis.process.env;\n return !!(\n env.VERCEL ||\n env.VERCEL_ENV ||\n env.AWS_LAMBDA_FUNCTION_NAME ||\n env.NETLIFY ||\n env.FUNCTIONS_WORKER_RUNTIME ||\n env.K_SERVICE ||\n env.FUNCTION_TARGET ||\n env.DENO_DEPLOYMENT_ID\n );\n }\n\n private static readonly SERVERLESS_PERSISTENCE_WARNING =\n 'Serverless environment detected — file-system persistence is disabled in auto mode. ' +\n 'Data will NOT be persisted across function invocations. ' +\n 'Set persistence: false to silence this warning, or provide a custom adapter ' +\n '(e.g. Upstash Redis, Vercel KV) via persistence: { adapter: yourAdapter }.';\n\n /**\n * Initialize the persistence adapter based on configuration.\n * Defaults to 'auto' when persistence is not specified.\n * Use `persistence: false` to explicitly disable persistence.\n *\n * In serverless environments (Vercel, AWS Lambda, etc.), auto mode disables\n * file-system persistence and emits a warning. Use `persistence: false` or\n * supply a custom adapter for serverless-safe operation.\n */\n private async initPersistence(): Promise {\n const persistence = this.config.persistence === undefined ? 'auto' : this.config.persistence;\n if (persistence === false) return;\n\n if (typeof persistence === 'string') {\n if (persistence === 'auto') {\n if (this.isBrowserEnvironment()) {\n const { LocalStoragePersistenceAdapter } = await import('./persistence/local-storage-adapter.js');\n this.persistenceAdapter = new LocalStoragePersistenceAdapter();\n this.logger.debug('Auto-detected browser environment, using localStorage persistence');\n } else if (this.isServerlessEnvironment()) {\n this.logger.warn(InMemoryDriver.SERVERLESS_PERSISTENCE_WARNING);\n } else {\n const { FileSystemPersistenceAdapter } = await import('./persistence/file-adapter.js');\n this.persistenceAdapter = new FileSystemPersistenceAdapter();\n this.logger.debug('Auto-detected Node.js environment, using file persistence');\n }\n } else if (persistence === 'file') {\n const { FileSystemPersistenceAdapter } = await import('./persistence/file-adapter.js');\n this.persistenceAdapter = new FileSystemPersistenceAdapter();\n } else if (persistence === 'local') {\n const { LocalStoragePersistenceAdapter } = await import('./persistence/local-storage-adapter.js');\n this.persistenceAdapter = new LocalStoragePersistenceAdapter();\n } else {\n throw new Error(`Unknown persistence type: \"${persistence}\". Use 'file', 'local', or 'auto'.`);\n }\n } else if ('adapter' in persistence && persistence.adapter) {\n this.persistenceAdapter = persistence.adapter;\n } else if ('type' in persistence) {\n if (persistence.type === 'auto') {\n if (this.isBrowserEnvironment()) {\n const { LocalStoragePersistenceAdapter } = await import('./persistence/local-storage-adapter.js');\n this.persistenceAdapter = new LocalStoragePersistenceAdapter({\n key: persistence.key,\n });\n this.logger.debug('Auto-detected browser environment, using localStorage persistence');\n } else if (this.isServerlessEnvironment()) {\n this.logger.warn(InMemoryDriver.SERVERLESS_PERSISTENCE_WARNING);\n } else {\n const { FileSystemPersistenceAdapter } = await import('./persistence/file-adapter.js');\n this.persistenceAdapter = new FileSystemPersistenceAdapter({\n path: persistence.path,\n autoSaveInterval: persistence.autoSaveInterval,\n });\n this.logger.debug('Auto-detected Node.js environment, using file persistence');\n }\n } else if (persistence.type === 'file') {\n const { FileSystemPersistenceAdapter } = await import('./persistence/file-adapter.js');\n this.persistenceAdapter = new FileSystemPersistenceAdapter({\n path: persistence.path,\n autoSaveInterval: persistence.autoSaveInterval,\n });\n } else if (persistence.type === 'local') {\n const { LocalStoragePersistenceAdapter } = await import('./persistence/local-storage-adapter.js');\n this.persistenceAdapter = new LocalStoragePersistenceAdapter({\n key: persistence.key,\n });\n }\n }\n\n if (this.persistenceAdapter) {\n this.logger.debug('Persistence adapter initialized');\n }\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n\n/**\n * Simple In-Memory Query Matcher\n * \n * Implements a subset of the ObjectStack Filter Protocol (MongoDB-compatible)\n * for evaluating conditions against in-memory JavaScript objects.\n */\n\ntype RecordType = Record;\n\n/**\n * matches - Check if a record matches a filter criteria\n * @param record The data record to check\n * @param filter The filter condition (where clause)\n */\nexport function match(record: RecordType, filter: any): boolean {\n if (!filter || Object.keys(filter).length === 0) return true;\n \n // 1. Handle Top-Level Logical Operators ($and, $or, $not)\n // These usually appear at the root or nested.\n \n // $and: [ { ... }, { ... } ]\n if (Array.isArray(filter.$and)) {\n if (!filter.$and.every((f: any) => match(record, f))) {\n return false;\n }\n }\n \n // $or: [ { ... }, { ... } ]\n if (Array.isArray(filter.$or)) {\n if (!filter.$or.some((f: any) => match(record, f))) {\n return false;\n }\n }\n \n // $not: { ... }\n if (filter.$not) {\n if (match(record, filter.$not)) {\n return false;\n }\n }\n \n // 2. Iterate over field constraints\n for (const key of Object.keys(filter)) {\n // Skip logical operators we already handled (or future ones)\n if (key.startsWith('$')) continue;\n \n const condition = filter[key];\n const value = getValueByPath(record, key);\n \n if (!checkCondition(value, condition)) {\n return false;\n }\n }\n \n return true;\n}\n\n/**\n * Access nested properties via dot-notation (e.g. \"user.name\")\n */\nexport function getValueByPath(obj: any, path: string): any {\n if (!path.includes('.')) return obj[path];\n return path.split('.').reduce((o, i) => (o ? o[i] : undefined), obj);\n}\n\n/**\n * Evaluate a specific condition against a value\n */\nfunction checkCondition(value: any, condition: any): boolean {\n // Case A: Implicit Equality (e.g. status: 'active')\n // If condition is a primitive or Date/Array (exact match), treat as equality.\n if (\n typeof condition !== 'object' || \n condition === null || \n condition instanceof Date ||\n Array.isArray(condition)\n ) {\n // Loose equality to handle undefined/null mismatch or string/number coercion if desired.\n // But stick to == for JS loose equality which is often convenient in weakly typed queries.\n return value == condition;\n }\n \n // Case B: Operator Object (e.g. { $gt: 10, $lt: 20 })\n const keys = Object.keys(condition);\n const isOperatorObject = keys.some(k => k.startsWith('$'));\n \n if (!isOperatorObject) {\n // It's just a nested object comparison or implicit equality against an object\n // Simplistic check:\n return JSON.stringify(value) === JSON.stringify(condition);\n }\n\n // Iterate operators\n for (const op of keys) {\n const target = condition[op];\n \n // Handle undefined values\n if (value === undefined && op !== '$exists' && op !== '$ne' && op !== '$null') {\n return false; \n }\n\n switch (op) {\n case '$eq': \n if (value != target) return false; \n break;\n case '$ne': \n if (value == target) return false; \n break;\n \n // Numeric / Date\n case '$gt': \n if (!(value > target)) return false; \n break;\n case '$gte': \n if (!(value >= target)) return false; \n break;\n case '$lt': \n if (!(value < target)) return false; \n break;\n case '$lte': \n if (!(value <= target)) return false; \n break;\n case '$between':\n // target should be [min, max]\n if (Array.isArray(target) && (value < target[0] || value > target[1])) return false;\n break;\n\n // Sets\n case '$in': \n if (!Array.isArray(target) || !target.includes(value)) return false; \n break;\n case '$nin': \n if (Array.isArray(target) && target.includes(value)) return false; \n break;\n \n // Existence\n case '$exists':\n const exists = value !== undefined && value !== null;\n if (exists !== !!target) return false;\n break;\n\n // Strings\n case '$contains': \n if (typeof value !== 'string' || !value.includes(target)) return false; \n break;\n case '$notContains':\n if (typeof value !== 'string' || value.includes(target)) return false;\n break;\n case '$startsWith': \n if (typeof value !== 'string' || !value.startsWith(target)) return false; \n break;\n case '$endsWith': \n if (typeof value !== 'string' || !value.endsWith(target)) return false; \n break;\n case '$null':\n // $null: true → value must be null/undefined; $null: false → value must not be null/undefined\n if (target === true && value != null) return false;\n if (target === false && value == null) return false;\n break;\n case '$regex':\n try {\n const re = new RegExp(target, condition.$options || '');\n if (!re.test(String(value))) return false;\n } catch (e) { return false; }\n break;\n\n default: \n // Unknown operator, ignore or fail. Ignoring safe for optional features.\n break;\n }\n }\n \n return true;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { InMemoryDriver } from './memory-driver.js';\n\nexport { InMemoryDriver }; // Export class for direct usage\nexport type { InMemoryDriverConfig, PersistenceAdapterInterface } from './memory-driver.js';\n\nexport { FileSystemPersistenceAdapter } from './persistence/file-adapter.js';\nexport { LocalStoragePersistenceAdapter } from './persistence/local-storage-adapter.js';\n\nexport { MemoryAnalyticsService } from './memory-analytics.js';\nexport type { MemoryAnalyticsConfig } from './memory-analytics.js';\n\nexport { InMemoryStrategy } from './in-memory-strategy.js';\n\nexport default {\n id: 'com.objectstack.driver.memory',\n version: '1.0.0',\n\n onEnable: async (context: any) => {\n const { logger, config, drivers } = context;\n logger.info('[Memory Driver] Initializing...');\n\n if (drivers) {\n const driver = new InMemoryDriver(config);\n drivers.register(driver);\n logger.info(`[Memory Driver] Registered driver: ${driver.name}`);\n } else {\n logger.warn('[Memory Driver] No driver registry found in context.');\n }\n }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IAnalyticsService, AnalyticsResult, CubeMeta } from '@objectstack/spec/contracts';\nimport type { Cube, AnalyticsQuery } from '@objectstack/spec/data';\nimport type { InMemoryDriver } from './memory-driver.js';\nimport { Logger, createLogger } from '@objectstack/core';\n\n/**\n * Configuration for MemoryAnalyticsService\n */\nexport interface MemoryAnalyticsConfig {\n /** The data driver instance to use for queries */\n driver: InMemoryDriver;\n /** Cube definitions for the semantic layer */\n cubes: Cube[];\n /** Optional logger */\n logger?: Logger;\n}\n\n/**\n * Memory-Based Analytics Service\n * \n * Implements IAnalyticsService using InMemoryDriver's aggregation capabilities.\n * Provides a semantic layer (Cubes, Metrics, Dimensions) on top of in-memory data.\n * \n * Features:\n * - Cube-based semantic modeling\n * - Measure calculations (count, sum, avg, min, max, count_distinct)\n * - Dimension grouping\n * - Filter support\n * - Time dimension handling\n * - SQL generation (for debugging/transparency)\n * \n * This implementation is suitable for:\n * - Development and testing\n * - Local-first analytics\n * - Small to medium datasets\n * - Prototyping BI applications\n */\nexport class MemoryAnalyticsService implements IAnalyticsService {\n private driver: InMemoryDriver;\n private cubes: Map;\n private logger: Logger;\n\n constructor(config: MemoryAnalyticsConfig) {\n this.driver = config.driver;\n this.cubes = new Map(config.cubes.map(c => [c.name, c]));\n this.logger = config.logger || createLogger({ level: 'info', format: 'pretty' });\n this.logger.debug('MemoryAnalyticsService initialized', { cubeCount: this.cubes.size });\n }\n\n /**\n * Execute an analytical query using the memory driver's aggregation pipeline\n */\n async query(query: AnalyticsQuery): Promise {\n this.logger.debug('Executing analytics query', { cube: query.cube, measures: query.measures });\n\n // Get cube definition\n if (!query.cube) {\n throw new Error('Cube name is required');\n }\n const cube = this.cubes.get(query.cube);\n if (!cube) {\n throw new Error(`Cube not found: ${query.cube}`);\n }\n\n // Build MongoDB aggregation pipeline\n const pipeline: Record[] = [];\n\n // Stage 1: $match for filters\n if (query.filters && query.filters.length > 0) {\n const matchStage: Record = {};\n for (const filter of query.filters) {\n const mongoOp = this.convertOperatorToMongo(filter.operator);\n const fieldPath = this.resolveFieldPath(cube, filter.member);\n \n if (filter.values && filter.values.length > 0) {\n if (mongoOp === '$in') {\n matchStage[fieldPath] = { $in: filter.values };\n } else if (mongoOp === '$nin') {\n matchStage[fieldPath] = { $nin: filter.values };\n } else {\n matchStage[fieldPath] = { [mongoOp]: filter.values[0] };\n }\n } else if (mongoOp === '$exists') {\n matchStage[fieldPath] = { $exists: filter.operator === 'set' };\n }\n }\n if (Object.keys(matchStage).length > 0) {\n pipeline.push({ $match: matchStage });\n }\n }\n\n // Stage 2: Time dimension filters\n if (query.timeDimensions && query.timeDimensions.length > 0) {\n for (const timeDim of query.timeDimensions) {\n const fieldPath = this.resolveFieldPath(cube, timeDim.dimension);\n if (timeDim.dateRange) {\n const range = Array.isArray(timeDim.dateRange) \n ? timeDim.dateRange \n : this.parseDateRangeString(timeDim.dateRange);\n \n if (range.length === 2) {\n pipeline.push({\n $match: {\n [fieldPath]: {\n $gte: new Date(range[0]),\n $lte: new Date(range[1])\n }\n }\n });\n }\n }\n }\n }\n\n // Stage 3: $group for measures and dimensions\n const groupStage: Record = { _id: {} };\n \n // Add dimensions to _id\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n const fieldPath = this.resolveFieldPath(cube, dim);\n const dimName = this.getShortName(dim);\n groupStage._id[dimName] = `$${fieldPath}`;\n }\n } else {\n groupStage._id = null; // No grouping, aggregate all\n }\n\n // Add measures as computed fields\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const measureDef = this.resolveMeasure(cube, measure);\n const measureName = this.getShortName(measure);\n \n if (measureDef) {\n const aggregator = this.buildAggregator(measureDef);\n groupStage[measureName] = aggregator;\n }\n }\n }\n\n pipeline.push({ $group: groupStage });\n\n // Stage 4: $project to reshape results (use short names, we'll fix them later)\n const projectStage: Record = { _id: 0 };\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n const dimName = this.getShortName(dim);\n projectStage[dimName] = `$_id.${dimName}`;\n }\n }\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const measureName = this.getShortName(measure);\n projectStage[measureName] = `$${measureName}`;\n }\n }\n pipeline.push({ $project: projectStage });\n\n // Stage 5: $sort (use short names)\n if (query.order && Object.keys(query.order).length > 0) {\n const sortStage: Record = {};\n for (const [field, direction] of Object.entries(query.order)) {\n const shortName = this.getShortName(field);\n sortStage[shortName] = direction === 'asc' ? 1 : -1;\n }\n pipeline.push({ $sort: sortStage });\n }\n\n // Stage 6: $limit and $skip\n if (query.offset) {\n pipeline.push({ $skip: query.offset });\n }\n if (query.limit) {\n pipeline.push({ $limit: query.limit });\n }\n\n // Execute the aggregation pipeline\n const tableName = this.extractTableName(cube.sql);\n const rawRows = await this.driver.aggregate(tableName, pipeline);\n\n // Rename fields from short names to full cube.field names\n const rows = rawRows.map(row => {\n const renamedRow: Record = {};\n \n // Rename dimensions\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const shortName = this.getShortName(dim);\n if (shortName in row) {\n renamedRow[dim] = row[shortName];\n }\n }\n }\n \n // Rename measures\n if (query.measures) {\n for (const measure of query.measures) {\n const shortName = this.getShortName(measure);\n if (shortName in row) {\n renamedRow[measure] = row[shortName];\n }\n }\n }\n \n return renamedRow;\n });\n\n // Build field metadata\n const fields: Array<{ name: string; type: string }> = [];\n \n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const dimension = this.resolveDimension(cube, dim);\n fields.push({\n name: dim,\n type: dimension?.type || 'string'\n });\n }\n }\n \n if (query.measures) {\n for (const measure of query.measures) {\n const measureDef = this.resolveMeasure(cube, measure);\n fields.push({\n name: measure,\n type: this.measureTypeToFieldType(measureDef?.type || 'count')\n });\n }\n }\n\n this.logger.debug('Analytics query completed', { rowCount: rows.length });\n\n return {\n rows,\n fields,\n sql: this.generateSqlFromPipeline(tableName, pipeline) // For debugging\n };\n }\n\n /**\n * Get available cube metadata for discovery\n */\n async getMeta(cubeName?: string): Promise {\n const cubes = cubeName \n ? [this.cubes.get(cubeName)].filter(Boolean) as Cube[]\n : Array.from(this.cubes.values());\n\n return cubes.map(cube => ({\n name: cube.name,\n title: cube.title,\n measures: Object.entries(cube.measures).map(([key, measure]) => ({\n name: `${cube.name}.${key}`,\n type: measure.type,\n title: measure.label\n })),\n dimensions: Object.entries(cube.dimensions).map(([key, dimension]) => ({\n name: `${cube.name}.${key}`,\n type: dimension.type,\n title: dimension.label\n }))\n }));\n }\n\n /**\n * Generate SQL representation for debugging/transparency\n */\n async generateSql(query: AnalyticsQuery): Promise<{ sql: string; params: unknown[] }> {\n if (!query.cube) {\n throw new Error('Cube name is required');\n }\n const cube = this.cubes.get(query.cube);\n if (!cube) {\n throw new Error(`Cube not found: ${query.cube}`);\n }\n\n const tableName = this.extractTableName(cube.sql);\n const selectClauses: string[] = [];\n const groupByClauses: string[] = [];\n\n // Build SELECT for dimensions\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n const fieldPath = this.resolveFieldPath(cube, dim);\n selectClauses.push(`${fieldPath} AS \"${dim}\"`);\n groupByClauses.push(fieldPath);\n }\n }\n\n // Build SELECT for measures\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const measureDef = this.resolveMeasure(cube, measure);\n if (measureDef) {\n const aggSql = this.measureToSql(measureDef);\n selectClauses.push(`${aggSql} AS \"${measure}\"`);\n }\n }\n }\n\n // Build WHERE clause\n const whereClauses: string[] = [];\n if (query.filters && query.filters.length > 0) {\n for (const filter of query.filters) {\n const fieldPath = this.resolveFieldPath(cube, filter.member);\n const sqlOp = this.operatorToSql(filter.operator);\n if (filter.values && filter.values.length > 0) {\n whereClauses.push(`${fieldPath} ${sqlOp} '${filter.values[0]}'`);\n }\n }\n }\n\n let sql = `SELECT ${selectClauses.join(', ')} FROM ${tableName}`;\n if (whereClauses.length > 0) {\n sql += ` WHERE ${whereClauses.join(' AND ')}`;\n }\n if (groupByClauses.length > 0) {\n sql += ` GROUP BY ${groupByClauses.join(', ')}`;\n }\n if (query.order) {\n const orderClauses = Object.entries(query.order).map(([field, dir]) => \n `\"${field}\" ${dir.toUpperCase()}`\n );\n sql += ` ORDER BY ${orderClauses.join(', ')}`;\n }\n if (query.limit) {\n sql += ` LIMIT ${query.limit}`;\n }\n if (query.offset) {\n sql += ` OFFSET ${query.offset}`;\n }\n\n return { sql, params: [] };\n }\n\n // ===================================\n // Helper Methods\n // ===================================\n\n private resolveFieldPath(cube: Cube, member: string): string {\n // Handle both \"cube.field\" and \"field\" formats\n const parts = member.split('.');\n const fieldName = parts.length > 1 ? parts[1] : parts[0];\n\n // Check if it's a dimension\n const dimension = cube.dimensions[fieldName];\n if (dimension) {\n // Extract field path from SQL expression\n return dimension.sql.replace(/^\\$/, ''); // Remove $ prefix if present\n }\n\n // Check if it's a measure (for filters)\n const measure = cube.measures[fieldName];\n if (measure) {\n return measure.sql.replace(/^\\$/, '');\n }\n\n return fieldName;\n }\n\n private resolveMeasure(cube: Cube, measureName: string) {\n const parts = measureName.split('.');\n const fieldName = parts.length > 1 ? parts[1] : parts[0];\n return cube.measures[fieldName];\n }\n\n private resolveDimension(cube: Cube, dimensionName: string) {\n const parts = dimensionName.split('.');\n const fieldName = parts.length > 1 ? parts[1] : parts[0];\n return cube.dimensions[fieldName];\n }\n\n private getShortName(fullName: string): string {\n const parts = fullName.split('.');\n return parts.length > 1 ? parts[1] : parts[0];\n }\n\n private buildAggregator(measure: { type: string; sql: string; filters?: any[] }): any {\n const fieldPath = measure.sql.replace(/^\\$/, '');\n\n switch (measure.type) {\n case 'count':\n return { $sum: 1 };\n case 'sum':\n return { $sum: `$${fieldPath}` };\n case 'avg':\n return { $avg: `$${fieldPath}` };\n case 'min':\n return { $min: `$${fieldPath}` };\n case 'max':\n return { $max: `$${fieldPath}` };\n case 'count_distinct':\n return { $addToSet: `$${fieldPath}` }; // Will need post-processing for count\n default:\n return { $sum: 1 }; // Default to count\n }\n }\n\n private measureTypeToFieldType(measureType: string): string {\n switch (measureType) {\n case 'count':\n case 'sum':\n case 'count_distinct':\n return 'number';\n case 'avg':\n case 'min':\n case 'max':\n return 'number';\n case 'string':\n return 'string';\n case 'boolean':\n return 'boolean';\n default:\n return 'number';\n }\n }\n\n private convertOperatorToMongo(operator: string): string {\n const opMap: Record = {\n 'equals': '$eq',\n 'notEquals': '$ne',\n 'contains': '$regex',\n 'notContains': '$not',\n 'gt': '$gt',\n 'gte': '$gte',\n 'lt': '$lt',\n 'lte': '$lte',\n 'set': '$exists',\n 'notSet': '$exists',\n 'inDateRange': '$gte', // Will need special handling\n };\n return opMap[operator] || '$eq';\n }\n\n private operatorToSql(operator: string): string {\n const opMap: Record = {\n 'equals': '=',\n 'notEquals': '!=',\n 'contains': 'LIKE',\n 'notContains': 'NOT LIKE',\n 'gt': '>',\n 'gte': '>=',\n 'lt': '<',\n 'lte': '<=',\n };\n return opMap[operator] || '=';\n }\n\n private measureToSql(measure: { type: string; sql: string }): string {\n const fieldPath = measure.sql.replace(/^\\$/, '');\n \n switch (measure.type) {\n case 'count':\n return 'COUNT(*)';\n case 'sum':\n return `SUM(${fieldPath})`;\n case 'avg':\n return `AVG(${fieldPath})`;\n case 'min':\n return `MIN(${fieldPath})`;\n case 'max':\n return `MAX(${fieldPath})`;\n case 'count_distinct':\n return `COUNT(DISTINCT ${fieldPath})`;\n default:\n return 'COUNT(*)';\n }\n }\n\n private extractTableName(sql: string): string {\n // For simple table names, return as-is\n // For complex SQL, this would need more sophisticated parsing\n return sql.trim();\n }\n\n private parseDateRangeString(range: string): string[] {\n // Simple parser for common date range strings\n // In production, this would use a proper date range parser\n const now = new Date();\n const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n \n if (range === 'today') {\n return [today.toISOString(), new Date(today.getTime() + 86400000).toISOString()];\n } else if (range.startsWith('last ')) {\n const parts = range.split(' ');\n const num = parseInt(parts[1]);\n const unit = parts[2];\n const start = new Date(today);\n \n if (unit.startsWith('day')) {\n start.setDate(start.getDate() - num);\n } else if (unit.startsWith('week')) {\n start.setDate(start.getDate() - num * 7);\n } else if (unit.startsWith('month')) {\n start.setMonth(start.getMonth() - num);\n } else if (unit.startsWith('year')) {\n start.setFullYear(start.getFullYear() - num);\n }\n \n return [start.toISOString(), now.toISOString()];\n }\n \n return [range, range]; // Fallback\n }\n\n private generateSqlFromPipeline(table: string, pipeline: Record[]): string {\n // Simplified SQL generation for debugging\n // This is a basic representation of the aggregation pipeline\n const stages = pipeline.map((stage, idx) => {\n const op = Object.keys(stage)[0];\n return `/* Stage ${idx + 1}: ${op} */ ${JSON.stringify(stage[op])}`;\n }).join('\\n');\n \n return `-- MongoDB Aggregation Pipeline on table: ${table}\\n${stages}`;\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AnalyticsQuery, AnalyticsResult, AnalyticsStrategy, StrategyContext } from '@objectstack/spec/contracts';\n\n/**\n * InMemoryStrategy — Priority 3\n *\n * Delegates to an existing `IAnalyticsService` instance that was registered\n * as a fallback (typically `MemoryAnalyticsService` from this package).\n *\n * This is the lowest-priority strategy, used in:\n * - `dev` / `test` environments\n * - Any runtime where the backing driver is in-memory\n */\nexport class InMemoryStrategy implements AnalyticsStrategy {\n readonly name = 'InMemoryStrategy';\n readonly priority = 30;\n\n canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {\n if (!query.cube) return false;\n // Can handle when a fallback service exists\n if (ctx.fallbackService) return true;\n // Or when the driver is flagged as in-memory\n const caps = ctx.queryCapabilities(query.cube);\n return caps.inMemory;\n }\n\n async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise {\n if (!ctx.fallbackService) {\n throw new Error(\n `[InMemoryStrategy] No fallback analytics service available for cube \"${query.cube}\". ` +\n 'Register a MemoryAnalyticsService or configure a driver with analytics support.'\n );\n }\n return ctx.fallbackService.query(query);\n }\n\n async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {\n if (ctx.fallbackService?.generateSql) {\n return ctx.fallbackService.generateSql(query);\n }\n return {\n sql: `-- InMemoryStrategy: SQL generation not supported for cube \"${query.cube}\"`,\n params: [],\n };\n }\n}\n", "// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n", "// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n", "// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n", "// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return value.indexOf(\"%\") !== -1 ? tryDecode(value, decodeURIComponent_) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI\n};\n", "// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from \"./utils/url.js\";\nvar tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.#getParamValue(paramKey);\n return param && /\\%/.test(param) ? tryDecodeURIComponent(param) : param;\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = /\\%/.test(value) ? tryDecodeURIComponent(value) : value;\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n const requestInit = {\n body: await req[cacheKey](),\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers: req.header(),\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n", "// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n", "// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * \n * \n *

{content}

\n * \n * \n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();\n if (typeof arg === \"object\" && \"headers\" in arg) {\n const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);\n for (const [key, value] of argHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, { status, headers: responseHeaders });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n", "// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n", "// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n", "// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = url.pathname.slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = { basePath: this._basePath, path, method, handler };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} Env - env Object\n * @param {ExecutionContext} - context of execution\n * @returns {Response | Promise} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n", "// src/router/reg-exp-router/matcher.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nvar emptyParam = [];\nfunction match(method, path) {\n const matchers = this.buildAllMatchers();\n const match2 = ((method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match3 = path2.match(matcher[0]);\n if (!match3) {\n return [[], emptyParam];\n }\n const index = match3.indexOf(\"\", 1);\n return [matcher[1][index], match3];\n });\n this.match = match2;\n return match2(method, path);\n}\nexport {\n emptyParam,\n match\n};\n", "// src/router/reg-exp-router/node.ts\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = /* @__PURE__ */ Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class _Node {\n #index;\n #varIndex;\n #children = /* @__PURE__ */ Object.create(null);\n insert(tokens, index, paramMap, context, pathErrorCheckOnly) {\n if (tokens.length === 0) {\n if (this.#index !== void 0) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n this.#index = index;\n return;\n }\n const [token, ...restTokens] = tokens;\n const pattern = token === \"*\" ? restTokens.length === 0 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let node;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n if (regexpStr === \".*\") {\n throw PATH_ERROR;\n }\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n node = this.#children[regexpStr];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[regexpStr] = new _Node();\n if (name !== \"\") {\n node.#varIndex = context.varIndex++;\n }\n }\n if (!pathErrorCheckOnly && name !== \"\") {\n paramMap.push([name, node.#varIndex]);\n }\n } else {\n node = this.#children[token];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[token] = new _Node();\n }\n }\n node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.#children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.#children[k];\n return (typeof c.#varIndex === \"number\" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + c.buildRegExpStr();\n });\n if (typeof this.#index === \"number\") {\n strList.unshift(`#${this.#index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n Node,\n PATH_ERROR\n};\n", "// src/router/reg-exp-router/trie.ts\nimport { Node } from \"./node.js\";\nvar Trie = class {\n #context = { varIndex: 0 };\n #root = new Node();\n insert(path, index, pathErrorCheckOnly) {\n const paramAssoc = [];\n const groups = [];\n for (let i = 0; ; ) {\n let replaced = false;\n path = path.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = path.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);\n return paramAssoc;\n }\n buildRegExp() {\n let regexp = this.#root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (handlerIndex !== void 0) {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (paramIndex !== void 0) {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n", "// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport { PATH_ERROR } from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];\nvar wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n path === \"*\" ? \"\" : `^${path.replace(\n /\\/\\*$|([.\\\\+*[^\\]$()])/g,\n (_, metaChar) => metaChar ? `\\\\${metaChar}` : \"(?:|/.*)\"\n )}$`\n );\n}\nfunction clearWildcardRegExpCache() {\n wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\n}\nfunction buildMatcherFromPreprocessedRoutes(routes) {\n const trie = new Trie();\n const handlerData = [];\n if (routes.length === 0) {\n return nullMatcher;\n }\n const routesWithStaticPathFlag = routes.map(\n (route) => [!/\\*|\\/:/.test(route[0]), ...route]\n ).sort(\n ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length\n );\n const staticMap = /* @__PURE__ */ Object.create(null);\n for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {\n const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];\n if (pathErrorCheckOnly) {\n staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];\n } else {\n j++;\n }\n let paramAssoc;\n try {\n paramAssoc = trie.insert(path, j, pathErrorCheckOnly);\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n if (pathErrorCheckOnly) {\n continue;\n }\n handlerData[j] = handlers.map(([h, paramCount]) => {\n const paramIndexMap = /* @__PURE__ */ Object.create(null);\n paramCount -= 1;\n for (; paramCount >= 0; paramCount--) {\n const [key, value] = paramAssoc[paramCount];\n paramIndexMap[key] = value;\n }\n return [h, paramIndexMap];\n });\n }\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (let i = 0, len = handlerData.length; i < len; i++) {\n for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {\n const map = handlerData[i][j]?.[1];\n if (!map) {\n continue;\n }\n const keys = Object.keys(map);\n for (let k = 0, len3 = keys.length; k < len3; k++) {\n map[keys[k]] = paramReplacementMap[map[keys[k]]];\n }\n }\n }\n const handlerMap = [];\n for (const i in indexReplacementMap) {\n handlerMap[i] = handlerData[indexReplacementMap[i]];\n }\n return [regexp, handlerMap, staticMap];\n}\nfunction findMiddleware(middleware, path) {\n if (!middleware) {\n return void 0;\n }\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n #middleware;\n #routes;\n constructor() {\n this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n }\n add(method, path, handler) {\n const middleware = this.#middleware;\n const routes = this.#routes;\n if (!middleware || !routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n ;\n [middleware, routes].forEach((handlerMap) => {\n handlerMap[method] = /* @__PURE__ */ Object.create(null);\n Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n });\n });\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const paramCount = (path.match(/\\/:/g) || []).length;\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n if (method === METHOD_NAME_ALL) {\n Object.keys(middleware).forEach((m) => {\n middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n });\n } else {\n middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n Object.keys(middleware).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(middleware[m]).forEach((p) => {\n re.test(p) && middleware[m][p].push([handler, paramCount]);\n });\n }\n });\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(routes[m]).forEach(\n (p) => re.test(p) && routes[m][p].push([handler, paramCount])\n );\n }\n });\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (let i = 0, len = paths.length; i < len; i++) {\n const path2 = paths[i];\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n routes[m][path2] ||= [\n ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []\n ];\n routes[m][path2].push([handler, paramCount - len + i + 1]);\n }\n });\n }\n }\n match = match;\n buildAllMatchers() {\n const matchers = /* @__PURE__ */ Object.create(null);\n Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {\n matchers[method] ||= this.#buildMatcher(method);\n });\n this.#middleware = this.#routes = void 0;\n clearWildcardRegExpCache();\n return matchers;\n }\n #buildMatcher(method) {\n const routes = [];\n let hasOwnRoute = method === METHOD_NAME_ALL;\n [this.#middleware, this.#routes].forEach((r) => {\n const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];\n if (ownRoute.length !== 0) {\n hasOwnRoute ||= true;\n routes.push(...ownRoute);\n } else if (method !== METHOD_NAME_ALL) {\n routes.push(\n ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])\n );\n }\n });\n if (!hasOwnRoute) {\n return null;\n } else {\n return buildMatcherFromPreprocessedRoutes(routes);\n }\n }\n};\nexport {\n RegExpRouter\n};\n", "// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n #routers = [];\n #routes = [];\n constructor(init) {\n this.#routers = init.routers;\n }\n add(method, path, handler) {\n if (!this.#routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.#routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.#routes) {\n throw new Error(\"Fatal error\");\n }\n const routers = this.#routers;\n const routes = this.#routes;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {\n router.add(...routes[i2]);\n }\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.#routers = [router];\n this.#routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.#routes || this.#routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.#routers[0];\n }\n};\nexport {\n SmartRouter\n};\n", "// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nvar emptyParams = /* @__PURE__ */ Object.create(null);\nvar hasChildren = (children) => {\n for (const _ in children) {\n return true;\n }\n return false;\n};\nvar Node = class _Node {\n #methods;\n #children;\n #patterns;\n #order = 0;\n #params = emptyParams;\n constructor(method, handler, children) {\n this.#children = children || /* @__PURE__ */ Object.create(null);\n this.#methods = [];\n if (method && handler) {\n const m = /* @__PURE__ */ Object.create(null);\n m[method] = { handler, possibleKeys: [], score: 0 };\n this.#methods = [m];\n }\n this.#patterns = [];\n }\n insert(method, path, handler) {\n this.#order = ++this.#order;\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = [];\n for (let i = 0, len = parts.length; i < len; i++) {\n const p = parts[i];\n const nextP = parts[i + 1];\n const pattern = getPattern(p, nextP);\n const key = Array.isArray(pattern) ? pattern[0] : p;\n if (key in curNode.#children) {\n curNode = curNode.#children[key];\n if (pattern) {\n possibleKeys.push(pattern[1]);\n }\n continue;\n }\n curNode.#children[key] = new _Node();\n if (pattern) {\n curNode.#patterns.push(pattern);\n possibleKeys.push(pattern[1]);\n }\n curNode = curNode.#children[key];\n }\n curNode.#methods.push({\n [method]: {\n handler,\n possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),\n score: this.#order\n }\n });\n return curNode;\n }\n #pushHandlerSets(handlerSets, node, method, nodeParams, params) {\n for (let i = 0, len = node.#methods.length; i < len; i++) {\n const m = node.#methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n const processedSet = {};\n if (handlerSet !== void 0) {\n handlerSet.params = /* @__PURE__ */ Object.create(null);\n handlerSets.push(handlerSet);\n if (nodeParams !== emptyParams || params && params !== emptyParams) {\n for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {\n const key = handlerSet.possibleKeys[i2];\n const processed = processedSet[handlerSet.score];\n handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];\n processedSet[handlerSet.score] = true;\n }\n }\n }\n }\n }\n search(method, path) {\n const handlerSets = [];\n this.#params = emptyParams;\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n const curNodesQueue = [];\n const len = parts.length;\n let partOffsets = null;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.#children[part];\n if (nextNode) {\n nextNode.#params = node.#params;\n if (isLast) {\n if (nextNode.#children[\"*\"]) {\n this.#pushHandlerSets(handlerSets, nextNode.#children[\"*\"], method, node.#params);\n }\n this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {\n const pattern = node.#patterns[k];\n const params = node.#params === emptyParams ? {} : { ...node.#params };\n if (pattern === \"*\") {\n const astNode = node.#children[\"*\"];\n if (astNode) {\n this.#pushHandlerSets(handlerSets, astNode, method, node.#params);\n astNode.#params = params;\n tempNodes.push(astNode);\n }\n continue;\n }\n const [key, name, matcher] = pattern;\n if (!part && !(matcher instanceof RegExp)) {\n continue;\n }\n const child = node.#children[key];\n if (matcher instanceof RegExp) {\n if (partOffsets === null) {\n partOffsets = new Array(len);\n let offset = path[0] === \"/\" ? 1 : 0;\n for (let p = 0; p < len; p++) {\n partOffsets[p] = offset;\n offset += parts[p].length + 1;\n }\n }\n const restPathString = path.substring(partOffsets[i]);\n const m = matcher.exec(restPathString);\n if (m) {\n params[name] = m[0];\n this.#pushHandlerSets(handlerSets, child, method, node.#params, params);\n if (hasChildren(child.#children)) {\n child.#params = params;\n const componentCount = m[0].match(/\\//)?.length ?? 0;\n const targetCurNodes = curNodesQueue[componentCount] ||= [];\n targetCurNodes.push(child);\n }\n continue;\n }\n }\n if (matcher === true || matcher.test(part)) {\n params[name] = part;\n if (isLast) {\n this.#pushHandlerSets(handlerSets, child, method, params, node.#params);\n if (child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n params,\n node.#params\n );\n }\n } else {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n const shifted = curNodesQueue.shift();\n curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;\n }\n if (handlerSets.length > 1) {\n handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n }\n return [handlerSets.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n", "// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n #node;\n constructor() {\n this.#node = new Node();\n }\n add(method, path, handler) {\n const results = checkOptionalParameter(path);\n if (results) {\n for (let i = 0, len = results.length; i < len; i++) {\n this.#node.insert(method, results[i], handler);\n }\n return;\n }\n this.#node.insert(method, path, handler);\n }\n match(method, path) {\n return this.#node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n", "// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n /**\n * Creates an instance of the Hono class.\n *\n * @param options - Optional configuration options for the Hono instance.\n */\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Hono } from 'hono';\nimport { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime';\n\nexport interface ObjectStackHonoOptions {\n kernel: ObjectKernel;\n prefix?: string;\n}\n\n/**\n * Auth service interface with handleRequest method\n */\ninterface AuthService {\n handleRequest(request: Request): Promise;\n}\n\n/**\n * Middleware mode for existing Hono apps\n */\nexport function objectStackMiddleware(kernel: ObjectKernel) {\n return async (c: any, next: any) => {\n c.set('objectStack', kernel);\n await next();\n };\n}\n\n/**\n * Creates a full-featured Hono app with all ObjectStack route dispatchers.\n *\n * Only routes that need framework-specific handling (auth service, storage\n * formData, GraphQL raw result, discovery wrapper) are registered explicitly.\n * All other routes (meta, data, packages, analytics, automation, i18n, ui,\n * openapi, custom endpoints, and any future routes) are handled by a\n * catch-all that delegates to `HttpDispatcher.dispatch()`.\n *\n * This means new routes added to `HttpDispatcher` automatically work in\n * every adapter without any adapter-side code changes.\n *\n * @example\n * ```ts\n * import { createHonoApp } from '@objectstack/hono';\n * const app = createHonoApp({ kernel });\n * export default app;\n * ```\n */\nexport function createHonoApp(options: ObjectStackHonoOptions): Hono {\n const app = new Hono();\n const prefix = options.prefix || '/api';\n const dispatcher = new HttpDispatcher(options.kernel);\n\n const errorJson = (c: any, message: string, code: number = 500) => {\n return c.json({ success: false, error: { message, code } }, code);\n };\n\n const toResponse = (c: any, result: HttpDispatcherResult) => {\n if (result.handled) {\n if (result.response) {\n if (result.response.headers) {\n Object.entries(result.response.headers).forEach(([k, v]) => c.header(k, v as string));\n }\n return c.json(result.response.body, result.response.status);\n }\n if (result.result) {\n const res = result.result;\n if (res.type === 'redirect' && res.url) {\n return c.redirect(res.url);\n }\n if (res.type === 'stream' && res.events) {\n // SSE / Vercel Data Stream streaming response\n const headers: Record = {\n 'Content-Type': res.contentType || 'text/event-stream',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n ...(res.headers || {}),\n };\n const stream = new ReadableStream({\n async start(controller) {\n try {\n const encoder = new TextEncoder();\n for await (const event of res.events) {\n const chunk = res.vercelDataStream\n ? (typeof event === 'string' ? event : JSON.stringify(event) + '\\n')\n : `data: ${JSON.stringify(event)}\\n\\n`;\n controller.enqueue(encoder.encode(chunk));\n }\n } catch (err) {\n // Stream error — close gracefully\n } finally {\n controller.close();\n }\n },\n });\n return new Response(stream, { status: 200, headers });\n }\n if (res.type === 'stream' && res.stream) {\n if (res.headers) {\n Object.entries(res.headers).forEach(([k, v]) => c.header(k, v as string));\n }\n return new Response(res.stream, { status: 200 });\n }\n return c.json(res, 200);\n }\n }\n return errorJson(c, 'Not Found', 404);\n };\n\n // ─── Explicit routes (framework-specific handling required) ────────────────\n\n // --- Discovery ---\n app.get(prefix, async (c) => {\n return c.json({ data: await dispatcher.getDiscoveryInfo(prefix) });\n });\n\n app.get(`${prefix}/discovery`, async (c) => {\n return c.json({ data: await dispatcher.getDiscoveryInfo(prefix) });\n });\n\n // --- .well-known ---\n app.get('/.well-known/objectstack', (c) => {\n return c.redirect(prefix);\n });\n\n // --- Auth (needs auth service integration) ---\n app.all(`${prefix}/auth/*`, async (c) => {\n try {\n const path = c.req.path.substring(`${prefix}/auth/`.length);\n const method = c.req.method;\n\n // Try AuthPlugin service first (prefer async to support factory-based services)\n let authService: AuthService | null = null;\n try {\n if (typeof options.kernel.getServiceAsync === 'function') {\n authService = await options.kernel.getServiceAsync('auth');\n } else if (typeof options.kernel.getService === 'function') {\n authService = options.kernel.getService('auth');\n }\n } catch {\n // Service not registered — fall through to dispatcher\n authService = null;\n }\n\n if (authService && typeof authService.handleRequest === 'function') {\n const response = await authService.handleRequest(c.req.raw);\n return new Response(response.body, {\n status: response.status,\n headers: response.headers,\n });\n }\n\n // Fallback to legacy dispatcher\n const body = method === 'GET' || method === 'HEAD'\n ? {}\n : await c.req.json().catch(() => ({}));\n const result = await dispatcher.handleAuth(path, method, body, { request: c.req.raw });\n return toResponse(c, result);\n } catch (err: any) {\n return errorJson(c, err.message || 'Internal Server Error', err.statusCode || 500);\n }\n });\n\n // --- GraphQL (returns raw result, not HttpDispatcherResult) ---\n app.post(`${prefix}/graphql`, async (c) => {\n try {\n const body = await c.req.json();\n const result = await dispatcher.handleGraphQL(body, { request: c.req.raw });\n return c.json(result);\n } catch (err: any) {\n return errorJson(c, err.message || 'Internal Server Error', err.statusCode || 500);\n }\n });\n\n // --- Storage (needs formData parsing) ---\n app.all(`${prefix}/storage/*`, async (c) => {\n try {\n const subPath = c.req.path.substring(`${prefix}/storage`.length);\n const method = c.req.method;\n\n let file: any = undefined;\n if (method === 'POST' && subPath === '/upload') {\n const formData = await c.req.formData();\n file = formData.get('file');\n }\n\n const result = await dispatcher.handleStorage(subPath, method, file, { request: c.req.raw });\n return toResponse(c, result);\n } catch (err: any) {\n return errorJson(c, err.message || 'Internal Server Error', err.statusCode || 500);\n }\n });\n\n // ─── Catch-all: delegate to dispatcher.dispatch() ─────────────────────────\n // Handles meta, data, packages, analytics, automation, i18n, ui, openapi,\n // custom API endpoints, and any future routes added to HttpDispatcher.\n app.all(`${prefix}/*`, async (c) => {\n try {\n const subPath = c.req.path.substring(prefix.length);\n const method = c.req.method;\n\n let body: any = undefined;\n if (method === 'POST' || method === 'PUT' || method === 'PATCH') {\n body = await c.req.json().catch(() => ({}));\n }\n\n const queryParams: Record = {};\n const url = new URL(c.req.url);\n url.searchParams.forEach((val, key) => { queryParams[key] = val; });\n\n const result = await dispatcher.dispatch(method, subPath, body, queryParams, { request: c.req.raw }, prefix);\n return toResponse(c, result);\n } catch (err: any) {\n return errorJson(c, err.message || 'Internal Server Error', err.statusCode || 500);\n }\n });\n\n return app;\n}\n", "//#region src/utils/wildcard.ts\n/**\n* Escapes a character if it has a special meaning in regular expressions\n* and returns the character as is if it doesn't\n*/\nfunction escapeRegExpChar(char) {\n\tif (char === \"-\" || char === \"^\" || char === \"$\" || char === \"+\" || char === \".\" || char === \"(\" || char === \")\" || char === \"|\" || char === \"[\" || char === \"]\" || char === \"{\" || char === \"}\" || char === \"*\" || char === \"?\" || char === \"\\\\\") return `\\\\${char}`;\n\telse return char;\n}\n/**\n* Escapes all characters in a given string that have a special meaning in regular expressions\n*/\nfunction escapeRegExpString(str) {\n\tlet result = \"\";\n\tfor (let i = 0; i < str.length; i++) result += escapeRegExpChar(str[i]);\n\treturn result;\n}\n/**\n* Transforms one or more glob patterns into a RegExp pattern\n*/\nfunction transform(pattern, separator = true) {\n\tif (Array.isArray(pattern)) return `(?:${pattern.map((p) => `^${transform(p, separator)}$`).join(\"|\")})`;\n\tlet separatorSplitter = \"\";\n\tlet separatorMatcher = \"\";\n\tlet wildcard = \".\";\n\tif (separator === true) {\n\t\tseparatorSplitter = \"/\";\n\t\tseparatorMatcher = \"[/\\\\\\\\]\";\n\t\twildcard = \"[^/\\\\\\\\]\";\n\t} else if (separator) {\n\t\tseparatorSplitter = separator;\n\t\tseparatorMatcher = escapeRegExpString(separatorSplitter);\n\t\tif (separatorMatcher.length > 1) {\n\t\t\tseparatorMatcher = `(?:${separatorMatcher})`;\n\t\t\twildcard = `((?!${separatorMatcher}).)`;\n\t\t} else wildcard = `[^${separatorMatcher}]`;\n\t}\n\tconst requiredSeparator = separator ? `${separatorMatcher}+?` : \"\";\n\tconst optionalSeparator = separator ? `${separatorMatcher}*?` : \"\";\n\tconst segments = separator ? pattern.split(separatorSplitter) : [pattern];\n\tlet result = \"\";\n\tfor (let s = 0; s < segments.length; s++) {\n\t\tconst segment = segments[s];\n\t\tconst nextSegment = segments[s + 1];\n\t\tlet currentSeparator = \"\";\n\t\tif (!segment && s > 0) continue;\n\t\tif (separator) if (s === segments.length - 1) currentSeparator = optionalSeparator;\n\t\telse if (nextSegment !== \"**\") currentSeparator = requiredSeparator;\n\t\telse currentSeparator = \"\";\n\t\tif (separator && segment === \"**\") {\n\t\t\tif (currentSeparator) {\n\t\t\t\tresult += s === 0 ? \"\" : currentSeparator;\n\t\t\t\tresult += `(?:${wildcard}*?${currentSeparator})*?`;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (let c = 0; c < segment.length; c++) {\n\t\t\tconst char = segment[c];\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tif (c < segment.length - 1) {\n\t\t\t\t\tresult += escapeRegExpChar(segment[c + 1]);\n\t\t\t\t\tc++;\n\t\t\t\t}\n\t\t\t} else if (char === \"?\") result += wildcard;\n\t\t\telse if (char === \"*\") result += `${wildcard}*?`;\n\t\t\telse result += escapeRegExpChar(char);\n\t\t}\n\t\tresult += currentSeparator;\n\t}\n\treturn result;\n}\nfunction isMatch(regexp, sample) {\n\tif (typeof sample !== \"string\") throw new TypeError(`Sample must be a string, but ${typeof sample} given`);\n\treturn regexp.test(sample);\n}\n/**\n* Compiles one or more glob patterns into a RegExp and returns an isMatch function.\n* The isMatch function takes a sample string as its only argument and returns `true`\n* if the string matches the pattern(s).\n*\n* ```js\n* wildcardMatch('src/*.js')('src/index.js') //=> true\n* ```\n*\n* ```js\n* const isMatch = wildcardMatch('*.example.com', '.')\n* isMatch('foo.example.com') //=> true\n* isMatch('foo.bar.com') //=> false\n* ```\n*/\nfunction wildcardMatch(pattern, options) {\n\tif (typeof pattern !== \"string\" && !Array.isArray(pattern)) throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`);\n\tif (typeof options === \"string\" || typeof options === \"boolean\") options = { separator: options };\n\tif (arguments.length === 2 && !(typeof options === \"undefined\" || typeof options === \"object\" && options !== null && !Array.isArray(options))) throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof options} given`);\n\toptions = options || {};\n\tif (options.separator === \"\\\\\") throw new Error(\"\\\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead\");\n\tconst regexpPattern = transform(pattern, options.separator);\n\tconst regexp = new RegExp(`^${regexpPattern}$`, options.flags);\n\tconst fn = isMatch.bind(null, regexp);\n\tfn.options = options;\n\tfn.pattern = pattern;\n\tfn.regexp = regexp;\n\treturn fn;\n}\n//#endregion\nexport { wildcardMatch };\n", "import { wildcardMatch } from \"./wildcard.mjs\";\nimport { env } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/utils/url.ts\nfunction checkHasPath(url) {\n\ttry {\n\t\treturn (new URL(url).pathname.replace(/\\/+$/, \"\") || \"/\") !== \"/\";\n\t} catch {\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`);\n\t}\n}\nfunction assertHasProtocol(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\tif (parsedUrl.protocol !== \"http:\" && parsedUrl.protocol !== \"https:\") throw new BetterAuthError(`Invalid base URL: ${url}. URL must include 'http://' or 'https://'`);\n\t} catch (error) {\n\t\tif (error instanceof BetterAuthError) throw error;\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`, { cause: error });\n\t}\n}\nfunction withPath(url, path = \"/api/auth\") {\n\tassertHasProtocol(url);\n\tif (checkHasPath(url)) return url;\n\tconst trimmedUrl = url.replace(/\\/+$/, \"\");\n\tif (!path || path === \"/\") return trimmedUrl;\n\tpath = path.startsWith(\"/\") ? path : `/${path}`;\n\treturn `${trimmedUrl}${path}`;\n}\nfunction validateProxyHeader(header, type) {\n\tif (!header || header.trim() === \"\") return false;\n\tif (type === \"proto\") return header === \"http\" || header === \"https\";\n\tif (type === \"host\") {\n\t\tif ([\n\t\t\t/\\.\\./,\n\t\t\t/\\0/,\n\t\t\t/[\\s]/,\n\t\t\t/^[.]/,\n\t\t\t/[<>'\"]/,\n\t\t\t/javascript:/i,\n\t\t\t/file:/i,\n\t\t\t/data:/i\n\t\t].some((pattern) => pattern.test(header))) return false;\n\t\treturn /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(header) || /^(\\d{1,3}\\.){3}\\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\\[[0-9a-fA-F:]+\\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header);\n\t}\n\treturn false;\n}\nfunction getBaseURL(url, path, request, loadEnv, trustedProxyHeaders) {\n\tif (url) return withPath(url, path);\n\tif (loadEnv !== false) {\n\t\tconst fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== \"/\" ? env.BASE_URL : void 0);\n\t\tif (fromEnv) return withPath(fromEnv, path);\n\t}\n\tconst fromRequest = request?.headers.get(\"x-forwarded-host\");\n\tconst fromRequestProto = request?.headers.get(\"x-forwarded-proto\");\n\tif (fromRequest && fromRequestProto && trustedProxyHeaders) {\n\t\tif (validateProxyHeader(fromRequestProto, \"proto\") && validateProxyHeader(fromRequest, \"host\")) try {\n\t\t\treturn withPath(`${fromRequestProto}://${fromRequest}`, path);\n\t\t} catch (_error) {}\n\t}\n\tif (request) {\n\t\tconst url = getOrigin(request.url);\n\t\tif (!url) throw new BetterAuthError(\"Could not get origin from request. Please provide a valid base URL.\");\n\t\treturn withPath(url, path);\n\t}\n\tif (typeof window !== \"undefined\" && window.location) return withPath(window.location.origin, path);\n}\nfunction getOrigin(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\treturn parsedUrl.origin === \"null\" ? null : parsedUrl.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getProtocol(url) {\n\ttry {\n\t\treturn new URL(url).protocol;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getHost(url) {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Checks if the baseURL config is a dynamic config object\n*/\nfunction isDynamicBaseURLConfig(config) {\n\treturn typeof config === \"object\" && config !== null && \"allowedHosts\" in config && Array.isArray(config.allowedHosts);\n}\n/**\n* Extracts the host from the request headers.\n* Tries x-forwarded-host first (for proxy setups), then falls back to host header.\n*\n* @param request The incoming request\n* @returns The host string or null if not found\n*/\nfunction getHostFromRequest(request) {\n\tconst forwardedHost = request.headers.get(\"x-forwarded-host\");\n\tif (forwardedHost && validateProxyHeader(forwardedHost, \"host\")) return forwardedHost;\n\tconst host = request.headers.get(\"host\");\n\tif (host && validateProxyHeader(host, \"host\")) return host;\n\ttry {\n\t\treturn new URL(request.url).host;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Extracts the protocol from the request headers.\n* Tries x-forwarded-proto first (for proxy setups), then infers from request URL.\n*\n* @param request The incoming request\n* @param configProtocol Protocol override from config\n* @returns The protocol (\"http\" or \"https\")\n*/\nfunction getProtocolFromRequest(request, configProtocol) {\n\tif (configProtocol === \"http\" || configProtocol === \"https\") return configProtocol;\n\tconst forwardedProto = request.headers.get(\"x-forwarded-proto\");\n\tif (forwardedProto && validateProxyHeader(forwardedProto, \"proto\")) return forwardedProto;\n\ttry {\n\t\tconst url = new URL(request.url);\n\t\tif (url.protocol === \"http:\" || url.protocol === \"https:\") return url.protocol.slice(0, -1);\n\t} catch {}\n\treturn \"https\";\n}\n/**\n* Matches a hostname against a host pattern.\n* Supports wildcard patterns like `*.vercel.app` or `preview-*.myapp.com`.\n*\n* @param host The hostname to test (e.g., \"myapp.com\", \"preview-123.vercel.app\")\n* @param pattern The host pattern (e.g., \"myapp.com\", \"*.vercel.app\")\n* @returns {boolean} true if the host matches the pattern, false otherwise.\n*\n* @example\n* ```ts\n* matchesHostPattern(\"myapp.com\", \"myapp.com\") // true\n* matchesHostPattern(\"preview-123.vercel.app\", \"*.vercel.app\") // true\n* matchesHostPattern(\"preview-123.myapp.com\", \"preview-*.myapp.com\") // true\n* matchesHostPattern(\"evil.com\", \"myapp.com\") // false\n* ```\n*/\nconst matchesHostPattern = (host, pattern) => {\n\tif (!host || !pattern) return false;\n\tconst normalizedHost = host.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tconst normalizedPattern = pattern.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tif (normalizedPattern.includes(\"*\") || normalizedPattern.includes(\"?\")) return wildcardMatch(normalizedPattern)(normalizedHost);\n\treturn normalizedHost.toLowerCase() === normalizedPattern.toLowerCase();\n};\n/**\n* Resolves the base URL from a dynamic config based on the incoming request.\n* Validates the derived host against the allowedHosts allowlist.\n*\n* @param config The dynamic base URL config\n* @param request The incoming request\n* @param basePath The base path to append\n* @returns The resolved base URL with path\n* @throws BetterAuthError if host is not in allowedHosts and no fallback is set\n*/\nfunction resolveDynamicBaseURL(config, request, basePath) {\n\tconst host = getHostFromRequest(request);\n\tif (!host) {\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\tthrow new BetterAuthError(\"Could not determine host from request headers. Please provide a fallback URL in your baseURL config.\");\n\t}\n\tif (config.allowedHosts.some((pattern) => matchesHostPattern(host, pattern))) return withPath(`${getProtocolFromRequest(request, config.protocol)}://${host}`, basePath);\n\tif (config.fallback) return withPath(config.fallback, basePath);\n\tthrow new BetterAuthError(`Host \"${host}\" is not in the allowed hosts list. Allowed hosts: ${config.allowedHosts.join(\", \")}. Add this host to your allowedHosts config or provide a fallback URL.`);\n}\n/**\n* Resolves the base URL from any config type (static string or dynamic object).\n* This is the main entry point for base URL resolution.\n*\n* @param config The base URL config (string or object)\n* @param basePath The base path to append\n* @param request Optional request for dynamic resolution\n* @param loadEnv Whether to load from environment variables\n* @param trustedProxyHeaders Whether to trust proxy headers (for legacy behavior)\n* @returns The resolved base URL with path\n*/\nfunction resolveBaseURL(config, basePath, request, loadEnv, trustedProxyHeaders) {\n\tif (isDynamicBaseURLConfig(config)) {\n\t\tif (request) return resolveDynamicBaseURL(config, request, basePath);\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\treturn getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders);\n\t}\n\tif (typeof config === \"string\") return getBaseURL(config, basePath, request, loadEnv, trustedProxyHeaders);\n\treturn getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders);\n}\n//#endregion\nexport { getBaseURL, getHost, getHostFromRequest, getOrigin, getProtocol, getProtocolFromRequest, isDynamicBaseURLConfig, matchesHostPattern, resolveBaseURL, resolveDynamicBaseURL };\n", "import { createRandomStringGenerator } from \"@better-auth/utils/random\";\n//#region src/crypto/random.ts\nconst generateRandomString = createRandomStringGenerator(\"a-z\", \"0-9\", \"A-Z\", \"-_\");\n//#endregion\nexport { generateRandomString };\n", "//#region src/crypto/buffer.ts\n/**\n* Compare two buffers in constant time.\n*/\nfunction constantTimeEqual(a, b) {\n\tif (typeof a === \"string\") a = new TextEncoder().encode(a);\n\tif (typeof b === \"string\") b = new TextEncoder().encode(b);\n\tconst aBuffer = new Uint8Array(a);\n\tconst bBuffer = new Uint8Array(b);\n\tlet c = aBuffer.length ^ bBuffer.length;\n\tconst length = Math.max(aBuffer.length, bBuffer.length);\n\tfor (let i = 0; i < length; i++) c |= (i < aBuffer.length ? aBuffer[i] : 0) ^ (i < bBuffer.length ? bBuffer[i] : 0);\n\treturn c === 0;\n}\n//#endregion\nexport { constantTimeEqual };\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n value: TArg,\n length?: number,\n title: string = ''\n): TRet {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg): TRet {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg): TRet {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg): TRet {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg): TRet {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg) => TRet = isLE\n ? (u: TArg) => u as TRet\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg, errorTitle = ''): TRet {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg): TRet {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg): TRet;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet;\n};\n/** Callable hash function type. */\nexport type CHash = Hash, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg): TRet;\n create(): T;\n }\n : {\n (msg: TArg, opts?: TArg): TRet;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: TArg = {}\n): TRet> {\n const hashC: any = (msg: TArg, opts?: TArg) =>\n hashCons(opts as Opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet> => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport {\n abytes,\n aexists,\n ahash,\n aoutput,\n clean,\n type CHash,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC> implements Hash<_HMAC> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n canXOF = false;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: TArg, key: TArg) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: TArg): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: TArg): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest(): TRet {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out as TRet;\n }\n _cloneInto(to?: _HMAC): _HMAC {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - authentication key bytes\n * @param message - message bytes to authenticate\n * @returns Authentication tag bytes.\n * @example\n * Compute an RFC 2104 HMAC.\n * ```ts\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\ntype HmacFn = {\n (hash: TArg, key: TArg, message: TArg): TRet;\n create(hash: TArg, key: TArg): TRet<_HMAC>;\n};\nexport const hmac: TRet = /* @__PURE__ */ (() => {\n const hmac_ = ((\n hash: TArg,\n key: TArg,\n message: TArg\n ): TRet => new _HMAC(hash, key).update(message).digest()) as TRet;\n hmac_.create = (hash: TArg, key: TArg): TRet<_HMAC> =>\n new _HMAC(hash, key) as TRet<_HMAC>;\n return hmac_;\n})();\n", "/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.\n * @module\n */\nimport { hmac } from './hmac.ts';\nimport { abytes, ahash, anumber, type CHash, clean, type TArg, type TRet } from './utils.ts';\n\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @returns Pseudorandom key derived from input keying material.\n * @example\n * Run the HKDF extract step.\n * ```ts\n * import { extract } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\nexport function extract(\n hash: TArg,\n ikm: TArg,\n salt?: TArg\n): TRet {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined) salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\n\n// Shared mutable scratch byte for the RFC 5869 block counter `N`.\n// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);\n// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets\n * (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material with the requested length.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * Run the HKDF expand step.\n * ```ts\n * import { expand } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);\n * ```\n */\nexport function expand(\n hash: TArg,\n prk: TArg,\n info?: TArg,\n length: number = 32\n): TRet {\n ahash(hash);\n anumber(length, 'length');\n abytes(prk, undefined, 'prk');\n const olen = hash.outputLen;\n // RFC 5869 \u00A72.3: PRK is \"a pseudorandom key of at least HashLen octets\".\n if (prk.length < olen) throw new Error('\"prk\" must be at least HashLen octets');\n // RFC 5869 \u00A72.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.\n if (length > 255 * olen) throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined) info = EMPTY_BUFFER;\n else abytes(info, undefined, 'info');\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * olen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, olen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n clean(T, HKDF_COUNTER);\n return okm.slice(0, length) as TRet;\n}\n\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information bytes\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material derived from the input key.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * HKDF (RFC 5869): derive keys from an initial input.\n * ```ts\n * import { hkdf } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = utf8ToBytes('application-key');\n * const okm = hkdf(sha256, inputKey, salt, info, 32);\n * ```\n */\nexport const hkdf = (\n hash: TArg,\n ikm: TArg,\n salt: TArg,\n info: TArg,\n length: number\n): TRet => expand(hash, extract(hash, ikm, salt), info, length);\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD> implements Hash {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly canXOF = false;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: TArg): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: TArg): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): TRet {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n", "import { encoder, decoder } from '../lib/buffer_utils.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nexport function decode(input) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {\n alphabet: 'base64url',\n });\n }\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');\n try {\n return decodeBase64(encoded);\n }\n catch {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n}\nexport function encode(input) {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n if (Uint8Array.prototype.toBase64) {\n return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });\n }\n return encodeBase64(unencoded).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n", "export const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers) {\n buf.set(buffer, i);\n i += buffer.length;\n }\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function encode(string) {\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127) {\n throw new TypeError('non-ASCII string encountered in encode()');\n }\n bytes[i] = code;\n }\n return bytes;\n}\n", "export function encodeBase64(input) {\n if (Uint8Array.prototype.toBase64) {\n return input.toBase64();\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n}\nexport function decodeBase64(encoded) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(encoded);\n }\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n", "const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nconst isAlgorithm = (algorithm, name) => algorithm.name === name;\nfunction getHashLength(hash) {\n return parseInt(hash.name.slice(4), 10);\n}\nfunction checkHashLength(algorithm, expected) {\n const actual = getHashLength(algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n}\nfunction getNamedCurve(alg) {\n switch (alg) {\n case 'ES256':\n return 'P-256';\n case 'ES384':\n return 'P-384';\n case 'ES512':\n return 'P-521';\n default:\n throw new Error('unreachable');\n }\n}\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage)) {\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n }\n}\nexport function checkSigCryptoKey(key, alg, usage) {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512': {\n if (!isAlgorithm(key.algorithm, 'HMAC'))\n throw unusable('HMAC');\n checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n break;\n }\n case 'RS256':\n case 'RS384':\n case 'RS512': {\n if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n throw unusable('RSASSA-PKCS1-v1_5');\n checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n break;\n }\n case 'PS256':\n case 'PS384':\n case 'PS512': {\n if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n throw unusable('RSA-PSS');\n checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n break;\n }\n case 'Ed25519':\n case 'EdDSA': {\n if (!isAlgorithm(key.algorithm, 'Ed25519'))\n throw unusable('Ed25519');\n break;\n }\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87': {\n if (!isAlgorithm(key.algorithm, alg))\n throw unusable(alg);\n break;\n }\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n if (!isAlgorithm(key.algorithm, 'ECDSA'))\n throw unusable('ECDSA');\n const expected = getNamedCurve(alg);\n const actual = key.algorithm.namedCurve;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.namedCurve');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usage);\n}\nexport function checkEncCryptoKey(key, alg, usage) {\n switch (alg) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM': {\n if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n throw unusable('AES-GCM');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (!isAlgorithm(key.algorithm, 'AES-KW'))\n throw unusable('AES-KW');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'ECDH': {\n switch (key.algorithm.name) {\n case 'ECDH':\n case 'X25519':\n break;\n default:\n throw unusable('ECDH or X25519');\n }\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW':\n if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n throw unusable('PBKDF2');\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n throw unusable('RSA-OAEP');\n checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1);\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usage);\n}\n", "function message(msg, actual, ...types) {\n types = types.filter(Boolean);\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(', ')}, or ${last}.`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}.`;\n }\n else {\n msg += `of type ${types[0]}.`;\n }\n if (actual == null) {\n msg += ` Received ${actual}`;\n }\n else if (typeof actual === 'function' && actual.name) {\n msg += ` Received function ${actual.name}`;\n }\n else if (typeof actual === 'object' && actual != null) {\n if (actual.constructor?.name) {\n msg += ` Received an instance of ${actual.constructor.name}`;\n }\n }\n return msg;\n}\nexport const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types);\nexport const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);\n", "export class JOSEError extends Error {\n static code = 'ERR_JOSE_GENERIC';\n code = 'ERR_JOSE_GENERIC';\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JWTExpired extends JOSEError {\n static code = 'ERR_JWT_EXPIRED';\n code = 'ERR_JWT_EXPIRED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n static code = 'ERR_JOSE_NOT_SUPPORTED';\n code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n static code = 'ERR_JWE_DECRYPTION_FAILED';\n code = 'ERR_JWE_DECRYPTION_FAILED';\n constructor(message = 'decryption operation failed', options) {\n super(message, options);\n }\n}\nexport class JWEInvalid extends JOSEError {\n static code = 'ERR_JWE_INVALID';\n code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n static code = 'ERR_JWS_INVALID';\n code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n static code = 'ERR_JWT_INVALID';\n code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n static code = 'ERR_JWK_INVALID';\n code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n static code = 'ERR_JWKS_INVALID';\n code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n static code = 'ERR_JWKS_NO_MATCHING_KEY';\n code = 'ERR_JWKS_NO_MATCHING_KEY';\n constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator];\n static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSTimeout extends JOSEError {\n static code = 'ERR_JWKS_TIMEOUT';\n code = 'ERR_JWKS_TIMEOUT';\n constructor(message = 'request timed out', options) {\n super(message, options);\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n constructor(message = 'signature verification failed', options) {\n super(message, options);\n }\n}\n", "export function assertCryptoKey(key) {\n if (!isCryptoKey(key)) {\n throw new Error('CryptoKey instance expected');\n }\n}\nexport const isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === 'CryptoKey')\n return true;\n try {\n return key instanceof CryptoKey;\n }\n catch {\n return false;\n }\n};\nexport const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject';\nexport const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\n", "import { concat, uint64be } from './buffer_utils.js';\nimport { checkEncCryptoKey } from './crypto_key.js';\nimport { invalidKeyInput } from './invalid_key_input.js';\nimport { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js';\nimport { isCryptoKey } from './is_key_like.js';\nexport function cekLength(alg) {\n switch (alg) {\n case 'A128GCM':\n return 128;\n case 'A192GCM':\n return 192;\n case 'A256GCM':\n case 'A128CBC-HS256':\n return 256;\n case 'A192CBC-HS384':\n return 384;\n case 'A256CBC-HS512':\n return 512;\n default:\n throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);\n }\n}\nexport const generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3));\nfunction checkCekLength(cek, expected) {\n const actual = cek.byteLength << 3;\n if (actual !== expected) {\n throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);\n }\n}\nfunction ivBitLength(alg) {\n switch (alg) {\n case 'A128GCM':\n case 'A128GCMKW':\n case 'A192GCM':\n case 'A192GCMKW':\n case 'A256GCM':\n case 'A256GCMKW':\n return 96;\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n return 128;\n default:\n throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);\n }\n}\nexport const generateIv = (alg) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg) >> 3));\nexport function checkIvLength(enc, iv) {\n if (iv.length << 3 !== ivBitLength(enc)) {\n throw new JWEInvalid('Invalid Initialization Vector length');\n }\n}\nasync function cbcKeySetup(enc, cek, usage) {\n if (!(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));\n }\n const keySize = parseInt(enc.slice(1, 4), 10);\n const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, [usage]);\n const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {\n hash: `SHA-${keySize << 1}`,\n name: 'HMAC',\n }, false, ['sign']);\n return { encKey, macKey, keySize };\n}\nasync function cbcHmacTag(macKey, macData, keySize) {\n return new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));\n}\nasync function cbcEncrypt(enc, plaintext, cek, iv, aad) {\n const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, 'encrypt');\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({\n iv: iv,\n name: 'AES-CBC',\n }, encKey, plaintext));\n const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));\n const tag = await cbcHmacTag(macKey, macData, keySize);\n return { ciphertext, tag, iv };\n}\nasync function timingSafeEqual(a, b) {\n if (!(a instanceof Uint8Array)) {\n throw new TypeError('First argument must be a buffer');\n }\n if (!(b instanceof Uint8Array)) {\n throw new TypeError('Second argument must be a buffer');\n }\n const algorithm = { name: 'HMAC', hash: 'SHA-256' };\n const key = (await crypto.subtle.generateKey(algorithm, false, ['sign']));\n const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));\n const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));\n let out = 0;\n let i = -1;\n while (++i < 32) {\n out |= aHmac[i] ^ bHmac[i];\n }\n return out === 0;\n}\nasync function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {\n const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, 'decrypt');\n const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));\n const expectedTag = await cbcHmacTag(macKey, macData, keySize);\n let macCheckPassed;\n try {\n macCheckPassed = await timingSafeEqual(tag, expectedTag);\n }\n catch {\n }\n if (!macCheckPassed) {\n throw new JWEDecryptionFailed();\n }\n let plaintext;\n try {\n plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, encKey, ciphertext));\n }\n catch {\n }\n if (!plaintext) {\n throw new JWEDecryptionFailed();\n }\n return plaintext;\n}\nasync function gcmEncrypt(enc, plaintext, cek, iv, aad) {\n let encKey;\n if (cek instanceof Uint8Array) {\n encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);\n }\n else {\n checkEncCryptoKey(cek, enc, 'encrypt');\n encKey = cek;\n }\n const encrypted = new Uint8Array(await crypto.subtle.encrypt({\n additionalData: aad,\n iv: iv,\n name: 'AES-GCM',\n tagLength: 128,\n }, encKey, plaintext));\n const tag = encrypted.slice(-16);\n const ciphertext = encrypted.slice(0, -16);\n return { ciphertext, tag, iv };\n}\nasync function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {\n let encKey;\n if (cek instanceof Uint8Array) {\n encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']);\n }\n else {\n checkEncCryptoKey(cek, enc, 'decrypt');\n encKey = cek;\n }\n try {\n return new Uint8Array(await crypto.subtle.decrypt({\n additionalData: aad,\n iv: iv,\n name: 'AES-GCM',\n tagLength: 128,\n }, encKey, concat(ciphertext, tag)));\n }\n catch {\n throw new JWEDecryptionFailed();\n }\n}\nconst unsupportedEnc = 'Unsupported JWE Content Encryption Algorithm';\nexport async function encrypt(enc, plaintext, cek, iv, aad) {\n if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'));\n }\n if (iv) {\n checkIvLength(enc, iv);\n }\n else {\n iv = generateIv(enc);\n }\n switch (enc) {\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n if (cek instanceof Uint8Array) {\n checkCekLength(cek, parseInt(enc.slice(-3), 10));\n }\n return cbcEncrypt(enc, plaintext, cek, iv, aad);\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM':\n if (cek instanceof Uint8Array) {\n checkCekLength(cek, parseInt(enc.slice(1, 4), 10));\n }\n return gcmEncrypt(enc, plaintext, cek, iv, aad);\n default:\n throw new JOSENotSupported(unsupportedEnc);\n }\n}\nexport async function decrypt(enc, cek, ciphertext, iv, tag, aad) {\n if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'));\n }\n if (!iv) {\n throw new JWEInvalid('JWE Initialization Vector missing');\n }\n if (!tag) {\n throw new JWEInvalid('JWE Authentication Tag missing');\n }\n checkIvLength(enc, iv);\n switch (enc) {\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n if (cek instanceof Uint8Array)\n checkCekLength(cek, parseInt(enc.slice(-3), 10));\n return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM':\n if (cek instanceof Uint8Array)\n checkCekLength(cek, parseInt(enc.slice(1, 4), 10));\n return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);\n default:\n throw new JOSENotSupported(unsupportedEnc);\n }\n}\n", "import { decode } from '../util/base64url.js';\nexport const unprotected = Symbol();\nexport function assertNotSet(value, name) {\n if (value) {\n throw new TypeError(`${name} can only be called once`);\n }\n}\nexport function decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n }\n catch {\n throw new ErrorClass(`Failed to base64url decode the ${label}`);\n }\n}\nexport async function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\n", "const isObjectLike = (value) => typeof value === 'object' && value !== null;\nexport function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\nexport function isDisjoint(...headers) {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n}\nexport const isJWK = (key) => isObject(key) && typeof key.kty === 'string';\nexport const isPrivateJWK = (key) => key.kty !== 'oct' &&\n ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');\nexport const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;\nexport const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';\n", "import { checkEncCryptoKey } from './crypto_key.js';\nfunction checkKeySize(key, alg) {\n if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {\n throw new TypeError(`Invalid key size for alg: ${alg}`);\n }\n}\nfunction getCryptoKey(key, alg, usage) {\n if (key instanceof Uint8Array) {\n return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]);\n }\n checkEncCryptoKey(key, alg, usage);\n return key;\n}\nexport async function wrap(alg, key, cek) {\n const cryptoKey = await getCryptoKey(key, alg, 'wrapKey');\n checkKeySize(cryptoKey, alg);\n const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']);\n return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'));\n}\nexport async function unwrap(alg, key, encryptedKey) {\n const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey');\n checkKeySize(cryptoKey, alg);\n const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']);\n return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));\n}\n", "import { encode, concat, uint32be } from './buffer_utils.js';\nimport { checkEncCryptoKey } from './crypto_key.js';\nimport { digest } from './helpers.js';\nfunction lengthAndInput(input) {\n return concat(uint32be(input.length), input);\n}\nasync function concatKdf(Z, L, OtherInfo) {\n const dkLen = L >> 3;\n const hashLen = 32;\n const reps = Math.ceil(dkLen / hashLen);\n const dk = new Uint8Array(reps * hashLen);\n for (let i = 1; i <= reps; i++) {\n const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);\n hashInput.set(uint32be(i), 0);\n hashInput.set(Z, 4);\n hashInput.set(OtherInfo, 4 + Z.length);\n const hashResult = await digest('sha256', hashInput);\n dk.set(hashResult, (i - 1) * hashLen);\n }\n return dk.slice(0, dkLen);\n}\nexport async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {\n checkEncCryptoKey(publicKey, 'ECDH');\n checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');\n const algorithmID = lengthAndInput(encode(algorithm));\n const partyUInfo = lengthAndInput(apu);\n const partyVInfo = lengthAndInput(apv);\n const suppPubInfo = uint32be(keyLength);\n const suppPrivInfo = new Uint8Array();\n const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);\n const Z = new Uint8Array(await crypto.subtle.deriveBits({\n name: publicKey.algorithm.name,\n public: publicKey,\n }, privateKey, getEcdhBitLength(publicKey)));\n return concatKdf(Z, keyLength, otherInfo);\n}\nfunction getEcdhBitLength(publicKey) {\n if (publicKey.algorithm.name === 'X25519') {\n return 256;\n }\n return (Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3);\n}\nexport function allowed(key) {\n switch (key.algorithm.namedCurve) {\n case 'P-256':\n case 'P-384':\n case 'P-521':\n return true;\n default:\n return key.algorithm.name === 'X25519';\n }\n}\n", "import { encode as b64u } from '../util/base64url.js';\nimport * as aeskw from './aeskw.js';\nimport { checkEncCryptoKey } from './crypto_key.js';\nimport { concat, encode } from './buffer_utils.js';\nimport { JWEInvalid } from '../util/errors.js';\nfunction getCryptoKey(key, alg) {\n if (key instanceof Uint8Array) {\n return crypto.subtle.importKey('raw', key, 'PBKDF2', false, [\n 'deriveBits',\n ]);\n }\n checkEncCryptoKey(key, alg, 'deriveBits');\n return key;\n}\nconst concatSalt = (alg, p2sInput) => concat(encode(alg), Uint8Array.of(0x00), p2sInput);\nasync function deriveKey(p2s, alg, p2c, key) {\n if (!(p2s instanceof Uint8Array) || p2s.length < 8) {\n throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets');\n }\n const salt = concatSalt(alg, p2s);\n const keylen = parseInt(alg.slice(13, 16), 10);\n const subtleAlg = {\n hash: `SHA-${alg.slice(8, 11)}`,\n iterations: p2c,\n name: 'PBKDF2',\n salt,\n };\n const cryptoKey = await getCryptoKey(key, alg);\n return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));\n}\nexport async function wrap(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {\n const derived = await deriveKey(p2s, alg, p2c, key);\n const encryptedKey = await aeskw.wrap(alg.slice(-6), derived, cek);\n return { encryptedKey, p2c, p2s: b64u(p2s) };\n}\nexport async function unwrap(alg, key, encryptedKey, p2c, p2s) {\n const derived = await deriveKey(p2s, alg, p2c, key);\n return aeskw.unwrap(alg.slice(-6), derived, encryptedKey);\n}\n", "import { JOSENotSupported } from '../util/errors.js';\nimport { checkSigCryptoKey } from './crypto_key.js';\nimport { invalidKeyInput } from './invalid_key_input.js';\nexport function checkKeyLength(alg, key) {\n if (alg.startsWith('RS') || alg.startsWith('PS')) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n }\n }\n}\nfunction subtleAlgorithm(alg, algorithm) {\n const hash = `SHA-${alg.slice(-3)}`;\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { hash, name: 'HMAC' };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { hash, name: 'RSASSA-PKCS1-v1_5' };\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n case 'Ed25519':\n case 'EdDSA':\n return { name: 'Ed25519' };\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return { name: alg };\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\nasync function getSigKey(alg, key, usage) {\n if (key instanceof Uint8Array) {\n if (!alg.startsWith('HS')) {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n }\n checkSigCryptoKey(key, alg, usage);\n return key;\n}\nexport async function sign(alg, key, data) {\n const cryptoKey = await getSigKey(alg, key, 'sign');\n checkKeyLength(alg, cryptoKey);\n const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);\n return new Uint8Array(signature);\n}\nexport async function verify(alg, key, signature, data) {\n const cryptoKey = await getSigKey(alg, key, 'verify');\n checkKeyLength(alg, cryptoKey);\n const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n try {\n return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n }\n catch {\n return false;\n }\n}\n", "import { checkEncCryptoKey } from './crypto_key.js';\nimport { checkKeyLength } from './signing.js';\nimport { JOSENotSupported } from '../util/errors.js';\nconst subtleAlgorithm = (alg) => {\n switch (alg) {\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n return 'RSA-OAEP';\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n};\nexport async function encrypt(alg, key, cek) {\n checkEncCryptoKey(key, alg, 'encrypt');\n checkKeyLength(alg, key);\n return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));\n}\nexport async function decrypt(alg, key, encryptedKey) {\n checkEncCryptoKey(key, alg, 'decrypt');\n checkKeyLength(alg, key);\n return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));\n}\n", "import { JOSENotSupported } from '../util/errors.js';\nconst unsupportedAlg = 'Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value';\nfunction subtleMapping(jwk) {\n let algorithm;\n let keyUsages;\n switch (jwk.kty) {\n case 'AKP': {\n switch (jwk.alg) {\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: jwk.alg };\n keyUsages = jwk.priv ? ['sign'] : ['verify'];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'RSA': {\n switch (jwk.alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n };\n keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'EC': {\n switch (jwk.alg) {\n case 'ES256':\n case 'ES384':\n case 'ES512':\n algorithm = {\n name: 'ECDSA',\n namedCurve: { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[jwk.alg],\n };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'OKP': {\n switch (jwk.alg) {\n case 'Ed25519':\n case 'EdDSA':\n algorithm = { name: 'Ed25519' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n }\n return { algorithm, keyUsages };\n}\nexport async function jwkToKey(jwk) {\n if (!jwk.alg) {\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n }\n const { algorithm, keyUsages } = subtleMapping(jwk);\n const keyData = { ...jwk };\n if (keyData.kty !== 'AKP') {\n delete keyData.alg;\n }\n delete keyData.use;\n return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);\n}\n", "import { isJWK } from './type_checks.js';\nimport { decode } from '../util/base64url.js';\nimport { jwkToKey } from './jwk_to_key.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nconst unusableForAlg = 'given KeyObject instance cannot be used for this algorithm';\nlet cache;\nconst handleJWK = async (key, jwk, alg, freeze = false) => {\n cache ||= new WeakMap();\n let cached = cache.get(key);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const cryptoKey = await jwkToKey({ ...jwk, alg });\n if (freeze)\n Object.freeze(key);\n if (!cached) {\n cache.set(key, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nconst handleKeyObject = (keyObject, alg) => {\n cache ||= new WeakMap();\n let cached = cache.get(keyObject);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const isPublic = keyObject.type === 'public';\n const extractable = isPublic ? true : false;\n let cryptoKey;\n if (keyObject.asymmetricKeyType === 'x25519') {\n switch (alg) {\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n break;\n default:\n throw new TypeError(unusableForAlg);\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']);\n }\n if (keyObject.asymmetricKeyType === 'ed25519') {\n if (alg !== 'EdDSA' && alg !== 'Ed25519') {\n throw new TypeError(unusableForAlg);\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n isPublic ? 'verify' : 'sign',\n ]);\n }\n switch (keyObject.asymmetricKeyType) {\n case 'ml-dsa-44':\n case 'ml-dsa-65':\n case 'ml-dsa-87': {\n if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {\n throw new TypeError(unusableForAlg);\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n isPublic ? 'verify' : 'sign',\n ]);\n }\n }\n if (keyObject.asymmetricKeyType === 'rsa') {\n let hash;\n switch (alg) {\n case 'RSA-OAEP':\n hash = 'SHA-1';\n break;\n case 'RS256':\n case 'PS256':\n case 'RSA-OAEP-256':\n hash = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'RSA-OAEP-384':\n hash = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'RSA-OAEP-512':\n hash = 'SHA-512';\n break;\n default:\n throw new TypeError(unusableForAlg);\n }\n if (alg.startsWith('RSA-OAEP')) {\n return keyObject.toCryptoKey({\n name: 'RSA-OAEP',\n hash,\n }, extractable, isPublic ? ['encrypt'] : ['decrypt']);\n }\n cryptoKey = keyObject.toCryptoKey({\n name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',\n hash,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (keyObject.asymmetricKeyType === 'ec') {\n const nist = new Map([\n ['prime256v1', 'P-256'],\n ['secp384r1', 'P-384'],\n ['secp521r1', 'P-521'],\n ]);\n const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);\n if (!namedCurve) {\n throw new TypeError(unusableForAlg);\n }\n const expectedCurve = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };\n if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDSA',\n namedCurve,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (alg.startsWith('ECDH-ES')) {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDH',\n namedCurve,\n }, extractable, isPublic ? [] : ['deriveBits']);\n }\n }\n if (!cryptoKey) {\n throw new TypeError(unusableForAlg);\n }\n if (!cached) {\n cache.set(keyObject, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nexport async function normalizeKey(key, alg) {\n if (key instanceof Uint8Array) {\n return key;\n }\n if (isCryptoKey(key)) {\n return key;\n }\n if (isKeyObject(key)) {\n if (key.type === 'secret') {\n return key.export();\n }\n if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') {\n try {\n return handleKeyObject(key, alg);\n }\n catch (err) {\n if (err instanceof TypeError) {\n throw err;\n }\n }\n }\n let jwk = key.export({ format: 'jwk' });\n return handleJWK(key, jwk, alg);\n }\n if (isJWK(key)) {\n if (key.k) {\n return decode(key.k);\n }\n return handleJWK(key, key, alg, true);\n }\n throw new Error('unreachable');\n}\n", "import { decode as decodeBase64URL } from '../util/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';\nimport { jwkToKey } from '../lib/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, options) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n let ext;\n alg ??= jwk.alg;\n ext ??= options?.extractable ?? jwk.ext;\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if ('oth' in jwk && jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n return jwkToKey({ ...jwk, alg, ext });\n case 'AKP': {\n if (typeof jwk.alg !== 'string' || !jwk.alg) {\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n }\n if (alg !== undefined && alg !== jwk.alg) {\n throw new TypeError('JWK alg and alg option value mismatch');\n }\n return jwkToKey({ ...jwk, ext });\n }\n case 'EC':\n case 'OKP':\n return jwkToKey({ ...jwk, alg, ext });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n", "import { invalidKeyInput } from './invalid_key_input.js';\nimport { encode as b64u } from '../util/base64url.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nexport async function keyToJWK(key) {\n if (isKeyObject(key)) {\n if (key.type === 'secret') {\n key = key.export();\n }\n else {\n return key.export({ format: 'jwk' });\n }\n }\n if (key instanceof Uint8Array) {\n return {\n kty: 'oct',\n k: b64u(key),\n };\n }\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'Uint8Array'));\n }\n if (!key.extractable) {\n throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');\n }\n const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key);\n if (jwk.kty === 'AKP') {\n ;\n jwk.alg = alg;\n }\n return jwk;\n}\n", "import { toSPKI as exportPublic, toPKCS8 as exportPrivate } from '../lib/asn1.js';\nimport { keyToJWK } from '../lib/key_to_jwk.js';\nexport async function exportSPKI(key) {\n return exportPublic(key);\n}\nexport async function exportPKCS8(key) {\n return exportPrivate(key);\n}\nexport async function exportJWK(key) {\n return keyToJWK(key);\n}\n", "import { encrypt, decrypt } from './content_encryption.js';\nimport { encode as b64u } from '../util/base64url.js';\nexport async function wrap(alg, key, cek, iv) {\n const jweAlgorithm = alg.slice(0, 7);\n const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array());\n return {\n encryptedKey: wrapped.ciphertext,\n iv: b64u(wrapped.iv),\n tag: b64u(wrapped.tag),\n };\n}\nexport async function unwrap(alg, key, encryptedKey, iv, tag) {\n const jweAlgorithm = alg.slice(0, 7);\n return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array());\n}\n", "import * as aeskw from './aeskw.js';\nimport * as ecdhes from './ecdhes.js';\nimport * as pbes2kw from './pbes2kw.js';\nimport * as rsaes from './rsaes.js';\nimport { encode as b64u } from '../util/base64url.js';\nimport { normalizeKey } from './normalize_key.js';\nimport { JOSENotSupported, JWEInvalid } from '../util/errors.js';\nimport { decodeBase64url } from './helpers.js';\nimport { generateCek, cekLength } from './content_encryption.js';\nimport { importJWK } from '../key/import.js';\nimport { exportJWK } from '../key/export.js';\nimport { isObject } from './type_checks.js';\nimport { wrap as aesGcmKwWrap, unwrap as aesGcmKwUnwrap } from './aesgcmkw.js';\nimport { assertCryptoKey } from './is_key_like.js';\nconst unsupportedAlgHeader = 'Invalid or unsupported \"alg\" (JWE Algorithm) header value';\nfunction assertEncryptedKey(encryptedKey) {\n if (encryptedKey === undefined)\n throw new JWEInvalid('JWE Encrypted Key missing');\n}\nexport async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {\n switch (alg) {\n case 'dir': {\n if (encryptedKey !== undefined)\n throw new JWEInvalid('Encountered unexpected JWE Encrypted Key');\n return key;\n }\n case 'ECDH-ES':\n if (encryptedKey !== undefined)\n throw new JWEInvalid('Encountered unexpected JWE Encrypted Key');\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n if (!isObject(joseHeader.epk))\n throw new JWEInvalid(`JOSE Header \"epk\" (Ephemeral Public Key) missing or invalid`);\n assertCryptoKey(key);\n if (!ecdhes.allowed(key))\n throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');\n const epk = await importJWK(joseHeader.epk, alg);\n assertCryptoKey(epk);\n let partyUInfo;\n let partyVInfo;\n if (joseHeader.apu !== undefined) {\n if (typeof joseHeader.apu !== 'string')\n throw new JWEInvalid(`JOSE Header \"apu\" (Agreement PartyUInfo) invalid`);\n partyUInfo = decodeBase64url(joseHeader.apu, 'apu', JWEInvalid);\n }\n if (joseHeader.apv !== undefined) {\n if (typeof joseHeader.apv !== 'string')\n throw new JWEInvalid(`JOSE Header \"apv\" (Agreement PartyVInfo) invalid`);\n partyVInfo = decodeBase64url(joseHeader.apv, 'apv', JWEInvalid);\n }\n const sharedSecret = await ecdhes.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);\n if (alg === 'ECDH-ES')\n return sharedSecret;\n assertEncryptedKey(encryptedKey);\n return aeskw.unwrap(alg.slice(-6), sharedSecret, encryptedKey);\n }\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n assertEncryptedKey(encryptedKey);\n assertCryptoKey(key);\n return rsaes.decrypt(alg, key, encryptedKey);\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n assertEncryptedKey(encryptedKey);\n if (typeof joseHeader.p2c !== 'number')\n throw new JWEInvalid(`JOSE Header \"p2c\" (PBES2 Count) missing or invalid`);\n const p2cLimit = options?.maxPBES2Count || 10_000;\n if (joseHeader.p2c > p2cLimit)\n throw new JWEInvalid(`JOSE Header \"p2c\" (PBES2 Count) out is of acceptable bounds`);\n if (typeof joseHeader.p2s !== 'string')\n throw new JWEInvalid(`JOSE Header \"p2s\" (PBES2 Salt) missing or invalid`);\n let p2s;\n p2s = decodeBase64url(joseHeader.p2s, 'p2s', JWEInvalid);\n return pbes2kw.unwrap(alg, key, encryptedKey, joseHeader.p2c, p2s);\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n assertEncryptedKey(encryptedKey);\n return aeskw.unwrap(alg, key, encryptedKey);\n }\n case 'A128GCMKW':\n case 'A192GCMKW':\n case 'A256GCMKW': {\n assertEncryptedKey(encryptedKey);\n if (typeof joseHeader.iv !== 'string')\n throw new JWEInvalid(`JOSE Header \"iv\" (Initialization Vector) missing or invalid`);\n if (typeof joseHeader.tag !== 'string')\n throw new JWEInvalid(`JOSE Header \"tag\" (Authentication Tag) missing or invalid`);\n let iv;\n iv = decodeBase64url(joseHeader.iv, 'iv', JWEInvalid);\n let tag;\n tag = decodeBase64url(joseHeader.tag, 'tag', JWEInvalid);\n return aesGcmKwUnwrap(alg, key, encryptedKey, iv, tag);\n }\n default: {\n throw new JOSENotSupported(unsupportedAlgHeader);\n }\n }\n}\nexport async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {\n let encryptedKey;\n let parameters;\n let cek;\n switch (alg) {\n case 'dir': {\n cek = key;\n break;\n }\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n assertCryptoKey(key);\n if (!ecdhes.allowed(key)) {\n throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');\n }\n const { apu, apv } = providedParameters;\n let ephemeralKey;\n if (providedParameters.epk) {\n ephemeralKey = (await normalizeKey(providedParameters.epk, alg));\n }\n else {\n ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ['deriveBits'])).privateKey;\n }\n const { x, y, crv, kty } = await exportJWK(ephemeralKey);\n const sharedSecret = await ecdhes.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);\n parameters = { epk: { x, crv, kty } };\n if (kty === 'EC')\n parameters.epk.y = y;\n if (apu)\n parameters.apu = b64u(apu);\n if (apv)\n parameters.apv = b64u(apv);\n if (alg === 'ECDH-ES') {\n cek = sharedSecret;\n break;\n }\n cek = providedCek || generateCek(enc);\n const kwAlg = alg.slice(-6);\n encryptedKey = await aeskw.wrap(kwAlg, sharedSecret, cek);\n break;\n }\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n cek = providedCek || generateCek(enc);\n assertCryptoKey(key);\n encryptedKey = await rsaes.encrypt(alg, key, cek);\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n cek = providedCek || generateCek(enc);\n const { p2c, p2s } = providedParameters;\n ({ encryptedKey, ...parameters } = await pbes2kw.wrap(alg, key, cek, p2c, p2s));\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n cek = providedCek || generateCek(enc);\n encryptedKey = await aeskw.wrap(alg, key, cek);\n break;\n }\n case 'A128GCMKW':\n case 'A192GCMKW':\n case 'A256GCMKW': {\n cek = providedCek || generateCek(enc);\n const { iv } = providedParameters;\n ({ encryptedKey, ...parameters } = await aesGcmKwWrap(alg, key, cek, iv));\n break;\n }\n default: {\n throw new JOSENotSupported(unsupportedAlgHeader);\n }\n }\n return { cek, encryptedKey, parameters };\n}\n", "import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js';\nexport function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n }\n if (!protectedHeader || protectedHeader.crit === undefined) {\n return new Set();\n }\n if (!Array.isArray(protectedHeader.crit) ||\n protectedHeader.crit.length === 0 ||\n protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n }\n let recognized;\n if (recognizedOption !== undefined) {\n recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n }\n else {\n recognized = recognizedDefault;\n }\n for (const parameter of protectedHeader.crit) {\n if (!recognized.has(parameter)) {\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n }\n if (joseHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n }\n if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n }\n return new Set(protectedHeader.crit);\n}\n", "export function validateAlgorithms(option, algorithms) {\n if (algorithms !== undefined &&\n (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n }\n if (!algorithms) {\n return undefined;\n }\n return new Set(algorithms);\n}\n", "import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport { isKeyLike } from './is_key_like.js';\nimport * as jwk from './type_checks.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n if (key.use !== undefined) {\n let expected;\n switch (usage) {\n case 'sign':\n case 'verify':\n expected = 'sig';\n break;\n case 'encrypt':\n case 'decrypt':\n expected = 'enc';\n break;\n }\n if (key.use !== expected) {\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n }\n if (key.alg !== undefined && key.alg !== alg) {\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n }\n if (Array.isArray(key.key_ops)) {\n let expectedKeyOp;\n switch (true) {\n case usage === 'sign' || usage === 'verify':\n case alg === 'dir':\n case alg.includes('CBC-HS'):\n expectedKeyOp = usage;\n break;\n case alg.startsWith('PBES2'):\n expectedKeyOp = 'deriveBits';\n break;\n case /^A\\d{3}(?:GCM)?(?:KW)?$/.test(alg):\n if (!alg.includes('GCM') && alg.endsWith('KW')) {\n expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey';\n }\n else {\n expectedKeyOp = usage;\n }\n break;\n case usage === 'encrypt' && alg.startsWith('RSA'):\n expectedKeyOp = 'wrapKey';\n break;\n case usage === 'decrypt':\n expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits';\n break;\n }\n if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n }\n return true;\n};\nconst symmetricTypeCheck = (alg, key, usage) => {\n if (key instanceof Uint8Array)\n return;\n if (jwk.isJWK(key)) {\n if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'));\n }\n if (key.type !== 'secret') {\n throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n }\n};\nconst asymmetricTypeCheck = (alg, key, usage) => {\n if (jwk.isJWK(key)) {\n switch (usage) {\n case 'decrypt':\n case 'sign':\n if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation must be a private JWK`);\n case 'encrypt':\n case 'verify':\n if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation must be a public JWK`);\n }\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n if (key.type === 'secret') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n }\n if (key.type === 'public') {\n switch (usage) {\n case 'sign':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n case 'decrypt':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n }\n }\n if (key.type === 'private') {\n switch (usage) {\n case 'verify':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n case 'encrypt':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n }\n }\n};\nexport function checkKeyType(alg, key, usage) {\n switch (alg.substring(0, 2)) {\n case 'A1':\n case 'A2':\n case 'di':\n case 'HS':\n case 'PB':\n symmetricTypeCheck(alg, key, usage);\n break;\n default:\n asymmetricTypeCheck(alg, key, usage);\n }\n}\n", "import { JOSENotSupported, JWEInvalid } from '../util/errors.js';\nimport { concat } from './buffer_utils.js';\nfunction supported(name) {\n if (typeof globalThis[name] === 'undefined') {\n throw new JOSENotSupported(`JWE \"zip\" (Compression Algorithm) Header Parameter requires the ${name} API.`);\n }\n}\nexport async function compress(input) {\n supported('CompressionStream');\n const cs = new CompressionStream('deflate-raw');\n const writer = cs.writable.getWriter();\n writer.write(input).catch(() => { });\n writer.close().catch(() => { });\n const chunks = [];\n const reader = cs.readable.getReader();\n for (;;) {\n const { value, done } = await reader.read();\n if (done)\n break;\n chunks.push(value);\n }\n return concat(...chunks);\n}\nexport async function decompress(input, maxLength) {\n supported('DecompressionStream');\n const ds = new DecompressionStream('deflate-raw');\n const writer = ds.writable.getWriter();\n writer.write(input).catch(() => { });\n writer.close().catch(() => { });\n const chunks = [];\n let length = 0;\n const reader = ds.readable.getReader();\n for (;;) {\n const { value, done } = await reader.read();\n if (done)\n break;\n chunks.push(value);\n length += value.byteLength;\n if (maxLength !== Infinity && length > maxLength) {\n throw new JWEInvalid('Decompressed plaintext exceeded the configured limit');\n }\n }\n return concat(...chunks);\n}\n", "import { decode as b64u } from '../../util/base64url.js';\nimport { decrypt } from '../../lib/content_encryption.js';\nimport { decodeBase64url } from '../../lib/helpers.js';\nimport { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { isObject } from '../../lib/type_checks.js';\nimport { decryptKeyManagement } from '../../lib/key_management.js';\nimport { decoder, concat, encode } from '../../lib/buffer_utils.js';\nimport { generateCek } from '../../lib/content_encryption.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { validateAlgorithms } from '../../lib/validate_algorithms.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { decompress } from '../../lib/deflate.js';\nexport async function flattenedDecrypt(jwe, key, options) {\n if (!isObject(jwe)) {\n throw new JWEInvalid('Flattened JWE must be an object');\n }\n if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {\n throw new JWEInvalid('JOSE Header missing');\n }\n if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {\n throw new JWEInvalid('JWE Initialization Vector incorrect type');\n }\n if (typeof jwe.ciphertext !== 'string') {\n throw new JWEInvalid('JWE Ciphertext missing or incorrect type');\n }\n if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {\n throw new JWEInvalid('JWE Authentication Tag incorrect type');\n }\n if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {\n throw new JWEInvalid('JWE Protected Header incorrect type');\n }\n if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {\n throw new JWEInvalid('JWE Encrypted Key incorrect type');\n }\n if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {\n throw new JWEInvalid('JWE AAD incorrect type');\n }\n if (jwe.header !== undefined && !isObject(jwe.header)) {\n throw new JWEInvalid('JWE Shared Unprotected Header incorrect type');\n }\n if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {\n throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');\n }\n let parsedProt;\n if (jwe.protected) {\n try {\n const protectedHeader = b64u(jwe.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWEInvalid('JWE Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {\n throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jwe.header,\n ...jwe.unprotected,\n };\n validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);\n if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {\n throw new JOSENotSupported('Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.');\n }\n if (joseHeader.zip !== undefined && !parsedProt?.zip) {\n throw new JWEInvalid('JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.');\n }\n const { alg, enc } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header');\n }\n if (typeof enc !== 'string' || !enc) {\n throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');\n }\n const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms);\n const contentEncryptionAlgorithms = options &&\n validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);\n if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||\n (!keyManagementAlgorithms && alg.startsWith('PBES2'))) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {\n throw new JOSEAlgNotAllowed('\"enc\" (Encryption Algorithm) Header Parameter value not allowed');\n }\n let encryptedKey;\n if (jwe.encrypted_key !== undefined) {\n encryptedKey = decodeBase64url(jwe.encrypted_key, 'encrypted_key', JWEInvalid);\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jwe);\n resolvedKey = true;\n }\n checkKeyType(alg === 'dir' ? enc : alg, key, 'decrypt');\n const k = await normalizeKey(key, alg);\n let cek;\n try {\n cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);\n }\n catch (err) {\n if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {\n throw err;\n }\n cek = generateCek(enc);\n }\n let iv;\n let tag;\n if (jwe.iv !== undefined) {\n iv = decodeBase64url(jwe.iv, 'iv', JWEInvalid);\n }\n if (jwe.tag !== undefined) {\n tag = decodeBase64url(jwe.tag, 'tag', JWEInvalid);\n }\n const protectedHeader = jwe.protected !== undefined ? encode(jwe.protected) : new Uint8Array();\n let additionalData;\n if (jwe.aad !== undefined) {\n additionalData = concat(protectedHeader, encode('.'), encode(jwe.aad));\n }\n else {\n additionalData = protectedHeader;\n }\n const ciphertext = decodeBase64url(jwe.ciphertext, 'ciphertext', JWEInvalid);\n const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);\n const result = { plaintext };\n if (joseHeader.zip === 'DEF') {\n const maxDecompressedLength = options?.maxDecompressedLength ?? 250_000;\n if (maxDecompressedLength === 0) {\n throw new JOSENotSupported('JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.');\n }\n if (maxDecompressedLength !== Infinity &&\n (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) {\n throw new TypeError('maxDecompressedLength must be 0, a positive safe integer, or Infinity');\n }\n result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => {\n if (cause instanceof JWEInvalid)\n throw cause;\n throw new JWEInvalid('Failed to decompress plaintext', { cause });\n });\n }\n if (jwe.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jwe.aad !== undefined) {\n result.additionalAuthenticatedData = decodeBase64url(jwe.aad, 'aad', JWEInvalid);\n }\n if (jwe.unprotected !== undefined) {\n result.sharedUnprotectedHeader = jwe.unprotected;\n }\n if (jwe.header !== undefined) {\n result.unprotectedHeader = jwe.header;\n }\n if (resolvedKey) {\n return { ...result, key: k };\n }\n return result;\n}\n", "import { flattenedDecrypt } from '../flattened/decrypt.js';\nimport { JWEInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactDecrypt(jwe, key, options) {\n if (jwe instanceof Uint8Array) {\n jwe = decoder.decode(jwe);\n }\n if (typeof jwe !== 'string') {\n throw new JWEInvalid('Compact JWE must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.');\n if (length !== 5) {\n throw new JWEInvalid('Invalid Compact JWE');\n }\n const decrypted = await flattenedDecrypt({\n ciphertext,\n iv: iv || undefined,\n protected: protectedHeader,\n tag: tag || undefined,\n encrypted_key: encryptedKey || undefined,\n }, key, options);\n const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: decrypted.key };\n }\n return result;\n}\n", "import { encode as b64u } from '../../util/base64url.js';\nimport { unprotected, assertNotSet } from '../../lib/helpers.js';\nimport { encrypt } from '../../lib/content_encryption.js';\nimport { encryptKeyManagement } from '../../lib/key_management.js';\nimport { JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { concat, encode } from '../../lib/buffer_utils.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { compress } from '../../lib/deflate.js';\nexport class FlattenedEncrypt {\n #plaintext;\n #protectedHeader;\n #sharedUnprotectedHeader;\n #unprotectedHeader;\n #aad;\n #cek;\n #iv;\n #keyManagementParameters;\n constructor(plaintext) {\n if (!(plaintext instanceof Uint8Array)) {\n throw new TypeError('plaintext must be an instance of Uint8Array');\n }\n this.#plaintext = plaintext;\n }\n setKeyManagementParameters(parameters) {\n assertNotSet(this.#keyManagementParameters, 'setKeyManagementParameters');\n this.#keyManagementParameters = parameters;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n assertNotSet(this.#protectedHeader, 'setProtectedHeader');\n this.#protectedHeader = protectedHeader;\n return this;\n }\n setSharedUnprotectedHeader(sharedUnprotectedHeader) {\n assertNotSet(this.#sharedUnprotectedHeader, 'setSharedUnprotectedHeader');\n this.#sharedUnprotectedHeader = sharedUnprotectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n assertNotSet(this.#unprotectedHeader, 'setUnprotectedHeader');\n this.#unprotectedHeader = unprotectedHeader;\n return this;\n }\n setAdditionalAuthenticatedData(aad) {\n this.#aad = aad;\n return this;\n }\n setContentEncryptionKey(cek) {\n assertNotSet(this.#cek, 'setContentEncryptionKey');\n this.#cek = cek;\n return this;\n }\n setInitializationVector(iv) {\n assertNotSet(this.#iv, 'setInitializationVector');\n this.#iv = iv;\n return this;\n }\n async encrypt(key, options) {\n if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) {\n throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');\n }\n if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {\n throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this.#protectedHeader,\n ...this.#unprotectedHeader,\n ...this.#sharedUnprotectedHeader,\n };\n validateCrit(JWEInvalid, new Map(), options?.crit, this.#protectedHeader, joseHeader);\n if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {\n throw new JOSENotSupported('Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.');\n }\n if (joseHeader.zip !== undefined && !this.#protectedHeader?.zip) {\n throw new JWEInvalid('JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.');\n }\n const { alg, enc } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('JWE \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n if (typeof enc !== 'string' || !enc) {\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid');\n }\n let encryptedKey;\n if (this.#cek && (alg === 'dir' || alg === 'ECDH-ES')) {\n throw new TypeError(`setContentEncryptionKey cannot be called with JWE \"alg\" (Algorithm) Header ${alg}`);\n }\n checkKeyType(alg === 'dir' ? enc : alg, key, 'encrypt');\n let cek;\n {\n let parameters;\n const k = await normalizeKey(key, alg);\n ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters));\n if (parameters) {\n if (options && unprotected in options) {\n if (!this.#unprotectedHeader) {\n this.setUnprotectedHeader(parameters);\n }\n else {\n this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters };\n }\n }\n else if (!this.#protectedHeader) {\n this.setProtectedHeader(parameters);\n }\n else {\n this.#protectedHeader = { ...this.#protectedHeader, ...parameters };\n }\n }\n }\n let additionalData;\n let protectedHeaderS;\n let protectedHeaderB;\n let aadMember;\n if (this.#protectedHeader) {\n protectedHeaderS = b64u(JSON.stringify(this.#protectedHeader));\n protectedHeaderB = encode(protectedHeaderS);\n }\n else {\n protectedHeaderS = '';\n protectedHeaderB = new Uint8Array();\n }\n if (this.#aad) {\n aadMember = b64u(this.#aad);\n const aadMemberBytes = encode(aadMember);\n additionalData = concat(protectedHeaderB, encode('.'), aadMemberBytes);\n }\n else {\n additionalData = protectedHeaderB;\n }\n let plaintext = this.#plaintext;\n if (joseHeader.zip === 'DEF') {\n plaintext = await compress(plaintext).catch((cause) => {\n throw new JWEInvalid('Failed to compress plaintext', { cause });\n });\n }\n const { ciphertext, tag, iv } = await encrypt(enc, plaintext, cek, this.#iv, additionalData);\n const jwe = {\n ciphertext: b64u(ciphertext),\n };\n if (iv) {\n jwe.iv = b64u(iv);\n }\n if (tag) {\n jwe.tag = b64u(tag);\n }\n if (encryptedKey) {\n jwe.encrypted_key = b64u(encryptedKey);\n }\n if (aadMember) {\n jwe.aad = aadMember;\n }\n if (this.#protectedHeader) {\n jwe.protected = protectedHeaderS;\n }\n if (this.#sharedUnprotectedHeader) {\n jwe.unprotected = this.#sharedUnprotectedHeader;\n }\n if (this.#unprotectedHeader) {\n jwe.header = this.#unprotectedHeader;\n }\n return jwe;\n }\n}\n", "import { decode as b64u } from '../../util/base64url.js';\nimport { verify } from '../../lib/signing.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder, encode } from '../../lib/buffer_utils.js';\nimport { decodeBase64url } from '../../lib/helpers.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { isObject } from '../../lib/type_checks.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { validateAlgorithms } from '../../lib/validate_algorithms.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nexport async function flattenedVerify(jws, key, options) {\n if (!isObject(jws)) {\n throw new JWSInvalid('Flattened JWS must be an object');\n }\n if (jws.protected === undefined && jws.header === undefined) {\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n }\n if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n throw new JWSInvalid('JWS Protected Header incorrect type');\n }\n if (jws.payload === undefined) {\n throw new JWSInvalid('JWS Payload missing');\n }\n if (typeof jws.signature !== 'string') {\n throw new JWSInvalid('JWS Signature missing or incorrect type');\n }\n if (jws.header !== undefined && !isObject(jws.header)) {\n throw new JWSInvalid('JWS Unprotected Header incorrect type');\n }\n let parsedProt = {};\n if (jws.protected) {\n try {\n const protectedHeader = b64u(jws.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWSInvalid('JWS Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jws.header)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jws.header,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = parsedProt.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n if (algorithms && !algorithms.has(alg)) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (b64) {\n if (typeof jws.payload !== 'string') {\n throw new JWSInvalid('JWS Payload must be a string');\n }\n }\n else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jws);\n resolvedKey = true;\n }\n checkKeyType(alg, key, 'verify');\n const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array(), encode('.'), typeof jws.payload === 'string'\n ? b64\n ? encode(jws.payload)\n : encoder.encode(jws.payload)\n : jws.payload);\n const signature = decodeBase64url(jws.signature, 'signature', JWSInvalid);\n const k = await normalizeKey(key, alg);\n const verified = await verify(alg, k, signature, data);\n if (!verified) {\n throw new JWSSignatureVerificationFailed();\n }\n let payload;\n if (b64) {\n payload = decodeBase64url(jws.payload, 'payload', JWSInvalid);\n }\n else if (typeof jws.payload === 'string') {\n payload = encoder.encode(jws.payload);\n }\n else {\n payload = jws.payload;\n }\n const result = { payload };\n if (jws.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jws.header !== undefined) {\n result.unprotectedHeader = jws.header;\n }\n if (resolvedKey) {\n return { ...result, key: k };\n }\n return result;\n}\n", "import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n if (jws instanceof Uint8Array) {\n jws = decoder.decode(jws);\n }\n if (typeof jws !== 'string') {\n throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n if (length !== 3) {\n throw new JWSInvalid('Invalid Compact JWS');\n }\n const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n", "import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { encoder, decoder } from './buffer_utils.js';\nimport { isObject } from './type_checks.js';\nconst epoch = (date) => Math.floor(date.getTime() / 1000);\nconst minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport function secs(str) {\n const matched = REGEX.exec(str);\n if (!matched || (matched[4] && matched[1])) {\n throw new TypeError('Invalid time period format');\n }\n const value = parseFloat(matched[2]);\n const unit = matched[3].toLowerCase();\n let numericDate;\n switch (unit) {\n case 'sec':\n case 'secs':\n case 'second':\n case 'seconds':\n case 's':\n numericDate = Math.round(value);\n break;\n case 'minute':\n case 'minutes':\n case 'min':\n case 'mins':\n case 'm':\n numericDate = Math.round(value * minute);\n break;\n case 'hour':\n case 'hours':\n case 'hr':\n case 'hrs':\n case 'h':\n numericDate = Math.round(value * hour);\n break;\n case 'day':\n case 'days':\n case 'd':\n numericDate = Math.round(value * day);\n break;\n case 'week':\n case 'weeks':\n case 'w':\n numericDate = Math.round(value * week);\n break;\n default:\n numericDate = Math.round(value * year);\n break;\n }\n if (matched[1] === '-' || matched[4] === 'ago') {\n return -numericDate;\n }\n return numericDate;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input)) {\n throw new TypeError(`Invalid ${label} input`);\n }\n return input;\n}\nconst normalizeTyp = (value) => {\n if (value.includes('/')) {\n return value.toLowerCase();\n }\n return `application/${value.toLowerCase()}`;\n};\nconst checkAudiencePresence = (audPayload, audOption) => {\n if (typeof audPayload === 'string') {\n return audOption.includes(audPayload);\n }\n if (Array.isArray(audPayload)) {\n return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n }\n return false;\n};\nexport function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(decoder.decode(encodedPayload));\n }\n catch {\n }\n if (!isObject(payload)) {\n throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n }\n const { typ } = options;\n if (typ &&\n (typeof protectedHeader.typ !== 'string' ||\n normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, 'typ', 'check_failed');\n }\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n const presenceCheck = [...requiredClaims];\n if (maxTokenAge !== undefined)\n presenceCheck.push('iat');\n if (audience !== undefined)\n presenceCheck.push('aud');\n if (subject !== undefined)\n presenceCheck.push('sub');\n if (issuer !== undefined)\n presenceCheck.push('iss');\n for (const claim of new Set(presenceCheck.reverse())) {\n if (!(claim in payload)) {\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, 'missing');\n }\n }\n if (issuer &&\n !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', payload, 'iss', 'check_failed');\n }\n if (subject && payload.sub !== subject) {\n throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', payload, 'sub', 'check_failed');\n }\n if (audience &&\n !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', payload, 'aud', 'check_failed');\n }\n let tolerance;\n switch (typeof options.clockTolerance) {\n case 'string':\n tolerance = secs(options.clockTolerance);\n break;\n case 'number':\n tolerance = options.clockTolerance;\n break;\n case 'undefined':\n tolerance = 0;\n break;\n default:\n throw new TypeError('Invalid clockTolerance option type');\n }\n const { currentDate } = options;\n const now = epoch(currentDate || new Date());\n if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n throw new JWTClaimValidationFailed('\"iat\" claim must be a number', payload, 'iat', 'invalid');\n }\n if (payload.nbf !== undefined) {\n if (typeof payload.nbf !== 'number') {\n throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', payload, 'nbf', 'invalid');\n }\n if (payload.nbf > now + tolerance) {\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, 'nbf', 'check_failed');\n }\n }\n if (payload.exp !== undefined) {\n if (typeof payload.exp !== 'number') {\n throw new JWTClaimValidationFailed('\"exp\" claim must be a number', payload, 'exp', 'invalid');\n }\n if (payload.exp <= now - tolerance) {\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, 'exp', 'check_failed');\n }\n }\n if (maxTokenAge) {\n const age = now - payload.iat;\n const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n if (age - tolerance > max) {\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');\n }\n if (age < 0 - tolerance) {\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');\n }\n }\n return payload;\n}\nexport class JWTClaimsBuilder {\n #payload;\n constructor(payload) {\n if (!isObject(payload)) {\n throw new TypeError('JWT Claims Set MUST be an object');\n }\n this.#payload = structuredClone(payload);\n }\n data() {\n return encoder.encode(JSON.stringify(this.#payload));\n }\n get iss() {\n return this.#payload.iss;\n }\n set iss(value) {\n this.#payload.iss = value;\n }\n get sub() {\n return this.#payload.sub;\n }\n set sub(value) {\n this.#payload.sub = value;\n }\n get aud() {\n return this.#payload.aud;\n }\n set aud(value) {\n this.#payload.aud = value;\n }\n set jti(value) {\n this.#payload.jti = value;\n }\n set nbf(value) {\n if (typeof value === 'number') {\n this.#payload.nbf = validateInput('setNotBefore', value);\n }\n else if (value instanceof Date) {\n this.#payload.nbf = validateInput('setNotBefore', epoch(value));\n }\n else {\n this.#payload.nbf = epoch(new Date()) + secs(value);\n }\n }\n set exp(value) {\n if (typeof value === 'number') {\n this.#payload.exp = validateInput('setExpirationTime', value);\n }\n else if (value instanceof Date) {\n this.#payload.exp = validateInput('setExpirationTime', epoch(value));\n }\n else {\n this.#payload.exp = epoch(new Date()) + secs(value);\n }\n }\n set iat(value) {\n if (value === undefined) {\n this.#payload.iat = epoch(new Date());\n }\n else if (value instanceof Date) {\n this.#payload.iat = validateInput('setIssuedAt', epoch(value));\n }\n else if (typeof value === 'string') {\n this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));\n }\n else {\n this.#payload.iat = validateInput('setIssuedAt', value);\n }\n }\n}\n", "import { compactVerify } from '../jws/compact/verify.js';\nimport { validateClaimsSet } from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n const verified = await compactVerify(jwt, key, options);\n if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n const result = { payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n", "import { compactDecrypt } from '../jwe/compact/decrypt.js';\nimport { validateClaimsSet } from '../lib/jwt_claims_set.js';\nimport { JWTClaimValidationFailed } from '../util/errors.js';\nexport async function jwtDecrypt(jwt, key, options) {\n const decrypted = await compactDecrypt(jwt, key, options);\n const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options);\n const { protectedHeader } = decrypted;\n if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {\n throw new JWTClaimValidationFailed('replicated \"iss\" claim header parameter mismatch', payload, 'iss', 'mismatch');\n }\n if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {\n throw new JWTClaimValidationFailed('replicated \"sub\" claim header parameter mismatch', payload, 'sub', 'mismatch');\n }\n if (protectedHeader.aud !== undefined &&\n JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {\n throw new JWTClaimValidationFailed('replicated \"aud\" claim header parameter mismatch', payload, 'aud', 'mismatch');\n }\n const result = { payload, protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: decrypted.key };\n }\n return result;\n}\n", "import { FlattenedEncrypt } from '../flattened/encrypt.js';\nexport class CompactEncrypt {\n #flattened;\n constructor(plaintext) {\n this.#flattened = new FlattenedEncrypt(plaintext);\n }\n setContentEncryptionKey(cek) {\n this.#flattened.setContentEncryptionKey(cek);\n return this;\n }\n setInitializationVector(iv) {\n this.#flattened.setInitializationVector(iv);\n return this;\n }\n setProtectedHeader(protectedHeader) {\n this.#flattened.setProtectedHeader(protectedHeader);\n return this;\n }\n setKeyManagementParameters(parameters) {\n this.#flattened.setKeyManagementParameters(parameters);\n return this;\n }\n async encrypt(key, options) {\n const jwe = await this.#flattened.encrypt(key, options);\n return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');\n }\n}\n", "import { encode as b64u } from '../../util/base64url.js';\nimport { sign } from '../../lib/signing.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { concat, encode } from '../../lib/buffer_utils.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nimport { assertNotSet } from '../../lib/helpers.js';\nexport class FlattenedSign {\n #payload;\n #protectedHeader;\n #unprotectedHeader;\n constructor(payload) {\n if (!(payload instanceof Uint8Array)) {\n throw new TypeError('payload must be an instance of Uint8Array');\n }\n this.#payload = payload;\n }\n setProtectedHeader(protectedHeader) {\n assertNotSet(this.#protectedHeader, 'setProtectedHeader');\n this.#protectedHeader = protectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n assertNotSet(this.#unprotectedHeader, 'setUnprotectedHeader');\n this.#unprotectedHeader = unprotectedHeader;\n return this;\n }\n async sign(key, options) {\n if (!this.#protectedHeader && !this.#unprotectedHeader) {\n throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');\n }\n if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this.#protectedHeader,\n ...this.#unprotectedHeader,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this.#protectedHeader, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = this.#protectedHeader.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n checkKeyType(alg, key, 'sign');\n let payloadS;\n let payloadB;\n if (b64) {\n payloadS = b64u(this.#payload);\n payloadB = encode(payloadS);\n }\n else {\n payloadB = this.#payload;\n payloadS = '';\n }\n let protectedHeaderString;\n let protectedHeaderBytes;\n if (this.#protectedHeader) {\n protectedHeaderString = b64u(JSON.stringify(this.#protectedHeader));\n protectedHeaderBytes = encode(protectedHeaderString);\n }\n else {\n protectedHeaderString = '';\n protectedHeaderBytes = new Uint8Array();\n }\n const data = concat(protectedHeaderBytes, encode('.'), payloadB);\n const k = await normalizeKey(key, alg);\n const signature = await sign(alg, k, data);\n const jws = {\n signature: b64u(signature),\n payload: payloadS,\n };\n if (this.#unprotectedHeader) {\n jws.header = this.#unprotectedHeader;\n }\n if (this.#protectedHeader) {\n jws.protected = protectedHeaderString;\n }\n return jws;\n }\n}\n", "import { FlattenedSign } from '../flattened/sign.js';\nexport class CompactSign {\n #flattened;\n constructor(payload) {\n this.#flattened = new FlattenedSign(payload);\n }\n setProtectedHeader(protectedHeader) {\n this.#flattened.setProtectedHeader(protectedHeader);\n return this;\n }\n async sign(key, options) {\n const jws = await this.#flattened.sign(key, options);\n if (jws.payload === undefined) {\n throw new TypeError('use the flattened module for creating JWS with b64: false');\n }\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n }\n}\n", "import { CompactSign } from '../jws/compact/sign.js';\nimport { JWTInvalid } from '../util/errors.js';\nimport { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';\nexport class SignJWT {\n #protectedHeader;\n #jwt;\n constructor(payload = {}) {\n this.#jwt = new JWTClaimsBuilder(payload);\n }\n setIssuer(issuer) {\n this.#jwt.iss = issuer;\n return this;\n }\n setSubject(subject) {\n this.#jwt.sub = subject;\n return this;\n }\n setAudience(audience) {\n this.#jwt.aud = audience;\n return this;\n }\n setJti(jwtId) {\n this.#jwt.jti = jwtId;\n return this;\n }\n setNotBefore(input) {\n this.#jwt.nbf = input;\n return this;\n }\n setExpirationTime(input) {\n this.#jwt.exp = input;\n return this;\n }\n setIssuedAt(input) {\n this.#jwt.iat = input;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n this.#protectedHeader = protectedHeader;\n return this;\n }\n async sign(key, options) {\n const sig = new CompactSign(this.#jwt.data());\n sig.setProtectedHeader(this.#protectedHeader);\n if (Array.isArray(this.#protectedHeader?.crit) &&\n this.#protectedHeader.crit.includes('b64') &&\n this.#protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n return sig.sign(key, options);\n }\n}\n", "import { CompactEncrypt } from '../jwe/compact/encrypt.js';\nimport { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';\nimport { assertNotSet } from '../lib/helpers.js';\nexport class EncryptJWT {\n #cek;\n #iv;\n #keyManagementParameters;\n #protectedHeader;\n #replicateIssuerAsHeader;\n #replicateSubjectAsHeader;\n #replicateAudienceAsHeader;\n #jwt;\n constructor(payload = {}) {\n this.#jwt = new JWTClaimsBuilder(payload);\n }\n setIssuer(issuer) {\n this.#jwt.iss = issuer;\n return this;\n }\n setSubject(subject) {\n this.#jwt.sub = subject;\n return this;\n }\n setAudience(audience) {\n this.#jwt.aud = audience;\n return this;\n }\n setJti(jwtId) {\n this.#jwt.jti = jwtId;\n return this;\n }\n setNotBefore(input) {\n this.#jwt.nbf = input;\n return this;\n }\n setExpirationTime(input) {\n this.#jwt.exp = input;\n return this;\n }\n setIssuedAt(input) {\n this.#jwt.iat = input;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n assertNotSet(this.#protectedHeader, 'setProtectedHeader');\n this.#protectedHeader = protectedHeader;\n return this;\n }\n setKeyManagementParameters(parameters) {\n assertNotSet(this.#keyManagementParameters, 'setKeyManagementParameters');\n this.#keyManagementParameters = parameters;\n return this;\n }\n setContentEncryptionKey(cek) {\n assertNotSet(this.#cek, 'setContentEncryptionKey');\n this.#cek = cek;\n return this;\n }\n setInitializationVector(iv) {\n assertNotSet(this.#iv, 'setInitializationVector');\n this.#iv = iv;\n return this;\n }\n replicateIssuerAsHeader() {\n this.#replicateIssuerAsHeader = true;\n return this;\n }\n replicateSubjectAsHeader() {\n this.#replicateSubjectAsHeader = true;\n return this;\n }\n replicateAudienceAsHeader() {\n this.#replicateAudienceAsHeader = true;\n return this;\n }\n async encrypt(key, options) {\n const enc = new CompactEncrypt(this.#jwt.data());\n if (this.#protectedHeader &&\n (this.#replicateIssuerAsHeader ||\n this.#replicateSubjectAsHeader ||\n this.#replicateAudienceAsHeader)) {\n this.#protectedHeader = {\n ...this.#protectedHeader,\n iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : undefined,\n sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : undefined,\n aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : undefined,\n };\n }\n enc.setProtectedHeader(this.#protectedHeader);\n if (this.#iv) {\n enc.setInitializationVector(this.#iv);\n }\n if (this.#cek) {\n enc.setContentEncryptionKey(this.#cek);\n }\n if (this.#keyManagementParameters) {\n enc.setKeyManagementParameters(this.#keyManagementParameters);\n }\n return enc.encrypt(key, options);\n }\n}\n", "import { digest } from '../lib/helpers.js';\nimport { encode as b64u } from '../util/base64url.js';\nimport { JOSENotSupported, JWKInvalid } from '../util/errors.js';\nimport { encode } from '../lib/buffer_utils.js';\nimport { isKeyLike } from '../lib/is_key_like.js';\nimport { isJWK } from '../lib/type_checks.js';\nimport { exportJWK } from '../key/export.js';\nimport { invalidKeyInput } from '../lib/invalid_key_input.js';\nconst check = (value, description) => {\n if (typeof value !== 'string' || !value) {\n throw new JWKInvalid(`${description} missing or invalid`);\n }\n};\nexport async function calculateJwkThumbprint(key, digestAlgorithm) {\n let jwk;\n if (isJWK(key)) {\n jwk = key;\n }\n else if (isKeyLike(key)) {\n jwk = await exportJWK(key);\n }\n else {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n digestAlgorithm ??= 'sha256';\n if (digestAlgorithm !== 'sha256' &&\n digestAlgorithm !== 'sha384' &&\n digestAlgorithm !== 'sha512') {\n throw new TypeError('digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"');\n }\n let components;\n switch (jwk.kty) {\n case 'AKP':\n check(jwk.alg, '\"alg\" (Algorithm) Parameter');\n check(jwk.pub, '\"pub\" (Public key) Parameter');\n components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };\n break;\n case 'EC':\n check(jwk.crv, '\"crv\" (Curve) Parameter');\n check(jwk.x, '\"x\" (X Coordinate) Parameter');\n check(jwk.y, '\"y\" (Y Coordinate) Parameter');\n components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n break;\n case 'OKP':\n check(jwk.crv, '\"crv\" (Subtype of Key Pair) Parameter');\n check(jwk.x, '\"x\" (Public Key) Parameter');\n components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n break;\n case 'RSA':\n check(jwk.e, '\"e\" (Exponent) Parameter');\n check(jwk.n, '\"n\" (Modulus) Parameter');\n components = { e: jwk.e, kty: jwk.kty, n: jwk.n };\n break;\n case 'oct':\n check(jwk.k, '\"k\" (Key Value) Parameter');\n components = { k: jwk.k, kty: jwk.kty };\n break;\n default:\n throw new JOSENotSupported('\"kty\" (Key Type) Parameter missing or unsupported');\n }\n const data = encode(JSON.stringify(components));\n return b64u(await digest(digestAlgorithm, data));\n}\nexport async function calculateJwkThumbprintUri(key, digestAlgorithm) {\n digestAlgorithm ??= 'sha256';\n const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);\n return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;\n}\n", "import { importJWK } from '../key/import.js';\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nfunction getKtyFromAlg(alg) {\n switch (typeof alg === 'string' && alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n return 'RSA';\n case 'ES':\n return 'EC';\n case 'Ed':\n return 'OKP';\n case 'ML':\n return 'AKP';\n default:\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n }\n}\nfunction isJWKSLike(jwks) {\n return (jwks &&\n typeof jwks === 'object' &&\n Array.isArray(jwks.keys) &&\n jwks.keys.every(isJWKLike));\n}\nfunction isJWKLike(key) {\n return isObject(key);\n}\nclass LocalJWKSet {\n #jwks;\n #cached = new WeakMap();\n constructor(jwks) {\n if (!isJWKSLike(jwks)) {\n throw new JWKSInvalid('JSON Web Key Set malformed');\n }\n this.#jwks = structuredClone(jwks);\n }\n jwks() {\n return this.#jwks;\n }\n async getKey(protectedHeader, token) {\n const { alg, kid } = { ...protectedHeader, ...token?.header };\n const kty = getKtyFromAlg(alg);\n const candidates = this.#jwks.keys.filter((jwk) => {\n let candidate = kty === jwk.kty;\n if (candidate && typeof kid === 'string') {\n candidate = kid === jwk.kid;\n }\n if (candidate && (typeof jwk.alg === 'string' || kty === 'AKP')) {\n candidate = alg === jwk.alg;\n }\n if (candidate && typeof jwk.use === 'string') {\n candidate = jwk.use === 'sig';\n }\n if (candidate && Array.isArray(jwk.key_ops)) {\n candidate = jwk.key_ops.includes('verify');\n }\n if (candidate) {\n switch (alg) {\n case 'ES256':\n candidate = jwk.crv === 'P-256';\n break;\n case 'ES384':\n candidate = jwk.crv === 'P-384';\n break;\n case 'ES512':\n candidate = jwk.crv === 'P-521';\n break;\n case 'Ed25519':\n case 'EdDSA':\n candidate = jwk.crv === 'Ed25519';\n break;\n }\n }\n return candidate;\n });\n const { 0: jwk, length } = candidates;\n if (length === 0) {\n throw new JWKSNoMatchingKey();\n }\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n const _cached = this.#cached;\n error[Symbol.asyncIterator] = async function* () {\n for (const jwk of candidates) {\n try {\n yield await importWithAlgCache(_cached, jwk, alg);\n }\n catch { }\n }\n };\n throw error;\n }\n return importWithAlgCache(this.#cached, jwk, alg);\n }\n}\nasync function importWithAlgCache(cache, jwk, alg) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);\n if (cached[alg] === undefined) {\n const key = await importJWK({ ...jwk, ext: true }, alg);\n if (key instanceof Uint8Array || key.type !== 'public') {\n throw new JWKSInvalid('JSON Web Key Set members must be public keys');\n }\n cached[alg] = key;\n }\n return cached[alg];\n}\nexport function createLocalJWKSet(jwks) {\n const set = new LocalJWKSet(jwks);\n const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(localJWKSet, {\n jwks: {\n value: () => structuredClone(set.jwks()),\n enumerable: false,\n configurable: false,\n writable: false,\n },\n });\n return localJWKSet;\n}\n", "import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js';\nimport { createLocalJWKSet } from './local.js';\nimport { isObject } from '../lib/type_checks.js';\nfunction isCloudflareWorkers() {\n return (typeof WebSocketPair !== 'undefined' ||\n (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||\n (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));\n}\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'jose';\n const VERSION = 'v6.2.2';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nexport const customFetch = Symbol();\nasync function fetchJwks(url, headers, signal, fetchImpl = fetch) {\n const response = await fetchImpl(url, {\n method: 'GET',\n signal,\n redirect: 'manual',\n headers,\n }).catch((err) => {\n if (err.name === 'TimeoutError') {\n throw new JWKSTimeout();\n }\n throw err;\n });\n if (response.status !== 200) {\n throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');\n }\n try {\n return await response.json();\n }\n catch {\n throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');\n }\n}\nexport const jwksCache = Symbol();\nfunction isFreshJwksCache(input, cacheMaxAge) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {\n return false;\n }\n if (!('jwks' in input) ||\n !isObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isObject)) {\n return false;\n }\n return true;\n}\nclass RemoteJWKSet {\n #url;\n #timeoutDuration;\n #cooldownDuration;\n #cacheMaxAge;\n #jwksTimestamp;\n #pendingFetch;\n #headers;\n #customFetch;\n #local;\n #cache;\n constructor(url, options) {\n if (!(url instanceof URL)) {\n throw new TypeError('url must be an instance of URL');\n }\n this.#url = new URL(url.href);\n this.#timeoutDuration =\n typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;\n this.#cooldownDuration =\n typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;\n this.#cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;\n this.#headers = new Headers(options?.headers);\n if (USER_AGENT && !this.#headers.has('User-Agent')) {\n this.#headers.set('User-Agent', USER_AGENT);\n }\n if (!this.#headers.has('accept')) {\n this.#headers.set('accept', 'application/json');\n this.#headers.append('accept', 'application/jwk-set+json');\n }\n this.#customFetch = options?.[customFetch];\n if (options?.[jwksCache] !== undefined) {\n this.#cache = options?.[jwksCache];\n if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {\n this.#jwksTimestamp = this.#cache.uat;\n this.#local = createLocalJWKSet(this.#cache.jwks);\n }\n }\n }\n pendingFetch() {\n return !!this.#pendingFetch;\n }\n coolingDown() {\n return typeof this.#jwksTimestamp === 'number'\n ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration\n : false;\n }\n fresh() {\n return typeof this.#jwksTimestamp === 'number'\n ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge\n : false;\n }\n jwks() {\n return this.#local?.jwks();\n }\n async getKey(protectedHeader, token) {\n if (!this.#local || !this.fresh()) {\n await this.reload();\n }\n try {\n return await this.#local(protectedHeader, token);\n }\n catch (err) {\n if (err instanceof JWKSNoMatchingKey) {\n if (this.coolingDown() === false) {\n await this.reload();\n return this.#local(protectedHeader, token);\n }\n }\n throw err;\n }\n }\n async reload() {\n if (this.#pendingFetch && isCloudflareWorkers()) {\n this.#pendingFetch = undefined;\n }\n this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch)\n .then((json) => {\n this.#local = createLocalJWKSet(json);\n if (this.#cache) {\n this.#cache.uat = Date.now();\n this.#cache.jwks = json;\n }\n this.#jwksTimestamp = Date.now();\n this.#pendingFetch = undefined;\n })\n .catch((err) => {\n this.#pendingFetch = undefined;\n throw err;\n });\n await this.#pendingFetch;\n }\n}\nexport function createRemoteJWKSet(url, options) {\n const set = new RemoteJWKSet(url, options);\n const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(remoteJWKSet, {\n coolingDown: {\n get: () => set.coolingDown(),\n enumerable: true,\n configurable: false,\n },\n fresh: {\n get: () => set.fresh(),\n enumerable: true,\n configurable: false,\n },\n reload: {\n value: () => set.reload(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n reloading: {\n get: () => set.pendingFetch(),\n enumerable: true,\n configurable: false,\n },\n jwks: {\n value: () => set.jwks(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n });\n return remoteJWKSet;\n}\n", "import { decode as b64u } from './base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport { isObject } from '../lib/type_checks.js';\nexport function decodeProtectedHeader(token) {\n let protectedB64u;\n if (typeof token === 'string') {\n const parts = token.split('.');\n if (parts.length === 3 || parts.length === 5) {\n ;\n [protectedB64u] = parts;\n }\n }\n else if (typeof token === 'object' && token) {\n if ('protected' in token) {\n protectedB64u = token.protected;\n }\n else {\n throw new TypeError('Token does not contain a Protected Header');\n }\n }\n try {\n if (typeof protectedB64u !== 'string' || !protectedB64u) {\n throw new Error();\n }\n const result = JSON.parse(decoder.decode(b64u(protectedB64u)));\n if (!isObject(result)) {\n throw new Error();\n }\n return result;\n }\n catch {\n throw new TypeError('Invalid Token or Protected Header formatting');\n }\n}\n", "import { decode as b64u } from './base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport { isObject } from '../lib/type_checks.js';\nimport { JWTInvalid } from './errors.js';\nexport function decodeJwt(jwt) {\n if (typeof jwt !== 'string')\n throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');\n const { 1: payload, length } = jwt.split('.');\n if (length === 5)\n throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');\n if (length !== 3)\n throw new JWTInvalid('Invalid JWT');\n if (!payload)\n throw new JWTInvalid('JWTs must contain a payload');\n let decoded;\n try {\n decoded = b64u(payload);\n }\n catch {\n throw new JWTInvalid('Failed to base64url decode the payload');\n }\n let result;\n try {\n result = JSON.parse(decoder.decode(decoded));\n }\n catch {\n throw new JWTInvalid('Failed to parse the decoded payload as JSON');\n }\n if (!isObject(result))\n throw new JWTInvalid('Invalid JWT Claims Set');\n return result;\n}\n", "import { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { EncryptJWT, SignJWT, base64url, calculateJwkThumbprint, decodeProtectedHeader, jwtDecrypt, jwtVerify } from \"jose\";\n//#region src/crypto/jwt.ts\nasync function signJWT(payload, secret, expiresIn = 3600) {\n\treturn await new SignJWT(payload).setProtectedHeader({ alg: \"HS256\" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret));\n}\nasync function verifyJWT(token, secret) {\n\ttry {\n\t\treturn (await jwtVerify(token, new TextEncoder().encode(secret))).payload;\n\t} catch {\n\t\treturn null;\n\t}\n}\nconst info = new Uint8Array([\n\t66,\n\t101,\n\t116,\n\t116,\n\t101,\n\t114,\n\t65,\n\t117,\n\t116,\n\t104,\n\t46,\n\t106,\n\t115,\n\t32,\n\t71,\n\t101,\n\t110,\n\t101,\n\t114,\n\t97,\n\t116,\n\t101,\n\t100,\n\t32,\n\t69,\n\t110,\n\t99,\n\t114,\n\t121,\n\t112,\n\t116,\n\t105,\n\t111,\n\t110,\n\t32,\n\t75,\n\t101,\n\t121\n]);\nconst now = () => Date.now() / 1e3 | 0;\nconst alg = \"dir\";\nconst enc = \"A256CBC-HS512\";\nfunction deriveEncryptionSecret(secret, salt) {\n\treturn hkdf(sha256, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64);\n}\nfunction getCurrentSecret(secret) {\n\tif (typeof secret === \"string\") return secret;\n\tconst value = secret.keys.get(secret.currentVersion);\n\tif (!value) throw new Error(`Secret version ${secret.currentVersion} not found in keys`);\n\treturn value;\n}\nfunction getAllSecrets(secret) {\n\tif (typeof secret === \"string\") return [{\n\t\tversion: 0,\n\t\tvalue: secret\n\t}];\n\tconst result = [];\n\tfor (const [version, value] of secret.keys) result.push({\n\t\tversion,\n\t\tvalue\n\t});\n\tif (secret.legacySecret && !result.some((s) => s.value === secret.legacySecret)) result.push({\n\t\tversion: -1,\n\t\tvalue: secret.legacySecret\n\t});\n\treturn result;\n}\nasync function symmetricEncodeJWT(payload, secret, salt, expiresIn = 3600) {\n\tconst encryptionSecret = deriveEncryptionSecret(getCurrentSecret(secret), salt);\n\tconst thumbprint = await calculateJwkThumbprint({\n\t\tkty: \"oct\",\n\t\tk: base64url.encode(encryptionSecret)\n\t}, \"sha256\");\n\treturn await new EncryptJWT(payload).setProtectedHeader({\n\t\talg,\n\t\tenc,\n\t\tkid: thumbprint\n\t}).setIssuedAt().setExpirationTime(now() + expiresIn).setJti(crypto.randomUUID()).encrypt(encryptionSecret);\n}\nconst jwtDecryptOpts = {\n\tclockTolerance: 15,\n\tkeyManagementAlgorithms: [alg],\n\tcontentEncryptionAlgorithms: [enc, \"A256GCM\"]\n};\nasync function symmetricDecodeJWT(token, secret, salt) {\n\tif (!token) return null;\n\tlet hasKid = false;\n\ttry {\n\t\thasKid = decodeProtectedHeader(token).kid !== void 0;\n\t} catch {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst secrets = getAllSecrets(secret);\n\t\tconst { payload } = await jwtDecrypt(token, async (protectedHeader) => {\n\t\t\tconst kid = protectedHeader.kid;\n\t\t\tif (kid !== void 0) {\n\t\t\t\tfor (const s of secrets) {\n\t\t\t\t\tconst encryptionSecret = deriveEncryptionSecret(s.value, salt);\n\t\t\t\t\tif (kid === await calculateJwkThumbprint({\n\t\t\t\t\t\tkty: \"oct\",\n\t\t\t\t\t\tk: base64url.encode(encryptionSecret)\n\t\t\t\t\t}, \"sha256\")) return encryptionSecret;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"no matching decryption secret\");\n\t\t\t}\n\t\t\tif (secrets.length === 1) return deriveEncryptionSecret(secrets[0].value, salt);\n\t\t\treturn deriveEncryptionSecret(secrets[0].value, salt);\n\t\t}, jwtDecryptOpts);\n\t\treturn payload;\n\t} catch {\n\t\tif (hasKid) return null;\n\t\tconst secrets = getAllSecrets(secret);\n\t\tif (secrets.length <= 1) return null;\n\t\tfor (let i = 1; i < secrets.length; i++) try {\n\t\t\tconst s = secrets[i];\n\t\t\tconst { payload } = await jwtDecrypt(token, deriveEncryptionSecret(s.value, salt), jwtDecryptOpts);\n\t\t\treturn payload;\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\treturn null;\n\t}\n}\n//#endregion\nexport { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT };\n", "import { randomBytes, scrypt } from 'node:crypto';\n\nconst config = {\n N: 16384,\n r: 16,\n p: 1,\n dkLen: 64\n};\nfunction generateKey(password, salt) {\n return new Promise((resolve, reject) => {\n scrypt(\n password.normalize(\"NFKC\"),\n salt,\n config.dkLen,\n {\n N: config.N,\n r: config.r,\n p: config.p,\n maxmem: 128 * config.N * config.r * 2\n },\n (err, key) => {\n if (err)\n reject(err);\n else\n resolve(key);\n }\n );\n });\n}\nasync function hashPassword(password) {\n const salt = randomBytes(16).toString(\"hex\");\n const key = await generateKey(password, salt);\n return `${salt}:${key.toString(\"hex\")}`;\n}\nasync function verifyPassword(hash, password) {\n const [salt, key] = hash.split(\":\");\n if (!salt || !key) {\n throw new Error(\"Invalid password hash\");\n }\n const targetKey = await generateKey(password, salt);\n return targetKey.toString(\"hex\") === key;\n}\n\nexport { hashPassword, verifyPassword };\n", "import { hashPassword, verifyPassword } from \"@better-auth/utils/password\";\n//#region src/crypto/password.ts\n/**\n* `@better-auth/utils/password` uses the \"node\" export condition in package.json\n* to automatically pick the right implementation:\n* - Node.js / Bun / Deno \u2192 `node:crypto scrypt` (libuv thread pool, non-blocking)\n* - Unsupported runtimes \u2192 `@noble/hashes scrypt` (pure JS fallback)\n*/\nconst hashPassword$1 = hashPassword;\nconst verifyPassword$1 = async ({ hash, password }) => {\n\treturn verifyPassword(hash, password);\n};\n//#endregion\nexport { hashPassword$1 as hashPassword, verifyPassword$1 as verifyPassword };\n", "function getAlphabet(urlSafe) {\n return urlSafe ? \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n}\nfunction base64Encode(data, alphabet, padding) {\n let result = \"\";\n let buffer = 0;\n let shift = 0;\n for (const byte of data) {\n buffer = buffer << 8 | byte;\n shift += 8;\n while (shift >= 6) {\n shift -= 6;\n result += alphabet[buffer >> shift & 63];\n }\n }\n if (shift > 0) {\n result += alphabet[buffer << 6 - shift & 63];\n }\n if (padding) {\n const padCount = (4 - result.length % 4) % 4;\n result += \"=\".repeat(padCount);\n }\n return result;\n}\nfunction base64Decode(data, alphabet) {\n const decodeMap = /* @__PURE__ */ new Map();\n for (let i = 0; i < alphabet.length; i++) {\n decodeMap.set(alphabet[i], i);\n }\n const result = [];\n let buffer = 0;\n let bitsCollected = 0;\n for (const char of data) {\n if (char === \"=\")\n break;\n const value = decodeMap.get(char);\n if (value === void 0) {\n throw new Error(`Invalid Base64 character: ${char}`);\n }\n buffer = buffer << 6 | value;\n bitsCollected += 6;\n if (bitsCollected >= 8) {\n bitsCollected -= 8;\n result.push(buffer >> bitsCollected & 255);\n }\n }\n return Uint8Array.from(result);\n}\nconst base64 = {\n encode(data, options = {}) {\n const alphabet = getAlphabet(false);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base64Encode(buffer, alphabet, options.padding ?? true);\n },\n decode(data) {\n if (typeof data !== \"string\") {\n data = new TextDecoder().decode(data);\n }\n const urlSafe = data.includes(\"-\") || data.includes(\"_\");\n const alphabet = getAlphabet(urlSafe);\n return base64Decode(data, alphabet);\n }\n};\nconst base64Url = {\n encode(data, options = {}) {\n const alphabet = getAlphabet(true);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base64Encode(buffer, alphabet, options.padding ?? true);\n },\n decode(data) {\n const urlSafe = data.includes(\"-\") || data.includes(\"_\");\n const alphabet = getAlphabet(urlSafe);\n return base64Decode(data, alphabet);\n }\n};\n\nexport { base64, base64Url };\n", "function getWebcryptoSubtle() {\n const cr = typeof globalThis !== \"undefined\" && globalThis.crypto;\n if (cr && typeof cr.subtle === \"object\" && cr.subtle != null)\n return cr.subtle;\n throw new Error(\"crypto.subtle must be defined\");\n}\n\nexport { getWebcryptoSubtle };\n", "import { base64Url, base64 } from './base64.mjs';\nimport { getWebcryptoSubtle } from './index.mjs';\n\nfunction createHash(algorithm, encoding) {\n return {\n digest: async (input) => {\n const encoder = new TextEncoder();\n const data = typeof input === \"string\" ? encoder.encode(input) : input;\n const hashBuffer = await getWebcryptoSubtle().digest(algorithm, data);\n if (encoding === \"hex\") {\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return hashHex;\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n if (encoding.includes(\"url\")) {\n return base64Url.encode(hashBuffer, {\n padding: encoding !== \"base64urlnopad\"\n });\n }\n const hashBase64 = base64.encode(hashBuffer);\n return hashBase64;\n }\n return hashBuffer;\n }\n };\n}\n\nexport { createHash };\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - Value to inspect.\n * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.\n * @example\n * Guards a value before treating it as raw key material.\n *\n * ```ts\n * isBytes(new Uint8Array());\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /\n // cross-realm cases. The fallback still requires a real ArrayBuffer view\n // so plain JSON-deserialized `{ constructor: ... }`\n // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is boolean.\n * @param b - Value to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validates a boolean option before branching on it.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(b: boolean): void {\n if (typeof b !== 'boolean') throw new TypeError(`boolean expected, not ${b}`);\n}\n\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validates a non-negative length or counter.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport function anumber(n: number): void {\n if (typeof n !== 'number') throw new TypeError('number expected, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError('positive integer expected, got ' + n);\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - Value to validate.\n * @param length - Expected byte length.\n * @param title - Optional label used in error messages.\n * @returns The validated byte array.\n * On Node, `Buffer` is accepted too because it is a Uint8Array view.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument lengths. {@link RangeError}\n * @example\n * Validates a fixed-length nonce or key buffer.\n *\n * ```ts\n * abytes(new Uint8Array([1, 2]), 2);\n * ```\n */\nexport function abytes(\n value: TArg,\n length?: number,\n title: string = ''\n): TRet {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet;\n}\n\n/**\n * Asserts a hash- or MAC-like instance has not been destroyed or finished.\n * @param instance - Stateful instance to validate.\n * @param checkFinished - Whether to reject finished instances.\n * When `false`, only `destroyed` is checked.\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Guards against calling `update()` or `digest()` on a finished hash.\n *\n * ```ts\n * aexists({ destroyed: false, finished: false });\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a properly-sized byte array.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,\n * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.\n * @throws On wrong argument types. {@link TypeError}\n * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @throws On wrong output buffer alignment. {@link Error}\n * @example\n * Verifies that a caller-provided output buffer is large enough.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out: any, instance: any, onlyAligned = false): void {\n abytes(out, undefined, 'output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('digestInto() expects output buffer of length at least ' + min);\n }\n if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n}\n\n/** One-shot hash helper with `.create()`. */\nexport type IHash = {\n (data: string | TArg): TRet;\n /** Input block size in bytes. */\n blockLen: number;\n /** Digest size in bytes. */\n outputLen: number;\n /** Creates a fresh incremental hash instance of the same algorithm. */\n create: any;\n};\n\n/** One-shot MAC helper with `.create()`. */\nexport type CMac = {\n (msg: TArg, key: TArg): TRet;\n /** Input block size in bytes. */\n blockLen: number;\n /** Digest size in bytes. */\n outputLen: number;\n /**\n * Creates a fresh incremental MAC instance of the same algorithm.\n * @param key - MAC key bytes.\n * @param args - Additional constructor arguments, when the MAC wrapper needs them.\n * @returns Fresh incremental MAC instance.\n */\n create(key: TArg, ...args: A): H;\n};\n\n/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed-array view to Uint8Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint8Array view over the same bytes.\n * @example\n * Views 32-bit words as raw bytes without copying.\n *\n * ```ts\n * u8(new Uint32Array([1]));\n * ```\n */\nexport function u8(arr: TArg): TRet {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet;\n}\n\n/**\n * Casts a typed-array view to Uint32Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint32Array view over the same bytes. Callers are expected to provide a\n * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.\n * @example\n * Views a byte buffer as 32-bit words for block processing.\n *\n * ```ts\n * u32(new Uint8Array(4));\n * ```\n */\nexport function u32(arr: TArg): TRet {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet;\n}\n\n/**\n * Zeroizes typed arrays in place.\n * Warning: JS provides no guarantees.\n * @param arrays - Arrays to wipe.\n * @example\n * Wipes a temporary key buffer after use.\n *\n * ```ts\n * const bytes = new Uint8Array([1]);\n * clean(bytes);\n * ```\n */\nexport function clean(...arrays: TArg): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - Typed-array view to wrap.\n * @returns DataView over the same bytes.\n * @example\n * Creates an endian-aware view for length encoding.\n *\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Whether the current platform is little-endian.\n * Most are; some IBM systems are not.\n */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Reverses byte order of one 32-bit word.\n * @param word - Unsigned 32-bit word to swap.\n * @returns The same word with bytes reversed.\n * @example\n * Swaps a big-endian word into little-endian byte order.\n *\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport const byteSwap = (word: number): number =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n\n/**\n * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.\n * @param n - Unsigned 32-bit word to normalize.\n * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.\n * @example\n * Normalizes a host-endian word before passing it into an ARX/AES core.\n *\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - Uint32Array whose words should be swapped.\n * @returns The same array after in-place byte swapping.\n * @example\n * Swaps every 32-bit word in a word-view buffer.\n *\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport const byteSwap32 = (arr: TArg): TRet => {\n for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]);\n return arr as TRet;\n};\n\n/**\n * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.\n * @param u - Word view to normalize in place.\n * @returns Little-endian normalized word view.\n * @example\n * Normalizes a word-view buffer before block processing.\n *\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg) => TRet = isLE\n ? (u: TArg) => u as TRet\n : byteSwap32;\n\n// Built-in hex conversion:\n// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Formats ciphertext bytes for logs or test vectors.\n *\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - Hexadecimal string to decode.\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On malformed hexadecimal input. {@link RangeError}\n * @example\n * Parses a hex test vector into bytes.\n *\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array as TRet;\n}\n\n// Used in micro\n/**\n * Converts a big-endian hex string into bigint.\n * @param hex - Hexadecimal string without `0x`.\n * @returns Parsed bigint value. The empty string is treated as `0n`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parses a big-endian field element or counter from hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian\n}\n\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\n/**\n * Converts big-endian bytes into bigint.\n * @param bytes - Big-endian bytes.\n * @returns Parsed bigint value. Empty input is treated as `0n`.\n * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}\n * @example\n * Reads a big-endian integer from serialized bytes.\n *\n * ```ts\n * bytesToNumberBE(new Uint8Array([1, 0]));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\n// Used in micro, ff1\n/**\n * Converts a number into big-endian bytes of fixed length.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Big-endian bytes padded to `len`.\n * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,\n * and values that do not fit surface through the downstream hex parser instead of a\n * dedicated range guard here.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the requested output length cannot represent the encoded value. {@link RangeError}\n * @example\n * Encodes a counter as fixed-width big-endian bytes.\n *\n * ```ts\n * numberToBytesBE(1, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet {\n // Reject coercible non-numeric inputs before string/hex conversion changes behavior.\n if (typeof n === 'number') anumber(n);\n else if (typeof n !== 'bigint') throw new TypeError(`number or bigint expected, got ${typeof n}`);\n anumber(len);\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// Global symbols, but ts doesn't see them:\n// {@link https://github.com/microsoft/TypeScript/issues/31535 | TypeScript issue 31535}\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @param str - String to encode.\n * @returns UTF-8 bytes in a detached fresh Uint8Array copy.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encodes application text before encryption or MACing.\n *\n * ```ts\n * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)) as TRet; // {@link https://bugzil.la/1681809 | Firefox bug 1681809}\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @param bytes - UTF-8 bytes.\n * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed\n * UTF-8 is replacement-decoded instead of rejected.\n * @example\n * Decodes UTF-8 plaintext back into a string.\n *\n * ```ts\n * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'\n * ```\n */\nexport function bytesToUtf8(bytes: TArg): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n * @param a - First byte view.\n * @param b - Second byte view.\n * @returns `true` when the views overlap in memory.\n * @example\n * Detects whether two slices alias the same backing buffer.\n *\n * ```ts\n * overlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function overlapBytes(a: TArg, b: TArg): boolean {\n // Zero-length views cannot overwrite anything, even if their offset sits inside another range.\n if (!a.byteLength || !b.byteLength) return false;\n return (\n a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported for most ciphers\n * (except chacha/salsa, which were designed for this)\n * @param input - Input bytes.\n * @param output - Output bytes.\n * @throws If the output view would overwrite unread input bytes. {@link Error}\n * @example\n * Rejects an in-place layout that would overwrite unread input bytes.\n *\n * ```ts\n * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function complexOverlapBytes(input: TArg, output: TArg): void {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - Byte arrays to concatenate.\n * @returns Combined byte array.\n * @throws On wrong argument types inside the byte-array list. {@link TypeError}\n * @example\n * Builds a `nonce || ciphertext` style buffer.\n *\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg): TRet {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res as TRet;\n}\n\n// Used in ARX only\ntype EmptyObj = {};\n/**\n * Merges user options into defaults.\n * @param defaults - Default option values.\n * @param opts - User-provided overrides.\n * @returns Combined options object.\n * The merge mutates `defaults` in place and returns the same object.\n * @throws If options are missing or not an object. {@link Error}\n * @example\n * Applies user overrides to the default cipher options.\n *\n * ```ts\n * checkOpts({ rounds: 20 }, { rounds: 8 });\n * ```\n */\nexport function checkOpts(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/**\n * Compares two byte arrays in kinda constant time once lengths already match.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` when the arrays contain the same bytes. Different lengths still return early.\n * @example\n * Compares an expected authentication tag with the received one.\n *\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg, b: TArg): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// TODO: remove\n/** Incremental hash interface used internally. */\nexport interface IHash2 {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by the final digest. */\n outputLen: number;\n /**\n * Absorbs one more chunk into the hash state.\n * @param buf - Data chunk to hash.\n * @returns The same hash instance for chaining.\n */\n update(buf: string | TArg): this;\n /**\n * Writes the final digest into a caller-provided buffer.\n * @param buf - Destination buffer for the digest bytes.\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg): void;\n /**\n * Finalizes the hash and returns a fresh digest buffer.\n * @returns Digest bytes.\n */\n digest(): TRet;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n destroy(): void;\n}\n\n/**\n * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.\n * @param keyLen - Valid probe-key length used to read static metadata once.\n * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes\n * can pass any representative size as long as those values stay fixed.\n * @param macCons - Keyed MAC constructor or factory.\n * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.\n * @returns Callable MAC helper with `.create()`.\n */\nexport function wrapMacConstructor(\n keyLen: number,\n macCons: TArg<(key: Uint8Array, ...args: A) => H>,\n fromMsg?: TArg<(msg: Uint8Array) => A>\n): TRet> {\n const mac = macCons as (key: TArg, ...args: A) => H;\n const getArgs = (fromMsg || (() => [] as unknown as A)) as (msg: TArg) => A;\n const macC: any = (msg: TArg, key: TArg): TRet =>\n mac(key, ...getArgs(msg))\n .update(msg)\n .digest();\n const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));\n macC.outputLen = tmp.outputLen;\n macC.blockLen = tmp.blockLen;\n macC.create = (key: TArg, ...args: A) => mac(key, ...args);\n return macC as TRet>;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\n\n/** Sync cipher: takes byte array and returns byte array. */\nexport type Cipher = {\n /**\n * Encrypts plaintext bytes.\n * @param plaintext - Data to encrypt.\n * @returns Ciphertext bytes.\n */\n encrypt(plaintext: TArg): TRet;\n /**\n * Decrypts ciphertext bytes.\n * @param ciphertext - Data to decrypt.\n * @returns Plaintext bytes.\n */\n decrypt(ciphertext: TArg): TRet;\n};\n\n/** Async cipher e.g. from built-in WebCrypto. */\nexport type AsyncCipher = {\n /**\n * Encrypts plaintext bytes.\n * @param plaintext - Data to encrypt.\n * @returns Promise resolving to ciphertext bytes.\n */\n encrypt(plaintext: TArg): Promise>;\n /**\n * Decrypts ciphertext bytes.\n * @param ciphertext - Data to decrypt.\n * @returns Promise resolving to plaintext bytes.\n */\n decrypt(ciphertext: TArg): Promise>;\n};\n\n/** Cipher with `output` argument which can optimize by doing 1 less allocation. */\nexport type CipherWithOutput = Cipher & {\n /**\n * Encrypts plaintext bytes into an optional caller-provided buffer.\n * @param plaintext - Data to encrypt.\n * @param output - Optional destination buffer.\n * @returns Ciphertext bytes.\n */\n encrypt(plaintext: TArg, output?: TArg): TRet;\n /**\n * Decrypts ciphertext bytes into an optional caller-provided buffer.\n * @param ciphertext - Data to decrypt.\n * @param output - Optional destination buffer.\n * @returns Plaintext bytes.\n */\n decrypt(ciphertext: TArg, output?: TArg): TRet;\n};\n\n/**\n * Params are outside of return type, so it is accessible before calling constructor.\n * If function support multiple nonceLength's, we return the best one.\n */\nexport type CipherParams = {\n /** Cipher block size in bytes. */\n blockSize: number;\n /** Nonce length in bytes when the cipher uses a fixed nonce size. */\n nonceLength?: number;\n /** Authentication-tag length in bytes for AEAD modes. */\n tagLength?: number;\n /** Whether nonce length is variable at runtime. */\n varSizeNonce?: boolean;\n};\n/**\n * ARX AEAD cipher, like salsa or chacha.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param AAD - Optional associated data.\n * @returns Cipher instance with caller-managed output buffers.\n */\nexport type ARXCipher = ((\n key: TArg,\n nonce: TArg,\n AAD?: TArg\n) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n};\n/**\n * Cipher constructor signature.\n * @param key - Secret key bytes.\n * @param args - Additional constructor arguments, such as nonce or IV.\n * @returns Cipher instance.\n */\nexport type CipherCons = (key: TArg, ...args: T) => Cipher;\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * Used internally by the exported cipher constructors.\n * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`\n * arity (`fn.length === 2`), and tag-bearing constructors are expected to use\n * `args[1]` for optional AAD.\n * @__NO_SIDE_EFFECTS__\n * @param params - Static cipher metadata. See {@link CipherParams}.\n * @param constructor - Cipher constructor.\n * @returns Wrapped constructor with validation.\n */\nexport const wrapCipher = , P extends CipherParams>(\n params: P,\n constructor: C\n): C & P => {\n function wrappedCipher(key: TArg, ...args: any[]): TRet {\n // Validate key\n abytes(key, undefined, 'key');\n\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n }\n\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined) abytes(args[1], undefined, 'AAD');\n\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength: number, output?: TArg) => {\n if (output !== undefined) {\n if (fnLength !== 2) throw new Error('cipher output not supported');\n abytes(output, undefined, 'output');\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data: TArg, output?: TArg) {\n if (called) throw new Error('cannot encrypt() twice with same key + nonce');\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return (cipher as CipherWithOutput).encrypt(data, output);\n },\n decrypt(data: TArg, output?: TArg) {\n abytes(data);\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return (cipher as CipherWithOutput).decrypt(data, output);\n },\n };\n\n return wrCipher as TRet;\n }\n\n Object.assign(wrappedCipher, params);\n return wrappedCipher as C & P;\n};\n\n/**\n * Represents a Salsa or ChaCha xor stream.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Optional starting block counter.\n * @returns Output bytes.\n */\nexport type XorStream = (\n key: TArg,\n nonce: TArg,\n data: TArg,\n output?: TArg,\n counter?: number\n) => TRet;\n\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n * @param expectedLength - Required output length.\n * @param out - Optional destination buffer.\n * @param onlyAligned - Whether `out` must be 4-byte aligned.\n * @returns Output buffer ready for writing.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the provided output buffer has the wrong size or alignment. {@link Error}\n * @example\n * Reuses a caller-provided output buffer when lengths match.\n *\n * ```ts\n * getOutput(16, new Uint8Array(16));\n * ```\n */\nexport function getOutput(\n expectedLength: number,\n out?: TArg,\n onlyAligned = true\n): TRet {\n if (out === undefined) return new Uint8Array(expectedLength) as TRet;\n // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.\n abytes(out, undefined, 'output');\n if (out.length !== expectedLength)\n throw new Error(\n '\"output\" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length\n );\n if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n return out as TRet;\n}\n\n/**\n * Encodes data and AAD bit lengths into a 16-byte buffer.\n * @param dataLength - Data length in bits.\n * @param aadLength - AAD length in bits.\n * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305\n * conventions even though the helper parameter order is `(dataLength, aadLength)`.\n * @param isLE - Whether to encode lengths as little-endian.\n * @returns 16-byte length block.\n * @throws On wrong argument types passed to the endian validator. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Builds the length block appended by GCM and Poly1305.\n *\n * ```ts\n * u64Lengths(16, 8, true);\n * ```\n */\nexport function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet {\n // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.\n anumber(dataLength);\n anumber(aadLength);\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, BigInt(aadLength), isLE);\n view.setBigUint64(8, BigInt(dataLength), isLE);\n return num as TRet;\n}\n\n/**\n * Checks whether a byte array is aligned to a 4-byte offset.\n * @param bytes - Byte array to inspect.\n * @returns `true` when the view is 4-byte aligned.\n * @example\n * Checks whether a buffer can be safely viewed as Uint32Array.\n *\n * ```ts\n * isAligned32(new Uint8Array(4));\n * ```\n */\nexport function isAligned32(bytes: TArg): boolean {\n return bytes.byteOffset % 4 === 0;\n}\n\n/**\n * Copies bytes into a new Uint8Array.\n * @param bytes - Bytes to copy.\n * @returns Copied byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Copies input into an aligned Uint8Array before block processing.\n *\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg): TRet {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet;\n}\n\n/**\n * Cryptographically secure PRNG.\n * Uses internal OS-level `crypto.getRandomValues`.\n * @param bytesLength - Number of bytes to produce.\n * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so\n * non-integers, negative lengths, and oversize requests surface backend/runtime errors.\n * @returns Random byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}\n * @example\n * Generates a fresh nonce or key.\n *\n * ```ts\n * randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet {\n // Validate upfront so fractional / coercible lengths do not silently\n // truncate through Uint8Array().\n anumber(bytesLength);\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength)) as TRet;\n}\n\n/**\n * The pseudorandom number generator doesn't wipe current state:\n * instead, it generates new one based on previous state + entropy.\n * Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes,\n * which is in fact `reseed`, since it changes counter too.\n */\nexport interface PRG {\n /**\n * Mixes fresh entropy into the current generator state.\n * @param seed - Entropy bytes to absorb.\n */\n addEntropy(seed: TArg): void;\n /**\n * Produces a requested number of pseudorandom bytes.\n * @param bytesLength - Number of bytes to generate.\n * @returns Random byte array.\n */\n randomBytes(bytesLength: number): TRet;\n /** Destroys the generator state. */\n clean(): void;\n}\n\n/** Removes the nonce argument from a cipher constructor type. */\nexport type RemoveNonce any> = T extends (\n arg0: any,\n arg1: any,\n ...rest: infer R\n) => infer Ret\n ? (key: TArg, ...args: R) => Ret\n : never;\n/**\n * Cipher constructor that requires a nonce argument.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param args - Additional cipher-specific arguments.\n * @returns Cipher instance.\n */\nexport type CipherWithNonce = ((\n key: TArg,\n nonce: TArg,\n ...args: any[]\n) => Cipher | AsyncCipher) & {\n nonceLength: number;\n};\n\n/**\n * Uses CSPRNG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`\n * buffer on encrypt and intentionally does not support caller-provided destination buffers.\n * Too-short decrypt inputs are split into short/empty nonce views and then delegated\n * to the wrapped cipher instead of being rejected here first.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of\n * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to\n * `2**-33`, still negligible but creeping up.\n * @param fn - Cipher constructor that expects a nonce.\n * @param randomBytes_ - Random-byte source used for nonce generation.\n * @returns Cipher constructor that prepends the nonce to ciphertext.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}\n * @example\n * Prepends a fresh random nonce to every ciphertext.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';\n * const wrapped = managedNonce(gcm);\n * const key = randomBytes(16);\n * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));\n * wrapped(key).decrypt(ciphertext);\n * ```\n */\nexport function managedNonce(\n fn: T,\n randomBytes_: typeof randomBytes = randomBytes\n): TRet> {\n const { nonceLength } = fn;\n anumber(nonceLength);\n const addNonce = (\n nonce: TArg,\n ciphertext: TArg,\n plaintext: TArg\n ) => {\n const out = concatBytes(nonce, ciphertext);\n // Wrapped ciphers may alias caller plaintext on encrypt(); never zero\n // caller-owned buffers here.\n if (!overlapBytes(plaintext, ciphertext)) ciphertext.fill(0);\n return out;\n };\n // NOTE: we cannot support DST here, it would be mistake:\n // - we don't know how much dst length cipher requires\n // - nonce may unalign dst and break everything\n // - we create new u8a anyway (concatBytes)\n // - previously we passed all args to cipher, but that was mistake!\n const res = ((key: TArg, ...args: any[]): any => ({\n encrypt(plaintext: TArg) {\n abytes(plaintext);\n const nonce = randomBytes_(nonceLength);\n const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n // @ts-ignore\n if (encrypted instanceof Promise)\n return encrypted.then((ct) => addNonce(nonce, ct, plaintext));\n return addNonce(nonce, encrypted, plaintext);\n },\n decrypt(ciphertext: TArg) {\n abytes(ciphertext);\n const nonce = ciphertext.subarray(0, nonceLength);\n const decrypted = ciphertext.subarray(nonceLength);\n return fn(key, nonce, ...args).decrypt(decrypted);\n },\n })) as RemoveNonce & { blockSize?: number; tagLength?: number };\n // Auto-nonce wrappers still preserve the wrapped payload geometry.\n if ('blockSize' in fn) res.blockSize = (fn as any).blockSize;\n if ('tagLength' in fn) res.tagLength = (fn as any).tagLength;\n return res as TRet>;\n}\n\n/** `Uint8Array.of()` return type helper for TS 5.9. */\nexport type Uint8ArrayBuffer = TRet;\n", "/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).\nCounter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.\nCurrent noble policy is strict non-wrap for the shared 32-bit counter path:\nexported ARX ciphers reject initial `0xffffffff` and stop before any implicit\nwrap back to zero.\nSee {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.\n\n * @module\n */\nimport {\n type PRG,\n type TArg,\n type TRet,\n type XorStream,\n abool,\n abytes,\n anumber,\n checkOpts,\n clean,\n copyBytes,\n getOutput,\n isAligned32,\n isLE,\n randomBytes,\n swap32IfBE,\n u32,\n} from './utils.ts';\n\n// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.\n// Non-ASCII input would not match UTF-8 `TextEncoder` output.\nconst encodeStr = (str: string) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));\n// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.\n// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.\n// RFC 8439 \u00A72.3 / RFC 7539 \u00A72.3 only define the 256-bit-key constants; this 16-byte sigma is\n// kept for legacy allowShortKeys Salsa/ChaCha variants.\nconst sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();\n// RFC 8439 \u00A72.3 / RFC 7539 \u00A72.3 define words 0-3 as\n// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.\nconst sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();\n\n/**\n * Rotates a 32-bit word left.\n * @param a - Input word.\n * @param b - Rotation count in bits.\n * @returns Rotated 32-bit word.\n * @example\n * Moves the top byte of `0x12345678` into the low byte position.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(a: number, b: number): number {\n return (a << b) | (a >>> (32 - b));\n}\n\n/**\n * ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.\n * @param sigma - Sigma constants for the selected cipher layout.\n * @param key - Expanded key words.\n * @param nonce - Nonce and counter words prepared for the round function.\n * @param output - Output block written in place.\n * @param counter - Block counter value.\n * @param rounds - Optional round count override.\n */\nexport type CipherCoreFn = (\n sigma: TArg,\n key: TArg,\n nonce: TArg,\n output: TArg,\n counter: number,\n rounds?: number\n) => void;\n\n/**\n * Nonce-extension function used by XChaCha and XSalsa.\n * @param sigma - Sigma constants for the selected cipher layout.\n * @param key - Expanded key words.\n * @param input - Input nonce words used for subkey derivation.\n * @param output - Output buffer written with the derived nonce words.\n */\nexport type ExtendNonceFn = (\n sigma: TArg,\n key: TArg,\n input: TArg,\n output: TArg\n) => void;\n\n/** ARX cipher options.\n * * `allowShortKeys` for 16-byte keys\n * * `counterLength` in bytes\n * * `counterRight`: right: `nonce|counter`; left: `counter|nonce`\n * */\nexport type CipherOpts = {\n /** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */\n allowShortKeys?: boolean;\n /** Optional nonce-expansion hook used by extended-nonce variants. */\n extendNonceFn?: ExtendNonceFn;\n /** Counter length in bytes inside the nonce/counter layout. */\n counterLength?: number;\n /** Whether the layout is `nonce|counter` instead of `counter|nonce`. */\n counterRight?: boolean;\n /** Number of core rounds to execute. */\n rounds?: number;\n};\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\n// RFC 8439 \u00A72.2 / RFC 7539 \u00A72.2: the ChaCha state has 16 32-bit words.\nconst BLOCK_LEN32 = 16;\n\n// Counter policy for the shared public `counter` argument:\n// - RFC/IETF ChaCha20 uses a 32-bit counter.\n// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit\n// counter state and carry into the next word.\n// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium\n// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max\n// boundary instead of carrying.\n// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from\n// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.\n// Noble intentionally throws instead of silently picking one wrap model for users. In the default\n// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically\n// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement\n// whatever wider carry / wrap policy they need on top.\nconst MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();\nconst U32_EMPTY = /* @__PURE__ */ Uint32Array.of();\nfunction runCipher(\n core: TArg,\n sigma: TArg,\n key: TArg,\n nonce: TArg,\n data: TArg,\n output: TArg,\n counter: number,\n rounds: number\n): void {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isLE && isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n // RFC 8439 \u00A72.4.1 / RFC 7539 \u00A72.4.1 allow XORing one keystream block at a time and\n // truncating the final partial block instead of materializing the whole keystream.\n if (!isLE) {\n for (let pos = 0; pos < len; counter++) {\n core(\n sigma as TRet,\n key as TRet,\n nonce as TRet,\n b32,\n counter,\n rounds\n );\n // RFC 8439 \u00A72.4 / RFC 7539 \u00A72.4 serialize keystream words in little-endian order.\n swap32IfBE(b32);\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n return;\n }\n for (let pos = 0; pos < len; counter++) {\n core(\n sigma as TRet,\n key as TRet,\n nonce as TRet,\n b32,\n counter,\n rounds\n );\n // See MAX_COUNTER policy note above: never silently wrap the shared public counter.\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n\n/**\n * Creates an ARX stream cipher from a 32-bit core permutation.\n * Used internally to build the exported Salsa and ChaCha stream ciphers.\n * @param core - Core function that fills one keystream block.\n * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.\n * @returns Stream cipher function over byte arrays.\n * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}\n */\nexport function createCipher(core: TArg, opts: TArg): TRet {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n opts\n );\n if (typeof core !== 'function') throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (\n key: TArg,\n nonce: TArg,\n data: TArg,\n output?: TArg,\n counter = 0\n ): TRet => {\n abytes(key, undefined, 'key');\n abytes(nonce, undefined, 'nonce');\n abytes(data, undefined, 'data');\n const len = data.length;\n // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs\n // must match the logical result length exactly instead of returning an oversized workspace.\n output = getOutput(len, output, false);\n anumber(counter);\n // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.\n if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const toClean = [];\n\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length;\n let k: Uint8Array;\n let sigma: Uint32Array;\n if (l === 32) {\n // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and\n // final clean(...) all mutate or wipe the temporary buffer in place.\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n } else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n } else {\n abytes(key, 32, 'arx key');\n throw new Error('invalid key size');\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n }\n\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later\n // swap32IfBE(...) never mutates caller nonce bytes in place.\n if (!isLE || !isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));\n\n let k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n const n16 = nonce.subarray(0, 16);\n if (isLE) extendNonceFn(sigma as TRet, k32, u32(n16), k32);\n else {\n const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));\n extendNonceFn(sigmaRaw, k32, u32(n16), k32);\n clean(sigmaRaw);\n swap32IfBE(k32);\n }\n nonce = nonce.subarray(16);\n } else if (!isLE) swap32IfBE(k32);\n\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero\n // counter bytes, while Salsa/XSalsa append them after the nonce words.\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = swap32IfBE(u32(nonce));\n // Ensure temporary key/nonce copies are wiped even if the remaining\n // runtime guard in runCipher(...) throws on counter overflow.\n try {\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n return output as TRet;\n } finally {\n clean(...toClean);\n }\n };\n}\n\n/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */\nexport class _XorStreamPRG implements PRG {\n readonly blockLen: number;\n readonly keyLen: number;\n readonly nonceLen: number;\n private state: TRet;\n private buf: TRet;\n private key: TRet;\n private nonce: TRet;\n private pos: number;\n private ctr: number;\n private cipher: TArg;\n constructor(\n cipher: TArg,\n blockLen: number,\n keyLen: number,\n nonceLen: number,\n seed: TArg\n ) {\n this.cipher = cipher;\n this.blockLen = blockLen;\n this.keyLen = keyLen;\n this.nonceLen = nonceLen;\n this.state = new Uint8Array(this.keyLen + this.nonceLen) as TRet;\n this.reseed(seed);\n this.ctr = 0;\n this.pos = this.blockLen;\n this.buf = new Uint8Array(this.blockLen) as TRet;\n // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher\n // inputs in place through these subarray views.\n this.key = this.state.subarray(0, this.keyLen) as TRet;\n this.nonce = this.state.subarray(this.keyLen) as TRet;\n }\n private reseed(seed: TArg) {\n abytes(seed);\n if (!seed || seed.length === 0) throw new Error('entropy required');\n // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the\n // keystream so buffered leftovers from the previous state are never reused.\n for (let i = 0; i < seed.length; i++) this.state[i % this.state.length] ^= seed[i];\n this.ctr = 0;\n this.pos = this.blockLen;\n }\n addEntropy(seed: TArg): void {\n // Reject empty entropy before re-keying, otherwise a throwing call would still advance state.\n abytes(seed);\n if (seed.length === 0) throw new Error('entropy required');\n // Re-key from the current stream first, then mix external entropy into the fresh key||nonce\n // state through reseed() so stale buffered bytes are discarded.\n this.state.set(this.randomBytes(this.state.length));\n this.reseed(seed);\n }\n randomBytes(len: number): TRet {\n anumber(len);\n if (len === 0) return new Uint8Array(0) as TRet;\n const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;\n const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);\n // Preflight overflow so failed reads don't partially consume keystream\n // and leave the PRG repeating blocks.\n if (blocks > 0 && this.ctr > MAX_COUNTER - blocks) throw new Error('arx: counter overflow');\n const out = new Uint8Array(len);\n let outPos = 0;\n // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream\n // ciphers then emit raw keystream bytes directly into those buffers.\n // Serve buffered leftovers first so split reads stay identical to one larger read.\n if (this.pos < this.blockLen) {\n const take = Math.min(len, this.blockLen - this.pos);\n out.set(this.buf.subarray(this.pos, this.pos + take), 0);\n this.pos += take;\n outPos += take;\n if (outPos === len) return out as TRet; // fast path\n }\n // Full blocks directly to out\n const full = Math.floor((len - outPos) / this.blockLen);\n if (full > 0) {\n const blockBytes = full * this.blockLen;\n const b = out.subarray(outPos, outPos + blockBytes);\n this.cipher(this.key, this.nonce, b as TRet, b as TRet, this.ctr);\n this.ctr += full;\n outPos += blockBytes;\n }\n // Save leftovers\n const left = len - outPos;\n if (left > 0) {\n this.buf.fill(0);\n // NOTE: cipher will handle overflow\n this.cipher(\n this.key,\n this.nonce,\n this.buf as TRet,\n this.buf as TRet,\n this.ctr++\n );\n out.set(this.buf.subarray(0, left), outPos);\n this.pos = left;\n }\n return out as TRet;\n }\n // Clone seeds the new instance from this stream, so the source PRG advances too.\n clone(): _XorStreamPRG {\n return new _XorStreamPRG(\n this.cipher,\n this.blockLen,\n this.keyLen,\n this.nonceLen,\n this.randomBytes(this.state.length)\n );\n }\n // Zeroes the current state and leftover buffer, but does not make the instance unusable:\n // Later reads first drain zeros from the cleared buffer and then continue\n // from zero key||nonce state.\n clean(): void {\n this.pos = 0;\n this.ctr = 0;\n this.buf.fill(0);\n this.state.fill(0);\n }\n}\n\n/**\n * PRG constructor backed by an ARX stream cipher.\n * @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32\n * random bytes are mixed in by default: larger states keep a zero tail, while smaller states\n * wrap those bytes through `reseed()`'s XOR schedule.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n */\nexport type XorPRG = (seed?: TArg) => TRet<_XorStreamPRG>;\n\n/**\n * Creates a PRG constructor from a stream cipher.\n * @param cipher - Stream cipher used to fill output blocks.\n * @param blockLen - Keystream block length in bytes.\n * @param keyLen - Internal key length in bytes.\n * @param nonceLen - Internal nonce length in bytes.\n * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.\n * @example\n * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { createPRG } from '@noble/ciphers/_arx.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const init = createPRG(xchacha20, 64, 32, 24);\n * const prg = init(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const createPRG = (\n cipher: TArg,\n blockLen: number,\n keyLen: number,\n nonceLen: number\n): TRet => {\n return ((seed: TArg = randomBytes(32)): TRet<_XorStreamPRG> =>\n new _XorStreamPRG(\n cipher,\n blockLen,\n keyLen,\n nonceLen,\n seed\n ) as TRet<_XorStreamPRG>) as TRet;\n};\n", "/**\n * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out the {@link https://cr.yp.to/mac.html | original website}.\n * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.\n * @module\n */\n// prettier-ignore\nimport {\n abytes, aexists, aoutput, bytesToHex,\n clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE,\n wrapMacConstructor, type CMac, type IHash2, type TArg, type TRet\n} from './utils.ts';\n\n// Little-endian 2-byte load used by the Poly1305 limb decomposition.\nfunction u8to16(a: TArg, i: number) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n\nfunction bytesToNumberLE(bytes: TArg): bigint {\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\n/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */\nfunction poly1305_small(msg: TArg, key: TArg): TRet {\n abytes(msg);\n abytes(key, 32, 'key');\n const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5\n const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1\n const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');\n const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;\n const s = bytesToNumberLE(key.subarray(16));\n // Process by 16 byte chunks\n let acc = BigInt(0);\n for (let i = 0; i < msg.length; i += 16) {\n const m = msg.subarray(i, i + 16);\n // RFC 8439 \u00A72.5.1 / RFC 7539 \u00A72.5.1 append [0x01] to each chunk before multiplying by r.\n const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));\n acc = ((acc + n) * r) % POW_2_130_5;\n }\n const res = (acc + s) & POW_2_128_1;\n // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5 serialize the low 128 bits in little-endian order.\n return numberToBytesBE(res, 16).reverse() as TRet; // LE\n}\n\n// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.\n// @ts-expect-error\nfunction poly1305_computeTag_small(\n authKey: TArg,\n // AEAD trailer must already be the 16-byte length block:\n // 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.\n lengths: TArg,\n ciphertext: TArg,\n AAD?: TArg\n): TRet {\n // RFC 8439 \u00A72.8.1 / RFC 7539 \u00A72.8.1 MAC input is\n // AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.\n const res = [];\n const updatePadded2 = (msg: TArg) => {\n res.push(msg);\n const leftover = msg.length % 16;\n // RFC 8439 \u00A72.8.1 / RFC 7539 \u00A72.8.1: pad16(x) is empty for aligned\n // inputs, else 16-(len%16) zero bytes.\n if (leftover) res.push(new Uint8Array(16).slice(leftover));\n };\n if (AAD) updatePadded2(AAD);\n updatePadded2(ciphertext);\n res.push(lengths);\n return poly1305_small(concatBytes(...res), authKey);\n}\n\n/**\n * Incremental Poly1305 MAC state.\n * Prefer `poly1305()` for one-shot use.\n * @param key - 32-byte Poly1305 one-time key.\n * @example\n * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.\n *\n * ```ts\n * import { Poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const mac = new Poly1305(key);\n * mac.update(new Uint8Array([1, 2, 3]));\n * mac.digest();\n * ```\n */\nexport class Poly1305 implements IHash2 {\n readonly blockLen = 16;\n readonly outputLen = 16;\n private buffer = new Uint8Array(16);\n private r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3\n private h = new Uint16Array(10);\n private pad = new Uint16Array(8);\n private pos = 0;\n protected finished = false;\n protected destroyed = false;\n\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key: TArg) {\n key = copyBytes(abytes(key, 32, 'key'));\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n\n // RFC 8439 \u00A72.5.1 / RFC 7539 \u00A72.5.1 clamp r before multiplication.\n // These masks unpack that clamped value into 13-bit limbs, while pad\n // keeps the raw s half for finalize().\n // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n\n private process(data: TArg, offset: number, isLast = false) {\n // RFC 8439 \u00A72.5 / \u00A72.5.1 and RFC 7539 \u00A72.5 / \u00A72.5.1 add an extra high\n // bit to every full 16-byte block. The final partial block gets its\n // explicit `1` byte during digestInto(), so `hibit` stays zero there.\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n let c = 0;\n\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n\n private finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n\n // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5 reduce modulo 2^130-5 before repacking\n // to 16-bit words and adding the raw s half.\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data: TArg): this {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { buffer, blockLen } = this;\n const len = data.length;\n\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy(): void {\n // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.\n this.destroyed = true;\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out: TArg): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5: the final short block appends a\n // single `0x01` byte and zero-fills the remaining bytes before the\n // last multiplication step.\n buffer[pos++] = 1;\n for (; pos < 16; pos++) buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n }\n digest(): TRet {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy out before destroy() zeroes the internal buffer.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet;\n }\n}\n\n/** One-shot keyed hash helper with `.create()`. */\nexport type CHash = CMac;\n\n/**\n * Poly1305 MAC from RFC 8439.\n * @param msg - Message bytes to authenticate.\n * @param key - 32-byte Poly1305 one-time key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates one message with a one-shot Poly1305 call and a fresh key.\n *\n * ```ts\n * import { poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * poly1305(new Uint8Array(), key);\n * ```\n */\nexport const poly1305: TRet = /* @__PURE__ */ wrapMacConstructor(\n 32,\n (key: TArg) => new Poly1305(key)\n);\n", "/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and\n * is now used in TLS 1.3.\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out\n * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and\n * {@link https://cr.yp.to/chacha.html | website}.\n *\n * @module\n */\nimport { type XorPRG, createCipher, createPRG, rotl } from './_arx.ts';\nimport { poly1305 } from './_poly1305.ts';\nimport {\n type ARXCipher,\n type CipherWithOutput,\n type TArg,\n type TRet,\n type XorStream,\n abytes,\n clean,\n equalBytes,\n getOutput,\n swap8IfBE,\n swap32IfBE,\n u64Lengths,\n wrapCipher,\n} from './utils.ts';\n\n/**\n * ChaCha core function. It is implemented twice:\n * 1. Simple loop (chachaCore_small, hchacha_small)\n * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read\n * The specific implementation is selected in `createCipher` below.\n */\n\n/** RFC 8439 \u00A72.1 quarter round on words a, b, c, d. */\n// prettier-ignore\nfunction chachaQR(x: TArg, a: number, b: number, c: number, d: number) {\n x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 16);\n x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 12);\n x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 8);\n x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 7);\n}\n\n/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */\nfunction chachaRound(x: TArg, rounds = 20) {\n for (let r = 0; r < rounds; r += 2) {\n // RFC 8439 \u00A72.3 / \u00A72.3.1 inner_block: four column rounds, then four diagonal rounds.\n chachaQR(x, 0, 4, 8, 12);\n chachaQR(x, 1, 5, 9, 13);\n chachaQR(x, 2, 6, 10, 14);\n chachaQR(x, 3, 7, 11, 15);\n chachaQR(x, 0, 5, 10, 15);\n chachaQR(x, 1, 6, 11, 12);\n chachaQR(x, 2, 7, 8, 13);\n chachaQR(x, 3, 4, 9, 14);\n }\n}\n\n// Shared scratch for the auditability-only helper below; only the test-only\n// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.\nconst ctmp = /* @__PURE__ */ new Uint32Array(16);\n\n/** Small version of chacha without loop unrolling. Unused, provided for auditability. */\n// prettier-ignore\nfunction chacha(\n s: TArg, k: TArg, i: TArg, out: TArg,\n isHChacha: boolean = true, rounds: number = 20\n): void {\n // `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block\n // function or the full 128-bit nonce prefix for the HChaCha subkey path.\n // Create initial array using common pattern\n const y = Uint32Array.from([\n s[0], s[1], s[2], s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n k[0], k[1], k[2], k[3], // Key Key Key Key\n k[4], k[5], k[6], k[7], // Key Key Key Key\n i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce\n ]);\n const x = ctmp;\n x.set(y);\n chachaRound(x, rounds);\n\n // HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha\n // block path adds the original state word-by-word.\n if (isHChacha) {\n const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];\n for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];\n } else {\n for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;\n }\n}\n\n/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */\n// @ts-ignore\nconst chachaCore_small: typeof chachaCore = (s, k, n, out, cnt, rounds) =>\n // Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().\n chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);\n/** Identical to `hchacha`. Unused. */\n// @ts-ignore\nconst hchacha_small: typeof hchacha = chacha;\n\n/** RFC 8439 \u00A72.3 block core for `state = constants | key | counter | nonce`. */\n// prettier-ignore\nfunction chachaCore(\n s: TArg, k: TArg, n: TArg, out: TArg, cnt: number, rounds = 20\n): void {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // RFC 8439 \u00A72.3 / \u00A72.3.1: add the original state words back in state order.\n let oi = 0;\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha hashes key and nonce into key' and nonce' for xchacha20.\n * Algorithmically identical to `hchacha_small`, but this exported path\n * normalizes word order on big-endian hosts.\n * Need to find a way to merge it with `chachaCore` without 25% performance hit.\n * @param s - Sigma constants as 32-bit words.\n * @param k - Key words.\n * @param i - Nonce-prefix words.\n * @param out - Output buffer for the derived subkey.\n * @example\n * Derives the XChaCha subkey from sigma, key, and nonce-prefix words.\n *\n * ```ts\n * const sigma = new Uint32Array(4);\n * const key = new Uint32Array(8);\n * const nonce = new Uint32Array(4);\n * const out = new Uint32Array(8);\n * hchacha(sigma, key, nonce, out);\n * ```\n */\n// prettier-ignore\nexport function hchacha(\n s: TArg, k: TArg, i: TArg, out: TArg\n): void {\n let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]),\n x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]),\n x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]),\n x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.\n let oi = 0;\n out[oi++] = x00; out[oi++] = x01;\n out[oi++] = x02; out[oi++] = x03;\n out[oi++] = x12; out[oi++] = x13;\n out[oi++] = x14; out[oi++] = x15;\n swap32IfBE(out);\n}\n\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 16-byte or 32-byte key.\n * @param nonce - 8-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20orig } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(8);\n * chacha20orig(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20orig: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 32-byte key.\n * @param nonce - 24-byte extended nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * xchacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const xchacha20: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha8(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha8: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha12 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha12(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha12: TRet = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n\n// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.\nexport const __TESTS: {\n chachaCore_small: typeof chachaCore_small;\n chachaCore: typeof chachaCore;\n} = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });\n\n// RFC 8439 \u00A72.8.1 pad16(x): shared zero block for AAD/ciphertext padding.\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// RFC 8439 \u00A72.8 / \u00A72.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.\nconst updatePadded = (h: ReturnType, msg: TArg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover) h.update(ZEROS16.subarray(leftover));\n};\n\n// RFC 8439 \u00A72.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key\n// generation only needs 32 zero bytes.\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n fn: TArg,\n key: TArg,\n nonce: TArg,\n ciphertext: TArg,\n AAD?: TArg\n): TRet {\n if (AAD !== undefined) abytes(AAD, undefined, 'AAD');\n // RFC 8439 \u00A72.6 / \u00A72.8: derive the Poly1305 one-time key from counter 0,\n // then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).\n const authKey = fn(\n key as TRet,\n nonce as TRet,\n ZEROS32 as TRet\n );\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n\n // Methods below can be replaced with\n // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)\n const h = poly1305.create(authKey);\n if (AAD) updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n (xorStream: TArg) =>\n (key: TArg, nonce: TArg, AAD?: TArg): CipherWithOutput => {\n // This borrows caller key/nonce/AAD buffers by reference; mutating them after construction\n // changes future encrypt/decrypt results.\n const tagLength = 16;\n return {\n encrypt(plaintext: TArg, output?: TArg): TRet {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // RFC 8439 \u00A72.8: payload encryption starts at counter 1 because counter 0 produced the OTK.\n xorStream(\n key as TRet,\n nonce as TRet,\n oPlain as TRet,\n oPlain as TRet,\n 1\n );\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output as TRet;\n },\n decrypt(ciphertext: TArg, output?: TArg): TRet {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n // RFC 8439 \u00A72.8 / \u00A74: authenticate ciphertext before decrypting it, and compare tags with\n // the constant-time equalBytes() helper rather than decrypting speculative plaintext first.\n if (!equalBytes(passedTag, tag)) {\n clean(tag);\n throw new Error('invalid tag');\n }\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(\n key as TRet,\n nonce as TRet,\n output as TRet,\n output as TRet,\n 1\n ); // start stream with i=1\n clean(tag);\n return output as TRet;\n },\n };\n };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce.\n *\n * ```ts\n * import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * const cipher = chacha20poly1305(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const chacha20poly1305: TRet = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 12, tagLength: 16 },\n /* @__PURE__ */ _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n *\n * Can be safely used with random nonces (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * @param key - 32-byte key.\n * @param nonce - 24-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * const cipher = xchacha20poly1305(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const xchacha20poly1305: TRet = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 24, tagLength: 16 },\n /* @__PURE__ */ _poly1305_aead(xchacha20)\n);\n\n/**\n * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 40-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the test-only ChaCha20 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha20(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha20: TRet = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);\n/**\n * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Faster than `rngChacha20`.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 44-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the faster test-only ChaCha8 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha8(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha8: TRet = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);\n", "import { constantTimeEqual } from \"./buffer.mjs\";\nimport { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT } from \"./jwt.mjs\";\nimport { hashPassword, verifyPassword } from \"./password.mjs\";\nimport { generateRandomString } from \"./random.mjs\";\nimport { createHash } from \"@better-auth/utils/hash\";\nimport { getWebcryptoSubtle } from \"@better-auth/utils\";\nimport { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { bytesToHex, hexToBytes, managedNonce, utf8ToBytes } from \"@noble/ciphers/utils.js\";\n//#region src/crypto/index.ts\nconst algorithm = {\n\tname: \"HMAC\",\n\thash: \"SHA-256\"\n};\nconst ENVELOPE_PREFIX = \"$ba$\";\nfunction parseEnvelope(data) {\n\tif (!data.startsWith(ENVELOPE_PREFIX)) return null;\n\tconst firstSep = 4;\n\tconst secondSep = data.indexOf(\"$\", firstSep);\n\tif (secondSep === -1) return null;\n\tconst version = parseInt(data.slice(firstSep, secondSep), 10);\n\tif (!Number.isInteger(version) || version < 0) return null;\n\treturn {\n\t\tversion,\n\t\tciphertext: data.slice(secondSep + 1)\n\t};\n}\nfunction formatEnvelope(version, ciphertext) {\n\treturn `${ENVELOPE_PREFIX}${version}$${ciphertext}`;\n}\nasync function rawEncrypt(secret, data) {\n\tconst keyAsBytes = await createHash(\"SHA-256\").digest(secret);\n\tconst dataAsBytes = utf8ToBytes(data);\n\treturn bytesToHex(managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)).encrypt(dataAsBytes));\n}\nasync function rawDecrypt(secret, hex) {\n\tconst keyAsBytes = await createHash(\"SHA-256\").digest(secret);\n\tconst dataAsBytes = hexToBytes(hex);\n\tconst chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes));\n\treturn new TextDecoder().decode(chacha.decrypt(dataAsBytes));\n}\nconst symmetricEncrypt = async ({ key, data }) => {\n\tif (typeof key === \"string\") return rawEncrypt(key, data);\n\tconst secret = key.keys.get(key.currentVersion);\n\tif (!secret) throw new Error(`Secret version ${key.currentVersion} not found in keys`);\n\tconst ciphertext = await rawEncrypt(secret, data);\n\treturn formatEnvelope(key.currentVersion, ciphertext);\n};\nconst symmetricDecrypt = async ({ key, data }) => {\n\tif (typeof key === \"string\") return rawDecrypt(key, data);\n\tconst envelope = parseEnvelope(data);\n\tif (envelope) {\n\t\tconst secret = key.keys.get(envelope.version);\n\t\tif (!secret) throw new Error(`Secret version ${envelope.version} not found in keys (key may have been retired)`);\n\t\treturn rawDecrypt(secret, envelope.ciphertext);\n\t}\n\tif (key.legacySecret) return rawDecrypt(key.legacySecret, data);\n\tthrow new Error(\"Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.\");\n};\nconst getCryptoKey = async (secret) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await getWebcryptoSubtle().importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\nconst makeSignature = async (value, secret) => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value));\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n//#endregion\nexport { constantTimeEqual, formatEnvelope, generateRandomString, getCryptoKey, hashPassword, makeSignature, parseEnvelope, signJWT, symmetricDecodeJWT, symmetricDecrypt, symmetricEncodeJWT, symmetricEncrypt, verifyJWT, verifyPassword };\n", "//#region src/utils/date.ts\nconst getDate = (span, unit = \"ms\") => {\n\treturn new Date(Date.now() + (unit === \"sec\" ? span * 1e3 : span));\n};\n//#endregion\nexport { getDate };\n", "import { getAuthTables } from \"./get-tables.mjs\";\nimport { coreSchema } from \"./schema/shared.mjs\";\nimport { accountSchema } from \"./schema/account.mjs\";\nimport { rateLimitSchema } from \"./schema/rate-limit.mjs\";\nimport { sessionSchema } from \"./schema/session.mjs\";\nimport { userSchema } from \"./schema/user.mjs\";\nimport { verificationSchema } from \"./schema/verification.mjs\";\nexport { accountSchema, coreSchema, getAuthTables, rateLimitSchema, sessionSchema, userSchema, verificationSchema };\n", "import { getAuthTables } from \"@better-auth/core/db\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { filterOutputFields } from \"@better-auth/core/utils/db\";\n//#region src/db/schema.ts\nconst cache = /* @__PURE__ */ new WeakMap();\nfunction getFields(options, modelName, mode) {\n\tconst cacheKey = `${modelName}:${mode}`;\n\tif (!cache.has(options)) cache.set(options, /* @__PURE__ */ new Map());\n\tconst tableCache = cache.get(options);\n\tif (tableCache.has(cacheKey)) return tableCache.get(cacheKey);\n\tconst coreSchema = mode === \"output\" ? getAuthTables(options)[modelName]?.fields ?? {} : {};\n\tconst additionalFields = modelName === \"user\" || modelName === \"session\" || modelName === \"account\" ? options[modelName]?.additionalFields : void 0;\n\tlet schema = {\n\t\t...coreSchema,\n\t\t...additionalFields ?? {}\n\t};\n\tfor (const plugin of options.plugins || []) if (plugin.schema && plugin.schema[modelName]) schema = {\n\t\t...schema,\n\t\t...plugin.schema[modelName].fields\n\t};\n\ttableCache.set(cacheKey, schema);\n\treturn schema;\n}\nfunction parseUserOutput(options, user) {\n\treturn filterOutputFields(user, getFields(options, \"user\", \"output\"));\n}\nfunction parseSessionOutput(options, session) {\n\treturn filterOutputFields(session, getFields(options, \"session\", \"output\"));\n}\nfunction parseAccountOutput(options, account) {\n\tconst { accessToken: _accessToken, refreshToken: _refreshToken, idToken: _idToken, accessTokenExpiresAt: _accessTokenExpiresAt, refreshTokenExpiresAt: _refreshTokenExpiresAt, password: _password, ...rest } = filterOutputFields(account, getFields(options, \"account\", \"output\"));\n\treturn rest;\n}\nfunction parseInputData(data, schema) {\n\tconst action = schema.action || \"create\";\n\tconst fields = schema.fields;\n\tconst parsedData = Object.create(null);\n\tfor (const key in fields) {\n\t\tif (key in data) {\n\t\t\tif (fields[key].input === false) {\n\t\t\t\tif (fields[key].defaultValue !== void 0) {\n\t\t\t\t\tif (action !== \"update\") {\n\t\t\t\t\t\tparsedData[key] = fields[key].defaultValue;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (data[key]) throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t...BASE_ERROR_CODES.FIELD_NOT_ALLOWED,\n\t\t\t\t\tmessage: `${key} is not allowed to be set`\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (fields[key].validator?.input && data[key] !== void 0) {\n\t\t\t\tconst result = fields[key].validator.input[\"~standard\"].validate(data[key]);\n\t\t\t\tif (result instanceof Promise) throw APIError.from(\"INTERNAL_SERVER_ERROR\", BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED);\n\t\t\t\tif (\"issues\" in result && result.issues) throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t...BASE_ERROR_CODES.VALIDATION_ERROR,\n\t\t\t\t\tmessage: result.issues[0]?.message || \"Validation Error\"\n\t\t\t\t});\n\t\t\t\tparsedData[key] = result.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (fields[key].transform?.input && data[key] !== void 0) {\n\t\t\t\tparsedData[key] = fields[key].transform?.input(data[key]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparsedData[key] = data[key];\n\t\t\tcontinue;\n\t\t}\n\t\tif (fields[key].defaultValue !== void 0 && action === \"create\") {\n\t\t\tif (typeof fields[key].defaultValue === \"function\") {\n\t\t\t\tparsedData[key] = fields[key].defaultValue();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparsedData[key] = fields[key].defaultValue;\n\t\t\tcontinue;\n\t\t}\n\t\tif (fields[key].required && action === \"create\") throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t...BASE_ERROR_CODES.MISSING_FIELD,\n\t\t\tmessage: `${key} is required`\n\t\t});\n\t}\n\treturn parsedData;\n}\nfunction parseUserInput(options, user = {}, action) {\n\treturn parseInputData(user, {\n\t\tfields: getFields(options, \"user\", \"input\"),\n\t\taction\n\t});\n}\nfunction parseAdditionalUserInput(options, user) {\n\tconst schema = getFields(options, \"user\", \"input\");\n\treturn parseInputData(user || {}, { fields: schema });\n}\nfunction parseAccountInput(options, account) {\n\treturn parseInputData(account, { fields: getFields(options, \"account\", \"input\") });\n}\nfunction parseSessionInput(options, session, action) {\n\treturn parseInputData(session, {\n\t\tfields: getFields(options, \"session\", \"input\"),\n\t\taction\n\t});\n}\nfunction getSessionDefaultFields(options) {\n\tconst fields = getFields(options, \"session\", \"input\");\n\tconst defaults = {};\n\tfor (const key in fields) if (fields[key].defaultValue !== void 0) defaults[key] = typeof fields[key].defaultValue === \"function\" ? fields[key].defaultValue() : fields[key].defaultValue;\n\treturn defaults;\n}\nfunction mergeSchema(schema, newSchema) {\n\tif (!newSchema) return schema;\n\tfor (const table in newSchema) {\n\t\tconst newModelName = newSchema[table]?.modelName;\n\t\tif (newModelName) schema[table].modelName = newModelName;\n\t\tfor (const field in schema[table].fields) {\n\t\t\tconst newField = newSchema[table]?.fields?.[field];\n\t\t\tif (!newField) continue;\n\t\t\tschema[table].fields[field].fieldName = newField;\n\t\t}\n\t}\n\treturn schema;\n}\n//#endregion\nexport { getSessionDefaultFields, mergeSchema, parseAccountInput, parseAccountOutput, parseAdditionalUserInput, parseInputData, parseSessionInput, parseSessionOutput, parseUserInput, parseUserOutput };\n", "//#region src/utils/db.ts\n/**\n* Filters output data by removing fields with the `returned: false` attribute.\n* This ensures sensitive fields are not exposed in API responses.\n*/\nfunction filterOutputFields(data, additionalFields) {\n\tif (!data || !additionalFields) return data;\n\tconst returnFiltered = Object.entries(additionalFields).filter(([, { returned }]) => returned === false).map(([key]) => key);\n\treturn Object.entries(structuredClone(data)).filter(([key]) => !returnFiltered.includes(key)).reduce((acc, [key, value]) => ({\n\t\t...acc,\n\t\t[key]: value\n\t}), {});\n}\n//#endregion\nexport { filterOutputFields };\n", "//#region src/utils/is-promise.ts\nfunction isPromise(obj) {\n\treturn !!obj && (typeof obj === \"object\" || typeof obj === \"function\") && typeof obj.then === \"function\";\n}\n//#endregion\nexport { isPromise };\n", "import { symmetricDecodeJWT, symmetricEncodeJWT } from \"../crypto/jwt.mjs\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport * as z from \"zod\";\n//#region src/cookies/session-store.ts\nconst ALLOWED_COOKIE_SIZE = 4096;\nconst ESTIMATED_EMPTY_COOKIE_SIZE = 200;\nconst CHUNK_SIZE = ALLOWED_COOKIE_SIZE - ESTIMATED_EMPTY_COOKIE_SIZE;\n/**\n* Parse cookies from the request headers\n*/\nfunction parseCookiesFromContext(ctx) {\n\tconst cookieHeader = ctx.headers?.get(\"cookie\");\n\tif (!cookieHeader) return {};\n\tconst cookies = {};\n\tconst pairs = cookieHeader.split(\"; \");\n\tfor (const pair of pairs) {\n\t\tconst [name, ...valueParts] = pair.split(\"=\");\n\t\tif (name && valueParts.length > 0) cookies[name] = valueParts.join(\"=\");\n\t}\n\treturn cookies;\n}\n/**\n* Extract the chunk index from a cookie name\n*/\nfunction getChunkIndex(cookieName) {\n\tconst parts = cookieName.split(\".\");\n\tconst lastPart = parts[parts.length - 1];\n\tconst index = parseInt(lastPart || \"0\", 10);\n\treturn isNaN(index) ? 0 : index;\n}\n/**\n* Read all existing chunks from cookies\n*/\nfunction readExistingChunks(cookieName, ctx) {\n\tconst chunks = {};\n\tconst cookies = parseCookiesFromContext(ctx);\n\tfor (const [name, value] of Object.entries(cookies)) if (name.startsWith(cookieName)) chunks[name] = value;\n\treturn chunks;\n}\n/**\n* Get the full session data by joining all chunks\n*/\nfunction joinChunks(chunks) {\n\treturn Object.keys(chunks).sort((a, b) => {\n\t\treturn getChunkIndex(a) - getChunkIndex(b);\n\t}).map((key) => chunks[key]).join(\"\");\n}\n/**\n* Split a cookie value into chunks if needed\n*/\nfunction chunkCookie(storeName, cookie, chunks, logger) {\n\tconst chunkCount = Math.ceil(cookie.value.length / CHUNK_SIZE);\n\tif (chunkCount === 1) {\n\t\tchunks[cookie.name] = cookie.value;\n\t\treturn [cookie];\n\t}\n\tconst cookies = [];\n\tfor (let i = 0; i < chunkCount; i++) {\n\t\tconst name = `${cookie.name}.${i}`;\n\t\tconst start = i * CHUNK_SIZE;\n\t\tconst value = cookie.value.substring(start, start + CHUNK_SIZE);\n\t\tcookies.push({\n\t\t\t...cookie,\n\t\t\tname,\n\t\t\tvalue\n\t\t});\n\t\tchunks[name] = value;\n\t}\n\tlogger.debug(`CHUNKING_${storeName.toUpperCase()}_COOKIE`, {\n\t\tmessage: `${storeName} cookie exceeds allowed ${ALLOWED_COOKIE_SIZE} bytes.`,\n\t\temptyCookieSize: ESTIMATED_EMPTY_COOKIE_SIZE,\n\t\tvalueSize: cookie.value.length,\n\t\tchunkCount,\n\t\tchunks: cookies.map((c) => c.value.length + ESTIMATED_EMPTY_COOKIE_SIZE)\n\t});\n\treturn cookies;\n}\n/**\n* Get all cookies that should be cleaned (removed)\n*/\nfunction getCleanCookies(chunks, cookieOptions) {\n\tconst cleanedChunks = {};\n\tfor (const name in chunks) cleanedChunks[name] = {\n\t\tname,\n\t\tvalue: \"\",\n\t\tattributes: {\n\t\t\t...cookieOptions,\n\t\t\tmaxAge: 0\n\t\t}\n\t};\n\treturn cleanedChunks;\n}\n/**\n* Create a session store for handling cookie chunking.\n* When session data exceeds 4KB, it automatically splits it into multiple cookies.\n*\n* Based on next-auth's SessionStore implementation.\n* @see https://github.com/nextauthjs/next-auth/blob/27b2519b84b8eb9cf053775dea29d577d2aa0098/packages/next-auth/src/core/lib/cookie.ts\n*/\nconst storeFactory = (storeName) => (cookieName, cookieOptions, ctx) => {\n\tconst chunks = readExistingChunks(cookieName, ctx);\n\tconst logger = ctx.context.logger;\n\treturn {\n\t\tgetValue() {\n\t\t\treturn joinChunks(chunks);\n\t\t},\n\t\thasChunks() {\n\t\t\treturn Object.keys(chunks).length > 0;\n\t\t},\n\t\tchunk(value, options) {\n\t\t\tconst cleanedChunks = getCleanCookies(chunks, cookieOptions);\n\t\t\tfor (const name in chunks) delete chunks[name];\n\t\t\tconst cookies = cleanedChunks;\n\t\t\tconst chunked = chunkCookie(storeName, {\n\t\t\t\tname: cookieName,\n\t\t\t\tvalue,\n\t\t\t\tattributes: {\n\t\t\t\t\t...cookieOptions,\n\t\t\t\t\t...options\n\t\t\t\t}\n\t\t\t}, chunks, logger);\n\t\t\tfor (const chunk of chunked) cookies[chunk.name] = chunk;\n\t\t\treturn Object.values(cookies);\n\t\t},\n\t\tclean() {\n\t\t\tconst cleanedChunks = getCleanCookies(chunks, cookieOptions);\n\t\t\tfor (const name in chunks) delete chunks[name];\n\t\t\treturn Object.values(cleanedChunks);\n\t\t},\n\t\tsetCookies(cookies) {\n\t\t\tfor (const cookie of cookies) ctx.setCookie(cookie.name, cookie.value, cookie.attributes);\n\t\t}\n\t};\n};\nconst createSessionStore = storeFactory(\"Session\");\nconst createAccountStore = storeFactory(\"Account\");\nfunction getChunkedCookie(ctx, cookieName) {\n\tconst value = ctx.getCookie(cookieName);\n\tif (value) return value;\n\tconst chunks = [];\n\tconst cookieHeader = ctx.headers?.get(\"cookie\");\n\tif (!cookieHeader) return null;\n\tconst cookies = {};\n\tconst pairs = cookieHeader.split(\"; \");\n\tfor (const pair of pairs) {\n\t\tconst [name, ...valueParts] = pair.split(\"=\");\n\t\tif (name && valueParts.length > 0) cookies[name] = valueParts.join(\"=\");\n\t}\n\tfor (const [name, val] of Object.entries(cookies)) if (name.startsWith(cookieName + \".\")) {\n\t\tconst indexStr = name.split(\".\").at(-1);\n\t\tconst index = parseInt(indexStr || \"0\", 10);\n\t\tif (!isNaN(index)) chunks.push({\n\t\t\tindex,\n\t\t\tvalue: val\n\t\t});\n\t}\n\tif (chunks.length > 0) {\n\t\tchunks.sort((a, b) => a.index - b.index);\n\t\treturn chunks.map((c) => c.value).join(\"\");\n\t}\n\treturn null;\n}\nasync function setAccountCookie(c, accountData) {\n\tconst accountDataCookie = c.context.authCookies.accountData;\n\tconst options = {\n\t\tmaxAge: 300,\n\t\t...accountDataCookie.attributes\n\t};\n\tconst data = await symmetricEncodeJWT(accountData, c.context.secretConfig, \"better-auth-account\", options.maxAge);\n\tif (data.length > ALLOWED_COOKIE_SIZE) {\n\t\tconst accountStore = createAccountStore(accountDataCookie.name, options, c);\n\t\tconst cookies = accountStore.chunk(data, options);\n\t\taccountStore.setCookies(cookies);\n\t} else {\n\t\tconst accountStore = createAccountStore(accountDataCookie.name, options, c);\n\t\tif (accountStore.hasChunks()) {\n\t\t\tconst cleanCookies = accountStore.clean();\n\t\t\taccountStore.setCookies(cleanCookies);\n\t\t}\n\t\tc.setCookie(accountDataCookie.name, data, options);\n\t}\n}\nasync function getAccountCookie(c) {\n\tconst accountCookie = getChunkedCookie(c, c.context.authCookies.accountData.name);\n\tif (accountCookie) {\n\t\tconst accountData = safeJSONParse(await symmetricDecodeJWT(accountCookie, c.context.secretConfig, \"better-auth-account\"));\n\t\tif (accountData) return accountData;\n\t}\n\treturn null;\n}\nconst getSessionQuerySchema = z.optional(z.object({\n\tdisableCookieCache: z.coerce.boolean().meta({ description: \"Disable cookie cache and fetch session from database\" }).optional(),\n\tdisableRefresh: z.coerce.boolean().meta({ description: \"Disable session refresh. Useful for checking session status, without updating the session\" }).optional()\n}));\n//#endregion\nexport { createAccountStore, createSessionStore, getAccountCookie, getChunkedCookie, getSessionQuerySchema, setAccountCookie };\n", "//#region src/utils/time.ts\nconst SEC = 1e3;\nconst MIN = SEC * 60;\nconst HOUR = MIN * 60;\nconst DAY = HOUR * 24;\nconst WEEK = DAY * 7;\nconst MONTH = DAY * 30;\nconst YEAR = DAY * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;\nfunction parse(value) {\n\tconst match = REGEX.exec(value);\n\tif (!match || match[4] && match[1]) throw new TypeError(`Invalid time string format: \"${value}\". Use formats like \"7d\", \"30m\", \"1 hour\", etc.`);\n\tconst n = parseFloat(match[2]);\n\tconst unit = match[3].toLowerCase();\n\tlet result;\n\tswitch (unit) {\n\t\tcase \"years\":\n\t\tcase \"year\":\n\t\tcase \"yrs\":\n\t\tcase \"yr\":\n\t\tcase \"y\":\n\t\t\tresult = n * YEAR;\n\t\t\tbreak;\n\t\tcase \"months\":\n\t\tcase \"month\":\n\t\tcase \"mo\":\n\t\t\tresult = n * MONTH;\n\t\t\tbreak;\n\t\tcase \"weeks\":\n\t\tcase \"week\":\n\t\tcase \"w\":\n\t\t\tresult = n * WEEK;\n\t\t\tbreak;\n\t\tcase \"days\":\n\t\tcase \"day\":\n\t\tcase \"d\":\n\t\t\tresult = n * DAY;\n\t\t\tbreak;\n\t\tcase \"hours\":\n\t\tcase \"hour\":\n\t\tcase \"hrs\":\n\t\tcase \"hr\":\n\t\tcase \"h\":\n\t\t\tresult = n * HOUR;\n\t\t\tbreak;\n\t\tcase \"minutes\":\n\t\tcase \"minute\":\n\t\tcase \"mins\":\n\t\tcase \"min\":\n\t\tcase \"m\":\n\t\t\tresult = n * MIN;\n\t\t\tbreak;\n\t\tcase \"seconds\":\n\t\tcase \"second\":\n\t\tcase \"secs\":\n\t\tcase \"sec\":\n\t\tcase \"s\":\n\t\t\tresult = n * SEC;\n\t\t\tbreak;\n\t\tdefault: throw new TypeError(`Unknown time unit: \"${unit}\"`);\n\t}\n\tif (match[1] === \"-\" || match[4] === \"ago\") return -result;\n\treturn result;\n}\n/**\n* Parse a time string and return the value in milliseconds.\n*\n* @param value - A time string like \"7d\", \"30m\", \"1 hour\", \"2 hours ago\"\n* @returns The parsed value in milliseconds\n* @throws TypeError if the string format is invalid\n*\n* @example\n* ms(\"1d\") // 86400000\n* ms(\"2 hours\") // 7200000\n* ms(\"30s\") // 30000\n* ms(\"2 hours ago\") // -7200000\n*/\nfunction ms(value) {\n\treturn parse(value);\n}\n/**\n* Parse a time string and return the value in seconds.\n*\n* @param value - A time string like \"7d\", \"30m\", \"1 hour\", \"2 hours ago\"\n* @returns The parsed value in seconds (rounded)\n* @throws TypeError if the string format is invalid\n*\n* @example\n* sec(\"1d\") // 86400\n* sec(\"2 hours\") // 7200\n* sec(\"-30s\") // -30\n* sec(\"2 hours ago\") // -7200\n*/\nfunction sec(value) {\n\treturn Math.round(parse(value) / 1e3);\n}\n//#endregion\nexport { ms, sec };\n", "//#region src/cookies/cookie-utils.ts\nfunction tryDecode(str) {\n\ttry {\n\t\treturn decodeURIComponent(str);\n\t} catch {\n\t\treturn str;\n\t}\n}\nconst SECURE_COOKIE_PREFIX = \"__Secure-\";\nconst HOST_COOKIE_PREFIX = \"__Host-\";\n/**\n* Remove __Secure- or __Host- prefix from cookie name.\n*/\nfunction stripSecureCookiePrefix(cookieName) {\n\tif (cookieName.startsWith(\"__Secure-\")) return cookieName.slice(9);\n\tif (cookieName.startsWith(\"__Host-\")) return cookieName.slice(7);\n\treturn cookieName;\n}\n/**\n* Split a comma-joined `Set-Cookie` header string into individual cookies.\n*/\nfunction splitSetCookieHeader(setCookie) {\n\tif (!setCookie) return [];\n\tconst result = [];\n\tlet start = 0;\n\tlet i = 0;\n\twhile (i < setCookie.length) {\n\t\tif (setCookie[i] === \",\") {\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < setCookie.length && setCookie[j] === \" \") j++;\n\t\t\twhile (j < setCookie.length && setCookie[j] !== \"=\" && setCookie[j] !== \";\" && setCookie[j] !== \",\") j++;\n\t\t\tif (j < setCookie.length && setCookie[j] === \"=\") {\n\t\t\t\tconst part = setCookie.slice(start, i).trim();\n\t\t\t\tif (part) result.push(part);\n\t\t\t\tstart = i + 1;\n\t\t\t\twhile (start < setCookie.length && setCookie[start] === \" \") start++;\n\t\t\t\ti = start;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\tconst last = setCookie.slice(start).trim();\n\tif (last) result.push(last);\n\treturn result;\n}\nfunction parseSetCookieHeader(setCookie) {\n\tconst cookies = /* @__PURE__ */ new Map();\n\tsplitSetCookieHeader(setCookie).forEach((cookieString) => {\n\t\tconst [nameValue, ...attributes] = cookieString.split(\";\").map((part) => part.trim());\n\t\tconst [name, ...valueParts] = (nameValue || \"\").split(\"=\");\n\t\tconst value = valueParts.join(\"=\");\n\t\tif (!name || value === void 0) return;\n\t\tconst attrObj = { value: value.includes(\"%\") ? tryDecode(value) : value };\n\t\tattributes.forEach((attribute) => {\n\t\t\tconst [attrName, ...attrValueParts] = attribute.split(\"=\");\n\t\t\tconst attrValue = attrValueParts.join(\"=\");\n\t\t\tconst normalizedAttrName = attrName.trim().toLowerCase();\n\t\t\tswitch (normalizedAttrName) {\n\t\t\t\tcase \"max-age\":\n\t\t\t\t\tattrObj[\"max-age\"] = attrValue ? parseInt(attrValue.trim(), 10) : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"expires\":\n\t\t\t\t\tattrObj.expires = attrValue ? new Date(attrValue.trim()) : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"domain\":\n\t\t\t\t\tattrObj.domain = attrValue ? attrValue.trim() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"path\":\n\t\t\t\t\tattrObj.path = attrValue ? attrValue.trim() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"secure\":\n\t\t\t\t\tattrObj.secure = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"httponly\":\n\t\t\t\t\tattrObj.httponly = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"samesite\":\n\t\t\t\t\tattrObj.samesite = attrValue ? attrValue.trim().toLowerCase() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tattrObj[normalizedAttrName] = attrValue ? attrValue.trim() : true;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tcookies.set(name, attrObj);\n\t});\n\treturn cookies;\n}\nfunction setCookieToHeader(headers) {\n\treturn (context) => {\n\t\tconst setCookieHeader = context.response.headers.get(\"set-cookie\");\n\t\tif (!setCookieHeader) return;\n\t\tconst cookieMap = /* @__PURE__ */ new Map();\n\t\t(headers.get(\"cookie\") || \"\").split(\";\").forEach((cookie) => {\n\t\t\tconst [name, ...rest] = cookie.trim().split(\"=\");\n\t\t\tif (name && rest.length > 0) cookieMap.set(name, rest.join(\"=\"));\n\t\t});\n\t\tparseSetCookieHeader(setCookieHeader).forEach((value, name) => {\n\t\t\tcookieMap.set(name, value.value);\n\t\t});\n\t\tconst updatedCookies = Array.from(cookieMap.entries()).map(([name, value]) => `${name}=${value}`).join(\"; \");\n\t\theaders.set(\"cookie\", updatedCookies);\n\t};\n}\n//#endregion\nexport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, parseSetCookieHeader, setCookieToHeader, splitSetCookieHeader, stripSecureCookiePrefix };\n", "import { isDynamicBaseURLConfig } from \"../utils/url.mjs\";\nimport { getDate } from \"../utils/date.mjs\";\nimport { parseUserOutput } from \"../db/schema.mjs\";\nimport { isPromise } from \"../utils/is-promise.mjs\";\nimport { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT } from \"../crypto/jwt.mjs\";\nimport { createAccountStore, createSessionStore, getAccountCookie, getChunkedCookie, setAccountCookie } from \"./session-store.mjs\";\nimport { sec } from \"../utils/time.mjs\";\nimport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, parseSetCookieHeader, setCookieToHeader, splitSetCookieHeader, stripSecureCookiePrefix } from \"./cookie-utils.mjs\";\nimport { env, isProduction } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { filterOutputFields } from \"@better-auth/core/utils/db\";\nimport { base64Url } from \"@better-auth/utils/base64\";\nimport { binary } from \"@better-auth/utils/binary\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\n//#region src/cookies/index.ts\nfunction createCookieGetter(options) {\n\tconst baseURLString = typeof options.baseURL === \"string\" ? options.baseURL : void 0;\n\tconst dynamicProtocol = typeof options.baseURL === \"object\" && options.baseURL !== null ? options.baseURL.protocol : void 0;\n\tconst secureCookiePrefix = (options.advanced?.useSecureCookies !== void 0 ? options.advanced?.useSecureCookies : dynamicProtocol === \"https\" ? true : dynamicProtocol === \"http\" ? false : baseURLString ? baseURLString.startsWith(\"https://\") : isProduction) ? SECURE_COOKIE_PREFIX : \"\";\n\tconst crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled;\n\tconst domain = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (baseURLString ? new URL(baseURLString).hostname : void 0) : void 0;\n\tif (crossSubdomainEnabled && !domain && !isDynamicBaseURLConfig(options.baseURL)) throw new BetterAuthError(\"baseURL is required when crossSubdomainCookies are enabled.\");\n\tfunction createCookie(cookieName, overrideAttributes = {}) {\n\t\tconst prefix = options.advanced?.cookiePrefix || \"better-auth\";\n\t\tconst name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`;\n\t\tconst attributes = options.advanced?.cookies?.[cookieName]?.attributes ?? {};\n\t\treturn {\n\t\t\tname: `${secureCookiePrefix}${name}`,\n\t\t\tattributes: {\n\t\t\t\tsecure: !!secureCookiePrefix,\n\t\t\t\tsameSite: \"lax\",\n\t\t\t\tpath: \"/\",\n\t\t\t\thttpOnly: true,\n\t\t\t\t...crossSubdomainEnabled ? { domain } : {},\n\t\t\t\t...options.advanced?.defaultCookieAttributes,\n\t\t\t\t...overrideAttributes,\n\t\t\t\t...attributes\n\t\t\t}\n\t\t};\n\t}\n\treturn createCookie;\n}\nfunction getCookies(options) {\n\tconst createCookie = createCookieGetter(options);\n\tconst sessionToken = createCookie(\"session_token\", { maxAge: options.session?.expiresIn || sec(\"7d\") });\n\tconst sessionData = createCookie(\"session_data\", { maxAge: options.session?.cookieCache?.maxAge || 300 });\n\tconst accountData = createCookie(\"account_data\", { maxAge: options.session?.cookieCache?.maxAge || 300 });\n\tconst dontRememberToken = createCookie(\"dont_remember\");\n\treturn {\n\t\tsessionToken: {\n\t\t\tname: sessionToken.name,\n\t\t\tattributes: sessionToken.attributes\n\t\t},\n\t\tsessionData: {\n\t\t\tname: sessionData.name,\n\t\t\tattributes: sessionData.attributes\n\t\t},\n\t\tdontRememberToken: {\n\t\t\tname: dontRememberToken.name,\n\t\t\tattributes: dontRememberToken.attributes\n\t\t},\n\t\taccountData: {\n\t\t\tname: accountData.name,\n\t\t\tattributes: accountData.attributes\n\t\t}\n\t};\n}\nasync function setCookieCache(ctx, session, dontRememberMe) {\n\tif (!ctx.context.options.session?.cookieCache?.enabled) return;\n\tconst filteredSession = filterOutputFields(session.session, ctx.context.options.session?.additionalFields);\n\tconst filteredUser = parseUserOutput(ctx.context.options, session.user);\n\tconst versionConfig = ctx.context.options.session?.cookieCache?.version;\n\tlet version = \"1\";\n\tif (versionConfig) {\n\t\tif (typeof versionConfig === \"string\") version = versionConfig;\n\t\telse if (typeof versionConfig === \"function\") {\n\t\t\tconst result = versionConfig(session.session, session.user);\n\t\t\tversion = isPromise(result) ? await result : result;\n\t\t}\n\t}\n\tconst sessionData = {\n\t\tsession: filteredSession,\n\t\tuser: filteredUser,\n\t\tupdatedAt: Date.now(),\n\t\tversion\n\t};\n\tconst options = {\n\t\t...ctx.context.authCookies.sessionData.attributes,\n\t\tmaxAge: dontRememberMe ? void 0 : ctx.context.authCookies.sessionData.attributes.maxAge\n\t};\n\tconst expiresAtDate = getDate(options.maxAge || 60, \"sec\").getTime();\n\tconst strategy = ctx.context.options.session?.cookieCache?.strategy || \"compact\";\n\tlet data;\n\tif (strategy === \"jwe\") data = await symmetricEncodeJWT(sessionData, ctx.context.secretConfig, \"better-auth-session\", options.maxAge || 300);\n\telse if (strategy === \"jwt\") data = await signJWT(sessionData, ctx.context.secret, options.maxAge || 300);\n\telse data = base64Url.encode(JSON.stringify({\n\t\tsession: sessionData,\n\t\texpiresAt: expiresAtDate,\n\t\tsignature: await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, JSON.stringify({\n\t\t\t...sessionData,\n\t\t\texpiresAt: expiresAtDate\n\t\t}))\n\t}), { padding: false });\n\tif (data.length > 4093) {\n\t\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx);\n\t\tconst cookies = sessionStore.chunk(data, options);\n\t\tsessionStore.setCookies(cookies);\n\t} else {\n\t\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx);\n\t\tif (sessionStore.hasChunks()) {\n\t\t\tconst cleanCookies = sessionStore.clean();\n\t\t\tsessionStore.setCookies(cleanCookies);\n\t\t}\n\t\tctx.setCookie(ctx.context.authCookies.sessionData.name, data, options);\n\t}\n\tif (ctx.context.options.account?.storeAccountCookie) {\n\t\tconst accountData = await getAccountCookie(ctx);\n\t\tif (accountData) await setAccountCookie(ctx, accountData);\n\t}\n}\nasync function setSessionCookie(ctx, session, dontRememberMe, overrides) {\n\tconst dontRememberMeCookie = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);\n\tdontRememberMe = dontRememberMe !== void 0 ? dontRememberMe : !!dontRememberMeCookie;\n\tconst options = ctx.context.authCookies.sessionToken.attributes;\n\tconst maxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn;\n\tawait ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, {\n\t\t...options,\n\t\tmaxAge,\n\t\t...overrides\n\t});\n\tif (dontRememberMe) await ctx.setSignedCookie(ctx.context.authCookies.dontRememberToken.name, \"true\", ctx.context.secret, ctx.context.authCookies.dontRememberToken.attributes);\n\tawait setCookieCache(ctx, session, dontRememberMe);\n\tctx.context.setNewSession(session);\n}\n/**\n* Expires a cookie by setting `maxAge: 0` while preserving its attributes\n*/\nfunction expireCookie(ctx, cookie) {\n\tctx.setCookie(cookie.name, \"\", {\n\t\t...cookie.attributes,\n\t\tmaxAge: 0\n\t});\n}\nfunction deleteSessionCookie(ctx, skipDontRememberMe) {\n\texpireCookie(ctx, ctx.context.authCookies.sessionToken);\n\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\tif (ctx.context.options.account?.storeAccountCookie) {\n\t\texpireCookie(ctx, ctx.context.authCookies.accountData);\n\t\tconst accountStore = createAccountStore(ctx.context.authCookies.accountData.name, ctx.context.authCookies.accountData.attributes, ctx);\n\t\tconst cleanCookies = accountStore.clean();\n\t\taccountStore.setCookies(cleanCookies);\n\t}\n\tif (ctx.context.oauthConfig.storeStateStrategy === \"cookie\") expireCookie(ctx, ctx.context.createAuthCookie(\"oauth_state\"));\n\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, ctx.context.authCookies.sessionData.attributes, ctx);\n\tconst cleanCookies = sessionStore.clean();\n\tsessionStore.setCookies(cleanCookies);\n\tif (!skipDontRememberMe) expireCookie(ctx, ctx.context.authCookies.dontRememberToken);\n}\nfunction parseCookies(cookieHeader) {\n\tconst cookies = cookieHeader.split(\"; \");\n\tconst cookieMap = /* @__PURE__ */ new Map();\n\tcookies.forEach((cookie) => {\n\t\tconst [name, value] = cookie.split(/=(.*)/s);\n\t\tcookieMap.set(name, value);\n\t});\n\treturn cookieMap;\n}\nconst getSessionCookie = (request, config) => {\n\tconst cookies = (request instanceof Headers || !(\"headers\" in request) ? request : request.headers).get(\"cookie\");\n\tif (!cookies) return null;\n\tconst { cookieName = \"session_token\", cookiePrefix = \"better-auth\" } = config || {};\n\tconst parsedCookie = parseCookies(cookies);\n\tconst getCookie = (name) => parsedCookie.get(name) || parsedCookie.get(`__Secure-${name}`);\n\tconst sessionToken = getCookie(`${cookiePrefix}.${cookieName}`) || getCookie(`${cookiePrefix}-${cookieName}`);\n\tif (sessionToken) return sessionToken;\n\treturn null;\n};\nconst getCookieCache = async (request, config) => {\n\tconst cookies = (request instanceof Headers || !(\"headers\" in request) ? request : request.headers).get(\"cookie\");\n\tif (!cookies) return null;\n\tconst { cookieName = \"session_data\", cookiePrefix = \"better-auth\" } = config || {};\n\tconst name = config?.isSecure !== void 0 ? config.isSecure ? `${SECURE_COOKIE_PREFIX}${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}` : isProduction ? `${SECURE_COOKIE_PREFIX}${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}`;\n\tconst parsedCookie = parseCookies(cookies);\n\tlet sessionData = parsedCookie.get(name);\n\tif (!sessionData) {\n\t\tconst chunks = [];\n\t\tfor (const [cookieName, value] of parsedCookie.entries()) if (cookieName.startsWith(name + \".\")) {\n\t\t\tconst parts = cookieName.split(\".\");\n\t\t\tconst indexStr = parts[parts.length - 1];\n\t\t\tconst index = parseInt(indexStr || \"0\", 10);\n\t\t\tif (!isNaN(index)) chunks.push({\n\t\t\t\tindex,\n\t\t\t\tvalue\n\t\t\t});\n\t\t}\n\t\tif (chunks.length > 0) {\n\t\t\tchunks.sort((a, b) => a.index - b.index);\n\t\t\tsessionData = chunks.map((c) => c.value).join(\"\");\n\t\t}\n\t}\n\tif (sessionData) {\n\t\tconst secret = config?.secret || env.BETTER_AUTH_SECRET;\n\t\tif (!secret) throw new BetterAuthError(\"getCookieCache requires a secret to be provided. Either pass it as an option or set the BETTER_AUTH_SECRET environment variable\");\n\t\tconst strategy = config?.strategy || \"compact\";\n\t\tif (strategy === \"jwe\") {\n\t\t\tconst payload = await symmetricDecodeJWT(sessionData, secret, \"better-auth-session\");\n\t\t\tif (payload && payload.session && payload.user) {\n\t\t\t\tif (config?.version) {\n\t\t\t\t\tconst cookieVersion = payload.version || \"1\";\n\t\t\t\t\tlet expectedVersion = \"1\";\n\t\t\t\t\tif (typeof config.version === \"string\") expectedVersion = config.version;\n\t\t\t\t\telse if (typeof config.version === \"function\") {\n\t\t\t\t\t\tconst result = config.version(payload.session, payload.user);\n\t\t\t\t\t\texpectedVersion = isPromise(result) ? await result : result;\n\t\t\t\t\t}\n\t\t\t\t\tif (cookieVersion !== expectedVersion) return null;\n\t\t\t\t}\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn null;\n\t\t} else if (strategy === \"jwt\") {\n\t\t\tconst payload = await verifyJWT(sessionData, secret);\n\t\t\tif (payload && payload.session && payload.user) {\n\t\t\t\tif (config?.version) {\n\t\t\t\t\tconst cookieVersion = payload.version || \"1\";\n\t\t\t\t\tlet expectedVersion = \"1\";\n\t\t\t\t\tif (typeof config.version === \"string\") expectedVersion = config.version;\n\t\t\t\t\telse if (typeof config.version === \"function\") {\n\t\t\t\t\t\tconst result = config.version(payload.session, payload.user);\n\t\t\t\t\t\texpectedVersion = isPromise(result) ? await result : result;\n\t\t\t\t\t}\n\t\t\t\t\tif (cookieVersion !== expectedVersion) return null;\n\t\t\t\t}\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn null;\n\t\t} else {\n\t\t\tconst sessionDataPayload = safeJSONParse(binary.decode(base64Url.decode(sessionData)));\n\t\t\tif (!sessionDataPayload) return null;\n\t\t\tif (!await createHMAC(\"SHA-256\", \"base64urlnopad\").verify(secret, JSON.stringify({\n\t\t\t\t...sessionDataPayload.session,\n\t\t\t\texpiresAt: sessionDataPayload.expiresAt\n\t\t\t}), sessionDataPayload.signature)) return null;\n\t\t\tif (config?.version && sessionDataPayload.session) {\n\t\t\t\tconst cookieVersion = sessionDataPayload.session.version || \"1\";\n\t\t\t\tlet expectedVersion = \"1\";\n\t\t\t\tif (typeof config.version === \"string\") expectedVersion = config.version;\n\t\t\t\telse if (typeof config.version === \"function\") {\n\t\t\t\t\tconst result = config.version(sessionDataPayload.session.session, sessionDataPayload.session.user);\n\t\t\t\t\texpectedVersion = isPromise(result) ? await result : result;\n\t\t\t\t}\n\t\t\t\tif (cookieVersion !== expectedVersion) return null;\n\t\t\t}\n\t\t\treturn sessionDataPayload.session;\n\t\t}\n\t}\n\treturn null;\n};\n//#endregion\nexport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, createCookieGetter, createSessionStore, deleteSessionCookie, expireCookie, getAccountCookie, getChunkedCookie, getCookieCache, getCookies, getSessionCookie, parseCookies, parseSetCookieHeader, setCookieCache, setCookieToHeader, setSessionCookie, splitSetCookieHeader, stripSecureCookiePrefix };\n", "const decoders = /* @__PURE__ */ new Map();\nconst encoder = new TextEncoder();\nconst binary = {\n decode: (data, encoding = \"utf-8\") => {\n if (!decoders.has(encoding)) {\n decoders.set(encoding, new TextDecoder(encoding));\n }\n const decoder = decoders.get(encoding);\n return decoder.decode(data);\n },\n encode: encoder.encode\n};\n\nexport { binary };\n", "const hexadecimal = \"0123456789abcdef\";\nconst hex = {\n encode: (data) => {\n if (typeof data === \"string\") {\n data = new TextEncoder().encode(data);\n }\n if (data.byteLength === 0) {\n return \"\";\n }\n const buffer = new Uint8Array(data);\n let result = \"\";\n for (const byte of buffer) {\n result += byte.toString(16).padStart(2, \"0\");\n }\n return result;\n },\n decode: (data) => {\n if (!data) {\n return \"\";\n }\n if (typeof data === \"string\") {\n if (data.length % 2 !== 0) {\n throw new Error(\"Invalid hexadecimal string\");\n }\n if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) {\n throw new Error(\"Invalid hexadecimal string\");\n }\n const result = new Uint8Array(data.length / 2);\n for (let i = 0; i < data.length; i += 2) {\n result[i / 2] = parseInt(data.slice(i, i + 2), 16);\n }\n return new TextDecoder().decode(result);\n }\n return new TextDecoder().decode(data);\n }\n};\n\nexport { hex };\n", "import { hex } from './hex.mjs';\nimport { base64Url, base64 } from './base64.mjs';\nimport { getWebcryptoSubtle } from './index.mjs';\n\nconst createHMAC = (algorithm = \"SHA-256\", encoding = \"none\") => {\n const hmac = {\n importKey: async (key, keyUsage) => {\n return getWebcryptoSubtle().importKey(\n \"raw\",\n typeof key === \"string\" ? new TextEncoder().encode(key) : key,\n { name: \"HMAC\", hash: { name: algorithm } },\n false,\n [keyUsage]\n );\n },\n sign: async (hmacKey, data) => {\n if (typeof hmacKey === \"string\") {\n hmacKey = await hmac.importKey(hmacKey, \"sign\");\n }\n const signature = await getWebcryptoSubtle().sign(\n \"HMAC\",\n hmacKey,\n typeof data === \"string\" ? new TextEncoder().encode(data) : data\n );\n if (encoding === \"hex\") {\n return hex.encode(signature);\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n return base64Url.encode(signature, {\n padding: encoding !== \"base64urlnopad\"\n });\n }\n return signature;\n },\n verify: async (hmacKey, data, signature) => {\n if (typeof hmacKey === \"string\") {\n hmacKey = await hmac.importKey(hmacKey, \"verify\");\n }\n if (encoding === \"hex\") {\n signature = hex.decode(signature);\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n signature = await base64.decode(signature);\n }\n return getWebcryptoSubtle().verify(\n \"HMAC\",\n hmacKey,\n typeof signature === \"string\" ? new TextEncoder().encode(signature) : signature,\n typeof data === \"string\" ? new TextEncoder().encode(data) : data\n );\n }\n };\n return hmac;\n};\n\nexport { createHMAC };\n", "import { generateRandomString } from \"./crypto/random.mjs\";\nimport { symmetricDecrypt, symmetricEncrypt } from \"./crypto/index.mjs\";\nimport { expireCookie } from \"./cookies/index.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport * as z from \"zod\";\n//#region src/state.ts\nconst stateDataSchema = z.looseObject({\n\tcallbackURL: z.string(),\n\tcodeVerifier: z.string(),\n\terrorURL: z.string().optional(),\n\tnewUserURL: z.string().optional(),\n\texpiresAt: z.number(),\n\toauthState: z.string().optional(),\n\tlink: z.object({\n\t\temail: z.string(),\n\t\tuserId: z.coerce.string()\n\t}).optional(),\n\trequestSignUp: z.boolean().optional()\n});\nvar StateError = class extends BetterAuthError {\n\tcode;\n\tdetails;\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.code = options.code;\n\t\tthis.details = options.details;\n\t}\n};\nasync function generateGenericState(c, stateData, settings) {\n\tconst state = generateRandomString(32);\n\tif (c.context.oauthConfig.storeStateStrategy === \"cookie\") {\n\t\tconst payload = {\n\t\t\t...stateData,\n\t\t\toauthState: state\n\t\t};\n\t\tconst encryptedData = await symmetricEncrypt({\n\t\t\tkey: c.context.secretConfig,\n\t\t\tdata: JSON.stringify(payload)\n\t\t});\n\t\tconst stateCookie = c.context.createAuthCookie(settings?.cookieName ?? \"oauth_state\", { maxAge: 600 });\n\t\tc.setCookie(stateCookie.name, encryptedData, stateCookie.attributes);\n\t\treturn {\n\t\t\tstate,\n\t\t\tcodeVerifier: stateData.codeVerifier\n\t\t};\n\t}\n\tconst stateCookie = c.context.createAuthCookie(settings?.cookieName ?? \"state\", { maxAge: 300 });\n\tawait c.setSignedCookie(stateCookie.name, state, c.context.secret, stateCookie.attributes);\n\tconst expiresAt = /* @__PURE__ */ new Date();\n\texpiresAt.setMinutes(expiresAt.getMinutes() + 10);\n\tif (!await c.context.internalAdapter.createVerificationValue({\n\t\tvalue: JSON.stringify({\n\t\t\t...stateData,\n\t\t\toauthState: state\n\t\t}),\n\t\tidentifier: state,\n\t\texpiresAt\n\t})) throw new StateError(\"Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database\", { code: \"state_generation_error\" });\n\treturn {\n\t\tstate,\n\t\tcodeVerifier: stateData.codeVerifier\n\t};\n}\nasync function parseGenericState(c, state, settings) {\n\tconst storeStateStrategy = c.context.oauthConfig.storeStateStrategy;\n\tlet parsedData;\n\tif (storeStateStrategy === \"cookie\") {\n\t\tconst stateCookie = c.context.createAuthCookie(settings?.cookieName ?? \"oauth_state\");\n\t\tconst encryptedData = c.getCookie(stateCookie.name);\n\t\tif (!encryptedData) throw new StateError(\"State mismatch: auth state cookie not found\", {\n\t\t\tcode: \"state_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\ttry {\n\t\t\tconst decryptedData = await symmetricDecrypt({\n\t\t\t\tkey: c.context.secretConfig,\n\t\t\t\tdata: encryptedData\n\t\t\t});\n\t\t\tparsedData = stateDataSchema.parse(JSON.parse(decryptedData));\n\t\t} catch (error) {\n\t\t\tthrow new StateError(\"State invalid: Failed to decrypt or parse auth state\", {\n\t\t\t\tcode: \"state_invalid\",\n\t\t\t\tdetails: { state },\n\t\t\t\tcause: error\n\t\t\t});\n\t\t}\n\t\tif (!parsedData.oauthState || parsedData.oauthState !== state) throw new StateError(\"State mismatch: OAuth state parameter does not match stored state\", {\n\t\t\tcode: \"state_security_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\texpireCookie(c, stateCookie);\n\t} else {\n\t\tconst data = await c.context.internalAdapter.findVerificationValue(state);\n\t\tif (!data) throw new StateError(\"State mismatch: verification not found\", {\n\t\t\tcode: \"state_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\tparsedData = stateDataSchema.parse(JSON.parse(data.value));\n\t\tif (parsedData.oauthState !== void 0 && parsedData.oauthState !== state) throw new StateError(\"State mismatch: OAuth state parameter does not match stored state\", {\n\t\t\tcode: \"state_security_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\tconst stateCookie = c.context.createAuthCookie(settings?.cookieName ?? \"state\");\n\t\tconst stateCookieValue = await c.getSignedCookie(stateCookie.name, c.context.secret);\n\t\tif (!(settings?.skipStateCookieCheck ?? c.context.oauthConfig.skipStateCookieCheck) && (!stateCookieValue || stateCookieValue !== state)) throw new StateError(\"State mismatch: State not persisted correctly\", {\n\t\t\tcode: \"state_security_mismatch\",\n\t\t\tdetails: { state }\n\t\t});\n\t\texpireCookie(c, stateCookie);\n\t\tawait c.context.internalAdapter.deleteVerificationByIdentifier(state);\n\t}\n\tif (parsedData.expiresAt < Date.now()) throw new StateError(\"Invalid state: request expired\", {\n\t\tcode: \"state_mismatch\",\n\t\tdetails: { expiresAt: parsedData.expiresAt }\n\t});\n\treturn parsedData;\n}\n//#endregion\nexport { StateError, generateGenericState, parseGenericState };\n", "//#region src/context/global.ts\nconst symbol = Symbol.for(\"better-auth:global\");\nlet bind = null;\nconst __context = {};\nconst __betterAuthVersion = \"1.6.2\";\n/**\n* We store context instance in the globalThis.\n*\n* The reason we do this is that some bundlers, web framework, or package managers might\n* create multiple copies of BetterAuth in the same process intentionally or unintentionally.\n*\n* For example, yarn v1, Next.js, SSR, Vite...\n*\n* @internal\n*/\nfunction __getBetterAuthGlobal() {\n\tif (!globalThis[symbol]) {\n\t\tglobalThis[symbol] = {\n\t\t\tversion: __betterAuthVersion,\n\t\t\tepoch: 1,\n\t\t\tcontext: __context\n\t\t};\n\t\tbind = globalThis[symbol];\n\t}\n\tbind = globalThis[symbol];\n\tif (bind.version !== __betterAuthVersion) {\n\t\tbind.version = __betterAuthVersion;\n\t\tbind.epoch++;\n\t}\n\treturn globalThis[symbol];\n}\nfunction getBetterAuthVersion() {\n\treturn __getBetterAuthGlobal().version;\n}\n//#endregion\nexport { __getBetterAuthGlobal, getBetterAuthVersion };\n", "//#region src/async_hooks/index.ts\nconst AsyncLocalStoragePromise = import(\n\t/* @vite-ignore */\n\t/* webpackIgnore: true */\n\t\"node:async_hooks\"\n).then((mod) => mod.AsyncLocalStorage).catch((err) => {\n\tif (\"AsyncLocalStorage\" in globalThis) return globalThis.AsyncLocalStorage;\n\tif (typeof window !== \"undefined\") return null;\n\tconsole.warn(\"[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.\");\n\tconsole.warn(\"[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler\");\n\tconsole.warn(\"[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag\");\n\tthrow err;\n});\nasync function getAsyncLocalStorage() {\n\tconst mod = await AsyncLocalStoragePromise;\n\tif (mod === null) throw new Error(\"getAsyncLocalStorage is only available in server code\");\n\telse return mod;\n}\n//#endregion\nexport { getAsyncLocalStorage };\n", "import { __getBetterAuthGlobal } from \"./global.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/endpoint-context.ts\nconst ensureAsyncStorage = async () => {\n\tconst betterAuthGlobal = __getBetterAuthGlobal();\n\tif (!betterAuthGlobal.context.endpointContextAsyncStorage) {\n\t\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\t\tbetterAuthGlobal.context.endpointContextAsyncStorage = new AsyncLocalStorage();\n\t}\n\treturn betterAuthGlobal.context.endpointContextAsyncStorage;\n};\n/**\n* This is for internal use only. Most users should use `getCurrentAuthContext` instead.\n*\n* It is exposed for advanced use cases where you need direct access to the AsyncLocalStorage instance.\n*/\nasync function getCurrentAuthContextAsyncLocalStorage() {\n\treturn ensureAsyncStorage();\n}\nasync function getCurrentAuthContext() {\n\tconst context = (await ensureAsyncStorage()).getStore();\n\tif (!context) throw new Error(\"No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.\");\n\treturn context;\n}\nasync function runWithEndpointContext(context, fn) {\n\treturn (await ensureAsyncStorage()).run(context, fn);\n}\n//#endregion\nexport { getCurrentAuthContext, getCurrentAuthContextAsyncLocalStorage, runWithEndpointContext };\n", "import { __getBetterAuthGlobal } from \"./global.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/request-state.ts\nconst ensureAsyncStorage = async () => {\n\tconst betterAuthGlobal = __getBetterAuthGlobal();\n\tif (!betterAuthGlobal.context.requestStateAsyncStorage) {\n\t\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\t\tbetterAuthGlobal.context.requestStateAsyncStorage = new AsyncLocalStorage();\n\t}\n\treturn betterAuthGlobal.context.requestStateAsyncStorage;\n};\nasync function getRequestStateAsyncLocalStorage() {\n\treturn ensureAsyncStorage();\n}\nasync function hasRequestState() {\n\treturn (await ensureAsyncStorage()).getStore() !== void 0;\n}\nasync function getCurrentRequestState() {\n\tconst store = (await ensureAsyncStorage()).getStore();\n\tif (!store) throw new Error(\"No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.\");\n\treturn store;\n}\nasync function runWithRequestState(store, fn) {\n\treturn (await ensureAsyncStorage()).run(store, fn);\n}\nfunction defineRequestState(initFn) {\n\tconst ref = Object.freeze({});\n\treturn {\n\t\tget ref() {\n\t\t\treturn ref;\n\t\t},\n\t\tasync get() {\n\t\t\tconst store = await getCurrentRequestState();\n\t\t\tif (!store.has(ref)) {\n\t\t\t\tconst initialValue = await initFn();\n\t\t\t\tstore.set(ref, initialValue);\n\t\t\t\treturn initialValue;\n\t\t\t}\n\t\t\treturn store.get(ref);\n\t\t},\n\t\tasync set(value) {\n\t\t\t(await getCurrentRequestState()).set(ref, value);\n\t\t}\n\t};\n}\n//#endregion\nexport { defineRequestState, getCurrentRequestState, getRequestStateAsyncLocalStorage, hasRequestState, runWithRequestState };\n", "import { __getBetterAuthGlobal } from \"./global.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/transaction.ts\nconst ensureAsyncStorage = async () => {\n\tconst betterAuthGlobal = __getBetterAuthGlobal();\n\tif (!betterAuthGlobal.context.adapterAsyncStorage) {\n\t\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\t\tbetterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage();\n\t}\n\treturn betterAuthGlobal.context.adapterAsyncStorage;\n};\n/**\n* This is for internal use only. Most users should use `getCurrentAdapter` instead.\n*\n* It is exposed for advanced use cases where you need direct access to the AsyncLocalStorage instance.\n*/\nconst getCurrentDBAdapterAsyncLocalStorage = async () => {\n\treturn ensureAsyncStorage();\n};\nconst getCurrentAdapter = async (fallback) => {\n\treturn ensureAsyncStorage().then((als) => {\n\t\treturn als.getStore()?.adapter || fallback;\n\t}).catch(() => {\n\t\treturn fallback;\n\t});\n};\nconst runWithAdapter = async (adapter, fn) => {\n\tlet called = false;\n\treturn ensureAsyncStorage().then(async (als) => {\n\t\tcalled = true;\n\t\tconst pendingHooks = [];\n\t\tlet result;\n\t\tlet error;\n\t\tlet hasError = false;\n\t\ttry {\n\t\t\tresult = await als.run({\n\t\t\t\tadapter,\n\t\t\t\tpendingHooks\n\t\t\t}, fn);\n\t\t} catch (err) {\n\t\t\terror = err;\n\t\t\thasError = true;\n\t\t}\n\t\tfor (const hook of pendingHooks) await hook();\n\t\tif (hasError) throw error;\n\t\treturn result;\n\t}).catch((err) => {\n\t\tif (!called) return fn();\n\t\tthrow err;\n\t});\n};\nconst runWithTransaction = async (adapter, fn) => {\n\tlet called = true;\n\treturn ensureAsyncStorage().then(async (als) => {\n\t\tcalled = true;\n\t\tconst pendingHooks = [];\n\t\tlet result;\n\t\tlet error;\n\t\tlet hasError = false;\n\t\ttry {\n\t\t\tresult = await adapter.transaction(async (trx) => {\n\t\t\t\treturn als.run({\n\t\t\t\t\tadapter: trx,\n\t\t\t\t\tpendingHooks\n\t\t\t\t}, fn);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\thasError = true;\n\t\t\terror = e;\n\t\t}\n\t\tfor (const hook of pendingHooks) await hook();\n\t\tif (hasError) throw error;\n\t\treturn result;\n\t}).catch((err) => {\n\t\tif (!called) return fn();\n\t\tthrow err;\n\t});\n};\n/**\n* Queue a hook to be executed after the current transaction commits.\n* If not in a transaction, the hook will execute immediately.\n*/\nconst queueAfterTransactionHook = async (hook) => {\n\treturn ensureAsyncStorage().then((als) => {\n\t\tconst store = als.getStore();\n\t\tif (store) store.pendingHooks.push(hook);\n\t\telse return hook();\n\t}).catch(() => {\n\t\treturn hook();\n\t});\n};\n//#endregion\nexport { getCurrentAdapter, getCurrentDBAdapterAsyncLocalStorage, queueAfterTransactionHook, runWithAdapter, runWithTransaction };\n", "import { defineRequestState } from \"@better-auth/core/context\";\n//#region src/api/state/oauth.ts\nconst { get: getOAuthState, set: setOAuthState } = defineRequestState(() => null);\n//#endregion\nexport { getOAuthState, setOAuthState };\n", "import { generateRandomString } from \"../crypto/random.mjs\";\nimport { setOAuthState } from \"../api/state/oauth.mjs\";\nimport { StateError, generateGenericState, parseGenericState } from \"../state.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\n//#region src/oauth2/state.ts\nasync function generateState(c, link, additionalData) {\n\tconst callbackURL = c.body?.callbackURL || c.context.options.baseURL;\n\tif (!callbackURL) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.CALLBACK_URL_REQUIRED);\n\tconst codeVerifier = generateRandomString(128);\n\tconst stateData = {\n\t\t...additionalData ? additionalData : {},\n\t\tcallbackURL,\n\t\tcodeVerifier,\n\t\terrorURL: c.body?.errorCallbackURL,\n\t\tnewUserURL: c.body?.newUserCallbackURL,\n\t\tlink,\n\t\texpiresAt: Date.now() + 600 * 1e3,\n\t\trequestSignUp: c.body?.requestSignUp\n\t};\n\tawait setOAuthState(stateData);\n\ttry {\n\t\treturn generateGenericState(c, stateData);\n\t} catch (error) {\n\t\tc.context.logger.error(\"Failed to create verification\", error);\n\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\t\tmessage: \"Unable to create verification\",\n\t\t\tcause: error\n\t\t});\n\t}\n}\nasync function parseState(c) {\n\tconst state = c.query.state || c.body.state;\n\tconst errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;\n\tlet parsedData;\n\ttry {\n\t\tparsedData = await parseGenericState(c, state);\n\t} catch (error) {\n\t\tc.context.logger.error(\"Failed to parse state\", error);\n\t\tif (error instanceof StateError && error.code === \"state_security_mismatch\") throw c.redirect(`${errorURL}?error=state_mismatch`);\n\t\tthrow c.redirect(`${errorURL}?error=please_restart_the_process`);\n\t}\n\tif (!parsedData.errorURL) parsedData.errorURL = errorURL;\n\tif (parsedData) await setOAuthState(parsedData);\n\treturn parsedData;\n}\n//#endregion\nexport { generateState, parseState };\n", "//#region src/utils/hide-metadata.ts\nconst HIDE_METADATA = { scope: \"server\" };\n//#endregion\nexport { HIDE_METADATA };\n", "import { APIError } from \"@better-auth/core/error\";\nimport { APIError as APIError$1 } from \"better-call\";\n//#region src/utils/is-api-error.ts\nfunction isAPIError(error) {\n\treturn error instanceof APIError$1 || error instanceof APIError || error?.name === \"APIError\";\n}\n//#endregion\nexport { isAPIError };\n", "import { APIError, BetterCallError, ValidationError, hideInternalStackFrames, kAPIErrorHeaderSymbol, makeErrorForHideStackFrame, statusCodes } from \"./error.mjs\";\nimport { toResponse } from \"./to-response.mjs\";\nimport { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from \"./cookies.mjs\";\nimport { createInternalContext } from \"./context.mjs\";\nimport { createEndpoint } from \"./endpoint.mjs\";\nimport { createMiddleware } from \"./middleware.mjs\";\nimport { generator, getHTML } from \"./openapi.mjs\";\nimport { createRouter } from \"./router.mjs\";\n\nexport { APIError, BetterCallError, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, kAPIErrorHeaderSymbol, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };", "import { APIError } from \"./error\";\n\nconst jsonContentTypeRegex = /^application\\/([a-z0-9.+-]*\\+)?json/i;\n\nexport async function getBody(request: Request, allowedMediaTypes?: string[]) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\tconst normalizedContentType = contentType.toLowerCase();\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\t// Validate content-type if allowedMediaTypes is provided\n\tif (allowedMediaTypes && allowedMediaTypes.length > 0) {\n\t\tconst isAllowed = allowedMediaTypes.some((allowed) => {\n\t\t\t// Normalize both content types for comparison\n\t\t\tconst normalizedContentTypeBase = normalizedContentType\n\t\t\t\t.split(\";\")[0]!\n\t\t\t\t.trim();\n\t\t\tconst normalizedAllowed = allowed.toLowerCase().trim();\n\t\t\treturn (\n\t\t\t\tnormalizedContentTypeBase === normalizedAllowed ||\n\t\t\t\tnormalizedContentTypeBase.includes(normalizedAllowed)\n\t\t\t);\n\t\t});\n\n\t\tif (!isAllowed) {\n\t\t\tif (!normalizedContentType) {\n\t\t\t\tthrow new APIError(415, {\n\t\t\t\t\tmessage: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(\", \")}`,\n\t\t\t\t\tcode: \"UNSUPPORTED_MEDIA_TYPE\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow new APIError(415, {\n\t\t\t\tmessage: `Content-Type \"${contentType}\" is not allowed. Allowed types: ${allowedMediaTypes.join(\", \")}`,\n\t\t\t\tcode: \"UNSUPPORTED_MEDIA_TYPE\",\n\t\t\t});\n\t\t}\n\t}\n\n\tif (jsonContentTypeRegex.test(normalizedContentType)) {\n\t\treturn await request.json();\n\t}\n\n\tif (normalizedContentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (normalizedContentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (normalizedContentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (normalizedContentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tnormalizedContentType.includes(\"application/pdf\") ||\n\t\tnormalizedContentType.includes(\"image/\") ||\n\t\tnormalizedContentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (\n\t\tnormalizedContentType.includes(\"application/stream\") ||\n\t\trequest.body instanceof ReadableStream\n\t) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n\nexport function isAPIError(error: any): error is APIError {\n\treturn error instanceof APIError || error?.name === \"APIError\";\n}\n\nexport function tryDecode(str: string) {\n\ttry {\n\t\treturn str.includes(\"%\") ? decodeURIComponent(str) : str;\n\t} catch {\n\t\treturn str;\n\t}\n}\n\ntype Success = {\n\tdata: T;\n\terror: null;\n};\n\ntype Failure = {\n\tdata: null;\n\terror: E;\n};\n\ntype Result = Success | Failure;\n\nexport async function tryCatch(\n\tpromise: Promise,\n): Promise> {\n\ttry {\n\t\tconst data = await promise;\n\t\treturn { data, error: null };\n\t} catch (error) {\n\t\treturn { data: null, error: error as E };\n\t}\n}\n\n/**\n * Check if an object is a `Request`\n * - `instanceof`: works for native Request instances\n * - `toString`: handles where instanceof check fails but the object is still a valid Request\n */\nexport function isRequest(obj: unknown): obj is Request {\n\treturn (\n\t\tobj instanceof Request ||\n\t\tObject.prototype.toString.call(obj) === \"[object Request]\"\n\t);\n}\n", "import { getWebcryptoSubtle } from \"@better-auth/utils\";\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nexport const getCryptoKey = async (secret: string | BufferSource) => {\n\tconst secretBuf =\n\t\ttypeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await getWebcryptoSubtle().importKey(\n\t\t\"raw\",\n\t\tsecretBuf,\n\t\talgorithm,\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n};\n\nexport const verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await getWebcryptoSubtle().verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\nconst makeSignature = async (\n\tvalue: string,\n\tsecret: string | BufferSource,\n): Promise => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await getWebcryptoSubtle().sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nexport const signCookieValue = async (\n\tvalue: string,\n\tsecret: string | BufferSource,\n) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\n};\n", "import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (\n\tkey: string,\n\tvalue: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n", "import type { EndpointOptions } from \"./endpoint\";\nimport type { InputContext } from \"./context\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\n\ntype ValidationResponse =\n\t| {\n\t\t\tdata: {\n\t\t\t\tbody: any;\n\t\t\t\tquery: any;\n\t\t\t};\n\t\t\terror: null;\n\t }\n\t| {\n\t\t\tdata: null;\n\t\t\terror: {\n\t\t\t\tmessage: string;\n\t\t\t\tissues: readonly StandardSchemaV1.Issue[];\n\t\t\t};\n\t };\n\n/**\n * Runs validation on body and query\n * @returns error and data object\n */\nexport async function runValidation(\n\toptions: EndpointOptions,\n\tcontext: InputContext = {},\n): Promise {\n\tlet request = {\n\t\tbody: context.body,\n\t\tquery: context.query,\n\t} as {\n\t\tbody: any;\n\t\tquery: any;\n\t};\n\tif (options.body) {\n\t\tconst result = await options.body[\"~standard\"].validate(context.body);\n\t\tif (result.issues) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: fromError(result.issues, \"body\"),\n\t\t\t};\n\t\t}\n\t\trequest.body = result.value;\n\t}\n\n\tif (options.query) {\n\t\tconst result = await options.query[\"~standard\"].validate(context.query);\n\t\tif (result.issues) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: fromError(result.issues, \"query\"),\n\t\t\t};\n\t\t}\n\t\trequest.query = result.value;\n\t}\n\tif (options.requireHeaders && !context.headers) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: { message: \"Headers is required\", issues: [] },\n\t\t};\n\t}\n\tif (options.requireRequest && !context.request) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: { message: \"Request is required\", issues: [] },\n\t\t};\n\t}\n\treturn {\n\t\tdata: request,\n\t\terror: null,\n\t};\n}\n\nfunction fromError(\n\terror: readonly StandardSchemaV1.Issue[],\n\tvalidating: string,\n) {\n\tconst message = error\n\t\t.map((e) => {\n\t\t\treturn `[${e.path?.length ? `${validating}.` + e.path.map((x) => (typeof x === \"object\" ? x.key : x)).join(\".\") : validating}] ${e.message}`;\n\t\t})\n\t\t.join(\"; \");\n\n\treturn {\n\t\tmessage,\n\t\tissues: error,\n\t};\n}\n", "import { ZodObject, ZodOptional, ZodType } from \"zod\";\nimport type { Endpoint, EndpointOptions } from \"./endpoint\";\n\nexport type OpenAPISchemaType =\n\t| \"string\"\n\t| \"number\"\n\t| \"integer\"\n\t| \"boolean\"\n\t| \"array\"\n\t| \"object\";\n\nexport interface OpenAPIParameter {\n\tin: \"query\" | \"path\" | \"header\" | \"cookie\";\n\tname?: string;\n\tdescription?: string;\n\trequired?: boolean;\n\tschema?: {\n\t\ttype: OpenAPISchemaType;\n\t\tformat?: string | undefined;\n\t\titems?: {\n\t\t\ttype: OpenAPISchemaType;\n\t\t};\n\t\tenum?: string[];\n\t\tminLength?: number;\n\t\tdescription?: string | undefined;\n\t\tdefault?: string | undefined;\n\t\texample?: string | undefined;\n\t};\n}\n\nexport interface Path {\n\tget?: {\n\t\ttags?: string[];\n\t\toperationId?: string;\n\t\tdescription?: string;\n\t\tsecurity?: [{ bearerAuth: string[] }];\n\t\tparameters?: OpenAPIParameter[];\n\t\tresponses?: {\n\t\t\t[key in string]: {\n\t\t\t\tdescription?: string;\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n\tpost?: {\n\t\ttags?: string[];\n\t\toperationId?: string;\n\t\tdescription?: string;\n\t\tsecurity?: [{ bearerAuth: string[] }];\n\t\tparameters?: OpenAPIParameter[];\n\t\trequestBody?: {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\tproperties?: Record;\n\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\tresponses?: {\n\t\t\t[key in string]: {\n\t\t\t\tdescription?: string;\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n}\nconst paths: Record = {};\n\nfunction getTypeFromZodType(zodType: ZodType) {\n\tswitch (zodType.constructor.name) {\n\t\tcase \"ZodString\":\n\t\t\treturn \"string\";\n\t\tcase \"ZodNumber\":\n\t\t\treturn \"number\";\n\t\tcase \"ZodBoolean\":\n\t\t\treturn \"boolean\";\n\t\tcase \"ZodObject\":\n\t\t\treturn \"object\";\n\t\tcase \"ZodArray\":\n\t\t\treturn \"array\";\n\t\tdefault:\n\t\t\treturn \"string\";\n\t}\n}\n\nfunction getParameters(options: EndpointOptions) {\n\tconst parameters: OpenAPIParameter[] = [];\n\tif (options.metadata?.openapi?.parameters) {\n\t\tparameters.push(...options.metadata.openapi.parameters);\n\t\treturn parameters;\n\t}\n\tif (options.query instanceof ZodObject) {\n\t\tObject.entries(options.query.shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodObject) {\n\t\t\t\tparameters.push({\n\t\t\t\t\tname: key,\n\t\t\t\t\tin: \"query\",\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\t\t...(\"minLength\" in value && value.minLength\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tminLength: value.minLength as number,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tdescription: value.description,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\treturn parameters;\n}\n\nfunction getRequestBody(options: EndpointOptions): any {\n\tif (options.metadata?.openapi?.requestBody) {\n\t\treturn options.metadata.openapi.requestBody;\n\t}\n\tif (!options.body) return undefined;\n\tif (\n\t\toptions.body instanceof ZodObject ||\n\t\toptions.body instanceof ZodOptional\n\t) {\n\t\t// @ts-ignore\n\t\tconst shape = options.body.shape;\n\t\tif (!shape) return undefined;\n\t\tconst properties: Record = {};\n\t\tconst required: string[] = [];\n\t\tObject.entries(shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodObject) {\n\t\t\t\tproperties[key] = {\n\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\tdescription: value.description,\n\t\t\t\t};\n\t\t\t\tif (!(value instanceof ZodOptional)) {\n\t\t\t\t\trequired.push(key);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\trequired:\n\t\t\t\toptions.body instanceof ZodOptional\n\t\t\t\t\t? false\n\t\t\t\t\t: options.body\n\t\t\t\t\t\t? true\n\t\t\t\t\t\t: false,\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties,\n\t\t\t\t\t\trequired,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction getResponse(responses?: Record) {\n\treturn {\n\t\t\"400\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"message\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Bad Request. Usually due to missing parameters, or invalid parameters.\",\n\t\t},\n\t\t\"401\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"message\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Unauthorized. Due to missing or invalid authentication.\",\n\t\t},\n\t\t\"403\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Forbidden. You do not have permission to access this resource or to perform this action.\",\n\t\t},\n\t\t\"404\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Not Found. The requested resource was not found.\",\n\t\t},\n\t\t\"429\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Too Many Requests. You have exceeded the rate limit. Try again later.\",\n\t\t},\n\t\t\"500\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Internal Server Error. This is a problem with the server that you cannot fix.\",\n\t\t},\n\t\t...responses,\n\t} as any;\n}\n\nexport async function generator(\n\tendpoints: Record,\n\tconfig?: {\n\t\turl: string;\n\t},\n) {\n\tconst components = {\n\t\tschemas: {},\n\t};\n\n\tObject.entries(endpoints).forEach(([_, value]) => {\n\t\tconst options = value.options as EndpointOptions;\n\t\tif (!value.path || options.metadata?.SERVER_ONLY) return;\n\t\tif (options.method === \"GET\") {\n\t\t\tpaths[value.path] = {\n\t\t\t\tget: {\n\t\t\t\t\ttags: [\"Default\", ...(options.metadata?.openapi?.tags || [])],\n\t\t\t\t\tdescription: options.metadata?.openapi?.description,\n\t\t\t\t\toperationId: options.metadata?.openapi?.operationId,\n\t\t\t\t\tsecurity: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbearerAuth: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tparameters: getParameters(options),\n\t\t\t\t\tresponses: getResponse(options.metadata?.openapi?.responses),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (options.method === \"POST\") {\n\t\t\tconst body = getRequestBody(options);\n\t\t\tpaths[value.path] = {\n\t\t\t\tpost: {\n\t\t\t\t\ttags: [\"Default\", ...(options.metadata?.openapi?.tags || [])],\n\t\t\t\t\tdescription: options.metadata?.openapi?.description,\n\t\t\t\t\toperationId: options.metadata?.openapi?.operationId,\n\t\t\t\t\tsecurity: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbearerAuth: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tparameters: getParameters(options),\n\t\t\t\t\t...(body\n\t\t\t\t\t\t? { requestBody: body }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\t\t\t//set body none\n\t\t\t\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\tresponses: getResponse(options.metadata?.openapi?.responses),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t});\n\n\tconst res = {\n\t\topenapi: \"3.1.1\",\n\t\tinfo: {\n\t\t\ttitle: \"Better Auth\",\n\t\t\tdescription: \"API Reference for your Better Auth Instance\",\n\t\t\tversion: \"1.1.0\",\n\t\t},\n\t\tcomponents,\n\t\tsecurity: [\n\t\t\t{\n\t\t\t\tapiKeyCookie: [],\n\t\t\t},\n\t\t],\n\t\tservers: [\n\t\t\t{\n\t\t\t\turl: config?.url,\n\t\t\t},\n\t\t],\n\t\ttags: [\n\t\t\t{\n\t\t\t\tname: \"Default\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.\",\n\t\t\t},\n\t\t],\n\t\tpaths,\n\t};\n\treturn res;\n}\n\nexport const getHTML = (\n\tapiReference: Record,\n\tconfig?: {\n\t\tlogo?: string;\n\t\ttheme?: string;\n\t\ttitle?: string;\n\t\tdescription?: string;\n\t},\n) => `\n\n \n Scalar API Reference\n \n \n \n \n \n ${JSON.stringify(apiReference)}\n \n\t \n\t \n \n`;\n", "const NullProtoObj = /* @__PURE__ */ (() => {\n\tconst e = function() {};\n\treturn e.prototype = Object.create(null), Object.freeze(e.prototype), e;\n})();\n\n/**\n* Create a new router context.\n*/\nfunction createRouter() {\n\treturn {\n\t\troot: { key: \"\" },\n\t\tstatic: new NullProtoObj()\n\t};\n}\n\nfunction splitPath(path) {\n\tconst [_, ...s] = path.split(\"/\");\n\treturn s[s.length - 1] === \"\" ? s.slice(0, -1) : s;\n}\nfunction getMatchParams(segments, paramsMap) {\n\tconst params = new NullProtoObj();\n\tfor (const [index, name] of paramsMap) {\n\t\tconst segment = index < 0 ? segments.slice(-(index + 1)).join(\"/\") : segments[index];\n\t\tif (typeof name === \"string\") params[name] = segment;\n\t\telse {\n\t\t\tconst match = segment.match(name);\n\t\t\tif (match) for (const key in match.groups) params[key] = match.groups[key];\n\t\t}\n\t}\n\treturn params;\n}\n\n/**\n* Add a route to the router context.\n*/\nfunction addRoute(ctx, method = \"\", path, data) {\n\tmethod = method.toUpperCase();\n\tif (path.charCodeAt(0) !== 47) path = `/${path}`;\n\tpath = path.replace(/\\\\:/g, \"%3A\");\n\tconst segments = splitPath(path);\n\tlet node = ctx.root;\n\tlet _unnamedParamIndex = 0;\n\tconst paramsMap = [];\n\tconst paramsRegexp = [];\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tlet segment = segments[i];\n\t\tif (segment.startsWith(\"**\")) {\n\t\t\tif (!node.wildcard) node.wildcard = { key: \"**\" };\n\t\t\tnode = node.wildcard;\n\t\t\tparamsMap.push([\n\t\t\t\t-(i + 1),\n\t\t\t\tsegment.split(\":\")[1] || \"_\",\n\t\t\t\tsegment.length === 2\n\t\t\t]);\n\t\t\tbreak;\n\t\t}\n\t\tif (segment === \"*\" || segment.includes(\":\")) {\n\t\t\tif (!node.param) node.param = { key: \"*\" };\n\t\t\tnode = node.param;\n\t\t\tif (segment === \"*\") paramsMap.push([\n\t\t\t\ti,\n\t\t\t\t`_${_unnamedParamIndex++}`,\n\t\t\t\ttrue\n\t\t\t]);\n\t\t\telse if (segment.includes(\":\", 1)) {\n\t\t\t\tconst regexp = getParamRegexp(segment);\n\t\t\t\tparamsRegexp[i] = regexp;\n\t\t\t\tnode.hasRegexParam = true;\n\t\t\t\tparamsMap.push([\n\t\t\t\t\ti,\n\t\t\t\t\tregexp,\n\t\t\t\t\tfalse\n\t\t\t\t]);\n\t\t\t} else paramsMap.push([\n\t\t\t\ti,\n\t\t\t\tsegment.slice(1),\n\t\t\t\tfalse\n\t\t\t]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"\\\\*\") segment = segments[i] = \"*\";\n\t\telse if (segment === \"\\\\*\\\\*\") segment = segments[i] = \"**\";\n\t\tconst child = node.static?.[segment];\n\t\tif (child) node = child;\n\t\telse {\n\t\t\tconst staticNode = { key: segment };\n\t\t\tif (!node.static) node.static = new NullProtoObj();\n\t\t\tnode.static[segment] = staticNode;\n\t\t\tnode = staticNode;\n\t\t}\n\t}\n\tconst hasParams = paramsMap.length > 0;\n\tif (!node.methods) node.methods = new NullProtoObj();\n\tnode.methods[method] ??= [];\n\tnode.methods[method].push({\n\t\tdata: data || null,\n\t\tparamsRegexp,\n\t\tparamsMap: hasParams ? paramsMap : void 0\n\t});\n\tif (!hasParams) ctx.static[\"/\" + segments.join(\"/\")] = node;\n}\nfunction getParamRegexp(segment) {\n\tconst regex = segment.replace(/:(\\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\\./g, \"\\\\.\");\n\treturn /* @__PURE__ */ new RegExp(`^${regex}$`);\n}\n\n/**\n* Find a route by path.\n*/\nfunction findRoute(ctx, method = \"\", path, opts) {\n\tif (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);\n\tconst staticNode = ctx.static[path];\n\tif (staticNode && staticNode.methods) {\n\t\tconst staticMatch = staticNode.methods[method] || staticNode.methods[\"\"];\n\t\tif (staticMatch !== void 0) return staticMatch[0];\n\t}\n\tconst segments = splitPath(path);\n\tconst match = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0];\n\tif (match === void 0) return;\n\tif (opts?.params === false) return match;\n\treturn {\n\t\tdata: match.data,\n\t\tparams: match.paramsMap ? getMatchParams(segments, match.paramsMap) : void 0\n\t};\n}\nfunction _lookupTree(ctx, node, method, segments, index) {\n\tif (index === segments.length) {\n\t\tif (node.methods) {\n\t\t\tconst match = node.methods[method] || node.methods[\"\"];\n\t\t\tif (match) return match;\n\t\t}\n\t\tif (node.param && node.param.methods) {\n\t\t\tconst match = node.param.methods[method] || node.param.methods[\"\"];\n\t\t\tif (match) {\n\t\t\t\tconst pMap = match[0].paramsMap;\n\t\t\t\tif (pMap?.[pMap?.length - 1]?.[2]) return match;\n\t\t\t}\n\t\t}\n\t\tif (node.wildcard && node.wildcard.methods) {\n\t\t\tconst match = node.wildcard.methods[method] || node.wildcard.methods[\"\"];\n\t\t\tif (match) {\n\t\t\t\tconst pMap = match[0].paramsMap;\n\t\t\t\tif (pMap?.[pMap?.length - 1]?.[2]) return match;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\tconst segment = segments[index];\n\tif (node.static) {\n\t\tconst staticChild = node.static[segment];\n\t\tif (staticChild) {\n\t\t\tconst match = _lookupTree(ctx, staticChild, method, segments, index + 1);\n\t\t\tif (match) return match;\n\t\t}\n\t}\n\tif (node.param) {\n\t\tconst match = _lookupTree(ctx, node.param, method, segments, index + 1);\n\t\tif (match) {\n\t\t\tif (node.param.hasRegexParam) {\n\t\t\t\tconst exactMatch = match.find((m) => m.paramsRegexp[index]?.test(segment)) || match.find((m) => !m.paramsRegexp[index]);\n\t\t\t\treturn exactMatch ? [exactMatch] : void 0;\n\t\t\t}\n\t\t\treturn match;\n\t\t}\n\t}\n\tif (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[\"\"];\n}\n\n/**\n* Remove a route from the router context.\n*/\nfunction removeRoute(ctx, method, path) {\n\tconst segments = splitPath(path);\n\treturn _remove(ctx.root, method || \"\", segments, 0);\n}\nfunction _remove(node, method, segments, index) {\n\tif (index === segments.length) {\n\t\tif (node.methods && method in node.methods) {\n\t\t\tdelete node.methods[method];\n\t\t\tif (Object.keys(node.methods).length === 0) node.methods = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tconst segment = segments[index];\n\tif (segment === \"*\") {\n\t\tif (node.param) {\n\t\t\t_remove(node.param, method, segments, index + 1);\n\t\t\tif (_isEmptyNode(node.param)) node.param = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tif (segment.startsWith(\"**\")) {\n\t\tif (node.wildcard) {\n\t\t\t_remove(node.wildcard, method, segments, index + 1);\n\t\t\tif (_isEmptyNode(node.wildcard)) node.wildcard = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tconst childNode = node.static?.[segment];\n\tif (childNode) {\n\t\t_remove(childNode, method, segments, index + 1);\n\t\tif (_isEmptyNode(childNode)) {\n\t\t\tdelete node.static[segment];\n\t\t\tif (Object.keys(node.static).length === 0) node.static = void 0;\n\t\t}\n\t}\n}\nfunction _isEmptyNode(node) {\n\treturn node.methods === void 0 && node.static === void 0 && node.param === void 0 && node.wildcard === void 0;\n}\n\n/**\n* Find all route patterns that match the given path.\n*/\nfunction findAllRoutes(ctx, method = \"\", path, opts) {\n\tif (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);\n\tconst segments = splitPath(path);\n\tconst matches = _findAll(ctx, ctx.root, method, segments, 0);\n\tif (opts?.params === false) return matches;\n\treturn matches.map((m) => {\n\t\treturn {\n\t\t\tdata: m.data,\n\t\t\tparams: m.paramsMap ? getMatchParams(segments, m.paramsMap) : void 0\n\t\t};\n\t});\n}\nfunction _findAll(ctx, node, method, segments, index, matches = []) {\n\tconst segment = segments[index];\n\tif (node.wildcard && node.wildcard.methods) {\n\t\tconst match = node.wildcard.methods[method] || node.wildcard.methods[\"\"];\n\t\tif (match) matches.push(...match);\n\t}\n\tif (node.param) {\n\t\t_findAll(ctx, node.param, method, segments, index + 1, matches);\n\t\tif (index === segments.length && node.param.methods) {\n\t\t\tconst match = node.param.methods[method] || node.param.methods[\"\"];\n\t\t\tif (match) {\n\t\t\t\tconst pMap = match[0].paramsMap;\n\t\t\t\tif (pMap?.[pMap?.length - 1]?.[2]) matches.push(...match);\n\t\t\t}\n\t\t}\n\t}\n\tconst staticChild = node.static?.[segment];\n\tif (staticChild) _findAll(ctx, staticChild, method, segments, index + 1, matches);\n\tif (index === segments.length && node.methods) {\n\t\tconst match = node.methods[method] || node.methods[\"\"];\n\t\tif (match) matches.push(...match);\n\t}\n\treturn matches;\n}\n\nfunction routeToRegExp(route = \"/\") {\n\tconst reSegments = [];\n\tlet idCtr = 0;\n\tfor (const segment of route.split(\"/\")) {\n\t\tif (!segment) continue;\n\t\tif (segment === \"*\") reSegments.push(`(?<_${idCtr++}>[^/]*)`);\n\t\telse if (segment.startsWith(\"**\")) reSegments.push(segment === \"**\" ? \"?(?<_>.*)\" : `?(?<${segment.slice(3)}>.+)`);\n\t\telse if (segment.includes(\":\")) reSegments.push(segment.replace(/:(\\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\\./g, \"\\\\.\"));\n\t\telse reSegments.push(segment);\n\t}\n\treturn /* @__PURE__ */ new RegExp(`^/${reSegments.join(\"/\")}/?$`);\n}\n\nexport { NullProtoObj, addRoute, createRouter, findAllRoutes, findRoute, removeRoute, routeToRegExp };", "import {\n\taddRoute,\n\tcreateRouter as createRou3Router,\n\tfindAllRoutes,\n\tfindRoute,\n} from \"rou3\";\nimport { type Endpoint, createEndpoint } from \"./endpoint\";\nimport type { Middleware } from \"./middleware\";\nimport { generator, getHTML } from \"./openapi\";\nimport { toResponse } from \"./to-response\";\nimport { getBody, isAPIError, isRequest } from \"./utils\";\n\nexport interface RouterConfig {\n\tthrowError?: boolean;\n\tbasePath?: string;\n\trouterMiddleware?: Array<{\n\t\tpath: string;\n\t\tmiddleware: Middleware;\n\t}>;\n\t/**\n\t * additional Context that needs to passed to endpoints\n\t *\n\t * this will be available on `ctx.context` on endpoints\n\t */\n\trouterContext?: Record;\n\t/**\n\t * A callback to run before any response\n\t */\n\tonResponse?: (response: Response, request: Request) => any | Promise;\n\t/**\n\t * A callback to run before any request\n\t */\n\tonRequest?: (request: Request) => any | Promise;\n\t/**\n\t * A callback to run when an error is thrown in the router or middleware.\n\t *\n\t * @param error - the error that was thrown in the router or middleware.\n\t * @returns a Response object that will be returned to the client.\n\t */\n\tonError?: (\n\t\terror: unknown,\n\t\trequest: Request,\n\t) => void | Promise | Response | Promise;\n\t/**\n\t * List of allowed media types (MIME types) for the router\n\t *\n\t * if provided, only the media types in the list will be allowed to be passed in the body.\n\t *\n\t * If an endpoint has allowed media types, it will override the router's allowed media types.\n\t *\n\t * @example\n\t * ```ts\n\t * const router = createRouter({\n\t * \t\tallowedMediaTypes: [\"application/json\", \"application/x-www-form-urlencoded\"],\n\t * \t})\n\t */\n\tallowedMediaTypes?: string[];\n\t/**\n\t * Skip trailing slashes\n\t *\n\t * @default false\n\t */\n\tskipTrailingSlashes?: boolean;\n\t/**\n\t * Open API route configuration\n\t */\n\topenapi?: {\n\t\t/**\n\t\t * Disable openapi route\n\t\t *\n\t\t * @default false\n\t\t */\n\t\tdisabled?: boolean;\n\t\t/**\n\t\t * A path to display open api using scalar\n\t\t *\n\t\t * @default \"/api/reference\"\n\t\t */\n\t\tpath?: string;\n\t\t/**\n\t\t * Scalar Configuration\n\t\t */\n\t\tscalar?: {\n\t\t\t/**\n\t\t\t * Title\n\t\t\t * @default \"Open API Reference\"\n\t\t\t */\n\t\t\ttitle?: string;\n\t\t\t/**\n\t\t\t * Description\n\t\t\t *\n\t\t\t * @default \"Better Call Open API Reference\"\n\t\t\t */\n\t\t\tdescription?: string;\n\t\t\t/**\n\t\t\t * Logo URL\n\t\t\t */\n\t\t\tlogo?: string;\n\t\t\t/**\n\t\t\t * Scalar theme\n\t\t\t * @default \"saturn\"\n\t\t\t */\n\t\t\ttheme?: string;\n\t\t};\n\t};\n}\n\nexport const createRouter = <\n\tE extends Record,\n\tConfig extends RouterConfig,\n>(\n\tendpoints: E,\n\tconfig?: Config,\n) => {\n\tif (!config?.openapi?.disabled) {\n\t\tconst openapi = {\n\t\t\tpath: \"/api/reference\",\n\t\t\t...config?.openapi,\n\t\t};\n\t\t//@ts-expect-error\n\t\tendpoints[\"openapi\"] = createEndpoint(\n\t\t\topenapi.path,\n\t\t\t{\n\t\t\t\tmethod: \"GET\",\n\t\t\t},\n\t\t\tasync (c) => {\n\t\t\t\tconst schema = await generator(endpoints);\n\t\t\t\treturn new Response(getHTML(schema, openapi.scalar), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t}\n\tconst router = createRou3Router();\n\tconst middlewareRouter = createRou3Router();\n\n\tfor (const endpoint of Object.values(endpoints)) {\n\t\tif (!endpoint.options || !endpoint.path) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (endpoint.options?.metadata?.SERVER_ONLY) continue;\n\n\t\tconst methods = Array.isArray(endpoint.options?.method)\n\t\t\t? endpoint.options.method\n\t\t\t: [endpoint.options?.method];\n\n\t\tfor (const method of methods) {\n\t\t\taddRoute(router, method, endpoint.path, endpoint);\n\t\t}\n\t}\n\n\tif (config?.routerMiddleware?.length) {\n\t\tfor (const { path, middleware } of config.routerMiddleware) {\n\t\t\taddRoute(middlewareRouter, \"*\", path, middleware);\n\t\t}\n\t}\n\n\tconst processRequest = async (request: Request) => {\n\t\tconst url = new URL(request.url);\n\t\tconst pathname = url.pathname;\n\t\tconst path =\n\t\t\tconfig?.basePath && config.basePath !== \"/\"\n\t\t\t\t? pathname\n\t\t\t\t\t\t.split(config.basePath)\n\t\t\t\t\t\t.reduce((acc, curr, index) => {\n\t\t\t\t\t\t\tif (index !== 0) {\n\t\t\t\t\t\t\t\tif (index > 1) {\n\t\t\t\t\t\t\t\t\tacc.push(`${config.basePath}${curr}`);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tacc.push(curr);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t}, [] as string[])\n\t\t\t\t\t\t.join(\"\")\n\t\t\t\t: url.pathname;\n\t\tif (!path?.length) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\n\t\t// Reject paths with consecutive slashes\n\t\tif (/\\/{2,}/.test(path)) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\n\t\tconst route = findRoute(router, request.method, path) as {\n\t\t\tdata: Endpoint & { path: string };\n\t\t\tparams: Record;\n\t\t};\n\t\tconst hasTrailingSlash = path.endsWith(\"/\");\n\t\tconst routeHasTrailingSlash = route?.data?.path?.endsWith(\"/\");\n\n\t\t// If the path has a trailing slash and the route doesn't have a trailing slash and skipTrailingSlashes is not set, return 404\n\t\tif (\n\t\t\thasTrailingSlash !== routeHasTrailingSlash &&\n\t\t\t!config?.skipTrailingSlashes\n\t\t) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\t\tif (!route?.data)\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\n\t\tconst query: Record = {};\n\t\turl.searchParams.forEach((value, key) => {\n\t\t\tif (key in query) {\n\t\t\t\tif (Array.isArray(query[key])) {\n\t\t\t\t\t(query[key] as string[]).push(value);\n\t\t\t\t} else {\n\t\t\t\t\tquery[key] = [query[key] as string, value];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tquery[key] = value;\n\t\t\t}\n\t\t});\n\n\t\tconst handler = route.data as Endpoint;\n\n\t\ttry {\n\t\t\t// Determine which allowedMediaTypes to use: endpoint-level overrides router-level\n\t\t\tconst allowedMediaTypes =\n\t\t\t\thandler.options.metadata?.allowedMediaTypes ||\n\t\t\t\tconfig?.allowedMediaTypes;\n\t\t\tconst context = {\n\t\t\t\tpath,\n\t\t\t\tmethod: request.method as \"GET\",\n\t\t\t\theaders: request.headers,\n\t\t\t\tparams: route.params\n\t\t\t\t\t? (JSON.parse(JSON.stringify(route.params)) as any)\n\t\t\t\t\t: {},\n\t\t\t\trequest: request,\n\t\t\t\tbody: handler.options.disableBody\n\t\t\t\t\t? undefined\n\t\t\t\t\t: await getBody(\n\t\t\t\t\t\t\thandler.options.cloneRequest ? request.clone() : request,\n\t\t\t\t\t\t\tallowedMediaTypes,\n\t\t\t\t\t\t),\n\t\t\t\tquery,\n\t\t\t\t_flag: \"router\" as const,\n\t\t\t\tasResponse: true,\n\t\t\t\tcontext: config?.routerContext,\n\t\t\t};\n\t\t\tconst middlewareRoutes = findAllRoutes(middlewareRouter, \"*\", path);\n\t\t\tif (middlewareRoutes?.length) {\n\t\t\t\tfor (const { data: middleware, params } of middlewareRoutes) {\n\t\t\t\t\tconst res = await (middleware as Endpoint)({\n\t\t\t\t\t\t...context,\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tasResponse: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (res instanceof Response) return res;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst response = (await handler(context)) as Response;\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tif (config?.onError) {\n\t\t\t\ttry {\n\t\t\t\t\tconst errorResponse = await config.onError(error, request);\n\n\t\t\t\t\tif (errorResponse instanceof Response) {\n\t\t\t\t\t\treturn toResponse(errorResponse);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isAPIError(error)) {\n\t\t\t\t\t\treturn toResponse(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (config?.throwError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isAPIError(error)) {\n\t\t\t\treturn toResponse(error);\n\t\t\t}\n\n\t\t\tconsole.error(`# SERVER_ERROR: `, error);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: \"Internal Server Error\",\n\t\t\t});\n\t\t}\n\t};\n\n\treturn {\n\t\thandler: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = isRequest(onReq) ? onReq : request;\n\t\t\tconst res = await processRequest(req);\n\t\t\tconst onRes = await config?.onResponse?.(res, req);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType;\n", "import { runWithEndpointContext } from \"../context/endpoint-context.mjs\";\nimport { createEndpoint, createMiddleware } from \"better-call\";\n//#region src/api/index.ts\nconst optionsMiddleware = createMiddleware(async () => {\n\t/**\n\t* This will be passed on the instance of\n\t* the context. Used to infer the type\n\t* here.\n\t*/\n\treturn {};\n});\nconst createAuthMiddleware = createMiddleware.create({ use: [optionsMiddleware, createMiddleware(async () => {\n\treturn {};\n})] });\nconst use = [optionsMiddleware];\nfunction createAuthEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) {\n\tconst path = typeof pathOrOptions === \"string\" ? pathOrOptions : void 0;\n\tconst options = typeof handlerOrOptions === \"object\" ? handlerOrOptions : pathOrOptions;\n\tconst handler = typeof handlerOrOptions === \"function\" ? handlerOrOptions : handlerOrNever;\n\tif (path) return createEndpoint(path, {\n\t\t...options,\n\t\tuse: [...options?.use || [], ...use]\n\t}, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));\n\treturn createEndpoint({\n\t\t...options,\n\t\tuse: [...options?.use || [], ...use]\n\t}, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));\n}\n//#endregion\nexport { createAuthEndpoint, createAuthMiddleware, optionsMiddleware };\n", "import { wildcardMatch } from \"../utils/wildcard.mjs\";\nimport { getHost, getOrigin, getProtocol } from \"../utils/url.mjs\";\n//#region src/auth/trusted-origins.ts\n/**\n* Matches the given url against an origin or origin pattern\n* See \"options.trustedOrigins\" for details of supported patterns\n*\n* @param url The url to test\n* @param pattern The origin pattern\n* @param [settings] Specify supported pattern matching settings\n* @returns {boolean} true if the URL matches the origin pattern, false otherwise.\n*/\nconst matchesOriginPattern = (url, pattern, settings) => {\n\tif (url.startsWith(\"/\")) {\n\t\tif (settings?.allowRelativePaths) return url.startsWith(\"/\") && /^\\/(?!\\/|\\\\|%2f|%5c)[\\w\\-.\\+/@]*(?:\\?[\\w\\-.\\+/=&%@]*)?$/.test(url);\n\t\treturn false;\n\t}\n\tif (pattern.includes(\"*\") || pattern.includes(\"?\")) {\n\t\tif (pattern.includes(\"://\")) return wildcardMatch(pattern)(getOrigin(url) || url);\n\t\tconst host = getHost(url);\n\t\tif (!host) return false;\n\t\treturn wildcardMatch(pattern)(host);\n\t}\n\tconst protocol = getProtocol(url);\n\treturn protocol === \"http:\" || protocol === \"https:\" || !protocol ? pattern === getOrigin(url) : url.startsWith(pattern);\n};\n//#endregion\nexport { matchesOriginPattern };\n", "import { matchesOriginPattern } from \"../../auth/trusted-origins.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { normalizePathname } from \"@better-auth/core/utils/url\";\nimport { createAuthMiddleware } from \"@better-auth/core/api\";\nimport { deprecate } from \"@better-auth/core/utils/deprecate\";\n//#region src/api/middlewares/origin-check.ts\n/**\n* Checks if CSRF should be skipped for backward compatibility.\n* Previously, disableOriginCheck also disabled CSRF checks.\n* This maintains that behavior when disableCSRFCheck isn't explicitly set.\n* Only triggers for skipOriginCheck === true, not for path arrays.\n*/\nfunction shouldSkipCSRFForBackwardCompat(ctx) {\n\treturn ctx.context.skipOriginCheck === true && ctx.context.options.advanced?.disableCSRFCheck === void 0;\n}\n/**\n* Checks if the origin check should be skipped for the current request.\n* Handles both boolean (skip all) and array (skip specific paths) configurations.\n*/\nfunction shouldSkipOriginCheck(ctx) {\n\tconst skipOriginCheck = ctx.context.skipOriginCheck;\n\tif (skipOriginCheck === true) return true;\n\tif (Array.isArray(skipOriginCheck) && ctx.request) try {\n\t\tconst basePath = new URL(ctx.context.baseURL).pathname;\n\t\tconst currentPath = normalizePathname(ctx.request.url, basePath);\n\t\treturn skipOriginCheck.some((skipPath) => currentPath.startsWith(skipPath));\n\t} catch {}\n\treturn false;\n}\n/**\n* Logs deprecation warning for users relying on coupled behavior.\n* Only logs if user explicitly set disableOriginCheck (not test environment default).\n*/\nconst logBackwardCompatWarning = deprecate(function logBackwardCompatWarning() {}, \"disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config.\");\n/**\n* A middleware to validate callbackURL and origin against trustedOrigins.\n* Also handles CSRF protection using Fetch Metadata for first-login scenarios.\n*/\nconst originCheckMiddleware = createAuthMiddleware(async (ctx) => {\n\tif (ctx.request?.method === \"GET\" || ctx.request?.method === \"OPTIONS\" || ctx.request?.method === \"HEAD\" || !ctx.request) return;\n\tawait validateOrigin(ctx);\n\tif (shouldSkipOriginCheck(ctx)) return;\n\tconst { body, query } = ctx;\n\tconst callbackURL = body?.callbackURL || query?.callbackURL;\n\tconst redirectURL = body?.redirectTo;\n\tconst errorCallbackURL = body?.errorCallbackURL;\n\tconst newUserCallbackURL = body?.newUserCallbackURL;\n\tconst validateURL = (url, label) => {\n\t\tif (!url) return;\n\t\tif (!ctx.context.isTrustedOrigin(url, { allowRelativePaths: label !== \"origin\" })) {\n\t\t\tctx.context.logger.error(`Invalid ${label}: ${url}`);\n\t\t\tctx.context.logger.info(`If it's a valid URL, please add ${url} to trustedOrigins in your auth config\\n`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`);\n\t\t\tif (label === \"origin\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ORIGIN);\n\t\t\tif (label === \"callbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_CALLBACK_URL);\n\t\t\tif (label === \"redirectURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_REDIRECT_URL);\n\t\t\tif (label === \"errorCallbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);\n\t\t\tif (label === \"newUserCallbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);\n\t\t\tthrow APIError.fromStatus(\"FORBIDDEN\", { message: `Invalid ${label}` });\n\t\t}\n\t};\n\tcallbackURL && validateURL(callbackURL, \"callbackURL\");\n\tredirectURL && validateURL(redirectURL, \"redirectURL\");\n\terrorCallbackURL && validateURL(errorCallbackURL, \"errorCallbackURL\");\n\tnewUserCallbackURL && validateURL(newUserCallbackURL, \"newUserCallbackURL\");\n});\nconst originCheck = (getValue) => createAuthMiddleware(async (ctx) => {\n\tif (!ctx.request) return;\n\tif (shouldSkipOriginCheck(ctx)) return;\n\tconst callbackURL = getValue(ctx);\n\tconst validateURL = (url, label) => {\n\t\tif (!url) return;\n\t\tif (!ctx.context.isTrustedOrigin(url, { allowRelativePaths: label !== \"origin\" })) {\n\t\t\tctx.context.logger.error(`Invalid ${label}: ${url}`);\n\t\t\tctx.context.logger.info(`If it's a valid URL, please add ${url} to trustedOrigins in your auth config\\n`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`);\n\t\t\tif (label === \"origin\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ORIGIN);\n\t\t\tif (label === \"callbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_CALLBACK_URL);\n\t\t\tif (label === \"redirectURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_REDIRECT_URL);\n\t\t\tif (label === \"errorCallbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);\n\t\t\tif (label === \"newUserCallbackURL\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);\n\t\t\tthrow APIError.fromStatus(\"FORBIDDEN\", { message: `Invalid ${label}` });\n\t\t}\n\t};\n\tconst callbacks = Array.isArray(callbackURL) ? callbackURL : [callbackURL];\n\tfor (const url of callbacks) validateURL(url, \"callbackURL\");\n});\n/**\n* Validates origin header against trusted origins.\n* @param ctx - The endpoint context\n* @param forceValidate - If true, always validate origin regardless of cookies/skip flags\n*/\nasync function validateOrigin(ctx, forceValidate = false) {\n\tconst headers = ctx.request?.headers;\n\tif (!headers || !ctx.request) return;\n\tconst originHeader = headers.get(\"origin\") || headers.get(\"referer\") || \"\";\n\tconst useCookies = headers.has(\"cookie\");\n\tif (ctx.context.skipCSRFCheck) return;\n\tif (shouldSkipCSRFForBackwardCompat(ctx)) {\n\t\tctx.context.options.advanced?.disableOriginCheck === true && logBackwardCompatWarning();\n\t\treturn;\n\t}\n\tif (shouldSkipOriginCheck(ctx)) return;\n\tif (!(forceValidate || useCookies)) return;\n\tif (!originHeader || originHeader === \"null\") throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN);\n\tconst trustedOrigins = Array.isArray(ctx.context.options.trustedOrigins) ? ctx.context.trustedOrigins : [...ctx.context.trustedOrigins, ...(await ctx.context.options.trustedOrigins?.(ctx.request))?.filter((v) => Boolean(v)) || []];\n\tif (!trustedOrigins.some((origin) => matchesOriginPattern(originHeader, origin))) {\n\t\tctx.context.logger.error(`Invalid origin: ${originHeader}`);\n\t\tctx.context.logger.info(`If it's a valid URL, please add ${originHeader} to trustedOrigins in your auth config\\n`, `Current list of trustedOrigins: ${trustedOrigins}`);\n\t\tthrow APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.INVALID_ORIGIN);\n\t}\n}\n/**\n* Middleware for CSRF protection using Fetch Metadata headers.\n* This prevents cross-site navigation login attacks while supporting progressive enhancement.\n*/\nconst formCsrfMiddleware = createAuthMiddleware(async (ctx) => {\n\tif (!ctx.request) return;\n\tawait validateFormCsrf(ctx);\n});\n/**\n* Validates CSRF protection for first-login scenarios using Fetch Metadata headers.\n* This prevents cross-site form submission attacks while supporting progressive enhancement.\n*/\nasync function validateFormCsrf(ctx) {\n\tconst req = ctx.request;\n\tif (!req) return;\n\tif (ctx.context.skipCSRFCheck) return;\n\tif (shouldSkipCSRFForBackwardCompat(ctx)) return;\n\tconst headers = req.headers;\n\tif (headers.has(\"cookie\")) return await validateOrigin(ctx);\n\tconst site = headers.get(\"Sec-Fetch-Site\");\n\tconst mode = headers.get(\"Sec-Fetch-Mode\");\n\tconst dest = headers.get(\"Sec-Fetch-Dest\");\n\tif (Boolean(site && site.trim() || mode && mode.trim() || dest && dest.trim())) {\n\t\tif (site === \"cross-site\" && mode === \"navigate\") {\n\t\t\tctx.context.logger.error(\"Blocked cross-site navigation login attempt (CSRF protection)\", {\n\t\t\t\tsecFetchSite: site,\n\t\t\t\tsecFetchMode: mode,\n\t\t\t\tsecFetchDest: dest\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);\n\t\t}\n\t\treturn await validateOrigin(ctx, true);\n\t}\n}\n//#endregion\nexport { formCsrfMiddleware, originCheck, originCheckMiddleware };\n", "//#region src/utils/url.ts\n/**\n* Normalizes a request pathname by removing the basePath prefix and trailing slashes.\n* This is useful for matching paths against configured path lists.\n*\n* @param requestUrl - The full request URL\n* @param basePath - The base path of the auth API (e.g., \"/api/auth\")\n* @returns The normalized path without basePath prefix or trailing slashes,\n* or \"/\" if URL parsing fails\n*\n* @example\n* normalizePathname(\"http://localhost:3000/api/auth/sso/saml2/callback/provider1\", \"/api/auth\")\n* // Returns: \"/sso/saml2/callback/provider1\"\n*\n* normalizePathname(\"http://localhost:3000/sso/saml2/callback/provider1/\", \"/\")\n* // Returns: \"/sso/saml2/callback/provider1\"\n*/\nfunction normalizePathname(requestUrl, basePath) {\n\tlet pathname;\n\ttry {\n\t\tpathname = new URL(requestUrl).pathname.replace(/\\/+$/, \"\") || \"/\";\n\t} catch {\n\t\treturn \"/\";\n\t}\n\tif (basePath === \"/\" || basePath === \"\") return pathname;\n\tif (pathname === basePath) return \"/\";\n\tif (pathname.startsWith(basePath + \"/\")) return pathname.slice(basePath.length).replace(/\\/+$/, \"\") || \"/\";\n\treturn pathname;\n}\n//#endregion\nexport { normalizePathname };\n", "//#region src/utils/deprecate.ts\n/**\n* Wraps a function to log a deprecation warning at once.\n*/\nfunction deprecate(fn, message, logger) {\n\tlet warned = false;\n\treturn function(...args) {\n\t\tif (!warned) {\n\t\t\t(logger?.warn ?? console.warn)(`[Deprecation] ${message}`);\n\t\t\twarned = true;\n\t\t}\n\t\treturn fn.apply(this, args);\n\t};\n}\n//#endregion\nexport { deprecate };\n", "import { isDevelopment, isTest } from \"@better-auth/core/env\";\nimport { isValidIP, normalizeIP } from \"@better-auth/core/utils/ip\";\n//#region src/utils/get-request-ip.ts\nconst LOCALHOST_IP = \"127.0.0.1\";\nfunction getIp(req, options) {\n\tif (options.advanced?.ipAddress?.disableIpTracking) return null;\n\tconst headers = \"headers\" in req ? req.headers : req;\n\tconst ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || [\"x-forwarded-for\"];\n\tfor (const key of ipHeaders) {\n\t\tconst value = \"get\" in headers ? headers.get(key) : headers[key];\n\t\tif (typeof value === \"string\") {\n\t\t\tconst ip = value.split(\",\")[0].trim();\n\t\t\tif (isValidIP(ip)) return normalizeIP(ip, { ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet });\n\t\t}\n\t}\n\tif (isTest() || isDevelopment()) return LOCALHOST_IP;\n\treturn null;\n}\n//#endregion\nexport { getIp };\n", "import * as z from \"zod\";\n//#region src/utils/ip.ts\n/**\n* Checks if an IP is valid IPv4 or IPv6\n*/\nfunction isValidIP(ip) {\n\treturn z.ipv4().safeParse(ip).success || z.ipv6().safeParse(ip).success;\n}\n/**\n* Checks if an IP is IPv6\n*/\nfunction isIPv6(ip) {\n\treturn z.ipv6().safeParse(ip).success;\n}\n/**\n* Converts IPv4-mapped IPv6 address to IPv4\n* e.g., \"::ffff:192.0.2.1\" -> \"192.0.2.1\"\n*/\nfunction extractIPv4FromMapped(ipv6) {\n\tconst lower = ipv6.toLowerCase();\n\tif (lower.startsWith(\"::ffff:\")) {\n\t\tconst ipv4Part = lower.substring(7);\n\t\tif (z.ipv4().safeParse(ipv4Part).success) return ipv4Part;\n\t}\n\tconst parts = ipv6.split(\":\");\n\tif (parts.length === 7 && parts[5]?.toLowerCase() === \"ffff\") {\n\t\tconst ipv4Part = parts[6];\n\t\tif (ipv4Part && z.ipv4().safeParse(ipv4Part).success) return ipv4Part;\n\t}\n\tif (lower.includes(\"::ffff:\") || lower.includes(\":ffff:\")) {\n\t\tconst groups = expandIPv6(ipv6);\n\t\tif (groups.length === 8 && groups[0] === \"0000\" && groups[1] === \"0000\" && groups[2] === \"0000\" && groups[3] === \"0000\" && groups[4] === \"0000\" && groups[5] === \"ffff\" && groups[6] && groups[7]) return `${Number.parseInt(groups[6].substring(0, 2), 16)}.${Number.parseInt(groups[6].substring(2, 4), 16)}.${Number.parseInt(groups[7].substring(0, 2), 16)}.${Number.parseInt(groups[7].substring(2, 4), 16)}`;\n\t}\n\treturn null;\n}\n/**\n* Expands a compressed IPv6 address to full form\n* e.g., \"2001:db8::1\" -> [\"2001\", \"0db8\", \"0000\", \"0000\", \"0000\", \"0000\", \"0000\", \"0001\"]\n*/\nfunction expandIPv6(ipv6) {\n\tif (ipv6.includes(\"::\")) {\n\t\tconst sides = ipv6.split(\"::\");\n\t\tconst left = sides[0] ? sides[0].split(\":\") : [];\n\t\tconst right = sides[1] ? sides[1].split(\":\") : [];\n\t\tconst missingGroups = 8 - left.length - right.length;\n\t\tconst zeros = Array(missingGroups).fill(\"0000\");\n\t\tconst paddedLeft = left.map((g) => g.padStart(4, \"0\"));\n\t\tconst paddedRight = right.map((g) => g.padStart(4, \"0\"));\n\t\treturn [\n\t\t\t...paddedLeft,\n\t\t\t...zeros,\n\t\t\t...paddedRight\n\t\t];\n\t}\n\treturn ipv6.split(\":\").map((g) => g.padStart(4, \"0\"));\n}\n/**\n* Normalizes an IPv6 address to canonical form\n* e.g., \"2001:DB8::1\" -> \"2001:0db8:0000:0000:0000:0000:0000:0001\"\n*/\nfunction normalizeIPv6(ipv6, subnetPrefix) {\n\tconst groups = expandIPv6(ipv6);\n\tif (subnetPrefix && subnetPrefix < 128) {\n\t\tlet bitsRemaining = subnetPrefix;\n\t\treturn groups.map((group) => {\n\t\t\tif (bitsRemaining <= 0) return \"0000\";\n\t\t\tif (bitsRemaining >= 16) {\n\t\t\t\tbitsRemaining -= 16;\n\t\t\t\treturn group;\n\t\t\t}\n\t\t\tconst masked = Number.parseInt(group, 16) & (65535 << 16 - bitsRemaining & 65535);\n\t\t\tbitsRemaining = 0;\n\t\t\treturn masked.toString(16).padStart(4, \"0\");\n\t\t}).join(\":\").toLowerCase();\n\t}\n\treturn groups.join(\":\").toLowerCase();\n}\n/**\n* Normalizes an IP address (IPv4 or IPv6) for consistent rate limiting.\n*\n* @param ip - The IP address to normalize\n* @param options - Normalization options\n* @returns Normalized IP address\n*\n* @example\n* normalizeIP(\"2001:DB8::1\")\n* // -> \"2001:0db8:0000:0000:0000:0000:0000:0000\"\n*\n* @example\n* normalizeIP(\"::ffff:192.0.2.1\")\n* // -> \"192.0.2.1\" (converted to IPv4)\n*\n* @example\n* normalizeIP(\"2001:db8::1\", { ipv6Subnet: 64 })\n* // -> \"2001:0db8:0000:0000:0000:0000:0000:0000\" (subnet /64)\n*/\nfunction normalizeIP(ip, options = {}) {\n\tif (z.ipv4().safeParse(ip).success) return ip.toLowerCase();\n\tif (!isIPv6(ip)) return ip.toLowerCase();\n\tconst ipv4 = extractIPv4FromMapped(ip);\n\tif (ipv4) return ipv4.toLowerCase();\n\treturn normalizeIPv6(ip, options.ipv6Subnet || 64);\n}\n/**\n* Creates a rate limit key from IP and path\n* Uses a separator to prevent collision attacks\n*\n* @param ip - The IP address (should be normalized)\n* @param path - The request path\n* @returns Rate limit key\n*/\nfunction createRateLimitKey(ip, path) {\n\treturn `${ip}|${path}`;\n}\n//#endregion\nexport { createRateLimitKey, isValidIP, normalizeIP };\n", "import { wildcardMatch } from \"../../utils/wildcard.mjs\";\nimport { getIp } from \"../../utils/get-request-ip.mjs\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { normalizePathname } from \"@better-auth/core/utils/url\";\nimport { createRateLimitKey } from \"@better-auth/core/utils/ip\";\n//#region src/api/rate-limiter/index.ts\nconst memory = /* @__PURE__ */ new Map();\nfunction shouldRateLimit(max, window, rateLimitData) {\n\tconst now = Date.now();\n\tconst windowInMs = window * 1e3;\n\treturn now - rateLimitData.lastRequest < windowInMs && rateLimitData.count >= max;\n}\nfunction rateLimitResponse(retryAfter) {\n\treturn new Response(JSON.stringify({ message: \"Too many requests. Please try again later.\" }), {\n\t\tstatus: 429,\n\t\tstatusText: \"Too Many Requests\",\n\t\theaders: { \"X-Retry-After\": retryAfter.toString() }\n\t});\n}\nfunction getRetryAfter(lastRequest, window) {\n\tconst now = Date.now();\n\tconst windowInMs = window * 1e3;\n\treturn Math.ceil((lastRequest + windowInMs - now) / 1e3);\n}\nfunction createDatabaseStorageWrapper(ctx) {\n\tconst model = \"rateLimit\";\n\tconst db = ctx.adapter;\n\treturn {\n\t\tget: async (key) => {\n\t\t\tconst data = (await db.findMany({\n\t\t\t\tmodel,\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"key\",\n\t\t\t\t\tvalue: key\n\t\t\t\t}]\n\t\t\t}))[0];\n\t\t\tif (typeof data?.lastRequest === \"bigint\") data.lastRequest = Number(data.lastRequest);\n\t\t\treturn data;\n\t\t},\n\t\tset: async (key, value, _update) => {\n\t\t\ttry {\n\t\t\t\tif (_update) await db.updateMany({\n\t\t\t\t\tmodel,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"key\",\n\t\t\t\t\t\tvalue: key\n\t\t\t\t\t}],\n\t\t\t\t\tupdate: {\n\t\t\t\t\t\tcount: value.count,\n\t\t\t\t\t\tlastRequest: value.lastRequest\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\telse await db.create({\n\t\t\t\t\tmodel,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tcount: value.count,\n\t\t\t\t\t\tlastRequest: value.lastRequest\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tctx.logger.error(\"Error setting rate limit\", e);\n\t\t\t}\n\t\t}\n\t};\n}\nfunction getRateLimitStorage(ctx, rateLimitSettings) {\n\tif (ctx.options.rateLimit?.customStorage) return ctx.options.rateLimit.customStorage;\n\tconst storage = ctx.rateLimit.storage;\n\tif (storage === \"secondary-storage\") return {\n\t\tget: async (key) => {\n\t\t\tconst data = await ctx.options.secondaryStorage?.get(key);\n\t\t\treturn data ? safeJSONParse(data) : null;\n\t\t},\n\t\tset: async (key, value, _update) => {\n\t\t\tconst ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10;\n\t\t\tawait ctx.options.secondaryStorage?.set?.(key, JSON.stringify(value), ttl);\n\t\t}\n\t};\n\telse if (storage === \"memory\") return {\n\t\tasync get(key) {\n\t\t\tconst entry = memory.get(key);\n\t\t\tif (!entry) return null;\n\t\t\tif (Date.now() >= entry.expiresAt) {\n\t\t\t\tmemory.delete(key);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn entry.data;\n\t\t},\n\t\tasync set(key, value, _update) {\n\t\t\tconst ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10;\n\t\t\tconst expiresAt = Date.now() + ttl * 1e3;\n\t\t\tmemory.set(key, {\n\t\t\t\tdata: value,\n\t\t\t\texpiresAt\n\t\t\t});\n\t\t}\n\t};\n\treturn createDatabaseStorageWrapper(ctx);\n}\nlet ipWarningLogged = false;\nasync function resolveRateLimitConfig(req, ctx) {\n\tconst basePath = new URL(ctx.baseURL).pathname;\n\tconst path = normalizePathname(req.url, basePath);\n\tlet currentWindow = ctx.rateLimit.window;\n\tlet currentMax = ctx.rateLimit.max;\n\tconst ip = getIp(req, ctx.options);\n\tif (!ip) {\n\t\tif (!ipWarningLogged) {\n\t\t\tctx.logger.warn(\"Rate limiting skipped: could not determine client IP address. Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed.\");\n\t\t\tipWarningLogged = true;\n\t\t}\n\t\treturn null;\n\t}\n\tconst key = createRateLimitKey(ip, path);\n\tconst specialRule = getDefaultSpecialRules().find((rule) => rule.pathMatcher(path));\n\tif (specialRule) {\n\t\tcurrentWindow = specialRule.window;\n\t\tcurrentMax = specialRule.max;\n\t}\n\tfor (const plugin of ctx.options.plugins || []) if (plugin.rateLimit) {\n\t\tconst matchedRule = plugin.rateLimit.find((rule) => rule.pathMatcher(path));\n\t\tif (matchedRule) {\n\t\t\tcurrentWindow = matchedRule.window;\n\t\t\tcurrentMax = matchedRule.max;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (ctx.rateLimit.customRules) {\n\t\tconst _path = Object.keys(ctx.rateLimit.customRules).find((p) => {\n\t\t\tif (p.includes(\"*\")) return wildcardMatch(p)(path);\n\t\t\treturn p === path;\n\t\t});\n\t\tif (_path) {\n\t\t\tconst customRule = ctx.rateLimit.customRules[_path];\n\t\t\tconst resolved = typeof customRule === \"function\" ? await customRule(req, {\n\t\t\t\twindow: currentWindow,\n\t\t\t\tmax: currentMax\n\t\t\t}) : customRule;\n\t\t\tif (resolved) {\n\t\t\t\tcurrentWindow = resolved.window;\n\t\t\t\tcurrentMax = resolved.max;\n\t\t\t}\n\t\t\tif (resolved === false) return null;\n\t\t}\n\t}\n\treturn {\n\t\tkey,\n\t\tcurrentWindow,\n\t\tcurrentMax\n\t};\n}\nasync function onRequestRateLimit(req, ctx) {\n\tif (!ctx.rateLimit.enabled) return;\n\tconst config = await resolveRateLimitConfig(req, ctx);\n\tif (!config) return;\n\tconst { key, currentWindow, currentMax } = config;\n\tconst data = await getRateLimitStorage(ctx, { window: currentWindow }).get(key);\n\tif (data && shouldRateLimit(currentMax, currentWindow, data)) return rateLimitResponse(getRetryAfter(data.lastRequest, currentWindow));\n}\nasync function onResponseRateLimit(req, ctx) {\n\tif (!ctx.rateLimit.enabled) return;\n\tconst config = await resolveRateLimitConfig(req, ctx);\n\tif (!config) return;\n\tconst { key, currentWindow } = config;\n\tconst storage = getRateLimitStorage(ctx, { window: currentWindow });\n\tconst data = await storage.get(key);\n\tconst now = Date.now();\n\tif (!data) await storage.set(key, {\n\t\tkey,\n\t\tcount: 1,\n\t\tlastRequest: now\n\t});\n\telse if (now - data.lastRequest > currentWindow * 1e3) await storage.set(key, {\n\t\t...data,\n\t\tcount: 1,\n\t\tlastRequest: now\n\t}, true);\n\telse await storage.set(key, {\n\t\t...data,\n\t\tcount: data.count + 1,\n\t\tlastRequest: now\n\t}, true);\n}\nfunction getDefaultSpecialRules() {\n\treturn [{\n\t\tpathMatcher(path) {\n\t\t\treturn path.startsWith(\"/sign-in\") || path.startsWith(\"/sign-up\") || path.startsWith(\"/change-password\") || path.startsWith(\"/change-email\");\n\t\t},\n\t\twindow: 10,\n\t\tmax: 3\n\t}, {\n\t\tpathMatcher(path) {\n\t\t\treturn path === \"/request-password-reset\" || path === \"/send-verification-email\" || path.startsWith(\"/forget-password\") || path === \"/email-otp/send-verification-otp\" || path === \"/email-otp/request-password-reset\";\n\t\t},\n\t\twindow: 60,\n\t\tmax: 3\n\t}];\n}\n//#endregion\nexport { onRequestRateLimit, onResponseRateLimit };\n", "import { defineRequestState } from \"@better-auth/core/context\";\n//#region src/api/state/should-session-refresh.ts\n/**\n* State for skipping session refresh\n*\n* In some cases, such as when using server-side rendering (SSR) or when dealing with\n* certain types of requests, it may be necessary to skip session refresh to prevent\n* potential inconsistencies between the session data in the database and the session\n* data stored in cookies.\n*/\nconst { get: getShouldSkipSessionRefresh, set: setShouldSkipSessionRefresh } = defineRequestState(() => false);\n//#endregion\nexport { getShouldSkipSessionRefresh, setShouldSkipSessionRefresh };\n", "import { isAPIError } from \"../../utils/is-api-error.mjs\";\nimport { getDate } from \"../../utils/date.mjs\";\nimport { parseSessionOutput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { symmetricDecodeJWT, verifyJWT } from \"../../crypto/jwt.mjs\";\nimport { getChunkedCookie, getSessionQuerySchema } from \"../../cookies/session-store.mjs\";\nimport { deleteSessionCookie, expireCookie, setCookieCache, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { getShouldSkipSessionRefresh } from \"../state/should-session-refresh.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { createAuthEndpoint, createAuthMiddleware } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\nimport { base64Url } from \"@better-auth/utils/base64\";\nimport { binary } from \"@better-auth/utils/binary\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\n//#region src/api/routes/session.ts\nconst getSession = () => createAuthEndpoint(\"/get-session\", {\n\tmethod: [\"GET\", \"POST\"],\n\toperationId: \"getSession\",\n\tquery: getSessionQuerySchema,\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\toperationId: \"getSession\",\n\t\tdescription: \"Get the current session\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tnullable: true,\n\t\t\t\tproperties: {\n\t\t\t\t\tsession: { $ref: \"#/components/schemas/Session\" },\n\t\t\t\t\tuser: { $ref: \"#/components/schemas/User\" }\n\t\t\t\t},\n\t\t\t\trequired: [\"session\", \"user\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst deferSessionRefresh = ctx.context.options.session?.deferSessionRefresh;\n\tconst isPostRequest = ctx.method === \"POST\";\n\tif (isPostRequest && !deferSessionRefresh) throw APIError.from(\"METHOD_NOT_ALLOWED\", BASE_ERROR_CODES.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);\n\ttry {\n\t\tconst sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);\n\t\tif (!sessionCookieToken) return null;\n\t\tconst sessionDataCookie = getChunkedCookie(ctx, ctx.context.authCookies.sessionData.name);\n\t\tlet sessionDataPayload = null;\n\t\tif (sessionDataCookie) {\n\t\t\tconst strategy = ctx.context.options.session?.cookieCache?.strategy || \"compact\";\n\t\t\tif (strategy === \"jwe\") {\n\t\t\t\tconst payload = await symmetricDecodeJWT(sessionDataCookie, ctx.context.secretConfig, \"better-auth-session\");\n\t\t\t\tif (payload && payload.session && payload.user) sessionDataPayload = {\n\t\t\t\t\tsession: {\n\t\t\t\t\t\tsession: payload.session,\n\t\t\t\t\t\tuser: payload.user,\n\t\t\t\t\t\tupdatedAt: payload.updatedAt,\n\t\t\t\t\t\tversion: payload.version\n\t\t\t\t\t},\n\t\t\t\t\texpiresAt: payload.exp ? payload.exp * 1e3 : Date.now()\n\t\t\t\t};\n\t\t\t\telse {\n\t\t\t\t\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\t\t\treturn ctx.json(null);\n\t\t\t\t}\n\t\t\t} else if (strategy === \"jwt\") {\n\t\t\t\tconst payload = await verifyJWT(sessionDataCookie, ctx.context.secret);\n\t\t\t\tif (payload && payload.session && payload.user) sessionDataPayload = {\n\t\t\t\t\tsession: {\n\t\t\t\t\t\tsession: payload.session,\n\t\t\t\t\t\tuser: payload.user,\n\t\t\t\t\t\tupdatedAt: payload.updatedAt,\n\t\t\t\t\t\tversion: payload.version\n\t\t\t\t\t},\n\t\t\t\t\texpiresAt: payload.exp ? payload.exp * 1e3 : Date.now()\n\t\t\t\t};\n\t\t\t\telse {\n\t\t\t\t\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\t\t\treturn ctx.json(null);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst parsed = safeJSONParse(binary.decode(base64Url.decode(sessionDataCookie)));\n\t\t\t\tif (parsed) if (await createHMAC(\"SHA-256\", \"base64urlnopad\").verify(ctx.context.secret, JSON.stringify({\n\t\t\t\t\t...parsed.session,\n\t\t\t\t\texpiresAt: parsed.expiresAt\n\t\t\t\t}), parsed.signature)) sessionDataPayload = parsed;\n\t\t\t\telse {\n\t\t\t\t\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\t\t\treturn ctx.json(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);\n\t\t/**\n\t\t* If session data is present in the cookie, check if it should be used or refreshed\n\t\t*/\n\t\tif (sessionDataPayload?.session && ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache) {\n\t\t\tconst session = sessionDataPayload.session;\n\t\t\tconst versionConfig = ctx.context.options.session?.cookieCache?.version;\n\t\t\tlet expectedVersion = \"1\";\n\t\t\tif (versionConfig) {\n\t\t\t\tif (typeof versionConfig === \"string\") expectedVersion = versionConfig;\n\t\t\t\telse if (typeof versionConfig === \"function\") {\n\t\t\t\t\tconst result = versionConfig(session.session, session.user);\n\t\t\t\t\texpectedVersion = result instanceof Promise ? await result : result;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((session.version || \"1\") !== expectedVersion) expireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\telse {\n\t\t\t\tconst cachedSessionExpiresAt = new Date(session.session.expiresAt);\n\t\t\t\tif (sessionDataPayload.expiresAt < Date.now() || cachedSessionExpiresAt < /* @__PURE__ */ new Date()) expireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\t\telse {\n\t\t\t\t\tconst cookieRefreshCache = ctx.context.sessionConfig.cookieRefreshCache;\n\t\t\t\t\tif (cookieRefreshCache === false) {\n\t\t\t\t\t\tctx.context.session = session;\n\t\t\t\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t\t\t...session.session,\n\t\t\t\t\t\t\texpiresAt: new Date(session.session.expiresAt),\n\t\t\t\t\t\t\tcreatedAt: new Date(session.session.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(session.session.updatedAt)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t\t\t...session.user,\n\t\t\t\t\t\t\tcreatedAt: new Date(session.user.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(session.user.updatedAt)\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\t\t\tuser: parsedUser\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst timeUntilExpiry = sessionDataPayload.expiresAt - Date.now();\n\t\t\t\t\tconst updateAge = cookieRefreshCache.updateAge * 1e3;\n\t\t\t\t\tconst shouldSkipSessionRefresh = await getShouldSkipSessionRefresh();\n\t\t\t\t\tif (timeUntilExpiry < updateAge && !shouldSkipSessionRefresh) {\n\t\t\t\t\t\tconst newExpiresAt = getDate(ctx.context.options.session?.cookieCache?.maxAge || 300, \"sec\");\n\t\t\t\t\t\tconst refreshedSession = {\n\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t...session.session,\n\t\t\t\t\t\t\t\texpiresAt: newExpiresAt\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tuser: session.user,\n\t\t\t\t\t\t\tupdatedAt: Date.now()\n\t\t\t\t\t\t};\n\t\t\t\t\t\tawait setCookieCache(ctx, refreshedSession, false);\n\t\t\t\t\t\tconst sessionTokenOptions = ctx.context.authCookies.sessionToken.attributes;\n\t\t\t\t\t\tconst sessionTokenMaxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn;\n\t\t\t\t\t\tawait ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, {\n\t\t\t\t\t\t\t...sessionTokenOptions,\n\t\t\t\t\t\t\tmaxAge: sessionTokenMaxAge\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst parsedRefreshedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t\t\t...refreshedSession.session,\n\t\t\t\t\t\t\texpiresAt: new Date(refreshedSession.session.expiresAt),\n\t\t\t\t\t\t\tcreatedAt: new Date(refreshedSession.session.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(refreshedSession.session.updatedAt)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst parsedRefreshedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t\t\t...refreshedSession.user,\n\t\t\t\t\t\t\tcreatedAt: new Date(refreshedSession.user.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(refreshedSession.user.updatedAt)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tctx.context.session = {\n\t\t\t\t\t\t\tsession: parsedRefreshedSession,\n\t\t\t\t\t\t\tuser: parsedRefreshedUser\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\t\tsession: parsedRefreshedSession,\n\t\t\t\t\t\t\tuser: parsedRefreshedUser\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t\t...session.session,\n\t\t\t\t\t\texpiresAt: new Date(session.session.expiresAt),\n\t\t\t\t\t\tcreatedAt: new Date(session.session.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(session.session.updatedAt)\n\t\t\t\t\t});\n\t\t\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t\t...session.user,\n\t\t\t\t\t\tcreatedAt: new Date(session.user.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(session.user.updatedAt)\n\t\t\t\t\t});\n\t\t\t\t\tctx.context.session = {\n\t\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\t\tuser: parsedUser\n\t\t\t\t\t};\n\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\t\tuser: parsedUser\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst session = await ctx.context.internalAdapter.findSession(sessionCookieToken);\n\t\tctx.context.session = session;\n\t\tif (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) {\n\t\t\tdeleteSessionCookie(ctx);\n\t\t\tif (session) {\n\t\t\t\t/**\n\t\t\t\t* if session expired clean up the session\n\t\t\t\t* Only delete on POST when deferSessionRefresh is enabled\n\t\t\t\t*/\n\t\t\t\tif (!deferSessionRefresh || isPostRequest) await ctx.context.internalAdapter.deleteSession(session.session.token);\n\t\t\t}\n\t\t\treturn ctx.json(null);\n\t\t}\n\t\t/**\n\t\t* We don't need to update the session if the user doesn't want to be remembered\n\t\t* or if the session refresh is disabled\n\t\t*/\n\t\tif (dontRememberMe || ctx.query?.disableRefresh) {\n\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedSession,\n\t\t\t\tuser: parsedUser\n\t\t\t});\n\t\t}\n\t\tconst expiresIn = ctx.context.sessionConfig.expiresIn;\n\t\tconst updateAge = ctx.context.sessionConfig.updateAge;\n\t\tconst shouldBeUpdated = session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3 <= Date.now();\n\t\tconst disableRefresh = ctx.query?.disableRefresh || ctx.context.options.session?.disableSessionRefresh;\n\t\tconst shouldSkipSessionRefresh = await getShouldSkipSessionRefresh();\n\t\tconst needsRefresh = shouldBeUpdated && !disableRefresh && !shouldSkipSessionRefresh;\n\t\t/**\n\t\t* When deferSessionRefresh is enabled and this is a GET request,\n\t\t* return the session without performing writes, but include needsRefresh flag\n\t\t*/\n\t\tif (deferSessionRefresh && !isPostRequest) {\n\t\t\tawait setCookieCache(ctx, session, !!dontRememberMe);\n\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedSession,\n\t\t\t\tuser: parsedUser,\n\t\t\t\tneedsRefresh\n\t\t\t});\n\t\t}\n\t\tif (needsRefresh) {\n\t\t\tconst updatedSession = await ctx.context.internalAdapter.updateSession(session.session.token, {\n\t\t\t\texpiresAt: getDate(ctx.context.sessionConfig.expiresIn, \"sec\"),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t\t});\n\t\t\tif (!updatedSession) {\n\t\t\t\t/**\n\t\t\t\t* Handle case where session update fails (e.g., concurrent deletion)\n\t\t\t\t*/\n\t\t\t\tdeleteSessionCookie(ctx);\n\t\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_GET_SESSION);\n\t\t\t}\n\t\t\tconst maxAge = (updatedSession.expiresAt.valueOf() - Date.now()) / 1e3;\n\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\tsession: updatedSession,\n\t\t\t\tuser: session.user\n\t\t\t}, false, { maxAge });\n\t\t\tconst parsedUpdatedSession = parseSessionOutput(ctx.context.options, updatedSession);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedUpdatedSession,\n\t\t\t\tuser: parsedUser\n\t\t\t});\n\t\t}\n\t\tawait setCookieCache(ctx, session, !!dontRememberMe);\n\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\treturn ctx.json({\n\t\t\tsession: parsedSession,\n\t\t\tuser: parsedUser\n\t\t});\n\t} catch (error) {\n\t\tif (isAPIError(error)) throw error;\n\t\tctx.context.logger.error(\"INTERNAL_SERVER_ERROR\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", BASE_ERROR_CODES.FAILED_TO_GET_SESSION);\n\t}\n});\nconst getSessionFromCtx = async (ctx, config) => {\n\tif (ctx.context.session) return ctx.context.session;\n\tconst session = await getSession()({\n\t\t...ctx,\n\t\tmethod: \"GET\",\n\t\tasResponse: false,\n\t\theaders: ctx.headers,\n\t\treturnHeaders: false,\n\t\treturnStatus: false,\n\t\tquery: {\n\t\t\t...config,\n\t\t\t...ctx.query\n\t\t}\n\t}).catch((e) => {\n\t\treturn null;\n\t});\n\tctx.context.session = session;\n\treturn session;\n};\n/**\n* The middleware forces the endpoint to require a valid session.\n*/\nconst sessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware forces the endpoint to require a valid session and ignores cookie cache.\n* This should be used for sensitive operations like password changes, account deletion, etc.\n* to ensure that revoked sessions cannot be used even if they're still cached in cookies.\n*/\nconst sensitiveSessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx, { disableCookieCache: true });\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware allows you to call the endpoint on the client if session is valid.\n* However, if called on the server, no session is required.\n*/\nconst requestOnlySessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session && (ctx.request || ctx.headers)) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware forces the endpoint to require a valid session,\n* as well as making sure the session is fresh before proceeding.\n*\n* Session freshness check will be skipped if the session config's freshAge\n* is set to 0\n*/\nconst freshSessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\tif (ctx.context.sessionConfig.freshAge !== 0) {\n\t\tconst createdAt = new Date(session.session.createdAt).getTime();\n\t\tconst freshAge = ctx.context.sessionConfig.freshAge * 1e3;\n\t\tif (Date.now() - createdAt >= freshAge) throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.SESSION_NOT_FRESH);\n\t}\n\treturn { session };\n});\n/**\n* user active sessions list\n*/\nconst listSessions = () => createAuthEndpoint(\"/list-sessions\", {\n\tmethod: \"GET\",\n\toperationId: \"listUserSessions\",\n\tuse: [sessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\toperationId: \"listUserSessions\",\n\t\tdescription: \"List all active sessions for the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: { $ref: \"#/components/schemas/Session\" }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\ttry {\n\t\tconst activeSessions = (await ctx.context.internalAdapter.listSessions(ctx.context.session.user.id, { onlyActiveSessions: true })).filter((session) => {\n\t\t\treturn session.expiresAt > /* @__PURE__ */ new Date();\n\t\t});\n\t\treturn ctx.json(activeSessions.map((session) => parseSessionOutput(ctx.context.options, session)));\n\t} catch (e) {\n\t\tctx.context.logger.error(e);\n\t\tthrow ctx.error(\"INTERNAL_SERVER_ERROR\");\n\t}\n});\n/**\n* revoke a single session\n*/\nconst revokeSession = createAuthEndpoint(\"/revoke-session\", {\n\tmethod: \"POST\",\n\tbody: z.object({ token: z.string().meta({ description: \"The token to revoke\" }) }),\n\tuse: [sensitiveSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke a single session\",\n\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\ttype: \"object\",\n\t\t\tproperties: { token: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tdescription: \"The token to revoke\"\n\t\t\t} },\n\t\t\trequired: [\"token\"]\n\t\t} } } },\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if the session was revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst token = ctx.body.token;\n\tif ((await ctx.context.internalAdapter.findSession(token))?.session.userId === ctx.context.session.user.id) try {\n\t\tawait ctx.context.internalAdapter.deleteSession(token);\n\t} catch (error) {\n\t\tctx.context.logger.error(error && typeof error === \"object\" && \"name\" in error ? error.name : \"\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\t\tmessage: \"Internal Server Error\",\n\t\t\tcode: \"INTERNAL_SERVER_ERROR\"\n\t\t});\n\t}\n\treturn ctx.json({ status: true });\n});\n/**\n* revoke all user sessions\n*/\nconst revokeSessions = createAuthEndpoint(\"/revoke-sessions\", {\n\tmethod: \"POST\",\n\tuse: [sensitiveSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke all sessions for the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if all sessions were revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\ttry {\n\t\tawait ctx.context.internalAdapter.deleteSessions(ctx.context.session.user.id);\n\t} catch (error) {\n\t\tctx.context.logger.error(error && typeof error === \"object\" && \"name\" in error ? error.name : \"\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\t\tmessage: \"Internal Server Error\",\n\t\t\tcode: \"INTERNAL_SERVER_ERROR\"\n\t\t});\n\t}\n\treturn ctx.json({ status: true });\n});\nconst revokeOtherSessions = createAuthEndpoint(\"/revoke-other-sessions\", {\n\tmethod: \"POST\",\n\trequireHeaders: true,\n\tuse: [sensitiveSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke all other sessions for the user except the current one\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if all other sessions were revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tif (!session.user) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\tconst otherSessions = (await ctx.context.internalAdapter.listSessions(session.user.id)).filter((session) => {\n\t\treturn session.expiresAt > /* @__PURE__ */ new Date();\n\t}).filter((session) => session.token !== ctx.context.session.session.token);\n\tawait Promise.all(otherSessions.map((session) => ctx.context.internalAdapter.deleteSession(session.token)));\n\treturn ctx.json({ status: true });\n});\n//#endregion\nexport { freshSessionMiddleware, getSession, getSessionFromCtx, listSessions, requestOnlySessionMiddleware, revokeOtherSessions, revokeSession, revokeSessions, sensitiveSessionMiddleware, sessionMiddleware };\n", "import { base64Url } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\n//#region src/db/verification-token-storage.ts\nconst defaultKeyHasher = async (identifier) => {\n\tconst hash = await createHash(\"SHA-256\").digest(new TextEncoder().encode(identifier));\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n};\nasync function processIdentifier(identifier, option) {\n\tif (!option || option === \"plain\") return identifier;\n\tif (option === \"hashed\") return defaultKeyHasher(identifier);\n\tif (typeof option === \"object\" && \"hash\" in option) return option.hash(identifier);\n\treturn identifier;\n}\nfunction getStorageOption(identifier, config) {\n\tif (!config) return;\n\tif (typeof config === \"object\" && \"default\" in config) {\n\t\tif (config.overrides) {\n\t\t\tfor (const [prefix, option] of Object.entries(config.overrides)) if (identifier.startsWith(prefix)) return option;\n\t\t}\n\t\treturn config.default;\n\t}\n\treturn config;\n}\n//#endregion\nexport { getStorageOption, processIdentifier };\n", "import { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID } from \"./attributes.mjs\";\nimport { withSpan } from \"./tracer.mjs\";\nexport { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID, withSpan };\n", "import { getCurrentAdapter, getCurrentAuthContext, queueAfterTransactionHook } from \"@better-auth/core/context\";\nimport { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_HOOK_TYPE, withSpan } from \"@better-auth/core/instrumentation\";\n//#region src/db/with-hooks.ts\nfunction getWithHooks(adapter, ctx) {\n\tconst hooksEntries = ctx.hooks;\n\tasync function createWithHooks(data, model, customCreateFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet actualData = data;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.create?.before;\n\t\t\tif (toRun) {\n\t\t\t\tconst result = await withSpan(`db create.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"create.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(actualData, context));\n\t\t\t\tif (result === false) return null;\n\t\t\t\tif (typeof result === \"object\" && \"data\" in result) actualData = {\n\t\t\t\t\t...actualData,\n\t\t\t\t\t...result.data\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tlet created = null;\n\t\tif (!customCreateFn || customCreateFn.executeMainFn) created = await (await getCurrentAdapter(adapter)).create({\n\t\t\tmodel,\n\t\t\tdata: actualData,\n\t\t\tforceAllowId: true\n\t\t});\n\t\tif (customCreateFn?.fn) created = await customCreateFn.fn(created ?? actualData);\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.create?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db create.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"create.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(created, context));\n\t\t\t});\n\t\t}\n\t\treturn created;\n\t}\n\tasync function updateWithHooks(data, where, model, customUpdateFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet actualData = data;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.update?.before;\n\t\t\tif (toRun) {\n\t\t\t\tconst result = await withSpan(`db update.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"update.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(data, context));\n\t\t\t\tif (result === false) return null;\n\t\t\t\tif (typeof result === \"object\" && \"data\" in result) actualData = {\n\t\t\t\t\t...actualData,\n\t\t\t\t\t...result.data\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null;\n\t\tconst updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).update({\n\t\t\tmodel,\n\t\t\tupdate: actualData,\n\t\t\twhere\n\t\t}) : customUpdated;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.update?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db update.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"update.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(updated, context));\n\t\t\t});\n\t\t}\n\t\treturn updated;\n\t}\n\tasync function updateManyWithHooks(data, where, model, customUpdateFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet actualData = data;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.update?.before;\n\t\t\tif (toRun) {\n\t\t\t\tconst result = await withSpan(`db updateMany.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"updateMany.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(data, context));\n\t\t\t\tif (result === false) return null;\n\t\t\t\tif (typeof result === \"object\" && \"data\" in result) actualData = {\n\t\t\t\t\t...actualData,\n\t\t\t\t\t...result.data\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null;\n\t\tconst updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).updateMany({\n\t\t\tmodel,\n\t\t\tupdate: actualData,\n\t\t\twhere\n\t\t}) : customUpdated;\n\t\tfor (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.update?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db updateMany.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"updateMany.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(updated, context));\n\t\t\t});\n\t\t}\n\t\treturn updated;\n\t}\n\tasync function deleteWithHooks(where, model, customDeleteFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet entityToDelete = null;\n\t\ttry {\n\t\t\tentityToDelete = (await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel,\n\t\t\t\twhere,\n\t\t\t\tlimit: 1\n\t\t\t}))[0] || null;\n\t\t} catch {}\n\t\tif (entityToDelete) for (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.delete?.before;\n\t\t\tif (toRun) {\n\t\t\t\tif (await withSpan(`db delete.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"delete.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(entityToDelete, context)) === false) return null;\n\t\t\t}\n\t\t}\n\t\tconst customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null;\n\t\tconst deleted = (!customDeleteFn || customDeleteFn.executeMainFn) && entityToDelete ? await (await getCurrentAdapter(adapter)).delete({\n\t\t\tmodel,\n\t\t\twhere\n\t\t}) : customDeleted;\n\t\tif (entityToDelete) for (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.delete?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db delete.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"delete.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(entityToDelete, context));\n\t\t\t});\n\t\t}\n\t\treturn deleted;\n\t}\n\tasync function deleteManyWithHooks(where, model, customDeleteFn) {\n\t\tconst context = await getCurrentAuthContext().catch(() => null);\n\t\tlet entitiesToDelete = [];\n\t\ttry {\n\t\t\tentitiesToDelete = await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel,\n\t\t\t\twhere\n\t\t\t});\n\t\t} catch {}\n\t\tfor (const entity of entitiesToDelete) for (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.delete?.before;\n\t\t\tif (toRun) {\n\t\t\t\tif (await withSpan(`db delete.before ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"delete.before\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(entity, context)) === false) return null;\n\t\t\t}\n\t\t}\n\t\tconst customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null;\n\t\tconst deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await (await getCurrentAdapter(adapter)).deleteMany({\n\t\t\tmodel,\n\t\t\twhere\n\t\t}) : customDeleted;\n\t\tfor (const entity of entitiesToDelete) for (const { source, hooks } of hooksEntries) {\n\t\t\tconst toRun = hooks[model]?.delete?.after;\n\t\t\tif (toRun) await queueAfterTransactionHook(async () => {\n\t\t\t\tawait withSpan(`db delete.after ${model}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"delete.after\",\n\t\t\t\t\t[ATTR_DB_COLLECTION_NAME]: model,\n\t\t\t\t\t[ATTR_CONTEXT]: source\n\t\t\t\t}, () => toRun(entity, context));\n\t\t\t});\n\t\t}\n\t\treturn deleted;\n\t}\n\treturn {\n\t\tcreateWithHooks,\n\t\tupdateWithHooks,\n\t\tupdateManyWithHooks,\n\t\tdeleteWithHooks,\n\t\tdeleteManyWithHooks\n\t};\n}\n//#endregion\nexport { getWithHooks };\n", "import { getIp } from \"../utils/get-request-ip.mjs\";\nimport { getDate } from \"../utils/date.mjs\";\nimport { getSessionDefaultFields, parseSessionOutput, parseUserOutput } from \"./schema.mjs\";\nimport { getStorageOption, processIdentifier } from \"./verification-token-storage.mjs\";\nimport { getWithHooks } from \"./with-hooks.mjs\";\nimport { getCurrentAdapter, getCurrentAuthContext, runWithTransaction } from \"@better-auth/core/context\";\nimport { generateId } from \"@better-auth/core/utils/id\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\n//#region src/db/internal-adapter.ts\nfunction getTTLSeconds(expiresAt, now = Date.now()) {\n\tconst expiresMs = typeof expiresAt === \"number\" ? expiresAt : expiresAt.getTime();\n\treturn Math.max(Math.floor((expiresMs - now) / 1e3), 0);\n}\nconst createInternalAdapter = (adapter, ctx) => {\n\tconst logger = ctx.logger;\n\tconst options = ctx.options;\n\tconst secondaryStorage = options.secondaryStorage;\n\tconst sessionExpiration = options.session?.expiresIn || 3600 * 24 * 7;\n\tconst { createWithHooks, updateWithHooks, updateManyWithHooks, deleteWithHooks, deleteManyWithHooks } = getWithHooks(adapter, ctx);\n\tasync function refreshUserSessions(user) {\n\t\tif (!secondaryStorage) return;\n\t\tconst listRaw = await secondaryStorage.get(`active-sessions-${user.id}`);\n\t\tif (!listRaw) return;\n\t\tconst now = Date.now();\n\t\tconst validSessions = (safeJSONParse(listRaw) || []).filter((s) => s.expiresAt > now);\n\t\tawait Promise.all(validSessions.map(async ({ token }) => {\n\t\t\tconst cached = await secondaryStorage.get(token);\n\t\t\tif (!cached) return;\n\t\t\tconst parsed = safeJSONParse(cached);\n\t\t\tif (!parsed) return;\n\t\t\tconst sessionTTL = getTTLSeconds(parsed.session.expiresAt, now);\n\t\t\tawait secondaryStorage.set(token, JSON.stringify({\n\t\t\t\tsession: parsed.session,\n\t\t\t\tuser\n\t\t\t}), Math.floor(sessionTTL));\n\t\t}));\n\t}\n\treturn {\n\t\tcreateOAuthUser: async (user, account) => {\n\t\t\treturn runWithTransaction(adapter, async () => {\n\t\t\t\tconst createdUser = await createWithHooks({\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\t...user\n\t\t\t\t}, \"user\", void 0);\n\t\t\t\treturn {\n\t\t\t\t\tuser: createdUser,\n\t\t\t\t\taccount: await createWithHooks({\n\t\t\t\t\t\t...account,\n\t\t\t\t\t\tuserId: createdUser.id,\n\t\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t\t\t\t}, \"account\", void 0)\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tcreateUser: async (user) => {\n\t\t\treturn await createWithHooks({\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...user,\n\t\t\t\temail: user.email?.toLowerCase()\n\t\t\t}, \"user\", void 0);\n\t\t},\n\t\tcreateAccount: async (account) => {\n\t\t\treturn await createWithHooks({\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...account\n\t\t\t}, \"account\", void 0);\n\t\t},\n\t\tlistSessions: async (userId, options) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst currentList = await secondaryStorage.get(`active-sessions-${userId}`);\n\t\t\t\tif (!currentList) return [];\n\t\t\t\tconst list = safeJSONParse(currentList) || [];\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst seenTokens = /* @__PURE__ */ new Set();\n\t\t\t\tconst sessions = [];\n\t\t\t\tfor (const { token, expiresAt } of list) {\n\t\t\t\t\tif (expiresAt <= now || seenTokens.has(token)) continue;\n\t\t\t\t\tseenTokens.add(token);\n\t\t\t\t\tconst data = await secondaryStorage.get(token);\n\t\t\t\t\tif (!data) continue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed = typeof data === \"string\" ? JSON.parse(data) : data;\n\t\t\t\t\t\tif (!parsed?.session) continue;\n\t\t\t\t\t\tsessions.push(parseSessionOutput(ctx.options, {\n\t\t\t\t\t\t\t...parsed.session,\n\t\t\t\t\t\t\texpiresAt: new Date(parsed.session.expiresAt)\n\t\t\t\t\t\t}));\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn sessions;\n\t\t\t}\n\t\t\treturn await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"session\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}, ...options?.onlyActiveSessions ? [{\n\t\t\t\t\tfield: \"expiresAt\",\n\t\t\t\t\tvalue: /* @__PURE__ */ new Date(),\n\t\t\t\t\toperator: \"gt\"\n\t\t\t\t}] : []]\n\t\t\t});\n\t\t},\n\t\tlistUsers: async (limit, offset, sortBy, where) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"user\",\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\tsortBy,\n\t\t\t\twhere\n\t\t\t});\n\t\t},\n\t\tcountTotalUsers: async (where) => {\n\t\t\tconst total = await (await getCurrentAdapter(adapter)).count({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere\n\t\t\t});\n\t\t\tif (typeof total === \"string\") return parseInt(total);\n\t\t\treturn total;\n\t\t},\n\t\tdeleteUser: async (userId) => {\n\t\t\tif (!secondaryStorage || options.session?.storeSessionInDatabase) await deleteManyWithHooks([{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"session\", void 0);\n\t\t\tawait deleteManyWithHooks([{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"account\", void 0);\n\t\t\tawait deleteWithHooks([{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"user\", void 0);\n\t\t},\n\t\tcreateSession: async (userId, dontRememberMe, override, overrideAll) => {\n\t\t\tconst headers = await (async () => {\n\t\t\t\tconst ctx = await getCurrentAuthContext().catch(() => null);\n\t\t\t\treturn ctx?.headers || ctx?.request?.headers;\n\t\t\t})();\n\t\t\tconst storeInDb = options.session?.storeSessionInDatabase;\n\t\t\tconst { id: _, ...rest } = override || {};\n\t\t\tlet sessionId;\n\t\t\tif (secondaryStorage && !storeInDb) {\n\t\t\t\tconst generatedId = ctx.generateId({ model: \"session\" });\n\t\t\t\tsessionId = generatedId !== false ? generatedId : generateId();\n\t\t\t}\n\t\t\tconst defaultAdditionalFields = getSessionDefaultFields(options);\n\t\t\tconst data = {\n\t\t\t\t...sessionId ? { id: sessionId } : {},\n\t\t\t\tipAddress: headers ? getIp(headers, options) || \"\" : \"\",\n\t\t\t\tuserAgent: headers?.get(\"user-agent\") || \"\",\n\t\t\t\t...rest,\n\t\t\t\texpiresAt: dontRememberMe ? getDate(3600 * 24, \"sec\") : getDate(sessionExpiration, \"sec\"),\n\t\t\t\tuserId,\n\t\t\t\ttoken: generateId(32),\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...defaultAdditionalFields,\n\t\t\t\t...overrideAll ? rest : {}\n\t\t\t};\n\t\t\treturn await createWithHooks(data, \"session\", secondaryStorage ? {\n\t\t\t\tfn: async (sessionData) => {\n\t\t\t\t\t/**\n\t\t\t\t\t* store the session token for the user\n\t\t\t\t\t* so we can retrieve it later for listing sessions\n\t\t\t\t\t*/\n\t\t\t\t\tconst currentList = await secondaryStorage.get(`active-sessions-${userId}`);\n\t\t\t\t\tlet list = [];\n\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\tif (currentList) {\n\t\t\t\t\t\tlist = safeJSONParse(currentList) || [];\n\t\t\t\t\t\tlist = list.filter((session) => session.expiresAt > now && session.token !== data.token);\n\t\t\t\t\t}\n\t\t\t\t\tconst sorted = [...list, {\n\t\t\t\t\t\ttoken: data.token,\n\t\t\t\t\t\texpiresAt: data.expiresAt.getTime()\n\t\t\t\t\t}].sort((a, b) => a.expiresAt - b.expiresAt);\n\t\t\t\t\tconst furthestSessionTTL = getTTLSeconds(sorted.at(-1)?.expiresAt ?? data.expiresAt.getTime(), now);\n\t\t\t\t\tif (furthestSessionTTL > 0) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(sorted), furthestSessionTTL);\n\t\t\t\t\tconst user = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\twhere: [{\n\t\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\t\tvalue: userId\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tconst sessionTTL = getTTLSeconds(data.expiresAt, now);\n\t\t\t\t\tif (sessionTTL > 0) await secondaryStorage.set(data.token, JSON.stringify({\n\t\t\t\t\t\tsession: sessionData,\n\t\t\t\t\t\tuser\n\t\t\t\t\t}), sessionTTL);\n\t\t\t\t\treturn sessionData;\n\t\t\t\t},\n\t\t\t\texecuteMainFn: storeInDb\n\t\t\t} : void 0);\n\t\t},\n\t\tfindSession: async (token) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst sessionStringified = await secondaryStorage.get(token);\n\t\t\t\tif (!sessionStringified && (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase)) return null;\n\t\t\t\tif (sessionStringified) {\n\t\t\t\t\tconst s = safeJSONParse(sessionStringified);\n\t\t\t\t\tif (!s) return null;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsession: parseSessionOutput(ctx.options, {\n\t\t\t\t\t\t\t...s.session,\n\t\t\t\t\t\t\texpiresAt: new Date(s.session.expiresAt),\n\t\t\t\t\t\t\tcreatedAt: new Date(s.session.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(s.session.updatedAt)\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tuser: parseUserOutput(ctx.options, {\n\t\t\t\t\t\t\t...s.user,\n\t\t\t\t\t\t\tcreatedAt: new Date(s.user.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(s.user.updatedAt)\n\t\t\t\t\t\t})\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst result = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"session\",\n\t\t\t\twhere: [{\n\t\t\t\t\tvalue: token,\n\t\t\t\t\tfield: \"token\"\n\t\t\t\t}],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { user, ...session } = result;\n\t\t\tif (!user) return null;\n\t\t\treturn {\n\t\t\t\tsession: parseSessionOutput(ctx.options, session),\n\t\t\t\tuser: parseUserOutput(ctx.options, user)\n\t\t\t};\n\t\t},\n\t\tfindSessions: async (sessionTokens, options) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst sessions = [];\n\t\t\t\tfor (const sessionToken of sessionTokens) {\n\t\t\t\t\tconst sessionStringified = await secondaryStorage.get(sessionToken);\n\t\t\t\t\tif (sessionStringified) try {\n\t\t\t\t\t\tconst s = typeof sessionStringified === \"string\" ? JSON.parse(sessionStringified) : sessionStringified;\n\t\t\t\t\t\tif (!s) return [];\n\t\t\t\t\t\tconst expiresAt = new Date(s.session.expiresAt);\n\t\t\t\t\t\tif (options?.onlyActiveSessions && expiresAt <= /* @__PURE__ */ new Date()) continue;\n\t\t\t\t\t\tconst session = {\n\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t...s.session,\n\t\t\t\t\t\t\t\texpiresAt: new Date(s.session.expiresAt)\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\t\t...s.user,\n\t\t\t\t\t\t\t\tcreatedAt: new Date(s.user.createdAt),\n\t\t\t\t\t\t\t\tupdatedAt: new Date(s.user.updatedAt)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsessions.push(session);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn sessions;\n\t\t\t}\n\t\t\tconst sessions = await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"session\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"token\",\n\t\t\t\t\tvalue: sessionTokens,\n\t\t\t\t\toperator: \"in\"\n\t\t\t\t}, ...options?.onlyActiveSessions ? [{\n\t\t\t\t\tfield: \"expiresAt\",\n\t\t\t\t\tvalue: /* @__PURE__ */ new Date(),\n\t\t\t\t\toperator: \"gt\"\n\t\t\t\t}] : []],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (!sessions.length) return [];\n\t\t\tif (sessions.some((session) => !session.user)) return [];\n\t\t\treturn sessions.map((_session) => {\n\t\t\t\tconst { user, ...session } = _session;\n\t\t\t\treturn {\n\t\t\t\t\tsession,\n\t\t\t\t\tuser\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tupdateSession: async (sessionToken, session) => {\n\t\t\treturn await updateWithHooks(session, [{\n\t\t\t\tfield: \"token\",\n\t\t\t\tvalue: sessionToken\n\t\t\t}], \"session\", secondaryStorage ? {\n\t\t\t\tasync fn(data) {\n\t\t\t\t\tconst currentSession = await secondaryStorage.get(sessionToken);\n\t\t\t\t\tif (!currentSession) return null;\n\t\t\t\t\tconst parsedSession = safeJSONParse(currentSession);\n\t\t\t\t\tif (!parsedSession) return null;\n\t\t\t\t\tconst mergedSession = {\n\t\t\t\t\t\t...parsedSession.session,\n\t\t\t\t\t\t...data,\n\t\t\t\t\t\texpiresAt: new Date(data.expiresAt ?? parsedSession.session.expiresAt),\n\t\t\t\t\t\tcreatedAt: new Date(parsedSession.session.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(data.updatedAt ?? parsedSession.session.updatedAt)\n\t\t\t\t\t};\n\t\t\t\t\tconst updatedSession = parseSessionOutput(ctx.options, mergedSession);\n\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\tconst expiresMs = new Date(updatedSession.expiresAt).getTime();\n\t\t\t\t\tconst sessionTTL = getTTLSeconds(expiresMs, now);\n\t\t\t\t\tif (sessionTTL > 0) {\n\t\t\t\t\t\tawait secondaryStorage.set(sessionToken, JSON.stringify({\n\t\t\t\t\t\t\tsession: updatedSession,\n\t\t\t\t\t\t\tuser: parsedSession.user\n\t\t\t\t\t\t}), sessionTTL);\n\t\t\t\t\t\tconst listKey = `active-sessions-${updatedSession.userId}`;\n\t\t\t\t\t\tconst listRaw = await secondaryStorage.get(listKey);\n\t\t\t\t\t\tconst sorted = (listRaw ? safeJSONParse(listRaw) || [] : []).filter((s) => s.token !== sessionToken && s.expiresAt > now).concat([{\n\t\t\t\t\t\t\ttoken: sessionToken,\n\t\t\t\t\t\t\texpiresAt: expiresMs\n\t\t\t\t\t\t}]).sort((a, b) => a.expiresAt - b.expiresAt);\n\t\t\t\t\t\tconst furthestSessionExp = sorted.at(-1)?.expiresAt;\n\t\t\t\t\t\tif (furthestSessionExp && furthestSessionExp > now) await secondaryStorage.set(listKey, JSON.stringify(sorted), getTTLSeconds(furthestSessionExp, now));\n\t\t\t\t\t\telse await secondaryStorage.delete(listKey);\n\t\t\t\t\t}\n\t\t\t\t\treturn updatedSession;\n\t\t\t\t},\n\t\t\t\texecuteMainFn: options.session?.storeSessionInDatabase\n\t\t\t} : void 0);\n\t\t},\n\t\tdeleteSession: async (token) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst data = await secondaryStorage.get(token);\n\t\t\t\tif (data) {\n\t\t\t\t\tconst { session } = safeJSONParse(data) ?? {};\n\t\t\t\t\tif (!session) {\n\t\t\t\t\t\tlogger.error(\"Session not found in secondary storage\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst userId = session.userId;\n\t\t\t\t\tconst currentList = await secondaryStorage.get(`active-sessions-${userId}`);\n\t\t\t\t\tif (currentList) {\n\t\t\t\t\t\tconst list = safeJSONParse(currentList) || [];\n\t\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\t\tconst filtered = list.filter((session) => session.expiresAt > now && session.token !== token);\n\t\t\t\t\t\tconst furthestSessionExp = filtered.sort((a, b) => a.expiresAt - b.expiresAt).at(-1)?.expiresAt;\n\t\t\t\t\t\tif (filtered.length > 0 && furthestSessionExp && furthestSessionExp > Date.now()) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(filtered), getTTLSeconds(furthestSessionExp, now));\n\t\t\t\t\t\telse await secondaryStorage.delete(`active-sessions-${userId}`);\n\t\t\t\t\t} else logger.error(\"Active sessions list not found in secondary storage\");\n\t\t\t\t}\n\t\t\t\tawait secondaryStorage.delete(token);\n\t\t\t\tif (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return;\n\t\t\t}\n\t\t\tawait deleteWithHooks([{\n\t\t\t\tfield: \"token\",\n\t\t\t\tvalue: token\n\t\t\t}], \"session\", void 0);\n\t\t},\n\t\tdeleteAccounts: async (userId) => {\n\t\t\tawait deleteManyWithHooks([{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"account\", void 0);\n\t\t},\n\t\tdeleteAccount: async (accountId) => {\n\t\t\tawait deleteWithHooks([{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: accountId\n\t\t\t}], \"account\", void 0);\n\t\t},\n\t\tdeleteSessions: async (userIdOrSessionTokens) => {\n\t\t\tif (secondaryStorage) {\n\t\t\t\tif (typeof userIdOrSessionTokens === \"string\") {\n\t\t\t\t\tconst activeSession = await secondaryStorage.get(`active-sessions-${userIdOrSessionTokens}`);\n\t\t\t\t\tconst sessions = activeSession ? safeJSONParse(activeSession) : [];\n\t\t\t\t\tif (!sessions) return;\n\t\t\t\t\tfor (const session of sessions) await secondaryStorage.delete(session.token);\n\t\t\t\t\tawait secondaryStorage.delete(`active-sessions-${userIdOrSessionTokens}`);\n\t\t\t\t} else for (const sessionToken of userIdOrSessionTokens) if (await secondaryStorage.get(sessionToken)) await secondaryStorage.delete(sessionToken);\n\t\t\t\tif (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return;\n\t\t\t}\n\t\t\tawait deleteManyWithHooks([{\n\t\t\t\tfield: Array.isArray(userIdOrSessionTokens) ? \"token\" : \"userId\",\n\t\t\t\tvalue: userIdOrSessionTokens,\n\t\t\t\toperator: Array.isArray(userIdOrSessionTokens) ? \"in\" : void 0\n\t\t\t}], \"session\", void 0);\n\t\t},\n\t\tfindOAuthUser: async (email, accountId, providerId) => {\n\t\t\tconst account = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tvalue: accountId,\n\t\t\t\t\tfield: \"accountId\"\n\t\t\t\t}, {\n\t\t\t\t\tvalue: providerId,\n\t\t\t\t\tfield: \"providerId\"\n\t\t\t\t}],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (account) if (account.user) return {\n\t\t\t\tuser: account.user,\n\t\t\t\tlinkedAccount: account,\n\t\t\t\taccounts: [account]\n\t\t\t};\n\t\t\telse {\n\t\t\t\tconst user = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tvalue: email.toLowerCase(),\n\t\t\t\t\t\tfield: \"email\"\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (user) return {\n\t\t\t\t\tuser,\n\t\t\t\t\tlinkedAccount: account,\n\t\t\t\t\taccounts: [account]\n\t\t\t\t};\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst user = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tvalue: email.toLowerCase(),\n\t\t\t\t\t\tfield: \"email\"\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (user) return {\n\t\t\t\t\tuser,\n\t\t\t\t\tlinkedAccount: null,\n\t\t\t\t\taccounts: await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\t\t\tmodel: \"account\",\n\t\t\t\t\t\twhere: [{\n\t\t\t\t\t\t\tvalue: user.id,\n\t\t\t\t\t\t\tfield: \"userId\"\n\t\t\t\t\t\t}]\n\t\t\t\t\t}) || []\n\t\t\t\t};\n\t\t\t\telse return null;\n\t\t\t}\n\t\t},\n\t\tfindUserByEmail: async (email, options) => {\n\t\t\tconst result = await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tvalue: email.toLowerCase(),\n\t\t\t\t\tfield: \"email\"\n\t\t\t\t}],\n\t\t\t\tjoin: { ...options?.includeAccounts ? { account: true } : {} }\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { account: accounts, ...user } = result;\n\t\t\treturn {\n\t\t\t\tuser,\n\t\t\t\taccounts: accounts ?? []\n\t\t\t};\n\t\t},\n\t\tfindUserById: async (userId) => {\n\t\t\tif (!userId) return null;\n\t\t\treturn await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tlinkAccount: async (account) => {\n\t\t\treturn await createWithHooks({\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...account\n\t\t\t}, \"account\", void 0);\n\t\t},\n\t\tupdateUser: async (userId, data) => {\n\t\t\tconst user = await updateWithHooks(data, [{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: userId\n\t\t\t}], \"user\", void 0);\n\t\t\tawait refreshUserSessions(user);\n\t\t\treturn user;\n\t\t},\n\t\tupdateUserByEmail: async (email, data) => {\n\t\t\tconst user = await updateWithHooks(data, [{\n\t\t\t\tfield: \"email\",\n\t\t\t\tvalue: email.toLowerCase()\n\t\t\t}], \"user\", void 0);\n\t\t\tawait refreshUserSessions(user);\n\t\t\treturn user;\n\t\t},\n\t\tupdatePassword: async (userId, password) => {\n\t\t\tawait updateManyWithHooks({ password }, [{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: userId\n\t\t\t}, {\n\t\t\t\tfield: \"providerId\",\n\t\t\t\tvalue: \"credential\"\n\t\t\t}], \"account\", void 0);\n\t\t},\n\t\tfindAccounts: async (userId) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindAccount: async (accountId) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"accountId\",\n\t\t\t\t\tvalue: accountId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindAccountByProviderId: async (accountId, providerId) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findOne({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"accountId\",\n\t\t\t\t\tvalue: accountId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"providerId\",\n\t\t\t\t\tvalue: providerId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindAccountByUserId: async (userId) => {\n\t\t\treturn await (await getCurrentAdapter(adapter)).findMany({\n\t\t\t\tmodel: \"account\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tupdateAccount: async (id, data) => {\n\t\t\treturn await updateWithHooks(data, [{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: id\n\t\t\t}], \"account\", void 0);\n\t\t},\n\t\tcreateVerificationValue: async (data) => {\n\t\t\tconst storageOption = getStorageOption(data.identifier, options.verification?.storeIdentifier);\n\t\t\tconst storedIdentifier = await processIdentifier(data.identifier, storageOption);\n\t\t\treturn await createWithHooks({\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t...data,\n\t\t\t\tidentifier: storedIdentifier\n\t\t\t}, \"verification\", secondaryStorage ? {\n\t\t\t\tasync fn(verificationData) {\n\t\t\t\t\tconst ttl = getTTLSeconds(verificationData.expiresAt);\n\t\t\t\t\tif (ttl > 0) await secondaryStorage.set(`verification:${storedIdentifier}`, JSON.stringify(verificationData), ttl);\n\t\t\t\t\treturn verificationData;\n\t\t\t\t},\n\t\t\t\texecuteMainFn: options.verification?.storeInDatabase\n\t\t\t} : void 0);\n\t\t},\n\t\tfindVerificationValue: async (identifier) => {\n\t\t\tconst storageOption = getStorageOption(identifier, options.verification?.storeIdentifier);\n\t\t\tconst storedIdentifier = await processIdentifier(identifier, storageOption);\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst cached = await secondaryStorage.get(`verification:${storedIdentifier}`);\n\t\t\t\tif (cached) {\n\t\t\t\t\tconst parsed = safeJSONParse(cached);\n\t\t\t\t\tif (parsed) return parsed;\n\t\t\t\t}\n\t\t\t\tif (storageOption && storageOption !== \"plain\") {\n\t\t\t\t\tconst plainCached = await secondaryStorage.get(`verification:${identifier}`);\n\t\t\t\t\tif (plainCached) {\n\t\t\t\t\t\tconst parsed = safeJSONParse(plainCached);\n\t\t\t\t\t\tif (parsed) return parsed;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!options.verification?.storeInDatabase) return null;\n\t\t\t}\n\t\t\tconst currentAdapter = await getCurrentAdapter(adapter);\n\t\t\tasync function findByIdentifier(id) {\n\t\t\t\treturn currentAdapter.findMany({\n\t\t\t\t\tmodel: \"verification\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"identifier\",\n\t\t\t\t\t\tvalue: id\n\t\t\t\t\t}],\n\t\t\t\t\tsortBy: {\n\t\t\t\t\t\tfield: \"createdAt\",\n\t\t\t\t\t\tdirection: \"desc\"\n\t\t\t\t\t},\n\t\t\t\t\tlimit: 1\n\t\t\t\t});\n\t\t\t}\n\t\t\tlet verification = await findByIdentifier(storedIdentifier);\n\t\t\tif (!verification.length && storageOption && storageOption !== \"plain\") verification = await findByIdentifier(identifier);\n\t\t\tif (!options.verification?.disableCleanup) await deleteManyWithHooks([{\n\t\t\t\tfield: \"expiresAt\",\n\t\t\t\tvalue: /* @__PURE__ */ new Date(),\n\t\t\t\toperator: \"lt\"\n\t\t\t}], \"verification\", void 0);\n\t\t\treturn verification[0] || null;\n\t\t},\n\t\tdeleteVerificationByIdentifier: async (identifier) => {\n\t\t\tconst storedIdentifier = await processIdentifier(identifier, getStorageOption(identifier, options.verification?.storeIdentifier));\n\t\t\tif (secondaryStorage) await secondaryStorage.delete(`verification:${storedIdentifier}`);\n\t\t\tif (!secondaryStorage || options.verification?.storeInDatabase) await deleteWithHooks([{\n\t\t\t\tfield: \"identifier\",\n\t\t\t\tvalue: storedIdentifier\n\t\t\t}], \"verification\", void 0);\n\t\t},\n\t\tupdateVerificationByIdentifier: async (identifier, data) => {\n\t\t\tconst storedIdentifier = await processIdentifier(identifier, getStorageOption(identifier, options.verification?.storeIdentifier));\n\t\t\tif (secondaryStorage) {\n\t\t\t\tconst cached = await secondaryStorage.get(`verification:${storedIdentifier}`);\n\t\t\t\tif (cached) {\n\t\t\t\t\tconst parsed = safeJSONParse(cached);\n\t\t\t\t\tif (parsed) {\n\t\t\t\t\t\tconst updated = {\n\t\t\t\t\t\t\t...parsed,\n\t\t\t\t\t\t\t...data\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst expiresAt = updated.expiresAt ?? parsed.expiresAt;\n\t\t\t\t\t\tconst ttl = getTTLSeconds(expiresAt instanceof Date ? expiresAt : new Date(expiresAt));\n\t\t\t\t\t\tif (ttl > 0) await secondaryStorage.set(`verification:${storedIdentifier}`, JSON.stringify(updated), ttl);\n\t\t\t\t\t\tif (!options.verification?.storeInDatabase) return updated;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!secondaryStorage || options.verification?.storeInDatabase) return await updateWithHooks(data, [{\n\t\t\t\tfield: \"identifier\",\n\t\t\t\tvalue: storedIdentifier\n\t\t\t}], \"verification\", void 0);\n\t\t\treturn data;\n\t\t}\n\t};\n};\n//#endregion\nexport { createInternalAdapter };\n", "import { getBaseURL, isDynamicBaseURLConfig } from \"../utils/url.mjs\";\nimport { createInternalAdapter } from \"../db/internal-adapter.mjs\";\nimport { isPromise } from \"../utils/is-promise.mjs\";\nimport { env } from \"@better-auth/core/env\";\nimport { defu } from \"defu\";\n//#region src/context/helpers.ts\nasync function runPluginInit(context) {\n\tlet options = context.options;\n\tconst plugins = options.plugins || [];\n\tconst pluginTrustedOrigins = [];\n\tconst dbHooks = [];\n\tfor (const plugin of plugins) if (plugin.init) {\n\t\tconst initPromise = plugin.init(context);\n\t\tlet result;\n\t\tif (isPromise(initPromise)) result = await initPromise;\n\t\telse result = initPromise;\n\t\tif (typeof result === \"object\") {\n\t\t\tif (result.options) {\n\t\t\t\tconst { databaseHooks, trustedOrigins, ...restOpts } = result.options;\n\t\t\t\tif (databaseHooks) dbHooks.push({\n\t\t\t\t\tsource: `plugin:${plugin.id}`,\n\t\t\t\t\thooks: databaseHooks\n\t\t\t\t});\n\t\t\t\tif (trustedOrigins) pluginTrustedOrigins.push(trustedOrigins);\n\t\t\t\toptions = defu(options, restOpts);\n\t\t\t}\n\t\t\tif (result.context) Object.assign(context, result.context);\n\t\t}\n\t}\n\tif (pluginTrustedOrigins.length > 0) {\n\t\tconst allSources = [...options.trustedOrigins ? [options.trustedOrigins] : [], ...pluginTrustedOrigins];\n\t\tconst staticOrigins = allSources.filter(Array.isArray).flat();\n\t\tconst dynamicOrigins = allSources.filter((s) => typeof s === \"function\");\n\t\tif (dynamicOrigins.length > 0) options.trustedOrigins = async (request) => {\n\t\t\tconst resolved = await Promise.all(dynamicOrigins.map((fn) => fn(request)));\n\t\t\treturn [...staticOrigins, ...resolved.flat()].filter((v) => typeof v === \"string\" && v !== \"\");\n\t\t};\n\t\telse options.trustedOrigins = staticOrigins;\n\t}\n\tif (options.databaseHooks) dbHooks.push({\n\t\tsource: \"user\",\n\t\thooks: options.databaseHooks\n\t});\n\tcontext.internalAdapter = createInternalAdapter(context.adapter, {\n\t\toptions,\n\t\tlogger: context.logger,\n\t\thooks: dbHooks,\n\t\tgenerateId: context.generateId\n\t});\n\tcontext.options = options;\n}\nfunction getInternalPlugins(options) {\n\tconst plugins = [];\n\tif (options.advanced?.crossSubDomainCookies?.enabled) {}\n\treturn plugins;\n}\nasync function getTrustedOrigins(options, request) {\n\tconst trustedOrigins = [];\n\tif (isDynamicBaseURLConfig(options.baseURL)) {\n\t\tconst allowedHosts = options.baseURL.allowedHosts;\n\t\tfor (const host of allowedHosts) if (!host.includes(\"://\")) {\n\t\t\ttrustedOrigins.push(`https://${host}`);\n\t\t\tif (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) trustedOrigins.push(`http://${host}`);\n\t\t} else trustedOrigins.push(host);\n\t\tif (options.baseURL.fallback) try {\n\t\t\ttrustedOrigins.push(new URL(options.baseURL.fallback).origin);\n\t\t} catch {}\n\t} else {\n\t\tconst baseURL = getBaseURL(typeof options.baseURL === \"string\" ? options.baseURL : void 0, options.basePath, request);\n\t\tif (baseURL) trustedOrigins.push(new URL(baseURL).origin);\n\t}\n\tif (options.trustedOrigins) {\n\t\tif (Array.isArray(options.trustedOrigins)) trustedOrigins.push(...options.trustedOrigins);\n\t\tif (typeof options.trustedOrigins === \"function\") {\n\t\t\tconst validOrigins = await options.trustedOrigins(request);\n\t\t\ttrustedOrigins.push(...validOrigins);\n\t\t}\n\t}\n\tconst envTrustedOrigins = env.BETTER_AUTH_TRUSTED_ORIGINS;\n\tif (envTrustedOrigins) trustedOrigins.push(...envTrustedOrigins.split(\",\"));\n\treturn trustedOrigins.filter((v) => Boolean(v));\n}\nasync function getAwaitableValue(arr, item) {\n\tif (!arr) return void 0;\n\tfor (const val of arr) {\n\t\tconst value = typeof val === \"function\" ? await val() : val;\n\t\tif (value[item.field ?? \"id\"] === item.value) return value;\n\t}\n}\nasync function getTrustedProviders(options, request) {\n\tconst trustedProviders = options.account?.accountLinking?.trustedProviders;\n\tif (!trustedProviders) return [];\n\tif (Array.isArray(trustedProviders)) return trustedProviders.filter((v) => Boolean(v));\n\treturn (await trustedProviders(request) ?? []).filter((v) => Boolean(v));\n}\n//#endregion\nexport { getAwaitableValue, getInternalPlugins, getTrustedOrigins, getTrustedProviders, runPluginInit };\n", "function isPlainObject(value) {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {\n return false;\n }\n if (Symbol.iterator in value) {\n return false;\n }\n if (Symbol.toStringTag in value) {\n return Object.prototype.toString.call(value) === \"[object Module]\";\n }\n return true;\n}\n\nfunction _defu(baseObject, defaults, namespace = \".\", merger) {\n if (!isPlainObject(defaults)) {\n return _defu(baseObject, {}, namespace, merger);\n }\n const object = { ...defaults };\n for (const key of Object.keys(baseObject)) {\n if (key === \"__proto__\" || key === \"constructor\") {\n continue;\n }\n const value = baseObject[key];\n if (value === null || value === void 0) {\n continue;\n }\n if (merger && merger(object, key, value, namespace)) {\n continue;\n }\n if (Array.isArray(value) && Array.isArray(object[key])) {\n object[key] = [...value, ...object[key]];\n } else if (isPlainObject(value) && isPlainObject(object[key])) {\n object[key] = _defu(\n value,\n object[key],\n (namespace ? `${namespace}.` : \"\") + key.toString(),\n merger\n );\n } else {\n object[key] = value;\n }\n }\n return object;\n}\nfunction createDefu(merger) {\n return (...arguments_) => (\n // eslint-disable-next-line unicorn/no-array-reduce\n arguments_.reduce((p, c) => _defu(p, c, \"\", merger), {})\n );\n}\nconst defu = createDefu();\nconst defuFn = createDefu((object, key, currentValue) => {\n if (object[key] !== void 0 && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\nconst defuArrayFn = createDefu((object, key, currentValue) => {\n if (Array.isArray(object[key]) && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\n\nexport { createDefu, defu as default, defu, defuArrayFn, defuFn };\n", "import { symmetricDecrypt, symmetricEncrypt } from \"../crypto/index.mjs\";\n//#region src/oauth2/utils.ts\n/**\n* Check if a string looks like encrypted data\n*/\nfunction isLikelyEncrypted(token) {\n\tif (token.startsWith(\"$ba$\")) return true;\n\treturn token.length % 2 === 0 && /^[0-9a-f]+$/i.test(token);\n}\nfunction decryptOAuthToken(token, ctx) {\n\tif (!token) return token;\n\tif (ctx.options.account?.encryptOAuthTokens) {\n\t\tif (!isLikelyEncrypted(token)) return token;\n\t\treturn symmetricDecrypt({\n\t\t\tkey: ctx.secretConfig,\n\t\t\tdata: token\n\t\t});\n\t}\n\treturn token;\n}\nfunction setTokenUtil(token, ctx) {\n\tif (ctx.options.account?.encryptOAuthTokens && token) return symmetricEncrypt({\n\t\tkey: ctx.secretConfig,\n\t\tdata: token\n\t});\n\treturn token;\n}\n//#endregion\nexport { decryptOAuthToken, setTokenUtil };\n", "import { parseAccountOutput } from \"../../db/schema.mjs\";\nimport { getAwaitableValue } from \"../../context/helpers.mjs\";\nimport { getAccountCookie, setAccountCookie } from \"../../cookies/session-store.mjs\";\nimport { generateState } from \"../../oauth2/state.mjs\";\nimport { decryptOAuthToken, setTokenUtil } from \"../../oauth2/utils.mjs\";\nimport { freshSessionMiddleware, getSessionFromCtx, sessionMiddleware } from \"./session.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { SocialProviderListEnum } from \"@better-auth/core/social-providers\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/account.ts\nconst listUserAccounts = createAuthEndpoint(\"/list-accounts\", {\n\tmethod: \"GET\",\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: {\n\t\toperationId: \"listUserAccounts\",\n\t\tdescription: \"List all accounts linked to the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\tproviderId: { type: \"string\" },\n\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\taccountId: { type: \"string\" },\n\t\t\t\t\t\tuserId: { type: \"string\" },\n\t\t\t\t\t\tscopes: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" }\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"providerId\",\n\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\"updatedAt\",\n\t\t\t\t\t\t\"accountId\",\n\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\"scopes\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (c) => {\n\tconst session = c.context.session;\n\tconst accounts = await c.context.internalAdapter.findAccounts(session.user.id);\n\treturn c.json(accounts.map((a) => {\n\t\tconst { scope, ...parsed } = parseAccountOutput(c.context.options, a);\n\t\treturn {\n\t\t\t...parsed,\n\t\t\tscopes: scope?.split(\",\") || []\n\t\t};\n\t}));\n});\nconst linkSocialAccount = createAuthEndpoint(\"/link-social\", {\n\tmethod: \"POST\",\n\trequireHeaders: true,\n\tbody: z.object({\n\t\tcallbackURL: z.string().meta({ description: \"The URL to redirect to after the user has signed in\" }).optional(),\n\t\tprovider: SocialProviderListEnum,\n\t\tidToken: z.object({\n\t\t\ttoken: z.string(),\n\t\t\tnonce: z.string().optional(),\n\t\t\taccessToken: z.string().optional(),\n\t\t\trefreshToken: z.string().optional(),\n\t\t\tscopes: z.array(z.string()).optional()\n\t\t}).optional(),\n\t\trequestSignUp: z.boolean().optional(),\n\t\tscopes: z.array(z.string()).meta({ description: \"Additional scopes to request from the provider\" }).optional(),\n\t\terrorCallbackURL: z.string().meta({ description: \"The URL to redirect to if there is an error during the link process\" }).optional(),\n\t\tdisableRedirect: z.boolean().meta({ description: \"Disable automatic redirection to the provider. Useful for handling the redirection yourself\" }).optional(),\n\t\tadditionalData: z.record(z.string(), z.any()).optional()\n\t}),\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Link a social account to the user\",\n\t\toperationId: \"linkSocialAccount\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\turl: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The authorization URL to redirect the user to\"\n\t\t\t\t\t},\n\t\t\t\t\tredirect: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the user should be redirected to the authorization URL\"\n\t\t\t\t\t},\n\t\t\t\t\tstatus: { type: \"boolean\" }\n\t\t\t\t},\n\t\t\t\trequired: [\"redirect\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (c) => {\n\tconst session = c.context.session;\n\tconst provider = await getAwaitableValue(c.context.socialProviders, { value: c.body.provider });\n\tif (!provider) {\n\t\tc.context.logger.error(\"Provider not found. Make sure to add the provider in your auth config\", { provider: c.body.provider });\n\t\tthrow APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.PROVIDER_NOT_FOUND);\n\t}\n\tif (c.body.idToken) {\n\t\tif (!provider.verifyIdToken) {\n\t\t\tc.context.logger.error(\"Provider does not support id token verification\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);\n\t\t}\n\t\tconst { token, nonce } = c.body.idToken;\n\t\tif (!await provider.verifyIdToken(token, nonce)) {\n\t\t\tc.context.logger.error(\"Invalid id token\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_TOKEN);\n\t\t}\n\t\tconst linkingUserInfo = await provider.getUserInfo({\n\t\t\tidToken: token,\n\t\t\taccessToken: c.body.idToken.accessToken,\n\t\t\trefreshToken: c.body.idToken.refreshToken\n\t\t});\n\t\tif (!linkingUserInfo || !linkingUserInfo?.user) {\n\t\t\tc.context.logger.error(\"Failed to get user info\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);\n\t\t}\n\t\tconst linkingUserId = String(linkingUserInfo.user.id);\n\t\tif (!linkingUserInfo.user.email) {\n\t\t\tc.context.logger.error(\"User email not found\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);\n\t\t}\n\t\tif ((await c.context.internalAdapter.findAccounts(session.user.id)).find((a) => a.providerId === provider.id && a.accountId === linkingUserId)) return c.json({\n\t\t\turl: \"\",\n\t\t\tstatus: true,\n\t\t\tredirect: false\n\t\t});\n\t\tif (!c.context.trustedProviders.includes(provider.id) && !linkingUserInfo.user.emailVerified || c.context.options.account?.accountLinking?.enabled === false) throw APIError.from(\"UNAUTHORIZED\", {\n\t\t\tmessage: \"Account not linked - linking not allowed\",\n\t\t\tcode: \"LINKING_NOT_ALLOWED\"\n\t\t});\n\t\tif (linkingUserInfo.user.email?.toLowerCase() !== session.user.email.toLowerCase() && c.context.options.account?.accountLinking?.allowDifferentEmails !== true) throw APIError.from(\"UNAUTHORIZED\", {\n\t\t\tmessage: \"Account not linked - different emails not allowed\",\n\t\t\tcode: \"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED\"\n\t\t});\n\t\ttry {\n\t\t\tawait c.context.internalAdapter.createAccount({\n\t\t\t\tuserId: session.user.id,\n\t\t\t\tproviderId: provider.id,\n\t\t\t\taccountId: linkingUserId,\n\t\t\t\taccessToken: c.body.idToken.accessToken,\n\t\t\t\tidToken: token,\n\t\t\t\trefreshToken: c.body.idToken.refreshToken,\n\t\t\t\tscope: c.body.idToken.scopes?.join(\",\")\n\t\t\t});\n\t\t} catch (_e) {\n\t\t\tthrow APIError.from(\"EXPECTATION_FAILED\", {\n\t\t\t\tmessage: \"Account not linked - unable to create account\",\n\t\t\t\tcode: \"LINKING_FAILED\"\n\t\t\t});\n\t\t}\n\t\tif (c.context.options.account?.accountLinking?.updateUserInfoOnLink === true) try {\n\t\t\tawait c.context.internalAdapter.updateUser(session.user.id, {\n\t\t\t\tname: linkingUserInfo.user?.name,\n\t\t\t\timage: linkingUserInfo.user?.image\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.warn(\"Could not update user - \" + e.toString());\n\t\t}\n\t\treturn c.json({\n\t\t\turl: \"\",\n\t\t\tstatus: true,\n\t\t\tredirect: false\n\t\t});\n\t}\n\tconst state = await generateState(c, {\n\t\tuserId: session.user.id,\n\t\temail: session.user.email\n\t}, c.body.additionalData);\n\tconst url = await provider.createAuthorizationURL({\n\t\tstate: state.state,\n\t\tcodeVerifier: state.codeVerifier,\n\t\tredirectURI: `${c.context.baseURL}/callback/${provider.id}`,\n\t\tscopes: c.body.scopes\n\t});\n\tif (!c.body.disableRedirect) c.setHeader(\"Location\", url.toString());\n\treturn c.json({\n\t\turl: url.toString(),\n\t\tredirect: !c.body.disableRedirect\n\t});\n});\nconst unlinkAccount = createAuthEndpoint(\"/unlink-account\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tproviderId: z.string(),\n\t\taccountId: z.string().optional()\n\t}),\n\tuse: [freshSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Unlink an account\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst { providerId, accountId } = ctx.body;\n\tconst accounts = await ctx.context.internalAdapter.findAccounts(ctx.context.session.user.id);\n\tif (accounts.length === 1 && !ctx.context.options.account?.accountLinking?.allowUnlinkingAll) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT);\n\tconst accountExist = accounts.find((account) => accountId ? account.accountId === accountId && account.providerId === providerId : account.providerId === providerId);\n\tif (!accountExist) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);\n\tawait ctx.context.internalAdapter.deleteAccount(accountExist.id);\n\treturn ctx.json({ status: true });\n});\nconst getAccessToken = createAuthEndpoint(\"/get-access-token\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tproviderId: z.string().meta({ description: \"The provider ID for the OAuth provider\" }),\n\t\taccountId: z.string().meta({ description: \"The account ID associated with the refresh token\" }).optional(),\n\t\tuserId: z.string().meta({ description: \"The user ID associated with the account\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\tdescription: \"Get a valid access token, doing a refresh if needed\",\n\t\tresponses: {\n\t\t\t200: {\n\t\t\t\tdescription: \"A Valid access token\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttokenType: { type: \"string\" },\n\t\t\t\t\t\tidToken: { type: \"string\" },\n\t\t\t\t\t\taccessToken: { type: \"string\" },\n\t\t\t\t\t\taccessTokenExpiresAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} } }\n\t\t\t},\n\t\t\t400: { description: \"Invalid refresh token or provider configuration\" }\n\t\t}\n\t} }\n}, async (ctx) => {\n\tconst { providerId, accountId, userId } = ctx.body || {};\n\tconst req = ctx.request;\n\tconst session = await getSessionFromCtx(ctx);\n\tif (req && !session) throw ctx.error(\"UNAUTHORIZED\");\n\tconst resolvedUserId = session?.user?.id || userId;\n\tif (!resolvedUserId) throw ctx.error(\"UNAUTHORIZED\");\n\tconst provider = await getAwaitableValue(ctx.context.socialProviders, { value: providerId });\n\tif (!provider) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: `Provider ${providerId} is not supported.`,\n\t\tcode: \"PROVIDER_NOT_SUPPORTED\"\n\t});\n\tconst accountData = await getAccountCookie(ctx);\n\tlet account = void 0;\n\tif (accountData && accountData.userId === resolvedUserId && providerId === accountData.providerId && (!accountId || accountData.accountId === accountId)) account = accountData;\n\telse account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.accountId === accountId && acc.providerId === providerId : acc.providerId === providerId);\n\tif (!account) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);\n\ttry {\n\t\tlet newTokens = null;\n\t\tconst accessTokenExpired = account.accessTokenExpiresAt && new Date(account.accessTokenExpiresAt).getTime() - Date.now() < 5e3;\n\t\tif (account.refreshToken && accessTokenExpired && provider.refreshAccessToken) {\n\t\t\tconst refreshToken = await decryptOAuthToken(account.refreshToken, ctx.context);\n\t\t\tnewTokens = await provider.refreshAccessToken(refreshToken);\n\t\t\tconst updatedData = {\n\t\t\t\taccessToken: await setTokenUtil(newTokens?.accessToken, ctx.context),\n\t\t\t\taccessTokenExpiresAt: newTokens?.accessTokenExpiresAt,\n\t\t\t\trefreshToken: newTokens?.refreshToken ? await setTokenUtil(newTokens.refreshToken, ctx.context) : account.refreshToken,\n\t\t\t\trefreshTokenExpiresAt: newTokens?.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt,\n\t\t\t\tidToken: newTokens?.idToken || account.idToken\n\t\t\t};\n\t\t\tlet updatedAccount = null;\n\t\t\tif (account.id) updatedAccount = await ctx.context.internalAdapter.updateAccount(account.id, updatedData);\n\t\t\tif (ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, {\n\t\t\t\t...account,\n\t\t\t\t...updatedAccount ?? updatedData\n\t\t\t});\n\t\t}\n\t\tconst accessTokenExpiresAt = (() => {\n\t\t\tif (newTokens?.accessTokenExpiresAt) {\n\t\t\t\tif (typeof newTokens.accessTokenExpiresAt === \"string\") return new Date(newTokens.accessTokenExpiresAt);\n\t\t\t\treturn newTokens.accessTokenExpiresAt;\n\t\t\t}\n\t\t\tif (account.accessTokenExpiresAt) {\n\t\t\t\tif (typeof account.accessTokenExpiresAt === \"string\") return new Date(account.accessTokenExpiresAt);\n\t\t\t\treturn account.accessTokenExpiresAt;\n\t\t\t}\n\t\t})();\n\t\tconst tokens = {\n\t\t\taccessToken: newTokens?.accessToken ?? await decryptOAuthToken(account.accessToken ?? \"\", ctx.context),\n\t\t\taccessTokenExpiresAt,\n\t\t\tscopes: account.scope?.split(\",\") ?? [],\n\t\t\tidToken: newTokens?.idToken ?? account.idToken ?? void 0\n\t\t};\n\t\treturn ctx.json(tokens);\n\t} catch (_error) {\n\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Failed to get a valid access token\",\n\t\t\tcode: \"FAILED_TO_GET_ACCESS_TOKEN\"\n\t\t});\n\t}\n});\nconst refreshToken = createAuthEndpoint(\"/refresh-token\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tproviderId: z.string().meta({ description: \"The provider ID for the OAuth provider\" }),\n\t\taccountId: z.string().meta({ description: \"The account ID associated with the refresh token\" }).optional(),\n\t\tuserId: z.string().meta({ description: \"The user ID associated with the account\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\tdescription: \"Refresh the access token using a refresh token\",\n\t\tresponses: {\n\t\t\t200: {\n\t\t\t\tdescription: \"Access token refreshed successfully\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttokenType: { type: \"string\" },\n\t\t\t\t\t\tidToken: { type: \"string\" },\n\t\t\t\t\t\taccessToken: { type: \"string\" },\n\t\t\t\t\t\trefreshToken: { type: \"string\" },\n\t\t\t\t\t\taccessTokenExpiresAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\trefreshTokenExpiresAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} } }\n\t\t\t},\n\t\t\t400: { description: \"Invalid refresh token or provider configuration\" }\n\t\t}\n\t} }\n}, async (ctx) => {\n\tconst { providerId, accountId, userId } = ctx.body;\n\tconst req = ctx.request;\n\tconst session = await getSessionFromCtx(ctx);\n\tif (req && !session) throw ctx.error(\"UNAUTHORIZED\");\n\tconst resolvedUserId = session?.user?.id || userId;\n\tif (!resolvedUserId) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: `Either userId or session is required`,\n\t\tcode: \"USER_ID_OR_SESSION_REQUIRED\"\n\t});\n\tconst provider = await getAwaitableValue(ctx.context.socialProviders, { value: providerId });\n\tif (!provider) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: `Provider ${providerId} is not supported.`,\n\t\tcode: \"PROVIDER_NOT_SUPPORTED\"\n\t});\n\tif (!provider.refreshAccessToken) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: `Provider ${providerId} does not support token refreshing.`,\n\t\tcode: \"TOKEN_REFRESH_NOT_SUPPORTED\"\n\t});\n\tlet account = void 0;\n\tconst accountData = await getAccountCookie(ctx);\n\tif (accountData && accountData.userId === resolvedUserId && (!providerId || providerId === accountData?.providerId)) account = accountData;\n\telse account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.accountId === accountId && acc.providerId === providerId : acc.providerId === providerId);\n\tif (!account) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);\n\tlet refreshToken = void 0;\n\tif (accountData && providerId === accountData.providerId) refreshToken = accountData.refreshToken ?? void 0;\n\telse refreshToken = account.refreshToken ?? void 0;\n\tif (!refreshToken) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: \"Refresh token not found\",\n\t\tcode: \"REFRESH_TOKEN_NOT_FOUND\"\n\t});\n\ttry {\n\t\tconst decryptedRefreshToken = await decryptOAuthToken(refreshToken, ctx.context);\n\t\tconst tokens = await provider.refreshAccessToken(decryptedRefreshToken);\n\t\tconst resolvedRefreshToken = tokens.refreshToken ? await setTokenUtil(tokens.refreshToken, ctx.context) : refreshToken;\n\t\tconst resolvedRefreshTokenExpiresAt = tokens.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt;\n\t\tif (account.id) {\n\t\t\tconst updateData = {\n\t\t\t\t...account || {},\n\t\t\t\taccessToken: await setTokenUtil(tokens.accessToken, ctx.context),\n\t\t\t\trefreshToken: resolvedRefreshToken,\n\t\t\t\taccessTokenExpiresAt: tokens.accessTokenExpiresAt,\n\t\t\t\trefreshTokenExpiresAt: resolvedRefreshTokenExpiresAt,\n\t\t\t\tscope: tokens.scopes?.join(\",\") || account.scope,\n\t\t\t\tidToken: tokens.idToken || account.idToken\n\t\t\t};\n\t\t\tawait ctx.context.internalAdapter.updateAccount(account.id, updateData);\n\t\t}\n\t\tif (accountData && providerId === accountData.providerId && ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, {\n\t\t\t...accountData,\n\t\t\taccessToken: await setTokenUtil(tokens.accessToken, ctx.context),\n\t\t\trefreshToken: resolvedRefreshToken,\n\t\t\taccessTokenExpiresAt: tokens.accessTokenExpiresAt,\n\t\t\trefreshTokenExpiresAt: resolvedRefreshTokenExpiresAt,\n\t\t\tscope: tokens.scopes?.join(\",\") || accountData.scope,\n\t\t\tidToken: tokens.idToken || accountData.idToken\n\t\t});\n\t\treturn ctx.json({\n\t\t\taccessToken: tokens.accessToken,\n\t\t\trefreshToken: tokens.refreshToken ?? decryptedRefreshToken,\n\t\t\taccessTokenExpiresAt: tokens.accessTokenExpiresAt,\n\t\t\trefreshTokenExpiresAt: resolvedRefreshTokenExpiresAt,\n\t\t\tscope: tokens.scopes?.join(\",\") || account.scope,\n\t\t\tidToken: tokens.idToken || account.idToken,\n\t\t\tproviderId: account.providerId,\n\t\t\taccountId: account.accountId\n\t\t});\n\t} catch (_error) {\n\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Failed to refresh access token\",\n\t\t\tcode: \"FAILED_TO_REFRESH_ACCESS_TOKEN\"\n\t\t});\n\t}\n});\nconst accountInfoQuerySchema = z.optional(z.object({ accountId: z.string().meta({ description: \"The provider given account id for which to get the account info\" }).optional() }));\nconst accountInfo = createAuthEndpoint(\"/account-info\", {\n\tmethod: \"GET\",\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Get the account info provided by the provider\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tuser: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\t\t\temail: { type: \"string\" },\n\t\t\t\t\t\t\timage: { type: \"string\" },\n\t\t\t\t\t\t\temailVerified: { type: \"boolean\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"id\", \"emailVerified\"]\n\t\t\t\t\t},\n\t\t\t\t\tdata: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\tadditionalProperties: true\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"user\", \"data\"],\n\t\t\t\tadditionalProperties: false\n\t\t\t} } }\n\t\t} }\n\t} },\n\tquery: accountInfoQuerySchema\n}, async (ctx) => {\n\tconst providedAccountId = ctx.query?.accountId;\n\tlet account = void 0;\n\tif (!providedAccountId) {\n\t\tif (ctx.context.options.account?.storeAccountCookie) {\n\t\t\tconst accountData = await getAccountCookie(ctx);\n\t\t\tif (accountData) account = accountData;\n\t\t}\n\t} else {\n\t\tconst accountData = await ctx.context.internalAdapter.findAccount(providedAccountId);\n\t\tif (accountData) account = accountData;\n\t}\n\tif (!account || account.userId !== ctx.context.session.user.id) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);\n\tconst provider = await getAwaitableValue(ctx.context.socialProviders, { value: account.providerId });\n\tif (!provider) throw APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\tmessage: `Provider account provider is ${account.providerId} but it is not configured`,\n\t\tcode: \"PROVIDER_NOT_CONFIGURED\"\n\t});\n\tconst tokens = await getAccessToken({\n\t\t...ctx,\n\t\tmethod: \"POST\",\n\t\tbody: {\n\t\t\taccountId: account.accountId,\n\t\t\tproviderId: account.providerId\n\t\t},\n\t\treturnHeaders: false,\n\t\treturnStatus: false\n\t});\n\tif (!tokens.accessToken) throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: \"Access token not found\",\n\t\tcode: \"ACCESS_TOKEN_NOT_FOUND\"\n\t});\n\tconst info = await provider.getUserInfo({\n\t\t...tokens,\n\t\taccessToken: tokens.accessToken\n\t});\n\treturn ctx.json(info);\n});\n//#endregion\nexport { accountInfo, getAccessToken, linkSocialAccount, listUserAccounts, refreshToken, unlinkAccount };\n", "import { APIError } from \"../error/index.mjs\";\nimport { createAuthorizationURL } from \"../oauth2/create-authorization-url.mjs\";\nimport { refreshAccessToken } from \"../oauth2/refresh-access-token.mjs\";\nimport { validateAuthorizationCode } from \"../oauth2/validate-authorization-code.mjs\";\nimport { betterFetch } from \"@better-fetch/fetch\";\nimport { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from \"jose\";\n//#region src/social-providers/apple.ts\nconst apple = (options) => {\n\tconst tokenEndpoint = \"https://appleid.apple.com/auth/token\";\n\treturn {\n\t\tid: \"apple\",\n\t\tname: \"Apple\",\n\t\tasync createAuthorizationURL({ state, scopes, redirectURI }) {\n\t\t\tconst _scope = options.disableDefaultScope ? [] : [\"email\", \"name\"];\n\t\t\tif (options.scope) _scope.push(...options.scope);\n\t\t\tif (scopes) _scope.push(...scopes);\n\t\t\treturn await createAuthorizationURL({\n\t\t\t\tid: \"apple\",\n\t\t\t\toptions,\n\t\t\t\tauthorizationEndpoint: \"https://appleid.apple.com/auth/authorize\",\n\t\t\t\tscopes: _scope,\n\t\t\t\tstate,\n\t\t\t\tredirectURI,\n\t\t\t\tresponseMode: \"form_post\",\n\t\t\t\tresponseType: \"code id_token\"\n\t\t\t});\n\t\t},\n\t\tvalidateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n\t\t\treturn validateAuthorizationCode({\n\t\t\t\tcode,\n\t\t\t\tcodeVerifier,\n\t\t\t\tredirectURI,\n\t\t\t\toptions,\n\t\t\t\ttokenEndpoint\n\t\t\t});\n\t\t},\n\t\tasync verifyIdToken(token, nonce) {\n\t\t\tif (options.disableIdTokenSignIn) return false;\n\t\t\tif (options.verifyIdToken) return options.verifyIdToken(token, nonce);\n\t\t\ttry {\n\t\t\t\tconst { kid, alg: jwtAlg } = decodeProtectedHeader(token);\n\t\t\t\tif (!kid || !jwtAlg) return false;\n\t\t\t\tconst { payload: jwtClaims } = await jwtVerify(token, await getApplePublicKey(kid), {\n\t\t\t\t\talgorithms: [jwtAlg],\n\t\t\t\t\tissuer: \"https://appleid.apple.com\",\n\t\t\t\t\taudience: options.audience && options.audience.length ? options.audience : options.appBundleIdentifier ? options.appBundleIdentifier : options.clientId,\n\t\t\t\t\tmaxTokenAge: \"1h\"\n\t\t\t\t});\n\t\t\t\t[\"email_verified\", \"is_private_email\"].forEach((field) => {\n\t\t\t\t\tif (jwtClaims[field] !== void 0) jwtClaims[field] = Boolean(jwtClaims[field]);\n\t\t\t\t});\n\t\t\t\tif (nonce && jwtClaims.nonce !== nonce) return false;\n\t\t\t\treturn !!jwtClaims;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t\trefreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n\t\t\treturn refreshAccessToken({\n\t\t\t\trefreshToken,\n\t\t\t\toptions,\n\t\t\t\ttokenEndpoint\n\t\t\t});\n\t\t},\n\t\tasync getUserInfo(token) {\n\t\t\tif (options.getUserInfo) return options.getUserInfo(token);\n\t\t\tif (!token.idToken) return null;\n\t\t\tconst profile = decodeJwt(token.idToken);\n\t\t\tif (!profile) return null;\n\t\t\tlet name;\n\t\t\tif (token.user?.name) name = `${token.user.name.firstName || \"\"} ${token.user.name.lastName || \"\"}`.trim();\n\t\t\telse name = profile.name || \"\";\n\t\t\tconst emailVerified = typeof profile.email_verified === \"boolean\" ? profile.email_verified : profile.email_verified === \"true\";\n\t\t\tconst enrichedProfile = {\n\t\t\t\t...profile,\n\t\t\t\tname\n\t\t\t};\n\t\t\tconst userMap = await options.mapProfileToUser?.(enrichedProfile);\n\t\t\treturn {\n\t\t\t\tuser: {\n\t\t\t\t\tid: profile.sub,\n\t\t\t\t\tname: enrichedProfile.name,\n\t\t\t\t\temailVerified,\n\t\t\t\t\temail: profile.email,\n\t\t\t\t\t...userMap\n\t\t\t\t},\n\t\t\t\tdata: enrichedProfile\n\t\t\t};\n\t\t},\n\t\toptions\n\t};\n};\nconst getApplePublicKey = async (kid) => {\n\tconst { data } = await betterFetch(`https://appleid.apple.com/auth/keys`);\n\tif (!data?.keys) throw new APIError(\"BAD_REQUEST\", { message: \"Keys not found\" });\n\tconst jwk = data.keys.find((key) => key.kid === kid);\n\tif (!jwk) throw new Error(`JWK with kid ${kid} not found`);\n\treturn await importJWK(jwk, jwk.alg);\n};\n//#endregion\nexport { apple, getApplePublicKey };\n", "import { base64Url } from \"@better-auth/utils/base64\";\n//#region src/oauth2/utils.ts\nfunction getOAuth2Tokens(data) {\n\tconst getDate = (seconds) => {\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\treturn new Date(now.getTime() + seconds * 1e3);\n\t};\n\treturn {\n\t\ttokenType: data.token_type,\n\t\taccessToken: data.access_token,\n\t\trefreshToken: data.refresh_token,\n\t\taccessTokenExpiresAt: data.expires_in ? getDate(data.expires_in) : void 0,\n\t\trefreshTokenExpiresAt: data.refresh_token_expires_in ? getDate(data.refresh_token_expires_in) : void 0,\n\t\tscopes: data?.scope ? typeof data.scope === \"string\" ? data.scope.split(\" \") : data.scope : [],\n\t\tidToken: data.id_token,\n\t\traw: data\n\t};\n}\nasync function generateCodeChallenge(codeVerifier) {\n\tconst data = new TextEncoder().encode(codeVerifier);\n\tconst hash = await crypto.subtle.digest(\"SHA-256\", data);\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n}\n//#endregion\nexport { generateCodeChallenge, getOAuth2Tokens };\n", "import { generateCodeChallenge } from \"./utils.mjs\";\n//#region src/oauth2/create-authorization-url.ts\nasync function createAuthorizationURL({ id, options, authorizationEndpoint, state, codeVerifier, scopes, claims, redirectURI, duration, prompt, accessType, responseType, display, loginHint, hd, responseMode, additionalParams, scopeJoiner }) {\n\toptions = typeof options === \"function\" ? await options() : options;\n\tconst url = new URL(options.authorizationEndpoint || authorizationEndpoint);\n\turl.searchParams.set(\"response_type\", responseType || \"code\");\n\tconst primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;\n\turl.searchParams.set(\"client_id\", primaryClientId);\n\turl.searchParams.set(\"state\", state);\n\tif (scopes) url.searchParams.set(\"scope\", scopes.join(scopeJoiner || \" \"));\n\turl.searchParams.set(\"redirect_uri\", options.redirectURI || redirectURI);\n\tduration && url.searchParams.set(\"duration\", duration);\n\tdisplay && url.searchParams.set(\"display\", display);\n\tloginHint && url.searchParams.set(\"login_hint\", loginHint);\n\tprompt && url.searchParams.set(\"prompt\", prompt);\n\thd && url.searchParams.set(\"hd\", hd);\n\taccessType && url.searchParams.set(\"access_type\", accessType);\n\tresponseMode && url.searchParams.set(\"response_mode\", responseMode);\n\tif (codeVerifier) {\n\t\tconst codeChallenge = await generateCodeChallenge(codeVerifier);\n\t\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\t\turl.searchParams.set(\"code_challenge\", codeChallenge);\n\t}\n\tif (claims) {\n\t\tconst claimsObj = claims.reduce((acc, claim) => {\n\t\t\tacc[claim] = null;\n\t\t\treturn acc;\n\t\t}, {});\n\t\turl.searchParams.set(\"claims\", JSON.stringify({ id_token: {\n\t\t\temail: null,\n\t\t\temail_verified: null,\n\t\t\t...claimsObj\n\t\t} }));\n\t}\n\tif (additionalParams) Object.entries(additionalParams).forEach(([key, value]) => {\n\t\turl.searchParams.set(key, value);\n\t});\n\treturn url;\n}\n//#endregion\nexport { createAuthorizationURL };\n", "export class BetterFetchError extends Error {\n\tconstructor(\n\t\tpublic status: number,\n\t\tpublic statusText: string,\n\t\tpublic error: any,\n\t) {\n\t\tsuper(statusText || status.toString(), {\n\t\t\tcause: error,\n\t\t});\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n", "import type { StandardSchemaV1 } from \"./standard-schema\";\nimport type { Schema } from \"./create-fetch\";\nimport type { BetterFetchError } from \"./error\";\nimport type { BetterFetchOption } from \"./types\";\n\nexport type RequestContext = any> = {\n\turl: URL | string;\n\theaders: Headers;\n\tbody: any;\n\tmethod: string;\n\tsignal: AbortSignal;\n} & BetterFetchOption;\nexport type ResponseContext = {\n\tresponse: Response;\n\trequest: RequestContext;\n};\nexport type SuccessContext = {\n\tdata: Res;\n\tresponse: Response;\n\trequest: RequestContext;\n};\nexport type ErrorContext = {\n\tresponse: Response;\n\trequest: RequestContext;\n\terror: BetterFetchError & Record;\n};\nexport interface FetchHooks {\n\t/**\n\t * a callback function that will be called when a\n\t * request is made.\n\t *\n\t * The returned context object will be reassigned to\n\t * the original request context.\n\t */\n\tonRequest?: >(\n\t\tcontext: RequestContext,\n\t) => Promise | RequestContext | void;\n\t/**\n\t * a callback function that will be called when\n\t * response is received. This will be called before\n\t * the response is parsed and returned.\n\t *\n\t * The returned response will be reassigned to the\n\t * original response if it's changed.\n\t */\n\tonResponse?: (\n\t\tcontext: ResponseContext,\n\t) =>\n\t\t| Promise\n\t\t| Response\n\t\t| ResponseContext\n\t\t| void;\n\t/**\n\t * a callback function that will be called when a\n\t * response is successful.\n\t */\n\tonSuccess?: (context: SuccessContext) => Promise | void;\n\t/**\n\t * a callback function that will be called when an\n\t * error occurs.\n\t */\n\tonError?: (context: ErrorContext) => Promise | void;\n\t/**\n\t * a callback function that will be called when a\n\t * request is retried.\n\t */\n\tonRetry?: (response: ResponseContext) => Promise | void;\n\t/**\n\t * Options for the hooks\n\t */\n\thookOptions?: {\n\t\t/**\n\t\t * Clone the response\n\t\t * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone\n\t\t */\n\t\tcloneResponse?: boolean;\n\t};\n}\n\n/**\n * A plugin that returns an id and hooks\n */\nexport type BetterFetchPlugin<\n\tExtraOptions extends Record = Record,\n> = {\n\t/**\n\t * A unique id for the plugin\n\t */\n\tid: string;\n\t/**\n\t * A name for the plugin\n\t */\n\tname: string;\n\t/**\n\t * A description for the plugin\n\t */\n\tdescription?: string;\n\t/**\n\t * A version for the plugin\n\t */\n\tversion?: string;\n\t/**\n\t * Hooks for the plugin\n\t */\n\thooks?: FetchHooks;\n\t/**\n\t * A function that will be called when the plugin is\n\t * initialized. This will be called before the any\n\t * of the other internal functions.\n\t *\n\t * The returned options will be merged with the\n\t * original options.\n\t */\n\tinit?: (\n\t\turl: string,\n\t\toptions?: BetterFetchOption & ExtraOptions,\n\t) =>\n\t\t| Promise<{\n\t\t\t\turl: string;\n\t\t\t\toptions?: BetterFetchOption;\n\t\t }>\n\t\t| {\n\t\t\t\turl: string;\n\t\t\t\toptions?: BetterFetchOption;\n\t\t };\n\t/**\n\t * A schema for the plugin\n\t */\n\tschema?: Schema;\n\t/**\n\t * Additional options that can be passed to the plugin\n\t *\n\t * @deprecated Use type inference through direct typescript instead\n\t * ```ts\n\t * const plugin = {\n\t *\n\t * } satisfies BetterFetchPlugin<{\n\t * myCustomOptions: string;\n\t * }>\n\t * ```\n\t */\n\tgetOptions?: () => StandardSchemaV1;\n};\n\nexport const initializePlugins = async (\n\turl: string,\n\toptions?: BetterFetchOption,\n) => {\n\tlet opts = options || {};\n\tconst hooks: {\n\t\tonRequest: Array;\n\t\tonResponse: Array;\n\t\tonSuccess: Array;\n\t\tonError: Array;\n\t\tonRetry: Array;\n\t} = {\n\t\tonRequest: [options?.onRequest],\n\t\tonResponse: [options?.onResponse],\n\t\tonSuccess: [options?.onSuccess],\n\t\tonError: [options?.onError],\n\t\tonRetry: [options?.onRetry],\n\t};\n\tif (!options || !options?.plugins) {\n\t\treturn {\n\t\t\turl,\n\t\t\toptions: opts,\n\t\t\thooks,\n\t\t};\n\t}\n\tfor (const plugin of options?.plugins || []) {\n\t\tif (plugin.init) {\n\t\t\tconst pluginRes = await plugin.init?.(url.toString(), options);\n\t\t\topts = pluginRes.options || opts;\n\t\t\turl = pluginRes.url;\n\t\t}\n\t\thooks.onRequest.push(plugin.hooks?.onRequest);\n\t\thooks.onResponse.push(plugin.hooks?.onResponse);\n\t\thooks.onSuccess.push(plugin.hooks?.onSuccess);\n\t\thooks.onError.push(plugin.hooks?.onError);\n\t\thooks.onRetry.push(plugin.hooks?.onRetry);\n\t}\n\n\treturn {\n\t\turl,\n\t\toptions: opts,\n\t\thooks,\n\t};\n};\n", "export type RetryCondition = (\n\tresponse: Response | null,\n) => boolean | Promise;\n\nexport type LinearRetry = {\n\ttype: \"linear\";\n\tattempts: number;\n\tdelay: number;\n\tshouldRetry?: RetryCondition;\n};\n\nexport type ExponentialRetry = {\n\ttype: \"exponential\";\n\tattempts: number;\n\tbaseDelay: number;\n\tmaxDelay: number;\n\tshouldRetry?: RetryCondition;\n};\n\nexport type RetryOptions = LinearRetry | ExponentialRetry | number;\n\nexport interface RetryStrategy {\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise;\n\tgetDelay(attempt: number): number;\n}\n\nclass LinearRetryStrategy implements RetryStrategy {\n\tconstructor(private options: LinearRetry) {}\n\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise {\n\t\tif (this.options.shouldRetry) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tattempt < this.options.attempts && this.options.shouldRetry(response),\n\t\t\t);\n\t\t}\n\t\treturn Promise.resolve(attempt < this.options.attempts);\n\t}\n\n\tgetDelay(): number {\n\t\treturn this.options.delay;\n\t}\n}\n\nclass ExponentialRetryStrategy implements RetryStrategy {\n\tconstructor(private options: ExponentialRetry) {}\n\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise {\n\t\tif (this.options.shouldRetry) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tattempt < this.options.attempts && this.options.shouldRetry(response),\n\t\t\t);\n\t\t}\n\t\treturn Promise.resolve(attempt < this.options.attempts);\n\t}\n\n\tgetDelay(attempt: number): number {\n\t\tconst delay = Math.min(\n\t\t\tthis.options.maxDelay,\n\t\t\tthis.options.baseDelay * 2 ** attempt,\n\t\t);\n\t\treturn delay;\n\t}\n}\n\nexport function createRetryStrategy(options: RetryOptions): RetryStrategy {\n\tif (typeof options === \"number\") {\n\t\treturn new LinearRetryStrategy({\n\t\t\ttype: \"linear\",\n\t\t\tattempts: options,\n\t\t\tdelay: 1000,\n\t\t});\n\t}\n\n\tswitch (options.type) {\n\t\tcase \"linear\":\n\t\t\treturn new LinearRetryStrategy(options);\n\t\tcase \"exponential\":\n\t\t\treturn new ExponentialRetryStrategy(options);\n\t\tdefault:\n\t\t\tthrow new Error(\"Invalid retry strategy\");\n\t}\n}\n", "import type { BetterFetchOption } from \"./types\";\n\nexport type typeOrTypeReturning = T | (() => T);\n/**\n * Bearer token authentication\n *\n * the value of `token` will be added to a header as\n * `auth: Bearer token`,\n */\nexport type Bearer = {\n\ttype: \"Bearer\";\n\ttoken: typeOrTypeReturning>;\n};\n\n/**\n * Basic auth\n */\nexport type Basic = {\n\ttype: \"Basic\";\n\tusername: typeOrTypeReturning;\n\tpassword: typeOrTypeReturning;\n};\n\n/**\n * Custom auth\n *\n * @param prefix - prefix of the header\n * @param value - value of the header\n *\n * @example\n * ```ts\n * {\n * type: \"Custom\",\n * prefix: \"Token\",\n * value: \"token\"\n * }\n * ```\n */\nexport type Custom = {\n\ttype: \"Custom\";\n\tprefix: typeOrTypeReturning;\n\tvalue: typeOrTypeReturning;\n};\n\nexport type Auth = Bearer | Basic | Custom;\n\nexport const getAuthHeader = async (options?: BetterFetchOption) => {\n\tconst headers: Record = {};\n\tconst getValue = async (\n\t\tvalue: typeOrTypeReturning<\n\t\t\tstring | undefined | Promise\n\t\t>,\n\t) => (typeof value === \"function\" ? await value() : value);\n\tif (options?.auth) {\n\t\tif (options.auth.type === \"Bearer\") {\n\t\t\tconst token = await getValue(options.auth.token);\n\t\t\tif (!token) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `Bearer ${token}`;\n\t\t} else if (options.auth.type === \"Basic\") {\n\t\t\tconst [username, password] = await Promise.all([\n\t\t\t\tgetValue(options.auth.username),\n\t\t\t\tgetValue(options.auth.password),\n\t\t\t]);\n\t\t\tif (!username || !password) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `Basic ${btoa(`${username}:${password}`)}`;\n\t\t} else if (options.auth.type === \"Custom\") {\n\t\t\tconst [prefix, value] = await Promise.all([\n\t\t\t\tgetValue(options.auth.prefix),\n\t\t\t\tgetValue(options.auth.value),\n\t\t\t]);\n\t\t\tif (!value) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `${prefix ?? \"\"} ${value}`;\n\t\t}\n\t}\n\treturn headers;\n};\n", "import type { StandardSchemaV1 } from \"./standard-schema\";\nimport { getAuthHeader } from \"./auth\";\nimport { methods } from \"./create-fetch\";\nimport type { BetterFetchOption, FetchEsque } from \"./types\";\n\nconst JSON_RE = /^application\\/(?:[\\w!#$%&*.^`~-]*\\+)?json(;.+)?$/i;\n\nexport type ResponseType = \"json\" | \"text\" | \"blob\";\nexport function detectResponseType(request: Response): ResponseType {\n\tconst _contentType = request.headers.get(\"content-type\");\n\tconst textTypes = new Set([\n\t\t\"image/svg\",\n\t\t\"application/xml\",\n\t\t\"application/xhtml\",\n\t\t\"application/html\",\n\t]);\n\tif (!_contentType) {\n\t\treturn \"json\";\n\t}\n\tconst contentType = _contentType.split(\";\").shift() || \"\";\n\tif (JSON_RE.test(contentType)) {\n\t\treturn \"json\";\n\t}\n\tif (textTypes.has(contentType) || contentType.startsWith(\"text/\")) {\n\t\treturn \"text\";\n\t}\n\treturn \"blob\";\n}\n\nexport function isJSONParsable(value: any) {\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn false;\n\t}\n}\n\n//https://github.com/unjs/ofetch/blob/main/src/utils.ts\nexport function isJSONSerializable(value: any) {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst t = typeof value;\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n\t\treturn true;\n\t}\n\tif (t !== \"object\") {\n\t\treturn false;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn true;\n\t}\n\tif (value.buffer) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t(value.constructor && value.constructor.name === \"Object\") ||\n\t\ttypeof value.toJSON === \"function\"\n\t);\n}\n\nexport function jsonParse(text: string) {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch (error) {\n\t\treturn text;\n\t}\n}\n\nexport function isFunction(value: any): value is () => any {\n\treturn typeof value === \"function\";\n}\n\nexport function getFetch(options?: BetterFetchOption): FetchEsque {\n\tif (options?.customFetchImpl) {\n\t\treturn options.customFetchImpl;\n\t}\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) {\n\t\treturn globalThis.fetch;\n\t}\n\tif (typeof window !== \"undefined\" && isFunction(window.fetch)) {\n\t\treturn window.fetch;\n\t}\n\tthrow new Error(\"No fetch implementation found\");\n}\n\nexport function isPayloadMethod(method?: string) {\n\tif (!method) {\n\t\treturn false;\n\t}\n\tconst payloadMethod = [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\treturn payloadMethod.includes(method.toUpperCase());\n}\n\nexport function isRouteMethod(method?: string) {\n\tconst routeMethod = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\tif (!method) {\n\t\treturn false;\n\t}\n\treturn routeMethod.includes(method.toUpperCase());\n}\n\nexport async function getHeaders(opts?: BetterFetchOption) {\n\tconst headers = new Headers(opts?.headers);\n\tconst authHeader = await getAuthHeader(opts);\n\tfor (const [key, value] of Object.entries(authHeader || {})) {\n\t\theaders.set(key, value);\n\t}\n\tif (!headers.has(\"content-type\")) {\n\t\tconst t = detectContentType(opts?.body);\n\t\tif (t) {\n\t\t\theaders.set(\"content-type\", t);\n\t\t}\n\t}\n\n\treturn headers;\n}\n\nexport function getURL(url: string, options?: BetterFetchOption) {\n\tif (url.startsWith(\"@\")) {\n\t\tconst m = url.toString().split(\"@\")[1].split(\"/\")[0];\n\t\tif (methods.includes(m)) {\n\t\t\turl = url.replace(`@${m}/`, \"/\");\n\t\t}\n\t}\n\tlet _url: string | URL;\n\ttry {\n\t\tif (url.startsWith(\"http\")) {\n\t\t\t_url = url;\n\t\t} else {\n\t\t\tlet baseURL = options?.baseURL;\n\t\t\tif (baseURL && !baseURL?.endsWith(\"/\")) {\n\t\t\t\tbaseURL = baseURL + \"/\";\n\t\t\t}\n\t\t\tif (url.startsWith(\"/\")) {\n\t\t\t\t_url = new URL(url.substring(1), baseURL);\n\t\t\t} else {\n\t\t\t\t_url = new URL(url, options?.baseURL);\n\t\t\t}\n\t\t}\n\t} catch (e) {\n\t\tif (e instanceof TypeError) {\n\t\t\tif (!options?.baseURL) {\n\t\t\t\tthrow TypeError(\n\t\t\t\t\t`Invalid URL ${url}. Are you passing in a relative url but not setting the baseURL?`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow TypeError(\n\t\t\t\t`Invalid URL ${url}. Please validate that you are passing the correct input.`,\n\t\t\t);\n\t\t}\n\t\tthrow e;\n\t}\n\n\t/**\n\t * Dynamic Parameters.\n\t */\n\tif (options?.params) {\n\t\tif (Array.isArray(options?.params)) {\n\t\t\tconst params = options?.params\n\t\t\t\t? Array.isArray(options.params)\n\t\t\t\t\t? `/${options.params.join(\"/\")}`\n\t\t\t\t\t: `/${Object.values(options.params).join(\"/\")}`\n\t\t\t\t: \"\";\n\t\t\t_url = _url.toString().split(\"/:\")[0];\n\t\t\t_url = `${_url.toString()}${params}`;\n\t\t} else {\n\t\t\tfor (const [key, value] of Object.entries(options?.params)) {\n\t\t\t\t_url = _url.toString().replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t}\n\tconst __url = new URL(_url);\n\t/**\n\t * Query Parameters\n\t */\n\tconst queryParams = options?.query;\n\tif (queryParams) {\n\t\tfor (const [key, value] of Object.entries(queryParams)) {\n\t\t\t__url.searchParams.append(key, String(value));\n\t\t}\n\t}\n\treturn __url;\n}\n\nexport function detectContentType(body: any) {\n\tif (isJSONSerializable(body)) {\n\t\treturn \"application/json\";\n\t}\n\n\treturn null;\n}\n\nexport function getBody(options?: BetterFetchOption) {\n\tif (!options?.body) {\n\t\treturn null;\n\t}\n\tconst headers = new Headers(options?.headers);\n\tif (isJSONSerializable(options.body) && !headers.has(\"content-type\")) {\n\t\tfor (const [key, value] of Object.entries(options?.body)) {\n\t\t\tif (value instanceof Date) {\n\t\t\t\toptions.body[key] = value.toISOString();\n\t\t\t}\n\t\t}\n\t\treturn JSON.stringify(options.body);\n\t}\n\n\tif (\n\t\theaders.has(\"content-type\") &&\n\t\theaders.get(\"content-type\") === \"application/x-www-form-urlencoded\"\n\t) {\n\t\tif (isJSONSerializable(options.body)) {\n\t\t\treturn new URLSearchParams(options.body).toString();\n\t\t}\n\t\treturn options.body;\n\t}\n\n\treturn options.body;\n}\n\nexport function getMethod(url: string, options?: BetterFetchOption) {\n\tif (options?.method) {\n\t\treturn options.method.toUpperCase();\n\t}\n\tif (url.startsWith(\"@\")) {\n\t\tconst pMethod = url.split(\"@\")[1]?.split(\"/\")[0];\n\t\tif (!methods.includes(pMethod)) {\n\t\t\treturn options?.body ? \"POST\" : \"GET\";\n\t\t}\n\t\treturn pMethod.toUpperCase();\n\t}\n\treturn options?.body ? \"POST\" : \"GET\";\n}\n\nexport function getTimeout(\n\toptions?: BetterFetchOption,\n\tcontroller?: AbortController,\n) {\n\tlet abortTimeout: ReturnType | undefined;\n\tif (!options?.signal && options?.timeout) {\n\t\tabortTimeout = setTimeout(() => controller?.abort(), options?.timeout);\n\t}\n\treturn {\n\t\tabortTimeout,\n\t\tclearTimeout: () => {\n\t\t\tif (abortTimeout) {\n\t\t\t\tclearTimeout(abortTimeout);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function bodyParser(data: any, responseType: ResponseType) {\n\tif (responseType === \"json\") {\n\t\treturn JSON.parse(data);\n\t}\n\treturn data;\n}\n\nexport class ValidationError extends Error {\n\tpublic readonly issues: ReadonlyArray;\n\n\tconstructor(issues: ReadonlyArray, message?: string) {\n\t\t// Default message fallback in case one isn't supplied.\n\t\tsuper(message || JSON.stringify(issues, null, 2));\n\t\tthis.issues = issues;\n\n\t\t// Set the prototype explicitly to ensure that instanceof works correctly.\n\t\tObject.setPrototypeOf(this, ValidationError.prototype);\n\t}\n}\n\nexport async function parseStandardSchema(\n\tschema: TSchema,\n\tinput: StandardSchemaV1.InferInput,\n): Promise> {\n\tconst result = await schema[\"~standard\"].validate(input);\n\n\tif (result.issues) {\n\t\tthrow new ValidationError(result.issues);\n\t}\n\treturn result.value;\n}\n", "import type { StandardSchemaV1 } from \"../standard-schema\";\nimport type { StringLiteralUnion } from \"../type-utils\";\n\nexport type FetchSchema = {\n\tinput?: StandardSchemaV1;\n\toutput?: StandardSchemaV1;\n\tquery?: StandardSchemaV1;\n\tparams?: StandardSchemaV1> | undefined;\n\tmethod?: Methods;\n};\n\nexport type Methods = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\n\nexport const methods = [\"get\", \"post\", \"put\", \"patch\", \"delete\"];\n\ntype RouteKey = StringLiteralUnion<`@${Methods}/`>;\n\nexport type FetchSchemaRoutes = {\n\t[key in RouteKey]?: FetchSchema;\n};\n\nexport const createSchema = <\n\tF extends FetchSchemaRoutes,\n\tS extends SchemaConfig,\n>(\n\tschema: F,\n\tconfig?: S,\n) => {\n\treturn {\n\t\tschema: schema as F,\n\t\tconfig: config as S,\n\t};\n};\n\nexport type SchemaConfig = {\n\tstrict?: boolean;\n\t/**\n\t * A prefix that will be prepended when it's\n\t * calling the schema.\n\t *\n\t * NOTE: Make sure to handle converting\n\t * the prefix to the baseURL in the init\n\t * function if you you are defining for a\n\t * plugin.\n\t */\n\tprefix?: \"\" | (string & Record);\n\t/**\n\t * The base url of the schema. By default it's the baseURL of the fetch instance.\n\t */\n\tbaseURL?: \"\" | (string & Record);\n};\n\nexport type Schema = {\n\tschema: FetchSchemaRoutes;\n\tconfig: SchemaConfig;\n};\n", "import { betterFetch } from \"../fetch\";\nimport { BetterFetchPlugin } from \"../plugins\";\nimport type { BetterFetchOption } from \"../types\";\nimport { parseStandardSchema } from \"../utils\";\nimport type { BetterFetch, CreateFetchOption } from \"./types\";\n\nexport const applySchemaPlugin = (config: CreateFetchOption) =>\n\t({\n\t\tid: \"apply-schema\",\n\t\tname: \"Apply Schema\",\n\t\tversion: \"1.0.0\",\n\t\tasync init(url, options) {\n\t\t\tconst schema =\n\t\t\t\tconfig.plugins?.find((plugin) =>\n\t\t\t\t\tplugin.schema?.config\n\t\t\t\t\t\t? url.startsWith(plugin.schema.config.baseURL || \"\") ||\n\t\t\t\t\t\t\turl.startsWith(plugin.schema.config.prefix || \"\")\n\t\t\t\t\t\t: false,\n\t\t\t\t)?.schema || config.schema;\n\t\t\tif (schema) {\n\t\t\t\tlet urlKey = url;\n\t\t\t\tif (schema.config?.prefix) {\n\t\t\t\t\tif (urlKey.startsWith(schema.config.prefix)) {\n\t\t\t\t\t\turlKey = urlKey.replace(schema.config.prefix, \"\");\n\t\t\t\t\t\tif (schema.config.baseURL) {\n\t\t\t\t\t\t\turl = url.replace(schema.config.prefix, schema.config.baseURL);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (schema.config?.baseURL) {\n\t\t\t\t\tif (urlKey.startsWith(schema.config.baseURL)) {\n\t\t\t\t\t\turlKey = urlKey.replace(schema.config.baseURL, \"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst keySchema = schema.schema[urlKey];\n\t\t\t\tif (keySchema) {\n\t\t\t\t\tlet opts = {\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\tmethod: keySchema.method,\n\t\t\t\t\t\toutput: keySchema.output,\n\t\t\t\t\t};\n\t\t\t\t\tif (!options?.disableValidation) {\n\t\t\t\t\t\topts = {\n\t\t\t\t\t\t\t...opts,\n\t\t\t\t\t\t\tbody: keySchema.input\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.input, options?.body)\n\t\t\t\t\t\t\t\t: options?.body,\n\t\t\t\t\t\t\tparams: keySchema.params\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.params, options?.params)\n\t\t\t\t\t\t\t\t: options?.params,\n\t\t\t\t\t\t\tquery: keySchema.query\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.query, options?.query)\n\t\t\t\t\t\t\t\t: options?.query,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\toptions: opts,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\turl,\n\t\t\t\toptions,\n\t\t\t};\n\t\t},\n\t}) satisfies BetterFetchPlugin;\n\nexport const createFetch = here.` : description}\n

\n \n\n \n \n \n Go Home\n \n \n \n \n Ask AI\n \n \n \n \n \n \n`;\n};\nconst error = createAuthEndpoint(\"/error\", {\n\tmethod: \"GET\",\n\tmetadata: {\n\t\t...HIDE_METADATA,\n\t\topenapi: {\n\t\t\tdescription: \"Displays an error page\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"text/html\": { schema: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The HTML content of the error page\"\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (c) => {\n\tconst url = new URL(c.request?.url || \"\");\n\tconst unsanitizedCode = url.searchParams.get(\"error\") || \"UNKNOWN\";\n\tconst unsanitizedDescription = url.searchParams.get(\"error_description\") || null;\n\tconst safeCode = /^[\\'A-Za-z0-9_-]+$/.test(unsanitizedCode || \"\") ? unsanitizedCode : \"UNKNOWN\";\n\tconst safeDescription = unsanitizedDescription ? sanitize(unsanitizedDescription) : null;\n\tconst queryParams = new URLSearchParams();\n\tqueryParams.set(\"error\", safeCode);\n\tif (unsanitizedDescription) queryParams.set(\"error_description\", unsanitizedDescription);\n\tconst options = c.context.options;\n\tconst errorURL = options.onAPIError?.errorURL;\n\tif (errorURL) return new Response(null, {\n\t\tstatus: 302,\n\t\theaders: { Location: `${errorURL}${errorURL.includes(\"?\") ? \"&\" : \"?\"}${queryParams.toString()}` }\n\t});\n\tif (isProduction && !options.onAPIError?.customizeDefaultErrorPage) return new Response(null, {\n\t\tstatus: 302,\n\t\theaders: { Location: `/?${queryParams.toString()}` }\n\t});\n\treturn new Response(html(c.context.options, safeCode, safeDescription), { headers: { \"Content-Type\": \"text/html\" } });\n});\n//#endregion\nexport { error };\n", "import { HIDE_METADATA } from \"../../utils/hide-metadata.mjs\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\n//#region src/api/routes/ok.ts\nconst ok = createAuthEndpoint(\"/ok\", {\n\tmethod: \"GET\",\n\tmetadata: {\n\t\t...HIDE_METADATA,\n\t\topenapi: {\n\t\t\tdescription: \"Check if the API is working\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"API is working\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { ok: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the API is working\"\n\t\t\t\t\t} },\n\t\t\t\t\trequired: [\"ok\"]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\treturn ctx.json({ ok: true });\n});\n//#endregion\nexport { ok };\n", "import { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\n//#region src/utils/password.ts\nasync function validatePassword(ctx, data) {\n\tconst credentialAccount = (await ctx.context.internalAdapter.findAccounts(data.userId))?.find((account) => account.providerId === \"credential\");\n\tconst currentPassword = credentialAccount?.password;\n\tif (!credentialAccount || !currentPassword) return false;\n\treturn await ctx.context.password.verify({\n\t\thash: currentPassword,\n\t\tpassword: data.password\n\t});\n}\nasync function checkPassword(userId, c) {\n\tconst credentialAccount = (await c.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === \"credential\");\n\tconst currentPassword = credentialAccount?.password;\n\tconst password = c.body.password;\n\tif (!credentialAccount || !currentPassword || !password) {\n\t\tif (password) await c.context.password.hash(password);\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t}\n\tif (!await c.context.password.verify({\n\t\thash: currentPassword,\n\t\tpassword\n\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\treturn true;\n}\nasync function shouldRequirePassword(ctx, userId, allowPasswordless) {\n\tif (!allowPasswordless) return true;\n\tconst credentialAccount = (await ctx.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === \"credential\" && account.password);\n\treturn Boolean(credentialAccount);\n}\n//#endregion\nexport { checkPassword, shouldRequirePassword, validatePassword };\n", "import { originCheck } from \"../middlewares/origin-check.mjs\";\nimport { getDate } from \"../../utils/date.mjs\";\nimport { sensitiveSessionMiddleware } from \"./session.mjs\";\nimport { validatePassword } from \"../../utils/password.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { generateId } from \"@better-auth/core/utils/id\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/password.ts\nfunction redirectError(ctx, callbackURL, query) {\n\tconst url = callbackURL ? new URL(callbackURL, ctx.baseURL) : new URL(`${ctx.baseURL}/error`);\n\tif (query) Object.entries(query).forEach(([k, v]) => url.searchParams.set(k, v));\n\treturn url.href;\n}\nfunction redirectCallback(ctx, callbackURL, query) {\n\tconst url = new URL(callbackURL, ctx.baseURL);\n\tif (query) Object.entries(query).forEach(([k, v]) => url.searchParams.set(k, v));\n\treturn url.href;\n}\nconst requestPasswordReset = createAuthEndpoint(\"/request-password-reset\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\temail: z.email().meta({ description: \"The email address of the user to send a password reset email to\" }),\n\t\tredirectTo: z.string().meta({ description: \"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\toperationId: \"requestPasswordReset\",\n\t\tdescription: \"Send a password reset email to the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tstatus: { type: \"boolean\" },\n\t\t\t\t\tmessage: { type: \"string\" }\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} },\n\tuse: [originCheck((ctx) => ctx.body.redirectTo)]\n}, async (ctx) => {\n\tif (!ctx.context.options.emailAndPassword?.sendResetPassword) {\n\t\tctx.context.logger.error(\"Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Reset password isn't enabled\",\n\t\t\tcode: \"RESET_PASSWORD_DISABLED\"\n\t\t});\n\t}\n\tconst { email, redirectTo } = ctx.body;\n\tconst user = await ctx.context.internalAdapter.findUserByEmail(email, { includeAccounts: true });\n\tif (!user) {\n\t\t/**\n\t\t* We simulate the verification token generation and the database lookup\n\t\t* to mitigate timing attacks.\n\t\t*/\n\t\tgenerateId(24);\n\t\tawait ctx.context.internalAdapter.findVerificationValue(\"dummy-verification-token\");\n\t\tctx.context.logger.error(\"Reset Password: User not found\", { email });\n\t\treturn ctx.json({\n\t\t\tstatus: true,\n\t\t\tmessage: \"If this email exists in our system, check your email for the reset link\"\n\t\t});\n\t}\n\tconst expiresAt = getDate(ctx.context.options.emailAndPassword.resetPasswordTokenExpiresIn || 3600 * 1, \"sec\");\n\tconst verificationToken = generateId(24);\n\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\tvalue: user.user.id,\n\t\tidentifier: `reset-password:${verificationToken}`,\n\t\texpiresAt\n\t});\n\tconst callbackURL = redirectTo ? encodeURIComponent(redirectTo) : \"\";\n\tconst url = `${ctx.context.baseURL}/reset-password/${verificationToken}?callbackURL=${callbackURL}`;\n\tawait ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.sendResetPassword({\n\t\tuser: user.user,\n\t\turl,\n\t\ttoken: verificationToken\n\t}, ctx.request));\n\treturn ctx.json({\n\t\tstatus: true,\n\t\tmessage: \"If this email exists in our system, check your email for the reset link\"\n\t});\n});\nconst requestPasswordResetCallback = createAuthEndpoint(\"/reset-password/:token\", {\n\tmethod: \"GET\",\n\toperationId: \"forgetPasswordCallback\",\n\tquery: z.object({ callbackURL: z.string().meta({ description: \"The URL to redirect the user to reset their password\" }) }),\n\tuse: [originCheck((ctx) => ctx.query.callbackURL)],\n\tmetadata: { openapi: {\n\t\toperationId: \"resetPasswordCallback\",\n\t\tdescription: \"Redirects the user to the callback URL with the token\",\n\t\tparameters: [{\n\t\t\tname: \"token\",\n\t\t\tin: \"path\",\n\t\t\trequired: true,\n\t\t\tdescription: \"The token to reset the password\",\n\t\t\tschema: { type: \"string\" }\n\t\t}, {\n\t\t\tname: \"callbackURL\",\n\t\t\tin: \"query\",\n\t\t\trequired: true,\n\t\t\tdescription: \"The URL to redirect the user to reset their password\",\n\t\t\tschema: { type: \"string\" }\n\t\t}],\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { token: { type: \"string\" } }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst { token } = ctx.params;\n\tconst { callbackURL } = ctx.query;\n\tif (!token || !callbackURL) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: \"INVALID_TOKEN\" }));\n\tconst verification = await ctx.context.internalAdapter.findVerificationValue(`reset-password:${token}`);\n\tif (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: \"INVALID_TOKEN\" }));\n\tthrow ctx.redirect(redirectCallback(ctx.context, callbackURL, { token }));\n});\nconst resetPassword = createAuthEndpoint(\"/reset-password\", {\n\tmethod: \"POST\",\n\toperationId: \"resetPassword\",\n\tquery: z.object({ token: z.string().optional() }).optional(),\n\tbody: z.object({\n\t\tnewPassword: z.string().meta({ description: \"The new password to set\" }),\n\t\ttoken: z.string().meta({ description: \"The token to reset the password\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\toperationId: \"resetPassword\",\n\t\tdescription: \"Reset the password for a user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst token = ctx.body.token || ctx.query?.token;\n\tif (!token) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_TOKEN);\n\tconst { newPassword } = ctx.body;\n\tconst minLength = ctx.context.password?.config.minPasswordLength;\n\tconst maxLength = ctx.context.password?.config.maxPasswordLength;\n\tif (newPassword.length < minLength) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_SHORT);\n\tif (newPassword.length > maxLength) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_LONG);\n\tconst id = `reset-password:${token}`;\n\tconst verification = await ctx.context.internalAdapter.findVerificationValue(id);\n\tif (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_TOKEN);\n\tconst userId = verification.value;\n\tconst hashedPassword = await ctx.context.password.hash(newPassword);\n\tif (!(await ctx.context.internalAdapter.findAccounts(userId)).find((ac) => ac.providerId === \"credential\")) await ctx.context.internalAdapter.createAccount({\n\t\tuserId,\n\t\tproviderId: \"credential\",\n\t\tpassword: hashedPassword,\n\t\taccountId: userId\n\t});\n\telse await ctx.context.internalAdapter.updatePassword(userId, hashedPassword);\n\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(id);\n\tif (ctx.context.options.emailAndPassword?.onPasswordReset) {\n\t\tconst user = await ctx.context.internalAdapter.findUserById(userId);\n\t\tif (user) await ctx.context.options.emailAndPassword.onPasswordReset({ user }, ctx.request);\n\t}\n\tif (ctx.context.options.emailAndPassword?.revokeSessionsOnPasswordReset) await ctx.context.internalAdapter.deleteSessions(userId);\n\treturn ctx.json({ status: true });\n});\nconst verifyPassword = createAuthEndpoint(\"/verify-password\", {\n\tmethod: \"POST\",\n\tbody: z.object({ password: z.string().meta({ description: \"The password to verify\" }) }),\n\tmetadata: {\n\t\tscope: \"server\",\n\t\topenapi: {\n\t\t\toperationId: \"verifyPassword\",\n\t\t\tdescription: \"Verify the current user's password\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t},\n\tuse: [sensitiveSessionMiddleware]\n}, async (ctx) => {\n\tconst { password } = ctx.body;\n\tconst session = ctx.context.session;\n\tif (!await validatePassword(ctx, {\n\t\tpassword,\n\t\tuserId: session.user.id\n\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\treturn ctx.json({ status: true });\n});\n//#endregion\nexport { requestPasswordReset, requestPasswordResetCallback, resetPassword, verifyPassword };\n", "import { formCsrfMiddleware } from \"../middlewares/origin-check.mjs\";\nimport { parseUserOutput } from \"../../db/schema.mjs\";\nimport { getAwaitableValue } from \"../../context/helpers.mjs\";\nimport { setSessionCookie } from \"../../cookies/index.mjs\";\nimport { generateState } from \"../../oauth2/state.mjs\";\nimport { handleOAuthUserInfo } from \"../../oauth2/link-account.mjs\";\nimport { createEmailVerificationToken } from \"./email-verification.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { SocialProviderListEnum } from \"@better-auth/core/social-providers\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/sign-in.ts\nconst socialSignInBodySchema = z.object({\n\tcallbackURL: z.string().meta({ description: \"Callback URL to redirect to after the user has signed in\" }).optional(),\n\tnewUserCallbackURL: z.string().optional(),\n\terrorCallbackURL: z.string().meta({ description: \"Callback URL to redirect to if an error happens\" }).optional(),\n\tprovider: SocialProviderListEnum,\n\tdisableRedirect: z.boolean().meta({ description: \"Disable automatic redirection to the provider. Useful for handling the redirection yourself\" }).optional(),\n\tidToken: z.optional(z.object({\n\t\ttoken: z.string().meta({ description: \"ID token from the provider\" }),\n\t\tnonce: z.string().meta({ description: \"Nonce used to generate the token\" }).optional(),\n\t\taccessToken: z.string().meta({ description: \"Access token from the provider\" }).optional(),\n\t\trefreshToken: z.string().meta({ description: \"Refresh token from the provider\" }).optional(),\n\t\texpiresAt: z.number().meta({ description: \"Expiry date of the token\" }).optional(),\n\t\tuser: z.object({\n\t\t\tname: z.object({\n\t\t\t\tfirstName: z.string().optional(),\n\t\t\t\tlastName: z.string().optional()\n\t\t\t}).optional(),\n\t\t\temail: z.string().optional()\n\t\t}).meta({ description: \"The user object from the provider. Only available for some providers like Apple.\" }).optional()\n\t})),\n\tscopes: z.array(z.string()).meta({ description: \"Array of scopes to request from the provider. This will override the default scopes passed.\" }).optional(),\n\trequestSignUp: z.boolean().meta({ description: \"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider\" }).optional(),\n\tloginHint: z.string().meta({ description: \"The login hint to use for the authorization code request\" }).optional(),\n\tadditionalData: z.record(z.string(), z.any()).optional().meta({ description: \"Additional data to be passed through the OAuth flow\" })\n});\nconst signInSocial = () => createAuthEndpoint(\"/sign-in/social\", {\n\tmethod: \"POST\",\n\toperationId: \"socialSignIn\",\n\tbody: socialSignInBodySchema,\n\tmetadata: {\n\t\t$Infer: {\n\t\t\tbody: {},\n\t\t\treturned: {}\n\t\t},\n\t\topenapi: {\n\t\t\tdescription: \"Sign in with a social provider\",\n\t\t\toperationId: \"socialSignIn\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success - Returns either session details or redirect URL\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"Session response when idToken is provided\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttoken: { type: \"string\" },\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t$ref: \"#/components/schemas/User\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\turl: { type: \"string\" },\n\t\t\t\t\t\tredirect: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tenum: [false]\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"redirect\",\n\t\t\t\t\t\t\"token\",\n\t\t\t\t\t\t\"user\"\n\t\t\t\t\t]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (c) => {\n\tconst provider = await getAwaitableValue(c.context.socialProviders, { value: c.body.provider });\n\tif (!provider) {\n\t\tc.context.logger.error(\"Provider not found. Make sure to add the provider in your auth config\", { provider: c.body.provider });\n\t\tthrow APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.PROVIDER_NOT_FOUND);\n\t}\n\tif (c.body.idToken) {\n\t\tif (!provider.verifyIdToken) {\n\t\t\tc.context.logger.error(\"Provider does not support id token verification\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);\n\t\t}\n\t\tconst { token, nonce } = c.body.idToken;\n\t\tif (!await provider.verifyIdToken(token, nonce)) {\n\t\t\tc.context.logger.error(\"Invalid id token\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_TOKEN);\n\t\t}\n\t\tconst userInfo = await provider.getUserInfo({\n\t\t\tidToken: token,\n\t\t\taccessToken: c.body.idToken.accessToken,\n\t\t\trefreshToken: c.body.idToken.refreshToken,\n\t\t\tuser: c.body.idToken.user\n\t\t});\n\t\tif (!userInfo || !userInfo?.user) {\n\t\t\tc.context.logger.error(\"Failed to get user info\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);\n\t\t}\n\t\tif (!userInfo.user.email) {\n\t\t\tc.context.logger.error(\"User email not found\", { provider: c.body.provider });\n\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);\n\t\t}\n\t\tconst data = await handleOAuthUserInfo(c, {\n\t\t\tuserInfo: {\n\t\t\t\t...userInfo.user,\n\t\t\t\temail: userInfo.user.email,\n\t\t\t\tid: String(userInfo.user.id),\n\t\t\t\tname: userInfo.user.name || \"\",\n\t\t\t\timage: userInfo.user.image,\n\t\t\t\temailVerified: userInfo.user.emailVerified || false\n\t\t\t},\n\t\t\taccount: {\n\t\t\t\tproviderId: provider.id,\n\t\t\t\taccountId: String(userInfo.user.id),\n\t\t\t\taccessToken: c.body.idToken.accessToken\n\t\t\t},\n\t\t\tcallbackURL: c.body.callbackURL,\n\t\t\tdisableSignUp: provider.disableImplicitSignUp && !c.body.requestSignUp || provider.disableSignUp\n\t\t});\n\t\tif (data.error) throw APIError.from(\"UNAUTHORIZED\", {\n\t\t\tmessage: data.error,\n\t\t\tcode: \"OAUTH_LINK_ERROR\"\n\t\t});\n\t\tawait setSessionCookie(c, data.data);\n\t\treturn c.json({\n\t\t\tredirect: false,\n\t\t\ttoken: data.data.session.token,\n\t\t\turl: void 0,\n\t\t\tuser: parseUserOutput(c.context.options, data.data.user)\n\t\t});\n\t}\n\tconst { codeVerifier, state } = await generateState(c, void 0, c.body.additionalData);\n\tconst url = await provider.createAuthorizationURL({\n\t\tstate,\n\t\tcodeVerifier,\n\t\tredirectURI: `${c.context.baseURL}/callback/${provider.id}`,\n\t\tscopes: c.body.scopes,\n\t\tloginHint: c.body.loginHint\n\t});\n\tif (!c.body.disableRedirect) c.setHeader(\"Location\", url.toString());\n\treturn c.json({\n\t\turl: url.toString(),\n\t\tredirect: !c.body.disableRedirect\n\t});\n});\nconst signInEmail = () => createAuthEndpoint(\"/sign-in/email\", {\n\tmethod: \"POST\",\n\toperationId: \"signInEmail\",\n\tuse: [formCsrfMiddleware],\n\tbody: z.object({\n\t\temail: z.string().meta({ description: \"Email of the user\" }),\n\t\tpassword: z.string().meta({ description: \"Password of the user\" }),\n\t\tcallbackURL: z.string().meta({ description: \"Callback URL to use as a redirect for email verification\" }).optional(),\n\t\trememberMe: z.boolean().meta({ description: \"If this is false, the session will not be remembered. Default is `true`.\" }).default(true).optional()\n\t}),\n\tmetadata: {\n\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\", \"application/json\"],\n\t\t$Infer: {\n\t\t\tbody: {},\n\t\t\treturned: {}\n\t\t},\n\t\topenapi: {\n\t\t\toperationId: \"signInEmail\",\n\t\t\tdescription: \"Sign in with email and password\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success - Returns either session details or redirect URL\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"Session response when idToken is provided\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tredirect: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tenum: [false]\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Session token\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\turl: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tnullable: true\n\t\t\t\t\t\t},\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t$ref: \"#/components/schemas/User\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"redirect\",\n\t\t\t\t\t\t\"token\",\n\t\t\t\t\t\t\"user\"\n\t\t\t\t\t]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\tif (!ctx.context.options?.emailAndPassword?.enabled) {\n\t\tctx.context.logger.error(\"Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\tcode: \"EMAIL_PASSWORD_DISABLED\",\n\t\t\tmessage: \"Email and password is not enabled\"\n\t\t});\n\t}\n\tconst { email, password } = ctx.body;\n\tif (!z.email().safeParse(email).success) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_EMAIL);\n\tconst user = await ctx.context.internalAdapter.findUserByEmail(email, { includeAccounts: true });\n\tif (!user) {\n\t\tawait ctx.context.password.hash(password);\n\t\tctx.context.logger.error(\"User not found\", { email });\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);\n\t}\n\tconst credentialAccount = user.accounts.find((a) => a.providerId === \"credential\");\n\tif (!credentialAccount) {\n\t\tawait ctx.context.password.hash(password);\n\t\tctx.context.logger.error(\"Credential account not found\", { email });\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);\n\t}\n\tconst currentPassword = credentialAccount?.password;\n\tif (!currentPassword) {\n\t\tawait ctx.context.password.hash(password);\n\t\tctx.context.logger.error(\"Password not found\", { email });\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);\n\t}\n\tif (!await ctx.context.password.verify({\n\t\thash: currentPassword,\n\t\tpassword\n\t})) {\n\t\tctx.context.logger.error(\"Invalid password\");\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);\n\t}\n\tif (ctx.context.options?.emailAndPassword?.requireEmailVerification && !user.user.emailVerified) {\n\t\tif (!ctx.context.options?.emailVerification?.sendVerificationEmail) throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.EMAIL_NOT_VERIFIED);\n\t\tif (ctx.context.options?.emailVerification?.sendOnSignIn) {\n\t\t\tconst token = await createEmailVerificationToken(ctx.context.secret, user.user.email, void 0, ctx.context.options.emailVerification?.expiresIn);\n\t\t\tconst callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent(\"/\");\n\t\t\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`;\n\t\t\tawait ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({\n\t\t\t\tuser: user.user,\n\t\t\t\turl,\n\t\t\t\ttoken\n\t\t\t}, ctx.request));\n\t\t}\n\t\tthrow APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.EMAIL_NOT_VERIFIED);\n\t}\n\tconst session = await ctx.context.internalAdapter.createSession(user.user.id, ctx.body.rememberMe === false);\n\tif (!session) {\n\t\tctx.context.logger.error(\"Failed to create session\");\n\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);\n\t}\n\tawait setSessionCookie(ctx, {\n\t\tsession,\n\t\tuser: user.user\n\t}, ctx.body.rememberMe === false);\n\tif (ctx.body.callbackURL) ctx.setHeader(\"Location\", ctx.body.callbackURL);\n\treturn ctx.json({\n\t\tredirect: !!ctx.body.callbackURL,\n\t\ttoken: session.token,\n\t\turl: ctx.body.callbackURL,\n\t\tuser: parseUserOutput(ctx.context.options, user.user)\n\t});\n});\n//#endregion\nexport { signInEmail, signInSocial };\n", "import { deleteSessionCookie } from \"../../cookies/index.mjs\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\n//#region src/api/routes/sign-out.ts\nconst signOut = createAuthEndpoint(\"/sign-out\", {\n\tmethod: \"POST\",\n\toperationId: \"signOut\",\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\toperationId: \"signOut\",\n\t\tdescription: \"Sign out the current user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { success: { type: \"boolean\" } }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);\n\tif (sessionCookieToken) try {\n\t\tawait ctx.context.internalAdapter.deleteSession(sessionCookieToken);\n\t} catch (e) {\n\t\tctx.context.logger.error(\"Failed to delete session from database\", e);\n\t}\n\tdeleteSessionCookie(ctx);\n\treturn ctx.json({ success: true });\n});\n//#endregion\nexport { signOut };\n", "import { isAPIError } from \"../../utils/is-api-error.mjs\";\nimport { formCsrfMiddleware } from \"../middlewares/origin-check.mjs\";\nimport { parseUserInput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { setSessionCookie } from \"../../cookies/index.mjs\";\nimport { createEmailVerificationToken } from \"./email-verification.mjs\";\nimport { runWithTransaction } from \"@better-auth/core/context\";\nimport { isDevelopment } from \"@better-auth/core/env\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { generateId } from \"@better-auth/core/utils/id\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/sign-up.ts\nconst signUpEmailBodySchema = z.object({\n\tname: z.string(),\n\temail: z.email(),\n\tpassword: z.string().nonempty(),\n\timage: z.string().optional(),\n\tcallbackURL: z.string().optional(),\n\trememberMe: z.boolean().optional()\n}).and(z.record(z.string(), z.any()));\nconst signUpEmail = () => createAuthEndpoint(\"/sign-up/email\", {\n\tmethod: \"POST\",\n\toperationId: \"signUpWithEmailAndPassword\",\n\tuse: [formCsrfMiddleware],\n\tbody: signUpEmailBodySchema,\n\tmetadata: {\n\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\", \"application/json\"],\n\t\t$Infer: {\n\t\t\tbody: {},\n\t\t\treturned: {}\n\t\t},\n\t\topenapi: {\n\t\t\toperationId: \"signUpWithEmailAndPassword\",\n\t\t\tdescription: \"Sign up a user using email and password\",\n\t\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tname: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The name of the user\"\n\t\t\t\t\t},\n\t\t\t\t\temail: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The email of the user\"\n\t\t\t\t\t},\n\t\t\t\t\tpassword: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The password of the user\"\n\t\t\t\t\t},\n\t\t\t\t\timage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The profile image URL of the user\"\n\t\t\t\t\t},\n\t\t\t\t\tcallbackURL: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The URL to use for email verification callback\"\n\t\t\t\t\t},\n\t\t\t\t\trememberMe: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"If this is false, the session will not be remembered. Default is `true`.\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\n\t\t\t\t\t\"name\",\n\t\t\t\t\t\"email\",\n\t\t\t\t\t\"password\"\n\t\t\t\t]\n\t\t\t} } } },\n\t\t\tresponses: {\n\t\t\t\t\"200\": {\n\t\t\t\t\tdescription: \"Successfully created user\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\tdescription: \"Authentication token for the session\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"The unique identifier of the user\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"The email address of the user\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"The name of the user\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\timage: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\tdescription: \"The profile image URL of the user\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\temailVerified: {\n\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the email has been verified\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"When the user was created\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"When the user was last updated\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\t\t\"email\",\n\t\t\t\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\t\t\t\"emailVerified\",\n\t\t\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"user\"]\n\t\t\t\t\t} } }\n\t\t\t\t},\n\t\t\t\t\"422\": {\n\t\t\t\t\tdescription: \"Unprocessable Entity. User already exists or failed to create user.\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: { message: { type: \"string\" } }\n\t\t\t\t\t} } }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}, async (ctx) => {\n\treturn runWithTransaction(ctx.context.adapter, async () => {\n\t\tif (!ctx.context.options.emailAndPassword?.enabled || ctx.context.options.emailAndPassword?.disableSignUp) throw APIError.from(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Email and password sign up is not enabled\",\n\t\t\tcode: \"EMAIL_PASSWORD_SIGN_UP_DISABLED\"\n\t\t});\n\t\tconst body = ctx.body;\n\t\tconst { name, email, password, image, callbackURL: _callbackURL, rememberMe, ...rest } = body;\n\t\tif (!z.email().safeParse(email).success) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_EMAIL);\n\t\tif (!password || typeof password !== \"string\") throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\tconst minPasswordLength = ctx.context.password.config.minPasswordLength;\n\t\tif (password.length < minPasswordLength) {\n\t\t\tctx.context.logger.error(\"Password is too short\");\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_SHORT);\n\t\t}\n\t\tconst maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n\t\tif (password.length > maxPasswordLength) {\n\t\t\tctx.context.logger.error(\"Password is too long\");\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_LONG);\n\t\t}\n\t\tconst shouldReturnGenericDuplicateResponse = ctx.context.options.emailAndPassword.requireEmailVerification;\n\t\tconst shouldSkipAutoSignIn = ctx.context.options.emailAndPassword.autoSignIn === false || shouldReturnGenericDuplicateResponse;\n\t\tconst additionalUserFields = parseUserInput(ctx.context.options, rest, \"create\");\n\t\tconst normalizedEmail = email.toLowerCase();\n\t\tconst dbUser = await ctx.context.internalAdapter.findUserByEmail(normalizedEmail);\n\t\tif (dbUser?.user) {\n\t\t\tctx.context.logger.info(`Sign-up attempt for existing email: ${email}`);\n\t\t\tif (shouldReturnGenericDuplicateResponse) {\n\t\t\t\t/**\n\t\t\t\t* Hash the password to reduce timing differences\n\t\t\t\t* between existing and non-existing emails.\n\t\t\t\t*/\n\t\t\t\tawait ctx.context.password.hash(password);\n\t\t\t\tif (ctx.context.options.emailAndPassword?.onExistingUserSignUp) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.onExistingUserSignUp({ user: dbUser.user }, ctx.request));\n\t\t\t\tconst now = /* @__PURE__ */ new Date();\n\t\t\t\tconst generatedId = ctx.context.generateId({ model: \"user\" }) || generateId();\n\t\t\t\tconst coreFields = {\n\t\t\t\t\tname,\n\t\t\t\t\temail: normalizedEmail,\n\t\t\t\t\temailVerified: false,\n\t\t\t\t\timage: image || null,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now\n\t\t\t\t};\n\t\t\t\tconst customSyntheticUser = ctx.context.options.emailAndPassword?.customSyntheticUser;\n\t\t\t\tlet syntheticUser;\n\t\t\t\tif (customSyntheticUser) {\n\t\t\t\t\tconst additionalFieldKeys = Object.keys(ctx.context.options.user?.additionalFields ?? {});\n\t\t\t\t\tconst additionalFields = {};\n\t\t\t\t\tfor (const key of additionalFieldKeys) if (key in additionalUserFields) additionalFields[key] = additionalUserFields[key];\n\t\t\t\t\tsyntheticUser = customSyntheticUser({\n\t\t\t\t\t\tcoreFields,\n\t\t\t\t\t\tadditionalFields,\n\t\t\t\t\t\tid: generatedId\n\t\t\t\t\t});\n\t\t\t\t} else syntheticUser = {\n\t\t\t\t\t...coreFields,\n\t\t\t\t\t...additionalUserFields,\n\t\t\t\t\tid: generatedId\n\t\t\t\t};\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttoken: null,\n\t\t\t\t\tuser: parseUserOutput(ctx.context.options, syntheticUser)\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow APIError.from(\"UNPROCESSABLE_ENTITY\", BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);\n\t\t}\n\t\t/**\n\t\t* Hash the password\n\t\t*\n\t\t* This is done prior to creating the user\n\t\t* to ensure that any plugin that\n\t\t* may break the hashing should break\n\t\t* before the user is created.\n\t\t*/\n\t\tconst hash = await ctx.context.password.hash(password);\n\t\tlet createdUser;\n\t\ttry {\n\t\t\tcreatedUser = await ctx.context.internalAdapter.createUser({\n\t\t\t\temail: normalizedEmail,\n\t\t\t\tname,\n\t\t\t\timage,\n\t\t\t\t...additionalUserFields,\n\t\t\t\temailVerified: false\n\t\t\t});\n\t\t\tif (!createdUser) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.FAILED_TO_CREATE_USER);\n\t\t} catch (e) {\n\t\t\tif (isDevelopment()) ctx.context.logger.error(\"Failed to create user\", e);\n\t\t\tif (isAPIError(e)) throw e;\n\t\t\tctx.context.logger?.error(\"Failed to create user\", e);\n\t\t\tthrow APIError.from(\"UNPROCESSABLE_ENTITY\", BASE_ERROR_CODES.FAILED_TO_CREATE_USER);\n\t\t}\n\t\tif (!createdUser) throw APIError.from(\"UNPROCESSABLE_ENTITY\", BASE_ERROR_CODES.FAILED_TO_CREATE_USER);\n\t\tawait ctx.context.internalAdapter.linkAccount({\n\t\t\tuserId: createdUser.id,\n\t\t\tproviderId: \"credential\",\n\t\t\taccountId: createdUser.id,\n\t\t\tpassword: hash\n\t\t});\n\t\tif (ctx.context.options.emailVerification?.sendOnSignUp ?? ctx.context.options.emailAndPassword.requireEmailVerification) {\n\t\t\tconst token = await createEmailVerificationToken(ctx.context.secret, createdUser.email, void 0, ctx.context.options.emailVerification?.expiresIn);\n\t\t\tconst callbackURL = body.callbackURL ? encodeURIComponent(body.callbackURL) : encodeURIComponent(\"/\");\n\t\t\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`;\n\t\t\tif (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({\n\t\t\t\tuser: createdUser,\n\t\t\t\turl,\n\t\t\t\ttoken\n\t\t\t}, ctx.request));\n\t\t}\n\t\tif (shouldSkipAutoSignIn) return ctx.json({\n\t\t\ttoken: null,\n\t\t\tuser: parseUserOutput(ctx.context.options, createdUser)\n\t\t});\n\t\tconst session = await ctx.context.internalAdapter.createSession(createdUser.id, rememberMe === false);\n\t\tif (!session) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession,\n\t\t\tuser: createdUser\n\t\t}, rememberMe === false);\n\t\treturn ctx.json({\n\t\t\ttoken: session.token,\n\t\t\tuser: parseUserOutput(ctx.context.options, createdUser)\n\t\t});\n\t});\n});\n//#endregion\nexport { signUpEmail };\n", "import { parseSessionInput, parseSessionOutput } from \"../../db/schema.mjs\";\nimport { setSessionCookie } from \"../../cookies/index.mjs\";\nimport { sessionMiddleware } from \"./session.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/update-session.ts\nconst updateSessionBodySchema = z.record(z.string().meta({ description: \"Field name must be a string\" }), z.any());\nconst updateSession = () => createAuthEndpoint(\"/update-session\", {\n\tmethod: \"POST\",\n\toperationId: \"updateSession\",\n\tbody: updateSessionBodySchema,\n\tuse: [sessionMiddleware],\n\tmetadata: {\n\t\t$Infer: { body: {} },\n\t\topenapi: {\n\t\t\toperationId: \"updateSession\",\n\t\t\tdescription: \"Update the current session\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { session: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/Session\"\n\t\t\t\t\t} }\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\tconst body = ctx.body;\n\tif (typeof body !== \"object\" || Array.isArray(body)) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);\n\tconst session = ctx.context.session;\n\tconst additionalFields = parseSessionInput(ctx.context.options, body, \"update\");\n\tif (Object.keys(additionalFields).length === 0) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"No fields to update\" });\n\tconst newSession = await ctx.context.internalAdapter.updateSession(session.session.token, {\n\t\t...additionalFields,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}) ?? {\n\t\t...session.session,\n\t\t...additionalFields,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tawait setSessionCookie(ctx, {\n\t\tsession: newSession,\n\t\tuser: session.user\n\t});\n\treturn ctx.json({ session: parseSessionOutput(ctx.context.options, newSession) });\n});\n//#endregion\nexport { updateSession };\n", "import { originCheck } from \"../middlewares/origin-check.mjs\";\nimport { parseUserInput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { generateRandomString } from \"../../crypto/random.mjs\";\nimport { deleteSessionCookie, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { getSessionFromCtx, sensitiveSessionMiddleware, sessionMiddleware } from \"./session.mjs\";\nimport { createEmailVerificationToken } from \"./email-verification.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/update-user.ts\nconst updateUserBodySchema = z.record(z.string().meta({ description: \"Field name must be a string\" }), z.any());\nconst updateUser = () => createAuthEndpoint(\"/update-user\", {\n\tmethod: \"POST\",\n\toperationId: \"updateUser\",\n\tbody: updateUserBodySchema,\n\tuse: [sessionMiddleware],\n\tmetadata: {\n\t\t$Infer: { body: {} },\n\t\topenapi: {\n\t\t\toperationId: \"updateUser\",\n\t\t\tdescription: \"Update the current user\",\n\t\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tname: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The name of the user\"\n\t\t\t\t\t},\n\t\t\t\t\timage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The image of the user\",\n\t\t\t\t\t\tnullable: true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} } } },\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { user: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/User\"\n\t\t\t\t\t} }\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\tconst body = ctx.body;\n\tif (typeof body !== \"object\" || Array.isArray(body)) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);\n\tif (body.email) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED);\n\tconst { name, image, ...rest } = body;\n\tconst session = ctx.context.session;\n\tconst additionalFields = parseUserInput(ctx.context.options, rest, \"update\");\n\tif (image === void 0 && name === void 0 && Object.keys(additionalFields).length === 0) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"No fields to update\" });\n\tconst updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, {\n\t\tname,\n\t\timage,\n\t\t...additionalFields\n\t}) ?? {\n\t\t...session.user,\n\t\t...name !== void 0 && { name },\n\t\t...image !== void 0 && { image },\n\t\t...additionalFields\n\t};\n\t/**\n\t* Update the session cookie with the new user data\n\t*/\n\tawait setSessionCookie(ctx, {\n\t\tsession: session.session,\n\t\tuser: updatedUser\n\t});\n\treturn ctx.json({ status: true });\n});\nconst changePassword = createAuthEndpoint(\"/change-password\", {\n\tmethod: \"POST\",\n\toperationId: \"changePassword\",\n\tbody: z.object({\n\t\tnewPassword: z.string().meta({ description: \"The new password to set\" }),\n\t\tcurrentPassword: z.string().meta({ description: \"The current password is required\" }),\n\t\trevokeOtherSessions: z.boolean().meta({ description: \"Must be a boolean value\" }).optional()\n\t}),\n\tuse: [sensitiveSessionMiddleware],\n\tmetadata: { openapi: {\n\t\toperationId: \"changePassword\",\n\t\tdescription: \"Change the password of the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Password successfully changed\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\ttoken: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\tdescription: \"New session token if other sessions were revoked\"\n\t\t\t\t\t},\n\t\t\t\t\tuser: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"The unique identifier of the user\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\tdescription: \"The email address of the user\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"The name of the user\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\timage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\tdescription: \"The profile image URL of the user\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\temailVerified: {\n\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\tdescription: \"Whether the email has been verified\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"When the user was created\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"When the user was last updated\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"email\",\n\t\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\t\"emailVerified\",\n\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t]\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"user\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst { newPassword, currentPassword, revokeOtherSessions } = ctx.body;\n\tconst session = ctx.context.session;\n\tconst minPasswordLength = ctx.context.password.config.minPasswordLength;\n\tif (newPassword.length < minPasswordLength) {\n\t\tctx.context.logger.error(\"Password is too short\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_SHORT);\n\t}\n\tconst maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n\tif (newPassword.length > maxPasswordLength) {\n\t\tctx.context.logger.error(\"Password is too long\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_LONG);\n\t}\n\tconst account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account) => account.providerId === \"credential\" && account.password);\n\tif (!account || !account.password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);\n\tconst passwordHash = await ctx.context.password.hash(newPassword);\n\tif (!await ctx.context.password.verify({\n\t\thash: account.password,\n\t\tpassword: currentPassword\n\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\tawait ctx.context.internalAdapter.updateAccount(account.id, { password: passwordHash });\n\tlet token = null;\n\tif (revokeOtherSessions) {\n\t\tawait ctx.context.internalAdapter.deleteSessions(session.user.id);\n\t\tconst newSession = await ctx.context.internalAdapter.createSession(session.user.id);\n\t\tif (!newSession) throw APIError.from(\"INTERNAL_SERVER_ERROR\", BASE_ERROR_CODES.FAILED_TO_GET_SESSION);\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession: newSession,\n\t\t\tuser: session.user\n\t\t});\n\t\ttoken = newSession.token;\n\t}\n\treturn ctx.json({\n\t\ttoken,\n\t\tuser: parseUserOutput(ctx.context.options, session.user)\n\t});\n});\nconst setPassword = createAuthEndpoint({\n\tmethod: \"POST\",\n\tbody: z.object({ newPassword: z.string().meta({ description: \"The new password to set is required\" }) }),\n\tuse: [sensitiveSessionMiddleware]\n}, async (ctx) => {\n\tconst { newPassword } = ctx.body;\n\tconst session = ctx.context.session;\n\tconst minPasswordLength = ctx.context.password.config.minPasswordLength;\n\tif (newPassword.length < minPasswordLength) {\n\t\tctx.context.logger.error(\"Password is too short\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_SHORT);\n\t}\n\tconst maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n\tif (newPassword.length > maxPasswordLength) {\n\t\tctx.context.logger.error(\"Password is too long\");\n\t\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_TOO_LONG);\n\t}\n\tconst account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account) => account.providerId === \"credential\" && account.password);\n\tconst passwordHash = await ctx.context.password.hash(newPassword);\n\tif (!account) {\n\t\tawait ctx.context.internalAdapter.linkAccount({\n\t\t\tuserId: session.user.id,\n\t\t\tproviderId: \"credential\",\n\t\t\taccountId: session.user.id,\n\t\t\tpassword: passwordHash\n\t\t});\n\t\treturn ctx.json({ status: true });\n\t}\n\tthrow APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.PASSWORD_ALREADY_SET);\n});\nconst deleteUser = createAuthEndpoint(\"/delete-user\", {\n\tmethod: \"POST\",\n\tuse: [sensitiveSessionMiddleware],\n\tbody: z.object({\n\t\tcallbackURL: z.string().meta({ description: \"The callback URL to redirect to after the user is deleted\" }).optional(),\n\t\tpassword: z.string().meta({ description: \"The password of the user is required to delete the user\" }).optional(),\n\t\ttoken: z.string().meta({ description: \"The token to delete the user is required\" }).optional()\n\t}),\n\tmetadata: { openapi: {\n\t\toperationId: \"deleteUser\",\n\t\tdescription: \"Delete the user\",\n\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\ttype: \"object\",\n\t\t\tproperties: {\n\t\t\t\tcallbackURL: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The callback URL to redirect to after the user is deleted\"\n\t\t\t\t},\n\t\t\t\tpassword: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The user's password. Required if session is not fresh\"\n\t\t\t\t},\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The deletion verification token\"\n\t\t\t\t}\n\t\t\t}\n\t\t} } } },\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"User deletion processed successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tsuccess: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the operation was successful\"\n\t\t\t\t\t},\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tenum: [\"User deleted\", \"Verification email sent\"],\n\t\t\t\t\t\tdescription: \"Status message of the deletion process\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"success\", \"message\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tif (!ctx.context.options.user?.deleteUser?.enabled) {\n\t\tctx.context.logger.error(\"Delete user is disabled. Enable it in the options\");\n\t\tthrow APIError.fromStatus(\"NOT_FOUND\");\n\t}\n\tconst session = ctx.context.session;\n\tif (ctx.body.password) {\n\t\tconst account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account) => account.providerId === \"credential\" && account.password);\n\t\tif (!account || !account.password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);\n\t\tif (!await ctx.context.password.verify({\n\t\t\thash: account.password,\n\t\t\tpassword: ctx.body.password\n\t\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t}\n\tif (ctx.body.token) {\n\t\tawait deleteUserCallback({\n\t\t\t...ctx,\n\t\t\tquery: { token: ctx.body.token }\n\t\t});\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t\tmessage: \"User deleted\"\n\t\t});\n\t}\n\tif (ctx.context.options.user.deleteUser?.sendDeleteAccountVerification) {\n\t\tconst token = generateRandomString(32, \"0-9\", \"a-z\");\n\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\tvalue: session.user.id,\n\t\t\tidentifier: `delete-account-${token}`,\n\t\t\texpiresAt: new Date(Date.now() + (ctx.context.options.user.deleteUser?.deleteTokenExpiresIn || 3600 * 24) * 1e3)\n\t\t});\n\t\tconst url = `${ctx.context.baseURL}/delete-user/callback?token=${token}&callbackURL=${encodeURIComponent(ctx.body.callbackURL || \"/\")}`;\n\t\tawait ctx.context.runInBackgroundOrAwait(ctx.context.options.user.deleteUser.sendDeleteAccountVerification({\n\t\t\tuser: session.user,\n\t\t\turl,\n\t\t\ttoken\n\t\t}, ctx.request));\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t\tmessage: \"Verification email sent\"\n\t\t});\n\t}\n\tif (!ctx.body.password && ctx.context.sessionConfig.freshAge !== 0) {\n\t\tconst createdAt = new Date(session.session.createdAt).getTime();\n\t\tconst freshAge = ctx.context.sessionConfig.freshAge * 1e3;\n\t\tif (Date.now() - createdAt >= freshAge) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.SESSION_EXPIRED);\n\t}\n\tconst beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete;\n\tif (beforeDelete) await beforeDelete(session.user, ctx.request);\n\tawait ctx.context.internalAdapter.deleteUser(session.user.id);\n\tawait ctx.context.internalAdapter.deleteSessions(session.user.id);\n\tdeleteSessionCookie(ctx);\n\tconst afterDelete = ctx.context.options.user.deleteUser?.afterDelete;\n\tif (afterDelete) await afterDelete(session.user, ctx.request);\n\treturn ctx.json({\n\t\tsuccess: true,\n\t\tmessage: \"User deleted\"\n\t});\n});\nconst deleteUserCallback = createAuthEndpoint(\"/delete-user/callback\", {\n\tmethod: \"GET\",\n\tquery: z.object({\n\t\ttoken: z.string().meta({ description: \"The token to verify the deletion request\" }),\n\t\tcallbackURL: z.string().meta({ description: \"The URL to redirect to after deletion\" }).optional()\n\t}),\n\tuse: [originCheck((ctx) => ctx.query.callbackURL)],\n\tmetadata: { openapi: {\n\t\tdescription: \"Callback to complete user deletion with verification token\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"User successfully deleted\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tsuccess: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the deletion was successful\"\n\t\t\t\t\t},\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tenum: [\"User deleted\"],\n\t\t\t\t\t\tdescription: \"Confirmation message\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"success\", \"message\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tif (!ctx.context.options.user?.deleteUser?.enabled) {\n\t\tctx.context.logger.error(\"Delete user is disabled. Enable it in the options\");\n\t\tthrow APIError.from(\"NOT_FOUND\", {\n\t\t\tmessage: \"Not found\",\n\t\t\tcode: \"NOT_FOUND\"\n\t\t});\n\t}\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);\n\tconst token = await ctx.context.internalAdapter.findVerificationValue(`delete-account-${ctx.query.token}`);\n\tif (!token || token.expiresAt < /* @__PURE__ */ new Date()) throw APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.INVALID_TOKEN);\n\tif (token.value !== session.user.id) throw APIError.from(\"NOT_FOUND\", BASE_ERROR_CODES.INVALID_TOKEN);\n\tconst beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete;\n\tif (beforeDelete) await beforeDelete(session.user, ctx.request);\n\tawait ctx.context.internalAdapter.deleteUser(session.user.id);\n\tawait ctx.context.internalAdapter.deleteSessions(session.user.id);\n\tawait ctx.context.internalAdapter.deleteAccounts(session.user.id);\n\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(`delete-account-${ctx.query.token}`);\n\tdeleteSessionCookie(ctx);\n\tconst afterDelete = ctx.context.options.user.deleteUser?.afterDelete;\n\tif (afterDelete) await afterDelete(session.user, ctx.request);\n\tif (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL || \"/\");\n\treturn ctx.json({\n\t\tsuccess: true,\n\t\tmessage: \"User deleted\"\n\t});\n});\nconst changeEmail = createAuthEndpoint(\"/change-email\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tnewEmail: z.email().meta({ description: \"The new email address to set must be a valid email address\" }),\n\t\tcallbackURL: z.string().meta({ description: \"The URL to redirect to after email verification\" }).optional()\n\t}),\n\tuse: [sensitiveSessionMiddleware],\n\tmetadata: { openapi: {\n\t\toperationId: \"changeEmail\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Email change request processed successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tuser: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/User\"\n\t\t\t\t\t},\n\t\t\t\t\tstatus: {\n\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\tdescription: \"Indicates if the request was successful\"\n\t\t\t\t\t},\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tenum: [\"Email updated\", \"Verification email sent\"],\n\t\t\t\t\t\tdescription: \"Status message of the email change process\",\n\t\t\t\t\t\tnullable: true\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tif (!ctx.context.options.user?.changeEmail?.enabled) {\n\t\tctx.context.logger.error(\"Change email is disabled.\");\n\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Change email is disabled\" });\n\t}\n\tconst newEmail = ctx.body.newEmail.toLowerCase();\n\tif (newEmail === ctx.context.session.user.email) {\n\t\tctx.context.logger.error(\"Email is the same\");\n\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Email is the same\" });\n\t}\n\t/**\n\t* Early config check: ensure at least one email-change flow is\n\t* available for the current session state. Without this, an\n\t* existing-email lookup would return 200 while a non-existing\n\t* email would later throw 400, leaking email existence.\n\t*/\n\tconst canUpdateWithoutVerification = ctx.context.session.user.emailVerified !== true && ctx.context.options.user.changeEmail.updateEmailWithoutVerification;\n\tconst canSendConfirmation = ctx.context.session.user.emailVerified && ctx.context.options.user.changeEmail.sendChangeEmailConfirmation;\n\tconst canSendVerification = ctx.context.options.emailVerification?.sendVerificationEmail;\n\tif (!canUpdateWithoutVerification && !canSendConfirmation && !canSendVerification) {\n\t\tctx.context.logger.error(\"Verification email isn't enabled.\");\n\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Verification email isn't enabled\" });\n\t}\n\tif (await ctx.context.internalAdapter.findUserByEmail(newEmail)) {\n\t\tawait createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn);\n\t\tctx.context.logger.info(\"Change email attempt for existing email\");\n\t\treturn ctx.json({ status: true });\n\t}\n\t/**\n\t* If the email is not verified, we can update the email if the option is enabled\n\t*/\n\tif (canUpdateWithoutVerification) {\n\t\tawait ctx.context.internalAdapter.updateUserByEmail(ctx.context.session.user.email, { email: newEmail });\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession: ctx.context.session.session,\n\t\t\tuser: {\n\t\t\t\t...ctx.context.session.user,\n\t\t\t\temail: newEmail\n\t\t\t}\n\t\t});\n\t\tif (canSendVerification) {\n\t\t\tconst token = await createEmailVerificationToken(ctx.context.secret, newEmail, void 0, ctx.context.options.emailVerification?.expiresIn);\n\t\t\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n\t\t\tawait ctx.context.runInBackgroundOrAwait(canSendVerification({\n\t\t\t\tuser: {\n\t\t\t\t\t...ctx.context.session.user,\n\t\t\t\t\temail: newEmail\n\t\t\t\t},\n\t\t\t\turl,\n\t\t\t\ttoken\n\t\t\t}, ctx.request));\n\t\t}\n\t\treturn ctx.json({ status: true });\n\t}\n\t/**\n\t* If the email is verified, we need to send a verification email\n\t*/\n\tif (canSendConfirmation) {\n\t\tconst token = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: \"change-email-confirmation\" });\n\t\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n\t\tawait ctx.context.runInBackgroundOrAwait(canSendConfirmation({\n\t\t\tuser: ctx.context.session.user,\n\t\t\tnewEmail,\n\t\t\turl,\n\t\t\ttoken\n\t\t}, ctx.request));\n\t\treturn ctx.json({ status: true });\n\t}\n\tif (!canSendVerification) {\n\t\tctx.context.logger.error(\"Verification email isn't enabled.\");\n\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Verification email isn't enabled\" });\n\t}\n\tconst token = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: \"change-email-verification\" });\n\tconst url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n\tawait ctx.context.runInBackgroundOrAwait(canSendVerification({\n\t\tuser: {\n\t\t\t...ctx.context.session.user,\n\t\t\temail: newEmail\n\t\t},\n\t\turl,\n\t\ttoken\n\t}, ctx.request));\n\treturn ctx.json({ status: true });\n});\n//#endregion\nexport { changeEmail, changePassword, deleteUser, deleteUserCallback, setPassword, updateUser };\n", "import { isAPIError } from \"../utils/is-api-error.mjs\";\nimport { hasRequestState, runWithEndpointContext, runWithRequestState } from \"@better-auth/core/context\";\nimport { shouldPublishLog } from \"@better-auth/core/env\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createDefu } from \"defu\";\nimport { ATTR_CONTEXT, ATTR_HOOK_TYPE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID, withSpan } from \"@better-auth/core/instrumentation\";\nimport { kAPIErrorHeaderSymbol, toResponse } from \"better-call\";\n//#region src/api/to-auth-endpoints.ts\nconst defuReplaceArrays = createDefu((obj, key, value) => {\n\tif (Array.isArray(obj[key]) && Array.isArray(value)) {\n\t\tobj[key] = value;\n\t\treturn true;\n\t}\n});\nconst hooksSourceWeakMap = /* @__PURE__ */ new WeakMap();\nfunction getOperationId(endpoint, key) {\n\tif (!endpoint?.options) return key;\n\tconst opts = endpoint.options;\n\treturn opts.operationId ?? opts.metadata?.openapi?.operationId ?? key;\n}\nfunction toAuthEndpoints(endpoints, ctx) {\n\tconst api = {};\n\tfor (const [key, endpoint] of Object.entries(endpoints)) {\n\t\tapi[key] = async (context) => {\n\t\t\tconst operationId = getOperationId(endpoint, key);\n\t\t\tconst endpointMethod = endpoint?.options?.method;\n\t\t\tconst defaultMethod = Array.isArray(endpointMethod) ? endpointMethod[0] : endpointMethod;\n\t\t\tconst run = async () => {\n\t\t\t\tconst authContext = await ctx;\n\t\t\t\tconst methodName = context?.method ?? context?.request?.method ?? defaultMethod ?? \"?\";\n\t\t\t\tconst route = endpoint.path ?? \"/:virtual\";\n\t\t\t\tlet internalContext = {\n\t\t\t\t\t...context,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...authContext,\n\t\t\t\t\t\treturned: void 0,\n\t\t\t\t\t\tresponseHeaders: void 0,\n\t\t\t\t\t\tsession: null\n\t\t\t\t\t},\n\t\t\t\t\tpath: endpoint.path,\n\t\t\t\t\theaders: context?.headers ? new Headers(context?.headers) : void 0\n\t\t\t\t};\n\t\t\t\tconst hasRequest = context?.request instanceof Request;\n\t\t\t\tconst shouldReturnResponse = context?.asResponse ?? hasRequest;\n\t\t\t\treturn withSpan(`${methodName} ${route}`, {\n\t\t\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t\t\t}, async () => runWithEndpointContext(internalContext, async () => {\n\t\t\t\t\tconst { beforeHooks, afterHooks } = getHooks(authContext);\n\t\t\t\t\tconst before = await runBeforeHooks(internalContext, beforeHooks, endpoint, operationId);\n\t\t\t\t\t/**\n\t\t\t\t\t* If `before.context` is returned, it should\n\t\t\t\t\t* get merged with the original context\n\t\t\t\t\t*/\n\t\t\t\t\tif (\"context\" in before && before.context && typeof before.context === \"object\") {\n\t\t\t\t\t\tconst { headers, ...rest } = before.context;\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t* Headers should be merged differently\n\t\t\t\t\t\t* so the hook doesn't override the whole\n\t\t\t\t\t\t* header\n\t\t\t\t\t\t*/\n\t\t\t\t\t\tif (headers) headers.forEach((value, key) => {\n\t\t\t\t\t\t\tinternalContext.headers.set(key, value);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tinternalContext = defuReplaceArrays(rest, internalContext);\n\t\t\t\t\t} else if (before) return shouldReturnResponse ? toResponse(before, { headers: context?.headers }) : context?.returnHeaders ? {\n\t\t\t\t\t\theaders: context?.headers,\n\t\t\t\t\t\tresponse: before\n\t\t\t\t\t} : before;\n\t\t\t\t\tinternalContext.asResponse = false;\n\t\t\t\t\tinternalContext.returnHeaders = true;\n\t\t\t\t\tinternalContext.returnStatus = true;\n\t\t\t\t\tconst result = await runWithEndpointContext(internalContext, () => withSpan(`handler ${route}`, {\n\t\t\t\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t\t\t\t}, () => endpoint(internalContext))).catch((e) => {\n\t\t\t\t\t\tif (isAPIError(e))\n /**\n\t\t\t\t\t\t* API Errors from response are caught\n\t\t\t\t\t\t* and returned to hooks\n\t\t\t\t\t\t*/\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tresponse: e,\n\t\t\t\t\t\t\tstatus: e.statusCode,\n\t\t\t\t\t\t\theaders: e.headers ? new Headers(e.headers) : null\n\t\t\t\t\t\t};\n\t\t\t\t\t\tthrow e;\n\t\t\t\t\t});\n\t\t\t\t\tif (result && result instanceof Response) return result;\n\t\t\t\t\tinternalContext.context.returned = result.response;\n\t\t\t\t\tinternalContext.context.responseHeaders = result.headers;\n\t\t\t\t\tconst after = await runAfterHooks(internalContext, afterHooks, endpoint, operationId);\n\t\t\t\t\tif (after.response) result.response = after.response;\n\t\t\t\t\tif (isAPIError(result.response) && shouldPublishLog(authContext.logger.level, \"debug\")) result.response.stack = result.response.errorStack;\n\t\t\t\t\tif (isAPIError(result.response) && !shouldReturnResponse) throw result.response;\n\t\t\t\t\treturn shouldReturnResponse ? toResponse(result.response, {\n\t\t\t\t\t\theaders: result.headers,\n\t\t\t\t\t\tstatus: result.status\n\t\t\t\t\t}) : context?.returnHeaders ? context?.returnStatus ? {\n\t\t\t\t\t\theaders: result.headers,\n\t\t\t\t\t\tresponse: result.response,\n\t\t\t\t\t\tstatus: result.status\n\t\t\t\t\t} : {\n\t\t\t\t\t\theaders: result.headers,\n\t\t\t\t\t\tresponse: result.response\n\t\t\t\t\t} : context?.returnStatus ? {\n\t\t\t\t\t\tresponse: result.response,\n\t\t\t\t\t\tstatus: result.status\n\t\t\t\t\t} : result.response;\n\t\t\t\t}));\n\t\t\t};\n\t\t\tif (await hasRequestState()) return run();\n\t\t\telse return runWithRequestState(/* @__PURE__ */ new WeakMap(), run);\n\t\t};\n\t\tapi[key].path = endpoint.path;\n\t\tapi[key].options = endpoint.options;\n\t}\n\treturn api;\n}\nasync function runBeforeHooks(context, hooks, endpoint, operationId) {\n\tlet modifiedContext = {};\n\tfor (const hook of hooks) {\n\t\tlet matched = false;\n\t\ttry {\n\t\t\tmatched = hook.matcher(context);\n\t\t} catch (error) {\n\t\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\t\tcontext.context.logger.error(`An error occurred during ${hookSource} hook matcher execution:`, error);\n\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", { message: `An error occurred during hook matcher execution. Check the logs for more details.` });\n\t\t}\n\t\tif (matched) {\n\t\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\t\tconst route = endpoint.path ?? \"/:virtual\";\n\t\t\tconst result = await withSpan(`hook before ${route} ${hookSource}`, {\n\t\t\t\t[ATTR_HOOK_TYPE]: \"before\",\n\t\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t\t[ATTR_CONTEXT]: hookSource,\n\t\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t\t}, () => hook.handler({\n\t\t\t\t...context,\n\t\t\t\treturnHeaders: false\n\t\t\t})).catch((e) => {\n\t\t\t\tif (isAPIError(e) && shouldPublishLog(context.context.logger.level, \"debug\")) e.stack = e.errorStack;\n\t\t\t\tthrow e;\n\t\t\t});\n\t\t\tif (result && typeof result === \"object\") {\n\t\t\t\tif (\"context\" in result && typeof result.context === \"object\") {\n\t\t\t\t\tconst { headers, ...rest } = result.context;\n\t\t\t\t\tif (headers instanceof Headers) if (modifiedContext.headers) headers.forEach((value, key) => {\n\t\t\t\t\t\tmodifiedContext.headers?.set(key, value);\n\t\t\t\t\t});\n\t\t\t\t\telse modifiedContext.headers = headers;\n\t\t\t\t\tmodifiedContext = defuReplaceArrays(rest, modifiedContext);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t}\n\treturn { context: modifiedContext };\n}\nasync function runAfterHooks(context, hooks, endpoint, operationId) {\n\tfor (const hook of hooks) if (hook.matcher(context)) {\n\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\tconst route = endpoint.path ?? \"/:virtual\";\n\t\tconst result = await withSpan(`hook after ${route} ${hookSource}`, {\n\t\t\t[ATTR_HOOK_TYPE]: \"after\",\n\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t[ATTR_CONTEXT]: hookSource,\n\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t}, () => hook.handler(context)).catch((e) => {\n\t\t\tif (isAPIError(e)) {\n\t\t\t\tconst headers = e[kAPIErrorHeaderSymbol];\n\t\t\t\tif (shouldPublishLog(context.context.logger.level, \"debug\")) e.stack = e.errorStack;\n\t\t\t\treturn {\n\t\t\t\t\tresponse: e,\n\t\t\t\t\theaders: headers ? headers : e.headers ? new Headers(e.headers) : null\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow e;\n\t\t});\n\t\tif (result.headers) result.headers.forEach((value, key) => {\n\t\t\tif (!context.context.responseHeaders) context.context.responseHeaders = new Headers({ [key]: value });\n\t\t\telse if (key.toLowerCase() === \"set-cookie\") context.context.responseHeaders.append(key, value);\n\t\t\telse context.context.responseHeaders.set(key, value);\n\t\t});\n\t\tif (result.response) context.context.returned = result.response;\n\t}\n\treturn {\n\t\tresponse: context.context.returned,\n\t\theaders: context.context.responseHeaders\n\t};\n}\nfunction getHooks(authContext) {\n\tconst plugins = authContext.options.plugins || [];\n\tconst beforeHooks = [];\n\tconst afterHooks = [];\n\tconst beforeHookHandler = authContext.options.hooks?.before;\n\tif (beforeHookHandler) {\n\t\thooksSourceWeakMap.set(beforeHookHandler, \"user\");\n\t\tbeforeHooks.push({\n\t\t\tmatcher: () => true,\n\t\t\thandler: beforeHookHandler\n\t\t});\n\t}\n\tconst afterHookHandler = authContext.options.hooks?.after;\n\tif (afterHookHandler) {\n\t\thooksSourceWeakMap.set(afterHookHandler, \"user\");\n\t\tafterHooks.push({\n\t\t\tmatcher: () => true,\n\t\t\thandler: afterHookHandler\n\t\t});\n\t}\n\tconst pluginBeforeHooks = plugins.flatMap((plugin) => (plugin.hooks?.before ?? []).map((h) => {\n\t\thooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`);\n\t\treturn h;\n\t}));\n\tconst pluginAfterHooks = plugins.flatMap((plugin) => (plugin.hooks?.after ?? []).map((h) => {\n\t\thooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`);\n\t\treturn h;\n\t}));\n\t/**\n\t* Add plugin added hooks at last\n\t*/\n\tif (pluginBeforeHooks.length) beforeHooks.push(...pluginBeforeHooks);\n\tif (pluginAfterHooks.length) afterHooks.push(...pluginAfterHooks);\n\treturn {\n\t\tbeforeHooks,\n\t\tafterHooks\n\t};\n}\n//#endregion\nexport { toAuthEndpoints };\n", "import { isAPIError } from \"../utils/is-api-error.mjs\";\nimport { requireOrgRole, requireResourceOwnership } from \"./middlewares/authorization.mjs\";\nimport { formCsrfMiddleware, originCheck, originCheckMiddleware } from \"./middlewares/origin-check.mjs\";\nimport { getIp } from \"../utils/get-request-ip.mjs\";\nimport { onRequestRateLimit, onResponseRateLimit } from \"./rate-limiter/index.mjs\";\nimport { getOAuthState } from \"./state/oauth.mjs\";\nimport { getShouldSkipSessionRefresh, setShouldSkipSessionRefresh } from \"./state/should-session-refresh.mjs\";\nimport { freshSessionMiddleware, getSession, getSessionFromCtx, listSessions, requestOnlySessionMiddleware, revokeOtherSessions, revokeSession, revokeSessions, sensitiveSessionMiddleware, sessionMiddleware } from \"./routes/session.mjs\";\nimport { accountInfo, getAccessToken, linkSocialAccount, listUserAccounts, refreshToken, unlinkAccount } from \"./routes/account.mjs\";\nimport { callbackOAuth } from \"./routes/callback.mjs\";\nimport { createEmailVerificationToken, sendVerificationEmail, sendVerificationEmailFn, verifyEmail } from \"./routes/email-verification.mjs\";\nimport { error } from \"./routes/error.mjs\";\nimport { ok } from \"./routes/ok.mjs\";\nimport { requestPasswordReset, requestPasswordResetCallback, resetPassword, verifyPassword } from \"./routes/password.mjs\";\nimport { signInEmail, signInSocial } from \"./routes/sign-in.mjs\";\nimport { signOut } from \"./routes/sign-out.mjs\";\nimport { signUpEmail } from \"./routes/sign-up.mjs\";\nimport { updateSession } from \"./routes/update-session.mjs\";\nimport { changeEmail, changePassword, deleteUser, deleteUserCallback, setPassword, updateUser } from \"./routes/update-user.mjs\";\nimport { toAuthEndpoints } from \"./to-auth-endpoints.mjs\";\nimport { logger } from \"@better-auth/core/env\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { ATTR_CONTEXT, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, withSpan } from \"@better-auth/core/instrumentation\";\nimport { normalizePathname } from \"@better-auth/core/utils/url\";\nimport { createRouter } from \"better-call\";\nimport { createAuthEndpoint, createAuthMiddleware, optionsMiddleware } from \"@better-auth/core/api\";\n//#region src/api/index.ts\nfunction checkEndpointConflicts(options, logger) {\n\tconst endpointRegistry = /* @__PURE__ */ new Map();\n\toptions.plugins?.forEach((plugin) => {\n\t\tif (plugin.endpoints) {\n\t\t\tfor (const [key, endpoint] of Object.entries(plugin.endpoints)) if (endpoint && \"path\" in endpoint && typeof endpoint.path === \"string\") {\n\t\t\t\tconst path = endpoint.path;\n\t\t\t\tlet methods = [];\n\t\t\t\tif (endpoint.options && \"method\" in endpoint.options) {\n\t\t\t\t\tif (Array.isArray(endpoint.options.method)) methods = endpoint.options.method;\n\t\t\t\t\telse if (typeof endpoint.options.method === \"string\") methods = [endpoint.options.method];\n\t\t\t\t}\n\t\t\t\tif (methods.length === 0) methods = [\"*\"];\n\t\t\t\tif (!endpointRegistry.has(path)) endpointRegistry.set(path, []);\n\t\t\t\tendpointRegistry.get(path).push({\n\t\t\t\t\tpluginId: plugin.id,\n\t\t\t\t\tendpointKey: key,\n\t\t\t\t\tmethods\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n\tconst conflicts = [];\n\tfor (const [path, entries] of endpointRegistry.entries()) if (entries.length > 1) {\n\t\tconst methodMap = /* @__PURE__ */ new Map();\n\t\tlet hasConflict = false;\n\t\tfor (const entry of entries) for (const method of entry.methods) {\n\t\t\tif (!methodMap.has(method)) methodMap.set(method, []);\n\t\t\tmethodMap.get(method).push(entry.pluginId);\n\t\t\tif (methodMap.get(method).length > 1) hasConflict = true;\n\t\t\tif (method === \"*\" && entries.length > 1) hasConflict = true;\n\t\t\telse if (method !== \"*\" && methodMap.has(\"*\")) hasConflict = true;\n\t\t}\n\t\tif (hasConflict) {\n\t\t\tconst uniquePlugins = [...new Set(entries.map((e) => e.pluginId))];\n\t\t\tconst conflictingMethods = [];\n\t\t\tfor (const [method, plugins] of methodMap.entries()) if (plugins.length > 1 || method === \"*\" && entries.length > 1 || method !== \"*\" && methodMap.has(\"*\")) conflictingMethods.push(method);\n\t\t\tconflicts.push({\n\t\t\t\tpath,\n\t\t\t\tplugins: uniquePlugins,\n\t\t\t\tconflictingMethods\n\t\t\t});\n\t\t}\n\t}\n\tif (conflicts.length > 0) {\n\t\tconst conflictMessages = conflicts.map((conflict) => ` - \"${conflict.path}\" [${conflict.conflictingMethods.join(\", \")}] used by plugins: ${conflict.plugins.join(\", \")}`).join(\"\\n\");\n\t\tlogger.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:\n${conflictMessages}\n\nTo resolve this, you can:\n\t1. Use only one of the conflicting plugins\n\t2. Configure the plugins to use different paths (if supported)\n\t3. Ensure plugins use different HTTP methods for the same path\n`);\n\t}\n}\nfunction getEndpoints(ctx, options) {\n\tconst pluginEndpoints = options.plugins?.reduce((acc, plugin) => {\n\t\treturn {\n\t\t\t...acc,\n\t\t\t...plugin.endpoints\n\t\t};\n\t}, {}) ?? {};\n\tconst middlewares = options.plugins?.map((plugin) => plugin.middlewares?.map((m) => {\n\t\tconst middleware = (async (context) => {\n\t\t\tconst authContext = await ctx;\n\t\t\treturn withSpan(`middleware ${m.path} ${plugin.id}`, {\n\t\t\t\t[ATTR_HOOK_TYPE]: \"middleware\",\n\t\t\t\t[ATTR_HTTP_ROUTE]: m.path,\n\t\t\t\t[ATTR_CONTEXT]: `plugin:${plugin.id}`\n\t\t\t}, () => m.middleware({\n\t\t\t\t...context,\n\t\t\t\tcontext: {\n\t\t\t\t\t...authContext,\n\t\t\t\t\t...context.context\n\t\t\t\t}\n\t\t\t}));\n\t\t});\n\t\tmiddleware.options = m.middleware.options;\n\t\treturn {\n\t\t\tpath: m.path,\n\t\t\tmiddleware\n\t\t};\n\t})).filter((plugin) => plugin !== void 0).flat() || [];\n\treturn {\n\t\tapi: toAuthEndpoints({\n\t\t\tsignInSocial: signInSocial(),\n\t\t\tcallbackOAuth,\n\t\t\tgetSession: getSession(),\n\t\t\tsignOut,\n\t\t\tsignUpEmail: signUpEmail(),\n\t\t\tsignInEmail: signInEmail(),\n\t\t\tresetPassword,\n\t\t\tverifyPassword,\n\t\t\tverifyEmail,\n\t\t\tsendVerificationEmail,\n\t\t\tchangeEmail,\n\t\t\tchangePassword,\n\t\t\tsetPassword,\n\t\t\tupdateSession: updateSession(),\n\t\t\tupdateUser: updateUser(),\n\t\t\tdeleteUser,\n\t\t\trequestPasswordReset,\n\t\t\trequestPasswordResetCallback,\n\t\t\tlistSessions: listSessions(),\n\t\t\trevokeSession,\n\t\t\trevokeSessions,\n\t\t\trevokeOtherSessions,\n\t\t\tlinkSocialAccount,\n\t\t\tlistUserAccounts,\n\t\t\tdeleteUserCallback,\n\t\t\tunlinkAccount,\n\t\t\trefreshToken,\n\t\t\tgetAccessToken,\n\t\t\taccountInfo,\n\t\t\t...pluginEndpoints,\n\t\t\tok,\n\t\t\terror\n\t\t}, ctx),\n\t\tmiddlewares\n\t};\n}\nconst router = (ctx, options) => {\n\tconst { api, middlewares } = getEndpoints(ctx, options);\n\tconst basePath = new URL(ctx.baseURL).pathname;\n\treturn createRouter(api, {\n\t\trouterContext: ctx,\n\t\topenapi: { disabled: true },\n\t\tbasePath,\n\t\trouterMiddleware: [{\n\t\t\tpath: \"/**\",\n\t\t\tmiddleware: originCheckMiddleware\n\t\t}, ...middlewares],\n\t\tallowedMediaTypes: [\"application/json\"],\n\t\tskipTrailingSlashes: options.advanced?.skipTrailingSlashes ?? false,\n\t\tasync onRequest(req) {\n\t\t\tconst disabledPaths = ctx.options.disabledPaths || [];\n\t\t\tconst normalizedPath = normalizePathname(req.url, basePath);\n\t\t\tif (disabledPaths.includes(normalizedPath)) return new Response(\"Not Found\", { status: 404 });\n\t\t\tlet currentRequest = req;\n\t\t\tfor (const plugin of ctx.options.plugins || []) if (plugin.onRequest) {\n\t\t\t\tconst response = await withSpan(`onRequest ${plugin.id}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"onRequest\",\n\t\t\t\t\t[ATTR_CONTEXT]: `plugin:${plugin.id}`\n\t\t\t\t}, () => plugin.onRequest(currentRequest, ctx));\n\t\t\t\tif (response && \"response\" in response) return response.response;\n\t\t\t\tif (response && \"request\" in response) currentRequest = response.request;\n\t\t\t}\n\t\t\tconst rateLimitResponse = await onRequestRateLimit(currentRequest, ctx);\n\t\t\tif (rateLimitResponse) return rateLimitResponse;\n\t\t\treturn currentRequest;\n\t\t},\n\t\tasync onResponse(res, req) {\n\t\t\tawait onResponseRateLimit(req, ctx);\n\t\t\tfor (const plugin of ctx.options.plugins || []) if (plugin.onResponse) {\n\t\t\t\tconst response = await withSpan(`onResponse ${plugin.id}`, {\n\t\t\t\t\t[ATTR_HOOK_TYPE]: \"onResponse\",\n\t\t\t\t\t[ATTR_CONTEXT]: `plugin:${plugin.id}`,\n\t\t\t\t\t[ATTR_HTTP_RESPONSE_STATUS_CODE]: res.status\n\t\t\t\t}, () => plugin.onResponse(res, ctx));\n\t\t\t\tif (response) return response.response;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tonError(e) {\n\t\t\tif (isAPIError(e) && e.status === \"FOUND\") return;\n\t\t\tif (options.onAPIError?.throw) throw e;\n\t\t\tif (options.onAPIError?.onError) {\n\t\t\t\toptions.onAPIError.onError(e, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst optLogLevel = options.logger?.level;\n\t\t\tconst log = optLogLevel === \"error\" || optLogLevel === \"warn\" || optLogLevel === \"debug\" ? logger : void 0;\n\t\t\tif (options.logger?.disabled !== true) {\n\t\t\t\tif (e && typeof e === \"object\" && \"message\" in e && typeof e.message === \"string\") {\n\t\t\t\t\tif (e.message.includes(\"no column\") || e.message.includes(\"column\") || e.message.includes(\"relation\") || e.message.includes(\"table\") || e.message.includes(\"does not exist\")) {\n\t\t\t\t\t\tctx.logger?.error(e.message);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (isAPIError(e)) {\n\t\t\t\t\tif (e.status === \"INTERNAL_SERVER_ERROR\") ctx.logger.error(e.status, e);\n\t\t\t\t\tlog?.error(e.message);\n\t\t\t\t} else ctx.logger?.error(e && typeof e === \"object\" && \"name\" in e ? e.name : \"\", e);\n\t\t\t}\n\t\t}\n\t});\n};\n//#endregion\nexport { APIError, accountInfo, callbackOAuth, changeEmail, changePassword, checkEndpointConflicts, createAuthEndpoint, createAuthMiddleware, createEmailVerificationToken, deleteUser, deleteUserCallback, error, formCsrfMiddleware, freshSessionMiddleware, getAccessToken, getEndpoints, getIp, getOAuthState, getSession, getSessionFromCtx, getShouldSkipSessionRefresh, isAPIError, linkSocialAccount, listSessions, listUserAccounts, ok, optionsMiddleware, originCheck, originCheckMiddleware, refreshToken, requestOnlySessionMiddleware, requestPasswordReset, requestPasswordResetCallback, requireOrgRole, requireResourceOwnership, resetPassword, revokeOtherSessions, revokeSession, revokeSessions, router, sendVerificationEmail, sendVerificationEmailFn, sensitiveSessionMiddleware, sessionMiddleware, setPassword, setShouldSkipSessionRefresh, signInEmail, signInSocial, signOut, signUpEmail, unlinkAccount, updateSession, updateUser, verifyEmail, verifyPassword };\n", "import { getAuthTables } from \"@better-auth/core/db\";\nimport { logger } from \"@better-auth/core/env\";\n//#region src/db/adapter-base.ts\nasync function getBaseAdapter(options, handleDirectDatabase) {\n\tlet adapter;\n\tif (!options.database) {\n\t\tconst tables = getAuthTables(options);\n\t\tconst memoryDB = Object.keys(tables).reduce((acc, key) => {\n\t\t\tacc[key] = [];\n\t\t\treturn acc;\n\t\t}, {});\n\t\tconst { memoryAdapter } = await import(\"@better-auth/memory-adapter\");\n\t\tadapter = memoryAdapter(memoryDB)(options);\n\t} else if (typeof options.database === \"function\") adapter = options.database(options);\n\telse adapter = await handleDirectDatabase(options);\n\tif (!adapter.transaction) {\n\t\tlogger.warn(\"Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.\");\n\t\tadapter.transaction = async (cb) => {\n\t\t\treturn cb(adapter);\n\t\t};\n\t}\n\treturn adapter;\n}\n//#endregion\nexport { getBaseAdapter };\n", "import { getBaseAdapter } from \"./adapter-base.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/db/adapter-kysely.ts\nasync function getAdapter(options) {\n\treturn getBaseAdapter(options, async (opts) => {\n\t\tconst { createKyselyAdapter } = await import(\"../adapters/kysely-adapter/index.mjs\");\n\t\tconst { kysely, databaseType, transaction } = await createKyselyAdapter(opts);\n\t\tif (!kysely) throw new BetterAuthError(\"Failed to initialize database adapter\");\n\t\tconst { kyselyAdapter } = await import(\"../adapters/kysely-adapter/index.mjs\");\n\t\treturn kyselyAdapter(kysely, {\n\t\t\ttype: databaseType || \"sqlite\",\n\t\t\tdebugLogs: opts.database && \"debugLogs\" in opts.database ? opts.database.debugLogs : false,\n\t\t\ttransaction\n\t\t})(opts);\n\t});\n}\n//#endregion\nexport { getAdapter };\n", "import { getAuthTables } from \"@better-auth/core/db\";\n//#region src/db/get-schema.ts\nfunction getSchema(config) {\n\tconst tables = getAuthTables(config);\n\tconst schema = {};\n\tfor (const key in tables) {\n\t\tconst table = tables[key];\n\t\tconst fields = table.fields;\n\t\tconst actualFields = {};\n\t\tObject.entries(fields).forEach(([key, field]) => {\n\t\t\tactualFields[field.fieldName || key] = field;\n\t\t\tif (field.references) {\n\t\t\t\tconst refTable = tables[field.references.model];\n\t\t\t\tif (refTable) actualFields[field.fieldName || key].references = {\n\t\t\t\t\t...field.references,\n\t\t\t\t\tmodel: refTable.modelName,\n\t\t\t\t\tfield: field.references.field\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t\tif (schema[table.modelName]) {\n\t\t\tschema[table.modelName].fields = {\n\t\t\t\t...schema[table.modelName].fields,\n\t\t\t\t...actualFields\n\t\t\t};\n\t\t\tcontinue;\n\t\t}\n\t\tschema[table.modelName] = {\n\t\t\tfields: actualFields,\n\t\t\torder: table.order || Infinity\n\t\t};\n\t}\n\treturn schema;\n}\n//#endregion\nexport { getSchema };\n", "import { getSchema } from \"./get-schema.mjs\";\nimport { getAuthTables } from \"@better-auth/core/db\";\nimport { createLogger } from \"@better-auth/core/env\";\nimport { createKyselyAdapter } from \"@better-auth/kysely-adapter\";\nimport { initGetFieldName, initGetModelName } from \"@better-auth/core/db/adapter\";\nimport { sql } from \"kysely\";\n//#region src/db/get-migration.ts\nconst map = {\n\tpostgres: {\n\t\tstring: [\n\t\t\t\"character varying\",\n\t\t\t\"varchar\",\n\t\t\t\"text\",\n\t\t\t\"uuid\"\n\t\t],\n\t\tnumber: [\n\t\t\t\"int4\",\n\t\t\t\"integer\",\n\t\t\t\"bigint\",\n\t\t\t\"smallint\",\n\t\t\t\"numeric\",\n\t\t\t\"real\",\n\t\t\t\"double precision\"\n\t\t],\n\t\tboolean: [\"bool\", \"boolean\"],\n\t\tdate: [\n\t\t\t\"timestamptz\",\n\t\t\t\"timestamp\",\n\t\t\t\"date\"\n\t\t],\n\t\tjson: [\"json\", \"jsonb\"]\n\t},\n\tmysql: {\n\t\tstring: [\n\t\t\t\"varchar\",\n\t\t\t\"text\",\n\t\t\t\"uuid\"\n\t\t],\n\t\tnumber: [\n\t\t\t\"integer\",\n\t\t\t\"int\",\n\t\t\t\"bigint\",\n\t\t\t\"smallint\",\n\t\t\t\"decimal\",\n\t\t\t\"float\",\n\t\t\t\"double\"\n\t\t],\n\t\tboolean: [\"boolean\", \"tinyint\"],\n\t\tdate: [\n\t\t\t\"timestamp\",\n\t\t\t\"datetime\",\n\t\t\t\"date\"\n\t\t],\n\t\tjson: [\"json\"]\n\t},\n\tsqlite: {\n\t\tstring: [\"TEXT\"],\n\t\tnumber: [\"INTEGER\", \"REAL\"],\n\t\tboolean: [\"INTEGER\", \"BOOLEAN\"],\n\t\tdate: [\"DATE\", \"INTEGER\"],\n\t\tjson: [\"TEXT\"]\n\t},\n\tmssql: {\n\t\tstring: [\n\t\t\t\"varchar\",\n\t\t\t\"nvarchar\",\n\t\t\t\"uniqueidentifier\"\n\t\t],\n\t\tnumber: [\n\t\t\t\"int\",\n\t\t\t\"bigint\",\n\t\t\t\"smallint\",\n\t\t\t\"decimal\",\n\t\t\t\"float\",\n\t\t\t\"double\"\n\t\t],\n\t\tboolean: [\"bit\", \"smallint\"],\n\t\tdate: [\n\t\t\t\"datetime2\",\n\t\t\t\"date\",\n\t\t\t\"datetime\"\n\t\t],\n\t\tjson: [\"varchar\", \"nvarchar\"]\n\t}\n};\nfunction matchType(columnDataType, fieldType, dbType) {\n\tfunction normalize(type) {\n\t\treturn type.toLowerCase().split(\"(\")[0].trim();\n\t}\n\tif (fieldType === \"string[]\" || fieldType === \"number[]\") return columnDataType.toLowerCase().includes(\"json\");\n\tconst types = map[dbType];\n\treturn (Array.isArray(fieldType) ? types[\"string\"].map((t) => t.toLowerCase()) : types[fieldType].map((t) => t.toLowerCase())).includes(normalize(columnDataType));\n}\n/**\n* Get the current PostgreSQL schema (search_path) for the database connection\n* Returns the first schema in the search_path, defaulting to 'public' if not found\n*/\nasync function getPostgresSchema(db) {\n\ttry {\n\t\tconst result = await sql`SHOW search_path`.execute(db);\n\t\tconst searchPath = result.rows[0]?.search_path ?? result.rows[0]?.searchPath;\n\t\tif (searchPath) return searchPath.split(\",\").map((s) => s.trim()).map((s) => s.replace(/^[\"']|[\"']$/g, \"\")).filter((s) => !s.startsWith(\"$\") && !s.startsWith(\"\\\\$\"))[0] || \"public\";\n\t} catch {}\n\treturn \"public\";\n}\nasync function getMigrations(config) {\n\tconst betterAuthSchema = getSchema(config);\n\tconst logger = createLogger(config.logger);\n\tlet { kysely: db, databaseType: dbType } = await createKyselyAdapter(config);\n\tif (!dbType) {\n\t\tlogger.warn(\"Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.\");\n\t\tdbType = \"sqlite\";\n\t}\n\tif (!db) {\n\t\tlogger.error(\"Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter.\");\n\t\tprocess.exit(1);\n\t}\n\tlet currentSchema = \"public\";\n\tif (dbType === \"postgres\") {\n\t\tcurrentSchema = await getPostgresSchema(db);\n\t\tlogger.debug(`PostgreSQL migration: Using schema '${currentSchema}' (from search_path)`);\n\t\ttry {\n\t\t\tconst schemaCheck = await sql`\n\t\t\t\tSELECT schema_name\n\t\t\t\tFROM information_schema.schemata\n\t\t\t\tWHERE schema_name = ${currentSchema}\n\t\t\t`.execute(db);\n\t\t\tif (!(schemaCheck.rows[0]?.schema_name ?? schemaCheck.rows[0]?.schemaName)) logger.warn(`Schema '${currentSchema}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`);\n\t\t} catch (error) {\n\t\t\tlogger.debug(`Could not verify schema existence: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\tconst allTableMetadata = await db.introspection.getTables();\n\tlet tableMetadata = allTableMetadata;\n\tif (dbType === \"postgres\") try {\n\t\tconst tablesInSchema = await sql`\n\t\t\t\tSELECT table_name\n\t\t\t\tFROM information_schema.tables\n\t\t\t\tWHERE table_schema = ${currentSchema}\n\t\t\t\tAND table_type = 'BASE TABLE'\n\t\t\t`.execute(db);\n\t\tconst tableNamesInSchema = new Set(tablesInSchema.rows.map((row) => row.table_name ?? row.tableName));\n\t\ttableMetadata = allTableMetadata.filter((table) => table.schema === currentSchema && tableNamesInSchema.has(table.name));\n\t\tlogger.debug(`Found ${tableMetadata.length} table(s) in schema '${currentSchema}': ${tableMetadata.map((t) => t.name).join(\", \") || \"(none)\"}`);\n\t} catch (error) {\n\t\tlogger.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tconst toBeCreated = [];\n\tconst toBeAdded = [];\n\tfor (const [key, value] of Object.entries(betterAuthSchema)) {\n\t\tconst table = tableMetadata.find((t) => t.name === key);\n\t\tif (!table) {\n\t\t\tconst tIndex = toBeCreated.findIndex((t) => t.table === key);\n\t\t\tconst tableData = {\n\t\t\t\ttable: key,\n\t\t\t\tfields: value.fields,\n\t\t\t\torder: value.order || Infinity\n\t\t\t};\n\t\t\tconst insertIndex = toBeCreated.findIndex((t) => (t.order || Infinity) > tableData.order);\n\t\t\tif (insertIndex === -1) if (tIndex === -1) toBeCreated.push(tableData);\n\t\t\telse toBeCreated[tIndex].fields = {\n\t\t\t\t...toBeCreated[tIndex].fields,\n\t\t\t\t...value.fields\n\t\t\t};\n\t\t\telse toBeCreated.splice(insertIndex, 0, tableData);\n\t\t\tcontinue;\n\t\t}\n\t\tconst toBeAddedFields = {};\n\t\tfor (const [fieldName, field] of Object.entries(value.fields)) {\n\t\t\tconst column = table.columns.find((c) => c.name === fieldName);\n\t\t\tif (!column) {\n\t\t\t\ttoBeAddedFields[fieldName] = field;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (matchType(column.dataType, field.type, dbType)) continue;\n\t\t\telse logger.warn(`Field ${fieldName} in table ${key} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`);\n\t\t}\n\t\tif (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({\n\t\t\ttable: key,\n\t\t\tfields: toBeAddedFields,\n\t\t\torder: value.order || Infinity\n\t\t});\n\t}\n\tconst migrations = [];\n\tconst useUUIDs = config.advanced?.database?.generateId === \"uuid\";\n\tconst useNumberId = config.advanced?.database?.generateId === \"serial\";\n\tfunction getType(field, fieldName) {\n\t\tconst type = field.type;\n\t\tconst provider = dbType || \"sqlite\";\n\t\tconst typeMap = {\n\t\t\tstring: {\n\t\t\t\tsqlite: \"text\",\n\t\t\t\tpostgres: \"text\",\n\t\t\t\tmysql: field.unique ? \"varchar(255)\" : field.references ? \"varchar(36)\" : field.sortable ? \"varchar(255)\" : field.index ? \"varchar(255)\" : \"text\",\n\t\t\t\tmssql: field.unique || field.sortable ? \"varchar(255)\" : field.references ? \"varchar(36)\" : \"varchar(8000)\"\n\t\t\t},\n\t\t\tboolean: {\n\t\t\t\tsqlite: \"integer\",\n\t\t\t\tpostgres: \"boolean\",\n\t\t\t\tmysql: \"boolean\",\n\t\t\t\tmssql: \"smallint\"\n\t\t\t},\n\t\t\tnumber: {\n\t\t\t\tsqlite: field.bigint ? \"bigint\" : \"integer\",\n\t\t\t\tpostgres: field.bigint ? \"bigint\" : \"integer\",\n\t\t\t\tmysql: field.bigint ? \"bigint\" : \"integer\",\n\t\t\t\tmssql: field.bigint ? \"bigint\" : \"integer\"\n\t\t\t},\n\t\t\tdate: {\n\t\t\t\tsqlite: \"date\",\n\t\t\t\tpostgres: \"timestamptz\",\n\t\t\t\tmysql: \"timestamp(3)\",\n\t\t\t\tmssql: sql`datetime2(3)`\n\t\t\t},\n\t\t\tjson: {\n\t\t\t\tsqlite: \"text\",\n\t\t\t\tpostgres: \"jsonb\",\n\t\t\t\tmysql: \"json\",\n\t\t\t\tmssql: \"varchar(8000)\"\n\t\t\t},\n\t\t\tid: {\n\t\t\t\tpostgres: useNumberId ? sql`integer GENERATED BY DEFAULT AS IDENTITY` : useUUIDs ? \"uuid\" : \"text\",\n\t\t\t\tmysql: useNumberId ? \"integer\" : useUUIDs ? \"varchar(36)\" : \"varchar(36)\",\n\t\t\t\tmssql: useNumberId ? \"integer\" : useUUIDs ? \"varchar(36)\" : \"varchar(36)\",\n\t\t\t\tsqlite: useNumberId ? \"integer\" : \"text\"\n\t\t\t},\n\t\t\tforeignKeyId: {\n\t\t\t\tpostgres: useNumberId ? \"integer\" : useUUIDs ? \"uuid\" : \"text\",\n\t\t\t\tmysql: useNumberId ? \"integer\" : useUUIDs ? \"varchar(36)\" : \"varchar(36)\",\n\t\t\t\tmssql: useNumberId ? \"integer\" : useUUIDs ? \"varchar(36)\" : \"varchar(36)\",\n\t\t\t\tsqlite: useNumberId ? \"integer\" : \"text\"\n\t\t\t},\n\t\t\t\"string[]\": {\n\t\t\t\tsqlite: \"text\",\n\t\t\t\tpostgres: \"jsonb\",\n\t\t\t\tmysql: \"json\",\n\t\t\t\tmssql: \"varchar(8000)\"\n\t\t\t},\n\t\t\t\"number[]\": {\n\t\t\t\tsqlite: \"text\",\n\t\t\t\tpostgres: \"jsonb\",\n\t\t\t\tmysql: \"json\",\n\t\t\t\tmssql: \"varchar(8000)\"\n\t\t\t}\n\t\t};\n\t\tif (fieldName === \"id\" || field.references?.field === \"id\") {\n\t\t\tif (fieldName === \"id\") return typeMap.id[provider];\n\t\t\treturn typeMap.foreignKeyId[provider];\n\t\t}\n\t\tif (Array.isArray(type)) return \"text\";\n\t\tif (!(type in typeMap)) throw new Error(`Unsupported field type '${String(type)}' for field '${fieldName}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: \"string\") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);\n\t\treturn typeMap[type][provider];\n\t}\n\tconst getModelName = initGetModelName({\n\t\tschema: getAuthTables(config),\n\t\tusePlural: false\n\t});\n\tconst getFieldName = initGetFieldName({\n\t\tschema: getAuthTables(config),\n\t\tusePlural: false\n\t});\n\tfunction getReferencePath(model, field) {\n\t\ttry {\n\t\t\treturn `${getModelName(model)}.${getFieldName({\n\t\t\t\tmodel,\n\t\t\t\tfield\n\t\t\t})}`;\n\t\t} catch {\n\t\t\treturn `${model}.${field}`;\n\t\t}\n\t}\n\tif (toBeAdded.length) for (const table of toBeAdded) for (const [fieldName, field] of Object.entries(table.fields)) {\n\t\tconst type = getType(field, fieldName);\n\t\tconst builder = db.schema.alterTable(table.table);\n\t\tif (field.index) {\n\t\t\tconst indexName = `${table.table}_${fieldName}_${field.unique ? \"uidx\" : \"idx\"}`;\n\t\t\tconst indexBuilder = db.schema.createIndex(indexName).on(table.table).columns([fieldName]);\n\t\t\tmigrations.push(field.unique ? indexBuilder.unique() : indexBuilder);\n\t\t}\n\t\tconst built = builder.addColumn(fieldName, type, (col) => {\n\t\t\tcol = field.required !== false ? col.notNull() : col;\n\t\t\tif (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || \"cascade\");\n\t\t\tif (field.unique) col = col.unique();\n\t\t\tif (field.type === \"date\" && typeof field.defaultValue === \"function\" && (dbType === \"postgres\" || dbType === \"mysql\" || dbType === \"mssql\")) if (dbType === \"mysql\") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`);\n\t\t\telse col = col.defaultTo(sql`CURRENT_TIMESTAMP`);\n\t\t\treturn col;\n\t\t});\n\t\tmigrations.push(built);\n\t}\n\tconst toBeIndexed = [];\n\tif (toBeCreated.length) for (const table of toBeCreated) {\n\t\tconst idType = getType({ type: useNumberId ? \"number\" : \"string\" }, \"id\");\n\t\tlet dbT = db.schema.createTable(table.table).addColumn(\"id\", idType, (col) => {\n\t\t\tif (useNumberId) {\n\t\t\t\tif (dbType === \"postgres\") return col.primaryKey().notNull();\n\t\t\t\telse if (dbType === \"sqlite\") return col.primaryKey().notNull();\n\t\t\t\telse if (dbType === \"mssql\") return col.identity().primaryKey().notNull();\n\t\t\t\treturn col.autoIncrement().primaryKey().notNull();\n\t\t\t}\n\t\t\tif (useUUIDs) {\n\t\t\t\tif (dbType === \"postgres\") return col.primaryKey().defaultTo(sql`pg_catalog.gen_random_uuid()`).notNull();\n\t\t\t\treturn col.primaryKey().notNull();\n\t\t\t}\n\t\t\treturn col.primaryKey().notNull();\n\t\t});\n\t\tfor (const [fieldName, field] of Object.entries(table.fields)) {\n\t\t\tconst type = getType(field, fieldName);\n\t\t\tdbT = dbT.addColumn(fieldName, type, (col) => {\n\t\t\t\tcol = field.required !== false ? col.notNull() : col;\n\t\t\t\tif (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || \"cascade\");\n\t\t\t\tif (field.unique) col = col.unique();\n\t\t\t\tif (field.type === \"date\" && typeof field.defaultValue === \"function\" && (dbType === \"postgres\" || dbType === \"mysql\" || dbType === \"mssql\")) if (dbType === \"mysql\") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`);\n\t\t\t\telse col = col.defaultTo(sql`CURRENT_TIMESTAMP`);\n\t\t\t\treturn col;\n\t\t\t});\n\t\t\tif (field.index) {\n\t\t\t\tconst builder = db.schema.createIndex(`${table.table}_${fieldName}_${field.unique ? \"uidx\" : \"idx\"}`).on(table.table).columns([fieldName]);\n\t\t\t\ttoBeIndexed.push(field.unique ? builder.unique() : builder);\n\t\t\t}\n\t\t}\n\t\tmigrations.push(dbT);\n\t}\n\tif (toBeIndexed.length) for (const index of toBeIndexed) migrations.push(index);\n\tasync function runMigrations() {\n\t\tfor (const migration of migrations) await migration.execute();\n\t}\n\tasync function compileMigrations() {\n\t\treturn migrations.map((m) => m.compile().sql).join(\";\\n\\n\") + \";\";\n\t}\n\treturn {\n\t\ttoBeCreated,\n\t\ttoBeAdded,\n\t\trunMigrations,\n\t\tcompileMigrations\n\t};\n}\n//#endregion\nexport { getMigrations, matchType };\n", "//#region src/utils/constants.ts\nconst DEFAULT_SECRET = \"better-auth-secret-12345678901234567890\";\n//#endregion\nexport { DEFAULT_SECRET };\n", "import \"../utils/constants.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/context/secret-utils.ts\n/**\n* Estimates the entropy of a string in bits.\n* This is a simple approximation that helps detect low-entropy secrets.\n*/\nfunction estimateEntropy(str) {\n\tconst unique = new Set(str).size;\n\tif (unique === 0) return 0;\n\treturn Math.log2(Math.pow(unique, str.length));\n}\nfunction parseSecretsEnv(envValue) {\n\tif (!envValue) return null;\n\treturn envValue.split(\",\").map((entry) => {\n\t\tentry = entry.trim();\n\t\tconst colonIdx = entry.indexOf(\":\");\n\t\tif (colonIdx === -1) throw new BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry: \"${entry}\". Expected format: \":\"`);\n\t\tconst version = parseInt(entry.slice(0, colonIdx), 10);\n\t\tif (!Number.isInteger(version) || version < 0) throw new BetterAuthError(`Invalid version in BETTER_AUTH_SECRETS: \"${entry.slice(0, colonIdx)}\". Version must be a non-negative integer.`);\n\t\tconst value = entry.slice(colonIdx + 1).trim();\n\t\tif (!value) throw new BetterAuthError(`Empty secret value for version ${version} in BETTER_AUTH_SECRETS.`);\n\t\treturn {\n\t\t\tversion,\n\t\t\tvalue\n\t\t};\n\t});\n}\nfunction validateSecretsArray(secrets, logger) {\n\tif (secrets.length === 0) throw new BetterAuthError(\"`secrets` array must contain at least one entry.\");\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const s of secrets) {\n\t\tconst version = parseInt(String(s.version), 10);\n\t\tif (!Number.isInteger(version) || version < 0 || String(version) !== String(s.version).trim()) throw new BetterAuthError(`Invalid version ${s.version} in \\`secrets\\`. Version must be a non-negative integer.`);\n\t\tif (!s.value) throw new BetterAuthError(`Empty secret value for version ${version} in \\`secrets\\`.`);\n\t\tif (seen.has(version)) throw new BetterAuthError(`Duplicate version ${version} in \\`secrets\\`. Each version must be unique.`);\n\t\tseen.add(version);\n\t}\n\tconst current = secrets[0];\n\tif (current.value.length < 32) logger.warn(`[better-auth] Warning: the current secret (version ${current.version}) should be at least 32 characters long for adequate security.`);\n\tif (estimateEntropy(current.value) < 120) logger.warn(\"[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.\");\n}\nfunction buildSecretConfig(secrets, legacySecret) {\n\tconst keys = /* @__PURE__ */ new Map();\n\tfor (const s of secrets) keys.set(parseInt(String(s.version), 10), s.value);\n\treturn {\n\t\tkeys,\n\t\tcurrentVersion: parseInt(String(secrets[0].version), 10),\n\t\tlegacySecret: legacySecret && legacySecret !== \"better-auth-secret-12345678901234567890\" ? legacySecret : void 0\n\t};\n}\n//#endregion\nexport { buildSecretConfig, parseSecretsEnv, validateSecretsArray };\n", "import { getBaseURL, isDynamicBaseURLConfig } from \"../utils/url.mjs\";\nimport { matchesOriginPattern } from \"../auth/trusted-origins.mjs\";\nimport { createInternalAdapter } from \"../db/internal-adapter.mjs\";\nimport { isPromise } from \"../utils/is-promise.mjs\";\nimport { getInternalPlugins, getTrustedOrigins, getTrustedProviders, runPluginInit } from \"./helpers.mjs\";\nimport { hashPassword, verifyPassword } from \"../crypto/password.mjs\";\nimport { createCookieGetter, getCookies } from \"../cookies/index.mjs\";\nimport { checkPassword } from \"../utils/password.mjs\";\nimport { checkEndpointConflicts } from \"../api/index.mjs\";\nimport { DEFAULT_SECRET } from \"../utils/constants.mjs\";\nimport { buildSecretConfig, parseSecretsEnv, validateSecretsArray } from \"./secret-utils.mjs\";\nimport { getBetterAuthVersion } from \"@better-auth/core/context\";\nimport { getAuthTables } from \"@better-auth/core/db\";\nimport { createLogger, env, isProduction, isTest } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { generateId } from \"@better-auth/core/utils/id\";\nimport { socialProviders } from \"@better-auth/core/social-providers\";\nimport { createTelemetry } from \"@better-auth/telemetry\";\nimport defu$1 from \"defu\";\n//#region src/context/create-context.ts\n/**\n* Estimates the entropy of a string in bits.\n* This is a simple approximation that helps detect low-entropy secrets.\n*/\nfunction estimateEntropy(str) {\n\tconst unique = new Set(str).size;\n\tif (unique === 0) return 0;\n\treturn Math.log2(Math.pow(unique, str.length));\n}\n/**\n* Validates that the secret meets minimum security requirements.\n* Throws BetterAuthError if the secret is invalid.\n* Skips validation for DEFAULT_SECRET in test environments only.\n* Only throws for DEFAULT_SECRET in production environment.\n*/\nfunction validateSecret(secret, logger) {\n\tconst isDefaultSecret = secret === DEFAULT_SECRET;\n\tif (isTest()) return;\n\tif (isDefaultSecret && isProduction) throw new BetterAuthError(\"You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.\");\n\tif (!secret) throw new BetterAuthError(\"BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).\");\n\tif (secret.length < 32) logger.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with \\`npx auth secret\\` or \\`openssl rand -base64 32\\`.`);\n\tif (estimateEntropy(secret) < 120) logger.warn(\"[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.\");\n}\nasync function createAuthContext(adapter, options, getDatabaseType) {\n\tif (!options.database) options = defu$1(options, {\n\t\tsession: { cookieCache: {\n\t\t\tenabled: true,\n\t\t\tstrategy: \"jwe\",\n\t\t\trefreshCache: true,\n\t\t\tmaxAge: options.session?.expiresIn || 3600 * 24 * 7\n\t\t} },\n\t\taccount: {\n\t\t\tstoreStateStrategy: \"cookie\",\n\t\t\tstoreAccountCookie: true\n\t\t}\n\t});\n\tconst plugins = options.plugins || [];\n\tconst internalPlugins = getInternalPlugins(options);\n\tconst logger = createLogger(options.logger);\n\tconst isDynamicConfig = isDynamicBaseURLConfig(options.baseURL);\n\tif (isDynamicBaseURLConfig(options.baseURL)) {\n\t\tconst { allowedHosts } = options.baseURL;\n\t\tif (!allowedHosts || allowedHosts.length === 0) throw new BetterAuthError(\"baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., [\\\"myapp.com\\\", \\\"*.vercel.app\\\"]).\");\n\t}\n\tconst baseURL = isDynamicConfig ? void 0 : getBaseURL(typeof options.baseURL === \"string\" ? options.baseURL : void 0, options.basePath);\n\tif (!baseURL && !isDynamicConfig) logger.warn(`[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_URL environment variable. Without this, callbacks and redirects may not work correctly.`);\n\tif (adapter.id === \"memory\" && options.advanced?.database?.generateId === false) logger.error(`[better-auth] Misconfiguration detected.\nYou are using the memory DB with generateId: false.\nThis will cause no id to be generated for any model.\nMost of the features of Better Auth will not work correctly.`);\n\tconst secretsArray = options.secrets ?? parseSecretsEnv(env.BETTER_AUTH_SECRETS);\n\tconst legacySecret = options.secret || env.BETTER_AUTH_SECRET || env.AUTH_SECRET || \"\";\n\tlet secret;\n\tlet secretConfig;\n\tif (secretsArray) {\n\t\tvalidateSecretsArray(secretsArray, logger);\n\t\tsecret = secretsArray[0].value;\n\t\tsecretConfig = buildSecretConfig(secretsArray, legacySecret);\n\t} else {\n\t\tsecret = legacySecret || \"better-auth-secret-12345678901234567890\";\n\t\tvalidateSecret(secret, logger);\n\t\tsecretConfig = secret;\n\t}\n\toptions = {\n\t\t...options,\n\t\tsecret,\n\t\tbaseURL: isDynamicConfig ? options.baseURL : baseURL ? new URL(baseURL).origin : \"\",\n\t\tbasePath: options.basePath || \"/api/auth\",\n\t\tplugins: plugins.concat(internalPlugins)\n\t};\n\tcheckEndpointConflicts(options, logger);\n\tconst cookies = getCookies(options);\n\tconst tables = getAuthTables(options);\n\tconst providers = (await Promise.all(Object.entries(options.socialProviders || {}).map(async ([key, originalConfig]) => {\n\t\tconst config = typeof originalConfig === \"function\" ? await originalConfig() : originalConfig;\n\t\tif (config == null) return null;\n\t\tif (config.enabled === false) return null;\n\t\tif (!config.clientId) logger.warn(`Social provider ${key} is missing clientId or clientSecret`);\n\t\tconst provider = socialProviders[key](config);\n\t\tprovider.disableImplicitSignUp = config.disableImplicitSignUp;\n\t\treturn provider;\n\t}))).filter((x) => x !== null);\n\tconst generateIdFunc = ({ model, size }) => {\n\t\tif (typeof options.advanced?.generateId === \"function\") return options.advanced.generateId({\n\t\t\tmodel,\n\t\t\tsize\n\t\t});\n\t\tconst dbGenerateId = options?.advanced?.database?.generateId;\n\t\tif (typeof dbGenerateId === \"function\") return dbGenerateId({\n\t\t\tmodel,\n\t\t\tsize\n\t\t});\n\t\tif (dbGenerateId === \"uuid\") return crypto.randomUUID();\n\t\tif (dbGenerateId === \"serial\" || dbGenerateId === false) return false;\n\t\treturn generateId(size);\n\t};\n\tconst { publish } = await createTelemetry(options, {\n\t\tadapter: adapter.id,\n\t\tdatabase: typeof options.database === \"function\" ? \"adapter\" : getDatabaseType(options.database)\n\t});\n\tconst pluginIds = new Set(options.plugins.map((p) => p.id));\n\tconst getPluginFn = (id) => options.plugins.find((p) => p.id === id) ?? null;\n\tconst hasPluginFn = (id) => pluginIds.has(id);\n\tconst trustedOrigins = await getTrustedOrigins(options);\n\tconst trustedProviders = await getTrustedProviders(options);\n\tconst ctx = {\n\t\tappName: options.appName || \"Better Auth\",\n\t\tbaseURL: baseURL || \"\",\n\t\tversion: getBetterAuthVersion(),\n\t\tsocialProviders: providers,\n\t\toptions,\n\t\toauthConfig: {\n\t\t\tstoreStateStrategy: options.account?.storeStateStrategy || (options.database ? \"database\" : \"cookie\"),\n\t\t\tskipStateCookieCheck: !!options.account?.skipStateCookieCheck\n\t\t},\n\t\ttables,\n\t\ttrustedOrigins,\n\t\ttrustedProviders,\n\t\tisTrustedOrigin(url, settings) {\n\t\t\treturn this.trustedOrigins.some((origin) => matchesOriginPattern(url, origin, settings));\n\t\t},\n\t\tsessionConfig: {\n\t\t\tupdateAge: options.session?.updateAge !== void 0 ? options.session.updateAge : 1440 * 60,\n\t\t\texpiresIn: options.session?.expiresIn || 3600 * 24 * 7,\n\t\t\tfreshAge: options.session?.freshAge === void 0 ? 3600 * 24 : options.session.freshAge,\n\t\t\tcookieRefreshCache: (() => {\n\t\t\t\tconst refreshCache = options.session?.cookieCache?.refreshCache;\n\t\t\t\tconst maxAge = options.session?.cookieCache?.maxAge || 300;\n\t\t\t\tif ((!!options.database || !!options.secondaryStorage) && refreshCache) {\n\t\t\t\t\tlogger.warn(\"[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` \u2014 remove it from your config to silence this warning.\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (refreshCache === false || refreshCache === void 0) return false;\n\t\t\t\tif (refreshCache === true) return {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tupdateAge: Math.floor(maxAge * .2)\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tupdateAge: refreshCache.updateAge !== void 0 ? refreshCache.updateAge : Math.floor(maxAge * .2)\n\t\t\t\t};\n\t\t\t})()\n\t\t},\n\t\tsecret,\n\t\tsecretConfig,\n\t\trateLimit: {\n\t\t\t...options.rateLimit,\n\t\t\tenabled: options.rateLimit?.enabled ?? isProduction,\n\t\t\twindow: options.rateLimit?.window || 10,\n\t\t\tmax: options.rateLimit?.max || 100,\n\t\t\tstorage: options.rateLimit?.storage || (options.secondaryStorage ? \"secondary-storage\" : \"memory\")\n\t\t},\n\t\tauthCookies: cookies,\n\t\tlogger,\n\t\tgenerateId: generateIdFunc,\n\t\tsession: null,\n\t\tsecondaryStorage: options.secondaryStorage,\n\t\tpassword: {\n\t\t\thash: options.emailAndPassword?.password?.hash || hashPassword,\n\t\t\tverify: options.emailAndPassword?.password?.verify || verifyPassword,\n\t\t\tconfig: {\n\t\t\t\tminPasswordLength: options.emailAndPassword?.minPasswordLength || 8,\n\t\t\t\tmaxPasswordLength: options.emailAndPassword?.maxPasswordLength || 128\n\t\t\t},\n\t\t\tcheckPassword\n\t\t},\n\t\tsetNewSession(session) {\n\t\t\tthis.newSession = session;\n\t\t},\n\t\tnewSession: null,\n\t\tadapter,\n\t\tinternalAdapter: createInternalAdapter(adapter, {\n\t\t\toptions,\n\t\t\tlogger,\n\t\t\thooks: options.databaseHooks ? [{\n\t\t\t\tsource: \"user\",\n\t\t\t\thooks: options.databaseHooks\n\t\t\t}] : [],\n\t\t\tgenerateId: generateIdFunc\n\t\t}),\n\t\tcreateAuthCookie: createCookieGetter(options),\n\t\tasync runMigrations() {\n\t\t\tthrow new BetterAuthError(\"runMigrations will be set by the specific init implementation\");\n\t\t},\n\t\tpublishTelemetry: publish,\n\t\tskipCSRFCheck: !!options.advanced?.disableCSRFCheck,\n\t\tskipOriginCheck: options.advanced?.disableOriginCheck !== void 0 ? options.advanced.disableOriginCheck : isTest() ? true : false,\n\t\trunInBackground: options.advanced?.backgroundTasks?.handler ?? ((p) => {\n\t\t\tp.catch(() => {});\n\t\t}),\n\t\tasync runInBackgroundOrAwait(promise) {\n\t\t\ttry {\n\t\t\t\tif (options.advanced?.backgroundTasks?.handler) {\n\t\t\t\t\tif (promise instanceof Promise) options.advanced.backgroundTasks.handler(promise.catch((e) => {\n\t\t\t\t\t\tlogger.error(\"Failed to run background task:\", e);\n\t\t\t\t\t}));\n\t\t\t\t} else await promise;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error(\"Failed to run background task:\", e);\n\t\t\t}\n\t\t},\n\t\tgetPlugin: getPluginFn,\n\t\thasPlugin: hasPluginFn\n\t};\n\tconst initOrPromise = runPluginInit(ctx);\n\tif (isPromise(initOrPromise)) await initOrPromise;\n\treturn ctx;\n}\n//#endregion\nexport { createAuthContext };\n", "import fs from \"node:fs\";\nimport fsPromises from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { ENV, env, getBooleanEnvVar, getEnvVar, isTest, logger } from \"@better-auth/core/env\";\nimport { betterFetch } from \"@better-fetch/fetch\";\nimport { base64 } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\nimport { createRandomStringGenerator } from \"@better-auth/utils/random\";\n//#region src/detectors/detect-auth-config.ts\nasync function getTelemetryAuthConfig(options, context) {\n\treturn {\n\t\tdatabase: context?.database,\n\t\tadapter: context?.adapter,\n\t\temailVerification: {\n\t\t\tsendVerificationEmail: !!options.emailVerification?.sendVerificationEmail,\n\t\t\tsendOnSignUp: !!options.emailVerification?.sendOnSignUp,\n\t\t\tsendOnSignIn: !!options.emailVerification?.sendOnSignIn,\n\t\t\tautoSignInAfterVerification: !!options.emailVerification?.autoSignInAfterVerification,\n\t\t\texpiresIn: options.emailVerification?.expiresIn,\n\t\t\tbeforeEmailVerification: !!options.emailVerification?.beforeEmailVerification,\n\t\t\tafterEmailVerification: !!options.emailVerification?.afterEmailVerification\n\t\t},\n\t\temailAndPassword: {\n\t\t\tenabled: !!options.emailAndPassword?.enabled,\n\t\t\tdisableSignUp: !!options.emailAndPassword?.disableSignUp,\n\t\t\trequireEmailVerification: !!options.emailAndPassword?.requireEmailVerification,\n\t\t\tmaxPasswordLength: options.emailAndPassword?.maxPasswordLength,\n\t\t\tminPasswordLength: options.emailAndPassword?.minPasswordLength,\n\t\t\tsendResetPassword: !!options.emailAndPassword?.sendResetPassword,\n\t\t\tresetPasswordTokenExpiresIn: options.emailAndPassword?.resetPasswordTokenExpiresIn,\n\t\t\tonPasswordReset: !!options.emailAndPassword?.onPasswordReset,\n\t\t\tpassword: {\n\t\t\t\thash: !!options.emailAndPassword?.password?.hash,\n\t\t\t\tverify: !!options.emailAndPassword?.password?.verify\n\t\t\t},\n\t\t\tautoSignIn: !!options.emailAndPassword?.autoSignIn,\n\t\t\trevokeSessionsOnPasswordReset: !!options.emailAndPassword?.revokeSessionsOnPasswordReset\n\t\t},\n\t\tsocialProviders: await Promise.all(Object.keys(options.socialProviders || {}).map(async (key) => {\n\t\t\tconst p = options.socialProviders?.[key];\n\t\t\tif (!p) return {};\n\t\t\tconst provider = typeof p === \"function\" ? await p() : p;\n\t\t\treturn {\n\t\t\t\tid: key,\n\t\t\t\tmapProfileToUser: !!provider.mapProfileToUser,\n\t\t\t\tdisableDefaultScope: !!provider.disableDefaultScope,\n\t\t\t\tdisableIdTokenSignIn: !!provider.disableIdTokenSignIn,\n\t\t\t\tdisableImplicitSignUp: provider.disableImplicitSignUp,\n\t\t\t\tdisableSignUp: provider.disableSignUp,\n\t\t\t\tgetUserInfo: !!provider.getUserInfo,\n\t\t\t\toverrideUserInfoOnSignIn: !!provider.overrideUserInfoOnSignIn,\n\t\t\t\tprompt: provider.prompt,\n\t\t\t\tverifyIdToken: !!provider.verifyIdToken,\n\t\t\t\tscope: provider.scope,\n\t\t\t\trefreshAccessToken: !!provider.refreshAccessToken\n\t\t\t};\n\t\t})),\n\t\tplugins: options.plugins?.map((p) => p.id.toString()),\n\t\tuser: {\n\t\t\tmodelName: options.user?.modelName,\n\t\t\tfields: options.user?.fields,\n\t\t\tadditionalFields: options.user?.additionalFields,\n\t\t\tchangeEmail: {\n\t\t\t\tenabled: options.user?.changeEmail?.enabled,\n\t\t\t\tsendChangeEmailConfirmation: !!options.user?.changeEmail?.sendChangeEmailConfirmation\n\t\t\t}\n\t\t},\n\t\tverification: {\n\t\t\tmodelName: options.verification?.modelName,\n\t\t\tdisableCleanup: options.verification?.disableCleanup,\n\t\t\tfields: options.verification?.fields\n\t\t},\n\t\tsession: {\n\t\t\tmodelName: options.session?.modelName,\n\t\t\tadditionalFields: options.session?.additionalFields,\n\t\t\tcookieCache: {\n\t\t\t\tenabled: options.session?.cookieCache?.enabled,\n\t\t\t\tmaxAge: options.session?.cookieCache?.maxAge,\n\t\t\t\tstrategy: options.session?.cookieCache?.strategy\n\t\t\t},\n\t\t\tdisableSessionRefresh: options.session?.disableSessionRefresh,\n\t\t\texpiresIn: options.session?.expiresIn,\n\t\t\tfields: options.session?.fields,\n\t\t\tfreshAge: options.session?.freshAge,\n\t\t\tpreserveSessionInDatabase: options.session?.preserveSessionInDatabase,\n\t\t\tstoreSessionInDatabase: options.session?.storeSessionInDatabase,\n\t\t\tupdateAge: options.session?.updateAge\n\t\t},\n\t\taccount: {\n\t\t\tmodelName: options.account?.modelName,\n\t\t\tfields: options.account?.fields,\n\t\t\tencryptOAuthTokens: options.account?.encryptOAuthTokens,\n\t\t\tupdateAccountOnSignIn: options.account?.updateAccountOnSignIn,\n\t\t\taccountLinking: {\n\t\t\t\tenabled: options.account?.accountLinking?.enabled,\n\t\t\t\ttrustedProviders: options.account?.accountLinking?.trustedProviders,\n\t\t\t\tupdateUserInfoOnLink: options.account?.accountLinking?.updateUserInfoOnLink,\n\t\t\t\tallowUnlinkingAll: options.account?.accountLinking?.allowUnlinkingAll\n\t\t\t}\n\t\t},\n\t\thooks: {\n\t\t\tafter: !!options.hooks?.after,\n\t\t\tbefore: !!options.hooks?.before\n\t\t},\n\t\tsecondaryStorage: !!options.secondaryStorage,\n\t\tadvanced: {\n\t\t\tcookiePrefix: !!options.advanced?.cookiePrefix,\n\t\t\tcookies: !!options.advanced?.cookies,\n\t\t\tcrossSubDomainCookies: {\n\t\t\t\tdomain: !!options.advanced?.crossSubDomainCookies?.domain,\n\t\t\t\tenabled: options.advanced?.crossSubDomainCookies?.enabled,\n\t\t\t\tadditionalCookies: options.advanced?.crossSubDomainCookies?.additionalCookies\n\t\t\t},\n\t\t\tdatabase: {\n\t\t\t\tgenerateId: options.advanced?.database?.generateId,\n\t\t\t\tdefaultFindManyLimit: options.advanced?.database?.defaultFindManyLimit\n\t\t\t},\n\t\t\tuseSecureCookies: options.advanced?.useSecureCookies,\n\t\t\tipAddress: {\n\t\t\t\tdisableIpTracking: options.advanced?.ipAddress?.disableIpTracking,\n\t\t\t\tipAddressHeaders: options.advanced?.ipAddress?.ipAddressHeaders\n\t\t\t},\n\t\t\tdisableCSRFCheck: options.advanced?.disableCSRFCheck,\n\t\t\tcookieAttributes: {\n\t\t\t\texpires: options.advanced?.defaultCookieAttributes?.expires,\n\t\t\t\tsecure: options.advanced?.defaultCookieAttributes?.secure,\n\t\t\t\tsameSite: options.advanced?.defaultCookieAttributes?.sameSite,\n\t\t\t\tdomain: !!options.advanced?.defaultCookieAttributes?.domain,\n\t\t\t\tpath: options.advanced?.defaultCookieAttributes?.path,\n\t\t\t\thttpOnly: options.advanced?.defaultCookieAttributes?.httpOnly\n\t\t\t}\n\t\t},\n\t\ttrustedOrigins: options.trustedOrigins?.length,\n\t\trateLimit: {\n\t\t\tstorage: options.rateLimit?.storage,\n\t\t\tmodelName: options.rateLimit?.modelName,\n\t\t\twindow: options.rateLimit?.window,\n\t\t\tcustomStorage: !!options.rateLimit?.customStorage,\n\t\t\tenabled: options.rateLimit?.enabled,\n\t\t\tmax: options.rateLimit?.max\n\t\t},\n\t\tonAPIError: {\n\t\t\terrorURL: options.onAPIError?.errorURL,\n\t\t\tonError: !!options.onAPIError?.onError,\n\t\t\tthrow: options.onAPIError?.throw\n\t\t},\n\t\tlogger: {\n\t\t\tdisabled: options.logger?.disabled,\n\t\t\tlevel: options.logger?.level,\n\t\t\tlog: !!options.logger?.log\n\t\t},\n\t\tdatabaseHooks: {\n\t\t\tuser: {\n\t\t\t\tcreate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.user?.create?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.user?.create?.before\n\t\t\t\t},\n\t\t\t\tupdate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.user?.update?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.user?.update?.before\n\t\t\t\t}\n\t\t\t},\n\t\t\tsession: {\n\t\t\t\tcreate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.session?.create?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.session?.create?.before\n\t\t\t\t},\n\t\t\t\tupdate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.session?.update?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.session?.update?.before\n\t\t\t\t}\n\t\t\t},\n\t\t\taccount: {\n\t\t\t\tcreate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.account?.create?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.account?.create?.before\n\t\t\t\t},\n\t\t\t\tupdate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.account?.update?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.account?.update?.before\n\t\t\t\t}\n\t\t\t},\n\t\t\tverification: {\n\t\t\t\tcreate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.verification?.create?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.verification?.create?.before\n\t\t\t\t},\n\t\t\t\tupdate: {\n\t\t\t\t\tafter: !!options.databaseHooks?.verification?.update?.after,\n\t\t\t\t\tbefore: !!options.databaseHooks?.verification?.update?.before\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/detectors/detect-project-info.ts\nfunction detectPackageManager() {\n\tconst userAgent = env.npm_config_user_agent;\n\tif (!userAgent) return;\n\tconst pmSpec = userAgent.split(\" \")[0];\n\tconst separatorPos = pmSpec.lastIndexOf(\"/\");\n\tconst name = pmSpec.substring(0, separatorPos);\n\treturn {\n\t\tname: name === \"npminstall\" ? \"cnpm\" : name,\n\t\tversion: pmSpec.substring(separatorPos + 1)\n\t};\n}\n//#endregion\n//#region src/detectors/detect-system-info.ts\nfunction isCI() {\n\treturn env.CI !== \"false\" && (\"BUILD_ID\" in env || \"BUILD_NUMBER\" in env || \"CI\" in env || \"CI_APP_ID\" in env || \"CI_BUILD_ID\" in env || \"CI_BUILD_NUMBER\" in env || \"CI_NAME\" in env || \"CONTINUOUS_INTEGRATION\" in env || \"RUN_ID\" in env);\n}\n//#endregion\n//#region src/detectors/detect-runtime.ts\nfunction detectRuntime() {\n\tif (typeof Deno !== \"undefined\") return {\n\t\tname: \"deno\",\n\t\tversion: Deno?.version?.deno ?? null\n\t};\n\tif (typeof Bun !== \"undefined\") return {\n\t\tname: \"bun\",\n\t\tversion: Bun?.version ?? null\n\t};\n\tif (typeof process !== \"undefined\" && process?.versions?.node) return {\n\t\tname: \"node\",\n\t\tversion: process.versions.node ?? null\n\t};\n\treturn {\n\t\tname: \"edge\",\n\t\tversion: null\n\t};\n}\nfunction detectEnvironment() {\n\treturn getEnvVar(\"NODE_ENV\") === \"production\" ? \"production\" : isCI() ? \"ci\" : isTest() ? \"test\" : \"development\";\n}\n//#endregion\n//#region src/utils/hash.ts\nasync function hashToBase64(data) {\n\tconst buffer = await createHash(\"SHA-256\").digest(data);\n\treturn base64.encode(buffer);\n}\n//#endregion\n//#region src/utils/id.ts\nconst generateId = (size) => {\n\treturn createRandomStringGenerator(\"a-z\", \"A-Z\", \"0-9\")(size || 32);\n};\n//#endregion\n//#region src/node.ts\nlet packageJSONCache;\nasync function readRootPackageJson() {\n\tif (packageJSONCache) return packageJSONCache;\n\ttry {\n\t\tconst cwd = process.cwd();\n\t\tif (!cwd) return void 0;\n\t\tconst raw = await fsPromises.readFile(path.join(cwd, \"package.json\"), \"utf-8\");\n\t\tpackageJSONCache = JSON.parse(raw);\n\t\treturn packageJSONCache;\n\t} catch {}\n}\nasync function getPackageVersion(pkg) {\n\tif (packageJSONCache) return packageJSONCache.dependencies?.[pkg] || packageJSONCache.devDependencies?.[pkg] || packageJSONCache.peerDependencies?.[pkg];\n\ttry {\n\t\tconst cwd = process.cwd();\n\t\tif (!cwd) throw new Error(\"no-cwd\");\n\t\tconst pkgJsonPath = path.join(cwd, \"node_modules\", pkg, \"package.json\");\n\t\tconst raw = await fsPromises.readFile(pkgJsonPath, \"utf-8\");\n\t\treturn JSON.parse(raw).version || await getVersionFromLocalPackageJson(pkg) || void 0;\n\t} catch {}\n\treturn getVersionFromLocalPackageJson(pkg);\n}\nasync function getVersionFromLocalPackageJson(pkg) {\n\tconst json = await readRootPackageJson();\n\tif (!json) return void 0;\n\treturn {\n\t\t...json.dependencies,\n\t\t...json.devDependencies,\n\t\t...json.peerDependencies\n\t}[pkg];\n}\nasync function getNameFromLocalPackageJson() {\n\treturn (await readRootPackageJson())?.name;\n}\nasync function detectSystemInfo() {\n\ttry {\n\t\tconst cpus = os.cpus();\n\t\treturn {\n\t\t\tdeploymentVendor: getVendor(),\n\t\t\tsystemPlatform: os.platform(),\n\t\t\tsystemRelease: os.release(),\n\t\t\tsystemArchitecture: os.arch(),\n\t\t\tcpuCount: cpus.length,\n\t\t\tcpuModel: cpus.length ? cpus[0].model : null,\n\t\t\tcpuSpeed: cpus.length ? cpus[0].speed : null,\n\t\t\tmemory: os.totalmem(),\n\t\t\tisWSL: await isWsl(),\n\t\t\tisDocker: await isDocker(),\n\t\t\tisTTY: process.stdout ? process.stdout.isTTY : null\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsystemPlatform: null,\n\t\t\tsystemRelease: null,\n\t\t\tsystemArchitecture: null,\n\t\t\tcpuCount: null,\n\t\t\tcpuModel: null,\n\t\t\tcpuSpeed: null,\n\t\t\tmemory: null,\n\t\t\tisWSL: null,\n\t\t\tisDocker: null,\n\t\t\tisTTY: null\n\t\t};\n\t}\n}\nfunction getVendor() {\n\tconst env = process.env;\n\tconst hasAny = (...keys) => keys.some((k) => Boolean(env[k]));\n\tif (hasAny(\"CF_PAGES\", \"CF_PAGES_URL\", \"CF_ACCOUNT_ID\") || typeof navigator !== \"undefined\" && navigator.userAgent === \"Cloudflare-Workers\") return \"cloudflare\";\n\tif (hasAny(\"VERCEL\", \"VERCEL_URL\", \"VERCEL_ENV\")) return \"vercel\";\n\tif (hasAny(\"NETLIFY\", \"NETLIFY_URL\")) return \"netlify\";\n\tif (hasAny(\"RENDER\", \"RENDER_URL\", \"RENDER_INTERNAL_HOSTNAME\", \"RENDER_SERVICE_ID\")) return \"render\";\n\tif (hasAny(\"AWS_LAMBDA_FUNCTION_NAME\", \"AWS_EXECUTION_ENV\", \"LAMBDA_TASK_ROOT\")) return \"aws\";\n\tif (hasAny(\"GOOGLE_CLOUD_FUNCTION_NAME\", \"GOOGLE_CLOUD_PROJECT\", \"GCP_PROJECT\", \"K_SERVICE\")) return \"gcp\";\n\tif (hasAny(\"AZURE_FUNCTION_NAME\", \"FUNCTIONS_WORKER_RUNTIME\", \"WEBSITE_INSTANCE_ID\", \"WEBSITE_SITE_NAME\")) return \"azure\";\n\tif (hasAny(\"DENO_DEPLOYMENT_ID\", \"DENO_REGION\")) return \"deno-deploy\";\n\tif (hasAny(\"FLY_APP_NAME\", \"FLY_REGION\", \"FLY_ALLOC_ID\")) return \"fly-io\";\n\tif (hasAny(\"RAILWAY_STATIC_URL\", \"RAILWAY_ENVIRONMENT_NAME\")) return \"railway\";\n\tif (hasAny(\"DYNO\", \"HEROKU_APP_NAME\")) return \"heroku\";\n\tif (hasAny(\"DO_DEPLOYMENT_ID\", \"DO_APP_NAME\", \"DIGITALOCEAN\")) return \"digitalocean\";\n\tif (hasAny(\"KOYEB\", \"KOYEB_DEPLOYMENT_ID\", \"KOYEB_APP_NAME\")) return \"koyeb\";\n\treturn null;\n}\nlet isDockerCached;\nasync function hasDockerEnv() {\n\ttry {\n\t\tfs.statSync(\"/.dockerenv\");\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function hasDockerCGroup() {\n\ttry {\n\t\treturn fs.readFileSync(\"/proc/self/cgroup\", \"utf8\").includes(\"docker\");\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function isDocker() {\n\tif (isDockerCached === void 0) isDockerCached = await hasDockerEnv() || await hasDockerCGroup();\n\treturn isDockerCached;\n}\nlet isInsideContainerCached;\nconst hasContainerEnv = async () => {\n\ttry {\n\t\tfs.statSync(\"/run/.containerenv\");\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\nasync function isInsideContainer() {\n\tif (isInsideContainerCached === void 0) isInsideContainerCached = await hasContainerEnv() || await isDocker();\n\treturn isInsideContainerCached;\n}\nasync function isWsl() {\n\ttry {\n\t\tif (process.platform !== \"linux\") return false;\n\t\tif (os.release().toLowerCase().includes(\"microsoft\")) {\n\t\t\tif (await isInsideContainer()) return false;\n\t\t\treturn true;\n\t\t}\n\t\treturn fs.readFileSync(\"/proc/version\", \"utf8\").toLowerCase().includes(\"microsoft\") ? !await isInsideContainer() : false;\n\t} catch {\n\t\treturn false;\n\t}\n}\nlet projectIdCached = null;\nasync function getProjectId(baseUrl) {\n\tif (projectIdCached) return projectIdCached;\n\tconst projectName = await getNameFromLocalPackageJson();\n\tif (projectName) {\n\t\tprojectIdCached = await hashToBase64(baseUrl ? baseUrl + projectName : projectName);\n\t\treturn projectIdCached;\n\t}\n\tif (baseUrl) {\n\t\tprojectIdCached = await hashToBase64(baseUrl);\n\t\treturn projectIdCached;\n\t}\n\tprojectIdCached = generateId(32);\n\treturn projectIdCached;\n}\nasync function detectDatabaseNode() {\n\tfor (const [pkg, name] of Object.entries({\n\t\tpg: \"postgresql\",\n\t\tmysql: \"mysql\",\n\t\tmariadb: \"mariadb\",\n\t\tsqlite3: \"sqlite\",\n\t\t\"better-sqlite3\": \"sqlite\",\n\t\t\"@prisma/client\": \"prisma\",\n\t\tmongoose: \"mongodb\",\n\t\tmongodb: \"mongodb\",\n\t\t\"drizzle-orm\": \"drizzle\"\n\t})) {\n\t\tconst version = await getPackageVersion(pkg);\n\t\tif (version) return {\n\t\t\tname,\n\t\t\tversion\n\t\t};\n\t}\n}\nasync function detectFrameworkNode() {\n\tfor (const [pkg, name] of Object.entries({\n\t\tnext: \"next\",\n\t\tnuxt: \"nuxt\",\n\t\t\"react-router\": \"react-router\",\n\t\tastro: \"astro\",\n\t\t\"@sveltejs/kit\": \"sveltekit\",\n\t\t\"solid-start\": \"solid-start\",\n\t\t\"tanstack-start\": \"tanstack-start\",\n\t\thono: \"hono\",\n\t\texpress: \"express\",\n\t\telysia: \"elysia\",\n\t\texpo: \"expo\"\n\t})) {\n\t\tconst version = await getPackageVersion(pkg);\n\t\tif (version) return {\n\t\t\tname,\n\t\t\tversion\n\t\t};\n\t}\n}\nconst noop = async function noop() {};\nasync function createTelemetry(options, context) {\n\tconst debugEnabled = options.telemetry?.debug || getBooleanEnvVar(\"BETTER_AUTH_TELEMETRY_DEBUG\", false);\n\tconst telemetryEndpoint = ENV.BETTER_AUTH_TELEMETRY_ENDPOINT;\n\tif (!telemetryEndpoint && !context?.customTrack) return { publish: noop };\n\tconst track = async (event) => {\n\t\tif (context?.customTrack) await context.customTrack(event).catch(logger.error);\n\t\telse if (telemetryEndpoint) if (debugEnabled) logger.info(\"telemetry event\", JSON.stringify(event, null, 2));\n\t\telse await betterFetch(telemetryEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: event\n\t\t}).catch(logger.error);\n\t};\n\tconst isEnabled = async () => {\n\t\tconst telemetryEnabled = options.telemetry?.enabled !== void 0 ? options.telemetry.enabled : false;\n\t\treturn (getBooleanEnvVar(\"BETTER_AUTH_TELEMETRY\", false) || telemetryEnabled) && (context?.skipTestCheck || !isTest());\n\t};\n\tconst enabled = await isEnabled();\n\tlet anonymousId;\n\tif (enabled) {\n\t\tanonymousId = await getProjectId(typeof options.baseURL === \"string\" ? options.baseURL : void 0);\n\t\ttrack({\n\t\t\ttype: \"init\",\n\t\t\tpayload: {\n\t\t\t\tconfig: await getTelemetryAuthConfig(options, context),\n\t\t\t\truntime: detectRuntime(),\n\t\t\t\tdatabase: await detectDatabaseNode(),\n\t\t\t\tframework: await detectFrameworkNode(),\n\t\t\t\tenvironment: detectEnvironment(),\n\t\t\t\tsystemInfo: await detectSystemInfo(),\n\t\t\t\tpackageManager: detectPackageManager()\n\t\t\t},\n\t\t\tanonymousId\n\t\t});\n\t}\n\treturn { publish: async (event) => {\n\t\tif (!enabled) return;\n\t\tif (!anonymousId) anonymousId = await getProjectId(typeof options.baseURL === \"string\" ? options.baseURL : void 0);\n\t\tawait track({\n\t\t\ttype: event.type,\n\t\t\tpayload: event.payload,\n\t\t\tanonymousId\n\t\t});\n\t} };\n}\n//#endregion\nexport { createTelemetry, getTelemetryAuthConfig };\n", "import { getAdapter } from \"../db/adapter-kysely.mjs\";\nimport { getMigrations } from \"../db/get-migration.mjs\";\nimport { createAuthContext } from \"./create-context.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { getKyselyDatabaseType } from \"@better-auth/kysely-adapter\";\n//#region src/context/init.ts\nconst init = async (options) => {\n\tconst adapter = await getAdapter(options);\n\tconst getDatabaseType = (database) => getKyselyDatabaseType(database) || \"unknown\";\n\tconst ctx = await createAuthContext(adapter, options, getDatabaseType);\n\tctx.runMigrations = async function() {\n\t\tif (!options.database || \"updateMany\" in options.database) throw new BetterAuthError(\"Database is not provided or it's an adapter. Migrations are only supported with a database instance.\");\n\t\tconst { runMigrations } = await getMigrations(options);\n\t\tawait runMigrations();\n\t};\n\treturn ctx;\n};\n//#endregion\nexport { init };\n", "import { getBaseURL, getOrigin, isDynamicBaseURLConfig, resolveBaseURL } from \"../utils/url.mjs\";\nimport { getTrustedOrigins, getTrustedProviders } from \"../context/helpers.mjs\";\nimport { createCookieGetter, getCookies } from \"../cookies/index.mjs\";\nimport { getEndpoints, router } from \"../api/index.mjs\";\nimport { runWithAdapter } from \"@better-auth/core/context\";\nimport { BASE_ERROR_CODES, BetterAuthError } from \"@better-auth/core/error\";\n//#region src/auth/base.ts\nconst createBetterAuth = (options, initFn) => {\n\tconst authContext = initFn(options);\n\tconst { api } = getEndpoints(authContext, options);\n\treturn {\n\t\thandler: async (request) => {\n\t\t\tconst ctx = await authContext;\n\t\t\tconst basePath = ctx.options.basePath || \"/api/auth\";\n\t\t\tlet handlerCtx;\n\t\t\tif (isDynamicBaseURLConfig(options.baseURL)) {\n\t\t\t\thandlerCtx = Object.create(Object.getPrototypeOf(ctx), Object.getOwnPropertyDescriptors(ctx));\n\t\t\t\tconst baseURL = resolveBaseURL(options.baseURL, basePath, request);\n\t\t\t\tif (baseURL) {\n\t\t\t\t\thandlerCtx.baseURL = baseURL;\n\t\t\t\t\thandlerCtx.options = {\n\t\t\t\t\t\t...ctx.options,\n\t\t\t\t\t\tbaseURL: getOrigin(baseURL) || void 0\n\t\t\t\t\t};\n\t\t\t\t} else throw new BetterAuthError(\"Could not resolve base URL from request. Check your allowedHosts config.\");\n\t\t\t\tconst trustedOriginOptions = {\n\t\t\t\t\t...handlerCtx.options,\n\t\t\t\t\tbaseURL: options.baseURL\n\t\t\t\t};\n\t\t\t\thandlerCtx.trustedOrigins = await getTrustedOrigins(trustedOriginOptions, request);\n\t\t\t\tif (options.advanced?.crossSubDomainCookies?.enabled) {\n\t\t\t\t\thandlerCtx.authCookies = getCookies(handlerCtx.options);\n\t\t\t\t\thandlerCtx.createAuthCookie = createCookieGetter(handlerCtx.options);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thandlerCtx = ctx;\n\t\t\t\tif (!ctx.options.baseURL) {\n\t\t\t\t\tconst baseURL = getBaseURL(void 0, basePath, request, void 0, ctx.options.advanced?.trustedProxyHeaders);\n\t\t\t\t\tif (baseURL) {\n\t\t\t\t\t\tctx.baseURL = baseURL;\n\t\t\t\t\t\tctx.options.baseURL = getOrigin(ctx.baseURL) || void 0;\n\t\t\t\t\t} else throw new BetterAuthError(\"Could not get base URL from request. Please provide a valid base URL.\");\n\t\t\t\t}\n\t\t\t\thandlerCtx.trustedOrigins = await getTrustedOrigins(ctx.options, request);\n\t\t\t}\n\t\t\thandlerCtx.trustedProviders = await getTrustedProviders(handlerCtx.options, request);\n\t\t\tconst { handler } = router(handlerCtx, options);\n\t\t\treturn runWithAdapter(handlerCtx.adapter, () => handler(request));\n\t\t},\n\t\tapi,\n\t\toptions,\n\t\t$context: authContext,\n\t\t$ERROR_CODES: {\n\t\t\t...options.plugins?.reduce((acc, plugin) => {\n\t\t\t\tif (plugin.$ERROR_CODES) return {\n\t\t\t\t\t...acc,\n\t\t\t\t\t...plugin.$ERROR_CODES\n\t\t\t\t};\n\t\t\t\treturn acc;\n\t\t\t}, {}),\n\t\t\t...BASE_ERROR_CODES\n\t\t}\n\t};\n};\n//#endregion\nexport { createBetterAuth };\n", "import { init } from \"../context/init.mjs\";\nimport { createBetterAuth } from \"./base.mjs\";\n//#region src/auth/full.ts\n/**\n* Better Auth initializer for full mode (with Kysely)\n*\n* @example\n* ```ts\n* import { betterAuth } from \"better-auth\";\n*\n* const auth = betterAuth({\n* \tdatabase: new PostgresDialect({ connection: process.env.DATABASE_URL }),\n* });\n* ```\n*\n* For minimal mode (without Kysely), import from `better-auth/minimal` instead\n* @example\n* ```ts\n* import { betterAuth } from \"better-auth/minimal\";\n*\n* const auth = betterAuth({\n*\t database: drizzleAdapter(db, { provider: \"pg\" }),\n* });\n*/\nconst betterAuth = (options) => {\n\treturn createBetterAuth(options, init);\n};\n//#endregion\nexport { betterAuth };\n", "import { getBaseURL, getHost, getHostFromRequest, getOrigin, getProtocol, getProtocolFromRequest, isDynamicBaseURLConfig, matchesHostPattern, resolveBaseURL, resolveDynamicBaseURL } from \"./utils/url.mjs\";\nimport { generateGenericState, parseGenericState } from \"./state.mjs\";\nimport { generateState, parseState } from \"./oauth2/state.mjs\";\nimport { HIDE_METADATA } from \"./utils/hide-metadata.mjs\";\nimport { APIError } from \"./api/index.mjs\";\nimport { betterAuth } from \"./auth/full.mjs\";\nimport { getCurrentAdapter } from \"@better-auth/core/context\";\nimport { createTelemetry, getTelemetryAuthConfig } from \"@better-auth/telemetry\";\nexport * from \"@better-auth/core\";\nexport * from \"@better-auth/core/db\";\nexport * from \"@better-auth/core/env\";\nexport * from \"@better-auth/core/error\";\nexport * from \"@better-auth/core/oauth2\";\nexport * from \"@better-auth/core/utils/error-codes\";\nexport * from \"@better-auth/core/utils/id\";\nexport * from \"@better-auth/core/utils/json\";\nexport { APIError, HIDE_METADATA, betterAuth, createTelemetry, generateGenericState, generateState, getBaseURL, getCurrentAdapter, getHost, getHostFromRequest, getOrigin, getProtocol, getProtocolFromRequest, getTelemetryAuthConfig, isDynamicBaseURLConfig, matchesHostPattern, parseGenericState, parseState, resolveBaseURL, resolveDynamicBaseURL };\n", "//#region src/client/parser.ts\nconst PROTO_POLLUTION_PATTERNS = {\n\tproto: /\"(?:_|\\\\u0{2}5[Ff]){2}(?:p|\\\\u0{2}70)(?:r|\\\\u0{2}72)(?:o|\\\\u0{2}6[Ff])(?:t|\\\\u0{2}74)(?:o|\\\\u0{2}6[Ff])(?:_|\\\\u0{2}5[Ff]){2}\"\\s*:/,\n\tconstructor: /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/,\n\tprotoShort: /\"__proto__\"\\s*:/,\n\tconstructorShort: /\"constructor\"\\s*:/\n};\nconst JSON_SIGNATURE = /^\\s*[\"[{]|^\\s*-?\\d{1,16}(\\.\\d{1,17})?([Ee][+-]?\\d+)?\\s*$/;\nconst SPECIAL_VALUES = {\n\ttrue: true,\n\tfalse: false,\n\tnull: null,\n\tundefined: void 0,\n\tnan: NaN,\n\tinfinity: Number.POSITIVE_INFINITY,\n\t\"-infinity\": Number.NEGATIVE_INFINITY\n};\nconst ISO_DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,7}))?(?:Z|([+-])(\\d{2}):(\\d{2}))$/;\nfunction isValidDate(date) {\n\treturn date instanceof Date && !isNaN(date.getTime());\n}\nfunction parseISODate(value) {\n\tconst match = ISO_DATE_REGEX.exec(value);\n\tif (!match) return null;\n\tconst [, year, month, day, hour, minute, second, ms, offsetSign, offsetHour, offsetMinute] = match;\n\tconst date = new Date(Date.UTC(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10), parseInt(hour, 10), parseInt(minute, 10), parseInt(second, 10), ms ? parseInt(ms.padEnd(3, \"0\"), 10) : 0));\n\tif (offsetSign) {\n\t\tconst offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === \"+\" ? -1 : 1);\n\t\tdate.setUTCMinutes(date.getUTCMinutes() + offset);\n\t}\n\treturn isValidDate(date) ? date : null;\n}\nfunction betterJSONParse(value, options = {}) {\n\tconst { strict = false, warnings = false, reviver, parseDates = true } = options;\n\tif (typeof value !== \"string\") return value;\n\tconst trimmed = value.trim();\n\tif (trimmed.length > 0 && trimmed[0] === \"\\\"\" && trimmed.endsWith(\"\\\"\") && !trimmed.slice(1, -1).includes(\"\\\"\")) return trimmed.slice(1, -1);\n\tconst lowerValue = trimmed.toLowerCase();\n\tif (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) return SPECIAL_VALUES[lowerValue];\n\tif (!JSON_SIGNATURE.test(trimmed)) {\n\t\tif (strict) throw new SyntaxError(\"[better-json] Invalid JSON\");\n\t\treturn value;\n\t}\n\tif (Object.entries(PROTO_POLLUTION_PATTERNS).some(([key, pattern]) => {\n\t\tconst matches = pattern.test(trimmed);\n\t\tif (matches && warnings) console.warn(`[better-json] Detected potential prototype pollution attempt using ${key} pattern`);\n\t\treturn matches;\n\t}) && strict) throw new Error(\"[better-json] Potential prototype pollution attempt detected\");\n\ttry {\n\t\tconst secureReviver = (key, value) => {\n\t\t\tif (key === \"__proto__\" || key === \"constructor\" && value && typeof value === \"object\" && \"prototype\" in value) {\n\t\t\t\tif (warnings) console.warn(`[better-json] Dropping \"${key}\" key to prevent prototype pollution`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parseDates && typeof value === \"string\") {\n\t\t\t\tconst date = parseISODate(value);\n\t\t\t\tif (date) return date;\n\t\t\t}\n\t\t\treturn reviver ? reviver(key, value) : value;\n\t\t};\n\t\treturn JSON.parse(trimmed, secureReviver);\n\t} catch (error) {\n\t\tif (strict) throw error;\n\t\treturn value;\n\t}\n}\nfunction parseJSON(value, options = { strict: true }) {\n\treturn betterJSONParse(value, options);\n}\n//#endregion\nexport { parseJSON };\n", "import { getDate } from \"../../utils/date.mjs\";\nimport { parseJSON } from \"../../client/parser.mjs\";\nimport { getCurrentAdapter } from \"@better-auth/core/context\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { filterOutputFields } from \"@better-auth/core/utils/db\";\n//#region src/plugins/organization/adapter.ts\nconst getOrgAdapter = (context, options) => {\n\tconst baseAdapter = context.adapter;\n\tconst orgAdditionalFields = options?.schema?.organization?.additionalFields;\n\tconst memberAdditionalFields = options?.schema?.member?.additionalFields;\n\tconst invitationAdditionalFields = options?.schema?.invitation?.additionalFields;\n\tconst teamAdditionalFields = options?.schema?.team?.additionalFields;\n\treturn {\n\t\tfindOrganizationBySlug: async (slug) => {\n\t\t\treturn filterOutputFields(await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"slug\",\n\t\t\t\t\tvalue: slug\n\t\t\t\t}]\n\t\t\t}), orgAdditionalFields);\n\t\t},\n\t\tcreateOrganization: async (data) => {\n\t\t\tconst organization = await (await getCurrentAdapter(baseAdapter)).create({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\tdata: {\n\t\t\t\t\t...data.organization,\n\t\t\t\t\tmetadata: data.organization.metadata ? JSON.stringify(data.organization.metadata) : void 0\n\t\t\t\t},\n\t\t\t\tforceAllowId: true\n\t\t\t});\n\t\t\treturn filterOutputFields({\n\t\t\t\t...organization,\n\t\t\t\tmetadata: organization.metadata && typeof organization.metadata === \"string\" ? JSON.parse(organization.metadata) : void 0\n\t\t\t}, orgAdditionalFields);\n\t\t},\n\t\tfindMemberByEmail: async (data) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst user = await adapter.findOne({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"email\",\n\t\t\t\t\tvalue: data.email.toLowerCase()\n\t\t\t\t}]\n\t\t\t});\n\t\t\tif (!user) return null;\n\t\t\tconst member = await adapter.findOne({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: user.id\n\t\t\t\t}]\n\t\t\t});\n\t\t\tif (!member) return null;\n\t\t\treturn {\n\t\t\t\t...member,\n\t\t\t\tuser: {\n\t\t\t\t\tid: user.id,\n\t\t\t\t\tname: user.name,\n\t\t\t\t\temail: user.email,\n\t\t\t\t\timage: user.image\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tlistMembers: async (data) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst members = await Promise.all([adapter.findMany({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}, ...data.filter?.field ? [{\n\t\t\t\t\tfield: data.filter?.field,\n\t\t\t\t\tvalue: data.filter?.value,\n\t\t\t\t\t...data.filter.operator ? { operator: data.filter.operator } : {}\n\t\t\t\t}] : []],\n\t\t\t\tlimit: data.limit || (typeof options?.membershipLimit === \"number\" ? options.membershipLimit : 100) || 100,\n\t\t\t\toffset: data.offset || 0,\n\t\t\t\tsortBy: data.sortBy ? {\n\t\t\t\t\tfield: data.sortBy,\n\t\t\t\t\tdirection: data.sortOrder || \"asc\"\n\t\t\t\t} : void 0\n\t\t\t}), adapter.count({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}, ...data.filter?.field ? [{\n\t\t\t\t\tfield: data.filter?.field,\n\t\t\t\t\tvalue: data.filter?.value,\n\t\t\t\t\t...data.filter.operator ? { operator: data.filter.operator } : {}\n\t\t\t\t}] : []]\n\t\t\t})]);\n\t\t\tconst users = await adapter.findMany({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: members[0].map((member) => member.userId),\n\t\t\t\t\toperator: \"in\"\n\t\t\t\t}]\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tmembers: members[0].map((member) => {\n\t\t\t\t\tconst user = users.find((user) => user.id === member.userId);\n\t\t\t\t\tif (!user) throw new BetterAuthError(\"Unexpected error: User not found for member\");\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...member,\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tid: user.id,\n\t\t\t\t\t\t\tname: user.name,\n\t\t\t\t\t\t\temail: user.email,\n\t\t\t\t\t\t\timage: user.image\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t\ttotal: members[1]\n\t\t\t};\n\t\t},\n\t\tfindMemberByOrgId: async (data) => {\n\t\t\tconst result = await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (!result || !result.user) return null;\n\t\t\tconst { user, ...member } = result;\n\t\t\treturn {\n\t\t\t\t...member,\n\t\t\t\tuser: {\n\t\t\t\t\tid: user.id,\n\t\t\t\t\tname: user.name,\n\t\t\t\t\temail: user.email,\n\t\t\t\t\timage: user.image\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tfindMemberById: async (memberId) => {\n\t\t\tconst result = await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: memberId\n\t\t\t\t}],\n\t\t\t\tjoin: { user: true }\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { user, ...member } = result;\n\t\t\treturn {\n\t\t\t\t...member,\n\t\t\t\tuser: {\n\t\t\t\t\tid: user.id,\n\t\t\t\t\tname: user.name,\n\t\t\t\t\temail: user.email,\n\t\t\t\t\timage: user.image\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tcreateMember: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).create({\n\t\t\t\tmodel: \"member\",\n\t\t\t\tdata: {\n\t\t\t\t\t...data,\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tupdateMember: async (memberId, role) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).update({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: memberId\n\t\t\t\t}],\n\t\t\t\tupdate: { role }\n\t\t\t});\n\t\t},\n\t\tdeleteMember: async ({ memberId, organizationId, userId: _userId }) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tlet userId;\n\t\t\tif (!_userId) {\n\t\t\t\tconst member = await adapter.findOne({\n\t\t\t\t\tmodel: \"member\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\tvalue: memberId\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!member) throw new BetterAuthError(\"Member not found\");\n\t\t\t\tuserId = member.userId;\n\t\t\t} else userId = _userId;\n\t\t\tconst member = await adapter.delete({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: memberId\n\t\t\t\t}]\n\t\t\t});\n\t\t\tif (options?.teams?.enabled) {\n\t\t\t\tconst teams = await adapter.findMany({\n\t\t\t\t\tmodel: \"team\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\t\tvalue: organizationId\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tawait Promise.all(teams.map((team) => adapter.deleteMany({\n\t\t\t\t\tmodel: \"teamMember\",\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\t\tvalue: team.id\n\t\t\t\t\t}, {\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: userId\n\t\t\t\t\t}]\n\t\t\t\t})));\n\t\t\t}\n\t\t\treturn member;\n\t\t},\n\t\tupdateOrganization: async (organizationId, data) => {\n\t\t\tconst organization = await (await getCurrentAdapter(baseAdapter)).update({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}],\n\t\t\t\tupdate: {\n\t\t\t\t\t...data,\n\t\t\t\t\tmetadata: typeof data.metadata === \"object\" ? JSON.stringify(data.metadata) : data.metadata\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (!organization) return null;\n\t\t\treturn filterOutputFields({\n\t\t\t\t...organization,\n\t\t\t\tmetadata: organization.metadata ? parseJSON(organization.metadata) : void 0\n\t\t\t}, orgAdditionalFields);\n\t\t},\n\t\tdeleteOrganization: async (organizationId) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tawait adapter.deleteMany({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t\tawait adapter.deleteMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t\tawait adapter.delete({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t\treturn organizationId;\n\t\t},\n\t\tsetActiveOrganization: async (sessionToken, organizationId, ctx) => {\n\t\t\treturn await context.internalAdapter.updateSession(sessionToken, { activeOrganizationId: organizationId });\n\t\t},\n\t\tfindOrganizationById: async (organizationId) => {\n\t\t\treturn filterOutputFields(await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t}), orgAdditionalFields);\n\t\t},\n\t\tcheckMembership: async ({ userId, organizationId }) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindFullOrganization: async ({ organizationId, isSlug, includeTeams, membersLimit }) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst result = await adapter.findOne({\n\t\t\t\tmodel: \"organization\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: isSlug ? \"slug\" : \"id\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}],\n\t\t\t\tjoin: {\n\t\t\t\t\tinvitation: true,\n\t\t\t\t\tmember: membersLimit ? { limit: membersLimit } : true,\n\t\t\t\t\t...includeTeams ? { team: true } : {}\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { invitation: invitations, member: members, team: teams, ...org } = result;\n\t\t\tconst userIds = members.map((member) => member.userId);\n\t\t\tconst users = userIds.length > 0 ? await adapter.findMany({\n\t\t\t\tmodel: \"user\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: userIds,\n\t\t\t\t\toperator: \"in\"\n\t\t\t\t}],\n\t\t\t\tlimit: (typeof options?.membershipLimit === \"number\" ? options.membershipLimit : 100) || 100\n\t\t\t}) : [];\n\t\t\tconst userMap = new Map(users.map((user) => [user.id, user]));\n\t\t\tconst membersWithUsers = members.map((member) => {\n\t\t\t\tconst user = userMap.get(member.userId);\n\t\t\t\tif (!user) throw new BetterAuthError(\"Unexpected error: User not found for member\");\n\t\t\t\treturn {\n\t\t\t\t\t...filterOutputFields(member, memberAdditionalFields),\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid: user.id,\n\t\t\t\t\t\tname: user.name,\n\t\t\t\t\t\temail: user.email,\n\t\t\t\t\t\timage: user.image\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t});\n\t\t\tconst filteredOrg = filterOutputFields(org, orgAdditionalFields);\n\t\t\tconst filteredInvitations = invitations.map((inv) => filterOutputFields(inv, invitationAdditionalFields));\n\t\t\tconst filteredTeams = teams?.map((team) => filterOutputFields(team, teamAdditionalFields));\n\t\t\treturn {\n\t\t\t\t...filteredOrg,\n\t\t\t\tinvitations: filteredInvitations,\n\t\t\t\tmembers: membersWithUsers,\n\t\t\t\tteams: filteredTeams\n\t\t\t};\n\t\t},\n\t\tlistOrganizations: async (userId) => {\n\t\t\tconst result = await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: userId\n\t\t\t\t}],\n\t\t\t\tjoin: { organization: true }\n\t\t\t});\n\t\t\tif (!result || result.length === 0) return [];\n\t\t\treturn result.map((member) => filterOutputFields(member.organization, orgAdditionalFields));\n\t\t},\n\t\tcreateTeam: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).create({\n\t\t\t\tmodel: \"team\",\n\t\t\t\tdata\n\t\t\t});\n\t\t},\n\t\tfindTeamById: async ({ teamId, organizationId, includeTeamMembers }) => {\n\t\t\tconst result = await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"team\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}, ...organizationId ? [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}] : []],\n\t\t\t\tjoin: { ...includeTeamMembers ? { teamMember: true } : {} }\n\t\t\t});\n\t\t\tif (!result) return null;\n\t\t\tconst { teamMember, ...team } = result;\n\t\t\treturn {\n\t\t\t\t...team,\n\t\t\t\t...includeTeamMembers ? { members: teamMember } : {}\n\t\t\t};\n\t\t},\n\t\tupdateTeam: async (teamId, data) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tif (\"id\" in data) data.id = void 0;\n\t\t\treturn await adapter.update({\n\t\t\t\tmodel: \"team\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}],\n\t\t\t\tupdate: { ...data }\n\t\t\t});\n\t\t},\n\t\tdeleteTeam: async (teamId) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tawait adapter.deleteMany({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t\treturn await adapter.delete({\n\t\t\t\tmodel: \"team\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tlistTeams: async (organizationId) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"team\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tcreateTeamInvitation: async ({ email, role, teamId, organizationId, inviterId, expiresIn = 1e3 * 60 * 60 * 48 }) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst expiresAt = getDate(expiresIn);\n\t\t\treturn await adapter.create({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\tdata: {\n\t\t\t\t\temail,\n\t\t\t\t\trole,\n\t\t\t\t\torganizationId,\n\t\t\t\t\tteamId,\n\t\t\t\t\tinviterId,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\texpiresAt\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tsetActiveTeam: async (sessionToken, teamId, ctx) => {\n\t\t\treturn await context.internalAdapter.updateSession(sessionToken, { activeTeamId: teamId });\n\t\t},\n\t\tlistTeamMembers: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tcountTeamMembers: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).count({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tcountMembers: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).count({\n\t\t\t\tmodel: \"member\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tlistTeamsByUser: async (data) => {\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}],\n\t\t\t\tjoin: { team: true }\n\t\t\t})).map((result) => result.team);\n\t\t},\n\t\tfindTeamMember: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindOrCreateTeamMember: async (data) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst member = await adapter.findOne({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}]\n\t\t\t});\n\t\t\tif (member) return member;\n\t\t\treturn await adapter.create({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\tdata: {\n\t\t\t\t\tteamId: data.teamId,\n\t\t\t\t\tuserId: data.userId,\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tremoveTeamMember: async (data) => {\n\t\t\tawait (await getCurrentAdapter(baseAdapter)).deleteMany({\n\t\t\t\tmodel: \"teamMember\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: data.teamId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\tvalue: data.userId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindInvitationsByTeamId: async (teamId) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"teamId\",\n\t\t\t\t\tvalue: teamId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tlistUserInvitations: async (email) => {\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"email\",\n\t\t\t\t\tvalue: email.toLowerCase()\n\t\t\t\t}],\n\t\t\t\tjoin: { organization: true }\n\t\t\t})).filter(Boolean).map(({ organization, ...inv }) => ({\n\t\t\t\t...inv,\n\t\t\t\torganizationName: organization?.name\n\t\t\t}));\n\t\t},\n\t\tcreateInvitation: async ({ invitation, user }) => {\n\t\t\tconst adapter = await getCurrentAdapter(baseAdapter);\n\t\t\tconst expiresAt = getDate(options?.invitationExpiresIn || 3600 * 48, \"sec\");\n\t\t\treturn await adapter.create({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\tdata: {\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\tinviterId: user.id,\n\t\t\t\t\t...invitation,\n\t\t\t\t\tteamId: invitation.teamIds.length > 0 ? invitation.teamIds.join(\",\") : null\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tfindInvitationById: async (id) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: id\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tfindPendingInvitation: async (data) => {\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [\n\t\t\t\t\t{\n\t\t\t\t\t\tfield: \"email\",\n\t\t\t\t\t\tvalue: data.email.toLowerCase()\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tfield: \"status\",\n\t\t\t\t\t\tvalue: \"pending\"\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})).filter((invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date());\n\t\t},\n\t\tfindPendingInvitations: async (data) => {\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"status\",\n\t\t\t\t\tvalue: \"pending\"\n\t\t\t\t}]\n\t\t\t})).filter((invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date());\n\t\t},\n\t\tlistInvitations: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: data.organizationId\n\t\t\t\t}]\n\t\t\t});\n\t\t},\n\t\tupdateInvitation: async (data) => {\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).update({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: data.invitationId\n\t\t\t\t}],\n\t\t\t\tupdate: { status: data.status }\n\t\t\t});\n\t\t}\n\t};\n};\n//#endregion\nexport { getOrgAdapter };\n", "import { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/plugins/access/access.ts\nfunction role(statements) {\n\treturn {\n\t\tauthorize(request, connector = \"AND\") {\n\t\t\tlet success = false;\n\t\t\tfor (const [requestedResource, requestedActions] of Object.entries(request)) {\n\t\t\t\tconst allowedActions = statements[requestedResource];\n\t\t\t\tif (!allowedActions) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: `You are not allowed to access resource: ${requestedResource}`\n\t\t\t\t};\n\t\t\t\tif (Array.isArray(requestedActions)) success = requestedActions.every((requestedAction) => allowedActions.includes(requestedAction));\n\t\t\t\telse if (typeof requestedActions === \"object\") {\n\t\t\t\t\tconst actions = requestedActions;\n\t\t\t\t\tif (actions.connector === \"OR\") success = actions.actions.some((requestedAction) => allowedActions.includes(requestedAction));\n\t\t\t\t\telse success = actions.actions.every((requestedAction) => allowedActions.includes(requestedAction));\n\t\t\t\t} else throw new BetterAuthError(\"Invalid access control request\");\n\t\t\t\tif (success && connector === \"OR\") return { success };\n\t\t\t\tif (!success && connector === \"AND\") return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: `unauthorized to access resource \"${requestedResource}\"`\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (success) return { success };\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: \"Not authorized\"\n\t\t\t};\n\t\t},\n\t\tstatements\n\t};\n}\nfunction createAccessControl(s) {\n\treturn {\n\t\tnewRole(statements) {\n\t\t\treturn role(statements);\n\t\t},\n\t\tstatements: s\n\t};\n}\n//#endregion\nexport { createAccessControl, role };\n", "import { createAccessControl } from \"../../access/access.mjs\";\n//#region src/plugins/organization/access/statement.ts\nconst defaultStatements = {\n\torganization: [\"update\", \"delete\"],\n\tmember: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tinvitation: [\"create\", \"cancel\"],\n\tteam: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tac: [\n\t\t\"create\",\n\t\t\"read\",\n\t\t\"update\",\n\t\t\"delete\"\n\t]\n};\nconst defaultAc = createAccessControl(defaultStatements);\nconst adminAc = defaultAc.newRole({\n\torganization: [\"update\"],\n\tinvitation: [\"create\", \"cancel\"],\n\tmember: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tteam: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tac: [\n\t\t\"create\",\n\t\t\"read\",\n\t\t\"update\",\n\t\t\"delete\"\n\t]\n});\nconst ownerAc = defaultAc.newRole({\n\torganization: [\"update\", \"delete\"],\n\tmember: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tinvitation: [\"create\", \"cancel\"],\n\tteam: [\n\t\t\"create\",\n\t\t\"update\",\n\t\t\"delete\"\n\t],\n\tac: [\n\t\t\"create\",\n\t\t\"read\",\n\t\t\"update\",\n\t\t\"delete\"\n\t]\n});\nconst memberAc = defaultAc.newRole({\n\torganization: [],\n\tmember: [],\n\tinvitation: [],\n\tteam: [],\n\tac: [\"read\"]\n});\nconst defaultRoles = {\n\tadmin: adminAc,\n\towner: ownerAc,\n\tmember: memberAc\n};\n//#endregion\nexport { adminAc, defaultAc, defaultRoles, defaultStatements, memberAc, ownerAc };\n", "//#region src/plugins/organization/permission.ts\nconst hasPermissionFn = (input, acRoles) => {\n\tif (!input.permissions) return false;\n\tconst roles = input.role.split(\",\");\n\tconst creatorRole = input.options.creatorRole || \"owner\";\n\tconst isCreator = roles.includes(creatorRole);\n\tconst allowCreatorsAllPermissions = input.allowCreatorAllPermissions || false;\n\tif (isCreator && allowCreatorsAllPermissions) return true;\n\tfor (const role of roles) if ((acRoles[role]?.authorize(input.permissions))?.success) return true;\n\treturn false;\n};\nconst cacheAllRoles = /* @__PURE__ */ new Map();\n//#endregion\nexport { cacheAllRoles, hasPermissionFn };\n", "import { APIError } from \"../../api/index.mjs\";\nimport { defaultRoles } from \"./access/statement.mjs\";\nimport { cacheAllRoles, hasPermissionFn } from \"./permission.mjs\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/has-permission.ts\nconst hasPermission = async (input, ctx) => {\n\tlet acRoles = { ...input.options.roles || defaultRoles };\n\tif (ctx && input.organizationId && input.options.dynamicAccessControl?.enabled && input.options.ac && !input.useMemoryCache) {\n\t\tconst roles = await ctx.context.adapter.findMany({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: input.organizationId\n\t\t\t}]\n\t\t});\n\t\tfor (const { role, permission: permissionsString } of roles) {\n\t\t\tconst result = z.record(z.string(), z.array(z.string())).safeParse(JSON.parse(permissionsString));\n\t\t\tif (!result.success) {\n\t\t\t\tctx.context.logger.error(\"[hasPermission] Invalid permissions for role \" + role, { permissions: JSON.parse(permissionsString) });\n\t\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", { message: \"Invalid permissions for role \" + role });\n\t\t\t}\n\t\t\tconst merged = { ...acRoles[role]?.statements };\n\t\t\tfor (const [key, actions] of Object.entries(result.data)) merged[key] = [...new Set([...merged[key] ?? [], ...actions])];\n\t\t\tacRoles[role] = input.options.ac.newRole(merged);\n\t\t}\n\t}\n\tif (input.useMemoryCache) acRoles = cacheAllRoles.get(input.organizationId) || acRoles;\n\tcacheAllRoles.set(input.organizationId, acRoles);\n\treturn hasPermissionFn(input, acRoles);\n};\n//#endregion\nexport { hasPermission };\n", "//#region package.json\nvar version = \"1.6.2\";\n//#endregion\nexport { version };\n", "import { version } from \"./package.mjs\";\n//#region src/version.ts\nconst PACKAGE_VERSION = version;\n//#endregion\nexport { PACKAGE_VERSION };\n", "import { defineErrorCodes } from \"@better-auth/core/utils/error-codes\";\n//#region src/plugins/organization/error-codes.ts\nconst ORGANIZATION_ERROR_CODES = defineErrorCodes({\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION: \"You are not allowed to create a new organization\",\n\tYOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS: \"You have reached the maximum number of organizations\",\n\tORGANIZATION_ALREADY_EXISTS: \"Organization already exists\",\n\tORGANIZATION_SLUG_ALREADY_TAKEN: \"Organization slug already taken\",\n\tORGANIZATION_NOT_FOUND: \"Organization not found\",\n\tUSER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION: \"User is not a member of the organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION: \"You are not allowed to update this organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION: \"You are not allowed to delete this organization\",\n\tNO_ACTIVE_ORGANIZATION: \"No active organization\",\n\tUSER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION: \"User is already a member of this organization\",\n\tMEMBER_NOT_FOUND: \"Member not found\",\n\tROLE_NOT_FOUND: \"Role not found\",\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM: \"You are not allowed to create a new team\",\n\tTEAM_ALREADY_EXISTS: \"Team already exists\",\n\tTEAM_NOT_FOUND: \"Team not found\",\n\tYOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER: \"You cannot leave the organization as the only owner\",\n\tYOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER: \"You cannot leave the organization without an owner\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER: \"You are not allowed to delete this member\",\n\tYOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION: \"You are not allowed to invite users to this organization\",\n\tUSER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION: \"User is already invited to this organization\",\n\tINVITATION_NOT_FOUND: \"Invitation not found\",\n\tYOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION: \"You are not the recipient of the invitation\",\n\tEMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION: \"Email verification required before accepting or rejecting invitation\",\n\tYOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION: \"You are not allowed to cancel this invitation\",\n\tINVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION: \"Inviter is no longer a member of the organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE: \"You are not allowed to invite a user with this role\",\n\tFAILED_TO_RETRIEVE_INVITATION: \"Failed to retrieve invitation\",\n\tYOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS: \"You have reached the maximum number of teams\",\n\tUNABLE_TO_REMOVE_LAST_TEAM: \"Unable to remove last team\",\n\tYOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER: \"You are not allowed to update this member\",\n\tORGANIZATION_MEMBERSHIP_LIMIT_REACHED: \"Organization membership limit reached\",\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION: \"You are not allowed to create teams in this organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION: \"You are not allowed to delete teams in this organization\",\n\tYOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM: \"You are not allowed to update this team\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM: \"You are not allowed to delete this team\",\n\tINVITATION_LIMIT_REACHED: \"Invitation limit reached\",\n\tTEAM_MEMBER_LIMIT_REACHED: \"Team member limit reached\",\n\tUSER_IS_NOT_A_MEMBER_OF_THE_TEAM: \"User is not a member of the team\",\n\tYOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM: \"You are not allowed to list the members of this team\",\n\tYOU_DO_NOT_HAVE_AN_ACTIVE_TEAM: \"You do not have an active team\",\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER: \"You are not allowed to create a new member\",\n\tYOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER: \"You are not allowed to remove a team member\",\n\tYOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION: \"You are not allowed to access this organization as an owner\",\n\tYOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION: \"You are not a member of this organization\",\n\tMISSING_AC_INSTANCE: \"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information\",\n\tYOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE: \"You must be in an organization to create a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE: \"You are not allowed to create a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE: \"You are not allowed to update a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE: \"You are not allowed to delete a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE: \"You are not allowed to read a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE: \"You are not allowed to list a role\",\n\tYOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE: \"You are not allowed to get a role\",\n\tTOO_MANY_ROLES: \"This organization has too many roles\",\n\tINVALID_RESOURCE: \"The provided permission includes an invalid resource\",\n\tROLE_NAME_IS_ALREADY_TAKEN: \"That role name is already taken\",\n\tCANNOT_DELETE_A_PRE_DEFINED_ROLE: \"Cannot delete a pre-defined role\",\n\tROLE_IS_ASSIGNED_TO_MEMBERS: \"Cannot delete a role that is assigned to members. Please reassign the members to a different role first\"\n});\n//#endregion\nexport { ORGANIZATION_ERROR_CODES };\n", "//#region src/utils/shim.ts\nconst shimContext = (originalObject, newContext) => {\n\tconst shimmedObj = {};\n\tfor (const [key, value] of Object.entries(originalObject)) {\n\t\tshimmedObj[key] = (ctx) => {\n\t\t\treturn value({\n\t\t\t\t...ctx,\n\t\t\t\tcontext: {\n\t\t\t\t\t...newContext,\n\t\t\t\t\t...ctx.context\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t\tshimmedObj[key].path = value.path;\n\t\tshimmedObj[key].method = value.method;\n\t\tshimmedObj[key].options = value.options;\n\t\tshimmedObj[key].headers = value.headers;\n\t}\n\treturn shimmedObj;\n};\n//#endregion\nexport { shimContext };\n", "import { sessionMiddleware } from \"../../api/routes/session.mjs\";\nimport { createAuthMiddleware } from \"@better-auth/core/api\";\n//#region src/plugins/organization/call.ts\nconst orgMiddleware = createAuthMiddleware(async () => {\n\treturn {};\n});\n/**\n* The middleware forces the endpoint to require a valid session by utilizing the `sessionMiddleware`.\n* It also appends additional types to the session type regarding organizations.\n*/\nconst orgSessionMiddleware = createAuthMiddleware({ use: [sessionMiddleware] }, async (ctx) => {\n\treturn { session: ctx.context.session };\n});\n//#endregion\nexport { orgMiddleware, orgSessionMiddleware };\n", "import * as z from \"zod\";\n//#region src/db/to-zod.ts\nfunction toZodSchema({ fields, isClientSide }) {\n\tconst zodFields = Object.keys(fields).reduce((acc, key) => {\n\t\tconst field = fields[key];\n\t\tif (!field) return acc;\n\t\tif (isClientSide && field.input === false) return acc;\n\t\tlet schema;\n\t\tif (field.type === \"json\") schema = z.json ? z.json() : z.any();\n\t\telse if (field.type === \"string[]\" || field.type === \"number[]\") schema = z.array(field.type === \"string[]\" ? z.string() : z.number());\n\t\telse if (Array.isArray(field.type)) schema = z.any();\n\t\telse schema = z[field.type]();\n\t\tif (field?.required === false) schema = schema.optional();\n\t\tif (!isClientSide && field?.returned === false) return acc;\n\t\treturn {\n\t\t\t...acc,\n\t\t\t[key]: schema\n\t\t};\n\t}, {});\n\treturn z.object(zodFields);\n}\n//#endregion\nexport { toZodSchema };\n", "import { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-access-control.ts\nconst normalizeRoleName = (role) => role.toLowerCase();\nconst DEFAULT_MAXIMUM_ROLES_PER_ORGANIZATION = Number.POSITIVE_INFINITY;\nconst getAdditionalFields = (options, shouldBePartial = false) => {\n\tconst additionalFields = options?.schema?.organizationRole?.additionalFields || {};\n\tif (shouldBePartial) for (const key in additionalFields) additionalFields[key].required = false;\n\treturn {\n\t\tadditionalFieldsSchema: toZodSchema({\n\t\t\tfields: additionalFields,\n\t\t\tisClientSide: true\n\t\t}),\n\t\t$AdditionalFields: {},\n\t\t$ReturnAdditionalFields: {}\n\t};\n};\nconst baseCreateOrgRoleSchema = z.object({\n\torganizationId: z.string().optional().meta({ description: \"The id of the organization to create the role in. If not provided, the user's active organization will be used.\" }),\n\trole: z.string().meta({ description: \"The name of the role to create\" }),\n\tpermission: z.record(z.string(), z.array(z.string())).meta({ description: \"The permission to assign to the role\" })\n});\nconst createOrgRole = (options) => {\n\tconst { additionalFieldsSchema, $AdditionalFields, $ReturnAdditionalFields } = getAdditionalFields(options, false);\n\treturn createAuthEndpoint(\"/organization/create-role\", {\n\t\tmethod: \"POST\",\n\t\tbody: baseCreateOrgRoleSchema.safeExtend({ additionalFields: z.object({ ...additionalFieldsSchema.shape }).optional() }),\n\t\tmetadata: { $Infer: { body: {} } },\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware]\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tlet roleName = ctx.body.role;\n\t\tconst permission = ctx.body.permission;\n\t\tconst additionalFields = ctx.body.additionalFields;\n\t\tconst ac = options.ac;\n\t\tif (!ac) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.`, `\\nPlease refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`);\n\t\t\tthrow APIError.from(\"NOT_IMPLEMENTED\", ORGANIZATION_ERROR_CODES.MISSING_AC_INSTANCE);\n\t\t}\n\t\tconst organizationId = ctx.body.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to create a role. Either set an active org id, or pass an organizationId in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE);\n\t\t}\n\t\troleName = normalizeRoleName(roleName);\n\t\tawait checkIfRoleNameIsTakenByPreDefinedRole({\n\t\t\trole: roleName,\n\t\t\torganizationId,\n\t\t\toptions,\n\t\t\tctx\n\t\t});\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to create a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { ac: [\"create\"] },\n\t\t\trole: member.role\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to create a role. If this is unexpected, please make sure the role associated to that member has the \"ac\" resource with the \"create\" permission.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId,\n\t\t\t\trole: member.role\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE);\n\t\t}\n\t\tconst maximumRolesPerOrganization = typeof options.dynamicAccessControl?.maximumRolesPerOrganization === \"function\" ? await options.dynamicAccessControl.maximumRolesPerOrganization(organizationId) : options.dynamicAccessControl?.maximumRolesPerOrganization ?? DEFAULT_MAXIMUM_ROLES_PER_ORGANIZATION;\n\t\tconst rolesInDB = await ctx.context.adapter.count({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (rolesInDB >= maximumRolesPerOrganization) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] Failed to create a new role, the organization has too many roles. Maximum allowed roles is ${maximumRolesPerOrganization}.`, {\n\t\t\t\torganizationId,\n\t\t\t\tmaximumRolesPerOrganization,\n\t\t\t\trolesInDB\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TOO_MANY_ROLES);\n\t\t}\n\t\tawait checkForInvalidResources({\n\t\t\tac,\n\t\t\tctx,\n\t\t\tpermission\n\t\t});\n\t\tawait checkIfMemberHasPermission({\n\t\t\tctx,\n\t\t\tmember,\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissionRequired: permission,\n\t\t\tuser,\n\t\t\taction: \"create\"\n\t\t});\n\t\tawait checkIfRoleNameIsTakenByRoleInDB({\n\t\t\tctx,\n\t\t\torganizationId,\n\t\t\trole: roleName\n\t\t});\n\t\tconst newRole = ac.newRole(permission);\n\t\tconst data = {\n\t\t\t...await ctx.context.adapter.create({\n\t\t\t\tmodel: \"organizationRole\",\n\t\t\t\tdata: {\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t\t\torganizationId,\n\t\t\t\t\tpermission: JSON.stringify(permission),\n\t\t\t\t\trole: roleName,\n\t\t\t\t\t...additionalFields\n\t\t\t\t}\n\t\t\t}),\n\t\t\tpermission\n\t\t};\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t\troleData: data,\n\t\t\tstatements: newRole.statements\n\t\t});\n\t});\n};\nconst deleteOrgRoleBodySchema = z.object({ organizationId: z.string().optional().meta({ description: \"The id of the organization to create the role in. If not provided, the user's active organization will be used.\" }) }).and(z.union([z.object({ roleName: z.string().nonempty().meta({ description: \"The name of the role to delete\" }) }), z.object({ roleId: z.string().nonempty().meta({ description: \"The id of the role to delete\" }) })]));\nconst deleteOrgRole = (options) => {\n\treturn createAuthEndpoint(\"/organization/delete-role\", {\n\t\tmethod: \"POST\",\n\t\tbody: deleteOrgRoleBodySchema,\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware],\n\t\tmetadata: { $Infer: { body: {} } }\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tconst organizationId = ctx.body.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to delete a role. Either set an active org id, or pass an organizationId in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\t}\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to delete a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { ac: [\"delete\"] },\n\t\t\trole: member.role\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to delete a role. If this is unexpected, please make sure the role associated to that member has the \"ac\" resource with the \"delete\" permission.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId,\n\t\t\t\trole: member.role\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE);\n\t\t}\n\t\tif (ctx.body.roleName) {\n\t\t\tconst roleName = ctx.body.roleName;\n\t\t\tconst defaultRoles = options.roles ? Object.keys(options.roles) : [\n\t\t\t\t\"owner\",\n\t\t\t\t\"admin\",\n\t\t\t\t\"member\"\n\t\t\t];\n\t\t\tif (defaultRoles.includes(roleName)) {\n\t\t\t\tctx.context.logger.error(`[Dynamic Access Control] Cannot delete a pre-defined role.`, {\n\t\t\t\t\troleName,\n\t\t\t\t\torganizationId,\n\t\t\t\t\tdefaultRoles\n\t\t\t\t});\n\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.CANNOT_DELETE_A_PRE_DEFINED_ROLE);\n\t\t\t}\n\t\t}\n\t\tlet condition;\n\t\tif (ctx.body.roleName) condition = {\n\t\t\tfield: \"role\",\n\t\t\tvalue: ctx.body.roleName,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse if (ctx.body.roleId) condition = {\n\t\t\tfield: \"id\",\n\t\t\tvalue: ctx.body.roleId,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\tconst existingRoleInDB = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition]\n\t\t});\n\t\tif (!existingRoleInDB) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, {\n\t\t\t\t...\"roleName\" in ctx.body ? { roleName: ctx.body.roleName } : { roleId: ctx.body.roleId },\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\texistingRoleInDB.permission = JSON.parse(existingRoleInDB.permission);\n\t\tconst roleToDelete = existingRoleInDB.role;\n\t\tif ((await ctx.context.adapter.findMany({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"role\",\n\t\t\t\tvalue: roleToDelete,\n\t\t\t\toperator: \"contains\"\n\t\t\t}]\n\t\t})).find((member) => {\n\t\t\treturn member.role.split(\",\").map((r) => r.trim()).includes(roleToDelete);\n\t\t})) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] Cannot delete a role that is assigned to members.`, {\n\t\t\t\trole: existingRoleInDB.role,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_IS_ASSIGNED_TO_MEMBERS);\n\t\t}\n\t\tawait ctx.context.adapter.delete({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition]\n\t\t});\n\t\treturn ctx.json({ success: true });\n\t});\n};\nconst listOrgRolesQuerySchema = z.object({ organizationId: z.string().optional().meta({ description: \"The id of the organization to list roles for. If not provided, the user's active organization will be used.\" }) }).optional();\nconst listOrgRoles = (options) => {\n\tconst { $ReturnAdditionalFields } = getAdditionalFields(options, false);\n\treturn createAuthEndpoint(\"/organization/list-roles\", {\n\t\tmethod: \"GET\",\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware],\n\t\tquery: listOrgRolesQuerySchema\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tconst organizationId = ctx.query?.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to list roles. Either set an active org id, or pass an organizationId in the request query.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\t}\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to list roles.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { ac: [\"read\"] },\n\t\t\trole: member.role\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to list roles.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId,\n\t\t\t\trole: member.role\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE);\n\t\t}\n\t\tlet roles = await ctx.context.adapter.findMany({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\troles = roles.map((x) => ({\n\t\t\t...x,\n\t\t\tpermission: JSON.parse(x.permission)\n\t\t}));\n\t\treturn ctx.json(roles);\n\t});\n};\nconst getOrgRoleQuerySchema = z.object({ organizationId: z.string().optional().meta({ description: \"The id of the organization to read a role for. If not provided, the user's active organization will be used.\" }) }).and(z.union([z.object({ roleName: z.string().nonempty().meta({ description: \"The name of the role to read\" }) }), z.object({ roleId: z.string().nonempty().meta({ description: \"The id of the role to read\" }) })])).optional();\nconst getOrgRole = (options) => {\n\tconst { $ReturnAdditionalFields } = getAdditionalFields(options, false);\n\treturn createAuthEndpoint(\"/organization/get-role\", {\n\t\tmethod: \"GET\",\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware],\n\t\tquery: getOrgRoleQuerySchema,\n\t\tmetadata: { $Infer: { query: {} } }\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tconst organizationId = ctx.query?.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to read a role. Either set an active org id, or pass an organizationId in the request query.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\t}\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to read a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { ac: [\"read\"] },\n\t\t\trole: member.role\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to read a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId,\n\t\t\t\trole: member.role\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE);\n\t\t}\n\t\tlet condition;\n\t\tif (ctx.query.roleName) condition = {\n\t\t\tfield: \"role\",\n\t\t\tvalue: ctx.query.roleName,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse if (ctx.query.roleId) condition = {\n\t\t\tfield: \"id\",\n\t\t\tvalue: ctx.query.roleId,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request query.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\tconst role = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition]\n\t\t});\n\t\tif (!role) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, {\n\t\t\t\t...\"roleName\" in ctx.query ? { roleName: ctx.query.roleName } : { roleId: ctx.query.roleId },\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\trole.permission = JSON.parse(role.permission);\n\t\treturn ctx.json(role);\n\t});\n};\nconst roleNameOrIdSchema = z.union([z.object({ roleName: z.string().nonempty().meta({ description: \"The name of the role to update\" }) }), z.object({ roleId: z.string().nonempty().meta({ description: \"The id of the role to update\" }) })]);\nconst updateOrgRole = (options) => {\n\tconst { additionalFieldsSchema, $AdditionalFields, $ReturnAdditionalFields } = getAdditionalFields(options, true);\n\treturn createAuthEndpoint(\"/organization/update-role\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\torganizationId: z.string().optional().meta({ description: \"The id of the organization to update the role in. If not provided, the user's active organization will be used.\" }),\n\t\t\tdata: z.object({\n\t\t\t\tpermission: z.record(z.string(), z.array(z.string())).optional().meta({ description: \"The permission to update the role with\" }),\n\t\t\t\troleName: z.string().optional().meta({ description: \"The name of the role to update\" }),\n\t\t\t\t...additionalFieldsSchema.shape\n\t\t\t})\n\t\t}).and(roleNameOrIdSchema),\n\t\tmetadata: { $Infer: { body: {} } },\n\t\trequireHeaders: true,\n\t\tuse: [orgSessionMiddleware]\n\t}, async (ctx) => {\n\t\tconst { session, user } = ctx.context.session;\n\t\tconst ac = options.ac;\n\t\tif (!ac) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The organization plugin is missing a pre-defined ac instance.`, `\\nPlease refer to the documentation here: https://better-auth.com/docs/plugins/organization#dynamic-access-control`);\n\t\t\tthrow APIError.from(\"NOT_IMPLEMENTED\", ORGANIZATION_ERROR_CODES.MISSING_AC_INSTANCE);\n\t\t}\n\t\tconst organizationId = ctx.body.organizationId ?? session.activeOrganizationId;\n\t\tif (!organizationId) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The session is missing an active organization id to update a role. Either set an active org id, or pass an organizationId in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\t}\n\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, {\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: user.id,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}]\n\t\t});\n\t\tif (!member) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not a member of the organization to update a role.`, {\n\t\t\t\tuserId: user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\t}\n\t\tif (!await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\trole: member.role,\n\t\t\tpermissions: { ac: [\"update\"] }\n\t\t}, ctx)) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The user is not permitted to update a role.`);\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE);\n\t\t}\n\t\tlet condition;\n\t\tif (ctx.body.roleName) condition = {\n\t\t\tfield: \"role\",\n\t\t\tvalue: ctx.body.roleName,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse if (ctx.body.roleId) condition = {\n\t\t\tfield: \"id\",\n\t\t\tvalue: ctx.body.roleId,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t};\n\t\telse {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id is not provided in the request body.`);\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\tconst role = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition]\n\t\t});\n\t\tif (!role) {\n\t\t\tctx.context.logger.error(`[Dynamic Access Control] The role name/id does not exist in the database.`, {\n\t\t\t\t...\"roleName\" in ctx.body ? { roleName: ctx.body.roleName } : { roleId: ctx.body.roleId },\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND);\n\t\t}\n\t\trole.permission = role.permission ? JSON.parse(role.permission) : void 0;\n\t\tconst { permission: _, roleName: __, ...additionalFields } = ctx.body.data;\n\t\tconst updateData = { ...additionalFields };\n\t\tif (ctx.body.data.permission) {\n\t\t\tconst newPermission = ctx.body.data.permission;\n\t\t\tawait checkForInvalidResources({\n\t\t\t\tac,\n\t\t\t\tctx,\n\t\t\t\tpermission: newPermission\n\t\t\t});\n\t\t\tawait checkIfMemberHasPermission({\n\t\t\t\tctx,\n\t\t\t\tmember,\n\t\t\t\toptions,\n\t\t\t\torganizationId,\n\t\t\t\tpermissionRequired: newPermission,\n\t\t\t\tuser,\n\t\t\t\taction: \"update\"\n\t\t\t});\n\t\t\tupdateData.permission = newPermission;\n\t\t}\n\t\tif (ctx.body.data.roleName) {\n\t\t\tlet newRoleName = ctx.body.data.roleName;\n\t\t\tnewRoleName = normalizeRoleName(newRoleName);\n\t\t\tawait checkIfRoleNameIsTakenByPreDefinedRole({\n\t\t\t\trole: newRoleName,\n\t\t\t\torganizationId,\n\t\t\t\toptions,\n\t\t\t\tctx\n\t\t\t});\n\t\t\tawait checkIfRoleNameIsTakenByRoleInDB({\n\t\t\t\trole: newRoleName,\n\t\t\t\torganizationId,\n\t\t\t\tctx\n\t\t\t});\n\t\t\tupdateData.role = newRoleName;\n\t\t}\n\t\tconst update = {\n\t\t\t...updateData,\n\t\t\t...updateData.permission ? { permission: JSON.stringify(updateData.permission) } : {}\n\t\t};\n\t\tawait ctx.context.adapter.update({\n\t\t\tmodel: \"organizationRole\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId,\n\t\t\t\toperator: \"eq\",\n\t\t\t\tconnector: \"AND\"\n\t\t\t}, condition],\n\t\t\tupdate\n\t\t});\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t\troleData: {\n\t\t\t\t...role,\n\t\t\t\t...update,\n\t\t\t\tpermission: updateData.permission || role.permission || null\n\t\t\t}\n\t\t});\n\t});\n};\nasync function checkForInvalidResources({ ac, ctx, permission }) {\n\tconst validResources = Object.keys(ac.statements);\n\tconst providedResources = Object.keys(permission);\n\tif (providedResources.some((r) => !validResources.includes(r))) {\n\t\tctx.context.logger.error(`[Dynamic Access Control] The provided permission includes an invalid resource.`, {\n\t\t\tprovidedResources,\n\t\t\tvalidResources\n\t\t});\n\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.INVALID_RESOURCE);\n\t}\n}\nasync function checkIfMemberHasPermission({ ctx, permissionRequired: permission, options, organizationId, member, user, action }) {\n\tconst hasNecessaryPermissions = [];\n\tconst permissionEntries = Object.entries(permission);\n\tfor await (const [resource, permissions] of permissionEntries) for await (const perm of permissions) hasNecessaryPermissions.push({\n\t\tresource: { [resource]: [perm] },\n\t\thasPermission: await hasPermission({\n\t\t\toptions,\n\t\t\torganizationId,\n\t\t\tpermissions: { [resource]: [perm] },\n\t\t\tuseMemoryCache: true,\n\t\t\trole: member.role\n\t\t}, ctx)\n\t});\n\tconst missingPermissions = hasNecessaryPermissions.filter((x) => x.hasPermission === false).map((x) => {\n\t\tconst key = Object.keys(x.resource)[0];\n\t\treturn `${key}:${x.resource[key][0]}`;\n\t});\n\tif (missingPermissions.length > 0) {\n\t\tctx.context.logger.error(`[Dynamic Access Control] The user is missing permissions necessary to ${action} a role with those set of permissions.\\n`, {\n\t\t\tuserId: user.id,\n\t\t\torganizationId,\n\t\t\trole: member.role,\n\t\t\tmissingPermissions\n\t\t});\n\t\tlet error;\n\t\tif (action === \"create\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE;\n\t\telse if (action === \"update\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE;\n\t\telse if (action === \"delete\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE;\n\t\telse if (action === \"read\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE;\n\t\telse if (action === \"list\") error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE;\n\t\telse error = ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE;\n\t\tthrow APIError.fromStatus(\"FORBIDDEN\", {\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code,\n\t\t\tmissingPermissions\n\t\t});\n\t}\n}\nasync function checkIfRoleNameIsTakenByPreDefinedRole({ options, organizationId, role, ctx }) {\n\tconst defaultRoles = options.roles ? Object.keys(options.roles) : [\n\t\t\"owner\",\n\t\t\"admin\",\n\t\t\"member\"\n\t];\n\tif (defaultRoles.includes(role)) {\n\t\tctx.context.logger.error(`[Dynamic Access Control] The role name \"${role}\" is already taken by a pre-defined role.`, {\n\t\t\trole,\n\t\t\torganizationId,\n\t\t\tdefaultRoles\n\t\t});\n\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NAME_IS_ALREADY_TAKEN);\n\t}\n}\nasync function checkIfRoleNameIsTakenByRoleInDB({ organizationId, role, ctx }) {\n\tif (await ctx.context.adapter.findOne({\n\t\tmodel: \"organizationRole\",\n\t\twhere: [{\n\t\t\tfield: \"organizationId\",\n\t\t\tvalue: organizationId,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t}, {\n\t\t\tfield: \"role\",\n\t\t\tvalue: role,\n\t\t\toperator: \"eq\",\n\t\t\tconnector: \"AND\"\n\t\t}]\n\t})) {\n\t\tctx.context.logger.error(`[Dynamic Access Control] The role name \"${role}\" is already taken by a role in the database.`, {\n\t\t\trole,\n\t\t\torganizationId\n\t\t});\n\t\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ROLE_NAME_IS_ALREADY_TAKEN);\n\t}\n}\n//#endregion\nexport { createOrgRole, deleteOrgRole, getOrgRole, listOrgRoles, updateOrgRole };\n", "import { getDate } from \"../../../utils/date.mjs\";\nimport { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { getSessionFromCtx } from \"../../../api/routes/session.mjs\";\nimport { defaultRoles } from \"../access/statement.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { getOrgAdapter } from \"../adapter.mjs\";\nimport { orgMiddleware, orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { parseRoles } from \"../organization.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-invites.ts\nconst baseInvitationSchema = z.object({\n\temail: z.string().meta({ description: \"The email address of the user to invite\" }),\n\trole: z.union([z.string().meta({ description: \"The role to assign to the user\" }), z.array(z.string().meta({ description: \"The roles to assign to the user\" }))]).meta({ description: \"The role(s) to assign to the user. It can be `admin`, `member`, owner. Eg: \\\"member\\\"\" }),\n\torganizationId: z.string().meta({ description: \"The organization ID to invite the user to\" }).optional(),\n\tresend: z.boolean().meta({ description: \"Resend the invitation email, if the user is already invited. Eg: true\" }).optional(),\n\tteamId: z.union([z.string().meta({ description: \"The team ID to invite the user to\" }).optional(), z.array(z.string()).meta({ description: \"The team IDs to invite the user to\" }).optional()])\n});\nconst createInvitation = (option) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: option?.schema?.invitation?.additionalFields || {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/invite-member\", {\n\t\tmethod: \"POST\",\n\t\trequireHeaders: true,\n\t\tuse: [orgMiddleware, orgSessionMiddleware],\n\t\tbody: z.object({\n\t\t\t...baseInvitationSchema.shape,\n\t\t\t...additionalFieldsSchema.shape\n\t\t}),\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\toperationId: \"createOrganizationInvitation\",\n\t\t\t\tdescription: \"Create an invitation to an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\t\temail: { type: \"string\" },\n\t\t\t\t\t\t\trole: { type: \"string\" },\n\t\t\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\t\t\tinviterId: { type: \"string\" },\n\t\t\t\t\t\t\tstatus: { type: \"string\" },\n\t\t\t\t\t\t\texpiresAt: { type: \"string\" },\n\t\t\t\t\t\t\tcreatedAt: { type: \"string\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"email\",\n\t\t\t\t\t\t\t\"role\",\n\t\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\t\"inviterId\",\n\t\t\t\t\t\t\t\"status\",\n\t\t\t\t\t\t\t\"expiresAt\",\n\t\t\t\t\t\t\t\"createdAt\"\n\t\t\t\t\t\t]\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = ctx.context.session;\n\t\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tconst email = ctx.body.email.toLowerCase();\n\t\tif (!z.email().safeParse(email).success) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_EMAIL);\n\t\tconst adapter = getOrgAdapter(ctx.context, option);\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\t\tif (!await hasPermission({\n\t\t\trole: member.role,\n\t\t\toptions: ctx.context.orgOptions,\n\t\t\tpermissions: { invitation: [\"create\"] },\n\t\t\torganizationId\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION);\n\t\tconst creatorRole = ctx.context.orgOptions.creatorRole || \"owner\";\n\t\tconst roles = parseRoles(ctx.body.role);\n\t\tconst rolesArray = roles.split(\",\").map((r) => r.trim()).filter(Boolean);\n\t\tconst defaults = Object.keys(defaultRoles);\n\t\tconst customRoles = Object.keys(ctx.context.orgOptions.roles || {});\n\t\tconst validStaticRoles = new Set([...defaults, ...customRoles]);\n\t\tconst unknownRoles = rolesArray.filter((role) => !validStaticRoles.has(role));\n\t\tif (unknownRoles.length > 0) if (ctx.context.orgOptions.dynamicAccessControl?.enabled) {\n\t\t\tconst foundRoleNames = (await ctx.context.adapter.findMany({\n\t\t\t\tmodel: \"organizationRole\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"organizationId\",\n\t\t\t\t\tvalue: organizationId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"role\",\n\t\t\t\t\tvalue: unknownRoles,\n\t\t\t\t\toperator: \"in\"\n\t\t\t\t}]\n\t\t\t})).map((r) => r.role);\n\t\t\tconst stillInvalid = unknownRoles.filter((r) => !foundRoleNames.includes(r));\n\t\t\tif (stillInvalid.length > 0) throw new APIError(\"BAD_REQUEST\", { message: `${ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND}: ${stillInvalid.join(\", \")}` });\n\t\t} else throw new APIError(\"BAD_REQUEST\", { message: `${ORGANIZATION_ERROR_CODES.ROLE_NOT_FOUND}: ${unknownRoles.join(\", \")}` });\n\t\tif (!member.role.split(\",\").map((r) => r.trim()).includes(creatorRole) && roles.split(\",\").includes(creatorRole)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE);\n\t\tif (await adapter.findMemberByEmail({\n\t\t\temail,\n\t\t\torganizationId\n\t\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\tconst alreadyInvited = await adapter.findPendingInvitation({\n\t\t\temail,\n\t\t\torganizationId\n\t\t});\n\t\tif (alreadyInvited.length && !ctx.body.resend) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION);\n\t\tconst organization = await adapter.findOrganizationById(organizationId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tif (alreadyInvited.length && ctx.body.resend) {\n\t\t\tconst existingInvitation = alreadyInvited[0];\n\t\t\tconst newExpiresAt = getDate(ctx.context.orgOptions.invitationExpiresIn || 3600 * 48, \"sec\");\n\t\t\tawait ctx.context.adapter.update({\n\t\t\t\tmodel: \"invitation\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: existingInvitation.id\n\t\t\t\t}],\n\t\t\t\tupdate: { expiresAt: newExpiresAt }\n\t\t\t});\n\t\t\tconst updatedInvitation = {\n\t\t\t\t...existingInvitation,\n\t\t\t\texpiresAt: newExpiresAt\n\t\t\t};\n\t\t\tif (ctx.context.orgOptions.sendInvitationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.orgOptions.sendInvitationEmail({\n\t\t\t\tid: updatedInvitation.id,\n\t\t\t\trole: updatedInvitation.role,\n\t\t\t\temail: updatedInvitation.email.toLowerCase(),\n\t\t\t\torganization,\n\t\t\t\tinviter: {\n\t\t\t\t\t...member,\n\t\t\t\t\tuser: session.user\n\t\t\t\t},\n\t\t\t\tinvitation: updatedInvitation\n\t\t\t}, ctx.request));\n\t\t\treturn ctx.json(updatedInvitation);\n\t\t}\n\t\tif (alreadyInvited.length && ctx.context.orgOptions.cancelPendingInvitationsOnReInvite) await adapter.updateInvitation({\n\t\t\tinvitationId: alreadyInvited[0].id,\n\t\t\tstatus: \"canceled\"\n\t\t});\n\t\tconst invitationLimit = typeof ctx.context.orgOptions.invitationLimit === \"function\" ? await ctx.context.orgOptions.invitationLimit({\n\t\t\tuser: session.user,\n\t\t\torganization,\n\t\t\tmember\n\t\t}, ctx.context) : ctx.context.orgOptions.invitationLimit ?? 100;\n\t\tif ((await adapter.findPendingInvitations({ organizationId })).length >= invitationLimit) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.INVITATION_LIMIT_REACHED);\n\t\tif (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== \"undefined\" && \"teamId\" in ctx.body && ctx.body.teamId) {\n\t\t\tconst teamIds = typeof ctx.body.teamId === \"string\" ? [ctx.body.teamId] : ctx.body.teamId;\n\t\t\tfor (const teamId of teamIds) {\n\t\t\t\tconst team = await adapter.findTeamById({\n\t\t\t\t\tteamId,\n\t\t\t\t\torganizationId,\n\t\t\t\t\tincludeTeamMembers: true\n\t\t\t\t});\n\t\t\t\tif (!team) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\t\t\t\tconst maximumMembersPerTeam = typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === \"function\" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({\n\t\t\t\t\tteamId,\n\t\t\t\t\tsession,\n\t\t\t\t\torganizationId\n\t\t\t\t}) : ctx.context.orgOptions.teams.maximumMembersPerTeam;\n\t\t\t\tif (team.members.length >= maximumMembersPerTeam) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED);\n\t\t\t}\n\t\t}\n\t\tconst teamIds = \"teamId\" in ctx.body ? typeof ctx.body.teamId === \"string\" ? [ctx.body.teamId] : ctx.body.teamId ?? [] : [];\n\t\tconst { email: _, role: __, organizationId: ___, resend: ____, ...additionalFields } = ctx.body;\n\t\tlet invitationData = {\n\t\t\trole: roles,\n\t\t\temail,\n\t\t\torganizationId,\n\t\t\tteamIds,\n\t\t\t...additionalFields ? additionalFields : {}\n\t\t};\n\t\tif (option?.organizationHooks?.beforeCreateInvitation) {\n\t\t\tconst response = await option?.organizationHooks.beforeCreateInvitation({\n\t\t\t\tinvitation: {\n\t\t\t\t\t...invitationData,\n\t\t\t\t\tinviterId: session.user.id,\n\t\t\t\t\tteamId: teamIds.length > 0 ? teamIds[0] : void 0\n\t\t\t\t},\n\t\t\t\tinviter: session.user,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) invitationData = {\n\t\t\t\t...invitationData,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst invitation = await adapter.createInvitation({\n\t\t\tinvitation: invitationData,\n\t\t\tuser: session.user\n\t\t});\n\t\tif (ctx.context.orgOptions.sendInvitationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.orgOptions.sendInvitationEmail({\n\t\t\tid: invitation.id,\n\t\t\trole: invitation.role,\n\t\t\temail: invitation.email.toLowerCase(),\n\t\t\torganization,\n\t\t\tinviter: {\n\t\t\t\t...member,\n\t\t\t\tuser: session.user\n\t\t\t},\n\t\t\tinvitation\n\t\t}, ctx.request));\n\t\tif (option?.organizationHooks?.afterCreateInvitation) await option?.organizationHooks.afterCreateInvitation({\n\t\t\tinvitation,\n\t\t\tinviter: session.user,\n\t\t\torganization\n\t\t});\n\t\treturn ctx.json(invitation);\n\t});\n};\nconst acceptInvitationBodySchema = z.object({ invitationId: z.string().meta({ description: \"The ID of the invitation to accept\" }) });\nconst acceptInvitation = (options) => createAuthEndpoint(\"/organization/accept-invitation\", {\n\tmethod: \"POST\",\n\tbody: acceptInvitationBodySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Accept an invitation to an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tinvitation: { type: \"object\" },\n\t\t\t\t\tmember: { type: \"object\" }\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst invitation = await adapter.findInvitationById(ctx.body.invitationId);\n\tif (!invitation || invitation.expiresAt < /* @__PURE__ */ new Date() || invitation.status !== \"pending\") throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND);\n\tif (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);\n\tif (ctx.context.orgOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION);\n\tconst membershipLimit = ctx.context.orgOptions?.membershipLimit || 100;\n\tconst membersCount = await adapter.countMembers({ organizationId: invitation.organizationId });\n\tconst organization = await adapter.findOrganizationById(invitation.organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (membersCount >= (typeof membershipLimit === \"number\" ? membershipLimit : await membershipLimit(session.user, organization))) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED);\n\tif (options?.organizationHooks?.beforeAcceptInvitation) await options?.organizationHooks.beforeAcceptInvitation({\n\t\tinvitation,\n\t\tuser: session.user,\n\t\torganization\n\t});\n\tconst acceptedI = await adapter.updateInvitation({\n\t\tinvitationId: ctx.body.invitationId,\n\t\tstatus: \"accepted\"\n\t});\n\tif (!acceptedI) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.FAILED_TO_RETRIEVE_INVITATION);\n\tif (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && \"teamId\" in acceptedI && acceptedI.teamId) {\n\t\tconst teamIds = acceptedI.teamId.split(\",\");\n\t\tconst onlyOne = teamIds.length === 1;\n\t\tfor (const teamId of teamIds) {\n\t\t\tawait adapter.findOrCreateTeamMember({\n\t\t\t\tteamId,\n\t\t\t\tuserId: session.user.id\n\t\t\t});\n\t\t\tif (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== \"undefined\") {\n\t\t\t\tif (await adapter.countTeamMembers({ teamId }) >= (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === \"function\" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({\n\t\t\t\t\tteamId,\n\t\t\t\t\tsession,\n\t\t\t\t\torganizationId: invitation.organizationId\n\t\t\t\t}) : ctx.context.orgOptions.teams.maximumMembersPerTeam)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED);\n\t\t\t}\n\t\t}\n\t\tif (onlyOne) {\n\t\t\tconst teamId = teamIds[0];\n\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\tsession: await adapter.setActiveTeam(session.session.token, teamId, ctx),\n\t\t\t\tuser: session.user\n\t\t\t});\n\t\t}\n\t}\n\tconst member = await adapter.createMember({\n\t\torganizationId: invitation.organizationId,\n\t\tuserId: session.user.id,\n\t\trole: invitation.role,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n\tawait adapter.setActiveOrganization(session.session.token, invitation.organizationId, ctx);\n\tif (options?.organizationHooks?.afterAcceptInvitation) await options?.organizationHooks.afterAcceptInvitation({\n\t\tinvitation: acceptedI,\n\t\tmember,\n\t\tuser: session.user,\n\t\torganization\n\t});\n\treturn ctx.json({\n\t\tinvitation: acceptedI,\n\t\tmember\n\t});\n});\nconst rejectInvitationBodySchema = z.object({ invitationId: z.string().meta({ description: \"The ID of the invitation to reject\" }) });\nconst rejectInvitation = (options) => createAuthEndpoint(\"/organization/reject-invitation\", {\n\tmethod: \"POST\",\n\tbody: rejectInvitationBodySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Reject an invitation to an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tinvitation: { type: \"object\" },\n\t\t\t\t\tmember: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tnullable: true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst invitation = await adapter.findInvitationById(ctx.body.invitationId);\n\tif (!invitation || invitation.status !== \"pending\") throw APIError.from(\"BAD_REQUEST\", {\n\t\tmessage: \"Invitation not found!\",\n\t\tcode: \"INVITATION_NOT_FOUND\"\n\t});\n\tif (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);\n\tif (ctx.context.orgOptions.requireEmailVerificationOnInvitation && !session.user.emailVerified) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION);\n\tconst organization = await adapter.findOrganizationById(invitation.organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (options?.organizationHooks?.beforeRejectInvitation) await options?.organizationHooks.beforeRejectInvitation({\n\t\tinvitation,\n\t\tuser: session.user,\n\t\torganization\n\t});\n\tconst rejectedI = await adapter.updateInvitation({\n\t\tinvitationId: ctx.body.invitationId,\n\t\tstatus: \"rejected\"\n\t});\n\tif (options?.organizationHooks?.afterRejectInvitation) await options?.organizationHooks.afterRejectInvitation({\n\t\tinvitation: rejectedI || invitation,\n\t\tuser: session.user,\n\t\torganization\n\t});\n\treturn ctx.json({\n\t\tinvitation: rejectedI,\n\t\tmember: null\n\t});\n});\nconst cancelInvitationBodySchema = z.object({ invitationId: z.string().meta({ description: \"The ID of the invitation to cancel\" }) });\nconst cancelInvitation = (options) => createAuthEndpoint(\"/organization/cancel-invitation\", {\n\tmethod: \"POST\",\n\tbody: cancelInvitationBodySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\topenapi: {\n\t\toperationId: \"cancelOrganizationInvitation\",\n\t\tdescription: \"Cancel an invitation to an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { invitation: { type: \"object\" } }\n\t\t\t} } }\n\t\t} }\n\t}\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst invitation = await adapter.findInvitationById(ctx.body.invitationId);\n\tif (!invitation) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND);\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId: invitation.organizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tif (!await hasPermission({\n\t\trole: member.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { invitation: [\"cancel\"] },\n\t\torganizationId: invitation.organizationId\n\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION);\n\tconst organization = await adapter.findOrganizationById(invitation.organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (options?.organizationHooks?.beforeCancelInvitation) await options?.organizationHooks.beforeCancelInvitation({\n\t\tinvitation,\n\t\tcancelledBy: session.user,\n\t\torganization\n\t});\n\tconst canceledI = await adapter.updateInvitation({\n\t\tinvitationId: ctx.body.invitationId,\n\t\tstatus: \"canceled\"\n\t});\n\tif (options?.organizationHooks?.afterCancelInvitation) await options?.organizationHooks.afterCancelInvitation({\n\t\tinvitation: canceledI || invitation,\n\t\tcancelledBy: session.user,\n\t\torganization\n\t});\n\treturn ctx.json(canceledI);\n});\nconst getInvitationQuerySchema = z.object({ id: z.string().meta({ description: \"The ID of the invitation to get\" }) });\nconst getInvitation = (options) => createAuthEndpoint(\"/organization/get-invitation\", {\n\tmethod: \"GET\",\n\tuse: [orgMiddleware],\n\trequireHeaders: true,\n\tquery: getInvitationQuerySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"Get an invitation by ID\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\temail: { type: \"string\" },\n\t\t\t\t\trole: { type: \"string\" },\n\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\tinviterId: { type: \"string\" },\n\t\t\t\t\tstatus: { type: \"string\" },\n\t\t\t\t\texpiresAt: { type: \"string\" },\n\t\t\t\t\torganizationName: { type: \"string\" },\n\t\t\t\t\torganizationSlug: { type: \"string\" },\n\t\t\t\t\tinviterEmail: { type: \"string\" }\n\t\t\t\t},\n\t\t\t\trequired: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"email\",\n\t\t\t\t\t\"role\",\n\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\"inviterId\",\n\t\t\t\t\t\"status\",\n\t\t\t\t\t\"expiresAt\",\n\t\t\t\t\t\"organizationName\",\n\t\t\t\t\t\"organizationSlug\",\n\t\t\t\t\t\"inviterEmail\"\n\t\t\t\t]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw APIError.fromStatus(\"UNAUTHORIZED\", { message: \"Not authenticated\" });\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst invitation = await adapter.findInvitationById(ctx.query.id);\n\tif (!invitation || invitation.status !== \"pending\" || invitation.expiresAt < /* @__PURE__ */ new Date()) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"Invitation not found!\" });\n\tif (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION);\n\tconst organization = await adapter.findOrganizationById(invitation.organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: invitation.inviterId,\n\t\torganizationId: invitation.organizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION);\n\treturn ctx.json({\n\t\t...invitation,\n\t\torganizationName: organization.name,\n\t\torganizationSlug: organization.slug,\n\t\tinviterEmail: member.user.email\n\t});\n});\nconst listInvitationQuerySchema = z.object({ organizationId: z.string().meta({ description: \"The ID of the organization to list invitations for\" }).optional() }).optional();\nconst listInvitations = (options) => createAuthEndpoint(\"/organization/list-invitations\", {\n\tmethod: \"GET\",\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tquery: listInvitationQuerySchema\n}, async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw APIError.fromStatus(\"UNAUTHORIZED\", { message: \"Not authenticated\" });\n\tconst orgId = ctx.query?.organizationId || session.session.activeOrganizationId;\n\tif (!orgId) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"Organization ID is required\" });\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId: orgId\n\t})) throw APIError.fromStatus(\"FORBIDDEN\", { message: \"You are not a member of this organization\" });\n\tconst invitations = await adapter.listInvitations({ organizationId: orgId });\n\treturn ctx.json(invitations);\n});\n/**\n* List all invitations a user has received\n*/\nconst listUserInvitations = (options) => createAuthEndpoint(\"/organization/list-user-invitations\", {\n\tmethod: \"GET\",\n\tuse: [orgMiddleware],\n\tquery: z.object({ email: z.string().meta({ description: \"The email of the user to list invitations for. This only works for server side API calls.\" }).optional() }).optional(),\n\tmetadata: { openapi: {\n\t\tdescription: \"List all invitations a user has received\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\temail: { type: \"string\" },\n\t\t\t\t\t\trole: { type: \"string\" },\n\t\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\t\torganizationName: { type: \"string\" },\n\t\t\t\t\t\tinviterId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The ID of the user who created the invitation\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tteamId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The ID of the team associated with the invitation\",\n\t\t\t\t\t\t\tnullable: true\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: { type: \"string\" },\n\t\t\t\t\t\texpiresAt: { type: \"string\" },\n\t\t\t\t\t\tcreatedAt: { type: \"string\" }\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"email\",\n\t\t\t\t\t\t\"role\",\n\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\"organizationName\",\n\t\t\t\t\t\t\"inviterId\",\n\t\t\t\t\t\t\"status\",\n\t\t\t\t\t\t\"expiresAt\",\n\t\t\t\t\t\t\"createdAt\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (ctx.request && ctx.query?.email) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User email cannot be passed for client side API calls.\" });\n\tconst userEmail = session?.user.email || ctx.query?.email;\n\tif (!userEmail) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"Missing session headers, or email query parameter.\" });\n\tconst pendingInvitations = (await getOrgAdapter(ctx.context, options).listUserInvitations(userEmail)).filter((inv) => inv.status === \"pending\");\n\treturn ctx.json(pendingInvitations);\n});\n//#endregion\nexport { acceptInvitation, cancelInvitation, createInvitation, getInvitation, listInvitations, listUserInvitations, rejectInvitation };\n", "import { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { getSessionFromCtx, sessionMiddleware } from \"../../../api/routes/session.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { getOrgAdapter } from \"../adapter.mjs\";\nimport { orgMiddleware, orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { parseRoles } from \"../organization.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { whereOperators } from \"@better-auth/core/db/adapter\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-members.ts\nconst baseMemberSchema = z.object({\n\tuserId: z.coerce.string().meta({ description: \"The user Id which represents the user to be added as a member. If `null` is provided, then it's expected to provide session headers. Eg: \\\"user-id\\\"\" }),\n\trole: z.union([z.string(), z.array(z.string())]).meta({ description: \"The role(s) to assign to the new member. Eg: [\\\"admin\\\", \\\"sale\\\"]\" }),\n\torganizationId: z.string().meta({ description: \"An optional organization ID to pass. If not provided, will default to the user's active organization. Eg: \\\"org-id\\\"\" }).optional(),\n\tteamId: z.string().meta({ description: \"An optional team ID to add the member to. Eg: \\\"team-id\\\"\" }).optional()\n});\nconst addMember = (option) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: option?.schema?.member?.additionalFields || {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint({\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\t...baseMemberSchema.shape,\n\t\t\t...additionalFieldsSchema.shape\n\t\t}),\n\t\tuse: [orgMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\toperationId: \"addOrganizationMember\",\n\t\t\t\tdescription: \"Add a member to an organization\"\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = ctx.body.userId ? await getSessionFromCtx(ctx).catch((e) => null) : null;\n\t\tconst orgId = ctx.body.organizationId || session?.session.activeOrganizationId;\n\t\tif (!orgId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\tconst teamId = \"teamId\" in ctx.body ? ctx.body.teamId : void 0;\n\t\tif (teamId && !ctx.context.orgOptions.teams?.enabled) {\n\t\t\tctx.context.logger.error(\"Teams are not enabled\");\n\t\t\tthrow APIError.fromStatus(\"BAD_REQUEST\", { message: \"Teams are not enabled\" });\n\t\t}\n\t\tconst adapter = getOrgAdapter(ctx.context, option);\n\t\tconst user = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n\t\tif (!user) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.USER_NOT_FOUND);\n\t\tif (await adapter.findMemberByEmail({\n\t\t\temail: user.email,\n\t\t\torganizationId: orgId\n\t\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION);\n\t\tif (teamId) {\n\t\t\tconst team = await adapter.findTeamById({\n\t\t\t\tteamId,\n\t\t\t\torganizationId: orgId\n\t\t\t});\n\t\t\tif (!team || team.organizationId !== orgId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\t\t}\n\t\tconst membershipLimit = ctx.context.orgOptions?.membershipLimit || 100;\n\t\tconst count = await adapter.countMembers({ organizationId: orgId });\n\t\tconst organization = await adapter.findOrganizationById(orgId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tif (count >= (typeof membershipLimit === \"number\" ? membershipLimit : await membershipLimit(user, organization))) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED);\n\t\tconst { role: _, userId: __, organizationId: ___, ...additionalFields } = ctx.body;\n\t\tlet memberData = {\n\t\t\torganizationId: orgId,\n\t\t\tuserId: user.id,\n\t\t\trole: parseRoles(ctx.body.role),\n\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\t...additionalFields ? additionalFields : {}\n\t\t};\n\t\tif (option?.organizationHooks?.beforeAddMember) {\n\t\t\tconst response = await option?.organizationHooks.beforeAddMember({\n\t\t\t\tmember: {\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\torganizationId: orgId,\n\t\t\t\t\trole: parseRoles(ctx.body.role),\n\t\t\t\t\t...additionalFields\n\t\t\t\t},\n\t\t\t\tuser,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) memberData = {\n\t\t\t\t...memberData,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst createdMember = await adapter.createMember(memberData);\n\t\tif (teamId) await adapter.findOrCreateTeamMember({\n\t\t\tuserId: user.id,\n\t\t\tteamId\n\t\t});\n\t\tif (option?.organizationHooks?.afterAddMember) await option?.organizationHooks.afterAddMember({\n\t\t\tmember: createdMember,\n\t\t\tuser,\n\t\t\torganization\n\t\t});\n\t\treturn ctx.json(createdMember);\n\t});\n};\nconst removeMemberBodySchema = z.object({\n\tmemberIdOrEmail: z.string().meta({ description: \"The ID or email of the member to remove\" }),\n\torganizationId: z.string().meta({ description: \"The ID of the organization to remove the member from. If not provided, the active organization will be used. Eg: \\\"org-id\\\"\" }).optional()\n});\nconst removeMember = (options) => createAuthEndpoint(\"/organization/remove-member\", {\n\tmethod: \"POST\",\n\tbody: removeMemberBodySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Remove a member from an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { member: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\tuserId: { type: \"string\" },\n\t\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\t\trole: { type: \"string\" }\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\"role\"\n\t\t\t\t\t]\n\t\t\t\t} },\n\t\t\t\trequired: [\"member\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tlet toBeRemovedMember = null;\n\tif (ctx.body.memberIdOrEmail.includes(\"@\")) toBeRemovedMember = await adapter.findMemberByEmail({\n\t\temail: ctx.body.memberIdOrEmail,\n\t\torganizationId\n\t});\n\telse {\n\t\tconst result = await adapter.findMemberById(ctx.body.memberIdOrEmail);\n\t\tif (!result) toBeRemovedMember = null;\n\t\telse {\n\t\t\tconst { user: _user, ...member } = result;\n\t\t\ttoBeRemovedMember = member;\n\t\t}\n\t}\n\tif (!toBeRemovedMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tconst roles = toBeRemovedMember.role.split(\",\");\n\tconst creatorRole = ctx.context.orgOptions?.creatorRole || \"owner\";\n\tif (roles.includes(creatorRole)) {\n\t\tif (!member.role.split(\",\").map((r) => r.trim()).includes(creatorRole)) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);\n\t\tconst { members } = await adapter.listMembers({ organizationId });\n\t\tif (members.filter((member) => {\n\t\t\treturn member.role.split(\",\").includes(creatorRole);\n\t\t}).length <= 1) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);\n\t}\n\tif (!await hasPermission({\n\t\trole: member.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { member: [\"delete\"] },\n\t\torganizationId\n\t}, ctx)) throw APIError.from(\"UNAUTHORIZED\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER);\n\tif (toBeRemovedMember?.organizationId !== organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst userBeingRemoved = await ctx.context.internalAdapter.findUserById(toBeRemovedMember.userId);\n\tif (!userBeingRemoved) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User not found\" });\n\tif (options?.organizationHooks?.beforeRemoveMember) await options?.organizationHooks.beforeRemoveMember({\n\t\tmember: toBeRemovedMember,\n\t\tuser: userBeingRemoved,\n\t\torganization\n\t});\n\tawait adapter.deleteMember({\n\t\tmemberId: toBeRemovedMember.id,\n\t\torganizationId,\n\t\tuserId: toBeRemovedMember.userId\n\t});\n\tif (session.user.id === toBeRemovedMember.userId && session.session.activeOrganizationId === toBeRemovedMember.organizationId) await adapter.setActiveOrganization(session.session.token, null, ctx);\n\tif (options?.organizationHooks?.afterRemoveMember) await options?.organizationHooks.afterRemoveMember({\n\t\tmember: toBeRemovedMember,\n\t\tuser: userBeingRemoved,\n\t\torganization\n\t});\n\treturn ctx.json({ member: toBeRemovedMember });\n});\nconst updateMemberRoleBodySchema = z.object({\n\trole: z.union([z.string(), z.array(z.string())]).meta({ description: \"The new role to be applied. This can be a string or array of strings representing the roles. Eg: [\\\"admin\\\", \\\"sale\\\"]\" }),\n\tmemberId: z.string().meta({ description: \"The member id to apply the role update to. Eg: \\\"member-id\\\"\" }),\n\torganizationId: z.string().meta({ description: \"An optional organization ID which the member is a part of to apply the role update. If not provided, you must provide session headers to get the active organization. Eg: \\\"organization-id\\\"\" }).optional()\n});\nconst updateMemberRole = (option) => createAuthEndpoint(\"/organization/update-member-role\", {\n\tmethod: \"POST\",\n\tbody: updateMemberRoleBodySchema,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: {\n\t\t$Infer: { body: {} },\n\t\topenapi: {\n\t\t\toperationId: \"updateOrganizationMemberRole\",\n\t\t\tdescription: \"Update the role of a member in an organization\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { member: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\t\tuserId: { type: \"string\" },\n\t\t\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\t\t\trole: { type: \"string\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\t\"role\"\n\t\t\t\t\t\t]\n\t\t\t\t\t} },\n\t\t\t\t\trequired: [\"member\"]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tif (!ctx.body.role) throw APIError.fromStatus(\"BAD_REQUEST\");\n\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst roleToSet = Array.isArray(ctx.body.role) ? ctx.body.role : ctx.body.role ? [ctx.body.role] : [];\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tconst toBeUpdatedMember = member.id !== ctx.body.memberId ? await adapter.findMemberById(ctx.body.memberId) : member;\n\tif (!toBeUpdatedMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tif (!(toBeUpdatedMember.organizationId === organizationId)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);\n\tconst creatorRole = ctx.context.orgOptions?.creatorRole || \"owner\";\n\tconst updatingMemberRoles = member.role.split(\",\");\n\tconst isUpdatingCreator = toBeUpdatedMember.role.split(\",\").includes(creatorRole);\n\tconst updaterIsCreator = updatingMemberRoles.includes(creatorRole);\n\tconst isSettingCreatorRole = roleToSet.includes(creatorRole);\n\tconst memberIsUpdatingThemselves = member.id === toBeUpdatedMember.id;\n\tif (isUpdatingCreator && !updaterIsCreator || isSettingCreatorRole && !updaterIsCreator) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);\n\tif (updaterIsCreator && memberIsUpdatingThemselves) {\n\t\tif ((await ctx.context.adapter.findMany({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: organizationId\n\t\t\t}]\n\t\t})).filter((member) => {\n\t\t\treturn member.role.split(\",\").includes(creatorRole);\n\t\t}).length <= 1 && !isSettingCreatorRole) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER);\n\t}\n\tif (!await hasPermission({\n\t\trole: member.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { member: [\"update\"] },\n\t\tallowCreatorAllPermissions: true,\n\t\torganizationId\n\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER);\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst userBeingUpdated = await ctx.context.internalAdapter.findUserById(toBeUpdatedMember.userId);\n\tif (!userBeingUpdated) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User not found\" });\n\tconst previousRole = toBeUpdatedMember.role;\n\tconst newRole = parseRoles(ctx.body.role);\n\tif (option?.organizationHooks?.beforeUpdateMemberRole) {\n\t\tconst response = await option?.organizationHooks.beforeUpdateMemberRole({\n\t\t\tmember: toBeUpdatedMember,\n\t\t\tnewRole,\n\t\t\tuser: userBeingUpdated,\n\t\t\torganization\n\t\t});\n\t\tif (response && typeof response === \"object\" && \"data\" in response) {\n\t\t\tconst updatedMember = await adapter.updateMember(ctx.body.memberId, response.data.role || newRole);\n\t\t\tif (!updatedMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\t\t\tif (option?.organizationHooks?.afterUpdateMemberRole) await option?.organizationHooks.afterUpdateMemberRole({\n\t\t\t\tmember: updatedMember,\n\t\t\t\tpreviousRole,\n\t\t\t\tuser: userBeingUpdated,\n\t\t\t\torganization\n\t\t\t});\n\t\t\treturn ctx.json(updatedMember);\n\t\t}\n\t}\n\tconst updatedMember = await adapter.updateMember(ctx.body.memberId, newRole);\n\tif (!updatedMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tif (option?.organizationHooks?.afterUpdateMemberRole) await option?.organizationHooks.afterUpdateMemberRole({\n\t\tmember: updatedMember,\n\t\tpreviousRole,\n\t\tuser: userBeingUpdated,\n\t\torganization\n\t});\n\treturn ctx.json(updatedMember);\n});\nconst getActiveMember = (options) => createAuthEndpoint(\"/organization/get-active-member\", {\n\tmethod: \"GET\",\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"Get the member details of the active organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\tuserId: { type: \"string\" },\n\t\t\t\t\torganizationId: { type: \"string\" },\n\t\t\t\t\trole: { type: \"string\" }\n\t\t\t\t},\n\t\t\t\trequired: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"userId\",\n\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\"role\"\n\t\t\t\t]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst organizationId = session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst member = await getOrgAdapter(ctx.context, options).findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\treturn ctx.json(member);\n});\nconst leaveOrganizationBodySchema = z.object({ organizationId: z.string().meta({ description: \"The organization Id for the member to leave. Eg: \\\"organization-id\\\"\" }) });\nconst leaveOrganization = (options) => createAuthEndpoint(\"/organization/leave\", {\n\tmethod: \"POST\",\n\tbody: leaveOrganizationBodySchema,\n\trequireHeaders: true,\n\tuse: [sessionMiddleware, orgMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId: ctx.body.organizationId\n\t});\n\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND);\n\tconst creatorRole = ctx.context.orgOptions?.creatorRole || \"owner\";\n\tif (member.role.split(\",\").includes(creatorRole)) {\n\t\tif ((await ctx.context.adapter.findMany({\n\t\t\tmodel: \"member\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"organizationId\",\n\t\t\t\tvalue: ctx.body.organizationId\n\t\t\t}]\n\t\t})).filter((member) => member.role.split(\",\").includes(creatorRole)).length <= 1) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER);\n\t}\n\tawait adapter.deleteMember({\n\t\tmemberId: member.id,\n\t\torganizationId: ctx.body.organizationId,\n\t\tuserId: session.user.id\n\t});\n\tif (session.session.activeOrganizationId === ctx.body.organizationId) await adapter.setActiveOrganization(session.session.token, null, ctx);\n\treturn ctx.json(member);\n});\nconst listMembers = (options) => createAuthEndpoint(\"/organization/list-members\", {\n\tmethod: \"GET\",\n\tquery: z.object({\n\t\tlimit: z.string().meta({ description: \"The number of users to return\" }).or(z.number()).optional(),\n\t\toffset: z.string().meta({ description: \"The offset to start from\" }).or(z.number()).optional(),\n\t\tsortBy: z.string().meta({ description: \"The field to sort by\" }).optional(),\n\t\tsortDirection: z.enum([\"asc\", \"desc\"]).meta({ description: \"The direction to sort by\" }).optional(),\n\t\tfilterField: z.string().meta({ description: \"The field to filter by\" }).optional(),\n\t\tfilterValue: z.string().meta({ description: \"The value to filter by\" }).or(z.number()).or(z.boolean()).or(z.array(z.string())).or(z.array(z.number())).optional(),\n\t\tfilterOperator: z.enum(whereOperators).meta({ description: \"The operator to use for the filter\" }).optional(),\n\t\torganizationId: z.string().meta({ description: \"The organization ID to list members for. If not provided, will default to the user's active organization. Eg: \\\"organization-id\\\"\" }).optional(),\n\t\torganizationSlug: z.string().meta({ description: \"The organization slug to list members for. If not provided, will default to the user's active organization. Eg: \\\"organization-slug\\\"\" }).optional()\n\t}).optional(),\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tlet organizationId = ctx.query?.organizationId || session.session.activeOrganizationId;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (ctx.query?.organizationSlug) {\n\t\tconst organization = await adapter.findOrganizationBySlug(ctx.query?.organizationSlug);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\torganizationId = organization.id;\n\t}\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t})) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\tconst { members, total } = await adapter.listMembers({\n\t\torganizationId,\n\t\tlimit: ctx.query?.limit ? Number(ctx.query.limit) : void 0,\n\t\toffset: ctx.query?.offset ? Number(ctx.query.offset) : void 0,\n\t\tsortBy: ctx.query?.sortBy,\n\t\tsortOrder: ctx.query?.sortDirection,\n\t\tfilter: ctx.query?.filterField ? {\n\t\t\tfield: ctx.query?.filterField,\n\t\t\toperator: ctx.query.filterOperator,\n\t\t\tvalue: ctx.query.filterValue\n\t\t} : void 0\n\t});\n\treturn ctx.json({\n\t\tmembers,\n\t\ttotal\n\t});\n});\nconst getActiveMemberRoleQuerySchema = z.object({\n\tuserId: z.string().meta({ description: \"The user ID to get the role for. If not provided, will default to the current user's\" }).optional(),\n\torganizationId: z.string().meta({ description: \"The organization ID to list members for. If not provided, will default to the user's active organization. Eg: \\\"organization-id\\\"\" }).optional(),\n\torganizationSlug: z.string().meta({ description: \"The organization slug to list members for. If not provided, will default to the user's active organization. Eg: \\\"organization-slug\\\"\" }).optional()\n}).optional();\nconst getActiveMemberRole = (options) => createAuthEndpoint(\"/organization/get-active-member-role\", {\n\tmethod: \"GET\",\n\tquery: getActiveMemberRoleQuerySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tlet organizationId = ctx.query?.organizationId || session.session.activeOrganizationId;\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (ctx.query?.organizationSlug) {\n\t\tconst organization = await adapter.findOrganizationBySlug(ctx.query?.organizationSlug);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\torganizationId = organization.id;\n\t}\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst isMember = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!isMember) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\tif (!ctx.query?.userId) return ctx.json({ role: isMember.role });\n\tconst userIdToGetRole = ctx.query?.userId;\n\tconst member = await adapter.findMemberByOrgId({\n\t\tuserId: userIdToGetRole,\n\t\torganizationId\n\t});\n\tif (!member) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION);\n\treturn ctx.json({ role: member?.role });\n});\n//#endregion\nexport { addMember, getActiveMember, getActiveMemberRole, leaveOrganization, listMembers, removeMember, updateMemberRole };\n", "import { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { getSessionFromCtx, requestOnlySessionMiddleware } from \"../../../api/routes/session.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { getOrgAdapter } from \"../adapter.mjs\";\nimport { orgMiddleware, orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-org.ts\nconst baseOrganizationSchema = z.object({\n\tname: z.string().min(1).meta({ description: \"The name of the organization\" }),\n\tslug: z.string().min(1).meta({ description: \"The slug of the organization\" }),\n\tuserId: z.coerce.string().meta({ description: \"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server. server-only. Eg: \\\"user-id\\\"\" }).optional(),\n\tlogo: z.string().meta({ description: \"The logo of the organization\" }).optional(),\n\tmetadata: z.record(z.string(), z.any()).meta({ description: \"The metadata of the organization\" }).optional(),\n\tkeepCurrentActiveOrganization: z.boolean().meta({ description: \"Whether to keep the current active organization active after creating a new one. Eg: true\" }).optional()\n});\nconst createOrganization = (options) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: options?.schema?.organization?.additionalFields || {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/create\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\t...baseOrganizationSchema.shape,\n\t\t\t...additionalFieldsSchema.shape\n\t\t}),\n\t\tuse: [orgMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Create an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tdescription: \"The organization that was created\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/Organization\"\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = await getSessionFromCtx(ctx);\n\t\tif (!session && (ctx.request || ctx.headers)) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\tlet user = session?.user || null;\n\t\tif (!user) {\n\t\t\tif (!ctx.body.userId) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\t\tuser = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n\t\t}\n\t\tif (!user) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\tconst options = ctx.context.orgOptions;\n\t\tconst canCreateOrg = typeof options?.allowUserToCreateOrganization === \"function\" ? await options.allowUserToCreateOrganization(user) : options?.allowUserToCreateOrganization === void 0 ? true : options.allowUserToCreateOrganization;\n\t\tconst isSystemAction = !session && ctx.body.userId;\n\t\tif (!canCreateOrg && !isSystemAction) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst userOrganizations = await adapter.listOrganizations(user.id);\n\t\tif (typeof options.organizationLimit === \"number\" ? userOrganizations.length >= options.organizationLimit : typeof options.organizationLimit === \"function\" ? await options.organizationLimit(user) : false) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS);\n\t\tif (await adapter.findOrganizationBySlug(ctx.body.slug)) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_ALREADY_EXISTS);\n\t\tlet { keepCurrentActiveOrganization: _, userId: __, ...orgData } = ctx.body;\n\t\tif (options?.organizationHooks?.beforeCreateOrganization) {\n\t\t\tconst response = await options?.organizationHooks.beforeCreateOrganization({\n\t\t\t\torganization: orgData,\n\t\t\t\tuser\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) orgData = {\n\t\t\t\t...ctx.body,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst organization = await adapter.createOrganization({ organization: {\n\t\t\t...orgData,\n\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t} });\n\t\tlet member;\n\t\tlet teamMember = null;\n\t\tlet data = {\n\t\t\tuserId: user.id,\n\t\t\torganizationId: organization.id,\n\t\t\trole: ctx.context.orgOptions.creatorRole || \"owner\"\n\t\t};\n\t\tif (options?.organizationHooks?.beforeAddMember) {\n\t\t\tconst response = await options?.organizationHooks.beforeAddMember({\n\t\t\t\tmember: {\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\torganizationId: organization.id,\n\t\t\t\t\trole: ctx.context.orgOptions.creatorRole || \"owner\"\n\t\t\t\t},\n\t\t\t\tuser,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) data = {\n\t\t\t\t...data,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tmember = await adapter.createMember(data);\n\t\tif (options?.organizationHooks?.afterAddMember) await options?.organizationHooks.afterAddMember({\n\t\t\tmember,\n\t\t\tuser,\n\t\t\torganization\n\t\t});\n\t\tif (options?.teams?.enabled && options.teams.defaultTeam?.enabled !== false) {\n\t\t\tlet teamData = {\n\t\t\t\torganizationId: organization.id,\n\t\t\t\tname: `${organization.name}`,\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t};\n\t\t\tif (options?.organizationHooks?.beforeCreateTeam) {\n\t\t\t\tconst response = await options?.organizationHooks.beforeCreateTeam({\n\t\t\t\t\tteam: {\n\t\t\t\t\t\torganizationId: organization.id,\n\t\t\t\t\t\tname: `${organization.name}`\n\t\t\t\t\t},\n\t\t\t\t\tuser,\n\t\t\t\t\torganization\n\t\t\t\t});\n\t\t\t\tif (response && typeof response === \"object\" && \"data\" in response) teamData = {\n\t\t\t\t\t...teamData,\n\t\t\t\t\t...response.data\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst defaultTeam = await options.teams.defaultTeam?.customCreateDefaultTeam?.(organization, ctx) || await adapter.createTeam(teamData);\n\t\t\tteamMember = await adapter.findOrCreateTeamMember({\n\t\t\t\tteamId: defaultTeam.id,\n\t\t\t\tuserId: user.id\n\t\t\t});\n\t\t\tif (options?.organizationHooks?.afterCreateTeam) await options?.organizationHooks.afterCreateTeam({\n\t\t\t\tteam: defaultTeam,\n\t\t\t\tuser,\n\t\t\t\torganization\n\t\t\t});\n\t\t}\n\t\tif (options?.organizationHooks?.afterCreateOrganization) await options?.organizationHooks.afterCreateOrganization({\n\t\t\torganization,\n\t\t\tuser,\n\t\t\tmember\n\t\t});\n\t\tif (ctx.context.session && !ctx.body.keepCurrentActiveOrganization) await adapter.setActiveOrganization(ctx.context.session.session.token, organization.id, ctx);\n\t\tif (teamMember && ctx.context.session && !ctx.body.keepCurrentActiveOrganization) await adapter.setActiveTeam(ctx.context.session.session.token, teamMember.teamId, ctx);\n\t\treturn ctx.json({\n\t\t\t...organization,\n\t\t\tmetadata: organization.metadata && typeof organization.metadata === \"string\" ? JSON.parse(organization.metadata) : organization.metadata,\n\t\t\tmembers: [member]\n\t\t});\n\t});\n};\nconst checkOrganizationSlugBodySchema = z.object({ slug: z.string().meta({ description: \"The organization slug to check. Eg: \\\"my-org\\\"\" }) });\nconst checkOrganizationSlug = (options) => createAuthEndpoint(\"/organization/check-slug\", {\n\tmethod: \"POST\",\n\tbody: checkOrganizationSlugBodySchema,\n\tuse: [requestOnlySessionMiddleware, orgMiddleware]\n}, async (ctx) => {\n\tif (!await getOrgAdapter(ctx.context, options).findOrganizationBySlug(ctx.body.slug)) return ctx.json({ status: true });\n\tthrow APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_SLUG_ALREADY_TAKEN);\n});\nconst baseUpdateOrganizationSchema = z.object({\n\tname: z.string().min(1).meta({ description: \"The name of the organization\" }).optional(),\n\tslug: z.string().min(1).meta({ description: \"The slug of the organization\" }).optional(),\n\tlogo: z.string().meta({ description: \"The logo of the organization\" }).optional(),\n\tmetadata: z.record(z.string(), z.any()).meta({ description: \"The metadata of the organization\" }).optional()\n});\nconst updateOrganization = (options) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: options?.schema?.organization?.additionalFields || {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/update\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\tdata: z.object({\n\t\t\t\t...additionalFieldsSchema.shape,\n\t\t\t\t...baseUpdateOrganizationSchema.shape\n\t\t\t}).partial(),\n\t\t\torganizationId: z.string().meta({ description: \"The organization ID. Eg: \\\"org-id\\\"\" }).optional()\n\t\t}),\n\t\trequireHeaders: true,\n\t\tuse: [orgMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Update an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tdescription: \"The updated organization\",\n\t\t\t\t\t\t$ref: \"#/components/schemas/Organization\"\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = await ctx.context.getSession(ctx);\n\t\tif (!session) throw APIError.fromStatus(\"UNAUTHORIZED\", { message: \"User not found\" });\n\t\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t\tif (!await hasPermission({\n\t\t\tpermissions: { organization: [\"update\"] },\n\t\t\trole: member.role,\n\t\t\toptions: ctx.context.orgOptions,\n\t\t\torganizationId\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION);\n\t\tif (typeof ctx.body.data.slug === \"string\") {\n\t\t\tconst existingOrganization = await adapter.findOrganizationBySlug(ctx.body.data.slug);\n\t\t\tif (existingOrganization && existingOrganization.id !== organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_SLUG_ALREADY_TAKEN);\n\t\t}\n\t\tif (options?.organizationHooks?.beforeUpdateOrganization) {\n\t\t\tconst response = await options.organizationHooks.beforeUpdateOrganization({\n\t\t\t\torganization: ctx.body.data,\n\t\t\t\tuser: session.user,\n\t\t\t\tmember\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) ctx.body.data = {\n\t\t\t\t...ctx.body.data,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst updatedOrg = await adapter.updateOrganization(organizationId, ctx.body.data);\n\t\tif (options?.organizationHooks?.afterUpdateOrganization) await options.organizationHooks.afterUpdateOrganization({\n\t\t\torganization: updatedOrg,\n\t\t\tuser: session.user,\n\t\t\tmember\n\t\t});\n\t\treturn ctx.json(updatedOrg);\n\t});\n};\nconst deleteOrganizationBodySchema = z.object({ organizationId: z.string().meta({ description: \"The organization id to delete\" }) });\nconst deleteOrganization = (options) => {\n\treturn createAuthEndpoint(\"/organization/delete\", {\n\t\tmethod: \"POST\",\n\t\tbody: deleteOrganizationBodySchema,\n\t\trequireHeaders: true,\n\t\tuse: [orgMiddleware],\n\t\tmetadata: { openapi: {\n\t\t\tdescription: \"Delete an organization\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"The organization id that was deleted\"\n\t\t\t\t} } }\n\t\t\t} }\n\t\t} }\n\t}, async (ctx) => {\n\t\tif (ctx.context.orgOptions.disableOrganizationDeletion) throw APIError.from(\"NOT_FOUND\", {\n\t\t\tmessage: \"Organization deletion is disabled\",\n\t\t\tcode: \"ORGANIZATION_DELETION_DISABLED\"\n\t\t});\n\t\tconst session = await ctx.context.getSession(ctx);\n\t\tif (!session) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\tconst organizationId = ctx.body.organizationId;\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t\tif (!await hasPermission({\n\t\t\trole: member.role,\n\t\t\tpermissions: { organization: [\"delete\"] },\n\t\t\torganizationId,\n\t\t\toptions: ctx.context.orgOptions\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION);\n\t\tif (organizationId === session.session.activeOrganizationId)\n /**\n\t\t* If the organization is deleted, we set the active organization to null\n\t\t*/\n\t\tawait adapter.setActiveOrganization(session.session.token, null, ctx);\n\t\tconst org = await adapter.findOrganizationById(organizationId);\n\t\tif (!org) throw APIError.fromStatus(\"BAD_REQUEST\");\n\t\tif (options?.organizationHooks?.beforeDeleteOrganization) await options.organizationHooks.beforeDeleteOrganization({\n\t\t\torganization: org,\n\t\t\tuser: session.user\n\t\t});\n\t\tawait adapter.deleteOrganization(organizationId);\n\t\tif (options?.organizationHooks?.afterDeleteOrganization) await options.organizationHooks.afterDeleteOrganization({\n\t\t\torganization: org,\n\t\t\tuser: session.user\n\t\t});\n\t\treturn ctx.json(org);\n\t});\n};\nconst getFullOrganizationQuerySchema = z.optional(z.object({\n\torganizationId: z.string().meta({ description: \"The organization id to get\" }).optional(),\n\torganizationSlug: z.string().meta({ description: \"The organization slug to get\" }).optional(),\n\tmembersLimit: z.number().or(z.string().transform((val) => parseInt(val))).meta({ description: \"The limit of members to get. By default, it uses the membershipLimit option.\" }).optional()\n}));\nconst getFullOrganization = (options) => createAuthEndpoint(\"/organization/get-full-organization\", {\n\tmethod: \"GET\",\n\tquery: getFullOrganizationQuerySchema,\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\tmetadata: { openapi: {\n\t\toperationId: \"getOrganization\",\n\t\tdescription: \"Get the full organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tdescription: \"The organization\",\n\t\t\t\t$ref: \"#/components/schemas/Organization\"\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst organizationId = ctx.query?.organizationSlug || ctx.query?.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) return ctx.json(null, { status: 200 });\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tconst organization = await adapter.findFullOrganization({\n\t\torganizationId,\n\t\tisSlug: !!ctx.query?.organizationSlug,\n\t\tincludeTeams: ctx.context.orgOptions.teams?.enabled,\n\t\tmembersLimit: ctx.query?.membersLimit\n\t});\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (!await adapter.checkMembership({\n\t\tuserId: session.user.id,\n\t\torganizationId: organization.id\n\t})) {\n\t\tawait adapter.setActiveOrganization(session.session.token, null, ctx);\n\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t}\n\treturn ctx.json(organization);\n});\nconst setActiveOrganizationBodySchema = z.object({\n\torganizationId: z.string().meta({ description: \"The organization id to set as active. It can be null to unset the active organization. Eg: \\\"org-id\\\"\" }).nullable().optional(),\n\torganizationSlug: z.string().meta({ description: \"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided. Eg: \\\"org-slug\\\"\" }).optional()\n});\nconst setActiveOrganization = (options) => {\n\treturn createAuthEndpoint(\"/organization/set-active\", {\n\t\tmethod: \"POST\",\n\t\tbody: setActiveOrganizationBodySchema,\n\t\tuse: [orgSessionMiddleware, orgMiddleware],\n\t\trequireHeaders: true,\n\t\tmetadata: { openapi: {\n\t\t\toperationId: \"setActiveOrganization\",\n\t\t\tdescription: \"Set the active organization\",\n\t\t\tresponses: { \"200\": {\n\t\t\t\tdescription: \"Success\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"The organization\",\n\t\t\t\t\t$ref: \"#/components/schemas/Organization\"\n\t\t\t\t} } }\n\t\t\t} }\n\t\t} }\n\t}, async (ctx) => {\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst session = ctx.context.session;\n\t\tlet organizationId = ctx.body.organizationId;\n\t\tconst organizationSlug = ctx.body.organizationSlug;\n\t\tif (organizationId === null) {\n\t\t\tif (!session.session.activeOrganizationId) return ctx.json(null);\n\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\tsession: await adapter.setActiveOrganization(session.session.token, null, ctx),\n\t\t\t\tuser: session.user\n\t\t\t});\n\t\t\treturn ctx.json(null);\n\t\t}\n\t\tif (!organizationId && !organizationSlug) {\n\t\t\tconst sessionOrgId = session.session.activeOrganizationId;\n\t\t\tif (!sessionOrgId) return ctx.json(null);\n\t\t\torganizationId = sessionOrgId;\n\t\t}\n\t\tif (organizationSlug && !organizationId) {\n\t\t\tconst organization = await adapter.findOrganizationBySlug(organizationSlug);\n\t\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\t\torganizationId = organization.id;\n\t\t}\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tif (!await adapter.checkMembership({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t})) {\n\t\t\tawait adapter.setActiveOrganization(session.session.token, null, ctx);\n\t\t\tthrow APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t\t}\n\t\tconst organization = await adapter.findOrganizationById(organizationId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession: await adapter.setActiveOrganization(session.session.token, organization.id, ctx),\n\t\t\tuser: session.user\n\t\t});\n\t\treturn ctx.json(organization);\n\t});\n};\nconst listOrganizations = (options) => createAuthEndpoint(\"/organization/list\", {\n\tmethod: \"GET\",\n\tuse: [orgMiddleware, orgSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"List all organizations\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: { $ref: \"#/components/schemas/Organization\" }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst organizations = await getOrgAdapter(ctx.context, options).listOrganizations(ctx.context.session.user.id);\n\treturn ctx.json(organizations);\n});\n//#endregion\nexport { checkOrganizationSlug, createOrganization, deleteOrganization, getFullOrganization, listOrganizations, setActiveOrganization, updateOrganization };\n", "import { generateId } from \"@better-auth/core/utils/id\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/schema.ts\nconst roleSchema = z.string();\nconst invitationStatus = z.enum([\n\t\"pending\",\n\t\"accepted\",\n\t\"rejected\",\n\t\"canceled\"\n]).default(\"pending\");\nz.object({\n\tid: z.string().default(generateId),\n\tname: z.string(),\n\tslug: z.string(),\n\tlogo: z.string().nullish().optional(),\n\tmetadata: z.record(z.string(), z.unknown()).or(z.string().transform((v) => JSON.parse(v))).optional(),\n\tcreatedAt: z.date()\n});\nz.object({\n\tid: z.string().default(generateId),\n\torganizationId: z.string(),\n\tuserId: z.coerce.string(),\n\trole: roleSchema,\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nz.object({\n\tid: z.string().default(generateId),\n\torganizationId: z.string(),\n\temail: z.string(),\n\trole: roleSchema,\n\tstatus: invitationStatus,\n\tteamId: z.string().nullish(),\n\tinviterId: z.string(),\n\texpiresAt: z.date(),\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nconst teamSchema = z.object({\n\tid: z.string().default(generateId),\n\tname: z.string().min(1),\n\torganizationId: z.string(),\n\tcreatedAt: z.date(),\n\tupdatedAt: z.date().optional()\n});\nz.object({\n\tid: z.string().default(generateId),\n\tteamId: z.string(),\n\tuserId: z.string(),\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nz.object({\n\tid: z.string().default(generateId),\n\torganizationId: z.string(),\n\trole: z.string(),\n\tpermission: z.record(z.string(), z.array(z.string())),\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date()),\n\tupdatedAt: z.date().optional()\n});\nconst defaultRoles = [\n\t\"admin\",\n\t\"member\",\n\t\"owner\"\n];\nz.union([z.enum(defaultRoles), z.array(z.enum(defaultRoles))]);\n//#endregion\nexport { teamSchema };\n", "import { toZodSchema } from \"../../../db/to-zod.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { getSessionFromCtx } from \"../../../api/routes/session.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"../error-codes.mjs\";\nimport { getOrgAdapter } from \"../adapter.mjs\";\nimport { orgMiddleware, orgSessionMiddleware } from \"../call.mjs\";\nimport { hasPermission } from \"../has-permission.mjs\";\nimport { teamSchema } from \"../schema.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/routes/crud-team.ts\nconst teamBaseSchema = z.object({\n\tname: z.string().meta({ description: \"The name of the team. Eg: \\\"my-team\\\"\" }),\n\torganizationId: z.string().meta({ description: \"The organization ID which the team will be created in. Defaults to the active organization. Eg: \\\"organization-id\\\"\" }).optional()\n});\nconst createTeam = (options) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: options?.schema?.team?.additionalFields ?? {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/create-team\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\t...teamBaseSchema.shape,\n\t\t\t...additionalFieldsSchema.shape\n\t\t}),\n\t\tuse: [orgMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Create a new team within an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Team created successfully\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"Unique identifier of the created team\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"Name of the team\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\torganizationId: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"ID of the organization the team belongs to\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"Timestamp when the team was created\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"Timestamp when the team was last updated\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t]\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = await getSessionFromCtx(ctx);\n\t\tconst organizationId = ctx.body.organizationId || session?.session.activeOrganizationId;\n\t\tif (!session && (ctx.request || ctx.headers)) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tif (session) {\n\t\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\t\tuserId: session.user.id,\n\t\t\t\torganizationId\n\t\t\t});\n\t\t\tif (!member) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION);\n\t\t\tif (!await hasPermission({\n\t\t\t\trole: member.role,\n\t\t\t\toptions: ctx.context.orgOptions,\n\t\t\t\tpermissions: { team: [\"create\"] },\n\t\t\t\torganizationId\n\t\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION);\n\t\t}\n\t\tconst existingTeams = await adapter.listTeams(organizationId);\n\t\tconst maximum = typeof ctx.context.orgOptions.teams?.maximumTeams === \"function\" ? await ctx.context.orgOptions.teams?.maximumTeams({\n\t\t\torganizationId,\n\t\t\tsession\n\t\t}, ctx) : ctx.context.orgOptions.teams?.maximumTeams;\n\t\tif (maximum ? existingTeams.length >= maximum : false) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS);\n\t\tconst { name, organizationId: _, ...additionalFields } = ctx.body;\n\t\tconst organization = await adapter.findOrganizationById(organizationId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tlet teamData = {\n\t\t\tname,\n\t\t\torganizationId,\n\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\t...additionalFields\n\t\t};\n\t\tif (options?.organizationHooks?.beforeCreateTeam) {\n\t\t\tconst response = await options?.organizationHooks.beforeCreateTeam({\n\t\t\t\tteam: {\n\t\t\t\t\tname,\n\t\t\t\t\torganizationId,\n\t\t\t\t\t...additionalFields\n\t\t\t\t},\n\t\t\t\tuser: session?.user,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) teamData = {\n\t\t\t\t...teamData,\n\t\t\t\t...response.data\n\t\t\t};\n\t\t}\n\t\tconst createdTeam = await adapter.createTeam(teamData);\n\t\tif (options?.organizationHooks?.afterCreateTeam) await options?.organizationHooks.afterCreateTeam({\n\t\t\tteam: createdTeam,\n\t\t\tuser: session?.user,\n\t\t\torganization\n\t\t});\n\t\treturn ctx.json(createdTeam);\n\t});\n};\nconst removeTeamBodySchema = z.object({\n\tteamId: z.string().meta({ description: `The team ID of the team to remove. Eg: \"team-id\"` }),\n\torganizationId: z.string().meta({ description: `The organization ID which the team falls under. If not provided, it will default to the user's active organization. Eg: \"organization-id\"` }).optional()\n});\nconst removeTeam = (options) => createAuthEndpoint(\"/organization/remove-team\", {\n\tmethod: \"POST\",\n\tbody: removeTeamBodySchema,\n\tuse: [orgMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Remove a team from an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Team removed successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"Confirmation message indicating successful removal\",\n\t\t\t\t\tenum: [\"Team removed successfully.\"]\n\t\t\t\t} },\n\t\t\t\trequired: [\"message\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tconst organizationId = ctx.body.organizationId || session?.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tif (!session && (ctx.request || ctx.headers)) throw APIError.fromStatus(\"UNAUTHORIZED\");\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (session) {\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member || session.session?.activeTeamId === ctx.body.teamId) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM);\n\t\tif (!await hasPermission({\n\t\t\trole: member.role,\n\t\t\toptions: ctx.context.orgOptions,\n\t\t\tpermissions: { team: [\"delete\"] },\n\t\t\torganizationId\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION);\n\t}\n\tconst team = await adapter.findTeamById({\n\t\tteamId: ctx.body.teamId,\n\t\torganizationId\n\t});\n\tif (!team || team.organizationId !== organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\tif (!ctx.context.orgOptions.teams?.allowRemovingAllTeams) {\n\t\tif ((await adapter.listTeams(organizationId)).length <= 1) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.UNABLE_TO_REMOVE_LAST_TEAM);\n\t}\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tif (options?.organizationHooks?.beforeDeleteTeam) await options?.organizationHooks.beforeDeleteTeam({\n\t\tteam,\n\t\tuser: session?.user,\n\t\torganization\n\t});\n\tawait adapter.deleteTeam(team.id);\n\tif (options?.organizationHooks?.afterDeleteTeam) await options?.organizationHooks.afterDeleteTeam({\n\t\tteam,\n\t\tuser: session?.user,\n\t\torganization\n\t});\n\treturn ctx.json({ message: \"Team removed successfully.\" });\n});\nconst updateTeam = (options) => {\n\tconst additionalFieldsSchema = toZodSchema({\n\t\tfields: options?.schema?.team?.additionalFields ?? {},\n\t\tisClientSide: true\n\t});\n\treturn createAuthEndpoint(\"/organization/update-team\", {\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\tteamId: z.string().meta({ description: `The ID of the team to be updated. Eg: \"team-id\"` }),\n\t\t\tdata: z.object({\n\t\t\t\t...teamSchema.shape,\n\t\t\t\t...additionalFieldsSchema.shape\n\t\t\t}).partial()\n\t\t}),\n\t\trequireHeaders: true,\n\t\tuse: [orgMiddleware, orgSessionMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Update an existing team in an organization\",\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Team updated successfully\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"Unique identifier of the updated team\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"Updated name of the team\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\torganizationId: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tdescription: \"ID of the organization the team belongs to\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"Timestamp when the team was created\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\tdescription: \"Timestamp when the team was last updated\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t]\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst session = ctx.context.session;\n\t\tconst organizationId = ctx.body.data.organizationId || session.session.activeOrganizationId;\n\t\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\tconst adapter = getOrgAdapter(ctx.context, options);\n\t\tconst member = await adapter.findMemberByOrgId({\n\t\t\tuserId: session.user.id,\n\t\t\torganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM);\n\t\tif (!await hasPermission({\n\t\t\trole: member.role,\n\t\t\toptions: ctx.context.orgOptions,\n\t\t\tpermissions: { team: [\"update\"] },\n\t\t\torganizationId\n\t\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM);\n\t\tconst team = await adapter.findTeamById({\n\t\t\tteamId: ctx.body.teamId,\n\t\t\torganizationId\n\t\t});\n\t\tif (!team || team.organizationId !== organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\t\tconst { name, organizationId: __, ...additionalFields } = ctx.body.data;\n\t\tconst organization = await adapter.findOrganizationById(organizationId);\n\t\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\t\tconst updates = {\n\t\t\tname,\n\t\t\t...additionalFields\n\t\t};\n\t\tif (options?.organizationHooks?.beforeUpdateTeam) {\n\t\t\tconst response = await options?.organizationHooks.beforeUpdateTeam({\n\t\t\t\tteam,\n\t\t\t\tupdates,\n\t\t\t\tuser: session.user,\n\t\t\t\torganization\n\t\t\t});\n\t\t\tif (response && typeof response === \"object\" && \"data\" in response) {\n\t\t\t\tconst modifiedUpdates = response.data;\n\t\t\t\tconst updatedTeam = await adapter.updateTeam(team.id, modifiedUpdates);\n\t\t\t\tif (options?.organizationHooks?.afterUpdateTeam) await options?.organizationHooks.afterUpdateTeam({\n\t\t\t\t\tteam: updatedTeam,\n\t\t\t\t\tuser: session.user,\n\t\t\t\t\torganization\n\t\t\t\t});\n\t\t\t\treturn ctx.json(updatedTeam);\n\t\t\t}\n\t\t}\n\t\tconst updatedTeam = await adapter.updateTeam(team.id, updates);\n\t\tif (options?.organizationHooks?.afterUpdateTeam) await options?.organizationHooks.afterUpdateTeam({\n\t\t\tteam: updatedTeam,\n\t\t\tuser: session.user,\n\t\t\torganization\n\t\t});\n\t\treturn ctx.json(updatedTeam);\n\t});\n};\nconst listOrganizationTeamsQuerySchema = z.optional(z.object({ organizationId: z.string().meta({ description: `The organization ID which the teams are under to list. Defaults to the users active organization. Eg: \"organization-id\"` }).optional() }));\nconst listOrganizationTeams = (options) => createAuthEndpoint(\"/organization/list-teams\", {\n\tmethod: \"GET\",\n\tquery: listOrganizationTeamsQuerySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"List all teams in an organization\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Teams retrieved successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Unique identifier of the team\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Name of the team\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\torganizationId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"ID of the organization the team belongs to\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\tdescription: \"Timestamp when the team was created\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\tdescription: \"Timestamp when the team was last updated\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"name\",\n\t\t\t\t\t\t\"organizationId\",\n\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\tdescription: \"Array of team objects within the organization\"\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst organizationId = ctx.query?.organizationId || session?.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst adapter = getOrgAdapter(ctx.context, options);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId: organizationId || \"\"\n\t})) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION);\n\tconst teams = await adapter.listTeams(organizationId);\n\treturn ctx.json(teams);\n});\nconst setActiveTeamBodySchema = z.object({ teamId: z.string().meta({ description: \"The team id to set as active. It can be null to unset the active team\" }).nullable().optional() });\nconst setActiveTeam = (options) => createAuthEndpoint(\"/organization/set-active-team\", {\n\tmethod: \"POST\",\n\tbody: setActiveTeamBodySchema,\n\trequireHeaders: true,\n\tuse: [orgSessionMiddleware, orgMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Set the active team\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tdescription: \"The team\",\n\t\t\t\t$ref: \"#/components/schemas/Team\"\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst session = ctx.context.session;\n\tif (ctx.body.teamId === null) {\n\t\tif (!session.session.activeTeamId) return ctx.json(null);\n\t\tawait setSessionCookie(ctx, {\n\t\t\tsession: await adapter.setActiveTeam(session.session.token, null, ctx),\n\t\t\tuser: session.user\n\t\t});\n\t\treturn ctx.json(null);\n\t}\n\tlet teamId;\n\tif (!ctx.body.teamId) {\n\t\tconst sessionTeamId = session.session.activeTeamId;\n\t\tif (!sessionTeamId) return ctx.json(null);\n\t\telse teamId = sessionTeamId;\n\t} else teamId = ctx.body.teamId;\n\tconst team = await adapter.findTeamById({ teamId });\n\tif (!team) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\tif (!await adapter.findTeamMember({\n\t\tteamId,\n\t\tuserId: session.user.id\n\t})) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);\n\tawait setSessionCookie(ctx, {\n\t\tsession: await adapter.setActiveTeam(session.session.token, team.id, ctx),\n\t\tuser: session.user\n\t});\n\treturn ctx.json(team);\n});\nconst listUserTeams = (options) => createAuthEndpoint(\"/organization/list-user-teams\", {\n\tmethod: \"GET\",\n\tmetadata: { openapi: {\n\t\tdescription: \"List all teams that the current user is a part of.\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Teams retrieved successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"The team\",\n\t\t\t\t\t$ref: \"#/components/schemas/Team\"\n\t\t\t\t},\n\t\t\t\tdescription: \"Array of team objects within the organization\"\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst teams = await getOrgAdapter(ctx.context, ctx.context.orgOptions).listTeamsByUser({ userId: session.user.id });\n\treturn ctx.json(teams);\n});\nconst listTeamMembersQuerySchema = z.optional(z.object({ teamId: z.string().optional().meta({ description: \"The team whose members we should return. If this is not provided the members of the current active team get returned.\" }) }));\nconst listTeamMembers = (options) => createAuthEndpoint(\"/organization/list-team-members\", {\n\tmethod: \"GET\",\n\tquery: listTeamMembersQuerySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"List the members of the given team.\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Teams retrieved successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tdescription: \"The team member\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Unique identifier of the team member\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tuserId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The user ID of the team member\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tteamId: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The team ID of the team the team member is in\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\tdescription: \"Timestamp when the team member was created\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\n\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\"teamId\",\n\t\t\t\t\t\t\"createdAt\"\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\tdescription: \"Array of team member objects within the team\"\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst teamId = ctx.query?.teamId || session?.session.activeTeamId;\n\tif (!teamId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM);\n\tif (!await adapter.findTeamMember({\n\t\tuserId: session.user.id,\n\t\tteamId\n\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);\n\tconst members = await adapter.listTeamMembers({ teamId });\n\treturn ctx.json(members);\n});\nconst addTeamMemberBodySchema = z.object({\n\tteamId: z.string().meta({ description: \"The team the user should be a member of.\" }),\n\tuserId: z.coerce.string().meta({ description: \"The user Id which represents the user to be added as a member.\" }),\n\torganizationId: z.string().meta({ description: \"The organization ID which the team falls under. If not provided, it will default to the user's active organization.\" }).optional()\n});\nconst addTeamMember = (options) => createAuthEndpoint(\"/organization/add-team-member\", {\n\tmethod: \"POST\",\n\tbody: addTeamMemberBodySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"The newly created member\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Team member created successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tdescription: \"The team member\",\n\t\t\t\tproperties: {\n\t\t\t\t\tid: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"Unique identifier of the team member\"\n\t\t\t\t\t},\n\t\t\t\t\tuserId: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The user ID of the team member\"\n\t\t\t\t\t},\n\t\t\t\t\tteamId: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"The team ID of the team the team member is in\"\n\t\t\t\t\t},\n\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\tdescription: \"Timestamp when the team member was created\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"userId\",\n\t\t\t\t\t\"teamId\",\n\t\t\t\t\t\"createdAt\"\n\t\t\t\t]\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst currentMember = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!currentMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\tif (!await hasPermission({\n\t\trole: currentMember.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { member: [\"update\"] },\n\t\torganizationId\n\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: ctx.body.userId,\n\t\torganizationId\n\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\tconst team = await adapter.findTeamById({\n\t\tteamId: ctx.body.teamId,\n\t\torganizationId\n\t});\n\tif (!team) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst userBeingAdded = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n\tif (!userBeingAdded) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User not found\" });\n\tif (options?.organizationHooks?.beforeAddTeamMember) {\n\t\tconst response = await options?.organizationHooks.beforeAddTeamMember({\n\t\t\tteamMember: {\n\t\t\t\tteamId: ctx.body.teamId,\n\t\t\t\tuserId: ctx.body.userId\n\t\t\t},\n\t\t\tteam,\n\t\t\tuser: userBeingAdded,\n\t\t\torganization\n\t\t});\n\t\tif (response && typeof response === \"object\" && \"data\" in response) {}\n\t}\n\tconst teamMember = await adapter.findOrCreateTeamMember({\n\t\tteamId: ctx.body.teamId,\n\t\tuserId: ctx.body.userId\n\t});\n\tif (options?.organizationHooks?.afterAddTeamMember) await options?.organizationHooks.afterAddTeamMember({\n\t\tteamMember,\n\t\tteam,\n\t\tuser: userBeingAdded,\n\t\torganization\n\t});\n\treturn ctx.json(teamMember);\n});\nconst removeTeamMemberBodySchema = z.object({\n\tteamId: z.string().meta({ description: \"The team the user should be removed from.\" }),\n\tuserId: z.coerce.string().meta({ description: \"The user which should be removed from the team.\" }),\n\torganizationId: z.string().meta({ description: \"The organization ID which the team falls under. If not provided, it will default to the user's active organization.\" }).optional()\n});\nconst removeTeamMember = (options) => createAuthEndpoint(\"/organization/remove-team-member\", {\n\tmethod: \"POST\",\n\tbody: removeTeamMemberBodySchema,\n\tmetadata: { openapi: {\n\t\tdescription: \"Remove a member from a team\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Team member removed successfully\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"Confirmation message indicating successful removal\",\n\t\t\t\t\tenum: [\"Team member removed successfully.\"]\n\t\t\t\t} },\n\t\t\t\trequired: [\"message\"]\n\t\t\t} } }\n\t\t} }\n\t} },\n\trequireHeaders: true,\n\tuse: [orgMiddleware, orgSessionMiddleware]\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tconst adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n\tconst organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n\tif (!organizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\tconst currentMember = await adapter.findMemberByOrgId({\n\t\tuserId: session.user.id,\n\t\torganizationId\n\t});\n\tif (!currentMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\tif (!await hasPermission({\n\t\trole: currentMember.role,\n\t\toptions: ctx.context.orgOptions,\n\t\tpermissions: { member: [\"delete\"] },\n\t\torganizationId\n\t}, ctx)) throw APIError.from(\"FORBIDDEN\", ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER);\n\tif (!await adapter.findMemberByOrgId({\n\t\tuserId: ctx.body.userId,\n\t\torganizationId\n\t})) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\tconst team = await adapter.findTeamById({\n\t\tteamId: ctx.body.teamId,\n\t\torganizationId\n\t});\n\tif (!team) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND);\n\tconst organization = await adapter.findOrganizationById(organizationId);\n\tif (!organization) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND);\n\tconst userBeingRemoved = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n\tif (!userBeingRemoved) throw APIError.fromStatus(\"BAD_REQUEST\", { message: \"User not found\" });\n\tconst teamMember = await adapter.findTeamMember({\n\t\tteamId: ctx.body.teamId,\n\t\tuserId: ctx.body.userId\n\t});\n\tif (!teamMember) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM);\n\tif (options?.organizationHooks?.beforeRemoveTeamMember) await options?.organizationHooks.beforeRemoveTeamMember({\n\t\tteamMember,\n\t\tteam,\n\t\tuser: userBeingRemoved,\n\t\torganization\n\t});\n\tawait adapter.removeTeamMember({\n\t\tteamId: ctx.body.teamId,\n\t\tuserId: ctx.body.userId\n\t});\n\tif (options?.organizationHooks?.afterRemoveTeamMember) await options?.organizationHooks.afterRemoveTeamMember({\n\t\tteamMember,\n\t\tteam,\n\t\tuser: userBeingRemoved,\n\t\torganization\n\t});\n\treturn ctx.json({ message: \"Team member removed successfully.\" });\n});\n//#endregion\nexport { addTeamMember, createTeam, listOrganizationTeams, listTeamMembers, listUserTeams, removeTeam, removeTeamMember, setActiveTeam, updateTeam };\n", "import { getSessionFromCtx } from \"../../api/routes/session.mjs\";\nimport { PACKAGE_VERSION } from \"../../version.mjs\";\nimport { defaultRoles } from \"./access/statement.mjs\";\nimport { ORGANIZATION_ERROR_CODES } from \"./error-codes.mjs\";\nimport { getOrgAdapter } from \"./adapter.mjs\";\nimport { shimContext } from \"../../utils/shim.mjs\";\nimport { orgSessionMiddleware } from \"./call.mjs\";\nimport { hasPermission } from \"./has-permission.mjs\";\nimport { createOrgRole, deleteOrgRole, getOrgRole, listOrgRoles, updateOrgRole } from \"./routes/crud-access-control.mjs\";\nimport { acceptInvitation, cancelInvitation, createInvitation, getInvitation, listInvitations, listUserInvitations, rejectInvitation } from \"./routes/crud-invites.mjs\";\nimport { addMember, getActiveMember, getActiveMemberRole, leaveOrganization, listMembers, removeMember, updateMemberRole } from \"./routes/crud-members.mjs\";\nimport { checkOrganizationSlug, createOrganization, deleteOrganization, getFullOrganization, listOrganizations, setActiveOrganization, updateOrganization } from \"./routes/crud-org.mjs\";\nimport { addTeamMember, createTeam, listOrganizationTeams, listTeamMembers, listUserTeams, removeTeam, removeTeamMember, setActiveTeam, updateTeam } from \"./routes/crud-team.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/organization/organization.ts\nfunction parseRoles(roles) {\n\treturn Array.isArray(roles) ? roles.join(\",\") : roles;\n}\nconst createHasPermissionBodySchema = z.object({ organizationId: z.string().optional() }).and(z.union([z.object({\n\tpermission: z.record(z.string(), z.array(z.string())),\n\tpermissions: z.undefined()\n}), z.object({\n\tpermission: z.undefined(),\n\tpermissions: z.record(z.string(), z.array(z.string()))\n})]));\nconst createHasPermission = (options) => {\n\treturn createAuthEndpoint(\"/organization/has-permission\", {\n\t\tmethod: \"POST\",\n\t\trequireHeaders: true,\n\t\tbody: createHasPermissionBodySchema,\n\t\tuse: [orgSessionMiddleware],\n\t\tmetadata: {\n\t\t\t$Infer: { body: {} },\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Check if the user has permission\",\n\t\t\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tpermission: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tdescription: \"The permission to check\",\n\t\t\t\t\t\t\tdeprecated: true\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpermissions: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tdescription: \"The permission to check\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"permissions\"]\n\t\t\t\t} } } },\n\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\terror: { type: \"string\" },\n\t\t\t\t\t\t\tsuccess: { type: \"boolean\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"success\"]\n\t\t\t\t\t} } }\n\t\t\t\t} }\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\tconst activeOrganizationId = ctx.body.organizationId || ctx.context.session.session.activeOrganizationId;\n\t\tif (!activeOrganizationId) throw APIError.from(\"BAD_REQUEST\", ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION);\n\t\tconst member = await getOrgAdapter(ctx.context, options).findMemberByOrgId({\n\t\t\tuserId: ctx.context.session.user.id,\n\t\t\torganizationId: activeOrganizationId\n\t\t});\n\t\tif (!member) throw APIError.from(\"UNAUTHORIZED\", ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION);\n\t\tconst result = await hasPermission({\n\t\t\trole: member.role,\n\t\t\toptions,\n\t\t\tpermissions: ctx.body.permissions,\n\t\t\torganizationId: activeOrganizationId\n\t\t}, ctx);\n\t\treturn ctx.json({\n\t\t\terror: null,\n\t\t\tsuccess: result\n\t\t});\n\t});\n};\nfunction organization(options) {\n\tconst opts = options || {};\n\tlet endpoints = {\n\t\tcreateOrganization: createOrganization(opts),\n\t\tupdateOrganization: updateOrganization(opts),\n\t\tdeleteOrganization: deleteOrganization(opts),\n\t\tsetActiveOrganization: setActiveOrganization(opts),\n\t\tgetFullOrganization: getFullOrganization(opts),\n\t\tlistOrganizations: listOrganizations(opts),\n\t\tcreateInvitation: createInvitation(opts),\n\t\tcancelInvitation: cancelInvitation(opts),\n\t\tacceptInvitation: acceptInvitation(opts),\n\t\tgetInvitation: getInvitation(opts),\n\t\trejectInvitation: rejectInvitation(opts),\n\t\tlistInvitations: listInvitations(opts),\n\t\tgetActiveMember: getActiveMember(opts),\n\t\tcheckOrganizationSlug: checkOrganizationSlug(opts),\n\t\taddMember: addMember(opts),\n\t\tremoveMember: removeMember(opts),\n\t\tupdateMemberRole: updateMemberRole(opts),\n\t\tleaveOrganization: leaveOrganization(opts),\n\t\tlistUserInvitations: listUserInvitations(opts),\n\t\tlistMembers: listMembers(opts),\n\t\tgetActiveMemberRole: getActiveMemberRole(opts)\n\t};\n\tconst teamSupport = opts.teams?.enabled;\n\tconst teamEndpoints = {\n\t\tcreateTeam: createTeam(opts),\n\t\tlistOrganizationTeams: listOrganizationTeams(opts),\n\t\tremoveTeam: removeTeam(opts),\n\t\tupdateTeam: updateTeam(opts),\n\t\tsetActiveTeam: setActiveTeam(opts),\n\t\tlistUserTeams: listUserTeams(opts),\n\t\tlistTeamMembers: listTeamMembers(opts),\n\t\taddTeamMember: addTeamMember(opts),\n\t\tremoveTeamMember: removeTeamMember(opts)\n\t};\n\tif (teamSupport) endpoints = {\n\t\t...endpoints,\n\t\t...teamEndpoints\n\t};\n\tconst dynamicAccessControlEndpoints = {\n\t\tcreateOrgRole: createOrgRole(opts),\n\t\tdeleteOrgRole: deleteOrgRole(opts),\n\t\tlistOrgRoles: listOrgRoles(opts),\n\t\tgetOrgRole: getOrgRole(opts),\n\t\tupdateOrgRole: updateOrgRole(opts)\n\t};\n\tif (opts.dynamicAccessControl?.enabled) endpoints = {\n\t\t...endpoints,\n\t\t...dynamicAccessControlEndpoints\n\t};\n\tconst roles = {\n\t\t...defaultRoles,\n\t\t...opts.roles\n\t};\n\tconst teamSchema = teamSupport ? {\n\t\tteam: {\n\t\t\tmodelName: opts.schema?.team?.modelName,\n\t\t\tfields: {\n\t\t\t\tname: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.team?.fields?.name\n\t\t\t\t},\n\t\t\t\torganizationId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.team?.fields?.organizationId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.team?.fields?.createdAt\n\t\t\t\t},\n\t\t\t\tupdatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.team?.fields?.updatedAt,\n\t\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date()\n\t\t\t\t},\n\t\t\t\t...opts.schema?.team?.additionalFields || {}\n\t\t\t}\n\t\t},\n\t\tteamMember: {\n\t\t\tmodelName: opts.schema?.teamMember?.modelName,\n\t\t\tfields: {\n\t\t\t\tteamId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"team\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.teamMember?.fields?.teamId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tuserId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.teamMember?.fields?.userId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.teamMember?.fields?.createdAt\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} : {};\n\tconst organizationRoleSchema = opts.dynamicAccessControl?.enabled ? { organizationRole: {\n\t\tfields: {\n\t\t\torganizationId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\tfield: \"id\"\n\t\t\t\t},\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.organizationId,\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\trole: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.role,\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tpermission: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.permission\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: true,\n\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date(),\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.createdAt\n\t\t\t},\n\t\t\tupdatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: false,\n\t\t\t\tfieldName: opts.schema?.organizationRole?.fields?.updatedAt,\n\t\t\t\tonUpdate: () => /* @__PURE__ */ new Date()\n\t\t\t},\n\t\t\t...opts.schema?.organizationRole?.additionalFields || {}\n\t\t},\n\t\tmodelName: opts.schema?.organizationRole?.modelName\n\t} } : {};\n\tconst schema = {\n\t\torganization: {\n\t\t\tmodelName: opts.schema?.organization?.modelName,\n\t\t\tfields: {\n\t\t\t\tname: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.name\n\t\t\t\t},\n\t\t\t\tslug: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tunique: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.slug,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tlogo: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.logo\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.createdAt\n\t\t\t\t},\n\t\t\t\tmetadata: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.organization?.fields?.metadata\n\t\t\t\t},\n\t\t\t\t...opts.schema?.organization?.additionalFields || {}\n\t\t\t}\n\t\t},\n\t\t...organizationRoleSchema,\n\t\t...teamSchema,\n\t\tmember: {\n\t\t\tmodelName: opts.schema?.member?.modelName,\n\t\t\tfields: {\n\t\t\t\torganizationId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.member?.fields?.organizationId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\tuserId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.member?.fields?.userId,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\trole: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tdefaultValue: \"member\",\n\t\t\t\t\tfieldName: opts.schema?.member?.fields?.role\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.member?.fields?.createdAt\n\t\t\t\t},\n\t\t\t\t...opts.schema?.member?.additionalFields || {}\n\t\t\t}\n\t\t},\n\t\tinvitation: {\n\t\t\tmodelName: opts.schema?.invitation?.modelName,\n\t\t\tfields: {\n\t\t\t\torganizationId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.organizationId,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\temail: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.email,\n\t\t\t\t\tindex: true\n\t\t\t\t},\n\t\t\t\trole: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.role\n\t\t\t\t},\n\t\t\t\t...teamSupport ? { teamId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.teamId\n\t\t\t\t} } : {},\n\t\t\t\tstatus: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsortable: true,\n\t\t\t\t\tdefaultValue: \"pending\",\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.status\n\t\t\t\t},\n\t\t\t\texpiresAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.expiresAt\n\t\t\t\t},\n\t\t\t\tcreatedAt: {\n\t\t\t\t\ttype: \"date\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.createdAt,\n\t\t\t\t\tdefaultValue: () => /* @__PURE__ */ new Date()\n\t\t\t\t},\n\t\t\t\tinviterId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\treferences: {\n\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\tfield: \"id\"\n\t\t\t\t\t},\n\t\t\t\t\tfieldName: opts.schema?.invitation?.fields?.inviterId,\n\t\t\t\t\trequired: true\n\t\t\t\t},\n\t\t\t\t...opts.schema?.invitation?.additionalFields || {}\n\t\t\t}\n\t\t}\n\t};\n\treturn {\n\t\tid: \"organization\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\t...shimContext(endpoints, {\n\t\t\t\torgOptions: opts,\n\t\t\t\troles,\n\t\t\t\tgetSession: async (context) => {\n\t\t\t\t\treturn await getSessionFromCtx(context);\n\t\t\t\t}\n\t\t\t}),\n\t\t\thasPermission: createHasPermission(opts)\n\t\t},\n\t\tschema: {\n\t\t\t...schema,\n\t\t\tsession: { fields: {\n\t\t\t\tactiveOrganizationId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.session?.fields?.activeOrganizationId\n\t\t\t\t},\n\t\t\t\t...teamSupport ? { activeTeamId: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: false,\n\t\t\t\t\tfieldName: opts.schema?.session?.fields?.activeTeamId\n\t\t\t\t} } : {}\n\t\t\t} }\n\t\t},\n\t\t$Infer: {\n\t\t\tOrganization: {},\n\t\t\tInvitation: {},\n\t\t\tMember: {},\n\t\t\tTeam: teamSupport ? {} : {},\n\t\t\tTeamMember: teamSupport ? {} : {},\n\t\t\tActiveOrganization: {}\n\t\t},\n\t\t$ERROR_CODES: ORGANIZATION_ERROR_CODES,\n\t\toptions: opts\n\t};\n}\n//#endregion\nexport { organization, parseRoles };\n", "import { defineErrorCodes } from \"@better-auth/core/utils/error-codes\";\n//#region src/plugins/two-factor/error-code.ts\nconst TWO_FACTOR_ERROR_CODES = defineErrorCodes({\n\tOTP_NOT_ENABLED: \"OTP not enabled\",\n\tOTP_HAS_EXPIRED: \"OTP has expired\",\n\tTOTP_NOT_ENABLED: \"TOTP not enabled\",\n\tTWO_FACTOR_NOT_ENABLED: \"Two factor isn't enabled\",\n\tBACKUP_CODES_NOT_ENABLED: \"Backup codes aren't enabled\",\n\tINVALID_BACKUP_CODE: \"Invalid backup code\",\n\tINVALID_CODE: \"Invalid code\",\n\tTOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: \"Too many attempts. Please request a new code.\",\n\tINVALID_TWO_FACTOR_COOKIE: \"Invalid two factor cookie\"\n});\n//#endregion\nexport { TWO_FACTOR_ERROR_CODES };\n", "//#region src/plugins/two-factor/constant.ts\nconst TWO_FACTOR_COOKIE_NAME = \"two_factor\";\nconst TRUST_DEVICE_COOKIE_NAME = \"trust_device\";\nconst TRUST_DEVICE_COOKIE_MAX_AGE = 720 * 60 * 60;\n//#endregion\nexport { TRUST_DEVICE_COOKIE_MAX_AGE, TRUST_DEVICE_COOKIE_NAME, TWO_FACTOR_COOKIE_NAME };\n", "import { parseUserOutput } from \"../../db/schema.mjs\";\nimport { generateRandomString } from \"../../crypto/random.mjs\";\nimport { expireCookie, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { getSessionFromCtx } from \"../../api/routes/session.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"./error-code.mjs\";\nimport { TRUST_DEVICE_COOKIE_NAME, TWO_FACTOR_COOKIE_NAME } from \"./constant.mjs\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\n//#region src/plugins/two-factor/verify-two-factor.ts\nasync function verifyTwoFactor(ctx) {\n\tconst invalid = (errorKey) => {\n\t\tthrow APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES[errorKey]);\n\t};\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) {\n\t\tconst twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME);\n\t\tconst signedTwoFactorCookie = await ctx.getSignedCookie(twoFactorCookie.name, ctx.context.secret);\n\t\tif (!signedTwoFactorCookie) throw APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE);\n\t\tconst verificationToken = await ctx.context.internalAdapter.findVerificationValue(signedTwoFactorCookie);\n\t\tif (!verificationToken) throw APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE);\n\t\tconst user = await ctx.context.internalAdapter.findUserById(verificationToken.value);\n\t\tif (!user) throw APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE);\n\t\tconst dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);\n\t\treturn {\n\t\t\tvalid: async (ctx) => {\n\t\t\t\tconst session = await ctx.context.internalAdapter.createSession(verificationToken.value, !!dontRememberMe);\n\t\t\t\tif (!session) throw APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\t\t\t\tmessage: \"failed to create session\",\n\t\t\t\t\tcode: \"FAILED_TO_CREATE_SESSION\"\n\t\t\t\t});\n\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(signedTwoFactorCookie);\n\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\tsession,\n\t\t\t\t\tuser\n\t\t\t\t});\n\t\t\t\texpireCookie(ctx, twoFactorCookie);\n\t\t\t\tif (ctx.body.trustDevice) {\n\t\t\t\t\tconst maxAge = ctx.context.getPlugin(\"two-factor\").options?.trustDeviceMaxAge ?? 2592e3;\n\t\t\t\t\tconst trustDeviceCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge });\n\t\t\t\t\t/**\n\t\t\t\t\t* Create a random identifier for the trust device record.\n\t\t\t\t\t* Store it in the verification table with an expiration\n\t\t\t\t\t* so the server can validate and revoke it.\n\t\t\t\t\t*/\n\t\t\t\t\tconst trustIdentifier = `trust-device-${generateRandomString(32)}`;\n\t\t\t\t\tconst token = await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, `${user.id}!${trustIdentifier}`);\n\t\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\t\tvalue: user.id,\n\t\t\t\t\t\tidentifier: trustIdentifier,\n\t\t\t\t\t\texpiresAt: new Date(Date.now() + maxAge * 1e3)\n\t\t\t\t\t});\n\t\t\t\t\tawait ctx.setSignedCookie(trustDeviceCookie.name, `${token}!${trustIdentifier}`, ctx.context.secret, trustDeviceCookie.attributes);\n\t\t\t\t\texpireCookie(ctx, ctx.context.authCookies.dontRememberToken);\n\t\t\t\t}\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttoken: session.token,\n\t\t\t\t\tuser: parseUserOutput(ctx.context.options, user)\n\t\t\t\t});\n\t\t\t},\n\t\t\tinvalid,\n\t\t\tsession: {\n\t\t\t\tsession: null,\n\t\t\t\tuser\n\t\t\t},\n\t\t\tkey: signedTwoFactorCookie\n\t\t};\n\t}\n\treturn {\n\t\tvalid: async (ctx) => {\n\t\t\treturn ctx.json({\n\t\t\t\ttoken: session.session.token,\n\t\t\t\tuser: parseUserOutput(ctx.context.options, session.user)\n\t\t\t});\n\t\t},\n\t\tinvalid,\n\t\tsession,\n\t\tkey: `${session.user.id}!${session.session.id}`\n\t};\n}\n//#endregion\nexport { verifyTwoFactor };\n", "import { parseUserOutput } from \"../../../db/schema.mjs\";\nimport { generateRandomString } from \"../../../crypto/random.mjs\";\nimport { symmetricDecrypt, symmetricEncrypt } from \"../../../crypto/index.mjs\";\nimport { sessionMiddleware } from \"../../../api/routes/session.mjs\";\nimport { shouldRequirePassword } from \"../../../utils/password.mjs\";\nimport { PACKAGE_VERSION } from \"../../../version.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"../error-code.mjs\";\nimport { verifyTwoFactor } from \"../verify-two-factor.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/two-factor/backup-codes/index.ts\nfunction generateBackupCodesFn(options) {\n\treturn Array.from({ length: options?.amount ?? 10 }).fill(null).map(() => generateRandomString(options?.length ?? 10, \"a-z\", \"0-9\", \"A-Z\")).map((code) => `${code.slice(0, 5)}-${code.slice(5)}`);\n}\nasync function generateBackupCodes(secret, options) {\n\tconst backupCodes = options?.customBackupCodesGenerate ? options.customBackupCodesGenerate() : generateBackupCodesFn(options);\n\tif (options?.storeBackupCodes === \"encrypted\") return {\n\t\tbackupCodes,\n\t\tencryptedBackupCodes: await symmetricEncrypt({\n\t\t\tdata: JSON.stringify(backupCodes),\n\t\t\tkey: secret\n\t\t})\n\t};\n\tif (typeof options?.storeBackupCodes === \"object\" && \"encrypt\" in options?.storeBackupCodes) return {\n\t\tbackupCodes,\n\t\tencryptedBackupCodes: await options?.storeBackupCodes.encrypt(JSON.stringify(backupCodes))\n\t};\n\treturn {\n\t\tbackupCodes,\n\t\tencryptedBackupCodes: JSON.stringify(backupCodes)\n\t};\n}\nasync function verifyBackupCode(data, key, options) {\n\tconst codes = await getBackupCodes(data.backupCodes, key, options);\n\tif (!codes) return {\n\t\tstatus: false,\n\t\tupdated: null\n\t};\n\treturn {\n\t\tstatus: codes.includes(data.code),\n\t\tupdated: codes.filter((code) => code !== data.code)\n\t};\n}\nasync function getBackupCodes(backupCodes, key, options) {\n\tif (options?.storeBackupCodes === \"encrypted\") return safeJSONParse(await symmetricDecrypt({\n\t\tkey,\n\t\tdata: backupCodes\n\t}));\n\tif (typeof options?.storeBackupCodes === \"object\" && \"decrypt\" in options?.storeBackupCodes) return safeJSONParse(await options?.storeBackupCodes.decrypt(backupCodes));\n\treturn safeJSONParse(backupCodes);\n}\nconst verifyBackupCodeBodySchema = z.object({\n\tcode: z.string().meta({ description: `A backup code to verify. Eg: \"123456\"` }),\n\tdisableSession: z.boolean().meta({ description: \"If true, the session cookie will not be set.\" }).optional(),\n\ttrustDevice: z.boolean().meta({ description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\" }).optional()\n});\nconst viewBackupCodesBodySchema = z.object({ userId: z.coerce.string().meta({ description: `The user ID to view all backup codes. Eg: \"user-id\"` }) });\nconst backupCode2fa = (opts) => {\n\tconst twoFactorTable = \"twoFactor\";\n\tconst passwordSchema = z.string().meta({ description: \"The users password.\" });\n\tconst generateBackupCodesBodySchema = opts.allowPasswordless ? z.object({ password: passwordSchema.optional() }) : z.object({ password: passwordSchema });\n\treturn {\n\t\tid: \"backup_code\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\tverifyBackupCode: createAuthEndpoint(\"/two-factor/verify-backup-code\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: verifyBackupCodeBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tdescription: \"Verify a backup code for two-factor authentication\",\n\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\tdescription: \"Backup code verified successfully\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Unique identifier of the user\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's email address\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temailVerified: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the email is verified\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's name\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\timage: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's profile image URL\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\ttwoFactorEnabled: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Whether two-factor authentication is enabled for the user\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the user was created\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the user was last updated\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\t\t\t\"twoFactorEnabled\",\n\t\t\t\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdescription: \"The authenticated user object with two-factor details\"\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Session token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tuserId: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"ID of the user associated with the session\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the session was created\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\texpiresAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the session expires\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\t\"token\",\n\t\t\t\t\t\t\t\t\t\t\"userId\",\n\t\t\t\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\t\t\t\"expiresAt\"\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdescription: \"The current session object, included unless disableSession is true\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\trequired: [\"user\", \"session\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst { session, valid } = await verifyTwoFactor(ctx);\n\t\t\t\tconst user = session.user;\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED);\n\t\t\t\tconst validate = await verifyBackupCode({\n\t\t\t\t\tbackupCodes: twoFactor.backupCodes,\n\t\t\t\t\tcode: ctx.body.code\n\t\t\t\t}, ctx.context.secretConfig, opts);\n\t\t\t\tif (!validate.status) throw APIError.from(\"UNAUTHORIZED\", TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE);\n\t\t\t\tconst updatedBackupCodes = await symmetricEncrypt({\n\t\t\t\t\tkey: ctx.context.secretConfig,\n\t\t\t\t\tdata: JSON.stringify(validate.updated)\n\t\t\t\t});\n\t\t\t\tif (!await ctx.context.adapter.update({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\tupdate: { backupCodes: updatedBackupCodes },\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\tvalue: twoFactor.id\n\t\t\t\t\t}, {\n\t\t\t\t\t\tfield: \"backupCodes\",\n\t\t\t\t\t\tvalue: twoFactor.backupCodes\n\t\t\t\t\t}]\n\t\t\t\t})) throw APIError.fromStatus(\"CONFLICT\", { message: \"Failed to verify backup code. Please try again.\" });\n\t\t\t\tif (!ctx.body.disableSession) return valid(ctx);\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttoken: session.session?.token,\n\t\t\t\t\tuser: parseUserOutput(ctx.context.options, session.user)\n\t\t\t\t});\n\t\t\t}),\n\t\t\tgenerateBackupCodes: createAuthEndpoint(\"/two-factor/generate-backup-codes\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: generateBackupCodesBodySchema,\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tdescription: \"Generate new backup codes for two-factor authentication\",\n\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\tdescription: \"Backup codes generated successfully\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\tdescription: \"Indicates if the backup codes were generated successfully\",\n\t\t\t\t\t\t\t\t\tenum: [true]\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbackupCodes: {\n\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\t\t\tdescription: \"Array of generated backup codes in plain text\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\trequired: [\"status\", \"backupCodes\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst user = ctx.context.session.user;\n\t\t\t\tif (!user.twoFactorEnabled) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED);\n\t\t\t\tif (await shouldRequirePassword(ctx, user.id, opts.allowPasswordless)) {\n\t\t\t\t\tif (!ctx.body.password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t\tawait ctx.context.password.checkPassword(user.id, ctx);\n\t\t\t\t}\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED);\n\t\t\t\tconst backupCodes = await generateBackupCodes(ctx.context.secretConfig, opts);\n\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\tupdate: { backupCodes: backupCodes.encryptedBackupCodes },\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\tvalue: twoFactor.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\treturn ctx.json({\n\t\t\t\t\tstatus: true,\n\t\t\t\t\tbackupCodes: backupCodes.backupCodes\n\t\t\t\t});\n\t\t\t}),\n\t\t\tviewBackupCodes: createAuthEndpoint({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: viewBackupCodesBodySchema\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: ctx.body.userId\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED);\n\t\t\t\tconst decryptedBackupCodes = await getBackupCodes(twoFactor.backupCodes, ctx.context.secretConfig, opts);\n\t\t\t\tif (!decryptedBackupCodes) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE);\n\t\t\t\treturn ctx.json({\n\t\t\t\t\tstatus: true,\n\t\t\t\t\tbackupCodes: decryptedBackupCodes\n\t\t\t\t});\n\t\t\t})\n\t\t}\n\t};\n};\n//#endregion\nexport { backupCode2fa, generateBackupCodes };\n", "import { base64Url } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\n//#region src/plugins/two-factor/utils.ts\nconst defaultKeyHasher = async (token) => {\n\tconst hash = await createHash(\"SHA-256\").digest(new TextEncoder().encode(token));\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n};\n//#endregion\nexport { defaultKeyHasher };\n", "import { parseUserOutput } from \"../../../db/schema.mjs\";\nimport { constantTimeEqual } from \"../../../crypto/buffer.mjs\";\nimport { generateRandomString } from \"../../../crypto/random.mjs\";\nimport { symmetricDecrypt, symmetricEncrypt } from \"../../../crypto/index.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { PACKAGE_VERSION } from \"../../../version.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"../error-code.mjs\";\nimport { verifyTwoFactor } from \"../verify-two-factor.mjs\";\nimport { defaultKeyHasher } from \"../utils.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/two-factor/otp/index.ts\nconst verifyOTPBodySchema = z.object({\n\tcode: z.string().meta({ description: \"The otp code to verify. Eg: \\\"012345\\\"\" }),\n\ttrustDevice: z.boolean().optional().meta({ description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\" })\n});\nconst send2FaOTPBodySchema = z.object({ trustDevice: z.boolean().optional().meta({ description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\" }) }).optional();\n/**\n* The otp adapter is created from the totp adapter.\n*/\nconst otp2fa = (options) => {\n\tconst opts = {\n\t\tstoreOTP: \"plain\",\n\t\tdigits: 6,\n\t\t...options,\n\t\tperiod: (options?.period || 3) * 60 * 1e3\n\t};\n\tasync function storeOTP(ctx, otp) {\n\t\tif (opts.storeOTP === \"hashed\") return await defaultKeyHasher(otp);\n\t\tif (typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) return await opts.storeOTP.hash(otp);\n\t\tif (typeof opts.storeOTP === \"object\" && \"encrypt\" in opts.storeOTP) return await opts.storeOTP.encrypt(otp);\n\t\tif (opts.storeOTP === \"encrypted\") return await symmetricEncrypt({\n\t\t\tkey: ctx.context.secretConfig,\n\t\t\tdata: otp\n\t\t});\n\t\treturn otp;\n\t}\n\tasync function decryptOrHashForComparison(ctx, storedOtp, userInput) {\n\t\tif (opts.storeOTP === \"hashed\") return [storedOtp, await defaultKeyHasher(userInput)];\n\t\tif (opts.storeOTP === \"encrypted\") return [await symmetricDecrypt({\n\t\t\tkey: ctx.context.secretConfig,\n\t\t\tdata: storedOtp\n\t\t}), userInput];\n\t\tif (typeof opts.storeOTP === \"object\" && \"encrypt\" in opts.storeOTP) return [await opts.storeOTP.decrypt(storedOtp), userInput];\n\t\tif (typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) return [storedOtp, await opts.storeOTP.hash(userInput)];\n\t\treturn [storedOtp, userInput];\n\t}\n\treturn {\n\t\tid: \"otp\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\tsendTwoFactorOTP: createAuthEndpoint(\"/two-factor/send-otp\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: send2FaOTPBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Send two factor OTP\",\n\t\t\t\t\tdescription: \"Send two factor OTP to the user\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (!options || !options.sendOTP) {\n\t\t\t\t\tctx.context.logger.error(\"send otp isn't configured. Please configure the send otp function on otp options.\");\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"otp isn't configured\",\n\t\t\t\t\t\tcode: \"OTP_NOT_CONFIGURED\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst { session, key } = await verifyTwoFactor(ctx);\n\t\t\t\tconst code = generateRandomString(opts.digits, \"0-9\");\n\t\t\t\tconst hashedCode = await storeOTP(ctx, code);\n\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\tvalue: `${hashedCode}:0`,\n\t\t\t\t\tidentifier: `2fa-otp-${key}`,\n\t\t\t\t\texpiresAt: new Date(Date.now() + opts.period)\n\t\t\t\t});\n\t\t\t\tconst sendOTPResult = options.sendOTP({\n\t\t\t\t\tuser: session.user,\n\t\t\t\t\totp: code\n\t\t\t\t}, ctx);\n\t\t\t\tif (sendOTPResult instanceof Promise) await ctx.context.runInBackgroundOrAwait(sendOTPResult.catch((e) => {\n\t\t\t\t\tctx.context.logger.error(\"Failed to send two-factor OTP\", e);\n\t\t\t\t}));\n\t\t\t\treturn ctx.json({ status: true });\n\t\t\t}),\n\t\t\tverifyTwoFactorOTP: createAuthEndpoint(\"/two-factor/verify-otp\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: verifyOTPBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Verify two factor OTP\",\n\t\t\t\t\tdescription: \"Verify two factor OTP\",\n\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\tdescription: \"Two-factor OTP verified successfully\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\tdescription: \"Session token for the authenticated session\"\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Unique identifier of the user\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's email address\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temailVerified: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the email is verified\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's name\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\timage: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's profile image URL\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the user was created\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tupdatedAt: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"date-time\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Timestamp when the user was last updated\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\t\"id\",\n\t\t\t\t\t\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\t\t\t\t\t\"updatedAt\"\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdescription: \"The authenticated user object\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\trequired: [\"token\", \"user\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst { session, key, valid, invalid } = await verifyTwoFactor(ctx);\n\t\t\t\tconst toCheckOtp = await ctx.context.internalAdapter.findVerificationValue(`2fa-otp-${key}`);\n\t\t\t\tconst [otp, counter] = toCheckOtp?.value?.split(\":\") ?? [];\n\t\t\t\tif (!toCheckOtp || toCheckOtp.expiresAt < /* @__PURE__ */ new Date()) {\n\t\t\t\t\tif (toCheckOtp) await ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`);\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.OTP_HAS_EXPIRED);\n\t\t\t\t}\n\t\t\t\tconst allowedAttempts = options?.allowedAttempts || 5;\n\t\t\t\tif (parseInt(counter) >= allowedAttempts) {\n\t\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`);\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE);\n\t\t\t\t}\n\t\t\t\tconst [storedValue, inputValue] = await decryptOrHashForComparison(ctx, otp, ctx.body.code);\n\t\t\t\tif (constantTimeEqual(new TextEncoder().encode(storedValue), new TextEncoder().encode(inputValue))) {\n\t\t\t\t\tif (!session.user.twoFactorEnabled) {\n\t\t\t\t\t\tif (!session.session) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);\n\t\t\t\t\t\tconst updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { twoFactorEnabled: true });\n\t\t\t\t\t\tconst newSession = await ctx.context.internalAdapter.createSession(session.user.id, false, session.session);\n\t\t\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\t\t\tsession: newSession,\n\t\t\t\t\t\t\tuser: updatedUser\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait ctx.context.internalAdapter.deleteSession(session.session.token);\n\t\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\t\ttoken: newSession.token,\n\t\t\t\t\t\t\tuser: parseUserOutput(ctx.context.options, updatedUser)\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\treturn valid(ctx);\n\t\t\t\t} else {\n\t\t\t\t\tawait ctx.context.internalAdapter.updateVerificationByIdentifier(`2fa-otp-${key}`, { value: `${otp}:${(parseInt(counter, 10) || 0) + 1}` });\n\t\t\t\t\treturn invalid(\"INVALID_CODE\");\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t};\n};\n//#endregion\nexport { otp2fa };\n", "//#region src/plugins/two-factor/schema.ts\nconst schema = {\n\tuser: { fields: { twoFactorEnabled: {\n\t\ttype: \"boolean\",\n\t\trequired: false,\n\t\tdefaultValue: false,\n\t\tinput: false\n\t} } },\n\ttwoFactor: { fields: {\n\t\tsecret: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\treturned: false,\n\t\t\tindex: true\n\t\t},\n\t\tbackupCodes: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\treturned: false\n\t\t},\n\t\tuserId: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\treturned: false,\n\t\t\treferences: {\n\t\t\t\tmodel: \"user\",\n\t\t\t\tfield: \"id\"\n\t\t\t},\n\t\t\tindex: true\n\t\t},\n\t\tverified: {\n\t\t\ttype: \"boolean\",\n\t\t\trequired: false,\n\t\t\tdefaultValue: true,\n\t\t\tinput: false\n\t\t}\n\t} }\n};\n//#endregion\nexport { schema };\n", "import { symmetricDecrypt } from \"../../../crypto/index.mjs\";\nimport { setSessionCookie } from \"../../../cookies/index.mjs\";\nimport { sessionMiddleware } from \"../../../api/routes/session.mjs\";\nimport { shouldRequirePassword } from \"../../../utils/password.mjs\";\nimport { PACKAGE_VERSION } from \"../../../version.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"../error-code.mjs\";\nimport { verifyTwoFactor } from \"../verify-two-factor.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\nimport { createOTP } from \"@better-auth/utils/otp\";\n//#region src/plugins/two-factor/totp/index.ts\nconst generateTOTPBodySchema = z.object({ secret: z.string().meta({ description: \"The secret to generate the TOTP code\" }) });\nconst verifyTOTPBodySchema = z.object({\n\tcode: z.string().meta({ description: \"The otp code to verify. Eg: \\\"012345\\\"\" }),\n\ttrustDevice: z.boolean().meta({ description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\" }).optional()\n});\nconst totp2fa = (options) => {\n\tconst opts = {\n\t\t...options,\n\t\tdigits: options?.digits || 6,\n\t\tperiod: options?.period || 30\n\t};\n\tconst passwordSchema = z.string().meta({ description: \"User password\" });\n\tconst getTOTPURIBodySchema = options?.allowPasswordless ? z.object({ password: passwordSchema.optional() }) : z.object({ password: passwordSchema });\n\tconst twoFactorTable = \"twoFactor\";\n\treturn {\n\t\tid: \"totp\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\tgenerateTOTP: createAuthEndpoint({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: generateTOTPBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Generate TOTP code\",\n\t\t\t\t\tdescription: \"Use this endpoint to generate a TOTP code\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { code: { type: \"string\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (options?.disable) {\n\t\t\t\t\tctx.context.logger.error(\"totp isn't configured. please pass totp option on two factor plugin to enable totp\");\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"totp isn't configured\",\n\t\t\t\t\t\tcode: \"TOTP_NOT_CONFIGURED\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { code: await createOTP(ctx.body.secret, {\n\t\t\t\t\tperiod: opts.period,\n\t\t\t\t\tdigits: opts.digits\n\t\t\t\t}).totp() };\n\t\t\t}),\n\t\t\tgetTOTPURI: createAuthEndpoint(\"/two-factor/get-totp-uri\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tbody: getTOTPURIBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Get TOTP URI\",\n\t\t\t\t\tdescription: \"Use this endpoint to get the TOTP URI\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { totpURI: { type: \"string\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (options?.disable) {\n\t\t\t\t\tctx.context.logger.error(\"totp isn't configured. please pass totp option on two factor plugin to enable totp\");\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"totp isn't configured\",\n\t\t\t\t\t\tcode: \"TOTP_NOT_CONFIGURED\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst user = ctx.context.session.user;\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED);\n\t\t\t\tconst secret = await symmetricDecrypt({\n\t\t\t\t\tkey: ctx.context.secretConfig,\n\t\t\t\t\tdata: twoFactor.secret\n\t\t\t\t});\n\t\t\t\tif (await shouldRequirePassword(ctx, user.id, options?.allowPasswordless)) {\n\t\t\t\t\tif (!ctx.body.password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t\tawait ctx.context.password.checkPassword(user.id, ctx);\n\t\t\t\t}\n\t\t\t\treturn { totpURI: createOTP(secret, {\n\t\t\t\t\tdigits: opts.digits,\n\t\t\t\t\tperiod: opts.period\n\t\t\t\t}).url(options?.issuer || ctx.context.appName, user.email) };\n\t\t\t}),\n\t\t\tverifyTOTP: createAuthEndpoint(\"/two-factor/verify-totp\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: verifyTOTPBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Verify two factor TOTP\",\n\t\t\t\t\tdescription: \"Verify two factor TOTP\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (options?.disable) {\n\t\t\t\t\tctx.context.logger.error(\"totp isn't configured. please pass totp option on two factor plugin to enable totp\");\n\t\t\t\t\tthrow APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"totp isn't configured\",\n\t\t\t\t\t\tcode: \"TOTP_NOT_CONFIGURED\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst { session, valid, invalid } = await verifyTwoFactor(ctx);\n\t\t\t\tconst user = session.user;\n\t\t\t\tconst isSignIn = !session.session;\n\t\t\t\tconst twoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tif (!twoFactor) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED);\n\t\t\t\tif (isSignIn && twoFactor.verified === false) throw APIError.from(\"BAD_REQUEST\", TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED);\n\t\t\t\tif (!await createOTP(await symmetricDecrypt({\n\t\t\t\t\tkey: ctx.context.secretConfig,\n\t\t\t\t\tdata: twoFactor.secret\n\t\t\t\t}), {\n\t\t\t\t\tperiod: opts.period,\n\t\t\t\t\tdigits: opts.digits\n\t\t\t\t}).verify(ctx.body.code)) return invalid(\"INVALID_CODE\");\n\t\t\t\tif (twoFactor.verified !== true) {\n\t\t\t\t\tif (!user.twoFactorEnabled) {\n\t\t\t\t\t\tconst activeSession = session.session;\n\t\t\t\t\t\tconst updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: true });\n\t\t\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\t\t\tsession: await ctx.context.internalAdapter.createSession(user.id, false, activeSession),\n\t\t\t\t\t\t\tuser: updatedUser\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait ctx.context.internalAdapter.deleteSession(activeSession.token);\n\t\t\t\t\t}\n\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\tmodel: twoFactorTable,\n\t\t\t\t\t\tupdate: { verified: true },\n\t\t\t\t\t\twhere: [{\n\t\t\t\t\t\t\tfield: \"id\",\n\t\t\t\t\t\t\tvalue: twoFactor.id\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn valid(ctx);\n\t\t\t})\n\t\t}\n\t};\n};\n//#endregion\nexport { totp2fa };\n", "function getAlphabet(hex) {\n return hex ? \"0123456789ABCDEFGHIJKLMNOPQRSTUV\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n}\nfunction createDecodeMap(alphabet) {\n const decodeMap = /* @__PURE__ */ new Map();\n for (let i = 0; i < alphabet.length; i++) {\n decodeMap.set(alphabet[i], i);\n }\n return decodeMap;\n}\nfunction base32Encode(data, alphabet, padding) {\n let result = \"\";\n let buffer = 0;\n let shift = 0;\n for (const byte of data) {\n buffer = buffer << 8 | byte;\n shift += 8;\n while (shift >= 5) {\n shift -= 5;\n result += alphabet[buffer >> shift & 31];\n }\n }\n if (shift > 0) {\n result += alphabet[buffer << 5 - shift & 31];\n }\n if (padding) {\n const padCount = (8 - result.length % 8) % 8;\n result += \"=\".repeat(padCount);\n }\n return result;\n}\nfunction base32Decode(data, alphabet) {\n const decodeMap = createDecodeMap(alphabet);\n const result = [];\n let buffer = 0;\n let bitsCollected = 0;\n for (const char of data) {\n if (char === \"=\")\n break;\n const value = decodeMap.get(char);\n if (value === void 0) {\n throw new Error(`Invalid Base32 character: ${char}`);\n }\n buffer = buffer << 5 | value;\n bitsCollected += 5;\n while (bitsCollected >= 8) {\n bitsCollected -= 8;\n result.push(buffer >> bitsCollected & 255);\n }\n }\n return Uint8Array.from(result);\n}\nconst base32 = {\n /**\n * Encodes data into a Base32 string.\n * @param data - The data to encode (ArrayBuffer, TypedArray, or string).\n * @param options - Encoding options.\n * @returns The Base32 encoded string.\n */\n encode(data, options = {}) {\n const alphabet = getAlphabet(false);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base32Encode(buffer, alphabet, options.padding ?? true);\n },\n /**\n * Decodes a Base32 string into a Uint8Array.\n * @param data - The Base32 encoded string or ArrayBuffer/TypedArray.\n * @returns The decoded Uint8Array.\n */\n decode(data) {\n if (typeof data !== \"string\") {\n data = new TextDecoder().decode(data);\n }\n const alphabet = getAlphabet(false);\n return base32Decode(data, alphabet);\n }\n};\nconst base32hex = {\n /**\n * Encodes data into a Base32hex string.\n * @param data - The data to encode (ArrayBuffer, TypedArray, or string).\n * @param options - Encoding options.\n * @returns The Base32hex encoded string.\n */\n encode(data, options = {}) {\n const alphabet = getAlphabet(true);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base32Encode(buffer, alphabet, options.padding ?? true);\n },\n /**\n * Decodes a Base32hex string into a Uint8Array.\n * @param data - The Base32hex encoded string.\n * @returns The decoded Uint8Array.\n */\n decode(data) {\n const alphabet = getAlphabet(true);\n return base32Decode(data, alphabet);\n }\n};\n\nexport { base32, base32hex };\n", "import { base32 } from './base32.mjs';\nimport { createHMAC } from './hmac.mjs';\nimport './hex.mjs';\nimport './base64.mjs';\nimport './index.mjs';\n\nconst defaultPeriod = 30;\nconst defaultDigits = 6;\nasync function generateHOTP(secret, {\n counter,\n digits,\n hash = \"SHA-1\"\n}) {\n const _digits = digits ?? defaultDigits;\n if (_digits < 1 || _digits > 8) {\n throw new TypeError(\"Digits must be between 1 and 8\");\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigUint64(0, BigInt(counter), false);\n const bytes = new Uint8Array(buffer);\n const hmacResult = new Uint8Array(await createHMAC(hash).sign(secret, bytes));\n const offset = hmacResult[hmacResult.length - 1] & 15;\n const truncated = (hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255;\n const otp = truncated % 10 ** _digits;\n return otp.toString().padStart(_digits, \"0\");\n}\nasync function generateTOTP(secret, options) {\n const digits = options?.digits ?? defaultDigits;\n const period = options?.period ?? defaultPeriod;\n const milliseconds = period * 1e3;\n const counter = Math.floor(Date.now() / milliseconds);\n return await generateHOTP(secret, { counter, digits, hash: options?.hash });\n}\nasync function verifyTOTP(otp, {\n window = 1,\n digits = defaultDigits,\n secret,\n period = defaultPeriod\n}) {\n const milliseconds = period * 1e3;\n const counter = Math.floor(Date.now() / milliseconds);\n for (let i = -window; i <= window; i++) {\n const generatedOTP = await generateHOTP(secret, {\n counter: counter + i,\n digits\n });\n if (otp === generatedOTP) {\n return true;\n }\n }\n return false;\n}\nfunction generateQRCode({\n issuer,\n account,\n secret,\n digits = defaultDigits,\n period = defaultPeriod\n}) {\n const encodedIssuer = encodeURIComponent(issuer);\n const encodedAccountName = encodeURIComponent(account);\n const baseURI = `otpauth://totp/${encodedIssuer}:${encodedAccountName}`;\n const params = new URLSearchParams({\n secret: base32.encode(secret, {\n padding: false\n }),\n issuer\n });\n if (digits !== void 0) {\n params.set(\"digits\", digits.toString());\n }\n if (period !== void 0) {\n params.set(\"period\", period.toString());\n }\n return `${baseURI}?${params.toString()}`;\n}\nconst createOTP = (secret, opts) => {\n const digits = opts?.digits ?? defaultDigits;\n const period = opts?.period ?? defaultPeriod;\n return {\n hotp: (counter) => generateHOTP(secret, { counter, digits }),\n totp: () => generateTOTP(secret, { digits, period }),\n verify: (otp, options) => verifyTOTP(otp, { secret, digits, period, ...options }),\n url: (issuer, account) => generateQRCode({ issuer, account, secret, digits, period })\n };\n};\n\nexport { createOTP };\n", "import { mergeSchema } from \"../../db/schema.mjs\";\nimport { generateRandomString } from \"../../crypto/random.mjs\";\nimport { symmetricEncrypt } from \"../../crypto/index.mjs\";\nimport { deleteSessionCookie, expireCookie, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { sessionMiddleware } from \"../../api/routes/session.mjs\";\nimport { shouldRequirePassword, validatePassword } from \"../../utils/password.mjs\";\nimport { PACKAGE_VERSION } from \"../../version.mjs\";\nimport { TWO_FACTOR_ERROR_CODES } from \"./error-code.mjs\";\nimport { twoFactorClient } from \"./client.mjs\";\nimport { TRUST_DEVICE_COOKIE_NAME, TWO_FACTOR_COOKIE_NAME } from \"./constant.mjs\";\nimport { backupCode2fa, generateBackupCodes } from \"./backup-codes/index.mjs\";\nimport { otp2fa } from \"./otp/index.mjs\";\nimport { schema } from \"./schema.mjs\";\nimport { totp2fa } from \"./totp/index.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint, createAuthMiddleware } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\nimport { createOTP } from \"@better-auth/utils/otp\";\n//#region src/plugins/two-factor/index.ts\nconst twoFactor = (options) => {\n\tconst opts = { twoFactorTable: \"twoFactor\" };\n\tconst trustDeviceMaxAge = options?.trustDeviceMaxAge ?? 2592e3;\n\tconst allowPasswordless = options?.allowPasswordless;\n\tconst backupCodeOptions = {\n\t\tstoreBackupCodes: \"encrypted\",\n\t\t...options?.backupCodeOptions\n\t};\n\tconst totp = totp2fa({\n\t\t...options?.totpOptions,\n\t\tallowPasswordless: options?.totpOptions?.allowPasswordless ?? allowPasswordless\n\t});\n\tconst backupCode = backupCode2fa({\n\t\t...backupCodeOptions,\n\t\tallowPasswordless: options?.backupCodeOptions?.allowPasswordless ?? allowPasswordless\n\t});\n\tconst otp = otp2fa(options?.otpOptions);\n\tconst passwordSchema = z.string().meta({ description: \"User password\" });\n\tconst enableTwoFactorBodySchema = allowPasswordless ? z.object({\n\t\tpassword: passwordSchema.optional(),\n\t\tissuer: z.string().meta({ description: \"Custom issuer for the TOTP URI\" }).optional()\n\t}) : z.object({\n\t\tpassword: passwordSchema,\n\t\tissuer: z.string().meta({ description: \"Custom issuer for the TOTP URI\" }).optional()\n\t});\n\tconst disableTwoFactorBodySchema = allowPasswordless ? z.object({ password: passwordSchema.optional() }) : z.object({ password: passwordSchema });\n\treturn {\n\t\tid: \"two-factor\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\t...totp.endpoints,\n\t\t\t...otp.endpoints,\n\t\t\t...backupCode.endpoints,\n\t\t\tenableTwoFactor: createAuthEndpoint(\"/two-factor/enable\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: enableTwoFactorBodySchema,\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Enable two factor authentication\",\n\t\t\t\t\tdescription: \"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\ttotpURI: {\n\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\tdescription: \"TOTP URI\"\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbackupCodes: {\n\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\t\t\tdescription: \"Backup codes\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst user = ctx.context.session.user;\n\t\t\t\tconst { password, issuer } = ctx.body;\n\t\t\t\tif (await shouldRequirePassword(ctx, user.id, allowPasswordless)) {\n\t\t\t\t\tif (!password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t\tif (!await validatePassword(ctx, {\n\t\t\t\t\t\tpassword,\n\t\t\t\t\t\tuserId: user.id\n\t\t\t\t\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t}\n\t\t\t\tconst secret = generateRandomString(32);\n\t\t\t\tconst encryptedSecret = await symmetricEncrypt({\n\t\t\t\t\tkey: ctx.context.secretConfig,\n\t\t\t\t\tdata: secret\n\t\t\t\t});\n\t\t\t\tconst backupCodes = await generateBackupCodes(ctx.context.secretConfig, backupCodeOptions);\n\t\t\t\tif (options?.skipVerificationOnEnable) {\n\t\t\t\t\tconst updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: true });\n\t\t\t\t\t/**\n\t\t\t\t\t* Update the session cookie with the new user data\n\t\t\t\t\t*/\n\t\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\t\tsession: await ctx.context.internalAdapter.createSession(updatedUser.id, false, ctx.context.session.session),\n\t\t\t\t\t\tuser: updatedUser\n\t\t\t\t\t});\n\t\t\t\t\tawait ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token);\n\t\t\t\t}\n\t\t\t\tconst existingTwoFactor = await ctx.context.adapter.findOne({\n\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tawait ctx.context.adapter.deleteMany({\n\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: user.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\tawait ctx.context.adapter.create({\n\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tsecret: encryptedSecret,\n\t\t\t\t\t\tbackupCodes: backupCodes.encryptedBackupCodes,\n\t\t\t\t\t\tuserId: user.id,\n\t\t\t\t\t\tverified: existingTwoFactor != null && existingTwoFactor.verified !== false || !!options?.skipVerificationOnEnable\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tconst totpURI = createOTP(secret, {\n\t\t\t\t\tdigits: options?.totpOptions?.digits || 6,\n\t\t\t\t\tperiod: options?.totpOptions?.period\n\t\t\t\t}).url(issuer || options?.issuer || ctx.context.appName, user.email);\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttotpURI,\n\t\t\t\t\tbackupCodes: backupCodes.backupCodes\n\t\t\t\t});\n\t\t\t}),\n\t\t\tdisableTwoFactor: createAuthEndpoint(\"/two-factor/disable\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: disableTwoFactorBodySchema,\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tsummary: \"Disable two factor authentication\",\n\t\t\t\t\tdescription: \"Use this endpoint to disable two factor authentication.\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Successful response\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst user = ctx.context.session.user;\n\t\t\t\tconst { password } = ctx.body;\n\t\t\t\tif (await shouldRequirePassword(ctx, user.id, allowPasswordless)) {\n\t\t\t\t\tif (!password) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t\tif (!await validatePassword(ctx, {\n\t\t\t\t\t\tpassword,\n\t\t\t\t\t\tuserId: user.id\n\t\t\t\t\t})) throw APIError.from(\"BAD_REQUEST\", BASE_ERROR_CODES.INVALID_PASSWORD);\n\t\t\t\t}\n\t\t\t\tconst updatedUser = await ctx.context.internalAdapter.updateUser(user.id, { twoFactorEnabled: false });\n\t\t\t\tawait ctx.context.adapter.delete({\n\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\twhere: [{\n\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\tvalue: updatedUser.id\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t\t/**\n\t\t\t\t* Update the session cookie with the new user data\n\t\t\t\t*/\n\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\tsession: await ctx.context.internalAdapter.createSession(updatedUser.id, false, ctx.context.session.session),\n\t\t\t\t\tuser: updatedUser\n\t\t\t\t});\n\t\t\t\tawait ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token);\n\t\t\t\tconst disableTrustCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });\n\t\t\t\tconst disableTrustValue = await ctx.getSignedCookie(disableTrustCookie.name, ctx.context.secret);\n\t\t\t\tif (disableTrustValue) {\n\t\t\t\t\tconst [, trustId] = disableTrustValue.split(\"!\");\n\t\t\t\t\tif (trustId) await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustId);\n\t\t\t\t\texpireCookie(ctx, disableTrustCookie);\n\t\t\t\t}\n\t\t\t\treturn ctx.json({ status: true });\n\t\t\t})\n\t\t},\n\t\toptions,\n\t\thooks: { after: [{\n\t\t\tmatcher(context) {\n\t\t\t\treturn context.path === \"/sign-in/email\" || context.path === \"/sign-in/username\" || context.path === \"/sign-in/phone-number\";\n\t\t\t},\n\t\t\thandler: createAuthMiddleware(async (ctx) => {\n\t\t\t\tconst data = ctx.context.newSession;\n\t\t\t\tif (!data) return;\n\t\t\t\tif (!data?.user.twoFactorEnabled) return;\n\t\t\t\tconst trustDeviceCookieAttrs = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });\n\t\t\t\tconst trustDeviceCookie = await ctx.getSignedCookie(trustDeviceCookieAttrs.name, ctx.context.secret);\n\t\t\t\tif (trustDeviceCookie) {\n\t\t\t\t\tconst [token, trustIdentifier] = trustDeviceCookie.split(\"!\");\n\t\t\t\t\tif (token && trustIdentifier) {\n\t\t\t\t\t\tif (token === await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, `${data.user.id}!${trustIdentifier}`)) {\n\t\t\t\t\t\t\tconst verificationRecord = await ctx.context.internalAdapter.findVerificationValue(trustIdentifier);\n\t\t\t\t\t\t\tif (verificationRecord && verificationRecord.value === data.user.id && verificationRecord.expiresAt > /* @__PURE__ */ new Date()) {\n\t\t\t\t\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(trustIdentifier);\n\t\t\t\t\t\t\t\tconst newTrustIdentifier = `trust-device-${generateRandomString(32)}`;\n\t\t\t\t\t\t\t\tconst newToken = await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, `${data.user.id}!${newTrustIdentifier}`);\n\t\t\t\t\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\t\t\t\t\tvalue: data.user.id,\n\t\t\t\t\t\t\t\t\tidentifier: newTrustIdentifier,\n\t\t\t\t\t\t\t\t\texpiresAt: new Date(Date.now() + trustDeviceMaxAge * 1e3)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst newTrustDeviceCookie = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, { maxAge: trustDeviceMaxAge });\n\t\t\t\t\t\t\t\tawait ctx.setSignedCookie(newTrustDeviceCookie.name, `${newToken}!${newTrustIdentifier}`, ctx.context.secret, trustDeviceCookieAttrs.attributes);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\texpireCookie(ctx, trustDeviceCookieAttrs);\n\t\t\t\t}\n\t\t\t\t/**\n\t\t\t\t* remove the session cookie. It's set by the sign in credential\n\t\t\t\t*/\n\t\t\t\tdeleteSessionCookie(ctx, true);\n\t\t\t\tawait ctx.context.internalAdapter.deleteSession(data.session.token);\n\t\t\t\tconst maxAge = options?.twoFactorCookieMaxAge ?? 600;\n\t\t\t\tconst twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME, { maxAge });\n\t\t\t\tconst identifier = `2fa-${generateRandomString(20)}`;\n\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\tvalue: data.user.id,\n\t\t\t\t\tidentifier,\n\t\t\t\t\texpiresAt: new Date(Date.now() + maxAge * 1e3)\n\t\t\t\t});\n\t\t\t\tawait ctx.setSignedCookie(twoFactorCookie.name, identifier, ctx.context.secret, twoFactorCookie.attributes);\n\t\t\t\tconst twoFactorMethods = [];\n\t\t\t\t/**\n\t\t\t\t* totp requires per-user setup, so we check\n\t\t\t\t* that the user actually has a secret stored.\n\t\t\t\t*/\n\t\t\t\tif (!options?.totpOptions?.disable) {\n\t\t\t\t\tconst userTotpSecret = await ctx.context.adapter.findOne({\n\t\t\t\t\t\tmodel: opts.twoFactorTable,\n\t\t\t\t\t\twhere: [{\n\t\t\t\t\t\t\tfield: \"userId\",\n\t\t\t\t\t\t\tvalue: data.user.id\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tif (userTotpSecret && userTotpSecret.verified !== false) twoFactorMethods.push(\"totp\");\n\t\t\t\t}\n\t\t\t\t/**\n\t\t\t\t* otp is server-level \u2014 if sendOTP is configured,\n\t\t\t\t* any user with 2fa enabled can receive a code.\n\t\t\t\t*/\n\t\t\t\tif (options?.otpOptions?.sendOTP) twoFactorMethods.push(\"otp\");\n\t\t\t\treturn ctx.json({\n\t\t\t\t\ttwoFactorRedirect: true,\n\t\t\t\t\ttwoFactorMethods\n\t\t\t\t});\n\t\t\t})\n\t\t}] },\n\t\tschema: mergeSchema(schema, {\n\t\t\t...options?.schema,\n\t\t\ttwoFactor: {\n\t\t\t\t...options?.schema?.twoFactor,\n\t\t\t\t...options?.twoFactorTable ? { modelName: options.twoFactorTable } : {}\n\t\t\t}\n\t\t}),\n\t\trateLimit: [{\n\t\t\tpathMatcher(path) {\n\t\t\t\treturn path.startsWith(\"/two-factor/\");\n\t\t\t},\n\t\t\twindow: 10,\n\t\t\tmax: 3\n\t\t}],\n\t\t$ERROR_CODES: TWO_FACTOR_ERROR_CODES\n\t};\n};\n//#endregion\nexport { TWO_FACTOR_ERROR_CODES, twoFactor, twoFactorClient };\n", "import { base64Url } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\n//#region src/plugins/magic-link/utils.ts\nconst defaultKeyHasher = async (otp) => {\n\tconst hash = await createHash(\"SHA-256\").digest(new TextEncoder().encode(otp));\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n};\n//#endregion\nexport { defaultKeyHasher };\n", "import { originCheck } from \"../../api/middlewares/origin-check.mjs\";\nimport { parseSessionOutput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { generateRandomString } from \"../../crypto/random.mjs\";\nimport { setSessionCookie } from \"../../cookies/index.mjs\";\nimport { PACKAGE_VERSION } from \"../../version.mjs\";\nimport { defaultKeyHasher } from \"./utils.mjs\";\nimport { createAuthEndpoint } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/plugins/magic-link/index.ts\nconst signInMagicLinkBodySchema = z.object({\n\temail: z.email().meta({ description: \"Email address to send the magic link\" }),\n\tname: z.string().meta({ description: \"User display name. Only used if the user is registering for the first time. Eg: \\\"my-name\\\"\" }).optional(),\n\tcallbackURL: z.string().meta({ description: \"URL to redirect after magic link verification\" }).optional(),\n\tnewUserCallbackURL: z.string().meta({ description: \"URL to redirect after new user signup. Only used if the user is registering for the first time.\" }).optional(),\n\terrorCallbackURL: z.string().meta({ description: \"URL to redirect after error.\" }).optional(),\n\tmetadata: z.record(z.string(), z.any()).meta({ description: \"Additional metadata to pass to sendMagicLink.\" }).optional()\n});\nconst magicLinkVerifyQuerySchema = z.object({\n\ttoken: z.string().meta({ description: \"Verification token\" }),\n\tcallbackURL: z.string().meta({ description: \"URL to redirect after magic link verification, if not provided the user will be redirected to the root URL. Eg: \\\"/dashboard\\\"\" }).optional(),\n\terrorCallbackURL: z.string().meta({ description: \"URL to redirect after error.\" }).optional(),\n\tnewUserCallbackURL: z.string().meta({ description: \"URL to redirect after new user signup. Only used if the user is registering for the first time.\" }).optional()\n});\nconst magicLink = (options) => {\n\tconst opts = {\n\t\tstoreToken: \"plain\",\n\t\tallowedAttempts: 1,\n\t\t...options\n\t};\n\tasync function storeToken(ctx, token) {\n\t\tif (opts.storeToken === \"hashed\") return await defaultKeyHasher(token);\n\t\tif (typeof opts.storeToken === \"object\" && \"type\" in opts.storeToken && opts.storeToken.type === \"custom-hasher\") return await opts.storeToken.hash(token);\n\t\treturn token;\n\t}\n\treturn {\n\t\tid: \"magic-link\",\n\t\tversion: PACKAGE_VERSION,\n\t\tendpoints: {\n\t\t\tsignInMagicLink: createAuthEndpoint(\"/sign-in/magic-link\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\trequireHeaders: true,\n\t\t\t\tbody: signInMagicLinkBodySchema,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\toperationId: \"signInWithMagicLink\",\n\t\t\t\t\tdescription: \"Sign in with magic link\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { status: { type: \"boolean\" } }\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst { email, metadata } = ctx.body;\n\t\t\t\tconst verificationToken = opts?.generateToken ? await opts.generateToken(email) : generateRandomString(32, \"a-z\", \"A-Z\");\n\t\t\t\tconst storedToken = await storeToken(ctx, verificationToken);\n\t\t\t\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t\t\t\tidentifier: storedToken,\n\t\t\t\t\tvalue: JSON.stringify({\n\t\t\t\t\t\temail,\n\t\t\t\t\t\tname: ctx.body.name,\n\t\t\t\t\t\tattempt: 0\n\t\t\t\t\t}),\n\t\t\t\t\texpiresAt: new Date(Date.now() + (opts.expiresIn || 300) * 1e3)\n\t\t\t\t});\n\t\t\t\tconst realBaseURL = new URL(ctx.context.baseURL);\n\t\t\t\tconst pathname = realBaseURL.pathname === \"/\" ? \"\" : realBaseURL.pathname;\n\t\t\t\tconst basePath = pathname ? \"\" : ctx.context.options.basePath || \"\";\n\t\t\t\tconst url = new URL(`${pathname}${basePath}/magic-link/verify`, realBaseURL.origin);\n\t\t\t\turl.searchParams.set(\"token\", verificationToken);\n\t\t\t\turl.searchParams.set(\"callbackURL\", ctx.body.callbackURL || \"/\");\n\t\t\t\tif (ctx.body.newUserCallbackURL) url.searchParams.set(\"newUserCallbackURL\", ctx.body.newUserCallbackURL);\n\t\t\t\tif (ctx.body.errorCallbackURL) url.searchParams.set(\"errorCallbackURL\", ctx.body.errorCallbackURL);\n\t\t\t\tawait options.sendMagicLink({\n\t\t\t\t\temail,\n\t\t\t\t\turl: url.toString(),\n\t\t\t\t\ttoken: verificationToken,\n\t\t\t\t\tmetadata\n\t\t\t\t}, ctx);\n\t\t\t\treturn ctx.json({ status: true });\n\t\t\t}),\n\t\t\tmagicLinkVerify: createAuthEndpoint(\"/magic-link/verify\", {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tquery: magicLinkVerifyQuerySchema,\n\t\t\t\tuse: [\n\t\t\t\t\toriginCheck((ctx) => {\n\t\t\t\t\t\treturn ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : \"/\";\n\t\t\t\t\t}),\n\t\t\t\t\toriginCheck((ctx) => {\n\t\t\t\t\t\treturn ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : \"/\";\n\t\t\t\t\t}),\n\t\t\t\t\toriginCheck((ctx) => {\n\t\t\t\t\t\treturn ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : \"/\";\n\t\t\t\t\t})\n\t\t\t\t],\n\t\t\t\trequireHeaders: true,\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\toperationId: \"verifyMagicLink\",\n\t\t\t\t\tdescription: \"Verify magic link\",\n\t\t\t\t\tresponses: { 200: {\n\t\t\t\t\t\tdescription: \"Success\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tsession: { $ref: \"#/components/schemas/Session\" },\n\t\t\t\t\t\t\t\tuser: { $ref: \"#/components/schemas/User\" }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\tconst token = ctx.query.token;\n\t\t\t\tconst callbackURL = new URL(ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : \"/\", ctx.context.baseURL).toString();\n\t\t\t\tconst errorCallbackURL = new URL(ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : callbackURL, ctx.context.baseURL);\n\t\t\t\tfunction redirectWithError(error) {\n\t\t\t\t\terrorCallbackURL.searchParams.set(\"error\", error);\n\t\t\t\t\tthrow ctx.redirect(errorCallbackURL.toString());\n\t\t\t\t}\n\t\t\t\tconst newUserCallbackURL = new URL(ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : callbackURL, ctx.context.baseURL).toString();\n\t\t\t\tconst storedToken = await storeToken(ctx, token);\n\t\t\t\tconst tokenValue = await ctx.context.internalAdapter.findVerificationValue(storedToken);\n\t\t\t\tif (!tokenValue) redirectWithError(\"INVALID_TOKEN\");\n\t\t\t\tif (tokenValue.expiresAt < /* @__PURE__ */ new Date()) {\n\t\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(storedToken);\n\t\t\t\t\tredirectWithError(\"EXPIRED_TOKEN\");\n\t\t\t\t}\n\t\t\t\tconst { email, name, attempt = 0 } = JSON.parse(tokenValue.value);\n\t\t\t\tif (attempt >= opts.allowedAttempts) {\n\t\t\t\t\tawait ctx.context.internalAdapter.deleteVerificationByIdentifier(storedToken);\n\t\t\t\t\tredirectWithError(\"ATTEMPTS_EXCEEDED\");\n\t\t\t\t}\n\t\t\t\tawait ctx.context.internalAdapter.updateVerificationByIdentifier(storedToken, { value: JSON.stringify({\n\t\t\t\t\temail,\n\t\t\t\t\tname,\n\t\t\t\t\tattempt: attempt + 1\n\t\t\t\t}) });\n\t\t\t\tlet isNewUser = false;\n\t\t\t\tlet user = await ctx.context.internalAdapter.findUserByEmail(email).then((res) => res?.user);\n\t\t\t\tif (!user) if (!opts.disableSignUp) {\n\t\t\t\t\tconst newUser = await ctx.context.internalAdapter.createUser({\n\t\t\t\t\t\temail,\n\t\t\t\t\t\temailVerified: true,\n\t\t\t\t\t\tname: name || \"\"\n\t\t\t\t\t});\n\t\t\t\t\tisNewUser = true;\n\t\t\t\t\tuser = newUser;\n\t\t\t\t\tif (!user) redirectWithError(\"failed_to_create_user\");\n\t\t\t\t} else redirectWithError(\"new_user_signup_disabled\");\n\t\t\t\tif (!user.emailVerified) user = await ctx.context.internalAdapter.updateUser(user.id, { emailVerified: true });\n\t\t\t\tconst session = await ctx.context.internalAdapter.createSession(user.id);\n\t\t\t\tif (!session) redirectWithError(\"failed_to_create_session\");\n\t\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\t\tsession,\n\t\t\t\t\tuser\n\t\t\t\t});\n\t\t\t\tif (!ctx.query.callbackURL) return ctx.json({\n\t\t\t\t\ttoken: session.token,\n\t\t\t\t\tuser: parseUserOutput(ctx.context.options, user),\n\t\t\t\t\tsession: parseSessionOutput(ctx.context.options, session)\n\t\t\t\t});\n\t\t\t\tif (isNewUser) throw ctx.redirect(newUserCallbackURL);\n\t\t\t\tthrow ctx.redirect(callbackURL);\n\t\t\t})\n\t\t},\n\t\trateLimit: [{\n\t\t\tpathMatcher(path) {\n\t\t\t\treturn path.startsWith(\"/sign-in/magic-link\") || path.startsWith(\"/magic-link/verify\");\n\t\t\t},\n\t\t\twindow: opts.rateLimit?.window || 60,\n\t\t\tmax: opts.rateLimit?.max || 5\n\t\t}],\n\t\toptions\n\t};\n};\n//#endregion\nexport { magicLink };\n", "import { createAdapterFactory, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName } from \"@better-auth/core/db/adapter\";\nexport * from \"@better-auth/core/db/adapter\";\n//#region src/adapters/index.ts\n/**\n* @deprecated Use `createAdapterFactory` instead.\n*/\nconst createAdapter = createAdapterFactory;\n//#endregion\nexport { createAdapter, createAdapterFactory, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName };\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { betterAuth } from 'better-auth';\nimport type { Auth, BetterAuthOptions } from 'better-auth';\nimport { organization } from 'better-auth/plugins/organization';\nimport { twoFactor } from 'better-auth/plugins/two-factor';\nimport { magicLink } from 'better-auth/plugins/magic-link';\nimport type { AuthConfig } from '@objectstack/spec/system';\nimport type { IDataEngine } from '@objectstack/core';\nimport { createObjectQLAdapterFactory } from './objectql-adapter.js';\nimport {\n AUTH_USER_CONFIG,\n AUTH_SESSION_CONFIG,\n AUTH_ACCOUNT_CONFIG,\n AUTH_VERIFICATION_CONFIG,\n buildOrganizationPluginSchema,\n buildTwoFactorPluginSchema,\n} from './auth-schema-config.js';\n\n/**\n * Extended options for AuthManager\n */\nexport interface AuthManagerOptions extends Partial {\n /**\n * Better-Auth instance (for advanced use cases)\n * If not provided, one will be created from config\n */\n authInstance?: Auth;\n\n /**\n * ObjectQL Data Engine instance\n * Required for database operations using ObjectQL instead of third-party ORMs\n */\n dataEngine?: IDataEngine;\n\n /**\n * Base path for auth routes\n * Forwarded to better-auth's basePath option so it can match incoming\n * request URLs without manual path rewriting.\n * @default '/api/v1/auth'\n */\n basePath?: string;\n}\n\n/**\n * Authentication Manager\n *\n * Wraps better-auth and provides authentication services for ObjectStack.\n * Supports multiple authentication methods:\n * - Email/password\n * - OAuth providers (Google, GitHub, etc.)\n * - Magic links\n * - Two-factor authentication\n * - Passkeys\n * - Organization/teams\n */\nexport class AuthManager {\n private auth: Auth | null = null;\n private config: AuthManagerOptions;\n\n constructor(config: AuthManagerOptions) {\n this.config = config;\n\n // Use provided auth instance\n if (config.authInstance) {\n this.auth = config.authInstance;\n }\n // Don't create auth instance automatically to avoid database initialization errors\n // It will be created lazily when needed\n }\n\n /**\n * Get or create the better-auth instance (lazy initialization)\n */\n private getOrCreateAuth(): Auth {\n if (!this.auth) {\n this.auth = this.createAuthInstance();\n }\n return this.auth;\n }\n\n /**\n * Create a better-auth instance from configuration\n */\n private createAuthInstance(): Auth {\n const betterAuthConfig: BetterAuthOptions = {\n // Base configuration\n secret: this.config.secret || this.generateSecret(),\n baseURL: this.config.baseUrl || 'http://localhost:3000',\n basePath: this.config.basePath || '/api/v1/auth',\n\n // Database adapter configuration\n database: this.createDatabaseConfig(),\n\n // Model/field mapping: camelCase (better-auth) → snake_case (ObjectStack)\n // These declarations tell better-auth the actual table/column names used\n // by ObjectStack's protocol layer, enabling automatic transformation via\n // createAdapterFactory.\n user: {\n ...AUTH_USER_CONFIG,\n },\n account: {\n ...AUTH_ACCOUNT_CONFIG,\n },\n verification: {\n ...AUTH_VERIFICATION_CONFIG,\n },\n\n // Social / OAuth providers\n ...(this.config.socialProviders ? { socialProviders: this.config.socialProviders as any } : {}),\n\n // Email and password configuration\n emailAndPassword: {\n enabled: this.config.emailAndPassword?.enabled ?? true,\n ...(this.config.emailAndPassword?.disableSignUp != null\n ? { disableSignUp: this.config.emailAndPassword.disableSignUp } : {}),\n ...(this.config.emailAndPassword?.requireEmailVerification != null\n ? { requireEmailVerification: this.config.emailAndPassword.requireEmailVerification } : {}),\n ...(this.config.emailAndPassword?.minPasswordLength != null\n ? { minPasswordLength: this.config.emailAndPassword.minPasswordLength } : {}),\n ...(this.config.emailAndPassword?.maxPasswordLength != null\n ? { maxPasswordLength: this.config.emailAndPassword.maxPasswordLength } : {}),\n ...(this.config.emailAndPassword?.resetPasswordTokenExpiresIn != null\n ? { resetPasswordTokenExpiresIn: this.config.emailAndPassword.resetPasswordTokenExpiresIn } : {}),\n ...(this.config.emailAndPassword?.autoSignIn != null\n ? { autoSignIn: this.config.emailAndPassword.autoSignIn } : {}),\n ...(this.config.emailAndPassword?.revokeSessionsOnPasswordReset != null\n ? { revokeSessionsOnPasswordReset: this.config.emailAndPassword.revokeSessionsOnPasswordReset } : {}),\n },\n\n // Email verification\n ...(this.config.emailVerification ? {\n emailVerification: {\n ...(this.config.emailVerification.sendOnSignUp != null\n ? { sendOnSignUp: this.config.emailVerification.sendOnSignUp } : {}),\n ...(this.config.emailVerification.sendOnSignIn != null\n ? { sendOnSignIn: this.config.emailVerification.sendOnSignIn } : {}),\n ...(this.config.emailVerification.autoSignInAfterVerification != null\n ? { autoSignInAfterVerification: this.config.emailVerification.autoSignInAfterVerification } : {}),\n ...(this.config.emailVerification.expiresIn != null\n ? { expiresIn: this.config.emailVerification.expiresIn } : {}),\n },\n } : {}),\n\n // Session configuration\n session: {\n ...AUTH_SESSION_CONFIG,\n expiresIn: this.config.session?.expiresIn || 60 * 60 * 24 * 7, // 7 days default\n updateAge: this.config.session?.updateAge || 60 * 60 * 24, // 1 day default\n },\n\n // better-auth plugins — registered based on AuthPluginConfig flags\n plugins: this.buildPluginList(),\n\n // Trusted origins for CSRF protection (supports wildcards like \"https://*.example.com\")\n ...(this.config.trustedOrigins?.length ? { trustedOrigins: this.config.trustedOrigins } : {}),\n\n // Advanced options (cross-subdomain cookies, secure cookies, CSRF, etc.)\n ...(this.config.advanced ? {\n advanced: {\n ...(this.config.advanced.crossSubDomainCookies\n ? { crossSubDomainCookies: this.config.advanced.crossSubDomainCookies } : {}),\n ...(this.config.advanced.useSecureCookies != null\n ? { useSecureCookies: this.config.advanced.useSecureCookies } : {}),\n ...(this.config.advanced.disableCSRFCheck != null\n ? { disableCSRFCheck: this.config.advanced.disableCSRFCheck } : {}),\n ...(this.config.advanced.cookiePrefix != null\n ? { cookiePrefix: this.config.advanced.cookiePrefix } : {}),\n },\n } : {}),\n };\n\n return betterAuth(betterAuthConfig);\n }\n\n /**\n * Build the list of better-auth plugins based on AuthPluginConfig flags.\n *\n * Each plugin that introduces its own database tables is configured with\n * a `schema` option containing the appropriate snake_case field mappings,\n * so that `createAdapterFactory` transforms them automatically.\n */\n private buildPluginList(): any[] {\n const pluginConfig = this.config.plugins;\n const plugins: any[] = [];\n\n if (pluginConfig?.organization) {\n plugins.push(organization({\n schema: buildOrganizationPluginSchema(),\n }));\n }\n\n if (pluginConfig?.twoFactor) {\n plugins.push(twoFactor({\n schema: buildTwoFactorPluginSchema(),\n }));\n }\n\n if (pluginConfig?.magicLink) {\n // magic-link reuses the `verification` table — no extra schema mapping needed.\n // The sendMagicLink callback must be provided by the application at a higher level.\n // Here we provide a no-op default that logs a warning; real applications should\n // override this via AuthManagerOptions or a config extension point.\n plugins.push(magicLink({\n sendMagicLink: async ({ email, url }) => {\n console.warn(\n `[AuthManager] Magic-link requested for ${email} but no sendMagicLink handler configured. URL: ${url}`,\n );\n },\n }));\n }\n\n return plugins;\n }\n\n /**\n * Create database configuration using ObjectQL adapter\n *\n * better-auth resolves the `database` option as follows:\n * - `undefined` → in-memory adapter\n * - `typeof fn === \"function\"` → treated as `DBAdapterInstance`, called with `(options)`\n * - otherwise → forwarded to Kysely adapter factory (pool/dialect)\n *\n * A raw `CustomAdapter` object would fall into the third branch and fail\n * silently. We therefore wrap the ObjectQL adapter in a factory function\n * so it is correctly recognised as a `DBAdapterInstance`.\n */\n private createDatabaseConfig(): any {\n // Use ObjectQL adapter factory if dataEngine is provided\n if (this.config.dataEngine) {\n // createObjectQLAdapterFactory returns an AdapterFactory\n // (options => DBAdapter) which better-auth invokes via getBaseAdapter().\n // The factory is created by better-auth's createAdapterFactory and\n // automatically applies modelName/fields transformations declared in\n // the betterAuth config above.\n return createObjectQLAdapterFactory(this.config.dataEngine);\n }\n\n // Fallback warning if no dataEngine is provided\n console.warn(\n '⚠️ WARNING: No dataEngine provided to AuthManager! ' +\n 'Using in-memory storage. This is NOT suitable for production. ' +\n 'Please provide a dataEngine instance (e.g., ObjectQL) in AuthManagerOptions.'\n );\n\n // Return a minimal in-memory configuration as fallback\n // This allows the system to work in development/testing without a real database\n return undefined; // better-auth will use its default in-memory adapter\n }\n\n /**\n * Generate a secure secret if not provided\n */\n private generateSecret(): string {\n const envSecret = process.env.AUTH_SECRET;\n\n if (!envSecret) {\n // In production, a secret MUST be provided\n // For development/testing, we'll use a fallback but warn about it\n const fallbackSecret = 'dev-secret-' + Date.now();\n\n console.warn(\n '⚠️ WARNING: No AUTH_SECRET environment variable set! ' +\n 'Using a temporary development secret. ' +\n 'This is NOT secure for production use. ' +\n 'Please set AUTH_SECRET in your environment variables.'\n );\n\n return fallbackSecret;\n }\n\n return envSecret;\n }\n\n /**\n * Update the base URL at runtime.\n *\n * This **must** be called before the first request triggers lazy\n * initialisation of the better-auth instance — typically from a\n * `kernel:ready` hook where the actual server port is known.\n *\n * If the auth instance has already been created this is a no-op and\n * a warning is emitted.\n */\n setRuntimeBaseUrl(url: string): void {\n if (this.auth) {\n console.warn(\n '[AuthManager] setRuntimeBaseUrl() called after the auth instance was already created — ignoring. ' +\n 'Ensure this method is called before the first request.',\n );\n return;\n }\n this.config = { ...this.config, baseUrl: url };\n }\n\n /**\n * Get the underlying better-auth instance\n * Useful for advanced use cases\n */\n getAuthInstance(): Auth {\n return this.getOrCreateAuth();\n }\n\n /**\n * Handle an authentication request\n * Forwards the request directly to better-auth's universal handler\n *\n * better-auth catches internal errors (database / adapter / ORM) and\n * returns a 500 Response instead of throwing. We therefore inspect the\n * response status and log server errors so they are not silently swallowed.\n *\n * @param request - Web standard Request object\n * @returns Web standard Response object\n */\n async handleRequest(request: Request): Promise {\n const auth = this.getOrCreateAuth();\n const response = await auth.handler(request);\n\n if (response.status >= 500) {\n try {\n const body = await response.clone().text();\n console.error('[AuthManager] better-auth returned error:', response.status, body);\n } catch {\n console.error('[AuthManager] better-auth returned error:', response.status, '(unable to read body)');\n }\n }\n\n return response;\n }\n\n /**\n * Get the better-auth API for programmatic access\n * Use this for server-side operations (e.g., creating users, checking sessions)\n */\n get api() {\n return this.getOrCreateAuth().api;\n }\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IDataEngine } from '@objectstack/core';\nimport { createAdapterFactory } from 'better-auth/adapters';\nimport type { CleanedWhere } from 'better-auth/adapters';\nimport { SystemObjectName } from '@objectstack/spec/system';\n\n/**\n * Mapping from better-auth model names to ObjectStack protocol object names.\n *\n * better-auth uses hardcoded model names ('user', 'session', 'account', 'verification')\n * while ObjectStack's protocol layer uses `sys_` prefixed names. This map bridges the two.\n */\nexport const AUTH_MODEL_TO_PROTOCOL: Record = {\n user: SystemObjectName.USER,\n session: SystemObjectName.SESSION,\n account: SystemObjectName.ACCOUNT,\n verification: SystemObjectName.VERIFICATION,\n};\n\n/**\n * Resolve a better-auth model name to the ObjectStack protocol object name.\n * Falls back to the original model name for custom / non-core models.\n */\nexport function resolveProtocolName(model: string): string {\n return AUTH_MODEL_TO_PROTOCOL[model] ?? model;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert better-auth where clause to ObjectQL query format.\n *\n * Field names in the incoming {@link CleanedWhere} are expected to already be\n * in snake_case (transformed by `createAdapterFactory`).\n */\nfunction convertWhere(where: CleanedWhere[]): Record {\n const filter: Record = {};\n\n for (const condition of where) {\n const fieldName = condition.field;\n\n if (condition.operator === 'eq') {\n filter[fieldName] = condition.value;\n } else if (condition.operator === 'ne') {\n filter[fieldName] = { $ne: condition.value };\n } else if (condition.operator === 'in') {\n filter[fieldName] = { $in: condition.value };\n } else if (condition.operator === 'gt') {\n filter[fieldName] = { $gt: condition.value };\n } else if (condition.operator === 'gte') {\n filter[fieldName] = { $gte: condition.value };\n } else if (condition.operator === 'lt') {\n filter[fieldName] = { $lt: condition.value };\n } else if (condition.operator === 'lte') {\n filter[fieldName] = { $lte: condition.value };\n } else if (condition.operator === 'contains') {\n filter[fieldName] = { $regex: condition.value };\n }\n }\n\n return filter;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create an ObjectQL adapter **factory** for better-auth.\n *\n * Uses better-auth's official `createAdapterFactory` so that model-name and\n * field-name transformations (declared via `modelName` / `fields` in the\n * betterAuth config) are applied **automatically** before any data reaches\n * ObjectQL. This eliminates the need for manual camelCase ↔ snake_case\n * conversion inside the adapter.\n *\n * The returned value is an `AdapterFactory` – a function of type\n * `(options: BetterAuthOptions) => DBAdapter` – which is the shape expected\n * by `betterAuth({ database: … })`.\n *\n * @param dataEngine - ObjectQL data engine instance\n * @returns better-auth AdapterFactory\n */\nexport function createObjectQLAdapterFactory(dataEngine: IDataEngine) {\n return createAdapterFactory({\n config: {\n adapterId: 'objectql',\n // ObjectQL natively supports these types — no extra conversion needed\n supportsBooleans: true,\n supportsDates: true,\n supportsJSON: true,\n },\n adapter: () => ({\n create: async >(\n { model, data, select: _select }: { model: string; data: T; select?: string[] },\n ): Promise => {\n const result = await dataEngine.insert(model, data);\n return result as T;\n },\n\n findOne: async (\n { model, where, select, join: _join }: { model: string; where: CleanedWhere[]; select?: string[]; join?: any },\n ): Promise => {\n const filter = convertWhere(where);\n\n const result = await dataEngine.findOne(model, { where: filter, fields: select });\n\n return result ? (result as T) : null;\n },\n\n findMany: async (\n { model, where, limit, offset, sortBy, join: _join }: {\n model: string; where?: CleanedWhere[]; limit: number;\n offset?: number; sortBy?: { field: string; direction: 'asc' | 'desc' }; join?: any;\n },\n ): Promise => {\n const filter = where ? convertWhere(where) : {};\n\n const orderBy = sortBy\n ? [{ field: sortBy.field, order: sortBy.direction as 'asc' | 'desc' }]\n : undefined;\n\n const results = await dataEngine.find(model, {\n where: filter,\n limit: limit || 100,\n offset,\n orderBy,\n });\n\n return results as T[];\n },\n\n count: async (\n { model, where }: { model: string; where?: CleanedWhere[] },\n ): Promise => {\n const filter = where ? convertWhere(where) : {};\n return await dataEngine.count(model, { where: filter });\n },\n\n update: async (\n { model, where, update }: { model: string; where: CleanedWhere[]; update: T },\n ): Promise => {\n const filter = convertWhere(where);\n\n // ObjectQL requires an ID for updates – find the record first\n const record = await dataEngine.findOne(model, { where: filter });\n if (!record) return null;\n\n const result = await dataEngine.update(model, { ...(update as any), id: record.id });\n return result ? (result as T) : null;\n },\n\n updateMany: async (\n { model, where, update }: { model: string; where: CleanedWhere[]; update: Record },\n ): Promise => {\n const filter = convertWhere(where);\n\n // Sequential updates: ObjectQL requires an ID per update\n const records = await dataEngine.find(model, { where: filter });\n for (const record of records) {\n await dataEngine.update(model, { ...update, id: record.id });\n }\n return records.length;\n },\n\n delete: async (\n { model, where }: { model: string; where: CleanedWhere[] },\n ): Promise => {\n const filter = convertWhere(where);\n\n const record = await dataEngine.findOne(model, { where: filter });\n if (!record) return;\n\n await dataEngine.delete(model, { where: { id: record.id } });\n },\n\n deleteMany: async (\n { model, where }: { model: string; where: CleanedWhere[] },\n ): Promise => {\n const filter = convertWhere(where);\n\n const records = await dataEngine.find(model, { where: filter });\n for (const record of records) {\n await dataEngine.delete(model, { where: { id: record.id } });\n }\n return records.length;\n },\n }),\n });\n}\n\n// ---------------------------------------------------------------------------\n// Legacy adapter (kept for backward compatibility)\n// ---------------------------------------------------------------------------\n\n/**\n * Create a raw ObjectQL adapter for better-auth (without factory wrapping).\n *\n * > **Prefer {@link createObjectQLAdapterFactory}** for production use.\n * > The factory version leverages `createAdapterFactory` and automatically\n * > handles model-name + field-name transformations declared in the\n * > better-auth config.\n *\n * This function is retained for direct / low-level usage where callers\n * manage field-name conversion themselves.\n *\n * @param dataEngine - ObjectQL data engine instance\n * @returns better-auth CustomAdapter (raw, without factory wrapping)\n */\nexport function createObjectQLAdapter(dataEngine: IDataEngine) {\n return {\n create: async >({ model, data, select: _select }: { model: string; data: T; select?: string[] }): Promise => {\n const objectName = resolveProtocolName(model);\n const result = await dataEngine.insert(objectName, data);\n return result as T;\n },\n\n findOne: async ({ model, where, select, join: _join }: { model: string; where: CleanedWhere[]; select?: string[]; join?: any }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const result = await dataEngine.findOne(objectName, { where: filter, fields: select });\n return result ? result as T : null;\n },\n\n findMany: async ({ model, where, limit, offset, sortBy, join: _join }: { model: string; where?: CleanedWhere[]; limit: number; offset?: number; sortBy?: { field: string; direction: 'asc' | 'desc' }; join?: any }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = where ? convertWhere(where) : {};\n const orderBy = sortBy ? [{ field: sortBy.field, order: sortBy.direction as 'asc' | 'desc' }] : undefined;\n const results = await dataEngine.find(objectName, { where: filter, limit: limit || 100, offset, orderBy });\n return results as T[];\n },\n\n count: async ({ model, where }: { model: string; where?: CleanedWhere[] }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = where ? convertWhere(where) : {};\n return await dataEngine.count(objectName, { where: filter });\n },\n\n update: async ({ model, where, update }: { model: string; where: CleanedWhere[]; update: Record }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const record = await dataEngine.findOne(objectName, { where: filter });\n if (!record) return null;\n const result = await dataEngine.update(objectName, { ...update, id: record.id });\n return result ? result as T : null;\n },\n\n updateMany: async ({ model, where, update }: { model: string; where: CleanedWhere[]; update: Record }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const records = await dataEngine.find(objectName, { where: filter });\n for (const record of records) {\n await dataEngine.update(objectName, { ...update, id: record.id });\n }\n return records.length;\n },\n\n delete: async ({ model, where }: { model: string; where: CleanedWhere[] }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const record = await dataEngine.findOne(objectName, { where: filter });\n if (!record) return;\n await dataEngine.delete(objectName, { where: { id: record.id } });\n },\n\n deleteMany: async ({ model, where }: { model: string; where: CleanedWhere[] }): Promise => {\n const objectName = resolveProtocolName(model);\n const filter = convertWhere(where);\n const records = await dataEngine.find(objectName, { where: filter });\n for (const record of records) {\n await dataEngine.delete(objectName, { where: { id: record.id } });\n }\n return records.length;\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { SystemObjectName } from '@objectstack/spec/system';\n\n/**\n * better-auth ↔ ObjectStack Schema Mapping\n *\n * better-auth uses camelCase field names internally (e.g. `emailVerified`, `userId`)\n * while ObjectStack's protocol layer uses snake_case (e.g. `email_verified`, `user_id`).\n *\n * These constants declare the `modelName` and `fields` mappings for each core auth\n * model, following better-auth's official schema customisation API\n * ({@link https://www.better-auth.com/docs/concepts/database}).\n *\n * The mappings serve two purposes:\n * 1. `modelName` — maps the default model name to the ObjectStack protocol name\n * (e.g. `user` → `sys_user`).\n * 2. `fields` — maps camelCase field names to their snake_case database column\n * equivalents. Only fields whose names differ need to be listed; fields that\n * are already identical (e.g. `email`, `name`, `token`) are omitted.\n *\n * These mappings are consumed by:\n * - The `betterAuth()` configuration in {@link AuthManager} so that\n * `getAuthTables()` builds the correct schema.\n * - The ObjectQL adapter factory (via `createAdapterFactory`) which uses the\n * schema to transform data and where-clauses automatically.\n */\n\n// ---------------------------------------------------------------------------\n// User model\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth `user` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | emailVerified | email_verified |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_USER_CONFIG = {\n modelName: SystemObjectName.USER, // 'sys_user'\n fields: {\n emailVerified: 'email_verified',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Session model\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth `session` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | userId | user_id |\n * | expiresAt | expires_at |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n * | ipAddress | ip_address |\n * | userAgent | user_agent |\n */\nexport const AUTH_SESSION_CONFIG = {\n modelName: SystemObjectName.SESSION, // 'sys_session'\n fields: {\n userId: 'user_id',\n expiresAt: 'expires_at',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n ipAddress: 'ip_address',\n userAgent: 'user_agent',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Account model\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth `account` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:--------------------------|:-------------------------------|\n * | userId | user_id |\n * | providerId | provider_id |\n * | accountId | account_id |\n * | accessToken | access_token |\n * | refreshToken | refresh_token |\n * | idToken | id_token |\n * | accessTokenExpiresAt | access_token_expires_at |\n * | refreshTokenExpiresAt | refresh_token_expires_at |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_ACCOUNT_CONFIG = {\n modelName: SystemObjectName.ACCOUNT, // 'sys_account'\n fields: {\n userId: 'user_id',\n providerId: 'provider_id',\n accountId: 'account_id',\n accessToken: 'access_token',\n refreshToken: 'refresh_token',\n idToken: 'id_token',\n accessTokenExpiresAt: 'access_token_expires_at',\n refreshTokenExpiresAt: 'refresh_token_expires_at',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Verification model\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth `verification` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | expiresAt | expires_at |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_VERIFICATION_CONFIG = {\n modelName: SystemObjectName.VERIFICATION, // 'sys_verification'\n fields: {\n expiresAt: 'expires_at',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ===========================================================================\n// Plugin Table Mappings\n// ===========================================================================\n//\n// better-auth plugins (organization, two-factor, etc.) introduce additional\n// tables with their own camelCase field names. The mappings below are passed\n// to the plugin's `schema` option so that `createAdapterFactory` transforms\n// them to snake_case automatically, just like the core models above.\n// ===========================================================================\n\n// ---------------------------------------------------------------------------\n// Organization plugin – organization table\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `organization` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_ORGANIZATION_SCHEMA = {\n modelName: SystemObjectName.ORGANIZATION, // 'sys_organization'\n fields: {\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – member table\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `member` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | organizationId | organization_id |\n * | userId | user_id |\n * | createdAt | created_at |\n */\nexport const AUTH_MEMBER_SCHEMA = {\n modelName: SystemObjectName.MEMBER, // 'sys_member'\n fields: {\n organizationId: 'organization_id',\n userId: 'user_id',\n createdAt: 'created_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – invitation table\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `invitation` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | organizationId | organization_id |\n * | inviterId | inviter_id |\n * | expiresAt | expires_at |\n * | createdAt | created_at |\n * | teamId | team_id |\n */\nexport const AUTH_INVITATION_SCHEMA = {\n modelName: SystemObjectName.INVITATION, // 'sys_invitation'\n fields: {\n organizationId: 'organization_id',\n inviterId: 'inviter_id',\n expiresAt: 'expires_at',\n createdAt: 'created_at',\n teamId: 'team_id',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – session additional fields\n// ---------------------------------------------------------------------------\n\n/**\n * Organization plugin adds `activeOrganizationId` (and optionally\n * `activeTeamId`) to the session model. These field mappings are\n * injected via the organization plugin's `schema.session.fields`.\n */\nexport const AUTH_ORG_SESSION_FIELDS = {\n activeOrganizationId: 'active_organization_id',\n activeTeamId: 'active_team_id',\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – team table (optional, when teams enabled)\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `team` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | organizationId | organization_id |\n * | createdAt | created_at |\n * | updatedAt | updated_at |\n */\nexport const AUTH_TEAM_SCHEMA = {\n modelName: SystemObjectName.TEAM, // 'sys_team'\n fields: {\n organizationId: 'organization_id',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Organization plugin – teamMember table (optional, when teams enabled)\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Organization plugin `teamMember` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | teamId | team_id |\n * | userId | user_id |\n * | createdAt | created_at |\n */\nexport const AUTH_TEAM_MEMBER_SCHEMA = {\n modelName: SystemObjectName.TEAM_MEMBER, // 'sys_team_member'\n fields: {\n teamId: 'team_id',\n userId: 'user_id',\n createdAt: 'created_at',\n },\n} as const;\n\n// ---------------------------------------------------------------------------\n// Two-Factor plugin – twoFactor table\n// ---------------------------------------------------------------------------\n\n/**\n * better-auth Two-Factor plugin `twoFactor` model mapping.\n *\n * | camelCase (better-auth) | snake_case (ObjectStack) |\n * |:------------------------|:-------------------------|\n * | backupCodes | backup_codes |\n * | userId | user_id |\n */\nexport const AUTH_TWO_FACTOR_SCHEMA = {\n modelName: SystemObjectName.TWO_FACTOR, // 'sys_two_factor'\n fields: {\n backupCodes: 'backup_codes',\n userId: 'user_id',\n },\n} as const;\n\n/**\n * Two-Factor plugin adds a `twoFactorEnabled` field to the user model.\n */\nexport const AUTH_TWO_FACTOR_USER_FIELDS = {\n twoFactorEnabled: 'two_factor_enabled',\n} as const;\n\n/**\n * Builds the `schema` option for better-auth's `twoFactor()` plugin.\n *\n * @returns An object suitable for `twoFactor({ schema: … })`\n */\nexport function buildTwoFactorPluginSchema() {\n return {\n twoFactor: AUTH_TWO_FACTOR_SCHEMA,\n user: {\n fields: AUTH_TWO_FACTOR_USER_FIELDS,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helper: build organization plugin schema option\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the `schema` option for better-auth's `organization()` plugin.\n *\n * The organization plugin accepts a `schema` sub-option that allows\n * customising model names and field names for each table it manages.\n * This helper assembles the correct snake_case mappings from the\n * individual `AUTH_*_SCHEMA` constants above.\n *\n * @returns An object suitable for `organization({ schema: … })`\n */\nexport function buildOrganizationPluginSchema() {\n return {\n organization: AUTH_ORGANIZATION_SCHEMA,\n member: AUTH_MEMBER_SCHEMA,\n invitation: AUTH_INVITATION_SCHEMA,\n team: AUTH_TEAM_SCHEMA,\n teamMember: AUTH_TEAM_MEMBER_SCHEMA,\n session: {\n fields: AUTH_ORG_SESSION_FIELDS,\n },\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_user — System User Object\n *\n * Canonical user identity record for the ObjectStack platform.\n * Backed by better-auth's `user` model with ObjectStack field conventions.\n *\n * @namespace sys\n */\nexport const SysUser = ObjectSchema.create({\n namespace: 'sys',\n name: 'user',\n label: 'User',\n pluralLabel: 'Users',\n icon: 'user',\n isSystem: true,\n description: 'User accounts for authentication',\n titleFormat: '{name} ({email})',\n compactLayout: ['name', 'email', 'email_verified'],\n \n fields: {\n id: Field.text({\n label: 'User ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n email: Field.email({\n label: 'Email',\n required: true,\n searchable: true,\n }),\n \n email_verified: Field.boolean({\n label: 'Email Verified',\n defaultValue: false,\n }),\n \n name: Field.text({\n label: 'Name',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n image: Field.url({\n label: 'Profile Image',\n required: false,\n }),\n },\n \n indexes: [\n { fields: ['email'], unique: true },\n { fields: ['created_at'], unique: false },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: true,\n mru: true,\n },\n \n validations: [\n {\n name: 'email_unique',\n type: 'unique',\n severity: 'error',\n message: 'Email must be unique',\n fields: ['email'],\n caseSensitive: false,\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_session — System Session Object\n *\n * Active user session record for the ObjectStack platform.\n * Backed by better-auth's `session` model with ObjectStack field conventions.\n *\n * @namespace sys\n */\nexport const SysSession = ObjectSchema.create({\n namespace: 'sys',\n name: 'session',\n label: 'Session',\n pluralLabel: 'Sessions',\n icon: 'key',\n isSystem: true,\n description: 'Active user sessions',\n titleFormat: 'Session {token}',\n compactLayout: ['user_id', 'expires_at', 'ip_address'],\n \n fields: {\n id: Field.text({\n label: 'Session ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n }),\n \n expires_at: Field.datetime({\n label: 'Expires At',\n required: true,\n }),\n \n token: Field.text({\n label: 'Session Token',\n required: true,\n }),\n \n ip_address: Field.text({\n label: 'IP Address',\n required: false,\n maxLength: 45, // Support IPv6\n }),\n \n user_agent: Field.textarea({\n label: 'User Agent',\n required: false,\n }),\n },\n \n indexes: [\n { fields: ['token'], unique: true },\n { fields: ['user_id'], unique: false },\n { fields: ['expires_at'], unique: false },\n ],\n \n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_account — System Account Object\n *\n * OAuth / credential provider account record.\n * Backed by better-auth's `account` model with ObjectStack field conventions.\n *\n * @namespace sys\n */\nexport const SysAccount = ObjectSchema.create({\n namespace: 'sys',\n name: 'account',\n label: 'Account',\n pluralLabel: 'Accounts',\n icon: 'link',\n isSystem: true,\n description: 'OAuth and authentication provider accounts',\n titleFormat: '{provider_id} - {account_id}',\n compactLayout: ['provider_id', 'user_id', 'account_id'],\n \n fields: {\n id: Field.text({\n label: 'Account ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n provider_id: Field.text({\n label: 'Provider ID',\n required: true,\n description: 'OAuth provider identifier (google, github, etc.)',\n }),\n \n account_id: Field.text({\n label: 'Provider Account ID',\n required: true,\n description: \"User's ID in the provider's system\",\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n description: 'Link to user table',\n }),\n \n access_token: Field.textarea({\n label: 'Access Token',\n required: false,\n }),\n \n refresh_token: Field.textarea({\n label: 'Refresh Token',\n required: false,\n }),\n \n id_token: Field.textarea({\n label: 'ID Token',\n required: false,\n }),\n \n access_token_expires_at: Field.datetime({\n label: 'Access Token Expires At',\n required: false,\n }),\n \n refresh_token_expires_at: Field.datetime({\n label: 'Refresh Token Expires At',\n required: false,\n }),\n \n scope: Field.text({\n label: 'OAuth Scope',\n required: false,\n }),\n \n password: Field.text({\n label: 'Password Hash',\n required: false,\n description: 'Hashed password for email/password provider',\n }),\n },\n \n indexes: [\n { fields: ['user_id'], unique: false },\n { fields: ['provider_id', 'account_id'], unique: true },\n ],\n \n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: true,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_verification — System Verification Object\n *\n * Email and phone verification token record.\n * Backed by better-auth's `verification` model with ObjectStack field conventions.\n *\n * @namespace sys\n */\nexport const SysVerification = ObjectSchema.create({\n namespace: 'sys',\n name: 'verification',\n label: 'Verification',\n pluralLabel: 'Verifications',\n icon: 'shield-check',\n isSystem: true,\n description: 'Email and phone verification tokens',\n titleFormat: 'Verification for {identifier}',\n compactLayout: ['identifier', 'expires_at', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Verification ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n value: Field.text({\n label: 'Verification Token',\n required: true,\n description: 'Token or code for verification',\n }),\n \n expires_at: Field.datetime({\n label: 'Expires At',\n required: true,\n }),\n \n identifier: Field.text({\n label: 'Identifier',\n required: true,\n description: 'Email address or phone number',\n }),\n },\n \n indexes: [\n { fields: ['value'], unique: true },\n { fields: ['identifier'], unique: false },\n { fields: ['expires_at'], unique: false },\n ],\n \n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'create', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_organization — System Organization Object\n *\n * Multi-organization support for the ObjectStack platform.\n * Backed by better-auth's organization plugin.\n *\n * @namespace sys\n */\nexport const SysOrganization = ObjectSchema.create({\n namespace: 'sys',\n name: 'organization',\n label: 'Organization',\n pluralLabel: 'Organizations',\n icon: 'building-2',\n isSystem: true,\n description: 'Organizations for multi-tenant grouping',\n titleFormat: '{name}',\n compactLayout: ['name', 'slug', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Organization ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n name: Field.text({\n label: 'Name',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n slug: Field.text({\n label: 'Slug',\n required: false,\n maxLength: 255,\n description: 'URL-friendly identifier',\n }),\n \n logo: Field.url({\n label: 'Logo',\n required: false,\n }),\n \n metadata: Field.textarea({\n label: 'Metadata',\n required: false,\n description: 'JSON-serialized organization metadata',\n }),\n },\n \n indexes: [\n { fields: ['slug'], unique: true },\n { fields: ['name'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: true,\n mru: true,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_member — System Member Object\n *\n * Organization membership linking users to organizations with roles.\n * Backed by better-auth's organization plugin.\n *\n * @namespace sys\n */\nexport const SysMember = ObjectSchema.create({\n namespace: 'sys',\n name: 'member',\n label: 'Member',\n pluralLabel: 'Members',\n icon: 'user-check',\n isSystem: true,\n description: 'Organization membership records',\n titleFormat: '{user_id} in {organization_id}',\n compactLayout: ['user_id', 'organization_id', 'role'],\n \n fields: {\n id: Field.text({\n label: 'Member ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n organization_id: Field.text({\n label: 'Organization ID',\n required: true,\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n }),\n \n role: Field.text({\n label: 'Role',\n required: false,\n description: 'Member role within the organization (e.g. admin, member)',\n maxLength: 100,\n }),\n },\n \n indexes: [\n { fields: ['organization_id', 'user_id'], unique: true },\n { fields: ['user_id'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_invitation — System Invitation Object\n *\n * Organization invitation tokens for inviting users.\n * Backed by better-auth's organization plugin.\n *\n * @namespace sys\n */\nexport const SysInvitation = ObjectSchema.create({\n namespace: 'sys',\n name: 'invitation',\n label: 'Invitation',\n pluralLabel: 'Invitations',\n icon: 'mail',\n isSystem: true,\n description: 'Organization invitations for user onboarding',\n titleFormat: 'Invitation to {organization_id}',\n compactLayout: ['email', 'organization_id', 'status'],\n \n fields: {\n id: Field.text({\n label: 'Invitation ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n organization_id: Field.text({\n label: 'Organization ID',\n required: true,\n }),\n \n email: Field.email({\n label: 'Email',\n required: true,\n description: 'Email address of the invited user',\n }),\n \n role: Field.text({\n label: 'Role',\n required: false,\n maxLength: 100,\n description: 'Role to assign upon acceptance',\n }),\n \n status: Field.select(['pending', 'accepted', 'rejected', 'expired', 'canceled'], {\n label: 'Status',\n required: true,\n defaultValue: 'pending',\n }),\n \n inviter_id: Field.text({\n label: 'Inviter ID',\n required: true,\n description: 'User ID of the person who sent the invitation',\n }),\n \n expires_at: Field.datetime({\n label: 'Expires At',\n required: true,\n }),\n \n team_id: Field.text({\n label: 'Team ID',\n required: false,\n description: 'Optional team to assign upon acceptance',\n }),\n },\n \n indexes: [\n { fields: ['organization_id'] },\n { fields: ['email'] },\n { fields: ['expires_at'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_team — System Team Object\n *\n * Teams within an organization for fine-grained grouping.\n * Backed by better-auth's organization plugin (teams feature).\n *\n * @namespace sys\n */\nexport const SysTeam = ObjectSchema.create({\n namespace: 'sys',\n name: 'team',\n label: 'Team',\n pluralLabel: 'Teams',\n icon: 'users',\n isSystem: true,\n description: 'Teams within organizations for fine-grained grouping',\n titleFormat: '{name}',\n compactLayout: ['name', 'organization_id', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Team ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n name: Field.text({\n label: 'Name',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n organization_id: Field.text({\n label: 'Organization ID',\n required: true,\n }),\n },\n \n indexes: [\n { fields: ['organization_id'] },\n { fields: ['name', 'organization_id'], unique: true },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: true,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_team_member — System Team Member Object\n *\n * Links users to teams within organizations.\n * Backed by better-auth's organization plugin (teams feature).\n *\n * @namespace sys\n */\nexport const SysTeamMember = ObjectSchema.create({\n namespace: 'sys',\n name: 'team_member',\n label: 'Team Member',\n pluralLabel: 'Team Members',\n icon: 'user-plus',\n isSystem: true,\n description: 'Team membership records linking users to teams',\n titleFormat: '{user_id} in {team_id}',\n compactLayout: ['user_id', 'team_id', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Team Member ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n team_id: Field.text({\n label: 'Team ID',\n required: true,\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n }),\n },\n \n indexes: [\n { fields: ['team_id', 'user_id'], unique: true },\n { fields: ['user_id'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_api_key — System API Key Object\n *\n * API keys for programmatic/machine access to the platform.\n *\n * @namespace sys\n */\nexport const SysApiKey = ObjectSchema.create({\n namespace: 'sys',\n name: 'api_key',\n label: 'API Key',\n pluralLabel: 'API Keys',\n icon: 'key-round',\n isSystem: true,\n description: 'API keys for programmatic access',\n titleFormat: '{name}',\n compactLayout: ['name', 'user_id', 'expires_at'],\n \n fields: {\n id: Field.text({\n label: 'API Key ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n name: Field.text({\n label: 'Name',\n required: true,\n maxLength: 255,\n description: 'Human-readable label for the API key',\n }),\n \n key: Field.text({\n label: 'Key',\n required: true,\n description: 'Hashed API key value',\n }),\n \n prefix: Field.text({\n label: 'Prefix',\n required: false,\n maxLength: 16,\n description: 'Visible prefix for identifying the key (e.g., \"osk_\")',\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n description: 'Owner user of this API key',\n }),\n \n scopes: Field.textarea({\n label: 'Scopes',\n required: false,\n description: 'JSON array of permission scopes',\n }),\n \n expires_at: Field.datetime({\n label: 'Expires At',\n required: false,\n }),\n \n last_used_at: Field.datetime({\n label: 'Last Used At',\n required: false,\n }),\n \n revoked: Field.boolean({\n label: 'Revoked',\n defaultValue: false,\n }),\n },\n \n indexes: [\n { fields: ['key'], unique: true },\n { fields: ['user_id'] },\n { fields: ['prefix'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_two_factor — System Two-Factor Object\n *\n * Two-factor authentication credentials (TOTP, backup codes).\n * Backed by better-auth's two-factor plugin.\n *\n * @namespace sys\n */\nexport const SysTwoFactor = ObjectSchema.create({\n namespace: 'sys',\n name: 'two_factor',\n label: 'Two Factor',\n pluralLabel: 'Two Factor Credentials',\n icon: 'smartphone',\n isSystem: true,\n description: 'Two-factor authentication credentials',\n titleFormat: 'Two-factor for {user_id}',\n compactLayout: ['user_id', 'created_at'],\n \n fields: {\n id: Field.text({\n label: 'Two Factor ID',\n required: true,\n readonly: true,\n }),\n \n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n \n user_id: Field.text({\n label: 'User ID',\n required: true,\n }),\n \n secret: Field.text({\n label: 'Secret',\n required: true,\n description: 'TOTP secret key',\n }),\n \n backup_codes: Field.textarea({\n label: 'Backup Codes',\n required: false,\n description: 'JSON-serialized backup recovery codes',\n }),\n },\n \n indexes: [\n { fields: ['user_id'], unique: true },\n ],\n \n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * sys_user_preference — System User Preference Object\n *\n * Per-user key-value preferences for storing UI state, settings, and personalization.\n * Supports the User Preferences layer in the Config Resolution hierarchy\n * (Runtime > User Preferences > Tenant > Env).\n *\n * Common use cases:\n * - UI preferences: theme, locale, timezone, sidebar state\n * - Feature flags: plugin.ai.auto_save, plugin.dev.debug_mode\n * - User-specific settings: default_view, notifications_enabled\n *\n * @namespace sys\n */\nexport const SysUserPreference = ObjectSchema.create({\n namespace: 'sys',\n name: 'user_preference',\n label: 'User Preference',\n pluralLabel: 'User Preferences',\n icon: 'settings',\n isSystem: true,\n description: 'Per-user key-value preferences (theme, locale, etc.)',\n titleFormat: '{key}',\n compactLayout: ['user_id', 'key'],\n\n fields: {\n id: Field.text({\n label: 'Preference ID',\n required: true,\n readonly: true,\n }),\n\n created_at: Field.datetime({\n label: 'Created At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n\n updated_at: Field.datetime({\n label: 'Updated At',\n defaultValue: 'NOW()',\n readonly: true,\n }),\n\n user_id: Field.text({\n label: 'User ID',\n required: true,\n maxLength: 255,\n description: 'Owner user of this preference',\n }),\n\n key: Field.text({\n label: 'Key',\n required: true,\n maxLength: 255,\n description: 'Preference key (e.g., theme, locale, plugin.ai.auto_save)',\n }),\n\n value: Field.json({\n label: 'Value',\n description: 'Preference value (any JSON-serializable type)',\n }),\n },\n\n indexes: [\n { fields: ['user_id', 'key'], unique: true },\n { fields: ['user_id'], unique: false },\n ],\n\n enable: {\n trackHistory: false,\n searchable: false,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete'],\n trash: false,\n mru: false,\n },\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext, IHttpServer } from '@objectstack/core';\nimport { AuthConfig } from '@objectstack/spec/system';\nimport { AuthManager } from './auth-manager.js';\nimport {\n SysUser, SysSession, SysAccount, SysVerification,\n SysOrganization, SysMember, SysInvitation,\n SysTeam, SysTeamMember,\n SysApiKey, SysTwoFactor, SysUserPreference,\n} from './objects/index.js';\n\n/**\n * Auth Plugin Options\n * Extends AuthConfig from spec with additional runtime options\n */\nexport interface AuthPluginOptions extends Partial {\n /**\n * Whether to automatically register auth routes\n * @default true\n */\n registerRoutes?: boolean;\n \n /**\n * Base path for auth routes\n * @default '/api/v1/auth'\n */\n basePath?: string;\n}\n\n/**\n * Authentication Plugin\n * \n * Provides authentication and identity services for ObjectStack applications.\n * \n * **Dual-Mode Operation:**\n * - **Server mode** (HonoServerPlugin active): Registers HTTP routes at basePath,\n * forwarding all auth requests to better-auth's universal handler.\n * - **MSW/Mock mode** (no HTTP server): Gracefully skips route registration but\n * still registers the `auth` service, allowing HttpDispatcher.handleAuth() to\n * simulate auth flows (sign-up, sign-in, etc.) for development and testing.\n * \n * Features:\n * - Session management\n * - User registration/login\n * - OAuth providers (Google, GitHub, etc.)\n * - Organization/team support\n * - 2FA, passkeys, magic links\n * \n * This plugin registers:\n * - `auth` service (auth manager instance) — always\n * - `app.com.objectstack.system` service (system object definitions) — always\n * - HTTP routes for authentication endpoints — only when HTTP server is available\n * \n * Integrates with better-auth library to provide comprehensive\n * authentication capabilities including email/password, OAuth, 2FA,\n * magic links, passkeys, and organization support.\n */\nexport class AuthPlugin implements Plugin {\n name = 'com.objectstack.auth';\n type = 'standard';\n version = '1.0.0';\n dependencies: string[] = ['com.objectstack.engine.objectql']; // manifest service required\n \n private options: AuthPluginOptions;\n private authManager: AuthManager | null = null;\n\n constructor(options: AuthPluginOptions = {}) {\n this.options = {\n registerRoutes: true,\n basePath: '/api/v1/auth',\n ...options\n };\n }\n\n async init(ctx: PluginContext): Promise {\n ctx.logger.info('Initializing Auth Plugin...');\n\n // Validate required configuration\n if (!this.options.secret) {\n throw new Error('AuthPlugin: secret is required');\n }\n\n // Get data engine service for database operations\n const dataEngine = ctx.getService('data');\n if (!dataEngine) {\n ctx.logger.warn('No data engine service found - auth will use in-memory storage');\n }\n\n // Initialize auth manager with data engine\n this.authManager = new AuthManager({\n ...this.options,\n dataEngine,\n });\n\n // Register auth service\n ctx.registerService('auth', this.authManager);\n\n // Register system objects via the manifest service.\n ctx.getService<{ register(m: any): void }>('manifest').register({\n id: 'com.objectstack.system',\n name: 'System',\n version: '1.0.0',\n type: 'plugin',\n namespace: 'sys',\n objects: [\n SysUser, SysSession, SysAccount, SysVerification,\n SysOrganization, SysMember, SysInvitation,\n SysTeam, SysTeamMember,\n SysApiKey, SysTwoFactor, SysUserPreference,\n ],\n });\n\n // Contribute navigation items to the Setup App (if SetupPlugin is loaded).\n // Uses try/catch so AuthPlugin works independently of SetupPlugin.\n try {\n const setupNav = ctx.getService<{ contribute(c: any): void }>('setupNav');\n if (setupNav) {\n setupNav.contribute({\n areaId: 'area_administration',\n items: [\n { id: 'nav_users', type: 'object', label: 'Users', objectName: 'user', icon: 'users', order: 10 },\n { id: 'nav_organizations', type: 'object', label: 'Organizations', objectName: 'organization', icon: 'building-2', order: 20 },\n { id: 'nav_teams', type: 'object', label: 'Teams', objectName: 'team', icon: 'users-round', order: 30 },\n { id: 'nav_api_keys', type: 'object', label: 'API Keys', objectName: 'api_key', icon: 'key', order: 40 },\n { id: 'nav_sessions', type: 'object', label: 'Sessions', objectName: 'session', icon: 'monitor', order: 50 },\n ],\n });\n ctx.logger.info('Auth navigation items contributed to Setup App');\n }\n } catch {\n // SetupPlugin not loaded — skip silently\n }\n\n ctx.logger.info('Auth Plugin initialized successfully');\n }\n\n async start(ctx: PluginContext): Promise {\n ctx.logger.info('Starting Auth Plugin...');\n\n if (!this.authManager) {\n throw new Error('Auth manager not initialized');\n }\n\n // Defer HTTP route registration to kernel:ready hook.\n // This ensures all plugins (including HonoServerPlugin) have completed\n // their init and start phases before we attempt to look up the\n // http-server service — making AuthPlugin resilient to plugin\n // loading order.\n if (this.options.registerRoutes) {\n ctx.hook('kernel:ready', async () => {\n let httpServer: IHttpServer | null = null;\n try {\n httpServer = ctx.getService('http-server');\n } catch {\n // Service not found — expected in MSW/mock mode\n }\n\n if (httpServer) {\n // Auto-detect the actual server URL when no explicit baseUrl was\n // configured, or when the configured baseUrl uses a different port\n // than the running server (e.g. port 3000 configured but 3002 bound).\n // getPort() is optional on IHttpServer; duck-type check for it.\n const serverWithPort = httpServer as IHttpServer & { getPort?: () => number };\n if (this.authManager && typeof serverWithPort.getPort === 'function') {\n const actualPort = serverWithPort.getPort();\n if (actualPort) {\n const configuredUrl = this.options.baseUrl || 'http://localhost:3000';\n const configuredOrigin = new URL(configuredUrl).origin;\n const actualUrl = `http://localhost:${actualPort}`;\n\n if (configuredOrigin !== actualUrl) {\n this.authManager.setRuntimeBaseUrl(actualUrl);\n ctx.logger.info(\n `Auth baseUrl auto-updated to ${actualUrl} (configured: ${configuredUrl})`,\n );\n }\n }\n }\n\n // Route registration errors should propagate (server misconfiguration)\n this.registerAuthRoutes(httpServer, ctx);\n ctx.logger.info(`Auth routes registered at ${this.options.basePath}`);\n } else {\n ctx.logger.warn(\n 'No HTTP server available — auth routes not registered. ' +\n 'Auth service is still available for MSW/mock environments via HttpDispatcher.'\n );\n }\n });\n }\n\n // Register auth middleware on ObjectQL engine (if available)\n try {\n const ql = ctx.getService('objectql');\n if (ql && typeof ql.registerMiddleware === 'function') {\n ql.registerMiddleware(async (opCtx: any, next: () => Promise) => {\n // If context already has userId or isSystem, skip auth resolution\n if (opCtx.context?.userId || opCtx.context?.isSystem) {\n return next();\n }\n // Future: resolve session from AsyncLocalStorage or request context\n await next();\n });\n ctx.logger.info('Auth middleware registered on ObjectQL engine');\n }\n } catch (_e) {\n ctx.logger.debug('ObjectQL engine not available, skipping auth middleware registration');\n }\n\n ctx.logger.info('Auth Plugin started successfully');\n }\n\n async destroy(): Promise {\n // Cleanup if needed\n this.authManager = null;\n }\n\n /**\n * Register authentication routes with HTTP server\n * \n * Uses better-auth's universal handler for all authentication requests.\n * This forwards all requests under basePath to better-auth, which handles:\n * - Email/password authentication\n * - OAuth providers (Google, GitHub, etc.)\n * - Session management\n * - Password reset\n * - Email verification\n * - 2FA, passkeys, magic links (if enabled)\n */\n private registerAuthRoutes(httpServer: IHttpServer, ctx: PluginContext): void {\n if (!this.authManager) return;\n\n const basePath = this.options.basePath || '/api/v1/auth';\n\n // Get raw Hono app to use native wildcard routing\n // Type assertion is safe here because we explicitly require Hono server as a dependency\n if (!('getRawApp' in httpServer) || typeof (httpServer as any).getRawApp !== 'function') {\n ctx.logger.error('HTTP server does not support getRawApp() - wildcard routing requires Hono server');\n throw new Error(\n 'AuthPlugin requires HonoServerPlugin for wildcard routing support. ' +\n 'Please ensure HonoServerPlugin is loaded before AuthPlugin.'\n );\n }\n\n const rawApp = (httpServer as any).getRawApp();\n\n // Register wildcard route to forward all auth requests to better-auth.\n // better-auth is configured with basePath matching our route prefix, so we\n // forward the original request directly — no path rewriting needed.\n rawApp.all(`${basePath}/*`, async (c: any) => {\n try {\n // Forward the original request to better-auth handler\n const response = await this.authManager!.handleRequest(c.req.raw);\n\n // better-auth catches internal errors and returns error Responses\n // without throwing, so the catch block below would never trigger.\n // We proactively log server errors here for observability.\n if (response.status >= 500) {\n try {\n const body = await response.clone().text();\n ctx.logger.error('[AuthPlugin] better-auth returned server error', new Error(`HTTP ${response.status}: ${body}`));\n } catch {\n ctx.logger.error('[AuthPlugin] better-auth returned server error', new Error(`HTTP ${response.status}: (unable to read body)`));\n }\n }\n \n return response;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n ctx.logger.error('Auth request error:', err);\n \n // Return error response\n return new Response(\n JSON.stringify({\n success: false,\n error: err.message,\n }),\n {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n });\n\n ctx.logger.info(`Auth routes registered: All requests under ${basePath}/* forwarded to better-auth`);\n }\n}\n\n\n\n", "// src/server.ts\nimport { createServer as createServerHTTP } from \"http\";\n\n// src/listener.ts\nimport { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from \"http2\";\n\n// src/request.ts\nimport { Http2ServerRequest } from \"http2\";\nimport { Readable } from \"stream\";\nvar RequestError = class extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = \"RequestError\";\n }\n};\nvar toRequestError = (e) => {\n if (e instanceof RequestError) {\n return e;\n }\n return new RequestError(e.message, { cause: e });\n};\nvar GlobalRequest = global.Request;\nvar Request = class extends GlobalRequest {\n constructor(input, options) {\n if (typeof input === \"object\" && getRequestCache in input) {\n input = input[getRequestCache]();\n }\n if (typeof options?.body?.getReader !== \"undefined\") {\n ;\n options.duplex ??= \"half\";\n }\n super(input, options);\n }\n};\nvar newHeadersFromIncoming = (incoming) => {\n const headerRecord = [];\n const rawHeaders = incoming.rawHeaders;\n for (let i = 0; i < rawHeaders.length; i += 2) {\n const { [i]: key, [i + 1]: value } = rawHeaders;\n if (key.charCodeAt(0) !== /*:*/\n 58) {\n headerRecord.push([key, value]);\n }\n }\n return new Headers(headerRecord);\n};\nvar wrapBodyStream = Symbol(\"wrapBodyStream\");\nvar newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n const init = {\n method,\n headers,\n signal: abortController.signal\n };\n if (method === \"TRACE\") {\n init.method = \"GET\";\n const req = new Request(url, init);\n Object.defineProperty(req, \"method\", {\n get() {\n return \"TRACE\";\n }\n });\n return req;\n }\n if (!(method === \"GET\" || method === \"HEAD\")) {\n if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) {\n init.body = new ReadableStream({\n start(controller) {\n controller.enqueue(incoming.rawBody);\n controller.close();\n }\n });\n } else if (incoming[wrapBodyStream]) {\n let reader;\n init.body = new ReadableStream({\n async pull(controller) {\n try {\n reader ||= Readable.toWeb(incoming).getReader();\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n });\n } else {\n init.body = Readable.toWeb(incoming);\n }\n }\n return new Request(url, init);\n};\nvar getRequestCache = Symbol(\"getRequestCache\");\nvar requestCache = Symbol(\"requestCache\");\nvar incomingKey = Symbol(\"incomingKey\");\nvar urlKey = Symbol(\"urlKey\");\nvar headersKey = Symbol(\"headersKey\");\nvar abortControllerKey = Symbol(\"abortControllerKey\");\nvar getAbortController = Symbol(\"getAbortController\");\nvar requestPrototype = {\n get method() {\n return this[incomingKey].method || \"GET\";\n },\n get url() {\n return this[urlKey];\n },\n get headers() {\n return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n },\n [getAbortController]() {\n this[getRequestCache]();\n return this[abortControllerKey];\n },\n [getRequestCache]() {\n this[abortControllerKey] ||= new AbortController();\n return this[requestCache] ||= newRequestFromIncoming(\n this.method,\n this[urlKey],\n this.headers,\n this[incomingKey],\n this[abortControllerKey]\n );\n }\n};\n[\n \"body\",\n \"bodyUsed\",\n \"cache\",\n \"credentials\",\n \"destination\",\n \"integrity\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"keepalive\"\n].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n get() {\n return this[getRequestCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n value: function() {\n return this[getRequestCache]()[k]();\n }\n });\n});\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: function(depth, options, inspectFn) {\n const props = {\n method: this.method,\n url: this.url,\n headers: this.headers,\n nativeRequest: this[requestCache]\n };\n return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;\n }\n});\nObject.setPrototypeOf(requestPrototype, Request.prototype);\nvar newRequest = (incoming, defaultHostname) => {\n const req = Object.create(requestPrototype);\n req[incomingKey] = incoming;\n const incomingUrl = incoming.url || \"\";\n if (incomingUrl[0] !== \"/\" && // short-circuit for performance. most requests are relative URL.\n (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n if (incoming instanceof Http2ServerRequest) {\n throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n }\n try {\n const url2 = new URL(incomingUrl);\n req[urlKey] = url2.href;\n } catch (e) {\n throw new RequestError(\"Invalid absolute URL\", { cause: e });\n }\n return req;\n }\n const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n if (!host) {\n throw new RequestError(\"Missing host header\");\n }\n let scheme;\n if (incoming instanceof Http2ServerRequest) {\n scheme = incoming.scheme;\n if (!(scheme === \"http\" || scheme === \"https\")) {\n throw new RequestError(\"Unsupported scheme\");\n }\n } else {\n scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n }\n const url = new URL(`${scheme}://${host}${incomingUrl}`);\n if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\\d+$/, \"\")) {\n throw new RequestError(\"Invalid host header\");\n }\n req[urlKey] = url.href;\n return req;\n};\n\n// src/response.ts\nvar responseCache = Symbol(\"responseCache\");\nvar getResponseCache = Symbol(\"getResponseCache\");\nvar cacheKey = Symbol(\"cache\");\nvar GlobalResponse = global.Response;\nvar Response2 = class _Response {\n #body;\n #init;\n [getResponseCache]() {\n delete this[cacheKey];\n return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);\n }\n constructor(body, init) {\n let headers;\n this.#body = body;\n if (init instanceof _Response) {\n const cachedGlobalResponse = init[responseCache];\n if (cachedGlobalResponse) {\n this.#init = cachedGlobalResponse;\n this[getResponseCache]();\n return;\n } else {\n this.#init = init.#init;\n headers = new Headers(init.#init.headers);\n }\n } else {\n this.#init = init;\n }\n if (typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) {\n ;\n this[cacheKey] = [init?.status || 200, body, headers || init?.headers];\n }\n }\n get headers() {\n const cache = this[cacheKey];\n if (cache) {\n if (!(cache[2] instanceof Headers)) {\n cache[2] = new Headers(\n cache[2] || { \"content-type\": \"text/plain; charset=UTF-8\" }\n );\n }\n return cache[2];\n }\n return this[getResponseCache]().headers;\n }\n get status() {\n return this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n }\n get ok() {\n const status = this.status;\n return status >= 200 && status < 300;\n }\n};\n[\"body\", \"bodyUsed\", \"redirected\", \"statusText\", \"trailers\", \"type\", \"url\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n get() {\n return this[getResponseCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n value: function() {\n return this[getResponseCache]()[k]();\n }\n });\n});\nObject.defineProperty(Response2.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: function(depth, options, inspectFn) {\n const props = {\n status: this.status,\n headers: this.headers,\n ok: this.ok,\n nativeResponse: this[responseCache]\n };\n return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;\n }\n});\nObject.setPrototypeOf(Response2, GlobalResponse);\nObject.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);\n\n// src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n const cancel = (error) => {\n reader.cancel(error).catch(() => {\n });\n };\n writable.on(\"close\", cancel);\n writable.on(\"error\", cancel);\n (currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n return reader.closed.finally(() => {\n writable.off(\"close\", cancel);\n writable.off(\"error\", cancel);\n });\n function handleStreamError(error) {\n if (error) {\n writable.destroy(error);\n }\n }\n function onDrain() {\n reader.read().then(flow, handleStreamError);\n }\n function flow({ done, value }) {\n try {\n if (done) {\n writable.end();\n } else if (!writable.write(value)) {\n writable.once(\"drain\", onDrain);\n } else {\n return reader.read().then(flow, handleStreamError);\n }\n } catch (e) {\n handleStreamError(e);\n }\n }\n}\nfunction writeFromReadableStream(stream, writable) {\n if (stream.locked) {\n throw new TypeError(\"ReadableStream is locked.\");\n } else if (writable.destroyed) {\n return;\n }\n return writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nvar buildOutgoingHttpHeaders = (headers) => {\n const res = {};\n if (!(headers instanceof Headers)) {\n headers = new Headers(headers ?? void 0);\n }\n const cookies = [];\n for (const [k, v] of headers) {\n if (k === \"set-cookie\") {\n cookies.push(v);\n } else {\n res[k] = v;\n }\n }\n if (cookies.length > 0) {\n res[\"set-cookie\"] = cookies;\n }\n res[\"content-type\"] ??= \"text/plain; charset=UTF-8\";\n return res;\n};\n\n// src/utils/response/constants.ts\nvar X_ALREADY_SENT = \"x-hono-already-sent\";\n\n// src/globals.ts\nimport crypto from \"crypto\";\nif (typeof global.crypto === \"undefined\") {\n global.crypto = crypto;\n}\n\n// src/listener.ts\nvar outgoingEnded = Symbol(\"outgoingEnded\");\nvar incomingDraining = Symbol(\"incomingDraining\");\nvar DRAIN_TIMEOUT_MS = 500;\nvar MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nvar drainIncoming = (incoming) => {\n const incomingWithDrainState = incoming;\n if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {\n return;\n }\n incomingWithDrainState[incomingDraining] = true;\n if (incoming instanceof Http2ServerRequest2) {\n try {\n ;\n incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);\n } catch {\n }\n return;\n }\n let bytesRead = 0;\n const cleanup = () => {\n clearTimeout(timer);\n incoming.off(\"data\", onData);\n incoming.off(\"end\", cleanup);\n incoming.off(\"error\", cleanup);\n };\n const forceClose = () => {\n cleanup();\n const socket = incoming.socket;\n if (socket && !socket.destroyed) {\n socket.destroySoon();\n }\n };\n const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n timer.unref?.();\n const onData = (chunk) => {\n bytesRead += chunk.length;\n if (bytesRead > MAX_DRAIN_BYTES) {\n forceClose();\n }\n };\n incoming.on(\"data\", onData);\n incoming.on(\"end\", cleanup);\n incoming.on(\"error\", cleanup);\n incoming.resume();\n};\nvar handleRequestError = () => new Response(null, {\n status: 400\n});\nvar handleFetchError = (e) => new Response(null, {\n status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500\n});\nvar handleResponseError = (e, outgoing) => {\n const err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n if (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") {\n console.info(\"The user aborted a request.\");\n } else {\n console.error(e);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n }\n outgoing.end(`Error: ${err.message}`);\n outgoing.destroy(err);\n }\n};\nvar flushHeaders = (outgoing) => {\n if (\"flushHeaders\" in outgoing && outgoing.writable) {\n outgoing.flushHeaders();\n }\n};\nvar responseViaCache = async (res, outgoing) => {\n let [status, body, header] = res[cacheKey];\n let hasContentLength = false;\n if (!header) {\n header = { \"content-type\": \"text/plain; charset=UTF-8\" };\n } else if (header instanceof Headers) {\n hasContentLength = header.has(\"content-length\");\n header = buildOutgoingHttpHeaders(header);\n } else if (Array.isArray(header)) {\n const headerObj = new Headers(header);\n hasContentLength = headerObj.has(\"content-length\");\n header = buildOutgoingHttpHeaders(headerObj);\n } else {\n for (const key in header) {\n if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n hasContentLength = true;\n break;\n }\n }\n }\n if (!hasContentLength) {\n if (typeof body === \"string\") {\n header[\"Content-Length\"] = Buffer.byteLength(body);\n } else if (body instanceof Uint8Array) {\n header[\"Content-Length\"] = body.byteLength;\n } else if (body instanceof Blob) {\n header[\"Content-Length\"] = body.size;\n }\n }\n outgoing.writeHead(status, header);\n if (typeof body === \"string\" || body instanceof Uint8Array) {\n outgoing.end(body);\n } else if (body instanceof Blob) {\n outgoing.end(new Uint8Array(await body.arrayBuffer()));\n } else {\n flushHeaders(outgoing);\n await writeFromReadableStream(body, outgoing)?.catch(\n (e) => handleResponseError(e, outgoing)\n );\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar isPromise = (res) => typeof res.then === \"function\";\nvar responseViaResponseObject = async (res, outgoing, options = {}) => {\n if (isPromise(res)) {\n if (options.errorHandler) {\n try {\n res = await res;\n } catch (err) {\n const errRes = await options.errorHandler(err);\n if (!errRes) {\n return;\n }\n res = errRes;\n }\n } else {\n res = await res.catch(handleFetchError);\n }\n }\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);\n if (res.body) {\n const reader = res.body.getReader();\n const values = [];\n let done = false;\n let currentReadPromise = void 0;\n if (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n let maxReadCount = 2;\n for (let i = 0; i < maxReadCount; i++) {\n currentReadPromise ||= reader.read();\n const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n console.error(e);\n done = true;\n });\n if (!chunk) {\n if (i === 1) {\n await new Promise((resolve) => setTimeout(resolve));\n maxReadCount = 3;\n continue;\n }\n break;\n }\n currentReadPromise = void 0;\n if (chunk.value) {\n values.push(chunk.value);\n }\n if (chunk.done) {\n done = true;\n break;\n }\n }\n if (done && !(\"content-length\" in resHeaderRecord)) {\n resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n }\n }\n outgoing.writeHead(res.status, resHeaderRecord);\n values.forEach((value) => {\n ;\n outgoing.write(value);\n });\n if (done) {\n outgoing.end();\n } else {\n if (values.length === 0) {\n flushHeaders(outgoing);\n }\n await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n }\n } else if (resHeaderRecord[X_ALREADY_SENT]) {\n } else {\n outgoing.writeHead(res.status, resHeaderRecord);\n outgoing.end();\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar getRequestListener = (fetchCallback, options = {}) => {\n const autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n if (options.overrideGlobalObjects !== false && global.Request !== Request) {\n Object.defineProperty(global, \"Request\", {\n value: Request\n });\n Object.defineProperty(global, \"Response\", {\n value: Response2\n });\n }\n return async (incoming, outgoing) => {\n let res, req;\n try {\n req = newRequest(incoming, options.hostname);\n let incomingEnded = !autoCleanupIncoming || incoming.method === \"GET\" || incoming.method === \"HEAD\";\n if (!incomingEnded) {\n ;\n incoming[wrapBodyStream] = true;\n incoming.on(\"end\", () => {\n incomingEnded = true;\n });\n if (incoming instanceof Http2ServerRequest2) {\n ;\n outgoing[outgoingEnded] = () => {\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n };\n }\n outgoing.on(\"finish\", () => {\n if (!incomingEnded) {\n drainIncoming(incoming);\n }\n });\n }\n outgoing.on(\"close\", () => {\n const abortController = req[abortControllerKey];\n if (abortController) {\n if (incoming.errored) {\n req[abortControllerKey].abort(incoming.errored.toString());\n } else if (!outgoing.writableFinished) {\n req[abortControllerKey].abort(\"Client connection prematurely closed.\");\n }\n }\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n });\n res = fetchCallback(req, { incoming, outgoing });\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n } catch (e) {\n if (!res) {\n if (options.errorHandler) {\n res = await options.errorHandler(req ? e : toRequestError(e));\n if (!res) {\n return;\n }\n } else if (!req) {\n res = handleRequestError();\n } else {\n res = handleFetchError(e);\n }\n } else {\n return handleResponseError(e, outgoing);\n }\n }\n try {\n return await responseViaResponseObject(res, outgoing, options);\n } catch (e) {\n return handleResponseError(e, outgoing);\n }\n };\n};\n\n// src/server.ts\nvar createAdaptorServer = (options) => {\n const fetchCallback = options.fetch;\n const requestListener = getRequestListener(fetchCallback, {\n hostname: options.hostname,\n overrideGlobalObjects: options.overrideGlobalObjects,\n autoCleanupIncoming: options.autoCleanupIncoming\n });\n const createServer = options.createServer || createServerHTTP;\n const server = createServer(options.serverOptions || {}, requestListener);\n return server;\n};\nvar serve = (options, listeningListener) => {\n const server = createAdaptorServer(options);\n server.listen(options?.port ?? 3e3, options.hostname, () => {\n const serverInfo = server.address();\n listeningListener && listeningListener(serverInfo);\n });\n return server;\n};\nexport {\n RequestError,\n createAdaptorServer,\n getRequestListener,\n serve\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Shared Schemas and Utilities\n * Common schemas used across multiple modules\n */\n\nexport * from './identifiers.zod';\nexport * from './mapping.zod';\nexport * from './http.zod';\nexport * from './enums.zod';\nexport * from './metadata-types.zod';\nexport * from './branded-types.zod';\nexport * from './suggestions.zod';\nexport * from './error-map.zod';\nexport * from './metadata-collection.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * System Identifier Schema\n * \n * Universal naming convention for all machine identifiers (API Names) in ObjectStack.\n * Enforces lowercase with underscores or dots to ensure:\n * - Cross-platform compatibility (case-insensitive filesystems)\n * - URL-friendliness (no encoding needed)\n * - Database consistency (no collation issues)\n * - Security (no case-sensitivity bugs in permission checks)\n * \n * **Applies to all metadata that acts as a machine identifier:**\n * - Object names (tables/collections)\n * - Field names\n * - Role names\n * - Permission set names\n * - Action/trigger names\n * - Event keys\n * - App IDs\n * - Menu/page IDs\n * - Select option values\n * - Workflow names\n * - Webhook names\n * \n * **Naming Convention Summary:**\n * | Type | Pattern | Example |\n * |------|---------|---------|\n * | Machine ID | snake_case | `crm_account`, `btn_submit`, `role_admin` |\n * | Event keys | dot.notation | `user.login`, `order.created` |\n * | Labels | Any case | `Client Account`, `Submit Form` |\n * \n * @example Valid identifiers\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * - 'order.created' (for events)\n * - 'api_v2_endpoint'\n * \n * @example Invalid identifiers (will be rejected)\n * - 'Account' (uppercase)\n * - 'CrmAccount' (camelCase)\n * - 'crm-account' (kebab-case - use underscore instead)\n * - 'user profile' (spaces)\n */\nexport const SystemIdentifierSchema = z\n .string()\n .min(2, { message: 'System identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., \"user_profile\" or \"order.created\")',\n })\n .describe('System identifier (lowercase with underscores or dots)');\n\n/**\n * Strict Snake Case Identifier\n * \n * More restrictive than SystemIdentifierSchema - only allows underscores (no dots).\n * Use this for identifiers that should NOT contain dots (e.g., database table/column names).\n * \n * @example Valid\n * - 'account'\n * - 'crm_account'\n * - 'user_profile'\n * \n * @example Invalid\n * - 'user.profile' (dots not allowed)\n * - 'UserProfile' (uppercase)\n */\nexport const SnakeCaseIdentifierSchema = z\n .string()\n .min(2, { message: 'Identifier must be at least 2 characters' })\n .regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., \"user_profile\")',\n })\n .describe('Snake case identifier (lowercase with underscores only)');\n\n/**\n * Event Name Identifier\n * \n * Specialized identifier for event names that encourages dot notation.\n * Used in event-driven systems, message queues, and webhooks.\n * \n * Pattern: `namespace.action` or `entity.event_type`\n * \n * @example Valid\n * - 'user.created'\n * - 'order.paid'\n * - 'user.login_success'\n * - 'alarm.high_cpu'\n * \n * @example Invalid\n * - 'UserCreated' (camelCase)\n * - 'user_created' (should use dots for namespacing)\n */\nexport const EventNameSchema = z\n .string()\n .min(3, { message: 'Event name must be at least 3 characters' })\n .regex(/^[a-z][a-z0-9_.]*$/, {\n message:\n 'Event name must be lowercase with dots for namespacing (e.g., \"user.created\", \"order.paid\")',\n })\n .describe('Event name (lowercase with dot notation for namespacing)');\n\n/**\n * Type Exports\n */\nexport type SystemIdentifier = z.infer;\nexport type SnakeCaseIdentifier = z.infer;\nexport type EventName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Base Field Mapping Protocol\n * \n * Shared by: ETL, Sync, Connector, External Lookup\n * \n * This module provides the canonical field mapping schema used across\n * ObjectStack for data transformation and synchronization.\n * \n * **Use Cases:**\n * - ETL pipelines (data/mapping.zod.ts)\n * - Data synchronization (automation/sync.zod.ts)\n * - Integration connectors (integration/connector.zod.ts)\n * - External lookups (data/external-lookup.zod.ts)\n * \n * @example Basic field mapping\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'external_user_id',\n * target: 'user_id',\n * };\n * ```\n * \n * @example With transformation\n * ```typescript\n * const mapping: FieldMapping = {\n * source: 'user_name',\n * target: 'name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: 'Unknown'\n * };\n * ```\n */\n\n/**\n * Transform Type Schema\n * \n * Defines the type of transformation to apply to a field value.\n * Implementations can extend this for domain-specific transforms.\n */\nexport const TransformTypeSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('constant'),\n value: z.unknown().describe('Constant value to use'),\n }).describe('Set a constant value'),\n \n z.object({\n type: z.literal('cast'),\n targetType: z.enum(['string', 'number', 'boolean', 'date']).describe('Target data type'),\n }).describe('Cast to a specific data type'),\n \n z.object({\n type: z.literal('lookup'),\n table: z.string().describe('Lookup table name'),\n keyField: z.string().describe('Field to match on'),\n valueField: z.string().describe('Field to retrieve'),\n }).describe('Lookup value from another table'),\n \n z.object({\n type: z.literal('javascript'),\n expression: z.string().describe('JavaScript expression (e.g., \"value.toUpperCase()\")'),\n }).describe('Custom JavaScript transformation'),\n \n z.object({\n type: z.literal('map'),\n mappings: z.record(z.string(), z.unknown()).describe('Value mappings (e.g., {\"Active\": \"active\"})'),\n }).describe('Map values using a dictionary'),\n]);\n\nexport type TransformType = z.infer;\n\n/**\n * Field Mapping Schema\n * \n * Base schema for mapping fields between source and target systems.\n * \n * **NAMING CONVENTION:**\n * - source: Field name in the source system\n * - target: Field name in the target system (should be snake_case for ObjectStack)\n * \n * @example\n * ```typescript\n * {\n * source: 'FirstName',\n * target: 'first_name',\n * transform: { type: 'cast', targetType: 'string' },\n * defaultValue: ''\n * }\n * ```\n */\nexport const FieldMappingSchema = z.object({\n /**\n * Source field name\n */\n source: z.string().describe('Source field name'),\n \n /**\n * Target field name (should be snake_case for ObjectStack)\n */\n target: z.string().describe('Target field name'),\n \n /**\n * Transformation to apply\n */\n transform: TransformTypeSchema.optional().describe('Transformation to apply'),\n \n /**\n * Default value if source is null/undefined\n */\n defaultValue: z.unknown().optional().describe('Default if source is null/undefined'),\n});\n\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Shared HTTP Schemas\n * \n * Common HTTP-related schemas used across API and System protocols.\n * These schemas ensure consistency across different parts of the stack.\n */\n\n// ==========================================\n// Basic HTTP Types\n// ==========================================\n\n/**\n * HTTP Method Enum\n */\nexport const HttpMethod = z.enum([\n 'GET', \n 'POST', \n 'PUT', \n 'DELETE', \n 'PATCH', \n 'HEAD', \n 'OPTIONS'\n]);\n\nexport type HttpMethod = z.infer;\n\n/**\n * HTTP Method Schema (subset for UI/View data sources)\n * Common HTTP methods used in view data source configurations.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\nexport type HttpMethodType = z.infer;\n\n/**\n * HTTP Request Configuration Schema\n * Defines a complete HTTP request configuration used by API data providers.\n * Migrated from ui/view.zod.ts to shared for reuse across modules.\n */\nexport const HttpRequestSchema = z.object({\n url: z.string().describe('API endpoint URL'),\n method: HttpMethodSchema.optional().default('GET').describe('HTTP method'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n params: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n body: z.unknown().optional().describe('Request body for POST/PUT/PATCH'),\n});\n\nexport type HttpRequest = z.infer;\n\n// ==========================================\n// CORS Configuration\n// ==========================================\n\n/**\n * CORS Configuration Schema\n * Cross-Origin Resource Sharing configuration\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\", \"https://app.example.com\"],\n * \"methods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n * \"credentials\": true,\n * \"maxAge\": 86400\n * }\n */\nexport const CorsConfigSchema = z.object({\n /**\n * Enable CORS\n */\n enabled: z.boolean().default(true).describe('Enable CORS'),\n \n /**\n * Allowed origins (* for all)\n */\n origins: z.union([\n z.string(),\n z.array(z.string())\n ]).default('*').describe('Allowed origins (* for all)'),\n \n /**\n * Allowed HTTP methods\n */\n methods: z.array(HttpMethod).optional().describe('Allowed HTTP methods'),\n \n /**\n * Allow credentials (cookies, authorization headers)\n */\n credentials: z.boolean().default(false).describe('Allow credentials (cookies, authorization headers)'),\n \n /**\n * Preflight cache duration in seconds\n */\n maxAge: z.number().int().optional().describe('Preflight cache duration in seconds'),\n});\n\nexport type CorsConfig = z.infer;\n\n// ==========================================\n// Rate Limiting\n// ==========================================\n\n/**\n * Rate Limit Configuration Schema\n * \n * Used by:\n * - api/endpoint.zod.ts (ApiEndpointSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"enabled\": true,\n * \"windowMs\": 60000,\n * \"maxRequests\": 100\n * }\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Enable rate limiting\n */\n enabled: z.boolean().default(false).describe('Enable rate limiting'),\n \n /**\n * Time window in milliseconds\n */\n windowMs: z.number().int().default(60000).describe('Time window in milliseconds'),\n \n /**\n * Max requests per window\n */\n maxRequests: z.number().int().default(100).describe('Max requests per window'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n// ==========================================\n// Static File Serving\n// ==========================================\n\n/**\n * Static Mount Configuration Schema\n * Configuration for serving static files\n * \n * Used by:\n * - api/router.zod.ts (RouterConfigSchema)\n * - system/http-server.zod.ts (HttpServerConfigSchema)\n * \n * @example\n * {\n * \"path\": \"/static\",\n * \"directory\": \"./public\",\n * \"cacheControl\": \"public, max-age=31536000\"\n * }\n */\nexport const StaticMountSchema = z.object({\n /**\n * URL path to serve from\n */\n path: z.string().describe('URL path to serve from'),\n \n /**\n * Physical directory to serve\n */\n directory: z.string().describe('Physical directory to serve'),\n \n /**\n * Cache-Control header value\n */\n cacheControl: z.string().optional().describe('Cache-Control header value'),\n});\n\nexport type StaticMount = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Shared Enumerations\n// ============================================================================\n\n/** Aggregation functions used across query, data-engine, analytics, field */\nexport const AggregationFunctionEnum = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'percentile', 'median', 'stddev', 'variance',\n]).describe('Standard aggregation functions');\nexport type AggregationFunction = z.infer;\n\n/** Sort direction used across query, data-engine, analytics */\nexport const SortDirectionEnum = z.enum(['asc', 'desc'])\n .describe('Sort order direction');\nexport type SortDirection = z.infer;\n\n/** Reusable sort item — field + direction pair used across views, data sources, filters */\nexport const SortItemSchema = z.object({\n field: z.string().describe('Field name to sort by'),\n order: SortDirectionEnum.describe('Sort direction'),\n}).describe('Sort field and direction pair');\nexport type SortItem = z.infer;\n\n/** CRUD mutation events used across hook, validation, object CDC */\nexport const MutationEventEnum = z.enum([\n 'insert', 'update', 'delete', 'upsert',\n]).describe('Data mutation event types');\nexport type MutationEvent = z.infer;\n\n/** Database isolation levels — unified format */\nexport const IsolationLevelEnum = z.enum([\n 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable', 'snapshot',\n]).describe('Transaction isolation levels (snake_case standard)');\nexport type IsolationLevel = z.infer;\n\n/** Cache eviction strategies */\nexport const CacheStrategyEnum = z.enum(['lru', 'lfu', 'ttl', 'fifo'])\n .describe('Cache eviction strategy');\nexport type CacheStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from './identifiers.zod';\n\n// ============================================================================\n// Shared Metadata Types\n// ============================================================================\n\n/** Supported metadata file formats */\nexport const MetadataFormatSchema = z.enum(['yaml', 'json', 'typescript', 'javascript'])\n .describe('Metadata file format');\nexport type MetadataFormat = z.infer;\n\n/** Base metadata record fields shared across kernel and system layers */\nexport const BaseMetadataRecordSchema = z.object({\n id: z.string().describe('Unique metadata record identifier'),\n type: z.string().describe('Metadata type (e.g. \"object\", \"view\", \"flow\")'),\n name: SnakeCaseIdentifierSchema.describe('Machine name (snake_case)'),\n format: MetadataFormatSchema.optional().describe('Source file format'),\n}).describe('Base metadata record fields shared across kernel and system');\nexport type BaseMetadataRecord = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema, SystemIdentifierSchema } from './identifiers.zod';\n\n/**\n * Branded Types for ObjectStack Identifiers\n *\n * Branded types provide compile-time safety by preventing accidental mixing\n * of different identifier kinds. For example, you cannot pass an ObjectName\n * where a FieldName is expected, even though both are strings at runtime.\n *\n * @example\n * ```ts\n * import { ObjectNameSchema, FieldNameSchema } from '@objectstack/spec';\n *\n * const objName = ObjectNameSchema.parse('project_task'); // ObjectName\n * const fieldName = FieldNameSchema.parse('task_name'); // FieldName\n *\n * // TypeScript will catch this at compile time:\n * // const fn: FieldName = objName; // Error!\n * ```\n */\n\n/**\n * ObjectName — Branded type for business object names.\n *\n * Must be snake_case (no dots). Used for table/collection names.\n *\n * @example 'project_task', 'crm_account', 'user_profile'\n */\nexport const ObjectNameSchema = SnakeCaseIdentifierSchema\n .brand<'ObjectName'>()\n .describe('Branded object name (snake_case, no dots)');\n\nexport type ObjectName = z.infer;\n\n/**\n * FieldName — Branded type for field (column) names.\n *\n * Must be snake_case (no dots). Used for column/property names within objects.\n *\n * @example 'first_name', 'created_at', 'total_amount'\n */\nexport const FieldNameSchema = SnakeCaseIdentifierSchema\n .brand<'FieldName'>()\n .describe('Branded field name (snake_case, no dots)');\n\nexport type FieldName = z.infer;\n\n/**\n * ViewName — Branded type for view identifiers.\n *\n * Must be a valid system identifier (lowercase, may contain dots for namespacing).\n *\n * @example 'all_tasks', 'my_open_deals', 'contact.recent'\n */\nexport const ViewNameSchema = SystemIdentifierSchema\n .brand<'ViewName'>()\n .describe('Branded view name (system identifier)');\n\nexport type ViewName = z.infer;\n\n/**\n * AppName — Branded type for application identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'crm', 'helpdesk', 'project_management'\n */\nexport const AppNameSchema = SystemIdentifierSchema\n .brand<'AppName'>()\n .describe('Branded app name (system identifier)');\n\nexport type AppName = z.infer;\n\n/**\n * FlowName — Branded type for flow identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'approval_flow', 'onboarding_wizard', 'lead_qualification'\n */\nexport const FlowNameSchema = SystemIdentifierSchema\n .brand<'FlowName'>()\n .describe('Branded flow name (system identifier)');\n\nexport type FlowName = z.infer;\n\n/**\n * RoleName — Branded type for role identifiers.\n *\n * Must be a valid system identifier.\n *\n * @example 'admin', 'sales_manager', 'read_only'\n */\nexport const RoleNameSchema = SystemIdentifierSchema\n .brand<'RoleName'>()\n .describe('Branded role name (system identifier)');\n\nexport type RoleName = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Field-level encryption protocol\n * GDPR/HIPAA/PCI-DSS compliant\n */\nexport const EncryptionAlgorithmSchema = z.enum([\n 'aes-256-gcm',\n 'aes-256-cbc',\n 'chacha20-poly1305',\n]).describe('Supported encryption algorithm');\n\nexport type EncryptionAlgorithm = z.infer;\n\nexport const KeyManagementProviderSchema = z.enum([\n 'local',\n 'aws-kms',\n 'azure-key-vault',\n 'gcp-kms',\n 'hashicorp-vault',\n]).describe('Key management service provider');\n\nexport type KeyManagementProvider = z.infer;\n\nexport const KeyRotationPolicySchema = z.object({\n enabled: z.boolean().default(false).describe('Enable automatic key rotation'),\n frequencyDays: z.number().min(1).default(90).describe('Rotation frequency in days'),\n retainOldVersions: z.number().default(3).describe('Number of old key versions to retain'),\n autoRotate: z.boolean().default(true).describe('Automatically rotate without manual approval'),\n}).describe('Policy for automatic encryption key rotation');\n\nexport type KeyRotationPolicy = z.infer;\nexport type KeyRotationPolicyInput = z.input;\n\nexport const EncryptionConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable field-level encryption'),\n algorithm: EncryptionAlgorithmSchema.default('aes-256-gcm').describe('Encryption algorithm'),\n keyManagement: z.object({\n provider: KeyManagementProviderSchema.describe('Key management service provider'),\n keyId: z.string().optional().describe('Key identifier in the provider'),\n rotationPolicy: KeyRotationPolicySchema.optional().describe('Key rotation policy'),\n }).describe('Key management configuration'),\n scope: z.enum(['field', 'record', 'table', 'database']).describe('Encryption scope level'),\n deterministicEncryption: z.boolean().default(false).describe('Allows equality queries on encrypted data'),\n searchableEncryption: z.boolean().default(false).describe('Allows search on encrypted data'),\n}).describe('Field-level encryption configuration');\n\nexport type EncryptionConfig = z.infer;\nexport type EncryptionConfigInput = z.input;\n\nexport const FieldEncryptionSchema = z.object({\n fieldName: z.string().describe('Name of the field to encrypt'),\n encryptionConfig: EncryptionConfigSchema.describe('Encryption settings for this field'),\n indexable: z.boolean().default(false).describe('Allow indexing on encrypted field'),\n}).describe('Per-field encryption assignment');\n\nexport type FieldEncryption = z.infer;\nexport type FieldEncryptionInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data masking protocol for PII protection\n */\nexport const MaskingStrategySchema = z.enum([\n 'redact', // Complete redaction: ****\n 'partial', // Partial masking: 138****5678\n 'hash', // Hash value: sha256(value)\n 'tokenize', // Tokenization: token-12345\n 'randomize', // Randomize: generate random value\n 'nullify', // Null value: null\n 'substitute', // Substitute with dummy data\n]).describe('Data masking strategy for PII protection');\n\nexport type MaskingStrategy = z.infer;\n\nexport const MaskingRuleSchema = z.object({\n field: z.string().describe('Field name to apply masking to'),\n strategy: MaskingStrategySchema.describe('Masking strategy to use'),\n pattern: z.string().optional().describe('Regex pattern for partial masking'),\n preserveFormat: z.boolean().default(true).describe('Keep the original data format after masking'),\n preserveLength: z.boolean().default(true).describe('Keep the original data length after masking'),\n roles: z.array(z.string()).optional().describe('Roles that see masked data'),\n exemptRoles: z.array(z.string()).optional().describe('Roles that see unmasked data'),\n}).describe('Masking rule for a single field');\n\nexport type MaskingRule = z.infer;\nexport type MaskingRuleInput = z.input;\n\nexport const MaskingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable data masking'),\n rules: z.array(MaskingRuleSchema).describe('List of field-level masking rules'),\n auditUnmasking: z.boolean().default(true).describe('Log when masked data is accessed unmasked'),\n}).describe('Top-level data masking configuration for PII protection');\n\nexport type MaskingConfig = z.infer;\nexport type MaskingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\nimport { EncryptionConfigSchema } from '../system/encryption.zod';\nimport { MaskingRuleSchema } from '../system/masking.zod';\n\n/**\n * Field Type Enum\n */\nexport const FieldType = z.enum([\n // Core Text\n 'text', 'textarea', 'email', 'url', 'phone', 'password',\n // Rich Content\n 'markdown', 'html', 'richtext',\n // Numbers\n 'number', 'currency', 'percent', \n // Date & Time\n 'date', 'datetime', 'time',\n // Logic\n 'boolean', 'toggle', // Toggle is a distinct UI from checkbox\n // Selection\n 'select', // Single select dropdown\n 'multiselect', // Multi select (often tags)\n 'radio', // Radio group\n 'checkboxes', // Checkbox group\n // Relational\n 'lookup', 'master_detail', // Dynamic reference\n 'tree', // Hierarchical reference\n // Media\n 'image', 'file', 'avatar', 'video', 'audio',\n // Calculated / System\n 'formula', 'summary', 'autonumber',\n // Enhanced Types\n 'location', // GPS coordinates\n 'address', // Structured address\n 'code', // Code editor (JSON/SQL/JS)\n 'json', // Structured JSON data\n 'color', // Color picker\n 'rating', // Star rating\n 'slider', // Numeric slider\n 'signature', // Digital signature\n 'qrcode', // QR code / Barcode\n 'progress', // Progress bar\n 'tags', // Simple tag list\n // AI/ML Types\n 'vector', // Vector embeddings for AI/ML (semantic search, RAG)\n]);\n\nexport type FieldType = z.infer;\n\n/**\n * Select Option Schema\n * \n * Defines option values for select/picklist fields.\n * \n * **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.\n * It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.\n * \n * @example Good\n * { label: 'New', value: 'new' }\n * { label: 'In Progress', value: 'in_progress' }\n * { label: 'Closed Won', value: 'closed_won' }\n * \n * @example Bad (will be rejected)\n * { label: 'New', value: 'New' } // uppercase\n * { label: 'In Progress', value: 'In Progress' } // spaces and uppercase\n * { label: 'Closed Won', value: 'Closed_Won' } // mixed case\n */\nexport const SelectOptionSchema = z.object({\n label: z.string().describe('Display label (human-readable, any case allowed)'),\n value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),\n color: z.string().optional().describe('Color code for badges/charts'),\n default: z.boolean().optional().describe('Is default option'),\n});\n\n/**\n * Location Coordinates Schema\n * GPS coordinates for location field type\n */\nexport const LocationCoordinatesSchema = z.object({\n latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),\n longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),\n altitude: z.number().optional().describe('Altitude in meters'),\n accuracy: z.number().optional().describe('Accuracy in meters'),\n});\n\n/**\n * Currency Configuration Schema\n * Configuration for currency field type supporting multi-currency\n * \n * Note: Currency codes are validated by length only (3 characters) to support:\n * - Standard ISO 4217 codes (USD, EUR, CNY, etc.)\n * - Cryptocurrency codes (BTC, ETH, etc.)\n * - Custom business-specific codes\n * Stricter validation can be implemented at the application layer based on business requirements.\n */\nexport const CurrencyConfigSchema = z.object({\n precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),\n currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),\n defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),\n});\n\n/**\n * Currency Value Schema\n * Runtime value structure for currency fields\n * \n * Note: Currency codes are validated by length only (3 characters) to support flexibility.\n * See CurrencyConfigSchema for details on currency code validation strategy.\n */\nexport const CurrencyValueSchema = z.object({\n value: z.number().describe('Monetary amount'),\n currency: z.string().length(3).describe('Currency code (ISO 4217)'),\n});\n\n/**\n * Address Schema\n * Structured address for address field type\n */\nexport const AddressSchema = z.object({\n street: z.string().optional().describe('Street address'),\n city: z.string().optional().describe('City name'),\n state: z.string().optional().describe('State/Province'),\n postalCode: z.string().optional().describe('Postal/ZIP code'),\n country: z.string().optional().describe('Country name or code'),\n countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),\n formatted: z.string().optional().describe('Formatted address string'),\n});\n\n/**\n * Vector Configuration Schema\n * Configuration for vector field type supporting AI/ML embeddings\n * \n * Vector fields store numerical embeddings for semantic search, similarity matching,\n * and Retrieval-Augmented Generation (RAG) workflows.\n * \n * @example\n * // Text embeddings for semantic search\n * {\n * dimensions: 1536, // OpenAI text-embedding-ada-002\n * distanceMetric: 'cosine',\n * indexed: true\n * }\n * \n * @example\n * // Image embeddings with normalization\n * {\n * dimensions: 512, // ResNet-50\n * distanceMetric: 'euclidean',\n * normalized: true,\n * indexed: true\n * }\n */\nexport const VectorConfigSchema = z.object({\n dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),\n distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),\n normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),\n indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),\n indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),\n});\n\n/**\n * File Attachment Configuration Schema\n * Configuration for file and attachment field types\n * \n * Provides comprehensive file upload capabilities with:\n * - File type restrictions (allowed/blocked)\n * - File size limits (min/max)\n * - Virus scanning integration\n * - Storage provider integration\n * - Image-specific features (dimensions, thumbnails)\n * \n * @example Basic file upload with size limit\n * {\n * maxSize: 10485760, // 10MB\n * allowedTypes: ['.pdf', '.docx', '.xlsx'],\n * virusScan: true\n * }\n * \n * @example Image upload with validation\n * {\n * maxSize: 5242880, // 5MB\n * allowedTypes: ['.jpg', '.jpeg', '.png', '.webp'],\n * imageValidation: {\n * maxWidth: 4096,\n * maxHeight: 4096,\n * generateThumbnails: true\n * }\n * }\n */\nexport const FileAttachmentConfigSchema = z.object({\n /** File Size Limits */\n minSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n maxSize: z.number().min(1).optional().describe('Maximum file size in bytes (e.g., 10485760 = 10MB)'),\n \n /** File Type Restrictions */\n allowedTypes: z.array(z.string()).optional().describe('Allowed file extensions (e.g., [\".pdf\", \".docx\", \".jpg\"])'),\n blockedTypes: z.array(z.string()).optional().describe('Blocked file extensions (e.g., [\".exe\", \".bat\", \".sh\"])'),\n allowedMimeTypes: z.array(z.string()).optional().describe('Allowed MIME types (e.g., [\"image/jpeg\", \"application/pdf\"])'),\n blockedMimeTypes: z.array(z.string()).optional().describe('Blocked MIME types'),\n \n /** Virus Scanning */\n virusScan: z.boolean().default(false).describe('Enable virus scanning for uploaded files'),\n virusScanProvider: z.enum(['clamav', 'virustotal', 'metadefender', 'custom']).optional().describe('Virus scanning service provider'),\n virusScanOnUpload: z.boolean().default(true).describe('Scan files immediately on upload'),\n quarantineOnThreat: z.boolean().default(true).describe('Quarantine files if threat detected'),\n \n /** Storage Configuration */\n storageProvider: z.string().optional().describe('Object storage provider name (references ObjectStorageConfig)'),\n storageBucket: z.string().optional().describe('Target bucket name'),\n storagePrefix: z.string().optional().describe('Storage path prefix (e.g., \"uploads/documents/\")'),\n \n /** Image-Specific Validation */\n imageValidation: z.object({\n minWidth: z.number().min(1).optional().describe('Minimum image width in pixels'),\n maxWidth: z.number().min(1).optional().describe('Maximum image width in pixels'),\n minHeight: z.number().min(1).optional().describe('Minimum image height in pixels'),\n maxHeight: z.number().min(1).optional().describe('Maximum image height in pixels'),\n aspectRatio: z.string().optional().describe('Required aspect ratio (e.g., \"16:9\", \"1:1\")'),\n generateThumbnails: z.boolean().default(false).describe('Auto-generate thumbnails'),\n thumbnailSizes: z.array(z.object({\n name: z.string().describe('Thumbnail variant name (e.g., \"small\", \"medium\", \"large\")'),\n width: z.number().min(1).describe('Thumbnail width in pixels'),\n height: z.number().min(1).describe('Thumbnail height in pixels'),\n crop: z.boolean().default(false).describe('Crop to exact dimensions'),\n })).optional().describe('Thumbnail size configurations'),\n preserveMetadata: z.boolean().default(false).describe('Preserve EXIF metadata'),\n autoRotate: z.boolean().default(true).describe('Auto-rotate based on EXIF orientation'),\n }).optional().describe('Image-specific validation rules'),\n \n /** Upload Behavior */\n allowMultiple: z.boolean().default(false).describe('Allow multiple file uploads (overrides field.multiple)'),\n allowReplace: z.boolean().default(true).describe('Allow replacing existing files'),\n allowDelete: z.boolean().default(true).describe('Allow deleting uploaded files'),\n requireUpload: z.boolean().default(false).describe('Require at least one file when field is required'),\n \n /** Metadata Extraction */\n extractMetadata: z.boolean().default(true).describe('Extract file metadata (name, size, type, etc.)'),\n extractText: z.boolean().default(false).describe('Extract text content from documents (OCR/parsing)'),\n \n /** Versioning */\n versioningEnabled: z.boolean().default(false).describe('Keep previous versions of replaced files'),\n maxVersions: z.number().min(1).optional().describe('Maximum number of versions to retain'),\n \n /** Access Control */\n publicRead: z.boolean().default(false).describe('Allow public read access to uploaded files'),\n presignedUrlExpiry: z.number().min(60).max(604800).default(3600).describe('Presigned URL expiration in seconds (default: 1 hour)'),\n}).refine((data) => {\n // Validate minSize is less than or equal to maxSize\n if (data.minSize !== undefined && data.maxSize !== undefined && data.minSize > data.maxSize) {\n return false;\n }\n return true;\n}, {\n message: 'minSize must be less than or equal to maxSize',\n}).refine((data) => {\n // Validate virusScanProvider requires virusScan to be enabled\n if (data.virusScanProvider !== undefined && data.virusScan !== true) {\n return false;\n }\n return true;\n}, {\n message: 'virusScanProvider requires virusScan to be enabled',\n});\n\n/**\n * Data Quality Rules Schema\n * Defines data quality validation and monitoring for fields\n * \n * @example Unique SSN field with completeness requirement\n * {\n * uniqueness: true,\n * completeness: 0.95, // 95% of records must have this field\n * accuracy: {\n * source: 'government_db',\n * threshold: 0.98\n * }\n * }\n */\nexport const DataQualityRulesSchema = z.object({\n /** Enforce uniqueness constraint */\n uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),\n \n /** Completeness ratio (0-1) indicating minimum percentage of non-null values */\n completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),\n \n /** Accuracy validation against authoritative source */\n accuracy: z.object({\n source: z.string().describe('Reference data source for validation (e.g., \"api.verify.com\", \"master_data\")'),\n threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),\n }).optional().describe('Accuracy validation configuration'),\n});\n\n/**\n * Computed Field Caching Schema\n * Configuration for caching computed/formula field results\n * \n * @example Cache product price with 1-hour TTL, invalidate on inventory changes\n * {\n * enabled: true,\n * ttl: 3600,\n * invalidateOn: ['inventory.quantity', 'pricing.discount']\n * }\n */\nexport const ComputedFieldCacheSchema = z.object({\n /** Enable caching for this computed field */\n enabled: z.boolean().describe('Enable caching for computed field results'),\n \n /** Time-to-live in seconds */\n ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),\n \n /** Array of field paths that trigger cache invalidation when changed */\n invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., [\"inventory.quantity\", \"pricing.base_price\"])'),\n});\n\n/**\n * Field Schema - Best Practice Enterprise Pattern\n */\n/**\n * Field Definition Schema\n * Defines the properties, type, and behavior of a single field (column) on an object.\n * \n * @example Lookup Field\n * {\n * name: \"account_id\",\n * label: \"Account\",\n * type: \"lookup\",\n * reference: \"accounts\",\n * required: true\n * }\n * \n * @example Select Field\n * {\n * name: \"status\",\n * label: \"Status\",\n * type: \"select\",\n * options: [\n * { label: \"Open\", value: \"open\" },\n * { label: \"Closed\", value: \"closed\" }\n * ],\n * defaultValue: \"open\"\n * }\n */\nexport const FieldSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),\n label: z.string().optional().describe('Human readable label'),\n type: FieldType.describe('Field Data Type'),\n description: z.string().optional().describe('Tooltip/Help text'),\n format: z.string().optional().describe('Format string (e.g. email, phone)'),\n\n /** Storage Layer Mapping */\n columnName: z.string().optional().describe('Physical column name in the target datasource. Defaults to the field key when not set.'),\n\n /** Database Constraints */\n required: z.boolean().default(false).describe('Is required'),\n searchable: z.boolean().default(false).describe('Is searchable'),\n multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),\n unique: z.boolean().default(false).describe('Is unique constraint'),\n defaultValue: z.unknown().optional().describe('Default value'),\n \n /** Text/String Constraints */\n maxLength: z.number().optional().describe('Max character length'),\n minLength: z.number().optional().describe('Min character length'),\n \n /** Number Constraints */\n precision: z.number().optional().describe('Total digits'),\n scale: z.number().optional().describe('Decimal places'),\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n\n /** Selection Options */\n options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),\n\n /**\n * Relationship Config\n * \n * Used by `lookup` and `master_detail` field types to define cross-object references.\n * The `reference` property is **required** for these types — it identifies the target\n * object whose records this field links to. The engine uses `reference` during $expand\n * post-processing to resolve foreign key IDs into full related objects via batch queries.\n * \n * For `master_detail` fields, the parent record controls the lifecycle of child records\n * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.\n */\n reference: z.string().optional().describe(\n 'Target object name (snake_case) for lookup/master_detail fields. '\n + 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'\n ),\n referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. \"active = true\")'),\n writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),\n deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),\n\n /** Calculation */\n expression: z.string().optional().describe('Formula expression'),\n summaryOperations: z.object({\n object: z.string().describe('Source child object name for roll-up'),\n field: z.string().describe('Field on child object to aggregate'),\n function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),\n }).optional().describe('Roll-up summary definition'),\n\n /** Enhanced Field Type Configurations */\n // Code field config\n language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),\n theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),\n lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),\n \n // Rating field config\n maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),\n allowHalf: z.boolean().optional().describe('Allow half-star ratings'),\n \n // Location field config\n displayMap: z.boolean().optional().describe('Display map widget for location field'),\n allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),\n \n // Address field config\n addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),\n \n // Color field config\n colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),\n allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),\n presetColors: z.array(z.string()).optional().describe('Preset color options'),\n \n // Slider field config\n step: z.number().optional().describe('Step increment for slider (default: 1)'),\n showValue: z.boolean().optional().describe('Display current value on slider'),\n marks: z.record(z.string(), z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: \"Low\", 50: \"Medium\", 100: \"High\"})'),\n \n // QR Code / Barcode field config\n // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'\n // Runtime validation should enforce this constraint\n barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),\n qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is \"qr\"'),\n displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),\n allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),\n\n // Currency field config\n currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),\n\n // Vector field config\n vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),\n\n // File attachment field config\n fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe('Configuration for file and attachment field types'),\n\n /** Enhanced Security & Compliance */\n // Encryption configuration\n encryptionConfig: EncryptionConfigSchema.optional().describe('Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)'),\n \n // Data masking rules\n maskingRule: MaskingRuleSchema.optional().describe('Data masking rules for PII protection'),\n \n // Audit trail\n auditTrail: z.boolean().default(false).describe('Enable detailed audit trail for this field (tracks all changes with user and timestamp)'),\n \n /** Field Dependencies & Relationships */\n // Field dependencies\n dependencies: z.array(z.string()).optional().describe('Array of field names that this field depends on (for formulas, visibility rules, etc.)'),\n \n /** Computed Field Optimization */\n // Computed field caching\n cached: ComputedFieldCacheSchema.optional().describe('Caching configuration for computed/formula fields'),\n \n /** Data Quality & Governance */\n // Data quality rules\n dataQuality: DataQualityRulesSchema.optional().describe('Data quality validation and monitoring rules'),\n\n /** Layout & Grouping */\n group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., \"contact_info\", \"billing\", \"system\")'),\n\n /** Conditional Requirements */\n conditionalRequired: z.string().optional().describe('Formula expression that makes this field required when TRUE (e.g., \"status = \\'closed_won\\'\")'),\n\n /** Security & Visibility */\n hidden: z.boolean().default(false).describe('Hidden from default UI'),\n readonly: z.boolean().default(false).describe('Read-only in UI'),\n sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),\n inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),\n trackFeedHistory: z.boolean().optional().describe('Track field changes in Chatter/activity feed (Salesforce pattern)'),\n caseSensitive: z.boolean().optional().describe('Whether text comparisons are case-sensitive'),\n autonumberFormat: z.string().optional().describe('Auto-number display format pattern (e.g., \"CASE-{0000}\")'),\n /** Indexing */\n index: z.boolean().default(false).describe('Create standard database index'),\n externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),\n});\n\nexport type Field = z.infer;\nexport type SelectOption = z.infer;\nexport type LocationCoordinates = z.infer;\nexport type Address = z.infer;\nexport type CurrencyConfig = z.infer;\nexport type CurrencyConfigInput = z.input;\nexport type CurrencyValue = z.infer;\nexport type VectorConfig = z.infer;\nexport type VectorConfigInput = z.input;\nexport type FileAttachmentConfig = z.infer;\nexport type FileAttachmentConfigInput = z.input;\nexport type DataQualityRules = z.infer;\nexport type DataQualityRulesInput = z.input;\nexport type ComputedFieldCache = z.infer;\n\n/**\n * Field Factory Helper\n */\nexport type FieldInput = Omit, 'type'>;\n\nexport const Field = {\n text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),\n textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),\n number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),\n boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),\n date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),\n datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),\n currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),\n percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),\n url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),\n email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),\n phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),\n image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),\n file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),\n avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),\n formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),\n summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),\n autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),\n markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),\n html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),\n password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),\n \n /**\n * Select field helper with backward-compatible API\n * \n * Automatically converts option values to lowercase to enforce naming conventions.\n * \n * @example Old API (array first) - auto-converts to lowercase\n * Field.select(['High', 'Low'], { label: 'Priority' })\n * // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]\n * \n * @example New API (config object) - enforces lowercase\n * Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })\n * \n * @example Multi-word values - converts to snake_case\n * Field.select(['In Progress', 'Closed Won'], { label: 'Status' })\n * // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]\n */\n select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {\n // Helper function to convert string to lowercase snake_case\n const toSnakeCase = (str: string): string => {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)\n };\n\n // Support both old and new signatures:\n // Old: Field.select(['a', 'b'], { label: 'X' })\n // New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })\n let options: SelectOption[];\n let finalConfig: FieldInput;\n \n if (Array.isArray(optionsOrConfig)) {\n // Old signature: array as first param\n options = optionsOrConfig.map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n finalConfig = config || {};\n } else {\n // New signature: config object with options\n options = (optionsOrConfig.options || []).map(o => \n typeof o === 'string' \n ? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case\n : { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase\n );\n // Remove options from config to avoid confusion\n const { options: _, ...restConfig } = optionsOrConfig;\n finalConfig = restConfig;\n }\n \n return { type: 'select', options, ...finalConfig } as const;\n },\n\n \n lookup: (reference: string, config: FieldInput = {}) => ({ \n type: 'lookup', \n reference, \n ...config \n } as const),\n \n masterDetail: (reference: string, config: FieldInput = {}) => ({ \n type: 'master_detail', \n reference, \n ...config \n } as const),\n\n // Enhanced Field Type Helpers\n location: (config: FieldInput = {}) => ({ \n type: 'location', \n ...config \n } as const),\n \n address: (config: FieldInput = {}) => ({ \n type: 'address', \n ...config \n } as const),\n \n richtext: (config: FieldInput = {}) => ({ \n type: 'richtext', \n ...config \n } as const),\n \n code: (language?: string, config: FieldInput = {}) => ({ \n type: 'code', \n language,\n ...config \n } as const),\n \n color: (config: FieldInput = {}) => ({ \n type: 'color', \n ...config \n } as const),\n \n rating: (maxRating: number = 5, config: FieldInput = {}) => ({ \n type: 'rating', \n maxRating,\n ...config \n } as const),\n \n signature: (config: FieldInput = {}) => ({ \n type: 'signature', \n ...config \n } as const),\n \n slider: (config: FieldInput = {}) => ({ \n type: 'slider', \n ...config \n } as const),\n \n qrcode: (config: FieldInput = {}) => ({ \n type: 'qrcode', \n ...config \n } as const),\n \n json: (config: FieldInput = {}) => ({ \n type: 'json', \n ...config \n } as const),\n \n vector: (dimensions: number, config: FieldInput = {}) => ({ \n type: 'vector', \n vectorConfig: {\n dimensions,\n distanceMetric: 'cosine' as const,\n normalized: false,\n indexed: true,\n ...config.vectorConfig\n },\n ...config \n } as const),\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { FieldType } from '../data/field.zod';\n\n/**\n * \"Did you mean?\" Suggestion Utilities\n *\n * Provides fuzzy matching for common ObjectStack identifiers.\n * Used by the custom error map to suggest corrections for typos.\n *\n * @example\n * ```ts\n * suggestFieldType('text_area'); // ['textarea']\n * suggestFieldType('String'); // ['text']\n * suggestFieldType('int'); // ['number']\n * ```\n */\n\n/**\n * Compute Levenshtein edit distance between two strings.\n * Uses space-optimized two-row approach (O(min(m,n)) space).\n */\nexport function levenshteinDistance(a: string, b: string): number {\n const la = a.length;\n const lb = b.length;\n\n if (la === 0) return lb;\n if (lb === 0) return la;\n\n // Use only two rows for space efficiency\n let prev = new Array(lb + 1);\n let curr = new Array(lb + 1);\n\n for (let j = 0; j <= lb; j++) {\n prev[j] = j;\n }\n\n for (let i = 1; i <= la; i++) {\n curr[0] = i;\n for (let j = 1; j <= lb; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n prev[j] + 1, // deletion\n curr[j - 1] + 1, // insertion\n prev[j - 1] + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n\n return prev[lb];\n}\n\n/**\n * Find the closest matches from a list of candidates.\n *\n * @param input - The user-provided (possibly invalid) value\n * @param candidates - Array of valid values to compare against\n * @param maxDistance - Maximum edit distance to consider (default: 3)\n * @param maxResults - Maximum number of suggestions to return (default: 3)\n * @returns Array of suggested values, sorted by similarity\n */\nexport function findClosestMatches(\n input: string,\n candidates: readonly string[],\n maxDistance = 3,\n maxResults = 3,\n): string[] {\n const normalized = input.toLowerCase().replace(/[-\\s]/g, '_');\n\n const scored = candidates\n .map((candidate) => ({\n value: candidate,\n distance: levenshteinDistance(normalized, candidate),\n }))\n .filter((s) => s.distance <= maxDistance && s.distance > 0)\n .sort((a, b) => a.distance - b.distance);\n\n return scored.slice(0, maxResults).map((s) => s.value);\n}\n\n/**\n * Well-known aliases that map common typos / alternative names to valid FieldTypes.\n */\nconst FIELD_TYPE_ALIASES: Record = {\n // Common alternative names\n string: 'text',\n str: 'text',\n varchar: 'text',\n char: 'text',\n int: 'number',\n integer: 'number',\n float: 'number',\n double: 'number',\n decimal: 'number',\n numeric: 'number',\n bool: 'boolean',\n checkbox: 'boolean',\n check: 'boolean',\n date_time: 'datetime',\n timestamp: 'datetime',\n // Common typos\n text_area: 'textarea',\n textarea_: 'textarea',\n textfield: 'text',\n dropdown: 'select',\n picklist: 'select',\n enum: 'select',\n multi_select: 'multiselect',\n multiselect_: 'multiselect',\n reference: 'lookup',\n ref: 'lookup',\n foreign_key: 'lookup',\n fk: 'lookup',\n relation: 'lookup',\n master: 'master_detail',\n richtext_: 'richtext',\n rich_text: 'richtext',\n upload: 'file',\n attachment: 'file',\n photo: 'image',\n picture: 'image',\n img: 'image',\n percent_: 'percent',\n percentage: 'percent',\n money: 'currency',\n price: 'currency',\n auto_number: 'autonumber',\n auto_increment: 'autonumber',\n sequence: 'autonumber',\n markdown_: 'markdown',\n md: 'markdown',\n barcode: 'qrcode',\n tag: 'tags',\n star: 'rating',\n stars: 'rating',\n geo: 'location',\n gps: 'location',\n coordinates: 'location',\n embed: 'vector',\n embedding: 'vector',\n embeddings: 'vector',\n};\n\n/**\n * Suggest valid FieldType values for an invalid input.\n *\n * First checks known aliases, then falls back to fuzzy matching.\n *\n * @param input - Invalid field type string\n * @returns Array of suggested valid FieldType values\n *\n * @example\n * ```ts\n * suggestFieldType('text_area'); // ['textarea']\n * suggestFieldType('String'); // ['text']\n * suggestFieldType('int'); // ['number']\n * suggestFieldType('dropdown'); // ['select']\n * ```\n */\nexport function suggestFieldType(input: string): string[] {\n const normalized = input.toLowerCase().replace(/[-\\s]/g, '_');\n\n // Check alias map first\n const alias = FIELD_TYPE_ALIASES[normalized];\n if (alias) {\n return [alias];\n }\n\n // Fall back to fuzzy matching\n return findClosestMatches(normalized, FieldType.options);\n}\n\n/**\n * Format a \"Did you mean?\" message for display.\n *\n * @param suggestions - Array of suggested values\n * @returns Formatted string or empty string if no suggestions\n */\nexport function formatSuggestion(suggestions: string[]): string {\n if (suggestions.length === 0) return '';\n if (suggestions.length === 1) return `Did you mean '${suggestions[0]}'?`;\n return `Did you mean one of: ${suggestions.map((s) => `'${s}'`).join(', ')}?`;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { suggestFieldType, formatSuggestion, findClosestMatches } from './suggestions.zod';\nimport { FieldType } from '../data/field.zod';\n\n/**\n * Zod v4 raw issue type used by the error map.\n */\nexport type ObjectStackRawIssue = z.core.$ZodRawIssue;\n\n/**\n * ObjectStack Custom Zod Error Map\n *\n * Provides contextual, actionable error messages for ObjectStack schema validation.\n * Instead of generic Zod messages like \"Invalid option\", this error map returns\n * messages that explain the ObjectStack context and suggest fixes.\n *\n * In Zod v4, the error map is a function `(issue) => { message: string } | string | null`.\n * Pass it via the `error` option on `.safeParse()` / `.parse()`.\n *\n * @example\n * ```ts\n * import { objectStackErrorMap } from '@objectstack/spec';\n *\n * // Per-parse usage\n * SomeSchema.safeParse(data, { error: objectStackErrorMap });\n * ```\n */\nexport const objectStackErrorMap = (issue: ObjectStackRawIssue): { message: string } | null => {\n // --- Invalid value (enum) with suggestions ---\n if (issue.code === 'invalid_value') {\n const values = issue.values as unknown[];\n const input = issue.input;\n const received = String(input ?? '');\n const options = values.map(String);\n\n // Check if this looks like a FieldType enum\n const fieldTypeOptions = FieldType.options as readonly string[];\n const isFieldTypeEnum = options.length > 10 &&\n fieldTypeOptions.every((ft) => options.includes(ft));\n\n if (isFieldTypeEnum) {\n const suggestions = suggestFieldType(received);\n const suggestion = formatSuggestion(suggestions);\n const base = `Invalid field type '${received}'.`;\n return {\n message: suggestion ? `${base} ${suggestion}` : `${base} Valid types: ${options.slice(0, 10).join(', ')}...`,\n };\n }\n\n // Generic enum suggestion\n const suggestions = findClosestMatches(received, options);\n const suggestion = formatSuggestion(suggestions);\n const base = `Invalid value '${received}'.`;\n return {\n message: suggestion\n ? `${base} ${suggestion}`\n : `${base} Expected one of: ${options.join(', ')}.`,\n };\n }\n\n // --- String/array/number size validation ---\n if (issue.code === 'too_small') {\n const origin = issue.origin as string;\n const minimum = issue.minimum as number;\n if (origin === 'string') {\n return {\n message: `Must be at least ${minimum} character${minimum === 1 ? '' : 's'} long.`,\n };\n }\n }\n\n if (issue.code === 'too_big') {\n const origin = issue.origin as string;\n const maximum = issue.maximum as number;\n if (origin === 'string') {\n return {\n message: `Must be at most ${maximum} character${maximum === 1 ? '' : 's'} long.`,\n };\n }\n }\n\n // --- String format validation (regex) ---\n if (issue.code === 'invalid_format') {\n const format = issue.format as string;\n const input = issue.input as string | undefined;\n if (format === 'regex' && input) {\n const pathArr = issue.path as (string | number)[] | undefined;\n const pathStr = pathArr?.join('.') ?? '';\n if (pathStr.endsWith('name') || pathStr === 'name') {\n return {\n message: `Invalid identifier '${input}'. Must be lowercase snake_case (e.g., 'my_object', 'task_name'). No uppercase, spaces, or hyphens allowed.`,\n };\n }\n }\n }\n\n // --- Missing required / type mismatch ---\n if (issue.code === 'invalid_type') {\n const expected = issue.expected as string;\n const input = issue.input;\n if (input === undefined) {\n const pathArr = issue.path as (string | number)[] | undefined;\n const field = pathArr?.[pathArr.length - 1] ?? '';\n return {\n message: `Required property '${field}' is missing.`,\n };\n }\n const receivedType = input === null ? 'null' : typeof input;\n return {\n message: `Expected ${expected} but received ${receivedType}.`,\n };\n }\n\n // --- Unrecognized keys ---\n if (issue.code === 'unrecognized_keys') {\n const keys = issue.keys as string[];\n const keyStr = keys.join(', ');\n return {\n message: `Unrecognized key${keys.length > 1 ? 's' : ''}: ${keyStr}. Check for typos in property names.`,\n };\n }\n\n // Fallback to Zod default\n return null;\n};\n\n/**\n * Zod Issue interface (subset needed for formatting).\n */\ninterface ZodIssueMinimal {\n path: PropertyKey[];\n message: string;\n code?: string;\n}\n\n/**\n * Format a single Zod issue into a human-readable line.\n *\n * @param issue - A single Zod issue\n * @returns Formatted string with path and message\n */\nexport function formatZodIssue(issue: ZodIssueMinimal): string {\n const path = issue.path.length > 0\n ? issue.path.join('.')\n : '(root)';\n return ` ✗ ${path}: ${issue.message}`;\n}\n\n/**\n * Pretty-print Zod validation errors for CLI output.\n *\n * Formats a ZodError into a readable block suitable for terminal display.\n * Groups errors by path depth and includes a summary count.\n *\n * @param error - A ZodError to format\n * @param label - Optional label for the error block (e.g., 'Stack validation failed')\n * @returns Formatted multi-line string\n *\n * @example\n * ```ts\n * import { formatZodError, ObjectStackDefinitionSchema } from '@objectstack/spec';\n *\n * const result = ObjectStackDefinitionSchema.safeParse(data);\n * if (!result.success) {\n * console.error(formatZodError(result.error, 'Stack validation failed'));\n * }\n * ```\n *\n * Output:\n * ```\n * Stack validation failed (3 issues):\n *\n * ✗ manifest.name: Required property 'name' is missing.\n * ✗ objects[0].fields.status.type: Invalid field type 'dropdown'. Did you mean 'select'?\n * ✗ views[0].object: Invalid identifier 'MyTasks'. Must be lowercase snake_case.\n * ```\n */\nexport function formatZodError(error: z.ZodError, label?: string): string {\n const count = error.issues.length;\n const header = label\n ? `${label} (${count} issue${count === 1 ? '' : 's'}):`\n : `Validation failed (${count} issue${count === 1 ? '' : 's'}):`;\n\n const lines = error.issues.map(formatZodIssue);\n\n return `${header}\\n\\n${lines.join('\\n')}`;\n}\n\n/**\n * Parse with the ObjectStack error map and return formatted errors.\n *\n * A convenience function that combines parsing with the custom error map\n * and pretty-print formatting. Returns a discriminated union result.\n *\n * @param schema - Any Zod schema to parse with\n * @param data - Data to validate\n * @param label - Optional label for error formatting\n * @returns Object with `success`, `data`, and optional `formatted` error string\n *\n * @example\n * ```ts\n * const result = safeParsePretty(ObjectStackDefinitionSchema, config, 'objectstack.config.ts');\n * if (!result.success) {\n * console.error(result.formatted);\n * process.exit(1);\n * }\n * ```\n */\nexport function safeParsePretty(\n schema: T,\n data: unknown,\n label?: string,\n): { success: true; data: z.infer } | { success: false; error: z.ZodError; formatted: string } {\n const result = schema.safeParse(data, { error: objectStackErrorMap });\n if (result.success) {\n return { success: true, data: result.data };\n }\n return {\n success: false,\n error: result.error,\n formatted: formatZodError(result.error, label),\n };\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Metadata Collection Utilities\n * \n * Provides support for defining metadata collections in either array or map (Record) format.\n * Map format automatically injects the key as the `name` field, following the same pattern\n * used by `fields` in ObjectSchema (which already uses `z.record(key, FieldSchema)`).\n * \n * ## Usage\n * \n * Both formats are accepted and normalized to arrays:\n * \n * ```ts\n * // Array format (traditional)\n * defineStack({\n * objects: [\n * { name: 'account', fields: { ... } },\n * { name: 'contact', fields: { ... } },\n * ]\n * });\n * \n * // Map format (key becomes `name`)\n * defineStack({\n * objects: {\n * account: { fields: { ... } },\n * contact: { fields: { ... } },\n * }\n * });\n * ```\n * \n * @module\n */\n\n/**\n * Input type for metadata collections: accepts either an array or a named map.\n * When using map format, the key is injected as the `name` field of each item.\n * \n * @typeParam T - The metadata item type (e.g., `ObjectSchema`, `AppSchema`)\n * \n * @example\n * ```ts\n * // Array format — name is required in each item\n * const apps: MetadataCollectionInput = [\n * { name: 'sales', label: 'Sales' },\n * { name: 'service', label: 'Service' },\n * ];\n * \n * // Map format — key serves as name, so name is optional in value\n * const apps: MetadataCollectionInput = {\n * sales: { label: 'Sales' },\n * service: { label: 'Service' },\n * };\n * ```\n */\nexport type MetadataCollectionInput =\n | T[]\n | Record & { name?: string }>;\n\n/**\n * List of metadata fields in ObjectStackDefinitionSchema that support map format.\n * These are fields where each item has a `name` field that can be inferred from the map key.\n * \n * Excluded fields:\n * - `views` — ViewSchema has no `name` field (it's a container with `list`/`form`)\n * - `objectExtensions` — uses `extend` as its identifier, not `name`\n * - `data` — DatasetSchema uses `object` as its identifier\n * - `translations` — TranslationBundleSchema is a record, not a named object\n * - `plugins` / `devPlugins` — not named metadata schemas\n */\nexport const MAP_SUPPORTED_FIELDS = [\n 'objects',\n 'apps',\n 'pages',\n 'dashboards',\n 'reports',\n 'actions',\n 'themes',\n 'workflows',\n 'approvals',\n 'flows',\n 'roles',\n 'permissions',\n 'sharingRules',\n 'policies',\n 'apis',\n 'webhooks',\n 'agents',\n 'ragPipelines',\n 'hooks',\n 'mappings',\n 'analyticsCubes',\n 'connectors',\n 'datasources',\n] as const;\n\nexport type MapSupportedField = (typeof MAP_SUPPORTED_FIELDS)[number];\n\n/**\n * Mapping from plural manifest field names to singular metadata type names.\n *\n * Manifest / `defineStack()` uses plural property names because they are\n * collection fields (e.g. `objects: [...]`, `apps: [...]`). The metadata\n * registry and `MetadataTypeSchema` use singular names as the canonical form.\n *\n * Use this mapping at the boundary where manifest fields are fed into the\n * metadata registry to ensure a consistent singular naming convention.\n */\nexport const PLURAL_TO_SINGULAR: Record = {\n objects: 'object',\n apps: 'app',\n pages: 'page',\n dashboards: 'dashboard',\n reports: 'report',\n actions: 'action',\n themes: 'theme',\n workflows: 'workflow',\n approvals: 'approval',\n flows: 'flow',\n roles: 'role',\n permissions: 'permission',\n profiles: 'profile',\n sharingRules: 'sharingRule',\n policies: 'policy',\n apis: 'api',\n webhooks: 'webhook',\n agents: 'agent',\n ragPipelines: 'ragPipeline',\n hooks: 'hook',\n mappings: 'mapping',\n analyticsCubes: 'analyticsCube',\n connectors: 'connector',\n datasources: 'datasource',\n views: 'view',\n};\n\n/** Reverse mapping: singular metadata type → plural manifest field name. */\nexport const SINGULAR_TO_PLURAL: Record = Object.fromEntries(\n Object.entries(PLURAL_TO_SINGULAR).map(([plural, singular]) => [singular, plural]),\n);\n\n/** Convert a plural manifest field name to its singular metadata type name. Returns the input unchanged if no mapping exists. */\nexport function pluralToSingular(key: string): string {\n return PLURAL_TO_SINGULAR[key] ?? key;\n}\n\n/** Convert a singular metadata type name to its plural manifest field name. Returns the input unchanged if no mapping exists. */\nexport function singularToPlural(key: string): string {\n return SINGULAR_TO_PLURAL[key] ?? key;\n}\n\n\n/**\n * Normalize a single metadata collection value from map format to array format.\n * If the input is already an array (or nullish), it is returned unchanged.\n * If the input is a plain object (map), it is converted to an array where\n * each key is injected as the `name` field of the corresponding item.\n * \n * **Precedence:** If an item already has a `name` property, it is preserved\n * (the map key is only used as a fallback).\n * \n * @param value - The raw input value (array, map, or nullish)\n * @param keyField - The field name to inject the key into (default: `'name'`)\n * @returns The normalized array, or the original value if already an array/nullish\n * \n * @example\n * ```ts\n * // Map input\n * normalizeMetadataCollection({\n * account: { fields: { name: { type: 'text' } } },\n * contact: { fields: { email: { type: 'email' } } },\n * });\n * // → [\n * // { name: 'account', fields: { name: { type: 'text' } } },\n * // { name: 'contact', fields: { email: { type: 'email' } } },\n * // ]\n * \n * // Array input (pass-through)\n * normalizeMetadataCollection([{ name: 'account', fields: {} }]);\n * // → [{ name: 'account', fields: {} }]\n * ```\n */\nexport function normalizeMetadataCollection(value: unknown, keyField = 'name'): unknown {\n // Nullish or already an array — pass through\n if (value == null || Array.isArray(value)) return value;\n\n // Plain object — treat as map and convert to array\n if (typeof value === 'object') {\n return Object.entries(value as Record).map(([key, item]) => {\n if (item && typeof item === 'object' && !Array.isArray(item)) {\n const obj = item as Record;\n // Only inject key if the item doesn't already have the field set\n if (!(keyField in obj) || obj[keyField] === undefined) {\n return { ...obj, [keyField]: key };\n }\n return obj;\n }\n // Non-object values (shouldn't happen, but let Zod handle the error)\n return item;\n });\n }\n\n // Other types — return as-is and let Zod validation handle the error\n return value;\n}\n\n/**\n * Normalize all metadata collections in a stack definition input.\n * Converts any map-formatted collections to arrays with key→name injection.\n * \n * This function is applied to the raw input before Zod validation,\n * ensuring the canonical internal format is always arrays.\n * \n * @param input - The raw stack definition input\n * @returns A new object with all map collections normalized to arrays\n */\nexport function normalizeStackInput>(input: T): T {\n const result = { ...input };\n for (const field of MAP_SUPPORTED_FIELDS) {\n if (field in result) {\n (result as Record)[field] = normalizeMetadataCollection(result[field]);\n }\n }\n return result;\n}\n\n/**\n * Mapping of legacy / alternative field names to their canonical names\n * in `ObjectStackDefinitionSchema`.\n *\n * Plugins may use legacy names (e.g., `triggers` instead of `hooks`).\n * This map lets `normalizePluginMetadata()` rewrite them automatically.\n */\nexport const METADATA_ALIASES: Record = {\n triggers: 'hooks',\n};\n\n/**\n * Normalize plugin metadata so it matches the canonical format expected by the runtime.\n *\n * This handles two issues that commonly arise when loading third-party plugin metadata:\n *\n * 1. **Map → Array conversion** — plugins often define metadata as maps\n * (e.g., `actions: { convert_lead: { ... } }`), but the runtime expects arrays.\n * Every key listed in {@link MAP_SUPPORTED_FIELDS} is normalized via\n * {@link normalizeMetadataCollection}.\n *\n * 2. **Field aliasing** — plugins may use legacy or alternative field names\n * (e.g., `triggers` instead of `hooks`). {@link METADATA_ALIASES} maps them\n * to their canonical counterparts.\n *\n * 3. **Recursive normalization** — if the plugin itself contains nested `plugins`,\n * each nested plugin is normalized recursively.\n *\n * @param metadata - Raw plugin metadata object\n * @returns A new object with all collections normalized to arrays, aliases resolved,\n * and nested plugins recursively normalized\n *\n * @example\n * ```ts\n * const raw = {\n * actions: { lead_convert: { type: 'custom', label: 'Convert' } },\n * triggers: { lead_scoring: { object: 'lead', event: 'afterInsert' } },\n * };\n * const normalized = normalizePluginMetadata(raw);\n * // normalized.actions → [{ name: 'lead_convert', type: 'custom', label: 'Convert' }]\n * // normalized.hooks → [{ name: 'lead_scoring', object: 'lead', event: 'afterInsert' }]\n * // normalized.triggers → removed (merged into hooks)\n * ```\n */\nexport function normalizePluginMetadata>(metadata: T): T {\n const result = { ...metadata };\n\n // 1. Resolve aliases (e.g. triggers → hooks), merging with any existing canonical values\n for (const [alias, canonical] of Object.entries(METADATA_ALIASES)) {\n if (alias in result) {\n const aliasValue = normalizeMetadataCollection(result[alias]);\n const canonicalValue = normalizeMetadataCollection(result[canonical]);\n\n // Merge: canonical array wins; alias values are appended\n if (Array.isArray(aliasValue)) {\n (result as Record)[canonical] = Array.isArray(canonicalValue)\n ? [...canonicalValue, ...aliasValue]\n : aliasValue;\n }\n\n delete (result as Record)[alias];\n }\n }\n\n // 2. Normalize map-formatted collections → arrays\n for (const field of MAP_SUPPORTED_FIELDS) {\n if (field in result) {\n (result as Record)[field] = normalizeMetadataCollection(result[field]);\n }\n }\n\n // 3. Recursively normalize nested plugins\n if (Array.isArray(result.plugins)) {\n (result as Record).plugins = result.plugins.map((p: unknown) => {\n if (p && typeof p === 'object' && !Array.isArray(p)) {\n return normalizePluginMetadata(p as Record);\n }\n return p;\n });\n }\n\n return result;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './query.zod';\nexport * from './filter.zod';\nexport * from './object.zod';\nexport * from './field.zod';\nexport * from './validation.zod';\nexport * from './hook.zod';\nexport * from './mapping.zod';\nexport * from './data-engine.zod';\nexport * from './driver.zod';\nexport * from './driver-sql.zod';\nexport * from './driver-nosql.zod';\n\nexport * from './dataset.zod';\n\n// Seed Loader Protocol (Relationship Resolution & Dependency Ordering)\nexport * from './seed-loader.zod';\n\n// Document Management Protocol\nexport * from './document.zod';\n\n// External Lookup Protocol\nexport * from './external-lookup.zod';\nexport * from './datasource.zod';\n\n// Analytics Protocol (Semantic Layer)\nexport * from './analytics.zod';\n\n// Feed & Activity Protocol\nexport * from './feed.zod';\n\n// Subscription Protocol\nexport * from './subscription.zod';\n\n// Turso Multi-Tenant Driver\nexport * from './driver/turso-multi-tenant.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Query DSL Specification\n * \n * Based on industry best practices from:\n * - Prisma ORM\n * - Strapi CMS\n * - TypeORM\n * - LoopBack Framework\n * \n * Version: 1.0.0\n * Status: Draft\n * \n * Objective: Define a JSON-based, database-agnostic query syntax standard\n * for data filtering interactions between frontend and backend APIs.\n * \n * Design Principles:\n * 1. Declarative: Frontend describes \"what data to get\", not \"how to query\"\n * 2. Database Agnostic: Syntax contains no database-specific directives\n * 3. Type Safe: Structure can be statically inferred by TypeScript\n * 4. Convention over Configuration: Implicit syntax for common queries\n */\n\n/**\n * Field Reference\n * Represents a reference to another field/column instead of a literal value.\n * Used for joins (ON clause) and cross-field comparisons.\n * \n * @example\n * // user.id = order.owner_id\n * { \"$eq\": { \"$field\": \"order.owner_id\" } }\n */\nexport const FieldReferenceSchema = z.object({\n $field: z.string().describe('Field Reference/Column Name')\n});\n\nexport type FieldReference = z.infer;\n\n// ============================================================================\n// 3.1 Comparison Operators\n// ============================================================================\n\n/**\n * Comparison operators for equality and inequality checks.\n * Supported data types: Any\n */\nexport const EqualityOperatorSchema = z.object({\n /** Equal to (default) - SQL: = | MongoDB: $eq */\n $eq: z.any().optional(),\n \n /** Not equal to - SQL: <> or != | MongoDB: $ne */\n $ne: z.any().optional(),\n});\n\n/**\n * Comparison operators for numeric and date comparisons.\n * Supported data types: Number, Date\n */\nexport const ComparisonOperatorSchema = z.object({\n /** Greater than - SQL: > | MongoDB: $gt */\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Greater than or equal to - SQL: >= | MongoDB: $gte */\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than - SQL: < | MongoDB: $lt */\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n /** Less than or equal to - SQL: <= | MongoDB: $lte */\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n});\n\n// ============================================================================\n// 3.2 Set & Range Operators\n// ============================================================================\n\n/**\n * Set operators for membership checks.\n */\nexport const SetOperatorSchema = z.object({\n /** In list - SQL: IN (?, ?, ?) | MongoDB: $in */\n $in: z.array(z.any()).optional(),\n \n /** Not in list - SQL: NOT IN (...) | MongoDB: $nin */\n $nin: z.array(z.any()).optional(),\n});\n\n/**\n * Range operator for interval checks (closed interval).\n * SQL: BETWEEN ? AND ? | MongoDB: $gte AND $lte\n */\nexport const RangeOperatorSchema = z.object({\n /** Between (inclusive) - takes [min, max] array */\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n});\n\n// ============================================================================\n// 3.3 String-Specific Operators\n// ============================================================================\n\n/**\n * String pattern matching operators.\n * Note: Case sensitivity should be handled at backend level.\n */\nexport const StringOperatorSchema = z.object({\n /** Contains substring - SQL: LIKE %?% | MongoDB: $regex */\n $contains: z.string().optional(),\n \n /** Does not contain substring - SQL: NOT LIKE %?% | MongoDB: $not: $regex */\n $notContains: z.string().optional(),\n \n /** Starts with prefix - SQL: LIKE ?% | MongoDB: $regex */\n $startsWith: z.string().optional(),\n \n /** Ends with suffix - SQL: LIKE %? | MongoDB: $regex */\n $endsWith: z.string().optional(),\n});\n\n// ============================================================================\n// 3.5 Special Operators\n// ============================================================================\n\n/**\n * Special check operators for null and existence.\n */\nexport const SpecialOperatorSchema = z.object({\n /** Is null check - SQL: IS NULL (true) / IS NOT NULL (false) | MongoDB: field: null */\n $null: z.boolean().optional(),\n \n /** Field exists check (primarily for NoSQL) - MongoDB: $exists */\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// Combined Field Operators\n// ============================================================================\n\n/**\n * All field-level operators combined.\n * These can be applied to individual fields in a filter.\n */\nexport const FieldOperatorsSchema = z.object({\n // Equality\n $eq: z.any().optional(),\n $ne: z.any().optional(),\n \n // Comparison (numeric/date)\n $gt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $gte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lt: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n $lte: z.union([z.number(), z.date(), FieldReferenceSchema]).optional(),\n \n // Set & Range\n $in: z.array(z.any()).optional(),\n $nin: z.array(z.any()).optional(),\n $between: z.tuple([\n z.union([z.number(), z.date(), FieldReferenceSchema]),\n z.union([z.number(), z.date(), FieldReferenceSchema])\n ]).optional(),\n \n // String-specific\n $contains: z.string().optional(),\n $notContains: z.string().optional(),\n $startsWith: z.string().optional(),\n $endsWith: z.string().optional(),\n \n // Special\n $null: z.boolean().optional(),\n $exists: z.boolean().optional(),\n});\n\n// ============================================================================\n// 3.4 Logical Operators & Recursive Filter Structure\n// ============================================================================\n\n/**\n * Recursive filter type that supports:\n * 1. Implicit equality: { field: value }\n * 2. Explicit operators: { field: { $op: value } }\n * 3. Logical combinations: { $and: [...], $or: [...], $not: {...} }\n * 4. Nested relations: { relation: { field: value } }\n */\nexport type FilterCondition = {\n [key: string]: \n | any // Implicit equality: key: value\n | z.infer // Explicit operators: key: { $op: value }\n | FilterCondition; // Nested relation: key: { nested: ... }\n} & {\n /** Logical AND - combines all conditions that must be true */\n $and?: FilterCondition[];\n \n /** Logical OR - at least one condition must be true */\n $or?: FilterCondition[];\n \n /** Logical NOT - negates the condition */\n $not?: FilterCondition;\n};\n\n/**\n * Zod schema for recursive filter validation.\n * Uses z.lazy() to handle recursive structure.\n */\nexport const FilterConditionSchema: z.ZodType = z.lazy(() =>\n z.record(z.string(), z.unknown()).and(\n z.object({\n $and: z.array(FilterConditionSchema).optional(),\n $or: z.array(FilterConditionSchema).optional(),\n $not: FilterConditionSchema.optional(),\n })\n )\n);\n\n// ============================================================================\n// Query Filter Wrapper\n// ============================================================================\n\n/**\n * Top-level query filter wrapper.\n * This is typically used as the \"where\" clause in a query.\n * \n * @example\n * ```typescript\n * const filter: QueryFilter = {\n * where: {\n * status: \"active\", // Implicit equality\n * age: { $gte: 18 }, // Explicit operator\n * $or: [ // Logical combination\n * { role: \"admin\" },\n * { email: { $contains: \"@company.com\" } }\n * ],\n * profile: { // Nested relation\n * verified: true\n * }\n * }\n * }\n * ```\n */\nexport const QueryFilterSchema = z.object({\n where: FilterConditionSchema.optional(),\n});\n\n// ============================================================================\n// TypeScript Type Exports\n// ============================================================================\n\n/**\n * Type-safe filter operators for use in TypeScript.\n * \n * @example\n * ```typescript\n * type UserFilter = Filter;\n * \n * const filter: UserFilter = {\n * age: { $gte: 18 },\n * email: { $contains: \"@example.com\" }\n * };\n * ```\n */\nexport type Filter = {\n [K in keyof T]?: \n | T[K] // Implicit equality\n | {\n $eq?: T[K];\n $ne?: T[K];\n $gt?: T[K] extends number | Date ? T[K] : never;\n $gte?: T[K] extends number | Date ? T[K] : never;\n $lt?: T[K] extends number | Date ? T[K] : never;\n $lte?: T[K] extends number | Date ? T[K] : never;\n $in?: T[K][];\n $nin?: T[K][];\n $between?: T[K] extends number | Date ? [T[K], T[K]] : never;\n $contains?: T[K] extends string ? string : never;\n $notContains?: T[K] extends string ? string : never;\n $startsWith?: T[K] extends string ? string : never;\n $endsWith?: T[K] extends string ? string : never;\n $null?: boolean;\n $exists?: boolean;\n }\n | (T[K] extends object ? Filter : never); // Nested relation\n} & {\n $and?: Filter[];\n $or?: Filter[];\n $not?: Filter;\n};\n\n/**\n * Scalar types supported by the filter system.\n */\nexport type Scalar = string | number | boolean | Date | null;\n\n// Export inferred types\nexport type FieldOperators = z.infer;\nexport type QueryFilter = z.infer;\n\n// ============================================================================\n// Normalization Utilities (Internal Representation)\n// ============================================================================\n\n/**\n * Normalized filter AST structure.\n * This is the internal representation after converting all syntactic sugar\n * to explicit operators.\n * \n * Stage 1: Normalization Pass\n * Input: { age: 18, role: \"admin\" }\n * Output: { $and: [{ age: { $eq: 18 } }, { role: { $eq: \"admin\" } }] }\n * \n * This simplifies adapter implementation by providing a consistent structure.\n */\nexport const NormalizedFilterSchema: z.ZodType = z.lazy(() => \n z.object({\n $and: z.array(\n z.union([\n // Field condition: { field: { $op: value } }\n z.record(z.string(), FieldOperatorsSchema),\n // Nested logical group\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $or: z.array(\n z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ])\n ).optional(),\n \n $not: z.union([\n z.record(z.string(), FieldOperatorsSchema),\n NormalizedFilterSchema,\n ]).optional(),\n })\n);\n\nexport type NormalizedFilter = z.infer;\n\n// ============================================================================\n// AST Array Format Detection & Validation\n// ============================================================================\n\n/**\n * Set of valid AST comparison operators (case-insensitive).\n * Used by `isFilterAST()` to validate AST structure beyond `Array.isArray`.\n */\nexport const VALID_AST_OPERATORS = new Set([\n '=', '==', '!=', '<>', '>', '>=', '<', '<=',\n 'in', 'nin', 'not_in',\n 'contains', 'notcontains', 'not_contains', 'like',\n 'startswith', 'starts_with',\n 'endswith', 'ends_with',\n 'between',\n 'is_null', 'is_not_null',\n]);\n\n/**\n * Detect whether a value is a valid Filter AST array structure.\n *\n * A valid AST is one of:\n * - Comparison node: `[field: string, operator: string, value: unknown]` where operator is a known operator\n * - Logical node: `[\"and\" | \"or\", ...children]` where children are valid AST nodes\n * - Legacy flat array: `[[cond], [cond], ...]` where all elements are sub-arrays (each a valid AST node)\n *\n * This replaces the naïve `Array.isArray(filter)` check, preventing accidental\n * misidentification of arbitrary arrays as filter ASTs.\n *\n * @example\n * isFilterAST([\"status\", \"=\", \"active\"]) // true\n * isFilterAST([\"and\", [\"a\", \"=\", 1], [\"b\", \">\", 2]]) // true\n * isFilterAST([[\"a\", \"=\", 1], [\"b\", \"=\", 2]]) // true (legacy)\n * isFilterAST([1, 2, 3]) // false\n * isFilterAST(\"not an array\") // false\n * isFilterAST({ status: \"active\" }) // false\n */\nexport function isFilterAST(filter: unknown): boolean {\n if (!Array.isArray(filter) || filter.length === 0) return false;\n\n const first = filter[0];\n\n // Logical node: [\"and\", ...] or [\"or\", ...]\n if (typeof first === 'string') {\n const lower = first.toLowerCase();\n if (lower === 'and' || lower === 'or') {\n return filter.length >= 2 && filter.slice(1).every((child: unknown) => isFilterAST(child));\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof filter[1] === 'string') {\n return VALID_AST_OPERATORS.has(filter[1].toLowerCase());\n }\n }\n\n // Legacy flat array: [[cond], [cond], ...]\n if (filter.every((item: unknown) => isFilterAST(item))) {\n return filter.length > 0;\n }\n\n return false;\n}\n\n// ============================================================================\n// AST Array → FilterCondition Conversion\n// ============================================================================\n\n/**\n * Operator mapping from AST infix operators to FilterCondition `$`-prefixed operators.\n */\nconst AST_OPERATOR_MAP: Record = {\n '=': '$eq',\n '==': '$eq',\n '!=': '$ne',\n '<>': '$ne',\n '>': '$gt',\n '>=': '$gte',\n '<': '$lt',\n '<=': '$lte',\n 'in': '$in',\n 'nin': '$nin',\n 'not_in': '$nin',\n 'contains': '$contains',\n 'notcontains': '$notContains',\n 'not_contains': '$notContains',\n 'like': '$contains',\n 'startswith': '$startsWith',\n 'starts_with': '$startsWith',\n 'endswith': '$endsWith',\n 'ends_with': '$endsWith',\n 'between': '$between',\n 'is_null': '$null',\n 'is_not_null': '$null',\n};\n\n/**\n * Convert a single AST comparison node `[field, operator, value]` to a FilterCondition object.\n */\nfunction convertComparison(node: [string, string, unknown]): FilterCondition {\n const [field, operator, value] = node;\n const op = operator.toLowerCase();\n\n // Special case: equality shorthand\n if (op === '=' || op === '==') {\n return { [field]: value } as FilterCondition;\n }\n\n // Null check operators\n if (op === 'is_null') {\n return { [field]: { $null: true } } as FilterCondition;\n }\n if (op === 'is_not_null') {\n return { [field]: { $null: false } } as FilterCondition;\n }\n\n const mapped = AST_OPERATOR_MAP[op];\n if (mapped) {\n return { [field]: { [mapped]: value } } as FilterCondition;\n }\n\n // Fallback: use the operator as-is with $ prefix\n return { [field]: { [`$${op}`]: value } } as FilterCondition;\n}\n\n/**\n * Parse a filter from AST array format to FilterCondition object format.\n *\n * The AST array format is used by the ObjectUI client and the `FilterBuilder`:\n * - Comparison: `[field, operator, value]` → `{ field: value }` or `{ field: { $op: value } }`\n * - Logical AND: `[\"and\", cond1, cond2, ...]` → `{ $and: [...] }`\n * - Logical OR: `[\"or\", cond1, cond2, ...]` → `{ $or: [...] }`\n *\n * If the input is already a FilterCondition object (not an array), it is returned as-is.\n * If the input is `null` or `undefined`, it is returned as-is.\n *\n * @example\n * // Simple condition\n * parseFilterAST([\"status\", \"=\", \"active\"])\n * // → { status: \"active\" }\n *\n * @example\n * // Compound AND\n * parseFilterAST([\"and\", [\"priority\", \"=\", \"high\"], [\"status\", \"=\", \"active\"]])\n * // → { $and: [{ priority: \"high\" }, { status: \"active\" }] }\n *\n * @example\n * // Object passthrough\n * parseFilterAST({ status: \"active\" })\n * // → { status: \"active\" }\n */\nexport function parseFilterAST(filter: unknown): FilterCondition | undefined {\n if (filter == null) return undefined;\n if (!Array.isArray(filter)) return filter as FilterCondition;\n if (filter.length === 0) return undefined;\n\n const first = filter[0];\n\n // Logical node: [\"and\", cond1, cond2, ...] or [\"or\", cond1, cond2, ...]\n if (typeof first === 'string' && (first.toLowerCase() === 'and' || first.toLowerCase() === 'or')) {\n const logicOp = `$${first.toLowerCase()}` as '$and' | '$or';\n const children = filter.slice(1).map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { [logicOp]: children } as FilterCondition;\n }\n\n // Comparison node: [field, operator, value]\n if (filter.length >= 2 && typeof first === 'string') {\n return convertComparison(filter as [string, string, unknown]);\n }\n\n // Legacy flat array: [[field, op, val], [field, op, val], ...]\n // All elements are sub-arrays → treat as implicit AND\n if (filter.every((item: unknown) => Array.isArray(item))) {\n const children = filter.map((child: unknown) => parseFilterAST(child)).filter(Boolean) as FilterCondition[];\n if (children.length === 0) return undefined;\n if (children.length === 1) return children[0];\n return { $and: children } as FilterCondition;\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Constants & Metadata\n// ============================================================================\n\n/**\n * All supported operator keys.\n * Useful for validation and parsing.\n */\nexport const FILTER_OPERATORS = [\n // Equality\n '$eq', '$ne',\n // Comparison\n '$gt', '$gte', '$lt', '$lte',\n // Set & Range\n '$in', '$nin', '$between',\n // String\n '$contains', '$notContains', '$startsWith', '$endsWith',\n // Special\n '$null', '$exists',\n] as const;\n\n/**\n * Logical operator keys.\n */\nexport const LOGICAL_OPERATORS = ['$and', '$or', '$not'] as const;\n\n/**\n * All operator keys (field + logical).\n */\nexport const ALL_OPERATORS = [...FILTER_OPERATORS, ...LOGICAL_OPERATORS] as const;\n\nexport type FilterOperatorKey = typeof FILTER_OPERATORS[number];\nexport type LogicalOperatorKey = typeof LOGICAL_OPERATORS[number];\nexport type OperatorKey = typeof ALL_OPERATORS[number];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\n\n/**\n * Sort Node\n * Represents \"Order By\".\n */\nexport const SortNodeSchema = z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc']).default('asc')\n});\n\n/**\n * Aggregation Function Enum\n * Standard aggregation functions for data analysis.\n * \n * Supported Functions:\n * - **count**: Count rows (SQL: COUNT(*) or COUNT(field))\n * - **sum**: Sum numeric values (SQL: SUM(field))\n * - **avg**: Average numeric values (SQL: AVG(field))\n * - **min**: Minimum value (SQL: MIN(field))\n * - **max**: Maximum value (SQL: MAX(field))\n * - **count_distinct**: Count unique values (SQL: COUNT(DISTINCT field))\n * - **array_agg**: Aggregate values into array (SQL: ARRAY_AGG(field))\n * - **string_agg**: Concatenate values (SQL: STRING_AGG(field, delimiter))\n * \n * Performance Considerations:\n * - COUNT(*) is typically faster than COUNT(field) as it doesn't check for nulls\n * - COUNT DISTINCT may require additional memory for tracking unique values\n * - Window aggregates (with OVER clause) can be more efficient than subqueries\n * - Large GROUP BY operations benefit from proper indexing on grouped fields\n * \n * @example\n * // SQL: SELECT region, SUM(amount) FROM sales GROUP BY region\n * {\n * object: 'sales',\n * fields: ['region'],\n * aggregations: [\n * { function: 'sum', field: 'amount', alias: 'total_sales' }\n * ],\n * groupBy: ['region']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT COUNT(Id) FROM Account\n * {\n * object: 'account',\n * aggregations: [\n * { function: 'count', alias: 'total_accounts' }\n * ]\n * }\n */\nexport const AggregationFunction = z.enum([\n 'count', 'sum', 'avg', 'min', 'max',\n 'count_distinct', 'array_agg', 'string_agg'\n]);\n\n/**\n * Aggregation Node\n * Represents an aggregated field with function.\n * \n * Aggregations summarize data across groups of rows (GROUP BY).\n * Used with `groupBy` to create analytical queries.\n * \n * @example\n * // SQL: SELECT customer_id, COUNT(*), SUM(amount) FROM orders GROUP BY customer_id\n * {\n * object: 'order',\n * fields: ['customer_id'],\n * aggregations: [\n * { function: 'count', alias: 'order_count' },\n * { function: 'sum', field: 'amount', alias: 'total_amount' }\n * ],\n * groupBy: ['customer_id']\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT LeadSource, COUNT(Id) FROM Lead GROUP BY LeadSource\n * {\n * object: 'lead',\n * fields: ['lead_source'],\n * aggregations: [\n * { function: 'count', alias: 'lead_count' }\n * ],\n * groupBy: ['lead_source']\n * }\n */\nexport const AggregationNodeSchema = z.object({\n function: AggregationFunction.describe('Aggregation function'),\n field: z.string().optional().describe('Field to aggregate (optional for COUNT(*))'),\n alias: z.string().describe('Result column alias'),\n distinct: z.boolean().optional().describe('Apply DISTINCT before aggregation'),\n filter: FilterConditionSchema.optional().describe('Filter/Condition to apply to the aggregation (FILTER WHERE clause)'),\n});\n\n/**\n * Join Type Enum\n * Standard SQL join types for combining tables.\n * \n * Join Types:\n * - **inner**: Returns only matching rows from both tables (SQL: INNER JOIN)\n * - **left**: Returns all rows from left table, matching rows from right (SQL: LEFT JOIN)\n * - **right**: Returns all rows from right table, matching rows from left (SQL: RIGHT JOIN)\n * - **full**: Returns all rows from both tables (SQL: FULL OUTER JOIN)\n * \n * @example\n * // SQL: SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * on: ['order.customer_id', '=', 'customer.id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL-style: Find all customers and their orders (if any)\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * on: ['customer.id', '=', 'order.customer_id']\n * }\n * ]\n * }\n */\nexport const JoinType = z.enum(['inner', 'left', 'right', 'full']);\n\n/**\n * Join Execution Strategy\n * Hints to the query engine on how to execute the join.\n * \n * Strategies:\n * - **auto**: Engine decides best strategy (Default).\n * - **database**: Push down join to the database (Requires same datasource).\n * - **hash**: Load both sets into memory and hash join (Cross-datasource, memory intensive).\n * - **loop**: Nested loop lookup (N+1 safe version). (Good for small right-side lookups).\n */\nexport const JoinStrategy = z.enum(['auto', 'database', 'hash', 'loop']);\n\n/**\n * Join Node\n * Represents table joins for combining data from multiple objects.\n * \n * Joins connect related data across multiple tables using ON conditions.\n * Supports both direct object joins and subquery joins.\n * \n * @example\n * // SQL: SELECT o.*, c.name FROM orders o INNER JOIN customers c ON o.customer_id = c.id\n * {\n * object: 'order',\n * fields: ['id', 'amount'],\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Multi-table join\n * // SELECT * FROM orders o\n * // INNER JOIN customers c ON o.customer_id = c.id\n * // LEFT JOIN shipments s ON o.id = s.order_id\n * {\n * object: 'order',\n * joins: [\n * {\n * type: 'inner',\n * object: 'customer',\n * alias: 'c',\n * on: ['order.customer_id', '=', 'c.id']\n * },\n * {\n * type: 'left',\n * object: 'shipment',\n * alias: 's',\n * on: ['order.id', '=', 's.order_id']\n * }\n * ]\n * }\n * \n * @example\n * // Salesforce SOQL: SELECT Name, (SELECT LastName FROM Contacts) FROM Account\n * {\n * object: 'account',\n * fields: ['name'],\n * joins: [\n * {\n * type: 'left',\n * object: 'contact',\n * on: ['account.id', '=', 'contact.account_id']\n * }\n * ]\n * }\n * \n * @example\n * // Subquery Join: Join with a filtered/aggregated dataset\n * {\n * object: 'customer',\n * joins: [\n * {\n * type: 'left',\n * object: 'order',\n * alias: 'high_value_orders',\n * on: ['customer.id', '=', 'high_value_orders.customer_id'],\n * subquery: {\n * object: 'order',\n * fields: ['customer_id', 'total'],\n * filters: ['total', '>', 1000]\n * }\n * }\n * ]\n * }\n */\nexport const JoinNodeSchema: z.ZodType = z.lazy(() => \n z.object({\n type: JoinType.describe('Join type'),\n strategy: JoinStrategy.optional().describe('Execution strategy hint'),\n object: z.string().describe('Object/table to join'),\n alias: z.string().optional().describe('Table alias'),\n on: FilterConditionSchema.describe('Join condition'),\n subquery: z.lazy(() => QuerySchema).optional().describe('Subquery instead of object'),\n })\n);\n\n/**\n * Window Function Enum\n * Advanced analytical functions for row-based calculations.\n * \n * Window Functions:\n * - **row_number**: Sequential number within partition (SQL: ROW_NUMBER() OVER (...))\n * - **rank**: Rank with gaps for ties (SQL: RANK() OVER (...))\n * - **dense_rank**: Rank without gaps (SQL: DENSE_RANK() OVER (...))\n * - **percent_rank**: Relative rank as percentage (SQL: PERCENT_RANK() OVER (...))\n * - **lag**: Access previous row value (SQL: LAG(field) OVER (...))\n * - **lead**: Access next row value (SQL: LEAD(field) OVER (...))\n * - **first_value**: First value in window (SQL: FIRST_VALUE(field) OVER (...))\n * - **last_value**: Last value in window (SQL: LAST_VALUE(field) OVER (...))\n * - **sum/avg/count/min/max**: Aggregates over window (SQL: SUM(field) OVER (...))\n * \n * @example\n * // SQL: SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) as rank\n * // FROM orders\n * {\n * object: 'order',\n * fields: ['id', 'customer_id', 'amount'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'rank',\n * over: {\n * partitionBy: ['customer_id'],\n * orderBy: [{ field: 'amount', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Running total with SUM() OVER (...)\n * {\n * object: 'transaction',\n * fields: ['date', 'amount'],\n * windowFunctions: [\n * {\n * function: 'sum',\n * field: 'amount',\n * alias: 'running_total',\n * over: {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: 'UNBOUNDED PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunction = z.enum([\n 'row_number', 'rank', 'dense_rank', 'percent_rank',\n 'lag', 'lead', 'first_value', 'last_value',\n 'sum', 'avg', 'count', 'min', 'max'\n]);\n\n/**\n * Window Specification\n * Defines PARTITION BY and ORDER BY for window functions.\n * \n * Window specifications control how window functions compute values:\n * - **partitionBy**: Divide rows into groups (like GROUP BY but without collapsing rows)\n * - **orderBy**: Define order for ranking and offset functions\n * - **frame**: Specify which rows to include in aggregate calculations\n * \n * @example\n * // Partition by department, order by salary\n * {\n * partitionBy: ['department'],\n * orderBy: [{ field: 'salary', order: 'desc' }]\n * }\n * \n * @example\n * // Moving average with frame specification\n * {\n * orderBy: [{ field: 'date', order: 'asc' }],\n * frame: {\n * type: 'rows',\n * start: '6 PRECEDING',\n * end: 'CURRENT ROW'\n * }\n * }\n */\nexport const WindowSpecSchema = z.object({\n partitionBy: z.array(z.string()).optional().describe('PARTITION BY fields'),\n orderBy: z.array(SortNodeSchema).optional().describe('ORDER BY specification'),\n frame: z.object({\n type: z.enum(['rows', 'range']).optional(),\n start: z.string().optional().describe('Frame start (e.g., \"UNBOUNDED PRECEDING\", \"1 PRECEDING\")'),\n end: z.string().optional().describe('Frame end (e.g., \"CURRENT ROW\", \"1 FOLLOWING\")'),\n }).optional().describe('Window frame specification'),\n});\n\n/**\n * Window Function Node\n * Represents window function with OVER clause.\n * \n * Window functions perform calculations across a set of rows related to the current row,\n * without collapsing the result set (unlike GROUP BY aggregations).\n * \n * @example\n * // SQL: Top 3 products per category\n * // SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as rank\n * // FROM products\n * {\n * object: 'product',\n * fields: ['name', 'category', 'sales'],\n * windowFunctions: [\n * {\n * function: 'row_number',\n * alias: 'category_rank',\n * over: {\n * partitionBy: ['category'],\n * orderBy: [{ field: 'sales', order: 'desc' }]\n * }\n * }\n * ]\n * }\n * \n * @example\n * // SQL: Year-over-year comparison with LAG\n * {\n * object: 'monthly_sales',\n * fields: ['month', 'revenue'],\n * windowFunctions: [\n * {\n * function: 'lag',\n * field: 'revenue',\n * alias: 'prev_year_revenue',\n * over: {\n * orderBy: [{ field: 'month', order: 'asc' }]\n * }\n * }\n * ]\n * }\n */\nexport const WindowFunctionNodeSchema = z.object({\n function: WindowFunction.describe('Window function name'),\n field: z.string().optional().describe('Field to operate on (for aggregate window functions)'),\n alias: z.string().describe('Result column alias'),\n over: WindowSpecSchema.describe('Window specification (OVER clause)'),\n});\n\n/**\n * Field Selection Node\n * Represents \"Select\" attributes, including joins.\n */\nexport const FieldNodeSchema: z.ZodType = z.lazy(() => \n z.union([\n z.string(), // Primitive field: \"name\"\n z.object({\n field: z.string(), // Relationship field: \"owner\"\n fields: z.array(FieldNodeSchema).optional(), // Nested select: [\"name\", \"email\"]\n alias: z.string().optional()\n })\n ])\n);\n\n/**\n * Full-Text Search Configuration\n * Defines full-text search parameters for text queries.\n * \n * Supports:\n * - Multi-field search\n * - Relevance scoring\n * - Fuzzy matching\n * - Language-specific analyzers\n * \n * @example\n * {\n * query: \"John Smith\",\n * fields: [\"name\", \"email\", \"description\"],\n * fuzzy: true,\n * boost: { \"name\": 2.0, \"email\": 1.5 }\n * }\n */\nexport const FullTextSearchSchema = z.object({\n query: z.string().describe('Search query text'),\n fields: z.array(z.string()).optional().describe('Fields to search in (if not specified, searches all text fields)'),\n fuzzy: z.boolean().optional().default(false).describe('Enable fuzzy matching (tolerates typos)'),\n operator: z.enum(['and', 'or']).optional().default('or').describe('Logical operator between terms'),\n boost: z.record(z.string(), z.number()).optional().describe('Field-specific relevance boosting (field name -> boost factor)'),\n minScore: z.number().optional().describe('Minimum relevance score threshold'),\n language: z.string().optional().describe('Language for text analysis (e.g., \"en\", \"zh\", \"es\")'),\n highlight: z.boolean().optional().default(false).describe('Enable search result highlighting'),\n});\n\nexport type FullTextSearch = z.infer;\n\n/**\n * Query AST Schema\n * The universal data retrieval contract defined in `ast-structure.mdx`.\n * \n * This schema represents ObjectQL - a universal query language that abstracts\n * SQL, NoSQL, and SaaS APIs into a single unified interface.\n * \n * Updates (v2):\n * - Aligned with modern ORM standards (Prisma/TypeORM)\n * - Added `cursor` based pagination support\n * - Renamed `top`/`skip` to `limit`/`offset`\n * - Unified filtering syntax with `FilterConditionSchema`\n * \n * Updates (v3):\n * - Added `search` parameter for full-text search (P2 requirement)\n * \n * @example\n * // Simple query: SELECT name, email FROM account WHERE status = 'active'\n * {\n * object: 'account',\n * fields: ['name', 'email'],\n * where: { status: 'active' }\n * }\n * \n * @example\n * // Pagination with Limit/Offset\n * {\n * object: 'post',\n * where: { published: true },\n * orderBy: [{ field: 'created_at', order: 'desc' }],\n * limit: 20,\n * offset: 40\n * }\n * \n * @example\n * // Full-text search\n * {\n * object: 'article',\n * search: {\n * query: \"machine learning\",\n * fields: [\"title\", \"content\"],\n * fuzzy: true,\n * boost: { \"title\": 2.0 }\n * },\n * limit: 10\n * }\n */\nconst BaseQuerySchema = z.object({\n /** Target Entity */\n object: z.string().describe('Object name (e.g. account)'),\n \n /** Select Clause */\n fields: z.array(FieldNodeSchema).optional().describe('Fields to retrieve'),\n \n /** Where Clause (Filtering) */\n where: FilterConditionSchema.optional().describe('Filtering criteria (WHERE)'),\n \n /** Full-Text Search */\n search: FullTextSearchSchema.optional().describe('Full-text search configuration ($search parameter)'),\n \n /** Order By Clause (Sorting) */\n orderBy: z.array(SortNodeSchema).optional().describe('Sorting instructions (ORDER BY)'),\n \n /** Pagination */\n limit: z.number().optional().describe('Max records to return (LIMIT)'),\n offset: z.number().optional().describe('Records to skip (OFFSET)'),\n top: z.number().optional().describe('Alias for limit (OData compatibility)'),\n cursor: z.record(z.string(), z.unknown()).optional().describe('Cursor for keyset pagination'),\n \n /** Joins */\n joins: z.array(JoinNodeSchema).optional().describe('Explicit Table Joins'),\n \n /** Aggregations */\n aggregations: z.array(AggregationNodeSchema).optional().describe('Aggregation functions'),\n \n /** Group By Clause */\n groupBy: z.array(z.string()).optional().describe('GROUP BY fields'),\n \n /** Having Clause */\n having: FilterConditionSchema.optional().describe('HAVING clause for aggregation filtering'),\n \n /** Window Functions */\n windowFunctions: z.array(WindowFunctionNodeSchema).optional().describe('Window functions with OVER clause'),\n \n /** Subquery flag */\n distinct: z.boolean().optional().describe('SELECT DISTINCT flag'),\n});\n\n/**\n * QueryAST — Abstract Syntax Tree for data queries.\n *\n * The `expand` property enables recursive loading of related records through\n * lookup and master_detail fields. Each key is a relationship field name; the\n * value is a nested QueryAST that can further filter, select, sort, and expand\n * the related records (up to a default max depth of 3).\n *\n * @example\n * ```ts\n * const ast: QueryAST = {\n * object: 'task',\n * fields: ['title', 'assignee'],\n * expand: {\n * assignee: { object: 'user', fields: ['name', 'email'] },\n * project: {\n * object: 'project',\n * expand: { org: { object: 'org' } } // nested expand\n * }\n * }\n * };\n * ```\n */\nexport type QueryAST = z.infer & {\n expand?: Record;\n};\n\nexport type QueryInput = z.input & {\n expand?: Record;\n};\n\nexport const QuerySchema: z.ZodType = BaseQuerySchema.extend({\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional().describe(\n 'Recursive relation loading map. Keys are lookup/master_detail field names; '\n + 'values are nested QueryAST objects that control select, filter, sort, and '\n + 'further expansion on the related object. The engine resolves expand via '\n + 'batch $in queries (driver-agnostic) with a default max depth of 3.'\n ),\n});\n\nexport type SortNode = z.infer;\nexport type AggregationNode = z.infer;\nexport type JoinNode = z.infer;\nexport type WindowFunctionNode = z.infer;\nexport type WindowSpec = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # ObjectStack Validation Protocol\n * \n * This module defines the validation schema protocol for ObjectStack, providing a comprehensive\n * type-safe validation system similar to Salesforce's validation rules but with enhanced capabilities.\n * \n * ## Overview\n * \n * Validation rules are applied at the data layer to ensure data integrity and enforce business logic.\n * The system supports multiple validation types:\n * \n * 1. **Script Validation**: Formula-based validation using expressions\n * 2. **Uniqueness Validation**: Enforce unique constraints across fields\n * 3. **State Machine Validation**: Control allowed state transitions\n * 4. **Format Validation**: Validate field formats (email, URL, regex, etc.)\n * 5. **Cross-Field Validation**: Validate relationships between multiple fields\n * 6. **Async Validation**: Remote validation via API calls\n * 7. **Custom Validation**: User-defined validation functions\n * 8. **Conditional Validation**: Apply validations based on conditions\n * \n * ## Salesforce Comparison\n * \n * ObjectStack validation rules are inspired by Salesforce validation rules but enhanced:\n * - Salesforce: Formula-based validation with `Error Condition Formula`\n * - ObjectStack: Multiple validation types with composable rules\n * \n * Example Salesforce validation rule:\n * ```\n * Rule Name: Discount_Cannot_Exceed_40_Percent\n * Error Condition Formula: Discount_Percent__c > 0.40\n * Error Message: Discount cannot exceed 40%.\n * ```\n * \n * Equivalent ObjectStack rule:\n * ```typescript\n * {\n * type: 'script',\n * name: 'discount_cannot_exceed_40_percent',\n * condition: 'discount_percent > 0.40',\n * message: 'Discount cannot exceed 40%',\n * severity: 'error'\n * }\n * ```\n */\n\n/**\n * Base Validation Rule\n * \n * All validation rules extend from this base schema with common properties.\n * \n * ## Industry Standard Enhancements\n * - **Label/Description**: Essential for governance in large systems with thousands of rules.\n * - **Events**: granular control over validation timing (Context-aware validation).\n * - **Tags**: categorization for reporting and management.\n */\nconst BaseValidationSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label for the rule listing'),\n description: z.string().optional().describe('Administrative notes explaining the business reason'),\n \n // Execution Control\n active: z.boolean().default(true),\n events: z.array(z.enum(['insert', 'update', 'delete'])).default(['insert', 'update']).describe('Validation contexts'),\n priority: z.number().int().min(0).max(9999).default(100).describe('Execution priority (lower runs first, default: 100)'),\n \n // Classification\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g., \"compliance\", \"billing\")'),\n \n // Feedback\n severity: z.enum(['error', 'warning', 'info']).default('error'),\n message: z.string().describe('Error message to display to the user'),\n});\n\n/**\n * 1. Script/Expression Validation\n * Generic formula-based validation.\n */\nexport const ScriptValidationSchema = BaseValidationSchema.extend({\n type: z.literal('script'),\n condition: z.string().describe('Formula expression. If TRUE, validation fails. (e.g. amount < 0)'),\n});\n\n/**\n * 2. Uniqueness Validation\n * specialized optimized check for unique constraints.\n */\nexport const UniquenessValidationSchema = BaseValidationSchema.extend({\n type: z.literal('unique'),\n fields: z.array(z.string()).describe('Fields that must be combined unique'),\n scope: z.string().optional().describe('Formula condition for scope (e.g. active = true)'),\n caseSensitive: z.boolean().default(true),\n});\n\n/**\n * 3. State Machine Validation\n * State transition logic.\n */\nexport const StateMachineValidationSchema = BaseValidationSchema.extend({\n type: z.literal('state_machine'),\n field: z.string().describe('State field (e.g. status)'),\n transitions: z.record(z.string(), z.array(z.string())).describe('Map of { OldState: [AllowedNewStates] }'),\n});\n\n/**\n * 4. Value Format Validation\n * Regex or specialized formats.\n */\nexport const FormatValidationSchema = BaseValidationSchema.extend({\n type: z.literal('format'),\n field: z.string(),\n regex: z.string().optional(),\n format: z.enum(['email', 'url', 'phone', 'json']).optional(),\n});\n\n/**\n * 5. Cross-Field Validation\n * Validates relationships between multiple fields.\n * \n * ## Use Cases\n * - Date range validations (end_date > start_date)\n * - Amount comparisons (discount < total)\n * - Complex business rules involving multiple fields\n * \n * ## Salesforce Examples\n * \n * ### Example 1: Close Date Must Be In Current or Future Month\n * **Salesforce Formula:**\n * ```\n * MONTH(CloseDate) < MONTH(TODAY()) ||\n * YEAR(CloseDate) < YEAR(TODAY())\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'close_date_future',\n * condition: 'MONTH(close_date) >= MONTH(TODAY()) AND YEAR(close_date) >= YEAR(TODAY())',\n * fields: ['close_date'],\n * message: 'Close Date must be in the current or a future month'\n * }\n * ```\n * \n * ### Example 2: Discount Validation\n * **Salesforce Formula:**\n * ```\n * Discount__c > (Amount__c * 0.40)\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'discount_limit',\n * condition: 'discount > (amount * 0.40)',\n * fields: ['discount', 'amount'],\n * message: 'Discount cannot exceed 40% of the amount'\n * }\n * ```\n * \n * ### Example 3: Opportunity Must Have Products\n * **Salesforce Formula:**\n * ```\n * ISBLANK(Products__c) && ISPICKVAL(StageName, \"Closed Won\")\n * ```\n * \n * **ObjectStack Equivalent:**\n * ```typescript\n * {\n * type: 'cross_field',\n * name: 'products_required_for_won',\n * condition: 'products = null AND stage = \"closed_won\"',\n * fields: ['products', 'stage'],\n * message: 'Opportunity must have products to be marked as Closed Won'\n * }\n * ```\n */\nexport const CrossFieldValidationSchema = BaseValidationSchema.extend({\n type: z.literal('cross_field'),\n condition: z.string().describe('Formula expression comparing fields (e.g. \"end_date > start_date\")'),\n fields: z.array(z.string()).describe('Fields involved in the validation'),\n});\n\n/**\n * 6. JSON Structure Validation\n * Validates JSON fields against a JSON Schema.\n * \n * ## Use Cases\n * - Validating configuration objects stored in JSON fields\n * - Enforcing API payload structures\n * - Complex nested data validation\n */\nexport const JSONValidationSchema = BaseValidationSchema.extend({\n type: z.literal('json_schema'),\n field: z.string().describe('JSON field to validate'),\n schema: z.record(z.string(), z.unknown()).describe('JSON Schema object definition'),\n});\n\n/**\n * 7. Async Validation\n * Remote validation via API call or database query.\n * \n * ## Use Cases\n * \n * ### 1. Email Uniqueness Check\n * Check if an email address is already registered in the system.\n * ```typescript\n * {\n * type: 'async',\n * name: 'unique_email',\n * field: 'email',\n * validatorUrl: '/api/users/check-email',\n * message: 'This email address is already registered',\n * debounce: 500, // Wait 500ms after user stops typing\n * timeout: 3000\n * }\n * ```\n * \n * ### 2. Username Availability\n * Verify username is available before form submission.\n * ```typescript\n * {\n * type: 'async',\n * name: 'username_available',\n * field: 'username',\n * validatorUrl: '/api/users/check-username',\n * message: 'This username is already taken',\n * debounce: 300,\n * timeout: 2000\n * }\n * ```\n * \n * ### 3. Tax ID Validation\n * Validate tax ID with government API (e.g., IRS, HMRC).\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_tax_id',\n * field: 'tax_id',\n * validatorFunction: 'validateTaxIdWithIRS',\n * message: 'Invalid Tax ID number',\n * timeout: 10000, // Government APIs may be slow\n * params: { country: 'US', format: 'EIN' }\n * }\n * ```\n * \n * ### 4. Credit Card Validation\n * Verify credit card with payment gateway without charging.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_card',\n * field: 'card_number',\n * validatorUrl: 'https://api.stripe.com/v1/tokens/validate',\n * message: 'Invalid credit card number',\n * timeout: 5000,\n * params: { \n * mode: 'validate_only',\n * checkFunds: false \n * }\n * }\n * ```\n * \n * ### 5. Address Validation\n * Validate and standardize addresses using geocoding services.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_address',\n * field: 'street_address',\n * validatorFunction: 'validateAddressWithGoogleMaps',\n * message: 'Unable to verify address',\n * timeout: 4000,\n * params: {\n * includeFields: ['city', 'state', 'zip'],\n * strictMode: true,\n * country: 'US'\n * }\n * }\n * ```\n * \n * ### 6. Domain Name Availability\n * Check if domain name is available for registration.\n * ```typescript\n * {\n * type: 'async',\n * name: 'domain_available',\n * field: 'domain_name',\n * validatorUrl: '/api/domains/check-availability',\n * message: 'This domain is already taken or reserved',\n * debounce: 500,\n * timeout: 2000\n * }\n * ```\n * \n * ### 7. Coupon Code Validation\n * Verify coupon code is valid and not expired.\n * ```typescript\n * {\n * type: 'async',\n * name: 'validate_coupon',\n * field: 'coupon_code',\n * validatorUrl: '/api/coupons/validate',\n * message: 'Invalid or expired coupon code',\n * timeout: 2000,\n * params: {\n * checkExpiration: true,\n * checkUsageLimit: true,\n * userId: '{{current_user_id}}'\n * }\n * }\n * ```\n */\nexport const AsyncValidationSchema = BaseValidationSchema.extend({\n type: z.literal('async'),\n field: z.string().describe('Field to validate'),\n validatorUrl: z.string().optional().describe('External API endpoint for validation'),\n method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method for external call'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for the request'),\n validatorFunction: z.string().optional().describe('Reference to custom validator function'),\n timeout: z.number().optional().default(5000).describe('Timeout in milliseconds'),\n debounce: z.number().optional().describe('Debounce delay in milliseconds'),\n params: z.record(z.string(), z.unknown()).optional().describe('Additional parameters to pass to validator'),\n});\n\n/**\n * 8. Custom Validator Function\n * User-defined validation logic with code reference.\n */\nexport const CustomValidatorSchema = BaseValidationSchema.extend({\n type: z.literal('custom'),\n handler: z.string().describe('Name of the custom validation function registered in the system'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the custom handler'),\n});\n\n/**\n * 9. Master Validation Rule Schema\n */\n/** Base type for validation rules - used for z.lazy() recursive type annotation */\nexport interface BaseValidationRuleShape {\n type: string;\n name: string;\n message: string;\n label?: string;\n description?: string;\n active?: boolean;\n events?: ('insert' | 'update' | 'delete')[];\n priority?: number;\n tags?: string[];\n severity?: 'error' | 'warning' | 'info';\n [key: string]: unknown;\n}\n\nexport const ValidationRuleSchema: z.ZodType = z.lazy(() =>\n z.discriminatedUnion('type', [\n ScriptValidationSchema,\n UniquenessValidationSchema,\n StateMachineValidationSchema,\n FormatValidationSchema,\n CrossFieldValidationSchema,\n JSONValidationSchema,\n AsyncValidationSchema,\n CustomValidatorSchema,\n ConditionalValidationSchema,\n ])\n);\n\n/**\n * 8. Conditional Validation\n * Validation that only applies when a condition is met.\n * \n * ## Overview\n * Conditional validations follow the pattern: \"Validate X only if Y is true\"\n * This allows for context-aware validation rules that adapt to different scenarios.\n * \n * ## Use Cases\n * \n * ### 1. Validate Based on Record Type\n * Apply different validation rules based on the type of record.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_approval_required',\n * when: 'account_type = \"enterprise\"',\n * message: 'Enterprise validation',\n * then: {\n * type: 'script',\n * name: 'require_approval',\n * message: 'Enterprise accounts require manager approval',\n * condition: 'approval_status = null'\n * }\n * }\n * ```\n * \n * ### 2. Conditional Field Requirements\n * Require certain fields only when specific conditions are met.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'shipping_address_when_required',\n * when: 'requires_shipping = true',\n * message: 'Shipping validation',\n * then: {\n * type: 'script',\n * name: 'shipping_address_required',\n * message: 'Shipping address is required for physical products',\n * condition: 'shipping_address = null OR shipping_address = \"\"'\n * }\n * }\n * ```\n * \n * ### 3. Amount-Based Validation\n * Apply different rules based on transaction amount.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'high_value_approval',\n * when: 'order_total > 10000',\n * message: 'High value order validation',\n * then: {\n * type: 'script',\n * name: 'manager_approval_required',\n * message: 'Orders over $10,000 require manager approval',\n * condition: 'manager_approval_id = null'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'standard_validation',\n * message: 'Payment method is required',\n * condition: 'payment_method = null'\n * }\n * }\n * ```\n * \n * ### 4. Regional Compliance\n * Apply region-specific validation rules.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'regional_compliance',\n * when: 'region = \"EU\"',\n * message: 'EU compliance validation',\n * then: {\n * type: 'script',\n * name: 'gdpr_consent',\n * message: 'GDPR consent is required for EU customers',\n * condition: 'gdpr_consent_given = false'\n * },\n * otherwise: {\n * type: 'script',\n * name: 'tos_acceptance',\n * message: 'Terms of Service acceptance required',\n * condition: 'tos_accepted = false'\n * }\n * }\n * ```\n * \n * ### 5. Nested Conditional Validation\n * Create complex validation logic with nested conditions.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'country_state_validation',\n * when: 'country = \"US\"',\n * message: 'US-specific validation',\n * then: {\n * type: 'conditional',\n * name: 'california_validation',\n * when: 'state = \"CA\"',\n * message: 'California-specific validation',\n * then: {\n * type: 'script',\n * name: 'ca_tax_id_required',\n * message: 'California requires a valid tax ID',\n * condition: 'tax_id = null OR NOT(REGEX(tax_id, \"^\\\\d{2}-\\\\d{7}$\"))'\n * }\n * }\n * }\n * ```\n * \n * ### 6. Tax Validation for Taxable Items\n * Only validate tax fields when the item is taxable.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'tax_field_validation',\n * when: 'is_taxable = true',\n * message: 'Tax validation',\n * then: {\n * type: 'script',\n * name: 'tax_code_required',\n * message: 'Tax code is required for taxable items',\n * condition: 'tax_code = null OR tax_code = \"\"'\n * }\n * }\n * ```\n * \n * ### 7. Role-Based Validation\n * Apply validation based on user role.\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'role_based_approval_limit',\n * when: 'user_role = \"manager\"',\n * message: 'Manager approval limits',\n * then: {\n * type: 'script',\n * name: 'manager_limit',\n * message: 'Managers can approve up to $50,000',\n * condition: 'approval_amount > 50000'\n * }\n * }\n * ```\n * \n * ## Salesforce Pattern Comparison\n * \n * Salesforce doesn't have explicit \"conditional validation\" rules but achieves similar\n * behavior using formula logic. ObjectStack makes this pattern explicit and composable.\n * \n * **Salesforce Approach:**\n * ```\n * IF(\n * ISPICKVAL(Type, \"Enterprise\"),\n * AND(Amount > 100000, ISBLANK(Approval__c)),\n * FALSE\n * )\n * ```\n * \n * **ObjectStack Approach:**\n * ```typescript\n * {\n * type: 'conditional',\n * name: 'enterprise_high_value',\n * when: 'type = \"enterprise\"',\n * then: {\n * type: 'cross_field',\n * name: 'amount_approval',\n * condition: 'amount > 100000 AND approval = null',\n * fields: ['amount', 'approval']\n * }\n * }\n * ```\n */\nexport const ConditionalValidationSchema = BaseValidationSchema.extend({\n type: z.literal('conditional'),\n when: z.string().describe('Condition formula (e.g. \"type = \\'enterprise\\'\")'),\n then: ValidationRuleSchema.describe('Validation rule to apply when condition is true'),\n otherwise: ValidationRuleSchema.optional().describe('Validation rule to apply when condition is false'),\n});\n\nexport type ValidationRule = z.infer;\nexport type ScriptValidation = z.infer;\nexport type UniquenessValidation = z.infer;\nexport type StateMachineValidation = z.infer;\nexport type FormatValidation = z.infer;\nexport type CrossFieldValidation = z.infer;\nexport type JSONValidation = z.infer;\nexport type AsyncValidation = z.infer;\nexport type CustomValidation = z.infer;\nexport type ConditionalValidation = z.infer;", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * XState-inspired State Machine Protocol\n * Used to define strict business logic constraints and lifecycle management.\n * Prevent AI \"hallucinations\" by enforcing valid valid transitions.\n */\n\n// --- Primitives ---\n\n/**\n * References a named action (side effect)\n * Can be a script, a webhook, or a field update.\n */\nexport const ActionRefSchema = z.union([\n z.string().describe('Action Name'),\n z.object({\n type: z.string(), // e.g., 'xstate.assign', 'log', 'email'\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n/**\n * References a named condition (guard)\n * Must evaluate to true for the transition to occur.\n */\nexport const GuardRefSchema = z.union([\n z.string().describe('Guard Name (e.g., \"isManager\", \"amountGT1000\")'),\n z.object({\n type: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n })\n]);\n\n// --- Core Structure ---\n\n/**\n * State Transition Definition\n * \"When EVENT happens, if GUARD is true, go to TARGET and run ACTIONS\"\n */\nexport const TransitionSchema = z.object({\n target: z.string().optional().describe('Target State ID'),\n cond: GuardRefSchema.optional().describe('Condition (Guard) required to take this path'),\n actions: z.array(ActionRefSchema).optional().describe('Actions to execute during transition'),\n description: z.string().optional().describe('Human readable description of this rule'),\n});\n\n/**\n * Event Definition (Signals)\n */\nexport const EventSchema = z.object({\n type: z.string().describe('Event Type (e.g. \"APPROVE\", \"REJECT\", \"Submit\")'),\n // Payload validation schema could go here if we want deep validation\n schema: z.record(z.string(), z.unknown()).optional().describe('Expected event payload structure'),\n});\n\nexport type ActionRef = z.infer;\nexport type Transition = z.infer;\n\nexport type StateNodeConfig = {\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n entry?: ActionRef[];\n exit?: ActionRef[];\n on?: Record;\n always?: Transition[];\n initial?: string;\n states?: Record;\n meta?: {\n label?: string;\n description?: string;\n color?: string;\n aiInstructions?: string;\n };\n};\n\n/**\n * State Node Definition\n */\nexport const StateNodeSchema: z.ZodType = z.lazy(() => z.object({\n /** Type of state */\n type: z.enum(['atomic', 'compound', 'parallel', 'final', 'history']).default('atomic'),\n \n /** Entry/Exit Actions */\n entry: z.array(ActionRefSchema).optional().describe('Actions to run when entering this state'),\n exit: z.array(ActionRefSchema).optional().describe('Actions to run when leaving this state'),\n \n /** Transitions (Events) */\n on: z.record(z.string(), z.union([\n z.string(), // Shorthand target\n TransitionSchema, \n z.array(TransitionSchema)\n ])).optional().describe('Map of Event Type -> Transition Definition'),\n \n /** Always Transitions (Eventless) */\n always: z.array(TransitionSchema).optional(),\n\n /** Nesting (Hierarchical States) */\n initial: z.string().optional().describe('Initial child state (if compound)'),\n states: z.record(z.string(), StateNodeSchema).optional(),\n \n /** Metadata for UI/AI */\n meta: z.object({\n label: z.string().optional(),\n description: z.string().optional(),\n color: z.string().optional(), // For UI diagrams\n // Instructions for AI Agent when in this state\n aiInstructions: z.string().optional().describe('Specific instructions for AI when in this state'),\n }).optional(),\n}));\n\n/**\n * Top-Level State Machine Definition\n */\nexport const StateMachineSchema = z.object({\n id: SnakeCaseIdentifierSchema.describe('Unique Machine ID'),\n description: z.string().optional(),\n \n /** Context (Memory) Schema */\n contextSchema: z.record(z.string(), z.unknown()).optional().describe('Zod Schema for the machine context/memory'),\n \n /** Initial State */\n initial: z.string().describe('Initial State ID'),\n \n /** State Definitions */\n states: z.record(z.string(), StateNodeSchema).describe('State Nodes'),\n \n /** Global Listeners */\n on: z.record(z.string(), z.union([z.string(), TransitionSchema, z.array(TransitionSchema)])).optional(),\n});\n\nexport type StateMachineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * I18n Object Schema\n * Structured internationalization label with translation key and parameters.\n * \n * @example\n * ```typescript\n * const label: I18nObject = {\n * key: 'views.task_list.label',\n * defaultValue: 'Task List',\n * params: { count: 5 },\n * };\n * ```\n */\nexport const I18nObjectSchema = z.object({\n /** Translation key (e.g., \"views.task_list.label\", \"apps.crm.description\") */\n key: z.string().describe('Translation key (e.g., \"views.task_list.label\")'),\n\n /** Default value when translation is not available */\n defaultValue: z.string().optional().describe('Fallback value when translation key is not found'),\n\n /** Interpolation parameters for dynamic translations */\n params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional().describe('Interpolation parameters (e.g., { count: 5 })'),\n});\n\nexport type I18nObject = z.infer;\n\n/**\n * I18n Label Schema\n * \n * A plain string label for display purposes.\n * i18n translation keys are auto-generated by the framework at registration time\n * based on a standardized naming convention (e.g., `apps...label`).\n * Developers only need to provide the default-language string; translations are\n * managed through translation files, not inline i18n objects.\n * \n * @example\n * ```typescript\n * const label: I18nLabel = \"All Active\";\n * ```\n */\nexport const I18nLabelSchema = z.string().describe('Display label (plain string; i18n keys are auto-generated by the framework)');\n\nexport type I18nLabel = z.infer;\n\n/**\n * ARIA Accessibility Properties Schema\n * \n * Common ARIA attributes for UI components to support screen readers\n * and assistive technologies.\n * \n * Aligned with WAI-ARIA 1.2 specification.\n * \n * @see https://www.w3.org/TR/wai-aria-1.2/\n * \n * @example\n * ```typescript\n * const aria: AriaProps = {\n * ariaLabel: 'Close dialog',\n * ariaDescribedBy: 'dialog-description',\n * role: 'dialog',\n * };\n * ```\n */\nexport const AriaPropsSchema = z.object({\n /** Accessible label for screen readers */\n ariaLabel: I18nLabelSchema.optional().describe('Accessible label for screen readers (WAI-ARIA aria-label)'),\n\n /** ID of element that describes this component */\n ariaDescribedBy: z.string().optional().describe('ID of element providing additional description (WAI-ARIA aria-describedby)'),\n\n /** WAI-ARIA role override */\n role: z.string().optional().describe('WAI-ARIA role attribute (e.g., \"dialog\", \"navigation\", \"alert\")'),\n}).describe('ARIA accessibility attributes');\n\nexport type AriaProps = z.infer;\n\n/**\n * Plural Rule Schema\n *\n * Defines plural forms for a translation key, following ICU MessageFormat / i18next conventions.\n * Supports zero, one, two, few, many, other forms per CLDR plural rules.\n *\n * @see https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules\n *\n * @example\n * ```typescript\n * const plural: PluralRule = {\n * key: 'items.count',\n * zero: 'No items',\n * one: '{count} item',\n * other: '{count} items',\n * };\n * ```\n */\nexport const PluralRuleSchema = z.object({\n /** Translation key for the plural form */\n key: z.string().describe('Translation key'),\n /** Form for zero quantity */\n zero: z.string().optional().describe('Zero form (e.g., \"No items\")'),\n /** Form for singular (1) */\n one: z.string().optional().describe('Singular form (e.g., \"{count} item\")'),\n /** Form for dual (2) — used in Arabic, Welsh, etc. */\n two: z.string().optional().describe('Dual form (e.g., \"{count} items\" for exactly 2)'),\n /** Form for few (2-4 in Slavic languages) */\n few: z.string().optional().describe('Few form (e.g., for 2-4 in some languages)'),\n /** Form for many (5+ in Slavic languages) */\n many: z.string().optional().describe('Many form (e.g., for 5+ in some languages)'),\n /** Default/fallback form */\n other: z.string().describe('Default plural form (e.g., \"{count} items\")'),\n}).describe('ICU plural rules for a translation key');\n\nexport type PluralRule = z.infer;\n\n/**\n * Number Format Schema\n *\n * Defines number formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: NumberFormat = {\n * style: 'currency',\n * currency: 'USD',\n * minimumFractionDigits: 2,\n * };\n * ```\n */\nexport const NumberFormatSchema = z.object({\n style: z.enum(['decimal', 'currency', 'percent', 'unit']).default('decimal')\n .describe('Number formatting style'),\n currency: z.string().optional().describe('ISO 4217 currency code (e.g., \"USD\", \"EUR\")'),\n unit: z.string().optional().describe('Unit for unit formatting (e.g., \"kilometer\", \"liter\")'),\n minimumFractionDigits: z.number().optional().describe('Minimum number of fraction digits'),\n maximumFractionDigits: z.number().optional().describe('Maximum number of fraction digits'),\n useGrouping: z.boolean().optional().describe('Whether to use grouping separators (e.g., 1,000)'),\n}).describe('Number formatting rules');\n\nexport type NumberFormat = z.infer;\n\n/**\n * Date Format Schema\n *\n * Defines date/time formatting rules for localization.\n *\n * @example\n * ```typescript\n * const format: DateFormat = {\n * dateStyle: 'medium',\n * timeStyle: 'short',\n * timeZone: 'America/New_York',\n * };\n * ```\n */\nexport const DateFormatSchema = z.object({\n dateStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Date display style'),\n timeStyle: z.enum(['full', 'long', 'medium', 'short']).optional()\n .describe('Time display style'),\n timeZone: z.string().optional().describe('IANA time zone (e.g., \"America/New_York\")'),\n hour12: z.boolean().optional().describe('Use 12-hour format'),\n}).describe('Date/time formatting rules');\n\nexport type DateFormat = z.infer;\n\n/**\n * Locale Configuration Schema\n *\n * Defines a complete locale configuration including language code,\n * fallback chain, and formatting preferences.\n *\n * @example\n * ```typescript\n * const locale: LocaleConfig = {\n * code: 'zh-CN',\n * fallbackChain: ['zh-TW', 'en'],\n * direction: 'ltr',\n * numberFormat: { style: 'decimal', useGrouping: true },\n * dateFormat: { dateStyle: 'medium', timeStyle: 'short' },\n * };\n * ```\n */\nexport const LocaleConfigSchema = z.object({\n /** BCP 47 language code (e.g., \"en-US\", \"zh-CN\", \"ar-SA\") */\n code: z.string().describe('BCP 47 language code (e.g., \"en-US\", \"zh-CN\")'),\n\n /** Ordered fallback chain for missing translations */\n fallbackChain: z.array(z.string()).optional()\n .describe('Fallback language codes in priority order (e.g., [\"zh-TW\", \"en\"])'),\n\n /** Text direction */\n direction: z.enum(['ltr', 'rtl']).default('ltr')\n .describe('Text direction: left-to-right or right-to-left'),\n\n /** Default number formatting */\n numberFormat: NumberFormatSchema.optional().describe('Default number formatting rules'),\n\n /** Default date formatting */\n dateFormat: DateFormatSchema.optional().describe('Default date/time formatting rules'),\n}).describe('Locale configuration');\n\nexport type LocaleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Action Parameter Schema\n * Defines inputs required before executing an action.\n */\nexport const ActionParamSchema = z.object({\n name: z.string(),\n label: I18nLabelSchema,\n type: FieldType,\n required: z.boolean().default(false),\n options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),\n});\n\n/**\n * Action type enum values.\n */\nexport const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api']);\n\n/**\n * Action types that require a `target` field.\n * Derived from ActionType, excluding 'script' which allows inline handlers.\n * These types reference an external resource (URL, flow, modal, or API endpoint)\n * and cannot function without a target binding.\n */\nconst TARGET_REQUIRED_TYPES: ReadonlySet = new Set(\n ActionType.options.filter((t) => t !== 'script'),\n);\n\n/**\n * Action Schema\n * \n * **NAMING CONVENTION:**\n * Action names are machine identifiers used in code and must be lowercase snake_case.\n * \n * **TARGET BINDING:**\n * The `target` field is the canonical way to bind an action to its handler.\n * - `type: 'script'` — `target` is recommended (references a script/function name).\n * - `type: 'url'` — `target` is **required** (the URL to navigate to).\n * - `type: 'flow'` — `target` is **required** (the flow name to invoke).\n * - `type: 'modal'` — `target` is **required** (the modal/page name to open).\n * - `type: 'api'` — `target` is **required** (the API endpoint to call).\n * \n * The `execute` field is **deprecated** and will be removed in a future version.\n * If `execute` is provided without `target`, it is automatically migrated to `target`.\n * \n * @example Good action names\n * - 'on_close_deal'\n * - 'send_welcome_email'\n * - 'approve_contract'\n * - 'export_report'\n * \n * @example Bad action names (will be rejected)\n * - 'OnCloseDeal' (PascalCase)\n * - 'sendEmail' (camelCase)\n * - 'Send Email' (spaces)\n * \n * Note: The action name is the configuration ID. JavaScript function names can use camelCase,\n * but the metadata ID must be lowercase snake_case.\n */\nexport const ActionSchema = z.object({\n /** Machine name of the action */\n name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display label'),\n\n /** Target object this action belongs to (optional, snake_case) */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\\'s actions array by defineStack().'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Where does this action appear? */\n locations: z.array(z.enum([\n 'list_toolbar', 'list_item', \n 'record_header', 'record_more', 'record_related',\n 'global_nav'\n ])).optional().describe('Locations where this action is visible'),\n\n /** \n * Visual Component Type\n * Defaults to 'button' or 'menu_item' based on location,\n * but can be overridden.\n */\n component: z.enum([\n 'action:button', // Standard Button\n 'action:icon', // Icon only\n 'action:menu', // Dropdown menu\n 'action:group' // Button Group\n ]).optional().describe('Visual component override'),\n \n /** What type of interaction? */\n type: ActionType.default('script').describe('Action functionality type'),\n \n /** \n * Payload / Target — the canonical binding for the action handler.\n * Required for url, flow, modal, and api types.\n * Recommended for script type.\n */\n target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint'),\n\n /** \n * @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.\n */\n execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),\n \n /** User Input Requirements */\n params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),\n \n /** Visual Style */\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),\n\n /** UX Behavior */\n confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),\n successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),\n refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),\n \n /** Access */\n visible: z.string().optional().describe('Formula returning boolean'),\n disabled: z.union([z.boolean(), z.string()]).optional().describe('Whether the action is disabled, or a condition expression string'),\n\n /** Keyboard Shortcut */\n shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., \"Ctrl+S\")'),\n\n /** Bulk Operations */\n bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),\n\n /** Execution */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds for the action'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).transform((data) => {\n // Auto-migrate deprecated `execute` → `target` for backward compatibility\n if (data.execute && !data.target) {\n return { ...data, target: data.execute };\n }\n return data;\n}).refine((data) => {\n // Require `target` for types that reference an external resource\n if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {\n return false;\n }\n return true;\n}, {\n message: \"Action 'target' is required when type is 'url', 'flow', 'modal', or 'api'.\",\n path: ['target'],\n});\n\nexport type Action = z.infer;\nexport type ActionParam = z.infer;\nexport type ActionInput = z.input;\n\n/**\n * Action Factory Helper\n */\nexport const Action = {\n create: (config: z.input): Action => ActionSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from './field.zod';\nimport { ValidationRuleSchema } from './validation.zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\nimport { ActionSchema } from '../ui/action.zod';\n\n/**\n * API Operations Enum\n */\nexport const ApiMethod = z.enum([\n 'get', 'list', // Read\n 'create', 'update', 'delete', // Write\n 'upsert', // Idempotent Write\n 'bulk', // Batch operations\n 'aggregate', // Analytics (count, sum)\n 'history', // Audit access\n 'search', // Search access\n 'restore', 'purge', // Trash management\n 'import', 'export', // Data portability\n]);\nexport type ApiMethod = z.infer;\n\n/**\n * Capability Flags\n * Defines what system features are enabled for this object.\n * \n * Optimized based on industry standards (Salesforce, ServiceNow):\n * - Added `activities` (Tasks/Events)\n * - Added `mru` (Recent Items)\n * - Added `feeds` (Social/Chatter)\n * - Grouped API permissions\n * \n * @example\n * {\n * trackHistory: true,\n * searchable: true,\n * apiEnabled: true,\n * files: true\n * }\n */\nexport const ObjectCapabilities = z.object({\n /** Enable history tracking (Audit Trail) */\n trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),\n \n /** Enable global search indexing */\n searchable: z.boolean().default(true).describe('Index records for global search'),\n \n /** Enable REST/GraphQL API access */\n apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),\n\n /** \n * API Supported Operations\n * Granular control over API exposure.\n */\n apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),\n \n /** Enable standard attachments/files engine */\n files: z.boolean().default(false).describe('Enable file attachments and document management'),\n \n /** Enable social collaboration (Comments, Mentions, Feeds) */\n feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),\n \n /** Enable standard Activity suite (Tasks, Calendars, Events) */\n activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),\n \n /** Enable Recycle Bin / Soft Delete */\n trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),\n\n /** Enable \"Recently Viewed\" tracking */\n mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),\n \n /** Allow cloning records */\n clone: z.boolean().default(true).describe('Allow record deep cloning'),\n});\n\n/**\n * Schema for database indexes.\n * Enhanced with additional index types and configuration options\n * \n * @example\n * {\n * name: \"idx_account_name\",\n * fields: [\"name\"],\n * type: \"btree\",\n * unique: true\n * }\n */\nexport const IndexSchema = z.object({\n name: z.string().optional().describe('Index name (auto-generated if not provided)'),\n fields: z.array(z.string()).describe('Fields included in the index'),\n type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),\n unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),\n partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),\n});\n\n/**\n * Search Configuration\n * Defines how this object behaves in search results.\n * \n * @example\n * {\n * fields: [\"name\", \"email\", \"phone\"],\n * displayFields: [\"name\", \"title\"],\n * filters: [\"status = 'active'\"]\n * }\n */\nexport const SearchConfigSchema = z.object({\n fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),\n displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),\n filters: z.array(z.string()).optional().describe('Default filters for search results'),\n});\n\n/**\n * Multi-Tenancy Configuration Schema\n * Configures tenant isolation strategy for SaaS applications\n * \n * @example Shared database with tenant_id isolation\n * {\n * enabled: true,\n * strategy: 'shared',\n * tenantField: 'tenant_id',\n * crossTenantAccess: false\n * }\n */\nexport const TenancyConfigSchema = z.object({\n enabled: z.boolean().describe('Enable multi-tenancy for this object'),\n strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),\n tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),\n crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),\n});\n\n/**\n * Soft Delete Configuration Schema\n * Implements recycle bin / trash functionality\n * \n * @example Standard soft delete with cascade\n * {\n * enabled: true,\n * field: 'deleted_at',\n * cascadeDelete: true\n * }\n */\nexport const SoftDeleteConfigSchema = z.object({\n enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),\n field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),\n cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),\n});\n\n/**\n * Versioning Configuration Schema\n * Implements record versioning and history tracking\n * \n * @example Snapshot versioning with 90-day retention\n * {\n * enabled: true,\n * strategy: 'snapshot',\n * retentionDays: 90,\n * versionField: 'version'\n * }\n */\nexport const VersioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable record versioning'),\n strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),\n retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),\n versionField: z.string().default('version').describe('Field name for version number/timestamp'),\n});\n\n/**\n * Partitioning Strategy Schema\n * Configures table partitioning for performance at scale\n * \n * @example Range partitioning by date (monthly)\n * {\n * enabled: true,\n * strategy: 'range',\n * key: 'created_at',\n * interval: '1 month'\n * }\n */\nexport const PartitioningConfigSchema = z.object({\n enabled: z.boolean().describe('Enable table partitioning'),\n strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),\n key: z.string().describe('Field name to partition by'),\n interval: z.string().optional().describe('Partition interval for range strategy (e.g., \"1 month\", \"1 year\")'),\n}).refine((data) => {\n // If strategy is 'range', interval must be provided\n if (data.strategy === 'range' && !data.interval) {\n return false;\n }\n return true;\n}, {\n message: 'interval is required when strategy is \"range\"',\n});\n\n/**\n * Change Data Capture (CDC) Configuration Schema\n * Enables real-time data streaming to external systems\n * \n * @example Stream all changes to Kafka\n * {\n * enabled: true,\n * events: ['insert', 'update', 'delete'],\n * destination: 'kafka://events.objectstack'\n * }\n */\nexport const CDCConfigSchema = z.object({\n enabled: z.boolean().describe('Enable Change Data Capture'),\n events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),\n destination: z.string().describe('Destination endpoint (e.g., \"kafka://topic\", \"webhook://url\")'),\n});\n\n/**\n * Base Object Schema Definition\n * \n * The Blueprint of a Business Object.\n * Represents a table, a collection, or a virtual entity.\n * \n * @example\n * ```yaml\n * name: project_task\n * label: Project Task\n * icon: task\n * fields:\n * project:\n * type: lookup\n * reference: project\n * status:\n * type: select\n * options: [todo, in_progress, done]\n * enable:\n * trackHistory: true\n * files: true\n * ```\n */\nconst ObjectSchemaBase = z.object({\n /** \n * Identity & Metadata \n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),\n label: z.string().optional().describe('Human readable singular label (e.g. \"Account\")'),\n pluralLabel: z.string().optional().describe('Human readable plural label (e.g. \"Accounts\")'),\n description: z.string().optional().describe('Developer documentation / description'),\n icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),\n \n /**\n * Namespace & Domain Classification\n * \n * Groups objects into logical domains for routing, permissions, and discovery.\n * System objects use `'sys'`; business packages use their own namespace.\n * \n * When set, `tableName` is auto-derived as `{namespace}_{name}` by\n * `ObjectSchema.create()` unless an explicit `tableName` is provided.\n * \n * Namespace must be a single lowercase word (no underscores or hyphens)\n * to ensure clean auto-derivation of `{namespace}_{name}` table names.\n * \n * @example namespace: 'sys' → tableName defaults to 'sys_user'\n * @example namespace: 'crm' → tableName defaults to 'crm_account'\n */\n namespace: z.string().regex(/^[a-z][a-z0-9]*$/).optional().describe('Logical domain namespace — single lowercase word (e.g. \"sys\", \"crm\"). Used for routing, permissions, and auto-deriving tableName as {namespace}_{name}.'),\n\n /**\n * Taxonomy & Organization\n */\n tags: z.array(z.string()).optional().describe('Categorization tags (e.g. \"sales\", \"system\", \"reference\")'),\n active: z.boolean().optional().default(true).describe('Is the object active and usable'),\n isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),\n abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),\n\n /** \n * Storage & Virtualization \n */\n datasource: z.string().optional().default('default').describe('Target Datasource ID. \"default\" is the primary DB.'),\n tableName: z.string().optional().describe('Physical table/collection name in the target datasource. Auto-derived as {namespace}_{name} when namespace is set.'),\n \n /** \n * Data Model \n */\n fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {\n message: 'Field names must be lowercase snake_case (e.g., \"first_name\", \"company\", \"annual_revenue\")',\n }), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),\n indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),\n \n /**\n * Advanced Data Management\n */\n \n // Multi-tenancy configuration\n tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),\n \n // Soft delete configuration\n softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),\n \n // Versioning configuration\n versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),\n \n // Partitioning strategy\n partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),\n \n // Change Data Capture\n cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),\n \n /**\n * Logic & Validation (Co-located)\n * Best Practice: Define rules close to data.\n */\n validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),\n \n /**\n * State Machine(s)\n * Named record of state machines, where each key is a unique machine identifier.\n * Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).\n * \n * @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }\n */\n stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),\n\n /** \n * Display & UI Hints (Data-Layer)\n */\n displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., \"name\", \"title\"). Defaults to \"name\" if present.'),\n recordName: z.object({\n type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),\n displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., \"CASE-{0000}\", \"INV-{YYYY}-{0000}\")'),\n startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),\n }).optional().describe('Record name generation configuration (Salesforce pattern)'),\n titleFormat: z.string().optional().describe('Title expression (e.g. \"{name} - {code}\"). Overrides displayNameField.'),\n compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),\n \n /** \n * Search Engine Config \n */\n search: SearchConfigSchema.optional().describe('Search engine configuration'),\n \n /** \n * System Capabilities \n */\n enable: ObjectCapabilities.optional().describe('Enabled system features modules'),\n\n /** Record Types */\n recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),\n\n /** Sharing Model */\n sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),\n\n /** Key Prefix */\n keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., \"001\" for Account)'),\n\n /**\n * Object Actions\n * \n * Actions associated with this object. Populated automatically by `defineStack()`\n * when top-level actions specify `objectName` matching this object.\n * Can also be defined directly on the object.\n * \n * Aligns with Salesforce/ServiceNow patterns where actions are part of the\n * object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)\n * include the action list without requiring downstream merge.\n */\n actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),\n});\n\n/**\n * Converts a snake_case name to a human-readable Title Case label.\n * @example snakeCaseToLabel('project_task') → 'Project Task'\n */\nfunction snakeCaseToLabel(name: string): string {\n return name\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n}\n\n/**\n * Enhanced ObjectSchema with Factory\n */\nexport const ObjectSchema = Object.assign(ObjectSchemaBase, {\n /**\n * Type-safe factory for creating business object definitions.\n * \n * Enhancements over raw schema:\n * - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).\n * - **Validation**: Runs Zod `.parse()` to validate the config at creation time.\n * \n * @example\n * ```ts\n * const Task = ObjectSchema.create({\n * name: 'project_task',\n * // label auto-generated as 'Project Task'\n * fields: {\n * subject: { type: 'text', label: 'Subject', required: true },\n * },\n * });\n * ```\n */\n create: >(config: T): Omit & Pick => {\n const withDefaults = {\n ...config,\n label: config.label ?? snakeCaseToLabel(config.name),\n // Auto-derive tableName as {namespace}_{name} when namespace is set\n tableName: config.tableName ?? (config.namespace ? `${config.namespace}_${config.name}` : undefined),\n };\n return ObjectSchemaBase.parse(withDefaults) as Omit & Pick;\n },\n});\n\nexport type ServiceObject = z.infer;\nexport type ServiceObjectInput = z.input;\nexport type ObjectCapabilities = z.infer;\nexport type ObjectIndex = z.infer;\nexport type TenancyConfig = z.infer;\nexport type SoftDeleteConfig = z.infer;\nexport type VersioningConfig = z.infer;\nexport type PartitioningConfig = z.infer;\nexport type CDCConfig = z.infer;\n\n// =================================================================\n// Object Ownership Model\n// =================================================================\n\n/**\n * How a package relates to an object it references.\n * \n * - `own`: This package is the original author/owner of the object.\n * Only one package may own a given object name. The owner defines\n * the base schema (table name, primary key, core fields).\n * \n * - `extend`: This package adds fields, views, or actions to an\n * existing object owned by another package. Multiple packages\n * may extend the same object. Extensions are merged at boot time.\n * \n * Follows Salesforce/ServiceNow patterns:\n * object name = database table name, globally unique, no namespace prefix.\n */\nexport const ObjectOwnershipEnum = z.enum(['own', 'extend']);\nexport type ObjectOwnership = z.infer;\n\n/**\n * Object Extension Entry — used in `objectExtensions` array.\n * Declares fields/config to merge into an existing object owned by another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact', // target object FQN\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\nexport const ObjectExtensionSchema = z.object({\n /** The target object name (FQN) to extend */\n extend: z.string().describe('Target object name (FQN) to extend'),\n \n /** Fields to merge into the target object (additive) */\n fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),\n \n /** Override label */\n label: z.string().optional().describe('Override label for the extended object'),\n \n /** Override plural label */\n pluralLabel: z.string().optional().describe('Override plural label for the extended object'),\n \n /** Override description */\n description: z.string().optional().describe('Override description for the extended object'),\n \n /** Additional validation rules to add */\n validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),\n \n /** Additional indexes to add */\n indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),\n \n /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */\n priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),\n});\n\nexport type ObjectExtension = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Hook Lifecycle Events\n * Defines the interception points in the ObjectQL execution pipeline.\n */\nexport const HookEvent = z.enum([\n // Read Operations\n 'beforeFind', 'afterFind',\n 'beforeFindOne', 'afterFindOne',\n 'beforeCount', 'afterCount',\n 'beforeAggregate', 'afterAggregate',\n\n // Write Operations\n 'beforeInsert', 'afterInsert',\n 'beforeUpdate', 'afterUpdate',\n 'beforeDelete', 'afterDelete',\n \n // Bulk Operations (Query-based)\n 'beforeUpdateMany', 'afterUpdateMany',\n 'beforeDeleteMany', 'afterDeleteMany',\n]);\n\n/**\n * Hook Definition Schema\n * \n * Hooks serve as the \"Logic Layer\" in ObjectStack, allowing developers to \n * inject custom code during the data access lifecycle.\n * \n * Use cases:\n * - Data Enrichment (Default values, Calculated fields)\n * - Validation (Complex business rules)\n * - Side Effects (Sending emails, Syncing to external systems)\n * - Security (Filtering data based on context)\n */\nexport const HookSchema = z.object({\n /**\n * Unique identifier for the hook\n * Required for debugging and overriding.\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Hook unique name (snake_case)'),\n\n /**\n * Human readable label\n */\n label: z.string().optional().describe('Description of what this hook does'),\n\n /**\n * Target Object(s)\n * can be:\n * - Single object: \"account\"\n * - List of objects: [\"account\", \"contact\"]\n * - Wildcard: \"*\" (All objects)\n */\n object: z.union([z.string(), z.array(z.string())]).describe('Target object(s)'),\n\n /**\n * Events to subscribe to\n * Combinations of timing (before/after) and action (find/insert/update/delete/etc)\n */\n events: z.array(HookEvent).describe('Lifecycle events'),\n\n /**\n * Handler Logic\n * Reference to a registered function in the plugin system OR a direct function (runtime only).\n */\n handler: z.union([z.string(), z.function()]).optional().describe('Handler function name (string) or inline function reference'),\n\n /**\n * Execution Order\n * Lower numbers run first.\n * - System Hooks: 0-99\n * - App Hooks: 100-999\n * - User Hooks: 1000+\n */\n priority: z.number().default(100).describe('Execution priority'),\n\n /**\n * Async / Background Execution\n * If true, the hook runs in the background and does not block the transaction.\n * Only applicable for 'after*' events.\n * Default: false (Blocking)\n */\n async: z.boolean().default(false).describe('Run specifically as fire-and-forget'),\n\n /**\n * Declarative Condition\n * Formula expression evaluated before the handler runs.\n * If provided and evaluates to FALSE, the hook is skipped entirely.\n * Useful for filtering by record data without writing handler code.\n * \n * @example \"status = 'active' AND amount > 1000\"\n */\n condition: z.string().optional().describe('Formula expression; hook runs only when TRUE (e.g., \"status = \\'closed\\' AND amount > 1000\")'),\n\n /**\n * Human-readable description\n */\n description: z.string().optional().describe('Human-readable description of what this hook does'),\n\n /**\n * Retry Policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().default(3).describe('Maximum retry attempts on failure'),\n backoffMs: z.number().default(1000).describe('Backoff delay between retries in milliseconds'),\n }).optional().describe('Retry policy for failed hook executions'),\n\n /**\n * Execution Timeout\n */\n timeout: z.number().optional().describe('Maximum execution time in milliseconds before the hook is aborted'),\n\n /**\n * Error Policy\n * What to do if the hook throws an exception?\n * - abort: Rollback transaction (if blocking)\n * - log: Log error and continue\n */\n onError: z.enum(['abort', 'log']).default('abort').describe('Error handling strategy'),\n});\n\n/**\n * Hook Runtime Context\n * Defines what is available to the hook handler during execution.\n * \n * Best Practices:\n * - **Immutability**: `object`, `event`, `id` are immutable.\n * - **Mutability**: `input` and `result` are mutable to allow transformation.\n * - **Encapsulation**: `session` isolates auth info; `transaction` ensures atomicity.\n */\nexport const HookContextSchema = z.object({\n /** Tracing ID */\n id: z.string().optional().describe('Unique execution ID for tracing'),\n\n /** Target Object Name */\n object: z.string(),\n \n /** Current Lifecycle Event */\n event: HookEvent,\n\n /** \n * Input Parameters (Mutable)\n * Modify this to change the behavior of the operation.\n * \n * - find: { query: QueryAST, options: DriverOptions }\n * - insert: { doc: Record, options: DriverOptions }\n * - update: { id: ID, doc: Record, options: DriverOptions }\n * - delete: { id: ID, options: DriverOptions }\n * - updateMany: { query: QueryAST, doc: Record, options: DriverOptions }\n * - deleteMany: { query: QueryAST, options: DriverOptions }\n */\n input: z.record(z.string(), z.unknown()).describe('Mutable input parameters'),\n\n /** \n * Operation Result (Mutable)\n * Available in 'after*' events. Modify this to transform the output.\n */\n result: z.unknown().optional().describe('Operation result (After hooks only)'),\n\n /**\n * Data Snapshot\n * The state of the record BEFORE the operation (for update/delete).\n */\n previous: z.record(z.string(), z.unknown()).optional().describe('Record state before operation'),\n\n /**\n * Execution Session\n * Contains authentication and tenancy information.\n */\n session: z.object({\n userId: z.string().optional(),\n tenantId: z.string().optional(),\n roles: z.array(z.string()).optional(),\n accessToken: z.string().optional(),\n }).optional().describe('Current session context'),\n \n /**\n * Transaction Handle\n * If the operation is part of a transaction, use this handle for side-effects.\n */\n transaction: z.unknown().optional().describe('Database transaction handle'),\n\n /**\n * Engine Access\n * Reference to the ObjectQL engine for performing side effects.\n */\n ql: z.unknown().describe('ObjectQL Engine Reference'),\n\n /**\n * Cross-Object API\n * Provides a scoped data access interface for performing CRUD operations\n * on other objects within hooks. Bound to the current execution context\n * (userId, tenantId, transaction).\n *\n * Usage in hooks:\n * const users = ctx.api.object('user');\n * const admin = await users.findOne({ filter: { role: 'admin' } });\n */\n api: z.unknown().optional().describe('Cross-object data access (ScopedContext)'),\n\n /**\n * Current User Info\n * Convenience shortcut for session.userId + additional user metadata.\n * Populated by the engine when available.\n */\n user: z.object({\n id: z.string().optional(),\n name: z.string().optional(),\n email: z.string().optional(),\n }).optional().describe('Current user info shortcut'),\n});\n\nexport type Hook = z.input;\nexport type ResolvedHook = z.output;\nexport type HookEventType = z.infer;\nexport type HookContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { QuerySchema } from './query.zod';\n\n/**\n * Transformation Logic\n * Built-in helpers for converting data during import.\n */\nexport const TransformType = z.enum([\n 'none', // Direct copy\n 'constant', // Use a hardcoded value\n 'lookup', // Resolve FK (Name -> ID)\n 'split', // \"John Doe\" -> [\"John\", \"Doe\"]\n 'join', // [\"John\", \"Doe\"] -> \"John Doe\"\n 'javascript', // Custom script (Review security!)\n 'map' // Value mapping (e.g. \"Active\" -> \"active\")\n]);\n\n/**\n * Field Mapping Item\n */\nexport const FieldMappingSchema = z.object({\n /** Source Column */\n source: z.union([z.string(), z.array(z.string())]).describe('Source column header(s)'),\n \n /** Target Field */\n target: z.union([z.string(), z.array(z.string())]).describe('Target object field(s)'),\n \n /** Transformation */\n transform: TransformType.default('none'),\n \n /** Configuration for transform */\n params: z.object({\n // Constant\n value: z.unknown().optional(),\n \n // Lookup\n object: z.string().optional(), // Lookup Object\n fromField: z.string().optional(), // Match on (e.g. \"name\")\n toField: z.string().optional(), // Value to take (e.g. \"id\")\n autoCreate: z.boolean().optional(), // Create if missing\n \n // Map\n valueMap: z.record(z.string(), z.unknown()).optional(), // { \"Open\": \"draft\" }\n \n // Split/Join\n separator: z.string().optional()\n }).optional()\n});\n\n/**\n * Data Mapping Schema\n * Defines a reusable data mapping configuration for ETL operations.\n * \n * **NAMING CONVENTION:**\n * Mapping names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good mapping names\n * - 'salesforce_to_crm'\n * - 'csv_import_contacts'\n * - 'api_sync_orders'\n * \n * @example Bad mapping names (will be rejected)\n * - 'SalesforceToCRM' (PascalCase)\n * - 'CSV Import' (spaces)\n */\nexport const MappingSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Mapping unique name (lowercase snake_case)'),\n label: z.string().optional(),\n \n /** Scope */\n sourceFormat: z.enum(['csv', 'json', 'xml', 'sql']).default('csv'),\n targetObject: z.string().describe('Target Object Name'),\n \n /** Column Mappings */\n fieldMapping: z.array(FieldMappingSchema),\n \n /** Upsert Logic */\n mode: z.enum(['insert', 'update', 'upsert']).default('insert'),\n upsertKey: z.array(z.string()).optional().describe('Fields to match for upsert (e.g. email)'),\n \n /** Extract Logic (For Export) */\n extractQuery: QuerySchema.optional().describe('Query to run for export only'),\n \n /** Error Handling */\n errorPolicy: z.enum(['skip', 'abort', 'retry']).default('skip'),\n batchSize: z.number().default(1000)\n});\n\nexport type Mapping = z.infer;\nexport type FieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Execution Context Schema\n * \n * Defines the runtime context that flows from HTTP request → data operations.\n * This is the \"identity + environment\" envelope that every data operation can carry.\n * \n * Design:\n * - All fields are optional for backward compatibility\n * - `isSystem` bypasses permission checks (for internal/migration operations)\n * - `transaction` carries the database transaction handle for atomicity\n * - `traceId` enables distributed tracing across microservices\n * \n * Usage:\n * engine.find('account', { context: { userId: '...', tenantId: '...' } })\n */\nexport const ExecutionContextSchema = z.object({\n /** Current user ID (resolved from session) */\n userId: z.string().optional(),\n \n /** Current organization/tenant ID (resolved from session.activeOrganizationId) */\n tenantId: z.string().optional(),\n \n /** User role names (resolved from Member + Role) */\n roles: z.array(z.string()).default([]),\n \n /** Aggregated permission names (resolved from PermissionSet) */\n permissions: z.array(z.string()).default([]),\n \n /** Whether this is a system-level operation (bypasses permission checks) */\n isSystem: z.boolean().default(false),\n \n /** Raw access token (for external API call pass-through) */\n accessToken: z.string().optional(),\n \n /** Database transaction handle */\n transaction: z.unknown().optional(),\n \n /** Request trace ID (for distributed tracing) */\n traceId: z.string().optional(),\n});\n\nexport type ExecutionContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from './filter.zod';\nimport { SortNodeSchema, QuerySchema, FullTextSearchSchema, FieldNodeSchema, AggregationNodeSchema } from './query.zod';\nimport { ExecutionContextSchema } from '../kernel/execution-context.zod';\n\n/**\n * Data Engine Protocol\n * \n * Defines the standard interface for data persistence engines in ObjectStack.\n * This protocol abstracts the underlying storage mechanism (SQL, NoSQL, API, Memory),\n * allowing the ObjectQL engine to execute standardized CRUD and Aggregation operations\n * regardless of where the data resides.\n * \n * The Data Engine acts as the \"Driver\" layer in the Hexagonal Architecture.\n */\n\n// ==========================================================================\n// 1. Shared Definitions\n// ==========================================================================\n\n/**\n * Data Engine Query filter conditions\n * Supports simple key-value map or complex Logic/Field expressions (DSL)\n */\nexport const DataEngineFilterSchema = z.union([\n z.record(z.string(), z.unknown()),\n FilterConditionSchema\n]).describe('Data Engine query filter conditions');\n\n/**\n * Sort order definition\n * Supports:\n * - { name: 'asc' }\n * - { name: 1 }\n * - [{ field: 'name', order: 'asc' }]\n */\nexport const DataEngineSortSchema = z.union([\n z.record(z.string(), z.enum(['asc', 'desc'])), \n z.record(z.string(), z.union([z.literal(1), z.literal(-1)])),\n z.array(SortNodeSchema)\n]).describe('Sort order definition');\n\n// ==========================================================================\n// 1b. Base Engine Options (shared context)\n// ==========================================================================\n\n/**\n * Base Engine Options\n * \n * All Data Engine operation options extend this schema to carry\n * an optional ExecutionContext for identity, tenant, and transaction propagation.\n */\nexport const BaseEngineOptionsSchema = z.object({\n /** Execution context (identity, tenant, transaction) */\n context: ExecutionContextSchema.optional(),\n});\n\n// ==========================================================================\n// 2. method: FIND (QueryAST-aligned)\n// ==========================================================================\n\n/**\n * Engine Query Options — QueryAST-aligned parameters for IDataEngine.find/findOne.\n * \n * Uses standard QueryAST field names (where/fields/orderBy/limit/offset/expand)\n * so that no mechanical translation is needed between the Engine and Driver layers.\n * \n * @example\n * ```ts\n * engine.find('account', {\n * where: { status: 'active' },\n * fields: ['id', 'name', 'email'],\n * orderBy: [{ field: 'name', order: 'asc' }],\n * limit: 10,\n * offset: 20,\n * expand: { owner: { object: 'user', fields: ['name'] } },\n * });\n * ```\n */\nexport const EngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions (WHERE) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n\n /** Fields to retrieve (SELECT) — standard QueryAST `fields` */\n fields: z.array(FieldNodeSchema).optional(),\n\n /** Sorting instructions (ORDER BY) — standard QueryAST `orderBy` */\n orderBy: z.array(SortNodeSchema).optional(),\n\n /** Max records to return (LIMIT) */\n limit: z.number().optional(),\n\n /** Records to skip (OFFSET) — standard QueryAST `offset` */\n offset: z.number().optional(),\n\n /** Alias for limit (OData compatibility) */\n top: z.number().optional(),\n\n /** Cursor for keyset pagination */\n cursor: z.record(z.string(), z.unknown()).optional(),\n\n /** Full-text search configuration */\n search: FullTextSearchSchema.optional(),\n\n /**\n * Recursive relation loading map (expand).\n * \n * Keys are lookup/master_detail field names; values are nested QueryAST\n * objects that control select, filter, sort, and further expansion on\n * the related object. The engine resolves expand via batch $in queries\n * (driver-agnostic) with a default max depth of 3.\n */\n expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional(),\n\n /** SELECT DISTINCT flag */\n distinct: z.boolean().optional(),\n}).describe('QueryAST-aligned query options for IDataEngine.find() operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineQueryOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineQueryOptionsSchema` instead.\n * This schema uses legacy parameter names (filter/select/sort/skip/populate)\n * that require mechanical translation to QueryAST. Migrate to the\n * QueryAST-aligned `EngineQueryOptionsSchema` (where/fields/orderBy/offset/expand).\n */\nexport const DataEngineQueryOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineQueryOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n /** @deprecated Use `fields` (EngineQueryOptionsSchema) */\n select: z.array(z.string()).optional(),\n /** @deprecated Use `orderBy` (EngineQueryOptionsSchema) */\n sort: DataEngineSortSchema.optional(),\n limit: z.number().int().min(1).optional(),\n /** @deprecated Use `offset` (EngineQueryOptionsSchema) */\n skip: z.number().int().min(0).optional(),\n top: z.number().int().min(1).optional(),\n /** @deprecated Use `expand` (EngineQueryOptionsSchema) */\n populate: z.array(z.string()).optional(),\n}).describe('Query options for IDataEngine.find() operations');\n\n// ==========================================================================\n// 3. method: INSERT\n// ==========================================================================\n\nexport const DataEngineInsertOptionsSchema = BaseEngineOptionsSchema.extend({\n /** \n * Return the inserted record(s)? \n * Some drivers support RETURNING clause for efficiency.\n * Default: true\n */\n returning: z.boolean().default(true).optional(),\n}).describe('Options for DataEngine.insert operations');\n\n// ==========================================================================\n// 4. method: UPDATE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions to identify records to update — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Perform an upsert? If true, insert if not found. */\n upsert: z.boolean().default(false).optional(),\n /** Update multiple records? If false, only the first match is updated. Default: false */\n multi: z.boolean().default(false).optional(),\n /** Return the updated record(s)? Default: false (returns update count/status) */\n returning: z.boolean().default(false).optional(),\n}).describe('QueryAST-aligned options for DataEngine.update operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineUpdateOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineUpdateOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineUpdateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineUpdateOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n upsert: z.boolean().default(false).optional(),\n multi: z.boolean().default(false).optional(),\n returning: z.boolean().default(false).optional(),\n}).describe('Options for DataEngine.update operations');\n\n// ==========================================================================\n// 5. method: DELETE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions to identify records to delete — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Delete multiple records? If false, only the first match is deleted. Default: false */\n multi: z.boolean().default(false).optional(),\n}).describe('QueryAST-aligned options for DataEngine.delete operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineDeleteOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineDeleteOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineDeleteOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineDeleteOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n multi: z.boolean().default(false).optional(),\n}).describe('Options for DataEngine.delete operations');\n\n// ==========================================================================\n// 6. method: AGGREGATE (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions (WHERE) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Group By fields */\n groupBy: z.array(z.string()).optional(),\n /** \n * Aggregation definitions — uses standard AggregationNodeSchema (`function` key).\n * e.g. [{ function: 'sum', field: 'amount', alias: 'total' }]\n */\n aggregations: z.array(AggregationNodeSchema).optional(),\n}).describe('QueryAST-aligned options for DataEngine.aggregate operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineAggregateOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineAggregateOptionsSchema` instead.\n * Migrate `filter` → `where`, aggregation `method` → `function`.\n */\nexport const DataEngineAggregateOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineAggregateOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n groupBy: z.array(z.string()).optional(),\n /** \n * @deprecated Use `EngineAggregateOptionsSchema` with standard AggregationNodeSchema (`function` key).\n */\n aggregations: z.array(z.object({\n field: z.string(),\n method: z.enum(['count', 'sum', 'avg', 'min', 'max', 'count_distinct']),\n alias: z.string().optional()\n })).optional(),\n}).describe('Options for DataEngine.aggregate operations');\n\n// ==========================================================================\n// 7. method: COUNT (QueryAST-aligned)\n// ==========================================================================\n\nexport const EngineCountOptionsSchema = BaseEngineOptionsSchema.extend({\n /** Filter conditions — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n}).describe('QueryAST-aligned options for DataEngine.count operations');\n\n// --------------------------------------------------------------------------\n// Legacy: DataEngineCountOptionsSchema (DEPRECATED)\n// --------------------------------------------------------------------------\n\n/**\n * @deprecated Use `EngineCountOptionsSchema` instead.\n * Migrate `filter` → `where`.\n */\nexport const DataEngineCountOptionsSchema = BaseEngineOptionsSchema.extend({\n /** @deprecated Use `where` (EngineCountOptionsSchema) */\n filter: DataEngineFilterSchema.optional(),\n}).describe('Options for DataEngine.count operations');\n\n// ==========================================================================\n// 8. Definition (Contract)\n// ==========================================================================\n\nexport const DataEngineContractSchema = z.object({\n find: z.function()\n .input(z.tuple([z.string(), EngineQueryOptionsSchema.optional()]))\n .output(z.promise(z.array(z.unknown()))),\n \n findOne: z.function()\n .input(z.tuple([z.string(), EngineQueryOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n insert: z.function()\n .input(z.tuple([z.string(), z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]), DataEngineInsertOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n update: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), EngineUpdateOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n delete: z.function()\n .input(z.tuple([z.string(), EngineDeleteOptionsSchema.optional()]))\n .output(z.promise(z.unknown())),\n \n count: z.function()\n .input(z.tuple([z.string(), EngineCountOptionsSchema.optional()]))\n .output(z.promise(z.number())),\n \n aggregate: z.function()\n .input(z.tuple([z.string(), EngineAggregateOptionsSchema]))\n .output(z.promise(z.array(z.unknown())))\n}).describe('Standard Data Engine Contract');\n\n// ==========================================================================\n// 9. Virtualization & RPC Protocol\n// ==========================================================================\n\n/**\n * Data Engine RPC Request (Virtual ObjectQL)\n * \n * This schema defines the serialized format for executing Data Engine operations\n * via HTTP, Message Queue, or Plugin boundaries.\n * \n * It enables \"Virtual Data Engines\" where the implementation resides in a \n * separate microservice or plugin.\n */\n\n/**\n * RPC backward-compatibility mixin — shared `@deprecated filter` field.\n * When both `filter` and `where` are present, the protocol/engine ignores\n * `filter` in favor of `where`; only one should be provided.\n */\nconst RpcLegacyFilterMixin = {\n /** @deprecated Use `where` */\n filter: DataEngineFilterSchema.optional(),\n};\n\n/**\n * RPC query options that accept BOTH new (where/fields/orderBy) and\n * legacy (filter/select/sort/skip/populate) parameter names.\n * \n * **Precedence:** When both legacy and new keys are present for the same\n * concern, the protocol normalizer uses the new key (`where` > `filter`,\n * `fields` > `select`, `orderBy` > `sort`, `offset` > `skip`,\n * `expand` > `populate`). Callers should not mix vocabularies.\n */\nconst RpcQueryOptionsSchema = EngineQueryOptionsSchema.extend({\n ...RpcLegacyFilterMixin,\n /** @deprecated Use `fields` */\n select: z.array(z.string()).optional(),\n /** @deprecated Use `orderBy` */\n sort: DataEngineSortSchema.optional(),\n /** @deprecated Use `offset` */\n skip: z.number().int().min(0).optional(),\n /** @deprecated Use `expand` */\n populate: z.array(z.string()).optional(),\n});\n\nexport const DataEngineFindRequestSchema = z.object({\n method: z.literal('find'),\n object: z.string(),\n query: RpcQueryOptionsSchema.optional()\n});\n\nexport const DataEngineFindOneRequestSchema = z.object({\n method: z.literal('findOne'),\n object: z.string(),\n query: RpcQueryOptionsSchema.optional()\n});\n\nexport const DataEngineInsertRequestSchema = z.object({\n method: z.literal('insert'),\n object: z.string(),\n data: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]),\n options: DataEngineInsertOptionsSchema.optional()\n});\n\nexport const DataEngineUpdateRequestSchema = z.object({\n method: z.literal('update'),\n object: z.string(),\n data: z.record(z.string(), z.unknown()),\n id: z.union([z.string(), z.number()]).optional().describe('ID for single update, or use where in options'),\n options: EngineUpdateOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineDeleteRequestSchema = z.object({\n method: z.literal('delete'),\n object: z.string(),\n id: z.union([z.string(), z.number()]).optional().describe('ID for single delete, or use where in options'),\n options: EngineDeleteOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineCountRequestSchema = z.object({\n method: z.literal('count'),\n object: z.string(),\n query: EngineCountOptionsSchema.extend(RpcLegacyFilterMixin).optional()\n});\n\nexport const DataEngineAggregateRequestSchema = z.object({\n method: z.literal('aggregate'),\n object: z.string(),\n query: EngineAggregateOptionsSchema.extend(RpcLegacyFilterMixin)\n});\n\n/**\n * Data Engine Execute Request (Raw Command)\n * Execute a raw command/query native to the driver (e.g. SQL, Shell, Remote API).\n */\nexport const DataEngineExecuteRequestSchema = z.object({\n method: z.literal('execute'),\n /** The abstract command (string SQL, or JSON object) */\n command: z.unknown(),\n /** Optional options */\n options: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Data Engine Vector Find Request (AI/RAG)\n * Perform a similarity search using vector embeddings.\n */\nexport const DataEngineVectorFindRequestSchema = z.object({\n method: z.literal('vectorFind'),\n object: z.string(),\n /** The vector embedding to search for */\n vector: z.array(z.number()),\n /** Optional pre-filter (Metadata filtering) — standard QueryAST `where` */\n where: z.union([z.record(z.string(), z.unknown()), FilterConditionSchema]).optional(),\n /** Fields to retrieve — standard QueryAST `fields` */\n fields: z.array(z.string()).optional(),\n /** Number of results */\n limit: z.number().int().default(5).optional(),\n /** Minimum similarity score (0-1) or distance threshold */\n threshold: z.number().optional()\n});\n\n/**\n * Data Engine Batch Request\n * Execute multiple operations in a single transaction/request efficiently.\n */\nexport const DataEngineBatchRequestSchema = z.object({\n method: z.literal('batch'),\n requests: z.array(z.discriminatedUnion('method', [\n DataEngineFindRequestSchema,\n DataEngineFindOneRequestSchema,\n DataEngineInsertRequestSchema,\n DataEngineUpdateRequestSchema,\n DataEngineDeleteRequestSchema,\n DataEngineCountRequestSchema,\n DataEngineAggregateRequestSchema,\n DataEngineExecuteRequestSchema,\n DataEngineVectorFindRequestSchema\n ])),\n /** \n * Transaction Mode\n * - true: All or nothing (Atomic)\n * - false: Best effort, continue on error\n */\n transaction: z.boolean().default(true).optional()\n});\n\n/**\n * Unified Data Engine Request Union\n * Use this to validate any incoming \"Virtual ObjectQL\" request.\n */\nexport const DataEngineRequestSchema = z.discriminatedUnion('method', [\n DataEngineFindRequestSchema,\n DataEngineFindOneRequestSchema,\n DataEngineInsertRequestSchema,\n DataEngineUpdateRequestSchema,\n DataEngineDeleteRequestSchema,\n DataEngineCountRequestSchema,\n DataEngineAggregateRequestSchema,\n DataEngineBatchRequestSchema,\n DataEngineExecuteRequestSchema,\n DataEngineVectorFindRequestSchema\n]).describe('Virtual ObjectQL Request Protocol');\n\n// ==========================================================================\n// 10. Type Exports\n// ==========================================================================\n\n// --- New: QueryAST-aligned types (preferred) ---\nexport type EngineQueryOptions = z.infer;\nexport type EngineUpdateOptions = z.infer;\nexport type EngineDeleteOptions = z.infer;\nexport type EngineAggregateOptions = z.infer;\nexport type EngineCountOptions = z.infer;\n\n// --- Legacy: deprecated types (kept for backward compatibility) ---\nexport type DataEngineFilter = z.infer;\n/** @deprecated Use standard `SortNode[]` from QueryAST instead. */\nexport type DataEngineSort = z.infer;\nexport type BaseEngineOptions = z.infer;\n/** @deprecated Use `EngineQueryOptions` instead. */\nexport type DataEngineQueryOptions = z.infer;\nexport type DataEngineInsertOptions = z.infer;\n/** @deprecated Use `EngineUpdateOptions` instead. */\nexport type DataEngineUpdateOptions = z.infer;\n/** @deprecated Use `EngineDeleteOptions` instead. */\nexport type DataEngineDeleteOptions = z.infer;\n/** @deprecated Use `EngineAggregateOptions` instead. */\nexport type DataEngineAggregateOptions = z.infer;\n/** @deprecated Use `EngineCountOptions` instead. */\nexport type DataEngineCountOptions = z.infer;\nexport type DataEngineRequest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { QuerySchema } from '../data/query.zod';\nimport { IsolationLevelEnum } from '../shared/enums.zod';\n\n/**\n * Common Driver Options\n * Passed to most driver methods to control behavior (transactions, timeouts, etc.)\n */\nexport const DriverOptionsSchema = z.object({\n /**\n * Transaction handle/identifier.\n * If provided, the operation must run within this transaction.\n */\n transaction: z.unknown().optional().describe('Transaction handle'),\n\n /**\n * Operation timeout in milliseconds.\n */\n timeout: z.number().optional().describe('Timeout in ms'),\n\n /**\n * Whether to bypass cache and force a fresh read.\n */\n skipCache: z.boolean().optional().describe('Bypass cache'),\n\n /**\n * Distributed Tracing Context.\n * Used for passing OpenTelemetry span context or request IDs for observability.\n */\n traceContext: z.record(z.string(), z.string()).optional().describe('OpenTelemetry context or request ID'),\n\n /**\n * Tenant Identifier.\n * For multi-tenant databases (row-level security or schema-per-tenant).\n */\n tenantId: z.string().optional().describe('Tenant Isolation identifier'),\n});\n\n/**\n * Driver Capabilities Schema\n * \n * Defines what features a database driver supports.\n * This allows ObjectQL to adapt its behavior based on underlying database capabilities.\n * Enhanced with granular capability flags for better feature detection.\n */\nexport const DriverCapabilitiesSchema = z.object({\n // ============================================================================\n // Basic CRUD Operations\n // ============================================================================\n \n /**\n * Whether the driver supports create operations.\n */\n create: z.boolean().default(true).describe('Supports CREATE operations'),\n \n /**\n * Whether the driver supports read operations.\n */\n read: z.boolean().default(true).describe('Supports READ operations'),\n \n /**\n * Whether the driver supports update operations.\n */\n update: z.boolean().default(true).describe('Supports UPDATE operations'),\n \n /**\n * Whether the driver supports delete operations.\n */\n delete: z.boolean().default(true).describe('Supports DELETE operations'),\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n \n /**\n * Whether the driver supports bulk create operations.\n */\n bulkCreate: z.boolean().default(false).describe('Supports bulk CREATE operations'),\n \n /**\n * Whether the driver supports bulk update operations.\n */\n bulkUpdate: z.boolean().default(false).describe('Supports bulk UPDATE operations'),\n \n /**\n * Whether the driver supports bulk delete operations.\n */\n bulkDelete: z.boolean().default(false).describe('Supports bulk DELETE operations'),\n\n // ============================================================================\n // Transaction & Connection Management\n // ============================================================================\n \n /**\n * Whether the driver supports database transactions.\n * If true, beginTransaction, commit, and rollback must be implemented.\n */\n transactions: z.boolean().default(false).describe('Supports ACID transactions'),\n \n /**\n * Whether the driver supports savepoints within transactions.\n */\n savepoints: z.boolean().default(false).describe('Supports transaction savepoints'),\n \n /**\n * Supported transaction isolation levels.\n */\n isolationLevels: z.array(IsolationLevelEnum).optional().describe('Supported isolation levels'),\n\n // ============================================================================\n // Query Operations\n // ============================================================================\n \n /**\n * Whether the driver supports WHERE clause filters.\n * If false, ObjectQL will fetch all records and filter in memory.\n * \n * Example: Memory driver might not support complex filter conditions.\n */\n queryFilters: z.boolean().default(true).describe('Supports WHERE clause filtering'),\n\n /**\n * Whether the driver supports aggregation functions (COUNT, SUM, AVG, etc.).\n * If false, ObjectQL will compute aggregations in memory.\n */\n queryAggregations: z.boolean().default(false).describe('Supports GROUP BY and aggregation functions'),\n\n /**\n * Whether the driver supports ORDER BY sorting.\n * If false, ObjectQL will sort results in memory.\n */\n querySorting: z.boolean().default(true).describe('Supports ORDER BY sorting'),\n\n /**\n * Whether the driver supports LIMIT/OFFSET pagination.\n * If false, ObjectQL will fetch all records and paginate in memory.\n */\n queryPagination: z.boolean().default(true).describe('Supports LIMIT/OFFSET pagination'),\n\n /**\n * Whether the driver supports window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.).\n * If false, ObjectQL will compute window functions in memory.\n */\n queryWindowFunctions: z.boolean().default(false).describe('Supports window functions with OVER clause'),\n\n /**\n * Whether the driver supports subqueries (nested SELECT statements).\n * If false, ObjectQL will execute queries separately and combine results.\n */\n querySubqueries: z.boolean().default(false).describe('Supports subqueries'),\n \n /**\n * Whether the driver supports Common Table Expressions (WITH clause).\n */\n queryCTE: z.boolean().default(false).describe('Supports Common Table Expressions (WITH clause)'),\n\n /**\n * Whether the driver supports SQL-style joins.\n * If false, ObjectQL will fetch related data separately and join in memory.\n */\n joins: z.boolean().default(false).describe('Supports SQL joins'),\n\n // ============================================================================\n // Advanced Features\n // ============================================================================\n \n /**\n * Whether the driver supports full-text search.\n * If true, text search queries can be pushed to the database.\n */\n fullTextSearch: z.boolean().default(false).describe('Supports full-text search'),\n \n /**\n * Whether the driver supports JSON querying capabilities.\n */\n jsonQuery: z.boolean().default(false).describe('Supports JSON field querying'),\n \n /**\n * Whether the driver supports geospatial queries.\n */\n geospatialQuery: z.boolean().default(false).describe('Supports geospatial queries'),\n \n /**\n * Whether the driver supports streaming large result sets.\n */\n streaming: z.boolean().default(false).describe('Supports result streaming (cursors/iterators)'),\n\n /**\n * Whether the driver supports JSON field types.\n * If false, JSON data will be serialized as strings.\n */\n jsonFields: z.boolean().default(false).describe('Supports JSON field types'),\n\n /**\n * Whether the driver supports array field types.\n * If false, arrays will be stored as JSON strings or in separate tables.\n */\n arrayFields: z.boolean().default(false).describe('Supports array field types'),\n\n /**\n * Whether the driver supports vector embeddings and similarity search.\n * Required for RAG (Retrieval-Augmented Generation) and AI features.\n */\n vectorSearch: z.boolean().default(false).describe('Supports vector embeddings and similarity search'),\n\n // ============================================================================\n // Schema Management\n // ============================================================================\n \n /**\n * Whether the driver supports automatic schema synchronization.\n */\n schemaSync: z.boolean().default(false).describe('Supports automatic schema synchronization'),\n\n /**\n * Whether the driver supports batching multiple schema sync operations\n * into a single (or fewer) round-trips for the DDL phase. When true,\n * the engine may call `syncSchemasBatch()` instead of calling\n * `syncSchema()` per object, reducing network round-trips for remote drivers.\n */\n batchSchemaSync: z.boolean().default(false).describe('Supports batched schema sync to reduce schema DDL round-trips'),\n \n /**\n * Whether the driver supports database migrations.\n */\n migrations: z.boolean().default(false).describe('Supports database migrations'),\n \n /**\n * Whether the driver supports index management.\n */\n indexes: z.boolean().default(false).describe('Supports index creation and management'),\n\n // ============================================================================\n // Performance & Optimization\n // ============================================================================\n \n /**\n * Whether the driver supports connection pooling.\n */\n connectionPooling: z.boolean().default(false).describe('Supports connection pooling'),\n \n /**\n * Whether the driver supports prepared statements.\n */\n preparedStatements: z.boolean().default(false).describe('Supports prepared statements (SQL injection prevention)'),\n \n /**\n * Whether the driver supports query result caching.\n */\n queryCache: z.boolean().default(false).describe('Supports query result caching'),\n});\n\n/**\n * Unified Database Driver Interface\n * \n * This is the contract that all storage adapters (Postgres, Mongo, Excel, Salesforce) must implement.\n * It abstracts the underlying engine, enabling ObjectStack to be \"Database Agnostic\".\n */\nexport const DriverInterfaceSchema = z.object({\n /**\n * Driver name (e.g., 'postgresql', 'mongodb', 'rest_api').\n */\n name: z.string().describe('Driver unique name'),\n\n /**\n * Driver version.\n */\n version: z.string().describe('Driver version'),\n\n /**\n * Capabilities descriptor.\n */\n supports: DriverCapabilitiesSchema,\n\n // ============================================================================\n // Lifecycle Management\n // ============================================================================\n\n /**\n * Initialize connection pool or authenticate.\n */\n connect: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.void()))\n .describe('Establish connection'),\n\n /**\n * Close connections and cleanup resources.\n */\n disconnect: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.void()))\n .describe('Close connection'),\n\n /**\n * Check connection health.\n * @returns true if healthy, false otherwise.\n */\n checkHealth: z.function()\n .input(z.tuple([]))\n .output(z.promise(z.boolean()))\n .describe('Health check'),\n \n /**\n * Get Connection Pool Statistics.\n * Useful for monitoring database load.\n */\n getPoolStats: z.function()\n .input(z.tuple([]))\n .output(z.object({\n total: z.number(),\n idle: z.number(),\n active: z.number(),\n waiting: z.number(),\n }).optional())\n .optional()\n .describe('Get connection pool statistics'),\n\n // ============================================================================\n // Raw Execution (Escape Hatch)\n // ============================================================================\n\n /**\n * Execute a raw command/query native to the driver.\n * Useful for complex reports, stored procedures, or DDL not covered by standard sync.\n * \n * @param command - The raw command (e.g., SQL string, shell command, or remote API payload).\n * @param parameters - Optional array of bound parameters for safe execution (prevention of injection).\n * @param options - Driver options (transaction context, timeout).\n * @returns Promise resolving to the raw result from the driver.\n * \n * @example\n * // SQL Driver\n * await driver.execute('SELECT * FROM complex_view WHERE id = ?', [123]);\n * \n * // Mongo Driver\n * await driver.execute({ aggregate: 'orders', pipeline: [...] });\n */\n execute: z.function()\n .input(z.tuple([z.unknown(), z.array(z.unknown()).optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.unknown()))\n .describe('Execute raw command'),\n\n // ============================================================================\n // CRUD Operations\n // ============================================================================\n\n /**\n * Find multiple records matching the structured query.\n * Parsing the QueryAST is the responsibility of the driver implementation.\n * \n * @param object - The name of the object/table to query (e.g. 'account').\n * @param query - The structured QueryAST (filters, sorts, joins, pagination).\n * @param options - Driver options.\n * @returns Array of records.\n * \n * @example\n * await driver.find('account', {\n * filters: [['status', '=', 'active'], 'and', ['amount', '>', 500]],\n * sort: [{ field: 'created_at', order: 'desc' }],\n * top: 10\n * });\n * @returns Array of records.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n find: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown()))))\n .describe('Find records'),\n\n /**\n * Stream records matching the structured query.\n * Optimized for large datasets to avoid memory overflow.\n * \n * @param object - The name of the object.\n * @param query - The structured QueryAST.\n * @param options - Driver options.\n * @returns AsyncIterable/ReadableStream of records.\n */\n findStream: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.unknown())\n .describe('Stream records (AsyncIterable)'),\n\n /**\n * Find a single record by query.\n * Similar to find(), but returns only the first match or null.\n * \n * @param object - The name of the object.\n * @param query - QueryAST.\n * @param options - Driver options.\n * @returns The record or null.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n findOne: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown()).nullable()))\n .describe('Find one record'),\n\n /**\n * Create a new record.\n * \n * @param object - The object name.\n * @param data - Key-value map of field data.\n * @param options - Driver options.\n * @returns The created record, including server-generated fields (id, created_at, etc.).\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n create: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Create record'),\n\n /**\n * Update an existing record by ID.\n * \n * @param object - The object name.\n * @param id - The unique identifier of the record.\n * @param data - The fields to update.\n * @param options - Driver options.\n * @returns The updated record.\n * MUST return `id` as string. MUST NOT return implementation details like `_id`.\n */\n update: z.function()\n .input(z.tuple([z.string(), z.string().or(z.number()), z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Update record'),\n\n /**\n * Upsert (Update or Insert) a record.\n * \n * @param object - The object name.\n * @param data - The data to upsert.\n * @param conflictKeys - Fields to check for conflict (uniqueness).\n * @param options - Driver options.\n * @returns The created or updated record.\n */\n upsert: z.function()\n .input(z.tuple([z.string(), z.record(z.string(), z.unknown()), z.array(z.string()).optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.record(z.string(), z.unknown())))\n .describe('Upsert record'),\n\n /**\n * Delete a record by ID.\n * \n * @param object - The object name.\n * @param id - The unique identifier of the record.\n * @param options - Driver options.\n * @returns True if deleted, false if not found.\n */\n delete: z.function()\n .input(z.tuple([z.string(), z.string().or(z.number()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.boolean()))\n .describe('Delete record'),\n\n /**\n * Count records matching a query.\n * \n * @param object - The object name.\n * @param query - Optional filtering criteria.\n * @param options - Driver options.\n * @returns Total count.\n */\n count: z.function()\n .input(z.tuple([z.string(), QuerySchema.optional(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .describe('Count records'),\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n\n /**\n * Create multiple records in a single batch.\n * Optimized for performance.\n * \n * @param object - The object name.\n * @param dataArray - Array of record data.\n * @returns Array of created records.\n */\n bulkCreate: z.function()\n .input(z.tuple([z.string(), z.array(z.record(z.string(), z.unknown())), DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown())))),\n\n /**\n * Update multiple records in a single batch.\n * \n * @param object - The object name.\n * @param updates - Array of objects containing {id, data}.\n * @returns Array of updated records.\n */\n bulkUpdate: z.function()\n .input(z.tuple([z.string(), z.array(z.object({ id: z.string().or(z.number()), data: z.record(z.string(), z.unknown()) })), DriverOptionsSchema.optional()]))\n .output(z.promise(z.array(z.record(z.string(), z.unknown())))),\n\n /**\n * Delete multiple records in a single batch.\n * \n * @param object - The object name.\n * @param ids - Array of record IDs.\n */\n bulkDelete: z.function()\n .input(z.tuple([z.string(), z.array(z.string().or(z.number())), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void())),\n\n /**\n * Update multiple records matching a query.\n * Direct database push-down. DOES NOT trigger per-record hooks.\n * \n * @param object - The object name.\n * @param query - The filtering criteria.\n * @param data - The data to update.\n * @returns Count of modified records.\n */\n updateMany: z.function()\n .input(z.tuple([z.string(), QuerySchema, z.record(z.string(), z.unknown()), DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .optional(),\n\n /**\n * Delete multiple records matching a query.\n * Direct database push-down. DOES NOT trigger per-record hooks.\n * \n * @param object - The object name.\n * @param query - The filtering criteria.\n * @returns Count of deleted records.\n */\n deleteMany: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.number()))\n .optional(),\n\n // ============================================================================\n // Transaction Management\n // ============================================================================\n\n /**\n * Begin a new database transaction.\n * @param options - Isolation level and other settings.\n * @returns A transaction handle to be passed to subsequent operations via `options.transaction`.\n */\n beginTransaction: z.function()\n .input(z.tuple([z.object({\n isolationLevel: IsolationLevelEnum.optional()\n }).optional()]))\n .output(z.promise(z.unknown()))\n .describe('Start transaction'),\n\n /**\n * Commit the transaction.\n * @param transaction - The transaction handle.\n */\n commit: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.promise(z.void()))\n .describe('Commit transaction'),\n\n /**\n * Rollback the transaction.\n * @param transaction - The transaction handle.\n */\n rollback: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.promise(z.void()))\n .describe('Rollback transaction'),\n\n // ============================================================================\n // Schema Management\n // ============================================================================\n\n /**\n * Synchronize the database schema with the Object definition.\n * This is an idempotent operation: it should create tables if missing, \n * add columns if missing, and update indexes.\n * \n * @param object - The object name.\n * @param schema - The full Object Schema (fields, indexes, etc).\n * @param options - Driver options.\n */\n syncSchema: z.function()\n .input(z.tuple([z.string(), z.unknown(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void()))\n .describe('Sync object schema to DB'),\n\n /**\n * Batch-synchronize multiple object schemas with fewer round-trips.\n *\n * Drivers that advertise `supports.batchSchemaSync = true` MUST implement\n * this method. The engine will call it once with every\n * `{ object, schema }` pair instead of calling `syncSchema()` N times.\n *\n * @param schemas - Array of `{ object: string; schema: unknown }` pairs.\n * @param options - Driver options.\n */\n syncSchemasBatch: z.function()\n .input(z.tuple([\n z.array(z.object({ object: z.string(), schema: z.unknown() })),\n DriverOptionsSchema.optional(),\n ]))\n .output(z.promise(z.void()))\n .optional()\n .describe('Batch sync multiple schemas in one round-trip'),\n \n /**\n * Drop the underlying table or collection for an object.\n * WARNING: Destructive operation.\n * \n * @param object - The object name.\n */\n dropTable: z.function()\n .input(z.tuple([z.string(), DriverOptionsSchema.optional()]))\n .output(z.promise(z.void())),\n\n /**\n * Analyze query performance.\n * Returns execution plan without executing the query (where possible).\n * \n * @param object - The object name.\n * @param query - The query to explain.\n * @returns The execution plan details.\n */\n explain: z.function()\n .input(z.tuple([z.string(), QuerySchema, DriverOptionsSchema.optional()]))\n .output(z.promise(z.unknown()))\n .optional(),\n});\n\n/**\n * Connection Pool Configuration Schema\n * Manages database connection pooling for performance\n */\nexport const PoolConfigSchema = z.object({\n min: z.number().min(0).default(2).describe('Minimum number of connections in pool'),\n max: z.number().min(1).default(10).describe('Maximum number of connections in pool'),\n idleTimeoutMillis: z.number().min(0).default(30000).describe('Time in ms before idle connection is closed'),\n connectionTimeoutMillis: z.number().min(0).default(5000).describe('Time in ms to wait for available connection'),\n});\n\n/**\n * Driver Configuration Schema\n * Base configuration for database drivers\n */\nexport const DriverConfigSchema = z.object({\n name: z.string().describe('Driver instance name'),\n type: z.enum(['sql', 'nosql', 'cache', 'search', 'graph', 'timeseries']).describe('Driver type category'),\n capabilities: DriverCapabilitiesSchema.describe('Driver capability flags'),\n connectionString: z.string().optional().describe('Database connection string (driver-specific format)'),\n poolConfig: PoolConfigSchema.optional().describe('Connection pool configuration'),\n});\n\n/**\n * TypeScript types\n */\nexport type DriverOptions = z.infer;\nexport type DriverCapabilities = z.infer;\nexport type DriverInterface = z.infer;\nexport type DriverConfig = z.infer;\nexport type PoolConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DriverConfigSchema } from './driver.zod';\n\n/**\n * SQL Dialect Enumeration\n * Supported SQL database dialects\n */\nexport const SQLDialectSchema = z.enum([\n 'postgresql',\n 'mysql',\n 'sqlite',\n 'mssql',\n 'oracle',\n 'mariadb',\n]);\n\nexport type SQLDialect = z.infer;\n\n/**\n * Data Type Mapping Schema\n * Maps ObjectStack field types to SQL-specific data types\n * \n * @example PostgreSQL data type mapping\n * {\n * text: 'VARCHAR(255)',\n * number: 'NUMERIC',\n * boolean: 'BOOLEAN',\n * date: 'DATE',\n * datetime: 'TIMESTAMP',\n * json: 'JSONB',\n * uuid: 'UUID',\n * binary: 'BYTEA'\n * }\n */\nexport const DataTypeMappingSchema = z.object({\n text: z.string().describe('SQL type for text fields (e.g., VARCHAR, TEXT)'),\n number: z.string().describe('SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)'),\n boolean: z.string().describe('SQL type for boolean fields (e.g., BOOLEAN, BIT)'),\n date: z.string().describe('SQL type for date fields (e.g., DATE)'),\n datetime: z.string().describe('SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)'),\n json: z.string().optional().describe('SQL type for JSON fields (e.g., JSON, JSONB)'),\n uuid: z.string().optional().describe('SQL type for UUID fields (e.g., UUID, CHAR(36))'),\n binary: z.string().optional().describe('SQL type for binary fields (e.g., BLOB, BYTEA)'),\n});\n\nexport type DataTypeMapping = z.infer;\n\n/**\n * SSL Configuration Schema\n * SSL/TLS connection configuration for secure database connections\n * \n * @example PostgreSQL SSL configuration\n * {\n * rejectUnauthorized: true,\n * ca: '/path/to/ca-cert.pem',\n * cert: '/path/to/client-cert.pem',\n * key: '/path/to/client-key.pem'\n * }\n */\nexport const SSLConfigSchema = z.object({\n rejectUnauthorized: z.boolean().default(true).describe('Reject connections with invalid certificates'),\n ca: z.string().optional().describe('CA certificate file path or content'),\n cert: z.string().optional().describe('Client certificate file path or content'),\n key: z.string().optional().describe('Client private key file path or content'),\n}).refine((data) => {\n // If cert is provided, key must also be provided, and vice versa\n const hasCert = data.cert !== undefined;\n const hasKey = data.key !== undefined;\n return hasCert === hasKey;\n}, {\n message: 'Client certificate (cert) and private key (key) must be provided together',\n});\n\nexport type SSLConfig = z.infer;\n\n/**\n * SQL Driver Configuration Schema\n * Extended driver configuration specific to SQL databases\n * \n * @example PostgreSQL driver configuration\n * {\n * name: 'primary-db',\n * type: 'sql',\n * dialect: 'postgresql',\n * connectionString: 'postgresql://user:pass@localhost:5432/mydb',\n * dataTypeMapping: {\n * text: 'VARCHAR(255)',\n * number: 'NUMERIC',\n * boolean: 'BOOLEAN',\n * date: 'DATE',\n * datetime: 'TIMESTAMP',\n * json: 'JSONB',\n * uuid: 'UUID',\n * binary: 'BYTEA'\n * },\n * ssl: true,\n * sslConfig: {\n * rejectUnauthorized: true,\n * ca: '/etc/ssl/certs/ca.pem'\n * },\n * poolConfig: {\n * min: 2,\n * max: 10,\n * idleTimeoutMillis: 30000,\n * connectionTimeoutMillis: 5000\n * },\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: true,\n * bulkDelete: true,\n * transactions: true,\n * savepoints: true,\n * isolationLevels: ['read-committed', 'repeatable-read', 'serializable'],\n * queryFilters: true,\n * queryAggregations: true,\n * querySorting: true,\n * queryPagination: true,\n * queryWindowFunctions: true,\n * querySubqueries: true,\n * queryCTE: true,\n * joins: true,\n * fullTextSearch: true,\n * jsonQuery: true,\n * geospatialQuery: false,\n * streaming: true,\n * jsonFields: true,\n * arrayFields: true,\n * vectorSearch: true,\n * schemaSync: true,\n * migrations: true,\n * indexes: true,\n * connectionPooling: true,\n * preparedStatements: true,\n * queryCache: false\n * }\n * }\n */\nexport const SQLDriverConfigSchema = DriverConfigSchema.extend({\n type: z.literal('sql').describe('Driver type must be \"sql\"'),\n dialect: SQLDialectSchema.describe('SQL database dialect'),\n dataTypeMapping: DataTypeMappingSchema.describe('SQL data type mapping configuration'),\n ssl: z.boolean().default(false).describe('Enable SSL/TLS connection'),\n sslConfig: SSLConfigSchema.optional().describe('SSL/TLS configuration (required when ssl is true)'),\n}).refine((data) => {\n // If ssl is enabled, sslConfig must be provided\n if (data.ssl && !data.sslConfig) {\n return false;\n }\n return true;\n}, {\n message: 'sslConfig is required when ssl is true',\n});\n\nexport type SQLDriverConfig = z.infer;\n\n// ==========================================================================\n// SQLite-Specific Constants\n// ==========================================================================\n\n/**\n * Default data type mappings for SQLite/libSQL dialect.\n *\n * SQLite uses a simplified type system with type affinity:\n * - TEXT: strings, dates, UUIDs\n * - REAL: floating-point numbers\n * - INTEGER: integers, booleans\n * - BLOB: binary data\n *\n * @see https://www.sqlite.org/datatype3.html\n */\nexport const SQLiteDataTypeMappingDefaults: DataTypeMapping = {\n text: 'TEXT',\n number: 'REAL',\n boolean: 'INTEGER',\n date: 'TEXT',\n datetime: 'TEXT',\n json: 'TEXT',\n uuid: 'TEXT',\n binary: 'BLOB',\n};\n\n/**\n * SQLite ALTER TABLE Limitations.\n *\n * SQLite has limited ALTER TABLE support compared to other SQL databases.\n * This constant documents the known limitations that affect migration planning.\n * The schema diff service must use the \"table rebuild\" strategy for operations\n * that SQLite cannot perform natively.\n *\n * @see https://www.sqlite.org/lang_altertable.html\n */\nexport const SQLiteAlterTableLimitations = {\n /** SQLite supports ADD COLUMN */\n supportsAddColumn: true,\n /** SQLite supports RENAME COLUMN (3.25.0+) */\n supportsRenameColumn: true,\n /** SQLite supports DROP COLUMN (3.35.0+) */\n supportsDropColumn: true,\n /** SQLite does NOT support MODIFY/ALTER COLUMN type */\n supportsModifyColumn: false,\n /** SQLite does NOT support adding constraints to existing columns */\n supportsAddConstraint: false,\n /**\n * When an unsupported alteration is needed, the migration planner\n * must use the 12-step table rebuild strategy:\n * 1. CREATE new table with desired schema\n * 2. Copy data from old table\n * 3. DROP old table\n * 4. RENAME new table to old name\n */\n rebuildStrategy: 'create_copy_drop_rename',\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DriverConfigSchema } from './driver.zod';\n\n/**\n * NoSQL Database Type Enumeration\n * Supported NoSQL database types\n */\nexport const NoSQLDatabaseTypeSchema = z.enum([\n 'mongodb',\n 'couchdb',\n 'dynamodb',\n 'cassandra',\n 'redis',\n 'elasticsearch',\n 'neo4j',\n 'orientdb',\n]);\n\nexport type NoSQLDatabaseType = z.infer;\n\n/**\n * NoSQL Query Operation Types\n * Different types of operations supported by NoSQL databases\n */\nexport const NoSQLOperationTypeSchema = z.enum([\n 'find', // Query documents/records\n 'findOne', // Get single document\n 'insert', // Insert document\n 'update', // Update document\n 'delete', // Delete document\n 'aggregate', // Aggregation pipeline\n 'mapReduce', // MapReduce operation\n 'count', // Count documents\n 'distinct', // Get distinct values\n 'createIndex', // Create index\n 'dropIndex', // Drop index\n]);\n\nexport type NoSQLOperationType = z.infer;\n\n/**\n * NoSQL Consistency Level\n * Consistency guarantees for distributed NoSQL databases\n * \n * Consistency levels (from strongest to weakest):\n * - **all**: All replicas must respond (strongest consistency, lowest availability)\n * - **quorum**: Majority of replicas must respond (balanced)\n * - **one**: Any single replica responds (weakest consistency, highest availability)\n * - **local_quorum**: Majority of replicas in local datacenter\n * - **each_quorum**: Quorum of replicas in each datacenter\n * - **eventual**: Eventual consistency (highest availability, weakest consistency)\n */\nexport const ConsistencyLevelSchema = z.enum([\n 'all',\n 'quorum',\n 'one',\n 'local_quorum',\n 'each_quorum',\n 'eventual',\n]);\n\nexport type ConsistencyLevel = z.infer;\n\n/**\n * NoSQL Index Type\n * Types of indexes supported by NoSQL databases\n */\nexport const NoSQLIndexTypeSchema = z.enum([\n 'single', // Single field index\n 'compound', // Multiple fields index\n 'unique', // Unique constraint\n 'text', // Full-text search index\n 'geospatial', // Geospatial index (2d, 2dsphere)\n 'hashed', // Hashed index for sharding\n 'ttl', // Time-to-live index (auto-deletion)\n 'sparse', // Sparse index (only indexed documents with field)\n]);\n\nexport type NoSQLIndexType = z.infer;\n\n/**\n * NoSQL Sharding Configuration\n * Configuration for horizontal partitioning across multiple nodes\n */\nexport const ShardingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable sharding'),\n shardKey: z.string().optional().describe('Field to use as shard key'),\n shardingStrategy: z.enum(['hash', 'range', 'zone']).optional().describe('Sharding strategy'),\n numShards: z.number().int().positive().optional().describe('Number of shards'),\n});\n\nexport type ShardingConfig = z.infer;\n\n/**\n * NoSQL Replication Configuration\n * Configuration for data replication across nodes\n */\nexport const ReplicationConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable replication'),\n replicaSetName: z.string().optional().describe('Replica set name'),\n replicas: z.number().int().positive().optional().describe('Number of replicas'),\n readPreference: z.enum(['primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'])\n .optional()\n .describe('Read preference for replica set'),\n writeConcern: z.enum(['majority', 'acknowledged', 'unacknowledged'])\n .optional()\n .describe('Write concern level'),\n});\n\nexport type ReplicationConfig = z.infer;\n\n/**\n * Document Schema Validation\n * Schema validation rules for document-based NoSQL databases\n */\nexport const DocumentSchemaValidationSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable schema validation'),\n validationLevel: z.enum(['strict', 'moderate', 'off']).optional().describe('Validation strictness'),\n validationAction: z.enum(['error', 'warn']).optional().describe('Action on validation failure'),\n jsonSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for validation'),\n});\n\nexport type DocumentSchemaValidation = z.infer;\n\n/**\n * NoSQL Data Type Mapping Schema\n * Maps ObjectStack field types to NoSQL-specific data types\n * \n * @example MongoDB data type mapping\n * {\n * text: 'string',\n * number: 'double',\n * boolean: 'bool',\n * date: 'date',\n * datetime: 'date',\n * json: 'object',\n * uuid: 'string',\n * binary: 'binData',\n * array: 'array',\n * objectId: 'objectId'\n * }\n */\nexport const NoSQLDataTypeMappingSchema = z.object({\n text: z.string().describe('NoSQL type for text fields'),\n number: z.string().describe('NoSQL type for number fields'),\n boolean: z.string().describe('NoSQL type for boolean fields'),\n date: z.string().describe('NoSQL type for date fields'),\n datetime: z.string().describe('NoSQL type for datetime fields'),\n json: z.string().optional().describe('NoSQL type for JSON/object fields'),\n uuid: z.string().optional().describe('NoSQL type for UUID fields'),\n binary: z.string().optional().describe('NoSQL type for binary fields'),\n array: z.string().optional().describe('NoSQL type for array fields'),\n objectId: z.string().optional().describe('NoSQL type for ObjectID fields (MongoDB)'),\n geopoint: z.string().optional().describe('NoSQL type for geospatial point fields'),\n});\n\nexport type NoSQLDataTypeMapping = z.infer;\n\n/**\n * NoSQL Driver Configuration Schema\n * Extended driver configuration specific to NoSQL databases\n * \n * @example MongoDB driver configuration\n * {\n * name: 'primary-mongo',\n * type: 'nosql',\n * databaseType: 'mongodb',\n * connectionString: 'mongodb://user:pass@localhost:27017/mydb',\n * dataTypeMapping: {\n * text: 'string',\n * number: 'double',\n * boolean: 'bool',\n * date: 'date',\n * datetime: 'date',\n * json: 'object',\n * uuid: 'string',\n * binary: 'binData',\n * array: 'array',\n * objectId: 'objectId'\n * },\n * consistency: 'quorum',\n * replication: {\n * enabled: true,\n * replicaSetName: 'rs0',\n * replicas: 3,\n * readPreference: 'primaryPreferred',\n * writeConcern: 'majority'\n * },\n * sharding: {\n * enabled: true,\n * shardKey: '_id',\n * shardingStrategy: 'hash',\n * numShards: 4\n * },\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: true,\n * bulkDelete: true,\n * transactions: true,\n * savepoints: false,\n * queryFilters: true,\n * queryAggregations: true,\n * querySorting: true,\n * queryPagination: true,\n * queryWindowFunctions: false,\n * querySubqueries: false,\n * queryCTE: false,\n * joins: false,\n * fullTextSearch: true,\n * jsonQuery: true,\n * geospatialQuery: true,\n * streaming: true,\n * jsonFields: true,\n * arrayFields: true,\n * vectorSearch: false,\n * schemaSync: true,\n * migrations: false,\n * indexes: true,\n * connectionPooling: true,\n * preparedStatements: false,\n * queryCache: false\n * }\n * }\n * \n * @example DynamoDB driver configuration\n * {\n * name: 'dynamodb-main',\n * type: 'nosql',\n * databaseType: 'dynamodb',\n * region: 'us-east-1',\n * accessKeyId: 'AKIAIOSFODNN7EXAMPLE',\n * secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n * consistency: 'eventual',\n * capabilities: {\n * create: true,\n * read: true,\n * update: true,\n * delete: true,\n * bulkCreate: true,\n * bulkUpdate: false,\n * bulkDelete: false,\n * transactions: true,\n * queryFilters: true,\n * queryAggregations: false,\n * querySorting: true,\n * queryPagination: true,\n * fullTextSearch: false,\n * jsonQuery: true,\n * indexes: true\n * }\n * }\n */\nexport const NoSQLDriverConfigSchema = DriverConfigSchema.extend({\n type: z.literal('nosql').describe('Driver type must be \"nosql\"'),\n databaseType: NoSQLDatabaseTypeSchema.describe('Specific NoSQL database type'),\n dataTypeMapping: NoSQLDataTypeMappingSchema.describe('NoSQL data type mapping configuration'),\n \n /**\n * Consistency level for reads/writes\n */\n consistency: ConsistencyLevelSchema.optional().describe('Consistency level for operations'),\n \n /**\n * Replication configuration\n */\n replication: ReplicationConfigSchema.optional().describe('Replication configuration'),\n \n /**\n * Sharding configuration\n */\n sharding: ShardingConfigSchema.optional().describe('Sharding configuration'),\n \n /**\n * Schema validation rules (for document databases)\n */\n schemaValidation: DocumentSchemaValidationSchema.optional().describe('Document schema validation'),\n \n /**\n * AWS Region (for DynamoDB, DocumentDB, etc.)\n */\n region: z.string().optional().describe('AWS region (for managed NoSQL services)'),\n \n /**\n * AWS Access Key ID (for DynamoDB, DocumentDB, etc.)\n */\n accessKeyId: z.string().optional().describe('AWS access key ID'),\n \n /**\n * AWS Secret Access Key (for DynamoDB, DocumentDB, etc.)\n */\n secretAccessKey: z.string().optional().describe('AWS secret access key'),\n \n /**\n * Time-to-live (TTL) field name\n * Automatically delete documents after a specified time\n */\n ttlField: z.string().optional().describe('Field name for TTL (auto-deletion)'),\n \n /**\n * Maximum document size in bytes\n */\n maxDocumentSize: z.number().int().positive().optional().describe('Maximum document size in bytes'),\n \n /**\n * Collection/Table name prefix\n * Useful for multi-tenancy or environment isolation\n */\n collectionPrefix: z.string().optional().describe('Prefix for collection/table names'),\n});\n\nexport type NoSQLDriverConfig = z.infer;\n\n/**\n * NoSQL Query Options\n * Additional options for NoSQL queries\n */\nexport const NoSQLQueryOptionsSchema = z.object({\n /**\n * Consistency level for this query\n */\n consistency: ConsistencyLevelSchema.optional().describe('Consistency level override'),\n \n /**\n * Read from secondary replicas\n */\n readFromSecondary: z.boolean().optional().describe('Allow reading from secondary replicas'),\n \n /**\n * Projection (fields to include/exclude)\n */\n projection: z.record(z.string(), z.union([z.literal(0), z.literal(1)])).optional().describe('Field projection'),\n \n /**\n * Query timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().describe('Query timeout (ms)'),\n \n /**\n * Use cursor for large result sets\n */\n useCursor: z.boolean().optional().describe('Use cursor instead of loading all results'),\n \n /**\n * Batch size for cursor iteration\n */\n batchSize: z.number().int().positive().optional().describe('Cursor batch size'),\n \n /**\n * Enable query profiling\n */\n profile: z.boolean().optional().describe('Enable query profiling'),\n \n /**\n * Use hinted index\n */\n hint: z.string().optional().describe('Index hint for query optimization'),\n});\n\nexport type NoSQLQueryOptions = z.infer;\n\n/**\n * NoSQL Aggregation Pipeline Stage\n * Represents a single stage in an aggregation pipeline (MongoDB-style)\n */\nexport const AggregationStageSchema = z.object({\n /**\n * Stage operator (e.g., $match, $group, $sort, $project)\n */\n operator: z.string().describe('Aggregation operator (e.g., $match, $group, $sort)'),\n \n /**\n * Stage parameters/options\n */\n options: z.record(z.string(), z.unknown()).describe('Stage-specific options'),\n});\n\nexport type AggregationStage = z.infer;\n\n/**\n * NoSQL Aggregation Pipeline\n * Sequence of aggregation stages for complex data transformations\n */\nexport const AggregationPipelineSchema = z.object({\n /**\n * Collection/Table to aggregate\n */\n collection: z.string().describe('Collection/table name'),\n \n /**\n * Pipeline stages\n */\n stages: z.array(AggregationStageSchema).describe('Aggregation pipeline stages'),\n \n /**\n * Additional options\n */\n options: NoSQLQueryOptionsSchema.optional().describe('Query options'),\n});\n\nexport type AggregationPipeline = z.infer;\n\n/**\n * NoSQL Index Definition\n * Definition for creating indexes in NoSQL databases\n */\nexport const NoSQLIndexSchema = z.object({\n /**\n * Index name\n */\n name: z.string().describe('Index name'),\n \n /**\n * Index type\n */\n type: NoSQLIndexTypeSchema.describe('Index type'),\n \n /**\n * Fields to index\n * For compound indexes, order matters\n */\n fields: z.array(z.object({\n field: z.string().describe('Field name'),\n order: z.enum(['asc', 'desc', 'text', '2dsphere']).optional().describe('Index order or type'),\n })).describe('Fields to index'),\n \n /**\n * Unique constraint\n */\n unique: z.boolean().default(false).describe('Enforce uniqueness'),\n \n /**\n * Sparse index (only index documents with the field)\n */\n sparse: z.boolean().default(false).describe('Sparse index'),\n \n /**\n * TTL in seconds (for TTL indexes)\n */\n expireAfterSeconds: z.number().int().positive().optional().describe('TTL in seconds'),\n \n /**\n * Partial index filter\n */\n partialFilterExpression: z.record(z.string(), z.unknown()).optional().describe('Partial index filter'),\n \n /**\n * Background index creation\n */\n background: z.boolean().default(false).describe('Create index in background'),\n});\n\nexport type NoSQLIndex = z.infer;\n\n/**\n * NoSQL Transaction Options\n * Options for NoSQL transactions (where supported)\n */\nexport const NoSQLTransactionOptionsSchema = z.object({\n /**\n * Read concern level\n */\n readConcern: z.enum(['local', 'majority', 'linearizable', 'snapshot']).optional().describe('Read concern level'),\n \n /**\n * Write concern level\n */\n writeConcern: z.enum(['majority', 'acknowledged', 'unacknowledged']).optional().describe('Write concern level'),\n \n /**\n * Read preference\n */\n readPreference: z.enum(['primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'])\n .optional()\n .describe('Read preference'),\n \n /**\n * Transaction timeout in milliseconds\n */\n maxCommitTimeMS: z.number().int().positive().optional().describe('Transaction commit timeout (ms)'),\n});\n\nexport type NoSQLTransactionOptions = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Data Import Strategy\n * Defines how the engine handles existing records.\n */\nexport const DatasetMode = z.enum([\n 'insert', // Try to insert, fail on duplicate\n 'update', // Only update found records, ignore new\n 'upsert', // Create new or Update existing (Standard)\n 'replace', // Delete ALL records in object then insert (Dangerous - use for cache tables)\n 'ignore' // Try to insert, silently skip duplicates\n]);\n\n/**\n * Dataset Schema (Seed Data / Fixtures)\n * \n * Standardized format for transporting data.\n * Used for:\n * 1. System Bootstrapping (Admin accounts, Standard Roles)\n * 2. Reference Data (Countries, Currencies)\n * 3. Demo/Test Data\n */\nexport const DatasetSchema = z.object({\n /** \n * Target Object \n * The machine name of the object to populate.\n */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target Object Name'),\n\n /** \n * Idempotency Key (The \"Upsert\" Key)\n * The field used to check if a record already exists.\n * Best Practice: Use a natural key like 'code', 'slug', 'username' or 'external_id'.\n * Standard: 'id' is rarely used for portable seed data — prefer natural keys.\n */\n externalId: z.string().default('name').describe('Field match for uniqueness check'),\n\n /** \n * Import Strategy\n */\n mode: DatasetMode.default('upsert').describe('Conflict resolution strategy'),\n\n /**\n * Environment Scope\n * - 'all': Always load\n * - 'dev': Only for development/demo\n * - 'test': Only for CI/CD tests\n */\n env: z.array(z.enum(['prod', 'dev', 'test'])).default(['prod', 'dev', 'test']).describe('Applicable environments'),\n\n /** \n * The Payload\n * Array of raw JSON objects matching the Object Schema.\n */\n records: z.array(z.record(z.string(), z.unknown())).describe('Data records'),\n});\n\n/** Parsed/output type — all defaults are applied (env, mode, externalId always present) */\nexport type Dataset = z.infer;\n\n/** Input type — fields with defaults (env, mode, externalId) are optional */\nexport type DatasetInput = z.input;\n\nexport type DatasetImportMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DatasetSchema, DatasetMode } from './dataset.zod';\n\n/**\n * # Seed Loader Protocol\n *\n * Defines the schemas for metadata-driven seed data loading with automatic\n * relationship resolution, dependency ordering, and multi-pass insertion.\n *\n * ## Architecture Alignment\n * - **Salesforce Data Loader**: External ID-based upsert with relationship resolution\n * - **ServiceNow**: Sys ID and display value mapping during import\n * - **Airtable**: Linked record resolution via display names\n *\n * ## Loading Flow\n * ```\n * 1. Build object dependency graph from field metadata (lookup/master_detail)\n * 2. Topological sort → determine insert order (parents before children)\n * 3. Pass 1: Insert/upsert records, resolve references via externalId\n * 4. Pass 2: Fill deferred references (circular/delayed dependencies)\n * 5. Validate & report unresolved references\n * 6. Return structured result with per-object stats\n * ```\n */\n\n// ==========================================================================\n// 1. Reference Resolution\n// ==========================================================================\n\n/**\n * Describes how a single field reference should be resolved during seed loading.\n *\n * When a lookup/master_detail field value is not an internal ID, the loader\n * attempts to match it against the target object's externalId field.\n */\nexport const ReferenceResolutionSchema = z.object({\n /** The field name on the source object (e.g., 'account_id') */\n field: z.string().describe('Source field name containing the reference value'),\n\n /** The target object being referenced (e.g., 'account') */\n targetObject: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Target object name (snake_case)'),\n\n /**\n * The field on the target object used to match the reference value.\n * Defaults to the target object's externalId (usually 'name').\n */\n targetField: z.string().default('name').describe('Field on target object used for matching'),\n\n /** The field type that triggered this resolution (lookup or master_detail) */\n fieldType: z.enum(['lookup', 'master_detail']).describe('Relationship field type'),\n}).describe('Describes how a field reference is resolved during seed loading');\n\nexport type ReferenceResolution = z.infer;\n\n// ==========================================================================\n// 2. Object Dependency Node\n// ==========================================================================\n\n/**\n * Represents a single object in the dependency graph.\n * Built from object metadata by inspecting lookup/master_detail fields.\n */\nexport const ObjectDependencyNodeSchema = z.object({\n /** Object machine name */\n object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Object name (snake_case)'),\n\n /**\n * Objects that this object depends on (via lookup/master_detail fields).\n * These must be loaded before this object.\n */\n dependsOn: z.array(z.string()).describe('Objects this object depends on'),\n\n /**\n * Field-level reference details for each dependency.\n * Maps field name → reference resolution info.\n */\n references: z.array(ReferenceResolutionSchema).describe('Field-level reference details'),\n}).describe('Object node in the seed data dependency graph');\n\nexport type ObjectDependencyNode = z.infer;\n\n// ==========================================================================\n// 3. Object Dependency Graph\n// ==========================================================================\n\n/**\n * The complete object dependency graph for seed data loading.\n * Used to determine topological insert order and detect circular dependencies.\n */\nexport const ObjectDependencyGraphSchema = z.object({\n /** All object nodes in the graph */\n nodes: z.array(ObjectDependencyNodeSchema).describe('All objects in the dependency graph'),\n\n /**\n * Topologically sorted object names for insertion order.\n * Parent objects appear before child objects.\n */\n insertOrder: z.array(z.string()).describe('Topologically sorted insert order'),\n\n /**\n * Circular dependency chains detected in the graph.\n * Each chain is an array of object names forming a cycle.\n * When present, the loader must use a multi-pass strategy.\n *\n * @example [['project', 'task', 'project']]\n */\n circularDependencies: z.array(z.array(z.string())).default([])\n .describe('Circular dependency chains (e.g., [[\"a\", \"b\", \"a\"]])'),\n}).describe('Complete object dependency graph for seed data loading');\n\nexport type ObjectDependencyGraph = z.infer;\n\n// ==========================================================================\n// 4. Reference Resolution Error\n// ==========================================================================\n\n/**\n * Actionable error for a failed reference resolution.\n * Provides all context needed to diagnose and fix the broken reference.\n *\n * Aligns with Salesforce Data Loader error reporting patterns:\n * field name, target object, attempted value, and reason.\n */\nexport const ReferenceResolutionErrorSchema = z.object({\n /** The source object containing the broken reference */\n sourceObject: z.string().describe('Object with the broken reference'),\n\n /** The field containing the unresolved value */\n field: z.string().describe('Field name with unresolved reference'),\n\n /** The target object that was searched */\n targetObject: z.string().describe('Target object searched for the reference'),\n\n /** The externalId field used for matching on the target object */\n targetField: z.string().describe('ExternalId field used for matching'),\n\n /** The value that could not be resolved */\n attemptedValue: z.unknown().describe('Value that failed to resolve'),\n\n /** The index of the record in the dataset's records array */\n recordIndex: z.number().int().min(0).describe('Index of the record in the dataset'),\n\n /** Human-readable error message */\n message: z.string().describe('Human-readable error description'),\n}).describe('Actionable error for a failed reference resolution');\n\nexport type ReferenceResolutionError = z.infer;\n\n// ==========================================================================\n// 5. Seed Loader Configuration\n// ==========================================================================\n\n/**\n * Configuration for the seed data loader.\n * Controls behavior for reference resolution, error handling, and validation.\n */\nexport const SeedLoaderConfigSchema = z.object({\n /**\n * Dry-run mode: validate all references without writing data.\n * Surfaces broken references before any mutations occur.\n * @default false\n */\n dryRun: z.boolean().default(false)\n .describe('Validate references without writing data'),\n\n /**\n * Whether to halt on the first reference resolution error.\n * When false, collects all errors and continues loading.\n * @default false\n */\n haltOnError: z.boolean().default(false)\n .describe('Stop on first reference resolution error'),\n\n /**\n * Enable multi-pass loading for circular dependencies.\n * Pass 1: Insert records with null for circular references.\n * Pass 2: Update records to fill deferred references.\n * @default true\n */\n multiPass: z.boolean().default(true)\n .describe('Enable multi-pass loading for circular dependencies'),\n\n /**\n * Default dataset mode when not specified per-dataset.\n * @default 'upsert'\n */\n defaultMode: DatasetMode.default('upsert')\n .describe('Default conflict resolution strategy'),\n\n /**\n * Maximum number of records to process in a single batch.\n * Controls memory usage for large datasets.\n * @default 1000\n */\n batchSize: z.number().int().min(1).default(1000)\n .describe('Maximum records per batch insert/upsert'),\n\n /**\n * Whether to wrap the entire load operation in a transaction.\n * When true, all-or-nothing semantics apply.\n * @default false\n */\n transaction: z.boolean().default(false)\n .describe('Wrap entire load in a transaction (all-or-nothing)'),\n\n /**\n * Environment filter. Only datasets matching this environment are loaded.\n * When not specified, all datasets are loaded regardless of env scope.\n */\n env: z.enum(['prod', 'dev', 'test']).optional()\n .describe('Only load datasets matching this environment'),\n}).describe('Seed data loader configuration');\n\nexport type SeedLoaderConfig = z.infer;\n\n/** Input type — all fields with defaults are optional */\nexport type SeedLoaderConfigInput = z.input;\n\n// ==========================================================================\n// 6. Per-Object Load Result\n// ==========================================================================\n\n/**\n * Result of loading a single object's dataset.\n */\nexport const DatasetLoadResultSchema = z.object({\n /** Target object name */\n object: z.string().describe('Object that was loaded'),\n\n /** Import mode used */\n mode: DatasetMode.describe('Import mode used'),\n\n /** Number of records successfully inserted */\n inserted: z.number().int().min(0).describe('Records inserted'),\n\n /** Number of records successfully updated (upsert matched existing) */\n updated: z.number().int().min(0).describe('Records updated'),\n\n /** Number of records skipped (mode: ignore, or already exists) */\n skipped: z.number().int().min(0).describe('Records skipped'),\n\n /** Number of records with errors */\n errored: z.number().int().min(0).describe('Records with errors'),\n\n /** Total records in the dataset */\n total: z.number().int().min(0).describe('Total records in dataset'),\n\n /** Number of references resolved via externalId */\n referencesResolved: z.number().int().min(0).describe('References resolved via externalId'),\n\n /** Number of references deferred to pass 2 (circular dependencies) */\n referencesDeferred: z.number().int().min(0).describe('References deferred to second pass'),\n\n /** Reference resolution errors for this object */\n errors: z.array(ReferenceResolutionErrorSchema).default([])\n .describe('Reference resolution errors'),\n}).describe('Result of loading a single dataset');\n\nexport type DatasetLoadResult = z.infer;\n\n// ==========================================================================\n// 7. Seed Loader Result\n// ==========================================================================\n\n/**\n * Complete result of a seed loading operation.\n * Aggregates all per-object results and provides summary statistics.\n */\nexport const SeedLoaderResultSchema = z.object({\n /** Whether the overall load operation succeeded */\n success: z.boolean().describe('Overall success status'),\n\n /** Was this a dry-run (validation only, no writes)? */\n dryRun: z.boolean().describe('Whether this was a dry-run'),\n\n /** The dependency graph used for ordering */\n dependencyGraph: ObjectDependencyGraphSchema.describe('Object dependency graph'),\n\n /** Per-object load results, in the order they were processed */\n results: z.array(DatasetLoadResultSchema).describe('Per-object load results'),\n\n /** All reference resolution errors across all objects */\n errors: z.array(ReferenceResolutionErrorSchema).describe('All reference resolution errors'),\n\n /** Summary statistics */\n summary: z.object({\n /** Total objects processed */\n objectsProcessed: z.number().int().min(0).describe('Total objects processed'),\n\n /** Total records across all objects */\n totalRecords: z.number().int().min(0).describe('Total records across all objects'),\n\n /** Total records inserted */\n totalInserted: z.number().int().min(0).describe('Total records inserted'),\n\n /** Total records updated */\n totalUpdated: z.number().int().min(0).describe('Total records updated'),\n\n /** Total records skipped */\n totalSkipped: z.number().int().min(0).describe('Total records skipped'),\n\n /** Total records with errors */\n totalErrored: z.number().int().min(0).describe('Total records with errors'),\n\n /** Total references resolved via externalId */\n totalReferencesResolved: z.number().int().min(0).describe('Total references resolved'),\n\n /** Total references deferred to second pass */\n totalReferencesDeferred: z.number().int().min(0).describe('Total references deferred'),\n\n /** Number of circular dependency chains detected */\n circularDependencyCount: z.number().int().min(0).describe('Circular dependency chains detected'),\n\n /** Duration of the load operation in milliseconds */\n durationMs: z.number().min(0).describe('Load duration in milliseconds'),\n }).describe('Summary statistics'),\n}).describe('Complete seed loader result');\n\nexport type SeedLoaderResult = z.infer;\n\n// ==========================================================================\n// 8. Seed Loader Request\n// ==========================================================================\n\n/**\n * Input request for the seed loader.\n * Combines datasets with loader configuration.\n */\nexport const SeedLoaderRequestSchema = z.object({\n /** Datasets to load */\n datasets: z.array(DatasetSchema).min(1).describe('Datasets to load'),\n\n /** Loader configuration */\n config: z.preprocess((val) => val ?? {}, SeedLoaderConfigSchema).describe('Loader configuration'),\n}).describe('Seed loader request with datasets and configuration');\n\nexport type SeedLoaderRequest = z.infer;\n\n/** Input type — config defaults are optional */\nexport type SeedLoaderRequestInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Document Version Schema\n * \n * Represents a single version of a document in a version-controlled system.\n * Each version is immutable and maintains its own metadata and download URL.\n * \n * @example\n * ```json\n * {\n * \"versionNumber\": 2,\n * \"createdAt\": 1704067200000,\n * \"createdBy\": \"user_123\",\n * \"size\": 2048576,\n * \"checksum\": \"a1b2c3d4e5f6\",\n * \"downloadUrl\": \"https://storage.example.com/docs/v2/file.pdf\",\n * \"isLatest\": true\n * }\n * ```\n */\nexport const DocumentVersionSchema = z.object({\n /**\n * Sequential version number (increments with each new version)\n */\n versionNumber: z.number().describe('Version number'),\n\n /**\n * Timestamp when this version was created (Unix milliseconds)\n */\n createdAt: z.number().describe('Creation timestamp'),\n\n /**\n * User ID who created this version\n */\n createdBy: z.string().describe('Creator user ID'),\n\n /**\n * File size in bytes\n */\n size: z.number().describe('File size in bytes'),\n\n /**\n * Checksum/hash of the file content (for integrity verification)\n */\n checksum: z.string().describe('File checksum'),\n\n /**\n * URL to download this specific version\n */\n downloadUrl: z.string().url().describe('Download URL'),\n\n /**\n * Whether this is the latest version\n * @default false\n */\n isLatest: z.boolean().optional().default(false).describe('Is latest version'),\n});\n\n/**\n * Document Template Schema\n * \n * Defines a reusable document template with dynamic placeholders.\n * Templates can be used to generate documents with variable content.\n * \n * @example\n * ```json\n * {\n * \"id\": \"contract-template\",\n * \"name\": \"Service Agreement\",\n * \"description\": \"Standard service agreement template\",\n * \"fileUrl\": \"https://example.com/templates/contract.docx\",\n * \"fileType\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n * \"placeholders\": [\n * {\n * \"key\": \"client_name\",\n * \"label\": \"Client Name\",\n * \"type\": \"text\",\n * \"required\": true\n * },\n * {\n * \"key\": \"contract_date\",\n * \"label\": \"Contract Date\",\n * \"type\": \"date\",\n * \"required\": true\n * }\n * ]\n * }\n * ```\n */\nexport const DocumentTemplateSchema = z.object({\n /**\n * Unique identifier for the template\n */\n id: z.string().describe('Template ID'),\n\n /**\n * Human-readable name of the template\n */\n name: z.string().describe('Template name'),\n\n /**\n * Optional description of the template's purpose\n */\n description: z.string().optional().describe('Template description'),\n\n /**\n * URL to the template file\n */\n fileUrl: z.string().url().describe('Template file URL'),\n\n /**\n * MIME type of the template file\n */\n fileType: z.string().describe('File MIME type'),\n\n /**\n * List of dynamic placeholders in the template\n */\n placeholders: z.array(z.object({\n /**\n * Placeholder identifier (used in template)\n */\n key: z.string().describe('Placeholder key'),\n\n /**\n * Human-readable label for the placeholder\n */\n label: z.string().describe('Placeholder label'),\n\n /**\n * Data type of the placeholder value\n */\n type: z.enum(['text', 'number', 'date', 'image']).describe('Placeholder type'),\n\n /**\n * Whether this placeholder must be filled\n * @default false\n */\n required: z.boolean().optional().default(false).describe('Is required'),\n })).describe('Template placeholders'),\n});\n\n/**\n * E-Signature Configuration Schema\n * \n * Configuration for electronic signature workflows.\n * Supports integration with popular e-signature providers.\n * \n * @example\n * ```json\n * {\n * \"provider\": \"docusign\",\n * \"enabled\": true,\n * \"signers\": [\n * {\n * \"email\": \"client@example.com\",\n * \"name\": \"John Doe\",\n * \"role\": \"Client\",\n * \"order\": 1\n * },\n * {\n * \"email\": \"manager@example.com\",\n * \"name\": \"Jane Smith\",\n * \"role\": \"Manager\",\n * \"order\": 2\n * }\n * ],\n * \"expirationDays\": 30,\n * \"reminderDays\": 7\n * }\n * ```\n */\nexport const ESignatureConfigSchema = z.object({\n /**\n * E-signature service provider\n */\n provider: z.enum(['docusign', 'adobe-sign', 'hellosign', 'custom']).describe('E-signature provider'),\n\n /**\n * Whether e-signature is enabled for this document\n * @default false\n */\n enabled: z.boolean().optional().default(false).describe('E-signature enabled'),\n\n /**\n * List of signers in signing order\n */\n signers: z.array(z.object({\n /**\n * Signer's email address\n */\n email: z.string().email().describe('Signer email'),\n\n /**\n * Signer's full name\n */\n name: z.string().describe('Signer name'),\n\n /**\n * Signer's role in the document\n */\n role: z.string().describe('Signer role'),\n\n /**\n * Signing order (lower numbers sign first)\n */\n order: z.number().describe('Signing order'),\n })).describe('Document signers'),\n\n /**\n * Days until signature request expires\n * @default 30\n */\n expirationDays: z.number().optional().default(30).describe('Expiration days'),\n\n /**\n * Days between reminder emails\n * @default 7\n */\n reminderDays: z.number().optional().default(7).describe('Reminder interval days'),\n});\n\n/**\n * Document Schema\n * \n * Comprehensive document management protocol supporting versioning,\n * templates, e-signatures, and access control.\n * \n * @example\n * ```json\n * {\n * \"id\": \"doc_123\",\n * \"name\": \"Service Agreement 2024\",\n * \"description\": \"Annual service agreement\",\n * \"fileType\": \"application/pdf\",\n * \"fileSize\": 1048576,\n * \"category\": \"contracts\",\n * \"tags\": [\"legal\", \"2024\", \"services\"],\n * \"versioning\": {\n * \"enabled\": true,\n * \"versions\": [\n * {\n * \"versionNumber\": 1,\n * \"createdAt\": 1704067200000,\n * \"createdBy\": \"user_123\",\n * \"size\": 1048576,\n * \"checksum\": \"abc123\",\n * \"downloadUrl\": \"https://example.com/docs/v1.pdf\",\n * \"isLatest\": true\n * }\n * ],\n * \"majorVersion\": 1,\n * \"minorVersion\": 0\n * },\n * \"access\": {\n * \"isPublic\": false,\n * \"sharedWith\": [\"user_456\", \"team_789\"],\n * \"expiresAt\": 1735689600000\n * },\n * \"metadata\": {\n * \"author\": \"John Doe\",\n * \"department\": \"Legal\"\n * }\n * }\n * ```\n */\nexport const DocumentSchema = z.object({\n /**\n * Unique document identifier\n */\n id: z.string().describe('Document ID'),\n\n /**\n * Document name\n */\n name: z.string().describe('Document name'),\n\n /**\n * Optional document description\n */\n description: z.string().optional().describe('Document description'),\n\n /**\n * MIME type of the document\n */\n fileType: z.string().describe('File MIME type'),\n\n /**\n * File size in bytes\n */\n fileSize: z.number().describe('File size in bytes'),\n\n /**\n * Document category for organization\n */\n category: z.string().optional().describe('Document category'),\n\n /**\n * Tags for searchability and organization\n */\n tags: z.array(z.string()).optional().describe('Document tags'),\n\n /**\n * Version control configuration\n */\n versioning: z.object({\n /**\n * Whether versioning is enabled\n */\n enabled: z.boolean().describe('Versioning enabled'),\n\n /**\n * List of all document versions\n */\n versions: z.array(DocumentVersionSchema).describe('Version history'),\n\n /**\n * Current major version number\n */\n majorVersion: z.number().describe('Major version'),\n\n /**\n * Current minor version number\n */\n minorVersion: z.number().describe('Minor version'),\n }).optional().describe('Version control'),\n\n /**\n * Template configuration (if document is generated from template)\n */\n template: DocumentTemplateSchema.optional().describe('Document template'),\n\n /**\n * E-signature configuration\n */\n eSignature: ESignatureConfigSchema.optional().describe('E-signature config'),\n\n /**\n * Access control settings\n */\n access: z.object({\n /**\n * Whether document is publicly accessible\n * @default false\n */\n isPublic: z.boolean().optional().default(false).describe('Public access'),\n\n /**\n * List of user/team IDs with access\n */\n sharedWith: z.array(z.string()).optional().describe('Shared with'),\n\n /**\n * Timestamp when access expires (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Access expiration'),\n }).optional().describe('Access control'),\n\n /**\n * Custom metadata fields\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\n// Type exports\nexport type Document = z.infer;\nexport type DocumentVersion = z.infer;\nexport type DocumentTemplate = z.infer;\nexport type ESignatureConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldMappingSchema as BaseFieldMappingSchema } from '../shared/mapping.zod';\n\n/**\n * External Data Source Schema\n * \n * Configuration for connecting to external data systems.\n * Similar to Salesforce External Objects for real-time data integration.\n * \n * @example\n * ```json\n * {\n * \"id\": \"salesforce-accounts\",\n * \"name\": \"Salesforce Account Data\",\n * \"type\": \"rest-api\",\n * \"endpoint\": \"https://api.salesforce.com/services/data/v58.0\",\n * \"authentication\": {\n * \"type\": \"oauth2\",\n * \"config\": {\n * \"clientId\": \"...\",\n * \"clientSecret\": \"...\",\n * \"tokenUrl\": \"https://login.salesforce.com/services/oauth2/token\"\n * }\n * }\n * }\n * ```\n */\nexport const ExternalDataSourceSchema = z.object({\n /**\n * Unique identifier for the external data source\n */\n id: z.string().describe('Data source ID'),\n\n /**\n * Human-readable name of the data source\n */\n name: z.string().describe('Data source name'),\n\n /**\n * Protocol type for connecting to the data source\n */\n type: z.enum(['odata', 'rest-api', 'graphql', 'custom']).describe('Protocol type'),\n\n /**\n * Base URL endpoint for the external system\n */\n endpoint: z.string().url().describe('API endpoint URL'),\n\n /**\n * Authentication configuration\n */\n authentication: z.object({\n /**\n * Authentication method\n */\n type: z.enum(['oauth2', 'api-key', 'basic', 'none']).describe('Auth type'),\n\n /**\n * Authentication-specific configuration\n * Structure varies based on auth type\n */\n config: z.record(z.string(), z.unknown()).describe('Auth configuration'),\n }).describe('Authentication'),\n});\n\n/**\n * Field Mapping Schema for External Lookups\n * \n * Extends the base field mapping with external lookup specific features.\n * Uses the canonical field mapping protocol from shared/mapping.zod.ts.\n * \n * @see {@link BaseFieldMappingSchema} for the base field mapping schema\n * \n * @example\n * ```json\n * {\n * \"source\": \"AccountName\",\n * \"target\": \"name\",\n * \"readonly\": true\n * }\n * ```\n */\nexport const ExternalFieldMappingSchema = BaseFieldMappingSchema.extend({\n /**\n * Field data type\n */\n type: z.string().optional().describe('Field type'),\n\n /**\n * Whether the field is read-only\n * @default true\n */\n readonly: z.boolean().optional().default(true).describe('Read-only field'),\n});\n\n/**\n * External Lookup Schema\n * \n * Real-time data lookup protocol for external systems.\n * Enables querying external data sources without replication.\n * Inspired by Salesforce External Objects and OData protocols.\n * \n * @example\n * ```json\n * {\n * \"fieldName\": \"external_account\",\n * \"dataSource\": {\n * \"id\": \"salesforce-api\",\n * \"name\": \"Salesforce\",\n * \"type\": \"rest-api\",\n * \"endpoint\": \"https://api.salesforce.com/services/data/v58.0\",\n * \"authentication\": {\n * \"type\": \"oauth2\",\n * \"config\": {\"clientId\": \"...\"}\n * }\n * },\n * \"query\": {\n * \"endpoint\": \"/sobjects/Account\",\n * \"method\": \"GET\",\n * \"parameters\": {\"limit\": 100}\n * },\n * \"fieldMappings\": [\n * {\n * \"externalField\": \"Name\",\n * \"localField\": \"account_name\",\n * \"type\": \"text\",\n * \"readonly\": true\n * }\n * ],\n * \"caching\": {\n * \"enabled\": true,\n * \"ttl\": 300,\n * \"strategy\": \"ttl\"\n * },\n * \"fallback\": {\n * \"enabled\": true,\n * \"showError\": true\n * },\n * \"rateLimit\": {\n * \"requestsPerSecond\": 10,\n * \"burstSize\": 20\n * }\n * }\n * ```\n */\nexport const ExternalLookupSchema = z.object({\n /**\n * Name of the field that uses external lookup\n */\n fieldName: z.string().describe('Field name'),\n\n /**\n * External data source configuration\n */\n dataSource: ExternalDataSourceSchema.describe('External data source'),\n\n /**\n * Query configuration for fetching external data\n */\n query: z.object({\n /**\n * API endpoint path (relative to base endpoint)\n */\n endpoint: z.string().describe('Query endpoint path'),\n\n /**\n * HTTP method for the query\n * @default 'GET'\n */\n method: z.enum(['GET', 'POST']).optional().default('GET').describe('HTTP method'),\n\n /**\n * Query parameters or request body\n */\n parameters: z.record(z.string(), z.unknown()).optional().describe('Query parameters'),\n }).describe('Query configuration'),\n\n /**\n * Mapping between external and local fields\n */\n fieldMappings: z.array(ExternalFieldMappingSchema).describe('Field mappings'),\n\n /**\n * Cache configuration for external data\n */\n caching: z.object({\n /**\n * Whether caching is enabled\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Cache enabled'),\n\n /**\n * Time-to-live in seconds\n * @default 300\n */\n ttl: z.number().optional().default(300).describe('Cache TTL (seconds)'),\n\n /**\n * Cache eviction strategy\n * @default 'ttl'\n */\n strategy: z.enum(['lru', 'lfu', 'ttl']).optional().default('ttl').describe('Cache strategy'),\n }).optional().describe('Caching configuration'),\n\n /**\n * Fallback behavior when external system is unavailable\n */\n fallback: z.object({\n /**\n * Whether fallback is enabled\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Fallback enabled'),\n\n /**\n * Default value to use when external system fails\n */\n defaultValue: z.unknown().optional().describe('Default fallback value'),\n\n /**\n * Whether to show error message to user\n * @default true\n */\n showError: z.boolean().optional().default(true).describe('Show error to user'),\n }).optional().describe('Fallback configuration'),\n\n /**\n * Rate limiting to prevent overwhelming external system\n */\n rateLimit: z.object({\n /**\n * Maximum requests per second\n */\n requestsPerSecond: z.number().describe('Requests per second limit'),\n\n /**\n * Burst size for handling spikes\n */\n burstSize: z.number().optional().describe('Burst size'),\n }).optional().describe('Rate limiting'),\n\n /**\n * Retry configuration with exponential backoff\n *\n * @example\n * ```json\n * {\n * \"maxRetries\": 3,\n * \"initialDelayMs\": 1000,\n * \"maxDelayMs\": 30000,\n * \"backoffMultiplier\": 2,\n * \"retryableStatusCodes\": [429, 500, 502, 503, 504]\n * }\n * ```\n */\n retry: z.object({\n /** Maximum number of retry attempts */\n maxRetries: z.number().min(0).default(3).describe('Maximum retry attempts'),\n /** Initial delay before first retry (ms) */\n initialDelayMs: z.number().default(1000).describe('Initial retry delay in milliseconds'),\n /** Maximum delay between retries (ms) */\n maxDelayMs: z.number().default(30000).describe('Maximum retry delay in milliseconds'),\n /** Backoff multiplier for exponential backoff */\n backoffMultiplier: z.number().default(2).describe('Exponential backoff multiplier'),\n /** HTTP status codes that trigger a retry */\n retryableStatusCodes: z.array(z.number()).default([429, 500, 502, 503, 504])\n .describe('HTTP status codes that are retryable'),\n }).optional().describe('Retry configuration with exponential backoff'),\n\n /**\n * Request/response transformation pipeline\n *\n * Allows transforming request parameters and response data\n * before they are processed by the external lookup system.\n */\n transform: z.object({\n /** Transform request parameters before sending */\n request: z.object({\n /** Header transformations (key-value additions) */\n headers: z.record(z.string(), z.string()).optional().describe('Additional request headers'),\n /** Query parameter transformations */\n queryParams: z.record(z.string(), z.string()).optional().describe('Additional query parameters'),\n }).optional().describe('Request transformation'),\n /** Transform response data after receiving */\n response: z.object({\n /** JSONPath expression to extract data from response */\n dataPath: z.string().optional().describe('JSONPath to extract data (e.g., \"$.data.results\")'),\n /** JSONPath expression to extract total count for pagination */\n totalPath: z.string().optional().describe('JSONPath to extract total count (e.g., \"$.meta.total\")'),\n }).optional().describe('Response transformation'),\n }).optional().describe('Request/response transformation pipeline'),\n\n /** Pagination support for external data sources */\n pagination: z.object({\n /** Pagination type */\n type: z.enum(['offset', 'cursor', 'page']).default('offset').describe('Pagination type'),\n /** Page size */\n pageSize: z.number().default(100).describe('Items per page'),\n /** Maximum pages to fetch */\n maxPages: z.number().optional().describe('Maximum number of pages to fetch'),\n }).optional().describe('Pagination configuration for external data'),\n});\n\n// Type exports\nexport type ExternalLookup = z.infer;\nexport type ExternalDataSource = z.infer;\nexport type ExternalFieldMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n\n/**\n * Driver Identifier\n * Can be a built-in driver or a plugin-contributed driver (e.g., \"com.vendor.snowflake\").\n */\nexport const DriverType = z.string().describe('Underlying driver identifier');\n\n/**\n * Driver Definition Schema\n * Metadata describing a Database Driver.\n * Plugins use this to register new connectivity options.\n */\nexport const DriverDefinitionSchema = z.object({\n id: z.string().describe('Unique driver identifier (e.g. \"postgres\")'),\n label: z.string().describe('Display label (e.g. \"PostgreSQL\")'),\n description: z.string().optional(),\n icon: z.string().optional(),\n \n /**\n * Configuration Schema (JSON Schema)\n * Describes the structure of the `config` object needed for this driver.\n * Used by the UI to generate the connection form.\n */\n configSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for connection configuration'),\n \n /**\n * Default Capabilities\n * What this driver supports out-of-the-box.\n */\n capabilities: z.lazy(() => DatasourceCapabilities).optional(),\n});\n\n/**\n * Datasource Capabilities Schema\n * Declares what this datasource naturally supports.\n * The ObjectQL engine uses this to determine what logic to push down\n * and what to compute in memory.\n */\nexport const DatasourceCapabilities = z.object({\n // ============================================================================\n // Transaction & Connection Management\n // ============================================================================\n \n /** Can handle ACID transactions? */\n transactions: z.boolean().default(false),\n \n // ============================================================================\n // Query Operations\n // ============================================================================\n \n /** Can execute WHERE clause filters natively? */\n queryFilters: z.boolean().default(false),\n \n /** Can perform aggregation (group by, sum, avg)? */\n queryAggregations: z.boolean().default(false),\n \n /** Can perform ORDER BY sorting? */\n querySorting: z.boolean().default(false),\n \n /** Can perform LIMIT/OFFSET pagination? */\n queryPagination: z.boolean().default(false),\n \n /** Can perform window functions? */\n queryWindowFunctions: z.boolean().default(false),\n \n /** Can perform subqueries? */\n querySubqueries: z.boolean().default(false),\n \n /** Can execute SQL-like joins natively? */\n joins: z.boolean().default(false),\n \n // ============================================================================\n // Advanced Features\n // ============================================================================\n \n /** Can perform full-text search? */\n fullTextSearch: z.boolean().default(false),\n \n /** Is read-only? */\n readOnly: z.boolean().default(false),\n \n /** Is scheme-less (needs schema inference)? */\n dynamicSchema: z.boolean().default(false),\n});\n\n/**\n * Datasource Schema\n * Represents a connection to an external data store.\n */\nexport const DatasourceSchema = z.object({\n /** Machine Name */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique datasource identifier'),\n \n /** Human Label */\n label: z.string().optional().describe('Display label'),\n \n /** Driver */\n driver: DriverType.describe('Underlying driver type'),\n \n /** \n * Connection Configuration \n * Specific to the driver (e.g., host, port, user, password, bucket, etc.)\n * Stored securely (passwords usually interpolated from ENV).\n */\n config: z.record(z.string(), z.unknown()).describe('Driver specific configuration'),\n \n /**\n * Connection Pool Configuration\n * Standard connection pooling settings.\n */\n pool: z.object({\n min: z.number().default(0).describe('Minimum connections'),\n max: z.number().default(10).describe('Maximum connections'),\n idleTimeoutMillis: z.number().default(30000).describe('Idle timeout'),\n connectionTimeoutMillis: z.number().default(3000).describe('Connection establishment timeout'),\n }).optional().describe('Connection pool settings'),\n\n /**\n * Read Replicas\n * Optional list of duplicate configurations for read-only operations.\n * Useful for scaling read throughput.\n */\n readReplicas: z.array(z.record(z.string(), z.unknown())).optional().describe('Read-only replica configurations'),\n\n /**\n * Capability Overrides\n * Manually override what the driver claims to support.\n */\n capabilities: DatasourceCapabilities.optional().describe('Capability overrides'),\n \n /** Health Check */\n healthCheck: z.object({\n enabled: z.boolean().default(true).describe('Enable health check endpoint'),\n intervalMs: z.number().default(30000).describe('Health check interval in milliseconds'),\n timeoutMs: z.number().default(5000).describe('Health check timeout in milliseconds'),\n }).optional().describe('Datasource health check configuration'),\n\n /** SSL/TLS Configuration */\n ssl: z.object({\n enabled: z.boolean().default(false).describe('Enable SSL/TLS for database connection'),\n rejectUnauthorized: z.boolean().default(true).describe('Reject connections with invalid/self-signed certificates'),\n ca: z.string().optional().describe('CA certificate (PEM format or path to file)'),\n cert: z.string().optional().describe('Client certificate (PEM format or path to file)'),\n key: z.string().optional().describe('Client private key (PEM format or path to file)'),\n }).optional().describe('SSL/TLS configuration for secure database connections'),\n\n /** Retry Policy */\n retryPolicy: z.object({\n maxRetries: z.number().default(3).describe('Maximum number of retry attempts'),\n baseDelayMs: z.number().default(1000).describe('Base delay between retries in milliseconds'),\n maxDelayMs: z.number().default(30000).describe('Maximum delay between retries in milliseconds'),\n backoffMultiplier: z.number().default(2).describe('Exponential backoff multiplier'),\n }).optional().describe('Connection retry policy for transient failures'),\n\n /** Description */\n description: z.string().optional().describe('Internal description'),\n \n /** Is enabled? */\n active: z.boolean().default(true).describe('Is datasource enabled'),\n});\n\nexport type Datasource = z.infer;\nexport type DatasourceCapabilitiesType = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Analytics/Semantic Layer Protocol\n * \n * Defines the \"Business Logic\" for data analysis.\n * Inspired by Cube.dev, LookML, and dbt MetricFlow.\n * \n * This layer decouples the \"Physical Data\" (Tables/Columns) from the \n * \"Business Data\" (Metrics/Dimensions).\n */\n\n/**\n * Aggregation Metric Type\n * The mathematical operation to perform on a metric.\n */\nexport const AggregationMetricType = z.enum([\n 'count', \n 'sum', \n 'avg', \n 'min', \n 'max', \n 'count_distinct', \n 'number', // Custom SQL expression returning a number\n 'string', // Custom SQL expression returning a string\n 'boolean' // Custom SQL expression returning a boolean\n]);\n\n/**\n * Dimension Type\n * The nature of the grouping field.\n */\nexport const DimensionType = z.enum([\n 'string', \n 'number', \n 'boolean', \n 'time', \n 'geo'\n]);\n\n/**\n * Time Interval for Time Dimensions\n */\nexport const TimeUpdateInterval = z.enum([\n 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'\n]);\n\n/**\n * Metric Schema\n * A quantitative measurement (e.g., \"Total Revenue\", \"Average Order Value\").\n */\nexport const MetricSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique metric ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: AggregationMetricType,\n \n /** Source Calculation */\n sql: z.string().describe('SQL expression or field reference'),\n \n /** Filtering for this specific metric (e.g. \"Revenue from Premium Users\") */\n filters: z.array(z.object({\n sql: z.string()\n })).optional(),\n \n /** Format for display (e.g. \"currency\", \"percent\") */\n format: z.string().optional(),\n});\n\n/**\n * Dimension Schema\n * A categorical attribute to group by (e.g., \"Product Category\", \"Order Date\").\n */\nexport const DimensionSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique dimension ID'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n \n type: DimensionType,\n \n /** Source Column */\n sql: z.string().describe('SQL expression or column reference'),\n \n /** For Time Dimensions: Supported Granularities */\n granularities: z.array(TimeUpdateInterval).optional(),\n});\n\n/**\n * Join Schema\n * Defines how this cube relates to others.\n */\nexport const CubeJoinSchema = z.object({\n name: z.string().describe('Target cube name'),\n relationship: z.enum(['one_to_one', 'one_to_many', 'many_to_one']).default('many_to_one'),\n sql: z.string().describe('Join condition (ON clause)'),\n});\n\n/**\n * Cube Schema\n * A logical data model representing a business entity or process for analysis.\n * Maps physical tables to business metrics and dimensions.\n */\nexport const CubeSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Cube name (snake_case)'),\n title: z.string().optional(),\n description: z.string().optional(),\n \n /** Physical Data Source */\n sql: z.string().describe('Base SQL statement or Table Name'),\n \n /** Semantic Definitions */\n measures: z.record(z.string(), MetricSchema).describe('Quantitative metrics'),\n dimensions: z.record(z.string(), DimensionSchema).describe('Qualitative attributes'),\n \n /** Relationships */\n joins: z.record(z.string(), CubeJoinSchema).optional(),\n \n /** Pre-aggregations / Caching */\n refreshKey: z.object({\n every: z.string().optional(), // e.g. \"1 hour\"\n sql: z.string().optional(), // SQL to check for data changes\n }).optional(),\n \n /** Access Control */\n public: z.boolean().default(false),\n});\n\n/**\n * Analytics Query Schema\n * The request format for the Analytics API.\n */\nexport const AnalyticsQuerySchema = z.object({\n cube: z.string().optional().describe('Target cube name (optional when provided externally, e.g. in API request wrapper)'),\n measures: z.array(z.string()).describe('List of metrics to calculate'),\n dimensions: z.array(z.string()).optional().describe('List of dimensions to group by'),\n \n filters: z.array(z.object({\n member: z.string().describe('Dimension or Measure'),\n operator: z.enum(['equals', 'notEquals', 'contains', 'notContains', 'gt', 'gte', 'lt', 'lte', 'set', 'notSet', 'inDateRange']),\n values: z.array(z.string()).optional(),\n })).optional(),\n \n timeDimensions: z.array(z.object({\n dimension: z.string(),\n granularity: TimeUpdateInterval.optional(),\n dateRange: z.union([\n z.string(), // \"Last 7 days\"\n z.array(z.string()) // [\"2023-01-01\", \"2023-01-31\"]\n ]).optional(),\n })).optional(),\n \n order: z.record(z.string(), z.enum(['asc', 'desc'])).optional(),\n \n limit: z.number().optional(),\n offset: z.number().optional(),\n \n timezone: z.string().optional().default('UTC'),\n});\n\nexport type Metric = z.infer;\nexport type Dimension = z.infer;\nexport type CubeJoin = z.infer;\nexport type Cube = z.infer;\nexport type AnalyticsQuery = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Feed Item Type\n * Unified activity types for the record timeline.\n * Covers comments, field changes, tasks, events, and system activities.\n */\nexport const FeedItemType = z.enum([\n 'comment',\n 'field_change',\n 'task',\n 'event',\n 'email',\n 'call',\n 'note',\n 'file',\n 'record_create',\n 'record_delete',\n 'approval',\n 'sharing',\n 'system',\n]);\nexport type FeedItemType = z.infer;\n\n/**\n * Mention Schema\n * Represents an @mention within comment body text.\n */\nexport const MentionSchema = z.object({\n type: z.enum(['user', 'team', 'record']).describe('Mention target type'),\n id: z.string().describe('Target ID'),\n name: z.string().describe('Display name for rendering'),\n offset: z.number().int().min(0).describe('Character offset in body text'),\n length: z.number().int().min(1).describe('Length of mention token in body text'),\n});\nexport type Mention = z.infer;\n\n/**\n * Field Change Entry Schema\n * Represents a single field-level change within a field_change feed item.\n */\nexport const FieldChangeEntrySchema = z.object({\n field: z.string().describe('Field machine name'),\n fieldLabel: z.string().optional().describe('Field display label'),\n oldValue: z.unknown().optional().describe('Previous value'),\n newValue: z.unknown().optional().describe('New value'),\n oldDisplayValue: z.string().optional().describe('Human-readable old value'),\n newDisplayValue: z.string().optional().describe('Human-readable new value'),\n});\nexport type FieldChangeEntry = z.infer;\n\n/**\n * Reaction Schema\n * Represents an emoji reaction on a feed item.\n */\nexport const ReactionSchema = z.object({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n userIds: z.array(z.string()).describe('Users who reacted'),\n count: z.number().int().min(1).describe('Total reaction count'),\n});\nexport type Reaction = z.infer;\n\n/**\n * Feed Actor Schema\n * Represents the actor who performed the action.\n */\nexport const FeedActorSchema = z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n avatarUrl: z.string().url().optional().describe('Actor avatar URL'),\n source: z.string().optional().describe('Source application (e.g., \"Omni\", \"API\", \"Studio\")'),\n});\nexport type FeedActor = z.infer;\n\n/**\n * Feed Item Visibility\n */\nexport const FeedVisibility = z.enum(['public', 'internal', 'private']);\nexport type FeedVisibility = z.infer;\n\n/**\n * Feed Item Schema\n * A single entry in the unified activity timeline.\n *\n * @example Comment\n * {\n * id: 'feed_001',\n * type: 'comment',\n * object: 'account',\n * recordId: 'rec_123',\n * body: 'Great progress! @jane.doe can you follow up?',\n * mentions: [{ type: 'user', id: 'user_123', name: 'Jane Doe', offset: 17, length: 9 }],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:30:00Z',\n * }\n *\n * @example Field Change\n * {\n * id: 'feed_002',\n * type: 'field_change',\n * object: 'account',\n * recordId: 'rec_123',\n * changes: [\n * { field: 'status', oldDisplayValue: 'New', newDisplayValue: 'Active' },\n * { field: 'region', oldDisplayValue: '', newDisplayValue: 'Asia-Pacific' },\n * ],\n * actor: { type: 'user', id: 'user_456', name: 'John Smith' },\n * createdAt: '2026-01-15T10:25:00Z',\n * }\n */\nexport const FeedItemSchema = z.object({\n /** Unique identifier */\n id: z.string().describe('Feed item ID'),\n\n /** Feed item type */\n type: FeedItemType.describe('Activity type'),\n\n /** Target record reference */\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID this feed item belongs to'),\n\n /** Actor (who performed the action) */\n actor: FeedActorSchema.describe('Who performed this action'),\n\n /** Content (for comments/notes) */\n body: z.string().optional().describe('Rich text body (Markdown supported)'),\n\n /** @Mentions */\n mentions: z.array(MentionSchema).optional().describe('Mentioned users/teams/records'),\n\n /** Field changes (for field_change type) */\n changes: z.array(FieldChangeEntrySchema).optional().describe('Field-level changes'),\n\n /** Reactions */\n reactions: z.array(ReactionSchema).optional().describe('Emoji reactions on this item'),\n\n /** Reply threading */\n parentId: z.string().optional().describe('Parent feed item ID for threaded replies'),\n replyCount: z.number().int().min(0).default(0).describe('Number of replies'),\n\n /** Pin / Star */\n pinned: z.boolean().default(false).describe('Whether the feed item is pinned to the top of the timeline'),\n pinnedAt: z.string().datetime().optional().describe('Timestamp when the item was pinned'),\n pinnedBy: z.string().optional().describe('User ID who pinned the item'),\n starred: z.boolean().default(false).describe('Whether the feed item is starred/bookmarked by the current user'),\n starredAt: z.string().datetime().optional().describe('Timestamp when the item was starred'),\n\n /** Visibility */\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public (all users), internal (team only), private (author + mentioned)'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n editedAt: z.string().datetime().optional().describe('When comment was last edited'),\n isEdited: z.boolean().default(false).describe('Whether comment has been edited'),\n});\nexport type FeedItem = z.infer;\n\n/**\n * Feed Filter Mode\n * Controls which feed item types to display in the timeline.\n */\nexport const FeedFilterMode = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\nexport type FeedFilterMode = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Subscription Event Type\n * Event types that can be subscribed to for record-level notifications.\n */\nexport const SubscriptionEventType = z.enum([\n 'comment',\n 'mention',\n 'field_change',\n 'task',\n 'approval',\n 'all',\n]);\nexport type SubscriptionEventType = z.infer;\n\n/**\n * Notification Channel\n * Delivery channels for record subscription notifications.\n */\nexport const NotificationChannel = z.enum([\n 'in_app',\n 'email',\n 'push',\n 'slack',\n]);\nexport type NotificationChannel = z.infer;\n\n/**\n * Record Subscription Schema\n * Defines a user's subscription to record-level notifications.\n * Enables Airtable-style bell icon for record change notifications.\n */\nexport const RecordSubscriptionSchema = z.object({\n /** Target */\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n\n /** Subscriber */\n userId: z.string().describe('Subscribing user ID'),\n\n /** Events to subscribe to */\n events: z.array(SubscriptionEventType)\n .default(['all'])\n .describe('Event types to receive notifications for'),\n\n /** Notification channels */\n channels: z.array(NotificationChannel)\n .default(['in_app'])\n .describe('Notification delivery channels'),\n\n /** Active */\n active: z.boolean().default(true).describe('Whether the subscription is active'),\n\n /** Timestamps */\n createdAt: z.string().datetime().describe('Subscription creation timestamp'),\n});\nexport type RecordSubscription = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Turso Multi-Tenant Router Schema\n *\n * Defines the configuration for Turso DB-per-Tenant architectures where each\n * tenant receives an independent Turso/libSQL database. The router resolves\n * the correct database URL and auth token per request based on the current\n * tenant context.\n *\n * Architecture: Shared Compute + Isolated Data\n * - Serverless functions are shared across tenants\n * - Each tenant has a physically isolated Turso database\n * - Turso Platform API manages database lifecycle (create/delete/suspend)\n *\n * @see https://docs.turso.tech/features/multi-db-schemas\n */\n\n// ==========================================================================\n// 1. Tenant Resolver Strategy\n// ==========================================================================\n\n/**\n * Strategy for resolving which tenant database to connect to.\n */\nexport const TenantResolverStrategySchema = z.enum([\n 'header', // Resolve from X-Tenant-ID request header\n 'subdomain', // Resolve from subdomain (e.g., acme.app.com → acme)\n 'path', // Resolve from URL path segment (e.g., /api/acme/...)\n 'token', // Resolve from JWT claim (e.g., tenant_id in access token)\n 'lookup', // Resolve from control-plane database lookup\n]).describe('Strategy for resolving tenant identity from request context');\n\nexport type TenantResolverStrategy = z.infer;\n\n// ==========================================================================\n// 2. Turso Group Configuration\n// ==========================================================================\n\n/**\n * Turso Database Group Configuration.\n * Groups allow databases to share schema and be managed as a unit.\n * All databases in a group are deployed to the same set of locations.\n *\n * @see https://docs.turso.tech/features/multi-db-schemas\n */\nexport const TursoGroupSchema = z.object({\n /**\n * Group name identifier.\n * Used to reference the group when creating new tenant databases.\n */\n name: z.string().min(1).describe('Turso database group name'),\n\n /**\n * Primary location for the group (Turso region code).\n * Example: 'iad' (US East), 'lhr' (London), 'nrt' (Tokyo)\n */\n primaryLocation: z.string().min(2).describe('Primary Turso region code (e.g., iad, lhr, nrt)'),\n\n /**\n * Additional replica locations for read performance.\n * Databases in this group will have read replicas in these regions.\n */\n replicaLocations: z.array(z.string().min(2)).default([]).describe('Additional replica region codes'),\n\n /**\n * Schema database name within the group.\n * When using multi-db schemas, this is the \"parent\" database\n * whose schema is shared by all child (tenant) databases.\n */\n schemaDatabase: z.string().optional().describe('Schema database name for multi-db schemas'),\n}).describe('Turso database group configuration');\n\nexport type TursoGroup = z.infer;\n\n// ==========================================================================\n// 3. Tenant Database Lifecycle Hooks\n// ==========================================================================\n\n/**\n * Database Lifecycle Hook Schema.\n * Defines what happens at each tenant lifecycle event.\n */\nexport const TenantDatabaseLifecycleSchema = z.object({\n /**\n * Hook executed when a new tenant is created.\n * Defines how the tenant database is provisioned.\n */\n onTenantCreate: z.object({\n /** Whether to automatically create a Turso database */\n autoCreate: z.boolean().default(true).describe('Auto-create database on tenant registration'),\n\n /** Database group to create the database in */\n group: z.string().optional().describe('Turso group for the new database'),\n\n /** Whether to apply schema from the group schema database */\n applyGroupSchema: z.boolean().default(true).describe('Apply shared schema from group'),\n\n /** Seed data to populate on creation */\n seedData: z.boolean().default(false).describe('Populate seed data on creation'),\n }).describe('Tenant creation hook'),\n\n /**\n * Hook executed when a tenant is deleted/destroyed.\n */\n onTenantDelete: z.object({\n /** Whether to destroy the database immediately or schedule for deletion */\n immediate: z.boolean().default(false).describe('Destroy database immediately'),\n\n /** Grace period in hours before permanent deletion (soft-delete) */\n gracePeriodHours: z.number().int().min(0).default(72).describe('Grace period before permanent deletion'),\n\n /** Whether to create a final backup before deletion */\n createBackup: z.boolean().default(true).describe('Create backup before deletion'),\n }).describe('Tenant deletion hook'),\n\n /**\n * Hook executed when a tenant is suspended (e.g., unpaid, policy violation).\n */\n onTenantSuspend: z.object({\n /** Whether to revoke auth tokens on suspension */\n revokeTokens: z.boolean().default(true).describe('Revoke auth tokens on suspension'),\n\n /** Whether to set database to read-only mode */\n readOnly: z.boolean().default(true).describe('Set database to read-only on suspension'),\n }).describe('Tenant suspension hook'),\n}).describe('Tenant database lifecycle hooks');\n\nexport type TenantDatabaseLifecycle = z.infer;\n\n// ==========================================================================\n// 4. Multi-Tenant Router Configuration\n// ==========================================================================\n\n/**\n * Turso Multi-Tenant Configuration Schema.\n *\n * Configures the DB-per-Tenant router that resolves the correct Turso\n * database for each request. Works with the Turso Platform API to manage\n * database lifecycle.\n *\n * @example\n * ```ts\n * const config = TursoMultiTenantConfigSchema.parse({\n * organizationSlug: 'myorg',\n * urlTemplate: 'libsql://{tenant_id}-myorg.turso.io',\n * groupAuthToken: process.env.TURSO_GROUP_AUTH_TOKEN,\n * tenantResolverStrategy: 'token',\n * group: {\n * name: 'production',\n * primaryLocation: 'iad',\n * replicaLocations: ['lhr', 'nrt'],\n * schemaDatabase: 'schema-db',\n * },\n * lifecycle: {\n * onTenantCreate: { autoCreate: true, applyGroupSchema: true },\n * onTenantDelete: { gracePeriodHours: 168 },\n * onTenantSuspend: { revokeTokens: true },\n * },\n * });\n * ```\n */\nexport const TursoMultiTenantConfigSchema = z.object({\n /**\n * Turso organization slug.\n * Used for Platform API calls and URL construction.\n */\n organizationSlug: z.string().min(1).describe('Turso organization slug'),\n\n /**\n * URL template for constructing tenant database URLs.\n * Use `{tenant_id}` as placeholder for the tenant identifier.\n *\n * Example: 'libsql://{tenant_id}-myorg.turso.io'\n */\n urlTemplate: z.string().min(1).describe('URL template with {tenant_id} placeholder'),\n\n /**\n * Group-level auth token for Turso Platform API operations.\n * Used for database creation, deletion, and management.\n * This token has full access to all databases in the group.\n */\n groupAuthToken: z.string().min(1).describe('Group-level auth token for platform operations'),\n\n /**\n * Strategy for resolving tenant identity from the request context.\n */\n tenantResolverStrategy: TenantResolverStrategySchema.default('token'),\n\n /**\n * Turso database group configuration.\n */\n group: TursoGroupSchema.optional().describe('Database group configuration'),\n\n /**\n * Lifecycle hooks for tenant database management.\n */\n lifecycle: TenantDatabaseLifecycleSchema.optional().describe('Lifecycle hooks'),\n\n /**\n * Maximum number of cached tenant database connections.\n * Connections are evicted using LRU strategy when the limit is reached.\n */\n maxCachedConnections: z.number().int().min(1).default(100).describe('Max cached tenant connections (LRU)'),\n\n /**\n * Connection cache TTL in seconds.\n * Cached connections are refreshed after this period.\n */\n connectionCacheTTL: z.number().int().min(0).default(300).describe('Connection cache TTL in seconds'),\n}).describe('Turso multi-tenant router configuration');\n\nexport type TursoMultiTenantConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Permission Protocol Exports\n * \n * Fine-grained Access Control\n * - Permission Sets (CRUD + Field-Level Security)\n * - Sharing Rules (Record Ownership)\n * - Territory Management (Geographic/Hierarchical)\n * - Row-Level Security (RLS - PostgreSQL-style)\n */\n\nexport * from './permission.zod';\nexport * from './sharing.zod';\nexport * from './territory.zod';\nexport * from './rls.zod';\nexport * from './policy.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Row-Level Security (RLS) Protocol\n * \n * Implements fine-grained record-level access control inspired by PostgreSQL RLS\n * and Salesforce Criteria-Based Sharing Rules.\n * \n * ## Overview\n * \n * Row-Level Security (RLS) allows you to control which rows users can access\n * in database tables based on their identity and role. Unlike object-level\n * permissions (CRUD), RLS provides record-level filtering.\n * \n * ## Use Cases\n * \n * 1. **Multi-Tenant Data Isolation**\n * - Users only see records from their organization\n * - `using: \"tenant_id = current_user.tenant_id\"`\n * \n * 2. **Ownership-Based Access**\n * - Users only see records they own\n * - `using: \"owner_id = current_user.id\"`\n * \n * 3. **Department-Based Access**\n * - Users only see records from their department\n * - `using: \"department = current_user.department\"`\n * \n * 4. **Regional Access Control**\n * - Sales reps only see accounts in their territory\n * - `using: \"region IN (current_user.assigned_regions)\"`\n * \n * 5. **Time-Based Access**\n * - Users can only access active records\n * - `using: \"status = 'active' AND expiry_date > NOW()\"`\n * \n * ## PostgreSQL RLS Comparison\n * \n * PostgreSQL RLS Example:\n * ```sql\n * CREATE POLICY tenant_isolation ON accounts\n * FOR SELECT\n * USING (tenant_id = current_setting('app.current_tenant_id')::uuid);\n * \n * CREATE POLICY account_insert ON accounts\n * FOR INSERT\n * WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);\n * ```\n * \n * ObjectStack RLS Equivalent:\n * ```typescript\n * {\n * name: 'tenant_isolation',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id'\n * }\n * ```\n * \n * ## Salesforce Sharing Rules Comparison\n * \n * Salesforce uses \"Sharing Rules\" and \"Role Hierarchy\" for record-level access.\n * ObjectStack RLS provides similar functionality with more flexibility.\n * \n * Salesforce:\n * - Criteria-Based Sharing: Share records matching criteria with users/roles\n * - Owner-Based Sharing: Share records based on owner's role\n * - Manual Sharing: Individual record sharing\n * \n * ObjectStack RLS:\n * - More flexible formula-based conditions\n * - Direct SQL-like syntax\n * - Supports complex logic with AND/OR/NOT\n * \n * ## Best Practices\n * \n * 1. **Always Define SELECT Policy**: Control what users can view\n * 2. **Define INSERT/UPDATE CHECK Policies**: Prevent data leakage\n * 3. **Use Role-Based Policies**: Apply different rules to different roles\n * 4. **Test Thoroughly**: RLS can have complex interactions\n * 5. **Monitor Performance**: Complex RLS policies can impact query performance\n * \n * ## Security Considerations\n * \n * 1. **Defense in Depth**: RLS is one layer; use with object permissions\n * 2. **Default Deny**: If no policy matches, access is denied\n * 3. **Policy Precedence**: More permissive policy wins (OR logic)\n * 4. **Context Variables**: Ensure current_user context is always set\n * \n * @see https://www.postgresql.org/docs/current/ddl-rowsecurity.html\n * @see https://help.salesforce.com/s/articleView?id=sf.security_sharing_rules.htm\n */\n\n/**\n * RLS Operation Enum\n * Specifies which database operation this policy applies to.\n * \n * - **select**: Controls which rows can be read (SELECT queries)\n * - **insert**: Controls which rows can be inserted (INSERT statements)\n * - **update**: Controls which rows can be updated (UPDATE statements)\n * - **delete**: Controls which rows can be deleted (DELETE statements)\n * - **all**: Shorthand for all operations (equivalent to defining 4 separate policies)\n */\nexport const RLSOperation = z.enum(['select', 'insert', 'update', 'delete', 'all']);\n\nexport type RLSOperation = z.infer;\n\n/**\n * Row-Level Security Policy Schema\n * \n * Defines a single RLS policy that filters records based on conditions.\n * Multiple policies can be defined for the same object, and they are\n * combined with OR logic (union of results).\n * \n * @example Multi-Tenant Isolation\n * ```typescript\n * {\n * name: 'tenant_isolation',\n * label: 'Multi-Tenant Data Isolation',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id',\n * enabled: true\n * }\n * ```\n * \n * @example Owner-Based Access\n * ```typescript\n * {\n * name: 'owner_access',\n * label: 'Users Can View Their Own Records',\n * object: 'opportunity',\n * operation: 'select',\n * using: 'owner_id = current_user.id',\n * enabled: true\n * }\n * ```\n * \n * @example Manager Can View Team Records\n * ```typescript\n * {\n * name: 'manager_team_access',\n * label: 'Managers Can View Team Records',\n * object: 'task',\n * operation: 'select',\n * using: 'assigned_to_id IN (SELECT id FROM users WHERE manager_id = current_user.id)',\n * roles: ['manager', 'director'],\n * enabled: true\n * }\n * ```\n * \n * @example Prevent Cross-Tenant Data Insertion\n * ```typescript\n * {\n * name: 'tenant_insert_check',\n * label: 'Prevent Cross-Tenant Data Creation',\n * object: 'account',\n * operation: 'insert',\n * check: 'tenant_id = current_user.tenant_id',\n * enabled: true\n * }\n * ```\n * \n * @example Regional Sales Access\n * ```typescript\n * {\n * name: 'regional_sales_access',\n * label: 'Sales Reps Access Regional Accounts',\n * object: 'account',\n * operation: 'select',\n * using: 'region = current_user.region OR region IS NULL',\n * roles: ['sales_rep'],\n * enabled: true\n * }\n * ```\n * \n * @example Time-Based Access Control\n * ```typescript\n * {\n * name: 'active_records_only',\n * label: 'Users Only Access Active Records',\n * object: 'contract',\n * operation: 'select',\n * using: 'status = \"active\" AND start_date <= NOW() AND end_date >= NOW()',\n * enabled: true\n * }\n * ```\n * \n * @example Hierarchical Access (Role-Based)\n * ```typescript\n * {\n * name: 'executive_full_access',\n * label: 'Executives See All Records',\n * object: 'account',\n * operation: 'all',\n * using: '1 = 1', // Always true - see everything\n * roles: ['ceo', 'cfo', 'cto'],\n * enabled: true\n * }\n * ```\n */\nexport const RowLevelSecurityPolicySchema = z.object({\n /**\n * Unique identifier for this policy.\n * Must be unique within the object.\n * Use snake_case following ObjectStack naming conventions.\n * \n * @example \"tenant_isolation\", \"owner_access\", \"manager_team_view\"\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Policy unique identifier (snake_case)'),\n\n /**\n * Human-readable label for the policy.\n * Used in admin UI and logs.\n * \n * @example \"Multi-Tenant Data Isolation\", \"Owner-Based Access\"\n */\n label: z.string()\n .optional()\n .describe('Human-readable policy label'),\n\n /**\n * Description explaining what this policy does and why.\n * Helps with governance and compliance.\n * \n * @example \"Ensures users can only access records from their own tenant organization\"\n */\n description: z.string()\n .optional()\n .describe('Policy description and business justification'),\n\n /**\n * Target object (table) this policy applies to.\n * Must reference a valid ObjectStack object name.\n * \n * @example \"account\", \"opportunity\", \"contact\", \"custom_object\"\n */\n object: z.string()\n .describe('Target object name'),\n\n /**\n * Database operation(s) this policy applies to.\n * \n * - **select**: Controls read access (SELECT queries)\n * - **insert**: Controls insert access (INSERT statements)\n * - **update**: Controls update access (UPDATE statements)\n * - **delete**: Controls delete access (DELETE statements)\n * - **all**: Applies to all operations\n * \n * @example \"select\" - Most common, controls what users can view\n * @example \"all\" - Apply same rule to all operations\n */\n operation: RLSOperation\n .describe('Database operation this policy applies to'),\n\n /**\n * USING clause - Filter condition for SELECT/UPDATE/DELETE.\n * \n * This is a SQL-like expression evaluated for each row.\n * Only rows where this expression returns TRUE are accessible.\n * \n * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed).\n * For SELECT/UPDATE/DELETE operations, USING is required.\n * \n * **Security Note**: RLS conditions are executed at the database level with\n * parameterized queries. The implementation must use prepared statements\n * to prevent SQL injection. Never concatenate user input directly into\n * RLS conditions.\n * \n * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations\n * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain\n * semantic equivalence.\n * \n * Available context variables:\n * - `current_user.id` - Current user's ID\n * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext)\n * - `current_user.role` - Current user's role\n * - `current_user.department` - Current user's department\n * - `current_user.*` - Any custom user field\n * - `NOW()` - Current timestamp\n * - `CURRENT_DATE` - Current date\n * - `CURRENT_TIME` - Current time\n * \n * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`),\n * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`).\n * Implementations must handle this mapping.\n * \n * Supported operators:\n * - Comparison: =, !=, <, >, <=, >=, <> (not equal)\n * - Logical: AND, OR, NOT\n * - NULL checks: IS NULL, IS NOT NULL\n * - Set operations: IN, NOT IN\n * - String: LIKE, NOT LIKE, ILIKE (case-insensitive)\n * - Pattern matching: ~ (regex), !~ (not regex)\n * - Subqueries: (SELECT ...)\n * - Array operations: ANY, ALL\n * \n * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE)\n * \n * @example \"tenant_id = current_user.tenant_id\"\n * @example \"owner_id = current_user.id OR created_by = current_user.id\"\n * @example \"department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)\"\n * @example \"status = 'active' AND expiry_date > NOW()\"\n */\n using: z.string()\n .optional()\n .describe('Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies.'),\n\n /**\n * CHECK clause - Validation for INSERT/UPDATE operations.\n * \n * Similar to USING but applies to new/modified rows.\n * Prevents users from creating/updating rows they wouldn't be able to see.\n * \n * **Default Behavior**: If not specified, implementations should use the\n * USING clause as the CHECK clause. This ensures data integrity by preventing\n * users from creating records they cannot view.\n * \n * Use cases:\n * - Prevent cross-tenant data creation\n * - Enforce mandatory field values\n * - Validate data integrity rules\n * - Restrict certain operations (e.g., only allow creating \"draft\" status)\n * \n * @example \"tenant_id = current_user.tenant_id\"\n * @example \"status IN ('draft', 'pending')\" - Only allow certain statuses\n * @example \"created_by = current_user.id\" - Must be the creator\n */\n check: z.string()\n .optional()\n .describe('Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)'),\n\n /**\n * Restrict this policy to specific roles.\n * If specified, only users with these roles will have this policy applied.\n * If omitted, policy applies to all users (except those with bypassRLS permission).\n * \n * Role names must match defined roles in the system.\n * \n * @example [\"sales_rep\", \"account_manager\"]\n * @example [\"employee\"] - Apply to all employees\n * @example [\"guest\"] - Special restrictions for guests\n */\n roles: z.array(z.string())\n .optional()\n .describe('Roles this policy applies to (omit for all roles)'),\n\n /**\n * Whether this policy is currently active.\n * Disabled policies are not evaluated.\n * Useful for temporary policy changes without deletion.\n * \n * @default true\n */\n enabled: z.boolean()\n .default(true)\n .describe('Whether this policy is active'),\n\n /**\n * Policy priority for conflict resolution.\n * Higher numbers = higher priority.\n * When multiple policies apply, the most permissive wins (OR logic).\n * Priority is only used for ordering evaluation (performance).\n * \n * @default 0\n */\n priority: z.number()\n .int()\n .default(0)\n .describe('Policy evaluation priority (higher = evaluated first)'),\n\n /**\n * Tags for policy categorization and reporting.\n * Useful for governance, compliance, and auditing.\n * \n * @example [\"compliance\", \"gdpr\", \"pci\"]\n * @example [\"multi-tenant\", \"security\"]\n */\n tags: z.array(z.string())\n .optional()\n .describe('Policy categorization tags'),\n}).superRefine((data, ctx) => {\n // Ensure at least one of USING or CHECK is provided\n if (!data.using && !data.check) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'At least one of \"using\" or \"check\" must be specified. For SELECT/UPDATE/DELETE operations, provide \"using\". For INSERT operations, provide \"check\".',\n });\n }\n \n // For non-insert operations, USING should typically be present\n // This is a soft warning through documentation, not enforced here\n // since 'all' and mixed operation types are valid\n});\n\n/**\n * RLS Audit Event Schema\n * \n * Records a single RLS policy evaluation event for compliance and debugging.\n */\nexport const RLSAuditEventSchema = z.object({\n /** ISO 8601 timestamp of the evaluation */\n timestamp: z.string()\n .describe('ISO 8601 timestamp of the evaluation'),\n\n /** ID of the user whose access was evaluated */\n userId: z.string()\n .describe('User ID whose access was evaluated'),\n\n /** Database operation being performed */\n operation: z.enum(['select', 'insert', 'update', 'delete'])\n .describe('Database operation being performed'),\n\n /** Target object (table) name */\n object: z.string()\n .describe('Target object name'),\n\n /** Name of the RLS policy evaluated */\n policyName: z.string()\n .describe('Name of the RLS policy evaluated'),\n\n /** Whether access was granted */\n granted: z.boolean()\n .describe('Whether access was granted'),\n\n /** Time taken to evaluate the policy in milliseconds */\n evaluationDurationMs: z.number()\n .describe('Policy evaluation duration in milliseconds'),\n\n /** Which USING/CHECK clause matched */\n matchedCondition: z.string()\n .optional()\n .describe('Which USING/CHECK clause matched'),\n\n /** Number of rows affected by the operation */\n rowCount: z.number()\n .optional()\n .describe('Number of rows affected'),\n\n /** Additional metadata for the audit event */\n metadata: z.record(z.string(), z.unknown())\n .optional()\n .describe('Additional audit event metadata'),\n});\n\nexport type RLSAuditEvent = z.infer;\n\n/**\n * RLS Audit Configuration Schema\n * \n * Controls how RLS policy evaluations are logged and monitored.\n */\nexport const RLSAuditConfigSchema = z.object({\n /** Enable RLS audit logging */\n enabled: z.boolean()\n .describe('Enable RLS audit logging'),\n\n /** Which evaluations to log */\n logLevel: z.enum(['all', 'denied_only', 'granted_only', 'none'])\n .describe('Which evaluations to log'),\n\n /** Where to send audit logs */\n destination: z.enum(['system_log', 'audit_trail', 'external'])\n .describe('Audit log destination'),\n\n /** Sampling rate for high-traffic environments (0-1) */\n sampleRate: z.number()\n .min(0)\n .max(1)\n .describe('Sampling rate (0-1) for high-traffic environments'),\n\n /** Number of days to retain audit logs */\n retentionDays: z.number()\n .int()\n .default(90)\n .describe('Audit log retention period in days'),\n\n /** Whether to include row data in audit logs (security-sensitive) */\n includeRowData: z.boolean()\n .default(false)\n .describe('Include row data in audit logs (security-sensitive)'),\n\n /** Alert when access is denied */\n alertOnDenied: z.boolean()\n .default(true)\n .describe('Send alerts when access is denied'),\n});\n\nexport type RLSAuditConfig = z.infer;\n\n/**\n * RLS Configuration Schema\n * \n * Global configuration for the Row-Level Security system.\n * Defines how RLS is enforced across the entire platform.\n */\nexport const RLSConfigSchema = z.object({\n /**\n * Global RLS enable/disable flag.\n * When false, all RLS policies are ignored (use with caution!).\n * \n * @default true\n */\n enabled: z.boolean()\n .default(true)\n .describe('Enable RLS enforcement globally'),\n\n /**\n * Default behavior when no policies match.\n * \n * - **deny**: Deny access (secure default)\n * - **allow**: Allow access (permissive mode, not recommended)\n * \n * @default \"deny\"\n */\n defaultPolicy: z.enum(['deny', 'allow'])\n .default('deny')\n .describe('Default action when no policies match'),\n\n /**\n * Whether to allow superusers to bypass RLS.\n * Superusers include system administrators and service accounts.\n * \n * @default true\n */\n allowSuperuserBypass: z.boolean()\n .default(true)\n .describe('Allow superusers to bypass RLS'),\n\n /**\n * List of roles that can bypass RLS.\n * Users with these roles see all records regardless of policies.\n * \n * @example [\"system_admin\", \"data_auditor\"]\n */\n bypassRoles: z.array(z.string())\n .optional()\n .describe('Roles that bypass RLS (see all data)'),\n\n /**\n * Whether to log RLS policy evaluations.\n * Useful for debugging and auditing.\n * Can impact performance if enabled globally.\n * \n * @default false\n */\n logEvaluations: z.boolean()\n .default(false)\n .describe('Log RLS policy evaluations for debugging'),\n\n /**\n * Cache RLS policy evaluation results.\n * Can improve performance for frequently accessed records.\n * Cache is invalidated when policies change or user context changes.\n * \n * @default true\n */\n cacheResults: z.boolean()\n .default(true)\n .describe('Cache RLS evaluation results'),\n\n /**\n * Cache TTL in seconds.\n * How long to cache RLS evaluation results.\n * \n * @default 300 (5 minutes)\n */\n cacheTtlSeconds: z.number()\n .int()\n .positive()\n .default(300)\n .describe('Cache TTL in seconds'),\n\n /**\n * Performance optimization: Pre-fetch user context.\n * Load user context once per request instead of per-query.\n * \n * @default true\n */\n prefetchUserContext: z.boolean()\n .default(true)\n .describe('Pre-fetch user context for performance'),\n\n /**\n * Audit logging configuration for RLS evaluations.\n */\n audit: RLSAuditConfigSchema\n .optional()\n .describe('RLS audit logging configuration'),\n});\n\n/**\n * User Context Schema\n * \n * Represents the current user's context for RLS evaluation.\n * This data is used to evaluate USING and CHECK clauses.\n */\nexport const RLSUserContextSchema = z.object({\n /**\n * User ID\n */\n id: z.string()\n .describe('User ID'),\n\n /**\n * User email\n */\n email: z.string()\n .email()\n .optional()\n .describe('User email'),\n\n /**\n * Tenant/Organization ID\n */\n tenantId: z.string()\n .optional()\n .describe('Tenant/Organization ID'),\n\n /**\n * User role(s)\n */\n role: z.union([\n z.string(),\n z.array(z.string()),\n ])\n .optional()\n .describe('User role(s)'),\n\n /**\n * User department\n */\n department: z.string()\n .optional()\n .describe('User department'),\n\n /**\n * Additional custom attributes\n * Can include any custom user fields for RLS evaluation\n */\n attributes: z.record(z.string(), z.unknown())\n .optional()\n .describe('Additional custom user attributes'),\n});\n\n/**\n * RLS Policy Evaluation Result\n * \n * Result of evaluating an RLS policy for a specific record.\n * Used for debugging and audit logging.\n */\nexport const RLSEvaluationResultSchema = z.object({\n /**\n * Policy name that was evaluated\n */\n policyName: z.string()\n .describe('Policy name'),\n\n /**\n * Whether access was granted\n */\n granted: z.boolean()\n .describe('Whether access was granted'),\n\n /**\n * Evaluation duration in milliseconds\n */\n durationMs: z.number()\n .optional()\n .describe('Evaluation duration in milliseconds'),\n\n /**\n * Error message if evaluation failed\n */\n error: z.string()\n .optional()\n .describe('Error message if evaluation failed'),\n\n /**\n * Evaluated USING clause result\n */\n usingResult: z.boolean()\n .optional()\n .describe('USING clause evaluation result'),\n\n /**\n * Evaluated CHECK clause result (for INSERT/UPDATE)\n */\n checkResult: z.boolean()\n .optional()\n .describe('CHECK clause evaluation result'),\n});\n\n/**\n * Type exports\n */\nexport type RowLevelSecurityPolicy = z.infer;\nexport type RLSConfig = z.infer;\nexport type RLSUserContext = z.infer;\nexport type RLSEvaluationResult = z.infer;\n\n/**\n * Helper factory for creating RLS policies\n */\nexport const RLS = {\n /**\n * Create a simple owner-based policy\n */\n ownerPolicy: (object: string, ownerField: string = 'owner_id'): RowLevelSecurityPolicy => ({\n name: `${object}_owner_access`,\n label: `Owner Access for ${object}`,\n object,\n operation: 'all',\n using: `${ownerField} = current_user.id`,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a tenant isolation policy\n */\n tenantPolicy: (object: string, tenantField: string = 'tenant_id'): RowLevelSecurityPolicy => ({\n name: `${object}_tenant_isolation`,\n label: `Tenant Isolation for ${object}`,\n object,\n operation: 'all',\n using: `${tenantField} = current_user.tenant_id`,\n check: `${tenantField} = current_user.tenant_id`,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a role-based policy\n */\n rolePolicy: (object: string, roles: string[], condition: string): RowLevelSecurityPolicy => ({\n name: `${object}_${roles.join('_')}_access`,\n label: `${roles.join(', ')} Access for ${object}`,\n object,\n operation: 'select',\n using: condition,\n roles,\n enabled: true,\n priority: 0,\n }),\n\n /**\n * Create a permissive policy (allow all for specific roles)\n */\n allowAllPolicy: (object: string, roles: string[]): RowLevelSecurityPolicy => ({\n name: `${object}_${roles.join('_')}_full_access`,\n label: `Full Access for ${roles.join(', ')}`,\n object,\n operation: 'all',\n using: '1 = 1', // Always true\n roles,\n enabled: true,\n priority: 0,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { RowLevelSecurityPolicySchema } from './rls.zod';\n\n/**\n * Entity (Object) Level Permissions\n * Defines CRUD + VAMA (View All / Modify All) + Lifecycle access.\n * \n * Refined with enterprise data lifecycle controls:\n * - Transfer (Ownership change)\n * - Restore (Soft delete recovery)\n * - Purge (Hard delete / Compliance)\n */\nexport const ObjectPermissionSchema = z.object({\n /** C: Create */\n allowCreate: z.boolean().default(false).describe('Create permission'),\n /** R: Read (Owned records or Shared records) */\n allowRead: z.boolean().default(false).describe('Read permission'),\n /** U: Edit (Owned records or Shared records) */\n allowEdit: z.boolean().default(false).describe('Edit permission'),\n /** D: Delete (Owned records or Shared records) */\n allowDelete: z.boolean().default(false).describe('Delete permission'),\n \n /** Lifecycle Operations */\n allowTransfer: z.boolean().default(false).describe('Change record ownership'),\n allowRestore: z.boolean().default(false).describe('Restore from trash (Undelete)'),\n allowPurge: z.boolean().default(false).describe('Permanently delete (Hard Delete/GDPR)'),\n\n /** \n * View All Records: Super-user read access. \n * Bypasses Sharing Rules and Ownership checks.\n * Equivalent to Microsoft Dataverse \"Organization\" level read access.\n */\n viewAllRecords: z.boolean().default(false).describe('View All Data (Bypass Sharing)'),\n \n /** \n * Modify All Records: Super-user write access. \n * Bypasses Sharing Rules and Ownership checks.\n * Equivalent to Microsoft Dataverse \"Organization\" level write access.\n */\n modifyAllRecords: z.boolean().default(false).describe('Modify All Data (Bypass Sharing)'),\n});\n\n/**\n * Field Level Security (FLS)\n */\nexport const FieldPermissionSchema = z.object({\n /** Can see this field */\n readable: z.boolean().default(true).describe('Field read access'),\n /** Can edit this field */\n editable: z.boolean().default(false).describe('Field edit access'),\n});\n\n/**\n * Permission Set Schema\n * Defines a collection of permissions that can be assigned to users.\n * \n * DIFFERENTIATION:\n * - Profile: The ONE primary functional definition of a user (e.g. Standard User).\n * - Permission Set: Add-on capabilities assigned to users (e.g. Export Reports).\n * - Role: (Defined in src/system/role.zod.ts) Defines data visibility hierarchy.\n * \n * **NAMING CONVENTION:**\n * Permission set names MUST be lowercase snake_case to prevent security issues.\n * \n * @example Good permission set names\n * - 'read_only'\n * - 'system_admin'\n * - 'standard_user'\n * - 'api_access'\n * \n * @example Bad permission set names (will be rejected)\n * - 'ReadOnly' (camelCase)\n * - 'SystemAdmin' (mixed case)\n * - 'Read Only' (spaces)\n */\nexport const PermissionSetSchema = z.object({\n /** Unique permission set name */\n name: SnakeCaseIdentifierSchema.describe('Permission set unique name (lowercase snake_case)'),\n \n /** Display label */\n label: z.string().optional().describe('Display label'),\n \n /** Is this a Profile? (Base set for a user) */\n isProfile: z.boolean().default(false).describe('Whether this is a user profile'),\n \n /** Object Permissions Map: -> permissions */\n objects: z.record(z.string(), ObjectPermissionSchema).describe('Entity permissions'),\n \n /** Field Permissions Map: . -> permissions */\n fields: z.record(z.string(), FieldPermissionSchema).optional().describe('Field level security'),\n \n /** System permissions (e.g., \"manage_users\") */\n systemPermissions: z.array(z.string()).optional().describe('System level capabilities'),\n \n /**\n * Tab/App Visibility Permissions (Salesforce Pattern)\n * Controls which app tabs are visible, hidden, or set as default for this permission set.\n * \n * @example\n * ```typescript\n * tabPermissions: {\n * 'app_crm': 'visible',\n * 'app_admin': 'hidden',\n * 'app_sales': 'default_on'\n * }\n * ```\n */\n tabPermissions: z.record(z.string(), z.enum(['visible', 'hidden', 'default_on', 'default_off'])).optional()\n .describe('App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)'),\n \n /** \n * Row-Level Security Rules\n * \n * Row-level security policies that filter records based on user context.\n * These rules are applied in addition to object-level permissions.\n * \n * Uses the canonical RLS protocol from rls.zod.ts for comprehensive\n * row-level security features including PostgreSQL-style USING and CHECK clauses.\n * \n * @see {@link RowLevelSecurityPolicySchema} for full RLS specification\n * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation\n * \n * @example Multi-tenant isolation\n * ```typescript\n * rls: [{\n * name: 'tenant_filter',\n * object: 'account',\n * operation: 'select',\n * using: 'tenant_id = current_user.tenant_id'\n * }]\n * ```\n */\n rowLevelSecurity: z.array(RowLevelSecurityPolicySchema).optional()\n .describe('Row-level security policies (see rls.zod.ts for full spec)'),\n \n /**\n * Context-Based Access Control Variables\n * \n * Custom context variables that can be referenced in RLS rules.\n * These variables are evaluated at runtime based on the user's session.\n * \n * Common context variables:\n * - `current_user.id` - Current user ID\n * - `current_user.tenant_id` - User's tenant/organization ID\n * - `current_user.department` - User's department\n * - `current_user.role` - User's role\n * - `current_user.region` - User's geographic region\n * \n * @example Custom context\n * ```typescript\n * contextVariables: {\n * allowed_regions: ['US', 'EU'],\n * access_level: 2,\n * custom_attribute: 'value'\n * }\n * ```\n */\n contextVariables: z.record(z.string(), z.unknown()).optional().describe('Context variables for RLS evaluation'),\n});\n\nexport type PermissionSet = z.infer;\nexport type ObjectPermission = z.infer;\nexport type FieldPermission = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Organization-Wide Defaults (OWD)\n * The baseline security posture for an object.\n */\nexport const OWDModel = z.enum([\n 'private', // Only owner can see\n 'public_read', // Everyone can see, owner can edit\n 'public_read_write', // Everyone can see and edit\n 'controlled_by_parent' // Access derived from parent record (Master-Detail)\n]);\n\n/**\n * Sharing Rule Type\n * How is the data shared?\n */\nexport const SharingRuleType = z.enum([\n 'owner', // Based on record ownership (Role Hierarchy)\n 'criteria', // Based on field values (e.g. Status = 'Open')\n]);\n\n/**\n * Sharing Level\n * What access is granted?\n */\nexport const SharingLevel = z.enum([\n 'read', // Read Only\n 'edit', // Read / Write\n 'full' // Full Access (Transfer, Share, Delete)\n]);\n\n/**\n * Recipient Type \n * Who receives the access?\n */\nexport const ShareRecipientType = z.enum([\n 'user',\n 'group',\n 'role',\n 'role_and_subordinates',\n 'guest' // for public sharing\n]);\n\n/**\n * Base Sharing Rule\n * Common metadata for all sharing strategies.\n */\nconst BaseSharingRuleSchema = z.object({\n // Identification\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique rule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n description: z.string().optional().describe('Administrative notes'),\n \n // Scope\n object: z.string().describe('Target Object Name'),\n active: z.boolean().default(true),\n \n // Access\n accessLevel: SharingLevel.default('read'),\n \n // Recipient (Whom to share with)\n sharedWith: z.object({\n type: ShareRecipientType,\n value: z.string().describe('ID or Code of the User/Group/Role'),\n }).describe('The recipient of the shared access'),\n});\n\n/**\n * 1. Criteria-Based Sharing Rule\n * Share records that meet specific field criteria.\n */\nexport const CriteriaSharingRuleSchema = BaseSharingRuleSchema.extend({\n type: z.literal('criteria'),\n condition: z.string().describe('Formula condition (e.g. \"department = \\'Sales\\'\")'),\n});\n\n/**\n * 2. Owner-Based Sharing Rule\n * Share records owned by a specific group of users.\n */\nexport const OwnerSharingRuleSchema = BaseSharingRuleSchema.extend({\n type: z.literal('owner'),\n ownedBy: z.object({\n type: ShareRecipientType,\n value: z.string(),\n }).describe('Source group/role whose records are being shared'),\n});\n\n/**\n * Master Sharing Rule Schema\n */\nexport const SharingRuleSchema = z.discriminatedUnion('type', [\n CriteriaSharingRuleSchema,\n OwnerSharingRuleSchema\n]);\n\nexport type SharingRule = z.infer;\nexport type CriteriaSharingRule = z.infer;\nexport type OwnerSharingRule = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Territory Management Protocol\n * Defines a matrix reporting structure that exists parallel to the Role Hierarchy.\n * \n * USE CASE:\n * - Enterprise Sales Teams (Geo-based: \"EMEA\", \"APAC\")\n * - Industry Verticals (Industry-based: \"Healthcare\", \"Financial\")\n * - Strategic Accounts (Account-based: \"Strategic Accounts\")\n * \n * DIFFERENCE FROM ROLE:\n * - Role: Hierarchy of PEOPLE (Who reports to whom). Stable. HR-driven.\n * - Territory: Hierarchy of ACCOUNTS/REVENUE (Who owns which market). Flexible. Sales-driven.\n * - One User can be assigned to MANY Territories (Matrix).\n * - One User has only ONE Role (Tree).\n */\n\nexport const TerritoryType = z.enum([\n 'geography', // Region/Country/City\n 'industry', // Vertical\n 'named_account', // Key Accounts\n 'product_line' // Product Specialty\n]);\n\n/**\n * Territory Model Schema\n * A container for a version of territory planning.\n * (e.g. \"Fiscal Year 2024 Planning\" vs \"Fiscal Year 2025 Planning\")\n */\nexport const TerritoryModelSchema = z.object({\n name: z.string().describe('Model Name (e.g. FY24 Planning)'),\n state: z.enum(['planning', 'active', 'archived']).default('planning'),\n startDate: z.string().optional(),\n endDate: z.string().optional(),\n});\n\n/**\n * Territory Node Schema\n * A single node in the territory tree.\n * \n * **NAMING CONVENTION:**\n * Territory names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good territory names\n * - 'west_coast'\n * - 'emea_region'\n * - 'healthcare_vertical'\n * - 'strategic_accounts'\n * \n * @example Bad territory names (will be rejected)\n * - 'WestCoast' (PascalCase)\n * - 'West Coast' (spaces)\n */\nexport const TerritorySchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Territory unique name (lowercase snake_case)'),\n label: z.string().describe('Territory Label (e.g. \"West Coast\")'),\n \n /** Structure */\n modelId: z.string().describe('Belongs to which Territory Model'),\n parent: z.string().optional().describe('Parent Territory'),\n type: TerritoryType.default('geography'),\n \n /** \n * Assignment Rules (The \"Magic\")\n * How do accounts automatically fall into this territory?\n * e.g. \"BillingCountry = 'US' AND BillingState = 'CA'\"\n */\n assignmentRule: z.string().optional().describe('Criteria based assignment rule'),\n \n /**\n * User Assignment\n * Users assigned to work this territory.\n */\n assignedUsers: z.array(z.string()).optional(),\n \n /** Access Level */\n accountAccess: z.enum(['read', 'edit']).default('read'),\n opportunityAccess: z.enum(['read', 'edit']).default('read'),\n caseAccess: z.enum(['read', 'edit']).default('read'),\n});\n\nexport type Territory = z.infer;\nexport type TerritoryModel = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Password Complexity Policy\n */\nexport const PasswordPolicySchema = z.object({\n minLength: z.number().default(8),\n requireUppercase: z.boolean().default(true),\n requireLowercase: z.boolean().default(true),\n requireNumbers: z.boolean().default(true),\n requireSymbols: z.boolean().default(false),\n expirationDays: z.number().optional().describe('Force password change every X days'),\n historyCount: z.number().default(3).describe('Prevent reusing last X passwords'),\n});\n\n/**\n * Network Access Policy (IP Whitelisting)\n */\nexport const NetworkPolicySchema = z.object({\n trustedRanges: z.array(z.string()).describe('CIDR ranges allowed to access (e.g. 10.0.0.0/8)'),\n blockUnknown: z.boolean().default(false).describe('Block all IPs not in trusted ranges'),\n vpnRequired: z.boolean().default(false),\n});\n\n/**\n * Session Policy\n */\nexport const SessionPolicySchema = z.object({\n idleTimeout: z.number().default(30).describe('Minutes before idle session logout'),\n absoluteTimeout: z.number().default(480).describe('Max session duration (minutes)'),\n forceMfa: z.boolean().default(false).describe('Require 2FA for all users'),\n});\n\n/**\n * Audit Retention Policy\n */\nexport const AuditPolicySchema = z.object({\n logRetentionDays: z.number().default(180),\n sensitiveFields: z.array(z.string()).describe('Fields to redact in logs (e.g. password, ssn)'),\n captureRead: z.boolean().default(false).describe('Log read access (High volume!)'),\n});\n\n/**\n * Security Policy Schema\n * \"The Cloud Compliance Contract\"\n */\nexport const PolicySchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Policy Name'),\n \n password: PasswordPolicySchema.optional(),\n network: NetworkPolicySchema.optional(),\n session: SessionPolicySchema.optional(),\n audit: AuditPolicySchema.optional(),\n\n /** Assignment */\n isDefault: z.boolean().default(false).describe('Apply to all users by default'),\n assignedProfiles: z.array(z.string()).optional().describe('Apply to specific profiles'),\n});\n\nexport type Policy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * UI Protocol Exports\n * \n * Presentation & Interaction\n * - App, Page, View (Grid/Kanban)\n * - Dashboard (Widgets), Report\n * - Action (Triggers)\n * - Chart (Unified Visualization Types)\n */\n\nexport * from './chart.zod';\nexport * from './i18n.zod';\nexport * from './responsive.zod';\nexport * from './app.zod';\nexport * from './view.zod';\nexport * from './dashboard.zod';\nexport * from './report.zod';\nexport * from './action.zod';\nexport * from './page.zod';\nexport * from './widget.zod';\nexport * from './component.zod';\nexport * from './theme.zod';\nexport * from './touch.zod';\nexport * from './offline.zod';\nexport * from './keyboard.zod';\nexport * from './animation.zod';\nexport * from './notification.zod';\nexport * from './dnd.zod';\nexport * from './sharing.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Unified Chart Type Taxonomy\n * \n * Shared by Dashboard and Report widgets.\n * Provides a comprehensive set of chart types for data visualization.\n */\n\n/**\n * Chart Type Enum\n * Categorized by visualization purpose\n */\nexport const ChartTypeSchema = z.enum([\n // Comparison\n 'bar',\n 'horizontal-bar',\n 'column',\n 'grouped-bar',\n 'stacked-bar',\n 'bi-polar-bar',\n \n // Trend\n 'line',\n 'area',\n 'stacked-area',\n 'step-line',\n 'spline',\n \n // Distribution\n 'pie',\n 'donut',\n 'funnel',\n 'pyramid',\n \n // Relationship\n 'scatter',\n 'bubble',\n \n // Composition\n 'treemap',\n 'sunburst',\n 'sankey',\n 'word-cloud',\n \n // Performance\n 'gauge',\n 'solid-gauge',\n 'metric',\n 'kpi',\n 'bullet',\n \n // Geo\n 'choropleth',\n 'bubble-map',\n 'gl-map',\n \n // Advanced\n 'heatmap',\n 'radar',\n 'waterfall',\n 'box-plot',\n 'violin',\n 'candlestick',\n 'stock',\n \n // Tabular\n 'table',\n 'pivot',\n]);\n\nexport type ChartType = z.infer;\n\n/**\n * Chart Axis Schema\n * Definition for X and Y axes\n */\nexport const ChartAxisSchema = z.object({\n /** Data field to map to this axis */\n field: z.string().describe('Data field key'),\n \n /** Axis title */\n title: I18nLabelSchema.optional().describe('Axis display title'),\n\n /** Value formatting (d3-format or similar) */\n format: z.string().optional().describe('Value format string (e.g., \"$0,0.00\")'),\n \n /** Axis scale settings */\n min: z.number().optional().describe('Minimum value'),\n max: z.number().optional().describe('Maximum value'),\n stepSize: z.number().optional().describe('Step size for ticks'),\n \n /** Appearance */\n showGridLines: z.boolean().default(true),\n position: z.enum(['left', 'right', 'top', 'bottom']).optional().describe('Axis position'),\n \n /** Logarithmic scale */\n logarithmic: z.boolean().default(false),\n});\n\n/**\n * Chart Series Schema\n * Defines a single data series in the chart\n */\nexport const ChartSeriesSchema = z.object({\n /** Field name for values */\n name: z.string().describe('Field name or series identifier'),\n \n /** Display label */\n label: I18nLabelSchema.optional().describe('Series display label'),\n \n /** Series type override (combo charts) */\n type: ChartTypeSchema.optional().describe('Override chart type for this series'),\n \n /** Specific color */\n color: z.string().optional().describe('Series color (hex/rgb/token)'),\n \n /** Stacking group */\n stack: z.string().optional().describe('Stack identifier to group series'),\n \n /** Axis binding */\n yAxis: z.enum(['left', 'right']).default('left').describe('Bind to specific Y-Axis'),\n});\n\n/**\n * Chart Annotation Schema\n * Static lines or regions to highlight data\n */\nexport const ChartAnnotationSchema = z.object({\n type: z.enum(['line', 'region']).default('line'),\n axis: z.enum(['x', 'y']).default('y'),\n value: z.union([z.number(), z.string()]).describe('Start value'),\n endValue: z.union([z.number(), z.string()]).optional().describe('End value for regions'),\n color: z.string().optional(),\n label: I18nLabelSchema.optional(),\n style: z.enum(['solid', 'dashed', 'dotted']).default('dashed'),\n});\n\n/**\n * Chart Interaction Schema\n */\nexport const ChartInteractionSchema = z.object({\n tooltips: z.boolean().default(true),\n zoom: z.boolean().default(false),\n brush: z.boolean().default(false),\n clickAction: z.string().optional().describe('Action ID to trigger on click'),\n});\n\n/**\n * Chart Configuration Base\n * Common configuration for all chart types\n */\nexport const ChartConfigSchema = z.object({\n /** Chart Type */\n type: ChartTypeSchema,\n \n /** Titles */\n title: I18nLabelSchema.optional().describe('Chart title'),\n subtitle: I18nLabelSchema.optional().describe('Chart subtitle'),\n description: I18nLabelSchema.optional().describe('Accessibility description'),\n \n /** Axes Mapping */\n xAxis: ChartAxisSchema.optional().describe('X-Axis configuration'),\n yAxis: z.array(ChartAxisSchema).optional().describe('Y-Axis configuration (support dual axis)'),\n \n /** Series Configuration */\n series: z.array(ChartSeriesSchema).optional().describe('Defined series configuration'),\n \n /** Appearance */\n colors: z.array(z.string()).optional().describe('Color palette'),\n height: z.number().optional().describe('Fixed height in pixels'),\n \n /** Components */\n showLegend: z.boolean().default(true).describe('Display legend'),\n showDataLabels: z.boolean().default(false).describe('Display data labels'),\n \n /** Annotations & Reference Lines */\n annotations: z.array(ChartAnnotationSchema).optional(),\n \n /** Interactions */\n interaction: ChartInteractionSchema.optional(),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport type ChartConfig = z.infer;\nexport type ChartAxis = z.infer;\nexport type ChartSeries = z.infer;\nexport type ChartAnnotation = z.infer;\nexport type ChartInteraction = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Breakpoint Name Enum\n * Matches the breakpoint names defined in theme.zod.ts BreakpointsSchema.\n */\nexport const BreakpointName = z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl']);\n\nexport type BreakpointName = z.infer;\n\n/**\n * Responsive Configuration Schema\n *\n * Provides responsive layout configuration for UI components.\n * Maps breakpoint names to layout behavior (columns, visibility, order).\n *\n * Aligned with theme.zod.ts BreakpointsSchema for a unified responsive system.\n *\n * @example\n * ```typescript\n * const config: ResponsiveConfig = {\n * columns: { xs: 12, sm: 6, lg: 4 },\n * hiddenOn: ['xs'],\n * order: { xs: 2, lg: 1 },\n * };\n * ```\n */\n/**\n * Breakpoint Column Map Schema\n * Maps breakpoint names to grid column counts (1-12).\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointColumnMapSchema = z.object({\n xs: z.number().min(1).max(12).optional(),\n sm: z.number().min(1).max(12).optional(),\n md: z.number().min(1).max(12).optional(),\n lg: z.number().min(1).max(12).optional(),\n xl: z.number().min(1).max(12).optional(),\n '2xl': z.number().min(1).max(12).optional(),\n}).describe('Grid columns per breakpoint (1-12)');\n\n/**\n * Breakpoint Order Map Schema\n * Maps breakpoint names to display order numbers.\n * All entries are optional — only specified breakpoints are configured.\n */\nexport const BreakpointOrderMapSchema = z.object({\n xs: z.number().optional(),\n sm: z.number().optional(),\n md: z.number().optional(),\n lg: z.number().optional(),\n xl: z.number().optional(),\n '2xl': z.number().optional(),\n}).describe('Display order per breakpoint');\n\nexport const ResponsiveConfigSchema = z.object({\n /** Minimum breakpoint for visibility */\n breakpoint: BreakpointName.optional()\n .describe('Minimum breakpoint for visibility'),\n\n /** Hide on specific breakpoints */\n hiddenOn: z.array(BreakpointName).optional()\n .describe('Hide on these breakpoints'),\n\n /** Grid columns per breakpoint (1-12 column grid) */\n columns: BreakpointColumnMapSchema.optional().describe('Grid columns per breakpoint'),\n\n /** Display order per breakpoint */\n order: BreakpointOrderMapSchema.optional().describe('Display order per breakpoint'),\n}).describe('Responsive layout configuration');\n\nexport type ResponsiveConfig = z.infer;\n\n/**\n * Performance Configuration Schema\n *\n * Defines performance optimization settings for UI components\n * such as lazy loading, virtual scrolling, and caching.\n *\n * @example\n * ```typescript\n * const perf: PerformanceConfig = {\n * lazyLoad: true,\n * virtualScroll: { enabled: true, itemHeight: 40, overscan: 5 },\n * cacheStrategy: 'stale-while-revalidate',\n * prefetch: true,\n * };\n * ```\n */\nexport const PerformanceConfigSchema = z.object({\n /** Enable lazy loading for this component */\n lazyLoad: z.boolean().optional()\n .describe('Enable lazy loading (defer rendering until visible)'),\n\n /** Virtual scrolling configuration for large datasets */\n virtualScroll: z.object({\n enabled: z.boolean().default(false).describe('Enable virtual scrolling'),\n itemHeight: z.number().optional().describe('Fixed item height in pixels (for estimation)'),\n overscan: z.number().optional().describe('Number of extra items to render outside viewport'),\n }).optional().describe('Virtual scrolling configuration'),\n\n /** Client-side caching strategy */\n cacheStrategy: z.enum([\n 'none',\n 'cache-first',\n 'network-first',\n 'stale-while-revalidate',\n ]).optional().describe('Client-side data caching strategy'),\n\n /** Enable data prefetching */\n prefetch: z.boolean().optional()\n .describe('Prefetch data before component is visible'),\n\n /** Maximum number of items to render before pagination */\n pageSize: z.number().optional()\n .describe('Number of items per page for pagination'),\n\n /** Debounce interval for user interactions (ms) */\n debounceMs: z.number().optional()\n .describe('Debounce interval for user interactions in milliseconds'),\n}).describe('Performance optimization configuration');\n\nexport type PerformanceConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module ui/sharing\n *\n * Sharing & Embedding Protocol\n *\n * Defines schemas for public link sharing, embed configuration,\n * domain restrictions, and password protection for apps, pages, and forms.\n */\n\nimport { z } from 'zod';\n\n/**\n * Sharing Config Schema\n * Configuration for public sharing of an app, page, or form.\n * Supports public links, password protection, domain restrictions, and expiration.\n */\nexport const SharingConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable public sharing'),\n publicLink: z.string().optional().describe('Generated public share URL'),\n password: z.string().optional().describe('Password required to access shared link'),\n allowedDomains: z.array(z.string()).optional()\n .describe('Restrict access to specific email domains (e.g. [\"example.com\"])'),\n expiresAt: z.string().optional()\n .describe('Expiration date/time in ISO 8601 format'),\n allowAnonymous: z.boolean().optional().default(false)\n .describe('Allow access without authentication'),\n});\n\n/**\n * Embed Config Schema\n * Configuration for iframe embedding of an app, page, or form.\n * Supports origin restrictions, display options, and responsive sizing.\n */\nexport const EmbedConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable iframe embedding'),\n allowedOrigins: z.array(z.string()).optional()\n .describe('Allowed iframe parent origins (e.g. [\"https://example.com\"])'),\n width: z.string().optional().default('100%').describe('Embed width (CSS value)'),\n height: z.string().optional().default('600px').describe('Embed height (CSS value)'),\n showHeader: z.boolean().optional().default(true).describe('Show interface header in embed'),\n showNavigation: z.boolean().optional().default(false).describe('Show navigation in embed'),\n responsive: z.boolean().optional().default(true).describe('Enable responsive resizing'),\n});\n\n// Type Exports\nexport type SharingConfig = z.infer;\nexport type EmbedConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema, EmbedConfigSchema } from './sharing.zod';\n\n/**\n * Base Navigation Item Schema\n * Shared properties for all navigation types.\n * \n * **NAMING CONVENTION:**\n * Navigation item IDs are used in URLs and configuration and must be lowercase snake_case.\n * \n * @example Good IDs\n * - 'menu_accounts'\n * - 'page_dashboard'\n * - 'nav_settings'\n * \n * @example Bad IDs (will be rejected)\n * - 'MenuAccounts' (PascalCase)\n * - 'Page Dashboard' (spaces)\n */\nconst BaseNavItemSchema = z.object({\n /** Unique identifier for the item */\n id: SnakeCaseIdentifierSchema.describe('Unique identifier for this navigation item (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Display proper label'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Icon name'),\n\n /** Sort order within the same level (lower numbers appear first) */\n order: z.number().optional().describe('Sort order within the same level (lower = first)'),\n\n /** Badge text or count displayed on the navigation item (e.g. \"3\", \"New\") */\n badge: z.union([z.string(), z.number()]).optional().describe('Badge text or count displayed on the item'),\n\n /** \n * Visibility condition. \n * Formula expression returning boolean. \n * e.g. \"user.is_admin || user.department == 'sales'\"\n */\n visible: z.string().optional().describe('Visibility formula condition'),\n\n /** Permissions required to see/access this navigation item */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this item'),\n});\n\n/**\n * 1. Object Navigation Item\n * Navigates to an object's list view.\n */\nexport const ObjectNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('object'),\n objectName: z.string().describe('Target object name'),\n viewName: z.string().optional().describe('Default list view to open. Defaults to \"all\"'),\n});\n\n/**\n * 2. Dashboard Navigation Item\n * Navigates to a specific dashboard.\n */\nexport const DashboardNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('dashboard'),\n dashboardName: z.string().describe('Target dashboard name'),\n});\n\n/**\n * 3. Page Navigation Item\n * Navigates to a custom UI page/component.\n */\nexport const PageNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('page'),\n pageName: z.string().describe('Target custom page component name'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the page context'),\n});\n\n/**\n * 4. URL Navigation Item\n * Navigates to an external or absolute URL.\n */\nexport const UrlNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('url'),\n url: z.string().describe('Target external URL'),\n target: z.enum(['_self', '_blank']).default('_self').describe('Link target window'),\n});\n\n/**\n * 5. Report Navigation Item\n * Navigates to a specific report.\n */\nexport const ReportNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('report'),\n reportName: z.string().describe('Target report name'),\n});\n\n/**\n * 6. Action Navigation Item\n * Triggers an action (e.g. opening a flow, running a script, or launching a screen action).\n */\nexport const ActionNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('action'),\n actionDef: z.object({\n actionName: z.string().describe('Action machine name to execute'),\n params: z.record(z.string(), z.unknown()).optional().describe('Parameters passed to the action'),\n }).describe('Action definition to execute when clicked'),\n});\n\n/**\n * 7. Group Navigation Item\n * A container for child navigation items (Sub-menu).\n * Does not perform navigation itself.\n */\nexport const GroupNavItemSchema = BaseNavItemSchema.extend({\n type: z.literal('group'),\n expanded: z.boolean().default(false).describe('Default expansion state in sidebar'),\n // children property is added in the recursive definition below\n});\n\n/**\n * Recursive Union of all navigation item types.\n * Allows constructing an unlimited-depth navigation tree.\n */\nexport const NavigationItemSchema: z.ZodType = z.lazy(() => \n z.union([\n ObjectNavItemSchema.extend({\n children: z.array(NavigationItemSchema).optional().describe('Child navigation items (e.g. specific views)'),\n }),\n DashboardNavItemSchema,\n PageNavItemSchema,\n UrlNavItemSchema,\n ReportNavItemSchema,\n ActionNavItemSchema,\n GroupNavItemSchema.extend({\n children: z.array(NavigationItemSchema).describe('Child navigation items'),\n })\n ])\n);\n\n/**\n * App Branding Configuration\n * Allows configuring the look and feel of the specific app.\n */\nexport const AppBrandingSchema = z.object({\n primaryColor: z.string().optional().describe('Primary theme color hex code'),\n logo: z.string().optional().describe('Custom logo URL for this app'),\n favicon: z.string().optional().describe('Custom favicon URL for this app'),\n});\n\n/**\n * Navigation Area Schema\n * \n * A logical grouping (zone/section) of navigation items, similar to Salesforce \"App Areas\"\n * or Dynamics 365 \"Site Map Areas\". Each area represents a business domain (e.g. Sales, Service, Settings)\n * and contains its own independent navigation tree.\n * \n * Areas allow large applications to partition navigation by business function while\n * keeping a single AppSchema definition. The runtime may render areas as top-level tabs,\n * sidebar sections, or a switchable navigation context.\n * \n * @example\n * ```ts\n * const salesArea: NavigationArea = {\n * id: 'area_sales',\n * label: 'Sales',\n * icon: 'briefcase',\n * order: 1,\n * navigation: [\n * { id: 'nav_leads', type: 'object', label: 'Leads', objectName: 'lead' },\n * { id: 'nav_opportunities', type: 'object', label: 'Opportunities', objectName: 'opportunity' },\n * ],\n * };\n * ```\n */\nexport const NavigationAreaSchema = z.object({\n /** Unique area identifier */\n id: SnakeCaseIdentifierSchema.describe('Unique area identifier (lowercase snake_case)'),\n\n /** Display label */\n label: I18nLabelSchema.describe('Area display label'),\n\n /** Icon name (Lucide) */\n icon: z.string().optional().describe('Area icon name'),\n\n /** Sort order among areas (lower = first) */\n order: z.number().optional().describe('Sort order among areas (lower = first)'),\n\n /** Area description */\n description: I18nLabelSchema.optional().describe('Area description'),\n\n /** \n * Visibility condition.\n * Formula expression returning boolean.\n */\n visible: z.string().optional().describe('Visibility formula condition for this area'),\n\n /** Permissions required to access this area */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this area'),\n\n /** Navigation items within this area */\n navigation: z.array(NavigationItemSchema).describe('Navigation items within this area'),\n});\n\n/**\n * Schema for Applications (Apps).\n * A logical container for business functionality (e.g., \"Sales CRM\", \"HR Portal\").\n * \n * **NAMING CONVENTION:**\n * App names are used in URLs and routing and must be lowercase snake_case.\n * Prefix with 'app_' is recommended for clarity.\n * \n * @example Good app names\n * - 'app_crm'\n * - 'app_finance'\n * - 'app_portal'\n * - 'sales_app'\n * \n * @example Bad app names (will be rejected)\n * - 'CRM' (uppercase)\n * - 'FinanceApp' (mixed case)\n * - 'Sales App' (spaces)\n */\n/**\n * App Configuration Schema\n * Defines a business application container, including its navigation, branding, and permissions.\n * \n * The App is the top-level navigation shell. The `navigation[]` field holds the complete\n * sidebar tree with unlimited nesting depth via `type: 'group'` items. Pages are referenced\n * by name via `type: 'page'` items and defined independently.\n * \n * @example CRM App with nested navigation tree\n * {\n * name: \"crm\",\n * label: \"Sales CRM\",\n * icon: \"briefcase\",\n * navigation: [\n * { type: \"group\", id: \"grp_sales\", label: \"Sales Cloud\", expanded: true, children: [\n * { type: \"page\", id: \"nav_pipeline\", label: \"Pipeline\", pageName: \"page_pipeline\" },\n * { type: \"page\", id: \"nav_accounts\", label: \"Accounts\", pageName: \"page_accounts\" },\n * ]},\n * { type: \"page\", id: \"nav_settings\", label: \"Settings\", pageName: \"admin_settings\" },\n * ]\n * }\n */\nexport const AppSchema = z.object({\n /** Machine name (id) */\n name: SnakeCaseIdentifierSchema.describe('App unique machine name (lowercase snake_case)'),\n \n /** Display label */\n label: I18nLabelSchema.describe('App display label'),\n\n /** App version */\n version: z.string().optional().describe('App version'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('App description'),\n \n /** Icon name (Lucide) */\n icon: z.string().optional().describe('App icon used in the App Launcher'),\n \n /** Branding/Theming Configuration */\n branding: AppBrandingSchema.optional().describe('App-specific branding'),\n \n /** Application status */\n active: z.boolean().optional().default(true).describe('Whether the app is enabled'),\n\n /** Is this the default app for new users? */\n isDefault: z.boolean().optional().default(false).describe('Is default app'),\n \n /** \n * Full Navigation Tree — supports unlimited nesting depth.\n * Pages are referenced by name via `type: 'page'` items.\n * Groups can contain other groups for arbitrary sidebar depth.\n * \n * For simple apps, use `navigation` directly.\n * For enterprise apps with multiple business domains, use `areas` instead.\n */\n navigation: z.array(NavigationItemSchema).optional()\n .describe('Full navigation tree for the app sidebar'),\n\n /**\n * Navigation Areas — partitions navigation by business domain.\n * Each area defines an independent navigation tree (e.g. Sales, Service, Settings).\n * When areas are defined, they take precedence over the top-level `navigation` array.\n * \n * @example\n * ```ts\n * areas: [\n * { id: 'area_sales', label: 'Sales', icon: 'briefcase', order: 1, navigation: [...] },\n * { id: 'area_service', label: 'Service', icon: 'headset', order: 2, navigation: [...] },\n * ]\n * ```\n */\n areas: z.array(NavigationAreaSchema).optional()\n .describe('Navigation areas for partitioning navigation by business domain'),\n \n /** \n * App-level Home Page Override\n * ID of the navigation item to act as the landing page.\n * If not set, usually defaults to the first navigation item.\n */\n homePageId: z.string().optional().describe('ID of the navigation item to serve as landing page'),\n\n /** \n * Access Control\n * List of permissions required to access this app.\n * Modern replacement for role/profile based assignment.\n * Example: [\"app.access.crm\"]\n */\n requiredPermissions: z.array(z.string()).optional().describe('Permissions required to access this app'),\n \n /** \n * Package Components (For config file convenience)\n * In a real monorepo these might be auto-discovered, but here we allow explicit registration.\n */\n objects: z.array(z.unknown()).optional().describe('Objects belonging to this app'),\n apis: z.array(z.unknown()).optional().describe('Custom APIs belonging to this app'),\n\n /** Sharing configuration for public access */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration'),\n\n /** Embed configuration for iframe embedding */\n embed: EmbedConfigSchema.optional().describe('Iframe embedding configuration'),\n\n /** Mobile navigation mode */\n mobileNavigation: z.object({\n mode: z.enum(['drawer', 'bottom_nav', 'hamburger']).default('drawer')\n .describe('Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu'),\n bottomNavItems: z.array(z.string()).optional()\n .describe('Navigation item IDs to show in bottom nav (max 5)'),\n }).optional().describe('Mobile-specific navigation configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the application'),\n});\n\n/**\n * App Factory Helper\n */\nexport const App = {\n create: (config: z.input): App => AppSchema.parse(config),\n} as const;\n\n/**\n * Type-safe factory for creating application definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example CRM App with nested navigation tree\n * ```ts\n * const crmApp = defineApp({\n * name: 'crm',\n * label: 'Sales CRM',\n * navigation: [\n * { id: 'grp_sales', type: 'group', label: 'Sales Cloud', expanded: true, children: [\n * { id: 'nav_pipeline', type: 'page', label: 'Pipeline', pageName: 'page_pipeline' },\n * { id: 'nav_accounts', type: 'page', label: 'Accounts', pageName: 'page_accounts' },\n * ]},\n * { id: 'nav_settings', type: 'page', label: 'Settings', pageName: 'admin_settings' },\n * ],\n * });\n * ```\n */\nexport function defineApp(config: z.input): App {\n return AppSchema.parse(config);\n}\n\n// Main Types\nexport type App = z.infer;\nexport type AppInput = z.input;\nexport type AppBranding = z.infer;\nexport type NavigationItem = z.infer;\nexport type NavigationArea = z.infer;\n\n// Discriminated Item Types (Helper exports)\nexport type ObjectNavItem = z.infer;\nexport type DashboardNavItem = z.infer;\nexport type PageNavItem = z.infer;\nexport type UrlNavItem = z.infer;\nexport type ReportNavItem = z.infer;\nexport type ActionNavItem = z.infer;\nexport type GroupNavItem = z.infer & { children: NavigationItem[] };\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { SharingConfigSchema } from './sharing.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * HTTP Method Enum & HTTP Request Schema\n * Migrated to shared/http.zod.ts. Re-exported here for backward compatibility.\n */\nimport { HttpMethodSchema, HttpRequestSchema } from '../shared/http.zod';\nexport { HttpMethodSchema, HttpRequestSchema };\n\n/**\n * View Data Source Configuration\n * Supports three modes:\n * 1. 'object': Standard Protocol - Auto-connects to ObjectStack Metadata and Data APIs\n * 2. 'api': Custom API - Explicitly provided API URLs\n * 3. 'value': Static Data - Hardcoded data array\n */\nexport const ViewDataSchema = z.discriminatedUnion('provider', [\n z.object({\n provider: z.literal('object'),\n object: z.string().describe('Target object name'),\n }),\n z.object({\n provider: z.literal('api'),\n read: HttpRequestSchema.optional().describe('Configuration for fetching data'),\n write: HttpRequestSchema.optional().describe('Configuration for submitting data (for forms/editable tables)'),\n }),\n z.object({\n provider: z.literal('value'),\n items: z.array(z.unknown()).describe('Static data array'),\n }),\n]);\n\n/**\n * View Filter Rule Schema\n * Standardized filter condition used in list views, tabs, and page-level filters.\n * Uses a declarative array-of-objects format: [{ field, operator, value }].\n *\n * @example\n * ```ts\n * filter: [\n * { field: 'status', operator: 'equals', value: 'active' },\n * { field: 'close_date', operator: 'this_quarter' },\n * ]\n * ```\n */\nexport const ViewFilterRuleSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n /** Filter operator */\n operator: z.string().describe('Filter operator (e.g. equals, not_equals, contains, this_quarter)'),\n /** Filter value (optional for unary operators like is_null, this_quarter) */\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Filter value'),\n}).describe('View filter rule');\n\nexport type ViewFilterRule = z.infer;\n\n/**\n * Column Summary Function Schema\n * Aggregation function for column footer (Airtable-style column summaries)\n */\nexport const ColumnSummarySchema = z.enum([\n 'none',\n 'count',\n 'count_empty',\n 'count_filled',\n 'count_unique',\n 'percent_empty',\n 'percent_filled',\n 'sum',\n 'avg',\n 'min',\n 'max',\n]).describe('Aggregation function for column footer summary');\n\n/**\n * List Column Configuration Schema\n * Detailed configuration for individual list view columns\n */\nexport const ListColumnSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n width: z.number().positive().optional().describe('Column width in pixels'),\n align: z.enum(['left', 'center', 'right']).optional().describe('Text alignment'),\n hidden: z.boolean().optional().describe('Hide column by default'),\n sortable: z.boolean().optional().describe('Allow sorting by this column'),\n resizable: z.boolean().optional().describe('Allow resizing this column'),\n wrap: z.boolean().optional().describe('Allow text wrapping'),\n type: z.string().optional().describe('Renderer type override (e.g., \"currency\", \"date\")'),\n\n /** Pinning (Airtable-style frozen columns) */\n pinned: z.enum(['left', 'right']).optional().describe('Pin/freeze column to left or right side'),\n\n /** Column Footer Summary (Airtable-style aggregation) */\n summary: ColumnSummarySchema.optional().describe('Footer aggregation function for this column'),\n\n /** Interaction */\n link: z.boolean().optional().describe('Functions as the primary navigation link (triggers View navigation)'),\n action: z.string().optional().describe('Registered Action ID to execute when clicked'),\n});\n\n/**\n * List View Selection Configuration\n */\nexport const SelectionConfigSchema = z.object({\n type: z.enum(['none', 'single', 'multiple']).default('none').describe('Selection mode'),\n});\n\n/**\n * List View Pagination Configuration\n */\nexport const PaginationConfigSchema = z.object({\n pageSize: z.number().int().positive().default(25).describe('Number of records per page'),\n pageSizeOptions: z.array(z.number().int().positive()).optional().describe('Available page size options'),\n});\n\n/**\n * Row Height / Density Schema (Airtable-style)\n * Controls the visual density of rows in a list view.\n */\nexport const RowHeightSchema = z.enum([\n 'compact', // Minimal padding, single line\n 'short', // Reduced padding\n 'medium', // Default padding\n 'tall', // Extra padding, multi-line preview\n 'extra_tall', // Maximum padding, rich content preview\n]).describe('Row height / density setting for list view');\n\n/**\n * Grouping Field Configuration\n * Defines a single grouping level for record grouping.\n */\nexport const GroupingFieldSchema = z.object({\n field: z.string().describe('Field name to group by'),\n order: z.enum(['asc', 'desc']).default('asc').describe('Group sort order'),\n collapsed: z.boolean().default(false).describe('Collapse groups by default'),\n});\n\n/**\n * Grouping Configuration Schema (Airtable-style)\n * Supports multi-level grouping for grid/gallery views.\n */\nexport const GroupingConfigSchema = z.object({\n fields: z.array(GroupingFieldSchema).min(1).describe('Fields to group by (supports up to 3 levels)'),\n}).describe('Record grouping configuration');\n\n/**\n * Gallery View Configuration (Airtable-style)\n * Configures card layout for gallery/card views.\n */\nexport const GalleryConfigSchema = z.object({\n coverField: z.string().optional().describe('Attachment/image field to display as card cover'),\n coverFit: z.enum(['cover', 'contain']).default('cover').describe('Image fit mode for card cover'),\n cardSize: z.enum(['small', 'medium', 'large']).default('medium').describe('Card size in gallery view'),\n titleField: z.string().optional().describe('Field to display as card title'),\n visibleFields: z.array(z.string()).optional().describe('Fields to display on card body'),\n}).describe('Gallery/card view configuration');\n\n/**\n * Timeline View Configuration (Airtable-style)\n * Configures timeline/chronological views.\n */\nexport const TimelineConfigSchema = z.object({\n startDateField: z.string().describe('Field for timeline item start date'),\n endDateField: z.string().optional().describe('Field for timeline item end date'),\n titleField: z.string().describe('Field to display as timeline item title'),\n groupByField: z.string().optional().describe('Field to group timeline rows'),\n colorField: z.string().optional().describe('Field to determine item color'),\n scale: z.enum(['hour', 'day', 'week', 'month', 'quarter', 'year']).default('week').describe('Default timeline scale'),\n}).describe('Timeline view configuration');\n\n/**\n * View Sharing Configuration (Airtable-style)\n * Defines who can see and modify a view.\n */\nexport const ViewSharingSchema = z.object({\n type: z.enum(['personal', 'collaborative']).default('collaborative').describe('View ownership type'),\n lockedBy: z.string().optional().describe('User who locked the view configuration'),\n}).describe('View sharing and access configuration');\n\n/**\n * Row Color Configuration (Airtable-style)\n * Defines how rows are colored based on field values.\n */\nexport const RowColorConfigSchema = z.object({\n field: z.string().describe('Field to derive color from (typically a select/status field)'),\n colors: z.record(z.string(), z.string()).optional().describe('Map of field value to color (hex/token)'),\n}).describe('Row color configuration based on field values');\n\n/**\n * Visualization Type Schema\n * Whitelist of visualization types the user can switch between.\n * Maps to Airtable's \"Visualizations\" setting in Appearance panel.\n */\nexport const VisualizationTypeSchema = z.enum([\n 'grid',\n 'kanban',\n 'gallery',\n 'calendar',\n 'timeline',\n 'gantt',\n 'map',\n]).describe('Visualization type that users can switch to');\n\n/**\n * User Actions Configuration Schema (Airtable Interface parity)\n * Controls which interactive actions are available to users in the view toolbar.\n * Each boolean toggles the corresponding toolbar element on/off.\n *\n * @see Airtable Interface → \"User actions\" panel\n */\nexport const UserActionsConfigSchema = z.object({\n sort: z.boolean().default(true).describe('Allow users to sort records'),\n search: z.boolean().default(true).describe('Allow users to search records'),\n filter: z.boolean().default(true).describe('Allow users to filter records'),\n rowHeight: z.boolean().default(true).describe('Allow users to toggle row height/density'),\n addRecordForm: z.boolean().default(false).describe('Add records through a form instead of inline'),\n buttons: z.array(z.string()).optional().describe('Custom action button IDs to show in the toolbar'),\n}).describe('User action toggles for the view toolbar');\n\n/**\n * Appearance Configuration Schema (Airtable Interface parity)\n * Controls visual presentation options for the view.\n *\n * @see Airtable Interface → \"Appearance\" panel\n */\nexport const AppearanceConfigSchema = z.object({\n showDescription: z.boolean().default(true).describe('Show the view description text'),\n allowedVisualizations: z.array(VisualizationTypeSchema).optional()\n .describe('Whitelist of visualization types users can switch between (e.g. [\"grid\", \"gallery\", \"kanban\"])'),\n}).describe('Appearance and visualization configuration');\n\n/**\n * View Tab Schema (Airtable Interface parity)\n * Defines a tab in a multi-tab view interface.\n * Each tab references a named list view and can be ordered, pinned, or set as default.\n *\n * @see Airtable Interface → \"Tabs\" panel\n */\nexport const ViewTabSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Tab identifier (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label'),\n icon: z.string().optional().describe('Tab icon name'),\n view: z.string().optional().describe('Referenced list view name from listViews'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Tab-specific filter criteria'),\n order: z.number().int().min(0).optional().describe('Tab display order'),\n pinned: z.boolean().default(false).describe('Pin tab (cannot be removed by users)'),\n isDefault: z.boolean().default(false).describe('Set as the default active tab'),\n visible: z.boolean().default(true).describe('Tab visibility'),\n}).describe('Tab configuration for multi-tab view interface');\n\n/**\n * Add Record Configuration Schema (Airtable Interface parity)\n * Configures the \"Add Record\" entry point for a list view.\n *\n * @see Airtable Interface → \"+ Add record\" button\n */\nexport const AddRecordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Show the add record entry point'),\n position: z.enum(['top', 'bottom', 'both']).default('bottom').describe('Position of the add record button'),\n mode: z.enum(['inline', 'form', 'modal']).default('inline').describe('How to add a new record'),\n formView: z.string().optional().describe('Named form view to use when mode is \"form\" or \"modal\"'),\n}).describe('Add record entry point configuration');\n\n/**\n * Kanban Settings\n */\nexport const KanbanConfigSchema = z.object({\n groupByField: z.string().describe('Field to group columns by (usually status/select)'),\n summarizeField: z.string().optional().describe('Field to sum at top of column (e.g. amount)'),\n columns: z.array(z.string()).describe('Fields to show on cards'),\n});\n\n/**\n * Calendar Settings\n */\nexport const CalendarConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string().optional(),\n titleField: z.string(),\n colorField: z.string().optional(),\n});\n\n/**\n * Gantt Settings\n */\nexport const GanttConfigSchema = z.object({\n startDateField: z.string(),\n endDateField: z.string(),\n titleField: z.string(),\n progressField: z.string().optional(),\n dependenciesField: z.string().optional(),\n});\n\n/**\n * Navigation Mode Enum\n * Defines how to navigate to the detail view from a list item.\n */\nexport const NavigationModeSchema = z.enum([\n 'page', // Navigate to a new route (default)\n 'drawer', // Open details in a side drawer/panel\n 'modal', // Open details in a modal dialog\n 'split', // Show details side-by-side with the list (master-detail)\n 'popover', // Show details in a popover (lightweight)\n 'new_window', // Open in new browser tab/window\n 'none' // No navigation (read-only list)\n]);\n\n/**\n * Navigation Configuration Schema\n */\nexport const NavigationConfigSchema = z.object({\n mode: NavigationModeSchema.default('page'),\n \n /** Target View Config */\n view: z.string().optional().describe('Name of the form view to use for details (e.g. \"summary_view\", \"edit_form\")'),\n \n /** Interaction Triggers */\n preventNavigation: z.boolean().default(false).describe('Disable standard navigation entirely'),\n openNewTab: z.boolean().default(false).describe('Force open in new tab (applies to page mode)'),\n \n /** Dimensions (for modal/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Width of the drawer/modal (e.g. \"600px\", \"50%\")'),\n});\n\n/**\n * List View Schema (Expanded)\n * Defines how a collection of records is displayed to the user.\n * \n * **NAMING CONVENTION:**\n * View names (when provided) are machine identifiers and must be lowercase snake_case.\n * \n * @example Standard Grid\n * {\n * name: \"all_active\",\n * label: \"All Active\",\n * type: \"grid\",\n * columns: [\"name\", \"status\", \"created_at\"],\n * filter: [[\"status\", \"=\", \"active\"]]\n * }\n * \n * @example Kanban Board\n * {\n * type: \"kanban\",\n * columns: [\"name\", \"amount\"],\n * kanban: {\n * groupByField: \"stage\",\n * summarizeField: \"amount\",\n * columns: [\"name\", \"close_date\"]\n * }\n * }\n */\nexport const ListViewSchema = z.object({\n name: SnakeCaseIdentifierSchema.optional().describe('Internal view name (lowercase snake_case)'),\n label: I18nLabelSchema.optional(), // Display label override (supports i18n)\n type: z.enum([\n 'grid', // Standard Data Table\n 'kanban', // Board / Columns\n 'gallery', // Card Deck / Masonry\n 'calendar', // Monthly/Weekly/Daily\n 'timeline', // Chronological Stream (Feed)\n 'gantt', // Project Timeline\n 'map' // Geospatial\n ]).default('grid'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n /** Shared Query Config */\n columns: z.union([\n z.array(z.string()), // Legacy: simple field names\n z.array(ListColumnSchema), // Enhanced: detailed column config\n ]).describe('Fields to display as columns'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Filter criteria (JSON Rules)'),\n sort: z.union([\n z.string(), //Legacy \"field desc\"\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional(),\n \n /** Search & Filter */\n searchableFields: z.array(z.string()).optional().describe('Fields enabled for search'),\n filterableFields: z.array(z.string()).optional().describe('Fields enabled for end-user filtering in the top bar'),\n\n /** Quick Filters (One-click filter chips, Salesforce ListFilter pattern) */\n quickFilters: z.array(z.object({\n field: z.string().describe('Field name to filter by'),\n label: z.string().optional().describe('Display label for the chip'),\n operator: z.enum(['equals', 'not_equals', 'contains', 'in', 'is_null', 'is_not_null']).default('equals').describe('Filter operator'),\n value: z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(z.union([z.string(), z.number()]))])\n .optional().describe('Preset filter value'),\n })).optional().describe('One-click filter chips for quick record filtering'),\n\n /** Grid Features */\n resizable: z.boolean().optional().describe('Enable column resizing'),\n striped: z.boolean().optional().describe('Striped row styling'),\n bordered: z.boolean().optional().describe('Show borders'),\n\n /** Selection */\n selection: SelectionConfigSchema.optional().describe('Row selection configuration'),\n\n /** Navigation / Interaction */\n navigation: NavigationConfigSchema.optional().describe('Configuration for item click navigation (page, drawer, modal, etc.)'),\n\n /** Pagination */\n pagination: PaginationConfigSchema.optional().describe('Pagination configuration'),\n\n /** Type Specific Config */\n kanban: KanbanConfigSchema.optional(),\n calendar: CalendarConfigSchema.optional(),\n gantt: GanttConfigSchema.optional(),\n gallery: GalleryConfigSchema.optional(),\n timeline: TimelineConfigSchema.optional(),\n\n /** View Metadata (Airtable-style view management) */\n description: I18nLabelSchema.optional().describe('View description for documentation/tooltips'),\n sharing: ViewSharingSchema.optional().describe('View sharing and access configuration'),\n\n /** Row Height / Density (Airtable-style) */\n rowHeight: RowHeightSchema.optional().describe('Row height / density setting'),\n\n /** Record Grouping (Airtable-style) */\n grouping: GroupingConfigSchema.optional().describe('Group records by one or more fields'),\n\n /** Row Color (Airtable-style) */\n rowColor: RowColorConfigSchema.optional().describe('Color rows based on field value'),\n\n /** Field Visibility & Ordering per View (Airtable-style) */\n hiddenFields: z.array(z.string()).optional().describe('Fields to hide in this specific view'),\n fieldOrder: z.array(z.string()).optional().describe('Explicit field display order for this view'),\n\n /** Row & Bulk Actions */\n rowActions: z.array(z.string()).optional().describe('Actions available for individual row items'),\n bulkActions: z.array(z.string()).optional().describe('Actions available when multiple rows are selected'),\n\n /** Performance */\n virtualScroll: z.boolean().optional().describe('Enable virtual scrolling for large datasets'),\n\n /** Conditional Formatting */\n conditionalFormatting: z.array(z.object({\n condition: z.string().describe('Condition expression to evaluate'),\n style: z.record(z.string(), z.string()).describe('CSS styles to apply when condition is true'),\n })).optional().describe('Conditional formatting rules for list rows'),\n\n /** Inline Edit */\n inlineEdit: z.boolean().optional().describe('Allow inline editing of records directly in the list view'),\n\n /** Export */\n exportOptions: z.array(z.enum(['csv', 'xlsx', 'pdf', 'json'])).optional().describe('Available export format options'),\n\n /** User Actions (Airtable Interface parity) */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles for the view toolbar'),\n\n /** Appearance (Airtable Interface parity) */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** Tabs (Airtable Interface parity) */\n tabs: z.array(ViewTabSchema).optional().describe('Tab definitions for multi-tab view interface'),\n\n /** Add Record (Airtable Interface parity) */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record Count Display (Airtable Interface parity) */\n showRecordCount: z.boolean().optional().describe('Show record count at the bottom of the list'),\n\n /** Advanced: Allow Printing (Airtable Interface parity) */\n allowPrinting: z.boolean().optional().describe('Allow users to print the view'),\n\n /** Empty State */\n emptyState: z.object({\n title: I18nLabelSchema.optional(),\n message: I18nLabelSchema.optional(),\n icon: z.string().optional(),\n }).optional().describe('Empty state configuration when no records found'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the list view'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Form Field Configuration Schema\n * Detailed configuration for individual form fields\n */\nexport const FormFieldSchema = z.object({\n field: z.string().describe('Field name (snake_case)'),\n label: I18nLabelSchema.optional().describe('Display label override'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n helpText: I18nLabelSchema.optional().describe('Help/hint text'),\n readonly: z.boolean().optional().describe('Read-only override'),\n required: z.boolean().optional().describe('Required override'),\n hidden: z.boolean().optional().describe('Hidden override'),\n colSpan: z.number().int().min(1).max(4).optional().describe('Column span in grid layout (1-4)'),\n widget: z.string().optional().describe('Custom widget/component name'),\n dependsOn: z.string().optional().describe('Parent field name for cascading'),\n visibleOn: z.string().optional().describe('Visibility condition expression'),\n});\n\n/**\n * Form Layout Section\n */\nexport const FormSectionSchema = z.object({\n label: I18nLabelSchema.optional(),\n collapsible: z.boolean().default(false),\n collapsed: z.boolean().default(false),\n columns: z.enum(['1', '2', '3', '4']).default('2').transform(val => parseInt(val) as 1 | 2 | 3 | 4),\n fields: z.array(z.union([\n z.string(), // Legacy: simple field name\n FormFieldSchema, // Enhanced: detailed field config\n ])),\n});\n\n/**\n * Form View Schema\n * Defines the layout for creating or editing a single record.\n * \n * @example Simple Sectioned Form\n * {\n * type: \"simple\",\n * sections: [\n * {\n * label: \"General Info\",\n * columns: 2,\n * fields: [\"name\", \"status\"]\n * },\n * {\n * label: \"Details\",\n * fields: [\"description\", { field: \"priority\", widget: \"rating\" }]\n * }\n * ]\n * }\n */\nexport const FormViewSchema = z.object({\n type: z.enum([\n 'simple', // Single column or sections\n 'tabbed', // Tabs\n 'wizard', // Step by step\n 'split', // Master-Detail split\n 'drawer', // Side panel\n 'modal' // Dialog\n ]).default('simple'),\n \n /** Data Source Configuration */\n data: ViewDataSchema.optional().describe('Data source configuration (defaults to \"object\" provider)'),\n \n sections: z.array(FormSectionSchema).optional(), // For simple layout\n groups: z.array(FormSectionSchema).optional(), // Legacy support -> alias to sections\n\n /** Default Sort for Related Lists (e.g., sort child records by date) */\n defaultSort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n order: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n })).optional().describe('Default sort order for related list views within this form'),\n\n /** Public form sharing configuration */\n sharing: SharingConfigSchema.optional().describe('Public sharing configuration for this form'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes for the form view'),\n});\n\n/**\n * Master View Schema\n * Can define multiple named views.\n */\n/**\n * View Container Schema\n * Aggregates all view definitions for a specific object or context.\n * \n * @example\n * {\n * list: { type: \"grid\", columns: [\"name\"] },\n * form: { type: \"simple\", fields: [\"name\"] },\n * listViews: {\n * \"all\": { label: \"All\", filter: [] },\n * \"my\": { label: \"Mine\", filter: [[\"owner\", \"=\", \"{user_id}\"]] }\n * }\n * }\n */\nexport const ViewSchema = z.object({\n list: ListViewSchema.optional(), // Default list view\n form: FormViewSchema.optional(), // Default form view\n listViews: z.record(z.string(), ListViewSchema).optional().describe('Additional named list views'),\n formViews: z.record(z.string(), FormViewSchema).optional().describe('Additional named form views'),\n});\n\n/**\n * Type-safe factory for creating view definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const taskViews = defineView({\n * list: {\n * type: 'grid',\n * data: { provider: 'object', object: 'task' },\n * columns: ['subject', 'status', 'priority', 'due_date'],\n * },\n * form: {\n * type: 'simple',\n * sections: [{ label: 'Details', fields: [{ field: 'subject' }] }],\n * },\n * });\n * ```\n */\nexport function defineView(config: z.input): View {\n return ViewSchema.parse(config);\n}\n\nexport type View = z.infer;\nexport type ListView = z.infer;\nexport type FormView = z.infer;\nexport type FormSection = z.infer;\nexport type ListColumn = z.infer;\nexport type FormField = z.infer;\nexport type SelectionConfig = z.infer;\nexport type NavigationConfig = z.infer;\nexport type PaginationConfig = z.infer;\nexport type ViewData = z.infer;\nexport type HttpRequest = z.infer;\nexport type HttpMethod = z.infer;\nexport type ColumnSummary = z.infer;\nexport type RowHeight = z.infer;\nexport type GroupingConfig = z.infer;\nexport type GalleryConfig = z.infer;\nexport type TimelineConfig = z.infer;\nexport type ViewSharing = z.infer;\nexport type RowColorConfig = z.infer;\nexport type VisualizationType = z.infer;\nexport type UserActionsConfig = z.infer;\nexport type AppearanceConfig = z.infer;\nexport type ViewTab = z.infer;\nexport type AddRecordConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ChartTypeSchema, ChartConfigSchema } from './chart.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Color variant for dashboard widgets (e.g., KPI cards).\n */\nexport const WidgetColorVariantSchema = z.enum([\n 'default',\n 'blue',\n 'teal',\n 'orange',\n 'purple',\n 'success',\n 'warning',\n 'danger',\n]).describe('Widget color variant');\n\n/**\n * Action type for widget action buttons.\n */\nexport const WidgetActionTypeSchema = z.enum([\n 'script',\n 'url',\n 'modal',\n 'flow',\n 'api',\n]).describe('Widget action type');\n\n/**\n * Dashboard Header Action Schema\n * An action button displayed in the dashboard header area.\n */\nexport const DashboardHeaderActionSchema = z.object({\n /** Action label */\n label: I18nLabelSchema.describe('Action button label'),\n\n /** Action URL or target */\n actionUrl: z.string().describe('URL or target for the action'),\n\n /** Action type */\n actionType: WidgetActionTypeSchema.optional().describe('Type of action'),\n\n /** Icon identifier */\n icon: z.string().optional().describe('Icon identifier for the action button'),\n}).describe('Dashboard header action');\n\n/**\n * Dashboard Header Schema\n * Structured header configuration for the dashboard.\n */\nexport const DashboardHeaderSchema = z.object({\n /** Whether to show the dashboard title in the header */\n showTitle: z.boolean().default(true).describe('Show dashboard title in header'),\n\n /** Whether to show the dashboard description in the header */\n showDescription: z.boolean().default(true).describe('Show dashboard description in header'),\n\n /** Action buttons displayed in the header */\n actions: z.array(DashboardHeaderActionSchema).optional().describe('Header action buttons'),\n}).describe('Dashboard header configuration');\n\n/**\n * Widget Measure Schema\n * A single measure definition for multi-measure pivot/matrix widgets.\n */\nexport const WidgetMeasureSchema = z.object({\n /** Value field to aggregate */\n valueField: z.string().describe('Field to aggregate'),\n\n /** Aggregate function */\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max']).default('count').describe('Aggregate function'),\n\n /** Display label for the measure */\n label: I18nLabelSchema.optional().describe('Measure display label'),\n\n /** Number format string (e.g., \"$0,0.00\", \"0.0%\") */\n format: z.string().optional().describe('Number format string'),\n}).describe('Widget measure definition');\n\n/**\n * Dashboard Widget Schema\n * A single component on the dashboard grid.\n */\nexport const DashboardWidgetSchema = z.object({\n /** Unique widget identifier (snake_case, used for targetWidgets references) */\n id: SnakeCaseIdentifierSchema.describe('Unique widget identifier (snake_case)'),\n\n /** Widget Title */\n title: I18nLabelSchema.optional().describe('Widget title'),\n\n /** Widget Description (displayed below the title) */\n description: I18nLabelSchema.optional().describe('Widget description text below the header'),\n \n /** Visualization Type */\n type: ChartTypeSchema.default('metric').describe('Visualization type'),\n \n /** Chart Configuration */\n chartConfig: ChartConfigSchema.optional().describe('Chart visualization configuration'),\n\n /** Color variant for the widget (e.g., KPI card accent color) */\n colorVariant: WidgetColorVariantSchema.optional().describe('Widget color variant for theming'),\n\n /** Action URL for the widget header action button */\n actionUrl: z.string().optional().describe('URL or target for the widget action button'),\n\n /** Action type for the widget header action button */\n actionType: WidgetActionTypeSchema.optional().describe('Type of action for the widget action button'),\n\n /** Icon for the widget header action button */\n actionIcon: z.string().optional().describe('Icon identifier for the widget action button'),\n \n /** Data Source Object */\n object: z.string().optional().describe('Data source object name'),\n \n /** Data Filter (MongoDB-style FilterCondition) */\n filter: FilterConditionSchema.optional().describe('Data filter criteria'),\n \n /** Category Field (X-Axis / Group By) */\n categoryField: z.string().optional().describe('Field for grouping (X-Axis)'),\n \n /** Value Field (Y-Axis) */\n valueField: z.string().optional().describe('Field for values (Y-Axis)'),\n \n /** Aggregate operation */\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max']).optional().default('count').describe('Aggregate function'),\n \n /** Multi-measure definitions for pivot/matrix widgets */\n measures: z.array(WidgetMeasureSchema).optional().describe('Multiple measures for pivot/matrix analysis'),\n \n /** \n * Layout Position (React-Grid-Layout style)\n * x: column (0-11)\n * y: row\n * w: width (1-12)\n * h: height\n */\n layout: z.object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n }).describe('Grid layout position'),\n \n /** Widget specific options (colors, legend, etc.) */\n options: z.unknown().optional().describe('Widget specific configuration'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * Dynamic options binding for global filters.\n * Allows dropdown options to be fetched from an object at runtime.\n */\nexport const GlobalFilterOptionsFromSchema = z.object({\n /** Source object name to fetch options from */\n object: z.string().describe('Source object name'),\n\n /** Field to use as option value */\n valueField: z.string().describe('Field to use as option value'),\n\n /** Field to use as option label */\n labelField: z.string().describe('Field to use as option label'),\n\n /** Optional filter to apply when fetching options */\n filter: FilterConditionSchema.optional().describe('Filter to apply to source object'),\n}).describe('Dynamic filter options from object');\n\n/**\n * Global Filter Schema\n * Defines a single global filter control for the dashboard filter bar.\n */\nexport const GlobalFilterSchema = z.object({\n /** Field name to filter on */\n field: z.string().describe('Field name to filter on'),\n\n /** Display label for the filter */\n label: I18nLabelSchema.optional().describe('Display label for the filter'),\n\n /** Filter input type */\n type: z.enum(['text', 'select', 'date', 'number', 'lookup']).optional().describe('Filter input type'),\n\n /** Static options for select/lookup filters */\n options: z.array(z.object({\n value: z.union([z.string(), z.number(), z.boolean()]).describe('Option value'),\n label: I18nLabelSchema,\n })).optional().describe('Static filter options'),\n\n /** Dynamic data binding for filter options */\n optionsFrom: GlobalFilterOptionsFromSchema.optional().describe('Dynamic filter options from object'),\n\n /** Default filter value */\n defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional().describe('Default filter value'),\n\n /** Filter application scope */\n scope: z.enum(['dashboard', 'widget']).default('dashboard').describe('Filter application scope'),\n\n /** Widget IDs to apply this filter to (when scope is widget) */\n targetWidgets: z.array(z.string()).optional().describe('Widget IDs to apply this filter to'),\n});\n\n/**\n * Dashboard Schema\n * Represents a page containing multiple visualizations.\n * \n * @example Sales Executive Dashboard\n * {\n * name: \"sales_overview\",\n * label: \"Sales Executive Overview\",\n * widgets: [\n * {\n * title: \"Total Pipe\",\n * type: \"metric\",\n * object: \"opportunity\",\n * valueField: \"amount\",\n * aggregate: \"sum\",\n * layout: { x: 0, y: 0, w: 3, h: 2 }\n * },\n * {\n * title: \"Revenue by Region\",\n * type: \"bar\",\n * object: \"order\",\n * categoryField: \"region\",\n * valueField: \"total\",\n * aggregate: \"sum\",\n * layout: { x: 3, y: 0, w: 6, h: 4 }\n * }\n * ]\n * }\n */\nexport const DashboardSchema = z.object({\n /** Machine name */\n name: SnakeCaseIdentifierSchema.describe('Dashboard unique name'),\n \n /** Display label */\n label: I18nLabelSchema.describe('Dashboard label'),\n \n /** Description */\n description: I18nLabelSchema.optional().describe('Dashboard description'),\n\n /** Structured header configuration */\n header: DashboardHeaderSchema.optional().describe('Dashboard header configuration'),\n \n /** Collection of widgets */\n widgets: z.array(DashboardWidgetSchema).describe('Widgets to display'),\n\n /** Auto-refresh */\n refreshInterval: z.number().optional().describe('Auto-refresh interval in seconds'),\n\n /** Dashboard Date Range (Global time filter) */\n dateRange: z.object({\n field: z.string().optional().describe('Default date field name for time-based filtering'),\n defaultRange: z.enum(['today', 'yesterday', 'this_week', 'last_week', 'this_month', 'last_month', 'this_quarter', 'last_quarter', 'this_year', 'last_year', 'last_7_days', 'last_30_days', 'last_90_days', 'custom']).default('this_month').describe('Default date range preset'),\n allowCustomRange: z.boolean().default(true).describe('Allow users to pick a custom date range'),\n }).optional().describe('Global dashboard date range filter configuration'),\n\n /** Global Filters */\n globalFilters: z.array(GlobalFilterSchema).optional().describe('Global filters that apply to all widgets in the dashboard'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\nexport type Dashboard = z.infer;\nexport type DashboardInput = z.input;\nexport type DashboardWidget = z.infer;\nexport type DashboardHeader = z.infer;\nexport type DashboardHeaderAction = z.infer;\nexport type WidgetMeasure = z.infer;\nexport type WidgetColorVariant = z.infer;\nexport type WidgetActionType = z.infer;\nexport type GlobalFilter = z.infer;\nexport type GlobalFilterOptionsFrom = z.infer;\n\n/**\n * Dashboard Factory Helper\n */\nexport const Dashboard = {\n create: (config: z.input): Dashboard => DashboardSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ChartConfigSchema } from './chart.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema, PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Report Type Enum\n */\nexport const ReportType = z.enum([\n 'tabular', // Simple list\n 'summary', // Grouped by row\n 'matrix', // Grouped by row and column\n 'joined' // Joined multiple blocks\n]);\n\n/**\n * Report Column Schema\n */\nexport const ReportColumnSchema = z.object({\n field: z.string().describe('Field name'),\n label: I18nLabelSchema.optional().describe('Override label'),\n aggregate: z.enum(['sum', 'avg', 'max', 'min', 'count', 'unique']).optional().describe('Aggregation function'),\n /** Responsive visibility/priority per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive visibility for this column'),\n});\n\n/**\n * Report Grouping Schema\n */\nexport const ReportGroupingSchema = z.object({\n field: z.string().describe('Field to group by'),\n sortOrder: z.enum(['asc', 'desc']).default('asc'),\n dateGranularity: z.enum(['day', 'week', 'month', 'quarter', 'year']).optional().describe('For date fields'),\n});\n\n/**\n * Report Chart Schema\n * Embedded visualization configuration using unified chart taxonomy.\n */\nexport const ReportChartSchema = ChartConfigSchema.extend({\n /** Report-specific chart configuration */\n xAxis: z.string().describe('Grouping field for X-Axis'),\n yAxis: z.string().describe('Summary field for Y-Axis'),\n groupBy: z.string().optional().describe('Additional grouping field'),\n});\n\n/**\n * Report Schema\n * Deep data analysis definition.\n */\nexport const ReportSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Report unique name'),\n label: I18nLabelSchema.describe('Report label'),\n description: I18nLabelSchema.optional(),\n \n /** Data Source */\n objectName: z.string().describe('Primary object'),\n \n /** Report Configuration */\n type: ReportType.default('tabular').describe('Report format type'),\n \n columns: z.array(ReportColumnSchema).describe('Columns to display'),\n \n /** Grouping (for Summary/Matrix) */\n groupingsDown: z.array(ReportGroupingSchema).optional().describe('Row groupings'),\n groupingsAcross: z.array(ReportGroupingSchema).optional().describe('Column groupings (Matrix only)'),\n \n /** Filtering (MongoDB-style FilterCondition) */\n filter: FilterConditionSchema.optional().describe('Filter criteria'),\n \n /** Visualization */\n chart: ReportChartSchema.optional().describe('Embedded chart configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\n/**\n * Report Types\n * \n * Note: For configuration/definition contexts, use the Input types (e.g., ReportInput)\n * which allow optional fields with defaults to be omitted.\n */\nexport type Report = z.infer;\nexport type ReportColumn = z.infer;\nexport type ReportGrouping = z.infer;\nexport type ReportChart = z.infer;\n\n/**\n * Input Types for Report Configuration\n * Use these when defining reports in configuration files.\n */\nexport type ReportInput = z.input;\nexport type ReportColumnInput = z.input;\nexport type ReportGroupingInput = z.input;\nexport type ReportChartInput = z.input;\n\n/**\n * Report Factory Helper\n */\nexport const Report = {\n create: (config: ReportInput): Report => ReportSchema.parse(config),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { SortItemSchema } from '../shared/enums.zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { ResponsiveConfigSchema } from './responsive.zod';\nimport {\n UserActionsConfigSchema,\n AppearanceConfigSchema,\n ViewTabSchema,\n ViewFilterRuleSchema,\n AddRecordConfigSchema,\n} from './view.zod';\n\n/**\n * Page Region Schema\n * A named region in the template where components are dropped.\n */\nexport const PageRegionSchema = z.object({\n name: z.string().describe('Region name (e.g. \"sidebar\", \"main\", \"header\")'),\n width: z.enum(['small', 'medium', 'large', 'full']).optional(),\n components: z.array(z.lazy(() => PageComponentSchema)).describe('Components in this region')\n});\n\n/**\n * Standard Page Component Types\n */\nexport const PageComponentType = z.enum([\n // Structure\n 'page:header', 'page:footer', 'page:sidebar', 'page:tabs', 'page:accordion', 'page:card', 'page:section',\n // Record Context\n 'record:details', 'record:highlights', 'record:related_list', 'record:activity', 'record:chatter', 'record:path',\n // Navigation\n 'app:launcher', 'nav:menu', 'nav:breadcrumb',\n // Utility\n 'global:search', 'global:notifications', 'user:profile',\n // AI\n 'ai:chat_window', 'ai:suggestion',\n // Content Elements (Airtable Interface parity)\n 'element:text', 'element:number', 'element:image', 'element:divider',\n // Interactive Elements (Phase B — Element Library)\n 'element:button', 'element:filter', 'element:form', 'element:record_picker'\n]);\n\n/**\n * Element Data Source Schema\n * Per-element data binding for multi-object pages.\n * Overrides page-level object context so each element can query a different object.\n */\nexport const ElementDataSourceSchema = z.object({\n object: z.string().describe('Object to query'),\n view: z.string().optional().describe('Named view to apply'),\n filter: FilterConditionSchema.optional().describe('Additional filter criteria'),\n sort: z.array(SortItemSchema).optional().describe('Sort order'),\n limit: z.number().int().positive().optional().describe('Max records to display'),\n});\n\n/**\n * Page Component Schema\n * A configured instance of a UI component.\n */\nexport const PageComponentSchema = z.object({\n /** Definition */\n type: z.union([\n PageComponentType,\n z.string()\n ]).describe('Component Type (Standard enum or custom string)'),\n id: z.string().optional().describe('Unique instance ID'),\n \n /** Configuration */\n label: I18nLabelSchema.optional(),\n properties: z.record(z.string(), z.unknown()).describe('Component props passed to the widget. See component.zod.ts for schemas.'),\n \n /** \n * Event Handlers \n * Map event names to Action expressions.\n * \"onClick\": \"set_variable('userId', $event.id)\"\n * \"onRowSelect\": \"navigate_to('page_detail', { id: $event.id })\"\n */\n events: z.record(z.string(), z.string()).optional().describe('Event handlers map'),\n\n /** Appearance */\n style: z.record(z.string(), z.string()).optional().describe('Inline styles or utility classes'),\n className: z.string().optional().describe('CSS class names'),\n\n /** Visibility Rule */\n visibility: z.string().optional().describe('Visibility filter/formula'),\n\n /** Per-element data binding, overrides page-level object context */\n dataSource: ElementDataSourceSchema.optional().describe('Per-element data binding for multi-object pages'),\n\n /** Responsive layout overrides per breakpoint */\n responsive: ResponsiveConfigSchema.optional().describe('Responsive layout configuration'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * Page Variable Schema\n * Defines local state for the page.\n * Variables can be bound to interactive elements (e.g. element:record_picker, element:filter).\n */\nexport const PageVariableSchema = z.object({\n name: z.string().describe('Variable name'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array', 'record_id']).default('string'),\n defaultValue: z.unknown().optional(),\n /** Source element binding (e.g. element:record_picker writes to this variable) */\n source: z.string().optional().describe('Component ID that writes to this variable'),\n});\n\n/**\n * Blank Page Layout Item Schema\n * Positions a component on a free-form grid canvas.\n */\nexport const BlankPageLayoutItemSchema = z.object({\n componentId: z.string().describe('Reference to a PageComponent.id in the page'),\n x: z.number().int().min(0).describe('Grid column position (0-based)'),\n y: z.number().int().min(0).describe('Grid row position (0-based)'),\n width: z.number().int().min(1).describe('Width in grid columns'),\n height: z.number().int().min(1).describe('Height in grid rows'),\n});\n\n/**\n * Blank Page Layout Schema\n * Free-form canvas composition with grid-based positioning.\n * Used when page type is 'blank' to enable drag-and-drop element placement.\n */\nexport const BlankPageLayoutSchema = z.object({\n columns: z.number().int().min(1).default(12).describe('Number of grid columns'),\n rowHeight: z.number().int().min(1).default(40).describe('Height of each grid row in pixels'),\n gap: z.number().int().min(0).default(8).describe('Gap between grid items in pixels'),\n items: z.array(BlankPageLayoutItemSchema).describe('Positioned components on the canvas'),\n});\n\n/**\n * Page Type Schema\n * Unified page type enum covering both platform pages (Salesforce FlexiPage style)\n * and Airtable-inspired interface page types.\n *\n * **Disambiguation of similar types:**\n * - `record` vs `record_detail`: `record` is a component-based layout page (FlexiPage style with regions),\n * `record_detail` is a field-display page showing all fields of a single record (Airtable style).\n * Use `record` for custom record pages with regions/components, `record_detail` for auto-generated detail views.\n * - `home` vs `overview`: `home` is the platform-level landing page (tab landing),\n * `overview` is an interface-level navigation hub with links/instructions.\n * Use `home` for app-level landing, `overview` for in-interface navigation hubs.\n * - `app` vs `utility` vs `blank`: `app` is an app-level page with navigation context,\n * `utility` is a floating utility panel (e.g. notes, phone), `blank` is a free-form canvas\n * for custom composition. They serve distinct layout purposes.\n */\nexport const PageTypeSchema = z.enum([\n // Platform page types (Salesforce FlexiPage style)\n 'record', // Component-based record layout page with regions\n 'home', // Platform-level home/landing page\n 'app', // App-level page with navigation context\n 'utility', // Floating utility panel (e.g. notes, phone dialer)\n // Interface page types (Airtable Interface parity)\n 'dashboard', // KPI summary with charts/metrics\n 'grid', // Spreadsheet-like data table\n 'list', // Record list with quick actions\n 'gallery', // Card-based visual browsing\n 'kanban', // Status-based board\n 'calendar', // Date-based scheduling\n 'timeline', // Gantt-like project timeline\n 'form', // Data entry form\n 'record_detail', // Auto-generated single record field display\n 'record_review', // Sequential record review/approval\n 'overview', // Interface-level navigation/landing hub\n 'blank', // Free-form canvas for custom composition\n]).describe('Page type — platform or interface page types');\n\n/**\n * Record Review Config Schema\n * Configuration for a sequential record review/approval page.\n * Users navigate through records one-by-one, taking actions (approve/reject/skip).\n * Only applicable when page type is 'record_review'.\n */\nexport const RecordReviewConfigSchema = z.object({\n object: z.string().describe('Target object for review'),\n filter: FilterConditionSchema.optional().describe('Filter criteria for review queue'),\n sort: z.array(SortItemSchema).optional().describe('Sort order for review queue'),\n displayFields: z.array(z.string()).optional()\n .describe('Fields to display on the review page'),\n actions: z.array(z.object({\n label: z.string().describe('Action button label'),\n type: z.enum(['approve', 'reject', 'skip', 'custom'])\n .describe('Action type'),\n field: z.string().optional()\n .describe('Field to update on action'),\n value: z.union([z.string(), z.number(), z.boolean()]).optional()\n .describe('Value to set on action'),\n nextRecord: z.boolean().optional().default(true)\n .describe('Auto-advance to next record after action'),\n })).describe('Review actions'),\n navigation: z.enum(['sequential', 'random', 'filtered'])\n .optional().default('sequential')\n .describe('Record navigation mode'),\n showProgress: z.boolean().optional().default(true)\n .describe('Show review progress indicator'),\n});\n\n/**\n * Interface Page Configuration Schema (Airtable Interface parity)\n * Page-level declarative configuration for Airtable-style interface pages.\n * Covers title/data binding, levels, filter by, appearance, user actions,\n * tabs, record count, add record, and advanced options (printing).\n *\n * @see Airtable Interface → right panel (Page / Data / Appearance / User filters / User actions / Advanced)\n */\nexport const InterfacePageConfigSchema = z.object({\n /** Data binding */\n source: z.string().optional().describe('Source object name for the page'),\n levels: z.number().int().min(1).optional().describe('Number of hierarchy levels to display'),\n filterBy: z.array(ViewFilterRuleSchema).optional().describe('Page-level filter criteria'),\n\n /** Appearance */\n appearance: AppearanceConfigSchema.optional().describe('Appearance and visualization configuration'),\n\n /** User filters */\n userFilters: z.object({\n elements: z.array(z.enum(['grid', 'gallery', 'kanban'])).optional()\n .describe('Visualization element types available in user filter bar'),\n tabs: z.array(ViewTabSchema).optional().describe('User-configurable tabs'),\n }).optional().describe('User filter configuration'),\n\n /** User actions */\n userActions: UserActionsConfigSchema.optional().describe('User action toggles'),\n\n /** Add record */\n addRecord: AddRecordConfigSchema.optional().describe('Add record entry point configuration'),\n\n /** Record count */\n showRecordCount: z.boolean().optional().describe('Show record count at page bottom'),\n\n /** Advanced */\n allowPrinting: z.boolean().optional().describe('Allow users to print the page'),\n}).describe('Interface-level page configuration (Airtable parity)');\n\n/**\n * Page Schema\n * Defines a composition of components for a specific context.\n * Supports both platform pages (Salesforce FlexiPage style: record, home, app, utility)\n * and interface pages (Airtable Interface style: dashboard, grid, kanban, record_review, etc.).\n * \n * **NAMING CONVENTION:**\n * Page names are used in routing and must be lowercase snake_case.\n * Prefix with 'page_' is recommended for clarity.\n * \n * @example Good page names\n * - 'page_dashboard'\n * - 'page_settings'\n * - 'home_page'\n * - 'record_detail'\n * \n * @example Bad page names (will be rejected)\n * - 'PageDashboard' (PascalCase)\n * - 'Settings Page' (spaces)\n */\nexport const PageSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Page unique name (lowercase snake_case)'),\n label: I18nLabelSchema,\n description: I18nLabelSchema.optional(),\n\n /** Icon (used in interface navigation) */\n icon: z.string().optional().describe('Page icon name'),\n \n /** Page Type */\n type: PageTypeSchema.default('record').describe('Page type'),\n \n /** Page State Definitions */\n variables: z.array(PageVariableSchema).optional().describe('Local page state variables'),\n\n /** Context */\n object: z.string().optional().describe('Bound object (for Record pages)'),\n\n /** Record Review Configuration (only for record_review pages) */\n recordReview: RecordReviewConfigSchema.optional()\n .describe('Record review configuration (required when type is \"record_review\")'),\n\n /** Blank Page Layout (only for blank pages) */\n blankLayout: BlankPageLayoutSchema.optional()\n .describe('Free-form grid layout for blank pages (used when type is \"blank\")'),\n \n /** Layout Template */\n template: z.string().default('default').describe('Layout template name (e.g. \"header-sidebar-main\")'),\n \n /** Regions & Content */\n regions: z.array(PageRegionSchema).describe('Defined regions with components'),\n \n /** Activation */\n isDefault: z.boolean().default(false),\n assignedProfiles: z.array(z.string()).optional(),\n\n /** Interface Page Configuration (Airtable Interface parity) */\n interfaceConfig: InterfacePageConfigSchema.optional()\n .describe('Interface-level page configuration (for Airtable-style interface pages)'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n}).superRefine((data, ctx) => {\n if (data.type === 'record_review' && !data.recordReview) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['recordReview'],\n message: 'recordReview is required when type is \"record_review\"',\n });\n }\n if (data.type === 'blank' && !data.blankLayout) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['blankLayout'],\n message: 'blankLayout is required when type is \"blank\"',\n });\n }\n});\n\nexport type Page = z.infer;\nexport type PageType = z.infer;\nexport type PageComponent = z.infer;\nexport type PageRegion = z.infer;\nexport type PageVariable = z.infer;\nexport type ElementDataSource = z.infer;\nexport type RecordReviewConfig = z.infer;\nexport type BlankPageLayoutItem = z.infer;\nexport type BlankPageLayout = z.infer;\nexport type InterfacePageConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from '../data/field.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { PerformanceConfigSchema } from './responsive.zod';\n\n/**\n * Widget Lifecycle Hooks Schema\n * \n * Defines lifecycle callbacks for custom widgets inspired by Web Components and React.\n * These hooks allow widgets to perform initialization, cleanup, and respond to changes.\n * \n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components\n * @see https://react.dev/reference/react/Component#component-lifecycle\n * \n * @example\n * ```typescript\n * const widget = {\n * lifecycle: {\n * onMount: \"console.log('Widget mounted')\",\n * onUpdate: \"if (prevProps.value !== props.value) { updateUI() }\",\n * onUnmount: \"cleanup()\",\n * onValidate: \"return value.length > 0 ? null : 'Required field'\"\n * }\n * }\n * ```\n */\nexport const WidgetLifecycleSchema = z.object({\n /**\n * Called when widget is mounted/rendered for the first time\n * Use for initialization, setting up event listeners, loading data, etc.\n * \n * @example \"initializeDatePicker(); loadOptions();\"\n */\n onMount: z.string().optional().describe('Initialization code when widget mounts'),\n\n /**\n * Called when widget props change\n * Receives previous props for comparison\n * \n * @example \"if (prevProps.value !== props.value) { updateDisplay() }\"\n */\n onUpdate: z.string().optional().describe('Code to run when props change'),\n\n /**\n * Called when widget is about to be removed from DOM\n * Use for cleanup, removing event listeners, canceling timers, etc.\n * \n * @example \"destroyDatePicker(); cancelPendingRequests();\"\n */\n onUnmount: z.string().optional().describe('Cleanup code when widget unmounts'),\n\n /**\n * Custom validation logic for this widget\n * Should return error message string if invalid, null/undefined if valid\n * \n * @example \"return value && value.length >= 10 ? null : 'Minimum 10 characters'\"\n */\n onValidate: z.string().optional().describe('Custom validation logic'),\n\n /**\n * Called when widget receives focus\n * \n * @example \"highlightField(); logFocusEvent();\"\n */\n onFocus: z.string().optional().describe('Code to run on focus'),\n\n /**\n * Called when widget loses focus\n * \n * @example \"validateField(); saveFieldState();\"\n */\n onBlur: z.string().optional().describe('Code to run on blur'),\n\n /**\n * Called on any error in the widget\n * \n * @example \"logError(error); showErrorNotification();\"\n */\n onError: z.string().optional().describe('Error handling code'),\n});\n\nexport type WidgetLifecycle = z.infer;\n\n/**\n * Widget Event Schema\n * \n * Defines custom events that widgets can emit, inspired by DOM Events and Lightning Web Components.\n * \n * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events\n * @see https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.events\n * \n * @example\n * ```typescript\n * const searchEvent = {\n * name: 'search',\n * bubbles: true,\n * cancelable: false,\n * payload: {\n * query: 'string',\n * filters: 'object'\n * }\n * }\n * ```\n */\nexport const WidgetEventSchema = z.object({\n /**\n * Event name\n * Should be lowercase, dash-separated for consistency\n * \n * @example \"value-change\", \"item-selected\", \"search-complete\"\n */\n name: z.string().describe('Event name'),\n\n /**\n * Event label for documentation\n */\n label: I18nLabelSchema.optional().describe('Human-readable event label'),\n\n /**\n * Event description\n */\n description: I18nLabelSchema.optional().describe('Event description and usage'),\n\n /**\n * Whether event bubbles up through the DOM hierarchy\n * \n * @default false\n */\n bubbles: z.boolean().default(false).describe('Whether event bubbles'),\n\n /**\n * Whether event can be cancelled\n * \n * @default false\n */\n cancelable: z.boolean().default(false).describe('Whether event is cancelable'),\n\n /**\n * Event payload schema\n * Defines the data structure sent with the event\n * \n * @example { userId: 'string', timestamp: 'number' }\n */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event payload schema'),\n});\n\nexport type WidgetEvent = z.infer;\n\n/**\n * Widget Property Definition Schema\n * \n * Defines the contract for widget configuration properties.\n * Inspired by React PropTypes and Web Component attributes.\n * \n * @see https://react.dev/reference/react/Component#static-proptypes\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements\n * \n * @example\n * ```typescript\n * const widgetProps = {\n * maxLength: {\n * type: 'number',\n * required: false,\n * default: 100,\n * description: 'Maximum input length'\n * }\n * }\n * ```\n */\nexport const WidgetPropertySchema = z.object({\n /**\n * Property name\n * Should be camelCase following ObjectStack conventions\n */\n name: z.string().describe('Property name (camelCase)'),\n\n /**\n * Property label for UI\n */\n label: I18nLabelSchema.optional().describe('Human-readable label'),\n\n /**\n * Property data type\n * \n * @example \"string\", \"number\", \"boolean\", \"array\", \"object\", \"function\"\n */\n type: z.enum(['string', 'number', 'boolean', 'array', 'object', 'function', 'any'])\n .describe('TypeScript type'),\n\n /**\n * Whether property is required\n * \n * @default false\n */\n required: z.boolean().default(false).describe('Whether property is required'),\n\n /**\n * Default value for the property\n */\n default: z.unknown().optional().describe('Default value'),\n\n /**\n * Property description\n */\n description: I18nLabelSchema.optional().describe('Property description'),\n\n /**\n * Property validation schema\n * Can include min/max, regex, enum values, etc.\n */\n validation: z.record(z.string(), z.unknown()).optional().describe('Validation rules'),\n\n /**\n * Property category for grouping in UI\n */\n category: z.string().optional().describe('Property category'),\n});\n\nexport type WidgetProperty = z.infer;\n\n/**\n * Widget Manifest Schema\n * \n * Complete definition for a custom widget including metadata, lifecycle, events, and props.\n * This is used for widget registration and discovery.\n * \n * @example\n * ```typescript\n * const customWidget = {\n * name: 'custom_date_picker',\n * label: 'Custom Date Picker',\n * version: '1.0.0',\n * author: 'Company Name',\n * fieldTypes: ['date', 'datetime'],\n * lifecycle: { ... },\n * events: [ ... ],\n * properties: [ ... ]\n * }\n * ```\n */\n/**\n * Widget Source Schema\n * Defines how the widget code is loaded.\n */\nexport const WidgetSourceSchema = z.discriminatedUnion('type', [\n // NPM Registry (standard)\n z.object({\n type: z.literal('npm'),\n packageName: z.string().describe('NPM package name'),\n version: z.string().default('latest'),\n exportName: z.string().optional().describe('Named export (default: default)'),\n }),\n // Module Federation (Remote)\n z.object({\n type: z.literal('remote'),\n url: z.string().url().describe('Remote entry URL (.js)'),\n moduleName: z.string().describe('Exposed module name'),\n scope: z.string().describe('Remote scope name'),\n }),\n // Inline Code (Simple scripts)\n z.object({\n type: z.literal('inline'),\n code: z.string().describe('JavaScript code body'),\n }),\n]);\n\nexport type WidgetSource = z.infer;\n\nexport const WidgetManifestSchema = z.object({\n /**\n * Widget identifier (snake_case)\n */\n name: SnakeCaseIdentifierSchema\n .describe('Widget identifier (snake_case)'),\n\n /**\n * Human-readable widget name\n */\n label: I18nLabelSchema.describe('Widget display name'),\n\n /**\n * Widget description\n */\n description: I18nLabelSchema.optional().describe('Widget description'),\n\n /**\n * Widget version (semver)\n */\n version: z.string().optional().describe('Widget version (semver)'),\n\n /**\n * Widget author/organization\n */\n author: z.string().optional().describe('Widget author'),\n\n /**\n * Icon name or URL\n */\n icon: z.string().optional().describe('Widget icon'),\n\n /**\n * Field types this widget supports\n * \n * @example [\"text\", \"email\", \"url\"]\n */\n fieldTypes: z.array(z.string()).optional().describe('Supported field types'),\n\n /**\n * Widget category for organization\n */\n category: z.enum(['input', 'display', 'picker', 'editor', 'custom'])\n .default('custom')\n .describe('Widget category'),\n\n /**\n * Widget lifecycle hooks\n */\n lifecycle: WidgetLifecycleSchema.optional().describe('Lifecycle hooks'),\n\n /**\n * Custom events this widget emits\n */\n events: z.array(WidgetEventSchema).optional().describe('Custom events'),\n\n /**\n * Widget configuration properties\n */\n properties: z.array(WidgetPropertySchema).optional().describe('Configuration properties'),\n\n /**\n * Widget implementation\n * Defines how to load the widget code\n */\n implementation: WidgetSourceSchema.optional().describe('Widget implementation source'),\n\n /**\n * Widget dependencies\n * External libraries or scripts needed\n */\n dependencies: z.array(z.object({\n name: z.string(),\n version: z.string().optional(),\n url: z.string().url().optional(),\n })).optional().describe('Widget dependencies'),\n\n /**\n * Widget screenshots for showcase\n */\n screenshots: z.array(z.string().url()).optional().describe('Screenshot URLs'),\n\n /**\n * Widget documentation URL\n */\n documentation: z.string().url().optional().describe('Documentation URL'),\n\n /**\n * License information\n */\n license: z.string().optional().describe('License (SPDX identifier)'),\n\n /**\n * Tags for discovery\n */\n tags: z.array(z.string()).optional().describe('Tags for categorization'),\n\n /** ARIA accessibility attributes */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n\n /** Performance optimization settings */\n performance: PerformanceConfigSchema.optional().describe('Performance optimization settings'),\n});\n\nexport type WidgetManifest = z.infer;\n\n/**\n * Field Widget Props Schema\n * \n * This defines the contract for custom field components and plugin UI extensions.\n * Third-party developers use this interface to build custom field widgets that integrate\n * seamlessly with the ObjectStack UI system.\n * \n * @example\n * // Custom widget implementation\n * function CustomDatePicker(props: FieldWidgetProps) {\n * const { value, onChange, readonly, required, error, field, record, options } = props;\n * // Widget implementation...\n * }\n */\nexport const FieldWidgetPropsSchema = z.object({\n /**\n * Current field value.\n * Type depends on the field type (string, number, boolean, array, object, etc.)\n */\n value: z.unknown().describe('Current field value'),\n\n /**\n * Callback function to update the field value.\n * Should be called when user interaction changes the value.\n * \n * @param newValue - The new value to set\n */\n onChange: z.function()\n .input(z.tuple([z.unknown()]))\n .output(z.void())\n .describe('Callback to update field value'),\n\n /**\n * Whether the field is in read-only mode.\n * When true, the widget should display the value but not allow editing.\n */\n readonly: z.boolean().default(false).describe('Read-only mode flag'),\n\n /**\n * Whether the field is required.\n * Widget should indicate required state visually and validate accordingly.\n */\n required: z.boolean().default(false).describe('Required field flag'),\n\n /**\n * Validation error message to display.\n * When present, widget should display the error in its UI.\n */\n error: z.string().optional().describe('Validation error message'),\n\n /**\n * Complete field definition from the schema.\n * Contains metadata like type, constraints, options, etc.\n */\n field: FieldSchema.describe('Field schema definition'),\n\n /**\n * The complete record/document being edited.\n * Useful for conditional logic and cross-field dependencies.\n */\n record: z.record(z.string(), z.unknown()).optional().describe('Complete record data'),\n\n /**\n * Custom options passed to the widget.\n * Can contain widget-specific configuration like themes, behaviors, etc.\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Custom widget options'),\n});\n\n/**\n * TypeScript type for Field Widget Props\n */\nexport type FieldWidgetProps = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FilterConditionSchema } from '../data/filter.zod';\nimport { ViewFilterRuleSchema } from './view.zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\nimport { FeedItemType, FeedFilterMode } from '../data/feed.zod';\n\n/**\n * Empty Properties Schema\n */\nconst EmptyProps = z.object({});\n\n/**\n * ----------------------------------------------------------------------\n * 1. Structure Components\n * ----------------------------------------------------------------------\n */\n\nexport const PageHeaderProps = z.object({\n title: I18nLabelSchema.describe('Page title'),\n subtitle: I18nLabelSchema.optional().describe('Page subtitle'),\n icon: z.string().optional().describe('Icon name'),\n breadcrumb: z.boolean().default(true).describe('Show breadcrumb'),\n actions: z.array(z.string()).optional().describe('Action IDs to show in header'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageTabsProps = z.object({\n type: z.enum(['line', 'card', 'pill']).default('line'),\n position: z.enum(['top', 'left']).default('top'),\n items: z.array(z.object({\n label: I18nLabelSchema,\n icon: z.string().optional(),\n children: z.array(z.unknown()).describe('Child components')\n })),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageCardProps = z.object({\n title: I18nLabelSchema.optional(),\n bordered: z.boolean().default(true),\n actions: z.array(z.string()).optional(),\n /** Slot for nested content in the Card body */\n body: z.array(z.unknown()).optional().describe('Card content components (slot)'),\n /** Slot for footer content */\n footer: z.array(z.unknown()).optional().describe('Card footer components (slot)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 2. Record Context Components\n * ----------------------------------------------------------------------\n */\n\nexport const RecordDetailsProps = z.object({\n columns: z.enum(['1', '2', '3', '4']).default('2').describe('Number of columns for field layout (1-4)'),\n layout: z.enum(['auto', 'custom']).default('auto').describe('Layout mode: auto uses object compactLayout, custom uses explicit sections'),\n sections: z.array(z.string()).optional().describe('Section IDs to show (required when layout is \"custom\")'),\n fields: z.array(z.string()).optional().describe('Explicit field list to display (optional, overrides compactLayout)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordRelatedListProps = z.object({\n objectName: z.string().describe('Related object name (e.g., \"task\", \"opportunity\")'),\n relationshipField: z.string().describe('Field on related object that points to this record (e.g., \"account_id\")'),\n columns: z.array(z.string()).describe('Fields to display in the related list'),\n sort: z.union([\n z.string(),\n z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc'])\n }))\n ]).optional().describe('Sort order for related records'),\n limit: z.number().int().positive().default(5).describe('Number of records to display initially'),\n filter: z.array(ViewFilterRuleSchema).optional().describe('Additional filter criteria for related records'),\n title: I18nLabelSchema.optional().describe('Custom title for the related list'),\n showViewAll: z.boolean().default(true).describe('Show \"View All\" link to see all related records'),\n actions: z.array(z.string()).optional().describe('Action IDs available for related records'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordHighlightsProps = z.object({\n fields: z.array(z.string()).min(1).max(7).describe('Key fields to highlight (1-7 fields max, typically displayed as prominent cards)'),\n layout: z.enum(['horizontal', 'vertical']).default('horizontal').describe('Layout orientation for highlight fields'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordActivityProps = z.object({\n /** Activity types to display (unified enum including comment, field_change, etc.) */\n types: z.array(FeedItemType).optional().describe('Feed item types to show (default: all)'),\n /** Default filter mode (Airtable-style dropdown) */\n filterMode: FeedFilterMode.default('all').describe('Default activity filter'),\n /** Allow user to switch filter modes */\n showFilterToggle: z.boolean().default(true).describe('Show filter dropdown in panel header'),\n /** Pagination */\n limit: z.number().int().positive().default(20).describe('Number of items to load per page'),\n /** Show completed activities */\n showCompleted: z.boolean().default(false).describe('Include completed activities'),\n /** Merge field_change + comment in a unified timeline */\n unifiedTimeline: z.boolean().default(true).describe('Mix field changes and comments in one timeline (Airtable style)'),\n /** Show the comment input box at the bottom */\n showCommentInput: z.boolean().default(true).describe('Show \"Leave a comment\" input at the bottom'),\n /** Enable @mentions in comments */\n enableMentions: z.boolean().default(true).describe('Enable @mentions in comments'),\n /** Enable emoji reactions */\n enableReactions: z.boolean().default(false).describe('Enable emoji reactions on feed items'),\n /** Enable threaded replies */\n enableThreading: z.boolean().default(false).describe('Enable threaded replies on comments'),\n /** Show notification subscription toggle (bell icon) */\n showSubscriptionToggle: z.boolean().default(true).describe('Show bell icon for record-level notification subscription'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordChatterProps = z.object({\n /** Panel position */\n position: z.enum(['sidebar', 'inline', 'drawer']).default('sidebar').describe('Where to render the chatter panel'),\n /** Panel width (for sidebar/drawer) */\n width: z.union([z.string(), z.number()]).optional().describe('Panel width (e.g., \"350px\", \"30%\")'),\n /** Collapsible */\n collapsible: z.boolean().default(true).describe('Whether the panel can be collapsed'),\n /** Default collapsed state */\n defaultCollapsed: z.boolean().default(false).describe('Whether the panel starts collapsed'),\n /** Feed configuration (delegates to RecordActivityProps) */\n feed: RecordActivityProps.optional().describe('Embedded activity feed configuration'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const RecordPathProps = z.object({\n statusField: z.string().describe('Field name representing the current status/stage'),\n stages: z.array(z.object({\n value: z.string(),\n label: I18nLabelSchema,\n })).optional().describe('Explicit stage definitions (if not using field metadata)'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const PageAccordionProps = z.object({\n items: z.array(z.object({\n label: I18nLabelSchema,\n icon: z.string().optional(),\n collapsed: z.boolean().default(false),\n children: z.array(z.unknown()).describe('Child components'),\n })),\n allowMultiple: z.boolean().default(false).describe('Allow multiple panels to be expanded simultaneously'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const AIChatWindowProps = z.object({\n mode: z.enum(['float', 'sidebar', 'inline']).default('float').describe('Display mode for the chat window'),\n agentId: z.string().optional().describe('Specific AI agent to use'),\n context: z.record(z.string(), z.unknown()).optional().describe('Contextual data to pass to the AI'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 3. Content Element Components (Airtable Interface Parity)\n * ----------------------------------------------------------------------\n */\n\nexport const ElementTextPropsSchema = z.object({\n content: z.string().describe('Text or Markdown content'),\n variant: z.enum(['heading', 'subheading', 'body', 'caption'])\n .optional().default('body').describe('Text style variant'),\n align: z.enum(['left', 'center', 'right'])\n .optional().default('left').describe('Text alignment'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementNumberPropsSchema = z.object({\n object: z.string().describe('Source object'),\n field: z.string().optional().describe('Field to aggregate'),\n aggregate: z.enum(['count', 'sum', 'avg', 'min', 'max'])\n .describe('Aggregation function'),\n filter: FilterConditionSchema.optional().describe('Filter criteria'),\n format: z.enum(['number', 'currency', 'percent']).optional().describe('Number display format'),\n prefix: z.string().optional().describe('Prefix text (e.g. \"$\")'),\n suffix: z.string().optional().describe('Suffix text (e.g. \"%\")'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementImagePropsSchema = z.object({\n src: z.string().describe('Image URL or attachment field'),\n alt: z.string().optional().describe('Alt text for accessibility'),\n fit: z.enum(['cover', 'contain', 'fill'])\n .optional().default('cover').describe('Image object-fit mode'),\n height: z.number().optional().describe('Fixed height in pixels'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * 4. Interactive Element Components (Phase B — Element Library)\n * ----------------------------------------------------------------------\n */\n\nexport const ElementButtonPropsSchema = z.object({\n label: I18nLabelSchema.describe('Button display label'),\n variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link'])\n .optional().default('primary').describe('Button visual variant'),\n size: z.enum(['small', 'medium', 'large'])\n .optional().default('medium').describe('Button size'),\n icon: z.string().optional().describe('Icon name (Lucide icon)'),\n iconPosition: z.enum(['left', 'right'])\n .optional().default('left').describe('Icon position relative to label'),\n disabled: z.boolean().optional().default(false).describe('Disable the button'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementFilterPropsSchema = z.object({\n object: z.string().describe('Object to filter'),\n fields: z.array(z.string()).describe('Filterable field names'),\n targetVariable: z.string().optional().describe('Page variable to store filter state'),\n layout: z.enum(['inline', 'dropdown', 'sidebar'])\n .optional().default('inline').describe('Filter display layout'),\n showSearch: z.boolean().optional().default(true).describe('Show search input'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementFormPropsSchema = z.object({\n object: z.string().describe('Object for the form'),\n fields: z.array(z.string()).optional().describe('Fields to display (defaults to all editable fields)'),\n mode: z.enum(['create', 'edit']).optional().default('create').describe('Form mode'),\n submitLabel: I18nLabelSchema.optional().describe('Submit button label'),\n onSubmit: z.string().optional().describe('Action expression on form submit'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\nexport const ElementRecordPickerPropsSchema = z.object({\n object: z.string().describe('Object to pick records from'),\n displayField: z.string().describe('Field to display as the record label'),\n searchFields: z.array(z.string()).optional().describe('Fields to search against'),\n filter: FilterConditionSchema.optional().describe('Filter criteria for available records'),\n multiple: z.boolean().optional().default(false).describe('Allow multiple record selection'),\n targetVariable: z.string().optional().describe('Page variable to bind selected record ID(s)'),\n placeholder: I18nLabelSchema.optional().describe('Placeholder text'),\n /** ARIA accessibility */\n aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),\n});\n\n/**\n * ----------------------------------------------------------------------\n * Component Props Map\n * Maps Component Type to its Property Schema\n * ----------------------------------------------------------------------\n */\nexport const ComponentPropsMap = {\n // Structure\n 'page:header': PageHeaderProps,\n 'page:tabs': PageTabsProps,\n 'page:card': PageCardProps,\n 'page:footer': EmptyProps,\n 'page:sidebar': EmptyProps,\n 'page:accordion': PageAccordionProps,\n 'page:section': EmptyProps,\n\n // Record\n 'record:details': RecordDetailsProps,\n 'record:related_list': RecordRelatedListProps,\n 'record:highlights': RecordHighlightsProps,\n 'record:activity': RecordActivityProps,\n 'record:chatter': RecordChatterProps,\n 'record:path': RecordPathProps,\n\n // Navigation\n 'app:launcher': EmptyProps,\n 'nav:menu': EmptyProps,\n 'nav:breadcrumb': EmptyProps,\n\n // Utility\n 'global:search': EmptyProps,\n 'global:notifications': EmptyProps,\n 'user:profile': EmptyProps,\n \n // AI\n 'ai:chat_window': AIChatWindowProps,\n 'ai:suggestion': z.object({ context: z.string().optional() }),\n\n // Content Elements\n 'element:text': ElementTextPropsSchema,\n 'element:number': ElementNumberPropsSchema,\n 'element:image': ElementImagePropsSchema,\n 'element:divider': EmptyProps,\n\n // Interactive Elements\n 'element:button': ElementButtonPropsSchema,\n 'element:filter': ElementFilterPropsSchema,\n 'element:form': ElementFormPropsSchema,\n 'element:record_picker': ElementRecordPickerPropsSchema,\n} as const;\n\n/**\n * Type Helper to extract props from map\n */\nexport type ComponentProps = z.infer;\nexport type ComponentPropsInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Touch Target Configuration Schema\n * Ensures touch targets meet WCAG 2.5.5 minimum size requirements (44x44px).\n */\nexport const TouchTargetConfigSchema = z.object({\n minWidth: z.number().default(44).describe('Minimum touch target width in pixels (WCAG 2.5.5: 44px)'),\n minHeight: z.number().default(44).describe('Minimum touch target height in pixels (WCAG 2.5.5: 44px)'),\n padding: z.number().optional().describe('Additional padding around touch target in pixels'),\n hitSlop: z.object({\n top: z.number().optional().describe('Extra hit area above the element'),\n right: z.number().optional().describe('Extra hit area to the right of the element'),\n bottom: z.number().optional().describe('Extra hit area below the element'),\n left: z.number().optional().describe('Extra hit area to the left of the element'),\n }).optional().describe('Invisible hit area extension beyond the visible bounds'),\n}).describe('Touch target sizing configuration (WCAG accessible)');\n\nexport type TouchTargetConfig = z.infer;\n\n/**\n * Gesture Type Enum\n * Supported touch gesture types.\n */\nexport const GestureTypeSchema = z.enum([\n 'swipe',\n 'pinch',\n 'long_press',\n 'double_tap',\n 'drag',\n 'rotate',\n 'pan',\n]).describe('Touch gesture type');\n\nexport type GestureType = z.infer;\n\n/**\n * Swipe Direction Enum\n */\nexport const SwipeDirectionSchema = z.enum(['up', 'down', 'left', 'right']);\n\nexport type SwipeDirection = z.infer;\n\n/**\n * Swipe Gesture Configuration Schema\n */\nexport const SwipeGestureConfigSchema = z.object({\n direction: z.array(SwipeDirectionSchema).describe('Allowed swipe directions'),\n threshold: z.number().optional().describe('Minimum distance in pixels to recognize swipe'),\n velocity: z.number().optional().describe('Minimum velocity (px/ms) to trigger swipe'),\n}).describe('Swipe gesture recognition settings');\n\nexport type SwipeGestureConfig = z.infer;\n\n/**\n * Pinch Gesture Configuration Schema\n */\nexport const PinchGestureConfigSchema = z.object({\n minScale: z.number().optional().describe('Minimum scale factor (e.g., 0.5 for 50%)'),\n maxScale: z.number().optional().describe('Maximum scale factor (e.g., 3.0 for 300%)'),\n}).describe('Pinch/zoom gesture recognition settings');\n\nexport type PinchGestureConfig = z.infer;\n\n/**\n * Long Press Gesture Configuration Schema\n */\nexport const LongPressGestureConfigSchema = z.object({\n duration: z.number().default(500).describe('Hold duration in milliseconds to trigger long press'),\n moveTolerance: z.number().optional().describe('Max movement in pixels allowed during press'),\n}).describe('Long press gesture recognition settings');\n\nexport type LongPressGestureConfig = z.infer;\n\n/**\n * Gesture Configuration Schema\n * Unified configuration for all supported gesture types.\n */\nexport const GestureConfigSchema = z.object({\n type: GestureTypeSchema.describe('Gesture type to configure'),\n label: I18nLabelSchema.optional().describe('Descriptive label for the gesture action'),\n enabled: z.boolean().default(true).describe('Whether this gesture is active'),\n swipe: SwipeGestureConfigSchema.optional().describe('Swipe gesture settings (when type is swipe)'),\n pinch: PinchGestureConfigSchema.optional().describe('Pinch gesture settings (when type is pinch)'),\n longPress: LongPressGestureConfigSchema.optional().describe('Long press settings (when type is long_press)'),\n}).describe('Per-gesture configuration');\n\nexport type GestureConfig = z.infer;\n\n/**\n * Touch Interaction Schema\n * Top-level touch and gesture interaction configuration for a component.\n */\nexport const TouchInteractionSchema = z.object({\n gestures: z.array(GestureConfigSchema).optional().describe('Configured gesture recognizers'),\n touchTarget: TouchTargetConfigSchema.optional().describe('Touch target sizing and hit area'),\n hapticFeedback: z.boolean().optional().describe('Enable haptic feedback on touch interactions'),\n}).merge(AriaPropsSchema.partial()).describe('Touch and gesture interaction configuration');\n\nexport type TouchInteraction = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Focus Trap Configuration Schema\n * Constrains keyboard focus within a specific container (e.g., modals, dialogs).\n */\nexport const FocusTrapConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable focus trapping within this container'),\n initialFocus: z.string().optional().describe('CSS selector for the element to focus on activation'),\n returnFocus: z.boolean().default(true).describe('Return focus to trigger element on deactivation'),\n escapeDeactivates: z.boolean().default(true).describe('Allow Escape key to deactivate the focus trap'),\n}).describe('Focus trap configuration for modal-like containers');\n\nexport type FocusTrapConfig = z.infer;\n\n/**\n * Keyboard Shortcut Schema\n * Defines a single keyboard shortcut binding.\n */\nexport const KeyboardShortcutSchema = z.object({\n key: z.string().describe('Key combination (e.g., \"Ctrl+S\", \"Alt+N\", \"Escape\")'),\n action: z.string().describe('Action identifier to invoke when shortcut is triggered'),\n description: I18nLabelSchema.optional().describe('Human-readable description of what the shortcut does'),\n scope: z.enum(['global', 'view', 'form', 'modal', 'list']).default('global')\n .describe('Scope in which this shortcut is active'),\n}).describe('Keyboard shortcut binding');\n\nexport type KeyboardShortcut = z.infer;\n\n/**\n * Focus Management Schema\n * Controls tab order, focus visibility, and navigation behavior.\n */\nexport const FocusManagementSchema = z.object({\n tabOrder: z.enum(['auto', 'manual']).default('auto')\n .describe('Tab order strategy: auto (DOM order) or manual (explicit tabIndex)'),\n skipLinks: z.boolean().default(false).describe('Provide skip-to-content navigation links'),\n focusVisible: z.boolean().default(true).describe('Show visible focus indicators for keyboard users'),\n focusTrap: FocusTrapConfigSchema.optional().describe('Focus trap settings'),\n arrowNavigation: z.boolean().default(false)\n .describe('Enable arrow key navigation between focusable items'),\n}).describe('Focus and tab navigation management');\n\nexport type FocusManagement = z.infer;\n\n/**\n * Keyboard Navigation Configuration Schema\n * Top-level keyboard navigation and shortcut configuration.\n */\nexport const KeyboardNavigationConfigSchema = z.object({\n shortcuts: z.array(KeyboardShortcutSchema).optional().describe('Registered keyboard shortcuts'),\n focusManagement: FocusManagementSchema.optional().describe('Focus and tab order management'),\n rovingTabindex: z.boolean().default(false)\n .describe('Enable roving tabindex pattern for composite widgets'),\n}).merge(AriaPropsSchema.partial()).describe('Keyboard navigation and shortcut configuration');\n\nexport type KeyboardNavigationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\nimport { TouchTargetConfigSchema } from './touch.zod';\nimport { FocusManagementSchema } from './keyboard.zod';\n\n/**\n * Color Palette Schema\n * Defines brand colors and their variants.\n */\nexport const ColorPaletteSchema = z.object({\n primary: z.string().describe('Primary brand color (hex, rgb, or hsl)'),\n secondary: z.string().optional().describe('Secondary brand color'),\n accent: z.string().optional().describe('Accent color for highlights'),\n success: z.string().optional().describe('Success state color (default: green)'),\n warning: z.string().optional().describe('Warning state color (default: yellow)'),\n error: z.string().optional().describe('Error state color (default: red)'),\n info: z.string().optional().describe('Info state color (default: blue)'),\n \n // Neutral colors\n background: z.string().optional().describe('Background color'),\n surface: z.string().optional().describe('Surface/card background color'),\n text: z.string().optional().describe('Primary text color'),\n textSecondary: z.string().optional().describe('Secondary text color'),\n border: z.string().optional().describe('Border color'),\n disabled: z.string().optional().describe('Disabled state color'),\n \n // Color variants (shades)\n primaryLight: z.string().optional().describe('Lighter shade of primary'),\n primaryDark: z.string().optional().describe('Darker shade of primary'),\n secondaryLight: z.string().optional().describe('Lighter shade of secondary'),\n secondaryDark: z.string().optional().describe('Darker shade of secondary'),\n});\n\n/**\n * Typography Settings Schema\n * Font families, sizes, weights, and line heights.\n */\nexport const TypographySchema = z.object({\n fontFamily: z.object({\n base: z.string().optional().describe('Base font family (default: system fonts)'),\n heading: z.string().optional().describe('Heading font family'),\n mono: z.string().optional().describe('Monospace font family for code'),\n }).optional(),\n \n fontSize: z.object({\n xs: z.string().optional().describe('Extra small font size (e.g., 0.75rem)'),\n sm: z.string().optional().describe('Small font size (e.g., 0.875rem)'),\n base: z.string().optional().describe('Base font size (e.g., 1rem)'),\n lg: z.string().optional().describe('Large font size (e.g., 1.125rem)'),\n xl: z.string().optional().describe('Extra large font size (e.g., 1.25rem)'),\n '2xl': z.string().optional().describe('2X large font size (e.g., 1.5rem)'),\n '3xl': z.string().optional().describe('3X large font size (e.g., 1.875rem)'),\n '4xl': z.string().optional().describe('4X large font size (e.g., 2.25rem)'),\n }).optional(),\n \n fontWeight: z.object({\n light: z.number().optional().describe('Light weight (default: 300)'),\n normal: z.number().optional().describe('Normal weight (default: 400)'),\n medium: z.number().optional().describe('Medium weight (default: 500)'),\n semibold: z.number().optional().describe('Semibold weight (default: 600)'),\n bold: z.number().optional().describe('Bold weight (default: 700)'),\n }).optional(),\n \n lineHeight: z.object({\n tight: z.string().optional().describe('Tight line height (e.g., 1.25)'),\n normal: z.string().optional().describe('Normal line height (e.g., 1.5)'),\n relaxed: z.string().optional().describe('Relaxed line height (e.g., 1.75)'),\n loose: z.string().optional().describe('Loose line height (e.g., 2)'),\n }).optional(),\n \n letterSpacing: z.object({\n tighter: z.string().optional().describe('Tighter letter spacing (e.g., -0.05em)'),\n tight: z.string().optional().describe('Tight letter spacing (e.g., -0.025em)'),\n normal: z.string().optional().describe('Normal letter spacing (e.g., 0)'),\n wide: z.string().optional().describe('Wide letter spacing (e.g., 0.025em)'),\n wider: z.string().optional().describe('Wider letter spacing (e.g., 0.05em)'),\n }).optional(),\n});\n\n/**\n * Spacing Units Schema\n * Defines spacing scale for margins, padding, gaps.\n */\nexport const SpacingSchema = z.object({\n '0': z.string().optional().describe('0 spacing (0)'),\n '1': z.string().optional().describe('Spacing unit 1 (e.g., 0.25rem)'),\n '2': z.string().optional().describe('Spacing unit 2 (e.g., 0.5rem)'),\n '3': z.string().optional().describe('Spacing unit 3 (e.g., 0.75rem)'),\n '4': z.string().optional().describe('Spacing unit 4 (e.g., 1rem)'),\n '5': z.string().optional().describe('Spacing unit 5 (e.g., 1.25rem)'),\n '6': z.string().optional().describe('Spacing unit 6 (e.g., 1.5rem)'),\n '8': z.string().optional().describe('Spacing unit 8 (e.g., 2rem)'),\n '10': z.string().optional().describe('Spacing unit 10 (e.g., 2.5rem)'),\n '12': z.string().optional().describe('Spacing unit 12 (e.g., 3rem)'),\n '16': z.string().optional().describe('Spacing unit 16 (e.g., 4rem)'),\n '20': z.string().optional().describe('Spacing unit 20 (e.g., 5rem)'),\n '24': z.string().optional().describe('Spacing unit 24 (e.g., 6rem)'),\n});\n\n/**\n * Border Radius Schema\n * Rounded corners configuration.\n */\nexport const BorderRadiusSchema = z.object({\n none: z.string().optional().describe('No border radius (0)'),\n sm: z.string().optional().describe('Small border radius (e.g., 0.125rem)'),\n base: z.string().optional().describe('Base border radius (e.g., 0.25rem)'),\n md: z.string().optional().describe('Medium border radius (e.g., 0.375rem)'),\n lg: z.string().optional().describe('Large border radius (e.g., 0.5rem)'),\n xl: z.string().optional().describe('Extra large border radius (e.g., 0.75rem)'),\n '2xl': z.string().optional().describe('2X large border radius (e.g., 1rem)'),\n full: z.string().optional().describe('Full border radius (50%)'),\n});\n\n/**\n * Shadow Schema\n * Box shadow effects.\n */\nexport const ShadowSchema = z.object({\n none: z.string().optional().describe('No shadow'),\n sm: z.string().optional().describe('Small shadow'),\n base: z.string().optional().describe('Base shadow'),\n md: z.string().optional().describe('Medium shadow'),\n lg: z.string().optional().describe('Large shadow'),\n xl: z.string().optional().describe('Extra large shadow'),\n '2xl': z.string().optional().describe('2X large shadow'),\n inner: z.string().optional().describe('Inner shadow (inset)'),\n});\n\n/**\n * Breakpoints Schema\n * Responsive design breakpoints.\n */\nexport const BreakpointsSchema = z.object({\n xs: z.string().optional().describe('Extra small breakpoint (e.g., 480px)'),\n sm: z.string().optional().describe('Small breakpoint (e.g., 640px)'),\n md: z.string().optional().describe('Medium breakpoint (e.g., 768px)'),\n lg: z.string().optional().describe('Large breakpoint (e.g., 1024px)'),\n xl: z.string().optional().describe('Extra large breakpoint (e.g., 1280px)'),\n '2xl': z.string().optional().describe('2X large breakpoint (e.g., 1536px)'),\n});\n\n/**\n * Animation Schema\n * Animation timing and duration settings.\n */\nexport const AnimationSchema = z.object({\n duration: z.object({\n fast: z.string().optional().describe('Fast animation (e.g., 150ms)'),\n base: z.string().optional().describe('Base animation (e.g., 300ms)'),\n slow: z.string().optional().describe('Slow animation (e.g., 500ms)'),\n }).optional(),\n \n timing: z.object({\n linear: z.string().optional().describe('Linear timing function'),\n ease: z.string().optional().describe('Ease timing function'),\n ease_in: z.string().optional().describe('Ease-in timing function'),\n ease_out: z.string().optional().describe('Ease-out timing function'),\n ease_in_out: z.string().optional().describe('Ease-in-out timing function'),\n }).optional(),\n});\n\n/**\n * Z-Index Scale Schema\n * Layering and stacking order.\n */\nexport const ZIndexSchema = z.object({\n base: z.number().optional().describe('Base z-index (e.g., 0)'),\n dropdown: z.number().optional().describe('Dropdown z-index (e.g., 1000)'),\n sticky: z.number().optional().describe('Sticky z-index (e.g., 1020)'),\n fixed: z.number().optional().describe('Fixed z-index (e.g., 1030)'),\n modalBackdrop: z.number().optional().describe('Modal backdrop z-index (e.g., 1040)'),\n modal: z.number().optional().describe('Modal z-index (e.g., 1050)'),\n popover: z.number().optional().describe('Popover z-index (e.g., 1060)'),\n tooltip: z.number().optional().describe('Tooltip z-index (e.g., 1070)'),\n});\n\n/**\n * Theme Mode Schema\n */\nexport const ThemeModeSchema = z.enum(['light', 'dark', 'auto']);\n\n/** @deprecated Use ThemeModeSchema instead */\nexport const ThemeMode = ThemeModeSchema;\n\n/**\n * Density Mode Schema\n * Controls spacing and sizing for different use cases.\n */\nexport const DensityModeSchema = z.enum(['compact', 'regular', 'spacious']);\n\n/** @deprecated Use DensityModeSchema instead */\nexport const DensityMode = DensityModeSchema;\n\n/**\n * WCAG Contrast Level Schema\n * Web Content Accessibility Guidelines color contrast requirements.\n */\nexport const WcagContrastLevelSchema = z.enum(['AA', 'AAA']);\n\n/** @deprecated Use WcagContrastLevelSchema instead */\nexport const WcagContrastLevel = WcagContrastLevelSchema;\n\n/**\n * Theme Configuration Schema\n * Complete theme definition for brand customization.\n */\nexport const ThemeSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Unique theme identifier (snake_case)'),\n label: z.string().describe('Human-readable theme name'),\n description: z.string().optional().describe('Theme description'),\n \n /** Theme mode */\n mode: ThemeModeSchema.default('light').describe('Theme mode (light, dark, or auto)'),\n \n /** Color system */\n colors: ColorPaletteSchema.describe('Color palette configuration'),\n \n /** Typography */\n typography: TypographySchema.optional().describe('Typography settings'),\n \n /** Spacing */\n spacing: SpacingSchema.optional().describe('Spacing scale'),\n \n /** Border radius */\n borderRadius: BorderRadiusSchema.optional().describe('Border radius scale'),\n \n /** Shadows */\n shadows: ShadowSchema.optional().describe('Box shadow effects'),\n \n /** Breakpoints */\n breakpoints: BreakpointsSchema.optional().describe('Responsive breakpoints'),\n \n /** Animation */\n animation: AnimationSchema.optional().describe('Animation settings'),\n \n /** Z-Index */\n zIndex: ZIndexSchema.optional().describe('Z-index scale for layering'),\n \n /** Custom CSS variables */\n customVars: z.record(z.string(), z.string()).optional().describe('Custom CSS variables (key-value pairs)'),\n \n /** Logo */\n logo: z.object({\n light: z.string().optional().describe('Logo URL for light mode'),\n dark: z.string().optional().describe('Logo URL for dark mode'),\n favicon: z.string().optional().describe('Favicon URL'),\n }).optional().describe('Logo assets'),\n \n /** Extends another theme */\n extends: z.string().optional().describe('Base theme to extend from'),\n\n /** Display density mode */\n density: DensityModeSchema.optional().describe('Display density: compact, regular, or spacious'),\n\n /** WCAG contrast level requirement */\n wcagContrast: WcagContrastLevelSchema.optional().describe('WCAG color contrast level (AA or AAA)'),\n\n /** Right-to-left language support */\n rtl: z.boolean().optional().describe('Enable right-to-left layout direction'),\n\n /** Touch target accessibility configuration */\n touchTarget: TouchTargetConfigSchema.optional().describe('Touch target sizing defaults'),\n\n /** Keyboard navigation and focus management */\n keyboardNavigation: FocusManagementSchema.optional().describe('Keyboard focus management settings'),\n});\n\nexport type Theme = z.infer;\nexport type ColorPalette = z.infer;\nexport type Typography = z.infer;\nexport type Spacing = z.infer;\nexport type BorderRadius = z.infer;\nexport type Shadow = z.infer;\nexport type Breakpoints = z.infer;\nexport type Animation = z.infer;\nexport type ZIndex = z.infer;\nexport type ThemeMode = z.infer;\nexport type DensityMode = z.infer;\nexport type WcagContrastLevel = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema } from './i18n.zod';\n\n/**\n * Offline Strategy Schema\n * Determines how data is fetched when connectivity is limited.\n */\nexport const OfflineStrategySchema = z.enum([\n 'cache_first',\n 'network_first',\n 'stale_while_revalidate',\n 'network_only',\n 'cache_only',\n]).describe('Data fetching strategy for offline/online transitions');\n\nexport type OfflineStrategy = z.infer;\n\n/**\n * Conflict Resolution Strategy Enum\n */\nexport const ConflictResolutionSchema = z.enum([\n 'client_wins',\n 'server_wins',\n 'manual',\n 'last_write_wins',\n]).describe('How to resolve conflicts when syncing offline changes');\n\nexport type ConflictResolution = z.infer;\n\n/**\n * Sync Configuration Schema\n * Controls how offline mutations are synchronized with the server.\n */\nexport const SyncConfigSchema = z.object({\n strategy: OfflineStrategySchema.default('network_first').describe('Sync fetch strategy'),\n conflictResolution: ConflictResolutionSchema.default('last_write_wins').describe('Conflict resolution policy'),\n retryInterval: z.number().optional().describe('Retry interval in milliseconds between sync attempts'),\n maxRetries: z.number().optional().describe('Maximum number of sync retry attempts'),\n batchSize: z.number().optional().describe('Number of mutations to sync per batch'),\n}).describe('Offline-to-online synchronization configuration');\n\nexport type SyncConfig = z.infer;\n\n/**\n * Persist Storage Backend Enum\n */\nexport const PersistStorageSchema = z.enum([\n 'indexeddb',\n 'localstorage',\n 'sqlite',\n]).describe('Client-side storage backend for offline cache');\n\nexport type PersistStorage = z.infer;\n\n/**\n * Eviction Policy Enum\n */\nexport const EvictionPolicySchema = z.enum([\n 'lru',\n 'lfu',\n 'fifo',\n]).describe('Cache eviction policy');\n\nexport type EvictionPolicy = z.infer;\n\n/**\n * Offline Cache Configuration Schema\n * Controls how data is persisted on the client for offline access.\n */\nexport const OfflineCacheConfigSchema = z.object({\n maxSize: z.number().optional().describe('Maximum cache size in bytes'),\n ttl: z.number().optional().describe('Time-to-live for cached entries in milliseconds'),\n persistStorage: PersistStorageSchema.default('indexeddb').describe('Storage backend'),\n evictionPolicy: EvictionPolicySchema.default('lru').describe('Cache eviction policy when full'),\n}).describe('Client-side offline cache configuration');\n\nexport type OfflineCacheConfig = z.infer;\n\n/**\n * Offline Configuration Schema\n * Top-level offline support configuration for an application or component.\n */\nexport const OfflineConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable offline support'),\n strategy: OfflineStrategySchema.default('network_first').describe('Default offline fetch strategy'),\n cache: OfflineCacheConfigSchema.optional().describe('Cache settings for offline data'),\n sync: SyncConfigSchema.optional().describe('Sync settings for offline mutations'),\n offlineIndicator: z.boolean().default(true).describe('Show a visual indicator when offline'),\n offlineMessage: I18nLabelSchema.optional().describe('Customizable offline status message shown to users'),\n queueMaxSize: z.number().optional().describe('Maximum number of queued offline mutations'),\n}).describe('Offline support configuration');\n\nexport type OfflineConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Transition Preset Schema\n * Common animation transition presets.\n */\nexport const TransitionPresetSchema = z.enum([\n 'fade',\n 'slide_up',\n 'slide_down',\n 'slide_left',\n 'slide_right',\n 'scale',\n 'rotate',\n 'flip',\n 'none',\n]).describe('Transition preset type');\n\nexport type TransitionPreset = z.infer;\n\n/**\n * Easing Function Schema\n * Supported animation easing/timing functions.\n */\nexport const EasingFunctionSchema = z.enum([\n 'linear',\n 'ease',\n 'ease_in',\n 'ease_out',\n 'ease_in_out',\n 'spring',\n]).describe('Animation easing function');\n\nexport type EasingFunction = z.infer;\n\n/**\n * Transition Configuration Schema\n * Defines a single animation transition with timing and easing options.\n */\nexport const TransitionConfigSchema = z.object({\n preset: TransitionPresetSchema.optional().describe('Transition preset to apply'),\n duration: z.number().optional().describe('Transition duration in milliseconds'),\n easing: EasingFunctionSchema.optional().describe('Easing function for the transition'),\n delay: z.number().optional().describe('Delay before transition starts in milliseconds'),\n customKeyframes: z.string().optional().describe('CSS @keyframes name for custom animations'),\n themeToken: z.string().optional().describe('Reference to a theme animation token (e.g. \"animation.duration.fast\")'),\n}).describe('Animation transition configuration');\n\nexport type TransitionConfig = z.infer;\n\n/**\n * Animation Trigger Schema\n * Events that can trigger an animation.\n */\nexport const AnimationTriggerSchema = z.enum([\n 'on_mount',\n 'on_unmount',\n 'on_hover',\n 'on_focus',\n 'on_click',\n 'on_scroll',\n 'on_visible',\n]).describe('Event that triggers the animation');\n\nexport type AnimationTrigger = z.infer;\n\n/**\n * Component Animation Schema\n * Animation configuration for an individual UI component.\n */\nexport const ComponentAnimationSchema = z.object({\n label: I18nLabelSchema.optional().describe('Descriptive label for this animation configuration'),\n enter: TransitionConfigSchema.optional().describe('Enter/mount animation'),\n exit: TransitionConfigSchema.optional().describe('Exit/unmount animation'),\n hover: TransitionConfigSchema.optional().describe('Hover state animation'),\n trigger: AnimationTriggerSchema.optional().describe('When to trigger the animation'),\n reducedMotion: z.enum(['respect', 'disable', 'alternative']).default('respect')\n .describe('Accessibility: how to handle prefers-reduced-motion'),\n}).merge(AriaPropsSchema.partial()).describe('Component-level animation configuration');\n\nexport type ComponentAnimation = z.infer;\n\n/**\n * Page Transition Schema\n * Defines the animation used when navigating between pages.\n */\nexport const PageTransitionSchema = z.object({\n type: TransitionPresetSchema.default('fade').describe('Page transition type'),\n duration: z.number().default(300).describe('Transition duration in milliseconds'),\n easing: EasingFunctionSchema.default('ease_in_out').describe('Easing function for the transition'),\n crossFade: z.boolean().default(false).describe('Whether to cross-fade between pages'),\n}).describe('Page-level transition configuration');\n\nexport type PageTransition = z.infer;\n\n/**\n * Motion Configuration Schema\n * Top-level animation and motion design configuration.\n */\nexport const MotionConfigSchema = z.object({\n label: I18nLabelSchema.optional().describe('Descriptive label for the motion configuration'),\n defaultTransition: TransitionConfigSchema.optional().describe('Default transition applied to all animations'),\n pageTransitions: PageTransitionSchema.optional().describe('Page navigation transition settings'),\n componentAnimations: z.record(z.string(), ComponentAnimationSchema).optional()\n .describe('Component name to animation configuration mapping'),\n reducedMotion: z.boolean().default(false).describe('When true, respect prefers-reduced-motion and suppress animations globally'),\n enabled: z.boolean().default(true).describe('Enable or disable all animations globally'),\n}).describe('Top-level motion and animation design configuration');\n\nexport type MotionConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Notification Type Schema\n * Defines the visual presentation style of the notification.\n */\nexport const NotificationTypeSchema = z.enum([\n 'toast',\n 'snackbar',\n 'banner',\n 'alert',\n 'inline',\n]).describe('Notification presentation style');\n\nexport type NotificationType = z.infer;\n\n/**\n * Notification Severity Schema\n * Indicates the urgency and visual treatment of the notification.\n */\nexport const NotificationSeveritySchema = z.enum([\n 'info',\n 'success',\n 'warning',\n 'error',\n]).describe('Notification severity level');\n\nexport type NotificationSeverity = z.infer;\n\n/**\n * Notification Position Schema\n * Screen position for rendering notifications.\n */\nexport const NotificationPositionSchema = z.enum([\n 'top_left',\n 'top_center',\n 'top_right',\n 'bottom_left',\n 'bottom_center',\n 'bottom_right',\n]).describe('Screen position for notification placement');\n\nexport type NotificationPosition = z.infer;\n\n/**\n * Notification Action Schema\n * Defines an interactive action button within a notification.\n */\nexport const NotificationActionSchema = z.object({\n label: I18nLabelSchema.describe('Action button label'),\n action: z.string().describe('Action identifier to execute'),\n variant: z.enum(['primary', 'secondary', 'link']).default('primary')\n .describe('Button variant style'),\n}).describe('Notification action button');\n\nexport type NotificationAction = z.infer;\n\n/**\n * Notification Schema\n * Defines a single notification instance with content, behavior, and positioning.\n */\nexport const NotificationSchema = z.object({\n type: NotificationTypeSchema.default('toast').describe('Notification presentation style'),\n severity: NotificationSeveritySchema.default('info').describe('Notification severity level'),\n title: I18nLabelSchema.optional().describe('Notification title'),\n message: I18nLabelSchema.describe('Notification message body'),\n icon: z.string().optional().describe('Icon name override'),\n duration: z.number().optional().describe('Auto-dismiss duration in ms, omit for persistent'),\n dismissible: z.boolean().default(true).describe('Allow user to dismiss the notification'),\n actions: z.array(NotificationActionSchema).optional().describe('Action buttons'),\n position: NotificationPositionSchema.optional().describe('Override default position'),\n}).merge(AriaPropsSchema.partial()).describe('Notification instance definition');\n\nexport type Notification = z.infer;\n\n/**\n * Notification Config Schema\n * Top-level notification system configuration.\n */\nexport const NotificationConfigSchema = z.object({\n defaultPosition: NotificationPositionSchema.default('top_right')\n .describe('Default screen position for notifications'),\n defaultDuration: z.number().default(5000)\n .describe('Default auto-dismiss duration in ms'),\n maxVisible: z.number().default(5)\n .describe('Maximum number of notifications visible at once'),\n stackDirection: z.enum(['up', 'down']).default('down')\n .describe('Stack direction for multiple notifications'),\n pauseOnHover: z.boolean().default(true)\n .describe('Pause auto-dismiss timer on hover'),\n}).describe('Global notification system configuration');\n\nexport type NotificationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';\n\n/**\n * Drag Handle Schema\n * Defines how a drag interaction is initiated on an element.\n */\nexport const DragHandleSchema = z.enum([\n 'element',\n 'handle',\n 'grip_icon',\n]).describe('Drag initiation method');\n\nexport type DragHandle = z.infer;\n\n/**\n * Drop Effect Schema\n * Visual feedback indicating the result of a drop operation.\n */\nexport const DropEffectSchema = z.enum([\n 'move',\n 'copy',\n 'link',\n 'none',\n]).describe('Drop operation effect');\n\nexport type DropEffect = z.infer;\n\n/**\n * Drag Constraint Schema\n * Constrains drag movement along axes, within bounds, or to a grid.\n */\nexport const DragConstraintSchema = z.object({\n axis: z.enum(['x', 'y', 'both']).default('both').describe('Constrain drag axis'),\n bounds: z.enum(['parent', 'viewport', 'none']).default('none').describe('Constrain within bounds'),\n grid: z.tuple([z.number(), z.number()]).optional().describe('Snap to grid [x, y] in pixels'),\n}).describe('Drag movement constraints');\n\nexport type DragConstraint = z.infer;\n\n/**\n * Drop Zone Schema\n * Configures a container that accepts dragged items.\n */\nexport const DropZoneSchema = z.object({\n label: I18nLabelSchema.optional().describe('Accessible label for the drop zone'),\n accept: z.array(z.string()).describe('Accepted drag item types'),\n maxItems: z.number().optional().describe('Maximum items allowed in drop zone'),\n highlightOnDragOver: z.boolean().default(true).describe('Highlight drop zone when dragging over'),\n dropEffect: DropEffectSchema.default('move').describe('Visual effect on drop'),\n}).merge(AriaPropsSchema.partial()).describe('Drop zone configuration');\n\nexport type DropZone = z.infer;\n\n/**\n * Drag Item Schema\n * Configures a draggable element including handle, constraints, and preview.\n */\nexport const DragItemSchema = z.object({\n type: z.string().describe('Drag item type identifier for matching with drop zones'),\n label: I18nLabelSchema.optional().describe('Accessible label describing the draggable item'),\n handle: DragHandleSchema.default('element').describe('How to initiate drag'),\n constraint: DragConstraintSchema.optional().describe('Drag movement constraints'),\n preview: z.enum(['element', 'custom', 'none']).default('element').describe('Drag preview type'),\n disabled: z.boolean().default(false).describe('Disable dragging'),\n}).merge(AriaPropsSchema.partial()).describe('Draggable item configuration');\n\nexport type DragItem = z.infer;\n\n/**\n * Drag and Drop Configuration Schema\n * Top-level drag-and-drop interaction configuration for a component.\n */\nexport const DndConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable drag and drop'),\n dragItem: DragItemSchema.optional().describe('Configuration for draggable item'),\n dropZone: DropZoneSchema.optional().describe('Configuration for drop target'),\n sortable: z.boolean().default(false).describe('Enable sortable list behavior'),\n autoScroll: z.boolean().default(true).describe('Auto-scroll during drag near edges'),\n touchDelay: z.number().default(200).describe('Delay in ms before drag starts on touch devices'),\n}).describe('Drag and drop interaction configuration');\n\nexport type DndConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * System Protocol Exports\n * \n * Runtime Services & Infrastructure Configuration\n * - Infrastructure: Cache, Queue, Storage, Search, HTTP\n * - Observability: Audit, Logging, Metrics, Tracing, Change Management\n * - Security: Compliance, Encryption, Masking, Auth Config\n * - Services: Job, Worker, Notification, Translation\n */\n\n// Infrastructure Services\nexport * from './cache.zod';\nexport * from './disaster-recovery.zod';\nexport * from './message-queue.zod';\nexport * from './object-storage.zod';\nexport * from './search-engine.zod';\nexport * from './http-server.zod';\n\n// Observability & Operations\nexport * from './audit.zod';\nexport * from './logging.zod';\nexport * from './metrics.zod';\nexport * from './tracing.zod';\nexport * from './change-management.zod';\nexport * from './migration.zod';\n\n// Security & Compliance\nexport * from './auth-config.zod';\nexport * from './compliance.zod';\nexport * from './encryption.zod';\nexport * from './masking.zod';\nexport * from './security-context.zod';\nexport * from './incident-response.zod';\nexport * from './supplier-security.zod';\nexport * from './training.zod';\n\n// Runtime Services\nexport * from './job.zod';\nexport * from './worker.zod';\nexport * from './notification.zod';\nexport * from './translation.zod';\nexport * from './translation-typegen';\nexport * from './translation-skeleton';\nexport * from './collaboration.zod';\nexport * from './metadata-persistence.zod';\nexport * from './core-services.zod';\n\n// Multi-Tenant & Licensing\nexport * from './tenant.zod';\nexport * from './license.zod';\nexport * from './registry-config.zod';\n\n// Provisioning & Deployment\nexport * from './provisioning.zod';\nexport * from './deploy-bundle.zod';\nexport * from './app-install.zod';\n\n// Constants\nexport * from './constants';\n\n// Types\nexport * from './types';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Application-Level Cache Protocol\n * \n * Multi-tier caching strategy for application data.\n * Supports Memory, Redis, Memcached, and CDN.\n * \n * ## Caching in ObjectStack\n * \n * **Application Cache (`system/cache.zod.ts`) - This File**\n * - **Purpose**: Cache computed data, query results, aggregations\n * - **Technologies**: Redis, Memcached, in-memory LRU\n * - **Configuration**: TTL, eviction policies, cache warming\n * - **Use case**: Cache expensive database queries, computed values\n * - **Scope**: Application layer, server-side data storage\n * \n * **HTTP Cache (`api/http-cache.zod.ts`)**\n * - **Purpose**: Cache API responses at HTTP protocol level\n * - **Technologies**: HTTP headers (ETag, Last-Modified, Cache-Control), CDN\n * - **Configuration**: Cache-Control headers, validation tokens\n * - **Use case**: Reduce API response time for repeated metadata requests\n * - **Scope**: HTTP layer, client-server communication\n * \n * @see ../../api/http-cache.zod.ts for HTTP-level caching\n */\nexport const CacheStrategySchema = z.enum([\n 'lru', // Least Recently Used\n 'lfu', // Least Frequently Used\n 'fifo', // First In First Out\n 'ttl', // Time To Live only\n 'adaptive', // Dynamic strategy selection\n]).describe('Cache eviction strategy');\n\nexport type CacheStrategy = z.infer;\n\nexport const CacheTierSchema = z.object({\n name: z.string().describe('Unique cache tier name'),\n type: z.enum(['memory', 'redis', 'memcached', 'cdn']).describe('Cache backend type'),\n maxSize: z.number().optional().describe('Max size in MB'),\n ttl: z.number().default(300).describe('Default TTL in seconds'),\n strategy: CacheStrategySchema.default('lru').describe('Eviction strategy'),\n warmup: z.boolean().default(false).describe('Pre-populate cache on startup'),\n}).describe('Configuration for a single cache tier in the hierarchy');\n\nexport type CacheTier = z.infer;\nexport type CacheTierInput = z.input;\n\nexport const CacheInvalidationSchema = z.object({\n trigger: z.enum(['create', 'update', 'delete', 'manual']).describe('Event that triggers invalidation'),\n scope: z.enum(['key', 'pattern', 'tag', 'all']).describe('Invalidation scope'),\n pattern: z.string().optional().describe('Key pattern for pattern-based invalidation'),\n tags: z.array(z.string()).optional().describe('Cache tags to invalidate'),\n}).describe('Rule defining when and how cached entries are invalidated');\n\nexport type CacheInvalidation = z.infer;\n\nexport const CacheConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable application-level caching'),\n tiers: z.array(CacheTierSchema).describe('Ordered cache tier hierarchy'),\n invalidation: z.array(CacheInvalidationSchema).describe('Cache invalidation rules'),\n prefetch: z.boolean().default(false).describe('Enable cache prefetching'),\n compression: z.boolean().default(false).describe('Enable data compression in cache'),\n encryption: z.boolean().default(false).describe('Enable encryption for cached data'),\n}).describe('Top-level application cache configuration');\n\nexport type CacheConfig = z.infer;\nexport type CacheConfigInput = z.input;\n\n/**\n * Distributed Cache Consistency Schema\n *\n * Defines write strategies for distributed cache consistency.\n *\n * - **write_through**: Write to cache and backend simultaneously\n * - **write_behind**: Write to cache first, async persist to backend\n * - **write_around**: Write to backend only, cache on next read\n * - **refresh_ahead**: Proactively refresh expiring entries before TTL\n */\nexport const CacheConsistencySchema = z.enum([\n 'write_through',\n 'write_behind',\n 'write_around',\n 'refresh_ahead',\n]).describe('Distributed cache write consistency strategy');\n\nexport type CacheConsistency = z.infer;\n\n/**\n * Cache Avalanche Prevention Schema\n *\n * Strategies to prevent cache stampede/avalanche when many keys expire simultaneously.\n *\n * @example\n * ```typescript\n * const prevention: CacheAvalanchePrevention = {\n * jitterTtl: { enabled: true, maxJitterSeconds: 60 },\n * circuitBreaker: { enabled: true, failureThreshold: 5, resetTimeout: 30 },\n * lockout: { enabled: true, lockTimeoutMs: 5000 },\n * };\n * ```\n */\nexport const CacheAvalanchePreventionSchema = z.object({\n /** TTL jitter to stagger cache expiration */\n jitterTtl: z.object({\n enabled: z.boolean().default(false).describe('Add random jitter to TTL values'),\n maxJitterSeconds: z.number().default(60).describe('Maximum jitter added to TTL in seconds'),\n }).optional().describe('TTL jitter to prevent simultaneous expiration'),\n\n /** Circuit breaker to protect backend under cache pressure */\n circuitBreaker: z.object({\n enabled: z.boolean().default(false).describe('Enable circuit breaker for backend protection'),\n failureThreshold: z.number().default(5).describe('Failures before circuit opens'),\n resetTimeout: z.number().default(30).describe('Seconds before half-open state'),\n }).optional().describe('Circuit breaker for backend protection'),\n\n /** Cache lock to prevent thundering herd on key miss */\n lockout: z.object({\n enabled: z.boolean().default(false).describe('Enable cache locking for key regeneration'),\n lockTimeoutMs: z.number().default(5000).describe('Maximum lock wait time in milliseconds'),\n }).optional().describe('Lock-based stampede prevention'),\n}).describe('Cache avalanche/stampede prevention configuration');\n\nexport type CacheAvalanchePrevention = z.infer;\n\n/**\n * Cache Warmup Strategy Schema\n *\n * Defines how cache is pre-populated on startup or after cache flush.\n */\nexport const CacheWarmupSchema = z.object({\n /** Enable cache warming */\n enabled: z.boolean().default(false).describe('Enable cache warmup'),\n /** Warmup strategy */\n strategy: z.enum(['eager', 'lazy', 'scheduled']).default('lazy')\n .describe('Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)'),\n /** Cron schedule for scheduled warmup */\n schedule: z.string().optional().describe('Cron expression for scheduled warmup'),\n /** Keys/patterns to warm up */\n patterns: z.array(z.string()).optional().describe('Key patterns to warm up (e.g., \"user:*\", \"config:*\")'),\n /** Maximum concurrent warmup operations */\n concurrency: z.number().default(10).describe('Maximum concurrent warmup operations'),\n}).describe('Cache warmup strategy');\n\nexport type CacheWarmup = z.infer;\n\n/**\n * Distributed Cache Configuration Schema\n *\n * Extended cache configuration for distributed multi-node deployments.\n * Adds consistency strategies, avalanche prevention, and warmup policies.\n *\n * @example\n * ```typescript\n * const distributedCache: DistributedCacheConfig = {\n * enabled: true,\n * tiers: [\n * { name: 'l1', type: 'memory', maxSize: 100, ttl: 60, strategy: 'lru' },\n * { name: 'l2', type: 'redis', maxSize: 1000, ttl: 300, strategy: 'lru' },\n * ],\n * invalidation: [\n * { trigger: 'update', scope: 'key' },\n * ],\n * consistency: 'write_through',\n * avalanchePrevention: {\n * jitterTtl: { enabled: true, maxJitterSeconds: 30 },\n * circuitBreaker: { enabled: true, failureThreshold: 5 },\n * },\n * warmup: { enabled: true, strategy: 'eager', patterns: ['config:*'] },\n * };\n * ```\n */\nexport const DistributedCacheConfigSchema = CacheConfigSchema.extend({\n /** Distributed write consistency strategy */\n consistency: CacheConsistencySchema.optional().describe('Distributed cache consistency strategy'),\n /** Avalanche/stampede prevention settings */\n avalanchePrevention: CacheAvalanchePreventionSchema.optional()\n .describe('Cache avalanche and stampede prevention'),\n /** Cache warmup configuration */\n warmup: CacheWarmupSchema.optional().describe('Cache warmup strategy'),\n}).describe('Distributed cache configuration with consistency and avalanche prevention');\n\nexport type DistributedCacheConfig = z.infer;\nexport type DistributedCacheConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Backup Strategy Schema\n *\n * Defines backup methods for disaster recovery.\n *\n * - **full**: Complete snapshot of all data\n * - **incremental**: Only changes since last backup\n * - **differential**: All changes since last full backup\n *\n * @example\n * ```typescript\n * const backup: BackupConfig = {\n * strategy: 'incremental',\n * schedule: '0 2 * * *',\n * retention: { days: 30, minCopies: 3 },\n * encryption: { enabled: true, algorithm: 'AES-256-GCM' },\n * };\n * ```\n */\nexport const BackupStrategySchema = z.enum([\n 'full',\n 'incremental',\n 'differential',\n]).describe('Backup strategy type');\n\nexport type BackupStrategy = z.infer;\n\n/**\n * Backup Retention Policy Schema\n */\nexport const BackupRetentionSchema = z.object({\n /** Number of days to retain backups */\n days: z.number().min(1).describe('Retention period in days'),\n /** Minimum number of backup copies to keep regardless of age */\n minCopies: z.number().min(1).default(3).describe('Minimum backup copies to retain'),\n /** Maximum number of backup copies */\n maxCopies: z.number().optional().describe('Maximum backup copies to store'),\n}).describe('Backup retention policy');\n\nexport type BackupRetention = z.infer;\n\n/**\n * Backup Configuration Schema\n */\nexport const BackupConfigSchema = z.object({\n /** Backup strategy */\n strategy: BackupStrategySchema.default('incremental').describe('Backup strategy'),\n /** Cron schedule for automated backups */\n schedule: z.string().optional().describe('Cron expression for backup schedule (e.g., \"0 2 * * *\")'),\n /** Retention policy */\n retention: BackupRetentionSchema.describe('Backup retention policy'),\n /** Storage destination */\n destination: z.object({\n type: z.enum(['s3', 'gcs', 'azure_blob', 'local']).describe('Storage backend type'),\n bucket: z.string().optional().describe('Cloud storage bucket/container name'),\n path: z.string().optional().describe('Storage path prefix'),\n region: z.string().optional().describe('Cloud storage region'),\n }).describe('Backup storage destination'),\n /** Encryption settings */\n encryption: z.object({\n enabled: z.boolean().default(true).describe('Enable backup encryption'),\n algorithm: z.enum(['AES-256-GCM', 'AES-256-CBC', 'ChaCha20-Poly1305']).default('AES-256-GCM')\n .describe('Encryption algorithm'),\n keyId: z.string().optional().describe('KMS key ID for encryption'),\n }).optional().describe('Backup encryption settings'),\n /** Compression settings */\n compression: z.object({\n enabled: z.boolean().default(true).describe('Enable backup compression'),\n algorithm: z.enum(['gzip', 'zstd', 'lz4', 'snappy']).default('zstd').describe('Compression algorithm'),\n }).optional().describe('Backup compression settings'),\n /** Verify backup integrity after creation */\n verifyAfterBackup: z.boolean().default(true).describe('Verify backup integrity after creation'),\n}).describe('Backup configuration');\n\nexport type BackupConfig = z.infer;\nexport type BackupConfigInput = z.input;\n\n/**\n * Failover Mode Schema\n *\n * Defines how traffic is routed between primary and secondary systems.\n *\n * - **active_passive**: Secondary is standby, activated on primary failure\n * - **active_active**: Both primary and secondary handle traffic\n * - **pilot_light**: Minimal secondary with quick scale-up capability\n * - **warm_standby**: Reduced-capacity secondary, faster failover than pilot light\n */\nexport const FailoverModeSchema = z.enum([\n 'active_passive',\n 'active_active',\n 'pilot_light',\n 'warm_standby',\n]).describe('Failover mode');\n\nexport type FailoverMode = z.infer;\n\n/**\n * Failover Configuration Schema\n */\nexport const FailoverConfigSchema = z.object({\n /** Failover mode */\n mode: FailoverModeSchema.default('active_passive').describe('Failover mode'),\n /** Automatic failover enabled */\n autoFailover: z.boolean().default(true).describe('Enable automatic failover'),\n /** Health check interval in seconds */\n healthCheckInterval: z.number().default(30).describe('Health check interval in seconds'),\n /** Number of consecutive failures before triggering failover */\n failureThreshold: z.number().default(3).describe('Consecutive failures before failover'),\n /** Regions/zones for disaster recovery */\n regions: z.array(z.object({\n name: z.string().describe('Region identifier (e.g., \"us-east-1\", \"eu-west-1\")'),\n role: z.enum(['primary', 'secondary', 'witness']).describe('Region role'),\n endpoint: z.string().optional().describe('Region endpoint URL'),\n priority: z.number().optional().describe('Failover priority (lower = higher priority)'),\n })).min(2).describe('Multi-region configuration (minimum 2 regions)'),\n /** DNS failover configuration */\n dns: z.object({\n ttl: z.number().default(60).describe('DNS TTL in seconds for failover'),\n provider: z.enum(['route53', 'cloudflare', 'azure_dns', 'custom']).optional()\n .describe('DNS provider for automatic failover'),\n }).optional().describe('DNS failover settings'),\n}).describe('Failover configuration');\n\nexport type FailoverConfig = z.infer;\nexport type FailoverConfigInput = z.input;\n\n/**\n * Recovery Point Objective (RPO) Schema\n *\n * Maximum acceptable amount of data loss measured in time.\n */\nexport const RPOSchema = z.object({\n /** RPO value */\n value: z.number().min(0).describe('RPO value'),\n /** RPO time unit */\n unit: z.enum(['seconds', 'minutes', 'hours']).default('minutes').describe('RPO time unit'),\n}).describe('Recovery Point Objective (maximum acceptable data loss)');\n\nexport type RPO = z.infer;\n\n/**\n * Recovery Time Objective (RTO) Schema\n *\n * Maximum acceptable time to restore service after a disaster.\n */\nexport const RTOSchema = z.object({\n /** RTO value */\n value: z.number().min(0).describe('RTO value'),\n /** RTO time unit */\n unit: z.enum(['seconds', 'minutes', 'hours']).default('minutes').describe('RTO time unit'),\n}).describe('Recovery Time Objective (maximum acceptable downtime)');\n\nexport type RTO = z.infer;\n\n/**\n * Disaster Recovery Plan Schema\n *\n * Complete disaster recovery configuration for an ObjectStack deployment.\n * Covers backup, failover, replication, and recovery objectives.\n *\n * Aligned with industry standards:\n * - ISO 22301 (Business Continuity Management)\n * - AWS Well-Architected Framework (Reliability Pillar)\n *\n * @example\n * ```typescript\n * const drPlan: DisasterRecoveryPlan = {\n * enabled: true,\n * rpo: { value: 15, unit: 'minutes' },\n * rto: { value: 1, unit: 'hours' },\n * backup: {\n * strategy: 'incremental',\n * schedule: '0 0/6 * * *',\n * retention: { days: 90, minCopies: 5 },\n * destination: { type: 's3', bucket: 'backup-bucket', region: 'us-east-1' },\n * },\n * failover: {\n * mode: 'active_passive',\n * autoFailover: true,\n * healthCheckInterval: 30,\n * failureThreshold: 3,\n * regions: [\n * { name: 'us-east-1', role: 'primary' },\n * { name: 'us-west-2', role: 'secondary' },\n * ],\n * },\n * };\n * ```\n */\nexport const DisasterRecoveryPlanSchema = z.object({\n /** Enable disaster recovery */\n enabled: z.boolean().default(false).describe('Enable disaster recovery plan'),\n\n /** Recovery Point Objective */\n rpo: RPOSchema.describe('Recovery Point Objective'),\n\n /** Recovery Time Objective */\n rto: RTOSchema.describe('Recovery Time Objective'),\n\n /** Backup configuration */\n backup: BackupConfigSchema.describe('Backup configuration'),\n\n /** Failover configuration */\n failover: FailoverConfigSchema.optional().describe('Multi-region failover configuration'),\n\n /** Data replication settings */\n replication: z.object({\n /** Replication mode */\n mode: z.enum(['synchronous', 'asynchronous', 'semi_synchronous']).default('asynchronous')\n .describe('Data replication mode'),\n /** Maximum replication lag allowed (seconds) */\n maxLagSeconds: z.number().optional().describe('Maximum acceptable replication lag in seconds'),\n /** Objects/tables to replicate (empty = all) */\n includeObjects: z.array(z.string()).optional().describe('Objects to replicate (empty = all)'),\n /** Objects/tables to exclude from replication */\n excludeObjects: z.array(z.string()).optional().describe('Objects to exclude from replication'),\n }).optional().describe('Data replication settings'),\n\n /** Automated recovery testing */\n testing: z.object({\n /** Enable periodic DR testing */\n enabled: z.boolean().default(false).describe('Enable automated DR testing'),\n /** Cron schedule for DR tests */\n schedule: z.string().optional().describe('Cron expression for DR test schedule'),\n /** Notification channel for test results */\n notificationChannel: z.string().optional().describe('Notification channel for DR test results'),\n }).optional().describe('Automated disaster recovery testing'),\n\n /** Runbook URL for manual procedures */\n runbookUrl: z.string().optional().describe('URL to disaster recovery runbook/playbook'),\n\n /** Contact list for DR incidents */\n contacts: z.array(z.object({\n name: z.string().describe('Contact name'),\n role: z.string().describe('Contact role (e.g., \"DBA\", \"SRE Lead\")'),\n email: z.string().optional().describe('Contact email'),\n phone: z.string().optional().describe('Contact phone'),\n })).optional().describe('Emergency contact list for DR incidents'),\n}).describe('Complete disaster recovery plan configuration');\n\nexport type DisasterRecoveryPlan = z.infer;\nexport type DisasterRecoveryPlanInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Message queue protocol for async communication\n * Supports Kafka, RabbitMQ, AWS SQS, Redis Pub/Sub\n */\nexport const MessageQueueProviderSchema = z.enum([\n 'kafka',\n 'rabbitmq',\n 'aws-sqs',\n 'redis-pubsub',\n 'google-pubsub',\n 'azure-service-bus',\n]).describe('Supported message queue backend provider');\n\nexport type MessageQueueProvider = z.infer;\n\nexport const TopicConfigSchema = z.object({\n name: z.string().describe('Topic name identifier'),\n partitions: z.number().default(1).describe('Number of partitions for parallel consumption'),\n replicationFactor: z.number().default(1).describe('Number of replicas for fault tolerance'),\n retentionMs: z.number().optional().describe('Message retention period in milliseconds'),\n compressionType: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression algorithm'),\n}).describe('Configuration for a message queue topic');\n\nexport type TopicConfig = z.infer;\n\nexport const ConsumerConfigSchema = z.object({\n groupId: z.string().describe('Consumer group identifier'),\n autoOffsetReset: z.enum(['earliest', 'latest']).default('latest').describe('Where to start reading when no offset exists'),\n enableAutoCommit: z.boolean().default(true).describe('Automatically commit consumed offsets'),\n maxPollRecords: z.number().default(500).describe('Maximum records returned per poll'),\n}).describe('Consumer group configuration for topic consumption');\n\nexport type ConsumerConfig = z.infer;\n\nexport const DeadLetterQueueSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable dead letter queue for failed messages'),\n maxRetries: z.number().default(3).describe('Maximum delivery attempts before sending to DLQ'),\n queueName: z.string().describe('Name of the dead letter queue'),\n}).describe('Dead letter queue configuration for unprocessable messages');\n\nexport type DeadLetterQueue = z.infer;\n\nexport const MessageQueueConfigSchema = z.object({\n provider: MessageQueueProviderSchema.describe('Message queue backend provider'),\n topics: z.array(TopicConfigSchema).describe('List of topic configurations'),\n consumers: z.array(ConsumerConfigSchema).optional().describe('Consumer group configurations'),\n deadLetterQueue: DeadLetterQueueSchema.optional().describe('Dead letter queue for failed messages'),\n ssl: z.boolean().default(false).describe('Enable SSL/TLS for broker connections'),\n sasl: z.object({\n mechanism: z.enum(['plain', 'scram-sha-256', 'scram-sha-512']).describe('SASL authentication mechanism'),\n username: z.string().describe('SASL username'),\n password: z.string().describe('SASL password'),\n }).optional().describe('SASL authentication configuration'),\n}).describe('Top-level message queue configuration');\n\nexport type MessageQueueConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SystemIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Object Storage Protocol\n * \n * Unified storage protocol that combines:\n * - Object storage systems (S3, Azure Blob, GCS, MinIO)\n * - Scoped storage configuration (temp, cache, data, logs, config, public)\n * - Multi-cloud storage providers\n * - Bucket/container configuration\n * - Access control and permissions\n * - Lifecycle policies for data retention\n * - Presigned URLs for secure direct access\n * - Multipart uploads for large files\n */\n\n// ============================================================================\n// Storage Scope Protocol (formerly from scoped-storage.zod.ts)\n// ============================================================================\n\n/**\n * Storage Scope Enum\n * Defines the lifecycle and persistence guarantee of the storage area.\n */\nexport const StorageScopeSchema = z.enum([\n 'global', // Global application-wide storage\n 'tenant', // Tenant-scoped storage (multi-tenant apps)\n 'user', // User-scoped storage\n 'session', // Session-scoped storage (ephemeral)\n 'temp', // Ephemeral, cleared on restart\n 'cache', // Ephemeral, survives restarts, cleared on LRU/Expiration\n 'data', // Persistent, backed up\n 'logs', // Append-only, rotated\n 'config', // Read-heavy, versioned\n 'public' // Publicly accessible static assets\n]).describe('Storage scope classification');\n\nexport type StorageScope = z.infer;\n\n/**\n * File Metadata Schema\n * Standardized file attribute structure\n */\nexport const FileMetadataSchema = z.object({\n path: z.string().describe('File path'),\n name: z.string().describe('File name'),\n size: z.number().int().describe('File size in bytes'),\n mimeType: z.string().describe('MIME type'),\n lastModified: z.string().datetime().describe('Last modified timestamp'),\n created: z.string().datetime().describe('Creation timestamp'),\n etag: z.string().optional().describe('Entity tag'),\n});\n\nexport type FileMetadata = z.infer;\n\n// ============================================================================\n// Enums\n// ============================================================================\n\n/**\n * Storage Provider Types\n * \n * Supported cloud and self-hosted object storage providers.\n */\nexport const StorageProviderSchema = z.enum([\n 's3', // Amazon S3\n 'azure_blob', // Azure Blob Storage\n 'gcs', // Google Cloud Storage\n 'minio', // MinIO (self-hosted S3-compatible)\n 'r2', // Cloudflare R2\n 'spaces', // DigitalOcean Spaces\n 'wasabi', // Wasabi Hot Cloud Storage\n 'backblaze', // Backblaze B2\n 'local', // Local filesystem (development only)\n]).describe('Storage provider type');\n\nexport type StorageProvider = z.infer;\n\n/**\n * Storage Access Control List (ACL)\n * \n * Predefined access control configurations for objects and buckets.\n */\nexport const StorageAclSchema = z.enum([\n 'private', // Owner has full control, no one else has access\n 'public_read', // Owner has full control, everyone can read\n 'public_read_write', // Owner has full control, everyone can read/write (not recommended)\n 'authenticated_read', // Owner has full control, authenticated users can read\n 'bucket_owner_read', // Object owner has full control, bucket owner can read\n 'bucket_owner_full_control', // Both object and bucket owner have full control\n]).describe('Storage access control level');\n\nexport type StorageAcl = z.infer;\n\n/**\n * Storage Class / Tier\n * \n * Different storage tiers for cost optimization.\n * Maps to provider-specific storage classes.\n */\nexport const StorageClassSchema = z.enum([\n 'standard', // Standard/hot storage for frequently accessed data\n 'intelligent', // Intelligent tiering (auto-moves between hot/cool)\n 'infrequent_access', // Infrequent access/cool storage\n 'glacier', // Archive/cold storage (slower retrieval)\n 'deep_archive', // Deep archive (cheapest, slowest retrieval)\n]).describe('Storage class/tier for cost optimization');\n\nexport type StorageClass = z.infer;\n\n/**\n * Lifecycle Transition Action\n */\nexport const LifecycleActionSchema = z.enum([\n 'transition', // Move to different storage class\n 'delete', // Delete the object\n 'abort', // Abort incomplete multipart uploads\n]).describe('Lifecycle policy action type');\n\nexport type LifecycleAction = z.infer;\n\n// ============================================================================\n// Configuration Schemas\n// ============================================================================\n\n/**\n * Object Metadata Schema\n * \n * Standard and custom metadata attached to stored objects.\n * \n * @example\n * {\n * contentType: 'image/jpeg',\n * contentLength: 1024000,\n * etag: '\"abc123\"',\n * lastModified: new Date('2024-01-01'),\n * custom: {\n * uploadedBy: 'user123',\n * department: 'marketing'\n * }\n * }\n */\nexport const ObjectMetadataSchema = z.object({\n contentType: z.string().describe('MIME type (e.g., image/jpeg, application/pdf)'),\n contentLength: z.number().min(0).describe('File size in bytes'),\n contentEncoding: z.string().optional().describe('Content encoding (e.g., gzip)'),\n contentDisposition: z.string().optional().describe('Content disposition header'),\n contentLanguage: z.string().optional().describe('Content language'),\n cacheControl: z.string().optional().describe('Cache control directives'),\n etag: z.string().optional().describe('Entity tag for versioning/caching'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n versionId: z.string().optional().describe('Object version identifier'),\n storageClass: StorageClassSchema.optional().describe('Storage class/tier'),\n encryption: z.object({\n algorithm: z.string().describe('Encryption algorithm (e.g., AES256, aws:kms)'),\n keyId: z.string().optional().describe('KMS key ID if using managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n custom: z.record(z.string(), z.string()).optional().describe('Custom user-defined metadata'),\n});\n\nexport type ObjectMetadata = z.infer;\n\n/**\n * Presigned URL Configuration\n * \n * Configuration for generating temporary URLs for direct access to objects.\n * Useful for secure file uploads/downloads without exposing credentials.\n * \n * @example\n * // Generate download URL valid for 1 hour\n * {\n * operation: 'get',\n * expiresIn: 3600,\n * contentType: 'image/jpeg'\n * }\n * \n * @example\n * // Generate upload URL valid for 15 minutes with size limit\n * {\n * operation: 'put',\n * expiresIn: 900,\n * contentType: 'application/pdf',\n * maxSize: 10485760\n * }\n */\nexport const PresignedUrlConfigSchema = z.object({\n operation: z.enum(['get', 'put', 'delete', 'head']).describe('Allowed operation'),\n expiresIn: z.number().min(1).max(604800).describe('Expiration time in seconds (max 7 days)'),\n contentType: z.string().optional().describe('Required content type for PUT operations'),\n maxSize: z.number().min(0).optional().describe('Maximum file size in bytes for PUT operations'),\n responseContentType: z.string().optional().describe('Override content-type for GET operations'),\n responseContentDisposition: z.string().optional().describe('Override content-disposition for GET operations'),\n});\n\nexport type PresignedUrlConfig = z.infer;\n\n/**\n * Multipart Upload Configuration\n * \n * Configuration for chunked uploads of large files.\n * Enables resumable uploads and parallel transfer.\n * \n * @example\n * // Enable multipart for files > 100MB with 10MB chunks\n * {\n * enabled: true,\n * partSize: 10485760,\n * maxParts: 10000,\n * threshold: 104857600,\n * maxConcurrent: 4\n * }\n */\nexport const MultipartUploadConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable multipart uploads'),\n partSize: z.number().min(5 * 1024 * 1024).max(5 * 1024 * 1024 * 1024).default(10 * 1024 * 1024).describe('Part size in bytes (min 5MB, max 5GB)'),\n maxParts: z.number().min(1).max(10000).default(10000).describe('Maximum number of parts (max 10,000)'),\n threshold: z.number().min(0).default(100 * 1024 * 1024).describe('File size threshold to trigger multipart upload (bytes)'),\n maxConcurrent: z.number().min(1).max(100).default(4).describe('Maximum concurrent part uploads'),\n abortIncompleteAfterDays: z.number().min(1).optional().describe('Auto-abort incomplete uploads after N days'),\n});\n\nexport type MultipartUploadConfig = z.infer;\n\n/**\n * Access Control Configuration\n * \n * Fine-grained access control for buckets and objects.\n * \n * @example\n * {\n * acl: 'private',\n * allowedOrigins: ['https://app.example.com'],\n * allowedMethods: ['GET', 'PUT'],\n * corsEnabled: true,\n * publicAccess: {\n * allowPublicRead: false,\n * allowPublicWrite: false\n * }\n * }\n */\nexport const AccessControlConfigSchema = z.object({\n acl: StorageAclSchema.default('private').describe('Default access control level'),\n allowedOrigins: z.array(z.string()).optional().describe('CORS allowed origins'),\n allowedMethods: z.array(z.enum(['GET', 'PUT', 'POST', 'DELETE', 'HEAD'])).optional().describe('CORS allowed HTTP methods'),\n allowedHeaders: z.array(z.string()).optional().describe('CORS allowed headers'),\n exposeHeaders: z.array(z.string()).optional().describe('CORS exposed headers'),\n maxAge: z.number().min(0).optional().describe('CORS preflight cache duration in seconds'),\n corsEnabled: z.boolean().default(false).describe('Enable CORS configuration'),\n publicAccess: z.object({\n allowPublicRead: z.boolean().default(false).describe('Allow public read access'),\n allowPublicWrite: z.boolean().default(false).describe('Allow public write access'),\n allowPublicList: z.boolean().default(false).describe('Allow public bucket listing'),\n }).optional().describe('Public access control'),\n allowedIps: z.array(z.string()).optional().describe('Allowed IP addresses/CIDR blocks'),\n blockedIps: z.array(z.string()).optional().describe('Blocked IP addresses/CIDR blocks'),\n});\n\nexport type AccessControlConfig = z.infer;\n\n/**\n * Lifecycle Policy Rule\n * \n * Individual rule for automatic object lifecycle management.\n * \n * @example\n * // Transition to infrequent access after 30 days\n * {\n * id: 'move_to_ia',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 30,\n * targetStorageClass: 'infrequent_access'\n * }\n * \n * @example\n * // Delete objects after 365 days\n * {\n * id: 'delete_old',\n * enabled: true,\n * action: 'delete',\n * daysAfterCreation: 365\n * }\n */\nexport const LifecyclePolicyRuleSchema = z.object({\n id: SystemIdentifierSchema.describe('Rule identifier'),\n enabled: z.boolean().default(true).describe('Enable this rule'),\n action: LifecycleActionSchema.describe('Action to perform'),\n prefix: z.string().optional().describe('Object key prefix filter (e.g., \"uploads/\")'),\n tags: z.record(z.string(), z.string()).optional().describe('Object tag filters'),\n daysAfterCreation: z.number().min(0).optional().describe('Days after object creation'),\n daysAfterModification: z.number().min(0).optional().describe('Days after last modification'),\n targetStorageClass: StorageClassSchema.optional().describe('Target storage class for transition action'),\n}).refine((data) => {\n // Validate that transition action has targetStorageClass\n if (data.action === 'transition' && !data.targetStorageClass) {\n return false;\n }\n return true;\n}, {\n message: 'targetStorageClass is required when action is \"transition\"',\n});\n\nexport type LifecyclePolicyRule = z.infer;\n\n/**\n * Lifecycle Policy Configuration\n * \n * Collection of lifecycle rules for automatic data management.\n * \n * @example\n * {\n * enabled: true,\n * rules: [\n * {\n * id: 'archive_old_files',\n * enabled: true,\n * action: 'transition',\n * daysAfterCreation: 90,\n * targetStorageClass: 'glacier'\n * },\n * {\n * id: 'delete_temp_files',\n * enabled: true,\n * action: 'delete',\n * prefix: 'temp/',\n * daysAfterCreation: 7\n * }\n * ]\n * }\n */\nexport const LifecyclePolicyConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable lifecycle policies'),\n rules: z.array(LifecyclePolicyRuleSchema).default([]).describe('Lifecycle rules'),\n});\n\nexport type LifecyclePolicyConfig = z.infer;\n\n/**\n * Bucket Configuration Schema\n * \n * Comprehensive configuration for a storage bucket/container.\n * \n * @example\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'my-app-uploads',\n * region: 'us-east-1',\n * provider: 's3',\n * versioning: true,\n * accessControl: {\n * acl: 'private',\n * corsEnabled: true,\n * allowedOrigins: ['https://app.example.com']\n * },\n * multipartConfig: {\n * enabled: true,\n * threshold: 104857600\n * }\n * }\n */\nexport const BucketConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Bucket identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n bucketName: z.string().describe('Actual bucket/container name in storage provider'),\n region: z.string().optional().describe('Storage region (e.g., us-east-1, westus)'),\n provider: StorageProviderSchema.describe('Storage provider'),\n endpoint: z.string().optional().describe('Custom endpoint URL (for S3-compatible providers)'),\n pathStyle: z.boolean().default(false).describe('Use path-style URLs (for S3-compatible providers)'),\n \n versioning: z.boolean().default(false).describe('Enable object versioning'),\n encryption: z.object({\n enabled: z.boolean().default(false).describe('Enable server-side encryption'),\n algorithm: z.enum(['AES256', 'aws:kms', 'azure:kms', 'gcp:kms']).default('AES256').describe('Encryption algorithm'),\n kmsKeyId: z.string().optional().describe('KMS key ID for managed encryption'),\n }).optional().describe('Server-side encryption configuration'),\n \n accessControl: AccessControlConfigSchema.optional().describe('Access control configuration'),\n lifecyclePolicy: LifecyclePolicyConfigSchema.optional().describe('Lifecycle policy configuration'),\n multipartConfig: MultipartUploadConfigSchema.optional().describe('Multipart upload configuration'),\n \n tags: z.record(z.string(), z.string()).optional().describe('Bucket tags for organization'),\n description: z.string().optional().describe('Bucket description'),\n enabled: z.boolean().default(true).describe('Enable this bucket'),\n});\n\nexport type BucketConfig = z.infer;\n\n/**\n * Storage Connection Configuration\n * \n * Provider-specific connection credentials and settings.\n * \n * @example S3\n * {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * sessionToken: '${AWS_SESSION_TOKEN}',\n * region: 'us-east-1'\n * }\n * \n * @example Azure\n * {\n * accountName: 'mystorageaccount',\n * accountKey: '${AZURE_STORAGE_KEY}',\n * endpoint: 'https://mystorageaccount.blob.core.windows.net'\n * }\n */\nexport const StorageConnectionSchema = z.object({\n // AWS S3 / MinIO\n accessKeyId: z.string().optional().describe('AWS access key ID or MinIO access key'),\n secretAccessKey: z.string().optional().describe('AWS secret access key or MinIO secret key'),\n sessionToken: z.string().optional().describe('AWS session token for temporary credentials'),\n \n // Azure Blob Storage\n accountName: z.string().optional().describe('Azure storage account name'),\n accountKey: z.string().optional().describe('Azure storage account key'),\n sasToken: z.string().optional().describe('Azure SAS token'),\n \n // Google Cloud Storage\n projectId: z.string().optional().describe('GCP project ID'),\n credentials: z.string().optional().describe('GCP service account credentials JSON'),\n \n // Common\n endpoint: z.string().optional().describe('Custom endpoint URL'),\n region: z.string().optional().describe('Default region'),\n useSSL: z.boolean().default(true).describe('Use SSL/TLS for connections'),\n timeout: z.number().min(0).optional().describe('Connection timeout in milliseconds'),\n});\n\nexport type StorageConnection = z.infer;\n\n/**\n * Object Storage Configuration\n * \n * Complete object storage system configuration.\n * \n * @example\n * {\n * name: 'production_storage',\n * label: 'Production File Storage',\n * provider: 's3',\n * scope: 'global',\n * connection: {\n * accessKeyId: '${AWS_ACCESS_KEY_ID}',\n * secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n * region: 'us-east-1'\n * },\n * buckets: [\n * {\n * name: 'user_uploads',\n * label: 'User Uploads',\n * bucketName: 'prod-uploads',\n * provider: 's3',\n * region: 'us-east-1'\n * }\n * ],\n * defaultBucket: 'user_uploads'\n * }\n */\nexport const ObjectStorageConfigSchema = z.object({\n name: SystemIdentifierSchema.describe('Storage configuration identifier'),\n label: z.string().describe('Display label'),\n provider: StorageProviderSchema.describe('Primary storage provider'),\n \n /**\n * Storage scope\n * Defines the lifecycle and access pattern for this storage\n */\n scope: StorageScopeSchema.optional().default('global').describe('Storage scope'),\n \n connection: StorageConnectionSchema.describe('Connection credentials'),\n buckets: z.array(BucketConfigSchema).default([]).describe('Configured buckets'),\n defaultBucket: z.string().optional().describe('Default bucket name for operations'),\n \n /**\n * Base path or location\n * For local/scoped storage configurations\n */\n location: z.string().optional().describe('Root path (local) or base location'),\n \n /**\n * Storage quota in bytes\n */\n quota: z.number().int().positive().optional().describe('Max size in bytes'),\n \n /**\n * Provider-specific options\n */\n options: z.record(z.string(), z.unknown()).optional().describe('Provider-specific configuration options'),\n \n enabled: z.boolean().default(true).describe('Enable this storage configuration'),\n description: z.string().optional().describe('Configuration description'),\n});\n\nexport type ObjectStorageConfig = z.infer;\n\n// ============================================================================\n// Helper Examples\n// ============================================================================\n\n/**\n * Example: AWS S3 Configuration\n */\nexport const s3StorageExample = ObjectStorageConfigSchema.parse({\n name: 'aws_s3_storage',\n label: 'AWS S3 Production Storage',\n provider: 's3',\n connection: {\n accessKeyId: '${AWS_ACCESS_KEY_ID}',\n secretAccessKey: '${AWS_SECRET_ACCESS_KEY}',\n region: 'us-east-1',\n },\n buckets: [\n {\n name: 'user_uploads',\n label: 'User Uploads',\n bucketName: 'my-app-user-uploads',\n region: 'us-east-1',\n provider: 's3',\n versioning: true,\n encryption: {\n enabled: true,\n algorithm: 'aws:kms',\n kmsKeyId: '${AWS_KMS_KEY_ID}',\n },\n accessControl: {\n acl: 'private',\n corsEnabled: true,\n allowedOrigins: ['https://app.example.com'],\n allowedMethods: ['GET', 'PUT', 'POST'],\n },\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'archive_old_uploads',\n enabled: true,\n action: 'transition',\n daysAfterCreation: 90,\n targetStorageClass: 'glacier',\n },\n ],\n },\n multipartConfig: {\n enabled: true,\n partSize: 10 * 1024 * 1024,\n threshold: 100 * 1024 * 1024,\n maxConcurrent: 4,\n },\n },\n ],\n defaultBucket: 'user_uploads',\n enabled: true,\n});\n\n/**\n * Example: MinIO Configuration\n */\nexport const minioStorageExample = ObjectStorageConfigSchema.parse({\n name: 'minio_local',\n label: 'MinIO Local Storage',\n provider: 'minio',\n connection: {\n accessKeyId: 'minioadmin',\n secretAccessKey: 'minioadmin',\n endpoint: 'http://localhost:9000',\n useSSL: false,\n },\n buckets: [\n {\n name: 'development_files',\n label: 'Development Files',\n bucketName: 'dev-files',\n provider: 'minio',\n endpoint: 'http://localhost:9000',\n pathStyle: true,\n accessControl: {\n acl: 'private',\n },\n },\n ],\n defaultBucket: 'development_files',\n enabled: true,\n});\n\n/**\n * Example: Azure Blob Storage Configuration\n */\nexport const azureBlobStorageExample = ObjectStorageConfigSchema.parse({\n name: 'azure_blob_storage',\n label: 'Azure Blob Storage',\n provider: 'azure_blob',\n connection: {\n accountName: 'mystorageaccount',\n accountKey: '${AZURE_STORAGE_KEY}',\n endpoint: 'https://mystorageaccount.blob.core.windows.net',\n },\n buckets: [\n {\n name: 'media_files',\n label: 'Media Files',\n bucketName: 'media',\n provider: 'azure_blob',\n region: 'eastus',\n accessControl: {\n acl: 'public_read',\n publicAccess: {\n allowPublicRead: true,\n allowPublicWrite: false,\n allowPublicList: false,\n },\n },\n },\n ],\n defaultBucket: 'media_files',\n enabled: true,\n});\n\n/**\n * Example: Google Cloud Storage Configuration\n */\nexport const gcsStorageExample = ObjectStorageConfigSchema.parse({\n name: 'gcs_storage',\n label: 'Google Cloud Storage',\n provider: 'gcs',\n connection: {\n projectId: 'my-gcp-project',\n credentials: '${GCP_SERVICE_ACCOUNT_JSON}',\n },\n buckets: [\n {\n name: 'backup_storage',\n label: 'Backup Storage',\n bucketName: 'my-app-backups',\n region: 'us-central1',\n provider: 'gcs',\n lifecyclePolicy: {\n enabled: true,\n rules: [\n {\n id: 'delete_old_backups',\n enabled: true,\n action: 'delete',\n daysAfterCreation: 30,\n },\n ],\n },\n },\n ],\n defaultBucket: 'backup_storage',\n enabled: true,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Full-text search protocol\n * Supports Elasticsearch, Algolia, Meilisearch, Typesense\n */\nexport const SearchProviderSchema = z.enum([\n 'elasticsearch',\n 'algolia',\n 'meilisearch',\n 'typesense',\n 'opensearch',\n]).describe('Supported full-text search engine provider');\n\nexport type SearchProvider = z.infer;\n\nexport const AnalyzerConfigSchema = z.object({\n type: z.enum(['standard', 'simple', 'whitespace', 'keyword', 'pattern', 'language']).describe('Text analyzer type'),\n language: z.string().optional().describe('Language for language-specific analysis'),\n stopwords: z.array(z.string()).optional().describe('Custom stopwords to filter during analysis'),\n customFilters: z.array(z.string()).optional().describe('Additional token filter names to apply'),\n}).describe('Text analyzer configuration for index tokenization and normalization');\n\nexport type AnalyzerConfig = z.infer;\n\nexport const SearchIndexConfigSchema = z.object({\n indexName: z.string().describe('Name of the search index'),\n objectName: z.string().describe('Source ObjectQL object'),\n fields: z.array(z.object({\n name: z.string().describe('Field name to index'),\n type: z.enum(['text', 'keyword', 'number', 'date', 'boolean', 'geo']).describe('Index field data type'),\n analyzer: z.string().optional().describe('Named analyzer to use for this field'),\n searchable: z.boolean().default(true).describe('Include field in full-text search'),\n filterable: z.boolean().default(false).describe('Allow filtering on this field'),\n sortable: z.boolean().default(false).describe('Allow sorting by this field'),\n boost: z.number().default(1).describe('Relevance boost factor for this field'),\n })).describe('Fields to include in the search index'),\n replicas: z.number().default(1).describe('Number of index replicas for availability'),\n shards: z.number().default(1).describe('Number of index shards for distribution'),\n}).describe('Search index definition mapping an ObjectQL object to a search engine index');\n\nexport type SearchIndexConfig = z.infer;\n\nexport const FacetConfigSchema = z.object({\n field: z.string().describe('Field name to generate facets from'),\n maxValues: z.number().default(10).describe('Maximum number of facet values to return'),\n sort: z.enum(['count', 'alpha']).default('count').describe('Facet value sort order'),\n}).describe('Faceted search configuration for a single field');\n\nexport type FacetConfig = z.infer;\n\nexport const SearchConfigSchema = z.object({\n provider: SearchProviderSchema.describe('Search engine backend provider'),\n indexes: z.array(SearchIndexConfigSchema).describe('Search index definitions'),\n analyzers: z.record(z.string(), AnalyzerConfigSchema).optional().describe('Named text analyzer configurations'),\n facets: z.array(FacetConfigSchema).optional().describe('Faceted search configurations'),\n typoTolerance: z.boolean().default(true).describe('Enable typo-tolerant search'),\n synonyms: z.record(z.string(), z.array(z.string())).optional().describe('Synonym mappings for search expansion'),\n ranking: z.array(z.enum(['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom'])).optional().describe('Custom ranking rule order'),\n}).describe('Top-level full-text search engine configuration');\n\nexport type SearchConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, CorsConfigSchema, RateLimitConfigSchema, StaticMountSchema } from '../shared/http.zod';\n\n/**\n * HTTP Server Protocol\n * \n * Defines the runtime HTTP server configuration and capabilities.\n * Provides abstractions for HTTP server implementations (Express, Fastify, Hono, etc.)\n * \n * Architecture alignment:\n * - Kubernetes: Service and Ingress resources\n * - AWS: API Gateway configuration\n * - Spring Boot: Application properties\n */\n\n// ==========================================\n// Server Configuration\n// ==========================================\n\n/**\n * HTTP Server Configuration Schema\n * Core configuration for HTTP server instances\n * \n * @example\n * {\n * \"port\": 3000,\n * \"host\": \"0.0.0.0\",\n * \"cors\": {\n * \"enabled\": true,\n * \"origins\": [\"http://localhost:3000\"]\n * },\n * \"compression\": true,\n * \"requestTimeout\": 30000\n * }\n */\nexport const HttpServerConfigSchema = z.object({\n /**\n * Server port number\n */\n port: z.number().int().min(1).max(65535).default(3000).describe('Port number to listen on'),\n \n /**\n * Server host address\n */\n host: z.string().default('0.0.0.0').describe('Host address to bind to'),\n \n /**\n * CORS configuration\n */\n cors: CorsConfigSchema.optional().describe('CORS configuration'),\n \n /**\n * Request handling options\n */\n requestTimeout: z.number().int().default(30000).describe('Request timeout in milliseconds'),\n bodyLimit: z.string().default('10mb').describe('Maximum request body size'),\n \n /**\n * Compression settings\n */\n compression: z.boolean().default(true).describe('Enable response compression'),\n \n /**\n * Security headers\n */\n security: z.object({\n helmet: z.boolean().default(true).describe('Enable security headers via helmet'),\n rateLimit: RateLimitConfigSchema.optional().describe('Global rate limiting configuration'),\n }).optional().describe('Security configuration'),\n \n /**\n * Static file serving\n */\n static: z.array(StaticMountSchema).optional().describe('Static file serving configuration'),\n \n /**\n * Trust proxy settings\n */\n trustProxy: z.boolean().default(false).describe('Trust X-Forwarded-* headers'),\n});\n\nexport type HttpServerConfig = z.infer;\nexport type HttpServerConfigInput = z.input;\n\n// ==========================================\n// Route Registration\n// ==========================================\n\n/**\n * Route Handler Metadata Schema\n * Metadata for route handlers used in registration\n */\nexport const RouteHandlerMetadataSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (supports parameters like /api/users/:id)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Handler function name or identifier\n */\n handler: z.string().describe('Handler identifier or name'),\n \n /**\n * Route metadata\n */\n metadata: z.object({\n summary: z.string().optional().describe('Route summary for documentation'),\n description: z.string().optional().describe('Route description'),\n tags: z.array(z.string()).optional().describe('Tags for grouping'),\n operationId: z.string().optional().describe('Unique operation identifier'),\n }).optional(),\n \n /**\n * Security requirements\n */\n security: z.object({\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n rateLimit: z.string().optional().describe('Rate limit policy override'),\n }).optional(),\n});\n\nexport type RouteHandlerMetadata = z.infer;\nexport type RouteHandlerMetadataInput = z.input;\n\n// ==========================================\n// Middleware Configuration\n// ==========================================\n\n/**\n * Middleware Type Enum\n */\nexport const MiddlewareType = z.enum([\n 'authentication', // Authentication middleware\n 'authorization', // Authorization/permission checks\n 'logging', // Request/response logging\n 'validation', // Input validation\n 'transformation', // Request/response transformation\n 'error', // Error handling\n 'custom', // Custom middleware\n]);\n\nexport type MiddlewareType = z.infer;\n\n/**\n * Middleware Configuration Schema\n * Defines middleware execution order and configuration\n * \n * @example\n * {\n * \"name\": \"auth_middleware\",\n * \"type\": \"authentication\",\n * \"enabled\": true,\n * \"order\": 10,\n * \"config\": {\n * \"jwtSecret\": \"secret\",\n * \"excludePaths\": [\"/health\", \"/metrics\"]\n * }\n * }\n */\nexport const MiddlewareConfigSchema = z.object({\n /**\n * Middleware identifier\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Middleware name (snake_case)'),\n \n /**\n * Middleware type\n */\n type: MiddlewareType.describe('Middleware type'),\n \n /**\n * Enable/disable middleware\n */\n enabled: z.boolean().default(true).describe('Whether middleware is enabled'),\n \n /**\n * Execution order (lower numbers execute first)\n */\n order: z.number().int().default(100).describe('Execution order priority'),\n \n /**\n * Middleware-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Middleware configuration object'),\n \n /**\n * Path patterns to apply middleware to\n */\n paths: z.object({\n include: z.array(z.string()).optional().describe('Include path patterns (glob)'),\n exclude: z.array(z.string()).optional().describe('Exclude path patterns (glob)'),\n }).optional().describe('Path filtering'),\n});\n\nexport type MiddlewareConfig = z.infer;\nexport type MiddlewareConfigInput = z.input;\n\n// ==========================================\n// Server Lifecycle Events\n// ==========================================\n\n/**\n * Server Event Type Enum\n */\nexport const ServerEventType = z.enum([\n 'starting', // Server is starting\n 'started', // Server has started and is listening\n 'stopping', // Server is stopping\n 'stopped', // Server has stopped\n 'request', // Request received\n 'response', // Response sent\n 'error', // Error occurred\n]);\n\nexport type ServerEventType = z.infer;\n\n/**\n * Server Event Schema\n * Events emitted by the HTTP server during lifecycle\n */\nexport const ServerEventSchema = z.object({\n /**\n * Event type\n */\n type: ServerEventType.describe('Event type'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp (ISO 8601)'),\n \n /**\n * Event payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Event-specific data'),\n});\n\nexport type ServerEvent = z.infer;\n\n// ==========================================\n// Server Capability Declaration\n// ==========================================\n\n/**\n * Server Capabilities Schema\n * Declares what features a server implementation supports\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Supported HTTP versions\n */\n httpVersions: z.array(z.enum(['1.0', '1.1', '2.0', '3.0'])).default(['1.1']).describe('Supported HTTP versions'),\n \n /**\n * WebSocket support\n */\n websocket: z.boolean().default(false).describe('WebSocket support'),\n \n /**\n * Server-Sent Events support\n */\n sse: z.boolean().default(false).describe('Server-Sent Events support'),\n \n /**\n * HTTP/2 Server Push\n */\n serverPush: z.boolean().default(false).describe('HTTP/2 Server Push support'),\n \n /**\n * Streaming support\n */\n streaming: z.boolean().default(true).describe('Response streaming support'),\n \n /**\n * Middleware support\n */\n middleware: z.boolean().default(true).describe('Middleware chain support'),\n \n /**\n * Route parameterization\n */\n routeParams: z.boolean().default(true).describe('URL parameter support (/users/:id)'),\n \n /**\n * Built-in compression\n */\n compression: z.boolean().default(true).describe('Built-in compression support'),\n});\n\nexport type ServerCapabilities = z.infer;\nexport type ServerCapabilitiesInput = z.input;\n\n// ==========================================\n// Server Status & Metrics\n// ==========================================\n\n/**\n * Server Status Schema\n * Current operational status of the server\n */\nexport const ServerStatusSchema = z.object({\n /**\n * Server state\n */\n state: z.enum(['stopped', 'starting', 'running', 'stopping', 'error']).describe('Current server state'),\n \n /**\n * Uptime in milliseconds\n */\n uptime: z.number().int().optional().describe('Server uptime in milliseconds'),\n \n /**\n * Server information\n */\n server: z.object({\n port: z.number().int().describe('Listening port'),\n host: z.string().describe('Bound host'),\n url: z.string().optional().describe('Full server URL'),\n }).optional(),\n \n /**\n * Connection metrics\n */\n connections: z.object({\n active: z.number().int().describe('Active connections'),\n total: z.number().int().describe('Total connections handled'),\n }).optional(),\n \n /**\n * Request metrics\n */\n requests: z.object({\n total: z.number().int().describe('Total requests processed'),\n success: z.number().int().describe('Successful requests'),\n errors: z.number().int().describe('Failed requests'),\n }).optional(),\n});\n\nexport type ServerStatus = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create HTTP server configuration\n */\nexport const HttpServerConfig = Object.assign(HttpServerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create middleware configuration\n */\nexport const MiddlewareConfig = Object.assign(MiddlewareConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Audit Log Architecture\n * \n * Comprehensive audit logging system for compliance and security.\n * Supports SOX, HIPAA, GDPR, and other regulatory requirements.\n * \n * Features:\n * - Records all CRUD operations on data\n * - Tracks authentication events (login, logout, password reset)\n * - Monitors authorization changes (permissions, roles)\n * - Configurable retention policies (180-day GDPR requirement)\n * - Suspicious activity detection and alerting\n */\n\n/**\n * Audit Event Type Enum\n * Categorizes different types of auditable events in the system\n */\nexport const AuditEventType = z.enum([\n // Data Operations (CRUD)\n 'data.create', // Record creation\n 'data.read', // Record retrieval/viewing\n 'data.update', // Record modification\n 'data.delete', // Record deletion\n 'data.export', // Data export operations\n 'data.import', // Data import operations\n 'data.bulk_update', // Bulk update operations\n 'data.bulk_delete', // Bulk delete operations\n \n // Authentication Events\n 'auth.login', // Successful login\n 'auth.login_failed', // Failed login attempt\n 'auth.logout', // User logout\n 'auth.session_created', // New session created\n 'auth.session_expired', // Session expiration\n 'auth.password_reset', // Password reset initiated\n 'auth.password_changed', // Password successfully changed\n 'auth.email_verified', // Email verification completed\n 'auth.mfa_enabled', // Multi-factor auth enabled\n 'auth.mfa_disabled', // Multi-factor auth disabled\n 'auth.account_locked', // Account locked (too many failures)\n 'auth.account_unlocked', // Account unlocked\n \n // Authorization Events\n 'authz.permission_granted', // Permission granted to user\n 'authz.permission_revoked', // Permission revoked from user\n 'authz.role_assigned', // Role assigned to user\n 'authz.role_removed', // Role removed from user\n 'authz.role_created', // New role created\n 'authz.role_updated', // Role permissions modified\n 'authz.role_deleted', // Role deleted\n 'authz.policy_created', // Security policy created\n 'authz.policy_updated', // Security policy updated\n 'authz.policy_deleted', // Security policy deleted\n \n // System Events\n 'system.config_changed', // System configuration modified\n 'system.plugin_installed', // Plugin installed\n 'system.plugin_uninstalled', // Plugin uninstalled\n 'system.backup_created', // Backup created\n 'system.backup_restored', // Backup restored\n 'system.integration_added', // External integration added\n 'system.integration_removed',// External integration removed\n \n // Security Events\n 'security.access_denied', // Access denied (authorization failure)\n 'security.suspicious_activity', // Suspicious activity detected\n 'security.data_breach', // Potential data breach detected\n 'security.api_key_created', // API key created\n 'security.api_key_revoked', // API key revoked\n]);\n\nexport type AuditEventType = z.infer;\n\n/**\n * Audit Event Severity Level\n * Indicates the importance/criticality of an audit event\n */\nexport const AuditEventSeverity = z.enum([\n 'debug', // Diagnostic information\n 'info', // Informational events (normal operations)\n 'notice', // Normal but significant events\n 'warning', // Warning conditions\n 'error', // Error conditions\n 'critical', // Critical conditions requiring immediate attention\n 'alert', // Action must be taken immediately\n 'emergency', // System is unusable\n]);\n\nexport type AuditEventSeverity = z.infer;\n\n/**\n * Audit Event Actor Schema\n * Identifies who/what performed the action\n */\nexport const AuditEventActorSchema = z.object({\n /**\n * Actor type (user, system, service, api_client, etc.)\n */\n type: z.enum(['user', 'system', 'service', 'api_client', 'integration']).describe('Actor type'),\n \n /**\n * Unique identifier for the actor\n */\n id: z.string().describe('Actor identifier'),\n \n /**\n * Display name of the actor\n */\n name: z.string().optional().describe('Actor display name'),\n \n /**\n * Email address (for user actors)\n */\n email: z.string().email().optional().describe('Actor email address'),\n \n /**\n * IP address of the actor\n */\n ipAddress: z.string().optional().describe('Actor IP address'),\n \n /**\n * User agent string (for web/API requests)\n */\n userAgent: z.string().optional().describe('User agent string'),\n});\n\nexport type AuditEventActor = z.infer;\n\n/**\n * Audit Event Target Schema\n * Identifies what was acted upon\n */\nexport const AuditEventTargetSchema = z.object({\n /**\n * Target type (e.g., 'object', 'record', 'user', 'role', 'config')\n */\n type: z.string().describe('Target type'),\n \n /**\n * Unique identifier for the target\n */\n id: z.string().describe('Target identifier'),\n \n /**\n * Display name of the target\n */\n name: z.string().optional().describe('Target display name'),\n \n /**\n * Additional metadata about the target\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Target metadata'),\n});\n\nexport type AuditEventTarget = z.infer;\n\n/**\n * Audit Event Change Schema\n * Describes what changed (for update operations)\n */\nexport const AuditEventChangeSchema = z.object({\n /**\n * Field/property that changed\n */\n field: z.string().describe('Changed field name'),\n \n /**\n * Value before the change\n */\n oldValue: z.unknown().optional().describe('Previous value'),\n \n /**\n * Value after the change\n */\n newValue: z.unknown().optional().describe('New value'),\n});\n\nexport type AuditEventChange = z.infer;\n\n/**\n * Audit Event Schema\n * Complete audit event record\n */\nexport const AuditEventSchema = z.object({\n /**\n * Unique identifier for this audit event\n */\n id: z.string().describe('Audit event ID'),\n \n /**\n * Type of event being audited\n */\n eventType: AuditEventType.describe('Event type'),\n \n /**\n * Severity level of the event\n */\n severity: AuditEventSeverity.default('info').describe('Event severity'),\n \n /**\n * Timestamp when the event occurred (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n \n /**\n * Who/what performed the action\n */\n actor: AuditEventActorSchema.describe('Event actor'),\n \n /**\n * What was acted upon\n */\n target: AuditEventTargetSchema.optional().describe('Event target'),\n \n /**\n * Human-readable description of the action\n */\n description: z.string().describe('Event description'),\n \n /**\n * Detailed changes (for update operations)\n */\n changes: z.array(AuditEventChangeSchema).optional().describe('List of changes'),\n \n /**\n * Result of the action (success, failure, partial)\n */\n result: z.enum(['success', 'failure', 'partial']).default('success').describe('Action result'),\n \n /**\n * Error message (if result is failure)\n */\n errorMessage: z.string().optional().describe('Error message'),\n \n /**\n * Tenant identifier (for multi-tenant systems)\n */\n tenantId: z.string().optional().describe('Tenant identifier'),\n \n /**\n * Request/trace ID for correlation\n */\n requestId: z.string().optional().describe('Request ID for tracing'),\n \n /**\n * Additional context and metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n \n /**\n * Geographic location (if available)\n */\n location: z.object({\n country: z.string().optional(),\n region: z.string().optional(),\n city: z.string().optional(),\n }).optional().describe('Geographic location'),\n});\n\nexport type AuditEvent = z.infer;\n\n/**\n * Audit Retention Policy Schema\n * Defines how long audit logs are retained\n */\nexport const AuditRetentionPolicySchema = z.object({\n /**\n * Retention period in days\n * Default: 180 days (GDPR 6-month requirement)\n */\n retentionDays: z.number().int().min(1).default(180).describe('Retention period in days'),\n \n /**\n * Whether to archive logs after retention period\n * If true, logs are moved to cold storage; if false, they are deleted\n */\n archiveAfterRetention: z.boolean().default(true).describe('Archive logs after retention period'),\n \n /**\n * Archive storage configuration\n */\n archiveStorage: z.object({\n type: z.enum(['s3', 'gcs', 'azure_blob', 'filesystem']).describe('Archive storage type'),\n endpoint: z.string().optional().describe('Storage endpoint URL'),\n bucket: z.string().optional().describe('Storage bucket/container name'),\n path: z.string().optional().describe('Storage path prefix'),\n credentials: z.record(z.string(), z.unknown()).optional().describe('Storage credentials'),\n }).optional().describe('Archive storage configuration'),\n \n /**\n * Event types that have different retention periods\n * Overrides the default retentionDays for specific event types\n */\n customRetention: z.record(z.string(), z.number().int().positive()).optional().describe('Custom retention by event type'),\n \n /**\n * Minimum retention period for compliance\n * Prevents accidental deletion below compliance requirements\n */\n minimumRetentionDays: z.number().int().positive().optional().describe('Minimum retention for compliance'),\n});\n\nexport type AuditRetentionPolicy = z.infer;\n\n/**\n * Suspicious Activity Rule Schema\n * Defines rules for detecting suspicious activities\n */\nexport const SuspiciousActivityRuleSchema = z.object({\n /**\n * Unique identifier for the rule\n */\n id: z.string().describe('Rule identifier'),\n \n /**\n * Rule name\n */\n name: z.string().describe('Rule name'),\n \n /**\n * Rule description\n */\n description: z.string().optional().describe('Rule description'),\n \n /**\n * Whether the rule is enabled\n */\n enabled: z.boolean().default(true).describe('Rule enabled status'),\n \n /**\n * Event types to monitor\n */\n eventTypes: z.array(AuditEventType).describe('Event types to monitor'),\n \n /**\n * Detection condition\n */\n condition: z.object({\n /**\n * Number of events that trigger the rule\n */\n threshold: z.number().int().positive().describe('Event threshold'),\n \n /**\n * Time window in seconds\n */\n windowSeconds: z.number().int().positive().describe('Time window in seconds'),\n \n /**\n * Grouping criteria (e.g., by actor.id, by ipAddress)\n */\n groupBy: z.array(z.string()).optional().describe('Grouping criteria'),\n \n /**\n * Additional filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters'),\n }).describe('Detection condition'),\n \n /**\n * Actions to take when rule is triggered\n */\n actions: z.array(z.enum([\n 'alert', // Send alert notification\n 'lock_account', // Lock the user account\n 'block_ip', // Block the IP address\n 'require_mfa', // Require multi-factor authentication\n 'log_critical', // Log as critical event\n 'webhook', // Call webhook\n ])).describe('Actions to take'),\n \n /**\n * Severity level for triggered alerts\n */\n alertSeverity: AuditEventSeverity.default('warning').describe('Alert severity'),\n \n /**\n * Notification configuration\n */\n notifications: z.object({\n /**\n * Email addresses to notify\n */\n email: z.array(z.string().email()).optional().describe('Email recipients'),\n \n /**\n * Slack webhook URL\n */\n slack: z.string().url().optional().describe('Slack webhook URL'),\n \n /**\n * Custom webhook URL\n */\n webhook: z.string().url().optional().describe('Custom webhook URL'),\n }).optional().describe('Notification configuration'),\n});\n\nexport type SuspiciousActivityRule = z.infer;\n\n/**\n * Audit Log Storage Configuration\n * Defines where and how audit logs are stored\n */\nexport const AuditStorageConfigSchema = z.object({\n /**\n * Storage backend type\n */\n type: z.enum([\n 'database', // Store in database (PostgreSQL, MySQL, etc.)\n 'elasticsearch', // Store in Elasticsearch\n 'mongodb', // Store in MongoDB\n 'clickhouse', // Store in ClickHouse (for analytics)\n 's3', // Store in S3-compatible storage\n 'gcs', // Store in Google Cloud Storage\n 'azure_blob', // Store in Azure Blob Storage\n 'custom', // Custom storage implementation\n ]).describe('Storage backend type'),\n \n /**\n * Connection string or configuration\n */\n connectionString: z.string().optional().describe('Connection string'),\n \n /**\n * Storage configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Storage-specific configuration'),\n \n /**\n * Whether to enable buffering/batching\n */\n bufferEnabled: z.boolean().default(true).describe('Enable buffering'),\n \n /**\n * Buffer size (number of events before flush)\n */\n bufferSize: z.number().int().positive().default(100).describe('Buffer size'),\n \n /**\n * Buffer flush interval in seconds\n */\n flushIntervalSeconds: z.number().int().positive().default(5).describe('Flush interval in seconds'),\n \n /**\n * Whether to compress stored data\n */\n compression: z.boolean().default(true).describe('Enable compression'),\n});\n\nexport type AuditStorageConfig = z.infer;\n\n/**\n * Audit Event Filter Schema\n * Defines filters for querying audit events\n */\nexport const AuditEventFilterSchema = z.object({\n /**\n * Filter by event types\n */\n eventTypes: z.array(AuditEventType).optional().describe('Event types to include'),\n \n /**\n * Filter by severity levels\n */\n severities: z.array(AuditEventSeverity).optional().describe('Severity levels to include'),\n \n /**\n * Filter by actor ID\n */\n actorId: z.string().optional().describe('Actor identifier'),\n \n /**\n * Filter by tenant ID\n */\n tenantId: z.string().optional().describe('Tenant identifier'),\n \n /**\n * Filter by time range\n */\n timeRange: z.object({\n from: z.string().datetime().describe('Start time'),\n to: z.string().datetime().describe('End time'),\n }).optional().describe('Time range filter'),\n \n /**\n * Filter by result status\n */\n result: z.enum(['success', 'failure', 'partial']).optional().describe('Result status'),\n \n /**\n * Search query (full-text search)\n */\n searchQuery: z.string().optional().describe('Search query'),\n \n /**\n * Custom filters\n */\n customFilters: z.record(z.string(), z.unknown()).optional().describe('Custom filters'),\n});\n\nexport type AuditEventFilter = z.infer;\n\n/**\n * Complete Audit Configuration Schema\n * Main configuration for the audit system\n */\nexport const AuditConfigSchema = z.object({\n /**\n * Unique identifier for this audit configuration\n * Must be in snake_case following ObjectStack conventions\n * Maximum length: 64 characters\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n \n /**\n * Human-readable label\n */\n label: z.string().describe('Display label'),\n \n /**\n * Whether audit logging is enabled\n */\n enabled: z.boolean().default(true).describe('Enable audit logging'),\n \n /**\n * Event types to audit\n * If not specified, all event types are audited\n */\n eventTypes: z.array(AuditEventType).optional().describe('Event types to audit'),\n \n /**\n * Event types to exclude from auditing\n */\n excludeEventTypes: z.array(AuditEventType).optional().describe('Event types to exclude'),\n \n /**\n * Minimum severity level to log\n * Events below this level are not logged\n */\n minimumSeverity: AuditEventSeverity.default('info').describe('Minimum severity level'),\n \n /**\n * Storage configuration\n */\n storage: AuditStorageConfigSchema.describe('Storage configuration'),\n \n /**\n * Retention policy\n */\n retentionPolicy: AuditRetentionPolicySchema.optional().describe('Retention policy'),\n \n /**\n * Suspicious activity detection rules\n */\n suspiciousActivityRules: z.array(SuspiciousActivityRuleSchema).default([]).describe('Suspicious activity rules'),\n \n /**\n * Whether to include sensitive data in audit logs\n * If false, sensitive fields are redacted/masked\n */\n includeSensitiveData: z.boolean().default(false).describe('Include sensitive data'),\n \n /**\n * Fields to redact from audit logs\n */\n redactFields: z.array(z.string()).default([\n 'password',\n 'passwordHash',\n 'token',\n 'apiKey',\n 'secret',\n 'creditCard',\n 'ssn',\n ]).describe('Fields to redact'),\n \n /**\n * Whether to log successful read operations\n * Can be disabled to reduce log volume\n */\n logReads: z.boolean().default(false).describe('Log read operations'),\n \n /**\n * Sampling rate for read operations (0.0 to 1.0)\n * Only applies if logReads is true\n */\n readSamplingRate: z.number().min(0).max(1).default(0.1).describe('Read sampling rate'),\n \n /**\n * Whether to log system/internal operations\n */\n logSystemEvents: z.boolean().default(true).describe('Log system events'),\n \n /**\n * Custom audit event handlers\n * Note: Function handlers are for runtime configuration only and will not be serialized to JSON Schema\n */\n customHandlers: z.array(z.object({\n eventType: AuditEventType.describe('Event type to handle'),\n handlerId: z.string().describe('Unique identifier for the handler'),\n })).optional().describe('Custom event handler references'),\n \n /**\n * Compliance mode configuration\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox', // Sarbanes-Oxley Act\n 'hipaa', // Health Insurance Portability and Accountability Act\n 'gdpr', // General Data Protection Regulation\n 'pci_dss', // Payment Card Industry Data Security Standard\n 'iso_27001',// ISO/IEC 27001\n 'fedramp', // Federal Risk and Authorization Management Program\n ])).optional().describe('Compliance standards'),\n \n /**\n * Whether to enforce immutable audit logs\n */\n immutableLogs: z.boolean().default(true).describe('Enforce immutable logs'),\n \n /**\n * Whether to require cryptographic signing\n */\n requireSigning: z.boolean().default(false).describe('Require log signing'),\n \n /**\n * Signing key configuration\n */\n signingKey: z.string().optional().describe('Signing key'),\n }).optional().describe('Compliance configuration'),\n});\n\nexport type AuditConfig = z.infer;\n\n/**\n * Default suspicious activity rules\n * Common security patterns to detect\n */\nexport const DEFAULT_SUSPICIOUS_ACTIVITY_RULES: SuspiciousActivityRule[] = [\n {\n id: 'multiple_failed_logins',\n name: 'Multiple Failed Login Attempts',\n description: 'Detects multiple failed login attempts from the same user or IP',\n enabled: true,\n eventTypes: ['auth.login_failed'],\n condition: {\n threshold: 5,\n windowSeconds: 600, // 10 minutes\n groupBy: ['actor.id', 'actor.ipAddress'],\n },\n actions: ['alert', 'lock_account'],\n alertSeverity: 'warning',\n },\n {\n id: 'bulk_data_export',\n name: 'Bulk Data Export',\n description: 'Detects large data export operations',\n enabled: true,\n eventTypes: ['data.export'],\n condition: {\n threshold: 3,\n windowSeconds: 3600, // 1 hour\n groupBy: ['actor.id'],\n },\n actions: ['alert', 'log_critical'],\n alertSeverity: 'warning',\n },\n {\n id: 'suspicious_permission_changes',\n name: 'Rapid Permission Changes',\n description: 'Detects rapid permission or role changes',\n enabled: true,\n eventTypes: ['authz.permission_granted', 'authz.role_assigned'],\n condition: {\n threshold: 10,\n windowSeconds: 300, // 5 minutes\n groupBy: ['actor.id'],\n },\n actions: ['alert', 'log_critical'],\n alertSeverity: 'critical',\n },\n {\n id: 'after_hours_access',\n name: 'After Hours Access',\n description: 'Detects access during non-business hours',\n enabled: false, // Disabled by default, requires time zone configuration\n eventTypes: ['auth.login'],\n condition: {\n threshold: 1,\n windowSeconds: 86400, // 24 hours\n },\n actions: ['alert'],\n alertSeverity: 'notice',\n },\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Logging Protocol - Comprehensive Observability Logging\n * \n * Unified logging protocol that combines:\n * - Basic kernel logging (LoggerConfig)\n * - Enterprise-grade features (LoggingConfig)\n * - Multiple log destinations (file, console, external services)\n * - Structured logging with enrichment\n * - Log aggregation and forwarding\n * - Integration with external log management systems\n */\n\n// ============================================================================\n// Basic Logger Protocol (formerly from logger.zod.ts)\n// ============================================================================\n\n/**\n * Log Level Enum\n * Standard RFC 5424 severity levels (simplified)\n */\nexport const LogLevel = z.enum([\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'fatal',\n 'silent'\n]).describe('Log severity level');\n\nexport type LogLevel = z.infer;\n\n/**\n * Log Format Enum\n */\nexport const LogFormat = z.enum([\n 'json', // Structured JSON for machine parsing\n 'text', // Simple text format\n 'pretty' // Colored human-readable output for CLI/console\n]).describe('Log output format');\n\nexport type LogFormat = z.infer;\n\n/**\n * Logger Configuration Schema\n * Configuration for the Kernel's internal logger\n */\nexport const LoggerConfigSchema = z.object({\n /**\n * Logger name\n */\n name: z.string().optional().describe('Logger name identifier'),\n\n /**\n * Minimum level to log\n */\n level: LogLevel.optional().default('info'),\n\n /**\n * Output format\n */\n format: LogFormat.optional().default('json'),\n\n /**\n * Redact sensitive keys\n */\n redact: z.array(z.string()).optional().default(['password', 'token', 'secret', 'key'])\n .describe('Keys to redact from log context'),\n\n /**\n * Enable source location (file/line)\n */\n sourceLocation: z.boolean().optional().default(false)\n .describe('Include file and line number'),\n\n /**\n * Log to file (optional)\n */\n file: z.string().optional().describe('Path to log file'),\n\n /**\n * Log rotation config (if file is set)\n */\n rotation: z.object({\n maxSize: z.string().optional().default('10m'),\n maxFiles: z.number().optional().default(5)\n }).optional()\n});\n\nexport type LoggerConfig = z.infer;\n\n/**\n * Log Entry Schema\n * The shape of a structured log record\n */\nexport const LogEntrySchema = z.object({\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n level: LogLevel,\n message: z.string().describe('Log message'),\n context: z.record(z.string(), z.unknown()).optional().describe('Structured context data'),\n error: z.record(z.string(), z.unknown()).optional().describe('Error object if present'),\n \n /** Tracing */\n traceId: z.string().optional().describe('Distributed trace ID'),\n spanId: z.string().optional().describe('Span ID'),\n \n /** Source */\n service: z.string().optional().describe('Service name'),\n component: z.string().optional().describe('Component name (e.g. plugin id)'),\n});\n\nexport type LogEntry = z.infer;\n\n// ============================================================================\n// Extended Logging Protocol (enterprise features)\n// ============================================================================\n\n/**\n * Extended Log Level Enum\n * Standard RFC 5424 severity levels with trace\n */\nexport const ExtendedLogLevel = z.enum([\n 'trace', // Very detailed debugging information\n 'debug', // Debugging information\n 'info', // Informational messages\n 'warn', // Warning messages\n 'error', // Error messages\n 'fatal', // Fatal errors causing shutdown\n]).describe('Extended log severity level');\n\nexport type ExtendedLogLevel = z.infer;\n\n/**\n * Log Destination Type Enum\n * Where logs can be sent\n */\nexport const LogDestinationType = z.enum([\n 'console', // Standard output/error\n 'file', // File system\n 'syslog', // System logger\n 'elasticsearch', // Elasticsearch\n 'cloudwatch', // AWS CloudWatch\n 'stackdriver', // Google Cloud Logging\n 'azure_monitor', // Azure Monitor\n 'datadog', // Datadog\n 'splunk', // Splunk\n 'loki', // Grafana Loki\n 'http', // HTTP endpoint\n 'kafka', // Apache Kafka\n 'redis', // Redis streams\n 'custom', // Custom implementation\n]).describe('Log destination type');\n\nexport type LogDestinationType = z.infer;\n\n/**\n * Console Destination Configuration\n */\nexport const ConsoleDestinationConfigSchema = z.object({\n /**\n * Output stream\n */\n stream: z.enum(['stdout', 'stderr']).optional().default('stdout'),\n\n /**\n * Enable colored output\n */\n colors: z.boolean().optional().default(true),\n\n /**\n * Pretty print JSON\n */\n prettyPrint: z.boolean().optional().default(false),\n}).describe('Console destination configuration');\n\nexport type ConsoleDestinationConfig = z.infer;\n\n/**\n * File Destination Configuration\n */\nexport const FileDestinationConfigSchema = z.object({\n /**\n * File path\n */\n path: z.string().describe('Log file path'),\n\n /**\n * Enable log rotation\n */\n rotation: z.object({\n /**\n * Maximum file size before rotation (e.g., '10m', '100k', '1g')\n */\n maxSize: z.string().optional().default('10m'),\n\n /**\n * Maximum number of files to keep\n */\n maxFiles: z.number().int().positive().optional().default(5),\n\n /**\n * Compress rotated files\n */\n compress: z.boolean().optional().default(true),\n\n /**\n * Rotation interval (e.g., 'daily', 'weekly')\n */\n interval: z.enum(['hourly', 'daily', 'weekly', 'monthly']).optional(),\n }).optional(),\n\n /**\n * File encoding\n */\n encoding: z.string().optional().default('utf8'),\n\n /**\n * Append to existing file\n */\n append: z.boolean().optional().default(true),\n}).describe('File destination configuration');\n\nexport type FileDestinationConfig = z.infer;\n\n/**\n * HTTP Destination Configuration\n */\nexport const HttpDestinationConfigSchema = z.object({\n /**\n * HTTP endpoint URL\n */\n url: z.string().url().describe('HTTP endpoint URL'),\n\n /**\n * HTTP method\n */\n method: z.enum(['POST', 'PUT']).optional().default('POST'),\n\n /**\n * Headers to include\n */\n headers: z.record(z.string(), z.string()).optional(),\n\n /**\n * Authentication\n */\n auth: z.object({\n type: z.enum(['basic', 'bearer', 'api_key']).describe('Auth type'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n apiKeyHeader: z.string().optional().default('X-API-Key'),\n }).optional(),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n /**\n * Maximum batch size\n */\n maxSize: z.number().int().positive().optional().default(100),\n\n /**\n * Flush interval in milliseconds\n */\n flushInterval: z.number().int().positive().optional().default(5000),\n }).optional(),\n\n /**\n * Retry configuration\n */\n retry: z.object({\n /**\n * Maximum retry attempts\n */\n maxAttempts: z.number().int().positive().optional().default(3),\n\n /**\n * Initial retry delay in milliseconds\n */\n initialDelay: z.number().int().positive().optional().default(1000),\n\n /**\n * Backoff multiplier\n */\n backoffMultiplier: z.number().positive().optional().default(2),\n }).optional(),\n\n /**\n * Timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().default(30000),\n}).describe('HTTP destination configuration');\n\nexport type HttpDestinationConfig = z.infer;\n\n/**\n * External Service Destination Configuration\n * Generic configuration for cloud logging services\n */\nexport const ExternalServiceDestinationConfigSchema = z.object({\n /**\n * Service-specific endpoint\n */\n endpoint: z.string().url().optional(),\n\n /**\n * Region (for cloud services)\n */\n region: z.string().optional(),\n\n /**\n * Credentials\n */\n credentials: z.object({\n accessKeyId: z.string().optional(),\n secretAccessKey: z.string().optional(),\n apiKey: z.string().optional(),\n projectId: z.string().optional(),\n }).optional(),\n\n /**\n * Log group/stream/index name\n */\n logGroup: z.string().optional(),\n logStream: z.string().optional(),\n index: z.string().optional(),\n\n /**\n * Service-specific configuration\n */\n config: z.record(z.string(), z.unknown()).optional(),\n}).describe('External service destination configuration');\n\nexport type ExternalServiceDestinationConfig = z.infer;\n\n/**\n * Log Destination Schema\n * Configuration for a single log destination\n */\nexport const LogDestinationSchema = z.object({\n /**\n * Destination name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Destination name (snake_case)'),\n\n /**\n * Destination type\n */\n type: LogDestinationType.describe('Destination type'),\n\n /**\n * Minimum log level for this destination\n */\n level: ExtendedLogLevel.optional().default('info'),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Console configuration\n */\n console: ConsoleDestinationConfigSchema.optional(),\n\n /**\n * File configuration\n */\n file: FileDestinationConfigSchema.optional(),\n\n /**\n * HTTP configuration\n */\n http: HttpDestinationConfigSchema.optional(),\n\n /**\n * External service configuration\n */\n externalService: ExternalServiceDestinationConfigSchema.optional(),\n\n /**\n * Format for this destination\n */\n format: z.enum(['json', 'text', 'pretty']).optional().default('json'),\n\n /**\n * Filter function reference (runtime only)\n */\n filterId: z.string().optional().describe('Filter function identifier'),\n}).describe('Log destination configuration');\n\nexport type LogDestination = z.infer;\n\n/**\n * Log Enrichment Configuration\n * Add contextual data to all log entries\n */\nexport const LogEnrichmentConfigSchema = z.object({\n /**\n * Static fields to add to all logs\n */\n staticFields: z.record(z.string(), z.unknown()).optional().describe('Static fields added to every log'),\n\n /**\n * Dynamic field enrichers (runtime only)\n * References to functions that add dynamic context\n */\n dynamicEnrichers: z.array(z.string()).optional().describe('Dynamic enricher function IDs'),\n\n /**\n * Add hostname\n */\n addHostname: z.boolean().optional().default(true),\n\n /**\n * Add process ID\n */\n addProcessId: z.boolean().optional().default(true),\n\n /**\n * Add environment info\n */\n addEnvironment: z.boolean().optional().default(true),\n\n /**\n * Add timestamp in additional formats\n */\n addTimestampFormats: z.object({\n unix: z.boolean().optional().default(false),\n iso: z.boolean().optional().default(true),\n }).optional(),\n\n /**\n * Add caller information (file, line, function)\n */\n addCaller: z.boolean().optional().default(false),\n\n /**\n * Add correlation IDs\n */\n addCorrelationIds: z.boolean().optional().default(true),\n}).describe('Log enrichment configuration');\n\nexport type LogEnrichmentConfig = z.infer;\n\n/**\n * Structured Log Entry Schema\n * Enhanced structured log record with enrichment\n */\nexport const StructuredLogEntrySchema = z.object({\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n\n /**\n * Log level\n */\n level: ExtendedLogLevel.describe('Log severity level'),\n\n /**\n * Log message\n */\n message: z.string().describe('Log message'),\n\n /**\n * Structured context data\n */\n context: z.record(z.string(), z.unknown()).optional().describe('Structured context'),\n\n /**\n * Error information\n */\n error: z.object({\n name: z.string().optional(),\n message: z.string().optional(),\n stack: z.string().optional(),\n code: z.string().optional(),\n details: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Error details'),\n\n /**\n * Trace context\n */\n trace: z.object({\n traceId: z.string().describe('Trace ID'),\n spanId: z.string().describe('Span ID'),\n parentSpanId: z.string().optional().describe('Parent span ID'),\n traceFlags: z.number().int().optional().describe('Trace flags'),\n }).optional().describe('Distributed tracing context'),\n\n /**\n * Source information\n */\n source: z.object({\n service: z.string().optional().describe('Service name'),\n component: z.string().optional().describe('Component name'),\n file: z.string().optional().describe('Source file'),\n line: z.number().int().optional().describe('Line number'),\n function: z.string().optional().describe('Function name'),\n }).optional().describe('Source information'),\n\n /**\n * Host information\n */\n host: z.object({\n hostname: z.string().optional(),\n pid: z.number().int().optional(),\n ip: z.string().optional(),\n }).optional().describe('Host information'),\n\n /**\n * Environment\n */\n environment: z.string().optional().describe('Environment (e.g., production, staging)'),\n\n /**\n * User information\n */\n user: z.object({\n id: z.string().optional(),\n username: z.string().optional(),\n email: z.string().optional(),\n }).optional().describe('User context'),\n\n /**\n * Request information\n */\n request: z.object({\n id: z.string().optional(),\n method: z.string().optional(),\n path: z.string().optional(),\n userAgent: z.string().optional(),\n ip: z.string().optional(),\n }).optional().describe('Request context'),\n\n /**\n * Custom labels/tags\n */\n labels: z.record(z.string(), z.string()).optional().describe('Custom labels'),\n\n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n}).describe('Structured log entry');\n\nexport type StructuredLogEntry = z.infer;\n\n/**\n * Logging Configuration Schema\n * Main configuration for the logging system\n */\nexport const LoggingConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable logging\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Global minimum log level\n */\n level: ExtendedLogLevel.optional().default('info'),\n\n /**\n * Default logger configuration\n * Basic logger config for the kernel\n */\n default: LoggerConfigSchema.optional().describe('Default logger configuration'),\n\n /**\n * Named logger configurations\n * Map of logger name to logger config for different components/modules\n */\n loggers: z.record(z.string(), LoggerConfigSchema).optional().describe('Named logger configurations'),\n\n /**\n * Log destinations\n */\n destinations: z.array(LogDestinationSchema).describe('Log destinations'),\n\n /**\n * Log enrichment configuration\n */\n enrichment: LogEnrichmentConfigSchema.optional(),\n\n /**\n * Fields to redact from logs\n */\n redact: z.array(z.string()).optional().default([\n 'password',\n 'passwordHash',\n 'token',\n 'apiKey',\n 'secret',\n 'creditCard',\n 'ssn',\n 'authorization',\n ]).describe('Fields to redact'),\n\n /**\n * Sampling configuration\n */\n sampling: z.object({\n /**\n * Enable sampling\n */\n enabled: z.boolean().optional().default(false),\n\n /**\n * Sample rate (0.0 to 1.0)\n */\n rate: z.number().min(0).max(1).optional().default(1.0),\n\n /**\n * Sample rate by level\n */\n rateByLevel: z.record(z.string(), z.number().min(0).max(1)).optional(),\n }).optional(),\n\n /**\n * Buffer configuration\n */\n buffer: z.object({\n /**\n * Enable buffering\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Buffer size\n */\n size: z.number().int().positive().optional().default(1000),\n\n /**\n * Flush interval in milliseconds\n */\n flushInterval: z.number().int().positive().optional().default(1000),\n\n /**\n * Flush on shutdown\n */\n flushOnShutdown: z.boolean().optional().default(true),\n }).optional(),\n\n /**\n * Performance configuration\n */\n performance: z.object({\n /**\n * Async logging\n */\n async: z.boolean().optional().default(true),\n\n /**\n * Worker threads for async logging\n */\n workers: z.number().int().positive().optional().default(1),\n }).optional(),\n}).describe('Logging configuration');\n\nexport type LoggingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metrics Protocol - Performance and Operational Metrics\n * \n * Comprehensive metrics collection and monitoring:\n * - Counter, Gauge, Histogram, Summary metric types\n * - Time-series data collection\n * - SLI/SLO definitions\n * - Metric aggregation and export\n * - Integration with monitoring systems (Prometheus, etc.)\n */\n\n/**\n * Metric Type Enum\n * Standard Prometheus metric types\n */\nexport const MetricType = z.enum([\n 'counter', // Monotonically increasing value\n 'gauge', // Value that can go up and down\n 'histogram', // Observations bucketed by configurable ranges\n 'summary', // Observations with quantiles\n]).describe('Metric type');\n\nexport type MetricType = z.infer;\n\n/**\n * Metric Unit Enum\n * Standard units for metrics\n */\nexport const MetricUnit = z.enum([\n // Time units\n 'nanoseconds',\n 'microseconds',\n 'milliseconds',\n 'seconds',\n 'minutes',\n 'hours',\n 'days',\n\n // Size units\n 'bytes',\n 'kilobytes',\n 'megabytes',\n 'gigabytes',\n 'terabytes',\n\n // Rate units\n 'requests_per_second',\n 'events_per_second',\n 'bytes_per_second',\n\n // Percentage\n 'percent',\n 'ratio',\n\n // Count\n 'count',\n 'operations',\n\n // Custom\n 'custom',\n]).describe('Metric unit');\n\nexport type MetricUnit = z.infer;\n\n/**\n * Metric Aggregation Type\n */\nexport const MetricAggregationType = z.enum([\n 'sum', // Sum of all values\n 'avg', // Average of all values\n 'min', // Minimum value\n 'max', // Maximum value\n 'count', // Count of observations\n 'p50', // 50th percentile (median)\n 'p75', // 75th percentile\n 'p90', // 90th percentile\n 'p95', // 95th percentile\n 'p99', // 99th percentile\n 'p999', // 99.9th percentile\n 'rate', // Rate of change\n 'stddev', // Standard deviation\n]).describe('Metric aggregation type');\n\nexport type MetricAggregationType = z.infer;\n\n/**\n * Histogram Bucket Configuration\n */\nexport const HistogramBucketConfigSchema = z.object({\n /**\n * Bucket type\n */\n type: z.enum(['linear', 'exponential', 'explicit']).describe('Bucket type'),\n\n /**\n * Linear bucket configuration\n */\n linear: z.object({\n start: z.number().describe('Start value'),\n width: z.number().positive().describe('Bucket width'),\n count: z.number().int().positive().describe('Number of buckets'),\n }).optional(),\n\n /**\n * Exponential bucket configuration\n */\n exponential: z.object({\n start: z.number().positive().describe('Start value'),\n factor: z.number().positive().describe('Growth factor'),\n count: z.number().int().positive().describe('Number of buckets'),\n }).optional(),\n\n /**\n * Explicit bucket boundaries\n */\n explicit: z.object({\n boundaries: z.array(z.number()).describe('Bucket boundaries'),\n }).optional(),\n}).describe('Histogram bucket configuration');\n\nexport type HistogramBucketConfig = z.infer;\n\n/**\n * Metric Labels Schema\n * Key-value pairs for metric dimensions\n */\nexport const MetricLabelsSchema = z.record(z.string(), z.string()).describe('Metric labels');\n\nexport type MetricLabels = z.infer;\n\n/**\n * Metric Definition Schema\n */\nexport const MetricDefinitionSchema = z.object({\n /**\n * Metric name (snake_case)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Metric name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().optional().describe('Display label'),\n\n /**\n * Metric type\n */\n type: MetricType.describe('Metric type'),\n\n /**\n * Metric unit\n */\n unit: MetricUnit.optional().describe('Metric unit'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('Metric description'),\n\n /**\n * Label names for this metric\n */\n labelNames: z.array(z.string()).optional().default([]).describe('Label names'),\n\n /**\n * Histogram configuration (for histogram type)\n */\n histogram: HistogramBucketConfigSchema.optional(),\n\n /**\n * Summary configuration (for summary type)\n */\n summary: z.object({\n /**\n * Quantiles to track\n */\n quantiles: z.array(z.number().min(0).max(1)).optional().default([0.5, 0.9, 0.99]),\n\n /**\n * Max age of observations in seconds\n */\n maxAge: z.number().int().positive().optional().default(600),\n\n /**\n * Number of age buckets\n */\n ageBuckets: z.number().int().positive().optional().default(5),\n }).optional(),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Metric definition');\n\nexport type MetricDefinition = z.infer;\n\n/**\n * Metric Data Point Schema\n * A single metric observation\n */\nexport const MetricDataPointSchema = z.object({\n /**\n * Metric name\n */\n name: z.string().describe('Metric name'),\n\n /**\n * Metric type\n */\n type: MetricType.describe('Metric type'),\n\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Observation timestamp'),\n\n /**\n * Value (for counter and gauge)\n */\n value: z.number().optional().describe('Metric value'),\n\n /**\n * Labels\n */\n labels: MetricLabelsSchema.optional().describe('Metric labels'),\n\n /**\n * Histogram data\n */\n histogram: z.object({\n count: z.number().int().nonnegative().describe('Total count'),\n sum: z.number().describe('Sum of all values'),\n buckets: z.array(z.object({\n upperBound: z.number().describe('Upper bound of bucket'),\n count: z.number().int().nonnegative().describe('Count in bucket'),\n })).describe('Histogram buckets'),\n }).optional(),\n\n /**\n * Summary data\n */\n summary: z.object({\n count: z.number().int().nonnegative().describe('Total count'),\n sum: z.number().describe('Sum of all values'),\n quantiles: z.array(z.object({\n quantile: z.number().min(0).max(1).describe('Quantile (0-1)'),\n value: z.number().describe('Quantile value'),\n })).describe('Summary quantiles'),\n }).optional(),\n}).describe('Metric data point');\n\nexport type MetricDataPoint = z.infer;\n\n/**\n * Time Series Data Point Schema\n */\nexport const TimeSeriesDataPointSchema = z.object({\n /**\n * Timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Timestamp'),\n\n /**\n * Value\n */\n value: z.number().describe('Value'),\n\n /**\n * Labels/tags\n */\n labels: z.record(z.string(), z.string()).optional().describe('Labels'),\n}).describe('Time series data point');\n\nexport type TimeSeriesDataPoint = z.infer;\n\n/**\n * Time Series Schema\n */\nexport const TimeSeriesSchema = z.object({\n /**\n * Series name\n */\n name: z.string().describe('Series name'),\n\n /**\n * Series labels\n */\n labels: z.record(z.string(), z.string()).optional().describe('Series labels'),\n\n /**\n * Data points\n */\n dataPoints: z.array(TimeSeriesDataPointSchema).describe('Data points'),\n\n /**\n * Start time\n */\n startTime: z.string().datetime().optional().describe('Start time'),\n\n /**\n * End time\n */\n endTime: z.string().datetime().optional().describe('End time'),\n}).describe('Time series');\n\nexport type TimeSeries = z.infer;\n\n/**\n * Metric Aggregation Configuration\n */\nexport const MetricAggregationConfigSchema = z.object({\n /**\n * Aggregation type\n */\n type: MetricAggregationType.describe('Aggregation type'),\n\n /**\n * Time window for aggregation\n */\n window: z.object({\n /**\n * Window size in seconds\n */\n size: z.number().int().positive().describe('Window size in seconds'),\n\n /**\n * Sliding window (true) or tumbling window (false)\n */\n sliding: z.boolean().optional().default(false),\n\n /**\n * Slide interval for sliding windows\n */\n slideInterval: z.number().int().positive().optional(),\n }).optional(),\n\n /**\n * Group by labels\n */\n groupBy: z.array(z.string()).optional().describe('Group by label names'),\n\n /**\n * Filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter criteria'),\n}).describe('Metric aggregation configuration');\n\nexport type MetricAggregationConfig = z.infer;\n\n/**\n * Service Level Indicator (SLI) Schema\n */\nexport const ServiceLevelIndicatorSchema = z.object({\n /**\n * SLI name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('SLI name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('SLI description'),\n\n /**\n * Metric name this SLI is based on\n */\n metric: z.string().describe('Base metric name'),\n\n /**\n * SLI type\n */\n type: z.enum([\n 'availability', // Percentage of successful requests\n 'latency', // Response time percentile\n 'throughput', // Requests per second\n 'error_rate', // Error percentage\n 'saturation', // Resource utilization\n 'custom', // Custom calculation\n ]).describe('SLI type'),\n\n /**\n * Success criteria\n */\n successCriteria: z.object({\n /**\n * Threshold value\n */\n threshold: z.number().describe('Threshold value'),\n\n /**\n * Comparison operator\n */\n operator: z.enum(['lt', 'lte', 'gt', 'gte', 'eq']).describe('Comparison operator'),\n\n /**\n * Percentile (for latency SLIs)\n */\n percentile: z.number().min(0).max(1).optional().describe('Percentile (0-1)'),\n }).describe('Success criteria'),\n\n /**\n * Measurement window\n */\n window: z.object({\n /**\n * Window size in seconds\n */\n size: z.number().int().positive().describe('Window size in seconds'),\n\n /**\n * Rolling window (true) or calendar-aligned (false)\n */\n rolling: z.boolean().optional().default(true),\n }).describe('Measurement window'),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Service Level Indicator');\n\nexport type ServiceLevelIndicator = z.infer;\n\n/**\n * Service Level Objective (SLO) Schema\n */\nexport const ServiceLevelObjectiveSchema = z.object({\n /**\n * SLO name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('SLO name (snake_case)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('SLO description'),\n\n /**\n * SLI this SLO is based on\n */\n sli: z.string().describe('SLI name'),\n\n /**\n * Target percentage (0-100)\n */\n target: z.number().min(0).max(100).describe('Target percentage'),\n\n /**\n * Time period for SLO\n */\n period: z.object({\n /**\n * Period type\n */\n type: z.enum(['rolling', 'calendar']).describe('Period type'),\n\n /**\n * Duration in seconds (for rolling)\n */\n duration: z.number().int().positive().optional().describe('Duration in seconds'),\n\n /**\n * Calendar period (for calendar)\n */\n calendar: z.enum(['daily', 'weekly', 'monthly', 'quarterly', 'yearly']).optional(),\n }).describe('Time period'),\n\n /**\n * Error budget configuration\n */\n errorBudget: z.object({\n /**\n * Auto-calculated budget (1 - target)\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Alert when budget consumed percentage exceeds threshold\n */\n alertThreshold: z.number().min(0).max(100).optional().default(80),\n\n /**\n * Burn rate alert windows\n */\n burnRateWindows: z.array(z.object({\n /**\n * Window size in seconds\n */\n window: z.number().int().positive().describe('Window size'),\n\n /**\n * Burn rate multiplier threshold\n */\n threshold: z.number().positive().describe('Burn rate threshold'),\n })).optional(),\n }).optional(),\n\n /**\n * Alert configuration\n */\n alerts: z.array(z.object({\n /**\n * Alert name\n */\n name: z.string().describe('Alert name'),\n\n /**\n * Severity\n */\n severity: z.enum(['info', 'warning', 'critical']).describe('Alert severity'),\n\n /**\n * Condition\n */\n condition: z.object({\n type: z.enum(['slo_breach', 'error_budget', 'burn_rate']).describe('Condition type'),\n threshold: z.number().optional().describe('Threshold value'),\n }).describe('Alert condition'),\n })).optional().default([]),\n\n /**\n * Enabled flag\n */\n enabled: z.boolean().optional().default(true),\n}).describe('Service Level Objective');\n\nexport type ServiceLevelObjective = z.infer;\n\n/**\n * Metric Export Configuration\n */\nexport const MetricExportConfigSchema = z.object({\n /**\n * Export type\n */\n type: z.enum([\n 'prometheus', // Prometheus exposition format\n 'openmetrics', // OpenMetrics format\n 'graphite', // Graphite plaintext protocol\n 'statsd', // StatsD protocol\n 'influxdb', // InfluxDB line protocol\n 'datadog', // Datadog agent\n 'cloudwatch', // AWS CloudWatch\n 'stackdriver', // Google Cloud Monitoring\n 'azure_monitor', // Azure Monitor\n 'http', // HTTP push\n 'custom', // Custom exporter\n ]).describe('Export type'),\n\n /**\n * Endpoint configuration\n */\n endpoint: z.string().optional().describe('Export endpoint'),\n\n /**\n * Export interval in seconds\n */\n interval: z.number().int().positive().optional().default(60),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n enabled: z.boolean().optional().default(true),\n size: z.number().int().positive().optional().default(1000),\n }).optional(),\n\n /**\n * Authentication\n */\n auth: z.object({\n type: z.enum(['none', 'basic', 'bearer', 'api_key']).describe('Auth type'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n }).optional(),\n\n /**\n * Additional configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Additional configuration'),\n}).describe('Metric export configuration');\n\nexport type MetricExportConfig = z.infer;\n\n/**\n * Metrics Configuration Schema\n */\nexport const MetricsConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable metrics collection\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Metric definitions\n */\n metrics: z.array(MetricDefinitionSchema).optional().default([]),\n\n /**\n * Default labels applied to all metrics\n */\n defaultLabels: MetricLabelsSchema.optional().default({}),\n\n /**\n * Aggregation configurations\n */\n aggregations: z.array(MetricAggregationConfigSchema).optional().default([]),\n\n /**\n * Service Level Indicators\n */\n slis: z.array(ServiceLevelIndicatorSchema).optional().default([]),\n\n /**\n * Service Level Objectives\n */\n slos: z.array(ServiceLevelObjectiveSchema).optional().default([]),\n\n /**\n * Export configurations\n */\n exports: z.array(MetricExportConfigSchema).optional().default([]),\n\n /**\n * Collection interval in seconds\n */\n collectionInterval: z.number().int().positive().optional().default(15),\n\n /**\n * Retention configuration\n */\n retention: z.object({\n /**\n * Retention period in seconds\n */\n period: z.number().int().positive().optional().default(604800), // 7 days\n\n /**\n * Downsampling configuration\n */\n downsampling: z.array(z.object({\n /**\n * After this duration, downsample to this resolution\n */\n afterSeconds: z.number().int().positive().describe('Downsample after seconds'),\n\n /**\n * Resolution in seconds\n */\n resolution: z.number().int().positive().describe('Downsampled resolution'),\n })).optional(),\n }).optional(),\n\n /**\n * Cardinality limits\n */\n cardinalityLimits: z.object({\n /**\n * Maximum unique label combinations per metric\n */\n maxLabelCombinations: z.number().int().positive().optional().default(10000),\n\n /**\n * Action when limit exceeded\n */\n onLimitExceeded: z.enum(['drop', 'sample', 'alert']).optional().default('alert'),\n }).optional(),\n}).describe('Metrics configuration');\n\nexport type MetricsConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tracing Protocol - Distributed Tracing & Observability\n * \n * Comprehensive distributed tracing based on OpenTelemetry standards:\n * - Trace context propagation\n * - Span creation and management\n * - Sampling strategies\n * - Integration with tracing backends (Jaeger, Zipkin, etc.)\n * - W3C Trace Context standard compliance\n */\n\n/**\n * Trace State Schema\n * W3C Trace Context tracestate header\n */\nexport const TraceStateSchema = z.object({\n /**\n * Vendor-specific key-value pairs\n */\n entries: z.record(z.string(), z.string()).describe('Trace state entries'),\n}).describe('Trace state');\n\nexport type TraceState = z.infer;\n\n/**\n * Trace Flags Enum\n * W3C Trace Context trace flags\n */\nexport const TraceFlagsSchema = z.number().int().min(0).max(255).describe('Trace flags bitmap');\n\nexport type TraceFlags = z.infer;\n\n/**\n * Trace Context Schema\n * W3C Trace Context standard\n */\nexport const TraceContextSchema = z.object({\n /**\n * Trace ID (128-bit identifier, 32 hex chars)\n */\n traceId: z.string()\n .regex(/^[0-9a-f]{32}$/)\n .describe('Trace ID (32 hex chars)'),\n\n /**\n * Span ID (64-bit identifier, 16 hex chars)\n */\n spanId: z.string()\n .regex(/^[0-9a-f]{16}$/)\n .describe('Span ID (16 hex chars)'),\n\n /**\n * Trace flags (8-bit)\n */\n traceFlags: TraceFlagsSchema.optional().default(1),\n\n /**\n * Trace state (vendor-specific)\n */\n traceState: TraceStateSchema.optional(),\n\n /**\n * Parent span ID\n */\n parentSpanId: z.string()\n .regex(/^[0-9a-f]{16}$/)\n .optional()\n .describe('Parent span ID (16 hex chars)'),\n\n /**\n * Is sampled\n */\n sampled: z.boolean().optional().default(true),\n\n /**\n * Remote context (from incoming request)\n */\n remote: z.boolean().optional().default(false),\n}).describe('Trace context (W3C Trace Context)');\n\nexport type TraceContext = z.infer;\n\n/**\n * Span Kind Enum\n * OpenTelemetry span kinds\n */\nexport const SpanKind = z.enum([\n 'internal', // Internal operation\n 'server', // Server-side request handling\n 'client', // Client-side request\n 'producer', // Message producer\n 'consumer', // Message consumer\n]).describe('Span kind');\n\nexport type SpanKind = z.infer;\n\n/**\n * Span Status Enum\n * OpenTelemetry span status\n */\nexport const SpanStatus = z.enum([\n 'unset', // Default status\n 'ok', // Successful operation\n 'error', // Error occurred\n]).describe('Span status');\n\nexport type SpanStatus = z.infer;\n\n/**\n * Span Attribute Value Schema\n */\nexport const SpanAttributeValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.array(z.string()),\n z.array(z.number()),\n z.array(z.boolean()),\n]).describe('Span attribute value');\n\nexport type SpanAttributeValue = z.infer;\n\n/**\n * Span Attributes Schema\n * OpenTelemetry semantic conventions\n */\nexport const SpanAttributesSchema = z.record(z.string(), SpanAttributeValueSchema).describe('Span attributes');\n\nexport type SpanAttributes = z.infer;\n\n/**\n * Span Event Schema\n */\nexport const SpanEventSchema = z.object({\n /**\n * Event name\n */\n name: z.string().describe('Event name'),\n\n /**\n * Event timestamp (ISO 8601)\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /**\n * Event attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Event attributes'),\n}).describe('Span event');\n\nexport type SpanEvent = z.infer;\n\n/**\n * Span Link Schema\n * Links to other spans\n */\nexport const SpanLinkSchema = z.object({\n /**\n * Linked trace context\n */\n context: TraceContextSchema.describe('Linked trace context'),\n\n /**\n * Link attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Link attributes'),\n}).describe('Span link');\n\nexport type SpanLink = z.infer;\n\n/**\n * Span Schema\n * OpenTelemetry span representation\n */\nexport const SpanSchema = z.object({\n /**\n * Trace context\n */\n context: TraceContextSchema.describe('Trace context'),\n\n /**\n * Span name\n */\n name: z.string().describe('Span name'),\n\n /**\n * Span kind\n */\n kind: SpanKind.optional().default('internal'),\n\n /**\n * Start time (ISO 8601)\n */\n startTime: z.string().datetime().describe('Span start time'),\n\n /**\n * End time (ISO 8601)\n */\n endTime: z.string().datetime().optional().describe('Span end time'),\n\n /**\n * Duration in milliseconds\n */\n duration: z.number().nonnegative().optional().describe('Duration in milliseconds'),\n\n /**\n * Span status\n */\n status: z.object({\n code: SpanStatus.describe('Status code'),\n message: z.string().optional().describe('Status message'),\n }).optional(),\n\n /**\n * Span attributes\n */\n attributes: SpanAttributesSchema.optional().default({}),\n\n /**\n * Span events\n */\n events: z.array(SpanEventSchema).optional().default([]),\n\n /**\n * Span links\n */\n links: z.array(SpanLinkSchema).optional().default([]),\n\n /**\n * Resource attributes\n */\n resource: SpanAttributesSchema.optional().describe('Resource attributes'),\n\n /**\n * Instrumentation library\n */\n instrumentationLibrary: z.object({\n name: z.string().describe('Library name'),\n version: z.string().optional().describe('Library version'),\n }).optional(),\n}).describe('OpenTelemetry span');\n\nexport type Span = z.infer;\n\n/**\n * Sampling Decision Enum\n */\nexport const SamplingDecision = z.enum([\n 'drop', // Do not record or export\n 'record_only', // Record but do not export\n 'record_and_sample', // Record and export\n]).describe('Sampling decision');\n\nexport type SamplingDecision = z.infer;\n\n/**\n * Sampling Strategy Type Enum\n */\nexport const SamplingStrategyType = z.enum([\n 'always_on', // Always sample\n 'always_off', // Never sample\n 'trace_id_ratio', // Sample based on trace ID ratio\n 'rate_limiting', // Rate-limited sampling\n 'parent_based', // Respect parent span sampling decision\n 'probability', // Probability-based sampling\n 'composite', // Combine multiple strategies\n 'custom', // Custom sampling logic\n]).describe('Sampling strategy type');\n\nexport type SamplingStrategyType = z.infer;\n\n/**\n * Trace Sampling Configuration Schema\n */\nexport const TraceSamplingConfigSchema = z.object({\n /**\n * Sampling strategy type\n */\n type: SamplingStrategyType.describe('Sampling strategy'),\n\n /**\n * Sample ratio (0.0 to 1.0) for trace_id_ratio and probability strategies\n */\n ratio: z.number().min(0).max(1).optional().describe('Sample ratio (0-1)'),\n\n /**\n * Rate limit (traces per second) for rate_limiting strategy\n */\n rateLimit: z.number().positive().optional().describe('Traces per second'),\n\n /**\n * Parent-based configuration\n */\n parentBased: z.object({\n /**\n * Sampler to use when parent is sampled\n */\n whenParentSampled: SamplingStrategyType.optional().default('always_on'),\n\n /**\n * Sampler to use when parent is not sampled\n */\n whenParentNotSampled: SamplingStrategyType.optional().default('always_off'),\n\n /**\n * Sampler to use when there is no parent (root span)\n */\n root: SamplingStrategyType.optional().default('trace_id_ratio'),\n\n /**\n * Root sampler ratio\n */\n rootRatio: z.number().min(0).max(1).optional().default(0.1),\n }).optional(),\n\n /**\n * Composite sampling (multiple strategies)\n */\n composite: z.array(z.object({\n strategy: SamplingStrategyType.describe('Strategy type'),\n ratio: z.number().min(0).max(1).optional(),\n condition: z.record(z.string(), z.unknown()).optional().describe('Condition for this strategy'),\n })).optional(),\n\n /**\n * Sampling rules\n */\n rules: z.array(z.object({\n /**\n * Rule name\n */\n name: z.string().describe('Rule name'),\n\n /**\n * Match condition\n */\n match: z.object({\n /**\n * Service name pattern\n */\n service: z.string().optional(),\n\n /**\n * Span name pattern (regex)\n */\n spanName: z.string().optional(),\n\n /**\n * Attribute filters\n */\n attributes: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n\n /**\n * Sampling decision for matching spans\n */\n decision: SamplingDecision.describe('Sampling decision'),\n\n /**\n * Sample rate for this rule\n */\n rate: z.number().min(0).max(1).optional(),\n })).optional().default([]),\n\n /**\n * Custom sampler ID (for custom strategy)\n */\n customSamplerId: z.string().optional().describe('Custom sampler identifier'),\n}).describe('Trace sampling configuration');\n\nexport type TraceSamplingConfig = z.infer;\n\n/**\n * Trace Context Propagation Format Enum\n */\nexport const TracePropagationFormat = z.enum([\n 'w3c', // W3C Trace Context\n 'b3', // Zipkin B3 (single header)\n 'b3_multi', // Zipkin B3 (multi header)\n 'jaeger', // Jaeger propagation\n 'xray', // AWS X-Ray\n 'ottrace', // OpenTracing\n 'custom', // Custom format\n]).describe('Trace propagation format');\n\nexport type TracePropagationFormat = z.infer;\n\n/**\n * Trace Context Propagation Schema\n */\nexport const TraceContextPropagationSchema = z.object({\n /**\n * Propagation formats (in priority order)\n */\n formats: z.array(TracePropagationFormat).optional().default(['w3c']),\n\n /**\n * Extract context from incoming requests\n */\n extract: z.boolean().optional().default(true),\n\n /**\n * Inject context into outgoing requests\n */\n inject: z.boolean().optional().default(true),\n\n /**\n * Custom header mappings\n */\n headers: z.object({\n /**\n * Trace ID header name\n */\n traceId: z.string().optional(),\n\n /**\n * Span ID header name\n */\n spanId: z.string().optional(),\n\n /**\n * Trace flags header name\n */\n traceFlags: z.string().optional(),\n\n /**\n * Trace state header name\n */\n traceState: z.string().optional(),\n }).optional(),\n\n /**\n * Baggage propagation\n */\n baggage: z.object({\n /**\n * Enable baggage propagation\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Maximum baggage size in bytes\n */\n maxSize: z.number().int().positive().optional().default(8192),\n\n /**\n * Allowed baggage keys (whitelist)\n */\n allowedKeys: z.array(z.string()).optional(),\n }).optional(),\n}).describe('Trace context propagation');\n\nexport type TraceContextPropagation = z.infer;\n\n/**\n * OpenTelemetry Exporter Type Enum\n */\nexport const OtelExporterType = z.enum([\n 'otlp_http', // OTLP over HTTP\n 'otlp_grpc', // OTLP over gRPC\n 'jaeger', // Jaeger\n 'zipkin', // Zipkin\n 'console', // Console (for debugging)\n 'datadog', // Datadog\n 'honeycomb', // Honeycomb\n 'lightstep', // Lightstep\n 'newrelic', // New Relic\n 'custom', // Custom exporter\n]).describe('OpenTelemetry exporter type');\n\nexport type OtelExporterType = z.infer;\n\n/**\n * OpenTelemetry Compatibility Schema\n */\nexport const OpenTelemetryCompatibilitySchema = z.object({\n /**\n * OpenTelemetry SDK version\n */\n sdkVersion: z.string().optional().describe('OTel SDK version'),\n\n /**\n * Exporter configuration\n */\n exporter: z.object({\n /**\n * Exporter type\n */\n type: OtelExporterType.describe('Exporter type'),\n\n /**\n * Endpoint URL\n */\n endpoint: z.string().url().optional().describe('Exporter endpoint'),\n\n /**\n * Protocol version\n */\n protocol: z.string().optional().describe('Protocol version'),\n\n /**\n * Headers\n */\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n\n /**\n * Timeout in milliseconds\n */\n timeout: z.number().int().positive().optional().default(10000),\n\n /**\n * Compression\n */\n compression: z.enum(['none', 'gzip']).optional().default('none'),\n\n /**\n * Batch configuration\n */\n batch: z.object({\n /**\n * Maximum batch size\n */\n maxBatchSize: z.number().int().positive().optional().default(512),\n\n /**\n * Maximum queue size\n */\n maxQueueSize: z.number().int().positive().optional().default(2048),\n\n /**\n * Export timeout in milliseconds\n */\n exportTimeout: z.number().int().positive().optional().default(30000),\n\n /**\n * Scheduled delay in milliseconds\n */\n scheduledDelay: z.number().int().positive().optional().default(5000),\n }).optional(),\n }).describe('Exporter configuration'),\n\n /**\n * Resource attributes (service identification)\n */\n resource: z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Service name'),\n\n /**\n * Service version\n */\n serviceVersion: z.string().optional().describe('Service version'),\n\n /**\n * Service instance ID\n */\n serviceInstanceId: z.string().optional().describe('Service instance ID'),\n\n /**\n * Service namespace\n */\n serviceNamespace: z.string().optional().describe('Service namespace'),\n\n /**\n * Deployment environment\n */\n deploymentEnvironment: z.string().optional().describe('Deployment environment'),\n\n /**\n * Additional resource attributes\n */\n attributes: SpanAttributesSchema.optional().describe('Additional resource attributes'),\n }).describe('Resource attributes'),\n\n /**\n * Instrumentation configuration\n */\n instrumentation: z.object({\n /**\n * Auto-instrumentation enabled\n */\n autoInstrumentation: z.boolean().optional().default(true),\n\n /**\n * Instrumentation libraries to enable\n */\n libraries: z.array(z.string()).optional().describe('Enabled libraries'),\n\n /**\n * Instrumentation libraries to disable\n */\n disabledLibraries: z.array(z.string()).optional().describe('Disabled libraries'),\n }).optional(),\n\n /**\n * Semantic conventions version\n */\n semanticConventionsVersion: z.string().optional().describe('Semantic conventions version'),\n}).describe('OpenTelemetry compatibility configuration');\n\nexport type OpenTelemetryCompatibility = z.infer;\n\n/**\n * Tracing Configuration Schema\n */\nexport const TracingConfigSchema = z.object({\n /**\n * Configuration name\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .max(64)\n .describe('Configuration name (snake_case, max 64 chars)'),\n\n /**\n * Display label\n */\n label: z.string().describe('Display label'),\n\n /**\n * Enable tracing\n */\n enabled: z.boolean().optional().default(true),\n\n /**\n * Sampling configuration\n */\n sampling: TraceSamplingConfigSchema.optional().default({ type: 'always_on', rules: [] }),\n\n /**\n * Context propagation\n */\n propagation: TraceContextPropagationSchema.optional().default({ formats: ['w3c'], extract: true, inject: true }),\n\n /**\n * OpenTelemetry configuration\n */\n openTelemetry: OpenTelemetryCompatibilitySchema.optional(),\n\n /**\n * Span limits\n */\n spanLimits: z.object({\n /**\n * Maximum number of attributes per span\n */\n maxAttributes: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum number of events per span\n */\n maxEvents: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum number of links per span\n */\n maxLinks: z.number().int().positive().optional().default(128),\n\n /**\n * Maximum attribute value length\n */\n maxAttributeValueLength: z.number().int().positive().optional().default(4096),\n }).optional(),\n\n /**\n * Trace ID generator\n */\n traceIdGenerator: z.enum(['random', 'uuid', 'custom']).optional().default('random'),\n\n /**\n * Custom trace ID generator ID\n */\n customTraceIdGeneratorId: z.string().optional().describe('Custom generator identifier'),\n\n /**\n * Performance configuration\n */\n performance: z.object({\n /**\n * Async span export\n */\n asyncExport: z.boolean().optional().default(true),\n\n /**\n * Background export interval in milliseconds\n */\n exportInterval: z.number().int().positive().optional().default(5000),\n }).optional(),\n}).describe('Tracing configuration');\n\nexport type TracingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Unified Security Context Protocol\n *\n * Provides a central governance layer that correlates and unifies\n * the four independent security subsystems:\n * - **Audit** (audit.zod.ts): Event logging and suspicious activity detection\n * - **Encryption** (encryption.zod.ts): Field-level encryption and key management\n * - **Compliance** (compliance.zod.ts): Regulatory framework enforcement (GDPR/HIPAA/SOX/PCI-DSS)\n * - **Masking** (masking.zod.ts): PII data masking and tokenization\n *\n * This schema enforces cross-cutting security policies, ensuring compliance\n * frameworks drive encryption requirements, masking rules respect role-based\n * audit visibility, and all security operations are correlated in a single\n * governance context.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Shared data classification enum used across security subsystems.\n * Defines the canonical set of data sensitivity labels.\n */\nexport const DataClassificationSchema = z.enum([\n 'pii', 'phi', 'pci', 'financial', 'confidential', 'internal', 'public',\n]).describe('Data classification level');\n\nexport type DataClassification = z.infer;\n\n/**\n * Shared compliance framework enum used across compliance and security schemas.\n * Defines the canonical set of regulatory frameworks.\n */\nexport const ComplianceFrameworkSchema = z.enum([\n 'gdpr', 'hipaa', 'sox', 'pci_dss', 'ccpa', 'iso27001',\n]).describe('Compliance framework identifier');\n\nexport type ComplianceFramework = z.infer;\n\n/**\n * Compliance-driven audit requirement.\n * Maps specific compliance frameworks to the audit event types that MUST be captured.\n */\nexport const ComplianceAuditRequirementSchema = z.object({\n framework: ComplianceFrameworkSchema\n .describe('Compliance framework identifier'),\n requiredEvents: z.array(z.string())\n .describe('Audit event types required by this framework (e.g., \"data.delete\", \"auth.login\")'),\n retentionDays: z.number().min(1)\n .describe('Minimum audit log retention period required by this framework (in days)'),\n alertOnMissing: z.boolean().default(true)\n .describe('Raise alert if a required audit event is not being captured'),\n}).describe('Compliance framework audit event requirements');\n\nexport type ComplianceAuditRequirement = z.infer;\n\n/**\n * Compliance-driven encryption requirement.\n * Maps compliance frameworks to encryption mandates for specific data classifications.\n */\nexport const ComplianceEncryptionRequirementSchema = z.object({\n framework: ComplianceFrameworkSchema\n .describe('Compliance framework identifier'),\n dataClassifications: z.array(DataClassificationSchema)\n .describe('Data classifications that must be encrypted under this framework'),\n minimumAlgorithm: z.enum(['aes-256-gcm', 'aes-256-cbc', 'chacha20-poly1305']).default('aes-256-gcm')\n .describe('Minimum encryption algorithm strength required'),\n keyRotationMaxDays: z.number().min(1).default(90)\n .describe('Maximum key rotation interval required (in days)'),\n}).describe('Compliance framework encryption requirements');\n\nexport type ComplianceEncryptionRequirement = z.infer;\n\n/**\n * Masking visibility rule.\n * Controls which roles can view unmasked data with audit trail enforcement.\n */\nexport const MaskingVisibilityRuleSchema = z.object({\n dataClassification: DataClassificationSchema\n .describe('Data classification this rule applies to'),\n defaultMasked: z.boolean().default(true)\n .describe('Whether data is masked by default'),\n unmaskRoles: z.array(z.string()).optional()\n .describe('Roles allowed to view unmasked data'),\n auditUnmask: z.boolean().default(true)\n .describe('Log an audit event when data is unmasked'),\n requireApproval: z.boolean().default(false)\n .describe('Require explicit approval before unmasking'),\n approvalRoles: z.array(z.string()).optional()\n .describe('Roles that can approve unmasking requests'),\n}).describe('Masking visibility and audit rule per data classification');\n\nexport type MaskingVisibilityRule = z.infer;\n\n/**\n * Security Event Correlation Schema.\n * Defines how security events from different subsystems are correlated.\n */\nexport const SecurityEventCorrelationSchema = z.object({\n enabled: z.boolean().default(true)\n .describe('Enable cross-subsystem security event correlation'),\n correlationId: z.boolean().default(true)\n .describe('Inject a shared correlation ID into audit, encryption, and masking events'),\n linkAuthToAudit: z.boolean().default(true)\n .describe('Link authentication events to subsequent data operation audit trails'),\n linkEncryptionToAudit: z.boolean().default(true)\n .describe('Log encryption/decryption operations in the audit trail'),\n linkMaskingToAudit: z.boolean().default(true)\n .describe('Log masking/unmasking operations in the audit trail'),\n}).describe('Cross-subsystem security event correlation configuration');\n\nexport type SecurityEventCorrelation = z.infer;\n\n/**\n * Data Classification Policy Schema.\n * Assigns classification labels to fields/objects for unified security enforcement.\n */\nexport const DataClassificationPolicySchema = z.object({\n classification: DataClassificationSchema\n .describe('Data classification level'),\n requireEncryption: z.boolean().default(false)\n .describe('Encryption required for this classification'),\n requireMasking: z.boolean().default(false)\n .describe('Masking required for this classification'),\n requireAudit: z.boolean().default(false)\n .describe('Audit trail required for access to this classification'),\n retentionDays: z.number().optional()\n .describe('Data retention limit in days (for compliance)'),\n}).describe('Security policy for a specific data classification level');\n\nexport type DataClassificationPolicy = z.infer;\n\n/**\n * Security Context Configuration Schema\n *\n * Top-level unified security governance context that ties together\n * audit, encryption, compliance, and masking subsystems.\n */\nexport const SecurityContextConfigSchema = z.object({\n enabled: z.boolean().default(true)\n .describe('Enable unified security context governance'),\n\n complianceAuditRequirements: z.array(ComplianceAuditRequirementSchema).optional()\n .describe('Compliance-driven audit event requirements'),\n\n complianceEncryptionRequirements: z.array(ComplianceEncryptionRequirementSchema).optional()\n .describe('Compliance-driven encryption requirements by data classification'),\n\n maskingVisibility: z.array(MaskingVisibilityRuleSchema).optional()\n .describe('Masking visibility rules per data classification'),\n\n dataClassifications: z.array(DataClassificationPolicySchema).optional()\n .describe('Data classification policies for unified security enforcement'),\n\n eventCorrelation: SecurityEventCorrelationSchema.optional()\n .describe('Cross-subsystem security event correlation settings'),\n\n enforceOnWrite: z.boolean().default(true)\n .describe('Enforce encryption and masking requirements on data write operations'),\n\n enforceOnRead: z.boolean().default(true)\n .describe('Enforce masking and audit requirements on data read operations'),\n\n failOpen: z.boolean().default(false)\n .describe('When false (default), deny access if security context cannot be evaluated'),\n}).describe('Unified security context governance configuration');\n\nexport type SecurityContextConfig = z.infer;\nexport type SecurityContextConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Change Type Enum\n * \n * Classification of change requests based on risk and approval requirements.\n * Follows ITIL change management best practices.\n */\nexport const ChangeTypeSchema = z.enum([\n 'standard', // Pre-approved, low-risk changes\n 'normal', // Requires standard approval process\n 'emergency', // Fast-track approval for critical issues\n 'major', // Requires CAB (Change Advisory Board) approval\n]);\n\n/**\n * Change Priority Enum\n * \n * Priority level for change request processing.\n */\nexport const ChangePrioritySchema = z.enum([\n 'critical',\n 'high',\n 'medium',\n 'low',\n]);\n\n/**\n * Change Status Enum\n * \n * Current status of a change request in its lifecycle.\n */\nexport const ChangeStatusSchema = z.enum([\n 'draft',\n 'submitted',\n 'in-review',\n 'approved',\n 'scheduled',\n 'in-progress',\n 'completed',\n 'failed',\n 'rolled-back',\n 'cancelled',\n]);\n\n/**\n * Change Impact Schema\n * \n * Assessment of the impact and scope of a change request.\n * Used for risk evaluation and approval routing.\n * \n * @example\n * ```json\n * {\n * \"level\": \"high\",\n * \"affectedSystems\": [\"crm-api\", \"customer-portal\"],\n * \"affectedUsers\": 5000,\n * \"downtime\": {\n * \"required\": true,\n * \"durationMinutes\": 30\n * }\n * }\n * ```\n */\nexport const ChangeImpactSchema = z.object({\n /**\n * Overall impact level of the change\n */\n level: z.enum(['low', 'medium', 'high', 'critical']).describe('Impact level'),\n\n /**\n * List of systems affected by this change\n */\n affectedSystems: z.array(z.string()).describe('Affected systems'),\n\n /**\n * Estimated number of users affected\n */\n affectedUsers: z.number().optional().describe('Affected user count'),\n\n /**\n * Downtime requirements\n */\n downtime: z.object({\n /**\n * Whether downtime is required\n */\n required: z.boolean().describe('Downtime required'),\n\n /**\n * Duration of downtime in minutes\n */\n durationMinutes: z.number().optional().describe('Downtime duration'),\n }).optional().describe('Downtime information'),\n});\n\n/**\n * Rollback Plan Schema\n * \n * Detailed procedure for reverting changes if implementation fails.\n * Required for all non-standard changes.\n * \n * @example\n * ```json\n * {\n * \"description\": \"Revert database schema to previous version\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Stop application servers\",\n * \"estimatedMinutes\": 5\n * },\n * {\n * \"order\": 2,\n * \"description\": \"Restore database backup\",\n * \"estimatedMinutes\": 15\n * }\n * ],\n * \"testProcedure\": \"Verify application login and basic functionality\"\n * }\n * ```\n */\nexport const RollbackPlanSchema = z.object({\n /**\n * High-level description of the rollback approach\n */\n description: z.string().describe('Rollback description'),\n\n /**\n * Sequential steps to execute rollback\n */\n steps: z.array(z.object({\n /**\n * Step execution order\n */\n order: z.number().describe('Step order'),\n\n /**\n * Detailed description of this step\n */\n description: z.string().describe('Step description'),\n\n /**\n * Estimated time to complete this step\n */\n estimatedMinutes: z.number().describe('Estimated duration'),\n })).describe('Rollback steps'),\n\n /**\n * Testing procedure to verify successful rollback\n */\n testProcedure: z.string().optional().describe('Test procedure'),\n});\n\n/**\n * Change Request Schema\n * \n * Comprehensive change management protocol for IT governance.\n * Supports change requests, deployment tracking, and ITIL compliance.\n * \n * @example\n * ```json\n * {\n * \"id\": \"CHG-2024-001\",\n * \"title\": \"Upgrade CRM Database Schema\",\n * \"description\": \"Migrate customer database to new schema version 2.0\",\n * \"type\": \"normal\",\n * \"priority\": \"high\",\n * \"status\": \"approved\",\n * \"requestedBy\": \"user_123\",\n * \"requestedAt\": 1704067200000,\n * \"impact\": {\n * \"level\": \"high\",\n * \"affectedSystems\": [\"crm-api\", \"customer-portal\"],\n * \"affectedUsers\": 5000,\n * \"downtime\": {\n * \"required\": true,\n * \"durationMinutes\": 30\n * }\n * },\n * \"implementation\": {\n * \"description\": \"Execute database migration scripts\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Backup current database\",\n * \"estimatedMinutes\": 10\n * }\n * ],\n * \"testing\": \"Run integration test suite\"\n * },\n * \"rollbackPlan\": {\n * \"description\": \"Restore from backup\",\n * \"steps\": [\n * {\n * \"order\": 1,\n * \"description\": \"Restore backup\",\n * \"estimatedMinutes\": 15\n * }\n * ]\n * },\n * \"schedule\": {\n * \"plannedStart\": 1704153600000,\n * \"plannedEnd\": 1704155400000\n * }\n * }\n * ```\n */\nexport const ChangeRequestSchema = z.object({\n /**\n * Unique change request identifier\n */\n id: z.string().describe('Change request ID'),\n\n /**\n * Short descriptive title of the change\n */\n title: z.string().describe('Change title'),\n\n /**\n * Detailed description of the change and its purpose\n */\n description: z.string().describe('Change description'),\n\n /**\n * Change classification type\n */\n type: ChangeTypeSchema.describe('Change type'),\n\n /**\n * Priority level for processing\n */\n priority: ChangePrioritySchema.describe('Change priority'),\n\n /**\n * Current status in the change lifecycle\n */\n status: ChangeStatusSchema.describe('Change status'),\n\n /**\n * User ID of the change requester\n */\n requestedBy: z.string().describe('Requester user ID'),\n\n /**\n * Timestamp when change was requested (Unix milliseconds)\n */\n requestedAt: z.number().describe('Request timestamp'),\n\n /**\n * Impact assessment of the change\n */\n impact: ChangeImpactSchema.describe('Impact assessment'),\n\n /**\n * Implementation plan and procedures\n */\n implementation: z.object({\n /**\n * High-level implementation description\n */\n description: z.string().describe('Implementation description'),\n\n /**\n * Sequential implementation steps\n */\n steps: z.array(z.object({\n /**\n * Step execution order\n */\n order: z.number().describe('Step order'),\n\n /**\n * Detailed description of this step\n */\n description: z.string().describe('Step description'),\n\n /**\n * Estimated time to complete this step\n */\n estimatedMinutes: z.number().describe('Estimated duration'),\n })).describe('Implementation steps'),\n\n /**\n * Testing procedures to verify successful implementation\n */\n testing: z.string().optional().describe('Testing procedure'),\n }).describe('Implementation plan'),\n\n /**\n * Rollback plan in case of failure\n */\n rollbackPlan: RollbackPlanSchema.describe('Rollback plan'),\n\n /**\n * Change schedule and timing\n */\n schedule: z.object({\n /**\n * Planned start time (Unix milliseconds)\n */\n plannedStart: z.number().describe('Planned start time'),\n\n /**\n * Planned end time (Unix milliseconds)\n */\n plannedEnd: z.number().describe('Planned end time'),\n\n /**\n * Actual start time (Unix milliseconds)\n */\n actualStart: z.number().optional().describe('Actual start time'),\n\n /**\n * Actual end time (Unix milliseconds)\n */\n actualEnd: z.number().optional().describe('Actual end time'),\n }).optional().describe('Schedule'),\n\n /**\n * Security impact assessment for the change (A.8.32)\n */\n securityImpact: z.object({\n /**\n * Whether a security impact assessment has been performed\n */\n assessed: z.boolean().describe('Whether security impact has been assessed'),\n\n /**\n * Security risk level of this change\n */\n riskLevel: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional()\n .describe('Security risk level'),\n\n /**\n * Data classifications affected by this change\n */\n affectedDataClassifications: z.array(DataClassificationSchema)\n .optional().describe('Affected data classifications'),\n\n /**\n * Whether the change requires security team approval\n */\n requiresSecurityApproval: z.boolean().default(false)\n .describe('Whether security team approval is required'),\n\n /**\n * Security reviewer user ID\n */\n reviewedBy: z.string().optional()\n .describe('Security reviewer user ID'),\n\n /**\n * Security review completion timestamp (Unix milliseconds)\n */\n reviewedAt: z.number().optional()\n .describe('Security review timestamp'),\n\n /**\n * Security review notes or conditions\n */\n reviewNotes: z.string().optional()\n .describe('Security review notes or conditions'),\n }).optional().describe('Security impact assessment per ISO 27001:2022 A.8.32'),\n\n /**\n * Approval workflow configuration\n */\n approval: z.object({\n /**\n * Whether approval is required for this change\n */\n required: z.boolean().describe('Approval required'),\n\n /**\n * List of approvers and their approval status\n */\n approvers: z.array(z.object({\n /**\n * Approver user ID\n */\n userId: z.string().describe('Approver user ID'),\n\n /**\n * Timestamp when approval was granted (Unix milliseconds)\n */\n approvedAt: z.number().optional().describe('Approval timestamp'),\n\n /**\n * Comments from the approver\n */\n comments: z.string().optional().describe('Approver comments'),\n })).describe('Approvers'),\n }).optional().describe('Approval workflow'),\n\n /**\n * Supporting documentation and files\n */\n attachments: z.array(z.object({\n /**\n * Attachment file name\n */\n name: z.string().describe('Attachment name'),\n\n /**\n * URL to download the attachment\n */\n url: z.string().url().describe('Attachment URL'),\n })).optional().describe('Attachments'),\n\n /**\n * Custom metadata key-value pairs for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n});\n\n// Type exports\nexport type ChangeRequest = z.infer;\nexport type ChangeType = z.infer;\nexport type ChangeStatus = z.infer;\nexport type ChangePriority = z.infer;\nexport type ChangeImpact = z.infer;\nexport type RollbackPlan = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldSchema } from '../data/field.zod';\nimport { ObjectSchema } from '../data/object.zod';\n\n// --- Atomic Operations ---\n\nexport const AddFieldOperation = z.object({\n type: z.literal('add_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to add'),\n field: FieldSchema.describe('Full field definition to add')\n}).describe('Add a new field to an existing object');\n\nexport const ModifyFieldOperation = z.object({\n type: z.literal('modify_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to modify'),\n changes: z.record(z.string(), z.unknown()).describe('Partial field definition updates')\n}).describe('Modify properties of an existing field');\n\nexport const RemoveFieldOperation = z.object({\n type: z.literal('remove_field'),\n objectName: z.string().describe('Target object name'),\n fieldName: z.string().describe('Name of the field to remove')\n}).describe('Remove a field from an existing object');\n\nexport const CreateObjectOperation = z.object({\n type: z.literal('create_object'),\n object: ObjectSchema.describe('Full object definition to create')\n}).describe('Create a new object');\n\nexport const RenameObjectOperation = z.object({\n type: z.literal('rename_object'),\n oldName: z.string().describe('Current object name'),\n newName: z.string().describe('New object name')\n}).describe('Rename an existing object');\n\nexport const DeleteObjectOperation = z.object({\n type: z.literal('delete_object'),\n objectName: z.string().describe('Name of the object to delete')\n}).describe('Delete an existing object');\n\nexport const ExecuteSqlOperation = z.object({\n type: z.literal('execute_sql'),\n sql: z.string().describe('Raw SQL statement to execute'),\n description: z.string().optional().describe('Human-readable description of the SQL')\n}).describe('Execute a raw SQL statement');\n\n// Union of all possible operations\nexport const MigrationOperationSchema = z.discriminatedUnion('type', [\n AddFieldOperation,\n ModifyFieldOperation,\n RemoveFieldOperation,\n CreateObjectOperation,\n RenameObjectOperation,\n DeleteObjectOperation,\n ExecuteSqlOperation\n]);\n\n// --- Migration & ChangeSet ---\n\nexport const MigrationDependencySchema = z.object({\n migrationId: z.string().describe('ID of the migration this depends on'),\n package: z.string().optional().describe('Package that owns the dependency migration')\n}).describe('Dependency reference to another migration that must run first');\n\nexport const ChangeSetSchema = z.object({\n id: z.string().uuid().describe('Unique identifier for this change set'),\n name: z.string().describe('Human readable name for the migration'),\n description: z.string().optional().describe('Detailed description of what this migration does'),\n author: z.string().optional().describe('Author who created this migration'),\n createdAt: z.string().datetime().optional().describe('ISO 8601 timestamp when the migration was created'),\n \n // Dependencies ensure migrations run in order\n dependencies: z.array(MigrationDependencySchema).optional().describe('Migrations that must run before this one'),\n \n // The actual atomic operations\n operations: z.array(MigrationOperationSchema).describe('Ordered list of atomic migration operations'),\n \n // Rollback operations (AI should generate these too)\n rollback: z.array(MigrationOperationSchema).optional().describe('Operations to reverse this migration')\n}).describe('A versioned set of atomic schema migration operations');\n\nexport type ChangeSet = z.infer;\nexport type MigrationOperation = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Better-Auth Configuration Protocol\n * \n * Defines the configuration required to initialize the Better-Auth kernel.\n * Used in server-side configuration injection.\n */\n\nexport const AuthProviderConfigSchema = z.object({\n id: z.string().describe('Provider ID (github, google)'),\n clientId: z.string().describe('OAuth Client ID'),\n clientSecret: z.string().describe('OAuth Client Secret'),\n scope: z.array(z.string()).optional().describe('Requested permissions'),\n});\n\nexport const AuthPluginConfigSchema = z.object({\n organization: z.boolean().default(false).describe('Enable Organization/Teams support'),\n twoFactor: z.boolean().default(false).describe('Enable 2FA'),\n passkeys: z.boolean().default(false).describe('Enable Passkey support'),\n magicLink: z.boolean().default(false).describe('Enable Magic Link login'),\n});\n\n/**\n * Mutual TLS (mTLS) Configuration Schema\n * \n * Enables client certificate authentication for zero-trust architectures.\n */\nexport const MutualTLSConfigSchema = z.object({\n /** Enable mutual TLS authentication */\n enabled: z.boolean()\n .default(false)\n .describe('Enable mutual TLS authentication'),\n\n /** Require client certificates for all connections */\n clientCertRequired: z.boolean()\n .default(false)\n .describe('Require client certificates for all connections'),\n\n /** PEM-encoded CA certificates or file paths for trust validation */\n trustedCAs: z.array(z.string())\n .describe('PEM-encoded CA certificates or file paths'),\n\n /** Certificate Revocation List URL */\n crlUrl: z.string()\n .optional()\n .describe('Certificate Revocation List (CRL) URL'),\n\n /** Online Certificate Status Protocol URL */\n ocspUrl: z.string()\n .optional()\n .describe('Online Certificate Status Protocol (OCSP) URL'),\n\n /** Certificate validation strictness level */\n certificateValidation: z.enum(['strict', 'relaxed', 'none'])\n .describe('Certificate validation strictness level'),\n\n /** Allowed Common Names on client certificates */\n allowedCNs: z.array(z.string())\n .optional()\n .describe('Allowed Common Names (CN) on client certificates'),\n\n /** Allowed Organizational Units on client certificates */\n allowedOUs: z.array(z.string())\n .optional()\n .describe('Allowed Organizational Units (OU) on client certificates'),\n\n /** Certificate pinning configuration */\n pinning: z.object({\n /** Enable certificate pinning */\n enabled: z.boolean().describe('Enable certificate pinning'),\n /** Array of pinned certificate hashes */\n pins: z.array(z.string()).describe('Pinned certificate hashes'),\n })\n .optional()\n .describe('Certificate pinning configuration'),\n});\n\nexport type MutualTLSConfig = z.infer;\n\n/**\n * Social / OAuth Provider Configuration\n *\n * Maps provider id → { clientId, clientSecret, ... }.\n * Keys must match Better-Auth built-in provider names (google, github, etc.).\n */\nexport const SocialProviderConfigSchema = z.record(\n z.string(),\n z.object({\n clientId: z.string().describe('OAuth Client ID'),\n clientSecret: z.string().describe('OAuth Client Secret'),\n enabled: z.boolean().optional().default(true).describe('Enable this provider'),\n scope: z.array(z.string()).optional().describe('Additional OAuth scopes'),\n }).catchall(z.unknown()),\n).optional().describe(\n 'Social/OAuth provider map forwarded to better-auth socialProviders. ' +\n 'Keys are provider ids (google, github, apple, …).'\n);\n\n/**\n * Email + Password Configuration\n */\nexport const EmailAndPasswordConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable email/password auth'),\n disableSignUp: z.boolean().optional().describe('Disable new user registration via email/password'),\n requireEmailVerification: z.boolean().optional().describe(\n 'Require email verification before creating a session'\n ),\n minPasswordLength: z.number().optional().describe('Minimum password length (default 8)'),\n maxPasswordLength: z.number().optional().describe('Maximum password length (default 128)'),\n resetPasswordTokenExpiresIn: z.number().optional().describe(\n 'Reset-password token TTL in seconds (default 3600)'\n ),\n autoSignIn: z.boolean().optional().describe('Auto sign-in after sign-up (default true)'),\n revokeSessionsOnPasswordReset: z.boolean().optional().describe(\n 'Revoke all other sessions on password reset'\n ),\n}).optional().describe('Email and password authentication options forwarded to better-auth');\n\n/**\n * Email Verification Configuration\n */\nexport const EmailVerificationConfigSchema = z.object({\n sendOnSignUp: z.boolean().optional().describe(\n 'Automatically send verification email after sign-up'\n ),\n sendOnSignIn: z.boolean().optional().describe(\n 'Send verification email on sign-in when not yet verified'\n ),\n autoSignInAfterVerification: z.boolean().optional().describe(\n 'Auto sign-in the user after email verification'\n ),\n expiresIn: z.number().optional().describe(\n 'Verification token TTL in seconds (default 3600)'\n ),\n}).optional().describe('Email verification options forwarded to better-auth');\n\n/**\n * Advanced / Low-level Better-Auth Options\n */\nexport const AdvancedAuthConfigSchema = z.object({\n crossSubDomainCookies: z.object({\n enabled: z.boolean().describe('Enable cross-subdomain cookies'),\n additionalCookies: z.array(z.string()).optional().describe('Extra cookies shared across subdomains'),\n domain: z.string().optional().describe(\n 'Cookie domain override — defaults to root domain derived from baseUrl'\n ),\n }).optional().describe(\n 'Share auth cookies across subdomains (critical for *.example.com multi-tenant)'\n ),\n useSecureCookies: z.boolean().optional().describe('Force Secure flag on cookies'),\n disableCSRFCheck: z.boolean().optional().describe(\n '⚠ Disable CSRF check — security risk, use with caution'\n ),\n cookiePrefix: z.string().optional().describe('Prefix for auth cookie names'),\n}).optional().describe('Advanced / low-level Better-Auth options');\n\nexport const AuthConfigSchema = z.object({\n secret: z.string().optional().describe('Encryption secret'),\n baseUrl: z.string().optional().describe('Base URL for auth routes'),\n databaseUrl: z.string().optional().describe('Database connection string'),\n providers: z.array(AuthProviderConfigSchema).optional(),\n plugins: AuthPluginConfigSchema.optional(),\n session: z.object({\n expiresIn: z.number().default(60 * 60 * 24 * 7).describe('Session duration in seconds'),\n updateAge: z.number().default(60 * 60 * 24).describe('Session update frequency'),\n }).optional(),\n trustedOrigins: z.array(z.string()).optional().describe(\n 'Trusted origins for CSRF protection. Supports wildcards (e.g. \"https://*.example.com\"). ' +\n 'The baseUrl origin is always trusted implicitly.'\n ),\n socialProviders: SocialProviderConfigSchema,\n emailAndPassword: EmailAndPasswordConfigSchema,\n emailVerification: EmailVerificationConfigSchema,\n advanced: AdvancedAuthConfigSchema,\n mutualTls: MutualTLSConfigSchema.optional().describe('Mutual TLS (mTLS) configuration'),\n}).catchall(z.unknown());\n\nexport type AuthProviderConfig = z.infer;\nexport type AuthPluginConfig = z.infer;\nexport type SocialProviderConfig = z.infer;\nexport type EmailAndPasswordConfig = z.infer;\nexport type EmailVerificationConfig = z.infer;\nexport type AdvancedAuthConfig = z.infer;\nexport type AuthConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ComplianceFrameworkSchema } from './security-context.zod';\n\n/**\n * Compliance protocol for GDPR, CCPA, HIPAA, SOX, PCI-DSS\n */\nexport const GDPRConfigSchema = z.object({\n enabled: z.boolean().describe('Enable GDPR compliance controls'),\n dataSubjectRights: z.object({\n rightToAccess: z.boolean().default(true).describe('Allow data subjects to access their data'),\n rightToRectification: z.boolean().default(true).describe('Allow data subjects to correct their data'),\n rightToErasure: z.boolean().default(true).describe('Allow data subjects to request deletion'),\n rightToRestriction: z.boolean().default(true).describe('Allow data subjects to restrict processing'),\n rightToPortability: z.boolean().default(true).describe('Allow data subjects to export their data'),\n rightToObjection: z.boolean().default(true).describe('Allow data subjects to object to processing'),\n }).describe('Data subject rights configuration per GDPR Articles 15-21'),\n legalBasis: z.enum([\n 'consent',\n 'contract',\n 'legal-obligation',\n 'vital-interests',\n 'public-task',\n 'legitimate-interests',\n ]).describe('Legal basis for data processing under GDPR Article 6'),\n consentTracking: z.boolean().default(true).describe('Track and record user consent'),\n dataRetentionDays: z.number().optional().describe('Maximum data retention period in days'),\n dataProcessingAgreement: z.string().optional().describe('URL or reference to the data processing agreement'),\n}).describe('GDPR (General Data Protection Regulation) compliance configuration');\n\nexport type GDPRConfig = z.infer;\nexport type GDPRConfigInput = z.input;\n\nexport const HIPAAConfigSchema = z.object({\n enabled: z.boolean().describe('Enable HIPAA compliance controls'),\n phi: z.object({\n encryption: z.boolean().default(true).describe('Encrypt Protected Health Information at rest'),\n accessControl: z.boolean().default(true).describe('Enforce role-based access to PHI'),\n auditTrail: z.boolean().default(true).describe('Log all PHI access events'),\n backupAndRecovery: z.boolean().default(true).describe('Enable PHI backup and disaster recovery'),\n }).describe('Protected Health Information safeguards'),\n businessAssociateAgreement: z.boolean().default(false).describe('BAA is in place with third-party processors'),\n}).describe('HIPAA (Health Insurance Portability and Accountability Act) compliance configuration');\n\nexport type HIPAAConfig = z.infer;\nexport type HIPAAConfigInput = z.input;\n\nexport const PCIDSSConfigSchema = z.object({\n enabled: z.boolean().describe('Enable PCI-DSS compliance controls'),\n level: z.enum(['1', '2', '3', '4']).describe('PCI-DSS compliance level (1 = highest)'),\n cardDataFields: z.array(z.string()).describe('Field names containing cardholder data'),\n tokenization: z.boolean().default(true).describe('Replace card data with secure tokens'),\n encryptionInTransit: z.boolean().default(true).describe('Encrypt cardholder data during transmission'),\n encryptionAtRest: z.boolean().default(true).describe('Encrypt stored cardholder data'),\n}).describe('PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration');\n\nexport type PCIDSSConfig = z.infer;\nexport type PCIDSSConfigInput = z.input;\n\nexport const AuditLogConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable audit logging'),\n retentionDays: z.number().default(365).describe('Number of days to retain audit logs'),\n immutable: z.boolean().default(true).describe('Prevent modification or deletion of audit logs'),\n signLogs: z.boolean().default(false).describe('Cryptographically sign log entries for tamper detection'),\n events: z.array(z.enum([\n 'create',\n 'read',\n 'update',\n 'delete',\n 'export',\n 'permission-change',\n 'login',\n 'logout',\n 'failed-login',\n ])).describe('Event types to capture in the audit log'),\n}).describe('Audit log configuration for compliance and security monitoring');\n\nexport type AuditLogConfig = z.infer;\nexport type AuditLogConfigInput = z.input;\n\n/**\n * Audit Finding Severity Schema\n *\n * Severity classification for audit findings.\n */\nexport const AuditFindingSeveritySchema = z.enum([\n 'critical', // Immediate remediation required\n 'major', // Significant non-conformity\n 'minor', // Minor non-conformity\n 'observation', // Improvement opportunity\n]);\n\n/**\n * Audit Finding Status Schema\n *\n * Lifecycle status of an audit finding.\n */\nexport const AuditFindingStatusSchema = z.enum([\n 'open', // Finding identified, not yet addressed\n 'in_remediation', // Remediation in progress\n 'remediated', // Remediation completed, pending verification\n 'verified', // Remediation verified and accepted\n 'accepted_risk', // Risk accepted by management\n 'closed', // Finding closed\n]);\n\n/**\n * Audit Finding Schema (A.5.35)\n *\n * Individual finding from a compliance or security audit.\n * Supports tracking from discovery through remediation and verification.\n *\n * @example\n * ```json\n * {\n * \"id\": \"FIND-2024-001\",\n * \"title\": \"Insufficient access logging\",\n * \"description\": \"PHI access events are not being logged for HIPAA compliance\",\n * \"severity\": \"major\",\n * \"status\": \"in_remediation\",\n * \"controlReference\": \"A.8.15\",\n * \"framework\": \"iso27001\",\n * \"identifiedAt\": 1704067200000,\n * \"identifiedBy\": \"external_auditor\",\n * \"remediationPlan\": \"Implement audit logging for all PHI access events\",\n * \"remediationDeadline\": 1706745600000\n * }\n * ```\n */\nexport const AuditFindingSchema = z.object({\n /**\n * Unique finding identifier\n */\n id: z.string().describe('Unique finding identifier'),\n\n /**\n * Short descriptive title\n */\n title: z.string().describe('Finding title'),\n\n /**\n * Detailed description of the finding\n */\n description: z.string().describe('Finding description'),\n\n /**\n * Finding severity\n */\n severity: AuditFindingSeveritySchema.describe('Finding severity'),\n\n /**\n * Current status\n */\n status: AuditFindingStatusSchema.describe('Finding status'),\n\n /**\n * ISO 27001 control reference (e.g., \"A.5.35\", \"A.8.15\")\n */\n controlReference: z.string().optional().describe('ISO 27001 control reference'),\n\n /**\n * Compliance framework\n */\n framework: ComplianceFrameworkSchema.optional()\n .describe('Related compliance framework'),\n\n /**\n * Timestamp when finding was identified (Unix milliseconds)\n */\n identifiedAt: z.number().describe('Identification timestamp'),\n\n /**\n * User or entity who identified the finding\n */\n identifiedBy: z.string().describe('Identifier (auditor name or system)'),\n\n /**\n * Planned remediation actions\n */\n remediationPlan: z.string().optional().describe('Remediation plan'),\n\n /**\n * Remediation deadline (Unix milliseconds)\n */\n remediationDeadline: z.number().optional().describe('Remediation deadline timestamp'),\n\n /**\n * Timestamp when remediation was verified (Unix milliseconds)\n */\n verifiedAt: z.number().optional().describe('Verification timestamp'),\n\n /**\n * Verifier name or role\n */\n verifiedBy: z.string().optional().describe('Verifier name or role'),\n\n /**\n * Notes or comments\n */\n notes: z.string().optional().describe('Additional notes'),\n}).describe('Audit finding with remediation tracking per ISO 27001:2022 A.5.35');\n\nexport type AuditFinding = z.infer;\n\n/**\n * Audit Schedule Schema (A.5.35)\n *\n * Defines audit scheduling for independent information security reviews.\n * Supports recurring audits, scope definition, and assessor assignment.\n *\n * @example\n * ```json\n * {\n * \"id\": \"AUDIT-2024-Q1\",\n * \"title\": \"Q1 ISO 27001 Internal Audit\",\n * \"scope\": [\"access_control\", \"encryption\", \"incident_response\"],\n * \"framework\": \"iso27001\",\n * \"scheduledAt\": 1711929600000,\n * \"assessor\": \"internal_audit_team\",\n * \"recurrenceMonths\": 3\n * }\n * ```\n */\nexport const AuditScheduleSchema = z.object({\n /**\n * Unique audit schedule identifier\n */\n id: z.string().describe('Unique audit schedule identifier'),\n\n /**\n * Audit title or name\n */\n title: z.string().describe('Audit title'),\n\n /**\n * Scope of areas to audit\n */\n scope: z.array(z.string()).describe('Audit scope areas'),\n\n /**\n * Target compliance framework\n */\n framework: ComplianceFrameworkSchema\n .describe('Target compliance framework'),\n\n /**\n * Scheduled audit date (Unix milliseconds)\n */\n scheduledAt: z.number().describe('Scheduled audit timestamp'),\n\n /**\n * Actual completion date (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Completion timestamp'),\n\n /**\n * Assessor name, team, or external firm\n */\n assessor: z.string().describe('Assessor or audit team'),\n\n /**\n * Whether this is an external (independent) audit\n */\n isExternal: z.boolean().default(false).describe('Whether this is an external audit'),\n\n /**\n * Recurrence interval in months (0 = one-time)\n */\n recurrenceMonths: z.number().default(0).describe('Recurrence interval in months (0 = one-time)'),\n\n /**\n * Findings from this audit\n */\n findings: z.array(AuditFindingSchema).optional().describe('Audit findings'),\n}).describe('Audit schedule for independent security reviews per ISO 27001:2022 A.5.35');\n\nexport type AuditSchedule = z.infer;\n\nexport const ComplianceConfigSchema = z.object({\n gdpr: GDPRConfigSchema.optional().describe('GDPR compliance settings'),\n hipaa: HIPAAConfigSchema.optional().describe('HIPAA compliance settings'),\n pciDss: PCIDSSConfigSchema.optional().describe('PCI-DSS compliance settings'),\n auditLog: AuditLogConfigSchema.describe('Audit log configuration'),\n auditSchedules: z.array(AuditScheduleSchema).optional()\n .describe('Scheduled compliance audits (A.5.35)'),\n}).describe('Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance');\n\nexport type ComplianceConfig = z.infer;\nexport type ComplianceConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Incident Response Protocol — ISO 27001:2022 (A.5.24–A.5.28)\n *\n * Defines schemas for information security event management including\n * incident classification, severity grading, response procedures,\n * and notification matrices.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Incident Severity Schema\n *\n * Severity grading for security incidents following ISO 27001 guidelines.\n * Determines response urgency and escalation requirements.\n */\nexport const IncidentSeveritySchema = z.enum([\n 'critical', // Immediate threat to business operations or data integrity\n 'high', // Significant impact requiring urgent response\n 'medium', // Moderate impact with controlled response timeline\n 'low', // Minor impact with standard response procedures\n]);\n\n/**\n * Incident Category Schema\n *\n * Classification of security incidents by type (A.5.25).\n * Used for routing, reporting, and trend analysis.\n */\nexport const IncidentCategorySchema = z.enum([\n 'data_breach', // Unauthorized access or disclosure of data\n 'malware', // Malicious software detection\n 'unauthorized_access', // Unauthorized system or data access\n 'denial_of_service', // Service availability attack\n 'social_engineering', // Phishing, pretexting, or manipulation\n 'insider_threat', // Threat originating from internal actors\n 'physical_security', // Physical security breach\n 'configuration_error', // Security misconfiguration\n 'vulnerability_exploit', // Exploitation of known vulnerability\n 'policy_violation', // Violation of security policies\n 'other', // Other security incidents\n]);\n\n/**\n * Incident Status Schema\n *\n * Current status of a security incident in its lifecycle.\n */\nexport const IncidentStatusSchema = z.enum([\n 'reported', // Initial report received\n 'triaged', // Severity and category assessed\n 'investigating', // Active investigation in progress\n 'containing', // Containment measures being applied\n 'eradicating', // Root cause being removed\n 'recovering', // Systems being restored to normal\n 'resolved', // Incident resolved\n 'closed', // Post-incident review complete\n]);\n\n/**\n * Incident Response Phase Schema\n *\n * Defines structured response phases per NIST SP 800-61 / ISO 27001 (A.5.26).\n */\nexport const IncidentResponsePhaseSchema = z.object({\n /**\n * Phase name identifier\n */\n phase: z.enum([\n 'identification',\n 'containment',\n 'eradication',\n 'recovery',\n 'lessons_learned',\n ]).describe('Response phase name'),\n\n /**\n * Phase description and objectives\n */\n description: z.string().describe('Phase description and objectives'),\n\n /**\n * Responsible team or role for this phase\n */\n assignedTo: z.string().describe('Responsible team or role'),\n\n /**\n * Target completion time in hours from incident start\n */\n targetHours: z.number().min(0).describe('Target completion time in hours'),\n\n /**\n * Actual completion timestamp (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Actual completion timestamp'),\n\n /**\n * Notes and findings during this phase\n */\n notes: z.string().optional().describe('Phase notes and findings'),\n}).describe('Incident response phase with timing and assignment');\n\nexport type IncidentResponsePhase = z.infer;\n\n/**\n * Notification Rule Schema\n *\n * Defines who must be notified and when, based on severity (A.5.27).\n */\nexport const IncidentNotificationRuleSchema = z.object({\n /**\n * Minimum severity level that triggers this notification\n */\n severity: IncidentSeveritySchema.describe('Minimum severity to trigger notification'),\n\n /**\n * Notification channels to use\n */\n channels: z.array(z.enum([\n 'email',\n 'sms',\n 'slack',\n 'pagerduty',\n 'webhook',\n ])).describe('Notification channels'),\n\n /**\n * Roles or teams to notify\n */\n recipients: z.array(z.string()).describe('Roles or teams to notify'),\n\n /**\n * Maximum time in minutes to send notification after incident detection\n */\n withinMinutes: z.number().min(1).describe('Notification deadline in minutes from detection'),\n\n /**\n * Whether to notify external regulators (for data breaches)\n */\n notifyRegulators: z.boolean().default(false)\n .describe('Whether to notify regulatory authorities'),\n\n /**\n * Regulatory notification deadline in hours (e.g., GDPR 72h)\n */\n regulatorDeadlineHours: z.number().optional()\n .describe('Regulatory notification deadline in hours'),\n}).describe('Incident notification rule per severity level');\n\nexport type IncidentNotificationRule = z.infer;\n\n/**\n * Notification Matrix Schema\n *\n * Complete notification matrix mapping severity levels to stakeholder groups (A.5.27).\n */\nexport const IncidentNotificationMatrixSchema = z.object({\n /**\n * Notification rules ordered by severity\n */\n rules: z.array(IncidentNotificationRuleSchema)\n .describe('Notification rules by severity level'),\n\n /**\n * Default escalation timeout in minutes before auto-escalation\n */\n escalationTimeoutMinutes: z.number().default(30)\n .describe('Auto-escalation timeout in minutes'),\n\n /**\n * Escalation chain: ordered list of roles to escalate to\n */\n escalationChain: z.array(z.string()).default([])\n .describe('Ordered escalation chain of roles'),\n}).describe('Incident notification matrix with escalation policies');\n\nexport type IncidentNotificationMatrix = z.infer;\n\n/**\n * Incident Schema\n *\n * Comprehensive security incident record following ISO 27001:2022 (A.5.24–A.5.28).\n * Tracks the full incident lifecycle from detection through post-incident review.\n *\n * @example\n * ```json\n * {\n * \"id\": \"INC-2024-001\",\n * \"title\": \"Unauthorized API Access Detected\",\n * \"description\": \"Multiple failed authentication attempts from unknown IP range\",\n * \"severity\": \"high\",\n * \"category\": \"unauthorized_access\",\n * \"status\": \"investigating\",\n * \"reportedBy\": \"monitoring_system\",\n * \"reportedAt\": 1704067200000,\n * \"affectedSystems\": [\"api-gateway\", \"auth-service\"],\n * \"affectedDataClassifications\": [\"pii\", \"confidential\"],\n * \"responsePhases\": [\n * {\n * \"phase\": \"identification\",\n * \"description\": \"Identify scope of unauthorized access\",\n * \"assignedTo\": \"security_team\",\n * \"targetHours\": 2\n * }\n * ]\n * }\n * ```\n */\nexport const IncidentSchema = z.object({\n /**\n * Unique incident identifier\n */\n id: z.string().describe('Unique incident identifier'),\n\n /**\n * Short descriptive title of the incident\n */\n title: z.string().describe('Incident title'),\n\n /**\n * Detailed description of the security event\n */\n description: z.string().describe('Detailed incident description'),\n\n /**\n * Severity classification\n */\n severity: IncidentSeveritySchema.describe('Incident severity level'),\n\n /**\n * Incident category / type\n */\n category: IncidentCategorySchema.describe('Incident category'),\n\n /**\n * Current status in the incident lifecycle\n */\n status: IncidentStatusSchema.describe('Current incident status'),\n\n /**\n * User or system that reported the incident\n */\n reportedBy: z.string().describe('Reporter user ID or system name'),\n\n /**\n * Timestamp when the incident was reported (Unix milliseconds)\n */\n reportedAt: z.number().describe('Report timestamp'),\n\n /**\n * Timestamp when the incident was detected (may differ from reported)\n */\n detectedAt: z.number().optional().describe('Detection timestamp'),\n\n /**\n * Timestamp when the incident was resolved\n */\n resolvedAt: z.number().optional().describe('Resolution timestamp'),\n\n /**\n * Systems affected by the incident\n */\n affectedSystems: z.array(z.string()).describe('Affected systems'),\n\n /**\n * Data classifications affected (for data breach assessment)\n */\n affectedDataClassifications: z.array(DataClassificationSchema)\n .optional().describe('Affected data classifications'),\n\n /**\n * Structured response phases tracking\n */\n responsePhases: z.array(IncidentResponsePhaseSchema).optional()\n .describe('Incident response phases'),\n\n /**\n * Root cause analysis (completed post-incident)\n */\n rootCause: z.string().optional().describe('Root cause analysis'),\n\n /**\n * Corrective actions taken or planned\n */\n correctiveActions: z.array(z.string()).optional()\n .describe('Corrective actions taken or planned'),\n\n /**\n * Lessons learned from the incident (A.5.28)\n */\n lessonsLearned: z.string().optional()\n .describe('Lessons learned from the incident'),\n\n /**\n * Related change request IDs (if changes resulted from incident)\n */\n relatedChangeRequestIds: z.array(z.string()).optional()\n .describe('Related change request IDs'),\n\n /**\n * Custom metadata for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Custom metadata key-value pairs'),\n}).describe('Security incident record per ISO 27001:2022 A.5.24–A.5.28');\n\n/**\n * Incident Response Policy Schema\n *\n * Organization-level incident response policy configuration (A.5.24).\n */\nexport const IncidentResponsePolicySchema = z.object({\n /**\n * Whether incident response is enabled\n */\n enabled: z.boolean().default(true)\n .describe('Enable incident response management'),\n\n /**\n * Notification matrix configuration\n */\n notificationMatrix: IncidentNotificationMatrixSchema\n .describe('Notification and escalation matrix'),\n\n /**\n * Default response team or role\n */\n defaultResponseTeam: z.string()\n .describe('Default incident response team or role'),\n\n /**\n * Maximum time in hours to begin initial triage\n */\n triageDeadlineHours: z.number().default(1)\n .describe('Maximum hours to begin triage after detection'),\n\n /**\n * Whether to require post-incident review for all incidents\n */\n requirePostIncidentReview: z.boolean().default(true)\n .describe('Require post-incident review for all incidents'),\n\n /**\n * Minimum severity level that requires regulatory notification\n */\n regulatoryNotificationThreshold: IncidentSeveritySchema.default('high')\n .describe('Minimum severity requiring regulatory notification'),\n\n /**\n * Retention period for incident records in days\n */\n retentionDays: z.number().default(2555)\n .describe('Incident record retention period in days (default ~7 years)'),\n}).describe('Organization-level incident response policy per ISO 27001:2022');\n\n// Type exports\nexport type IncidentSeverity = z.infer;\nexport type IncidentCategory = z.infer;\nexport type IncidentStatus = z.infer;\nexport type Incident = z.infer;\nexport type IncidentResponsePolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { DataClassificationSchema } from './security-context.zod';\n\n/**\n * Supplier Security Protocol — ISO 27001:2022 (A.5.19–A.5.22)\n *\n * Defines schemas for supplier information security management including\n * risk assessment, security requirements, monitoring, and change control.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Supplier Risk Level Schema\n *\n * Risk classification for supplier relationships based on data access\n * and service criticality.\n */\nexport const SupplierRiskLevelSchema = z.enum([\n 'critical', // Direct access to sensitive data or core infrastructure\n 'high', // Significant data processing or service dependency\n 'medium', // Limited data access with moderate dependency\n 'low', // Minimal data access and low service dependency\n]);\n\n/**\n * Supplier Assessment Status Schema\n *\n * Current status of a supplier security assessment.\n */\nexport const SupplierAssessmentStatusSchema = z.enum([\n 'pending', // Assessment not yet started\n 'in_progress', // Assessment currently underway\n 'completed', // Assessment completed\n 'expired', // Assessment past its validity period\n 'failed', // Supplier did not meet security requirements\n]);\n\n/**\n * Supplier Security Requirement Schema\n *\n * Individual security requirement to assess against a supplier (A.5.20).\n */\nexport const SupplierSecurityRequirementSchema = z.object({\n /**\n * Requirement identifier\n */\n id: z.string().describe('Requirement identifier'),\n\n /**\n * Requirement description\n */\n description: z.string().describe('Requirement description'),\n\n /**\n * ISO 27001 control reference (e.g., \"A.5.19\")\n */\n controlReference: z.string().optional()\n .describe('ISO 27001 control reference'),\n\n /**\n * Whether this requirement is mandatory\n */\n mandatory: z.boolean().default(true)\n .describe('Whether this requirement is mandatory'),\n\n /**\n * Compliance status\n */\n compliant: z.boolean().optional()\n .describe('Whether the supplier meets this requirement'),\n\n /**\n * Evidence or notes for compliance assessment\n */\n evidence: z.string().optional()\n .describe('Compliance evidence or assessment notes'),\n}).describe('Individual supplier security requirement');\n\nexport type SupplierSecurityRequirement = z.infer;\n\n/**\n * Supplier Security Assessment Schema\n *\n * Comprehensive supplier security assessment record (A.5.19–A.5.21).\n *\n * @example\n * ```json\n * {\n * \"supplierId\": \"SUP-001\",\n * \"supplierName\": \"Cloud Provider Inc.\",\n * \"riskLevel\": \"critical\",\n * \"status\": \"completed\",\n * \"assessedBy\": \"security_team\",\n * \"assessedAt\": 1704067200000,\n * \"validUntil\": 1735689600000,\n * \"requirements\": [\n * {\n * \"id\": \"REQ-001\",\n * \"description\": \"Data encryption at rest using AES-256\",\n * \"controlReference\": \"A.8.24\",\n * \"mandatory\": true,\n * \"compliant\": true\n * }\n * ],\n * \"overallCompliant\": true,\n * \"dataClassificationsShared\": [\"pii\", \"confidential\"]\n * }\n * ```\n */\nexport const SupplierSecurityAssessmentSchema = z.object({\n /**\n * Unique supplier identifier\n */\n supplierId: z.string().describe('Unique supplier identifier'),\n\n /**\n * Supplier name\n */\n supplierName: z.string().describe('Supplier display name'),\n\n /**\n * Risk classification\n */\n riskLevel: SupplierRiskLevelSchema.describe('Supplier risk classification'),\n\n /**\n * Assessment status\n */\n status: SupplierAssessmentStatusSchema.describe('Assessment status'),\n\n /**\n * User or team who performed the assessment\n */\n assessedBy: z.string().describe('Assessor user ID or team'),\n\n /**\n * Assessment completion timestamp (Unix milliseconds)\n */\n assessedAt: z.number().describe('Assessment timestamp'),\n\n /**\n * Assessment validity expiry (Unix milliseconds)\n */\n validUntil: z.number().describe('Assessment validity expiry timestamp'),\n\n /**\n * Security requirements assessed\n */\n requirements: z.array(SupplierSecurityRequirementSchema)\n .describe('Security requirements and their compliance status'),\n\n /**\n * Overall compliance result\n */\n overallCompliant: z.boolean().describe('Whether supplier meets all mandatory requirements'),\n\n /**\n * Data classifications shared with this supplier\n */\n dataClassificationsShared: z.array(DataClassificationSchema)\n .optional().describe('Data classifications shared with supplier'),\n\n /**\n * Services provided by the supplier\n */\n servicesProvided: z.array(z.string()).optional()\n .describe('Services provided by this supplier'),\n\n /**\n * Certifications held by the supplier\n */\n certifications: z.array(z.string()).optional()\n .describe('Supplier certifications (e.g., ISO 27001, SOC 2)'),\n\n /**\n * Remediation items for non-compliant requirements\n */\n remediationItems: z.array(z.object({\n requirementId: z.string().describe('Non-compliant requirement ID'),\n action: z.string().describe('Required remediation action'),\n deadline: z.number().describe('Remediation deadline timestamp'),\n status: z.enum(['pending', 'in_progress', 'completed']).default('pending')\n .describe('Remediation status'),\n })).optional().describe('Remediation items for non-compliant requirements'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Custom metadata key-value pairs'),\n}).describe('Supplier security assessment record per ISO 27001:2022 A.5.19–A.5.21');\n\n/**\n * Supplier Security Policy Schema\n *\n * Organization-level supplier security management policy (A.5.22).\n */\nexport const SupplierSecurityPolicySchema = z.object({\n /**\n * Whether supplier security management is enabled\n */\n enabled: z.boolean().default(true)\n .describe('Enable supplier security management'),\n\n /**\n * Reassessment interval in days\n */\n reassessmentIntervalDays: z.number().default(365)\n .describe('Supplier reassessment interval in days'),\n\n /**\n * Whether to require supplier security assessment before onboarding\n */\n requirePreOnboardingAssessment: z.boolean().default(true)\n .describe('Require security assessment before supplier onboarding'),\n\n /**\n * Minimum risk level that requires formal assessment\n */\n formalAssessmentThreshold: SupplierRiskLevelSchema.default('medium')\n .describe('Minimum risk level requiring formal assessment'),\n\n /**\n * Whether to monitor supplier security changes (A.5.22)\n */\n monitorChanges: z.boolean().default(true)\n .describe('Monitor supplier security posture changes'),\n\n /**\n * Required certifications for critical suppliers\n */\n requiredCertifications: z.array(z.string()).default([])\n .describe('Required certifications for critical-risk suppliers'),\n}).describe('Organization-level supplier security management policy per ISO 27001:2022');\n\n// Type exports\nexport type SupplierRiskLevel = z.infer;\nexport type SupplierAssessmentStatus = z.infer;\nexport type SupplierSecurityAssessment = z.infer;\nexport type SupplierSecurityPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Information Security Training Protocol — ISO 27001:2022 (A.6.3)\n *\n * Defines schemas for security awareness and training management including\n * course definitions, completion tracking, and organizational training plans.\n *\n * @see https://www.iso.org/standard/27001\n * @category Security\n */\n\n/**\n * Training Category Schema\n *\n * Classification of training content by domain.\n */\nexport const TrainingCategorySchema = z.enum([\n 'security_awareness', // General security awareness\n 'data_protection', // Data handling and privacy\n 'incident_response', // Incident reporting and response\n 'access_control', // Access management best practices\n 'phishing_awareness', // Phishing and social engineering\n 'compliance', // Regulatory compliance (GDPR, HIPAA, etc.)\n 'secure_development', // Secure coding and development practices\n 'physical_security', // Physical security awareness\n 'business_continuity', // Business continuity and disaster recovery\n 'other', // Other training categories\n]);\n\n/**\n * Training Completion Status Schema\n */\nexport const TrainingCompletionStatusSchema = z.enum([\n 'not_started', // Training not yet begun\n 'in_progress', // Training currently underway\n 'completed', // Training completed successfully\n 'failed', // Training assessment not passed\n 'expired', // Training certification has expired\n]);\n\n/**\n * Training Course Schema\n *\n * Definition of a security training course or module.\n *\n * @example\n * ```json\n * {\n * \"id\": \"COURSE-SEC-001\",\n * \"title\": \"Information Security Fundamentals\",\n * \"description\": \"Annual security awareness training for all employees\",\n * \"category\": \"security_awareness\",\n * \"durationMinutes\": 60,\n * \"mandatory\": true,\n * \"targetRoles\": [\"all_employees\"],\n * \"validityDays\": 365,\n * \"passingScore\": 80\n * }\n * ```\n */\nexport const TrainingCourseSchema = z.object({\n /**\n * Unique course identifier\n */\n id: z.string().describe('Unique course identifier'),\n\n /**\n * Course title\n */\n title: z.string().describe('Course title'),\n\n /**\n * Course description and objectives\n */\n description: z.string().describe('Course description and learning objectives'),\n\n /**\n * Training category\n */\n category: TrainingCategorySchema.describe('Training category'),\n\n /**\n * Estimated duration in minutes\n */\n durationMinutes: z.number().min(1).describe('Estimated course duration in minutes'),\n\n /**\n * Whether this training is mandatory\n */\n mandatory: z.boolean().default(false).describe('Whether training is mandatory'),\n\n /**\n * Target roles or groups for this training\n */\n targetRoles: z.array(z.string()).describe('Target roles or groups'),\n\n /**\n * Validity period in days before recertification is needed\n */\n validityDays: z.number().optional().describe('Certification validity period in days'),\n\n /**\n * Minimum passing score (percentage) for assessment\n */\n passingScore: z.number().min(0).max(100).optional()\n .describe('Minimum passing score percentage'),\n\n /**\n * Course version for tracking content updates\n */\n version: z.string().optional().describe('Course content version'),\n}).describe('Security training course definition');\n\n/**\n * Training Record Schema\n *\n * Individual employee training completion record.\n */\nexport const TrainingRecordSchema = z.object({\n /**\n * Reference to the course ID\n */\n courseId: z.string().describe('Training course identifier'),\n\n /**\n * User who completed (or is assigned) the training\n */\n userId: z.string().describe('User identifier'),\n\n /**\n * Completion status\n */\n status: TrainingCompletionStatusSchema.describe('Training completion status'),\n\n /**\n * Training assignment date (Unix milliseconds)\n */\n assignedAt: z.number().describe('Assignment timestamp'),\n\n /**\n * Training completion date (Unix milliseconds)\n */\n completedAt: z.number().optional().describe('Completion timestamp'),\n\n /**\n * Assessment score (percentage)\n */\n score: z.number().min(0).max(100).optional().describe('Assessment score percentage'),\n\n /**\n * Certification expiry date (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Certification expiry timestamp'),\n\n /**\n * Notes or comments from instructor or system\n */\n notes: z.string().optional().describe('Training notes or comments'),\n}).describe('Individual training completion record');\n\n/**\n * Training Plan Schema\n *\n * Organizational training plan defining schedule and requirements (A.6.3).\n */\nexport const TrainingPlanSchema = z.object({\n /**\n * Whether training management is enabled\n */\n enabled: z.boolean().default(true).describe('Enable training management'),\n\n /**\n * Training courses in the plan\n */\n courses: z.array(TrainingCourseSchema).describe('Training courses'),\n\n /**\n * Default recertification interval in days\n */\n recertificationIntervalDays: z.number().default(365)\n .describe('Default recertification interval in days'),\n\n /**\n * Whether to track training completion for compliance reporting\n */\n trackCompletion: z.boolean().default(true)\n .describe('Track training completion for compliance'),\n\n /**\n * Grace period in days after expiry before non-compliance escalation\n */\n gracePeriodDays: z.number().default(30)\n .describe('Grace period in days after certification expiry'),\n\n /**\n * Whether to send reminders for upcoming training deadlines\n */\n sendReminders: z.boolean().default(true)\n .describe('Send reminders for upcoming training deadlines'),\n\n /**\n * Days before deadline to send first reminder\n */\n reminderDaysBefore: z.number().default(14)\n .describe('Days before deadline to send first reminder'),\n}).describe('Organizational training plan per ISO 27001:2022 A.6.3');\n\n// Type exports\nexport type TrainingCategory = z.infer;\nexport type TrainingCompletionStatus = z.infer;\nexport type TrainingCourse = z.infer;\nexport type TrainingRecord = z.infer;\nexport type TrainingPlan = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Cron Schedule Schema\n * Schedule jobs using cron expressions\n */\nexport const CronScheduleSchema = z.object({\n type: z.literal('cron'),\n expression: z.string().describe('Cron expression (e.g., \"0 0 * * *\" for daily at midnight)'),\n timezone: z.string().optional().default('UTC').describe('Timezone for cron execution (e.g., \"America/New_York\")'),\n});\n\n/**\n * Interval Schedule Schema\n * Schedule jobs at fixed intervals\n */\nexport const IntervalScheduleSchema = z.object({\n type: z.literal('interval'),\n intervalMs: z.number().int().positive().describe('Interval in milliseconds'),\n});\n\n/**\n * Once Schedule Schema\n * Schedule a job to run once at a specific time\n */\nexport const OnceScheduleSchema = z.object({\n type: z.literal('once'),\n at: z.string().datetime().describe('ISO 8601 datetime when to execute'),\n});\n\n/**\n * Schedule Schema\n * Discriminated union of all schedule types\n */\nexport const ScheduleSchema = z.discriminatedUnion('type', [\n CronScheduleSchema,\n IntervalScheduleSchema,\n OnceScheduleSchema,\n]);\n\nexport type Schedule = z.infer;\nexport type CronSchedule = z.infer;\nexport type IntervalSchedule = z.infer;\nexport type OnceSchedule = z.infer;\nexport type JobSchedule = Schedule; // Alias for backwards compatibility\n\n/**\n * Retry Policy Schema\n * Configuration for job retry behavior with exponential backoff\n */\nexport const RetryPolicySchema = z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum number of retry attempts'),\n backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay in milliseconds'),\n backoffMultiplier: z.number().positive().default(2).describe('Multiplier for exponential backoff'),\n});\n\nexport type RetryPolicy = z.infer;\n\n/**\n * Job Schema\n * Defines a scheduled job that executes background logic.\n * \n * @example Metadata Sync Job (Cron)\n * {\n * id: \"job_sync_meta\",\n * name: \"sync_metadata_nightly\",\n * schedule: {\n * type: \"cron\",\n * expression: \"0 0 * * *\", // Midnight\n * timezone: \"UTC\"\n * },\n * handler: \"services/syncStatus.ts:syncAll\", \n * retryPolicy: {\n * maxRetries: 3,\n * backoffMs: 5000\n * }\n * }\n */\nexport const JobSchema = z.object({\n id: z.string().describe('Unique job identifier'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Job name (snake_case)'),\n schedule: ScheduleSchema.describe('Job schedule configuration'),\n handler: z.string().describe('Handler path (e.g. \"path/to/file:functionName\") or script ID'),\n retryPolicy: RetryPolicySchema.optional().describe('Retry policy configuration'),\n timeout: z.number().int().positive().optional().describe('Timeout in milliseconds'),\n enabled: z.boolean().default(true).describe('Whether the job is enabled'),\n});\n\nexport type Job = z.infer;\n\n/**\n * Job Execution Status Enum\n * Status of job execution\n */\nexport const JobExecutionStatus = z.enum([\n 'running',\n 'success',\n 'failed',\n 'timeout',\n]);\n\nexport type JobExecutionStatus = z.infer;\n\n/**\n * Job Execution Schema\n * Logs for job execution\n */\nexport const JobExecutionSchema = z.object({\n jobId: z.string().describe('Job identifier'),\n startedAt: z.string().datetime().describe('ISO 8601 datetime when execution started'),\n completedAt: z.string().datetime().optional().describe('ISO 8601 datetime when execution completed'),\n status: JobExecutionStatus.describe('Execution status'),\n error: z.string().optional().describe('Error message if failed'),\n duration: z.number().int().optional().describe('Execution duration in milliseconds'),\n});\n\nexport type JobExecution = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Worker System Protocol\n * \n * Background task processing system with queues, priorities, and retry logic.\n * Provides a robust foundation for async task execution similar to:\n * - Sidekiq (Ruby)\n * - Celery (Python)\n * - Bull/BullMQ (Node.js)\n * - AWS SQS/Lambda\n * \n * Features:\n * - Task queues with priorities\n * - Task scheduling and retry logic\n * - Batch processing\n * - Dead letter queues\n * - Task monitoring and logging\n * \n * @example Basic task\n * ```typescript\n * const task: Task = {\n * id: 'task-123',\n * type: 'send_email',\n * payload: { to: 'user@example.com', subject: 'Welcome' },\n * queue: 'notifications',\n * priority: 5\n * };\n * ```\n */\n\n// ==========================================\n// Task Priority\n// ==========================================\n\n/**\n * Task Priority Enum\n * Lower numbers = higher priority\n */\nexport const TaskPriority = z.enum([\n 'critical', // 0 - Must execute immediately\n 'high', // 1 - Execute soon\n 'normal', // 2 - Default priority\n 'low', // 3 - Execute when resources available\n 'background', // 4 - Execute during low-traffic periods\n]);\n\nexport type TaskPriority = z.infer;\n\n/**\n * Task Priority Mapping\n * Maps priority names to numeric values for sorting\n */\nexport const TASK_PRIORITY_VALUES: Record = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n background: 4,\n};\n\n// ==========================================\n// Task Status\n// ==========================================\n\n/**\n * Task Status Enum\n * Lifecycle states of a task\n */\nexport const TaskStatus = z.enum([\n 'pending', // Waiting to be processed\n 'queued', // In queue, ready for worker\n 'processing', // Currently being executed\n 'completed', // Successfully completed\n 'failed', // Failed (may retry)\n 'cancelled', // Manually cancelled\n 'timeout', // Exceeded execution timeout\n 'dead', // Moved to dead letter queue\n]);\n\nexport type TaskStatus = z.infer;\n\n// ==========================================\n// Task Schema\n// ==========================================\n\n/**\n * Task Retry Policy Schema\n * Configuration for task retry behavior\n */\nexport const TaskRetryPolicySchema = z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy between retries'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay in milliseconds'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay in milliseconds'),\n backoffMultiplier: z.number().positive().default(2).describe('Multiplier for exponential backoff'),\n});\n\nexport type TaskRetryPolicy = z.infer;\nexport type TaskRetryPolicyInput = z.input;\n\n/**\n * Task Schema\n * Represents a background task to be executed\n * \n * @example\n * {\n * \"id\": \"task-abc123\",\n * \"type\": \"send_email\",\n * \"payload\": { \"to\": \"user@example.com\", \"template\": \"welcome\" },\n * \"queue\": \"notifications\",\n * \"priority\": \"high\",\n * \"retryPolicy\": {\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * }\n * }\n */\nexport const TaskSchema = z.object({\n /**\n * Unique task identifier\n */\n id: z.string().describe('Unique task identifier'),\n \n /**\n * Task type (handler identifier)\n */\n type: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Task type (snake_case)'),\n \n /**\n * Task payload data\n */\n payload: z.unknown().describe('Task payload data'),\n \n /**\n * Queue name\n */\n queue: z.string().default('default').describe('Queue name'),\n \n /**\n * Task priority\n */\n priority: TaskPriority.default('normal').describe('Task priority level'),\n \n /**\n * Retry policy\n */\n retryPolicy: TaskRetryPolicySchema.optional().describe('Retry policy configuration'),\n \n /**\n * Execution timeout in milliseconds\n */\n timeoutMs: z.number().int().positive().optional().describe('Task timeout in milliseconds'),\n \n /**\n * Scheduled execution time\n */\n scheduledAt: z.string().datetime().optional().describe('ISO 8601 datetime to execute task'),\n \n /**\n * Maximum execution attempts\n */\n attempts: z.number().int().min(0).default(0).describe('Number of execution attempts'),\n \n /**\n * Task status\n */\n status: TaskStatus.default('pending').describe('Current task status'),\n \n /**\n * Task metadata\n */\n metadata: z.object({\n createdAt: z.string().datetime().optional().describe('When task was created'),\n updatedAt: z.string().datetime().optional().describe('Last update time'),\n createdBy: z.string().optional().describe('User who created task'),\n tags: z.array(z.string()).optional().describe('Task tags for filtering'),\n }).optional().describe('Task metadata'),\n});\n\nexport type Task = z.infer;\nexport type TaskInput = z.input;\n\n// ==========================================\n// Task Execution Result\n// ==========================================\n\n/**\n * Task Execution Result Schema\n * Result of a task execution attempt\n */\nexport const TaskExecutionResultSchema = z.object({\n /**\n * Task identifier\n */\n taskId: z.string().describe('Task identifier'),\n \n /**\n * Execution status\n */\n status: TaskStatus.describe('Execution status'),\n \n /**\n * Execution result data\n */\n result: z.unknown().optional().describe('Execution result data'),\n \n /**\n * Error information\n */\n error: z.object({\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Error stack trace'),\n code: z.string().optional().describe('Error code'),\n }).optional().describe('Error details if failed'),\n \n /**\n * Execution duration\n */\n durationMs: z.number().int().optional().describe('Execution duration in milliseconds'),\n \n /**\n * Execution timestamps\n */\n startedAt: z.string().datetime().describe('When execution started'),\n completedAt: z.string().datetime().optional().describe('When execution completed'),\n \n /**\n * Retry information\n */\n attempt: z.number().int().min(1).describe('Attempt number (1-indexed)'),\n willRetry: z.boolean().describe('Whether task will be retried'),\n});\n\nexport type TaskExecutionResult = z.infer;\n\n// ==========================================\n// Queue Configuration\n// ==========================================\n\n/**\n * Queue Configuration Schema\n * Configuration for a task queue\n * \n * @example\n * {\n * \"name\": \"notifications\",\n * \"concurrency\": 10,\n * \"rateLimit\": {\n * \"max\": 100,\n * \"duration\": 60000\n * }\n * }\n */\nexport const QueueConfigSchema = z.object({\n /**\n * Queue name\n */\n name: z.string().describe('Queue name (snake_case)'),\n \n /**\n * Maximum concurrent workers\n */\n concurrency: z.number().int().min(1).default(5).describe('Max concurrent task executions'),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n max: z.number().int().positive().describe('Maximum tasks per duration'),\n duration: z.number().int().positive().describe('Duration in milliseconds'),\n }).optional().describe('Rate limit configuration'),\n \n /**\n * Default retry policy\n */\n defaultRetryPolicy: TaskRetryPolicySchema.optional().describe('Default retry policy for tasks'),\n \n /**\n * Dead letter queue\n */\n deadLetterQueue: z.string().optional().describe('Dead letter queue name'),\n \n /**\n * Queue priority\n */\n priority: z.number().int().min(0).default(0).describe('Queue priority (lower = higher priority)'),\n \n /**\n * Auto-scaling configuration\n */\n autoScale: z.object({\n enabled: z.boolean().default(false).describe('Enable auto-scaling'),\n minWorkers: z.number().int().min(1).default(1).describe('Minimum workers'),\n maxWorkers: z.number().int().min(1).default(10).describe('Maximum workers'),\n scaleUpThreshold: z.number().int().positive().default(100).describe('Queue size to scale up'),\n scaleDownThreshold: z.number().int().min(0).default(10).describe('Queue size to scale down'),\n }).optional().describe('Auto-scaling configuration'),\n});\n\nexport type QueueConfig = z.infer;\nexport type QueueConfigInput = z.input;\n\n// ==========================================\n// Batch Processing\n// ==========================================\n\n/**\n * Batch Task Schema\n * Configuration for batch processing multiple items\n * \n * @example\n * {\n * \"id\": \"batch-import-123\",\n * \"type\": \"import_records\",\n * \"items\": [{ \"name\": \"Item 1\" }, { \"name\": \"Item 2\" }],\n * \"batchSize\": 100,\n * \"queue\": \"batch_processing\"\n * }\n */\nexport const BatchTaskSchema = z.object({\n /**\n * Batch job identifier\n */\n id: z.string().describe('Unique batch job identifier'),\n \n /**\n * Task type for processing each item\n */\n type: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Task type (snake_case)'),\n \n /**\n * Items to process\n */\n items: z.array(z.unknown()).describe('Array of items to process'),\n \n /**\n * Batch size (items per task)\n */\n batchSize: z.number().int().min(1).default(100).describe('Number of items per batch'),\n \n /**\n * Queue name\n */\n queue: z.string().default('batch').describe('Queue for batch tasks'),\n \n /**\n * Priority\n */\n priority: TaskPriority.default('normal').describe('Batch task priority'),\n \n /**\n * Parallel processing\n */\n parallel: z.boolean().default(true).describe('Process batches in parallel'),\n \n /**\n * Stop on error\n */\n stopOnError: z.boolean().default(false).describe('Stop batch if any item fails'),\n \n /**\n * Progress callback\n * \n * Called after each batch completes to report progress.\n * Invoked asynchronously and should not throw errors.\n * If the callback throws, the error is logged but batch processing continues.\n * \n * @param progress - Object containing processed count, total count, and failed count\n */\n onProgress: z.function()\n .input(z.tuple([z.object({\n processed: z.number(),\n total: z.number(),\n failed: z.number(),\n })]))\n .output(z.void())\n .optional()\n .describe('Progress callback function (called after each batch)'),\n});\n\nexport type BatchTask = z.infer;\nexport type BatchTaskInput = z.input;\n\n/**\n * Batch Progress Schema\n * Tracks progress of a batch job\n */\nexport const BatchProgressSchema = z.object({\n /**\n * Batch job identifier\n */\n batchId: z.string().describe('Batch job identifier'),\n \n /**\n * Total items\n */\n total: z.number().int().min(0).describe('Total number of items'),\n \n /**\n * Processed items\n */\n processed: z.number().int().min(0).default(0).describe('Items processed'),\n \n /**\n * Successful items\n */\n succeeded: z.number().int().min(0).default(0).describe('Items succeeded'),\n \n /**\n * Failed items\n */\n failed: z.number().int().min(0).default(0).describe('Items failed'),\n \n /**\n * Progress percentage\n */\n percentage: z.number().min(0).max(100).describe('Progress percentage'),\n \n /**\n * Status\n */\n status: z.enum(['pending', 'running', 'completed', 'failed', 'cancelled']).describe('Batch status'),\n \n /**\n * Timestamps\n */\n startedAt: z.string().datetime().optional().describe('When batch started'),\n completedAt: z.string().datetime().optional().describe('When batch completed'),\n});\n\nexport type BatchProgress = z.infer;\nexport type BatchProgressInput = z.input;\n\n// ==========================================\n// Worker Configuration\n// ==========================================\n\n/**\n * Worker Configuration Schema\n * Configuration for a worker instance\n */\nexport const WorkerConfigSchema = z.object({\n /**\n * Worker name\n */\n name: z.string().describe('Worker name'),\n \n /**\n * Queues to process\n */\n queues: z.array(z.string()).min(1).describe('Queue names to process'),\n \n /**\n * Queue configurations\n */\n queueConfigs: z.array(QueueConfigSchema).optional().describe('Queue configurations'),\n \n /**\n * Polling interval\n */\n pollIntervalMs: z.number().int().positive().default(1000).describe('Queue polling interval in milliseconds'),\n \n /**\n * Visibility timeout\n */\n visibilityTimeoutMs: z.number().int().positive().default(30000)\n .describe('How long a task is invisible after being claimed'),\n \n /**\n * Task timeout\n */\n defaultTimeoutMs: z.number().int().positive().default(300000).describe('Default task timeout in milliseconds'),\n \n /**\n * Graceful shutdown timeout\n */\n shutdownTimeoutMs: z.number().int().positive().default(30000)\n .describe('Graceful shutdown timeout in milliseconds'),\n \n /**\n * Task handlers\n */\n handlers: z.record(z.string(), z.function()).optional().describe('Task type handlers'),\n});\n\nexport type WorkerConfig = z.infer;\nexport type WorkerConfigInput = z.input;\n\n// ==========================================\n// Worker Stats\n// ==========================================\n\n/**\n * Worker Stats Schema\n * Runtime statistics for a worker\n */\nexport const WorkerStatsSchema = z.object({\n /**\n * Worker name\n */\n workerName: z.string().describe('Worker name'),\n \n /**\n * Total tasks processed\n */\n totalProcessed: z.number().int().min(0).describe('Total tasks processed'),\n \n /**\n * Successful tasks\n */\n succeeded: z.number().int().min(0).describe('Successful tasks'),\n \n /**\n * Failed tasks\n */\n failed: z.number().int().min(0).describe('Failed tasks'),\n \n /**\n * Active tasks\n */\n active: z.number().int().min(0).describe('Currently active tasks'),\n \n /**\n * Average execution time\n */\n avgExecutionMs: z.number().min(0).optional().describe('Average execution time in milliseconds'),\n \n /**\n * Uptime\n */\n uptimeMs: z.number().int().min(0).describe('Worker uptime in milliseconds'),\n \n /**\n * Queue stats\n */\n queues: z.record(z.string(), z.object({\n pending: z.number().int().min(0).describe('Pending tasks'),\n active: z.number().int().min(0).describe('Active tasks'),\n completed: z.number().int().min(0).describe('Completed tasks'),\n failed: z.number().int().min(0).describe('Failed tasks'),\n })).optional().describe('Per-queue statistics'),\n});\n\nexport type WorkerStats = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create a task\n */\nexport const Task = Object.assign(TaskSchema, {\n create: >(task: T) => task,\n});\n\n/**\n * Helper to create a queue config\n */\nexport const QueueConfig = Object.assign(QueueConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create a worker config\n */\nexport const WorkerConfig = Object.assign(WorkerConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create a batch task\n */\nexport const BatchTask = Object.assign(BatchTaskSchema, {\n create: >(batch: T) => batch,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Email Template Schema\n * \n * Defines the structure and content of email notifications.\n * Supports variables for personalization and file attachments.\n * \n * @example\n * ```json\n * {\n * \"id\": \"welcome-email\",\n * \"subject\": \"Welcome to {{company_name}}\",\n * \"body\": \"

Welcome {{user_name}}!

\",\n * \"bodyType\": \"html\",\n * \"variables\": [\"company_name\", \"user_name\"],\n * \"attachments\": [\n * {\n * \"name\": \"guide.pdf\",\n * \"url\": \"https://example.com/guide.pdf\"\n * }\n * ]\n * }\n * ```\n */\nexport const EmailTemplateSchema = z.object({\n /**\n * Unique identifier for the email template\n */\n id: z.string().describe('Template identifier'),\n\n /**\n * Email subject line (supports variable interpolation)\n */\n subject: z.string().describe('Email subject'),\n\n /**\n * Email body content\n */\n body: z.string().describe('Email body content'),\n\n /**\n * Content type of the email body\n * @default 'html'\n */\n bodyType: z.enum(['text', 'html', 'markdown']).optional().default('html').describe('Body content type'),\n\n /**\n * List of template variables for dynamic content\n */\n variables: z.array(z.string()).optional().describe('Template variables'),\n\n /**\n * File attachments to include with the email\n */\n attachments: z.array(z.object({\n name: z.string().describe('Attachment filename'),\n url: z.string().url().describe('Attachment URL'),\n })).optional().describe('Email attachments'),\n});\n\n/**\n * SMS Template Schema\n * \n * Defines the structure of SMS text message notifications.\n * Includes character limits and variable support.\n * \n * @example\n * ```json\n * {\n * \"id\": \"verification-sms\",\n * \"message\": \"Your code is {{code}}\",\n * \"maxLength\": 160,\n * \"variables\": [\"code\"]\n * }\n * ```\n */\nexport const SMSTemplateSchema = z.object({\n /**\n * Unique identifier for the SMS template\n */\n id: z.string().describe('Template identifier'),\n\n /**\n * SMS message content (supports variable interpolation)\n */\n message: z.string().describe('SMS message content'),\n\n /**\n * Maximum character length for the SMS\n * @default 160\n */\n maxLength: z.number().optional().default(160).describe('Maximum message length'),\n\n /**\n * List of template variables for dynamic content\n */\n variables: z.array(z.string()).optional().describe('Template variables'),\n});\n\n/**\n * Push Notification Schema\n * \n * Defines mobile and web push notification structure.\n * Supports rich notifications with actions and badges.\n * \n * @example\n * ```json\n * {\n * \"title\": \"New Message\",\n * \"body\": \"You have a new message from John\",\n * \"icon\": \"https://example.com/icon.png\",\n * \"badge\": 5,\n * \"data\": {\"messageId\": \"msg_123\"},\n * \"actions\": [\n * {\"action\": \"view\", \"title\": \"View\"},\n * {\"action\": \"dismiss\", \"title\": \"Dismiss\"}\n * ]\n * }\n * ```\n */\nexport const PushNotificationSchema = z.object({\n /**\n * Notification title\n */\n title: z.string().describe('Notification title'),\n\n /**\n * Notification body text\n */\n body: z.string().describe('Notification body'),\n\n /**\n * Icon URL to display with notification\n */\n icon: z.string().url().optional().describe('Notification icon URL'),\n\n /**\n * Badge count to display on app icon\n */\n badge: z.number().optional().describe('Badge count'),\n\n /**\n * Custom data payload\n */\n data: z.record(z.string(), z.unknown()).optional().describe('Custom data'),\n\n /**\n * Action buttons for the notification\n */\n actions: z.array(z.object({\n action: z.string().describe('Action identifier'),\n title: z.string().describe('Action button title'),\n })).optional().describe('Notification actions'),\n});\n\n/**\n * In-App Notification Schema\n * \n * Defines in-application notification banners and toasts.\n * Includes severity levels and auto-dismiss settings.\n * \n * @example\n * ```json\n * {\n * \"title\": \"System Update\",\n * \"message\": \"New features are now available\",\n * \"type\": \"info\",\n * \"actionUrl\": \"/updates\",\n * \"dismissible\": true,\n * \"expiresAt\": 1704067200000\n * }\n * ```\n */\nexport const InAppNotificationSchema = z.object({\n /**\n * Notification title\n */\n title: z.string().describe('Notification title'),\n\n /**\n * Notification message content\n */\n message: z.string().describe('Notification message'),\n\n /**\n * Notification severity type\n */\n type: z.enum(['info', 'success', 'warning', 'error']).describe('Notification type'),\n\n /**\n * Optional URL to navigate to when clicked\n */\n actionUrl: z.string().optional().describe('Action URL'),\n\n /**\n * Whether the notification can be dismissed by the user\n * @default true\n */\n dismissible: z.boolean().optional().default(true).describe('User dismissible'),\n\n /**\n * Timestamp when notification expires (Unix milliseconds)\n */\n expiresAt: z.number().optional().describe('Expiration timestamp'),\n});\n\n/**\n * Notification Channel Enum\n * \n * Supported notification delivery channels.\n */\nexport const NotificationChannelSchema = z.enum([\n 'email',\n 'sms',\n 'push',\n 'in-app',\n 'slack',\n 'teams',\n 'webhook',\n]);\n\n/**\n * Notification Configuration Schema\n * \n * Unified notification management protocol supporting multiple channels.\n * Includes scheduling, retry policies, and delivery tracking.\n * \n * @example\n * ```json\n * {\n * \"id\": \"welcome-notification\",\n * \"name\": \"Welcome Email\",\n * \"channel\": \"email\",\n * \"template\": {\n * \"id\": \"tpl-001\",\n * \"subject\": \"Welcome!\",\n * \"body\": \"

Welcome

\",\n * \"bodyType\": \"html\"\n * },\n * \"recipients\": {\n * \"to\": [\"user@example.com\"],\n * \"cc\": [\"admin@example.com\"]\n * },\n * \"schedule\": {\n * \"type\": \"immediate\"\n * },\n * \"retryPolicy\": {\n * \"enabled\": true,\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * },\n * \"tracking\": {\n * \"trackOpens\": true,\n * \"trackClicks\": true,\n * \"trackDelivery\": true\n * }\n * }\n * ```\n */\nexport const NotificationConfigSchema = z.object({\n /**\n * Unique identifier for this notification configuration\n */\n id: z.string().describe('Notification ID'),\n\n /**\n * Human-readable name for this notification\n */\n name: z.string().describe('Notification name'),\n\n /**\n * Delivery channel for the notification\n */\n channel: NotificationChannelSchema.describe('Notification channel'),\n\n /**\n * Notification template based on channel type\n */\n template: z.union([\n EmailTemplateSchema,\n SMSTemplateSchema,\n PushNotificationSchema,\n InAppNotificationSchema,\n ]).describe('Notification template'),\n\n /**\n * Recipient configuration\n */\n recipients: z.object({\n /**\n * Primary recipients\n */\n to: z.array(z.string()).describe('Primary recipients'),\n\n /**\n * CC recipients (email only)\n */\n cc: z.array(z.string()).optional().describe('CC recipients'),\n\n /**\n * BCC recipients (email only)\n */\n bcc: z.array(z.string()).optional().describe('BCC recipients'),\n }).describe('Recipients'),\n\n /**\n * Scheduling configuration\n */\n schedule: z.object({\n /**\n * Scheduling type\n */\n type: z.enum(['immediate', 'delayed', 'scheduled']).describe('Schedule type'),\n\n /**\n * Delay in milliseconds (for delayed type)\n */\n delay: z.number().optional().describe('Delay in milliseconds'),\n\n /**\n * Scheduled send time (Unix timestamp in milliseconds)\n */\n scheduledAt: z.number().optional().describe('Scheduled timestamp'),\n }).optional().describe('Scheduling'),\n\n /**\n * Retry policy for failed deliveries\n */\n retryPolicy: z.object({\n /**\n * Enable automatic retries\n * @default true\n */\n enabled: z.boolean().optional().default(true).describe('Enable retries'),\n\n /**\n * Maximum number of retry attempts\n * @default 3\n */\n maxRetries: z.number().optional().default(3).describe('Max retry attempts'),\n\n /**\n * Backoff strategy for retries\n */\n backoffStrategy: z.enum(['exponential', 'linear', 'fixed']).describe('Backoff strategy'),\n }).optional().describe('Retry policy'),\n\n /**\n * Delivery tracking configuration\n */\n tracking: z.object({\n /**\n * Track when emails are opened\n * @default false\n */\n trackOpens: z.boolean().optional().default(false).describe('Track opens'),\n\n /**\n * Track when links are clicked\n * @default false\n */\n trackClicks: z.boolean().optional().default(false).describe('Track clicks'),\n\n /**\n * Track delivery status\n * @default true\n */\n trackDelivery: z.boolean().optional().default(true).describe('Track delivery'),\n }).optional().describe('Tracking configuration'),\n});\n\n// Type exports\nexport type NotificationConfig = z.infer;\nexport type NotificationChannel = z.infer;\nexport type EmailTemplate = z.infer;\nexport type SMSTemplate = z.infer;\nexport type PushNotification = z.infer;\nexport type InAppNotification = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const LocaleSchema = z.string().describe('BCP-47 Language Tag (e.g. en-US, zh-CN)');\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-level Translation (per-object file)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Field Translation Schema\n * Translation data for a single field.\n */\nexport const FieldTranslationSchema = z.object({\n label: z.string().optional().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n placeholder: z.string().optional().describe('Translated placeholder text for form inputs'),\n options: z.record(z.string(), z.string()).optional().describe('Option value to translated label map'),\n}).describe('Translation data for a single field');\n\nexport type FieldTranslation = z.infer;\n\n/**\n * Object Translation Data Schema\n *\n * Translation data for a **single object** in a **single locale**.\n * Use this schema to validate per-object translation files.\n *\n * File convention: `i18n/{locale}/{object_name}.json`\n *\n * @example\n * ```json\n * // i18n/en/account.json\n * {\n * \"label\": \"Account\",\n * \"pluralLabel\": \"Accounts\",\n * \"fields\": {\n * \"name\": { \"label\": \"Account Name\", \"help\": \"Legal name\" },\n * \"type\": { \"label\": \"Type\", \"options\": { \"customer\": \"Customer\" } }\n * }\n * }\n * ```\n */\nexport const ObjectTranslationDataSchema = z.object({\n /** Translated singular label for the object */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label for the object */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional().describe('Field-level translations'),\n}).describe('Translation data for a single object');\n\nexport type ObjectTranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Locale-level Translation Data (per-locale aggregate)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Data Schema\n * Supports i18n for labels, messages, and options within a single locale.\n * Example structure:\n * ```json\n * {\n * \"objects\": { \"account\": { \"label\": \"Account\" } },\n * \"apps\": { \"crm\": { \"label\": \"CRM\" } },\n * \"messages\": { \"common.save\": \"Save\" }\n * }\n * ```\n */\nexport const TranslationDataSchema = z.object({\n /** Object translations */\n objects: z.record(z.string(), ObjectTranslationDataSchema).optional().describe('Object translations keyed by object name'),\n \n /** App/Menu translations */\n apps: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** UI Messages */\n messages: z.record(z.string(), z.string()).optional().describe('UI message translations keyed by message ID'),\n \n /** Validation Error Messages */\n validationMessages: z.record(z.string(), z.string()).optional().describe('Translatable validation error messages keyed by rule name (e.g., {\"discount_limit\": \"折扣不能超过40%\"})'),\n}).describe('Translation data for objects, apps, and UI messages');\n\nexport type TranslationData = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Bundle (all locales)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport const TranslationBundleSchema = z.record(LocaleSchema, TranslationDataSchema).describe('Map of locale codes to translation data');\n\nexport type TranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// File Organization Convention\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation File Organization Strategy\n *\n * Defines how translation files are organized on disk.\n *\n * - `bundled` — All locales in a single `TranslationBundle` file.\n * Best for small projects with few objects.\n * ```\n * src/translations/\n * crm.translation.ts # { en: {...}, \"zh-CN\": {...} }\n * ```\n *\n * - `per_locale` — One file per locale containing all namespaces.\n * Recommended when a single locale file stays under ~500 lines.\n * ```\n * src/translations/\n * en.ts # TranslationData for English\n * zh-CN.ts # TranslationData for Chinese\n * ```\n *\n * - `per_namespace` — One file per namespace (object) per locale.\n * Recommended for large projects with many objects/languages.\n * Aligns with Salesforce DX and ServiceNow conventions.\n * ```\n * i18n/\n * en/\n * account.json # ObjectTranslationData\n * contact.json\n * common.json # messages + app labels\n * zh-CN/\n * account.json\n * contact.json\n * common.json\n * ```\n */\nexport const TranslationFileOrganizationSchema = z.enum([\n 'bundled',\n 'per_locale',\n 'per_namespace',\n]).describe('Translation file organization strategy');\n\nexport type TranslationFileOrganization = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Configuration\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Configuration Schema\n *\n * Defines internationalization settings for the stack.\n *\n * @example\n * ```typescript\n * export default defineStack({\n * i18n: {\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'zh-CN', 'ja-JP'],\n * fallbackLocale: 'en',\n * fileOrganization: 'per_locale',\n * },\n * translations: [...],\n * });\n * ```\n */\n/**\n * Message format standard used for interpolation, pluralization, and\n * gender-aware translations.\n *\n * - `icu` — ICU MessageFormat (recommended for complex plurals, gender, select).\n * Strings may contain `{count, plural, one {# item} other {# items}}` patterns.\n * - `simple` — Simple `{variable}` interpolation only (default).\n */\nexport const MessageFormatSchema = z.enum([\n 'icu',\n 'simple',\n]).describe('Message interpolation format: ICU MessageFormat or simple {variable} replacement');\n\nexport type MessageFormat = z.infer;\n\nexport const TranslationConfigSchema = z.object({\n /** Default locale for the application */\n defaultLocale: LocaleSchema.describe('Default locale (e.g., \"en\")'),\n /** Supported BCP-47 locale codes */\n supportedLocales: z.array(LocaleSchema).describe('Supported BCP-47 locale codes'),\n /** Fallback locale when translation is not found */\n fallbackLocale: LocaleSchema.optional().describe('Fallback locale code'),\n /** How translation files are organized on disk */\n fileOrganization: TranslationFileOrganizationSchema.default('per_locale')\n .describe('File organization strategy'),\n /**\n * Message interpolation format.\n * When set to `'icu'`, messages and validationMessages are expected to use\n * ICU MessageFormat syntax (plurals, select, number/date skeletons).\n * @default 'simple'\n */\n messageFormat: MessageFormatSchema.default('simple')\n .describe('Message interpolation format (ICU MessageFormat or simple)'),\n /** Load translations on demand instead of eagerly */\n lazyLoad: z.boolean().default(false).describe('Load translations on demand'),\n /** Cache loaded translations in memory */\n cache: z.boolean().default(true).describe('Cache loaded translations'),\n}).describe('Internationalization configuration');\n\nexport type TranslationConfig = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Object-First Translation Node (object-first aggregated structure)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Translatable option map: option value → translated label */\nconst OptionTranslationMapSchema = z.record(z.string(), z.string())\n .describe('Option value to translated label map');\n\n/**\n * ObjectTranslationNodeSchema\n *\n * Object-first aggregated translation node that groups **all** translatable\n * content for a single object under one key. Aligns with Salesforce / Dynamics\n * conventions where translations are organized per-object rather than per-category.\n *\n * Located at `o.{object_name}` inside an {@link AppTranslationBundle}.\n *\n * @example\n * ```typescript\n * const accountNode: ObjectTranslationNode = {\n * label: '客户',\n * pluralLabel: '客户',\n * description: '客户管理对象',\n * fields: {\n * name: { label: '客户名称', help: '公司或组织的法定名称' },\n * industry: { label: '行业', options: { tech: '科技', finance: '金融' } },\n * },\n * _options: { status: { active: '活跃', inactive: '停用' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: {\n * convert_lead: { label: '转换线索', confirmMessage: '确认转换?' },\n * },\n * };\n * ```\n */\nexport const ObjectTranslationNodeSchema = z.object({\n /** Translated singular label */\n label: z.string().describe('Translated singular label'),\n /** Translated plural label */\n pluralLabel: z.string().optional().describe('Translated plural label'),\n /** Translated object description */\n description: z.string().optional().describe('Translated object description'),\n /** Translated help text shown in tooltips or guidance panels */\n helpText: z.string().optional().describe('Translated help text for the object'),\n\n /** Field-level translations keyed by field name (snake_case) */\n fields: z.record(z.string(), FieldTranslationSchema).optional()\n .describe('Field translations keyed by field name'),\n\n /**\n * Global picklist / select option overrides scoped to this object.\n * Keyed by field name → { optionValue: translatedLabel }.\n */\n _options: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Object-scoped picklist option translations keyed by field name'),\n\n /** View translations keyed by view name */\n _views: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated view label'),\n description: z.string().optional().describe('Translated view description'),\n })).optional().describe('View translations keyed by view name'),\n\n /** Section (form section / tab) translations keyed by section name */\n _sections: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated section label'),\n })).optional().describe('Section translations keyed by section name'),\n\n /** Action translations keyed by action name */\n _actions: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated action label'),\n confirmMessage: z.string().optional().describe('Translated confirmation message'),\n })).optional().describe('Action translations keyed by action name'),\n\n /** Notification message translations keyed by notification name */\n _notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Notification translations keyed by notification name'),\n\n /** Error message translations keyed by error code */\n _errors: z.record(z.string(), z.string()).optional()\n .describe('Error message translations keyed by error code'),\n}).describe('Object-first aggregated translation node');\n\nexport type ObjectTranslationNode = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// App Translation Bundle (object-first, full application)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * AppTranslationBundleSchema\n *\n * Complete application translation bundle for a **single locale** using\n * the **object-first** convention. All per-object translatable content\n * is aggregated under `o.{object_name}`, while global (non-object-bound)\n * translations are kept in dedicated top-level groups.\n *\n * This schema is designed for:\n * - Translation workbench UIs (object-level editing & coverage)\n * - CLI skeleton generation (`objectstack i18n extract`)\n * - Automated diff/coverage detection\n *\n * @example\n * ```typescript\n * const zh: AppTranslationBundle = {\n * o: {\n * account: {\n * label: '客户',\n * fields: { name: { label: '客户名称' } },\n * _options: { industry: { tech: '科技' } },\n * _views: { all_accounts: { label: '全部客户' } },\n * _sections: { basic_info: { label: '基本信息' } },\n * _actions: { convert: { label: '转换' } },\n * },\n * },\n * _globalOptions: { currency: { usd: '美元', eur: '欧元' } },\n * app: { crm: { label: '客户关系管理', description: '管理销售流程' } },\n * nav: { home: '首页', settings: '设置' },\n * dashboard: { sales_overview: { label: '销售概览' } },\n * reports: { pipeline_report: { label: '管道报表' } },\n * pages: { landing: { title: '欢迎' } },\n * messages: { 'common.save': '保存' },\n * validationMessages: { 'discount_limit': '折扣不能超过40%' },\n * };\n * ```\n */\nexport const AppTranslationBundleSchema = z.object({\n /**\n * Bundle-level metadata.\n * Provides locale-aware rendering hints such as text direction (bidi)\n * and the canonical locale code this bundle represents.\n */\n _meta: z.object({\n /** BCP-47 locale code this bundle represents */\n locale: z.string().optional().describe('BCP-47 locale code for this bundle'),\n /** Text direction for the locale */\n direction: z.enum(['ltr', 'rtl']).optional().describe('Text direction: left-to-right or right-to-left'),\n }).optional().describe('Bundle-level metadata (locale, bidi direction)'),\n\n /**\n * Namespace for plugin/extension isolation.\n * When multiple plugins contribute translations, each should use a unique\n * namespace to avoid key collisions (e.g. \"crm\", \"helpdesk\", \"plugin-xyz\").\n */\n namespace: z.string().optional()\n .describe('Namespace for plugin isolation to avoid translation key collisions'),\n\n /** Object-first translations keyed by object name (snake_case) */\n o: z.record(z.string(), ObjectTranslationNodeSchema).optional()\n .describe('Object-first translations keyed by object name'),\n\n /** Global picklist options not bound to any specific object */\n _globalOptions: z.record(z.string(), OptionTranslationMapSchema).optional()\n .describe('Global picklist option translations keyed by option set name'),\n\n /** App-level translations */\n app: z.record(z.string(), z.object({\n label: z.string().describe('Translated app label'),\n description: z.string().optional().describe('Translated app description'),\n })).optional().describe('App translations keyed by app name'),\n\n /** Navigation menu translations */\n nav: z.record(z.string(), z.string()).optional()\n .describe('Navigation item translations keyed by nav item name'),\n\n /** Dashboard translations keyed by dashboard name */\n dashboard: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated dashboard label'),\n description: z.string().optional().describe('Translated dashboard description'),\n })).optional().describe('Dashboard translations keyed by dashboard name'),\n\n /** Report translations keyed by report name */\n reports: z.record(z.string(), z.object({\n label: z.string().optional().describe('Translated report label'),\n description: z.string().optional().describe('Translated report description'),\n })).optional().describe('Report translations keyed by report name'),\n\n /** Page translations keyed by page name */\n pages: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated page title'),\n description: z.string().optional().describe('Translated page description'),\n })).optional().describe('Page translations keyed by page name'),\n\n /** UI message translations (supports ICU MessageFormat when enabled) */\n messages: z.record(z.string(), z.string()).optional()\n .describe('UI message translations keyed by message ID (supports ICU MessageFormat)'),\n\n /** Validation error message translations (supports ICU MessageFormat when enabled) */\n validationMessages: z.record(z.string(), z.string()).optional()\n .describe('Validation error message translations keyed by rule name (supports ICU MessageFormat)'),\n\n /** Global notification translations not bound to a specific object */\n notifications: z.record(z.string(), z.object({\n title: z.string().optional().describe('Translated notification title'),\n body: z.string().optional().describe('Translated notification body (supports ICU MessageFormat when enabled)'),\n })).optional().describe('Global notification translations keyed by notification name'),\n\n /** Global error message translations not bound to a specific object */\n errors: z.record(z.string(), z.string()).optional()\n .describe('Global error message translations keyed by error code'),\n}).describe('Object-first application translation bundle for a single locale');\n\nexport type AppTranslationBundle = z.infer;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Translation Diff & Coverage\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Translation Diff Status\n *\n * Status of a single translation entry compared to the source metadata.\n */\nexport const TranslationDiffStatusSchema = z.enum([\n 'missing',\n 'redundant',\n 'stale',\n]).describe('Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)');\n\nexport type TranslationDiffStatus = z.infer;\n\n/**\n * TranslationDiffItemSchema\n *\n * Describes a single translation key that is missing, redundant, or stale\n * relative to the source metadata. Used by CLI/API diff detection.\n *\n * @example\n * ```typescript\n * const item: TranslationDiffItem = {\n * key: 'o.account.fields.website.label',\n * status: 'missing',\n * objectName: 'account',\n * locale: 'zh-CN',\n * };\n * ```\n */\nexport const TranslationDiffItemSchema = z.object({\n /** Dot-path translation key (e.g. \"o.account.fields.website.label\") */\n key: z.string().describe('Dot-path translation key'),\n /** Diff status */\n status: TranslationDiffStatusSchema.describe('Diff status of this translation key'),\n /** Object name if the key belongs to an object translation node */\n objectName: z.string().optional().describe('Associated object name (snake_case)'),\n /** Locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /**\n * Hash of the source metadata value at the time the translation was made.\n * Used by CLI/Workbench to detect stale translations without a full diff.\n */\n sourceHash: z.string().optional().describe('Hash of source metadata for precise stale detection'),\n /**\n * AI-suggested translation text for missing or stale entries.\n * Populated by AI translation hooks or TMS integrations.\n */\n aiSuggested: z.string().optional().describe('AI-suggested translation for this key'),\n /** Confidence score (0-1) for the AI suggestion */\n aiConfidence: z.number().min(0).max(1).optional().describe('AI suggestion confidence score (0–1)'),\n}).describe('A single translation diff item');\n\nexport type TranslationDiffItem = z.infer;\n\n/**\n * TranslationCoverageResultSchema\n *\n * Aggregated coverage result for a locale, optionally scoped to a single object.\n * Returned by the i18n diff detection API.\n *\n * @example\n * ```typescript\n * const result: TranslationCoverageResult = {\n * locale: 'zh-CN',\n * totalKeys: 120,\n * translatedKeys: 105,\n * missingKeys: 12,\n * redundantKeys: 3,\n * staleKeys: 0,\n * coveragePercent: 87.5,\n * items: [ ... ],\n * };\n * ```\n */\n/**\n * Per-group coverage breakdown entry.\n */\nexport const CoverageBreakdownEntrySchema = z.object({\n /** Group category (e.g. \"fields\", \"views\", \"actions\", \"messages\") */\n group: z.string().describe('Translation group category'),\n /** Total translatable keys in this group */\n totalKeys: z.number().int().nonnegative().describe('Total keys in this group'),\n /** Number of translated keys in this group */\n translatedKeys: z.number().int().nonnegative().describe('Translated keys in this group'),\n /** Coverage percentage for this group */\n coveragePercent: z.number().min(0).max(100).describe('Coverage percentage for this group'),\n}).describe('Coverage breakdown for a single translation group');\n\nexport type CoverageBreakdownEntry = z.infer;\n\nexport const TranslationCoverageResultSchema = z.object({\n /** BCP-47 locale code */\n locale: z.string().describe('BCP-47 locale code'),\n /** Optional object name scope */\n objectName: z.string().optional().describe('Object name scope (omit for full bundle)'),\n /** Total translatable keys derived from metadata */\n totalKeys: z.number().int().nonnegative().describe('Total translatable keys from metadata'),\n /** Number of keys that have a translation */\n translatedKeys: z.number().int().nonnegative().describe('Number of translated keys'),\n /** Number of missing translations */\n missingKeys: z.number().int().nonnegative().describe('Number of missing translations'),\n /** Number of redundant (orphaned) translations */\n redundantKeys: z.number().int().nonnegative().describe('Number of redundant translations'),\n /** Number of stale translations */\n staleKeys: z.number().int().nonnegative().describe('Number of stale translations'),\n /** Coverage percentage (0-100) */\n coveragePercent: z.number().min(0).max(100).describe('Translation coverage percentage'),\n /** Individual diff items */\n items: z.array(TranslationDiffItemSchema).describe('Detailed diff items'),\n /**\n * Per-group coverage breakdown for translation project management.\n * Each entry represents a logical group (e.g. \"fields\", \"views\", \"actions\",\n * \"messages\") with its own coverage statistics.\n */\n breakdown: z.array(CoverageBreakdownEntrySchema).optional()\n .describe('Per-group coverage breakdown'),\n}).describe('Aggregated translation coverage result');\n\nexport type TranslationCoverageResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Translation Skeleton Protocol Constants\n *\n * Defines the placeholder convention used in AI-friendly translation\n * skeleton templates. Runtime implementations (skeleton generation,\n * validation) belong in implementation packages (CLI, service-i18n, etc.).\n *\n * @example\n * ```json\n * {\n * \"label\": \"__TRANSLATE__: \\\"Task\\\"\",\n * \"fields\": {\n * \"subject\": { \"label\": \"__TRANSLATE__: \\\"Subject\\\"\" }\n * }\n * }\n * ```\n */\n\n/** Placeholder prefix used in translation skeleton output */\nexport const TRANSLATE_PLACEHOLDER = '__TRANSLATE__';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Real-Time Collaboration Protocol\n * \n * Defines schemas for real-time collaborative editing in ObjectStack.\n * Supports Operational Transformation (OT), CRDT (Conflict-free Replicated Data Types),\n * cursor sharing, and awareness state for collaborative applications.\n * \n * Industry alignment: Google Docs, Figma, VSCode Live Share, Yjs\n */\n\n// ==========================================\n// Operational Transformation (OT)\n// ==========================================\n\n/**\n * OT Operation Type Enum\n * Types of operations in Operational Transformation\n */\nexport const OTOperationType = z.enum([\n 'insert', // Insert characters at position\n 'delete', // Delete characters at position\n 'retain', // Keep characters (used for composing operations)\n]);\n\nexport type OTOperationType = z.infer;\n\n/**\n * OT Operation Component\n * Single component of an OT operation\n */\nexport const OTComponentSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('insert'),\n text: z.string().describe('Text to insert'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Text formatting attributes (e.g., bold, italic)'),\n }),\n z.object({\n type: z.literal('delete'),\n count: z.number().int().positive().describe('Number of characters to delete'),\n }),\n z.object({\n type: z.literal('retain'),\n count: z.number().int().positive().describe('Number of characters to retain'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Attribute changes to apply'),\n }),\n]);\n\nexport type OTComponent = z.infer;\n\n/**\n * OT Operation Schema\n * Represents a complete OT operation\n * Based on the OT algorithm used by Google Docs and other collaborative editors\n */\nexport const OTOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n documentId: z.string().describe('Document identifier'),\n userId: z.string().describe('User who created the operation'),\n sessionId: z.string().uuid().describe('Session identifier'),\n components: z.array(OTComponentSchema).describe('Operation components'),\n baseVersion: z.number().int().nonnegative().describe('Document version this operation is based on'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional operation metadata'),\n});\n\nexport type OTOperation = z.infer;\n\n/**\n * OT Transform Result\n * Result of transforming one operation against another\n */\nexport const OTTransformResultSchema = z.object({\n operation: OTOperationSchema.describe('Transformed operation'),\n transformed: z.boolean().describe('Whether transformation was applied'),\n conflicts: z.array(z.string()).optional().describe('Conflict descriptions if any'),\n});\n\nexport type OTTransformResult = z.infer;\n\n// ==========================================\n// CRDT (Conflict-free Replicated Data Types)\n// ==========================================\n\n/**\n * CRDT Type Enum\n * Types of CRDTs supported\n */\nexport const CRDTType = z.enum([\n 'lww-register', // Last-Write-Wins Register\n 'g-counter', // Grow-only Counter\n 'pn-counter', // Positive-Negative Counter\n 'g-set', // Grow-only Set\n 'or-set', // Observed-Remove Set\n 'lww-map', // Last-Write-Wins Map\n 'text', // CRDT-based Text (e.g., Yjs, Automerge)\n 'tree', // CRDT-based Tree structure\n 'json', // CRDT-based JSON (e.g., Automerge)\n]);\n\nexport type CRDTType = z.infer;\n\n/**\n * Vector Clock Schema\n * Tracks causality in distributed systems\n */\nexport const VectorClockSchema = z.object({\n clock: z.record(z.string(), z.number().int().nonnegative()).describe('Map of replica ID to logical timestamp'),\n});\n\nexport type VectorClock = z.infer;\n\n/**\n * LWW-Register Schema\n * Last-Write-Wins Register CRDT\n */\nexport const LWWRegisterSchema = z.object({\n type: z.literal('lww-register'),\n value: z.unknown().describe('Current register value'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of last write'),\n replicaId: z.string().describe('ID of replica that performed last write'),\n vectorClock: VectorClockSchema.optional().describe('Optional vector clock for causality tracking'),\n});\n\nexport type LWWRegister = z.infer;\n\n/**\n * Counter Operation Schema\n * Operations for Counter CRDTs\n */\nexport const CounterOperationSchema = z.object({\n replicaId: z.string().describe('Replica identifier'),\n delta: z.number().int().describe('Change amount (positive for increment, negative for decrement)'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of operation'),\n});\n\nexport type CounterOperation = z.infer;\n\n/**\n * G-Counter Schema\n * Grow-only Counter CRDT\n */\nexport const GCounterSchema = z.object({\n type: z.literal('g-counter'),\n counts: z.record(z.string(), z.number().int().nonnegative()).describe('Map of replica ID to count'),\n});\n\nexport type GCounter = z.infer;\n\n/**\n * PN-Counter Schema\n * Positive-Negative Counter CRDT (supports increment and decrement)\n */\nexport const PNCounterSchema = z.object({\n type: z.literal('pn-counter'),\n positive: z.record(z.string(), z.number().int().nonnegative()).describe('Positive increments per replica'),\n negative: z.record(z.string(), z.number().int().nonnegative()).describe('Negative increments per replica'),\n});\n\nexport type PNCounter = z.infer;\n\n/**\n * OR-Set Element Schema\n * Element in an Observed-Remove Set\n */\nexport const ORSetElementSchema = z.object({\n value: z.unknown().describe('Element value'),\n timestamp: z.string().datetime().describe('Addition timestamp'),\n replicaId: z.string().describe('Replica that added the element'),\n uid: z.string().uuid().describe('Unique identifier for this addition'),\n removed: z.boolean().optional().default(false).describe('Whether element has been removed'),\n});\n\nexport type ORSetElement = z.infer;\n\n/**\n * OR-Set Schema\n * Observed-Remove Set CRDT\n */\nexport const ORSetSchema = z.object({\n type: z.literal('or-set'),\n elements: z.array(ORSetElementSchema).describe('Set elements with metadata'),\n});\n\nexport type ORSet = z.infer;\n\n/**\n * Text CRDT Operation Schema\n * Operations for text-based CRDTs (e.g., Yjs, Automerge)\n */\nexport const TextCRDTOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n replicaId: z.string().describe('Replica identifier'),\n position: z.number().int().nonnegative().describe('Position in document'),\n insert: z.string().optional().describe('Text to insert'),\n delete: z.number().int().positive().optional().describe('Number of characters to delete'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of operation'),\n lamportTimestamp: z.number().int().nonnegative().describe('Lamport timestamp for ordering'),\n});\n\nexport type TextCRDTOperation = z.infer;\n\n/**\n * Text CRDT State Schema\n * State of a text-based CRDT document\n */\nexport const TextCRDTStateSchema = z.object({\n type: z.literal('text'),\n documentId: z.string().describe('Document identifier'),\n content: z.string().describe('Current text content'),\n operations: z.array(TextCRDTOperationSchema).describe('History of operations'),\n lamportClock: z.number().int().nonnegative().describe('Current Lamport clock value'),\n vectorClock: VectorClockSchema.describe('Vector clock for causality'),\n});\n\nexport type TextCRDTState = z.infer;\n\n/**\n * CRDT State Union\n * Discriminated union of all CRDT types\n */\nexport const CRDTStateSchema = z.discriminatedUnion('type', [\n LWWRegisterSchema,\n GCounterSchema,\n PNCounterSchema,\n ORSetSchema,\n TextCRDTStateSchema,\n]);\n\nexport type CRDTState = z.infer;\n\n/**\n * CRDT Merge Schema\n * Result of merging two CRDT states\n */\nexport const CRDTMergeResultSchema = z.object({\n state: CRDTStateSchema.describe('Merged CRDT state'),\n conflicts: z.array(z.object({\n type: z.string().describe('Conflict type'),\n description: z.string().describe('Conflict description'),\n resolved: z.boolean().describe('Whether conflict was automatically resolved'),\n })).optional().describe('Conflicts encountered during merge'),\n});\n\nexport type CRDTMergeResult = z.infer;\n\n// ==========================================\n// Cursor Sharing\n// ==========================================\n\n/**\n * Cursor Color Preset Enum\n * Standard color presets for cursor visualization\n */\nexport const CursorColorPreset = z.enum([\n 'blue',\n 'green',\n 'red',\n 'yellow',\n 'purple',\n 'orange',\n 'pink',\n 'teal',\n 'indigo',\n 'cyan',\n]);\n\nexport type CursorColorPreset = z.infer;\n\n/**\n * Cursor Style Schema\n * Visual styling for collaborative cursors\n */\nexport const CursorStyleSchema = z.object({\n color: z.union([CursorColorPreset, z.string()]).describe('Cursor color (preset or custom hex)'),\n opacity: z.number().min(0).max(1).optional().default(1).describe('Cursor opacity (0-1)'),\n label: z.string().optional().describe('Label to display with cursor (usually username)'),\n showLabel: z.boolean().optional().default(true).describe('Whether to show label'),\n pulseOnUpdate: z.boolean().optional().default(true).describe('Whether to pulse when cursor moves'),\n});\n\nexport type CursorStyle = z.infer;\n\n/**\n * Cursor Selection Schema\n * Represents a text selection in collaborative editing\n */\nexport const CursorSelectionSchema = z.object({\n anchor: z.object({\n line: z.number().int().nonnegative().describe('Anchor line number'),\n column: z.number().int().nonnegative().describe('Anchor column number'),\n }).describe('Selection anchor (start point)'),\n focus: z.object({\n line: z.number().int().nonnegative().describe('Focus line number'),\n column: z.number().int().nonnegative().describe('Focus column number'),\n }).describe('Selection focus (end point)'),\n direction: z.enum(['forward', 'backward']).optional().describe('Selection direction'),\n});\n\nexport type CursorSelection = z.infer;\n\n/**\n * Collaborative Cursor Schema\n * Complete cursor state for a collaborative user\n */\nexport const CollaborativeCursorSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier'),\n userName: z.string().describe('Display name of user'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Cursor line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Cursor column number (0-indexed)'),\n }).describe('Current cursor position'),\n selection: CursorSelectionSchema.optional().describe('Current text selection'),\n style: CursorStyleSchema.describe('Visual style for this cursor'),\n isTyping: z.boolean().optional().default(false).describe('Whether user is currently typing'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional cursor metadata'),\n});\n\nexport type CollaborativeCursor = z.infer;\n\n/**\n * Cursor Update Schema\n * Update to a collaborative cursor\n */\nexport const CursorUpdateSchema = z.object({\n position: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }).optional().describe('Updated cursor position'),\n selection: CursorSelectionSchema.optional().describe('Updated selection'),\n isTyping: z.boolean().optional().describe('Updated typing state'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type CursorUpdate = z.infer;\n\n// ==========================================\n// Awareness State\n// ==========================================\n\n/**\n * User Activity Status Enum\n * User activity status for awareness\n */\nexport const UserActivityStatus = z.enum([\n 'active', // User is actively editing\n 'idle', // User is idle but connected\n 'viewing', // User is viewing but not editing\n 'disconnected', // User is disconnected\n]);\n\nexport type UserActivityStatus = z.infer;\n\n/**\n * Awareness User State Schema\n * Tracks what a user is doing in the collaborative session\n */\nexport const AwarenessUserStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n userName: z.string().describe('Display name'),\n userAvatar: z.string().optional().describe('User avatar URL'),\n status: UserActivityStatus.describe('Current activity status'),\n currentDocument: z.string().optional().describe('Document ID user is currently editing'),\n currentView: z.string().optional().describe('Current view/page user is on'),\n lastActivity: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n joinedAt: z.string().datetime().describe('ISO 8601 datetime when user joined session'),\n permissions: z.array(z.string()).optional().describe('User permissions in this session'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional user state metadata'),\n});\n\nexport type AwarenessUserState = z.infer;\n\n/**\n * Awareness Session Schema\n * Represents the complete awareness state for a collaboration session\n */\nexport const AwarenessSessionSchema = z.object({\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().optional().describe('Document ID this session is for'),\n users: z.array(AwarenessUserStateSchema).describe('Active users in session'),\n startedAt: z.string().datetime().describe('ISO 8601 datetime when session started'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last update'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Session metadata'),\n});\n\nexport type AwarenessSession = z.infer;\n\n/**\n * Awareness Update Schema\n * Update to awareness state\n */\nexport const AwarenessUpdateSchema = z.object({\n status: UserActivityStatus.optional().describe('Updated status'),\n currentDocument: z.string().optional().describe('Updated current document'),\n currentView: z.string().optional().describe('Updated current view'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type AwarenessUpdate = z.infer;\n\n/**\n * Awareness Event Schema\n * Events that occur in awareness tracking\n */\nexport const AwarenessEventSchema = z.object({\n eventId: z.string().uuid().describe('Event identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n eventType: z.enum([\n 'user.joined',\n 'user.left',\n 'user.updated',\n 'session.created',\n 'session.ended',\n ]).describe('Type of awareness event'),\n userId: z.string().optional().describe('User involved in event'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime of event'),\n payload: z.unknown().describe('Event payload'),\n});\n\nexport type AwarenessEvent = z.infer;\n\n// ==========================================\n// Collaboration Session Management\n// ==========================================\n\n/**\n * Collaboration Mode Enum\n * Types of collaboration modes\n */\nexport const CollaborationMode = z.enum([\n 'ot', // Operational Transformation\n 'crdt', // CRDT-based\n 'lock', // Pessimistic locking (turn-based)\n 'hybrid', // Hybrid approach\n]);\n\nexport type CollaborationMode = z.infer;\n\n/**\n * Collaboration Session Config\n * Configuration for a collaboration session\n */\nexport const CollaborationSessionConfigSchema = z.object({\n mode: CollaborationMode.describe('Collaboration mode to use'),\n enableCursorSharing: z.boolean().optional().default(true).describe('Enable cursor sharing'),\n enablePresence: z.boolean().optional().default(true).describe('Enable presence tracking'),\n enableAwareness: z.boolean().optional().default(true).describe('Enable awareness state'),\n maxUsers: z.number().int().positive().optional().describe('Maximum concurrent users'),\n idleTimeout: z.number().int().positive().optional().default(300000).describe('Idle timeout in milliseconds'),\n conflictResolution: z.enum(['ot', 'crdt', 'manual']).optional().default('ot').describe('Conflict resolution strategy'),\n persistence: z.boolean().optional().default(true).describe('Enable operation persistence'),\n snapshot: z.object({\n enabled: z.boolean().describe('Enable periodic snapshots'),\n interval: z.number().int().positive().describe('Snapshot interval in milliseconds'),\n }).optional().describe('Snapshot configuration'),\n});\n\nexport type CollaborationSessionConfig = z.infer;\n\n/**\n * Collaboration Session Schema\n * Complete collaboration session state\n */\nexport const CollaborationSessionSchema = z.object({\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier'),\n config: CollaborationSessionConfigSchema.describe('Session configuration'),\n users: z.array(AwarenessUserStateSchema).describe('Active users'),\n cursors: z.array(CollaborativeCursorSchema).describe('Active cursors'),\n version: z.number().int().nonnegative().describe('Current document version'),\n operations: z.array(z.union([OTOperationSchema, TextCRDTOperationSchema])).optional().describe('Recent operations'),\n createdAt: z.string().datetime().describe('ISO 8601 datetime when session was created'),\n lastActivity: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n status: z.enum(['active', 'idle', 'ended']).describe('Session status'),\n});\n\nexport type CollaborationSession = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metadata Scope Enum\n * Defines the lifecycle and mutability of a metadata item.\n */\nexport const MetadataScopeSchema = z.enum([\n 'system', // Defined in Code (Files). Read-only at runtime. Upgraded via deployment.\n 'platform', // Defined in DB (Global). admin-configured. Overrides system.\n 'user', // Defined in DB (Personal). User-configured. Overrides platform/system.\n]);\n\n/**\n * Metadata Lifecycle State\n */\nexport const MetadataStateSchema = z.enum([\n 'draft', // Work in progress, not active\n 'active', // Live and running\n 'archived', // Soft deleted\n 'deprecated' // Running but flagged for removal\n]);\n\n/**\n * Unified Metadata Persistence Protocol\n * \n * Defines the standardized envelope for storing ANY metadata item (Object, View, Flow)\n * in the database (e.g. `_framework_metadata` or generic `metadata` table).\n * \n * This treats \"Metadata as Data\".\n */\nexport const MetadataRecordSchema = z.object({\n /** Primary Key (UUID) */\n id: z.string(),\n \n /** \n * Machine Name \n * The unique identifier used in code references (e.g. \"account_list_view\").\n */\n name: z.string(),\n \n /**\n * Metadata Type\n * e.g. \"object\", \"view\", \"permission_set\", \"flow\"\n */\n type: z.string(),\n \n /**\n * Namespace / Module\n * Groups metadata into packages (e.g. \"crm\", \"finance\", \"core\").\n */\n namespace: z.string().default('default'),\n\n /**\n * Package Ownership Reference\n * Links this metadata record to the package that delivered it.\n * When set, the record is \"managed\" by the package and should not be\n * directly edited — customizations go through the overlay system.\n * Null/undefined means the record was created independently (not from a package).\n */\n packageId: z.string().optional().describe('Package ID that owns/delivered this metadata'),\n\n /**\n * Managed By Indicator\n * Determines who controls this metadata record's lifecycle.\n * - \"package\": Delivered and upgraded by a plugin package (read-only base)\n * - \"platform\": Created by platform admin via UI\n * - \"user\": Created by end user\n */\n managedBy: z.enum(['package', 'platform', 'user']).optional()\n .describe('Who manages this metadata record lifecycle'),\n \n /**\n * Ownership differentiation\n */\n scope: MetadataScopeSchema.default('platform'),\n \n /**\n * The Payload\n * Stores the actual configuration JSON.\n * This field holds the value of `ViewSchema`, `ObjectSchema`, etc.\n */\n metadata: z.record(z.string(), z.unknown()),\n\n /**\n * Extension / Merge Strategy\n * If this record overrides a system record, how should it be applied?\n */\n extends: z.string().optional().describe('Name of the parent metadata to extend/override'),\n strategy: z.enum(['merge', 'replace']).default('merge'),\n\n /** Owner (for user-scope items) */\n owner: z.string().optional(),\n \n /** State */\n state: MetadataStateSchema.default('active'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant isolation'),\n\n /** Version number for optimistic concurrency */\n version: z.number().default(1).describe('Record version for optimistic concurrency control'),\n\n /** Checksum for change detection */\n checksum: z.string().optional().describe('Content checksum for change detection'),\n\n /** Source origin marker */\n source: z.enum(['filesystem', 'database', 'api', 'migration']).optional().describe('Origin of this metadata record'),\n\n /** Classification tags */\n tags: z.array(z.string()).optional().describe('Classification tags for filtering and grouping'),\n \n /** Package Publishing */\n publishedDefinition: z.unknown().optional()\n .describe('Snapshot of the last published definition'),\n publishedAt: z.string().datetime().optional()\n .describe('When this metadata was last published'),\n publishedBy: z.string().optional()\n .describe('Who published this version'),\n\n /** Audit */\n createdBy: z.string().optional(),\n createdAt: z.string().datetime().optional().describe('Creation timestamp'),\n updatedBy: z.string().optional(),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n});\n\nexport type MetadataRecord = z.infer;\nexport type MetadataScope = z.infer;\n\n/**\n * Package Publish Result\n * Returned by `publishPackage()` after a package-level metadata publish operation.\n */\nexport const PackagePublishResultSchema = z.object({\n success: z.boolean().describe('Whether the publish succeeded'),\n packageId: z.string().describe('The package ID that was published'),\n version: z.number().int().describe('New version number after publish'),\n publishedAt: z.string().datetime().describe('Publish timestamp'),\n itemsPublished: z.number().int().describe('Total metadata items published'),\n validationErrors: z.array(z.object({\n type: z.string().describe('Metadata type that failed validation'),\n name: z.string().describe('Item name that failed validation'),\n message: z.string().describe('Validation error message'),\n })).optional().describe('Validation errors if publish failed'),\n});\n\nexport type PackagePublishResult = z.infer;\n\n/**\n * Metadata Format\n * Supported file formats for metadata serialization.\n */\nexport const MetadataFormatSchema = z.enum([\n 'json', 'yaml', 'yml', 'ts', 'js',\n 'typescript', 'javascript' // Aliases\n]);\n\n/**\n * Metadata Stats\n * Statistics about a metadata item.\n */\nexport const MetadataStatsSchema = z.object({\n path: z.string().optional(),\n size: z.number().optional(),\n mtime: z.string().datetime().optional(),\n hash: z.string().optional(),\n etag: z.string().optional(), // Required by local cache\n modifiedAt: z.string().datetime().optional(), // Alias for mtime\n format: MetadataFormatSchema.optional(), // Required for serialization\n});\n\n/**\n * Metadata Loader Contract\n * Describes the capabilities and identity of a metadata loader.\n */\nexport const MetadataLoaderContractSchema = z.object({\n name: z.string(),\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Loader protocol identifier'),\n description: z.string().optional(),\n supportedFormats: z.array(z.string()).optional(),\n supportsWatch: z.boolean().optional(),\n supportsWrite: z.boolean().optional(),\n supportsCache: z.boolean().optional(),\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n scope: MetadataScopeSchema.optional(),\n namespace: z.string().optional(),\n raw: z.boolean().optional().describe('Return raw file content instead of parsed JSON'),\n cache: z.boolean().optional(),\n useCache: z.boolean().optional(), // Alias for cache\n validate: z.boolean().optional(),\n ifNoneMatch: z.string().optional(), // For caching\n recursive: z.boolean().optional(),\n limit: z.number().optional(),\n patterns: z.array(z.string()).optional(),\n loader: z.string().optional().describe('Specific loader to use (e.g. filesystem, database)'),\n});\n\n/**\n * Metadata Load Result\n */\nexport const MetadataLoadResultSchema = z.object({\n data: z.unknown(),\n stats: MetadataStatsSchema.optional(),\n format: MetadataFormatSchema.optional(),\n source: z.string().optional(), // File path or URL\n fromCache: z.boolean().optional(),\n etag: z.string().optional(),\n notModified: z.boolean().optional(),\n loadTime: z.number().optional(),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n format: MetadataFormatSchema.optional(),\n create: z.boolean().default(true),\n overwrite: z.boolean().default(true),\n path: z.string().optional(),\n prettify: z.boolean().optional(),\n indent: z.number().optional(),\n sortKeys: z.boolean().optional(),\n backup: z.boolean().optional(),\n atomic: z.boolean().optional(),\n loader: z.string().optional().describe('Specific loader to use (e.g. filesystem, database)'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n success: z.boolean(),\n path: z.string().optional(),\n stats: MetadataStatsSchema.optional(),\n etag: z.string().optional(),\n size: z.number().optional(),\n saveTime: z.number().optional(),\n backupPath: z.string().optional(),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n type: z.enum(['add', 'change', 'unlink', 'added', 'changed', 'deleted']),\n path: z.string(),\n name: z.string().optional(),\n stats: MetadataStatsSchema.optional(),\n metadataType: z.string().optional(),\n data: z.unknown().optional(),\n timestamp: z.string().datetime().optional(),\n});\n\n/**\n * Metadata Collection Info\n */\nexport const MetadataCollectionInfoSchema = z.object({\n type: z.string(),\n count: z.number(),\n namespaces: z.array(z.string()),\n});\n\n/**\n * Metadata Export/Import Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n types: z.array(z.string()).optional(),\n namespaces: z.array(z.string()).optional(),\n output: z.string().describe('Output directory or file'),\n format: MetadataFormatSchema.default('json'),\n});\n\nexport const MetadataImportOptionsSchema = z.object({\n source: z.string().describe('Input directory or file'),\n strategy: z.enum(['merge', 'replace', 'skip']).default('merge'),\n validate: z.boolean().default(true),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Source Origin\n * Indicates where a metadata record was loaded from.\n */\nexport const MetadataSourceSchema = z.enum([\n 'filesystem', // Loaded from local files\n 'database', // Loaded from database via datasource\n 'api', // Loaded from remote API\n 'migration', // Created during a migration process\n]);\n\n/**\n * Metadata Manager Config\n * \n * Unified configuration for the MetadataManager.\n * Supports datasource-backed persistence via `datasource` field,\n * which references a DatasourceSchema.name resolved at runtime.\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n * When provided, metadata is persisted to a database table.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory for filesystem-based metadata'),\n\n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).optional().describe('Enabled metadata formats'),\n\n /**\n * Enable file watching\n */\n watch: z.boolean().optional().describe('Enable file watching for filesystem loaders'),\n\n /**\n * Cache configuration\n */\n cache: z.boolean().optional().describe('Enable metadata caching'),\n\n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n }).optional().describe('File watcher options'),\n});\n\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataLoadOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\nexport type MetadataSource = z.infer;\n\n/**\n * Metadata History Record\n *\n * Represents a single version snapshot in the metadata change history.\n * Stored in the sys_metadata_history table for version tracking and rollback.\n */\nexport const MetadataHistoryRecordSchema = z.object({\n /** Primary Key (UUID) */\n id: z.string(),\n\n /** Reference to the parent metadata record ID */\n metadataId: z.string().describe('Foreign key to sys_metadata.id'),\n\n /**\n * Machine Name\n * Denormalized from parent for easier querying.\n */\n name: z.string(),\n\n /**\n * Metadata Type\n * Denormalized from parent for easier querying.\n */\n type: z.string(),\n\n /**\n * Version Number\n * Snapshot of the metadata version at this point in history.\n */\n version: z.number().describe('Version number at this snapshot'),\n\n /**\n * Operation Type\n * Indicates what kind of change triggered this history record.\n */\n operationType: z.enum(['create', 'update', 'publish', 'revert', 'delete']).describe('Type of operation that created this history entry'),\n\n /**\n * Historical Metadata Snapshot\n * Full JSON payload of the metadata definition at this version.\n * May be stored as a raw JSON string in the history table, or as a parsed object\n * in higher-level APIs. When `includeMetadata` is false, this field is null.\n */\n metadata: z\n .union([z.string(), z.record(z.string(), z.unknown())])\n .nullable()\n .optional()\n .describe('Snapshot of metadata definition at this version (raw JSON string or parsed object)'),\n\n /**\n * Content Checksum\n * SHA-256 checksum of the normalized metadata JSON for change detection.\n */\n checksum: z.string().describe('SHA-256 checksum of metadata content'),\n\n /**\n * Previous Checksum\n * Checksum of the previous version for diff optimization.\n */\n previousChecksum: z.string().optional().describe('Checksum of the previous version'),\n\n /**\n * Change Note\n * Human-readable description of what changed in this version.\n */\n changeNote: z.string().optional().describe('Description of changes made in this version'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant isolation'),\n\n /** Audit: who made this change */\n recordedBy: z.string().optional().describe('User who made this change'),\n\n /** Audit: when was this version recorded */\n recordedAt: z.string().datetime().describe('Timestamp when this version was recorded'),\n});\n\nexport type MetadataHistoryRecord = z.infer;\n\n/**\n * Metadata History Query Options\n * Options for retrieving metadata version history.\n */\nexport const MetadataHistoryQueryOptionsSchema = z.object({\n /** Limit number of history records returned */\n limit: z.number().int().positive().optional().describe('Maximum number of history records to return'),\n\n /** Offset for pagination */\n offset: z.number().int().nonnegative().optional().describe('Number of records to skip'),\n\n /** Only return versions after this timestamp */\n since: z.string().datetime().optional().describe('Only return history after this timestamp'),\n\n /** Only return versions before this timestamp */\n until: z.string().datetime().optional().describe('Only return history before this timestamp'),\n\n /** Filter by operation type */\n operationType: z.enum(['create', 'update', 'publish', 'revert', 'delete']).optional().describe('Filter by operation type'),\n\n /** Include full metadata payload in results (default: true) */\n includeMetadata: z.boolean().optional().default(true).describe('Include full metadata payload'),\n});\n\nexport type MetadataHistoryQueryOptions = z.infer;\n\n/**\n * Metadata History Query Result\n * Result of querying metadata version history.\n */\nexport const MetadataHistoryQueryResultSchema = z.object({\n /** Array of history records */\n records: z.array(MetadataHistoryRecordSchema),\n\n /** Total number of history records (for pagination) */\n total: z.number().int().nonnegative(),\n\n /** Whether there are more records available */\n hasMore: z.boolean(),\n});\n\nexport type MetadataHistoryQueryResult = z.infer;\n\n/**\n * Metadata Diff Result\n * Result of comparing two versions of metadata.\n */\nexport const MetadataDiffResultSchema = z.object({\n /** Metadata type */\n type: z.string(),\n\n /** Metadata name */\n name: z.string(),\n\n /** Version 1 (older) */\n version1: z.number(),\n\n /** Version 2 (newer) */\n version2: z.number(),\n\n /** Checksum of version 1 */\n checksum1: z.string(),\n\n /** Checksum of version 2 */\n checksum2: z.string(),\n\n /** Whether the versions are identical */\n identical: z.boolean(),\n\n /** JSON patch operations to transform v1 into v2 */\n patch: z.array(z.unknown()).optional().describe('JSON patch operations'),\n\n /** Human-readable diff summary */\n summary: z.string().optional().describe('Human-readable summary of changes'),\n});\n\nexport type MetadataDiffResult = z.infer;\n\n/**\n * Metadata History Retention Policy\n * Configuration for automatic cleanup of old history records.\n */\nexport const MetadataHistoryRetentionPolicySchema = z.object({\n /** Maximum number of versions to keep per metadata item */\n maxVersions: z.number().int().positive().optional().describe('Maximum number of versions to retain'),\n\n /** Maximum age of history records in days */\n maxAgeDays: z.number().int().positive().optional().describe('Maximum age of history records in days'),\n\n /** Whether to enable automatic cleanup */\n autoCleanup: z.boolean().default(false).describe('Enable automatic cleanup of old history'),\n\n /** Cleanup interval in hours */\n cleanupIntervalHours: z.number().int().positive().default(24).describe('How often to run cleanup (in hours)'),\n});\n\nexport type MetadataHistoryRetentionPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Service Registry Protocol\n * \n * Defines the standard built-in services that constitute the ObjectStack Kernel.\n * This registry is used by the `ObjectKernel` and `HttpDispatcher` to:\n * 1. Verify service availability.\n * 2. Route requests to the correct service handler.\n * 3. Type-check service interactions.\n */\n\n// ==========================================\n// Service Identifiers\n// ==========================================\n\nexport const CoreServiceName = z.enum([\n // Core Data & Metadata\n 'metadata', // Object/Field Definitions\n 'data', // CRUD & Query Engine\n 'auth', // Authentication & Identity\n \n // Infrastructure\n 'file-storage', // Storage Driver (Local/S3)\n 'search', // Search Engine (Elastic/Meili)\n 'cache', // Cache Driver (Redis/Memory)\n 'queue', // Job Queue (BullMQ/Redis)\n \n // Advanced Capabilities\n 'automation', // Flow & Script Engine\n 'graphql', // GraphQL API Engine\n 'analytics', // BI & Semantic Layer\n 'realtime', // WebSocket & PubSub\n 'job', // Background Job Manager\n 'notification', // Email/Push/SMS\n 'ai', // AI Engine (NLQ, Chat, Suggest, Insights)\n 'i18n', // Internationalization Service\n 'ui', // UI Metadata Service (View CRUD)\n 'workflow', // Workflow State Machine Engine\n]);\n\nexport type CoreServiceName = z.infer;\n\n/**\n * Service Criticality Level\n * Defines the startup behavior when a service is missing.\n */\nexport const ServiceCriticalitySchema = z.enum([\n 'required', // System fails to start if missing (Exit Code 1)\n 'core', // System warns if missing, functionality degraded (Warn)\n 'optional', // System ignores if missing, feature disabled (Info)\n]);\n\n/**\n * Service Requirement Definition\n */\nexport const ServiceRequirementDef = {\n // Required: The kernel cannot function without these\n data: 'required',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n metadata: 'core',\n auth: 'core',\n\n // Core: Highly recommended, defaults to in-memory / no-op if missing\n cache: 'core',\n queue: 'core',\n job: 'core',\n i18n: 'core',\n\n // Optional: Add-on capabilities\n 'file-storage': 'optional',\n search: 'optional',\n automation: 'optional',\n graphql: 'optional',\n analytics: 'optional',\n realtime: 'optional',\n notification: 'optional',\n ai: 'optional',\n ui: 'optional',\n workflow: 'optional',\n} as const;\n\n// ==========================================\n// Service Capabilities\n// ==========================================\n\n/**\n * Describes the availability and health of a service\n */\nexport const ServiceStatusSchema = z.object({\n name: CoreServiceName,\n enabled: z.boolean(),\n status: z.enum(['running', 'stopped', 'degraded', 'initializing']),\n version: z.string().optional(),\n provider: z.string().optional().describe('Implementation provider (e.g. \"s3\" for storage)'),\n features: z.array(z.string()).optional().describe('List of supported sub-features'),\n});\n\n/**\n * The Contract definition for what the Kernel MUST expose\n * map\n */\nexport const KernelServiceMapSchema = z.record(\n CoreServiceName, \n z.unknown().describe('Service Instance implementing the protocol interface')\n);\n\n// ==========================================\n// Service Interfaces (Stub definitions)\n// ==========================================\n// Ideally, we would define strict Typescript interfaces here \n// for what methods each service must expose to the Registry.\n// For Zod, we primarily validate configuration and status.\n\n// e.g.\nexport const ServiceConfigSchema = z.object({\n id: z.string(),\n name: CoreServiceName,\n options: z.record(z.string(), z.unknown()).optional(),\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Schema (Multi-Tenant Architecture)\n * \n * Defines the tenant/tenancy model for ObjectStack SaaS deployments.\n * Supports different levels of data isolation to meet varying security,\n * performance, and compliance requirements.\n * \n * Isolation Levels:\n * - shared_schema: All tenants share the same database and schema (row-level isolation)\n * - isolated_schema: Tenants have separate schemas within a shared database\n * - isolated_db: Each tenant has a completely separate database\n */\n\n/**\n * Tenant Isolation Level Enum\n * Defines how tenant data is separated in the system\n */\nexport const TenantIsolationLevel = z.enum([\n 'shared_schema', // Shared DB, shared schema, row-level isolation (most economical)\n 'isolated_schema', // Shared DB, separate schema per tenant (balanced)\n 'isolated_db', // Separate database per tenant (maximum isolation)\n]);\n\nexport type TenantIsolationLevel = z.infer;\n\n/**\n * Database Provider Enum\n * Defines which database backend is used for the tenant\n */\nexport const DatabaseProviderSchema = z.enum([\n 'turso', // Turso/libSQL (DB-per-Tenant, edge-native)\n 'postgres', // PostgreSQL (traditional, self-hosted or managed)\n 'memory', // In-memory (testing/development only)\n]).describe('Database provider for tenant data');\n\nexport type DatabaseProvider = z.infer;\n\n/**\n * Tenant Connection Config Schema\n * Stores the database connection details for a tenant (encrypted at rest)\n */\nexport const TenantConnectionConfigSchema = z.object({\n /** Database connection URL */\n url: z.string().min(1).describe('Database connection URL'),\n /** Authentication token (JWT for Turso, password for Postgres) */\n authToken: z.string().optional().describe('Database auth token (encrypted at rest)'),\n /** Turso database group name */\n group: z.string().optional().describe('Turso database group name'),\n}).describe('Tenant database connection configuration');\n\nexport type TenantConnectionConfig = z.infer;\n\n/**\n * Tenant Quota Schema\n * Defines resource limits and usage quotas for a tenant\n */\nexport const TenantQuotaSchema = z.object({\n /**\n * Maximum number of users allowed for this tenant\n */\n maxUsers: z.number().int().positive().optional().describe('Maximum number of users'),\n \n /**\n * Maximum storage space in bytes\n */\n maxStorage: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n \n /**\n * API rate limit (requests per minute)\n */\n apiRateLimit: z.number().int().positive().optional().describe('API requests per minute'),\n\n /**\n * Maximum number of custom objects the tenant can create\n */\n maxObjects: z.number().int().positive().optional().describe('Maximum number of custom objects'),\n\n /**\n * Maximum records per object/table\n */\n maxRecordsPerObject: z.number().int().positive().optional().describe('Maximum records per object'),\n\n /**\n * Maximum deployments allowed per day\n */\n maxDeploymentsPerDay: z.number().int().positive().optional().describe('Maximum deployments per day'),\n\n /**\n * Maximum storage in bytes\n */\n maxStorageBytes: z.number().int().positive().optional().describe('Maximum storage in bytes'),\n});\n\nexport type TenantQuota = z.infer;\n\n/**\n * Tenant Usage Schema\n * Tracks current resource usage for quota enforcement\n */\nexport const TenantUsageSchema = z.object({\n /** Current number of custom objects */\n currentObjectCount: z.number().int().min(0).default(0).describe('Current number of custom objects'),\n /** Current total record count across all objects */\n currentRecordCount: z.number().int().min(0).default(0).describe('Total records across all objects'),\n /** Current storage usage in bytes */\n currentStorageBytes: z.number().int().min(0).default(0).describe('Current storage usage in bytes'),\n /** Deployments executed today */\n deploymentsToday: z.number().int().min(0).default(0).describe('Deployments executed today'),\n /** Current number of active users */\n currentUsers: z.number().int().min(0).default(0).describe('Current number of active users'),\n /** API requests in the current minute */\n apiRequestsThisMinute: z.number().int().min(0).default(0).describe('API requests in the current minute'),\n /** Last updated timestamp (ISO 8601) */\n lastUpdatedAt: z.string().datetime().optional().describe('Last usage update time'),\n}).describe('Current tenant resource usage');\n\nexport type TenantUsage = z.infer;\n\n/**\n * Quota Enforcement Result\n * Result of checking whether an operation would exceed tenant quotas\n */\nexport const QuotaEnforcementResultSchema = z.object({\n /** Whether the operation is allowed */\n allowed: z.boolean().describe('Whether the operation is within quota'),\n /** Quota that would be exceeded (if not allowed) */\n exceededQuota: z.string().optional().describe('Name of the exceeded quota'),\n /** Current usage value */\n currentUsage: z.number().optional().describe('Current usage value'),\n /** Quota limit value */\n limit: z.number().optional().describe('Quota limit'),\n /** Human-readable message */\n message: z.string().optional().describe('Human-readable quota message'),\n}).describe('Quota enforcement check result');\n\nexport type QuotaEnforcementResult = z.infer;\n\n/**\n * Tenant Schema\n * \n * @deprecated This schema is maintained for backward compatibility only.\n * New implementations should use HubSpaceSchema which embeds tenant concepts.\n * \n * **Migration Guide:**\n * ```typescript\n * // Old approach (deprecated):\n * const tenant: Tenant = {\n * id: 'tenant_123',\n * name: 'My Tenant',\n * isolationLevel: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * };\n * \n * // New approach (recommended):\n * const space: HubSpace = {\n * id: '...uuid...',\n * name: 'My Tenant',\n * slug: 'my-tenant',\n * ownerId: 'user_id',\n * runtime: {\n * isolation: 'shared_schema',\n * quotas: { maxUsers: 100 }\n * },\n * bom: { ... }\n * };\n * ```\n * \n * See HubSpaceSchema in space.zod.ts for the recommended approach.\n */\nexport const TenantSchema = z.object({\n /**\n * Unique tenant identifier\n */\n id: z.string().describe('Unique tenant identifier'),\n \n /**\n * Tenant display name\n */\n name: z.string().describe('Tenant display name'),\n \n /**\n * Data isolation level\n */\n isolationLevel: TenantIsolationLevel,\n\n /**\n * Database provider for this tenant\n */\n databaseProvider: DatabaseProviderSchema.optional().describe('Database provider'),\n\n /**\n * Database connection configuration (encrypted at rest)\n */\n connectionConfig: TenantConnectionConfigSchema.optional().describe('Database connection config'),\n\n /**\n * Current provisioning status\n */\n provisioningStatus: z.enum([\n 'provisioning', 'active', 'suspended', 'failed', 'destroying',\n ]).optional().describe('Current provisioning lifecycle status'),\n\n /**\n * Tenant subscription plan\n */\n plan: z.enum(['free', 'pro', 'enterprise']).optional().describe('Subscription plan'),\n \n /**\n * Custom configuration values\n */\n customizations: z.record(z.string(), z.unknown()).optional().describe('Custom configuration values'),\n \n /**\n * Resource quotas\n */\n quotas: TenantQuotaSchema.optional(),\n});\n\nexport type Tenant = z.infer;\n\n/**\n * Tenant Isolation Strategy Documentation\n * \n * Comprehensive documentation of three isolation strategies for multi-tenant systems.\n * Each strategy has different trade-offs in terms of security, cost, complexity, and compliance.\n */\n\n/**\n * Row-Level Isolation Strategy (shared_schema)\n * \n * Recommended for: Most SaaS applications, cost-sensitive deployments\n * \n * IMPLEMENTATION:\n * - All tenants share the same database and schema\n * - Each table includes a tenant_id column\n * - PostgreSQL Row-Level Security (RLS) enforces isolation\n * - Queries automatically filter by tenant_id via RLS policies\n * \n * ADVANTAGES:\n * ✅ Simple backup and restore (single database)\n * ✅ Cost-effective (shared resources, minimal overhead)\n * ✅ Easy tenant migration (update tenant_id)\n * ✅ Efficient resource utilization (connection pooling)\n * ✅ Simple schema migrations (single schema to update)\n * ✅ Lower operational complexity\n * \n * DISADVANTAGES:\n * ❌ RLS misconfiguration can lead to data leakage\n * ❌ Performance impact from RLS policy evaluation\n * ❌ Noisy neighbor problem (one tenant can affect others)\n * ❌ Cannot easily isolate tenant to different hardware\n * ❌ Compliance challenges for regulated industries\n * \n * SECURITY CONSIDERATIONS:\n * - Requires careful RLS policy configuration\n * - Must validate tenant_id in all queries\n * - Need comprehensive testing of RLS policies\n * - Audit all database access patterns\n * - Implement application-level validation as defense-in-depth\n * \n * EXAMPLE RLS POLICY (PostgreSQL):\n * ```sql\n * -- Example: Apply RLS policy to a table (e.g., \"app_data\")\n * CREATE POLICY tenant_isolation ON app_data\n * USING (tenant_id = current_setting('app.current_tenant')::text);\n * \n * ALTER TABLE app_data ENABLE ROW LEVEL SECURITY;\n * ```\n */\nexport const RowLevelIsolationStrategySchema = z.object({\n strategy: z.literal('shared_schema').describe('Row-level isolation strategy'),\n \n /**\n * Database configuration for row-level isolation\n */\n database: z.object({\n /**\n * Whether to enable Row-Level Security (RLS)\n */\n enableRLS: z.boolean().default(true).describe('Enable PostgreSQL Row-Level Security'),\n \n /**\n * Tenant context setting method\n */\n contextMethod: z.enum([\n 'session_variable', // SET app.current_tenant = 'tenant_123'\n 'search_path', // SET search_path = tenant_123, public\n 'application_name', // SET application_name = 'tenant_123'\n ]).default('session_variable').describe('How to set tenant context'),\n \n /**\n * Session variable name for tenant context\n */\n contextVariable: z.string().default('app.current_tenant').describe('Session variable name'),\n \n /**\n * Whether to validate tenant_id at application level\n */\n applicationValidation: z.boolean().default(true).describe('Application-level tenant validation'),\n }).optional().describe('Database configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use partial indexes for tenant_id\n */\n usePartialIndexes: z.boolean().default(true).describe('Use partial indexes per tenant'),\n \n /**\n * Whether to use table partitioning\n */\n usePartitioning: z.boolean().default(false).describe('Use table partitioning by tenant_id'),\n \n /**\n * Connection pool size per tenant\n */\n poolSizePerTenant: z.number().int().positive().optional().describe('Connection pool size per tenant'),\n }).optional().describe('Performance settings'),\n});\n\nexport type RowLevelIsolationStrategy = z.infer;\nexport type RowLevelIsolationStrategyInput = z.input;\n\n/**\n * Schema-Level Isolation Strategy (isolated_schema)\n * \n * Recommended for: Enterprise SaaS, B2B platforms with compliance needs\n * \n * IMPLEMENTATION:\n * - All tenants share the same database server\n * - Each tenant has a separate database schema\n * - Schema name typically: tenant_\n * - Application switches schema using SET search_path\n * \n * ADVANTAGES:\n * ✅ Better isolation than row-level (schema boundaries)\n * ✅ Easier to debug (separate schemas)\n * ✅ Can grant different database permissions per schema\n * ✅ Reduced risk of data leakage\n * ✅ Performance isolation (indexes, statistics per schema)\n * ✅ Simplified queries (no tenant_id filtering needed)\n * \n * DISADVANTAGES:\n * ❌ More complex backups (must backup all schemas)\n * ❌ Higher migration costs (schema changes across all tenants)\n * ❌ Schema proliferation (PostgreSQL has limits)\n * ❌ Connection overhead (switching schemas)\n * ❌ More complex monitoring and maintenance\n * \n * SECURITY CONSIDERATIONS:\n * - Ensure proper schema permissions (GRANT USAGE ON SCHEMA)\n * - Validate schema name to prevent SQL injection\n * - Implement connection-level schema switching\n * - Audit schema access patterns\n * - Prevent cross-schema queries in application\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant schema\n * CREATE SCHEMA tenant_123;\n * \n * -- Grant access\n * GRANT USAGE ON SCHEMA tenant_123 TO app_user;\n * \n * -- Switch to tenant schema\n * SET search_path TO tenant_123, public;\n * ```\n */\nexport const SchemaLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_schema').describe('Schema-level isolation strategy'),\n \n /**\n * Schema configuration\n */\n schema: z.object({\n /**\n * Schema naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Schema naming pattern'),\n \n /**\n * Whether to include public schema in search_path\n */\n includePublicSchema: z.boolean().default(true).describe('Include public schema'),\n \n /**\n * Default schema for shared resources\n */\n sharedSchema: z.string().default('public').describe('Schema for shared resources'),\n \n /**\n * Whether to automatically create schema on tenant creation\n */\n autoCreateSchema: z.boolean().default(true).describe('Auto-create schema'),\n }).optional().describe('Schema configuration'),\n \n /**\n * Migration configuration\n */\n migrations: z.object({\n /**\n * Migration strategy\n */\n strategy: z.enum([\n 'parallel', // Run migrations on all schemas in parallel\n 'sequential', // Run migrations one schema at a time\n 'on_demand', // Run migrations when tenant accesses system\n ]).default('parallel').describe('Migration strategy'),\n \n /**\n * Maximum concurrent migrations\n */\n maxConcurrent: z.number().int().positive().default(10).describe('Max concurrent migrations'),\n \n /**\n * Whether to rollback on first failure\n */\n rollbackOnError: z.boolean().default(true).describe('Rollback on error'),\n }).optional().describe('Migration configuration'),\n \n /**\n * Performance optimization settings\n */\n performance: z.object({\n /**\n * Whether to use connection pooling per schema\n */\n poolPerSchema: z.boolean().default(false).describe('Separate pool per schema'),\n \n /**\n * Schema cache TTL in seconds\n */\n schemaCacheTTL: z.number().int().positive().default(3600).describe('Schema cache TTL'),\n }).optional().describe('Performance settings'),\n});\n\nexport type SchemaLevelIsolationStrategy = z.infer;\nexport type SchemaLevelIsolationStrategyInput = z.input;\n\n/**\n * Database-Level Isolation Strategy (isolated_db)\n * \n * Recommended for: Regulated industries (healthcare, finance), strict compliance requirements\n * \n * IMPLEMENTATION:\n * - Each tenant has a completely separate database\n * - Database name typically: tenant_\n * - Requires separate connection pool per tenant\n * - Complete physical and logical isolation\n * \n * ADVANTAGES:\n * ✅ Perfect data isolation (strongest security)\n * ✅ Meets strict regulatory requirements (HIPAA, SOX, PCI-DSS)\n * ✅ Complete performance isolation (no noisy neighbors)\n * ✅ Can place databases on different hardware\n * ✅ Easy to backup/restore individual tenant\n * ✅ Simplified compliance auditing per tenant\n * ✅ Can apply different encryption keys per database\n * \n * DISADVANTAGES:\n * ❌ Most expensive option (resource overhead)\n * ❌ Complex database server management (many databases)\n * ❌ Connection pool limits (max connections per server)\n * ❌ Difficult cross-tenant analytics\n * ❌ Higher operational complexity\n * ❌ Schema migrations take longer (many databases)\n * \n * SECURITY CONSIDERATIONS:\n * - Each database can have separate credentials\n * - Enables per-tenant encryption at rest\n * - Simplifies compliance and audit trails\n * - Prevents any cross-tenant data access\n * - Supports tenant-specific backup schedules\n * \n * EXAMPLE IMPLEMENTATION (PostgreSQL):\n * ```sql\n * -- Create tenant database\n * CREATE DATABASE tenant_123\n * WITH OWNER = tenant_123_user\n * ENCODING = 'UTF8'\n * LC_COLLATE = 'en_US.UTF-8'\n * LC_CTYPE = 'en_US.UTF-8';\n * \n * -- Connect to tenant database\n * \\c tenant_123\n * ```\n */\nexport const DatabaseLevelIsolationStrategySchema = z.object({\n strategy: z.literal('isolated_db').describe('Database-level isolation strategy'),\n \n /**\n * Database configuration\n */\n database: z.object({\n /**\n * Database naming pattern\n * Use {tenant_id} as placeholder (must contain only alphanumeric and underscores)\n * The tenant_id will be sanitized before substitution to prevent SQL injection\n */\n namingPattern: z.string().default('tenant_{tenant_id}').describe('Database naming pattern'),\n \n /**\n * Database server/cluster assignment strategy\n */\n serverStrategy: z.enum([\n 'shared', // All tenant databases on same server\n 'sharded', // Tenant databases distributed across servers\n 'dedicated', // Each tenant gets dedicated server (enterprise)\n ]).default('shared').describe('Server assignment strategy'),\n \n /**\n * Whether to use separate credentials per tenant\n */\n separateCredentials: z.boolean().default(true).describe('Separate credentials per tenant'),\n \n /**\n * Whether to automatically create database on tenant creation\n */\n autoCreateDatabase: z.boolean().default(true).describe('Auto-create database'),\n }).optional().describe('Database configuration'),\n \n /**\n * Connection pooling configuration\n */\n connectionPool: z.object({\n /**\n * Pool size per tenant database\n */\n poolSize: z.number().int().positive().default(10).describe('Connection pool size'),\n \n /**\n * Maximum number of tenant pools to keep active\n */\n maxActivePools: z.number().int().positive().default(100).describe('Max active pools'),\n \n /**\n * Idle pool timeout in seconds\n */\n idleTimeout: z.number().int().positive().default(300).describe('Idle pool timeout'),\n \n /**\n * Whether to use connection pooler (PgBouncer, etc.)\n */\n usePooler: z.boolean().default(true).describe('Use connection pooler'),\n }).optional().describe('Connection pool configuration'),\n \n /**\n * Backup and restore configuration\n */\n backup: z.object({\n /**\n * Backup strategy per tenant\n */\n strategy: z.enum([\n 'individual', // Separate backup per tenant\n 'consolidated', // Combined backup with all tenants\n 'on_demand', // Backup only when requested\n ]).default('individual').describe('Backup strategy'),\n \n /**\n * Backup frequency in hours\n */\n frequencyHours: z.number().int().positive().default(24).describe('Backup frequency'),\n \n /**\n * Retention period in days\n */\n retentionDays: z.number().int().positive().default(30).describe('Backup retention days'),\n }).optional().describe('Backup configuration'),\n \n /**\n * Encryption configuration\n */\n encryption: z.object({\n /**\n * Whether to use per-tenant encryption keys\n */\n perTenantKeys: z.boolean().default(false).describe('Per-tenant encryption keys'),\n \n /**\n * Encryption algorithm\n */\n algorithm: z.string().default('AES-256-GCM').describe('Encryption algorithm'),\n \n /**\n * Key management service\n */\n keyManagement: z.enum(['aws_kms', 'azure_key_vault', 'gcp_kms', 'hashicorp_vault', 'custom']).optional().describe('Key management service'),\n }).optional().describe('Encryption configuration'),\n});\n\nexport type DatabaseLevelIsolationStrategy = z.infer;\nexport type DatabaseLevelIsolationStrategyInput = z.input;\n\n/**\n * Tenant Isolation Configuration Schema\n * \n * Complete configuration for tenant isolation strategy.\n * Supports all three isolation levels with detailed configuration options.\n */\nexport const TenantIsolationConfigSchema = z.discriminatedUnion('strategy', [\n RowLevelIsolationStrategySchema,\n SchemaLevelIsolationStrategySchema,\n DatabaseLevelIsolationStrategySchema,\n]);\n\nexport type TenantIsolationConfig = z.infer;\n\n/**\n * Tenant Security Policy Schema\n * Defines security policies and compliance requirements for tenants\n */\nexport const TenantSecurityPolicySchema = z.object({\n /**\n * Encryption requirements\n */\n encryption: z.object({\n /**\n * Require encryption at rest\n */\n atRest: z.boolean().default(true).describe('Require encryption at rest'),\n \n /**\n * Require encryption in transit\n */\n inTransit: z.boolean().default(true).describe('Require encryption in transit'),\n \n /**\n * Require field-level encryption for sensitive data\n */\n fieldLevel: z.boolean().default(false).describe('Require field-level encryption'),\n }).optional().describe('Encryption requirements'),\n \n /**\n * Access control requirements\n */\n accessControl: z.object({\n /**\n * Require multi-factor authentication\n */\n requireMFA: z.boolean().default(false).describe('Require MFA'),\n \n /**\n * Require SSO/SAML authentication\n */\n requireSSO: z.boolean().default(false).describe('Require SSO'),\n \n /**\n * IP whitelist\n */\n ipWhitelist: z.array(z.string()).optional().describe('Allowed IP addresses'),\n \n /**\n * Session timeout in seconds\n */\n sessionTimeout: z.number().int().positive().default(3600).describe('Session timeout'),\n }).optional().describe('Access control requirements'),\n \n /**\n * Audit and compliance requirements\n */\n compliance: z.object({\n /**\n * Compliance standards to enforce\n */\n standards: z.array(z.enum([\n 'sox',\n 'hipaa',\n 'gdpr',\n 'pci_dss',\n 'iso_27001',\n 'fedramp',\n ])).optional().describe('Compliance standards'),\n \n /**\n * Require audit logging for all operations\n */\n requireAuditLog: z.boolean().default(true).describe('Require audit logging'),\n \n /**\n * Audit log retention period in days\n */\n auditRetentionDays: z.number().int().positive().default(365).describe('Audit retention days'),\n \n /**\n * Data residency requirements\n */\n dataResidency: z.object({\n /**\n * Required geographic region\n */\n region: z.string().optional().describe('Required region (e.g., US, EU, APAC)'),\n \n /**\n * Prohibited regions\n */\n excludeRegions: z.array(z.string()).optional().describe('Prohibited regions'),\n }).optional().describe('Data residency requirements'),\n }).optional().describe('Compliance requirements'),\n});\n\nexport type TenantSecurityPolicy = z.infer;\nexport type TenantSecurityPolicyInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metric Type Classification\n */\nexport const LicenseMetricType = z.enum([\n 'boolean', // Feature Flag (Enabled/Disabled)\n 'counter', // Usage Count (e.g. API Calls, Records Created) - Accumulates\n 'gauge', // Current Level (e.g. Storage Used, Users Active) - Point in time\n]).describe('License metric type');\nexport type LicenseMetricType = z.infer;\n\n/**\n * Feature/Limit Definition Schema\n * Defines a controllable capability of the system.\n */\nexport const FeatureSchema = z.object({\n code: z.string().regex(/^[a-z_][a-z0-9_.]*$/).describe('Feature code (e.g. core.api_access)'),\n label: z.string(),\n description: z.string().optional(),\n \n type: LicenseMetricType.default('boolean'),\n \n /** For counters/gauges */\n unit: z.enum(['count', 'bytes', 'seconds', 'percent']).optional(),\n \n /** Dependencies (e.g. 'audit_log' requires 'enterprise_tier') */\n requires: z.array(z.string()).optional(),\n});\n\n/**\n * Subscription Plan Schema\n * Defines a tier of service (e.g. \"Free\", \"Pro\", \"Enterprise\").\n */\nexport const PlanSchema = z.object({\n code: z.string().describe('Plan code (e.g. pro_v1)'),\n label: z.string(),\n active: z.boolean().default(true),\n \n /** Feature Entitlements */\n features: z.array(z.string()).describe('List of enabled boolean features'),\n \n /** Limit Quotas */\n limits: z.record(z.string(), z.number()).describe('Map of metric codes to limit values (e.g. { storage_gb: 10 })'),\n \n /** Pricing (Optional Metadata) */\n currency: z.string().default('USD').optional(),\n priceMonthly: z.number().optional(),\n priceYearly: z.number().optional(),\n});\n\n/**\n * License Schema\n * The actual entitlement object assigned to a Space.\n * Often signed as a JWT.\n */\nexport const LicenseSchema = z.object({\n /** Identity */\n spaceId: z.string().describe('Target Space ID'),\n planCode: z.string(),\n \n /** Validity */\n issuedAt: z.string().datetime(),\n expiresAt: z.string().datetime().optional(), // Null = Perpetual\n \n /** Status */\n status: z.enum(['active', 'expired', 'suspended', 'trial']),\n \n /** Overrides (Specific to this space, exceeding the plan) */\n customFeatures: z.array(z.string()).optional(),\n customLimits: z.record(z.string(), z.number()).optional(),\n \n /** Authorized Add-ons */\n plugins: z.array(z.string()).optional().describe('List of enabled plugin package IDs'),\n\n /** Signature */\n signature: z.string().optional().describe('Cryptographic signature of the license'),\n});\n\nexport type Feature = z.infer;\nexport type FeatureInput = z.input;\nexport type Plan = z.infer;\nexport type PlanInput = z.input;\nexport type License = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Registry Configuration Protocol\n * \n * Defines the configuration for the ObjectStack Registry Service.\n * Includes federation, synchronization, and storage settings.\n */\n\n/**\n * Registry Sync Policy\n * Defines how registries synchronize with upstreams\n */\nexport const RegistrySyncPolicySchema = z.enum([\n 'manual', // Manual synchronization only\n 'auto', // Automatic synchronization\n 'proxy', // Proxy requests to upstream without caching\n]).describe('Registry synchronization strategy');\n\n/**\n * Registry Upstream Configuration\n * Configuration for upstream registry connection\n */\nexport const RegistryUpstreamSchema = z.object({\n /**\n * Upstream registry URL\n */\n url: z.string().url()\n .describe('Upstream registry endpoint'),\n \n /**\n * Synchronization policy\n */\n syncPolicy: RegistrySyncPolicySchema.default('auto'),\n \n /**\n * Sync interval in seconds (for auto sync)\n */\n syncInterval: z.number().int().min(60).optional()\n .describe('Auto-sync interval in seconds'),\n \n /**\n * Authentication credentials\n */\n auth: z.object({\n type: z.enum(['none', 'basic', 'bearer', 'api-key', 'oauth2']).default('none'),\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n apiKey: z.string().optional(),\n }).optional(),\n \n /**\n * TLS/SSL configuration\n */\n tls: z.object({\n enabled: z.boolean().default(true),\n verifyCertificate: z.boolean().default(true),\n certificate: z.string().optional(),\n privateKey: z.string().optional(),\n }).optional(),\n \n /**\n * Timeout settings\n */\n timeout: z.number().int().min(1000).default(30000)\n .describe('Request timeout in milliseconds'),\n \n /**\n * Retry configuration\n */\n retry: z.object({\n maxAttempts: z.number().int().min(0).default(3),\n backoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),\n }).optional(),\n});\n\n/**\n * Registry Configuration\n * Complete registry configuration supporting federation\n */\nexport const RegistryConfigSchema = z.object({\n /**\n * Registry type\n */\n type: z.enum([\n 'public', // Public marketplace (e.g., plugins.objectstack.com)\n 'private', // Private enterprise registry\n 'hybrid', // Hybrid with upstream federation\n ]).describe('Registry deployment type'),\n \n /**\n * Upstream registries (for hybrid/private registries)\n */\n upstream: z.array(RegistryUpstreamSchema).optional()\n .describe('Upstream registries to sync from or proxy to'),\n \n /**\n * Scopes managed by this registry\n */\n scope: z.array(z.string()).optional()\n .describe('npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)'),\n \n /**\n * Default scope for new plugins\n */\n defaultScope: z.string().optional()\n .describe('Default scope prefix for new plugins'),\n \n /**\n * Registry storage configuration\n */\n storage: z.object({\n /**\n * Storage backend type\n */\n backend: z.enum(['local', 's3', 'gcs', 'azure-blob', 'oss']).default('local'),\n \n /**\n * Storage path or bucket name\n */\n path: z.string().optional(),\n \n /**\n * Credentials\n */\n credentials: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n \n /**\n * Registry visibility\n */\n visibility: z.enum(['public', 'private', 'internal']).default('private')\n .describe('Who can access this registry'),\n \n /**\n * Access control\n */\n accessControl: z.object({\n /**\n * Require authentication for read\n */\n requireAuthForRead: z.boolean().default(false),\n \n /**\n * Require authentication for write\n */\n requireAuthForWrite: z.boolean().default(true),\n \n /**\n * Allowed users/teams\n */\n allowedPrincipals: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Caching configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true),\n ttl: z.number().int().min(0).default(3600)\n .describe('Cache TTL in seconds'),\n maxSize: z.number().int().optional()\n .describe('Maximum cache size in bytes'),\n }).optional(),\n \n /**\n * Mirroring configuration (for high availability)\n */\n mirrors: z.array(z.object({\n url: z.string().url(),\n priority: z.number().int().min(1).default(1),\n })).optional()\n .describe('Mirror registries for redundancy'),\n});\n\nexport type RegistrySyncPolicy = z.infer;\nexport type RegistryUpstream = z.infer;\nexport type RegistryConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Tenant Provisioning Protocol\n *\n * Defines the schemas for the \"Register → Instant ObjectOS\" provisioning pipeline:\n * 1. User registers → ProvisioningRequest created\n * 2. Turso database created → Schema synced → Seed data applied\n * 3. Tenant status transitions: provisioning → active\n *\n * Provisioning is designed to be:\n * - **Idempotent**: Re-running the same request produces the same result\n * - **Observable**: Each step has explicit status tracking\n * - **Fast**: Target 2-5 seconds for complete provisioning\n */\n\n// ==========================================================================\n// 1. Enums & Constants\n// ==========================================================================\n\n/**\n * Tenant provisioning lifecycle status.\n */\nexport const TenantProvisioningStatusEnum = z.enum([\n 'provisioning', // Database creation in progress\n 'active', // Fully provisioned and operational\n 'suspended', // Temporarily disabled (billing, policy)\n 'failed', // Provisioning failed (requires retry or manual intervention)\n 'destroying', // Deletion in progress\n]).describe('Tenant provisioning lifecycle status');\n\nexport type TenantProvisioningStatus = z.infer;\n\n/**\n * Tenant subscription plan.\n */\nexport const TenantPlanSchema = z.enum([\n 'free', // Free tier with limited quotas\n 'pro', // Professional tier with higher quotas\n 'enterprise', // Enterprise tier with custom quotas and SLAs\n]).describe('Tenant subscription plan');\n\nexport type TenantPlan = z.infer;\n\n/**\n * Available deployment regions.\n */\nexport const TenantRegionSchema = z.enum([\n 'us-east', // US East (Virginia)\n 'us-west', // US West (Oregon)\n 'eu-west', // EU West (Ireland)\n 'eu-central', // EU Central (Frankfurt)\n 'ap-southeast',// Asia Pacific (Singapore)\n 'ap-northeast',// Asia Pacific (Tokyo)\n]).describe('Available deployment region');\n\nexport type TenantRegion = z.infer;\n\n// ==========================================================================\n// 2. Provisioning Step Tracking\n// ==========================================================================\n\n/**\n * Individual provisioning step status.\n * Tracks the progress of each step in the provisioning pipeline.\n */\nexport const ProvisioningStepSchema = z.object({\n /** Step identifier */\n name: z.string().min(1).describe('Step name (e.g., create_database, sync_schema)'),\n\n /** Step execution status */\n status: z.enum(['pending', 'running', 'completed', 'failed', 'skipped']).describe('Step status'),\n\n /** When the step started (ISO 8601) */\n startedAt: z.string().datetime().optional().describe('Step start time'),\n\n /** When the step completed (ISO 8601) */\n completedAt: z.string().datetime().optional().describe('Step completion time'),\n\n /** Duration in milliseconds */\n durationMs: z.number().int().min(0).optional().describe('Step duration in ms'),\n\n /** Error message if the step failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('Individual provisioning step status');\n\nexport type ProvisioningStep = z.infer;\n\n// ==========================================================================\n// 3. Provisioning Request & Result\n// ==========================================================================\n\n/**\n * Tenant Provisioning Request.\n * Input for creating a new tenant with its isolated database.\n */\nexport const TenantProvisioningRequestSchema = z.object({\n /** Organization ID that owns this tenant */\n orgId: z.string().min(1).describe('Organization ID'),\n\n /** Requested subscription plan */\n plan: TenantPlanSchema.default('free'),\n\n /** Preferred deployment region */\n region: TenantRegionSchema.default('us-east'),\n\n /** Optional tenant display name */\n displayName: z.string().optional().describe('Tenant display name'),\n\n /** Optional initial admin user email */\n adminEmail: z.string().email().optional().describe('Initial admin user email'),\n\n /** Optional metadata to attach to the tenant */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata'),\n}).describe('Tenant provisioning request');\n\nexport type TenantProvisioningRequest = z.infer;\n\n/**\n * Tenant Provisioning Result.\n * Output after provisioning completes (or fails).\n */\nexport const TenantProvisioningResultSchema = z.object({\n /** Unique tenant identifier */\n tenantId: z.string().min(1).describe('Provisioned tenant ID'),\n\n /** Database connection URL (libsql:// or https://) */\n connectionUrl: z.string().min(1).describe('Database connection URL'),\n\n /** Current provisioning status */\n status: TenantProvisioningStatusEnum,\n\n /** Deployment region */\n region: TenantRegionSchema,\n\n /** Active subscription plan */\n plan: TenantPlanSchema,\n\n /** Provisioning pipeline steps with status */\n steps: z.array(ProvisioningStepSchema).default([]).describe('Pipeline step statuses'),\n\n /** Total provisioning duration in milliseconds */\n totalDurationMs: z.number().int().min(0).optional().describe('Total provisioning duration'),\n\n /** Provisioned timestamp (ISO 8601) */\n provisionedAt: z.string().datetime().optional().describe('Provisioning completion time'),\n\n /** Error message if provisioning failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('Tenant provisioning result');\n\nexport type TenantProvisioningResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Deploy Bundle Protocol\n *\n * Defines the schemas for metadata-driven deployment:\n * Schema Push → Zod Validate → Diff → DDL Sync → Register\n *\n * This eliminates traditional CI/CD pipelines for schema changes.\n * A \"deploy\" is a bundle of metadata (objects, views, flows, permissions)\n * that is validated, diffed against the current state, and applied\n * as DDL migrations directly to the tenant database.\n *\n * Target: 2-5 second deploys vs. 2-15 minute traditional Docker/CI/CD.\n */\n\n// ==========================================================================\n// 1. Deploy Status\n// ==========================================================================\n\n/**\n * Deployment lifecycle status.\n */\nexport const DeployStatusEnum = z.enum([\n 'validating', // Zod schema validation in progress\n 'diffing', // Comparing desired state vs current state\n 'migrating', // Executing DDL statements\n 'registering', // Updating metadata registry\n 'ready', // Deployment complete and live\n 'failed', // Deployment failed at some stage\n 'rolling_back', // Rollback in progress\n]).describe('Deployment lifecycle status');\n\nexport type DeployStatus = z.infer;\n\n// ==========================================================================\n// 2. Deploy Diff\n// ==========================================================================\n\n/**\n * Schema change descriptor for a single entity (object/field).\n */\nexport const SchemaChangeSchema = z.object({\n /** Type of entity being changed */\n entityType: z.enum(['object', 'field', 'index', 'view', 'flow', 'permission']).describe('Entity type'),\n\n /** Name of the entity */\n entityName: z.string().min(1).describe('Entity name'),\n\n /** Parent entity name (e.g., object name for a field change) */\n parentEntity: z.string().optional().describe('Parent entity name'),\n\n /** Type of change */\n changeType: z.enum(['added', 'modified', 'removed']).describe('Change type'),\n\n /** Previous value (for modified/removed) */\n oldValue: z.unknown().optional().describe('Previous value'),\n\n /** New value (for added/modified) */\n newValue: z.unknown().optional().describe('New value'),\n}).describe('Individual schema change');\n\nexport type SchemaChange = z.infer;\n\n/**\n * Deploy Diff — what changed between current and desired state.\n */\nexport const DeployDiffSchema = z.object({\n /** List of all schema changes */\n changes: z.array(SchemaChangeSchema).default([]).describe('List of schema changes'),\n\n /** Summary counts */\n summary: z.object({\n added: z.number().int().min(0).default(0).describe('Number of added entities'),\n modified: z.number().int().min(0).default(0).describe('Number of modified entities'),\n removed: z.number().int().min(0).default(0).describe('Number of removed entities'),\n }).describe('Change summary counts'),\n\n /** Whether the diff contains breaking changes (e.g., column removal) */\n hasBreakingChanges: z.boolean().default(false).describe('Whether diff contains breaking changes'),\n}).describe('Schema diff between current and desired state');\n\nexport type DeployDiff = z.infer;\n\n// ==========================================================================\n// 3. Migration Plan\n// ==========================================================================\n\n/**\n * A single DDL migration statement.\n */\nexport const MigrationStatementSchema = z.object({\n /** SQL DDL statement to execute */\n sql: z.string().min(1).describe('SQL DDL statement'),\n\n /** Whether this statement is reversible */\n reversible: z.boolean().default(true).describe('Whether the statement can be reversed'),\n\n /** Reverse SQL statement (for rollback) */\n rollbackSql: z.string().optional().describe('Reverse SQL for rollback'),\n\n /** Execution order (lower = earlier) */\n order: z.number().int().min(0).describe('Execution order'),\n}).describe('Single DDL migration statement');\n\nexport type MigrationStatement = z.infer;\n\n/**\n * Migration Plan — ordered list of DDL statements to execute.\n */\nexport const MigrationPlanSchema = z.object({\n /** Ordered list of migration statements */\n statements: z.array(MigrationStatementSchema).default([]).describe('Ordered DDL statements'),\n\n /** SQL dialect the statements are written for */\n dialect: z.string().min(1).describe('Target SQL dialect'),\n\n /** Whether the entire plan is reversible */\n reversible: z.boolean().default(true).describe('Whether the plan can be fully rolled back'),\n\n /** Estimated execution time in milliseconds */\n estimatedDurationMs: z.number().int().min(0).optional().describe('Estimated execution time'),\n}).describe('Ordered migration plan');\n\nexport type MigrationPlan = z.infer;\n\n// ==========================================================================\n// 4. Deploy Validation\n// ==========================================================================\n\n/**\n * Validation issue found during bundle validation.\n */\nexport const DeployValidationIssueSchema = z.object({\n /** Severity of the issue */\n severity: z.enum(['error', 'warning', 'info']).describe('Issue severity'),\n\n /** Entity path where the issue was found */\n path: z.string().describe('Entity path (e.g., objects.project_task.fields.name)'),\n\n /** Human-readable issue description */\n message: z.string().describe('Issue description'),\n\n /** Zod error code if applicable */\n code: z.string().optional().describe('Validation error code'),\n}).describe('Validation issue');\n\nexport type DeployValidationIssue = z.infer;\n\n/**\n * Zod validation result for the entire deploy bundle.\n */\nexport const DeployValidationResultSchema = z.object({\n /** Whether the bundle passed validation */\n valid: z.boolean().describe('Whether the bundle is valid'),\n\n /** List of validation issues */\n issues: z.array(DeployValidationIssueSchema).default([]).describe('Validation issues'),\n\n /** Number of errors */\n errorCount: z.number().int().min(0).default(0).describe('Number of errors'),\n\n /** Number of warnings */\n warningCount: z.number().int().min(0).default(0).describe('Number of warnings'),\n}).describe('Bundle validation result');\n\nexport type DeployValidationResult = z.infer;\n\n// ==========================================================================\n// 5. Deploy Bundle & Manifest\n// ==========================================================================\n\n/**\n * Deploy Manifest — metadata about the deployment.\n */\nexport const DeployManifestSchema = z.object({\n /** Deployment version (semver) */\n version: z.string().min(1).describe('Deployment version'),\n\n /** SHA256 checksum of the bundle contents */\n checksum: z.string().optional().describe('SHA256 checksum'),\n\n /** Object definitions included in this deployment */\n objects: z.array(z.string()).default([]).describe('Object names included'),\n\n /** View definitions included */\n views: z.array(z.string()).default([]).describe('View names included'),\n\n /** Flow definitions included */\n flows: z.array(z.string()).default([]).describe('Flow names included'),\n\n /** Permission definitions included */\n permissions: z.array(z.string()).default([]).describe('Permission names included'),\n\n /** Timestamp of bundle creation (ISO 8601) */\n createdAt: z.string().datetime().optional().describe('Bundle creation time'),\n}).describe('Deployment manifest');\n\nexport type DeployManifest = z.infer;\n\n/**\n * Deploy Bundle — container for all metadata being deployed.\n * This is the primary input to the deploy pipeline.\n */\nexport const DeployBundleSchema = z.object({\n /** Bundle manifest with version and contents list */\n manifest: DeployManifestSchema,\n\n /** Object definitions (JSON-serialized ObjectStack objects) */\n objects: z.array(z.record(z.string(), z.unknown())).default([]).describe('Object definitions'),\n\n /** View definitions */\n views: z.array(z.record(z.string(), z.unknown())).default([]).describe('View definitions'),\n\n /** Flow definitions */\n flows: z.array(z.record(z.string(), z.unknown())).default([]).describe('Flow definitions'),\n\n /** Permission definitions */\n permissions: z.array(z.record(z.string(), z.unknown())).default([]).describe('Permission definitions'),\n\n /** Seed data records to populate after schema migration */\n seedData: z.array(z.record(z.string(), z.unknown())).default([]).describe('Seed data records'),\n}).describe('Deploy bundle containing all metadata for deployment');\n\nexport type DeployBundle = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * App Installation Protocol\n *\n * Defines the schemas for installing marketplace apps into tenant databases.\n * An \"app install\" injects metadata (objects, views, flows) + schema sync\n * into a tenant's isolated database.\n *\n * Install pipeline:\n * 1. Check compatibility (kernel version, existing objects, conflicts)\n * 2. Validate app manifest\n * 3. Apply schema changes (via deploy pipeline)\n * 4. Seed initial data\n * 5. Register app in tenant's metadata registry\n */\n\n// ==========================================================================\n// 1. App Manifest\n// ==========================================================================\n\n/**\n * App Manifest — describes an installable app package.\n */\nexport const AppManifestSchema = z.object({\n /** Unique app identifier (snake_case) */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('App identifier (snake_case)'),\n\n /** Display label for the app */\n label: z.string().min(1).describe('App display label'),\n\n /** App version (semver) */\n version: z.string().min(1).describe('App version (semver)'),\n\n /** App description */\n description: z.string().optional().describe('App description'),\n\n /** Minimum kernel version required */\n minKernelVersion: z.string().optional().describe('Minimum required kernel version'),\n\n /** Object definitions provided by this app */\n objects: z.array(z.string()).default([]).describe('Object names provided'),\n\n /** View definitions provided */\n views: z.array(z.string()).default([]).describe('View names provided'),\n\n /** Flow definitions provided */\n flows: z.array(z.string()).default([]).describe('Flow names provided'),\n\n /** Whether seed data is included */\n hasSeedData: z.boolean().default(false).describe('Whether app includes seed data'),\n\n /** Seed data records to populate on install */\n seedData: z.array(z.record(z.string(), z.unknown())).default([]).describe('Seed data records'),\n\n /** App dependencies (other apps that must be installed first) */\n dependencies: z.array(z.string()).default([]).describe('Required app dependencies'),\n}).describe('App manifest for marketplace installation');\n\nexport type AppManifest = z.infer;\n\n// ==========================================================================\n// 2. Compatibility Check\n// ==========================================================================\n\n/**\n * App Compatibility Check Result.\n */\nexport const AppCompatibilityCheckSchema = z.object({\n /** Whether the app is compatible with the current environment */\n compatible: z.boolean().describe('Whether the app is compatible'),\n\n /** Compatibility issues found */\n issues: z.array(z.object({\n /** Issue severity */\n severity: z.enum(['error', 'warning']).describe('Issue severity'),\n /** Issue description */\n message: z.string().describe('Issue description'),\n /** Issue category */\n category: z.enum([\n 'kernel_version', // Kernel version mismatch\n 'object_conflict', // Object name already exists\n 'dependency_missing', // Required dependency not installed\n 'quota_exceeded', // Tenant quota would be exceeded\n ]).describe('Issue category'),\n })).default([]).describe('Compatibility issues'),\n}).describe('App compatibility check result');\n\nexport type AppCompatibilityCheck = z.infer;\n\n// ==========================================================================\n// 3. Install Request & Result\n// ==========================================================================\n\n/**\n * App Install Request.\n */\nexport const AppInstallRequestSchema = z.object({\n /** Target tenant ID */\n tenantId: z.string().min(1).describe('Target tenant ID'),\n\n /** App identifier to install */\n appId: z.string().min(1).describe('App identifier'),\n\n /** Optional configuration overrides */\n configOverrides: z.record(z.string(), z.unknown()).optional().describe('Configuration overrides'),\n\n /** Whether to skip seed data */\n skipSeedData: z.boolean().default(false).describe('Skip seed data population'),\n}).describe('App install request');\n\nexport type AppInstallRequest = z.infer;\n\n/**\n * App Install Result.\n */\nexport const AppInstallResultSchema = z.object({\n /** Whether the installation succeeded */\n success: z.boolean().describe('Whether installation succeeded'),\n\n /** App identifier that was installed */\n appId: z.string().describe('Installed app identifier'),\n\n /** App version installed */\n version: z.string().describe('Installed app version'),\n\n /** Objects created or updated */\n installedObjects: z.array(z.string()).default([]).describe('Objects created/updated'),\n\n /** Tables created in the database */\n createdTables: z.array(z.string()).default([]).describe('Database tables created'),\n\n /** Number of seed records inserted */\n seededRecords: z.number().int().min(0).default(0).describe('Seed records inserted'),\n\n /** Installation duration in milliseconds */\n durationMs: z.number().int().min(0).optional().describe('Installation duration'),\n\n /** Error message if installation failed */\n error: z.string().optional().describe('Error message on failure'),\n}).describe('App install result');\n\nexport type AppInstallResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Package conventions and directory structure constants.\n * These define the \"Law of Location\" - where things must be in ObjectStack packages.\n * \n * These paths are the source of truth used by:\n * - ObjectOS Runtime (to locate package components)\n * - ObjectStack CLI (to scaffold and validate packages)\n * - ObjectStudio IDE (to provide intelligent navigation and validation)\n */\nexport const PKG_CONVENTIONS = {\n /**\n * Standard directories within ObjectStack packages.\n * All packages MUST follow these conventions for the runtime to locate resources.\n */\n DIRS: {\n /** \n * Location for schema definitions (Zod schemas, JSON schemas).\n * Path: src/schemas\n */\n SCHEMA: 'src/schemas',\n \n /** \n * Location for server-side code and triggers.\n * Path: src/server\n */\n SERVER: 'src/server',\n \n /** \n * Location for server-side trigger functions.\n * Path: src/triggers\n */\n TRIGGERS: 'src/triggers',\n \n /** \n * Location for client-side code.\n * Path: src/client\n */\n CLIENT: 'src/client',\n \n /** \n * Location for client-side page components.\n * Path: src/client/pages\n */\n PAGES: 'src/client/pages',\n \n /** \n * Location for static assets (images, fonts, etc.).\n * Path: assets\n */\n ASSETS: 'assets',\n },\n \n /**\n * Standard file names within ObjectStack packages.\n */\n FILES: {\n /** \n * Package manifest configuration file.\n * File: objectstack.config.ts\n */\n MANIFEST: 'objectstack.config.ts',\n \n /** \n * Main entry point for the package.\n * File: src/index.ts\n */\n ENTRY: 'src/index.ts',\n },\n} as const;\n\n/**\n * Type helper to extract directory path values.\n */\nexport type PackageDirectory = typeof PKG_CONVENTIONS.DIRS[keyof typeof PKG_CONVENTIONS.DIRS];\n\n/**\n * Type helper to extract file path values.\n */\nexport type PackageFile = typeof PKG_CONVENTIONS.FILES[keyof typeof PKG_CONVENTIONS.FILES];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * System Object Names — Protocol Layer Constants\n *\n * These constants define the canonical, protocol-level names for system objects.\n * All API calls, SDK references, permissions checks, and metadata lookups MUST use\n * these names instead of hardcoded strings or physical table names.\n *\n * The actual storage table name may differ via `ObjectSchema.tableName`.\n * The mapping between protocol name and storage name is handled by the\n * ObjectQL Engine / Driver layer.\n *\n * @example\n * ```ts\n * import { SystemObjectName } from '@objectstack/spec/system';\n *\n * // Always use the constant for API / SDK / permission references\n * const users = await engine.find(SystemObjectName.USER, { ... });\n * ```\n */\nexport const SystemObjectName = {\n /** Authentication: user identity */\n USER: 'sys_user',\n /** Authentication: active session */\n SESSION: 'sys_session',\n /** Authentication: OAuth / credential account */\n ACCOUNT: 'sys_account',\n /** Authentication: email / phone verification */\n VERIFICATION: 'sys_verification',\n /** Authentication: organization (multi-org support) */\n ORGANIZATION: 'sys_organization',\n /** Authentication: organization member */\n MEMBER: 'sys_member',\n /** Authentication: organization invitation */\n INVITATION: 'sys_invitation',\n /** Authentication: team within an organization */\n TEAM: 'sys_team',\n /** Authentication: team membership */\n TEAM_MEMBER: 'sys_team_member',\n /** Authentication: API key for programmatic access */\n API_KEY: 'sys_api_key',\n /** Authentication: two-factor authentication credentials */\n TWO_FACTOR: 'sys_two_factor',\n /** Authentication: user preferences (theme, locale, etc.) */\n USER_PREFERENCE: 'sys_user_preference',\n /** Security: role definition for RBAC */\n ROLE: 'sys_role',\n /** Security: permission set grouping */\n PERMISSION_SET: 'sys_permission_set',\n /** Audit: system audit log */\n AUDIT_LOG: 'sys_audit_log',\n /** System metadata storage */\n METADATA: 'sys_metadata',\n /** Realtime: user presence state */\n PRESENCE: 'sys_presence',\n} as const;\n\n/** Union type of all system object names */\nexport type SystemObjectName = typeof SystemObjectName[keyof typeof SystemObjectName];\n\n/**\n * System Field Names — Protocol Layer Constants\n *\n * These constants define the canonical, protocol-level names for common system fields.\n * All API calls, SDK references, and permission checks MUST use these constants\n * instead of hardcoded strings or physical column names.\n *\n * The actual storage column name may differ via `FieldSchema.columnName`.\n *\n * @example\n * ```ts\n * import { SystemFieldName } from '@objectstack/spec/system';\n *\n * // Use the constant to reference the owner field in queries\n * const myRecords = await engine.find('project', {\n * filters: [SystemFieldName.OWNER_ID, '=', currentUserId],\n * });\n * ```\n */\nexport const SystemFieldName = {\n /** Primary key */\n ID: 'id',\n /** Record creation timestamp */\n CREATED_AT: 'created_at',\n /** Record last-updated timestamp */\n UPDATED_AT: 'updated_at',\n /** Record owner (lookup to user) */\n OWNER_ID: 'owner_id',\n /** Tenant isolation key */\n TENANT_ID: 'tenant_id',\n /** Foreign key to user on session / account objects */\n USER_ID: 'user_id',\n /** Soft-delete timestamp */\n DELETED_AT: 'deleted_at',\n} as const;\n\n/** Union type of all system field names */\nexport type SystemFieldName = typeof SystemFieldName[keyof typeof SystemFieldName];\n\n/**\n * Storage Name Mapping — Protocol ↔ Physical Name Resolution\n *\n * Provides pure utility functions for resolving protocol-level names to\n * physical storage names and vice-versa.\n *\n * These helpers are intended for use inside the ObjectQL Engine and Driver layers.\n * They are intentionally stateless — they receive the object definition and return\n * the resolved name.\n */\nexport const StorageNameMapping = {\n /**\n * Resolve the physical table name for an object.\n * Priority: explicit `tableName` → auto-derived `{namespace}_{name}` → `name`.\n *\n * @param object - Object definition (at minimum `{ name: string; namespace?: string; tableName?: string }`)\n * @returns The physical table / collection name to use in storage operations.\n */\n resolveTableName(object: { name: string; namespace?: string; tableName?: string }): string {\n return object.tableName ?? (object.namespace ? `${object.namespace}_${object.name}` : object.name);\n },\n\n /**\n * Resolve the physical column name for a field.\n * Falls back to `fieldKey` when `columnName` is not set on the field.\n *\n * @param fieldKey - The protocol-level field key (snake_case identifier).\n * @param field - Field definition (at minimum `{ columnName?: string }`).\n * @returns The physical column name to use in storage operations.\n */\n resolveColumnName(fieldKey: string, field: { columnName?: string }): string {\n return field.columnName ?? fieldKey;\n },\n\n /**\n * Build a complete field-key → column-name map for an entire object.\n *\n * @param fields - The fields record from an ObjectSchema.\n * @returns A record mapping every protocol field key to its physical column name.\n */\n buildColumnMap(fields: Record): Record {\n const map: Record = {};\n for (const key of Object.keys(fields)) {\n map[key] = fields[key].columnName ?? key;\n }\n return map;\n },\n\n /**\n * Build a reverse column-name → field-key map for an entire object.\n * Useful for translating storage-layer results back to protocol-level field keys.\n *\n * @param fields - The fields record from an ObjectSchema.\n * @returns A record mapping every physical column name back to its protocol field key.\n */\n buildReverseColumnMap(fields: Record): Record {\n const map: Record = {};\n for (const key of Object.keys(fields)) {\n const col = fields[key].columnName ?? key;\n map[col] = key;\n }\n return map;\n },\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './cli-extension.zod';\nexport * from './cli-plugin-commands.zod';\nexport * from './context.zod';\nexport * from './dependency-resolution.zod';\nexport * from './dev-plugin.zod';\nexport * from './events.zod';\nexport * from './feature.zod';\nexport * from './manifest.zod';\nexport * from './metadata-customization.zod';\nexport * from './metadata-loader.zod';\nexport * from './metadata-plugin.zod';\nexport * from './package-artifact.zod';\nexport * from './package-registry.zod';\nexport * from './package-upgrade.zod';\nexport * from './plugin-capability.zod';\nexport * from './plugin-lifecycle-advanced.zod';\nexport * from './plugin-lifecycle-events.zod';\nexport * from './plugin-loading.zod';\nexport * from './plugin-runtime.zod';\nexport * from './plugin-security-advanced.zod';\nexport * from './plugin-structure.zod';\nexport * from './plugin-validator.zod';\nexport * from './plugin-versioning.zod';\nexport * from './plugin.zod';\nexport * from './service-registry.zod';\nexport * from './startup-orchestrator.zod';\nexport * from './plugin-registry.zod';\nexport * from './plugin-security.zod';\nexport * from './execution-context.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # CLI Extension Protocol\n * \n * Defines the contract for plugins that extend the ObjectStack CLI with\n * custom commands. This enables third-party packages (e.g., marketplace,\n * cloud deployment tools) to register new CLI commands via oclif's\n * built-in plugin system.\n * \n * ## How It Works (oclif Plugin Model)\n * \n * 1. **Declare** — Plugin's `package.json` includes an `oclif` config section\n * declaring its commands directory and any topics.\n * 2. **Discover** — The main CLI (`@objectstack/cli`) lists the plugin in its\n * `oclif.plugins` array, or users install it via `os plugins install `.\n * 3. **Load** — oclif automatically discovers and registers all Command classes\n * exported from the plugin's commands directory.\n * \n * ## Plugin Package Contract\n * \n * The plugin must be a valid oclif plugin:\n * \n * ```json\n * // package.json of the plugin\n * {\n * \"name\": \"@acme/plugin-marketplace\",\n * \"oclif\": {\n * \"commands\": {\n * \"strategy\": \"pattern\",\n * \"target\": \"./dist/commands\",\n * \"glob\": \"**\\/*.js\"\n * }\n * }\n * }\n * ```\n * \n * Commands are standard oclif Command classes:\n * \n * ```typescript\n * // src/commands/marketplace/search.ts\n * import { Args, Command, Flags } from '@oclif/core';\n * \n * export default class MarketplaceSearch extends Command {\n * static override description = 'Search marketplace apps';\n * static override args = {\n * query: Args.string({ description: 'Search query', required: true }),\n * };\n * async run() {\n * const { args } = await this.parse(MarketplaceSearch);\n * // ...\n * }\n * }\n * ```\n * \n * ## Migration from Commander.js\n * \n * The previous plugin model required `contributes.commands` in the manifest\n * and exported Commander.js `Command` instances. The new model uses oclif's\n * native plugin system for automatic command discovery and registration.\n * The `objectstack.config.ts` plugins array no longer determines CLI commands.\n */\n\n/**\n * Schema for a CLI Command Contribution declaration in the manifest.\n * \n * This declarative metadata describes CLI commands contributed by a plugin.\n * With the oclif migration, commands are auto-discovered from the plugin's\n * commands directory. This schema is retained for backward compatibility\n * and for describing command metadata in plugin manifests.\n */\nexport const CLICommandContributionSchema = z.object({\n /** \n * CLI command name. Must be a valid identifier: lowercase alphanumeric with hyphens.\n * This becomes a top-level subcommand of the `os` CLI.\n * \n * @example \"marketplace\"\n * @example \"deploy\"\n * @example \"cloud-sync\"\n */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n\n /** Brief description shown in `os --help` output. */\n description: z.string().optional().describe('Command description for help text'),\n\n /** \n * Module path that exports the oclif Command class(es).\n * Relative to the plugin package root. With oclif, this is typically\n * auto-discovered from the `commands` directory, but can be specified\n * for documentation or manifest purposes.\n * \n * @example \"./dist/commands/marketplace.js\"\n * @example \"./dist/commands\"\n */\n module: z.string().optional().describe('Module path exporting oclif Command classes'),\n});\n\n/**\n * Schema for oclif plugin configuration in package.json.\n * Validates the shape of the `oclif` section in a plugin's package.json.\n */\nexport const OclifPluginConfigSchema = z.object({\n /** Command discovery configuration */\n commands: z.object({\n /** Discovery strategy — typically \"pattern\" for file-based discovery */\n strategy: z.enum(['pattern', 'explicit', 'single']).optional()\n .describe('Command discovery strategy'),\n /** Directory path containing compiled command files */\n target: z.string().optional()\n .describe('Target directory for command files'),\n /** Glob pattern for matching command files */\n glob: z.string().optional()\n .describe('Glob pattern for command file matching'),\n }).optional().describe('Command discovery configuration'),\n\n /** Topic separator character (default: space) */\n topicSeparator: z.string().optional()\n .describe('Character separating topic and command names'),\n}).describe('oclif plugin configuration section');\n\n// ─── Types ───────────────────────────────────────────────────────────\n\nexport type CLICommandContribution = z.infer;\nexport type OclifPluginConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Package Artifact Format Protocol\n *\n * Defines the standard structure of a package artifact (.tgz) produced by\n * `os plugin build`. The marketplace uses these schemas to validate, store,\n * and distribute package artifacts.\n *\n * ## Artifact Internal Structure\n * ```\n * ├── manifest.json ← ManifestSchema serialized\n * ├── metadata/ ← 30+ metadata types (JSON)\n * │ ├── objects/ ← *.object.json\n * │ ├── views/ ← *.view.json\n * │ ├── pages/ ← *.page.json\n * │ ├── flows/ ← *.flow.json\n * │ ├── dashboards/ ← *.dashboard.json\n * │ ├── permissions/ ← *.permission.json\n * │ ├── agents/ ← *.agent.json\n * │ └── ... ← Other metadata types\n * ├── assets/ ← Static resources\n * │ ├── icon.svg\n * │ └── screenshots/\n * ├── data/ ← Seed data (DatasetSchema serialized)\n * ├── locales/ ← i18n translation files\n * ├── checksums.json ← SHA256 checksum per file\n * └── signature.sig ← RSA-SHA256 package signature\n * ```\n *\n * ## Architecture Alignment\n * - **Salesforce**: Managed Package .zip with metadata components\n * - **npm**: .tgz with package.json + contents\n * - **Helm**: Chart .tgz with Chart.yaml + templates\n * - **VS Code**: .vsix (zip) with extension manifest + assets\n */\n\n// ==========================================\n// Metadata Category Definitions\n// ==========================================\n\n/**\n * Supported metadata categories within an artifact.\n * Each category maps to a subdirectory under `metadata/`.\n */\nexport const MetadataCategoryEnum = z.enum([\n 'objects',\n 'views',\n 'pages',\n 'flows',\n 'dashboards',\n 'permissions',\n 'agents',\n 'reports',\n 'actions',\n 'translations',\n 'themes',\n 'datasets',\n 'apis',\n 'triggers',\n 'workflows',\n]).describe('Metadata category within the artifact');\n\nexport type MetadataCategory = z.infer;\n\n// ==========================================\n// Artifact File Entry\n// ==========================================\n\n/**\n * A single file entry within the artifact.\n */\nexport const ArtifactFileEntrySchema = z.object({\n /** Relative path within the artifact (e.g. \"metadata/objects/account.object.json\") */\n path: z.string().describe('Relative file path within the artifact'),\n\n /** File size in bytes */\n size: z.number().int().nonnegative().describe('File size in bytes'),\n\n /** Metadata category (if under metadata/) */\n category: MetadataCategoryEnum.optional()\n .describe('Metadata category this file belongs to'),\n}).describe('A single file entry within the artifact');\n\nexport type ArtifactFileEntry = z.infer;\n\n// ==========================================\n// Artifact Checksum\n// ==========================================\n\n/**\n * Checksum map for artifact integrity verification.\n * Maps relative file paths to their SHA256 hash values.\n *\n * @example\n * {\n * \"manifest.json\": \"a1b2c3...\",\n * \"metadata/objects/account.object.json\": \"d4e5f6...\"\n * }\n */\nexport const ArtifactChecksumSchema = z.object({\n /** Hash algorithm used (default: SHA256) */\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm used for checksums'),\n\n /** Map of relative file paths to their hash values */\n files: z.record(z.string(), z.string().regex(/^[a-f0-9]+$/))\n .describe('File path to hash value mapping'),\n}).describe('Checksum manifest for artifact integrity verification');\n\nexport type ArtifactChecksum = z.infer;\n\n// ==========================================\n// Artifact Signature\n// ==========================================\n\n/**\n * Digital signature for artifact authenticity verification.\n * Ensures the artifact was produced by a trusted publisher and has not been tampered with.\n */\nexport const ArtifactSignatureSchema = z.object({\n /** Signature algorithm */\n algorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).default('RSA-SHA256')\n .describe('Signing algorithm used'),\n\n /** Public key reference (URL or fingerprint) for verification */\n publicKeyRef: z.string()\n .describe('Public key reference (URL or fingerprint) for signature verification'),\n\n /** Base64-encoded signature value */\n signature: z.string()\n .describe('Base64-encoded digital signature'),\n\n /** Timestamp of when the artifact was signed */\n signedAt: z.string().datetime().optional()\n .describe('ISO 8601 timestamp of when the artifact was signed'),\n\n /** Signer identity (publisher ID or email) */\n signedBy: z.string().optional()\n .describe('Identity of the signer (publisher ID or email)'),\n}).describe('Digital signature for artifact authenticity verification');\n\nexport type ArtifactSignature = z.infer;\n\n// ==========================================\n// Package Artifact Schema\n// ==========================================\n\n/**\n * Package Artifact Schema\n *\n * Describes the complete structure and metadata of a built package artifact.\n * This schema is used to validate artifacts before upload to the marketplace.\n */\nexport const PackageArtifactSchema = z.object({\n /** Artifact format version (for forward compatibility) */\n formatVersion: z.string().regex(/^\\d+\\.\\d+$/).default('1.0')\n .describe('Artifact format version (e.g. \"1.0\")'),\n\n /** Package ID from the manifest */\n packageId: z.string().describe('Package identifier from manifest'),\n\n /** Package version from the manifest */\n version: z.string().describe('Package version from manifest'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format of the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().positive().optional()\n .describe('Total artifact file size in bytes'),\n\n /** Build timestamp */\n builtAt: z.string().datetime()\n .describe('ISO 8601 timestamp of when the artifact was built'),\n\n /** Build tool and version that produced this artifact */\n builtWith: z.string().optional()\n .describe('Build tool identifier (e.g. \"os-cli@3.2.0\")'),\n\n /** File listing within the artifact */\n files: z.array(ArtifactFileEntrySchema).optional()\n .describe('List of files contained in the artifact'),\n\n /** Metadata categories present in the artifact */\n metadataCategories: z.array(MetadataCategoryEnum).optional()\n .describe('Metadata categories included in this artifact'),\n\n /** Integrity checksums for all files */\n checksums: ArtifactChecksumSchema.optional()\n .describe('SHA256 checksums for artifact integrity verification'),\n\n /** Digital signature for authenticity */\n signature: ArtifactSignatureSchema.optional()\n .describe('Digital signature for artifact authenticity verification'),\n}).describe('Package artifact structure and metadata');\n\nexport type PackageArtifact = z.infer;\nexport type PackageArtifactInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PackageArtifactSchema, ArtifactChecksumSchema, ArtifactSignatureSchema } from './package-artifact.zod';\n\n/**\n * # CLI Plugin Commands Protocol\n *\n * Defines the input/output schemas for the `os plugin` CLI commands\n * that manage the package build → validate → publish lifecycle.\n *\n * ## Commands\n * ```\n * os plugin build — Build a .tgz artifact from the current project\n * os plugin validate — Validate an artifact's structure, checksums, and signature\n * os plugin publish — Upload an artifact to the marketplace\n * ```\n *\n * ## Architecture Alignment\n * - **npm**: `npm pack` → `npm publish`\n * - **Helm**: `helm package` → `helm push`\n * - **VS Code**: `vsce package` → `vsce publish`\n * - **Salesforce**: `sf package version create` → `sf package version promote`\n */\n\n// ==========================================\n// os plugin build\n// ==========================================\n\n/**\n * Options for the `os plugin build` command.\n * Reads the project manifest and produces a .tgz artifact.\n */\nexport const PluginBuildOptionsSchema = z.object({\n /** Project root directory (defaults to cwd) */\n directory: z.string().optional()\n .describe('Project root directory (defaults to current working directory)'),\n\n /** Output directory for the built artifact */\n outDir: z.string().optional()\n .describe('Output directory for the built artifact (defaults to ./dist)'),\n\n /** Archive format */\n format: z.enum(['tgz', 'zip']).default('tgz')\n .describe('Archive format for the artifact'),\n\n /** Whether to sign the artifact */\n sign: z.boolean().default(false)\n .describe('Whether to digitally sign the artifact'),\n\n /** Path to the private key for signing */\n privateKeyPath: z.string().optional()\n .describe('Path to RSA/ECDSA private key file for signing'),\n\n /** Signing algorithm */\n signAlgorithm: z.enum(['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512', 'ECDSA-SHA256']).optional()\n .describe('Signing algorithm to use'),\n\n /** Checksum algorithm */\n checksumAlgorithm: z.enum(['sha256', 'sha384', 'sha512']).default('sha256')\n .describe('Hash algorithm for file checksums'),\n\n /** Whether to include seed data */\n includeData: z.boolean().default(true)\n .describe('Whether to include seed data in the artifact'),\n\n /** Whether to include locale/translation files */\n includeLocales: z.boolean().default(true)\n .describe('Whether to include locale/translation files'),\n}).describe('Options for the os plugin build command');\n\nexport type PluginBuildOptions = z.infer;\n\n/**\n * Result of the `os plugin build` command.\n */\nexport const PluginBuildResultSchema = z.object({\n /** Whether the build succeeded */\n success: z.boolean().describe('Whether the build succeeded'),\n\n /** Path to the generated artifact file */\n artifactPath: z.string().optional()\n .describe('Absolute path to the generated artifact file'),\n\n /** Artifact metadata (validated against PackageArtifactSchema) */\n artifact: PackageArtifactSchema.optional()\n .describe('Artifact metadata'),\n\n /** Total file count in the artifact */\n fileCount: z.number().int().min(0).optional()\n .describe('Total number of files in the artifact'),\n\n /** Total artifact size in bytes */\n size: z.number().int().min(0).optional()\n .describe('Total artifact size in bytes'),\n\n /** Build duration in milliseconds */\n durationMs: z.number().optional()\n .describe('Build duration in milliseconds'),\n\n /** Error message if build failed */\n errorMessage: z.string().optional()\n .describe('Error message if build failed'),\n\n /** Warnings emitted during build */\n warnings: z.array(z.string()).optional()\n .describe('Warnings emitted during build'),\n}).describe('Result of the os plugin build command');\n\nexport type PluginBuildResult = z.infer;\n\n// ==========================================\n// os plugin validate\n// ==========================================\n\n/**\n * Validation severity levels.\n */\nexport const ValidationSeverityEnum = z.enum([\n 'error', // Must fix — artifact is invalid\n 'warning', // Should fix — may cause issues\n 'info', // Informational — suggestion\n]).describe('Validation issue severity');\n\n/**\n * A single validation finding.\n */\nexport const ValidationFindingSchema = z.object({\n /** Finding severity */\n severity: ValidationSeverityEnum.describe('Issue severity level'),\n\n /** Rule or check that produced this finding */\n rule: z.string().describe('Validation rule identifier'),\n\n /** Human-readable message */\n message: z.string().describe('Human-readable finding description'),\n\n /** File path within the artifact (if applicable) */\n path: z.string().optional()\n .describe('Relative file path within the artifact'),\n}).describe('A single validation finding');\n\nexport type ValidationFinding = z.infer;\n\n/**\n * Options for the `os plugin validate` command.\n */\nexport const PluginValidateOptionsSchema = z.object({\n /** Path to the .tgz artifact file to validate */\n artifactPath: z.string()\n .describe('Path to the artifact file to validate'),\n\n /** Whether to verify the digital signature */\n verifySignature: z.boolean().default(true)\n .describe('Whether to verify the digital signature'),\n\n /** Path to the public key for signature verification */\n publicKeyPath: z.string().optional()\n .describe('Path to the public key for signature verification'),\n\n /** Whether to verify SHA256 checksums of all files */\n verifyChecksums: z.boolean().default(true)\n .describe('Whether to verify checksums of all files'),\n\n /** Whether to validate metadata schema compliance */\n validateMetadata: z.boolean().default(true)\n .describe('Whether to validate metadata against schemas'),\n\n /** Target platform version for compatibility check */\n platformVersion: z.string().optional()\n .describe('Platform version for compatibility verification'),\n}).describe('Options for the os plugin validate command');\n\nexport type PluginValidateOptions = z.infer;\n\n/**\n * Result of the `os plugin validate` command.\n */\nexport const PluginValidateResultSchema = z.object({\n /** Whether the artifact is valid (no error-level findings) */\n valid: z.boolean().describe('Whether the artifact passed validation'),\n\n /** Artifact metadata extracted from the archive */\n artifact: PackageArtifactSchema.optional()\n .describe('Extracted artifact metadata'),\n\n /** Checksum verification result */\n checksumVerification: z.object({\n /** Whether all checksums match */\n passed: z.boolean().describe('Whether all checksums match'),\n /** Checksum details */\n checksums: ArtifactChecksumSchema.optional().describe('Verified checksums'),\n /** Files with mismatched checksums */\n mismatches: z.array(z.string()).optional()\n .describe('Files with checksum mismatches'),\n }).optional().describe('Checksum verification result'),\n\n /** Signature verification result */\n signatureVerification: z.object({\n /** Whether the signature is valid */\n passed: z.boolean().describe('Whether the signature is valid'),\n /** Signature details */\n signature: ArtifactSignatureSchema.optional().describe('Signature details'),\n /** Reason for failure */\n failureReason: z.string().optional().describe('Signature verification failure reason'),\n }).optional().describe('Signature verification result'),\n\n /** Platform compatibility result */\n platformCompatibility: z.object({\n /** Whether the artifact is compatible with the target platform */\n compatible: z.boolean().describe('Whether artifact is compatible'),\n /** Required platform version range */\n requiredRange: z.string().optional().describe('Required platform version range'),\n /** Target platform version checked against */\n targetVersion: z.string().optional().describe('Target platform version'),\n }).optional().describe('Platform compatibility check result'),\n\n /** All validation findings */\n findings: z.array(ValidationFindingSchema)\n .describe('All validation findings'),\n\n /** Counts by severity */\n summary: z.object({\n errors: z.number().int().min(0).describe('Error count'),\n warnings: z.number().int().min(0).describe('Warning count'),\n infos: z.number().int().min(0).describe('Info count'),\n }).optional().describe('Finding counts by severity'),\n}).describe('Result of the os plugin validate command');\n\nexport type PluginValidateResult = z.infer;\n\n// ==========================================\n// os plugin publish\n// ==========================================\n\n/**\n * Options for the `os plugin publish` command.\n */\nexport const PluginPublishOptionsSchema = z.object({\n /** Path to the .tgz artifact file to publish */\n artifactPath: z.string()\n .describe('Path to the artifact file to publish'),\n\n /** Marketplace API base URL */\n registryUrl: z.string().url().optional()\n .describe('Marketplace API base URL'),\n\n /** Authentication token for the marketplace API */\n token: z.string().optional()\n .describe('Authentication token for marketplace API'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional()\n .describe('Release notes for this version'),\n\n /** Whether this is a pre-release */\n preRelease: z.boolean().default(false)\n .describe('Whether this is a pre-release version'),\n\n /** Whether to skip validation before publishing */\n skipValidation: z.boolean().default(false)\n .describe('Whether to skip local validation before publish'),\n\n /** Access level for the published package */\n access: z.enum(['public', 'restricted']).default('public')\n .describe('Package access level on the marketplace'),\n\n /** Tags for categorization */\n tags: z.array(z.string()).optional()\n .describe('Tags for marketplace categorization'),\n}).describe('Options for the os plugin publish command');\n\nexport type PluginPublishOptions = z.infer;\n\n/**\n * Result of the `os plugin publish` command.\n */\nexport const PluginPublishResultSchema = z.object({\n /** Whether the publish succeeded */\n success: z.boolean().describe('Whether the publish succeeded'),\n\n /** Package ID that was published */\n packageId: z.string().optional()\n .describe('Published package identifier'),\n\n /** Version that was published */\n version: z.string().optional()\n .describe('Published version string'),\n\n /** Artifact reference in the marketplace */\n artifactUrl: z.string().url().optional()\n .describe('URL of the published artifact in the marketplace'),\n\n /** SHA256 checksum of the uploaded artifact */\n sha256: z.string().optional()\n .describe('SHA256 checksum of the uploaded artifact'),\n\n /** Submission ID for tracking the review process */\n submissionId: z.string().optional()\n .describe('Marketplace submission ID for review tracking'),\n\n /** Error message if publish failed */\n errorMessage: z.string().optional()\n .describe('Error message if publish failed'),\n\n /** Human-readable status message */\n message: z.string().optional()\n .describe('Human-readable status message'),\n}).describe('Result of the os plugin publish command');\n\nexport type PluginPublishResult = z.infer;\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type ValidationSeverity = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TenantQuotaSchema } from '../system/tenant.zod.js';\n\n/**\n * Runtime Mode Enum\n * Defines the operating mode of the kernel\n */\nexport const RuntimeMode = z.enum([\n 'development', // Hot-reload, verbose logging\n 'production', // Optimized, strict security\n 'test', // Mocked interfaces\n 'provisioning', // Setup/Migration mode\n 'preview', // Demo/preview mode — bypass auth, simulate admin identity\n]).describe('Kernel operating mode');\n\nexport type RuntimeMode = z.infer;\n\n/**\n * Preview Mode Configuration Schema\n *\n * Configures the kernel's preview/demo mode behaviour.\n * When `mode` is set to `'preview'`, the platform skips authentication\n * screens and optionally simulates an admin identity so that visitors\n * (e.g. app-marketplace customers) can explore the system without\n * registering or logging in.\n *\n * **Security note:** preview mode should NEVER be used in production.\n * The runtime must enforce this constraint.\n *\n * @example\n * ```ts\n * const ctx = KernelContextSchema.parse({\n * instanceId: '550e8400-e29b-41d4-a716-446655440000',\n * mode: 'preview',\n * version: '1.0.0',\n * cwd: '/app',\n * startTime: Date.now(),\n * previewMode: {\n * autoLogin: true,\n * simulatedRole: 'admin',\n * },\n * });\n * ```\n */\nexport const PreviewModeConfigSchema = z.object({\n /**\n * Automatically log in as a simulated user on startup.\n * When enabled, the frontend skips login/registration screens entirely.\n */\n autoLogin: z.boolean().default(true)\n .describe('Auto-login as simulated user, skipping login/registration pages'),\n\n /**\n * Role of the simulated user.\n * Determines the permission level of the auto-created preview session.\n */\n simulatedRole: z.enum(['admin', 'user', 'viewer']).default('admin')\n .describe('Permission role for the simulated preview user'),\n\n /**\n * Display name for the simulated user shown in the UI.\n */\n simulatedUserName: z.string().default('Preview User')\n .describe('Display name for the simulated preview user'),\n\n /**\n * Whether the preview session is read-only.\n * When true, all write operations (create, update, delete) are blocked.\n */\n readOnly: z.boolean().default(false)\n .describe('Restrict the preview session to read-only operations'),\n\n /**\n * Session duration in seconds. After expiry the preview session ends.\n * 0 means no expiration.\n */\n expiresInSeconds: z.number().int().min(0).default(0)\n .describe('Preview session duration in seconds (0 = no expiration)'),\n\n /**\n * Optional banner message shown in the UI to indicate preview mode.\n * Useful for marketplace demos so visitors know they are in a sandbox.\n */\n bannerMessage: z.string().optional()\n .describe('Banner message displayed in the UI during preview mode'),\n});\n\nexport type PreviewModeConfig = z.infer;\n\n/**\n * Kernel Context Schema\n * Defines the static environment information available to the Kernel at boot.\n */\nexport const KernelContextSchema = z.object({\n /**\n * Instance Identity\n */\n instanceId: z.string().uuid().describe('Unique UUID for this running kernel process'),\n \n /**\n * Environment Metadata\n */\n mode: RuntimeMode.default('production'),\n version: z.string().describe('Kernel version'),\n appName: z.string().optional().describe('Host application name'),\n \n /**\n * Paths\n */\n cwd: z.string().describe('Current working directory'),\n workspaceRoot: z.string().optional().describe('Workspace root if different from cwd'),\n \n /**\n * Telemetry\n */\n startTime: z.number().int().describe('Boot timestamp (ms)'),\n \n /**\n * Feature Flags (Global)\n */\n features: z.record(z.string(), z.boolean()).default({}).describe('Global feature toggles'),\n\n /**\n * Preview Mode Configuration.\n * Only relevant when `mode` is `'preview'`. Configures auto-login,\n * simulated identity, read-only restrictions, and UI banner.\n */\n previewMode: PreviewModeConfigSchema.optional()\n .describe('Preview/demo mode configuration (used when mode is \"preview\")'),\n});\n\nexport type KernelContext = z.infer;\n\n// ==========================================================================\n// Tenant Runtime Context\n// ==========================================================================\n\n/**\n * Tenant Runtime Context Schema.\n *\n * Extends the base KernelContext with tenant-specific information.\n * Constructed per-request from: session → org → tenant lookup.\n * Provides the tenant identity, plan, region, and database URL to all\n * downstream services during request processing.\n */\nexport const TenantRuntimeContextSchema = KernelContextSchema.extend({\n /** Unique tenant identifier resolved from the current session */\n tenantId: z.string().min(1).describe('Resolved tenant identifier'),\n\n /** Tenant subscription plan */\n tenantPlan: z.enum(['free', 'pro', 'enterprise']).describe('Tenant subscription plan'),\n\n /** Tenant deployment region */\n tenantRegion: z.string().optional().describe('Tenant deployment region'),\n\n /** Tenant database connection URL */\n tenantDbUrl: z.string().min(1).describe('Tenant database connection URL'),\n\n /** Optional tenant quotas for the current plan */\n tenantQuotas: TenantQuotaSchema.optional().describe('Tenant resource quotas'),\n}).describe('Tenant-aware kernel runtime context');\n\nexport type TenantRuntimeContext = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dependency Resolution Protocol\n *\n * Defines schemas for runtime dependency resolution when installing,\n * upgrading, or managing packages. Provides a standardized way to\n * express dependency conflicts, resolution results, and installation order.\n *\n * ## Architecture Alignment\n * - **npm**: Dependency tree resolution with conflict detection\n * - **Helm**: Dependency management with version constraints\n * - **Salesforce**: Package dependency validation at install time\n *\n * ## Resolution Flow\n * ```\n * 1. Parse manifest.dependencies (SemVer ranges)\n * 2. Check installed packages registry\n * 3. Resolve each dependency → satisfied | needs_install | needs_upgrade | conflict\n * 4. Detect circular dependencies\n * 5. Compute topological install order\n * 6. Return resolution result with required actions\n * ```\n */\n\n// ==========================================\n// Dependency Resolution Status\n// ==========================================\n\n/**\n * Resolution status for a single dependency.\n */\nexport const DependencyStatusEnum = z.enum([\n 'satisfied', // Already installed and version compatible\n 'needs_install', // Not installed, needs to be installed\n 'needs_upgrade', // Installed but version incompatible, needs upgrade\n 'conflict', // Conflicts with another package's dependency\n]).describe('Resolution status for a dependency');\n\nexport type DependencyStatus = z.infer;\n\n// ==========================================\n// Resolved Dependency\n// ==========================================\n\n/**\n * Single dependency resolution result.\n * Describes the state of one dependency after resolution.\n */\nexport const ResolvedDependencySchema = z.object({\n /** Package identifier of the dependency */\n packageId: z.string().describe('Dependency package identifier'),\n\n /** SemVer range required by the parent package */\n requiredRange: z.string().describe('SemVer range required (e.g. \"^2.0.0\")'),\n\n /** Actual version resolved (if available) */\n resolvedVersion: z.string().optional()\n .describe('Actual version resolved from registry'),\n\n /** Currently installed version (if any) */\n installedVersion: z.string().optional()\n .describe('Currently installed version'),\n\n /** Resolution status */\n status: DependencyStatusEnum.describe('Resolution status'),\n\n /** Conflict details (when status is \"conflict\") */\n conflictReason: z.string().optional()\n .describe('Explanation of the conflict'),\n}).describe('Resolution result for a single dependency');\n\nexport type ResolvedDependency = z.infer;\n\n// ==========================================\n// Required Action\n// ==========================================\n\n/**\n * An action required before installation can proceed.\n */\nexport const RequiredActionSchema = z.object({\n /** Type of action required */\n type: z.enum(['install', 'upgrade', 'confirm_conflict'])\n .describe('Type of action required'),\n\n /** Target package identifier */\n packageId: z.string().describe('Target package identifier'),\n\n /** Human-readable description of the action */\n description: z.string().describe('Human-readable action description'),\n}).describe('Action required before installation can proceed');\n\nexport type RequiredAction = z.infer;\n\n// ==========================================\n// Dependency Resolution Result\n// ==========================================\n\n/**\n * Complete dependency resolution result.\n * Aggregates all dependency statuses and computes installation feasibility.\n */\nexport const DependencyResolutionResultSchema = z.object({\n /** All dependencies and their resolution results */\n dependencies: z.array(ResolvedDependencySchema)\n .describe('Resolution result for each dependency'),\n\n /** Whether installation can proceed without conflicts */\n canProceed: z.boolean()\n .describe('Whether installation can proceed'),\n\n /** Actions that require user confirmation or system execution */\n requiredActions: z.array(RequiredActionSchema)\n .describe('Actions required before proceeding'),\n\n /** Topologically sorted package IDs for installation order */\n installOrder: z.array(z.string())\n .describe('Topologically sorted package IDs for installation'),\n\n /** Detected circular dependency chains */\n circularDependencies: z.array(z.array(z.string())).optional()\n .describe('Circular dependency chains detected (e.g. [[\"A\", \"B\", \"A\"]])'),\n}).describe('Complete dependency resolution result');\n\nexport type DependencyResolutionResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Dev Mode Plugin Protocol\n *\n * Defines the schema for a development-mode plugin that automatically enables\n * all platform services for local simulation. When loaded as a `devPlugin`,\n * the kernel bootstraps every subsystem (data, UI, API, auth, events, jobs, …)\n * using in-memory or stub implementations so that developers can exercise the\n * full stack without external dependencies.\n *\n * Design goals:\n * - Zero-config by default: `devPlugins: ['@objectstack/plugin-dev']`\n * - Every service can be overridden or disabled individually\n * - Preset profiles (minimal / standard / full) for common scenarios\n *\n * Inspired by:\n * - Spring Boot DevTools (auto-configuration)\n * - Next.js Dev Server (HMR + mock APIs)\n * - Vite Plugin Dev Mode (instant startup)\n */\n\n// ============================================================================\n// Dev Service Override\n// ============================================================================\n\n/**\n * Dev Service Override Schema\n *\n * Allows fine-grained control over a single service in development mode.\n * Each override targets a service by name and specifies whether it should\n * be enabled, which implementation strategy to use, and optional config.\n */\nexport const DevServiceOverrideSchema = z.object({\n /** Service identifier (e.g. 'auth', 'eventBus', 'fileStorage') */\n service: z.string().min(1).describe('Target service identifier'),\n\n /** Whether this service is enabled in dev mode */\n enabled: z.boolean().default(true).describe('Enable or disable this service'),\n\n /**\n * Implementation strategy for the service in dev mode.\n * - mock: Use a mock/stub that records calls (for assertions)\n * - memory: Use a real but in-memory implementation (e.g. SQLite, Map)\n * - stub: Use a static/no-op implementation\n * - passthrough: Use the real production implementation (for integration testing)\n */\n strategy: z.enum(['mock', 'memory', 'stub', 'passthrough']).default('memory')\n .describe('Implementation strategy for development'),\n\n /** Optional per-service configuration (strategy-specific) */\n config: z.record(z.string(), z.unknown()).optional()\n .describe('Strategy-specific configuration for this service override'),\n});\n\nexport type DevServiceOverride = z.infer;\n\n// ============================================================================\n// Dev Fixture Configuration\n// ============================================================================\n\n/**\n * Dev Fixture Config Schema\n *\n * Configures automatic seed/fixture data loading in development mode.\n * Fixtures provide a reproducible dataset for local development and demos.\n */\nexport const DevFixtureConfigSchema = z.object({\n /** Whether to load fixtures on startup */\n enabled: z.boolean().default(true).describe('Load fixture data on startup'),\n\n /**\n * Glob patterns pointing to fixture files\n * (e.g. `[\"./fixtures/*.json\", \"./test/data/*.yml\"]`)\n */\n paths: z.array(z.string()).optional()\n .describe('Glob patterns for fixture files'),\n\n /** Whether to reset data before loading fixtures */\n resetBeforeLoad: z.boolean().default(true)\n .describe('Clear existing data before loading fixtures'),\n\n /**\n * Environment tag filter – only load fixtures tagged for these environments.\n * When omitted, all fixtures are loaded.\n */\n envFilter: z.array(z.string()).optional()\n .describe('Only load fixtures matching these environment tags'),\n});\n\nexport type DevFixtureConfig = z.infer;\n\n// ============================================================================\n// Dev Tools Configuration\n// ============================================================================\n\n/**\n * Dev Tools Config Schema\n *\n * Optional developer tooling that can be enabled alongside the dev plugin.\n */\nexport const DevToolsConfigSchema = z.object({\n /** Enable hot-module replacement / live reload */\n hotReload: z.boolean().default(true).describe('Enable HMR / live-reload'),\n\n /** Enable request inspector UI for debugging HTTP traffic */\n requestInspector: z.boolean().default(false).describe('Enable request inspector'),\n\n /** Enable an in-browser database explorer */\n dbExplorer: z.boolean().default(false).describe('Enable database explorer UI'),\n\n /** Enable verbose logging across all services */\n verboseLogging: z.boolean().default(true).describe('Enable verbose logging'),\n\n /** Enable OpenAPI / Swagger documentation endpoint */\n apiDocs: z.boolean().default(true).describe('Serve OpenAPI docs at /_dev/docs'),\n\n /** Enable a mail catcher for outbound email (like MailHog) */\n mailCatcher: z.boolean().default(false).describe('Capture outbound emails in dev'),\n});\n\nexport type DevToolsConfig = z.infer;\n\n// ============================================================================\n// Dev Plugin Preset\n// ============================================================================\n\n/**\n * Dev Plugin Preset\n *\n * Predefined configuration profiles for common development scenarios.\n * - minimal: Only core data services (fast startup, low memory)\n * - standard: Core + API + auth + events (typical full-stack dev)\n * - full: Every service enabled, including background jobs and AI agents\n */\nexport const DevPluginPreset = z.enum([\n 'minimal',\n 'standard',\n 'full',\n]).describe('Predefined dev configuration profile');\n\nexport type DevPluginPreset = z.infer;\n\n// ============================================================================\n// Dev Plugin Configuration\n// ============================================================================\n\n/**\n * Dev Plugin Config Schema\n *\n * Top-level configuration for the development-mode plugin.\n * This is the shape of the configuration payload that\n * `@objectstack/plugin-dev` (or equivalent) understands.\n *\n * The outer wiring (e.g. how a stack declares `devPlugins`) is defined\n * by the stack/manifest schemas; this type only describes the plugin's\n * own config object.\n *\n * @example Minimal usage (zero-config)\n * ```ts\n * const devConfig: DevPluginConfig = {};\n * ```\n *\n * @example With preset\n * ```ts\n * const devConfig: DevPluginConfig = {\n * preset: 'full',\n * };\n * ```\n *\n * @example Fine-grained overrides\n * ```ts\n * const devConfig: DevPluginConfig = {\n * preset: 'standard',\n * services: {\n * auth: { enabled: true, strategy: 'mock' },\n * fileStorage: { enabled: false },\n * },\n * fixtures: { paths: ['./fixtures/*.json'] },\n * tools: { dbExplorer: true },\n * };\n * ```\n */\nexport const DevPluginConfigSchema = z.object({\n /**\n * Configuration preset.\n * When provided, services and tools are pre-configured for the selected\n * profile. Individual `services` and `tools` settings override the preset.\n * @default 'standard'\n */\n preset: DevPluginPreset.default('standard')\n .describe('Base configuration preset'),\n\n /**\n * Per-service overrides.\n * Keys are service names; values configure the dev strategy.\n * Only services explicitly listed here override the preset defaults.\n */\n services: z.record(\n z.string().min(1),\n DevServiceOverrideSchema.omit({ service: true }),\n ).optional().describe('Per-service dev overrides keyed by service name'),\n\n /** Fixture / seed data configuration */\n fixtures: DevFixtureConfigSchema.optional()\n .describe('Fixture data loading configuration'),\n\n /** Developer tooling configuration */\n tools: DevToolsConfigSchema.optional()\n .describe('Developer tooling settings'),\n\n /**\n * Port for the dev-tools UI dashboard.\n * Serves a lightweight web dashboard for inspecting services, events,\n * and request logs during development.\n * @default 4400\n */\n port: z.number().int().min(1).max(65535).default(4400)\n .describe('Port for the dev-tools dashboard'),\n\n /**\n * Auto-open the dev-tools dashboard in the default browser on startup.\n */\n open: z.boolean().default(false)\n .describe('Auto-open dev dashboard in browser'),\n\n /**\n * Seed a default admin user for development.\n * When enabled, the dev plugin creates a pre-authenticated admin user\n * so that developers can bypass login flows.\n */\n seedAdminUser: z.boolean().default(true)\n .describe('Create a default admin user for development'),\n\n /**\n * Simulated latency (ms) to add to service calls.\n * Helps developers build UIs that handle loading states correctly.\n * Set to 0 to disable.\n */\n simulatedLatency: z.number().int().min(0).default(0)\n .describe('Artificial latency (ms) added to service calls'),\n});\n\nexport type DevPluginConfig = z.infer;\nexport type DevPluginConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventNameSchema } from '../../shared/identifiers.zod';\n\n// ==========================================\n// Event Priority\n// ==========================================\n\n/**\n * Event Priority Enum\n * Priority levels for event processing\n * Lower numbers = higher priority\n */\nexport const EventPriority = z.enum([\n 'critical', // 0 - Process immediately, block if necessary\n 'high', // 1 - Process soon, minimal delay\n 'normal', // 2 - Default priority\n 'low', // 3 - Process when resources available\n 'background', // 4 - Process during idle time\n]);\n\nexport type EventPriority = z.infer;\n\n/**\n * Event Priority Values\n * Maps priority names to numeric values for sorting\n */\nexport const EVENT_PRIORITY_VALUES: Record = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n background: 4,\n};\n\n// ==========================================\n// Event Metadata\n// ==========================================\n\n/**\n * Event Metadata Schema\n * Metadata associated with every event\n */\nexport const EventMetadataSchema = z.object({\n source: z.string().describe('Event source (e.g., plugin name, system component)'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when event was created'),\n userId: z.string().optional().describe('User who triggered the event'),\n tenantId: z.string().optional().describe('Tenant identifier for multi-tenant systems'),\n correlationId: z.string().optional().describe('Correlation ID for event tracing'),\n causationId: z.string().optional().describe('ID of the event that caused this event'),\n priority: EventPriority.optional().default('normal').describe('Event priority'),\n});\n\n// ==========================================\n// Event Schema\n// ==========================================\n\n/**\n * Event Type Definition Schema\n * Defines the structure of an event type\n * \n * @example\n * {\n * \"name\": \"order.created\",\n * \"version\": \"1.0.0\",\n * \"schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"orderId\": { \"type\": \"string\" },\n * \"customerId\": { \"type\": \"string\" },\n * \"total\": { \"type\": \"number\" }\n * }\n * }\n * }\n */\nexport const EventTypeDefinitionSchema = z.object({\n name: EventNameSchema.describe('Event type name (lowercase with dots)'),\n version: z.string().default('1.0.0').describe('Event schema version'),\n schema: z.unknown().optional().describe('JSON Schema for event payload validation'),\n description: z.string().optional().describe('Event type description'),\n deprecated: z.boolean().optional().default(false).describe('Whether this event type is deprecated'),\n tags: z.array(z.string()).optional().describe('Event type tags'),\n});\n\nexport type EventTypeDefinition = z.infer;\n\n/**\n * Event Schema\n * Base schema for all events in the system\n * \n * Event names follow dot notation for namespacing (e.g., 'user.created', 'order.paid').\n * This aligns with industry standards for event-driven architectures and message queues.\n */\nexport const EventSchema = z.object({\n /**\n * Event identifier (for tracking and deduplication)\n */\n id: z.string().optional().describe('Unique event identifier'),\n \n /**\n * Event name\n */\n name: EventNameSchema.describe('Event name (lowercase with dots, e.g., user.created, order.paid)'),\n \n /**\n * Event payload\n */\n payload: z.unknown().describe('Event payload schema'),\n \n /**\n * Event metadata\n */\n metadata: EventMetadataSchema.describe('Event metadata'),\n});\n\nexport type Event = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Event Handlers\n// ==========================================\n\n/**\n * Event Handler Schema\n * Defines how to handle a specific event\n */\nexport const EventHandlerSchema = z.object({\n /**\n * Handler identifier\n */\n id: z.string().optional().describe('Unique handler identifier'),\n \n /**\n * Event name pattern\n */\n eventName: z.string().describe('Name of event to handle (supports wildcards like user.*)'),\n \n /**\n * Handler function\n */\n handler: z.unknown()\n .describe('Handler function'),\n \n /**\n * Execution priority\n */\n priority: z.number().int().default(0).describe('Execution priority (lower numbers execute first)'),\n \n /**\n * Async execution\n */\n async: z.boolean().default(true).describe('Execute in background (true) or block (false)'),\n \n /**\n * Retry configuration\n */\n retry: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),\n backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay'),\n backoffMultiplier: z.number().positive().default(2).describe('Backoff multiplier'),\n }).optional().describe('Retry policy for failed handlers'),\n \n /**\n * Timeout\n */\n timeoutMs: z.number().int().positive().optional().describe('Handler timeout in milliseconds'),\n \n /**\n * Filter function\n */\n filter: z.unknown()\n .optional()\n .describe('Optional filter to determine if handler should execute'),\n});\n\nexport type EventHandler = z.infer;\n\n/**\n * Event Route Schema\n * Routes events from one pattern to multiple targets with optional transformation\n */\nexport const EventRouteSchema = z.object({\n from: z.string().describe('Source event pattern (supports wildcards, e.g., user.* or *.created)'),\n to: z.array(z.string()).describe('Target event names to route to'),\n transform: z.unknown().optional().describe('Optional function to transform payload'),\n});\n\nexport type EventRoute = z.infer;\n\n/**\n * Event Persistence Schema\n * Configuration for persisting events to storage\n */\nexport const EventPersistenceSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable event persistence'),\n retention: z.number().int().positive().describe('Days to retain persisted events'),\n filter: z.unknown().optional().describe('Optional filter function to select which events to persist'),\n storage: z.enum(['database', 'file', 's3', 'custom']).default('database')\n .describe('Storage backend for persisted events'),\n});\n\nexport type EventPersistence = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Event Queue\n// ==========================================\n\n/**\n * Event Queue Configuration Schema\n * Configuration for async event processing queue\n * \n * @example\n * {\n * \"name\": \"event_queue\",\n * \"concurrency\": 10,\n * \"retryPolicy\": {\n * \"maxRetries\": 3,\n * \"backoffStrategy\": \"exponential\"\n * }\n * }\n */\nexport const EventQueueConfigSchema = z.object({\n /**\n * Queue name\n */\n name: z.string().default('events').describe('Event queue name'),\n \n /**\n * Concurrency\n */\n concurrency: z.number().int().min(1).default(10).describe('Max concurrent event handlers'),\n \n /**\n * Retry policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Max retries for failed events'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay'),\n }).optional().describe('Default retry policy for events'),\n \n /**\n * Dead letter queue\n */\n deadLetterQueue: z.string().optional().describe('Dead letter queue name for failed events'),\n \n /**\n * Enable priority processing\n */\n priorityEnabled: z.boolean().default(true).describe('Process events based on priority'),\n});\n\nexport type EventQueueConfig = z.infer;\n\n// ==========================================\n// Event Replay\n// ==========================================\n\n/**\n * Event Replay Configuration Schema\n * Configuration for replaying historical events\n * \n * @example\n * {\n * \"fromTimestamp\": \"2024-01-01T00:00:00Z\",\n * \"toTimestamp\": \"2024-01-31T23:59:59Z\",\n * \"eventTypes\": [\"order.created\", \"order.updated\"],\n * \"speed\": 10\n * }\n */\nexport const EventReplayConfigSchema = z.object({\n /**\n * Start timestamp\n */\n fromTimestamp: z.string().datetime().describe('Start timestamp for replay (ISO 8601)'),\n \n /**\n * End timestamp\n */\n toTimestamp: z.string().datetime().optional().describe('End timestamp for replay (ISO 8601)'),\n \n /**\n * Event types to replay\n */\n eventTypes: z.array(z.string()).optional().describe('Event types to replay (empty = all)'),\n \n /**\n * Event filters\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters for event selection'),\n \n /**\n * Replay speed multiplier\n */\n speed: z.number().positive().default(1).describe('Replay speed multiplier (1 = real-time)'),\n \n /**\n * Target handlers\n */\n targetHandlers: z.array(z.string()).optional().describe('Handler IDs to execute (empty = all)'),\n});\n\nexport type EventReplayConfig = z.infer;\n\n// ==========================================\n// Event Sourcing\n// ==========================================\n\n/**\n * Event Sourcing Configuration Schema\n * Configuration for event sourcing pattern\n * \n * Event sourcing stores all changes to application state as a sequence of events.\n * The current state can be reconstructed by replaying the events.\n * \n * @example\n * {\n * \"enabled\": true,\n * \"snapshotInterval\": 100,\n * \"retention\": 365\n * }\n */\nexport const EventSourcingConfigSchema = z.object({\n /**\n * Enable event sourcing\n */\n enabled: z.boolean().default(false).describe('Enable event sourcing'),\n \n /**\n * Snapshot interval\n */\n snapshotInterval: z.number().int().positive().default(100)\n .describe('Create snapshot every N events'),\n \n /**\n * Snapshot retention\n */\n snapshotRetention: z.number().int().positive().default(10)\n .describe('Number of snapshots to retain'),\n \n /**\n * Event retention\n */\n retention: z.number().int().positive().default(365)\n .describe('Days to retain events'),\n \n /**\n * Aggregate types\n */\n aggregateTypes: z.array(z.string()).optional()\n .describe('Aggregate types to enable event sourcing for'),\n \n /**\n * Storage configuration\n */\n storage: z.object({\n type: z.enum(['database', 'file', 's3', 'eventstore']).default('database')\n .describe('Storage backend'),\n options: z.record(z.string(), z.unknown()).optional().describe('Storage-specific options'),\n }).optional().describe('Event store configuration'),\n});\n\nexport type EventSourcingConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventSchema } from './core.zod';\n\n// ==========================================\n// Dead Letter Queue\n// ==========================================\n\n/**\n * Dead Letter Queue Entry Schema\n * Represents a failed event in the dead letter queue\n */\nexport const DeadLetterQueueEntrySchema = z.object({\n /**\n * Entry identifier\n */\n id: z.string().describe('Unique entry identifier'),\n \n /**\n * Original event\n */\n event: EventSchema.describe('Original event'),\n \n /**\n * Failure reason\n */\n error: z.object({\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Error stack trace'),\n code: z.string().optional().describe('Error code'),\n }).describe('Failure details'),\n \n /**\n * Retry count\n */\n retries: z.number().int().min(0).describe('Number of retry attempts'),\n \n /**\n * Timestamps\n */\n firstFailedAt: z.string().datetime().describe('When event first failed'),\n lastFailedAt: z.string().datetime().describe('When event last failed'),\n \n /**\n * Handler that failed\n */\n failedHandler: z.string().optional().describe('Handler ID that failed'),\n});\n\nexport type DeadLetterQueueEntry = z.infer;\n\n// ==========================================\n// Event Log\n// ==========================================\n\n/**\n * Event Log Entry Schema\n * Represents a logged event\n */\nexport const EventLogEntrySchema = z.object({\n /**\n * Log entry ID\n */\n id: z.string().describe('Unique log entry identifier'),\n \n /**\n * Event\n */\n event: EventSchema.describe('The event'),\n \n /**\n * Status\n */\n status: z.enum(['pending', 'processing', 'completed', 'failed']).describe('Processing status'),\n \n /**\n * Handlers executed\n */\n handlersExecuted: z.array(z.object({\n handlerId: z.string().describe('Handler identifier'),\n status: z.enum(['success', 'failed', 'timeout']).describe('Handler execution status'),\n durationMs: z.number().int().optional().describe('Execution duration'),\n error: z.string().optional().describe('Error message if failed'),\n })).optional().describe('Handlers that processed this event'),\n \n /**\n * Timestamps\n */\n receivedAt: z.string().datetime().describe('When event was received'),\n processedAt: z.string().datetime().optional().describe('When event was processed'),\n \n /**\n * Total duration\n */\n totalDurationMs: z.number().int().optional().describe('Total processing time'),\n});\n\nexport type EventLogEntry = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Webhook Integration\n// ==========================================\n\n/**\n * Event Webhook Configuration Schema\n * Configuration for sending events to webhooks\n * \n * @example\n * {\n * \"eventPattern\": \"order.*\",\n * \"url\": \"https://api.example.com/webhooks/orders\",\n * \"method\": \"POST\",\n * \"headers\": { \"Authorization\": \"Bearer token\" }\n * }\n */\nexport const EventWebhookConfigSchema = z.object({\n /**\n * Webhook identifier\n */\n id: z.string().optional().describe('Unique webhook identifier'),\n \n /**\n * Event pattern to match\n */\n eventPattern: z.string().describe('Event name pattern (supports wildcards)'),\n \n /**\n * Target URL\n */\n url: z.string().url().describe('Webhook endpoint URL'),\n \n /**\n * HTTP method\n */\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH']).default('POST').describe('HTTP method'),\n \n /**\n * Headers\n */\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n \n /**\n * Authentication\n */\n authentication: z.object({\n type: z.enum(['none', 'bearer', 'basic', 'api-key']).describe('Auth type'),\n credentials: z.record(z.string(), z.string()).optional().describe('Auth credentials'),\n }).optional().describe('Authentication configuration'),\n \n /**\n * Retry policy\n */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).default(3).describe('Max retry attempts'),\n backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),\n initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),\n maxDelayMs: z.number().int().positive().default(60000).describe('Max retry delay'),\n }).optional().describe('Retry policy'),\n \n /**\n * Timeout\n */\n timeoutMs: z.number().int().positive().default(30000).describe('Request timeout in milliseconds'),\n \n /**\n * Event transformation\n */\n transform: z.unknown()\n .optional()\n .describe('Transform event before sending'),\n \n /**\n * Enabled\n */\n enabled: z.boolean().default(true).describe('Whether webhook is enabled'),\n});\n\nexport type EventWebhookConfig = z.infer;\n\n// ==========================================\n// Message Queue Integration\n// ==========================================\n\n/**\n * Event Message Queue Configuration Schema\n * Configuration for publishing events to message queues\n * \n * @example\n * {\n * \"provider\": \"kafka\",\n * \"topic\": \"events\",\n * \"eventPattern\": \"*\",\n * \"partitionKey\": \"metadata.tenantId\"\n * }\n */\nexport const EventMessageQueueConfigSchema = z.object({\n /**\n * Provider\n */\n provider: z.enum(['kafka', 'rabbitmq', 'aws-sqs', 'redis-pubsub', 'google-pubsub', 'azure-service-bus'])\n .describe('Message queue provider'),\n \n /**\n * Topic/Queue name\n */\n topic: z.string().describe('Topic or queue name'),\n \n /**\n * Event pattern\n */\n eventPattern: z.string().default('*').describe('Event name pattern to publish (supports wildcards)'),\n \n /**\n * Partition key\n */\n partitionKey: z.string().optional().describe('JSON path for partition key (e.g., \"metadata.tenantId\")'),\n \n /**\n * Message format\n */\n format: z.enum(['json', 'avro', 'protobuf']).default('json').describe('Message serialization format'),\n \n /**\n * Include metadata\n */\n includeMetadata: z.boolean().default(true).describe('Include event metadata in message'),\n \n /**\n * Compression\n */\n compression: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression'),\n \n /**\n * Batch size\n */\n batchSize: z.number().int().min(1).default(1).describe('Batch size for publishing'),\n \n /**\n * Flush interval\n */\n flushIntervalMs: z.number().int().positive().default(1000).describe('Flush interval for batching'),\n});\n\nexport type EventMessageQueueConfig = z.infer;\n\n// ==========================================\n// Real-time Notifications\n// ==========================================\n\n/**\n * Real-time Notification Configuration Schema\n * Configuration for real-time event notifications via WebSocket/SSE\n * \n * @example\n * {\n * \"enabled\": true,\n * \"protocol\": \"websocket\",\n * \"eventPattern\": \"notification.*\",\n * \"userFilter\": true\n * }\n */\nexport const RealTimeNotificationConfigSchema = z.object({\n /**\n * Enable real-time notifications\n */\n enabled: z.boolean().default(true).describe('Enable real-time notifications'),\n \n /**\n * Protocol\n */\n protocol: z.enum(['websocket', 'sse', 'long-polling']).default('websocket')\n .describe('Real-time protocol'),\n \n /**\n * Event pattern\n */\n eventPattern: z.string().default('*').describe('Event pattern to broadcast'),\n \n /**\n * User-specific filtering\n */\n userFilter: z.boolean().default(true).describe('Filter events by user'),\n \n /**\n * Tenant-specific filtering\n */\n tenantFilter: z.boolean().default(true).describe('Filter events by tenant'),\n \n /**\n * Channels\n */\n channels: z.array(z.object({\n name: z.string().describe('Channel name'),\n eventPattern: z.string().describe('Event pattern for channel'),\n filter: z.unknown()\n .optional()\n .describe('Additional filter function'),\n })).optional().describe('Named channels for event broadcasting'),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n maxEventsPerSecond: z.number().int().positive().describe('Max events per second per client'),\n windowMs: z.number().int().positive().default(1000).describe('Rate limit window'),\n }).optional().describe('Rate limiting configuration'),\n});\n\nexport type RealTimeNotificationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventTypeDefinitionSchema } from './core.zod';\nimport { EventHandlerSchema, EventPersistenceSchema } from './handlers.zod';\nimport { EventQueueConfigSchema, EventSourcingConfigSchema } from './queue.zod';\nimport { EventWebhookConfigSchema, EventMessageQueueConfigSchema, RealTimeNotificationConfigSchema } from './integrations.zod';\n\n// ==========================================\n// Complete Event Bus Configuration\n// ==========================================\n\n/**\n * Event Bus Configuration Schema\n * Complete configuration for the event bus system\n * \n * @example\n * {\n * \"persistence\": { \"enabled\": true, \"retention\": 365 },\n * \"queue\": { \"concurrency\": 20 },\n * \"eventSourcing\": { \"enabled\": true },\n * \"webhooks\": [],\n * \"messageQueue\": { \"provider\": \"kafka\", \"topic\": \"events\" },\n * \"realtime\": { \"enabled\": true, \"protocol\": \"websocket\" }\n * }\n */\nexport const EventBusConfigSchema = z.object({\n /**\n * Event persistence\n */\n persistence: EventPersistenceSchema.optional().describe('Event persistence configuration'),\n \n /**\n * Event queue\n */\n queue: EventQueueConfigSchema.optional().describe('Event queue configuration'),\n \n /**\n * Event sourcing\n */\n eventSourcing: EventSourcingConfigSchema.optional().describe('Event sourcing configuration'),\n \n /**\n * Event replay\n */\n replay: z.object({\n enabled: z.boolean().default(true).describe('Enable event replay capability'),\n }).optional().describe('Event replay configuration'),\n \n /**\n * Webhooks\n */\n webhooks: z.array(EventWebhookConfigSchema).optional().describe('Webhook configurations'),\n \n /**\n * Message queue integration\n */\n messageQueue: EventMessageQueueConfigSchema.optional().describe('Message queue integration'),\n \n /**\n * Real-time notifications\n */\n realtime: RealTimeNotificationConfigSchema.optional().describe('Real-time notification configuration'),\n \n /**\n * Event type definitions\n */\n eventTypes: z.array(EventTypeDefinitionSchema).optional().describe('Event type definitions'),\n \n /**\n * Global handlers\n */\n handlers: z.array(EventHandlerSchema).optional().describe('Global event handlers'),\n});\n\nexport type EventBusConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Feature Rollout Strategy\n */\nexport const FeatureStrategy = z.enum([\n 'boolean', // Simple On/Off\n 'percentage', // Gradual rollout (0-100%)\n 'user_list', // Specific users\n 'group', // Specific groups/roles\n 'custom' // Custom constraint/script\n]);\n\n/**\n * Feature Flag Protocol\n * \n * Manages feature toggles and gradual rollouts.\n * Used for CI/CD, A/B Testing, and Trunk-Based Development.\n */\nexport const FeatureFlagSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Feature key (snake_case)'),\n label: z.string().optional().describe('Display label'),\n description: z.string().optional(),\n \n /** Default state */\n enabled: z.boolean().default(false).describe('Is globally enabled'),\n \n /** Rollout Strategy */\n strategy: FeatureStrategy.default('boolean'),\n \n /** Strategy Configuration */\n conditions: z.object({\n percentage: z.number().min(0).max(100).optional(),\n users: z.array(z.string()).optional(),\n groups: z.array(z.string()).optional(),\n expression: z.string().optional().describe('Custom formula expression')\n }).optional(),\n \n /** Integration */\n environment: z.enum(['dev', 'staging', 'prod', 'all']).default('all')\n .describe('Environment validity'),\n \n /** Expiration */\n expiresAt: z.string().datetime().optional().describe('Feature flag expiration date'),\n});\n\nexport const FeatureFlag = Object.assign(FeatureFlagSchema, {\n create: >(config: T) => config,\n});\n\nexport type FeatureFlag = z.infer;\nexport type FeatureFlagInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Capability Protocol\n * \n * Defines the standard way plugins declare their capabilities, implementations,\n * and conformance levels to ensure interoperability across vendors.\n * \n * Based on the Protocol-Oriented Architecture pattern similar to:\n * - Kubernetes CRDs (Custom Resource Definitions)\n * - OSGi Service Registry\n * - Eclipse Extension Points\n */\n\n/**\n * Capability Conformance Level\n * Indicates how completely a plugin implements a given protocol.\n */\nexport const CapabilityConformanceLevelSchema = z.enum([\n 'full', // Complete implementation of all protocol features\n 'partial', // Subset implementation with specific features listed\n 'experimental', // Unstable/preview implementation\n 'deprecated', // Still supported but scheduled for removal\n]).describe('Level of protocol conformance');\n\n/**\n * Protocol Version Schema\n * Uses semantic versioning to track protocol evolution.\n */\nexport const ProtocolVersionSchema = z.object({\n major: z.number().int().min(0),\n minor: z.number().int().min(0),\n patch: z.number().int().min(0),\n}).describe('Semantic version of the protocol');\n\n/**\n * Protocol Reference\n * Uniquely identifies a protocol/interface that a plugin can implement.\n * \n * Examples:\n * - com.objectstack.protocol.storage.v1\n * - com.objectstack.protocol.auth.oauth2.v2\n * - com.acme.protocol.payment.stripe.v1\n */\nexport const ProtocolReferenceSchema = z.object({\n /**\n * Protocol identifier using reverse domain notation.\n * Format: {domain}.protocol.{category}.{name}[.{subcategory}].v{major}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+protocol\\.[a-z][a-z0-9._]*\\.v\\d+$/)\n .describe('Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)'),\n \n /**\n * Human-readable protocol name\n */\n label: z.string(),\n \n /**\n * Protocol version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Detailed protocol specification URL or file reference\n */\n specification: z.string().optional().describe('URL or path to protocol specification'),\n \n /**\n * Brief description of what this protocol defines\n */\n description: z.string().optional(),\n});\n\n/**\n * Protocol Feature\n * Represents a specific capability within a protocol.\n */\nexport const ProtocolFeatureSchema = z.object({\n name: z.string().describe('Feature identifier within the protocol'),\n enabled: z.boolean().default(true),\n description: z.string().optional(),\n sinceVersion: z.string().optional().describe('Version when this feature was added'),\n deprecatedSince: z.string().optional().describe('Version when deprecated'),\n});\n\n/**\n * Plugin Capability Declaration\n * Documents what protocols a plugin implements and to what extent.\n */\nexport const PluginCapabilitySchema = z.object({\n /**\n * The protocol being implemented\n */\n protocol: ProtocolReferenceSchema,\n \n /**\n * Conformance level\n */\n conformance: CapabilityConformanceLevelSchema.default('full'),\n \n /**\n * Specific features implemented (required if conformance is 'partial')\n */\n implementedFeatures: z.array(z.string()).optional().describe('List of implemented feature names'),\n \n /**\n * Optional feature flags indicating advanced capabilities\n */\n features: z.array(ProtocolFeatureSchema).optional(),\n \n /**\n * Custom metadata for vendor-specific information\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Testing/Certification status\n */\n certified: z.boolean().default(false).describe('Has passed official conformance tests'),\n certificationDate: z.string().datetime().optional(),\n});\n\n/**\n * Plugin Interface Declaration\n * Defines the contract for services this plugin provides to other plugins.\n */\nexport const PluginInterfaceSchema = z.object({\n /**\n * Unique interface identifier\n * Format: {plugin-id}.interface.{name}\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+interface\\.[a-z][a-z0-9._]+$/)\n .describe('Unique interface identifier'),\n \n /**\n * Interface name\n */\n name: z.string(),\n \n /**\n * Description of what this interface provides\n */\n description: z.string().optional(),\n \n /**\n * Interface version\n */\n version: ProtocolVersionSchema,\n \n /**\n * Methods exposed by this interface\n */\n methods: z.array(z.object({\n name: z.string().describe('Method name'),\n description: z.string().optional(),\n parameters: z.array(z.object({\n name: z.string(),\n type: z.string().describe('Type notation (e.g., string, number, User)'),\n required: z.boolean().default(true),\n description: z.string().optional(),\n })).optional(),\n returnType: z.string().optional().describe('Return value type'),\n async: z.boolean().default(false).describe('Whether method returns a Promise'),\n })),\n \n /**\n * Events emitted by this interface\n */\n events: z.array(z.object({\n name: z.string().describe('Event name'),\n description: z.string().optional(),\n payload: z.string().optional().describe('Event payload type'),\n })).optional(),\n \n /**\n * Stability level\n */\n stability: z.enum(['stable', 'beta', 'alpha', 'experimental']).default('stable'),\n});\n\n/**\n * Plugin Dependency Declaration\n * Specifies what other plugins or capabilities this plugin requires.\n */\nexport const PluginDependencySchema = z.object({\n /**\n * Plugin ID using reverse domain notation\n */\n pluginId: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Required plugin identifier'),\n \n /**\n * Version constraint (supports semver ranges)\n * Examples: \"1.0.0\", \"^1.2.3\", \">=2.0.0 <3.0.0\"\n */\n version: z.string().describe('Semantic version constraint'),\n \n /**\n * Whether this dependency is optional\n */\n optional: z.boolean().default(false),\n \n /**\n * Reason for the dependency\n */\n reason: z.string().optional(),\n \n /**\n * Minimum required capabilities from the dependency\n */\n requiredCapabilities: z.array(z.string()).optional().describe('Protocol IDs the dependency must support'),\n});\n\n/**\n * Extension Point Declaration\n * Defines hooks where other plugins can extend this plugin's functionality.\n */\nexport const ExtensionPointSchema = z.object({\n /**\n * Extension point identifier\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+extension\\.[a-z][a-z0-9._]+$/)\n .describe('Unique extension point identifier'),\n \n /**\n * Extension point name\n */\n name: z.string(),\n \n /**\n * Description\n */\n description: z.string().optional(),\n \n /**\n * Type of extension point\n */\n type: z.enum([\n 'action', // Plugins can register executable actions\n 'hook', // Plugins can listen to lifecycle events\n 'widget', // Plugins can contribute UI widgets\n 'provider', // Plugins can provide data/services\n 'transformer', // Plugins can transform data\n 'validator', // Plugins can validate data\n 'decorator', // Plugins can enhance/wrap functionality\n ]),\n \n /**\n * Expected interface contract for extensions\n */\n contract: z.object({\n input: z.string().optional().describe('Input type/schema'),\n output: z.string().optional().describe('Output type/schema'),\n signature: z.string().optional().describe('Function signature if applicable'),\n }).optional(),\n \n /**\n * Cardinality\n */\n cardinality: z.enum(['single', 'multiple']).default('multiple')\n .describe('Whether multiple extensions can register to this point'),\n});\n\n/**\n * Complete Plugin Capability Manifest\n * This is included in the main plugin manifest to declare all capabilities.\n */\nexport const PluginCapabilityManifestSchema = z.object({\n /**\n * Protocols this plugin implements\n */\n implements: z.array(PluginCapabilitySchema).optional()\n .describe('List of protocols this plugin conforms to'),\n \n /**\n * Interfaces this plugin exposes to other plugins\n */\n provides: z.array(PluginInterfaceSchema).optional()\n .describe('Services/APIs this plugin offers to others'),\n \n /**\n * Dependencies on other plugins\n */\n requires: z.array(PluginDependencySchema).optional()\n .describe('Required plugins and their capabilities'),\n \n /**\n * Extension points this plugin defines\n */\n extensionPoints: z.array(ExtensionPointSchema).optional()\n .describe('Points where other plugins can extend this plugin'),\n \n /**\n * Extensions this plugin contributes to other plugins\n */\n extensions: z.array(z.object({\n targetPluginId: z.string().describe('Plugin ID being extended'),\n extensionPointId: z.string().describe('Extension point identifier'),\n implementation: z.string().describe('Path to implementation module'),\n priority: z.number().int().default(100).describe('Registration priority (lower = higher priority)'),\n })).optional().describe('Extensions contributed to other plugins'),\n});\n\n// Export types\nexport type CapabilityConformanceLevel = z.infer;\nexport type ProtocolVersion = z.infer;\nexport type ProtocolReference = z.infer;\nexport type ProtocolFeature = z.infer;\nexport type PluginCapability = z.infer;\nexport type PluginInterface = z.infer;\nexport type PluginDependency = z.infer;\nexport type ExtensionPoint = z.infer;\nexport type PluginCapabilityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Loading Protocol\n * \n * Defines the enhanced plugin loading mechanism for the microkernel architecture.\n * Inspired by industry best practices from:\n * - Kubernetes CRDs and Operators\n * - OSGi Dynamic Module System\n * - Eclipse Plugin Framework\n * - Webpack Module Federation\n * \n * This protocol enables:\n * - Lazy loading and code splitting\n * - Dynamic imports and parallel initialization\n * - Capability-based discovery\n * - Hot reload in development\n * - Advanced caching strategies\n */\n\n/**\n * Plugin Loading Strategy\n * Determines how and when a plugin is loaded into memory\n */\nexport const PluginLoadingStrategySchema = z.enum([\n 'eager', // Load immediately during bootstrap (critical plugins)\n 'lazy', // Load on first use (feature plugins)\n 'parallel', // Load in parallel with other plugins\n 'deferred', // Load after initial bootstrap complete\n 'on-demand', // Load only when explicitly requested\n]).describe('Plugin loading strategy');\n\n/**\n * Plugin Preloading Configuration\n * Configures preloading behavior for faster activation\n */\nexport const PluginPreloadConfigSchema = z.object({\n /**\n * Enable preloading for this plugin\n */\n enabled: z.boolean().default(false),\n \n /**\n * Preload priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Resources to preload\n */\n resources: z.array(z.enum([\n 'metadata', // Plugin manifest and metadata\n 'dependencies', // Plugin dependencies\n 'assets', // Static assets (icons, translations)\n 'code', // JavaScript code chunks\n 'services', // Service definitions\n ])).optional(),\n \n /**\n * Conditions for preloading\n */\n conditions: z.object({\n /**\n * Preload only on specific routes\n */\n routes: z.array(z.string()).optional(),\n \n /**\n * Preload only for specific user roles\n */\n roles: z.array(z.string()).optional(),\n \n /**\n * Preload based on device type\n */\n deviceType: z.array(z.enum(['desktop', 'mobile', 'tablet'])).optional(),\n \n /**\n * Network connection quality threshold\n */\n minNetworkSpeed: z.enum(['slow-2g', '2g', '3g', '4g']).optional(),\n }).optional(),\n}).describe('Plugin preloading configuration');\n\n/**\n * Plugin Code Splitting Configuration\n * Configures how plugin code is split for optimal loading\n */\nexport const PluginCodeSplittingSchema = z.object({\n /**\n * Enable code splitting for this plugin\n */\n enabled: z.boolean().default(true),\n \n /**\n * Split strategy\n */\n strategy: z.enum([\n 'route', // Split by UI routes\n 'feature', // Split by feature modules\n 'size', // Split by bundle size threshold\n 'custom', // Custom split points defined by plugin\n ]).default('feature'),\n \n /**\n * Chunk naming strategy\n */\n chunkNaming: z.enum(['hashed', 'named', 'sequential']).default('hashed'),\n \n /**\n * Maximum chunk size in KB\n */\n maxChunkSize: z.number().int().min(10).optional().describe('Max chunk size in KB'),\n \n /**\n * Shared dependencies optimization\n */\n sharedDependencies: z.object({\n enabled: z.boolean().default(true),\n /**\n * Minimum times a module must be shared before extraction\n */\n minChunks: z.number().int().min(1).default(2),\n }).optional(),\n}).describe('Plugin code splitting configuration');\n\n/**\n * Plugin Dynamic Import Configuration\n * Configures dynamic import behavior for runtime module loading\n */\nexport const PluginDynamicImportSchema = z.object({\n /**\n * Enable dynamic imports\n */\n enabled: z.boolean().default(true),\n \n /**\n * Import mode\n */\n mode: z.enum([\n 'async', // Asynchronous import (recommended)\n 'sync', // Synchronous import (blocking)\n 'eager', // Eager evaluation\n 'lazy', // Lazy evaluation\n ]).default('async'),\n \n /**\n * Prefetch strategy\n */\n prefetch: z.boolean().default(false).describe('Prefetch module in idle time'),\n \n /**\n * Preload strategy\n */\n preload: z.boolean().default(false).describe('Preload module in parallel with parent'),\n \n /**\n * Webpack magic comments support\n */\n webpackChunkName: z.string().optional().describe('Custom chunk name for webpack'),\n \n /**\n * Import timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000).describe('Dynamic import timeout (ms)'),\n \n /**\n * Retry configuration on import failure\n */\n retry: z.object({\n enabled: z.boolean().default(true),\n maxAttempts: z.number().int().min(1).max(10).default(3),\n backoffMs: z.number().int().min(0).default(1000).describe('Exponential backoff base delay'),\n }).optional(),\n}).describe('Plugin dynamic import configuration');\n\n/**\n * Plugin Initialization Configuration\n * Configures how plugin initialization is executed\n */\nexport const PluginInitializationSchema = z.object({\n /**\n * Initialization mode\n */\n mode: z.enum([\n 'sync', // Synchronous initialization\n 'async', // Asynchronous initialization\n 'parallel', // Parallel with other plugins\n 'sequential', // Must complete before next plugin\n ]).default('async'),\n \n /**\n * Initialization timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000),\n \n /**\n * Startup priority (lower = higher priority, earlier initialization)\n */\n priority: z.number().int().min(0).default(100),\n \n /**\n * Whether to continue bootstrap if this plugin fails\n */\n critical: z.boolean().default(false).describe('If true, kernel bootstrap fails if plugin fails'),\n \n /**\n * Retry configuration on initialization failure\n */\n retry: z.object({\n enabled: z.boolean().default(false),\n maxAttempts: z.number().int().min(1).max(5).default(3),\n backoffMs: z.number().int().min(0).default(1000),\n }).optional(),\n \n /**\n * Health check interval for monitoring\n */\n healthCheckInterval: z.number().int().min(0).optional().describe('Health check interval in ms (0 = disabled)'),\n}).describe('Plugin initialization configuration');\n\n/**\n * Plugin Dependency Resolution Configuration\n * Advanced dependency resolution using semantic versioning\n */\nexport const PluginDependencyResolutionSchema = z.object({\n /**\n * Dependency resolution strategy\n */\n strategy: z.enum([\n 'strict', // Exact version match required\n 'compatible', // Semver compatible versions (^)\n 'latest', // Always use latest compatible\n 'pinned', // Lock to specific version\n ]).default('compatible'),\n \n /**\n * Peer dependency handling\n */\n peerDependencies: z.object({\n /**\n * Whether to resolve peer dependencies\n */\n resolve: z.boolean().default(true),\n \n /**\n * Action on missing peer dependency\n */\n onMissing: z.enum(['error', 'warn', 'ignore']).default('warn'),\n \n /**\n * Action on peer version mismatch\n */\n onMismatch: z.enum(['error', 'warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Optional dependency handling\n */\n optionalDependencies: z.object({\n /**\n * Whether to attempt loading optional dependencies\n */\n load: z.boolean().default(true),\n \n /**\n * Action on optional dependency load failure\n */\n onFailure: z.enum(['warn', 'ignore']).default('warn'),\n }).optional(),\n \n /**\n * Conflict resolution\n */\n conflictResolution: z.enum([\n 'fail', // Fail on any version conflict\n 'latest', // Use latest version\n 'oldest', // Use oldest version\n 'manual', // Require manual resolution\n ]).default('latest'),\n \n /**\n * Circular dependency handling\n */\n circularDependencies: z.enum([\n 'error', // Throw error on circular dependency\n 'warn', // Warn but continue\n 'allow', // Allow circular dependencies\n ]).default('warn'),\n}).describe('Plugin dependency resolution configuration');\n\n/**\n * Plugin Hot Reload Configuration\n * Enables hot module replacement for development and production environments.\n * \n * Production mode adds safety features: health validation, rollback on failure,\n * connection draining, and concurrency control for zero-downtime reloads.\n */\nexport const PluginHotReloadSchema = z.object({\n /**\n * Enable hot reload\n */\n enabled: z.boolean().default(false),\n \n /**\n * Target environment for hot reload behavior\n */\n environment: z.enum([\n 'development', // Fast reload with relaxed safety (file watchers, no health validation)\n 'staging', // Production-like reload with validation but relaxed rollback\n 'production', // Full safety: health validation, rollback, connection draining\n ]).default('development').describe('Target environment controlling safety level'),\n \n /**\n * Hot reload strategy\n */\n strategy: z.enum([\n 'full', // Full plugin reload (destroy and reinitialize)\n 'partial', // Partial reload (update changed modules only)\n 'state-preserve', // Preserve plugin state during reload\n ]).default('full'),\n \n /**\n * Files to watch for changes\n */\n watchPatterns: z.array(z.string()).optional().describe('Glob patterns for files to watch'),\n \n /**\n * Files to ignore\n */\n ignorePatterns: z.array(z.string()).optional().describe('Glob patterns for files to ignore'),\n \n /**\n * Debounce delay in milliseconds\n */\n debounceMs: z.number().int().min(0).default(300),\n \n /**\n * Whether to preserve state during reload\n */\n preserveState: z.boolean().default(false),\n \n /**\n * State serialization\n */\n stateSerialization: z.object({\n enabled: z.boolean().default(false),\n /**\n * Path to state serialization handler\n */\n handler: z.string().optional(),\n }).optional(),\n \n /**\n * Hooks for hot reload lifecycle\n */\n hooks: z.object({\n beforeReload: z.string().optional().describe('Function to call before reload'),\n afterReload: z.string().optional().describe('Function to call after reload'),\n onError: z.string().optional().describe('Function to call on reload error'),\n }).optional(),\n \n /**\n * Production safety configuration\n * Applied when environment is 'staging' or 'production'\n */\n productionSafety: z.object({\n /**\n * Validate plugin health before completing reload\n */\n healthValidation: z.boolean().default(true)\n .describe('Run health checks after reload before accepting traffic'),\n \n /**\n * Automatically rollback to previous version on reload failure\n */\n rollbackOnFailure: z.boolean().default(true)\n .describe('Auto-rollback if reloaded plugin fails health check'),\n \n /**\n * Maximum time to wait for health validation after reload (ms)\n */\n healthTimeout: z.number().int().min(1000).default(30000)\n .describe('Health check timeout after reload in ms'),\n \n /**\n * Drain active connections before reload\n */\n drainConnections: z.boolean().default(true)\n .describe('Gracefully drain active requests before reloading'),\n \n /**\n * Maximum time to wait for connection draining (ms)\n */\n drainTimeout: z.number().int().min(0).default(15000)\n .describe('Max wait time for connection draining in ms'),\n \n /**\n * Maximum number of concurrent plugin reloads\n */\n maxConcurrentReloads: z.number().int().min(1).default(1)\n .describe('Limit concurrent reloads to prevent system instability'),\n \n /**\n * Minimum interval between reloads of the same plugin (ms)\n */\n minReloadInterval: z.number().int().min(1000).default(5000)\n .describe('Cooldown period between reloads of the same plugin'),\n }).optional(),\n}).describe('Plugin hot reload configuration');\n\n/**\n * Plugin Caching Configuration\n * Configures caching strategy for faster subsequent loads\n */\nexport const PluginCachingSchema = z.object({\n /**\n * Enable caching\n */\n enabled: z.boolean().default(true),\n \n /**\n * Cache storage type\n */\n storage: z.enum([\n 'memory', // In-memory cache (fastest, not persistent)\n 'disk', // Disk cache (persistent)\n 'indexeddb', // Browser IndexedDB (persistent, browser only)\n 'hybrid', // Memory + Disk hybrid\n ]).default('memory'),\n \n /**\n * Cache key strategy\n */\n keyStrategy: z.enum([\n 'version', // Cache by plugin version\n 'hash', // Cache by content hash\n 'timestamp', // Cache by last modified timestamp\n ]).default('version'),\n \n /**\n * Cache TTL in seconds\n */\n ttl: z.number().int().min(0).optional().describe('Time to live in seconds (0 = infinite)'),\n \n /**\n * Maximum cache size in MB\n */\n maxSize: z.number().int().min(1).optional().describe('Max cache size in MB'),\n \n /**\n * Cache invalidation triggers\n */\n invalidateOn: z.array(z.enum([\n 'version-change',\n 'dependency-change',\n 'manual',\n 'error',\n ])).optional(),\n \n /**\n * Compression\n */\n compression: z.object({\n enabled: z.boolean().default(false),\n algorithm: z.enum(['gzip', 'brotli', 'deflate']).default('gzip'),\n }).optional(),\n}).describe('Plugin caching configuration');\n\n/**\n * Plugin Sandboxing Configuration\n * Security isolation for plugins with configurable scope.\n * \n * Supports isolation beyond automation scripts: any plugin can be sandboxed\n * with process-level isolation and inter-plugin communication (IPC).\n */\nexport const PluginSandboxingSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(false),\n \n /**\n * Isolation scope - which plugins are subject to sandboxing\n */\n scope: z.enum([\n 'automation-only', // Sandbox automation/scripting plugins only (current behavior)\n 'untrusted-only', // Sandbox plugins below a trust threshold\n 'all-plugins', // Sandbox all plugins (maximum isolation)\n ]).default('automation-only').describe('Which plugins are subject to isolation'),\n \n /**\n * Sandbox isolation level\n */\n isolationLevel: z.enum([\n 'none', // No isolation\n 'process', // Separate process (Node.js worker threads)\n 'vm', // VM context isolation\n 'iframe', // iframe isolation (browser)\n 'web-worker', // Web Worker (browser)\n ]).default('none'),\n \n /**\n * Allowed capabilities\n */\n allowedCapabilities: z.array(z.string()).optional().describe('List of allowed capability IDs'),\n \n /**\n * Resource quotas\n */\n resourceQuotas: z.object({\n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(1).optional(),\n \n /**\n * Maximum CPU time in milliseconds\n */\n maxCpuTimeMs: z.number().int().min(100).optional(),\n \n /**\n * Maximum number of file descriptors\n */\n maxFileDescriptors: z.number().int().min(1).optional(),\n \n /**\n * Maximum network bandwidth in KB/s\n */\n maxNetworkKBps: z.number().int().min(1).optional(),\n }).optional(),\n \n /**\n * Permissions\n */\n permissions: z.object({\n /**\n * Allowed API access\n */\n allowedAPIs: z.array(z.string()).optional(),\n \n /**\n * Allowed file system paths\n */\n allowedPaths: z.array(z.string()).optional(),\n \n /**\n * Allowed network endpoints\n */\n allowedEndpoints: z.array(z.string()).optional(),\n \n /**\n * Allowed environment variables\n */\n allowedEnvVars: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Inter-Plugin Communication (IPC) configuration\n * Enables isolated plugins to communicate with the kernel and other plugins\n */\n ipc: z.object({\n /**\n * Enable IPC for sandboxed plugins\n */\n enabled: z.boolean().default(true)\n .describe('Allow sandboxed plugins to communicate via IPC'),\n \n /**\n * IPC transport mechanism\n */\n transport: z.enum([\n 'message-port', // MessagePort (worker threads / Web Workers)\n 'unix-socket', // Unix domain sockets (process isolation)\n 'tcp', // TCP sockets (container isolation)\n 'memory', // Shared memory channel (in-process VM)\n ]).default('message-port')\n .describe('IPC transport for cross-boundary communication'),\n \n /**\n * Maximum message size in bytes\n */\n maxMessageSize: z.number().int().min(1024).default(1048576)\n .describe('Maximum IPC message size in bytes (default 1MB)'),\n \n /**\n * Message timeout in milliseconds\n */\n timeout: z.number().int().min(100).default(30000)\n .describe('IPC message response timeout in ms'),\n \n /**\n * Allowed service calls through IPC\n */\n allowedServices: z.array(z.string()).optional()\n .describe('Service names the sandboxed plugin may invoke via IPC'),\n }).optional(),\n}).describe('Plugin sandboxing configuration');\n\n/**\n * Plugin Performance Monitoring Configuration\n * Telemetry and performance tracking\n */\nexport const PluginPerformanceMonitoringSchema = z.object({\n /**\n * Enable performance monitoring\n */\n enabled: z.boolean().default(false),\n \n /**\n * Metrics to collect\n */\n metrics: z.array(z.enum([\n 'load-time',\n 'init-time',\n 'memory-usage',\n 'cpu-usage',\n 'api-calls',\n 'error-rate',\n 'cache-hit-rate',\n ])).optional(),\n \n /**\n * Sampling rate (0-1, where 1 = 100%)\n */\n samplingRate: z.number().min(0).max(1).default(1),\n \n /**\n * Reporting interval in seconds\n */\n reportingInterval: z.number().int().min(1).default(60),\n \n /**\n * Performance budget thresholds\n */\n budgets: z.object({\n /**\n * Maximum load time in milliseconds\n */\n maxLoadTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum init time in milliseconds\n */\n maxInitTimeMs: z.number().int().min(0).optional(),\n \n /**\n * Maximum memory usage in MB\n */\n maxMemoryMB: z.number().int().min(0).optional(),\n }).optional(),\n \n /**\n * Action on budget violation\n */\n onBudgetViolation: z.enum(['warn', 'error', 'ignore']).default('warn'),\n}).describe('Plugin performance monitoring configuration');\n\n/**\n * Complete Plugin Loading Configuration\n * Combines all loading-related configurations\n */\nexport const PluginLoadingConfigSchema = z.object({\n /**\n * Loading strategy\n */\n strategy: PluginLoadingStrategySchema.default('lazy'),\n \n /**\n * Preloading configuration\n */\n preload: PluginPreloadConfigSchema.optional(),\n \n /**\n * Code splitting configuration\n */\n codeSplitting: PluginCodeSplittingSchema.optional(),\n \n /**\n * Dynamic import configuration\n */\n dynamicImport: PluginDynamicImportSchema.optional(),\n \n /**\n * Initialization configuration\n */\n initialization: PluginInitializationSchema.optional(),\n \n /**\n * Dependency resolution configuration\n */\n dependencyResolution: PluginDependencyResolutionSchema.optional(),\n \n /**\n * Hot reload configuration (development and production)\n */\n hotReload: PluginHotReloadSchema.optional(),\n \n /**\n * Caching configuration\n */\n caching: PluginCachingSchema.optional(),\n \n /**\n * Sandboxing configuration\n */\n sandboxing: PluginSandboxingSchema.optional(),\n \n /**\n * Performance monitoring\n */\n monitoring: PluginPerformanceMonitoringSchema.optional(),\n}).describe('Complete plugin loading configuration');\n\n/**\n * Plugin Loading Event\n * Emitted during plugin loading lifecycle\n */\nexport const PluginLoadingEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'load-started',\n 'load-completed',\n 'load-failed',\n 'init-started',\n 'init-completed',\n 'init-failed',\n 'preload-started',\n 'preload-completed',\n 'cache-hit',\n 'cache-miss',\n 'hot-reload',\n 'dynamic-load', // Plugin loaded at runtime\n 'dynamic-unload', // Plugin unloaded at runtime\n 'dynamic-discover', // Plugin discovered via registry\n ]),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Timestamp\n */\n timestamp: z.number().int().min(0),\n \n /**\n * Duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Error if event represents a failure\n */\n error: z.object({\n message: z.string(),\n code: z.string().optional(),\n stack: z.string().optional(),\n }).optional(),\n}).describe('Plugin loading lifecycle event');\n\n/**\n * Plugin Loading State\n * Tracks the current loading state of a plugin\n */\nexport const PluginLoadingStateSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current state\n */\n state: z.enum([\n 'pending', // Not yet loaded\n 'loading', // Currently loading\n 'loaded', // Code loaded, not initialized\n 'initializing', // Currently initializing\n 'ready', // Fully initialized and ready\n 'failed', // Failed to load or initialize\n 'reloading', // Hot reloading in progress\n 'unloading', // Being unloaded at runtime\n 'unloaded', // Successfully unloaded (dynamic loading)\n ]),\n \n /**\n * Load progress (0-100)\n */\n progress: z.number().min(0).max(100).default(0),\n \n /**\n * Loading start time\n */\n startedAt: z.number().int().min(0).optional(),\n \n /**\n * Loading completion time\n */\n completedAt: z.number().int().min(0).optional(),\n \n /**\n * Last error\n */\n lastError: z.string().optional(),\n \n /**\n * Retry count\n */\n retryCount: z.number().int().min(0).default(0),\n}).describe('Plugin loading state');\n\n// Export types\nexport type PluginLoadingStrategy = z.infer;\nexport type PluginPreloadConfig = z.infer;\nexport type PluginCodeSplitting = z.infer;\nexport type PluginDynamicImport = z.infer;\nexport type PluginInitialization = z.infer;\nexport type PluginDependencyResolution = z.infer;\nexport type PluginHotReload = z.infer;\nexport type PluginCaching = z.infer;\nexport type PluginSandboxing = z.infer;\nexport type PluginPerformanceMonitoring = z.infer;\nexport type PluginLoadingConfig = z.infer;\nexport type PluginLoadingEvent = z.infer;\nexport type PluginLoadingState = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// Service method interfaces use z.function() instead of z.any() for type safety.\n// Generic data fields use z.unknown() for type safety.\nexport const PluginContextSchema = z.object({\n ql: z.object({\n object: z.function().describe('Get object handle for method chaining'),\n query: z.function().describe('Execute a query'),\n }).passthrough().describe('ObjectQL Engine Interface'),\n\n os: z.object({\n getCurrentUser: z.function().describe('Get the current authenticated user'),\n getConfig: z.function().describe('Get platform configuration'),\n }).passthrough().describe('ObjectStack Kernel Interface'),\n\n logger: z.object({\n debug: z.function().describe('Log debug message'),\n info: z.function().describe('Log info message'),\n warn: z.function().describe('Log warning message'),\n error: z.function().describe('Log error message'),\n }).passthrough().describe('Logger Interface'),\n\n storage: z.object({\n get: z.function().describe('Get a value from storage'),\n set: z.function().describe('Set a value in storage'),\n delete: z.function().describe('Delete a value from storage'),\n }).passthrough().describe('Storage Interface'),\n\n i18n: z.object({\n t: z.function().describe('Translate a key'),\n getLocale: z.function().describe('Get current locale'),\n }).passthrough().describe('Internationalization Interface'),\n\n metadata: z.record(z.string(), z.unknown()),\n events: z.record(z.string(), z.unknown()),\n \n app: z.object({\n router: z.object({\n get: z.function().describe('Register GET route handler'),\n post: z.function().describe('Register POST route handler'),\n use: z.function().describe('Register middleware'),\n }).passthrough()\n }).passthrough().describe('App Framework Interface'),\n\n drivers: z.object({\n register: z.function().describe('Register a driver'),\n }).passthrough().describe('Driver Registry'),\n});\n\nexport type PluginContextData = z.infer;\nexport type PluginContext = PluginContextData;\n\n/**\n * Upgrade Context Schema\n *\n * Provides version migration context to the `onUpgrade` lifecycle hook.\n * Enables developers to write conditional migration logic based on\n * the previous and new versions.\n */\nexport const UpgradeContextSchema = z.object({\n /** Version before upgrade */\n previousVersion: z.string().describe('Version before upgrade'),\n\n /** Version after upgrade */\n newVersion: z.string().describe('Version after upgrade'),\n\n /** Whether this is a major version bump */\n isMajorUpgrade: z.boolean().describe('Whether this is a major version bump'),\n\n /** Metadata snapshot before upgrade (for migration logic) */\n previousMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Metadata snapshot before upgrade'),\n}).describe('Version migration context for onUpgrade hook');\n\nexport type UpgradeContext = z.infer;\n\nexport const PluginLifecycleSchema = z.object({\n onInstall: z.function().optional().describe('Called when plugin is installed'),\n \n onEnable: z.function().optional().describe('Called when plugin is enabled'),\n \n onDisable: z.function().optional().describe('Called when plugin is disabled'),\n \n onUninstall: z.function().optional().describe('Called when plugin is uninstalled'),\n \n onUpgrade: z.function().optional().describe('Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade'),\n});\n\nexport type PluginLifecycleHooks = z.infer;\n\n/**\n * Shared Plugin Types\n * These are the specialized plugin types common between Manifest (Package) and Plugin (Runtime).\n */\nexport const CORE_PLUGIN_TYPES = [\n 'ui', // Frontend: Serves static assets/SPA (e.g. Console, Studio)\n 'driver', // Connectivity: Database or Storage adapters (e.g. SQL, S3)\n 'server', // Protocol: HTTP/RPC Servers (e.g. Hono, GraphQL)\n 'app', // Business: Vertical Solution Bundle (Metadata + Logic)\n 'theme', // Appearance: UI Overrides & CSS Variables\n 'agent', // AI: Autonomous Agent & Tool Definitions\n 'objectql' // Core: ObjectQL Engine Data Provider\n] as const;\n\nexport const PluginSchema = PluginLifecycleSchema.extend({\n id: z.string().min(1).optional().describe('Unique Plugin ID (e.g. com.example.crm)'),\n type: z.enum([\n 'standard', // Default: General purpose backend logic (Service, Hook, etc.)\n ...CORE_PLUGIN_TYPES\n ]).default('standard').optional().describe('Plugin Type categorization for runtime behavior'),\n \n staticPath: z.string().optional().describe('Absolute path to static assets (Required for type=\"ui-plugin\")'),\n slug: z.string().regex(/^[a-z0-9-_]+$/).optional().describe('URL path segment (Required for type=\"ui-plugin\")'),\n default: z.boolean().optional().describe('Serve at root path (Only one \"ui-plugin\" can be default)'),\n \n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic Version'),\n description: z.string().optional(),\n author: z.string().optional(),\n homepage: z.string().url().optional(),\n});\n\nexport type PluginDefinition = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\nimport { PluginLoadingConfigSchema } from './plugin-loading.zod';\nimport { CORE_PLUGIN_TYPES } from './plugin.zod';\nimport { DatasetSchema } from '../data/dataset.zod';\n\n/**\n * Schema for the ObjectStack Manifest.\n * This defines the structure of a package configuration in the ObjectStack ecosystem.\n * All packages (apps, plugins, drivers, modules) must conform to this schema.\n * \n * @example App Package\n * ```yaml\n * id: com.acme.crm\n * version: 1.0.0\n * type: app\n * name: Acme CRM\n * description: Customer Relationship Management system\n * permissions:\n * - system.user.read\n * - system.object.create\n * objects:\n * - \"./src/objects/*.object.yml\"\n * ```\n */\nexport const ManifestSchema = z.object({\n /** \n * Unique package identifier using reverse domain notation.\n * Must be unique across the entire ecosystem.\n * \n * @example \"com.steedos.crm\"\n * @example \"org.apache.superset\"\n */\n id: z.string().describe('Unique package identifier (reverse domain style)'),\n \n /**\n * Short namespace identifier for metadata scoping.\n * Used as a prefix for objects and other metadata to prevent naming collisions\n * across packages from different vendors.\n * \n * Rules:\n * - 2-20 characters, lowercase letters, digits, and underscores only.\n * - Must be unique within a running instance.\n * - Platform-reserved namespaces (no prefix applied): \"base\", \"system\".\n * - FQN (Fully Qualified Name) = `{namespace}__{short_name}` (double underscore separator).\n * \n * @example \"crm\" → objects become crm__account, crm__deal\n * @example \"todo\" → objects become todo__task\n * @example \"base\" → objects keep short name (platform reserved)\n */\n namespace: z.string()\n .regex(/^[a-z][a-z0-9_]{1,19}$/, 'Namespace must be 2-20 chars, lowercase alphanumeric + underscore')\n .optional()\n .describe('Short namespace identifier for metadata scoping (e.g. \"crm\", \"todo\")'),\n \n /** \n * Package version following semantic versioning (major.minor.patch).\n * \n * @example \"1.0.0\"\n * @example \"2.1.0-beta.1\"\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Package version (semantic versioning)'),\n \n /** \n * Type of the package in the ObjectStack ecosystem.\n * - plugin: General-purpose functionality extension (Runtime: standard)\n * - app: Business application package\n * - driver: Connectivity adapter\n * - server: Protocol gateway (Hono, GraphQL)\n * - ui: Frontend package (Static/SPA)\n * - theme: UI Theme\n * - agent: AI Agent\n * - module: Reusable code library/shared module\n * - objectql: Core engine\n * - adapter: Host adapter (Express, Fastify)\n */\n type: z.enum([\n 'plugin', \n ...CORE_PLUGIN_TYPES,\n 'module', \n 'gateway', // Deprecated: use 'server'\n 'adapter'\n ]).describe('Type of package'),\n \n /** \n * Human-readable name of the package.\n * Displayed in the UI for users.\n * \n * @example \"Project Management\"\n */\n name: z.string().describe('Human-readable package name'),\n \n /** \n * Brief description of the package functionality.\n * Displayed in the marketplace and plugin manager.\n */\n description: z.string().optional().describe('Package description'),\n \n /** \n * Array of permission strings that the package requires.\n * These form the \"Scope\" requested by the package at installation.\n * \n * @example [\"system.user.read\", \"system.data.write\"]\n */\n permissions: z.array(z.string()).optional().describe('Array of required permission strings'),\n \n /** \n * Glob patterns specifying ObjectQL schemas files.\n * Matches `*.object.yml` or `*.object.ts` files to load business objects.\n * \n * @example [\"./src/objects/*.object.yml\"]\n */\n objects: z.array(z.string()).optional().describe('Glob patterns for ObjectQL schemas files'),\n\n /**\n * Defines system level DataSources.\n * Matches `*.datasource.yml` files.\n * \n * @example [\"./src/datasources/*.datasource.mongo.yml\"]\n */\n datasources: z.array(z.string()).optional().describe('Glob patterns for Datasource definitions'),\n\n /**\n * Package Dependencies.\n * Map of package IDs to version requirements.\n * \n * @example { \"@steedos/plugin-auth\": \"^2.0.0\" }\n */\n dependencies: z.record(z.string(), z.string()).optional().describe('Package dependencies'),\n\n /**\n * Plugin Configuration Schema.\n * Defines the settings this plugin exposes to the user via UI/ENV.\n * Uses a simplified JSON Schema format.\n * \n * @example\n * {\n * \"title\": \"Stripe Config\",\n * \"properties\": {\n * \"apiKey\": { \"type\": \"string\", \"secret\": true },\n * \"currency\": { \"type\": \"string\", \"default\": \"USD\" }\n * }\n * }\n */\n configuration: z.object({\n title: z.string().optional(),\n properties: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']).describe('Data type of the setting'),\n default: z.unknown().optional().describe('Default value'),\n description: z.string().optional().describe('Tooltip description'),\n required: z.boolean().optional().describe('Is this setting required?'),\n secret: z.boolean().optional().describe('If true, value is encrypted/masked (e.g. API Keys)'),\n enum: z.array(z.string()).optional().describe('Allowed values for select inputs'),\n })).describe('Map of configuration keys to their definitions')\n }).optional().describe('Plugin configuration settings'),\n\n /**\n * Contribution Points (VS Code Style).\n * formalized way to extend the platform capabilities.\n */\n contributes: z.object({\n /**\n * Register new Metadata Kinds (CRDs).\n * Enables the system to parse and validate new file types.\n * Example: Registering a BI plugin to handle *.report.ts\n */\n kinds: z.array(z.object({\n id: z.string().describe('The generic identifier of the kind (e.g., \"sys.bi.report\")'),\n globs: z.array(z.string()).describe('File patterns to watch (e.g., [\"**/*.report.ts\"])'),\n description: z.string().optional().describe('Description of what this kind represents'),\n })).optional().describe('New Metadata Types to recognize'),\n\n /**\n * Register System Hooks.\n * Declares that this plugin listens to specific system events.\n */\n events: z.array(z.string()).optional().describe('Events this plugin listens to'),\n\n /**\n * Register UI Menus.\n */\n menus: z.record(z.string(), z.array(z.object({\n id: z.string(),\n label: z.string(),\n command: z.string().optional(),\n }))).optional().describe('UI Menu contributions'),\n\n /**\n * Register Custom Themes.\n */\n themes: z.array(z.object({\n id: z.string(),\n label: z.string(),\n path: z.string(),\n })).optional().describe('Theme contributions'),\n\n /**\n * Register Translations.\n * Path to translation files (e.g. \"locales/en.json\").\n */\n translations: z.array(z.object({\n locale: z.string(),\n path: z.string(),\n })).optional().describe('Translation resources'),\n\n /**\n * Register Server Actions.\n * Invocable functions exposed to Flows or API.\n */\n actions: z.array(z.object({\n name: z.string().describe('Unique action name'),\n label: z.string().optional(),\n description: z.string().optional(),\n input: z.unknown().optional().describe('Input validation schema'),\n output: z.unknown().optional().describe('Output schema'),\n })).optional().describe('Exposed server actions'),\n\n /**\n * Register Storage Drivers.\n * Enables connecting to new types of datasources.\n */\n drivers: z.array(z.object({\n id: z.string().describe('Driver unique identifier (e.g. \"postgres\", \"mongo\")'),\n label: z.string().describe('Human readable name'),\n description: z.string().optional(),\n })).optional().describe('Driver contributions'),\n\n /**\n * Register Custom Field Types.\n * Extends the data model with new widget types.\n */\n fieldTypes: z.array(z.object({\n name: z.string().describe('Unique field type name (e.g. \"vector\")'),\n label: z.string().describe('Display label'),\n description: z.string().optional(),\n })).optional().describe('Field Type contributions'),\n \n /**\n * Register Custom Query Operators/Functions.\n * Extends ObjectQL with new functions (e.g. distance()).\n */\n functions: z.array(z.object({\n name: z.string().describe('Function name (e.g. \"distance\")'),\n description: z.string().optional(),\n args: z.array(z.string()).optional().describe('Argument types'),\n returnType: z.string().optional(),\n })).optional().describe('Query Function contributions'),\n\n /**\n * Register API Route Namespaces.\n * Declares the API endpoints this plugin provides to the HttpDispatcher.\n * The kernel routes matching prefixes to this plugin's handler.\n * \n * @example\n * routes: [\n * { prefix: '/api/v1/ai', service: 'ai', methods: ['aiNlq', 'aiChat'] }\n * ]\n */\n routes: z.array(z.object({\n /** URL path prefix (e.g. \"/api/v1/ai\") */\n prefix: z.string().regex(/^\\//).describe('API path prefix'),\n /** Service name this plugin provides */\n service: z.string().describe('Service name this plugin provides'),\n /** Protocol method names implemented */\n methods: z.array(z.string()).optional()\n .describe('Protocol method names implemented (e.g. [\"aiNlq\", \"aiChat\"])'),\n })).optional().describe('API route contributions to HttpDispatcher'),\n\n /**\n * Register CLI Commands.\n * Allows plugins to extend the ObjectStack CLI with custom commands.\n * Each command entry declares metadata; the actual Commander.js command\n * is resolved at runtime by importing the plugin's module.\n * \n * The plugin package must export a `commands` array of Commander.js `Command` instances\n * from its main entry point or from the path specified in `module`.\n * \n * @example\n * ```yaml\n * commands:\n * - name: marketplace\n * description: \"Manage marketplace apps\"\n * module: \"./cli\" # optional, defaults to package main\n * - name: deploy\n * description: \"Deploy to cloud\"\n * ```\n */\n commands: z.array(z.object({\n /** CLI command name (e.g., \"marketplace\", \"deploy\"). Must be a valid CLI identifier. */\n name: z.string()\n .regex(/^[a-z][a-z0-9-]*$/, 'Command name must be lowercase alphanumeric with hyphens')\n .describe('CLI command name'),\n /** Brief description shown in `os --help` */\n description: z.string().optional().describe('Command description for help text'),\n /** \n * Optional module path (relative to package root) that exports the Commander.js commands.\n * If omitted, the CLI will import from the package's main entry point.\n * The module must export a `commands` array of Commander.js `Command` instances,\n * or a single `Command` instance as default export.\n */\n module: z.string().optional().describe('Module path exporting Commander.js commands'),\n })).optional().describe('CLI command contributions'),\n }).optional().describe('Platform contributions'),\n\n /** \n * Initial data seeding configuration.\n * Defines default records to be inserted when the package is installed.\n * \n * Uses the standard DatasetSchema which supports idempotent upsert via\n * `externalId`, environment scoping via `env`, and multiple conflict\n * resolution modes.\n * \n * @deprecated Prefer using the top-level `data` field on the Stack Definition\n * (defineStack({ data: [...] })) for better visibility and metadata registration.\n * This field is retained for backward compatibility with manifest-only packages.\n */\n data: z.array(DatasetSchema).optional().describe('Initial seed data (prefer top-level data field)'),\n\n /**\n * Plugin Capability Manifest.\n * Declares protocols implemented, interfaces provided, dependencies, and extension points.\n * This enables plugin interoperability and automatic discovery.\n */\n capabilities: PluginCapabilityManifestSchema.optional()\n .describe('Plugin capability declarations for interoperability'),\n\n /** \n * Extension points contributed by this package.\n * Allows packages to extend UI components, add functionality, etc.\n */\n extensions: z.record(z.string(), z.unknown()).optional().describe('Extension points and contributions'),\n\n /**\n * Plugin Loading Configuration.\n * Configures how the plugin is loaded, initialized, and managed at runtime.\n * Includes strategies for lazy loading, code splitting, caching, and hot reload.\n */\n loading: PluginLoadingConfigSchema.optional()\n .describe('Plugin loading and runtime behavior configuration'),\n\n /**\n * Platform Compatibility Requirements.\n * Specifies the minimum ObjectStack platform version required to run this package.\n * Used at install time to prevent incompatible packages from being installed.\n *\n * @example\n * ```yaml\n * engine:\n * objectstack: \">=3.0.0\"\n * ```\n */\n engine: z.object({\n /** ObjectStack platform version requirement (SemVer range) */\n objectstack: z.string()\n .regex(/^[><=~^]*\\d+\\.\\d+\\.\\d+/)\n .describe('ObjectStack platform version requirement (SemVer range, e.g. \">=3.0.0\")'),\n }).optional().describe('Platform compatibility requirements'),\n});\n\n/**\n * TypeScript type inferred from the ManifestSchema.\n * Use this type for type-safe manifest handling in TypeScript code.\n */\nexport type ObjectStackManifest = z.infer;\nexport type ObjectStackManifestInput = z.input;\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Customization Layer Protocol\n * \n * Defines the overlay system for managing user customizations on top of\n * package-delivered metadata. This protocol solves the critical challenge\n * of separating \"vendor-managed\" metadata from \"customer-customized\" metadata,\n * enabling safe package upgrades without losing user changes.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed vs Unmanaged metadata components\n * - **ServiceNow**: Update Sets with collision detection\n * - **WordPress**: Parent/child theme overlay model\n * - **Kubernetes**: Strategic merge patch for resource customization\n * \n * ## Three-Layer Model\n * ```\n * ┌─────────────────────────────────┐\n * │ User Layer (scope: user) │ ← Personal overrides (per-user)\n * ├─────────────────────────────────┤\n * │ Platform Layer (scope: platform)│ ← Admin customizations (per-tenant)\n * ├─────────────────────────────────┤\n * │ System Layer (scope: system) │ ← Package-delivered metadata (read-only)\n * └─────────────────────────────────┘\n * ```\n * \n * ## Merge Resolution Order\n * Effective metadata = System ← merge(Platform) ← merge(User)\n * Each layer only stores the delta (changed fields), not the full definition.\n */\n\n// ==========================================\n// Customization Tracking\n// ==========================================\n\n/**\n * Customization Origin\n * Identifies who created the customization.\n */\nexport const CustomizationOriginSchema = z.enum([\n 'package', // Delivered by a plugin package (system layer, read-only)\n 'admin', // Created/modified by platform admin via UI\n 'user', // Created/modified by end user via UI\n 'migration', // Created during data migration\n 'api', // Created via API\n]);\n\n/**\n * Field-Level Change Tracking\n * Records exactly which fields were modified by the customer.\n */\nexport const FieldChangeSchema = z.object({\n /** JSON path to the changed field (e.g. \"fields.status.label\") */\n path: z.string().describe('JSON path to the changed field'),\n\n /** Original value from the package (for diff/rollback) */\n originalValue: z.unknown().optional().describe('Original value from the package'),\n\n /** Current customized value */\n currentValue: z.unknown().describe('Current customized value'),\n\n /** Who made this change */\n changedBy: z.string().optional().describe('User or admin who made this change'),\n\n /** When this change was made */\n changedAt: z.string().datetime().optional().describe('Timestamp of the change'),\n});\n\n/**\n * Metadata Overlay Schema\n * \n * Represents a customization layer on top of package-delivered metadata.\n * Each overlay stores only the delta (changed fields) relative to the base definition.\n * \n * During package upgrades, the system performs a 3-way merge:\n * 1. Old package version (base)\n * 2. New package version (theirs)\n * 3. Customer customizations (ours)\n * \n * @example\n * ```yaml\n * # Package delivers: object \"crm__account\" with field \"status\" label \"Status\"\n * # Admin changes label to \"Account Status\"\n * # Overlay record:\n * baseType: object\n * baseName: crm__account\n * packageId: com.acme.crm\n * packageVersion: \"1.0.0\"\n * changes:\n * - path: \"fields.status.label\"\n * originalValue: \"Status\"\n * currentValue: \"Account Status\"\n * ```\n */\nexport const MetadataOverlaySchema = z.object({\n /** Primary key */\n id: z.string().describe('Overlay record ID (UUID)'),\n\n /** The metadata type being customized (e.g. \"object\", \"view\", \"flow\") */\n baseType: z.string().describe('Metadata type being customized'),\n\n /** The metadata name being customized (e.g. \"crm__account\") */\n baseName: z.string().describe('Metadata name being customized'),\n\n /** Package that owns the base metadata (null for platform-created metadata) */\n packageId: z.string().optional().describe('Package ID that delivered the base metadata'),\n\n /** Package version when the customization was made (for upgrade diffing) */\n packageVersion: z.string().optional().describe('Package version when overlay was created'),\n\n /** Customization scope */\n scope: z.enum(['platform', 'user']).default('platform')\n .describe('Customization scope (platform=admin, user=personal)'),\n\n /** Tenant ID for multi-tenant isolation */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Owner user ID (for user-scope overlays) */\n owner: z.string().optional().describe('Owner user ID for user-scope overlays'),\n\n /**\n * The overlay payload.\n * Contains only the changed fields, using JSON Merge Patch semantics (RFC 7396).\n * - To modify a field: include the field with its new value\n * - To delete a field: set its value to null\n * - Omitted fields remain unchanged from base\n */\n patch: z.record(z.string(), z.unknown()).describe('JSON Merge Patch payload (changed fields only)'),\n\n /**\n * Detailed change tracking for each modified field.\n * Enables field-level conflict detection during upgrades.\n */\n changes: z.array(FieldChangeSchema).optional()\n .describe('Field-level change tracking for conflict detection'),\n\n /** Whether this overlay is currently active */\n active: z.boolean().default(true).describe('Whether this overlay is active'),\n\n /** Audit timestamps */\n createdAt: z.string().datetime().optional(),\n createdBy: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n updatedBy: z.string().optional(),\n});\n\n// ==========================================\n// Merge & Conflict Resolution\n// ==========================================\n\n/**\n * Merge Conflict\n * Represents a conflict between package update and customer customization.\n */\nexport const MergeConflictSchema = z.object({\n /** JSON path to the conflicting field */\n path: z.string().describe('JSON path to the conflicting field'),\n\n /** Value in the old package version */\n baseValue: z.unknown().describe('Value in the old package version'),\n\n /** Value in the new package version */\n incomingValue: z.unknown().describe('Value in the new package version'),\n\n /** Customer's customized value */\n customValue: z.unknown().describe('Customer customized value'),\n\n /** Suggested resolution strategy */\n suggestedResolution: z.enum([\n 'keep-custom', // Keep customer's customization\n 'accept-incoming', // Accept package update\n 'manual', // Requires manual resolution\n ]).describe('Suggested resolution strategy'),\n\n /** Reason for the suggested resolution */\n reason: z.string().optional().describe('Explanation for the suggested resolution'),\n});\n\n/**\n * Merge Strategy Configuration\n * Controls how metadata merging behaves during package upgrades.\n */\nexport const MergeStrategyConfigSchema = z.object({\n /** Default strategy when no field-level rule matches */\n defaultStrategy: z.enum([\n 'keep-custom', // Preserve all customer customizations (safe)\n 'accept-incoming', // Accept all package updates (overwrite)\n 'three-way-merge', // Intelligent 3-way merge with conflict detection\n ]).default('three-way-merge').describe('Default merge strategy'),\n\n /** \n * Field paths that should always accept incoming package updates.\n * Use for fields that the package vendor considers \"owned\" and should not be customized.\n * @example [\"fields.*.type\", \"triggers.*\"]\n */\n alwaysAcceptIncoming: z.array(z.string()).optional()\n .describe('Field paths that always accept package updates'),\n\n /**\n * Field paths where customer customizations always win.\n * Use for UI-facing fields like labels, descriptions, help text.\n * @example [\"fields.*.label\", \"fields.*.helpText\", \"description\"]\n */\n alwaysKeepCustom: z.array(z.string()).optional()\n .describe('Field paths where customer customizations always win'),\n\n /** Whether to automatically resolve non-conflicting changes */\n autoResolveNonConflicting: z.boolean().default(true)\n .describe('Auto-resolve changes that do not conflict'),\n});\n\n/**\n * Merge Result\n * Result of a 3-way merge operation during package upgrade.\n */\nexport const MergeResultSchema = z.object({\n /** Whether the merge completed successfully (no unresolved conflicts) */\n success: z.boolean().describe('Whether merge completed without unresolved conflicts'),\n\n /** The merged metadata payload */\n mergedMetadata: z.record(z.string(), z.unknown()).optional()\n .describe('Merged metadata result'),\n\n /** Updated overlay with remaining customizations */\n updatedOverlay: z.record(z.string(), z.unknown()).optional()\n .describe('Updated overlay after merge'),\n\n /** List of conflicts that require manual resolution */\n conflicts: z.array(MergeConflictSchema).optional()\n .describe('Unresolved merge conflicts'),\n\n /** Summary of automatically resolved changes */\n autoResolved: z.array(z.object({\n path: z.string(),\n resolution: z.string(),\n description: z.string().optional(),\n })).optional().describe('Summary of auto-resolved changes'),\n\n /** Statistics */\n stats: z.object({\n totalFields: z.number().int().min(0).describe('Total fields evaluated'),\n unchanged: z.number().int().min(0).describe('Fields with no changes'),\n autoResolved: z.number().int().min(0).describe('Fields auto-resolved'),\n conflicts: z.number().int().min(0).describe('Fields with conflicts'),\n }).optional(),\n});\n\n// ==========================================\n// Customization Management\n// ==========================================\n\n/**\n * Customizable Metadata Policy\n * Defines what parts of a metadata item can be customized by admins/users.\n * Package vendors use this to control customization boundaries.\n */\nexport const CustomizationPolicySchema = z.object({\n /** Metadata type this policy applies to */\n metadataType: z.string().describe('Metadata type (e.g. \"object\", \"view\")'),\n\n /** Whether customization is allowed at all for this type */\n allowCustomization: z.boolean().default(true),\n\n /**\n * Field paths that are locked (cannot be customized).\n * @example [\"name\", \"type\", \"fields.*.type\"]\n */\n lockedFields: z.array(z.string()).optional()\n .describe('Field paths that cannot be customized'),\n\n /**\n * Field paths that are customizable.\n * If specified, only these fields can be customized (whitelist mode).\n * @example [\"label\", \"description\", \"fields.*.label\", \"fields.*.helpText\"]\n */\n customizableFields: z.array(z.string()).optional()\n .describe('Field paths that can be customized (whitelist)'),\n\n /**\n * Whether users can add new fields to package objects.\n * When true, admins can extend package objects with custom fields.\n */\n allowAddFields: z.boolean().default(true)\n .describe('Whether admins can add new fields to package objects'),\n\n /**\n * Whether users can delete package-delivered fields.\n * Typically false — fields can only be hidden, not deleted.\n */\n allowDeleteFields: z.boolean().default(false)\n .describe('Whether admins can delete package-delivered fields'),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type CustomizationOrigin = z.infer;\nexport type FieldChange = z.infer;\nexport type MetadataOverlay = z.infer;\nexport type MergeConflict = z.infer;\nexport type MergeStrategyConfig = z.infer;\nexport type MergeResult = z.infer;\nexport type CustomizationPolicy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Metadata Loader Protocol\n * \n * Defines the standard interface for loading and saving metadata in ObjectStack.\n * This protocol enables consistent metadata operations across different storage backends\n * (filesystem, HTTP, S3, databases) and serialization formats (JSON, YAML, TypeScript).\n */\n\n/**\n * Metadata Format Enum\n * Supported serialization formats for metadata\n */\nexport const MetadataFormatSchema = z.enum(['json', 'yaml', 'typescript', 'javascript']);\n\n/**\n * Metadata Statistics\n * Information about a metadata item without loading its full content\n */\nexport const MetadataStatsSchema = z.object({\n /**\n * Size of the metadata file in bytes\n */\n size: z.number().int().min(0).describe('File size in bytes'),\n \n /**\n * Last modification timestamp\n */\n modifiedAt: z.string().datetime().describe('Last modified date'),\n \n /**\n * ETag for cache validation\n * Used for conditional requests (If-None-Match header)\n */\n etag: z.string().describe('Entity tag for cache validation'),\n \n /**\n * Serialization format\n */\n format: MetadataFormatSchema.describe('Serialization format'),\n \n /**\n * Full file path (if applicable)\n */\n path: z.string().optional().describe('File system path'),\n \n /**\n * Additional metadata provider-specific properties\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Provider-specific metadata'),\n});\n\n/**\n * Metadata Load Options\n */\nexport const MetadataLoadOptionsSchema = z.object({\n /**\n * Glob patterns to match files\n * Example: [\"**\\/*.object.ts\", \"**\\/*.object.json\"]\n */\n patterns: z.array(z.string()).optional().describe('File glob patterns'),\n \n /**\n * If-None-Match header for conditional loading\n * Only load if ETag doesn't match\n */\n ifNoneMatch: z.string().optional().describe('ETag for conditional request'),\n \n /**\n * If-Modified-Since header for conditional loading\n */\n ifModifiedSince: z.string().datetime().optional().describe('Only load if modified after this date'),\n \n /**\n * Whether to validate against Zod schema\n */\n validate: z.boolean().default(true).describe('Validate against schema'),\n \n /**\n * Whether to use cache if available\n */\n useCache: z.boolean().default(true).describe('Enable caching'),\n \n /**\n * Filter function (serialized as string)\n * Example: \"(item) => item.name.startsWith('sys_')\"\n */\n filter: z.string().optional().describe('Filter predicate as string'),\n \n /**\n * Maximum number of items to load\n */\n limit: z.number().int().min(1).optional().describe('Maximum items to load'),\n \n /**\n * Recursively search subdirectories\n */\n recursive: z.boolean().default(true).describe('Search subdirectories'),\n});\n\n/**\n * Metadata Save Options\n */\nexport const MetadataSaveOptionsSchema = z.object({\n /**\n * Serialization format\n */\n format: MetadataFormatSchema.default('typescript').describe('Output format'),\n \n /**\n * Prettify output (formatted with indentation)\n */\n prettify: z.boolean().default(true).describe('Format with indentation'),\n \n /**\n * Indentation size (spaces)\n */\n indent: z.number().int().min(0).max(8).default(2).describe('Indentation spaces'),\n \n /**\n * Sort object keys alphabetically\n */\n sortKeys: z.boolean().default(false).describe('Sort object keys'),\n \n /**\n * Include default values in output\n */\n includeDefaults: z.boolean().default(false).describe('Include default values'),\n \n /**\n * Create backup before overwriting\n */\n backup: z.boolean().default(false).describe('Create backup file'),\n \n /**\n * Overwrite if exists\n */\n overwrite: z.boolean().default(true).describe('Overwrite existing file'),\n \n /**\n * Atomic write (write to temp file, then rename)\n */\n atomic: z.boolean().default(true).describe('Use atomic write operation'),\n \n /**\n * Custom file path (overrides default location)\n */\n path: z.string().optional().describe('Custom output path'),\n});\n\n/**\n * Metadata Export Options\n */\nexport const MetadataExportOptionsSchema = z.object({\n /**\n * Output file path\n */\n output: z.string().describe('Output file path'),\n \n /**\n * Export format\n */\n format: MetadataFormatSchema.default('json').describe('Export format'),\n \n /**\n * Filter predicate as string\n */\n filter: z.string().optional().describe('Filter items to export'),\n \n /**\n * Include statistics in export\n */\n includeStats: z.boolean().default(false).describe('Include metadata statistics'),\n \n /**\n * Compress output\n */\n compress: z.boolean().default(false).describe('Compress output (gzip)'),\n \n /**\n * Pretty print output\n */\n prettify: z.boolean().default(true).describe('Pretty print output'),\n});\n\n/**\n * Metadata Import Options\n */\nexport const MetadataImportOptionsSchema = z.object({\n /**\n * Conflict resolution strategy\n */\n conflictResolution: z.enum(['skip', 'overwrite', 'merge', 'fail'])\n .default('merge')\n .describe('How to handle existing items'),\n \n /**\n * Validate items against schema\n */\n validate: z.boolean().default(true).describe('Validate before import'),\n \n /**\n * Dry run (don't actually save)\n */\n dryRun: z.boolean().default(false).describe('Simulate import without saving'),\n \n /**\n * Continue on errors\n */\n continueOnError: z.boolean().default(false).describe('Continue if validation fails'),\n \n /**\n * Transform function (as string)\n * Example: \"(item) => ({ ...item, imported: true })\"\n */\n transform: z.string().optional().describe('Transform items before import'),\n});\n\n/**\n * Metadata Loader Result\n * Result of a metadata load operation\n */\nexport const MetadataLoadResultSchema = z.object({\n /**\n * Loaded data\n */\n data: z.unknown().nullable().describe('Loaded metadata'),\n \n /**\n * Whether data came from cache (304 Not Modified)\n */\n fromCache: z.boolean().default(false).describe('Loaded from cache'),\n \n /**\n * Not modified (conditional request matched)\n */\n notModified: z.boolean().default(false).describe('Not modified since last request'),\n \n /**\n * ETag of loaded data\n */\n etag: z.string().optional().describe('Entity tag'),\n \n /**\n * Statistics about loaded data\n */\n stats: MetadataStatsSchema.optional().describe('Metadata statistics'),\n \n /**\n * Load time in milliseconds\n */\n loadTime: z.number().min(0).optional().describe('Load duration in ms'),\n});\n\n/**\n * Metadata Save Result\n */\nexport const MetadataSaveResultSchema = z.object({\n /**\n * Whether save was successful\n */\n success: z.boolean().describe('Save successful'),\n \n /**\n * Path where file was saved\n */\n path: z.string().describe('Output path'),\n \n /**\n * Generated ETag\n */\n etag: z.string().optional().describe('Generated entity tag'),\n \n /**\n * File size in bytes\n */\n size: z.number().int().min(0).optional().describe('File size'),\n \n /**\n * Save time in milliseconds\n */\n saveTime: z.number().min(0).optional().describe('Save duration in ms'),\n \n /**\n * Backup path (if created)\n */\n backupPath: z.string().optional().describe('Backup file path'),\n});\n\n/**\n * Metadata Watch Event\n */\nexport const MetadataWatchEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum(['added', 'changed', 'deleted']).describe('Event type'),\n \n /**\n * Metadata type (e.g., 'object', 'view', 'app')\n */\n metadataType: z.string().describe('Type of metadata'),\n \n /**\n * Item name/identifier\n */\n name: z.string().describe('Item identifier'),\n \n /**\n * Full file path\n */\n path: z.string().describe('File path'),\n \n /**\n * Loaded item data (for added/changed events)\n */\n data: z.unknown().optional().describe('Item data'),\n \n /**\n * Timestamp\n */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\n/**\n * Metadata Collection Info\n * Summary of a metadata collection\n */\nexport const MetadataCollectionInfoSchema = z.object({\n /**\n * Collection type (e.g., 'object', 'view', 'app')\n */\n type: z.string().describe('Collection type'),\n \n /**\n * Total items in collection\n */\n count: z.number().int().min(0).describe('Number of items'),\n \n /**\n * Formats found in collection\n */\n formats: z.array(MetadataFormatSchema).describe('Formats in collection'),\n \n /**\n * Total size in bytes\n */\n totalSize: z.number().int().min(0).optional().describe('Total size in bytes'),\n \n /**\n * Last modified timestamp\n */\n lastModified: z.string().datetime().optional().describe('Last modification date'),\n \n /**\n * Collection location (path or URL)\n */\n location: z.string().optional().describe('Collection location'),\n});\n\n/**\n * Metadata Loader Interface Contract\n * Defines the standard methods all metadata loaders must implement\n */\nexport const MetadataLoaderContractSchema = z.object({\n /**\n * Loader name/identifier\n */\n name: z.string().describe('Loader identifier'),\n\n /**\n * Protocol handled by this loader (e.g. 'file:', 'http:', 's3:', 'datasource:')\n */\n protocol: z.enum(['file:', 'http:', 's3:', 'datasource:', 'memory:']).describe('Protocol identifier'),\n\n /**\n * Detailed capabilities\n */\n capabilities: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n watch: z.boolean().default(false),\n list: z.boolean().default(true),\n }).describe('Loader capabilities'),\n \n /**\n * Supported formats\n */\n supportedFormats: z.array(MetadataFormatSchema).describe('Supported formats'),\n \n /**\n * Whether loader supports watching for changes\n */\n supportsWatch: z.boolean().default(false).describe('Supports file watching'),\n \n /**\n * Whether loader supports saving\n */\n supportsWrite: z.boolean().default(true).describe('Supports write operations'),\n \n /**\n * Whether loader supports caching\n */\n supportsCache: z.boolean().default(true).describe('Supports caching'),\n});\n\n/**\n * Metadata Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\nexport const MetadataFallbackStrategySchema = z.enum([\n 'filesystem', // Fall back to filesystem-based loading\n 'memory', // Fall back to in-memory storage\n 'none', // No fallback — fail immediately\n]);\n\n/**\n * Metadata Manager Configuration\n */\nexport const MetadataManagerConfigSchema = z.object({\n /**\n * Datasource Name Reference\n * References a DatasourceSchema.name (e.g. 'default').\n * At runtime, resolved from kernel service `driver.{name}` to obtain the actual driver.\n */\n datasource: z.string().optional().describe('Datasource name reference for database persistence'),\n\n /**\n * Metadata Table Name\n * The database table used for metadata storage when datasource is configured.\n */\n tableName: z.string().default('sys_metadata').describe('Database table name for metadata storage'),\n\n /**\n * Fallback Strategy\n * Determines behavior when the primary datasource is unavailable.\n */\n fallback: MetadataFallbackStrategySchema.default('none').describe('Fallback strategy when datasource is unavailable'),\n\n /**\n * Root directory for metadata (for filesystem loaders)\n */\n rootDir: z.string().optional().describe('Root directory path'),\n \n /**\n * Enabled serialization formats\n */\n formats: z.array(MetadataFormatSchema).default(['typescript', 'json', 'yaml']).describe('Enabled formats'),\n \n /**\n * Cache configuration\n */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable caching'),\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n maxSize: z.number().int().min(0).optional().describe('Max cache size in bytes'),\n }).optional().describe('Cache settings'),\n \n /**\n * Watch for file changes\n */\n watch: z.boolean().default(false).describe('Enable file watching'),\n \n /**\n * Watch options\n */\n watchOptions: z.object({\n ignored: z.array(z.string()).optional().describe('Patterns to ignore'),\n persistent: z.boolean().default(true).describe('Keep process running'),\n ignoreInitial: z.boolean().default(true).describe('Ignore initial add events'),\n }).optional().describe('File watcher options'),\n \n /**\n * Validation settings\n */\n validation: z.object({\n strict: z.boolean().default(true).describe('Strict validation'),\n throwOnError: z.boolean().default(true).describe('Throw on validation error'),\n }).optional().describe('Validation settings'),\n \n /**\n * Loader-specific options\n */\n loaderOptions: z.record(z.string(), z.unknown()).optional().describe('Loader-specific configuration'),\n});\n\n// Export types\nexport type MetadataFormat = z.infer;\nexport type MetadataStats = z.infer;\nexport type MetadataLoadOptions = z.input;\nexport type MetadataSaveOptions = z.infer;\nexport type MetadataExportOptions = z.infer;\nexport type MetadataImportOptions = z.infer;\nexport type MetadataLoadResult = z.infer;\nexport type MetadataSaveResult = z.infer;\nexport type MetadataWatchEvent = z.infer;\nexport type MetadataCollectionInfo = z.infer;\nexport type MetadataLoaderContract = z.input;\nexport type MetadataManagerConfig = z.input;\nexport type MetadataFallbackStrategy = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { MetadataManagerConfigSchema } from './metadata-loader.zod';\nimport { MergeStrategyConfigSchema, CustomizationPolicySchema } from './metadata-customization.zod';\n\n/**\n * # Metadata Plugin Protocol\n *\n * Defines the specification for the **Metadata Plugin** — the central authority\n * responsible for managing ALL metadata across the ObjectStack platform.\n *\n * ## Architecture\n * The Metadata Plugin consolidates all scattered metadata operations into a single,\n * cohesive plugin that \"takes over\" the entire platform's metadata management:\n *\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ Metadata Plugin │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Type Registry │ │ Loader │ │ Customization Layer │ │\n * │ │ (all types) │ │ (file/db/s3)│ │ (overlay / merge) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * │ │\n * │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │\n * │ │ Persistence │ │ Query │ │ Lifecycle │ │\n * │ │ (db records) │ │ (search) │ │ (validate/deploy) │ │\n * │ └──────────────┘ └──────────────┘ └──────────────────────┘ │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n *\n * ## References\n * - kernel/metadata-loader.zod.ts — Storage backend protocol\n * - kernel/metadata-customization.zod.ts — Overlay/merge protocol\n * - system/metadata-persistence.zod.ts — Database record format\n * - contracts/metadata-service.ts — Service interface\n */\n\n// ==========================================\n// Metadata Type Registry\n// ==========================================\n\n/**\n * Platform Metadata Type Enum\n *\n * The canonical list of all metadata types managed by the platform.\n * Each type maps to a specific Zod schema (e.g., ObjectSchema, ViewSchema).\n * Plugins can extend this registry via `contributes.kinds` in the manifest.\n *\n * ## Naming Convention\n * **IMPORTANT:** All metadata type names are in **SINGULAR** form:\n * - ✅ Use: `'agent'`, `'tool'`, `'skill'`, `'view'`, `'flow'`, `'action'`\n * - ❌ NOT: `'agents'`, `'tools'`, `'skills'`, `'views'`, `'flows'`, `'actions'`\n *\n * This convention applies to:\n * - Protocol definitions (this enum)\n * - UI plugin registrations (`metadataTypes`, `metadataIcons`)\n * - Metadata service operations\n * - File patterns (`*.agent.ts`, `*.tool.ts`)\n *\n * REST API endpoints continue to use plural forms per REST conventions:\n * - `/api/v1/ai/agents`, `/api/v1/ai/conversations`\n */\nexport const MetadataTypeSchema = z.enum([\n // Data Protocol\n 'object', // Business entity definition (ObjectSchema)\n 'field', // Standalone field definition (FieldSchema)\n 'trigger', // Data-layer event triggers (TriggerSchema)\n 'validation', // Validation rules (ValidationSchema)\n 'hook', // Data hooks (HookSchema)\n\n // UI Protocol\n 'view', // List/form views (ViewSchema)\n 'page', // Standalone pages (PageSchema)\n 'dashboard', // Dashboard layouts (DashboardSchema)\n 'app', // Application shell (AppSchema)\n 'action', // UI/Server actions (ActionSchema)\n 'report', // Report definitions (ReportSchema)\n\n // Automation Protocol\n 'flow', // Visual logic flows (FlowSchema)\n 'workflow', // State machines (WorkflowSchema)\n 'approval', // Approval processes (ApprovalSchema)\n\n // System Protocol\n 'datasource', // Data connections (DatasourceSchema)\n 'translation', // i18n resources (TranslationSchema)\n 'router', // API routes\n 'function', // Serverless functions\n 'service', // Service definitions\n\n // Security Protocol\n 'permission', // Permission sets (PermissionSetSchema)\n 'profile', // User profiles (ProfileSchema)\n 'role', // Security roles\n\n // AI Protocol\n 'agent', // AI agent definitions (AgentSchema)\n 'tool', // AI tool definitions (ToolSchema)\n 'skill', // AI skill definitions (SkillSchema)\n]);\n\nexport type MetadataType = z.infer;\n\n// ==========================================\n// Type Registry Entry\n// ==========================================\n\n/**\n * Metadata Type Registry Entry\n *\n * Describes a registered metadata type, including its validation schema,\n * file patterns, and capabilities. Used by the metadata plugin to:\n * 1. Discover metadata files on disk\n * 2. Validate metadata payloads\n * 3. Determine storage behavior\n */\nexport const MetadataTypeRegistryEntrySchema = z.object({\n /** Metadata type identifier (e.g., 'object', 'view') */\n type: MetadataTypeSchema.describe('Metadata type identifier'),\n\n /** Human-readable label */\n label: z.string().describe('Display label for the metadata type'),\n\n /** Brief description */\n description: z.string().optional().describe('Description of the metadata type'),\n\n /**\n * File glob patterns for this type.\n * Used to discover metadata files on disk.\n * @example [\"**\\/*.object.ts\", \"**\\/*.object.yml\"]\n */\n filePatterns: z.array(z.string()).describe('Glob patterns to discover files of this type'),\n\n /**\n * Whether this type supports the customization overlay system.\n * When true, platform/user overlays can be applied on top of package-delivered metadata.\n */\n supportsOverlay: z.boolean().default(true).describe('Whether overlay customization is supported'),\n\n /**\n * Whether metadata of this type can be created at runtime via API.\n * Some types (e.g., 'object') may be restricted to deployment-only.\n */\n allowRuntimeCreate: z.boolean().default(true).describe('Allow runtime creation via API'),\n\n /**\n * Whether this type supports versioning.\n * When true, changes are tracked with version history.\n */\n supportsVersioning: z.boolean().default(false).describe('Whether version history is tracked'),\n\n /**\n * Priority order for loading (lower = earlier).\n * Objects load before views, views before dashboards.\n */\n loadOrder: z.number().int().min(0).default(100).describe('Loading priority (lower = earlier)'),\n\n /** The domain this type belongs to */\n domain: z.enum(['data', 'ui', 'automation', 'system', 'security', 'ai'])\n .describe('Protocol domain'),\n});\n\nexport type MetadataTypeRegistryEntry = z.infer;\n\n// ==========================================\n// Metadata Query Protocol\n// ==========================================\n\n/**\n * Metadata Query Schema\n *\n * Standard protocol for searching and filtering metadata items.\n * Used by the metadata service to support advanced metadata discovery.\n */\nexport const MetadataQuerySchema = z.object({\n /** Filter by metadata type(s) */\n types: z.array(MetadataTypeSchema).optional().describe('Filter by metadata types'),\n\n /** Filter by namespace(s) */\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n\n /** Filter by package ID */\n packageId: z.string().optional().describe('Filter by owning package'),\n\n /** Full-text search across name, label, description */\n search: z.string().optional().describe('Full-text search query'),\n\n /** Filter by scope */\n scope: z.enum(['system', 'platform', 'user']).optional().describe('Filter by scope'),\n\n /** Filter by state */\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional().describe('Filter by lifecycle state'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Sort field */\n sortBy: z.enum(['name', 'type', 'updatedAt', 'createdAt']).default('name').describe('Sort field'),\n\n /** Sort direction */\n sortOrder: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n\n /** Pagination: page number (1-based) */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(500).default(50).describe('Items per page'),\n});\n\nexport type MetadataQuery = z.input;\n\n/**\n * Metadata Query Result\n */\nexport const MetadataQueryResultSchema = z.object({\n /** Matched items */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n namespace: z.string().optional().describe('Namespace'),\n label: z.string().optional().describe('Display label'),\n scope: z.enum(['system', 'platform', 'user']).optional(),\n state: z.enum(['draft', 'active', 'archived', 'deprecated']).optional(),\n packageId: z.string().optional(),\n updatedAt: z.string().datetime().optional(),\n })).describe('Matched metadata items'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching items'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page'),\n\n /** Page size */\n pageSize: z.number().int().min(1).describe('Page size'),\n});\n\nexport type MetadataQueryResult = z.infer;\n\n// ==========================================\n// Metadata Lifecycle Events\n// ==========================================\n\n/**\n * Metadata Event Schema\n *\n * Events emitted by the metadata plugin when metadata changes.\n * Enables reactive patterns across the platform (cache invalidation,\n * UI refresh, dependency tracking, etc.).\n */\nexport const MetadataEventSchema = z.object({\n /** Event type */\n event: z.enum([\n 'metadata.registered',\n 'metadata.updated',\n 'metadata.unregistered',\n 'metadata.validated',\n 'metadata.deployed',\n 'metadata.overlay.applied',\n 'metadata.overlay.removed',\n 'metadata.imported',\n 'metadata.exported',\n ]).describe('Event type'),\n\n /** Metadata type */\n metadataType: MetadataTypeSchema.describe('Metadata type'),\n\n /** Item name */\n name: z.string().describe('Metadata item name'),\n\n /** Namespace */\n namespace: z.string().optional().describe('Namespace'),\n\n /** Package ID (if package-managed) */\n packageId: z.string().optional().describe('Owning package ID'),\n\n /** Timestamp */\n timestamp: z.string().datetime().describe('Event timestamp'),\n\n /** Actor who caused the event */\n actor: z.string().optional().describe('User or system that triggered the event'),\n\n /** Additional event-specific payload */\n payload: z.record(z.string(), z.unknown()).optional().describe('Event-specific payload'),\n});\n\nexport type MetadataEvent = z.infer;\n\n// ==========================================\n// Metadata Validation\n// ==========================================\n\n/**\n * Metadata Validation Result\n */\nexport const MetadataValidationResultSchema = z.object({\n /** Whether validation passed */\n valid: z.boolean().describe('Whether the metadata is valid'),\n\n /** Validation errors */\n errors: z.array(z.object({\n path: z.string().describe('JSON path to the invalid field'),\n message: z.string().describe('Error description'),\n code: z.string().optional().describe('Error code'),\n })).optional().describe('Validation errors'),\n\n /** Validation warnings (non-blocking) */\n warnings: z.array(z.object({\n path: z.string().describe('JSON path to the field'),\n message: z.string().describe('Warning description'),\n })).optional().describe('Validation warnings'),\n});\n\nexport type MetadataValidationResult = z.infer;\n\n// ==========================================\n// Metadata Plugin Configuration\n// ==========================================\n\n/**\n * Metadata Plugin Configuration\n *\n * The unified configuration for the metadata plugin, combining\n * storage, caching, customization, and type registry settings.\n */\nexport const MetadataPluginConfigSchema = z.object({\n /**\n * Storage configuration.\n * References MetadataManagerConfigSchema for the underlying storage backend.\n */\n storage: MetadataManagerConfigSchema.describe('Storage backend configuration'),\n\n /**\n * Default customization policies per metadata type.\n * Controls what parts of metadata can be customized by admins/users.\n */\n customizationPolicies: z.array(CustomizationPolicySchema).optional()\n .describe('Default customization policies per type'),\n\n /**\n * Merge strategy for package upgrades.\n */\n mergeStrategy: MergeStrategyConfigSchema.optional()\n .describe('Merge strategy for package upgrades'),\n\n /**\n * Additional metadata type registrations.\n * Used by plugins to register custom metadata types beyond the built-in set.\n */\n additionalTypes: z.array(MetadataTypeRegistryEntrySchema.omit({ type: true }).extend({\n type: z.string().describe('Custom metadata type identifier'),\n })).optional().describe('Additional custom metadata types'),\n\n /**\n * Enable metadata change events.\n * When true, the plugin emits events on every metadata change.\n */\n enableEvents: z.boolean().default(true).describe('Emit metadata change events'),\n\n /**\n * Enable metadata validation on write operations.\n * When true, all metadata is validated against its type schema before saving.\n */\n validateOnWrite: z.boolean().default(true).describe('Validate metadata on write'),\n\n /**\n * Enable metadata versioning.\n * When true, changes to metadata are tracked with version history.\n */\n enableVersioning: z.boolean().default(false).describe('Track metadata version history'),\n\n /**\n * Maximum number of metadata items to keep in memory cache.\n */\n cacheMaxItems: z.number().int().min(0).default(10000).describe('Max items in memory cache'),\n});\n\nexport type MetadataPluginConfig = z.input;\n\n// ==========================================\n// Metadata Plugin Manifest\n// ==========================================\n\n/**\n * Metadata Plugin Manifest\n *\n * The complete manifest for the Metadata Plugin, declaring its identity,\n * capabilities, and configuration. This is the \"contract\" between the\n * metadata plugin and the kernel.\n */\nexport const MetadataPluginManifestSchema = z.object({\n /** Plugin identifier */\n id: z.literal('com.objectstack.metadata').describe('Metadata plugin ID'),\n\n /** Plugin name */\n name: z.literal('ObjectStack Metadata Service').describe('Plugin name'),\n\n /** Plugin version */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).describe('Plugin version'),\n\n /** Plugin type */\n type: z.literal('standard').describe('Plugin type'),\n\n /** Plugin description */\n description: z.string().default('Core metadata management service for ObjectStack platform')\n .describe('Plugin description'),\n\n /**\n * Capabilities this plugin provides.\n * The kernel uses this to route metadata requests to this plugin.\n */\n capabilities: z.object({\n /** Supports CRUD operations on metadata */\n crud: z.boolean().default(true).describe('Supports metadata CRUD'),\n\n /** Supports metadata query/search */\n query: z.boolean().default(true).describe('Supports metadata query'),\n\n /** Supports the overlay/customization system */\n overlay: z.boolean().default(true).describe('Supports customization overlays'),\n\n /** Supports file watching for hot reload */\n watch: z.boolean().default(false).describe('Supports file watching'),\n\n /** Supports bulk import/export */\n importExport: z.boolean().default(true).describe('Supports import/export'),\n\n /** Supports metadata validation */\n validation: z.boolean().default(true).describe('Supports schema validation'),\n\n /** Supports metadata versioning */\n versioning: z.boolean().default(false).describe('Supports version history'),\n\n /** Supports metadata events */\n events: z.boolean().default(true).describe('Emits metadata events'),\n }).describe('Plugin capabilities'),\n\n /** Plugin configuration */\n config: MetadataPluginConfigSchema.optional().describe('Plugin configuration'),\n});\n\nexport type MetadataPluginManifest = z.input;\n\n// ==========================================\n// Built-in Type Registry Defaults\n// ==========================================\n\n/**\n * Default Type Registry\n *\n * The built-in metadata type registry with default configurations.\n * Plugins extend this via `contributes.kinds` in the manifest.\n */\nexport const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntry[] = [\n // Data Protocol (load first)\n { type: 'object', label: 'Object', filePatterns: ['**/*.object.ts', '**/*.object.yml', '**/*.object.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 10, domain: 'data' },\n { type: 'field', label: 'Field', filePatterns: ['**/*.field.ts', '**/*.field.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 20, domain: 'data' },\n { type: 'trigger', label: 'Trigger', filePatterns: ['**/*.trigger.ts', '**/*.trigger.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'validation', label: 'Validation Rule', filePatterns: ['**/*.validation.ts', '**/*.validation.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n { type: 'hook', label: 'Hook', filePatterns: ['**/*.hook.ts', '**/*.hook.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 30, domain: 'data' },\n\n // UI Protocol\n { type: 'view', label: 'View', filePatterns: ['**/*.view.ts', '**/*.view.yml', '**/*.view.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'page', label: 'Page', filePatterns: ['**/*.page.ts', '**/*.page.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'dashboard', label: 'Dashboard', filePatterns: ['**/*.dashboard.ts', '**/*.dashboard.yml', '**/*.dashboard.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n { type: 'app', label: 'Application', filePatterns: ['**/*.app.ts', '**/*.app.yml', '**/*.app.json'], supportsOverlay: true, allowRuntimeCreate: false, supportsVersioning: true, loadOrder: 70, domain: 'ui' },\n { type: 'action', label: 'Action', filePatterns: ['**/*.action.ts', '**/*.action.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 50, domain: 'ui' },\n { type: 'report', label: 'Report', filePatterns: ['**/*.report.ts', '**/*.report.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 60, domain: 'ui' },\n\n // Automation Protocol\n { type: 'flow', label: 'Flow', filePatterns: ['**/*.flow.ts', '**/*.flow.yml', '**/*.flow.json'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'workflow', label: 'Workflow', filePatterns: ['**/*.workflow.ts', '**/*.workflow.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 80, domain: 'automation' },\n { type: 'approval', label: 'Approval Process', filePatterns: ['**/*.approval.ts', '**/*.approval.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 80, domain: 'automation' },\n\n // System Protocol\n { type: 'datasource', label: 'Datasource', filePatterns: ['**/*.datasource.ts', '**/*.datasource.yml'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 5, domain: 'system' },\n { type: 'translation', label: 'Translation', filePatterns: ['**/*.translation.ts', '**/*.translation.yml', '**/*.translation.json'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 90, domain: 'system' },\n { type: 'router', label: 'Router', filePatterns: ['**/*.router.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'function', label: 'Function', filePatterns: ['**/*.function.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n { type: 'service', label: 'Service', filePatterns: ['**/*.service.ts'], supportsOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, loadOrder: 40, domain: 'system' },\n\n // Security Protocol\n { type: 'permission', label: 'Permission Set', filePatterns: ['**/*.permission.ts', '**/*.permission.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 15, domain: 'security' },\n { type: 'profile', label: 'Profile', filePatterns: ['**/*.profile.ts', '**/*.profile.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n { type: 'role', label: 'Role', filePatterns: ['**/*.role.ts', '**/*.role.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 15, domain: 'security' },\n\n // AI Protocol\n { type: 'agent', label: 'AI Agent', filePatterns: ['**/*.agent.ts', '**/*.agent.yml'], supportsOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, loadOrder: 90, domain: 'ai' },\n { type: 'tool', label: 'AI Tool', filePatterns: ['**/*.tool.ts', '**/*.tool.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 85, domain: 'ai' },\n { type: 'skill', label: 'AI Skill', filePatterns: ['**/*.skill.ts', '**/*.skill.yml'], supportsOverlay: true, allowRuntimeCreate: true, supportsVersioning: false, loadOrder: 88, domain: 'ai' },\n];\n\n// ==========================================\n// Bulk Operation Types\n// ==========================================\n\n/**\n * Bulk Register Request\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n /** Items to register */\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Namespace'),\n })).min(1).describe('Items to register'),\n\n /** Continue on individual item failure */\n continueOnError: z.boolean().default(false).describe('Continue if individual item fails'),\n\n /** Validate items before registering */\n validate: z.boolean().default(true).describe('Validate before register'),\n});\n\nexport type MetadataBulkRegisterRequest = z.input;\n\n/**\n * Bulk Operation Result\n */\nexport const MetadataBulkResultSchema = z.object({\n /** Total items processed */\n total: z.number().int().min(0).describe('Total items processed'),\n\n /** Successfully processed items */\n succeeded: z.number().int().min(0).describe('Successfully processed'),\n\n /** Failed items */\n failed: z.number().int().min(0).describe('Failed items'),\n\n /** Per-item error details */\n errors: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n error: z.string().describe('Error message'),\n })).optional().describe('Per-item errors'),\n});\n\nexport type MetadataBulkResult = z.infer;\n\n// ==========================================\n// Metadata Dependency\n// ==========================================\n\n/**\n * Metadata Dependency Schema\n *\n * Tracks dependencies between metadata items.\n * Used for impact analysis and safe deletion checks.\n */\nexport const MetadataDependencySchema = z.object({\n /** Source metadata type */\n sourceType: z.string().describe('Dependent metadata type'),\n\n /** Source metadata name */\n sourceName: z.string().describe('Dependent metadata name'),\n\n /** Target metadata type */\n targetType: z.string().describe('Referenced metadata type'),\n\n /** Target metadata name */\n targetName: z.string().describe('Referenced metadata name'),\n\n /** Dependency kind */\n kind: z.enum(['reference', 'extends', 'includes', 'triggers'])\n .describe('How the dependency is formed'),\n});\n\nexport type MetadataDependency = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\nimport { DependencyResolutionResultSchema } from './dependency-resolution.zod';\n\n/**\n * # Package Registry Protocol\n * \n * Defines the runtime state and lifecycle operations for installed packages.\n * \n * ## Key Distinction: Package vs App\n * - **Package (Manifest)**: The unit of installation — a deployable artifact containing\n * metadata (objects, actions, flows, etc.) and optionally one or more Apps.\n * - **App (AppSchema)**: A UI navigation shell defined inside a package.\n * \n * A package may contain:\n * - Zero apps (pure functionality plugin, e.g. a storage driver)\n * - One app (typical business application)\n * - Multiple apps (suite of applications)\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Packages with install/uninstall lifecycle\n * - **VS Code**: Extension marketplace with enable/disable per-workspace\n * - **Kubernetes**: Helm charts with release state tracking\n * - **npm**: Package registry with install/uninstall/version management\n */\n\n// ==========================================\n// Package Status & Lifecycle\n// ==========================================\n\n/**\n * Package installation status.\n */\nexport const PackageStatusEnum = z.enum([\n 'installed', // Successfully installed and enabled\n 'disabled', // Installed but disabled (metadata not active)\n 'installing', // Installation in progress\n 'upgrading', // Upgrade in progress\n 'uninstalling', // Removal in progress\n 'error', // Installation or runtime error\n]).describe('Package installation status');\nexport type PackageStatus = z.infer;\n\n/**\n * Installed Package Schema\n * \n * Wraps a ManifestSchema with runtime lifecycle state.\n * This is the \"row\" in the installed packages table.\n */\nexport const InstalledPackageSchema = z.object({\n /** \n * The full package manifest (source of truth for package definition).\n */\n manifest: ManifestSchema.describe('Full package manifest'),\n\n /**\n * Current lifecycle status.\n */\n status: PackageStatusEnum.default('installed')\n .describe('Package state: installed, disabled, installing, upgrading, uninstalling, or error'),\n\n /**\n * Whether the package is currently enabled (active).\n * When disabled, the package's metadata is not loaded into the registry.\n */\n enabled: z.boolean().default(true)\n .describe('Whether the package is currently enabled'),\n\n /**\n * ISO 8601 timestamp of when the package was installed.\n */\n installedAt: z.string().datetime().optional()\n .describe('Installation timestamp'),\n\n /**\n * ISO 8601 timestamp of last update.\n */\n updatedAt: z.string().datetime().optional()\n .describe('Last update timestamp'),\n\n /**\n * The currently installed version string.\n * Mirrors manifest.version for quick access without parsing the full manifest.\n */\n installedVersion: z.string().optional()\n .describe('Currently installed version for quick access'),\n\n /**\n * The previously installed version (before last upgrade).\n * Useful for rollback and upgrade tracking.\n */\n previousVersion: z.string().optional()\n .describe('Version before the last upgrade'),\n\n /**\n * ISO 8601 timestamp of when the package was last enabled/disabled.\n */\n statusChangedAt: z.string().datetime().optional()\n .describe('Status change timestamp'),\n\n /**\n * Error message if status is 'error'.\n */\n errorMessage: z.string().optional()\n .describe('Error message when status is error'),\n\n /**\n * Configuration values set by the user for this package.\n * Keys correspond to the package's `configuration.properties`.\n */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided configuration settings'),\n\n /**\n * Upgrade history for this package.\n * Records each version migration with status and optional log.\n */\n upgradeHistory: z.array(z.object({\n /** Previous version before upgrade */\n fromVersion: z.string().describe('Version before upgrade'),\n /** New version after upgrade */\n toVersion: z.string().describe('Version after upgrade'),\n /** Timestamp of the upgrade */\n upgradedAt: z.string().datetime().describe('Upgrade timestamp'),\n /** Outcome of the upgrade */\n status: z.enum(['success', 'failed', 'rolled_back']).describe('Upgrade outcome'),\n /** Migration log entries */\n migrationLog: z.array(z.string()).optional().describe('Migration step logs'),\n })).optional().describe('Version upgrade history'),\n\n /**\n * Namespaces registered by this package.\n * Tracks which namespace prefixes are occupied by this package.\n */\n registeredNamespaces: z.array(z.string()).optional()\n .describe('Namespace prefixes registered by this package'),\n}).describe('Installed package with runtime lifecycle state');\nexport type InstalledPackage = z.infer;\n\n// ==========================================\n// Namespace Registry\n// ==========================================\n\n/**\n * Namespace Registry Entry\n * Tracks namespace ownership within the platform instance.\n */\nexport const NamespaceRegistryEntrySchema = z.object({\n /** Namespace prefix */\n namespace: z.string().describe('Namespace prefix'),\n\n /** Package that owns this namespace */\n packageId: z.string().describe('Owning package ID'),\n\n /** Registration timestamp */\n registeredAt: z.string().datetime().describe('Registration timestamp'),\n\n /** Namespace status */\n status: z.enum(['active', 'disabled', 'reserved'])\n .describe('Namespace status'),\n}).describe('Namespace ownership entry in the registry');\n\nexport type NamespaceRegistryEntry = z.infer;\n\n/**\n * Namespace Conflict Error\n * Describes a namespace collision detected during package installation.\n */\nexport const NamespaceConflictErrorSchema = z.object({\n /** Error type discriminator */\n type: z.literal('namespace_conflict').describe('Error type'),\n\n /** Namespace that was requested */\n requestedNamespace: z.string().describe('Requested namespace'),\n\n /** ID of the package that already owns the namespace */\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n\n /** Name of the conflicting package */\n conflictingPackageName: z.string().describe('Conflicting package display name'),\n\n /** Suggested alternative namespace */\n suggestion: z.string().optional()\n .describe('Suggested alternative namespace'),\n}).describe('Namespace collision error during installation');\n\nexport type NamespaceConflictError = z.infer;\n\n// ==========================================\n// Package Registry Request/Response Schemas\n// ==========================================\n\n/**\n * List Packages Request\n */\nexport const ListPackagesRequestSchema = z.object({\n /** Filter by status */\n status: PackageStatusEnum.optional().describe('Filter by package status'),\n /** Filter by package type */\n type: ManifestSchema.shape.type.optional().describe('Filter by package type'),\n /** Filter by enabled state */\n enabled: z.boolean().optional().describe('Filter by enabled state'),\n}).describe('List packages request');\nexport type ListPackagesRequest = z.infer;\n\n/**\n * List Packages Response\n */\nexport const ListPackagesResponseSchema = z.object({\n packages: z.array(InstalledPackageSchema).describe('List of installed packages'),\n total: z.number().describe('Total package count'),\n}).describe('List packages response');\nexport type ListPackagesResponse = z.infer;\n\n/**\n * Get Package Request\n */\nexport const GetPackageRequestSchema = z.object({\n /** Package ID (reverse domain identifier from manifest) */\n id: z.string().describe('Package identifier'),\n}).describe('Get package request');\nexport type GetPackageRequest = z.infer;\n\n/**\n * Get Package Response\n */\nexport const GetPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Package details'),\n}).describe('Get package response');\nexport type GetPackageResponse = z.infer;\n\n/**\n * Install Package Request\n * \n * Accepts a full manifest to install. In a production system,\n * this might also accept a package ID to fetch from a marketplace.\n */\nexport const InstallPackageRequestSchema = z.object({\n /** The package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n /** Optional: user-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n /** Whether to enable immediately after install (default: true) */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n /**\n * Current platform version for compatibility checking.\n * When provided, the system compares this against the package's\n * `engine.objectstack` requirement to verify compatibility.\n */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n}).describe('Install package request');\nexport type InstallPackageRequest = z.infer;\n\n/**\n * Install Package Response\n */\nexport const InstallPackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n message: z.string().optional().describe('Installation status message'),\n /** Dependency resolution result (when dependencies were analyzed) */\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result from install analysis'),\n}).describe('Install package response');\nexport type InstallPackageResponse = z.infer;\n\n/**\n * Uninstall Package Request\n */\nexport const UninstallPackageRequestSchema = z.object({\n /** Package ID to uninstall */\n id: z.string().describe('Package ID to uninstall'),\n}).describe('Uninstall package request');\nexport type UninstallPackageRequest = z.infer;\n\n/**\n * Uninstall Package Response\n */\nexport const UninstallPackageResponseSchema = z.object({\n id: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n}).describe('Uninstall package response');\nexport type UninstallPackageResponse = z.infer;\n\n/**\n * Enable Package Request\n */\nexport const EnablePackageRequestSchema = z.object({\n /** Package ID to enable */\n id: z.string().describe('Package ID to enable'),\n}).describe('Enable package request');\nexport type EnablePackageRequest = z.infer;\n\n/**\n * Enable Package Response\n */\nexport const EnablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Enabled package details'),\n message: z.string().optional().describe('Enable status message'),\n}).describe('Enable package response');\nexport type EnablePackageResponse = z.infer;\n\n/**\n * Disable Package Request\n */\nexport const DisablePackageRequestSchema = z.object({\n /** Package ID to disable */\n id: z.string().describe('Package ID to disable'),\n}).describe('Disable package request');\nexport type DisablePackageRequest = z.infer;\n\n/**\n * Disable Package Response\n */\nexport const DisablePackageResponseSchema = z.object({\n package: InstalledPackageSchema.describe('Disabled package details'),\n message: z.string().optional().describe('Disable status message'),\n}).describe('Disable package response');\nexport type DisablePackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ManifestSchema } from './manifest.zod';\n\n/**\n * # Package Upgrade Protocol\n * \n * Defines the complete lifecycle for upgrading installed packages,\n * including pre-upgrade analysis, snapshot/backup, execution, validation,\n * and rollback capabilities.\n * \n * ## Architecture Alignment\n * - **Salesforce**: Managed Package upgrade with push upgrades and subscriber control\n * - **ServiceNow**: Update Sets with preview, commit, and back-out support\n * - **Helm**: Helm upgrade with rollback to previous release\n * - **Kubernetes**: Rolling update with readiness probes and automatic rollback\n * \n * ## Upgrade Flow\n * ```\n * 1. PreCheck → Validate compatibility, check dependencies\n * 2. Plan → Generate upgrade plan with metadata diff\n * 3. Snapshot → Backup current state (metadata + customizations)\n * 4. Execute → Apply new package metadata with 3-way merge\n * 5. Validate → Run post-upgrade health checks\n * 6. Commit → Finalize upgrade (or Rollback on failure)\n * ```\n */\n\n// ==========================================\n// Upgrade Plan & Analysis\n// ==========================================\n\n/**\n * Metadata Change Type\n * Type of change detected between package versions.\n */\nexport const MetadataChangeTypeSchema = z.enum([\n 'added', // New metadata item added in new version\n 'modified', // Existing metadata item modified\n 'removed', // Metadata item removed in new version\n 'renamed', // Metadata item renamed\n]).describe('Type of metadata change between package versions');\n\n/**\n * Metadata Diff Item\n * Describes a single metadata change between two package versions.\n */\nexport const MetadataDiffItemSchema = z.object({\n /** Metadata type (e.g. \"object\", \"view\", \"flow\") */\n type: z.string().describe('Metadata type'),\n\n /** Metadata name */\n name: z.string().describe('Metadata name'),\n\n /** Type of change */\n changeType: MetadataChangeTypeSchema.describe('Category of metadata modification (added, modified, removed, or renamed)'),\n\n /** Whether this change has potential conflicts with customizations */\n hasConflict: z.boolean().default(false)\n .describe('Whether this change may conflict with customizations'),\n\n /** Human-readable summary of the change */\n summary: z.string().optional().describe('Human-readable change summary'),\n\n /** Previous name (for renames) */\n previousName: z.string().optional().describe('Previous name if renamed'),\n}).describe('Single metadata change between package versions');\n\n/**\n * Upgrade Impact Level\n * Indicates the severity of impact the upgrade will have.\n */\nexport const UpgradeImpactLevelSchema = z.enum([\n 'none', // No impact, seamless upgrade\n 'low', // Minor changes, no user action needed\n 'medium', // Some changes that may affect workflows\n 'high', // Significant changes, user review recommended\n 'critical', // Breaking changes, manual intervention required\n]).describe('Severity of upgrade impact');\n\n/**\n * Upgrade Plan Schema\n * The analysis result before executing an upgrade.\n * Generated by comparing old version metadata with new version metadata.\n */\nexport const UpgradePlanSchema = z.object({\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Current installed version */\n fromVersion: z.string().describe('Currently installed version'),\n\n /** Target version to upgrade to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Overall impact level */\n impactLevel: UpgradeImpactLevelSchema.describe('Severity assessment from none (seamless) to critical (breaking changes)'),\n\n /** List of all metadata changes between versions */\n changes: z.array(MetadataDiffItemSchema).describe('All metadata changes'),\n\n /** Number of customer customizations that may be affected */\n affectedCustomizations: z.number().int().min(0).default(0)\n .describe('Count of customizations that may be affected'),\n\n /** Whether any migration scripts need to run */\n requiresMigration: z.boolean().default(false)\n .describe('Whether data migration scripts are needed'),\n\n /** Migration script paths (relative to package root) */\n migrationScripts: z.array(z.string()).optional()\n .describe('Paths to migration scripts'),\n\n /** Dependencies that also need upgrading */\n dependencyUpgrades: z.array(z.object({\n packageId: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n })).optional().describe('Dependent packages that also need upgrading'),\n\n /** Estimated upgrade duration in seconds */\n estimatedDuration: z.number().int().min(0).optional()\n .describe('Estimated upgrade duration in seconds'),\n\n /** Human-readable summary */\n summary: z.string().optional().describe('Human-readable upgrade summary'),\n}).describe('Upgrade analysis plan generated before execution');\n\n// ==========================================\n// Upgrade Snapshot (Pre-Upgrade Backup)\n// ==========================================\n\n/**\n * Upgrade Snapshot Schema\n * Captures the complete state before an upgrade for rollback capability.\n */\nexport const UpgradeSnapshotSchema = z.object({\n /** Snapshot ID (UUID) */\n id: z.string().describe('Snapshot identifier'),\n\n /** Package being upgraded */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being upgraded from */\n fromVersion: z.string().describe('Version before upgrade'),\n\n /** Version being upgraded to */\n toVersion: z.string().describe('Target upgrade version'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n\n /** Complete manifest of the old package version */\n previousManifest: ManifestSchema.describe('Complete manifest of the previous package version'),\n\n /**\n * Snapshot of all metadata records owned by this package.\n * Stored as array of { type, name, metadata } tuples.\n */\n metadataSnapshot: z.array(z.object({\n type: z.string(),\n name: z.string(),\n metadata: z.record(z.string(), z.unknown()),\n })).describe('Snapshot of all package metadata'),\n\n /**\n * Snapshot of all customer customizations (overlays) for this package's metadata.\n */\n customizationSnapshot: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Snapshot of customer customizations'),\n\n /** When the snapshot was created */\n createdAt: z.string().datetime().describe('Snapshot creation timestamp'),\n\n /** Expiry time for snapshot cleanup */\n expiresAt: z.string().datetime().optional().describe('Snapshot expiry timestamp'),\n}).describe('Pre-upgrade state snapshot for rollback capability');\n\n// ==========================================\n// Upgrade Request/Response\n// ==========================================\n\n/**\n * Upgrade Package Request\n */\nexport const UpgradePackageRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (if omitted, upgrades to latest) */\n targetVersion: z.string().optional().describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional().describe('New manifest (if installing from local)'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum([\n 'keep-custom',\n 'accept-incoming',\n 'three-way-merge',\n ]).default('three-way-merge').describe('How to handle customer customizations'),\n\n /** Whether to run in dry-run mode (preview only, no changes) */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Whether to skip pre-upgrade validation */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\n\n/**\n * Upgrade Phase\n * Current phase of the upgrade process.\n */\nexport const UpgradePhaseSchema = z.enum([\n 'pending', // Upgrade requested but not started\n 'analyzing', // Generating upgrade plan\n 'snapshot', // Creating pre-upgrade snapshot\n 'executing', // Applying metadata changes\n 'migrating', // Running migration scripts\n 'validating', // Post-upgrade validation\n 'completed', // Upgrade completed successfully\n 'failed', // Upgrade failed\n 'rolling-back', // Rollback in progress\n 'rolled-back', // Rollback completed\n]).describe('Current phase of the upgrade process');\n\n/**\n * Upgrade Package Response\n */\nexport const UpgradePackageResponseSchema = z.object({\n /** Whether the upgrade was successful */\n success: z.boolean().describe('Whether the upgrade succeeded'),\n\n /** Current upgrade phase */\n phase: UpgradePhaseSchema.describe('Current upgrade phase'),\n\n /** The upgrade plan that was executed */\n plan: UpgradePlanSchema.optional().describe('Upgrade plan'),\n\n /** Snapshot ID for rollback */\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n\n /** Merge conflicts that need manual resolution (if any) */\n conflicts: z.array(z.object({\n path: z.string(),\n baseValue: z.unknown(),\n incomingValue: z.unknown(),\n customValue: z.unknown(),\n })).optional().describe('Unresolved merge conflicts'),\n\n /** Error message (if failed) */\n errorMessage: z.string().optional().describe('Error message if upgrade failed'),\n\n /** Human-readable summary */\n message: z.string().optional().describe('Human-readable status message'),\n}).describe('Upgrade package response');\n\n// ==========================================\n// Rollback\n// ==========================================\n\n/**\n * Rollback Package Request\n */\nexport const RollbackPackageRequestSchema = z.object({\n /** Package ID to rollback */\n packageId: z.string().describe('Package ID to rollback'),\n\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\n\n/**\n * Rollback Package Response\n */\nexport const RollbackPackageResponseSchema = z.object({\n /** Whether the rollback was successful */\n success: z.boolean().describe('Whether the rollback succeeded'),\n\n /** Restored version */\n restoredVersion: z.string().optional().describe('Version restored to'),\n\n /** Message */\n message: z.string().optional().describe('Rollback status message'),\n}).describe('Rollback package response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type MetadataChangeType = z.infer;\nexport type MetadataDiffItem = z.infer;\nexport type UpgradeImpactLevel = z.infer;\nexport type UpgradePlan = z.infer;\nexport type UpgradeSnapshot = z.infer;\nexport type UpgradePackageRequest = z.infer;\nexport type UpgradePhase = z.infer;\nexport type UpgradePackageResponse = z.infer;\nexport type RollbackPackageRequest = z.infer;\nexport type RollbackPackageResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Advanced Plugin Lifecycle Protocol\n * \n * Defines advanced lifecycle management capabilities including:\n * - Hot reload and live updates\n * - Graceful degradation and fallback mechanisms\n * - Health monitoring and auto-recovery\n * - State preservation during updates\n * \n * This protocol extends the basic plugin lifecycle with enterprise-grade\n * features for production environments.\n */\n\n/**\n * Plugin Health Status\n * Represents the current operational state of a plugin\n */\nexport const PluginHealthStatusSchema = z.enum([\n 'healthy', // Plugin is operating normally\n 'degraded', // Plugin is operational but with reduced functionality\n 'unhealthy', // Plugin has critical issues but still running\n 'failed', // Plugin has failed and is not operational\n 'recovering', // Plugin is in recovery process\n 'unknown', // Health status cannot be determined\n]).describe('Current health status of the plugin');\n\n/**\n * Plugin Health Check Configuration\n * Defines how to check plugin health\n */\nexport const PluginHealthCheckSchema = z.object({\n /**\n * Health check interval in milliseconds\n */\n interval: z.number().int().min(1000).default(30000)\n .describe('How often to perform health checks (default: 30s)'),\n \n /**\n * Timeout for health check in milliseconds\n */\n timeout: z.number().int().min(100).default(5000)\n .describe('Maximum time to wait for health check response'),\n \n /**\n * Number of consecutive failures before marking as unhealthy\n */\n failureThreshold: z.number().int().min(1).default(3)\n .describe('Consecutive failures needed to mark unhealthy'),\n \n /**\n * Number of consecutive successes to recover from unhealthy state\n */\n successThreshold: z.number().int().min(1).default(1)\n .describe('Consecutive successes needed to mark healthy'),\n \n /**\n * Custom health check function name or endpoint\n */\n checkMethod: z.string().optional()\n .describe('Method name to call for health check'),\n \n /**\n * Enable automatic restart on failure\n */\n autoRestart: z.boolean().default(false)\n .describe('Automatically restart plugin on health check failure'),\n \n /**\n * Maximum number of restart attempts\n */\n maxRestartAttempts: z.number().int().min(0).default(3)\n .describe('Maximum restart attempts before giving up'),\n \n /**\n * Backoff strategy for restarts\n */\n restartBackoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential')\n .describe('Backoff strategy for restart delays'),\n});\n\n/**\n * Plugin Health Report\n * Detailed health information from a plugin\n */\nexport const PluginHealthReportSchema = z.object({\n /**\n * Overall health status\n */\n status: PluginHealthStatusSchema,\n \n /**\n * Timestamp of the health check\n */\n timestamp: z.string().datetime(),\n \n /**\n * Human-readable message about health status\n */\n message: z.string().optional(),\n \n /**\n * Detailed metrics\n */\n metrics: z.object({\n uptime: z.number().describe('Plugin uptime in milliseconds'),\n memoryUsage: z.number().optional().describe('Memory usage in bytes'),\n cpuUsage: z.number().optional().describe('CPU usage percentage'),\n activeConnections: z.number().optional().describe('Number of active connections'),\n errorRate: z.number().optional().describe('Error rate (errors per minute)'),\n responseTime: z.number().optional().describe('Average response time in ms'),\n }).partial().optional(),\n \n /**\n * List of checks performed\n */\n checks: z.array(z.object({\n name: z.string().describe('Check name'),\n status: z.enum(['passed', 'failed', 'warning']),\n message: z.string().optional(),\n data: z.record(z.string(), z.unknown()).optional(),\n })).optional(),\n \n /**\n * Dependencies health\n */\n dependencies: z.array(z.object({\n pluginId: z.string(),\n status: PluginHealthStatusSchema,\n message: z.string().optional(),\n })).optional(),\n});\n\n/**\n * Distributed State Configuration\n * Configuration for distributed state management in cluster environments\n */\nexport const DistributedStateConfigSchema = z.object({\n /**\n * Distributed cache provider\n */\n provider: z.enum(['redis', 'etcd', 'custom'])\n .describe('Distributed state backend provider'),\n \n /**\n * Connection URL or endpoints\n */\n endpoints: z.array(z.string()).optional()\n .describe('Backend connection endpoints'),\n \n /**\n * Key prefix for namespacing\n */\n keyPrefix: z.string().optional()\n .describe('Prefix for all keys (e.g., \"plugin:my-plugin:\")'),\n \n /**\n * Time to live in seconds\n */\n ttl: z.number().int().min(0).optional()\n .describe('State expiration time in seconds'),\n \n /**\n * Authentication configuration\n */\n auth: z.object({\n username: z.string().optional(),\n password: z.string().optional(),\n token: z.string().optional(),\n certificate: z.string().optional(),\n }).optional(),\n \n /**\n * Replication settings\n */\n replication: z.object({\n enabled: z.boolean().default(true),\n minReplicas: z.number().int().min(1).default(1),\n }).optional(),\n \n /**\n * Custom provider configuration\n */\n customConfig: z.record(z.string(), z.unknown()).optional()\n .describe('Provider-specific configuration'),\n});\n\n/**\n * Hot Reload Configuration\n * Controls how plugins handle live updates\n */\nexport const HotReloadConfigSchema = z.object({\n /**\n * Enable hot reload capability\n */\n enabled: z.boolean().default(false),\n \n /**\n * Watch file patterns for auto-reload\n */\n watchPatterns: z.array(z.string()).optional()\n .describe('Glob patterns to watch for changes'),\n \n /**\n * Debounce delay before reloading (milliseconds)\n */\n debounceDelay: z.number().int().min(0).default(1000)\n .describe('Wait time after change detection before reload'),\n \n /**\n * Preserve plugin state during reload\n */\n preserveState: z.boolean().default(true)\n .describe('Keep plugin state across reloads'),\n \n /**\n * State serialization strategy\n */\n stateStrategy: z.enum(['memory', 'disk', 'distributed', 'none']).default('memory')\n .describe('How to preserve state during reload'),\n \n /**\n * Distributed state configuration (required when stateStrategy is \"distributed\")\n */\n distributedConfig: DistributedStateConfigSchema.optional()\n .describe('Configuration for distributed state management'),\n \n /**\n * Graceful shutdown timeout\n */\n shutdownTimeout: z.number().int().min(0).default(30000)\n .describe('Maximum time to wait for graceful shutdown'),\n \n /**\n * Pre-reload hooks\n */\n beforeReload: z.array(z.string()).optional()\n .describe('Hook names to call before reload'),\n \n /**\n * Post-reload hooks\n */\n afterReload: z.array(z.string()).optional()\n .describe('Hook names to call after reload'),\n});\n\n/**\n * Graceful Degradation Configuration\n * Defines how plugin degrades when dependencies fail\n */\nexport const GracefulDegradationSchema = z.object({\n /**\n * Enable graceful degradation\n */\n enabled: z.boolean().default(true),\n \n /**\n * Fallback mode when dependencies fail\n */\n fallbackMode: z.enum([\n 'minimal', // Provide minimal functionality\n 'cached', // Use cached data\n 'readonly', // Allow read-only operations\n 'offline', // Offline mode with local data\n 'disabled', // Disable plugin functionality\n ]).default('minimal'),\n \n /**\n * Critical dependencies that must be available\n */\n criticalDependencies: z.array(z.string()).optional()\n .describe('Plugin IDs that are required for operation'),\n \n /**\n * Optional dependencies that can fail\n */\n optionalDependencies: z.array(z.string()).optional()\n .describe('Plugin IDs that are nice to have but not required'),\n \n /**\n * Feature flags for degraded mode\n */\n degradedFeatures: z.array(z.object({\n feature: z.string().describe('Feature name'),\n enabled: z.boolean().describe('Whether feature is available in degraded mode'),\n reason: z.string().optional(),\n })).optional(),\n \n /**\n * Automatic recovery attempts\n */\n autoRecovery: z.object({\n enabled: z.boolean().default(true),\n retryInterval: z.number().int().min(1000).default(60000)\n .describe('Interval between recovery attempts (ms)'),\n maxAttempts: z.number().int().min(0).default(5)\n .describe('Maximum recovery attempts before giving up'),\n }).optional(),\n});\n\n/**\n * Plugin Update Strategy\n * Defines how plugin handles version updates\n */\nexport const PluginUpdateStrategySchema = z.object({\n /**\n * Update mode\n */\n mode: z.enum([\n 'manual', // Manual updates only\n 'automatic', // Automatic updates\n 'scheduled', // Scheduled update windows\n 'rolling', // Rolling updates with zero downtime\n ]).default('manual'),\n \n /**\n * Version constraints for automatic updates\n */\n autoUpdateConstraints: z.object({\n major: z.boolean().default(false).describe('Allow major version updates'),\n minor: z.boolean().default(true).describe('Allow minor version updates'),\n patch: z.boolean().default(true).describe('Allow patch version updates'),\n }).optional(),\n \n /**\n * Update schedule (for scheduled mode)\n */\n schedule: z.object({\n /**\n * Cron expression for update window\n */\n cron: z.string().optional(),\n \n /**\n * Timezone for schedule\n */\n timezone: z.string().default('UTC'),\n \n /**\n * Maintenance window duration in minutes\n */\n maintenanceWindow: z.number().int().min(1).default(60),\n }).optional(),\n \n /**\n * Rollback configuration\n */\n rollback: z.object({\n enabled: z.boolean().default(true),\n \n /**\n * Automatic rollback on failure\n */\n automatic: z.boolean().default(true),\n \n /**\n * Keep N previous versions for rollback\n */\n keepVersions: z.number().int().min(1).default(3),\n \n /**\n * Rollback timeout in milliseconds\n */\n timeout: z.number().int().min(1000).default(30000),\n }).optional(),\n \n /**\n * Pre-update validation\n */\n validation: z.object({\n /**\n * Run compatibility checks before update\n */\n checkCompatibility: z.boolean().default(true),\n \n /**\n * Run tests before applying update\n */\n runTests: z.boolean().default(false),\n \n /**\n * Test suite to run\n */\n testSuite: z.string().optional(),\n }).optional(),\n});\n\n/**\n * Plugin State Snapshot\n * Captures plugin state for preservation during updates/reloads\n */\nexport const PluginStateSnapshotSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Version at time of snapshot\n */\n version: z.string(),\n \n /**\n * Snapshot timestamp\n */\n timestamp: z.string().datetime(),\n \n /**\n * Serialized state data\n */\n state: z.record(z.string(), z.unknown()),\n \n /**\n * State metadata\n */\n metadata: z.object({\n checksum: z.string().optional().describe('State checksum for verification'),\n compressed: z.boolean().default(false),\n encryption: z.string().optional().describe('Encryption algorithm if encrypted'),\n }).optional(),\n});\n\n/**\n * Advanced Plugin Lifecycle Configuration\n * Complete configuration for advanced lifecycle management\n */\nexport const AdvancedPluginLifecycleConfigSchema = z.object({\n /**\n * Health monitoring configuration\n */\n health: PluginHealthCheckSchema.optional(),\n \n /**\n * Hot reload configuration\n */\n hotReload: HotReloadConfigSchema.optional(),\n \n /**\n * Graceful degradation configuration\n */\n degradation: GracefulDegradationSchema.optional(),\n \n /**\n * Update strategy\n */\n updates: PluginUpdateStrategySchema.optional(),\n \n /**\n * Resource limits\n */\n resources: z.object({\n maxMemory: z.number().int().optional().describe('Maximum memory in bytes'),\n maxCpu: z.number().min(0).max(100).optional().describe('Maximum CPU percentage'),\n maxConnections: z.number().int().optional().describe('Maximum concurrent connections'),\n timeout: z.number().int().optional().describe('Operation timeout in milliseconds'),\n }).optional(),\n \n /**\n * Monitoring and observability\n */\n observability: z.object({\n enableMetrics: z.boolean().default(true),\n enableTracing: z.boolean().default(true),\n enableProfiling: z.boolean().default(false),\n metricsInterval: z.number().int().min(1000).default(60000)\n .describe('Metrics collection interval in ms'),\n }).optional(),\n});\n\n// Export types\nexport type PluginHealthStatus = z.infer;\nexport type PluginHealthCheck = z.infer;\nexport type PluginHealthReport = z.infer;\nexport type DistributedStateConfig = z.infer;\nexport type HotReloadConfig = z.infer;\nexport type GracefulDegradation = z.infer;\nexport type PluginUpdateStrategy = z.infer;\nexport type PluginStateSnapshot = z.infer;\nexport type AdvancedPluginLifecycleConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Plugin Lifecycle Events Protocol\n * \n * Zod schemas for plugin lifecycle event data structures.\n * These schemas align with the IPluginLifecycleEvents contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Event Payload Schemas\n// ============================================================================\n\n/**\n * Event Phase Enum\n * Lifecycle phase where an error occurred\n */\nexport const EventPhaseSchema = z.enum(['init', 'start', 'destroy'])\n .describe('Plugin lifecycle phase');\n\nexport type EventPhase = z.infer;\n\n/**\n * Plugin Event Base Schema\n * Common fields for all plugin events\n */\nexport const PluginEventBaseSchema = z.object({\n /**\n * Plugin name\n */\n pluginName: z.string().describe('Name of the plugin'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds when event occurred'),\n});\n\n/**\n * Plugin Registered Event Schema\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"version\": \"1.0.0\"\n * }\n */\nexport const PluginRegisteredEventSchema = PluginEventBaseSchema.extend({\n /**\n * Plugin version (optional)\n */\n version: z.string().optional().describe('Plugin version'),\n});\n\nexport type PluginRegisteredEvent = z.infer;\n\n/**\n * Plugin Lifecycle Phase Event Schema\n * For init, start, destroy phases\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"duration\": 1250,\n * \"phase\": \"init\"\n * }\n */\nexport const PluginLifecyclePhaseEventSchema = PluginEventBaseSchema.extend({\n /**\n * Duration of the phase (milliseconds)\n */\n duration: z.number().min(0).optional().describe('Duration of the lifecycle phase in milliseconds'),\n \n /**\n * Lifecycle phase\n */\n phase: EventPhaseSchema.optional().describe('Lifecycle phase'),\n});\n\nexport type PluginLifecyclePhaseEvent = z.infer;\n\n/**\n * Plugin Error Event Schema\n * When a plugin encounters an error\n * \n * @example\n * {\n * \"pluginName\": \"crm-plugin\",\n * \"timestamp\": 1706659200000,\n * \"error\": Error(\"Connection failed\"),\n * \"phase\": \"start\",\n * \"errorMessage\": \"Connection failed\",\n * \"errorStack\": \"Error: Connection failed\\n at ...\"\n * }\n */\nexport const PluginErrorEventSchema = PluginEventBaseSchema.extend({\n /**\n * Error object\n */\n error: z.object({\n name: z.string().describe('Error class name'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n code: z.string().optional().describe('Error code'),\n }).describe('Serializable error representation'),\n \n /**\n * Lifecycle phase where error occurred\n */\n phase: EventPhaseSchema.describe('Lifecycle phase where error occurred'),\n \n /**\n * Error message (for serialization)\n */\n errorMessage: z.string().optional().describe('Error message'),\n \n /**\n * Error stack trace (for debugging)\n */\n errorStack: z.string().optional().describe('Error stack trace'),\n});\n\nexport type PluginErrorEvent = z.infer;\n\n// ============================================================================\n// Service Event Schemas\n// ============================================================================\n\n/**\n * Service Registered Event Schema\n * \n * @example\n * {\n * \"serviceName\": \"database\",\n * \"timestamp\": 1706659200000,\n * \"serviceType\": \"IDataEngine\"\n * }\n */\nexport const ServiceRegisteredEventSchema = z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Name of the registered service'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Service type (optional)\n */\n serviceType: z.string().optional().describe('Type or interface name of the service'),\n});\n\nexport type ServiceRegisteredEvent = z.infer;\n\n/**\n * Service Unregistered Event Schema\n * \n * @example\n * {\n * \"serviceName\": \"database\",\n * \"timestamp\": 1706659200000\n * }\n */\nexport const ServiceUnregisteredEventSchema = z.object({\n /**\n * Service name\n */\n serviceName: z.string().describe('Name of the unregistered service'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n});\n\nexport type ServiceUnregisteredEvent = z.infer;\n\n// ============================================================================\n// Hook Event Schemas\n// ============================================================================\n\n/**\n * Hook Registered Event Schema\n * \n * @example\n * {\n * \"hookName\": \"data.beforeInsert\",\n * \"timestamp\": 1706659200000,\n * \"handlerCount\": 3\n * }\n */\nexport const HookRegisteredEventSchema = z.object({\n /**\n * Hook name\n */\n hookName: z.string().describe('Name of the hook'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Number of handlers registered for this hook\n */\n handlerCount: z.number().int().min(0).describe('Number of handlers registered for this hook'),\n});\n\nexport type HookRegisteredEvent = z.infer;\n\n/**\n * Hook Triggered Event Schema\n * \n * @example\n * {\n * \"hookName\": \"data.beforeInsert\",\n * \"timestamp\": 1706659200000,\n * \"args\": [{ \"object\": \"customer\", \"data\": {...} }],\n * \"handlerCount\": 3\n * }\n */\nexport const HookTriggeredEventSchema = z.object({\n /**\n * Hook name\n */\n hookName: z.string().describe('Name of the hook'),\n \n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n \n /**\n * Arguments passed to the hook\n */\n args: z.array(z.unknown()).describe('Arguments passed to the hook handlers'),\n \n /**\n * Number of handlers that will handle this event\n */\n handlerCount: z.number().int().min(0).optional().describe('Number of handlers that will handle this event'),\n});\n\nexport type HookTriggeredEvent = z.infer;\n\n// ============================================================================\n// Kernel Event Schemas\n// ============================================================================\n\n/**\n * Kernel Event Base Schema\n * Common fields for kernel events\n */\nexport const KernelEventBaseSchema = z.object({\n /**\n * Event timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds'),\n});\n\n/**\n * Kernel Ready Event Schema\n * \n * @example\n * {\n * \"timestamp\": 1706659200000,\n * \"duration\": 5400,\n * \"pluginCount\": 12\n * }\n */\nexport const KernelReadyEventSchema = KernelEventBaseSchema.extend({\n /**\n * Total initialization duration (milliseconds)\n */\n duration: z.number().min(0).optional().describe('Total initialization duration in milliseconds'),\n \n /**\n * Number of plugins initialized\n */\n pluginCount: z.number().int().min(0).optional().describe('Number of plugins initialized'),\n});\n\nexport type KernelReadyEvent = z.infer;\n\n/**\n * Kernel Shutdown Event Schema\n * \n * @example\n * {\n * \"timestamp\": 1706659200000,\n * \"reason\": \"SIGTERM received\"\n * }\n */\nexport const KernelShutdownEventSchema = KernelEventBaseSchema.extend({\n /**\n * Shutdown reason (optional)\n */\n reason: z.string().optional().describe('Reason for kernel shutdown'),\n});\n\nexport type KernelShutdownEvent = z.infer;\n\n// ============================================================================\n// Event Type Registry\n// ============================================================================\n\n/**\n * Plugin Lifecycle Event Type Enum\n * All possible plugin lifecycle event types\n */\nexport const PluginLifecycleEventType = z.enum([\n 'kernel:ready',\n 'kernel:shutdown',\n 'kernel:before-init',\n 'kernel:after-init',\n 'plugin:registered',\n 'plugin:before-init',\n 'plugin:init',\n 'plugin:after-init',\n 'plugin:before-start',\n 'plugin:started',\n 'plugin:after-start',\n 'plugin:before-destroy',\n 'plugin:destroyed',\n 'plugin:after-destroy',\n 'plugin:error',\n 'service:registered',\n 'service:unregistered',\n 'hook:registered',\n 'hook:triggered',\n]).describe('Plugin lifecycle event type');\n\nexport type PluginLifecycleEventType = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Runtime Management Protocol\n * \n * Defines the protocol for dynamic plugin loading, unloading, and discovery\n * at runtime. Addresses the \"Dynamic Loading\" gap in the microkernel architecture\n * by enabling plugins to be loaded and unloaded without restarting the kernel.\n * \n * Inspired by:\n * - OSGi Dynamic Module System (bundle lifecycle)\n * - Kubernetes Operator pattern (reconciliation loop)\n * - VS Code Extension Host (activation events)\n * \n * This protocol enables:\n * - Runtime load/unload of plugins without kernel restart\n * - Plugin discovery from registries and local filesystem\n * - Activation events (load plugin only when needed)\n * - Safe unload with dependency awareness\n */\n\n/**\n * Dynamic Plugin Operation Type\n * Operations that can be performed on plugins at runtime\n */\nexport const DynamicPluginOperationSchema = z.enum([\n 'load', // Load and initialize a plugin at runtime\n 'unload', // Gracefully unload a running plugin\n 'reload', // Unload then load (e.g., version upgrade)\n 'enable', // Enable a loaded but disabled plugin\n 'disable', // Disable a running plugin without unloading\n]).describe('Runtime plugin operation type');\n\n/**\n * Plugin Source\n * Where to resolve a plugin for dynamic loading\n */\nexport const PluginSourceSchema = z.object({\n /**\n * Source type\n */\n type: z.enum([\n 'npm', // npm registry package\n 'local', // Local filesystem path\n 'url', // Remote URL (tarball or module)\n 'registry', // ObjectStack plugin registry\n 'git', // Git repository\n ]).describe('Plugin source type'),\n \n /**\n * Source location (package name, path, URL, or git repo)\n */\n location: z.string().describe('Package name, file path, URL, or git repository'),\n \n /**\n * Version constraint (semver range)\n */\n version: z.string().optional().describe('Semver version range (e.g., \"^1.0.0\")'),\n \n /**\n * Integrity hash for verification\n */\n integrity: z.string().optional().describe('Subresource Integrity hash (e.g., \"sha384-...\")'),\n}).describe('Plugin source location for dynamic resolution');\n\n/**\n * Activation Event\n * Defines when a dynamically available plugin should be activated.\n * Plugins remain dormant until an activation event fires.\n */\nexport const ActivationEventSchema = z.object({\n /**\n * Event type\n */\n type: z.enum([\n 'onCommand', // Activate when a specific command is executed\n 'onRoute', // Activate when a URL route is matched\n 'onObject', // Activate when a specific object type is accessed\n 'onEvent', // Activate when a system event fires\n 'onService', // Activate when a service is requested\n 'onSchedule', // Activate on a cron schedule\n 'onStartup', // Activate immediately on kernel startup\n ]).describe('Trigger type for lazy activation'),\n \n /**\n * Pattern to match (command name, route glob, object name, event pattern, etc.)\n */\n pattern: z.string().describe('Match pattern for the activation trigger'),\n}).describe('Lazy activation trigger for a dynamic plugin');\n\n/**\n * Dynamic Load Request\n * Request to load a plugin at runtime\n */\nexport const DynamicLoadRequestSchema = z.object({\n /**\n * Plugin identifier to load\n */\n pluginId: z.string().describe('Unique plugin identifier'),\n \n /**\n * Plugin source\n */\n source: PluginSourceSchema,\n \n /**\n * Activation events (if omitted, plugin activates immediately)\n */\n activationEvents: z.array(ActivationEventSchema).optional()\n .describe('Lazy activation triggers; if omitted plugin starts immediately'),\n \n /**\n * Configuration overrides for the plugin\n */\n config: z.record(z.string(), z.unknown()).optional()\n .describe('Runtime configuration overrides'),\n \n /**\n * Loading priority (lower = higher priority)\n */\n priority: z.number().int().min(0).default(100)\n .describe('Loading priority (lower is higher)'),\n \n /**\n * Whether to enable sandboxing for this dynamically loaded plugin\n */\n sandbox: z.boolean().default(false)\n .describe('Run in an isolated sandbox'),\n \n /**\n * Timeout for the load operation in milliseconds\n */\n timeout: z.number().int().min(1000).default(60000)\n .describe('Maximum time to complete loading in ms'),\n}).describe('Request to dynamically load a plugin at runtime');\n\n/**\n * Dynamic Unload Request\n * Request to unload a plugin at runtime\n */\nexport const DynamicUnloadRequestSchema = z.object({\n /**\n * Plugin identifier to unload\n */\n pluginId: z.string().describe('Plugin to unload'),\n \n /**\n * Unload strategy\n */\n strategy: z.enum([\n 'graceful', // Wait for in-flight requests, then unload\n 'forceful', // Unload immediately, cancel pending work\n 'drain', // Stop accepting new work, finish existing, then unload\n ]).default('graceful').describe('How to handle in-flight work during unload'),\n \n /**\n * Timeout for the unload operation in milliseconds\n */\n timeout: z.number().int().min(1000).default(30000)\n .describe('Maximum time to complete unloading in ms'),\n \n /**\n * Whether to remove cached artifacts\n */\n cleanupCache: z.boolean().default(false)\n .describe('Remove cached code and assets after unload'),\n \n /**\n * Action for dependents: plugins that depend on this one\n */\n dependentAction: z.enum([\n 'cascade', // Also unload dependent plugins\n 'warn', // Warn about dependents but proceed\n 'block', // Block unload if dependents exist\n ]).default('block').describe('How to handle plugins that depend on this one'),\n}).describe('Request to dynamically unload a plugin at runtime');\n\n/**\n * Dynamic Plugin Operation Result\n * Result of a dynamic load/unload/reload operation\n */\nexport const DynamicPluginResultSchema = z.object({\n /**\n * Whether the operation succeeded\n */\n success: z.boolean(),\n \n /**\n * The operation that was performed\n */\n operation: DynamicPluginOperationSchema,\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Operation duration in milliseconds\n */\n durationMs: z.number().int().min(0).optional(),\n \n /**\n * Resulting plugin version (for load/reload)\n */\n version: z.string().optional(),\n \n /**\n * Error details if operation failed\n */\n error: z.object({\n code: z.string().describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n details: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n \n /**\n * Warnings (e.g., dependents affected)\n */\n warnings: z.array(z.string()).optional(),\n}).describe('Result of a dynamic plugin operation');\n\n/**\n * Plugin Discovery Source\n * Defines where to discover available plugins at runtime\n */\nexport const PluginDiscoverySourceSchema = z.object({\n /**\n * Discovery source type\n */\n type: z.enum([\n 'registry', // ObjectStack plugin registry API\n 'npm', // npm registry search\n 'directory', // Local filesystem directory scan\n 'url', // Remote manifest URL\n ]).describe('Discovery source type'),\n \n /**\n * Source endpoint or path\n */\n endpoint: z.string().describe('Registry URL, directory path, or manifest URL'),\n \n /**\n * Polling interval in milliseconds (0 = manual only)\n */\n pollInterval: z.number().int().min(0).default(0)\n .describe('How often to re-scan for new plugins (0 = manual)'),\n \n /**\n * Filter criteria for discovered plugins\n */\n filter: z.object({\n /**\n * Only discover plugins matching these tags\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Only discover plugins from these vendors\n */\n vendors: z.array(z.string()).optional(),\n \n /**\n * Minimum trust level\n */\n minTrustLevel: z.enum(['verified', 'trusted', 'community', 'untrusted']).optional(),\n }).optional(),\n}).describe('Source for runtime plugin discovery');\n\n/**\n * Plugin Discovery Configuration\n * Controls how the kernel discovers available plugins at runtime\n */\nexport const PluginDiscoveryConfigSchema = z.object({\n /**\n * Enable runtime plugin discovery\n */\n enabled: z.boolean().default(false),\n \n /**\n * Discovery sources\n */\n sources: z.array(PluginDiscoverySourceSchema).default([]),\n \n /**\n * Auto-load discovered plugins matching criteria\n */\n autoLoad: z.boolean().default(false)\n .describe('Automatically load newly discovered plugins'),\n \n /**\n * Require approval before loading discovered plugins\n */\n requireApproval: z.boolean().default(true)\n .describe('Require admin approval before loading discovered plugins'),\n}).describe('Runtime plugin discovery configuration');\n\n/**\n * Dynamic Loading Configuration\n * Top-level configuration for the dynamic plugin loading subsystem\n */\nexport const DynamicLoadingConfigSchema = z.object({\n /**\n * Enable dynamic loading/unloading at runtime\n */\n enabled: z.boolean().default(false)\n .describe('Enable runtime load/unload of plugins'),\n \n /**\n * Maximum number of dynamically loaded plugins\n */\n maxDynamicPlugins: z.number().int().min(1).default(50)\n .describe('Upper limit on runtime-loaded plugins'),\n \n /**\n * Plugin discovery configuration\n */\n discovery: PluginDiscoveryConfigSchema.optional(),\n \n /**\n * Default sandbox policy for dynamically loaded plugins\n */\n defaultSandbox: z.boolean().default(true)\n .describe('Sandbox dynamically loaded plugins by default'),\n \n /**\n * Allowed plugin sources (empty = all allowed)\n */\n allowedSources: z.array(z.enum(['npm', 'local', 'url', 'registry', 'git'])).optional()\n .describe('Restrict which source types are permitted'),\n \n /**\n * Require integrity verification for remote plugins\n */\n requireIntegrity: z.boolean().default(true)\n .describe('Require integrity hash verification for remote sources'),\n \n /**\n * Global timeout for dynamic operations in milliseconds\n */\n operationTimeout: z.number().int().min(1000).default(60000)\n .describe('Default timeout for load/unload operations in ms'),\n}).describe('Dynamic plugin loading subsystem configuration');\n\n// Export types\nexport type DynamicPluginOperation = z.infer;\nexport type PluginSource = z.infer;\nexport type ActivationEvent = z.infer;\nexport type DynamicLoadRequest = z.infer;\nexport type DynamicUnloadRequest = z.infer;\nexport type DynamicPluginResult = z.infer;\nexport type PluginDiscoverySource = z.infer;\nexport type PluginDiscoveryConfig = z.infer;\nexport type DynamicLoadingConfig = z.infer;\n\n// Export input types for schemas with defaults\nexport type DynamicLoadRequestInput = z.input;\nexport type DynamicUnloadRequestInput = z.input;\nexport type DynamicLoadingConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Security and Sandboxing Protocol\n * \n * Defines comprehensive security mechanisms for plugin isolation, permission\n * management, and threat protection in the ObjectStack ecosystem.\n * \n * Features:\n * - Fine-grained permission system\n * - Resource access control\n * - Sandboxing and isolation\n * - Security scanning and verification\n * - Runtime security monitoring\n */\n\n/**\n * Permission Scope\n * Defines the scope of a permission\n */\nexport const PermissionScopeSchema = z.enum([\n 'global', // Applies to entire system\n 'tenant', // Applies to specific tenant\n 'user', // Applies to specific user\n 'resource', // Applies to specific resource\n 'plugin', // Applies within plugin boundaries\n]).describe('Scope of permission application');\n\n/**\n * Permission Action\n * Standard CRUD + extended actions\n */\nexport const PermissionActionSchema = z.enum([\n 'create', // Create new resources\n 'read', // Read existing resources\n 'update', // Update existing resources\n 'delete', // Delete resources\n 'execute', // Execute operations/functions\n 'manage', // Full management rights\n 'configure', // Configuration changes\n 'share', // Share with others\n 'export', // Export data\n 'import', // Import data\n 'admin', // Administrative access\n]).describe('Type of action being permitted');\n\n/**\n * Resource Type\n * Types of resources that can be accessed\n */\nexport const ResourceTypeSchema = z.enum([\n 'data.object', // ObjectQL objects\n 'data.record', // Individual records\n 'data.field', // Specific fields\n 'ui.view', // UI views\n 'ui.dashboard', // Dashboards\n 'ui.report', // Reports\n 'system.config', // System configuration\n 'system.plugin', // Other plugins\n 'system.api', // API endpoints\n 'system.service', // System services\n 'storage.file', // File storage\n 'storage.database', // Database access\n 'network.http', // HTTP requests\n 'network.websocket', // WebSocket connections\n 'process.spawn', // Process spawning\n 'process.env', // Environment variables\n]).describe('Type of resource being accessed');\n\n/**\n * Permission Definition\n * Defines a single permission requirement\n */\nexport const PermissionSchema = z.object({\n /**\n * Permission identifier\n */\n id: z.string().describe('Unique permission identifier'),\n \n /**\n * Resource type\n */\n resource: ResourceTypeSchema,\n \n /**\n * Allowed actions\n */\n actions: z.array(PermissionActionSchema),\n \n /**\n * Permission scope\n */\n scope: PermissionScopeSchema.default('plugin'),\n \n /**\n * Resource filter\n */\n filter: z.object({\n /**\n * Specific resource IDs\n */\n resourceIds: z.array(z.string()).optional(),\n \n /**\n * Filter condition\n */\n condition: z.string().optional().describe('Filter expression (e.g., owner = currentUser)'),\n \n /**\n * Field-level access\n */\n fields: z.array(z.string()).optional().describe('Allowed fields for data resources'),\n }).optional(),\n \n /**\n * Human-readable description\n */\n description: z.string(),\n \n /**\n * Whether this permission is required or optional\n */\n required: z.boolean().default(true),\n \n /**\n * Justification for permission\n */\n justification: z.string().optional().describe('Why this permission is needed'),\n});\n\n/**\n * Permission Set\n * Collection of permissions for a plugin\n */\nexport const PermissionSetSchema = z.object({\n /**\n * All permissions required by plugin\n */\n permissions: z.array(PermissionSchema),\n \n /**\n * Permission groups for easier management\n */\n groups: z.array(z.object({\n name: z.string().describe('Group name'),\n description: z.string(),\n permissions: z.array(z.string()).describe('Permission IDs in this group'),\n })).optional(),\n \n /**\n * Default grant strategy\n */\n defaultGrant: z.enum([\n 'prompt', // Always prompt user\n 'allow', // Allow by default\n 'deny', // Deny by default\n 'inherit', // Inherit from parent\n ]).default('prompt'),\n});\n\n/**\n * Runtime Configuration\n * Defines the execution environment for plugin isolation\n */\nexport const RuntimeConfigSchema = z.object({\n /**\n * Runtime engine type\n */\n engine: z.enum([\n 'v8-isolate', // V8 isolate-based isolation (lightweight, fast)\n 'wasm', // WebAssembly-based isolation (secure, portable)\n 'container', // Container-based isolation (Docker, podman)\n 'process', // Process-based isolation (traditional)\n ]).default('v8-isolate')\n .describe('Execution environment engine'),\n \n /**\n * Engine-specific configuration\n */\n engineConfig: z.object({\n /**\n * WASM-specific settings (when engine is \"wasm\")\n */\n wasm: z.object({\n /**\n * Maximum memory pages (64KB per page)\n */\n maxMemoryPages: z.number().int().min(1).max(65536).optional()\n .describe('Maximum WASM memory pages (64KB each)'),\n \n /**\n * Instruction execution limit\n */\n instructionLimit: z.number().int().min(1).optional()\n .describe('Maximum instructions before timeout'),\n \n /**\n * Enable SIMD instructions\n */\n enableSimd: z.boolean().default(false)\n .describe('Enable WebAssembly SIMD support'),\n \n /**\n * Enable threads\n */\n enableThreads: z.boolean().default(false)\n .describe('Enable WebAssembly threads'),\n \n /**\n * Enable bulk memory operations\n */\n enableBulkMemory: z.boolean().default(true)\n .describe('Enable bulk memory operations'),\n }).optional(),\n \n /**\n * Container-specific settings (when engine is \"container\")\n */\n container: z.object({\n /**\n * Container image\n */\n image: z.string().optional()\n .describe('Container image to use'),\n \n /**\n * Container runtime\n */\n runtime: z.enum(['docker', 'podman', 'containerd']).default('docker'),\n \n /**\n * Resource limits\n */\n resources: z.object({\n cpuLimit: z.string().optional().describe('CPU limit (e.g., \"0.5\", \"2\")'),\n memoryLimit: z.string().optional().describe('Memory limit (e.g., \"512m\", \"1g\")'),\n }).optional(),\n \n /**\n * Network mode\n */\n networkMode: z.enum(['none', 'bridge', 'host']).default('bridge'),\n }).optional(),\n \n /**\n * V8 Isolate-specific settings (when engine is \"v8-isolate\")\n */\n v8Isolate: z.object({\n /**\n * Heap size limit in MB\n */\n heapSizeMb: z.number().int().min(1).optional(),\n \n /**\n * Enable snapshot\n */\n enableSnapshot: z.boolean().default(true),\n }).optional(),\n }).optional(),\n \n /**\n * General resource limits (applies to all engines)\n */\n resourceLimits: z.object({\n /**\n * Maximum memory in bytes\n */\n maxMemory: z.number().int().optional()\n .describe('Maximum memory allocation'),\n \n /**\n * Maximum CPU percentage\n */\n maxCpu: z.number().min(0).max(100).optional()\n .describe('Maximum CPU usage percentage'),\n \n /**\n * Execution timeout in milliseconds\n */\n timeout: z.number().int().min(0).optional()\n .describe('Maximum execution time'),\n }).optional(),\n});\n\n/**\n * Sandbox Configuration\n * Defines how plugin is isolated\n */\nexport const SandboxConfigSchema = z.object({\n /**\n * Enable sandboxing\n */\n enabled: z.boolean().default(true),\n \n /**\n * Sandboxing level\n */\n level: z.enum([\n 'none', // No sandboxing\n 'minimal', // Basic isolation\n 'standard', // Standard sandboxing\n 'strict', // Strict isolation\n 'paranoid', // Maximum isolation\n ]).default('standard'),\n \n /**\n * Runtime environment configuration\n */\n runtime: RuntimeConfigSchema.optional()\n .describe('Execution environment and isolation settings'),\n \n /**\n * File system access\n */\n filesystem: z.object({\n mode: z.enum(['none', 'readonly', 'restricted', 'full']).default('restricted'),\n allowedPaths: z.array(z.string()).optional().describe('Whitelisted paths'),\n deniedPaths: z.array(z.string()).optional().describe('Blacklisted paths'),\n maxFileSize: z.number().int().optional().describe('Maximum file size in bytes'),\n }).optional(),\n \n /**\n * Network access\n */\n network: z.object({\n mode: z.enum(['none', 'local', 'restricted', 'full']).default('restricted'),\n allowedHosts: z.array(z.string()).optional().describe('Whitelisted hosts'),\n deniedHosts: z.array(z.string()).optional().describe('Blacklisted hosts'),\n allowedPorts: z.array(z.number()).optional().describe('Allowed port numbers'),\n maxConnections: z.number().int().optional(),\n }).optional(),\n \n /**\n * Process execution\n */\n process: z.object({\n allowSpawn: z.boolean().default(false).describe('Allow spawning child processes'),\n allowedCommands: z.array(z.string()).optional().describe('Whitelisted commands'),\n timeout: z.number().int().optional().describe('Process timeout in ms'),\n }).optional(),\n \n /**\n * Memory limits\n */\n memory: z.object({\n maxHeap: z.number().int().optional().describe('Maximum heap size in bytes'),\n maxStack: z.number().int().optional().describe('Maximum stack size in bytes'),\n }).optional(),\n \n /**\n * CPU limits\n */\n cpu: z.object({\n maxCpuPercent: z.number().min(0).max(100).optional(),\n maxThreads: z.number().int().optional(),\n }).optional(),\n \n /**\n * Environment variables\n */\n environment: z.object({\n mode: z.enum(['none', 'readonly', 'restricted', 'full']).default('readonly'),\n allowedVars: z.array(z.string()).optional(),\n deniedVars: z.array(z.string()).optional(),\n }).optional(),\n});\n\n/**\n * Security Vulnerability\n * Represents a known security vulnerability\n */\nexport const KernelSecurityVulnerabilitySchema = z.object({\n /**\n * CVE identifier\n */\n cve: z.string().optional(),\n \n /**\n * Vulnerability identifier\n */\n id: z.string(),\n \n /**\n * Severity level\n */\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),\n \n /**\n * Category (e.g., SAST, DAST, Dependency)\n */\n category: z.string().optional(),\n\n /**\n * Title\n */\n title: z.string(),\n \n /**\n * Location of the vulnerability\n */\n location: z.string().optional(),\n\n /**\n * Remediation steps\n */\n remediation: z.string().optional(),\n\n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Affected versions\n */\n affectedVersions: z.array(z.string()),\n \n /**\n * Fixed in versions\n */\n fixedIn: z.array(z.string()).optional(),\n \n /**\n * CVSS score\n */\n cvssScore: z.number().min(0).max(10).optional(),\n \n /**\n * Exploit availability\n */\n exploitAvailable: z.boolean().default(false),\n \n /**\n * Patch available\n */\n patchAvailable: z.boolean().default(false),\n \n /**\n * Workaround\n */\n workaround: z.string().optional(),\n \n /**\n * References\n */\n references: z.array(z.string()).optional(),\n \n /**\n * Discovered date\n */\n discoveredDate: z.string().datetime().optional(),\n \n /**\n * Published date\n */\n publishedDate: z.string().datetime().optional(),\n});\n\n/**\n * Security Scan Result\n * Result of security scanning\n */\nexport const KernelSecurityScanResultSchema = z.object({\n /**\n * Scan timestamp\n */\n timestamp: z.string().datetime(),\n \n /**\n * Scanner information\n */\n scanner: z.object({\n name: z.string(),\n version: z.string(),\n }),\n \n /**\n * Overall status\n */\n status: z.enum(['passed', 'failed', 'warning']),\n \n /**\n * Vulnerabilities found\n */\n vulnerabilities: z.array(KernelSecurityVulnerabilitySchema).optional(),\n \n /**\n * Code quality issues\n */\n codeIssues: z.array(z.object({\n severity: z.enum(['error', 'warning', 'info']),\n type: z.string().describe('Issue type (e.g., sql-injection, xss)'),\n file: z.string(),\n line: z.number().int().optional(),\n message: z.string(),\n suggestion: z.string().optional(),\n })).optional(),\n \n /**\n * Dependency vulnerabilities\n */\n dependencyVulnerabilities: z.array(z.object({\n package: z.string(),\n version: z.string(),\n vulnerability: KernelSecurityVulnerabilitySchema,\n })).optional(),\n \n /**\n * License compliance\n */\n licenseCompliance: z.object({\n status: z.enum(['compliant', 'non-compliant', 'unknown']),\n issues: z.array(z.object({\n package: z.string(),\n license: z.string(),\n reason: z.string(),\n })).optional(),\n }).optional(),\n \n /**\n * Summary statistics\n */\n summary: z.object({\n totalVulnerabilities: z.number().int(),\n criticalCount: z.number().int(),\n highCount: z.number().int(),\n mediumCount: z.number().int(),\n lowCount: z.number().int(),\n infoCount: z.number().int(),\n }),\n});\n\n/**\n * Security Policy\n * Defines security policies for plugin\n */\nexport const KernelSecurityPolicySchema = z.object({\n /**\n * Content Security Policy\n */\n csp: z.object({\n directives: z.record(z.string(), z.array(z.string())).optional(),\n reportOnly: z.boolean().default(false),\n }).optional(),\n \n /**\n * CORS policy\n */\n cors: z.object({\n allowedOrigins: z.array(z.string()),\n allowedMethods: z.array(z.string()),\n allowedHeaders: z.array(z.string()),\n allowCredentials: z.boolean().default(false),\n maxAge: z.number().int().optional(),\n }).optional(),\n \n /**\n * Rate limiting\n */\n rateLimit: z.object({\n enabled: z.boolean().default(true),\n maxRequests: z.number().int(),\n windowMs: z.number().int().describe('Time window in milliseconds'),\n strategy: z.enum(['fixed', 'sliding', 'token-bucket']).default('sliding'),\n }).optional(),\n \n /**\n * Authentication requirements\n */\n authentication: z.object({\n required: z.boolean().default(true),\n methods: z.array(z.enum(['jwt', 'oauth2', 'api-key', 'session', 'certificate'])),\n tokenExpiration: z.number().int().optional().describe('Token expiration in seconds'),\n }).optional(),\n \n /**\n * Encryption requirements\n */\n encryption: z.object({\n dataAtRest: z.boolean().default(false).describe('Encrypt data at rest'),\n dataInTransit: z.boolean().default(true).describe('Enforce HTTPS/TLS'),\n algorithm: z.string().optional().describe('Encryption algorithm'),\n minKeyLength: z.number().int().optional().describe('Minimum key length in bits'),\n }).optional(),\n \n /**\n * Audit logging\n */\n auditLog: z.object({\n enabled: z.boolean().default(true),\n events: z.array(z.string()).optional().describe('Events to log'),\n retention: z.number().int().optional().describe('Log retention in days'),\n }).optional(),\n});\n\n/**\n * Plugin Trust Level\n * Indicates trust level of plugin\n */\nexport const PluginTrustLevelSchema = z.enum([\n 'verified', // Official/verified plugin\n 'trusted', // Trusted third-party\n 'community', // Community plugin\n 'untrusted', // Unverified plugin\n 'blocked', // Blocked/malicious\n]).describe('Trust level of the plugin');\n\n/**\n * Plugin Security Manifest\n * Complete security information for plugin\n */\nexport const PluginSecurityManifestSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Trust level\n */\n trustLevel: PluginTrustLevelSchema,\n \n /**\n * Required permissions\n */\n permissions: PermissionSetSchema,\n \n /**\n * Sandbox configuration\n */\n sandbox: SandboxConfigSchema,\n \n /**\n * Security policy\n */\n policy: KernelSecurityPolicySchema.optional(),\n \n /**\n * Security scan results\n */\n scanResults: z.array(KernelSecurityScanResultSchema).optional(),\n \n /**\n * Known vulnerabilities\n */\n vulnerabilities: z.array(KernelSecurityVulnerabilitySchema).optional(),\n \n /**\n * Code signing\n */\n codeSigning: z.object({\n signed: z.boolean(),\n signature: z.string().optional(),\n certificate: z.string().optional(),\n algorithm: z.string().optional(),\n timestamp: z.string().datetime().optional(),\n }).optional(),\n \n /**\n * Security certifications\n */\n certifications: z.array(z.object({\n name: z.string().describe('Certification name (e.g., SOC 2, ISO 27001)'),\n issuer: z.string(),\n issuedDate: z.string().datetime(),\n expiryDate: z.string().datetime().optional(),\n certificateUrl: z.string().url().optional(),\n })).optional(),\n \n /**\n * Security contact\n */\n securityContact: z.object({\n email: z.string().email().optional(),\n url: z.string().url().optional(),\n pgpKey: z.string().optional(),\n }).optional(),\n \n /**\n * Vulnerability disclosure policy\n */\n vulnerabilityDisclosure: z.object({\n policyUrl: z.string().url().optional(),\n responseTime: z.number().int().optional().describe('Expected response time in hours'),\n bugBounty: z.boolean().default(false),\n }).optional(),\n});\n\n// Export types\nexport type PermissionScope = z.infer;\nexport type PermissionAction = z.infer;\nexport type ResourceType = z.infer;\nexport type Permission = z.infer;\nexport type PermissionSet = z.infer;\nexport type RuntimeConfig = z.infer;\nexport type SandboxConfig = z.infer;\nexport type KernelSecurityVulnerability = z.infer;\nexport type KernelSecurityScanResult = z.infer;\nexport type KernelSecurityPolicy = z.infer;\nexport type PluginTrustLevel = z.infer;\nexport type PluginSecurityManifest = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * ObjectStack Plugin Structure Standards (OPS)\n * \n * Formal Zod definitions for the Plugin Directory Structure and File Naming conventions.\n * This can be used by the CLI or IDE extensions to lint project structure.\n * \n * @see PLUGIN_STANDARDS.md\n */\n\n// REGEX: snake_case identifiers\nconst SNAKE_CASE_REGEX = /^[a-z][a-z0-9_]*$/;\n\n// REGEX: Standard File Suffixes\nconst OPS_FILE_SUFFIX_REGEX = /\\.(object|field|trigger|function|view|page|dashboard|flow|app|router|service)\\.ts$/;\n\n/**\n * Validates a single file path against OPS Naming Conventions.\n * \n * @example Valid Paths\n * - \"src/crm/lead.object.ts\"\n * - \"src/finance/invoice_payment.trigger.ts\"\n * - \"src/index.ts\"\n * \n * @example Invalid Paths\n * - \"src/CRM/LeadObject.ts\" (PascalCase)\n * - \"src/utils/helper.js\" (Wrong extension)\n */\nexport const OpsFilePathSchema = z.string().describe('Validates a file path against OPS naming conventions').superRefine((path, ctx) => {\n // 1. Must be in src/\n if (!path.startsWith('src/')) {\n // Non-source files (package.json, config) are ignored by this specific validator\n // or handled separately.\n return; \n }\n\n const parts = path.split('/');\n \n // 2. Validate Domain Directory (src/[domain])\n if (parts.length > 2) {\n const domainDir = parts[1];\n if (!SNAKE_CASE_REGEX.test(domainDir)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Domain directory '${domainDir}' must be lowercase snake_case`\n });\n }\n }\n\n // 3. Validate Filename suffix\n const filename = parts[parts.length - 1];\n \n // Skip index.ts and utility files if they don't match the specific resource pattern\n // But strict OPS encourages explicit suffixes for resources.\n if (filename === 'index.ts' || filename === 'main.ts') return;\n\n if (!SNAKE_CASE_REGEX.test(filename.split('.')[0])) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Filename '${filename}' base name must be lowercase snake_case`\n });\n }\n\n if (!OPS_FILE_SUFFIX_REGEX.test(filename)) {\n // We allow other files, but we warn or mark them as non-standard resources\n // For strict mode:\n // ctx.addIssue({\n // code: z.ZodIssueCode.custom,\n // message: `Filename '${filename}' does not end with a valid semantic suffix (.object.ts, .view.ts, etc.)`\n // });\n }\n});\n\n/**\n * Schema for a \"Scanned Module\" structure.\n * Represents the contents of a domain folder.\n */\nexport const OpsDomainModuleSchema = z.object({\n name: z.string().regex(SNAKE_CASE_REGEX).describe('Module name (snake_case)'),\n files: z.array(z.string()).describe('List of files in this module'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n}).describe('Scanned domain module representing a plugin folder').superRefine((module, ctx) => {\n // Rule: Must have an index.ts\n if (!module.files.includes('index.ts')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Module '${module.name}' is missing an 'index.ts' entry point.`\n });\n }\n});\n\n/**\n * Schema for a full Plugin Project Layout\n */\nexport const OpsPluginStructureSchema = z.object({\n root: z.string().describe('Root directory path of the plugin project'),\n files: z.array(z.string()).describe('List of all file paths relative to root'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n}).describe('Full plugin project layout validated against OPS conventions').superRefine((project, ctx) => {\n // Check for configuration file\n if (!project.files.includes('objectstack.config.ts')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"Missing 'objectstack.config.ts' configuration file.\"\n });\n }\n \n // Validate each source file individually\n project.files.filter(f => f.startsWith('src/')).forEach(file => {\n const result = OpsFilePathSchema.safeParse(file);\n if (!result.success) {\n result.error.issues.forEach(issue => {\n ctx.addIssue({ ...issue, path: [file] });\n })\n }\n });\n});\n\nexport type OpsFilePath = z.infer;\nexport type OpsDomainModule = z.infer;\nexport type OpsPluginStructure = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Plugin Validator Protocol\n * \n * Zod schemas for plugin validation data structures.\n * These schemas align with the IPluginValidator contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Validation Result Schemas\n// ============================================================================\n\n/**\n * Validation Error Schema\n * Represents a single validation error\n * \n * @example\n * {\n * \"field\": \"version\",\n * \"message\": \"Invalid semver format\",\n * \"code\": \"INVALID_VERSION\"\n * }\n */\nexport const ValidationErrorSchema = z.object({\n /**\n * Field that failed validation\n */\n field: z.string().describe('Field name that failed validation'),\n \n /**\n * Human-readable error message\n */\n message: z.string().describe('Human-readable error message'),\n \n /**\n * Machine-readable error code (optional)\n */\n code: z.string().optional().describe('Machine-readable error code'),\n});\n\nexport type ValidationError = z.infer;\n\n/**\n * Validation Warning Schema\n * Represents a non-fatal validation warning\n * \n * @example\n * {\n * \"field\": \"description\",\n * \"message\": \"Description is empty\",\n * \"code\": \"MISSING_DESCRIPTION\"\n * }\n */\nexport const ValidationWarningSchema = z.object({\n /**\n * Field with warning\n */\n field: z.string().describe('Field name with warning'),\n \n /**\n * Human-readable warning message\n */\n message: z.string().describe('Human-readable warning message'),\n \n /**\n * Machine-readable warning code (optional)\n */\n code: z.string().optional().describe('Machine-readable warning code'),\n});\n\nexport type ValidationWarning = z.infer;\n\n/**\n * Validation Result Schema\n * Result of plugin validation operation\n * \n * @example\n * {\n * \"valid\": false,\n * \"errors\": [{\n * \"field\": \"name\",\n * \"message\": \"Plugin name is required\",\n * \"code\": \"REQUIRED_FIELD\"\n * }],\n * \"warnings\": [{\n * \"field\": \"description\",\n * \"message\": \"Description is recommended\",\n * \"code\": \"MISSING_DESCRIPTION\"\n * }]\n * }\n */\nexport const ValidationResultSchema = z.object({\n /**\n * Whether validation passed\n */\n valid: z.boolean().describe('Whether the plugin passed validation'),\n \n /**\n * Validation errors (if any)\n */\n errors: z.array(ValidationErrorSchema).optional().describe('Validation errors'),\n \n /**\n * Validation warnings (non-fatal issues)\n */\n warnings: z.array(ValidationWarningSchema).optional().describe('Validation warnings'),\n});\n\nexport type ValidationResult = z.infer;\n\n// ============================================================================\n// Plugin Metadata Schema\n// ============================================================================\n\n/**\n * Plugin Schema\n * Metadata structure for a plugin\n * \n * This aligns with and extends the existing PluginSchema from plugin.zod.ts\n * \n * @example\n * {\n * \"name\": \"crm-plugin\",\n * \"version\": \"1.0.0\",\n * \"dependencies\": [\"core-plugin\"]\n * }\n */\nexport const PluginMetadataSchema = z.object({\n /**\n * Unique plugin identifier (snake_case)\n */\n name: z.string().min(1).describe('Unique plugin identifier'),\n \n /**\n * Plugin version (semver)\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/).optional().describe('Semantic version (e.g., 1.0.0)'),\n \n /**\n * Plugin dependencies (array of plugin names)\n */\n dependencies: z.array(z.string()).optional().describe('Array of plugin names this plugin depends on'),\n \n /**\n * Plugin signature for cryptographic verification (optional)\n */\n signature: z.string().optional().describe('Cryptographic signature for plugin verification'),\n \n /**\n * Additional plugin metadata\n */\n}).passthrough().describe('Plugin metadata for validation');\n\nexport type PluginMetadata = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Versioning and Compatibility Protocol\n * \n * Defines comprehensive versioning, compatibility checking, and dependency\n * resolution mechanisms for the plugin ecosystem.\n * \n * Based on semantic versioning (SemVer) with extensions for:\n * - Compatibility matrices\n * - Breaking change detection\n * - Migration paths\n * - Multi-version support\n */\n\n/**\n * Semantic Version Schema\n * Standard SemVer format with optional pre-release and build metadata\n */\nexport const SemanticVersionSchema = z.object({\n major: z.number().int().min(0).describe('Major version (breaking changes)'),\n minor: z.number().int().min(0).describe('Minor version (backward compatible features)'),\n patch: z.number().int().min(0).describe('Patch version (backward compatible fixes)'),\n preRelease: z.string().optional().describe('Pre-release identifier (alpha, beta, rc.1)'),\n build: z.string().optional().describe('Build metadata'),\n}).describe('Semantic version number');\n\n/**\n * Version Constraint Schema\n * Defines version requirements using SemVer ranges\n */\nexport const VersionConstraintSchema = z.union([\n z.string().regex(/^[\\d.]+$/).describe('Exact version: `1.2.3`'),\n z.string().regex(/^\\^[\\d.]+$/).describe('Compatible with: `^1.2.3` (`>=1.2.3 <2.0.0`)'),\n z.string().regex(/^~[\\d.]+$/).describe('Approximately: `~1.2.3` (`>=1.2.3 <1.3.0`)'),\n z.string().regex(/^>=[\\d.]+$/).describe('Greater than or equal: `>=1.2.3`'),\n z.string().regex(/^>[\\d.]+$/).describe('Greater than: `>1.2.3`'),\n z.string().regex(/^<=[\\d.]+$/).describe('Less than or equal: `<=1.2.3`'),\n z.string().regex(/^<[\\d.]+$/).describe('Less than: `<1.2.3`'),\n z.string().regex(/^[\\d.]+ - [\\d.]+$/).describe('Range: `1.2.3 - 2.3.4`'),\n z.literal('*').describe('Any version'),\n z.literal('latest').describe('Latest stable version'),\n]);\n\n/**\n * Compatibility Level\n * Describes the level of compatibility between versions\n */\nexport const CompatibilityLevelSchema = z.enum([\n 'fully-compatible', // 100% compatible, drop-in replacement\n 'backward-compatible', // Backward compatible, new features added\n 'deprecated-compatible', // Compatible but uses deprecated features\n 'breaking-changes', // Breaking changes, migration required\n 'incompatible', // Completely incompatible\n]).describe('Compatibility level between versions');\n\n/**\n * Breaking Change\n * Documents a breaking change in a version\n */\nexport const BreakingChangeSchema = z.object({\n /**\n * Version where the change was introduced\n */\n introducedIn: z.string().describe('Version that introduced this breaking change'),\n \n /**\n * Type of breaking change\n */\n type: z.enum([\n 'api-removed', // API removed\n 'api-renamed', // API renamed\n 'api-signature-changed', // Function signature changed\n 'behavior-changed', // Behavior changed\n 'dependency-changed', // Dependency requirement changed\n 'configuration-changed', // Configuration schema changed\n 'protocol-changed', // Protocol implementation changed\n ]),\n \n /**\n * What was changed\n */\n description: z.string(),\n \n /**\n * Migration guide\n */\n migrationGuide: z.string().optional().describe('How to migrate from old to new'),\n \n /**\n * Deprecated in version\n */\n deprecatedIn: z.string().optional().describe('Version where old API was deprecated'),\n \n /**\n * Will be removed in version\n */\n removedIn: z.string().optional().describe('Version where old API will be removed'),\n \n /**\n * Automated migration available\n */\n automatedMigration: z.boolean().default(false)\n .describe('Whether automated migration tool is available'),\n \n /**\n * Impact severity\n */\n severity: z.enum(['critical', 'major', 'minor']).describe('Impact severity'),\n});\n\n/**\n * Deprecation Notice\n * Information about deprecated features\n */\nexport const DeprecationNoticeSchema = z.object({\n /**\n * Feature or API being deprecated\n */\n feature: z.string().describe('Deprecated feature identifier'),\n \n /**\n * Version when deprecated\n */\n deprecatedIn: z.string(),\n \n /**\n * Planned removal version\n */\n removeIn: z.string().optional(),\n \n /**\n * Reason for deprecation\n */\n reason: z.string(),\n \n /**\n * Recommended alternative\n */\n alternative: z.string().optional().describe('What to use instead'),\n \n /**\n * Migration path\n */\n migrationPath: z.string().optional().describe('How to migrate to alternative'),\n});\n\n/**\n * Compatibility Matrix Entry\n * Maps compatibility between different plugin versions\n */\nexport const CompatibilityMatrixEntrySchema = z.object({\n /**\n * Source version\n */\n from: z.string().describe('Version being upgraded from'),\n \n /**\n * Target version\n */\n to: z.string().describe('Version being upgraded to'),\n \n /**\n * Compatibility level\n */\n compatibility: CompatibilityLevelSchema,\n \n /**\n * Breaking changes list\n */\n breakingChanges: z.array(BreakingChangeSchema).optional(),\n \n /**\n * Migration required\n */\n migrationRequired: z.boolean().default(false),\n \n /**\n * Migration complexity\n */\n migrationComplexity: z.enum(['trivial', 'simple', 'moderate', 'complex', 'major']).optional(),\n \n /**\n * Estimated migration time in hours\n */\n estimatedMigrationTime: z.number().optional(),\n \n /**\n * Migration script available\n */\n migrationScript: z.string().optional().describe('Path to migration script'),\n \n /**\n * Test coverage for migration\n */\n testCoverage: z.number().min(0).max(100).optional()\n .describe('Percentage of migration covered by tests'),\n});\n\n/**\n * Plugin Compatibility Matrix\n * Complete compatibility information for a plugin\n */\nexport const PluginCompatibilityMatrixSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Current version\n */\n currentVersion: z.string(),\n \n /**\n * Compatibility entries\n */\n compatibilityMatrix: z.array(CompatibilityMatrixEntrySchema),\n \n /**\n * Supported versions\n */\n supportedVersions: z.array(z.object({\n version: z.string(),\n supported: z.boolean(),\n endOfLife: z.string().datetime().optional().describe('End of support date'),\n securitySupport: z.boolean().default(false).describe('Still receives security updates'),\n })),\n \n /**\n * Minimum compatible version\n */\n minimumCompatibleVersion: z.string().optional()\n .describe('Oldest version that can be directly upgraded'),\n});\n\n/**\n * Dependency Conflict\n * Represents a conflict in plugin dependencies at the kernel level.\n * Models plugin-to-plugin dependency conflicts with typed conflict categories.\n * \n * @see hub/plugin-security.zod.ts DependencyConflictSchema for hub-level package version conflicts\n * which focuses on marketplace registry resolution.\n */\nexport const DependencyConflictSchema = z.object({\n /**\n * Type of conflict\n */\n type: z.enum([\n 'version-mismatch', // Different versions required\n 'missing-dependency', // Required dependency not found\n 'circular-dependency', // Circular dependency detected\n 'incompatible-versions', // Incompatible versions required by different plugins\n 'conflicting-interfaces', // Plugins implement conflicting interfaces\n ]),\n \n /**\n * Plugins involved in conflict\n */\n plugins: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n requirement: z.string().optional().describe('What this plugin requires'),\n })),\n \n /**\n * Conflict description\n */\n description: z.string(),\n \n /**\n * Possible resolutions\n */\n resolutions: z.array(z.object({\n strategy: z.enum([\n 'upgrade', // Upgrade one or more plugins\n 'downgrade', // Downgrade one or more plugins\n 'replace', // Replace with alternative plugin\n 'disable', // Disable conflicting plugin\n 'manual', // Manual intervention required\n ]),\n description: z.string(),\n automaticResolution: z.boolean().default(false),\n riskLevel: z.enum(['low', 'medium', 'high']),\n })).optional(),\n \n /**\n * Severity of conflict\n */\n severity: z.enum(['critical', 'error', 'warning', 'info']),\n});\n\n/**\n * Dependency Resolution Result\n * Result of dependency resolution process\n */\nexport const PluginDependencyResolutionResultSchema = z.object({\n /**\n * Resolution successful\n */\n success: z.boolean(),\n \n /**\n * Resolved plugin versions\n */\n resolved: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n resolvedVersion: z.string(),\n })).optional(),\n \n /**\n * Conflicts found\n */\n conflicts: z.array(DependencyConflictSchema).optional(),\n \n /**\n * Warnings\n */\n warnings: z.array(z.string()).optional(),\n \n /**\n * Installation order (topologically sorted)\n */\n installationOrder: z.array(z.string()).optional()\n .describe('Plugin IDs in order they should be installed'),\n \n /**\n * Dependency graph\n */\n dependencyGraph: z.record(z.string(), z.array(z.string())).optional()\n .describe('Map of plugin ID to its dependencies'),\n});\n\n/**\n * Multi-Version Support Configuration\n * Allows running multiple versions of a plugin simultaneously\n */\nexport const MultiVersionSupportSchema = z.object({\n /**\n * Enable multi-version support\n */\n enabled: z.boolean().default(false),\n \n /**\n * Maximum concurrent versions\n */\n maxConcurrentVersions: z.number().int().min(1).default(2)\n .describe('How many versions can run at the same time'),\n \n /**\n * Version selection strategy\n */\n selectionStrategy: z.enum([\n 'latest', // Always use latest version\n 'stable', // Use latest stable version\n 'compatible', // Use version compatible with dependencies\n 'pinned', // Use pinned version\n 'canary', // Use canary/preview version\n 'custom', // Custom selection logic\n ]).default('latest'),\n \n /**\n * Version routing rules\n */\n routing: z.array(z.object({\n condition: z.string().describe('Routing condition (e.g., tenant, user, feature flag)'),\n version: z.string().describe('Version to use when condition matches'),\n priority: z.number().int().default(100).describe('Rule priority'),\n })).optional(),\n \n /**\n * Gradual rollout configuration\n */\n rollout: z.object({\n enabled: z.boolean().default(false),\n strategy: z.enum(['percentage', 'blue-green', 'canary']),\n percentage: z.number().min(0).max(100).optional()\n .describe('Percentage of traffic to new version'),\n duration: z.number().int().optional()\n .describe('Rollout duration in milliseconds'),\n }).optional(),\n});\n\n/**\n * Plugin Version Metadata\n * Complete version information for a plugin\n */\nexport const PluginVersionMetadataSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Version number\n */\n version: SemanticVersionSchema,\n \n /**\n * Version string (computed)\n */\n versionString: z.string().describe('Full version string (e.g., 1.2.3-beta.1+build.123)'),\n \n /**\n * Release date\n */\n releaseDate: z.string().datetime(),\n \n /**\n * Release notes\n */\n releaseNotes: z.string().optional(),\n \n /**\n * Breaking changes\n */\n breakingChanges: z.array(BreakingChangeSchema).optional(),\n \n /**\n * Deprecations\n */\n deprecations: z.array(DeprecationNoticeSchema).optional(),\n \n /**\n * Compatibility matrix\n */\n compatibilityMatrix: z.array(CompatibilityMatrixEntrySchema).optional(),\n \n /**\n * Security vulnerabilities fixed\n */\n securityFixes: z.array(z.object({\n cve: z.string().optional().describe('CVE identifier'),\n severity: z.enum(['critical', 'high', 'medium', 'low']),\n description: z.string(),\n fixedIn: z.string().describe('Version where vulnerability was fixed'),\n })).optional(),\n \n /**\n * Download statistics\n */\n statistics: z.object({\n downloads: z.number().int().min(0).optional(),\n installations: z.number().int().min(0).optional(),\n ratings: z.number().min(0).max(5).optional(),\n }).optional(),\n \n /**\n * Support status\n */\n support: z.object({\n status: z.enum(['active', 'maintenance', 'deprecated', 'eol']),\n endOfLife: z.string().datetime().optional(),\n securitySupport: z.boolean().default(true),\n }),\n});\n\n// Export types\nexport type SemanticVersion = z.infer;\nexport type VersionConstraint = z.infer;\nexport type CompatibilityLevel = z.infer;\nexport type BreakingChange = z.infer;\nexport type DeprecationNotice = z.infer;\nexport type CompatibilityMatrixEntry = z.infer;\nexport type PluginCompatibilityMatrix = z.infer;\nexport type DependencyConflict = z.infer;\nexport type PluginDependencyResolutionResult = z.infer;\nexport type MultiVersionSupport = z.infer;\nexport type PluginVersionMetadata = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Service Registry Protocol\n * \n * Zod schemas for service registry data structures.\n * These schemas align with the IServiceRegistry contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n * \n * Note: IServiceRegistry itself is a runtime interface (methods only),\n * so it correctly remains a TypeScript interface. This file contains\n * schemas for configuration and metadata related to service registry.\n */\n\n// ============================================================================\n// Service Metadata Schemas\n// ============================================================================\n\n/**\n * Service Scope Type Enum\n * Different service scoping strategies\n */\nexport const ServiceScopeType = z.enum([\n 'singleton', // Single instance shared across the application\n 'transient', // New instance created each time\n 'scoped', // Instance per scope (request, session, transaction, etc.)\n]).describe('Service scope type');\n\nexport type ServiceScopeType = z.infer;\n\n/**\n * Service Metadata Schema\n * Metadata about a registered service\n * \n * @example\n * {\n * \"name\": \"database\",\n * \"scope\": \"singleton\",\n * \"type\": \"IDataEngine\",\n * \"registeredAt\": 1706659200000\n * }\n */\nexport const ServiceMetadataSchema = z.object({\n /**\n * Service name (unique identifier)\n */\n name: z.string().min(1).describe('Unique service name identifier'),\n \n /**\n * Service scope type\n */\n scope: ServiceScopeType.optional().default('singleton')\n .describe('Service scope type'),\n \n /**\n * Service type or interface name (optional)\n */\n type: z.string().optional().describe('Service type or interface name'),\n \n /**\n * Registration timestamp (Unix milliseconds)\n */\n registeredAt: z.number().int().optional()\n .describe('Unix timestamp in milliseconds when service was registered'),\n \n /**\n * Additional metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Additional service-specific metadata'),\n});\n\nexport type ServiceMetadata = z.infer;\n\n// ============================================================================\n// Service Registry Configuration Schemas\n// ============================================================================\n\n/**\n * Service Registry Configuration Schema\n * Configuration for service registry behavior\n * \n * @example\n * {\n * \"strictMode\": true,\n * \"allowOverwrite\": false,\n * \"enableLogging\": true,\n * \"scopeTypes\": [\"singleton\", \"transient\", \"request\", \"session\"]\n * }\n */\nexport const ServiceRegistryConfigSchema = z.object({\n /**\n * Strict mode: throw errors on invalid operations\n * @default true\n */\n strictMode: z.boolean().optional().default(true)\n .describe('Throw errors on invalid operations (duplicate registration, service not found, etc.)'),\n \n /**\n * Allow overwriting existing services\n * @default false\n */\n allowOverwrite: z.boolean().optional().default(false)\n .describe('Allow overwriting existing service registrations'),\n \n /**\n * Enable logging for service operations\n * @default false\n */\n enableLogging: z.boolean().optional().default(false)\n .describe('Enable logging for service registration and retrieval'),\n \n /**\n * Custom scope types (beyond singleton, transient, scoped)\n * @default ['singleton', 'transient', 'scoped']\n */\n scopeTypes: z.array(z.string()).optional()\n .describe('Supported scope types'),\n \n /**\n * Maximum number of services (prevent memory leaks)\n */\n maxServices: z.number().int().min(1).optional()\n .describe('Maximum number of services that can be registered'),\n});\n\nexport type ServiceRegistryConfig = z.infer;\nexport type ServiceRegistryConfigInput = z.input;\n\n// ============================================================================\n// Service Factory Schemas\n// ============================================================================\n\n/**\n * Service Factory Registration Schema\n * Configuration for registering a service factory\n * \n * @example\n * {\n * \"name\": \"logger\",\n * \"scope\": \"singleton\",\n * \"factoryType\": \"sync\"\n * }\n */\nexport const ServiceFactoryRegistrationSchema = z.object({\n /**\n * Service name (unique identifier)\n */\n name: z.string().min(1).describe('Unique service name identifier'),\n \n /**\n * Service scope type\n */\n scope: ServiceScopeType.optional().default('singleton')\n .describe('Service scope type'),\n \n /**\n * Factory type (sync or async)\n */\n factoryType: z.enum(['sync', 'async']).optional().default('sync')\n .describe('Whether factory is synchronous or asynchronous'),\n \n /**\n * Whether this is a singleton (cache factory result)\n */\n singleton: z.boolean().optional().default(true)\n .describe('Whether to cache the factory result (singleton pattern)'),\n});\n\nexport type ServiceFactoryRegistration = z.infer;\n\n// ============================================================================\n// Scoped Service Schemas\n// ============================================================================\n\n/**\n * Scope Configuration Schema\n * Configuration for creating a new scope\n * \n * @example\n * {\n * \"scopeType\": \"request\",\n * \"scopeId\": \"req-12345\",\n * \"metadata\": {\n * \"userId\": \"user-123\",\n * \"requestId\": \"req-12345\"\n * }\n * }\n */\nexport const ScopeConfigSchema = z.object({\n /**\n * Type of scope (request, session, transaction, etc.)\n */\n scopeType: z.string().describe('Type of scope'),\n \n /**\n * Scope identifier (optional, auto-generated if not provided)\n */\n scopeId: z.string().optional().describe('Unique scope identifier'),\n \n /**\n * Scope metadata (context information)\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Scope-specific context metadata'),\n});\n\nexport type ScopeConfig = z.infer;\n\n/**\n * Scope Info Schema\n * Information about an active scope\n * \n * @example\n * {\n * \"scopeId\": \"req-12345\",\n * \"scopeType\": \"request\",\n * \"createdAt\": 1706659200000,\n * \"serviceCount\": 5,\n * \"metadata\": {\n * \"userId\": \"user-123\"\n * }\n * }\n */\nexport const ScopeInfoSchema = z.object({\n /**\n * Scope identifier\n */\n scopeId: z.string().describe('Unique scope identifier'),\n \n /**\n * Type of scope\n */\n scopeType: z.string().describe('Type of scope'),\n \n /**\n * Creation timestamp (Unix milliseconds)\n */\n createdAt: z.number().int().describe('Unix timestamp in milliseconds when scope was created'),\n \n /**\n * Number of services in this scope\n */\n serviceCount: z.number().int().min(0).optional()\n .describe('Number of services registered in this scope'),\n \n /**\n * Scope metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n .describe('Scope-specific context metadata'),\n});\n\nexport type ScopeInfo = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Startup Orchestrator Protocol\n * \n * Zod schemas for plugin startup orchestration data structures.\n * These schemas align with the IStartupOrchestrator contract interface.\n * \n * Following ObjectStack \"Zod First\" principle - all data structures\n * must have Zod schemas for runtime validation and JSON Schema generation.\n */\n\n// ============================================================================\n// Startup Configuration Schemas\n// ============================================================================\n\n/**\n * Startup Options Schema\n * Configuration for plugin startup orchestration\n * \n * @example\n * {\n * \"timeout\": 30000,\n * \"rollbackOnFailure\": true,\n * \"healthCheck\": false,\n * \"parallel\": false\n * }\n */\nexport const StartupOptionsSchema = z.object({\n /**\n * Maximum time (ms) to wait for each plugin to start\n * @default 30000 (30 seconds)\n */\n timeout: z.number().int().min(0).optional().default(30000)\n .describe('Maximum time in milliseconds to wait for each plugin to start'),\n \n /**\n * Whether to rollback (destroy) already-started plugins on failure\n * @default true\n */\n rollbackOnFailure: z.boolean().optional().default(true)\n .describe('Whether to rollback already-started plugins if any plugin fails'),\n \n /**\n * Whether to run health checks after startup\n * @default false\n */\n healthCheck: z.boolean().optional().default(false)\n .describe('Whether to run health checks after plugin startup'),\n \n /**\n * Whether to run plugins in parallel (if dependencies allow)\n * @default false (sequential startup)\n */\n parallel: z.boolean().optional().default(false)\n .describe('Whether to start plugins in parallel when dependencies allow'),\n \n /**\n * Custom context to pass to plugin lifecycle methods\n */\n context: z.unknown().optional().describe('Custom context object to pass to plugin lifecycle methods'),\n});\n\nexport type StartupOptions = z.infer;\nexport type StartupOptionsInput = z.input;\n\n// ============================================================================\n// Health Status Schemas\n// ============================================================================\n\n/**\n * Health Status Schema\n * Health status for a plugin\n * \n * @example\n * {\n * \"healthy\": true,\n * \"timestamp\": 1706659200000,\n * \"details\": {\n * \"databaseConnected\": true,\n * \"memoryUsage\": 45.2\n * }\n * }\n */\nexport const HealthStatusSchema = z.object({\n /**\n * Whether the plugin is healthy\n */\n healthy: z.boolean().describe('Whether the plugin is healthy'),\n \n /**\n * Health check timestamp (Unix milliseconds)\n */\n timestamp: z.number().int().describe('Unix timestamp in milliseconds when health check was performed'),\n \n /**\n * Optional health details (plugin-specific)\n */\n details: z.record(z.string(), z.unknown()).optional().describe('Optional plugin-specific health details'),\n \n /**\n * Optional error message if unhealthy\n */\n message: z.string().optional().describe('Error message if plugin is unhealthy'),\n});\n\nexport type HealthStatus = z.infer;\n\n// ============================================================================\n// Startup Result Schemas\n// ============================================================================\n\n/**\n * Plugin Startup Result Schema\n * Result of a single plugin startup operation\n * \n * @example\n * {\n * \"plugin\": { \"name\": \"crm-plugin\", \"version\": \"1.0.0\" },\n * \"success\": true,\n * \"duration\": 1250,\n * \"health\": {\n * \"healthy\": true,\n * \"timestamp\": 1706659200000\n * }\n * }\n */\nexport const PluginStartupResultSchema = z.object({\n /**\n * Plugin that was started\n */\n plugin: z.object({\n name: z.string(),\n version: z.string().optional(),\n }).passthrough().describe('Plugin metadata'),\n \n /**\n * Whether startup was successful\n */\n success: z.boolean().describe('Whether the plugin started successfully'),\n \n /**\n * Time taken to start (milliseconds)\n */\n duration: z.number().min(0).describe('Time taken to start the plugin in milliseconds'),\n \n /**\n * Error if startup failed\n */\n error: z.object({\n name: z.string().describe('Error class name'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n code: z.string().optional().describe('Error code'),\n }).optional().describe('Serializable error representation if startup failed'),\n \n /**\n * Health status after startup (if healthCheck enabled)\n */\n health: HealthStatusSchema.optional().describe('Health status after startup if health check was enabled'),\n});\n\nexport type PluginStartupResult = z.infer;\n\n// ============================================================================\n// Startup Orchestration Result Schema\n// ============================================================================\n\n/**\n * Startup Orchestration Result Schema\n * Overall result of orchestrating startup for multiple plugins\n * \n * @example\n * {\n * \"results\": [\n * { \"plugin\": { \"name\": \"plugin1\" }, \"success\": true, \"duration\": 1200 },\n * { \"plugin\": { \"name\": \"plugin2\" }, \"success\": true, \"duration\": 850 }\n * ],\n * \"totalDuration\": 2050,\n * \"allSuccessful\": true\n * }\n */\nexport const StartupOrchestrationResultSchema = z.object({\n /**\n * Individual plugin startup results\n */\n results: z.array(PluginStartupResultSchema).describe('Startup results for each plugin'),\n \n /**\n * Total time taken for all plugins (milliseconds)\n */\n totalDuration: z.number().min(0).describe('Total time taken for all plugins in milliseconds'),\n \n /**\n * Whether all plugins started successfully\n */\n allSuccessful: z.boolean().describe('Whether all plugins started successfully'),\n \n /**\n * Plugins that were rolled back (if rollbackOnFailure was enabled)\n */\n rolledBack: z.array(z.string()).optional().describe('Names of plugins that were rolled back'),\n});\n\nexport type StartupOrchestrationResult = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginCapabilityManifestSchema } from './plugin-capability.zod';\n\n/**\n * # Plugin Registry Protocol\n * \n * Defines the schema for the plugin discovery and registry system.\n * This enables plugins from different vendors to be discovered, validated,\n * and composed together in the ObjectStack ecosystem.\n */\n\n/**\n * Plugin Vendor Information\n */\nexport const PluginVendorSchema = z.object({\n /**\n * Vendor identifier (reverse domain notation)\n * Example: \"com.acme\", \"org.apache\", \"com.objectstack\"\n */\n id: z.string()\n .regex(/^[a-z][a-z0-9]*(\\.[a-z][a-z0-9]*)+$/)\n .describe('Vendor identifier (reverse domain)'),\n \n /**\n * Vendor display name\n */\n name: z.string(),\n \n /**\n * Vendor website\n */\n website: z.string().url().optional(),\n \n /**\n * Contact email\n */\n email: z.string().email().optional(),\n \n /**\n * Verification status\n */\n verified: z.boolean().default(false).describe('Whether vendor is verified by ObjectStack'),\n \n /**\n * Trust level\n */\n trustLevel: z.enum(['official', 'verified', 'community', 'unverified']).default('unverified'),\n});\n\n/**\n * Plugin Quality Metrics\n */\nexport const PluginQualityMetricsSchema = z.object({\n /**\n * Test coverage percentage\n */\n testCoverage: z.number().min(0).max(100).optional(),\n \n /**\n * Documentation score (0-100)\n */\n documentationScore: z.number().min(0).max(100).optional(),\n \n /**\n * Code quality score (0-100)\n */\n codeQuality: z.number().min(0).max(100).optional(),\n \n /**\n * Security scan status\n */\n securityScan: z.object({\n lastScanDate: z.string().datetime().optional(),\n vulnerabilities: z.object({\n critical: z.number().int().min(0).default(0),\n high: z.number().int().min(0).default(0),\n medium: z.number().int().min(0).default(0),\n low: z.number().int().min(0).default(0),\n }).optional(),\n passed: z.boolean().default(false),\n }).optional(),\n \n /**\n * Conformance test results\n */\n conformanceTests: z.array(z.object({\n protocolId: z.string().describe('Protocol being tested'),\n passed: z.boolean(),\n totalTests: z.number().int().min(0),\n passedTests: z.number().int().min(0),\n lastRunDate: z.string().datetime().optional(),\n })).optional(),\n});\n\n/**\n * Plugin Usage Statistics\n */\nexport const PluginStatisticsSchema = z.object({\n /**\n * Total downloads\n */\n downloads: z.number().int().min(0).default(0),\n \n /**\n * Downloads in the last 30 days\n */\n downloadsLastMonth: z.number().int().min(0).default(0),\n \n /**\n * Number of active installations\n */\n activeInstallations: z.number().int().min(0).default(0),\n \n /**\n * User ratings\n */\n ratings: z.object({\n average: z.number().min(0).max(5).default(0),\n count: z.number().int().min(0).default(0),\n distribution: z.object({\n '5': z.number().int().min(0).default(0),\n '4': z.number().int().min(0).default(0),\n '3': z.number().int().min(0).default(0),\n '2': z.number().int().min(0).default(0),\n '1': z.number().int().min(0).default(0),\n }).optional(),\n }).optional(),\n \n /**\n * GitHub stars (if open source)\n */\n stars: z.number().int().min(0).optional(),\n \n /**\n * Number of dependent plugins\n */\n dependents: z.number().int().min(0).default(0),\n});\n\n/**\n * Plugin Registry Entry\n * Complete metadata for a plugin in the registry.\n */\nexport const PluginRegistryEntrySchema = z.object({\n /**\n * Plugin identifier (must match manifest.id)\n */\n id: z.string()\n .regex(/^([a-z][a-z0-9]*\\.)+[a-z][a-z0-9-]+$/)\n .describe('Plugin identifier (reverse domain notation)'),\n \n /**\n * Current version\n */\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/),\n \n /**\n * Plugin display name\n */\n name: z.string(),\n \n /**\n * Short description\n */\n description: z.string().optional(),\n \n /**\n * Detailed documentation/README\n */\n readme: z.string().optional(),\n \n /**\n * Plugin type/category\n */\n category: z.enum([\n 'data', // Data management, storage, databases\n 'integration', // External service integrations\n 'ui', // UI components and themes\n 'analytics', // Analytics and reporting\n 'security', // Security, auth, compliance\n 'automation', // Workflows and automation\n 'ai', // AI/ML capabilities\n 'utility', // General utilities\n 'driver', // Database/storage drivers\n 'gateway', // API gateways\n 'adapter', // Runtime adapters\n ]).optional(),\n \n /**\n * Tags for categorization\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Vendor information\n */\n vendor: PluginVendorSchema,\n \n /**\n * Capability manifest (what the plugin implements/provides)\n */\n capabilities: PluginCapabilityManifestSchema.optional(),\n \n /**\n * Compatibility information\n */\n compatibility: z.object({\n /**\n * Minimum ObjectStack version required\n */\n minObjectStackVersion: z.string().optional(),\n \n /**\n * Maximum ObjectStack version supported\n */\n maxObjectStackVersion: z.string().optional(),\n \n /**\n * Node.js version requirement\n */\n nodeVersion: z.string().optional(),\n \n /**\n * Supported platforms\n */\n platforms: z.array(z.enum(['linux', 'darwin', 'win32', 'browser'])).optional(),\n }).optional(),\n \n /**\n * Links and resources\n */\n links: z.object({\n homepage: z.string().url().optional(),\n repository: z.string().url().optional(),\n documentation: z.string().url().optional(),\n bugs: z.string().url().optional(),\n changelog: z.string().url().optional(),\n }).optional(),\n \n /**\n * Media assets\n */\n media: z.object({\n icon: z.string().url().optional(),\n logo: z.string().url().optional(),\n screenshots: z.array(z.string().url()).optional(),\n video: z.string().url().optional(),\n }).optional(),\n \n /**\n * Quality metrics\n */\n quality: PluginQualityMetricsSchema.optional(),\n \n /**\n * Usage statistics\n */\n statistics: PluginStatisticsSchema.optional(),\n \n /**\n * License information\n */\n license: z.string().optional().describe('SPDX license identifier'),\n \n /**\n * Pricing (if commercial)\n */\n pricing: z.object({\n model: z.enum(['free', 'freemium', 'paid', 'enterprise']),\n price: z.number().min(0).optional(),\n currency: z.string().default('USD').optional(),\n billingPeriod: z.enum(['one-time', 'monthly', 'yearly']).optional(),\n }).optional(),\n \n /**\n * Publication dates\n */\n publishedAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n \n /**\n * Deprecation status\n */\n deprecated: z.boolean().default(false),\n deprecationMessage: z.string().optional(),\n replacedBy: z.string().optional().describe('Plugin ID that replaces this one'),\n \n /**\n * Feature flags\n */\n flags: z.object({\n experimental: z.boolean().default(false),\n beta: z.boolean().default(false),\n featured: z.boolean().default(false),\n verified: z.boolean().default(false),\n }).optional(),\n});\n\n/**\n * Plugin Search Filters\n */\nexport const PluginSearchFiltersSchema = z.object({\n /**\n * Search query\n */\n query: z.string().optional(),\n \n /**\n * Filter by category\n */\n category: z.array(z.string()).optional(),\n \n /**\n * Filter by tags\n */\n tags: z.array(z.string()).optional(),\n \n /**\n * Filter by vendor trust level\n */\n trustLevel: z.array(z.enum(['official', 'verified', 'community', 'unverified'])).optional(),\n \n /**\n * Filter by protocols implemented\n */\n implementsProtocols: z.array(z.string()).optional(),\n \n /**\n * Filter by pricing model\n */\n pricingModel: z.array(z.enum(['free', 'freemium', 'paid', 'enterprise'])).optional(),\n \n /**\n * Minimum rating\n */\n minRating: z.number().min(0).max(5).optional(),\n \n /**\n * Sort options\n */\n sortBy: z.enum([\n 'relevance',\n 'downloads',\n 'rating',\n 'updated',\n 'name',\n ]).optional(),\n \n /**\n * Sort order\n */\n sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),\n \n /**\n * Pagination\n */\n page: z.number().int().min(1).default(1).optional(),\n limit: z.number().int().min(1).max(100).default(20).optional(),\n});\n\n/**\n * Plugin Installation Configuration\n */\nexport const PluginInstallConfigSchema = z.object({\n /**\n * Plugin identifier to install\n */\n pluginId: z.string(),\n \n /**\n * Version to install (supports semver ranges)\n */\n version: z.string().optional().describe('Defaults to latest'),\n \n /**\n * Plugin-specific configuration values\n */\n config: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Whether to auto-update\n */\n autoUpdate: z.boolean().default(false).optional(),\n \n /**\n * Installation options\n */\n options: z.object({\n /**\n * Skip dependency installation\n */\n skipDependencies: z.boolean().default(false).optional(),\n \n /**\n * Force reinstall\n */\n force: z.boolean().default(false).optional(),\n \n /**\n * Installation target\n */\n target: z.enum(['system', 'space', 'user']).default('space').optional(),\n }).optional(),\n});\n\n// Export types\nexport type PluginVendor = z.infer;\nexport type PluginVendorInput = z.input;\nexport type PluginQualityMetrics = z.infer;\nexport type PluginQualityMetricsInput = z.input;\nexport type PluginStatistics = z.infer;\nexport type PluginStatisticsInput = z.input;\nexport type PluginRegistryEntry = z.infer;\nexport type PluginRegistryEntryInput = z.input;\nexport type PluginSearchFilters = z.infer;\nexport type PluginSearchFiltersInput = z.input;\nexport type PluginInstallConfig = z.infer;\nexport type PluginInstallConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Plugin Security & Dependency Resolution Protocol\n * \n * Provides comprehensive security scanning, vulnerability management,\n * and dependency resolution for the ObjectStack plugin ecosystem.\n * \n * Features:\n * - CVE/vulnerability scanning\n * - Dependency graph resolution\n * - Semantic version conflict detection\n * - Supply chain security\n * - Plugin sandboxing policies\n * - Trust and verification workflows\n */\n\n// ============================================================================\n// Security Scanning\n// ============================================================================\n\n/**\n * Vulnerability Severity\n */\nexport const VulnerabilitySeverity = z.enum([\n 'critical',\n 'high',\n 'medium',\n 'low',\n 'info',\n]).describe('Severity level of a security vulnerability');\n\nexport type VulnerabilitySeverity = z.infer;\n\n/**\n * Security Vulnerability\n */\nexport const SecurityVulnerabilitySchema = z.object({\n /**\n * CVE identifier (if applicable)\n */\n cve: z.string().regex(/^CVE-\\d{4}-\\d+$/).optional().describe('CVE identifier'),\n \n /**\n * Vulnerability identifier (GHSA, SNYK, etc.)\n */\n id: z.string().describe('Vulnerability ID'),\n \n /**\n * Title\n */\n title: z.string().describe('Short title summarizing the vulnerability'),\n \n /**\n * Description\n */\n description: z.string().describe('Detailed description of the vulnerability'),\n \n /**\n * Severity\n */\n severity: VulnerabilitySeverity.describe('Severity level of this vulnerability'),\n \n /**\n * CVSS score (0-10)\n */\n cvss: z.number().min(0).max(10).optional().describe('CVSS score ranging from 0 to 10'),\n \n /**\n * Affected package\n */\n package: z.object({\n name: z.string().describe('Name of the affected package'),\n version: z.string().describe('Version of the affected package'),\n ecosystem: z.string().optional().describe('Package ecosystem (e.g., npm, pip, maven)'),\n }).describe('Affected package information'),\n \n /**\n * Vulnerable version range\n */\n vulnerableVersions: z.string().describe('Semver range of vulnerable versions'),\n \n /**\n * Patched versions\n */\n patchedVersions: z.string().optional().describe('Semver range of patched versions'),\n \n /**\n * References\n */\n references: z.array(z.object({\n type: z.enum(['advisory', 'article', 'report', 'web']).describe('Type of reference source'),\n url: z.string().url().describe('URL of the reference'),\n })).default([]).describe('External references related to the vulnerability'),\n \n /**\n * CWE (Common Weakness Enumeration)\n */\n cwe: z.array(z.string()).default([]).describe('CWE identifiers associated with this vulnerability'),\n \n /**\n * Published date\n */\n publishedAt: z.string().datetime().optional().describe('ISO 8601 date when the vulnerability was published'),\n \n /**\n * Mitigation advice\n */\n mitigation: z.string().optional().describe('Recommended steps to mitigate the vulnerability'),\n}).describe('A known security vulnerability in a package dependency');\n\nexport type SecurityVulnerability = z.infer;\n\n/**\n * Security Scan Result\n */\nexport const SecurityScanResultSchema = z.object({\n /**\n * Scan identifier\n */\n scanId: z.string().uuid().describe('Unique identifier for this security scan'),\n \n /**\n * Plugin being scanned\n */\n plugin: z.object({\n id: z.string().describe('Plugin identifier'),\n version: z.string().describe('Plugin version that was scanned'),\n }).describe('Plugin that was scanned'),\n \n /**\n * Scan timestamp\n */\n scannedAt: z.string().datetime().describe('ISO 8601 timestamp when the scan was performed'),\n \n /**\n * Scanner information\n */\n scanner: z.object({\n name: z.string().describe('Scanner name (e.g., snyk, osv, trivy)'),\n version: z.string().describe('Version of the scanner tool'),\n }).describe('Information about the scanner tool used'),\n \n /**\n * Scan status\n */\n status: z.enum(['passed', 'failed', 'warning']).describe('Overall result status of the security scan'),\n \n /**\n * Vulnerabilities found\n */\n vulnerabilities: z.array(SecurityVulnerabilitySchema).describe('List of vulnerabilities discovered during the scan'),\n \n /**\n * Vulnerability summary\n */\n summary: z.object({\n critical: z.number().int().min(0).default(0).describe('Count of critical severity vulnerabilities'),\n high: z.number().int().min(0).default(0).describe('Count of high severity vulnerabilities'),\n medium: z.number().int().min(0).default(0).describe('Count of medium severity vulnerabilities'),\n low: z.number().int().min(0).default(0).describe('Count of low severity vulnerabilities'),\n info: z.number().int().min(0).default(0).describe('Count of informational severity vulnerabilities'),\n total: z.number().int().min(0).default(0).describe('Total count of all vulnerabilities'),\n }).describe('Summary counts of vulnerabilities by severity'),\n \n /**\n * License compliance issues\n */\n licenseIssues: z.array(z.object({\n package: z.string().describe('Name of the package with a license issue'),\n license: z.string().describe('License identifier of the package'),\n reason: z.string().describe('Reason the license is flagged'),\n severity: z.enum(['error', 'warning', 'info']).describe('Severity of the license compliance issue'),\n })).default([]).describe('License compliance issues found during the scan'),\n \n /**\n * Code quality issues\n */\n codeQuality: z.object({\n score: z.number().min(0).max(100).optional().describe('Overall code quality score from 0 to 100'),\n issues: z.array(z.object({\n type: z.enum(['security', 'quality', 'style']).describe('Category of the code quality issue'),\n severity: z.enum(['error', 'warning', 'info']).describe('Severity of the code quality issue'),\n message: z.string().describe('Description of the code quality issue'),\n file: z.string().optional().describe('File path where the issue was found'),\n line: z.number().int().optional().describe('Line number where the issue was found'),\n })).default([]).describe('List of individual code quality issues'),\n }).optional().describe('Code quality analysis results'),\n \n /**\n * Next scan scheduled\n */\n nextScanAt: z.string().datetime().optional().describe('ISO 8601 timestamp for the next scheduled scan'),\n}).describe('Result of a security scan performed on a plugin');\n\nexport type SecurityScanResult = z.infer;\n\n/**\n * Security Policy\n */\nexport const SecurityPolicySchema = z.object({\n /**\n * Policy identifier\n */\n id: z.string().describe('Unique identifier for the security policy'),\n \n /**\n * Policy name\n */\n name: z.string().describe('Human-readable name of the security policy'),\n \n /**\n * Automatic scanning\n */\n autoScan: z.object({\n enabled: z.boolean().default(true).describe('Whether automatic scanning is enabled'),\n frequency: z.enum(['on-publish', 'daily', 'weekly', 'monthly']).default('daily').describe('How often automatic scans are performed'),\n }).describe('Automatic security scanning configuration'),\n \n /**\n * Vulnerability thresholds\n */\n thresholds: z.object({\n /**\n * Block plugin if critical vulnerabilities exceed this\n */\n maxCritical: z.number().int().min(0).default(0).describe('Maximum allowed critical vulnerabilities before blocking'),\n \n /**\n * Block plugin if high vulnerabilities exceed this\n */\n maxHigh: z.number().int().min(0).default(0).describe('Maximum allowed high vulnerabilities before blocking'),\n \n /**\n * Warn if medium vulnerabilities exceed this\n */\n maxMedium: z.number().int().min(0).default(5).describe('Maximum allowed medium vulnerabilities before warning'),\n }).describe('Vulnerability count thresholds for policy enforcement'),\n \n /**\n * Allowed licenses\n */\n allowedLicenses: z.array(z.string()).default([\n 'MIT',\n 'Apache-2.0',\n 'BSD-3-Clause',\n 'BSD-2-Clause',\n 'ISC',\n ]).describe('List of SPDX license identifiers that are permitted'),\n \n /**\n * Prohibited licenses\n */\n prohibitedLicenses: z.array(z.string()).default([\n 'GPL-3.0',\n 'AGPL-3.0',\n ]).describe('List of SPDX license identifiers that are prohibited'),\n \n /**\n * Code signing requirements\n */\n codeSigning: z.object({\n required: z.boolean().default(false).describe('Whether code signing is required for plugins'),\n allowedSigners: z.array(z.string()).default([]).describe('List of trusted signer identities'),\n }).optional().describe('Code signing requirements for plugin artifacts'),\n \n /**\n * Sandbox restrictions\n */\n sandbox: z.object({\n /**\n * Restrict network access\n */\n networkAccess: z.enum(['none', 'localhost', 'allowlist', 'all']).default('all').describe('Level of network access granted to the plugin'),\n \n /**\n * Allowed network destinations (if allowlist)\n */\n allowedDestinations: z.array(z.string()).default([]).describe('Permitted network destinations when using allowlist mode'),\n \n /**\n * File system access\n */\n filesystemAccess: z.enum(['none', 'read-only', 'temp-only', 'full']).default('full').describe('Level of file system access granted to the plugin'),\n \n /**\n * Maximum memory (MB)\n */\n maxMemoryMB: z.number().int().positive().optional().describe('Maximum memory allocation in megabytes'),\n \n /**\n * Maximum CPU time (seconds)\n */\n maxCPUSeconds: z.number().int().positive().optional().describe('Maximum CPU time allowed in seconds'),\n }).optional().describe('Sandbox restrictions for plugin execution'),\n}).describe('Security policy governing plugin scanning and enforcement');\n\nexport type SecurityPolicy = z.infer;\n\n// ============================================================================\n// Dependency Resolution\n// ============================================================================\n\n/**\n * Package Dependency\n */\nexport const PackageDependencySchema = z.object({\n /**\n * Package name/ID\n */\n name: z.string().describe('Package name or identifier'),\n \n /**\n * Version constraint (semver range)\n */\n versionConstraint: z.string().describe('Semver range (e.g., `^1.0.0`, `>=2.0.0 <3.0.0`)'),\n \n /**\n * Dependency type\n */\n type: z.enum(['required', 'optional', 'peer', 'dev']).default('required').describe('Category of the dependency relationship'),\n \n /**\n * Resolved version (filled during resolution)\n */\n resolvedVersion: z.string().optional().describe('Concrete version resolved during dependency resolution'),\n}).describe('A package dependency with its version constraint');\n\nexport type PackageDependency = z.infer;\n\n/**\n * Dependency Graph Node\n */\nexport const DependencyGraphNodeSchema = z.object({\n /**\n * Package identifier\n */\n id: z.string().describe('Unique identifier of the package'),\n \n /**\n * Package version\n */\n version: z.string().describe('Resolved version of the package'),\n \n /**\n * Dependencies of this package\n */\n dependencies: z.array(PackageDependencySchema).default([]).describe('Dependencies required by this package'),\n \n /**\n * Depth in dependency tree\n */\n depth: z.number().int().min(0).describe('Depth level in the dependency tree (0 = root)'),\n \n /**\n * Whether this is a direct dependency\n */\n isDirect: z.boolean().describe('Whether this is a direct (top-level) dependency'),\n \n /**\n * Package metadata\n */\n metadata: z.object({\n name: z.string().describe('Display name of the package'),\n description: z.string().optional().describe('Short description of the package'),\n license: z.string().optional().describe('SPDX license identifier of the package'),\n homepage: z.string().url().optional().describe('Homepage URL of the package'),\n }).optional().describe('Additional metadata about the package'),\n}).describe('A node in the dependency graph representing a resolved package');\n\nexport type DependencyGraphNode = z.infer;\n\n/**\n * Dependency Graph\n */\nexport const DependencyGraphSchema = z.object({\n /**\n * Root package\n */\n root: z.object({\n id: z.string().describe('Identifier of the root package'),\n version: z.string().describe('Version of the root package'),\n }).describe('Root package of the dependency graph'),\n \n /**\n * All nodes in the graph\n */\n nodes: z.array(DependencyGraphNodeSchema).describe('All resolved package nodes in the dependency graph'),\n \n /**\n * Edges (dependency relationships)\n */\n edges: z.array(z.object({\n from: z.string().describe('Package ID'),\n to: z.string().describe('Package ID'),\n constraint: z.string().describe('Version constraint'),\n })).describe('Directed edges representing dependency relationships'),\n \n /**\n * Resolution statistics\n */\n stats: z.object({\n totalDependencies: z.number().int().min(0).describe('Total number of resolved dependencies'),\n directDependencies: z.number().int().min(0).describe('Number of direct (top-level) dependencies'),\n maxDepth: z.number().int().min(0).describe('Maximum depth of the dependency tree'),\n }).describe('Summary statistics for the dependency graph'),\n}).describe('Complete dependency graph for a package and its transitive dependencies');\n\nexport type DependencyGraph = z.infer;\n\n/**\n * Dependency Conflict\n * \n * Hub-level dependency conflict detected during plugin resolution.\n * Focuses on package version conflicts across the marketplace/registry.\n * \n * @see kernel/plugin-versioning.zod.ts DependencyConflictSchema for kernel-level plugin conflicts\n * which models plugin-to-plugin conflicts with richer resolution strategies.\n */\nexport const PackageDependencyConflictSchema = z.object({\n /**\n * Package with conflict\n */\n package: z.string().describe('Name of the package with conflicting version requirements'),\n \n /**\n * Conflicting versions\n */\n conflicts: z.array(z.object({\n version: z.string().describe('Conflicting version of the package'),\n requestedBy: z.array(z.string()).describe('Packages that require this version'),\n constraint: z.string().describe('Semver constraint that produced this version requirement'),\n })).describe('List of conflicting version requirements'),\n \n /**\n * Suggested resolution\n */\n resolution: z.object({\n strategy: z.enum(['pick-highest', 'pick-lowest', 'manual']).describe('Strategy used to resolve the conflict'),\n version: z.string().optional().describe('Resolved version selected by the strategy'),\n reason: z.string().optional().describe('Explanation of why this resolution was chosen'),\n }).optional().describe('Suggested resolution for the conflict'),\n \n /**\n * Severity\n */\n severity: z.enum(['error', 'warning', 'info']).describe('Severity level of the dependency conflict'),\n}).describe('A detected conflict between dependency version requirements');\n\nexport type PackageDependencyConflict = z.infer;\n\n/**\n * Dependency Resolution Result\n */\nexport const PackageDependencyResolutionResultSchema = z.object({\n /**\n * Resolution status\n */\n status: z.enum(['success', 'conflict', 'error']).describe('Overall status of the dependency resolution'),\n \n /**\n * Resolved dependency graph\n */\n graph: DependencyGraphSchema.optional().describe('Resolved dependency graph if resolution succeeded'),\n \n /**\n * Conflicts detected\n */\n conflicts: z.array(PackageDependencyConflictSchema).default([]).describe('List of dependency conflicts detected during resolution'),\n \n /**\n * Errors encountered\n */\n errors: z.array(z.object({\n package: z.string().describe('Name of the package that caused the error'),\n error: z.string().describe('Error message describing what went wrong'),\n })).default([]).describe('Errors encountered during dependency resolution'),\n \n /**\n * Installation order (topological sort)\n */\n installOrder: z.array(z.string()).default([]).describe('Topologically sorted list of package IDs for installation'),\n \n /**\n * Resolution time (ms)\n */\n resolvedIn: z.number().int().min(0).optional().describe('Time taken to resolve dependencies in milliseconds'),\n}).describe('Result of a dependency resolution process');\n\nexport type PackageDependencyResolutionResult = z.infer;\n\n// ============================================================================\n// Supply Chain Security\n// ============================================================================\n\n/**\n * SBOM (Software Bill of Materials) Entry\n */\nexport const SBOMEntrySchema = z.object({\n /**\n * Component name\n */\n name: z.string().describe('Name of the software component'),\n \n /**\n * Component version\n */\n version: z.string().describe('Version of the software component'),\n \n /**\n * Package URL (purl)\n */\n purl: z.string().optional().describe('Package URL identifier'),\n \n /**\n * License\n */\n license: z.string().optional().describe('SPDX license identifier of the component'),\n \n /**\n * Hashes\n */\n hashes: z.object({\n sha256: z.string().optional().describe('SHA-256 hash of the component artifact'),\n sha512: z.string().optional().describe('SHA-512 hash of the component artifact'),\n }).optional().describe('Cryptographic hashes for integrity verification'),\n \n /**\n * Supplier\n */\n supplier: z.object({\n name: z.string().describe('Name of the component supplier'),\n url: z.string().url().optional().describe('URL of the component supplier'),\n }).optional().describe('Supplier information for the component'),\n \n /**\n * External references\n */\n externalRefs: z.array(z.object({\n type: z.enum(['website', 'repository', 'documentation', 'issue-tracker']).describe('Type of external reference'),\n url: z.string().url().describe('URL of the external reference'),\n })).default([]).describe('External references related to the component'),\n}).describe('A single entry in a Software Bill of Materials');\n\nexport type SBOMEntry = z.infer;\n\n/**\n * Software Bill of Materials (SBOM)\n */\nexport const SBOMSchema = z.object({\n /**\n * SBOM format\n */\n format: z.enum(['spdx', 'cyclonedx']).default('cyclonedx').describe('SBOM standard format used'),\n \n /**\n * SBOM version\n */\n version: z.string().describe('Version of the SBOM specification'),\n \n /**\n * Plugin metadata\n */\n plugin: z.object({\n id: z.string().describe('Plugin identifier'),\n version: z.string().describe('Plugin version'),\n name: z.string().describe('Human-readable plugin name'),\n }).describe('Metadata about the plugin this SBOM describes'),\n \n /**\n * Components (dependencies)\n */\n components: z.array(SBOMEntrySchema).describe('List of software components included in the plugin'),\n \n /**\n * Generation timestamp\n */\n generatedAt: z.string().datetime().describe('ISO 8601 timestamp when the SBOM was generated'),\n \n /**\n * Generator tool\n */\n generator: z.object({\n name: z.string().describe('Name of the SBOM generator tool'),\n version: z.string().describe('Version of the SBOM generator tool'),\n }).optional().describe('Tool used to generate this SBOM'),\n}).describe('Software Bill of Materials for a plugin');\n\nexport type SBOM = z.infer;\n\n/**\n * Plugin Provenance\n * Verifiable chain of custody for plugin artifacts\n */\nexport const PluginProvenanceSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string().describe('Unique identifier of the plugin'),\n \n /**\n * Plugin version\n */\n version: z.string().describe('Version of the plugin artifact'),\n \n /**\n * Build information\n */\n build: z.object({\n /**\n * Build timestamp\n */\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the build was produced'),\n \n /**\n * Build environment\n */\n environment: z.object({\n os: z.string().describe('Operating system used for the build'),\n arch: z.string().describe('CPU architecture used for the build'),\n nodeVersion: z.string().describe('Node.js version used for the build'),\n }).optional().describe('Environment details where the build was executed'),\n \n /**\n * Source repository\n */\n source: z.object({\n repository: z.string().url().describe('URL of the source repository'),\n commit: z.string().regex(/^[a-f0-9]{40}$/).describe('Full SHA-1 commit hash of the source'),\n branch: z.string().optional().describe('Branch name the build was produced from'),\n tag: z.string().optional().describe('Git tag associated with the build'),\n }).optional().describe('Source repository information for the build'),\n \n /**\n * Builder identity\n */\n builder: z.object({\n name: z.string().describe('Name of the person or system that produced the build'),\n email: z.string().email().optional().describe('Email address of the builder'),\n }).optional().describe('Identity of the builder who produced the artifact'),\n }).describe('Build provenance information'),\n \n /**\n * Artifact hashes\n */\n artifacts: z.array(z.object({\n filename: z.string().describe('Name of the artifact file'),\n sha256: z.string().describe('SHA-256 hash of the artifact'),\n size: z.number().int().positive().describe('Size of the artifact in bytes'),\n })).describe('List of build artifacts with integrity hashes'),\n \n /**\n * Signatures\n */\n signatures: z.array(z.object({\n algorithm: z.enum(['rsa', 'ecdsa', 'ed25519']).describe('Cryptographic algorithm used for signing'),\n publicKey: z.string().describe('Public key used to verify the signature'),\n signature: z.string().describe('Digital signature value'),\n signedBy: z.string().describe('Identity of the signer'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the signature was created'),\n })).default([]).describe('Cryptographic signatures for the plugin artifact'),\n \n /**\n * Attestations\n */\n attestations: z.array(z.object({\n type: z.enum(['code-review', 'security-scan', 'test-results', 'ci-build']).describe('Type of attestation'),\n status: z.enum(['passed', 'failed']).describe('Result status of the attestation'),\n url: z.string().url().optional().describe('URL with details about the attestation'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp when the attestation was issued'),\n })).default([]).describe('Verification attestations for the plugin'),\n}).describe('Verifiable provenance and chain of custody for a plugin artifact');\n\nexport type PluginProvenance = z.infer;\n\n// ============================================================================\n// Trust & Verification\n// ============================================================================\n\n/**\n * Plugin Trust Score\n */\nexport const PluginTrustScoreSchema = z.object({\n /**\n * Plugin identifier\n */\n pluginId: z.string().describe('Unique identifier of the plugin'),\n \n /**\n * Overall trust score (0-100)\n */\n score: z.number().min(0).max(100).describe('Overall trust score from 0 to 100'),\n \n /**\n * Score components\n */\n components: z.object({\n /**\n * Vendor reputation (0-100)\n */\n vendorReputation: z.number().min(0).max(100).describe('Vendor reputation score from 0 to 100'),\n \n /**\n * Security scan results (0-100)\n */\n securityScore: z.number().min(0).max(100).describe('Security scan results score from 0 to 100'),\n \n /**\n * Code quality (0-100)\n */\n codeQuality: z.number().min(0).max(100).describe('Code quality score from 0 to 100'),\n \n /**\n * Community engagement (0-100)\n */\n communityScore: z.number().min(0).max(100).describe('Community engagement score from 0 to 100'),\n \n /**\n * Update frequency (0-100)\n */\n maintenanceScore: z.number().min(0).max(100).describe('Maintenance and update frequency score from 0 to 100'),\n }).describe('Individual score components contributing to the overall trust score'),\n \n /**\n * Trust level\n */\n level: z.enum(['verified', 'trusted', 'neutral', 'untrusted', 'blocked']).describe('Computed trust level based on the overall score'),\n \n /**\n * Verification badges\n */\n badges: z.array(z.enum([\n 'official', // Official ObjectStack plugin\n 'verified-vendor', // Verified vendor\n 'security-scanned', // Passed security scan\n 'code-signed', // Digitally signed\n 'open-source', // Open source\n 'popular', // High downloads\n ])).default([]).describe('Verification badges earned by the plugin'),\n \n /**\n * Last updated\n */\n updatedAt: z.string().datetime().describe('ISO 8601 timestamp when the trust score was last updated'),\n}).describe('Trust score and verification status for a plugin');\n\nexport type PluginTrustScore = z.infer;\n\n// ============================================================================\n// Export All\n// ============================================================================\n\nexport const PluginSecurityProtocol = {\n VulnerabilitySeverity,\n SecurityVulnerability: SecurityVulnerabilitySchema,\n SecurityScanResult: SecurityScanResultSchema,\n SecurityPolicy: SecurityPolicySchema,\n PackageDependency: PackageDependencySchema,\n DependencyGraphNode: DependencyGraphNodeSchema,\n DependencyGraph: DependencyGraphSchema,\n DependencyConflict: PackageDependencyConflictSchema,\n DependencyResolutionResult: PackageDependencyResolutionResultSchema,\n SBOMEntry: SBOMEntrySchema,\n SBOM: SBOMSchema,\n PluginProvenance: PluginProvenanceSchema,\n PluginTrustScore: PluginTrustScoreSchema,\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Cloud Protocol\n *\n * Cloud-specific protocols for the ObjectStack SaaS platform.\n * These schemas define the contract for cloud services like:\n * - Marketplace (listing, publishing, review, search, install)\n * - Developer Portal (developer registration, API keys, publishing analytics)\n * - Marketplace Administration (review workflow, curation, governance)\n * - App Store (customer experience: reviews, recommendations, subscriptions)\n * - Future: Composer, Space, Hub Federation\n */\nexport * from './marketplace.zod';\nexport * from './developer-portal.zod';\nexport * from './marketplace-admin.zod';\nexport * from './app-store.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Marketplace Protocol\n * \n * Defines the core schemas for the plugin marketplace ecosystem, covering:\n * - **Developer Side**: Package publishing, submission, and version releases\n * - **Platform Side**: Marketplace listing, review, approval, and discovery\n * \n * This protocol defines the contract between plugin developers, the marketplace\n * platform, and customers who install plugins.\n * \n * ## Architecture Alignment\n * - **Salesforce AppExchange**: Security review, managed packages, listing profiles\n * - **VS Code Marketplace**: Extension publishing, ratings, verified publishers\n * - **npm Registry**: Package publishing, versioning, scoped packages\n * - **Shopify App Store**: App review process, billing integration, merchant installs\n * \n * ## Developer Publishing Flow\n * ```\n * 1. Develop → Build plugin locally using ObjectStack CLI\n * 2. Validate → Run `os plugin validate` (schema + security checks)\n * 3. Build → Run `os plugin build` (bundle + sign)\n * 4. Submit → Run `os plugin publish` (submit to marketplace)\n * 5. Review → Platform conducts automated + manual review\n * 6. Publish → Approved listing goes live on marketplace\n * ```\n * \n * ## Platform Management Flow\n * ```\n * 1. Receive → Accept submissions from verified publishers\n * 2. Scan → Automated security scan and compatibility check\n * 3. Review → Human review for quality and policy compliance\n * 4. Catalog → Index in marketplace search catalog\n * 5. Monitor → Track installs, ratings, issues, and enforce SLAs\n * ```\n */\n\n// ==========================================\n// Publisher Identity\n// ==========================================\n\n/**\n * Publisher Verification Status\n */\nexport const PublisherVerificationSchema = z.enum([\n 'unverified', // Not yet verified\n 'pending', // Verification in progress\n 'verified', // Identity verified by platform\n 'trusted', // Trusted publisher (track record of quality)\n 'partner', // Official platform partner\n]).describe('Publisher verification status');\n\n/**\n * Publisher Schema\n * Represents a developer or organization that publishes packages.\n */\nexport const PublisherSchema = z.object({\n /** Publisher unique identifier */\n id: z.string().describe('Publisher ID'),\n\n /** Display name */\n name: z.string().describe('Publisher display name'),\n\n /** Publisher type */\n type: z.enum(['individual', 'organization']).describe('Publisher type'),\n\n /** Verification status */\n verification: PublisherVerificationSchema.default('unverified')\n .describe('Publisher verification status'),\n\n /** Contact email */\n email: z.string().email().optional().describe('Contact email'),\n\n /** Website URL */\n website: z.string().url().optional().describe('Publisher website'),\n\n /** Organization logo URL */\n logoUrl: z.string().url().optional().describe('Publisher logo URL'),\n\n /** Short description/bio */\n description: z.string().optional().describe('Publisher description'),\n\n /** Registration date */\n registeredAt: z.string().datetime().optional()\n .describe('Publisher registration timestamp'),\n}).describe('Developer or organization that publishes packages');\n\n// ==========================================\n// Artifact Reference & Distribution\n// ==========================================\n\n/**\n * Artifact Reference Schema\n *\n * Points to a downloadable package artifact with integrity verification.\n * Used in marketplace listings and install workflows.\n */\nexport const ArtifactReferenceSchema = z.object({\n /** Artifact download URL */\n url: z.string().url().describe('Artifact download URL'),\n\n /** SHA256 integrity checksum */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA256 checksum'),\n\n /** File size in bytes */\n size: z.number().int().positive().describe('Artifact size in bytes'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).default('tgz').describe('Artifact format'),\n\n /** Upload timestamp */\n uploadedAt: z.string().datetime().describe('Upload timestamp'),\n}).describe('Reference to a downloadable package artifact');\n\nexport type ArtifactReference = z.infer;\n\n/**\n * Artifact Download Response Schema\n *\n * Response from the artifact download API endpoint.\n * Provides a time-limited download URL with integrity metadata.\n */\nexport const ArtifactDownloadResponseSchema = z.object({\n /** Pre-signed or direct download URL */\n downloadUrl: z.string().url().describe('Artifact download URL (may be pre-signed)'),\n\n /** SHA256 checksum for download verification */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA256 checksum for verification'),\n\n /** File size in bytes */\n size: z.number().int().positive().describe('Artifact size in bytes'),\n\n /** Artifact format */\n format: z.enum(['tgz', 'zip']).describe('Artifact format'),\n\n /** URL expiration time (for pre-signed URLs) */\n expiresAt: z.string().datetime().optional()\n .describe('URL expiration timestamp for pre-signed URLs'),\n}).describe('Artifact download response with integrity metadata');\n\nexport type ArtifactDownloadResponse = z.infer;\n\n// ==========================================\n// Marketplace Listing\n// ==========================================\n\n/**\n * Marketplace Category\n */\nexport const MarketplaceCategorySchema = z.enum([\n 'crm', // Customer Relationship Management\n 'erp', // Enterprise Resource Planning\n 'hr', // Human Resources\n 'finance', // Finance & Accounting\n 'project', // Project Management\n 'collaboration', // Collaboration & Communication\n 'analytics', // Analytics & Reporting\n 'integration', // Integrations & Connectors\n 'automation', // Automation & Workflows\n 'ai', // AI & Machine Learning\n 'security', // Security & Compliance\n 'developer-tools', // Developer Tools\n 'ui-theme', // UI Themes & Appearance\n 'storage', // Storage & Drivers\n 'other', // Other / Uncategorized\n]).describe('Marketplace package category');\n\n/**\n * Listing Status\n */\nexport const ListingStatusSchema = z.enum([\n 'draft', // Not yet submitted\n 'submitted', // Submitted for review\n 'in-review', // Under review\n 'approved', // Approved, ready to publish\n 'published', // Live on marketplace\n 'rejected', // Review rejected\n 'suspended', // Suspended by platform (policy violation)\n 'deprecated', // Deprecated by publisher\n 'unlisted', // Available by direct link only\n]).describe('Marketplace listing status');\n\n/**\n * Pricing Model\n */\nexport const PricingModelSchema = z.enum([\n 'free', // Free to install\n 'freemium', // Free with paid premium features\n 'paid', // Requires purchase\n 'subscription', // Recurring subscription\n 'usage-based', // Pay per usage\n 'contact-sales', // Enterprise pricing, contact for quote\n]).describe('Package pricing model');\n\n/**\n * Marketplace Listing Schema\n * \n * The public-facing profile of a package on the marketplace.\n * Contains marketing information, pricing, and installation metadata.\n */\nexport const MarketplaceListingSchema = z.object({\n /** Listing ID (matches package ID) */\n id: z.string().describe('Listing ID (matches package manifest ID)'),\n\n /** Package ID (reverse domain notation) */\n packageId: z.string().describe('Package identifier'),\n\n /** Publisher information */\n publisherId: z.string().describe('Publisher ID'),\n\n /** Current listing status */\n status: ListingStatusSchema.default('draft')\n .describe('Publication state: draft, published, under-review, suspended, deprecated, or unlisted'),\n\n /** Display name */\n name: z.string().describe('Display name'),\n\n /** Tagline (short description for cards/search results) */\n tagline: z.string().max(120).optional().describe('Short tagline (max 120 chars)'),\n\n /** Full description (supports Markdown) */\n description: z.string().optional().describe('Full description (Markdown)'),\n\n /** Category */\n category: MarketplaceCategorySchema.describe('Package category'),\n\n /** Additional tags for search discovery */\n tags: z.array(z.string()).optional().describe('Search tags'),\n\n /** Icon/logo URL */\n iconUrl: z.string().url().optional().describe('Package icon URL'),\n\n /** Screenshot URLs */\n screenshots: z.array(z.object({\n url: z.string().url(),\n caption: z.string().optional(),\n })).optional().describe('Screenshots'),\n\n /** Documentation URL */\n documentationUrl: z.string().url().optional()\n .describe('Documentation URL'),\n\n /** Support URL */\n supportUrl: z.string().url().optional()\n .describe('Support URL'),\n\n /** Source repository URL (if open source) */\n repositoryUrl: z.string().url().optional()\n .describe('Source repository URL'),\n\n /** Pricing model */\n pricing: PricingModelSchema.default('free')\n .describe('Pricing model'),\n\n /** Price in cents (if paid) */\n priceInCents: z.number().int().min(0).optional()\n .describe('Price in cents (e.g. 999 = $9.99)'),\n\n /** Latest published version */\n latestVersion: z.string().describe('Latest published version'),\n\n /** Minimum platform version required */\n minPlatformVersion: z.string().optional()\n .describe('Minimum ObjectStack platform version'),\n\n /** Available versions for installation */\n versions: z.array(z.object({\n version: z.string().describe('Version string'),\n releaseDate: z.string().datetime().describe('Release date'),\n releaseNotes: z.string().optional().describe('Release notes'),\n minPlatformVersion: z.string().optional().describe('Minimum platform version'),\n deprecated: z.boolean().default(false).describe('Whether this version is deprecated'),\n /** Artifact reference for this version */\n artifact: ArtifactReferenceSchema.optional()\n .describe('Downloadable artifact for this version'),\n })).optional().describe('Published versions'),\n\n /** Aggregate statistics */\n stats: z.object({\n totalInstalls: z.number().int().min(0).default(0).describe('Total installs'),\n activeInstalls: z.number().int().min(0).default(0).describe('Active installs'),\n averageRating: z.number().min(0).max(5).optional().describe('Average user rating (0-5)'),\n totalRatings: z.number().int().min(0).default(0).describe('Total ratings count'),\n totalReviews: z.number().int().min(0).default(0).describe('Total reviews count'),\n }).optional().describe('Aggregate marketplace statistics'),\n\n /** First published date */\n publishedAt: z.string().datetime().optional()\n .describe('First published timestamp'),\n\n /** Last updated date */\n updatedAt: z.string().datetime().optional()\n .describe('Last updated timestamp'),\n}).describe('Public-facing package listing on the marketplace');\n\n// ==========================================\n// Package Submission & Review\n// ==========================================\n\n/**\n * Package Submission Schema\n * A developer's submission of a package version for marketplace review.\n */\nexport const PackageSubmissionSchema = z.object({\n /** Submission ID */\n id: z.string().describe('Submission ID'),\n\n /** Package ID */\n packageId: z.string().describe('Package identifier'),\n\n /** Version being submitted */\n version: z.string().describe('Version being submitted'),\n\n /** Publisher ID */\n publisherId: z.string().describe('Publisher submitting'),\n\n /** Submission status */\n status: z.enum([\n 'pending', // Awaiting review\n 'scanning', // Automated scan in progress\n 'in-review', // Under manual review\n 'changes-requested', // Reviewer requests changes\n 'approved', // Approved for publishing\n 'rejected', // Rejected\n ]).default('pending').describe('Review status'),\n\n /**\n * Package artifact URL or reference.\n * Points to the built package bundle for review.\n */\n artifactUrl: z.string().describe('Package artifact URL for review'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional().describe('Release notes for this version'),\n\n /** Whether this is the first submission (new listing) vs version update */\n isNewListing: z.boolean().default(false).describe('Whether this is a new listing submission'),\n\n /** Automated scan results */\n scanResults: z.object({\n /** Whether automated scan passed */\n passed: z.boolean(),\n /** Security scan score (0-100) */\n securityScore: z.number().min(0).max(100).optional(),\n /** Compatibility check passed */\n compatibilityCheck: z.boolean().optional(),\n /** Issues found during scan */\n issues: z.array(z.object({\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),\n message: z.string(),\n file: z.string().optional(),\n line: z.number().optional(),\n })).optional(),\n }).optional().describe('Automated scan results'),\n\n /** Reviewer notes (from platform reviewer) */\n reviewerNotes: z.string().optional().describe('Notes from the platform reviewer'),\n\n /** Submitted timestamp */\n submittedAt: z.string().datetime().optional().describe('Submission timestamp'),\n\n /** Review completed timestamp */\n reviewedAt: z.string().datetime().optional().describe('Review completion timestamp'),\n}).describe('Developer submission of a package version for review');\n\n// ==========================================\n// Marketplace Search & Discovery\n// ==========================================\n\n/**\n * Marketplace Search Request\n */\nexport const MarketplaceSearchRequestSchema = z.object({\n /** Search query string */\n query: z.string().optional().describe('Full-text search query'),\n\n /** Filter by category */\n category: MarketplaceCategorySchema.optional().describe('Filter by category'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n\n /** Filter by pricing model */\n pricing: PricingModelSchema.optional().describe('Filter by pricing model'),\n\n /** Filter by publisher verification level */\n publisherVerification: PublisherVerificationSchema.optional()\n .describe('Filter by publisher verification level'),\n\n /** Sort by */\n sortBy: z.enum([\n 'relevance', // Best match (default for search)\n 'popularity', // Most installs\n 'rating', // Highest rated\n 'newest', // Most recently published\n 'updated', // Most recently updated\n 'name', // Alphabetical\n ]).default('relevance').describe('Sort field'),\n\n /** Sort direction */\n sortDirection: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),\n\n /** Pagination: page number */\n page: z.number().int().min(1).default(1).describe('Page number'),\n\n /** Pagination: items per page */\n pageSize: z.number().int().min(1).max(100).default(20).describe('Items per page'),\n\n /** Filter by minimum platform version compatibility */\n platformVersion: z.string().optional()\n .describe('Filter by platform version compatibility'),\n}).describe('Marketplace search request');\n\n/**\n * Marketplace Search Response\n */\nexport const MarketplaceSearchResponseSchema = z.object({\n /** Search results */\n items: z.array(MarketplaceListingSchema).describe('Search result listings'),\n\n /** Total count (for pagination) */\n total: z.number().int().min(0).describe('Total matching results'),\n\n /** Current page */\n page: z.number().int().min(1).describe('Current page number'),\n\n /** Items per page */\n pageSize: z.number().int().min(1).describe('Items per page'),\n\n /** Facets for filtering */\n facets: z.object({\n categories: z.array(z.object({\n category: MarketplaceCategorySchema,\n count: z.number().int().min(0),\n })).optional(),\n pricing: z.array(z.object({\n model: PricingModelSchema,\n count: z.number().int().min(0),\n })).optional(),\n }).optional().describe('Aggregation facets for refining search'),\n}).describe('Marketplace search response');\n\n// ==========================================\n// Marketplace Install from Marketplace\n// ==========================================\n\n/**\n * Install from Marketplace Request\n * Extends the basic package install with marketplace-specific fields.\n */\nexport const MarketplaceInstallRequestSchema = z.object({\n /** Listing ID to install */\n listingId: z.string().describe('Marketplace listing ID'),\n\n /** Specific version to install (defaults to latest) */\n version: z.string().optional().describe('Version to install'),\n\n /** License key (for paid packages) */\n licenseKey: z.string().optional().describe('License key for paid packages'),\n\n /** User-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n\n /** Whether to enable immediately after install */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n\n /** Artifact reference (resolved from listing version, or provided directly) */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference for direct installation'),\n\n /** Tenant ID */\n tenantId: z.string().optional().describe('Tenant identifier'),\n}).describe('Install from marketplace request');\n\n/**\n * Install from Marketplace Response\n */\nexport const MarketplaceInstallResponseSchema = z.object({\n /** Whether installation was successful */\n success: z.boolean().describe('Whether installation succeeded'),\n\n /** Installed package ID */\n packageId: z.string().optional().describe('Installed package identifier'),\n\n /** Installed version */\n version: z.string().optional().describe('Installed version'),\n\n /** Human-readable message */\n message: z.string().optional().describe('Installation status message'),\n}).describe('Install from marketplace response');\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type PublisherVerification = z.infer;\nexport type Publisher = z.infer;\nexport type MarketplaceCategory = z.infer;\nexport type ListingStatus = z.infer;\nexport type PricingModel = z.infer;\nexport type MarketplaceListing = z.infer;\nexport type PackageSubmission = z.infer;\nexport type MarketplaceSearchRequest = z.infer;\nexport type MarketplaceSearchResponse = z.infer;\nexport type MarketplaceInstallRequest = z.infer;\nexport type MarketplaceInstallResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PublisherVerificationSchema } from './marketplace.zod';\n\n/**\n * # Developer Portal Protocol\n *\n * Defines schemas for the developer-facing side of the marketplace ecosystem.\n * Covers the complete developer journey:\n *\n * ```\n * Register → Create App → Develop → Validate → Build → Submit → Monitor → Iterate\n * ```\n *\n * ## Architecture Alignment\n * - **Salesforce Partner Portal**: ISV registration, AppExchange publishing, Trialforce\n * - **Shopify Partner Dashboard**: App management, analytics, billing\n * - **VS Code Marketplace Management**: Extension publishing, statistics, tokens\n *\n * ## Identity Integration (better-auth)\n * Authentication, organization management, and API keys are handled by the\n * Identity module (`@objectstack/spec` Identity namespace), which follows the\n * better-auth specification. This module only defines marketplace-specific\n * extensions on top of the shared identity layer:\n *\n * - **User & Session** → `Identity.UserSchema`, `Identity.SessionSchema`\n * - **Organization & Members** → `Identity.OrganizationSchema`, `Identity.MemberSchema`\n * - **API Keys** → `Identity.ApiKeySchema` (with marketplace scopes)\n *\n * ## Key Concepts\n * - **Publisher Profile**: Links an Identity Organization to a marketplace publisher\n * - **App Listing Management**: CRUD for marketplace listings (draft → published)\n * - **Version Channels**: alpha / beta / rc / stable release channels\n * - **Publishing Analytics**: Install trends, revenue, ratings over time\n */\n\n// ==========================================\n// Publisher Profile (extends Identity.Organization)\n// ==========================================\n\n/**\n * Publisher Profile Schema\n *\n * Links an Identity Organization to a marketplace publisher identity.\n * The organization itself (name, slug, logo, members) is managed via\n * Identity.OrganizationSchema and Identity.MemberSchema (better-auth aligned).\n *\n * This schema only holds marketplace-specific publisher metadata.\n */\nexport const PublisherProfileSchema = z.object({\n /** Organization ID (references Identity.Organization.id) */\n organizationId: z.string().describe('Identity Organization ID'),\n\n /** Publisher ID (marketplace-assigned identifier) */\n publisherId: z.string().describe('Marketplace publisher ID'),\n\n /** Verification level (marketplace trust tier) */\n verification: PublisherVerificationSchema.default('unverified'),\n\n /** Accepted developer program agreement version */\n agreementVersion: z.string().optional().describe('Accepted developer agreement version'),\n\n /** Publisher-specific website (may differ from org) */\n website: z.string().url().optional().describe('Publisher website'),\n\n /** Publisher-specific support email */\n supportEmail: z.string().email().optional().describe('Publisher support email'),\n\n /** Registration timestamp (when org became a publisher) */\n registeredAt: z.string().datetime(),\n});\n\n// ==========================================\n// Version Channels & Release Management\n// ==========================================\n\n/**\n * Release Channel — allows pre-release distribution\n */\nexport const ReleaseChannelSchema = z.enum([\n 'alpha', // Early development, unstable\n 'beta', // Feature-complete, testing phase\n 'rc', // Release candidate, final testing\n 'stable', // Production-ready, general availability\n]);\n\n/**\n * Version Release Schema\n *\n * A single version release of a package with channel assignment.\n */\nexport const VersionReleaseSchema = z.object({\n /** Semver version string */\n version: z.string().describe('Semver version (e.g., 2.1.0-beta.1)'),\n\n /** Release channel */\n channel: ReleaseChannelSchema.default('stable'),\n\n /** Release notes (Markdown) */\n releaseNotes: z.string().optional().describe('Release notes (Markdown)'),\n\n /** Changelog entries (structured) */\n changelog: z.array(z.object({\n type: z.enum(['added', 'changed', 'fixed', 'removed', 'deprecated', 'security']),\n description: z.string(),\n })).optional().describe('Structured changelog entries'),\n\n /** Minimum platform version required */\n minPlatformVersion: z.string().optional(),\n\n /** Build artifact URL */\n artifactUrl: z.string().optional().describe('Built package artifact URL'),\n\n /** Artifact checksum (integrity) */\n artifactChecksum: z.string().optional().describe('SHA-256 checksum'),\n\n /** Whether this version is deprecated */\n deprecated: z.boolean().default(false),\n\n /** Deprecation message (if deprecated) */\n deprecationMessage: z.string().optional(),\n\n /** Release timestamp */\n releasedAt: z.string().datetime().optional(),\n});\n\n// ==========================================\n// App Listing Management (Developer CRUD)\n// ==========================================\n\n/**\n * Create Listing Request — developer creates a new marketplace listing\n */\nexport const CreateListingRequestSchema = z.object({\n /** Package ID (reverse domain, e.g., com.acme.crm) */\n packageId: z.string().describe('Package identifier'),\n\n /** Display name */\n name: z.string().describe('App display name'),\n\n /** Short tagline (max 120 chars) */\n tagline: z.string().max(120).optional(),\n\n /** Full description (Markdown) */\n description: z.string().optional(),\n\n /** Category */\n category: z.string().describe('Marketplace category'),\n\n /** Additional tags */\n tags: z.array(z.string()).optional(),\n\n /** Icon URL */\n iconUrl: z.string().url().optional(),\n\n /** Screenshots */\n screenshots: z.array(z.object({\n url: z.string().url(),\n caption: z.string().optional(),\n })).optional(),\n\n /** Documentation URL */\n documentationUrl: z.string().url().optional(),\n\n /** Support URL */\n supportUrl: z.string().url().optional(),\n\n /** Source repository URL */\n repositoryUrl: z.string().url().optional(),\n\n /** Pricing model */\n pricing: z.enum([\n 'free', 'freemium', 'paid', 'subscription', 'usage-based', 'contact-sales',\n ]).default('free'),\n\n /** Price in cents (if paid) */\n priceInCents: z.number().int().min(0).optional(),\n});\n\n/**\n * Update Listing Request — developer updates listing metadata\n */\nexport const UpdateListingRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing ID to update'),\n\n /** Updatable fields (all optional, partial update) */\n name: z.string().optional(),\n tagline: z.string().max(120).optional(),\n description: z.string().optional(),\n category: z.string().optional(),\n tags: z.array(z.string()).optional(),\n iconUrl: z.string().url().optional(),\n screenshots: z.array(z.object({\n url: z.string().url(),\n caption: z.string().optional(),\n })).optional(),\n documentationUrl: z.string().url().optional(),\n supportUrl: z.string().url().optional(),\n repositoryUrl: z.string().url().optional(),\n pricing: z.enum([\n 'free', 'freemium', 'paid', 'subscription', 'usage-based', 'contact-sales',\n ]).optional(),\n priceInCents: z.number().int().min(0).optional(),\n});\n\n/**\n * Listing Action Request — lifecycle actions on a listing\n */\nexport const ListingActionRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing ID'),\n\n /** Action to perform */\n action: z.enum([\n 'submit', // Submit for review\n 'unlist', // Remove from public search (keep accessible by direct link)\n 'deprecate', // Mark as deprecated\n 'reactivate', // Reactivate unlisted/deprecated listing\n ]).describe('Action to perform on listing'),\n\n /** Reason for action (e.g., deprecation message) */\n reason: z.string().optional(),\n});\n\n// ==========================================\n// Publishing Analytics (Developer Dashboard)\n// ==========================================\n\n/**\n * Analytics Time Range\n */\nexport const AnalyticsTimeRangeSchema = z.enum([\n 'last_7d',\n 'last_30d',\n 'last_90d',\n 'last_365d',\n 'all_time',\n]);\n\n/**\n * Publishing Analytics Request\n */\nexport const PublishingAnalyticsRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing to get analytics for'),\n\n /** Time range */\n timeRange: AnalyticsTimeRangeSchema.default('last_30d'),\n\n /** Metrics to include */\n metrics: z.array(z.enum([\n 'installs', // Install count over time\n 'uninstalls', // Uninstall count over time\n 'active_installs', // Active install trend\n 'ratings', // Rating distribution\n 'revenue', // Revenue (for paid apps)\n 'page_views', // Listing page views\n ])).optional().describe('Metrics to include (default: all)'),\n});\n\n/**\n * Time Series Data Point\n */\nexport const TimeSeriesPointSchema = z.object({\n /** ISO date string (day granularity) */\n date: z.string(),\n /** Metric value */\n value: z.number(),\n});\n\n/**\n * Publishing Analytics Response\n */\nexport const PublishingAnalyticsResponseSchema = z.object({\n /** Listing ID */\n listingId: z.string(),\n\n /** Time range */\n timeRange: AnalyticsTimeRangeSchema,\n\n /** Summary statistics */\n summary: z.object({\n totalInstalls: z.number().int().min(0),\n activeInstalls: z.number().int().min(0),\n totalUninstalls: z.number().int().min(0),\n averageRating: z.number().min(0).max(5).optional(),\n totalRatings: z.number().int().min(0),\n totalRevenue: z.number().min(0).optional().describe('Revenue in cents'),\n pageViews: z.number().int().min(0),\n }),\n\n /** Time series data by metric */\n timeSeries: z.record(z.string(), z.array(TimeSeriesPointSchema)).optional()\n .describe('Time series keyed by metric name'),\n\n /** Rating distribution (1-5 stars) */\n ratingDistribution: z.object({\n 1: z.number().int().min(0).default(0),\n 2: z.number().int().min(0).default(0),\n 3: z.number().int().min(0).default(0),\n 4: z.number().int().min(0).default(0),\n 5: z.number().int().min(0).default(0),\n }).optional(),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type PublisherProfile = z.infer;\nexport type ReleaseChannel = z.infer;\nexport type VersionRelease = z.infer;\nexport type CreateListingRequest = z.infer;\nexport type UpdateListingRequest = z.infer;\nexport type ListingActionRequest = z.infer;\nexport type AnalyticsTimeRange = z.infer;\nexport type PublishingAnalyticsRequest = z.infer;\nexport type TimeSeriesPoint = z.infer;\nexport type PublishingAnalyticsResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # Marketplace Administration Protocol\n *\n * Defines schemas for the platform (Cloud) side of marketplace operations.\n * Covers the administrative workflows for managing and governing the marketplace.\n *\n * ## Architecture Alignment\n * - **Salesforce AppExchange Admin**: Security review, ISV monitoring, partner management\n * - **Apple App Store Connect Review**: Human review process, guidelines, rejection reasons\n * - **Google Play Console**: Policy enforcement, quality gates, content moderation\n *\n * ## Key Concepts\n * - **Review Process**: Structured workflow for submission review (automated + manual)\n * - **Curation**: Featured apps, curated collections, editorial picks\n * - **Governance**: Policy enforcement, takedown, compliance\n * - **Platform Analytics**: Marketplace health, trending, abuse detection\n */\n\n// ==========================================\n// Review Process\n// ==========================================\n\n/**\n * Review Criteria — checklist items for human reviewers\n */\nexport const ReviewCriterionSchema = z.object({\n /** Criterion identifier */\n id: z.string().describe('Criterion ID'),\n\n /** Category of criterion */\n category: z.enum([\n 'security', // Security best practices\n 'performance', // Performance / resource usage\n 'quality', // Code quality / best practices\n 'ux', // User experience standards\n 'documentation', // Documentation completeness\n 'policy', // Policy compliance (no malware, GDPR, etc.)\n 'compatibility', // Platform compatibility\n ]),\n\n /** Description of what to check */\n description: z.string(),\n\n /** Whether this criterion must pass for approval */\n required: z.boolean().default(true),\n\n /** Pass/fail result */\n passed: z.boolean().optional(),\n\n /** Reviewer notes for this criterion */\n notes: z.string().optional(),\n});\n\n/**\n * Review Decision\n */\nexport const ReviewDecisionSchema = z.enum([\n 'approved', // Approved for publishing\n 'rejected', // Rejected (with reasons)\n 'changes-requested', // Needs changes before re-review\n]);\n\n/**\n * Rejection Reason Category\n */\nexport const RejectionReasonSchema = z.enum([\n 'security-vulnerability', // Security issues found\n 'policy-violation', // Violates marketplace policy\n 'quality-below-standard', // Does not meet quality bar\n 'misleading-metadata', // Listing info doesn't match functionality\n 'incompatible', // Incompatible with current platform\n 'duplicate', // Duplicate of existing listing\n 'insufficient-documentation', // Inadequate documentation\n 'other', // Other reason (see notes)\n]);\n\n/**\n * Submission Review Schema\n *\n * The review record attached to a package submission.\n */\nexport const SubmissionReviewSchema = z.object({\n /** Review ID */\n id: z.string().describe('Review ID'),\n\n /** Submission ID being reviewed */\n submissionId: z.string().describe('Submission being reviewed'),\n\n /** Reviewer user ID */\n reviewerId: z.string().describe('Platform reviewer ID'),\n\n /** Review decision */\n decision: ReviewDecisionSchema.optional().describe('Final decision'),\n\n /** Review criteria checklist */\n criteria: z.array(ReviewCriterionSchema).optional()\n .describe('Review checklist results'),\n\n /** Rejection reasons (if rejected) */\n rejectionReasons: z.array(RejectionReasonSchema).optional(),\n\n /** Detailed feedback for the developer */\n feedback: z.string().optional().describe('Detailed review feedback (Markdown)'),\n\n /** Internal notes (not visible to developer) */\n internalNotes: z.string().optional().describe('Internal reviewer notes'),\n\n /** Review started timestamp */\n startedAt: z.string().datetime().optional(),\n\n /** Review completed timestamp */\n completedAt: z.string().datetime().optional(),\n});\n\n// ==========================================\n// Curation: Featured & Collections\n// ==========================================\n\n/**\n * Featured Listing — promoted on marketplace homepage\n */\nexport const FeaturedListingSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Featured listing ID'),\n\n /** Featured position/priority (lower = higher priority) */\n priority: z.number().int().min(0).default(0),\n\n /** Featured banner image URL */\n bannerUrl: z.string().url().optional(),\n\n /** Featured reason / editorial note */\n editorialNote: z.string().optional(),\n\n /** Start date for featured period */\n startDate: z.string().datetime(),\n\n /** End date for featured period */\n endDate: z.string().datetime().optional(),\n\n /** Whether currently active */\n active: z.boolean().default(true),\n});\n\n/**\n * Curated Collection — a themed group of listings\n */\nexport const CuratedCollectionSchema = z.object({\n /** Collection unique identifier */\n id: z.string().describe('Collection ID'),\n\n /** Collection display name */\n name: z.string().describe('Collection name'),\n\n /** Collection description */\n description: z.string().optional(),\n\n /** Cover image URL */\n coverImageUrl: z.string().url().optional(),\n\n /** Listing IDs in this collection (ordered) */\n listingIds: z.array(z.string()).min(1).describe('Ordered listing IDs'),\n\n /** Whether publicly visible */\n published: z.boolean().default(false),\n\n /** Sort order for display among collections */\n sortOrder: z.number().int().min(0).default(0),\n\n /** Created by (admin user ID) */\n createdBy: z.string().optional(),\n\n /** Created at */\n createdAt: z.string().datetime().optional(),\n\n /** Updated at */\n updatedAt: z.string().datetime().optional(),\n});\n\n// ==========================================\n// Governance & Policy\n// ==========================================\n\n/**\n * Policy Violation Type\n */\nexport const PolicyViolationTypeSchema = z.enum([\n 'malware', // Malicious software\n 'data-harvesting', // Unauthorized data collection\n 'spam', // Spammy or misleading content\n 'copyright', // Copyright/IP infringement\n 'inappropriate-content', // Inappropriate or offensive content\n 'terms-of-service', // General ToS violation\n 'security-risk', // Unresolved critical security issues\n 'abandoned', // Abandoned / no longer maintained\n]);\n\n/**\n * Policy Action — enforcement action on a listing\n */\nexport const PolicyActionSchema = z.object({\n /** Action ID */\n id: z.string().describe('Action ID'),\n\n /** Listing ID */\n listingId: z.string().describe('Target listing ID'),\n\n /** Violation type */\n violationType: PolicyViolationTypeSchema,\n\n /** Action taken */\n action: z.enum([\n 'warning', // Warning to publisher\n 'suspend', // Temporarily suspend listing\n 'takedown', // Permanently remove listing\n 'restrict', // Restrict new installs (existing users keep access)\n ]),\n\n /** Detailed reason */\n reason: z.string().describe('Explanation of the violation'),\n\n /** Admin user who took the action */\n actionBy: z.string().describe('Admin user ID'),\n\n /** Timestamp */\n actionAt: z.string().datetime(),\n\n /** Resolution notes (if resolved) */\n resolution: z.string().optional(),\n\n /** Whether resolved */\n resolved: z.boolean().default(false),\n});\n\n// ==========================================\n// Platform Analytics\n// ==========================================\n\n/**\n * Marketplace Health Metrics — overall platform statistics\n */\nexport const MarketplaceHealthMetricsSchema = z.object({\n /** Total number of published listings */\n totalListings: z.number().int().min(0),\n\n /** Listings by status breakdown (partial — only non-zero statuses) */\n listingsByStatus: z.record(z.string(), z.number().int().min(0)).optional(),\n\n /** Listings by category breakdown (partial — only non-zero categories) */\n listingsByCategory: z.record(z.string(), z.number().int().min(0)).optional(),\n\n /** Total registered publishers */\n totalPublishers: z.number().int().min(0),\n\n /** Verified publishers count */\n verifiedPublishers: z.number().int().min(0),\n\n /** Total installs across all listings (all time) */\n totalInstalls: z.number().int().min(0),\n\n /** Average time from submission to review completion (hours) */\n averageReviewTime: z.number().min(0).optional(),\n\n /** Pending review queue size */\n pendingReviews: z.number().int().min(0),\n\n /** Listings by pricing model (partial — only non-zero models) */\n listingsByPricing: z.record(z.string(), z.number().int().min(0)).optional(),\n\n /** Snapshot timestamp */\n snapshotAt: z.string().datetime(),\n});\n\n/**\n * Trending Listing — computed from recent activity\n */\nexport const TrendingListingSchema = z.object({\n /** Listing ID */\n listingId: z.string(),\n\n /** Trending rank (1 = most trending) */\n rank: z.number().int().min(1),\n\n /** Trend score (computed from velocity of installs, ratings, page views) */\n trendScore: z.number().min(0),\n\n /** Install velocity (installs per day over measurement period) */\n installVelocity: z.number().min(0),\n\n /** Measurement period (e.g., \"7d\", \"30d\") */\n period: z.string(),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type ReviewCriterion = z.infer;\nexport type ReviewDecision = z.infer;\nexport type RejectionReason = z.infer;\nexport type SubmissionReview = z.infer;\nexport type FeaturedListing = z.infer;\nexport type CuratedCollection = z.infer;\nexport type PolicyViolationType = z.infer;\nexport type PolicyAction = z.infer;\nexport type MarketplaceHealthMetrics = z.infer;\nexport type TrendingListing = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { MarketplaceCategorySchema, PricingModelSchema } from './marketplace.zod';\n\n/**\n * # App Store Protocol (Customer Experience)\n *\n * Defines schemas for the end-customer experience when browsing, evaluating,\n * installing, and managing marketplace apps from within ObjectOS.\n *\n * ## Architecture Alignment\n * - **Salesforce AppExchange (Customer)**: Browse apps, read reviews, 1-click install\n * - **Shopify App Store (Merchant)**: App evaluation, trial, install, manage subscriptions\n * - **Apple App Store (User)**: Ratings, reviews, featured collections, personalized recs\n *\n * ## Customer Journey\n * ```\n * Discover → Evaluate → Install → Configure → Use → Rate/Review → Manage\n * ```\n *\n * ## Key Concepts\n * - **Reviews & Ratings**: User-submitted ratings and reviews with moderation\n * - **Collections & Recommendations**: Personalized discovery and curated picks\n * - **Subscription Management**: Manage licenses, billing, and renewals\n * - **Installed App Management**: Enable, disable, configure, upgrade, uninstall\n */\n\n// ==========================================\n// User Reviews & Ratings\n// ==========================================\n\n/**\n * Review Moderation Status\n */\nexport const ReviewModerationStatusSchema = z.enum([\n 'pending', // Awaiting moderation\n 'approved', // Approved and visible\n 'flagged', // Flagged for review\n 'rejected', // Rejected (spam, inappropriate)\n]);\n\n/**\n * User Review Schema — a customer's review of an installed app\n */\nexport const UserReviewSchema = z.object({\n /** Review ID */\n id: z.string().describe('Review ID'),\n\n /** Listing ID being reviewed */\n listingId: z.string().describe('Listing being reviewed'),\n\n /** Reviewer user ID */\n userId: z.string().describe('Review author user ID'),\n\n /** Reviewer display name */\n displayName: z.string().optional().describe('Reviewer display name'),\n\n /** Star rating (1-5) */\n rating: z.number().int().min(1).max(5).describe('Star rating (1-5)'),\n\n /** Review title */\n title: z.string().max(200).optional().describe('Review title'),\n\n /** Review body text */\n body: z.string().max(5000).optional().describe('Review text'),\n\n /** Version the reviewer is using */\n appVersion: z.string().optional().describe('App version being reviewed'),\n\n /** Moderation status */\n moderationStatus: ReviewModerationStatusSchema.default('pending'),\n\n /** Number of \"helpful\" votes from other users */\n helpfulCount: z.number().int().min(0).default(0),\n\n /** Publisher's response to this review */\n publisherResponse: z.object({\n body: z.string(),\n respondedAt: z.string().datetime(),\n }).optional().describe('Publisher response to review'),\n\n /** Submitted timestamp */\n submittedAt: z.string().datetime(),\n\n /** Updated timestamp */\n updatedAt: z.string().datetime().optional(),\n});\n\n/**\n * Submit Review Request\n */\nexport const SubmitReviewRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing to review'),\n\n /** Star rating (1-5) */\n rating: z.number().int().min(1).max(5).describe('Star rating'),\n\n /** Review title */\n title: z.string().max(200).optional(),\n\n /** Review body */\n body: z.string().max(5000).optional(),\n});\n\n/**\n * List Reviews Request — customer browsing reviews\n */\nexport const ListReviewsRequestSchema = z.object({\n /** Listing ID */\n listingId: z.string().describe('Listing to get reviews for'),\n\n /** Sort by */\n sortBy: z.enum(['newest', 'oldest', 'highest', 'lowest', 'most-helpful'])\n .default('newest'),\n\n /** Filter by rating */\n rating: z.number().int().min(1).max(5).optional(),\n\n /** Pagination */\n page: z.number().int().min(1).default(1),\n pageSize: z.number().int().min(1).max(50).default(10),\n});\n\n/**\n * List Reviews Response\n */\nexport const ListReviewsResponseSchema = z.object({\n /** Reviews */\n items: z.array(UserReviewSchema),\n\n /** Total count */\n total: z.number().int().min(0),\n\n /** Pagination */\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n\n /** Rating summary */\n ratingSummary: z.object({\n averageRating: z.number().min(0).max(5),\n totalRatings: z.number().int().min(0),\n distribution: z.object({\n 1: z.number().int().min(0).default(0),\n 2: z.number().int().min(0).default(0),\n 3: z.number().int().min(0).default(0),\n 4: z.number().int().min(0).default(0),\n 5: z.number().int().min(0).default(0),\n }),\n }).optional(),\n});\n\n// ==========================================\n// App Discovery & Recommendations\n// ==========================================\n\n/**\n * App Recommendation Reason\n */\nexport const RecommendationReasonSchema = z.enum([\n 'popular-in-category', // Popular in your industry/category\n 'similar-users', // Used by similar organizations\n 'complements-installed', // Complements apps you already use\n 'trending', // Currently trending\n 'new-release', // Recently released / major update\n 'editor-pick', // Editorial/curated recommendation\n]);\n\n/**\n * Recommended App\n */\nexport const RecommendedAppSchema = z.object({\n /** Listing ID */\n listingId: z.string(),\n\n /** App name */\n name: z.string(),\n\n /** Short tagline */\n tagline: z.string().optional(),\n\n /** Icon URL */\n iconUrl: z.string().url().optional(),\n\n /** Category */\n category: MarketplaceCategorySchema,\n\n /** Pricing */\n pricing: PricingModelSchema,\n\n /** Average rating */\n averageRating: z.number().min(0).max(5).optional(),\n\n /** Active installs */\n activeInstalls: z.number().int().min(0).optional(),\n\n /** Why this is recommended */\n reason: RecommendationReasonSchema,\n});\n\n/**\n * App Discovery Request — personalized browse/home page\n */\nexport const AppDiscoveryRequestSchema = z.object({\n /** Tenant ID for personalization */\n tenantId: z.string().optional(),\n\n /** Categories the customer is interested in */\n categories: z.array(MarketplaceCategorySchema).optional(),\n\n /** Platform version for compatibility filtering */\n platformVersion: z.string().optional(),\n\n /** Max number of items per section */\n limit: z.number().int().min(1).max(50).default(10),\n});\n\n/**\n * App Discovery Response — structured content for the storefront\n */\nexport const AppDiscoveryResponseSchema = z.object({\n /** Featured apps (editorial picks) */\n featured: z.array(RecommendedAppSchema).optional(),\n\n /** Personalized recommendations */\n recommended: z.array(RecommendedAppSchema).optional(),\n\n /** Trending apps */\n trending: z.array(RecommendedAppSchema).optional(),\n\n /** Recently added */\n newArrivals: z.array(RecommendedAppSchema).optional(),\n\n /** Curated collections */\n collections: z.array(z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().optional(),\n coverImageUrl: z.string().url().optional(),\n apps: z.array(RecommendedAppSchema),\n })).optional(),\n});\n\n// ==========================================\n// Subscription & License Management\n// ==========================================\n\n/**\n * Subscription Status\n */\nexport const SubscriptionStatusSchema = z.enum([\n 'active', // Active and paid\n 'trialing', // Free trial period\n 'past-due', // Payment overdue\n 'cancelled', // Cancelled (still active until period ends)\n 'expired', // Expired / ended\n]);\n\n/**\n * App Subscription Schema — customer's license/subscription for an app\n */\nexport const AppSubscriptionSchema = z.object({\n /** Subscription ID */\n id: z.string().describe('Subscription ID'),\n\n /** Listing ID */\n listingId: z.string().describe('App listing ID'),\n\n /** Tenant ID */\n tenantId: z.string().describe('Customer tenant ID'),\n\n /** Subscription status */\n status: SubscriptionStatusSchema,\n\n /** License key */\n licenseKey: z.string().optional(),\n\n /** Plan/tier name (if multiple plans) */\n plan: z.string().optional().describe('Subscription plan name'),\n\n /** Billing cycle */\n billingCycle: z.enum(['monthly', 'annual']).optional(),\n\n /** Price per billing cycle (in cents) */\n priceInCents: z.number().int().min(0).optional(),\n\n /** Current period start */\n currentPeriodStart: z.string().datetime().optional(),\n\n /** Current period end */\n currentPeriodEnd: z.string().datetime().optional(),\n\n /** Trial end date (if trialing) */\n trialEndDate: z.string().datetime().optional(),\n\n /** Whether auto-renew is on */\n autoRenew: z.boolean().default(true),\n\n /** Created timestamp */\n createdAt: z.string().datetime(),\n});\n\n// ==========================================\n// Installed App Management (Customer Side)\n// ==========================================\n\n/**\n * Installed App Summary — what the customer sees in their \"My Apps\" dashboard\n */\nexport const InstalledAppSummarySchema = z.object({\n /** Listing ID */\n listingId: z.string(),\n\n /** Package ID */\n packageId: z.string(),\n\n /** Display name */\n name: z.string(),\n\n /** Icon URL */\n iconUrl: z.string().url().optional(),\n\n /** Installed version */\n installedVersion: z.string(),\n\n /** Latest available version */\n latestVersion: z.string().optional(),\n\n /** Whether an update is available */\n updateAvailable: z.boolean().default(false),\n\n /** Whether the app is currently enabled */\n enabled: z.boolean().default(true),\n\n /** Subscription status (for paid apps) */\n subscriptionStatus: SubscriptionStatusSchema.optional(),\n\n /** Installed timestamp */\n installedAt: z.string().datetime(),\n});\n\n/**\n * List Installed Apps Request\n */\nexport const ListInstalledAppsRequestSchema = z.object({\n /** Tenant ID */\n tenantId: z.string().optional(),\n\n /** Filter by enabled/disabled */\n enabled: z.boolean().optional(),\n\n /** Filter by update availability */\n updateAvailable: z.boolean().optional(),\n\n /** Sort by */\n sortBy: z.enum(['name', 'installed-date', 'updated-date']).default('name'),\n\n /** Pagination */\n page: z.number().int().min(1).default(1),\n pageSize: z.number().int().min(1).max(100).default(20),\n});\n\n/**\n * List Installed Apps Response\n */\nexport const ListInstalledAppsResponseSchema = z.object({\n /** Installed apps */\n items: z.array(InstalledAppSummarySchema),\n\n /** Total count */\n total: z.number().int().min(0),\n\n /** Pagination */\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n});\n\n// ==========================================\n// Export Types\n// ==========================================\n\nexport type ReviewModerationStatus = z.infer;\nexport type UserReview = z.infer;\nexport type SubmitReviewRequest = z.infer;\nexport type ListReviewsRequest = z.infer;\nexport type ListReviewsResponse = z.infer;\nexport type RecommendationReason = z.infer;\nexport type RecommendedApp = z.infer;\nexport type AppDiscoveryRequest = z.infer;\nexport type AppDiscoveryResponse = z.infer;\nexport type SubscriptionStatus = z.infer;\nexport type AppSubscription = z.infer;\nexport type InstalledAppSummary = z.infer;\nexport type ListInstalledAppsRequest = z.infer;\nexport type ListInstalledAppsResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Quality Assurance (QA) Protocol\n * \n * Defines how business logic and metadata are tested.\n * Includes:\n * - Test Scenarios\n * - Test Cases\n * - Expected Outcomes\n */\n\nexport * from './testing.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// --- Building Blocks ---\n\nexport const TestContextSchema = z.record(z.string(), z.unknown()).describe('Initial context or variables for the test');\n\n// Action Types\nexport const TestActionTypeSchema = z.enum([\n 'create_record',\n 'update_record',\n 'delete_record',\n 'read_record',\n 'query_records',\n 'api_call',\n 'run_script',\n 'wait' // Testing async processes\n]).describe('Type of test action to perform');\n\nexport const TestActionSchema = z.object({\n type: TestActionTypeSchema.describe('The action type to execute'),\n target: z.string().describe('Target Object, API Endpoint, or Function Name'),\n payload: z.record(z.string(), z.unknown()).optional().describe('Data to send or use'),\n user: z.string().optional().describe('Run as specific user/role for impersonation testing')\n}).describe('A single test action to execute against the system');\n\n// Assertion Types\nexport const TestAssertionTypeSchema = z.enum([\n 'equals',\n 'not_equals',\n 'contains',\n 'not_contains',\n 'is_null',\n 'not_null',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'error' // Expecting an error\n]).describe('Comparison operator for test assertions');\n\nexport const TestAssertionSchema = z.object({\n field: z.string().describe('Field path in the result to check (e.g. \"body.data.0.status\")'),\n operator: TestAssertionTypeSchema.describe('Comparison operator to use'),\n expectedValue: z.unknown().describe('Expected value to compare against')\n}).describe('A test assertion that validates the result of a test action');\n\n// --- Test Structure ---\n\nexport const TestStepSchema = z.object({\n name: z.string().describe('Step name for identification in test reports'),\n description: z.string().optional().describe('Human-readable description of what this step tests'),\n action: TestActionSchema.describe('The action to execute in this step'),\n assertions: z.array(TestAssertionSchema).optional().describe('Assertions to validate after the action completes'),\n // Capture outputs to variables for subsequent steps\n capture: z.record(z.string(), z.string()).optional().describe('Map result fields to context variables: { \"newId\": \"body.id\" }')\n}).describe('A single step in a test scenario, consisting of an action and optional assertions');\n\nexport const TestScenarioSchema = z.object({\n id: z.string().describe('Unique scenario identifier'),\n name: z.string().describe('Scenario name for test reports'),\n description: z.string().optional().describe('Detailed description of the test scenario'),\n tags: z.array(z.string()).optional().describe('Tags for filtering and categorization (e.g. \"critical\", \"regression\", \"crm\")'),\n \n setup: z.array(TestStepSchema).optional().describe('Steps to run before main test (preconditions)'),\n steps: z.array(TestStepSchema).describe('Main test sequence to execute'),\n teardown: z.array(TestStepSchema).optional().describe('Steps to cleanup after test execution'),\n \n // Environment requirements\n requires: z.object({\n params: z.array(z.string()).optional().describe('Required environment variables or parameters'),\n plugins: z.array(z.string()).optional().describe('Required plugins that must be loaded')\n }).optional().describe('Environment requirements for this scenario')\n}).describe('A complete test scenario with setup, execution steps, and teardown');\n\nexport const TestSuiteSchema = z.object({\n name: z.string().describe('Test suite name'),\n scenarios: z.array(TestScenarioSchema).describe('List of test scenarios in this suite')\n}).describe('A collection of test scenarios grouped into a test suite');\n\nexport type TestSuite = z.infer;\nexport type TestScenario = z.infer;\nexport type TestStep = z.infer;\nexport type TestAction = z.infer;\nexport type TestAssertion = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './identity.zod';\nexport * from './protocol';\nexport * from './role.zod';\nexport * from './organization.zod';\nexport * from './scim.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Identity & User Model Specification\n * \n * Defines the standard user, account, and session data models for ObjectStack.\n * These schemas represent \"who is logged in\" and their associated data.\n * \n * This is separate from authentication configuration (auth.zod.ts) which\n * defines \"how to login\".\n */\n\n/**\n * User Schema\n * Core user identity data model\n */\nexport const UserSchema = z.object({\n /**\n * Unique user identifier\n */\n id: z.string().describe('Unique user identifier'),\n \n /**\n * User's email address (primary identifier)\n */\n email: z.string().email().describe('User email address'),\n \n /**\n * Email verification status\n */\n emailVerified: z.boolean().default(false).describe('Whether email is verified'),\n \n /**\n * User's display name\n */\n name: z.string().optional().describe('User display name'),\n \n /**\n * User's profile image URL\n */\n image: z.string().url().optional().describe('Profile image URL'),\n \n /**\n * Account creation timestamp\n */\n createdAt: z.string().datetime().describe('Account creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type User = z.infer;\n\n/**\n * Account Schema\n * Links external OAuth/OIDC/SAML accounts to a user\n */\nexport const AccountSchema = z.object({\n /**\n * Unique account identifier\n */\n id: z.string().describe('Unique account identifier'),\n \n /**\n * Associated user ID\n */\n userId: z.string().describe('Associated user ID'),\n \n /**\n * Account type/provider\n */\n type: z.enum([\n 'oauth',\n 'oidc',\n 'email',\n 'credentials',\n 'saml',\n 'ldap',\n ]).describe('Account type'),\n \n /**\n * Provider name (e.g., 'google', 'github', 'okta')\n */\n provider: z.string().describe('Provider name'),\n \n /**\n * Provider account ID\n */\n providerAccountId: z.string().describe('Provider account ID'),\n \n /**\n * OAuth refresh token\n */\n refreshToken: z.string().optional().describe('OAuth refresh token'),\n \n /**\n * OAuth access token\n */\n accessToken: z.string().optional().describe('OAuth access token'),\n \n /**\n * Token expiry timestamp\n */\n expiresAt: z.number().optional().describe('Token expiry timestamp (Unix)'),\n \n /**\n * OAuth token type\n */\n tokenType: z.string().optional().describe('OAuth token type'),\n \n /**\n * OAuth scope\n */\n scope: z.string().optional().describe('OAuth scope'),\n \n /**\n * OAuth ID token\n */\n idToken: z.string().optional().describe('OAuth ID token'),\n \n /**\n * Session state\n */\n sessionState: z.string().optional().describe('Session state'),\n \n /**\n * Account creation timestamp\n */\n createdAt: z.string().datetime().describe('Account creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type Account = z.infer;\n\n/**\n * Session Schema\n * User session data model\n */\nexport const SessionSchema = z.object({\n /**\n * Unique session identifier\n */\n id: z.string().describe('Unique session identifier'),\n \n /**\n * Session token\n */\n sessionToken: z.string().describe('Session token'),\n \n /**\n * Associated user ID\n */\n userId: z.string().describe('Associated user ID'),\n \n /**\n * Active organization ID for this session\n * Used for context switching in multi-tenant applications\n */\n activeOrganizationId: z.string().optional().describe('Active organization ID for context switching'),\n \n /**\n * Session expiry timestamp\n */\n expires: z.string().datetime().describe('Session expiry timestamp'),\n \n /**\n * Session creation timestamp\n */\n createdAt: z.string().datetime().describe('Session creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n \n /**\n * IP address of the session\n */\n ipAddress: z.string().optional().describe('IP address'),\n \n /**\n * User agent string\n */\n userAgent: z.string().optional().describe('User agent string'),\n \n /**\n * Device fingerprint\n */\n fingerprint: z.string().optional().describe('Device fingerprint'),\n});\n\nexport type Session = z.infer;\n\n/**\n * Verification Token Schema\n * Email verification and password reset tokens\n */\nexport const VerificationTokenSchema = z.object({\n /**\n * Token identifier (email or phone)\n */\n identifier: z.string().describe('Token identifier (email or phone)'),\n \n /**\n * Verification token\n */\n token: z.string().describe('Verification token'),\n \n /**\n * Token expiry timestamp\n */\n expires: z.string().datetime().describe('Token expiry timestamp'),\n \n /**\n * Token creation timestamp\n */\n createdAt: z.string().datetime().describe('Token creation timestamp'),\n});\n\nexport type VerificationToken = z.infer;\n\n/**\n * API Key Schema\n *\n * Aligns with better-auth's API key plugin capabilities.\n * Provides programmatic access to ObjectStack APIs (CI/CD, service-to-service, CLI).\n *\n * @see https://www.better-auth.com/docs/plugins/api-key\n */\nexport const ApiKeySchema = z.object({\n /**\n * Unique API key identifier\n */\n id: z.string().describe('API key identifier'),\n\n /**\n * Human-readable name for the key\n */\n name: z.string().describe('API key display name'),\n\n /**\n * Key prefix (visible portion for identification, e.g., \"os_pk_ab\")\n */\n start: z.string().optional().describe('Key prefix for identification'),\n\n /**\n * Custom prefix for the key (e.g., \"os_pk_\")\n */\n prefix: z.string().optional().describe('Custom key prefix'),\n\n /**\n * User ID of the key owner\n */\n userId: z.string().describe('Owner user ID'),\n\n /**\n * Organization ID the key is scoped to (optional)\n */\n organizationId: z.string().optional().describe('Scoped organization ID'),\n\n /**\n * Key expiration timestamp (null = never expires)\n */\n expiresAt: z.string().datetime().optional().describe('Expiration timestamp'),\n\n /**\n * Creation timestamp\n */\n createdAt: z.string().datetime().describe('Creation timestamp'),\n\n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n\n /**\n * Last used timestamp\n */\n lastUsedAt: z.string().datetime().optional().describe('Last used timestamp'),\n\n /**\n * Last refetch timestamp (for cached permission checks)\n */\n lastRefetchAt: z.string().datetime().optional().describe('Last refetch timestamp'),\n\n /**\n * Whether this key is enabled\n */\n enabled: z.boolean().default(true).describe('Whether the key is active'),\n\n /**\n * Rate limiting: enabled flag\n */\n rateLimitEnabled: z.boolean().optional().describe('Whether rate limiting is enabled'),\n\n /**\n * Rate limiting: time window in milliseconds\n */\n rateLimitTimeWindow: z.number().int().min(0).optional().describe('Rate limit window (ms)'),\n\n /**\n * Rate limiting: max requests per window\n */\n rateLimitMax: z.number().int().min(0).optional().describe('Max requests per window'),\n\n /**\n * Rate limiting: remaining requests in current window\n */\n remaining: z.number().int().min(0).optional().describe('Remaining requests'),\n\n /**\n * Permissions assigned to this key (granular access control)\n */\n permissions: z.record(z.string(), z.boolean()).optional()\n .describe('Granular permission flags'),\n\n /**\n * Scopes assigned to this key (high-level access categories)\n */\n scopes: z.array(z.string()).optional()\n .describe('High-level access scopes'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\nexport type ApiKey = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Authentication Wire Protocol & Constants\n * \n * Defines the API contract and constants for authentication communication.\n * These constants ensure consistent behavior across all ObjectStack implementations.\n */\n\n/**\n * Authentication Constants\n * Standard headers, prefixes, and identifiers for auth communication\n */\nexport const AUTH_CONSTANTS = {\n /**\n * HTTP header key for authentication tokens\n */\n HEADER_KEY: 'Authorization',\n \n /**\n * Token prefix for Bearer authentication\n */\n TOKEN_PREFIX: 'Bearer ',\n \n /**\n * Cookie prefix for ObjectStack auth cookies\n */\n COOKIE_PREFIX: 'os_',\n \n /**\n * CSRF token header name\n */\n CSRF_HEADER: 'x-os-csrf-token',\n \n /**\n * Default session cookie name\n */\n SESSION_COOKIE: 'os_session_token',\n \n /**\n * Default CSRF cookie name\n */\n CSRF_COOKIE: 'os_csrf_token',\n \n /**\n * Refresh token cookie name\n */\n REFRESH_TOKEN_COOKIE: 'os_refresh_token',\n} as const;\n\n/**\n * Authentication Headers Interface\n * Standard headers used in authenticated requests\n */\nexport interface AuthHeaders {\n /**\n * Authorization header with Bearer token\n * @example \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n */\n Authorization?: string;\n \n /**\n * CSRF token header\n * @example \"x-os-csrf-token: abc123def456...\"\n */\n 'x-os-csrf-token'?: string;\n \n /**\n * Session ID header (alternative to cookie)\n * @example \"x-os-session-id: session_abc123...\"\n */\n 'x-os-session-id'?: string;\n \n /**\n * API key header (for service-to-service auth)\n * @example \"x-os-api-key: sk_live_abc123...\"\n */\n 'x-os-api-key'?: string;\n}\n\n/**\n * Authentication Response Interface\n * Standard response format for authentication operations\n */\nexport interface AuthResponse {\n /**\n * Access token (JWT or opaque token)\n */\n accessToken: string;\n \n /**\n * Refresh token (for token renewal)\n */\n refreshToken?: string;\n \n /**\n * Token type (usually \"Bearer\")\n */\n tokenType: string;\n \n /**\n * Token expiry in seconds\n */\n expiresIn: number;\n \n /**\n * User information\n */\n user: {\n id: string;\n email: string;\n name?: string;\n image?: string;\n };\n \n /**\n * Session ID\n */\n sessionId?: string;\n}\n\n/**\n * Authentication Error Codes\n * Standard error codes for authentication failures\n */\nexport const AUTH_ERROR_CODES = {\n INVALID_CREDENTIALS: 'invalid_credentials',\n INVALID_TOKEN: 'invalid_token',\n TOKEN_EXPIRED: 'token_expired',\n INSUFFICIENT_PERMISSIONS: 'insufficient_permissions',\n ACCOUNT_LOCKED: 'account_locked',\n ACCOUNT_NOT_VERIFIED: 'account_not_verified',\n TOO_MANY_REQUESTS: 'too_many_requests',\n INVALID_CSRF_TOKEN: 'invalid_csrf_token',\n SESSION_EXPIRED: 'session_expired',\n OAUTH_ERROR: 'oauth_error',\n PROVIDER_ERROR: 'provider_error',\n} as const;\n\n/**\n * Authentication Error Interface\n * Standard error response format\n */\nexport interface AuthError {\n /**\n * Error code from AUTH_ERROR_CODES\n */\n code: typeof AUTH_ERROR_CODES[keyof typeof AUTH_ERROR_CODES];\n \n /**\n * Human-readable error message\n */\n message: string;\n \n /**\n * Additional error details\n */\n details?: Record;\n}\n\n/**\n * Token Payload Interface\n * Standard JWT payload structure\n */\nexport interface TokenPayload {\n /**\n * Subject (user ID)\n */\n sub: string;\n \n /**\n * Issued at timestamp\n */\n iat: number;\n \n /**\n * Expiration timestamp\n */\n exp: number;\n \n /**\n * Session ID\n */\n sid?: string;\n \n /**\n * User email\n */\n email?: string;\n \n /**\n * User roles\n */\n roles?: string[];\n \n /**\n * User permissions\n */\n permissions?: string[];\n \n /**\n * Additional custom claims\n */\n [key: string]: any;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Role Schema (aka Business Unit / Org Unit)\n * Defines the organizational hierarchy (Reporting Structure).\n * \n * COMPARISON:\n * - Salesforce: \"Role\" (Hierarchy for visibility rollup)\n * - Microsoft: \"Business Unit\" (Structural container for data)\n * - Kubernetes/AWS: \"Role\" usually refers to Permissions (we use PermissionSet for that)\n * \n * ROLES IN OBJECTSTACK:\n * Used primarily for \"Reporting Structure\" - Managers see subordinates' data.\n * \n * **NAMING CONVENTION:**\n * Role names MUST be lowercase snake_case to prevent security issues.\n * \n * @example Good role names\n * - 'sales_manager'\n * - 'ceo'\n * - 'region_east_vp'\n * - 'engineering_lead'\n * \n * @example Bad role names (will be rejected)\n * - 'SalesManager' (camelCase)\n * - 'CEO' (uppercase)\n * - 'Region East VP' (spaces and uppercase)\n */\nexport const RoleSchema = z.object({\n /** Identity */\n name: SnakeCaseIdentifierSchema.describe('Unique role name (lowercase snake_case)'),\n label: z.string().describe('Display label (e.g. VP of Sales)'),\n \n /** Hierarchy */\n parent: z.string().optional().describe('Parent Role ID (Reports To)'),\n \n /** Description */\n description: z.string().optional(),\n});\n\nexport type Role = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Organization Schema (Multi-Tenant Architecture)\n * \n * Defines the standard organization/workspace model for ObjectStack.\n * Supports B2B SaaS scenarios where users belong to multiple teams/workspaces.\n * \n * This aligns with better-auth's organization plugin capabilities.\n */\n\n/**\n * Organization Schema\n * Represents a team, workspace, or tenant in a multi-tenant application\n */\nexport const OrganizationSchema = z.object({\n /**\n * Unique organization identifier\n */\n id: z.string().describe('Unique organization identifier'),\n \n /**\n * Organization name (display name)\n */\n name: z.string().describe('Organization display name'),\n \n /**\n * Organization slug (URL-friendly identifier)\n * Must be unique across all organizations\n */\n slug: z.string()\n .regex(/^[a-z0-9_-]+$/)\n .describe('Unique URL-friendly slug (lowercase alphanumeric, hyphens, underscores)'),\n \n /**\n * Organization logo URL\n */\n logo: z.string().url().optional().describe('Organization logo URL'),\n \n /**\n * Custom metadata for the organization\n * Can store additional configuration, settings, or custom fields\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n \n /**\n * Organization creation timestamp\n */\n createdAt: z.string().datetime().describe('Organization creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type Organization = z.infer;\n\n/**\n * Organization Member Schema\n * Links users to organizations with specific roles\n */\nexport const MemberSchema = z.object({\n /**\n * Unique member identifier\n */\n id: z.string().describe('Unique member identifier'),\n \n /**\n * Organization ID this membership belongs to\n */\n organizationId: z.string().describe('Organization ID'),\n \n /**\n * User ID of the member\n */\n userId: z.string().describe('User ID'),\n \n /**\n * Member's role within the organization\n * Common roles: 'owner', 'admin', 'member', 'guest'\n * Can be customized per application\n */\n role: z.string().describe('Member role (e.g., owner, admin, member, guest)'),\n \n /**\n * Member creation timestamp\n */\n createdAt: z.string().datetime().describe('Member creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type Member = z.infer;\n\n/**\n * Invitation Status Enum\n */\nexport const InvitationStatus = z.enum(['pending', 'accepted', 'rejected', 'expired']);\n\nexport type InvitationStatus = z.infer;\n\n/**\n * Organization Invitation Schema\n * Represents an invitation to join an organization\n */\nexport const InvitationSchema = z.object({\n /**\n * Unique invitation identifier\n */\n id: z.string().describe('Unique invitation identifier'),\n \n /**\n * Organization ID the invitation is for\n */\n organizationId: z.string().describe('Organization ID'),\n \n /**\n * Email address of the invitee\n */\n email: z.string().email().describe('Invitee email address'),\n \n /**\n * Role the invitee will receive upon accepting\n * Common roles: 'admin', 'member', 'guest'\n */\n role: z.string().describe('Role to assign upon acceptance'),\n \n /**\n * Invitation status\n */\n status: InvitationStatus.default('pending').describe('Invitation status'),\n \n /**\n * Invitation expiration timestamp\n */\n expiresAt: z.string().datetime().describe('Invitation expiry timestamp'),\n \n /**\n * User ID of the person who sent the invitation\n */\n inviterId: z.string().describe('User ID of the inviter'),\n \n /**\n * Invitation creation timestamp\n */\n createdAt: z.string().datetime().describe('Invitation creation timestamp'),\n \n /**\n * Last update timestamp\n */\n updatedAt: z.string().datetime().describe('Last update timestamp'),\n});\n\nexport type Invitation = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # SCIM 2.0 Protocol Implementation\n * \n * System for Cross-domain Identity Management (SCIM) 2.0 specification\n * implementation for ObjectStack.\n * \n * ## Overview\n * \n * SCIM 2.0 is an HTTP-based protocol for managing user and group identities\n * across domains. It provides a standardized REST API for user provisioning,\n * de-provisioning, and synchronization.\n * \n * ## Use Cases\n * \n * 1. **Enterprise SSO Integration**\n * - Integrate with Okta, Azure AD, OneLogin\n * - Automatic user provisioning from corporate directory\n * - Just-in-Time (JIT) user creation on first login\n * \n * 2. **User Lifecycle Management**\n * - Automatically create users when they join organization\n * - Update user attributes when they change roles\n * - Deactivate users when they leave organization\n * \n * 3. **Group/Department Synchronization**\n * - Sync organizational structure from AD/LDAP\n * - Maintain group memberships automatically\n * - Map corporate roles to application permissions\n * \n * 4. **Compliance & Audit**\n * - Maintain accurate user directory\n * - Track all identity changes\n * - Meet SOX/HIPAA requirements for user management\n * \n * ## Specification References\n * \n * - **RFC 7643**: SCIM Core Schema\n * - **RFC 7644**: SCIM Protocol\n * - **RFC 7642**: SCIM Requirements\n * \n * ## Industry Implementations\n * \n * - **Okta**: Leading SCIM provider\n * - **Azure AD**: Microsoft's identity platform\n * - **OneLogin**: Enterprise SSO provider\n * - **Google Workspace**: Google's identity management\n * \n * @see https://datatracker.ietf.org/doc/html/rfc7643\n * @see https://datatracker.ietf.org/doc/html/rfc7644\n */\n\n/**\n * SCIM Schema URIs\n * Standard schema identifiers defined in RFC 7643\n */\nexport const SCIM_SCHEMAS = {\n USER: 'urn:ietf:params:scim:schemas:core:2.0:User',\n GROUP: 'urn:ietf:params:scim:schemas:core:2.0:Group',\n ENTERPRISE_USER: 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User',\n RESOURCE_TYPE: 'urn:ietf:params:scim:schemas:core:2.0:ResourceType',\n SERVICE_PROVIDER_CONFIG: 'urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig',\n SCHEMA: 'urn:ietf:params:scim:schemas:core:2.0:Schema',\n LIST_RESPONSE: 'urn:ietf:params:scim:api:messages:2.0:ListResponse',\n PATCH_OP: 'urn:ietf:params:scim:api:messages:2.0:PatchOp',\n BULK_REQUEST: 'urn:ietf:params:scim:api:messages:2.0:BulkRequest',\n BULK_RESPONSE: 'urn:ietf:params:scim:api:messages:2.0:BulkResponse',\n ERROR: 'urn:ietf:params:scim:api:messages:2.0:Error',\n} as const;\n\n/**\n * SCIM Meta Schema\n * Common metadata for all SCIM resources\n */\nexport const SCIMMetaSchema = z.object({\n /**\n * Resource type name\n * @example \"User\", \"Group\"\n */\n resourceType: z.string()\n .optional()\n .describe('Resource type'),\n\n /**\n * Resource creation timestamp (ISO 8601)\n */\n created: z.string()\n .datetime()\n .optional()\n .describe('Creation timestamp'),\n\n /**\n * Last modification timestamp (ISO 8601)\n */\n lastModified: z.string()\n .datetime()\n .optional()\n .describe('Last modification timestamp'),\n\n /**\n * Resource location URI\n * Absolute URL to the resource\n */\n location: z.string()\n .url()\n .optional()\n .describe('Resource location URI'),\n\n /**\n * Entity tag for optimistic concurrency control\n * Used with If-Match header for conditional updates\n */\n version: z.string()\n .optional()\n .describe('Entity tag (ETag) for concurrency control'),\n});\n\nexport type SCIMMeta = z.infer;\n\n/**\n * SCIM Name Schema\n * Structured name components\n */\nexport const SCIMNameSchema = z.object({\n /**\n * Full name formatted for display\n * @example \"Ms. Barbara Jane Jensen III\"\n */\n formatted: z.string()\n .optional()\n .describe('Formatted full name'),\n\n /**\n * Family name (surname)\n * @example \"Jensen\"\n */\n familyName: z.string()\n .optional()\n .describe('Family name (last name)'),\n\n /**\n * Given name (first name)\n * @example \"Barbara\"\n */\n givenName: z.string()\n .optional()\n .describe('Given name (first name)'),\n\n /**\n * Middle name\n * @example \"Jane\"\n */\n middleName: z.string()\n .optional()\n .describe('Middle name'),\n\n /**\n * Honorific prefix\n * @example \"Ms.\", \"Dr.\", \"Prof.\"\n */\n honorificPrefix: z.string()\n .optional()\n .describe('Honorific prefix (Mr., Ms., Dr.)'),\n\n /**\n * Honorific suffix\n * @example \"III\", \"Jr.\", \"Sr.\"\n */\n honorificSuffix: z.string()\n .optional()\n .describe('Honorific suffix (Jr., Sr.)'),\n});\n\nexport type SCIMName = z.infer;\n\n/**\n * SCIM Email Schema\n * Multi-valued email address\n */\nexport const SCIMEmailSchema = z.object({\n /**\n * Email address value\n */\n value: z.string()\n .email()\n .describe('Email address'),\n\n /**\n * Email type\n * @example \"work\", \"home\", \"other\"\n */\n type: z.enum(['work', 'home', 'other'])\n .optional()\n .describe('Email type'),\n\n /**\n * Display label for the email\n */\n display: z.string()\n .optional()\n .describe('Display label'),\n\n /**\n * Whether this is the primary email\n */\n primary: z.boolean()\n .optional()\n .default(false)\n .describe('Primary email indicator'),\n});\n\nexport type SCIMEmail = z.infer;\n\n/**\n * SCIM Phone Number Schema\n * Multi-valued phone number\n */\nexport const SCIMPhoneNumberSchema = z.object({\n /**\n * Phone number value\n * Format is not enforced to support international numbers\n */\n value: z.string()\n .describe('Phone number'),\n\n /**\n * Phone type\n */\n type: z.enum(['work', 'home', 'mobile', 'fax', 'pager', 'other'])\n .optional()\n .describe('Phone number type'),\n\n /**\n * Display label for the phone number\n */\n display: z.string()\n .optional()\n .describe('Display label'),\n\n /**\n * Whether this is the primary phone\n */\n primary: z.boolean()\n .optional()\n .default(false)\n .describe('Primary phone indicator'),\n});\n\nexport type SCIMPhoneNumber = z.infer;\n\n/**\n * SCIM Address Schema\n * Multi-valued physical mailing address\n */\nexport const SCIMAddressSchema = z.object({\n /**\n * Full mailing address formatted for display\n */\n formatted: z.string()\n .optional()\n .describe('Formatted address'),\n\n /**\n * Full street address\n */\n streetAddress: z.string()\n .optional()\n .describe('Street address'),\n\n /**\n * City or locality\n */\n locality: z.string()\n .optional()\n .describe('City/Locality'),\n\n /**\n * State or region\n */\n region: z.string()\n .optional()\n .describe('State/Region'),\n\n /**\n * Zip code or postal code\n */\n postalCode: z.string()\n .optional()\n .describe('Postal code'),\n\n /**\n * Country\n */\n country: z.string()\n .optional()\n .describe('Country'),\n\n /**\n * Address type\n */\n type: z.enum(['work', 'home', 'other'])\n .optional()\n .describe('Address type'),\n\n /**\n * Whether this is the primary address\n */\n primary: z.boolean()\n .optional()\n .default(false)\n .describe('Primary address indicator'),\n});\n\nexport type SCIMAddress = z.infer;\n\n/**\n * SCIM Group Reference\n * Reference to a group the user belongs to\n */\nexport const SCIMGroupReferenceSchema = z.object({\n /**\n * Group identifier\n */\n value: z.string()\n .describe('Group ID'),\n\n /**\n * Direct reference to the group resource\n */\n $ref: z.string()\n .url()\n .optional()\n .describe('URI reference to the group'),\n\n /**\n * Human-readable group name\n */\n display: z.string()\n .optional()\n .describe('Group display name'),\n\n /**\n * Type of group\n */\n type: z.enum(['direct', 'indirect'])\n .optional()\n .describe('Membership type'),\n});\n\nexport type SCIMGroupReference = z.infer;\n\n/**\n * SCIM Enterprise User Extension\n * Enterprise-specific user attributes\n */\nexport const SCIMEnterpriseUserSchema = z.object({\n /**\n * Employee number\n */\n employeeNumber: z.string()\n .optional()\n .describe('Employee number'),\n\n /**\n * Cost center\n */\n costCenter: z.string()\n .optional()\n .describe('Cost center'),\n\n /**\n * Organization unit\n */\n organization: z.string()\n .optional()\n .describe('Organization'),\n\n /**\n * Division\n */\n division: z.string()\n .optional()\n .describe('Division'),\n\n /**\n * Department\n */\n department: z.string()\n .optional()\n .describe('Department'),\n\n /**\n * Manager reference\n */\n manager: z.object({\n value: z.string().describe('Manager ID'),\n $ref: z.string().url().optional().describe('Manager URI'),\n displayName: z.string().optional().describe('Manager name'),\n })\n .optional()\n .describe('Manager reference'),\n});\n\nexport type SCIMEnterpriseUser = z.infer;\n\n/**\n * SCIM User Schema (Core)\n * Complete SCIM 2.0 User resource\n */\nexport const SCIMUserSchema = z.object({\n /**\n * SCIM schema URIs\n * Must include at minimum the core User schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.USER),\n 'Must include core User schema URI'\n )\n .default([SCIM_SCHEMAS.USER])\n .describe('SCIM schema URIs (must include User schema)'),\n\n /**\n * Unique identifier\n */\n id: z.string()\n .optional()\n .describe('Unique resource identifier'),\n\n /**\n * External identifier\n * Identifier from the provisioning client\n */\n externalId: z.string()\n .optional()\n .describe('External identifier from client system'),\n\n /**\n * Unique username\n * REQUIRED for user creation\n */\n userName: z.string()\n .describe('Unique username (REQUIRED)'),\n\n /**\n * Structured name\n */\n name: SCIMNameSchema\n .optional()\n .describe('Structured name components'),\n\n /**\n * Display name\n */\n displayName: z.string()\n .optional()\n .describe('Display name for UI'),\n\n /**\n * Nickname or casual name\n */\n nickName: z.string()\n .optional()\n .describe('Nickname'),\n\n /**\n * Profile URL\n */\n profileUrl: z.string()\n .url()\n .optional()\n .describe('Profile page URL'),\n\n /**\n * Job title\n */\n title: z.string()\n .optional()\n .describe('Job title'),\n\n /**\n * User type (employee, contractor, etc.)\n */\n userType: z.string()\n .optional()\n .describe('User type (employee, contractor)'),\n\n /**\n * Preferred language (ISO 639-1)\n */\n preferredLanguage: z.string()\n .optional()\n .describe('Preferred language (ISO 639-1)'),\n\n /**\n * Locale (e.g., en-US)\n */\n locale: z.string()\n .optional()\n .describe('Locale (e.g., en-US)'),\n\n /**\n * Timezone (e.g., America/Los_Angeles)\n */\n timezone: z.string()\n .optional()\n .describe('Timezone'),\n\n /**\n * Account active status\n */\n active: z.boolean()\n .optional()\n .default(true)\n .describe('Account active status'),\n\n /**\n * Password (write-only, never returned)\n */\n password: z.string()\n .optional()\n .describe('Password (write-only)'),\n\n /**\n * Email addresses (multi-valued)\n */\n emails: z.array(SCIMEmailSchema)\n .optional()\n .describe('Email addresses'),\n\n /**\n * Phone numbers (multi-valued)\n */\n phoneNumbers: z.array(SCIMPhoneNumberSchema)\n .optional()\n .describe('Phone numbers'),\n\n /**\n * Instant messaging addresses\n */\n ims: z.array(z.object({\n value: z.string(),\n type: z.string().optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('IM addresses'),\n\n /**\n * Photos (profile pictures)\n */\n photos: z.array(z.object({\n value: z.string().url(),\n type: z.enum(['photo', 'thumbnail']).optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('Photo URLs'),\n\n /**\n * Physical addresses\n */\n addresses: z.array(SCIMAddressSchema)\n .optional()\n .describe('Physical addresses'),\n\n /**\n * Group memberships\n */\n groups: z.array(SCIMGroupReferenceSchema)\n .optional()\n .describe('Group memberships'),\n\n /**\n * User entitlements\n */\n entitlements: z.array(z.object({\n value: z.string(),\n type: z.string().optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('Entitlements'),\n\n /**\n * User roles\n */\n roles: z.array(z.object({\n value: z.string(),\n type: z.string().optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('Roles'),\n\n /**\n * X509 certificates\n */\n x509Certificates: z.array(z.object({\n value: z.string(),\n type: z.string().optional(),\n primary: z.boolean().optional(),\n }))\n .optional()\n .describe('X509 certificates'),\n\n /**\n * Resource metadata\n */\n meta: SCIMMetaSchema\n .optional()\n .describe('Resource metadata'),\n\n /**\n * Enterprise user extension\n * Only present when enterprise extension is used\n */\n [SCIM_SCHEMAS.ENTERPRISE_USER]: SCIMEnterpriseUserSchema\n .optional()\n .describe('Enterprise user attributes'),\n}).superRefine((data, ctx) => {\n // Validate that enterprise extension schema URI is present when extension data is provided\n const hasEnterpriseExtension = data[SCIM_SCHEMAS.ENTERPRISE_USER] != null;\n if (!hasEnterpriseExtension) {\n return;\n }\n\n const schemas = data.schemas || [];\n if (!schemas.includes(SCIM_SCHEMAS.ENTERPRISE_USER)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['schemas'],\n message: `schemas must include \"${SCIM_SCHEMAS.ENTERPRISE_USER}\" when enterprise user extension attributes are present`,\n });\n }\n});\n\nexport type SCIMUser = z.infer;\n\n/**\n * SCIM Member Reference\n * Reference to a member in a group\n */\nexport const SCIMMemberReferenceSchema = z.object({\n /**\n * Member identifier\n */\n value: z.string()\n .describe('Member ID'),\n\n /**\n * Direct reference to the member resource\n */\n $ref: z.string()\n .url()\n .optional()\n .describe('URI reference to the member'),\n\n /**\n * Member type (User or Group for nested groups)\n */\n type: z.enum(['User', 'Group'])\n .optional()\n .describe('Member type'),\n\n /**\n * Human-readable member name\n */\n display: z.string()\n .optional()\n .describe('Member display name'),\n});\n\nexport type SCIMMemberReference = z.infer;\n\n/**\n * SCIM Group Schema\n * Complete SCIM 2.0 Group resource\n */\nexport const SCIMGroupSchema = z.object({\n /**\n * SCIM schema URIs\n * Must include at minimum the core Group schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.GROUP),\n 'Must include core Group schema URI'\n )\n .default([SCIM_SCHEMAS.GROUP])\n .describe('SCIM schema URIs (must include Group schema)'),\n\n /**\n * Unique identifier\n */\n id: z.string()\n .optional()\n .describe('Unique resource identifier'),\n\n /**\n * External identifier\n */\n externalId: z.string()\n .optional()\n .describe('External identifier from client system'),\n\n /**\n * Group display name\n * REQUIRED for group creation\n */\n displayName: z.string()\n .describe('Group display name (REQUIRED)'),\n\n /**\n * Group members\n */\n members: z.array(SCIMMemberReferenceSchema)\n .optional()\n .describe('Group members'),\n\n /**\n * Resource metadata\n */\n meta: SCIMMetaSchema\n .optional()\n .describe('Resource metadata'),\n});\n\nexport type SCIMGroup = z.infer;\n\n/**\n * SCIM Resource Union Type\n * Known SCIM resource types for type-safe list responses\n */\nexport type SCIMResource = SCIMUser | SCIMGroup;\n\n/**\n * SCIM List Response\n * Paginated list of resources\n * \n * Generic type T allows for type-safe responses when the resource type is known.\n * For mixed resource types, use SCIMResource union.\n */\nexport const SCIMListResponseSchema = z.object({\n /**\n * SCIM schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.LIST_RESPONSE),\n { message: `schemas must include ${SCIM_SCHEMAS.LIST_RESPONSE}` }\n )\n .default([SCIM_SCHEMAS.LIST_RESPONSE])\n .describe('SCIM schema URIs'),\n\n /**\n * Total number of results matching the query\n */\n totalResults: z.number()\n .int()\n .min(0)\n .describe('Total results count'),\n\n /**\n * Resources returned in this response\n * Use SCIMListResponseOf for type-safe responses\n */\n Resources: z.array(z.union([SCIMUserSchema, SCIMGroupSchema, z.record(z.string(), z.unknown())]))\n .describe('Resources array (Users, Groups, or custom resources)'),\n\n /**\n * 1-based index of the first result\n */\n startIndex: z.number()\n .int()\n .min(1)\n .optional()\n .describe('Start index (1-based)'),\n\n /**\n * Number of resources per page\n */\n itemsPerPage: z.number()\n .int()\n .min(0)\n .optional()\n .describe('Items per page'),\n});\n\nexport type SCIMListResponse = z.infer;\n\n/**\n * SCIM Error Response\n * Error response format\n */\nexport const SCIMErrorSchema = z.object({\n /**\n * SCIM schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.ERROR),\n { message: `schemas must include ${SCIM_SCHEMAS.ERROR}` }\n )\n .default([SCIM_SCHEMAS.ERROR])\n .describe('SCIM schema URIs'),\n\n /**\n * HTTP status code\n */\n status: z.number()\n .int()\n .min(400)\n .max(599)\n .describe('HTTP status code'),\n\n /**\n * SCIM error type\n */\n scimType: z.enum([\n 'invalidFilter',\n 'tooMany',\n 'uniqueness',\n 'mutability',\n 'invalidSyntax',\n 'invalidPath',\n 'noTarget',\n 'invalidValue',\n 'invalidVers',\n 'sensitive',\n ])\n .optional()\n .describe('SCIM error type'),\n\n /**\n * Human-readable error description\n */\n detail: z.string()\n .optional()\n .describe('Error detail message'),\n});\n\nexport type SCIMError = z.infer;\n\n/**\n * SCIM Patch Operation\n * For PATCH requests\n */\nexport const SCIMPatchOperationSchema = z.object({\n /**\n * Operation type\n */\n op: z.enum(['add', 'remove', 'replace'])\n .describe('Operation type'),\n\n /**\n * Attribute path to modify\n */\n path: z.string()\n .optional()\n .describe('Attribute path (optional for add)'),\n\n /**\n * Value to set\n */\n value: z.unknown()\n .optional()\n .describe('Value to set'),\n});\n\nexport type SCIMPatchOperation = z.infer;\n\n/**\n * SCIM Patch Request\n */\nexport const SCIMPatchRequestSchema = z.object({\n /**\n * SCIM schema URI\n */\n schemas: z.array(z.string())\n .min(1)\n .refine(\n (schemas) => schemas.includes(SCIM_SCHEMAS.PATCH_OP),\n { message: 'SCIM PATCH requests must include the PatchOp schema URI' }\n )\n .default([SCIM_SCHEMAS.PATCH_OP])\n .describe('SCIM schema URIs'),\n\n /**\n * Array of patch operations\n */\n Operations: z.array(SCIMPatchOperationSchema)\n .min(1)\n .describe('Patch operations'),\n});\n\nexport type SCIMPatchRequest = z.infer;\n\n/**\n * Helper factory for creating SCIM resources\n */\nexport const SCIM = {\n /**\n * Create a basic SCIM user\n */\n user: (userName: string, email: string, givenName?: string, familyName?: string): SCIMUser => ({\n schemas: [SCIM_SCHEMAS.USER],\n userName,\n emails: [{ value: email, type: 'work', primary: true }],\n name: {\n givenName,\n familyName,\n },\n active: true,\n }),\n\n /**\n * Create a SCIM group\n */\n group: (displayName: string, members?: SCIMMemberReference[]): SCIMGroup => ({\n schemas: [SCIM_SCHEMAS.GROUP],\n displayName,\n members: members || [],\n }),\n\n /**\n * Create a list response\n */\n listResponse: (resources: T[], totalResults?: number): SCIMListResponse => ({\n schemas: [SCIM_SCHEMAS.LIST_RESPONSE],\n totalResults: totalResults ?? resources.length,\n Resources: resources as Array>,\n startIndex: 1,\n itemsPerPage: resources.length,\n }),\n\n /**\n * Create an error response\n */\n error: (\n status: number,\n detail: string,\n scimType?: 'invalidFilter' | 'tooMany' | 'uniqueness' | 'mutability' | \n 'invalidSyntax' | 'invalidPath' | 'noTarget' | 'invalidValue' | \n 'invalidVers' | 'sensitive'\n ): SCIMError => ({\n schemas: [SCIM_SCHEMAS.ERROR],\n status,\n detail,\n scimType,\n }),\n} as const;\n\n// ─── SCIM 2.0 Bulk Operations (RFC 7644 §3.7) ──────────────────────────────\n\n/**\n * SCIM Bulk Operation Schema\n * A single operation within a bulk request\n */\nexport const SCIMBulkOperationSchema = z.object({\n /** HTTP method for this operation */\n method: z.enum(['POST', 'PUT', 'PATCH', 'DELETE'])\n .describe('HTTP method for the bulk operation'),\n\n /** Resource path (e.g. /Users, /Groups/{id}) */\n path: z.string()\n .describe('Resource endpoint path (e.g. /Users, /Groups/{id})'),\n\n /** Client-assigned identifier for cross-referencing operations */\n bulkId: z.string()\n .optional()\n .describe('Client-assigned ID for cross-referencing between operations'),\n\n /** Request body for POST/PUT/PATCH operations */\n data: z.record(z.string(), z.unknown())\n .optional()\n .describe('Request body for POST/PUT/PATCH operations'),\n\n /** ETag value for optimistic concurrency control */\n version: z.string()\n .optional()\n .describe('ETag for optimistic concurrency control'),\n});\n\nexport type SCIMBulkOperation = z.infer;\n\n/**\n * SCIM Bulk Request Schema\n * Batch multiple SCIM operations into a single HTTP request\n */\nexport const SCIMBulkRequestSchema = z.object({\n /** SCIM schema URI for bulk request */\n schemas: z.array(z.literal(SCIM_SCHEMAS.BULK_REQUEST))\n .default([SCIM_SCHEMAS.BULK_REQUEST])\n .describe('SCIM schema URIs (BulkRequest)'),\n\n /** Array of operations to execute */\n operations: z.array(SCIMBulkOperationSchema)\n .min(1)\n .describe('Bulk operations to execute (minimum 1)'),\n\n /** Stop processing after N errors */\n failOnErrors: z.number()\n .int()\n .optional()\n .describe('Stop processing after this many errors'),\n});\n\nexport type SCIMBulkRequest = z.infer;\n\n/**\n * SCIM Bulk Response Operation Schema\n * Result of a single operation within a bulk response\n */\nexport const SCIMBulkResponseOperationSchema = z.object({\n /** HTTP method that was executed */\n method: z.enum(['POST', 'PUT', 'PATCH', 'DELETE'])\n .describe('HTTP method that was executed'),\n\n /** Client-assigned bulk operation ID */\n bulkId: z.string()\n .optional()\n .describe('Client-assigned bulk operation ID'),\n\n /** URL of the created/modified resource */\n location: z.string()\n .optional()\n .describe('URL of the created or modified resource'),\n\n /** HTTP status code as string */\n status: z.string()\n .describe('HTTP status code as string (e.g. \"201\", \"400\")'),\n\n /** Response body, typically present for errors */\n response: z.unknown()\n .optional()\n .describe('Response body (typically present for errors)'),\n});\n\nexport type SCIMBulkResponseOperation = z.infer;\n\n/**\n * SCIM Bulk Response Schema\n * Response to a bulk request containing results for each operation\n */\nexport const SCIMBulkResponseSchema = z.object({\n /** SCIM schema URI for bulk response */\n schemas: z.array(z.literal(SCIM_SCHEMAS.BULK_RESPONSE))\n .default([SCIM_SCHEMAS.BULK_RESPONSE])\n .describe('SCIM schema URIs (BulkResponse)'),\n\n /** Array of operation results */\n operations: z.array(SCIMBulkResponseOperationSchema)\n .describe('Results for each bulk operation'),\n});\n\nexport type SCIMBulkResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * AI Protocol Exports\n * \n * AI/ML Capabilities\n * - Agent Configuration (Agent → Skill → Tool architecture)\n * - Tool Metadata (first-class AI tool definitions)\n * - Skill Metadata (ability groups / capability bundles)\n * - DevOps Agent (Self-iterating Development)\n * - Model Registry & Selection\n * - Model Context Protocol (MCP)\n * - RAG Pipeline\n * - Natural Language Query (NLQ)\n * - Workflow Automation\n * - Predictive Analytics\n * - Conversation Memory & Token Management\n * - Cost Tracking & Budget Management\n * - Plugin Development (AI-assisted)\n * - Runtime Operations (AIOps)\n */\n\nexport * from './agent.zod';\nexport * from './tool.zod';\nexport * from './skill.zod';\nexport * from './agent-action.zod';\nexport * from './devops-agent.zod';\nexport * from './plugin-development.zod';\nexport * from './runtime-ops.zod';\nexport * from './model-registry.zod';\nexport * from './mcp.zod';\nexport * from './rag-pipeline.zod';\nexport * from './nlq.zod';\nexport * from './orchestration.zod';\nexport * from './predictive.zod';\nexport * from './conversation.zod';\nexport * from './cost.zod';\nexport * from './feedback-loop.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { StateMachineSchema } from '../automation/state-machine.zod';\n\n/**\n * AI Model Configuration\n */\nexport const AIModelConfigSchema = z.object({\n provider: z.enum(['openai', 'azure_openai', 'anthropic', 'local']).default('openai'),\n model: z.string().describe('Model name (e.g. gpt-4, claude-3-opus)'),\n temperature: z.number().min(0).max(2).default(0.7),\n maxTokens: z.number().optional(),\n topP: z.number().optional(),\n});\n\n/**\n * AI Tool Definition\n * References to Actions, Flows, or Objects available to the Agent.\n */\nexport const AIToolSchema = z.object({\n type: z.enum(['action', 'flow', 'query', 'vector_search']),\n name: z.string().describe('Reference name (Action Name, Flow Name)'),\n description: z.string().optional().describe('Override description for the LLM'),\n});\n\n/**\n * AI Knowledge Base\n * RAG configuration.\n */\nexport const AIKnowledgeSchema = z.object({\n topics: z.array(z.string()).describe('Topics/Tags to recruit knowledge from'),\n indexes: z.array(z.string()).describe('Vector Store Indexes'),\n});\n\n/**\n * Structured Output Format\n * Defines the expected output format for agent responses\n */\nexport const StructuredOutputFormatSchema = z.enum([\n 'json_object',\n 'json_schema',\n 'regex',\n 'grammar',\n 'xml',\n]).describe('Output format for structured agent responses');\n\n/**\n * Transform Pipeline Step\n * Post-processing steps applied to structured output\n */\nexport const TransformPipelineStepSchema = z.enum([\n 'trim',\n 'parse_json',\n 'validate',\n 'coerce_types',\n]).describe('Post-processing step for structured output');\n\n/**\n * Structured Output Configuration\n * Controls how the agent formats and validates its output\n */\nexport const StructuredOutputConfigSchema = z.object({\n /** Output format type */\n format: StructuredOutputFormatSchema.describe('Expected output format'),\n\n /** JSON Schema definition for output validation */\n schema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema definition for output'),\n\n /** Whether to enforce exact schema compliance */\n strict: z.boolean().default(false).describe('Enforce exact schema compliance'),\n\n /** Retry on validation failure */\n retryOnValidationFailure: z.boolean().default(true).describe('Retry generation when output fails validation'),\n\n /** Maximum retry attempts */\n maxRetries: z.number().int().min(0).default(3).describe('Maximum retries on validation failure'),\n\n /** Fallback format if primary format fails */\n fallbackFormat: StructuredOutputFormatSchema.optional().describe('Fallback format if primary format fails'),\n\n /** Post-processing pipeline steps */\n transformPipeline: z.array(TransformPipelineStepSchema).optional().describe('Post-processing steps applied to output'),\n}).describe('Structured output configuration for agent responses');\n\nexport type StructuredOutputFormat = z.infer;\nexport type TransformPipelineStep = z.infer;\nexport type StructuredOutputConfig = z.infer;\n\n/**\n * AI Agent Schema\n * Definition of an autonomous agent specialized for a domain.\n *\n * The Agent → Skill → Tool three-tier architecture aligns with\n * Salesforce Agentforce, Microsoft Copilot Studio, and ServiceNow\n * Now Assist metadata patterns.\n *\n * - **skills**: Primary capability model — references skill names.\n * - **tools**: Fallback / direct tool references (legacy inline format).\n *\n * @example Agent-Skill Architecture\n * ```ts\n * defineAgent({\n * name: 'support_tier_1',\n * label: 'First Line Support',\n * role: 'Help Desk Assistant',\n * instructions: 'You are a helpful assistant. Always verify user identity first.',\n * skills: ['case_management', 'knowledge_search'],\n * knowledge: { topics: ['faq', 'policies'], indexes: ['support_docs'] },\n * });\n * ```\n *\n * @example Legacy Tool References (backward-compatible)\n * ```ts\n * defineAgent({\n * name: 'support_tier_1',\n * label: 'First Line Support',\n * role: 'Help Desk Assistant',\n * instructions: 'You are a helpful assistant.',\n * tools: [\n * { type: 'flow', name: 'reset_password', description: 'Trigger password reset email' },\n * { type: 'query', name: 'get_order_status', description: 'Check order shipping status' },\n * ],\n * });\n * ```\n */\nexport const AgentSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Agent unique identifier'),\n label: z.string().describe('Agent display name'),\n avatar: z.string().optional(),\n role: z.string().describe('The persona/role (e.g. \"Senior Support Engineer\")'),\n\n /** Cognition */\n instructions: z.string().describe('System Prompt / Prime Directives'),\n model: AIModelConfigSchema.optional(),\n lifecycle: StateMachineSchema.optional().describe('State machine defining the agent conversation follow and constraints'),\n\n /** Capabilities — Skill-based (primary) */\n skills: z.array(z.string().regex(/^[a-z_][a-z0-9_]*$/)).optional().describe('Skill names to attach (Agent→Skill→Tool architecture)'),\n\n /** Capabilities — Direct tool references (fallback / legacy) */\n tools: z.array(AIToolSchema).optional().describe('Direct tool references (legacy fallback)'),\n\n /** Knowledge */\n knowledge: AIKnowledgeSchema.optional().describe('RAG access'),\n\n /** Interface */\n active: z.boolean().default(true),\n access: z.array(z.string()).optional().describe('Who can chat with this agent'),\n\n /** Permission profiles/roles required to use this agent */\n permissions: z.array(z.string()).optional().describe('Required permissions or roles'),\n\n /** Multi-tenancy & Visibility */\n tenantId: z.string().optional().describe('Tenant/Organization ID'),\n visibility: z.enum(['global', 'organization', 'private']).default('organization'),\n\n /** Autonomous Reasoning */\n planning: z.object({\n /** Planning strategy for autonomous reasoning loops */\n strategy: z.enum(['react', 'plan_and_execute', 'reflexion', 'tree_of_thought']).default('react').describe('Autonomous reasoning strategy'),\n\n /** Maximum reasoning iterations before stopping */\n maxIterations: z.number().int().min(1).max(100).default(10).describe('Maximum planning loop iterations'),\n\n /** Whether the agent can revise its own plan mid-execution */\n allowReplan: z.boolean().default(true).describe('Allow dynamic re-planning based on intermediate results'),\n }).optional().describe('Autonomous reasoning and planning configuration'),\n\n /** Memory Management */\n memory: z.object({\n /** Short-term (working) memory configuration */\n shortTerm: z.object({\n /** Maximum number of recent messages to retain */\n maxMessages: z.number().int().min(1).default(50).describe('Max recent messages in working memory'),\n\n /** Maximum token budget for short-term context */\n maxTokens: z.number().int().min(100).optional().describe('Max tokens for short-term context window'),\n }).optional().describe('Short-term / working memory'),\n\n /** Long-term (persistent) memory configuration */\n longTerm: z.object({\n /** Whether long-term memory is enabled */\n enabled: z.boolean().default(false).describe('Enable long-term memory persistence'),\n\n /** Storage backend for long-term memory */\n store: z.enum(['vector', 'database', 'redis']).default('vector').describe('Long-term memory storage backend'),\n\n /** Maximum number of persisted memory entries */\n maxEntries: z.number().int().min(1).optional().describe('Max entries in long-term memory'),\n }).optional().describe('Long-term / persistent memory'),\n\n /** Reflection interval — how often the agent reflects on past actions */\n reflectionInterval: z.number().int().min(1).optional().describe('Reflect every N interactions to improve behavior'),\n }).optional().describe('Agent memory management'),\n\n /** Guardrails */\n guardrails: z.object({\n /** Maximum tokens the agent may consume per invocation */\n maxTokensPerInvocation: z.number().int().min(1).optional().describe('Token budget per single invocation'),\n\n /** Maximum wall-clock time per invocation in seconds */\n maxExecutionTimeSec: z.number().int().min(1).optional().describe('Max execution time in seconds'),\n\n /** Topics or actions the agent must avoid */\n blockedTopics: z.array(z.string()).optional().describe('Forbidden topics or action names'),\n }).optional().describe('Safety guardrails for the agent'),\n\n /** Structured Output */\n structuredOutput: StructuredOutputConfigSchema.optional().describe('Structured output format and validation configuration'),\n});\n\n/**\n * Type-safe factory for creating AI agent definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example Agent-Skill Architecture (recommended)\n * ```ts\n * const supportAgent = defineAgent({\n * name: 'support_agent',\n * label: 'Support Agent',\n * role: 'Senior Support Engineer',\n * instructions: 'You help customers resolve technical issues.',\n * skills: ['case_management', 'knowledge_search'],\n * });\n * ```\n *\n * @example Legacy Tool References (backward-compatible)\n * ```ts\n * const supportAgent = defineAgent({\n * name: 'support_agent',\n * label: 'Support Agent',\n * role: 'Senior Support Engineer',\n * instructions: 'You help customers resolve technical issues.',\n * tools: [{ type: 'action', name: 'create_ticket' }],\n * });\n * ```\n */\nexport function defineAgent(config: z.input): Agent {\n return AgentSchema.parse(config);\n}\n\nexport type Agent = z.infer;\nexport type AITool = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Tool Category\n// ==========================================\n\n/**\n * Tool Category\n * Classifies the tool by its operational domain.\n */\nexport const ToolCategorySchema = z.enum([\n 'data', // CRUD / query operations\n 'action', // Side-effect actions (send email, create record)\n 'flow', // Trigger a visual flow\n 'integration', // External API / webhook calls\n 'vector_search', // RAG / vector search\n 'analytics', // Aggregation & reporting\n 'utility', // Formatters, parsers, helpers\n]).describe('Tool operational category');\n\nexport type ToolCategory = z.infer;\n\n// ==========================================\n// Tool Schema\n// ==========================================\n\n/**\n * Tool Schema\n *\n * First-class metadata definition for an AI-callable tool.\n * Tools are the atomic units of AI capability — each tool\n * represents a single, well-defined operation with strict\n * parameter validation via JSON Schema.\n *\n * Aligned with Salesforce Agentforce, Microsoft Copilot Studio,\n * and ServiceNow Now Assist metadata patterns.\n *\n * @example\n * ```ts\n * const tool = defineTool({\n * name: 'create_case',\n * label: 'Create Support Case',\n * description: 'Creates a new support case record',\n * category: 'action',\n * parameters: {\n * type: 'object',\n * properties: {\n * subject: { type: 'string', description: 'Case subject' },\n * priority: { type: 'string', enum: ['low', 'medium', 'high'] },\n * },\n * required: ['subject'],\n * },\n * objectName: 'support_case',\n * requiresConfirmation: true,\n * });\n * ```\n */\nexport const ToolSchema = z.object({\n /** Machine name (snake_case, globally unique) */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Tool unique identifier (snake_case)'),\n\n /** Human-readable display name */\n label: z.string().describe('Tool display name'),\n\n /** Detailed description for LLM consumption (the model reads this to decide when to call the tool) */\n description: z.string().describe('Tool description for LLM function calling'),\n\n /** Operational category */\n category: ToolCategorySchema.optional().describe('Tool category for grouping and filtering'),\n\n /**\n * JSON Schema describing the tool input parameters.\n * Must be a valid JSON Schema object. The AI model generates\n * arguments conforming to this schema.\n */\n parameters: z.record(z.string(), z.unknown()).describe('JSON Schema for tool parameters'),\n\n /**\n * Optional JSON Schema for the tool output.\n * Used for structured output validation and downstream tool chaining.\n */\n outputSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for tool output'),\n\n /**\n * Associated object name (when the tool operates on a specific data object).\n * @example 'support_case'\n */\n objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object name (snake_case)'),\n\n /** Whether the tool requires human confirmation before execution */\n requiresConfirmation: z.boolean().default(false).describe('Require user confirmation before execution'),\n\n /** Permission profiles/roles required to use this tool */\n permissions: z.array(z.string()).optional().describe('Required permissions or roles'),\n\n /** Whether the tool is enabled */\n active: z.boolean().default(true).describe('Whether the tool is enabled'),\n\n /** Whether this is a platform built-in tool (vs. user-defined) */\n builtIn: z.boolean().default(false).describe('Platform built-in tool flag'),\n});\n\nexport type Tool = z.infer;\n\n// ==========================================\n// Factory\n// ==========================================\n\n/**\n * Type-safe factory for creating AI tool metadata definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const tool = defineTool({\n * name: 'query_orders',\n * label: 'Query Orders',\n * description: 'Search and filter customer orders',\n * category: 'data',\n * parameters: {\n * type: 'object',\n * properties: {\n * customerId: { type: 'string' },\n * status: { type: 'string', enum: ['pending', 'shipped', 'delivered'] },\n * },\n * required: ['customerId'],\n * },\n * });\n * ```\n */\nexport function defineTool(config: z.input): Tool {\n return ToolSchema.parse(config);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n// ==========================================\n// Trigger Condition\n// ==========================================\n\n/**\n * Skill Trigger Condition Schema\n *\n * Defines programmatic conditions under which a skill becomes active.\n * Allows context-aware activation based on object type, user role, etc.\n */\nexport const SkillTriggerConditionSchema = z.object({\n /** Condition field (e.g. 'objectName', 'userRole', 'channel') */\n field: z.string().describe('Context field to evaluate'),\n\n /** Comparison operator */\n operator: z.enum(['eq', 'neq', 'in', 'not_in', 'contains']).describe('Comparison operator'),\n\n /** Expected value(s) */\n value: z.union([z.string(), z.array(z.string())]).describe('Expected value or values'),\n});\n\nexport type SkillTriggerCondition = z.infer;\n\n// ==========================================\n// Skill Schema\n// ==========================================\n\n/**\n * Skill Schema\n *\n * An ability group that aggregates related tools by domain.\n * Skills are the middle tier of the Agent → Skill → Tool architecture,\n * providing reusable capability bundles that can be shared across agents.\n *\n * Aligned with Salesforce Agentforce Topics, Microsoft Copilot Studio Topics,\n * and ServiceNow Skill metadata patterns.\n *\n * @example\n * ```ts\n * const skill = defineSkill({\n * name: 'case_management',\n * label: 'Case Management',\n * description: 'Handles support case lifecycle',\n * instructions: 'Use these tools to create, update, and resolve support cases.',\n * tools: ['create_case', 'update_case', 'resolve_case', 'query_cases'],\n * triggerPhrases: ['create a case', 'open a ticket', 'resolve issue'],\n * });\n * ```\n */\nexport const SkillSchema = z.object({\n /** Machine name (snake_case, globally unique) */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Skill unique identifier (snake_case)'),\n\n /** Human-readable display name */\n label: z.string().describe('Skill display name'),\n\n /** Detailed description of the skill's purpose */\n description: z.string().optional().describe('Skill description'),\n\n /**\n * Instructions injected into the system prompt when this skill is active.\n * Guides the LLM on how and when to use the skill's tools.\n */\n instructions: z.string().optional().describe('LLM instructions when skill is active'),\n\n /**\n * References to tool names that belong to this skill.\n * Tools must be registered as first-class metadata (type: 'tool').\n */\n tools: z.array(z.string().regex(/^[a-z_][a-z0-9_]*$/)).describe('Tool names belonging to this skill'),\n\n /**\n * Natural language phrases that trigger skill activation.\n * Used for intent matching and skill routing.\n */\n triggerPhrases: z.array(z.string()).optional().describe('Phrases that activate this skill'),\n\n /**\n * Programmatic conditions for skill activation.\n * Evaluated against the runtime context (object name, user role, etc.).\n */\n triggerConditions: z.array(SkillTriggerConditionSchema).optional().describe('Programmatic activation conditions'),\n\n /** Permission profiles/roles required to use this skill */\n permissions: z.array(z.string()).optional().describe('Required permissions or roles'),\n\n /** Whether the skill is enabled */\n active: z.boolean().default(true).describe('Whether the skill is enabled'),\n});\n\nexport type Skill = z.infer;\n\n// ==========================================\n// Factory\n// ==========================================\n\n/**\n * Type-safe factory for creating AI skill definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const skill = defineSkill({\n * name: 'order_management',\n * label: 'Order Management',\n * description: 'Handles order lifecycle operations',\n * instructions: 'Use these tools to manage customer orders.',\n * tools: ['create_order', 'update_order', 'cancel_order'],\n * triggerPhrases: ['place an order', 'cancel my order'],\n * triggerConditions: [\n * { field: 'objectName', operator: 'eq', value: 'order' },\n * ],\n * });\n * ```\n */\nexport function defineSkill(config: z.input): Skill {\n return SkillSchema.parse(config);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * AI Agent Action Protocol\n * \n * Defines how AI agents can interact with the UI by mapping natural language intents\n * to structured UI actions. This enables agents to not only query data but also\n * manipulate the interface, navigate between views, and trigger workflows.\n * \n * Architecture Alignment:\n * - Salesforce Einstein: Action recommendations and automated UI interactions\n * - ServiceNow Virtual Agent: UI action automation\n * - Microsoft Power Virtual Agents: Bot actions and UI integration\n * \n * Use Cases:\n * - \"Open the new account form\" → Navigate to form view\n * - \"Show me all active opportunities\" → Navigate to list view with filter\n * - \"Create a new task for John\" → Open form with pre-filled data\n * - \"Switch to the kanban view\" → Change view mode\n */\n\n// ==========================================\n// UI Action Types\n// ==========================================\n\n/**\n * Navigation Action Types\n * Actions that change the current view or location\n */\nexport const NavigationActionTypeSchema = z.enum([\n 'navigate_to_object_list', // Navigate to object list view\n 'navigate_to_object_form', // Navigate to object form (new/edit)\n 'navigate_to_record_detail', // Navigate to specific record detail page\n 'navigate_to_dashboard', // Navigate to dashboard\n 'navigate_to_report', // Navigate to report view\n 'navigate_to_app', // Switch to different app\n 'navigate_back', // Go back to previous view\n 'navigate_home', // Go to home page\n 'open_tab', // Open new tab\n 'close_tab', // Close current tab\n]);\n\nexport type NavigationActionType = z.infer;\n\n/**\n * View Manipulation Action Types\n * Actions that change how data is displayed\n */\nexport const ViewActionTypeSchema = z.enum([\n 'change_view_mode', // Switch between list/kanban/calendar/gantt\n 'apply_filter', // Apply filter to current view\n 'clear_filter', // Clear filters\n 'apply_sort', // Apply sorting\n 'change_grouping', // Change grouping (for kanban/pivot)\n 'show_columns', // Show/hide columns\n 'expand_record', // Expand record in list\n 'collapse_record', // Collapse record in list\n 'refresh_view', // Refresh current view\n 'export_data', // Export view data\n]);\n\nexport type ViewActionType = z.infer;\n\n/**\n * Form Action Types\n * Actions that interact with forms\n */\nexport const FormActionTypeSchema = z.enum([\n 'create_record', // Create new record (submit form)\n 'update_record', // Update existing record\n 'delete_record', // Delete record\n 'fill_field', // Fill a specific form field\n 'clear_field', // Clear a form field\n 'submit_form', // Submit the form\n 'cancel_form', // Cancel form editing\n 'validate_form', // Validate form data\n 'save_draft', // Save as draft\n]);\n\nexport type FormActionType = z.infer;\n\n/**\n * Data Action Types\n * Actions that perform data operations\n */\nexport const DataActionTypeSchema = z.enum([\n 'select_record', // Select record(s) in list\n 'deselect_record', // Deselect record(s)\n 'select_all', // Select all records\n 'deselect_all', // Deselect all records\n 'bulk_update', // Bulk update selected records\n 'bulk_delete', // Bulk delete selected records\n 'bulk_export', // Bulk export selected records\n]);\n\nexport type DataActionType = z.infer;\n\n/**\n * Workflow Action Types\n * Actions that trigger workflows or automations\n */\nexport const WorkflowActionTypeSchema = z.enum([\n 'trigger_flow', // Trigger a flow/workflow\n 'trigger_approval', // Start approval process\n 'trigger_webhook', // Trigger webhook\n 'run_report', // Run a report\n 'send_email', // Send email\n 'send_notification', // Send notification\n 'schedule_task', // Schedule a task\n]);\n\nexport type WorkflowActionType = z.infer;\n\n/**\n * UI Component Action Types\n * Actions that interact with UI components\n */\nexport const ComponentActionTypeSchema = z.enum([\n 'open_modal', // Open modal dialog\n 'close_modal', // Close modal dialog\n 'open_sidebar', // Open sidebar panel\n 'close_sidebar', // Close sidebar panel\n 'show_notification', // Show toast/notification\n 'hide_notification', // Hide notification\n 'open_dropdown', // Open dropdown menu\n 'close_dropdown', // Close dropdown menu\n 'toggle_section', // Toggle collapsible section\n]);\n\nexport type ComponentActionType = z.infer;\n\n/**\n * All UI Action Types Combined\n */\nexport const UIActionTypeSchema = z.union([\n NavigationActionTypeSchema,\n ViewActionTypeSchema,\n FormActionTypeSchema,\n DataActionTypeSchema,\n WorkflowActionTypeSchema,\n ComponentActionTypeSchema,\n]);\n\nexport type UIActionType = z.infer;\n\n// ==========================================\n// Action Parameters\n// ==========================================\n\n/**\n * Navigation Action Parameters\n */\nexport const NavigationActionParamsSchema = z.object({\n object: z.string().optional().describe('Object name (for object-specific navigation)'),\n recordId: z.string().optional().describe('Record ID (for detail page)'),\n viewType: z.enum(['list', 'form', 'detail', 'kanban', 'calendar', 'gantt']).optional(),\n dashboardId: z.string().optional().describe('Dashboard ID'),\n reportId: z.string().optional().describe('Report ID'),\n appName: z.string().optional().describe('App name'),\n mode: z.enum(['new', 'edit', 'view']).optional().describe('Form mode'),\n openInNewTab: z.boolean().optional().describe('Open in new tab'),\n});\n\nexport type NavigationActionParams = z.infer;\n\n/**\n * View Action Parameters\n */\nexport const ViewActionParamsSchema = z.object({\n viewMode: z.enum(['list', 'kanban', 'calendar', 'gantt', 'pivot']).optional(),\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter conditions'),\n sort: z.array(z.object({\n field: z.string(),\n order: z.enum(['asc', 'desc']),\n })).optional(),\n groupBy: z.string().optional().describe('Field to group by'),\n columns: z.array(z.string()).optional().describe('Columns to show/hide'),\n recordId: z.string().optional().describe('Record to expand/collapse'),\n exportFormat: z.enum(['csv', 'xlsx', 'pdf', 'json']).optional(),\n});\n\nexport type ViewActionParams = z.infer;\n\n/**\n * Form Action Parameters\n */\nexport const FormActionParamsSchema = z.object({\n object: z.string().optional().describe('Object name'),\n recordId: z.string().optional().describe('Record ID (for edit/delete)'),\n fieldValues: z.record(z.string(), z.unknown()).optional().describe('Field name-value pairs'),\n fieldName: z.string().optional().describe('Specific field to fill/clear'),\n fieldValue: z.unknown().optional().describe('Value to set'),\n validateOnly: z.boolean().optional().describe('Validate without saving'),\n});\n\nexport type FormActionParams = z.infer;\n\n/**\n * Data Action Parameters\n */\nexport const DataActionParamsSchema = z.object({\n recordIds: z.array(z.string()).optional().describe('Record IDs to select/operate on'),\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter for bulk operations'),\n updateData: z.record(z.string(), z.unknown()).optional().describe('Data for bulk update'),\n exportFormat: z.enum(['csv', 'xlsx', 'pdf', 'json']).optional(),\n});\n\nexport type DataActionParams = z.infer;\n\n/**\n * Workflow Action Parameters\n */\nexport const WorkflowActionParamsSchema = z.object({\n flowName: z.string().optional().describe('Flow/workflow name'),\n approvalProcessName: z.string().optional().describe('Approval process name'),\n webhookUrl: z.string().optional().describe('Webhook URL'),\n reportName: z.string().optional().describe('Report name'),\n emailTemplate: z.string().optional().describe('Email template'),\n recipients: z.array(z.string()).optional().describe('Email recipients'),\n subject: z.string().optional().describe('Email subject'),\n message: z.string().optional().describe('Notification/email message'),\n taskData: z.record(z.string(), z.unknown()).optional().describe('Task creation data'),\n scheduleTime: z.string().optional().describe('Schedule time (ISO 8601)'),\n contextData: z.record(z.string(), z.unknown()).optional().describe('Additional context data'),\n});\n\nexport type WorkflowActionParams = z.infer;\n\n/**\n * Component Action Parameters\n */\nexport const ComponentActionParamsSchema = z.object({\n componentId: z.string().optional().describe('Component ID'),\n modalConfig: z.object({\n title: z.string().optional(),\n content: z.unknown().optional(),\n size: z.enum(['small', 'medium', 'large', 'fullscreen']).optional(),\n }).optional(),\n notificationConfig: z.object({\n type: z.enum(['info', 'success', 'warning', 'error']).optional(),\n message: z.string(),\n duration: z.number().optional().describe('Duration in ms'),\n }).optional(),\n sidebarConfig: z.object({\n position: z.enum(['left', 'right']).optional(),\n width: z.string().optional(),\n content: z.unknown().optional(),\n }).optional(),\n});\n\nexport type ComponentActionParams = z.infer;\n\n// ==========================================\n// Agent Action Schema\n// ==========================================\n\n/**\n * Agent UI Action Schema\n * Complete definition of an AI agent's UI action\n */\nexport const AgentActionSchema = z.object({\n /**\n * Action identifier (generated)\n */\n id: z.string().optional().describe('Unique action ID'),\n \n /**\n * Action type\n */\n type: UIActionTypeSchema.describe('Type of UI action to perform'),\n \n /**\n * Action parameters (discriminated union based on type)\n */\n params: z.union([\n NavigationActionParamsSchema,\n ViewActionParamsSchema,\n FormActionParamsSchema,\n DataActionParamsSchema,\n WorkflowActionParamsSchema,\n ComponentActionParamsSchema,\n ]).describe('Action-specific parameters'),\n \n /**\n * Confirmation requirement\n */\n requireConfirmation: z.boolean().default(false).describe('Require user confirmation before executing'),\n \n /**\n * Confirmation message\n */\n confirmationMessage: z.string().optional().describe('Message to show in confirmation dialog'),\n \n /**\n * Success message\n */\n successMessage: z.string().optional().describe('Message to show on success'),\n \n /**\n * Error handling\n */\n onError: z.enum(['retry', 'skip', 'abort']).default('abort').describe('Error handling strategy'),\n \n /**\n * Execution metadata\n */\n metadata: z.object({\n intent: z.string().optional().describe('Original user intent/query'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n agentName: z.string().optional().describe('Agent that generated this action'),\n timestamp: z.string().datetime().optional().describe('Generation timestamp (ISO 8601)'),\n }).optional(),\n});\n\n/**\n * Agent Action Typed Schemas\n * Bind params to specific action types for type safety\n */\nexport const NavigationAgentActionSchema = AgentActionSchema.extend({\n type: NavigationActionTypeSchema,\n params: NavigationActionParamsSchema,\n});\n\nexport const ViewAgentActionSchema = AgentActionSchema.extend({\n type: ViewActionTypeSchema,\n params: ViewActionParamsSchema,\n});\n\nexport const FormAgentActionSchema = AgentActionSchema.extend({\n type: FormActionTypeSchema,\n params: FormActionParamsSchema,\n});\n\nexport const DataAgentActionSchema = AgentActionSchema.extend({\n type: DataActionTypeSchema,\n params: DataActionParamsSchema,\n});\n\nexport const WorkflowAgentActionSchema = AgentActionSchema.extend({\n type: WorkflowActionTypeSchema,\n params: WorkflowActionParamsSchema,\n});\n\nexport const ComponentAgentActionSchema = AgentActionSchema.extend({\n type: ComponentActionTypeSchema,\n params: ComponentActionParamsSchema,\n});\n\n/**\n * Typed Agent Action Union\n * Replaces the generic AgentActionSchema for stricter typing where possible\n */\nexport const TypedAgentActionSchema = z.union([\n NavigationAgentActionSchema,\n ViewAgentActionSchema,\n FormAgentActionSchema,\n DataAgentActionSchema,\n WorkflowAgentActionSchema,\n ComponentAgentActionSchema,\n]);\n\nexport type AgentAction = z.infer;\n\n/**\n * Agent Action Sequence Schema\n * Multiple actions to be executed in sequence\n */\nexport const AgentActionSequenceSchema = z.object({\n /**\n * Sequence identifier\n */\n id: z.string().optional().describe('Unique sequence ID'),\n \n /**\n * Actions to execute\n */\n actions: z.array(AgentActionSchema).describe('Ordered list of actions'),\n \n /**\n * Execution mode\n */\n mode: z.enum(['sequential', 'parallel']).default('sequential').describe('Execution mode'),\n \n /**\n * Stop on first error\n */\n stopOnError: z.boolean().default(true).describe('Stop sequence on first error'),\n \n /**\n * Transaction mode (all-or-nothing)\n */\n atomic: z.boolean().default(false).describe('Transaction mode (all-or-nothing)'),\n\n startTime: z.string().datetime().optional().describe('Execution start time (ISO 8601)'),\n\n endTime: z.string().datetime().optional().describe('Execution end time (ISO 8601)'),\n /**\n * Metadata\n */\n metadata: z.object({\n intent: z.string().optional().describe('Original user intent'),\n confidence: z.number().min(0).max(1).optional().describe('Overall confidence score'),\n agentName: z.string().optional().describe('Agent that generated this sequence'),\n }).optional(),\n});\n\nexport type AgentActionSequence = z.infer;\n\n/**\n * Agent Action Result Schema\n * Result of executing an agent action\n */\nexport const AgentActionResultSchema = z.object({\n /**\n * Action ID\n */\n actionId: z.string().describe('ID of the executed action'),\n \n /**\n * Execution status\n */\n status: z.enum(['success', 'error', 'cancelled', 'pending']).describe('Execution status'),\n \n /**\n * Result data\n */\n data: z.unknown().optional().describe('Action result data'),\n \n /**\n * Error information\n */\n error: z.object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n }).optional().describe('Error details if status is \"error\"'),\n \n /**\n * Execution metadata\n */\n metadata: z.object({\n startTime: z.string().optional().describe('Execution start time (ISO 8601)'),\n endTime: z.string().optional().describe('Execution end time (ISO 8601)'),\n duration: z.number().optional().describe('Execution duration in ms'),\n }).optional(),\n});\n\nexport type AgentActionResult = z.infer;\n\n/**\n * Agent Action Sequence Result Schema\n * Result of executing an action sequence\n */\nexport const AgentActionSequenceResultSchema = z.object({\n /**\n * Sequence ID\n */\n sequenceId: z.string().describe('ID of the executed sequence'),\n \n /**\n * Overall status\n */\n status: z.enum(['success', 'partial_success', 'error', 'cancelled']).describe('Overall execution status'),\n \n /**\n * Individual action results\n */\n results: z.array(AgentActionResultSchema).describe('Results for each action'),\n \n /**\n * Summary\n */\n summary: z.object({\n total: z.number().describe('Total number of actions'),\n successful: z.number().describe('Number of successful actions'),\n failed: z.number().describe('Number of failed actions'),\n cancelled: z.number().describe('Number of cancelled actions'),\n }),\n \n /**\n * Execution metadata\n */\n metadata: z.object({\n startTime: z.string().optional(),\n endTime: z.string().optional(),\n totalDuration: z.number().optional().describe('Total execution time in ms'),\n }).optional(),\n});\n\nexport type AgentActionSequenceResult = z.infer;\n\n// ==========================================\n// Helper Schemas\n// ==========================================\n\n/**\n * Intent to Action Mapping Schema\n * Maps natural language intent patterns to UI actions\n */\nexport const IntentActionMappingSchema = z.object({\n /**\n * Intent pattern (regex or exact match)\n */\n intent: z.string().describe('Intent pattern (e.g., \"open_new_record_form\")'),\n \n /**\n * Intent examples (for training)\n */\n examples: z.array(z.string()).optional().describe('Example user queries'),\n \n /**\n * Action template\n */\n actionTemplate: AgentActionSchema.describe('Action to execute'),\n \n /**\n * Parameter extraction rules\n */\n paramExtraction: z.record(z.string(), z.object({\n type: z.enum(['entity', 'slot', 'context']),\n required: z.boolean().default(false),\n default: z.unknown().optional(),\n })).optional().describe('Rules for extracting parameters from user input'),\n \n /**\n * Confidence threshold\n */\n minConfidence: z.number().min(0).max(1).default(0.7).describe('Minimum confidence to execute'),\n});\n\nexport type IntentActionMapping = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { AgentSchema, AIToolSchema } from './agent.zod';\n\n/**\n * DevOps Agent Protocol\n * \n * Defines autonomous DevOps agents that can self-iterate on enterprise\n * management software development using the ObjectStack specification.\n * \n * This agent integrates with GitHub for version control and Vercel for\n * deployment, enabling fully automated development, testing, and release cycles.\n * \n * Architecture:\n * - Self-iterating development based on ObjectStack specifications\n * - Automated code generation following best practices\n * - Continuous integration and deployment\n * - Version management and release automation\n * - Monitoring and rollback capabilities\n * \n * Use Cases:\n * - Automated feature development from specifications\n * - Self-healing code based on test failures\n * - Automated dependency updates\n * - Continuous optimization and refactoring\n * - Automated documentation generation\n * \n * @example\n * ```typescript\n * import { DevOpsAgent } from '@objectstack/spec/ai';\n * \n * const agent: DevOpsAgent = {\n * name: 'devops_automation_agent',\n * label: 'DevOps Automation Agent',\n * role: 'Senior Full-Stack DevOps Engineer',\n * instructions: '...',\n * developmentConfig: {\n * specificationSource: 'packages/spec',\n * codeGeneration: {\n * enabled: true,\n * targets: ['frontend', 'backend', 'api'],\n * },\n * },\n * integrations: {\n * github: {\n * connector: 'github_production',\n * repository: {\n * owner: 'objectstack-ai',\n * name: 'app',\n * },\n * },\n * vercel: {\n * connector: 'vercel_production',\n * project: 'objectstack-app',\n * },\n * },\n * };\n * ```\n */\n\n/**\n * Code Generation Targets\n */\nexport const CodeGenerationTargetSchema = z.enum([\n 'frontend', // Frontend UI components\n 'backend', // Backend services\n 'api', // API endpoints\n 'database', // Database schemas\n 'tests', // Test suites\n 'documentation', // Documentation\n 'infrastructure', // Infrastructure as code\n]).describe('Code generation target');\n\nexport type CodeGenerationTarget = z.infer;\n\n/**\n * Code Generation Configuration\n */\nexport const CodeGenerationConfigSchema = z.object({\n /**\n * Enable code generation\n */\n enabled: z.boolean().optional().default(true).describe('Enable code generation'),\n \n /**\n * Generation targets\n */\n targets: z.array(CodeGenerationTargetSchema).describe('Code generation targets'),\n \n /**\n * Template repository\n */\n templateRepo: z.string().optional().describe('Template repository for scaffolding'),\n \n /**\n * Code style guide\n */\n styleGuide: z.string().optional().describe('Code style guide to follow'),\n \n /**\n * Include tests\n */\n includeTests: z.boolean().optional().default(true).describe('Generate tests with code'),\n \n /**\n * Include documentation\n */\n includeDocumentation: z.boolean().optional().default(true).describe('Generate documentation'),\n \n /**\n * Validation mode\n */\n validationMode: z.enum(['strict', 'moderate', 'permissive']).optional().default('strict').describe('Code validation strictness'),\n});\n\nexport type CodeGenerationConfig = z.infer;\n\n/**\n * Testing Configuration\n */\nexport const TestingConfigSchema = z.object({\n /**\n * Enable automated testing\n */\n enabled: z.boolean().optional().default(true).describe('Enable automated testing'),\n \n /**\n * Test types to run\n */\n testTypes: z.array(z.enum([\n 'unit',\n 'integration',\n 'e2e',\n 'performance',\n 'security',\n 'accessibility',\n ])).optional().default(['unit', 'integration']).describe('Types of tests to run'),\n \n /**\n * Minimum coverage threshold\n */\n coverageThreshold: z.number().min(0).max(100).optional().default(80).describe('Minimum test coverage percentage'),\n \n /**\n * Test framework\n */\n framework: z.string().optional().describe('Testing framework (e.g., vitest, jest, playwright)'),\n \n /**\n * Run tests before commit\n */\n preCommitTests: z.boolean().optional().default(true).describe('Run tests before committing'),\n \n /**\n * Auto-fix failing tests\n */\n autoFix: z.boolean().optional().default(false).describe('Attempt to auto-fix failing tests'),\n});\n\nexport type TestingConfig = z.infer;\n\n/**\n * CI/CD Pipeline Stage\n */\nexport const PipelineStageSchema = z.object({\n /**\n * Stage name\n */\n name: z.string().describe('Pipeline stage name'),\n \n /**\n * Stage type\n */\n type: z.enum([\n 'build',\n 'test',\n 'lint',\n 'security_scan',\n 'deploy',\n 'smoke_test',\n 'rollback',\n ]).describe('Stage type'),\n \n /**\n * Stage order\n */\n order: z.number().int().min(0).describe('Execution order'),\n \n /**\n * Run in parallel\n */\n parallel: z.boolean().optional().default(false).describe('Can run in parallel with other stages'),\n \n /**\n * Commands to execute\n */\n commands: z.array(z.string()).describe('Commands to execute'),\n \n /**\n * Environment variables\n */\n env: z.record(z.string(), z.string()).optional().describe('Stage-specific environment variables'),\n \n /**\n * Timeout in seconds\n */\n timeout: z.number().int().min(60).optional().default(600).describe('Stage timeout in seconds'),\n \n /**\n * Retry on failure\n */\n retryOnFailure: z.boolean().optional().default(false).describe('Retry stage on failure'),\n \n /**\n * Max retry attempts\n */\n maxRetries: z.number().int().min(0).max(5).optional().default(0).describe('Maximum retry attempts'),\n});\n\nexport type PipelineStage = z.infer;\n\n/**\n * CI/CD Pipeline Configuration\n */\nexport const CICDPipelineConfigSchema = z.object({\n /**\n * Pipeline name\n */\n name: z.string().describe('Pipeline name'),\n \n /**\n * Pipeline trigger\n */\n trigger: z.enum([\n 'push',\n 'pull_request',\n 'release',\n 'schedule',\n 'manual',\n ]).describe('Pipeline trigger'),\n \n /**\n * Branch filters\n */\n branches: z.array(z.string()).optional().describe('Branches to run pipeline on'),\n \n /**\n * Pipeline stages\n */\n stages: z.array(PipelineStageSchema).describe('Pipeline stages'),\n \n /**\n * Enable notifications\n */\n notifications: z.object({\n onSuccess: z.boolean().optional().default(false),\n onFailure: z.boolean().optional().default(true),\n channels: z.array(z.string()).optional().describe('Notification channels (e.g., slack, email)'),\n }).optional().describe('Pipeline notifications'),\n});\n\nexport type CICDPipelineConfig = z.infer;\n\n/**\n * Version Management Configuration\n */\nexport const VersionManagementSchema = z.object({\n /**\n * Versioning scheme\n */\n scheme: z.enum(['semver', 'calver', 'custom']).optional().default('semver').describe('Versioning scheme'),\n \n /**\n * Auto-increment strategy\n */\n autoIncrement: z.enum(['major', 'minor', 'patch', 'none']).optional().default('patch').describe('Auto-increment strategy'),\n \n /**\n * Version prefix\n */\n prefix: z.string().optional().default('v').describe('Version tag prefix'),\n \n /**\n * Create changelog\n */\n generateChangelog: z.boolean().optional().default(true).describe('Generate changelog automatically'),\n \n /**\n * Changelog format\n */\n changelogFormat: z.enum(['conventional', 'keepachangelog', 'custom']).optional().default('conventional').describe('Changelog format'),\n \n /**\n * Tag releases\n */\n tagReleases: z.boolean().optional().default(true).describe('Create Git tags for releases'),\n});\n\nexport type VersionManagement = z.infer;\n\n/**\n * Deployment Strategy Configuration\n */\nexport const DeploymentStrategySchema = z.object({\n /**\n * Strategy type\n */\n type: z.enum([\n 'rolling',\n 'blue_green',\n 'canary',\n 'recreate',\n ]).optional().default('rolling').describe('Deployment strategy'),\n \n /**\n * Canary percentage (for canary deployments)\n */\n canaryPercentage: z.number().min(0).max(100).optional().default(10).describe('Canary deployment percentage'),\n \n /**\n * Health check URL\n */\n healthCheckUrl: z.string().optional().describe('Health check endpoint'),\n \n /**\n * Health check timeout\n */\n healthCheckTimeout: z.number().int().min(10).optional().default(60).describe('Health check timeout in seconds'),\n \n /**\n * Rollback on failure\n */\n autoRollback: z.boolean().optional().default(true).describe('Automatically rollback on failure'),\n \n /**\n * Smoke tests\n */\n smokeTests: z.array(z.string()).optional().describe('Smoke test commands to run post-deployment'),\n});\n\nexport type DeploymentStrategy = z.infer;\n\n/**\n * Monitoring Configuration\n */\nexport const MonitoringConfigSchema = z.object({\n /**\n * Enable monitoring\n */\n enabled: z.boolean().optional().default(true).describe('Enable monitoring'),\n \n /**\n * Metrics to track\n */\n metrics: z.array(z.enum([\n 'performance',\n 'errors',\n 'usage',\n 'availability',\n 'latency',\n ])).optional().default(['performance', 'errors', 'availability']).describe('Metrics to monitor'),\n \n /**\n * Alert thresholds\n */\n alerts: z.array(z.object({\n name: z.string().describe('Alert name'),\n metric: z.string().describe('Metric to monitor'),\n threshold: z.number().describe('Alert threshold'),\n severity: z.enum(['info', 'warning', 'critical']).describe('Alert severity'),\n })).optional().describe('Alert configurations'),\n \n /**\n * Monitoring integrations\n */\n integrations: z.array(z.string()).optional().describe('Monitoring service integrations'),\n});\n\nexport type MonitoringConfig = z.infer;\n\n/**\n * Development Configuration\n */\nexport const DevelopmentConfigSchema = z.object({\n /**\n * ObjectStack specification source\n */\n specificationSource: z.string().describe('Path to ObjectStack specification'),\n \n /**\n * Code generation configuration\n */\n codeGeneration: CodeGenerationConfigSchema.describe('Code generation settings'),\n \n /**\n * Testing configuration\n */\n testing: TestingConfigSchema.optional().describe('Testing configuration'),\n \n /**\n * Linting configuration\n */\n linting: z.object({\n enabled: z.boolean().optional().default(true),\n autoFix: z.boolean().optional().default(true),\n rules: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Code linting configuration'),\n \n /**\n * Formatting configuration\n */\n formatting: z.object({\n enabled: z.boolean().optional().default(true),\n autoFormat: z.boolean().optional().default(true),\n config: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Code formatting configuration'),\n});\n\nexport type DevelopmentConfig = z.infer;\n\n/**\n * GitHub Integration Configuration\n */\nexport const GitHubIntegrationSchema = z.object({\n /**\n * GitHub connector reference\n */\n connector: z.string().describe('GitHub connector name'),\n \n /**\n * Repository configuration\n */\n repository: z.object({\n owner: z.string().describe('Repository owner'),\n name: z.string().describe('Repository name'),\n }).describe('Repository configuration'),\n \n /**\n * Default branch for features\n */\n featureBranch: z.string().optional().default('develop').describe('Default feature branch'),\n \n /**\n * Pull request configuration\n */\n pullRequest: z.object({\n autoCreate: z.boolean().optional().default(true).describe('Automatically create PRs'),\n autoMerge: z.boolean().optional().default(false).describe('Automatically merge PRs when checks pass'),\n requireReviews: z.boolean().optional().default(true).describe('Require reviews before merge'),\n deleteBranchOnMerge: z.boolean().optional().default(true).describe('Delete feature branch after merge'),\n }).optional().describe('Pull request settings'),\n});\n\nexport type GitHubIntegration = z.infer;\n\n/**\n * Vercel Integration Configuration\n */\nexport const VercelIntegrationSchema = z.object({\n /**\n * Vercel connector reference\n */\n connector: z.string().describe('Vercel connector name'),\n \n /**\n * Project name\n */\n project: z.string().describe('Vercel project name'),\n \n /**\n * Environment mapping\n */\n environments: z.object({\n production: z.string().optional().default('main').describe('Production branch'),\n preview: z.array(z.string()).optional().default(['develop', 'feature/*']).describe('Preview branches'),\n }).optional().describe('Environment mapping'),\n \n /**\n * Deployment configuration\n */\n deployment: z.object({\n autoDeployProduction: z.boolean().optional().default(false).describe('Auto-deploy to production'),\n autoDeployPreview: z.boolean().optional().default(true).describe('Auto-deploy preview environments'),\n requireApproval: z.boolean().optional().default(true).describe('Require approval for production deployments'),\n }).optional().describe('Deployment settings'),\n});\n\nexport type VercelIntegration = z.infer;\n\n/**\n * Integration Configuration\n */\nexport const IntegrationConfigSchema = z.object({\n /**\n * GitHub integration\n */\n github: GitHubIntegrationSchema.describe('GitHub integration configuration'),\n \n /**\n * Vercel integration\n */\n vercel: VercelIntegrationSchema.describe('Vercel integration configuration'),\n \n /**\n * Additional integrations\n */\n additional: z.record(z.string(), z.unknown()).optional().describe('Additional integration configurations'),\n});\n\nexport type IntegrationConfig = z.infer;\n\n/**\n * DevOps Agent Schema\n * Complete autonomous DevOps agent configuration\n */\nexport const DevOpsAgentSchema = AgentSchema.extend({\n /**\n * Development configuration\n */\n developmentConfig: DevelopmentConfigSchema.describe('Development configuration'),\n \n /**\n * CI/CD pipelines\n */\n pipelines: z.array(CICDPipelineConfigSchema).optional().describe('CI/CD pipelines'),\n \n /**\n * Version management\n */\n versionManagement: VersionManagementSchema.optional().describe('Version management configuration'),\n \n /**\n * Deployment strategy\n */\n deploymentStrategy: DeploymentStrategySchema.optional().describe('Deployment strategy'),\n \n /**\n * Monitoring configuration\n */\n monitoring: MonitoringConfigSchema.optional().describe('Monitoring configuration'),\n \n /**\n * Integration configuration\n */\n integrations: IntegrationConfigSchema.describe('Integration configurations'),\n \n /**\n * Self-iteration configuration\n */\n selfIteration: z.object({\n enabled: z.boolean().optional().default(true).describe('Enable self-iteration'),\n iterationFrequency: z.string().optional().describe('Iteration frequency (cron expression)'),\n optimizationGoals: z.array(z.enum([\n 'performance',\n 'security',\n 'code_quality',\n 'test_coverage',\n 'documentation',\n ])).optional().describe('Optimization goals'),\n learningMode: z.enum(['conservative', 'balanced', 'aggressive']).optional().default('balanced').describe('Learning mode'),\n }).optional().describe('Self-iteration configuration'),\n});\n\nexport type DevOpsAgent = z.infer;\n\n/**\n * DevOps Tools Extension\n * Additional tools available to DevOps agents\n */\nexport const DevOpsToolSchema = AIToolSchema.extend({\n type: z.enum([\n 'action',\n 'flow',\n 'query',\n 'vector_search',\n // DevOps-specific tools\n 'git_operation',\n 'code_generation',\n 'test_execution',\n 'deployment',\n 'monitoring',\n ]),\n});\n\nexport type DevOpsTool = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Full-Stack DevOps Agent\n */\nexport const fullStackDevOpsAgentExample: DevOpsAgent = {\n name: 'devops_automation_agent',\n label: 'DevOps Automation Agent',\n visibility: 'organization',\n avatar: '/avatars/devops-bot.png',\n role: 'Senior Full-Stack DevOps Engineer',\n \n instructions: `You are an autonomous DevOps agent specialized in enterprise management software development.\n\nYour responsibilities:\n1. Generate code based on ObjectStack specifications\n2. Write comprehensive tests for all generated code\n3. Ensure code quality through linting and formatting\n4. Manage Git workflow (commits, branches, PRs)\n5. Deploy applications to Vercel\n6. Monitor deployments and handle rollbacks\n7. Continuously optimize and iterate on the codebase\n\nGuidelines:\n- Follow ObjectStack naming conventions (camelCase for props, snake_case for names)\n- Write clean, maintainable, well-documented code\n- Ensure 80%+ test coverage\n- Use conventional commit messages\n- Create detailed PR descriptions\n- Deploy only after all checks pass\n- Monitor production deployments closely\n- Learn from failures and optimize continuously\n\nAlways prioritize code quality, security, and maintainability.`,\n \n model: {\n provider: 'openai',\n model: 'gpt-4-turbo-preview',\n temperature: 0.3,\n maxTokens: 8192,\n },\n \n tools: [\n {\n type: 'action',\n name: 'generate_from_spec',\n description: 'Generate code from ObjectStack specification',\n },\n {\n type: 'action',\n name: 'run_tests',\n description: 'Execute test suites',\n },\n {\n type: 'action',\n name: 'commit_and_push',\n description: 'Commit changes and push to GitHub',\n },\n {\n type: 'action',\n name: 'create_pull_request',\n description: 'Create pull request on GitHub',\n },\n {\n type: 'action',\n name: 'deploy_to_vercel',\n description: 'Deploy application to Vercel',\n },\n {\n type: 'action',\n name: 'check_deployment_health',\n description: 'Check deployment health status',\n },\n {\n type: 'action',\n name: 'rollback_deployment',\n description: 'Rollback to previous deployment',\n },\n ],\n \n knowledge: {\n topics: [\n 'objectstack_protocol',\n 'typescript_best_practices',\n 'testing_strategies',\n 'ci_cd_patterns',\n 'deployment_strategies',\n ],\n indexes: ['devops_knowledge_base'],\n },\n \n developmentConfig: {\n specificationSource: 'packages/spec',\n \n codeGeneration: {\n enabled: true,\n targets: ['frontend', 'backend', 'api', 'tests', 'documentation'],\n styleGuide: 'objectstack',\n includeTests: true,\n includeDocumentation: true,\n validationMode: 'strict',\n },\n \n testing: {\n enabled: true,\n testTypes: ['unit', 'integration', 'e2e'],\n coverageThreshold: 80,\n framework: 'vitest',\n preCommitTests: true,\n autoFix: false,\n },\n \n linting: {\n enabled: true,\n autoFix: true,\n },\n \n formatting: {\n enabled: true,\n autoFormat: true,\n },\n },\n \n pipelines: [\n {\n name: 'CI Pipeline',\n trigger: 'pull_request',\n branches: ['main', 'develop'],\n stages: [\n {\n name: 'Install Dependencies',\n type: 'build',\n order: 1,\n commands: ['pnpm install'],\n timeout: 300,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Lint',\n type: 'lint',\n order: 2,\n parallel: true,\n commands: ['pnpm run lint'],\n timeout: 180,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Type Check',\n type: 'lint',\n order: 2,\n parallel: true,\n commands: ['pnpm run type-check'],\n timeout: 180,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Test',\n type: 'test',\n order: 3,\n commands: ['pnpm run test:ci'],\n timeout: 600,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Build',\n type: 'build',\n order: 4,\n commands: ['pnpm run build'],\n timeout: 600,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Security Scan',\n type: 'security_scan',\n order: 5,\n commands: ['pnpm audit', 'pnpm run security-scan'],\n timeout: 300,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n ],\n },\n {\n name: 'CD Pipeline',\n trigger: 'push',\n branches: ['main'],\n stages: [\n {\n name: 'Deploy to Production',\n type: 'deploy',\n order: 1,\n commands: ['vercel deploy --prod'],\n timeout: 600,\n parallel: false,\n retryOnFailure: false,\n maxRetries: 0,\n },\n {\n name: 'Smoke Tests',\n type: 'smoke_test',\n order: 2,\n commands: ['pnpm run test:smoke'],\n timeout: 300,\n parallel: false,\n retryOnFailure: true,\n maxRetries: 2,\n },\n ],\n notifications: {\n onSuccess: true,\n onFailure: true,\n channels: ['slack', 'email'],\n },\n },\n ],\n \n versionManagement: {\n scheme: 'semver',\n autoIncrement: 'patch',\n prefix: 'v',\n generateChangelog: true,\n changelogFormat: 'conventional',\n tagReleases: true,\n },\n \n deploymentStrategy: {\n type: 'rolling',\n healthCheckUrl: '/api/health',\n healthCheckTimeout: 60,\n autoRollback: true,\n smokeTests: ['pnpm run test:smoke'],\n canaryPercentage: 10,\n },\n \n monitoring: {\n enabled: true,\n metrics: ['performance', 'errors', 'availability'],\n alerts: [\n {\n name: 'High Error Rate',\n metric: 'error_rate',\n threshold: 0.05,\n severity: 'critical',\n },\n {\n name: 'Slow Response Time',\n metric: 'response_time',\n threshold: 1000,\n severity: 'warning',\n },\n ],\n integrations: ['vercel', 'datadog'],\n },\n \n integrations: {\n github: {\n connector: 'github_production',\n repository: {\n owner: 'objectstack-ai',\n name: 'app',\n },\n featureBranch: 'develop',\n pullRequest: {\n autoCreate: true,\n autoMerge: false,\n requireReviews: true,\n deleteBranchOnMerge: true,\n },\n },\n \n vercel: {\n connector: 'vercel_production',\n project: 'objectstack-app',\n environments: {\n production: 'main',\n preview: ['develop', 'feature/*'],\n },\n deployment: {\n autoDeployProduction: false,\n autoDeployPreview: true,\n requireApproval: true,\n },\n },\n },\n \n selfIteration: {\n enabled: true,\n iterationFrequency: '0 0 * * 0', // Weekly on Sunday\n optimizationGoals: ['code_quality', 'test_coverage', 'performance'],\n learningMode: 'balanced',\n },\n \n active: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # AI-Driven Plugin Development Protocol\n * \n * Defines protocols for AI-powered plugin development including:\n * - Natural language to code generation\n * - Intelligent code scaffolding\n * - Automated testing and validation\n * - AI-powered code review and optimization\n * - Plugin composition and recommendation\n */\n\n/**\n * Code Generation Request\n * Request for AI to generate plugin code\n */\nexport const CodeGenerationRequestSchema = z.object({\n /**\n * Natural language description of desired functionality\n */\n description: z.string().describe('What the plugin should do'),\n \n /**\n * Plugin type to generate\n */\n pluginType: z.enum([\n 'driver', // Data driver plugin\n 'app', // Application plugin\n 'widget', // UI widget\n 'integration', // External integration\n 'automation', // Automation/workflow\n 'analytics', // Analytics plugin\n 'ai-agent', // AI agent plugin\n 'custom', // Custom plugin type\n ]),\n \n /**\n * Output format for generated code\n */\n outputFormat: z.enum([\n 'source-code', // Generate TypeScript/JavaScript source code\n 'low-code-schema', // Generate ObjectStack JSON/YAML schema definitions\n 'dsl', // Generate domain-specific language definitions\n ]).default('source-code')\n .describe('Format of the generated output'),\n \n /**\n * Target programming language (for source-code format)\n */\n language: z.enum(['typescript', 'javascript', 'python']).default('typescript'),\n \n /**\n * Framework preferences\n */\n framework: z.object({\n runtime: z.enum(['node', 'browser', 'edge', 'universal']).optional(),\n uiFramework: z.enum(['react', 'vue', 'svelte', 'none']).optional(),\n testing: z.enum(['vitest', 'jest', 'mocha', 'none']).optional(),\n }).optional(),\n \n /**\n * Required capabilities\n */\n capabilities: z.array(z.string()).optional().describe('Protocol IDs to implement'),\n \n /**\n * Dependencies\n */\n dependencies: z.array(z.string()).optional().describe('Required plugin IDs'),\n \n /**\n * Example usage (helps AI understand intent)\n */\n examples: z.array(z.object({\n input: z.string(),\n expectedOutput: z.string(),\n description: z.string().optional(),\n })).optional(),\n \n /**\n * Code style preferences (for source-code format)\n */\n style: z.object({\n indentation: z.enum(['tab', '2spaces', '4spaces']).default('2spaces'),\n quotes: z.enum(['single', 'double']).default('single'),\n semicolons: z.boolean().default(true),\n trailingComma: z.boolean().default(true),\n }).optional(),\n \n /**\n * Low-code schema preferences (for low-code-schema format)\n */\n schemaOptions: z.object({\n /**\n * Schema format\n */\n format: z.enum(['json', 'yaml', 'typescript']).default('typescript')\n .describe('Output schema format'),\n \n /**\n * Include example data\n */\n includeExamples: z.boolean().default(true),\n \n /**\n * Validation strictness\n */\n strictValidation: z.boolean().default(true),\n \n /**\n * Generate UI definitions\n */\n generateUI: z.boolean().default(true)\n .describe('Generate view, dashboard, and page definitions'),\n \n /**\n * Generate data models\n */\n generateDataModels: z.boolean().default(true)\n .describe('Generate object and field definitions'),\n }).optional(),\n \n /**\n * Additional context\n */\n context: z.object({\n /**\n * Existing code to extend\n */\n existingCode: z.string().optional(),\n \n /**\n * Related documentation URLs\n */\n documentationUrls: z.array(z.string()).optional(),\n \n /**\n * Similar plugins for reference\n */\n referencePlugins: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Generation options\n */\n options: z.object({\n /**\n * Include tests\n */\n generateTests: z.boolean().default(true),\n \n /**\n * Include documentation\n */\n generateDocs: z.boolean().default(true),\n \n /**\n * Include examples\n */\n generateExamples: z.boolean().default(true),\n \n /**\n * Code coverage target\n */\n targetCoverage: z.number().min(0).max(100).default(80),\n \n /**\n * Optimization level\n */\n optimizationLevel: z.enum(['none', 'basic', 'aggressive']).default('basic'),\n }).optional(),\n});\n\n/**\n * Generated Code\n * Result of code generation\n */\nexport const GeneratedCodeSchema = z.object({\n /**\n * Output format used\n */\n outputFormat: z.enum(['source-code', 'low-code-schema', 'dsl']),\n \n /**\n * Main plugin code (for source-code format)\n */\n code: z.string().optional(),\n \n /**\n * Language used (for source-code format)\n */\n language: z.string().optional(),\n \n /**\n * Low-code schema definitions (for low-code-schema format)\n */\n schemas: z.array(z.object({\n type: z.enum(['object', 'view', 'dashboard', 'app', 'workflow', 'api', 'page']),\n path: z.string().describe('File path for the schema'),\n content: z.string().describe('Schema content (JSON/YAML/TypeScript)'),\n description: z.string().optional(),\n })).optional()\n .describe('Generated low-code schema files'),\n \n /**\n * File structure\n */\n files: z.array(z.object({\n path: z.string(),\n content: z.string(),\n description: z.string().optional(),\n })),\n \n /**\n * Generated tests\n */\n tests: z.array(z.object({\n path: z.string(),\n content: z.string(),\n coverage: z.number().min(0).max(100).optional(),\n })).optional(),\n \n /**\n * Documentation\n */\n documentation: z.object({\n readme: z.string().optional(),\n api: z.string().optional(),\n usage: z.string().optional(),\n }).optional(),\n \n /**\n * Package metadata\n */\n package: z.object({\n name: z.string(),\n version: z.string(),\n dependencies: z.record(z.string(), z.string()).optional(),\n devDependencies: z.record(z.string(), z.string()).optional(),\n }).optional(),\n \n /**\n * Quality metrics\n */\n quality: z.object({\n complexity: z.number().optional().describe('Cyclomatic complexity'),\n maintainability: z.number().min(0).max(100).optional(),\n testCoverage: z.number().min(0).max(100).optional(),\n lintScore: z.number().min(0).max(100).optional(),\n }).optional(),\n \n /**\n * AI confidence score\n */\n confidence: z.number().min(0).max(100).describe('AI confidence in generated code'),\n \n /**\n * Suggestions for improvement\n */\n suggestions: z.array(z.string()).optional(),\n \n /**\n * Warnings or caveats\n */\n warnings: z.array(z.string()).optional(),\n});\n\n/**\n * Plugin Scaffolding Template\n * Template for plugin structure\n */\nexport const PluginScaffoldingTemplateSchema = z.object({\n /**\n * Template identifier\n */\n id: z.string(),\n \n /**\n * Template name\n */\n name: z.string(),\n \n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Plugin type\n */\n pluginType: z.string(),\n \n /**\n * File structure\n */\n structure: z.array(z.object({\n type: z.enum(['file', 'directory']),\n path: z.string(),\n template: z.string().optional().describe('Template content with variables'),\n optional: z.boolean().default(false),\n })),\n \n /**\n * Variables to be filled\n */\n variables: z.array(z.object({\n name: z.string(),\n description: z.string(),\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']),\n required: z.boolean().default(true),\n default: z.unknown().optional(),\n validation: z.string().optional().describe('Validation regex or rule'),\n })),\n \n /**\n * Post-scaffold scripts\n */\n scripts: z.array(z.object({\n name: z.string(),\n command: z.string(),\n description: z.string().optional(),\n optional: z.boolean().default(false),\n })).optional(),\n});\n\n/**\n * AI Code Review Result\n * Result of AI-powered code review\n */\nexport const AICodeReviewResultSchema = z.object({\n /**\n * Overall assessment\n */\n assessment: z.enum(['excellent', 'good', 'acceptable', 'needs-improvement', 'poor']),\n \n /**\n * Overall score (0-100)\n */\n score: z.number().min(0).max(100),\n \n /**\n * Issues found\n */\n issues: z.array(z.object({\n severity: z.enum(['critical', 'error', 'warning', 'info', 'style']),\n category: z.enum([\n 'bug',\n 'security',\n 'performance',\n 'maintainability',\n 'style',\n 'documentation',\n 'testing',\n 'type-safety',\n 'best-practice',\n ]),\n file: z.string(),\n line: z.number().int().optional(),\n column: z.number().int().optional(),\n message: z.string(),\n suggestion: z.string().optional(),\n autoFixable: z.boolean().default(false),\n autoFix: z.string().optional().describe('Automated fix code'),\n })),\n \n /**\n * Positive highlights\n */\n highlights: z.array(z.object({\n category: z.string(),\n description: z.string(),\n file: z.string().optional(),\n })).optional(),\n \n /**\n * Quality metrics\n */\n metrics: z.object({\n complexity: z.number().optional(),\n maintainability: z.number().min(0).max(100).optional(),\n testCoverage: z.number().min(0).max(100).optional(),\n duplicateCode: z.number().min(0).max(100).optional(),\n technicalDebt: z.string().optional().describe('Estimated technical debt'),\n }).optional(),\n \n /**\n * Recommendations\n */\n recommendations: z.array(z.object({\n priority: z.enum(['high', 'medium', 'low']),\n title: z.string(),\n description: z.string(),\n effort: z.enum(['trivial', 'small', 'medium', 'large']).optional(),\n })),\n \n /**\n * Security analysis\n */\n security: z.object({\n vulnerabilities: z.array(z.object({\n severity: z.enum(['critical', 'high', 'medium', 'low']),\n type: z.string(),\n description: z.string(),\n remediation: z.string().optional(),\n })).optional(),\n score: z.number().min(0).max(100).optional(),\n }).optional(),\n});\n\n/**\n * Plugin Composition Request\n * Request for AI to compose multiple plugins together\n */\nexport const PluginCompositionRequestSchema = z.object({\n /**\n * Desired outcome\n */\n goal: z.string().describe('What should the composed plugins achieve'),\n \n /**\n * Available plugins\n */\n availablePlugins: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n capabilities: z.array(z.string()).optional(),\n description: z.string().optional(),\n })),\n \n /**\n * Constraints\n */\n constraints: z.object({\n /**\n * Maximum plugins to use\n */\n maxPlugins: z.number().int().min(1).optional(),\n \n /**\n * Required plugins\n */\n requiredPlugins: z.array(z.string()).optional(),\n \n /**\n * Excluded plugins\n */\n excludedPlugins: z.array(z.string()).optional(),\n \n /**\n * Performance requirements\n */\n performance: z.object({\n maxLatency: z.number().optional().describe('Maximum latency in ms'),\n maxMemory: z.number().optional().describe('Maximum memory in bytes'),\n }).optional(),\n }).optional(),\n \n /**\n * Optimization criteria\n */\n optimize: z.enum([\n 'performance',\n 'reliability',\n 'simplicity',\n 'cost',\n 'security',\n ]).optional(),\n});\n\n/**\n * Plugin Composition Result\n * AI-generated plugin composition\n */\nexport const PluginCompositionResultSchema = z.object({\n /**\n * Selected plugins\n */\n plugins: z.array(z.object({\n pluginId: z.string(),\n version: z.string(),\n role: z.string().describe('Role in the composition'),\n configuration: z.record(z.string(), z.unknown()).optional(),\n })),\n \n /**\n * Integration code\n */\n integration: z.object({\n /**\n * Glue code to connect plugins\n */\n code: z.string(),\n \n /**\n * Configuration\n */\n config: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Initialization order\n */\n initOrder: z.array(z.string()),\n }),\n \n /**\n * Data flow diagram\n */\n dataFlow: z.array(z.object({\n from: z.string(),\n to: z.string(),\n data: z.string().describe('Data type or description'),\n })),\n \n /**\n * Expected performance\n */\n performance: z.object({\n estimatedLatency: z.number().optional().describe('Estimated latency in ms'),\n estimatedMemory: z.number().optional().describe('Estimated memory in bytes'),\n }).optional(),\n \n /**\n * Confidence score\n */\n confidence: z.number().min(0).max(100),\n \n /**\n * Alternative compositions\n */\n alternatives: z.array(z.object({\n description: z.string(),\n plugins: z.array(z.string()),\n tradeoffs: z.string(),\n })).optional(),\n \n /**\n * Warnings and considerations\n */\n warnings: z.array(z.string()).optional(),\n});\n\n/**\n * Plugin Recommendation Request\n * Request for plugin recommendations\n */\nexport const PluginRecommendationRequestSchema = z.object({\n /**\n * User context\n */\n context: z.object({\n /**\n * Current plugins installed\n */\n installedPlugins: z.array(z.string()).optional(),\n \n /**\n * User's industry\n */\n industry: z.string().optional(),\n \n /**\n * Use cases\n */\n useCases: z.array(z.string()).optional(),\n \n /**\n * Team size\n */\n teamSize: z.number().int().optional(),\n \n /**\n * Budget constraints\n */\n budget: z.enum(['free', 'low', 'medium', 'high', 'unlimited']).optional(),\n }),\n \n /**\n * Recommendation criteria\n */\n criteria: z.object({\n /**\n * Prioritize by\n */\n prioritize: z.enum([\n 'popularity',\n 'rating',\n 'compatibility',\n 'features',\n 'cost',\n 'support',\n ]).optional(),\n \n /**\n * Only certified plugins\n */\n certifiedOnly: z.boolean().default(false),\n \n /**\n * Minimum rating\n */\n minRating: z.number().min(0).max(5).optional(),\n \n /**\n * Maximum results\n */\n maxResults: z.number().int().min(1).max(50).default(10),\n }).optional(),\n});\n\n/**\n * Plugin Recommendation\n * AI-generated plugin recommendation\n */\nexport const PluginRecommendationSchema = z.object({\n /**\n * Recommended plugins\n */\n recommendations: z.array(z.object({\n pluginId: z.string(),\n name: z.string(),\n description: z.string(),\n score: z.number().min(0).max(100).describe('Relevance score'),\n reasons: z.array(z.string()).describe('Why this plugin is recommended'),\n benefits: z.array(z.string()),\n considerations: z.array(z.string()).optional(),\n alternatives: z.array(z.string()).optional(),\n estimatedValue: z.string().optional().describe('Expected value/ROI'),\n })),\n \n /**\n * Recommended combinations\n */\n combinations: z.array(z.object({\n plugins: z.array(z.string()),\n description: z.string(),\n synergies: z.array(z.string()).describe('How these plugins work well together'),\n totalScore: z.number().min(0).max(100),\n })).optional(),\n \n /**\n * Learning path\n */\n learningPath: z.array(z.object({\n step: z.number().int(),\n plugin: z.string(),\n reason: z.string(),\n resources: z.array(z.string()).optional(),\n })).optional(),\n});\n\n// Export types\nexport type CodeGenerationRequest = z.infer;\nexport type GeneratedCode = z.infer;\nexport type PluginScaffoldingTemplate = z.infer;\nexport type AICodeReviewResult = z.infer;\nexport type PluginCompositionRequest = z.infer;\nexport type PluginCompositionResult = z.infer;\nexport type PluginRecommendationRequest = z.infer;\nexport type PluginRecommendation = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { PluginHealthStatusSchema } from '../kernel/plugin-lifecycle-advanced.zod';\n\n/**\n * # Runtime AI Operations (AIOps) Protocol\n * \n * Defines protocols for AI-powered runtime operations including:\n * - Self-healing and automatic recovery\n * - Intelligent auto-scaling\n * - Anomaly detection and prediction\n * - Performance optimization\n * - Root cause analysis\n */\n\n/**\n * Anomaly Detection Configuration\n * Configuration for detecting anomalies in plugin behavior\n */\nexport const AnomalyDetectionConfigSchema = z.object({\n /**\n * Enable anomaly detection\n */\n enabled: z.boolean().default(true),\n \n /**\n * Metrics to monitor\n */\n metrics: z.array(z.enum([\n 'cpu-usage',\n 'memory-usage',\n 'response-time',\n 'error-rate',\n 'throughput',\n 'latency',\n 'connection-count',\n 'queue-depth',\n ])),\n \n /**\n * Detection algorithm\n */\n algorithm: z.enum([\n 'statistical', // Statistical thresholds\n 'machine-learning', // ML-based detection\n 'heuristic', // Rule-based heuristics\n 'hybrid', // Combination of methods\n ]).default('hybrid'),\n \n /**\n * Sensitivity level\n */\n sensitivity: z.enum(['low', 'medium', 'high']).default('medium')\n .describe('How aggressively to detect anomalies'),\n \n /**\n * Time window for analysis (seconds)\n */\n timeWindow: z.number().int().min(60).default(300)\n .describe('Historical data window for anomaly detection'),\n \n /**\n * Confidence threshold (0-100)\n */\n confidenceThreshold: z.number().min(0).max(100).default(80)\n .describe('Minimum confidence to flag as anomaly'),\n \n /**\n * Alert on detection\n */\n alertOnDetection: z.boolean().default(true),\n});\n\n/**\n * Self-Healing Action\n * Defines an automated recovery action\n */\nexport const SelfHealingActionSchema = z.object({\n /**\n * Action identifier\n */\n id: z.string(),\n \n /**\n * Action type\n */\n type: z.enum([\n 'restart', // Restart the plugin\n 'scale', // Scale resources\n 'rollback', // Rollback to previous version\n 'clear-cache', // Clear caches\n 'adjust-config', // Adjust configuration\n 'execute-script', // Run custom script\n 'notify', // Notify administrators\n ]),\n \n /**\n * Trigger condition\n */\n trigger: z.object({\n /**\n * Health status that triggers this action\n */\n healthStatus: z.array(PluginHealthStatusSchema).optional(),\n \n /**\n * Anomaly types that trigger this action\n */\n anomalyTypes: z.array(z.string()).optional(),\n \n /**\n * Error patterns that trigger this action\n */\n errorPatterns: z.array(z.string()).optional(),\n \n /**\n * Custom condition expression\n */\n customCondition: z.string().optional()\n .describe('Custom trigger condition (e.g., \"errorRate > 0.1\")'),\n }),\n \n /**\n * Action parameters\n */\n parameters: z.record(z.string(), z.unknown()).optional(),\n \n /**\n * Maximum number of attempts\n */\n maxAttempts: z.number().int().min(1).default(3),\n \n /**\n * Cooldown period between attempts (seconds)\n */\n cooldown: z.number().int().min(0).default(60),\n \n /**\n * Timeout for action execution (seconds)\n */\n timeout: z.number().int().min(1).default(300),\n \n /**\n * Require manual approval\n */\n requireApproval: z.boolean().default(false),\n \n /**\n * Priority\n */\n priority: z.number().int().min(1).default(5)\n .describe('Action priority (lower number = higher priority)'),\n});\n\n/**\n * Self-Healing Configuration\n * Complete configuration for self-healing capabilities\n */\nexport const SelfHealingConfigSchema = z.object({\n /**\n * Enable self-healing\n */\n enabled: z.boolean().default(true),\n \n /**\n * Healing strategy\n */\n strategy: z.enum([\n 'conservative', // Only safe, proven actions\n 'moderate', // Balanced approach\n 'aggressive', // Try more recovery options\n ]).default('moderate'),\n \n /**\n * Recovery actions\n */\n actions: z.array(SelfHealingActionSchema),\n \n /**\n * Anomaly detection\n */\n anomalyDetection: AnomalyDetectionConfigSchema.optional(),\n \n /**\n * Maximum concurrent healing operations\n */\n maxConcurrentHealing: z.number().int().min(1).default(1)\n .describe('Maximum number of simultaneous healing attempts'),\n \n /**\n * Learning mode\n */\n learning: z.object({\n enabled: z.boolean().default(true)\n .describe('Learn from successful/failed healing attempts'),\n \n feedbackLoop: z.boolean().default(true)\n .describe('Adjust strategy based on outcomes'),\n }).optional(),\n});\n\n/**\n * Auto-Scaling Policy\n * Defines how to automatically scale plugin resources\n */\nexport const AutoScalingPolicySchema = z.object({\n /**\n * Enable auto-scaling\n */\n enabled: z.boolean().default(false),\n \n /**\n * Scaling metric\n */\n metric: z.enum([\n 'cpu-usage',\n 'memory-usage',\n 'request-rate',\n 'response-time',\n 'queue-depth',\n 'custom',\n ]),\n \n /**\n * Custom metric query (when metric is \"custom\")\n */\n customMetric: z.string().optional(),\n \n /**\n * Target value for the metric\n */\n targetValue: z.number()\n .describe('Desired metric value (e.g., 70 for 70% CPU)'),\n \n /**\n * Scaling bounds\n */\n bounds: z.object({\n /**\n * Minimum instances\n */\n minInstances: z.number().int().min(1).default(1),\n \n /**\n * Maximum instances\n */\n maxInstances: z.number().int().min(1).default(10),\n \n /**\n * Minimum resources per instance\n */\n minResources: z.object({\n cpu: z.string().optional().describe('CPU limit (e.g., \"0.5\", \"1\")'),\n memory: z.string().optional().describe('Memory limit (e.g., \"512Mi\", \"1Gi\")'),\n }).optional(),\n \n /**\n * Maximum resources per instance\n */\n maxResources: z.object({\n cpu: z.string().optional(),\n memory: z.string().optional(),\n }).optional(),\n }),\n \n /**\n * Scale up behavior\n */\n scaleUp: z.object({\n /**\n * Threshold to trigger scale up\n */\n threshold: z.number()\n .describe('Metric value that triggers scale up'),\n \n /**\n * Stabilization window (seconds)\n */\n stabilizationWindow: z.number().int().min(0).default(60)\n .describe('How long metric must exceed threshold'),\n \n /**\n * Cooldown period (seconds)\n */\n cooldown: z.number().int().min(0).default(300)\n .describe('Minimum time between scale-up operations'),\n \n /**\n * Step size\n */\n stepSize: z.number().int().min(1).default(1)\n .describe('Number of instances to add'),\n }),\n \n /**\n * Scale down behavior\n */\n scaleDown: z.object({\n /**\n * Threshold to trigger scale down\n */\n threshold: z.number()\n .describe('Metric value that triggers scale down'),\n \n /**\n * Stabilization window (seconds)\n */\n stabilizationWindow: z.number().int().min(0).default(300)\n .describe('How long metric must be below threshold'),\n \n /**\n * Cooldown period (seconds)\n */\n cooldown: z.number().int().min(0).default(600)\n .describe('Minimum time between scale-down operations'),\n \n /**\n * Step size\n */\n stepSize: z.number().int().min(1).default(1)\n .describe('Number of instances to remove'),\n }),\n \n /**\n * Predictive scaling\n */\n predictive: z.object({\n enabled: z.boolean().default(false)\n .describe('Use ML to predict future load'),\n \n lookAhead: z.number().int().min(60).default(300)\n .describe('How far ahead to predict (seconds)'),\n \n confidence: z.number().min(0).max(100).default(80)\n .describe('Minimum confidence for prediction-based scaling'),\n }).optional(),\n});\n\n/**\n * Root Cause Analysis Request\n * Request for AI to analyze root cause of issues\n */\nexport const RootCauseAnalysisRequestSchema = z.object({\n /**\n * Incident identifier\n */\n incidentId: z.string(),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Symptoms observed\n */\n symptoms: z.array(z.object({\n type: z.string().describe('Symptom type'),\n description: z.string(),\n severity: z.enum(['low', 'medium', 'high', 'critical']),\n timestamp: z.string().datetime(),\n })),\n \n /**\n * Time range for analysis\n */\n timeRange: z.object({\n start: z.string().datetime(),\n end: z.string().datetime(),\n }),\n \n /**\n * Include log analysis\n */\n analyzeLogs: z.boolean().default(true),\n \n /**\n * Include metric analysis\n */\n analyzeMetrics: z.boolean().default(true),\n \n /**\n * Include dependency analysis\n */\n analyzeDependencies: z.boolean().default(true),\n \n /**\n * Context information\n */\n context: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Root Cause Analysis Result\n * Result of root cause analysis\n */\nexport const RootCauseAnalysisResultSchema = z.object({\n /**\n * Analysis identifier\n */\n analysisId: z.string(),\n \n /**\n * Incident identifier\n */\n incidentId: z.string(),\n \n /**\n * Identified root causes\n */\n rootCauses: z.array(z.object({\n /**\n * Cause identifier\n */\n id: z.string(),\n \n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Confidence score (0-100)\n */\n confidence: z.number().min(0).max(100),\n \n /**\n * Category\n */\n category: z.enum([\n 'code-defect',\n 'configuration',\n 'resource-exhaustion',\n 'dependency-failure',\n 'network-issue',\n 'data-corruption',\n 'security-breach',\n 'other',\n ]),\n \n /**\n * Evidence\n */\n evidence: z.array(z.object({\n type: z.enum(['log', 'metric', 'trace', 'event']),\n content: z.string(),\n timestamp: z.string().datetime().optional(),\n })),\n \n /**\n * Impact assessment\n */\n impact: z.enum(['low', 'medium', 'high', 'critical']),\n \n /**\n * Recommended actions\n */\n recommendations: z.array(z.string()),\n })),\n \n /**\n * Contributing factors\n */\n contributingFactors: z.array(z.object({\n description: z.string(),\n confidence: z.number().min(0).max(100),\n })).optional(),\n \n /**\n * Timeline of events\n */\n timeline: z.array(z.object({\n timestamp: z.string().datetime(),\n event: z.string(),\n significance: z.enum(['low', 'medium', 'high']),\n })).optional(),\n \n /**\n * Remediation plan\n */\n remediation: z.object({\n /**\n * Immediate actions\n */\n immediate: z.array(z.string()),\n \n /**\n * Short-term fixes\n */\n shortTerm: z.array(z.string()),\n \n /**\n * Long-term improvements\n */\n longTerm: z.array(z.string()),\n }).optional(),\n \n /**\n * Overall confidence in analysis\n */\n overallConfidence: z.number().min(0).max(100),\n \n /**\n * Analysis timestamp\n */\n timestamp: z.string().datetime(),\n});\n\n/**\n * Performance Optimization Suggestion\n * AI-generated performance optimization suggestion\n */\nexport const PerformanceOptimizationSchema = z.object({\n /**\n * Optimization identifier\n */\n id: z.string(),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Optimization type\n */\n type: z.enum([\n 'caching',\n 'query-optimization',\n 'resource-allocation',\n 'code-refactoring',\n 'architecture-change',\n 'configuration-tuning',\n ]),\n \n /**\n * Description\n */\n description: z.string(),\n \n /**\n * Expected impact\n */\n expectedImpact: z.object({\n /**\n * Performance improvement percentage\n */\n performanceGain: z.number().min(0).max(100)\n .describe('Expected performance improvement (%)'),\n \n /**\n * Resource savings\n */\n resourceSavings: z.object({\n cpu: z.number().optional().describe('CPU reduction (%)'),\n memory: z.number().optional().describe('Memory reduction (%)'),\n network: z.number().optional().describe('Network reduction (%)'),\n }).optional(),\n \n /**\n * Cost reduction\n */\n costReduction: z.number().optional()\n .describe('Estimated cost reduction (%)'),\n }),\n \n /**\n * Implementation difficulty\n */\n difficulty: z.enum(['trivial', 'easy', 'moderate', 'complex', 'very-complex']),\n \n /**\n * Implementation steps\n */\n steps: z.array(z.string()),\n \n /**\n * Risks and considerations\n */\n risks: z.array(z.string()).optional(),\n \n /**\n * Confidence score\n */\n confidence: z.number().min(0).max(100),\n \n /**\n * Priority\n */\n priority: z.enum(['low', 'medium', 'high', 'critical']),\n});\n\n/**\n * AIOps Agent Configuration\n * Configuration for AI operations agent\n */\nexport const AIOpsAgentConfigSchema = z.object({\n /**\n * Agent identifier\n */\n agentId: z.string(),\n \n /**\n * Plugin identifier\n */\n pluginId: z.string(),\n \n /**\n * Self-healing configuration\n */\n selfHealing: SelfHealingConfigSchema.optional(),\n \n /**\n * Auto-scaling policies\n */\n autoScaling: z.array(AutoScalingPolicySchema).optional(),\n \n /**\n * Continuous monitoring\n */\n monitoring: z.object({\n enabled: z.boolean().default(true),\n interval: z.number().int().min(1000).default(60000)\n .describe('Monitoring interval in milliseconds'),\n \n /**\n * Metrics to collect\n */\n metrics: z.array(z.string()).optional(),\n }).optional(),\n \n /**\n * Proactive optimization\n */\n optimization: z.object({\n enabled: z.boolean().default(true),\n \n /**\n * Scan interval (seconds)\n */\n scanInterval: z.number().int().min(3600).default(86400)\n .describe('How often to scan for optimization opportunities'),\n \n /**\n * Auto-apply optimizations\n */\n autoApply: z.boolean().default(false)\n .describe('Automatically apply low-risk optimizations'),\n }).optional(),\n \n /**\n * Incident response\n */\n incidentResponse: z.object({\n enabled: z.boolean().default(true),\n \n /**\n * Auto-trigger root cause analysis\n */\n autoRCA: z.boolean().default(true),\n \n /**\n * Notification channels\n */\n notifications: z.array(z.object({\n channel: z.enum(['email', 'slack', 'webhook', 'sms']),\n config: z.record(z.string(), z.unknown()),\n })).optional(),\n }).optional(),\n});\n\n// Export types\nexport type AnomalyDetectionConfig = z.infer;\nexport type SelfHealingAction = z.infer;\nexport type SelfHealingConfig = z.infer;\nexport type AutoScalingPolicy = z.infer;\nexport type RootCauseAnalysisRequest = z.infer;\nexport type RootCauseAnalysisResult = z.infer;\nexport type PerformanceOptimization = z.infer;\nexport type AIOpsAgentConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * AI Model Registry Protocol\n * \n * Centralized registry for managing AI models, prompt templates, and model versioning.\n * Enables AI-powered ObjectStack applications to discover and use LLMs consistently.\n */\n\n/**\n * Model Provider Type\n */\nexport const ModelProviderSchema = z.enum([\n 'openai',\n 'azure_openai',\n 'anthropic',\n 'google',\n 'cohere',\n 'huggingface',\n 'local',\n 'custom',\n]);\n\n/**\n * Model Capability\n */\nexport const ModelCapabilitySchema = z.object({\n textGeneration: z.boolean().optional().default(true).describe('Supports text generation'),\n textEmbedding: z.boolean().optional().default(false).describe('Supports text embedding'),\n imageGeneration: z.boolean().optional().default(false).describe('Supports image generation'),\n imageUnderstanding: z.boolean().optional().default(false).describe('Supports image understanding'),\n functionCalling: z.boolean().optional().default(false).describe('Supports function calling'),\n codeGeneration: z.boolean().optional().default(false).describe('Supports code generation'),\n reasoning: z.boolean().optional().default(false).describe('Supports advanced reasoning'),\n});\n\n/**\n * Model Limits\n */\nexport const ModelLimitsSchema = z.object({\n maxTokens: z.number().int().positive().describe('Maximum tokens per request'),\n contextWindow: z.number().int().positive().describe('Context window size'),\n maxOutputTokens: z.number().int().positive().optional().describe('Maximum output tokens'),\n rateLimit: z.object({\n requestsPerMinute: z.number().int().positive().optional(),\n tokensPerMinute: z.number().int().positive().optional(),\n }).optional(),\n});\n\n/**\n * Model Pricing\n */\nexport const ModelPricingSchema = z.object({\n currency: z.string().optional().default('USD'),\n inputCostPer1kTokens: z.number().optional().describe('Cost per 1K input tokens'),\n outputCostPer1kTokens: z.number().optional().describe('Cost per 1K output tokens'),\n embeddingCostPer1kTokens: z.number().optional().describe('Cost per 1K embedding tokens'),\n});\n\n/**\n * Model Configuration\n */\nexport const ModelConfigSchema = z.object({\n /** Identity */\n id: z.string().describe('Unique model identifier'),\n name: z.string().describe('Model display name'),\n version: z.string().describe('Model version (e.g., \"gpt-4-turbo-2024-04-09\")'),\n provider: ModelProviderSchema,\n \n /** Capabilities */\n capabilities: ModelCapabilitySchema,\n limits: ModelLimitsSchema,\n \n /** Pricing */\n pricing: ModelPricingSchema.optional(),\n \n /** Configuration */\n endpoint: z.string().url().optional().describe('Custom API endpoint'),\n apiKey: z.string().optional().describe('API key (Warning: Prefer secretRef)'),\n secretRef: z.string().optional().describe('Reference to stored secret (e.g. system:openai_api_key)'),\n region: z.string().optional().describe('Deployment region (e.g., \"us-east-1\")'),\n \n /** Metadata */\n description: z.string().optional(),\n tags: z.array(z.string()).optional().describe('Tags for categorization'),\n deprecated: z.boolean().optional().default(false),\n recommendedFor: z.array(z.string()).optional().describe('Use case recommendations'),\n});\n\n/**\n * Prompt Template Variable\n */\nexport const PromptVariableSchema = z.object({\n name: z.string().describe('Variable name (e.g., \"user_name\", \"context\")'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).default('string'),\n required: z.boolean().default(false),\n defaultValue: z.unknown().optional(),\n description: z.string().optional(),\n validation: z.object({\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n pattern: z.string().optional(),\n enum: z.array(z.unknown()).optional(),\n }).optional(),\n});\n\n/**\n * Prompt Template\n */\nexport const PromptTemplateSchema = z.object({\n /** Identity */\n id: z.string().describe('Unique template identifier'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Template name (snake_case)'),\n label: z.string().describe('Display name'),\n \n /** Template Content */\n system: z.string().optional().describe('System prompt'),\n user: z.string().describe('User prompt template with variables'),\n assistant: z.string().optional().describe('Assistant message prefix'),\n \n /** Variables */\n variables: z.array(PromptVariableSchema).optional().describe('Template variables'),\n \n /** Model Configuration */\n modelId: z.string().optional().describe('Recommended model ID'),\n temperature: z.number().min(0).max(2).optional(),\n maxTokens: z.number().optional(),\n topP: z.number().optional(),\n frequencyPenalty: z.number().optional(),\n presencePenalty: z.number().optional(),\n stopSequences: z.array(z.string()).optional(),\n \n /** Metadata */\n version: z.string().optional().default('1.0.0'),\n description: z.string().optional(),\n category: z.string().optional().describe('Template category (e.g., \"code_generation\", \"support\")'),\n tags: z.array(z.string()).optional(),\n examples: z.array(z.object({\n input: z.record(z.string(), z.unknown()).describe('Example variable values'),\n output: z.string().describe('Expected output'),\n })).optional(),\n});\n\n/**\n * Model Registry Entry\n */\nexport const ModelRegistryEntrySchema = z.object({\n model: ModelConfigSchema,\n status: z.enum(['active', 'deprecated', 'experimental', 'disabled']).default('active'),\n priority: z.number().int().default(0).describe('Priority for model selection'),\n fallbackModels: z.array(z.string()).optional().describe('Fallback model IDs'),\n healthCheck: z.object({\n enabled: z.boolean().default(true),\n intervalSeconds: z.number().int().default(300),\n lastChecked: z.string().optional().describe('ISO timestamp'),\n status: z.enum(['healthy', 'unhealthy', 'unknown']).default('unknown'),\n }).optional(),\n});\n\n/**\n * Model Registry\n */\nexport const ModelRegistrySchema = z.object({\n name: z.string().describe('Registry name'),\n models: z.record(z.string(), ModelRegistryEntrySchema).describe('Model entries by ID'),\n promptTemplates: z.record(z.string(), PromptTemplateSchema).optional().describe('Prompt templates by name'),\n defaultModel: z.string().optional().describe('Default model ID'),\n enableAutoFallback: z.boolean().default(true).describe('Auto-fallback on errors'),\n});\n\n/**\n * Model Selection Criteria\n */\nexport const ModelSelectionCriteriaSchema = z.object({\n capabilities: z.array(z.string()).optional().describe('Required capabilities'),\n maxCostPer1kTokens: z.number().optional().describe('Maximum acceptable cost'),\n minContextWindow: z.number().optional().describe('Minimum context window size'),\n provider: ModelProviderSchema.optional(),\n tags: z.array(z.string()).optional(),\n excludeDeprecated: z.boolean().default(true),\n});\n\n// Type exports\nexport type ModelProvider = z.infer;\nexport type ModelCapability = z.infer;\nexport type ModelLimits = z.infer;\nexport type ModelPricing = z.infer;\nexport type ModelConfig = z.infer;\nexport type PromptVariable = z.infer;\nexport type PromptTemplate = z.infer;\nexport type ModelRegistryEntry = z.infer;\nexport type ModelRegistry = z.infer;\nexport type ModelSelectionCriteria = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Model Context Protocol (MCP)\n * \n * Defines the protocol for connecting AI assistants to external tools, data sources,\n * and resources. MCP enables AI models to access contextual information, invoke\n * functions, and interact with external systems in a standardized way.\n * \n * Architecture Alignment:\n * - Anthropic Model Context Protocol (MCP)\n * - OpenAI Function Calling / Tools\n * - LangChain Tool Interface\n * - Microsoft Semantic Kernel Plugins\n * \n * Use Cases:\n * - Connect AI agents to ObjectStack data (Objects, Views, Reports)\n * - Expose business logic as callable tools (Workflows, Flows, Actions)\n * - Provide dynamic context to AI models (User profile, Recent activity)\n * - Enable AI to read and modify data through standardized interfaces\n */\n\n// ==========================================\n// MCP Transport Configuration\n// ==========================================\n\n/**\n * MCP Transport Type\n * Defines how the MCP server communicates\n */\nexport const MCPTransportTypeSchema = z.enum([\n 'stdio', // Standard input/output (for local processes)\n 'http', // HTTP REST API\n 'websocket', // WebSocket bidirectional communication\n 'grpc', // gRPC for high-performance communication\n]);\n\n/**\n * MCP Transport Configuration\n */\nexport const MCPTransportConfigSchema = z.object({\n type: MCPTransportTypeSchema,\n \n /** HTTP/WebSocket Configuration */\n url: z.string().url().optional().describe('Server URL (for HTTP/WebSocket/gRPC)'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for requests'),\n \n /** Authentication */\n auth: z.object({\n type: z.enum(['none', 'bearer', 'api_key', 'oauth2', 'custom']).default('none'),\n token: z.string().optional().describe('Bearer token or API key'),\n secretRef: z.string().optional().describe('Reference to stored secret'),\n headerName: z.string().optional().describe('Custom auth header name'),\n }).optional(),\n \n /** Connection Options */\n timeout: z.number().int().positive().optional().default(30000).describe('Request timeout in milliseconds'),\n retryAttempts: z.number().int().min(0).max(5).optional().default(3),\n retryDelay: z.number().int().positive().optional().default(1000).describe('Delay between retries in milliseconds'),\n \n /** STDIO Configuration */\n command: z.string().optional().describe('Command to execute (for stdio transport)'),\n args: z.array(z.string()).optional().describe('Command arguments'),\n env: z.record(z.string(), z.string()).optional().describe('Environment variables'),\n workingDirectory: z.string().optional().describe('Working directory for the process'),\n});\n\n// ==========================================\n// MCP Resource Protocol\n// ==========================================\n\n/**\n * MCP Resource Type\n * Types of resources that can be exposed through MCP\n */\nexport const MCPResourceTypeSchema = z.enum([\n 'text', // Plain text or markdown content\n 'json', // Structured JSON data\n 'binary', // Binary data (files, images, etc.)\n 'stream', // Streaming data\n]);\n\n/**\n * MCP Resource Schema\n * Represents a piece of contextual information available to the AI\n */\nexport const MCPResourceSchema = z.object({\n /** Identity */\n uri: z.string().describe('Unique resource identifier (e.g., \"objectstack://objects/account/ABC123\")'),\n name: z.string().describe('Human-readable resource name'),\n description: z.string().optional().describe('Resource description for AI consumption'),\n \n /** Resource Type */\n mimeType: z.string().optional().describe('MIME type (e.g., \"application/json\", \"text/plain\")'),\n resourceType: MCPResourceTypeSchema.default('json'),\n \n /** Content */\n content: z.unknown().optional().describe('Resource content (for static resources)'),\n contentUrl: z.string().url().optional().describe('URL to fetch content dynamically'),\n \n /** Metadata */\n size: z.number().int().nonnegative().optional().describe('Resource size in bytes'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp (ISO 8601)'),\n tags: z.array(z.string()).optional().describe('Tags for resource categorization'),\n \n /** Access Control */\n permissions: z.object({\n read: z.boolean().default(true),\n write: z.boolean().default(false),\n delete: z.boolean().default(false),\n }).optional(),\n \n /** Caching */\n cacheable: z.boolean().default(true).describe('Whether this resource can be cached'),\n cacheMaxAge: z.number().int().nonnegative().optional().describe('Cache max age in seconds'),\n});\n\n/**\n * MCP Resource Template\n * Dynamic resource generation pattern\n */\nexport const MCPResourceTemplateSchema = z.object({\n uriPattern: z.string().describe('URI pattern with variables (e.g., \"objectstack://objects/{objectName}/{recordId}\")'),\n name: z.string().describe('Template name'),\n description: z.string().optional(),\n \n /** Parameters */\n parameters: z.array(z.object({\n name: z.string().describe('Parameter name'),\n type: z.enum(['string', 'number', 'boolean']).default('string'),\n required: z.boolean().default(true),\n description: z.string().optional(),\n pattern: z.string().optional().describe('Regex validation pattern'),\n default: z.unknown().optional(),\n })).describe('URI parameters'),\n \n /** Generation Logic */\n handler: z.string().optional().describe('Handler function name for dynamic generation'),\n \n mimeType: z.string().optional(),\n resourceType: MCPResourceTypeSchema.default('json'),\n});\n\n// ==========================================\n// MCP Tool Protocol\n// ==========================================\n\n/**\n * MCP Tool Parameter Schema\n * Defines parameters for MCP tool functions\n */\nexport const MCPToolParameterSchema: z.ZodType = z.object({\n name: z.string().describe('Parameter name'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']),\n description: z.string().describe('Parameter description for AI consumption'),\n required: z.boolean().default(false),\n default: z.unknown().optional(),\n \n /** Validation */\n enum: z.array(z.unknown()).optional().describe('Allowed values'),\n pattern: z.string().optional().describe('Regex validation pattern (for strings)'),\n minimum: z.number().optional().describe('Minimum value (for numbers)'),\n maximum: z.number().optional().describe('Maximum value (for numbers)'),\n minLength: z.number().int().nonnegative().optional().describe('Minimum length (for strings/arrays)'),\n maxLength: z.number().int().nonnegative().optional().describe('Maximum length (for strings/arrays)'),\n \n /** Nested Schema */\n properties: z.record(z.string(), z.lazy(() => MCPToolParameterSchema)).optional().describe('Properties for object types'),\n items: z.lazy(() => MCPToolParameterSchema).optional().describe('Item schema for array types'),\n});\n\n/**\n * MCP Tool Parameter Type (inferred before schema to avoid circular reference)\n */\nexport type MCPToolParameter = {\n name: string;\n type: 'string' | 'number' | 'boolean' | 'object' | 'array';\n description: string;\n required?: boolean;\n default?: unknown;\n enum?: unknown[];\n pattern?: string;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n properties?: Record;\n items?: MCPToolParameter;\n};\n\n/**\n * MCP Tool Schema\n * Represents a callable function or action available to the AI\n */\nexport const MCPToolSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Tool function name (snake_case)'),\n description: z.string().describe('Tool description for AI consumption (be detailed and specific)'),\n \n /** Parameters */\n parameters: z.array(MCPToolParameterSchema).describe('Tool parameters'),\n \n /** Return Type */\n returns: z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array', 'void']),\n description: z.string().optional(),\n schema: MCPToolParameterSchema.optional().describe('Return value schema'),\n }).optional(),\n \n /** Execution Configuration */\n handler: z.string().describe('Handler function or endpoint reference'),\n async: z.boolean().default(true).describe('Whether the tool executes asynchronously'),\n timeout: z.number().int().positive().optional().describe('Execution timeout in milliseconds'),\n \n /** Side Effects */\n sideEffects: z.enum(['none', 'read', 'write', 'delete']).default('read').describe('Tool side effects'),\n requiresConfirmation: z.boolean().default(false).describe('Require user confirmation before execution'),\n confirmationMessage: z.string().optional(),\n \n /** Examples */\n examples: z.array(z.object({\n description: z.string(),\n parameters: z.record(z.string(), z.unknown()),\n result: z.unknown().optional(),\n })).optional().describe('Usage examples for AI learning'),\n \n /** Metadata */\n category: z.string().optional().describe('Tool category (e.g., \"data\", \"workflow\", \"analytics\")'),\n tags: z.array(z.string()).optional(),\n deprecated: z.boolean().default(false),\n version: z.string().optional().default('1.0.0'),\n});\n\n// ==========================================\n// MCP Prompt Protocol\n// ==========================================\n\n/**\n * MCP Prompt Argument\n * Dynamic arguments for prompt templates\n */\nexport const MCPPromptArgumentSchema = z.object({\n name: z.string().describe('Argument name'),\n description: z.string().optional(),\n type: z.enum(['string', 'number', 'boolean']).default('string'),\n required: z.boolean().default(false),\n default: z.unknown().optional(),\n});\n\n/**\n * MCP Prompt Message\n * Individual message in a prompt template\n */\nexport const MCPPromptMessageSchema = z.object({\n role: z.enum(['system', 'user', 'assistant']).describe('Message role'),\n content: z.string().describe('Message content (can include {{variable}} placeholders)'),\n});\n\n/**\n * MCP Prompt Schema\n * Predefined prompt templates available to the AI\n */\nexport const MCPPromptSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Prompt template name (snake_case)'),\n description: z.string().optional().describe('Prompt description'),\n \n /** Template */\n messages: z.array(MCPPromptMessageSchema).describe('Prompt message sequence'),\n \n /** Arguments */\n arguments: z.array(MCPPromptArgumentSchema).optional().describe('Dynamic arguments for the prompt'),\n \n /** Metadata */\n category: z.string().optional(),\n tags: z.array(z.string()).optional(),\n version: z.string().optional().default('1.0.0'),\n});\n\n// ==========================================\n// MCP Streaming Configuration\n// ==========================================\n\n/**\n * MCP Streaming Configuration\n * Controls streaming behavior for MCP server communication\n */\nexport const MCPStreamingConfigSchema = z.object({\n /** Whether streaming is enabled */\n enabled: z.boolean().describe('Enable streaming for MCP communication'),\n\n /** Size of each streamed chunk in bytes */\n chunkSize: z.number().int().positive().optional().describe('Size of each streamed chunk in bytes'),\n\n /** Heartbeat interval to keep connection alive */\n heartbeatIntervalMs: z.number().int().positive().optional().default(30000).describe('Heartbeat interval in milliseconds'),\n\n /** Backpressure handling strategy */\n backpressure: z.enum(['drop', 'buffer', 'block']).optional().describe('Backpressure handling strategy'),\n}).describe('Streaming configuration for MCP communication');\n\n// ==========================================\n// MCP Tool Approval Configuration\n// ==========================================\n\n/**\n * MCP Tool Approval Configuration\n * Controls approval requirements for tool execution\n */\nexport const MCPToolApprovalSchema = z.object({\n /** Whether tool execution requires approval */\n requireApproval: z.boolean().default(false).describe('Require approval before tool execution'),\n\n /** Strategy for handling approvals */\n approvalStrategy: z.enum(['human_in_loop', 'auto_approve', 'policy_based']).describe('Approval strategy for tool execution'),\n\n /** Regex patterns matching tool names that require approval */\n dangerousToolPatterns: z.array(z.string()).optional().describe('Regex patterns for tools needing approval'),\n\n /** Timeout in seconds for auto-approval */\n autoApproveTimeout: z.number().int().positive().optional().describe('Auto-approve timeout in seconds'),\n}).describe('Tool approval configuration for MCP');\n\n// ==========================================\n// MCP Sampling Configuration\n// ==========================================\n\n/**\n * MCP Sampling Configuration\n * Controls LLM sampling behavior for MCP servers\n */\nexport const MCPSamplingConfigSchema = z.object({\n /** Whether sampling is enabled */\n enabled: z.boolean().describe('Enable LLM sampling'),\n\n /** Maximum tokens to generate */\n maxTokens: z.number().int().positive().describe('Maximum tokens to generate'),\n\n /** Sampling temperature */\n temperature: z.number().min(0).max(2).optional().describe('Sampling temperature'),\n\n /** Stop sequences to end generation */\n stopSequences: z.array(z.string()).optional().describe('Stop sequences to end generation'),\n\n /** Preferred model IDs in priority order */\n modelPreferences: z.array(z.string()).optional().describe('Preferred model IDs in priority order'),\n\n /** System prompt for sampling context */\n systemPrompt: z.string().optional().describe('System prompt for sampling context'),\n}).describe('Sampling configuration for MCP');\n\n// ==========================================\n// MCP Roots Configuration\n// ==========================================\n\n/**\n * MCP Root Entry\n * A single root directory or resource available to the MCP client\n */\nexport const MCPRootEntrySchema = z.object({\n /** Root URI */\n uri: z.string().describe('Root URI (e.g., file:///path/to/project)'),\n\n /** Human-readable name for the root */\n name: z.string().optional().describe('Human-readable root name'),\n\n /** Whether the root is read-only */\n readOnly: z.boolean().optional().describe('Whether the root is read-only'),\n}).describe('A single root directory or resource');\n\n/**\n * MCP Roots Configuration\n * Controls filesystem/resource roots available to the MCP client\n */\nexport const MCPRootsConfigSchema = z.object({\n /** Root directories/resources */\n roots: z.array(MCPRootEntrySchema).describe('Root directories or resources available to the client'),\n\n /** Watch roots for changes */\n watchForChanges: z.boolean().default(false).describe('Watch root directories for filesystem changes'),\n\n /** Notify server on root changes */\n notifyOnChange: z.boolean().default(true).describe('Notify server when root contents change'),\n}).describe('Roots configuration for MCP client');\n\n// ==========================================\n// MCP Server Configuration\n// ==========================================\n\n/**\n * MCP Capability\n * Features supported by the MCP server\n */\nexport const MCPCapabilitySchema = z.object({\n resources: z.boolean().default(false).describe('Supports resource listing and retrieval'),\n resourceTemplates: z.boolean().default(false).describe('Supports dynamic resource templates'),\n tools: z.boolean().default(false).describe('Supports tool/function calling'),\n prompts: z.boolean().default(false).describe('Supports prompt templates'),\n sampling: z.boolean().default(false).describe('Supports sampling from LLMs'),\n logging: z.boolean().default(false).describe('Supports logging and debugging'),\n});\n\n/**\n * MCP Server Info\n * Server metadata and capabilities\n */\nexport const MCPServerInfoSchema = z.object({\n name: z.string().describe('Server name'),\n version: z.string().describe('Server version (semver)'),\n description: z.string().optional(),\n capabilities: MCPCapabilitySchema,\n \n /** Protocol Version */\n protocolVersion: z.string().default('2024-11-05').describe('MCP protocol version'),\n \n /** Metadata */\n vendor: z.string().optional().describe('Server vendor/provider'),\n homepage: z.string().url().optional().describe('Server homepage URL'),\n documentation: z.string().url().optional().describe('Documentation URL'),\n});\n\n/**\n * MCP Server Configuration\n * Complete MCP server definition\n */\nexport const MCPServerConfigSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Server unique identifier (snake_case)'),\n label: z.string().describe('Display name'),\n description: z.string().optional(),\n \n /** Server Info */\n serverInfo: MCPServerInfoSchema,\n \n /** Transport */\n transport: MCPTransportConfigSchema,\n \n /** Resources */\n resources: z.array(MCPResourceSchema).optional().describe('Static resources'),\n resourceTemplates: z.array(MCPResourceTemplateSchema).optional().describe('Dynamic resource templates'),\n \n /** Tools */\n tools: z.array(MCPToolSchema).optional().describe('Available tools'),\n \n /** Prompts */\n prompts: z.array(MCPPromptSchema).optional().describe('Prompt templates'),\n \n /** Lifecycle */\n autoStart: z.boolean().default(false).describe('Auto-start server on system boot'),\n restartOnFailure: z.boolean().default(true).describe('Auto-restart on failure'),\n healthCheck: z.object({\n enabled: z.boolean().default(true),\n interval: z.number().int().positive().default(60000).describe('Health check interval in milliseconds'),\n timeout: z.number().int().positive().default(5000).describe('Health check timeout in milliseconds'),\n endpoint: z.string().optional().describe('Health check endpoint (for HTTP servers)'),\n }).optional(),\n \n /** Access Control */\n permissions: z.object({\n allowedAgents: z.array(z.string()).optional().describe('Agent names allowed to use this server'),\n allowedUsers: z.array(z.string()).optional().describe('User IDs allowed to use this server'),\n requireAuth: z.boolean().default(true),\n }).optional(),\n \n /** Rate Limiting */\n rateLimit: z.object({\n enabled: z.boolean().default(false),\n requestsPerMinute: z.number().int().positive().optional(),\n requestsPerHour: z.number().int().positive().optional(),\n burstSize: z.number().int().positive().optional(),\n }).optional(),\n \n /** Metadata */\n tags: z.array(z.string()).optional(),\n status: z.enum(['active', 'inactive', 'maintenance', 'deprecated']).default('active'),\n version: z.string().optional().default('1.0.0'),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n\n /** Streaming */\n streaming: MCPStreamingConfigSchema.optional().describe('Streaming configuration'),\n\n /** Tool Approval */\n toolApproval: MCPToolApprovalSchema.optional().describe('Tool approval configuration'),\n\n /** Sampling */\n sampling: MCPSamplingConfigSchema.optional().describe('LLM sampling configuration'),\n});\n\n// ==========================================\n// MCP Request/Response Schemas\n// ==========================================\n\n/**\n * MCP Resource Request\n */\nexport const MCPResourceRequestSchema = z.object({\n uri: z.string().describe('Resource URI to fetch'),\n parameters: z.record(z.string(), z.unknown()).optional().describe('URI template parameters'),\n});\n\n/**\n * MCP Resource Response\n */\nexport const MCPResourceResponseSchema = z.object({\n resource: MCPResourceSchema,\n content: z.unknown().describe('Resource content'),\n});\n\n/**\n * MCP Tool Call Request\n */\nexport const MCPToolCallRequestSchema = z.object({\n toolName: z.string().describe('Tool to invoke'),\n parameters: z.record(z.string(), z.unknown()).describe('Tool parameters'),\n \n /** Execution Options */\n timeout: z.number().int().positive().optional(),\n confirmationProvided: z.boolean().optional().describe('User confirmation for tools that require it'),\n \n /** Context */\n context: z.object({\n userId: z.string().optional(),\n sessionId: z.string().optional(),\n agentName: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n }).optional(),\n});\n\n/**\n * MCP Tool Call Response\n */\nexport const MCPToolCallResponseSchema = z.object({\n toolName: z.string(),\n status: z.enum(['success', 'error', 'timeout', 'cancelled']),\n \n /** Result */\n result: z.unknown().optional().describe('Tool execution result'),\n \n /** Error */\n error: z.object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n }).optional(),\n \n /** Metrics */\n executionTime: z.number().nonnegative().optional().describe('Execution time in milliseconds'),\n timestamp: z.string().datetime().optional(),\n});\n\n/**\n * MCP Prompt Request\n */\nexport const MCPPromptRequestSchema = z.object({\n promptName: z.string().describe('Prompt template to use'),\n arguments: z.record(z.string(), z.unknown()).optional().describe('Prompt arguments'),\n});\n\n/**\n * MCP Prompt Response\n */\nexport const MCPPromptResponseSchema = z.object({\n promptName: z.string(),\n messages: z.array(MCPPromptMessageSchema).describe('Rendered prompt messages'),\n});\n\n// ==========================================\n// MCP Client Configuration\n// ==========================================\n\n/**\n * MCP Client Configuration\n * Configuration for AI clients connecting to MCP servers\n */\nexport const MCPClientConfigSchema = z.object({\n /** Server Connection */\n servers: z.array(MCPServerConfigSchema).describe('MCP servers to connect to'),\n \n /** Client Settings */\n defaultTimeout: z.number().int().positive().default(30000).describe('Default timeout for requests'),\n enableCaching: z.boolean().default(true).describe('Enable client-side caching'),\n cacheMaxAge: z.number().int().nonnegative().default(300).describe('Cache max age in seconds'),\n \n /** Retry Logic */\n retryAttempts: z.number().int().min(0).max(5).default(3),\n retryDelay: z.number().int().positive().default(1000),\n \n /** Logging */\n enableLogging: z.boolean().default(true),\n logLevel: z.enum(['debug', 'info', 'warn', 'error']).default('info'),\n\n /** Roots */\n roots: MCPRootsConfigSchema.optional().describe('Root directories/resources configuration'),\n});\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type MCPTransportType = z.infer;\nexport type MCPTransportConfig = z.infer;\nexport type MCPResourceType = z.infer;\nexport type MCPResource = z.infer;\nexport type MCPResourceTemplate = z.infer;\n// MCPToolParameter type is exported above with the schema\nexport type MCPTool = z.infer;\nexport type MCPPromptArgument = z.infer;\nexport type MCPPromptMessage = z.infer;\nexport type MCPPrompt = z.infer;\nexport type MCPCapability = z.infer;\nexport type MCPServerInfo = z.infer;\nexport type MCPServerConfig = z.infer;\nexport type MCPResourceRequest = z.infer;\nexport type MCPResourceResponse = z.infer;\nexport type MCPToolCallRequest = z.infer;\nexport type MCPToolCallResponse = z.infer;\nexport type MCPPromptRequest = z.infer;\nexport type MCPPromptResponse = z.infer;\nexport type MCPClientConfig = z.infer;\nexport type MCPStreamingConfig = z.infer;\nexport type MCPToolApproval = z.infer;\nexport type MCPSamplingConfig = z.infer;\nexport type MCPRootEntry = z.infer;\nexport type MCPRootsConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * AI Cost Tracking Protocol\n * \n * Monitor and control AI API costs with budgets, alerts, and analytics.\n * Provides cost optimization, budget enforcement, and financial reporting.\n */\n\n/**\n * Token Usage Schema\n * Standardized across all AI operations\n */\nexport const TokenUsageSchema = z.object({\n prompt: z.number().int().nonnegative().describe('Input tokens'),\n completion: z.number().int().nonnegative().describe('Output tokens'),\n total: z.number().int().nonnegative().describe('Total tokens'),\n});\n\nexport type TokenUsage = z.infer;\n\n/**\n * AI Operation Cost Schema\n * Unified cost tracking for all AI operations\n */\nexport const AIOperationCostSchema = z.object({\n operationId: z.string(),\n operationType: z.enum(['conversation', 'orchestration', 'prediction', 'rag', 'nlq']),\n agentName: z.string().optional().describe('Agent that performed the operation'),\n modelId: z.string(),\n tokens: TokenUsageSchema,\n cost: z.number().nonnegative().describe('Cost in USD'),\n timestamp: z.string().datetime(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type AIOperationCost = z.infer;\n\n/**\n * Cost Metric Type\n */\nexport const CostMetricTypeSchema = z.enum([\n 'token', // Cost per token\n 'request', // Cost per API request\n 'character', // Cost per character (e.g., TTS)\n 'second', // Cost per second (e.g., speech)\n 'image', // Cost per image\n 'embedding', // Cost per embedding\n]);\n\n/**\n * Billing Period\n */\nexport const BillingPeriodSchema = z.enum([\n 'hourly',\n 'daily',\n 'weekly',\n 'monthly',\n 'quarterly',\n 'yearly',\n 'custom',\n]);\n\n/**\n * Cost Entry\n * Extended from AIOperationCostSchema with additional tracking fields\n */\nexport const CostEntrySchema = z.object({\n /** Identity */\n id: z.string().describe('Unique cost entry ID'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Request Details */\n modelId: z.string().describe('AI model used'),\n provider: z.string().describe('AI provider (e.g., \"openai\", \"anthropic\")'),\n operation: z.string().describe('Operation type (e.g., \"chat_completion\", \"embedding\")'),\n \n /** Usage Metrics - Standardized */\n tokens: TokenUsageSchema.optional().describe('Standardized token usage'),\n requestCount: z.number().int().positive().default(1),\n \n /** Cost Calculation */\n promptCost: z.number().nonnegative().optional().describe('Cost of prompt tokens'),\n completionCost: z.number().nonnegative().optional().describe('Cost of completion tokens'),\n totalCost: z.number().nonnegative().describe('Total cost in base currency'),\n currency: z.string().default('USD'),\n \n /** Context */\n sessionId: z.string().optional().describe('Conversation session ID'),\n userId: z.string().optional().describe('User who triggered the request'),\n agentId: z.string().optional().describe('AI agent ID'),\n object: z.string().optional().describe('Related object (e.g., \"case\", \"project\")'),\n recordId: z.string().optional().describe('Related record ID'),\n \n /** Metadata */\n tags: z.array(z.string()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Budget Type\n */\nexport const BudgetTypeSchema = z.enum([\n 'global', // Organization-wide budget\n 'user', // Per-user budget\n 'agent', // Per-agent budget\n 'object', // Per-object budget (e.g., per case)\n 'project', // Per-project budget\n 'department', // Per-department budget\n]);\n\n/**\n * Budget Limit\n */\nexport const BudgetLimitSchema = z.object({\n /** Limit Configuration */\n type: BudgetTypeSchema,\n scope: z.string().optional().describe('Scope identifier (userId, agentId, etc.)'),\n \n /** Limit Amount */\n maxCost: z.number().nonnegative().describe('Maximum cost limit'),\n currency: z.string().default('USD'),\n \n /** Period */\n period: BillingPeriodSchema,\n customPeriodDays: z.number().int().positive().optional().describe('Custom period in days'),\n \n /** Soft Limits & Warnings */\n softLimit: z.number().nonnegative().optional().describe('Soft limit for warnings'),\n warnThresholds: z.array(z.number().min(0).max(1)).optional().describe('Warning thresholds (e.g., [0.5, 0.8, 0.95])'),\n \n /** Enforcement */\n enforced: z.boolean().default(true).describe('Block requests when exceeded'),\n gracePeriodSeconds: z.number().int().nonnegative().default(0).describe('Grace period after limit exceeded'),\n \n /** Rollover */\n allowRollover: z.boolean().default(false).describe('Allow unused budget to rollover'),\n maxRolloverPercentage: z.number().min(0).max(1).optional().describe('Max rollover as % of limit'),\n \n /** Metadata */\n name: z.string().optional().describe('Budget name'),\n description: z.string().optional(),\n active: z.boolean().default(true),\n tags: z.array(z.string()).optional(),\n});\n\n/**\n * Budget Status\n */\nexport const BudgetStatusSchema = z.object({\n /** Budget Reference */\n budgetId: z.string(),\n type: BudgetTypeSchema,\n scope: z.string().optional(),\n \n /** Current Period */\n periodStart: z.string().datetime().describe('ISO 8601 timestamp'),\n periodEnd: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Usage */\n currentCost: z.number().nonnegative().default(0),\n maxCost: z.number().nonnegative(),\n currency: z.string().default('USD'),\n \n /** Status */\n percentageUsed: z.number().nonnegative().describe('Usage as percentage (can exceed 1.0 if over budget)'),\n remainingCost: z.number().describe('Remaining budget (can be negative if exceeded)'),\n isExceeded: z.boolean().default(false),\n isWarning: z.boolean().default(false),\n \n /** Projections */\n projectedCost: z.number().nonnegative().optional().describe('Projected cost for period'),\n projectedOverage: z.number().nonnegative().optional().describe('Projected overage'),\n \n /** Last Update */\n lastUpdated: z.string().datetime().describe('ISO 8601 timestamp'),\n});\n\n/**\n * Cost Alert Type\n */\nexport const CostAlertTypeSchema = z.enum([\n 'threshold_warning', // Warning threshold reached\n 'threshold_critical', // Critical threshold reached\n 'limit_exceeded', // Budget limit exceeded\n 'anomaly_detected', // Unusual spending pattern\n 'projection_exceeded', // Projected to exceed budget\n]);\n\n/**\n * Cost Alert\n */\nexport const CostAlertSchema = z.object({\n /** Alert Details */\n id: z.string(),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n type: CostAlertTypeSchema,\n severity: z.enum(['info', 'warning', 'critical']),\n \n /** Budget Context */\n budgetId: z.string().optional(),\n budgetType: BudgetTypeSchema.optional(),\n scope: z.string().optional(),\n \n /** Alert Information */\n message: z.string().describe('Alert message'),\n currentCost: z.number().nonnegative(),\n maxCost: z.number().nonnegative().optional(),\n threshold: z.number().min(0).max(1).optional(),\n currency: z.string().default('USD'),\n \n /** Recommendations */\n recommendations: z.array(z.string()).optional(),\n \n /** Status */\n acknowledged: z.boolean().default(false),\n acknowledgedBy: z.string().optional(),\n acknowledgedAt: z.string().datetime().optional(),\n resolved: z.boolean().default(false),\n \n /** Metadata */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Cost Breakdown Dimension\n */\nexport const CostBreakdownDimensionSchema = z.enum([\n 'model',\n 'provider',\n 'user',\n 'agent',\n 'object',\n 'operation',\n 'date',\n 'hour',\n 'tag',\n]);\n\n/**\n * Cost Breakdown Entry\n */\nexport const CostBreakdownEntrySchema = z.object({\n dimension: CostBreakdownDimensionSchema,\n value: z.string().describe('Dimension value (e.g., model ID, user ID)'),\n \n /** Metrics */\n totalCost: z.number().nonnegative(),\n requestCount: z.number().int().nonnegative(),\n totalTokens: z.number().int().nonnegative().optional(),\n \n /** Share */\n percentageOfTotal: z.number().min(0).max(1),\n \n /** Time Range */\n periodStart: z.string().datetime().optional(),\n periodEnd: z.string().datetime().optional(),\n});\n\n/**\n * Cost Analytics\n */\nexport const CostAnalyticsSchema = z.object({\n /** Time Range */\n periodStart: z.string().datetime().describe('ISO 8601 timestamp'),\n periodEnd: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Summary Metrics */\n totalCost: z.number().nonnegative(),\n totalRequests: z.number().int().nonnegative(),\n totalTokens: z.number().int().nonnegative().optional(),\n currency: z.string().default('USD'),\n \n /** Averages */\n averageCostPerRequest: z.number().nonnegative(),\n averageCostPerToken: z.number().nonnegative().optional(),\n averageRequestsPerDay: z.number().nonnegative(),\n \n /** Trends */\n costTrend: z.enum(['increasing', 'decreasing', 'stable']).optional(),\n trendPercentage: z.number().optional().describe('% change vs previous period'),\n \n /** Breakdowns */\n byModel: z.array(CostBreakdownEntrySchema).optional(),\n byProvider: z.array(CostBreakdownEntrySchema).optional(),\n byUser: z.array(CostBreakdownEntrySchema).optional(),\n byAgent: z.array(CostBreakdownEntrySchema).optional(),\n byOperation: z.array(CostBreakdownEntrySchema).optional(),\n byDate: z.array(CostBreakdownEntrySchema).optional(),\n \n /** Top Consumers */\n topModels: z.array(CostBreakdownEntrySchema).optional(),\n topUsers: z.array(CostBreakdownEntrySchema).optional(),\n topAgents: z.array(CostBreakdownEntrySchema).optional(),\n \n /** Efficiency Metrics */\n tokensPerDollar: z.number().nonnegative().optional(),\n requestsPerDollar: z.number().nonnegative().optional(),\n});\n\n/**\n * Cost Optimization Recommendation\n */\nexport const CostOptimizationRecommendationSchema = z.object({\n /** Recommendation Details */\n id: z.string(),\n type: z.enum([\n 'switch_model',\n 'reduce_tokens',\n 'batch_requests',\n 'cache_results',\n 'adjust_parameters',\n 'limit_usage',\n ]),\n \n /** Impact */\n title: z.string(),\n description: z.string(),\n estimatedSavings: z.number().nonnegative().optional(),\n savingsPercentage: z.number().min(0).max(1).optional(),\n \n /** Implementation */\n priority: z.enum(['low', 'medium', 'high']),\n effort: z.enum(['low', 'medium', 'high']),\n actionable: z.boolean().default(true),\n actionSteps: z.array(z.string()).optional(),\n \n /** Context */\n targetModel: z.string().optional(),\n alternativeModel: z.string().optional(),\n affectedUsers: z.array(z.string()).optional(),\n \n /** Status */\n status: z.enum(['pending', 'accepted', 'rejected', 'implemented']).default('pending'),\n implementedAt: z.string().datetime().optional(),\n});\n\n/**\n * Cost Report\n */\nexport const CostReportSchema = z.object({\n /** Report Metadata */\n id: z.string(),\n name: z.string(),\n generatedAt: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Time Range */\n periodStart: z.string().datetime().describe('ISO 8601 timestamp'),\n periodEnd: z.string().datetime().describe('ISO 8601 timestamp'),\n period: BillingPeriodSchema,\n \n /** Analytics */\n analytics: CostAnalyticsSchema,\n \n /** Budgets */\n budgets: z.array(BudgetStatusSchema).optional(),\n \n /** Alerts */\n alerts: z.array(CostAlertSchema).optional(),\n activeAlertCount: z.number().int().nonnegative().default(0),\n \n /** Recommendations */\n recommendations: z.array(CostOptimizationRecommendationSchema).optional(),\n \n /** Comparisons */\n previousPeriodCost: z.number().nonnegative().optional(),\n costChange: z.number().optional().describe('Change vs previous period'),\n costChangePercentage: z.number().optional(),\n \n /** Forecasting */\n forecastedCost: z.number().nonnegative().optional(),\n forecastedBudgetStatus: z.enum(['under', 'at', 'over']).optional(),\n \n /** Export */\n format: z.enum(['summary', 'detailed', 'executive']).default('summary'),\n currency: z.string().default('USD'),\n});\n\n/**\n * Cost Query Filters\n */\nexport const CostQueryFiltersSchema = z.object({\n /** Time Range */\n startDate: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n endDate: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n \n /** Dimensions */\n modelIds: z.array(z.string()).optional(),\n providers: z.array(z.string()).optional(),\n userIds: z.array(z.string()).optional(),\n agentIds: z.array(z.string()).optional(),\n operations: z.array(z.string()).optional(),\n sessionIds: z.array(z.string()).optional(),\n \n /** Cost Range */\n minCost: z.number().nonnegative().optional(),\n maxCost: z.number().nonnegative().optional(),\n \n /** Tags */\n tags: z.array(z.string()).optional(),\n \n /** Aggregation */\n groupBy: z.array(CostBreakdownDimensionSchema).optional(),\n \n /** Sorting */\n orderBy: z.enum(['timestamp', 'cost', 'tokens']).optional().default('timestamp'),\n orderDirection: z.enum(['asc', 'desc']).optional().default('desc'),\n \n /** Pagination */\n limit: z.number().int().positive().optional(),\n offset: z.number().int().nonnegative().optional(),\n});\n\n// Type exports\nexport type CostMetricType = z.infer;\nexport type BillingPeriod = z.infer;\nexport type CostEntry = z.infer;\nexport type BudgetType = z.infer;\nexport type BudgetLimit = z.infer;\nexport type BudgetStatus = z.infer;\nexport type CostAlertType = z.infer;\nexport type CostAlert = z.infer;\nexport type CostBreakdownDimension = z.infer;\nexport type CostBreakdownEntry = z.infer;\nexport type CostAnalytics = z.infer;\nexport type CostOptimizationRecommendation = z.infer;\nexport type CostReport = z.infer;\nexport type CostQueryFilters = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * RAG (Retrieval-Augmented Generation) Pipeline Protocol\n * \n * Defines schemas for building context-aware AI assistants using RAG techniques.\n * Enables vector search, document chunking, embeddings, and retrieval configuration.\n */\n\n/**\n * Vector Store Provider\n */\nexport const VectorStoreProviderSchema = z.enum([\n 'pinecone',\n 'weaviate',\n 'qdrant',\n 'milvus',\n 'chroma',\n 'pgvector',\n 'redis',\n 'opensearch',\n 'elasticsearch',\n 'custom',\n]);\n\n/**\n * Embedding Model\n */\nexport const EmbeddingModelSchema = z.object({\n provider: z.enum(['openai', 'cohere', 'huggingface', 'azure_openai', 'local', 'custom']),\n model: z.string().describe('Model name (e.g., \"text-embedding-3-large\")'),\n dimensions: z.number().int().positive().describe('Embedding vector dimensions'),\n maxTokens: z.number().int().positive().optional().describe('Maximum tokens per embedding'),\n batchSize: z.number().int().positive().optional().default(100).describe('Batch size for embedding'),\n endpoint: z.string().url().optional().describe('Custom endpoint URL'),\n apiKey: z.string().optional().describe('API key'),\n secretRef: z.string().optional().describe('Reference to stored secret'),\n});\n\n/**\n * Text Chunking Strategy\n */\nexport const ChunkingStrategySchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('fixed'),\n chunkSize: z.number().int().positive().describe('Fixed chunk size in tokens/chars'),\n chunkOverlap: z.number().int().min(0).default(0).describe('Overlap between chunks'),\n unit: z.enum(['tokens', 'characters']).default('tokens'),\n }),\n z.object({\n type: z.literal('semantic'),\n model: z.string().optional().describe('Model for semantic chunking'),\n minChunkSize: z.number().int().positive().default(100),\n maxChunkSize: z.number().int().positive().default(1000),\n }),\n z.object({\n type: z.literal('recursive'),\n separators: z.array(z.string()).default(['\\n\\n', '\\n', ' ', '']),\n chunkSize: z.number().int().positive(),\n chunkOverlap: z.number().int().min(0).default(0),\n }),\n z.object({\n type: z.literal('markdown'),\n maxChunkSize: z.number().int().positive().default(1000),\n respectHeaders: z.boolean().default(true).describe('Keep headers with content'),\n respectCodeBlocks: z.boolean().default(true).describe('Keep code blocks intact'),\n }),\n]);\n\n/**\n * Document Metadata Schema\n */\nexport const DocumentMetadataSchema = z.object({\n source: z.string().describe('Document source (file path, URL, etc.)'),\n sourceType: z.enum(['file', 'url', 'api', 'database', 'custom']).optional(),\n title: z.string().optional(),\n author: z.string().optional().describe('Document author'),\n createdAt: z.string().datetime().optional().describe('ISO timestamp'),\n updatedAt: z.string().datetime().optional().describe('ISO timestamp'),\n tags: z.array(z.string()).optional(),\n category: z.string().optional(),\n language: z.string().optional().describe('Document language (ISO 639-1 code)'),\n custom: z.record(z.string(), z.unknown()).optional().describe('Custom metadata fields'),\n});\n\n/**\n * Document Chunk\n */\nexport const DocumentChunkSchema = z.object({\n id: z.string().describe('Unique chunk identifier'),\n content: z.string().describe('Chunk text content'),\n embedding: z.array(z.number()).optional().describe('Embedding vector'),\n metadata: DocumentMetadataSchema,\n chunkIndex: z.number().int().min(0).describe('Chunk position in document'),\n tokens: z.number().int().optional().describe('Token count'),\n});\n\n/**\n * Retrieval Strategy\n */\nexport const RetrievalStrategySchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('similarity'),\n topK: z.number().int().positive().default(5).describe('Number of results to retrieve'),\n scoreThreshold: z.number().min(0).max(1).optional().describe('Minimum similarity score'),\n }),\n z.object({\n type: z.literal('mmr'),\n topK: z.number().int().positive().default(5),\n fetchK: z.number().int().positive().default(20).describe('Initial fetch size'),\n lambda: z.number().min(0).max(1).default(0.5).describe('Diversity vs relevance (0=diverse, 1=relevant)'),\n }),\n z.object({\n type: z.literal('hybrid'),\n topK: z.number().int().positive().default(5),\n vectorWeight: z.number().min(0).max(1).default(0.7).describe('Weight for vector search'),\n keywordWeight: z.number().min(0).max(1).default(0.3).describe('Weight for keyword search'),\n }),\n z.object({\n type: z.literal('parent_document'),\n topK: z.number().int().positive().default(5),\n retrieveParent: z.boolean().default(true).describe('Retrieve full parent document'),\n }),\n]);\n\n/**\n * Reranking Configuration\n */\nexport const RerankingConfigSchema = z.object({\n enabled: z.boolean().default(false),\n model: z.string().optional().describe('Reranking model name'),\n provider: z.enum(['cohere', 'huggingface', 'custom']).optional(),\n topK: z.number().int().positive().default(3).describe('Final number of results after reranking'),\n});\n\n/**\n * Vector Store Configuration\n */\nexport const VectorStoreConfigSchema = z.object({\n provider: VectorStoreProviderSchema,\n indexName: z.string().describe('Index/collection name'),\n namespace: z.string().optional().describe('Namespace for multi-tenancy'),\n \n /** Connection */\n host: z.string().optional().describe('Vector store host'),\n port: z.number().int().optional().describe('Vector store port'),\n secretRef: z.string().optional().describe('Reference to stored secret'),\n apiKey: z.string().optional().describe('API key or reference to secret'),\n \n /** Configuration */\n dimensions: z.number().int().positive().describe('Vector dimensions'),\n metric: z.enum(['cosine', 'euclidean', 'dotproduct']).optional().default('cosine'),\n \n /** Performance */\n batchSize: z.number().int().positive().optional().default(100),\n connectionPoolSize: z.number().int().positive().optional().default(10),\n timeout: z.number().int().positive().optional().default(30000).describe('Timeout in milliseconds'),\n});\n\n/**\n * Document Loader Configuration\n */\nexport const DocumentLoaderConfigSchema = z.object({\n type: z.enum(['file', 'directory', 'url', 'api', 'database', 'custom']),\n \n /** Source */\n source: z.string().describe('Source path, URL, or identifier'),\n \n /** File Types */\n fileTypes: z.array(z.string()).optional().describe('Accepted file extensions (e.g., [\".pdf\", \".md\"])'),\n \n /** Processing */\n recursive: z.boolean().optional().default(false).describe('Process directories recursively'),\n maxFileSize: z.number().int().optional().describe('Maximum file size in bytes'),\n excludePatterns: z.array(z.string()).optional().describe('Patterns to exclude'),\n \n /** Text Extraction */\n extractImages: z.boolean().optional().default(false).describe('Extract text from images (OCR)'),\n extractTables: z.boolean().optional().default(false).describe('Extract and format tables'),\n \n /** Custom Loader */\n loaderConfig: z.record(z.string(), z.unknown()).optional().describe('Custom loader-specific config'),\n});\n\n/**\n * Filter Expression Schema\n */\nexport const FilterExpressionSchema = z.object({\n field: z.string().describe('Metadata field to filter'),\n operator: z.enum(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'in', 'nin', 'contains']).default('eq'),\n value: z.union([z.string(), z.number(), z.boolean(), z.array(z.union([z.string(), z.number()]))]).describe('Filter value'),\n});\n\nexport type FilterGroup = {\n logic: 'and' | 'or';\n filters: (z.infer | FilterGroup)[];\n};\n\nexport const FilterGroupSchema: z.ZodType = z.object({\n logic: z.enum(['and', 'or']).default('and'),\n filters: z.array(z.union([FilterExpressionSchema, z.lazy(() => FilterGroupSchema)])),\n});\n\n/**\n * Standardized Metadata Filter\n */\nexport const MetadataFilterSchema = z.union([\n FilterExpressionSchema,\n FilterGroupSchema,\n // Legacy support for simple key-value map\n z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.union([z.string(), z.number()]))]))\n]);\n\n/**\n * RAG Pipeline Configuration\n */\nexport const RAGPipelineConfigSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Pipeline name (snake_case)'),\n label: z.string().describe('Display name'),\n description: z.string().optional(),\n \n /** Components */\n embedding: EmbeddingModelSchema,\n vectorStore: VectorStoreConfigSchema,\n chunking: ChunkingStrategySchema,\n retrieval: RetrievalStrategySchema,\n reranking: RerankingConfigSchema.optional(),\n \n /** Document Loading */\n loaders: z.array(DocumentLoaderConfigSchema).optional().describe('Document loaders'),\n \n /** Context Management */\n maxContextTokens: z.number().int().positive().default(4000).describe('Maximum tokens in context'),\n contextWindow: z.number().int().positive().optional().describe('LLM context window size'),\n \n /** Metadata Filtering */\n metadataFilters: MetadataFilterSchema.optional().describe('Global filters for retrieval'),\n \n /** Caching */\n enableCache: z.boolean().default(true),\n cacheTTL: z.number().int().positive().default(3600).describe('Cache TTL in seconds'),\n cacheInvalidationStrategy: z.enum(['time_based', 'manual', 'on_update']).default('time_based').optional(),\n});\n\n/**\n * RAG Query Request\n */\nexport const RAGQueryRequestSchema = z.object({\n query: z.string().describe('User query'),\n pipelineName: z.string().describe('Pipeline to use'),\n \n /** Override defaults */\n topK: z.number().int().positive().optional(),\n metadataFilters: z.record(z.string(), z.unknown()).optional(),\n \n /** Context */\n conversationHistory: z.array(z.object({\n role: z.enum(['user', 'assistant', 'system']),\n content: z.string(),\n })).optional(),\n \n /** Options */\n includeMetadata: z.boolean().default(true),\n includeSources: z.boolean().default(true),\n});\n\n/**\n * RAG Query Response\n */\nexport const RAGQueryResponseSchema = z.object({\n query: z.string(),\n results: z.array(z.object({\n content: z.string(),\n score: z.number(),\n metadata: DocumentMetadataSchema.optional(),\n chunkId: z.string().optional(),\n })),\n context: z.string().describe('Assembled context for LLM'),\n tokens: TokenUsageSchema.optional().describe('Token usage for this query'),\n cost: z.number().nonnegative().optional().describe('Cost for this query in USD'),\n retrievalTime: z.number().optional().describe('Retrieval time in milliseconds'),\n});\n\n/**\n * RAG Pipeline Status\n */\nexport const RAGPipelineStatusSchema = z.object({\n name: z.string(),\n status: z.enum(['active', 'indexing', 'error', 'disabled']),\n documentsIndexed: z.number().int().min(0),\n lastIndexed: z.string().datetime().optional().describe('ISO timestamp'),\n errorMessage: z.string().optional(),\n health: z.object({\n vectorStore: z.enum(['healthy', 'unhealthy', 'unknown']),\n embeddingService: z.enum(['healthy', 'unhealthy', 'unknown']),\n }).optional(),\n});\n\n// Type exports\nexport type VectorStoreProvider = z.infer;\nexport type EmbeddingModel = z.infer;\nexport type ChunkingStrategy = z.infer;\nexport type DocumentMetadata = z.infer;\nexport type DocumentChunk = z.infer;\nexport type RetrievalStrategy = z.infer;\nexport type RerankingConfig = z.infer;\nexport type VectorStoreConfig = z.infer;\nexport type DocumentLoaderConfig = z.infer;\nexport type RAGPipelineConfig = z.infer;\nexport type RAGQueryRequest = z.infer;\nexport type RAGQueryResponse = z.infer;\nexport type RAGPipelineStatus = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * Natural Language Query (NLQ) Protocol\n * \n * Transforms natural language queries into ObjectQL AST (Abstract Syntax Tree).\n * Enables business users to query data using natural language instead of writing code.\n */\n\n/**\n * Query Intent Type\n */\nexport const QueryIntentSchema = z.enum([\n 'select', // Retrieve data (e.g., \"show me all accounts\")\n 'aggregate', // Aggregation (e.g., \"total revenue by region\")\n 'filter', // Filter data (e.g., \"accounts created last month\")\n 'sort', // Sort data (e.g., \"top 10 opportunities by value\")\n 'compare', // Compare values (e.g., \"compare this quarter vs last quarter\")\n 'trend', // Analyze trends (e.g., \"sales trend over time\")\n 'insight', // Generate insights (e.g., \"what's unusual about this data\")\n 'create', // Create record (e.g., \"create a new task\")\n 'update', // Update record (e.g., \"mark this as complete\")\n 'delete', // Delete record (e.g., \"remove this contact\")\n]);\n\n/**\n * Entity Recognition\n */\nexport const EntitySchema = z.object({\n type: z.enum(['object', 'field', 'value', 'operator', 'function', 'timeframe']),\n text: z.string().describe('Original text from query'),\n value: z.unknown().describe('Normalized value'),\n confidence: z.number().min(0).max(1).describe('Confidence score'),\n span: z.tuple([z.number(), z.number()]).optional().describe('Character span in query'),\n});\n\n/**\n * Timeframe Detection\n */\nexport const TimeframeSchema = z.object({\n type: z.enum(['absolute', 'relative']),\n start: z.string().optional().describe('Start date (ISO format)'),\n end: z.string().optional().describe('End date (ISO format)'),\n relative: z.object({\n unit: z.enum(['hour', 'day', 'week', 'month', 'quarter', 'year']),\n value: z.number().int(),\n direction: z.enum(['past', 'future', 'current']).default('past'),\n }).optional(),\n text: z.string().describe('Original timeframe text'),\n});\n\n/**\n * NLQ Field Mapping\n * Maps natural language field names to actual object fields\n */\nexport const NLQFieldMappingSchema = z.object({\n naturalLanguage: z.string().describe('NL field name (e.g., \"customer name\")'),\n objectField: z.string().describe('Actual field name (e.g., \"account.name\")'),\n object: z.string().describe('Object name'),\n field: z.string().describe('Field name'),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Query Context\n */\nexport const QueryContextSchema = z.object({\n /** User Information */\n userId: z.string().optional(),\n userRole: z.string().optional(),\n \n /** Current Context */\n currentObject: z.string().optional().describe('Current object being viewed'),\n currentRecordId: z.string().optional().describe('Current record ID'),\n \n /** Conversation History */\n conversationHistory: z.array(z.object({\n query: z.string(),\n timestamp: z.string(),\n intent: QueryIntentSchema.optional(),\n })).optional(),\n \n /** Preferences */\n defaultLimit: z.number().int().default(100),\n timezone: z.string().default('UTC'),\n locale: z.string().default('en-US'),\n});\n\n/**\n * NLQ Parse Result\n */\nexport const NLQParseResultSchema = z.object({\n /** Original Query */\n originalQuery: z.string(),\n \n /** Intent Detection */\n intent: QueryIntentSchema,\n intentConfidence: z.number().min(0).max(1),\n \n /** Entity Recognition */\n entities: z.array(EntitySchema),\n \n /** Object & Field Resolution */\n targetObject: z.string().optional().describe('Primary object to query'),\n fields: z.array(NLQFieldMappingSchema).optional(),\n \n /** Temporal Information */\n timeframe: TimeframeSchema.optional(),\n \n /** Query AST */\n ast: z.record(z.string(), z.unknown()).describe('Generated ObjectQL AST'),\n \n /** Metadata */\n confidence: z.number().min(0).max(1).describe('Overall confidence'),\n ambiguities: z.array(z.object({\n type: z.string(),\n description: z.string(),\n suggestions: z.array(z.string()).optional(),\n })).optional().describe('Detected ambiguities requiring clarification'),\n \n /** Alternative Interpretations */\n alternatives: z.array(z.object({\n interpretation: z.string(),\n confidence: z.number(),\n ast: z.unknown(),\n })).optional(),\n});\n\n/**\n * NLQ Request\n */\nexport const NLQRequestSchema = z.object({\n /** Query */\n query: z.string().describe('Natural language query'),\n \n /** Context */\n context: QueryContextSchema.optional(),\n \n /** Options */\n includeAlternatives: z.boolean().default(false).describe('Include alternative interpretations'),\n maxAlternatives: z.number().int().default(3),\n minConfidence: z.number().min(0).max(1).default(0.5).describe('Minimum confidence threshold'),\n \n /** Execution */\n executeQuery: z.boolean().default(false).describe('Execute query and return results'),\n maxResults: z.number().int().optional().describe('Maximum results to return'),\n});\n\n/**\n * NLQ Response\n */\nexport const NLQResponseSchema = z.object({\n /** Parse Result */\n parseResult: NLQParseResultSchema,\n \n /** Query Results (if executeQuery = true) */\n results: z.array(z.record(z.string(), z.unknown())).optional().describe('Query results'),\n totalCount: z.number().int().optional(),\n \n /** Execution Metadata */\n executionTime: z.number().optional().describe('Execution time in milliseconds'),\n needsClarification: z.boolean().describe('Whether query needs clarification'),\n \n /** Cost Tracking */\n tokens: TokenUsageSchema.optional().describe('Token usage for this query'),\n cost: z.number().nonnegative().optional().describe('Cost for this query in USD'),\n \n /** Suggestions */\n suggestions: z.array(z.string()).optional().describe('Query refinement suggestions'),\n});\n\n/**\n * NLQ Training Example\n */\nexport const NLQTrainingExampleSchema = z.object({\n /** Input */\n query: z.string().describe('Natural language query'),\n context: QueryContextSchema.optional(),\n \n /** Expected Output */\n expectedIntent: QueryIntentSchema,\n expectedObject: z.string().optional(),\n expectedAST: z.record(z.string(), z.unknown()).describe('Expected ObjectQL AST'),\n \n /** Metadata */\n category: z.string().optional().describe('Example category'),\n tags: z.array(z.string()).optional(),\n notes: z.string().optional(),\n});\n\n/**\n * NLQ Model Configuration\n */\nexport const NLQModelConfigSchema = z.object({\n /** Model */\n modelId: z.string().describe('Model from registry'),\n \n /** Prompt Engineering */\n systemPrompt: z.string().optional().describe('System prompt override'),\n includeSchema: z.boolean().default(true).describe('Include object schema in prompt'),\n includeExamples: z.boolean().default(true).describe('Include examples in prompt'),\n \n /** Intent Detection */\n enableIntentDetection: z.boolean().default(true),\n intentThreshold: z.number().min(0).max(1).default(0.7),\n \n /** Entity Recognition */\n enableEntityRecognition: z.boolean().default(true),\n entityRecognitionModel: z.string().optional(),\n \n /** Field Resolution */\n enableFuzzyMatching: z.boolean().default(true).describe('Fuzzy match field names'),\n fuzzyMatchThreshold: z.number().min(0).max(1).default(0.8),\n \n /** Temporal Processing */\n enableTimeframeDetection: z.boolean().default(true),\n defaultTimeframe: z.string().optional().describe('Default timeframe if not specified'),\n \n /** Performance */\n enableCaching: z.boolean().default(true),\n cacheTTL: z.number().int().default(3600).describe('Cache TTL in seconds'),\n});\n\n/**\n * NLQ Analytics\n */\nexport const NLQAnalyticsSchema = z.object({\n /** Query Metrics */\n totalQueries: z.number().int(),\n successfulQueries: z.number().int(),\n failedQueries: z.number().int(),\n averageConfidence: z.number().min(0).max(1),\n \n /** Intent Distribution */\n intentDistribution: z.record(z.string(), z.number().int()).describe('Count by intent type'),\n \n /** Common Patterns */\n topQueries: z.array(z.object({\n query: z.string(),\n count: z.number().int(),\n averageConfidence: z.number(),\n })),\n \n /** Performance */\n averageParseTime: z.number().describe('Average parse time in milliseconds'),\n averageExecutionTime: z.number().optional(),\n \n /** Issues */\n lowConfidenceQueries: z.array(z.object({\n query: z.string(),\n confidence: z.number(),\n timestamp: z.string().datetime(),\n })),\n \n /** Timeframe */\n startDate: z.string().datetime().describe('ISO timestamp'),\n endDate: z.string().datetime().describe('ISO timestamp'),\n});\n\n/**\n * Field Synonym Configuration\n */\nexport const FieldSynonymConfigSchema = z.object({\n object: z.string().describe('Object name'),\n field: z.string().describe('Field name'),\n synonyms: z.array(z.string()).describe('Natural language synonyms'),\n examples: z.array(z.string()).optional().describe('Example queries using synonyms'),\n});\n\n/**\n * Query Template\n */\nexport const QueryTemplateSchema = z.object({\n id: z.string(),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Template name (snake_case)'),\n label: z.string(),\n \n /** Template */\n pattern: z.string().describe('Query pattern with placeholders'),\n variables: z.array(z.object({\n name: z.string(),\n type: z.enum(['object', 'field', 'value', 'timeframe']),\n required: z.boolean().default(false),\n })),\n \n /** Generated AST */\n astTemplate: z.record(z.string(), z.unknown()).describe('AST template with variable placeholders'),\n \n /** Metadata */\n category: z.string().optional(),\n examples: z.array(z.string()).optional(),\n tags: z.array(z.string()).optional(),\n});\n\n// Type exports\nexport type QueryIntent = z.infer;\nexport type Entity = z.infer;\nexport type Timeframe = z.infer;\nexport type NLQFieldMapping = z.infer;\nexport type QueryContext = z.infer;\nexport type NLQParseResult = z.infer;\nexport type NLQRequest = z.infer;\nexport type NLQResponse = z.infer;\nexport type NLQTrainingExample = z.infer;\nexport type NLQModelConfig = z.infer;\nexport type NLQAnalytics = z.infer;\nexport type FieldSynonymConfig = z.infer;\nexport type QueryTemplate = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * AI Agentic Orchestration Protocol\n * \n * Defines intelligent orchestration flows where AI Agents leverage cognitive skills\n * to automate business processes with dynamic reasoning, planning, and execution.\n * \n * Distinction from Standard Workflows:\n * - Standard Workflow: Deterministic (If X then Y). defined in src/data/workflow.zod.ts\n * - AI Orchestration: Probabilistic & Agentic (Goal -> Plan -> Execute).\n * \n * Use Cases:\n * - Complex Support Triage (Analyze sentiment + intent -> Draft response -> Route)\n * - Intelligent Document Processing (OCR -> Extract Entities -> Validate -> Entry)\n * - Research Agent (Search Web -> Summarize -> Generate Report)\n */\n\n/**\n * Orchestration Trigger Types\n * Defines when an AI Agentic Flow should be initiated\n */\nexport const AIOrchestrationTriggerSchema = z.enum([\n 'record_created', // When a new record is created\n 'record_updated', // When a record is updated\n 'field_changed', // When specific field(s) change\n 'scheduled', // Time-based trigger (cron)\n 'manual', // User-initiated trigger\n 'webhook', // External system trigger\n 'batch', // Batch processing trigger\n]);\n\n/**\n * AI Task Types\n * Cognitive operations that can be performed by AI\n */\nexport const AITaskTypeSchema = z.enum([\n 'classify', // Categorize content into predefined classes\n 'extract', // Extract structured data from unstructured content\n 'summarize', // Generate concise summaries of text\n 'generate', // Generate new content (text, code, etc.)\n 'predict', // Make predictions based on historical data\n 'translate', // Translate text between languages\n 'sentiment', // Analyze sentiment (positive, negative, neutral)\n 'entity_recognition', // Identify named entities (people, places, etc.)\n 'anomaly_detection', // Detect outliers or unusual patterns\n 'recommendation', // Recommend items or actions\n]);\n\n/**\n * AI Task Configuration\n * Individual AI task within a workflow\n */\nexport const AITaskSchema = z.object({\n /** Task Identity */\n id: z.string().optional().describe('Optional task ID for referencing'),\n name: z.string().describe('Human-readable task name'),\n type: AITaskTypeSchema,\n \n /** Model Configuration */\n model: z.string().optional().describe('Model ID from registry (uses default if not specified)'),\n promptTemplate: z.string().optional().describe('Prompt template ID for this task'),\n \n /** Input Configuration */\n inputFields: z.array(z.string()).describe('Source fields to process (e.g., [\"description\", \"comments\"])'),\n inputSchema: z.record(z.string(), z.unknown()).optional().describe('Validation schema for inputs'),\n inputContext: z.record(z.string(), z.unknown()).optional().describe('Additional context for the AI model'),\n \n /** Output Configuration */\n outputField: z.string().describe('Target field to store the result'),\n outputSchema: z.record(z.string(), z.unknown()).optional().describe('Validation schema for output'),\n outputFormat: z.enum(['text', 'json', 'number', 'boolean', 'array']).optional().default('text'),\n \n /** Classification-specific options */\n classes: z.array(z.string()).optional().describe('Valid classes for classification tasks'),\n multiClass: z.boolean().optional().default(false).describe('Allow multiple classes to be selected'),\n \n /** Extraction-specific options */\n extractionSchema: z.record(z.string(), z.unknown()).optional().describe('JSON schema for structured extraction'),\n \n /** Generation-specific options */\n maxLength: z.number().optional().describe('Maximum length for generated content'),\n temperature: z.number().min(0).max(2).optional().describe('Model temperature override'),\n \n /** Error Handling */\n fallbackValue: z.unknown().optional().describe('Fallback value if AI task fails'),\n retryAttempts: z.number().int().min(0).max(5).optional().default(1),\n \n /** Conditional Execution */\n condition: z.string().optional().describe('Formula condition - task only runs if TRUE'),\n \n /** Task Metadata */\n description: z.string().optional(),\n active: z.boolean().optional().default(true),\n});\n\n/**\n * Workflow Field Condition\n * Specifies which field changes trigger the workflow\n */\nexport const WorkflowFieldConditionSchema = z.object({\n field: z.string().describe('Field name to monitor'),\n operator: z.enum(['changed', 'changed_to', 'changed_from', 'is', 'is_not']).optional().default('changed'),\n value: z.unknown().optional().describe('Value to compare against (for changed_to/changed_from/is/is_not)'),\n});\n\n/**\n * Workflow Schedule Configuration\n * For time-based workflow execution\n */\nexport const WorkflowScheduleSchema = z.object({\n type: z.enum(['cron', 'interval', 'daily', 'weekly', 'monthly']).default('cron'),\n cron: z.string().optional().describe('Cron expression (required if type is \"cron\")'),\n interval: z.number().optional().describe('Interval in minutes (required if type is \"interval\")'),\n time: z.string().optional().describe('Time of day for daily schedules (HH:MM format)'),\n dayOfWeek: z.number().int().min(0).max(6).optional().describe('Day of week for weekly (0=Sunday)'),\n dayOfMonth: z.number().int().min(1).max(31).optional().describe('Day of month for monthly'),\n timezone: z.string().optional().default('UTC'),\n});\n\n/**\n * Post-Processing Action\n * Actions to execute after AI tasks complete\n */\nexport const PostProcessingActionSchema = z.object({\n type: z.enum(['field_update', 'send_email', 'create_record', 'update_related', 'trigger_flow', 'webhook']),\n name: z.string().describe('Action name'),\n config: z.record(z.string(), z.unknown()).describe('Action-specific configuration'),\n condition: z.string().optional().describe('Execute only if condition is TRUE'),\n});\n\n/**\n * AI Agentic Orchestration Schema\n * Complete workflow definition with AI-powered tasks\n */\nexport const AIOrchestrationSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Orchestration unique identifier (snake_case)'),\n label: z.string().describe('Display name'),\n description: z.string().optional(),\n \n /** Target Object */\n objectName: z.string().describe('Target object for this orchestration'),\n \n /** Trigger Configuration */\n trigger: AIOrchestrationTriggerSchema,\n \n /** Trigger-specific configuration */\n fieldConditions: z.array(WorkflowFieldConditionSchema).optional().describe('Fields to monitor (for field_changed trigger)'),\n schedule: WorkflowScheduleSchema.optional().describe('Schedule configuration (for scheduled trigger)'),\n webhookConfig: z.object({\n secret: z.string().optional().describe('Webhook verification secret'),\n headers: z.record(z.string(), z.string()).optional().describe('Expected headers'),\n }).optional().describe('Webhook configuration (for webhook trigger)'),\n \n /** Entry Criteria */\n entryCriteria: z.string().optional().describe('Formula condition - workflow only runs if TRUE'),\n \n /** AI Tasks */\n aiTasks: z.array(AITaskSchema).describe('AI tasks to execute in sequence'),\n \n /** Post-Processing */\n postActions: z.array(PostProcessingActionSchema).optional().describe('Actions after AI tasks complete'),\n \n /** Execution Options */\n executionMode: z.enum(['sequential', 'parallel']).optional().default('sequential').describe('How to execute multiple AI tasks'),\n stopOnError: z.boolean().optional().default(false).describe('Stop workflow if any task fails'),\n \n /** Performance & Limits */\n timeout: z.number().optional().describe('Maximum execution time in seconds'),\n priority: z.enum(['low', 'normal', 'high', 'critical']).optional().default('normal'),\n \n /** Monitoring & Logging */\n enableLogging: z.boolean().optional().default(true),\n enableMetrics: z.boolean().optional().default(true),\n notifyOnFailure: z.array(z.string()).optional().describe('User IDs to notify on failure'),\n \n /** Status */\n active: z.boolean().optional().default(true),\n version: z.string().optional().default('1.0.0'),\n \n /** Metadata */\n tags: z.array(z.string()).optional(),\n category: z.string().optional().describe('Workflow category (e.g., \"support\", \"sales\", \"hr\")'),\n owner: z.string().optional().describe('User ID of workflow owner'),\n createdAt: z.string().datetime().optional().describe('ISO timestamp'),\n updatedAt: z.string().datetime().optional().describe('ISO timestamp'),\n});\n\n/**\n * Batch AI Orchestration Execution Request\n * For processing multiple records at once\n */\nexport const BatchAIOrchestrationExecutionSchema = z.object({\n workflowName: z.string().describe('Orchestration to execute'),\n recordIds: z.array(z.string()).describe('Records to process'),\n batchSize: z.number().int().min(1).max(1000).optional().default(10),\n parallelism: z.number().int().min(1).max(10).optional().default(3),\n priority: z.enum(['low', 'normal', 'high']).optional().default('normal'),\n});\n\n/**\n * AI Orchestration Execution Result\n * Result of a single execution\n */\nexport const AIOrchestrationExecutionResultSchema = z.object({\n workflowName: z.string(),\n recordId: z.string(),\n status: z.enum(['success', 'partial_success', 'failed', 'skipped']),\n executionTime: z.number().describe('Execution time in milliseconds'),\n tasksExecuted: z.number().int().describe('Number of tasks executed'),\n tasksSucceeded: z.number().int().describe('Number of tasks succeeded'),\n tasksFailed: z.number().int().describe('Number of tasks failed'),\n taskResults: z.array(z.object({\n taskId: z.string().optional(),\n taskName: z.string(),\n status: z.enum(['success', 'failed', 'skipped']),\n output: z.unknown().optional(),\n error: z.string().optional(),\n executionTime: z.number().optional().describe('Task execution time in milliseconds'),\n modelUsed: z.string().optional(),\n tokensUsed: z.number().optional(),\n })).optional(),\n tokens: TokenUsageSchema.optional().describe('Total token usage for this execution'),\n cost: z.number().nonnegative().optional().describe('Total cost for this execution in USD'),\n error: z.string().optional(),\n startedAt: z.string().datetime().describe('ISO timestamp'),\n completedAt: z.string().datetime().optional().describe('ISO timestamp'),\n});\n\n// Type exports\nexport type AIOrchestrationTrigger = z.infer;\nexport type AITaskType = z.infer;\nexport type AITask = z.infer;\nexport type WorkflowFieldCondition = z.infer;\nexport type WorkflowSchedule = z.infer;\nexport type PostProcessingAction = z.infer;\nexport type AIOrchestration = z.infer;\nexport type BatchAIOrchestrationExecution = z.infer;\nexport type AIOrchestrationExecutionResult = z.infer;\n\n// ==========================================\n// Multi-Agent Coordination\n// ==========================================\n\n/**\n * Multi-Agent Communication Protocol\n * \n * Defines how agents communicate with each other in a group.\n */\nexport const AgentCommunicationProtocolSchema = z.enum([\n 'message_passing', // Direct message exchange between agents\n 'shared_memory', // Agents read/write to a shared context store\n 'blackboard', // Centralized workspace agents contribute to\n]);\n\nexport type AgentCommunicationProtocol = z.infer;\n\n/**\n * Agent Role in a Multi-Agent Group\n * \n * Defines the function an agent plays within a coordinated group.\n */\nexport const AgentGroupRoleSchema = z.enum([\n 'coordinator', // Orchestrates other agents and delegates tasks\n 'specialist', // Domain expert performing specific tasks\n 'critic', // Reviews and validates other agents' outputs\n 'executor', // Carries out actions in the real world (APIs, DB writes)\n]);\n\nexport type AgentGroupRole = z.infer;\n\n/**\n * Agent Group Member Schema\n * \n * Configuration for a single agent within a multi-agent group.\n */\nexport const AgentGroupMemberSchema = z.object({\n /** Reference to agent name (must match an existing AgentSchema name) */\n agentId: z.string().describe('Agent identifier (reference to AgentSchema.name)'),\n\n /** Role this agent plays in the group */\n role: AgentGroupRoleSchema.describe('Agent role within the group'),\n\n /** Capabilities / skills this agent contributes */\n capabilities: z.array(z.string()).optional().describe('List of capabilities this agent contributes'),\n\n /** Dependencies on other agents in the group */\n dependencies: z.array(z.string()).optional().describe('Agent IDs this agent depends on for input'),\n\n /** Priority order within the group (lower = higher priority) */\n priority: z.number().int().min(0).optional().describe('Execution priority (0 = highest)'),\n});\n\nexport type AgentGroupMember = z.infer;\n\n/**\n * Multi-Agent Group Schema\n * \n * Defines a coordinated group of agents that collaborate to solve\n * complex problems exceeding the capability of a single agent.\n * \n * @example Multi-Agent Code Review Group\n * ```typescript\n * const codeReviewGroup: MultiAgentGroup = {\n * name: 'code_review_team',\n * label: 'Code Review Team',\n * strategy: 'sequential',\n * agents: [\n * { agentId: 'code_analyzer', role: 'specialist', capabilities: ['static_analysis'] },\n * { agentId: 'security_scanner', role: 'specialist', capabilities: ['vulnerability_detection'] },\n * { agentId: 'code_reviewer', role: 'critic', capabilities: ['code_quality'] },\n * { agentId: 'merge_agent', role: 'executor', capabilities: ['git_operations'], dependencies: ['code_reviewer'] },\n * ],\n * communication: { protocol: 'blackboard' },\n * conflictResolution: 'voting',\n * };\n * ```\n */\nexport const MultiAgentGroupSchema = z.object({\n /** Group identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Group unique identifier (snake_case)'),\n label: z.string().describe('Group display name'),\n description: z.string().optional(),\n\n /** Orchestration strategy */\n strategy: z.enum([\n 'sequential', // Agents execute one after another\n 'parallel', // Agents execute concurrently\n 'debate', // Agents propose, argue, and converge on a solution\n 'hierarchical', // Coordinator delegates to specialists\n 'swarm', // Agents self-organize dynamically\n ]).describe('Multi-agent orchestration strategy'),\n\n /** Agents in this group */\n agents: z.array(AgentGroupMemberSchema).min(2).describe('Agent members (minimum 2)'),\n\n /** Inter-agent communication */\n communication: z.object({\n /** Communication protocol */\n protocol: AgentCommunicationProtocolSchema.describe('Inter-agent communication protocol'),\n\n /** Message queue name (for message_passing) */\n messageQueue: z.string().optional().describe('Message queue identifier for async communication'),\n\n /** Maximum rounds of communication */\n maxRounds: z.number().int().min(1).optional().describe('Maximum communication rounds before forced termination'),\n }).describe('Communication configuration'),\n\n /** Conflict resolution strategy */\n conflictResolution: z.enum([\n 'voting', // Majority vote decides\n 'priorityBased', // Highest-priority agent decides\n 'consensusBased', // All agents must agree\n 'coordinatorDecides', // Coordinator agent has final say\n ]).optional().describe('How conflicts between agents are resolved'),\n\n /** Timeout for the entire group execution in seconds */\n timeout: z.number().int().min(1).optional().describe('Maximum execution time in seconds for the group'),\n\n /** Whether the group is active */\n active: z.boolean().default(true).describe('Whether this agent group is active'),\n});\n\nexport type MultiAgentGroup = z.infer;\nexport type MultiAgentGroupInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * Predictive Analytics Protocol\n * \n * Defines predictive models and machine learning configurations for\n * data-driven decision making and forecasting in ObjectStack applications.\n * \n * Use Cases:\n * - Lead scoring and conversion prediction\n * - Customer churn prediction\n * - Sales forecasting\n * - Demand forecasting\n * - Anomaly detection in operational data\n * - Customer segmentation and clustering\n * - Price optimization\n * - Recommendation systems\n */\n\n/**\n * Predictive Model Types\n */\nexport const PredictiveModelTypeSchema = z.enum([\n 'classification', // Binary or multi-class classification\n 'regression', // Numerical prediction\n 'clustering', // Unsupervised grouping\n 'forecasting', // Time-series prediction\n 'anomaly_detection', // Outlier detection\n 'recommendation', // Item or action recommendation\n 'ranking', // Ordering items by relevance\n]);\n\n/**\n * Model Feature Definition\n * Describes an input feature for a predictive model\n */\nexport const ModelFeatureSchema = z.object({\n /** Feature Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Feature name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n \n /** Data Source */\n field: z.string().describe('Source field name'),\n object: z.string().optional().describe('Source object (if different from target)'),\n \n /** Feature Type */\n dataType: z.enum(['numeric', 'categorical', 'text', 'datetime', 'boolean']).describe('Feature data type'),\n \n /** Feature Engineering */\n transformation: z.enum([\n 'none',\n 'normalize', // Normalize to 0-1 range\n 'standardize', // Z-score standardization\n 'one_hot_encode', // One-hot encoding for categorical\n 'label_encode', // Label encoding for categorical\n 'log_transform', // Logarithmic transformation\n 'binning', // Discretize continuous values\n 'embedding', // Text/categorical embedding\n ]).optional().default('none'),\n \n /** Configuration */\n required: z.boolean().optional().default(true),\n defaultValue: z.unknown().optional(),\n \n /** Metadata */\n description: z.string().optional(),\n importance: z.number().optional().describe('Feature importance score (0-1)'),\n});\n\n/**\n * Model Hyperparameters\n * Configuration specific to model algorithms\n */\nexport const HyperparametersSchema = z.object({\n /** General Parameters */\n learningRate: z.number().optional().describe('Learning rate for training'),\n epochs: z.number().int().optional().describe('Number of training epochs'),\n batchSize: z.number().int().optional().describe('Training batch size'),\n \n /** Tree-based Models (Random Forest, XGBoost, etc.) */\n maxDepth: z.number().int().optional().describe('Maximum tree depth'),\n numTrees: z.number().int().optional().describe('Number of trees in ensemble'),\n minSamplesSplit: z.number().int().optional().describe('Minimum samples to split node'),\n minSamplesLeaf: z.number().int().optional().describe('Minimum samples in leaf node'),\n \n /** Neural Networks */\n hiddenLayers: z.array(z.number().int()).optional().describe('Hidden layer sizes'),\n activation: z.string().optional().describe('Activation function'),\n dropout: z.number().optional().describe('Dropout rate'),\n \n /** Regularization */\n l1Regularization: z.number().optional().describe('L1 regularization strength'),\n l2Regularization: z.number().optional().describe('L2 regularization strength'),\n \n /** Clustering */\n numClusters: z.number().int().optional().describe('Number of clusters (k-means, etc.)'),\n \n /** Time Series */\n seasonalPeriod: z.number().int().optional().describe('Seasonal period for time series'),\n forecastHorizon: z.number().int().optional().describe('Number of periods to forecast'),\n \n /** Additional custom parameters */\n custom: z.record(z.string(), z.unknown()).optional().describe('Algorithm-specific parameters'),\n});\n\n/**\n * Model Training Configuration\n */\nexport const TrainingConfigSchema = z.object({\n /** Data Split */\n trainingDataRatio: z.number().min(0).max(1).optional().default(0.8).describe('Proportion of data for training'),\n validationDataRatio: z.number().min(0).max(1).optional().default(0.1).describe('Proportion for validation'),\n testDataRatio: z.number().min(0).max(1).optional().default(0.1).describe('Proportion for testing'),\n \n /** Data Filtering */\n dataFilter: z.string().optional().describe('Formula to filter training data'),\n minRecords: z.number().int().optional().default(100).describe('Minimum records required'),\n maxRecords: z.number().int().optional().describe('Maximum records to use'),\n \n /** Training Strategy */\n strategy: z.enum(['full', 'incremental', 'online', 'transfer_learning']).optional().default('full'),\n crossValidation: z.boolean().optional().default(true),\n folds: z.number().int().min(2).max(10).optional().default(5).describe('Cross-validation folds'),\n \n /** Early Stopping */\n earlyStoppingEnabled: z.boolean().optional().default(true),\n earlyStoppingPatience: z.number().int().optional().default(10).describe('Epochs without improvement before stopping'),\n \n /** Resource Limits */\n maxTrainingTime: z.number().optional().describe('Maximum training time in seconds'),\n gpuEnabled: z.boolean().optional().default(false),\n \n /** Reproducibility */\n randomSeed: z.number().int().optional().describe('Random seed for reproducibility'),\n}).superRefine((data, ctx) => {\n if (data.trainingDataRatio && data.validationDataRatio && data.testDataRatio) {\n const sum = data.trainingDataRatio + data.validationDataRatio + data.testDataRatio;\n if (Math.abs(sum - 1) > 0.01) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Data split ratios must sum to 1. Current sum: ${sum}`,\n path: ['trainingDataRatio'],\n });\n }\n }\n});\n\n/**\n * Model Evaluation Metrics\n */\nexport const EvaluationMetricsSchema = z.object({\n /** Classification Metrics */\n accuracy: z.number().optional(),\n precision: z.number().optional(),\n recall: z.number().optional(),\n f1Score: z.number().optional(),\n auc: z.number().optional().describe('Area Under ROC Curve'),\n \n /** Regression Metrics */\n mse: z.number().optional().describe('Mean Squared Error'),\n rmse: z.number().optional().describe('Root Mean Squared Error'),\n mae: z.number().optional().describe('Mean Absolute Error'),\n r2Score: z.number().optional().describe('R-squared score'),\n \n /** Clustering Metrics */\n silhouetteScore: z.number().optional(),\n daviesBouldinIndex: z.number().optional(),\n \n /** Time Series Metrics */\n mape: z.number().optional().describe('Mean Absolute Percentage Error'),\n smape: z.number().optional().describe('Symmetric MAPE'),\n \n /** Additional Metrics */\n custom: z.record(z.string(), z.number()).optional(),\n});\n\n/**\n * Predictive Model Schema\n * Complete definition of a predictive model\n */\nexport const PredictiveModelSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Model unique identifier (snake_case)'),\n label: z.string().describe('Model display name'),\n description: z.string().optional(),\n \n /** Model Type */\n type: PredictiveModelTypeSchema,\n algorithm: z.string().optional().describe('Specific algorithm (e.g., \"random_forest\", \"xgboost\", \"lstm\")'),\n \n /** Target Object & Field */\n objectName: z.string().describe('Target object for predictions'),\n target: z.string().describe('Target field to predict'),\n targetType: z.enum(['numeric', 'categorical', 'binary']).optional().describe('Target field type'),\n \n /** Features */\n features: z.array(ModelFeatureSchema).describe('Input features for the model'),\n \n /** Hyperparameters */\n hyperparameters: HyperparametersSchema.optional(),\n \n /** Training Configuration */\n training: TrainingConfigSchema.optional(),\n \n /** Model Performance */\n metrics: EvaluationMetricsSchema.optional().describe('Evaluation metrics from last training'),\n \n /** Deployment */\n deploymentStatus: z.enum(['draft', 'training', 'trained', 'deployed', 'deprecated']).optional().default('draft'),\n version: z.string().optional().default('1.0.0'),\n \n /** Prediction Configuration */\n predictionField: z.string().optional().describe('Field to store predictions'),\n confidenceField: z.string().optional().describe('Field to store confidence scores'),\n updateTrigger: z.enum(['on_create', 'on_update', 'manual', 'scheduled']).optional().default('on_create'),\n \n /** Retraining */\n autoRetrain: z.boolean().optional().default(false),\n retrainSchedule: z.string().optional().describe('Cron expression for auto-retraining'),\n retrainThreshold: z.number().optional().describe('Performance threshold to trigger retraining'),\n \n /** Explainability */\n enableExplainability: z.boolean().optional().default(false).describe('Generate feature importance & explanations'),\n \n /** Monitoring */\n enableMonitoring: z.boolean().optional().default(true),\n alertOnDrift: z.boolean().optional().default(true).describe('Alert when model drift is detected'),\n \n /** Access Control */\n active: z.boolean().optional().default(true),\n owner: z.string().optional().describe('User ID of model owner'),\n permissions: z.array(z.string()).optional().describe('User/group IDs with access'),\n \n /** Metadata */\n tags: z.array(z.string()).optional(),\n category: z.string().optional().describe('Model category (e.g., \"sales\", \"marketing\", \"operations\")'),\n lastTrainedAt: z.string().datetime().optional().describe('ISO timestamp'),\n createdAt: z.string().datetime().optional().describe('ISO timestamp'),\n updatedAt: z.string().datetime().optional().describe('ISO timestamp'),\n});\n\n/**\n * Prediction Request\n * Request for making predictions using a trained model\n */\nexport const PredictionRequestSchema = z.object({\n modelName: z.string().describe('Model to use for prediction'),\n recordIds: z.array(z.string()).optional().describe('Specific records to predict (if not provided, uses all)'),\n inputData: z.record(z.string(), z.unknown()).optional().describe('Direct input data (alternative to recordIds)'),\n returnConfidence: z.boolean().optional().default(true),\n returnExplanation: z.boolean().optional().default(false),\n});\n\n/**\n * Prediction Result\n * Result of a prediction request\n */\nexport const PredictionResultSchema = z.object({\n modelName: z.string(),\n modelVersion: z.string(),\n recordId: z.string().optional(),\n prediction: z.unknown().describe('The predicted value'),\n confidence: z.number().optional().describe('Confidence score (0-1)'),\n probabilities: z.record(z.string(), z.number()).optional().describe('Class probabilities (for classification)'),\n explanation: z.object({\n topFeatures: z.array(z.object({\n feature: z.string(),\n importance: z.number(),\n value: z.unknown(),\n })).optional(),\n reasoning: z.string().optional(),\n }).optional(),\n tokens: TokenUsageSchema.optional().describe('Token usage for this prediction (if AI-powered)'),\n cost: z.number().nonnegative().optional().describe('Cost for this prediction in USD'),\n metadata: z.object({\n executionTime: z.number().optional().describe('Execution time in milliseconds'),\n timestamp: z.string().datetime().optional().describe('ISO timestamp'),\n }).optional(),\n});\n\n/**\n * Model Drift Detection\n * Monitoring for model performance degradation\n */\nexport const ModelDriftSchema = z.object({\n modelName: z.string(),\n driftType: z.enum(['feature_drift', 'prediction_drift', 'performance_drift']),\n severity: z.enum(['low', 'medium', 'high', 'critical']),\n detectedAt: z.string().datetime().describe('ISO timestamp'),\n metrics: z.object({\n driftScore: z.number().describe('Drift magnitude (0-1)'),\n affectedFeatures: z.array(z.string()).optional(),\n performanceChange: z.number().optional().describe('Change in performance metric'),\n }),\n recommendation: z.string().optional(),\n autoRetrainTriggered: z.boolean().optional().default(false),\n});\n\n// Type exports\nexport type PredictiveModelType = z.infer;\nexport type ModelFeature = z.infer;\nexport type Hyperparameters = z.infer;\nexport type TrainingConfig = z.infer;\nexport type EvaluationMetrics = z.infer;\nexport type PredictiveModel = z.infer;\nexport type PredictionRequest = z.infer;\nexport type PredictionResult = z.infer;\nexport type ModelDrift = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { TokenUsageSchema } from './cost.zod';\n\n/**\n * AI Conversation Memory Protocol\n * \n * Multi-turn AI conversations with token budget management.\n * Enables context preservation, conversation history, and token optimization.\n */\n\n/**\n * Message Role\n */\nexport const MessageRoleSchema = z.enum([\n 'system',\n 'user',\n 'assistant',\n 'function',\n 'tool',\n]);\n\n/**\n * Message Content Type\n */\nexport const MessageContentTypeSchema = z.enum([\n 'text',\n 'image',\n 'file',\n 'code',\n 'structured',\n]);\n\n/**\n * Message Content - Discriminated Union\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n text: z.string().describe('Text content'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n imageUrl: z.string().url().describe('Image URL'),\n detail: z.enum(['low', 'high', 'auto']).optional().default('auto'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const FileContentSchema = z.object({\n type: z.literal('file'),\n fileUrl: z.string().url().describe('File attachment URL'),\n mimeType: z.string().describe('MIME type'),\n fileName: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const CodeContentSchema = z.object({\n type: z.literal('code'),\n text: z.string().describe('Code snippet'),\n language: z.string().optional().default('text'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const MessageContentSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n FileContentSchema,\n CodeContentSchema\n]);\n\n/**\n * Function Call\n */\nexport const FunctionCallSchema = z.object({\n name: z.string().describe('Function name'),\n arguments: z.string().describe('JSON string of function arguments'),\n result: z.string().optional().describe('Function execution result'),\n});\n\n/**\n * Tool Call\n */\nexport const ToolCallSchema = z.object({\n id: z.string().describe('Tool call ID'),\n type: z.enum(['function']).default('function'),\n function: FunctionCallSchema,\n});\n\n/**\n * Conversation Message\n */\nexport const ConversationMessageSchema = z.object({\n /** Identity */\n id: z.string().describe('Unique message ID'),\n timestamp: z.string().datetime().describe('ISO 8601 timestamp'),\n \n /** Content */\n role: MessageRoleSchema,\n content: z.array(MessageContentSchema).describe('Message content (multimodal array)'),\n \n /** Function/Tool Calls */\n functionCall: FunctionCallSchema.optional().describe('Legacy function call'),\n toolCalls: z.array(ToolCallSchema).optional().describe('Tool calls'),\n toolCallId: z.string().optional().describe('Tool call ID this message responds to'),\n \n /** Metadata */\n name: z.string().optional().describe('Name of the function/user'),\n tokens: TokenUsageSchema.optional().describe('Token usage for this message'),\n cost: z.number().nonnegative().optional().describe('Cost for this message in USD'),\n \n /** Context Management */\n pinned: z.boolean().optional().default(false).describe('Prevent removal during pruning'),\n importance: z.number().min(0).max(1).optional().describe('Importance score for pruning'),\n embedding: z.array(z.number()).optional().describe('Vector embedding for semantic search'),\n \n /** Annotations */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Token Budget Strategy\n */\nexport const TokenBudgetStrategySchema = z.enum([\n 'fifo', // First-in-first-out (oldest messages dropped)\n 'importance', // Drop by importance score\n 'semantic', // Keep semantically relevant messages\n 'sliding_window', // Fixed window of recent messages\n 'summary', // Summarize old context\n]);\n\n/**\n * Token Budget Configuration\n */\nexport const TokenBudgetConfigSchema = z.object({\n /** Budget Limits */\n maxTokens: z.number().int().positive().describe('Maximum total tokens'),\n maxPromptTokens: z.number().int().positive().optional().describe('Max tokens for prompt'),\n maxCompletionTokens: z.number().int().positive().optional().describe('Max tokens for completion'),\n \n /** Buffer & Reserves */\n reserveTokens: z.number().int().nonnegative().default(500).describe('Reserve tokens for system messages'),\n bufferPercentage: z.number().min(0).max(1).default(0.1).describe('Buffer percentage (0.1 = 10%)'),\n \n /** Pruning Strategy */\n strategy: TokenBudgetStrategySchema.default('sliding_window'),\n \n /** Strategy-Specific Options */\n slidingWindowSize: z.number().int().positive().optional().describe('Number of recent messages to keep'),\n minImportanceScore: z.number().min(0).max(1).optional().describe('Minimum importance to keep'),\n semanticThreshold: z.number().min(0).max(1).optional().describe('Semantic similarity threshold'),\n \n /** Summarization */\n enableSummarization: z.boolean().default(false).describe('Enable context summarization'),\n summarizationThreshold: z.number().int().positive().optional().describe('Trigger summarization at N tokens'),\n summaryModel: z.string().optional().describe('Model ID for summarization'),\n \n /** Monitoring */\n warnThreshold: z.number().min(0).max(1).default(0.8).describe('Warn at % of budget (0.8 = 80%)'),\n});\n\n/**\n * Token Usage Stats\n */\nexport const TokenUsageStatsSchema = z.object({\n promptTokens: z.number().int().nonnegative().default(0),\n completionTokens: z.number().int().nonnegative().default(0),\n totalTokens: z.number().int().nonnegative().default(0),\n \n /** Budget Status */\n budgetLimit: z.number().int().positive(),\n budgetUsed: z.number().int().nonnegative().default(0),\n budgetRemaining: z.number().int().nonnegative(),\n budgetPercentage: z.number().min(0).max(1).describe('Usage as percentage of budget'),\n \n /** Message Stats */\n messageCount: z.number().int().nonnegative().default(0),\n prunedMessageCount: z.number().int().nonnegative().default(0),\n summarizedMessageCount: z.number().int().nonnegative().default(0),\n});\n\n/**\n * Conversation Context\n */\nexport const ConversationContextSchema = z.object({\n /** Identity */\n sessionId: z.string().describe('Conversation session ID'),\n userId: z.string().optional().describe('User identifier'),\n agentId: z.string().optional().describe('AI agent identifier'),\n \n /** Context Data */\n object: z.string().optional().describe('Related object (e.g., \"case\", \"project\")'),\n recordId: z.string().optional().describe('Related record ID'),\n scope: z.record(z.string(), z.unknown()).optional().describe('Additional context scope'),\n \n /** System Instructions */\n systemMessage: z.string().optional().describe('System prompt/instructions'),\n \n /** Metadata */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Conversation Session\n */\nexport const ConversationSessionSchema = z.object({\n /** Identity */\n id: z.string().describe('Unique session ID'),\n name: z.string().optional().describe('Session name/title'),\n \n /** Configuration */\n context: ConversationContextSchema,\n modelId: z.string().optional().describe('AI model ID'),\n tokenBudget: TokenBudgetConfigSchema,\n \n /** Messages */\n messages: z.array(ConversationMessageSchema).default([]),\n \n /** Token Tracking */\n tokens: TokenUsageStatsSchema.optional(),\n totalTokens: TokenUsageSchema.optional().describe('Total tokens across all messages'),\n totalCost: z.number().nonnegative().optional().describe('Total cost for this session in USD'),\n \n /** Session Status */\n status: z.enum(['active', 'paused', 'completed', 'archived']).default('active'),\n \n /** Timestamps */\n createdAt: z.string().datetime().describe('ISO 8601 timestamp'),\n updatedAt: z.string().datetime().describe('ISO 8601 timestamp'),\n expiresAt: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Conversation Summary\n */\nexport const ConversationSummarySchema = z.object({\n /** Summary Content */\n summary: z.string().describe('Conversation summary'),\n keyPoints: z.array(z.string()).optional().describe('Key discussion points'),\n \n /** Token Savings */\n originalTokens: z.number().int().nonnegative().describe('Original token count'),\n summaryTokens: z.number().int().nonnegative().describe('Summary token count'),\n tokensSaved: z.number().int().nonnegative().describe('Tokens saved'),\n \n /** Source Messages */\n messageRange: z.object({\n startIndex: z.number().int().nonnegative(),\n endIndex: z.number().int().nonnegative(),\n }).describe('Range of messages summarized'),\n \n /** Metadata */\n generatedAt: z.string().datetime().describe('ISO 8601 timestamp'),\n modelId: z.string().optional().describe('Model used for summarization'),\n});\n\n/**\n * Message Pruning Event\n */\nexport const MessagePruningEventSchema = z.object({\n /** Event Details */\n timestamp: z.string().datetime().describe('Event timestamp'),\n /** Pruned Messages */\n prunedMessages: z.array(z.object({\n messageId: z.string(),\n role: MessageRoleSchema,\n tokens: z.number().int().nonnegative(),\n importance: z.number().min(0).max(1).optional(),\n })),\n \n /** Impact */\n tokensFreed: z.number().int().nonnegative(),\n messagesRemoved: z.number().int().nonnegative(),\n \n /** Post-Pruning State */\n remainingTokens: z.number().int().nonnegative(),\n remainingMessages: z.number().int().nonnegative(),\n});\n\n/**\n * Conversation Analytics\n */\nexport const ConversationAnalyticsSchema = z.object({\n /** Session Info */\n sessionId: z.string(),\n \n /** Message Statistics */\n totalMessages: z.number().int().nonnegative(),\n userMessages: z.number().int().nonnegative(),\n assistantMessages: z.number().int().nonnegative(),\n systemMessages: z.number().int().nonnegative(),\n \n /** Token Statistics */\n totalTokens: z.number().int().nonnegative(),\n averageTokensPerMessage: z.number().nonnegative(),\n peakTokenUsage: z.number().int().nonnegative(),\n \n /** Efficiency Metrics */\n pruningEvents: z.number().int().nonnegative().default(0),\n summarizationEvents: z.number().int().nonnegative().default(0),\n tokensSavedByPruning: z.number().int().nonnegative().default(0),\n tokensSavedBySummarization: z.number().int().nonnegative().default(0),\n \n /** Duration */\n duration: z.number().nonnegative().optional().describe('Session duration in seconds'),\n firstMessageAt: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n lastMessageAt: z.string().datetime().optional().describe('ISO 8601 timestamp'),\n});\n\nexport type MessageRole = z.infer;\nexport type MessageContentType = z.infer;\nexport type MessageContent = z.infer;\nexport type FunctionCall = z.infer;\nexport type ToolCall = z.infer;\nexport type ConversationMessage = z.infer;\nexport type TokenBudgetStrategy = z.infer;\nexport type TokenBudgetConfig = z.infer;\nexport type TokenUsageStats = z.infer;\nexport type ConversationContext = z.infer;\nexport type ConversationSession = z.infer;\nexport type ConversationSummary = z.infer;\nexport type MessagePruningEvent = z.infer;\nexport type ConversationAnalytics = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ChangeSetSchema } from '../system/migration.zod';\n\n// Identifying the source of truth\nexport const MetadataSourceSchema = z.object({\n file: z.string().optional(),\n line: z.number().optional(),\n column: z.number().optional(),\n // Logic references\n package: z.string().optional(),\n object: z.string().optional(),\n field: z.string().optional(),\n component: z.string().optional() // specific UI component or flow node\n});\n\n// The Runtime Issue\nexport const IssueSchema = z.object({\n id: z.string(),\n severity: z.enum(['critical', 'error', 'warning', 'info']),\n message: z.string(),\n stackTrace: z.string().optional(),\n timestamp: z.string().datetime(),\n userId: z.string().optional(),\n \n // Context snapshot\n context: z.record(z.string(), z.unknown()).optional(),\n \n // The suspected metadata culprit\n source: MetadataSourceSchema.optional()\n});\n\n// The AI's proposed resolution\nexport const ResolutionSchema = z.object({\n issueId: z.string(),\n reasoning: z.string().describe('Explanation of why this fix is needed'),\n confidence: z.number().min(0).max(1),\n \n // Actionable change to fix the issue\n fix: z.discriminatedUnion('type', [\n z.object({\n type: z.literal('metadata_change'),\n changeSet: ChangeSetSchema\n }),\n z.object({\n type: z.literal('manual_intervention'),\n instructions: z.string()\n })\n ])\n});\n\n// Complete Feedback Loop Record\nexport const FeedbackLoopSchema = z.object({\n issue: IssueSchema,\n analysis: z.string().optional().describe('AI analysis of the root cause'),\n resolutions: z.array(ResolutionSchema).optional(),\n status: z.enum(['open', 'analyzing', 'resolved', 'ignored']).default('open')\n});\n\nexport type FeedbackLoop = z.infer;\nexport type Issue = z.infer;\nexport type Resolution = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * API Protocol Exports\n * \n * API Contracts & Envelopes\n * - Request/Response schemas\n * - Error handling\n * - OData v4 compatibility\n * - Batch operations\n * - Metadata caching\n * - HttpDispatcher routing\n * - API versioning\n */\n\nexport * from './contract.zod';\nexport * from './endpoint.zod';\nexport * from './discovery.zod';\nexport * from './events.zod';\nexport * from './realtime-shared.zod';\nexport * from './realtime.zod';\nexport * from './websocket.zod';\nexport * from './router.zod';\nexport * from './odata.zod';\nexport * from './graphql.zod';\nexport * from './batch.zod';\nexport * from './http-cache.zod';\nexport * from './errors.zod';\nexport * from './protocol.zod';\nexport * from './rest-server.zod';\nexport * from './registry.zod';\nexport * from './documentation.zod';\nexport * from './analytics.zod';\nexport * from './versioning.zod';\n\n// Legacy interface export (deprecated)\n// export type { IObjectStackProtocol } from './protocol';\n\nexport * from './auth.zod';\nexport * from './auth-endpoints.zod';\nexport * from './storage.zod';\nexport * from './metadata.zod';\nexport * from './dispatcher.zod';\nexport * from './plugin-rest-api.zod';\nexport * from './query-adapter.zod';\nexport * from './feed-api.zod';\nexport * from './export.zod';\nexport * from './automation-api.zod';\nexport * from './package-api.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { QuerySchema } from '../data/query.zod';\n\n// ==========================================\n// 1. Base Envelopes\n// ==========================================\n\nexport const ApiErrorSchema = z.object({\n code: z.string().describe('Error code (e.g. validation_error)'),\n message: z.string().describe('Readable error message'),\n category: z.string().optional().describe('Error category (e.g. validation, authorization)'),\n details: z.unknown().optional().describe('Additional error context (e.g. field validation errors)'),\n requestId: z.string().optional().describe('Request ID for tracking'),\n});\n\nexport const BaseResponseSchema = z.object({\n success: z.boolean().describe('Operation success status'),\n error: ApiErrorSchema.optional().describe('Error details if success is false'),\n meta: z.object({\n timestamp: z.string(),\n duration: z.number().optional(),\n requestId: z.string().optional(),\n traceId: z.string().optional(),\n }).optional().describe('Response metadata'),\n});\n\n// ==========================================\n// 2. Request Payloads (Inputs)\n// ==========================================\n\nexport const RecordDataSchema = z.record(z.string(), z.unknown()).describe('Key-value map of record data');\n\n/**\n * Standard Create Request\n */\nexport const CreateRequestSchema = z.object({\n data: RecordDataSchema.describe('Record data to insert'),\n});\n\n/**\n * Standard Update Request\n */\nexport const UpdateRequestSchema = z.object({\n data: RecordDataSchema.describe('Partial record data to update'),\n});\n\n/**\n * Standard Bulk Request\n */\nexport const BulkRequestSchema = z.object({\n records: z.array(RecordDataSchema).describe('Array of records to process'),\n allOrNone: z.boolean().default(true).describe('If true, rollback entire transaction on any failure'),\n});\n\n/**\n * Export Request\n */\nexport const ExportRequestSchema = z.intersection(\n QuerySchema,\n z.object({\n format: z.enum(['csv', 'json', 'xlsx']).default('csv'),\n })\n);\n\n// ==========================================\n// 3. Response Payloads (Outputs)\n// ==========================================\n\n/**\n * Single Record Response (Get/Create/Update)\n */\nexport const SingleRecordResponseSchema = BaseResponseSchema.extend({\n data: RecordDataSchema.describe('The requested or modified record'),\n});\n\n/**\n * List/Query Response\n */\nexport const ListRecordResponseSchema = BaseResponseSchema.extend({\n data: z.array(RecordDataSchema).describe('Array of matching records'),\n pagination: z.object({\n total: z.number().optional().describe('Total matching records count'),\n limit: z.number().optional().describe('Page size'),\n offset: z.number().optional().describe('Page offset'),\n cursor: z.string().optional().describe('Cursor for next page'),\n nextCursor: z.string().optional().describe('Next cursor for pagination'),\n hasMore: z.boolean().describe('Are there more pages?'),\n }).describe('Pagination info'),\n});\n\n/**\n * ID Request (Get/Delete)\n */\nexport const IdRequestSchema = z.object({\n id: z.string().describe('Record ID'),\n});\n\n/**\n * Modification Result (for Batch/Bulk operations)\n */\nexport const ModificationResultSchema = z.object({\n id: z.string().optional().describe('Record ID if processed'),\n success: z.boolean(),\n errors: z.array(ApiErrorSchema).optional(),\n index: z.number().optional().describe('Index in original request'),\n data: z.unknown().optional().describe('Result data (e.g. created record)'),\n});\n\n/**\n * Bulk Operation Response\n */\nexport const BulkResponseSchema = BaseResponseSchema.extend({\n data: z.array(ModificationResultSchema).describe('Results for each item in the batch'),\n});\n\n/**\n * Delete Response\n */\nexport const DeleteResponseSchema = BaseResponseSchema.extend({\n id: z.string().describe('ID of the deleted record'),\n});\n\n// ==========================================\n// 4. API Contract Registry\n// ==========================================\n\n/**\n * Standard API Contracts map\n * Used for generating SDKs and Documentation\n */\nexport const StandardApiContracts = {\n create: {\n input: CreateRequestSchema,\n output: SingleRecordResponseSchema\n },\n delete: {\n input: IdRequestSchema,\n output: DeleteResponseSchema\n },\n get: {\n input: IdRequestSchema,\n output: SingleRecordResponseSchema\n },\n update: {\n input: UpdateRequestSchema,\n output: SingleRecordResponseSchema\n },\n list: {\n input: QuerySchema,\n output: ListRecordResponseSchema\n },\n bulkCreate: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkUpdate: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkUpsert: {\n input: BulkRequestSchema,\n output: BulkResponseSchema\n },\n bulkDelete: {\n input: z.object({ ids: z.array(z.string()) }),\n output: BulkResponseSchema\n }\n};\n\n// ==========================================\n// 5. DataLoader / N+1 Query Prevention\n// ==========================================\n\n/**\n * DataLoader Configuration Schema\n * Batch loading configuration to prevent N+1 query problems\n */\nexport const DataLoaderConfigSchema = z.object({\n maxBatchSize: z.number().int().default(100).describe('Maximum number of keys per batch load'),\n batchScheduleFn: z.enum(['microtask', 'timeout', 'manual']).default('microtask')\n .describe('Scheduling strategy for collecting batch keys'),\n cacheEnabled: z.boolean().default(true).describe('Enable per-request result caching'),\n cacheKeyFn: z.string().optional().describe('Name or identifier of the cache key function'),\n cacheTtl: z.number().min(0).optional().describe('Cache time-to-live in seconds (0 = no expiration)'),\n coalesceRequests: z.boolean().default(true).describe('Deduplicate identical requests within a batch window'),\n maxConcurrency: z.number().int().optional().describe('Maximum parallel batch requests'),\n});\n\n/**\n * Batch Loading Strategy Schema\n * Defines how batched data loading is orchestrated\n */\nexport const BatchLoadingStrategySchema = z.object({\n strategy: z.enum(['dataloader', 'windowed', 'prefetch']).describe('Batch loading strategy type'),\n windowMs: z.number().optional().describe('Collection window duration in milliseconds (for windowed strategy)'),\n prefetchDepth: z.number().int().optional().describe('Depth of relation prefetching (for prefetch strategy)'),\n associationLoading: z.enum(['lazy', 'eager', 'batch']).default('batch')\n .describe('How to load related associations'),\n});\n\n/**\n * Query Optimization Configuration Schema\n * Top-level configuration for N+1 prevention and query optimization\n */\nexport const QueryOptimizationConfigSchema = z.object({\n preventNPlusOne: z.boolean().describe('Enable N+1 query detection and prevention'),\n dataLoader: DataLoaderConfigSchema.optional().describe('DataLoader batch loading configuration'),\n batchStrategy: BatchLoadingStrategySchema.optional().describe('Batch loading strategy configuration'),\n maxQueryDepth: z.number().int().describe('Maximum depth for nested relation queries'),\n queryComplexityLimit: z.number().optional().describe('Maximum allowed query complexity score'),\n enableQueryPlan: z.boolean().default(false).describe('Log query execution plans for debugging'),\n});\n\nexport type ApiError = z.infer;\nexport type BaseResponse = z.infer;\nexport type RecordData = z.infer;\nexport type CreateRequest = z.infer;\nexport type UpdateRequest = z.infer;\nexport type BulkRequest = z.infer;\nexport type ExportRequest = z.infer;\nexport type SingleRecordResponse = z.infer;\nexport type ListRecordResponse = z.infer;\nexport type IdRequest = z.infer;\nexport type ModificationResult = z.infer;\nexport type BulkResponse = z.infer;\nexport type DeleteResponse = z.infer;\nexport type DataLoaderConfig = z.infer;\nexport type BatchLoadingStrategy = z.infer;\nexport type QueryOptimizationConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, RateLimitConfigSchema } from '../shared/http.zod';\n\n/**\n * API Mapping Schema\n * Transform input/output data.\n */\nexport const ApiMappingSchema = z.object({\n source: z.string().describe('Source field/path'),\n target: z.string().describe('Target field/path'),\n transform: z.string().optional().describe('Transformation function name'),\n});\n\n/**\n * API Endpoint Schema\n * Defines an external facing API contract.\n */\nexport const ApiEndpointSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique endpoint ID'),\n path: z.string().regex(/^\\//).describe('URL Path (e.g. /api/v1/customers)'),\n method: HttpMethod.describe('HTTP Method'),\n \n /** Documentation */\n summary: z.string().optional(),\n description: z.string().optional(),\n \n /** Execution Logic */\n type: z.enum(['flow', 'script', 'object_operation', 'proxy']).describe('Implementation type'),\n target: z.string().describe('Target Flow ID, Script Name, or Proxy URL'),\n \n /** Logic Config */\n objectParams: z.object({\n object: z.string().optional(),\n operation: z.enum(['find', 'get', 'create', 'update', 'delete']).optional(),\n }).optional().describe('For object_operation type'),\n \n /** Data Transformation */\n inputMapping: z.array(ApiMappingSchema).optional().describe('Map Request Body to Internal Params'),\n outputMapping: z.array(ApiMappingSchema).optional().describe('Map Internal Result to Response Body'),\n \n /** Policies */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n rateLimit: RateLimitConfigSchema.optional().describe('Rate limiting policy'),\n cacheTtl: z.number().optional().describe('Response cache TTL in seconds'),\n});\n\nexport const ApiEndpoint = Object.assign(ApiEndpointSchema, {\n create: >(config: T) => config,\n});\n\nexport type ApiEndpoint = z.infer;\nexport type ApiEndpointInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\n\n/**\n * Service Status Enum\n * Describes the operational state of a service in the discovery response.\n *\n * - `available` – Fully operational: service is registered AND HTTP handler is verified.\n * - `registered` – Route is declared in the dispatcher table but the HTTP handler has\n * not been verified (may 501 at runtime).\n * - `unavailable` – Service is not installed / not registered in the kernel.\n * - `degraded` – Partially working (e.g., in-memory fallback, missing persistence).\n * - `stub` – Placeholder handler that always returns 501 Not Implemented.\n */\nexport const ServiceStatus = z.enum([\n 'available',\n 'registered',\n 'unavailable',\n 'degraded',\n 'stub',\n]).describe(\n 'available = fully operational, registered = route declared but handler unverified, '\n + 'unavailable = not installed, degraded = partial, stub = placeholder that returns 501'\n);\n\nexport type ServiceStatus = z.infer;\n\n/**\n * Service Status in Discovery Response\n * Reports per-service availability so clients can adapt their UI accordingly.\n */\nexport const ServiceInfoSchema = z.object({\n /** Whether the service is enabled and available */\n enabled: z.boolean(),\n /** Current operational status */\n status: ServiceStatus,\n /**\n * Whether the HTTP handler for this service is confirmed to be mounted.\n *\n * Semantics:\n * - `undefined` (omitted) = handler readiness is unknown / not yet verified.\n * - `true` = handler is registered in the adapter / dispatcher (safe to call).\n * - `false` = route is declared but no handler exists or only a stub is present\n * — requests are expected to receive 501 Not Implemented.\n *\n * Clients SHOULD check this flag before displaying or invoking a service endpoint and may\n * distinguish between \"unknown\" (omitted) and \"known missing\" (`false`).\n */\n handlerReady: z.boolean().optional().describe(\n 'Whether the HTTP handler is confirmed to be mounted. '\n + 'Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501).'\n ),\n /** Route path (only present if enabled) */\n route: z.string().optional().describe('e.g. /api/v1/analytics'),\n /** Implementation provider name */\n provider: z.string().optional().describe('e.g. \"objectql\", \"plugin-redis\", \"driver-memory\"'),\n /** Service version */\n version: z.string().optional().describe('Semantic version of the service implementation (e.g. \"3.0.6\")'),\n /** Human-readable reason if unavailable */\n message: z.string().optional().describe('e.g. \"Install plugin-workflow to enable\"'),\n /** Rate limit configuration for this service */\n rateLimit: z.object({\n requestsPerMinute: z.number().int().optional().describe('Maximum requests per minute'),\n requestsPerHour: z.number().int().optional().describe('Maximum requests per hour'),\n burstLimit: z.number().int().optional().describe('Maximum burst request count'),\n retryAfterMs: z.number().int().optional().describe('Suggested retry-after delay in milliseconds when rate-limited'),\n }).optional().describe('Rate limit and quota info for this service'),\n});\n\n/**\n * API Routes Schema\n * The \"Map\" for the frontend to know where to send requests.\n * This decouples the frontend from hardcoded URL paths.\n */\nexport const ApiRoutesSchema = z.object({\n /** Base URL for Object CRUD (Data Protocol) */\n data: z.string().describe('e.g. /api/v1/data'),\n \n /** Base URL for Schema Definitions (Metadata Protocol) */\n metadata: z.string().describe('e.g. /api/v1/meta'),\n\n /** Base URL for API Discovery endpoint */\n discovery: z.string().optional().describe('e.g. /api/v1/discovery'),\n\n /** Base URL for UI Configurations (Views, Menus) */\n ui: z.string().optional().describe('e.g. /api/v1/ui'),\n \n /** Base URL for Authentication (plugin-provided) */\n auth: z.string().optional().describe('e.g. /api/v1/auth'),\n \n /** Base URL for Automation (Flows/Scripts) */\n automation: z.string().optional().describe('e.g. /api/v1/automation'),\n \n /** Base URL for File/Storage operations */\n storage: z.string().optional().describe('e.g. /api/v1/storage'),\n \n /** Base URL for Analytics/BI operations */\n analytics: z.string().optional().describe('e.g. /api/v1/analytics'),\n \n /** GraphQL Endpoint (if enabled) */\n graphql: z.string().optional().describe('e.g. /graphql'),\n\n /** Base URL for Package Management */\n packages: z.string().optional().describe('e.g. /api/v1/packages'),\n\n /** Base URL for Workflow Engine */\n workflow: z.string().optional().describe('e.g. /api/v1/workflow'),\n\n /** Base URL for Realtime (WebSocket/SSE) */\n realtime: z.string().optional().describe('e.g. /api/v1/realtime'),\n\n /** Base URL for Notification Service */\n notifications: z.string().optional().describe('e.g. /api/v1/notifications'),\n\n /** Base URL for AI Engine (NLQ, Chat, Suggest) */\n ai: z.string().optional().describe('e.g. /api/v1/ai'),\n\n /** Base URL for Internationalization */\n i18n: z.string().optional().describe('e.g. /api/v1/i18n'),\n\n /** Base URL for Feed / Chatter API */\n feed: z.string().optional().describe('e.g. /api/v1/feed'),\n});\n\n/**\n * Discovery Response Schema\n * The root object returned by the Metadata Discovery Endpoint.\n * \n * Design rationale:\n * - `services` is the single source of truth for service availability.\n * Each service entry includes `enabled`, `status`, `route`, and `provider`.\n * - `routes` is a convenience shortcut: a flat map of service-name → route-path\n * so that clients can resolve endpoints without iterating the services map.\n * - `capabilities`/`features` was removed because it was fully derivable\n * from `services[x].enabled`. Use `services` to determine feature availability.\n */\nexport const DiscoverySchema = z.object({\n /** System Identity */\n name: z.string(),\n version: z.string(),\n environment: z.enum(['production', 'sandbox', 'development']),\n \n /** Dynamic Routing — convenience shortcut for client routing */\n routes: ApiRoutesSchema,\n \n /** Localization Info (helping frontend init i18n) */\n locale: z.object({\n default: z.string(),\n supported: z.array(z.string()),\n timezone: z.string(),\n }),\n \n /**\n * Per-service status map.\n * This is the **single source of truth** for service availability.\n * Clients use this to determine which features are available,\n * show/hide UI elements, and display appropriate messages.\n */\n services: z.record(z.string(), ServiceInfoSchema).describe(\n 'Per-service availability map keyed by CoreServiceName'\n ),\n\n /**\n * Hierarchical capability descriptors.\n * Declares platform features so clients can adapt UI without probing individual services.\n * Each key is a capability domain (e.g., \"comments\", \"automation\", \"search\"),\n * and its value describes what sub-features are available.\n */\n capabilities: z.record(z.string(), z.object({\n enabled: z.boolean().describe('Whether this capability is available'),\n features: z.record(z.string(), z.boolean()).optional()\n .describe('Sub-feature flags within this capability'),\n description: z.string().optional()\n .describe('Human-readable capability description'),\n })).optional().describe('Hierarchical capability descriptors for frontend intelligent adaptation'),\n\n /**\n * Schema discovery URLs for cross-ecosystem interoperability.\n */\n schemaDiscovery: z.object({\n openapi: z.string().optional().describe('URL to OpenAPI (Swagger) specification (e.g., \"/api/v1/openapi.json\")'),\n graphql: z.string().optional().describe('URL to GraphQL schema endpoint (e.g., \"/graphql\")'),\n jsonSchema: z.string().optional().describe('URL to JSON Schema definitions'),\n }).optional().describe('Schema discovery endpoints for API toolchain integration'),\n\n /**\n * Custom metadata key-value pairs for extensibility\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata key-value pairs for extensibility'),\n});\n\n/**\n * Well-Known Capabilities Schema\n * Flat boolean flags for quick feature detection by clients (ObjectUI).\n * Each flag indicates whether the backend supports a specific capability.\n * Clients can use these to show/hide UI elements without probing individual endpoints.\n */\nexport const WellKnownCapabilitiesSchema = z.object({\n /** Whether the backend supports Feed / Chatter API */\n feed: z.boolean().describe('Whether the backend supports Feed / Chatter API'),\n /** Whether the backend supports comments (a subset of Feed) */\n comments: z.boolean().describe('Whether the backend supports comments (a subset of Feed)'),\n /** Whether the backend supports Automation CRUD (flows, triggers) */\n automation: z.boolean().describe('Whether the backend supports Automation CRUD (flows, triggers)'),\n /** Whether the backend supports cron scheduling */\n cron: z.boolean().describe('Whether the backend supports cron scheduling'),\n /** Whether the backend supports full-text search */\n search: z.boolean().describe('Whether the backend supports full-text search'),\n /** Whether the backend supports async export */\n export: z.boolean().describe('Whether the backend supports async export'),\n /** Whether the backend supports chunked (multipart) uploads */\n chunkedUpload: z.boolean().describe('Whether the backend supports chunked (multipart) uploads'),\n}).describe('Well-known capability flags for frontend intelligent adaptation');\n\nexport type WellKnownCapabilities = z.infer;\nexport type DiscoveryResponse = z.infer;\nexport type ApiRoutes = z.infer;\nexport type ServiceInfo = z.infer;\n\n// ============================================================================\n// Route Health Report\n// ============================================================================\n\n/**\n * Single route health entry for the coverage report.\n */\nexport const RouteHealthEntrySchema = z.object({\n /** Route path (e.g. /api/v1/analytics) */\n route: z.string().describe('Route path pattern'),\n /** HTTP method */\n method: HttpMethod.describe('HTTP method (GET, POST, etc.)'),\n /** Target service name */\n service: z.string().describe('Target service name'),\n /** Whether the route is declared in discovery */\n declared: z.boolean().describe('Whether the route is declared in discovery/metadata'),\n /** Whether the handler is actually registered in the adapter/dispatcher */\n handlerRegistered: z.boolean().describe('Whether the HTTP handler is registered'),\n /**\n * Health check result:\n * - `pass` – Handler exists and responds (2xx/4xx — i.e., not 404/501/503)\n * - `fail` – Handler returned 501 or 503\n * - `missing` – No handler registered (404)\n * - `skip` – Health check was not performed\n */\n healthStatus: z.enum(['pass', 'fail', 'missing', 'skip']).describe(\n 'pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked'\n ),\n /** Optional diagnostic message */\n message: z.string().optional().describe('Diagnostic message'),\n});\n\nexport type RouteHealthEntry = z.infer;\n\n/**\n * Route Health Report Schema\n * Aggregated route coverage report produced at startup or on demand.\n *\n * This report enables automated detection of routes that are declared\n * in discovery metadata but have no corresponding HTTP handler.\n */\nexport const RouteHealthReportSchema = z.object({\n /** ISO 8601 timestamp of when the report was generated */\n timestamp: z.string().describe('ISO 8601 timestamp of report generation'),\n /** Adapter name that generated the report (e.g. \"hono\", \"express\", \"nextjs\") */\n adapter: z.string().describe('Adapter or runtime that produced this report'),\n /** Total routes declared in discovery / dispatcher table */\n totalDeclared: z.number().int().describe('Total routes declared in discovery'),\n /** Routes with a confirmed handler registration */\n totalRegistered: z.number().int().describe('Routes with confirmed handler'),\n /** Routes missing a handler */\n totalMissing: z.number().int().describe('Routes missing a handler'),\n /** Per-route health entries */\n routes: z.array(RouteHealthEntrySchema).describe('Per-route health entries'),\n});\n\nexport type RouteHealthReport = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Metadata Event Types\n *\n * Triggered when metadata items are created, updated, or deleted.\n * Follows the pattern: `metadata.{type}.{action}`\n *\n * Examples:\n * - `metadata.object.created` - A new object was created\n * - `metadata.view.updated` - A view was updated\n * - `metadata.agent.deleted` - An agent was deleted\n */\nexport const MetadataEventType = z.enum([\n 'metadata.object.created',\n 'metadata.object.updated',\n 'metadata.object.deleted',\n 'metadata.field.created',\n 'metadata.field.updated',\n 'metadata.field.deleted',\n 'metadata.view.created',\n 'metadata.view.updated',\n 'metadata.view.deleted',\n 'metadata.app.created',\n 'metadata.app.updated',\n 'metadata.app.deleted',\n 'metadata.agent.created',\n 'metadata.agent.updated',\n 'metadata.agent.deleted',\n 'metadata.tool.created',\n 'metadata.tool.updated',\n 'metadata.tool.deleted',\n 'metadata.flow.created',\n 'metadata.flow.updated',\n 'metadata.flow.deleted',\n 'metadata.action.created',\n 'metadata.action.updated',\n 'metadata.action.deleted',\n 'metadata.workflow.created',\n 'metadata.workflow.updated',\n 'metadata.workflow.deleted',\n 'metadata.dashboard.created',\n 'metadata.dashboard.updated',\n 'metadata.dashboard.deleted',\n 'metadata.report.created',\n 'metadata.report.updated',\n 'metadata.report.deleted',\n 'metadata.role.created',\n 'metadata.role.updated',\n 'metadata.role.deleted',\n 'metadata.permission.created',\n 'metadata.permission.updated',\n 'metadata.permission.deleted',\n]);\n\nexport type MetadataEventType = z.infer;\n\n/**\n * Data Event Types\n *\n * Triggered when data records are created, updated, or deleted.\n * Follows the pattern: `data.record.{action}`\n */\nexport const DataEventType = z.enum([\n 'data.record.created',\n 'data.record.updated',\n 'data.record.deleted',\n 'data.field.changed',\n]);\n\nexport type DataEventType = z.infer;\n\n/**\n * Metadata Event Payload\n *\n * Represents a metadata change event (create, update, delete).\n * Used for real-time synchronization of metadata across clients.\n */\nexport const MetadataEventSchema = z.object({\n /** Unique event identifier */\n id: z.string().uuid().describe('Unique event identifier'),\n\n /** Event type (metadata.{type}.{action}) */\n type: MetadataEventType.describe('Event type'),\n\n /** Metadata type (object, view, agent, tool, etc.) */\n metadataType: z.string().describe('Metadata type (object, view, agent, etc.)'),\n\n /** Metadata item name */\n name: z.string().describe('Metadata item name'),\n\n /** Package ID (if applicable) */\n packageId: z.string().optional().describe('Package ID'),\n\n /** Full definition (only for create/update events) */\n definition: z.unknown().optional().describe('Full definition (create/update only)'),\n\n /** User who triggered the event */\n userId: z.string().optional().describe('User who triggered the event'),\n\n /** Event timestamp (ISO 8601) */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\nexport type MetadataEvent = z.infer;\n\n/**\n * Data Event Payload\n *\n * Represents a data record change event (create, update, delete).\n * Used for real-time synchronization of data records across clients.\n */\nexport const DataEventSchema = z.object({\n /** Unique event identifier */\n id: z.string().uuid().describe('Unique event identifier'),\n\n /** Event type (data.record.{action}) */\n type: DataEventType.describe('Event type'),\n\n /** Object name */\n object: z.string().describe('Object name'),\n\n /** Record ID */\n recordId: z.string().describe('Record ID'),\n\n /** Changed fields (update events only) */\n changes: z.record(z.string(), z.unknown()).optional().describe('Changed fields'),\n\n /** Record before update (update events only) */\n before: z.record(z.string(), z.unknown()).optional().describe('Before state'),\n\n /** Record after update (create/update events) */\n after: z.record(z.string(), z.unknown()).optional().describe('After state'),\n\n /** User who triggered the event */\n userId: z.string().optional().describe('User who triggered the event'),\n\n /** Event timestamp (ISO 8601) */\n timestamp: z.string().datetime().describe('Event timestamp'),\n});\n\nexport type DataEvent = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Realtime Shared Protocol\n * \n * Shared schemas and types for real-time communication protocols.\n * This module consolidates overlapping definitions between the transport-level\n * realtime protocol (SSE/Polling/WebSocket) and the WebSocket collaboration protocol.\n * \n * **Architecture:**\n * - `realtime-shared.zod.ts` — Shared base schemas (Presence, Event types)\n * - `realtime.zod.ts` — Transport-layer protocol (Channel, Subscription, Transport selection)\n * - `websocket.zod.ts` — Collaboration protocol (Cursor, OT editing, Advanced presence)\n * \n * @see realtime.zod.ts for transport-layer configuration\n * @see websocket.zod.ts for collaborative editing protocol\n */\n\n// ==========================================\n// Shared Presence Status\n// ==========================================\n\n/**\n * Presence Status Enum (Unified)\n * \n * Canonical user presence status shared across all realtime protocols.\n * Used by both transport-level presence tracking (realtime.zod.ts)\n * and WebSocket collaboration presence (websocket.zod.ts).\n * \n * @example\n * ```typescript\n * import { PresenceStatus } from './realtime-shared.zod';\n * const status = PresenceStatus.parse('online'); // ✅\n * ```\n */\nexport const PresenceStatus = z.enum([\n 'online', // User is actively connected\n 'away', // User is idle/inactive\n 'busy', // User is busy (do not disturb)\n 'offline', // User is disconnected\n]);\n\nexport type PresenceStatus = z.infer;\n\n// ==========================================\n// Shared Realtime Actions\n// ==========================================\n\n/**\n * Realtime Record Action Enum (Unified)\n * \n * Canonical action types for real-time record change events.\n * Shared between transport-level events and WebSocket event messages.\n */\nexport const RealtimeRecordAction = z.enum([\n 'created',\n 'updated',\n 'deleted',\n]);\n\nexport type RealtimeRecordAction = z.infer;\n\n// ==========================================\n// Shared Base Presence Schema\n// ==========================================\n\n/**\n * Base Presence Schema (Unified)\n * \n * Core presence fields shared across all realtime protocols.\n * Transport-level (realtime.zod.ts) and collaboration-level (websocket.zod.ts)\n * presence schemas extend this base with protocol-specific fields.\n * \n * @example\n * ```typescript\n * const presence = BasePresenceSchema.parse({\n * userId: 'user-123',\n * status: 'online',\n * lastSeen: '2024-01-15T10:30:00Z',\n * });\n * ```\n */\nexport const BasePresenceSchema = z.object({\n /** User identifier */\n userId: z.string().describe('User identifier'),\n\n /** Current presence status */\n status: PresenceStatus.describe('Current presence status'),\n\n /** Last activity timestamp */\n lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n\n /** Custom metadata */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom presence data (e.g., current page, custom status)'),\n});\n\nexport type BasePresence = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { RealtimeRecordAction, BasePresenceSchema } from './realtime-shared.zod';\n\n// Re-export shared types for backward compatibility\nexport { PresenceStatus, RealtimeRecordAction, BasePresenceSchema } from './realtime-shared.zod';\nexport type { BasePresence } from './realtime-shared.zod';\n\n/**\n * Transport Protocol Enum\n * Defines the communication protocol for realtime data synchronization\n */\nexport const TransportProtocol = z.enum([\n 'websocket', // Full-duplex, low latency communication\n 'sse', // Server-Sent Events, unidirectional push\n 'polling', // Short polling, best compatibility\n]);\n\nexport type TransportProtocol = z.infer;\n\n/**\n * Event Type Enum\n * Types of realtime events that can be subscribed to\n */\nexport const RealtimeEventType = z.enum([\n 'record.created',\n 'record.updated',\n 'record.deleted',\n 'field.changed',\n]);\n\nexport type RealtimeEventType = z.infer;\n\n/**\n * Subscription Event Configuration\n * Defines what events to subscribe to with optional filtering\n */\nexport const SubscriptionEventSchema = z.object({\n type: RealtimeEventType.describe('Type of event to subscribe to'),\n object: z.string().optional().describe('Object name to subscribe to'),\n filters: z.unknown().optional().describe('Filter conditions'),\n});\n\n/**\n * Subscription Schema\n * Configuration for subscribing to realtime events\n */\nexport const SubscriptionSchema = z.object({\n id: z.string().uuid().describe('Unique subscription identifier'),\n events: z.array(SubscriptionEventSchema).describe('Array of events to subscribe to'),\n transport: TransportProtocol.describe('Transport protocol to use'),\n channel: z.string().optional().describe('Optional channel name for grouping subscriptions'),\n});\n\nexport type Subscription = z.infer;\n\n/**\n * Presence Schema\n * Tracks user online status and metadata.\n * Extends the shared BasePresenceSchema for transport-level presence tracking.\n */\nexport const RealtimePresenceSchema = BasePresenceSchema;\n\nexport type RealtimePresence = z.infer;\n\n/**\n * Realtime Event Schema\n * Represents a realtime synchronization event\n */\nexport const RealtimeEventSchema = z.object({\n id: z.string().uuid().describe('Unique event identifier'),\n type: z.string().describe('Event type (e.g., record.created, record.updated)'),\n object: z.string().optional().describe('Object name the event relates to'),\n action: RealtimeRecordAction.optional().describe('Action performed'),\n payload: z.record(z.string(), z.unknown()).describe('Event payload data'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when event occurred'),\n userId: z.string().optional().describe('User who triggered the event'),\n sessionId: z.string().optional().describe('Session identifier'),\n});\n\nexport type RealtimeEvent = z.infer;\n\n/**\n * Realtime Configuration Schema\n * \n * Configuration for enabling realtime data synchronization.\n */\nexport const RealtimeConfigSchema = z.object({\n /** Enable realtime sync */\n enabled: z.boolean().default(true).describe('Enable realtime synchronization'),\n \n /** Transport protocol */\n transport: TransportProtocol.default('websocket').describe('Transport protocol'),\n \n /** Default subscriptions */\n subscriptions: z.array(SubscriptionSchema).optional().describe('Default subscriptions'),\n}).passthrough(); // Allow additional properties\n\nexport type RealtimeConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { EventNameSchema } from '../shared/identifiers.zod';\nimport { PresenceStatus } from './realtime-shared.zod';\n\n// Re-export shared PresenceStatus for backward compatibility\nexport { PresenceStatus } from './realtime-shared.zod';\n\n/**\n * WebSocket Event Protocol\n * \n * Defines the schema for WebSocket-based real-time communication in ObjectStack.\n * Supports event subscriptions, filtering, presence tracking, and collaborative editing.\n * \n * Industry alignment: Firebase Realtime Database, Socket.IO, Pusher\n */\n\n// ==========================================\n// Message Types\n// ==========================================\n\n/**\n * WebSocket Message Type Enum\n * Defines the types of messages that can be sent over WebSocket\n */\nexport const WebSocketMessageType = z.enum([\n 'subscribe', // Client subscribes to events\n 'unsubscribe', // Client unsubscribes from events\n 'event', // Server sends event to client\n 'ping', // Keepalive ping\n 'pong', // Keepalive pong response\n 'ack', // Acknowledgment of message receipt\n 'error', // Error message\n 'presence', // Presence update (user status)\n 'cursor', // Cursor position update (collaborative editing)\n 'edit', // Document edit operation (collaborative editing)\n]);\n\nexport type WebSocketMessageType = z.infer;\n\n// ==========================================\n// Event Subscription\n// ==========================================\n\n/**\n * Event Filter Operator Enum\n * SQL-like filter operators for event filtering\n */\nexport const FilterOperator = z.enum([\n 'eq', // Equal\n 'ne', // Not equal\n 'gt', // Greater than\n 'gte', // Greater than or equal\n 'lt', // Less than\n 'lte', // Less than or equal\n 'in', // In array\n 'nin', // Not in array\n 'contains', // String contains\n 'startsWith', // String starts with\n 'endsWith', // String ends with\n 'exists', // Field exists\n 'regex', // Regex match\n]);\n\nexport type FilterOperator = z.infer;\n\n/**\n * Event Filter Condition\n * Defines a single filter condition for event filtering\n */\nexport const EventFilterCondition = z.object({\n field: z.string().describe('Field path to filter on (supports dot notation, e.g., \"user.email\")'),\n operator: FilterOperator.describe('Comparison operator'),\n value: z.unknown().optional().describe('Value to compare against (not needed for \"exists\" operator)'),\n});\n\nexport type EventFilterCondition = z.infer;\n\n/**\n * Event Filter Schema\n * Logical combination of filter conditions\n */\nexport const EventFilterSchema: z.ZodType<{\n conditions?: EventFilterCondition[];\n and?: EventFilter[];\n or?: EventFilter[];\n not?: EventFilter;\n}> = z.object({\n conditions: z.array(EventFilterCondition).optional().describe('Array of filter conditions'),\n and: z.lazy(() => z.array(EventFilterSchema)).optional().describe('AND logical combination of filters'),\n or: z.lazy(() => z.array(EventFilterSchema)).optional().describe('OR logical combination of filters'),\n not: z.lazy(() => EventFilterSchema).optional().describe('NOT logical negation of filter'),\n});\n\nexport type EventFilter = z.infer;\n\n/**\n * Event Pattern Schema\n * Event name pattern that supports wildcards for subscriptions\n */\nexport const EventPatternSchema = z\n .string()\n .min(1)\n .regex(/^[a-z*][a-z0-9_.*]*$/, {\n message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., \"record.*\", \"*.created\", \"user.login\")',\n })\n .describe('Event pattern (supports wildcards like \"record.*\" or \"*.created\")');\n\nexport type EventPattern = z.infer;\n\n/**\n * Event Subscription Config\n * Configuration for subscribing to specific events\n */\nexport const EventSubscriptionSchema = z.object({\n subscriptionId: z.string().uuid().describe('Unique subscription identifier'),\n events: z.array(EventPatternSchema).describe('Event patterns to subscribe to (supports wildcards, e.g., \"record.*\", \"user.created\")'),\n objects: z.array(z.string()).optional().describe('Object names to filter events by (e.g., [\"account\", \"contact\"])'),\n filters: EventFilterSchema.optional().describe('Advanced filter conditions for event payloads'),\n channels: z.array(z.string()).optional().describe('Channel names for scoped subscriptions'),\n});\n\nexport type EventSubscription = z.infer;\n\n/**\n * Unsubscribe Request\n * Request to unsubscribe from events\n */\nexport const UnsubscribeRequestSchema = z.object({\n subscriptionId: z.string().uuid().describe('Subscription ID to unsubscribe from'),\n});\n\nexport type UnsubscribeRequest = z.infer;\n\n// ==========================================\n// Presence Tracking\n// ==========================================\n\n/**\n * Presence Status Enum\n * Re-exported from realtime-shared.zod.ts for backward compatibility\n */\nexport const WebSocketPresenceStatus = PresenceStatus;\n\nexport type WebSocketPresenceStatus = z.infer;\n\n/**\n * Presence State Schema\n * Tracks real-time user presence and activity\n */\nexport const PresenceStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Unique session identifier'),\n status: WebSocketPresenceStatus.describe('Current presence status'),\n lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),\n currentLocation: z.string().optional().describe('Current page/route user is viewing'),\n device: z.enum(['desktop', 'mobile', 'tablet', 'other']).optional().describe('Device type'),\n customStatus: z.string().optional().describe('Custom user status message'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional custom presence data'),\n});\n\nexport type PresenceState = z.infer;\n\n/**\n * Presence Update Request\n * Client request to update presence status\n */\nexport const PresenceUpdateSchema = z.object({\n status: WebSocketPresenceStatus.optional().describe('Updated presence status'),\n currentLocation: z.string().optional().describe('Updated current location'),\n customStatus: z.string().optional().describe('Updated custom status message'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),\n});\n\nexport type PresenceUpdate = z.infer;\n\n// ==========================================\n// Collaborative Editing Protocol\n// ==========================================\n\n/**\n * Cursor Position Schema\n * Represents a cursor position in a document\n */\nexport const CursorPositionSchema = z.object({\n userId: z.string().describe('User identifier'),\n sessionId: z.string().uuid().describe('Session identifier'),\n documentId: z.string().describe('Document identifier being edited'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Column number (0-indexed)'),\n }).optional().describe('Cursor position in document'),\n selection: z.object({\n start: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }),\n end: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }),\n }).optional().describe('Selection range (if text is selected)'),\n color: z.string().optional().describe('Cursor color for visual representation'),\n userName: z.string().optional().describe('Display name of user'),\n lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),\n});\n\nexport type CursorPosition = z.infer;\n\n/**\n * Edit Operation Type Enum\n * Types of edit operations for collaborative editing\n */\nexport const EditOperationType = z.enum([\n 'insert', // Insert text at position\n 'delete', // Delete text from range\n 'replace', // Replace text in range\n]);\n\nexport type EditOperationType = z.infer;\n\n/**\n * Edit Operation Schema\n * Represents a single edit operation on a document\n * Supports Operational Transformation (OT) for conflict resolution\n */\nexport const EditOperationSchema = z.object({\n operationId: z.string().uuid().describe('Unique operation identifier'),\n documentId: z.string().describe('Document identifier'),\n userId: z.string().describe('User who performed the edit'),\n sessionId: z.string().uuid().describe('Session identifier'),\n type: EditOperationType.describe('Type of edit operation'),\n position: z.object({\n line: z.number().int().nonnegative().describe('Line number (0-indexed)'),\n column: z.number().int().nonnegative().describe('Column number (0-indexed)'),\n }).describe('Starting position of the operation'),\n endPosition: z.object({\n line: z.number().int().nonnegative(),\n column: z.number().int().nonnegative(),\n }).optional().describe('Ending position (for delete/replace operations)'),\n content: z.string().optional().describe('Content to insert/replace'),\n version: z.number().int().nonnegative().describe('Document version before this operation'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),\n baseOperationId: z.string().uuid().optional().describe('Previous operation ID this builds upon (for OT)'),\n});\n\nexport type EditOperation = z.infer;\n\n/**\n * Document State Schema\n * Represents the current state of a collaborative document\n */\nexport const DocumentStateSchema = z.object({\n documentId: z.string().describe('Document identifier'),\n version: z.number().int().nonnegative().describe('Current document version'),\n content: z.string().describe('Current document content'),\n lastModified: z.string().datetime().describe('ISO 8601 datetime of last modification'),\n activeSessions: z.array(z.string().uuid()).describe('Active editing session IDs'),\n checksum: z.string().optional().describe('Content checksum for integrity verification'),\n});\n\nexport type DocumentState = z.infer;\n\n// ==========================================\n// WebSocket Messages\n// ==========================================\n\n/**\n * Base WebSocket Message\n * All WebSocket messages extend this base structure\n */\nconst BaseWebSocketMessage = z.object({\n messageId: z.string().uuid().describe('Unique message identifier'),\n type: WebSocketMessageType.describe('Message type'),\n timestamp: z.string().datetime().describe('ISO 8601 datetime when message was sent'),\n});\n\n/**\n * Subscribe Message\n * Client sends this to subscribe to events\n */\nexport const SubscribeMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('subscribe'),\n subscription: EventSubscriptionSchema.describe('Subscription configuration'),\n});\n\nexport type SubscribeMessage = z.infer;\n\n/**\n * Unsubscribe Message\n * Client sends this to unsubscribe from events\n */\nexport const UnsubscribeMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('unsubscribe'),\n request: UnsubscribeRequestSchema.describe('Unsubscribe request'),\n});\n\nexport type UnsubscribeMessage = z.infer;\n\n/**\n * Event Message\n * Server sends this when a subscribed event occurs\n */\nexport const EventMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('event'),\n subscriptionId: z.string().uuid().describe('Subscription ID this event belongs to'),\n eventName: EventNameSchema.describe('Event name'),\n object: z.string().optional().describe('Object name the event relates to'),\n payload: z.unknown().describe('Event payload data'),\n userId: z.string().optional().describe('User who triggered the event'),\n});\n\nexport type EventMessage = z.infer;\n\n/**\n * Presence Message\n * Presence update message\n */\nexport const PresenceMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('presence'),\n presence: PresenceStateSchema.describe('Presence state'),\n});\n\nexport type PresenceMessage = z.infer;\n\n/**\n * Cursor Message\n * Cursor position update for collaborative editing\n */\nexport const CursorMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('cursor'),\n cursor: CursorPositionSchema.describe('Cursor position'),\n});\n\nexport type CursorMessage = z.infer;\n\n/**\n * Edit Message\n * Document edit operation for collaborative editing\n */\nexport const EditMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('edit'),\n operation: EditOperationSchema.describe('Edit operation'),\n});\n\nexport type EditMessage = z.infer;\n\n/**\n * Acknowledgment Message\n * Server acknowledges receipt of a message\n */\nexport const AckMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('ack'),\n ackMessageId: z.string().uuid().describe('ID of the message being acknowledged'),\n success: z.boolean().describe('Whether the operation was successful'),\n error: z.string().optional().describe('Error message if operation failed'),\n});\n\nexport type AckMessage = z.infer;\n\n/**\n * Error Message\n * Server sends error information\n */\nexport const ErrorMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('error'),\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n details: z.unknown().optional().describe('Additional error details'),\n});\n\nexport type ErrorMessage = z.infer;\n\n/**\n * Ping Message\n * Keepalive ping from client or server\n */\nexport const PingMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('ping'),\n});\n\nexport type PingMessage = z.infer;\n\n/**\n * Pong Message\n * Keepalive pong response\n */\nexport const PongMessageSchema = BaseWebSocketMessage.extend({\n type: z.literal('pong'),\n pingMessageId: z.string().uuid().optional().describe('ID of ping message being responded to'),\n});\n\nexport type PongMessage = z.infer;\n\n/**\n * WebSocket Message Union\n * Discriminated union of all WebSocket message types\n */\nexport const WebSocketMessageSchema = z.discriminatedUnion('type', [\n SubscribeMessageSchema,\n UnsubscribeMessageSchema,\n EventMessageSchema,\n PresenceMessageSchema,\n CursorMessageSchema,\n EditMessageSchema,\n AckMessageSchema,\n ErrorMessageSchema,\n PingMessageSchema,\n PongMessageSchema,\n]);\n\nexport type WebSocketMessage = z.infer;\n\n// ==========================================\n// Connection Configuration\n// ==========================================\n\n/**\n * WebSocket Connection Config\n * Configuration for WebSocket connections\n */\nexport const WebSocketConfigSchema = z.object({\n url: z.string().url().describe('WebSocket server URL'),\n protocols: z.array(z.string()).optional().describe('WebSocket sub-protocols'),\n reconnect: z.boolean().optional().default(true).describe('Enable automatic reconnection'),\n reconnectInterval: z.number().int().positive().optional().default(1000).describe('Reconnection interval in milliseconds'),\n maxReconnectAttempts: z.number().int().positive().optional().default(5).describe('Maximum reconnection attempts'),\n pingInterval: z.number().int().positive().optional().default(30000).describe('Ping interval in milliseconds'),\n timeout: z.number().int().positive().optional().default(5000).describe('Message timeout in milliseconds'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers for WebSocket handshake'),\n});\n\nexport type WebSocketConfig = z.infer;\n\n// ==========================================\n// Simplified Collaboration API\n// ==========================================\n\n/**\n * Simplified WebSocket Event Schema\n * \n * A simplified event schema for basic WebSocket communication.\n * Complements the comprehensive WebSocketMessageSchema above for simpler use cases.\n * \n * @example Subscribe to channel\n * ```typescript\n * {\n * type: 'subscribe',\n * channel: 'record.account.123',\n * payload: { events: ['created', 'updated'] },\n * timestamp: Date.now()\n * }\n * ```\n * \n * @example Data change notification\n * ```typescript\n * {\n * type: 'data-change',\n * channel: 'record.account.123',\n * payload: { id: '123', action: 'updated', data: {...} },\n * timestamp: Date.now()\n * }\n * ```\n */\nexport const WebSocketEventSchema = z.object({\n type: z.enum([\n 'subscribe', // Client subscribes to channel\n 'unsubscribe', // Client unsubscribes from channel\n 'data-change', // Data modification event\n 'presence-update', // User presence change\n 'cursor-update', // Cursor position change (collaborative editing)\n 'error', // Error message\n ]).describe('Event type'),\n channel: z.string().describe('Channel identifier (e.g., \"record.account.123\", \"user.456\")'),\n payload: z.unknown().describe('Event payload data'),\n timestamp: z.number().describe('Unix timestamp in milliseconds'),\n});\n\nexport type WebSocketEvent = z.infer;\n\n/**\n * Simplified Presence State Schema\n * \n * A simplified presence schema for basic user presence tracking.\n * Complements the comprehensive PresenceStateSchema for simpler integrations.\n * \n * Use this for basic presence features. For advanced features like device tracking,\n * custom status, and session management, use the comprehensive PresenceStateSchema above.\n * \n * @example User online\n * ```typescript\n * {\n * userId: 'user123',\n * userName: 'John Doe',\n * status: 'online',\n * lastSeen: Date.now(),\n * metadata: { currentPage: '/dashboard' }\n * }\n * ```\n */\nexport const SimplePresenceStateSchema = z.object({\n userId: z.string().describe('User identifier'),\n userName: z.string().describe('User display name'),\n status: z.enum(['online', 'away', 'offline']).describe('User presence status'),\n lastSeen: z.number().describe('Unix timestamp of last activity in milliseconds'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional presence metadata (e.g., current page, custom status)'),\n});\n\nexport type SimplePresenceState = z.infer;\n\n/**\n * Simplified Cursor Position Schema\n * \n * A simplified cursor position schema for basic collaborative editing.\n * Complements the comprehensive CursorPositionSchema for simpler use cases.\n * \n * Use this for basic cursor sharing. For advanced features like selections,\n * color coding, and document versioning, use the comprehensive CursorPositionSchema above.\n * \n * @example Cursor in text field\n * ```typescript\n * {\n * userId: 'user123',\n * recordId: 'account_456',\n * fieldName: 'description',\n * position: 42,\n * selection: { start: 42, end: 57 }\n * }\n * ```\n */\nexport const SimpleCursorPositionSchema = z.object({\n userId: z.string().describe('User identifier'),\n recordId: z.string().describe('Record identifier being edited'),\n fieldName: z.string().describe('Field name being edited'),\n position: z.number().describe('Cursor position (character offset from start)'),\n selection: z.object({\n start: z.number().describe('Selection start position'),\n end: z.number().describe('Selection end position'),\n }).optional().describe('Text selection range (if text is selected)'),\n});\n\nexport type SimpleCursorPosition = z.infer;\n\n/**\n * WebSocket Server Configuration Schema\n * \n * Server-side configuration for WebSocket services.\n * Controls features like presence tracking, cursor sharing, and connection management.\n * \n * @example Production configuration\n * ```typescript\n * {\n * enabled: true,\n * path: '/ws',\n * heartbeatInterval: 30000,\n * reconnectAttempts: 5,\n * presence: true,\n * cursorSharing: true\n * }\n * ```\n */\nexport const WebSocketServerConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable WebSocket server'),\n path: z.string().default('/ws').describe('WebSocket endpoint path'),\n heartbeatInterval: z.number().default(30000).describe('Heartbeat interval in milliseconds'),\n reconnectAttempts: z.number().default(5).describe('Maximum reconnection attempts for clients'),\n presence: z.boolean().default(false).describe('Enable presence tracking'),\n cursorSharing: z.boolean().default(false).describe('Enable collaborative cursor sharing'),\n});\n\nexport type WebSocketServerConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { CorsConfigSchema, StaticMountSchema, HttpMethod } from '../shared/http.zod';\n\n// Re-export HttpMethod for convenience\nexport { HttpMethod };\n\n/**\n * Route Category Enum\n * Classifies routes for middleware application and security policies.\n */\nexport const RouteCategory = z.enum([\n 'system', // Health, Metrics, Info (No Auth usually)\n 'api', // Business Logic API (Auth required)\n 'auth', // Login/Callback endpoints\n 'static', // Asset serving\n 'webhook', // External callbacks\n 'plugin' // Plugin extensions\n]);\n\nexport type RouteCategory = z.infer;\n\n/**\n * Route Definition Schema\n * Describes a single routable endpoint in the Kernel.\n */\nexport const RouteDefinitionSchema = z.object({\n /**\n * HTTP Method\n */\n method: HttpMethod,\n \n /**\n * URL Path Pattern (supports parameters like /user/:id)\n */\n path: z.string().describe('URL Path pattern'),\n \n /**\n * Route Type/Category\n */\n category: RouteCategory.default('api'),\n \n /**\n * Handler Identifier\n * References an internal function or plugin action ID.\n */\n handler: z.string().describe('Unique handler identifier'),\n \n /**\n * Route specific metadata\n */\n summary: z.string().optional().describe('OpenAPI summary'),\n description: z.string().optional().describe('OpenAPI description'),\n \n /**\n * Security constraints\n */\n public: z.boolean().default(false).describe('Is publicly accessible'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /**\n * Performance hints\n */\n timeout: z.number().int().optional().describe('Execution timeout in ms'),\n rateLimit: z.string().optional().describe('Rate limit policy name'),\n});\n\nexport type RouteDefinition = z.infer;\n\n/**\n * Router Configuration Schema\n * Global routing table configuration.\n */\nexport const RouterConfigSchema = z.object({\n /**\n * URL Prefix for all kernel routes\n */\n basePath: z.string().default('/api').describe('Global API prefix'),\n \n /**\n * Standard Protocol Mounts (Relative to basePath)\n */\n mounts: z.object({\n data: z.string().default('/data').describe('Data Protocol (CRUD)'),\n metadata: z.string().default('/meta').describe('Metadata Protocol (Schemas)'),\n auth: z.string().default('/auth').describe('Auth Protocol'),\n automation: z.string().default('/automation').describe('Automation Protocol'),\n storage: z.string().default('/storage').describe('Storage Protocol'),\n analytics: z.string().default('/analytics').describe('Analytics Protocol'),\n graphql: z.string().default('/graphql').describe('GraphQL Endpoint'),\n ui: z.string().default('/ui').describe('UI Metadata Protocol (Views, Layouts)'),\n workflow: z.string().default('/workflow').describe('Workflow Engine Protocol'),\n realtime: z.string().default('/realtime').describe('Realtime/WebSocket Protocol'),\n notifications: z.string().default('/notifications').describe('Notification Protocol'),\n ai: z.string().default('/ai').describe('AI Engine Protocol (NLQ, Chat, Suggest)'),\n i18n: z.string().default('/i18n').describe('Internationalization Protocol'),\n packages: z.string().default('/packages').describe('Package Management Protocol'),\n }).default({\n data: '/data',\n metadata: '/meta',\n auth: '/auth',\n automation: '/automation',\n storage: '/storage',\n analytics: '/analytics',\n graphql: '/graphql',\n ui: '/ui',\n workflow: '/workflow',\n realtime: '/realtime',\n notifications: '/notifications',\n ai: '/ai',\n i18n: '/i18n',\n packages: '/packages',\n }), // Defaults match standardized spec\n\n /**\n * Cross-Origin Resource Sharing\n */\n cors: CorsConfigSchema.optional(),\n \n /**\n * Static asset mounts\n */\n staticMounts: z.array(StaticMountSchema).optional(),\n});\n\nexport type RouterConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * OData v4 Protocol Support\n * \n * Open Data Protocol (OData) v4 is an industry-standard protocol for building\n * and consuming RESTful APIs. It provides a uniform way to expose, structure,\n * query, and manipulate data.\n * \n * ## Overview\n * \n * OData v4 provides standardized URL conventions for querying data including:\n * - $select: Choose which fields to return\n * - $filter: Filter results with complex expressions\n * - $orderby: Sort results\n * - $top/$skip: Pagination\n * - $expand: Include related entities\n * - $count: Get total count\n * \n * ## Use Cases\n * \n * 1. **Enterprise Integration**\n * - Integrate with Microsoft Dynamics 365\n * - Connect to SharePoint Online\n * - SAP OData services\n * \n * 2. **API Standardization**\n * - Provide consistent query interface\n * - Standard pagination and filtering\n * - Industry-recognized protocol\n * \n * 3. **External Data Sources**\n * - Connect to OData-compliant systems\n * - Federated queries\n * - Data virtualization\n * \n * @see https://www.odata.org/documentation/\n * @see https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html\n * \n * @example OData Query\n * ```\n * GET /api/odata/customers?\n * $select=name,email&\n * $filter=country eq 'US' and revenue gt 100000&\n * $orderby=revenue desc&\n * $top=10&\n * $skip=20&\n * $expand=orders&\n * $count=true\n * ```\n * \n * @example Programmatic Use\n * ```typescript\n * const query: ODataQuery = {\n * select: ['name', 'email'],\n * filter: \"country eq 'US' and revenue gt 100000\",\n * orderby: 'revenue desc',\n * top: 10,\n * skip: 20,\n * expand: ['orders'],\n * count: true\n * }\n * ```\n */\n\n/**\n * OData Query Options Schema\n * \n * System query options defined by OData v4 specification.\n * These are URL query parameters that control the query execution.\n * \n * @see https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html#sec_SystemQueryOptions\n */\nexport const ODataQuerySchema = z.object({\n /**\n * $select - Select specific fields to return\n * \n * Comma-separated list of field names to include in the response.\n * Reduces payload size and improves performance.\n * \n * @example \"name,email,phone\"\n * @example \"id,customer/name\" - With navigation path\n */\n $select: z.union([\n z.string(), // \"name,email\"\n z.array(z.string()), // [\"name\", \"email\"]\n ]).optional().describe('Fields to select'),\n\n /**\n * $filter - Filter results with conditions\n * \n * OData filter expression using comparison operators, logical operators,\n * and functions.\n * \n * Comparison: eq, ne, lt, le, gt, ge\n * Logical: and, or, not\n * Functions: contains, startswith, endswith, length, indexof, substring, etc.\n * \n * @example \"age gt 18\"\n * @example \"country eq 'US' and revenue gt 100000\"\n * @example \"contains(name, 'Smith')\"\n * @example \"startswith(email, 'admin') and isActive eq true\"\n */\n $filter: z.string().optional().describe('Filter expression (OData filter syntax)'),\n\n /**\n * $orderby - Sort results\n * \n * Comma-separated list of fields with optional asc/desc.\n * Default is ascending.\n * \n * @example \"name\"\n * @example \"revenue desc\"\n * @example \"country asc, revenue desc\"\n */\n $orderby: z.union([\n z.string(), // \"name desc\"\n z.array(z.string()), // [\"name desc\", \"email asc\"]\n ]).optional().describe('Sort order'),\n\n /**\n * $top - Limit number of results\n * \n * Maximum number of results to return.\n * Equivalent to SQL LIMIT or FETCH FIRST.\n * \n * @example 10\n * @example 100\n */\n $top: z.number().int().min(0).optional().describe('Max results to return'),\n\n /**\n * $skip - Skip results for pagination\n * \n * Number of results to skip before returning results.\n * Equivalent to SQL OFFSET.\n * \n * @example 20\n * @example 100\n */\n $skip: z.number().int().min(0).optional().describe('Results to skip'),\n\n /**\n * $expand - Include related entities (lookup/master_detail fields)\n * \n * Comma-separated list of navigation properties (relationship field names) to expand.\n * Loads related data in the same request by resolving lookup and master_detail fields.\n * The engine replaces foreign key IDs with full related objects via batch $in queries.\n * Supports nested expand via OData parenthetical syntax.\n * \n * Behavior:\n * - Only fields with `type: 'lookup'` or `type: 'master_detail'` and a valid `reference` are expanded.\n * - Fields without a schema or reference definition are silently skipped (ID returned as-is).\n * - Maximum expand depth defaults to 3 (configurable via QueryAdapterConfig).\n * \n * @example \"orders\"\n * @example \"customer,products\"\n * @example \"orders($select=id,total)\" - With nested query options\n */\n $expand: z.union([\n z.string(), // \"orders\"\n z.array(z.string()), // [\"orders\", \"customer\"]\n ]).optional().describe('Navigation properties to expand (lookup/master_detail fields)'),\n\n /**\n * $count - Include total count\n * \n * When true, includes totalResults count in response.\n * Useful for pagination UI.\n * \n * @example true\n */\n $count: z.boolean().optional().describe('Include total count'),\n\n /**\n * $search - Full-text search\n * \n * Free-text search expression.\n * Search implementation is service-specific.\n * \n * @example \"John Smith\"\n * @example \"urgent AND support\"\n */\n $search: z.string().optional().describe('Search expression'),\n\n /**\n * $format - Response format\n * \n * Preferred response format.\n * \n * @example \"json\"\n * @example \"xml\"\n */\n $format: z.enum(['json', 'xml', 'atom']).optional().describe('Response format'),\n\n /**\n * $apply - Data aggregation\n * \n * Aggregation transformations (groupby, aggregate, etc.)\n * Part of OData aggregation extension.\n * \n * @example \"groupby((country),aggregate(revenue with sum as totalRevenue))\"\n */\n $apply: z.string().optional().describe('Aggregation expression'),\n});\n\nexport type ODataQuery = z.infer;\n\n/**\n * OData Filter Operator\n * \n * Standard comparison and logical operators in OData filter expressions.\n */\nexport const ODataFilterOperatorSchema = z.enum([\n // Comparison Operators\n 'eq', // Equal to\n 'ne', // Not equal to\n 'lt', // Less than\n 'le', // Less than or equal to\n 'gt', // Greater than\n 'ge', // Greater than or equal to\n\n // Logical Operators\n 'and', // Logical AND\n 'or', // Logical OR\n 'not', // Logical NOT\n\n // Grouping\n '(', // Left parenthesis\n ')', // Right parenthesis\n\n // Other\n 'in', // Value in list\n 'has', // Has flag (for enum flags)\n]);\n\nexport type ODataFilterOperator = z.infer;\n\n/**\n * OData Filter Function\n * \n * Standard functions available in OData filter expressions.\n */\nexport const ODataFilterFunctionSchema = z.enum([\n // String Functions\n 'contains', // contains(field, 'value')\n 'startswith', // startswith(field, 'value')\n 'endswith', // endswith(field, 'value')\n 'length', // length(field)\n 'indexof', // indexof(field, 'substring')\n 'substring', // substring(field, start, length)\n 'tolower', // tolower(field)\n 'toupper', // toupper(field)\n 'trim', // trim(field)\n 'concat', // concat(field1, field2)\n\n // Date/Time Functions\n 'year', // year(dateField)\n 'month', // month(dateField)\n 'day', // day(dateField)\n 'hour', // hour(datetimeField)\n 'minute', // minute(datetimeField)\n 'second', // second(datetimeField)\n 'date', // date(datetimeField)\n 'time', // time(datetimeField)\n 'now', // now()\n 'maxdatetime', // maxdatetime()\n 'mindatetime', // mindatetime()\n\n // Math Functions\n 'round', // round(numField)\n 'floor', // floor(numField)\n 'ceiling', // ceiling(numField)\n\n // Type Functions\n 'cast', // cast(field, 'Edm.String')\n 'isof', // isof(field, 'Type')\n\n // Collection Functions\n 'any', // collection/any(d:d/prop eq value)\n 'all', // collection/all(d:d/prop eq value)\n]);\n\nexport type ODataFilterFunction = z.infer;\n\n/**\n * OData Response Schema\n * \n * Standard OData JSON response format.\n */\nexport const ODataResponseSchema = z.object({\n /**\n * OData context URL\n * Describes the payload structure\n */\n '@odata.context': z.string().url().optional().describe('Metadata context URL'),\n\n /**\n * Total count (when $count=true)\n */\n '@odata.count': z.number().int().optional().describe('Total results count'),\n\n /**\n * Next link for pagination\n */\n '@odata.nextLink': z.string().url().optional().describe('Next page URL'),\n\n /**\n * Result array\n */\n value: z.array(z.record(z.string(), z.unknown())).describe('Results array'),\n});\n\nexport type ODataResponse = z.infer;\n\n/**\n * OData Error Response Schema\n * \n * Standard OData error format.\n */\nexport const ODataErrorSchema = z.object({\n error: z.object({\n /**\n * Error code\n */\n code: z.string().describe('Error code'),\n\n /**\n * Error message\n */\n message: z.string().describe('Error message'),\n\n /**\n * Target of the error (field name, etc.)\n */\n target: z.string().optional().describe('Error target'),\n\n /**\n * Additional error details\n */\n details: z.array(z.object({\n code: z.string(),\n message: z.string(),\n target: z.string().optional(),\n })).optional().describe('Error details'),\n\n /**\n * Inner error for debugging\n */\n innererror: z.record(z.string(), z.unknown()).optional().describe('Inner error details'),\n }),\n});\n\nexport type ODataError = z.infer;\n\n/**\n * OData Metadata Configuration\n * \n * Configuration for OData metadata endpoint ($metadata).\n */\nexport const ODataMetadataSchema = z.object({\n /**\n * Service namespace\n */\n namespace: z.string().describe('Service namespace'),\n\n /**\n * Entity types to expose\n */\n entityTypes: z.array(z.object({\n name: z.string().describe('Entity type name'),\n key: z.array(z.string()).describe('Key fields'),\n properties: z.array(z.object({\n name: z.string(),\n type: z.string().describe('OData type (Edm.String, Edm.Int32, etc.)'),\n nullable: z.boolean().default(true),\n })),\n navigationProperties: z.array(z.object({\n name: z.string(),\n type: z.string(),\n partner: z.string().optional(),\n })).optional(),\n })).describe('Entity types'),\n\n /**\n * Entity sets\n */\n entitySets: z.array(z.object({\n name: z.string().describe('Entity set name'),\n entityType: z.string().describe('Entity type'),\n })).describe('Entity sets'),\n});\n\nexport type ODataMetadata = z.infer;\n\n/**\n * Helper functions for OData operations\n */\nexport const OData = {\n /**\n * Build OData query URL\n */\n buildUrl: (baseUrl: string, query: ODataQuery): string => {\n const params = new URLSearchParams();\n\n if (query.$select) {\n params.append('$select', Array.isArray(query.$select) ? query.$select.join(',') : query.$select);\n }\n if (query.$filter) {\n params.append('$filter', query.$filter);\n }\n if (query.$orderby) {\n params.append('$orderby', Array.isArray(query.$orderby) ? query.$orderby.join(',') : query.$orderby);\n }\n if (query.$top !== undefined) {\n params.append('$top', query.$top.toString());\n }\n if (query.$skip !== undefined) {\n params.append('$skip', query.$skip.toString());\n }\n if (query.$expand) {\n params.append('$expand', Array.isArray(query.$expand) ? query.$expand.join(',') : query.$expand);\n }\n if (query.$count !== undefined) {\n params.append('$count', query.$count.toString());\n }\n if (query.$search) {\n params.append('$search', query.$search);\n }\n if (query.$format) {\n params.append('$format', query.$format);\n }\n if (query.$apply) {\n params.append('$apply', query.$apply);\n }\n\n const queryString = params.toString();\n return queryString ? `${baseUrl}?${queryString}` : baseUrl;\n },\n\n /**\n * Create a simple filter expression\n */\n filter: {\n eq: (field: string, value: string | number | boolean) => \n `${field} eq ${typeof value === 'string' ? `'${value}'` : value}`,\n ne: (field: string, value: string | number | boolean) => \n `${field} ne ${typeof value === 'string' ? `'${value}'` : value}`,\n gt: (field: string, value: number) => `${field} gt ${value}`,\n lt: (field: string, value: number) => `${field} lt ${value}`,\n contains: (field: string, value: string) => `contains(${field}, '${value}')`,\n and: (...expressions: string[]) => expressions.join(' and '),\n or: (...expressions: string[]) => expressions.join(' or '),\n },\n} as const;\n\n/**\n * OData Configuration Schema\n * \n * Configuration for enabling OData v4 API endpoint.\n */\nexport const ODataConfigSchema = z.object({\n /** Enable OData endpoint */\n enabled: z.boolean().default(true).describe('Enable OData API'),\n \n /** OData endpoint path */\n path: z.string().default('/odata').describe('OData endpoint path'),\n \n /** Metadata configuration */\n metadata: ODataMetadataSchema.optional().describe('OData metadata configuration'),\n}).passthrough(); // Allow additional properties for flexibility\n\nexport type ODataConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldType } from '../data/field.zod';\n\n/**\n * GraphQL Protocol Support\n * \n * GraphQL is a query language for APIs and a runtime for executing those queries.\n * It provides a complete and understandable description of the data in your API,\n * gives clients the power to ask for exactly what they need, and enables powerful\n * developer tools.\n * \n * ## Overview\n * \n * GraphQL provides:\n * - Type-safe schema definition\n * - Precise data fetching (no over/under-fetching)\n * - Introspection and documentation\n * - Real-time subscriptions\n * - Batched queries with DataLoader\n * \n * ## Use Cases\n * \n * 1. **Modern API Development**\n * - Mobile and web applications\n * - Microservices federation\n * - Real-time dashboards\n * \n * 2. **Data Aggregation**\n * - Multi-source data integration\n * - Complex nested queries\n * - Efficient data loading\n * \n * 3. **Developer Experience**\n * - Self-documenting API\n * - Type safety and validation\n * - GraphQL playground\n * \n * @see https://graphql.org/\n * @see https://spec.graphql.org/\n * \n * @example GraphQL Query\n * ```graphql\n * query GetCustomer($id: ID!) {\n * customer(id: $id) {\n * id\n * name\n * email\n * orders(limit: 10, status: \"active\") {\n * id\n * total\n * items {\n * product {\n * name\n * price\n * }\n * }\n * }\n * }\n * }\n * ```\n * \n * @example GraphQL Mutation\n * ```graphql\n * mutation CreateOrder($input: CreateOrderInput!) {\n * createOrder(input: $input) {\n * id\n * orderNumber\n * status\n * }\n * }\n * ```\n */\n\n// ==========================================\n// 1. GraphQL Type System\n// ==========================================\n\n/**\n * GraphQL Scalar Types\n * \n * Built-in scalar types in GraphQL plus custom scalars.\n */\nexport const GraphQLScalarType = z.enum([\n // Built-in GraphQL Scalars\n 'ID',\n 'String',\n 'Int',\n 'Float',\n 'Boolean',\n \n // Extended Scalars (common custom types)\n 'DateTime',\n 'Date',\n 'Time',\n 'JSON',\n 'JSONObject',\n 'Upload',\n 'URL',\n 'Email',\n 'PhoneNumber',\n 'Currency',\n 'Decimal',\n 'BigInt',\n 'Long',\n 'UUID',\n 'Base64',\n 'Void',\n]);\n\nexport type GraphQLScalarType = z.infer;\n\n/**\n * GraphQL Type Configuration\n * \n * Configuration for generating GraphQL types from Object definitions.\n */\nexport const GraphQLTypeConfigSchema = z.object({\n /** Type name in GraphQL schema */\n name: z.string().describe('GraphQL type name (PascalCase recommended)'),\n \n /** Source Object name */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Description for GraphQL schema documentation */\n description: z.string().optional().describe('Type description'),\n \n /** Fields to include/exclude */\n fields: z.object({\n /** Include only these fields (allow list) */\n include: z.array(z.string()).optional().describe('Fields to include'),\n \n /** Exclude these fields (deny list) */\n exclude: z.array(z.string()).optional().describe('Fields to exclude (e.g., sensitive fields)'),\n \n /** Custom field mappings */\n mappings: z.record(z.string(), z.object({\n graphqlName: z.string().optional().describe('Custom GraphQL field name'),\n graphqlType: z.string().optional().describe('Override GraphQL type'),\n description: z.string().optional().describe('Field description'),\n deprecationReason: z.string().optional().describe('Why field is deprecated'),\n nullable: z.boolean().optional().describe('Override nullable'),\n })).optional().describe('Field-level customizations'),\n }).optional().describe('Field configuration'),\n \n /** Interfaces this type implements */\n interfaces: z.array(z.string()).optional().describe('GraphQL interface names'),\n \n /** Whether this is an interface definition */\n isInterface: z.boolean().optional().default(false).describe('Define as GraphQL interface'),\n \n /** Custom directives */\n directives: z.array(z.object({\n name: z.string().describe('Directive name'),\n args: z.record(z.string(), z.unknown()).optional().describe('Directive arguments'),\n })).optional().describe('GraphQL directives'),\n});\n\nexport type GraphQLTypeConfig = z.infer;\nexport type GraphQLTypeConfigInput = z.input;\n\n// ==========================================\n// 2. Query Generation Configuration\n// ==========================================\n\n/**\n * GraphQL Query Configuration\n * \n * Configuration for auto-generating query fields from Objects.\n */\nexport const GraphQLQueryConfigSchema = z.object({\n /** Query name */\n name: z.string().describe('Query field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Query type: single record or list */\n type: z.enum(['get', 'list', 'search']).describe('Query type'),\n \n /** Description */\n description: z.string().optional().describe('Query description'),\n \n /** Input arguments */\n args: z.record(z.string(), z.object({\n type: z.string().describe('GraphQL type (e.g., \"ID!\", \"String\", \"Int\")'),\n description: z.string().optional().describe('Argument description'),\n defaultValue: z.unknown().optional().describe('Default value'),\n })).optional().describe('Query arguments'),\n \n /** Filtering configuration */\n filtering: z.object({\n enabled: z.boolean().default(true).describe('Allow filtering'),\n fields: z.array(z.string()).optional().describe('Filterable fields'),\n operators: z.array(z.enum([\n 'eq', 'ne', 'gt', 'gte', 'lt', 'lte',\n 'in', 'notIn', 'contains', 'startsWith', 'endsWith',\n 'isNull', 'isNotNull',\n ])).optional().describe('Allowed filter operators'),\n }).optional().describe('Filtering capabilities'),\n \n /** Sorting configuration */\n sorting: z.object({\n enabled: z.boolean().default(true).describe('Allow sorting'),\n fields: z.array(z.string()).optional().describe('Sortable fields'),\n defaultSort: z.object({\n field: z.string(),\n direction: z.enum(['ASC', 'DESC']),\n }).optional().describe('Default sort order'),\n }).optional().describe('Sorting capabilities'),\n \n /** Pagination configuration */\n pagination: z.object({\n enabled: z.boolean().default(true).describe('Enable pagination'),\n type: z.enum(['offset', 'cursor', 'relay']).default('offset').describe('Pagination style'),\n defaultLimit: z.number().int().min(1).default(20).describe('Default page size'),\n maxLimit: z.number().int().min(1).default(100).describe('Maximum page size'),\n cursors: z.object({\n field: z.string().default('id').describe('Field to use for cursor pagination'),\n }).optional(),\n }).optional().describe('Pagination configuration'),\n \n /** Field selection */\n fields: z.object({\n /** Always include these fields */\n required: z.array(z.string()).optional().describe('Required fields (always returned)'),\n \n /** Allow selecting these fields */\n selectable: z.array(z.string()).optional().describe('Selectable fields'),\n }).optional().describe('Field selection configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(false).describe('Enable caching'),\n ttl: z.number().int().min(0).optional().describe('Cache TTL in seconds'),\n key: z.string().optional().describe('Cache key template'),\n }).optional().describe('Query caching'),\n});\n\nexport type GraphQLQueryConfig = z.infer;\nexport type GraphQLQueryConfigInput = z.input;\n\n// ==========================================\n// 3. Mutation Generation Configuration\n// ==========================================\n\n/**\n * GraphQL Mutation Configuration\n * \n * Configuration for auto-generating mutation fields from Objects.\n */\nexport const GraphQLMutationConfigSchema = z.object({\n /** Mutation name */\n name: z.string().describe('Mutation field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Mutation type */\n type: z.enum(['create', 'update', 'delete', 'upsert', 'custom']).describe('Mutation type'),\n \n /** Description */\n description: z.string().optional().describe('Mutation description'),\n \n /** Input type configuration */\n input: z.object({\n /** Input type name */\n typeName: z.string().optional().describe('Custom input type name'),\n \n /** Fields to include in input */\n fields: z.object({\n include: z.array(z.string()).optional().describe('Fields to include'),\n exclude: z.array(z.string()).optional().describe('Fields to exclude'),\n required: z.array(z.string()).optional().describe('Required input fields'),\n }).optional().describe('Input field configuration'),\n \n /** Validation */\n validation: z.object({\n enabled: z.boolean().default(true).describe('Enable input validation'),\n rules: z.array(z.string()).optional().describe('Custom validation rules'),\n }).optional().describe('Input validation'),\n }).optional().describe('Input configuration'),\n \n /** Return type configuration */\n output: z.object({\n /** Type of output */\n type: z.enum(['object', 'payload', 'boolean', 'custom']).default('object').describe('Output type'),\n \n /** Include success/error envelope */\n includeEnvelope: z.boolean().optional().default(false).describe('Wrap in success/error payload'),\n \n /** Custom output type */\n customType: z.string().optional().describe('Custom output type name'),\n }).optional().describe('Output configuration'),\n \n /** Transaction handling */\n transaction: z.object({\n enabled: z.boolean().default(true).describe('Use database transaction'),\n isolationLevel: z.enum(['read_uncommitted', 'read_committed', 'repeatable_read', 'serializable']).optional().describe('Transaction isolation level'),\n }).optional().describe('Transaction configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Hooks */\n hooks: z.object({\n before: z.array(z.string()).optional().describe('Pre-mutation hooks'),\n after: z.array(z.string()).optional().describe('Post-mutation hooks'),\n }).optional().describe('Lifecycle hooks'),\n});\n\nexport type GraphQLMutationConfig = z.infer;\nexport type GraphQLMutationConfigInput = z.input;\n\n// ==========================================\n// 4. Subscription Configuration\n// ==========================================\n\n/**\n * GraphQL Subscription Configuration\n * \n * Configuration for real-time GraphQL subscriptions.\n */\nexport const GraphQLSubscriptionConfigSchema = z.object({\n /** Subscription name */\n name: z.string().describe('Subscription field name (camelCase recommended)'),\n \n /** Source Object */\n object: z.string().describe('Source ObjectQL object name'),\n \n /** Subscription trigger events */\n events: z.array(z.enum(['created', 'updated', 'deleted', 'custom'])).describe('Events to subscribe to'),\n \n /** Description */\n description: z.string().optional().describe('Subscription description'),\n \n /** Filtering */\n filter: z.object({\n enabled: z.boolean().default(true).describe('Allow filtering subscriptions'),\n fields: z.array(z.string()).optional().describe('Filterable fields'),\n }).optional().describe('Subscription filtering'),\n \n /** Payload configuration */\n payload: z.object({\n /** Include the modified entity */\n includeEntity: z.boolean().default(true).describe('Include entity in payload'),\n \n /** Include previous values (for updates) */\n includePreviousValues: z.boolean().optional().default(false).describe('Include previous field values'),\n \n /** Include mutation metadata */\n includeMeta: z.boolean().optional().default(true).describe('Include metadata (timestamp, user, etc.)'),\n }).optional().describe('Payload configuration'),\n \n /** Authorization */\n authRequired: z.boolean().default(true).describe('Require authentication'),\n permissions: z.array(z.string()).optional().describe('Required permissions'),\n \n /** Rate limiting for subscriptions */\n rateLimit: z.object({\n enabled: z.boolean().default(true).describe('Enable rate limiting'),\n maxSubscriptionsPerUser: z.number().int().min(1).default(10).describe('Max concurrent subscriptions per user'),\n throttleMs: z.number().int().min(0).optional().describe('Throttle interval in milliseconds'),\n }).optional().describe('Subscription rate limiting'),\n});\n\nexport type GraphQLSubscriptionConfig = z.infer;\nexport type GraphQLSubscriptionConfigInput = z.input;\n\n// ==========================================\n// 5. Resolver Configuration\n// ==========================================\n\n/**\n * GraphQL Resolver Configuration\n * \n * Configuration for custom resolver logic.\n */\nexport const GraphQLResolverConfigSchema = z.object({\n /** Field path (e.g., \"Query.users\", \"Mutation.createUser\") */\n path: z.string().describe('Resolver path (Type.field)'),\n \n /** Resolver implementation type */\n type: z.enum(['datasource', 'computed', 'script', 'proxy']).describe('Resolver implementation type'),\n \n /** Implementation details */\n implementation: z.object({\n /** For datasource type */\n datasource: z.string().optional().describe('Datasource ID'),\n query: z.string().optional().describe('Query/SQL to execute'),\n \n /** For computed type */\n expression: z.string().optional().describe('Computation expression'),\n dependencies: z.array(z.string()).optional().describe('Dependent fields'),\n \n /** For script type */\n script: z.string().optional().describe('Script ID or inline code'),\n \n /** For proxy type */\n url: z.string().optional().describe('Proxy URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).optional().describe('HTTP method'),\n }).optional().describe('Implementation configuration'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(false).describe('Enable resolver caching'),\n ttl: z.number().int().min(0).optional().describe('Cache TTL in seconds'),\n keyArgs: z.array(z.string()).optional().describe('Arguments to include in cache key'),\n }).optional().describe('Resolver caching'),\n});\n\nexport type GraphQLResolverConfig = z.infer;\nexport type GraphQLResolverConfigInput = z.input;\n\n// ==========================================\n// 6. DataLoader Configuration\n// ==========================================\n\n/**\n * GraphQL DataLoader Configuration\n * \n * Configuration for batching and caching with DataLoader pattern.\n * Prevents N+1 query problems in GraphQL.\n */\nexport const GraphQLDataLoaderConfigSchema = z.object({\n /** Loader name */\n name: z.string().describe('DataLoader name'),\n \n /** Source Object or datasource */\n source: z.string().describe('Source object or datasource'),\n \n /** Batch function configuration */\n batchFunction: z.object({\n /** Type of batch operation */\n type: z.enum(['findByIds', 'query', 'script', 'custom']).describe('Batch function type'),\n \n /** For findByIds */\n keyField: z.string().optional().describe('Field to batch on (e.g., \"id\")'),\n \n /** For query */\n query: z.string().optional().describe('Query template'),\n \n /** For script */\n script: z.string().optional().describe('Script ID'),\n \n /** Maximum batch size */\n maxBatchSize: z.number().int().min(1).optional().default(100).describe('Maximum batch size'),\n }).describe('Batch function configuration'),\n \n /** Caching */\n cache: z.object({\n enabled: z.boolean().default(true).describe('Enable per-request caching'),\n \n /** Cache key function */\n keyFn: z.string().optional().describe('Custom cache key function'),\n }).optional().describe('DataLoader caching'),\n \n /** Options */\n options: z.object({\n /** Batch multiple requests in single tick */\n batch: z.boolean().default(true).describe('Enable batching'),\n \n /** Cache loaded values */\n cache: z.boolean().default(true).describe('Enable caching'),\n \n /** Maximum cache size */\n maxCacheSize: z.number().int().min(0).optional().describe('Max cache entries'),\n }).optional().describe('DataLoader options'),\n});\n\nexport type GraphQLDataLoaderConfig = z.infer;\nexport type GraphQLDataLoaderConfigInput = z.input;\n\n// ==========================================\n// 7. GraphQL Directive Schema\n// ==========================================\n\n/**\n * GraphQL Directive Location\n * \n * Where a directive can be used in the schema.\n */\nexport const GraphQLDirectiveLocation = z.enum([\n // Executable Directive Locations\n 'QUERY',\n 'MUTATION',\n 'SUBSCRIPTION',\n 'FIELD',\n 'FRAGMENT_DEFINITION',\n 'FRAGMENT_SPREAD',\n 'INLINE_FRAGMENT',\n 'VARIABLE_DEFINITION',\n \n // Type System Directive Locations\n 'SCHEMA',\n 'SCALAR',\n 'OBJECT',\n 'FIELD_DEFINITION',\n 'ARGUMENT_DEFINITION',\n 'INTERFACE',\n 'UNION',\n 'ENUM',\n 'ENUM_VALUE',\n 'INPUT_OBJECT',\n 'INPUT_FIELD_DEFINITION',\n]);\n\nexport type GraphQLDirectiveLocation = z.infer;\n\n/**\n * GraphQL Directive Configuration\n * \n * Custom directives for schema metadata and behavior.\n */\nexport const GraphQLDirectiveConfigSchema = z.object({\n /** Directive name */\n name: z.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe('Directive name (camelCase)'),\n \n /** Description */\n description: z.string().optional().describe('Directive description'),\n \n /** Where directive can be used */\n locations: z.array(GraphQLDirectiveLocation).describe('Directive locations'),\n \n /** Arguments */\n args: z.record(z.string(), z.object({\n type: z.string().describe('Argument type'),\n description: z.string().optional().describe('Argument description'),\n defaultValue: z.unknown().optional().describe('Default value'),\n })).optional().describe('Directive arguments'),\n \n /** Is repeatable */\n repeatable: z.boolean().optional().default(false).describe('Can be applied multiple times'),\n \n /** Implementation */\n implementation: z.object({\n /** Directive behavior type */\n type: z.enum(['auth', 'validation', 'transform', 'cache', 'deprecation', 'custom']).describe('Directive type'),\n \n /** Handler function */\n handler: z.string().optional().describe('Handler function name or script'),\n }).optional().describe('Directive implementation'),\n});\n\nexport type GraphQLDirectiveConfig = z.infer;\nexport type GraphQLDirectiveConfigInput = z.input;\n\n// ==========================================\n// 8. GraphQL Security - Query Depth Limiting\n// ==========================================\n\n/**\n * Query Depth Limiting Configuration\n * \n * Prevents deeply nested queries that could cause performance issues.\n */\nexport const GraphQLQueryDepthLimitSchema = z.object({\n /** Enable depth limiting */\n enabled: z.boolean().default(true).describe('Enable query depth limiting'),\n \n /** Maximum allowed depth */\n maxDepth: z.number().int().min(1).default(10).describe('Maximum query depth'),\n \n /** Fields to ignore in depth calculation */\n ignoreFields: z.array(z.string()).optional().describe('Fields excluded from depth calculation'),\n \n /** Callback on depth exceeded */\n onDepthExceeded: z.enum(['reject', 'log', 'warn']).default('reject').describe('Action when depth exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for depth violations'),\n});\n\nexport type GraphQLQueryDepthLimit = z.infer;\nexport type GraphQLQueryDepthLimitInput = z.input;\n\n// ==========================================\n// 9. GraphQL Security - Query Complexity\n// ==========================================\n\n/**\n * Query Complexity Calculation Configuration\n * \n * Assigns complexity scores to fields and limits total query complexity.\n * Prevents expensive queries from overloading the server.\n */\nexport const GraphQLQueryComplexitySchema = z.object({\n /** Enable complexity limiting */\n enabled: z.boolean().default(true).describe('Enable query complexity limiting'),\n \n /** Maximum allowed complexity score */\n maxComplexity: z.number().int().min(1).default(1000).describe('Maximum query complexity'),\n \n /** Default field complexity */\n defaultFieldComplexity: z.number().int().min(0).default(1).describe('Default complexity per field'),\n \n /** Field-specific complexity scores */\n fieldComplexity: z.record(z.string(), z.union([\n z.number().int().min(0),\n z.object({\n /** Base complexity */\n base: z.number().int().min(0).describe('Base complexity'),\n \n /** Multiplier based on arguments */\n multiplier: z.string().optional().describe('Argument multiplier (e.g., \"limit\")'),\n \n /** Custom complexity calculation */\n calculator: z.string().optional().describe('Custom calculator function'),\n }),\n ])).optional().describe('Per-field complexity configuration'),\n \n /** List multiplier */\n listMultiplier: z.number().min(0).default(10).describe('Multiplier for list fields'),\n \n /** Callback on complexity exceeded */\n onComplexityExceeded: z.enum(['reject', 'log', 'warn']).default('reject').describe('Action when complexity exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for complexity violations'),\n});\n\nexport type GraphQLQueryComplexity = z.infer;\nexport type GraphQLQueryComplexityInput = z.input;\n\n// ==========================================\n// 10. GraphQL Security - Rate Limiting\n// ==========================================\n\n/**\n * GraphQL Rate Limiting Configuration\n * \n * Rate limiting for GraphQL operations.\n */\nexport const GraphQLRateLimitSchema = z.object({\n /** Enable rate limiting */\n enabled: z.boolean().default(true).describe('Enable rate limiting'),\n \n /** Rate limit strategy */\n strategy: z.enum(['token_bucket', 'fixed_window', 'sliding_window', 'cost_based']).default('token_bucket').describe('Rate limiting strategy'),\n \n /** Global rate limits */\n global: z.object({\n /** Requests per time window */\n maxRequests: z.number().int().min(1).default(1000).describe('Maximum requests per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n }).optional().describe('Global rate limits'),\n \n /** Per-user rate limits */\n perUser: z.object({\n /** Requests per time window */\n maxRequests: z.number().int().min(1).default(100).describe('Maximum requests per user per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n }).optional().describe('Per-user rate limits'),\n \n /** Cost-based rate limiting */\n costBased: z.object({\n /** Enable cost-based limiting */\n enabled: z.boolean().default(false).describe('Enable cost-based rate limiting'),\n \n /** Maximum cost per time window */\n maxCost: z.number().int().min(1).default(10000).describe('Maximum cost per window'),\n \n /** Time window in milliseconds */\n windowMs: z.number().int().min(1000).default(60000).describe('Time window in milliseconds'),\n \n /** Use complexity as cost */\n useComplexityAsCost: z.boolean().default(true).describe('Use query complexity as cost'),\n }).optional().describe('Cost-based rate limiting'),\n \n /** Operation-specific limits */\n operations: z.record(z.string(), z.object({\n maxRequests: z.number().int().min(1).describe('Max requests for this operation'),\n windowMs: z.number().int().min(1000).describe('Time window'),\n })).optional().describe('Per-operation rate limits'),\n \n /** Callback on limit exceeded */\n onLimitExceeded: z.enum(['reject', 'queue', 'log']).default('reject').describe('Action when rate limit exceeded'),\n \n /** Custom error message */\n errorMessage: z.string().optional().describe('Custom error message for rate limit violations'),\n \n /** Headers to include in response */\n includeHeaders: z.boolean().default(true).describe('Include rate limit headers in response'),\n});\n\nexport type GraphQLRateLimit = z.infer;\nexport type GraphQLRateLimitInput = z.input;\n\n// ==========================================\n// 11. GraphQL Security - Persisted Queries\n// ==========================================\n\n/**\n * Persisted Queries Configuration\n * \n * Only allow pre-registered queries to execute (allow list approach).\n * Improves security and performance.\n */\nexport const GraphQLPersistedQuerySchema = z.object({\n /** Enable persisted queries */\n enabled: z.boolean().default(false).describe('Enable persisted queries'),\n \n /** Enforcement mode */\n mode: z.enum(['optional', 'required']).default('optional').describe('Persisted query mode (optional: allow both, required: only persisted)'),\n \n /** Query store configuration */\n store: z.object({\n /** Store type */\n type: z.enum(['memory', 'redis', 'database', 'file']).default('memory').describe('Query store type'),\n \n /** Store connection string */\n connection: z.string().optional().describe('Store connection string or path'),\n \n /** TTL for cached queries */\n ttl: z.number().int().min(0).optional().describe('TTL in seconds for stored queries'),\n }).optional().describe('Query store configuration'),\n \n /** Automatic Persisted Queries (APQ) */\n apq: z.object({\n /** Enable APQ */\n enabled: z.boolean().default(true).describe('Enable Automatic Persisted Queries'),\n \n /** Hash algorithm */\n hashAlgorithm: z.enum(['sha256', 'sha1', 'md5']).default('sha256').describe('Hash algorithm for query IDs'),\n \n /** Cache control */\n cache: z.object({\n /** Cache TTL */\n ttl: z.number().int().min(0).default(3600).describe('Cache TTL in seconds'),\n \n /** Max cache size */\n maxSize: z.number().int().min(1).optional().describe('Maximum number of cached queries'),\n }).optional().describe('APQ cache configuration'),\n }).optional().describe('Automatic Persisted Queries configuration'),\n \n /** Query allow list */\n allowlist: z.object({\n /** Enable allow list mode */\n enabled: z.boolean().default(false).describe('Enable query allow list (reject queries not in list)'),\n \n /** Allowed query IDs */\n queries: z.array(z.object({\n id: z.string().describe('Query ID or hash'),\n operation: z.string().optional().describe('Operation name'),\n query: z.string().optional().describe('Query string'),\n })).optional().describe('Allowed queries'),\n \n /** External allow list source */\n source: z.string().optional().describe('External allow list source (file path or URL)'),\n }).optional().describe('Query allow list configuration'),\n \n /** Security */\n security: z.object({\n /** Maximum query size */\n maxQuerySize: z.number().int().min(1).optional().describe('Maximum query string size in bytes'),\n \n /** Reject introspection in production */\n rejectIntrospection: z.boolean().default(false).describe('Reject introspection queries'),\n }).optional().describe('Security configuration'),\n});\n\nexport type GraphQLPersistedQuery = z.infer;\nexport type GraphQLPersistedQueryInput = z.input;\n\n// ==========================================\n// 12. GraphQL Federation\n// ==========================================\n\n/**\n * Federation Entity Key Definition\n * \n * Defines how entities are uniquely identified across subgraphs.\n * Corresponds to the `@key` directive in Apollo Federation.\n * \n * @see https://www.apollographql.com/docs/federation/entities\n */\nexport const FederationEntityKeySchema = z.object({\n /** Fields composing the key (e.g., \"id\" or \"sku packageId\") */\n fields: z.string().describe('Selection set of fields composing the entity key'),\n\n /** Whether this key can be used for resolution across subgraphs */\n resolvable: z.boolean().optional().default(true).describe('Whether entities can be resolved from this subgraph'),\n});\n\nexport type FederationEntityKey = z.infer;\n\n/**\n * Federation External Field\n * \n * Marks a field as owned by another subgraph (`@external`).\n */\nexport const FederationExternalFieldSchema = z.object({\n /** Field name */\n field: z.string().describe('Field name marked as external'),\n\n /** The subgraph that owns this field */\n ownerSubgraph: z.string().optional().describe('Subgraph that owns this field'),\n});\n\nexport type FederationExternalField = z.infer;\n\n/**\n * Federation Requires Directive\n * \n * Specifies fields that must be fetched from other subgraphs\n * before resolving a computed field.\n * Corresponds to the `@requires` directive in Apollo Federation.\n */\nexport const FederationRequiresSchema = z.object({\n /** The field that has this requirement */\n field: z.string().describe('Field with the requirement'),\n\n /** Selection set of external fields required for resolution */\n fields: z.string().describe('Selection set of required fields (e.g., \"price weight\")'),\n});\n\nexport type FederationRequires = z.infer;\n\n/**\n * Federation Provides Directive\n * \n * Indicates that a field resolution provides additional fields\n * of a returned entity type.\n * Corresponds to the `@provides` directive in Apollo Federation.\n */\nexport const FederationProvidesSchema = z.object({\n /** The field that provides additional data */\n field: z.string().describe('Field that provides additional entity fields'),\n\n /** Selection set of fields provided during resolution */\n fields: z.string().describe('Selection set of provided fields (e.g., \"name price\")'),\n});\n\nexport type FederationProvides = z.infer;\n\n/**\n * Federation Entity Configuration\n * \n * Configures a type as a federated entity that can be referenced\n * and extended across multiple subgraphs.\n */\nexport const FederationEntitySchema = z.object({\n /** Type/Object name */\n typeName: z.string().describe('GraphQL type name for this entity'),\n\n /** Entity keys (`@key` directive) */\n keys: z.array(FederationEntityKeySchema).min(1).describe('Entity key definitions'),\n\n /** External fields (`@external`) */\n externalFields: z.array(FederationExternalFieldSchema).optional().describe('Fields owned by other subgraphs'),\n\n /** Requires directives (`@requires`) */\n requires: z.array(FederationRequiresSchema).optional().describe('Required external fields for computed fields'),\n\n /** Provides directives (`@provides`) */\n provides: z.array(FederationProvidesSchema).optional().describe('Fields provided during resolution'),\n\n /** Whether this subgraph owns this entity */\n owner: z.boolean().optional().default(false).describe('Whether this subgraph is the owner of this entity'),\n});\n\nexport type FederationEntity = z.infer;\n\n/**\n * Subgraph Configuration\n * \n * Configuration for an individual subgraph in a federated architecture.\n */\nexport const SubgraphConfigSchema = z.object({\n /** Subgraph name */\n name: z.string().describe('Unique subgraph identifier'),\n\n /** Subgraph URL */\n url: z.string().describe('Subgraph endpoint URL'),\n\n /** Schema source */\n schemaSource: z.enum(['introspection', 'file', 'registry']).default('introspection').describe('How to obtain the subgraph schema'),\n\n /** Schema file path (when schemaSource is \"file\") */\n schemaPath: z.string().optional().describe('Path to schema file (SDL format)'),\n\n /** Federated entities defined by this subgraph */\n entities: z.array(FederationEntitySchema).optional().describe('Entity definitions for this subgraph'),\n\n /** Health check endpoint */\n healthCheck: z.object({\n enabled: z.boolean().default(true).describe('Enable health checking'),\n path: z.string().default('/health').describe('Health check endpoint path'),\n intervalMs: z.number().int().min(1000).default(30000).describe('Health check interval in milliseconds'),\n }).optional().describe('Subgraph health check configuration'),\n\n /** Request headers to forward */\n forwardHeaders: z.array(z.string()).optional().describe('HTTP headers to forward to this subgraph'),\n});\n\nexport type SubgraphConfig = z.infer;\nexport type SubgraphConfigInput = z.input;\n\n/**\n * Federation Gateway Configuration\n * \n * Root-level gateway configuration for Apollo Federation or similar.\n * Manages query planning, routing, and composition across subgraphs.\n */\nexport const FederationGatewaySchema = z.object({\n /** Enable federation mode */\n enabled: z.boolean().default(false).describe('Enable GraphQL Federation gateway mode'),\n\n /** Federation specification version */\n version: z.enum(['v1', 'v2']).default('v2').describe('Federation specification version'),\n\n /** Registered subgraphs */\n subgraphs: z.array(SubgraphConfigSchema).describe('Subgraph configurations'),\n\n /** Service discovery */\n serviceDiscovery: z.object({\n /** Discovery mode */\n type: z.enum(['static', 'dns', 'consul', 'kubernetes']).default('static').describe('Service discovery method'),\n\n /** Poll interval for dynamic discovery */\n pollIntervalMs: z.number().int().min(1000).optional().describe('Discovery poll interval in milliseconds'),\n\n /** Kubernetes namespace (when type is \"kubernetes\") */\n namespace: z.string().optional().describe('Kubernetes namespace for subgraph discovery'),\n }).optional().describe('Service discovery configuration'),\n\n /** Query planning */\n queryPlanning: z.object({\n /** Execution strategy */\n strategy: z.enum(['parallel', 'sequential', 'adaptive']).default('parallel').describe('Query execution strategy across subgraphs'),\n\n /** Maximum query depth across subgraphs */\n maxDepth: z.number().int().min(1).optional().describe('Max query depth in federated execution'),\n\n /** Dry-run mode for debugging query plans */\n dryRun: z.boolean().optional().default(false).describe('Log query plans without executing'),\n }).optional().describe('Query planning configuration'),\n\n /** Schema composition settings */\n composition: z.object({\n /** How schema conflicts are resolved */\n conflictResolution: z.enum(['error', 'first_wins', 'last_wins']).default('error').describe('Strategy for resolving schema conflicts'),\n\n /** Whether to validate composed schema */\n validate: z.boolean().default(true).describe('Validate composed supergraph schema'),\n }).optional().describe('Schema composition configuration'),\n\n /** Gateway-level error handling */\n errorHandling: z.object({\n /** Whether to include subgraph names in errors */\n includeSubgraphName: z.boolean().default(false).describe('Include subgraph name in error responses'),\n\n /** Partial error behavior */\n partialErrors: z.enum(['propagate', 'nullify', 'reject']).default('propagate').describe('Behavior when a subgraph returns partial errors'),\n }).optional().describe('Error handling configuration'),\n});\n\nexport type FederationGateway = z.infer;\nexport type FederationGatewayInput = z.input;\n\n// ==========================================\n// 13. Complete GraphQL Configuration\n// ==========================================\n\n/**\n * Complete GraphQL Configuration\n * \n * Root configuration for GraphQL API generation and security.\n */\nexport const GraphQLConfigSchema = z.object({\n /** Enable GraphQL API */\n enabled: z.boolean().default(true).describe('Enable GraphQL API'),\n \n /** GraphQL endpoint path */\n path: z.string().default('/graphql').describe('GraphQL endpoint path'),\n \n /** GraphQL Playground */\n playground: z.object({\n enabled: z.boolean().default(true).describe('Enable GraphQL Playground'),\n path: z.string().default('/playground').describe('Playground path'),\n }).optional().describe('GraphQL Playground configuration'),\n \n /** Schema generation */\n schema: z.object({\n /** Auto-generate types from Objects */\n autoGenerateTypes: z.boolean().default(true).describe('Auto-generate types from Objects'),\n \n /** Type configurations */\n types: z.array(GraphQLTypeConfigSchema).optional().describe('Type configurations'),\n \n /** Query configurations */\n queries: z.array(GraphQLQueryConfigSchema).optional().describe('Query configurations'),\n \n /** Mutation configurations */\n mutations: z.array(GraphQLMutationConfigSchema).optional().describe('Mutation configurations'),\n \n /** Subscription configurations */\n subscriptions: z.array(GraphQLSubscriptionConfigSchema).optional().describe('Subscription configurations'),\n \n /** Custom resolvers */\n resolvers: z.array(GraphQLResolverConfigSchema).optional().describe('Custom resolver configurations'),\n \n /** Custom directives */\n directives: z.array(GraphQLDirectiveConfigSchema).optional().describe('Custom directive configurations'),\n }).optional().describe('Schema generation configuration'),\n \n /** DataLoader configurations */\n dataLoaders: z.array(GraphQLDataLoaderConfigSchema).optional().describe('DataLoader configurations'),\n \n /** Security configuration */\n security: z.object({\n /** Query depth limiting */\n depthLimit: GraphQLQueryDepthLimitSchema.optional().describe('Query depth limiting'),\n \n /** Query complexity */\n complexity: GraphQLQueryComplexitySchema.optional().describe('Query complexity calculation'),\n \n /** Rate limiting */\n rateLimit: GraphQLRateLimitSchema.optional().describe('Rate limiting'),\n \n /** Persisted queries */\n persistedQueries: GraphQLPersistedQuerySchema.optional().describe('Persisted queries'),\n }).optional().describe('Security configuration'),\n\n /** Federation configuration */\n federation: FederationGatewaySchema.optional().describe('GraphQL Federation gateway configuration'),\n});\n\nexport const GraphQLConfig = Object.assign(GraphQLConfigSchema, {\n create: >(config: T) => config,\n});\n\nexport type GraphQLConfig = z.infer;\nexport type GraphQLConfigInput = z.input;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to map ObjectQL field type to GraphQL scalar type\n */\nexport const mapFieldTypeToGraphQL = (fieldType: z.infer): string => {\n const mapping: Record = {\n // Core Text\n 'text': 'String',\n 'textarea': 'String',\n 'email': 'Email',\n 'url': 'URL',\n 'phone': 'PhoneNumber',\n 'password': 'String',\n \n // Rich Content\n 'markdown': 'String',\n 'html': 'String',\n 'richtext': 'String',\n \n // Numbers\n 'number': 'Float',\n 'currency': 'Currency',\n 'percent': 'Float',\n \n // Date & Time\n 'date': 'Date',\n 'datetime': 'DateTime',\n 'time': 'Time',\n \n // Logic\n 'boolean': 'Boolean',\n 'toggle': 'Boolean',\n \n // Selection\n 'select': 'String',\n 'multiselect': '[String]',\n 'radio': 'String',\n 'checkboxes': '[String]',\n \n // Relational\n 'lookup': 'ID',\n 'master_detail': 'ID',\n 'tree': 'ID',\n \n // Media\n 'image': 'URL',\n 'file': 'URL',\n 'avatar': 'URL',\n 'video': 'URL',\n 'audio': 'URL',\n \n // Calculated\n 'formula': 'String',\n 'summary': 'Float',\n 'autonumber': 'String',\n \n // Enhanced Types\n 'location': 'JSONObject',\n 'address': 'JSONObject',\n 'code': 'String',\n 'json': 'JSON',\n 'color': 'String',\n 'rating': 'Float',\n 'slider': 'Float',\n 'signature': 'String',\n 'qrcode': 'String',\n 'progress': 'Float',\n 'tags': '[String]',\n \n // AI/ML\n 'vector': '[Float]',\n };\n \n return mapping[fieldType] || 'String';\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ApiErrorSchema, BaseResponseSchema, RecordDataSchema } from './contract.zod';\n\n/**\n * Batch Operations API\n * \n * Provides efficient bulk data operations with transaction support.\n * Implements P0/P1 requirements for ObjectStack kernel.\n * \n * Features:\n * - Batch create/update/delete operations\n * - Atomic transaction support (all-or-none)\n * - Partial success handling\n * - Detailed error reporting per record\n * \n * Industry alignment: Salesforce Bulk API, Microsoft Dynamics Bulk Operations\n */\n\n// ==========================================\n// Batch Operation Types\n// ==========================================\n\n/**\n * Batch Operation Type Enum\n * Defines the type of batch operation to perform\n */\nexport const BatchOperationType = z.enum([\n 'create', // Batch insert\n 'update', // Batch update\n 'upsert', // Batch upsert (insert or update based on external ID)\n 'delete', // Batch delete\n]);\n\nexport type BatchOperationType = z.infer;\n\n// ==========================================\n// Batch Request Schemas\n// ==========================================\n\n/**\n * Batch Record Schema\n * Individual record in a batch operation\n */\nexport const BatchRecordSchema = z.object({\n id: z.string().optional().describe('Record ID (required for update/delete)'),\n data: RecordDataSchema.optional().describe('Record data (required for create/update/upsert)'),\n externalId: z.string().optional().describe('External ID for upsert matching'),\n});\n\nexport type BatchRecord = z.infer;\n\n/**\n * Batch Operation Options Schema\n * Configuration options for batch operations\n */\nexport const BatchOptionsSchema = z.object({\n atomic: z.boolean().optional().default(true).describe('If true, rollback entire batch on any failure (transaction mode)'),\n returnRecords: z.boolean().optional().default(false).describe('If true, return full record data in response'),\n continueOnError: z.boolean().optional().default(false).describe('If true (and atomic=false), continue processing remaining records after errors'),\n validateOnly: z.boolean().optional().default(false).describe('If true, validate records without persisting changes (dry-run mode)'),\n});\n\nexport type BatchOptions = z.infer;\n\n/**\n * Batch Update Request Schema\n * Request payload for batch update operations\n * \n * @example\n * // POST /api/v1/data/{object}/batch\n * {\n * \"operation\": \"update\",\n * \"records\": [\n * { \"id\": \"1\", \"data\": { \"name\": \"Updated Name 1\", \"status\": \"active\" } },\n * { \"id\": \"2\", \"data\": { \"name\": \"Updated Name 2\", \"status\": \"active\" } }\n * ],\n * \"options\": {\n * \"atomic\": true,\n * \"returnRecords\": true\n * }\n * }\n */\nexport const BatchUpdateRequestSchema = z.object({\n operation: BatchOperationType.describe('Type of batch operation'),\n records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to process (max 200 per batch)'),\n options: BatchOptionsSchema.optional().describe('Batch operation options'),\n});\n\nexport type BatchUpdateRequest = z.input;\n\n/**\n * Simplified Batch Update Request (for updateMany API)\n * Simplified request for batch updates without operation field\n * \n * @example\n * // POST /api/v1/data/{object}/updateMany\n * {\n * \"records\": [\n * { \"id\": \"1\", \"data\": { \"name\": \"Updated Name 1\" } },\n * { \"id\": \"2\", \"data\": { \"name\": \"Updated Name 2\" } }\n * ],\n * \"options\": { \"atomic\": true }\n * }\n */\nexport const UpdateManyRequestSchema = z.object({\n records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to update (max 200 per batch)'),\n options: BatchOptionsSchema.optional().describe('Update options'),\n});\n\nexport type UpdateManyRequest = z.input;\n\n// ==========================================\n// Batch Response Schemas\n// ==========================================\n\n/**\n * Batch Operation Result Schema\n * Result for a single record in a batch operation\n */\nexport const BatchOperationResultSchema = z.object({\n id: z.string().optional().describe('Record ID if operation succeeded'),\n success: z.boolean().describe('Whether this record was processed successfully'),\n errors: z.array(ApiErrorSchema).optional().describe('Array of errors if operation failed'),\n data: RecordDataSchema.optional().describe('Full record data (if returnRecords=true)'),\n index: z.number().optional().describe('Index of the record in the request array'),\n});\n\nexport type BatchOperationResult = z.infer;\n\n/**\n * Batch Update Response Schema\n * Response payload for batch operations\n * \n * @example Success Response\n * {\n * \"success\": true,\n * \"operation\": \"update\",\n * \"total\": 2,\n * \"succeeded\": 2,\n * \"failed\": 0,\n * \"results\": [\n * { \"id\": \"1\", \"success\": true, \"index\": 0 },\n * { \"id\": \"2\", \"success\": true, \"index\": 1 }\n * ],\n * \"meta\": {\n * \"timestamp\": \"2026-01-29T12:00:00Z\",\n * \"duration\": 150\n * }\n * }\n * \n * @example Partial Success Response (atomic=false)\n * {\n * \"success\": false,\n * \"operation\": \"update\",\n * \"total\": 2,\n * \"succeeded\": 1,\n * \"failed\": 1,\n * \"results\": [\n * { \"id\": \"1\", \"success\": true, \"index\": 0 },\n * { \n * \"success\": false, \n * \"index\": 1,\n * \"errors\": [{ \"code\": \"validation_error\", \"message\": \"Invalid email format\" }]\n * }\n * ],\n * \"meta\": {\n * \"timestamp\": \"2026-01-29T12:00:00Z\"\n * }\n * }\n */\nexport const BatchUpdateResponseSchema = BaseResponseSchema.extend({\n operation: BatchOperationType.optional().describe('Operation type that was performed'),\n total: z.number().describe('Total number of records in the batch'),\n succeeded: z.number().describe('Number of records that succeeded'),\n failed: z.number().describe('Number of records that failed'),\n results: z.array(BatchOperationResultSchema).describe('Detailed results for each record'),\n});\n\nexport type BatchUpdateResponse = z.infer;\n\n// ==========================================\n// Batch Delete Schemas\n// ==========================================\n\n/**\n * Batch Delete Request Schema\n * Simplified request for batch delete operations\n * \n * @example\n * // POST /api/v1/data/{object}/deleteMany\n * {\n * \"ids\": [\"1\", \"2\", \"3\"],\n * \"options\": { \"atomic\": true }\n * }\n */\nexport const DeleteManyRequestSchema = z.object({\n ids: z.array(z.string()).min(1).max(200).describe('Array of record IDs to delete (max 200)'),\n options: BatchOptionsSchema.optional().describe('Delete options'),\n});\n\nexport type DeleteManyRequest = z.infer;\n\n// ==========================================\n// API Contract Exports\n// ==========================================\n\n/**\n * Batch API Contracts\n * Standardized contracts for batch operations\n */\nexport const BatchApiContracts = {\n batchOperation: {\n input: BatchUpdateRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n updateMany: {\n input: UpdateManyRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n deleteMany: {\n input: DeleteManyRequestSchema,\n output: BatchUpdateResponseSchema,\n },\n};\n\n/**\n * Batch Configuration Schema\n * \n * Configuration for enabling batch operations API.\n */\nexport const BatchConfigSchema = z.object({\n /** Enable batch operations */\n enabled: z.boolean().default(true).describe('Enable batch operations'),\n \n /** Maximum records per batch */\n maxRecordsPerBatch: z.number().int().min(1).max(1000).default(200).describe('Maximum records per batch'),\n \n /** Default options */\n defaultOptions: BatchOptionsSchema.optional().describe('Default batch options'),\n}).passthrough(); // Allow additional properties\n\nexport type BatchConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * HTTP Metadata Cache Protocol\n * \n * Implements efficient HTTP-level metadata caching with ETag support.\n * Implements P0 requirement for ObjectStack kernel.\n * \n * ## Caching in ObjectStack\n * \n * **HTTP Cache (`api/http-cache.zod.ts`) - This File**\n * - **Purpose**: Cache API responses at HTTP protocol level\n * - **Technologies**: HTTP headers (ETag, Last-Modified, Cache-Control), CDN\n * - **Configuration**: Cache-Control headers, validation tokens\n * - **Use case**: Reduce API response time for repeated metadata requests\n * - **Scope**: HTTP layer, client-server communication\n * \n * **Application Cache (`system/cache.zod.ts`)**\n * - **Purpose**: Cache computed data, query results, aggregations\n * - **Technologies**: Redis, Memcached, in-memory LRU\n * - **Configuration**: TTL, eviction policies, cache warming\n * - **Use case**: Cache expensive database queries, computed values\n * - **Scope**: Application layer, server-side data storage\n * \n * ## Features\n * - ETag-based conditional requests (HTTP 304 Not Modified)\n * - Cache-Control directives\n * - Metadata versioning\n * - Selective cache invalidation\n * \n * Industry alignment: HTTP Caching (RFC 7234), Salesforce Metadata API\n * \n * @see ../../system/cache.zod.ts for application-level caching\n */\n\n// ==========================================\n// Cache Control Headers\n// ==========================================\n\n/**\n * Cache Control Directive Enum\n * Standard HTTP cache control directives\n */\nexport const CacheDirective = z.enum([\n 'public', // Cacheable by any cache\n 'private', // Cacheable only by user-agent\n 'no-cache', // Must revalidate with server\n 'no-store', // Never cache\n 'must-revalidate', // Must revalidate stale responses\n 'max-age', // Maximum cache age in seconds\n]);\n\nexport type CacheDirective = z.infer;\n\n/**\n * Cache Control Schema\n * HTTP cache control configuration\n * \n * @example\n * {\n * \"directives\": [\"public\", \"max-age\"],\n * \"maxAge\": 3600,\n * \"staleWhileRevalidate\": 86400\n * }\n */\nexport const CacheControlSchema = z.object({\n directives: z.array(CacheDirective).describe('Cache control directives'),\n maxAge: z.number().optional().describe('Maximum cache age in seconds'),\n staleWhileRevalidate: z.number().optional().describe('Allow serving stale content while revalidating (seconds)'),\n staleIfError: z.number().optional().describe('Allow serving stale content on error (seconds)'),\n});\n\nexport type CacheControl = z.infer;\n\n// ==========================================\n// ETag Support\n// ==========================================\n\n/**\n * ETag Schema\n * Entity tag for cache validation\n * \n * ETags can be:\n * - Strong: Exact match required (e.g., \"686897696a7c876b7e\")\n * - Weak: Semantic equivalence (e.g., W/\"686897696a7c876b7e\")\n */\nexport const ETagSchema = z.object({\n value: z.string().describe('ETag value (hash or version identifier)'),\n weak: z.boolean().optional().default(false).describe('Whether this is a weak ETag'),\n});\n\nexport type ETag = z.infer;\n\n// ==========================================\n// Metadata Cache Request\n// ==========================================\n\n/**\n * Metadata Cache Request Schema\n * Request with cache validation headers\n * \n * @example\n * // GET /api/v1/metadata/objects/account\n * // Headers:\n * // If-None-Match: \"686897696a7c876b7e\"\n * // If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT\n */\nexport const MetadataCacheRequestSchema = z.object({\n ifNoneMatch: z.string().optional().describe('ETag value for conditional request (If-None-Match header)'),\n ifModifiedSince: z.string().datetime().optional().describe('Timestamp for conditional request (If-Modified-Since header)'),\n cacheControl: CacheControlSchema.optional().describe('Client cache control preferences'),\n});\n\nexport type MetadataCacheRequest = z.infer;\n\n// ==========================================\n// Metadata Cache Response\n// ==========================================\n\n/**\n * Metadata Cache Response Schema\n * Response with cache control headers\n * \n * @example Success Response (200 OK)\n * {\n * \"data\": { \"object\": \"account\" },\n * \"etag\": {\n * \"value\": \"686897696a7c876b7e\",\n * \"weak\": false\n * },\n * \"lastModified\": \"2026-01-29T12:00:00Z\",\n * \"cacheControl\": {\n * \"directives\": [\"public\", \"max-age\"],\n * \"maxAge\": 3600\n * }\n * }\n * \n * @example Not Modified Response (304 Not Modified)\n * {\n * \"notModified\": true,\n * \"etag\": {\n * \"value\": \"686897696a7c876b7e\"\n * }\n * }\n */\nexport const MetadataCacheResponseSchema = z.object({\n data: z.unknown().optional().describe('Metadata payload (omitted for 304 Not Modified)'),\n etag: ETagSchema.optional().describe('ETag for this resource version'),\n lastModified: z.string().datetime().optional().describe('Last modification timestamp'),\n cacheControl: CacheControlSchema.optional().describe('Cache control directives'),\n notModified: z.boolean().optional().default(false).describe('True if resource has not been modified (304 response)'),\n version: z.string().optional().describe('Metadata version identifier'),\n});\n\nexport type MetadataCacheResponse = z.infer;\n\n// ==========================================\n// Metadata Cache Invalidation\n// ==========================================\n\n/**\n * Cache Invalidation Target Enum\n * Specifies what to invalidate\n */\nexport const CacheInvalidationTarget = z.enum([\n 'all', // Invalidate all cached metadata\n 'object', // Invalidate specific object metadata\n 'field', // Invalidate specific field metadata\n 'permission', // Invalidate permission metadata\n 'layout', // Invalidate layout metadata\n 'custom', // Custom invalidation pattern\n]);\n\nexport type CacheInvalidationTarget = z.infer;\n\n/**\n * Cache Invalidation Request Schema\n * Request to invalidate cached metadata\n * \n * @example\n * // POST /api/v1/metadata/cache/invalidate\n * {\n * \"target\": \"object\",\n * \"identifiers\": [\"account\", \"contact\"],\n * \"cascade\": true\n * }\n */\nexport const CacheInvalidationRequestSchema = z.object({\n target: CacheInvalidationTarget.describe('What to invalidate'),\n identifiers: z.array(z.string()).optional().describe('Specific resources to invalidate (e.g., object names)'),\n cascade: z.boolean().optional().default(false).describe('If true, invalidate dependent resources'),\n pattern: z.string().optional().describe('Pattern for custom invalidation (supports wildcards)'),\n});\n\nexport type CacheInvalidationRequest = z.infer;\n\n/**\n * Cache Invalidation Response Schema\n * Response for cache invalidation\n * \n * @example\n * {\n * \"success\": true,\n * \"invalidated\": 5,\n * \"targets\": [\"account\", \"contact\", \"opportunity\"]\n * }\n */\nexport const CacheInvalidationResponseSchema = z.object({\n success: z.boolean().describe('Whether invalidation succeeded'),\n invalidated: z.number().describe('Number of cache entries invalidated'),\n targets: z.array(z.string()).optional().describe('List of invalidated resources'),\n});\n\nexport type CacheInvalidationResponse = z.infer;\n\n// ==========================================\n// Metadata Cache API Methods\n// ==========================================\n\n/**\n * Metadata Cache API Client Interface\n * \n * @example Usage\n * // Get metadata with cache support\n * const response = await client.meta.getCached('account', {\n * ifNoneMatch: '\"686897696a7c876b7e\"'\n * });\n * \n * if (response.notModified) {\n * // Use cached version\n * } else {\n * // Update cache with response.data\n * cache.set('account', response.data, {\n * etag: response.etag?.value,\n * maxAge: response.cacheControl?.maxAge\n * });\n * }\n */\nexport const MetadataCacheApi = {\n getCached: {\n input: MetadataCacheRequestSchema,\n output: MetadataCacheResponseSchema,\n },\n invalidate: {\n input: CacheInvalidationRequestSchema,\n output: CacheInvalidationResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Standardized Error Codes Protocol\n * \n * Implements P0 requirement for ObjectStack kernel.\n * Provides consistent, machine-readable error codes across the platform.\n * \n * Features:\n * - Categorized error codes (validation, authentication, authorization, etc.)\n * - HTTP status code mapping\n * - Localization support\n * - Retry guidance\n * \n * Industry alignment: Google Cloud Errors, AWS Error Codes, Stripe API Errors\n */\n\n// ==========================================\n// Error Code Categories\n// ==========================================\n\n/**\n * Error Category Enum\n * High-level categorization of errors\n */\nexport const ErrorCategory = z.enum([\n 'validation', // Input validation errors (400)\n 'authentication', // Authentication failures (401)\n 'authorization', // Permission denied errors (403)\n 'not_found', // Resource not found (404)\n 'conflict', // Resource conflict (409)\n 'rate_limit', // Rate limiting (429)\n 'server', // Internal server errors (500)\n 'external', // External service errors (502/503)\n 'maintenance', // Planned maintenance (503)\n]);\n\nexport type ErrorCategory = z.infer;\n\n// ==========================================\n// Standard Error Codes\n// ==========================================\n\n/**\n * Standard Error Code Enum\n * Machine-readable error codes for common error scenarios\n */\nexport const StandardErrorCode = z.enum([\n // Validation Errors (400)\n 'validation_error', // Generic validation failure\n 'invalid_field', // Invalid field value\n 'missing_required_field', // Required field missing\n 'invalid_format', // Field format invalid (e.g., email, date)\n 'value_too_long', // Field value exceeds max length\n 'value_too_short', // Field value below min length\n 'value_out_of_range', // Numeric value out of range\n 'invalid_reference', // Invalid foreign key reference\n 'duplicate_value', // Unique constraint violation\n 'invalid_query', // Malformed query syntax\n 'invalid_filter', // Invalid filter expression\n 'invalid_sort', // Invalid sort specification\n 'max_records_exceeded', // Query would return too many records\n \n // Authentication Errors (401)\n 'unauthenticated', // No valid authentication provided\n 'invalid_credentials', // Wrong username/password\n 'expired_token', // Authentication token expired\n 'invalid_token', // Authentication token invalid\n 'session_expired', // User session expired\n 'mfa_required', // Multi-factor authentication required\n 'email_not_verified', // Email verification required\n \n // Authorization Errors (403)\n 'permission_denied', // User lacks required permission\n 'insufficient_privileges', // Operation requires higher privileges\n 'field_not_accessible', // Field-level security restriction\n 'record_not_accessible', // Sharing rule restriction\n 'license_required', // Feature requires license\n 'ip_restricted', // IP address not allowed\n 'time_restricted', // Access outside allowed time window\n \n // Not Found Errors (404)\n 'resource_not_found', // Generic resource not found\n 'object_not_found', // Object/table not found\n 'record_not_found', // Record with given ID not found\n 'field_not_found', // Field not found in object\n 'endpoint_not_found', // API endpoint not found\n \n // Conflict Errors (409)\n 'resource_conflict', // Generic resource conflict\n 'concurrent_modification', // Record modified by another user\n 'delete_restricted', // Cannot delete due to dependencies\n 'duplicate_record', // Record already exists\n 'lock_conflict', // Record is locked by another process\n \n // Rate Limiting (429)\n 'rate_limit_exceeded', // Too many requests\n 'quota_exceeded', // API quota exceeded\n 'concurrent_limit_exceeded', // Too many concurrent requests\n \n // Server Errors (500)\n 'internal_error', // Generic internal server error\n 'database_error', // Database operation failed\n 'timeout', // Operation timed out\n 'service_unavailable', // Service temporarily unavailable\n 'not_implemented', // Feature not yet implemented\n \n // External Service Errors (502/503)\n 'external_service_error', // External API call failed\n 'integration_error', // Integration service error\n 'webhook_delivery_failed', // Webhook delivery failed\n \n // Batch Operation Errors\n 'batch_partial_failure', // Batch operation partially succeeded\n 'batch_complete_failure', // Batch operation completely failed\n 'transaction_failed', // Transaction rolled back\n]);\n\nexport type StandardErrorCode = z.infer;\n\n// ==========================================\n// Enhanced Error Schema\n// ==========================================\n\n/**\n * HTTP Status Code mapping for error categories\n */\nexport const ErrorHttpStatusMap: Record = {\n validation: 400,\n authentication: 401,\n authorization: 403,\n not_found: 404,\n conflict: 409,\n rate_limit: 429,\n server: 500,\n external: 502,\n maintenance: 503,\n};\n\n/**\n * Retry Strategy Enum\n * Guidance on whether to retry failed requests\n */\nexport const RetryStrategy = z.enum([\n 'no_retry', // Do not retry (permanent failure)\n 'retry_immediate', // Retry immediately\n 'retry_backoff', // Retry with exponential backoff\n 'retry_after', // Retry after specified delay\n]);\n\nexport type RetryStrategy = z.infer;\n\n/**\n * Field Error Schema\n * Detailed error for a specific field\n */\nexport const FieldErrorSchema = z.object({\n field: z.string().describe('Field path (supports dot notation)'),\n code: StandardErrorCode.describe('Error code for this field'),\n message: z.string().describe('Human-readable error message'),\n value: z.unknown().optional().describe('The invalid value that was provided'),\n constraint: z.unknown().optional().describe('The constraint that was violated (e.g., max length)'),\n});\n\nexport type FieldError = z.infer;\n\n/**\n * Enhanced API Error Schema\n * Standardized error response with detailed metadata\n * \n * @example Validation Error\n * {\n * \"code\": \"validation_error\",\n * \"message\": \"Validation failed for 2 fields\",\n * \"category\": \"validation\",\n * \"httpStatus\": 400,\n * \"retryable\": false,\n * \"retryStrategy\": \"no_retry\",\n * \"details\": {\n * \"fieldErrors\": [\n * {\n * \"field\": \"email\",\n * \"code\": \"invalid_format\",\n * \"message\": \"Email format is invalid\",\n * \"value\": \"not-an-email\"\n * },\n * {\n * \"field\": \"age\",\n * \"code\": \"value_out_of_range\",\n * \"message\": \"Age must be between 0 and 120\",\n * \"value\": 150,\n * \"constraint\": { \"min\": 0, \"max\": 120 }\n * }\n * ]\n * },\n * \"timestamp\": \"2026-01-29T12:00:00Z\",\n * \"requestId\": \"req_123456\",\n * \"documentation\": \"https://docs.objectstack.dev/errors/validation_error\"\n * }\n * \n * @example Rate Limit Error\n * {\n * \"code\": \"rate_limit_exceeded\",\n * \"message\": \"Rate limit exceeded. Try again in 60 seconds.\",\n * \"category\": \"rate_limit\",\n * \"httpStatus\": 429,\n * \"retryable\": true,\n * \"retryStrategy\": \"retry_after\",\n * \"retryAfter\": 60,\n * \"details\": {\n * \"limit\": 1000,\n * \"remaining\": 0,\n * \"resetAt\": \"2026-01-29T13:00:00Z\"\n * }\n * }\n */\nexport const EnhancedApiErrorSchema = z.object({\n code: StandardErrorCode.describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n category: ErrorCategory.optional().describe('Error category'),\n httpStatus: z.number().optional().describe('HTTP status code'),\n retryable: z.boolean().default(false).describe('Whether the request can be retried'),\n retryStrategy: RetryStrategy.optional().describe('Recommended retry strategy'),\n retryAfter: z.number().optional().describe('Seconds to wait before retrying'),\n details: z.unknown().optional().describe('Additional error context'),\n fieldErrors: z.array(FieldErrorSchema).optional().describe('Field-specific validation errors'),\n timestamp: z.string().datetime().optional().describe('When the error occurred'),\n requestId: z.string().optional().describe('Request ID for tracking'),\n traceId: z.string().optional().describe('Distributed trace ID'),\n documentation: z.string().url().optional().describe('URL to error documentation'),\n helpText: z.string().optional().describe('Suggested actions to resolve the error'),\n});\n\nexport type EnhancedApiError = z.infer;\n\n// ==========================================\n// Error Response Schema\n// ==========================================\n\n/**\n * Standardized Error Response Schema\n * Complete error response envelope\n * \n * @example\n * {\n * \"success\": false,\n * \"error\": {\n * \"code\": \"permission_denied\",\n * \"message\": \"You do not have permission to update this record\",\n * \"category\": \"authorization\",\n * \"httpStatus\": 403,\n * \"retryable\": false\n * }\n * }\n */\nexport const ErrorResponseSchema = z.object({\n success: z.literal(false).describe('Always false for error responses'),\n error: EnhancedApiErrorSchema.describe('Error details'),\n meta: z.object({\n timestamp: z.string().datetime().optional(),\n requestId: z.string().optional(),\n traceId: z.string().optional(),\n }).optional().describe('Response metadata'),\n});\n\nexport type ErrorResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Trigger events for workflow automation\n */\nexport const WorkflowTriggerType = z.enum([\n 'on_create', // When record is created\n 'on_update', // When record is updated\n 'on_create_or_update', // Both\n 'on_delete', // When record is deleted\n 'schedule' // Time-based (cron)\n]);\n\n/**\n * Schema for Workflow Field Update Action\n * @example\n * {\n * name: \"update_status\",\n * type: \"field_update\",\n * field: \"status\",\n * value: \"approved\"\n * }\n */\nexport const FieldUpdateActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('field_update'),\n field: z.string().describe('Field to update'),\n value: z.unknown().describe('Value or Formula to set'),\n});\n\n/**\n * Schema for Workflow Email Alert Action\n * @example\n * {\n * name: \"send_approval_email\",\n * type: \"email_alert\",\n * template: \"approval_request_email\",\n * recipients: [\"user_id_123\", \"manager_field\"]\n * }\n */\nexport const EmailAlertActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('email_alert'),\n template: z.string().describe('Email template ID/DevName'),\n recipients: z.array(z.string()).describe('List of recipient emails or user IDs'),\n});\n\n/**\n * Schema for Connector Action Reference\n * Executes a capability defined in an integration connector.\n * Replaces hardcoded vendor actions (Slack, Twilio, etc).\n * \n * @example Send Slack Message\n * {\n * name: \"notify_slack\",\n * type: \"connector_action\",\n * connectorId: \"slack\",\n * actionId: \"post_message\",\n * input: {\n * channel: \"#general\",\n * text: \"New deal closed: {name}\"\n * }\n * }\n */\nexport const ConnectorActionRefSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('connector_action'),\n connectorId: z.string().describe('Target Connector ID (e.g. slack, twilio)'),\n actionId: z.string().describe('Target Action ID (e.g. send_message)'),\n input: z.record(z.string(), z.unknown()).describe('Input parameters matching the action schema'),\n});\n\n/**\n * Schema for HTTP Callout Action\n * Makes a REST API call to an external service.\n * @example\n * {\n * name: \"sync_to_erp\",\n * type: \"http_call\",\n * url: \"https://erp.api/orders\",\n * method: \"POST\",\n * headers: { \"Authorization\": \"Bearer {token}\" },\n * body: \"{ ... }\"\n * }\n */\nexport const HttpCallActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('http_call'),\n url: z.string().describe('Target URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).default('POST').describe('HTTP Method'),\n headers: z.record(z.string(), z.string()).optional().describe('HTTP Headers'),\n body: z.string().optional().describe('Request body (JSON or text)'),\n});\n\n/**\n * Schema for Workflow Task Creation Action\n * @example\n * {\n * name: \"create_followup_task\",\n * type: \"task_creation\",\n * taskObject: \"tasks\",\n * subject: \"Follow up with client\",\n * dueDate: \"TODAY() + 3\"\n * }\n */\nexport const TaskCreationActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('task_creation'),\n taskObject: z.string().describe('Task object name (e.g., \"task\", \"project_task\")'),\n subject: z.string().describe('Task subject/title'),\n description: z.string().optional().describe('Task description'),\n assignedTo: z.string().optional().describe('User ID or field reference for assignee'),\n dueDate: z.string().optional().describe('Due date (ISO string or formula)'),\n priority: z.string().optional().describe('Task priority'),\n relatedTo: z.string().optional().describe('Related record ID or field reference'),\n additionalFields: z.record(z.string(), z.unknown()).optional().describe('Additional custom fields'),\n});\n\n/**\n * Schema for Workflow Push Notification Action\n */\nexport const PushNotificationActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('push_notification'),\n title: z.string().describe('Notification title'),\n body: z.string().describe('Notification body text'),\n recipients: z.array(z.string()).describe('User IDs or device tokens'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data payload'),\n badge: z.number().optional().describe('Badge count (iOS)'),\n sound: z.string().optional().describe('Notification sound'),\n clickAction: z.string().optional().describe('Action/URL when notification is clicked'),\n});\n\n/**\n * Schema for Workflow Custom Script Action\n */\nexport const CustomScriptActionSchema = z.object({\n name: z.string().describe('Action name'),\n type: z.literal('custom_script'),\n language: z.enum(['javascript', 'typescript', 'python']).default('javascript').describe('Script language'),\n code: z.string().describe('Script code to execute'),\n timeout: z.number().default(30000).describe('Execution timeout in milliseconds'),\n context: z.record(z.string(), z.unknown()).optional().describe('Additional context variables'),\n});\n\n/**\n * Universal Workflow Action Schema\n * Union of all supported action types.\n */\nexport const WorkflowActionSchema = z.discriminatedUnion('type', [\n FieldUpdateActionSchema,\n EmailAlertActionSchema,\n HttpCallActionSchema,\n ConnectorActionRefSchema,\n TaskCreationActionSchema,\n PushNotificationActionSchema,\n CustomScriptActionSchema,\n]);\n\nexport type WorkflowAction = z.infer;\n\n/**\n * Time Trigger Definition\n * Schedules actions to run relative to a specific time or date field.\n */\nexport const TimeTriggerSchema = z.object({\n id: z.string().optional().describe('Unique identifier'),\n \n /** Timing Logic */\n timeLength: z.number().int().describe('Duration amount (e.g. 1, 30)'),\n timeUnit: z.enum(['minutes', 'hours', 'days']).describe('Unit of time'),\n \n /** Reference Point */\n offsetDirection: z.enum(['before', 'after']).describe('Before or After the reference date'),\n offsetFrom: z.enum(['trigger_date', 'date_field']).describe('Basis for calculation'),\n dateField: z.string().optional().describe('Date field to calculate from (required if offsetFrom is date_field)'),\n \n /** Actions */\n actions: z.array(WorkflowActionSchema).describe('Actions to execute at the scheduled time'),\n});\n\n/**\n * Schema for Workflow Rules (Automation)\n * \n * **NAMING CONVENTION:**\n * Workflow names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good workflow names\n * - 'send_welcome_email'\n * - 'update_lead_status'\n * - 'notify_manager_on_close'\n * - 'calculate_discount'\n * \n * @example Bad workflow names (will be rejected)\n * - 'SendWelcomeEmail' (PascalCase)\n * - 'updateLeadStatus' (camelCase)\n * - 'Send Welcome Email' (spaces)\n * \n * @example Complete Workflow\n * {\n * name: \"new_lead_process\",\n * objectName: \"lead\",\n * triggerType: \"on_create\",\n * criteria: \"amount > 1000\",\n * active: true,\n * actions: [\n * {\n * name: \"set_status\",\n * type: \"field_update\",\n * field: \"status\",\n * value: \"new\"\n * },\n * {\n * name: \"notify_team\",\n * type: \"connector_action\",\n * connectorId: \"slack\",\n * actionId: \"post_message\",\n * input: { channel: \"#sales\", text: \"New high value lead!\" }\n * }\n * ],\n * timeTriggers: [\n * {\n * timeLength: 2,\n * timeUnit: \"days\",\n * offsetDirection: \"after\",\n * offsetFrom: \"trigger_date\",\n * actions: [\n * {\n * name: \"followup_check\",\n * type: \"task_creation\",\n * taskObject: \"task\",\n * subject: \"Follow up lead\",\n * dueDate: \"TODAY()\"\n * }\n * ]\n * }\n * ]\n * }\n */\nexport const WorkflowRuleSchema = z.object({\n /** Machine name */\n name: SnakeCaseIdentifierSchema.describe('Unique workflow name (lowercase snake_case)'),\n \n /** Target Object */\n objectName: z.string().describe('Target Object'),\n \n /** When to evaluate the rule */\n triggerType: WorkflowTriggerType.describe('When to evaluate'),\n \n /** \n * Condition to start the workflow.\n * If empty, runs on every trigger event.\n */\n criteria: z.string().optional().describe('Formula condition. If TRUE, actions execute.'),\n \n /** Actions to execute immediately */\n actions: z.array(WorkflowActionSchema).optional().describe('Immediate actions'),\n \n /** \n * Time-Dependent Actions \n * Actions scheduled to run in the future.\n */\n timeTriggers: z.array(TimeTriggerSchema).optional().describe('Scheduled actions relative to trigger or date field'),\n \n /** Active status */\n active: z.boolean().default(true).describe('Whether this workflow is active'),\n\n /** Execution Order */\n executionOrder: z.number().int().min(0).default(100).describe('Deterministic execution order when multiple workflows match (lower runs first)'),\n \n /** Recursion Control */\n reevaluateOnChange: z.boolean().default(false).describe('Re-evaluate rule if field updates change the record validity'),\n});\n\nexport type WorkflowRule = z.infer;\nexport type TimeTrigger = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { ViewSchema } from '../ui/view.zod';\nimport { DiscoverySchema } from './discovery.zod';\nimport { BatchUpdateRequestSchema, BatchUpdateResponseSchema, BatchOptionsSchema } from './batch.zod';\nimport { MetadataCacheRequestSchema, MetadataCacheResponseSchema } from './http-cache.zod';\nimport { QuerySchema } from '../data/query.zod';\nimport { \n AnalyticsQueryRequestSchema, \n AnalyticsResultResponseSchema, \n GetAnalyticsMetaRequestSchema, \n AnalyticsMetadataResponseSchema \n} from './analytics.zod';\nimport { RealtimePresenceSchema, TransportProtocol } from './realtime.zod';\nimport { ObjectPermissionSchema, FieldPermissionSchema } from '../security/permission.zod';\nimport { WorkflowRuleSchema } from '../automation/workflow.zod';\nimport { TranslationDataSchema } from '../system/translation.zod';\nimport type {\n GetFeedRequest,\n GetFeedResponse,\n CreateFeedItemRequest,\n CreateFeedItemResponse,\n UpdateFeedItemRequest,\n UpdateFeedItemResponse,\n DeleteFeedItemRequest,\n DeleteFeedItemResponse,\n AddReactionRequest,\n AddReactionResponse,\n RemoveReactionRequest,\n RemoveReactionResponse,\n PinFeedItemRequest,\n PinFeedItemResponse,\n UnpinFeedItemRequest,\n UnpinFeedItemResponse,\n StarFeedItemRequest,\n StarFeedItemResponse,\n UnstarFeedItemRequest,\n UnstarFeedItemResponse,\n SearchFeedRequest,\n SearchFeedResponse,\n GetChangelogRequest,\n GetChangelogResponse,\n SubscribeRequest,\n SubscribeResponse,\n FeedUnsubscribeRequest,\n UnsubscribeResponse,\n} from './feed-api.zod';\nimport {\n ListPackagesRequestSchema,\n ListPackagesResponseSchema,\n GetPackageRequestSchema,\n GetPackageResponseSchema,\n InstallPackageRequestSchema,\n InstallPackageResponseSchema,\n UninstallPackageRequestSchema,\n UninstallPackageResponseSchema,\n EnablePackageRequestSchema,\n EnablePackageResponseSchema,\n DisablePackageRequestSchema,\n DisablePackageResponseSchema,\n} from '../kernel/package-registry.zod';\nimport type {\n ListPackagesRequest,\n ListPackagesResponse,\n GetPackageRequest,\n GetPackageResponse,\n InstallPackageRequest,\n InstallPackageResponse,\n UninstallPackageRequest,\n UninstallPackageResponse,\n EnablePackageRequest,\n EnablePackageResponse,\n DisablePackageRequest,\n DisablePackageResponse,\n InstalledPackage,\n PackageStatus,\n} from '../kernel/package-registry.zod';\n\nexport const AutomationTriggerRequestSchema = z.object({\n trigger: z.string(),\n payload: z.record(z.string(), z.unknown())\n});\n\nexport const AutomationTriggerResponseSchema = z.object({\n success: z.boolean(),\n jobId: z.string().optional(),\n result: z.unknown().optional()\n});\n\n/**\n * ObjectStack Protocol - Zod Schema Definitions\n * \n * Defines the runtime-validated contract for interacting with ObjectStack metadata and data.\n * Used by API adapters (HTTP, WebSocket, gRPC) to fetch data/metadata without knowing engine internals.\n * \n * This protocol enables:\n * - Runtime request/response validation at API gateway level\n * - Automatic API documentation generation\n * - Type-safe RPC communication between microservices\n * - Client SDK generation from schemas\n * \n * Architecture Alignment:\n * - Salesforce: REST API Request/Response schemas\n * - Kubernetes: API Resource schemas with runtime validation\n * - GraphQL: Schema-first API design\n */\n\n// ==========================================\n// Discovery & Metadata Operations\n// ==========================================\n\n/**\n * Get API Discovery Request\n * No parameters needed\n */\nexport const GetDiscoveryRequestSchema = z.object({});\n\n/**\n * Get API Discovery Response\n * Derived from DiscoverySchema (single source of truth) for protocol-level use.\n * \n * All fields from DiscoverySchema are available but made optional (except `version`)\n * to support progressive disclosure and backward compatibility with existing clients.\n * \n * - `routes` provides a flat endpoint map for client routing.\n * - `services` is the single source of truth for service availability.\n * - `apiName` is kept as an optional alias for `name` for backward compatibility.\n * \n * @see DiscoverySchema in ./discovery.zod.ts — the canonical definition.\n */\nexport const GetDiscoveryResponseSchema = DiscoverySchema\n .partial()\n .required({ version: true })\n .extend({\n /** @deprecated Use `name` instead. Kept for backward compatibility. */\n apiName: z.string().optional().describe('API name (deprecated — use name)'),\n });\n\n/**\n * Get Metadata Types Request\n */\nexport const GetMetaTypesRequestSchema = z.object({});\n\n/**\n * Get Metadata Types Response\n */\nexport const GetMetaTypesResponseSchema = z.object({\n types: z.array(z.string()).describe('Available metadata type names (e.g., \"object\", \"plugin\", \"view\")'),\n});\n\n/**\n * Get Metadata Items Request\n * Get all items of a specific metadata type\n */\nexport const GetMetaItemsRequestSchema = z.object({\n type: z.string().describe('Metadata type name (e.g., \"object\", \"plugin\")'),\n packageId: z.string().optional().describe('Optional package ID to filter items by'),\n});\n\n/**\n * Get Metadata Items Response\n */\nexport const GetMetaItemsResponseSchema = z.object({\n type: z.string().describe('Metadata type name'),\n items: z.array(z.unknown()).describe('Array of metadata items'),\n});\n\n/**\n * Get Metadata Item Request\n * Get a specific metadata item by type and name\n */\nexport const GetMetaItemRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name (snake_case identifier)'),\n packageId: z.string().optional().describe('Optional package ID to filter items by'),\n});\n\n/**\n * Get Metadata Item Response\n */\nexport const GetMetaItemResponseSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n item: z.unknown().describe('Metadata item definition'),\n});\n\n/**\n * Save Metadata Item Request\n * Create or update a metadata item\n */\nexport const SaveMetaItemRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n item: z.unknown().describe('Metadata item definition'),\n});\n\n/**\n * Save Metadata Item Response\n */\nexport const SaveMetaItemResponseSchema = z.object({\n success: z.boolean(),\n message: z.string().optional(),\n});\n\n/**\n * Get Metadata Item with Cache Request\n * Get a specific metadata item with HTTP cache validation support\n */\nexport const GetMetaItemCachedRequestSchema = z.object({\n type: z.string().describe('Metadata type name'),\n name: z.string().describe('Item name'),\n cacheRequest: MetadataCacheRequestSchema.optional().describe('Cache validation parameters'),\n});\n\n/**\n * Get Metadata Item with Cache Response\n * Uses MetadataCacheResponse from http-cache.zod.ts\n */\nexport const GetMetaItemCachedResponseSchema = MetadataCacheResponseSchema;\n\n/**\n * Get UI View Request\n * Resolves the appropriate UI view for an object based on context.\n * Unlike getMetaItem, this does not require a specific View ID.\n */\nexport const GetUiViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n type: z.enum(['list', 'form']).describe('View type'),\n});\n\n/**\n * Get UI View Response\n */\nexport const GetUiViewResponseSchema = ViewSchema;\n\n// ==========================================\n// Data Operations\n// ==========================================\n\n/**\n * Find Data Request\n * Defines a query to retrieve records from a specific object.\n * Supports filtering, sorting, pagination, and field selection.\n * \n * @example\n * {\n * \"object\": \"customers\",\n * \"query\": {\n * \"where\": { \"status\": \"active\", \"revenue\": { \"$gt\": 10000 } },\n * \"orderBy\": [{ \"field\": \"name\", \"order\": \"desc\" }],\n * \"limit\": 10\n * }\n * }\n */\nexport const FindDataRequestSchema = z.object({\n object: z.string().describe('The unique machine name of the object to query (e.g. \"account\").'),\n query: QuerySchema.optional().describe('Structured query definition (filter, sort, select, pagination).'),\n});\n\n/**\n * Find Data Response\n * Returns a list of records matching the query criteria.\n */\nexport const FindDataResponseSchema = z.object({\n object: z.string().describe('The object name for the returned records.'),\n records: z.array(z.record(z.string(), z.unknown())).describe('The list of matching records.'),\n total: z.number().optional().describe('Total number of records matching the filter (if requested).'),\n nextCursor: z.string().optional().describe('Cursor for the next page of results (cursor-based pagination).'),\n hasMore: z.boolean().optional().describe('True if there are more records available (pagination).'),\n});\n\n/**\n * HTTP Find Query Parameters\n * \n * Canonical HTTP query parameter names for GET /data/:object list endpoints.\n * The canonical filter parameter is `filter` (singular). The plural `filters` is\n * accepted for backward compatibility but `filter` is the standard going forward.\n * \n * This schema defines the allowlisted query parameters for HTTP GET list requests.\n * Server-side parsers (protocol.ts) should accept both `filter` and `filters` and\n * normalize to `filter` (singular) internally.\n * \n * @example\n * GET /api/v1/data/contacts?filter={\"status\":\"active\"}&select=name,email&top=10&sort=name\n */\nexport const HttpFindQueryParamsSchema = z.object({\n /** @canonical Singular form — the standard going forward. JSON string of filter expression or AST. */\n filter: z.string().optional().describe('JSON-encoded filter expression (canonical, singular).'),\n /** @deprecated Use `filter` (singular). Accepted for backward compatibility. */\n filters: z.string().optional().describe('JSON-encoded filter expression (deprecated plural alias).'),\n select: z.string().optional().describe('Comma-separated list of fields to retrieve.'),\n sort: z.string().optional().describe('Sort expression (e.g. \"name asc,created_at desc\" or \"-created_at\").'),\n orderBy: z.string().optional().describe('Alias for sort (OData compatibility).'),\n top: z.coerce.number().optional().describe('Max records to return (limit).'),\n skip: z.coerce.number().optional().describe('Records to skip (offset).'),\n expand: z.string().optional().describe(\n 'Comma-separated list of lookup/master_detail field names to expand. '\n + 'Resolved to populate array and passed to the engine for batch $in expansion.'\n ),\n search: z.string().optional().describe('Full-text search query.'),\n distinct: z.coerce.boolean().optional().describe('SELECT DISTINCT flag.'),\n count: z.coerce.boolean().optional().describe('Include total count in response.'),\n});\n\n/**\n * Get Data Request\n * Retrieval of a single record by its unique identifier.\n * Only `select` and `expand` are permitted as additional query parameters.\n * All other query parameters should be discarded to prevent parameter pollution.\n * \n * @example\n * {\n * \"object\": \"contracts\",\n * \"id\": \"cnt_123456\",\n * \"select\": [\"name\", \"status\", \"amount\"],\n * \"expand\": [\"owner\", \"account\"]\n * }\n */\nexport const GetDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The unique record identifier (primary key).'),\n select: z.array(z.string()).optional().describe('Fields to include in the response (allowlisted query param).'),\n expand: z.array(z.string()).optional().describe(\n 'Lookup/master_detail field names to expand. '\n + 'The engine resolves these via batch $in queries, replacing foreign key IDs with full objects.'\n ),\n});\n\n/**\n * Get Data Response\n */\nexport const GetDataResponseSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The record ID.'),\n record: z.record(z.string(), z.unknown()).describe('The complete record data.'),\n});\n\n/**\n * Create Data Request\n * Creation of a new record.\n * \n * @example\n * {\n * \"object\": \"leads\",\n * \"data\": {\n * \"first_name\": \"John\",\n * \"last_name\": \"Doe\",\n * \"company\": \"Acme Inc\"\n * }\n * }\n */\nexport const CreateDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n data: z.record(z.string(), z.unknown()).describe('The dictionary of field values to insert.'),\n});\n\n/**\n * Create Data Response\n */\nexport const CreateDataResponseSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The ID of the newly created record.'),\n record: z.record(z.string(), z.unknown()).describe('The created record, including server-generated fields (created_at, owner).'),\n});\n\n/**\n * Update Data Request\n * Modification of an existing record.\n * \n * @example\n * {\n * \"object\": \"tasks\",\n * \"id\": \"tsk_001\",\n * \"data\": {\n * \"status\": \"completed\",\n * \"percent_complete\": 100\n * }\n * }\n */\nexport const UpdateDataRequestSchema = z.object({\n object: z.string().describe('The object name.'),\n id: z.string().describe('The ID of the record to update.'),\n data: z.record(z.string(), z.unknown()).describe('The fields to update (partial update).'),\n});\n\n/**\n * Update Data Response\n */\nexport const UpdateDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Updated record ID'),\n record: z.record(z.string(), z.unknown()).describe('Updated record'),\n});\n\n/**\n * Delete Data Request\n */\nexport const DeleteDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Record ID to delete'),\n});\n\n/**\n * Delete Data Response\n */\nexport const DeleteDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n id: z.string().describe('Deleted record ID'),\n success: z.boolean().describe('Whether deletion succeeded'),\n});\n\n// ==========================================\n// Batch Operations\n// ==========================================\n\n/**\n * Batch Data Request\n */\nexport const BatchDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n request: BatchUpdateRequestSchema.describe('Batch operation request'),\n});\n\n/**\n * Batch Data Response\n * Uses BatchUpdateResponse from batch.zod.ts\n */\nexport const BatchDataResponseSchema = BatchUpdateResponseSchema;\n\n/**\n * Create Many Data Request\n */\nexport const CreateManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.record(z.string(), z.unknown())).describe('Array of records to create'),\n});\n\n/**\n * Create Many Data Response\n */\nexport const CreateManyDataResponseSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.record(z.string(), z.unknown())).describe('Created records'),\n count: z.number().describe('Number of records created'),\n});\n\n/**\n * Update Many Data Request\n */\nexport const UpdateManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n records: z.array(z.object({\n id: z.string().describe('Record ID'),\n data: z.record(z.string(), z.unknown()).describe('Fields to update'),\n })).describe('Array of updates'),\n options: BatchOptionsSchema.optional().describe('Update options'),\n});\n\n/**\n * Update Many Data Response\n * Uses BatchUpdateResponse for consistency\n */\nexport const UpdateManyDataResponseSchema = BatchUpdateResponseSchema;\n\n/**\n * Delete Many Data Request\n */\nexport const DeleteManyDataRequestSchema = z.object({\n object: z.string().describe('Object name'),\n ids: z.array(z.string()).describe('Array of record IDs to delete'),\n options: BatchOptionsSchema.optional().describe('Delete options'),\n});\n\n/**\n * Delete Many Data Response\n */\nexport const DeleteManyDataResponseSchema = BatchUpdateResponseSchema;\n\n// ==========================================\n// Package Management Operations\n// ==========================================\n\n/**\n * Re-export Package Management Request/Response schemas from kernel.\n * These define the contract for package lifecycle management:\n * - List installed packages (with filters)\n * - Get a specific package by ID\n * - Install a new package (from manifest)\n * - Uninstall a package\n * - Enable/Disable a package\n * \n * Key distinction: Package (ManifestSchema) is the unit of installation.\n * An App (AppSchema) is a UI navigation entity within a package.\n * A package may contain 0, 1, or many apps.\n */\nexport {\n ListPackagesRequestSchema,\n ListPackagesResponseSchema,\n GetPackageRequestSchema,\n GetPackageResponseSchema,\n InstallPackageRequestSchema,\n InstallPackageResponseSchema,\n UninstallPackageRequestSchema,\n UninstallPackageResponseSchema,\n EnablePackageRequestSchema,\n EnablePackageResponseSchema,\n DisablePackageRequestSchema,\n DisablePackageResponseSchema,\n};\n\n// ==========================================\n// View Management Operations\n// ==========================================\n\nexport const ListViewsRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n type: z.enum(['list', 'form']).optional().describe('Filter by view type'),\n});\n\nexport const ListViewsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n views: z.array(ViewSchema).describe('Array of view definitions'),\n});\n\nexport const GetViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier'),\n});\n\nexport const GetViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n view: ViewSchema.describe('View definition'),\n});\n\nexport const CreateViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n data: ViewSchema.describe('View definition to create'),\n});\n\nexport const CreateViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Created view identifier'),\n view: ViewSchema.describe('Created view definition'),\n});\n\nexport const UpdateViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier'),\n data: ViewSchema.partial().describe('Partial view data to update'),\n});\n\nexport const UpdateViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Updated view identifier'),\n view: ViewSchema.describe('Updated view definition'),\n});\n\nexport const DeleteViewRequestSchema = z.object({\n object: z.string().describe('Object name (snake_case)'),\n viewId: z.string().describe('View identifier to delete'),\n});\n\nexport const DeleteViewResponseSchema = z.object({\n object: z.string().describe('Object name'),\n viewId: z.string().describe('Deleted view identifier'),\n success: z.boolean().describe('Whether deletion succeeded'),\n});\n\n// ==========================================\n// Permission Operations\n// ==========================================\n\nexport const CheckPermissionRequestSchema = z.object({\n object: z.string().describe('Object name to check permissions for'),\n action: z.enum(['create', 'read', 'edit', 'delete', 'transfer', 'restore', 'purge']).describe('Action to check'),\n recordId: z.string().optional().describe('Specific record ID (for record-level checks)'),\n field: z.string().optional().describe('Specific field name (for field-level checks)'),\n});\n\nexport const CheckPermissionResponseSchema = z.object({\n allowed: z.boolean().describe('Whether the action is permitted'),\n reason: z.string().optional().describe('Reason if denied'),\n});\n\nexport const GetObjectPermissionsRequestSchema = z.object({\n object: z.string().describe('Object name to get permissions for'),\n});\n\nexport const GetObjectPermissionsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n permissions: ObjectPermissionSchema.describe('Object-level permissions'),\n fieldPermissions: z.record(z.string(), FieldPermissionSchema).optional().describe('Field-level permissions keyed by field name'),\n});\n\nexport const GetEffectivePermissionsRequestSchema = z.object({});\n\nexport const GetEffectivePermissionsResponseSchema = z.object({\n objects: z.record(z.string(), ObjectPermissionSchema).describe('Effective object permissions keyed by object name'),\n systemPermissions: z.array(z.string()).describe('Effective system-level permissions'),\n});\n\n// ==========================================\n// Workflow Operations\n// ==========================================\n\nexport const GetWorkflowConfigRequestSchema = z.object({\n object: z.string().describe('Object name to get workflow config for'),\n});\n\nexport const GetWorkflowConfigResponseSchema = z.object({\n object: z.string().describe('Object name'),\n workflows: z.array(WorkflowRuleSchema).describe('Active workflow rules for this object'),\n});\n\nexport const WorkflowStateSchema = z.object({\n currentState: z.string().describe('Current workflow state name'),\n availableTransitions: z.array(z.object({\n name: z.string().describe('Transition name'),\n targetState: z.string().describe('Target state after transition'),\n label: z.string().optional().describe('Display label'),\n requiresApproval: z.boolean().default(false).describe('Whether transition requires approval'),\n })).describe('Available transitions from current state'),\n history: z.array(z.object({\n fromState: z.string().describe('Previous state'),\n toState: z.string().describe('New state'),\n action: z.string().describe('Action that triggered the transition'),\n userId: z.string().describe('User who performed the action'),\n timestamp: z.string().datetime().describe('When the transition occurred'),\n comment: z.string().optional().describe('Optional comment'),\n })).optional().describe('State transition history'),\n});\n\nexport const GetWorkflowStateRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID to get workflow state for'),\n});\n\nexport const GetWorkflowStateResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n state: WorkflowStateSchema.describe('Current workflow state and available transitions'),\n});\n\nexport const WorkflowTransitionRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n transition: z.string().describe('Transition name to execute'),\n comment: z.string().optional().describe('Optional comment for the transition'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data for the transition'),\n});\n\nexport const WorkflowTransitionResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the transition succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after transition'),\n});\n\nexport const WorkflowApproveRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n comment: z.string().optional().describe('Approval comment'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional data'),\n});\n\nexport const WorkflowApproveResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the approval succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after approval'),\n});\n\nexport const WorkflowRejectRequestSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n reason: z.string().describe('Rejection reason'),\n comment: z.string().optional().describe('Additional comment'),\n});\n\nexport const WorkflowRejectResponseSchema = z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n success: z.boolean().describe('Whether the rejection succeeded'),\n state: WorkflowStateSchema.describe('New workflow state after rejection'),\n});\n\n// ==========================================\n// Realtime Operations\n// ==========================================\n\nexport const RealtimeConnectRequestSchema = z.object({\n transport: TransportProtocol.optional().describe('Preferred transport protocol'),\n channels: z.array(z.string()).optional().describe('Channels to subscribe to on connect'),\n token: z.string().optional().describe('Authentication token'),\n});\n\nexport const RealtimeConnectResponseSchema = z.object({\n connectionId: z.string().describe('Unique connection identifier'),\n transport: TransportProtocol.describe('Negotiated transport protocol'),\n url: z.string().optional().describe('WebSocket/SSE endpoint URL'),\n});\n\nexport const RealtimeDisconnectRequestSchema = z.object({\n connectionId: z.string().optional().describe('Connection ID to disconnect'),\n});\n\nexport const RealtimeDisconnectResponseSchema = z.object({\n success: z.boolean().describe('Whether disconnection succeeded'),\n});\n\nexport const RealtimeSubscribeRequestSchema = z.object({\n channel: z.string().describe('Channel name to subscribe to'),\n events: z.array(z.string()).optional().describe('Specific event types to listen for'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Event filter criteria'),\n});\n\nexport const RealtimeSubscribeResponseSchema = z.object({\n subscriptionId: z.string().describe('Unique subscription identifier'),\n channel: z.string().describe('Subscribed channel name'),\n});\n\nexport const RealtimeUnsubscribeRequestSchema = z.object({\n subscriptionId: z.string().describe('Subscription ID to cancel'),\n});\n\nexport const RealtimeUnsubscribeResponseSchema = z.object({\n success: z.boolean().describe('Whether unsubscription succeeded'),\n});\n\nexport const SetPresenceRequestSchema = z.object({\n channel: z.string().describe('Channel to set presence in'),\n state: RealtimePresenceSchema.describe('Presence state to set'),\n});\n\nexport const SetPresenceResponseSchema = z.object({\n success: z.boolean().describe('Whether presence was set'),\n});\n\nexport const GetPresenceRequestSchema = z.object({\n channel: z.string().describe('Channel to get presence for'),\n});\n\nexport const GetPresenceResponseSchema = z.object({\n channel: z.string().describe('Channel name'),\n members: z.array(RealtimePresenceSchema).describe('Active members and their presence state'),\n});\n\n// ==========================================\n// Notification Operations\n// ==========================================\n\nexport const RegisterDeviceRequestSchema = z.object({\n token: z.string().describe('Device push notification token'),\n platform: z.enum(['ios', 'android', 'web']).describe('Device platform'),\n deviceId: z.string().optional().describe('Unique device identifier'),\n name: z.string().optional().describe('Device friendly name'),\n});\n\nexport const RegisterDeviceResponseSchema = z.object({\n deviceId: z.string().describe('Registered device ID'),\n success: z.boolean().describe('Whether registration succeeded'),\n});\n\nexport const UnregisterDeviceRequestSchema = z.object({\n deviceId: z.string().describe('Device ID to unregister'),\n});\n\nexport const UnregisterDeviceResponseSchema = z.object({\n success: z.boolean().describe('Whether unregistration succeeded'),\n});\n\nexport const NotificationPreferencesSchema = z.object({\n email: z.boolean().default(true).describe('Receive email notifications'),\n push: z.boolean().default(true).describe('Receive push notifications'),\n inApp: z.boolean().default(true).describe('Receive in-app notifications'),\n digest: z.enum(['none', 'daily', 'weekly']).default('none').describe('Email digest frequency'),\n channels: z.record(z.string(), z.object({\n enabled: z.boolean().default(true).describe('Whether this channel is enabled'),\n email: z.boolean().optional().describe('Override email setting'),\n push: z.boolean().optional().describe('Override push setting'),\n })).optional().describe('Per-channel notification preferences'),\n});\n\nexport const GetNotificationPreferencesRequestSchema = z.object({});\n\nexport const GetNotificationPreferencesResponseSchema = z.object({\n preferences: NotificationPreferencesSchema.describe('Current notification preferences'),\n});\n\nexport const UpdateNotificationPreferencesRequestSchema = z.object({\n preferences: NotificationPreferencesSchema.partial().describe('Preferences to update'),\n});\n\nexport const UpdateNotificationPreferencesResponseSchema = z.object({\n preferences: NotificationPreferencesSchema.describe('Updated notification preferences'),\n});\n\nexport const NotificationSchema = z.object({\n id: z.string().describe('Notification ID'),\n type: z.string().describe('Notification type'),\n title: z.string().describe('Notification title'),\n body: z.string().describe('Notification body text'),\n read: z.boolean().default(false).describe('Whether notification has been read'),\n data: z.record(z.string(), z.unknown()).optional().describe('Additional notification data'),\n actionUrl: z.string().optional().describe('URL to navigate to when clicked'),\n createdAt: z.string().datetime().describe('When notification was created'),\n});\n\nexport const ListNotificationsRequestSchema = z.object({\n read: z.boolean().optional().describe('Filter by read status'),\n type: z.string().optional().describe('Filter by notification type'),\n limit: z.number().default(20).describe('Maximum number of notifications to return'),\n cursor: z.string().optional().describe('Pagination cursor'),\n});\n\nexport const ListNotificationsResponseSchema = z.object({\n notifications: z.array(NotificationSchema).describe('List of notifications'),\n unreadCount: z.number().describe('Total number of unread notifications'),\n cursor: z.string().optional().describe('Next page cursor'),\n});\n\nexport const MarkNotificationsReadRequestSchema = z.object({\n ids: z.array(z.string()).describe('Notification IDs to mark as read'),\n});\n\nexport const MarkNotificationsReadResponseSchema = z.object({\n success: z.boolean().describe('Whether the operation succeeded'),\n readCount: z.number().describe('Number of notifications marked as read'),\n});\n\nexport const MarkAllNotificationsReadRequestSchema = z.object({});\n\nexport const MarkAllNotificationsReadResponseSchema = z.object({\n success: z.boolean().describe('Whether the operation succeeded'),\n readCount: z.number().describe('Number of notifications marked as read'),\n});\n\n// ==========================================\n// AI Operations\n// ==========================================\n\nexport const AiNlqRequestSchema = z.object({\n query: z.string().describe('Natural language query string'),\n object: z.string().optional().describe('Target object context'),\n conversationId: z.string().optional().describe('Conversation ID for multi-turn queries'),\n});\n\nexport const AiNlqResponseSchema = z.object({\n query: z.unknown().describe('Generated structured query (AST)'),\n explanation: z.string().optional().describe('Human-readable explanation of the query'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n suggestions: z.array(z.string()).optional().describe('Suggested follow-up queries'),\n});\n\n// AiChatRequestSchema and AiChatResponseSchema have been removed.\n// The AI chat wire protocol is now fully aligned with the Vercel AI SDK (`ai`).\n// Frontend consumers should use `@ai-sdk/react/useChat` directly.\n// See: https://ai-sdk.dev/docs\n\nexport const AiSuggestRequestSchema = z.object({\n object: z.string().describe('Object name for context'),\n field: z.string().optional().describe('Field to suggest values for'),\n recordId: z.string().optional().describe('Record ID for context'),\n partial: z.string().optional().describe('Partial input for completion'),\n});\n\nexport const AiSuggestResponseSchema = z.object({\n suggestions: z.array(z.object({\n value: z.unknown().describe('Suggested value'),\n label: z.string().describe('Display label'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n reason: z.string().optional().describe('Reason for this suggestion'),\n })).describe('Suggested values'),\n});\n\nexport const AiInsightsRequestSchema = z.object({\n object: z.string().describe('Object name to analyze'),\n recordId: z.string().optional().describe('Specific record to analyze'),\n type: z.enum(['summary', 'trends', 'anomalies', 'recommendations']).optional().describe('Type of insight'),\n});\n\nexport const AiInsightsResponseSchema = z.object({\n insights: z.array(z.object({\n type: z.string().describe('Insight type'),\n title: z.string().describe('Insight title'),\n description: z.string().describe('Detailed description'),\n confidence: z.number().min(0).max(1).optional().describe('Confidence score (0-1)'),\n data: z.record(z.string(), z.unknown()).optional().describe('Supporting data'),\n })).describe('Generated insights'),\n});\n\n// ==========================================\n// i18n Operations\n// ==========================================\n\nexport const GetLocalesRequestSchema = z.object({});\n\nexport const GetLocalesResponseSchema = z.object({\n locales: z.array(z.object({\n code: z.string().describe('BCP-47 locale code (e.g., en-US, zh-CN)'),\n label: z.string().describe('Display name of the locale'),\n isDefault: z.boolean().default(false).describe('Whether this is the default locale'),\n })).describe('Available locales'),\n});\n\nexport const GetTranslationsRequestSchema = z.object({\n locale: z.string().describe('BCP-47 locale code'),\n namespace: z.string().optional().describe('Translation namespace (e.g., objects, apps, messages)'),\n keys: z.array(z.string()).optional().describe('Specific translation keys to fetch'),\n});\n\nexport const GetTranslationsResponseSchema = z.object({\n locale: z.string().describe('Locale code'),\n translations: TranslationDataSchema.describe('Translation data'),\n});\n\nexport const GetFieldLabelsRequestSchema = z.object({\n object: z.string().describe('Object name'),\n locale: z.string().describe('BCP-47 locale code'),\n});\n\nexport const GetFieldLabelsResponseSchema = z.object({\n object: z.string().describe('Object name'),\n locale: z.string().describe('Locale code'),\n labels: z.record(z.string(), z.object({\n label: z.string().describe('Translated field label'),\n help: z.string().optional().describe('Translated help text'),\n options: z.record(z.string(), z.string()).optional().describe('Translated option labels'),\n })).describe('Field labels keyed by field name'),\n});\n\n// ==========================================\n// Protocol Interface Schema\n// ==========================================\n\n/**\n * ObjectStack Protocol Contract\n * \n * This schema defines the complete API contract as a Zod schema.\n * Unlike the old TypeScript interface, this provides runtime validation\n * and can be used for:\n * - API Gateway validation\n * - RPC call validation\n * - Client SDK generation\n * - API documentation generation\n * \n * Each method is defined with its request and response schemas.\n */\nexport const ObjectStackProtocolSchema = z.object({\n // Discovery & Metadata\n getDiscovery: z.function()\n .describe('Get API discovery information'),\n\n getMetaTypes: z.function()\n .describe('Get available metadata types'),\n\n getMetaItems: z.function()\n .describe('Get all items of a metadata type'),\n\n getMetaItem: z.function()\n .describe('Get a specific metadata item'),\n saveMetaItem: z.function()\n .describe('Save metadata item'),\n getMetaItemCached: z.function()\n .describe('Get a metadata item with cache validation'),\n\n getUiView: z.function()\n .describe('Get UI view definition'),\n\n // Analytics Operations\n analyticsQuery: z.function()\n .describe('Execute analytics query'),\n\n getAnalyticsMeta: z.function()\n .describe('Get analytics metadata (cubes)'),\n\n // Automation Operations\n triggerAutomation: z.function()\n .describe('Trigger an automation flow or script'),\n\n // Package Management Operations\n listPackages: z.function()\n .describe('List installed packages with optional filters'),\n\n getPackage: z.function()\n .describe('Get a specific installed package by ID'),\n\n installPackage: z.function()\n .describe('Install a new package from manifest'),\n\n uninstallPackage: z.function()\n .describe('Uninstall a package by ID'),\n\n enablePackage: z.function()\n .describe('Enable a disabled package'),\n\n disablePackage: z.function()\n .describe('Disable an installed package'),\n\n // Data Operations\n findData: z.function()\n .describe('Find data records'),\n\n getData: z.function()\n .describe('Get single data record'),\n\n createData: z.function()\n .describe('Create a data record'),\n\n updateData: z.function()\n .describe('Update a data record'),\n\n deleteData: z.function()\n .describe('Delete a data record'),\n\n // Batch Operations\n batchData: z.function()\n .describe('Perform batch operations'),\n\n createManyData: z.function()\n .describe('Create multiple records'),\n\n updateManyData: z.function()\n .describe('Update multiple records'),\n\n deleteManyData: z.function()\n .describe('Delete multiple records'),\n\n // View Management Operations\n listViews: z.function()\n .describe('List views for an object'),\n getView: z.function()\n .describe('Get a specific view'),\n createView: z.function()\n .describe('Create a new view'),\n updateView: z.function()\n .describe('Update an existing view'),\n deleteView: z.function()\n .describe('Delete a view'),\n\n // Permission Operations\n checkPermission: z.function()\n .describe('Check if an action is permitted'),\n getObjectPermissions: z.function()\n .describe('Get permissions for an object'),\n getEffectivePermissions: z.function()\n .describe('Get effective permissions for current user'),\n\n // Workflow Operations\n getWorkflowConfig: z.function()\n .describe('Get workflow configuration for an object'),\n getWorkflowState: z.function()\n .describe('Get workflow state for a record'),\n workflowTransition: z.function()\n .describe('Execute a workflow state transition'),\n workflowApprove: z.function()\n .describe('Approve a workflow step'),\n workflowReject: z.function()\n .describe('Reject a workflow step'),\n\n // Realtime Operations\n realtimeConnect: z.function()\n .describe('Establish realtime connection'),\n realtimeDisconnect: z.function()\n .describe('Close realtime connection'),\n realtimeSubscribe: z.function()\n .describe('Subscribe to a realtime channel'),\n realtimeUnsubscribe: z.function()\n .describe('Unsubscribe from a realtime channel'),\n setPresence: z.function()\n .describe('Set user presence state'),\n getPresence: z.function()\n .describe('Get channel presence information'),\n\n // Notification Operations\n registerDevice: z.function()\n .describe('Register a device for push notifications'),\n unregisterDevice: z.function()\n .describe('Unregister a device'),\n getNotificationPreferences: z.function()\n .describe('Get notification preferences'),\n updateNotificationPreferences: z.function()\n .describe('Update notification preferences'),\n listNotifications: z.function()\n .describe('List notifications'),\n markNotificationsRead: z.function()\n .describe('Mark specific notifications as read'),\n markAllNotificationsRead: z.function()\n .describe('Mark all notifications as read'),\n\n // AI Operations\n aiNlq: z.function()\n .describe('Natural language query'),\n aiChat: z.function()\n .describe('AI chat interaction'),\n aiSuggest: z.function()\n .describe('Get AI-powered suggestions'),\n aiInsights: z.function()\n .describe('Get AI-generated insights'),\n\n // i18n Operations\n getLocales: z.function()\n .describe('Get available locales'),\n getTranslations: z.function()\n .describe('Get translations for a locale'),\n getFieldLabels: z.function()\n .describe('Get translated field labels for an object'),\n\n // Feed Operations\n listFeed: z.function()\n .describe('List feed items for a record'),\n createFeedItem: z.function()\n .describe('Create a new feed item'),\n updateFeedItem: z.function()\n .describe('Update an existing feed item'),\n deleteFeedItem: z.function()\n .describe('Delete a feed item'),\n addReaction: z.function()\n .describe('Add an emoji reaction to a feed item'),\n removeReaction: z.function()\n .describe('Remove an emoji reaction from a feed item'),\n pinFeedItem: z.function()\n .describe('Pin a feed item'),\n unpinFeedItem: z.function()\n .describe('Unpin a feed item'),\n starFeedItem: z.function()\n .describe('Star a feed item'),\n unstarFeedItem: z.function()\n .describe('Unstar a feed item'),\n searchFeed: z.function()\n .describe('Search feed items'),\n getChangelog: z.function()\n .describe('Get field-level changelog for a record'),\n feedSubscribe: z.function()\n .describe('Subscribe to record notifications'),\n feedUnsubscribe: z.function()\n .describe('Unsubscribe from record notifications'),\n});\n\n/**\n * TypeScript Types\n * Derived from Zod schemas using z.infer\n */\nexport type GetDiscoveryRequest = z.infer;\nexport type GetDiscoveryResponse = z.infer;\nexport type GetMetaTypesRequest = z.infer;\nexport type GetMetaTypesResponse = z.infer;\nexport type GetMetaItemsRequest = z.infer;\nexport type GetMetaItemsResponse = z.infer;\nexport type GetMetaItemRequest = z.infer;\nexport type GetMetaItemResponse = z.infer;\nexport type SaveMetaItemRequest = z.infer;\nexport type SaveMetaItemResponse = z.infer;\nexport type GetMetaItemCachedRequest = z.infer;\nexport type GetMetaItemCachedResponse = z.infer;\nexport type GetUiViewRequest = z.infer;\nexport type GetUiViewResponse = z.infer;\n\ntype AnalyticsQueryRequest = z.infer;\ntype AnalyticsResultResponse = z.infer;\ntype GetAnalyticsMetaRequest = z.infer;\ntype GetAnalyticsMetaResponse = z.infer;\n\nexport type AutomationTriggerRequest = z.infer;\nexport type AutomationTriggerResponse = z.infer;\n\nexport type FindDataRequest = z.input;\nexport type FindDataResponse = z.infer;\nexport type GetDataRequest = z.input;\nexport type GetDataResponse = z.infer;\nexport type CreateDataRequest = z.input;\nexport type CreateDataResponse = z.infer;\nexport type UpdateDataRequest = z.input;\nexport type UpdateDataResponse = z.infer;\nexport type DeleteDataRequest = z.input;\nexport type DeleteDataResponse = z.infer;\n\nexport type BatchDataRequest = z.input;\nexport type BatchDataResponse = z.infer;\nexport type CreateManyDataRequest = z.input;\nexport type CreateManyDataResponse = z.infer;\nexport type UpdateManyDataRequest = z.input;\nexport type UpdateManyDataResponse = z.infer;\nexport type DeleteManyDataRequest = z.input;\nexport type DeleteManyDataResponse = z.infer;\n\n// View Management Types\nexport type ListViewsRequest = z.input;\nexport type ListViewsResponse = z.infer;\nexport type GetViewRequest = z.input;\nexport type GetViewResponse = z.infer;\nexport type CreateViewRequest = z.input;\nexport type CreateViewResponse = z.infer;\nexport type UpdateViewRequest = z.input;\nexport type UpdateViewResponse = z.infer;\nexport type DeleteViewRequest = z.input;\nexport type DeleteViewResponse = z.infer;\n\n// Permission Types\nexport type CheckPermissionRequest = z.input;\nexport type CheckPermissionResponse = z.infer;\nexport type GetObjectPermissionsRequest = z.input;\nexport type GetObjectPermissionsResponse = z.infer;\nexport type GetEffectivePermissionsRequest = z.input;\nexport type GetEffectivePermissionsResponse = z.infer;\n\n// Workflow Types\nexport type GetWorkflowConfigRequest = z.input;\nexport type GetWorkflowConfigResponse = z.infer;\nexport type WorkflowState = z.infer;\nexport type GetWorkflowStateRequest = z.input;\nexport type GetWorkflowStateResponse = z.infer;\nexport type WorkflowTransitionRequest = z.input;\nexport type WorkflowTransitionResponse = z.infer;\nexport type WorkflowApproveRequest = z.input;\nexport type WorkflowApproveResponse = z.infer;\nexport type WorkflowRejectRequest = z.input;\nexport type WorkflowRejectResponse = z.infer;\n\n// Realtime Types\nexport type RealtimeConnectRequest = z.input;\nexport type RealtimeConnectResponse = z.infer;\nexport type RealtimeDisconnectRequest = z.input;\nexport type RealtimeDisconnectResponse = z.infer;\nexport type RealtimeSubscribeRequest = z.input;\nexport type RealtimeSubscribeResponse = z.infer;\nexport type RealtimeUnsubscribeRequest = z.input;\nexport type RealtimeUnsubscribeResponse = z.infer;\nexport type SetPresenceRequest = z.input;\nexport type SetPresenceResponse = z.infer;\nexport type GetPresenceRequest = z.input;\nexport type GetPresenceResponse = z.infer;\n\n// Notification Types\nexport type RegisterDeviceRequest = z.input;\nexport type RegisterDeviceResponse = z.infer;\nexport type UnregisterDeviceRequest = z.input;\nexport type UnregisterDeviceResponse = z.infer;\nexport type NotificationPreferences = z.infer;\nexport type NotificationPreferencesInput = z.input;\nexport type GetNotificationPreferencesRequest = z.input;\nexport type GetNotificationPreferencesResponse = z.infer;\nexport type UpdateNotificationPreferencesRequest = z.input;\nexport type UpdateNotificationPreferencesResponse = z.infer;\nexport type Notification = z.infer;\nexport type NotificationInput = z.input;\nexport type ListNotificationsRequest = z.input;\nexport type ListNotificationsResponse = z.infer;\nexport type MarkNotificationsReadRequest = z.input;\nexport type MarkNotificationsReadResponse = z.infer;\nexport type MarkAllNotificationsReadRequest = z.input;\nexport type MarkAllNotificationsReadResponse = z.infer;\n\n// AI Types\nexport type AiNlqRequest = z.input;\nexport type AiNlqResponse = z.infer;\nexport type AiSuggestRequest = z.input;\nexport type AiSuggestResponse = z.infer;\nexport type AiInsightsRequest = z.input;\nexport type AiInsightsResponse = z.infer;\n\n// i18n Types\nexport type GetLocalesRequest = z.input;\nexport type GetLocalesResponse = z.infer;\nexport type GetTranslationsRequest = z.input;\nexport type GetTranslationsResponse = z.infer;\nexport type GetFieldLabelsRequest = z.input;\nexport type GetFieldLabelsResponse = z.infer;\n\n// Feed Types (re-exported from feed-api.zod.ts for convenience)\nexport type {\n GetFeedRequest,\n GetFeedResponse,\n CreateFeedItemRequest,\n CreateFeedItemResponse,\n UpdateFeedItemRequest,\n UpdateFeedItemResponse,\n DeleteFeedItemRequest,\n DeleteFeedItemResponse,\n AddReactionRequest,\n AddReactionResponse,\n RemoveReactionRequest,\n RemoveReactionResponse,\n PinFeedItemRequest,\n PinFeedItemResponse,\n UnpinFeedItemRequest,\n UnpinFeedItemResponse,\n StarFeedItemRequest,\n StarFeedItemResponse,\n UnstarFeedItemRequest,\n UnstarFeedItemResponse,\n SearchFeedRequest,\n SearchFeedResponse,\n GetChangelogRequest,\n GetChangelogResponse,\n SubscribeRequest,\n SubscribeResponse,\n FeedUnsubscribeRequest,\n UnsubscribeResponse,\n} from './feed-api.zod';\n\n// Package Management Types (re-exported from kernel for convenience)\nexport type { \n ListPackagesRequest,\n ListPackagesResponse,\n GetPackageRequest,\n GetPackageResponse,\n InstallPackageRequest,\n InstallPackageResponse,\n UninstallPackageRequest,\n UninstallPackageResponse,\n EnablePackageRequest,\n EnablePackageResponse,\n DisablePackageRequest,\n DisablePackageResponse,\n InstalledPackage,\n PackageStatus,\n};\n\n/**\n * Zod-inferred protocol type (for runtime validation only).\n * Use ObjectStackProtocol interface for implementation contracts.\n */\nexport type ObjectStackProtocolZod = z.infer;\n\n/**\n * ObjectStack Protocol Interface\n * \n * Properly typed interface for implementing the ObjectStack API protocol.\n * The Zod schema (ObjectStackProtocolSchema) is used for runtime validation,\n * while this interface provides compile-time type safety for implementations.\n */\nexport interface ObjectStackProtocol {\n // Discovery & Metadata (core)\n getDiscovery(request?: GetDiscoveryRequest): Promise;\n getMetaTypes(request?: GetMetaTypesRequest): Promise;\n getMetaItems(request: GetMetaItemsRequest): Promise;\n getMetaItem(request: GetMetaItemRequest): Promise;\n saveMetaItem(request: SaveMetaItemRequest): Promise;\n getMetaItemCached?(request: GetMetaItemCachedRequest): Promise;\n getUiView?(request: GetUiViewRequest): Promise;\n \n // Analytics (optional)\n analyticsQuery?(request: AnalyticsQueryRequest): Promise;\n getAnalyticsMeta?(request: GetAnalyticsMetaRequest): Promise;\n\n // Automation (optional)\n triggerAutomation?(request: AutomationTriggerRequest): Promise;\n\n // Package Management (optional)\n listPackages?(request: ListPackagesRequest): Promise;\n getPackage?(request: GetPackageRequest): Promise;\n installPackage?(request: InstallPackageRequest): Promise;\n uninstallPackage?(request: UninstallPackageRequest): Promise;\n enablePackage?(request: EnablePackageRequest): Promise;\n disablePackage?(request: DisablePackageRequest): Promise;\n\n // Data Operations (core)\n findData(request: FindDataRequest): Promise;\n getData(request: GetDataRequest): Promise;\n createData(request: CreateDataRequest): Promise;\n updateData(request: UpdateDataRequest): Promise;\n deleteData(request: DeleteDataRequest): Promise;\n \n // Batch Operations (optional)\n batchData?(request: BatchDataRequest): Promise;\n createManyData?(request: CreateManyDataRequest): Promise;\n updateManyData?(request: UpdateManyDataRequest): Promise;\n deleteManyData?(request: DeleteManyDataRequest): Promise;\n\n // View Management (optional)\n listViews?(request: ListViewsRequest): Promise;\n getView?(request: GetViewRequest): Promise;\n createView?(request: CreateViewRequest): Promise;\n updateView?(request: UpdateViewRequest): Promise;\n deleteView?(request: DeleteViewRequest): Promise;\n\n // Permissions (optional)\n checkPermission?(request: CheckPermissionRequest): Promise;\n getObjectPermissions?(request: GetObjectPermissionsRequest): Promise;\n getEffectivePermissions?(request: GetEffectivePermissionsRequest): Promise;\n\n // Workflows (optional)\n getWorkflowConfig?(request: GetWorkflowConfigRequest): Promise;\n getWorkflowState?(request: GetWorkflowStateRequest): Promise;\n workflowTransition?(request: WorkflowTransitionRequest): Promise;\n workflowApprove?(request: WorkflowApproveRequest): Promise;\n workflowReject?(request: WorkflowRejectRequest): Promise;\n\n // Realtime (optional)\n realtimeConnect?(request: RealtimeConnectRequest): Promise;\n realtimeDisconnect?(request: RealtimeDisconnectRequest): Promise;\n realtimeSubscribe?(request: RealtimeSubscribeRequest): Promise;\n realtimeUnsubscribe?(request: RealtimeUnsubscribeRequest): Promise;\n setPresence?(request: SetPresenceRequest): Promise;\n getPresence?(request: GetPresenceRequest): Promise;\n\n // Notifications (optional)\n registerDevice?(request: RegisterDeviceRequest): Promise;\n unregisterDevice?(request: UnregisterDeviceRequest): Promise;\n getNotificationPreferences?(request: GetNotificationPreferencesRequest): Promise;\n updateNotificationPreferences?(request: UpdateNotificationPreferencesRequest): Promise;\n listNotifications?(request: ListNotificationsRequest): Promise;\n markNotificationsRead?(request: MarkNotificationsReadRequest): Promise;\n markAllNotificationsRead?(request: MarkAllNotificationsReadRequest): Promise;\n\n // AI (optional — chat is now handled by Vercel AI SDK wire protocol)\n aiNlq?(request: AiNlqRequest): Promise;\n aiSuggest?(request: AiSuggestRequest): Promise;\n aiInsights?(request: AiInsightsRequest): Promise;\n\n // i18n (optional)\n getLocales?(request: GetLocalesRequest): Promise;\n getTranslations?(request: GetTranslationsRequest): Promise;\n getFieldLabels?(request: GetFieldLabelsRequest): Promise;\n\n // Feed (optional)\n listFeed?(request: GetFeedRequest): Promise;\n createFeedItem?(request: CreateFeedItemRequest): Promise;\n updateFeedItem?(request: UpdateFeedItemRequest): Promise;\n deleteFeedItem?(request: DeleteFeedItemRequest): Promise;\n addReaction?(request: AddReactionRequest): Promise;\n removeReaction?(request: RemoveReactionRequest): Promise;\n pinFeedItem?(request: PinFeedItemRequest): Promise;\n unpinFeedItem?(request: UnpinFeedItemRequest): Promise;\n starFeedItem?(request: StarFeedItemRequest): Promise;\n unstarFeedItem?(request: UnstarFeedItemRequest): Promise;\n searchFeed?(request: SearchFeedRequest): Promise;\n getChangelog?(request: GetChangelogRequest): Promise;\n feedSubscribe?(request: SubscribeRequest): Promise;\n feedUnsubscribe?(request: FeedUnsubscribeRequest): Promise;\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\n\n/**\n * REST API Server Protocol\n * \n * Defines the REST API server configuration for automatically generating\n * RESTful CRUD endpoints, metadata endpoints, and batch operations.\n * \n * Features:\n * - Automatic CRUD endpoint generation from Object definitions\n * - Standard REST conventions (GET, POST, PUT, PATCH, DELETE)\n * - Metadata API endpoints\n * - Batch operation endpoints\n * - OpenAPI/Swagger documentation generation\n * \n * Architecture alignment:\n * - Salesforce: REST API with Object CRUD\n * - Microsoft Dynamics: Web API with entity operations\n * - Strapi: Auto-generated REST endpoints\n */\n\n// ==========================================\n// REST API Configuration\n// ==========================================\n\n/**\n * REST API Configuration Schema\n * Core configuration for REST API server\n * \n * @example\n * {\n * \"version\": \"v1\",\n * \"basePath\": \"/api\",\n * \"enableCrud\": true,\n * \"enableMetadata\": true,\n * \"enableBatch\": true,\n * \"documentation\": {\n * \"enabled\": true,\n * \"title\": \"ObjectStack API\"\n * }\n * }\n */\nexport const RestApiConfigSchema = z.object({\n /**\n * API version identifier\n */\n version: z.string().regex(/^[a-zA-Z0-9_\\-\\.]+$/).default('v1').describe('API version (e.g., v1, v2, 2024-01)'),\n \n /**\n * Base path for all API routes\n */\n basePath: z.string().default('/api').describe('Base URL path for API'),\n \n /**\n * Full API path (combines basePath and version)\n */\n apiPath: z.string().optional().describe('Full API path (defaults to {basePath}/{version})'),\n \n /**\n * Enable automatic CRUD endpoints\n */\n enableCrud: z.boolean().default(true).describe('Enable automatic CRUD endpoint generation'),\n \n /**\n * Enable metadata endpoints\n */\n enableMetadata: z.boolean().default(true).describe('Enable metadata API endpoints'),\n \n /**\n * Enable UI API endpoints\n */\n enableUi: z.boolean().default(true).describe('Enable UI API endpoints (Views, Menus, Layouts)'),\n \n /**\n * Enable batch operation endpoints\n */\n enableBatch: z.boolean().default(true).describe('Enable batch operation endpoints'),\n \n /**\n * Enable discovery endpoint\n */\n enableDiscovery: z.boolean().default(true).describe('Enable API discovery endpoint'),\n\n /**\n * API documentation configuration\n */\n documentation: z.object({\n enabled: z.boolean().default(true).describe('Enable API documentation'),\n title: z.string().default('ObjectStack API').describe('API documentation title'),\n description: z.string().optional().describe('API description'),\n version: z.string().optional().describe('Documentation version'),\n termsOfService: z.string().optional().describe('Terms of service URL'),\n contact: z.object({\n name: z.string().optional(),\n url: z.string().optional(),\n email: z.string().optional(),\n }).optional(),\n license: z.object({\n name: z.string(),\n url: z.string().optional(),\n }).optional(),\n }).optional().describe('OpenAPI/Swagger documentation config'),\n \n /**\n * Response format configuration\n */\n responseFormat: z.object({\n envelope: z.boolean().default(true).describe('Wrap responses in standard envelope'),\n includeMetadata: z.boolean().default(true).describe('Include response metadata (timestamp, requestId)'),\n includePagination: z.boolean().default(true).describe('Include pagination info in list responses'),\n }).optional().describe('Response format options'),\n});\n\nexport type RestApiConfig = z.infer;\nexport type RestApiConfigInput = z.input;\n\n// ==========================================\n// CRUD Endpoint Configuration\n// ==========================================\n\n/**\n * CRUD Operation Type Enum\n */\nexport const CrudOperation = z.enum([\n 'create', // POST /api/v1/data/{object}\n 'read', // GET /api/v1/data/{object}/:id\n 'update', // PATCH /api/v1/data/{object}/:id\n 'delete', // DELETE /api/v1/data/{object}/:id\n 'list', // GET /api/v1/data/{object}\n]);\n\nexport type CrudOperation = z.infer;\n\n/**\n * CRUD Endpoint Pattern Schema\n * Defines the URL pattern for CRUD operations\n * \n * @example\n * {\n * \"create\": { \"method\": \"POST\", \"path\": \"/data/{object}\" },\n * \"read\": { \"method\": \"GET\", \"path\": \"/data/{object}/:id\" },\n * \"update\": { \"method\": \"PATCH\", \"path\": \"/data/{object}/:id\" },\n * \"delete\": { \"method\": \"DELETE\", \"path\": \"/data/{object}/:id\" },\n * \"list\": { \"method\": \"GET\", \"path\": \"/data/{object}\" }\n * }\n */\nexport const CrudEndpointPatternSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * URL path pattern (relative to API base)\n */\n path: z.string().describe('URL path pattern'),\n \n /**\n * Operation summary for documentation\n */\n summary: z.string().optional().describe('Operation summary'),\n \n /**\n * Operation description\n */\n description: z.string().optional().describe('Operation description'),\n});\n\nexport type CrudEndpointPattern = z.infer;\n\n/**\n * CRUD Endpoints Configuration Schema\n * Configuration for automatic CRUD endpoint generation\n */\nexport const CrudEndpointsConfigSchema = z.object({\n /**\n * Enable/disable specific CRUD operations\n */\n operations: z.object({\n create: z.boolean().default(true).describe('Enable create operation'),\n read: z.boolean().default(true).describe('Enable read operation'),\n update: z.boolean().default(true).describe('Enable update operation'),\n delete: z.boolean().default(true).describe('Enable delete operation'),\n list: z.boolean().default(true).describe('Enable list operation'),\n }).optional().describe('Enable/disable operations'),\n \n /**\n * Custom endpoint patterns (override defaults)\n */\n patterns: z.record(CrudOperation, CrudEndpointPatternSchema.optional()).optional()\n .describe('Custom URL patterns for operations'),\n \n /**\n * Path prefix for data operations\n */\n dataPrefix: z.string().default('/data').describe('URL prefix for data endpoints'),\n \n /**\n * Object name parameter style\n */\n objectParamStyle: z.enum(['path', 'query']).default('path')\n .describe('How object name is passed (path param or query param)'),\n});\n\nexport type CrudEndpointsConfig = z.infer;\nexport type CrudEndpointsConfigInput = z.input;\n\n// ==========================================\n// Metadata Endpoint Configuration\n// ==========================================\n\n/**\n * Metadata Endpoint Configuration Schema\n * Configuration for metadata API endpoints\n * \n * @example\n * {\n * \"prefix\": \"/meta\",\n * \"enableCache\": true,\n * \"endpoints\": {\n * \"types\": true,\n * \"objects\": true,\n * \"fields\": true\n * }\n * }\n */\nexport const MetadataEndpointsConfigSchema = z.object({\n /**\n * Path prefix for metadata operations\n */\n prefix: z.string().default('/meta').describe('URL prefix for metadata endpoints'),\n \n /**\n * Enable HTTP caching for metadata\n */\n enableCache: z.boolean().default(true).describe('Enable HTTP cache headers (ETag, Last-Modified)'),\n \n /**\n * Cache TTL in seconds\n */\n cacheTtl: z.number().int().default(3600).describe('Cache TTL in seconds'),\n \n /**\n * Enable specific metadata endpoints\n */\n endpoints: z.object({\n types: z.boolean().default(true).describe('GET /meta - List all metadata types'),\n items: z.boolean().default(true).describe('GET /meta/:type - List items of type'),\n item: z.boolean().default(true).describe('GET /meta/:type/:name - Get specific item'),\n schema: z.boolean().default(true).describe('GET /meta/:type/:name/schema - Get JSON schema'),\n }).optional().describe('Enable/disable specific endpoints'),\n});\n\nexport type MetadataEndpointsConfig = z.infer;\nexport type MetadataEndpointsConfigInput = z.input;\n\n// ==========================================\n// Batch Operation Endpoint Configuration\n// ==========================================\n\n/**\n * Batch Operation Endpoint Configuration Schema\n * Configuration for batch/bulk operation endpoints\n * \n * @example\n * {\n * \"maxBatchSize\": 200,\n * \"enableBatchEndpoint\": true,\n * \"enableCreateMany\": true,\n * \"enableUpdateMany\": true,\n * \"enableDeleteMany\": true\n * }\n */\nexport const BatchEndpointsConfigSchema = z.object({\n /**\n * Maximum batch size\n */\n maxBatchSize: z.number().int().min(1).max(1000).default(200)\n .describe('Maximum records per batch operation'),\n \n /**\n * Enable generic batch endpoint\n */\n enableBatchEndpoint: z.boolean().default(true)\n .describe('Enable POST /data/:object/batch endpoint'),\n \n /**\n * Enable specific batch operations\n */\n operations: z.object({\n createMany: z.boolean().default(true).describe('Enable POST /data/:object/createMany'),\n updateMany: z.boolean().default(true).describe('Enable POST /data/:object/updateMany'),\n deleteMany: z.boolean().default(true).describe('Enable POST /data/:object/deleteMany'),\n upsertMany: z.boolean().default(true).describe('Enable POST /data/:object/upsertMany'),\n }).optional().describe('Enable/disable specific batch operations'),\n \n /**\n * Transaction mode default\n */\n defaultAtomic: z.boolean().default(true)\n .describe('Default atomic/transaction mode for batch operations'),\n});\n\nexport type BatchEndpointsConfig = z.infer;\nexport type BatchEndpointsConfigInput = z.input;\n\n// ==========================================\n// Route Generation Configuration\n// ==========================================\n\n/**\n * Route Generation Configuration Schema\n * Controls automatic route generation for objects\n */\nexport const RouteGenerationConfigSchema = z.object({\n /**\n * Objects to include (if empty, include all)\n */\n includeObjects: z.array(z.string()).optional()\n .describe('Specific objects to generate routes for (empty = all)'),\n \n /**\n * Objects to exclude\n */\n excludeObjects: z.array(z.string()).optional()\n .describe('Objects to exclude from route generation'),\n \n /**\n * Object name transformations\n */\n nameTransform: z.enum(['none', 'plural', 'kebab-case', 'camelCase']).default('none')\n .describe('Transform object names in URLs'),\n \n /**\n * Custom route overrides per object\n */\n overrides: z.record(z.string(), z.object({\n enabled: z.boolean().optional().describe('Enable/disable routes for this object'),\n basePath: z.string().optional().describe('Custom base path'),\n operations: z.record(CrudOperation, z.boolean()).optional()\n .describe('Enable/disable specific operations'),\n })).optional().describe('Per-object route customization'),\n});\n\nexport type RouteGenerationConfig = z.infer;\nexport type RouteGenerationConfigInput = z.input;\n\n// ==========================================\n// OpenAPI 3.1 Webhooks & Callbacks\n// ==========================================\n\n/**\n * Webhook Event Schema\n * Defines an event that can trigger a webhook delivery\n */\nexport const WebhookEventSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Webhook event identifier (snake_case)'),\n description: z.string().describe('Human-readable event description'),\n method: HttpMethod.default('POST').describe('HTTP method for webhook delivery'),\n payloadSchema: z.string().describe('JSON Schema $ref for the webhook payload'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers to include in webhook delivery'),\n security: z.array(\n z.enum(['hmac_sha256', 'basic', 'bearer', 'api_key'])\n ).describe('Supported authentication methods for webhook verification'),\n});\n\nexport type WebhookEvent = z.infer;\n\n/**\n * Webhook Configuration Schema\n * Top-level webhook configuration for the REST API\n */\nexport const WebhookConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable webhook support'),\n events: z.array(WebhookEventSchema).describe('Registered webhook events'),\n deliveryConfig: z.object({\n maxRetries: z.number().int().default(3).describe('Maximum delivery retry attempts'),\n retryIntervalMs: z.number().int().default(5000).describe('Milliseconds between retry attempts'),\n timeoutMs: z.number().int().default(30000).describe('Delivery request timeout in milliseconds'),\n signatureHeader: z.string().default('X-Signature-256').describe('Header name for webhook signature'),\n }).describe('Webhook delivery configuration'),\n registrationEndpoint: z.string().default('/webhooks').describe('URL path for webhook registration'),\n});\n\nexport type WebhookConfig = z.infer;\n\n/**\n * Callback Schema\n * OpenAPI 3.1 callback definition for asynchronous API responses\n */\nexport const CallbackSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Callback identifier (snake_case)'),\n expression: z.string().describe('Runtime expression (e.g., {$request.body#/callbackUrl})'),\n method: HttpMethod.describe('HTTP method for callback request'),\n url: z.string().describe('Callback URL template with runtime expressions'),\n});\n\nexport type Callback = z.infer;\n\n/**\n * OpenAPI 3.1 Extensions Schema\n * Extensions specific to OpenAPI 3.1 specification\n */\nexport const OpenApi31ExtensionsSchema = z.object({\n webhooks: z.record(z.string(), WebhookEventSchema).optional()\n .describe('OpenAPI 3.1 webhooks (top-level webhook definitions)'),\n callbacks: z.record(z.string(), z.array(CallbackSchema)).optional()\n .describe('OpenAPI 3.1 callbacks (async response definitions)'),\n jsonSchemaDialect: z.string().default('https://json-schema.org/draft/2020-12/schema')\n .describe('JSON Schema dialect for schema definitions'),\n pathItemReferences: z.boolean().default(false)\n .describe('Allow $ref in path items (OpenAPI 3.1 feature)'),\n});\n\nexport type OpenApi31Extensions = z.infer;\n\n// ==========================================\n// Complete REST Server Configuration\n// ==========================================\n\n/**\n * REST Server Configuration Schema\n * Complete configuration for REST API server with auto-generated endpoints\n * \n * @example\n * {\n * \"api\": {\n * \"version\": \"v1\",\n * \"basePath\": \"/api\",\n * \"enableCrud\": true,\n * \"enableMetadata\": true,\n * \"enableBatch\": true\n * },\n * \"crud\": {\n * \"dataPrefix\": \"/data\"\n * },\n * \"metadata\": {\n * \"prefix\": \"/meta\",\n * \"enableCache\": true\n * },\n * \"batch\": {\n * \"maxBatchSize\": 200\n * },\n * \"routes\": {\n * \"excludeObjects\": [\"system_log\"]\n * }\n * }\n */\nexport const RestServerConfigSchema = z.object({\n /**\n * API configuration\n */\n api: RestApiConfigSchema.optional().describe('REST API configuration'),\n \n /**\n * CRUD endpoints configuration\n */\n crud: CrudEndpointsConfigSchema.optional().describe('CRUD endpoints configuration'),\n \n /**\n * Metadata endpoints configuration\n */\n metadata: MetadataEndpointsConfigSchema.optional().describe('Metadata endpoints configuration'),\n \n /**\n * Batch endpoints configuration\n */\n batch: BatchEndpointsConfigSchema.optional().describe('Batch endpoints configuration'),\n \n /**\n * Route generation configuration\n */\n routes: RouteGenerationConfigSchema.optional().describe('Route generation configuration'),\n \n /**\n * OpenAPI 3.1 extensions (webhooks, callbacks)\n */\n openApi31: OpenApi31ExtensionsSchema.optional().describe('OpenAPI 3.1 extensions configuration'),\n});\n\nexport type RestServerConfig = z.infer;\nexport type RestServerConfigInput = z.input;\n\n// ==========================================\n// Endpoint Registry\n// ==========================================\n\n/**\n * Generated Endpoint Schema\n * Represents a generated REST endpoint\n */\nexport const GeneratedEndpointSchema = z.object({\n /**\n * Endpoint identifier\n */\n id: z.string().describe('Unique endpoint identifier'),\n \n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method'),\n \n /**\n * Full URL path\n */\n path: z.string().describe('Full URL path'),\n \n /**\n * Object this endpoint operates on\n */\n object: z.string().describe('Object name (snake_case)'),\n \n /**\n * Operation type\n */\n operation: z.union([CrudOperation, z.string()]).describe('Operation type'),\n \n /**\n * Handler reference\n */\n handler: z.string().describe('Handler function identifier'),\n \n /**\n * Endpoint metadata\n */\n metadata: z.object({\n summary: z.string().optional(),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n deprecated: z.boolean().optional(),\n }).optional(),\n});\n\nexport type GeneratedEndpoint = z.infer;\n\n/**\n * Endpoint Registry Schema\n * Registry of all generated endpoints\n */\nexport const EndpointRegistrySchema = z.object({\n /**\n * Generated endpoints\n */\n endpoints: z.array(GeneratedEndpointSchema).describe('All generated endpoints'),\n \n /**\n * Total endpoint count\n */\n total: z.number().int().describe('Total number of endpoints'),\n \n /**\n * Endpoints by object\n */\n byObject: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()\n .describe('Endpoints grouped by object'),\n \n /**\n * Endpoints by operation\n */\n byOperation: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()\n .describe('Endpoints grouped by operation'),\n});\n\nexport type EndpointRegistry = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create REST API configuration\n */\nexport const RestApiConfig = Object.assign(RestApiConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create REST server configuration\n */\nexport const RestServerConfig = Object.assign(RestServerConfigSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod, RateLimitConfigSchema } from '../shared/http.zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Unified API Registry Protocol\n * \n * Provides a centralized registry for managing all API endpoints across different\n * API types (REST, GraphQL, OData, WebSocket, Auth, File, Plugin-registered).\n * \n * This enables:\n * - Unified API discovery and documentation (similar to Swagger/OpenAPI)\n * - API testing interfaces\n * - API governance and monitoring\n * - Plugin API registration\n * - Multi-protocol support\n * \n * Architecture Alignment:\n * - Kubernetes: Service Discovery & API Server\n * - AWS API Gateway: Unified API Management\n * - Kong Gateway: Plugin-based API Management\n * \n * @example API Registry Entry\n * ```typescript\n * const apiEntry: ApiRegistryEntry = {\n * id: 'customer_crud',\n * name: 'Customer CRUD API',\n * type: 'rest',\n * version: 'v1',\n * basePath: '/api/v1/data/customer',\n * endpoints: [...],\n * metadata: {\n * owner: 'sales_team',\n * tags: ['customer', 'crm']\n * }\n * }\n * ```\n */\n\n// ==========================================\n// API Type Enumeration\n// ==========================================\n\n/**\n * API Protocol Type\n * \n * Defines the different types of APIs supported by ObjectStack.\n */\nexport const ApiProtocolType = z.enum([\n 'rest', // RESTful API (CRUD operations)\n 'graphql', // GraphQL API (flexible queries)\n 'odata', // OData v4 API (enterprise integration)\n 'websocket', // WebSocket API (real-time)\n 'file', // File/Storage API (uploads/downloads)\n 'auth', // Authentication/Authorization API\n 'metadata', // Metadata/Schema API\n 'plugin', // Plugin-registered custom API\n 'webhook', // Webhook endpoints\n 'rpc', // JSON-RPC or similar\n]);\n\nexport type ApiProtocolType = z.infer;\n\n// ==========================================\n// API Endpoint Registration\n// ==========================================\n\n/**\n * HTTP Status Code\n */\nexport const HttpStatusCode = z.union([\n z.number().int().min(100).max(599),\n z.enum(['2xx', '3xx', '4xx', '5xx']), // Pattern matching\n]);\n\nexport type HttpStatusCode = z.infer;\n\n// ==========================================\n// Schema Reference Types\n// ==========================================\n\n/**\n * ObjectQL Reference Schema\n * \n * Allows referencing ObjectStack data objects instead of static JSON schemas.\n * When an API parameter or response references an ObjectQL object, the schema\n * is dynamically derived from the object definition, enabling automatic updates\n * when the object schema changes.\n * \n * **IMPORTANT - Schema Resolution Responsibility:**\n * The API Registry STORES these references as metadata but does NOT resolve them.\n * Schema resolution (expanding references into actual JSON Schema) is performed by:\n * - **API Gateway**: For runtime request/response validation\n * - **OpenAPI Generator**: For Swagger/OpenAPI documentation\n * - **GraphQL Schema Builder**: For GraphQL type generation\n * - **Documentation Tools**: For developer documentation\n * \n * This separation allows the Registry to remain lightweight and focused on\n * registration/discovery, while specialized tools handle schema transformation.\n * \n * **Benefits:**\n * - Auto-updating API documentation when object schemas change\n * - Consistent type definitions across API and database\n * - Reduced duplication and maintenance\n * - Registry remains protocol-agnostic and lightweight\n * \n * @example Reference Customer object\n * ```json\n * {\n * \"objectId\": \"customer\",\n * \"includeFields\": [\"id\", \"name\", \"email\"],\n * \"excludeFields\": [\"internal_notes\"]\n * }\n * ```\n */\nexport const ObjectQLReferenceSchema = z.object({\n /** Referenced object name (snake_case) */\n objectId: SnakeCaseIdentifierSchema.describe('Object name to reference'),\n \n /** Include only specific fields (optional) */\n includeFields: z.array(z.string()).optional()\n .describe('Include only these fields in the schema'),\n \n /** Exclude specific fields (optional) */\n excludeFields: z.array(z.string()).optional()\n .describe('Exclude these fields from the schema'),\n \n /** Include related objects via lookup fields */\n includeRelated: z.array(z.string()).optional()\n .describe('Include related objects via lookup fields'),\n});\n\nexport type ObjectQLReference = z.infer;\n\n/**\n * Schema Definition\n * \n * Unified schema definition that supports both:\n * 1. Static JSON Schema (traditional approach)\n * 2. Dynamic ObjectQL reference (linked to object definitions)\n * \n * When using ObjectQL references, the API documentation and validation\n * automatically update when object schemas change, eliminating the need\n * to manually sync API schemas with data models.\n */\nexport const SchemaDefinition = z.union([\n z.unknown().describe('Static JSON Schema definition'),\n z.object({\n $ref: ObjectQLReferenceSchema.describe('Dynamic reference to ObjectQL object'),\n }).describe('Dynamic ObjectQL reference'),\n]);\n\nexport type SchemaDefinition = z.infer;\n\n// ==========================================\n// API Parameter & Response Schemas\n// ==========================================\n\n/**\n * API Parameter Schema\n * \n * Defines a single API parameter (path, query, header, or body).\n * \n * **Enhancement: Dynamic Schema Linking**\n * - Supports both static JSON Schema and dynamic ObjectQL references\n * - When using ObjectQL references, parameter validation automatically updates\n * when the referenced object schema changes\n * \n * @example Static schema\n * ```json\n * {\n * \"name\": \"customer_id\",\n * \"in\": \"path\",\n * \"schema\": {\n * \"type\": \"string\",\n * \"format\": \"uuid\"\n * }\n * }\n * ```\n * \n * @example Dynamic ObjectQL reference\n * ```json\n * {\n * \"name\": \"customer\",\n * \"in\": \"body\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\",\n * \"excludeFields\": [\"internal_notes\"]\n * }\n * }\n * }\n * ```\n */\nexport const ApiParameterSchema = z.object({\n /** Parameter name */\n name: z.string().describe('Parameter name'),\n \n /** Parameter location */\n in: z.enum(['path', 'query', 'header', 'body', 'cookie']).describe('Parameter location'),\n \n /** Parameter description */\n description: z.string().optional().describe('Parameter description'),\n \n /** Required flag */\n required: z.boolean().default(false).describe('Whether parameter is required'),\n \n /** Parameter type/schema - supports static or dynamic (ObjectQL) schemas */\n schema: z.union([\n z.object({\n type: z.enum(['string', 'number', 'integer', 'boolean', 'array', 'object']).describe('Parameter type'),\n format: z.string().optional().describe('Format (e.g., date-time, email, uuid)'),\n enum: z.array(z.unknown()).optional().describe('Allowed values'),\n default: z.unknown().optional().describe('Default value'),\n items: z.unknown().optional().describe('Array item schema'),\n properties: z.record(z.string(), z.unknown()).optional().describe('Object properties'),\n }).describe('Static JSON Schema'),\n z.object({\n $ref: ObjectQLReferenceSchema,\n }).describe('Dynamic ObjectQL reference'),\n ]).describe('Parameter schema definition'),\n \n /** Example value */\n example: z.unknown().optional().describe('Example value'),\n});\n\nexport type ApiParameter = z.infer;\n\n/**\n * API Response Schema\n * \n * Defines an API response for a specific status code.\n * \n * **Enhancement: Dynamic Schema Linking**\n * - Response schema can reference ObjectQL objects\n * - When object definitions change, response documentation auto-updates\n * \n * @example Response with ObjectQL reference\n * ```json\n * {\n * \"statusCode\": 200,\n * \"description\": \"Customer retrieved successfully\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\",\n * \"excludeFields\": [\"password_hash\"]\n * }\n * }\n * }\n * ```\n */\nexport const ApiResponseSchema = z.object({\n /** HTTP status code */\n statusCode: HttpStatusCode.describe('HTTP status code'),\n \n /** Response description */\n description: z.string().describe('Response description'),\n \n /** Response content type */\n contentType: z.string().default('application/json').describe('Response content type'),\n \n /** Response schema - supports static or dynamic (ObjectQL) schemas */\n schema: z.union([\n z.unknown().describe('Static JSON Schema'),\n z.object({\n $ref: ObjectQLReferenceSchema,\n }).describe('Dynamic ObjectQL reference'),\n ]).optional().describe('Response body schema'),\n \n /** Response headers */\n headers: z.record(z.string(), z.object({\n description: z.string().optional(),\n schema: z.unknown(),\n })).optional().describe('Response headers'),\n \n /** Example response */\n example: z.unknown().optional().describe('Example response'),\n});\n\nexport type ApiResponse = z.infer;\nexport type ApiResponseInput = z.input;\n\n/**\n * API Endpoint Registration Schema\n * \n * Represents a single API endpoint registration with complete metadata.\n * \n * **Enhancements:**\n * 1. **RBAC Integration**: `requiredPermissions` field for automatic permission checking\n * 2. **Dynamic Schema Linking**: Parameters and responses can reference ObjectQL objects\n * 3. **Route Priority**: `priority` field for conflict resolution\n * 4. **Protocol Config**: `protocolConfig` for protocol-specific extensions\n * \n * @example REST Endpoint with RBAC\n * ```json\n * {\n * \"id\": \"get_customer_by_id\",\n * \"method\": \"GET\",\n * \"path\": \"/api/v1/data/customer/:id\",\n * \"summary\": \"Get customer by ID\",\n * \"requiredPermissions\": [\"customer.read\"],\n * \"parameters\": [\n * {\n * \"name\": \"id\",\n * \"in\": \"path\",\n * \"required\": true,\n * \"schema\": { \"type\": \"string\" }\n * }\n * ],\n * \"responses\": [\n * {\n * \"statusCode\": 200,\n * \"description\": \"Customer found\",\n * \"schema\": {\n * \"$ref\": {\n * \"objectId\": \"customer\"\n * }\n * }\n * }\n * ],\n * \"priority\": 100\n * }\n * ```\n * \n * @example Plugin Endpoint with Protocol Config\n * ```json\n * {\n * \"id\": \"grpc_service_method\",\n * \"path\": \"/grpc/ServiceName/MethodName\",\n * \"summary\": \"gRPC service method\",\n * \"protocolConfig\": {\n * \"subProtocol\": \"grpc\",\n * \"serviceName\": \"CustomerService\",\n * \"methodName\": \"GetCustomer\"\n * },\n * \"priority\": 50\n * }\n * ```\n */\nexport const ApiEndpointRegistrationSchema = z.object({\n /** Unique endpoint identifier */\n id: z.string().describe('Unique endpoint identifier'),\n \n /** HTTP method (for HTTP-based APIs) */\n method: HttpMethod.optional().describe('HTTP method'),\n \n /** URL path pattern */\n path: z.string().describe('URL path pattern'),\n \n /** Short summary */\n summary: z.string().optional().describe('Short endpoint summary'),\n \n /** Detailed description */\n description: z.string().optional().describe('Detailed endpoint description'),\n \n /** Operation ID (OpenAPI) */\n operationId: z.string().optional().describe('Unique operation identifier'),\n \n /** Tags for grouping */\n tags: z.array(z.string()).optional().default([]).describe('Tags for categorization'),\n \n /** Parameters */\n parameters: z.array(ApiParameterSchema).optional().default([]).describe('Endpoint parameters'),\n \n /** Request body schema */\n requestBody: z.object({\n description: z.string().optional(),\n required: z.boolean().default(false),\n contentType: z.string().default('application/json'),\n schema: z.unknown().optional(),\n example: z.unknown().optional(),\n }).optional().describe('Request body specification'),\n \n /** Response definitions */\n responses: z.array(ApiResponseSchema).optional().default([]).describe('Possible responses'),\n \n /** Rate Limiting */\n rateLimit: RateLimitConfigSchema.optional().describe('Endpoint specific rate limiting'),\n\n /** Security Requirements */\n security: z.array(z.record(z.string(), z.array(z.string()))).optional().describe('Security requirements (e.g. [{\"bearerAuth\": []}])'),\n \n /**\n * Required Permissions (RBAC Integration)\n * \n * Array of permission names required to access this endpoint.\n * The gateway layer automatically validates these permissions before\n * allowing the request to proceed, eliminating the need for permission\n * checks in individual API handlers.\n * \n * **Format:** `.` or system permission name\n * \n * **Object Permissions:**\n * - `customer.read` - Read customer records\n * - `customer.create` - Create customer records\n * - `customer.edit` - Update customer records\n * - `customer.delete` - Delete customer records\n * - `customer.viewAll` - View all customer records (bypass sharing)\n * - `customer.modifyAll` - Modify all customer records (bypass sharing)\n * \n * **System Permissions:**\n * - `manage_users` - User management\n * - `view_setup` - Access to system setup\n * - `customize_application` - Modify metadata\n * - `api_enabled` - API access\n * \n * @example Object-level permissions\n * ```json\n * {\n * \"requiredPermissions\": [\"customer.read\"]\n * }\n * ```\n * \n * @example Multiple permissions (ALL required)\n * ```json\n * {\n * \"requiredPermissions\": [\"customer.read\", \"account.read\"]\n * }\n * ```\n * \n * @example System permission\n * ```json\n * {\n * \"requiredPermissions\": [\"manage_users\"]\n * }\n * ```\n * \n * @see {@link file://../../permission/permission.zod.ts} for permission definitions\n */\n requiredPermissions: z.array(z.string()).optional().default([])\n .describe('Required RBAC permissions (e.g., \"customer.read\", \"manage_users\")'),\n \n /**\n * Route Priority\n * \n * Priority level for route conflict resolution. Higher priority routes\n * are registered first and take precedence when multiple routes match\n * the same path pattern.\n * \n * **Default:** 100 (medium priority)\n * **Range:** 0-1000 (higher = more important)\n * \n * **Use Cases:**\n * - Core system APIs: 900-1000\n * - Plugin APIs: 100-500\n * - Custom/override APIs: 500-900\n * - Fallback routes: 0-100\n * \n * @example High priority core endpoint\n * ```json\n * {\n * \"path\": \"/api/v1/data/:object/:id\",\n * \"priority\": 950\n * }\n * ```\n * \n * @example Medium priority plugin endpoint\n * ```json\n * {\n * \"path\": \"/api/v1/custom/action\",\n * \"priority\": 300\n * }\n * ```\n */\n priority: z.number().int().min(0).max(1000).optional().default(100)\n .describe('Route priority for conflict resolution (0-1000, higher = more important)'),\n \n /**\n * Protocol-Specific Configuration\n * \n * Allows plugins and custom APIs to define protocol-specific metadata\n * that can be used for specialized handling or documentation generation.\n * \n * **Examples:**\n * - gRPC: Service and method names\n * - tRPC: Procedure type (query/mutation)\n * - WebSocket: Event names and handlers\n * - Custom protocols: Any metadata needed\n * \n * @example gRPC configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"grpc\",\n * \"serviceName\": \"CustomerService\",\n * \"methodName\": \"GetCustomer\",\n * \"streaming\": false\n * }\n * }\n * ```\n * \n * @example tRPC configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"trpc\",\n * \"procedureType\": \"query\",\n * \"router\": \"customer\"\n * }\n * }\n * ```\n * \n * @example WebSocket configuration\n * ```json\n * {\n * \"protocolConfig\": {\n * \"subProtocol\": \"websocket\",\n * \"eventName\": \"customer.updated\",\n * \"direction\": \"server-to-client\"\n * }\n * }\n * ```\n */\n protocolConfig: z.record(z.string(), z.unknown()).optional()\n .describe('Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)'),\n \n /** Deprecation flag */\n deprecated: z.boolean().default(false).describe('Whether endpoint is deprecated'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation link'),\n});\n\nexport type ApiEndpointRegistration = z.infer;\nexport type ApiEndpointRegistrationInput = z.input;\n\n// ==========================================\n// API Registry Entry\n// ==========================================\n\n/**\n * API Metadata Schema\n * \n * Additional metadata for an API registration.\n */\nexport const ApiMetadataSchema = z.object({\n /** API owner/team */\n owner: z.string().optional().describe('Owner team or person'),\n \n /** API status */\n status: z.enum(['active', 'deprecated', 'experimental', 'beta']).default('active')\n .describe('API lifecycle status'),\n \n /** Categorization tags */\n tags: z.array(z.string()).optional().default([]).describe('Classification tags'),\n \n /** Plugin source (if plugin-registered) */\n pluginSource: z.string().optional().describe('Source plugin name'),\n \n /** Custom metadata */\n custom: z.record(z.string(), z.unknown()).optional().describe('Custom metadata fields'),\n});\n\nexport type ApiMetadata = z.infer;\nexport type ApiMetadataInput = z.input;\n\n/**\n * API Registry Entry Schema\n * \n * Complete registration entry for an API in the unified registry.\n * \n * @example REST API Entry\n * ```json\n * {\n * \"id\": \"customer_api\",\n * \"name\": \"Customer Management API\",\n * \"type\": \"rest\",\n * \"version\": \"v1\",\n * \"basePath\": \"/api/v1/data/customer\",\n * \"description\": \"CRUD operations for customer records\",\n * \"endpoints\": [...],\n * \"metadata\": {\n * \"owner\": \"sales_team\",\n * \"status\": \"active\",\n * \"tags\": [\"customer\", \"crm\"]\n * }\n * }\n * ```\n * \n * @example Plugin API Entry\n * ```json\n * {\n * \"id\": \"payment_webhook\",\n * \"name\": \"Payment Webhook API\",\n * \"type\": \"plugin\",\n * \"version\": \"1.0.0\",\n * \"basePath\": \"/plugins/payment/webhook\",\n * \"endpoints\": [...],\n * \"metadata\": {\n * \"pluginSource\": \"payment_gateway_plugin\",\n * \"status\": \"active\"\n * }\n * }\n * ```\n */\nexport const ApiRegistryEntrySchema = z.object({\n /** Unique API identifier */\n id: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique API identifier (snake_case)'),\n \n /** Human-readable name */\n name: z.string().describe('API display name'),\n \n /** API protocol type */\n type: ApiProtocolType.describe('API protocol type'),\n \n /** API version */\n version: z.string().describe('API version (e.g., v1, 2024-01)'),\n \n /** Base URL path */\n basePath: z.string().describe('Base URL path for this API'),\n \n /** API description */\n description: z.string().optional().describe('API description'),\n \n /** Endpoints in this API */\n endpoints: z.array(ApiEndpointRegistrationSchema).describe('Registered endpoints'),\n \n /** OpenAPI/GraphQL/OData specific configuration */\n config: z.record(z.string(), z.unknown()).optional().describe('Protocol-specific configuration'),\n \n /** API metadata */\n metadata: ApiMetadataSchema.optional().describe('Additional metadata'),\n \n /** Terms of service URL */\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n \n /** Contact information */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('Contact information'),\n \n /** License information */\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional().describe('License information'),\n});\n\nexport type ApiRegistryEntry = z.infer;\nexport type ApiRegistryEntryInput = z.input;\n\n// ==========================================\n// API Registry\n// ==========================================\n\n/**\n * Route Conflict Resolution Strategy\n * \n * Defines how to handle conflicts when multiple endpoints register\n * the same or overlapping URL patterns.\n */\nexport const ConflictResolutionStrategy = z.enum([\n 'error', // Throw error on conflict (safest, default)\n 'priority', // Use priority field to resolve (highest priority wins)\n 'first-wins', // First registered endpoint wins\n 'last-wins', // Last registered endpoint wins (override mode)\n]);\n\nexport type ConflictResolutionStrategy = z.infer;\n\n/**\n * API Registry Schema\n * \n * Central registry containing all registered APIs.\n * \n * **Enhancement: Route Conflict Detection**\n * - `conflictResolution`: Strategy for handling route conflicts\n * - Prevents silent overwrites and unexpected routing behavior\n * \n * @example\n * ```json\n * {\n * \"version\": \"1.0.0\",\n * \"conflictResolution\": \"priority\",\n * \"apis\": [\n * { \"id\": \"customer_api\", \"type\": \"rest\", ... },\n * { \"id\": \"graphql_api\", \"type\": \"graphql\", ... },\n * { \"id\": \"file_upload_api\", \"type\": \"file\", ... }\n * ],\n * \"totalApis\": 3,\n * \"totalEndpoints\": 47\n * }\n * ```\n * \n * @example Priority-based conflict resolution\n * ```json\n * {\n * \"conflictResolution\": \"priority\",\n * \"apis\": [\n * {\n * \"id\": \"core_api\",\n * \"endpoints\": [\n * {\n * \"path\": \"/api/v1/data/:object\",\n * \"priority\": 950\n * }\n * ]\n * },\n * {\n * \"id\": \"plugin_api\",\n * \"endpoints\": [\n * {\n * \"path\": \"/api/v1/data/custom\",\n * \"priority\": 300\n * }\n * ]\n * }\n * ]\n * }\n * ```\n */\nexport const ApiRegistrySchema = z.object({\n /** Registry version */\n version: z.string().describe('Registry version'),\n \n /**\n * Conflict Resolution Strategy\n * \n * Defines how to handle route conflicts when multiple endpoints\n * register the same or overlapping URL patterns.\n * \n * **Strategies:**\n * - `error`: Throw error on conflict (safest, prevents silent overwrites)\n * - `priority`: Use endpoint priority field (highest priority wins)\n * - `first-wins`: First registered endpoint wins (stable, predictable)\n * - `last-wins`: Last registered endpoint wins (allows overrides)\n * \n * **Default:** `error`\n * \n * **Best Practices:**\n * - Use `error` in production to catch configuration issues\n * - Use `priority` when mixing core and plugin APIs\n * - Use `last-wins` for development/testing overrides\n * \n * @example Prevent accidental conflicts\n * ```json\n * {\n * \"conflictResolution\": \"error\"\n * }\n * ```\n * \n * @example Allow plugin overrides with priority\n * ```json\n * {\n * \"conflictResolution\": \"priority\"\n * }\n * ```\n */\n conflictResolution: ConflictResolutionStrategy.optional().default('error')\n .describe('Strategy for handling route conflicts'),\n \n /** Registered APIs */\n apis: z.array(ApiRegistryEntrySchema).describe('All registered APIs'),\n \n /** Total API count */\n totalApis: z.number().int().describe('Total number of registered APIs'),\n \n /** Total endpoint count across all APIs */\n totalEndpoints: z.number().int().describe('Total number of endpoints'),\n \n /** APIs grouped by type */\n byType: z.record(ApiProtocolType, z.array(ApiRegistryEntrySchema)).optional()\n .describe('APIs grouped by protocol type'),\n \n /** APIs grouped by status */\n byStatus: z.record(z.string(), z.array(ApiRegistryEntrySchema)).optional()\n .describe('APIs grouped by status'),\n \n /** Last updated timestamp */\n updatedAt: z.string().datetime().optional().describe('Last registry update time'),\n});\n\nexport type ApiRegistry = z.infer;\n\n// ==========================================\n// API Discovery & Query\n// ==========================================\n\n/**\n * API Discovery Query Schema\n * \n * Query parameters for discovering/filtering APIs in the registry.\n * \n * @example\n * ```json\n * {\n * \"type\": \"rest\",\n * \"tags\": [\"customer\"],\n * \"status\": \"active\"\n * }\n * ```\n */\nexport const ApiDiscoveryQuerySchema = z.object({\n /** Filter by API type */\n type: ApiProtocolType.optional().describe('Filter by API protocol type'),\n \n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by tags (ANY match)'),\n \n /** Filter by status */\n status: z.enum(['active', 'deprecated', 'experimental', 'beta']).optional()\n .describe('Filter by lifecycle status'),\n \n /** Filter by plugin source */\n pluginSource: z.string().optional().describe('Filter by plugin name'),\n \n /** Search in name/description */\n search: z.string().optional().describe('Full-text search in name/description'),\n \n /** Filter by version */\n version: z.string().optional().describe('Filter by specific version'),\n});\n\nexport type ApiDiscoveryQuery = z.infer;\n\n/**\n * API Discovery Response Schema\n * \n * Response for API discovery queries.\n */\nexport const ApiDiscoveryResponseSchema = z.object({\n /** Matching APIs */\n apis: z.array(ApiRegistryEntrySchema).describe('Matching API entries'),\n \n /** Total matches */\n total: z.number().int().describe('Total matching APIs'),\n \n /** Applied filters */\n filters: ApiDiscoveryQuerySchema.optional().describe('Applied query filters'),\n});\n\nexport type ApiDiscoveryResponse = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create API endpoint registration\n */\nexport const ApiEndpointRegistration = Object.assign(ApiEndpointRegistrationSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API registry entry\n */\nexport const ApiRegistryEntry = Object.assign(ApiRegistryEntrySchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API registry\n */\nexport const ApiRegistry = Object.assign(ApiRegistrySchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * API Documentation & Testing Interface Protocol\n * \n * Provides schemas for generating interactive API documentation and testing\n * interfaces similar to Swagger UI, GraphQL Playground, Postman, etc.\n * \n * Features:\n * - OpenAPI/Swagger specification generation\n * - Interactive API testing playground\n * - API versioning and changelog\n * - Code generation templates\n * - Mock server configuration\n * \n * Architecture Alignment:\n * - Swagger UI: Interactive API documentation\n * - Postman: API testing collections\n * - GraphQL Playground: GraphQL-specific testing\n * - Redoc: Documentation rendering\n * \n * @example Documentation Config\n * ```typescript\n * const docConfig: ApiDocumentationConfig = {\n * enabled: true,\n * title: 'ObjectStack API',\n * version: '1.0.0',\n * servers: [{ url: 'https://api.example.com', description: 'Production' }],\n * ui: {\n * type: 'swagger-ui',\n * theme: 'light',\n * enableTryItOut: true\n * }\n * }\n * ```\n */\n\n// ==========================================\n// OpenAPI Specification\n// ==========================================\n\n/**\n * OpenAPI Server Schema\n * \n * Server configuration for OpenAPI specification.\n */\nexport const OpenApiServerSchema = z.object({\n /** Server URL */\n url: z.string().url().describe('Server base URL'),\n \n /** Server description */\n description: z.string().optional().describe('Server description'),\n \n /** Server variables */\n variables: z.record(z.string(), z.object({\n default: z.string(),\n description: z.string().optional(),\n enum: z.array(z.string()).optional(),\n })).optional().describe('URL template variables'),\n});\n\nexport type OpenApiServer = z.infer;\n\n/**\n * OpenAPI Security Scheme Schema\n * \n * Security scheme definition for OpenAPI.\n */\nexport const OpenApiSecuritySchemeSchema = z.object({\n /** Security scheme type */\n type: z.enum(['apiKey', 'http', 'oauth2', 'openIdConnect']).describe('Security type'),\n \n /** Scheme name */\n scheme: z.string().optional().describe('HTTP auth scheme (bearer, basic, etc.)'),\n \n /** Bearer format */\n bearerFormat: z.string().optional().describe('Bearer token format (e.g., JWT)'),\n \n /** API key name */\n name: z.string().optional().describe('API key parameter name'),\n \n /** API key location */\n in: z.enum(['header', 'query', 'cookie']).optional().describe('API key location'),\n \n /** OAuth flows */\n flows: z.object({\n implicit: z.unknown().optional(),\n password: z.unknown().optional(),\n clientCredentials: z.unknown().optional(),\n authorizationCode: z.unknown().optional(),\n }).optional().describe('OAuth2 flows'),\n \n /** OpenID Connect URL */\n openIdConnectUrl: z.string().url().optional().describe('OpenID Connect discovery URL'),\n \n /** Description */\n description: z.string().optional().describe('Security scheme description'),\n});\n\nexport type OpenApiSecurityScheme = z.infer;\n\n/**\n * OpenAPI Specification Schema\n * \n * Complete OpenAPI 3.0 specification structure.\n * \n * @see https://swagger.io/specification/\n * \n * @example\n * ```json\n * {\n * \"openapi\": \"3.0.0\",\n * \"info\": {\n * \"title\": \"ObjectStack API\",\n * \"version\": \"1.0.0\",\n * \"description\": \"ObjectStack unified API\"\n * },\n * \"servers\": [\n * { \"url\": \"https://api.example.com\" }\n * ],\n * \"paths\": { ... },\n * \"components\": { ... }\n * }\n * ```\n */\nexport const OpenApiSpecSchema = z.object({\n /** OpenAPI version */\n openapi: z.string().default('3.0.0').describe('OpenAPI specification version'),\n \n /** API information */\n info: z.object({\n title: z.string().describe('API title'),\n version: z.string().describe('API version'),\n description: z.string().optional().describe('API description'),\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional(),\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional(),\n }).describe('API metadata'),\n \n /** Servers */\n servers: z.array(OpenApiServerSchema).optional().default([]).describe('API servers'),\n \n /** API paths */\n paths: z.record(z.string(), z.unknown()).describe('API paths and operations'),\n \n /** Reusable components */\n components: z.object({\n schemas: z.record(z.string(), z.unknown()).optional(),\n responses: z.record(z.string(), z.unknown()).optional(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n examples: z.record(z.string(), z.unknown()).optional(),\n requestBodies: z.record(z.string(), z.unknown()).optional(),\n headers: z.record(z.string(), z.unknown()).optional(),\n securitySchemes: z.record(z.string(), OpenApiSecuritySchemeSchema).optional(),\n links: z.record(z.string(), z.unknown()).optional(),\n callbacks: z.record(z.string(), z.unknown()).optional(),\n }).optional().describe('Reusable components'),\n \n /** Security requirements */\n security: z.array(z.record(z.string(), z.array(z.string()))).optional()\n .describe('Global security requirements'),\n \n /** Tags */\n tags: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional(),\n })).optional().describe('Tag definitions'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation'),\n});\n\nexport type OpenApiSpec = z.infer;\n\n// ==========================================\n// API Testing Playground\n// ==========================================\n\n/**\n * API Testing UI Type\n */\nexport const ApiTestingUiType = z.enum([\n 'swagger-ui', // Swagger UI\n 'redoc', // Redoc\n 'rapidoc', // RapiDoc\n 'stoplight', // Stoplight Elements\n 'scalar', // Scalar API Reference\n 'graphql-playground', // GraphQL Playground\n 'graphiql', // GraphiQL\n 'postman', // Postman-like interface\n 'custom', // Custom implementation\n]);\n\nexport type ApiTestingUiType = z.infer;\n\n/**\n * API Testing UI Configuration Schema\n * \n * Configuration for interactive API testing interface.\n * \n * @example Swagger UI Config\n * ```json\n * {\n * \"type\": \"swagger-ui\",\n * \"path\": \"/api-docs\",\n * \"theme\": \"light\",\n * \"enableTryItOut\": true,\n * \"enableFilter\": true,\n * \"enableCors\": true,\n * \"defaultModelsExpandDepth\": 1\n * }\n * ```\n */\nexport const ApiTestingUiConfigSchema = z.object({\n /** UI type */\n type: ApiTestingUiType.describe('Testing UI implementation'),\n \n /** UI path */\n path: z.string().default('/api-docs').describe('URL path for documentation UI'),\n \n /** UI theme */\n theme: z.enum(['light', 'dark', 'auto']).default('light').describe('UI color theme'),\n \n /** Enable try-it-out feature */\n enableTryItOut: z.boolean().default(true).describe('Enable interactive API testing'),\n \n /** Enable filtering */\n enableFilter: z.boolean().default(true).describe('Enable endpoint filtering'),\n \n /** Enable CORS for testing */\n enableCors: z.boolean().default(true).describe('Enable CORS for browser testing'),\n \n /** Default expand depth for models */\n defaultModelsExpandDepth: z.number().int().min(-1).default(1)\n .describe('Default expand depth for schemas (-1 = fully expand)'),\n \n /** Display request duration */\n displayRequestDuration: z.boolean().default(true).describe('Show request duration'),\n \n /** Syntax highlighting */\n syntaxHighlighting: z.boolean().default(true).describe('Enable syntax highlighting'),\n \n /** Custom CSS URL */\n customCssUrl: z.string().url().optional().describe('Custom CSS stylesheet URL'),\n \n /** Custom JavaScript URL */\n customJsUrl: z.string().url().optional().describe('Custom JavaScript URL'),\n \n /** Layout options */\n layout: z.object({\n showExtensions: z.boolean().default(false).describe('Show vendor extensions'),\n showCommonExtensions: z.boolean().default(false).describe('Show common extensions'),\n deepLinking: z.boolean().default(true).describe('Enable deep linking'),\n displayOperationId: z.boolean().default(false).describe('Display operation IDs'),\n defaultModelRendering: z.enum(['example', 'model']).default('example')\n .describe('Default model rendering mode'),\n defaultModelsExpandDepth: z.number().int().default(1).describe('Models expand depth'),\n defaultModelExpandDepth: z.number().int().default(1).describe('Single model expand depth'),\n docExpansion: z.enum(['list', 'full', 'none']).default('list')\n .describe('Documentation expansion mode'),\n }).optional().describe('Layout configuration'),\n});\n\nexport type ApiTestingUiConfig = z.infer;\n\n/**\n * API Test Request Schema\n * \n * Represents a saved/example API test request.\n * \n * @example\n * ```json\n * {\n * \"name\": \"Get Customer by ID\",\n * \"description\": \"Retrieves a customer record\",\n * \"method\": \"GET\",\n * \"url\": \"/api/v1/data/customer/123\",\n * \"headers\": {\n * \"Authorization\": \"Bearer {{token}}\"\n * },\n * \"variables\": {\n * \"token\": \"sample_token\"\n * }\n * }\n * ```\n */\nexport const ApiTestRequestSchema = z.object({\n /** Request name */\n name: z.string().describe('Test request name'),\n \n /** Request description */\n description: z.string().optional().describe('Request description'),\n \n /** HTTP method */\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])\n .describe('HTTP method'),\n \n /** Request URL */\n url: z.string().describe('Request URL (can include variables)'),\n \n /** Request headers */\n headers: z.record(z.string(), z.string()).optional().default({})\n .describe('Request headers'),\n \n /** Query parameters */\n queryParams: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional().default({}).describe('Query parameters'),\n \n /** Request body */\n body: z.unknown().optional().describe('Request body'),\n \n /** Environment variables */\n variables: z.record(z.string(), z.unknown()).optional().default({})\n .describe('Template variables'),\n \n /** Expected response */\n expectedResponse: z.object({\n statusCode: z.number().int(),\n body: z.unknown().optional(),\n }).optional().describe('Expected response for validation'),\n});\n\nexport type ApiTestRequest = z.infer;\n\n/**\n * API Test Collection Schema\n * \n * Collection of test requests (similar to Postman collections).\n * \n * @example\n * ```json\n * {\n * \"name\": \"Customer API Tests\",\n * \"description\": \"Test collection for customer endpoints\",\n * \"variables\": {\n * \"baseUrl\": \"https://api.example.com\",\n * \"apiKey\": \"test_key\"\n * },\n * \"requests\": [...]\n * }\n * ```\n */\nexport const ApiTestCollectionSchema = z.object({\n /** Collection name */\n name: z.string().describe('Collection name'),\n \n /** Collection description */\n description: z.string().optional().describe('Collection description'),\n \n /** Collection variables */\n variables: z.record(z.string(), z.unknown()).optional().default({})\n .describe('Shared variables'),\n \n /** Test requests */\n requests: z.array(ApiTestRequestSchema).describe('Test requests in this collection'),\n \n /** Folders/grouping */\n folders: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n requests: z.array(ApiTestRequestSchema),\n })).optional().describe('Request folders for organization'),\n});\n\nexport type ApiTestCollection = z.infer;\n\n// ==========================================\n// API Documentation Configuration\n// ==========================================\n\n/**\n * API Changelog Entry Schema\n * \n * Documents changes in API versions.\n */\nexport const ApiChangelogEntrySchema = z.object({\n /** Version */\n version: z.string().describe('API version'),\n \n /** Release date */\n date: z.string().date().describe('Release date'),\n \n /** Changes */\n changes: z.object({\n added: z.array(z.string()).optional().default([]).describe('New features'),\n changed: z.array(z.string()).optional().default([]).describe('Changes'),\n deprecated: z.array(z.string()).optional().default([]).describe('Deprecations'),\n removed: z.array(z.string()).optional().default([]).describe('Removed features'),\n fixed: z.array(z.string()).optional().default([]).describe('Bug fixes'),\n security: z.array(z.string()).optional().default([]).describe('Security fixes'),\n }).describe('Version changes'),\n \n /** Migration guide */\n migrationGuide: z.string().optional().describe('Migration guide URL or text'),\n});\n\nexport type ApiChangelogEntry = z.infer;\n\n/**\n * Code Generation Template Schema\n * \n * Templates for generating client code.\n */\nexport const CodeGenerationTemplateSchema = z.object({\n /** Language/framework */\n language: z.string().describe('Target language/framework (e.g., typescript, python, curl)'),\n \n /** Template name */\n name: z.string().describe('Template name'),\n \n /** Template content */\n template: z.string().describe('Code template with placeholders'),\n \n /** Template variables */\n variables: z.array(z.string()).optional().describe('Required template variables'),\n});\n\nexport type CodeGenerationTemplate = z.infer;\n\n/**\n * API Documentation Configuration Schema\n * \n * Complete configuration for API documentation and testing interface.\n * \n * @example\n * ```json\n * {\n * \"enabled\": true,\n * \"title\": \"ObjectStack API Documentation\",\n * \"version\": \"1.0.0\",\n * \"description\": \"Unified API for ObjectStack platform\",\n * \"servers\": [\n * { \"url\": \"https://api.example.com\", \"description\": \"Production\" }\n * ],\n * \"ui\": {\n * \"type\": \"swagger-ui\",\n * \"theme\": \"light\",\n * \"enableTryItOut\": true\n * },\n * \"generateOpenApi\": true,\n * \"generateTestCollections\": true\n * }\n * ```\n */\nexport const ApiDocumentationConfigSchema = z.object({\n /** Enable documentation */\n enabled: z.boolean().default(true).describe('Enable API documentation'),\n \n /** Documentation title */\n title: z.string().default('API Documentation').describe('Documentation title'),\n \n /** API version */\n version: z.string().describe('API version'),\n \n /** API description */\n description: z.string().optional().describe('API description'),\n \n /** Server configurations */\n servers: z.array(OpenApiServerSchema).optional().default([])\n .describe('API server URLs'),\n \n /** UI configuration */\n ui: ApiTestingUiConfigSchema.optional().describe('Testing UI configuration'),\n \n /** Generate OpenAPI spec */\n generateOpenApi: z.boolean().default(true).describe('Generate OpenAPI 3.0 specification'),\n \n /** Generate test collections */\n generateTestCollections: z.boolean().default(true)\n .describe('Generate API test collections'),\n \n /** Test collections */\n testCollections: z.array(ApiTestCollectionSchema).optional().default([])\n .describe('Predefined test collections'),\n \n /** API changelog */\n changelog: z.array(ApiChangelogEntrySchema).optional().default([])\n .describe('API version changelog'),\n \n /** Code generation templates */\n codeTemplates: z.array(CodeGenerationTemplateSchema).optional().default([])\n .describe('Code generation templates'),\n \n /** Terms of service */\n termsOfService: z.string().url().optional().describe('Terms of service URL'),\n \n /** Contact information */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('Contact information'),\n \n /** License */\n license: z.object({\n name: z.string(),\n url: z.string().url().optional(),\n }).optional().describe('API license'),\n \n /** External documentation */\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional().describe('External documentation link'),\n \n /** Security schemes */\n securitySchemes: z.record(z.string(), OpenApiSecuritySchemeSchema).optional()\n .describe('Security scheme definitions'),\n \n /** Global tags */\n tags: z.array(z.object({\n name: z.string(),\n description: z.string().optional(),\n externalDocs: z.object({\n description: z.string().optional(),\n url: z.string().url(),\n }).optional(),\n })).optional().describe('Global tag definitions'),\n});\n\nexport type ApiDocumentationConfig = z.infer;\n\n// ==========================================\n// API Documentation Generation\n// ==========================================\n\n/**\n * Generated API Documentation Schema\n * \n * Output of documentation generation process.\n */\nexport const GeneratedApiDocumentationSchema = z.object({\n /** OpenAPI specification */\n openApiSpec: OpenApiSpecSchema.optional().describe('Generated OpenAPI specification'),\n \n /** Test collections */\n testCollections: z.array(ApiTestCollectionSchema).optional()\n .describe('Generated test collections'),\n \n /** Markdown documentation */\n markdown: z.string().optional().describe('Generated markdown documentation'),\n \n /** HTML documentation */\n html: z.string().optional().describe('Generated HTML documentation'),\n \n /** Generation timestamp */\n generatedAt: z.string().datetime().describe('Generation timestamp'),\n \n /** Source APIs */\n sourceApis: z.array(z.string()).describe('Source API IDs used for generation'),\n});\n\nexport type GeneratedApiDocumentation = z.infer;\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create API documentation config\n */\nexport const ApiDocumentationConfig = Object.assign(ApiDocumentationConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create API test collection\n */\nexport const ApiTestCollection = Object.assign(ApiTestCollectionSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create OpenAPI specification\n */\nexport const OpenApiSpec = Object.assign(OpenApiSpecSchema, {\n create: >(config: T) => config,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { AnalyticsQuerySchema, CubeSchema } from '../data/analytics.zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Analytics API Protocol\n * \n * Defines the HTTP interface for the Semantic Layer.\n * Provides endpoints for executing analytical queries and discovering metadata.\n */\n\n// ==========================================\n// 1. API Endpoints\n// ==========================================\n\nexport const AnalyticsEndpoint = z.enum([\n '/api/v1/analytics/query', // Execute analysis\n '/api/v1/analytics/meta', // Discover cubes/metrics\n '/api/v1/analytics/sql', // Dry-run SQL generation\n]);\n\n// ==========================================\n// 2. Query Execution\n// ==========================================\n\n/**\n * Query Request Body\n */\nexport const AnalyticsQueryRequestSchema = z.object({\n query: AnalyticsQuerySchema.describe('The analytic query definition'),\n cube: z.string().describe('Target cube name'),\n format: z.enum(['json', 'csv', 'xlsx']).default('json').describe('Response format'),\n});\n\n/**\n * Query Response (JSON)\n */\nexport const AnalyticsResultResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n rows: z.array(z.record(z.string(), z.unknown())).describe('Result rows'),\n fields: z.array(z.object({\n name: z.string(),\n type: z.string(),\n })).describe('Column metadata'),\n sql: z.string().optional().describe('Executed SQL (if debug enabled)'),\n }),\n});\n\n// ==========================================\n// 3. Metadata Discovery\n// ==========================================\n\n/**\n * Meta Request\n */\nexport const GetAnalyticsMetaRequestSchema = z.object({\n cube: z.string().optional().describe('Optional cube name to filter'),\n});\n\n/**\n * Meta Response\n * Returns available cubes, metrics, and dimensions.\n */\nexport const AnalyticsMetadataResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n cubes: z.array(CubeSchema).describe('Available cubes'),\n }),\n});\n\n// ==========================================\n// 4. SQL Dry-Run\n// ==========================================\n\nexport const AnalyticsSqlResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n sql: z.string(),\n params: z.array(z.unknown()),\n }),\n});\n\nexport type AnalyticsEndpoint = z.infer;\nexport type AnalyticsQueryRequest = z.infer;\nexport type AnalyticsMetadataResponse = z.infer;\nexport type AnalyticsSqlResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * # API Versioning Protocol\n * \n * Defines how API versions are negotiated between client and server.\n * Supports multiple versioning strategies and deprecation lifecycle management.\n * \n * Architecture Alignment:\n * - Salesforce: URL path versioning (v57.0, v58.0)\n * - Stripe: Date-based versioning (2024-01-01)\n * - Kubernetes: API group versioning (v1, v1beta1)\n * - GitHub: Accept header versioning (application/vnd.github.v3+json)\n * - Microsoft Graph: URL path versioning (v1.0, beta)\n */\n\n// ==========================================\n// Versioning Strategy\n// ==========================================\n\n/**\n * API Versioning Strategy\n * Determines how the API version is specified by clients.\n * \n * - `urlPath`: Version in URL path (e.g., /api/v1/data) — Most common, easy to understand\n * - `header`: Version in Accept header (e.g., Accept: application/vnd.objectstack.v1+json)\n * - `queryParam`: Version in query parameter (e.g., /api/data?version=v1)\n * - `dateBased`: Date-based version in header (e.g., ObjectStack-Version: 2025-01-01) — Stripe-style\n */\nexport const VersioningStrategy = z.enum([\n 'urlPath',\n 'header',\n 'queryParam',\n 'dateBased',\n]);\n\nexport type VersioningStrategy = z.infer;\n\n// ==========================================\n// Version Lifecycle\n// ==========================================\n\n/**\n * API Version Status\n * Lifecycle state of an API version.\n * \n * - `preview`: Available for testing, may change without notice (e.g., v2beta1)\n * - `current`: The recommended stable version\n * - `supported`: Older but still maintained (receives security fixes)\n * - `deprecated`: Scheduled for removal, clients should migrate\n * - `retired`: No longer available, requests return 410 Gone\n */\nexport const VersionStatus = z.enum([\n 'preview',\n 'current',\n 'supported',\n 'deprecated',\n 'retired',\n]);\n\nexport type VersionStatus = z.infer;\n\n// ==========================================\n// Version Definition\n// ==========================================\n\n/**\n * API Version Definition Schema\n * Describes a single API version and its lifecycle metadata.\n * \n * @example\n * {\n * \"version\": \"v1\",\n * \"status\": \"current\",\n * \"releasedAt\": \"2025-01-15\",\n * \"description\": \"Initial stable release\"\n * }\n * \n * @example Deprecated version\n * {\n * \"version\": \"v0\",\n * \"status\": \"deprecated\",\n * \"releasedAt\": \"2024-06-01\",\n * \"deprecatedAt\": \"2025-01-15\",\n * \"sunsetAt\": \"2025-07-15\",\n * \"migrationGuide\": \"https://docs.objectstack.dev/migrate/v0-to-v1\",\n * \"description\": \"Legacy API version\"\n * }\n */\nexport const VersionDefinitionSchema = z.object({\n /** Version identifier (e.g., \"v1\", \"v2beta1\", \"2025-01-01\") */\n version: z.string().describe('Version identifier (e.g., \"v1\", \"v2beta1\", \"2025-01-01\")'),\n\n /** Current lifecycle status */\n status: VersionStatus.describe('Lifecycle status of this version'),\n\n /** Date this version was released (ISO 8601 date) */\n releasedAt: z.string().describe('Release date (ISO 8601, e.g., \"2025-01-15\")'),\n\n /** Date this version was deprecated (ISO 8601 date) */\n deprecatedAt: z.string().optional()\n .describe('Deprecation date (ISO 8601). Only set for deprecated/retired versions'),\n\n /** Date this version will be retired (ISO 8601 date) */\n sunsetAt: z.string().optional()\n .describe('Sunset date (ISO 8601). After this date, the version returns 410 Gone'),\n\n /** URL to migration guide for moving to a newer version */\n migrationGuide: z.string().url().optional()\n .describe('URL to migration guide for upgrading from this version'),\n\n /** Human-readable description of this version */\n description: z.string().optional()\n .describe('Human-readable description or release notes summary'),\n\n /** Breaking changes introduced in or since this version */\n breakingChanges: z.array(z.string()).optional()\n .describe('List of breaking changes (for preview/new versions)'),\n});\n\nexport type VersionDefinition = z.infer;\n\n// ==========================================\n// Versioning Configuration\n// ==========================================\n\n/**\n * API Versioning Configuration Schema\n * Complete configuration for API version management.\n * \n * @example\n * {\n * \"strategy\": \"urlPath\",\n * \"current\": \"v1\",\n * \"default\": \"v1\",\n * \"versions\": [\n * { \"version\": \"v1\", \"status\": \"current\", \"releasedAt\": \"2025-01-15\" },\n * { \"version\": \"v2beta1\", \"status\": \"preview\", \"releasedAt\": \"2025-06-01\" }\n * ],\n * \"deprecation\": {\n * \"warnHeader\": true,\n * \"sunsetHeader\": true\n * }\n * }\n */\nexport const VersioningConfigSchema = z.object({\n /** Versioning strategy */\n strategy: VersioningStrategy.default('urlPath')\n .describe('How the API version is specified by clients'),\n\n /** Current (recommended) API version */\n current: z.string().describe('The current/recommended API version identifier'),\n\n /** Default version when none specified by client */\n default: z.string().describe('Fallback version when client does not specify one'),\n\n /** All available API versions */\n versions: z.array(VersionDefinitionSchema)\n .min(1)\n .describe('All available API versions with lifecycle metadata'),\n\n /** Header name for header-based versioning */\n headerName: z.string().default('ObjectStack-Version')\n .describe('HTTP header name for version negotiation (header/dateBased strategies)'),\n\n /** Query parameter name for queryParam strategy */\n queryParamName: z.string().default('version')\n .describe('Query parameter name for version specification (queryParam strategy)'),\n\n /** URL prefix pattern for urlPath strategy */\n urlPrefix: z.string().default('/api')\n .describe('URL prefix before version segment (urlPath strategy)'),\n\n /** Deprecation behavior */\n deprecation: z.object({\n /** Include Deprecation header in responses for deprecated versions */\n warnHeader: z.boolean().default(true)\n .describe('Include Deprecation header (RFC 8594) in responses'),\n\n /** Include Sunset header with retirement date */\n sunsetHeader: z.boolean().default(true)\n .describe('Include Sunset header (RFC 8594) with retirement date'),\n\n /** Include Link header pointing to migration guide */\n linkHeader: z.boolean().default(true)\n .describe('Include Link header pointing to migration guide URL'),\n\n /** Whether to reject requests to retired versions */\n rejectRetired: z.boolean().default(true)\n .describe('Return 410 Gone for retired API versions'),\n\n /** Custom deprecation warning message */\n warningMessage: z.string().optional()\n .describe('Custom warning message for deprecated version responses'),\n }).optional().describe('Deprecation lifecycle behavior'),\n\n /** Whether to include version info in discovery response */\n includeInDiscovery: z.boolean().default(true)\n .describe('Include version information in the API discovery endpoint'),\n});\n\nexport type VersioningConfig = z.infer;\nexport type VersioningConfigInput = z.input;\n\n// ==========================================\n// Version Negotiation Response\n// ==========================================\n\n/**\n * Version Negotiation Response Schema\n * Returned when a client requests version information or\n * included in the discovery endpoint response.\n * \n * @example\n * {\n * \"current\": \"v1\",\n * \"requested\": \"v1\",\n * \"resolved\": \"v1\",\n * \"supported\": [\"v1\", \"v2beta1\"],\n * \"deprecated\": [\"v0\"],\n * \"versions\": [...]\n * }\n */\nexport const VersionNegotiationResponseSchema = z.object({\n /** The current/recommended version */\n current: z.string().describe('Current recommended API version'),\n\n /** The version the client requested (if any) */\n requested: z.string().optional().describe('Version requested by the client'),\n\n /** The version actually being used for this request */\n resolved: z.string().describe('Resolved API version for this request'),\n\n /** All supported (non-retired) version identifiers */\n supported: z.array(z.string()).describe('All supported version identifiers'),\n\n /** Deprecated version identifiers (still functional but will be removed) */\n deprecated: z.array(z.string()).optional()\n .describe('Deprecated version identifiers'),\n\n /** Full version definitions (optional, for detailed clients) */\n versions: z.array(VersionDefinitionSchema).optional()\n .describe('Full version definitions with lifecycle metadata'),\n});\n\nexport type VersionNegotiationResponse = z.infer;\n\n// ==========================================\n// Default Versioning Configuration\n// ==========================================\n\n/**\n * Default versioning configuration for ObjectStack.\n * Uses URL path strategy with v1 as the current/default version.\n */\nexport const DEFAULT_VERSIONING_CONFIG: VersioningConfigInput = {\n strategy: 'urlPath',\n current: 'v1',\n default: 'v1',\n versions: [\n {\n version: 'v1',\n status: 'current',\n releasedAt: '2025-01-15',\n description: 'ObjectStack API v1 — Initial stable release',\n },\n ],\n deprecation: {\n warnHeader: true,\n sunsetHeader: true,\n linkHeader: true,\n rejectRetired: true,\n },\n includeInDiscovery: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Authentication Service Protocol\n * \n * Defines the standard API contracts for Identity, Session Management,\n * and Access Control.\n */\n\n// ==========================================\n// Authentication Types\n// ==========================================\n\nexport const AuthProvider = z.enum([\n 'local',\n 'google',\n 'github',\n 'microsoft',\n 'ldap',\n 'saml'\n]);\n\nexport const SessionUserSchema = z.object({\n id: z.string().describe('User ID'),\n email: z.string().email().describe('Email address'),\n emailVerified: z.boolean().default(false).describe('Is email verified?'),\n name: z.string().describe('Display name'),\n image: z.string().optional().describe('Avatar URL'),\n username: z.string().optional().describe('Username (optional)'),\n roles: z.array(z.string()).optional().default([]).describe('Assigned role IDs'),\n tenantId: z.string().optional().describe('Current tenant ID'),\n language: z.string().default('en').describe('Preferred language'),\n timezone: z.string().optional().describe('Preferred timezone'),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n});\n\nexport const SessionSchema = z.object({\n id: z.string(),\n expiresAt: z.string().datetime(),\n token: z.string().optional(),\n ipAddress: z.string().optional(),\n userAgent: z.string().optional(),\n userId: z.string(),\n});\n\n// ==========================================\n// Requests\n// ==========================================\n\nexport const LoginType = z.enum(['email', 'username', 'phone', 'magic-link', 'social']);\n\nexport const LoginRequestSchema = z.object({\n type: LoginType.default('email').describe('Login method'),\n email: z.string().email().optional().describe('Required for email/magic-link'),\n username: z.string().optional().describe('Required for username login'),\n password: z.string().optional().describe('Required for password login'),\n provider: z.string().optional().describe('Required for social (google, github)'),\n redirectTo: z.string().optional().describe('Redirect URL after successful login'),\n});\n\nexport const RegisterRequestSchema = z.object({\n email: z.string().email(),\n password: z.string(),\n name: z.string(),\n image: z.string().optional(),\n});\n\nexport const RefreshTokenRequestSchema = z.object({\n refreshToken: z.string().describe('Refresh token'),\n});\n\n// ==========================================\n// Responses\n// ==========================================\n\nexport const SessionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n session: SessionSchema.describe('Active Session Info'),\n user: SessionUserSchema.describe('Current User Details'),\n token: z.string().optional().describe('Bearer token if not using cookies'),\n }),\n});\n\nexport const UserProfileResponseSchema = BaseResponseSchema.extend({\n data: SessionUserSchema,\n});\n\nexport type AuthProvider = z.infer;\nexport type SessionUser = z.infer;\nexport type SessionUserInput = z.input;\nexport type Session = z.infer;\nexport type LoginType = z.infer;\nexport type LoginRequest = z.infer;\nexport type LoginRequestInput = z.input;\nexport type RegisterRequest = z.infer;\nexport type RefreshTokenRequest = z.infer;\nexport type SessionResponse = z.infer;\nexport type UserProfileResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Authentication Endpoint Specification\n * \n * Defines the canonical HTTP endpoints for the authentication service.\n * Based on better-auth v1.4.18 endpoint conventions.\n * \n * NOTE: ObjectStack's auth implementation uses better-auth library which has\n * established endpoint conventions. This spec documents those conventions as\n * the canonical API contract.\n */\n\n// ==========================================\n// Endpoint Path Definitions\n// ==========================================\n\n/**\n * Authentication Endpoint Paths\n * \n * These are the paths relative to the auth base route (e.g., /api/v1/auth).\n * Based on better-auth's endpoint structure.\n */\nexport const AuthEndpointPaths = {\n // Email/Password Authentication\n signInEmail: '/sign-in/email',\n signUpEmail: '/sign-up/email',\n signOut: '/sign-out',\n \n // Session Management\n getSession: '/get-session',\n \n // Password Management\n forgetPassword: '/forget-password',\n resetPassword: '/reset-password',\n \n // Email Verification\n sendVerificationEmail: '/send-verification-email',\n verifyEmail: '/verify-email',\n \n // OAuth (dynamic based on provider)\n // authorize: '/authorize/:provider'\n // callback: '/callback/:provider'\n \n // 2FA (when enabled)\n twoFactorEnable: '/two-factor/enable',\n twoFactorVerify: '/two-factor/verify',\n \n // Passkeys (when enabled)\n passkeyRegister: '/passkey/register',\n passkeyAuthenticate: '/passkey/authenticate',\n \n // Magic Links (when enabled)\n magicLinkSend: '/magic-link/send',\n magicLinkVerify: '/magic-link/verify',\n} as const;\n\n/**\n * HTTP Method + Path Specification\n * \n * Defines the complete HTTP contract for each endpoint.\n */\nexport const AuthEndpointSchema = z.object({\n /** Sign in with email and password */\n signInEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signInEmail),\n description: z.literal('Sign in with email and password'),\n }),\n \n /** Register new user with email and password */\n signUpEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signUpEmail),\n description: z.literal('Register new user with email and password'),\n }),\n \n /** Sign out current user */\n signOut: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.signOut),\n description: z.literal('Sign out current user'),\n }),\n \n /** Get current user session */\n getSession: z.object({\n method: z.literal('GET'),\n path: z.literal(AuthEndpointPaths.getSession),\n description: z.literal('Get current user session'),\n }),\n \n /** Request password reset email */\n forgetPassword: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.forgetPassword),\n description: z.literal('Request password reset email'),\n }),\n \n /** Reset password with token */\n resetPassword: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.resetPassword),\n description: z.literal('Reset password with token'),\n }),\n \n /** Send email verification */\n sendVerificationEmail: z.object({\n method: z.literal('POST'),\n path: z.literal(AuthEndpointPaths.sendVerificationEmail),\n description: z.literal('Send email verification link'),\n }),\n \n /** Verify email with token */\n verifyEmail: z.object({\n method: z.literal('GET'),\n path: z.literal(AuthEndpointPaths.verifyEmail),\n description: z.literal('Verify email with token'),\n }),\n});\n\n/**\n * Endpoint Aliases\n * \n * Common aliases for better developer experience.\n * These map to the canonical better-auth endpoints.\n */\nexport const AuthEndpointAliases = {\n login: AuthEndpointPaths.signInEmail,\n register: AuthEndpointPaths.signUpEmail,\n logout: AuthEndpointPaths.signOut,\n me: AuthEndpointPaths.getSession,\n} as const;\n\n/**\n * Full Endpoint URLs\n * \n * Helper to construct full endpoint URLs given a base path.\n */\nexport function getAuthEndpointUrl(basePath: string, endpoint: keyof typeof AuthEndpointPaths): string {\n const cleanBase = basePath.replace(/\\/$/, '');\n return `${cleanBase}${AuthEndpointPaths[endpoint]}`;\n}\n\n/**\n * Endpoint Mapping\n * \n * Maps common/legacy endpoint names to canonical better-auth paths.\n * This allows clients to use simpler names while maintaining compatibility.\n */\nexport const EndpointMapping = {\n '/login': AuthEndpointPaths.signInEmail,\n '/register': AuthEndpointPaths.signUpEmail,\n '/logout': AuthEndpointPaths.signOut,\n '/me': AuthEndpointPaths.getSession,\n '/refresh': AuthEndpointPaths.getSession, // Session refresh handled by better-auth automatically\n} as const;\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type AuthEndpoint = z.infer;\nexport type AuthEndpointPath = typeof AuthEndpointPaths[keyof typeof AuthEndpointPaths];\nexport type AuthEndpointAlias = keyof typeof AuthEndpointAliases;\nexport type EndpointMappingKey = keyof typeof EndpointMapping;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { FileMetadataSchema } from '../system/object-storage.zod';\n\n/**\n * Storage Service Protocol\n * \n * Defines the API contract for client-side file operations.\n * Focuses on secure, direct-to-cloud uploads (Presigned URLs)\n * rather than proxying bytes through the API server.\n */\n\n// ==========================================\n// Requests\n// ==========================================\n\nexport const GetPresignedUrlRequestSchema = z.object({\n filename: z.string().describe('Original filename'),\n mimeType: z.string().describe('File MIME type'),\n size: z.number().describe('File size in bytes'),\n scope: z.string().default('user').describe('Target storage scope (e.g. user, private, public)'),\n bucket: z.string().optional().describe('Specific bucket override (admin only)'),\n});\n\nexport const CompleteUploadRequestSchema = z.object({\n fileId: z.string().describe('File ID returned from presigned request'),\n eTag: z.string().optional().describe('S3 ETag verification'),\n});\n\n// ==========================================\n// Responses\n// ==========================================\n\nexport const PresignedUrlResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadUrl: z.string().describe('PUT/POST URL for direct upload'),\n downloadUrl: z.string().optional().describe('Public/Private preview URL'),\n fileId: z.string().describe('Temporary File ID'),\n method: z.enum(['PUT', 'POST']).describe('HTTP Method to use'),\n headers: z.record(z.string(), z.string()).optional().describe('Required headers for upload'),\n expiresIn: z.number().describe('URL expiry in seconds'),\n }),\n});\n\nexport const FileUploadResponseSchema = BaseResponseSchema.extend({\n data: FileMetadataSchema.describe('Uploaded file metadata'),\n});\n\nexport type GetPresignedUrlRequest = z.infer;\nexport type CompleteUploadRequest = z.infer;\nexport type PresignedUrlResponse = z.infer;\nexport type FileUploadResponse = z.infer;\n\n// ==========================================\n// Chunked / Resumable Upload Protocol\n// ==========================================\n\n/**\n * File Type Validation Schema\n * Configures allowed and blocked file types for upload endpoints.\n *\n * @example Allow images only\n * { mode: 'whitelist', mimeTypes: ['image/jpeg', 'image/png', 'image/webp'], maxFileSize: 10485760 }\n */\nexport const FileTypeValidationSchema = z.object({\n mode: z.enum(['whitelist', 'blacklist'])\n .describe('whitelist = only allow listed types, blacklist = block listed types'),\n mimeTypes: z.array(z.string()).min(1)\n .describe('List of MIME types to allow or block (e.g., \"image/jpeg\", \"application/pdf\")'),\n extensions: z.array(z.string()).optional()\n .describe('List of file extensions to allow or block (e.g., \".jpg\", \".pdf\")'),\n maxFileSize: z.number().int().min(1).optional()\n .describe('Maximum file size in bytes'),\n minFileSize: z.number().int().min(0).optional()\n .describe('Minimum file size in bytes (e.g., reject empty files)'),\n});\nexport type FileTypeValidation = z.infer;\n\n/**\n * Initiate Chunked Upload Request\n * Starts a resumable multipart upload session.\n *\n * @example POST /api/v1/storage/upload/chunked\n * { filename: 'large-video.mp4', mimeType: 'video/mp4', totalSize: 1073741824, chunkSize: 5242880 }\n */\nexport const InitiateChunkedUploadRequestSchema = z.object({\n filename: z.string().describe('Original filename'),\n mimeType: z.string().describe('File MIME type'),\n totalSize: z.number().int().min(1).describe('Total file size in bytes'),\n chunkSize: z.number().int().min(5242880).default(5242880)\n .describe('Size of each chunk in bytes (minimum 5MB per S3 spec)'),\n scope: z.string().default('user').describe('Target storage scope'),\n bucket: z.string().optional().describe('Specific bucket override (admin only)'),\n metadata: z.record(z.string(), z.string()).optional().describe('Custom metadata key-value pairs'),\n});\nexport type InitiateChunkedUploadRequest = z.infer;\n\n/**\n * Initiate Chunked Upload Response\n * Returns a resume token and upload session details.\n */\nexport const InitiateChunkedUploadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n resumeToken: z.string().describe('Opaque token for resuming interrupted uploads'),\n fileId: z.string().describe('Assigned file ID'),\n totalChunks: z.number().int().min(1).describe('Expected number of chunks'),\n chunkSize: z.number().int().describe('Chunk size in bytes'),\n expiresAt: z.string().datetime().describe('Upload session expiration timestamp'),\n }),\n});\nexport type InitiateChunkedUploadResponse = z.infer;\n\n/**\n * Upload Chunk Request\n * Uploads a single chunk of a multipart upload.\n *\n * @example PUT /api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex\n */\nexport const UploadChunkRequestSchema = z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n chunkIndex: z.number().int().min(0).describe('Zero-based chunk index'),\n resumeToken: z.string().describe('Resume token from initiate response'),\n});\nexport type UploadChunkRequest = z.infer;\n\n/**\n * Upload Chunk Response\n * Confirms a single chunk upload with ETag for assembly.\n */\nexport const UploadChunkResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n chunkIndex: z.number().int().describe('Chunk index that was uploaded'),\n eTag: z.string().describe('Chunk ETag for multipart completion'),\n bytesReceived: z.number().int().describe('Bytes received for this chunk'),\n }),\n});\nexport type UploadChunkResponse = z.infer;\n\n/**\n * Complete Chunked Upload Request\n * Assembles all uploaded chunks into a final file.\n *\n * @example POST /api/v1/storage/upload/chunked/:uploadId/complete\n */\nexport const CompleteChunkedUploadRequestSchema = z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n parts: z.array(z.object({\n chunkIndex: z.number().int().describe('Chunk index'),\n eTag: z.string().describe('ETag returned from chunk upload'),\n })).min(1).describe('Ordered list of uploaded parts for assembly'),\n});\nexport type CompleteChunkedUploadRequest = z.infer;\n\n/**\n * Complete Chunked Upload Response\n * Confirms that all chunks have been assembled into the final file.\n */\nexport const CompleteChunkedUploadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n fileId: z.string().describe('Final file ID'),\n key: z.string().describe('Storage key/path of the assembled file'),\n size: z.number().int().describe('Total file size in bytes'),\n mimeType: z.string().describe('File MIME type'),\n eTag: z.string().optional().describe('Final ETag of the assembled file'),\n url: z.string().optional().describe('Download URL for the assembled file'),\n }),\n});\nexport type CompleteChunkedUploadResponse = z.infer;\n\n/**\n * Upload Progress Schema\n * Represents the current progress of an active upload session.\n *\n * @example GET /api/v1/storage/upload/chunked/:uploadId/progress\n */\nexport const UploadProgressSchema = BaseResponseSchema.extend({\n data: z.object({\n uploadId: z.string().describe('Multipart upload session ID'),\n fileId: z.string().describe('Assigned file ID'),\n filename: z.string().describe('Original filename'),\n totalSize: z.number().int().describe('Total file size in bytes'),\n uploadedSize: z.number().int().describe('Bytes uploaded so far'),\n totalChunks: z.number().int().describe('Total expected chunks'),\n uploadedChunks: z.number().int().describe('Number of chunks uploaded'),\n percentComplete: z.number().min(0).max(100).describe('Upload progress percentage'),\n status: z.enum(['in_progress', 'completing', 'completed', 'failed', 'expired'])\n .describe('Current upload session status'),\n startedAt: z.string().datetime().describe('Upload session start timestamp'),\n expiresAt: z.string().datetime().describe('Session expiration timestamp'),\n }),\n});\nexport type UploadProgress = z.infer;\n\n// ==========================================\n// Storage API Contract Registry\n// ==========================================\n\n/**\n * Standard Storage API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const StorageApiContracts = {\n getPresignedUrl: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/presigned',\n input: GetPresignedUrlRequestSchema,\n output: PresignedUrlResponseSchema,\n },\n completeUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/complete',\n input: CompleteUploadRequestSchema,\n output: FileUploadResponseSchema,\n },\n initiateChunkedUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/chunked',\n input: InitiateChunkedUploadRequestSchema,\n output: InitiateChunkedUploadResponseSchema,\n },\n uploadChunk: {\n method: 'PUT' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex',\n input: UploadChunkRequestSchema,\n output: UploadChunkResponseSchema,\n },\n completeChunkedUpload: {\n method: 'POST' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/complete',\n input: CompleteChunkedUploadRequestSchema,\n output: CompleteChunkedUploadResponseSchema,\n },\n getUploadProgress: {\n method: 'GET' as const,\n path: '/api/v1/storage/upload/chunked/:uploadId/progress',\n output: UploadProgressSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { ObjectSchema } from '../data/object.zod';\nimport { AppSchema } from '../ui/app.zod';\nimport { MetadataTypeSchema, MetadataQuerySchema, MetadataQueryResultSchema, MetadataValidationResultSchema, MetadataBulkResultSchema, MetadataDependencySchema } from '../kernel/metadata-plugin.zod';\nimport { MetadataOverlaySchema } from '../kernel/metadata-customization.zod';\n\n/**\n * Metadata Service Protocol\n *\n * Defines the standard API contracts for the **@objectstack/metadata** package.\n * This is the single authority for ALL metadata-related services and APIs across\n * the entire platform, including Hono, Next.js, and NestJS adapters.\n *\n * ## Architecture\n * ```\n * ┌──────────────────────────────────────────────────────────────────┐\n * │ @objectstack/metadata — API Contracts │\n * │ │\n * │ CRUD │ Query/Search │ Bulk Ops │ Overlay │ Watch │\n * │ Import/Export│ Validation │ Type Reg │ Deps │ │\n * ├──────────────────────────────────────────────────────────────────┤\n * │ Hono Adapter │ Next.js Adapter │ NestJS Adapter │ CLI │\n * └──────────────────────────────────────────────────────────────────┘\n * ```\n *\n * ## Alignment\n * - **Salesforce**: Metadata API (deploy, retrieve, describe)\n * - **ServiceNow**: System Dictionary + Metadata API\n * - **Kubernetes**: API Server + CRD Registry\n */\n\n// ==========================================\n// 1. Legacy Responses (existing)\n// ==========================================\n\n/**\n * Single Object Definition Response\n * Returns the full JSON schema for an Entity (Fields, Actions, Config).\n */\nexport const ObjectDefinitionResponseSchema = BaseResponseSchema.extend({\n data: ObjectSchema.describe('Full Object Schema'),\n});\n\n/**\n * App Definition Response\n * Returns the navigation, branding, and layout for an App.\n */\nexport const AppDefinitionResponseSchema = BaseResponseSchema.extend({\n data: AppSchema.describe('Full App Configuration'),\n});\n\n/**\n * All Concepts Response\n * Bulk load lightweight definitions for autocomplete/pickers.\n */\nexport const ConceptListResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.object({\n name: z.string(),\n label: z.string(),\n icon: z.string().optional(),\n description: z.string().optional(),\n })).describe('List of available concepts (Objects, Apps, Flows)'),\n});\n\n// ==========================================\n// 2. CRUD Request / Response Schemas\n// ==========================================\n\n/**\n * Register (Create/Update) Metadata Request\n * POST /api/meta/:type\n * PUT /api/meta/:type/:name\n */\nexport const MetadataRegisterRequestSchema = z.object({\n type: MetadataTypeSchema.describe('Metadata type'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Item name (snake_case)'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n namespace: z.string().optional().describe('Optional namespace'),\n});\n\n/**\n * Single Metadata Item Response\n * GET /api/meta/:type/:name\n */\nexport const MetadataItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n definition: z.record(z.string(), z.unknown()).describe('Metadata definition payload'),\n }).describe('Metadata item'),\n});\n\n/**\n * Metadata List Response\n * GET /api/meta/:type\n */\nexport const MetadataListResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.record(z.string(), z.unknown())).describe('Array of metadata definitions'),\n});\n\n/**\n * Metadata Names Response\n * GET /api/meta/:type/names\n */\nexport const MetadataNamesResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.string()).describe('Array of metadata item names'),\n});\n\n/**\n * Metadata Exists Response\n * GET /api/meta/:type/:name/exists\n */\nexport const MetadataExistsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n exists: z.boolean().describe('Whether the item exists'),\n }),\n});\n\n/**\n * Metadata Delete Response\n * DELETE /api/meta/:type/:name\n */\nexport const MetadataDeleteResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Deleted item name'),\n }),\n});\n\n// ==========================================\n// 3. Query / Search\n// ==========================================\n\n/**\n * Metadata Query Request\n * POST /api/meta/query\n */\nexport const MetadataQueryRequestSchema = MetadataQuerySchema.describe(\n 'Metadata query with filtering, sorting, and pagination',\n);\n\n/**\n * Metadata Query Response\n * POST /api/meta/query\n */\nexport const MetadataQueryResponseSchema = BaseResponseSchema.extend({\n data: MetadataQueryResultSchema.describe('Paginated query result'),\n});\n\n// ==========================================\n// 4. Bulk Operations\n// ==========================================\n\n/**\n * Bulk Register Request\n * POST /api/meta/bulk/register\n */\nexport const MetadataBulkRegisterRequestSchema = z.object({\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n data: z.record(z.string(), z.unknown()).describe('Metadata payload'),\n })).min(1).describe('Items to register'),\n continueOnError: z.boolean().default(false).describe('Continue on individual failure'),\n validate: z.boolean().default(true).describe('Validate before registering'),\n});\n\n/**\n * Bulk Unregister Request\n * POST /api/meta/bulk/unregister\n */\nexport const MetadataBulkUnregisterRequestSchema = z.object({\n items: z.array(z.object({\n type: z.string().describe('Metadata type'),\n name: z.string().describe('Item name'),\n })).min(1).describe('Items to unregister'),\n});\n\n/**\n * Bulk Operation Response\n * POST /api/meta/bulk/*\n */\nexport const MetadataBulkResponseSchema = BaseResponseSchema.extend({\n data: MetadataBulkResultSchema.describe('Bulk operation result'),\n});\n\n// ==========================================\n// 5. Overlay / Customization\n// ==========================================\n\n/**\n * Get Overlay Response\n * GET /api/meta/:type/:name/overlay\n */\nexport const MetadataOverlayResponseSchema = BaseResponseSchema.extend({\n data: MetadataOverlaySchema.optional().describe('Overlay definition, undefined if none'),\n});\n\n/**\n * Save Overlay Request\n * PUT /api/meta/:type/:name/overlay\n */\nexport const MetadataOverlaySaveRequestSchema = MetadataOverlaySchema.describe(\n 'Overlay to save',\n);\n\n/**\n * Get Effective (merged) Response\n * GET /api/meta/:type/:name/effective\n */\nexport const MetadataEffectiveResponseSchema = BaseResponseSchema.extend({\n data: z.record(z.string(), z.unknown()).optional()\n .describe('Effective metadata with all overlays applied'),\n});\n\n// ==========================================\n// 6. Import / Export\n// ==========================================\n\n/**\n * Export Metadata Request\n * POST /api/meta/export\n */\nexport const MetadataExportRequestSchema = z.object({\n types: z.array(z.string()).optional().describe('Filter by metadata types'),\n namespaces: z.array(z.string()).optional().describe('Filter by namespaces'),\n format: z.enum(['json', 'yaml']).default('json').describe('Export format'),\n});\n\n/**\n * Export Metadata Response\n * POST /api/meta/export\n */\nexport const MetadataExportResponseSchema = BaseResponseSchema.extend({\n data: z.unknown().describe('Exported metadata bundle'),\n});\n\n/**\n * Import Metadata Request\n * POST /api/meta/import\n */\nexport const MetadataImportRequestSchema = z.object({\n data: z.unknown().describe('Metadata bundle to import'),\n conflictResolution: z.enum(['skip', 'overwrite', 'merge']).default('skip')\n .describe('Conflict resolution strategy'),\n validate: z.boolean().default(true).describe('Validate before import'),\n dryRun: z.boolean().default(false).describe('Dry run (no save)'),\n});\n\n/**\n * Import Metadata Response\n * POST /api/meta/import\n */\nexport const MetadataImportResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n total: z.number().int().min(0),\n imported: z.number().int().min(0),\n skipped: z.number().int().min(0),\n failed: z.number().int().min(0),\n errors: z.array(z.object({\n type: z.string(),\n name: z.string(),\n error: z.string(),\n })).optional(),\n }).describe('Import result'),\n});\n\n// ==========================================\n// 7. Validation\n// ==========================================\n\n/**\n * Validate Metadata Request\n * POST /api/meta/validate\n */\nexport const MetadataValidateRequestSchema = z.object({\n type: z.string().describe('Metadata type to validate against'),\n data: z.unknown().describe('Metadata payload to validate'),\n});\n\n/**\n * Validate Metadata Response\n * POST /api/meta/validate\n */\nexport const MetadataValidateResponseSchema = BaseResponseSchema.extend({\n data: MetadataValidationResultSchema.describe('Validation result'),\n});\n\n// ==========================================\n// 8. Type Registry\n// ==========================================\n\n/**\n * List Registered Types Response\n * GET /api/meta/types\n */\nexport const MetadataTypesResponseSchema = BaseResponseSchema.extend({\n data: z.array(z.string()).describe('Registered metadata type identifiers'),\n});\n\n/**\n * Type Info Response\n * GET /api/meta/types/:type\n */\nexport const MetadataTypeInfoResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n type: z.string().describe('Metadata type identifier'),\n label: z.string().describe('Display label'),\n description: z.string().optional().describe('Description'),\n filePatterns: z.array(z.string()).describe('File glob patterns'),\n supportsOverlay: z.boolean().describe('Overlay support'),\n domain: z.string().describe('Protocol domain'),\n }).optional().describe('Type info'),\n});\n\n// ==========================================\n// 9. Dependency Tracking\n// ==========================================\n\n/**\n * Dependencies Response\n * GET /api/meta/:type/:name/dependencies\n */\nexport const MetadataDependenciesResponseSchema = BaseResponseSchema.extend({\n data: z.array(MetadataDependencySchema).describe('Items this item depends on'),\n});\n\n/**\n * Dependents Response\n * GET /api/meta/:type/:name/dependents\n */\nexport const MetadataDependentsResponseSchema = BaseResponseSchema.extend({\n data: z.array(MetadataDependencySchema).describe('Items that depend on this item'),\n});\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type ObjectDefinitionResponse = z.infer;\nexport type AppDefinitionResponse = z.infer;\nexport type ConceptListResponse = z.infer;\nexport type MetadataRegisterRequest = z.infer;\nexport type MetadataItemResponse = z.infer;\nexport type MetadataListResponse = z.infer;\nexport type MetadataNamesResponse = z.infer;\nexport type MetadataExistsResponse = z.infer;\nexport type MetadataDeleteResponse = z.infer;\nexport type MetadataQueryResponse = z.infer;\nexport type MetadataBulkResponse = z.infer;\nexport type MetadataOverlayResponse = z.infer;\nexport type MetadataEffectiveResponse = z.infer;\nexport type MetadataExportResponse = z.infer;\nexport type MetadataImportResponse = z.infer;\nexport type MetadataValidateResponse = z.infer;\nexport type MetadataTypesResponse = z.infer;\nexport type MetadataTypeInfoResponse = z.infer;\nexport type MetadataDependenciesResponse = z.infer;\nexport type MetadataDependentsResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { CoreServiceName, ServiceCriticalitySchema } from '../system/core-services.zod';\n\n/**\n * # HttpDispatcher Protocol\n * \n * Defines how the ObjectStack HttpDispatcher routes incoming API requests\n * to the correct kernel service based on URL prefix matching.\n * \n * The dispatcher is the central routing component that:\n * 1. Matches incoming request URLs against registered route prefixes\n * 2. Delegates to the corresponding CoreService implementation\n * 3. Returns 503 Service Unavailable when a service is not registered\n * 4. Supports dynamic route registration from plugins via contributes.routes\n * \n * Architecture alignment:\n * - Kubernetes: API server aggregation layer\n * - Eclipse: Extension registry routing\n * - VS Code: Command palette routing\n */\n\n// ============================================================================\n// Route Definition\n// ============================================================================\n\n/**\n * Dispatcher Route Schema\n * Maps a URL prefix to a kernel service.\n * \n * @example\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"authRequired\": true,\n * \"criticality\": \"required\"\n * }\n */\nexport const DispatcherRouteSchema = z.object({\n /**\n * URL path prefix for routing.\n * Incoming requests matching this prefix are routed to the target service.\n * Must start with '/'.\n */\n prefix: z.string().regex(/^\\//).describe('URL path prefix for routing (e.g. /api/v1/data)'),\n \n /**\n * Target core service name.\n * The service that handles requests matching this prefix.\n */\n service: CoreServiceName.describe('Target core service name'),\n \n /**\n * Whether requests to this route require authentication.\n * Discovery endpoint is typically public; most others require auth.\n * @default true\n */\n authRequired: z.boolean().default(true).describe('Whether authentication is required'),\n \n /**\n * Service criticality level.\n * Determines behavior when the service is unavailable:\n * - required: return 500 Internal Server Error\n * - core: return 503 with degraded notice\n * - optional: return 503 Service Unavailable\n * @default 'optional'\n */\n criticality: ServiceCriticalitySchema.default('optional')\n .describe('Service criticality level for unavailability handling'),\n \n /**\n * Required permissions for accessing this route namespace.\n * Applied as a baseline before individual endpoint permission checks.\n */\n permissions: z.array(z.string()).optional()\n .describe('Required permissions for this route namespace'),\n});\n\nexport type DispatcherRoute = z.infer;\nexport type DispatcherRouteInput = z.input;\n\n// ============================================================================\n// Dispatcher Configuration\n// ============================================================================\n\n/**\n * Dispatcher Configuration Schema\n * Complete configuration for the HttpDispatcher routing table.\n * \n * @example\n * {\n * \"routes\": [\n * { \"prefix\": \"/api/v1/discovery\", \"service\": \"metadata\", \"authRequired\": false },\n * { \"prefix\": \"/api/v1/meta\", \"service\": \"metadata\" },\n * { \"prefix\": \"/api/v1/data\", \"service\": \"data\", \"criticality\": \"required\" },\n * { \"prefix\": \"/api/v1/auth\", \"service\": \"auth\", \"criticality\": \"required\" },\n * { \"prefix\": \"/api/v1/ai\", \"service\": \"ai\" }\n * ],\n * \"fallback\": \"404\"\n * }\n */\nexport const DispatcherConfigSchema = z.object({\n /**\n * Registered route mappings.\n * Routes are matched by longest-prefix-first strategy.\n */\n routes: z.array(DispatcherRouteSchema).describe('Route-to-service mappings'),\n \n /**\n * Behavior when no route matches the request.\n * - 404: Return 404 Not Found (default)\n * - proxy: Forward to a configured proxy target\n * - custom: Delegate to a custom handler\n * @default '404'\n */\n fallback: z.enum(['404', 'proxy', 'custom']).default('404')\n .describe('Behavior when no route matches'),\n \n /**\n * Proxy target URL for fallback: 'proxy' mode.\n */\n proxyTarget: z.string().url().optional()\n .describe('Proxy target URL when fallback is \"proxy\"'),\n});\n\nexport type DispatcherConfig = z.infer;\nexport type DispatcherConfigInput = z.input;\n\n// ============================================================================\n// Default Route Table\n// ============================================================================\n\n/**\n * Default route table for the ObjectStack HttpDispatcher.\n * Maps all Protocol namespaces to their corresponding services.\n * \n * This is the recommended baseline configuration. Plugins can extend\n * this table by declaring routes in their manifest's contributes.routes.\n */\nexport const DEFAULT_DISPATCHER_ROUTES: DispatcherRouteInput[] = [\n // Discovery (public)\n { prefix: '/api/v1/discovery', service: 'metadata', authRequired: false, criticality: 'required' },\n \n // Health (public)\n { prefix: '/api/v1/health', service: 'metadata', authRequired: false, criticality: 'required' },\n \n // Required Services\n { prefix: '/api/v1/meta', service: 'metadata', criticality: 'required' },\n { prefix: '/api/v1/data', service: 'data', criticality: 'required' },\n { prefix: '/api/v1/auth', service: 'auth', criticality: 'required' },\n \n // Optional Services (plugin-provided)\n { prefix: '/api/v1/packages', service: 'metadata' },\n { prefix: '/api/v1/ui', service: 'ui' }, // @deprecated — use /api/v1/meta/view and /api/v1/meta/dashboard instead\n { prefix: '/api/v1/workflow', service: 'workflow' },\n { prefix: '/api/v1/analytics', service: 'analytics' },\n { prefix: '/api/v1/automation', service: 'automation' },\n { prefix: '/api/v1/storage', service: 'file-storage' },\n { prefix: '/api/v1/feed', service: 'data' },\n { prefix: '/api/v1/i18n', service: 'i18n' },\n { prefix: '/api/v1/notifications', service: 'notification' },\n { prefix: '/api/v1/realtime', service: 'realtime' },\n { prefix: '/api/v1/ai', service: 'ai' },\n];\n\n// ============================================================================\n// Dispatcher Error Codes\n// ============================================================================\n\n/**\n * Semantic HTTP error codes used by the Dispatcher.\n *\n * The dispatcher MUST distinguish between these four failure modes so that\n * clients (and developers) can understand *why* an API call failed:\n *\n * - `404` – Route Not Found: no route is registered for this path.\n * - `405` – Method Not Allowed: route exists but the HTTP method is not supported.\n * - `501` – Not Implemented: route is declared but the handler is a stub / not yet coded.\n * - `503` – Service Unavailable: service exists but is temporarily down or not loaded.\n *\n * Note: These are string representations of HTTP status codes for use in enum\n * matching. The `DispatcherErrorResponseSchema.error.code` field carries the\n * numeric HTTP status code for direct use in HTTP responses.\n */\nexport const DispatcherErrorCode = z.enum(['404', '405', '501', '503']).describe(\n '404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable'\n);\n\nexport type DispatcherErrorCode = z.infer;\n\n/**\n * Dispatcher Error Response Schema\n *\n * Standardised error envelope returned by the dispatcher when a request cannot\n * be fulfilled. Adapters MUST use this shape (or a superset) for all non-2xx\n * responses so that clients can programmatically distinguish failure modes.\n */\nexport const DispatcherErrorResponseSchema = z.object({\n /** Always `false` for error responses */\n success: z.literal(false),\n error: z.object({\n /** HTTP status code */\n code: z.number().int().describe('HTTP status code (404, 405, 501, 503, …)'),\n /** Human-readable error message */\n message: z.string().describe('Human-readable error message'),\n /**\n * Machine-readable error type for programmatic branching.\n */\n type: z.enum([\n 'ROUTE_NOT_FOUND',\n 'METHOD_NOT_ALLOWED',\n 'NOT_IMPLEMENTED',\n 'SERVICE_UNAVAILABLE',\n ]).optional().describe('Machine-readable error type'),\n /** Route that was requested */\n route: z.string().optional().describe('Requested route path'),\n /** Service that the route maps to (if known) */\n service: z.string().optional().describe('Target service name, if resolvable'),\n /** Guidance for the developer */\n hint: z.string().optional().describe('Actionable hint for the developer (e.g., \"Install plugin-workflow\")'),\n }),\n});\n\nexport type DispatcherErrorResponse = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { HttpMethod } from '../shared/http.zod';\nimport { MiddlewareConfigSchema } from '../system/http-server.zod';\n\n/**\n * REST API Plugin Protocol\n * \n * Defines the schema for REST API plugins that register Discovery, Metadata,\n * Data CRUD, Batch, and Permission routes with the HTTP Dispatcher.\n * \n * This plugin type implements Phase 2 of the API Protocol implementation plan,\n * providing standardized REST endpoints with:\n * - Request validation middleware using Zod schemas\n * - Response envelope wrapping with BaseResponseSchema\n * - Error handling using ApiErrorSchema\n * - OpenAPI documentation auto-generation\n * \n * Features:\n * - Route registration for core API endpoints\n * - Automatic schema-based validation\n * - Standardized request/response envelopes\n * - OpenAPI/Swagger documentation generation\n * \n * Architecture Alignment:\n * - Salesforce: REST API with metadata and data CRUD\n * - Microsoft Dynamics: Web API with entity operations\n * - Strapi: Auto-generated REST endpoints from schemas\n * \n * @example Plugin Manifest\n * ```typescript\n * {\n * \"name\": \"rest_api\",\n * \"version\": \"1.0.0\",\n * \"type\": \"server\",\n * \"contributes\": {\n * \"routes\": [\n * {\n * \"prefix\": \"/api/v1/discovery\",\n * \"service\": \"metadata\",\n * \"methods\": [\"getDiscovery\"],\n * \"middleware\": [\n * { \"name\": \"response_envelope\", \"type\": \"transformation\", \"enabled\": true }\n * ]\n * },\n * {\n * \"prefix\": \"/api/v1/meta\",\n * \"service\": \"metadata\",\n * \"methods\": [\"getMetaTypes\", \"getMetaItems\", \"getMetaItem\", \"saveMetaItem\"],\n * \"middleware\": [\n * { \"name\": \"auth\", \"type\": \"authentication\", \"enabled\": true },\n * { \"name\": \"request_validation\", \"type\": \"validation\", \"enabled\": true }\n * ]\n * },\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"methods\": [\"findData\", \"getData\", \"createData\", \"updateData\", \"deleteData\"]\n * }\n * ]\n * }\n * }\n * ```\n */\n\n// ==========================================\n// REST API Route Categories\n// ==========================================\n\n/**\n * REST API Route Category Enum\n * Categorizes REST API routes by their primary function\n */\nexport const RestApiRouteCategory = z.enum([\n 'discovery', // API discovery and capabilities\n 'metadata', // Metadata operations (objects, fields, views)\n 'data', // Data CRUD operations\n 'batch', // Batch/bulk operations\n 'permission', // Permission/authorization checks\n 'analytics', // Analytics and reporting\n 'automation', // Automation triggers and flows\n 'workflow', // Workflow state management\n 'ui', // UI metadata (views, layouts)\n 'realtime', // Realtime/WebSocket\n 'notification', // Notification management\n 'ai', // AI operations (NLQ, chat)\n 'i18n', // Internationalization\n]);\n\nexport type RestApiRouteCategory = z.infer;\n\n// ==========================================\n// Route Registration Schema\n// ==========================================\n\n/**\n * Handler Implementation Status\n * Shared enum for tracking whether an endpoint has a real handler.\n * Used by both `RestApiEndpointSchema` and `RouteCoverageEntrySchema`.\n *\n * - `implemented` – A real handler is coded and registered.\n * - `stub` – A placeholder handler exists that returns 501 Not Implemented.\n * - `planned` – Declared in the protocol spec but not yet implemented.\n */\nexport const HandlerStatusSchema = z.enum(['implemented', 'stub', 'planned']);\nexport type HandlerStatus = z.infer;\n\n/**\n * REST API Endpoint Schema\n * Defines a single REST API endpoint with its metadata\n * \n * @example Discovery Endpoint\n * {\n * \"method\": \"GET\",\n * \"path\": \"/api/v1/discovery\",\n * \"handler\": \"getDiscovery\",\n * \"category\": \"discovery\",\n * \"public\": true,\n * \"description\": \"Get API discovery information\"\n * }\n */\nexport const RestApiEndpointSchema = z.object({\n /**\n * HTTP method\n */\n method: HttpMethod.describe('HTTP method for this endpoint'),\n \n /**\n * URL path pattern (supports parameters like :id)\n */\n path: z.string().describe('URL path pattern (e.g., /api/v1/data/:object/:id)'),\n \n /**\n * Handler reference (protocol method name)\n */\n handler: z.string().describe('Protocol method name or handler identifier'),\n \n /**\n * Route category\n */\n category: RestApiRouteCategory.describe('Route category'),\n \n /**\n * Whether endpoint is publicly accessible (no auth required)\n */\n public: z.boolean().default(false).describe('Is publicly accessible without authentication'),\n \n /**\n * Required permissions\n */\n permissions: z.array(z.string()).optional().describe('Required permissions (e.g., [\"data.read\", \"object.account.read\"])'),\n \n /**\n * OpenAPI documentation metadata\n */\n summary: z.string().optional().describe('Short description for OpenAPI'),\n description: z.string().optional().describe('Detailed description for OpenAPI'),\n tags: z.array(z.string()).optional().describe('OpenAPI tags for grouping'),\n \n /**\n * Request/Response schema references\n */\n requestSchema: z.string().optional().describe('Request schema name (for validation)'),\n responseSchema: z.string().optional().describe('Response schema name (for documentation)'),\n \n /**\n * Performance and reliability settings\n */\n timeout: z.number().int().optional().describe('Request timeout in milliseconds'),\n rateLimit: z.string().optional().describe('Rate limit policy name'),\n cacheable: z.boolean().default(false).describe('Whether response can be cached'),\n cacheTtl: z.number().int().optional().describe('Cache TTL in seconds'),\n\n /**\n * Handler implementation status.\n * Tracks whether this endpoint has a real handler or is only declared.\n *\n * - `implemented` – A real handler is coded and registered.\n * - `stub` – A placeholder handler exists that returns 501 Not Implemented.\n * - `planned` – Declared in the protocol spec but not yet implemented.\n * @default 'implemented'\n */\n handlerStatus: HandlerStatusSchema.optional()\n .describe('Handler implementation status: implemented (default if omitted), stub, or planned'),\n});\n\nexport type RestApiEndpoint = z.infer;\n\n/**\n * REST API Route Registration Schema\n * Registers a group of related endpoints under a common prefix\n * \n * @example Data CRUD Routes\n * {\n * \"prefix\": \"/api/v1/data\",\n * \"service\": \"data\",\n * \"category\": \"data\",\n * \"endpoints\": [\n * { \"method\": \"GET\", \"path\": \"/:object\", \"handler\": \"findData\" },\n * { \"method\": \"GET\", \"path\": \"/:object/:id\", \"handler\": \"getData\" },\n * { \"method\": \"POST\", \"path\": \"/:object\", \"handler\": \"createData\" },\n * { \"method\": \"PATCH\", \"path\": \"/:object/:id\", \"handler\": \"updateData\" },\n * { \"method\": \"DELETE\", \"path\": \"/:object/:id\", \"handler\": \"deleteData\" }\n * ],\n * \"middleware\": [\n * { \"name\": \"auth\", \"type\": \"authentication\", \"enabled\": true },\n * { \"name\": \"validation\", \"type\": \"validation\", \"enabled\": true },\n * { \"name\": \"response_envelope\", \"type\": \"transformation\", \"enabled\": true }\n * ]\n * }\n */\nexport const RestApiRouteRegistrationSchema = z.object({\n /**\n * URL prefix for this route group (e.g., /api/v1/data)\n */\n prefix: z.string().regex(/^\\//).describe('URL path prefix for this route group'),\n \n /**\n * Service name that handles these routes\n */\n service: z.string().describe('Core service name (metadata, data, auth, etc.)'),\n \n /**\n * Route category\n */\n category: RestApiRouteCategory.describe('Primary category for this route group'),\n \n /**\n * Protocol methods implemented\n */\n methods: z.array(z.string()).optional().describe('Protocol method names implemented'),\n \n /**\n * Detailed endpoint definitions\n */\n endpoints: z.array(RestApiEndpointSchema).optional().describe('Endpoint definitions'),\n \n /**\n * Middleware applied to all routes in this group\n */\n middleware: z.array(MiddlewareConfigSchema).optional().describe('Middleware stack for this route group'),\n \n /**\n * Whether authentication is required for all routes\n */\n authRequired: z.boolean().default(true).describe('Whether authentication is required by default'),\n \n /**\n * OpenAPI documentation\n */\n documentation: z.object({\n title: z.string().optional().describe('Route group title'),\n description: z.string().optional().describe('Route group description'),\n tags: z.array(z.string()).optional().describe('OpenAPI tags'),\n }).optional().describe('Documentation metadata for this route group'),\n});\n\nexport type RestApiRouteRegistration = z.infer;\n\n// ==========================================\n// Request Validation Configuration\n// ==========================================\n\n/**\n * Request Validation Mode Enum\n * Defines how validation errors are handled\n */\nexport const ValidationMode = z.enum([\n 'strict', // Reject requests with validation errors (400 Bad Request)\n 'permissive', // Log validation errors but allow request to proceed\n 'strip', // Remove invalid fields and continue with valid data\n]);\n\nexport type ValidationMode = z.infer;\n\n/**\n * Request Validation Configuration Schema\n * Configures Zod-based request validation middleware\n * \n * @example\n * {\n * \"enabled\": true,\n * \"mode\": \"strict\",\n * \"validateBody\": true,\n * \"validateQuery\": true,\n * \"validateParams\": true,\n * \"includeFieldErrors\": true\n * }\n */\nexport const RequestValidationConfigSchema = z.object({\n /**\n * Enable request validation\n */\n enabled: z.boolean().default(true).describe('Enable automatic request validation'),\n \n /**\n * Validation mode\n */\n mode: ValidationMode.default('strict').describe('How to handle validation errors'),\n \n /**\n * Validate request body\n */\n validateBody: z.boolean().default(true).describe('Validate request body against schema'),\n \n /**\n * Validate query parameters\n */\n validateQuery: z.boolean().default(true).describe('Validate query string parameters'),\n \n /**\n * Validate URL parameters\n */\n validateParams: z.boolean().default(true).describe('Validate URL path parameters'),\n \n /**\n * Validate request headers\n */\n validateHeaders: z.boolean().default(false).describe('Validate request headers'),\n \n /**\n * Include detailed field errors in response\n */\n includeFieldErrors: z.boolean().default(true).describe('Include field-level error details in response'),\n \n /**\n * Custom error message prefix\n */\n errorPrefix: z.string().optional().describe('Custom prefix for validation error messages'),\n \n /**\n * Schema registry reference\n */\n schemaRegistry: z.string().optional().describe('Schema registry name to use for validation'),\n});\n\nexport type RequestValidationConfig = z.infer;\nexport type RequestValidationConfigInput = z.input;\n\n// ==========================================\n// Response Envelope Configuration\n// ==========================================\n\n/**\n * Response Envelope Configuration Schema\n * Configures automatic response wrapping with BaseResponseSchema\n * \n * @example\n * {\n * \"enabled\": true,\n * \"includeMetadata\": true,\n * \"includeTimestamp\": true,\n * \"includeRequestId\": true,\n * \"includeDuration\": true\n * }\n */\nexport const ResponseEnvelopeConfigSchema = z.object({\n /**\n * Enable response envelope wrapping\n */\n enabled: z.boolean().default(true).describe('Enable automatic response envelope wrapping'),\n \n /**\n * Include metadata object\n */\n includeMetadata: z.boolean().default(true).describe('Include meta object in responses'),\n \n /**\n * Include timestamp in metadata\n */\n includeTimestamp: z.boolean().default(true).describe('Include timestamp in response metadata'),\n \n /**\n * Include request ID in metadata\n */\n includeRequestId: z.boolean().default(true).describe('Include requestId in response metadata'),\n \n /**\n * Include request duration in metadata\n */\n includeDuration: z.boolean().default(false).describe('Include request duration in ms'),\n \n /**\n * Include trace ID for distributed tracing\n */\n includeTraceId: z.boolean().default(false).describe('Include distributed traceId'),\n \n /**\n * Custom metadata fields\n */\n customMetadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata fields to include'),\n \n /**\n * Whether to wrap already-wrapped responses\n */\n skipIfWrapped: z.boolean().default(true).describe('Skip wrapping if response already has success field'),\n});\n\nexport type ResponseEnvelopeConfig = z.infer;\nexport type ResponseEnvelopeConfigInput = z.input;\n\n// ==========================================\n// Error Handling Configuration\n// ==========================================\n\n/**\n * Error Handling Configuration Schema\n * Configures error handling and ApiErrorSchema formatting\n * \n * @example\n * {\n * \"enabled\": true,\n * \"includeStackTrace\": false,\n * \"logErrors\": true,\n * \"exposeInternalErrors\": false,\n * \"customErrorMessages\": {\n * \"validation_error\": \"The request data is invalid. Please check your input.\"\n * }\n * }\n */\nexport const ErrorHandlingConfigSchema = z.object({\n /**\n * Enable standardized error handling\n */\n enabled: z.boolean().default(true).describe('Enable standardized error handling'),\n \n /**\n * Include stack traces in error responses (dev only)\n */\n includeStackTrace: z.boolean().default(false).describe('Include stack traces in error responses'),\n \n /**\n * Log errors to logger\n */\n logErrors: z.boolean().default(true).describe('Log errors to system logger'),\n \n /**\n * Expose internal error details\n */\n exposeInternalErrors: z.boolean().default(false).describe('Expose internal error details in responses'),\n \n /**\n * Include request ID in errors\n */\n includeRequestId: z.boolean().default(true).describe('Include requestId in error responses'),\n \n /**\n * Include timestamp in errors\n */\n includeTimestamp: z.boolean().default(true).describe('Include timestamp in error responses'),\n \n /**\n * Include error documentation URLs\n */\n includeDocumentation: z.boolean().default(true).describe('Include documentation URLs for errors'),\n \n /**\n * Documentation base URL\n */\n documentationBaseUrl: z.string().url().optional().describe('Base URL for error documentation'),\n \n /**\n * Custom error messages by code\n */\n customErrorMessages: z.record(z.string(), z.string()).optional()\n .describe('Custom error messages by error code'),\n \n /**\n * Sensitive fields to redact from error details\n */\n redactFields: z.array(z.string()).optional().describe('Field names to redact from error details'),\n});\n\nexport type ErrorHandlingConfig = z.infer;\nexport type ErrorHandlingConfigInput = z.input;\n\n// ==========================================\n// OpenAPI Documentation Configuration\n// ==========================================\n\n/**\n * OpenAPI Generation Configuration Schema\n * Configures automatic OpenAPI documentation generation\n * \n * @example\n * {\n * \"enabled\": true,\n * \"version\": \"3.0.0\",\n * \"title\": \"ObjectStack API\",\n * \"description\": \"ObjectStack REST API\",\n * \"outputPath\": \"/api/docs/openapi.json\",\n * \"uiPath\": \"/api/docs\",\n * \"includeInternal\": false,\n * \"generateSchemas\": true\n * }\n */\nexport const OpenApiGenerationConfigSchema = z.object({\n /**\n * Enable OpenAPI generation\n */\n enabled: z.boolean().default(true).describe('Enable automatic OpenAPI documentation generation'),\n \n /**\n * OpenAPI specification version\n */\n version: z.enum(['3.0.0', '3.0.1', '3.0.2', '3.0.3', '3.1.0']).default('3.0.3')\n .describe('OpenAPI specification version'),\n \n /**\n * API title\n */\n title: z.string().default('ObjectStack API').describe('API title'),\n \n /**\n * API description\n */\n description: z.string().optional().describe('API description'),\n \n /**\n * API version\n */\n apiVersion: z.string().default('1.0.0').describe('API version'),\n \n /**\n * Output path for OpenAPI spec\n */\n outputPath: z.string().default('/api/docs/openapi.json').describe('URL path to serve OpenAPI JSON'),\n \n /**\n * UI path for Swagger/Redoc\n */\n uiPath: z.string().default('/api/docs').describe('URL path to serve documentation UI'),\n \n /**\n * UI framework to use\n */\n uiFramework: z.enum(['swagger-ui', 'redoc', 'rapidoc', 'elements']).default('swagger-ui')\n .describe('Documentation UI framework'),\n \n /**\n * Include internal/admin endpoints\n */\n includeInternal: z.boolean().default(false).describe('Include internal endpoints in documentation'),\n \n /**\n * Generate JSON schemas from Zod\n */\n generateSchemas: z.boolean().default(true).describe('Auto-generate schemas from Zod definitions'),\n \n /**\n * Include examples in documentation\n */\n includeExamples: z.boolean().default(true).describe('Include request/response examples'),\n \n /**\n * Server URLs\n */\n servers: z.array(z.object({\n url: z.string().describe('Server URL'),\n description: z.string().optional().describe('Server description'),\n })).optional().describe('Server URLs for API'),\n \n /**\n * Contact information\n */\n contact: z.object({\n name: z.string().optional(),\n url: z.string().url().optional(),\n email: z.string().email().optional(),\n }).optional().describe('API contact information'),\n \n /**\n * License information\n */\n license: z.object({\n name: z.string().describe('License name'),\n url: z.string().url().optional().describe('License URL'),\n }).optional().describe('API license information'),\n \n /**\n * Security schemes\n */\n securitySchemes: z.record(z.string(), z.object({\n type: z.enum(['apiKey', 'http', 'oauth2', 'openIdConnect']),\n scheme: z.string().optional(),\n bearerFormat: z.string().optional(),\n })).optional().describe('Security scheme definitions'),\n});\n\nexport type OpenApiGenerationConfig = z.infer;\nexport type OpenApiGenerationConfigInput = z.input;\n\n// ==========================================\n// REST API Plugin Configuration\n// ==========================================\n\n/**\n * REST API Plugin Configuration Schema\n * Complete configuration for REST API plugin\n * \n * @example\n * {\n * \"enabled\": true,\n * \"basePath\": \"/api\",\n * \"version\": \"v1\",\n * \"routes\": [...],\n * \"validation\": { \"enabled\": true, \"mode\": \"strict\" },\n * \"responseEnvelope\": { \"enabled\": true, \"includeMetadata\": true },\n * \"errorHandling\": { \"enabled\": true, \"includeStackTrace\": false },\n * \"openApi\": { \"enabled\": true, \"title\": \"ObjectStack API\" }\n * }\n */\nexport const RestApiPluginConfigSchema = z.object({\n /**\n * Enable REST API plugin\n */\n enabled: z.boolean().default(true).describe('Enable REST API plugin'),\n \n /**\n * API base path\n */\n basePath: z.string().default('/api').describe('Base path for all API routes'),\n \n /**\n * API version\n */\n version: z.string().default('v1').describe('API version identifier'),\n \n /**\n * Route registrations\n */\n routes: z.array(RestApiRouteRegistrationSchema).describe('Route registrations'),\n \n /**\n * Request validation configuration\n */\n validation: RequestValidationConfigSchema.optional().describe('Request validation configuration'),\n \n /**\n * Response envelope configuration\n */\n responseEnvelope: ResponseEnvelopeConfigSchema.optional().describe('Response envelope configuration'),\n \n /**\n * Error handling configuration\n */\n errorHandling: ErrorHandlingConfigSchema.optional().describe('Error handling configuration'),\n \n /**\n * OpenAPI documentation configuration\n */\n openApi: OpenApiGenerationConfigSchema.optional().describe('OpenAPI documentation configuration'),\n \n /**\n * Global middleware applied to all routes\n */\n globalMiddleware: z.array(MiddlewareConfigSchema).optional().describe('Global middleware stack'),\n \n /**\n * CORS configuration\n */\n cors: z.object({\n enabled: z.boolean().default(true),\n origins: z.array(z.string()).optional(),\n methods: z.array(HttpMethod).optional(),\n credentials: z.boolean().default(true),\n }).optional().describe('CORS configuration'),\n \n /**\n * Performance settings\n */\n performance: z.object({\n enableCompression: z.boolean().default(true).describe('Enable response compression'),\n enableETag: z.boolean().default(true).describe('Enable ETag generation'),\n enableCaching: z.boolean().default(true).describe('Enable HTTP caching'),\n defaultCacheTtl: z.number().int().default(300).describe('Default cache TTL in seconds'),\n }).optional().describe('Performance optimization settings'),\n});\n\nexport type RestApiPluginConfig = z.infer;\nexport type RestApiPluginConfigInput = z.input;\n\n// ==========================================\n// Default Route Registrations\n// ==========================================\n\n/**\n * Default Discovery Routes\n * Standard routes for API discovery endpoint\n */\nexport const DEFAULT_DISCOVERY_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/discovery',\n service: 'metadata',\n category: 'discovery',\n methods: ['getDiscovery'],\n authRequired: false,\n endpoints: [{\n method: 'GET',\n path: '',\n handler: 'getDiscovery',\n category: 'discovery',\n public: true,\n summary: 'Get API discovery information',\n description: 'Returns API version, capabilities, and available routes',\n tags: ['Discovery'],\n responseSchema: 'GetDiscoveryResponseSchema',\n cacheable: true,\n cacheTtl: 3600, // Cache for 1 hour as discovery info rarely changes\n }],\n middleware: [\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n/**\n * Default Metadata Routes\n * Standard routes for metadata operations\n * \n * Note: getMetaItemCached is not a separate endpoint - it's handled by the getMetaItem\n * endpoint with HTTP cache headers (ETag, If-None-Match, etc.) for conditional requests.\n */\nexport const DEFAULT_METADATA_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/meta',\n service: 'metadata',\n category: 'metadata',\n methods: ['getMetaTypes', 'getMetaItems', 'getMetaItem', 'saveMetaItem'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '',\n handler: 'getMetaTypes',\n category: 'metadata',\n public: false,\n summary: 'List all metadata types',\n description: 'Returns available metadata types (object, field, view, etc.)',\n tags: ['Metadata'],\n responseSchema: 'GetMetaTypesResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:type',\n handler: 'getMetaItems',\n category: 'metadata',\n public: false,\n summary: 'List metadata items of a type',\n description: 'Returns all items of the specified metadata type',\n tags: ['Metadata'],\n responseSchema: 'GetMetaItemsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:type/:name',\n handler: 'getMetaItem',\n category: 'metadata',\n public: false,\n summary: 'Get specific metadata item',\n description: 'Returns a specific metadata item by type and name',\n tags: ['Metadata'],\n requestSchema: 'GetMetaItemRequestSchema',\n responseSchema: 'GetMetaItemResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'PUT',\n path: '/:type/:name',\n handler: 'saveMetaItem',\n category: 'metadata',\n public: false,\n summary: 'Create or update metadata item',\n description: 'Creates or updates a metadata item',\n tags: ['Metadata'],\n requestSchema: 'SaveMetaItemRequestSchema',\n responseSchema: 'SaveMetaItemResponseSchema',\n permissions: ['metadata.write'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n/**\n * Default Data CRUD Routes\n * Standard routes for data operations\n */\nexport const DEFAULT_DATA_CRUD_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/data',\n service: 'data',\n category: 'data',\n methods: ['findData', 'getData', 'createData', 'updateData', 'deleteData'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/:object',\n handler: 'findData',\n category: 'data',\n public: false,\n summary: 'Query records',\n description: 'Query records with filtering, sorting, and pagination',\n tags: ['Data'],\n requestSchema: 'FindDataRequestSchema',\n responseSchema: 'ListRecordResponseSchema',\n permissions: ['data.read'],\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/:object/:id',\n handler: 'getData',\n category: 'data',\n public: false,\n summary: 'Get record by ID',\n description: 'Retrieve a single record by its ID',\n tags: ['Data'],\n requestSchema: 'IdRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.read'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object',\n handler: 'createData',\n category: 'data',\n public: false,\n summary: 'Create record',\n description: 'Create a new record',\n tags: ['Data'],\n requestSchema: 'CreateRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.create'],\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/:object/:id',\n handler: 'updateData',\n category: 'data',\n public: false,\n summary: 'Update record',\n description: 'Update an existing record',\n tags: ['Data'],\n requestSchema: 'UpdateRequestSchema',\n responseSchema: 'SingleRecordResponseSchema',\n permissions: ['data.update'],\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/:object/:id',\n handler: 'deleteData',\n category: 'data',\n public: false,\n summary: 'Delete record',\n description: 'Delete a record by ID',\n tags: ['Data'],\n requestSchema: 'IdRequestSchema',\n responseSchema: 'DeleteResponseSchema',\n permissions: ['data.delete'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n/**\n * Default Batch Routes\n * Standard routes for batch operations\n */\nexport const DEFAULT_BATCH_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/data/:object',\n service: 'data',\n category: 'batch',\n methods: ['batchData', 'createManyData', 'updateManyData', 'deleteManyData'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/batch',\n handler: 'batchData',\n category: 'batch',\n public: false,\n summary: 'Batch operation',\n description: 'Execute a batch operation (create, update, upsert, delete)',\n tags: ['Batch'],\n requestSchema: 'BatchUpdateRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.batch'],\n timeout: 60000, // 60 seconds for batch operations\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/createMany',\n handler: 'createManyData',\n category: 'batch',\n public: false,\n summary: 'Batch create',\n description: 'Create multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'CreateManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.create', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/updateMany',\n handler: 'updateManyData',\n category: 'batch',\n public: false,\n summary: 'Batch update',\n description: 'Update multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'UpdateManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.update', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/deleteMany',\n handler: 'deleteManyData',\n category: 'batch',\n public: false,\n summary: 'Batch delete',\n description: 'Delete multiple records in a single operation',\n tags: ['Batch'],\n requestSchema: 'DeleteManyRequestSchema',\n responseSchema: 'BatchUpdateResponseSchema',\n permissions: ['data.delete', 'data.batch'],\n timeout: 60000,\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n/**\n * Default Permission Routes\n * Standard routes for permission checking\n */\nexport const DEFAULT_PERMISSION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/auth',\n service: 'auth',\n category: 'permission',\n methods: ['checkPermission', 'getObjectPermissions', 'getEffectivePermissions'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/check',\n handler: 'checkPermission',\n category: 'permission',\n public: false,\n summary: 'Check permission',\n description: 'Check if current user has a specific permission',\n tags: ['Permission'],\n requestSchema: 'CheckPermissionRequestSchema',\n responseSchema: 'CheckPermissionResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/permissions/:object',\n handler: 'getObjectPermissions',\n category: 'permission',\n public: false,\n summary: 'Get object permissions',\n description: 'Get all permissions for a specific object',\n tags: ['Permission'],\n responseSchema: 'ObjectPermissionsResponseSchema',\n cacheable: true,\n cacheTtl: 300,\n },\n {\n method: 'GET',\n path: '/permissions/effective',\n handler: 'getEffectivePermissions',\n category: 'permission',\n public: false,\n summary: 'Get effective permissions',\n description: 'Get all effective permissions for current user',\n tags: ['Permission'],\n responseSchema: 'EffectivePermissionsResponseSchema',\n cacheable: true,\n cacheTtl: 300,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// View Management Routes\n// ==========================================\n\n/**\n * Default View Management Routes\n * Standard routes for UI view CRUD operations\n */\nexport const DEFAULT_VIEW_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/ui',\n service: 'ui',\n category: 'ui',\n methods: ['listViews', 'getView', 'createView', 'updateView', 'deleteView'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/views/:object',\n handler: 'listViews',\n category: 'ui',\n public: false,\n summary: 'List views for an object',\n description: 'Returns all views (list, form) for the specified object',\n tags: ['Views', 'UI'],\n responseSchema: 'ListViewsResponseSchema',\n cacheable: true,\n cacheTtl: 1800,\n },\n {\n method: 'GET',\n path: '/views/:object/:viewId',\n handler: 'getView',\n category: 'ui',\n public: false,\n summary: 'Get a specific view',\n description: 'Returns a specific view definition by object and view ID',\n tags: ['Views', 'UI'],\n responseSchema: 'GetViewResponseSchema',\n cacheable: true,\n cacheTtl: 1800,\n },\n {\n method: 'POST',\n path: '/views/:object',\n handler: 'createView',\n category: 'ui',\n public: false,\n summary: 'Create a new view',\n description: 'Creates a new view definition for the specified object',\n tags: ['Views', 'UI'],\n requestSchema: 'CreateViewRequestSchema',\n responseSchema: 'CreateViewResponseSchema',\n permissions: ['ui.view.create'],\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/views/:object/:viewId',\n handler: 'updateView',\n category: 'ui',\n public: false,\n summary: 'Update a view',\n description: 'Updates an existing view definition',\n tags: ['Views', 'UI'],\n requestSchema: 'UpdateViewRequestSchema',\n responseSchema: 'UpdateViewResponseSchema',\n permissions: ['ui.view.update'],\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/views/:object/:viewId',\n handler: 'deleteView',\n category: 'ui',\n public: false,\n summary: 'Delete a view',\n description: 'Deletes a view definition',\n tags: ['Views', 'UI'],\n responseSchema: 'DeleteViewResponseSchema',\n permissions: ['ui.view.delete'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Workflow Routes\n// ==========================================\n\n/**\n * Default Workflow Routes\n * Standard routes for workflow state management and transitions\n */\nexport const DEFAULT_WORKFLOW_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/workflow',\n service: 'workflow',\n category: 'workflow',\n methods: ['getWorkflowConfig', 'getWorkflowState', 'workflowTransition', 'workflowApprove', 'workflowReject'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/:object/config',\n handler: 'getWorkflowConfig',\n category: 'workflow',\n public: false,\n summary: 'Get workflow configuration',\n description: 'Returns workflow rules and state machine configuration for an object',\n tags: ['Workflow'],\n responseSchema: 'GetWorkflowConfigResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/:object/:recordId/state',\n handler: 'getWorkflowState',\n category: 'workflow',\n public: false,\n summary: 'Get workflow state',\n description: 'Returns current workflow state and available transitions for a record',\n tags: ['Workflow'],\n responseSchema: 'GetWorkflowStateResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/transition',\n handler: 'workflowTransition',\n category: 'workflow',\n public: false,\n summary: 'Execute workflow transition',\n description: 'Transitions a record to a new workflow state',\n tags: ['Workflow'],\n requestSchema: 'WorkflowTransitionRequestSchema',\n responseSchema: 'WorkflowTransitionResponseSchema',\n permissions: ['workflow.transition'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/approve',\n handler: 'workflowApprove',\n category: 'workflow',\n public: false,\n summary: 'Approve workflow step',\n description: 'Approves a pending workflow approval step',\n tags: ['Workflow'],\n requestSchema: 'WorkflowApproveRequestSchema',\n responseSchema: 'WorkflowApproveResponseSchema',\n permissions: ['workflow.approve'],\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/:object/:recordId/reject',\n handler: 'workflowReject',\n category: 'workflow',\n public: false,\n summary: 'Reject workflow step',\n description: 'Rejects a pending workflow approval step',\n tags: ['Workflow'],\n requestSchema: 'WorkflowRejectRequestSchema',\n responseSchema: 'WorkflowRejectResponseSchema',\n permissions: ['workflow.reject'],\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Realtime Routes\n// ==========================================\n\n/**\n * Default Realtime Routes\n * Standard routes for realtime connection management and subscriptions\n */\nexport const DEFAULT_REALTIME_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/realtime',\n service: 'realtime',\n category: 'realtime',\n methods: ['realtimeConnect', 'realtimeDisconnect', 'realtimeSubscribe', 'realtimeUnsubscribe', 'setPresence', 'getPresence'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/connect',\n handler: 'realtimeConnect',\n category: 'realtime',\n public: false,\n summary: 'Establish realtime connection',\n description: 'Negotiates a realtime connection (WebSocket/SSE) and returns connection details',\n tags: ['Realtime'],\n requestSchema: 'RealtimeConnectRequestSchema',\n responseSchema: 'RealtimeConnectResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/disconnect',\n handler: 'realtimeDisconnect',\n category: 'realtime',\n public: false,\n summary: 'Close realtime connection',\n description: 'Closes an active realtime connection',\n tags: ['Realtime'],\n requestSchema: 'RealtimeDisconnectRequestSchema',\n responseSchema: 'RealtimeDisconnectResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/subscribe',\n handler: 'realtimeSubscribe',\n category: 'realtime',\n public: false,\n summary: 'Subscribe to channel',\n description: 'Subscribes to a realtime channel for receiving events',\n tags: ['Realtime'],\n requestSchema: 'RealtimeSubscribeRequestSchema',\n responseSchema: 'RealtimeSubscribeResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/unsubscribe',\n handler: 'realtimeUnsubscribe',\n category: 'realtime',\n public: false,\n summary: 'Unsubscribe from channel',\n description: 'Unsubscribes from a realtime channel',\n tags: ['Realtime'],\n requestSchema: 'RealtimeUnsubscribeRequestSchema',\n responseSchema: 'RealtimeUnsubscribeResponseSchema',\n cacheable: false,\n },\n {\n method: 'PUT',\n path: '/presence/:channel',\n handler: 'setPresence',\n category: 'realtime',\n public: false,\n summary: 'Set presence state',\n description: 'Sets the current user\\'s presence state in a channel',\n tags: ['Realtime'],\n requestSchema: 'SetPresenceRequestSchema',\n responseSchema: 'SetPresenceResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/presence/:channel',\n handler: 'getPresence',\n category: 'realtime',\n public: false,\n summary: 'Get channel presence',\n description: 'Returns all active members and their presence state in a channel',\n tags: ['Realtime'],\n responseSchema: 'GetPresenceResponseSchema',\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Notification Routes\n// ==========================================\n\n/**\n * Default Notification Routes\n * Standard routes for notification management (device registration, preferences, listing)\n */\nexport const DEFAULT_NOTIFICATION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/notifications',\n service: 'notification',\n category: 'notification',\n methods: [\n 'registerDevice', 'unregisterDevice',\n 'getNotificationPreferences', 'updateNotificationPreferences',\n 'listNotifications', 'markNotificationsRead', 'markAllNotificationsRead',\n ],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/devices',\n handler: 'registerDevice',\n category: 'notification',\n public: false,\n summary: 'Register device for push notifications',\n description: 'Registers a device token for receiving push notifications',\n tags: ['Notifications'],\n requestSchema: 'RegisterDeviceRequestSchema',\n responseSchema: 'RegisterDeviceResponseSchema',\n cacheable: false,\n },\n {\n method: 'DELETE',\n path: '/devices/:deviceId',\n handler: 'unregisterDevice',\n category: 'notification',\n public: false,\n summary: 'Unregister device',\n description: 'Removes a device from push notification registration',\n tags: ['Notifications'],\n responseSchema: 'UnregisterDeviceResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/preferences',\n handler: 'getNotificationPreferences',\n category: 'notification',\n public: false,\n summary: 'Get notification preferences',\n description: 'Returns current user notification preferences',\n tags: ['Notifications'],\n responseSchema: 'GetNotificationPreferencesResponseSchema',\n cacheable: false,\n },\n {\n method: 'PATCH',\n path: '/preferences',\n handler: 'updateNotificationPreferences',\n category: 'notification',\n public: false,\n summary: 'Update notification preferences',\n description: 'Updates user notification preferences',\n tags: ['Notifications'],\n requestSchema: 'UpdateNotificationPreferencesRequestSchema',\n responseSchema: 'UpdateNotificationPreferencesResponseSchema',\n cacheable: false,\n },\n {\n method: 'GET',\n path: '',\n handler: 'listNotifications',\n category: 'notification',\n public: false,\n summary: 'List notifications',\n description: 'Returns paginated list of notifications for the current user',\n tags: ['Notifications'],\n responseSchema: 'ListNotificationsResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/read',\n handler: 'markNotificationsRead',\n category: 'notification',\n public: false,\n summary: 'Mark notifications as read',\n description: 'Marks specific notifications as read by their IDs',\n tags: ['Notifications'],\n requestSchema: 'MarkNotificationsReadRequestSchema',\n responseSchema: 'MarkNotificationsReadResponseSchema',\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/read/all',\n handler: 'markAllNotificationsRead',\n category: 'notification',\n public: false,\n summary: 'Mark all notifications as read',\n description: 'Marks all notifications as read for the current user',\n tags: ['Notifications'],\n responseSchema: 'MarkAllNotificationsReadResponseSchema',\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// AI Routes\n// ==========================================\n\n/**\n * Default AI Routes\n * Standard routes for AI operations (NLQ, Chat, Suggest, Insights)\n */\nexport const DEFAULT_AI_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/ai',\n service: 'ai',\n category: 'ai',\n methods: ['aiNlq', 'aiSuggest', 'aiInsights'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/nlq',\n handler: 'aiNlq',\n category: 'ai',\n public: false,\n summary: 'Natural language query',\n description: 'Converts a natural language query to a structured query AST',\n tags: ['AI'],\n requestSchema: 'AiNlqRequestSchema',\n responseSchema: 'AiNlqResponseSchema',\n timeout: 30000,\n cacheable: false,\n },\n // AI chat route removed — wire protocol aligned with Vercel AI SDK.\n // The chat endpoint should use Vercel's `toDataStreamResponse()` directly.\n {\n method: 'POST',\n path: '/suggest',\n handler: 'aiSuggest',\n category: 'ai',\n public: false,\n summary: 'Get AI-powered suggestions',\n description: 'Returns AI-generated field value suggestions based on context',\n tags: ['AI'],\n requestSchema: 'AiSuggestRequestSchema',\n responseSchema: 'AiSuggestResponseSchema',\n timeout: 15000,\n cacheable: false,\n },\n {\n method: 'POST',\n path: '/insights',\n handler: 'aiInsights',\n category: 'ai',\n public: false,\n summary: 'Get AI-generated insights',\n description: 'Returns AI-generated insights (summaries, trends, anomalies, recommendations)',\n tags: ['AI'],\n requestSchema: 'AiInsightsRequestSchema',\n responseSchema: 'AiInsightsResponseSchema',\n timeout: 60000,\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// i18n Routes\n// ==========================================\n\n/**\n * Default i18n Routes\n * Standard routes for internationalization operations\n */\nexport const DEFAULT_I18N_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/i18n',\n service: 'i18n',\n category: 'i18n',\n methods: ['getLocales', 'getTranslations', 'getFieldLabels'],\n authRequired: true,\n endpoints: [\n {\n method: 'GET',\n path: '/locales',\n handler: 'getLocales',\n category: 'i18n',\n public: false,\n summary: 'Get available locales',\n description: 'Returns all available locales with their metadata',\n tags: ['i18n'],\n responseSchema: 'GetLocalesResponseSchema',\n cacheable: true,\n cacheTtl: 86400, // 24 hours — locales change very rarely\n },\n {\n method: 'GET',\n path: '/translations/:locale',\n handler: 'getTranslations',\n category: 'i18n',\n public: false,\n summary: 'Get translations for a locale',\n description: 'Returns translation strings for the specified locale and optional namespace',\n tags: ['i18n'],\n responseSchema: 'GetTranslationsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n {\n method: 'GET',\n path: '/labels/:object/:locale',\n handler: 'getFieldLabels',\n category: 'i18n',\n public: false,\n summary: 'Get translated field labels',\n description: 'Returns translated field labels, help text, and option labels for an object',\n tags: ['i18n'],\n responseSchema: 'GetFieldLabelsResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n ],\n};\n\n// ==========================================\n// Analytics Routes\n// ==========================================\n\n/**\n * Default Analytics Routes\n * Standard routes for analytics and BI operations\n */\nexport const DEFAULT_ANALYTICS_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/analytics',\n service: 'analytics',\n category: 'analytics',\n methods: ['analyticsQuery', 'getAnalyticsMeta'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/query',\n handler: 'analyticsQuery',\n category: 'analytics',\n public: false,\n summary: 'Execute analytics query',\n description: 'Executes a structured analytics query against the semantic layer',\n tags: ['Analytics'],\n requestSchema: 'AnalyticsQueryRequestSchema',\n responseSchema: 'AnalyticsResultResponseSchema',\n permissions: ['analytics.query'],\n timeout: 120000, // 2 minutes for analytics queries\n cacheable: false,\n },\n {\n method: 'GET',\n path: '/meta',\n handler: 'getAnalyticsMeta',\n category: 'analytics',\n public: false,\n summary: 'Get analytics metadata',\n description: 'Returns available cubes, dimensions, measures, and segments',\n tags: ['Analytics'],\n responseSchema: 'AnalyticsMetadataResponseSchema',\n cacheable: true,\n cacheTtl: 3600,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Automation Routes\n// ==========================================\n\n/**\n * Default Automation Routes\n * Standard routes for automation triggers\n */\nexport const DEFAULT_AUTOMATION_ROUTES: RestApiRouteRegistration = {\n prefix: '/api/v1/automation',\n service: 'automation',\n category: 'automation',\n methods: ['triggerAutomation'],\n authRequired: true,\n endpoints: [\n {\n method: 'POST',\n path: '/trigger',\n handler: 'triggerAutomation',\n category: 'automation',\n public: false,\n summary: 'Trigger automation',\n description: 'Triggers an automation flow or script by name',\n tags: ['Automation'],\n requestSchema: 'AutomationTriggerRequestSchema',\n responseSchema: 'AutomationTriggerResponseSchema',\n permissions: ['automation.trigger'],\n timeout: 120000, // 2 minutes for long-running automations\n cacheable: false,\n },\n ],\n middleware: [\n { name: 'auth', type: 'authentication', enabled: true, order: 10 },\n { name: 'validation', type: 'validation', enabled: true, order: 20 },\n { name: 'response_envelope', type: 'transformation', enabled: true, order: 100 },\n { name: 'error_handler', type: 'error', enabled: true, order: 200 },\n ],\n};\n\n// ==========================================\n// Helper Functions\n// ==========================================\n\n/**\n * Helper to create REST API plugin configuration\n */\nexport const RestApiPluginConfig = Object.assign(RestApiPluginConfigSchema, {\n create: >(config: T) => config,\n});\n\n/**\n * Helper to create route registration\n */\nexport const RestApiRouteRegistration = Object.assign(RestApiRouteRegistrationSchema, {\n create: >(registration: T) => registration,\n});\n\n/**\n * Get all default route registrations.\n * Returns the complete set of standard REST API routes covering all protocol namespaces.\n * \n * Route groups (13 total):\n * 1. Discovery - API capabilities and routing info\n * 2. Metadata - Object/field schema CRUD\n * 3. Data CRUD - Record operations\n * 4. Batch - Bulk operations\n * 5. Permission - Authorization checks\n * 6. Views - UI view CRUD\n * 7. Workflow - State machine transitions\n * 8. Realtime - WebSocket/SSE connections\n * 9. Notification - Push notifications and preferences\n * 10. AI - NLQ, chat, suggestions, insights\n * 11. i18n - Locales and translations\n * 12. Analytics - BI queries and metadata\n * 13. Automation - Trigger flows and scripts\n */\nexport function getDefaultRouteRegistrations(): RestApiRouteRegistration[] {\n return [\n DEFAULT_DISCOVERY_ROUTES,\n DEFAULT_METADATA_ROUTES,\n DEFAULT_DATA_CRUD_ROUTES,\n DEFAULT_BATCH_ROUTES,\n DEFAULT_PERMISSION_ROUTES,\n DEFAULT_VIEW_ROUTES,\n DEFAULT_WORKFLOW_ROUTES,\n DEFAULT_REALTIME_ROUTES,\n DEFAULT_NOTIFICATION_ROUTES,\n DEFAULT_AI_ROUTES,\n DEFAULT_I18N_ROUTES,\n DEFAULT_ANALYTICS_ROUTES,\n DEFAULT_AUTOMATION_ROUTES,\n ];\n}\n\n// ==========================================\n// Route Coverage Report\n// ==========================================\n\n/**\n * Route Coverage Entry Schema\n * Reports the coverage status of a single declared endpoint.\n */\nexport const RouteCoverageEntrySchema = z.object({\n /** Full URL path of the endpoint */\n path: z.string().describe('Full URL path (e.g. /api/v1/analytics/query)'),\n /** HTTP method */\n method: HttpMethod.describe('HTTP method (GET, POST, etc.)'),\n /** Route category */\n category: RestApiRouteCategory.describe('Route category'),\n /** Handler implementation status */\n handlerStatus: HandlerStatusSchema.describe('Handler status'),\n /** Target service */\n service: z.string().describe('Target service name'),\n /** Whether the handler was successfully called during health check */\n healthCheckPassed: z.boolean().optional().describe('Whether the health check probe succeeded'),\n});\n\nexport type RouteCoverageEntry = z.infer;\n\n/**\n * Route Coverage Report Schema\n *\n * Aggregated report generated by the adapter/dispatcher at startup.\n * Lists every declared endpoint and whether a handler is confirmed.\n *\n * Adapters SHOULD log a warning for every endpoint where\n * `handlerStatus !== 'implemented'` and emit this report as part\n * of the startup health diagnostics.\n */\nexport const RouteCoverageReportSchema = z.object({\n /** ISO 8601 timestamp of report generation */\n timestamp: z.string().describe('ISO 8601 timestamp'),\n /** Adapter that generated the report */\n adapter: z.string().describe('Adapter name (e.g. \"hono\", \"express\", \"nextjs\")'),\n /** Summary counters */\n summary: z.object({\n total: z.number().int().describe('Total declared endpoints'),\n implemented: z.number().int().describe('Endpoints with real handlers'),\n stub: z.number().int().describe('Endpoints with stub handlers (501)'),\n planned: z.number().int().describe('Endpoints not yet implemented'),\n }),\n /** Per-endpoint entries */\n entries: z.array(RouteCoverageEntrySchema).describe('Per-endpoint coverage entries'),\n});\n\nexport type RouteCoverageReport = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * API Query DSL Adapter Protocol\n * \n * Defines mapping rules between the internal unified query DSL\n * (defined in `data/query.zod.ts`) and external API protocol formats:\n * REST, GraphQL, and OData.\n * \n * This enables ObjectStack to expose a single internal query representation\n * while supporting multiple API standards for external consumers.\n * \n * @see data/query.zod.ts - Unified internal query DSL\n * @see api/rest-server.zod.ts - REST API configuration\n * @see api/graphql.zod.ts - GraphQL API configuration\n * @see api/odata.zod.ts - OData API configuration\n */\n\n// ==========================================\n// 1. Shared Adapter Types\n// ==========================================\n\n/**\n * Query Adapter Target Protocol\n */\nexport const QueryAdapterTargetSchema = z.enum([\n 'rest', // REST API (?filter[field][op]=value)\n 'graphql', // GraphQL (where: \\{ field: \\{ op: value \\}\\})\n 'odata', // OData ($filter=field op value)\n]);\n\nexport type QueryAdapterTarget = z.infer;\n\n/**\n * Operator Mapping Entry\n * \n * Maps a unified DSL operator to its protocol-specific syntax.\n */\nexport const OperatorMappingSchema = z.object({\n /** Unified DSL operator (e.g., 'eq', 'gt', 'contains') */\n operator: z.string().describe('Unified DSL operator'),\n\n /** REST query parameter format (e.g., 'filter[{field}][{op}]') */\n rest: z.string().optional().describe('REST query parameter template'),\n\n /** GraphQL where clause format (e.g., '{field}: { {op}: $value }') */\n graphql: z.string().optional().describe('GraphQL where clause template'),\n\n /** OData $filter expression format (e.g., '{field} {op} {value}') */\n odata: z.string().optional().describe('OData $filter expression template'),\n});\n\nexport type OperatorMapping = z.infer;\n\n// ==========================================\n// 2. REST Adapter Configuration\n// ==========================================\n\n/**\n * REST Query Adapter Configuration\n * \n * Defines how unified query DSL maps to REST query parameters.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10 }\n * REST: ?filter[status][eq]=active&limit=10\n */\nexport const RestQueryAdapterSchema = z.object({\n /** Filter parameter style */\n filterStyle: z.enum([\n 'bracket', // ?filter[field][op]=value (JSON API style)\n 'dot', // ?filter.field.op=value\n 'flat', // ?field=value (simple equality)\n 'rsql', // ?filter=field==value;field=gt=10 (RSQL / FIQL)\n ]).default('bracket').describe('REST filter parameter encoding style'),\n\n /** Pagination parameter names */\n pagination: z.object({\n /** Page size parameter name */\n limitParam: z.string().default('limit').describe('Page size parameter name'),\n\n /** Offset parameter name */\n offsetParam: z.string().default('offset').describe('Offset parameter name'),\n\n /** Cursor parameter name (for cursor-based pagination) */\n cursorParam: z.string().default('cursor').describe('Cursor parameter name'),\n\n /** Page number parameter name (for page-based pagination) */\n pageParam: z.string().default('page').describe('Page number parameter name'),\n }).optional().describe('Pagination parameter name mappings'),\n\n /** Sort parameter name and format */\n sorting: z.object({\n /** Sort parameter name */\n param: z.string().default('sort').describe('Sort parameter name'),\n\n /** Sort format */\n format: z.enum([\n 'comma', // ?sort=field1,-field2\n 'array', // ?sort[]=field1&sort[]=-field2\n 'pipe', // ?sort=field1|asc,field2|desc\n ]).default('comma').describe('Sort parameter encoding format'),\n }).optional().describe('Sort parameter mapping'),\n\n /** Field selection parameter name */\n fieldsParam: z.string().default('fields').describe('Field selection parameter name'),\n});\n\nexport type RestQueryAdapter = z.infer;\nexport type RestQueryAdapterInput = z.input;\n\n// ==========================================\n// 3. GraphQL Adapter Configuration\n// ==========================================\n\n/**\n * GraphQL Query Adapter Configuration\n * \n * Defines how unified query DSL maps to GraphQL arguments.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10, sort: [{ field: 'name', order: 'asc' }] }\n * GraphQL: query { items(where: { status: { eq: \"active\" } }, limit: 10, orderBy: { name: ASC }) { ... } }\n */\nexport const GraphQLQueryAdapterSchema = z.object({\n /** Filter argument name in GraphQL queries */\n filterArgName: z.string().default('where').describe('GraphQL filter argument name'),\n\n /** Filter nesting style */\n filterStyle: z.enum([\n 'nested', // where: { field: { op: value } } (Prisma style)\n 'flat', // where: { field_op: value } (Hasura style)\n 'array', // where: [{ field, op, value }] (Array of conditions)\n ]).default('nested').describe('GraphQL filter nesting style'),\n\n /** Pagination argument names */\n pagination: z.object({\n limitArg: z.string().default('limit').describe('Page size argument name'),\n offsetArg: z.string().default('offset').describe('Offset argument name'),\n firstArg: z.string().default('first').describe('Relay \"first\" argument name'),\n afterArg: z.string().default('after').describe('Relay \"after\" cursor argument name'),\n }).optional().describe('Pagination argument name mappings'),\n\n /** Sort argument configuration */\n sorting: z.object({\n argName: z.string().default('orderBy').describe('Sort argument name'),\n format: z.enum([\n 'enum', // orderBy: { field: ASC }\n 'array', // orderBy: [{ field: \"name\", direction: \"ASC\" }]\n ]).default('enum').describe('Sort argument format'),\n }).optional().describe('Sort argument mapping'),\n});\n\nexport type GraphQLQueryAdapter = z.infer;\nexport type GraphQLQueryAdapterInput = z.input;\n\n// ==========================================\n// 4. OData Adapter Configuration\n// ==========================================\n\n/**\n * OData Query Adapter Configuration\n * \n * Defines how unified query DSL maps to OData system query options.\n * \n * @example\n * Unified: { filters: [['status', '=', 'active']], top: 10, sort: [{ field: 'name', order: 'asc' }] }\n * OData: ?$filter=status eq 'active'&$top=10&$orderby=name asc\n */\nexport const ODataQueryAdapterSchema = z.object({\n /** OData version */\n version: z.enum(['v2', 'v4']).default('v4').describe('OData version'),\n\n /** System query option prefixes */\n usePrefix: z.boolean().default(true).describe('Use $ prefix for system query options ($filter vs filter)'),\n\n /** String function support */\n stringFunctions: z.array(z.enum([\n 'contains',\n 'startswith',\n 'endswith',\n 'tolower',\n 'toupper',\n 'trim',\n 'concat',\n 'substring',\n 'length',\n ])).optional().describe('Supported OData string functions'),\n\n /** Expand (nested resource) configuration */\n expand: z.object({\n enabled: z.boolean().default(true).describe('Enable $expand support'),\n maxDepth: z.number().int().min(1).default(3).describe('Maximum expand depth'),\n }).optional().describe('$expand configuration'),\n});\n\nexport type ODataQueryAdapter = z.infer;\nexport type ODataQueryAdapterInput = z.input;\n\n// ==========================================\n// 5. Complete Query Adapter Configuration\n// ==========================================\n\n/**\n * Query Adapter Configuration\n * \n * Root configuration for query DSL adapters across all supported protocols.\n * Controls how the internal unified DSL is translated to external API formats.\n */\nexport const QueryAdapterConfigSchema = z.object({\n /** Default operator mappings */\n operatorMappings: z.array(OperatorMappingSchema).optional().describe('Custom operator mappings'),\n\n /** REST adapter configuration */\n rest: RestQueryAdapterSchema.optional().describe('REST query adapter configuration'),\n\n /** GraphQL adapter configuration */\n graphql: GraphQLQueryAdapterSchema.optional().describe('GraphQL query adapter configuration'),\n\n /** OData adapter configuration */\n odata: ODataQueryAdapterSchema.optional().describe('OData query adapter configuration'),\n});\n\nexport type QueryAdapterConfig = z.infer;\nexport type QueryAdapterConfigInput = z.input;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport {\n FeedItemType,\n FeedItemSchema,\n FeedVisibility,\n MentionSchema,\n ReactionSchema,\n FieldChangeEntrySchema,\n} from '../data/feed.zod';\nimport {\n SubscriptionEventType,\n NotificationChannel,\n RecordSubscriptionSchema,\n} from '../data/subscription.zod';\n\n/**\n * Feed / Chatter API Protocol\n *\n * Defines the HTTP interface for the unified activity timeline (Feed).\n * Covers Feed CRUD, Emoji Reactions, Pin/Star, Search, Changelog,\n * and Record Subscription endpoints.\n *\n * Base path: /api/data/{object}/{recordId}/feed\n *\n * @example Endpoints\n * GET /api/data/{object}/{recordId}/feed — List feed items\n * POST /api/data/{object}/{recordId}/feed — Create feed item\n * PUT /api/data/{object}/{recordId}/feed/{feedId} — Update feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId} — Delete feed item\n * POST /api/data/{object}/{recordId}/feed/{feedId}/reactions — Add reaction\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/reactions/{emoji} — Remove reaction\n * POST /api/data/{object}/{recordId}/feed/{feedId}/pin — Pin feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/pin — Unpin feed item\n * POST /api/data/{object}/{recordId}/feed/{feedId}/star — Star feed item\n * DELETE /api/data/{object}/{recordId}/feed/{feedId}/star — Unstar feed item\n * GET /api/data/{object}/{recordId}/feed/search — Search feed items\n * GET /api/data/{object}/{recordId}/changelog — Get field-level changelog\n * POST /api/data/{object}/{recordId}/subscribe — Subscribe\n * DELETE /api/data/{object}/{recordId}/subscribe — Unsubscribe\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Common path parameters shared across all feed endpoints.\n */\nexport const FeedPathParamsSchema = z.object({\n object: z.string().describe('Object name (e.g., \"account\")'),\n recordId: z.string().describe('Record ID'),\n});\nexport type FeedPathParams = z.infer;\n\n/**\n * Path parameters for single-feed-item operations (update, delete).\n */\nexport const FeedItemPathParamsSchema = FeedPathParamsSchema.extend({\n feedId: z.string().describe('Feed item ID'),\n});\nexport type FeedItemPathParams = z.infer;\n\n// ==========================================\n// 2. Feed List (GET)\n// ==========================================\n\n/**\n * Feed filter type for the list query.\n * Maps to FeedFilterMode: all | comments_only | changes_only | tasks_only\n */\nexport const FeedListFilterType = z.enum([\n 'all',\n 'comments_only',\n 'changes_only',\n 'tasks_only',\n]);\n\n/**\n * Query parameters for listing feed items.\n *\n * @example GET /api/data/account/rec_123/feed?type=all&limit=20&cursor=xxx\n */\nexport const GetFeedRequestSchema = FeedPathParamsSchema.extend({\n type: FeedListFilterType.default('all')\n .describe('Filter by feed item category'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of items to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination (opaque string from previous response)'),\n});\nexport type GetFeedRequest = z.infer;\n\n/**\n * Response for the feed list endpoint.\n */\nexport const GetFeedResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n items: z.array(FeedItemSchema).describe('Feed items in reverse chronological order'),\n total: z.number().int().optional().describe('Total feed items matching filter'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more items are available'),\n }),\n});\nexport type GetFeedResponse = z.infer;\n\n// ==========================================\n// 3. Feed Create (POST)\n// ==========================================\n\n/**\n * Request body for creating a new feed item (comment, note, task, etc.).\n *\n * @example POST /api/data/account/rec_123/feed\n * { type: 'comment', body: 'Great progress! @jane can you follow up?', mentions: [...] }\n */\nexport const CreateFeedItemRequestSchema = FeedPathParamsSchema.extend({\n type: FeedItemType.describe('Type of feed item to create'),\n body: z.string().optional()\n .describe('Rich text body (Markdown supported)'),\n mentions: z.array(MentionSchema).optional()\n .describe('Mentioned users, teams, or records'),\n parentId: z.string().optional()\n .describe('Parent feed item ID for threaded replies'),\n visibility: FeedVisibility.default('public')\n .describe('Visibility: public, internal, or private'),\n});\nexport type CreateFeedItemRequest = z.infer;\n\n/**\n * Response after creating a feed item.\n */\nexport const CreateFeedItemResponseSchema = BaseResponseSchema.extend({\n data: FeedItemSchema.describe('The created feed item'),\n});\nexport type CreateFeedItemResponse = z.infer;\n\n// ==========================================\n// 4. Feed Update (PUT)\n// ==========================================\n\n/**\n * Request body for updating an existing feed item (e.g., editing a comment).\n *\n * @example PUT /api/data/account/rec_123/feed/feed_001\n * { body: 'Updated comment text', mentions: [...] }\n */\nexport const UpdateFeedItemRequestSchema = FeedItemPathParamsSchema.extend({\n body: z.string().optional()\n .describe('Updated rich text body'),\n mentions: z.array(MentionSchema).optional()\n .describe('Updated mentions'),\n visibility: FeedVisibility.optional()\n .describe('Updated visibility'),\n});\nexport type UpdateFeedItemRequest = z.infer;\n\n/**\n * Response after updating a feed item.\n */\nexport const UpdateFeedItemResponseSchema = BaseResponseSchema.extend({\n data: FeedItemSchema.describe('The updated feed item'),\n});\nexport type UpdateFeedItemResponse = z.infer;\n\n// ==========================================\n// 5. Feed Delete (DELETE)\n// ==========================================\n\n/**\n * Request parameters for deleting a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001\n */\nexport const DeleteFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type DeleteFeedItemRequest = z.infer;\n\n/**\n * Response after deleting a feed item.\n */\nexport const DeleteFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the deleted feed item'),\n }),\n});\nexport type DeleteFeedItemResponse = z.infer;\n\n// ==========================================\n// 6. Reactions (POST / DELETE)\n// ==========================================\n\n/**\n * Request for adding an emoji reaction to a feed item.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/reactions\n * { emoji: '👍' }\n */\nexport const AddReactionRequestSchema = FeedItemPathParamsSchema.extend({\n emoji: z.string().describe('Emoji character or shortcode (e.g., \"👍\", \":thumbsup:\")'),\n});\nexport type AddReactionRequest = z.infer;\n\n/**\n * Response after adding a reaction.\n */\nexport const AddReactionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n reactions: z.array(ReactionSchema).describe('Updated reaction list for the feed item'),\n }),\n});\nexport type AddReactionResponse = z.infer;\n\n/**\n * Request for removing an emoji reaction from a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/reactions/👍\n */\nexport const RemoveReactionRequestSchema = FeedItemPathParamsSchema.extend({\n emoji: z.string().describe('Emoji character or shortcode to remove'),\n});\nexport type RemoveReactionRequest = z.infer;\n\n/**\n * Response after removing a reaction.\n */\nexport const RemoveReactionResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n reactions: z.array(ReactionSchema).describe('Updated reaction list for the feed item'),\n }),\n});\nexport type RemoveReactionResponse = z.infer;\n\n// ==========================================\n// 7. Pin / Star\n// ==========================================\n\n/**\n * Request for pinning a feed item to the top of the timeline.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/pin\n */\nexport const PinFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type PinFeedItemRequest = z.infer;\n\n/**\n * Response after pinning a feed item.\n */\nexport const PinFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the pinned feed item'),\n pinned: z.boolean().describe('Whether the item is now pinned'),\n pinnedAt: z.string().datetime().describe('Timestamp when pinned'),\n }),\n});\nexport type PinFeedItemResponse = z.infer;\n\n/**\n * Request for unpinning a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/pin\n */\nexport const UnpinFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type UnpinFeedItemRequest = z.infer;\n\n/**\n * Response after unpinning a feed item.\n */\nexport const UnpinFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the unpinned feed item'),\n pinned: z.boolean().describe('Whether the item is now pinned (should be false)'),\n }),\n});\nexport type UnpinFeedItemResponse = z.infer;\n\n/**\n * Request for starring (bookmarking) a feed item.\n *\n * @example POST /api/data/account/rec_123/feed/feed_001/star\n */\nexport const StarFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type StarFeedItemRequest = z.infer;\n\n/**\n * Response after starring a feed item.\n */\nexport const StarFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the starred feed item'),\n starred: z.boolean().describe('Whether the item is now starred'),\n starredAt: z.string().datetime().describe('Timestamp when starred'),\n }),\n});\nexport type StarFeedItemResponse = z.infer;\n\n/**\n * Request for unstarring a feed item.\n *\n * @example DELETE /api/data/account/rec_123/feed/feed_001/star\n */\nexport const UnstarFeedItemRequestSchema = FeedItemPathParamsSchema;\nexport type UnstarFeedItemRequest = z.infer;\n\n/**\n * Response after unstarring a feed item.\n */\nexport const UnstarFeedItemResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n feedId: z.string().describe('ID of the unstarred feed item'),\n starred: z.boolean().describe('Whether the item is now starred (should be false)'),\n }),\n});\nexport type UnstarFeedItemResponse = z.infer;\n\n// ==========================================\n// 8. Activity Feed Search & Filter\n// ==========================================\n\n/**\n * Request for searching feed items with full-text query and advanced filters.\n *\n * @example GET /api/data/account/rec_123/feed/search?query=follow+up&actorId=user_456&dateFrom=2026-01-01T00:00:00Z\n */\nexport const SearchFeedRequestSchema = FeedPathParamsSchema.extend({\n query: z.string().min(1).describe('Full-text search query against feed body content'),\n type: FeedListFilterType.optional()\n .describe('Filter by feed item category'),\n actorId: z.string().optional()\n .describe('Filter by actor user ID'),\n dateFrom: z.string().datetime().optional()\n .describe('Filter feed items created after this timestamp'),\n dateTo: z.string().datetime().optional()\n .describe('Filter feed items created before this timestamp'),\n hasAttachments: z.boolean().optional()\n .describe('Filter for items with file attachments'),\n pinnedOnly: z.boolean().optional()\n .describe('Return only pinned items'),\n starredOnly: z.boolean().optional()\n .describe('Return only starred items'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of items to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type SearchFeedRequest = z.infer;\n\n/**\n * Response for the feed search endpoint.\n */\nexport const SearchFeedResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n items: z.array(FeedItemSchema).describe('Matching feed items sorted by relevance'),\n total: z.number().int().optional().describe('Total matching items'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more items are available'),\n }),\n});\nexport type SearchFeedResponse = z.infer;\n\n// ==========================================\n// 9. Changelog (Field-Level Audit Trail)\n// ==========================================\n\n/**\n * Request for retrieving the field-level changelog of a record.\n *\n * @example GET /api/data/account/rec_123/changelog?field=status&limit=50\n */\nexport const GetChangelogRequestSchema = FeedPathParamsSchema.extend({\n field: z.string().optional()\n .describe('Filter changelog to a specific field name'),\n actorId: z.string().optional()\n .describe('Filter changelog by actor user ID'),\n dateFrom: z.string().datetime().optional()\n .describe('Filter changes after this timestamp'),\n dateTo: z.string().datetime().optional()\n .describe('Filter changes before this timestamp'),\n limit: z.number().int().min(1).max(200).default(50)\n .describe('Maximum number of changelog entries to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type GetChangelogRequest = z.infer;\n\n/**\n * A single changelog entry representing one or more field changes at a point in time.\n */\nexport const ChangelogEntrySchema = z.object({\n id: z.string().describe('Changelog entry ID'),\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n actor: z.object({\n type: z.enum(['user', 'system', 'service', 'automation']).describe('Actor type'),\n id: z.string().describe('Actor ID'),\n name: z.string().optional().describe('Actor display name'),\n }).describe('Who made the change'),\n changes: z.array(FieldChangeEntrySchema).min(1).describe('Field-level changes'),\n timestamp: z.string().datetime().describe('When the change occurred'),\n source: z.string().optional().describe('Change source (e.g., \"API\", \"UI\", \"automation\")'),\n});\nexport type ChangelogEntry = z.infer;\n\n/**\n * Response for the changelog endpoint.\n */\nexport const GetChangelogResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n entries: z.array(ChangelogEntrySchema).describe('Changelog entries in reverse chronological order'),\n total: z.number().int().optional().describe('Total changelog entries matching filter'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more entries are available'),\n }),\n});\nexport type GetChangelogResponse = z.infer;\n\n// ==========================================\n// 10. Record Subscription (POST / DELETE)\n// ==========================================\n\n/**\n * Request for subscribing to record notifications.\n *\n * @example POST /api/data/account/rec_123/subscribe\n * { events: ['comment', 'field_change'], channels: ['in_app', 'email'] }\n */\nexport const SubscribeRequestSchema = FeedPathParamsSchema.extend({\n events: z.array(SubscriptionEventType).default(['all'])\n .describe('Event types to subscribe to'),\n channels: z.array(NotificationChannel).default(['in_app'])\n .describe('Notification delivery channels'),\n});\nexport type SubscribeRequest = z.infer;\n\n/**\n * Response after subscribing.\n */\nexport const SubscribeResponseSchema = BaseResponseSchema.extend({\n data: RecordSubscriptionSchema.describe('The created or updated subscription'),\n});\nexport type SubscribeResponse = z.infer;\n\n/**\n * Request for unsubscribing from record notifications.\n *\n * @example DELETE /api/data/account/rec_123/subscribe\n */\nexport const FeedUnsubscribeRequestSchema = FeedPathParamsSchema;\nexport type FeedUnsubscribeRequest = z.infer;\n\n/**\n * Response after unsubscribing.\n */\nexport const UnsubscribeResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n object: z.string().describe('Object name'),\n recordId: z.string().describe('Record ID'),\n unsubscribed: z.boolean().describe('Whether the user was unsubscribed'),\n }),\n});\nexport type UnsubscribeResponse = z.infer;\n\n// ==========================================\n// 11. Feed API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Feed/Chatter operations.\n */\nexport const FeedApiErrorCode = z.enum([\n 'feed_item_not_found',\n 'feed_permission_denied',\n 'feed_item_not_editable',\n 'feed_invalid_parent',\n 'reaction_already_exists',\n 'reaction_not_found',\n 'subscription_already_exists',\n 'subscription_not_found',\n 'invalid_feed_type',\n 'feed_already_pinned',\n 'feed_not_pinned',\n 'feed_already_starred',\n 'feed_not_starred',\n 'feed_search_query_too_short',\n]);\nexport type FeedApiErrorCode = z.infer;\n\n// ==========================================\n// 12. Feed API Contract Registry\n// ==========================================\n\n/**\n * Standard Feed API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const FeedApiContracts = {\n listFeed: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/feed',\n input: GetFeedRequestSchema,\n output: GetFeedResponseSchema,\n },\n createFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed',\n input: CreateFeedItemRequestSchema,\n output: CreateFeedItemResponseSchema,\n },\n updateFeedItem: {\n method: 'PUT' as const,\n path: '/api/data/:object/:recordId/feed/:feedId',\n input: UpdateFeedItemRequestSchema,\n output: UpdateFeedItemResponseSchema,\n },\n deleteFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId',\n input: DeleteFeedItemRequestSchema,\n output: DeleteFeedItemResponseSchema,\n },\n addReaction: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/reactions',\n input: AddReactionRequestSchema,\n output: AddReactionResponseSchema,\n },\n removeReaction: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/reactions/:emoji',\n input: RemoveReactionRequestSchema,\n output: RemoveReactionResponseSchema,\n },\n pinFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/pin',\n input: PinFeedItemRequestSchema,\n output: PinFeedItemResponseSchema,\n },\n unpinFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/pin',\n input: UnpinFeedItemRequestSchema,\n output: UnpinFeedItemResponseSchema,\n },\n starFeedItem: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/star',\n input: StarFeedItemRequestSchema,\n output: StarFeedItemResponseSchema,\n },\n unstarFeedItem: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/feed/:feedId/star',\n input: UnstarFeedItemRequestSchema,\n output: UnstarFeedItemResponseSchema,\n },\n searchFeed: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/feed/search',\n input: SearchFeedRequestSchema,\n output: SearchFeedResponseSchema,\n },\n getChangelog: {\n method: 'GET' as const,\n path: '/api/data/:object/:recordId/changelog',\n input: GetChangelogRequestSchema,\n output: GetChangelogResponseSchema,\n },\n subscribe: {\n method: 'POST' as const,\n path: '/api/data/:object/:recordId/subscribe',\n input: SubscribeRequestSchema,\n output: SubscribeResponseSchema,\n },\n unsubscribe: {\n method: 'DELETE' as const,\n path: '/api/data/:object/:recordId/subscribe',\n input: FeedUnsubscribeRequestSchema,\n output: UnsubscribeResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\n\n/**\n * Data Export & Import Protocol\n *\n * Defines schemas for streaming data export, import validation,\n * template-based field mapping, and scheduled export jobs.\n *\n * Industry alignment: Salesforce Data Export, Airtable CSV Export,\n * Dynamics 365 Data Management.\n *\n * Base path: /api/v1/data/{object}/export\n */\n\n// ==========================================\n// 1. Export Format & Configuration\n// ==========================================\n\n/**\n * Export Format Enum\n * Supported file formats for data export.\n */\nexport const ExportFormat = z.enum([\n 'csv',\n 'json',\n 'jsonl',\n 'xlsx',\n 'parquet',\n]);\nexport type ExportFormat = z.infer;\n\n/**\n * Export Job Status\n */\nexport const ExportJobStatus = z.enum([\n 'pending',\n 'processing',\n 'completed',\n 'failed',\n 'cancelled',\n 'expired',\n]);\nexport type ExportJobStatus = z.infer;\n\n// ==========================================\n// 2. Export Job Request / Response\n// ==========================================\n\n/**\n * Create Export Job Request\n * Initiates an asynchronous streaming export.\n *\n * @example POST /api/v1/data/account/export\n * { format: 'csv', fields: ['name', 'email', 'status'], filter: { status: 'active' }, limit: 10000 }\n */\nexport const CreateExportJobRequestSchema = z.object({\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional()\n .describe('Specific fields to include (omit for all fields)'),\n filter: z.record(z.string(), z.unknown()).optional()\n .describe('Filter criteria for records to export'),\n sort: z.array(z.object({\n field: z.string().describe('Field name to sort by'),\n direction: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n })).optional().describe('Sort order for exported records'),\n limit: z.number().int().min(1).optional()\n .describe('Maximum number of records to export'),\n includeHeaders: z.boolean().default(true)\n .describe('Include header row (CSV/XLSX)'),\n encoding: z.string().default('utf-8')\n .describe('Character encoding for the export file'),\n templateId: z.string().optional()\n .describe('Export template ID for predefined field mappings'),\n});\nexport type CreateExportJobRequest = z.infer;\n\n/**\n * Export Job Response\n * Returns the created export job with tracking info.\n */\nexport const CreateExportJobResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n status: ExportJobStatus.describe('Initial job status'),\n estimatedRecords: z.number().int().optional().describe('Estimated total records'),\n createdAt: z.string().datetime().describe('Job creation timestamp'),\n }),\n});\nexport type CreateExportJobResponse = z.infer;\n\n/**\n * Export Job Progress\n * Tracks the progress of an active export job.\n *\n * @example GET /api/v1/data/export/:jobId\n */\nexport const ExportJobProgressSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n status: ExportJobStatus.describe('Current job status'),\n format: ExportFormat.describe('Export format'),\n totalRecords: z.number().int().optional().describe('Total records to export'),\n processedRecords: z.number().int().describe('Records processed so far'),\n percentComplete: z.number().min(0).max(100).describe('Export progress percentage'),\n fileSize: z.number().int().optional().describe('Current file size in bytes'),\n downloadUrl: z.string().optional()\n .describe('Presigned download URL (available when status is \"completed\")'),\n downloadExpiresAt: z.string().datetime().optional()\n .describe('Download URL expiration timestamp'),\n error: z.object({\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n }).optional().describe('Error details if job failed'),\n startedAt: z.string().datetime().optional().describe('Processing start timestamp'),\n completedAt: z.string().datetime().optional().describe('Completion timestamp'),\n }),\n});\nexport type ExportJobProgress = z.infer;\n\n// ==========================================\n// 3. Import Validation & Deduplication\n// ==========================================\n\n/**\n * Import Validation Mode\n */\nexport const ImportValidationMode = z.enum([\n 'strict', // Reject entire import on any validation error\n 'lenient', // Skip invalid records, import valid ones\n 'dry_run', // Validate all records without persisting\n]);\nexport type ImportValidationMode = z.infer;\n\n/**\n * Deduplication Strategy\n * How to handle duplicate records during import.\n */\nexport const DeduplicationStrategy = z.enum([\n 'skip', // Skip duplicates (keep existing)\n 'update', // Update existing with import data\n 'create_new', // Create new record even if duplicate\n 'fail', // Fail the import if duplicates found\n]);\nexport type DeduplicationStrategy = z.infer;\n\n/**\n * Import Validation Config Schema\n * Configuration for validating and deduplicating imported data.\n *\n * @example\n * {\n * mode: 'lenient',\n * deduplication: { strategy: 'update', matchFields: ['email', 'external_id'] },\n * maxErrors: 50,\n * trimWhitespace: true,\n * }\n */\nexport const ImportValidationConfigSchema = z.object({\n mode: ImportValidationMode.default('strict')\n .describe('Validation mode for the import'),\n deduplication: z.object({\n strategy: DeduplicationStrategy.default('skip')\n .describe('How to handle duplicate records'),\n matchFields: z.array(z.string()).min(1)\n .describe('Fields used to identify duplicates (e.g., \"email\", \"external_id\")'),\n }).optional().describe('Deduplication configuration'),\n maxErrors: z.number().int().min(1).default(100)\n .describe('Maximum validation errors before aborting'),\n trimWhitespace: z.boolean().default(true)\n .describe('Trim leading/trailing whitespace from string fields'),\n dateFormat: z.string().optional()\n .describe('Expected date format in import data (e.g., \"YYYY-MM-DD\")'),\n nullValues: z.array(z.string()).optional()\n .describe('Strings to treat as null (e.g., [\"\", \"N/A\", \"null\"])'),\n});\nexport type ImportValidationConfig = z.infer;\n\n/**\n * Import Validation Result Schema\n * Summary of the import validation pass.\n */\nexport const ImportValidationResultSchema = BaseResponseSchema.extend({\n data: z.object({\n totalRecords: z.number().int().describe('Total records in import file'),\n validRecords: z.number().int().describe('Records that passed validation'),\n invalidRecords: z.number().int().describe('Records that failed validation'),\n duplicateRecords: z.number().int().describe('Duplicate records detected'),\n errors: z.array(z.object({\n row: z.number().int().describe('Row number in the import file'),\n field: z.string().optional().describe('Field that failed validation'),\n code: z.string().describe('Validation error code'),\n message: z.string().describe('Validation error message'),\n })).describe('List of validation errors'),\n preview: z.array(z.record(z.string(), z.unknown())).optional()\n .describe('Preview of first N valid records (for dry_run mode)'),\n }),\n});\nexport type ImportValidationResult = z.infer;\n\n// ==========================================\n// 4. Export/Import Template\n// ==========================================\n\n/**\n * Field Mapping Entry Schema\n * Maps a source field to a target field with optional transformation.\n */\nexport const FieldMappingEntrySchema = z.object({\n sourceField: z.string().describe('Field name in the source data (import) or object (export)'),\n targetField: z.string().describe('Field name in the target object (import) or file column (export)'),\n targetLabel: z.string().optional().describe('Display label for the target column (export)'),\n transform: z.enum(['none', 'uppercase', 'lowercase', 'trim', 'date_format', 'lookup'])\n .default('none')\n .describe('Transformation to apply during mapping'),\n defaultValue: z.unknown().optional()\n .describe('Default value if source field is null/empty'),\n required: z.boolean().default(false)\n .describe('Whether this field is required (import validation)'),\n});\nexport type FieldMappingEntry = z.infer;\n\n/**\n * Export/Import Template Schema\n * Reusable template for predefined field mappings.\n *\n * @example\n * {\n * name: 'account_export_v1',\n * label: 'Account Export (Standard)',\n * object: 'account',\n * direction: 'export',\n * mappings: [\n * { sourceField: 'name', targetField: 'Company Name' },\n * { sourceField: 'email', targetField: 'Email', transform: 'lowercase' },\n * ],\n * }\n */\nexport const ExportImportTemplateSchema = z.object({\n id: z.string().optional().describe('Template ID (generated on save)'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Template machine name (snake_case)'),\n label: z.string().describe('Human-readable template label'),\n description: z.string().optional().describe('Template description'),\n object: z.string().describe('Target object name'),\n direction: z.enum(['import', 'export', 'bidirectional'])\n .describe('Template direction'),\n format: ExportFormat.optional().describe('Default file format for this template'),\n mappings: z.array(FieldMappingEntrySchema).min(1)\n .describe('Field mapping entries'),\n createdAt: z.string().datetime().optional().describe('Template creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n createdBy: z.string().optional().describe('User who created the template'),\n});\nexport type ExportImportTemplate = z.infer;\n\n// ==========================================\n// 5. Scheduled Export Jobs\n// ==========================================\n\n/**\n * Scheduled Export Schema\n * Defines a recurring data export job.\n *\n * @example\n * {\n * name: 'weekly_account_export',\n * object: 'account',\n * format: 'csv',\n * schedule: { cronExpression: '0 6 * * MON', timezone: 'America/New_York' },\n * delivery: { method: 'email', recipients: ['admin@example.com'] },\n * }\n */\nexport const ScheduledExportSchema = z.object({\n id: z.string().optional().describe('Scheduled export ID'),\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Schedule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional().describe('Fields to include'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Record filter criteria'),\n templateId: z.string().optional().describe('Export template ID for field mappings'),\n schedule: z.object({\n cronExpression: z.string().describe('Cron expression for schedule'),\n timezone: z.string().default('UTC').describe('IANA timezone'),\n }).describe('Schedule timing configuration'),\n delivery: z.object({\n method: z.enum(['email', 'storage', 'webhook'])\n .describe('How to deliver the export file'),\n recipients: z.array(z.string()).optional()\n .describe('Email recipients (for email delivery)'),\n storagePath: z.string().optional()\n .describe('Storage path (for storage delivery)'),\n webhookUrl: z.string().optional()\n .describe('Webhook URL (for webhook delivery)'),\n }).describe('Export delivery configuration'),\n enabled: z.boolean().default(true).describe('Whether the scheduled export is active'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution'),\n createdAt: z.string().datetime().optional().describe('Creation timestamp'),\n createdBy: z.string().optional().describe('User who created the schedule'),\n});\nexport type ScheduledExport = z.infer;\n\n// ==========================================\n// 6. Get Export Job Download\n// ==========================================\n\n/**\n * Get Export Job Download Request\n * Retrieves a presigned download link for a completed export job.\n *\n * @example GET /api/v1/data/export/:jobId/download\n */\nexport const GetExportJobDownloadRequestSchema = z.object({\n jobId: z.string().describe('Export job ID'),\n});\nexport type GetExportJobDownloadRequest = z.infer;\n\n/**\n * Get Export Job Download Response\n * Returns the presigned download URL and metadata.\n */\nexport const GetExportJobDownloadResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobId: z.string().describe('Export job ID'),\n downloadUrl: z.string().describe('Presigned download URL'),\n fileName: z.string().describe('Suggested file name'),\n fileSize: z.number().int().describe('File size in bytes'),\n format: ExportFormat.describe('Export file format'),\n expiresAt: z.string().datetime().describe('Download URL expiration timestamp'),\n checksum: z.string().optional().describe('File checksum (SHA-256)'),\n }),\n});\nexport type GetExportJobDownloadResponse = z.infer;\n\n// ==========================================\n// 7. List Export Jobs\n// ==========================================\n\n/**\n * List Export Jobs Request\n * Retrieves a paginated list of historical export jobs.\n *\n * @example GET /api/v1/data/export?object=account&status=completed&limit=20\n */\nexport const ListExportJobsRequestSchema = z.object({\n object: z.string().optional().describe('Filter by object name'),\n status: ExportJobStatus.optional().describe('Filter by job status'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of jobs to return'),\n cursor: z.string().optional()\n .describe('Pagination cursor from a previous response'),\n});\nexport type ListExportJobsRequest = z.infer;\n\n/**\n * Export Job Summary\n * Compact representation of an export job for list views.\n */\nexport const ExportJobSummarySchema = z.object({\n jobId: z.string().describe('Export job ID'),\n object: z.string().describe('Object name that was exported'),\n status: ExportJobStatus.describe('Current job status'),\n format: ExportFormat.describe('Export file format'),\n totalRecords: z.number().int().optional().describe('Total records exported'),\n fileSize: z.number().int().optional().describe('File size in bytes'),\n createdAt: z.string().datetime().describe('Job creation timestamp'),\n completedAt: z.string().datetime().optional().describe('Completion timestamp'),\n createdBy: z.string().optional().describe('User who initiated the export'),\n});\nexport type ExportJobSummary = z.infer;\n\n/**\n * List Export Jobs Response\n * Paginated list of export jobs with cursor-based pagination.\n */\nexport const ListExportJobsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n jobs: z.array(ExportJobSummarySchema).describe('List of export jobs'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more jobs are available'),\n }),\n});\nexport type ListExportJobsResponse = z.infer;\n\n// ==========================================\n// 8. Schedule Export Request/Response\n// ==========================================\n\n/**\n * Schedule Export Request\n * Creates a new scheduled (recurring) export job.\n *\n * @example POST /api/v1/data/export/schedules\n */\nexport const ScheduleExportRequestSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Schedule name (snake_case)'),\n label: z.string().optional().describe('Human-readable label'),\n object: z.string().describe('Object name to export'),\n format: ExportFormat.default('csv').describe('Export file format'),\n fields: z.array(z.string()).optional().describe('Fields to include'),\n filter: z.record(z.string(), z.unknown()).optional().describe('Record filter criteria'),\n templateId: z.string().optional().describe('Export template ID for field mappings'),\n schedule: z.object({\n cronExpression: z.string().describe('Cron expression for schedule'),\n timezone: z.string().default('UTC').describe('IANA timezone'),\n }).describe('Schedule timing configuration'),\n delivery: z.object({\n method: z.enum(['email', 'storage', 'webhook'])\n .describe('How to deliver the export file'),\n recipients: z.array(z.string()).optional()\n .describe('Email recipients (for email delivery)'),\n storagePath: z.string().optional()\n .describe('Storage path (for storage delivery)'),\n webhookUrl: z.string().optional()\n .describe('Webhook URL (for webhook delivery)'),\n }).describe('Export delivery configuration'),\n});\nexport type ScheduleExportRequest = z.infer;\n\n/**\n * Schedule Export Response\n * Returns the created scheduled export with generated ID and next run info.\n */\nexport const ScheduleExportResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n id: z.string().describe('Scheduled export ID'),\n name: z.string().describe('Schedule name'),\n enabled: z.boolean().describe('Whether the schedule is active'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution'),\n createdAt: z.string().datetime().describe('Creation timestamp'),\n }),\n});\nexport type ScheduleExportResponse = z.infer;\n\n// ==========================================\n// 9. Export API Contracts\n// ==========================================\n\n/**\n * Export API Contract Registry\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const ExportApiContracts = {\n createExportJob: {\n method: 'POST' as const,\n path: '/api/v1/data/:object/export',\n input: CreateExportJobRequestSchema,\n output: CreateExportJobResponseSchema,\n },\n getExportJobProgress: {\n method: 'GET' as const,\n path: '/api/v1/data/export/:jobId',\n input: z.object({ jobId: z.string() }),\n output: ExportJobProgressSchema,\n },\n getExportJobDownload: {\n method: 'GET' as const,\n path: '/api/v1/data/export/:jobId/download',\n input: GetExportJobDownloadRequestSchema,\n output: GetExportJobDownloadResponseSchema,\n },\n listExportJobs: {\n method: 'GET' as const,\n path: '/api/v1/data/export',\n input: ListExportJobsRequestSchema,\n output: ListExportJobsResponseSchema,\n },\n scheduleExport: {\n method: 'POST' as const,\n path: '/api/v1/data/export/schedules',\n input: ScheduleExportRequestSchema,\n output: ScheduleExportResponseSchema,\n },\n cancelExportJob: {\n method: 'POST' as const,\n path: '/api/v1/data/export/:jobId/cancel',\n input: z.object({ jobId: z.string() }),\n output: BaseResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Flow Node Types\n */\nexport const FlowNodeAction = z.enum([\n 'start', // Trigger\n 'end', // Return/Stop\n 'decision', // If/Else logic\n 'assignment', // Set Variable\n 'loop', // For Each\n 'create_record', // CRUD: Create\n 'update_record', // CRUD: Update\n 'delete_record', // CRUD: Delete\n 'get_record', // CRUD: Get/Query\n 'http_request', // Webhook/API Call\n 'script', // Custom Script (JS/TS)\n 'screen', // Screen / User-Input Element\n 'wait', // Delay/Sleep\n 'subflow', // Call another flow\n 'connector_action', // Zapier-style integration action\n 'parallel_gateway', // BPMN Parallel Gateway — AND-split (all outgoing branches execute concurrently)\n 'join_gateway', // BPMN Join Gateway — AND-join (waits for all incoming branches to complete)\n 'boundary_event', // BPMN Boundary Event — attached to a host node for timer/error/signal interrupts\n]);\n\n/**\n * Flow Variable Schema\n * Variables available within the flow execution context.\n */\nexport const FlowVariableSchema = z.object({\n name: z.string().describe('Variable name'),\n type: z.string().describe('Data type (text, number, boolean, object, list)'),\n isInput: z.boolean().default(false).describe('Is input parameter'),\n isOutput: z.boolean().default(false).describe('Is output parameter'),\n});\n\n/**\n * Flow Node Schema\n * A single step in the visual logic graph.\n * \n * @example Decision Node\n * {\n * id: \"dec_1\",\n * type: \"decision\",\n * label: \"Is High Value?\",\n * config: {\n * conditions: [\n * { label: \"Yes\", expression: \"{amount} > 10000\" },\n * { label: \"No\", expression: \"true\" } // default\n * ]\n * },\n * position: { x: 300, y: 200 }\n * }\n */\nexport const FlowNodeSchema = z.object({\n id: z.string().describe('Node unique ID'),\n type: FlowNodeAction.describe('Action type'),\n label: z.string().describe('Node label'),\n \n /** Node Configuration Options (Specific to type) */\n config: z.record(z.string(), z.unknown()).optional().describe('Node configuration'),\n \n /** \n * Connector Action Configuration\n * Used when type is 'connector_action'\n */\n connectorConfig: z.object({\n connectorId: z.string(),\n actionId: z.string(),\n input: z.record(z.string(), z.unknown()).describe('Mapped inputs for the action'),\n }).optional(),\n\n /** UI Position (for the canvas) */\n position: z.object({ x: z.number(), y: z.number() }).optional(),\n\n /** Node-level execution timeout */\n timeoutMs: z.number().int().min(0).optional().describe('Maximum execution time for this node in milliseconds'),\n\n /** Node input schema declaration for Studio form generation and runtime validation */\n inputSchema: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).describe('Parameter type'),\n required: z.boolean().default(false).describe('Whether the parameter is required'),\n description: z.string().optional().describe('Parameter description'),\n })).optional().describe('Input parameter schema for this node'),\n\n /** Node output schema declaration */\n outputSchema: z.record(z.string(), z.object({\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']).describe('Output type'),\n description: z.string().optional().describe('Output description'),\n })).optional().describe('Output schema declaration for this node'),\n\n /**\n * Wait Event Configuration (for 'wait' nodes)\n * Defines what external event or condition should resume the paused execution.\n * Industry alignment: BPMN Intermediate Catch Events, Temporal Signals.\n */\n waitEventConfig: z.object({\n /** Type of event to wait for */\n eventType: z.enum(['timer', 'signal', 'webhook', 'manual', 'condition'])\n .describe('What kind of event resumes the execution'),\n /** Duration to wait (ISO 8601 duration or milliseconds) — for timer events */\n timerDuration: z.string().optional().describe('ISO 8601 duration (e.g., \"PT1H\") or wait time for timer events'),\n /** Signal name to listen for — for signal/webhook events */\n signalName: z.string().optional().describe('Named signal or webhook event to wait for'),\n /** Timeout before auto-failing or continuing — optional guard */\n timeoutMs: z.number().int().min(0).optional().describe('Maximum wait time before timeout (ms)'),\n /** Action to take on timeout */\n onTimeout: z.enum(['fail', 'continue']).default('fail').describe('Behavior when the wait times out'),\n }).optional().describe('Configuration for wait node event resumption'),\n\n /**\n * Boundary Event Configuration (for 'boundary_event' nodes)\n * Attaches an event handler to a host activity node (BPMN Boundary Event pattern).\n * Industry alignment: BPMN Boundary Error/Timer/Signal Events.\n */\n boundaryConfig: z.object({\n /** ID of the host node this boundary event is attached to */\n attachedToNodeId: z.string().describe('Host node ID this boundary event monitors'),\n /** Type of boundary event */\n eventType: z.enum(['error', 'timer', 'signal', 'cancel'])\n .describe('Boundary event trigger type'),\n /** Whether the boundary event interrupts the host activity */\n interrupting: z.boolean().default(true)\n .describe('If true, the host activity is cancelled when this event fires'),\n /** Error code filter — only for error boundary events */\n errorCode: z.string().optional().describe('Specific error code to catch (empty = catch all errors)'),\n /** Timer duration — only for timer boundary events */\n timerDuration: z.string().optional().describe('ISO 8601 duration for timer boundary events'),\n /** Signal name — only for signal boundary events */\n signalName: z.string().optional().describe('Named signal to catch'),\n }).optional().describe('Configuration for boundary events attached to host nodes'),\n});\n\n/**\n * Flow Edge Schema\n * Connections between nodes.\n */\nexport const FlowEdgeSchema = z.object({\n id: z.string().describe('Edge unique ID'),\n source: z.string().describe('Source Node ID'),\n target: z.string().describe('Target Node ID'),\n \n /** Condition for this path (only for decision/branch nodes) */\n condition: z.string().optional().describe('Expression returning boolean used for branching'),\n \n type: z.enum(['default', 'fault', 'conditional']).default('default')\n .describe('Connection type: default (normal flow), fault (error path), or conditional (expression-guarded)'),\n label: z.string().optional().describe('Label on the connector'),\n\n /**\n * Default Sequence Flow marker (BPMN Default Flow semantics).\n * When true, this edge is taken when no sibling conditional edges match.\n * Only meaningful on outgoing edges of decision/gateway nodes.\n */\n isDefault: z.boolean().default(false)\n .describe('Marks this edge as the default path when no other conditions match'),\n});\n\n/**\n * Flow Schema\n * Visual Business Logic Orchestration.\n * \n * @example Simple Approval Logic\n * {\n * name: \"approve_order_flow\",\n * label: \"Approve Large Orders\",\n * type: \"record_change\",\n * status: \"active\",\n * nodes: [\n * { id: \"start\", type: \"start\", label: \"Start\", position: {x: 0, y: 0} },\n * { id: \"check_amount\", type: \"decision\", label: \"Check Amount\", position: {x: 0, y: 100} },\n * { id: \"auto_approve\", type: \"update_record\", label: \"Auto Approve\", position: {x: -100, y: 200} },\n * { id: \"submit_for_approval\", type: \"connector_action\", label: \"Submit\", position: {x: 100, y: 200} }\n * ],\n * edges: [\n * { id: \"e1\", source: \"start\", target: \"check_amount\" },\n * { id: \"e2\", source: \"check_amount\", target: \"auto_approve\", condition: \"{amount} < 500\" },\n * { id: \"e3\", source: \"check_amount\", target: \"submit_for_approval\", condition: \"{amount} >= 500\" }\n * ]\n * }\n */\nexport const FlowSchema = z.object({\n /** Identity */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name'),\n label: z.string().describe('Flow label'),\n description: z.string().optional(),\n \n /** Metadata & Versioning */\n version: z.number().int().default(1).describe('Version number'),\n status: z.enum(['draft', 'active', 'obsolete', 'invalid']).default('draft').describe('Deployment status'),\n template: z.boolean().default(false).describe('Is logic template (Subflow)'),\n\n /** Trigger Type */\n type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).describe('Flow type'),\n \n /** Configuration Variables */\n variables: z.array(FlowVariableSchema).optional().describe('Flow variables'),\n \n /** Graph Definition */\n nodes: z.array(FlowNodeSchema).describe('Flow nodes'),\n edges: z.array(FlowEdgeSchema).describe('Flow connections'),\n \n /** Execution Config */\n active: z.boolean().default(false).describe('Is active (Deprecated: use status)'),\n runAs: z.enum(['system', 'user']).default('user').describe('Execution context'),\n\n /** Error Handling Strategy */\n errorHandling: z.object({\n strategy: z.enum(['fail', 'retry', 'continue']).default('fail').describe('How to handle node execution errors'),\n maxRetries: z.number().int().min(0).max(10).default(0).describe('Number of retry attempts (only for retry strategy)'),\n retryDelayMs: z.number().int().min(0).default(1000).describe('Delay between retries in milliseconds'),\n backoffMultiplier: z.number().min(1).default(1).describe('Multiplier for exponential backoff between retries'),\n maxRetryDelayMs: z.number().int().min(0).default(30000).describe('Maximum delay between retries in milliseconds'),\n jitter: z.boolean().default(false).describe('Add random jitter to retry delay to avoid thundering herd'),\n fallbackNodeId: z.string().optional().describe('Node ID to jump to on unrecoverable error'),\n }).optional().describe('Flow-level error handling configuration'),\n});\n\n/**\n * Type-safe factory for creating flow definitions.\n *\n * Validates the config at creation time using Zod `.parse()`.\n *\n * @example\n * ```ts\n * const onCreateFlow = defineFlow({\n * name: 'on_task_create',\n * label: 'On Task Create',\n * type: 'record_change',\n * nodes: [\n * { id: 'start', type: 'start', label: 'Start' },\n * { id: 'end', type: 'end', label: 'End' },\n * ],\n * edges: [{ id: 'e1', source: 'start', target: 'end' }],\n * });\n * ```\n */\nexport function defineFlow(config: z.input): FlowParsed {\n return FlowSchema.parse(config);\n}\n\nexport type Flow = z.input;\nexport type FlowParsed = z.infer;\nexport type FlowNode = z.input;\nexport type FlowNodeParsed = z.infer;\nexport type FlowEdge = z.input;\nexport type FlowEdgeParsed = z.infer;\n\n/**\n * Flow Version History Schema\n * Tracks historical versions of flow definitions for rollback support.\n *\n * Industry alignment: Salesforce Flow Versions, n8n Workflow History.\n */\nexport const FlowVersionHistorySchema = z.object({\n flowName: z.string().describe('Flow machine name'),\n version: z.number().int().min(1).describe('Version number'),\n definition: FlowSchema.describe('Complete flow definition snapshot'),\n createdAt: z.string().datetime().describe('When this version was created'),\n createdBy: z.string().optional().describe('User who created this version'),\n changeNote: z.string().optional().describe('Description of what changed in this version'),\n});\n\nexport type FlowVersionHistory = z.input;\nexport type FlowVersionHistoryParsed = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Automation Execution Protocol\n *\n * Defines schemas for execution logging, error tracking, checkpointing,\n * concurrency control, and scheduled execution persistence.\n *\n * Industry alignment: Salesforce Flow Interviews, Temporal Workflow History,\n * AWS Step Functions execution logs.\n */\n\n// ==========================================\n// 1. Execution Status\n// ==========================================\n\n/**\n * Execution Status Enum\n * Tracks the lifecycle of a flow execution instance.\n */\nexport const ExecutionStatus = z.enum([\n 'pending', // Queued, not yet started\n 'running', // Currently executing\n 'paused', // Paused at a wait/checkpoint node\n 'completed', // Successfully finished\n 'failed', // Terminated with error\n 'cancelled', // Manually cancelled\n 'timed_out', // Exceeded max execution time\n 'retrying', // Failed and retrying\n]);\nexport type ExecutionStatus = z.infer;\n\n// ==========================================\n// 2. Execution Log\n// ==========================================\n\n/**\n * Execution Step Log Entry\n * Records the result of executing a single node in the flow graph.\n */\nexport const ExecutionStepLogSchema = z.object({\n nodeId: z.string().describe('Node ID that was executed'),\n nodeType: z.string().describe('Node action type (e.g., \"decision\", \"http_request\")'),\n nodeLabel: z.string().optional().describe('Human-readable node label'),\n status: z.enum(['success', 'failure', 'skipped']).describe('Step execution result'),\n startedAt: z.string().datetime().describe('When the step started'),\n completedAt: z.string().datetime().optional().describe('When the step completed'),\n durationMs: z.number().int().min(0).optional().describe('Step execution duration in milliseconds'),\n input: z.record(z.string(), z.unknown()).optional().describe('Input data passed to the node'),\n output: z.record(z.string(), z.unknown()).optional().describe('Output data produced by the node'),\n error: z.object({\n code: z.string().describe('Error code'),\n message: z.string().describe('Error message'),\n stack: z.string().optional().describe('Stack trace'),\n }).optional().describe('Error details if step failed'),\n retryAttempt: z.number().int().min(0).optional().describe('Retry attempt number (0 = first try)'),\n});\nexport type ExecutionStepLog = z.infer;\n\n/**\n * Execution Log Schema\n * Full execution history for a single flow run.\n *\n * @example\n * {\n * id: 'exec_001',\n * flowName: 'approve_order_flow',\n * flowVersion: 1,\n * status: 'completed',\n * trigger: { type: 'record_change', recordId: 'rec_123', object: 'order' },\n * steps: [\n * { nodeId: 'start', nodeType: 'start', status: 'success', startedAt: '...', durationMs: 1 },\n * { nodeId: 'check_amount', nodeType: 'decision', status: 'success', startedAt: '...', durationMs: 5 },\n * ],\n * startedAt: '2026-02-01T10:00:00Z',\n * completedAt: '2026-02-01T10:00:01Z',\n * durationMs: 1050,\n * }\n */\nexport const ExecutionLogSchema = z.object({\n /** Unique execution ID */\n id: z.string().describe('Execution instance ID'),\n\n /** Flow reference */\n flowName: z.string().describe('Machine name of the executed flow'),\n flowVersion: z.number().int().optional().describe('Version of the flow that was executed'),\n\n /** Execution status */\n status: ExecutionStatus.describe('Current execution status'),\n\n /** Trigger context */\n trigger: z.object({\n type: z.string().describe('Trigger type (e.g., \"record_change\", \"schedule\", \"api\", \"manual\")'),\n recordId: z.string().optional().describe('Triggering record ID'),\n object: z.string().optional().describe('Triggering object name'),\n userId: z.string().optional().describe('User who triggered the execution'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional trigger context'),\n }).describe('What triggered this execution'),\n\n /** Step-by-step execution history */\n steps: z.array(ExecutionStepLogSchema).describe('Ordered list of executed steps'),\n\n /** Execution variables snapshot */\n variables: z.record(z.string(), z.unknown()).optional().describe('Final state of flow variables'),\n\n /** Timing */\n startedAt: z.string().datetime().describe('Execution start timestamp'),\n completedAt: z.string().datetime().optional().describe('Execution completion timestamp'),\n durationMs: z.number().int().min(0).optional().describe('Total execution duration in milliseconds'),\n\n /** Context */\n runAs: z.enum(['system', 'user']).optional().describe('Execution context identity'),\n tenantId: z.string().optional().describe('Tenant ID for multi-tenant isolation'),\n});\nexport type ExecutionLog = z.infer;\n\n// ==========================================\n// 3. Execution Error Tracking & Diagnostics\n// ==========================================\n\n/**\n * Execution Error Severity\n */\nexport const ExecutionErrorSeverity = z.enum([\n 'warning', // Non-fatal issue (e.g., deprecated node type)\n 'error', // Node-level failure (may be retried)\n 'critical', // Flow-level failure (execution terminated)\n]);\nexport type ExecutionErrorSeverity = z.infer;\n\n/**\n * Execution Error Schema\n * Detailed error record for diagnostics and troubleshooting.\n */\nexport const ExecutionErrorSchema = z.object({\n id: z.string().describe('Error record ID'),\n executionId: z.string().describe('Parent execution ID'),\n nodeId: z.string().optional().describe('Node where the error occurred'),\n severity: ExecutionErrorSeverity.describe('Error severity level'),\n code: z.string().describe('Machine-readable error code'),\n message: z.string().describe('Human-readable error message'),\n stack: z.string().optional().describe('Stack trace for debugging'),\n context: z.record(z.string(), z.unknown()).optional()\n .describe('Additional diagnostic context (input data, config snapshot)'),\n timestamp: z.string().datetime().describe('When the error occurred'),\n retryable: z.boolean().default(false).describe('Whether this error can be retried'),\n resolvedAt: z.string().datetime().optional().describe('When the error was resolved (e.g., after successful retry)'),\n});\nexport type ExecutionError = z.infer;\n\n// ==========================================\n// 4. Checkpointing / Resume\n// ==========================================\n\n/**\n * Checkpoint Schema\n * Captures the execution state at a specific node for pause/resume.\n *\n * Used by wait nodes, user-input screens, and crash recovery.\n */\nexport const CheckpointSchema = z.object({\n /** Unique checkpoint ID */\n id: z.string().describe('Checkpoint ID'),\n\n /** Execution reference */\n executionId: z.string().describe('Parent execution ID'),\n flowName: z.string().describe('Flow machine name'),\n\n /** State snapshot */\n currentNodeId: z.string().describe('Node ID where execution is paused'),\n variables: z.record(z.string(), z.unknown()).describe('Flow variable state at checkpoint'),\n completedNodeIds: z.array(z.string()).describe('List of node IDs already executed'),\n\n /** Timing */\n createdAt: z.string().datetime().describe('Checkpoint creation timestamp'),\n expiresAt: z.string().datetime().optional().describe('Checkpoint expiration (auto-cleanup)'),\n\n /** Reason */\n reason: z.enum(['wait', 'screen_input', 'approval', 'error', 'manual_pause', 'parallel_join', 'boundary_event'])\n .describe('Why the execution was checkpointed'),\n});\nexport type Checkpoint = z.infer;\n\n// ==========================================\n// 5. Concurrency Control\n// ==========================================\n\n/**\n * Concurrency Policy Schema\n * Controls how concurrent executions of the same flow are handled.\n *\n * Industry alignment: Salesforce \"Allow multiple instances\", Temporal \"Workflow ID reuse policy\"\n */\nexport const ConcurrencyPolicySchema = z.object({\n /** Maximum concurrent executions of this flow */\n maxConcurrent: z.number().int().min(1).default(1)\n .describe('Maximum number of concurrent executions allowed'),\n\n /** What to do when max concurrency is reached */\n onConflict: z.enum(['queue', 'reject', 'cancel_existing'])\n .default('queue')\n .describe('queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance'),\n\n /** Lock scope for concurrency */\n lockScope: z.enum(['global', 'per_record', 'per_user'])\n .default('global')\n .describe('Scope of the concurrency lock'),\n\n /** Queue timeout (only when onConflict is \"queue\") */\n queueTimeoutMs: z.number().int().min(0).optional()\n .describe('Maximum time to wait in queue before timing out (ms)'),\n});\nexport type ConcurrencyPolicy = z.infer;\n\n// ==========================================\n// 6. Scheduled Execution Persistence\n// ==========================================\n\n/**\n * Schedule State Schema\n * Tracks the runtime state of scheduled flow executions.\n *\n * Persists next-run times, pause/resume state, and execution history references.\n */\nexport const ScheduleStateSchema = z.object({\n /** Unique schedule ID */\n id: z.string().describe('Schedule instance ID'),\n\n /** Flow reference */\n flowName: z.string().describe('Flow machine name'),\n\n /** Schedule configuration */\n cronExpression: z.string().describe('Cron expression (e.g., \"0 9 * * MON-FRI\")'),\n timezone: z.string().default('UTC').describe('IANA timezone for cron evaluation'),\n\n /** Runtime state */\n status: z.enum(['active', 'paused', 'disabled', 'expired'])\n .default('active')\n .describe('Current schedule status'),\n nextRunAt: z.string().datetime().optional().describe('Next scheduled execution timestamp'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n lastExecutionId: z.string().optional().describe('Execution ID of the last run'),\n lastRunStatus: ExecutionStatus.optional().describe('Status of the last run'),\n\n /** Execution tracking */\n totalRuns: z.number().int().min(0).default(0).describe('Total number of executions'),\n consecutiveFailures: z.number().int().min(0).default(0).describe('Consecutive failed executions'),\n\n /** Bounds */\n startDate: z.string().datetime().optional().describe('Schedule effective start date'),\n endDate: z.string().datetime().optional().describe('Schedule expiration date'),\n maxRuns: z.number().int().min(1).optional().describe('Maximum total executions before auto-disable'),\n\n /** Metadata */\n createdAt: z.string().datetime().describe('Schedule creation timestamp'),\n updatedAt: z.string().datetime().optional().describe('Last update timestamp'),\n createdBy: z.string().optional().describe('User who created the schedule'),\n});\nexport type ScheduleState = z.infer;\n\n// ==========================================\n// Type Exports\n// ==========================================\n\nexport type ExecutionStepLogParsed = z.infer;\nexport type ExecutionLogParsed = z.infer;\nexport type ExecutionErrorParsed = z.infer;\nexport type CheckpointParsed = z.infer;\nexport type ConcurrencyPolicyParsed = z.infer;\nexport type ScheduleStateParsed = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { FlowSchema } from '../automation/flow.zod';\nimport { ExecutionLogSchema } from '../automation/execution.zod';\n\n/**\n * Automation API Protocol\n *\n * Defines REST CRUD endpoint schemas for managing automation flows,\n * triggering executions, and querying execution history.\n *\n * Base path: /api/automation\n *\n * @example Endpoints\n * GET /api/automation — List flows\n * GET /api/automation/:name — Get flow\n * POST /api/automation — Create flow\n * PUT /api/automation/:name — Update flow\n * DELETE /api/automation/:name — Delete flow\n * POST /api/automation/:name/trigger — Trigger flow execution\n * POST /api/automation/:name/toggle — Enable/disable flow\n * GET /api/automation/:name/runs — List execution runs\n * GET /api/automation/:name/runs/:runId — Get single execution run\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Path parameters for flow-level operations.\n */\nexport const AutomationFlowPathParamsSchema = z.object({\n name: z.string().describe('Flow machine name (snake_case)'),\n});\nexport type AutomationFlowPathParams = z.infer;\n\n/**\n * Path parameters for run-level operations.\n */\nexport const AutomationRunPathParamsSchema = AutomationFlowPathParamsSchema.extend({\n runId: z.string().describe('Execution run ID'),\n});\nexport type AutomationRunPathParams = z.infer;\n\n// ==========================================\n// 2. List Flows (GET /api/automation)\n// ==========================================\n\n/**\n * Query parameters for listing automation flows.\n *\n * @example GET /api/automation?status=active&limit=20\n */\nexport const ListFlowsRequestSchema = z.object({\n status: z.enum(['draft', 'active', 'obsolete', 'invalid']).optional()\n .describe('Filter by flow status'),\n type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).optional()\n .describe('Filter by flow type'),\n limit: z.number().int().min(1).max(100).default(50)\n .describe('Maximum number of flows to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type ListFlowsRequest = z.infer;\n\n/**\n * Summary information for a flow in list results.\n */\nexport const FlowSummarySchema = z.object({\n name: z.string().describe('Flow machine name'),\n label: z.string().describe('Flow display label'),\n type: z.string().describe('Flow type'),\n status: z.string().describe('Flow deployment status'),\n version: z.number().int().describe('Flow version number'),\n enabled: z.boolean().describe('Whether the flow is enabled for execution'),\n nodeCount: z.number().int().optional().describe('Number of nodes in the flow'),\n lastRunAt: z.string().datetime().optional().describe('Last execution timestamp'),\n});\nexport type FlowSummary = z.infer;\n\n/**\n * Response for the list flows endpoint.\n */\nexport const ListFlowsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n flows: z.array(FlowSummarySchema).describe('Flow summaries'),\n total: z.number().int().optional().describe('Total matching flows'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more flows are available'),\n }),\n});\nexport type ListFlowsResponse = z.infer;\n\n// ==========================================\n// 3. Get Flow (GET /api/automation/:name)\n// ==========================================\n\n/**\n * Request parameters for getting a single flow.\n */\nexport const GetFlowRequestSchema = AutomationFlowPathParamsSchema;\nexport type GetFlowRequest = z.infer;\n\n/**\n * Response for the get flow endpoint.\n */\nexport const GetFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('Full flow definition'),\n});\nexport type GetFlowResponse = z.infer;\n\n// ==========================================\n// 4. Create Flow (POST /api/automation)\n// ==========================================\n\n/**\n * Request body for creating a new flow.\n *\n * @example POST /api/automation\n * { name: 'approval_flow', label: 'Approval Flow', type: 'autolaunched', ... }\n */\nexport const CreateFlowRequestSchema = FlowSchema;\nexport type CreateFlowRequest = z.input;\n\n/**\n * Response after creating a flow.\n */\nexport const CreateFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('The created flow definition'),\n});\nexport type CreateFlowResponse = z.infer;\n\n// ==========================================\n// 5. Update Flow (PUT /api/automation/:name)\n// ==========================================\n\n/**\n * Request body for updating an existing flow.\n *\n * @example PUT /api/automation/approval_flow\n * { label: 'Updated Label', nodes: [...], edges: [...] }\n */\nexport const UpdateFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n definition: FlowSchema.partial().describe('Partial flow definition to update'),\n});\nexport type UpdateFlowRequest = z.infer;\n\n/**\n * Response after updating a flow.\n */\nexport const UpdateFlowResponseSchema = BaseResponseSchema.extend({\n data: FlowSchema.describe('The updated flow definition'),\n});\nexport type UpdateFlowResponse = z.infer;\n\n// ==========================================\n// 6. Delete Flow (DELETE /api/automation/:name)\n// ==========================================\n\n/**\n * Request parameters for deleting a flow.\n */\nexport const DeleteFlowRequestSchema = AutomationFlowPathParamsSchema;\nexport type DeleteFlowRequest = z.infer;\n\n/**\n * Response after deleting a flow.\n */\nexport const DeleteFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n name: z.string().describe('Name of the deleted flow'),\n deleted: z.boolean().describe('Whether the flow was deleted'),\n }),\n});\nexport type DeleteFlowResponse = z.infer;\n\n// ==========================================\n// 7. Trigger Flow (POST /api/automation/:name/trigger)\n// ==========================================\n\n/**\n * Request body for triggering a flow execution.\n *\n * @example POST /api/automation/approval_flow/trigger\n * { record: { id: 'rec-1' }, object: 'account', event: 'on_create' }\n */\nexport const TriggerFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n record: z.record(z.string(), z.unknown()).optional()\n .describe('Record that triggered the automation'),\n object: z.string().optional()\n .describe('Object name the record belongs to'),\n event: z.string().optional()\n .describe('Trigger event type'),\n userId: z.string().optional()\n .describe('User who triggered the automation'),\n params: z.record(z.string(), z.unknown()).optional()\n .describe('Additional contextual data'),\n});\nexport type TriggerFlowRequest = z.infer;\n\n/**\n * Response after triggering a flow execution.\n */\nexport const TriggerFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the automation completed successfully'),\n output: z.unknown().optional().describe('Output data from the automation'),\n error: z.string().optional().describe('Error message if execution failed'),\n durationMs: z.number().optional().describe('Execution duration in milliseconds'),\n }),\n});\nexport type TriggerFlowResponse = z.infer;\n\n// ==========================================\n// 8. Toggle Flow (POST /api/automation/:name/toggle)\n// ==========================================\n\n/**\n * Request body for enabling/disabling a flow.\n *\n * @example POST /api/automation/approval_flow/toggle\n * { enabled: true }\n */\nexport const ToggleFlowRequestSchema = AutomationFlowPathParamsSchema.extend({\n enabled: z.boolean().describe('Whether to enable (true) or disable (false) the flow'),\n});\nexport type ToggleFlowRequest = z.infer;\n\n/**\n * Response after toggling a flow.\n */\nexport const ToggleFlowResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n name: z.string().describe('Flow name'),\n enabled: z.boolean().describe('New enabled state'),\n }),\n});\nexport type ToggleFlowResponse = z.infer;\n\n// ==========================================\n// 9. List Runs (GET /api/automation/:name/runs)\n// ==========================================\n\n/**\n * Query parameters for listing execution runs.\n *\n * @example GET /api/automation/approval_flow/runs?status=completed&limit=10\n */\nexport const ListRunsRequestSchema = AutomationFlowPathParamsSchema.extend({\n status: z.enum(['pending', 'running', 'paused', 'completed', 'failed', 'cancelled', 'timed_out', 'retrying']).optional()\n .describe('Filter by execution status'),\n limit: z.number().int().min(1).max(100).default(20)\n .describe('Maximum number of runs to return'),\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n});\nexport type ListRunsRequest = z.infer;\n\n/**\n * Response for the list runs endpoint.\n */\nexport const ListRunsResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n runs: z.array(ExecutionLogSchema).describe('Execution run logs'),\n total: z.number().int().optional().describe('Total matching runs'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more runs are available'),\n }),\n});\nexport type ListRunsResponse = z.infer;\n\n// ==========================================\n// 10. Get Run (GET /api/automation/:name/runs/:runId)\n// ==========================================\n\n/**\n * Request parameters for getting a single execution run.\n */\nexport const GetRunRequestSchema = AutomationRunPathParamsSchema;\nexport type GetRunRequest = z.infer;\n\n/**\n * Response for the get run endpoint.\n */\nexport const GetRunResponseSchema = BaseResponseSchema.extend({\n data: ExecutionLogSchema.describe('Full execution log with step details'),\n});\nexport type GetRunResponse = z.infer;\n\n// ==========================================\n// 11. Automation API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Automation operations.\n */\nexport const AutomationApiErrorCode = z.enum([\n 'flow_not_found',\n 'flow_already_exists',\n 'flow_validation_failed',\n 'flow_disabled',\n 'execution_not_found',\n 'execution_failed',\n 'execution_timeout',\n 'node_executor_not_found',\n 'concurrent_execution_limit',\n]);\nexport type AutomationApiErrorCode = z.infer;\n\n// ==========================================\n// 12. Automation API Contract Registry\n// ==========================================\n\n/**\n * Standard Automation API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const AutomationApiContracts = {\n listFlows: {\n method: 'GET' as const,\n path: '/api/automation',\n input: ListFlowsRequestSchema,\n output: ListFlowsResponseSchema,\n },\n getFlow: {\n method: 'GET' as const,\n path: '/api/automation/:name',\n input: GetFlowRequestSchema,\n output: GetFlowResponseSchema,\n },\n createFlow: {\n method: 'POST' as const,\n path: '/api/automation',\n input: CreateFlowRequestSchema,\n output: CreateFlowResponseSchema,\n },\n updateFlow: {\n method: 'PUT' as const,\n path: '/api/automation/:name',\n input: UpdateFlowRequestSchema,\n output: UpdateFlowResponseSchema,\n },\n deleteFlow: {\n method: 'DELETE' as const,\n path: '/api/automation/:name',\n input: DeleteFlowRequestSchema,\n output: DeleteFlowResponseSchema,\n },\n triggerFlow: {\n method: 'POST' as const,\n path: '/api/automation/:name/trigger',\n input: TriggerFlowRequestSchema,\n output: TriggerFlowResponseSchema,\n },\n toggleFlow: {\n method: 'POST' as const,\n path: '/api/automation/:name/toggle',\n input: ToggleFlowRequestSchema,\n output: ToggleFlowResponseSchema,\n },\n listRuns: {\n method: 'GET' as const,\n path: '/api/automation/:name/runs',\n input: ListRunsRequestSchema,\n output: ListRunsResponseSchema,\n },\n getRun: {\n method: 'GET' as const,\n path: '/api/automation/:name/runs/:runId',\n input: GetRunRequestSchema,\n output: GetRunResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { BaseResponseSchema } from './contract.zod';\nimport { InstalledPackageSchema } from '../kernel/package-registry.zod';\nimport { DependencyResolutionResultSchema } from '../kernel/dependency-resolution.zod';\nimport { UpgradePlanSchema } from '../kernel/package-upgrade.zod';\nimport { PackageArtifactSchema } from '../kernel/package-artifact.zod';\nimport { ManifestSchema } from '../kernel/manifest.zod';\nimport { ArtifactReferenceSchema } from '../cloud/marketplace.zod';\n\n/**\n * # Package API Protocol\n *\n * REST API endpoint schemas for package lifecycle management.\n *\n * Base path: /api/v1/packages\n *\n * @example Endpoints\n * POST /api/v1/packages/install — Install a package\n * POST /api/v1/packages/upgrade — Upgrade a package\n * POST /api/v1/packages/resolve-dependencies — Resolve dependencies\n * POST /api/v1/packages/upload — Upload an artifact\n * GET /api/v1/packages — List installed packages\n * GET /api/v1/packages/:packageId — Get package details\n * POST /api/v1/packages/:packageId/rollback — Rollback a package\n * DELETE /api/v1/packages/:packageId — Uninstall a package\n */\n\n// ==========================================\n// 1. Path Parameters\n// ==========================================\n\n/**\n * Path parameters for package-level operations.\n */\nexport const PackagePathParamsSchema = z.object({\n packageId: z.string().describe('Package identifier'),\n});\nexport type PackagePathParams = z.infer;\n\n// ==========================================\n// 2. List Packages (GET /api/v1/packages)\n// ==========================================\n\n/**\n * Query parameters for listing installed packages.\n */\nexport const ListInstalledPackagesRequestSchema = z.object({\n /** Filter by package status */\n status: z.enum(['installed', 'disabled', 'installing', 'upgrading', 'uninstalling', 'error']).optional()\n .describe('Filter by package status'),\n /** Filter by enabled state */\n enabled: z.boolean().optional()\n .describe('Filter by enabled state'),\n /** Maximum number of packages to return */\n limit: z.number().int().min(1).max(100).default(50)\n .describe('Maximum number of packages to return'),\n /** Cursor for pagination */\n cursor: z.string().optional()\n .describe('Cursor for pagination'),\n}).describe('List installed packages request');\nexport type ListInstalledPackagesRequest = z.infer;\n\n/**\n * Response for listing installed packages.\n */\nexport const ListInstalledPackagesResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n packages: z.array(InstalledPackageSchema).describe('Installed packages'),\n total: z.number().int().optional().describe('Total matching packages'),\n nextCursor: z.string().optional().describe('Cursor for the next page'),\n hasMore: z.boolean().describe('Whether more packages are available'),\n }),\n}).describe('List installed packages response');\nexport type ListInstalledPackagesResponse = z.infer;\n\n// ==========================================\n// 3. Get Package (GET /api/v1/packages/:packageId)\n// ==========================================\n\n/**\n * Request for getting a single installed package.\n */\nexport const GetInstalledPackageRequestSchema = PackagePathParamsSchema;\nexport type GetInstalledPackageRequest = z.infer;\n\n/**\n * Response for getting a single installed package.\n */\nexport const GetInstalledPackageResponseSchema = BaseResponseSchema.extend({\n data: InstalledPackageSchema.describe('Installed package details'),\n}).describe('Get installed package response');\nexport type GetInstalledPackageResponse = z.infer;\n\n// ==========================================\n// 4. Install Package (POST /api/v1/packages/install)\n// ==========================================\n\n/**\n * Request body for installing a package.\n *\n * @example POST /api/v1/packages/install\n * { manifest: {...}, platformVersion: '3.2.0', enableOnInstall: true }\n */\nexport const PackageInstallRequestSchema = z.object({\n /** Package manifest to install */\n manifest: ManifestSchema.describe('Package manifest to install'),\n\n /** User-provided settings at install time */\n settings: z.record(z.string(), z.unknown()).optional()\n .describe('User-provided settings at install time'),\n\n /** Whether to enable immediately after install */\n enableOnInstall: z.boolean().default(true)\n .describe('Whether to enable immediately after install'),\n\n /** Current platform version for compatibility verification */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility verification'),\n\n /** Artifact reference for the package (if installing from marketplace) */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference for marketplace installation'),\n}).describe('Install package request');\nexport type PackageInstallRequest = z.infer;\n\n/**\n * Response after installing a package.\n */\nexport const PackageInstallResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n package: InstalledPackageSchema.describe('Installed package details'),\n dependencyResolution: DependencyResolutionResultSchema.optional()\n .describe('Dependency resolution result'),\n namespaceConflicts: z.array(z.object({\n type: z.literal('namespace_conflict').describe('Error type'),\n requestedNamespace: z.string().describe('Requested namespace'),\n conflictingPackageId: z.string().describe('Conflicting package ID'),\n conflictingPackageName: z.string().describe('Conflicting package name'),\n suggestion: z.string().optional().describe('Suggested alternative'),\n })).optional().describe('Namespace conflicts detected'),\n message: z.string().optional().describe('Installation status message'),\n }),\n}).describe('Install package response');\nexport type PackageInstallResponse = z.infer;\n\n// ==========================================\n// 5. Upgrade Package (POST /api/v1/packages/upgrade)\n// ==========================================\n\n/**\n * Request body for upgrading a package.\n *\n * @example POST /api/v1/packages/upgrade\n * { packageId: 'com.acme.crm', targetVersion: '2.0.0', createSnapshot: true }\n */\nexport const PackageUpgradeRequestSchema = z.object({\n /** Package ID to upgrade */\n packageId: z.string().describe('Package ID to upgrade'),\n\n /** Target version (defaults to latest) */\n targetVersion: z.string().optional()\n .describe('Target version (defaults to latest)'),\n\n /** New manifest for the target version */\n manifest: ManifestSchema.optional()\n .describe('New manifest for the target version'),\n\n /** Whether to create a pre-upgrade snapshot */\n createSnapshot: z.boolean().default(true)\n .describe('Whether to create a pre-upgrade backup snapshot'),\n\n /** Merge strategy for handling customizations */\n mergeStrategy: z.enum(['keep-custom', 'accept-incoming', 'three-way-merge'])\n .default('three-way-merge')\n .describe('How to handle customer customizations'),\n\n /** Preview upgrade without making changes */\n dryRun: z.boolean().default(false)\n .describe('Preview upgrade without making changes'),\n\n /** Skip pre-upgrade compatibility checks */\n skipValidation: z.boolean().default(false)\n .describe('Skip pre-upgrade compatibility checks'),\n}).describe('Upgrade package request');\nexport type PackageUpgradeRequest = z.infer;\n\n/**\n * Response after upgrading a package.\n */\nexport const PackageUpgradeResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the upgrade succeeded'),\n phase: z.string().describe('Current upgrade phase'),\n plan: UpgradePlanSchema.optional().describe('Upgrade plan that was executed'),\n snapshotId: z.string().optional().describe('Snapshot ID for rollback'),\n conflicts: z.array(z.object({\n path: z.string().describe('Conflict path'),\n baseValue: z.unknown().describe('Base value'),\n incomingValue: z.unknown().describe('Incoming value'),\n customValue: z.unknown().describe('Custom value'),\n })).optional().describe('Unresolved merge conflicts'),\n errorMessage: z.string().optional().describe('Error message if failed'),\n message: z.string().optional().describe('Human-readable status message'),\n }),\n}).describe('Upgrade package response');\nexport type PackageUpgradeResponse = z.infer;\n\n// ==========================================\n// 6. Resolve Dependencies (POST /api/v1/packages/resolve-dependencies)\n// ==========================================\n\n/**\n * Request body for resolving package dependencies.\n *\n * @example POST /api/v1/packages/resolve-dependencies\n * { manifest: {...}, platformVersion: '3.2.0' }\n */\nexport const ResolveDependenciesRequestSchema = z.object({\n /** Package manifest whose dependencies to resolve */\n manifest: ManifestSchema.describe('Package manifest to resolve dependencies for'),\n\n /** Current platform version for compatibility checking */\n platformVersion: z.string().optional()\n .describe('Current platform version for compatibility filtering'),\n}).describe('Resolve dependencies request');\nexport type ResolveDependenciesRequest = z.infer;\n\n/**\n * Response with dependency resolution results.\n */\nexport const ResolveDependenciesResponseSchema = BaseResponseSchema.extend({\n data: DependencyResolutionResultSchema.describe('Dependency resolution result with topological sort'),\n}).describe('Resolve dependencies response');\nexport type ResolveDependenciesResponse = z.infer;\n\n// ==========================================\n// 7. Upload Artifact (POST /api/v1/packages/upload)\n// ==========================================\n\n/**\n * Request body for uploading a package artifact.\n *\n * @example POST /api/v1/packages/upload\n * Content-Type: multipart/form-data\n * { artifact: , file: }\n */\nexport const UploadArtifactRequestSchema = z.object({\n /** Artifact metadata */\n artifact: PackageArtifactSchema.describe('Package artifact metadata'),\n\n /** SHA256 checksum of the uploaded file (for verification) */\n sha256: z.string().regex(/^[a-f0-9]{64}$/).optional()\n .describe('SHA256 checksum of the uploaded file'),\n\n /** Publisher authentication token */\n token: z.string().optional()\n .describe('Publisher authentication token'),\n\n /** Release notes for this version */\n releaseNotes: z.string().optional()\n .describe('Release notes for this version'),\n}).describe('Upload artifact request');\nexport type UploadArtifactRequest = z.infer;\n\n/**\n * Response after uploading a package artifact.\n */\nexport const UploadArtifactResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n /** Whether the upload succeeded */\n success: z.boolean().describe('Whether the upload succeeded'),\n /** Artifact reference for the uploaded package */\n artifactRef: ArtifactReferenceSchema.optional()\n .describe('Artifact reference in the registry'),\n /** Submission ID for review tracking */\n submissionId: z.string().optional()\n .describe('Marketplace submission ID for review tracking'),\n /** Message */\n message: z.string().optional().describe('Upload status message'),\n }),\n}).describe('Upload artifact response');\nexport type UploadArtifactResponse = z.infer;\n\n// ==========================================\n// 8. Rollback Package (POST /api/v1/packages/:packageId/rollback)\n// ==========================================\n\n/**\n * Request body for rolling back a package upgrade.\n */\nexport const PackageRollbackRequestSchema = PackagePathParamsSchema.extend({\n /** Snapshot ID to restore from */\n snapshotId: z.string().describe('Snapshot ID to restore from'),\n\n /** Whether to also rollback customizations */\n rollbackCustomizations: z.boolean().default(true)\n .describe('Whether to restore pre-upgrade customizations'),\n}).describe('Rollback package request');\nexport type PackageRollbackRequest = z.infer;\n\n/**\n * Response after rolling back a package.\n */\nexport const PackageRollbackResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n success: z.boolean().describe('Whether the rollback succeeded'),\n restoredVersion: z.string().optional().describe('Restored version'),\n message: z.string().optional().describe('Rollback status message'),\n }),\n}).describe('Rollback package response');\nexport type PackageRollbackResponse = z.infer;\n\n// ==========================================\n// 9. Uninstall Package (DELETE /api/v1/packages/:packageId)\n// ==========================================\n\n/**\n * Request for uninstalling a package.\n */\nexport const UninstallPackageApiRequestSchema = PackagePathParamsSchema;\nexport type UninstallPackageApiRequest = z.infer;\n\n/**\n * Response after uninstalling a package.\n */\nexport const UninstallPackageApiResponseSchema = BaseResponseSchema.extend({\n data: z.object({\n packageId: z.string().describe('Uninstalled package ID'),\n success: z.boolean().describe('Whether uninstall succeeded'),\n message: z.string().optional().describe('Uninstall status message'),\n }),\n}).describe('Uninstall package response');\nexport type UninstallPackageApiResponse = z.infer;\n\n// ==========================================\n// 10. Package API Error Codes\n// ==========================================\n\n/**\n * Error codes specific to Package operations.\n */\nexport const PackageApiErrorCode = z.enum([\n 'package_not_found',\n 'package_already_installed',\n 'version_not_found',\n 'dependency_conflict',\n 'namespace_conflict',\n 'platform_incompatible',\n 'artifact_invalid',\n 'checksum_mismatch',\n 'signature_invalid',\n 'upgrade_failed',\n 'rollback_failed',\n 'snapshot_not_found',\n 'upload_failed',\n]);\nexport type PackageApiErrorCode = z.infer;\n\n// ==========================================\n// 11. Package API Contract Registry\n// ==========================================\n\n/**\n * Standard Package API contracts map.\n * Used for generating SDKs, documentation, and route registration.\n */\nexport const PackageApiContracts = {\n listPackages: {\n method: 'GET' as const,\n path: '/api/v1/packages',\n input: ListInstalledPackagesRequestSchema,\n output: ListInstalledPackagesResponseSchema,\n },\n getPackage: {\n method: 'GET' as const,\n path: '/api/v1/packages/:packageId',\n input: GetInstalledPackageRequestSchema,\n output: GetInstalledPackageResponseSchema,\n },\n installPackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/install',\n input: PackageInstallRequestSchema,\n output: PackageInstallResponseSchema,\n },\n upgradePackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/upgrade',\n input: PackageUpgradeRequestSchema,\n output: PackageUpgradeResponseSchema,\n },\n resolveDependencies: {\n method: 'POST' as const,\n path: '/api/v1/packages/resolve-dependencies',\n input: ResolveDependenciesRequestSchema,\n output: ResolveDependenciesResponseSchema,\n },\n uploadArtifact: {\n method: 'POST' as const,\n path: '/api/v1/packages/upload',\n input: UploadArtifactRequestSchema,\n output: UploadArtifactResponseSchema,\n },\n rollbackPackage: {\n method: 'POST' as const,\n path: '/api/v1/packages/:packageId/rollback',\n input: PackageRollbackRequestSchema,\n output: PackageRollbackResponseSchema,\n },\n uninstallPackage: {\n method: 'DELETE' as const,\n path: '/api/v1/packages/:packageId',\n input: UninstallPackageApiRequestSchema,\n output: UninstallPackageApiResponseSchema,\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n\nexport * from './workflow.zod';\nexport * from './flow.zod';\nexport * from './execution.zod';\nexport * from './webhook.zod';\nexport * from './approval.zod';\nexport * from './etl.zod';\nexport * from './trigger-registry.zod';\nexport * from './sync.zod';\nexport * from './state-machine.zod';\nexport * from './node-executor.zod';\nexport * from './bpmn-interop.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Webhook Trigger Event\n * When should this webhook fire?\n */\nexport const WebhookTriggerType = z.enum([\n 'create', \n 'update', \n 'delete', \n 'undelete',\n 'api' // Manually triggered\n]);\n\n/**\n * CANONICAL WEBHOOK DEFINITION\n * \n * This is the single source of truth for webhook configuration across ObjectStack.\n * All other protocols (workflow, connector, etc.) should import and reference this schema.\n * \n * Webhook Protocol - Outbound HTTP Integration\n * Push data to external URLs when events occur in the system.\n * \n * **NAMING CONVENTION:**\n * Webhook names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good webhook names\n * - 'stripe_payment_sync'\n * - 'slack_notification'\n * - 'crm_lead_export'\n * \n * @example Bad webhook names (will be rejected)\n * - 'StripePaymentSync' (PascalCase)\n * - 'slackNotification' (camelCase)\n * \n * @example Basic webhook configuration\n * ```typescript\n * const webhook: Webhook = {\n * name: 'slack_notification',\n * label: 'Slack Order Notification',\n * object: 'order',\n * triggers: ['create', 'update'],\n * url: 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX',\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * authentication: {\n * type: 'bearer',\n * credentials: { token: process.env.SLACK_TOKEN }\n * },\n * retryPolicy: {\n * maxRetries: 3,\n * backoffStrategy: 'exponential'\n * }\n * }\n * ```\n */\nexport const WebhookSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Webhook unique name (lowercase snake_case)'),\n label: z.string().optional().describe('Human-readable webhook label'),\n \n /** Scope */\n object: z.string().optional().describe('Object to listen to (optional for manual webhooks)'),\n triggers: z.array(WebhookTriggerType).optional().describe('Events that trigger execution'),\n \n /** Target */\n url: z.string().url().describe('External webhook endpoint URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).default('POST').describe('HTTP method'),\n \n /** Headers */\n headers: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers'),\n \n /** Body/Payload */\n body: z.unknown().optional().describe('Request body payload (if not using default record data)'),\n \n /** Payload Configuration */\n payloadFields: z.array(z.string()).optional().describe('Fields to include. Empty = All'),\n includeSession: z.boolean().default(false).describe('Include user session info'),\n \n /** Authentication */\n authentication: z.object({\n type: z.enum(['none', 'bearer', 'basic', 'api-key']).describe('Authentication type'),\n credentials: z.record(z.string(), z.string()).optional().describe('Authentication credentials'),\n }).optional().describe('Authentication configuration'),\n \n /** Retry Policy */\n retryPolicy: z.object({\n maxRetries: z.number().int().min(0).max(10).default(3).describe('Maximum retry attempts'),\n backoffStrategy: z.enum(['exponential', 'linear', 'fixed']).default('exponential').describe('Backoff strategy'),\n initialDelayMs: z.number().int().min(100).default(1000).describe('Initial retry delay in milliseconds'),\n maxDelayMs: z.number().int().min(1000).default(60000).describe('Maximum retry delay in milliseconds'),\n }).optional().describe('Retry policy configuration'),\n \n /** Timeout */\n timeoutMs: z.number().int().min(1000).max(300000).default(30000).describe('Request timeout in milliseconds'),\n \n /** Security */\n secret: z.string().optional().describe('Signing secret for HMAC signature verification'),\n \n /** Status */\n isActive: z.boolean().default(true).describe('Whether webhook is active'),\n \n /** Metadata */\n description: z.string().optional().describe('Webhook description'),\n tags: z.array(z.string()).optional().describe('Tags for organization'),\n});\n\n/**\n * Webhook Receiver Schema (Inbound)\n * Handling incoming HTTP hooks from Stripe, Slack, etc.\n * \n * **NAMING CONVENTION:**\n * Webhook receiver names are machine identifiers and must be lowercase snake_case.\n * \n * @example Good names\n * - 'stripe_webhook_handler'\n * - 'github_events'\n * - 'twilio_status_callback'\n * \n * @example Bad names (will be rejected)\n * - 'StripeWebhookHandler' (PascalCase)\n */\nexport const WebhookReceiverSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Webhook receiver unique name (lowercase snake_case)'),\n path: z.string().describe('URL Path (e.g. /webhooks/stripe)'),\n \n /** Verification */\n verificationType: z.enum(['none', 'header_token', 'hmac', 'ip_whitelist']).default('none'),\n verificationParams: z.object({\n header: z.string().optional(),\n secret: z.string().optional(),\n ips: z.array(z.string()).optional()\n }).optional(),\n \n /** Action */\n action: z.enum(['trigger_flow', 'script', 'upsert_record']).default('trigger_flow'),\n target: z.string().describe('Flow ID or Script name'),\n});\n\nexport type Webhook = z.infer;\nexport type WebhookReceiver = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';\n\n/**\n * Approval Step Approver Type\n */\nexport const ApproverType = z.enum([\n 'user', // Specific user(s)\n 'role', // Users with specific role\n 'manager', // Submitter's manager\n 'field', // User ID defined in a record field\n 'queue' // Data ownership queue\n]);\n\n/**\n * Approval Action Type\n * Actions to execute on transition\n */\nexport const ApprovalActionType = z.enum([\n 'field_update',\n 'email_alert',\n 'webhook',\n 'script',\n 'connector_action' // Added for Zapier-style integrations\n]);\n\n/**\n * definition of an action to perform\n */\nexport const ApprovalActionSchema = z.object({\n type: ApprovalActionType,\n name: z.string().describe('Action name'),\n config: z.record(z.string(), z.unknown()).describe('Action configuration'),\n \n /** For connector actions */\n connectorId: z.string().optional(),\n actionId: z.string().optional(),\n});\n\n/**\n * Approval Process Step\n */\nexport const ApprovalStepSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Step machine name'),\n label: z.string().describe('Step display label'),\n description: z.string().optional(),\n \n /** Entry criteria for this step */\n entryCriteria: z.string().optional().describe('Formula expression to enter this step'),\n \n /** Who can approve */\n approvers: z.array(z.object({\n type: ApproverType,\n value: z.string().describe('User ID, Role Name, or Field Name')\n })).min(1).describe('List of allowed approvers'),\n \n /** Approval Logic */\n behavior: z.enum(['first_response', 'unanimous']).default('first_response')\n .describe('How to handle multiple approvers'),\n \n /** Rejection behavior */\n rejectionBehavior: z.enum(['reject_process', 'back_to_previous'])\n .default('reject_process').describe('What happens if rejected'),\n\n /** Actions */\n onApprove: z.array(ApprovalActionSchema).optional().describe('Actions on step approval'),\n onReject: z.array(ApprovalActionSchema).optional().describe('Actions on step rejection'),\n});\n\n/**\n * Approval Process Protocol\n * \n * Defines a complex review and approval cycle for a record.\n * Manages state locking, notifications, and transition logic.\n */\nexport const ApprovalProcessSchema = z.object({\n name: SnakeCaseIdentifierSchema.describe('Unique process name'),\n label: z.string().describe('Human readable label'),\n object: z.string().describe('Target Object Name'),\n \n active: z.boolean().default(false),\n description: z.string().optional(),\n \n /** Entry Criteria for the entire process */\n entryCriteria: z.string().optional().describe('Formula to allow submission'),\n \n /** Record Locking */\n lockRecord: z.boolean().default(true).describe('Lock record from editing during approval'),\n \n /** Steps */\n steps: z.array(ApprovalStepSchema).min(1).describe('Sequence of approval steps'),\n\n /** Escalation Configuration (SLA-based auto-escalation) */\n escalation: z.object({\n enabled: z.boolean().default(false).describe('Enable SLA-based escalation'),\n timeoutHours: z.number().min(1).describe('Hours before escalation triggers'),\n action: z.enum(['reassign', 'auto_approve', 'auto_reject', 'notify']).default('notify').describe('Action to take on escalation timeout'),\n escalateTo: z.string().optional().describe('User ID, role, or manager level to escalate to'),\n notifySubmitter: z.boolean().default(true).describe('Notify the original submitter on escalation'),\n }).optional().describe('SLA escalation configuration for pending approval steps'),\n \n /** Global Actions */\n onSubmit: z.array(ApprovalActionSchema).optional().describe('Actions on initial submission'),\n onFinalApprove: z.array(ApprovalActionSchema).optional().describe('Actions on final approval'),\n onFinalReject: z.array(ApprovalActionSchema).optional().describe('Actions on final rejection'),\n onRecall: z.array(ApprovalActionSchema).optional().describe('Actions on recall'),\n});\n\nexport const ApprovalProcess = Object.assign(ApprovalProcessSchema, {\n create: >(config: T) => config,\n});\n\nexport type ApprovalProcess = z.infer;\nexport type ApprovalStep = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * ETL (Extract, Transform, Load) Pipeline Protocol - LEVEL 2: Data Engineering\n * \n * Inspired by modern data integration platforms like Airbyte, Fivetran, and Apache NiFi.\n * \n * **Positioning in 3-Layer Architecture:**\n * - **L1: Simple Sync** (automation/sync.zod.ts) - Business users - Sync Salesforce to Sheets\n * - **L2: ETL Pipeline** (THIS FILE) - Data engineers - Aggregate 10 sources to warehouse\n * - **L3: Enterprise Connector** (integration/connector.zod.ts) - System integrators - Full SAP integration\n * \n * ETL pipelines enable automated data synchronization between systems, transforming\n * data as it moves from source to destination.\n * \n * **SCOPE: Advanced multi-source, multi-stage transformations.**\n * Supports complex operations: joins, aggregations, filtering, custom SQL.\n * \n * ## When to Use This Layer\n * \n * **Use ETL Pipeline when:**\n * - Combining data from multiple sources\n * - Need aggregations, joins, transformations\n * - Building data warehouses or analytics platforms\n * - Complex data transformations required\n * \n * **Examples:**\n * - Sales data from Salesforce + Marketing from HubSpot → Data Warehouse\n * - Multi-region databases → Consolidated reporting\n * - Legacy system migration with transformation\n * \n * **When to downgrade:**\n * - Simple 1:1 sync → Use {@link file://./sync.zod.ts | Simple Sync}\n * \n * **When to upgrade:**\n * - Need full connector lifecycle (auth, webhooks, rate limits) → Use {@link file://../integration/connector.zod.ts | Enterprise Connector}\n * \n * @see {@link file://./sync.zod.ts} for Level 1 (simple sync)\n * @see {@link file://../integration/connector.zod.ts} for Level 3 (enterprise integration)\n * \n * ## Use Cases\n * \n * 1. **Data Warehouse Population**\n * - Extract from multiple operational systems\n * - Transform to analytical schema\n * - Load into data warehouse\n * \n * 2. **System Integration**\n * - Sync data between CRM and Marketing Automation\n * - Keep product catalog synchronized across e-commerce platforms\n * - Replicate data for backup/disaster recovery\n * \n * 3. **Data Migration**\n * - Move data from legacy systems to modern platforms\n * - Consolidate data from multiple sources\n * - Split monolithic databases into microservices\n * \n * @see https://airbyte.com/\n * @see https://docs.fivetran.com/\n * @see https://nifi.apache.org/\n * \n * @example\n * ```typescript\n * const salesforceToDB: ETLPipeline = {\n * name: 'salesforce_to_postgres',\n * label: 'Salesforce Accounts to PostgreSQL',\n * source: {\n * type: 'api',\n * connector: 'salesforce',\n * config: { object: 'Account' }\n * },\n * destination: {\n * type: 'database',\n * connector: 'postgres',\n * config: { table: 'accounts' }\n * },\n * transformations: [\n * { type: 'map', config: { 'Name': 'account_name' } }\n * ],\n * schedule: '0 2 * * *' // Daily at 2 AM\n * }\n * ```\n */\n\n/**\n * ETL Source/Destination Type\n */\nexport const ETLEndpointTypeSchema = z.enum([\n 'database', // SQL/NoSQL databases\n 'api', // REST/GraphQL APIs\n 'file', // CSV, JSON, XML, Excel files\n 'stream', // Kafka, RabbitMQ, Kinesis\n 'object', // ObjectStack object\n 'warehouse', // Data warehouse (Snowflake, BigQuery, Redshift)\n 'storage', // S3, Azure Blob, Google Cloud Storage\n 'spreadsheet', // Google Sheets, Excel Online\n]);\n\nexport type ETLEndpointType = z.infer;\n\n/**\n * ETL Source Configuration\n */\nexport const ETLSourceSchema = z.object({\n /**\n * Source type\n */\n type: ETLEndpointTypeSchema.describe('Source type'),\n\n /**\n * Connector identifier\n * References a registered connector\n * \n * @example \"salesforce\", \"postgres\", \"mysql\", \"s3\"\n */\n connector: z.string().optional().describe('Connector ID'),\n\n /**\n * Source-specific configuration\n * Structure varies by source type\n * \n * @example For database: { table: 'customers', schema: 'public' }\n * @example For API: { endpoint: '/api/users', method: 'GET' }\n * @example For file: { path: 's3://bucket/data.csv', format: 'csv' }\n */\n config: z.record(z.string(), z.unknown()).describe('Source configuration'),\n\n /**\n * Incremental sync configuration\n * Allows extracting only changed data\n */\n incremental: z.object({\n enabled: z.boolean().default(false),\n cursorField: z.string().describe('Field to track progress (e.g., updated_at)'),\n cursorValue: z.unknown().optional().describe('Last processed value'),\n }).optional().describe('Incremental extraction config'),\n});\n\nexport type ETLSource = z.infer;\n\n/**\n * ETL Destination Configuration\n */\nexport const ETLDestinationSchema = z.object({\n /**\n * Destination type\n */\n type: ETLEndpointTypeSchema.describe('Destination type'),\n\n /**\n * Connector identifier\n */\n connector: z.string().optional().describe('Connector ID'),\n\n /**\n * Destination-specific configuration\n */\n config: z.record(z.string(), z.unknown()).describe('Destination configuration'),\n\n /**\n * Write mode\n */\n writeMode: z.enum([\n 'append', // Add new records\n 'overwrite', // Replace all data\n 'upsert', // Insert or update based on key\n 'merge', // Smart merge based on business rules\n ]).default('append').describe('How to write data'),\n\n /**\n * Primary key fields for upsert/merge\n */\n primaryKey: z.array(z.string()).optional().describe('Primary key fields'),\n});\n\nexport type ETLDestination = z.infer;\n\n/**\n * ETL Transformation Type\n */\nexport const ETLTransformationTypeSchema = z.enum([\n 'map', // Field mapping/renaming\n 'filter', // Row filtering\n 'aggregate', // Aggregation/grouping\n 'join', // Joining with other data\n 'script', // Custom JavaScript/Python script\n 'lookup', // Enrich with lookup data\n 'split', // Split one record into multiple\n 'merge', // Merge multiple records into one\n 'normalize', // Data normalization\n 'deduplicate', // Remove duplicates\n]);\n\nexport type ETLTransformationType = z.infer;\n\n/**\n * ETL Transformation Configuration\n */\nexport const ETLTransformationSchema = z.object({\n /**\n * Transformation name\n */\n name: z.string().optional().describe('Transformation name'),\n\n /**\n * Transformation type\n */\n type: ETLTransformationTypeSchema.describe('Transformation type'),\n\n /**\n * Transformation-specific configuration\n * \n * @example For map: { oldField: 'newField' }\n * @example For filter: { condition: 'status == \"active\"' }\n * @example For script: { language: 'javascript', code: '...' }\n */\n config: z.record(z.string(), z.unknown()).describe('Transformation config'),\n\n /**\n * Whether to continue on error\n */\n continueOnError: z.boolean().default(false).describe('Continue on error'),\n});\n\nexport type ETLTransformation = z.infer;\n\n/**\n * ETL Sync Mode\n */\nexport const ETLSyncModeSchema = z.enum([\n 'full', // Full refresh - extract all data every time\n 'incremental', // Only extract changed data\n 'cdc', // Change Data Capture - real-time streaming\n]);\n\nexport type ETLSyncMode = z.infer;\n\n/**\n * ETL Pipeline Schema\n * \n * Complete definition of a data pipeline from source to destination with transformations.\n */\nexport const ETLPipelineSchema = z.object({\n /**\n * Pipeline identifier (snake_case)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Pipeline identifier (snake_case)'),\n\n /**\n * Human-readable pipeline name\n */\n label: z.string().optional().describe('Pipeline display name'),\n\n /**\n * Pipeline description\n */\n description: z.string().optional().describe('Pipeline description'),\n\n /**\n * Data source configuration\n */\n source: ETLSourceSchema.describe('Data source'),\n\n /**\n * Data destination configuration\n */\n destination: ETLDestinationSchema.describe('Data destination'),\n\n /**\n * Transformation steps\n * Applied in order from source to destination\n */\n transformations: z.array(ETLTransformationSchema)\n .optional()\n .describe('Transformation pipeline'),\n\n /**\n * Sync mode\n */\n syncMode: ETLSyncModeSchema.default('full').describe('Sync mode'),\n\n /**\n * Execution schedule (cron expression)\n * \n * @example \"0 2 * * *\" - Daily at 2 AM\n * @example \"0 *\\/4 * * *\" - Every 4 hours\n * @example \"0 0 * * 0\" - Weekly on Sunday\n */\n schedule: z.string().optional().describe('Cron schedule expression'),\n\n /**\n * Whether pipeline is enabled\n */\n enabled: z.boolean().default(true).describe('Pipeline enabled status'),\n\n /**\n * Retry configuration for failed runs\n */\n retry: z.object({\n maxAttempts: z.number().int().min(0).default(3).describe('Max retry attempts'),\n backoffMs: z.number().int().min(0).default(60000).describe('Backoff in milliseconds'),\n }).optional().describe('Retry configuration'),\n\n /**\n * Notification configuration\n */\n notifications: z.object({\n onSuccess: z.array(z.string()).optional().describe('Email addresses for success notifications'),\n onFailure: z.array(z.string()).optional().describe('Email addresses for failure notifications'),\n }).optional().describe('Notification settings'),\n\n /**\n * Pipeline tags for organization\n */\n tags: z.array(z.string()).optional().describe('Pipeline tags'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\nexport type ETLPipeline = z.infer;\n\n/**\n * ETL Run Status\n */\nexport const ETLRunStatusSchema = z.enum([\n 'pending', // Queued for execution\n 'running', // Currently executing\n 'succeeded', // Completed successfully\n 'failed', // Failed with errors\n 'cancelled', // Manually cancelled\n 'timeout', // Timed out\n]);\n\nexport type ETLRunStatus = z.infer;\n\n/**\n * ETL Pipeline Run Result\n * \n * Result of a pipeline execution\n */\nexport const ETLPipelineRunSchema = z.object({\n /**\n * Run ID\n */\n id: z.string().describe('Run identifier'),\n\n /**\n * Pipeline name\n */\n pipelineName: z.string().describe('Pipeline name'),\n\n /**\n * Run status\n */\n status: ETLRunStatusSchema.describe('Run status'),\n\n /**\n * Start timestamp\n */\n startedAt: z.string().datetime().describe('Start time'),\n\n /**\n * End timestamp\n */\n completedAt: z.string().datetime().optional().describe('Completion time'),\n\n /**\n * Duration in milliseconds\n */\n durationMs: z.number().optional().describe('Duration in ms'),\n\n /**\n * Statistics\n */\n stats: z.object({\n recordsRead: z.number().int().default(0).describe('Records extracted'),\n recordsWritten: z.number().int().default(0).describe('Records loaded'),\n recordsErrored: z.number().int().default(0).describe('Records with errors'),\n bytesProcessed: z.number().int().default(0).describe('Bytes processed'),\n }).optional().describe('Run statistics'),\n\n /**\n * Error information\n */\n error: z.object({\n message: z.string().describe('Error message'),\n code: z.string().optional().describe('Error code'),\n details: z.unknown().optional().describe('Error details'),\n }).optional().describe('Error information'),\n\n /**\n * Execution logs\n */\n logs: z.array(z.string()).optional().describe('Execution logs'),\n});\n\nexport type ETLPipelineRun = z.infer;\n\n/**\n * Helper factory for creating ETL pipelines\n */\nexport const ETL = {\n /**\n * Create a simple database-to-database pipeline\n */\n databaseSync: (params: {\n name: string;\n sourceTable: string;\n destTable: string;\n schedule?: string;\n }): ETLPipeline => ({\n name: params.name,\n source: {\n type: 'database',\n config: { table: params.sourceTable },\n },\n destination: {\n type: 'database',\n config: { table: params.destTable },\n writeMode: 'upsert',\n },\n syncMode: 'incremental',\n schedule: params.schedule,\n enabled: true,\n }),\n\n /**\n * Create an API to database pipeline\n */\n apiToDatabase: (params: {\n name: string;\n apiConnector: string;\n destTable: string;\n schedule?: string;\n }): ETLPipeline => ({\n name: params.name,\n source: {\n type: 'api',\n connector: params.apiConnector,\n config: {},\n },\n destination: {\n type: 'database',\n config: { table: params.destTable },\n writeMode: 'append',\n },\n syncMode: 'full',\n schedule: params.schedule,\n enabled: true,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * Trigger Registry Protocol\n * \n * Lightweight automation triggers for simple integrations.\n * Inspired by Zapier, n8n, and Workato connector architectures.\n * \n * ## When to use Trigger Registry vs. Integration Connector?\n * \n * **Use `automation/trigger-registry.zod.ts` when:**\n * - Building simple automation triggers (e.g., \"when Slack message received, create task\")\n * - No complex authentication needed (simple API keys, basic auth)\n * - Lightweight, single-purpose integrations\n * - Quick setup with minimal configuration\n * - Webhook-based or polling triggers for automation workflows\n * \n * **Use `integration/connector.zod.ts` when:**\n * - Building enterprise-grade connectors (e.g., Salesforce, SAP, Oracle)\n * - Complex OAuth2/SAML authentication required\n * - Bidirectional sync with field mapping and transformations\n * - Webhook management and rate limiting required\n * - Full CRUD operations and data synchronization\n * \n * ## Use Cases\n * \n * 1. **Simple Automation Triggers**\n * - Slack notifications on record updates\n * - Twilio SMS on workflow events\n * - SendGrid email templates\n * \n * 2. **Lightweight Operations**\n * - Single-action integrations (send, notify, log)\n * - No bidirectional sync required\n * - Webhook receivers for incoming events\n * \n * 3. **Quick Integrations**\n * - Payment webhooks (Stripe, PayPal)\n * - Communication triggers (Twilio, SendGrid, Slack)\n * - Simple API calls to third-party services\n * \n * @see https://zapier.com/developer/documentation/v2/\n * @see https://docs.n8n.io/integrations/creating-nodes/\n * @see ../../integration/connector.zod.ts for enterprise connectors\n * \n * @example\n * ```typescript\n * const slackNotifier: Connector = {\n * id: 'slack_notify',\n * name: 'Slack Notification',\n * category: 'communication',\n * authentication: {\n * type: 'apiKey',\n * fields: [{ name: 'webhook_url', label: 'Webhook URL', type: 'url' }]\n * },\n * operations: [\n * { id: 'send_message', name: 'Send Message', type: 'action' }\n * ]\n * }\n * ```\n */\n\n/**\n * Connector Category\n */\nexport const ConnectorCategorySchema = z.enum([\n 'crm', // Customer Relationship Management\n 'payment', // Payment processors\n 'communication', // Email, SMS, Chat\n 'storage', // File storage\n 'analytics', // Analytics platforms\n 'database', // Databases\n 'marketing', // Marketing automation\n 'accounting', // Accounting software\n 'hr', // Human resources\n 'productivity', // Productivity tools\n 'ecommerce', // E-commerce platforms\n 'support', // Customer support\n 'devtools', // Developer tools\n 'social', // Social media\n 'other', // Other category\n]);\n\nexport type ConnectorCategory = z.infer;\n\n/**\n * Authentication Type\n */\nexport const AuthenticationTypeSchema = z.enum([\n 'none', // No authentication\n 'apiKey', // API key\n 'basic', // Basic auth (username/password)\n 'bearer', // Bearer token\n 'oauth1', // OAuth 1.0\n 'oauth2', // OAuth 2.0\n 'custom', // Custom authentication\n]);\n\nexport type AuthenticationType = z.infer;\n\n/**\n * Authentication Field Schema\n */\nexport const AuthFieldSchema = z.object({\n /**\n * Field name (machine name)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Field name (snake_case)'),\n\n /**\n * Field label\n */\n label: z.string().describe('Field label'),\n\n /**\n * Field type\n */\n type: z.enum(['text', 'password', 'url', 'select'])\n .default('text')\n .describe('Field type'),\n\n /**\n * Field description\n */\n description: z.string().optional().describe('Field description'),\n\n /**\n * Whether field is required\n */\n required: z.boolean().default(true).describe('Required field'),\n\n /**\n * Default value\n */\n default: z.string().optional().describe('Default value'),\n\n /**\n * Options for select fields\n */\n options: z.array(z.object({\n label: z.string(),\n value: z.string(),\n })).optional().describe('Select field options'),\n\n /**\n * Placeholder text\n */\n placeholder: z.string().optional().describe('Placeholder text'),\n});\n\nexport type AuthField = z.infer;\n\n/**\n * OAuth 2.0 Configuration\n */\nexport const OAuth2ConfigSchema = z.object({\n /**\n * Authorization URL\n */\n authorizationUrl: z.string().url().describe('Authorization endpoint URL'),\n\n /**\n * Token URL\n */\n tokenUrl: z.string().url().describe('Token endpoint URL'),\n\n /**\n * Scopes to request\n */\n scopes: z.array(z.string()).optional().describe('OAuth scopes'),\n\n /**\n * Client ID field name\n */\n clientIdField: z.string().default('client_id').describe('Client ID field name'),\n\n /**\n * Client secret field name\n */\n clientSecretField: z.string().default('client_secret').describe('Client secret field name'),\n});\n\nexport type OAuth2Config = z.infer;\n\n/**\n * Authentication Configuration\n */\nexport const AuthenticationSchema = z.object({\n /**\n * Authentication type\n */\n type: AuthenticationTypeSchema.describe('Authentication type'),\n\n /**\n * Authentication fields\n * Configuration fields needed for this auth type\n */\n fields: z.array(AuthFieldSchema).optional().describe('Authentication fields'),\n\n /**\n * OAuth 2.0 configuration (when type is oauth2)\n */\n oauth2: OAuth2ConfigSchema.optional().describe('OAuth 2.0 configuration'),\n\n /**\n * Test authentication instructions\n */\n test: z.object({\n url: z.string().optional().describe('Test endpoint URL'),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).default('GET').describe('HTTP method'),\n }).optional().describe('Authentication test configuration'),\n});\n\nexport type Authentication = z.infer;\n\n/**\n * Connector Operation Type\n */\nexport const OperationTypeSchema = z.enum([\n 'read', // Read/query data\n 'write', // Create/update data\n 'delete', // Delete data\n 'search', // Search operation\n 'trigger', // Webhook/polling trigger\n 'action', // Custom action\n]);\n\nexport type OperationType = z.infer;\n\n/**\n * Operation Parameter Schema\n */\nexport const OperationParameterSchema = z.object({\n /**\n * Parameter name\n */\n name: z.string().describe('Parameter name'),\n\n /**\n * Parameter label\n */\n label: z.string().describe('Parameter label'),\n\n /**\n * Parameter description\n */\n description: z.string().optional().describe('Parameter description'),\n\n /**\n * Parameter type\n */\n type: z.enum(['string', 'number', 'boolean', 'array', 'object', 'date', 'file'])\n .describe('Parameter type'),\n\n /**\n * Whether parameter is required\n */\n required: z.boolean().default(false).describe('Required parameter'),\n\n /**\n * Default value\n */\n default: z.unknown().optional().describe('Default value'),\n\n /**\n * Validation schema\n */\n validation: z.record(z.string(), z.unknown()).optional().describe('Validation rules'),\n\n /**\n * Dynamic options function\n */\n dynamicOptions: z.string().optional().describe('Function to load dynamic options'),\n});\n\nexport type OperationParameter = z.infer;\n\n/**\n * Connector Operation Schema\n */\nexport const ConnectorOperationSchema = z.object({\n /**\n * Operation identifier\n */\n id: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Operation ID (snake_case)'),\n\n /**\n * Operation name\n */\n name: z.string().describe('Operation name'),\n\n /**\n * Operation description\n */\n description: z.string().optional().describe('Operation description'),\n\n /**\n * Operation type\n */\n type: OperationTypeSchema.describe('Operation type'),\n\n /**\n * Input parameters\n */\n inputSchema: z.array(OperationParameterSchema)\n .optional()\n .describe('Input parameters'),\n\n /**\n * Output schema\n */\n outputSchema: z.record(z.string(), z.unknown())\n .optional()\n .describe('Output schema'),\n\n /**\n * Sample output for documentation\n */\n sampleOutput: z.unknown().optional().describe('Sample output'),\n\n /**\n * Whether operation supports pagination\n */\n supportsPagination: z.boolean().default(false).describe('Supports pagination'),\n\n /**\n * Whether operation supports filtering\n */\n supportsFiltering: z.boolean().default(false).describe('Supports filtering'),\n});\n\nexport type ConnectorOperation = z.infer;\n\n/**\n * Connector Trigger Schema\n * \n * Triggers are special operations that watch for events and initiate workflows.\n */\nexport const ConnectorTriggerSchema = z.object({\n /**\n * Trigger identifier\n */\n id: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Trigger ID (snake_case)'),\n\n /**\n * Trigger name\n */\n name: z.string().describe('Trigger name'),\n\n /**\n * Trigger description\n */\n description: z.string().optional().describe('Trigger description'),\n\n /**\n * Trigger type\n */\n type: z.enum(['webhook', 'polling', 'stream'])\n .describe('Trigger mechanism'),\n\n /**\n * Trigger configuration\n */\n config: z.record(z.string(), z.unknown())\n .optional()\n .describe('Trigger configuration'),\n\n /**\n * Output schema\n */\n outputSchema: z.record(z.string(), z.unknown())\n .optional()\n .describe('Event payload schema'),\n\n /**\n * Polling interval (for polling triggers)\n * In milliseconds\n */\n pollingIntervalMs: z.number().int().min(1000)\n .optional()\n .describe('Polling interval in ms'),\n});\n\nexport type ConnectorTrigger = z.infer;\n\n/**\n * Connector Schema\n * \n * Complete definition of a connector to an external system.\n */\nexport const ConnectorSchema = z.object({\n /**\n * Connector identifier\n * Must be globally unique\n */\n id: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Connector ID (snake_case)'),\n\n /**\n * Connector name\n */\n name: z.string().describe('Connector name'),\n\n /**\n * Connector description\n */\n description: z.string().optional().describe('Connector description'),\n\n /**\n * Connector version (semver)\n */\n version: z.string().optional().describe('Connector version'),\n\n /**\n * Connector icon URL or name\n */\n icon: z.string().optional().describe('Connector icon'),\n\n /**\n * Connector category\n */\n category: ConnectorCategorySchema.describe('Connector category'),\n\n /**\n * Base URL for API calls\n */\n baseUrl: z.string().url().optional().describe('API base URL'),\n\n /**\n * Authentication configuration\n */\n authentication: AuthenticationSchema.describe('Authentication config'),\n\n /**\n * Available operations\n */\n operations: z.array(ConnectorOperationSchema)\n .optional()\n .describe('Connector operations'),\n\n /**\n * Available triggers\n */\n triggers: z.array(ConnectorTriggerSchema)\n .optional()\n .describe('Connector triggers'),\n\n /**\n * Rate limiting information\n */\n rateLimit: z.object({\n requestsPerSecond: z.number().optional().describe('Max requests per second'),\n requestsPerMinute: z.number().optional().describe('Max requests per minute'),\n requestsPerHour: z.number().optional().describe('Max requests per hour'),\n }).optional().describe('Rate limiting'),\n\n /**\n * Connector author\n */\n author: z.string().optional().describe('Connector author'),\n\n /**\n * Documentation URL\n */\n documentation: z.string().url().optional().describe('Documentation URL'),\n\n /**\n * Homepage URL\n */\n homepage: z.string().url().optional().describe('Homepage URL'),\n\n /**\n * License\n */\n license: z.string().optional().describe('License (SPDX identifier)'),\n\n /**\n * Tags for discovery\n */\n tags: z.array(z.string()).optional().describe('Connector tags'),\n\n /**\n * Whether connector is verified/certified\n */\n verified: z.boolean().default(false).describe('Verified connector'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\nexport type Connector = z.infer;\n\n/**\n * Connector Instance Schema\n * \n * A configured instance of a connector with credentials.\n */\nexport const ConnectorInstanceSchema = z.object({\n /**\n * Instance ID\n */\n id: z.string().describe('Instance ID'),\n\n /**\n * Connector ID this instance uses\n */\n connectorId: z.string().describe('Connector ID'),\n\n /**\n * Instance name\n */\n name: z.string().describe('Instance name'),\n\n /**\n * Instance description\n */\n description: z.string().optional().describe('Instance description'),\n\n /**\n * Authentication credentials (encrypted)\n */\n credentials: z.record(z.string(), z.unknown()).describe('Encrypted credentials'),\n\n /**\n * Additional configuration\n */\n config: z.record(z.string(), z.unknown()).optional().describe('Additional config'),\n\n /**\n * Whether instance is active\n */\n active: z.boolean().default(true).describe('Instance active status'),\n\n /**\n * Created timestamp\n */\n createdAt: z.string().datetime().optional().describe('Creation time'),\n\n /**\n * Last tested timestamp\n */\n lastTestedAt: z.string().datetime().optional().describe('Last test time'),\n\n /**\n * Test status\n */\n testStatus: z.enum(['unknown', 'success', 'failed'])\n .default('unknown')\n .describe('Connection test status'),\n});\n\nexport type ConnectorInstance = z.infer;\n\n/**\n * Helper factory for creating connectors\n */\nexport const Connector = {\n /**\n * Create a basic API key connector\n */\n apiKey: (params: {\n id: string;\n name: string;\n category: ConnectorCategory;\n baseUrl: string;\n }): Connector => ({\n id: params.id,\n name: params.name,\n category: params.category,\n baseUrl: params.baseUrl,\n authentication: {\n type: 'apiKey',\n fields: [\n {\n name: 'api_key',\n label: 'API Key',\n type: 'password',\n required: true,\n },\n ],\n },\n verified: false,\n }),\n\n /**\n * Create an OAuth 2.0 connector\n */\n oauth2: (params: {\n id: string;\n name: string;\n category: ConnectorCategory;\n baseUrl: string;\n authUrl: string;\n tokenUrl: string;\n scopes?: string[];\n }): Connector => ({\n id: params.id,\n name: params.name,\n category: params.category,\n baseUrl: params.baseUrl,\n authentication: {\n type: 'oauth2',\n oauth2: {\n authorizationUrl: params.authUrl,\n tokenUrl: params.tokenUrl,\n clientIdField: 'client_id',\n clientSecretField: 'client_secret',\n scopes: params.scopes,\n },\n },\n verified: false,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { FieldMappingSchema } from '../shared/mapping.zod';\n\n/**\n * Data Sync Protocol - LEVEL 1: Simple Synchronization\n * \n * Inspired by Salesforce Connect, Segment Sync, and Census Reverse ETL.\n * \n * **Positioning in 3-Layer Architecture:**\n * - **L1: Simple Sync** (THIS FILE) - Business users - Sync Salesforce to Sheets\n * - **L2: ETL Pipeline** (automation/etl.zod.ts) - Data engineers - Aggregate 10 sources to warehouse\n * - **L3: Enterprise Connector** (integration/connector.zod.ts) - System integrators - Full SAP integration\n * \n * Data sync provides bidirectional or unidirectional data synchronization\n * between ObjectStack and external systems, maintaining data consistency\n * across platforms.\n * \n * **SCOPE: Simple field mappings only. NO complex transformations.**\n * For complex transformations (joins, aggregates, custom SQL), use ETL Pipeline (Level 2).\n * \n * ## When to Use This Layer\n * \n * **Use Simple Sync when:**\n * - Syncing 1:1 fields between two systems\n * - Simple field transformations (uppercase, cast, etc.)\n * - No complex logic required\n * - Business users need to configure integrations\n * \n * **Examples:**\n * - Salesforce Contact ↔ Google Sheets\n * - HubSpot Company ↔ CRM Account\n * - Shopify Orders → Accounting System\n * \n * **When to upgrade:**\n * - Need multi-source joins → Use {@link file://./etl.zod.ts | ETL Pipeline}\n * - Need complex authentication/webhooks → Use {@link file://../integration/connector.zod.ts | Enterprise Connector}\n * - Need aggregations or data warehousing → Use {@link file://./etl.zod.ts | ETL Pipeline}\n * \n * @see {@link file://./etl.zod.ts} for Level 2 (data engineering)\n * @see {@link file://../integration/connector.zod.ts} for Level 3 (enterprise integration)\n * \n * ## Use Cases\n * \n * 1. **CRM Integration**\n * - Sync contacts between ObjectStack and Salesforce\n * - Keep opportunity data synchronized\n * - Bidirectional updates\n * \n * 2. **Customer Data Platform (CDP)**\n * - Sync user profiles to Segment\n * - Enrichment data from Clearbit\n * - Marketing automation sync\n * \n * 3. **Operational Analytics**\n * - Sync production data to analytics warehouse\n * - Real-time dashboards\n * - Business intelligence\n * \n * @see https://help.salesforce.com/s/articleView?id=sf.platform_connect_about.htm\n * @see https://segment.com/docs/connections/sync/\n * @see https://www.getcensus.com/\n * \n * @example\n * ```typescript\n * const contactSync: DataSyncConfig = {\n * name: 'salesforce_contact_sync',\n * label: 'Salesforce Contact Sync',\n * source: {\n * object: 'contact',\n * filters: { status: 'active' }\n * },\n * destination: {\n * connector: 'salesforce',\n * operation: 'upsert_contact',\n * mapping: {\n * first_name: 'FirstName',\n * last_name: 'LastName',\n * email: 'Email'\n * }\n * },\n * syncMode: 'incremental',\n * schedule: '0 * * * *' // Hourly\n * }\n * ```\n */\n\n/**\n * Sync Direction\n */\nexport const SyncDirectionSchema = z.enum([\n 'push', // ObjectStack -> External (one-way)\n 'pull', // External -> ObjectStack (one-way)\n 'bidirectional', // Both directions\n]);\n\nexport type SyncDirection = z.infer;\n\n/**\n * Sync Mode\n */\nexport const SyncModeSchema = z.enum([\n 'full', // Full refresh every time\n 'incremental', // Only sync changed records\n 'realtime', // Real-time streaming sync\n]);\n\nexport type SyncMode = z.infer;\n\n/**\n * Conflict Resolution Strategy\n */\nexport const ConflictResolutionSchema = z.enum([\n 'source_wins', // Source system always wins\n 'destination_wins', // Destination system always wins\n 'latest_wins', // Most recently modified wins\n 'manual', // Flag for manual resolution\n 'merge', // Smart merge (custom logic)\n]);\n\nexport type ConflictResolution = z.infer;\n\n/**\n * Field Mapping for Data Sync\n * \n * Uses the canonical field mapping protocol from shared/mapping.zod.ts\n * for simple 1:1 field transformations.\n * \n * @see {@link FieldMappingSchema} for the base field mapping schema\n */\n\n/**\n * Data Source Configuration\n */\nexport const DataSourceConfigSchema = z.object({\n /**\n * Source object name\n * For ObjectStack objects\n */\n object: z.string().optional().describe('ObjectStack object name'),\n\n /**\n * Filter conditions\n * Only sync records matching these filters\n */\n filters: z.unknown().optional().describe('Filter conditions'),\n\n /**\n * Fields to include\n * If not specified, all fields are synced\n */\n fields: z.array(z.string()).optional().describe('Fields to sync'),\n\n /**\n * External connector instance ID\n * For external data sources\n */\n connectorInstanceId: z.string().optional().describe('Connector instance ID'),\n\n /**\n * External resource identifier\n * e.g., Salesforce object name, database table, API endpoint\n */\n externalResource: z.string().optional().describe('External resource ID'),\n});\n\nexport type DataSourceConfig = z.infer;\n\n/**\n * Data Destination Configuration\n */\nexport const DataDestinationConfigSchema = z.object({\n /**\n * Destination object name\n * For ObjectStack objects\n */\n object: z.string().optional().describe('ObjectStack object name'),\n\n /**\n * Connector instance ID\n * For external destinations\n */\n connectorInstanceId: z.string().optional().describe('Connector instance ID'),\n\n /**\n * Operation to perform\n */\n operation: z.enum([\n 'insert', // Create new records only\n 'update', // Update existing records only\n 'upsert', // Insert or update based on key\n 'delete', // Delete records\n 'sync', // Full synchronization\n ]).describe('Sync operation'),\n\n /**\n * Field mappings\n * Maps source fields to destination fields\n */\n mapping: z.union([\n z.record(z.string(), z.string()), // Simple mapping: { sourceField: 'destField' }\n z.array(FieldMappingSchema), // Advanced mapping with transformations\n ]).optional().describe('Field mappings'),\n\n /**\n * External resource identifier\n */\n externalResource: z.string().optional().describe('External resource ID'),\n\n /**\n * Match key for upsert operations\n * Fields to use for matching existing records\n */\n matchKey: z.array(z.string()).optional().describe('Match key fields'),\n});\n\nexport type DataDestinationConfig = z.infer;\n\n/**\n * Data Sync Configuration Schema\n * \n * Complete definition of a data synchronization between systems.\n */\nexport const DataSyncConfigSchema = z.object({\n /**\n * Sync configuration name (snake_case)\n */\n name: z.string()\n .regex(/^[a-z_][a-z0-9_]*$/)\n .describe('Sync configuration name (snake_case)'),\n\n /**\n * Human-readable label\n */\n label: z.string().optional().describe('Sync display name'),\n\n /**\n * Description\n */\n description: z.string().optional().describe('Sync description'),\n\n /**\n * Source configuration\n */\n source: DataSourceConfigSchema.describe('Data source'),\n\n /**\n * Destination configuration\n */\n destination: DataDestinationConfigSchema.describe('Data destination'),\n\n /**\n * Sync direction\n */\n direction: SyncDirectionSchema.default('push').describe('Sync direction'),\n\n /**\n * Sync mode\n */\n syncMode: SyncModeSchema.default('incremental').describe('Sync mode'),\n\n /**\n * Conflict resolution strategy\n */\n conflictResolution: ConflictResolutionSchema\n .default('latest_wins')\n .describe('Conflict resolution'),\n\n /**\n * Execution schedule (cron expression)\n * For scheduled syncs\n * \n * @example \"0 * * * *\" - Hourly\n * @example \"*\\/15 * * * *\" - Every 15 minutes\n */\n schedule: z.string().optional().describe('Cron schedule'),\n\n /**\n * Whether sync is enabled\n */\n enabled: z.boolean().default(true).describe('Sync enabled'),\n\n /**\n * Change tracking field\n * Field to track when records were last modified\n * Used for incremental sync\n * \n * @example \"updated_at\", \"modified_date\"\n */\n changeTrackingField: z.string()\n .optional()\n .describe('Field for change tracking'),\n\n /**\n * Batch size\n * Number of records to process per batch\n */\n batchSize: z.number().int().min(1).max(10000)\n .default(100)\n .describe('Batch size for processing'),\n\n /**\n * Retry configuration\n */\n retry: z.object({\n maxAttempts: z.number().int().min(0).default(3).describe('Max retries'),\n backoffMs: z.number().int().min(0).default(30000).describe('Backoff duration'),\n }).optional().describe('Retry configuration'),\n\n /**\n * Pre-sync validation rules\n */\n validation: z.object({\n required: z.array(z.string()).optional().describe('Required fields'),\n unique: z.array(z.string()).optional().describe('Unique constraint fields'),\n custom: z.array(z.object({\n name: z.string(),\n condition: z.string().describe('Validation condition'),\n message: z.string().describe('Error message'),\n })).optional().describe('Custom validation rules'),\n }).optional().describe('Validation rules'),\n\n /**\n * Error handling configuration\n */\n errorHandling: z.object({\n onValidationError: z.enum(['skip', 'fail', 'log']).default('skip'),\n onSyncError: z.enum(['skip', 'fail', 'retry']).default('retry'),\n notifyOnError: z.array(z.string()).optional().describe('Email notifications'),\n }).optional().describe('Error handling'),\n\n /**\n * Performance optimization\n */\n optimization: z.object({\n parallelBatches: z.boolean().default(false).describe('Process batches in parallel'),\n cacheEnabled: z.boolean().default(true).describe('Enable caching'),\n compressionEnabled: z.boolean().default(false).describe('Enable compression'),\n }).optional().describe('Performance optimization'),\n\n /**\n * Audit and logging\n */\n audit: z.object({\n logLevel: z.enum(['none', 'error', 'warn', 'info', 'debug']).default('info'),\n retainLogsForDays: z.number().int().min(1).default(30),\n trackChanges: z.boolean().default(true).describe('Track all changes'),\n }).optional().describe('Audit configuration'),\n\n /**\n * Tags for organization\n */\n tags: z.array(z.string()).optional().describe('Sync tags'),\n\n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom metadata'),\n});\n\nexport type DataSyncConfig = z.infer;\n\n/**\n * Sync Execution Status\n */\nexport const SyncExecutionStatusSchema = z.enum([\n 'pending', // Queued\n 'running', // Currently executing\n 'completed', // Successfully completed\n 'partial', // Completed with some errors\n 'failed', // Failed\n 'cancelled', // Manually cancelled\n]);\n\nexport type SyncExecutionStatus = z.infer;\n\n/**\n * Sync Execution Result Schema\n * \n * Result of a sync execution.\n */\nexport const SyncExecutionResultSchema = z.object({\n /**\n * Execution ID\n */\n id: z.string().describe('Execution ID'),\n\n /**\n * Sync configuration name\n */\n syncName: z.string().describe('Sync name'),\n\n /**\n * Execution status\n */\n status: SyncExecutionStatusSchema.describe('Execution status'),\n\n /**\n * Start timestamp\n */\n startedAt: z.string().datetime().describe('Start time'),\n\n /**\n * End timestamp\n */\n completedAt: z.string().datetime().optional().describe('Completion time'),\n\n /**\n * Duration in milliseconds\n */\n durationMs: z.number().optional().describe('Duration in ms'),\n\n /**\n * Statistics\n */\n stats: z.object({\n recordsProcessed: z.number().int().default(0).describe('Total records processed'),\n recordsInserted: z.number().int().default(0).describe('Records inserted'),\n recordsUpdated: z.number().int().default(0).describe('Records updated'),\n recordsDeleted: z.number().int().default(0).describe('Records deleted'),\n recordsSkipped: z.number().int().default(0).describe('Records skipped'),\n recordsErrored: z.number().int().default(0).describe('Records with errors'),\n conflictsDetected: z.number().int().default(0).describe('Conflicts detected'),\n conflictsResolved: z.number().int().default(0).describe('Conflicts resolved'),\n }).optional().describe('Execution statistics'),\n\n /**\n * Errors encountered\n */\n errors: z.array(z.object({\n recordId: z.string().optional().describe('Record ID'),\n field: z.string().optional().describe('Field name'),\n message: z.string().describe('Error message'),\n code: z.string().optional().describe('Error code'),\n })).optional().describe('Errors'),\n\n /**\n * Execution logs\n */\n logs: z.array(z.string()).optional().describe('Execution logs'),\n});\n\nexport type SyncExecutionResult = z.infer;\n\n/**\n * Helper factory for creating sync configurations\n */\nexport const Sync = {\n /**\n * Create a simple object-to-object sync\n */\n objectSync: (params: {\n name: string;\n sourceObject: string;\n destObject: string;\n mapping: Record;\n schedule?: string;\n }): DataSyncConfig => ({\n name: params.name,\n source: {\n object: params.sourceObject,\n },\n destination: {\n object: params.destObject,\n operation: 'upsert',\n mapping: params.mapping,\n },\n direction: 'push',\n syncMode: 'incremental',\n conflictResolution: 'latest_wins',\n batchSize: 100,\n schedule: params.schedule,\n enabled: true,\n }),\n\n /**\n * Create a connector sync\n */\n connectorSync: (params: {\n name: string;\n sourceObject: string;\n connectorInstanceId: string;\n externalResource: string;\n mapping: Record;\n schedule?: string;\n }): DataSyncConfig => ({\n name: params.name,\n source: {\n object: params.sourceObject,\n },\n destination: {\n connectorInstanceId: params.connectorInstanceId,\n externalResource: params.externalResource,\n operation: 'upsert',\n mapping: params.mapping,\n },\n direction: 'push',\n syncMode: 'incremental',\n conflictResolution: 'latest_wins',\n batchSize: 100,\n schedule: params.schedule,\n enabled: true,\n }),\n\n /**\n * Create a bidirectional sync\n */\n bidirectionalSync: (params: {\n name: string;\n object: string;\n connectorInstanceId: string;\n externalResource: string;\n mapping: Record;\n schedule?: string;\n }): DataSyncConfig => ({\n name: params.name,\n source: {\n object: params.object,\n },\n destination: {\n connectorInstanceId: params.connectorInstanceId,\n externalResource: params.externalResource,\n operation: 'sync',\n mapping: params.mapping,\n },\n direction: 'bidirectional',\n syncMode: 'incremental',\n conflictResolution: 'latest_wins',\n batchSize: 100,\n schedule: params.schedule,\n enabled: true,\n }),\n} as const;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module automation/node-executor\n *\n * Node Executor Plugin Protocol — Wait Node Pause/Resume\n *\n * Defines the specification for node executor plugins, with a focus on\n * the `wait` node executor that supports flow pause and external-event\n * resume (signal, manual, webhook, condition).\n *\n * The protocol covers:\n * - **WaitResumePayload**: The payload delivered when a paused flow is resumed\n * - **WaitExecutorConfig**: Configuration for the wait executor plugin\n * - **NodeExecutorDescriptor**: Generic node executor plugin descriptor\n */\n\nimport { z } from 'zod';\n\n// ─── Wait Event Types ────────────────────────────────────────────────\n\n/**\n * Wait event type — determines how a wait node is resumed.\n * Mirrors the `waitEventConfig.eventType` in flow.zod.ts.\n */\nexport const WaitEventTypeSchema = z.enum([\n 'timer', // Resume after duration/datetime\n 'signal', // Resume on named signal dispatch\n 'webhook', // Resume on incoming webhook call\n 'manual', // Resume by manual operator action\n 'condition', // Resume when a data condition is met (polling)\n]).describe('Wait event type determining how a paused flow is resumed');\n\nexport type WaitEventType = z.infer;\n\n// ─── Wait Resume Payload ─────────────────────────────────────────────\n\n/**\n * Payload delivered when a paused wait node is resumed by an external event.\n * The runtime engine passes this to the flow executor to continue execution.\n */\nexport const WaitResumePayloadSchema = z.object({\n /** The execution id of the paused flow */\n executionId: z.string().describe('Execution ID of the paused flow'),\n\n /** The checkpoint id being resumed */\n checkpointId: z.string().describe('Checkpoint ID to resume from'),\n\n /** The node id of the wait node being resumed */\n nodeId: z.string().describe('Wait node ID being resumed'),\n\n /** The event type that triggered the resume */\n eventType: WaitEventTypeSchema.describe('Event type that triggered resume'),\n\n /** Signal name (for signal events) */\n signalName: z.string().optional().describe('Signal name (when eventType is signal)'),\n\n /** Webhook payload data (for webhook events) */\n webhookPayload: z.record(z.string(), z.unknown()).optional()\n .describe('Webhook request payload (when eventType is webhook)'),\n\n /** Who/what triggered the resume */\n resumedBy: z.string().optional().describe('User ID or system identifier that triggered resume'),\n\n /** Timestamp of the resume event */\n resumedAt: z.string().datetime().describe('ISO 8601 timestamp of the resume event'),\n\n /** Additional variables to merge into flow context on resume */\n variables: z.record(z.string(), z.unknown()).optional()\n .describe('Variables to merge into flow context upon resume'),\n}).describe('Payload for resuming a paused wait node');\n\nexport type WaitResumePayload = z.infer;\n\n// ─── Wait Executor Config ────────────────────────────────────────────\n\n/**\n * Timeout behavior when a wait node exceeds its timeout.\n */\nexport const WaitTimeoutBehaviorSchema = z.enum([\n 'fail', // Mark execution as failed\n 'continue', // Continue to next node (skip wait)\n 'fallback', // Execute a fallback edge\n]).describe('Behavior when a wait node exceeds its timeout');\n\nexport type WaitTimeoutBehavior = z.infer;\n\n/**\n * Configuration for the wait node executor plugin.\n * Controls polling intervals, webhook endpoint patterns, and timeout behavior.\n */\nexport const WaitExecutorConfigSchema = z.object({\n /** Default timeout for wait nodes without explicit timeout (ms) */\n defaultTimeoutMs: z.number().int().min(0).default(86400000)\n .describe('Default timeout in ms (default: 24 hours)'),\n\n /** Default timeout behavior */\n defaultTimeoutBehavior: WaitTimeoutBehaviorSchema.default('fail')\n .describe('Default behavior when wait timeout is exceeded'),\n\n /** Polling interval for condition-based waits (ms) */\n conditionPollIntervalMs: z.number().int().min(1000).default(30000)\n .describe('Polling interval for condition waits in ms (default: 30s)'),\n\n /** Maximum polling attempts for condition waits (0 = unlimited until timeout) */\n conditionMaxPolls: z.number().int().min(0).default(0)\n .describe('Max polling attempts for condition waits (0 = unlimited)'),\n\n /** Webhook endpoint URL pattern (runtime fills in execution/node ids) */\n webhookUrlPattern: z.string().default('/api/v1/automation/resume/{executionId}/{nodeId}')\n .describe('URL pattern for webhook resume endpoints'),\n\n /** Whether to persist checkpoints to durable storage */\n persistCheckpoints: z.boolean().default(true)\n .describe('Persist wait checkpoints to durable storage'),\n\n /** Maximum concurrent paused executions (0 = unlimited) */\n maxPausedExecutions: z.number().int().min(0).default(0)\n .describe('Max concurrent paused executions (0 = unlimited)'),\n}).describe('Wait node executor plugin configuration');\n\nexport type WaitExecutorConfig = z.infer;\n\n// ─── Node Executor Descriptor ────────────────────────────────────────\n\n/**\n * Generic node executor plugin descriptor.\n * Each node type (wait, script, http_request, etc.) can register\n * a custom executor via this descriptor.\n */\nexport const NodeExecutorDescriptorSchema = z.object({\n /** Unique executor identifier */\n id: z.string().describe('Unique executor plugin identifier'),\n\n /** Human-readable name */\n name: z.string().describe('Display name'),\n\n /** The FlowNodeAction types this executor handles */\n nodeTypes: z.array(z.string()).min(1)\n .describe('FlowNodeAction types this executor handles'),\n\n /** Executor plugin version (semver) */\n version: z.string().describe('Plugin version (semver)'),\n\n /** Description of the executor */\n description: z.string().optional().describe('Executor description'),\n\n /** Whether this executor supports async pause/resume */\n supportsPause: z.boolean().default(false)\n .describe('Whether the executor supports async pause/resume'),\n\n /** Whether this executor supports cancellation mid-execution */\n supportsCancellation: z.boolean().default(false)\n .describe('Whether the executor supports mid-execution cancellation'),\n\n /** Whether this executor supports retry on failure */\n supportsRetry: z.boolean().default(true)\n .describe('Whether the executor supports retry on failure'),\n\n /** Executor-specific configuration schema (JSON Schema reference) */\n configSchemaRef: z.string().optional()\n .describe('JSON Schema $ref for executor-specific config'),\n}).describe('Node executor plugin descriptor');\n\nexport type NodeExecutorDescriptor = z.infer;\n\n// ─── Built-in Wait Executor Descriptor ───────────────────────────────\n\n/**\n * Built-in descriptor for the wait node executor.\n * Runtime implementations should register this or a compatible executor.\n */\nexport const WAIT_EXECUTOR_DESCRIPTOR: NodeExecutorDescriptor = {\n id: 'objectstack:wait-executor',\n name: 'Wait Node Executor',\n nodeTypes: ['wait'],\n version: '1.0.0',\n description: 'Pauses flow execution and resumes on timer, signal, webhook, manual action, or condition events.',\n supportsPause: true,\n supportsCancellation: true,\n supportsRetry: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module automation/bpmn-interop\n *\n * BPMN XML Interoperability Protocol\n *\n * Defines the specification for importing and exporting BPMN 2.0 XML\n * process definitions. This enables interoperability with external BPM\n * tools (Camunda, Activiti, jBPM, etc.) via a plugin-based approach.\n *\n * **Priority:** Low — long-term planning, not a core requirement.\n */\n\nimport { z } from 'zod';\n\n// ─── BPMN Element Mapping ────────────────────────────────────────────\n\n/**\n * Mapping between a BPMN XML element type and an ObjectStack FlowNodeAction.\n * Used during import/export to translate between the two models.\n */\nexport const BpmnElementMappingSchema = z.object({\n /** BPMN XML element type (e.g., \"bpmn:parallelGateway\", \"bpmn:serviceTask\") */\n bpmnType: z.string().describe('BPMN XML element type (e.g., \"bpmn:parallelGateway\")'),\n\n /** Corresponding ObjectStack FlowNodeAction */\n flowNodeAction: z.string().describe('ObjectStack FlowNodeAction value'),\n\n /** Whether this mapping is bidirectional (supports both import and export) */\n bidirectional: z.boolean().default(true).describe('Whether the mapping supports both import and export'),\n\n /** Notes about mapping limitations or special handling */\n notes: z.string().optional().describe('Notes about mapping limitations'),\n}).describe('Mapping between BPMN XML element and ObjectStack FlowNodeAction');\n\nexport type BpmnElementMapping = z.infer;\n\n// ─── BPMN Import Options ─────────────────────────────────────────────\n\n/**\n * Strategy for handling BPMN elements that have no direct ObjectStack mapping.\n */\nexport const BpmnUnmappedStrategySchema = z.enum([\n 'skip', // Skip unmapped elements silently\n 'warn', // Import with warnings\n 'error', // Fail on unmapped elements\n 'comment', // Import as annotation/comment nodes\n]).describe('Strategy for unmapped BPMN elements during import');\n\nexport type BpmnUnmappedStrategy = z.infer;\n\n/**\n * Options for importing a BPMN 2.0 XML process definition into an ObjectStack flow.\n */\nexport const BpmnImportOptionsSchema = z.object({\n /** Strategy for unmapped BPMN elements */\n unmappedStrategy: BpmnUnmappedStrategySchema.default('warn')\n .describe('How to handle unmapped BPMN elements'),\n\n /** Custom element mappings (override or extend built-in mappings) */\n customMappings: z.array(BpmnElementMappingSchema).optional()\n .describe('Custom element mappings to override or extend defaults'),\n\n /** Whether to import BPMN DI (diagram interchange) layout positions */\n importLayout: z.boolean().default(true)\n .describe('Import BPMN DI layout positions into canvas node coordinates'),\n\n /** Whether to import BPMN documentation as node descriptions */\n importDocumentation: z.boolean().default(true)\n .describe('Import BPMN documentation elements as node descriptions'),\n\n /** Target flow name (if not derived from BPMN process name) */\n flowName: z.string().optional()\n .describe('Override flow name (defaults to BPMN process name)'),\n\n /** Whether to validate the imported flow against ObjectStack schema */\n validateAfterImport: z.boolean().default(true)\n .describe('Validate imported flow against FlowSchema after import'),\n}).describe('Options for importing BPMN 2.0 XML into an ObjectStack flow');\n\nexport type BpmnImportOptions = z.infer;\n\n// ─── BPMN Export Options ─────────────────────────────────────────────\n\n/**\n * BPMN XML target version for export.\n */\nexport const BpmnVersionSchema = z.enum([\n '2.0', // BPMN 2.0 (most common, default)\n '2.0.2', // BPMN 2.0.2 (latest revision)\n]).describe('BPMN specification version for export');\n\nexport type BpmnVersion = z.infer;\n\n/**\n * Options for exporting an ObjectStack flow as BPMN 2.0 XML.\n */\nexport const BpmnExportOptionsSchema = z.object({\n /** Target BPMN version */\n version: BpmnVersionSchema.default('2.0')\n .describe('Target BPMN specification version'),\n\n /** Whether to include BPMN DI (diagram interchange) layout data */\n includeLayout: z.boolean().default(true)\n .describe('Include BPMN DI layout data from canvas positions'),\n\n /** Whether to include ObjectStack-specific extensions as BPMN extension elements */\n includeExtensions: z.boolean().default(false)\n .describe('Include ObjectStack extensions in BPMN extensionElements'),\n\n /** Custom element mappings (override built-in for export) */\n customMappings: z.array(BpmnElementMappingSchema).optional()\n .describe('Custom element mappings for export'),\n\n /** Whether to pretty-print the XML output */\n prettyPrint: z.boolean().default(true)\n .describe('Pretty-print XML output with indentation'),\n\n /** XML namespace prefix for BPMN elements */\n namespacePrefix: z.string().default('bpmn')\n .describe('XML namespace prefix for BPMN elements'),\n}).describe('Options for exporting an ObjectStack flow as BPMN 2.0 XML');\n\nexport type BpmnExportOptions = z.infer;\n\n// ─── BPMN Import/Export Result ───────────────────────────────────────\n\n/**\n * Diagnostic message from BPMN import/export operations.\n */\nexport const BpmnDiagnosticSchema = z.object({\n /** Severity level */\n severity: z.enum(['info', 'warning', 'error']).describe('Diagnostic severity'),\n\n /** Human-readable message */\n message: z.string().describe('Diagnostic message'),\n\n /** BPMN element ID (if applicable) */\n bpmnElementId: z.string().optional().describe('BPMN element ID related to this diagnostic'),\n\n /** ObjectStack node ID (if applicable) */\n nodeId: z.string().optional().describe('ObjectStack node ID related to this diagnostic'),\n}).describe('Diagnostic message from BPMN import/export');\n\nexport type BpmnDiagnostic = z.infer;\n\n/**\n * Result of a BPMN import or export operation.\n */\nexport const BpmnInteropResultSchema = z.object({\n /** Whether the operation completed successfully */\n success: z.boolean().describe('Whether the operation completed successfully'),\n\n /** Diagnostic messages (warnings, errors, info) */\n diagnostics: z.array(BpmnDiagnosticSchema).default([])\n .describe('Diagnostic messages from the operation'),\n\n /** Number of elements successfully mapped */\n mappedCount: z.number().int().min(0).default(0)\n .describe('Number of elements successfully mapped'),\n\n /** Number of elements skipped or unmapped */\n unmappedCount: z.number().int().min(0).default(0)\n .describe('Number of elements that could not be mapped'),\n}).describe('Result of a BPMN import/export operation');\n\nexport type BpmnInteropResult = z.infer;\n\n// ─── Built-in Element Mappings ───────────────────────────────────────\n\n/**\n * Built-in element mappings between BPMN 2.0 XML types and ObjectStack FlowNodeAction.\n * Import/export plugins should use these as defaults, with user overrides applied on top.\n */\nexport const BUILT_IN_BPMN_MAPPINGS: BpmnElementMapping[] = [\n { bpmnType: 'bpmn:startEvent', flowNodeAction: 'start', bidirectional: true },\n { bpmnType: 'bpmn:endEvent', flowNodeAction: 'end', bidirectional: true },\n { bpmnType: 'bpmn:exclusiveGateway', flowNodeAction: 'decision', bidirectional: true },\n { bpmnType: 'bpmn:parallelGateway', flowNodeAction: 'parallel_gateway', bidirectional: true },\n { bpmnType: 'bpmn:serviceTask', flowNodeAction: 'http_request', bidirectional: true, notes: 'Maps HTTP/connector tasks' },\n { bpmnType: 'bpmn:scriptTask', flowNodeAction: 'script', bidirectional: true },\n { bpmnType: 'bpmn:userTask', flowNodeAction: 'screen', bidirectional: true },\n { bpmnType: 'bpmn:callActivity', flowNodeAction: 'subflow', bidirectional: true },\n { bpmnType: 'bpmn:intermediateCatchEvent', flowNodeAction: 'wait', bidirectional: true, notes: 'Timer/signal/message catch events' },\n { bpmnType: 'bpmn:boundaryEvent', flowNodeAction: 'boundary_event', bidirectional: true },\n { bpmnType: 'bpmn:task', flowNodeAction: 'assignment', bidirectional: true, notes: 'Generic BPMN task maps to assignment' },\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Integration Protocol Exports\n * \n * External System Connection Protocols\n * - Connector configurations for SaaS, databases, file storage, message queues\n * - GitHub integration (version control, CI/CD)\n * - Vercel integration (deployment, hosting)\n * - Authentication methods (OAuth2, API Key, JWT, SAML)\n * - Data synchronization and field mapping\n * - Webhooks, rate limiting, and retry strategies\n */\n\n// Core Connector Protocol\nexport * from './connector.zod';\n\n// Connector Templates\nexport * from './connector/saas.zod';\nexport * from './connector/database.zod';\nexport * from './connector/file-storage.zod';\nexport * from './connector/message-queue.zod';\nexport * from './connector/github.zod';\nexport * from './connector/vercel.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\n/**\n * SHARED CONNECTOR AUTHENTICATION SCHEMAS\n * These schemas are used by connectors and integrations for external auth.\n * They define \"How we authenticate TO other systems\", not \"How users authenticate TO us\".\n */\n\n/**\n * OAuth2 Authentication Schema\n */\nexport const ConnectorOAuth2Schema = z.object({\n type: z.literal('oauth2'),\n authorizationUrl: z.string().url().describe('OAuth2 authorization endpoint'),\n tokenUrl: z.string().url().describe('OAuth2 token endpoint'),\n clientId: z.string().describe('OAuth2 client ID'),\n clientSecret: z.string().describe('OAuth2 client secret (typically from ENV)'),\n scopes: z.array(z.string()).optional().describe('Requested OAuth2 scopes'),\n redirectUri: z.string().url().optional().describe('OAuth2 redirect URI'),\n refreshToken: z.string().optional().describe('Refresh token for token renewal'),\n tokenExpiry: z.number().optional().describe('Token expiry timestamp'),\n});\n\n/**\n * API Key Authentication Schema\n */\nexport const ConnectorAPIKeySchema = z.object({\n type: z.literal('api-key'),\n key: z.string().describe('API key value'),\n headerName: z.string().default('X-API-Key').describe('HTTP header name for API key'),\n paramName: z.string().optional().describe('Query parameter name (alternative to header)'),\n});\n\n/**\n * Basic Authentication Schema\n */\nexport const ConnectorBasicAuthSchema = z.object({\n type: z.literal('basic'),\n username: z.string().describe('Username'),\n password: z.string().describe('Password'),\n});\n\n/**\n * Bearer Token Authentication Schema\n */\nexport const ConnectorBearerAuthSchema = z.object({\n type: z.literal('bearer'),\n token: z.string().describe('Bearer token'),\n});\n\n/**\n * No Authentication Schema\n */\nexport const ConnectorNoAuthSchema = z.object({\n type: z.literal('none'),\n});\n\n/**\n * Unified Connector Auth Configuration Schema\n */\nexport const ConnectorAuthConfigSchema = z.discriminatedUnion('type', [\n ConnectorOAuth2Schema,\n ConnectorAPIKeySchema,\n ConnectorBasicAuthSchema,\n ConnectorBearerAuthSchema,\n ConnectorNoAuthSchema,\n]);\n\nexport type ConnectorAuthConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport { WebhookSchema } from '../automation/webhook.zod';\nimport { ConnectorAuthConfigSchema } from '../shared/connector-auth.zod';\nimport { FieldMappingSchema as BaseFieldMappingSchema } from '../shared/mapping.zod';\n\n/**\n * Connector Protocol - LEVEL 3: Enterprise Connector\n * \n * Defines the standard connector specification for external system integration.\n * Connectors enable ObjectStack to sync data with SaaS apps, databases, file storage,\n * and message queues through a unified protocol.\n * \n * **Positioning in 3-Layer Architecture:**\n * - **L1: Simple Sync** (automation/sync.zod.ts) - Business users - Sync Salesforce to Sheets\n * - **L2: ETL Pipeline** (automation/etl.zod.ts) - Data engineers - Aggregate 10 sources to warehouse\n * - **L3: Enterprise Connector** (THIS FILE) - System integrators - Full SAP integration\n * \n * **SCOPE: Most comprehensive integration layer.**\n * Includes authentication, webhooks, rate limiting, field mapping, bidirectional sync,\n * retry policies, and complete lifecycle management.\n * \n * This protocol supports multiple authentication strategies, bidirectional sync,\n * field mapping, webhooks, and comprehensive rate limiting.\n * \n * Authentication is now imported from the canonical auth/config.zod.ts.\n * \n * ## When to Use This Layer\n * \n * **Use Enterprise Connector when:**\n * - Building enterprise-grade connectors (e.g., Salesforce, SAP, Oracle)\n * - Complex OAuth2/SAML authentication required\n * - Bidirectional sync with field mapping and transformations\n * - Webhook management and rate limiting required\n * - Full CRUD operations and data synchronization\n * - Need comprehensive retry strategies and error handling\n * \n * **Examples:**\n * - Full Salesforce integration with webhooks\n * - SAP ERP connector with CDC (Change Data Capture)\n * - Microsoft Dynamics 365 connector\n * \n * **When to downgrade:**\n * - Simple field sync → Use {@link file://../automation/sync.zod.ts | Simple Sync}\n * - Data transformation only → Use {@link file://../automation/etl.zod.ts | ETL Pipeline}\n * \n * @see {@link file://../automation/sync.zod.ts} for Level 1 (simple sync)\n * @see {@link file://../automation/etl.zod.ts} for Level 2 (data engineering)\n * \n * ## When to use Integration Connector vs. Trigger Registry?\n * \n * **Use `integration/connector.zod.ts` when:**\n * - Building enterprise-grade connectors (e.g., Salesforce, SAP, Oracle)\n * - Complex OAuth2/SAML authentication required\n * - Bidirectional sync with field mapping and transformations\n * - Webhook management and rate limiting required\n * - Full CRUD operations and data synchronization\n * - Need comprehensive retry strategies and error handling\n * \n * **Use `automation/trigger-registry.zod.ts` when:**\n * - Building simple automation triggers (e.g., \"when Slack message received, create task\")\n * - No complex authentication needed (simple API keys, basic auth)\n * - Lightweight, single-purpose integrations\n * - Quick setup with minimal configuration\n * \n * @see ../../automation/trigger-registry.zod.ts for lightweight automation triggers\n */\n\n// ============================================================================\n// Authentication Schemas - IMPORTED FROM CANONICAL SOURCE\n// Use ConnectorAuthConfigSchema from shared/connector-auth.zod.ts\n// ============================================================================\n\n// ============================================================================\n// Field Mapping Schema\n// Uses the canonical field mapping protocol from shared/mapping.zod.ts\n// Extended with connector-specific features\n// ============================================================================\n\n/**\n * Connector Field Mapping Configuration\n * \n * Extends the base field mapping with connector-specific features\n * like bidirectional sync modes and data type mapping.\n */\nexport const FieldMappingSchema = BaseFieldMappingSchema.extend({\n /**\n * Data type mapping (connector-specific)\n */\n dataType: z.enum([\n 'string',\n 'number',\n 'boolean',\n 'date',\n 'datetime',\n 'json',\n 'array',\n ]).optional().describe('Target data type'),\n \n /**\n * Is this field required?\n */\n required: z.boolean().default(false).describe('Field is required'),\n \n /**\n * Bidirectional sync mode (connector-specific)\n */\n syncMode: z.enum([\n 'read_only', // Only sync from external to ObjectStack\n 'write_only', // Only sync from ObjectStack to external\n 'bidirectional', // Sync both ways\n ]).default('bidirectional').describe('Sync mode'),\n});\n\nexport type FieldMapping = z.infer;\n\n// ============================================================================\n// Data Synchronization Configuration\n// ============================================================================\n\n/**\n * Sync Strategy Schema\n */\nexport const SyncStrategySchema = z.enum([\n 'full', // Full refresh (delete all and re-import)\n 'incremental', // Only sync changes since last sync\n 'upsert', // Insert new, update existing\n 'append_only', // Only insert new records\n]).describe('Synchronization strategy');\n\nexport type SyncStrategy = z.infer;\n\n/**\n * Conflict Resolution Strategy\n */\nexport const ConflictResolutionSchema = z.enum([\n 'source_wins', // External system data takes precedence\n 'target_wins', // ObjectStack data takes precedence\n 'latest_wins', // Most recently modified wins\n 'manual', // Flag for manual resolution\n]).describe('Conflict resolution strategy');\n\nexport type ConflictResolution = z.infer;\n\n/**\n * Data Synchronization Configuration\n */\nexport const DataSyncConfigSchema = z.object({\n /**\n * Sync strategy\n */\n strategy: SyncStrategySchema.optional().default('incremental'),\n \n /**\n * Sync direction\n */\n direction: z.enum([\n 'import', // External → ObjectStack\n 'export', // ObjectStack → External\n 'bidirectional', // Both ways\n ]).optional().default('import').describe('Sync direction'),\n \n /**\n * Sync frequency (cron expression)\n */\n schedule: z.string().optional().describe('Cron expression for scheduled sync'),\n \n /**\n * Enable real-time sync via webhooks\n */\n realtimeSync: z.boolean().optional().default(false).describe('Enable real-time sync'),\n \n /**\n * Field to track last sync timestamp\n */\n timestampField: z.string().optional().describe('Field to track last modification time'),\n \n /**\n * Conflict resolution strategy\n */\n conflictResolution: ConflictResolutionSchema.optional().default('latest_wins'),\n \n /**\n * Batch size for bulk operations\n */\n batchSize: z.number().min(1).max(10000).optional().default(1000).describe('Records per batch'),\n \n /**\n * Delete handling\n */\n deleteMode: z.enum([\n 'hard_delete', // Permanently delete\n 'soft_delete', // Mark as deleted\n 'ignore', // Don't sync deletions\n ]).optional().default('soft_delete').describe('Delete handling mode'),\n \n /**\n * Filter criteria for selective sync\n */\n filters: z.record(z.string(), z.unknown()).optional().describe('Filter criteria for selective sync'),\n});\n\nexport type DataSyncConfig = z.infer;\n\n// ============================================================================\n// Webhook Configuration\n// ============================================================================\n\n/**\n * Webhook Event Schema\n */\nexport const WebhookEventSchema = z.enum([\n 'record.created',\n 'record.updated',\n 'record.deleted',\n 'sync.started',\n 'sync.completed',\n 'sync.failed',\n 'auth.expired',\n 'rate_limit.exceeded',\n]).describe('Webhook event type');\n\nexport type WebhookEvent = z.infer;\n\n/**\n * Webhook Signature Algorithm\n */\nexport const WebhookSignatureAlgorithmSchema = z.enum([\n 'hmac_sha256',\n 'hmac_sha512',\n 'none',\n]).describe('Webhook signature algorithm');\n\nexport type WebhookSignatureAlgorithm = z.infer;\n\n/**\n * Webhook Configuration Schema\n * \n * Extends the canonical WebhookSchema with connector-specific event types.\n * This allows connectors to subscribe to both data events and connector lifecycle events.\n */\nexport const WebhookConfigSchema = WebhookSchema.extend({\n /**\n * Events to listen for\n * Connector-specific events like sync completion, auth expiry, etc.\n */\n events: z.array(WebhookEventSchema).optional().describe('Connector events to subscribe to'),\n \n /**\n * Signature algorithm for webhook security\n */\n signatureAlgorithm: WebhookSignatureAlgorithmSchema.optional().default('hmac_sha256'),\n});\n\nexport type WebhookConfig = z.infer;\n\n// ============================================================================\n// Rate Limiting and Retry Configuration\n// ============================================================================\n\n/**\n * Rate Limiting Strategy\n */\nexport const RateLimitStrategySchema = z.enum([\n 'fixed_window', // Fixed time window\n 'sliding_window', // Sliding time window\n 'token_bucket', // Token bucket algorithm\n 'leaky_bucket', // Leaky bucket algorithm\n]).describe('Rate limiting strategy');\n\nexport type RateLimitStrategy = z.infer;\n\n/**\n * Rate Limiting Configuration\n */\nexport const RateLimitConfigSchema = z.object({\n /**\n * Rate limiting strategy\n */\n strategy: RateLimitStrategySchema.optional().default('token_bucket'),\n \n /**\n * Maximum requests per window\n */\n maxRequests: z.number().min(1).describe('Maximum requests per window'),\n \n /**\n * Time window in seconds\n */\n windowSeconds: z.number().min(1).describe('Time window in seconds'),\n \n /**\n * Burst capacity (for token bucket)\n */\n burstCapacity: z.number().min(1).optional().describe('Burst capacity'),\n \n /**\n * Respect external system rate limits\n */\n respectUpstreamLimits: z.boolean().optional().default(true).describe('Respect external rate limit headers'),\n \n /**\n * Custom rate limit headers to check\n */\n rateLimitHeaders: z.object({\n remaining: z.string().optional().default('X-RateLimit-Remaining').describe('Header for remaining requests'),\n limit: z.string().optional().default('X-RateLimit-Limit').describe('Header for rate limit'),\n reset: z.string().optional().default('X-RateLimit-Reset').describe('Header for reset time'),\n }).optional().describe('Custom rate limit headers'),\n});\n\nexport type RateLimitConfig = z.infer;\n\n/**\n * Retry Strategy\n */\nexport const RetryStrategySchema = z.enum([\n 'exponential_backoff',\n 'linear_backoff',\n 'fixed_delay',\n 'no_retry',\n]).describe('Retry strategy');\n\nexport type RetryStrategy = z.infer;\n\n/**\n * Retry Configuration\n */\nexport const RetryConfigSchema = z.object({\n /**\n * Retry strategy\n */\n strategy: RetryStrategySchema.optional().default('exponential_backoff'),\n \n /**\n * Maximum retry attempts\n */\n maxAttempts: z.number().min(0).max(10).optional().default(3).describe('Maximum retry attempts'),\n \n /**\n * Initial delay in milliseconds\n */\n initialDelayMs: z.number().min(100).optional().default(1000).describe('Initial retry delay in ms'),\n \n /**\n * Maximum delay in milliseconds\n */\n maxDelayMs: z.number().min(1000).optional().default(60000).describe('Maximum retry delay in ms'),\n \n /**\n * Backoff multiplier (for exponential backoff)\n */\n backoffMultiplier: z.number().min(1).optional().default(2).describe('Exponential backoff multiplier'),\n \n /**\n * HTTP status codes to retry\n */\n retryableStatusCodes: z.array(z.number()).optional().default([408, 429, 500, 502, 503, 504]).describe('HTTP status codes to retry'),\n \n /**\n * Retry on network errors\n */\n retryOnNetworkError: z.boolean().optional().default(true).describe('Retry on network errors'),\n \n /**\n * Jitter to add randomness to retry delays\n */\n jitter: z.boolean().optional().default(true).describe('Add jitter to retry delays'),\n});\n\nexport type RetryConfig = z.infer;\n\n// ============================================================================\n// Error Mapping Configuration\n// ============================================================================\n\n/**\n * Error Category\n */\nexport const ErrorCategorySchema = z.enum([\n 'validation',\n 'authorization',\n 'not_found',\n 'conflict',\n 'rate_limit',\n 'timeout',\n 'server_error',\n 'integration_error',\n]).describe('Standard error category');\n\nexport type ErrorCategory = z.infer;\n\n/**\n * Error Mapping Rule\n * \n * Maps an external system error code to an ObjectStack standard error.\n */\nexport const ErrorMappingRuleSchema = z.object({\n sourceCode: z.union([z.string(), z.number()]).describe('External system error code'),\n sourceMessage: z.string().optional().describe('Pattern to match against error message'),\n targetCode: z.string().describe('ObjectStack standard error code'),\n targetCategory: ErrorCategorySchema.describe('Error category'),\n severity: z.enum(['low', 'medium', 'high', 'critical']).describe('Error severity level'),\n retryable: z.boolean().describe('Whether the error is retryable'),\n userMessage: z.string().optional().describe('Human-readable message to show users'),\n}).describe('Error mapping rule');\n\nexport type ErrorMappingRule = z.infer;\n\n/**\n * Error Mapping Configuration\n * \n * Configures how external system errors are mapped to ObjectStack standard errors.\n */\nexport const ErrorMappingConfigSchema = z.object({\n rules: z.array(ErrorMappingRuleSchema).describe('Error mapping rules'),\n defaultCategory: ErrorCategorySchema.optional().default('integration_error').describe('Default category for unmapped errors'),\n unmappedBehavior: z.enum(['passthrough', 'generic_error', 'throw']).describe('What to do with unmapped errors'),\n logUnmapped: z.boolean().optional().default(true).describe('Log unmapped errors'),\n}).describe('Error mapping configuration');\n\nexport type ErrorMappingConfig = z.infer;\n\n// ============================================================================\n// Health Check & Circuit Breaker Configuration\n// ============================================================================\n\n/**\n * Health Check Configuration\n * \n * Configures periodic health checks for connector endpoints.\n */\nexport const HealthCheckConfigSchema = z.object({\n enabled: z.boolean().describe('Enable health checks'),\n intervalMs: z.number().optional().default(60000).describe('Health check interval in milliseconds'),\n timeoutMs: z.number().optional().default(5000).describe('Health check timeout in milliseconds'),\n endpoint: z.string().optional().describe('Health check endpoint path'),\n method: z.enum(['GET', 'HEAD', 'OPTIONS']).optional().describe('HTTP method for health check'),\n expectedStatus: z.number().optional().default(200).describe('Expected HTTP status code'),\n unhealthyThreshold: z.number().optional().default(3).describe('Consecutive failures before marking unhealthy'),\n healthyThreshold: z.number().optional().default(1).describe('Consecutive successes before marking healthy'),\n}).describe('Health check configuration');\n\nexport type HealthCheckConfig = z.infer;\n\n/**\n * Circuit Breaker Configuration\n * \n * Implements the circuit breaker pattern to prevent cascading failures.\n */\nexport const CircuitBreakerConfigSchema = z.object({\n enabled: z.boolean().describe('Enable circuit breaker'),\n failureThreshold: z.number().optional().default(5).describe('Failures before opening circuit'),\n resetTimeoutMs: z.number().optional().default(30000).describe('Time in open state before half-open'),\n halfOpenMaxRequests: z.number().optional().default(1).describe('Requests allowed in half-open state'),\n monitoringWindow: z.number().optional().default(60000).describe('Rolling window for failure count in ms'),\n fallbackStrategy: z.enum(['cache', 'default_value', 'error', 'queue']).optional().describe('Fallback strategy when circuit is open'),\n}).describe('Circuit breaker configuration');\n\nexport type CircuitBreakerConfig = z.infer;\n\n/**\n * Connector Health Configuration\n * \n * Combines health check and circuit breaker for connector resilience.\n */\nexport const ConnectorHealthSchema = z.object({\n healthCheck: HealthCheckConfigSchema.optional().describe('Health check configuration'),\n circuitBreaker: CircuitBreakerConfigSchema.optional().describe('Circuit breaker configuration'),\n}).describe('Connector health configuration');\n\nexport type ConnectorHealth = z.infer;\n\n// ============================================================================\n// Base Connector Schema\n// ============================================================================\n\n/**\n * Connector Type\n */\nexport const ConnectorTypeSchema = z.enum([\n 'saas', // SaaS application connector\n 'database', // Database connector\n 'file_storage', // File storage connector\n 'message_queue', // Message queue connector\n 'api', // Generic REST/GraphQL API\n 'custom', // Custom connector\n]).describe('Connector type');\n\nexport type ConnectorType = z.infer;\n\n/**\n * Connector Status\n */\nexport const ConnectorStatusSchema = z.enum([\n 'active', // Connector is active and syncing\n 'inactive', // Connector is configured but disabled\n 'error', // Connector has errors\n 'configuring', // Connector is being set up\n]).describe('Connector status');\n\nexport type ConnectorStatus = z.infer;\n\n/**\n * Connector Action Definition\n */\nexport const ConnectorActionSchema = z.object({\n key: z.string().describe('Action key (machine name)'),\n label: z.string().describe('Human readable label'),\n description: z.string().optional(),\n inputSchema: z.record(z.string(), z.unknown()).optional().describe('Input parameters schema (JSON Schema)'),\n outputSchema: z.record(z.string(), z.unknown()).optional().describe('Output schema (JSON Schema)'),\n});\n\n/**\n * Connector Trigger Definition\n */\nexport const ConnectorTriggerSchema = z.object({\n key: z.string().describe('Trigger key'),\n label: z.string().describe('Trigger label'),\n description: z.string().optional(),\n type: z.enum(['polling', 'webhook']).describe('Trigger type'),\n interval: z.number().optional().describe('Polling interval in seconds'),\n});\n\n/**\n * Base Connector Schema\n * Core connector configuration shared across all connector types\n */\nexport const ConnectorSchema = z.object({\n /**\n * Machine name (snake_case)\n */\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Unique connector identifier'),\n \n /**\n * Human-readable label\n */\n label: z.string().describe('Display label'),\n \n /**\n * Connector type\n */\n type: ConnectorTypeSchema.describe('Connector type'),\n \n /**\n * Description\n */\n description: z.string().optional().describe('Connector description'),\n \n /**\n * Icon identifier\n */\n icon: z.string().optional().describe('Icon identifier'),\n \n /**\n * Authentication configuration\n */\n authentication: ConnectorAuthConfigSchema.describe('Authentication configuration'),\n\n /** Zapier-style Capabilities */\n actions: z.array(ConnectorActionSchema).optional(),\n triggers: z.array(ConnectorTriggerSchema).optional(),\n \n /**\n * Data synchronization configuration\n */\n syncConfig: DataSyncConfigSchema.optional().describe('Data sync configuration'),\n \n \n /**\n * Field mappings\n */\n fieldMappings: z.array(FieldMappingSchema).optional().describe('Field mapping rules'),\n \n /**\n * Webhook configuration\n */\n webhooks: z.array(WebhookConfigSchema).optional().describe('Webhook configurations'),\n \n /**\n * Rate limiting configuration\n */\n rateLimitConfig: RateLimitConfigSchema.optional().describe('Rate limiting configuration'),\n \n /**\n * Retry configuration\n */\n retryConfig: RetryConfigSchema.optional().describe('Retry configuration'),\n \n /**\n * Connection timeout in milliseconds\n */\n connectionTimeoutMs: z.number().min(1000).max(300000).optional().default(30000).describe('Connection timeout in ms'),\n \n /**\n * Request timeout in milliseconds\n */\n requestTimeoutMs: z.number().min(1000).max(300000).optional().default(30000).describe('Request timeout in ms'),\n \n /**\n * Connector status\n */\n status: ConnectorStatusSchema.optional().default('inactive').describe('Connector status'),\n \n /**\n * Enable connector\n */\n enabled: z.boolean().optional().default(true).describe('Enable connector'),\n \n /**\n * Error mapping configuration\n */\n errorMapping: ErrorMappingConfigSchema.optional().describe('Error mapping configuration'),\n \n /**\n * Health check and circuit breaker configuration\n */\n health: ConnectorHealthSchema.optional().describe('Health and resilience configuration'),\n \n /**\n * Custom metadata\n */\n metadata: z.record(z.string(), z.unknown()).optional().describe('Custom connector metadata'),\n});\n\nexport type Connector = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n FieldMappingSchema,\n} from '../connector.zod';\n\n/**\n * SaaS Connector Protocol Template\n * \n * Specialized connector for SaaS applications (Salesforce, HubSpot, Stripe, etc.)\n * Extends the base connector with SaaS-specific features like OAuth flows,\n * object type discovery, and API version management.\n */\n\n/**\n * SaaS Provider Types\n */\nexport const SaasProviderSchema = z.enum([\n 'salesforce',\n 'hubspot',\n 'stripe',\n 'shopify',\n 'zendesk',\n 'intercom',\n 'mailchimp',\n 'slack',\n 'microsoft_dynamics',\n 'servicenow',\n 'netsuite',\n 'custom',\n]).describe('SaaS provider type');\n\nexport type SaasProvider = z.infer;\n\n/**\n * API Version Configuration\n */\nexport const ApiVersionConfigSchema = z.object({\n version: z.string().describe('API version (e.g., \"v2\", \"2023-10-01\")'),\n isDefault: z.boolean().default(false).describe('Is this the default version'),\n deprecationDate: z.string().optional().describe('API version deprecation date (ISO 8601)'),\n sunsetDate: z.string().optional().describe('API version sunset date (ISO 8601)'),\n});\n\nexport type ApiVersionConfig = z.infer;\n\n/**\n * SaaS Object Type Schema\n * Represents a syncable entity in the SaaS system (e.g., Account, Contact, Deal)\n */\nexport const SaasObjectTypeSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Object type name (snake_case)'),\n label: z.string().describe('Display label'),\n apiName: z.string().describe('API name in external system'),\n enabled: z.boolean().default(true).describe('Enable sync for this object'),\n supportsCreate: z.boolean().default(true).describe('Supports record creation'),\n supportsUpdate: z.boolean().default(true).describe('Supports record updates'),\n supportsDelete: z.boolean().default(true).describe('Supports record deletion'),\n fieldMappings: z.array(FieldMappingSchema).optional().describe('Object-specific field mappings'),\n});\n\nexport type SaasObjectType = z.infer;\n\n/**\n * SaaS Connector Configuration Schema\n */\nexport const SaasConnectorSchema = ConnectorSchema.extend({\n type: z.literal('saas'),\n \n /**\n * SaaS provider\n */\n provider: SaasProviderSchema.describe('SaaS provider type'),\n \n /**\n * Base URL for API requests\n */\n baseUrl: z.string().url().describe('API base URL'),\n \n /**\n * API version configuration\n */\n apiVersion: ApiVersionConfigSchema.optional().describe('API version configuration'),\n \n /**\n * Supported object types to sync\n */\n objectTypes: z.array(SaasObjectTypeSchema).describe('Syncable object types'),\n \n /**\n * OAuth-specific settings\n */\n oauthSettings: z.object({\n scopes: z.array(z.string()).describe('Required OAuth scopes'),\n refreshTokenUrl: z.string().url().optional().describe('Token refresh endpoint'),\n revokeTokenUrl: z.string().url().optional().describe('Token revocation endpoint'),\n autoRefresh: z.boolean().default(true).describe('Automatically refresh expired tokens'),\n }).optional().describe('OAuth-specific configuration'),\n \n /**\n * Pagination settings\n */\n paginationConfig: z.object({\n type: z.enum(['cursor', 'offset', 'page']).default('cursor').describe('Pagination type'),\n defaultPageSize: z.number().min(1).max(1000).default(100).describe('Default page size'),\n maxPageSize: z.number().min(1).max(10000).default(1000).describe('Maximum page size'),\n }).optional().describe('Pagination configuration'),\n \n /**\n * Sandbox/test environment settings\n */\n sandboxConfig: z.object({\n enabled: z.boolean().default(false).describe('Use sandbox environment'),\n baseUrl: z.string().url().optional().describe('Sandbox API base URL'),\n }).optional().describe('Sandbox environment configuration'),\n \n /**\n * Custom request headers\n */\n customHeaders: z.record(z.string(), z.string()).optional().describe('Custom HTTP headers for all requests'),\n});\n\nexport type SaasConnector = z.infer;\nexport type SaaSConnector = SaasConnector; // Alias for alternative capitalization\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Salesforce Connector Configuration\n */\nexport const salesforceConnectorExample = {\n name: 'salesforce_production',\n label: 'Salesforce Production',\n type: 'saas',\n provider: 'salesforce',\n baseUrl: 'https://example.my.salesforce.com',\n apiVersion: {\n version: 'v59.0',\n isDefault: true,\n },\n authentication: {\n type: 'oauth2',\n clientId: '${SALESFORCE_CLIENT_ID}',\n clientSecret: '${SALESFORCE_CLIENT_SECRET}',\n authorizationUrl: 'https://login.salesforce.com/services/oauth2/authorize',\n tokenUrl: 'https://login.salesforce.com/services/oauth2/token',\n grantType: 'authorization_code',\n scopes: ['api', 'refresh_token', 'offline_access'],\n },\n objectTypes: [\n {\n name: 'account',\n label: 'Account',\n apiName: 'Account',\n enabled: true,\n supportsCreate: true,\n supportsUpdate: true,\n supportsDelete: true,\n },\n {\n name: 'contact',\n label: 'Contact',\n apiName: 'Contact',\n enabled: true,\n supportsCreate: true,\n supportsUpdate: true,\n supportsDelete: true,\n },\n ],\n syncConfig: {\n strategy: 'incremental',\n direction: 'bidirectional',\n schedule: '0 */6 * * *', // Every 6 hours\n realtimeSync: true,\n conflictResolution: 'latest_wins',\n batchSize: 200,\n deleteMode: 'soft_delete',\n },\n rateLimitConfig: {\n strategy: 'token_bucket',\n maxRequests: 100,\n windowSeconds: 20,\n respectUpstreamLimits: true,\n },\n retryConfig: {\n strategy: 'exponential_backoff',\n maxAttempts: 3,\n initialDelayMs: 1000,\n maxDelayMs: 30000,\n backoffMultiplier: 2,\n retryableStatusCodes: [408, 429, 500, 502, 503, 504],\n retryOnNetworkError: true,\n jitter: true,\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: HubSpot Connector Configuration\n */\nexport const hubspotConnectorExample = {\n name: 'hubspot_crm',\n label: 'HubSpot CRM',\n type: 'saas',\n provider: 'hubspot',\n baseUrl: 'https://api.hubapi.com',\n authentication: {\n type: 'api_key',\n apiKey: '${HUBSPOT_API_KEY}',\n headerName: 'Authorization',\n },\n objectTypes: [\n {\n name: 'company',\n label: 'Company',\n apiName: 'companies',\n enabled: true,\n supportsCreate: true,\n supportsUpdate: true,\n supportsDelete: true,\n },\n {\n name: 'deal',\n label: 'Deal',\n apiName: 'deals',\n enabled: true,\n supportsCreate: true,\n supportsUpdate: true,\n supportsDelete: true,\n },\n ],\n syncConfig: {\n strategy: 'incremental',\n direction: 'import',\n schedule: '0 */4 * * *', // Every 4 hours\n conflictResolution: 'source_wins',\n batchSize: 100,\n },\n rateLimitConfig: {\n strategy: 'token_bucket',\n maxRequests: 100,\n windowSeconds: 10,\n },\n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n FieldMappingSchema,\n} from '../connector.zod';\n\n/**\n * Database Connector Protocol Template\n * \n * Specialized connector for database systems (PostgreSQL, MySQL, SQL Server, etc.)\n * Extends the base connector with database-specific features like schema discovery,\n * CDC (Change Data Capture), and connection pooling.\n */\n\n/**\n * Database Provider Types\n */\nexport const DatabaseProviderSchema = z.enum([\n 'postgresql',\n 'mysql',\n 'mariadb',\n 'mssql',\n 'oracle',\n 'mongodb',\n 'redis',\n 'cassandra',\n 'snowflake',\n 'bigquery',\n 'redshift',\n 'custom',\n]).describe('Database provider type');\n\nexport type DatabaseProvider = z.infer;\n\n/**\n * Database Connection Pool Configuration\n */\nexport const DatabasePoolConfigSchema = z.object({\n min: z.number().min(0).default(2).describe('Minimum connections in pool'),\n max: z.number().min(1).default(10).describe('Maximum connections in pool'),\n idleTimeoutMs: z.number().min(1000).default(30000).describe('Idle connection timeout in ms'),\n connectionTimeoutMs: z.number().min(1000).default(10000).describe('Connection establishment timeout in ms'),\n acquireTimeoutMs: z.number().min(1000).default(30000).describe('Connection acquisition timeout in ms'),\n evictionRunIntervalMs: z.number().min(1000).default(30000).describe('Connection eviction check interval in ms'),\n testOnBorrow: z.boolean().default(true).describe('Test connection before use'),\n});\n\nexport type DatabasePoolConfig = z.infer;\n\n/**\n * SSL/TLS Configuration\n */\nexport const SslConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable SSL/TLS'),\n rejectUnauthorized: z.boolean().default(true).describe('Reject unauthorized certificates'),\n ca: z.string().optional().describe('Certificate Authority certificate'),\n cert: z.string().optional().describe('Client certificate'),\n key: z.string().optional().describe('Client private key'),\n});\n\nexport type SslConfig = z.infer;\n\n/**\n * Change Data Capture (CDC) Configuration\n */\nexport const CdcConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable CDC'),\n \n method: z.enum([\n 'log_based', // Transaction log parsing (e.g., PostgreSQL logical replication)\n 'trigger_based', // Database triggers for change tracking\n 'query_based', // Timestamp-based queries\n 'custom', // Custom CDC implementation\n ]).describe('CDC method'),\n \n slotName: z.string().optional().describe('Replication slot name (for log-based CDC)'),\n \n publicationName: z.string().optional().describe('Publication name (for PostgreSQL)'),\n \n startPosition: z.string().optional().describe('Starting position/LSN for CDC stream'),\n \n batchSize: z.number().min(1).max(10000).default(1000).describe('CDC batch size'),\n \n pollIntervalMs: z.number().min(100).default(1000).describe('CDC polling interval in ms'),\n});\n\nexport type CdcConfig = z.infer;\n\n/**\n * Database Table Configuration\n */\nexport const DatabaseTableSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Table name in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n schema: z.string().optional().describe('Database schema name'),\n tableName: z.string().describe('Actual table name in database'),\n primaryKey: z.string().describe('Primary key column'),\n enabled: z.boolean().default(true).describe('Enable sync for this table'),\n fieldMappings: z.array(FieldMappingSchema).optional().describe('Table-specific field mappings'),\n whereClause: z.string().optional().describe('SQL WHERE clause for filtering'),\n});\n\nexport type DatabaseTable = z.infer;\n\n/**\n * Database Connector Configuration Schema\n */\nexport const DatabaseConnectorSchema = ConnectorSchema.extend({\n type: z.literal('database'),\n \n /**\n * Database provider\n */\n provider: DatabaseProviderSchema.describe('Database provider type'),\n \n /**\n * Connection configuration\n */\n connectionConfig: z.object({\n host: z.string().describe('Database host'),\n port: z.number().min(1).max(65535).describe('Database port'),\n database: z.string().describe('Database name'),\n username: z.string().describe('Database username'),\n password: z.string().describe('Database password (typically from ENV)'),\n options: z.record(z.string(), z.unknown()).optional().describe('Driver-specific connection options'),\n }).describe('Database connection configuration'),\n \n /**\n * Connection pool configuration\n */\n poolConfig: DatabasePoolConfigSchema.optional().describe('Connection pool configuration'),\n \n /**\n * SSL/TLS configuration\n */\n sslConfig: SslConfigSchema.optional().describe('SSL/TLS configuration'),\n \n /**\n * Tables to sync\n */\n tables: z.array(DatabaseTableSchema).describe('Tables to sync'),\n \n /**\n * Change Data Capture configuration\n */\n cdcConfig: CdcConfigSchema.optional().describe('CDC configuration'),\n \n /**\n * Read replica configuration\n */\n readReplicaConfig: z.object({\n enabled: z.boolean().default(false).describe('Use read replicas'),\n hosts: z.array(z.object({\n host: z.string().describe('Replica host'),\n port: z.number().min(1).max(65535).describe('Replica port'),\n weight: z.number().min(0).max(1).default(1).describe('Load balancing weight'),\n })).describe('Read replica hosts'),\n }).optional().describe('Read replica configuration'),\n \n /**\n * Query timeout\n */\n queryTimeoutMs: z.number().min(1000).max(300000).optional().default(30000).describe('Query timeout in ms'),\n \n /**\n * Enable query logging\n */\n enableQueryLogging: z.boolean().optional().default(false).describe('Enable SQL query logging'),\n});\n\nexport type DatabaseConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: PostgreSQL Connector Configuration\n */\nexport const postgresConnectorExample = {\n name: 'postgres_production',\n label: 'Production PostgreSQL',\n type: 'database',\n provider: 'postgresql',\n authentication: {\n type: 'basic',\n username: '${DB_USERNAME}',\n password: '${DB_PASSWORD}',\n },\n connectionConfig: {\n host: 'db.example.com',\n port: 5432,\n database: 'production',\n username: '${DB_USERNAME}',\n password: '${DB_PASSWORD}',\n },\n poolConfig: {\n min: 2,\n max: 20,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 10000,\n acquireTimeoutMs: 30000,\n evictionRunIntervalMs: 30000,\n testOnBorrow: true,\n },\n sslConfig: {\n enabled: true,\n rejectUnauthorized: true,\n },\n tables: [\n {\n name: 'customer',\n label: 'Customer',\n schema: 'public',\n tableName: 'customers',\n primaryKey: 'id',\n enabled: true,\n },\n {\n name: 'order',\n label: 'Order',\n schema: 'public',\n tableName: 'orders',\n primaryKey: 'id',\n enabled: true,\n whereClause: 'status != \\'archived\\'',\n },\n ],\n cdcConfig: {\n enabled: true,\n method: 'log_based',\n slotName: 'objectstack_replication_slot',\n publicationName: 'objectstack_publication',\n batchSize: 1000,\n pollIntervalMs: 1000,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'bidirectional',\n realtimeSync: true,\n conflictResolution: 'latest_wins',\n batchSize: 1000,\n deleteMode: 'soft_delete',\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: MongoDB Connector Configuration\n */\nexport const mongoConnectorExample = {\n name: 'mongodb_analytics',\n label: 'MongoDB Analytics',\n type: 'database',\n provider: 'mongodb',\n authentication: {\n type: 'basic',\n username: '${MONGO_USERNAME}',\n password: '${MONGO_PASSWORD}',\n },\n connectionConfig: {\n host: 'mongodb.example.com',\n port: 27017,\n database: 'analytics',\n username: '${MONGO_USERNAME}',\n password: '${MONGO_PASSWORD}',\n options: {\n authSource: 'admin',\n replicaSet: 'rs0',\n },\n },\n tables: [\n {\n name: 'event',\n label: 'Event',\n tableName: 'events',\n primaryKey: 'id',\n enabled: true,\n },\n ],\n cdcConfig: {\n enabled: true,\n method: 'log_based',\n batchSize: 1000,\n pollIntervalMs: 500,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'import',\n batchSize: 1000,\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Snowflake Connector Configuration\n */\nexport const snowflakeConnectorExample = {\n name: 'snowflake_warehouse',\n label: 'Snowflake Data Warehouse',\n type: 'database',\n provider: 'snowflake',\n authentication: {\n type: 'basic',\n username: '${SNOWFLAKE_USERNAME}',\n password: '${SNOWFLAKE_PASSWORD}',\n },\n connectionConfig: {\n host: 'account.snowflakecomputing.com',\n port: 443,\n database: 'ANALYTICS_DB',\n username: '${SNOWFLAKE_USERNAME}',\n password: '${SNOWFLAKE_PASSWORD}',\n options: {\n warehouse: 'COMPUTE_WH',\n schema: 'PUBLIC',\n role: 'ANALYST',\n },\n },\n tables: [\n {\n name: 'sales_summary',\n label: 'Sales Summary',\n schema: 'PUBLIC',\n tableName: 'SALES_SUMMARY',\n primaryKey: 'ID',\n enabled: true,\n },\n ],\n syncConfig: {\n strategy: 'full',\n direction: 'import',\n schedule: '0 2 * * *', // Daily at 2 AM\n batchSize: 5000,\n },\n queryTimeoutMs: 60000,\n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n} from '../connector.zod';\n\n/**\n * File Storage Connector Protocol Template\n * \n * Specialized connector for file storage systems (S3, Azure Blob, Google Cloud Storage, etc.)\n * Extends the base connector with file-specific features like multipart uploads,\n * versioning, and metadata extraction.\n */\n\n/**\n * File Storage Provider Types\n */\nexport const FileStorageProviderSchema = z.enum([\n 's3', // Amazon S3\n 'azure_blob', // Azure Blob Storage\n 'gcs', // Google Cloud Storage\n 'dropbox', // Dropbox\n 'box', // Box\n 'onedrive', // Microsoft OneDrive\n 'google_drive', // Google Drive\n 'sharepoint', // SharePoint\n 'ftp', // FTP/SFTP\n 'local', // Local file system\n 'custom', // Custom file storage\n]).describe('File storage provider type');\n\nexport type FileStorageProvider = z.infer;\n\n/**\n * File Access Pattern\n */\nexport const FileAccessPatternSchema = z.enum([\n 'public_read', // Public read access\n 'private', // Private access\n 'authenticated_read', // Requires authentication\n 'bucket_owner_read', // Bucket owner has read access\n 'bucket_owner_full', // Bucket owner has full control\n]).describe('File access pattern');\n\nexport type FileAccessPattern = z.infer;\n\n/**\n * File Metadata Configuration\n */\nexport const FileMetadataConfigSchema = z.object({\n extractMetadata: z.boolean().default(true).describe('Extract file metadata'),\n \n metadataFields: z.array(z.enum([\n 'content_type',\n 'file_size',\n 'last_modified',\n 'etag',\n 'checksum',\n 'creator',\n 'created_at',\n 'custom',\n ])).optional().describe('Metadata fields to extract'),\n \n customMetadata: z.record(z.string(), z.string()).optional().describe('Custom metadata key-value pairs'),\n});\n\nexport type FileMetadataConfig = z.infer;\n\n/**\n * Multipart Upload Configuration\n */\nexport const MultipartUploadConfigSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable multipart uploads'),\n \n partSize: z.number().min(5 * 1024 * 1024).default(5 * 1024 * 1024).describe('Part size in bytes (min 5MB)'),\n \n maxConcurrentParts: z.number().min(1).max(10).default(5).describe('Maximum concurrent part uploads'),\n \n threshold: z.number().min(5 * 1024 * 1024).default(100 * 1024 * 1024).describe('File size threshold for multipart upload in bytes'),\n});\n\nexport type MultipartUploadConfig = z.infer;\n\n/**\n * File Versioning Configuration\n */\nexport const FileVersioningConfigSchema = z.object({\n enabled: z.boolean().default(false).describe('Enable file versioning'),\n \n maxVersions: z.number().min(1).max(100).optional().describe('Maximum versions to retain'),\n \n retentionDays: z.number().min(1).optional().describe('Version retention period in days'),\n});\n\nexport type FileVersioningConfig = z.infer;\n\n/**\n * File Filter Configuration\n */\nexport const FileFilterConfigSchema = z.object({\n includePatterns: z.array(z.string()).optional().describe('File patterns to include (glob)'),\n \n excludePatterns: z.array(z.string()).optional().describe('File patterns to exclude (glob)'),\n \n minFileSize: z.number().min(0).optional().describe('Minimum file size in bytes'),\n \n maxFileSize: z.number().min(1).optional().describe('Maximum file size in bytes'),\n \n allowedExtensions: z.array(z.string()).optional().describe('Allowed file extensions'),\n \n blockedExtensions: z.array(z.string()).optional().describe('Blocked file extensions'),\n});\n\nexport type FileFilterConfig = z.infer;\n\n/**\n * File Storage Bucket/Container Configuration\n */\nexport const StorageBucketSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Bucket identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n bucketName: z.string().describe('Actual bucket/container name in storage system'),\n region: z.string().optional().describe('Storage region'),\n enabled: z.boolean().default(true).describe('Enable sync for this bucket'),\n prefix: z.string().optional().describe('Prefix/path within bucket'),\n accessPattern: FileAccessPatternSchema.optional().describe('Access pattern'),\n fileFilters: FileFilterConfigSchema.optional().describe('File filter configuration'),\n});\n\nexport type StorageBucket = z.infer;\n\n/**\n * File Storage Connector Configuration Schema\n */\nexport const FileStorageConnectorSchema = ConnectorSchema.extend({\n type: z.literal('file_storage'),\n \n /**\n * File storage provider\n */\n provider: FileStorageProviderSchema.describe('File storage provider type'),\n \n /**\n * Storage configuration\n */\n storageConfig: z.object({\n endpoint: z.string().url().optional().describe('Custom endpoint URL'),\n region: z.string().optional().describe('Default region'),\n pathStyle: z.boolean().optional().default(false).describe('Use path-style URLs (for S3-compatible)'),\n }).optional().describe('Storage configuration'),\n \n /**\n * Buckets/containers to sync\n */\n buckets: z.array(StorageBucketSchema).describe('Buckets/containers to sync'),\n \n /**\n * File metadata configuration\n */\n metadataConfig: FileMetadataConfigSchema.optional().describe('Metadata extraction configuration'),\n \n /**\n * Multipart upload configuration\n */\n multipartConfig: MultipartUploadConfigSchema.optional().describe('Multipart upload configuration'),\n \n /**\n * File versioning configuration\n */\n versioningConfig: FileVersioningConfigSchema.optional().describe('File versioning configuration'),\n \n /**\n * Enable server-side encryption\n */\n encryption: z.object({\n enabled: z.boolean().default(false).describe('Enable server-side encryption'),\n algorithm: z.enum(['AES256', 'aws:kms', 'custom']).optional().describe('Encryption algorithm'),\n kmsKeyId: z.string().optional().describe('KMS key ID (for aws:kms)'),\n }).optional().describe('Encryption configuration'),\n \n /**\n * Lifecycle policy\n */\n lifecyclePolicy: z.object({\n enabled: z.boolean().default(false).describe('Enable lifecycle policy'),\n deleteAfterDays: z.number().min(1).optional().describe('Delete files after N days'),\n archiveAfterDays: z.number().min(1).optional().describe('Archive files after N days'),\n }).optional().describe('Lifecycle policy'),\n \n /**\n * Content processing configuration\n */\n contentProcessing: z.object({\n extractText: z.boolean().default(false).describe('Extract text from documents'),\n generateThumbnails: z.boolean().default(false).describe('Generate image thumbnails'),\n thumbnailSizes: z.array(z.object({\n width: z.number().min(1),\n height: z.number().min(1),\n })).optional().describe('Thumbnail sizes'),\n virusScan: z.boolean().default(false).describe('Scan for viruses'),\n }).optional().describe('Content processing configuration'),\n \n /**\n * Download/upload buffer size\n */\n bufferSize: z.number().min(1024).default(64 * 1024).describe('Buffer size in bytes'),\n \n /**\n * Enable transfer acceleration (for supported providers)\n */\n transferAcceleration: z.boolean().default(false).describe('Enable transfer acceleration'),\n});\n\nexport type FileStorageConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Amazon S3 Connector Configuration\n */\nexport const s3ConnectorExample = {\n name: 's3_production_assets',\n label: 'Production S3 Assets',\n type: 'file_storage',\n provider: 's3',\n authentication: {\n type: 'api_key',\n apiKey: '${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}',\n headerName: 'Authorization',\n },\n storageConfig: {\n region: 'us-east-1',\n pathStyle: false,\n },\n buckets: [\n {\n name: 'product_images',\n label: 'Product Images',\n bucketName: 'my-company-product-images',\n region: 'us-east-1',\n enabled: true,\n prefix: 'products/',\n accessPattern: 'public_read',\n fileFilters: {\n allowedExtensions: ['.jpg', '.jpeg', '.png', '.webp'],\n maxFileSize: 10 * 1024 * 1024, // 10MB\n },\n },\n {\n name: 'customer_documents',\n label: 'Customer Documents',\n bucketName: 'my-company-customer-docs',\n region: 'us-east-1',\n enabled: true,\n accessPattern: 'private',\n fileFilters: {\n allowedExtensions: ['.pdf', '.docx', '.xlsx'],\n maxFileSize: 50 * 1024 * 1024, // 50MB\n },\n },\n ],\n metadataConfig: {\n extractMetadata: true,\n metadataFields: ['content_type', 'file_size', 'last_modified', 'etag'],\n },\n multipartConfig: {\n enabled: true,\n partSize: 5 * 1024 * 1024, // 5MB\n maxConcurrentParts: 5,\n threshold: 100 * 1024 * 1024, // 100MB\n },\n versioningConfig: {\n enabled: true,\n maxVersions: 10,\n },\n encryption: {\n enabled: true,\n algorithm: 'aws:kms',\n kmsKeyId: '${AWS_KMS_KEY_ID}',\n },\n contentProcessing: {\n extractText: true,\n generateThumbnails: true,\n thumbnailSizes: [\n { width: 150, height: 150 },\n { width: 300, height: 300 },\n { width: 600, height: 600 },\n ],\n virusScan: true,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'bidirectional',\n realtimeSync: true,\n conflictResolution: 'latest_wins',\n batchSize: 100,\n },\n transferAcceleration: true,\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Google Drive Connector Configuration\n */\nexport const googleDriveConnectorExample = {\n name: 'google_drive_team',\n label: 'Google Drive Team Folder',\n type: 'file_storage',\n provider: 'google_drive',\n authentication: {\n type: 'oauth2',\n clientId: '${GOOGLE_CLIENT_ID}',\n clientSecret: '${GOOGLE_CLIENT_SECRET}',\n authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n tokenUrl: 'https://oauth2.googleapis.com/token',\n grantType: 'authorization_code',\n scopes: ['https://www.googleapis.com/auth/drive.file'],\n },\n buckets: [\n {\n name: 'team_drive',\n label: 'Team Drive',\n bucketName: 'shared-team-drive',\n enabled: true,\n fileFilters: {\n excludePatterns: ['*.tmp', '~$*'],\n },\n },\n ],\n metadataConfig: {\n extractMetadata: true,\n metadataFields: ['content_type', 'file_size', 'last_modified', 'creator', 'created_at'],\n },\n versioningConfig: {\n enabled: true,\n maxVersions: 5,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'bidirectional',\n realtimeSync: true,\n conflictResolution: 'latest_wins',\n batchSize: 50,\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Azure Blob Storage Connector Configuration\n */\nexport const azureBlobConnectorExample = {\n name: 'azure_blob_storage',\n label: 'Azure Blob Storage',\n type: 'file_storage',\n provider: 'azure_blob',\n authentication: {\n type: 'api_key',\n apiKey: '${AZURE_STORAGE_ACCOUNT_KEY}',\n headerName: 'x-ms-blob-type',\n },\n storageConfig: {\n endpoint: 'https://myaccount.blob.core.windows.net',\n },\n buckets: [\n {\n name: 'archive_container',\n label: 'Archive Container',\n bucketName: 'archive',\n enabled: true,\n accessPattern: 'private',\n },\n ],\n metadataConfig: {\n extractMetadata: true,\n metadataFields: ['content_type', 'file_size', 'last_modified', 'etag'],\n },\n encryption: {\n enabled: true,\n algorithm: 'AES256',\n },\n lifecyclePolicy: {\n enabled: true,\n archiveAfterDays: 90,\n deleteAfterDays: 365,\n },\n syncConfig: {\n strategy: 'incremental',\n direction: 'import',\n schedule: '0 1 * * *', // Daily at 1 AM\n batchSize: 200,\n },\n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n} from '../connector.zod';\n\n/**\n * Message Queue Connector Protocol Template\n * \n * Specialized connector for message queue systems (RabbitMQ, Kafka, SQS, etc.)\n * Extends the base connector with message queue-specific features like topics,\n * consumer groups, and message acknowledgment patterns.\n */\n\n/**\n * Message Queue Provider Types\n */\nexport const MessageQueueProviderSchema = z.enum([\n 'rabbitmq', // RabbitMQ\n 'kafka', // Apache Kafka\n 'redis_pubsub', // Redis Pub/Sub\n 'redis_streams', // Redis Streams\n 'aws_sqs', // Amazon SQS\n 'aws_sns', // Amazon SNS\n 'google_pubsub', // Google Cloud Pub/Sub\n 'azure_service_bus', // Azure Service Bus\n 'azure_event_hubs', // Azure Event Hubs\n 'nats', // NATS\n 'pulsar', // Apache Pulsar\n 'activemq', // Apache ActiveMQ\n 'custom', // Custom message queue\n]).describe('Message queue provider type');\n\nexport type MessageQueueProvider = z.infer;\n\n/**\n * Message Format\n */\nexport const MessageFormatSchema = z.enum([\n 'json',\n 'xml',\n 'protobuf',\n 'avro',\n 'text',\n 'binary',\n]).describe('Message format/serialization');\n\nexport type MessageFormat = z.infer;\n\n/**\n * Message Acknowledgment Mode\n */\nexport const AckModeSchema = z.enum([\n 'auto', // Auto-acknowledge\n 'manual', // Manual acknowledge after processing\n 'client', // Client-controlled acknowledge\n]).describe('Message acknowledgment mode');\n\nexport type AckMode = z.infer;\n\n/**\n * Delivery Guarantee\n */\nexport const DeliveryGuaranteeSchema = z.enum([\n 'at_most_once', // Fire and forget\n 'at_least_once', // May deliver duplicates\n 'exactly_once', // Guaranteed exactly once delivery\n]).describe('Message delivery guarantee');\n\nexport type DeliveryGuarantee = z.infer;\n\n/**\n * Consumer Configuration\n */\nexport const ConsumerConfigSchema = z.object({\n enabled: z.boolean().optional().default(true).describe('Enable consumer'),\n \n consumerGroup: z.string().optional().describe('Consumer group ID'),\n \n concurrency: z.number().min(1).max(100).optional().default(1).describe('Number of concurrent consumers'),\n \n prefetchCount: z.number().min(1).max(1000).optional().default(10).describe('Prefetch count'),\n \n ackMode: AckModeSchema.optional().default('manual'),\n \n autoCommit: z.boolean().optional().default(false).describe('Auto-commit offsets'),\n \n autoCommitIntervalMs: z.number().min(100).optional().default(5000).describe('Auto-commit interval in ms'),\n \n sessionTimeoutMs: z.number().min(1000).optional().default(30000).describe('Session timeout in ms'),\n \n rebalanceTimeoutMs: z.number().min(1000).optional().describe('Rebalance timeout in ms'),\n});\n\nexport type ConsumerConfig = z.infer;\n\n/**\n * Producer Configuration\n */\nexport const ProducerConfigSchema = z.object({\n enabled: z.boolean().optional().default(true).describe('Enable producer'),\n \n acks: z.enum(['0', '1', 'all']).optional().default('all').describe('Acknowledgment level'),\n \n compressionType: z.enum(['none', 'gzip', 'snappy', 'lz4', 'zstd']).optional().default('none').describe('Compression type'),\n \n batchSize: z.number().min(1).optional().default(16384).describe('Batch size in bytes'),\n \n lingerMs: z.number().min(0).optional().default(0).describe('Linger time in ms'),\n \n maxInFlightRequests: z.number().min(1).optional().default(5).describe('Max in-flight requests'),\n \n idempotence: z.boolean().optional().default(true).describe('Enable idempotent producer'),\n \n transactional: z.boolean().optional().default(false).describe('Enable transactional producer'),\n \n transactionTimeoutMs: z.number().min(1000).optional().describe('Transaction timeout in ms'),\n});\n\nexport type ProducerConfig = z.infer;\n\n/**\n * Dead Letter Queue Configuration\n */\nexport const DlqConfigSchema = z.object({\n enabled: z.boolean().optional().default(false).describe('Enable DLQ'),\n \n queueName: z.string().describe('Dead letter queue/topic name'),\n \n maxRetries: z.number().min(0).max(100).optional().default(3).describe('Max retries before DLQ'),\n \n retryDelayMs: z.number().min(0).optional().default(60000).describe('Retry delay in ms'),\n});\n\nexport type DlqConfig = z.infer;\n\n/**\n * Topic/Queue Configuration\n */\nexport const TopicQueueSchema = z.object({\n name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Topic/queue identifier in ObjectStack (snake_case)'),\n label: z.string().describe('Display label'),\n topicName: z.string().describe('Actual topic/queue name in message queue system'),\n enabled: z.boolean().optional().default(true).describe('Enable sync for this topic/queue'),\n \n /**\n * Consumer or Producer\n */\n mode: z.enum(['consumer', 'producer', 'both']).optional().default('both').describe('Consumer, producer, or both'),\n \n /**\n * Message format\n */\n messageFormat: MessageFormatSchema.optional().default('json'),\n \n /**\n * Partition/shard configuration\n */\n partitions: z.number().min(1).optional().describe('Number of partitions (for Kafka)'),\n \n /**\n * Replication factor\n */\n replicationFactor: z.number().min(1).optional().describe('Replication factor (for Kafka)'),\n \n /**\n * Consumer configuration\n */\n consumerConfig: ConsumerConfigSchema.optional().describe('Consumer-specific configuration'),\n \n /**\n * Producer configuration\n */\n producerConfig: ProducerConfigSchema.optional().describe('Producer-specific configuration'),\n \n /**\n * Dead letter queue configuration\n */\n dlqConfig: DlqConfigSchema.optional().describe('Dead letter queue configuration'),\n \n /**\n * Message routing key (for RabbitMQ)\n */\n routingKey: z.string().optional().describe('Routing key pattern'),\n \n /**\n * Message filter\n */\n messageFilter: z.object({\n headers: z.record(z.string(), z.string()).optional().describe('Filter by message headers'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Filter by message attributes'),\n }).optional().describe('Message filter criteria'),\n});\n\nexport type TopicQueue = z.infer;\n\n/**\n * Message Queue Connector Configuration Schema\n */\nexport const MessageQueueConnectorSchema = ConnectorSchema.extend({\n type: z.literal('message_queue'),\n \n /**\n * Message queue provider\n */\n provider: MessageQueueProviderSchema.describe('Message queue provider type'),\n \n /**\n * Broker configuration\n */\n brokerConfig: z.object({\n brokers: z.array(z.string()).describe('Broker addresses (host:port)'),\n clientId: z.string().optional().describe('Client ID'),\n connectionTimeoutMs: z.number().min(1000).optional().default(30000).describe('Connection timeout in ms'),\n requestTimeoutMs: z.number().min(1000).optional().default(30000).describe('Request timeout in ms'),\n }).describe('Broker connection configuration'),\n \n /**\n * Topics/queues to sync\n */\n topics: z.array(TopicQueueSchema).describe('Topics/queues to sync'),\n \n /**\n * Delivery guarantee\n */\n deliveryGuarantee: DeliveryGuaranteeSchema.optional().default('at_least_once'),\n \n /**\n * SSL/TLS configuration\n */\n sslConfig: z.object({\n enabled: z.boolean().optional().default(false).describe('Enable SSL/TLS'),\n rejectUnauthorized: z.boolean().optional().default(true).describe('Reject unauthorized certificates'),\n ca: z.string().optional().describe('CA certificate'),\n cert: z.string().optional().describe('Client certificate'),\n key: z.string().optional().describe('Client private key'),\n }).optional().describe('SSL/TLS configuration'),\n \n /**\n * SASL authentication (for Kafka)\n */\n saslConfig: z.object({\n mechanism: z.enum(['plain', 'scram-sha-256', 'scram-sha-512', 'aws']).describe('SASL mechanism'),\n username: z.string().optional().describe('SASL username'),\n password: z.string().optional().describe('SASL password'),\n }).optional().describe('SASL authentication configuration'),\n \n /**\n * Schema registry configuration (for Kafka/Avro)\n */\n schemaRegistry: z.object({\n url: z.string().url().describe('Schema registry URL'),\n auth: z.object({\n username: z.string().optional(),\n password: z.string().optional(),\n }).optional(),\n }).optional().describe('Schema registry configuration'),\n \n /**\n * Message ordering\n */\n preserveOrder: z.boolean().optional().default(true).describe('Preserve message ordering'),\n \n /**\n * Enable metrics\n */\n enableMetrics: z.boolean().optional().default(true).describe('Enable message queue metrics'),\n \n /**\n * Enable distributed tracing\n */\n enableTracing: z.boolean().optional().default(false).describe('Enable distributed tracing'),\n});\n\nexport type MessageQueueConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Apache Kafka Connector Configuration\n */\nexport const kafkaConnectorExample = {\n name: 'kafka_production',\n label: 'Production Kafka Cluster',\n type: 'message_queue',\n provider: 'kafka',\n authentication: {\n type: 'none',\n },\n brokerConfig: {\n brokers: ['kafka-1.example.com:9092', 'kafka-2.example.com:9092', 'kafka-3.example.com:9092'],\n clientId: 'objectstack-client',\n connectionTimeoutMs: 30000,\n requestTimeoutMs: 30000,\n },\n topics: [\n {\n name: 'order_events',\n label: 'Order Events',\n topicName: 'orders',\n enabled: true,\n mode: 'consumer',\n messageFormat: 'json',\n partitions: 10,\n replicationFactor: 3,\n consumerConfig: {\n enabled: true,\n consumerGroup: 'objectstack-consumer-group',\n concurrency: 5,\n prefetchCount: 100,\n ackMode: 'manual',\n autoCommit: false,\n sessionTimeoutMs: 30000,\n },\n dlqConfig: {\n enabled: true,\n queueName: 'orders-dlq',\n maxRetries: 3,\n retryDelayMs: 60000,\n },\n },\n {\n name: 'user_activity',\n label: 'User Activity',\n topicName: 'user-activity',\n enabled: true,\n mode: 'producer',\n messageFormat: 'json',\n partitions: 5,\n replicationFactor: 3,\n producerConfig: {\n enabled: true,\n acks: 'all',\n compressionType: 'snappy',\n batchSize: 16384,\n lingerMs: 10,\n maxInFlightRequests: 5,\n idempotence: true,\n },\n },\n ],\n deliveryGuarantee: 'at_least_once',\n saslConfig: {\n mechanism: 'scram-sha-256',\n username: '${KAFKA_USERNAME}',\n password: '${KAFKA_PASSWORD}',\n },\n sslConfig: {\n enabled: true,\n rejectUnauthorized: true,\n },\n preserveOrder: true,\n enableMetrics: true,\n enableTracing: true,\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: RabbitMQ Connector Configuration\n */\nexport const rabbitmqConnectorExample = {\n name: 'rabbitmq_events',\n label: 'RabbitMQ Event Bus',\n type: 'message_queue',\n provider: 'rabbitmq',\n authentication: {\n type: 'basic',\n username: '${RABBITMQ_USERNAME}',\n password: '${RABBITMQ_PASSWORD}',\n },\n brokerConfig: {\n brokers: ['amqp://rabbitmq.example.com:5672'],\n clientId: 'objectstack-rabbitmq-client',\n },\n topics: [\n {\n name: 'notifications',\n label: 'Notifications',\n topicName: 'notifications',\n enabled: true,\n mode: 'both',\n messageFormat: 'json',\n routingKey: 'notification.*',\n consumerConfig: {\n enabled: true,\n prefetchCount: 10,\n ackMode: 'manual',\n },\n producerConfig: {\n enabled: true,\n },\n dlqConfig: {\n enabled: true,\n queueName: 'notifications-dlq',\n maxRetries: 3,\n retryDelayMs: 30000,\n },\n },\n ],\n deliveryGuarantee: 'at_least_once',\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: AWS SQS Connector Configuration\n */\nexport const sqsConnectorExample = {\n name: 'aws_sqs_queue',\n label: 'AWS SQS Queue',\n type: 'message_queue',\n provider: 'aws_sqs',\n authentication: {\n type: 'api_key',\n apiKey: '${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}',\n headerName: 'Authorization',\n },\n brokerConfig: {\n brokers: ['https://sqs.us-east-1.amazonaws.com'],\n },\n topics: [\n {\n name: 'task_queue',\n label: 'Task Queue',\n topicName: 'task-queue',\n enabled: true,\n mode: 'consumer',\n messageFormat: 'json',\n consumerConfig: {\n enabled: true,\n concurrency: 10,\n prefetchCount: 10,\n ackMode: 'manual',\n },\n dlqConfig: {\n enabled: true,\n queueName: 'task-queue-dlq',\n maxRetries: 3,\n retryDelayMs: 120000,\n },\n },\n ],\n deliveryGuarantee: 'at_least_once',\n retryConfig: {\n strategy: 'exponential_backoff',\n maxAttempts: 3,\n initialDelayMs: 1000,\n maxDelayMs: 60000,\n backoffMultiplier: 2,\n },\n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Google Cloud Pub/Sub Connector Configuration\n */\nexport const pubsubConnectorExample = {\n name: 'gcp_pubsub',\n label: 'Google Cloud Pub/Sub',\n type: 'message_queue',\n provider: 'google_pubsub',\n authentication: {\n type: 'oauth2',\n clientId: '${GCP_CLIENT_ID}',\n clientSecret: '${GCP_CLIENT_SECRET}',\n authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n tokenUrl: 'https://oauth2.googleapis.com/token',\n grantType: 'client_credentials',\n scopes: ['https://www.googleapis.com/auth/pubsub'],\n },\n brokerConfig: {\n brokers: ['pubsub.googleapis.com'],\n },\n topics: [\n {\n name: 'analytics_events',\n label: 'Analytics Events',\n topicName: 'projects/my-project/topics/analytics-events',\n enabled: true,\n mode: 'both',\n messageFormat: 'json',\n consumerConfig: {\n enabled: true,\n consumerGroup: 'objectstack-subscription',\n concurrency: 5,\n prefetchCount: 100,\n ackMode: 'manual',\n },\n },\n ],\n deliveryGuarantee: 'at_least_once',\n enableMetrics: true,\n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n} from '../connector.zod';\n\n/**\n * GitHub Connector Protocol\n * \n * Specialized connector for GitHub integration enabling automated\n * version control operations, CI/CD workflows, and release management.\n * \n * Use Cases:\n * - Automated code commits and pull requests\n * - GitHub Actions workflow management\n * - Issue and project tracking\n * - Release and tag management\n * - Repository administration\n * \n * @example\n * ```typescript\n * import { GitHubConnector } from '@objectstack/spec/integration';\n * \n * const githubConnector: GitHubConnector = {\n * name: 'github_enterprise',\n * label: 'GitHub Enterprise',\n * type: 'saas',\n * provider: 'github',\n * baseUrl: 'https://api.github.com',\n * authentication: {\n * type: 'oauth2',\n * clientId: '${GITHUB_CLIENT_ID}',\n * clientSecret: '${GITHUB_CLIENT_SECRET}',\n * authorizationUrl: 'https://github.com/login/oauth/authorize',\n * tokenUrl: 'https://github.com/login/oauth/access_token',\n * grantType: 'authorization_code',\n * scopes: ['repo', 'workflow', 'admin:org'],\n * },\n * repositories: [\n * {\n * owner: 'objectstack-ai',\n * name: 'spec',\n * defaultBranch: 'main',\n * autoMerge: false,\n * },\n * ],\n * };\n * ```\n */\n\n/**\n * GitHub Provider Type\n */\nexport const GitHubProviderSchema = z.enum([\n 'github', // GitHub.com\n 'github_enterprise', // GitHub Enterprise Server\n]).describe('GitHub provider type');\n\nexport type GitHubProvider = z.infer;\n\n/**\n * GitHub Repository Configuration\n * Defines a repository to integrate with\n */\nexport const GitHubRepositorySchema = z.object({\n /**\n * Repository owner (organization or user)\n */\n owner: z.string().describe('Repository owner (organization or username)'),\n \n /**\n * Repository name\n */\n name: z.string().describe('Repository name'),\n \n /**\n * Default branch name\n */\n defaultBranch: z.string().optional().default('main').describe('Default branch name'),\n \n /**\n * Enable auto-merge for PRs\n */\n autoMerge: z.boolean().optional().default(false).describe('Enable auto-merge for pull requests'),\n \n /**\n * Branch protection rules\n */\n branchProtection: z.object({\n requiredReviewers: z.number().int().min(0).optional().default(1).describe('Required number of reviewers'),\n requireStatusChecks: z.boolean().optional().default(true).describe('Require status checks to pass'),\n enforceAdmins: z.boolean().optional().default(false).describe('Enforce protections for admins'),\n allowForcePushes: z.boolean().optional().default(false).describe('Allow force pushes'),\n allowDeletions: z.boolean().optional().default(false).describe('Allow branch deletions'),\n }).optional().describe('Branch protection configuration'),\n \n /**\n * Repository topics/tags\n */\n topics: z.array(z.string()).optional().describe('Repository topics'),\n});\n\nexport type GitHubRepository = z.infer;\n\n/**\n * GitHub Commit Configuration\n */\nexport const GitHubCommitConfigSchema = z.object({\n /**\n * Commit author name\n */\n authorName: z.string().optional().describe('Commit author name'),\n \n /**\n * Commit author email\n */\n authorEmail: z.string().email().optional().describe('Commit author email'),\n \n /**\n * GPG sign commits\n */\n signCommits: z.boolean().optional().default(false).describe('Sign commits with GPG'),\n \n /**\n * Commit message template\n */\n messageTemplate: z.string().optional().describe('Commit message template'),\n \n /**\n * Conventional commits format\n */\n useConventionalCommits: z.boolean().optional().default(true).describe('Use conventional commits format'),\n});\n\nexport type GitHubCommitConfig = z.infer;\n\n/**\n * GitHub Pull Request Configuration\n */\nexport const GitHubPullRequestConfigSchema = z.object({\n /**\n * Default PR title template\n */\n titleTemplate: z.string().optional().describe('PR title template'),\n \n /**\n * Default PR body template\n */\n bodyTemplate: z.string().optional().describe('PR body template'),\n \n /**\n * Default reviewers\n */\n defaultReviewers: z.array(z.string()).optional().describe('Default reviewers (usernames)'),\n \n /**\n * Default assignees\n */\n defaultAssignees: z.array(z.string()).optional().describe('Default assignees (usernames)'),\n \n /**\n * Default labels\n */\n defaultLabels: z.array(z.string()).optional().describe('Default labels'),\n \n /**\n * Enable draft PRs by default\n */\n draftByDefault: z.boolean().optional().default(false).describe('Create draft PRs by default'),\n \n /**\n * Auto-delete head branch after merge\n */\n deleteHeadBranch: z.boolean().optional().default(true).describe('Delete head branch after merge'),\n});\n\nexport type GitHubPullRequestConfig = z.infer;\n\n/**\n * GitHub Actions Workflow Configuration\n */\nexport const GitHubActionsWorkflowSchema = z.object({\n /**\n * Workflow name\n */\n name: z.string().describe('Workflow name'),\n \n /**\n * Workflow file path\n */\n path: z.string().describe('Workflow file path (e.g., .github/workflows/ci.yml)'),\n \n /**\n * Enable workflow\n */\n enabled: z.boolean().optional().default(true).describe('Enable workflow'),\n \n /**\n * Workflow triggers\n */\n triggers: z.array(z.enum([\n 'push',\n 'pull_request',\n 'release',\n 'schedule',\n 'workflow_dispatch',\n 'repository_dispatch',\n ])).optional().describe('Workflow triggers'),\n \n /**\n * Environment variables\n */\n env: z.record(z.string(), z.string()).optional().describe('Environment variables'),\n \n /**\n * Secrets required\n */\n secrets: z.array(z.string()).optional().describe('Required secrets'),\n});\n\nexport type GitHubActionsWorkflow = z.infer;\n\n/**\n * GitHub Release Configuration\n */\nexport const GitHubReleaseConfigSchema = z.object({\n /**\n * Tag name pattern\n */\n tagPattern: z.string().optional().default('v*').describe('Tag name pattern (e.g., v*, release/*)'),\n \n /**\n * Use semantic versioning\n */\n semanticVersioning: z.boolean().optional().default(true).describe('Use semantic versioning'),\n \n /**\n * Generate release notes automatically\n */\n autoReleaseNotes: z.boolean().optional().default(true).describe('Generate release notes automatically'),\n \n /**\n * Release name template\n */\n releaseNameTemplate: z.string().optional().describe('Release name template'),\n \n /**\n * Pre-release pattern\n */\n preReleasePattern: z.string().optional().describe('Pre-release pattern (e.g., *-alpha, *-beta)'),\n \n /**\n * Create draft releases\n */\n draftByDefault: z.boolean().optional().default(false).describe('Create draft releases by default'),\n});\n\nexport type GitHubReleaseConfig = z.infer;\n\n/**\n * GitHub Issue Tracking Configuration\n */\nexport const GitHubIssueTrackingSchema = z.object({\n /**\n * Enable issue tracking\n */\n enabled: z.boolean().optional().default(true).describe('Enable issue tracking'),\n \n /**\n * Default issue labels\n */\n defaultLabels: z.array(z.string()).optional().describe('Default issue labels'),\n \n /**\n * Issue template paths\n */\n templatePaths: z.array(z.string()).optional().describe('Issue template paths'),\n \n /**\n * Auto-assign issues\n */\n autoAssign: z.boolean().optional().default(false).describe('Auto-assign issues'),\n \n /**\n * Auto-close stale issues\n */\n autoCloseStale: z.object({\n enabled: z.boolean().default(false),\n daysBeforeStale: z.number().int().min(1).optional().default(60),\n daysBeforeClose: z.number().int().min(1).optional().default(7),\n staleLabel: z.string().optional().default('stale'),\n }).optional().describe('Auto-close stale issues configuration'),\n});\n\nexport type GitHubIssueTracking = z.infer;\n\n/**\n * GitHub Connector Schema\n * Complete GitHub integration configuration\n */\nexport const GitHubConnectorSchema = ConnectorSchema.extend({\n type: z.literal('saas'),\n \n /**\n * GitHub provider type\n */\n provider: GitHubProviderSchema.describe('GitHub provider'),\n \n /**\n * GitHub API base URL\n */\n baseUrl: z.string().url().optional().default('https://api.github.com').describe('GitHub API base URL'),\n \n /**\n * Repositories to integrate\n */\n repositories: z.array(GitHubRepositorySchema).describe('Repositories to manage'),\n \n /**\n * Commit configuration\n */\n commitConfig: GitHubCommitConfigSchema.optional().describe('Commit configuration'),\n \n /**\n * Pull request configuration\n */\n pullRequestConfig: GitHubPullRequestConfigSchema.optional().describe('Pull request configuration'),\n \n /**\n * GitHub Actions workflows\n */\n workflows: z.array(GitHubActionsWorkflowSchema).optional().describe('GitHub Actions workflows'),\n \n /**\n * Release configuration\n */\n releaseConfig: GitHubReleaseConfigSchema.optional().describe('Release configuration'),\n \n /**\n * Issue tracking configuration\n */\n issueTracking: GitHubIssueTrackingSchema.optional().describe('Issue tracking configuration'),\n \n /**\n * Enable webhooks\n */\n enableWebhooks: z.boolean().optional().default(true).describe('Enable GitHub webhooks'),\n \n /**\n * Webhook events to subscribe\n */\n webhookEvents: z.array(z.enum([\n 'push',\n 'pull_request',\n 'issues',\n 'issue_comment',\n 'release',\n 'workflow_run',\n 'deployment',\n 'deployment_status',\n 'check_run',\n 'check_suite',\n 'status',\n ])).optional().describe('Webhook events to subscribe to'),\n});\n\nexport type GitHubConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: GitHub.com Connector Configuration\n */\nexport const githubPublicConnectorExample = {\n name: 'github_public',\n label: 'GitHub.com',\n type: 'saas',\n provider: 'github',\n baseUrl: 'https://api.github.com',\n \n authentication: {\n type: 'oauth2',\n clientId: '${GITHUB_CLIENT_ID}',\n clientSecret: '${GITHUB_CLIENT_SECRET}',\n authorizationUrl: 'https://github.com/login/oauth/authorize',\n tokenUrl: 'https://github.com/login/oauth/access_token',\n scopes: ['repo', 'workflow', 'write:packages'],\n },\n \n repositories: [\n {\n owner: 'objectstack-ai',\n name: 'spec',\n defaultBranch: 'main',\n autoMerge: false,\n branchProtection: {\n requiredReviewers: 1,\n requireStatusChecks: true,\n enforceAdmins: false,\n allowForcePushes: false,\n allowDeletions: false,\n },\n topics: ['objectstack', 'low-code', 'metadata-driven'],\n },\n ],\n \n commitConfig: {\n authorName: 'ObjectStack Bot',\n authorEmail: 'bot@objectstack.ai',\n signCommits: false,\n useConventionalCommits: true,\n },\n \n pullRequestConfig: {\n titleTemplate: '{{type}}: {{description}}',\n defaultReviewers: ['team-lead'],\n defaultLabels: ['automated', 'ai-generated'],\n draftByDefault: false,\n deleteHeadBranch: true,\n },\n \n workflows: [\n {\n name: 'CI',\n path: '.github/workflows/ci.yml',\n enabled: true,\n triggers: ['push', 'pull_request'],\n },\n {\n name: 'Release',\n path: '.github/workflows/release.yml',\n enabled: true,\n triggers: ['release'],\n },\n ],\n \n releaseConfig: {\n tagPattern: 'v*',\n semanticVersioning: true,\n autoReleaseNotes: true,\n releaseNameTemplate: 'Release {{version}}',\n draftByDefault: false,\n },\n \n issueTracking: {\n enabled: true,\n defaultLabels: ['needs-triage'],\n autoAssign: false,\n autoCloseStale: {\n enabled: true,\n daysBeforeStale: 60,\n daysBeforeClose: 7,\n staleLabel: 'stale',\n },\n },\n \n enableWebhooks: true,\n webhookEvents: ['push', 'pull_request', 'release', 'workflow_run'],\n \n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: GitHub Enterprise Connector Configuration\n */\nexport const githubEnterpriseConnectorExample = {\n name: 'github_enterprise',\n label: 'GitHub Enterprise',\n type: 'saas',\n provider: 'github_enterprise',\n baseUrl: 'https://github.enterprise.com/api/v3',\n \n authentication: {\n type: 'oauth2',\n clientId: '${GITHUB_ENTERPRISE_CLIENT_ID}',\n clientSecret: '${GITHUB_ENTERPRISE_CLIENT_SECRET}',\n authorizationUrl: 'https://github.enterprise.com/login/oauth/authorize',\n tokenUrl: 'https://github.enterprise.com/login/oauth/access_token',\n scopes: ['repo', 'admin:org', 'workflow'],\n },\n \n repositories: [\n {\n owner: 'enterprise-org',\n name: 'internal-app',\n defaultBranch: 'develop',\n autoMerge: true,\n branchProtection: {\n requiredReviewers: 2,\n requireStatusChecks: true,\n enforceAdmins: true,\n allowForcePushes: false,\n allowDeletions: false,\n },\n },\n ],\n \n commitConfig: {\n authorName: 'CI Bot',\n authorEmail: 'ci-bot@enterprise.com',\n signCommits: true,\n useConventionalCommits: true,\n },\n \n pullRequestConfig: {\n titleTemplate: '[{{branch}}] {{description}}',\n bodyTemplate: `## Changes\\n\\n{{changes}}\\n\\n## Testing\\n\\n{{testing}}`,\n defaultReviewers: ['tech-lead', 'security-team'],\n defaultLabels: ['automated'],\n draftByDefault: true,\n deleteHeadBranch: true,\n },\n \n releaseConfig: {\n tagPattern: 'release/*',\n semanticVersioning: true,\n autoReleaseNotes: true,\n preReleasePattern: '*-rc*',\n draftByDefault: true,\n },\n \n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\nimport {\n ConnectorSchema,\n} from '../connector.zod';\n\n/**\n * Vercel Connector Protocol\n * \n * Specialized connector for Vercel deployment platform enabling automated\n * deployments, preview environments, and production releases.\n * \n * Use Cases:\n * - Automated deployments from Git\n * - Preview deployments for pull requests\n * - Production releases\n * - Environment variable management\n * - Domain and SSL configuration\n * - Edge function deployment\n * \n * @example\n * ```typescript\n * import { VercelConnector } from '@objectstack/spec/integration';\n * \n * const vercelConnector: VercelConnector = {\n * name: 'vercel_production',\n * label: 'Vercel Production',\n * type: 'saas',\n * provider: 'vercel',\n * baseUrl: 'https://api.vercel.com',\n * authentication: {\n * type: 'bearer',\n * token: '${VERCEL_TOKEN}',\n * },\n * projects: [\n * {\n * name: 'objectstack-app',\n * framework: 'nextjs',\n * gitRepository: {\n * type: 'github',\n * repo: 'objectstack-ai/app',\n * },\n * },\n * ],\n * };\n * ```\n */\n\n/**\n * Vercel Provider Type\n */\nexport const VercelProviderSchema = z.enum([\n 'vercel',\n]).describe('Vercel provider type');\n\nexport type VercelProvider = z.infer;\n\n/**\n * Vercel Framework Types\n */\nexport const VercelFrameworkSchema = z.enum([\n 'nextjs',\n 'react',\n 'vue',\n 'nuxtjs',\n 'gatsby',\n 'remix',\n 'astro',\n 'sveltekit',\n 'solid',\n 'angular',\n 'static',\n 'other',\n]).describe('Frontend framework');\n\nexport type VercelFramework = z.infer;\n\n/**\n * Git Repository Configuration\n */\nexport const GitRepositoryConfigSchema = z.object({\n /**\n * Git provider type\n */\n type: z.enum(['github', 'gitlab', 'bitbucket']).describe('Git provider'),\n \n /**\n * Repository identifier (owner/repo)\n */\n repo: z.string().describe('Repository identifier (e.g., owner/repo)'),\n \n /**\n * Production branch\n */\n productionBranch: z.string().optional().default('main').describe('Production branch name'),\n \n /**\n * Auto-deploy production branch\n */\n autoDeployProduction: z.boolean().optional().default(true).describe('Auto-deploy production branch'),\n \n /**\n * Auto-deploy preview branches\n */\n autoDeployPreview: z.boolean().optional().default(true).describe('Auto-deploy preview branches'),\n});\n\nexport type GitRepositoryConfig = z.infer;\n\n/**\n * Build Configuration\n */\nexport const BuildConfigSchema = z.object({\n /**\n * Build command\n */\n buildCommand: z.string().optional().describe('Build command (e.g., npm run build)'),\n \n /**\n * Output directory\n */\n outputDirectory: z.string().optional().describe('Output directory (e.g., .next, dist)'),\n \n /**\n * Install command\n */\n installCommand: z.string().optional().describe('Install command (e.g., npm install, pnpm install)'),\n \n /**\n * Development command\n */\n devCommand: z.string().optional().describe('Development command (e.g., npm run dev)'),\n \n /**\n * Node.js version\n */\n nodeVersion: z.string().optional().describe('Node.js version (e.g., 18.x, 20.x)'),\n \n /**\n * Environment variables\n */\n env: z.record(z.string(), z.string()).optional().describe('Build environment variables'),\n});\n\nexport type BuildConfig = z.infer;\n\n/**\n * Deployment Configuration\n */\nexport const DeploymentConfigSchema = z.object({\n /**\n * Enable automatic deployments\n */\n autoDeployment: z.boolean().optional().default(true).describe('Enable automatic deployments'),\n \n /**\n * Deployment regions\n */\n regions: z.array(z.enum([\n 'iad1', // US East (Washington, D.C.)\n 'sfo1', // US West (San Francisco)\n 'gru1', // South America (São Paulo)\n 'lhr1', // Europe West (London)\n 'fra1', // Europe Central (Frankfurt)\n 'sin1', // Asia (Singapore)\n 'syd1', // Australia (Sydney)\n 'hnd1', // Asia (Tokyo)\n 'icn1', // Asia (Seoul)\n ])).optional().describe('Deployment regions'),\n \n /**\n * Enable preview deployments\n */\n enablePreview: z.boolean().optional().default(true).describe('Enable preview deployments'),\n \n /**\n * Preview deployment comments on PRs\n */\n previewComments: z.boolean().optional().default(true).describe('Post preview URLs in PR comments'),\n \n /**\n * Production deployment protection\n */\n productionProtection: z.boolean().optional().default(true).describe('Require approval for production deployments'),\n \n /**\n * Deploy hooks\n */\n deployHooks: z.array(z.object({\n name: z.string().describe('Hook name'),\n url: z.string().url().describe('Deploy hook URL'),\n branch: z.string().optional().describe('Target branch'),\n })).optional().describe('Deploy hooks'),\n});\n\nexport type DeploymentConfig = z.infer;\n\n/**\n * Domain Configuration\n */\nexport const DomainConfigSchema = z.object({\n /**\n * Domain name\n */\n domain: z.string().describe('Domain name (e.g., app.example.com)'),\n \n /**\n * Enable HTTPS redirect\n */\n httpsRedirect: z.boolean().optional().default(true).describe('Redirect HTTP to HTTPS'),\n \n /**\n * Custom SSL certificate\n */\n customCertificate: z.object({\n cert: z.string().describe('SSL certificate'),\n key: z.string().describe('Private key'),\n ca: z.string().optional().describe('Certificate authority'),\n }).optional().describe('Custom SSL certificate'),\n \n /**\n * Git branch for this domain\n */\n gitBranch: z.string().optional().describe('Git branch to deploy to this domain'),\n});\n\nexport type DomainConfig = z.infer;\n\n/**\n * Environment Variables Configuration\n */\nexport const EnvironmentVariablesSchema = z.object({\n /**\n * Variable name\n */\n key: z.string().describe('Environment variable name'),\n \n /**\n * Variable value\n */\n value: z.string().describe('Environment variable value'),\n \n /**\n * Target environments\n */\n target: z.array(z.enum(['production', 'preview', 'development'])).describe('Target environments'),\n \n /**\n * Is secret (encrypted)\n */\n isSecret: z.boolean().optional().default(false).describe('Encrypt this variable'),\n \n /**\n * Git branch (for preview/development)\n */\n gitBranch: z.string().optional().describe('Specific git branch'),\n});\n\nexport type EnvironmentVariables = z.infer;\n\n/**\n * Edge Function Configuration\n */\nexport const EdgeFunctionConfigSchema = z.object({\n /**\n * Function name\n */\n name: z.string().describe('Edge function name'),\n \n /**\n * Function path\n */\n path: z.string().describe('Function path (e.g., /api/*)'),\n \n /**\n * Regions to deploy\n */\n regions: z.array(z.string()).optional().describe('Specific regions for this function'),\n \n /**\n * Memory limit (MB)\n */\n memoryLimit: z.number().int().min(128).max(3008).optional().default(1024).describe('Memory limit in MB'),\n \n /**\n * Timeout (seconds)\n */\n timeout: z.number().int().min(1).max(300).optional().default(10).describe('Timeout in seconds'),\n});\n\nexport type EdgeFunctionConfig = z.infer;\n\n/**\n * Vercel Project Configuration\n */\nexport const VercelProjectSchema = z.object({\n /**\n * Project name\n */\n name: z.string().describe('Vercel project name'),\n \n /**\n * Framework\n */\n framework: VercelFrameworkSchema.optional().describe('Frontend framework'),\n \n /**\n * Git repository\n */\n gitRepository: GitRepositoryConfigSchema.optional().describe('Git repository configuration'),\n \n /**\n * Build configuration\n */\n buildConfig: BuildConfigSchema.optional().describe('Build configuration'),\n \n /**\n * Deployment configuration\n */\n deploymentConfig: DeploymentConfigSchema.optional().describe('Deployment configuration'),\n \n /**\n * Custom domains\n */\n domains: z.array(DomainConfigSchema).optional().describe('Custom domains'),\n \n /**\n * Environment variables\n */\n environmentVariables: z.array(EnvironmentVariablesSchema).optional().describe('Environment variables'),\n \n /**\n * Edge functions\n */\n edgeFunctions: z.array(EdgeFunctionConfigSchema).optional().describe('Edge functions'),\n \n /**\n * Root directory\n */\n rootDirectory: z.string().optional().describe('Root directory (for monorepos)'),\n});\n\nexport type VercelProject = z.infer;\n\n/**\n * Vercel Monitoring Configuration\n */\nexport const VercelMonitoringSchema = z.object({\n /**\n * Enable Web Analytics\n */\n enableWebAnalytics: z.boolean().optional().default(false).describe('Enable Vercel Web Analytics'),\n \n /**\n * Enable Speed Insights\n */\n enableSpeedInsights: z.boolean().optional().default(false).describe('Enable Vercel Speed Insights'),\n \n /**\n * Enable Log Drains\n */\n logDrains: z.array(z.object({\n name: z.string().describe('Log drain name'),\n url: z.string().url().describe('Log drain URL'),\n headers: z.record(z.string(), z.string()).optional().describe('Custom headers'),\n sources: z.array(z.enum(['static', 'lambda', 'edge'])).optional().describe('Log sources'),\n })).optional().describe('Log drains configuration'),\n});\n\nexport type VercelMonitoring = z.infer;\n\n/**\n * Vercel Team Configuration\n */\nexport const VercelTeamSchema = z.object({\n /**\n * Team ID or slug\n */\n teamId: z.string().optional().describe('Team ID or slug'),\n \n /**\n * Team name\n */\n teamName: z.string().optional().describe('Team name'),\n});\n\nexport type VercelTeam = z.infer;\n\n/**\n * Vercel Connector Schema\n * Complete Vercel integration configuration\n */\nexport const VercelConnectorSchema = ConnectorSchema.extend({\n type: z.literal('saas'),\n \n /**\n * Vercel provider\n */\n provider: VercelProviderSchema.describe('Vercel provider'),\n \n /**\n * Vercel API base URL\n */\n baseUrl: z.string().url().optional().default('https://api.vercel.com').describe('Vercel API base URL'),\n \n /**\n * Team configuration\n */\n team: VercelTeamSchema.optional().describe('Vercel team configuration'),\n \n /**\n * Projects to manage\n */\n projects: z.array(VercelProjectSchema).describe('Vercel projects'),\n \n /**\n * Monitoring configuration\n */\n monitoring: VercelMonitoringSchema.optional().describe('Monitoring configuration'),\n \n /**\n * Enable webhooks\n */\n enableWebhooks: z.boolean().optional().default(true).describe('Enable Vercel webhooks'),\n \n /**\n * Webhook events to subscribe\n */\n webhookEvents: z.array(z.enum([\n 'deployment.created',\n 'deployment.succeeded',\n 'deployment.failed',\n 'deployment.ready',\n 'deployment.error',\n 'deployment.canceled',\n 'deployment-checks-completed',\n 'deployment-prepared',\n 'project.created',\n 'project.removed',\n ])).optional().describe('Webhook events to subscribe to'),\n});\n\nexport type VercelConnector = z.infer;\n\n// ============================================================================\n// Helper Functions & Examples\n// ============================================================================\n\n/**\n * Example: Vercel Next.js Project Configuration\n */\nexport const vercelNextJsConnectorExample = {\n name: 'vercel_production',\n label: 'Vercel Production',\n type: 'saas',\n provider: 'vercel',\n baseUrl: 'https://api.vercel.com',\n \n authentication: {\n type: 'bearer',\n token: '${VERCEL_TOKEN}',\n },\n \n projects: [\n {\n name: 'objectstack-app',\n framework: 'nextjs',\n \n gitRepository: {\n type: 'github',\n repo: 'objectstack-ai/app',\n productionBranch: 'main',\n autoDeployProduction: true,\n autoDeployPreview: true,\n },\n \n buildConfig: {\n buildCommand: 'npm run build',\n outputDirectory: '.next',\n installCommand: 'npm ci',\n devCommand: 'npm run dev',\n nodeVersion: '20.x',\n env: {\n NEXT_PUBLIC_API_URL: 'https://api.objectstack.ai',\n },\n },\n \n deploymentConfig: {\n autoDeployment: true,\n regions: ['iad1', 'sfo1', 'fra1'],\n enablePreview: true,\n previewComments: true,\n productionProtection: true,\n },\n \n domains: [\n {\n domain: 'app.objectstack.ai',\n httpsRedirect: true,\n gitBranch: 'main',\n },\n {\n domain: 'staging.objectstack.ai',\n httpsRedirect: true,\n gitBranch: 'develop',\n },\n ],\n \n environmentVariables: [\n {\n key: 'DATABASE_URL',\n value: '${DATABASE_URL}',\n target: ['production', 'preview'],\n isSecret: true,\n },\n {\n key: 'NEXT_PUBLIC_ANALYTICS_ID',\n value: 'UA-XXXXXXXX-X',\n target: ['production'],\n isSecret: false,\n },\n ],\n \n edgeFunctions: [\n {\n name: 'api-middleware',\n path: '/api/*',\n regions: ['iad1', 'sfo1'],\n memoryLimit: 1024,\n timeout: 10,\n },\n ],\n },\n ],\n \n monitoring: {\n enableWebAnalytics: true,\n enableSpeedInsights: true,\n logDrains: [\n {\n name: 'datadog-logs',\n url: 'https://http-intake.logs.datadoghq.com/api/v2/logs',\n headers: {\n 'DD-API-KEY': '${DATADOG_API_KEY}',\n },\n sources: ['lambda', 'edge'],\n },\n ],\n },\n \n enableWebhooks: true,\n webhookEvents: [\n 'deployment.succeeded',\n 'deployment.failed',\n 'deployment.ready',\n ],\n \n status: 'active',\n enabled: true,\n};\n\n/**\n * Example: Vercel Static Site Configuration\n */\nexport const vercelStaticSiteConnectorExample = {\n name: 'vercel_docs',\n label: 'Vercel Documentation',\n type: 'saas',\n provider: 'vercel',\n baseUrl: 'https://api.vercel.com',\n \n authentication: {\n type: 'bearer',\n token: '${VERCEL_TOKEN}',\n },\n \n team: {\n teamId: 'team_xxxxxx',\n teamName: 'ObjectStack',\n },\n \n projects: [\n {\n name: 'objectstack-docs',\n framework: 'static',\n \n gitRepository: {\n type: 'github',\n repo: 'objectstack-ai/docs',\n productionBranch: 'main',\n autoDeployProduction: true,\n autoDeployPreview: true,\n },\n \n buildConfig: {\n buildCommand: 'npm run build',\n outputDirectory: 'dist',\n installCommand: 'npm ci',\n nodeVersion: '18.x',\n },\n \n deploymentConfig: {\n autoDeployment: true,\n regions: ['iad1', 'lhr1', 'sin1'],\n enablePreview: true,\n previewComments: true,\n productionProtection: false,\n },\n \n domains: [\n {\n domain: 'docs.objectstack.ai',\n httpsRedirect: true,\n },\n ],\n \n environmentVariables: [\n {\n key: 'ALGOLIA_APP_ID',\n value: '${ALGOLIA_APP_ID}',\n target: ['production', 'preview'],\n isSecret: false,\n },\n {\n key: 'ALGOLIA_API_KEY',\n value: '${ALGOLIA_API_KEY}',\n target: ['production', 'preview'],\n isSecret: true,\n },\n ],\n },\n ],\n \n monitoring: {\n enableWebAnalytics: true,\n enableSpeedInsights: false,\n },\n \n enableWebhooks: false,\n \n status: 'active',\n enabled: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * ObjectStack Contracts\n * \n * Core interface definitions following \"Protocol First\" principle.\n * All interfaces should be defined in @objectstack/spec to avoid circular dependencies.\n */\n\nexport * from './logger.js';\nexport * from './data-engine.js';\nexport * from './data-driver.js';\nexport * from './http-server.js';\nexport * from './service-registry.js';\nexport * from './plugin-validator.js';\nexport * from './startup-orchestrator.js';\nexport * from './plugin-lifecycle-events.js';\nexport * from './schema-driver.js';\nexport * from './cache-service.js';\nexport * from './search-service.js';\nexport * from './queue-service.js';\nexport * from './notification-service.js';\nexport * from './storage-service.js';\nexport * from './metadata-service.js';\nexport * from './auth-service.js';\nexport * from './automation-service.js';\nexport * from './graphql-service.js';\nexport * from './analytics-service.js';\nexport * from './realtime-service.js';\nexport * from './job-service.js';\nexport * from './ai-service.js';\nexport * from './llm-adapter.js';\nexport * from './i18n-service.js';\nexport * from './ui-service.js';\nexport * from './workflow-service.js';\nexport * from './feed-service.js';\nexport * from './export-service.js';\nexport * from './package-service.js';\n\n// Provisioning & Deployment\nexport * from './turso-platform.js';\nexport * from './provisioning-service.js';\nexport * from './schema-diff-service.js';\nexport * from './deploy-pipeline-service.js';\nexport * from './tenant-router.js';\nexport * from './app-lifecycle-service.js';\nexport * from './seed-loader-service.js';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio\n * \n * Studio Protocol — Plugin system for ObjectStack Studio\n * \n * Defines the extension model that allows metadata types to contribute\n * custom viewers, designers, sidebar groups, actions, and commands.\n * Also includes the Object Designer protocol for visual field editing,\n * relationship mapping, and ER diagram configuration.\n */\n\nexport {\n // Schemas\n ViewModeSchema,\n MetadataViewerContributionSchema,\n SidebarGroupContributionSchema,\n ActionContributionSchema,\n ActionLocationSchema,\n MetadataIconContributionSchema,\n PanelContributionSchema,\n PanelLocationSchema,\n CommandContributionSchema,\n StudioPluginContributionsSchema,\n ActivationEventSchema,\n StudioPluginManifestSchema,\n\n // Types\n type ViewMode,\n type MetadataViewerContribution,\n type SidebarGroupContribution,\n type ActionContribution,\n type MetadataIconContribution,\n type PanelContribution,\n type CommandContribution,\n type StudioPluginContributions,\n type StudioPluginManifest,\n\n // Helpers\n defineStudioPlugin,\n} from './plugin.zod';\n\nexport {\n // Object Designer Schemas\n FieldPropertySectionSchema,\n FieldGroupSchema,\n FieldEditorConfigSchema,\n RelationshipDisplaySchema,\n RelationshipMapperConfigSchema,\n ERLayoutAlgorithmSchema,\n ERNodeDisplaySchema,\n ERDiagramConfigSchema,\n ObjectListDisplayModeSchema,\n ObjectSortFieldSchema,\n ObjectFilterSchema,\n ObjectManagerConfigSchema,\n ObjectPreviewTabSchema,\n ObjectPreviewConfigSchema,\n ObjectDesignerDefaultViewSchema,\n ObjectDesignerConfigSchema,\n\n // Object Designer Types\n type FieldPropertySection,\n type FieldGroup,\n type FieldEditorConfig,\n type RelationshipDisplay,\n type RelationshipMapperConfig,\n type ERLayoutAlgorithm,\n type ERNodeDisplay,\n type ERDiagramConfig,\n type ObjectListDisplayMode,\n type ObjectSortField,\n type ObjectFilter,\n type ObjectManagerConfig,\n type ObjectPreviewTab,\n type ObjectPreviewConfig,\n type ObjectDesignerDefaultView,\n type ObjectDesignerConfig,\n\n // Object Designer Helpers\n defineObjectDesignerConfig,\n} from './object-designer.zod';\n\nexport {\n // Page Builder Schemas\n CanvasSnapSettingsSchema,\n CanvasZoomSettingsSchema,\n ElementPaletteItemSchema,\n PageBuilderConfigSchema,\n /** @deprecated Use PageBuilderConfigSchema instead */\n InterfaceBuilderConfigSchema,\n\n // Page Builder Types\n type CanvasSnapSettings,\n type CanvasZoomSettings,\n type ElementPaletteItem,\n type PageBuilderConfig,\n /** @deprecated Use PageBuilderConfig instead */\n type InterfaceBuilderConfig,\n} from './page-builder.zod';\n\nexport {\n // Flow Builder Schemas\n FlowNodeShapeSchema,\n FlowNodeRenderDescriptorSchema,\n FlowCanvasNodeSchema,\n FlowCanvasEdgeStyleSchema,\n FlowCanvasEdgeSchema,\n FlowLayoutAlgorithmSchema,\n FlowLayoutDirectionSchema,\n FlowBuilderConfigSchema,\n BUILT_IN_NODE_DESCRIPTORS,\n\n // Flow Builder Types\n type FlowNodeShape,\n type FlowNodeRenderDescriptor,\n type FlowCanvasNode,\n type FlowCanvasEdgeStyle,\n type FlowCanvasEdge,\n type FlowLayoutAlgorithm,\n type FlowLayoutDirection,\n type FlowBuilderConfig,\n\n // Flow Builder Helpers\n defineFlowBuilderConfig,\n} from './flow-builder.zod';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio/plugin\n * \n * Studio Plugin Protocol\n * \n * Defines the specification for Studio plugins — a VS Code-like extension model\n * that allows each metadata type to contribute custom viewers, designers, \n * sidebar groups, actions, and commands.\n * \n * ## Architecture\n * \n * Like VS Code extensions, Studio plugins have two layers:\n * 1. **Manifest (Declarative)** — JSON-serializable contribution points\n * 2. **Activation (Imperative)** — Runtime registration of React components & handlers\n * \n * ```\n * ┌─────────────────────────────────────────────────────────┐\n * │ Studio Host │\n * │ ┌───────────────────────────────────────────────────┐ │\n * │ │ Plugin Registry │ │\n * │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │\n * │ │ │ Object │ │ Flow │ │ Agent │ ... │ │\n * │ │ │ Plugin │ │ Plugin │ │ Plugin │ │ │\n * │ │ └──────────┘ └──────────┘ └──────────┘ │ │\n * │ └───────────────────────────────────────────────────┘ │\n * │ │\n * │ ┌─── Sidebar ───┐ ┌──── Main Panel ────────────────┐ │\n * │ │ [plugin icons] │ │ PluginHost renders viewer │ │\n * │ │ [plugin groups]│ │ from highest-priority plugin │ │\n * │ └────────────────┘ └────────────────────────────────┘ │\n * └─────────────────────────────────────────────────────────┘\n * ```\n * \n * @example\n * ```typescript\n * import { StudioPluginManifestSchema } from '@objectstack/spec/studio';\n * \n * const manifest = StudioPluginManifestSchema.parse({\n * id: 'objectstack.object-designer',\n * name: 'Object Designer',\n * version: '1.0.0',\n * contributes: {\n * metadataViewers: [{\n * id: 'object-explorer',\n * metadataTypes: ['object', 'objects'],\n * label: 'Object Explorer',\n * priority: 100,\n * modes: ['preview', 'design', 'data'],\n * }],\n * },\n * });\n * ```\n */\n\nimport { z } from 'zod';\n\n// ─── View Mode ───────────────────────────────────────────────────────\n\n/** Supported view modes for metadata viewers */\nexport const ViewModeSchema = z.enum(['preview', 'design', 'code', 'data']);\nexport type ViewMode = z.infer;\n\n// ─── Metadata Viewer Contribution ────────────────────────────────────\n\n/**\n * Declares a metadata viewer/designer component.\n * The runtime component is registered imperatively during plugin activation.\n */\nexport const MetadataViewerContributionSchema = z.object({\n /** Unique viewer ID (namespaced: `pluginId.viewerId`) */\n id: z.string().describe('Unique viewer identifier'),\n\n /** Metadata type(s) this viewer handles (e.g., \"object\", \"flow\", \"agent\") */\n metadataTypes: z.array(z.string()).min(1).describe('Metadata types this viewer can handle'),\n\n /** Human-readable label shown in the view switcher */\n label: z.string().describe('Viewer display label'),\n\n /** Priority — highest-priority viewer becomes default. Built-in default = 0 */\n priority: z.number().default(0).describe('Viewer priority (higher wins)'),\n\n /** View modes this viewer supports */\n modes: z.array(ViewModeSchema).default(['preview']).describe('Supported view modes'),\n});\n\nexport type MetadataViewerContribution = z.infer;\n\n// ─── Sidebar Group Contribution ──────────────────────────────────────\n\n/**\n * Declares a sidebar group that organizes metadata types.\n * Plugins can add new groups or extend existing ones.\n */\nexport const SidebarGroupContributionSchema = z.object({\n /** Unique group key */\n key: z.string().describe('Unique group key'),\n\n /** Display label */\n label: z.string().describe('Group display label'),\n\n /** Lucide icon name (e.g., \"database\", \"workflow\") */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Metadata types belonging to this group */\n metadataTypes: z.array(z.string()).describe('Metadata types in this group'),\n\n /** Sort order — lower values appear first */\n order: z.number().default(100).describe('Sort order (lower = higher)'),\n});\n\nexport type SidebarGroupContribution = z.infer;\n\n// ─── Action Contribution ─────────────────────────────────────────────\n\n/** Where an action can appear in the UI */\nexport const ActionLocationSchema = z.enum(['toolbar', 'contextMenu', 'commandPalette']);\n\n/**\n * Declares an action that can be triggered on metadata items.\n * The handler is registered imperatively during activation.\n */\nexport const ActionContributionSchema = z.object({\n /** Unique action ID */\n id: z.string().describe('Unique action identifier'),\n\n /** Display label */\n label: z.string().describe('Action display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Where this action appears */\n location: ActionLocationSchema.describe('UI location'),\n\n /** Metadata types this action applies to (empty = all types) */\n metadataTypes: z.array(z.string()).default([]).describe('Applicable metadata types'),\n});\n\nexport type ActionContribution = z.infer;\n\n// ─── Metadata Icon Contribution ──────────────────────────────────────\n\n/**\n * Declares an icon and label for a metadata type.\n * Used by the sidebar and breadcrumbs.\n */\nexport const MetadataIconContributionSchema = z.object({\n /** Metadata type this icon represents */\n metadataType: z.string().describe('Metadata type'),\n\n /** Human-readable label */\n label: z.string().describe('Display label'),\n\n /** Lucide icon name */\n icon: z.string().describe('Lucide icon name'),\n});\n\nexport type MetadataIconContribution = z.infer;\n\n// ─── Panel Contribution ──────────────────────────────────────────────\n\n/** Where a panel can be placed */\nexport const PanelLocationSchema = z.enum(['bottom', 'right', 'modal']);\n\n/**\n * Declares an auxiliary panel (like VS Code's Terminal, Problems, Output panels).\n */\nexport const PanelContributionSchema = z.object({\n /** Unique panel ID */\n id: z.string().describe('Unique panel identifier'),\n\n /** Display label */\n label: z.string().describe('Panel display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Panel placement */\n location: PanelLocationSchema.default('bottom').describe('Panel location'),\n});\n\nexport type PanelContribution = z.infer;\n\n// ─── Command Contribution ────────────────────────────────────────────\n\n/**\n * Declares a command that can be invoked from the command palette\n * or programmatically by other plugins.\n */\nexport const CommandContributionSchema = z.object({\n /** Unique command ID (namespaced: `pluginId.commandName`) */\n id: z.string().describe('Unique command identifier'),\n\n /** Display label */\n label: z.string().describe('Command display label'),\n\n /** Keyboard shortcut (e.g., \"Ctrl+Shift+P\") */\n shortcut: z.string().optional().describe('Keyboard shortcut'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n});\n\nexport type CommandContribution = z.infer;\n\n// ─── Studio Plugin Contributions ─────────────────────────────────────\n\n/**\n * All contribution points a Studio plugin can declare.\n * Analogous to VS Code's `contributes` section in `package.json`.\n */\nexport const StudioPluginContributionsSchema = z.object({\n /** Metadata viewer/designer components */\n metadataViewers: z.array(MetadataViewerContributionSchema).default([]),\n\n /** Sidebar navigation groups */\n sidebarGroups: z.array(SidebarGroupContributionSchema).default([]),\n\n /** Toolbar / context menu / command palette actions */\n actions: z.array(ActionContributionSchema).default([]),\n\n /** Metadata type icons & labels */\n metadataIcons: z.array(MetadataIconContributionSchema).default([]),\n\n /** Auxiliary panels */\n panels: z.array(PanelContributionSchema).default([]),\n\n /** Command palette entries */\n commands: z.array(CommandContributionSchema).default([]),\n});\n\nexport type StudioPluginContributions = z.infer;\n\n// ─── Activation Events ───────────────────────────────────────────────\n\n/**\n * Events that trigger plugin activation.\n * Similar to VS Code's `activationEvents`.\n * \n * Patterns:\n * - `*` — Activate immediately (eager)\n * - `onMetadataType:object` — Activate when metadata type \"object\" is loaded\n * - `onCommand:myPlugin.doSomething` — Activate when command is invoked\n * - `onView:myPlugin.myPanel` — Activate when panel is opened\n */\nexport const ActivationEventSchema = z.string().describe('Activation event pattern');\n\n// ─── Studio Plugin Manifest ──────────────────────────────────────────\n\n/**\n * The declarative manifest for a Studio plugin.\n * \n * This is the \"package.json\" equivalent for Studio extensions.\n * All contribution points are declared here; runtime components\n * are registered imperatively during the `activate()` call.\n */\nexport const StudioPluginManifestSchema = z.object({\n /** \n * Unique plugin ID using reverse-domain notation.\n * @example \"objectstack.object-designer\"\n */\n id: z.string()\n .regex(/^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)*$/)\n .describe('Plugin ID (dot-separated lowercase)'),\n\n /** Human-readable plugin name */\n name: z.string().describe('Plugin display name'),\n\n /** Semantic version */\n version: z.string().default('0.0.1').describe('Plugin version'),\n\n /** Plugin description */\n description: z.string().optional().describe('Plugin description'),\n\n /** Author name */\n author: z.string().optional().describe('Author'),\n\n /** Declarative contribution points */\n contributes: StudioPluginContributionsSchema.default({\n metadataViewers: [],\n sidebarGroups: [],\n actions: [],\n metadataIcons: [],\n panels: [],\n commands: [],\n }),\n\n /** \n * Activation events — when to load this plugin.\n * Default `['*']` means eager activation.\n */\n activationEvents: z.array(ActivationEventSchema).default(['*']),\n});\n\nexport type StudioPluginManifest = z.infer;\n\n// ─── Helper: defineStudioPlugin ──────────────────────────────────────\n\n/**\n * Type-safe helper for defining a Studio plugin manifest.\n * \n * @example\n * ```typescript\n * const manifest = defineStudioPlugin({\n * id: 'objectstack.flow-designer',\n * name: 'Flow Designer',\n * contributes: {\n * metadataViewers: [{\n * id: 'flow-canvas',\n * metadataTypes: ['flows'],\n * label: 'Flow Canvas',\n * priority: 100,\n * modes: ['design', 'code'],\n * }],\n * },\n * });\n * ```\n */\nexport function defineStudioPlugin(\n input: z.input\n): StudioPluginManifest {\n return StudioPluginManifestSchema.parse(input);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio/object-designer\n *\n * Object Designer Protocol — Visual Field Editor, Relationship Mapper & ER Diagram\n *\n * Defines the specification for the Object Designer experience within ObjectStack Studio,\n * including:\n * - **Field Editor**: Visual field creation/editing with type-aware property panels\n * - **Relationship Mapper**: Visual lookup/master-detail relationship configuration\n * - **ER Diagram**: Entity-Relationship diagram rendering and interaction\n * - **Object Manager**: Unified object list with search, filtering, and bulk operations\n *\n * ## Architecture\n *\n * The Object Designer is composed of four interconnected panels:\n *\n * ```\n * ┌─────────────────────────────────────────────────────────────────┐\n * │ Object Manager (list / search) │\n * ├──────────────┬──────────────────────────┬──────────────────────┤\n * │ Object List │ Field Editor │ Property Panel │\n * │ (sidebar) │ (table + inline edit) │ (type-specific) │\n * │ │ │ │\n * │ ─ search │ ─ drag-to-reorder │ ─ constraints │\n * │ ─ filter │ ─ inline type picker │ ─ validation │\n * │ ─ group │ ─ batch add/remove │ ─ security │\n * │ ─ create │ ─ field groups │ ─ relationships │\n * ├──────────────┴──────────────────────────┴──────────────────────┤\n * │ ER Diagram (toggle panel) │\n * │ ─ auto-layout (force / hierarchy / grid) │\n * │ ─ interactive: click node → navigate to object │\n * │ ─ hover: highlight connected relationships │\n * │ ─ zoom/pan/minimap │\n * └─────────────────────────────────────────────────────────────────┘\n * ```\n *\n * @example\n * ```typescript\n * import {\n * ObjectDesignerConfigSchema,\n * ERDiagramConfigSchema,\n * } from '@objectstack/spec/studio';\n *\n * const config = ObjectDesignerConfigSchema.parse({\n * defaultView: 'field-editor',\n * fieldEditor: {\n * inlineEditing: true,\n * dragReorder: true,\n * showFieldGroups: true,\n * },\n * erDiagram: {\n * enabled: true,\n * layout: 'force',\n * showFieldDetails: true,\n * },\n * });\n * ```\n */\n\nimport { z } from 'zod';\n\n// ─── Field Editor ────────────────────────────────────────────────────\n\n/**\n * Field property panel section — groups related field properties\n * in the right-side property inspector.\n */\nexport const FieldPropertySectionSchema = z.object({\n /** Unique section key */\n key: z.string().describe('Section key (e.g., \"basics\", \"constraints\", \"security\")'),\n\n /** Display label */\n label: z.string().describe('Section display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Whether section is expanded by default */\n defaultExpanded: z.boolean().default(true).describe('Whether section is expanded by default'),\n\n /** Sort order — lower values appear first */\n order: z.number().default(0).describe('Sort order (lower = higher)'),\n});\n\nexport type FieldPropertySection = z.infer;\n\n/**\n * Field grouping configuration — organizes fields into collapsible groups\n * within the field editor table (e.g., \"Contact Info\", \"Billing\", \"System\").\n */\nexport const FieldGroupSchema = z.object({\n /** Group key (matches field.group value) */\n key: z.string().describe('Group key matching field.group values'),\n\n /** Display label */\n label: z.string().describe('Group display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Whether group is expanded by default */\n defaultExpanded: z.boolean().default(true).describe('Whether group is expanded by default'),\n\n /** Sort order — lower values appear first */\n order: z.number().default(0).describe('Sort order (lower = higher)'),\n});\n\nexport type FieldGroup = z.infer;\n\n/**\n * Field Editor configuration — controls the visual field editing experience.\n */\nexport const FieldEditorConfigSchema = z.object({\n /** Enable inline editing of field properties in the table */\n inlineEditing: z.boolean().default(true).describe('Enable inline editing of field properties'),\n\n /** Enable drag-and-drop field reordering */\n dragReorder: z.boolean().default(true).describe('Enable drag-and-drop field reordering'),\n\n /** Show field group headers for organizing fields */\n showFieldGroups: z.boolean().default(true).describe('Show field group headers'),\n\n /** Show the type-specific property panel on the right */\n showPropertyPanel: z.boolean().default(true).describe('Show the right-side property panel'),\n\n /** Default property panel sections to display */\n propertySections: z.array(FieldPropertySectionSchema).default([\n { key: 'basics', label: 'Basic Properties', defaultExpanded: true, order: 0 },\n { key: 'constraints', label: 'Constraints & Validation', defaultExpanded: true, order: 10 },\n { key: 'relationship', label: 'Relationship Config', defaultExpanded: true, order: 20 },\n { key: 'display', label: 'Display & UI', defaultExpanded: false, order: 30 },\n { key: 'security', label: 'Security & Compliance', defaultExpanded: false, order: 40 },\n { key: 'advanced', label: 'Advanced', defaultExpanded: false, order: 50 },\n ]).describe('Property panel section definitions'),\n\n /** Field groups for organizing fields in the editor */\n fieldGroups: z.array(FieldGroupSchema).default([]).describe('Field group definitions'),\n\n /** Maximum fields before pagination kicks in */\n paginationThreshold: z.number().default(50).describe('Number of fields before pagination is enabled'),\n\n /** Enable batch field operations (add multiple fields at once) */\n batchOperations: z.boolean().default(true).describe('Enable batch add/remove field operations'),\n\n /** Show field usage statistics (views, formulas, relationships referencing this field) */\n showUsageStats: z.boolean().default(false).describe('Show field usage statistics'),\n});\n\nexport type FieldEditorConfig = z.infer;\n\n// ─── Relationship Mapper ─────────────────────────────────────────────\n\n/**\n * Relationship display configuration — controls how relationships\n * are visualized in the mapper and ER diagram.\n */\nexport const RelationshipDisplaySchema = z.object({\n /** Relationship type to configure */\n type: z.enum(['lookup', 'master_detail', 'tree']).describe('Relationship type'),\n\n /** Line style for this relationship type */\n lineStyle: z.enum(['solid', 'dashed', 'dotted']).default('solid').describe('Line style in diagrams'),\n\n /** Line color (CSS color value) */\n color: z.string().default('#94a3b8').describe('Line color (CSS value)'),\n\n /** Highlighted color on hover/select */\n highlightColor: z.string().default('#0891b2').describe('Highlighted color on hover/select'),\n\n /** Cardinality label to display */\n cardinalityLabel: z.string().default('1:N').describe('Cardinality label (e.g., \"1:N\", \"1:1\", \"N:M\")'),\n});\n\nexport type RelationshipDisplay = z.infer;\n\n/**\n * Relationship Mapper configuration — controls the relationship\n * editing and visualization experience.\n */\nexport const RelationshipMapperConfigSchema = z.object({\n /** Enable visual relationship creation (drag from source to target) */\n visualCreation: z.boolean().default(true).describe('Enable drag-to-create relationships'),\n\n /** Show reverse relationships (child → parent) */\n showReverseRelationships: z.boolean().default(true).describe('Show reverse/child-to-parent relationships'),\n\n /** Show cascade delete warnings */\n showCascadeWarnings: z.boolean().default(true).describe('Show cascade delete behavior warnings'),\n\n /** Relationship display configuration by type */\n displayConfig: z.array(RelationshipDisplaySchema).default([\n { type: 'lookup', lineStyle: 'dashed', color: '#0891b2', highlightColor: '#06b6d4', cardinalityLabel: '1:N' },\n { type: 'master_detail', lineStyle: 'solid', color: '#ea580c', highlightColor: '#f97316', cardinalityLabel: '1:N' },\n { type: 'tree', lineStyle: 'dotted', color: '#8b5cf6', highlightColor: '#a78bfa', cardinalityLabel: '1:N' },\n ]).describe('Visual config per relationship type'),\n});\n\nexport type RelationshipMapperConfig = z.infer;\n\n// ─── ER Diagram ──────────────────────────────────────────────────────\n\n/** Layout algorithm for ER diagram */\nexport const ERLayoutAlgorithmSchema = z.enum([\n 'force', // Force-directed graph (natural clustering)\n 'hierarchy', // Top-down hierarchy (master → detail)\n 'grid', // Uniform grid layout\n 'circular', // Circular arrangement\n]).describe('ER diagram layout algorithm');\n\nexport type ERLayoutAlgorithm = z.infer;\n\n/**\n * Node display options — controls what information is shown\n * on each entity node in the ER diagram.\n */\nexport const ERNodeDisplaySchema = z.object({\n /** Show field list within the node */\n showFields: z.boolean().default(true).describe('Show field list inside entity nodes'),\n\n /** Maximum fields to show before collapsing (0 = no limit) */\n maxFieldsVisible: z.number().default(8).describe('Max fields visible before \"N more...\" collapse'),\n\n /** Show field types alongside field names */\n showFieldTypes: z.boolean().default(true).describe('Show field type badges'),\n\n /** Show required field indicators */\n showRequiredIndicator: z.boolean().default(true).describe('Show required field indicators'),\n\n /** Show record count on each node (requires data access) */\n showRecordCount: z.boolean().default(false).describe('Show live record count on nodes'),\n\n /** Show object icon */\n showIcon: z.boolean().default(true).describe('Show object icon on node header'),\n\n /** Show object description on hover tooltip */\n showDescription: z.boolean().default(true).describe('Show description tooltip on hover'),\n});\n\nexport type ERNodeDisplay = z.infer;\n\n/**\n * ER Diagram configuration — controls the entity-relationship\n * diagram rendering, interaction, and layout.\n */\nexport const ERDiagramConfigSchema = z.object({\n /** Enable the ER diagram panel */\n enabled: z.boolean().default(true).describe('Enable ER diagram panel'),\n\n /** Default layout algorithm */\n layout: ERLayoutAlgorithmSchema.default('force').describe('Default layout algorithm'),\n\n /** Node display options */\n nodeDisplay: ERNodeDisplaySchema.default({\n showFields: true,\n maxFieldsVisible: 8,\n showFieldTypes: true,\n showRequiredIndicator: true,\n showRecordCount: false,\n showIcon: true,\n showDescription: true,\n }).describe('Node display configuration'),\n\n /** Show minimap for navigation */\n showMinimap: z.boolean().default(true).describe('Show minimap for large diagrams'),\n\n /** Enable zoom controls */\n zoomControls: z.boolean().default(true).describe('Show zoom in/out/fit controls'),\n\n /** Minimum zoom level */\n minZoom: z.number().default(0.1).describe('Minimum zoom level'),\n\n /** Maximum zoom level */\n maxZoom: z.number().default(3).describe('Maximum zoom level'),\n\n /** Show relationship labels (cardinality) on edges */\n showEdgeLabels: z.boolean().default(true).describe('Show cardinality labels on relationship edges'),\n\n /** Highlight connected entities on hover */\n highlightOnHover: z.boolean().default(true).describe('Highlight connected entities on node hover'),\n\n /** Click behavior: navigate to object designer */\n clickToNavigate: z.boolean().default(true).describe('Click node to navigate to object detail'),\n\n /** Enable drag-and-drop to create relationships */\n dragToConnect: z.boolean().default(true).describe('Drag between nodes to create relationships'),\n\n /** Filter to show only objects with relationships (hide orphans) */\n hideOrphans: z.boolean().default(false).describe('Hide objects with no relationships'),\n\n /** Auto-fit diagram to viewport on initial load */\n autoFit: z.boolean().default(true).describe('Auto-fit diagram to viewport on load'),\n\n /** Export diagram options */\n exportFormats: z.array(z.enum(['png', 'svg', 'json'])).default(['png', 'svg']).describe('Available export formats for diagram'),\n});\n\nexport type ERDiagramConfig = z.infer;\n\n// ─── Object Manager ──────────────────────────────────────────────────\n\n/** Object list display mode */\nexport const ObjectListDisplayModeSchema = z.enum([\n 'table', // Traditional table with columns\n 'cards', // Card grid (visual overview)\n 'tree', // Hierarchical tree (grouped by package/namespace)\n]).describe('Object list display mode');\n\nexport type ObjectListDisplayMode = z.infer;\n\n/** Object list sort field */\nexport const ObjectSortFieldSchema = z.enum([\n 'name', // Sort by API name\n 'label', // Sort by display label\n 'fieldCount', // Sort by number of fields\n 'updatedAt', // Sort by last modified\n]).describe('Object list sort field');\n\nexport type ObjectSortField = z.infer;\n\n/** Object filter criteria */\nexport const ObjectFilterSchema = z.object({\n /** Filter by package/namespace */\n package: z.string().optional().describe('Filter by owning package'),\n\n /** Filter by tags */\n tags: z.array(z.string()).optional().describe('Filter by object tags'),\n\n /** Show system objects */\n includeSystem: z.boolean().default(true).describe('Include system-level objects'),\n\n /** Show abstract objects */\n includeAbstract: z.boolean().default(false).describe('Include abstract base objects'),\n\n /** Show only objects with specific field types */\n hasFieldType: z.string().optional().describe('Filter to objects containing a specific field type'),\n\n /** Show only objects with relationships */\n hasRelationships: z.boolean().optional().describe('Filter to objects with lookup/master_detail fields'),\n\n /** Text search across name, label, description */\n searchQuery: z.string().optional().describe('Free-text search across name, label, and description'),\n});\n\nexport type ObjectFilter = z.infer;\n\n/**\n * Object Manager configuration — controls the unified object list,\n * search, and management experience.\n */\nexport const ObjectManagerConfigSchema = z.object({\n /** Default display mode */\n defaultDisplayMode: ObjectListDisplayModeSchema.default('table').describe('Default list display mode'),\n\n /** Default sort field */\n defaultSortField: ObjectSortFieldSchema.default('label').describe('Default sort field'),\n\n /** Default sort direction */\n defaultSortDirection: z.enum(['asc', 'desc']).default('asc').describe('Default sort direction'),\n\n /** Default filters */\n defaultFilter: ObjectFilterSchema.default({\n includeSystem: true,\n includeAbstract: false,\n }).describe('Default filter configuration'),\n\n /** Show field count badge on each object row */\n showFieldCount: z.boolean().default(true).describe('Show field count badge'),\n\n /** Show relationship count badge */\n showRelationshipCount: z.boolean().default(true).describe('Show relationship count badge'),\n\n /** Show quick-preview tooltip with field list on hover */\n showQuickPreview: z.boolean().default(true).describe('Show quick field preview tooltip on hover'),\n\n /** Enable object comparison (diff two objects side-by-side) */\n enableComparison: z.boolean().default(false).describe('Enable side-by-side object comparison'),\n\n /** Show ER diagram toggle button in the toolbar */\n showERDiagramToggle: z.boolean().default(true).describe('Show ER diagram toggle in toolbar'),\n\n /** Show \"Create Object\" quick action */\n showCreateAction: z.boolean().default(true).describe('Show create object action'),\n\n /** Show object statistics summary bar (total objects, fields, relationships) */\n showStatsSummary: z.boolean().default(true).describe('Show statistics summary bar'),\n});\n\nexport type ObjectManagerConfig = z.infer;\n\n// ─── Object Preview ──────────────────────────────────────────────────\n\n/**\n * Preview tab configuration — defines the tabs available\n * when viewing a single object.\n */\nexport const ObjectPreviewTabSchema = z.object({\n /** Tab key */\n key: z.string().describe('Tab key'),\n\n /** Tab display label */\n label: z.string().describe('Tab display label'),\n\n /** Lucide icon name */\n icon: z.string().optional().describe('Lucide icon name'),\n\n /** Whether this tab is enabled */\n enabled: z.boolean().default(true).describe('Whether this tab is available'),\n\n /** Sort order */\n order: z.number().default(0).describe('Sort order (lower = higher)'),\n});\n\nexport type ObjectPreviewTab = z.infer;\n\n/**\n * Object Preview configuration — defines the tabs and layout\n * when viewing/editing a single object's metadata.\n */\nexport const ObjectPreviewConfigSchema = z.object({\n /** Tabs to show in the object detail view */\n tabs: z.array(ObjectPreviewTabSchema).default([\n { key: 'fields', label: 'Fields', icon: 'list', enabled: true, order: 0 },\n { key: 'relationships', label: 'Relationships', icon: 'link', enabled: true, order: 10 },\n { key: 'indexes', label: 'Indexes', icon: 'zap', enabled: true, order: 20 },\n { key: 'validations', label: 'Validations', icon: 'shield-check', enabled: true, order: 30 },\n { key: 'capabilities', label: 'Capabilities', icon: 'settings', enabled: true, order: 40 },\n { key: 'data', label: 'Data', icon: 'table-2', enabled: true, order: 50 },\n { key: 'api', label: 'API', icon: 'globe', enabled: true, order: 60 },\n { key: 'code', label: 'Code', icon: 'code-2', enabled: true, order: 70 },\n ]).describe('Object detail preview tabs'),\n\n /** Default active tab */\n defaultTab: z.string().default('fields').describe('Default active tab key'),\n\n /** Show object header with summary info */\n showHeader: z.boolean().default(true).describe('Show object summary header'),\n\n /** Show breadcrumbs */\n showBreadcrumbs: z.boolean().default(true).describe('Show navigation breadcrumbs'),\n});\n\nexport type ObjectPreviewConfig = z.infer;\n\n// ─── Top-Level Object Designer Config ────────────────────────────────\n\n/** Default view when entering the Object Designer */\nexport const ObjectDesignerDefaultViewSchema = z.enum([\n 'field-editor', // Field table editor (default)\n 'relationship-mapper', // Visual relationship view\n 'er-diagram', // Full ER diagram\n 'object-manager', // Object list/manager\n]).describe('Default view when entering the Object Designer');\n\nexport type ObjectDesignerDefaultView = z.infer;\n\n/**\n * Object Designer configuration — top-level config that composes\n * all sub-configurations for the visual object design experience.\n *\n * @example\n * ```typescript\n * const config = ObjectDesignerConfigSchema.parse({\n * defaultView: 'field-editor',\n * fieldEditor: {\n * inlineEditing: true,\n * dragReorder: true,\n * showFieldGroups: true,\n * },\n * erDiagram: {\n * enabled: true,\n * layout: 'force',\n * },\n * objectManager: {\n * defaultDisplayMode: 'table',\n * showERDiagramToggle: true,\n * },\n * });\n * ```\n */\nexport const ObjectDesignerConfigSchema = z.object({\n /** Default view when opening the designer */\n defaultView: ObjectDesignerDefaultViewSchema.default('field-editor').describe('Default view'),\n\n /** Field editor configuration */\n fieldEditor: FieldEditorConfigSchema.default({\n inlineEditing: true,\n dragReorder: true,\n showFieldGroups: true,\n showPropertyPanel: true,\n propertySections: [\n { key: 'basics', label: 'Basic Properties', defaultExpanded: true, order: 0 },\n { key: 'constraints', label: 'Constraints & Validation', defaultExpanded: true, order: 10 },\n { key: 'relationship', label: 'Relationship Config', defaultExpanded: true, order: 20 },\n { key: 'display', label: 'Display & UI', defaultExpanded: false, order: 30 },\n { key: 'security', label: 'Security & Compliance', defaultExpanded: false, order: 40 },\n { key: 'advanced', label: 'Advanced', defaultExpanded: false, order: 50 },\n ],\n fieldGroups: [],\n paginationThreshold: 50,\n batchOperations: true,\n showUsageStats: false,\n }).describe('Field editor configuration'),\n\n /** Relationship mapper configuration */\n relationshipMapper: RelationshipMapperConfigSchema.default({\n visualCreation: true,\n showReverseRelationships: true,\n showCascadeWarnings: true,\n displayConfig: [\n { type: 'lookup', lineStyle: 'dashed', color: '#0891b2', highlightColor: '#06b6d4', cardinalityLabel: '1:N' },\n { type: 'master_detail', lineStyle: 'solid', color: '#ea580c', highlightColor: '#f97316', cardinalityLabel: '1:N' },\n { type: 'tree', lineStyle: 'dotted', color: '#8b5cf6', highlightColor: '#a78bfa', cardinalityLabel: '1:N' },\n ],\n }).describe('Relationship mapper configuration'),\n\n /** ER diagram configuration */\n erDiagram: ERDiagramConfigSchema.default({\n enabled: true,\n layout: 'force',\n nodeDisplay: {\n showFields: true,\n maxFieldsVisible: 8,\n showFieldTypes: true,\n showRequiredIndicator: true,\n showRecordCount: false,\n showIcon: true,\n showDescription: true,\n },\n showMinimap: true,\n zoomControls: true,\n minZoom: 0.1,\n maxZoom: 3,\n showEdgeLabels: true,\n highlightOnHover: true,\n clickToNavigate: true,\n dragToConnect: true,\n hideOrphans: false,\n autoFit: true,\n exportFormats: ['png', 'svg'],\n }).describe('ER diagram configuration'),\n\n /** Object manager configuration */\n objectManager: ObjectManagerConfigSchema.default({\n defaultDisplayMode: 'table',\n defaultSortField: 'label',\n defaultSortDirection: 'asc',\n defaultFilter: {\n includeSystem: true,\n includeAbstract: false,\n },\n showFieldCount: true,\n showRelationshipCount: true,\n showQuickPreview: true,\n enableComparison: false,\n showERDiagramToggle: true,\n showCreateAction: true,\n showStatsSummary: true,\n }).describe('Object manager configuration'),\n\n /** Object preview configuration */\n objectPreview: ObjectPreviewConfigSchema.default({\n tabs: [\n { key: 'fields', label: 'Fields', icon: 'list', enabled: true, order: 0 },\n { key: 'relationships', label: 'Relationships', icon: 'link', enabled: true, order: 10 },\n { key: 'indexes', label: 'Indexes', icon: 'zap', enabled: true, order: 20 },\n { key: 'validations', label: 'Validations', icon: 'shield-check', enabled: true, order: 30 },\n { key: 'capabilities', label: 'Capabilities', icon: 'settings', enabled: true, order: 40 },\n { key: 'data', label: 'Data', icon: 'table-2', enabled: true, order: 50 },\n { key: 'api', label: 'API', icon: 'globe', enabled: true, order: 60 },\n { key: 'code', label: 'Code', icon: 'code-2', enabled: true, order: 70 },\n ],\n defaultTab: 'fields',\n showHeader: true,\n showBreadcrumbs: true,\n }).describe('Object preview configuration'),\n});\n\nexport type ObjectDesignerConfig = z.infer;\n\n// ─── Helper: defineObjectDesignerConfig ──────────────────────────────\n\n/**\n * Type-safe helper for defining Object Designer configuration.\n *\n * @example\n * ```typescript\n * const config = defineObjectDesignerConfig({\n * defaultView: 'er-diagram',\n * erDiagram: {\n * layout: 'hierarchy',\n * showMinimap: true,\n * },\n * objectManager: {\n * defaultDisplayMode: 'cards',\n * },\n * });\n * ```\n */\nexport function defineObjectDesignerConfig(\n input: z.input,\n): ObjectDesignerConfig {\n return ObjectDesignerConfigSchema.parse(input);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio/page-builder\n *\n * Studio Page Builder Protocol\n *\n * Defines the specification for the drag-and-drop Page Builder UI.\n * The builder allows visual composition of blank pages by placing\n * elements on a grid canvas with snapping, alignment, and layer ordering.\n */\n\nimport { z } from 'zod';\n\n/**\n * Canvas Snap Settings Schema\n * Controls grid snapping behavior during element placement.\n */\nexport const CanvasSnapSettingsSchema = z.object({\n enabled: z.boolean().default(true).describe('Enable snap-to-grid'),\n gridSize: z.number().int().min(1).default(8).describe('Snap grid size in pixels'),\n showGrid: z.boolean().default(true).describe('Show grid overlay on canvas'),\n showGuides: z.boolean().default(true).describe('Show alignment guides when dragging'),\n});\n\n/**\n * Canvas Zoom Settings Schema\n * Controls zoom behavior for the builder canvas.\n */\nexport const CanvasZoomSettingsSchema = z.object({\n min: z.number().min(0.1).default(0.25).describe('Minimum zoom level'),\n max: z.number().max(10).default(3).describe('Maximum zoom level'),\n default: z.number().default(1).describe('Default zoom level'),\n step: z.number().default(0.1).describe('Zoom step increment'),\n});\n\n/**\n * Element Palette Item Schema\n * An element available in the builder palette for drag-and-drop placement.\n */\nexport const ElementPaletteItemSchema = z.object({\n type: z.string().describe('Component type (e.g. \"element:button\", \"element:text\")'),\n label: z.string().describe('Display label in palette'),\n icon: z.string().optional().describe('Icon name for palette display'),\n category: z.enum(['content', 'interactive', 'data', 'layout'])\n .describe('Palette category grouping'),\n defaultWidth: z.number().int().min(1).default(4).describe('Default width in grid columns'),\n defaultHeight: z.number().int().min(1).default(2).describe('Default height in grid rows'),\n});\n\n/**\n * Page Builder Config Schema\n * Configuration for the Studio Page Builder.\n */\nexport const PageBuilderConfigSchema = z.object({\n snap: CanvasSnapSettingsSchema.optional().describe('Canvas snap settings'),\n zoom: CanvasZoomSettingsSchema.optional().describe('Canvas zoom settings'),\n palette: z.array(ElementPaletteItemSchema).optional()\n .describe('Custom element palette (defaults to all registered elements)'),\n showLayerPanel: z.boolean().default(true).describe('Show layer ordering panel'),\n showPropertyPanel: z.boolean().default(true).describe('Show property inspector panel'),\n undoLimit: z.number().int().min(1).default(50).describe('Maximum undo history steps'),\n});\n\n// Backward compatibility alias\n/** @deprecated Use PageBuilderConfigSchema instead */\nexport const InterfaceBuilderConfigSchema = PageBuilderConfigSchema;\n\n// Type Exports\nexport type CanvasSnapSettings = z.infer;\nexport type CanvasZoomSettings = z.infer;\nexport type ElementPaletteItem = z.infer;\n/** @deprecated Use PageBuilderConfig instead */\nexport type InterfaceBuilderConfig = z.infer;\nexport type PageBuilderConfig = z.infer;\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * @module studio/flow-builder\n *\n * Studio Flow Builder Protocol\n *\n * Defines the specification for the visual Flow Builder (automation canvas)\n * within ObjectStack Studio. Covers:\n * - **Node Shape Registry**: Shape and visual style per FlowNodeAction type\n * - **Canvas Node**: Position, size, and rendering hints for each node on canvas\n * - **Canvas Edge**: Visual properties for sequence flows (normal, default, fault)\n * - **Flow Builder Config**: Canvas settings, palette, minimap, and toolbar\n *\n * ## Architecture\n *\n * ```\n * ┌──────────────────────────────────────────────────────────────┐\n * │ Toolbar (run / save / undo / zoom / layout) │\n * ├──────────┬───────────────────────────────────┬───────────────┤\n * │ Node │ Canvas │ Property │\n * │ Palette │ ┌─────┐ ┌──────────┐ │ Panel │\n * │ │ │start│───▶│ decision │──▶ ... │ (node-aware) │\n * │ ─ BPMN │ └─────┘ └──────────┘ │ │\n * │ ─ CRUD │ ┌──────────┐ │ ─ config │\n * │ ─ Logic │ │parallel │ │ ─ edges │\n * │ ─ HTTP │ │ gateway │ │ ─ validation │\n * ├──────────┴───────────────────────────────────┴───────────────┤\n * │ Minimap / Zoom Controls │\n * └──────────────────────────────────────────────────────────────┘\n * ```\n */\n\nimport { z } from 'zod';\n\n// ─── Node Shape ──────────────────────────────────────────────────────\n\n/**\n * Shape used to render a flow node on the canvas.\n * Matches BPMN conventions where applicable.\n */\nexport const FlowNodeShapeSchema = z.enum([\n 'rounded_rect', // Default activity shape (assignments, CRUD, HTTP, script, subflow)\n 'circle', // Start / End events\n 'diamond', // Decision (XOR gateway)\n 'parallelogram', // Loop / iteration\n 'hexagon', // Wait / timer event\n 'diamond_thick', // Parallel gateway (AND-split) & Join gateway (AND-join)\n 'attached_circle', // Boundary event (attached to host node)\n 'screen_rect', // Screen / user-interaction node\n]).describe('Visual shape for rendering a flow node on the canvas');\n\nexport type FlowNodeShape = z.infer;\n\n/**\n * Maps each FlowNodeAction to its canvas rendering descriptor.\n * Used by the Studio flow canvas to determine shape, icon, and default size.\n */\nexport const FlowNodeRenderDescriptorSchema = z.object({\n /** The node action type this descriptor applies to */\n action: z.string().describe('FlowNodeAction value (e.g., \"parallel_gateway\")'),\n\n /** Visual shape on the canvas */\n shape: FlowNodeShapeSchema.describe('Shape to render'),\n\n /** Lucide icon name displayed inside the node */\n icon: z.string().describe('Lucide icon name'),\n\n /** Default label shown on the node when no user label is set */\n defaultLabel: z.string().describe('Default display label'),\n\n /** Default width in canvas pixels */\n defaultWidth: z.number().int().min(20).default(120).describe('Default width in pixels'),\n\n /** Default height in canvas pixels */\n defaultHeight: z.number().int().min(20).default(60).describe('Default height in pixels'),\n\n /** CSS color for the node fill */\n fillColor: z.string().default('#ffffff').describe('Node fill color (CSS value)'),\n\n /** CSS color for the node border */\n borderColor: z.string().default('#94a3b8').describe('Node border color (CSS value)'),\n\n /** Whether this node type can have boundary events attached */\n allowBoundaryEvents: z.boolean().default(false)\n .describe('Whether boundary events can be attached to this node type'),\n\n /** Category for palette grouping */\n paletteCategory: z.enum(['event', 'gateway', 'activity', 'data', 'subflow'])\n .describe('Palette category for grouping'),\n}).describe('Visual render descriptor for a flow node type');\n\nexport type FlowNodeRenderDescriptor = z.infer;\n\n// ─── Canvas Node ─────────────────────────────────────────────────────\n\n/**\n * A node instance on the flow canvas, containing position and visual overrides.\n */\nexport const FlowCanvasNodeSchema = z.object({\n /** Reference to the flow node id */\n nodeId: z.string().describe('Corresponding FlowNode.id'),\n\n /** X position on the canvas (pixels) */\n x: z.number().describe('X position on canvas'),\n\n /** Y position on the canvas (pixels) */\n y: z.number().describe('Y position on canvas'),\n\n /** Width override (pixels, optional — uses descriptor default) */\n width: z.number().int().min(20).optional().describe('Width override in pixels'),\n\n /** Height override (pixels, optional — uses descriptor default) */\n height: z.number().int().min(20).optional().describe('Height override in pixels'),\n\n /** Whether the node is collapsed (hides internal details) */\n collapsed: z.boolean().default(false).describe('Whether the node is collapsed'),\n\n /** Custom fill color override */\n fillColor: z.string().optional().describe('Fill color override'),\n\n /** Custom border color override */\n borderColor: z.string().optional().describe('Border color override'),\n\n /** User-defined comment/annotation visible on canvas */\n annotation: z.string().optional().describe('User annotation displayed near the node'),\n}).describe('Canvas layout data for a flow node');\n\nexport type FlowCanvasNode = z.infer;\n\n// ─── Canvas Edge ─────────────────────────────────────────────────────\n\n/**\n * Visual style for a sequence flow edge on the canvas.\n */\nexport const FlowCanvasEdgeStyleSchema = z.enum([\n 'solid', // Normal sequence flow\n 'dashed', // Default sequence flow (isDefault: true)\n 'dotted', // Conditional edge\n 'bold', // Fault / error edge\n]).describe('Edge line style');\n\nexport type FlowCanvasEdgeStyle = z.infer;\n\n/**\n * A sequence-flow edge on the flow canvas with visual properties.\n */\nexport const FlowCanvasEdgeSchema = z.object({\n /** Reference to the flow edge id */\n edgeId: z.string().describe('Corresponding FlowEdge.id'),\n\n /** Line style */\n style: FlowCanvasEdgeStyleSchema.default('solid').describe('Line style'),\n\n /** Line color (CSS value) */\n color: z.string().default('#94a3b8').describe('Edge line color'),\n\n /** Label position along the edge (0–1, 0.5 = midpoint) */\n labelPosition: z.number().min(0).max(1).default(0.5)\n .describe('Position of the condition label along the edge'),\n\n /** Optional waypoints for routing the edge around nodes */\n waypoints: z.array(z.object({\n x: z.number().describe('Waypoint X'),\n y: z.number().describe('Waypoint Y'),\n })).optional().describe('Manual waypoints for edge routing'),\n\n /** Whether to show an animated flow indicator */\n animated: z.boolean().default(false).describe('Show animated flow indicator'),\n}).describe('Canvas layout and visual data for a flow edge');\n\nexport type FlowCanvasEdge = z.infer;\n\n// ─── Flow Canvas Layout ──────────────────────────────────────────────\n\n/**\n * Auto-layout algorithm for the flow canvas.\n */\nexport const FlowLayoutAlgorithmSchema = z.enum([\n 'dagre', // Directed acyclic graph layout (top-down or left-right)\n 'elk', // Eclipse Layout Kernel (advanced hierarchical)\n 'force', // Force-directed graph\n 'manual', // User-positioned (no auto-layout)\n]).describe('Auto-layout algorithm for the flow canvas');\n\nexport type FlowLayoutAlgorithm = z.infer;\n\n/**\n * Direction for the auto-layout.\n */\nexport const FlowLayoutDirectionSchema = z.enum([\n 'TB', // Top to bottom\n 'BT', // Bottom to top\n 'LR', // Left to right\n 'RL', // Right to left\n]).describe('Auto-layout direction');\n\nexport type FlowLayoutDirection = z.infer;\n\n// ─── Flow Builder Config ─────────────────────────────────────────────\n\n/**\n * Flow Builder configuration — top-level config for the Studio\n * automation flow canvas editor.\n */\nexport const FlowBuilderConfigSchema = z.object({\n /** Canvas snap settings */\n snap: z.object({\n enabled: z.boolean().default(true).describe('Enable snap-to-grid'),\n gridSize: z.number().int().min(1).default(16).describe('Snap grid size in pixels'),\n showGrid: z.boolean().default(true).describe('Show grid overlay'),\n }).default({ enabled: true, gridSize: 16, showGrid: true })\n .describe('Canvas snap-to-grid settings'),\n\n /** Canvas zoom settings */\n zoom: z.object({\n min: z.number().min(0.1).default(0.25).describe('Minimum zoom level'),\n max: z.number().max(10).default(3).describe('Maximum zoom level'),\n default: z.number().default(1).describe('Default zoom level'),\n step: z.number().default(0.1).describe('Zoom step'),\n }).default({ min: 0.25, max: 3, default: 1, step: 0.1 })\n .describe('Canvas zoom settings'),\n\n /** Auto-layout algorithm */\n layoutAlgorithm: FlowLayoutAlgorithmSchema.default('dagre')\n .describe('Default auto-layout algorithm'),\n\n /** Auto-layout direction */\n layoutDirection: FlowLayoutDirectionSchema.default('TB')\n .describe('Default auto-layout direction'),\n\n /** Node render descriptors (override defaults per node type) */\n nodeDescriptors: z.array(FlowNodeRenderDescriptorSchema).optional()\n .describe('Custom node render descriptors (merged with built-in defaults)'),\n\n /** Show minimap for navigation */\n showMinimap: z.boolean().default(true).describe('Show minimap panel'),\n\n /** Show the node property panel */\n showPropertyPanel: z.boolean().default(true).describe('Show property panel'),\n\n /** Show the node palette sidebar */\n showPalette: z.boolean().default(true).describe('Show node palette sidebar'),\n\n /** Maximum undo history steps */\n undoLimit: z.number().int().min(1).default(50).describe('Maximum undo history steps'),\n\n /** Enable edge animation during execution preview */\n animateExecution: z.boolean().default(true)\n .describe('Animate edges during execution preview'),\n\n /** Connection validation — prevent invalid edges (e.g., duplicate, self-loop) */\n connectionValidation: z.boolean().default(true)\n .describe('Validate connections before creating edges'),\n}).describe('Studio Flow Builder configuration');\n\nexport type FlowBuilderConfig = z.infer;\n\n// ─── Built-in Node Descriptors ───────────────────────────────────────\n\n/**\n * Built-in node render descriptors for all standard FlowNodeAction types.\n * Studio implementations should merge user overrides on top of these defaults.\n */\nexport const BUILT_IN_NODE_DESCRIPTORS: FlowNodeRenderDescriptor[] = [\n { action: 'start', shape: 'circle', icon: 'play', defaultLabel: 'Start', defaultWidth: 60, defaultHeight: 60, fillColor: '#dcfce7', borderColor: '#16a34a', allowBoundaryEvents: false, paletteCategory: 'event' },\n { action: 'end', shape: 'circle', icon: 'square', defaultLabel: 'End', defaultWidth: 60, defaultHeight: 60, fillColor: '#fee2e2', borderColor: '#dc2626', allowBoundaryEvents: false, paletteCategory: 'event' },\n { action: 'decision', shape: 'diamond', icon: 'git-branch', defaultLabel: 'Decision', defaultWidth: 80, defaultHeight: 80, fillColor: '#fef9c3', borderColor: '#ca8a04', allowBoundaryEvents: false, paletteCategory: 'gateway' },\n { action: 'parallel_gateway', shape: 'diamond_thick', icon: 'git-fork', defaultLabel: 'Parallel Gateway', defaultWidth: 80, defaultHeight: 80, fillColor: '#dbeafe', borderColor: '#2563eb', allowBoundaryEvents: false, paletteCategory: 'gateway' },\n { action: 'join_gateway', shape: 'diamond_thick', icon: 'git-merge', defaultLabel: 'Join Gateway', defaultWidth: 80, defaultHeight: 80, fillColor: '#dbeafe', borderColor: '#2563eb', allowBoundaryEvents: false, paletteCategory: 'gateway' },\n { action: 'wait', shape: 'hexagon', icon: 'clock', defaultLabel: 'Wait', defaultWidth: 100, defaultHeight: 60, fillColor: '#f3e8ff', borderColor: '#7c3aed', allowBoundaryEvents: true, paletteCategory: 'event' },\n { action: 'boundary_event', shape: 'attached_circle', icon: 'alert-circle', defaultLabel: 'Boundary Event', defaultWidth: 40, defaultHeight: 40, fillColor: '#fff7ed', borderColor: '#ea580c', allowBoundaryEvents: false, paletteCategory: 'event' },\n { action: 'assignment', shape: 'rounded_rect', icon: 'pen-line', defaultLabel: 'Assignment', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'activity' },\n { action: 'create_record', shape: 'rounded_rect', icon: 'plus-circle', defaultLabel: 'Create Record', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'data' },\n { action: 'update_record', shape: 'rounded_rect', icon: 'edit', defaultLabel: 'Update Record', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'data' },\n { action: 'delete_record', shape: 'rounded_rect', icon: 'trash-2', defaultLabel: 'Delete Record', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'data' },\n { action: 'get_record', shape: 'rounded_rect', icon: 'search', defaultLabel: 'Get Record', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'data' },\n { action: 'http_request', shape: 'rounded_rect', icon: 'globe', defaultLabel: 'HTTP Request', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'activity' },\n { action: 'script', shape: 'rounded_rect', icon: 'code', defaultLabel: 'Script', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'activity' },\n { action: 'screen', shape: 'screen_rect', icon: 'monitor', defaultLabel: 'Screen', defaultWidth: 140, defaultHeight: 80, fillColor: '#f0f9ff', borderColor: '#0284c7', allowBoundaryEvents: false, paletteCategory: 'activity' },\n { action: 'loop', shape: 'parallelogram', icon: 'repeat', defaultLabel: 'Loop', defaultWidth: 120, defaultHeight: 60, fillColor: '#fef3c7', borderColor: '#d97706', allowBoundaryEvents: true, paletteCategory: 'activity' },\n { action: 'subflow', shape: 'rounded_rect', icon: 'layers', defaultLabel: 'Subflow', defaultWidth: 140, defaultHeight: 70, fillColor: '#ede9fe', borderColor: '#7c3aed', allowBoundaryEvents: true, paletteCategory: 'subflow' },\n { action: 'connector_action', shape: 'rounded_rect', icon: 'plug', defaultLabel: 'Connector', defaultWidth: 120, defaultHeight: 60, fillColor: '#ffffff', borderColor: '#94a3b8', allowBoundaryEvents: true, paletteCategory: 'activity' },\n];\n\n// ─── Helper: defineFlowBuilderConfig ─────────────────────────────────\n\n/**\n * Type-safe helper for defining Flow Builder configuration.\n *\n * @example\n * ```typescript\n * const config = defineFlowBuilderConfig({\n * layoutAlgorithm: 'dagre',\n * layoutDirection: 'LR',\n * showMinimap: true,\n * snap: { gridSize: 20 },\n * });\n * ```\n */\nexport function defineFlowBuilderConfig(\n input: z.input,\n): FlowBuilderConfig {\n return FlowBuilderConfigSchema.parse(input);\n}\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { z } from 'zod';\n\nimport { ManifestSchema } from './kernel/manifest.zod';\nimport { DatasourceSchema } from './data/datasource.zod';\nimport { TranslationBundleSchema, TranslationConfigSchema } from './system/translation.zod';\nimport { objectStackErrorMap, formatZodError } from './shared/error-map.zod';\nimport { normalizeStackInput, type MetadataCollectionInput, type MapSupportedField } from './shared/metadata-collection.zod';\n\n// Data Protocol\nimport { ObjectSchema, ObjectExtensionSchema } from './data/object.zod';\nimport { DatasetSchema } from './data/dataset.zod';\n\n// UI Protocol\nimport { AppSchema } from './ui/app.zod';\nimport { ViewSchema } from './ui/view.zod';\nimport { PageSchema } from './ui/page.zod';\nimport { DashboardSchema } from './ui/dashboard.zod';\nimport { ReportSchema } from './ui/report.zod';\nimport { ActionSchema } from './ui/action.zod';\nimport { ThemeSchema } from './ui/theme.zod';\n\n// Automation Protocol\nimport { ApprovalProcessSchema } from './automation/approval.zod';\nimport { WorkflowRuleSchema } from './automation/workflow.zod';\nimport { FlowSchema } from './automation/flow.zod';\n\n// Security Protocol\nimport { RoleSchema } from './identity/role.zod';\nimport { PermissionSetSchema } from './security/permission.zod';\nimport { SharingRuleSchema } from './security/sharing.zod';\nimport { PolicySchema } from './security/policy.zod';\n\nimport { ApiEndpointSchema } from './api/endpoint.zod';\nimport { FeatureFlagSchema } from './kernel/feature.zod';\n\n// AI Protocol\nimport { AgentSchema } from './ai/agent.zod';\nimport { RAGPipelineConfigSchema } from './ai/rag-pipeline.zod';\n\n// Data Protocol (additional)\nimport { HookSchema } from './data/hook.zod';\nimport { MappingSchema } from './data/mapping.zod';\nimport { CubeSchema } from './data/analytics.zod';\n\n// Automation Protocol (additional)\nimport { WebhookSchema } from './automation/webhook.zod';\n\n// Integration Protocol\nimport { ConnectorSchema } from './integration/connector.zod';\n\n/**\n * ObjectStack Ecosystem Definition\n * \n * This schema represents the \"Full Stack\" definition of a project or environment.\n * It is used for:\n * 1. Project Export/Import (YAML/JSON dumps)\n * 2. IDE Validation (IntelliSense)\n * 3. Runtime Bootstrapping (In-memory loading)\n * 4. Platform Reflection (API & Capabilities Discovery)\n */\n/**\n * 1. DEFINITION PROTOCOL (Static)\n * ----------------------------------------------------------------------\n * Describes the \"Blueprint\" or \"Source Code\" of an ObjectStack Plugin/Project.\n * This represents the complete declarative state of the application.\n * \n * Usage:\n * - Developers write this in files locally.\n * - AI Agents generate this to create apps.\n * - CI Tools deploy this to the server.\n */\nexport const ObjectStackDefinitionSchema = z.object({\n /** System Configuration */\n manifest: ManifestSchema.optional().describe('Project Package Configuration'),\n datasources: z.array(DatasourceSchema).optional().describe('External Data Connections'),\n translations: z.array(TranslationBundleSchema).optional().describe('I18n Translation Bundles'),\n i18n: TranslationConfigSchema.optional().describe('Internationalization configuration'),\n\n /** \n * ObjectQL: Data Layer \n * All business objects and entities.\n */\n objects: z.array(ObjectSchema).optional().describe('Business Objects definition (owned by this package)'),\n\n /**\n * Object Extensions: fields/config to merge into objects owned by other packages.\n * Use this instead of redefining an object when you want to add fields to\n * an existing object from another package.\n * \n * @example\n * ```ts\n * objectExtensions: [{\n * extend: 'contact',\n * fields: { sales_stage: Field.select([...]) },\n * }]\n * ```\n */\n objectExtensions: z.array(ObjectExtensionSchema).optional().describe('Extensions to objects owned by other packages'),\n\n /** \n * ObjectUI: User Interface Layer \n * Apps, Menus, Pages, and Visualizations.\n */\n apps: z.array(AppSchema).optional().describe('Applications'),\n views: z.array(ViewSchema).optional().describe('List Views'),\n pages: z.array(PageSchema).optional().describe('Custom Pages'),\n dashboards: z.array(DashboardSchema).optional().describe('Dashboards'),\n reports: z.array(ReportSchema).optional().describe('Analytics Reports'),\n actions: z.array(ActionSchema).optional().describe('Global and Object Actions'),\n themes: z.array(ThemeSchema).optional().describe('UI Themes'),\n\n /** \n * ObjectFlow: Automation Layer \n * Business logic, approvals, and workflows.\n */\n workflows: z.array(WorkflowRuleSchema).optional().describe('Event-driven workflows'),\n approvals: z.array(ApprovalProcessSchema).optional().describe('Approval processes'),\n flows: z.array(FlowSchema).optional().describe('Screen Flows'),\n\n /**\n * ObjectGuard: Security Layer\n */\n roles: z.array(RoleSchema).optional().describe('User Roles hierarchy'),\n permissions: z.array(PermissionSetSchema).optional().describe('Permission Sets and Profiles'),\n sharingRules: z.array(SharingRuleSchema).optional().describe('Record Sharing Rules'),\n policies: z.array(PolicySchema).optional().describe('Security & Compliance Policies'),\n\n /**\n * ObjectAPI: API Layer\n */\n apis: z.array(ApiEndpointSchema).optional().describe('API Endpoints'),\n webhooks: z.array(WebhookSchema).optional().describe('Outbound Webhooks'),\n\n /**\n * ObjectAI: Artificial Intelligence Layer\n */\n agents: z.array(AgentSchema).optional().describe('AI Agents and Assistants'),\n ragPipelines: z.array(RAGPipelineConfigSchema).optional().describe('RAG Pipelines'),\n\n /**\n * ObjectQL: Data Extensions\n * Hooks, mappings, and analytics cubes.\n */\n hooks: z.array(HookSchema).optional().describe('Object Lifecycle Hooks'),\n mappings: z.array(MappingSchema).optional().describe('Data Import/Export Mappings'),\n analyticsCubes: z.array(CubeSchema).optional().describe('Analytics Semantic Layer Cubes'),\n\n /**\n * Integration Protocol\n */\n connectors: z.array(ConnectorSchema).optional().describe('External System Connectors'),\n\n /**\n * Data Seeding Protocol\n * \n * Declarative seed data for bootstrapping, demos, and testing.\n * Each entry targets a specific object and provides records to load\n * using the specified conflict resolution strategy.\n * \n * Uses the standard DatasetSchema which supports:\n * - `externalId`: Idempotency key for upsert matching (default: 'name')\n * - `mode`: Conflict resolution (upsert, insert, ignore, replace)\n * - `env`: Environment scoping (prod, dev, test)\n * \n * @example\n * ```ts\n * data: [\n * {\n * object: 'account',\n * mode: 'upsert',\n * externalId: 'name',\n * records: [\n * { name: 'Acme Corp', type: 'customer', industry: 'technology' },\n * ]\n * }\n * ]\n * ```\n */\n data: z.array(DatasetSchema).optional().describe('Seed Data / Fixtures for bootstrapping'),\n\n /**\n * Plugins: External Capabilities\n * List of plugins to load. Can be a Manifest object, a package name string, or a Runtime Plugin instance.\n */\n plugins: z.array(z.unknown()).optional().describe('Plugins to load'),\n\n /**\n * DevPlugins: Development Capabilities\n * List of plugins to load ONLY in development environment.\n * Equivalent to `devDependencies` in package.json.\n * Useful for loading dev-tools, mock data generators, or referencing local sibling packages for debugging.\n */\n devPlugins: z.array(z.union([ManifestSchema, z.string()])).optional().describe('Plugins to load only in development (CLI dev command)'),\n});\n\nexport type ObjectStackDefinition = z.infer;\n\n/**\n * Extract the element type from an array type.\n * @internal\n */\ntype ExtractArrayItem = T extends (infer Item)[] ? Item : never;\n\n/**\n * Input type for `defineStack()` that accepts both array and map format\n * for all named metadata collections.\n * \n * Map format allows defining metadata using the key as the `name` field:\n * ```ts\n * // Array format (traditional)\n * objects: [{ name: 'task', fields: { ... } }]\n * \n * // Map format (key becomes name)\n * objects: { task: { fields: { ... } } }\n * ```\n * \n * The output type is always arrays (`ObjectStackDefinition`).\n */\nexport type ObjectStackDefinitionInput =\n Omit, MapSupportedField> & {\n [K in MapSupportedField]?: MetadataCollectionInput<\n ExtractArrayItem[K]>>\n >;\n };\n\n// Alias for backward compatibility\nexport const ObjectStackSchema = ObjectStackDefinitionSchema;\nexport type ObjectStack = ObjectStackDefinition;\n\n/**\n * Options for `defineStack()`.\n */\nexport interface DefineStackOptions {\n /**\n * When `true` (default), enables strict validation:\n * - All Zod schemas are validated (field names, types, etc.)\n * - Cross-reference validation runs (views/actions/workflows reference valid objects)\n * - Ensures data integrity and catches errors early\n *\n * When `false`, validation is skipped for maximum flexibility\n * (e.g., when views reference objects provided by other plugins).\n * Use this ONLY when you need to bypass validation for advanced use cases.\n *\n * @default true\n */\n strict?: boolean;\n}\n\n/**\n * Collect all object names defined in a stack definition.\n */\nfunction collectObjectNames(config: ObjectStackDefinition): Set {\n const names = new Set();\n if (config.objects) {\n for (const obj of config.objects) {\n names.add(obj.name);\n }\n }\n return names;\n}\n\n/**\n * Perform strict cross-reference validation on a parsed stack definition.\n * Returns an array of error messages (empty if valid).\n */\nfunction validateCrossReferences(config: ObjectStackDefinition): string[] {\n const errors: string[] = [];\n const objectNames = collectObjectNames(config);\n\n if (objectNames.size === 0) return errors;\n\n // Validate workflow → object references (uses `objectName`)\n if (config.workflows) {\n for (const workflow of config.workflows) {\n if (workflow.objectName && !objectNames.has(workflow.objectName)) {\n errors.push(\n `Workflow '${workflow.name}' references object '${workflow.objectName}' which is not defined in objects.`,\n );\n }\n }\n }\n\n // Validate approval → object references\n if (config.approvals) {\n for (const approval of config.approvals) {\n if (approval.object && !objectNames.has(approval.object)) {\n errors.push(\n `Approval '${approval.name}' references object '${approval.object}' which is not defined in objects.`,\n );\n }\n }\n }\n\n // Validate hook → object references\n if (config.hooks) {\n for (const hook of config.hooks) {\n if (hook.object) {\n const hookObjects = Array.isArray(hook.object) ? hook.object : [hook.object];\n for (const obj of hookObjects) {\n if (!objectNames.has(obj)) {\n errors.push(\n `Hook '${hook.name}' references object '${obj}' which is not defined in objects.`,\n );\n }\n }\n }\n }\n }\n\n // Validate view data source → object references (nested in data.object)\n if (config.views) {\n for (const [i, view] of config.views.entries()) {\n const checkViewData = (data: unknown, viewLabel: string) => {\n if (data && typeof data === 'object' && 'provider' in data && 'object' in data) {\n const d = data as { provider: string; object: string };\n if (d.provider === 'object' && d.object && !objectNames.has(d.object)) {\n errors.push(\n `${viewLabel} references object '${d.object}' which is not defined in objects.`,\n );\n }\n }\n };\n\n if (view.list?.data) {\n checkViewData(view.list.data, `View[${i}].list`);\n }\n if (view.form?.data) {\n checkViewData(view.form.data, `View[${i}].form`);\n }\n }\n }\n\n // Validate seed data → object references\n if (config.data) {\n for (const dataset of config.data) {\n if (dataset.object && !objectNames.has(dataset.object)) {\n errors.push(\n `Seed data references object '${dataset.object}' which is not defined in objects.`,\n );\n }\n }\n }\n\n // Validate app navigation → object/dashboard/page/report references\n if (config.apps) {\n const dashboardNames = new Set();\n if (config.dashboards) {\n for (const d of config.dashboards) {\n dashboardNames.add(d.name);\n }\n }\n const pageNames = new Set();\n if (config.pages) {\n for (const p of config.pages) {\n pageNames.add(p.name);\n }\n }\n const reportNames = new Set();\n if (config.reports) {\n for (const r of config.reports) {\n reportNames.add(r.name);\n }\n }\n\n for (const app of config.apps) {\n if (!app.navigation) continue;\n const checkNavItems = (items: unknown[], appName: string) => {\n for (const item of items) {\n if (!item || typeof item !== 'object') continue;\n const nav = item as Record;\n if (nav.type === 'object' && typeof nav.objectName === 'string' && !objectNames.has(nav.objectName)) {\n errors.push(\n `App '${appName}' navigation references object '${nav.objectName}' which is not defined in objects.`,\n );\n }\n if (nav.type === 'dashboard' && typeof nav.dashboardName === 'string' && dashboardNames.size > 0 && !dashboardNames.has(nav.dashboardName)) {\n errors.push(\n `App '${appName}' navigation references dashboard '${nav.dashboardName}' which is not defined in dashboards.`,\n );\n }\n if (nav.type === 'page' && typeof nav.pageName === 'string' && pageNames.size > 0 && !pageNames.has(nav.pageName)) {\n errors.push(\n `App '${appName}' navigation references page '${nav.pageName}' which is not defined in pages.`,\n );\n }\n if (nav.type === 'report' && typeof nav.reportName === 'string' && reportNames.size > 0 && !reportNames.has(nav.reportName)) {\n errors.push(\n `App '${appName}' navigation references report '${nav.reportName}' which is not defined in reports.`,\n );\n }\n // Recurse into group children\n if (nav.type === 'group' && Array.isArray(nav.children)) {\n checkNavItems(nav.children, appName);\n }\n }\n };\n checkNavItems(app.navigation, app.name);\n }\n }\n\n // Validate action → flow/modal cross-references\n // Note: When no flows/pages are defined (size === 0), targets are not validated\n // because the referenced items may be provided by a plugin.\n // This is consistent with dashboard/page/report validation in navigation.\n if (config.actions) {\n const flowNames = new Set();\n if (config.flows) {\n for (const flow of config.flows) {\n flowNames.add(flow.name);\n }\n }\n\n const pageNames = new Set();\n if (config.pages) {\n for (const page of config.pages) {\n pageNames.add(page.name);\n }\n }\n\n for (const action of config.actions) {\n // Validate flow-type actions reference a defined flow\n if (action.type === 'flow' && action.target && flowNames.size > 0 && !flowNames.has(action.target)) {\n errors.push(\n `Action '${action.name}' references flow '${action.target}' which is not defined in flows.`,\n );\n }\n\n // Validate modal-type actions reference a defined page\n if (action.type === 'modal' && action.target && pageNames.size > 0 && !pageNames.has(action.target)) {\n errors.push(\n `Action '${action.name}' references page '${action.target}' (via modal target) which is not defined in pages.`,\n );\n }\n\n // Validate action → object references (objectName)\n if (action.objectName && !objectNames.has(action.objectName)) {\n errors.push(\n `Action '${action.name}' references object '${action.objectName}' which is not defined in objects.`,\n );\n }\n }\n }\n\n return errors;\n}\n\n/**\n * Merge top-level actions into their target objects based on `objectName`.\n * \n * Actions with `objectName` are appended to the corresponding object's `actions` array.\n * Actions without `objectName` (global actions) are left untouched.\n * The top-level `actions` array is preserved for global access (e.g., platform overview, search).\n * \n * This aligns with Salesforce/ServiceNow patterns where object metadata includes its actions,\n * so API responses like `/api/v1/meta/objects/:name` include actions without downstream merge.\n * \n * @internal\n */\nfunction mergeActionsIntoObjects(config: ObjectStackDefinition): ObjectStackDefinition {\n if (!config.actions || !config.objects || config.objects.length === 0) {\n return config;\n }\n\n // Build map: objectName → actions[]\n const actionsByObject = new Map>();\n for (const action of config.actions) {\n if (action.objectName) {\n const list = actionsByObject.get(action.objectName) ?? [];\n list.push(action);\n actionsByObject.set(action.objectName, list);\n }\n }\n\n if (actionsByObject.size === 0) return config;\n\n // Merge into objects (shallow copy — only the `actions` field is modified;\n // other fields are shared references, consistent with mergeObjects() and Zod output)\n const newObjects = config.objects.map((obj) => {\n const objActions = actionsByObject.get(obj.name);\n if (!objActions) return obj;\n return {\n ...obj,\n actions: [...(obj.actions ?? []), ...objActions],\n };\n });\n\n return { ...config, objects: newObjects };\n}\n\n/**\n * Type-safe helper to define a generic stack.\n *\n * In ObjectStack, the concept of \"Project\" and \"Plugin\" is fluid:\n * - A **Project** is simply a Stack that is currently being executed (the `cwd`).\n * - A **Plugin** is a Stack that is being loaded by another Stack.\n *\n * This unified definition allows any \"Project\" (e.g., Todo App) to be imported\n * as a \"Plugin\" into a larger system (e.g., Company PaaS) without code changes.\n *\n * @param config - The stack definition object\n * @param options - Optional settings. Use `{ strict: true }` to validate cross-references.\n * @returns The validated stack definition\n *\n * @example\n * ```ts\n * // Basic usage (pass-through, backward compatible)\n * const stack = defineStack({ manifest: { ... }, objects: [...] });\n *\n * // Map format — key becomes `name` field\n * const stack = defineStack({\n * objects: {\n * task: { fields: { title: { type: 'text' } } },\n * project: { fields: { name: { type: 'text' } } },\n * },\n * apps: {\n * project_manager: { label: 'Project Manager', objects: ['task', 'project'] },\n * },\n * });\n *\n * // Strict mode — validates that views/workflows reference defined objects\n * const stack = defineStack({ manifest: { ... }, objects: [...], views: [...] }, { strict: true });\n * ```\n */\nexport function defineStack(\n config: ObjectStackDefinitionInput,\n options?: DefineStackOptions,\n): ObjectStackDefinition {\n // Default to strict=true for safety (validate by default)\n const strict = options?.strict !== false;\n\n // Normalize map-formatted collections to arrays (key → name injection)\n const normalized = normalizeStackInput(config as Record);\n\n if (!strict) {\n // Non-strict mode: skip validation (advanced use cases only)\n return mergeActionsIntoObjects(normalized as ObjectStackDefinition);\n }\n\n // Strict mode (default): parse with custom error map, then cross-reference validate\n const result = ObjectStackDefinitionSchema.safeParse(normalized, {\n error: objectStackErrorMap,\n });\n\n if (!result.success) {\n throw new Error(formatZodError(result.error, 'defineStack validation failed'));\n }\n\n const crossRefErrors = validateCrossReferences(result.data);\n if (crossRefErrors.length > 0) {\n const header = `defineStack cross-reference validation failed (${crossRefErrors.length} issue${crossRefErrors.length === 1 ? '' : 's'}):`;\n const lines = crossRefErrors.map((e) => ` ✗ ${e}`);\n throw new Error(`${header}\\n\\n${lines.join('\\n')}`);\n }\n\n return mergeActionsIntoObjects(result.data);\n}\n\n\n// ─── composeStacks ──────────────────────────────────────────────────\n\n/**\n * Strategy for resolving conflicts when multiple stacks define the same named item.\n *\n * - `'error'` — Throw an error when a duplicate name is detected (default).\n * - `'override'` — Last stack wins; later definitions replace earlier ones.\n * - `'merge'` — Shallow-merge items with the same name (later fields win).\n */\nexport const ConflictStrategySchema = z.enum(['error', 'override', 'merge']);\nexport type ConflictStrategy = z.infer;\n\n/**\n * Options for {@link composeStacks}.\n */\nexport const ComposeStacksOptionsSchema = z.object({\n /**\n * How to handle same-name objects across stacks.\n * @default 'error'\n */\n objectConflict: ConflictStrategySchema.default('error'),\n\n /**\n * Which manifest to keep when multiple stacks provide one.\n * - `'first'` — Use the first manifest found.\n * - `'last'` — Use the last manifest found (default).\n * - A number — Use the manifest from the stack at the given index.\n * @default 'last'\n */\n manifest: z.union([z.enum(['first', 'last']), z.number().int().min(0)]).default('last'),\n\n /**\n * Optional namespace prefix (reserved for Phase 2 — Marketplace isolation).\n * When set, object names from this composition are prefixed for isolation.\n */\n namespace: z.string().optional(),\n});\n\nexport type ComposeStacksOptions = z.input;\n\n/**\n * All array fields on `ObjectStackDefinition` that are simply concatenated.\n * @internal\n */\nconst CONCAT_ARRAY_FIELDS = [\n 'datasources',\n 'translations',\n 'objectExtensions',\n 'apps',\n 'views',\n 'pages',\n 'dashboards',\n 'reports',\n 'actions',\n 'themes',\n 'workflows',\n 'approvals',\n 'flows',\n 'roles',\n 'permissions',\n 'sharingRules',\n 'policies',\n 'apis',\n 'webhooks',\n 'agents',\n 'ragPipelines',\n 'hooks',\n 'mappings',\n 'analyticsCubes',\n 'connectors',\n 'data',\n 'plugins',\n 'devPlugins',\n] as const satisfies readonly (keyof ObjectStackDefinition)[];\n\n/**\n * Merge objects from multiple stacks according to the chosen conflict strategy.\n * @internal\n */\nfunction mergeObjects(\n stacks: ObjectStackDefinition[],\n strategy: ConflictStrategy,\n): ObjectStackDefinition['objects'] {\n type Obj = NonNullable[number];\n const map = new Map();\n const result: Obj[] = [];\n\n for (const stack of stacks) {\n if (!stack.objects) continue;\n for (const obj of stack.objects) {\n const existing = map.get(obj.name);\n if (!existing) {\n map.set(obj.name, obj);\n result.push(obj);\n continue;\n }\n\n switch (strategy) {\n case 'error':\n throw new Error(\n `composeStacks conflict: object '${obj.name}' is defined in multiple stacks. ` +\n `Use { objectConflict: 'override' } or { objectConflict: 'merge' } to resolve.`,\n );\n case 'override': {\n // Replace in-place in the result array\n const idx = result.indexOf(existing);\n result[idx] = obj;\n map.set(obj.name, obj);\n break;\n }\n case 'merge': {\n const merged = { ...existing, ...obj, fields: { ...existing.fields, ...obj.fields } } as Obj;\n const idx = result.indexOf(existing);\n result[idx] = merged;\n map.set(obj.name, merged);\n break;\n }\n }\n }\n }\n\n return result.length > 0 ? result : undefined;\n}\n\n/**\n * Select the manifest to use from multiple stacks.\n * @internal\n */\nfunction selectManifest(\n stacks: ObjectStackDefinition[],\n strategy: 'first' | 'last' | number,\n): ObjectStackDefinition['manifest'] {\n if (typeof strategy === 'number') {\n return stacks[strategy]?.manifest;\n }\n if (strategy === 'first') {\n for (const s of stacks) {\n if (s.manifest) return s.manifest;\n }\n return undefined;\n }\n // 'last' (default)\n for (let i = stacks.length - 1; i >= 0; i--) {\n if (stacks[i].manifest) return stacks[i].manifest;\n }\n return undefined;\n}\n\n/**\n * Declaratively compose multiple stack definitions into a single unified stack.\n *\n * This eliminates the manual `...spread` merging pattern when combining\n * multiple applications (e.g., CRM + Todo + BI) into a single project.\n *\n * **Array fields** (apps, views, dashboards, etc.) are concatenated in order.\n * **Objects** are merged according to the `objectConflict` strategy.\n * **Manifest** is selected based on the `manifest` option.\n *\n * @param stacks - Stack definitions to compose (order matters for conflict resolution)\n * @param options - Composition options (conflict strategy, manifest selection, etc.)\n * @returns A single merged `ObjectStackDefinition`\n *\n * @example\n * ```ts\n * import { composeStacks, defineStack } from '@objectstack/spec';\n *\n * const crm = defineStack({ ... });\n * const todo = defineStack({ ... });\n *\n * // Simple composition — throws on duplicate objects\n * const combined = composeStacks([crm, todo]);\n *\n * // Override strategy — later stacks win\n * const combined = composeStacks([crm, todo], { objectConflict: 'override' });\n *\n * // Merge strategy — fields from later stacks are shallow-merged\n * const combined = composeStacks([crm, todo], { objectConflict: 'merge' });\n * ```\n */\nexport function composeStacks(\n stacks: ObjectStackDefinition[],\n options?: ComposeStacksOptions,\n): ObjectStackDefinition {\n if (stacks.length === 0) return {} as ObjectStackDefinition;\n if (stacks.length === 1) return stacks[0];\n\n const opts = ComposeStacksOptionsSchema.parse(options ?? {});\n\n const composed: Record = {};\n\n // 1. Manifest — pick based on strategy\n composed.manifest = selectManifest(stacks, opts.manifest);\n\n // 2. i18n — last-wins (single object, not array)\n for (let i = stacks.length - 1; i >= 0; i--) {\n if (stacks[i].i18n) {\n composed.i18n = stacks[i].i18n;\n break;\n }\n }\n\n // 3. Objects — use conflict strategy\n const objects = mergeObjects(stacks, opts.objectConflict);\n if (objects) {\n composed.objects = objects;\n }\n\n // 4. All other array fields — simple concatenation\n for (const field of CONCAT_ARRAY_FIELDS) {\n const arrays = stacks\n .map((s) => (s as Record)[field])\n .filter((v): v is unknown[] => Array.isArray(v));\n if (arrays.length > 0) {\n composed[field] = arrays.flat();\n }\n }\n\n return mergeActionsIntoObjects(composed as ObjectStackDefinition);\n}\n\n\n/**\n * 2. RUNTIME CAPABILITIES PROTOCOL (Dynamic)\n * ----------------------------------------------------------------------\n * Describes what the ObjectOS Platform *is* and *can do*.\n * AI Agents read this to understand:\n * - What APIs are available?\n * - What features are enabled?\n * - What limits exist?\n * \n * The capabilities are organized by subsystem for clarity:\n * - ObjectQL: Data Layer capabilities\n * - ObjectUI: User Interface Layer capabilities \n * - ObjectOS: System Layer capabilities\n */\n\n/**\n * ObjectQL Capabilities Schema\n * \n * Defines capabilities related to the Data Layer:\n * - Query operations and advanced SQL features\n * - Data validation and business logic\n * - Database driver support\n * - AI/ML data features\n */\nexport const ObjectQLCapabilitiesSchema = z.object({\n /** Query Capabilities */\n queryFilters: z.boolean().default(true).describe('Supports WHERE clause filtering'),\n queryAggregations: z.boolean().default(true).describe('Supports GROUP BY and aggregation functions'),\n querySorting: z.boolean().default(true).describe('Supports ORDER BY sorting'),\n queryPagination: z.boolean().default(true).describe('Supports LIMIT/OFFSET pagination'),\n queryWindowFunctions: z.boolean().default(false).describe('Supports window functions with OVER clause'),\n querySubqueries: z.boolean().default(false).describe('Supports subqueries'),\n queryDistinct: z.boolean().default(true).describe('Supports SELECT DISTINCT'),\n queryHaving: z.boolean().default(false).describe('Supports HAVING clause for aggregations'),\n queryJoins: z.boolean().default(false).describe('Supports SQL-style joins'),\n \n /** Advanced Data Features */\n fullTextSearch: z.boolean().default(false).describe('Supports full-text search'),\n vectorSearch: z.boolean().default(false).describe('Supports vector embeddings and similarity search for AI/RAG'),\n geoSpatial: z.boolean().default(false).describe('Supports geospatial queries and location fields'),\n \n /** Field Type Support */\n jsonFields: z.boolean().default(true).describe('Supports JSON field types'),\n arrayFields: z.boolean().default(false).describe('Supports array field types'),\n \n /** Data Validation & Logic */\n validationRules: z.boolean().default(true).describe('Supports validation rules'),\n workflows: z.boolean().default(true).describe('Supports workflow automation'),\n triggers: z.boolean().default(true).describe('Supports database triggers'),\n formulas: z.boolean().default(true).describe('Supports formula fields'),\n \n /** Transaction & Performance */\n transactions: z.boolean().default(true).describe('Supports database transactions'),\n bulkOperations: z.boolean().default(true).describe('Supports bulk create/update/delete'),\n \n /** Driver Support */\n supportedDrivers: z.array(z.string()).optional().describe('Available database drivers (e.g., postgresql, mongodb, excel)'),\n});\n\n/**\n * ObjectUI Capabilities Schema\n * \n * Defines capabilities related to the UI Layer:\n * - View rendering (List, Form, Calendar, etc.)\n * - Dashboard and reporting\n * - Theming and customization\n * - UI actions and interactions\n */\nexport const ObjectUICapabilitiesSchema = z.object({\n /** View Types */\n listView: z.boolean().default(true).describe('Supports list/grid views'),\n formView: z.boolean().default(true).describe('Supports form views'),\n kanbanView: z.boolean().default(false).describe('Supports kanban board views'),\n calendarView: z.boolean().default(false).describe('Supports calendar views'),\n ganttView: z.boolean().default(false).describe('Supports Gantt chart views'),\n \n /** Analytics & Reporting */\n dashboards: z.boolean().default(true).describe('Supports dashboard creation'),\n reports: z.boolean().default(true).describe('Supports report generation'),\n charts: z.boolean().default(true).describe('Supports chart widgets'),\n \n /** Customization */\n customPages: z.boolean().default(true).describe('Supports custom page creation'),\n customThemes: z.boolean().default(false).describe('Supports custom theme creation'),\n customComponents: z.boolean().default(false).describe('Supports custom UI components/widgets'),\n \n /** Actions & Interactions */\n customActions: z.boolean().default(true).describe('Supports custom button actions'),\n screenFlows: z.boolean().default(false).describe('Supports interactive screen flows'),\n \n /** Responsive & Accessibility */\n mobileOptimized: z.boolean().default(false).describe('UI optimized for mobile devices'),\n accessibility: z.boolean().default(false).describe('WCAG accessibility support'),\n});\n\n/**\n * ObjectOS Capabilities Schema\n * \n * Defines capabilities related to the System Layer:\n * - Runtime environment and platform features\n * - API and integration capabilities\n * - Security and multi-tenancy\n * - System services (events, jobs, audit)\n */\nexport const ObjectOSCapabilitiesSchema = z.object({\n /** System Identity */\n version: z.string().describe('ObjectOS Kernel Version'),\n environment: z.enum(['development', 'test', 'staging', 'production']),\n \n /** API Surface */\n restApi: z.boolean().default(true).describe('REST API available'),\n graphqlApi: z.boolean().default(false).describe('GraphQL API available'),\n odataApi: z.boolean().default(false).describe('OData API available'),\n \n /** Real-time & Events */\n websockets: z.boolean().default(false).describe('WebSocket support for real-time updates'),\n serverSentEvents: z.boolean().default(false).describe('Server-Sent Events support'),\n eventBus: z.boolean().default(false).describe('Internal event bus for pub/sub'),\n \n /** Integration */\n webhooks: z.boolean().default(true).describe('Outbound webhook support'),\n apiContracts: z.boolean().default(false).describe('API contract definitions'),\n \n /** Security & Access Control */\n authentication: z.boolean().default(true).describe('Authentication system'),\n rbac: z.boolean().default(true).describe('Role-Based Access Control'),\n fieldLevelSecurity: z.boolean().default(false).describe('Field-level permissions'),\n rowLevelSecurity: z.boolean().default(false).describe('Row-level security/sharing rules'),\n \n /** Multi-tenancy */\n multiTenant: z.boolean().default(false).describe('Multi-tenant architecture support'),\n \n /** Platform Services */\n backgroundJobs: z.boolean().default(false).describe('Background job scheduling'),\n auditLogging: z.boolean().default(false).describe('Audit trail logging'),\n fileStorage: z.boolean().default(true).describe('File upload and storage'),\n \n /** Internationalization */\n i18n: z.boolean().default(true).describe('Internationalization support'),\n \n /** Plugin System */\n pluginSystem: z.boolean().default(false).describe('Plugin/extension system'),\n \n /** Active Features & Flags */\n features: z.array(FeatureFlagSchema).optional().describe('Active Feature Flags'),\n \n /** Available APIs */\n apis: z.array(ApiEndpointSchema).optional().describe('Available System & Business APIs'),\n network: z.object({\n graphql: z.boolean().default(false),\n search: z.boolean().default(false),\n websockets: z.boolean().default(false),\n files: z.boolean().default(true),\n analytics: z.boolean().default(false).describe('Is the Analytics/BI engine enabled?'),\n ai: z.boolean().default(false).describe('Is the AI engine enabled?'),\n workflow: z.boolean().default(false).describe('Is the Workflow engine enabled?'),\n notifications: z.boolean().default(false).describe('Is the Notification service enabled?'),\n i18n: z.boolean().default(false).describe('Is the i18n service enabled?'),\n }).optional().describe('Network Capabilities (GraphQL, WS, etc.)'),\n\n /** Introspection */\n systemObjects: z.array(z.string()).optional().describe('List of globally available System Objects'),\n \n /** Constraints (for AI Generation) */\n limits: z.object({\n maxObjects: z.number().optional(),\n maxFieldsPerObject: z.number().optional(),\n maxRecordsPerQuery: z.number().optional(),\n apiRateLimit: z.number().optional(),\n fileUploadSizeLimit: z.number().optional().describe('Max file size in bytes'),\n }).optional()\n});\n\n/**\n * Unified ObjectStack Capabilities Schema\n * \n * Complete capability descriptor for an ObjectStack instance.\n * Organized by architectural layer for clarity and maintainability.\n */\nexport const ObjectStackCapabilitiesSchema = z.object({\n /** Data Layer Capabilities (ObjectQL) */\n data: ObjectQLCapabilitiesSchema.describe('Data Layer capabilities'),\n \n /** User Interface Layer Capabilities (ObjectUI) */\n ui: ObjectUICapabilitiesSchema.describe('UI Layer capabilities'),\n \n /** System/Runtime Layer Capabilities (ObjectOS) */\n system: ObjectOSCapabilitiesSchema.describe('System/Runtime Layer capabilities'),\n});\n\nexport type ObjectQLCapabilities = z.infer;\nexport type ObjectUICapabilities = z.infer;\nexport type ObjectOSCapabilities = z.infer;\nexport type ObjectStackCapabilities = z.infer;\n\n\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Object Definitions Barrel\n * \n * Re-exports all *.object.ts definitions for auto-registration.\n * Hooks (*.hook.ts) and state machines (*.state.ts) are excluded \u2014\n * they are auto-associated by naming convention at runtime.\n */\nexport { Account } from './account.object';\nexport { Campaign } from './campaign.object';\nexport { Case } from './case.object';\nexport { Contact } from './contact.object';\nexport { Contract } from './contract.object';\nexport { Lead } from './lead.object';\nexport { Opportunity } from './opportunity.object';\nexport { Product } from './product.object';\nexport { Quote } from './quote.object';\nexport { Task } from './task.object';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Account = ObjectSchema.create({\n name: 'account',\n label: 'Account',\n pluralLabel: 'Accounts',\n icon: 'building',\n description: 'Companies and organizations doing business with us',\n titleFormat: '{account_number} - {name}',\n compactLayout: ['account_number', 'name', 'type', 'owner'],\n \n fields: {\n // AutoNumber field - Unique account identifier\n account_number: Field.autonumber({\n label: 'Account Number',\n format: 'ACC-{0000}',\n }),\n \n // Basic Information\n name: Field.text({ \n label: 'Account Name', \n required: true, \n searchable: true,\n maxLength: 255,\n }),\n \n // Select fields with custom options\n type: Field.select({\n label: 'Account Type',\n options: [\n { label: 'Prospect', value: 'prospect', color: '#FFA500', default: true },\n { label: 'Customer', value: 'customer', color: '#00AA00' },\n { label: 'Partner', value: 'partner', color: '#0000FF' },\n { label: 'Former Customer', value: 'former', color: '#999999' },\n ]\n }),\n \n industry: Field.select({\n label: 'Industry',\n options: [\n { label: 'Technology', value: 'technology' },\n { label: 'Finance', value: 'finance' },\n { label: 'Healthcare', value: 'healthcare' },\n { label: 'Retail', value: 'retail' },\n { label: 'Manufacturing', value: 'manufacturing' },\n { label: 'Education', value: 'education' },\n ]\n }),\n \n // Number fields\n annual_revenue: Field.currency({ \n label: 'Annual Revenue',\n scale: 2,\n min: 0,\n }),\n \n number_of_employees: Field.number({\n label: 'Employees',\n min: 0,\n }),\n \n // Contact Information\n phone: Field.text({ \n label: 'Phone',\n format: 'phone',\n }),\n \n website: Field.url({\n label: 'Website',\n }),\n \n // Structured Address field (new field type)\n billing_address: Field.address({\n label: 'Billing Address',\n addressFormat: 'international',\n }),\n \n // Office Location (new field type)\n office_location: Field.location({\n label: 'Office Location',\n displayMap: true,\n allowGeocoding: true,\n }),\n \n // Relationship fields\n owner: Field.lookup('user', {\n label: 'Account Owner',\n required: true,\n }),\n \n parent_account: Field.lookup('account', {\n label: 'Parent Account',\n description: 'Parent company in hierarchy',\n }),\n \n // Rich text field\n description: Field.markdown({\n label: 'Description',\n }),\n \n // Boolean field\n is_active: Field.boolean({\n label: 'Active',\n defaultValue: true,\n }),\n \n // Date field\n last_activity_date: Field.date({\n label: 'Last Activity Date',\n readonly: true,\n }),\n \n // Brand color (new field type)\n brand_color: Field.color({\n label: 'Brand Color',\n colorFormat: 'hex',\n presetColors: ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'],\n }),\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['name'] },\n { fields: ['owner'] },\n { fields: ['type', 'is_active'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true, // Track field changes\n searchable: true, // Include in global search\n apiEnabled: true, // Expose via REST/GraphQL\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search', 'export'], // Whitelist allowed API operations\n files: true, // Allow file attachments\n feeds: true, // Enable activity feed/chatter (Chatter-like)\n activities: true, // Enable tasks and events tracking\n trash: true, // Recycle bin support\n mru: true, // Track Most Recently Used\n },\n \n // Validation Rules\n validations: [\n {\n name: 'revenue_positive',\n type: 'script',\n severity: 'error',\n message: 'Annual Revenue must be positive',\n condition: 'annual_revenue < 0',\n },\n {\n name: 'account_name_unique',\n type: 'unique',\n severity: 'error',\n message: 'Account name must be unique',\n fields: ['name'],\n caseSensitive: false,\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'update_last_activity',\n objectName: 'account',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(owner) OR ISCHANGED(type)',\n actions: [\n {\n name: 'set_activity_date',\n type: 'field_update',\n field: 'last_activity_date',\n value: 'TODAY()',\n }\n ],\n active: true,\n }\n ],\n});", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * Campaign Object\n * Represents marketing campaigns\n */\nexport const Campaign = ObjectSchema.create({\n name: 'campaign',\n label: 'Campaign',\n pluralLabel: 'Campaigns',\n icon: 'megaphone',\n description: 'Marketing campaigns and initiatives',\n titleFormat: '{campaign_code} - {name}',\n compactLayout: ['campaign_code', 'name', 'type', 'status', 'start_date'],\n \n fields: {\n // AutoNumber field\n campaign_code: Field.autonumber({\n label: 'Campaign Code',\n format: 'CPG-{0000}',\n }),\n \n // Basic Information\n name: Field.text({ \n label: 'Campaign Name', \n required: true, \n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Type & Channel\n type: Field.select({\n label: 'Campaign Type',\n options: [\n { label: 'Email', value: 'email', default: true },\n { label: 'Webinar', value: 'webinar' },\n { label: 'Trade Show', value: 'trade_show' },\n { label: 'Conference', value: 'conference' },\n { label: 'Direct Mail', value: 'direct_mail' },\n { label: 'Social Media', value: 'social_media' },\n { label: 'Content Marketing', value: 'content' },\n { label: 'Partner Marketing', value: 'partner' },\n ]\n }),\n \n channel: Field.select({\n label: 'Primary Channel',\n options: [\n { label: 'Digital', value: 'digital' },\n { label: 'Social', value: 'social' },\n { label: 'Email', value: 'email' },\n { label: 'Events', value: 'events' },\n { label: 'Partner', value: 'partner' },\n ]\n }),\n \n // Status\n status: Field.select({\n label: 'Status',\n options: [\n { label: 'Planning', value: 'planning', color: '#999999', default: true },\n { label: 'In Progress', value: 'in_progress', color: '#FFA500' },\n { label: 'Completed', value: 'completed', color: '#00AA00' },\n { label: 'Aborted', value: 'aborted', color: '#FF0000' },\n ],\n required: true,\n }),\n \n // Dates\n start_date: Field.date({\n label: 'Start Date',\n required: true,\n }),\n \n end_date: Field.date({\n label: 'End Date',\n required: true,\n }),\n \n // Budget & ROI\n budgeted_cost: Field.currency({ \n label: 'Budgeted Cost',\n scale: 2,\n min: 0,\n }),\n \n actual_cost: Field.currency({ \n label: 'Actual Cost',\n scale: 2,\n min: 0,\n }),\n \n expected_revenue: Field.currency({ \n label: 'Expected Revenue',\n scale: 2,\n min: 0,\n }),\n \n actual_revenue: Field.currency({ \n label: 'Actual Revenue',\n scale: 2,\n min: 0,\n readonly: true,\n }),\n \n // Metrics\n target_size: Field.number({\n label: 'Target Size',\n description: 'Target number of leads/contacts',\n min: 0,\n }),\n \n num_sent: Field.number({\n label: 'Number Sent',\n min: 0,\n readonly: true,\n }),\n \n num_responses: Field.number({\n label: 'Number of Responses',\n min: 0,\n readonly: true,\n }),\n \n num_leads: Field.number({\n label: 'Number of Leads',\n min: 0,\n readonly: true,\n }),\n \n num_converted_leads: Field.number({\n label: 'Converted Leads',\n min: 0,\n readonly: true,\n }),\n \n num_opportunities: Field.number({\n label: 'Opportunities Created',\n min: 0,\n readonly: true,\n }),\n \n num_won_opportunities: Field.number({\n label: 'Won Opportunities',\n min: 0,\n readonly: true,\n }),\n \n // Calculated Metrics (Formula Fields)\n response_rate: Field.formula({\n label: 'Response Rate %',\n expression: 'IF(num_sent > 0, (num_responses / num_sent) * 100, 0)',\n scale: 2,\n }),\n \n roi: Field.formula({\n label: 'ROI %',\n expression: 'IF(actual_cost > 0, ((actual_revenue - actual_cost) / actual_cost) * 100, 0)',\n scale: 2,\n }),\n \n // Relationships\n parent_campaign: Field.lookup('campaign', {\n label: 'Parent Campaign',\n description: 'Parent campaign in hierarchy',\n }),\n \n owner: Field.lookup('user', {\n label: 'Campaign Owner',\n required: true,\n }),\n \n // Campaign Assets\n landing_page_url: Field.url({\n label: 'Landing Page',\n }),\n \n is_active: Field.boolean({\n label: 'Active',\n defaultValue: true,\n }),\n },\n \n // Database indexes\n indexes: [\n { fields: ['name'] },\n { fields: ['type'] },\n { fields: ['status'] },\n { fields: ['start_date'] },\n { fields: ['owner'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search', 'export'],\n files: true,\n feeds: true,\n activities: true,\n trash: true,\n mru: true,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'end_after_start',\n type: 'script',\n severity: 'error',\n message: 'End Date must be after Start Date',\n condition: 'end_date < start_date',\n },\n {\n name: 'actual_cost_within_budget',\n type: 'script',\n severity: 'warning',\n message: 'Actual Cost exceeds Budgeted Cost',\n condition: 'actual_cost > budgeted_cost',\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'campaign_completion_check',\n objectName: 'campaign',\n triggerType: 'on_read',\n criteria: 'end_date < TODAY() AND status = \"in_progress\"',\n actions: [\n {\n name: 'mark_completed',\n type: 'field_update',\n field: 'status',\n value: '\"completed\"',\n }\n ],\n active: true,\n }\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Case = ObjectSchema.create({\n name: 'case',\n label: 'Case',\n pluralLabel: 'Cases',\n icon: 'life-buoy',\n description: 'Customer support cases and service requests',\n \n fields: {\n // Case Information\n case_number: Field.autonumber({\n label: 'Case Number',\n format: 'CASE-{00000}',\n }),\n \n subject: Field.text({\n label: 'Subject',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n required: true,\n }),\n \n // Relationships\n account: Field.lookup('account', {\n label: 'Account',\n }),\n \n contact: Field.lookup('contact', {\n label: 'Contact',\n required: true,\n referenceFilters: ['account = {case.account}'],\n }),\n \n // Case Management\n status: Field.select({\n label: 'Status',\n required: true,\n options: [\n { label: 'New', value: 'new', color: '#808080', default: true },\n { label: 'In Progress', value: 'in_progress', color: '#FFA500' },\n { label: 'Waiting on Customer', value: 'waiting_customer', color: '#FFD700' },\n { label: 'Waiting on Support', value: 'waiting_support', color: '#4169E1' },\n { label: 'Escalated', value: 'escalated', color: '#FF0000' },\n { label: 'Resolved', value: 'resolved', color: '#00AA00' },\n { label: 'Closed', value: 'closed', color: '#006400' },\n ]\n }),\n \n priority: Field.select({\n label: 'Priority',\n required: true,\n options: [\n { label: 'Low', value: 'low', color: '#4169E1', default: true },\n { label: 'Medium', value: 'medium', color: '#FFA500' },\n { label: 'High', value: 'high', color: '#FF4500' },\n { label: 'Critical', value: 'critical', color: '#FF0000' },\n ]\n }),\n \n type: Field.select({\n label: 'Case Type',\n options: [\n { label: 'Question', value: 'question' },\n { label: 'Problem', value: 'problem' },\n { label: 'Feature Request', value: 'feature_request' },\n { label: 'Bug', value: 'bug' },\n ]\n }),\n \n origin: Field.select({\n label: 'Case Origin',\n options: [\n { label: 'Email', value: 'email' },\n { label: 'Phone', value: 'phone' },\n { label: 'Web', value: 'web' },\n { label: 'Chat', value: 'chat' },\n { label: 'Social Media', value: 'social_media' },\n ]\n }),\n \n // Assignment\n owner: Field.lookup('user', {\n label: 'Case Owner',\n required: true,\n }),\n \n // SLA and Metrics\n created_date: Field.datetime({\n label: 'Created Date',\n readonly: true,\n }),\n \n closed_date: Field.datetime({\n label: 'Closed Date',\n readonly: true,\n }),\n \n first_response_date: Field.datetime({\n label: 'First Response Date',\n readonly: true,\n }),\n \n resolution_time_hours: Field.number({\n label: 'Resolution Time (Hours)',\n readonly: true,\n scale: 2,\n }),\n \n sla_due_date: Field.datetime({\n label: 'SLA Due Date',\n }),\n \n is_sla_violated: Field.boolean({\n label: 'SLA Violated',\n defaultValue: false,\n readonly: true,\n }),\n \n // Escalation\n is_escalated: Field.boolean({\n label: 'Escalated',\n defaultValue: false,\n }),\n \n escalation_reason: Field.textarea({\n label: 'Escalation Reason',\n }),\n \n // Related case\n parent_case: Field.lookup('case', {\n label: 'Parent Case',\n description: 'Related parent case',\n }),\n \n // Resolution\n resolution: Field.markdown({\n label: 'Resolution',\n }),\n \n // Customer satisfaction\n customer_rating: Field.rating(5, {\n label: 'Customer Satisfaction',\n description: 'Customer satisfaction rating (1-5 stars)',\n }),\n \n customer_feedback: Field.textarea({\n label: 'Customer Feedback',\n }),\n \n // Customer signature (for case resolution acknowledgment)\n customer_signature: Field.signature({\n label: 'Customer Signature',\n description: 'Digital signature acknowledging case resolution',\n }),\n \n // Internal notes\n internal_notes: Field.markdown({\n label: 'Internal Notes',\n description: 'Internal notes not visible to customer',\n }),\n \n // Flags\n is_closed: Field.boolean({\n label: 'Is Closed',\n defaultValue: false,\n readonly: true,\n }),\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['case_number'], unique: true },\n { fields: ['account'] },\n { fields: ['owner'] },\n { fields: ['status'] },\n { fields: ['priority'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true, // Enable social feed, comments, and mentions\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n titleFormat: '{case_number} - {subject}',\n compactLayout: ['case_number', 'subject', 'account', 'status', 'priority'],\n \n // Removed: list_views and form_views belong in UI configuration, not object definition\n \n validations: [\n {\n name: 'resolution_required_for_closed',\n type: 'script',\n severity: 'error',\n message: 'Resolution is required when closing a case',\n condition: 'status = \"closed\" AND ISBLANK(resolution)',\n },\n {\n name: 'escalation_reason_required',\n type: 'script',\n severity: 'error',\n message: 'Escalation reason is required when escalating a case',\n condition: 'is_escalated = true AND ISBLANK(escalation_reason)',\n },\n {\n name: 'case_status_progression',\n type: 'state_machine',\n severity: 'warning',\n message: 'Invalid status transition',\n field: 'status',\n transitions: {\n 'new': ['in_progress', 'waiting_customer', 'closed'],\n 'in_progress': ['waiting_customer', 'waiting_support', 'escalated', 'resolved'],\n 'waiting_customer': ['in_progress', 'closed'],\n 'waiting_support': ['in_progress', 'escalated'],\n 'escalated': ['in_progress', 'resolved'],\n 'resolved': ['closed', 'in_progress'], // Can reopen\n 'closed': ['in_progress'], // Can reopen\n }\n },\n ],\n \n workflows: [\n {\n name: 'set_closed_flag',\n objectName: 'case',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(status)',\n active: true,\n actions: [\n {\n name: 'update_closed_flag',\n type: 'field_update',\n field: 'is_closed',\n value: 'status = \"closed\"',\n }\n ],\n },\n {\n name: 'set_closed_date',\n objectName: 'case',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(status) AND status = \"closed\"',\n active: true,\n actions: [\n {\n name: 'set_date',\n type: 'field_update',\n field: 'closed_date',\n value: 'NOW()',\n }\n ],\n },\n {\n name: 'calculate_resolution_time',\n objectName: 'case',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(closed_date) AND NOT(ISBLANK(closed_date))',\n active: true,\n actions: [\n {\n name: 'calc_time',\n type: 'field_update',\n field: 'resolution_time_hours',\n value: 'HOURS(created_date, closed_date)',\n }\n ],\n },\n {\n name: 'notify_on_critical',\n objectName: 'case',\n triggerType: 'on_create_or_update',\n criteria: 'priority = \"critical\"',\n active: true,\n actions: [\n {\n name: 'email_support_manager',\n type: 'email_alert',\n template: 'critical_case_alert',\n recipients: ['support_manager@example.com'],\n }\n ],\n },\n {\n name: 'notify_on_escalation',\n objectName: 'case',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(is_escalated) AND is_escalated = true',\n active: true,\n actions: [\n {\n name: 'email_escalation_team',\n type: 'email_alert',\n template: 'case_escalation_alert',\n recipients: ['escalation_team@example.com'],\n }\n ],\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Contact = ObjectSchema.create({\n name: 'contact',\n label: 'Contact',\n pluralLabel: 'Contacts',\n icon: 'user',\n description: 'People associated with accounts',\n \n fields: {\n // Name fields\n salutation: Field.select({\n label: 'Salutation',\n options: [\n { label: 'Mr.', value: 'mr' },\n { label: 'Ms.', value: 'ms' },\n { label: 'Mrs.', value: 'mrs' },\n { label: 'Dr.', value: 'dr' },\n { label: 'Prof.', value: 'prof' },\n ]\n }),\n first_name: Field.text({ \n label: 'First Name',\n required: true,\n searchable: true,\n }),\n last_name: Field.text({ \n label: 'Last Name',\n required: true,\n searchable: true,\n }),\n \n // Formula field - Full name\n full_name: Field.formula({\n label: 'Full Name',\n expression: 'CONCAT(salutation, \" \", first_name, \" \", last_name)',\n }),\n \n // Relationship: Link to Account (Master-Detail)\n account: Field.masterDetail('account', {\n label: 'Account',\n required: true,\n writeRequiresMasterRead: true,\n deleteBehavior: 'cascade', // Delete contacts when account is deleted\n }),\n \n // Contact Information\n email: Field.email({ \n label: 'Email',\n required: true,\n unique: true,\n }),\n \n phone: Field.text({ \n label: 'Phone',\n format: 'phone',\n }),\n \n mobile: Field.text({\n label: 'Mobile',\n format: 'phone',\n }),\n \n // Professional Information\n title: Field.text({\n label: 'Job Title',\n }),\n \n department: Field.select({\n label: 'Department',\n options: [\n { label: 'Executive', value: 'executive' },\n { label: 'Sales', value: 'sales' },\n { label: 'Marketing', value: 'marketing' },\n { label: 'Engineering', value: 'engineering' },\n { label: 'Support', value: 'support' },\n { label: 'Finance', value: 'finance' },\n { label: 'HR', value: 'hr' },\n { label: 'Operations', value: 'operations' },\n ]\n }),\n \n // Relationship fields\n reports_to: Field.lookup('contact', {\n label: 'Reports To',\n description: 'Direct manager/supervisor',\n }),\n \n owner: Field.lookup('user', {\n label: 'Contact Owner',\n required: true,\n }),\n \n // Mailing Address\n mailing_street: Field.textarea({ label: 'Mailing Street' }),\n mailing_city: Field.text({ label: 'Mailing City' }),\n mailing_state: Field.text({ label: 'Mailing State/Province' }),\n mailing_postal_code: Field.text({ label: 'Mailing Postal Code' }),\n mailing_country: Field.text({ label: 'Mailing Country' }),\n \n // Additional Information\n birthdate: Field.date({\n label: 'Birthdate',\n }),\n \n lead_source: Field.select({\n label: 'Lead Source',\n options: [\n { label: 'Web', value: 'web' },\n { label: 'Referral', value: 'referral' },\n { label: 'Event', value: 'event' },\n { label: 'Partner', value: 'partner' },\n { label: 'Advertisement', value: 'advertisement' },\n ]\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Flags\n is_primary: Field.boolean({\n label: 'Primary Contact',\n defaultValue: false,\n description: 'Is this the main contact for the account?',\n }),\n \n do_not_call: Field.boolean({\n label: 'Do Not Call',\n defaultValue: false,\n }),\n \n email_opt_out: Field.boolean({\n label: 'Email Opt Out',\n defaultValue: false,\n }),\n \n // Avatar field\n avatar: Field.avatar({\n label: 'Profile Picture',\n }),\n },\n \n // Enable features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true, // Enable social feed, comments, and mentions\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['account'] },\n { fields: ['email'], unique: true },\n { fields: ['owner'] },\n { fields: ['last_name', 'first_name'] },\n ],\n \n // Display configuration\n titleFormat: '{full_name}',\n compactLayout: ['full_name', 'email', 'account', 'phone'],\n \n // Validation Rules\n validations: [\n {\n name: 'email_required_for_opt_in',\n type: 'script',\n severity: 'error',\n message: 'Email is required when Email Opt Out is not checked',\n condition: 'email_opt_out = false AND ISBLANK(email)',\n },\n {\n name: 'email_unique_per_account',\n type: 'unique',\n severity: 'error',\n message: 'Email must be unique within an account',\n fields: ['email', 'account'],\n caseSensitive: false,\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'welcome_email',\n objectName: 'contact',\n triggerType: 'on_create',\n active: true,\n actions: [\n {\n name: 'send_welcome',\n type: 'email_alert',\n template: 'contact_welcome',\n recipients: ['{contact.email}'],\n }\n ],\n }\n ],\n});", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * Contract Object\n * Represents legal contracts with customers\n */\nexport const Contract = ObjectSchema.create({\n name: 'contract',\n label: 'Contract',\n pluralLabel: 'Contracts',\n icon: 'file-signature',\n description: 'Legal contracts and agreements',\n titleFormat: '{contract_number} - {account.name}',\n compactLayout: ['contract_number', 'account', 'status', 'start_date', 'end_date'],\n \n fields: {\n // AutoNumber field\n contract_number: Field.autonumber({\n label: 'Contract Number',\n format: 'CTR-{0000}',\n }),\n \n // Relationships\n account: Field.lookup('account', {\n label: 'Account',\n required: true,\n }),\n \n contact: Field.lookup('contact', {\n label: 'Primary Contact',\n required: true,\n referenceFilters: [\n 'account = {account}',\n ]\n }),\n \n opportunity: Field.lookup('opportunity', {\n label: 'Related Opportunity',\n referenceFilters: [\n 'account = {account}',\n ]\n }),\n \n owner: Field.lookup('user', {\n label: 'Contract Owner',\n required: true,\n }),\n \n // Status\n status: Field.select({\n label: 'Status',\n options: [\n { label: 'Draft', value: 'draft', color: '#999999', default: true },\n { label: 'In Approval', value: 'in_approval', color: '#FFA500' },\n { label: 'Activated', value: 'activated', color: '#00AA00' },\n { label: 'Expired', value: 'expired', color: '#FF0000' },\n { label: 'Terminated', value: 'terminated', color: '#666666' },\n ],\n required: true,\n }),\n \n // Contract Terms\n contract_term_months: Field.number({\n label: 'Contract Term (Months)',\n required: true,\n min: 1,\n }),\n \n start_date: Field.date({\n label: 'Start Date',\n required: true,\n }),\n \n end_date: Field.date({\n label: 'End Date',\n required: true,\n }),\n \n // Financial\n contract_value: Field.currency({ \n label: 'Contract Value',\n scale: 2,\n min: 0,\n required: true,\n }),\n \n billing_frequency: Field.select({\n label: 'Billing Frequency',\n options: [\n { label: 'Monthly', value: 'monthly', default: true },\n { label: 'Quarterly', value: 'quarterly' },\n { label: 'Annually', value: 'annually' },\n { label: 'One-time', value: 'one_time' },\n ]\n }),\n \n payment_terms: Field.select({\n label: 'Payment Terms',\n options: [\n { label: 'Net 15', value: 'net_15' },\n { label: 'Net 30', value: 'net_30', default: true },\n { label: 'Net 60', value: 'net_60' },\n { label: 'Net 90', value: 'net_90' },\n ]\n }),\n \n // Renewal\n auto_renewal: Field.boolean({\n label: 'Auto Renewal',\n defaultValue: false,\n }),\n \n renewal_notice_days: Field.number({\n label: 'Renewal Notice (Days)',\n min: 0,\n defaultValue: 30,\n }),\n \n // Legal\n contract_type: Field.select({\n label: 'Contract Type',\n options: [\n { label: 'Subscription', value: 'subscription' },\n { label: 'Service Agreement', value: 'service' },\n { label: 'License', value: 'license' },\n { label: 'Partnership', value: 'partnership' },\n { label: 'NDA', value: 'nda' },\n { label: 'MSA', value: 'msa' },\n ]\n }),\n \n signed_date: Field.date({\n label: 'Signed Date',\n }),\n \n signed_by: Field.text({\n label: 'Signed By',\n maxLength: 255,\n }),\n \n document_url: Field.url({\n label: 'Contract Document',\n }),\n \n // Terms & Conditions\n special_terms: Field.markdown({\n label: 'Special Terms',\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Billing Address\n billing_address: Field.address({\n label: 'Billing Address',\n addressFormat: 'international',\n }),\n },\n \n // Database indexes\n indexes: [\n { fields: ['account'] },\n { fields: ['status'] },\n { fields: ['start_date'] },\n { fields: ['end_date'] },\n { fields: ['owner'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search', 'export'],\n files: true,\n feeds: true,\n activities: true,\n trash: true,\n mru: true,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'end_after_start',\n type: 'script',\n severity: 'error',\n message: 'End Date must be after Start Date',\n condition: 'end_date <= start_date',\n },\n {\n name: 'valid_contract_term',\n type: 'script',\n severity: 'error',\n message: 'Contract Term must match date range',\n condition: 'MONTH_DIFF(end_date, start_date) != contract_term_months',\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'contract_expiration_check',\n objectName: 'contract',\n triggerType: 'scheduled',\n schedule: '0 0 * * *', // Daily at midnight\n criteria: 'end_date <= TODAY() AND status = \"activated\"',\n actions: [\n {\n name: 'mark_expired',\n type: 'field_update',\n field: 'status',\n value: '\"expired\"',\n },\n {\n name: 'notify_owner',\n type: 'email_alert',\n template: 'contract_expired',\n recipients: ['{owner}'],\n }\n ],\n active: true,\n },\n {\n name: 'renewal_reminder',\n objectName: 'contract',\n triggerType: 'scheduled',\n schedule: '0 0 * * *', // Daily at midnight\n criteria: 'DAYS_UNTIL(end_date) <= renewal_notice_days AND status = \"activated\"',\n actions: [\n {\n name: 'notify_renewal',\n type: 'email_alert',\n template: 'contract_renewal_reminder',\n recipients: ['{owner}', '{account.owner}'],\n }\n ],\n active: true,\n }\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\nimport { LeadStateMachine } from './lead.state';\n\nexport const Lead = ObjectSchema.create({\n name: 'lead',\n label: 'Lead',\n pluralLabel: 'Leads',\n icon: 'user-plus',\n description: 'Potential customers not yet qualified',\n \n fields: {\n // Personal Information\n salutation: Field.select({\n label: 'Salutation',\n options: [\n { label: 'Mr.', value: 'mr' },\n { label: 'Ms.', value: 'ms' },\n { label: 'Mrs.', value: 'mrs' },\n { label: 'Dr.', value: 'dr' },\n ]\n }),\n \n first_name: Field.text({\n label: 'First Name',\n required: true,\n searchable: true,\n }),\n \n last_name: Field.text({\n label: 'Last Name',\n required: true,\n searchable: true,\n }),\n \n full_name: Field.formula({\n label: 'Full Name',\n expression: 'CONCAT(salutation, \" \", first_name, \" \", last_name)',\n }),\n \n // Company Information\n company: Field.text({\n label: 'Company',\n required: true,\n searchable: true,\n }),\n \n title: Field.text({\n label: 'Job Title',\n }),\n \n industry: Field.select({\n label: 'Industry',\n options: [\n { label: 'Technology', value: 'technology' },\n { label: 'Finance', value: 'finance' },\n { label: 'Healthcare', value: 'healthcare' },\n { label: 'Retail', value: 'retail' },\n { label: 'Manufacturing', value: 'manufacturing' },\n { label: 'Education', value: 'education' },\n ]\n }),\n \n // Contact Information\n email: Field.email({\n label: 'Email',\n required: true,\n unique: true,\n }),\n \n phone: Field.text({\n label: 'Phone',\n format: 'phone',\n }),\n \n mobile: Field.text({\n label: 'Mobile',\n format: 'phone',\n }),\n \n website: Field.url({\n label: 'Website',\n }),\n \n // Lead Qualification\n status: Field.select({\n label: 'Lead Status',\n required: true,\n options: [\n { label: 'New', value: 'new', color: '#808080', default: true },\n { label: 'Contacted', value: 'contacted', color: '#FFA500' },\n { label: 'Qualified', value: 'qualified', color: '#4169E1' },\n { label: 'Unqualified', value: 'unqualified', color: '#FF0000' },\n { label: 'Converted', value: 'converted', color: '#00AA00' },\n ]\n }),\n \n rating: Field.rating(5, {\n label: 'Lead Score',\n description: 'Lead quality score (1-5 stars)',\n allowHalf: true,\n }),\n \n lead_source: Field.select({\n label: 'Lead Source',\n options: [\n { label: 'Web', value: 'web' },\n { label: 'Referral', value: 'referral' },\n { label: 'Event', value: 'event' },\n { label: 'Partner', value: 'partner' },\n { label: 'Advertisement', value: 'advertisement' },\n { label: 'Cold Call', value: 'cold_call' },\n ]\n }),\n \n // Assignment\n owner: Field.lookup('user', {\n label: 'Lead Owner',\n required: true,\n }),\n \n // Conversion tracking\n is_converted: Field.boolean({\n label: 'Converted',\n defaultValue: false,\n readonly: true,\n }),\n \n converted_account: Field.lookup('account', {\n label: 'Converted Account',\n readonly: true,\n }),\n \n converted_contact: Field.lookup('contact', {\n label: 'Converted Contact',\n readonly: true,\n }),\n \n converted_opportunity: Field.lookup('opportunity', {\n label: 'Converted Opportunity',\n readonly: true,\n }),\n \n converted_date: Field.datetime({\n label: 'Converted Date',\n readonly: true,\n }),\n \n // Address (using new address field type)\n address: Field.address({\n label: 'Address',\n addressFormat: 'international',\n }),\n \n // Additional Info\n annual_revenue: Field.currency({\n label: 'Annual Revenue',\n scale: 2,\n }),\n \n number_of_employees: Field.number({\n label: 'Number of Employees',\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Custom notes with rich text formatting\n notes: Field.richtext({\n label: 'Notes',\n description: 'Rich text notes with formatting',\n }),\n \n // Flags\n do_not_call: Field.boolean({\n label: 'Do Not Call',\n defaultValue: false,\n }),\n \n email_opt_out: Field.boolean({\n label: 'Email Opt Out',\n defaultValue: false,\n }),\n },\n\n // Lifecycle State Machine(s)\n // Enforces valid status transitions to prevent AI hallucinations\n // Using `stateMachines` (plural) for future extensibility.\n // For simple objects with one lifecycle, `stateMachine` (singular) is also supported.\n stateMachines: {\n lifecycle: LeadStateMachine,\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['email'], unique: true },\n { fields: ['owner'] },\n { fields: ['status'] },\n { fields: ['company'] },\n ],\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true, // Enable social feed, comments, and mentions\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n titleFormat: '{full_name} - {company}',\n compactLayout: ['full_name', 'company', 'email', 'status', 'owner'],\n \n // Removed: list_views and form_views belong in UI configuration, not object definition\n \n validations: [\n {\n name: 'email_required',\n type: 'script',\n severity: 'error',\n message: 'Email is required',\n condition: 'ISBLANK(email)',\n },\n {\n name: 'cannot_edit_converted',\n type: 'script',\n severity: 'error',\n message: 'Cannot edit a converted lead',\n condition: 'is_converted = true AND ISCHANGED(company, email, first_name, last_name)',\n },\n ],\n \n workflows: [\n {\n name: 'auto_qualify_high_score_leads',\n objectName: 'lead',\n triggerType: 'on_create_or_update',\n criteria: 'rating >= 4 AND status = \"new\"',\n active: true,\n actions: [\n {\n name: 'set_status',\n type: 'field_update',\n field: 'status',\n value: 'contacted',\n }\n ],\n },\n {\n name: 'notify_owner_on_high_score_lead',\n objectName: 'lead',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(rating) AND rating >= 4.5',\n active: true,\n actions: [\n {\n name: 'email_owner',\n type: 'email_alert',\n template: 'high_score_lead_notification',\n recipients: ['{owner.email}'],\n }\n ],\n }\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { StateMachineConfig } from '@objectstack/spec/automation';\n\n/**\n * Lead Lifecycle State Machine\n * \n * Defines the strict status transitions for Leads to prevent invalid operations\n * and guide AI agents.\n */\nexport const LeadStateMachine: StateMachineConfig = {\n id: 'lead_process',\n initial: 'new',\n states: {\n new: {\n on: {\n CONTACT: { target: 'contacted', description: 'Log initial contact' },\n DISQUALIFY: { target: 'unqualified', description: 'Mark as unqualified early' }\n },\n meta: {\n aiInstructions: 'New lead. Verify email and phone before contacting. Do not change status until contact is made.'\n }\n },\n contacted: {\n on: {\n QUALIFY: { target: 'qualified', cond: 'has_budget_and_authority' },\n DISQUALIFY: { target: 'unqualified' }\n },\n meta: {\n aiInstructions: 'Engage with the lead. Qualify by asking about budget, authority, need, and timeline (BANT).'\n }\n },\n qualified: {\n on: {\n CONVERT: { target: 'converted', cond: 'is_ready_to_buy' },\n DISQUALIFY: { target: 'unqualified' }\n },\n meta: {\n aiInstructions: 'Lead is qualified. Prepare for conversion to Deal/Opportunity. Check for existing accounts.'\n }\n },\n unqualified: {\n on: {\n REOPEN: { target: 'new', description: 'Re-evaluate lead' }\n },\n meta: {\n aiInstructions: 'Lead is dead. Do not contact unless new information surfaces.'\n }\n },\n converted: {\n type: 'final',\n meta: {\n aiInstructions: 'Lead is converted. No further actions allowed on this record.'\n }\n }\n }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\nimport { OpportunityStateMachine } from './opportunity.state';\n\nexport const Opportunity = ObjectSchema.create({\n name: 'opportunity',\n label: 'Opportunity',\n pluralLabel: 'Opportunities',\n icon: 'dollar-sign',\n description: 'Sales opportunities and deals in the pipeline',\n titleFormat: '{name} - {stage}',\n compactLayout: ['name', 'account', 'amount', 'stage', 'owner'],\n \n fields: {\n // Basic Information\n name: Field.text({ \n label: 'Opportunity Name',\n required: true,\n searchable: true,\n }),\n \n // Relationships\n account: Field.lookup('account', { \n label: 'Account',\n required: true,\n }),\n \n primary_contact: Field.lookup('contact', {\n label: 'Primary Contact',\n referenceFilters: ['account = {opportunity.account}'], // Filter contacts by account\n }),\n \n owner: Field.lookup('user', {\n label: 'Opportunity Owner',\n required: true,\n }),\n \n // Financial Information\n amount: Field.currency({\n label: 'Amount',\n required: true,\n scale: 2,\n min: 0,\n }),\n \n expected_revenue: Field.currency({\n label: 'Expected Revenue',\n scale: 2,\n readonly: true, // Calculated field\n }),\n \n // Sales Process\n stage: Field.select({\n label: 'Stage',\n required: true,\n options: [\n { label: 'Prospecting', value: 'prospecting', color: '#808080', default: true },\n { label: 'Qualification', value: 'qualification', color: '#FFA500' },\n { label: 'Needs Analysis', value: 'needs_analysis', color: '#FFD700' },\n { label: 'Proposal', value: 'proposal', color: '#4169E1' },\n { label: 'Negotiation', value: 'negotiation', color: '#9370DB' },\n { label: 'Closed Won', value: 'closed_won', color: '#00AA00' },\n { label: 'Closed Lost', value: 'closed_lost', color: '#FF0000' },\n ]\n }),\n \n probability: Field.percent({\n label: 'Probability (%)',\n min: 0,\n max: 100,\n defaultValue: 10,\n }),\n \n // Important Dates\n close_date: Field.date({\n label: 'Close Date',\n required: true,\n }),\n \n created_date: Field.datetime({\n label: 'Created Date',\n readonly: true,\n }),\n \n // Additional Classification\n type: Field.select({\n label: 'Opportunity Type',\n options: [\n { label: 'New Business', value: 'new_business' },\n { label: 'Existing Customer - Upgrade', value: 'existing_upgrade' },\n { label: 'Existing Customer - Renewal', value: 'existing_renewal' },\n { label: 'Existing Customer - Expansion', value: 'existing_expansion' },\n ]\n }),\n \n lead_source: Field.select({\n label: 'Lead Source',\n options: [\n { label: 'Web', value: 'web' },\n { label: 'Referral', value: 'referral' },\n { label: 'Event', value: 'event' },\n { label: 'Partner', value: 'partner' },\n { label: 'Advertisement', value: 'advertisement' },\n { label: 'Cold Call', value: 'cold_call' },\n ]\n }),\n \n // Competitor Analysis\n competitors: Field.select({\n label: 'Competitors',\n multiple: true,\n options: [\n { label: 'Competitor A', value: 'competitor_a' },\n { label: 'Competitor B', value: 'competitor_b' },\n { label: 'Competitor C', value: 'competitor_c' },\n ]\n }),\n \n // Campaign tracking\n campaign: Field.lookup('campaign', {\n label: 'Campaign',\n description: 'Marketing campaign that generated this opportunity',\n }),\n \n // Sales cycle metrics\n days_in_stage: Field.number({\n label: 'Days in Current Stage',\n readonly: true,\n }),\n \n // Additional information\n description: Field.markdown({\n label: 'Description',\n }),\n \n next_step: Field.textarea({\n label: 'Next Steps',\n }),\n \n // Flags\n is_private: Field.boolean({\n label: 'Private',\n defaultValue: false,\n }),\n \n forecast_category: Field.select({\n label: 'Forecast Category',\n options: [\n { label: 'Pipeline', value: 'pipeline' },\n { label: 'Best Case', value: 'best_case' },\n { label: 'Commit', value: 'commit' },\n { label: 'Omitted', value: 'omitted' },\n { label: 'Closed', value: 'closed' },\n ]\n }),\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['name'] },\n { fields: ['account'] },\n { fields: ['owner'] },\n { fields: ['stage'] },\n { fields: ['close_date'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true, // Critical for tracking stage changes\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'aggregate', 'search'], // Whitelist allowed API operations\n files: true, // Attach proposals, contracts\n feeds: true, // Team collaboration (Chatter-like)\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n // Removed: list_views and form_views belong in UI configuration, not object definition\n \n // Lifecycle State Machine(s)\n stateMachines: {\n lifecycle: OpportunityStateMachine,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'close_date_future',\n type: 'script',\n severity: 'warning',\n message: 'Close date should not be in the past unless opportunity is closed',\n condition: 'close_date < TODAY() AND stage != \"closed_won\" AND stage != \"closed_lost\"',\n },\n {\n name: 'amount_positive',\n type: 'script',\n severity: 'error',\n message: 'Amount must be greater than zero',\n condition: 'amount <= 0',\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'update_probability_by_stage',\n objectName: 'opportunity',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(stage)',\n active: true,\n actions: [\n {\n name: 'set_probability',\n type: 'field_update',\n field: 'probability',\n value: `CASE(stage,\n \"prospecting\", 10,\n \"qualification\", 25,\n \"needs_analysis\", 40,\n \"proposal\", 60,\n \"negotiation\", 80,\n \"closed_won\", 100,\n \"closed_lost\", 0,\n probability\n )`,\n },\n {\n name: 'set_forecast_category',\n type: 'field_update',\n field: 'forecast_category',\n value: `CASE(stage,\n \"prospecting\", \"pipeline\",\n \"qualification\", \"pipeline\",\n \"needs_analysis\", \"best_case\",\n \"proposal\", \"commit\",\n \"negotiation\", \"commit\",\n \"closed_won\", \"closed\",\n \"closed_lost\", \"omitted\",\n forecast_category\n )`,\n }\n ],\n },\n {\n name: 'calculate_expected_revenue',\n objectName: 'opportunity',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(amount) OR ISCHANGED(probability)',\n active: true,\n actions: [\n {\n name: 'update_expected_revenue',\n type: 'field_update',\n field: 'expected_revenue',\n value: 'amount * (probability / 100)',\n }\n ],\n },\n {\n name: 'notify_on_large_deal_won',\n objectName: 'opportunity',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(stage) AND stage = \"closed_won\" AND amount > 100000',\n active: true,\n actions: [\n {\n name: 'notify_management',\n type: 'email_alert',\n template: 'large_deal_won',\n recipients: ['sales_management@example.com'],\n }\n ],\n }\n ],\n});", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { StateMachineConfig } from '@objectstack/spec/automation';\n\n/**\n * Opportunity Sales Pipeline State Machine\n * \n * Defines the strict stage transitions for Opportunities to enforce\n * a valid sales process and guide AI agents.\n */\nexport const OpportunityStateMachine: StateMachineConfig = {\n id: 'opportunity_pipeline',\n initial: 'prospecting',\n states: {\n prospecting: {\n on: {\n QUALIFY: { target: 'qualification', description: 'Initial qualification passed' },\n LOSE: { target: 'closed_lost', description: 'Lost at prospecting stage' },\n },\n meta: {\n aiInstructions: 'New opportunity. Identify decision makers and confirm budget exists before advancing.',\n },\n },\n qualification: {\n on: {\n ANALYZE: { target: 'needs_analysis', description: 'Begin needs analysis' },\n LOSE: { target: 'closed_lost', description: 'Lost at qualification stage' },\n },\n meta: {\n aiInstructions: 'Qualifying opportunity. Gather BANT (Budget, Authority, Need, Timeline) details.',\n },\n },\n needs_analysis: {\n on: {\n PROPOSE: { target: 'proposal', description: 'Submit proposal' },\n LOSE: { target: 'closed_lost', description: 'Lost during needs analysis' },\n },\n meta: {\n aiInstructions: 'Analyzing customer needs. Document requirements and pain points before proposing.',\n },\n },\n proposal: {\n on: {\n NEGOTIATE: { target: 'negotiation', description: 'Enter negotiation' },\n LOSE: { target: 'closed_lost', description: 'Proposal rejected' },\n },\n meta: {\n aiInstructions: 'Proposal submitted. Follow up on pricing and terms. Prepare for negotiation.',\n },\n },\n negotiation: {\n on: {\n WIN: { target: 'closed_won', description: 'Deal won' },\n LOSE: { target: 'closed_lost', description: 'Lost in negotiation' },\n },\n meta: {\n aiInstructions: 'In negotiation. Focus on closing. Escalate blockers to management if needed.',\n },\n },\n closed_won: {\n type: 'final',\n meta: {\n aiInstructions: 'Deal won. No further stage changes allowed. Trigger contract creation.',\n },\n },\n closed_lost: {\n type: 'final',\n meta: {\n aiInstructions: 'Deal lost. Record loss reason. No further stage changes allowed.',\n },\n },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * Product Object\n * Represents products/services offered by the company\n */\nexport const Product = ObjectSchema.create({\n name: 'product',\n label: 'Product',\n pluralLabel: 'Products',\n icon: 'box',\n description: 'Products and services offered by the company',\n titleFormat: '{product_code} - {name}',\n compactLayout: ['product_code', 'name', 'category', 'is_active'],\n \n fields: {\n // AutoNumber field - Unique product identifier\n product_code: Field.autonumber({\n label: 'Product Code',\n format: 'PRD-{0000}',\n }),\n \n // Basic Information\n name: Field.text({ \n label: 'Product Name', \n required: true, \n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Categorization\n category: Field.select({\n label: 'Category',\n options: [\n { label: 'Software', value: 'software', default: true },\n { label: 'Hardware', value: 'hardware' },\n { label: 'Service', value: 'service' },\n { label: 'Subscription', value: 'subscription' },\n { label: 'Support', value: 'support' },\n ]\n }),\n \n family: Field.select({\n label: 'Product Family',\n options: [\n { label: 'Enterprise Solutions', value: 'enterprise' },\n { label: 'SMB Solutions', value: 'smb' },\n { label: 'Professional Services', value: 'services' },\n { label: 'Cloud Services', value: 'cloud' },\n ]\n }),\n \n // Pricing\n list_price: Field.currency({ \n label: 'List Price',\n scale: 2,\n min: 0,\n required: true,\n }),\n \n cost: Field.currency({ \n label: 'Cost',\n scale: 2,\n min: 0,\n }),\n \n // SKU and Inventory\n sku: Field.text({\n label: 'SKU',\n maxLength: 50,\n unique: true,\n }),\n \n quantity_on_hand: Field.number({\n label: 'Quantity on Hand',\n min: 0,\n defaultValue: 0,\n }),\n \n reorder_point: Field.number({\n label: 'Reorder Point',\n min: 0,\n }),\n \n // Status\n is_active: Field.boolean({\n label: 'Active',\n defaultValue: true,\n }),\n \n is_taxable: Field.boolean({\n label: 'Taxable',\n defaultValue: true,\n }),\n \n // Relationships\n product_manager: Field.lookup('user', {\n label: 'Product Manager',\n }),\n \n // Images and Assets\n image_url: Field.url({\n label: 'Product Image',\n }),\n \n datasheet_url: Field.url({\n label: 'Datasheet URL',\n }),\n },\n \n // Database indexes\n indexes: [\n { fields: ['name'] },\n { fields: ['sku'], unique: true },\n { fields: ['category'] },\n { fields: ['is_active'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search'],\n files: true,\n feeds: true,\n trash: true,\n mru: true,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'price_positive',\n type: 'script',\n severity: 'error',\n message: 'List Price must be positive',\n condition: 'list_price < 0',\n },\n {\n name: 'cost_less_than_price',\n type: 'script',\n severity: 'warning',\n message: 'Cost should be less than List Price',\n condition: 'cost >= list_price',\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\n/**\n * Quote Object\n * Represents price quotes sent to customers\n */\nexport const Quote = ObjectSchema.create({\n name: 'quote',\n label: 'Quote',\n pluralLabel: 'Quotes',\n icon: 'file-text',\n description: 'Price quotes for customers',\n titleFormat: '{quote_number} - {name}',\n compactLayout: ['quote_number', 'name', 'account', 'status', 'total_price'],\n \n fields: {\n // AutoNumber field\n quote_number: Field.autonumber({\n label: 'Quote Number',\n format: 'QTE-{0000}',\n }),\n \n // Basic Information\n name: Field.text({ \n label: 'Quote Name', \n required: true, \n searchable: true,\n maxLength: 255,\n }),\n \n // Relationships\n account: Field.lookup('account', {\n label: 'Account',\n required: true,\n }),\n \n contact: Field.lookup('contact', {\n label: 'Contact',\n required: true,\n referenceFilters: [\n 'account = {account}',\n ]\n }),\n \n opportunity: Field.lookup('opportunity', {\n label: 'Opportunity',\n referenceFilters: [\n 'account = {account}',\n ]\n }),\n \n owner: Field.lookup('user', {\n label: 'Quote Owner',\n required: true,\n }),\n \n // Status\n status: Field.select({\n label: 'Status',\n options: [\n { label: 'Draft', value: 'draft', color: '#999999', default: true },\n { label: 'In Review', value: 'in_review', color: '#FFA500' },\n { label: 'Presented', value: 'presented', color: '#4169E1' },\n { label: 'Accepted', value: 'accepted', color: '#00AA00' },\n { label: 'Rejected', value: 'rejected', color: '#FF0000' },\n { label: 'Expired', value: 'expired', color: '#666666' },\n ],\n required: true,\n }),\n \n // Dates\n quote_date: Field.date({\n label: 'Quote Date',\n required: true,\n defaultValue: 'TODAY()',\n }),\n \n expiration_date: Field.date({\n label: 'Expiration Date',\n required: true,\n }),\n \n // Pricing\n subtotal: Field.currency({ \n label: 'Subtotal',\n scale: 2,\n readonly: true,\n }),\n \n discount: Field.percent({\n label: 'Discount %',\n scale: 2,\n min: 0,\n max: 100,\n }),\n \n discount_amount: Field.currency({ \n label: 'Discount Amount',\n scale: 2,\n readonly: true,\n }),\n \n tax: Field.currency({ \n label: 'Tax',\n scale: 2,\n }),\n \n shipping_handling: Field.currency({ \n label: 'Shipping & Handling',\n scale: 2,\n }),\n \n total_price: Field.currency({ \n label: 'Total Price',\n scale: 2,\n readonly: true,\n }),\n \n // Terms\n payment_terms: Field.select({\n label: 'Payment Terms',\n options: [\n { label: 'Net 15', value: 'net_15' },\n { label: 'Net 30', value: 'net_30', default: true },\n { label: 'Net 60', value: 'net_60' },\n { label: 'Net 90', value: 'net_90' },\n { label: 'Due on Receipt', value: 'due_on_receipt' },\n ]\n }),\n \n shipping_terms: Field.text({\n label: 'Shipping Terms',\n maxLength: 255,\n }),\n \n // Billing & Shipping Address\n billing_address: Field.address({\n label: 'Billing Address',\n addressFormat: 'international',\n }),\n \n shipping_address: Field.address({\n label: 'Shipping Address',\n addressFormat: 'international',\n }),\n \n // Notes\n description: Field.markdown({\n label: 'Description',\n }),\n \n internal_notes: Field.textarea({\n label: 'Internal Notes',\n }),\n },\n \n // Database indexes\n indexes: [\n { fields: ['account'] },\n { fields: ['opportunity'] },\n { fields: ['owner'] },\n { fields: ['status'] },\n { fields: ['quote_date'] },\n ],\n \n // Enable advanced features\n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n apiMethods: ['get', 'list', 'create', 'update', 'delete', 'search', 'export'],\n files: true,\n feeds: true,\n activities: true,\n trash: true,\n mru: true,\n },\n \n // Validation Rules\n validations: [\n {\n name: 'expiration_after_quote',\n type: 'script',\n severity: 'error',\n message: 'Expiration Date must be after Quote Date',\n condition: 'expiration_date <= quote_date',\n },\n {\n name: 'valid_discount',\n type: 'script',\n severity: 'error',\n message: 'Discount cannot exceed 100%',\n condition: 'discount > 100',\n },\n ],\n \n // Workflow Rules\n workflows: [\n {\n name: 'quote_expired_check',\n objectName: 'quote',\n triggerType: 'on_read',\n criteria: 'expiration_date < TODAY() AND status NOT IN (\"accepted\", \"rejected\", \"expired\")',\n actions: [\n {\n name: 'mark_expired',\n type: 'field_update',\n field: 'status',\n value: '\"expired\"',\n }\n ],\n active: true,\n }\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Task = ObjectSchema.create({\n name: 'task',\n label: 'Task',\n pluralLabel: 'Tasks',\n icon: 'check-square',\n description: 'Activities and to-do items',\n \n fields: {\n // Task Information\n subject: Field.text({\n label: 'Subject',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Task Management\n status: Field.select({\n label: 'Status',\n required: true,\n options: [\n { label: 'Not Started', value: 'not_started', color: '#808080', default: true },\n { label: 'In Progress', value: 'in_progress', color: '#FFA500' },\n { label: 'Waiting', value: 'waiting', color: '#FFD700' },\n { label: 'Completed', value: 'completed', color: '#00AA00' },\n { label: 'Deferred', value: 'deferred', color: '#999999' },\n ]\n }),\n \n priority: Field.select({\n label: 'Priority',\n required: true,\n options: [\n { label: 'Low', value: 'low', color: '#4169E1', default: true },\n { label: 'Normal', value: 'normal', color: '#00AA00' },\n { label: 'High', value: 'high', color: '#FFA500' },\n { label: 'Urgent', value: 'urgent', color: '#FF0000' },\n ]\n }),\n \n type: Field.select({\n label: 'Task Type',\n options: [\n { label: 'Call', value: 'call' },\n { label: 'Email', value: 'email' },\n { label: 'Meeting', value: 'meeting' },\n { label: 'Follow-up', value: 'follow_up' },\n { label: 'Demo', value: 'demo' },\n { label: 'Other', value: 'other' },\n ]\n }),\n \n // Dates\n due_date: Field.date({\n label: 'Due Date',\n }),\n \n reminder_date: Field.datetime({\n label: 'Reminder Date/Time',\n }),\n \n completed_date: Field.datetime({\n label: 'Completed Date',\n readonly: true,\n }),\n \n // Assignment\n owner: Field.lookup('user', {\n label: 'Assigned To',\n required: true,\n }),\n \n // Related To (Polymorphic relationship - can link to multiple object types)\n related_to_type: Field.select({\n label: 'Related To Type',\n options: [\n { label: 'Account', value: 'account' },\n { label: 'Contact', value: 'contact' },\n { label: 'Opportunity', value: 'opportunity' },\n { label: 'Lead', value: 'lead' },\n { label: 'Case', value: 'case' },\n ]\n }),\n \n related_to_account: Field.lookup('account', {\n label: 'Related Account',\n }),\n \n related_to_contact: Field.lookup('contact', {\n label: 'Related Contact',\n }),\n \n related_to_opportunity: Field.lookup('opportunity', {\n label: 'Related Opportunity',\n }),\n \n related_to_lead: Field.lookup('lead', {\n label: 'Related Lead',\n }),\n \n related_to_case: Field.lookup('case', {\n label: 'Related Case',\n }),\n \n // Recurrence (for recurring tasks)\n is_recurring: Field.boolean({\n label: 'Recurring Task',\n defaultValue: false,\n }),\n \n recurrence_type: Field.select({\n label: 'Recurrence Type',\n options: [\n { label: 'Daily', value: 'daily' },\n { label: 'Weekly', value: 'weekly' },\n { label: 'Monthly', value: 'monthly' },\n { label: 'Yearly', value: 'yearly' },\n ]\n }),\n \n recurrence_interval: Field.number({\n label: 'Recurrence Interval',\n defaultValue: 1,\n min: 1,\n }),\n \n recurrence_end_date: Field.date({\n label: 'Recurrence End Date',\n }),\n \n // Flags\n is_completed: Field.boolean({\n label: 'Is Completed',\n defaultValue: false,\n readonly: true,\n }),\n \n is_overdue: Field.boolean({\n label: 'Is Overdue',\n defaultValue: false,\n readonly: true,\n }),\n \n // Progress\n progress_percent: Field.percent({\n label: 'Progress (%)',\n min: 0,\n max: 100,\n defaultValue: 0,\n }),\n \n // Time tracking\n estimated_hours: Field.number({\n label: 'Estimated Hours',\n scale: 2,\n min: 0,\n }),\n \n actual_hours: Field.number({\n label: 'Actual Hours',\n scale: 2,\n min: 0,\n }),\n },\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true, // Enable social feed, comments, and mentions\n activities: true, // Enable tasks and events tracking\n trash: true,\n mru: true, // Track Most Recently Used\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['status'] },\n { fields: ['priority'] },\n { fields: ['owner'] },\n { fields: ['due_date'] },\n ],\n \n titleFormat: '{subject}',\n compactLayout: ['subject', 'status', 'priority', 'due_date', 'owner'],\n \n // Removed: list_views and form_views belong in UI configuration, not object definition\n \n validations: [\n {\n name: 'completed_date_required',\n type: 'script',\n severity: 'error',\n message: 'Completed date is required when status is Completed',\n condition: 'status = \"completed\" AND ISBLANK(completed_date)',\n },\n {\n name: 'recurrence_fields_required',\n type: 'script',\n severity: 'error',\n message: 'Recurrence type is required for recurring tasks',\n condition: 'is_recurring = true AND ISBLANK(recurrence_type)',\n },\n {\n name: 'related_to_required',\n type: 'script',\n severity: 'warning',\n message: 'At least one related record should be selected',\n condition: 'ISBLANK(related_to_account) AND ISBLANK(related_to_contact) AND ISBLANK(related_to_opportunity) AND ISBLANK(related_to_lead) AND ISBLANK(related_to_case)',\n },\n ],\n \n workflows: [\n {\n name: 'set_completed_flag',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(status)',\n active: true,\n actions: [\n {\n name: 'update_completed_flag',\n type: 'field_update',\n field: 'is_completed',\n value: 'status = \"completed\"',\n }\n ],\n },\n {\n name: 'set_completed_date',\n objectName: 'task',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(status) AND status = \"completed\"',\n active: true,\n actions: [\n {\n name: 'set_date',\n type: 'field_update',\n field: 'completed_date',\n value: 'NOW()',\n },\n {\n name: 'set_progress',\n type: 'field_update',\n field: 'progress_percent',\n value: '100',\n }\n ],\n },\n {\n name: 'check_overdue',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'due_date < TODAY() AND is_completed = false',\n active: true,\n actions: [\n {\n name: 'set_overdue_flag',\n type: 'field_update',\n field: 'is_overdue',\n value: 'true',\n }\n ],\n },\n {\n name: 'notify_on_urgent',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'priority = \"urgent\" AND is_completed = false',\n active: true,\n actions: [\n {\n name: 'email_owner',\n type: 'email_alert',\n template: 'urgent_task_alert',\n recipients: ['{owner.email}'],\n }\n ],\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * API Definitions Barrel\n */\nexport { LeadConvertApi } from './lead-convert.api';\nexport { PipelineStatsApi } from './pipeline-stats.api';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ApiEndpoint } from '@objectstack/spec/api';\n\n/** POST /api/v1/crm/leads/convert */\nexport const LeadConvertApi = ApiEndpoint.create({\n name: 'lead_convert',\n path: '/api/v1/crm/leads/convert',\n method: 'POST',\n summary: 'Convert Lead to Account/Contact',\n type: 'flow',\n target: 'flow_lead_conversion_v2',\n inputMapping: [\n { source: 'body.leadId', target: 'leadRecordId' },\n { source: 'body.ownerId', target: 'newOwnerId' },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ApiEndpoint } from '@objectstack/spec/api';\n\n/** GET /api/v1/crm/stats/pipeline */\nexport const PipelineStatsApi = ApiEndpoint.create({\n name: 'get_pipeline_stats',\n path: '/api/v1/crm/stats/pipeline',\n method: 'GET',\n summary: 'Get Pipeline Statistics',\n description: 'Returns the total value of open opportunities grouped by stage',\n type: 'script',\n target: 'server/scripts/pipeline_stats.ts',\n authRequired: true,\n cacheTtl: 300,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Action Definitions Barrel\n *\n * Exports action metadata definitions only. Used by `Object.values()` in\n * objectstack.config.ts to auto-collect all action declarations for defineStack().\n *\n * **Handler functions** are exported from `./handlers/` \u2014 see register-handlers.ts\n * for the complete registration flow.\n */\nexport { EscalateCaseAction, CloseCaseAction } from './case.actions';\nexport { MarkPrimaryContactAction, SendEmailAction } from './contact.actions';\nexport { LogCallAction, ExportToCsvAction } from './global.actions';\nexport { ConvertLeadAction, CreateCampaignAction } from './lead.actions';\nexport { CloneOpportunityAction, MassUpdateStageAction } from './opportunity.actions';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Escalate Case */\nexport const EscalateCaseAction: Action = {\n name: 'escalate_case',\n label: 'Escalate Case',\n objectName: 'case',\n icon: 'alert-triangle',\n type: 'modal',\n target: 'escalate_case_modal',\n locations: ['record_header', 'list_item'],\n visible: 'is_escalated = false AND is_closed = false',\n params: [\n {\n name: 'reason',\n label: 'Escalation Reason',\n type: 'textarea',\n required: true,\n }\n ],\n confirmText: 'This will escalate the case to the escalation team. Continue?',\n successMessage: 'Case escalated successfully!',\n refreshAfter: true,\n};\n\n/** Close Case */\nexport const CloseCaseAction: Action = {\n name: 'close_case',\n label: 'Close Case',\n objectName: 'case',\n icon: 'check-circle',\n type: 'modal',\n target: 'close_case_modal',\n locations: ['record_header'],\n visible: 'is_closed = false',\n params: [\n {\n name: 'resolution',\n label: 'Resolution',\n type: 'textarea',\n required: true,\n }\n ],\n confirmText: 'Are you sure you want to close this case?',\n successMessage: 'Case closed successfully!',\n refreshAfter: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Mark Contact as Primary */\nexport const MarkPrimaryContactAction: Action = {\n name: 'mark_primary',\n label: 'Mark as Primary Contact',\n objectName: 'contact',\n icon: 'star',\n type: 'script',\n target: 'markAsPrimaryContact',\n locations: ['record_header', 'list_item'],\n visible: 'is_primary = false',\n confirmText: 'Mark this contact as the primary contact for the account?',\n successMessage: 'Contact marked as primary!',\n refreshAfter: true,\n};\n\n/** Send Email to Contact */\nexport const SendEmailAction: Action = {\n name: 'send_email',\n label: 'Send Email',\n objectName: 'contact',\n icon: 'mail',\n type: 'modal',\n target: 'email_composer',\n locations: ['record_header', 'list_item'],\n visible: 'email_opt_out = false',\n refreshAfter: false,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Log a Call */\nexport const LogCallAction: Action = {\n name: 'log_call',\n label: 'Log a Call',\n icon: 'phone',\n type: 'modal',\n target: 'call_log_modal',\n locations: ['record_header', 'list_item', 'record_related'],\n params: [\n {\n name: 'subject',\n label: 'Call Subject',\n type: 'text',\n required: true,\n },\n {\n name: 'duration',\n label: 'Duration (minutes)',\n type: 'number',\n required: true,\n },\n {\n name: 'notes',\n label: 'Call Notes',\n type: 'textarea',\n required: false,\n }\n ],\n successMessage: 'Call logged successfully!',\n refreshAfter: true,\n};\n\n/** Export to CSV */\nexport const ExportToCsvAction: Action = {\n name: 'export_csv',\n label: 'Export to CSV',\n icon: 'download',\n type: 'script',\n target: 'exportToCSV',\n locations: ['list_toolbar'],\n successMessage: 'Export completed!',\n refreshAfter: false,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Convert Lead to Account, Contact, and Opportunity */\nexport const ConvertLeadAction: Action = {\n name: 'convert_lead',\n label: 'Convert Lead',\n objectName: 'lead',\n icon: 'arrow-right-circle',\n type: 'flow',\n target: 'lead_conversion',\n locations: ['record_header', 'list_item'],\n visible: 'status = \"qualified\" AND is_converted = false',\n confirmText: 'Are you sure you want to convert this lead?',\n successMessage: 'Lead converted successfully!',\n refreshAfter: true,\n};\n\n/** Create Campaign from Leads */\nexport const CreateCampaignAction: Action = {\n name: 'create_campaign',\n label: 'Add to Campaign',\n objectName: 'lead',\n icon: 'send',\n type: 'modal',\n target: 'add_to_campaign_modal',\n locations: ['list_toolbar'],\n params: [\n {\n name: 'campaign',\n label: 'Campaign',\n type: 'lookup',\n required: true,\n }\n ],\n successMessage: 'Leads added to campaign!',\n refreshAfter: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Clone Opportunity */\nexport const CloneOpportunityAction: Action = {\n name: 'clone_opportunity',\n label: 'Clone Opportunity',\n objectName: 'opportunity',\n icon: 'copy',\n type: 'script',\n target: 'cloneRecord',\n locations: ['record_header', 'record_more'],\n successMessage: 'Opportunity cloned successfully!',\n refreshAfter: true,\n};\n\n/** Mass Update Opportunity Stage */\nexport const MassUpdateStageAction: Action = {\n name: 'mass_update_stage',\n label: 'Update Stage',\n objectName: 'opportunity',\n icon: 'layers',\n type: 'modal',\n target: 'mass_update_stage_modal',\n locations: ['list_toolbar'],\n params: [\n {\n name: 'stage',\n label: 'New Stage',\n type: 'select',\n required: true,\n options: [\n { label: 'Prospecting', value: 'prospecting' },\n { label: 'Qualification', value: 'qualification' },\n { label: 'Needs Analysis', value: 'needs_analysis' },\n { label: 'Proposal', value: 'proposal' },\n { label: 'Negotiation', value: 'negotiation' },\n { label: 'Closed Won', value: 'closed_won' },\n { label: 'Closed Lost', value: 'closed_lost' },\n ]\n }\n ],\n successMessage: 'Opportunities updated successfully!',\n refreshAfter: true,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Dashboard Definitions Barrel\n */\nexport { ExecutiveDashboard } from './executive.dashboard';\nexport { SalesDashboard } from './sales.dashboard';\nexport { ServiceDashboard } from './service.dashboard';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Dashboard } from '@objectstack/spec/ui';\n\nexport const ExecutiveDashboard: Dashboard = {\n name: 'executive_dashboard',\n label: 'Executive Overview',\n description: 'High-level business metrics',\n \n widgets: [\n // Row 1: Revenue Metrics\n {\n id: 'total_revenue_ytd',\n title: 'Total Revenue (YTD)',\n type: 'metric',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{current_year_start}' } },\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 0, w: 3, h: 2 },\n options: { prefix: '$', color: '#00AA00' }\n },\n {\n id: 'total_accounts',\n title: 'Total Accounts',\n type: 'metric',\n object: 'account',\n filter: { is_active: true },\n aggregate: 'count',\n layout: { x: 3, y: 0, w: 3, h: 2 },\n options: { color: '#4169E1' }\n },\n {\n id: 'total_contacts',\n title: 'Total Contacts',\n type: 'metric',\n object: 'contact',\n aggregate: 'count',\n layout: { x: 6, y: 0, w: 3, h: 2 },\n options: { color: '#9370DB' }\n },\n {\n id: 'total_leads',\n title: 'Total Leads',\n type: 'metric',\n object: 'lead',\n filter: { is_converted: false },\n aggregate: 'count',\n layout: { x: 9, y: 0, w: 3, h: 2 },\n options: { color: '#FFA500' }\n },\n \n // Row 2: Revenue Analysis\n {\n id: 'revenue_by_industry',\n title: 'Revenue by Industry',\n type: 'bar',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{current_year_start}' } },\n categoryField: 'account.industry',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 2, w: 6, h: 4 },\n },\n {\n id: 'quarterly_revenue_trend',\n title: 'Quarterly Revenue Trend',\n type: 'line',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{last_4_quarters}' } },\n categoryField: 'close_date',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 6, y: 2, w: 6, h: 4 },\n options: { dateGranularity: 'quarter' }\n },\n \n // Row 3: Customer & Activity Metrics\n {\n id: 'new_accounts_by_month',\n title: 'New Accounts by Month',\n type: 'bar',\n object: 'account',\n filter: { created_date: { $gte: '{last_6_months}' } },\n categoryField: 'created_date',\n aggregate: 'count',\n layout: { x: 0, y: 6, w: 4, h: 4 },\n options: { dateGranularity: 'month' }\n },\n {\n id: 'lead_conversion_rate',\n title: 'Lead Conversion Rate',\n type: 'metric',\n object: 'lead',\n valueField: 'is_converted',\n aggregate: 'avg',\n layout: { x: 4, y: 6, w: 4, h: 4 },\n options: { suffix: '%', color: '#00AA00' }\n },\n {\n id: 'top_accounts_by_revenue',\n title: 'Top Accounts by Revenue',\n type: 'table',\n object: 'account',\n aggregate: 'count',\n layout: { x: 8, y: 6, w: 4, h: 4 },\n options: {\n columns: ['name', 'annual_revenue', 'type'],\n sortBy: 'annual_revenue',\n sortOrder: 'desc',\n limit: 10,\n }\n },\n ]\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Dashboard } from '@objectstack/spec/ui';\n\nexport const SalesDashboard: Dashboard = {\n name: 'sales_dashboard',\n label: 'Sales Performance',\n description: 'Key sales metrics and pipeline overview',\n \n widgets: [\n // Row 1: Key Metrics\n {\n id: 'total_pipeline_value',\n title: 'Total Pipeline Value',\n type: 'metric',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 0, w: 3, h: 2 },\n options: { prefix: '$', color: '#4169E1' }\n },\n {\n id: 'closed_won_this_quarter',\n title: 'Closed Won This Quarter',\n type: 'metric',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{current_quarter_start}' } },\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 3, y: 0, w: 3, h: 2 },\n options: { prefix: '$', color: '#00AA00' }\n },\n {\n id: 'open_opportunities',\n title: 'Open Opportunities',\n type: 'metric',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n aggregate: 'count',\n layout: { x: 6, y: 0, w: 3, h: 2 },\n options: { color: '#FFA500' }\n },\n {\n id: 'win_rate',\n title: 'Win Rate',\n type: 'metric',\n object: 'opportunity',\n filter: { close_date: { $gte: '{current_quarter_start}' } },\n valueField: 'stage',\n aggregate: 'count',\n layout: { x: 9, y: 0, w: 3, h: 2 },\n options: { suffix: '%', color: '#9370DB' }\n },\n \n // Row 2: Pipeline Analysis\n {\n id: 'pipeline_by_stage',\n title: 'Pipeline by Stage',\n type: 'funnel',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n categoryField: 'stage',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 2, w: 6, h: 4 },\n options: { showValues: true }\n },\n {\n id: 'opportunities_by_owner',\n title: 'Opportunities by Owner',\n type: 'bar',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n categoryField: 'owner',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 6, y: 2, w: 6, h: 4 },\n options: { horizontal: true }\n },\n \n // Row 3: Trends\n {\n id: 'monthly_revenue_trend',\n title: 'Monthly Revenue Trend',\n type: 'line',\n object: 'opportunity',\n filter: { stage: 'closed_won', close_date: { $gte: '{last_12_months}' } },\n categoryField: 'close_date',\n valueField: 'amount',\n aggregate: 'sum',\n layout: { x: 0, y: 6, w: 8, h: 4 },\n options: { dateGranularity: 'month', showTrend: true }\n },\n {\n id: 'top_opportunities',\n title: 'Top Opportunities',\n type: 'table',\n object: 'opportunity',\n filter: { stage: { $nin: ['closed_won', 'closed_lost'] } },\n aggregate: 'count',\n layout: { x: 8, y: 6, w: 4, h: 4 },\n options: {\n columns: ['name', 'amount', 'stage', 'close_date'],\n sortBy: 'amount',\n sortOrder: 'desc',\n limit: 10,\n }\n },\n ]\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Dashboard } from '@objectstack/spec/ui';\n\nexport const ServiceDashboard: Dashboard = {\n name: 'service_dashboard',\n label: 'Customer Service',\n description: 'Support case metrics and performance',\n \n widgets: [\n // Row 1: Key Metrics\n {\n id: 'open_cases',\n title: 'Open Cases',\n type: 'metric',\n object: 'case',\n filter: { is_closed: false },\n aggregate: 'count',\n layout: { x: 0, y: 0, w: 3, h: 2 },\n options: { color: '#FFA500' }\n },\n {\n id: 'critical_cases',\n title: 'Critical Cases',\n type: 'metric',\n object: 'case',\n filter: { priority: 'critical', is_closed: false },\n aggregate: 'count',\n layout: { x: 3, y: 0, w: 3, h: 2 },\n options: { color: '#FF0000' }\n },\n {\n id: 'avg_resolution_time',\n title: 'Avg Resolution Time (hrs)',\n type: 'metric',\n object: 'case',\n filter: { is_closed: true },\n valueField: 'resolution_time_hours',\n aggregate: 'avg',\n layout: { x: 6, y: 0, w: 3, h: 2 },\n options: { suffix: 'h', color: '#4169E1' }\n },\n {\n id: 'sla_violations',\n title: 'SLA Violations',\n type: 'metric',\n object: 'case',\n filter: { is_sla_violated: true },\n aggregate: 'count',\n layout: { x: 9, y: 0, w: 3, h: 2 },\n options: { color: '#FF4500' }\n },\n \n // Row 2: Case Distribution\n {\n id: 'cases_by_status',\n title: 'Cases by Status',\n type: 'pie',\n object: 'case',\n filter: { is_closed: false },\n categoryField: 'status',\n aggregate: 'count',\n layout: { x: 0, y: 2, w: 4, h: 4 },\n options: { showLegend: true }\n },\n {\n id: 'cases_by_priority',\n title: 'Cases by Priority',\n type: 'pie',\n object: 'case',\n filter: { is_closed: false },\n categoryField: 'priority',\n aggregate: 'count',\n layout: { x: 4, y: 2, w: 4, h: 4 },\n options: { showLegend: true }\n },\n {\n id: 'cases_by_origin',\n title: 'Cases by Origin',\n type: 'bar',\n object: 'case',\n categoryField: 'origin',\n aggregate: 'count',\n layout: { x: 8, y: 2, w: 4, h: 4 },\n },\n \n // Row 3: Trends and Lists\n {\n id: 'daily_case_volume',\n title: 'Daily Case Volume',\n type: 'line',\n object: 'case',\n filter: { created_date: { $gte: '{last_30_days}' } },\n categoryField: 'created_date',\n aggregate: 'count',\n layout: { x: 0, y: 6, w: 8, h: 4 },\n options: { dateGranularity: 'day' }\n },\n {\n id: 'my_open_cases',\n title: 'My Open Cases',\n type: 'table',\n object: 'case',\n filter: { owner: '{current_user}', is_closed: false },\n aggregate: 'count',\n layout: { x: 8, y: 6, w: 4, h: 4 },\n options: {\n columns: ['case_number', 'subject', 'priority', 'status'],\n sortBy: 'priority',\n sortOrder: 'desc',\n limit: 10,\n }\n },\n ]\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Report Definitions Barrel\n */\nexport { AccountsByIndustryTypeReport } from './account.report';\nexport { CasesByStatusPriorityReport, SlaPerformanceReport } from './case.report';\nexport { ContactsByAccountReport } from './contact.report';\nexport { LeadsBySourceReport } from './lead.report';\nexport { OpportunitiesByStageReport, WonOpportunitiesByOwnerReport } from './opportunity.report';\nexport { TasksByOwnerReport } from './task.report';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const AccountsByIndustryTypeReport: ReportInput = {\n name: 'accounts_by_industry_type',\n label: 'Accounts by Industry and Type',\n description: 'Matrix report showing accounts by industry and type',\n objectName: 'account',\n type: 'matrix',\n columns: [\n { field: 'name', aggregate: 'count' },\n { field: 'annual_revenue', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'industry', sortOrder: 'asc' }],\n groupingsAcross: [{ field: 'type', sortOrder: 'asc' }],\n filter: { is_active: true },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const CasesByStatusPriorityReport: ReportInput = {\n name: 'cases_by_status_priority',\n label: 'Cases by Status and Priority',\n description: 'Summary of cases by status and priority',\n objectName: 'case',\n type: 'summary',\n columns: [\n { field: 'case_number', label: 'Case Number' },\n { field: 'subject', label: 'Subject' },\n { field: 'account', label: 'Account' },\n { field: 'owner', label: 'Owner' },\n { field: 'resolution_time_hours', label: 'Resolution Time', aggregate: 'avg' },\n ],\n groupingsDown: [\n { field: 'status', sortOrder: 'asc' },\n { field: 'priority', sortOrder: 'desc' },\n ],\n chart: { type: 'bar', title: 'Cases by Status', showLegend: true, xAxis: 'status', yAxis: 'case_number' }\n};\n\nexport const SlaPerformanceReport: ReportInput = {\n name: 'sla_performance',\n label: 'SLA Performance Report',\n description: 'Analysis of SLA compliance',\n objectName: 'case',\n type: 'summary',\n columns: [\n { field: 'case_number', aggregate: 'count' },\n { field: 'is_sla_violated', label: 'SLA Violated', aggregate: 'count' },\n { field: 'resolution_time_hours', label: 'Avg Resolution Time', aggregate: 'avg' },\n ],\n groupingsDown: [{ field: 'priority', sortOrder: 'desc' }],\n filter: { is_closed: true },\n chart: { type: 'column', title: 'SLA Violations by Priority', showLegend: false, xAxis: 'priority', yAxis: 'is_sla_violated' }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const ContactsByAccountReport: ReportInput = {\n name: 'contacts_by_account',\n label: 'Contacts by Account',\n description: 'List of contacts grouped by account',\n objectName: 'contact',\n type: 'summary',\n columns: [\n { field: 'full_name', label: 'Name' },\n { field: 'title', label: 'Title' },\n { field: 'email', label: 'Email' },\n { field: 'phone', label: 'Phone' },\n { field: 'is_primary', label: 'Primary Contact' },\n ],\n groupingsDown: [{ field: 'account', sortOrder: 'asc' }],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const LeadsBySourceReport: ReportInput = {\n name: 'leads_by_source',\n label: 'Leads by Source and Status',\n description: 'Lead pipeline analysis',\n objectName: 'lead',\n type: 'summary',\n columns: [\n { field: 'full_name', label: 'Name' },\n { field: 'company', label: 'Company' },\n { field: 'rating', label: 'Rating' },\n ],\n groupingsDown: [\n { field: 'lead_source', sortOrder: 'asc' },\n { field: 'status', sortOrder: 'asc' },\n ],\n filter: { is_converted: false },\n chart: { type: 'pie', title: 'Leads by Source', showLegend: true, xAxis: 'lead_source', yAxis: 'full_name' }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const OpportunitiesByStageReport: ReportInput = {\n name: 'opportunities_by_stage',\n label: 'Opportunities by Stage',\n description: 'Summary of opportunities grouped by stage',\n objectName: 'opportunity',\n type: 'summary',\n columns: [\n { field: 'name', label: 'Opportunity Name' },\n { field: 'account', label: 'Account' },\n { field: 'amount', label: 'Amount', aggregate: 'sum' },\n { field: 'close_date', label: 'Close Date' },\n { field: 'probability', label: 'Probability', aggregate: 'avg' },\n ],\n groupingsDown: [{ field: 'stage', sortOrder: 'asc' }],\n filter: { stage: { $ne: 'closed_lost' }, close_date: { $gte: '{current_year_start}' } },\n chart: { type: 'bar', title: 'Pipeline by Stage', showLegend: true, xAxis: 'stage', yAxis: 'amount' }\n};\n\nexport const WonOpportunitiesByOwnerReport: ReportInput = {\n name: 'won_opportunities_by_owner',\n label: 'Won Opportunities by Owner',\n description: 'Closed won opportunities grouped by owner',\n objectName: 'opportunity',\n type: 'summary',\n columns: [\n { field: 'name', label: 'Opportunity Name' },\n { field: 'account', label: 'Account' },\n { field: 'amount', label: 'Amount', aggregate: 'sum' },\n { field: 'close_date', label: 'Close Date' },\n ],\n groupingsDown: [{ field: 'owner', sortOrder: 'desc' }],\n filter: { stage: 'closed_won' },\n chart: { type: 'column', title: 'Revenue by Sales Rep', showLegend: false, xAxis: 'owner', yAxis: 'amount' }\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\nexport const TasksByOwnerReport: ReportInput = {\n name: 'tasks_by_owner',\n label: 'Tasks by Owner',\n description: 'Task summary by owner',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'status', label: 'Status' },\n { field: 'priority', label: 'Priority' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'actual_hours', label: 'Hours', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'owner', sortOrder: 'asc' }],\n filter: { is_completed: false },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Campaign Enrollment \u2014 scheduled flow to bulk enroll leads */\nexport const CampaignEnrollmentFlow: Flow = {\n name: 'campaign_enrollment',\n label: 'Enroll Leads in Campaign',\n description: 'Bulk enroll leads into marketing campaigns',\n type: 'schedule',\n\n variables: [\n { name: 'campaignId', type: 'text', isInput: true, isOutput: false },\n { name: 'leadStatus', type: 'text', isInput: true, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start (Monday 9 AM)', config: { schedule: '0 9 * * 1' } },\n {\n id: 'get_campaign', type: 'get_record', label: 'Get Campaign',\n config: { objectName: 'campaign', filter: { id: '{campaignId}' }, outputVariable: 'campaignRecord' },\n },\n {\n id: 'query_leads', type: 'get_record', label: 'Find Eligible Leads',\n config: { objectName: 'lead', filter: { status: '{leadStatus}', is_converted: false, email: { $ne: null } }, limit: 1000, outputVariable: 'leadList' },\n },\n {\n id: 'loop_leads', type: 'loop', label: 'Process Each Lead',\n config: { collection: '{leadList}', iteratorVariable: 'currentLead' },\n },\n {\n id: 'create_campaign_member', type: 'create_record', label: 'Add to Campaign',\n config: {\n objectName: 'campaign_member',\n fields: { campaign: '{campaignId}', lead: '{currentLead.id}', status: 'sent', added_date: '{NOW()}' },\n },\n },\n {\n id: 'update_campaign_stats', type: 'update_record', label: 'Update Campaign Stats',\n config: { objectName: 'campaign', filter: { id: '{campaignId}' }, fields: { num_sent: '{leadList.length}' } },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_campaign', type: 'default' },\n { id: 'e2', source: 'get_campaign', target: 'query_leads', type: 'default' },\n { id: 'e3', source: 'query_leads', target: 'loop_leads', type: 'default' },\n { id: 'e4', source: 'loop_leads', target: 'create_campaign_member', type: 'default' },\n { id: 'e5', source: 'create_campaign_member', target: 'update_campaign_stats', type: 'default' },\n { id: 'e6', source: 'update_campaign_stats', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Case Escalation \u2014 auto-escalate high-priority cases */\nexport const CaseEscalationFlow: Flow = {\n name: 'case_escalation',\n label: 'Case Escalation Process',\n description: 'Automatically escalate high-priority cases',\n type: 'record_change',\n\n variables: [\n { name: 'caseId', type: 'text', isInput: true, isOutput: false },\n ],\n\n nodes: [\n {\n id: 'start', type: 'start', label: 'Start',\n config: { objectName: 'case', criteria: 'priority = \"critical\" OR (priority = \"high\" AND account.type = \"customer\")' },\n },\n {\n id: 'get_case', type: 'get_record', label: 'Get Case Record',\n config: { objectName: 'case', filter: { id: '{caseId}' }, outputVariable: 'caseRecord' },\n },\n {\n id: 'assign_senior_agent', type: 'update_record', label: 'Assign to Senior Agent',\n config: {\n objectName: 'case', filter: { id: '{caseId}' },\n fields: { owner: '{caseRecord.owner.manager}', is_escalated: true, escalated_date: '{NOW()}' },\n },\n },\n {\n id: 'create_task', type: 'create_record', label: 'Create Follow-up Task',\n config: {\n objectName: 'task',\n fields: {\n subject: 'Follow up on escalated case: {caseRecord.case_number}',\n related_to: '{caseId}', owner: '{caseRecord.owner}',\n priority: 'high', status: 'not_started', due_date: '{TODAY() + 1}',\n },\n },\n },\n {\n id: 'notify_team', type: 'script', label: 'Notify Support Team',\n config: {\n actionType: 'email',\n template: 'case_escalated',\n recipients: ['{caseRecord.owner}', '{caseRecord.owner.manager}', 'support-team@example.com'],\n variables: {\n caseNumber: '{caseRecord.case_number}',\n priority: '{caseRecord.priority}',\n accountName: '{caseRecord.account.name}',\n },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_case', type: 'default' },\n { id: 'e2', source: 'get_case', target: 'assign_senior_agent', type: 'default' },\n { id: 'e3', source: 'assign_senior_agent', target: 'create_task', type: 'default' },\n { id: 'e4', source: 'create_task', target: 'notify_team', type: 'default' },\n { id: 'e5', source: 'notify_team', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Lead Conversion \u2014 multi-step screen flow to convert qualified leads */\nexport const LeadConversionFlow: Flow = {\n name: 'lead_conversion',\n label: 'Lead Conversion Process',\n description: 'Automated flow to convert qualified leads to accounts, contacts, and opportunities',\n type: 'screen',\n\n variables: [\n { name: 'leadId', type: 'text', isInput: true, isOutput: false },\n { name: 'createOpportunity', type: 'boolean', isInput: true, isOutput: false },\n { name: 'opportunityName', type: 'text', isInput: true, isOutput: false },\n { name: 'opportunityAmount', type: 'text', isInput: true, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start', config: { objectName: 'lead' } },\n {\n id: 'screen_1', type: 'screen', label: 'Conversion Details',\n config: {\n fields: [\n { name: 'createOpportunity', label: 'Create Opportunity?', type: 'boolean', required: true },\n { name: 'opportunityName', label: 'Opportunity Name', type: 'text', required: true, visibleWhen: '{createOpportunity} == true' },\n { name: 'opportunityAmount', label: 'Opportunity Amount', type: 'currency', visibleWhen: '{createOpportunity} == true' },\n ],\n },\n },\n {\n id: 'get_lead', type: 'get_record', label: 'Get Lead Record',\n config: { objectName: 'lead', filter: { id: '{leadId}' }, outputVariable: 'leadRecord' },\n },\n {\n id: 'create_account', type: 'create_record', label: 'Create Account',\n config: {\n objectName: 'account',\n fields: {\n name: '{leadRecord.company}', phone: '{leadRecord.phone}',\n website: '{leadRecord.website}', industry: '{leadRecord.industry}',\n annual_revenue: '{leadRecord.annual_revenue}',\n number_of_employees: '{leadRecord.number_of_employees}',\n billing_address: '{leadRecord.address}',\n owner: '{$User.Id}', is_active: true,\n },\n outputVariable: 'accountId',\n },\n },\n {\n id: 'create_contact', type: 'create_record', label: 'Create Contact',\n config: {\n objectName: 'contact',\n fields: {\n first_name: '{leadRecord.first_name}', last_name: '{leadRecord.last_name}',\n email: '{leadRecord.email}', phone: '{leadRecord.phone}',\n title: '{leadRecord.title}', account: '{accountId}',\n is_primary: true, owner: '{$User.Id}',\n },\n outputVariable: 'contactId',\n },\n },\n {\n id: 'decision_opportunity', type: 'decision', label: 'Create Opportunity?',\n config: { condition: '{createOpportunity} == true' },\n },\n {\n id: 'create_opportunity', type: 'create_record', label: 'Create Opportunity',\n config: {\n objectName: 'opportunity',\n fields: {\n name: '{opportunityName}', account: '{accountId}', contact: '{contactId}',\n amount: '{opportunityAmount}', stage: 'prospecting', probability: 10,\n lead_source: '{leadRecord.lead_source}', close_date: '{TODAY() + 90}', owner: '{$User.Id}',\n },\n outputVariable: 'opportunityId',\n },\n },\n {\n id: 'mark_converted', type: 'update_record', label: 'Mark Lead as Converted',\n config: {\n objectName: 'lead', filter: { id: '{leadId}' },\n fields: {\n is_converted: true, converted_date: '{NOW()}',\n converted_account: '{accountId}', converted_contact: '{contactId}',\n converted_opportunity: '{opportunityId}',\n },\n },\n },\n {\n id: 'send_notification', type: 'script', label: 'Send Confirmation Email',\n config: {\n actionType: 'email', template: 'lead_converted_notification',\n recipients: ['{$User.Email}'],\n variables: { leadName: '{leadRecord.full_name}', accountName: '{accountId.name}', contactName: '{contactId.full_name}' },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'screen_1', type: 'default' },\n { id: 'e2', source: 'screen_1', target: 'get_lead', type: 'default' },\n { id: 'e3', source: 'get_lead', target: 'create_account', type: 'default' },\n { id: 'e4', source: 'create_account', target: 'create_contact', type: 'default' },\n { id: 'e5', source: 'create_contact', target: 'decision_opportunity', type: 'default' },\n { id: 'e6', source: 'decision_opportunity', target: 'create_opportunity', type: 'default', condition: '{createOpportunity} == true', label: 'Yes' },\n { id: 'e7', source: 'decision_opportunity', target: 'mark_converted', type: 'default', condition: '{createOpportunity} != true', label: 'No' },\n { id: 'e8', source: 'create_opportunity', target: 'mark_converted', type: 'default' },\n { id: 'e9', source: 'mark_converted', target: 'send_notification', type: 'default' },\n { id: 'e10', source: 'send_notification', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Opportunity Approval \u2014 multi-level approval for deals over $100K */\nexport const OpportunityApprovalFlow: Flow = {\n name: 'opportunity_approval',\n label: 'Large Deal Approval',\n description: 'Approval process for opportunities over $100K',\n type: 'record_change',\n\n variables: [\n { name: 'opportunityId', type: 'text', isInput: true, isOutput: false },\n ],\n\n nodes: [\n {\n id: 'start', type: 'start', label: 'Start',\n config: { objectName: 'opportunity', criteria: 'amount > 100000 AND stage = \"proposal\"' },\n },\n {\n id: 'get_opportunity', type: 'get_record', label: 'Get Opportunity',\n config: { objectName: 'opportunity', filter: { id: '{opportunityId}' }, outputVariable: 'oppRecord' },\n },\n {\n id: 'approval_step_manager', type: 'connector_action', label: 'Sales Manager Approval',\n config: {\n actionType: 'approval',\n approver: '{oppRecord.owner.manager}',\n emailTemplate: 'opportunity_approval_request',\n comments: 'required',\n },\n },\n {\n id: 'decision_manager', type: 'decision', label: 'Manager Approved?',\n config: { condition: '{approval_step_manager.result} == \"approved\"' },\n },\n {\n id: 'approval_step_director', type: 'connector_action', label: 'Sales Director Approval',\n config: {\n actionType: 'approval',\n approver: '{oppRecord.owner.manager.manager}',\n emailTemplate: 'opportunity_approval_request',\n },\n },\n {\n id: 'decision_director', type: 'decision', label: 'Director Approved?',\n config: { condition: '{approval_step_director.result} == \"approved\"' },\n },\n {\n id: 'mark_approved', type: 'update_record', label: 'Mark as Approved',\n config: {\n objectName: 'opportunity', filter: { id: '{opportunityId}' },\n fields: { approval_status: 'approved', approved_date: '{NOW()}' },\n },\n },\n {\n id: 'notify_approval', type: 'script', label: 'Send Approval Notification',\n config: { actionType: 'email', template: 'opportunity_approved', recipients: ['{oppRecord.owner}'] },\n },\n {\n id: 'notify_rejection', type: 'script', label: 'Send Rejection Notification',\n config: { actionType: 'email', template: 'opportunity_rejected', recipients: ['{oppRecord.owner}'] },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_opportunity', type: 'default' },\n { id: 'e2', source: 'get_opportunity', target: 'approval_step_manager', type: 'default' },\n { id: 'e3', source: 'approval_step_manager', target: 'decision_manager', type: 'default' },\n { id: 'e4', source: 'decision_manager', target: 'approval_step_director', type: 'default', condition: '{approval_step_manager.result} == \"approved\"', label: 'Approved' },\n { id: 'e5', source: 'decision_manager', target: 'notify_rejection', type: 'default', condition: '{approval_step_manager.result} != \"approved\"', label: 'Rejected' },\n { id: 'e6', source: 'approval_step_director', target: 'decision_director', type: 'default' },\n { id: 'e7', source: 'decision_director', target: 'mark_approved', type: 'default', condition: '{approval_step_director.result} == \"approved\"', label: 'Approved' },\n { id: 'e8', source: 'decision_director', target: 'notify_rejection', type: 'default', condition: '{approval_step_director.result} != \"approved\"', label: 'Rejected' },\n { id: 'e9', source: 'mark_approved', target: 'notify_approval', type: 'default' },\n { id: 'e10', source: 'notify_approval', target: 'end', type: 'default' },\n { id: 'e11', source: 'notify_rejection', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Automation } from '@objectstack/spec';\ntype Flow = Automation.Flow;\n\n/** Quote Generation \u2014 screen flow to create a quote from an opportunity */\nexport const QuoteGenerationFlow: Flow = {\n name: 'quote_generation',\n label: 'Generate Quote from Opportunity',\n description: 'Create a quote based on opportunity details',\n type: 'screen',\n\n variables: [\n { name: 'opportunityId', type: 'text', isInput: true, isOutput: false },\n { name: 'quoteName', type: 'text', isInput: true, isOutput: false },\n { name: 'expirationDays', type: 'number', isInput: true, isOutput: false },\n { name: 'discount', type: 'number', isInput: true, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start', config: { objectName: 'opportunity' } },\n {\n id: 'screen_1', type: 'screen', label: 'Quote Details',\n config: {\n fields: [\n { name: 'quoteName', label: 'Quote Name', type: 'text', required: true },\n { name: 'expirationDays', label: 'Valid For (Days)', type: 'number', required: true, defaultValue: 30 },\n { name: 'discount', label: 'Discount %', type: 'percent', defaultValue: 0 },\n ],\n },\n },\n {\n id: 'get_opportunity', type: 'get_record', label: 'Get Opportunity',\n config: { objectName: 'opportunity', filter: { id: '{opportunityId}' }, outputVariable: 'oppRecord' },\n },\n {\n id: 'create_quote', type: 'create_record', label: 'Create Quote',\n config: {\n objectName: 'quote',\n fields: {\n name: '{quoteName}', opportunity: '{opportunityId}',\n account: '{oppRecord.account}', contact: '{oppRecord.contact}',\n owner: '{$User.Id}', status: 'draft',\n quote_date: '{TODAY()}', expiration_date: '{TODAY() + expirationDays}',\n subtotal: '{oppRecord.amount}', discount: '{discount}',\n discount_amount: '{oppRecord.amount * (discount / 100)}',\n total_price: '{oppRecord.amount * (1 - discount / 100)}',\n payment_terms: 'net_30',\n },\n outputVariable: 'quoteId',\n },\n },\n {\n id: 'update_opportunity', type: 'update_record', label: 'Update Opportunity',\n config: {\n objectName: 'opportunity', filter: { id: '{opportunityId}' },\n fields: { stage: 'proposal', last_activity_date: '{TODAY()}' },\n },\n },\n {\n id: 'notify_owner', type: 'script', label: 'Send Notification',\n config: {\n actionType: 'email', template: 'quote_created',\n recipients: ['{$User.Email}'],\n variables: { quoteName: '{quoteName}', quoteId: '{quoteId}' },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'screen_1', type: 'default' },\n { id: 'e2', source: 'screen_1', target: 'get_opportunity', type: 'default' },\n { id: 'e3', source: 'get_opportunity', target: 'create_quote', type: 'default' },\n { id: 'e4', source: 'create_quote', target: 'update_opportunity', type: 'default' },\n { id: 'e5', source: 'update_opportunity', target: 'notify_owner', type: 'default' },\n { id: 'e6', source: 'notify_owner', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Flow } from '@objectstack/spec/automation';\n\n/**\n * Flow Definitions Barrel\n */\nexport { CampaignEnrollmentFlow } from './campaign-enrollment.flow';\nexport { CaseEscalationFlow } from './case-escalation.flow';\nexport { LeadConversionFlow } from './lead-conversion.flow';\nexport { OpportunityApprovalFlow } from './opportunity-approval.flow';\nexport { QuoteGenerationFlow } from './quote-generation.flow';\n\nimport { CampaignEnrollmentFlow } from './campaign-enrollment.flow';\nimport { CaseEscalationFlow } from './case-escalation.flow';\nimport { LeadConversionFlow } from './lead-conversion.flow';\nimport { OpportunityApprovalFlow } from './opportunity-approval.flow';\nimport { QuoteGenerationFlow } from './quote-generation.flow';\n\n/** All flow definitions as a typed array for defineStack() */\nexport const allFlows: Flow[] = [\n CampaignEnrollmentFlow,\n CaseEscalationFlow,\n LeadConversionFlow,\n OpportunityApprovalFlow,\n QuoteGenerationFlow,\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Email Campaign Agent \u2014 creates and optimizes email campaigns */\nexport const EmailCampaignAgent = {\n name: 'email_campaign',\n label: 'Email Campaign Agent',\n role: 'creator',\n\n instructions: `You are an email marketing AI that creates and optimizes email campaigns.\n\nYour responsibilities:\n1. Write compelling email copy\n2. Optimize subject lines for open rates\n3. Personalize content based on recipient data\n4. A/B test different variations\n5. Analyze campaign performance\n6. Suggest improvements\n\nFollow email marketing best practices and maintain brand voice.`,\n\n model: { provider: 'anthropic', model: 'claude-3-opus', temperature: 0.8, maxTokens: 2000 },\n\n tools: [\n { type: 'action' as const, name: 'generate_email_copy', description: 'Generate email campaign copy' },\n { type: 'action' as const, name: 'optimize_subject_line', description: 'Optimize email subject line' },\n { type: 'action' as const, name: 'personalize_content', description: 'Personalize email content' },\n ],\n\n knowledge: {\n topics: ['email_marketing', 'brand_guidelines', 'campaign_templates'],\n indexes: ['sales_knowledge'],\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Lead Enrichment Agent \u2014 automatically enriches lead data from external sources */\nexport const LeadEnrichmentAgent = {\n name: 'lead_enrichment',\n label: 'Lead Enrichment Agent',\n role: 'worker',\n\n instructions: `You are a lead enrichment AI that enhances lead records with additional data.\n\nYour responsibilities:\n1. Look up company information from external databases\n2. Enrich contact details (job title, LinkedIn, etc.)\n3. Add firmographic data (industry, size, revenue)\n4. Research company technology stack\n5. Find social media profiles\n6. Validate email addresses and phone numbers\n\nAlways use reputable data sources and maintain data quality.`,\n\n model: { provider: 'openai', model: 'gpt-3.5-turbo', temperature: 0.3, maxTokens: 1000 },\n\n tools: [\n { type: 'action' as const, name: 'lookup_company', description: 'Look up company information' },\n { type: 'action' as const, name: 'enrich_contact', description: 'Enrich contact information' },\n { type: 'action' as const, name: 'validate_email', description: 'Validate email address' },\n ],\n\n knowledge: {\n topics: ['lead_enrichment', 'company_data'],\n indexes: ['sales_knowledge'],\n },\n\n triggers: [\n { type: 'object_create', objectName: 'lead' },\n ],\n\n schedule: { type: 'cron', expression: '0 */4 * * *', timezone: 'UTC' },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Revenue Intelligence Agent \u2014 analyzes pipeline and provides revenue insights */\nexport const RevenueIntelligenceAgent = {\n name: 'revenue_intelligence',\n label: 'Revenue Intelligence Agent',\n role: 'analyst',\n\n instructions: `You are a revenue intelligence AI that analyzes sales data and provides insights.\n\nYour responsibilities:\n1. Analyze pipeline health and quality\n2. Identify at-risk deals\n3. Forecast revenue with confidence intervals\n4. Detect anomalies and trends\n5. Suggest coaching opportunities\n6. Generate executive summaries\n\nUse statistical analysis and machine learning to provide data-driven insights.`,\n\n model: { provider: 'openai', model: 'gpt-4', temperature: 0.2, maxTokens: 3000 },\n\n tools: [\n { type: 'query' as const, name: 'analyze_pipeline', description: 'Analyze sales pipeline health' },\n { type: 'query' as const, name: 'identify_at_risk', description: 'Identify at-risk opportunities' },\n { type: 'query' as const, name: 'forecast_revenue', description: 'Generate revenue forecast' },\n ],\n\n knowledge: {\n topics: ['pipeline_analytics', 'revenue_forecasting', 'deal_risk'],\n indexes: ['sales_knowledge'],\n },\n\n schedule: { type: 'cron', expression: '0 8 * * 1', timezone: 'America/Los_Angeles' },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Sales Assistant \u2014 helps reps with lead qualification and opportunity management */\nexport const SalesAssistantAgent = {\n name: 'sales_assistant',\n label: 'Sales Assistant',\n role: 'assistant',\n\n instructions: `You are a sales assistant AI helping sales representatives manage their pipeline.\n\nYour responsibilities:\n1. Qualify incoming leads based on BANT criteria (Budget, Authority, Need, Timeline)\n2. Suggest next best actions for opportunities\n3. Draft personalized email templates\n4. Analyze win/loss patterns\n5. Provide competitive intelligence\n6. Generate sales forecasts\n\nAlways be professional, data-driven, and focused on helping close deals.`,\n\n model: { provider: 'openai', model: 'gpt-4', temperature: 0.7, maxTokens: 2000 },\n\n tools: [\n { type: 'action' as const, name: 'analyze_lead', description: 'Analyze a lead and provide qualification score' },\n { type: 'action' as const, name: 'suggest_next_action', description: 'Suggest next best action for an opportunity' },\n { type: 'action' as const, name: 'generate_email', description: 'Generate a personalized email template' },\n ],\n\n knowledge: {\n topics: ['sales_playbook', 'product_catalog', 'lead_qualification'],\n indexes: ['sales_knowledge'],\n },\n\n triggers: [\n { type: 'object_create', objectName: 'lead', condition: 'rating = \"hot\"' },\n { type: 'object_update', objectName: 'opportunity', condition: 'ISCHANGED(stage)' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Customer Service Agent \u2014 assists with case triage and resolution */\nexport const ServiceAgent = {\n name: 'service_agent',\n label: 'Customer Service Agent',\n role: 'assistant',\n\n instructions: `You are a customer service AI agent helping support representatives resolve customer issues.\n\nYour responsibilities:\n1. Triage incoming cases based on priority and category\n2. Suggest relevant knowledge articles\n3. Draft response templates\n4. Escalate critical issues\n5. Identify common problems and patterns\n6. Recommend process improvements\n\nAlways be empathetic, solution-focused, and customer-centric.`,\n\n model: { provider: 'openai', model: 'gpt-4', temperature: 0.5, maxTokens: 1500 },\n\n tools: [\n { type: 'action' as const, name: 'triage_case', description: 'Analyze case and assign priority' },\n { type: 'vector_search' as const, name: 'search_knowledge', description: 'Search knowledge base for solutions' },\n { type: 'action' as const, name: 'generate_response', description: 'Generate customer response' },\n ],\n\n knowledge: {\n topics: ['support_kb', 'sla_policies', 'case_resolution'],\n indexes: ['support_knowledge'],\n },\n\n triggers: [\n { type: 'object_create', objectName: 'case' },\n { type: 'object_update', objectName: 'case', condition: 'priority = \"critical\"' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Agent } from '@objectstack/spec/ai';\n\n/**\n * Agent Definitions Barrel\n */\nexport { EmailCampaignAgent } from './email-campaign.agent';\nexport { LeadEnrichmentAgent } from './lead-enrichment.agent';\nexport { RevenueIntelligenceAgent } from './revenue-intelligence.agent';\nexport { SalesAssistantAgent } from './sales.agent';\nexport { ServiceAgent } from './service.agent';\n\nimport { EmailCampaignAgent } from './email-campaign.agent';\nimport { LeadEnrichmentAgent } from './lead-enrichment.agent';\nimport { RevenueIntelligenceAgent } from './revenue-intelligence.agent';\nimport { SalesAssistantAgent } from './sales.agent';\nimport { ServiceAgent } from './service.agent';\n\n/** All agent definitions as a typed array for defineStack() */\nexport const allAgents: Agent[] = [\n EmailCampaignAgent,\n LeadEnrichmentAgent,\n RevenueIntelligenceAgent,\n SalesAssistantAgent,\n ServiceAgent,\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * RAG Pipeline Definitions Barrel\n */\nexport { CompetitiveIntelRAG } from './competitive-intel.rag';\nexport { ProductInfoRAG } from './product-info.rag';\nexport { SalesKnowledgeRAG } from './sales-knowledge.rag';\nexport { SupportKnowledgeRAG } from './support-knowledge.rag';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const CompetitiveIntelRAG = {\n name: 'competitive_intel',\n label: 'Competitive Intelligence Pipeline',\n description: 'RAG pipeline for competitive analysis and market insights',\n\n embedding: {\n provider: 'openai',\n model: 'text-embedding-3-large',\n dimensions: 1536,\n },\n\n vectorStore: {\n provider: 'pgvector',\n indexName: 'competitive_index',\n dimensions: 1536,\n metric: 'cosine',\n },\n\n chunking: {\n type: 'semantic',\n maxChunkSize: 1200,\n },\n\n retrieval: {\n type: 'similarity',\n topK: 7,\n scoreThreshold: 0.65,\n },\n\n reranking: {\n enabled: true,\n provider: 'cohere',\n model: 'cohere-rerank',\n topK: 5,\n },\n\n loaders: [\n { type: 'directory', source: '/knowledge/competitive', fileTypes: ['.md'], recursive: true },\n { type: 'directory', source: '/knowledge/market-research', fileTypes: ['.pdf'], recursive: true },\n ],\n\n maxContextTokens: 5000,\n enableCache: true,\n cacheTTL: 1800,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const ProductInfoRAG = {\n name: 'product_info',\n label: 'Product Information Pipeline',\n description: 'RAG pipeline for product catalog and specifications',\n\n embedding: {\n provider: 'openai',\n model: 'text-embedding-3-small',\n dimensions: 768,\n },\n\n vectorStore: {\n provider: 'pgvector',\n indexName: 'product_catalog_index',\n dimensions: 768,\n metric: 'cosine',\n },\n\n chunking: {\n type: 'semantic',\n maxChunkSize: 800,\n },\n\n retrieval: {\n type: 'hybrid',\n topK: 8,\n vectorWeight: 0.6,\n keywordWeight: 0.4,\n },\n\n loaders: [\n { type: 'directory', source: '/knowledge/products', fileTypes: ['.md', '.pdf'], recursive: true },\n ],\n\n maxContextTokens: 2000,\n enableCache: true,\n cacheTTL: 3600,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SalesKnowledgeRAG = {\n name: 'sales_knowledge',\n label: 'Sales Knowledge Pipeline',\n description: 'RAG pipeline for sales team knowledge and best practices',\n\n embedding: {\n provider: 'openai',\n model: 'text-embedding-3-large',\n dimensions: 1536,\n },\n\n vectorStore: {\n provider: 'pgvector',\n indexName: 'sales_playbook_index',\n dimensions: 1536,\n metric: 'cosine',\n },\n\n chunking: {\n type: 'semantic',\n maxChunkSize: 1000,\n },\n\n retrieval: {\n type: 'hybrid',\n topK: 10,\n vectorWeight: 0.7,\n keywordWeight: 0.3,\n },\n\n reranking: {\n enabled: true,\n provider: 'cohere',\n model: 'cohere-rerank',\n topK: 5,\n },\n\n loaders: [\n { type: 'directory', source: '/knowledge/sales', fileTypes: ['.md'], recursive: true },\n { type: 'directory', source: '/knowledge/products', fileTypes: ['.pdf'], recursive: true },\n ],\n\n maxContextTokens: 4000,\n enableCache: true,\n cacheTTL: 3600,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SupportKnowledgeRAG = {\n name: 'support_knowledge',\n label: 'Support Knowledge Pipeline',\n description: 'RAG pipeline for customer support knowledge base',\n\n embedding: {\n provider: 'openai',\n model: 'text-embedding-3-small',\n dimensions: 768,\n },\n\n vectorStore: {\n provider: 'pgvector',\n indexName: 'support_kb_index',\n dimensions: 768,\n metric: 'cosine',\n },\n\n chunking: {\n type: 'fixed',\n chunkSize: 512,\n chunkOverlap: 100,\n unit: 'tokens',\n },\n\n retrieval: {\n type: 'similarity',\n topK: 5,\n scoreThreshold: 0.75,\n },\n\n loaders: [\n { type: 'directory', source: '/knowledge/support', fileTypes: ['.md'], recursive: true },\n ],\n\n maxContextTokens: 3000,\n enableCache: true,\n cacheTTL: 3600,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Profile Definitions Barrel\n */\nexport { MarketingUserProfile } from './marketing-user.profile';\nexport { SalesManagerProfile } from './sales-manager.profile';\nexport { SalesRepProfile } from './sales-rep.profile';\nexport { ServiceAgentProfile } from './service-agent.profile';\nexport { SystemAdminProfile } from './system-admin.profile';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const MarketingUserProfile = {\n name: 'marketing_user',\n label: 'Marketing User',\n isProfile: true,\n objects: {\n lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n account: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n opportunity: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SalesManagerProfile = {\n name: 'sales_manager',\n label: 'Sales Manager',\n isProfile: true,\n objects: {\n lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n contract: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n product: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n case: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SalesRepProfile = {\n name: 'sales_rep',\n label: 'Sales Representative',\n isProfile: true,\n objects: {\n lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n contract: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n product: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n campaign: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n case: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: false, modifyAllRecords: false },\n },\n fields: {\n 'account.annual_revenue': { readable: true, editable: false },\n 'account.description': { readable: true, editable: true },\n 'opportunity.amount': { readable: true, editable: true },\n 'opportunity.probability': { readable: true, editable: true },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const ServiceAgentProfile = {\n name: 'service_agent',\n label: 'Service Agent',\n isProfile: true,\n objects: {\n lead: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n account: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n contact: { allowCreate: false, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n opportunity: { allowCreate: false, allowRead: false, allowEdit: false, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n case: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: false, viewAllRecords: false, modifyAllRecords: false },\n task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: false, modifyAllRecords: false },\n product: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false, viewAllRecords: true, modifyAllRecords: false },\n },\n fields: {\n 'case.is_sla_violated': { readable: true, editable: false },\n 'case.resolution_time_hours': { readable: true, editable: false },\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport const SystemAdminProfile = {\n name: 'system_admin',\n label: 'System Administrator',\n isProfile: true,\n objects: {\n lead: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n account: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n contact: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n opportunity: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n quote: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n contract: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n product: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n campaign: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n case: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n task: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },\n },\n systemPermissions: [\n 'view_setup', 'manage_users', 'customize_application',\n 'view_all_data', 'modify_all_data', 'manage_profiles',\n 'manage_roles', 'manage_sharing',\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * App Definitions Barrel\n */\nexport { CrmApp } from './crm.app';\nexport { CrmAppModern } from './crm_modern.app';\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { App } from '@objectstack/spec/ui';\n\nexport const CrmApp = App.create({\n name: 'crm_enterprise',\n label: 'Enterprise CRM',\n icon: 'briefcase',\n branding: {\n primaryColor: '#4169E1',\n secondaryColor: '#00AA00',\n logo: '/assets/crm-logo.png',\n favicon: '/assets/crm-favicon.ico',\n },\n \n navigation: [\n {\n id: 'group_sales',\n type: 'group',\n label: 'Sales',\n icon: 'chart-line',\n children: [\n { id: 'nav_lead', type: 'object', objectName: 'lead', label: 'Leads', icon: 'user-plus' },\n { id: 'nav_account', type: 'object', objectName: 'account', label: 'Accounts', icon: 'building' },\n { id: 'nav_contact', type: 'object', objectName: 'contact', label: 'Contacts', icon: 'user' },\n { id: 'nav_opportunity', type: 'object', objectName: 'opportunity', label: 'Opportunities', icon: 'bullseye' },\n { id: 'nav_quote', type: 'object', objectName: 'quote', label: 'Quotes', icon: 'file-invoice' },\n { id: 'nav_contract', type: 'object', objectName: 'contract', label: 'Contracts', icon: 'file-signature' },\n { id: 'nav_sales_dashboard', type: 'dashboard', dashboardName: 'sales_dashboard', label: 'Sales Dashboard', icon: 'chart-bar' },\n ]\n },\n {\n id: 'group_service',\n type: 'group',\n label: 'Service',\n icon: 'headset',\n children: [\n { id: 'nav_case', type: 'object', objectName: 'case', label: 'Cases', icon: 'life-ring' },\n { id: 'nav_task', type: 'object', objectName: 'task', label: 'Tasks', icon: 'tasks' },\n { id: 'nav_service_dashboard', type: 'dashboard', dashboardName: 'service_dashboard', label: 'Service Dashboard', icon: 'chart-pie' },\n ]\n },\n {\n id: 'group_marketing',\n type: 'group',\n label: 'Marketing',\n icon: 'megaphone',\n children: [\n { id: 'nav_campaign', type: 'object', objectName: 'campaign', label: 'Campaigns', icon: 'bullhorn' },\n { id: 'nav_lead_marketing', type: 'object', objectName: 'lead', label: 'Leads', icon: 'user-plus' },\n ]\n },\n {\n id: 'group_products',\n type: 'group',\n label: 'Products',\n icon: 'box',\n children: [\n { id: 'nav_product', type: 'object', objectName: 'product', label: 'Products', icon: 'box-open' },\n ]\n },\n {\n id: 'group_analytics',\n type: 'group',\n label: 'Analytics',\n icon: 'chart-area',\n children: [\n { id: 'nav_exec_dashboard', type: 'dashboard', dashboardName: 'executive_dashboard', label: 'Executive Dashboard', icon: 'tachometer-alt' },\n { id: 'nav_analytics_sales_db', type: 'dashboard', dashboardName: 'sales_dashboard', label: 'Sales Analytics', icon: 'chart-line' },\n { id: 'nav_analytics_service_db', type: 'dashboard', dashboardName: 'service_dashboard', label: 'Service Analytics', icon: 'chart-pie' },\n ]\n }\n ]\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { defineApp } from '@objectstack/spec/ui';\n\n/**\n * CRM App with full navigation tree\n * \n * Demonstrates:\n * - Unlimited nesting depth via `type: 'group'` items\n * - Pages referenced by name via `type: 'page'` items\n * - Sub-groups within groups (Lead Review nested under Sales Cloud)\n * - Global utility entries (Settings, Help) at sidebar bottom\n */\nexport const CrmApp = defineApp({\n name: 'crm',\n label: 'Sales CRM',\n description: 'Enterprise CRM with nested navigation tree',\n icon: 'briefcase',\n\n branding: {\n primaryColor: '#4169E1',\n logo: '/assets/crm-logo.png',\n favicon: '/assets/crm-favicon.ico',\n },\n\n navigation: [\n // \u2500\u2500 Sales Cloud \u2500\u2500\n {\n id: 'grp_sales',\n type: 'group',\n label: 'Sales Cloud',\n icon: 'briefcase',\n expanded: true,\n children: [\n { id: 'nav_pipeline', type: 'page', label: 'Pipeline', icon: 'columns', pageName: 'page_pipeline' },\n { id: 'nav_accounts', type: 'page', label: 'Accounts', icon: 'building', pageName: 'page_accounts' },\n { id: 'nav_leads', type: 'page', label: 'Leads', icon: 'user-plus', pageName: 'page_leads' },\n // Nested sub-group \u2014 impossible with the old Interface model\n {\n id: 'grp_review',\n type: 'group',\n label: 'Lead Review',\n icon: 'clipboard-check',\n expanded: false,\n children: [\n { id: 'nav_review_queue', type: 'page', label: 'Review Queue', icon: 'check-square', pageName: 'page_review_queue' },\n { id: 'nav_qualified', type: 'page', label: 'Qualified', icon: 'check-circle', pageName: 'page_qualified' },\n ],\n },\n ],\n },\n\n // \u2500\u2500 Analytics \u2500\u2500\n {\n id: 'grp_analytics',\n type: 'group',\n label: 'Analytics',\n icon: 'chart-line',\n expanded: false,\n children: [\n { id: 'nav_overview', type: 'page', label: 'Overview', icon: 'gauge', pageName: 'page_overview' },\n { id: 'nav_pipeline_report', type: 'page', label: 'Pipeline Report', icon: 'chart-bar', pageName: 'page_pipeline_report' },\n ],\n },\n\n // \u2500\u2500 Global Utility \u2500\u2500\n { id: 'nav_settings', type: 'page', label: 'Settings', icon: 'settings', pageName: 'admin_settings' },\n { id: 'nav_help', type: 'url', label: 'Help', icon: 'help-circle', url: 'https://help.example.com', target: '_blank' },\n ],\n\n homePageId: 'nav_pipeline',\n requiredPermissions: ['app.access.crm'],\n isDefault: true,\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Translation Definitions Barrel\n */\nexport { CrmTranslations } from './crm.translation';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * English (en) \u2014 CRM App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n * Each file exports a single `TranslationData` object for its locale.\n */\nexport const en: TranslationData = {\n objects: {\n account: {\n label: 'Account',\n pluralLabel: 'Accounts',\n fields: {\n account_number: { label: 'Account Number' },\n name: { label: 'Account Name', help: 'Legal name of the company or organization' },\n type: {\n label: 'Type',\n options: { prospect: 'Prospect', customer: 'Customer', partner: 'Partner', former: 'Former' },\n },\n industry: {\n label: 'Industry',\n options: {\n technology: 'Technology', finance: 'Finance', healthcare: 'Healthcare',\n retail: 'Retail', manufacturing: 'Manufacturing', education: 'Education',\n },\n },\n annual_revenue: { label: 'Annual Revenue' },\n number_of_employees: { label: 'Number of Employees' },\n phone: { label: 'Phone' },\n website: { label: 'Website' },\n billing_address: { label: 'Billing Address' },\n office_location: { label: 'Office Location' },\n owner: { label: 'Account Owner' },\n parent_account: { label: 'Parent Account' },\n description: { label: 'Description' },\n is_active: { label: 'Active' },\n last_activity_date: { label: 'Last Activity Date' },\n },\n },\n\n contact: {\n label: 'Contact',\n pluralLabel: 'Contacts',\n fields: {\n salutation: { label: 'Salutation' },\n first_name: { label: 'First Name' },\n last_name: { label: 'Last Name' },\n full_name: { label: 'Full Name' },\n account: { label: 'Account' },\n email: { label: 'Email' },\n phone: { label: 'Phone' },\n mobile: { label: 'Mobile' },\n title: { label: 'Title' },\n department: {\n label: 'Department',\n options: {\n Executive: 'Executive', Sales: 'Sales', Marketing: 'Marketing',\n Engineering: 'Engineering', Support: 'Support', Finance: 'Finance',\n HR: 'Human Resources', Operations: 'Operations',\n },\n },\n owner: { label: 'Contact Owner' },\n description: { label: 'Description' },\n is_primary: { label: 'Primary Contact' },\n },\n },\n\n lead: {\n label: 'Lead',\n pluralLabel: 'Leads',\n fields: {\n first_name: { label: 'First Name' },\n last_name: { label: 'Last Name' },\n company: { label: 'Company' },\n title: { label: 'Title' },\n email: { label: 'Email' },\n phone: { label: 'Phone' },\n status: {\n label: 'Status',\n options: {\n new: 'New', contacted: 'Contacted', qualified: 'Qualified',\n unqualified: 'Unqualified', converted: 'Converted',\n },\n },\n lead_source: {\n label: 'Lead Source',\n options: {\n Web: 'Web', Referral: 'Referral', Event: 'Event',\n Partner: 'Partner', Advertisement: 'Advertisement', 'Cold Call': 'Cold Call',\n },\n },\n owner: { label: 'Lead Owner' },\n is_converted: { label: 'Converted' },\n description: { label: 'Description' },\n },\n },\n\n opportunity: {\n label: 'Opportunity',\n pluralLabel: 'Opportunities',\n fields: {\n name: { label: 'Opportunity Name' },\n account: { label: 'Account' },\n primary_contact: { label: 'Primary Contact' },\n owner: { label: 'Opportunity Owner' },\n amount: { label: 'Amount' },\n expected_revenue: { label: 'Expected Revenue' },\n stage: {\n label: 'Stage',\n options: {\n prospecting: 'Prospecting', qualification: 'Qualification',\n needs_analysis: 'Needs Analysis', proposal: 'Proposal',\n negotiation: 'Negotiation', closed_won: 'Closed Won', closed_lost: 'Closed Lost',\n },\n },\n probability: { label: 'Probability (%)' },\n close_date: { label: 'Close Date' },\n type: {\n label: 'Type',\n options: {\n 'New Business': 'New Business',\n 'Existing Customer - Upgrade': 'Existing Customer - Upgrade',\n 'Existing Customer - Renewal': 'Existing Customer - Renewal',\n 'Existing Customer - Expansion': 'Existing Customer - Expansion',\n },\n },\n forecast_category: {\n label: 'Forecast Category',\n options: {\n Pipeline: 'Pipeline', 'Best Case': 'Best Case',\n Commit: 'Commit', Omitted: 'Omitted', Closed: 'Closed',\n },\n },\n description: { label: 'Description' },\n next_step: { label: 'Next Step' },\n },\n },\n },\n\n apps: {\n crm_enterprise: {\n label: 'Enterprise CRM',\n description: 'Customer relationship management for sales, service, and marketing',\n },\n },\n\n messages: {\n 'common.save': 'Save',\n 'common.cancel': 'Cancel',\n 'common.delete': 'Delete',\n 'common.edit': 'Edit',\n 'common.create': 'Create',\n 'common.search': 'Search',\n 'common.filter': 'Filter',\n 'common.export': 'Export',\n 'common.back': 'Back',\n 'common.confirm': 'Confirm',\n 'nav.sales': 'Sales',\n 'nav.service': 'Service',\n 'nav.marketing': 'Marketing',\n 'nav.products': 'Products',\n 'nav.analytics': 'Analytics',\n 'success.saved': 'Record saved successfully',\n 'success.converted': 'Lead converted successfully',\n 'confirm.delete': 'Are you sure you want to delete this record?',\n 'confirm.convert_lead': 'Convert this lead to account, contact, and opportunity?',\n 'error.required': 'This field is required',\n 'error.load_failed': 'Failed to load data',\n },\n\n validationMessages: {\n amount_required_for_closed: 'Amount is required when stage is Closed Won',\n close_date_required: 'Close date is required for opportunities',\n discount_limit: 'Discount cannot exceed 40%',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * \u7B80\u4F53\u4E2D\u6587 (zh-CN) \u2014 CRM App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const zhCN: TranslationData = {\n objects: {\n account: {\n label: '\u5BA2\u6237',\n pluralLabel: '\u5BA2\u6237',\n fields: {\n account_number: { label: '\u5BA2\u6237\u7F16\u53F7' },\n name: { label: '\u5BA2\u6237\u540D\u79F0', help: '\u516C\u53F8\u6216\u7EC4\u7EC7\u7684\u6CD5\u5B9A\u540D\u79F0' },\n type: {\n label: '\u7C7B\u578B',\n options: { prospect: '\u6F5C\u5728\u5BA2\u6237', customer: '\u6B63\u5F0F\u5BA2\u6237', partner: '\u5408\u4F5C\u4F19\u4F34', former: '\u524D\u5BA2\u6237' },\n },\n industry: {\n label: '\u884C\u4E1A',\n options: {\n technology: '\u79D1\u6280', finance: '\u91D1\u878D', healthcare: '\u533B\u7597',\n retail: '\u96F6\u552E', manufacturing: '\u5236\u9020', education: '\u6559\u80B2',\n },\n },\n annual_revenue: { label: '\u5E74\u8425\u6536' },\n number_of_employees: { label: '\u5458\u5DE5\u4EBA\u6570' },\n phone: { label: '\u7535\u8BDD' },\n website: { label: '\u7F51\u7AD9' },\n billing_address: { label: '\u8D26\u5355\u5730\u5740' },\n office_location: { label: '\u529E\u516C\u5730\u70B9' },\n owner: { label: '\u5BA2\u6237\u8D1F\u8D23\u4EBA' },\n parent_account: { label: '\u6BCD\u516C\u53F8' },\n description: { label: '\u63CF\u8FF0' },\n is_active: { label: '\u662F\u5426\u6D3B\u8DC3' },\n last_activity_date: { label: '\u6700\u8FD1\u6D3B\u52A8\u65E5\u671F' },\n },\n },\n\n contact: {\n label: '\u8054\u7CFB\u4EBA',\n pluralLabel: '\u8054\u7CFB\u4EBA',\n fields: {\n salutation: { label: '\u79F0\u8C13' },\n first_name: { label: '\u540D' },\n last_name: { label: '\u59D3' },\n full_name: { label: '\u5168\u540D' },\n account: { label: '\u6240\u5C5E\u5BA2\u6237' },\n email: { label: '\u90AE\u7BB1' },\n phone: { label: '\u7535\u8BDD' },\n mobile: { label: '\u624B\u673A' },\n title: { label: '\u804C\u4F4D' },\n department: {\n label: '\u90E8\u95E8',\n options: {\n Executive: '\u7BA1\u7406\u5C42', Sales: '\u9500\u552E\u90E8', Marketing: '\u5E02\u573A\u90E8',\n Engineering: '\u5DE5\u7A0B\u90E8', Support: '\u652F\u6301\u90E8', Finance: '\u8D22\u52A1\u90E8',\n HR: '\u4EBA\u529B\u8D44\u6E90', Operations: '\u8FD0\u8425\u90E8',\n },\n },\n owner: { label: '\u8054\u7CFB\u4EBA\u8D1F\u8D23\u4EBA' },\n description: { label: '\u63CF\u8FF0' },\n is_primary: { label: '\u4E3B\u8981\u8054\u7CFB\u4EBA' },\n },\n },\n\n lead: {\n label: '\u7EBF\u7D22',\n pluralLabel: '\u7EBF\u7D22',\n fields: {\n first_name: { label: '\u540D' },\n last_name: { label: '\u59D3' },\n company: { label: '\u516C\u53F8' },\n title: { label: '\u804C\u4F4D' },\n email: { label: '\u90AE\u7BB1' },\n phone: { label: '\u7535\u8BDD' },\n status: {\n label: '\u72B6\u6001',\n options: {\n new: '\u65B0\u5EFA', contacted: '\u5DF2\u8054\u7CFB', qualified: '\u5DF2\u786E\u8BA4',\n unqualified: '\u4E0D\u5408\u683C', converted: '\u5DF2\u8F6C\u5316',\n },\n },\n lead_source: {\n label: '\u7EBF\u7D22\u6765\u6E90',\n options: {\n Web: '\u7F51\u7AD9', Referral: '\u63A8\u8350', Event: '\u6D3B\u52A8',\n Partner: '\u5408\u4F5C\u4F19\u4F34', Advertisement: '\u5E7F\u544A', 'Cold Call': '\u964C\u751F\u62DC\u8BBF',\n },\n },\n owner: { label: '\u7EBF\u7D22\u8D1F\u8D23\u4EBA' },\n is_converted: { label: '\u5DF2\u8F6C\u5316' },\n description: { label: '\u63CF\u8FF0' },\n },\n },\n\n opportunity: {\n label: '\u5546\u673A',\n pluralLabel: '\u5546\u673A',\n fields: {\n name: { label: '\u5546\u673A\u540D\u79F0' },\n account: { label: '\u6240\u5C5E\u5BA2\u6237' },\n primary_contact: { label: '\u4E3B\u8981\u8054\u7CFB\u4EBA' },\n owner: { label: '\u5546\u673A\u8D1F\u8D23\u4EBA' },\n amount: { label: '\u91D1\u989D' },\n expected_revenue: { label: '\u9884\u671F\u6536\u5165' },\n stage: {\n label: '\u9636\u6BB5',\n options: {\n prospecting: '\u5BFB\u627E\u5BA2\u6237', qualification: '\u8D44\u683C\u5BA1\u67E5',\n needs_analysis: '\u9700\u6C42\u5206\u6790', proposal: '\u63D0\u6848',\n negotiation: '\u8C08\u5224', closed_won: '\u6210\u4EA4', closed_lost: '\u5931\u8D25',\n },\n },\n probability: { label: '\u6210\u4EA4\u6982\u7387 (%)' },\n close_date: { label: '\u9884\u8BA1\u6210\u4EA4\u65E5\u671F' },\n type: {\n label: '\u7C7B\u578B',\n options: {\n 'New Business': '\u65B0\u4E1A\u52A1',\n 'Existing Customer - Upgrade': '\u8001\u5BA2\u6237\u5347\u7EA7',\n 'Existing Customer - Renewal': '\u8001\u5BA2\u6237\u7EED\u7EA6',\n 'Existing Customer - Expansion': '\u8001\u5BA2\u6237\u62D3\u5C55',\n },\n },\n forecast_category: {\n label: '\u9884\u6D4B\u7C7B\u522B',\n options: {\n Pipeline: '\u7BA1\u9053', 'Best Case': '\u6700\u4F73\u60C5\u51B5',\n Commit: '\u627F\u8BFA', Omitted: '\u5DF2\u6392\u9664', Closed: '\u5DF2\u5173\u95ED',\n },\n },\n description: { label: '\u63CF\u8FF0' },\n next_step: { label: '\u4E0B\u4E00\u6B65' },\n },\n },\n },\n\n apps: {\n crm_enterprise: {\n label: '\u4F01\u4E1A CRM',\n description: '\u6DB5\u76D6\u9500\u552E\u3001\u670D\u52A1\u548C\u5E02\u573A\u8425\u9500\u7684\u5BA2\u6237\u5173\u7CFB\u7BA1\u7406\u7CFB\u7EDF',\n },\n },\n\n messages: {\n 'common.save': '\u4FDD\u5B58',\n 'common.cancel': '\u53D6\u6D88',\n 'common.delete': '\u5220\u9664',\n 'common.edit': '\u7F16\u8F91',\n 'common.create': '\u65B0\u5EFA',\n 'common.search': '\u641C\u7D22',\n 'common.filter': '\u7B5B\u9009',\n 'common.export': '\u5BFC\u51FA',\n 'common.back': '\u8FD4\u56DE',\n 'common.confirm': '\u786E\u8BA4',\n 'nav.sales': '\u9500\u552E',\n 'nav.service': '\u670D\u52A1',\n 'nav.marketing': '\u8425\u9500',\n 'nav.products': '\u4EA7\u54C1',\n 'nav.analytics': '\u6570\u636E\u5206\u6790',\n 'success.saved': '\u8BB0\u5F55\u4FDD\u5B58\u6210\u529F',\n 'success.converted': '\u7EBF\u7D22\u8F6C\u5316\u6210\u529F',\n 'confirm.delete': '\u786E\u5B9A\u8981\u5220\u9664\u6B64\u8BB0\u5F55\u5417\uFF1F',\n 'confirm.convert_lead': '\u5C06\u6B64\u7EBF\u7D22\u8F6C\u5316\u4E3A\u5BA2\u6237\u3001\u8054\u7CFB\u4EBA\u548C\u5546\u673A\uFF1F',\n 'error.required': '\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879',\n 'error.load_failed': '\u6570\u636E\u52A0\u8F7D\u5931\u8D25',\n },\n\n validationMessages: {\n amount_required_for_closed: '\u9636\u6BB5\u4E3A\"\u6210\u4EA4\"\u65F6\uFF0C\u91D1\u989D\u4E3A\u5FC5\u586B\u9879',\n close_date_required: '\u5546\u673A\u5FC5\u987B\u586B\u5199\u9884\u8BA1\u6210\u4EA4\u65E5\u671F',\n discount_limit: '\u6298\u6263\u4E0D\u80FD\u8D85\u8FC740%',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * \u65E5\u672C\u8A9E (ja-JP) \u2014 CRM App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const jaJP: TranslationData = {\n objects: {\n account: {\n label: '\u53D6\u5F15\u5148',\n pluralLabel: '\u53D6\u5F15\u5148',\n fields: {\n account_number: { label: '\u53D6\u5F15\u5148\u756A\u53F7' },\n name: { label: '\u53D6\u5F15\u5148\u540D', help: '\u4F1A\u793E\u307E\u305F\u306F\u7D44\u7E54\u306E\u6B63\u5F0F\u540D\u79F0' },\n type: {\n label: '\u30BF\u30A4\u30D7',\n options: { prospect: '\u898B\u8FBC\u307F\u5BA2', customer: '\u9867\u5BA2', partner: '\u30D1\u30FC\u30C8\u30CA\u30FC', former: '\u904E\u53BB\u306E\u53D6\u5F15\u5148' },\n },\n industry: {\n label: '\u696D\u7A2E',\n options: {\n technology: '\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC', finance: '\u91D1\u878D', healthcare: '\u30D8\u30EB\u30B9\u30B1\u30A2',\n retail: '\u5C0F\u58F2', manufacturing: '\u88FD\u9020', education: '\u6559\u80B2',\n },\n },\n annual_revenue: { label: '\u5E74\u9593\u58F2\u4E0A' },\n number_of_employees: { label: '\u5F93\u696D\u54E1\u6570' },\n phone: { label: '\u96FB\u8A71\u756A\u53F7' },\n website: { label: 'Web\u30B5\u30A4\u30C8' },\n billing_address: { label: '\u8ACB\u6C42\u5148\u4F4F\u6240' },\n office_location: { label: '\u30AA\u30D5\u30A3\u30B9\u6240\u5728\u5730' },\n owner: { label: '\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005' },\n parent_account: { label: '\u89AA\u53D6\u5F15\u5148' },\n description: { label: '\u8AAC\u660E' },\n is_active: { label: '\u6709\u52B9' },\n last_activity_date: { label: '\u6700\u7D42\u6D3B\u52D5\u65E5' },\n },\n },\n\n contact: {\n label: '\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005',\n pluralLabel: '\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005',\n fields: {\n salutation: { label: '\u656C\u79F0' },\n first_name: { label: '\u540D' },\n last_name: { label: '\u59D3' },\n full_name: { label: '\u6C0F\u540D' },\n account: { label: '\u53D6\u5F15\u5148' },\n email: { label: '\u30E1\u30FC\u30EB' },\n phone: { label: '\u96FB\u8A71' },\n mobile: { label: '\u643A\u5E2F\u96FB\u8A71' },\n title: { label: '\u5F79\u8077' },\n department: {\n label: '\u90E8\u9580',\n options: {\n Executive: '\u7D4C\u55B6\u5C64', Sales: '\u55B6\u696D\u90E8', Marketing: '\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u90E8',\n Engineering: '\u30A8\u30F3\u30B8\u30CB\u30A2\u30EA\u30F3\u30B0\u90E8', Support: '\u30B5\u30DD\u30FC\u30C8\u90E8', Finance: '\u7D4C\u7406\u90E8',\n HR: '\u4EBA\u4E8B\u90E8', Operations: '\u30AA\u30DA\u30EC\u30FC\u30B7\u30E7\u30F3\u90E8',\n },\n },\n owner: { label: '\u6240\u6709\u8005' },\n description: { label: '\u8AAC\u660E' },\n is_primary: { label: '\u4E3B\u62C5\u5F53\u8005' },\n },\n },\n\n lead: {\n label: '\u30EA\u30FC\u30C9',\n pluralLabel: '\u30EA\u30FC\u30C9',\n fields: {\n first_name: { label: '\u540D' },\n last_name: { label: '\u59D3' },\n company: { label: '\u4F1A\u793E\u540D' },\n title: { label: '\u5F79\u8077' },\n email: { label: '\u30E1\u30FC\u30EB' },\n phone: { label: '\u96FB\u8A71' },\n status: {\n label: '\u30B9\u30C6\u30FC\u30BF\u30B9',\n options: {\n new: '\u65B0\u898F', contacted: '\u30B3\u30F3\u30BF\u30AF\u30C8\u6E08\u307F', qualified: '\u9069\u683C',\n unqualified: '\u4E0D\u9069\u683C', converted: '\u53D6\u5F15\u958B\u59CB\u6E08\u307F',\n },\n },\n lead_source: {\n label: '\u30EA\u30FC\u30C9\u30BD\u30FC\u30B9',\n options: {\n Web: 'Web', Referral: '\u7D39\u4ECB', Event: '\u30A4\u30D9\u30F3\u30C8',\n Partner: '\u30D1\u30FC\u30C8\u30CA\u30FC', Advertisement: '\u5E83\u544A', 'Cold Call': '\u30B3\u30FC\u30EB\u30C9\u30B3\u30FC\u30EB',\n },\n },\n owner: { label: '\u30EA\u30FC\u30C9\u6240\u6709\u8005' },\n is_converted: { label: '\u53D6\u5F15\u958B\u59CB\u6E08\u307F' },\n description: { label: '\u8AAC\u660E' },\n },\n },\n\n opportunity: {\n label: '\u5546\u8AC7',\n pluralLabel: '\u5546\u8AC7',\n fields: {\n name: { label: '\u5546\u8AC7\u540D' },\n account: { label: '\u53D6\u5F15\u5148' },\n primary_contact: { label: '\u4E3B\u62C5\u5F53\u8005' },\n owner: { label: '\u5546\u8AC7\u6240\u6709\u8005' },\n amount: { label: '\u91D1\u984D' },\n expected_revenue: { label: '\u671F\u5F85\u53CE\u76CA' },\n stage: {\n label: '\u30D5\u30A7\u30FC\u30BA',\n options: {\n prospecting: '\u898B\u8FBC\u307F\u8ABF\u67FB', qualification: '\u9078\u5B9A',\n needs_analysis: '\u30CB\u30FC\u30BA\u5206\u6790', proposal: '\u63D0\u6848',\n negotiation: '\u4EA4\u6E09', closed_won: '\u6210\u7ACB', closed_lost: '\u4E0D\u6210\u7ACB',\n },\n },\n probability: { label: '\u78BA\u5EA6 (%)' },\n close_date: { label: '\u5B8C\u4E86\u4E88\u5B9A\u65E5' },\n type: {\n label: '\u30BF\u30A4\u30D7',\n options: {\n 'New Business': '\u65B0\u898F\u30D3\u30B8\u30CD\u30B9',\n 'Existing Customer - Upgrade': '\u65E2\u5B58\u9867\u5BA2 - \u30A2\u30C3\u30D7\u30B0\u30EC\u30FC\u30C9',\n 'Existing Customer - Renewal': '\u65E2\u5B58\u9867\u5BA2 - \u66F4\u65B0',\n 'Existing Customer - Expansion': '\u65E2\u5B58\u9867\u5BA2 - \u62E1\u5927',\n },\n },\n forecast_category: {\n label: '\u58F2\u4E0A\u4E88\u6E2C\u30AB\u30C6\u30B4\u30EA',\n options: {\n Pipeline: '\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3', 'Best Case': '\u6700\u826F\u30B1\u30FC\u30B9',\n Commit: '\u30B3\u30DF\u30C3\u30C8', Omitted: '\u9664\u5916', Closed: '\u5B8C\u4E86',\n },\n },\n description: { label: '\u8AAC\u660E' },\n next_step: { label: '\u6B21\u306E\u30B9\u30C6\u30C3\u30D7' },\n },\n },\n },\n\n apps: {\n crm_enterprise: {\n label: '\u30A8\u30F3\u30BF\u30FC\u30D7\u30E9\u30A4\u30BA CRM',\n description: '\u55B6\u696D\u30FB\u30B5\u30FC\u30D3\u30B9\u30FB\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u5411\u3051\u9867\u5BA2\u95A2\u4FC2\u7BA1\u7406\u30B7\u30B9\u30C6\u30E0',\n },\n },\n\n messages: {\n 'common.save': '\u4FDD\u5B58',\n 'common.cancel': '\u30AD\u30E3\u30F3\u30BB\u30EB',\n 'common.delete': '\u524A\u9664',\n 'common.edit': '\u7DE8\u96C6',\n 'common.create': '\u65B0\u898F\u4F5C\u6210',\n 'common.search': '\u691C\u7D22',\n 'common.filter': '\u30D5\u30A3\u30EB\u30BF\u30FC',\n 'common.export': '\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8',\n 'common.back': '\u623B\u308B',\n 'common.confirm': '\u78BA\u8A8D',\n 'nav.sales': '\u55B6\u696D',\n 'nav.service': '\u30B5\u30FC\u30D3\u30B9',\n 'nav.marketing': '\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0',\n 'nav.products': '\u88FD\u54C1',\n 'nav.analytics': '\u30A2\u30CA\u30EA\u30C6\u30A3\u30AF\u30B9',\n 'success.saved': '\u30EC\u30B3\u30FC\u30C9\u3092\u4FDD\u5B58\u3057\u307E\u3057\u305F',\n 'success.converted': '\u30EA\u30FC\u30C9\u3092\u53D6\u5F15\u958B\u59CB\u3057\u307E\u3057\u305F',\n 'confirm.delete': '\u3053\u306E\u30EC\u30B3\u30FC\u30C9\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F',\n 'confirm.convert_lead': '\u3053\u306E\u30EA\u30FC\u30C9\u3092\u53D6\u5F15\u5148\u30FB\u53D6\u5F15\u5148\u8CAC\u4EFB\u8005\u30FB\u5546\u8AC7\u306B\u5909\u63DB\u3057\u307E\u3059\u304B\uFF1F',\n 'error.required': '\u3053\u306E\u9805\u76EE\u306F\u5FC5\u9808\u3067\u3059',\n 'error.load_failed': '\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F',\n },\n\n validationMessages: {\n amount_required_for_closed: '\u30D5\u30A7\u30FC\u30BA\u304C\u300C\u6210\u7ACB\u300D\u306E\u5834\u5408\u3001\u91D1\u984D\u306F\u5FC5\u9808\u3067\u3059',\n close_date_required: '\u5546\u8AC7\u306B\u306F\u5B8C\u4E86\u4E88\u5B9A\u65E5\u304C\u5FC5\u8981\u3067\u3059',\n discount_limit: '\u5272\u5F15\u306F40%\u3092\u8D85\u3048\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * Espa\u00F1ol (es-ES) \u2014 CRM App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const esES: TranslationData = {\n objects: {\n account: {\n label: 'Cuenta',\n pluralLabel: 'Cuentas',\n fields: {\n account_number: { label: 'N\u00FAmero de Cuenta' },\n name: { label: 'Nombre de Cuenta', help: 'Nombre legal de la empresa u organizaci\u00F3n' },\n type: {\n label: 'Tipo',\n options: { prospect: 'Prospecto', customer: 'Cliente', partner: 'Socio', former: 'Anterior' },\n },\n industry: {\n label: 'Industria',\n options: {\n technology: 'Tecnolog\u00EDa', finance: 'Finanzas', healthcare: 'Salud',\n retail: 'Comercio', manufacturing: 'Manufactura', education: 'Educaci\u00F3n',\n },\n },\n annual_revenue: { label: 'Ingresos Anuales' },\n number_of_employees: { label: 'N\u00FAmero de Empleados' },\n phone: { label: 'Tel\u00E9fono' },\n website: { label: 'Sitio Web' },\n billing_address: { label: 'Direcci\u00F3n de Facturaci\u00F3n' },\n office_location: { label: 'Ubicaci\u00F3n de Oficina' },\n owner: { label: 'Propietario de Cuenta' },\n parent_account: { label: 'Cuenta Matriz' },\n description: { label: 'Descripci\u00F3n' },\n is_active: { label: 'Activo' },\n last_activity_date: { label: 'Fecha de \u00DAltima Actividad' },\n },\n },\n\n contact: {\n label: 'Contacto',\n pluralLabel: 'Contactos',\n fields: {\n salutation: { label: 'T\u00EDtulo' },\n first_name: { label: 'Nombre' },\n last_name: { label: 'Apellido' },\n full_name: { label: 'Nombre Completo' },\n account: { label: 'Cuenta' },\n email: { label: 'Correo Electr\u00F3nico' },\n phone: { label: 'Tel\u00E9fono' },\n mobile: { label: 'M\u00F3vil' },\n title: { label: 'Cargo' },\n department: {\n label: 'Departamento',\n options: {\n Executive: 'Ejecutivo', Sales: 'Ventas', Marketing: 'Marketing',\n Engineering: 'Ingenier\u00EDa', Support: 'Soporte', Finance: 'Finanzas',\n HR: 'Recursos Humanos', Operations: 'Operaciones',\n },\n },\n owner: { label: 'Propietario de Contacto' },\n description: { label: 'Descripci\u00F3n' },\n is_primary: { label: 'Contacto Principal' },\n },\n },\n\n lead: {\n label: 'Prospecto',\n pluralLabel: 'Prospectos',\n fields: {\n first_name: { label: 'Nombre' },\n last_name: { label: 'Apellido' },\n company: { label: 'Empresa' },\n title: { label: 'Cargo' },\n email: { label: 'Correo Electr\u00F3nico' },\n phone: { label: 'Tel\u00E9fono' },\n status: {\n label: 'Estado',\n options: {\n new: 'Nuevo', contacted: 'Contactado', qualified: 'Calificado',\n unqualified: 'No Calificado', converted: 'Convertido',\n },\n },\n lead_source: {\n label: 'Origen del Prospecto',\n options: {\n Web: 'Web', Referral: 'Referencia', Event: 'Evento',\n Partner: 'Socio', Advertisement: 'Publicidad', 'Cold Call': 'Llamada en Fr\u00EDo',\n },\n },\n owner: { label: 'Propietario' },\n is_converted: { label: 'Convertido' },\n description: { label: 'Descripci\u00F3n' },\n },\n },\n\n opportunity: {\n label: 'Oportunidad',\n pluralLabel: 'Oportunidades',\n fields: {\n name: { label: 'Nombre de Oportunidad' },\n account: { label: 'Cuenta' },\n primary_contact: { label: 'Contacto Principal' },\n owner: { label: 'Propietario de Oportunidad' },\n amount: { label: 'Monto' },\n expected_revenue: { label: 'Ingreso Esperado' },\n stage: {\n label: 'Etapa',\n options: {\n prospecting: 'Prospecci\u00F3n', qualification: 'Calificaci\u00F3n',\n needs_analysis: 'An\u00E1lisis de Necesidades', proposal: 'Propuesta',\n negotiation: 'Negociaci\u00F3n', closed_won: 'Cerrada Ganada', closed_lost: 'Cerrada Perdida',\n },\n },\n probability: { label: 'Probabilidad (%)' },\n close_date: { label: 'Fecha de Cierre' },\n type: {\n label: 'Tipo',\n options: {\n 'New Business': 'Nuevo Negocio',\n 'Existing Customer - Upgrade': 'Cliente Existente - Mejora',\n 'Existing Customer - Renewal': 'Cliente Existente - Renovaci\u00F3n',\n 'Existing Customer - Expansion': 'Cliente Existente - Expansi\u00F3n',\n },\n },\n forecast_category: {\n label: 'Categor\u00EDa de Pron\u00F3stico',\n options: {\n Pipeline: 'Pipeline', 'Best Case': 'Mejor Caso',\n Commit: 'Compromiso', Omitted: 'Omitida', Closed: 'Cerrada',\n },\n },\n description: { label: 'Descripci\u00F3n' },\n next_step: { label: 'Pr\u00F3ximo Paso' },\n },\n },\n },\n\n apps: {\n crm_enterprise: {\n label: 'CRM Empresarial',\n description: 'Gesti\u00F3n de relaciones con clientes para ventas, servicio y marketing',\n },\n },\n\n messages: {\n 'common.save': 'Guardar',\n 'common.cancel': 'Cancelar',\n 'common.delete': 'Eliminar',\n 'common.edit': 'Editar',\n 'common.create': 'Crear',\n 'common.search': 'Buscar',\n 'common.filter': 'Filtrar',\n 'common.export': 'Exportar',\n 'common.back': 'Volver',\n 'common.confirm': 'Confirmar',\n 'nav.sales': 'Ventas',\n 'nav.service': 'Servicio',\n 'nav.marketing': 'Marketing',\n 'nav.products': 'Productos',\n 'nav.analytics': 'Anal\u00EDtica',\n 'success.saved': 'Registro guardado exitosamente',\n 'success.converted': 'Prospecto convertido exitosamente',\n 'confirm.delete': '\u00BFEst\u00E1 seguro de que desea eliminar este registro?',\n 'confirm.convert_lead': '\u00BFConvertir este prospecto en cuenta, contacto y oportunidad?',\n 'error.required': 'Este campo es obligatorio',\n 'error.load_failed': 'Error al cargar los datos',\n },\n\n validationMessages: {\n amount_required_for_closed: 'El monto es obligatorio cuando la etapa es Cerrada Ganada',\n close_date_required: 'La fecha de cierre es obligatoria para las oportunidades',\n discount_limit: 'El descuento no puede superar el 40%',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationBundle } from '@objectstack/spec/system';\nimport { en } from './en';\nimport { zhCN } from './zh-CN';\nimport { jaJP } from './ja-JP';\nimport { esES } from './es-ES';\n\n/**\n * CRM App \u2014 Internationalization (i18n)\n *\n * Demonstrates **per-locale file splitting** convention:\n * each language is defined in its own file (`en.ts`, `zh-CN.ts`, `ja-JP.ts`, `es-ES.ts`)\n * and assembled into a single `TranslationBundle` here.\n *\n * Enterprise-grade multi-language translations covering:\n * - Core CRM objects: Account, Contact, Lead, Opportunity\n * - Select-field option labels for each object\n * - App & navigation group labels\n * - Common UI messages, validation messages\n *\n * Supported locales: en, zh-CN, ja-JP, es-ES\n */\nexport const CrmTranslations: TranslationBundle = {\n en,\n 'zh-CN': zhCN,\n 'ja-JP': jaJP,\n 'es-ES': esES,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * CRM Seed Data\n * \n * Demo records for all core CRM objects.\n * Uses the DatasetSchema format with upsert mode for idempotent loading.\n */\nimport type { DatasetInput } from '@objectstack/spec/data';\n\n// \u2500\u2500\u2500 Accounts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst accounts: DatasetInput = {\n object: 'account',\n mode: 'upsert',\n externalId: 'name',\n records: [\n {\n name: 'Acme Corporation',\n type: 'customer',\n industry: 'technology',\n annual_revenue: 5000000,\n number_of_employees: 250,\n phone: '+1-415-555-0100',\n website: 'https://acme.example.com',\n },\n {\n name: 'Globex Industries',\n type: 'prospect',\n industry: 'manufacturing',\n annual_revenue: 12000000,\n number_of_employees: 800,\n phone: '+1-312-555-0200',\n website: 'https://globex.example.com',\n },\n {\n name: 'Initech Solutions',\n type: 'customer',\n industry: 'finance',\n annual_revenue: 3500000,\n number_of_employees: 150,\n phone: '+1-212-555-0300',\n website: 'https://initech.example.com',\n },\n {\n name: 'Stark Medical',\n type: 'partner',\n industry: 'healthcare',\n annual_revenue: 8000000,\n number_of_employees: 400,\n phone: '+1-617-555-0400',\n website: 'https://starkmed.example.com',\n },\n {\n name: 'Wayne Enterprises',\n type: 'customer',\n industry: 'technology',\n annual_revenue: 25000000,\n number_of_employees: 2000,\n phone: '+1-650-555-0500',\n website: 'https://wayne.example.com',\n },\n ]\n};\n\n// \u2500\u2500\u2500 Contacts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst contacts: DatasetInput = {\n object: 'contact',\n mode: 'upsert',\n externalId: 'email',\n records: [\n {\n salutation: 'Mr.',\n first_name: 'John',\n last_name: 'Smith',\n email: 'john.smith@acme.example.com',\n phone: '+1-415-555-0101',\n title: 'VP of Engineering',\n department: 'Engineering',\n },\n {\n salutation: 'Ms.',\n first_name: 'Sarah',\n last_name: 'Johnson',\n email: 'sarah.j@globex.example.com',\n phone: '+1-312-555-0201',\n title: 'Chief Procurement Officer',\n department: 'Executive',\n },\n {\n salutation: 'Dr.',\n first_name: 'Michael',\n last_name: 'Chen',\n email: 'mchen@initech.example.com',\n phone: '+1-212-555-0301',\n title: 'Director of Operations',\n department: 'Operations',\n },\n {\n salutation: 'Ms.',\n first_name: 'Emily',\n last_name: 'Davis',\n email: 'emily.d@starkmed.example.com',\n phone: '+1-617-555-0401',\n title: 'Head of Partnerships',\n department: 'Sales',\n },\n {\n salutation: 'Mr.',\n first_name: 'Robert',\n last_name: 'Wilson',\n email: 'rwilson@wayne.example.com',\n phone: '+1-650-555-0501',\n title: 'CTO',\n department: 'Engineering',\n },\n ]\n};\n\n// \u2500\u2500\u2500 Leads \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst leads: DatasetInput = {\n object: 'lead',\n mode: 'upsert',\n externalId: 'email',\n records: [\n {\n first_name: 'Alice',\n last_name: 'Martinez',\n company: 'NextGen Retail',\n email: 'alice@nextgenretail.example.com',\n phone: '+1-503-555-0600',\n status: 'new',\n source: 'website',\n industry: 'Retail',\n },\n {\n first_name: 'David',\n last_name: 'Kim',\n company: 'EduTech Labs',\n email: 'dkim@edutechlabs.example.com',\n phone: '+1-408-555-0700',\n status: 'contacted',\n source: 'referral',\n industry: 'Education',\n },\n {\n first_name: 'Lisa',\n last_name: 'Thompson',\n company: 'CloudFirst Inc',\n email: 'lisa.t@cloudfirst.example.com',\n phone: '+1-206-555-0800',\n status: 'qualified',\n source: 'trade_show',\n industry: 'Technology',\n },\n ]\n};\n\n// \u2500\u2500\u2500 Opportunities \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst opportunities: DatasetInput = {\n object: 'opportunity',\n mode: 'upsert',\n externalId: 'name',\n records: [\n {\n name: 'Acme Platform Upgrade',\n amount: 150000,\n stage: 'proposal',\n probability: 60,\n close_date: new Date(Date.now() + 86400000 * 30),\n type: 'existing_business',\n forecast_category: 'pipeline',\n },\n {\n name: 'Globex Manufacturing Suite',\n amount: 500000,\n stage: 'qualification',\n probability: 30,\n close_date: new Date(Date.now() + 86400000 * 60),\n type: 'new_business',\n forecast_category: 'pipeline',\n },\n {\n name: 'Wayne Enterprise License',\n amount: 1200000,\n stage: 'negotiation',\n probability: 75,\n close_date: new Date(Date.now() + 86400000 * 14),\n type: 'new_business',\n forecast_category: 'commit',\n },\n {\n name: 'Initech Cloud Migration',\n amount: 80000,\n stage: 'needs_analysis',\n probability: 25,\n close_date: new Date(Date.now() + 86400000 * 45),\n type: 'existing_business',\n forecast_category: 'best_case',\n },\n ]\n};\n\n// \u2500\u2500\u2500 Products \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst products: DatasetInput = {\n object: 'product',\n mode: 'upsert',\n externalId: 'name',\n records: [\n {\n name: 'ObjectStack Platform',\n category: 'software',\n family: 'enterprise',\n list_price: 50000,\n is_active: true,\n },\n {\n name: 'Cloud Hosting (Annual)',\n category: 'subscription',\n family: 'cloud',\n list_price: 12000,\n is_active: true,\n },\n {\n name: 'Premium Support',\n category: 'support',\n family: 'services',\n list_price: 25000,\n is_active: true,\n },\n {\n name: 'Implementation Services',\n category: 'service',\n family: 'services',\n list_price: 75000,\n is_active: true,\n },\n ]\n};\n\n// \u2500\u2500\u2500 Tasks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst tasks: DatasetInput = {\n object: 'task',\n mode: 'upsert',\n externalId: 'subject',\n records: [\n {\n subject: 'Follow up with Acme on proposal',\n status: 'not_started',\n priority: 'high',\n due_date: new Date(Date.now() + 86400000 * 2),\n },\n {\n subject: 'Schedule demo for Globex team',\n status: 'in_progress',\n priority: 'normal',\n due_date: new Date(Date.now() + 86400000 * 5),\n },\n {\n subject: 'Prepare contract for Wayne Enterprises',\n status: 'not_started',\n priority: 'urgent',\n due_date: new Date(Date.now() + 86400000),\n },\n {\n subject: 'Send welcome package to Stark Medical',\n status: 'completed',\n priority: 'low',\n },\n {\n subject: 'Update CRM pipeline report',\n status: 'not_started',\n priority: 'normal',\n due_date: new Date(Date.now() + 86400000 * 7),\n },\n ]\n};\n\n/** All CRM seed datasets */\nexport const CrmSeedData: DatasetInput[] = [\n accounts,\n contacts,\n leads,\n opportunities,\n products,\n tasks,\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Share accounts with sales managers/directors based on customer status */\nexport const AccountTeamSharingRule = {\n name: 'account_team_sharing',\n label: 'Account Team Sharing',\n object: 'account',\n type: 'criteria' as const,\n condition: 'type = \"customer\" AND is_active = true',\n accessLevel: 'edit',\n sharedWith: { type: 'role', value: 'sales_manager' },\n};\n\n/** Territory-Based Sharing (criteria-based, by billing country) */\nexport const TerritorySharingRules = [\n {\n name: 'north_america_territory',\n label: 'North America Territory',\n object: 'account',\n type: 'criteria' as const,\n condition: 'billing_country IN (\"US\", \"CA\", \"MX\")',\n accessLevel: 'edit',\n sharedWith: { type: 'role', value: 'na_sales_team' },\n },\n {\n name: 'europe_territory',\n label: 'Europe Territory',\n object: 'account',\n type: 'criteria' as const,\n condition: 'billing_country IN (\"UK\", \"DE\", \"FR\", \"IT\", \"ES\")',\n accessLevel: 'edit',\n sharedWith: { type: 'role', value: 'eu_sales_team' },\n },\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Share escalated/critical cases with service managers */\nexport const CaseEscalationSharingRule = {\n name: 'case_escalation_sharing',\n label: 'Escalated Cases Sharing',\n object: 'case',\n type: 'criteria' as const,\n condition: 'priority = \"critical\" AND is_closed = false',\n accessLevel: 'edit',\n sharedWith: { type: 'role_and_subordinates', value: 'service_manager' },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** Share high-value open opportunities with management */\nexport const OpportunitySalesSharingRule = {\n name: 'opportunity_sales_sharing',\n label: 'Opportunity Sales Team Sharing',\n object: 'opportunity',\n type: 'criteria' as const,\n condition: 'stage NOT IN (\"closed_won\", \"closed_lost\") AND amount >= 100000',\n accessLevel: 'read',\n sharedWith: { type: 'role_and_subordinates', value: 'sales_director' },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/** CRM Role Hierarchy */\nexport const RoleHierarchy = {\n name: 'crm_role_hierarchy',\n label: 'CRM Role Hierarchy',\n roles: [\n { name: 'executive', label: 'Executive', parentRole: null },\n { name: 'sales_director', label: 'Sales Director', parentRole: 'executive' },\n { name: 'sales_manager', label: 'Sales Manager', parentRole: 'sales_director' },\n { name: 'sales_rep', label: 'Sales Representative', parentRole: 'sales_manager' },\n { name: 'service_director', label: 'Service Director', parentRole: 'executive' },\n { name: 'service_manager', label: 'Service Manager', parentRole: 'service_director' },\n { name: 'service_agent', label: 'Service Agent', parentRole: 'service_manager' },\n { name: 'marketing_director', label: 'Marketing Director', parentRole: 'executive' },\n { name: 'marketing_manager', label: 'Marketing Manager', parentRole: 'marketing_director' },\n { name: 'marketing_user', label: 'Marketing User', parentRole: 'marketing_manager' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { defineStack } from '@objectstack/spec';\n\n// \u2500\u2500\u2500 Barrel Imports (one per metadata type) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nimport * as objects from './src/objects';\nimport * as apis from './src/apis';\nimport * as actions from './src/actions';\nimport * as dashboards from './src/dashboards';\nimport * as reports from './src/reports';\nimport { allFlows } from './src/flows';\nimport { allAgents } from './src/agents';\nimport * as ragPipelines from './src/rag';\nimport * as profiles from './src/profiles';\nimport * as apps from './src/apps';\nimport * as translations from './src/translations';\nimport { CrmSeedData } from './src/data';\n\n// \u2500\u2500\u2500 Sharing & Security (special: mixed single/array values) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\nimport {\n AccountTeamSharingRule, TerritorySharingRules,\n OpportunitySalesSharingRule,\n CaseEscalationSharingRule,\n RoleHierarchy,\n} from './src/sharing';\n\n// \u2500\u2500\u2500 Action Handler Registration (runtime lifecycle) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Handlers are wired separately from metadata. The `onEnable` export\n// is called by the kernel's AppPlugin after the engine is ready.\n// See: src/actions/register-handlers.ts for the full registration flow.\nimport { registerCrmActionHandlers } from './src/actions/register-handlers';\n\n/**\n * Plugin lifecycle hook \u2014 called by AppPlugin when the engine is ready.\n * This is where action handlers are registered on the ObjectQL engine.\n */\nexport const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {\n registerCrmActionHandlers(ctx.ql);\n};\n\nexport default defineStack({\n manifest: {\n id: 'com.example.crm',\n namespace: 'crm',\n version: '3.0.0',\n type: 'app',\n name: 'Enterprise CRM',\n description: 'Comprehensive enterprise CRM demonstrating all ObjectStack Protocol features including AI, security, and automation',\n },\n\n // Auto-collected from barrel index files via Object.values()\n objects: Object.values(objects),\n apis: Object.values(apis),\n actions: Object.values(actions),\n dashboards: Object.values(dashboards),\n reports: Object.values(reports),\n flows: allFlows,\n agents: allAgents,\n ragPipelines: Object.values(ragPipelines),\n permissions: Object.values(profiles),\n apps: Object.values(apps),\n\n // Seed Data (top-level, registered as metadata)\n data: CrmSeedData,\n\n // I18n Configuration \u2014 per-locale file organization\n i18n: {\n defaultLocale: 'en',\n supportedLocales: ['en', 'zh-CN', 'ja-JP', 'es-ES'],\n fallbackLocale: 'en',\n fileOrganization: 'per_locale',\n },\n\n // I18n Translation Bundles (en, zh-CN, ja-JP, es-ES)\n translations: Object.values(translations),\n\n // Sharing & security\n sharingRules: [\n AccountTeamSharingRule,\n OpportunitySalesSharingRule,\n CaseEscalationSharingRule,\n ...TerritorySharingRules,\n ],\n roles: RoleHierarchy.roles.map((r: { name: string; label: string; parentRole: string | null }) => ({\n name: r.name,\n label: r.label,\n parent: r.parentRole ?? undefined,\n })),\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Object Definitions Barrel\n */\nexport { Task } from './task.object';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { ObjectSchema, Field } from '@objectstack/spec/data';\n\nexport const Task = ObjectSchema.create({\n name: 'task',\n label: 'Task',\n pluralLabel: 'Tasks',\n icon: 'check-square',\n description: 'Personal tasks and to-do items',\n \n fields: {\n // Task Information\n subject: Field.text({\n label: 'Subject',\n required: true,\n searchable: true,\n maxLength: 255,\n }),\n \n description: Field.markdown({\n label: 'Description',\n }),\n \n // Task Management\n status: Field.select({\n label: 'Status',\n required: true,\n options: [\n { label: 'Not Started', value: 'not_started', color: '#808080', default: true },\n { label: 'In Progress', value: 'in_progress', color: '#3B82F6' },\n { label: 'Waiting', value: 'waiting', color: '#F59E0B' },\n { label: 'Completed', value: 'completed', color: '#10B981' },\n { label: 'Deferred', value: 'deferred', color: '#6B7280' },\n ]\n }),\n \n priority: Field.select({\n label: 'Priority',\n required: true,\n options: [\n { label: 'Low', value: 'low', color: '#60A5FA', default: true },\n { label: 'Normal', value: 'normal', color: '#10B981' },\n { label: 'High', value: 'high', color: '#F59E0B' },\n { label: 'Urgent', value: 'urgent', color: '#EF4444' },\n ]\n }),\n \n category: Field.select({\n label: 'Category',\n options: [\n { label: 'Personal', value: 'personal' },\n { label: 'Work', value: 'work' },\n { label: 'Shopping', value: 'shopping' },\n { label: 'Health', value: 'health' },\n { label: 'Finance', value: 'finance' },\n { label: 'Other', value: 'other' },\n ]\n }),\n \n // Dates\n due_date: Field.date({\n label: 'Due Date',\n }),\n \n reminder_date: Field.datetime({\n label: 'Reminder Date/Time',\n }),\n \n completed_date: Field.datetime({\n label: 'Completed Date',\n readonly: true,\n }),\n \n // Assignment\n owner: Field.lookup('user', {\n label: 'Assigned To',\n required: true,\n }),\n \n // Tags\n tags: Field.select({\n label: 'Tags',\n multiple: true,\n options: [\n { label: 'Important', value: 'important', color: '#EF4444' },\n { label: 'Quick Win', value: 'quick_win', color: '#10B981' },\n { label: 'Blocked', value: 'blocked', color: '#F59E0B' },\n { label: 'Follow Up', value: 'follow_up', color: '#3B82F6' },\n { label: 'Review', value: 'review', color: '#8B5CF6' },\n ]\n }),\n \n // Recurrence\n is_recurring: Field.boolean({\n label: 'Recurring Task',\n defaultValue: false,\n }),\n \n recurrence_type: Field.select({\n label: 'Recurrence Type',\n options: [\n { label: 'Daily', value: 'daily' },\n { label: 'Weekly', value: 'weekly' },\n { label: 'Monthly', value: 'monthly' },\n { label: 'Yearly', value: 'yearly' },\n ]\n }),\n \n recurrence_interval: Field.number({\n label: 'Recurrence Interval',\n defaultValue: 1,\n min: 1,\n }),\n \n // Flags\n is_completed: Field.boolean({\n label: 'Is Completed',\n defaultValue: false,\n readonly: true,\n }),\n \n is_overdue: Field.boolean({\n label: 'Is Overdue',\n defaultValue: false,\n readonly: true,\n }),\n \n // Progress\n progress_percent: Field.percent({\n label: 'Progress (%)',\n min: 0,\n max: 100,\n defaultValue: 0,\n }),\n \n // Time Tracking\n estimated_hours: Field.number({\n label: 'Estimated Hours',\n scale: 2,\n min: 0,\n }),\n \n actual_hours: Field.number({\n label: 'Actual Hours',\n scale: 2,\n min: 0,\n }),\n \n // Additional fields\n notes: Field.richtext({\n label: 'Notes',\n description: 'Rich text notes with formatting',\n }),\n \n category_color: Field.color({\n label: 'Category Color',\n colorFormat: 'hex',\n presetColors: ['#EF4444', '#F59E0B', '#10B981', '#3B82F6', '#8B5CF6'],\n }),\n },\n \n enable: {\n trackHistory: true,\n searchable: true,\n apiEnabled: true,\n files: true,\n feeds: true,\n activities: true,\n trash: true,\n mru: true,\n },\n \n // Database indexes for performance\n indexes: [\n { fields: ['status'] },\n { fields: ['priority'] },\n { fields: ['owner'] },\n { fields: ['due_date'] },\n { fields: ['category'] },\n ],\n \n titleFormat: '{subject}',\n compactLayout: ['subject', 'status', 'priority', 'due_date', 'owner'],\n \n validations: [\n {\n name: 'completed_date_required',\n type: 'script',\n severity: 'error',\n message: 'Completed date is required when status is Completed',\n condition: 'status = \"completed\" AND ISBLANK(completed_date)',\n },\n {\n name: 'recurrence_fields_required',\n type: 'script',\n severity: 'error',\n message: 'Recurrence type is required for recurring tasks',\n condition: 'is_recurring = true AND ISBLANK(recurrence_type)',\n },\n ],\n \n workflows: [\n {\n name: 'set_completed_flag',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'ISCHANGED(status)',\n active: true,\n actions: [\n {\n name: 'update_completed_flag',\n type: 'field_update',\n field: 'is_completed',\n value: 'status = \"completed\"',\n }\n ],\n },\n {\n name: 'set_completed_date',\n objectName: 'task',\n triggerType: 'on_update',\n criteria: 'ISCHANGED(status) AND status = \"completed\"',\n active: true,\n actions: [\n {\n name: 'set_date',\n type: 'field_update',\n field: 'completed_date',\n value: 'NOW()',\n },\n {\n name: 'set_progress',\n type: 'field_update',\n field: 'progress_percent',\n value: '100',\n }\n ],\n },\n {\n name: 'check_overdue',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'due_date < TODAY() AND is_completed = false',\n active: true,\n actions: [\n {\n name: 'set_overdue_flag',\n type: 'field_update',\n field: 'is_overdue',\n value: 'true',\n }\n ],\n },\n {\n name: 'notify_on_urgent',\n objectName: 'task',\n triggerType: 'on_create_or_update',\n criteria: 'priority = \"urgent\" AND is_completed = false',\n active: true,\n actions: [\n {\n name: 'email_owner',\n type: 'email_alert',\n template: 'urgent_task_alert',\n recipients: ['{owner.email}'],\n }\n ],\n },\n ],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Action Definitions Barrel\n *\n * Exports action metadata definitions only. Used by `Object.values()` in\n * objectstack.config.ts to auto-collect all action declarations for defineStack().\n *\n * **Handler functions** are exported from `./handlers/` \u2014 see register-handlers.ts\n * for the complete registration flow.\n */\nexport {\n CompleteTaskAction,\n StartTaskAction,\n DeferTaskAction,\n SetReminderAction,\n CloneTaskAction,\n MassCompleteTasksAction,\n DeleteCompletedAction,\n ExportToCsvAction,\n} from './task.actions';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Action } from '@objectstack/spec/ui';\n\n/** Mark Task as Complete */\nexport const CompleteTaskAction: Action = {\n name: 'complete_task',\n label: 'Mark Complete',\n objectName: 'task',\n icon: 'check-circle',\n type: 'script',\n target: 'completeTask',\n locations: ['record_header', 'list_item'],\n successMessage: 'Task marked as complete!',\n refreshAfter: true,\n};\n\n/** Mark Task as In Progress */\nexport const StartTaskAction: Action = {\n name: 'start_task',\n label: 'Start Task',\n objectName: 'task',\n icon: 'play-circle',\n type: 'script',\n target: 'startTask',\n locations: ['record_header', 'list_item'],\n successMessage: 'Task started!',\n refreshAfter: true,\n};\n\n/** Defer Task */\nexport const DeferTaskAction: Action = {\n name: 'defer_task',\n label: 'Defer Task',\n objectName: 'task',\n icon: 'clock',\n type: 'modal',\n target: 'defer_task_modal',\n locations: ['record_header'],\n params: [\n {\n name: 'new_due_date',\n label: 'New Due Date',\n type: 'date',\n required: true,\n },\n {\n name: 'reason',\n label: 'Reason for Deferral',\n type: 'textarea',\n required: false,\n }\n ],\n successMessage: 'Task deferred successfully!',\n refreshAfter: true,\n};\n\n/** Set Reminder */\nexport const SetReminderAction: Action = {\n name: 'set_reminder',\n label: 'Set Reminder',\n objectName: 'task',\n icon: 'bell',\n type: 'modal',\n target: 'set_reminder_modal',\n locations: ['record_header', 'list_item'],\n params: [\n {\n name: 'reminder_date',\n label: 'Reminder Date/Time',\n type: 'datetime',\n required: true,\n }\n ],\n successMessage: 'Reminder set!',\n refreshAfter: true,\n};\n\n/** Clone Task */\nexport const CloneTaskAction: Action = {\n name: 'clone_task',\n label: 'Clone Task',\n objectName: 'task',\n icon: 'copy',\n type: 'script',\n target: 'cloneTask',\n locations: ['record_header'],\n successMessage: 'Task cloned successfully!',\n refreshAfter: true,\n};\n\n/** Mass Complete Tasks */\nexport const MassCompleteTasksAction: Action = {\n name: 'mass_complete',\n label: 'Complete Selected',\n objectName: 'task',\n icon: 'check-square',\n type: 'script',\n target: 'massCompleteTasks',\n locations: ['list_toolbar'],\n successMessage: 'Selected tasks marked as complete!',\n refreshAfter: true,\n};\n\n/** Delete Completed Tasks */\nexport const DeleteCompletedAction: Action = {\n name: 'delete_completed',\n label: 'Delete Completed',\n objectName: 'task',\n icon: 'trash-2',\n type: 'script',\n target: 'deleteCompletedTasks',\n locations: ['list_toolbar'],\n successMessage: 'Completed tasks deleted!',\n refreshAfter: true,\n};\n\n/** Export Tasks to CSV */\nexport const ExportToCsvAction: Action = {\n name: 'export_csv',\n label: 'Export to CSV',\n objectName: 'task',\n icon: 'download',\n type: 'script',\n target: 'exportTasksToCSV',\n locations: ['list_toolbar'],\n successMessage: 'Export completed!',\n refreshAfter: false,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Dashboard Definitions Barrel\n */\nexport { TaskDashboard } from './task.dashboard';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Dashboard } from '@objectstack/spec/ui';\n\nexport const TaskDashboard: Dashboard = {\n name: 'task_dashboard',\n label: 'Task Overview',\n description: 'Key task metrics and productivity overview',\n \n widgets: [\n // Row 1: Key Metrics\n {\n id: 'total_tasks',\n title: 'Total Tasks',\n type: 'metric',\n object: 'task',\n aggregate: 'count',\n layout: { x: 0, y: 0, w: 3, h: 2 },\n options: { color: '#3B82F6' }\n },\n {\n id: 'completed_today',\n title: 'Completed Today',\n type: 'metric',\n object: 'task',\n filter: { is_completed: true, completed_date: { $gte: '{today_start}' } },\n aggregate: 'count',\n layout: { x: 3, y: 0, w: 3, h: 2 },\n options: { color: '#10B981' }\n },\n {\n id: 'overdue_tasks',\n title: 'Overdue Tasks',\n type: 'metric',\n object: 'task',\n filter: { is_overdue: true, is_completed: false },\n aggregate: 'count',\n layout: { x: 6, y: 0, w: 3, h: 2 },\n options: { color: '#EF4444' }\n },\n {\n id: 'completion_rate',\n title: 'Completion Rate',\n type: 'metric',\n object: 'task',\n filter: { created_date: { $gte: '{current_week_start}' } },\n valueField: 'is_completed',\n aggregate: 'count',\n layout: { x: 9, y: 0, w: 3, h: 2 },\n options: { suffix: '%', color: '#8B5CF6' }\n },\n \n // Row 2: Task Distribution\n {\n id: 'tasks_by_status',\n title: 'Tasks by Status',\n type: 'pie',\n object: 'task',\n filter: { is_completed: false },\n categoryField: 'status',\n aggregate: 'count',\n layout: { x: 0, y: 2, w: 6, h: 4 },\n options: { showLegend: true }\n },\n {\n id: 'tasks_by_priority',\n title: 'Tasks by Priority',\n type: 'bar',\n object: 'task',\n filter: { is_completed: false },\n categoryField: 'priority',\n aggregate: 'count',\n layout: { x: 6, y: 2, w: 6, h: 4 },\n options: { horizontal: true }\n },\n \n // Row 3: Trends\n {\n id: 'weekly_task_completion',\n title: 'Weekly Task Completion',\n type: 'line',\n object: 'task',\n filter: { is_completed: true, completed_date: { $gte: '{last_4_weeks}' } },\n categoryField: 'completed_date',\n aggregate: 'count',\n layout: { x: 0, y: 6, w: 8, h: 4 },\n options: { showDataLabels: true }\n },\n {\n id: 'tasks_by_category',\n title: 'Tasks by Category',\n type: 'donut',\n object: 'task',\n filter: { is_completed: false },\n categoryField: 'category',\n aggregate: 'count',\n layout: { x: 8, y: 6, w: 4, h: 4 },\n options: { showLegend: true }\n },\n \n // Row 4: Tables\n {\n id: 'overdue_tasks_table',\n title: 'Overdue Tasks',\n type: 'table',\n object: 'task',\n filter: { is_overdue: true, is_completed: false },\n aggregate: 'count',\n layout: { x: 0, y: 10, w: 6, h: 4 },\n },\n {\n id: 'due_today',\n title: 'Due Today',\n type: 'table',\n object: 'task',\n filter: { due_date: '{today}', is_completed: false },\n aggregate: 'count',\n layout: { x: 6, y: 10, w: 6, h: 4 },\n },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Report Definitions Barrel\n */\nexport {\n TasksByStatusReport,\n TasksByPriorityReport,\n TasksByOwnerReport,\n OverdueTasksReport,\n CompletedTasksReport,\n TimeTrackingReport,\n} from './task.report';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ReportInput } from '@objectstack/spec/ui';\n\n/** Tasks by Status Report */\nexport const TasksByStatusReport: ReportInput = {\n name: 'tasks_by_status',\n label: 'Tasks by Status',\n description: 'Summary of tasks grouped by status',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'priority', label: 'Priority' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'owner', label: 'Assigned To' },\n ],\n groupingsDown: [{ field: 'status', sortOrder: 'asc' }],\n};\n\n/** Tasks by Priority Report */\nexport const TasksByPriorityReport: ReportInput = {\n name: 'tasks_by_priority',\n label: 'Tasks by Priority',\n description: 'Summary of tasks grouped by priority level',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'status', label: 'Status' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'category', label: 'Category' },\n ],\n groupingsDown: [{ field: 'priority', sortOrder: 'desc' }],\n filter: { is_completed: false },\n};\n\n/** Tasks by Owner Report */\nexport const TasksByOwnerReport: ReportInput = {\n name: 'tasks_by_owner',\n label: 'Tasks by Owner',\n description: 'Task summary by assignee',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'status', label: 'Status' },\n { field: 'priority', label: 'Priority' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'estimated_hours', label: 'Est. Hours', aggregate: 'sum' },\n { field: 'actual_hours', label: 'Actual Hours', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'owner', sortOrder: 'asc' }],\n filter: { is_completed: false },\n};\n\n/** Overdue Tasks Report */\nexport const OverdueTasksReport: ReportInput = {\n name: 'overdue_tasks',\n label: 'Overdue Tasks',\n description: 'All overdue tasks that need attention',\n objectName: 'task',\n type: 'tabular',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'due_date', label: 'Due Date' },\n { field: 'priority', label: 'Priority' },\n { field: 'owner', label: 'Assigned To' },\n { field: 'category', label: 'Category' },\n ],\n filter: { is_overdue: true, is_completed: false },\n};\n\n/** Completed Tasks Report */\nexport const CompletedTasksReport: ReportInput = {\n name: 'completed_tasks',\n label: 'Completed Tasks',\n description: 'All completed tasks with time tracking',\n objectName: 'task',\n type: 'summary',\n columns: [\n { field: 'subject', label: 'Subject' },\n { field: 'completed_date', label: 'Completed Date' },\n { field: 'estimated_hours', label: 'Est. Hours', aggregate: 'sum' },\n { field: 'actual_hours', label: 'Actual Hours', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'category', sortOrder: 'asc' }],\n filter: { is_completed: true },\n};\n\n/** Time Tracking Report */\nexport const TimeTrackingReport: ReportInput = {\n name: 'time_tracking',\n label: 'Time Tracking Report',\n description: 'Estimated vs actual hours analysis',\n objectName: 'task',\n type: 'matrix',\n columns: [\n { field: 'estimated_hours', label: 'Estimated Hours', aggregate: 'sum' },\n { field: 'actual_hours', label: 'Actual Hours', aggregate: 'sum' },\n ],\n groupingsDown: [{ field: 'owner', sortOrder: 'asc' }],\n groupingsAcross: [{ field: 'category', sortOrder: 'asc' }],\n filter: { is_completed: true },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Flow } from '@objectstack/spec/automation';\n\n/** Task Reminder Flow \u2014 scheduled flow to send reminders for upcoming tasks */\nexport const TaskReminderFlow: Flow = {\n name: 'task_reminder',\n label: 'Task Reminder Notification',\n description: 'Automated flow to send reminders for tasks approaching their due date',\n type: 'schedule',\n\n variables: [\n { name: 'tasksToRemind', type: 'record_collection', isInput: false, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start (Daily 8 AM)', config: { schedule: '0 8 * * *', objectName: 'task' } },\n {\n id: 'get_upcoming_tasks', type: 'get_record', label: 'Get Tasks Due Tomorrow',\n config: { objectName: 'task', filter: { due_date: '{tomorrow}', is_completed: false }, outputVariable: 'tasksToRemind', getAll: true },\n },\n {\n id: 'loop_tasks', type: 'loop', label: 'Loop Through Tasks',\n config: { collection: '{tasksToRemind}', iteratorVariable: 'currentTask' },\n },\n {\n id: 'send_reminder', type: 'script', label: 'Send Reminder Email',\n config: {\n actionType: 'email',\n inputs: {\n to: '{currentTask.owner.email}',\n subject: 'Task Due Tomorrow: {currentTask.subject}',\n template: 'task_reminder_email',\n data: { taskSubject: '{currentTask.subject}', dueDate: '{currentTask.due_date}', priority: '{currentTask.priority}' },\n },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_upcoming_tasks', type: 'default' },\n { id: 'e2', source: 'get_upcoming_tasks', target: 'loop_tasks', type: 'default' },\n { id: 'e3', source: 'loop_tasks', target: 'send_reminder', type: 'default' },\n { id: 'e4', source: 'send_reminder', target: 'end', type: 'default' },\n ],\n};\n\n/** Overdue Task Escalation Flow */\nexport const OverdueEscalationFlow: Flow = {\n name: 'overdue_escalation',\n label: 'Overdue Task Escalation',\n description: 'Escalates tasks that have been overdue for more than 3 days',\n type: 'schedule',\n\n variables: [\n { name: 'overdueTasks', type: 'record_collection', isInput: false, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start (Daily 9 AM)', config: { schedule: '0 9 * * *', objectName: 'task' } },\n {\n id: 'get_overdue_tasks', type: 'get_record', label: 'Get Severely Overdue Tasks',\n config: {\n objectName: 'task',\n filter: { due_date: { $lt: '{3_days_ago}' }, is_completed: false, is_overdue: true },\n outputVariable: 'overdueTasks', getAll: true,\n },\n },\n {\n id: 'loop_overdue', type: 'loop', label: 'Loop Through Overdue Tasks',\n config: { collection: '{overdueTasks}', iteratorVariable: 'currentTask' },\n },\n {\n id: 'update_priority', type: 'update_record', label: 'Escalate Priority',\n config: {\n objectName: 'task',\n filter: { id: '{currentTask.id}' },\n fields: { priority: 'urgent', tags: ['important', 'follow_up'] },\n },\n },\n {\n id: 'notify_owner', type: 'script', label: 'Notify Task Owner',\n config: {\n actionType: 'email',\n inputs: {\n to: '{currentTask.owner.email}',\n subject: 'URGENT: Task Overdue - {currentTask.subject}',\n template: 'overdue_escalation_email',\n data: { taskSubject: '{currentTask.subject}', dueDate: '{currentTask.due_date}', daysOverdue: '{currentTask.days_overdue}' },\n },\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_overdue_tasks', type: 'default' },\n { id: 'e2', source: 'get_overdue_tasks', target: 'loop_overdue', type: 'default' },\n { id: 'e3', source: 'loop_overdue', target: 'update_priority', type: 'default' },\n { id: 'e4', source: 'update_priority', target: 'notify_owner', type: 'default' },\n { id: 'e5', source: 'notify_owner', target: 'end', type: 'default' },\n ],\n};\n\n/** Task Completion Flow */\nexport const TaskCompletionFlow: Flow = {\n name: 'task_completion',\n label: 'Task Completion Process',\n description: 'Flow triggered when a task is marked as complete',\n type: 'record_change',\n\n variables: [\n { name: 'taskId', type: 'text', isInput: true, isOutput: false },\n { name: 'completedTask', type: 'record', isInput: false, isOutput: false },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start', config: { objectName: 'task', triggerCondition: 'ISCHANGED(status) AND status = \"completed\"' } },\n {\n id: 'get_task', type: 'get_record', label: 'Get Completed Task',\n config: { objectName: 'task', filter: { id: '{taskId}' }, outputVariable: 'completedTask' },\n },\n {\n id: 'check_recurring', type: 'decision', label: 'Is Recurring Task?',\n config: { condition: '{completedTask.is_recurring} == true' },\n },\n {\n id: 'create_next_task', type: 'create_record', label: 'Create Next Recurring Task',\n config: {\n objectName: 'task',\n fields: {\n subject: '{completedTask.subject}', description: '{completedTask.description}',\n priority: '{completedTask.priority}', category: '{completedTask.category}',\n owner: '{completedTask.owner}', is_recurring: true,\n recurrence_type: '{completedTask.recurrence_type}',\n recurrence_interval: '{completedTask.recurrence_interval}',\n due_date: 'DATEADD({completedTask.due_date}, {completedTask.recurrence_interval}, \"{completedTask.recurrence_type}\")',\n status: 'not_started', is_completed: false,\n },\n outputVariable: 'newTaskId',\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'get_task', type: 'default' },\n { id: 'e2', source: 'get_task', target: 'check_recurring', type: 'default' },\n { id: 'e3', source: 'check_recurring', target: 'create_next_task', type: 'default', condition: '{completedTask.is_recurring} == true', label: 'Yes' },\n { id: 'e4', source: 'check_recurring', target: 'end', type: 'default', condition: '{completedTask.is_recurring} != true', label: 'No' },\n { id: 'e5', source: 'create_next_task', target: 'end', type: 'default' },\n ],\n};\n\n/** Quick Add Task Flow \u2014 screen flow for quickly adding tasks */\nexport const QuickAddTaskFlow: Flow = {\n name: 'quick_add_task',\n label: 'Quick Add Task',\n description: 'Screen flow for quickly creating a new task',\n type: 'screen',\n\n variables: [\n { name: 'subject', type: 'text', isInput: true, isOutput: false },\n { name: 'priority', type: 'text', isInput: true, isOutput: false },\n { name: 'dueDate', type: 'date', isInput: true, isOutput: false },\n { name: 'newTaskId', type: 'text', isInput: false, isOutput: true },\n ],\n\n nodes: [\n { id: 'start', type: 'start', label: 'Start' },\n {\n id: 'screen_1', type: 'screen', label: 'Task Details',\n config: {\n fields: [\n { name: 'subject', label: 'Task Subject', type: 'text', required: true },\n { name: 'priority', label: 'Priority', type: 'select', options: ['low', 'normal', 'high', 'urgent'], defaultValue: 'normal' },\n { name: 'dueDate', label: 'Due Date', type: 'date', required: false },\n { name: 'category', label: 'Category', type: 'select', options: ['personal', 'work', 'shopping', 'health', 'finance', 'other'] },\n ],\n },\n },\n {\n id: 'create_task', type: 'create_record', label: 'Create Task',\n config: {\n objectName: 'task',\n fields: { subject: '{subject}', priority: '{priority}', due_date: '{dueDate}', category: '{category}', status: 'not_started', owner: '{$User.Id}' },\n outputVariable: 'newTaskId',\n },\n },\n {\n id: 'success_screen', type: 'screen', label: 'Success',\n config: {\n message: 'Task \"{subject}\" created successfully!',\n buttons: [\n { label: 'Create Another', action: 'restart' },\n { label: 'View Task', action: 'navigate', target: '/task/{newTaskId}' },\n { label: 'Done', action: 'finish' },\n ],\n },\n },\n { id: 'end', type: 'end', label: 'End' },\n ],\n\n edges: [\n { id: 'e1', source: 'start', target: 'screen_1', type: 'default' },\n { id: 'e2', source: 'screen_1', target: 'create_task', type: 'default' },\n { id: 'e3', source: 'create_task', target: 'success_screen', type: 'default' },\n { id: 'e4', source: 'success_screen', target: 'end', type: 'default' },\n ],\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Flow } from '@objectstack/spec/automation';\n\n/**\n * Flow Definitions Barrel\n */\nexport {\n TaskReminderFlow,\n OverdueEscalationFlow,\n TaskCompletionFlow,\n QuickAddTaskFlow,\n} from './task.flow';\n\nimport {\n TaskReminderFlow,\n OverdueEscalationFlow,\n TaskCompletionFlow,\n QuickAddTaskFlow,\n} from './task.flow';\n\n/** All flow definitions as a typed array for defineStack() */\nexport const allFlows: Flow[] = [\n TaskReminderFlow,\n OverdueEscalationFlow,\n TaskCompletionFlow,\n QuickAddTaskFlow,\n];\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * App Definitions Barrel\n */\nexport { TodoApp } from './todo.app';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { App } from '@objectstack/spec/ui';\n\nexport const TodoApp = App.create({\n name: 'todo_app',\n label: 'Todo Manager',\n icon: 'check-square',\n branding: {\n primaryColor: '#10B981',\n secondaryColor: '#3B82F6',\n logo: '/assets/todo-logo.png',\n favicon: '/assets/todo-favicon.ico',\n },\n \n navigation: [\n {\n id: 'group_tasks',\n type: 'group',\n label: 'Tasks',\n icon: 'check-square',\n children: [\n { id: 'nav_all_tasks', type: 'object', objectName: 'task', label: 'All Tasks', icon: 'list' },\n { id: 'nav_my_tasks', type: 'object', objectName: 'task', label: 'My Tasks', icon: 'user-check' },\n { id: 'nav_overdue', type: 'object', objectName: 'task', label: 'Overdue', icon: 'alert-circle' },\n { id: 'nav_today', type: 'object', objectName: 'task', label: 'Due Today', icon: 'calendar' },\n { id: 'nav_upcoming', type: 'object', objectName: 'task', label: 'Upcoming', icon: 'calendar-plus' },\n ]\n },\n {\n id: 'group_analytics',\n type: 'group',\n label: 'Analytics',\n icon: 'chart-bar',\n children: [\n { id: 'nav_dashboard', type: 'dashboard', dashboardName: 'task_dashboard', label: 'Dashboard', icon: 'layout-dashboard' },\n ]\n },\n ]\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Translation Definitions Barrel\n */\nexport { TodoTranslations } from './todo.translation';\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * English (en) \u2014 Todo App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n * Each file exports a single `TranslationData` object for its locale.\n */\nexport const en: TranslationData = {\n objects: {\n task: {\n label: 'Task',\n pluralLabel: 'Tasks',\n fields: {\n subject: { label: 'Subject', help: 'Brief title of the task' },\n description: { label: 'Description' },\n status: {\n label: 'Status',\n options: {\n not_started: 'Not Started',\n in_progress: 'In Progress',\n waiting: 'Waiting',\n completed: 'Completed',\n deferred: 'Deferred',\n },\n },\n priority: {\n label: 'Priority',\n options: {\n low: 'Low',\n normal: 'Normal',\n high: 'High',\n urgent: 'Urgent',\n },\n },\n category: {\n label: 'Category',\n options: {\n personal: 'Personal',\n work: 'Work',\n shopping: 'Shopping',\n health: 'Health',\n finance: 'Finance',\n other: 'Other',\n },\n },\n due_date: { label: 'Due Date' },\n reminder_date: { label: 'Reminder Date/Time' },\n completed_date: { label: 'Completed Date' },\n owner: { label: 'Assigned To' },\n tags: {\n label: 'Tags',\n options: {\n important: 'Important',\n quick_win: 'Quick Win',\n blocked: 'Blocked',\n follow_up: 'Follow Up',\n review: 'Review',\n },\n },\n is_recurring: { label: 'Recurring Task' },\n recurrence_type: {\n label: 'Recurrence Type',\n options: {\n daily: 'Daily',\n weekly: 'Weekly',\n monthly: 'Monthly',\n yearly: 'Yearly',\n },\n },\n recurrence_interval: { label: 'Recurrence Interval' },\n is_completed: { label: 'Is Completed' },\n is_overdue: { label: 'Is Overdue' },\n progress_percent: { label: 'Progress (%)' },\n estimated_hours: { label: 'Estimated Hours' },\n actual_hours: { label: 'Actual Hours' },\n notes: { label: 'Notes' },\n category_color: { label: 'Category Color' },\n },\n },\n },\n apps: {\n todo_app: {\n label: 'Todo Manager',\n description: 'Personal task management application',\n },\n },\n messages: {\n 'common.save': 'Save',\n 'common.cancel': 'Cancel',\n 'common.delete': 'Delete',\n 'common.edit': 'Edit',\n 'common.create': 'Create',\n 'common.search': 'Search',\n 'common.filter': 'Filter',\n 'common.sort': 'Sort',\n 'common.refresh': 'Refresh',\n 'common.export': 'Export',\n 'common.back': 'Back',\n 'common.confirm': 'Confirm',\n 'success.saved': 'Successfully saved',\n 'success.deleted': 'Successfully deleted',\n 'success.completed': 'Task marked as completed',\n 'confirm.delete': 'Are you sure you want to delete this task?',\n 'confirm.complete': 'Mark this task as completed?',\n 'error.required': 'This field is required',\n 'error.load_failed': 'Failed to load data',\n },\n validationMessages: {\n completed_date_required: 'Completed date is required when status is Completed',\n recurrence_fields_required: 'Recurrence type is required for recurring tasks',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\nimport type { StrictObjectTranslation } from '@objectstack/spec/system';\nimport { Task } from '../objects/task.object';\n\ntype TaskTranslation = StrictObjectTranslation;\n\n/**\n * \u7B80\u4F53\u4E2D\u6587 (zh-CN) \u2014 Todo App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const zhCN: TranslationData = {\n objects: {\n task: {\n label: '\u4EFB\u52A1',\n pluralLabel: '\u4EFB\u52A1',\n fields: {\n subject: { label: '\u4E3B\u9898', help: '\u4EFB\u52A1\u7684\u7B80\u8981\u6807\u9898' },\n description: { label: '\u63CF\u8FF0' },\n status: {\n label: '\u72B6\u6001',\n options: {\n not_started: '\u672A\u5F00\u59CB',\n in_progress: '\u8FDB\u884C\u4E2D',\n waiting: '\u7B49\u5F85\u4E2D',\n completed: '\u5DF2\u5B8C\u6210',\n deferred: '\u5DF2\u63A8\u8FDF',\n },\n },\n priority: {\n label: '\u4F18\u5148\u7EA7',\n options: {\n low: '\u4F4E',\n normal: '\u666E\u901A',\n high: '\u9AD8',\n urgent: '\u7D27\u6025',\n },\n },\n category: {\n label: '\u5206\u7C7B',\n options: {\n personal: '\u4E2A\u4EBA',\n work: '\u5DE5\u4F5C',\n shopping: '\u8D2D\u7269',\n health: '\u5065\u5EB7',\n finance: '\u8D22\u52A1',\n other: '\u5176\u4ED6',\n },\n },\n due_date: { label: '\u622A\u6B62\u65E5\u671F' },\n reminder_date: { label: '\u63D0\u9192\u65E5\u671F/\u65F6\u95F4' },\n completed_date: { label: '\u5B8C\u6210\u65E5\u671F' },\n owner: { label: '\u8D1F\u8D23\u4EBA' },\n tags: {\n label: '\u6807\u7B7E',\n options: {\n important: '\u91CD\u8981',\n quick_win: '\u901F\u80DC',\n blocked: '\u53D7\u963B',\n follow_up: '\u5F85\u8DDF\u8FDB',\n review: '\u5F85\u5BA1\u6838',\n },\n },\n is_recurring: { label: '\u5468\u671F\u6027\u4EFB\u52A1' },\n recurrence_type: {\n label: '\u91CD\u590D\u7C7B\u578B',\n options: {\n daily: '\u6BCF\u5929',\n weekly: '\u6BCF\u5468',\n monthly: '\u6BCF\u6708',\n yearly: '\u6BCF\u5E74',\n },\n },\n recurrence_interval: { label: '\u91CD\u590D\u95F4\u9694' },\n is_completed: { label: '\u662F\u5426\u5B8C\u6210' },\n is_overdue: { label: '\u662F\u5426\u903E\u671F' },\n progress_percent: { label: '\u8FDB\u5EA6 (%)' },\n estimated_hours: { label: '\u9884\u4F30\u5DE5\u65F6' },\n actual_hours: { label: '\u5B9E\u9645\u5DE5\u65F6' },\n notes: { label: '\u5907\u6CE8' },\n category_color: { label: '\u5206\u7C7B\u989C\u8272' },\n },\n } satisfies TaskTranslation,\n },\n apps: {\n todo_app: {\n label: '\u5F85\u529E\u7BA1\u7406',\n description: '\u4E2A\u4EBA\u4EFB\u52A1\u7BA1\u7406\u5E94\u7528',\n },\n },\n messages: {\n 'common.save': '\u4FDD\u5B58',\n 'common.cancel': '\u53D6\u6D88',\n 'common.delete': '\u5220\u9664',\n 'common.edit': '\u7F16\u8F91',\n 'common.create': '\u65B0\u5EFA',\n 'common.search': '\u641C\u7D22',\n 'common.filter': '\u7B5B\u9009',\n 'common.sort': '\u6392\u5E8F',\n 'common.refresh': '\u5237\u65B0',\n 'common.export': '\u5BFC\u51FA',\n 'common.back': '\u8FD4\u56DE',\n 'common.confirm': '\u786E\u8BA4',\n 'success.saved': '\u4FDD\u5B58\u6210\u529F',\n 'success.deleted': '\u5220\u9664\u6210\u529F',\n 'success.completed': '\u4EFB\u52A1\u5DF2\u6807\u8BB0\u4E3A\u5B8C\u6210',\n 'confirm.delete': '\u786E\u5B9A\u8981\u5220\u9664\u6B64\u4EFB\u52A1\u5417\uFF1F',\n 'confirm.complete': '\u786E\u5B9A\u5C06\u6B64\u4EFB\u52A1\u6807\u8BB0\u4E3A\u5B8C\u6210\uFF1F',\n 'error.required': '\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879',\n 'error.load_failed': '\u6570\u636E\u52A0\u8F7D\u5931\u8D25',\n },\n validationMessages: {\n completed_date_required: '\u72B6\u6001\u4E3A\"\u5DF2\u5B8C\u6210\"\u65F6\uFF0C\u5B8C\u6210\u65E5\u671F\u4E3A\u5FC5\u586B\u9879',\n recurrence_fields_required: '\u5468\u671F\u6027\u4EFB\u52A1\u5FC5\u987B\u6307\u5B9A\u91CD\u590D\u7C7B\u578B',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationData } from '@objectstack/spec/system';\n\n/**\n * \u65E5\u672C\u8A9E (ja-JP) \u2014 Todo App Translations\n *\n * Per-locale file: one file per language, following the `per_locale` convention.\n */\nexport const jaJP: TranslationData = {\n objects: {\n task: {\n label: '\u30BF\u30B9\u30AF',\n pluralLabel: '\u30BF\u30B9\u30AF',\n fields: {\n subject: { label: '\u4EF6\u540D', help: '\u30BF\u30B9\u30AF\u306E\u7C21\u5358\u306A\u30BF\u30A4\u30C8\u30EB' },\n description: { label: '\u8AAC\u660E' },\n status: {\n label: '\u30B9\u30C6\u30FC\u30BF\u30B9',\n options: {\n not_started: '\u672A\u7740\u624B',\n in_progress: '\u9032\u884C\u4E2D',\n waiting: '\u5F85\u6A5F\u4E2D',\n completed: '\u5B8C\u4E86',\n deferred: '\u5EF6\u671F',\n },\n },\n priority: {\n label: '\u512A\u5148\u5EA6',\n options: {\n low: '\u4F4E',\n normal: '\u901A\u5E38',\n high: '\u9AD8',\n urgent: '\u7DCA\u6025',\n },\n },\n category: {\n label: '\u30AB\u30C6\u30B4\u30EA',\n options: {\n personal: '\u500B\u4EBA',\n work: '\u4ED5\u4E8B',\n shopping: '\u8CB7\u3044\u7269',\n health: '\u5065\u5EB7',\n finance: '\u8CA1\u52D9',\n other: '\u305D\u306E\u4ED6',\n },\n },\n due_date: { label: '\u671F\u65E5' },\n reminder_date: { label: '\u30EA\u30DE\u30A4\u30F3\u30C0\u30FC\u65E5\u6642' },\n completed_date: { label: '\u5B8C\u4E86\u65E5' },\n owner: { label: '\u62C5\u5F53\u8005' },\n tags: {\n label: '\u30BF\u30B0',\n options: {\n important: '\u91CD\u8981',\n quick_win: '\u30AF\u30A4\u30C3\u30AF\u30A6\u30A3\u30F3',\n blocked: '\u30D6\u30ED\u30C3\u30AF\u4E2D',\n follow_up: '\u30D5\u30A9\u30ED\u30FC\u30A2\u30C3\u30D7',\n review: '\u30EC\u30D3\u30E5\u30FC',\n },\n },\n is_recurring: { label: '\u7E70\u308A\u8FD4\u3057\u30BF\u30B9\u30AF' },\n recurrence_type: {\n label: '\u7E70\u308A\u8FD4\u3057\u30BF\u30A4\u30D7',\n options: {\n daily: '\u6BCE\u65E5',\n weekly: '\u6BCE\u9031',\n monthly: '\u6BCE\u6708',\n yearly: '\u6BCE\u5E74',\n },\n },\n recurrence_interval: { label: '\u7E70\u308A\u8FD4\u3057\u9593\u9694' },\n is_completed: { label: '\u5B8C\u4E86\u6E08\u307F' },\n is_overdue: { label: '\u671F\u9650\u8D85\u904E' },\n progress_percent: { label: '\u9032\u6357\u7387 (%)' },\n estimated_hours: { label: '\u898B\u7A4D\u6642\u9593' },\n actual_hours: { label: '\u5B9F\u7E3E\u6642\u9593' },\n notes: { label: '\u30E1\u30E2' },\n category_color: { label: '\u30AB\u30C6\u30B4\u30EA\u8272' },\n },\n },\n },\n apps: {\n todo_app: {\n label: 'ToDo \u30DE\u30CD\u30FC\u30B8\u30E3\u30FC',\n description: '\u500B\u4EBA\u30BF\u30B9\u30AF\u7BA1\u7406\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3',\n },\n },\n messages: {\n 'common.save': '\u4FDD\u5B58',\n 'common.cancel': '\u30AD\u30E3\u30F3\u30BB\u30EB',\n 'common.delete': '\u524A\u9664',\n 'common.edit': '\u7DE8\u96C6',\n 'common.create': '\u65B0\u898F\u4F5C\u6210',\n 'common.search': '\u691C\u7D22',\n 'common.filter': '\u30D5\u30A3\u30EB\u30BF\u30FC',\n 'common.sort': '\u4E26\u3079\u66FF\u3048',\n 'common.refresh': '\u66F4\u65B0',\n 'common.export': '\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8',\n 'common.back': '\u623B\u308B',\n 'common.confirm': '\u78BA\u8A8D',\n 'success.saved': '\u4FDD\u5B58\u3057\u307E\u3057\u305F',\n 'success.deleted': '\u524A\u9664\u3057\u307E\u3057\u305F',\n 'success.completed': '\u30BF\u30B9\u30AF\u3092\u5B8C\u4E86\u306B\u3057\u307E\u3057\u305F',\n 'confirm.delete': '\u3053\u306E\u30BF\u30B9\u30AF\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F',\n 'confirm.complete': '\u3053\u306E\u30BF\u30B9\u30AF\u3092\u5B8C\u4E86\u306B\u3057\u307E\u3059\u304B\uFF1F',\n 'error.required': '\u3053\u306E\u9805\u76EE\u306F\u5FC5\u9808\u3067\u3059',\n 'error.load_failed': '\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F',\n },\n validationMessages: {\n completed_date_required: '\u30B9\u30C6\u30FC\u30BF\u30B9\u304C\u300C\u5B8C\u4E86\u300D\u306E\u5834\u5408\u3001\u5B8C\u4E86\u65E5\u306F\u5FC5\u9808\u3067\u3059',\n recurrence_fields_required: '\u7E70\u308A\u8FD4\u3057\u30BF\u30B9\u30AF\u306B\u306F\u7E70\u308A\u8FD4\u3057\u30BF\u30A4\u30D7\u304C\u5FC5\u8981\u3067\u3059',\n },\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { TranslationBundle } from '@objectstack/spec/system';\nimport { en } from './en';\nimport { zhCN } from './zh-CN';\nimport { jaJP } from './ja-JP';\n\n/**\n * Todo App \u2014 Internationalization (i18n)\n *\n * Demonstrates **per-locale file splitting** convention:\n * each language is defined in its own file (`en.ts`, `zh-CN.ts`, `ja-JP.ts`)\n * and assembled into a single `TranslationBundle` here.\n *\n * For large projects with many objects, use `per_namespace` organization\n * to further split each locale into per-object files (see i18n-standard docs).\n *\n * Supported locales: en (English), zh-CN (Chinese), ja-JP (Japanese)\n */\nexport const TodoTranslations: TranslationBundle = {\n en,\n 'zh-CN': zhCN,\n 'ja-JP': jaJP,\n};\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { defineStack } from '@objectstack/spec';\n\n// \u2500\u2500\u2500 Barrel Imports (one per metadata type) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nimport * as objects from './src/objects';\nimport * as actions from './src/actions';\nimport * as dashboards from './src/dashboards';\nimport * as reports from './src/reports';\nimport { allFlows } from './src/flows';\nimport * as apps from './src/apps';\nimport * as translations from './src/translations';\n\n// \u2500\u2500\u2500 Action Handler Registration (runtime lifecycle) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Handlers are wired separately from metadata. The `onEnable` export\n// is called by the kernel's AppPlugin after the engine is ready.\n// See: src/actions/register-handlers.ts for the full registration flow.\nimport { registerTaskActionHandlers } from './src/actions/register-handlers';\n\n/**\n * Plugin lifecycle hook \u2014 called by AppPlugin when the engine is ready.\n * This is where action handlers are registered on the ObjectQL engine.\n */\nexport const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {\n registerTaskActionHandlers(ctx.ql);\n};\n\nexport default defineStack({\n manifest: {\n id: 'com.example.todo',\n namespace: 'todo',\n version: '2.0.0',\n type: 'app',\n name: 'Todo Manager',\n description: 'A comprehensive Todo app demonstrating ObjectStack Protocol features including automation, dashboards, and reports',\n },\n\n // Seed Data (top-level, registered as metadata)\n data: [\n {\n object: 'task',\n mode: 'upsert' as const,\n externalId: 'subject',\n records: [\n { subject: 'Learn ObjectStack', status: 'completed', priority: 'high', category: 'work' },\n { subject: 'Build a cool app', status: 'in_progress', priority: 'normal', category: 'work', due_date: new Date(Date.now() + 86400000 * 3) },\n { subject: 'Review PR #102', status: 'completed', priority: 'high', category: 'work' },\n { subject: 'Write Documentation', status: 'not_started', priority: 'normal', category: 'work', due_date: new Date(Date.now() + 86400000) },\n { subject: 'Fix Server bug', status: 'waiting', priority: 'urgent', category: 'work' },\n { subject: 'Buy groceries', status: 'not_started', priority: 'low', category: 'shopping', due_date: new Date() },\n { subject: 'Schedule dentist appointment', status: 'not_started', priority: 'normal', category: 'health', due_date: new Date(Date.now() + 86400000 * 7) },\n { subject: 'Pay utility bills', status: 'not_started', priority: 'high', category: 'finance', due_date: new Date(Date.now() + 86400000 * 2) },\n ]\n }\n ],\n\n // Auto-collected from barrel index files via Object.values()\n objects: Object.values(objects),\n actions: Object.values(actions),\n dashboards: Object.values(dashboards),\n reports: Object.values(reports),\n flows: allFlows,\n apps: Object.values(apps),\n\n // I18n Configuration \u2014 per-locale file organization\n i18n: {\n defaultLocale: 'en',\n supportedLocales: ['en', 'zh-CN', 'ja-JP'],\n fallbackLocale: 'en',\n fileOrganization: 'per_locale',\n },\n\n // I18n Translation Bundles (en, zh-CN, ja-JP)\n translations: Object.values(translations),\n});\n\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { defineStack } from '@objectstack/spec';\n\n/**\n * BI Plugin - Business Intelligence Dashboard\n * \n * This plugin provides analytics and reporting capabilities.\n * (Placeholder - to be implemented)\n */\nexport default defineStack({\n manifest: {\n id: 'com.example.bi',\n namespace: 'bi',\n version: '1.0.0',\n type: 'plugin',\n name: 'BI Plugin',\n description: 'Business Intelligence dashboards and analytics',\n },\n \n // Placeholder - no objects or dashboards yet\n objects: [],\n dashboards: [],\n});\n", "// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Vercel Serverless API Entrypoint for App Host Example\n *\n * Boots the ObjectStack kernel lazily on the first request and delegates\n * all /api/* traffic to the ObjectStack Hono adapter.\n *\n * Uses `getRequestListener()` from `@hono/node-server` to handle Vercel's\n * pre-buffered request body properly.\n */\n\nimport { ObjectKernel, DriverPlugin, AppPlugin } from '@objectstack/runtime';\nimport { ObjectQLPlugin } from '@objectstack/objectql';\nimport { InMemoryDriver } from '@objectstack/driver-memory';\nimport { createHonoApp } from '@objectstack/hono';\nimport { AuthPlugin } from '@objectstack/plugin-auth';\nimport { getRequestListener } from '@hono/node-server';\nimport type { Hono } from 'hono';\nimport CrmApp from '@example/app-crm';\nimport TodoApp from '@example/app-todo';\nimport BiPluginManifest from '@example/plugin-bi';\n\n// ---------------------------------------------------------------------------\n// Singleton state \u2014 persists across warm Vercel invocations\n// ---------------------------------------------------------------------------\n\nlet _kernel: ObjectKernel | null = null;\nlet _app: Hono | null = null;\n\n/** Shared boot promise \u2014 prevents concurrent cold-start races. */\nlet _bootPromise: Promise | null = null;\n\n// ---------------------------------------------------------------------------\n// Kernel bootstrap\n// ---------------------------------------------------------------------------\n\n/**\n * Boot the ObjectStack kernel (one-time cold-start cost).\n *\n * Uses a shared promise so that concurrent requests during a cold start\n * wait for the same boot sequence rather than starting duplicates.\n */\nasync function ensureKernel(): Promise {\n if (_kernel) return _kernel;\n if (_bootPromise) return _bootPromise;\n\n _bootPromise = (async () => {\n console.log('[Vercel] Booting ObjectStack Kernel (app-host)...');\n\n try {\n const kernel = new ObjectKernel();\n\n // Register ObjectQL engine\n await kernel.use(new ObjectQLPlugin());\n\n // Database driver (in-memory for demo)\n await kernel.use(new DriverPlugin(new InMemoryDriver()));\n\n // Auth plugin \u2014 uses environment variables for configuration\n // Prefer VERCEL_PROJECT_PRODUCTION_URL (stable across deployments)\n // over VERCEL_URL (unique per deployment, causes origin mismatch).\n const vercelUrl = process.env.VERCEL_PROJECT_PRODUCTION_URL\n ? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`\n : process.env.VERCEL_URL\n ? `https://${process.env.VERCEL_URL}`\n : 'http://localhost:3000';\n\n await kernel.use(new AuthPlugin({\n secret: process.env.AUTH_SECRET || 'dev-secret-please-change-in-production-min-32-chars',\n baseUrl: vercelUrl,\n }));\n\n // Load app manifests\n await kernel.use(new AppPlugin(CrmApp));\n await kernel.use(new AppPlugin(TodoApp));\n await kernel.use(new AppPlugin(BiPluginManifest));\n\n await kernel.bootstrap();\n\n _kernel = kernel;\n console.log('[Vercel] Kernel ready.');\n return kernel;\n } catch (err) {\n // Clear the lock so the next request can retry\n _bootPromise = null;\n console.error('[Vercel] Kernel boot failed:', (err as any)?.message || err);\n throw err;\n }\n })();\n\n return _bootPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Hono app factory\n// ---------------------------------------------------------------------------\n\n/**\n * Get (or create) the Hono application backed by the ObjectStack kernel.\n * The prefix `/api/v1` matches the client SDK's default API path.\n */\nasync function ensureApp(): Promise {\n if (_app) return _app;\n\n const kernel = await ensureKernel();\n _app = createHonoApp({ kernel, prefix: '/api/v1' });\n return _app;\n}\n\n// ---------------------------------------------------------------------------\n// Body extraction \u2014 reads Vercel's pre-buffered request body.\n// ---------------------------------------------------------------------------\n\n/** Shape of the Vercel-augmented IncomingMessage passed via `env.incoming`. */\ninterface VercelIncomingMessage {\n rawBody?: Buffer | string;\n body?: unknown;\n headers?: Record;\n}\n\n/** Shape of the env object provided by `getRequestListener` on Vercel. */\ninterface VercelEnv {\n incoming?: VercelIncomingMessage;\n}\n\nfunction extractBody(\n incoming: VercelIncomingMessage,\n method: string,\n contentType: string | undefined,\n): BodyInit | null {\n if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return null;\n\n if (incoming.rawBody != null) {\n return incoming.rawBody;\n }\n\n if (incoming.body != null) {\n if (typeof incoming.body === 'string') return incoming.body;\n if (contentType?.includes('application/json')) return JSON.stringify(incoming.body);\n return String(incoming.body);\n }\n\n return null;\n}\n\n/**\n * Derive the correct public URL for the request, fixing the protocol when\n * running behind a reverse proxy such as Vercel's edge network.\n */\nfunction resolvePublicUrl(\n requestUrl: string,\n incoming: VercelIncomingMessage | undefined,\n): string {\n if (!incoming) return requestUrl;\n const fwdProto = incoming.headers?.['x-forwarded-proto'];\n const rawProto = Array.isArray(fwdProto) ? fwdProto[0] : fwdProto;\n // Accept only well-known protocol values to prevent header-injection attacks.\n const proto = rawProto === 'https' || rawProto === 'http' ? rawProto : undefined;\n if (proto === 'https' && requestUrl.startsWith('http:')) {\n return requestUrl.replace(/^http:/, 'https:');\n }\n return requestUrl;\n}\n\n// ---------------------------------------------------------------------------\n// Vercel Node.js serverless handler via @hono/node-server getRequestListener.\n// ---------------------------------------------------------------------------\n\nexport default getRequestListener(async (request, env) => {\n let app: Hono;\n try {\n app = await ensureApp();\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n console.error('[Vercel] Handler error \u2014 bootstrap did not complete:', message);\n return new Response(\n JSON.stringify({\n success: false,\n error: {\n message: 'Service Unavailable \u2014 kernel bootstrap failed.',\n code: 503,\n },\n }),\n { status: 503, headers: { 'content-type': 'application/json' } },\n );\n }\n\n const method = request.method.toUpperCase();\n const incoming = (env as VercelEnv)?.incoming;\n\n // Fix URL protocol using x-forwarded-proto (Vercel sets this to 'https').\n const url = resolvePublicUrl(request.url, incoming);\n\n console.log(`[Vercel] ${method} ${url}`);\n\n if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && incoming) {\n const contentType = incoming.headers?.['content-type'];\n const contentTypeStr = Array.isArray(contentType) ? contentType[0] : contentType;\n const body = extractBody(incoming, method, contentTypeStr);\n if (body != null) {\n return await app.fetch(\n new Request(url, { method, headers: request.headers, body }),\n );\n }\n }\n\n // For GET/HEAD/OPTIONS (or body-less requests): pass through with corrected URL.\n return await app.fetch(\n new Request(url, { method, headers: request.headers }),\n );\n});\n\n/**\n * Vercel per-function configuration.\n */\nexport const config = {\n memory: 1024,\n maxDuration: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ACA,KAAK;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,MAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;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A,MACnC;AAAA,IACJ;AAhBI,IAAAA,WAAA;AAAA;AAAA;;;AC7CJ;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA,IAAAE,YAAA;AAAA;AAKA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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P,KAAK,UAAU;AAAA,QACX,SAAS;AAAA,QACT,OAAO;AAAA,UACH,SAAS;AAAA,UACT,MAAM;AAAA,QACV;AAAA,MACJ,CAAC;AAAA,MACD,EAAE,QAAQ,KAAK,SAAS,EAAE,gBAAgB,mBAAmB,EAAE;AAAA,IACnE;AAAA,EACJ;AAEA,QAAM,SAAS,QAAQ,OAAO,YAAY;AAC1C,QAAM,WAAYD,MAAmB;AAGrC,QAAME,OAAM,iBAAiB,QAAQ,KAAK,QAAQ;AAElD,UAAQ,IAAI,YAAY,MAAM,IAAIA,IAAG,EAAE;AAEvC,MAAI,WAAW,SAAS,WAAW,UAAU,WAAW,aAAa,UAAU;AAC3E,UAAM,cAAc,SAAS,UAAU,cAAc;AACrD,UAAM,iBAAiB,MAAM,QAAQ,WAAW,IAAI,YAAY,CAAC,IAAI;AACrE,UAAM,OAAO,YAAY,UAAU,QAAQ,cAAc;AACzD,QAAI,QAAQ,MAAM;AACd,aAAO,MAAM,IAAI;AAAA,QACb,IAAI,QAAQA,MAAK,EAAE,QAAQ,SAAS,QAAQ,SAAS,KAAK,CAAC;AAAA,MAC/D;AAAA,IACJ;AAAA,EACJ;AAGA,SAAO,MAAM,IAAI;AAAA,IACb,IAAI,QAAQA,MAAK,EAAE,QAAQ,SAAS,QAAQ,QAAQ,CAAC;AAAA,EACzD;AACJ,CAAC;AAKM,IAAMC,UAAS;AAAA,EAClB,QAAQ;AAAA,EACR,aAAa;AACjB;", - "names": ["initializer", "init", "_a", "assert", "isObject", "array", "set", "match", "object", "schema", "path", "_params", "Class", "_a", "message", "config", "base64", "base64url", "hex", "error", "issue", "path", "_a", "_b", "_path", "schema", "_params", "time", "version", "_a", "inst", "_b", "result", "line", "base64", "algorithm", "r", "_a", "checks", "checkResult", "canary", "result", "_", "url", "isDate", "isValidDate", "isObject", "schema", "allowsEval", "results", "map", "left", "right", "keyResult", "valueResult", "output", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "number", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "error", "issue", "schema", "meta", "Class", "_emoji", "_undefined", "_null", "schema", "_params", "issue", "codec", "_payload", "process", "schema", "_params", "_a", "meta", "id", "_cached", "_schema", "registry", "ctx", "schema", "process", "_params", "json", "_schema", "file", "schema", "_params", "process", "core_exports", "_emoji", "_null", "_undefined", "process", "init_core", "checks_exports", "init_checks", "init_core", "date", "datetime", "duration", "time", "init_core", "init_schemas", "initializer", "init_errors", "init_core", "issue", "issues", "parse", "parseAsync", "safeParse", "safeParseAsync", "encode", "decode", "encodeAsync", "decodeAsync", "safeEncode", "safeDecode", "safeEncodeAsync", "safeDecodeAsync", "init_parse", "init_core", "init_errors", "schemas_exports", "_default", "base64", "base64url", "bigint", "boolean", "_catch", "cidrv4", "cidrv6", "cuid", "cuid2", "date", "describe", "e164", "email", "emoji", "_enum", "guid", "hex", "hostname", "intersection", "ipv4", "ipv6", "ksuid", "mac", "meta", "nanoid", "_null", "nullish", "number", "string", "ulid", "_undefined", "uuid", "_void", "xid", "_emoji", "_params", "alg", "enc", "schema", "init_schemas", "init_core", "init_checks", "init_parse", "def", "parse", "safeParse", "parseAsync", "safeParseAsync", "encode", "decode", "encodeAsync", "decodeAsync", "safeEncode", "safeDecode", "safeEncodeAsync", "safeDecodeAsync", "check", "json", "datetime", "time", "duration", "issue", "output", "map", "init_core", "ZodFirstPartyTypeKind", "schema", "path", "zodSchema", "objectSchema", "version", "init_checks", "init_schemas", "schemas_exports", "checks_exports", "bigint", "boolean", "date", "number", "string", "init_core", "init_schemas", "_default", "base64", "base64url", "bigint", "boolean", "_catch", "cidrv4", "cidrv6", "core_exports", "cuid", "cuid2", "date", "decode", "decodeAsync", "describe", "e164", "email", "emoji", "encode", "encodeAsync", "_enum", "guid", "hex", "hostname", "intersection", "ipv4", "ipv6", "ksuid", "mac", "meta", "nanoid", "_null", "nullish", "number", "parse", "parseAsync", "safeDecode", "safeDecodeAsync", "safeEncode", "safeEncodeAsync", "safeParse", "safeParseAsync", "string", "ulid", "_undefined", "uuid", "_void", "xid", "init_core", "init_schemas", "init_checks", "init_errors", "init_parse", "_default", "base64", "base64url", "bigint", "boolean", "_catch", "cidrv4", "cidrv6", "core_exports", "cuid", "cuid2", "date", "decode", "decodeAsync", "describe", "e164", "email", "emoji", "encode", "encodeAsync", "_enum", "guid", "hex", "hostname", "intersection", "ipv4", "ipv6", "ksuid", "mac", "meta", "nanoid", "_null", "nullish", "number", "parse", "parseAsync", "safeDecode", "safeDecodeAsync", "safeEncode", "safeEncodeAsync", "safeParse", "safeParseAsync", "string", "ulid", "_undefined", "uuid", "_void", "xid", "snakeCaseToLabel", "FieldReferenceSchema", "FieldOperatorsSchema", "FilterConditionSchema", "NormalizedFilterSchema", "SortNodeSchema", "AggregationFunction", "AggregationNodeSchema", "JoinType", "JoinStrategy", "JoinNodeSchema", "WindowFunction", "WindowSpecSchema", "WindowFunctionNodeSchema", "FieldNodeSchema", "FullTextSearchSchema", "BaseQuerySchema", "QuerySchema", "SystemIdentifierSchema", "SnakeCaseIdentifierSchema", "EncryptionAlgorithmSchema", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "MaskingStrategySchema", "MaskingRuleSchema", "FieldType", "SelectOptionSchema", "CurrencyConfigSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "FieldSchema", "BaseValidationSchema", "ScriptValidationSchema", "UniquenessValidationSchema", "StateMachineValidationSchema", "FormatValidationSchema", "CrossFieldValidationSchema", "JSONValidationSchema", "AsyncValidationSchema", "CustomValidatorSchema", "ValidationRuleSchema", "ConditionalValidationSchema", "ActionRefSchema", "GuardRefSchema", "TransitionSchema", "StateNodeSchema", "StateMachineSchema", "I18nLabelSchema", "AriaPropsSchema", "NumberFormatSchema", "DateFormatSchema", "ActionParamSchema", "ActionType", "TARGET_REQUIRED_TYPES", "ActionSchema", "ApiMethod", "ObjectCapabilities", "IndexSchema", "SearchConfigSchema", "TenancyConfigSchema", "SoftDeleteConfigSchema", "VersioningConfigSchema", "PartitioningConfigSchema", "CDCConfigSchema", "ObjectSchemaBase", "ObjectSchema", "DatasetMode", "DatasetSchema", "FieldMappingSchema", "AggregationMetricType", "DimensionType", "TimeUpdateInterval", "MetricSchema", "DimensionSchema", "CubeJoinSchema", "CubeSchema", "AnalyticsQuerySchema", "FeedItemType", "MentionSchema", "FieldChangeEntrySchema", "ReactionSchema", "FeedActorSchema", "FeedVisibility", "FeedItemSchema", "SubscriptionEventType", "NotificationChannel", "RecordSubscriptionSchema", "z", "config", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "hashCode", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "HashMap", "MingoError", "assert", "cloneDeep", "compare", "ensureArray", "findInsertIndex", "flatten", "groupBy", "has", "import_hash2", "intersection", "isArray", "isBoolean", "isDate", "isEmpty", "isEqual", "isFunction", "isInteger", "isNil", "isNumber", "isObject", "isObjectLike", "isOperator", "isRegExp", "isString", "isSymbol", "normalize", "removeValue", "resolve", "setValue", "typeOf", "unique", "import_hash", "hash", "flatten2", "unwrap", "path", "resolve2", "path2", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "util_exports", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "Context", "OpType", "ProcessingMode", "computeValue", "evalExpr", "import_util", "ProcessingMode2", "OpType2", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "concat", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "Aggregator", "import_util", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_expr", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "message", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "_expr", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_accumulator", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "sign", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "tag", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_first", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_firstN", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$in", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_last", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_lastN", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_maxN", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_minN", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "meta", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "meta", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "OPERATORS", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "Query", "import_util", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$eq", "$gt", "$gte", "$in", "$lt", "$lte", "$ne", "$nin", "wrap", "_options", "compare", "match", "isNull", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$eq", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$gt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$gte", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$lt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$lte", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$ne", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "date", "match", "year", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "date", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "date", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "date", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "require_median", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_expr", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_mergeObjects", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_percentile", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "map", "set", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "map", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "re", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_type", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_count", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "cached", "import_util", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "window", "config", "array", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "map", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "map", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "import_expression", "map", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "require_set", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "path", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_slice", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_elemMatch", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_size", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_array", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_internal", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$bitsAllClear", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$bitsAllSet", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$bitsAnyClear", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$bitsAnySet", "_options", "require_bitwise", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_eq", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$eq", "require_gt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$gt", "require_gte", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$gte", "require_in", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$in", "require_lt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$lt", "require_lte", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$lte", "require_ne", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$ne", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "$nin", "require_comparison", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_lt", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "path", "require_type", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "schema", "require_mod", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_and", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_or", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_not", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_query", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "_options", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "require_internal", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__export", "__copyProps", "__toESM", "clone", "path", "require_addToSet", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "set", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_max", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_min", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "wrap", "ok", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "require_push", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "require_set", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "path", "require_unset", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "import_util", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__copyProps", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__export", "__copyProps", "__toESM", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__hasOwnProp", "__export", "__copyProps", "core_exports", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__export", "__copyProps", "__toESM", "Aggregator", "import_core", "Query", "index_default", "env", "createLogger", "message", "args", "message", "APIError", "init_error", "message", "error", "schema", "date", "_reject", "isCompatible", "_a", "_b", "logger", "DiagComponentLogger", "DiagLogLevel", "logger", "DiagAPI", "logger", "__spreadArray", "__read", "_a", "_b", "BaseContext", "NoopContextManager", "_context", "__spreadArray", "__read", "API_NAME", "init_context", "ContextAPI", "_a", "__spreadArray", "__read", "TraceFlags", "NonRecordingSpan", "_status", "_a", "init_context", "init_context", "NoopTracer", "ProxyTracer", "version", "_options", "_context", "tracer", "NoopTracerProvider", "_options", "ProxyTracerProvider", "version", "_a", "SpanStatusCode", "API_NAME", "init_trace", "TraceAPI", "success", "version", "init_trace", "init_esm", "init_esm", "init_id", "init_error", "schema", "m", "init_error", "schema", "f", "init_id", "schema", "init_error", "schema", "schema", "schema", "transactionId", "init_error", "config", "schema", "logger", "createLogger", "join", "data", "unsafe_model", "select", "transformedData", "error", "file", "log", "config", "clone", "error", "join", "record", "isString", "isNumber", "isBoolean", "isDate", "isFunction", "isObject", "schema", "schema", "schema", "schema", "isObject", "isFunction", "isObject", "isString", "isString", "isObject", "isString", "sql", "message", "isString", "schema", "isNumber", "isBoolean", "isBoolean", "isString", "groupBy", "join", "fetch", "_props", "_props", "isFunction", "isString", "isFunction", "isFunction", "_props", "isNumber", "_props", "error", "_a", "_props", "error", "_a", "_props", "join_fn", "error", "_props", "isFunction", "randomString", "randomString", "_queryId", "schema", "join", "schema", "isString", "_promise", "resolve", "_props", "error", "set", "_props", "schema", "groupBy", "groupBy", "isFunction", "isFunction", "_node", "isNumber", "_a", "_props", "join_fn", "_alias", "groupBy", "error", "_props", "_alias", "isString", "_props", "_node", "_alias", "binary", "schema", "isFunction", "isObject", "isString", "_table", "_alias", "isString", "trim", "schema", "_node", "_node", "_props", "_props", "_props", "_props", "_node", "_node", "_node", "_props", "_props", "_props", "_props", "_props", "_props", "_props", "createView", "_transformer", "_props", "_props", "_props", "_props", "trim", "createView", "_props", "schema", "isFunction", "_driver", "_a", "_b", "error", "config", "isFunction", "isObject", "isFunction", "isObject", "_props", "_executor", "_state", "schema", "error", "_props", "_alias", "sql", "array", "isString", "isBoolean", "isNumber", "isDate", "sql", "_connection", "_db", "_promise", "_resolve", "config", "isFunction", "sql", "resolve", "_db", "_a", "sql", "_db", "_config", "config", "ID_WRAP_REGEX", "_db", "schema", "_db", "isObject", "isString", "isObject", "_config", "_connections", "isFunction", "sql", "resolve", "ID_WRAP_REGEX", "_db", "parseTableMetadata_fn", "LOCK_ID", "_config", "config", "PRIVATE_RELEASE_METHOD", "_config", "_connections", "_pool", "config", "isFunction", "sql", "_config", "config", "_config", "_pool", "_connection", "_tedious", "config", "resolve", "error", "randomString", "isString", "isNumber", "isBoolean", "isDate", "_db", "join", "_config", "config", "init_esm", "_config", "_connectionMutex", "_db", "_connection", "_a", "_promise", "_resolve", "ConnectionMutex", "getTableMetadata_fn", "init_esm", "config", "sql", "resolve", "_config", "_connectionMutex", "_db", "_connection", "_a", "_promise", "_resolve", "ConnectionMutex", "getTableMetadata_fn", "init_esm", "config", "sql", "resolve", "_config", "_connection", "_a", "_db", "init_esm", "config", "insensitiveIn", "insensitiveNotIn", "init_dist", "init_esm", "config", "BunSqliteDialect", "error", "NodeSqliteDialect", "D1SqliteDialect", "db", "schema", "join", "entry", "eb", "init_dist", "z", "config", "z", "SearchConfigSchema", "config", "z", "config", "z", "z", "HttpMethod", "HttpMethodSchema", "CorsConfigSchema", "RateLimitConfigSchema", "StaticMountSchema", "config", "SystemIdentifierSchema", "SnakeCaseIdentifierSchema", "z", "config", "z", "z", "z", "z", "I18nLabelSchema", "AriaPropsSchema", "NumberFormatSchema", "DateFormatSchema", "SnakeCaseIdentifierSchema", "LocaleSchema", "FieldTranslationSchema", "ObjectTranslationDataSchema", "TranslationDataSchema", "TranslationFileOrganizationSchema", "MessageFormatSchema", "OptionTranslationMapSchema", "ObjectTranslationNodeSchema", "TranslationDiffStatusSchema", "TranslationDiffItemSchema", "CoverageBreakdownEntrySchema", "z", "z", "z", "z", "z", "TranslationDataSchema", "HttpMethod", "config", "SnakeCaseIdentifierSchema", "RateLimitConfigSchema", "VersioningConfigSchema", "z", "StorageScopeSchema", "z", "FileMetadataSchema", "StorageProviderSchema", "StorageAclSchema", "StorageClassSchema", "LifecycleActionSchema", "MultipartUploadConfigSchema", "AccessControlConfigSchema", "LifecyclePolicyRuleSchema", "SystemIdentifierSchema", "LifecyclePolicyConfigSchema", "BucketConfigSchema", "StorageConnectionSchema", "ObjectStorageConfigSchema", "EncryptionAlgorithmSchema", "z", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "MaskingStrategySchema", "MaskingRuleSchema", "FieldType", "SelectOptionSchema", "SystemIdentifierSchema", "CurrencyConfigSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "FieldSchema", "BaseValidationSchema", "ScriptValidationSchema", "UniquenessValidationSchema", "StateMachineValidationSchema", "FormatValidationSchema", "CrossFieldValidationSchema", "JSONValidationSchema", "AsyncValidationSchema", "CustomValidatorSchema", "ValidationRuleSchema", "ConditionalValidationSchema", "ActionRefSchema", "GuardRefSchema", "TransitionSchema", "StateNodeSchema", "StateMachineSchema", "SnakeCaseIdentifierSchema", "ActionParamSchema", "I18nLabelSchema", "ActionType", "TARGET_REQUIRED_TYPES", "ActionSchema", "AriaPropsSchema", "ApiMethod", "ObjectCapabilities", "IndexSchema", "SearchConfigSchema", "TenancyConfigSchema", "SoftDeleteConfigSchema", "VersioningConfigSchema", "PartitioningConfigSchema", "CDCConfigSchema", "ObjectSchemaBase", "snakeCaseToLabel", "ObjectSchema", "config", "MetadataFormatSchema", "MetadataStatsSchema", "MetadataFallbackStrategySchema", "MetadataManagerConfigSchema", "MetadataBulkRegisterRequestSchema", "CoreServiceName", "ServiceCriticalitySchema", "z", "HttpServerConfigSchema", "CorsConfigSchema", "RateLimitConfigSchema", "StaticMountSchema", "HttpMethod", "MiddlewareType", "MiddlewareConfigSchema", "ServerEventType", "config", "config", "z", "HttpMethod", "z", "z", "z", "z", "z", "z", "z", "z", "z", "z", "z", "z", "config", "error", "message", "levelColors", "meta", "resolve", "logger", "logger", "error", "path", "version", "config", "map", "service", "duration", "__export", "path", "_context", "resolve", "url", "_PluginSandboxRuntime", "logger", "config", "allowed", "url", "SystemIdentifierSchema", "SnakeCaseIdentifierSchema", "EventNameSchema", "TransformTypeSchema", "z", "FieldMappingSchema", "HttpMethod", "HttpMethodSchema", "HttpRequestSchema", "CorsConfigSchema", "RateLimitConfigSchema", "StaticMountSchema", "SortDirectionEnum", "IsolationLevelEnum", "MetadataFormatSchema", "EncryptionAlgorithmSchema", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "MaskingStrategySchema", "MaskingRuleSchema", "FieldType", "SelectOptionSchema", "CurrencyConfigSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "logger", "config", "record", "error", "path", "env", "map", "sys", "appId", "SeedLoaderRequestSchema", "meta", "message", "method", "data", "expand", "_context", "labels", "registry", "success", "file", "info", "result", "object", "MetadataCategoryEnum", "z", "ArtifactFileEntrySchema", "ArtifactChecksumSchema", "ArtifactSignatureSchema", "PackageArtifactSchema", "TenantIsolationLevel", "DatabaseProviderSchema", "TenantConnectionConfigSchema", "TenantQuotaSchema", "RowLevelIsolationStrategySchema", "SchemaLevelIsolationStrategySchema", "DatabaseLevelIsolationStrategySchema", "DependencyStatusEnum", "ResolvedDependencySchema", "RequiredActionSchema", "DependencyResolutionResultSchema", "SnakeCaseIdentifierSchema", "EventNameSchema", "z", "EventNameSchema", "SnakeCaseIdentifierSchema", "config", "CapabilityConformanceLevelSchema", "ProtocolVersionSchema", "ProtocolReferenceSchema", "ProtocolFeatureSchema", "PluginCapabilitySchema", "PluginInterfaceSchema", "PluginDependencySchema", "ExtensionPointSchema", "PluginCapabilityManifestSchema", "PluginLoadingStrategySchema", "PluginPreloadConfigSchema", "PluginCodeSplittingSchema", "PluginDynamicImportSchema", "PluginInitializationSchema", "PluginDependencyResolutionSchema", "PluginHotReloadSchema", "PluginCachingSchema", "PluginSandboxingSchema", "PluginPerformanceMonitoringSchema", "PluginLoadingConfigSchema", "PluginLifecycleSchema", "CORE_PLUGIN_TYPES", "DatasetMode", "DatasetSchema", "ManifestSchema", "FieldChangeSchema", "MetadataOverlaySchema", "MergeConflictSchema", "MergeStrategyConfigSchema", "CustomizationPolicySchema", "MetadataFormatSchema", "MetadataStatsSchema", "MetadataLoadOptionsSchema", "MetadataSaveOptionsSchema", "MetadataExportOptionsSchema", "MetadataImportOptionsSchema", "MetadataLoadResultSchema", "MetadataSaveResultSchema", "MetadataWatchEventSchema", "MetadataCollectionInfoSchema", "MetadataLoaderContractSchema", "MetadataFallbackStrategySchema", "MetadataManagerConfigSchema", "MetadataTypeSchema", "MetadataTypeRegistryEntrySchema", "MetadataQuerySchema", "MetadataQueryResultSchema", "MetadataEventSchema", "MetadataValidationResultSchema", "MetadataPluginConfigSchema", "z", "MetadataBulkResultSchema", "MetadataDependencySchema", "PackageStatusEnum", "InstalledPackageSchema", "ManifestSchema", "ListPackagesRequestSchema", "ListPackagesResponseSchema", "GetPackageRequestSchema", "GetPackageResponseSchema", "InstallPackageRequestSchema", "InstallPackageResponseSchema", "DependencyResolutionResultSchema", "UninstallPackageRequestSchema", "UninstallPackageResponseSchema", "EnablePackageRequestSchema", "EnablePackageResponseSchema", "DisablePackageRequestSchema", "DisablePackageResponseSchema", "MetadataChangeTypeSchema", "MetadataDiffItemSchema", "UpgradeImpactLevelSchema", "UpgradePlanSchema", "UpgradePhaseSchema", "path", "file", "issue", "PluginCapabilityManifestSchema", "ExecutionContextSchema", "z", "I18nLabelSchema", "AriaPropsSchema", "NumberFormatSchema", "DateFormatSchema", "z", "BreakpointName", "BreakpointColumnMapSchema", "BreakpointOrderMapSchema", "ResponsiveConfigSchema", "PerformanceConfigSchema", "SystemIdentifierSchema", "SnakeCaseIdentifierSchema", "SharingConfigSchema", "EmbedConfigSchema", "BaseNavItemSchema", "ObjectNavItemSchema", "DashboardNavItemSchema", "PageNavItemSchema", "UrlNavItemSchema", "ReportNavItemSchema", "ActionNavItemSchema", "GroupNavItemSchema", "NavigationItemSchema", "AppBrandingSchema", "NavigationAreaSchema", "AppSchema", "config", "HttpMethod", "HttpMethodSchema", "HttpRequestSchema", "ViewDataSchema", "ViewFilterRuleSchema", "ColumnSummarySchema", "ListColumnSchema", "SelectionConfigSchema", "PaginationConfigSchema", "RowHeightSchema", "GroupingFieldSchema", "GroupingConfigSchema", "GalleryConfigSchema", "TimelineConfigSchema", "ViewSharingSchema", "RowColorConfigSchema", "VisualizationTypeSchema", "UserActionsConfigSchema", "AppearanceConfigSchema", "ViewTabSchema", "AddRecordConfigSchema", "KanbanConfigSchema", "CalendarConfigSchema", "GanttConfigSchema", "NavigationModeSchema", "NavigationConfigSchema", "ListViewSchema", "FormFieldSchema", "FormSectionSchema", "FormViewSchema", "ViewSchema", "FieldReferenceSchema", "z", "FieldOperatorsSchema", "FilterConditionSchema", "NormalizedFilterSchema", "I18nLabelSchema", "SnakeCaseIdentifierSchema", "ResponsiveConfigSchema", "AriaPropsSchema", "PerformanceConfigSchema", "z", "I18nLabelSchema", "ResponsiveConfigSchema", "SnakeCaseIdentifierSchema", "FilterConditionSchema", "AriaPropsSchema", "PerformanceConfigSchema", "EncryptionAlgorithmSchema", "z", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "MaskingStrategySchema", "MaskingRuleSchema", "FieldType", "SelectOptionSchema", "SystemIdentifierSchema", "CurrencyConfigSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "FieldSchema", "ActionParamSchema", "I18nLabelSchema", "ActionType", "TARGET_REQUIRED_TYPES", "ActionSchema", "SnakeCaseIdentifierSchema", "AriaPropsSchema", "z", "SortDirectionEnum", "SortItemSchema", "FilterConditionSchema", "I18nLabelSchema", "ResponsiveConfigSchema", "AriaPropsSchema", "ViewFilterRuleSchema", "AppearanceConfigSchema", "ViewTabSchema", "UserActionsConfigSchema", "AddRecordConfigSchema", "SnakeCaseIdentifierSchema", "PerformanceConfigSchema", "FieldSchema", "FeedItemType", "MentionSchema", "FieldChangeEntrySchema", "ReactionSchema", "FeedActorSchema", "FeedVisibility", "FeedFilterMode", "z", "z", "z", "SnakeCaseIdentifierSchema", "I18nLabelSchema", "AriaPropsSchema", "NotificationSchema", "NotificationConfigSchema", "schema", "cached", "ObjectSchema", "AppSchema", "InstalledPackageSchema", "ManifestSchema", "now", "hash", "config", "record", "error", "object", "groupBy", "map", "_request", "_ObjectQL", "expand", "ExecutionContextSchema", "ql", "__export", "__esm", "_LocalStoragePersistenceAdapter", "raw", "json", "path", "_InMemoryDriver", "config", "record", "object", "groupBy", "schema", "env", "LocalStoragePersistenceAdapter", "FileSystemPersistenceAdapter", "path", "paths", "match", "cacheKey", "decoder", "url", "path", "url", "_a", "path", "raw", "init", "_matchResult", "_a", "Context", "object", "html", "html2", "_res", "_path", "_notFoundHandler", "_a", "path", "url", "clone", "env", "Context", "path", "path2", "_a", "_a", "path", "path", "map", "_a", "re", "paths", "path2", "_routes", "_a", "init", "path", "router", "_children", "_a", "Node", "path", "_a", "Node", "path", "Hono", "Hono", "message", "toResponse", "encoder", "path", "file", "url", "transform", "init_error", "url", "error", "path", "config", "message", "info", "hash", "message", "hash", "info", "isLE", "decode", "encode", "encode", "string", "CHUNK_SIZE", "binary", "decode", "encode", "algorithm", "hash", "alg", "alg", "message", "_a", "alg", "enc", "tag", "algorithm", "decode", "algorithm", "isObjectLike", "isObject", "alg", "algorithm", "encode", "getCryptoKey", "alg", "encode", "deriveKey", "wrap", "unwrap", "alg", "algorithm", "hash", "subtleAlgorithm", "alg", "encrypt", "decrypt", "algorithm", "alg", "freeze", "cached", "hash", "decode", "alg", "isObject", "decode", "encode", "alg", "use", "wrap", "alg", "encode", "unwrap", "tag", "alg", "isObject", "decrypt", "unwrap", "tag", "enc", "encode", "encrypt", "wrap", "alg", "isObject", "protectedHeader", "decode", "alg", "enc", "tag", "encode", "tag", "alg", "enc", "encode", "tag", "isObject", "decode", "alg", "encode", "date", "isObject", "now", "jwt", "jwt", "_payload", "_protectedHeader", "_unprotectedHeader", "alg", "encode", "_flattened", "_protectedHeader", "_jwt", "_cek", "_iv", "_keyManagementParameters", "_protectedHeader", "_jwt", "enc", "check", "encode", "alg", "isObject", "jwk", "error", "_cached", "cache", "cached", "set", "VERSION", "url", "isObject", "_url", "json", "set", "decode", "isObject", "jwt", "decode", "isObject", "version", "config", "resolve", "hash", "hash", "base64", "algorithm", "encoder", "base64", "isBytes", "anumber", "abytes", "message", "aexists", "aoutput", "clean", "createView", "abytes", "hex", "error", "array", "abytes", "mac", "isLE", "anumber", "createView", "randomBytes", "anumber", "abytes", "clean", "abytes", "clean", "aexists", "aoutput", "abytes", "clean", "tag", "version", "hex", "init_error", "cache", "cacheKey", "schema", "APIError", "schema", "logger", "REGEX", "parse", "match", "parse", "init_error", "encoder", "decoder", "hex", "algorithm", "hmac", "hex", "base64", "domain", "version", "cleanCookies", "init_error", "string", "number", "boolean", "message", "stateCookie", "error", "symbol", "ensureAsyncStorage", "ensureAsyncStorage", "ensureAsyncStorage", "ensureAsyncStorage", "error", "init_error", "APIError", "error", "init_error", "allowed", "error", "tryDecode", "promise", "init", "body", "headers", "getCryptoKey", "tryDecode", "error", "path", "error", "getCryptoKey", "options", "url", "headers", "json", "path", "required", "config", "splitPath", "path", "match", "_a", "path", "splitPath", "match", "createRouter", "config", "schema", "router", "createRou3Router", "methods", "path", "url", "error", "isAPIError", "error", "APIError", "path", "url", "init_error", "message", "logger", "logBackwardCompatWarning", "url", "APIError", "ipv4", "ipv6", "path", "window", "now", "path", "_path", "config", "init_error", "APIError", "session", "parsedSession", "parsedUser", "updateAge", "shouldSkipSessionRefresh", "error", "isAPIError", "config", "string", "hash", "config", "init_id", "now", "logger", "cached", "options", "ctx", "sessions", "session", "email", "accounts", "isPlainObject", "object", "init_error", "init_error", "getDate", "now", "hash", "authorizationEndpoint", "duration", "url", "error", "url", "_a", "_b", "isJSONSerializable", "isFunction", "isJSONSerializable", "getBody", "url", "_a", "ValidationError", "message", "schema", "getURL", "url", "path", "_url", "_a", "_b", "fetch", "getBody", "clearTimeout", "parser", "isJSONResponse", "resolve", "refreshToken", "base64", "tokenEndpoint", "error", "now", "base64", "tokenEndpoint", "error", "tokenEndpoint", "refreshToken", "APIError", "init_error", "tokenEndpoint", "refreshToken", "error", "init_error", "authorizationEndpoint", "tokenEndpoint", "url", "refreshToken", "error", "APIError", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "refreshToken", "profile", "userMap", "error", "init_error", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "error", "refreshToken", "authorizationEndpoint", "tokenEndpoint", "userinfoEndpoint", "refreshToken", "error", "init_error", "refreshToken", "APIError", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "refreshToken", "error", "authorizationEndpoint", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "authorizationEndpoint", "tokenEndpoint", "refreshToken", "error", "init_error", "authorizationEndpoint", "tokenEndpoint", "error", "base64", "refreshToken", "APIError", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "init_error", "authorizationEndpoint", "tokenEndpoint", "refreshToken", "init_error", "authorizationEndpoint", "tokenEndpoint", "base64", "error", "refreshToken", "tokenEndpoint", "refreshToken", "error", "refreshToken", "error", "error", "base64", "refreshToken", "tokenEndpoint", "refreshToken", "error", "init_error", "authorizationEndpoint", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "url", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "error", "tokenEndpoint", "refreshToken", "tokenEndpoint", "refreshToken", "init_error", "error", "tokenEndpoint", "refreshToken", "error", "url", "error", "refreshToken", "url", "refreshToken", "error", "_enum", "string", "accounts", "string", "boolean", "APIError", "url", "refreshToken", "info", "init_error", "email", "APIError", "url", "string", "error", "jwt", "updatedUser", "url", "isAPIError", "string", "error", "url", "toRedirectTo", "custom", "error", "url", "init_error", "APIError", "init_error", "init_id", "url", "email", "string", "APIError", "verifyPassword", "init_error", "string", "boolean", "number", "APIError", "url", "email", "init_error", "init_id", "string", "email", "boolean", "APIError", "now", "hash", "isAPIError", "url", "init_error", "string", "APIError", "init_error", "string", "APIError", "boolean", "revokeOtherSessions", "account", "url", "email", "token", "init_error", "key", "isAPIError", "error", "APIError", "init_error", "logger", "path", "methods", "verifyPassword", "error", "rateLimitResponse", "isAPIError", "memoryAdapter", "init_error", "createKyselyAdapter", "kyselyAdapter", "config", "schema", "key", "init_dist", "init_esm", "map", "normalize", "config", "logger", "createLogger", "error", "init_error", "unique", "version", "logger", "init_error", "init_id", "fs", "path", "base64", "generateId", "raw", "path", "json", "env", "fs", "version", "noop", "estimateEntropy", "unique", "logger", "createLogger", "config", "url", "promise", "init_error", "init_dist", "init_error", "init_error", "init_id", "date", "match", "year", "day", "hour", "minute", "value", "error", "init_error", "organization", "user", "role", "member", "email", "init_error", "success", "role", "role", "string", "APIError", "version", "version", "schema", "string", "number", "init_error", "role", "string", "APIError", "defaultRoles", "member", "error", "init_error", "string", "boolean", "APIError", "email", "role", "organization", "teamIds", "init_error", "string", "APIError", "organization", "member", "updatedMember", "number", "_enum", "boolean", "init_error", "string", "boolean", "APIError", "options", "organization", "number", "init_id", "string", "_enum", "date", "defaultRoles", "init_error", "string", "APIError", "organization", "updatedTeam", "init_error", "string", "_undefined", "APIError", "teamSchema", "schema", "init_error", "APIError", "ctx", "session", "init_error", "string", "boolean", "twoFactor", "APIError", "defaultKeyHasher", "hash", "init_error", "string", "boolean", "defaultKeyHasher", "APIError", "schema", "init_error", "getAlphabet", "hex", "hash", "window", "string", "boolean", "APIError", "twoFactor", "init_error", "string", "APIError", "schema", "path", "defaultKeyHasher", "hash", "email", "string", "defaultKeyHasher", "url", "error", "path", "record", "SystemObjectName", "config", "email", "url", "ObjectSchema", "Field", "error", "crypto", "message", "Request", "url", "init", "error", "url2", "_a", "cache", "crypto", "isPromise", "resolve", "__export", "AggregationFunctionEnum", "AppNameSchema", "BaseMetadataRecordSchema", "CacheStrategyEnum", "CorsConfigSchema", "EventNameSchema", "FieldMappingSchema", "FieldNameSchema", "FlowNameSchema", "HttpMethod", "HttpMethodSchema", "HttpRequestSchema", "IsolationLevelEnum", "MetadataFormatSchema", "MutationEventEnum", "ObjectNameSchema", "PLURAL_TO_SINGULAR", "RateLimitConfigSchema", "RoleNameSchema", "SINGULAR_TO_PLURAL", "SnakeCaseIdentifierSchema", "SortDirectionEnum", "SortItemSchema", "StaticMountSchema", "SystemIdentifierSchema", "TransformTypeSchema", "ViewNameSchema", "pluralToSingular", "z", "EncryptionAlgorithmSchema", "KeyManagementProviderSchema", "KeyRotationPolicySchema", "EncryptionConfigSchema", "FieldEncryptionSchema", "MaskingStrategySchema", "MaskingRuleSchema", "MaskingConfigSchema", "FieldType", "SelectOptionSchema", "LocationCoordinatesSchema", "CurrencyConfigSchema", "CurrencyValueSchema", "AddressSchema", "VectorConfigSchema", "FileAttachmentConfigSchema", "DataQualityRulesSchema", "ComputedFieldCacheSchema", "FieldSchema", "Field", "config", "issue", "suggestions", "suggestion", "base", "path", "error", "schema", "data_exports", "ALL_OPERATORS", "AggregationFunction", "AggregationMetricType", "AggregationNodeSchema", "AggregationPipelineSchema", "AggregationStageSchema", "AnalyticsQuerySchema", "ApiMethod", "AsyncValidationSchema", "BaseEngineOptionsSchema", "CDCConfigSchema", "ComparisonOperatorSchema", "ConditionalValidationSchema", "ConsistencyLevelSchema", "CrossFieldValidationSchema", "CubeJoinSchema", "CubeSchema", "CustomValidatorSchema", "DataEngineAggregateOptionsSchema", "DataEngineAggregateRequestSchema", "DataEngineBatchRequestSchema", "DataEngineContractSchema", "DataEngineCountOptionsSchema", "DataEngineCountRequestSchema", "DataEngineDeleteOptionsSchema", "DataEngineDeleteRequestSchema", "DataEngineExecuteRequestSchema", "DataEngineFilterSchema", "DataEngineFindOneRequestSchema", "DataEngineFindRequestSchema", "DataEngineInsertOptionsSchema", "DataEngineInsertRequestSchema", "DataEngineQueryOptionsSchema", "DataEngineRequestSchema", "DataEngineSortSchema", "DataEngineUpdateOptionsSchema", "DataEngineUpdateRequestSchema", "DataEngineVectorFindRequestSchema", "DataTypeMappingSchema", "DatasetLoadResultSchema", "DatasetMode", "DatasetSchema", "DatasourceCapabilities", "DatasourceSchema", "DimensionSchema", "DimensionType", "DocumentSchema", "DocumentSchemaValidationSchema", "DocumentTemplateSchema", "DocumentVersionSchema", "DriverCapabilitiesSchema", "DriverConfigSchema", "DriverDefinitionSchema", "DriverInterfaceSchema", "DriverOptionsSchema", "DriverType", "ESignatureConfigSchema", "EngineAggregateOptionsSchema", "EngineCountOptionsSchema", "EngineDeleteOptionsSchema", "EngineQueryOptionsSchema", "EngineUpdateOptionsSchema", "EqualityOperatorSchema", "ExternalDataSourceSchema", "ExternalFieldMappingSchema", "ExternalLookupSchema", "FILTER_OPERATORS", "FeedActorSchema", "FeedFilterMode", "FeedItemSchema", "FeedItemType", "FeedVisibility", "FieldChangeEntrySchema", "FieldNodeSchema", "FieldOperatorsSchema", "FieldReferenceSchema", "FilterConditionSchema", "FormatValidationSchema", "FullTextSearchSchema", "HookContextSchema", "HookEvent", "HookSchema", "IndexSchema", "JSONValidationSchema", "JoinNodeSchema", "JoinStrategy", "JoinType", "LOGICAL_OPERATORS", "MappingSchema", "MentionSchema", "MetricSchema", "NoSQLDataTypeMappingSchema", "NoSQLDatabaseTypeSchema", "NoSQLDriverConfigSchema", "NoSQLIndexSchema", "NoSQLIndexTypeSchema", "NoSQLOperationTypeSchema", "NoSQLQueryOptionsSchema", "NoSQLTransactionOptionsSchema", "NormalizedFilterSchema", "NotificationChannel", "ObjectCapabilities", "ObjectDependencyGraphSchema", "ObjectDependencyNodeSchema", "ObjectExtensionSchema", "ObjectOwnershipEnum", "ObjectSchema", "PartitioningConfigSchema", "PoolConfigSchema", "QueryFilterSchema", "QuerySchema", "RangeOperatorSchema", "ReactionSchema", "RecordSubscriptionSchema", "ReferenceResolutionErrorSchema", "ReferenceResolutionSchema", "ReplicationConfigSchema", "SQLDialectSchema", "SQLDriverConfigSchema", "SQLiteAlterTableLimitations", "SQLiteDataTypeMappingDefaults", "SSLConfigSchema", "ScriptValidationSchema", "SearchConfigSchema", "SeedLoaderConfigSchema", "SeedLoaderRequestSchema", "SeedLoaderResultSchema", "SetOperatorSchema", "ShardingConfigSchema", "SoftDeleteConfigSchema", "SortNodeSchema", "SpecialOperatorSchema", "StateMachineValidationSchema", "StringOperatorSchema", "SubscriptionEventType", "TenancyConfigSchema", "TenantDatabaseLifecycleSchema", "TenantResolverStrategySchema", "TimeUpdateInterval", "TransformType", "TursoGroupSchema", "TursoMultiTenantConfigSchema", "UniquenessValidationSchema", "VALID_AST_OPERATORS", "ValidationRuleSchema", "VersioningConfigSchema", "WindowFunction", "WindowFunctionNodeSchema", "WindowSpecSchema", "isFilterAST", "parseFilterAST", "AST_OPERATOR_MAP", "convertComparison", "BaseQuerySchema", "BaseValidationSchema", "ActionRefSchema", "GuardRefSchema", "TransitionSchema", "EventSchema", "StateNodeSchema", "StateMachineSchema", "I18nObjectSchema", "I18nLabelSchema", "AriaPropsSchema", "PluralRuleSchema", "NumberFormatSchema", "DateFormatSchema", "LocaleConfigSchema", "ActionParamSchema", "ActionType", "TARGET_REQUIRED_TYPES", "ActionSchema", "ObjectSchemaBase", "snakeCaseToLabel", "ExecutionContextSchema", "RpcLegacyFilterMixin", "RpcQueryOptionsSchema", "FieldPermissionSchema", "ObjectPermissionSchema", "PermissionSetSchema", "RLSAuditConfigSchema", "RLSOperation", "RowLevelSecurityPolicySchema", "object", "AIChatWindowProps", "ActionNavItemSchema", "AddRecordConfigSchema", "AnimationSchema", "AnimationTriggerSchema", "App", "AppBrandingSchema", "AppSchema", "AppearanceConfigSchema", "BlankPageLayoutItemSchema", "BlankPageLayoutSchema", "BorderRadiusSchema", "BreakpointColumnMapSchema", "BreakpointName", "BreakpointOrderMapSchema", "BreakpointsSchema", "CalendarConfigSchema", "ChartAnnotationSchema", "ChartAxisSchema", "ChartConfigSchema", "ChartInteractionSchema", "ChartSeriesSchema", "ChartTypeSchema", "ColorPaletteSchema", "ColumnSummarySchema", "ComponentAnimationSchema", "ComponentPropsMap", "ConflictResolutionSchema", "DashboardHeaderActionSchema", "DashboardHeaderSchema", "DashboardNavItemSchema", "DashboardSchema", "DashboardWidgetSchema", "DensityModeSchema", "DndConfigSchema", "DragConstraintSchema", "DragHandleSchema", "DragItemSchema", "DropEffectSchema", "DropZoneSchema", "EasingFunctionSchema", "ElementButtonPropsSchema", "ElementDataSourceSchema", "ElementFilterPropsSchema", "ElementFormPropsSchema", "ElementImagePropsSchema", "ElementNumberPropsSchema", "ElementRecordPickerPropsSchema", "ElementTextPropsSchema", "EmbedConfigSchema", "EvictionPolicySchema", "FieldWidgetPropsSchema", "FocusManagementSchema", "FocusTrapConfigSchema", "FormFieldSchema", "FormSectionSchema", "FormViewSchema", "GalleryConfigSchema", "GanttConfigSchema", "GestureConfigSchema", "GestureTypeSchema", "GlobalFilterOptionsFromSchema", "GlobalFilterSchema", "GroupNavItemSchema", "GroupingConfigSchema", "GroupingFieldSchema", "InterfacePageConfigSchema", "KanbanConfigSchema", "KeyboardNavigationConfigSchema", "KeyboardShortcutSchema", "ListColumnSchema", "ListViewSchema", "LongPressGestureConfigSchema", "MotionConfigSchema", "NavigationAreaSchema", "NavigationConfigSchema", "NavigationItemSchema", "NavigationModeSchema", "NotificationActionSchema", "NotificationConfigSchema", "NotificationPositionSchema", "NotificationSchema", "NotificationSeveritySchema", "NotificationTypeSchema", "ObjectNavItemSchema", "OfflineCacheConfigSchema", "OfflineConfigSchema", "OfflineStrategySchema", "PageAccordionProps", "PageCardProps", "PageComponentSchema", "PageComponentType", "PageHeaderProps", "PageNavItemSchema", "PageRegionSchema", "PageSchema", "PageTabsProps", "PageTransitionSchema", "PageTypeSchema", "PageVariableSchema", "PaginationConfigSchema", "PerformanceConfigSchema", "PersistStorageSchema", "PinchGestureConfigSchema", "RecordActivityProps", "RecordChatterProps", "RecordDetailsProps", "RecordHighlightsProps", "RecordPathProps", "RecordRelatedListProps", "RecordReviewConfigSchema", "ReportChartSchema", "ReportColumnSchema", "ReportGroupingSchema", "ReportNavItemSchema", "ReportSchema", "ReportType", "ResponsiveConfigSchema", "RowColorConfigSchema", "RowHeightSchema", "SelectionConfigSchema", "ShadowSchema", "SharingConfigSchema", "SpacingSchema", "SwipeDirectionSchema", "SwipeGestureConfigSchema", "SyncConfigSchema", "ThemeModeSchema", "ThemeSchema", "TimelineConfigSchema", "TouchInteractionSchema", "TouchTargetConfigSchema", "TransitionConfigSchema", "TransitionPresetSchema", "TypographySchema", "UrlNavItemSchema", "UserActionsConfigSchema", "ViewDataSchema", "ViewFilterRuleSchema", "ViewSchema", "ViewSharingSchema", "ViewTabSchema", "VisualizationTypeSchema", "WcagContrastLevelSchema", "WidgetActionTypeSchema", "WidgetColorVariantSchema", "WidgetEventSchema", "WidgetLifecycleSchema", "WidgetManifestSchema", "WidgetMeasureSchema", "WidgetPropertySchema", "WidgetSourceSchema", "ZIndexSchema", "defineApp", "BaseNavItemSchema", "EmptyProps", "AccessControlConfigSchema", "AddFieldOperation", "AdvancedAuthConfigSchema", "AnalyzerConfigSchema", "AppCompatibilityCheckSchema", "AppInstallRequestSchema", "AppInstallResultSchema", "AppManifestSchema", "AppTranslationBundleSchema", "AuditConfigSchema", "AuditEventActorSchema", "AuditEventChangeSchema", "AuditEventFilterSchema", "AuditEventSchema", "AuditEventSeverity", "AuditEventTargetSchema", "AuditEventType", "AuditFindingSchema", "AuditFindingSeveritySchema", "AuditFindingStatusSchema", "AuditLogConfigSchema", "AuditRetentionPolicySchema", "AuditScheduleSchema", "AuditStorageConfigSchema", "AuthConfigSchema", "AuthPluginConfigSchema", "AuthProviderConfigSchema", "AwarenessEventSchema", "AwarenessSessionSchema", "AwarenessUpdateSchema", "AwarenessUserStateSchema", "BackupConfigSchema", "BackupRetentionSchema", "BackupStrategySchema", "BatchProgressSchema", "BatchTask", "BatchTaskSchema", "BucketConfigSchema", "CRDTMergeResultSchema", "CRDTStateSchema", "CRDTType", "CacheAvalanchePreventionSchema", "CacheConfigSchema", "CacheConsistencySchema", "CacheInvalidationSchema", "CacheStrategySchema", "CacheTierSchema", "CacheWarmupSchema", "ChangeImpactSchema", "ChangePrioritySchema", "ChangeRequestSchema", "ChangeSetSchema", "ChangeStatusSchema", "ChangeTypeSchema", "CollaborationMode", "CollaborationSessionConfigSchema", "CollaborationSessionSchema", "CollaborativeCursorSchema", "ComplianceAuditRequirementSchema", "ComplianceConfigSchema", "ComplianceEncryptionRequirementSchema", "ComplianceFrameworkSchema", "ConsoleDestinationConfigSchema", "ConsumerConfigSchema", "CoreServiceName", "CounterOperationSchema", "CoverageBreakdownEntrySchema", "CreateObjectOperation", "CronScheduleSchema", "CursorColorPreset", "CursorSelectionSchema", "CursorStyleSchema", "CursorUpdateSchema", "DataClassificationPolicySchema", "DataClassificationSchema", "DatabaseLevelIsolationStrategySchema", "DatabaseProviderSchema", "DeadLetterQueueSchema", "DeleteObjectOperation", "DeployBundleSchema", "DeployDiffSchema", "DeployManifestSchema", "DeployStatusEnum", "DeployValidationIssueSchema", "DeployValidationResultSchema", "DisasterRecoveryPlanSchema", "DistributedCacheConfigSchema", "EmailAndPasswordConfigSchema", "EmailTemplateSchema", "EmailVerificationConfigSchema", "ExecuteSqlOperation", "ExtendedLogLevel", "ExternalServiceDestinationConfigSchema", "FacetConfigSchema", "FailoverConfigSchema", "FailoverModeSchema", "FeatureSchema", "FieldTranslationSchema", "FileDestinationConfigSchema", "FileMetadataSchema", "GCounterSchema", "GDPRConfigSchema", "HIPAAConfigSchema", "HistogramBucketConfigSchema", "HttpDestinationConfigSchema", "HttpServerConfig", "HttpServerConfigSchema", "InAppNotificationSchema", "IncidentCategorySchema", "IncidentNotificationMatrixSchema", "IncidentNotificationRuleSchema", "IncidentResponsePhaseSchema", "IncidentResponsePolicySchema", "IncidentSchema", "IncidentSeveritySchema", "IncidentStatusSchema", "IntervalScheduleSchema", "JobExecutionSchema", "JobExecutionStatus", "JobSchema", "KernelServiceMapSchema", "LWWRegisterSchema", "LicenseMetricType", "LicenseSchema", "LifecycleActionSchema", "LifecyclePolicyConfigSchema", "LifecyclePolicyRuleSchema", "LocaleSchema", "LogDestinationSchema", "LogDestinationType", "LogEnrichmentConfigSchema", "LogEntrySchema", "LogFormat", "LogLevel", "LoggerConfigSchema", "LoggingConfigSchema", "MaskingVisibilityRuleSchema", "MessageFormatSchema", "MessageQueueConfigSchema", "MessageQueueProviderSchema", "MetadataCollectionInfoSchema", "MetadataDiffResultSchema", "MetadataExportOptionsSchema", "MetadataFallbackStrategySchema", "MetadataHistoryQueryOptionsSchema", "MetadataHistoryQueryResultSchema", "MetadataHistoryRecordSchema", "MetadataHistoryRetentionPolicySchema", "MetadataImportOptionsSchema", "MetadataLoadOptionsSchema", "MetadataLoadResultSchema", "MetadataLoaderContractSchema", "MetadataManagerConfigSchema", "MetadataRecordSchema", "MetadataSaveOptionsSchema", "MetadataSaveResultSchema", "MetadataScopeSchema", "MetadataSourceSchema", "MetadataStateSchema", "MetadataStatsSchema", "MetadataWatchEventSchema", "MetricAggregationConfigSchema", "MetricAggregationType", "MetricDataPointSchema", "MetricDefinitionSchema", "MetricExportConfigSchema", "MetricLabelsSchema", "MetricType", "MetricUnit", "MetricsConfigSchema", "MiddlewareConfig", "MiddlewareConfigSchema", "MiddlewareType", "MigrationDependencySchema", "MigrationOperationSchema", "MigrationPlanSchema", "MigrationStatementSchema", "ModifyFieldOperation", "MultipartUploadConfigSchema", "MutualTLSConfigSchema", "NotificationChannelSchema", "ORSetElementSchema", "ORSetSchema", "OTComponentSchema", "OTOperationSchema", "OTOperationType", "OTTransformResultSchema", "ObjectMetadataSchema", "ObjectStorageConfigSchema", "ObjectTranslationDataSchema", "ObjectTranslationNodeSchema", "OnceScheduleSchema", "OpenTelemetryCompatibilitySchema", "OtelExporterType", "PCIDSSConfigSchema", "PNCounterSchema", "PackagePublishResultSchema", "PlanSchema", "PresignedUrlConfigSchema", "ProvisioningStepSchema", "PushNotificationSchema", "QueueConfig", "QueueConfigSchema", "QuotaEnforcementResultSchema", "RPOSchema", "RTOSchema", "RegistryConfigSchema", "RegistrySyncPolicySchema", "RegistryUpstreamSchema", "RemoveFieldOperation", "RenameObjectOperation", "RetryPolicySchema", "RollbackPlanSchema", "RouteHandlerMetadataSchema", "RowLevelIsolationStrategySchema", "SMSTemplateSchema", "SamplingDecision", "SamplingStrategyType", "ScheduleSchema", "SchemaChangeSchema", "SchemaLevelIsolationStrategySchema", "SearchIndexConfigSchema", "SearchProviderSchema", "SecurityContextConfigSchema", "SecurityEventCorrelationSchema", "ServerCapabilitiesSchema", "ServerEventSchema", "ServerEventType", "ServerStatusSchema", "ServiceConfigSchema", "ServiceCriticalitySchema", "ServiceLevelIndicatorSchema", "ServiceLevelObjectiveSchema", "ServiceRequirementDef", "ServiceStatusSchema", "SocialProviderConfigSchema", "SpanAttributeValueSchema", "SpanAttributesSchema", "SpanEventSchema", "SpanKind", "SpanLinkSchema", "SpanSchema", "SpanStatus", "StorageAclSchema", "StorageClassSchema", "StorageConnectionSchema", "StorageProviderSchema", "StorageScopeSchema", "StructuredLogEntrySchema", "SupplierAssessmentStatusSchema", "SupplierRiskLevelSchema", "SupplierSecurityAssessmentSchema", "SupplierSecurityPolicySchema", "SupplierSecurityRequirementSchema", "SuspiciousActivityRuleSchema", "SystemObjectName", "Task", "TaskExecutionResultSchema", "TaskPriority", "TaskRetryPolicySchema", "TaskSchema", "TaskStatus", "TenantConnectionConfigSchema", "TenantIsolationConfigSchema", "TenantIsolationLevel", "TenantPlanSchema", "TenantProvisioningRequestSchema", "TenantProvisioningResultSchema", "TenantProvisioningStatusEnum", "TenantQuotaSchema", "TenantRegionSchema", "TenantSchema", "TenantSecurityPolicySchema", "TenantUsageSchema", "TextCRDTOperationSchema", "TextCRDTStateSchema", "TimeSeriesDataPointSchema", "TimeSeriesSchema", "TopicConfigSchema", "TraceContextPropagationSchema", "TraceContextSchema", "TraceFlagsSchema", "TracePropagationFormat", "TraceSamplingConfigSchema", "TraceStateSchema", "TracingConfigSchema", "TrainingCategorySchema", "TrainingCompletionStatusSchema", "TrainingCourseSchema", "TrainingPlanSchema", "TrainingRecordSchema", "TranslationBundleSchema", "TranslationConfigSchema", "TranslationCoverageResultSchema", "TranslationDataSchema", "TranslationDiffItemSchema", "TranslationDiffStatusSchema", "TranslationFileOrganizationSchema", "UserActivityStatus", "VectorClockSchema", "WorkerConfig", "WorkerConfigSchema", "WorkerStatsSchema", "azureBlobStorageExample", "gcsStorageExample", "minioStorageExample", "s3StorageExample", "OptionTranslationMapSchema", "map", "ActivationEventSchema", "AdvancedPluginLifecycleConfigSchema", "ArtifactChecksumSchema", "ArtifactFileEntrySchema", "ArtifactSignatureSchema", "BreakingChangeSchema", "CLICommandContributionSchema", "CORE_PLUGIN_TYPES", "CapabilityConformanceLevelSchema", "CompatibilityLevelSchema", "CompatibilityMatrixEntrySchema", "CustomizationOriginSchema", "CustomizationPolicySchema", "DeadLetterQueueEntrySchema", "DependencyConflictSchema", "DependencyGraphNodeSchema", "DependencyGraphSchema", "DependencyResolutionResultSchema", "DependencyStatusEnum", "DeprecationNoticeSchema", "DevFixtureConfigSchema", "DevPluginConfigSchema", "DevPluginPreset", "DevServiceOverrideSchema", "DevToolsConfigSchema", "DisablePackageRequestSchema", "DisablePackageResponseSchema", "DistributedStateConfigSchema", "DynamicLoadRequestSchema", "DynamicLoadingConfigSchema", "DynamicPluginOperationSchema", "DynamicPluginResultSchema", "DynamicUnloadRequestSchema", "EnablePackageRequestSchema", "EnablePackageResponseSchema", "EventBusConfigSchema", "EventHandlerSchema", "EventLogEntrySchema", "EventMessageQueueConfigSchema", "EventMetadataSchema", "EventPersistenceSchema", "EventPhaseSchema", "EventPriority", "EventQueueConfigSchema", "EventReplayConfigSchema", "EventRouteSchema", "EventSourcingConfigSchema", "EventTypeDefinitionSchema", "EventWebhookConfigSchema", "ExtensionPointSchema", "FeatureFlag", "FeatureFlagSchema", "FeatureStrategy", "FieldChangeSchema", "GetPackageRequestSchema", "GetPackageResponseSchema", "GracefulDegradationSchema", "HealthStatusSchema", "HookRegisteredEventSchema", "HookTriggeredEventSchema", "HotReloadConfigSchema", "InstallPackageRequestSchema", "InstallPackageResponseSchema", "InstalledPackageSchema", "KernelContextSchema", "KernelEventBaseSchema", "KernelReadyEventSchema", "KernelSecurityPolicySchema", "KernelSecurityScanResultSchema", "KernelSecurityVulnerabilitySchema", "KernelShutdownEventSchema", "ListPackagesRequestSchema", "ListPackagesResponseSchema", "ManifestSchema", "MergeConflictSchema", "MergeResultSchema", "MergeStrategyConfigSchema", "MetadataBulkRegisterRequestSchema", "MetadataBulkResultSchema", "MetadataCategoryEnum", "MetadataChangeTypeSchema", "MetadataDependencySchema", "MetadataDiffItemSchema", "MetadataEventSchema", "MetadataOverlaySchema", "MetadataPluginConfigSchema", "MetadataPluginManifestSchema", "MetadataQueryResultSchema", "MetadataQuerySchema", "MetadataTypeRegistryEntrySchema", "MetadataTypeSchema", "MetadataValidationResultSchema", "MultiVersionSupportSchema", "NamespaceConflictErrorSchema", "NamespaceRegistryEntrySchema", "OclifPluginConfigSchema", "OpsDomainModuleSchema", "OpsFilePathSchema", "OpsPluginStructureSchema", "PackageArtifactSchema", "PackageDependencyConflictSchema", "PackageDependencyResolutionResultSchema", "PackageDependencySchema", "PackageStatusEnum", "PermissionActionSchema", "PermissionSchema", "PermissionScopeSchema", "PluginBuildOptionsSchema", "PluginBuildResultSchema", "PluginCachingSchema", "PluginCapabilityManifestSchema", "PluginCapabilitySchema", "PluginCodeSplittingSchema", "PluginCompatibilityMatrixSchema", "PluginContextSchema", "PluginDependencyResolutionResultSchema", "PluginDependencyResolutionSchema", "PluginDependencySchema", "PluginDiscoveryConfigSchema", "PluginDiscoverySourceSchema", "PluginDynamicImportSchema", "PluginErrorEventSchema", "PluginEventBaseSchema", "PluginHealthCheckSchema", "PluginHealthReportSchema", "PluginHealthStatusSchema", "PluginHotReloadSchema", "PluginInitializationSchema", "PluginInstallConfigSchema", "PluginInterfaceSchema", "PluginLifecycleEventType", "PluginLifecyclePhaseEventSchema", "PluginLifecycleSchema", "PluginLoadingConfigSchema", "PluginLoadingEventSchema", "PluginLoadingStateSchema", "PluginLoadingStrategySchema", "PluginMetadataSchema", "PluginPerformanceMonitoringSchema", "PluginPreloadConfigSchema", "PluginProvenanceSchema", "PluginPublishOptionsSchema", "PluginPublishResultSchema", "PluginQualityMetricsSchema", "PluginRegisteredEventSchema", "PluginRegistryEntrySchema", "PluginSandboxingSchema", "PluginSchema", "PluginSearchFiltersSchema", "PluginSecurityManifestSchema", "PluginSourceSchema", "PluginStartupResultSchema", "PluginStateSnapshotSchema", "PluginStatisticsSchema", "PluginTrustLevelSchema", "PluginTrustScoreSchema", "PluginUpdateStrategySchema", "PluginValidateOptionsSchema", "PluginValidateResultSchema", "PluginVendorSchema", "PluginVersionMetadataSchema", "PreviewModeConfigSchema", "ProtocolFeatureSchema", "ProtocolReferenceSchema", "ProtocolVersionSchema", "RealTimeNotificationConfigSchema", "RequiredActionSchema", "ResolvedDependencySchema", "ResourceTypeSchema", "RollbackPackageRequestSchema", "RollbackPackageResponseSchema", "RuntimeConfigSchema", "RuntimeMode", "SBOMEntrySchema", "SBOMSchema", "SandboxConfigSchema", "ScopeConfigSchema", "ScopeInfoSchema", "SecurityPolicySchema", "SecurityScanResultSchema", "SecurityVulnerabilitySchema", "SemanticVersionSchema", "ServiceFactoryRegistrationSchema", "ServiceMetadataSchema", "ServiceRegisteredEventSchema", "ServiceRegistryConfigSchema", "ServiceScopeType", "ServiceUnregisteredEventSchema", "StartupOptionsSchema", "StartupOrchestrationResultSchema", "TenantRuntimeContextSchema", "UninstallPackageRequestSchema", "UninstallPackageResponseSchema", "UpgradeContextSchema", "UpgradeImpactLevelSchema", "UpgradePackageRequestSchema", "UpgradePackageResponseSchema", "UpgradePhaseSchema", "UpgradePlanSchema", "UpgradeSnapshotSchema", "ValidationErrorSchema", "ValidationFindingSchema", "ValidationResultSchema", "ValidationSeverityEnum", "ValidationWarningSchema", "VersionConstraintSchema", "VulnerabilitySeverity", "SNAKE_CASE_REGEX", "file", "ArtifactReferenceSchema", "ListingStatusSchema", "MarketplaceCategorySchema", "MarketplaceListingSchema", "PricingModelSchema", "PublisherVerificationSchema", "qa_exports", "SessionSchema", "email", "AckMessageSchema", "AddReactionRequestSchema", "AddReactionResponseSchema", "AiInsightsRequestSchema", "AiInsightsResponseSchema", "AiNlqRequestSchema", "AiNlqResponseSchema", "AiSuggestRequestSchema", "AiSuggestResponseSchema", "AnalyticsEndpoint", "AnalyticsMetadataResponseSchema", "AnalyticsQueryRequestSchema", "AnalyticsResultResponseSchema", "AnalyticsSqlResponseSchema", "ApiChangelogEntrySchema", "ApiDiscoveryQuerySchema", "ApiDiscoveryResponseSchema", "ApiDocumentationConfig", "ApiDocumentationConfigSchema", "ApiEndpoint", "ApiEndpointRegistration", "ApiEndpointRegistrationSchema", "ApiEndpointSchema", "ApiErrorSchema", "ApiMappingSchema", "ApiMetadataSchema", "ApiParameterSchema", "ApiProtocolType", "ApiRegistry", "ApiRegistryEntry", "ApiRegistryEntrySchema", "ApiRegistrySchema", "ApiResponseSchema", "ApiRoutesSchema", "ApiTestCollection", "ApiTestCollectionSchema", "ApiTestRequestSchema", "ApiTestingUiConfigSchema", "ApiTestingUiType", "AppDefinitionResponseSchema", "AuthEndpointAliases", "AuthEndpointPaths", "AuthEndpointSchema", "AuthProvider", "AutomationApiErrorCode", "AutomationFlowPathParamsSchema", "AutomationRunPathParamsSchema", "AutomationTriggerRequestSchema", "AutomationTriggerResponseSchema", "BasePresenceSchema", "BaseResponseSchema", "BatchConfigSchema", "BatchDataRequestSchema", "BatchEndpointsConfigSchema", "BatchLoadingStrategySchema", "BatchOperationResultSchema", "BatchOperationType", "BatchOptionsSchema", "BatchRecordSchema", "BatchUpdateRequestSchema", "BatchUpdateResponseSchema", "BulkRequestSchema", "BulkResponseSchema", "CacheControlSchema", "CacheDirective", "CacheInvalidationRequestSchema", "CacheInvalidationResponseSchema", "CacheInvalidationTarget", "CallbackSchema", "ChangelogEntrySchema", "CheckPermissionRequestSchema", "CheckPermissionResponseSchema", "CodeGenerationTemplateSchema", "CompleteChunkedUploadRequestSchema", "CompleteChunkedUploadResponseSchema", "CompleteUploadRequestSchema", "ConceptListResponseSchema", "ConflictResolutionStrategy", "CreateDataRequestSchema", "CreateDataResponseSchema", "CreateExportJobRequestSchema", "CreateExportJobResponseSchema", "CreateFeedItemRequestSchema", "CreateFeedItemResponseSchema", "CreateFlowResponseSchema", "CreateManyDataRequestSchema", "CreateManyDataResponseSchema", "CreateRequestSchema", "CreateViewRequestSchema", "CreateViewResponseSchema", "CrudEndpointPatternSchema", "CrudEndpointsConfigSchema", "CrudOperation", "CursorMessageSchema", "CursorPositionSchema", "DataEventSchema", "DataEventType", "DataLoaderConfigSchema", "DeduplicationStrategy", "DeleteDataRequestSchema", "DeleteDataResponseSchema", "DeleteFeedItemResponseSchema", "DeleteFlowResponseSchema", "DeleteManyDataRequestSchema", "DeleteManyRequestSchema", "DeleteResponseSchema", "DeleteViewRequestSchema", "DeleteViewResponseSchema", "DiscoverySchema", "DispatcherConfigSchema", "DispatcherErrorCode", "DispatcherErrorResponseSchema", "DispatcherRouteSchema", "DocumentStateSchema", "ETagSchema", "EditMessageSchema", "EditOperationSchema", "EditOperationType", "EndpointMapping", "EndpointRegistrySchema", "EnhancedApiErrorSchema", "ErrorCategory", "ErrorHandlingConfigSchema", "ErrorMessageSchema", "ErrorResponseSchema", "EventFilterCondition", "EventFilterSchema", "EventMessageSchema", "EventPatternSchema", "EventSubscriptionSchema", "ExportApiContracts", "ExportFormat", "ExportImportTemplateSchema", "ExportJobProgressSchema", "ExportJobStatus", "ExportJobSummarySchema", "ExportRequestSchema", "FederationEntityKeySchema", "FederationEntitySchema", "FederationExternalFieldSchema", "FederationGatewaySchema", "FederationProvidesSchema", "FederationRequiresSchema", "FeedApiErrorCode", "FeedItemPathParamsSchema", "FeedListFilterType", "FeedPathParamsSchema", "FieldErrorSchema", "FieldMappingEntrySchema", "FileTypeValidationSchema", "FileUploadResponseSchema", "FilterOperator", "FindDataRequestSchema", "FindDataResponseSchema", "FlowSummarySchema", "GeneratedApiDocumentationSchema", "GeneratedEndpointSchema", "GetAnalyticsMetaRequestSchema", "GetChangelogRequestSchema", "GetChangelogResponseSchema", "GetDataRequestSchema", "GetDataResponseSchema", "GetDiscoveryRequestSchema", "GetDiscoveryResponseSchema", "GetEffectivePermissionsRequestSchema", "GetEffectivePermissionsResponseSchema", "GetExportJobDownloadRequestSchema", "GetExportJobDownloadResponseSchema", "GetFeedRequestSchema", "GetFeedResponseSchema", "GetFieldLabelsRequestSchema", "GetFieldLabelsResponseSchema", "GetFlowResponseSchema", "GetInstalledPackageResponseSchema", "GetLocalesRequestSchema", "GetLocalesResponseSchema", "GetMetaItemCachedRequestSchema", "GetMetaItemRequestSchema", "GetMetaItemResponseSchema", "GetMetaItemsRequestSchema", "GetMetaItemsResponseSchema", "GetMetaTypesRequestSchema", "GetMetaTypesResponseSchema", "GetNotificationPreferencesRequestSchema", "GetNotificationPreferencesResponseSchema", "GetObjectPermissionsRequestSchema", "GetObjectPermissionsResponseSchema", "GetPresenceRequestSchema", "GetPresenceResponseSchema", "GetPresignedUrlRequestSchema", "GetRunResponseSchema", "GetTranslationsRequestSchema", "GetTranslationsResponseSchema", "GetUiViewRequestSchema", "GetViewRequestSchema", "GetViewResponseSchema", "GetWorkflowConfigRequestSchema", "GetWorkflowConfigResponseSchema", "GetWorkflowStateRequestSchema", "GetWorkflowStateResponseSchema", "GraphQLConfig", "GraphQLConfigSchema", "GraphQLDataLoaderConfigSchema", "GraphQLDirectiveConfigSchema", "GraphQLDirectiveLocation", "GraphQLMutationConfigSchema", "GraphQLPersistedQuerySchema", "GraphQLQueryAdapterSchema", "GraphQLQueryComplexitySchema", "GraphQLQueryConfigSchema", "GraphQLQueryDepthLimitSchema", "GraphQLRateLimitSchema", "GraphQLResolverConfigSchema", "GraphQLScalarType", "GraphQLSubscriptionConfigSchema", "GraphQLTypeConfigSchema", "HandlerStatusSchema", "HttpFindQueryParamsSchema", "HttpStatusCode", "IdRequestSchema", "ImportValidationConfigSchema", "ImportValidationMode", "ImportValidationResultSchema", "InitiateChunkedUploadRequestSchema", "InitiateChunkedUploadResponseSchema", "ListExportJobsRequestSchema", "ListExportJobsResponseSchema", "ListFlowsRequestSchema", "ListFlowsResponseSchema", "ListInstalledPackagesRequestSchema", "ListInstalledPackagesResponseSchema", "ListNotificationsRequestSchema", "ListNotificationsResponseSchema", "ListRecordResponseSchema", "ListRunsRequestSchema", "ListRunsResponseSchema", "ListViewsRequestSchema", "ListViewsResponseSchema", "LoginRequestSchema", "LoginType", "MarkAllNotificationsReadRequestSchema", "MarkAllNotificationsReadResponseSchema", "MarkNotificationsReadRequestSchema", "MarkNotificationsReadResponseSchema", "MetadataBulkResponseSchema", "MetadataBulkUnregisterRequestSchema", "MetadataCacheRequestSchema", "MetadataCacheResponseSchema", "MetadataDeleteResponseSchema", "MetadataDependenciesResponseSchema", "MetadataDependentsResponseSchema", "MetadataEffectiveResponseSchema", "MetadataEndpointsConfigSchema", "MetadataEventType", "MetadataExistsResponseSchema", "MetadataExportRequestSchema", "MetadataExportResponseSchema", "MetadataImportRequestSchema", "MetadataImportResponseSchema", "MetadataItemResponseSchema", "MetadataListResponseSchema", "MetadataNamesResponseSchema", "MetadataOverlayResponseSchema", "MetadataOverlaySaveRequestSchema", "MetadataQueryRequestSchema", "MetadataQueryResponseSchema", "MetadataRegisterRequestSchema", "MetadataTypeInfoResponseSchema", "MetadataTypesResponseSchema", "MetadataValidateRequestSchema", "MetadataValidateResponseSchema", "ModificationResultSchema", "NotificationPreferencesSchema", "ODataConfigSchema", "ODataErrorSchema", "ODataFilterFunctionSchema", "ODataFilterOperatorSchema", "ODataMetadataSchema", "ODataQueryAdapterSchema", "ODataQuerySchema", "ODataResponseSchema", "ObjectDefinitionResponseSchema", "ObjectQLReferenceSchema", "ObjectStackProtocolSchema", "OpenApi31ExtensionsSchema", "OpenApiGenerationConfigSchema", "OpenApiSecuritySchemeSchema", "OpenApiServerSchema", "OpenApiSpec", "OpenApiSpecSchema", "OperatorMappingSchema", "PackageApiErrorCode", "PackageInstallRequestSchema", "PackageInstallResponseSchema", "PackagePathParamsSchema", "PackageRollbackRequestSchema", "PackageRollbackResponseSchema", "PackageUpgradeRequestSchema", "PackageUpgradeResponseSchema", "PinFeedItemResponseSchema", "PingMessageSchema", "PongMessageSchema", "PresenceMessageSchema", "PresenceStateSchema", "PresenceStatus", "PresenceUpdateSchema", "PresignedUrlResponseSchema", "QueryAdapterConfigSchema", "QueryAdapterTargetSchema", "QueryOptimizationConfigSchema", "RealtimeConfigSchema", "RealtimeConnectRequestSchema", "RealtimeConnectResponseSchema", "RealtimeDisconnectRequestSchema", "RealtimeDisconnectResponseSchema", "RealtimeEventSchema", "RealtimeEventType", "RealtimePresenceSchema", "RealtimeRecordAction", "RealtimeSubscribeRequestSchema", "RealtimeSubscribeResponseSchema", "RealtimeUnsubscribeRequestSchema", "RealtimeUnsubscribeResponseSchema", "RecordDataSchema", "RefreshTokenRequestSchema", "RegisterDeviceRequestSchema", "RegisterDeviceResponseSchema", "RegisterRequestSchema", "RemoveReactionRequestSchema", "RemoveReactionResponseSchema", "RequestValidationConfigSchema", "ResolveDependenciesRequestSchema", "ResolveDependenciesResponseSchema", "ResponseEnvelopeConfigSchema", "RestApiConfig", "RestApiConfigSchema", "RestApiEndpointSchema", "RestApiPluginConfig", "RestApiPluginConfigSchema", "RestApiRouteCategory", "RestApiRouteRegistration", "RestApiRouteRegistrationSchema", "RestQueryAdapterSchema", "RestServerConfig", "RestServerConfigSchema", "RetryStrategy", "RouteCategory", "RouteCoverageEntrySchema", "RouteCoverageReportSchema", "RouteDefinitionSchema", "RouteGenerationConfigSchema", "RouteHealthEntrySchema", "RouteHealthReportSchema", "RouterConfigSchema", "SaveMetaItemRequestSchema", "SaveMetaItemResponseSchema", "ScheduleExportRequestSchema", "ScheduleExportResponseSchema", "ScheduledExportSchema", "SchemaDefinition", "SearchFeedRequestSchema", "SearchFeedResponseSchema", "ServiceInfoSchema", "ServiceStatus", "SessionResponseSchema", "SessionUserSchema", "SetPresenceRequestSchema", "SetPresenceResponseSchema", "SimpleCursorPositionSchema", "SimplePresenceStateSchema", "SingleRecordResponseSchema", "StandardApiContracts", "StandardErrorCode", "StarFeedItemResponseSchema", "SubgraphConfigSchema", "SubscribeMessageSchema", "SubscribeRequestSchema", "SubscribeResponseSchema", "SubscriptionEventSchema", "SubscriptionSchema", "ToggleFlowRequestSchema", "ToggleFlowResponseSchema", "TransportProtocol", "TriggerFlowRequestSchema", "TriggerFlowResponseSchema", "UninstallPackageApiResponseSchema", "UnpinFeedItemResponseSchema", "UnregisterDeviceRequestSchema", "UnregisterDeviceResponseSchema", "UnstarFeedItemResponseSchema", "UnsubscribeMessageSchema", "UnsubscribeRequestSchema", "UnsubscribeResponseSchema", "UpdateDataRequestSchema", "UpdateDataResponseSchema", "UpdateFeedItemRequestSchema", "UpdateFeedItemResponseSchema", "UpdateFlowRequestSchema", "UpdateFlowResponseSchema", "UpdateManyDataRequestSchema", "UpdateManyRequestSchema", "UpdateNotificationPreferencesRequestSchema", "UpdateNotificationPreferencesResponseSchema", "UpdateRequestSchema", "UpdateViewRequestSchema", "UpdateViewResponseSchema", "UploadArtifactRequestSchema", "UploadArtifactResponseSchema", "UploadChunkRequestSchema", "UploadChunkResponseSchema", "UploadProgressSchema", "UserProfileResponseSchema", "ValidationMode", "VersionDefinitionSchema", "VersionNegotiationResponseSchema", "VersionStatus", "VersioningStrategy", "WebSocketConfigSchema", "WebSocketEventSchema", "WebSocketMessageSchema", "WebSocketMessageType", "WebSocketPresenceStatus", "WebSocketServerConfigSchema", "WebhookConfigSchema", "WebhookEventSchema", "WellKnownCapabilitiesSchema", "WorkflowApproveRequestSchema", "WorkflowApproveResponseSchema", "WorkflowRejectRequestSchema", "WorkflowRejectResponseSchema", "WorkflowStateSchema", "WorkflowTransitionRequestSchema", "WorkflowTransitionResponseSchema", "BaseWebSocketMessage", "WorkflowTriggerType", "FieldUpdateActionSchema", "EmailAlertActionSchema", "ConnectorActionRefSchema", "HttpCallActionSchema", "TaskCreationActionSchema", "PushNotificationActionSchema", "CustomScriptActionSchema", "WorkflowActionSchema", "TimeTriggerSchema", "WorkflowRuleSchema", "FlowNodeAction", "FlowVariableSchema", "FlowNodeSchema", "FlowEdgeSchema", "FlowSchema", "ExecutionStatus", "ExecutionStepLogSchema", "ExecutionLogSchema", "ExecutionErrorSeverity", "ConnectorSchema", "ConnectorTriggerSchema", "DataSyncConfigSchema", "__export", "ActivationEventSchema", "z", "ManifestSchema", "DatasourceSchema", "TranslationBundleSchema", "TranslationConfigSchema", "ObjectSchema", "ObjectExtensionSchema", "AppSchema", "ViewSchema", "PageSchema", "DashboardSchema", "ReportSchema", "ActionSchema", "ThemeSchema", "WorkflowRuleSchema", "FlowSchema", "PermissionSetSchema", "ApiEndpointSchema", "HookSchema", "MappingSchema", "CubeSchema", "ConnectorSchema", "DatasetSchema", "config", "z", "z", "FeatureFlagSchema", "ApiEndpointSchema", "Task", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "ObjectSchema", "Task", "ObjectSchema", "CrmApp", "objects_exports", "Task", "Task", "ObjectSchema", "actions_exports", "ExportToCsvAction", "ExportToCsvAction", "dashboards_exports", "reports_exports", "TasksByOwnerReport", "TasksByOwnerReport", "allFlows", "apps_exports", "translations_exports", "en", "zhCN", "jaJP", "en", "zhCN", "jaJP", "objectstack_config_default", "objects_exports", "actions_exports", "dashboards_exports", "reports_exports", "allFlows", "apps_exports", "translations_exports", "objectstack_config_default", "objectstack_config_default", "env", "message", "url", "config"] -} From 60db1ea5db327c0dd83cbc0a8db5f9fbe7df544a Mon Sep 17 00:00:00 2001 From: Jack Zhuang <50353452+hotlong@users.noreply.github.com> Date: Tue, 14 Apr 2026 09:31:01 +0800 Subject: [PATCH 4/8] fix: update better-sqlite3 dependency to version 12.9.0 --- examples/app-host/package.json | 2 +- pnpm-lock.yaml | 12 ++---------- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/examples/app-host/package.json b/examples/app-host/package.json index f0bef2a2b..bf8298ae8 100644 --- a/examples/app-host/package.json +++ b/examples/app-host/package.json @@ -25,7 +25,7 @@ "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/runtime": "workspace:*", "@objectstack/spec": "workspace:*", - "better-sqlite3": "^11.8.1", + "better-sqlite3": "^12.9.0", "hono": "^4.12.12" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 71b307939..9585e8922 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -367,8 +367,8 @@ importers: specifier: workspace:* version: link:../../packages/spec better-sqlite3: - specifier: ^11.8.1 - version: 11.10.0 + specifier: ^12.9.0 + version: 12.9.0 hono: specifier: ^4.12.12 version: 4.12.12 @@ -4256,9 +4256,6 @@ packages: resolution: {integrity: sha512-pbnl5XzGBdrFU/wT4jqmJVPn2B6UHPBOhzMQkY/SPUPB6QtUXtmBHBIwCbXJol93mOpGMnQyP/+BB19q04xj7g==} engines: {node: '>=4'} - better-sqlite3@11.10.0: - resolution: {integrity: sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==} - better-sqlite3@12.9.0: resolution: {integrity: sha512-wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==} engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x} @@ -10492,11 +10489,6 @@ snapshots: dependencies: is-windows: 1.0.2 - better-sqlite3@11.10.0: - dependencies: - bindings: 1.5.0 - prebuild-install: 7.1.3 - better-sqlite3@12.9.0: dependencies: bindings: 1.5.0 From fbf4686e9fa7a0015e9223a10c0a2837c30f9bac Mon Sep 17 00:00:00 2001 From: "anthropic-code-agent[bot]" <242468646+Claude@users.noreply.github.com> Date: Tue, 14 Apr 2026 03:40:01 +0000 Subject: [PATCH 5/8] fix: set framework to "hono" in vercel.json per Vercel Hono docs Agent-Logs-Url: https://github.com/objectstack-ai/framework/sessions/733752b6-7f54-4d4e-99b1-edbc5cf6a176 Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com> --- examples/app-host/vercel.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/app-host/vercel.json b/examples/app-host/vercel.json index 74cb1e609..025616091 100644 --- a/examples/app-host/vercel.json +++ b/examples/app-host/vercel.json @@ -1,6 +1,6 @@ { "$schema": "https://openapi.vercel.sh/vercel.json", - "framework": null, + "framework": "hono", "installCommand": "cd ../.. && pnpm install", "buildCommand": "bash scripts/build-vercel.sh", "functions": { From 6c106d135e55eddd6f5696400f58f37e15e1d434 Mon Sep 17 00:00:00 2001 From: "anthropic-code-agent[bot]" <242468646+Claude@users.noreply.github.com> Date: Tue, 14 Apr 2026 03:56:40 +0000 Subject: [PATCH 6/8] fix: use TursoDriver instead of InMemoryDriver, remove unnecessary better-sqlite3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace InMemoryDriver with TursoDriver (remote mode for Vercel) - Add @libsql/client and @objectstack/driver-turso dependencies - Remove better-sqlite3 dependency (not needed for Turso remote mode) - Remove better-sqlite3 from esbuild externals and vercel.json includeFiles - Remove better-sqlite3 copy logic from build-vercel.sh - Add .env.example with Turso configuration - Update DEPLOYMENT.md with Turso environment variables and troubleshooting Turso remote mode uses HTTP-only connection via @libsql/client, which doesn't require native bindings like better-sqlite3. This makes the deployment simpler and more suitable for serverless environments. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com> --- examples/app-host/.env.example | 4 ++++ examples/app-host/DEPLOYMENT.md | 21 ++++++++++++++------- examples/app-host/package.json | 3 ++- examples/app-host/scripts/build-vercel.sh | 23 ----------------------- examples/app-host/scripts/bundle-api.mjs | 1 - examples/app-host/server/index.ts | 19 ++++++++++++++++--- examples/app-host/vercel.json | 3 +-- 7 files changed, 37 insertions(+), 37 deletions(-) create mode 100644 examples/app-host/.env.example diff --git a/examples/app-host/.env.example b/examples/app-host/.env.example new file mode 100644 index 000000000..0389ec433 --- /dev/null +++ b/examples/app-host/.env.example @@ -0,0 +1,4 @@ +# Turso Database Configuration +# Required for Vercel deployment +TURSO_DATABASE_URL=libsql://your-database.turso.io +TURSO_AUTH_TOKEN=your-auth-token-here diff --git a/examples/app-host/DEPLOYMENT.md b/examples/app-host/DEPLOYMENT.md index fe2f6938e..ad303f173 100644 --- a/examples/app-host/DEPLOYMENT.md +++ b/examples/app-host/DEPLOYMENT.md @@ -12,6 +12,10 @@ This example demonstrates how to deploy the ObjectStack app-host to Vercel using Set the following environment variables in your Vercel project: - `AUTH_SECRET`: A secure random string (minimum 32 characters) for authentication +- `TURSO_DATABASE_URL`: Your Turso database URL (e.g., `libsql://your-database.turso.io`) +- `TURSO_AUTH_TOKEN`: Your Turso authentication token + +You can get these credentials from [Turso Dashboard](https://turso.tech/). ## Deployment Steps @@ -35,6 +39,8 @@ Set the following environment variables in your Vercel project: 4. Set environment variables: ```bash vercel env add AUTH_SECRET + vercel env add TURSO_DATABASE_URL + vercel env add TURSO_AUTH_TOKEN ``` ### Option 2: Using Vercel Dashboard @@ -50,14 +56,13 @@ The build is configured in `vercel.json`: - **Install Command**: `cd ../.. && pnpm install` (installs monorepo dependencies) - **Build Command**: `bash scripts/build-vercel.sh` (builds and bundles the application) -- **Framework**: `null` (uses custom build setup) +- **Framework**: `hono` (uses Vercel's Hono framework preset) ## How It Works 1. **Build Process** (`scripts/build-vercel.sh`): - Builds the TypeScript project using Turbo - Bundles the server code using esbuild (`scripts/bundle-api.mjs`) - - Copies native dependencies (like better-sqlite3) to local node_modules 2. **API Handler** (`api/[[...route]].js`): - Committed catch-all route handler that Vercel detects pre-build @@ -66,6 +71,7 @@ The build is configured in `vercel.json`: 3. **Server Entrypoint** (`server/index.ts`): - Boots ObjectStack kernel with Hono adapter - Uses `@hono/node-server`'s `getRequestListener()` for Vercel compatibility + - Connects to Turso database in remote mode (HTTP-only, no local SQLite) - Handles Vercel's pre-buffered request body properly 4. **Hono Integration**: @@ -125,14 +131,15 @@ After deployment, your API will be available at: ### Runtime Errors - Check function logs in Vercel dashboard -- Verify environment variables are set correctly +- Verify environment variables are set correctly (`TURSO_DATABASE_URL`, `TURSO_AUTH_TOKEN`, `AUTH_SECRET`) - Ensure `AUTH_SECRET` is at least 32 characters +- Test Turso connection using the provided credentials -### Module Not Found +### Database Connection Issues -- The build script copies native modules to local node_modules -- Check that `better-sqlite3` is in dependencies -- Verify `vercel.json` includeFiles pattern matches the module +- Verify your Turso database URL and auth token are correct +- Check that your Turso database is accessible (not paused) +- The deployment uses TursoDriver in **remote mode** (HTTP-only), which doesn't require native modules like better-sqlite3 ## References diff --git a/examples/app-host/package.json b/examples/app-host/package.json index 8b4bd18c5..626c61c4a 100644 --- a/examples/app-host/package.json +++ b/examples/app-host/package.json @@ -17,7 +17,9 @@ "@example/app-todo": "workspace:*", "@example/plugin-bi": "workspace:*", "@hono/node-server": "^1.19.14", + "@libsql/client": "^0.14.0", "@objectstack/driver-memory": "workspace:*", + "@objectstack/driver-turso": "workspace:*", "@objectstack/hono": "workspace:*", "@objectstack/metadata": "workspace:*", "@objectstack/objectql": "workspace:*", @@ -25,7 +27,6 @@ "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/runtime": "workspace:*", "@objectstack/spec": "workspace:*", - "better-sqlite3": "^12.9.0", "hono": "^4.12.12" }, "devDependencies": { diff --git a/examples/app-host/scripts/build-vercel.sh b/examples/app-host/scripts/build-vercel.sh index a7e8460fc..aba537113 100755 --- a/examples/app-host/scripts/build-vercel.sh +++ b/examples/app-host/scripts/build-vercel.sh @@ -23,27 +23,4 @@ cd examples/app-host # 2. Bundle API serverless function node scripts/bundle-api.mjs -# 3. Copy native/external modules into local node_modules for Vercel packaging. -# -# This monorepo uses pnpm's default strict node_modules structure. Transitive -# native dependencies like better-sqlite3 only exist in the monorepo root's -# node_modules/.pnpm/ virtual store — they're NOT symlinked into -# examples/app-host/node_modules/. -# -# The vercel.json includeFiles pattern references node_modules/ relative to -# examples/app-host/, so we must copy the actual module files here for Vercel -# to include them in the serverless function's deployment package. -echo "[build-vercel] Copying external native modules to local node_modules..." -for mod in better-sqlite3; do - src="../../node_modules/$mod" - if [ -e "$src" ]; then - dest="node_modules/$mod" - mkdir -p "$(dirname "$dest")" - cp -rL "$src" "$dest" - echo "[build-vercel] ✓ Copied $mod" - else - echo "[build-vercel] ⚠ $mod not found at $src (skipped)" - fi -done - echo "[build-vercel] Done. Serverless function in api/[[...route]].js → api/_handler.js" diff --git a/examples/app-host/scripts/bundle-api.mjs b/examples/app-host/scripts/bundle-api.mjs index c252a084e..cc87745c8 100644 --- a/examples/app-host/scripts/bundle-api.mjs +++ b/examples/app-host/scripts/bundle-api.mjs @@ -16,7 +16,6 @@ import { build } from 'esbuild'; // Packages that cannot be bundled (native bindings / optional drivers) const EXTERNAL = [ - 'better-sqlite3', // Optional knex database drivers — never used at runtime, but knex requires() them 'pg', 'pg-native', diff --git a/examples/app-host/server/index.ts b/examples/app-host/server/index.ts index 0f296a485..59e516966 100644 --- a/examples/app-host/server/index.ts +++ b/examples/app-host/server/index.ts @@ -12,7 +12,7 @@ import { ObjectKernel, DriverPlugin, AppPlugin } from '@objectstack/runtime'; import { ObjectQLPlugin } from '@objectstack/objectql'; -import { InMemoryDriver } from '@objectstack/driver-memory'; +import { TursoDriver } from '@objectstack/driver-turso'; import { createHonoApp } from '@objectstack/hono'; import { AuthPlugin } from '@objectstack/plugin-auth'; import { getRequestListener } from '@hono/node-server'; @@ -54,8 +54,21 @@ async function ensureKernel(): Promise { // Register ObjectQL engine await kernel.use(new ObjectQLPlugin()); - // Database driver (in-memory for demo) - await kernel.use(new DriverPlugin(new InMemoryDriver())); + // Database driver - Turso (remote mode for Vercel) + const tursoUrl = process.env.TURSO_DATABASE_URL; + const tursoToken = process.env.TURSO_AUTH_TOKEN; + + if (!tursoUrl || !tursoToken) { + throw new Error('Missing required environment variables: TURSO_DATABASE_URL and TURSO_AUTH_TOKEN'); + } + + const tursoDriver = new TursoDriver({ + url: tursoUrl, + authToken: tursoToken, + // Remote mode - no local sync needed for Vercel + }); + + await kernel.use(new DriverPlugin(tursoDriver)); // Auth plugin — uses environment variables for configuration // Prefer VERCEL_PROJECT_PRODUCTION_URL (stable across deployments) diff --git a/examples/app-host/vercel.json b/examples/app-host/vercel.json index 025616091..2115782da 100644 --- a/examples/app-host/vercel.json +++ b/examples/app-host/vercel.json @@ -6,8 +6,7 @@ "functions": { "api/**/*.js": { "memory": 1024, - "maxDuration": 60, - "includeFiles": "node_modules/better-sqlite3/**" + "maxDuration": 60 } }, "rewrites": [ From ee32099e7cf430edf9aac59750eb036b8fec68c4 Mon Sep 17 00:00:00 2001 From: "anthropic-code-agent[bot]" <242468646+Claude@users.noreply.github.com> Date: Tue, 14 Apr 2026 04:07:42 +0000 Subject: [PATCH 7/8] fix: address PR review feedback - add type: module, fix .vercelignore, remove unused .npmrc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add "type": "module" to package.json for ESM compatibility (Vercel handler is ESM) - Fix .vercelignore to not exclude build dependencies (server/, scripts/bundle-api.mjs) - Remove app-specific .npmrc (not honored when install runs from monorepo root) These changes address feedback from @copilot-pull-request-reviewer: 1. ESM files require "type": "module" in package.json (matches apps/studio pattern) 2. Build script needs access to server/ and scripts/ during Vercel build 3. .npmrc node-linker=hoisted is unnecessary with Turso remote mode (no native modules) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com> --- examples/app-host/.npmrc | 3 --- examples/app-host/.vercelignore | 10 +--------- examples/app-host/package.json | 1 + 3 files changed, 2 insertions(+), 12 deletions(-) delete mode 100644 examples/app-host/.npmrc diff --git a/examples/app-host/.npmrc b/examples/app-host/.npmrc deleted file mode 100644 index 1501d084b..000000000 --- a/examples/app-host/.npmrc +++ /dev/null @@ -1,3 +0,0 @@ -# Vercel deployment configuration -# Use hoisted node_modules to prevent symlink issues -node-linker=hoisted diff --git a/examples/app-host/.vercelignore b/examples/app-host/.vercelignore index 97d9553bc..b6b512ed9 100644 --- a/examples/app-host/.vercelignore +++ b/examples/app-host/.vercelignore @@ -7,16 +7,8 @@ test/ *.test.ts *.spec.ts -# Ignore development files +# Ignore development-only files that are not required by the Vercel build debug-registry.ts -src/ - -# Ignore source files (only need the bundle) -server/ -scripts/bundle-api.mjs - -# Ignore metadata (using in-memory driver) -metadata/ # Keep only the bundled API handler !api/_handler.js diff --git a/examples/app-host/package.json b/examples/app-host/package.json index 626c61c4a..64e89c7b3 100644 --- a/examples/app-host/package.json +++ b/examples/app-host/package.json @@ -2,6 +2,7 @@ "name": "@example/app-host", "version": "4.0.3", "license": "Apache-2.0", + "type": "module", "private": true, "scripts": { "dev": "objectstack serve --dev", From 0d115e82cb59d9f652e8e8c1f1ded84ba0781f4d Mon Sep 17 00:00:00 2001 From: "anthropic-code-agent[bot]" <242468646+Claude@users.noreply.github.com> Date: Tue, 14 Apr 2026 04:10:27 +0000 Subject: [PATCH 8/8] chore: update pnpm-lock.yaml after dependency changes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regenerate lockfile to reflect package.json changes: - Added @libsql/client and @objectstack/driver-turso to examples/app-host - Removed better-sqlite3 from examples/app-host - Added "type": "module" to examples/app-host Fixes ERR_PNPM_OUTDATED_LOCKFILE in CI. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com> --- pnpm-lock.yaml | 309 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 213 insertions(+), 96 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5ab97b268..d50c0cdb5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -132,16 +132,16 @@ importers: version: 3.0.69(zod@4.3.6) '@ai-sdk/gateway': specifier: ^3.0.95 - version: 3.0.95(zod@4.3.6) + version: 3.0.96(zod@4.3.6) '@ai-sdk/google': specifier: ^3.0.62 - version: 3.0.62(zod@4.3.6) + version: 3.0.63(zod@4.3.6) '@ai-sdk/openai': specifier: ^3.0.52 version: 3.0.52(zod@4.3.6) '@ai-sdk/react': specifier: ^3.0.160 - version: 3.0.160(react@19.2.5)(zod@4.3.6) + version: 3.0.161(react@19.2.5)(zod@4.3.6) '@hono/node-server': specifier: ^1.19.14 version: 1.19.14(hono@4.12.12) @@ -246,7 +246,7 @@ importers: version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) ai: specifier: ^6.0.158 - version: 6.0.158(zod@4.3.6) + version: 6.0.159(zod@4.3.6) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -289,16 +289,16 @@ importers: version: 6.0.1(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) autoprefixer: specifier: ^10.4.27 - version: 10.4.27(postcss@8.5.9) + version: 10.5.0(postcss@8.5.9) esbuild: specifier: ^0.28.0 version: 0.28.0 happy-dom: specifier: ^20.8.9 - version: 20.8.9 + version: 20.9.0 msw: specifier: ^2.13.2 - version: 2.13.2(@types/node@25.6.0)(typescript@6.0.2) + version: 2.13.3(@types/node@25.6.0)(typescript@6.0.2) postcss: specifier: ^8.5.9 version: 8.5.9 @@ -313,7 +313,7 @@ importers: version: 8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3) vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) examples/app-crm: dependencies: @@ -342,9 +342,15 @@ importers: '@hono/node-server': specifier: ^1.19.14 version: 1.19.14(hono@4.12.12) + '@libsql/client': + specifier: ^0.14.0 + version: 0.14.0 '@objectstack/driver-memory': specifier: workspace:* version: link:../../packages/plugins/driver-memory + '@objectstack/driver-turso': + specifier: workspace:* + version: link:../../packages/plugins/driver-turso '@objectstack/hono': specifier: workspace:* version: link:../../packages/adapters/hono @@ -366,9 +372,6 @@ importers: '@objectstack/spec': specifier: workspace:* version: link:../../packages/spec - better-sqlite3: - specifier: ^12.9.0 - version: 12.9.0 hono: specifier: ^4.12.12 version: 4.12.12 @@ -440,7 +443,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/adapters/fastify: devDependencies: @@ -455,7 +458,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/adapters/hono: devDependencies: @@ -470,7 +473,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/adapters/nestjs: devDependencies: @@ -488,7 +491,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/adapters/nextjs: devDependencies: @@ -509,7 +512,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/adapters/nuxt: devDependencies: @@ -524,7 +527,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/adapters/sveltekit: devDependencies: @@ -539,13 +542,13 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/cli: dependencies: '@ai-sdk/gateway': specifier: ^3.0.95 - version: 3.0.95(zod@4.3.6) + version: 3.0.96(zod@4.3.6) '@objectstack/client': specifier: workspace:* version: link:../client @@ -615,7 +618,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/client: dependencies: @@ -649,13 +652,13 @@ importers: version: link:../runtime msw: specifier: ^2.13.2 - version: 2.13.2(@types/node@25.6.0)(typescript@6.0.2) + version: 2.13.3(@types/node@25.6.0)(typescript@6.0.2) typescript: specifier: ^6.0.2 version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/client-react: dependencies: @@ -702,7 +705,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/create-objectstack: dependencies: @@ -758,7 +761,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/objectql: dependencies: @@ -777,7 +780,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/driver-memory: dependencies: @@ -799,7 +802,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/driver-sql: dependencies: @@ -827,7 +830,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/driver-turso: dependencies: @@ -858,7 +861,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/plugin-audit: dependencies: @@ -877,7 +880,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/plugin-auth: dependencies: @@ -902,7 +905,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/plugin-dev: dependencies: @@ -948,7 +951,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/plugin-hono-server: dependencies: @@ -973,7 +976,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/plugin-mcp-server: dependencies: @@ -998,7 +1001,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/plugin-msw: dependencies: @@ -1016,7 +1019,7 @@ importers: version: link:../../types msw: specifier: ^2.13.2 - version: 2.13.2(@types/node@25.6.0)(typescript@6.0.2) + version: 2.13.3(@types/node@25.6.0)(typescript@6.0.2) devDependencies: '@objectstack/runtime': specifier: workspace:* @@ -1029,7 +1032,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/plugin-security: dependencies: @@ -1048,7 +1051,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/plugins/plugin-setup: dependencies: @@ -1067,7 +1070,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/rest: dependencies: @@ -1086,7 +1089,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/runtime: dependencies: @@ -1111,7 +1114,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-ai: dependencies: @@ -1120,10 +1123,10 @@ importers: version: 3.0.69(zod@4.3.6) '@ai-sdk/gateway': specifier: ^3.0.0 - version: 3.0.95(zod@4.3.6) + version: 3.0.96(zod@4.3.6) '@ai-sdk/google': specifier: ^3.0.0 - version: 3.0.62(zod@4.3.6) + version: 3.0.63(zod@4.3.6) '@ai-sdk/openai': specifier: ^3.0.0 version: 3.0.52(zod@4.3.6) @@ -1138,7 +1141,7 @@ importers: version: link:../../spec ai: specifier: ^6.0.158 - version: 6.0.158(zod@4.3.6) + version: 6.0.159(zod@4.3.6) devDependencies: '@types/node': specifier: ^25.6.0 @@ -1148,7 +1151,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-analytics: dependencies: @@ -1167,7 +1170,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-automation: dependencies: @@ -1186,7 +1189,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-cache: dependencies: @@ -1205,7 +1208,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-feed: dependencies: @@ -1224,7 +1227,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-i18n: dependencies: @@ -1243,7 +1246,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-job: dependencies: @@ -1262,7 +1265,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-queue: dependencies: @@ -1281,7 +1284,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-realtime: dependencies: @@ -1300,7 +1303,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/services/service-storage: dependencies: @@ -1319,13 +1322,13 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/spec: dependencies: ai: specifier: ^6.0.158 - version: 6.0.158(zod@4.3.6) + version: 6.0.159(zod@4.3.6) zod: specifier: ^4.3.6 version: 4.3.6 @@ -1344,7 +1347,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + version: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) packages/types: dependencies: @@ -1376,14 +1379,14 @@ packages: peerDependencies: zod: ^3.25.76 || ^4.1.8 - '@ai-sdk/gateway@3.0.95': - resolution: {integrity: sha512-ZmUNNbZl3V42xwQzPaNUi+s8eqR2lnrxf0bvB6YbLXpLjHYv0k2Y78t12cNOfY0bxGeuVVTLyk856uLuQIuXEQ==} + '@ai-sdk/gateway@3.0.96': + resolution: {integrity: sha512-BDiVEMUVHGpngReeigzLyJobG0TvzYbNGzdHI8JYBZHrjOX4aL6qwIls7z3p7V4TuXVWUCbG8TSWEe7ksX4Vhw==} engines: {node: '>=18'} peerDependencies: zod: ^3.25.76 || ^4.1.8 - '@ai-sdk/google@3.0.62': - resolution: {integrity: sha512-cC9HAjR5WZxjqGyEJrJqFTlVqyPE9UOFmmGdf5dINaimgfPmzqXYN1qTYEJ+1knbyTVsNMub0KAF5SOqqtO8IQ==} + '@ai-sdk/google@3.0.63': + resolution: {integrity: sha512-RfOZWVMYSPu2sPRfGajrauWAZ9BSaRopSn+AszkKWQ1MFj8nhaXvCqRHB5pBQUaHTfZKagvOmMpNfa/s3gPLgQ==} engines: {node: '>=18'} peerDependencies: zod: ^3.25.76 || ^4.1.8 @@ -1404,8 +1407,8 @@ packages: resolution: {integrity: sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==} engines: {node: '>=18'} - '@ai-sdk/react@3.0.160': - resolution: {integrity: sha512-ZDD42ggZYyBJjiX3PAl03t58uMJsIgreHfRhbdQR0hyuGlxcg1nXS5OvPRQUejNyGz/cM24/uGzt3Mn5ncdoOQ==} + '@ai-sdk/react@3.0.161': + resolution: {integrity: sha512-lFIZm7OggwNZD08Yz8ip0EPgmEn/lKZOB2MrKjzDpq6BT8gUX17TfaaUi9IICN8nOeLOZQqJKrWNnTXjcvElBw==} engines: {node: '>=18'} peerDependencies: react: ^18 || ~19.0.1 || ~19.1.2 || ^19.2.1 @@ -2373,25 +2376,48 @@ packages: '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} + '@libsql/client@0.14.0': + resolution: {integrity: sha512-/9HEKfn6fwXB5aTEEoMeFh4CtG0ZzbncBb1e++OCdVpgKZ/xyMsIVYXm0w7Pv4RUel803vE6LwniB3PqD72R0Q==} + '@libsql/client@0.17.2': resolution: {integrity: sha512-0aw0S3iQMHvOxfRt5j1atoCCPMT3gjsB2PS8/uxSM1DcDn39xqz6RlgSMxtP8I3JsxIXAFuw7S41baLEw0Zi+Q==} + '@libsql/core@0.14.0': + resolution: {integrity: sha512-nhbuXf7GP3PSZgdCY2Ecj8vz187ptHlZQ0VRc751oB2C1W8jQUXKKklvt7t1LJiUTQBVJuadF628eUk+3cRi4Q==} + '@libsql/core@0.17.2': resolution: {integrity: sha512-L8qv12HZ/jRBcETVR3rscP0uHNxh+K3EABSde6scCw7zfOdiLqO3MAkJaeE1WovPsjXzsN/JBoZED4+7EZVT3g==} + '@libsql/darwin-arm64@0.4.7': + resolution: {integrity: sha512-yOL742IfWUlUevnI5PdnIT4fryY3LYTdLm56bnY0wXBw7dhFcnjuA7jrH3oSVz2mjZTHujxoITgAE7V6Z+eAbg==} + cpu: [arm64] + os: [darwin] + '@libsql/darwin-arm64@0.5.29': resolution: {integrity: sha512-K+2RIB1OGFPYQbfay48GakLhqf3ArcbHqPFu7EZiaUcRgFcdw8RoltsMyvbj5ix2fY0HV3Q3Ioa/ByvQdaSM0A==} cpu: [arm64] os: [darwin] + '@libsql/darwin-x64@0.4.7': + resolution: {integrity: sha512-ezc7V75+eoyyH07BO9tIyJdqXXcRfZMbKcLCeF8+qWK5nP8wWuMcfOVywecsXGRbT99zc5eNra4NEx6z5PkSsA==} + cpu: [x64] + os: [darwin] + '@libsql/darwin-x64@0.5.29': resolution: {integrity: sha512-OtT+KFHsKFy1R5FVadr8FJ2Bb1mghtXTyJkxv0trocq7NuHntSki1eUbxpO5ezJesDvBlqFjnWaYYY516QNLhQ==} cpu: [x64] os: [darwin] + '@libsql/hrana-client@0.7.0': + resolution: {integrity: sha512-OF8fFQSkbL7vJY9rfuegK1R7sPgQ6kFMkDamiEccNUvieQ+3urzfDFI616oPl8V7T9zRmnTkSjMOImYCAVRVuw==} + '@libsql/hrana-client@0.9.0': resolution: {integrity: sha512-pxQ1986AuWfPX4oXzBvLwBnfgKDE5OMhAdR/5cZmRaB4Ygz5MecQybvwZupnRz341r2CtFmbk/BhSu7k2Lm+Jw==} + '@libsql/isomorphic-fetch@0.3.1': + resolution: {integrity: sha512-6kK3SUK5Uu56zPq/Las620n5aS9xJq+jMBcNSOmjhNf/MUvdyji4vrMTqD7ptY7/4/CAVEAYDeotUz60LNQHtw==} + engines: {node: '>=18.0.0'} + '@libsql/isomorphic-ws@0.1.5': resolution: {integrity: sha512-DtLWIH29onUYR00i0GlQ3UdcTRC6EP4u9w/h9LxpUZJWRMARk6dQwZ6Jkd+QdwVpuAOrdxt18v0K2uIYR3fwFg==} @@ -2405,26 +2431,51 @@ packages: cpu: [arm] os: [linux] + '@libsql/linux-arm64-gnu@0.4.7': + resolution: {integrity: sha512-WlX2VYB5diM4kFfNaYcyhw5y+UJAI3xcMkEUJZPtRDEIu85SsSFrQ+gvoKfcVh76B//ztSeEX2wl9yrjF7BBCA==} + cpu: [arm64] + os: [linux] + '@libsql/linux-arm64-gnu@0.5.29': resolution: {integrity: sha512-gURBqaiXIGGwFNEaUj8Ldk7Hps4STtG+31aEidCk5evMMdtsdfL3HPCpvys+ZF/tkOs2MWlRWoSq7SOuCE9k3w==} cpu: [arm64] os: [linux] + '@libsql/linux-arm64-musl@0.4.7': + resolution: {integrity: sha512-6kK9xAArVRlTCpWeqnNMCoXW1pe7WITI378n4NpvU5EJ0Ok3aNTIC2nRPRjhro90QcnmLL1jPcrVwO4WD1U0xw==} + cpu: [arm64] + os: [linux] + '@libsql/linux-arm64-musl@0.5.29': resolution: {integrity: sha512-fwgYZ0H8mUkyVqXZHF3mT/92iIh1N94Owi/f66cPVNsk9BdGKq5gVpoKO+7UxaNzuEH1roJp2QEwsCZMvBLpqg==} cpu: [arm64] os: [linux] + '@libsql/linux-x64-gnu@0.4.7': + resolution: {integrity: sha512-CMnNRCmlWQqqzlTw6NeaZXzLWI8bydaXDke63JTUCvu8R+fj/ENsLrVBtPDlxQ0wGsYdXGlrUCH8Qi9gJep0yQ==} + cpu: [x64] + os: [linux] + '@libsql/linux-x64-gnu@0.5.29': resolution: {integrity: sha512-y14V0vY0nmMC6G0pHeJcEarcnGU2H6cm21ZceRkacWHvQAEhAG0latQkCtoS2njFOXiYIg+JYPfAoWKbi82rkg==} cpu: [x64] os: [linux] + '@libsql/linux-x64-musl@0.4.7': + resolution: {integrity: sha512-nI6tpS1t6WzGAt1Kx1n1HsvtBbZ+jHn0m7ogNNT6pQHZQj7AFFTIMeDQw/i/Nt5H38np1GVRNsFe99eSIMs9XA==} + cpu: [x64] + os: [linux] + '@libsql/linux-x64-musl@0.5.29': resolution: {integrity: sha512-gquqwA/39tH4pFl+J9n3SOMSymjX+6kZ3kWgY3b94nXFTwac9bnFNMffIomgvlFaC4ArVqMnOZD3nuJ3H3VO1w==} cpu: [x64] os: [linux] + '@libsql/win32-x64-msvc@0.4.7': + resolution: {integrity: sha512-7pJzOWzPm6oJUxml+PCDRzYQ4A1hTMHAciTAHfFK4fkbDZX33nWPVG7Y3vqdKtslcwAzwmrNDc6sXy2nwWnbiw==} + cpu: [x64] + os: [win32] + '@libsql/win32-x64-msvc@0.5.29': resolution: {integrity: sha512-4/0CvEdhi6+KjMxMaVbFM2n2Z44escBRoEYpR+gZg64DdetzGnYm8mcNLcoySaDJZNaBd6wz5DNdgRmcI4hXcg==} cpu: [x64] @@ -3922,8 +3973,8 @@ packages: resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} engines: {node: '>= 14'} - ai@6.0.158: - resolution: {integrity: sha512-gLTp1UXFtMqKUi3XHs33K7UFglbvojkxF/aq337TxnLGOhHIW9+GyP2jwW4hYX87f1es+wId3VQoPRRu9zEStQ==} + ai@6.0.159: + resolution: {integrity: sha512-S18ozG7Dkm3Ud1tzOtAK5acczD4vygfml80RkpM9VWMFpvAFwAKSHaGYkATvPQHIE+VpD1tJY9zcTXLZ/zR5cw==} engines: {node: '>=18'} peerDependencies: zod: ^3.25.76 || ^4.1.8 @@ -4016,8 +4067,8 @@ packages: resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==} engines: {node: '>=8.0.0'} - autoprefixer@10.4.27: - resolution: {integrity: sha512-NP9APE+tO+LuJGn7/9+cohklunJsXWiaWEfV3si4Gi/XHDwVNgkwr1J3RQYFIvPy76GmJ9/bW8vyoU1LcxwKHA==} + autoprefixer@10.5.0: + resolution: {integrity: sha512-FMhOoZV4+qR6aTUALKX2rEqGG+oyATvwBt9IIzVR5rMa2HRWPkxf+P+PAJLD1I/H5/II+HuZcBJYEFBpq39ong==} engines: {node: ^10 || ^12 || >=14} hasBin: true peerDependencies: @@ -4520,8 +4571,8 @@ packages: engines: {node: '>=0.10.0'} hasBin: true - electron-to-chromium@1.5.335: - resolution: {integrity: sha512-q9n5T4BR4Xwa2cwbrwcsDJtHD/enpQ5S1xF1IAtdqf5AAgqDFmR/aakqH3ChFdqd/QXJhS3rnnXFtexU7rax6Q==} + electron-to-chromium@1.5.336: + resolution: {integrity: sha512-AbH9q9J455r/nLmdNZes0G0ZKcRX73FicwowalLs6ijwOmCJSRRrLX63lcAlzy9ux3dWK1w1+1nsBJEWN11hcQ==} emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} @@ -5012,8 +5063,8 @@ packages: h3@1.15.11: resolution: {integrity: sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==} - happy-dom@20.8.9: - resolution: {integrity: sha512-Tz23LR9T9jOGVZm2x1EPdXqwA37G/owYMxRwU0E4miurAtFsPMQ1d2Jc2okUaSjZqAFz2oEn3FLXC5a0a+siyA==} + happy-dom@20.9.0: + resolution: {integrity: sha512-GZZ9mKe8r646NUAf/zemnGbjYh4Bt8/MqASJY+pSm5ZDtc3YQox+4gsLI7yi1hba6o+eCsGxpHn5+iEVn31/FQ==} engines: {node: '>=20.0.0'} has-flag@4.0.0: @@ -5382,6 +5433,11 @@ packages: resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==} engines: {node: '>=6'} + libsql@0.4.7: + resolution: {integrity: sha512-T9eIRCs6b0J1SHKYIvD8+KCJMcWZ900iZyxdnSCdqxN12Z1ijzT+jY5nrk72Jw4B0HGzms2NgpryArlJqvc3Lw==} + cpu: [x64, arm64, wasm32] + os: [darwin, linux, win32] + libsql@0.5.29: resolution: {integrity: sha512-8lMP8iMgiBzzoNbAPQ59qdVcj6UaE/Vnm+fiwX4doX4Narook0a4GPKWBEv+CR8a1OwbfkgL18uBfBjWdF0Fzg==} cpu: [x64, arm64, wasm32, arm] @@ -5821,8 +5877,8 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - msw@2.13.2: - resolution: {integrity: sha512-go2H1TIERKkC48pXiwec5l6sbNqYuvqOk3/vHGo1Zd+pq/H63oFawDQerH+WQdUw/flJFHDG7F+QdWMwhntA/A==} + msw@2.13.3: + resolution: {integrity: sha512-/F49bxavkNGfreMlrKmTxZs6YorjfMbbDLd89Q3pWi+cXGtQQNXXaHt4MkXN7li91xnQJ24HWXqW9QDm5id33w==} engines: {node: '>=18'} hasBin: true peerDependencies: @@ -6446,8 +6502,8 @@ packages: resolution: {integrity: sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==} engines: {node: '>=10'} - rettime@0.10.1: - resolution: {integrity: sha512-uyDrIlUEH37cinabq0AX4QbgV4HbFZ/gqoiunWQ1UqBtRvTTytwhNYjE++pO/MjPTZL5KQCf2bEoJ/BJNVQ5Kw==} + rettime@0.11.7: + resolution: {integrity: sha512-DoAm1WjR1eH7z8sHPtvvUMIZh4/CSKkGCz6CxPqOrEAnOGtOuHSnSE9OC+razqxKuf4ub7pAYyl/vZV0vGs5tg==} reusify@1.1.0: resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} @@ -6968,8 +7024,8 @@ packages: undici-types@7.19.2: resolution: {integrity: sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==} - undici@7.24.8: - resolution: {integrity: sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==} + undici@7.25.0: + resolution: {integrity: sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==} engines: {node: '>=20.18.1'} unicorn-magic@0.1.0: @@ -7323,14 +7379,14 @@ snapshots: '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) zod: 4.3.6 - '@ai-sdk/gateway@3.0.95(zod@4.3.6)': + '@ai-sdk/gateway@3.0.96(zod@4.3.6)': dependencies: '@ai-sdk/provider': 3.0.8 '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) '@vercel/oidc': 3.1.0 zod: 4.3.6 - '@ai-sdk/google@3.0.62(zod@4.3.6)': + '@ai-sdk/google@3.0.63(zod@4.3.6)': dependencies: '@ai-sdk/provider': 3.0.8 '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) @@ -7353,10 +7409,10 @@ snapshots: dependencies: json-schema: 0.4.0 - '@ai-sdk/react@3.0.160(react@19.2.5)(zod@4.3.6)': + '@ai-sdk/react@3.0.161(react@19.2.5)(zod@4.3.6)': dependencies: '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) - ai: 6.0.158(zod@4.3.6) + ai: 6.0.159(zod@4.3.6) react: 19.2.5 swr: 2.4.1(react@19.2.5) throttleit: 2.1.0 @@ -8132,6 +8188,17 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@libsql/client@0.14.0': + dependencies: + '@libsql/core': 0.14.0 + '@libsql/hrana-client': 0.7.0 + js-base64: 3.7.8 + libsql: 0.4.7 + promise-limit: 2.7.0 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + '@libsql/client@0.17.2': dependencies: '@libsql/core': 0.17.2 @@ -8144,16 +8211,36 @@ snapshots: - encoding - utf-8-validate + '@libsql/core@0.14.0': + dependencies: + js-base64: 3.7.8 + '@libsql/core@0.17.2': dependencies: js-base64: 3.7.8 + '@libsql/darwin-arm64@0.4.7': + optional: true + '@libsql/darwin-arm64@0.5.29': optional: true + '@libsql/darwin-x64@0.4.7': + optional: true + '@libsql/darwin-x64@0.5.29': optional: true + '@libsql/hrana-client@0.7.0': + dependencies: + '@libsql/isomorphic-fetch': 0.3.1 + '@libsql/isomorphic-ws': 0.1.5 + js-base64: 3.7.8 + node-fetch: 3.3.2 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + '@libsql/hrana-client@0.9.0': dependencies: '@libsql/isomorphic-ws': 0.1.5 @@ -8165,6 +8252,8 @@ snapshots: - encoding - utf-8-validate + '@libsql/isomorphic-fetch@0.3.1': {} + '@libsql/isomorphic-ws@0.1.5': dependencies: '@types/ws': 8.18.1 @@ -8179,18 +8268,33 @@ snapshots: '@libsql/linux-arm-musleabihf@0.5.29': optional: true + '@libsql/linux-arm64-gnu@0.4.7': + optional: true + '@libsql/linux-arm64-gnu@0.5.29': optional: true + '@libsql/linux-arm64-musl@0.4.7': + optional: true + '@libsql/linux-arm64-musl@0.5.29': optional: true + '@libsql/linux-x64-gnu@0.4.7': + optional: true + '@libsql/linux-x64-gnu@0.5.29': optional: true + '@libsql/linux-x64-musl@0.4.7': + optional: true + '@libsql/linux-x64-musl@0.5.29': optional: true + '@libsql/win32-x64-msvc@0.4.7': + optional: true + '@libsql/win32-x64-msvc@0.5.29': optional: true @@ -9545,7 +9649,7 @@ snapshots: obug: 2.1.1 std-env: 4.0.0 tinyrainbow: 3.1.0 - vitest: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + vitest: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) '@vitest/expect@4.1.4': dependencies: @@ -9556,13 +9660,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.4(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3))': + '@vitest/mocker@4.1.4(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3))': dependencies: '@vitest/spy': 4.1.4 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - msw: 2.13.2(@types/node@25.6.0)(typescript@6.0.2) + msw: 2.13.3(@types/node@25.6.0)(typescript@6.0.2) vite: 8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3) '@vitest/pretty-format@4.1.4': @@ -9683,9 +9787,9 @@ snapshots: agent-base@7.1.4: {} - ai@6.0.158(zod@4.3.6): + ai@6.0.159(zod@4.3.6): dependencies: - '@ai-sdk/gateway': 3.0.95(zod@4.3.6) + '@ai-sdk/gateway': 3.0.96(zod@4.3.6) '@ai-sdk/provider': 3.0.8 '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) '@opentelemetry/api': 1.9.0 @@ -9758,7 +9862,7 @@ snapshots: atomic-sleep@1.0.0: {} - autoprefixer@10.4.27(postcss@8.5.9): + autoprefixer@10.5.0(postcss@8.5.9): dependencies: browserslist: 4.28.2 caniuse-lite: 1.0.30001787 @@ -9813,7 +9917,7 @@ snapshots: react: 19.2.5 react-dom: 19.2.5(react@19.2.5) svelte: 5.55.3 - vitest: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + vitest: 4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) transitivePeerDependencies: - '@cloudflare/workers-types' - '@opentelemetry/api' @@ -9880,7 +9984,7 @@ snapshots: dependencies: baseline-browser-mapping: 2.10.18 caniuse-lite: 1.0.30001787 - electron-to-chromium: 1.5.335 + electron-to-chromium: 1.5.336 node-releases: 2.0.37 update-browserslist-db: 1.2.3(browserslist@4.28.2) @@ -9964,7 +10068,7 @@ snapshots: parse5: 7.3.0 parse5-htmlparser2-tree-adapter: 7.1.0 parse5-parser-stream: 7.1.2 - undici: 7.24.8 + undici: 7.25.0 whatwg-mimetype: 4.0.0 chokidar@4.0.3: @@ -10193,7 +10297,7 @@ snapshots: dependencies: jake: 10.9.4 - electron-to-chromium@1.5.335: {} + electron-to-chromium@1.5.336: {} emoji-regex@8.0.0: {} @@ -10811,7 +10915,7 @@ snapshots: ufo: 1.6.3 uncrypto: 0.1.3 - happy-dom@20.8.9: + happy-dom@20.9.0: dependencies: '@types/node': 25.6.0 '@types/whatwg-mimetype': 3.0.2 @@ -11224,6 +11328,19 @@ snapshots: leven@3.1.0: {} + libsql@0.4.7: + dependencies: + '@neon-rs/load': 0.0.4 + detect-libc: 2.0.2 + optionalDependencies: + '@libsql/darwin-arm64': 0.4.7 + '@libsql/darwin-x64': 0.4.7 + '@libsql/linux-arm64-gnu': 0.4.7 + '@libsql/linux-arm64-musl': 0.4.7 + '@libsql/linux-x64-gnu': 0.4.7 + '@libsql/linux-x64-musl': 0.4.7 + '@libsql/win32-x64-msvc': 0.4.7 + libsql@0.5.29: dependencies: '@neon-rs/load': 0.0.4 @@ -11878,7 +11995,7 @@ snapshots: ms@2.1.3: {} - msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2): + msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2): dependencies: '@inquirer/confirm': 5.1.21(@types/node@25.6.0) '@mswjs/interceptors': 0.41.3 @@ -11891,7 +12008,7 @@ snapshots: outvariant: 1.4.3 path-to-regexp: 6.3.0 picocolors: 1.1.1 - rettime: 0.10.1 + rettime: 0.11.7 statuses: 2.0.2 strict-event-emitter: 0.5.1 tough-cookie: 6.0.1 @@ -12480,7 +12597,7 @@ snapshots: ret@0.5.0: {} - rettime@0.10.1: {} + rettime@0.11.7: {} reusify@1.1.0: {} @@ -13096,7 +13213,7 @@ snapshots: undici-types@7.19.2: {} - undici@7.24.8: {} + undici@7.25.0: {} unicorn-magic@0.1.0: {} @@ -13230,10 +13347,10 @@ snapshots: optionalDependencies: vite: 8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3) - vitest@4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.8.9)(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)): + vitest@4.1.4(@opentelemetry/api@1.9.0)(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(happy-dom@20.9.0)(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)): dependencies: '@vitest/expect': 4.1.4 - '@vitest/mocker': 4.1.4(msw@2.13.2(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + '@vitest/mocker': 4.1.4(msw@2.13.3(@types/node@25.6.0)(typescript@6.0.2))(vite@8.0.8(@types/node@25.6.0)(esbuild@0.28.0)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) '@vitest/pretty-format': 4.1.4 '@vitest/runner': 4.1.4 '@vitest/snapshot': 4.1.4 @@ -13256,7 +13373,7 @@ snapshots: '@opentelemetry/api': 1.9.0 '@types/node': 25.6.0 '@vitest/coverage-v8': 4.1.4(vitest@4.1.4) - happy-dom: 20.8.9 + happy-dom: 20.9.0 transitivePeerDependencies: - msw